[
  {
    "contest_id": "1",
    "index": "A",
    "title": "Theatre Square",
    "statement": "Theatre Square in the capital city of Berland has a rectangular shape with the size $n × m$ meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size $a × a$.\n\nWhat is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.",
    "tutorial": "The constraint that edges of each flagstone much be parralel to edges of the square allows to analyze X and Y axes separately, that is, how many segments of length 'a' are needed to cover segment of length 'm' and 'n' -- and take product of these two quantities. Answer = ceil(m/a) * ceil(n/a), where ceil(x) is the least integer which is above or equal to x. Using integers only, it is usually written as ((m+a-1)/a)*((n+a-1)/a). Note that answer may be as large as 10^18, which does not fit in 32-bit integer. Most difficulties, if any, contestants had with data types and operator priority, which are highly dependant on language used, so they are not covered here.",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1",
    "index": "B",
    "title": "Spreadsheet",
    "statement": "In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.\n\nThe rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23.\n\nSometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.\n\nYour task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.",
    "tutorial": "Let each letter representation of column number be associated with integer in radix-26, where 'A' = 0, 'B' = 1 ... 'Z'=25. Then, when converting letter representation to decimal representation, we take associated integer and add one plus quantity of valid all letter representations which are shorter than letter representation being converted. When converting from decimal representation to letter representation, we have to decide how many letters do we need. Easiest way to do this is to subtract one from number, then quantity of letter representation having length 1, then 2, then 3, and so on, until next subtraction would have produced negative result. At that point, the reduced number is the one which must be written using defined association with fixed number of digits, with leading zeroes (i.e. 'A's) as needed. Note that there is other ways to do the same which produce more compact code, but they are more error-prone as well.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1",
    "index": "C",
    "title": "Ancient Berland Circus",
    "statement": "Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.\n\nIn Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a special pillar, and the rope strung between the pillars marked the arena edges.\n\nRecently the scientists from Berland have discovered the remains of the ancient circus arena. They found only three pillars, the others were destroyed by the time.\n\nYou are given the coordinates of these three pillars. Find out what is the smallest area that the arena could have.",
    "tutorial": "The points can be vertices of regular N-polygon, if, and only if, for each pair, difference of their polar angles (as viewed from center of polygon) is a multiple of 2*pi/N. All points should lie on the circle with same center as the polygon. We can locate the center of polygon/circle [but we may avoid this, as a chord (like, say, (x1,y1)-(x2,y2)) is seen at twice greater angle from center, than it is seen from other point of a cricle (x3,y3)]. There are many ways to locate center of circle, the way I used is to build midpoint perpendiculares to segments (x1,y1)-(x2,y2) and (x2,y2)-(x3,y3) in form y = a*x + b and find their intersection. Formula y = a*x + b has drawback that it cannot be used if line is parallel to y, possible workaround is to rotate all points by random angle (using formulae x' = x*cos(a) - y*sin(a), y' = y*cos(a) + x*sin(a) ) until no segments are horizontal (and hence no perperdiculares are vertical). After the coordinates of the center are known, we use fancy function atan2, which returns angle in right quadrant: a[i] = atan2(y[i]-ycenter, x[i]-xcenter) Area of regular polygon increases with increasing N, so it is possible just to iterate through all possible values on N in ascending order, and exit from cycle as first satisfying N is found. Using sin(x) is makes it easy: sin(x) = 0 when x is mutiple of pi. So, for points to belong to regular, N-polygon, sin( N * (a[i]-a[j]) /2 )=0 because of finite precision arithmetic, fabs( sin( N * (a[i]-a[j]) /2 ) ) < eps ",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2",
    "index": "A",
    "title": "Winner",
    "statement": "The winner of the card game popular in Berland \"Berlogging\" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line \"name score\", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to $m$) at the end of the game, than wins the one of them who scored at least $m$ points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.",
    "tutorial": "To solve the problem we just need accurately follow all rules described in the problem statement. Let's describe in more details required sequence of actions. First of all, we need to find the maximum score m at the end of the game. This can be done by emulating. After all rounds played just iterate over players and choose one with the maximum score. Second, we need to figure out the set of players who have maximum score at the end of the game. We can do this in the same way as calculating maximum score. Just iterate over players after all rounds played and store all players with score equal to m. And the last, we need to find a winner. To do this we will emulate the game one more time looking for player from the winner list with score not less m after some round. This task demonstrates that sometimes it is easier to code everything stated in the problem statement, than thinking and optimizing.",
    "tags": [
      "hashing",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2",
    "index": "B",
    "title": "The least round way",
    "statement": "There is a square matrix $n × n$, consisting of non-negative integer numbers. You should find such a way on it that\n\n- starts in the upper left cell of the matrix;\n- each following cell is to the right or down from the current cell;\n- the way ends in the bottom right cell.\n\nMoreover, if we multiply together all the numbers along the way, the result should be the least \"round\". In other words, it should end in the least possible number of zeros.",
    "tutorial": "First of all, let's consider a case when there is at least one zero number in the square. In this case we can easily create a way with only one trailing zero in resulting multiplication - just output way over this zero number. The only case when this is not optimal way is when a way exists with no trailing zeroes at all. So, we can replace all 0's with 10's and solve the problem in general case. If there is an answer with no trailing zeroes - we will choose this one, otherwise we will output way over zero number. So, we can consider that all numbers in the square are positive. Let's understand what the number of zeroes in the resulting multiplication is. If we go along a way and count number of 2's and 5's in numbers factorization then the number of trailing zeros will be min(number of 2's, number of 5's). This allows us to solve the problem independently for 2's and 5's. The final answer will be just a minimum over these two solutions. Now, the last thing left is to solve the problem for 2's and 5's. New problem interpretation is the following: there is a square with numbers inside. We are to find a way with the minimal sum of the number over the way. This is classical dynamic programming problem. Let's consider that A[r,c] is the number in cell (r,c) and D[r,c] is the answer for this cell. Then D[r,c] = min(D[r-1,c],D[r,c-1]) + A[r][c]",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2",
    "index": "C",
    "title": "Commentator problem",
    "statement": "The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered.\n\nWould you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.",
    "tutorial": "Let's take two stadiums and find out a set of points from which the stadiums are observed at the same angle. Not very hard mathematical calculation shows that this is a line if stadiums have the same radius and this is a circle if they have different radiuses. Let's define S(i,j) as a set of points from which the stadiums i and j are observed at the same angle. Given that centers of stadiums are not on the same line, the intersection of S(1,2) with S(1,3) contains no more than two points. If we know these no more that 2 points we can double-check that they satisfy the criteria and chose the point with the maximum angle of observation.",
    "tags": [
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "5",
    "index": "A",
    "title": "Chat Servers Outgoing Traffic",
    "statement": "Polycarp is working on a new project called \"Polychat\". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:\n\n- Include a person to the chat ('Add' command).\n- Remove a person from the chat ('Remove' command).\n- Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).\n\nNow Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.\n\nPolycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends $l$ bytes to each participant of the chat, where $l$ is the length of the message.\n\nAs Polycarp has no time, he is asking for your help in solving this problem.",
    "tutorial": "Both are implementation problems. The only difficult, many participants faced with - to read data correctly. It is recommended to use gets(s) or getline(cin, s) in C++, readLine() method of BufferedReader class in Java.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "5",
    "index": "B",
    "title": "Center Alignment",
    "statement": "Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.\n\nYou are to implement the alignment in the shortest possible time. Good luck!",
    "tutorial": "Both are implementation problems. The only difficult, many participants faced with - to read data correctly. It is recommended to use gets(s) or getline(cin, s) in C++, readLine() method of BufferedReader class in Java.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "5",
    "index": "C",
    "title": "Longest Regular Bracket Sequence",
    "statement": "This is yet another problem dealing with regular bracket sequences.\n\nWe should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.\n\nYou are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.",
    "tutorial": "First of all, for each closing bracket in our string let's define 2 values: d[j] = position of corresponding open bracket, or -1 if closing bracket doesn't belong to any regular bracket sequence. c[j] = position of earliest opening bracket, such that substring s(c[j], j) (both boundaries are inclusive) is a regular bracket sequence. Let's consider c[j] to be -1 if closing bracket doesn't belong to any regular bracket sequence. It can be seen, that c[j] defines the beginning position of the longest regular bracket sequence, which will end in position j. So, having c[j] answer for the problem can be easily calculated. Both d[j] and c[j] can be found with following algorithm, which uses stack. Iterate through the characters of the string. If current character is opening bracket, put its position into the stack. If current character is closing bracket, there are 2 subcases: Stack is empty - this means that current closing bracket doesn't have corresponding open one. Hence, both d[j] and c[j] are equal to -1. Stack is not empty - we will have position of the corresponding open bracket on the top of the stack - let's put it to d[j] and remove this position from the stack. Now it is obvious, that c[j] is equal at least to d[j]. But probably, there is a better value for c[j]. To find this out, we just need to look at the position d[j] - 1. If there is a closing bracket at this position, and c[d[j] - 1] is not -1, than we have 2 regular bracket sequences s(c[d[j] - 1], d[j] - 1) and s(d[j], j), which can be concatenated into one larger regular bracket sequence. So we put c[j] to be c[d[j] - 1] for this case.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "5",
    "index": "D",
    "title": "Follow Traffic Rules",
    "statement": "Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed.\n\nIt is known that the car of an average Berland citizen has the acceleration (deceleration) speed of $a$ km/h$^{2}$, and has maximum speed of $v$ km/h. The road has the length of $l$ km, and the speed sign, limiting the speed to $w$ km/h, is placed $d$ km ($1 ≤ d < l$) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed.\n\nThe car can enter Bercouver at any speed.",
    "tutorial": "This problem can be solved by careful case handling. Let's construct O(1) solution for it. First of all, let's define 2 functions: $dist(speed, time)$ - calculates the distance will be covered in specified time, if car's current speed is speed. This function will not take car's speed limit into account. Also it assumes, that car is always driven with maximum acceleration $a$. It is obvious that required distance is equal to $speed * time + (a * time^2) / 2$. $travelTime(distance, speed)$ - calculates the time, required to travel specified distance, if car have starting speed equal to speed. This function will also take care about car's speed limit. We will have the following quadratic equation for time $t$: $a\\ast(t^{2})/2+s p e e d*t-d i s t a n c e=0$. This equation will have exactly 2 different roots. Using Viete's formulas it can be concluded, that one root of the equation is non-positive and other is non-negative. Let's define the larger root of the equation as $tAll$. It will be the answer, if there is no car's speed limit. To take the limit into account let's find the time, required to gain car's max speed. $tMax = (v - speed) / a$. If $tMax  \\ge  tAll$, function should just returns $tAll$ as a result. Otherwise result is $tMax$ hours to achieve car's maximal speed plus $(distance - dist(speed, tMax)) / v$ hours to cover remaining distance. Having these functions, solution will be the following: If $v  \\le  w$, answer is $travelTime(l, 0)$. Calculate $tw = w / a$ - time, required to gain speed $w$. Consider $dw = dist(0, tw)$. If $dw  \\ge  d$, we will pass the point there sign is placed before we gain speed $w$. Answer for this case is $travelTime(l, 0)$ as well. Otherwise, we will gain speed $w$ before the sign. Let's consider segment of the road $[dw, d]$. We need to find out the best strategy to drive it. It is obvious, that we definitely should have speed $w$ at the both ends of this segment. Also we know, that acceleration is equal to deceleration. Taking these facts into account we can see, that the speed in the optimal solution will be symmetrical with respect to the middle of the segment $[dw, d]$. Hence answer for this case will be $tw + 2 * travelTime(0.5 * (d - dw), w) + travelTime(l - d, w)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "5",
    "index": "E",
    "title": "Bindian Signalizing",
    "statement": "Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by $n$ hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.\n\nIn case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.\n\nAn important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.",
    "tutorial": "Let's reduce the problem from the circle to the straight line. Perform the following actions to do it: Find the hill with the maximal height (if it is not unique, choose any). Rotate all the sequence in such a way that hill with maximal height goes first. For convenience, add one more hill with maximum height to the end of the sequence. (It will represent the first hill, which goes after the last in the circle order). Now we have almost the same problem on the straight line. One exception is that now first hill is doubled. General idea of the solution: Consider there is a pair of hills, such that these hills are visible from each other. Let's define hill with lower height (if heights are equal - with lower position) as responsible for adding this pair to the answer. From this point of view, hill x will adds to the answer 3 kinds of hills as his pair: First hill to the left of the x, which is strictly higher than x. (Let's define its position as l[x]) First hill to the right of the x, which is strictly higher than x. (Let's call this hill y and define it's position as r[x]). All hills that are as high as x and are located between x and y. (Let's define this count as c[x]). Arrays r[x] and c[x] can be calculated by the following piece of code: c[n] = 0; for(int i = n - 1; i >= 0; --i) { r[i] = i + 1; while (r[i] < n && height[i] > height[r[i]]) r[i] = r[r[i]]; if (r[i] < n && height[i] == height[r[i]]) { c[i] = c[r[i]] + 1; r[i] = r[r[i]]; } } I am not going to prove here, that it works for the O(N) time, but believe it does :) Pay attention, that r[x] is undefined for hills with maximum height and this algorithm will find r[x] = n for such hills. Array l[x] can be found in a similar way. Having l[x], r[x] and c[x], it's not so difficult to calculate the answer. We should just notice, that: Each hill will add c[x] pairs to the answer. Each hill, lower than maximal, will also add 2 pairs (x, l[x]) and (x, r[x]) to the answer. The only corner case here is l[x] = 0 and r[x] = n, because (x, 0) and (x, n) is the same pair of hills in the original problem, where hills are circled.",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "6",
    "index": "A",
    "title": "Triangle",
    "statement": "Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same.\n\nThe boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him.",
    "tutorial": "For each of the possible combinations of three sticks , we can make a triangle if sum of the lengths of the smaller two is greater than the length of the third and we can make a segment in case of equality.",
    "code": "#include <iostream>\nusing namespace std;\n \nbool tr(int a,int b,int c)\n{\n  return ((a+b>c)&&(a+c>b)&&(b+c>a));\n}\n \nbool seg(int a,int b,int c)\n{\n  return ((a==b+c)||(b==a+c)||(c==a+b));\n}\n \nint main()\n{\n  bool normal=false;\n  bool deg=false;\n  int a,b,c,d;\n  cin>>a>>b>>c>>d;\n  normal=normal||(tr(a,b,c));\n  normal=normal||(tr(a,b,d));\n  normal=normal||(tr(a,c,d));\n  normal=normal||(tr(b,c,d));\n \n \n  deg=deg||(seg(a,b,c));\n  deg=deg||(seg(a,b,d));\n  deg=deg||(seg(a,c,d));\n  deg=deg||(seg(b,c,d));\n  \n  if(normal)\n    cout<<\"TRIANGLE\"<<endl;\n  else if(deg)\n    cout<<\"SEGMENT\"<<endl;\n  else\n    cout<<\"IMPOSSIBLE\"<<endl;\n \n  return 0;\n}",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 900
  },
  {
    "contest_id": "6",
    "index": "B",
    "title": "President's Office",
    "statement": "President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.\n\nThe office-room plan can be viewed as a matrix with $n$ rows and $m$ columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.",
    "tutorial": "For each cell of president's desk , we check all its neighbors and add their colors to a set. easy as pie!",
    "code": "#include <iostream>\n#include <string>\n#include <set>\nusing namespace std;\n set<char> adj;\n \nint main()\n{\n  int n,m;\n  char c;\n  cin>>n>>m>>c;\n  string room[n];\n  for(int i=0;i<n;i++)\n    cin>>room[i];\n  for(int i=0;i<n;i++)\n    {\n      for(int j=0;j<m;j++)\n        {\n          if(room[i][j]==c)\n            {\n              if(i!=0&&room[i-1][j]!=c)\n                adj.insert(room[i-1][j]);\n              if(i!=n-1&&room[i+1][j]!=c)\n                adj.insert(room[i+1][j]);\n              if(j!=0&&room[i][j-1]!=c)\n                adj.insert(room[i][j-1]);\n              if(j!=m-1&&room[i][j+1]!=c)\n                adj.insert(room[i][j+1]);\n            }\n        }\n    }\n  int x=0;\n  if(adj.find('.')!=adj.end())\n    x--;\n  cout<<adj.size()+x<<endl;\n  return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "6",
    "index": "C",
    "title": "Alice, Bob and Chocolate",
    "statement": "Alice and Bob like games. And now they are ready to start a new game. They have placed $n$ chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.\n\nHow many bars each of the players will consume?",
    "tutorial": "This one can be solved easily by simulation. see the code.",
    "code": "#include <iostream>\n#include <deque>\n#include <algorithm>\nusing namespace std;\n \nstruct eater{\n  int ate;\n  int wait;\n  void init()\n  {\n    ate=wait=0;\n  }\n};\n \nint main()\n{\n  eater alice,bob;\n  bob.init();\n  alice.init();\n  int n;\n  cin>>n;\n  deque<int> chocs;\n  for(int i=0;i<n;i++)\n    {\n      int t;\n      cin>>t;\n      chocs.push_back(t);\n    }\n  while(chocs.size()>0)\n    {\n      if(alice.wait!=0)\n          alice.wait--;\n      if(bob.wait!=0)\n        bob.wait--;\n      if(alice.wait==0)\n        {\n          alice.wait=chocs[0];\n          alice.ate++;\n          chocs.pop_front();\n        }\n      if(bob.wait==0)\n        {\n          if(chocs.size()==0)\n            break;\n          else\n            {\n              bob.wait=chocs[chocs.size()-1];\n              bob.ate++;\n              chocs.pop_back();\n            }\n        }\n    }\n  cout<<alice.ate<<\" \"<<bob.ate<<endl;\n  return 0;\n}",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "6",
    "index": "E",
    "title": "Exposition",
    "statement": "There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than $k$ millimeters.\n\nThe library has $n$ volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is $h_{i}$. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.",
    "tutorial": "I solved this one in O(nlgn) time using a segment-tree and keeping track of minimum and maximum element in each segment. Adding a number is O(lgn) because we need to update minimum and maximum for the log2n segments containing that number. For each start point we query the tree to find the maximal endpoint. This is again O(lgn) and is done O(n) times so we have a total complexity of O(nlgn) fitting perfectly in the time limit.",
    "tags": [
      "binary search",
      "data structures",
      "dsu",
      "trees",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "8",
    "index": "D",
    "title": "Two Friends",
    "statement": "Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square.\n\nOnce they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it.\n\nBob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends.\n\nThe film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than $t_{1}$, and the distance covered by Bob should not differ from the shortest one by more than $t_{2}$.\n\nFind the maximum distance that Alan and Bob will cover together, discussing the film.",
    "tutorial": "The main observation for this problem is the following: If Alan and/or Bob is at some point X and moves following some curve and travels distance d, then the point at which they finish can be ANY point on or inside the circle with center X and radius d. In other words: If you start at some point X and go to some point Y, you can do this on as long curve as we want(only not shorter then the distance(X, Y). Now, for convenience, lets say that T1 is the longest allowed path for Alan and T2 is the longest allowed path for Bob. These values are easily calculated: T1 = distance(cinema, shop) + distance(shop, home) + t1 T2 = distance(cinema, home) + t2Now, there are two cases. The first and trivial case is when distance(cinema, shop) + distance(shop, home) <= T2. In this case, it is OK for Bob to go to the shop with Alan. If they go to the shop together there is no need for them to ever split. So they go together all the way from the cinema to the shop and then from the shop to their home. In this case the solution is min(T1, T2) Why? (Hint: here the observation in the beginning is important).The second case is when Bob cannot go to the shop with Alan. We'll solve this case with binary search on the distance that they could cover together before splitting. Let's assume that the go to some point P together covering some distance x. After they split Bob goes home in straight line and Alan first goes to the shop in straight line and then goes home again in straight line. This circumstance forces three condition for the point P. Point P must be inside a circle with center 'cinema' and radius x. This follows directly from the main observation. x + distance(P, home) <= T2 - Bob must be able to go home in time. This condition means that P must be inside a circle with center home and radius max(0, T2 - x). x + distance(P, shop) + distance(shop, home) <= T1 - Alan must be able to go home in time. This condition means that P must be inside circle with center shop and radius max(0, T1 - x - distance(shop, home). Now we have three circles and if they intersect, then it's possible to choose point P in such a way that Alan and Bob will the together the first x meters of their journey.Now, the problem is to check if three circles intersect. I come up with easy solution for this problem. I haven't proven it correct, but it seem to work. I don't know if there is some standard algorithm for this problem. My idea is the following. Let the 3 circles be C1, C2 and C3. If C1 and C2 intersect they do it in one or two point. Now we check is some of these points is inside C3. If there is such point, then the 3 circles intersect, but if there is no such point, it doesn't necessarily mean thath the 3 circles doesn't intersect. We should try all permutations of the 3 circles. That is we first check C1 and C2 and the intersected points with C3, then C1 and C3 and the intersected points with C2, and so on.",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cstring>\n#include <cmath>\n#include <ctime>\n#include <complex>\nusing namespace std;\n\nconst double eps = 1e-10;\n\nconst int DIM = 2;\n\ntypedef complex<double> point;\ntypedef pair<point, double> circle;\ndouble T1, T2;\npoint cinema, shop, home;\n\ninline double dist(const point& a, const point& b) {\n    return abs(a - b);\n}\n\nvoid readPoint(point& p) {\n    double x, y;\n    cin >> x >> y;\n    p = point(x, y);\n}\n\ninline bool isIn(const circle& a, const circle& b) {\n    double A = dist(a.first, b.first) + a.second;\n    double B = b.second;\n    return A < B + eps;\n}\n\ninline bool isInPoint(const point& p, const circle& c) {\n    return dist(p, c.first) < c.second + eps;\n}\n\ninline bool doesIntersect(const circle& a, const circle& b) {\n    return dist(a.first, b.first) < a.second + b.second + eps;\n}\n\npoint getNewCoords(point e1prime, point e2prime, point P, point A) {\n    double c1 = A.real() - P.real();\n    double c2 = A.imag() - P.imag();\n    double x = c1 * e1prime.real() + c2 * e2prime.real();\n    double y = c1 * e1prime.imag() + c2 * e2prime.imag();\n    return point(x, y);\n}\n\npoint getOldCoors(point e1prime, point e2prime, point P, point A) {\n    double a1 = A.real();\n    double a2 = A.imag();\n    double x = a1 * e1prime.real() + a2 * e1prime.imag();\n    double y = a1 * e2prime.real() + a2 * e2prime.imag();\n    x += P.real();\n    y += P.imag();\n    return point(x, y);\n}\n\nvector<point> getIntersectedPoints(const circle& C1, const circle& C2) {\n    point P = C1.first;\n    point e1prime = C2.first - C1.first;\n    e1prime = e1prime / abs(e1prime);\n    point e2prime = point(e1prime.imag(), -e1prime.real());\n    point A = getNewCoords(e1prime, e2prime, P, C1.first);\n    point B = getNewCoords(e1prime, e2prime, P, C2.first);\n    double R1 = C1.second * C1.second;\n    double R2 = C2.second * C2.second;\n    double b = B.real();\n    double x = (b * b + R1 - R2) / (2.0 * b);\n    double Y = R1 - x * x;\n    if (Y < 0.0) Y = 0.0;\n    vector<point> ret;\n    if (Y < eps) {\n        ret.push_back(point(x, Y));\n    }\n    else {\n        ret.push_back(point(x, sqrt(Y)));\n        ret.push_back(point(x, -sqrt(Y)));\n    }\n    for (int i = 0; i < int(ret.size()); ++i) {\n        ret[i] = getOldCoors(e1prime, e2prime, P, ret[i]);\n    }\n    return ret;\n}\n\nbool my_comp(const circle& c1, const circle& c2) {\n    if (c1.first.real() < c2.first.real()) return true;\n    if (c1.first.real() > c2.first.real()) return false;\n    if (c1.first.imag() < c2.first.imag()) return true;\n    if (c1.first.imag() > c2.first.imag()) return false;\n    if (c1.second < c2.second) return true;\n    return false;\n}\n\nbool intersect3Circles(vector<circle>& circles) {\n    sort(circles.begin(), circles.end(), my_comp);\n    do {\n        if (!doesIntersect(circles[0], circles[1])) {\n            return false;\n        }\n        if (isIn(circles[0], circles[1])) {\n            if (doesIntersect(circles[0], circles[2])) {\n                return true;\n            }\n            else {\n                return false;\n            }\n        }\n    } while (next_permutation(circles.begin(), circles.end(), my_comp));\n\n    sort(circles.begin(), circles.end(), my_comp);\n    do {\n        vector<point> pts = getIntersectedPoints(circles[0], circles[1]);\n        bool ok = false;\n        for (int i = 0; i < int(pts.size()); ++i) {\n            if (isInPoint(pts[i], circles[2])) {\n                ok = true;\n                break;\n            }\n        }\n        if (ok) return true;\n    } while(next_permutation(circles.begin(), circles.end(), my_comp));\n    return false;\n}\n\nbool check(double Q) {\n    vector<circle> circles(3);\n    circles[0] = circle(cinema, Q);\n    circles[1] = circle(shop, max(0.0, T1 - dist(shop, home) - Q));\n    circles[2] = circle(home, max(0.0, T2 - Q));\n    return intersect3Circles(circles);\n}\n\nint main() {\n    cout.setf(ios::fixed);\n    cout.precision(9);\n    double t1, t2;\n    cin >> t1 >> t2;\n    readPoint(cinema);\n    readPoint(home);\n    readPoint(shop);\n    T2 = t2 + dist(cinema, home);\n    T1 = t1 + dist(cinema, shop) + dist(shop, home);\n    if (dist(cinema, shop) + dist(shop, home) < T2 + eps) {\n        cout << min(T1, T2) << endl;\n        return 0;\n    }\n    double L = 0.0;\n    double R = min(T1, T2);\n    check(1.000253);\n    for (int step = 1; step <= 40; ++step) {\n        double Q = (L + R) / 2.0;\n        if (check(Q)) {\n            L = Q;\n        }\n        else {\n            R = Q;\n        }\n    }\n    cout << (L + R) / 2.0 << endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "8",
    "index": "E",
    "title": "Beads",
    "statement": "One Martian boy called Zorg wants to present a string of beads to his friend from the Earth — Masha. He knows that Masha likes two colours: blue and red, — and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if one unfastens it, one might notice that all the strings of beads in the shop are of the same length. Because of the peculiarities of the Martian eyesight, if Zorg sees one blue-and-red string of beads first, and then the other with red beads instead of blue ones, and blue — instead of red, he regards these two strings of beads as identical. In other words, Zorg regards as identical not only those strings of beads that can be derived from each other by the string turnover, but as well those that can be derived from each other by a mutual replacement of colours and/or by the string turnover.\n\nIt is known that all Martians are very orderly, and if a Martian sees some amount of objects, he tries to put them in good order. Zorg thinks that a red bead is smaller than a blue one. Let's put 0 for a red bead, and 1 — for a blue one. From two strings the Martian puts earlier the string with a red bead in the $i$-th position, providing that the second string has a blue bead in the $i$-th position, and the first two beads $i - 1$ are identical.\n\nAt first Zorg unfastens all the strings of beads, and puts them into small heaps so, that in each heap strings are identical, in his opinion. Then he sorts out the heaps and chooses the minimum string in each heap, in his opinion. He gives the unnecassary strings back to the shop assistant and says he doesn't need them any more. Then Zorg sorts out the remaining strings of beads and buys the string with index $k$.\n\nAll these manupulations will take Zorg a lot of time, that's why he asks you to help and find the string of beads for Masha.",
    "tutorial": "This is quite an interesting problem for me. We must find the k-th lexicographically smallest number from a subset of the numbers from 0 to 2^N(It is easier to increase K with one and consider the all zeroes and all ones case, too). The numbers which we want to count are those which are smaller or equal to their inverted number(flip zeroes and ones), their reversed number(read the bits of the number from right to left) and their reversed and inverted number.Let's call a prefix the first half of the numbers, i.e. when only the first N/2 bits are set. Since N <= 50, there are at most 2 ^ 25 such numbers. Also we will only consider numbers with 0 at the first bit. If it is 1, then the inverse number will be smaller, so there are at most 2^24 prefixes. Now if we have some prefix, using dynamic programming we will see in how many ways can we finish it to a real number. The state of the dp is: (int pos, bool less, bool lessInv) and dp[pos][less][lessInv] is the number of ways to finish the number if we have to choose the pos-th bit now. less shows if so far we are less then or equal to the reversed number and lessInv shows if so far we are less then or equal to the inverted and reversed number. Using the dp we could easily find the k-th number.There is one final note. The DP here is run for every possible prefix and the prefixes could be up to 2^24. Every time we clear the DP table before running it. This makes the solution slow even for the 5 seconds time limit. There is one more observation which makes the solution run in time. We iterate the prefixes in order, that is in each step newprefix = oldprefix + 1. In this case only the last few bits of the prefix are changed. The other part of the prefix remains the same and there is no need to clear the whole DP table, only the parts that changed due to changing the last few bits. This is left for exercise.",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cstring>\n#include <cmath>\n#include <ctime>\nusing namespace std;\n\nconst int MAXN = 50;\n\ntypedef long long ll;\n\nint n, nPrefix;\nll rem;\nint s[MAXN];\n\nll dp[MAXN + 1][2][2];\n\nll f(int pos, int less, int lessRev) {\n    if (dp[pos][less][lessRev] != -1) return dp[pos][less][lessRev];\n    if (pos >= n) {\n        if (less && lessRev) {\n            dp[pos][less][lessRev] = 1;\n            return 1;\n        }\n        else {\n            dp[pos][less][lessRev] = 0;\n            return 0;\n        }\n    }\n    ll ret = 0;\n    for (int i = 0; i <= 1; ++i) {\n        int nextLess = less;\n        int nextLessRev = lessRev;\n        if (i > s[n - 1 - pos]) {\n            nextLess = 1;\n        }\n        else if (i < s[n - 1 - pos]) {\n            nextLess = 0;\n        }\n        if (1 - i > s[n - 1 - pos]) {\n            nextLessRev = 1;\n        }\n        if (1 - i < s[n - 1 - pos]) {\n            nextLessRev = 0;\n        }\n        ret += f(pos + 1, nextLess, nextLessRev);\n    }\n    dp[pos][less][lessRev] = ret;\n    return ret;\n}\n\nint main() {\n    cin >> n >> rem;\n    ++rem;\n    nPrefix = n / 2 + n % 2;\n    bool found = false;\n    int prefix;\n    memset(dp, -1, sizeof dp);\n    memset(s, 0, sizeof s);\n    for (prefix = 0; prefix < (1 << nPrefix); ++prefix) {\n        if (prefix > 0) {\n            int i = nPrefix - 1;\n            while (i >= 0) {\n                if (s[i] == 0) {\n                    s[i] = 1;\n                    break;\n                }\n                s[i] = 0;\n                --i;\n            }\n            for (int j = n - nPrefix; j <= n - 1 - i; ++j) {\n                dp[j][0][0] = -1;\n                dp[j][0][1] = -1;\n                dp[j][1][0] = -1;\n                dp[j][1][1] = -1;\n            }\n        }\n        int firstPos = nPrefix;\n        int less = 1;\n        int lessRev = 1;\n        if (n % 2 == 1 && s[nPrefix - 1] == 1) lessRev = 0;\n        ll temp = f(firstPos, less, lessRev);\n        if (temp < rem) {\n            rem -= temp;\n        }\n        else {\n            found = true;\n            break;\n        }\n    }\n    if (!found) {\n        cout << \"-1\" << endl;\n        return 0;\n    }\n    int less = 1, lessRev = 1;\n    if (n % 2 == 1 && s[nPrefix - 1] == 1) lessRev = 0;\n    for (int pos = nPrefix; pos < n; ++pos) {\n        int nextLess = less;\n        int nextLessRev = lessRev;\n        if (0 < s[n - 1 - pos]) nextLess = 0;\n        if (1 > s[n - 1 - pos]) nextLessRev = 1;\n        ll temp = f(pos + 1, nextLess, nextLessRev);\n        if (temp >= rem) {\n            s[pos] = 0;\n            less = nextLess;\n            lessRev = nextLessRev;\n            continue;\n        }\n        rem -= temp;\n        s[pos] = 1;\n        if (1 > s[n - 1 - pos]) less = 1;\n        if (0 < s[n - 1 - pos]) lessRev = 0;\n    }\n    for (int i = 0; i < n; ++i) {\n        cout << s[i];\n    }\n    cout << endl;\n    return 0;\n}",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "9",
    "index": "A",
    "title": "Die Roll",
    "statement": "Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.\n\nBut to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.\n\nYakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.\n\nIt is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.",
    "tutorial": "If the maximum of Yakko's and Wakko's points is a, then Dot will win, if she has not less than a points. So the probability of her win is (6 - (a-1)) / 6. Since there are only 6 values for a, you can simply hardcode the answers.",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 800
  },
  {
    "contest_id": "9",
    "index": "B",
    "title": "Running Student",
    "statement": "And again a misfortune fell on Poor Student. He is being late for an exam.\n\nHaving rushed to a bus stop that is in point $(0, 0)$, he got on a minibus and they drove along a straight line, parallel to axis $OX$, in the direction of increasing $x$.\n\nPoor Student knows the following:\n\n- during one run the minibus makes $n$ stops, the $i$-th stop is in point $(x_{i}, 0)$\n- coordinates of all the stops are different\n- the minibus drives at a constant speed, equal to $v_{b}$\n- it can be assumed the passengers get on and off the minibus at a bus stop momentarily\n- Student can get off the minibus only at a bus stop\n- Student will have to get off the minibus at a terminal stop, if he does not get off earlier\n- the University, where the exam will be held, is in point $(x_{u}, y_{u})$\n- Student can run from a bus stop to the University at a constant speed $v_{s}$ as long as needed\n- a distance between two points can be calculated according to the following formula: $\\sqrt{(x_{2}-x_{1})^{2}+(y_{2}-y_{1})^{2}}$\n- Student is already on the minibus, so, he cannot get off at the first bus stop\n\nPoor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.",
    "tutorial": "It is simple to calculate the time $ti$ that the Student will need, if he gets off the bus at the i-th stop: $ti = bi + si$, where $bi = xi / vb$ is the time he will drive on the bus, and $s_{i}=\\sqrt{(x_{i}-x_{u})^{2}+y_{u}^{2}}/v_{s}$ is the time he will need to get from the i-th stop to the University. We need to choose indices with minimal possible $ti$, and among them - the index with minimal possible $si$, that is, with maximal $bi$, that is (since the coordinates of bus stops are already ordered) with maximal i.Note that due to precision issues, you should be careful when you compare $ti$: the condition $ti$ = $tj$ should be written in the form $|ti - tj| <  \\epsilon $ for some small $ \\epsilon $.",
    "tags": [
      "brute force",
      "geometry",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "9",
    "index": "C",
    "title": "Hexadecimal's Numbers",
    "statement": "One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of $n$ different natural numbers from 1 to $n$ to obtain total control over her energy.\n\nBut his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully.",
    "tutorial": "Brute force solution, when you try each number from 1 to n, will not fit into the time limit.Note, however, that all good numbers have at most 10 digits, and each of the digits is 0 or 1. That is, there are at most $210$ binary strings to check. Each of these strings is a number from 1 to $210 - 1$ in binary representation. So the algorithm is the following: for each number from 1 to $210 - 1$ write its binary representation, read it as if it was decimal representation and compare the result to n.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "9",
    "index": "D",
    "title": "How many trees?",
    "statement": "In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terrible Game Cubes fall down on the city, bringing death to those modules, who cannot win the game...\n\nFor sure, as guard Bob appeared in Mainframe many modules stopped fearing Game Cubes. Because Bob (as he is alive yet) has never been defeated by User, and he always meddles with Game Cubes, because he is programmed to this.\n\nHowever, unpleasant situations can happen, when a Game Cube falls down on Lost Angles. Because there lives a nasty virus — Hexadecimal, who is... mmm... very strange. And she likes to play very much. So, willy-nilly, Bob has to play with her first, and then with User.\n\nThis time Hexadecimal invented the following entertainment: Bob has to leap over binary search trees with $n$ nodes. We should remind you that a binary search tree is a binary tree, each node has a distinct key, for each node the following is true: the left sub-tree of a node contains only nodes with keys less than the node's key, the right sub-tree of a node contains only nodes with keys greater than the node's key. All the keys are different positive integer numbers from $1$ to $n$. Each node of such a tree can have up to two children, or have no children at all (in the case when a node is a leaf).\n\nIn Hexadecimal's game all the trees are different, but the height of each is not lower than $h$. In this problem «height» stands for the maximum amount of nodes on the way from the root to the remotest leaf, the root node and the leaf itself included. When Bob leaps over a tree, it disappears. Bob gets the access to a Cube, when there are no trees left. He knows how many trees he will have to leap over in the worst case. And you?",
    "tutorial": "Denote by $tnh$ the number of binary search trees on n nodes with height equal to h. We will derive a recurrent formula for $tnh$. For the base case note that $t00 = 1$ (empty tree), and $ti0 = t0i = 0$ if i>0.Now take any binary search tree on n nodes with height equal to h. Let m be the number written at its root, $1  \\le  m  \\le  n$. The left subtree is a binary search tree on m-1 nodes, and the right subtree is a binary search tree on n-m nodes. The maximal of their heights must be equal to h-1. Consider 2 subcases:1. The height of the left subtree is equal to h-1. There are $tm - 1, h - 1$ such trees. The right subtree can have any height from 0 to h-1, so there are $\\textstyle\\sum_{i=0}^{h-1}t_{n-m,i}$ such trees. Since we can choose left and right subtrees independently, we have $\\begin{array}{c}{{\\displaystyle F_{m-1,h-1}\\displaystyle\\sum_{n=0}^{h-1}\\,t_{n-m,i}}}\\end{array}$ variants in this case.2. The height of the left subtree is less than h-1. There are $\\textstyle\\sum_{i=0}^{h-2}t_{m-1,i}$ such trees, and the right subtree must have height exactly h-1, which gives us totally $\\begin{array}{c}{{\\displaystyle F_{n-m,h-1}\\sum_{n=1}^{h-2}\\bigg(n_{m-1,i}}}\\end{array}$ variants.So the recurrent formula is the following: $t_{n h}=\\sum_{m=1}^{n}\\left(t_{m-1,h-1}\\sum_{i=0}^{h-1}t_{n-m,i}+t_{n-m,h-1}\\sum_{i=0}^{h-2}t_{m-1,i}\\right)$.All the values $tnh$ can be calculated by dynamic programming. The answer, then, is $\\textstyle\\sum_{i=h}^{n}t_{n i}$.",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "9",
    "index": "E",
    "title": "Interestring graph and Apples",
    "statement": "Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.\n\nShe has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$, where $x_{i} ≤ y_{i}$, is lexicographically smaller than the set $(u_{1}, v_{1}), (u_{2}, v_{2}), ..., (u_{n}, v_{n})$, where $u_{i} ≤ v_{i}$, provided that the sequence of integers $x_{1}, y_{1}, x_{2}, y_{2}, ..., x_{n}, y_{n}$ is lexicographically smaller than the sequence $u_{1}, v_{1}, u_{2}, v_{2}, ..., u_{n}, v_{n}$. If you do not cope, Hexadecimal will eat you. ...eat you alive.",
    "tutorial": "Interesting graph and Apples The funny ring consists of n vertices and n edges. If there is another edge except for these n, then the vertices it connects belong to more than one cycle. So, an interesting graph is just a funny ring. A graph is a funny ring if and only if the following conditions hold:A1. The degree of each vertex equals 2.A2. The graph is connected. Now let's figure out when a graph is not yet a funny ring, but can be transformed into a funny ring by adding edges. There are obvious necessary conditions:B1. m < n.B2. There are no cycles.B3. The degree of each vertex is not more than 2. Let's add edges so that these conditions were preserved, and the sequence of edges was lexicographically minimal. So, we add an edge (i,j) such that:1. The degrees of i and j are less than 2. (Otherwise we would break B3).2. i and j belong to different connected components. (Otherwise we would break B2).3. The pair (i,j) is lexicographically minimal. Let's see what we have when we can't add edges anymore. Since there are no cycles, each connected component is a tree, and therefore has at least one vertex with degree less than 2. If there are two connected components, then they could be connected by an edge without breaking B1-B3. So the graph is connected, has no cycles, and the degree of each vertex is not more than 2. This means that the obtained graph is just a walk and we can connect its end points to obtain a funny ring. To summarize, the algorithm is the following: 1. Check if A1-A2 hold. If yes, output \"YES\" and 0. 2. Check if B1-B3 hold. If no, output \"NO\". 3. Output \"YES\" and n-m. 4. Add edges as described. When the edge (i,j) is added, output \"i j\". 5. Find the only vertices i and j with degree less than 2 (they can be equal if n=1). Output \"i j\".",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "13",
    "index": "A",
    "title": "Numbers",
    "statement": "Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.\n\nNow he wonders what is an average value of sum of digits of the number $A$ written in all bases from $2$ to $A - 1$.\n\nNote that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.",
    "tutorial": "It is sufficient to iterate over all bases from 2 to A-2 and find the sum of digits in them. Then one should find the greatest common divisor of found sum and A-2 (which is equal to number of bases in which we found the sums). The numerator of the answer is equal to founded sum divided by this GCD and the denominator is equal to A-2 divided by this GCD.The complexity is O(A).",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "13",
    "index": "B",
    "title": "Letter A",
    "statement": "Little Petya learns how to write. The teacher gave pupils the task to write the letter $A$ on the sheet of paper. It is required to check whether Petya really had written the letter $A$.\n\nYou are given three segments on the plane. They form the letter $A$ if the following conditions hold:\n\n- Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments.\n- The angle between the first and the second segments is greater than $0$ and do not exceed $90$ degrees.\n- The third segment divides each of the first two segments in proportion not less than $1 / 4$ (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than $1 / 4$).",
    "tutorial": "This problem appeared to be quite unpleasant to code, but all what one need to do is to check whether all three statements are true. It is recommended to perform all computations using integer arithmetics and to use scalar and vector product instead of computing cosines of angles or angles itself.",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "13",
    "index": "C",
    "title": "Sequence",
    "statement": "Little Petya likes to play very much. And most of all he likes to play the following game:\n\nHe is given a sequence of $N$ integer numbers. At each step it is allowed to increase the value of any number by $1$ or to decrease it by $1$. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.\n\nThe sequence $a$ is called non-decreasing if $a_{1} ≤ a_{2} ≤ ... ≤ a_{N}$ holds, where $N$ is the length of the sequence.",
    "tutorial": "Note, that there exists a non-decreasing sequence, which can be obtained from the given sequence using minimal number of moves and in which all elements are equal to some element from the initial sequence (i.e. which consists only from the numbers from the initial sequence).Suppose {ai} is the initial sequence, {bi} is the same sequence, but in which all elements are distinct and they are sorted from smallest to greatest. Let f(i,j) be the minimal number of moves required to obtain the sequence in which the first i elements are non-decreasing and i-th element is at most bj. In that case the answer to the problem will be equals to f(n,k), where n is the length of {ai} and k is the length of {bi}. We will compute f(i,j) using the following recurrences:f(1,1)=|a1-b1|f(1,j)=min{|a1-bj|,f(1,j-1)}, j>1f(i,1)=|ai-b1|+f(i-1,1), i>1f(i,j)=min{f(i,j-1),f(i-1,j)+|ai-bj|}, i>1, j>1The complexity is O(N2). To avoid memory limit one should note that to compute f(i,*) you only need to know f(i-1,*) and the part of i-th row which is already computed.",
    "tags": [
      "dp",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "13",
    "index": "D",
    "title": "Triangles",
    "statement": "Little Petya likes to draw. He drew $N$ red and $M$ blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.",
    "tutorial": "We will solve the problem using the following algorithm:Fix some red point.Find the number of triangles with vertices in the red points which don't contain any blue points inside and which have the fixed red point as one of the vertices.Remove the fixed red point and go back to statement 1, if there remain any red point.The first and third statements are obvious, so the main part of the solution is statement 2.Suppose the red point A is fixed (in the first statement). Also suppose we have all other points which are still not removed (blue and red together) sorted by angle around the point A. We will iterate over all red points B, which will be the second vertice of triangle. Now, we need to find the number of triangles with vertices in red points which have points A and B as two vertices and which don't contain any blue point inside.To solve this problem we will iterate over all unremoved points C in the increasing order of angle ABC starting from the point after the point B (in the same order). To avoid double counting we will stop when the angle between vectors AB and AC become greater than 180 degrees or when we reach the point which was already considered. Then we will perform such actions:If C is red then we will check whether there are blue points inside triangle ABC and if not - we will increase the answer by 1. Note, that to perform this check we don't need to iterate over all blue points. It is sufficient to maintain such point D from the ones which we have already seen for which the angle ABD is the smallest possible. If D doesn't lies inside the triangle ABC, then there is no blue point which lies inside it.If C is blue, then we will compare the angle ABC with ABD and if ABC is smaller, we will replace old D with C.Note, that after choosing new B we consider that there is no point D and there will be no blue points inside triangles ABC until we reach the first blue point.The complexity is O(N2(N+M)).",
    "tags": [
      "dp",
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "13",
    "index": "E",
    "title": "Holes",
    "statement": "Little Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:\n\nThere are $N$ holes located in a single row and numbered from left to right with numbers from 1 to $N$. Each hole has it's own power (hole number $i$ has the power $a_{i}$). If you throw a ball into hole $i$ it will immediately jump to hole $i + a_{i}$, then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the $M$ moves the player can perform one of two actions:\n\n- Set the power of the hole $a$ to value $b$.\n- Throw a ball into the hole $a$ and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row.\n\nPetya is not good at math, so, as you have already guessed, you are to perform all computations.",
    "tutorial": "Let's divide all row into blocks of length K=sqrt(N) of consecutive holes. If N is not a complete square, then we will take K=sqrt(N) rounded down. For each hole we will maintain not only it's power (let's call it power[i]), but also the number of the first hole which belongs to other block and which can be reached from the current one with sequence of jumps (let's call it next[i]). Also, for each hole we will maintain the number of jumps required to reach the hole next[i] from the current one (let's call it count[i]). We will consider that there is a fictious hole, which lies after the hole N and it belongs to it's own block.To answer the query of the first type (when the ball is thrown) we will jump from the hole i to hole next[i] and so on, until we reach the fictious hole. Each time we will add count[i] to the answer. We will jump not more than N/K times.To maintain the query of the seqond type (when the power of hole i is changed) we will change power[i], next[i] and count[i]. Then for each hole which belongs to the same block as i and has smaller number than i we will update next[i] and power[i] in decreasing order of number of the hole. We will perform not more than K updates.The complexity is O(Nsqrt(N)).",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 2700
  },
  {
    "contest_id": "14",
    "index": "A",
    "title": "Letter",
    "statement": "A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with $n$ rows and $m$ columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.",
    "tutorial": "To find the smallest rectangle containing the picture, iterate through the pairs (i,j) such that the j-th symbol in i-th line is '*'; find the minimum and maximum values of i and j from these pairs. The rectangle to output is $[imin, imax]  \\times  [jmin, jmax]$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "14",
    "index": "B",
    "title": "Young Photographer",
    "statement": "Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position $x_{0}$ of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals $n$. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position $a_{1}$ to position $b_{1}$, the second — from $a_{2}$ to $b_{2}$\n\nWhat is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.",
    "tutorial": "First we find the intersection of all segments. To do this, denote by m the rightmost of left ends of the segments and denote by M the leftmost of right ends of the segments. The intersection of the segments is [m,M] (or empty set if m>M). Now determine the nearest point from this segment. If $x0 < m$, it's $m$, and the answer is $m - x0$. If $x0 > M$, it's $M$, and the answer is $x0 - M$. If $x_{0}\\in[m,M]$, it's $x0$, and the answer is 0. If m>M, then the answer is -1.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "14",
    "index": "C",
    "title": "Four Segments",
    "statement": "Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the program detects if the four given segments form a rectangle of a positive area and with sides parallel to coordinate axes. As Alex does badly at school and can't write this program by himself, he asks you to help him.",
    "tutorial": "There must be many ways to solve this problem. The following one seems quite easy to code.First count the number of distinct points among segments' ends. If it's not equal to 4, the segments can't form a rectangle and we output \"NO\". Then calculate the minimum and maximum coordinates of the 4 points: $xmin$, $xmax$, $ymin$, $ymax$. If $xmin = xmax$ or $ymin = ymax$, then even if the segments form a rectangle, it has zero area, so we also output \"NO\" in this case.Now if the segments indeed form a rectangle, we know the coordinates of its vertices - $(xmin, ymin)$, $(xmin, ymax)$, $(xmax, ymin)$ and $(xmax, ymax)$. We just check that every side of this rectangle appears in the input. If it is the case, we output \"YES\", otherwise we output \"NO\".",
    "tags": [
      "brute force",
      "constructive algorithms",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "14",
    "index": "D",
    "title": "Two Paths",
    "statement": "As you know, Bob's brother lives in Flatland. In Flatland there are $n$ cities, connected by $n - 1$ two-way roads. The cities are numbered from 1 to $n$. You can get from one city to another moving along the roads.\n\nThe «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).\n\nIt is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.",
    "tutorial": "Take any pair of non-intersecting paths. Since Flatland is connected, there must be a third path, connecting these two. Remove a road from the third path. Then Flatland is divided into two components - one containing the first path, and the other containing the second path. This observation suggests us the algorithm: iterate over the roads; for each road remove it, find the longest path in both connected components and multiply the lengths of these paths. The longest path in a tree can be found by depth first search from each leaf.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths",
      "trees",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "14",
    "index": "E",
    "title": "Camels",
    "statement": "Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with $t$ humps, representing them as polylines in the plane. Each polyline consists of $n$ vertices with coordinates $(x_{1}, y_{1})$, $(x_{2}, y_{2})$, ..., $(x_{n}, y_{n})$. The first vertex has a coordinate $x_{1} = 1$, the second — $x_{2} = 2$, etc. Coordinates $y_{i}$ might be any, but should satisfy the following conditions:\n\n- there should be $t$ humps precisely, i.e. such indexes $j$ ($2 ≤ j ≤ n - 1$), so that $y_{j - 1} < y_{j} > y_{j + 1}$,\n- there should be precisely $t - 1$ such indexes $j$ ($2 ≤ j ≤ n - 1$), so that $y_{j - 1} > y_{j} < y_{j + 1}$,\n- no segment of a polyline should be parallel to the $Ox$-axis,\n- all $y_{i}$ are integers between 1 and 4.\n\nFor a series of his drawings of camels with $t$ humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with $t$ humps for a given number $n$.",
    "tutorial": "Let us call an index j such that $yj - 1 > yj < yj + 1$ a cavity. Also, we'll call humps and cavities by the common word break. Then there must be exactly $T = 2t - 1$ breaks, and the first one must be a hump.Denote by $fnth$ the number of ways in which a camel with $t$ breaks, ending at the point (n,h), can be extended to the end (the vertical $xN = N$) so that the total number of breaks was equal to T. Note that:1. $fNTh = 1$, if h=1,2,3,4. (We have already finished the camel and it has T breaks)2. $fNth = 0$, if $0  \\le  t < T, h = 1, 2, 3, 4$. (We have already finished the camel, but it has less than T breaks)3. $fn, T + 1, h = 0$, if $1  \\le  n  \\le  N$, $h = 1, 2, 3, 4$. (The camel has already more than T breaks). Now we find the recurrent formula for $fnth$. Suppose that $t$ is even. Then the last break was a cavity, and we are moving up currently. We can continue moving up, then the number of breaks stays the same, and we move to one of the points $(n + 1, h + 1), (n + 1, h + 2), ..., (n + 1, 4)$. Or we can move down, then the number of breaks increases by 1, and we move to one of the points $(n + 1, h - 1), (n + 1, h - 2), ..., (n + 1, 1)$. This gives us the formula$f_{n t h}=\\sum_{H=h+1}^{4}f_{n+1,t,H}+\\sum_{H=1}^{h-1}f_{n+1,t+1,H}$.If $t$ is odd, then the last break was a hump, and similar reasoning leads to the formula$f_{n t h}=\\sum_{H=h+1}^{4}f_{n+1,t+1,H}+\\sum_{H=1}^{h-1}f_{n+1,t,H}$.We can calculate $fnth$ by dynamic programming. Consider now the point $(2, h)$ on a camel. There are h-1 ways to get to this point (starting from points $(1, 1), ..., (1, h - 1)$), and $f2, 0, h$ ways to extend the camel to the end. So the answer to the problem is $\\textstyle\\sum_{h=1}^{4}(h-1)f_{2,0,h}$.",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "17",
    "index": "A",
    "title": "Noldbach problem",
    "statement": "Nick is interested in prime numbers. Once he read about \\underline{Goldbach problem}. It states that every even integer greater than $2$ can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it \\underline{Noldbach problem}. Since Nick is interested only in prime numbers, Noldbach problem states that at least $k$ prime numbers from $2$ to $n$ inclusively can be expressed as the sum of three integer numbers: two neighboring prime numbers and $1$. For example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1.\n\nTwo prime numbers are called neighboring if there are no other prime numbers between them.\n\nYou are to help Nick, and find out if he is right or wrong.",
    "tutorial": "To solve this problem you were to find prime numbers in range $[2..N]$. The constraints were pretty small, so you could do that in any way - using the Sieve of Eratosthenes or simply looping over all possible divisors of a number.Take every pair of neighboring prime numbers and check if their sum increased by $1$ is a prime number too. Count the number of these pairs, compare it to $K$ and output the result.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "17",
    "index": "B",
    "title": "Hierarchy",
    "statement": "Nick's company employed $n$ people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are $m$ applications written in the following form: \\underline{«employee $a_{i}$ is ready to become a supervisor of employee $b_{i}$ at extra cost $c_{i}$»}. The qualification $q_{j}$ of each employee is known, and for each application the following is true: $q_{ai} > q_{bi}$.\n\nWould you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.",
    "tutorial": "Note that if employee, except one, has exactly one supervisor, then our hierarchy will be tree-like for sure.For each employee consider all applications in which he appears as a subordinate. If for more than one employee there are no such applications at all, it's obvious that $- 1$ is the answer. In other case, for each employee find such an application with minimal cost and add these costs to get the answer.Alternatively, you could use Kruskal's algorithm finding a minimum spanning tree for a graph. But you should be careful so that you don't assign the second supervisor to some employee.And yes, the employees' qualifications weren't actually needed to solve this problem :)",
    "tags": [
      "dfs and similar",
      "dsu",
      "greedy",
      "shortest paths"
    ],
    "rating": 1500
  },
  {
    "contest_id": "17",
    "index": "C",
    "title": "Balance",
    "statement": "Nick likes strings very much, he likes to rotate them, sort them, rearrange characters within a string... Once he wrote a random string of characters a, b, c on a piece of paper and began to perform the following operations:\n\n- to take two adjacent characters and replace the second character with the first one,\n- to take two adjacent characters and replace the first character with the second one\n\nTo understand these actions better, let's take a look at a string «abc». All of the following strings can be obtained by performing one of the described operations on «abc»: «bbc», «abb», «acc». Let's denote the \\underline{frequency of a character} for each of the characters a, b and c as the number of occurrences of this character in the string. For example, for string «abc»: |$a$| = 1, |$b$| = 1, |$c$| = 1, and for string «bbc»: |$a$| = 0, |$b$| = 2, |$c$| = 1.\n\nWhile performing the described operations, Nick sometimes got \\underline{balanced strings}. Let's say that a string is balanced, if the frequencies of each character differ by at most 1. That is $ - 1 ≤ |a| - |b| ≤ 1$, $ - 1 ≤ |a| - |c| ≤ 1$ и $ - 1 ≤ |b| - |c| ≤ 1$.\n\nWould you help Nick find the number of different balanced strings that can be obtained by performing the operations described above, perhaps multiple times, on the given string $s$. This number should be calculated modulo $51123987$.",
    "tutorial": "Consider the input string $A$ of length $n$. Let's perform some operations from the problem statement on this string; suppose we obtained some string $B$. Let compression of string $X$ be a string $X'$ obtained from $X$ by replacing all consecutive equal letters with one such letter. For example, if $S = \"aabcccbbaa\"$, then its compression $S' = \"abcba\"$.Now, consider compressions of strings $A$ and $B$ - $A'$ and $B'$. It can be proven that if $B$ can be obtained from some string $A$ using some number of operations from the problem statement, then $B'$ is a subsequence of $A'$, and vice versa - if for any strings $A$ and $B$ of equal length $B'$ is a subsequence of $A'$, then string $B$ can be obtained from string $A$ using some number of operations.Intuitively you can understand it in this manner: suppose we use some letter $a$ from position $i$ of $A$ in order to put letter $a$ at positions $j..k$ of $B$ (again, using problem statement operations). Then we can't use letters at positions $1..i - 1$ of string $A$ in order to influence positions $k + 1..n$ of string $B$ in any way; also, we can't use letters at positions $i + 1..n$ of string $A$ in order to influence positions $1..j - 1$ of string $B$.Now we have some basis for our solution, which will use dynamic programming. We'll form string $B$ letter by letter, considering the fact that $B'$ should still be a subsequence of $A'$ (that is, we'll search for $B'$ in $A'$ while forming $B$). For this matter we'll keep some position $i$ in string $A'$ denoting where we stopped searching $B'$ in $A'$ at the moment, and three variables $kA$, $kB$, $kC$, denoting the frequences of characters $a$, $b$, $c$ respectively in string $B$. Here are the transitions of our DP:1) The next character of string $B$ is $a$. Then we may go from the state $(i, kA, kB, kC)$ to the state $(nexti, 'a', kA + 1, kB, kC)$.2) The next character of string $B$ is $b$. Then we may go from the state $(i, kA, kB, kC)$ to the state $(nexti, 'b', kA, kB + 1, kC)$.3) The next character of string $B$ is $c$. Then we may go from the state $(i, kA, kB, kC)$ to the state $(nexti, 'c', kA, kB, kC + 1)$.Where $nexti, x$ is equal to minimal $j$ such that $j  \\ge  i$ and $A'j = x$ (that is, the nearest occurrence of character $x$ in $A'$, starting from position $i$). Clearly, if in some case $nexti, x$ is undefined, then the corresponding transition is impossible.Having calculated $f(i, kA, kB, kC)$, it's easy to find the answer: $\\textstyle\\sum_{i=1\\ldots1A^{\\prime}!}f(i,k A,k B,k C)$ for all triples $kA$, $kB$, $kC$ for which the balance condition is fulfilled.Such a solution exceeds time and memory limits. Note that if string $B$ is going to be balanced, then $kA, kB, kC  \\le  (n + 2) / 3$, so the number of states can be reduced up to 27 times. But it's also possible to decrease memory usage much storing matrix $f$ by layers, where each layer is given by some value of $kA$ (or $kB$ or $kC$). It's possible since the value of $kA$ is increased either by $0$ or by $1$ in each transition.The overall complexity is $O(N4)$ with a quite small constant.",
    "tags": [
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "17",
    "index": "D",
    "title": "Notepad",
    "statement": "Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base $b$ caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length $n$ without leading zeros in this number system. Each page in Nick's notepad has enough space for $c$ numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number $0$ as he has unpleasant memories about zero divide.\n\nWould you help Nick find out how many numbers will be written on the last page.",
    "tutorial": "The answer to the problem is $bn - 1 * (b - 1)$ mod $c$. The main thing you should be able to do in this problem - count the value of $AB$ mod $C$ for some long numbers $A$ and $B$ and a short number $C$. Simple exponentiation by squaring exceeds time limit since to converse of $B$ to binary you need about $O(|B|2)$ operations, where $|B|$ is the number of digits in decimal representation of number $B$.The first thing to do is to transform $A$ to $A$ mod $C$. It isn't difficult to understand that this transformation doesn't change the answer.Let's represent $C$ as $C = p1k1p2k2...pmkm$, where $pi$ are different prime numbers.Calculate $ti = AB$ mod $piki$ for all $i$ in the following way. There are two possible cases:1) $A$ is not divisible by $pi$: then $A$ and $pi$ are coprime, and you can use Euler's theorem: $AB' = AB$ (mod $C$), where $B' = B$ mod $ \\phi (C)$ and $ \\phi (C)$ is Euler's totient function;2) $A$ is divisible by $pi$: then if $B  \\ge  ki$ then $ti = AB$ mod $piki = 0$, and if $B < ki$ then you can calculate $ti$ in any way since B is very small.Since all $piki$ are pairwise coprime you may use chinese remainder theorem to obtain the answer.You can also use Euler's theorem directly. Note that if for some $B1, B2  \\ge  29$ you know that $|B1 - B2|$ mod $ \\phi (C) = 0$, then all $ti$ for them will be the same ($29$ is the maximal possible value of $ki$). Using that you may reduce $B$ so that it becomes relatively small and obtain the answer using exponentiation by squaring.There is another solution used by many contestants. Represent $B$ as $B = d0 + 10d1 + 102d2 + ... + 10mdm$, where $0  \\le  di  \\le  9$ (in fact $di$ is the $i$-th digit of $B$ counting from the last). Since $ax + y = ax \\cdot  ay$, you know that $AB = Ad0 \\cdot  A10d1 \\cdot  ... \\cdot  A10mdm$. The values of $ui = A10i$ can be obtained by successive exponentiation (that is, $ui = ui - 110$); if you have $A10i$, it's easy to get $A10idi = uidi$. The answer is the product above (modulo $C$, of course).",
    "tags": [
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "17",
    "index": "E",
    "title": "Palisection",
    "statement": "In an English class Nick had nothing to do at all, and remembered about wonderful strings called \\underline{palindromes}. We should remind you that a string is called a palindrome if it can be read the same way both from left to right and from right to left. Here are examples of such strings: «eye», «pop», «level», «aba», «deed», «racecar», «rotor», «madam».\n\nNick started to look carefully for all palindromes in the text that they were reading in the class. For each occurrence of each palindrome in the text he wrote a pair — the position of the beginning and the position of the ending of this occurrence in the text. Nick called each occurrence of each palindrome he found in the text \\underline{subpalindrome}. When he found all the subpalindromes, he decided to find out how many different pairs among these subpalindromes cross. Two subpalindromes cross if they cover common positions in the text. No palindrome can cross itself.\n\nLet's look at the actions, performed by Nick, by the example of text «babb». At first he wrote out all subpalindromes:\n\n\\begin{center}\n• «b» — $1..1$\n\\end{center}\n\n\\begin{center}\n• «bab» — $1..3$\n\\end{center}\n\n\\begin{center}\n• «a» — $2..2$\n\\end{center}\n\n\\begin{center}\n• «b» — $3..3$\n\\end{center}\n\n\\begin{center}\n• «bb» — $3..4$\n\\end{center}\n\n\\begin{center}\n• «b» — $4..4$\n\\end{center}\n\nThen Nick counted the amount of different pairs among these subpalindromes that cross. These pairs were six:\n\n\\begin{center}\n1. $1..1$ cross with $1..3$\n\\end{center}\n\n\\begin{center}\n2. $1..3$ cross with $2..2$\n\\end{center}\n\n\\begin{center}\n3. $1..3$ cross with $3..3$\n\\end{center}\n\n\\begin{center}\n4. $1..3$ cross with $3..4$\n\\end{center}\n\n\\begin{center}\n5. $3..3$ cross with $3..4$\n\\end{center}\n\n\\begin{center}\n6. $3..4$ cross with $4..4$\n\\end{center}\n\nSince it's very exhausting to perform all the described actions manually, Nick asked you to help him and write a program that can find out the amount of different subpalindrome pairs that cross. Two subpalindrome pairs are regarded as different if one of the pairs contains a subpalindrome that the other does not.",
    "tutorial": "The first thing to do is to find all subpalindromes in the given string. For this you may use a beautiful algorithm described for example here. In short, this algorithm find the maximal length of a subpalindrome with its center either at position $i$ of the string or between positions $i$ and $i + 1$ for each possible placement of the center.For example, suppose that the maximal subpalindrome length with center at position $i$ is $5$; it means that there are three subpalindromes with center at $i$, with lengths $1$ ($i..i$), $3$ ($i - 1..i + 1$) and $5$ ($i - 2..i + 2$). In general, all starting and finishing positions of subpalindromes with a fixed center lie on some interval of positions, which is pretty easy to find.Let's find for each position $i$ the value of $starti$, which is equal to the number of subpalindromes starting at position $i$. All these values can be found in linear time. Let's create an auxiliary array $ai$. If after processing a position in the string some new pack of subpalindromes was found and they start at positions $i..j$, then increase the value of $ai$ by $1$, and decrease the value of $aj + 1$ by $1$. Now $s t a r t_{i}=\\sum_{k=1\\ldots i}a_{i}$. Proving this fact is left as an exercise to the reader :)In a similar way it's possible to calculate $finishi$, which is equal to the number of subpalindromes finishing at position $i$.Since it's easy to count the total number of subpalindromes, let's find the number of non-intersecting pairs of subpalindromes and subtract this number from the total number of pairs to obtain the answer. Note that if two subpalindromes don't intersect then one of them lies strictly to the left of the other one in the string. Then, the number of non-intersecting pairs of subpalindromes is equal to: $\\textstyle\\sum_{i=1\\ldots n}(s t a r t_{i}\\cdot\\sum_{i=1,i-1}f i n i s h_{j})$This can be calculated in linear time if the value of $\\sum_{j=1..i-1}f i n i s h_{j}$ is recalculated by addition of $finishi$ before moving from position $i$ to position $i + 1$.The overall complexity of the algorithm is $O(N)$.",
    "tags": [
      "strings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "19",
    "index": "A",
    "title": "World Football Cup",
    "statement": "Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations:\n\n- the final tournament features $n$ teams ($n$ is always even)\n- the first $n / 2$ teams (according to the standings) come through to the knockout stage\n- the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals\n- it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity.\n\nYou are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.",
    "tutorial": "I think is' just a problem about writing code quickly and correctly.Just follow the statement. if you use c++ STL will make you life easier",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "19",
    "index": "B",
    "title": "Checkout Assistant",
    "statement": "Bob came to a cash & carry store, put $n$ items into his trolley, and went to the checkout counter to pay. Each item is described by its price $c_{i}$ and time $t_{i}$ in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant.",
    "tutorial": "First,for every i increase ti by 1..then you will see that statement require sum of t of the items bigger or equal to n..and their sum of c should be minimal..so it's just a 0-1 knapsack problem.",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "19",
    "index": "C",
    "title": "Deletion of Repeats",
    "statement": "Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length $x$ is such a substring of length $2x$, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat.\n\nYou're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above.",
    "tutorial": "First let's generate all repeats.In a repeat,the first number and the middle number must be the same, so we just look at all pair of postion which have same number..Thank to the statement..There are at most O(10N) such pair..And use suffix array to check if each pair can build a repeat...Then just sort all the interval and go through then to get the answer...http://en.wikipedia.org/wiki/Suffix_arraymaybe you think suffix array is hard to code..you can use hash and binary search to do the same..",
    "code": "#include <vector>\n#include <algorithm>\n#include <utility>\n#include <iostream>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <set>\n#include <map>\n#include <cstring>\n#include <time.h>\n#define rep(i,n) for(int i=0;i<n;i++)\n#define pb push_back\n#define Debug(x) cout<<#x<<\"=\"<<x<<endl;\n#define For(i,l,r) for(int i=l;i<=r;i++)\n#define tr(e,x) for(typeof(x.begin()) e=x.begin();e!=x.end();e++)\n#define printTime cout<<\"Time:\"<<pre-clock()<<endl;pre=clock();\nconst int inf=~0U>>1,maxn=100000+10,Log=20,seed=133331;\nusing namespace std;\ntypedef vector<int> VI;\ntypedef long long ll;\nconst ll F=354871524;\nmap<int,VI> Map;\nint n,A[maxn];\nll P[Log];\nll Hash[maxn][Log];\nvoid DoIt()\n{\n    P[0]=seed;rep(i,Log-1)P[i+1]=P[i]*P[i];\n    rep(j,Log)rep(i,n)\n    if(i+(1<<j)<=n)\n    {\n        ll&tmp=Hash[i][j];\n        if(!j)tmp=A[i]^F;\n        else tmp=(Hash[i][j-1])*P[j-1]+Hash[i+(1<<(j-1))][j-1];\n    }\n}\nint Lcp(int a,int b)\n{\n    if(a>b)swap(a,b);int ret=0;\n    for(int i=Log-1;i>=0;i--)\n    {\n        if(b+(1<<i)>n)continue;\n        if(Hash[a][i]==Hash[b][i])\n            a+=(1<<i),b+=(1<<i),ret+=(1<<i);\n    }\n    return ret;\n}\nbool Check(int a,int b)\n{\n    int s=b-a;\n    return Lcp(a,b)>=s;\n}\nstruct Seg\n{\n    int l,r,s;\n    Seg(int _l,int _r):l(_l),r(_r),s(r-l){}\n    bool operator<(const Seg&o)const\n    {\n        if(s!=o.s)return s<o.s;\n        return l<o.l;\n    }\n};\nint main()\n{\n    //freopen(\"in\",\"r\",stdin);\n    cin>>n;\n    rep(i,n)scanf(\"%d\",A+i),Map[A[i]].pb(i);\n    DoIt();\n    vector<Seg> S;\n    for(map<int,VI>::iterator it=Map.begin();it!=Map.end();it++)\n    {\n        VI&tmp=it->second;\n        For(i,0,tmp.size()-1)\n            For(j,i+1,tmp.size()-1)\n                if(Check(tmp[i],tmp[j]))\n                    S.pb(Seg(tmp[i],tmp[j]-1));\n    }\n    sort(S.begin(),S.end());\n    int now=0;\n    rep(i,S.size())\n    {\n        Seg&tmp=S[i];\n        if(tmp.l>=now)now=tmp.r+1;\n    }\n    cout<<n-now<<endl;\n    For(i,now,n-1)cout<<A[i]<<\" \";\n}",
    "tags": [
      "greedy",
      "hashing",
      "string suffix structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "19",
    "index": "D",
    "title": "Points",
    "statement": "Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point $(0, 0)$ is located in the bottom-left corner, $Ox$ axis is directed right, $Oy$ axis is directed up. Pete gives Bob requests of three types:\n\n- add x y — on the sheet of paper Bob marks a point with coordinates $(x, y)$. For each request of this type it's guaranteed that point $(x, y)$ is not yet marked on Bob's sheet at the time of the request.\n- remove x y — on the sheet of paper Bob erases the previously marked point with coordinates $(x, y)$. For each request of this type it's guaranteed that point $(x, y)$ is already marked on Bob's sheet at the time of the request.\n- find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point $(x, y)$. Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete.\n\nBob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to $2·10^{5}$, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please!",
    "tutorial": "First of all,do the discretization.Then the biggest value of x is n,so we can build a Segment Tree to Ask the question \"what is the first place from postion x and its value is bigger than y\"..if we find such postion we just find the smallest Y-value bigger than y in such postion--it can be done using set's operation upper_bound...http://en.wikipedia.org/wiki/Segment_tree so the algorithm is clear..For every possible value of x use a set to store all y value in it..And every time the action is \"find\" or \"remove\" just change this set and update the Segment Tree..otherwise use Segment Tree to find the answer..",
    "code": "#include <vector>\n#include <algorithm>\n#include <utility>\n#include <iostream>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <set>\n#include <map>\n#include <cstring>\n#include <time.h>\n#define rep(i,n) for(int i=0;i<n;i++)\n#define pb push_back\n#define Debug(x) cout<<#x<<\"=\"<<x<<endl;\n#define For(i,l,r) for(int i=l;i<=r;i++)\n#define tr(e,x) for(typeof(x.begin()) e=x.begin();e!=x.end();e++)\n#define printTime cout<<\"Time:\"<<pre-clock()<<endl;pre=clock();\nconst int inf=~0U>>1,maxn=200000+10;\nusing namespace std;\nint n,m;\nstruct Index\n{\n    int A[maxn],n;\n    int size(){return n;}\n    void clear(){n=0;}\n    void add(int x){A[n++]=x;}\n    void doit()\n    {\n        sort(A,A+n);n=unique(A,A+n)-A;\n    }\n    int operator[](int v){return lower_bound(A,A+n,v)-A;}\n}IX;\nchar cmd[100];\nstruct Action\n{\n    int type,x,y;\n    void readin()\n    {\n        scanf(\"%s%d%d\",cmd,&x,&y);\n        IX.add(x);\n        if(cmd[0]=='a')type=0;\n        if(cmd[0]=='r')type=1;\n        if(cmd[0]=='f')type=2;\n    }\n}A[maxn];\nset<int> S[maxn];\nint M(int i){return *(--S[i].end());}\nint Max[maxn*4];\n#define Tree int t,int l,int r\n#define Left t*2,l,l+r>>1\n#define Right t*2+1,l+r>>1,r\n#define root 1,0,m\nvoid Update(int t)\n{\n    Max[t]=max(Max[t*2],Max[t*2+1]);\n}\nvoid Change(Tree,int p)\n{\n    if(p<l||p>=r)return;\n    if(l+1==r){Max[t]=M(l);return;}\n    Change(Left,p);Change(Right,p);\n    Update(t);\n}\nint Query(Tree,int a,int c)\n{\n    if(a>=r||Max[t]<=c)return -1;\n    if(l+1==r)return l;\n    int tmp=Query(Left,a,c);if(tmp>=0)return tmp;\n    tmp=Query(Right,a,c);if(tmp>=0)return tmp;\n    return -1;\n}\nvoid init()\n{\n    cin>>n;\n    rep(i,n)A[i].readin();\n    IX.doit();\n}\nvoid Solve()\n{\n    m=IX.size();memset(Max,-1,sizeof Max);\n    rep(i,m)S[i].insert(-1);\n    rep(i,n)\n    {\n        int x=A[i].x,y=A[i].y;x=IX[x];\n        switch(A[i].type)\n        {\n            case 0:S[x].insert(y);Change(root,x);break;\n            case 1:S[x].erase(S[x].find(y));Change(root,x);break;\n            case 2:int tmp=Query(root,x+1,y);\n                if(tmp==-1)printf(\"-1\n\");\n                else\n                {\n                    set<int>::iterator it=S[tmp].upper_bound(y);\n                    printf(\"%d %d\n\",IX.A[tmp],*it);\n                }\n        }\n    }\n}\nint main()\n{\n    //freopen(\"in\",\"r\",stdin);\n    init();\n    Solve();\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2800
  },
  {
    "contest_id": "19",
    "index": "E",
    "title": "Fairy",
    "statement": "Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper $n$ points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess.",
    "tutorial": "It's a interesting problem.If you for every edge, try to remove it and check if it is a bipartite graph..I think it will get TLE..so let's analysis the property of bipartite graph..http://en.wikipedia.org/wiki/Bipartite_graphAfter reading it...we know.. It should never contain a cycle of odd length... and it can be 2-colored.. so first build a spanning forest for the graph.. and do the 2-color on it(Tree can be 2-colored). for convenience. Let TreeEdge={all edge in forest} NotTreeEdge={All edge}/TreeEdge ErrorEdge={all edge that two endpoint have the same color..} NotErorEdge=NotTreeEdge/ErroEdge.. First,consider a edge form NotTreeEdge,remove it can't change any node's color..so.. if |ErrorEdge|=0 of course we can remove all NotTreeEdge if =1 we just can remove the ErrorEdge if >1 we can't remove any from NotTreeEdge Now,Let consider a Edge e from TreeEdge.. Let Path(Edge e)=the path in forest between e's two endpoints.. if there is a Edge e' from ErrorEdge that Path(e') didn't go through e..it will destroy the bipartite graph.. if there is a Edge e' from ErrorEdge that Path(e') go through e and there is a Edge e'' from NotErrorEdge that Path(e'') go through e..it will also destroy the bipartite graph.. so now we need to know for every edge,how many such path go through it..it require a data structure... one way is to use heavy-light decomposition then we can update every path in O(LogN^2)... another way is to use Link-Cut Tree..It can do the same in O(LogN)....if you didn't see Link-Cut tree before,you can read thishttp://www.cs.cmu.edu/~sleator/papers/dynamic-trees.pdfor my code..use heavy-light decomposition",
    "code": "#include <vector>\n#include <algorithm>\n#include <utility>\n#include <iostream>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <set>\n#include <map>\n#include <cstring>\n#include <time.h>\n#define rep(i,n) for(int i=0;i<n;i++)\n#define pb push_back\n#define Debug(x) cout<<#x<<\"=\"<<x<<endl;\n#define For(i,l,r) for(int i=l;i<=r;i++)\n#define tr(e,x) for(vector<int>::iterator e=x.begin();e!=x.end();e++)\n#define printTime cout<<\"Time:\"<<pre-clock()<<endl;pre=clock();\nconst int inf=~0U>>1,maxn=10000;\nusing namespace std;\ntypedef pair<int,int> pi;\nvector<int> E[maxn];\nmap<pi,int> Map;\nvector<pi> Es;\nset<pi> InTree;\nint mnt=0,n,m;\nstruct TA\n{\n    vector<int> A;\n    int s;\n    void Add(int l,int d)\n    {\n        l-=s;\n        for(l++;l<=A.size();l+=l&-l)\n            A[l-1]+=d;\n    }\n    void Add(int l,int r,int d)\n    {\n        Add(l,d);Add(r+1,-d);\n    }\n    int Sum(int l)\n    {\n        l-=s;int ret=0;\n        for(l++;l;l-=l&-l)ret+=A[l-1];\n        return ret;\n    }\n    void Build(int l,int r)\n    {\n        s=l;int n=r-l+1;A=vector<int>(n);\n    }\n}T[2][maxn];\nvoid AddEdge(int s,int t)\n{\n    E[s].pb(t);E[t].pb(s);\n    Map[pi(s,t)]=Map[pi(t,s)]=mnt++;\n    Es.pb(pi(s,t));\n}\nint D[maxn],F[maxn];\nbool c[maxn];\nint Q[maxn],h,t,Size[maxn],own[maxn];\nbool Vis[maxn]={};\nvoid BFS(int vs)\n{\n    h=t=0;\n    for(F[vs]=-1,Vis[vs]=true,Q[t++]=vs,D[vs]=0;h<t;h++)\n    {\n        int x=Q[h];c[x]=D[x]%2;\n        tr(e,E[x])if(!Vis[*e])\n        {\n            Q[t++]=*e;F[*e]=x;\n            D[*e]=D[x]+1;Vis[*e]=true;\n            InTree.insert(pi(x,*e));\n            InTree.insert(pi(*e,x));\n        }\n    }\n    for(int i=h-1;i>=0;i--)\n    {\n        int x=Q[i];Size[x]=1;\n        tr(e,E[x])if(F[*e]==x)Size[x]+=Size[*e];\n    }\n    for(int i=0;i<h;i++)\n    {\n        int a=Q[i];if(own[a]>=0)continue;\n        int x=a,next;\n        for(;;x=next)\n        {\n            next=-1;own[x]=a;\n            tr(e,E[x])if(F[*e]==x)\n                if(next==-1||Size[*e]>Size[next])\n                    next=*e;\n            if(next==-1)break;\n        }\n        rep(j,2)T[j][a].Build(D[a],D[x]);\n    }\n}\nvoid MarkThePath(int u,int v,int t)\n{\n    for(;;)\n    {\n        if(D[u]<D[v])swap(u,v);\n        if(own[u]==own[v])\n        {\n            T[t][own[u]].Add(D[v]+1,D[u],1);\n            return;\n        }\n        if(D[own[u]]<D[own[v]])swap(u,v);\n        T[t][own[u]].Add(D[own[u]],D[u],1);\n        u=F[own[u]];\n    }\n}\nint GetTheValue(int u,int v,int t)\n{\n    if(D[u]<D[v])swap(u,v);\n    return T[t][own[u]].Sum(D[u]);\n}\nbool IsTreeEdge(int u,int v)\n{\n    if(D[u]<D[v])swap(u,v);\n    return D[u]==D[v]+1;\n}\nvoid init()\n{\n    scanf(\"%d%d\",&n,&m);int s,t;\n    rep(i,m)\n    {\n        scanf(\"%d%d\",&s,&t);--s;--t;\n        AddEdge(s,t);\n    }\n}\nvector<pi> Ans;\nvoid Solve()\n{\n    //Built It\n    memset(own,-1,sizeof own);\n    rep(i,n)if(!Vis[i])BFS(i);\n    vector<pi> TreeEdge,NotErrorEdge,ErrorEdge;\n    //For All Tree Not On Tree\n    rep(i,Es.size())\n    {\n        pi e=Es[i];\n        if(InTree.find(e)!=InTree.end())\n        {\n            TreeEdge.pb(e);\n        }\n        else\n        {\n            if(c[e.first]==c[e.second])\n                ErrorEdge.pb(e);\n            else\n                NotErrorEdge.pb(e);\n        }\n    }\n    if(ErrorEdge.size()==0)\n        Ans=NotErrorEdge;\n    if(ErrorEdge.size()==1)\n        Ans=ErrorEdge;\n    //Mark The Path For ErorrEdge\n    rep(i,ErrorEdge.size())\n    {\n        pi e=ErrorEdge[i];\n        MarkThePath(e.first,e.second,0);\n    }\n    //Mark The Path For NotErorrEdge\n    rep(i,NotErrorEdge.size())\n    {\n        pi e=NotErrorEdge[i];\n        MarkThePath(e.first,e.second,1);\n    }\n    // For All Tree Edge\n    int a[2];\n    rep(i,TreeEdge.size())\n    {\n        pi e=TreeEdge[i];\n        rep(j,2)a[j]=GetTheValue(e.first,e.second,j);\n        if(a[0]<ErrorEdge.size()||(a[0]&&a[1]))continue;\n        Ans.pb(e);\n    }\n    vector<int> Print;\n    rep(i,Ans.size())Print.pb(Map[Ans[i]]+1);\n    sort(Print.begin(),Print.end());\n    cout<<Print.size()<<endl;\n    rep(i,Print.size())cout<<Print[i]<<\" \";cout<<endl;\n}\nint main()\n{\n    //freopen(\"in\",\"r\",stdin);\n    init();\n    Solve();\n}",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "dsu"
    ],
    "rating": 2900
  },
  {
    "contest_id": "22",
    "index": "A",
    "title": "Second Order Statistics",
    "statement": "Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.",
    "tutorial": "In this problem one should find a minimal element from all elements, that are strictly greater, then the minimal one or report that it doesn't exist. Of course, there can be a lot of different solutions, but one of the simplest - to sort the given sequence and print the first element, that's not equal to the previous. If all elements are equal, then the required element doesn't exist.",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "22",
    "index": "B",
    "title": "Bargaining Table",
    "statement": "Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room $n × m$ meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office.",
    "tutorial": "In this problem one should find the maximal perimeter of a rectangle that contains no '1'. Define these rectangles \"correct\". To solve a problem you are to check each possible rectangle for correctness and calculate its perimeter. The easiest way to check all rectangles is using 6 nested cycles. Using 4 of them you fix the coordinates while other 2 will look for '1'. So the complexity is O((n*m)3). It seems slow, but those, who wrote such a solution, says that it hasn't any problems with TL.One may interest in much faster solution. Using simple DP solution one can get a solution with an O((n*m)2) complexity. It's clear, that rectangle with coordinates (x1, y1, x2, y2) is correct if and only if rectangles (x1, y1, x2-1, y2) and (x1, y1, x2, y2-1) are correct, and board[x2][y2] = '0'. So each of rectangles can be checked in O(1) and totally there will be O((n*m)2) operations.",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "22",
    "index": "C",
    "title": "System Administrator",
    "statement": "Bob got a job as a system administrator in X corporation. His first task was to connect $n$ servers with the help of $m$ two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index $v$ fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.",
    "tutorial": "In this problem you are to construct a connected graph, which contains n vertexes and m edges, and if we delete vertex with number v, our graph stops being connected or to report that such a graph doesn't exist. Moreover, each pair of vertexes can have no more than one edge connecting them. Obviously, a connected graph doesn't exist if the number of edges is less than n-1. It's easy to notice, that the maximal possible number of edges reaches when there is a vertex connected to v and doesn't connected to any other vertex, those can form up to complete graph. So the maximal number of edges is (n-1)*(n-2)/2+1. If m is in that range then required graph always exists. Then you should place one vertex on the one side of v (let it be 1), and other vertexes - on the other side. First, you should connect all this vertexes to v and then connect them between each other (except 1).",
    "tags": [
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "22",
    "index": "D",
    "title": "Segments",
    "statement": "You are given $n$ segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?",
    "tutorial": "In this problem one should place minimal number of points on the line such that any given segment touches at least one of these points. Let's call the coordinate of ending of any segment as event. There will be events of two types: beginning of a segment and its ending. Let's sort this events by coordinates. In the case of equality of some events consider that the event of the beginning will be less than the event of ending. Look at our events from left to right: if there is a beginning event, then push the number of this segment to the special queue. Once we take an ending of some segment, place the point here and clear the special queue (because each of segment in this queue will touch this point).",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "22",
    "index": "E",
    "title": "Scheme",
    "statement": "To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index $i$ got a person with index $f_{i}$, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes — there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they \\underline{add} into the scheme some instructions of type $(x_{i}, y_{i})$, which mean that person $x_{i}$ has to call person $y_{i}$ as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?",
    "tutorial": "Given an oriented graph, find the minimal number of edges one should add to this graph to make it strongly connected. Looking at statement we can get the fact that each vertex has exactly one outcoming edge. It means that starting at some point we'll get stuck in some cycle. So each connected (not strongly) component is a set of simple paths, ending in some cycle or just a simple cycle. First consider vertexes, which has no incoming edges. When passing through some vertex we'll paint it until the current vertex will be already painted. Then we call the starting vertex as \"beginning\" and the finishing one as \"ending\" of a component.After that consider other vertexes - they belong to cycles. Beginning and ending of a cycle - is any vertexes (possible coinciding) belonging to it. So we got a number of components which we have to connect. Let's connect them cyclically: the edge will pass from the ending of i-th component to the beginning of ((i+1)%k)-th, where k is the number of such components. The answer will be k. There is an exception: if we have only one component which is a simple cycle, the answer will be equal to 0.So we'll consider each edge exactly once and the total complexity will be O(n).",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "23",
    "index": "A",
    "title": "You're Given a String...",
    "statement": "You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).",
    "tutorial": "Iterate over all substrings, starting with the longest ones, and for each one count the number of appearances. The complexity is $O(L4)$ with a small multiplicative constant.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "23",
    "index": "B",
    "title": "Party",
    "statement": "$n$ people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly $2, 3, ..., n - 1$ friends among those who stayed by the moment of their leaving, did the same.\n\nWhat is the maximum amount of people that could stay at the party in the end?",
    "tutorial": "It's clear that at least one person (the one with the least number of friends) will have to leave. We claim that at least two persons will leave. Indeed, suppose that only one person left, and he had $d$ friends. Then all other people had more than $d$ friends before he left, and after that they had less than $d + 1$ friends, i.e. not more than $d$. So, his leaving influenced the number of friends for every other person, which means that he was friends with everyone: $d = N - 1$. But he has fewer friends than everyone - a contradiction.So, the answer is not more than $N - 2$. We'll prove that it's possible for $N - 2$ people to stay (of course, if $N > 1$). The graph of friendship will be the following: take a complete graph on $N$ vertices and delete one edge. Then the degrees of two vertices equal $N - 2$, and other degrees equal $N - 1$. After the first two vertices are removed, we have a complete graph on $N - 2$ vertices, and all degrees equal $N - 3$, which means that no one else will leave.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "23",
    "index": "C",
    "title": "Oranges and Apples",
    "statement": "In $2N - 1$ boxes there are apples and oranges. Your task is to choose $N$ boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges.",
    "tutorial": "Sort the boxes in increasing number of oranges. Count the total number of apples in boxes with odd and even numbers. If the boxes with odd numbers contain at least half of all apples, choose them (there are exactly $N$ boxes with odd numbers). If the boxes with even numbers contain at least half of all apples, take them and the last box (which contains the largest number of oranges). It's easy to see that in both cases the conditions of the task are fulfilled.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "23",
    "index": "D",
    "title": "Tetragon",
    "statement": "You're given the centers of three equal sides of a strictly convex tetragon. Your task is to restore the initial tetragon.",
    "tutorial": "Let ABCD be the quadrangle that we're looking for, and K, L, and M be the middle points of equal sides AB, BC and CD, correspondingly. Let M' be the point symmetric to M with respect to L. Triangles BLM' and CLM are equal by two sides and angle, so BM' = CM = BL = BK, i. e. B is the circumcenter of the triangle KLM'. Knowing B, we can reconstruct the whole quadrangle, using the symmetries with respect to the points K, L, and M, and then check whether it satisfies all conditions.Note that we don't know which of the given points is L, so we need to check all 3 cases.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "23",
    "index": "E",
    "title": "Tree",
    "statement": "Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree.",
    "tutorial": "Lemma. In one of optimal solutions there are no simple paths of length 3.Proof. We can remove the middle edge from such a path. The connected component will split into two components of sizes $a$ and $b$, where $a  \\ge  2, b  \\ge  2$, and therefore $ab  \\ge  a + b$.We'll root the tree and calculate recursively the numbers $hv$ = the solution of the problem for the subtree with the root $v$, and $fv$ = the product of $hu$ for all children of $v$. If $v$ is a leaf, then $hv = fv = 1$.We show how to calculate $hv$, given the solution for all subtrees of $v$. Consider the connected component of $v$ in an optimal solution. It follows from the lemma that the component has one of the following types:1. The single vertex $v$.2. The vertex $v$ and several children of $v$.3. The vertex $v$, one child of $v$ - $w$, and several children of $w$.In the first case the result of the game is $fv$.In the second case it equals $ \\Pi fi  \\cdot   \\Pi hj  \\cdot  k =  \\Pi (fi / hi)  \\cdot  fv  \\cdot  k$, where $i$ iterates over children belonging to the connected component, $j$ iterates over the rest children, and $k$ is the size of the component. Since we want to maximize the result, we're interested in children with the largest value of $fi / hi$. Therefore, the largest possible result in this case equals the maximum value of $ \\Pi i  \\le  s (fi / hi)  \\cdot  fv  \\cdot  (s + 1)$, where it's supposed that the children are sorted in descending order of $fi / hi$.In the third case we can use a similar reasoning for every child $w$. The best result will be the maximum of the expression $fv  \\cdot  (fw / hw)  \\cdot   \\Pi i  \\le  s (fi / hi)  \\cdot  (s + 2)$ as $w$ iterates over children of $v$, and $s$ iterates from 1 to the number of children of $w$; note that the children of $w$ have already been sorted in the previous step.Therefore, the number of operations necessary to calculate $fv$ is proportional to the total number of children and grandchildren of $v$, which is less than $n$. The complexity of the algorithm, then, is $O(n2)$ (ignoring operations with long numbers).",
    "tags": [
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "24",
    "index": "A",
    "title": "Ring road",
    "statement": "Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all $n$ cities of Berland were connected by $n$ two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all $n$ roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?",
    "tutorial": "This is pretty simple task - we have cycle and must direct all edges on it in one of 2 directions. We need to calculate cost of both orientation and print smallest of them.There is a small trick - we can calculate cost of only one orientation and then cost of the other will be sum of costs of all edges minus cost of first orientation.",
    "tags": [
      "graphs"
    ],
    "rating": 1400
  },
  {
    "contest_id": "24",
    "index": "B",
    "title": "F1 Champions",
    "statement": "Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare.\n\nLast year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.\n\nYou are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.",
    "tutorial": "Also very simple - we need literary do what we asked. We put all data in a map where for each pilot we have number of points and array of 50 elements - number of times pilot finished at corresponding place. Then we just need to find maximum in this array according to 2 given criteria.",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "24",
    "index": "C",
    "title": "Sequence of points",
    "statement": "You are given the following points with integer coordinates on the plane: $M_{0}, A_{0}, A_{1}, ..., A_{n - 1}$, where $n$ is odd number. Now we define the following infinite sequence of points $M_{i}$: $M_{i}$ is symmetric to $M_{i - 1}$ according ${\\cal A}_{\\{i-1\\}}\\,\\mathrm{\\mod}\\,\\,n$ (for every natural number $i$). Here point $B$ is symmetric to $A$ according $M$, if $M$ is the center of the line segment $AB$. Given index $j$ find the point $M_{j}$.",
    "tutorial": "Reflection over 2 points is just a parallel shift for a doubled vector between them. So $M2n$ = $M0$ because sequence of reflections may be replaced with sequence of shifts with doubled vectors $A0A2$, $A2A4$, ..., $An - 2A0$ - and their sum is 0. So we can replace j with $j' = jmod2N$. Now we can just perform j' reflections. Suppose we need to find M' (x', y') - reflection of M(x, y) witch center at A($x0$, $y0$). Then $x' = 2x0 - x$, $y' = 2y0 - y$.",
    "tags": [
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "24",
    "index": "D",
    "title": "Broken robot",
    "statement": "You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of $N$ rows and $M$ columns of cells. The robot is initially at some cell on the $i$-th row and the $j$-th column. Then at every step the robot could go to some another cell. The aim is to go to the bottommost ($N$-th) row. The robot can stay at it's current cell, move to the left, move to the right, or move to the cell below the current. If the robot is in the leftmost column it cannot move to the left, and if it is in the rightmost column it cannot move to the right. At every step all possible moves are equally probable. Return the expected number of step to reach the bottommost row.",
    "tutorial": "If robot is at last row then answer is 0. Suppose that for every cell of the next row we now expected number of steps to reach last row - $zi$. Let $xi$ be expected value of steps to reach the last row from current row. Then we have following system of equations:$x1 = 1 + x1 / 3 + x2 / 3 + z1 / 3$$xi = 1 + xi / 4 + xi - 1 / 4 + xi + 1 / 4 + zi / 4$ for i from 2 to M - 1$xM = 1 + xM / 3 + xM - 1 / 3 + zM / 3$This is tridiagonal system, it can be solved using tridiagonal matrix algorithm in linear time.So we just have to solve this for each row starting from N - 1 and ending at i and then take x[j].For M = 1 the answer is 2(N - i) because expected number of steps to go down is 2 - on each turn we either go down or stay",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "24",
    "index": "E",
    "title": "Berland collider",
    "statement": "Recently the construction of Berland collider has been completed. Collider can be represented as a long narrow tunnel that contains $n$ particles. We associate with collider 1-dimensional coordinate system, going from left to right. For each particle we know its coordinate and velocity at the moment of start of the collider. The velocities of the particles don't change after the launch of the collider. Berland scientists think that the big bang will happen at the first collision of particles, whose velocities differs in directions. Help them to determine how much time elapses after the launch of the collider before the big bang happens.",
    "tutorial": "At first we need to exclude answer -1. Answer is -1 if and only if first part of particles moves left and second part moves right (any of this parts may be empty)Let's use binary search. Maximal answer is 1e9. Suppose we need to unserstand - whether answer is more then t or less then t. Let's itirate particles from left to right and maintain maximal coordinate that particle moving right would achive. Then of we will meet particle moving left that will move to the left of that coordinate in time t that we have 2 particles that will collide before time t. Otherwise we won't have such pair of particles.",
    "tags": [
      "binary search"
    ],
    "rating": 2300
  },
  {
    "contest_id": "25",
    "index": "A",
    "title": "IQ test",
    "statement": "Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given $n$ numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given $n$ numbers finds one that is different in evenness.",
    "tutorial": "We can store two values, $count_{odd}$ and $count_{even}$, as the number of odd or even elements in the series. We can also store $last_{odd}$ and $last_{even}$ as the index of the last odd/even item encountered. If only one odd number appears --- output $last_{odd}$; otherwise only one even number appears, so output $last_{even}$.",
    "tags": [
      "brute force"
    ],
    "rating": 1300
  },
  {
    "contest_id": "25",
    "index": "B",
    "title": "Phone numbers",
    "statement": "Phone number in Berland is a sequence of $n$ digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.",
    "tutorial": "There are many ways of separating the string into clusters of 2 or 3 characters. One easy way is to output 2 characters at a time, until you have only 2 or 3 characters remaining.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "25",
    "index": "C",
    "title": "Roads in Berland",
    "statement": "There are $n$ cities numbered from 1 to $n$ in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build $k$ new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.",
    "tutorial": "If you are familiar with the Floyd-Warshall algorithm, then this solution may be easier to see.Initially, we are given a matrix $D$, where $D[i][j]$ is the distance of shortest path between city $i$ and city $j$. Suppose we build a new road between $a$ and $b$ with length shorter than $D[a][b]$. How do we update the rest of the graph accordingly?Define a new matrix $D'$, whose entries $D'[i][j]$ are the minimum path distance between $i$ and $j$ while taking into account the new road $ab$. There are three possibilities for each $i, j$:$D'[i][j]$ remains unchanged by the new road. In this case $D'[i][j] = D[i][j]$$D'[i][j]$ is shorter if we use the new road $ab$. This means that the new path $i, v_{1}, v_{2}, ..., v_{n}, j$ must include the road $a, b$. If we connect the vertices $i, a, b, j$ together in a path, then our new distance will be $D[i][a] + length(ab) + D[b][j]$.Lastly, we may have to use the road $ba$. (Note that this may not be the same as road $ab$.) In this case, we have $D'[i][j] = D[i][b] + length(ab) + D[a][j]$.Thus, for each new road that we build, we must update each path $i, j$ within the graph. Then we must sum shortest distances between cities. Updating the matrix and summing the total distance are both $O(N^{2})$, so about $300^{2}$ operations. Lastly, there are at most $300$ roads, so in total there are about $300^{3}$ operations.One thing to note is that the sum of all shortest distances between cities may be larger than an int; thus, we need to use a long when calculating the sum.",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "25",
    "index": "D",
    "title": "Roads not only in Berland",
    "statement": "Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are $n$ cities in Berland and neighboring countries in total and exactly $n - 1$ two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones.",
    "tutorial": "Before we start this problem, it is helpful to know about the union find data structure. The main idea is this: given some elements $x_{1}, x_{2}, x_{3}, ..., x_{n}$ that are partitioned in some way, we want to be able to do the following:merge any two sets together quicklyfind the parent set of any $x_{i}$This is a general data structure that sometimes appears in programming competitions. There are a lot of ways to implement it; one good example is written by Bruce Merry (aka BMerry) here.Back to the problem: Every day we are allowed to build exactly 1 road, and close exactly 1 road. Thus, we can break the problem into two parts:How do we connect the parts of the graph that are disconnected?How do we remove roads in a way that does not disconnect parts of the graph? Let $build$ be the list all roads that need to be built, and let $close$ be the list of nodes that need to be closed. We can show that in fact, these lists are of the same size. This is because the connected graph with $n$ nodes is a tree if and only if it has $n - 1$ edges. Thus, if we remove more roads than than we build, then the graph is disconnected. Also, if we build more roads than we remove, then we have some unnecessary roads (the graph is no longer a tree).Now consider the format of the input data:$a_{1}, b_{1}$$a_{2}, b_{2}$...$a_{None}, b_{None}$We can show that edge $(a_{i}, b_{i})$ is unnecessary if and only if the nodes $a_{i}, b_{i}$ have already been connected by edges $(a_{1}, b_{1}), (a_{2}, b_{2}), ..., (a_{None}, b_{None})$. In other words, if the vertices $a_{i}, b_{i}$ are in the same connected component before we, add $(a_{i}, b_{i})$ then we do not need to add $(a_{i}, b_{i})$. We can use union-find to help us solve this problem:<code>for( i from 1 to n-1 ){ if( find($a_{i}$)=find($b_{i}$) ) close.add$(a_{i}, b_{i})$; else merge($a_{i}, b_{i}$);}</code>In other words, we treat each connected component as a set. Union find allows us to find the connected component for each node. If the two connected components are the same, then our new edge is unnecessary. If they are different, then we can merge them together (with union find). This allows us to find the edges that we can remove.In order to find the edges that we need to add to the graph, we can also use union-find: whenever we find a component that is disconnected from component 1, then we just add an edge between them.<code>for( i from 2 to n ) if( find($v_{i}$)!=find($v_{1}$) ) { then merge$(v_{1}, v_{i})$; build.add$(v_{1}, v_{i})$; }</code>We just need to store the lists of roads that are unnecessary, and the roads that need to be built.",
    "tags": [
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "25",
    "index": "E",
    "title": "Test",
    "statement": "Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring $s_{1}$, the second enters an infinite loop if the input data contains the substring $s_{2}$, and the third requires too much memory if the input data contains the substring $s_{3}$. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions?",
    "tutorial": "The way I solved this problem is with a hash function. Hash functions can fail on certain cases, so in fact, my solution is not 'correct'. However, it passed all the test cases =PLet the input strings be $s_{0}, s_{1}, s_{2}$. We can build the shortest solution by permuting the strings and then trying to 'attach' them to each other. I.e., we need to find the longest overlapping segments at the end of string $a$ and the beginning of string $b$. The obvious brute force solution won't run in time. However, we can use a hash function to help us calculate the result in $O(n)$ time, where $n$ is $min(len(a), len(b))$. The hash function that I used was the polynomial $hash(x_{0}, x_{1}, ..., x_{n}) = x_{0} + ax_{1} + a^{2}x_{2} + ... + a^{n}x_{n}$. This polynomial is a good hash function in this problem because it has the following useful property:Given $hash(x_{i}, ..., x_{j})$, we can calculate the following values in $O(1)$ time:$hash(x_{None}, x_{i}, ..., x_{j}) = x_{None} + a  \\times  hash(x_{i}, ..., x_{j})$$hash(x_{i}, ..., x_{j}, x_{None}) = hash(x_{i}, ..., x_{j}) + a^{None}  \\times  x_{None}$In other words, if we know the hash for some subsequence, we can calculate the hash for the subsequence and the previous element, or the subsequence and the next element. Given two strings $a, b$, we can calculate the hash functions starting from the end of $a$ and starting from the beginning of $b$. If they are equal for length $n$, then that means that (maybe) $a$ and $b$ overlap by $n$ characters.Thus, we can try every permutation of $s_{0}, s_{1}, s_{2}$, and try appending the strings to each other. There is one last case: if $s_{i}$ is a substring of $s_{j}$ for some $i  \\neq  j$, then we can just ignore $s_{i}$. We can use hash functions to check that one string is contained within another one.",
    "tags": [
      "hashing",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "26",
    "index": "A",
    "title": "Almost Prime",
    "statement": "A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and $n$, inclusive.",
    "tutorial": "This is a straightforward implementation problem: factor every number from 1 to n into product of primes and count the number of distinct prime divisors.",
    "tags": [
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "26",
    "index": "B",
    "title": "Regular Bracket Sequence",
    "statement": "A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.\n\nOne day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?",
    "tutorial": "Read the string from left to right and calculate the balance of brackets at each step (i.e., the difference between the number of \"(\" and \")\" characters written out). We need to keep this balance non-negative. Hence, every time when the balance equals 0 and we read the \")\" character, we must omit it and not write it out. The answer to the problem is twice the number of \")\" characters that we wrote out.",
    "tags": [
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "26",
    "index": "C",
    "title": "Parquet",
    "statement": "Once Bob decided to lay a parquet floor in his living room. The living room is of size $n × m$ metres. Bob had planks of three types: $a$ planks $1 × 2$ meters, $b$ planks $2 × 1$ meters, and $c$ planks $2 × 2$ meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks.",
    "tutorial": "We'll derive several necessary conditions for the parquet to be possible. If some of them is not fulfilled, the answer is \"IMPOSSIBLE\".1. m*n must be even, because it equals the total area of the parquet, and the area of each plank is even.2. Suppose m (the number of columns) is odd. Paint the living room in two colors - black and white - in the following way: the first column is black, the second one is white, the third one is black, ..., the last one is black. The number of black squares is $n$ greater than the number of white squares. The planks 1x2 and 2x2 contain an equal number of black and white squares, so we must compensate the difference with 2x1 planks, and their number must be at least n/2. In this case we can parquet the last column with these planks, decrease $b$ by n/2 and decrease $m$ by one.3. If $n$ is odd, then by similar reasoning $a  \\ge  m / 2$.4. Now $m$ and $n$ are even. A similar reasoning shows that the number of 1x2 planks used must be even, and the number of 2x1 planks used must be even. So, if $a$ is odd, we decrease it by 1, and the same with $b$.5. Now we must have $mn  \\le  2a + 2b + 4c$, because otherwise the total area of planks would not be enough.6. If all the conditions were fulfilled, we can finish the parquet: divide it into 2x2 squares, and use one 2x2 plank, two 1x2 planks, or two 2x1 planks to cover each square.",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "26",
    "index": "D",
    "title": "Tickets",
    "statement": "As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly $n + m$ people will come to buy a ticket. $n$ of them will have only a single 10 euro banknote, and $m$ of them will have only a single 20 euro banknote. Currently Charlie has $k$ 10 euro banknotes, which he can use for change if needed. All $n + m$ people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.",
    "tutorial": "If we picture the graph of the number of 10-euro banknotes, it will be a broken line, starting at the point (0, k) and ending at the point (m+n, n+k-m). Exactly $m$ segments on the line are 'going down', and other $n$ segments are 'going up'. Hence the total number of possible graphs is $C(m + n, m)$ (the binomial coefficient). We need to find out the number of graphs which don't go under the X axis. To do that, we'll calculate the complementary number: the number of graphs which go under the X axis, or, equivalently, intersect the line y=-1. Here we'll use the so-called 'reflection principle'. Consider any graph that intersects the line y=-1, and take the last point of intersection. Reflect the part of the graph from this point to the end with respect to the line y=-1. We'll have a new graph, ending at the point $(m + n, - 2 - n - k + m)$. Conversely, any graph ending at this point will intersect the line y=-1, and we can apply the same operation to it. Hence, the number of graphs we're interested in equals the number of graphs starting at the point $(0, k)$ and ending at the point $(m + n, - 2 - n - k + m)$. Let $a$ and $b$ be the number of segments in such a graph which go up and down, respectively. Then $a + b = m + n$, $a - b + k = - 2 - n - k + m$. It follows that $a = m - k - 1$, and there are $C(m + n, m - k - 1)$ such graphs. So, the probability that the graph will go down the X axis is $C(m + n, m - k - 1) / C(m + n, m) = (m!n!) / ((n + k + 1)!(m - k - 1)!) = (m(m - 1)... (m - k)) / ((n + 1)(n + 2)... (n + k + 1))$. The answer to the problem is $1 - (m(m - 1)... (m - k)) / ((n + 1)(n + 2)... (n + k + 1))$.",
    "tags": [
      "combinatorics",
      "math",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "26",
    "index": "E",
    "title": "Multithreading",
    "statement": "You are given the following concurrent program. There are $N$ processes and the $i$-th process has the following pseudocode:\n\n\\begin{verbatim}\nrepeat\n$n_{i}$\ntimes\n\n$y_{i}$\n:=\n$y$\n\n$y$\n:=\n$y_{i} + 1$\nend repeat\n\\end{verbatim}\n\nHere $y$ is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning $y = 0$. You will be given an integer $W$ and $n_{i}$, for $i = 1, ... , N$. Determine if it is possible that after all processes terminate, $y = W$, and if it is possible output an arbitrary schedule that will produce this final value.",
    "tutorial": "It's clear that we must have $1  \\le  w  \\le   \\Sigma _{i} n_{i}$. If this condition is true, we show how to achieve the desired result in the following cases:1. $N = 1, w = n_{1}$. Obvious.2. $N  \\ge  2, w  \\ge  2$. For $w = 2$, the schedule is the following: 1, all loops of processes 3..N, $n_{2} - 1$ loops of the second process, 1, 2, $n_{1} - 1$ loops of the first process, 2. For $w > 2$, we just need to move several loops from the middle of the sequence to the end.3. $N  \\ge  2, w = 1$, and there exists an index $i$ such that $n_{i} = 1$. Then the schedule is the following: $i$, all loops of other processes, $i$.Now we'll show that in any other case the result $w$ is impossible. The case $N = 1, w  \\neq  n_{1}$ is obvious. We have one more case left: $N  \\ge  2, w = 1$, and $n_{i} > 1$ for each $i$. Suppose that there exists a schedule which results in $y = 1$. Consider the last writing operation in this schedule; suppose it is executed by the process $i$. Then the corresponding reading operation should have read the value y=0. This means that there were no writing operations before. But this is impossible, since $n_{i} > 1$, and this process executed $n_{i} - 1$ read/write loops.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2400
  },
  {
    "contest_id": "27",
    "index": "A",
    "title": "Next Test",
    "statement": "«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.\n\nYou are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.",
    "tutorial": "We will create an array of boolean used[1..3001] ans fill it with \"false\" values. For each of n given number, we will assign corresponding used value to \"true\". After that, the index of first element of used with \"false\" value is the answer to the problem.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "27",
    "index": "B",
    "title": "Tournament",
    "statement": "The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. $n$ best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. $n·(n - 1) / 2$ games were played during the tournament, and each participant had a match with each other participant.\n\nThe rules of the game are quite simple — the participant who falls asleep first wins. The secretary made a record of each game in the form «$x_{i}$ $y_{i}$», where $x_{i}$ and $y_{i}$ are the numbers of participants. The first number in each pair is a winner (i.e. $x_{i}$ is a winner and $y_{i}$ is a loser). There is no draws.\n\nRecently researches form the «Institute Of Sleep» have found that every person is characterized by a value $p_{j}$ — the speed of falling asleep. The person who has lower speed wins. Every person has its own value $p_{j}$, constant during the life.\n\nIt is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.",
    "tutorial": "To solve this problem first of all we should find such numbers A and B that occur in the input data not (n - 1) times, but (n - 2). We can notice, that winner-loser relation in this problem is transitive. This means that if X wins against Y and Y wins against Z, than X wins against Z. So to find out who is harsher A or B, let's look for such C, that the results of the match A with C and B with C are distinct. If such C exists, than the one, who wins against C should be printed first. If there is no such C, than both results of the match A versus B satisfy problem's statement.",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "27",
    "index": "C",
    "title": "Unordered Subsequence",
    "statement": "The sequence is called \\underline{ordered} if it is non-decreasing or non-increasing. For example, sequnces [3, 1, 1, 0] and [1, 2, 3, 100] are ordered, but the sequence [1, 3, 3, 1] is not. You are given a sequence of numbers. You are to find it's shortest subsequence which is not ordered.\n\nA subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.",
    "tutorial": "First of all, we should notice, that if answer exists, it consist of 3 elements. Here is linear time solution. Let's path with for-loop through the given array and on each iteration let's store current minimul and maximun elements positions. When we are looking at some element, it is enough to check, whereas this element makes unordered subsequence along with min and max elements of the previous part of the array. It is not obvious, but not very difficult to prove. You should try it yourself.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "27",
    "index": "D",
    "title": "Ring Road 2",
    "statement": "It is well known that Berland has $n$ cities, which form the Silver ring — cities $i$ and $i + 1$ ($1 ≤ i < n$) are connected by a road, as well as the cities $n$ and $1$. The goverment have decided to build $m$ new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve which lies inside or outside the ring. New roads will have no common points with the ring (except the endpoints of the road).\n\nNow the designers of the constructing plan wonder if it is possible to build the roads in such a way that no two roads intersect (note that the roads may intersect at their endpoints). If it is possible to do, which roads should be inside the ring, and which should be outside?",
    "tutorial": "Consider all m given roads as segments on numeric axis. Road from town a to town b should correspond to segment [min(a, b), max(a, b)]. For each pair of segments there are three types of positions: both ends of one segment are inside of the other one, both ends of one segment are outside of the other one and only one end of one segment is inside of the other one. In the first two cases positions of corresponding roads(inside circle or outside) are independend. But in the third case this positions must be opposite Let's build the graph. Vertexes will correspond to segments/roads and edge between vertexes i and j will mean that positions of this roads should be opposite. Now we have another problem: for given undirected graph, we must paint all vertexes in 2 colours such that for each edge, corresponding vertexes will have different colours. This problem can be solved using DFS algorithm. First, we will paint all vertexes in -1 colour. Let's begin for-loop through vertexes. If loop finds -1-vertex, assing colour 0 to the vertex and run DFS from it. DFS from vertex V should look through all neighbor vertex. If neighbor has colour -1, than assing to that neighbor colour, opposite to the colour of V and run DFS from it. If neighbor already has non-negative colour, we should check whereas this colour is opposite, because if it is not, answer is \"Impossible\". Such DFS will either build the correct answer or prove that it is impossible.",
    "tags": [
      "2-sat",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "27",
    "index": "E",
    "title": "Number With The Given Amount Of Divisors",
    "statement": "Given the number $n$, find the smallest positive integer which has exactly $n$ divisors. It is guaranteed that for the given $n$ the answer will not exceed $10^{18}$.",
    "tutorial": "Consider the number, that is our answer and factorize it. We will get such product $p_{1}^{None} \\cdot  p_{2}^{None} \\cdot  ...  \\cdot  p_{k}^{None}$. Product through each i $a_{i} + 1$ will be the number of divisors. So, if we will take first 10 prime numbers, their product will have 1024 divisors. This means that we need only first 10 primes to build our answer. Let's do it with dynamic programming: d[i][j] - the minimal number with i divisors that can be built with first j prime numbers. To calculate the answer for state (i, j) let's look over all powers of j-th prime number in the answer. If j-th prime number has power k in the answer, than $d[i][j] = d[i / (k + 1)][j - 1] * prime[j]^{k}$. For each power of j-th prime we must select the power, that gives us minimal d[i][j]. You should be extremely careful during the implementation, because all calculations are made on the edge of overflow.",
    "tags": [
      "brute force",
      "dp",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "28",
    "index": "A",
    "title": "Bender Problem",
    "statement": "Robot Bender decided to make Fray a birthday present. He drove $n$ nails and numbered them from $1$ to $n$ in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods.\n\nHelp Bender to solve this difficult task.",
    "tutorial": "Let's look at the first nail. If it is occupied by the fold place, then Bender will put next fold place on the third nail, then on fifth and so on. Else, is the first nail occupied by end, than second, fourth, sixth and so on nail will be occupied by the fold places. Let's see, if we can complete our polyline with the first nail, occupied by rhe fold place. It means we should check, if we have an unused pod with length $dist(nails[n], nails[1]) + dist(nails[1], nails[2])$. Then check the third nail and so on. If we have completed the polyline, then we have an answer. Else repeat previous procedure, but starting from the second nail.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "28",
    "index": "B",
    "title": "pSort",
    "statement": "One day $n$ cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from $1$). Also each cell determined it's favourite number. On it's move $i$-th cell can exchange it's value with the value of some other $j$-th cell, if $|i - j| = d_{i}$, where $d_{i}$ is a favourite number of $i$-th cell. Cells make moves in any order, the number of moves is unlimited.\n\nThe favourite number of each cell will be given to you. You will also be given a permutation of numbers from $1$ to $n$. You are to determine whether the game could move to this state.",
    "tutorial": "Let's consider a graph. Vertexes will correspond to place of the permutation. Places will be connected by an edge if and only if we can swap theirs values. Our problem has a solution when for every i, vertex p[i] can be reached from vertex i.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1600
  },
  {
    "contest_id": "28",
    "index": "C",
    "title": "Bath Queue",
    "statement": "There are $n$ students living in the campus. Every morning all students wake up at the same time and go to wash. There are $m$ rooms with wash basins. The $i$-th of these rooms contains $a_{i}$ wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.",
    "tutorial": "This problem is solved by dynamic programming Consider the following dynamics: $d[i][j][k]$. $i$ --- number of not yet processed students, $j$ --- number of not yet processed rooms, $k$ --- maximum queue in the previous rooms. The value we need is in state $d[n][m][0]$. Let's conside some state $(i, j, k)$ and search through all $c$ from 0 to $i$. If $c$ students will go to $j$th room, than a probability of such event consists of factors: $C^{c}_{i}$ --- which students will go to $j$th room. $(1 / j)^{c} \\cdot  ((j - 1) / j)^{None}$ --- probability, that $c$ students will go to $j$th room,and the rest of them will go to the rooms from first to $j - 1$th. Sum for all $n$ from 0 to $i$ values of $(1 / j)^{c} \\cdot  ((j - 1) / j)^{None} \\cdot  C^{c}_{i} \\cdot  d[i - c][j - 1][mx]$. Do not forget to update maximum queue value and get the accepted.",
    "tags": [
      "combinatorics",
      "dp",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "28",
    "index": "D",
    "title": "Don't fear, DravDe is kind",
    "statement": "A motorcade of $n$ trucks, driving from city «Z» to city «З», has approached a tunnel, known as Tunnel of Horror. Among truck drivers there were rumours about monster DravDe, who hunts for drivers in that tunnel. Some drivers fear to go first, others - to be the last, but let's consider the general case. Each truck is described with four numbers:\n\n- $v$ — value of the truck, of its passangers and cargo\n- $c$ — amount of passanger on the truck, the driver included\n- $l$ — total amount of people that should go into the tunnel before this truck, so that the driver can overcome his fear («if the monster appears in front of the motorcade, he'll eat them first»)\n- $r$ — total amount of people that should follow this truck, so that the driver can overcome his fear («if the monster appears behind the motorcade, he'll eat them first»).\n\nSince the road is narrow, it's impossible to escape DravDe, if he appears from one side. Moreover, the motorcade can't be rearranged. The order of the trucks can't be changed, but it's possible to take any truck out of the motorcade, and leave it near the tunnel for an indefinite period. You, as the head of the motorcade, should remove some of the trucks so, that the rest of the motorcade can move into the tunnel and the total amount of the left trucks' values is maximal.",
    "tutorial": "Let's split all trucks into different classes by the sum of $l_{i} + c_{i} + r_{i}$. Answer sequence consists of trucks from only one class, so let's solve problem for different classes independently. Let's loop through trucks from fixed class in the order, then follow in the motorcade and update values in dynamics $z[k]$ - maximum profit we can get, if last truck has $r_{i} = k$. Truck with number i can update two values: it can update value $z[r_{i}]$ with value $z[r_{i} + c_{i}] + v_{i}$. It means this truck continued some motorcade, started from some previous truck. if $l_{i} = 0$ it can update value $z[r_{i}]$ with $v_{i}$. It means this truck started motorcade. Answer will be in $z[0]$ To restore the trucks included in the answer, we can keep with the maximal sum in z the index of last truck that updated this sum. Also we store the ancestor p for each truck that updated something in z. This ancestor is calculated when we consider i-th truck and doesn't change further: p[i] = -1 if truck i became beginning of the motorcade, otherwise p[i] = last truck that updated $z[r_{i} + c_{i}]$. We start restore of the answer from last truck updated z[0]. After that we restore everything using only p.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "hashing"
    ],
    "rating": 2400
  },
  {
    "contest_id": "28",
    "index": "E",
    "title": "DravDe saves the world",
    "statement": "How horrible! The empire of galactic chickens tries to conquer a beautiful city \"Z\", they have built a huge incubator that produces millions of chicken soldiers a day, and fenced it around. The huge incubator looks like a polygon on the plane $Oxy$ with $n$ vertices. Naturally, DravDe can't keep still, he wants to destroy the chicken empire. For sure, he will start with the incubator.\n\nDravDe is strictly outside the incubator's territory in point $A(x_{a}, y_{a})$, and wants to get inside and kill all the chickens working there. But it takes a lot of doing! The problem is that recently DravDe went roller skating and has broken both his legs. He will get to the incubator's territory in his jet airplane LEVAP-41.\n\nLEVAP-41 flies at speed $V(x_{v}, y_{v}, z_{v})$. DravDe can get on the plane in point $A$, fly for some time, and then air drop himself. DravDe is very heavy, that's why he falls vertically at speed $F_{down}$, but in each point of his free fall DravDe can open his parachute, and from that moment he starts to fall at the wind speed $U(x_{u}, y_{u}, z_{u})$ until he lands. Unfortunately, DravDe isn't good at mathematics. Would you help poor world's saviour find such an air dropping plan, that allows him to land on the incubator's territory? If the answer is not unique, DravDe wants to find the plan with the minimum time of his flight on the plane. If the answers are still multiple, he wants to find the one with the minimum time of his free fall before opening his parachute",
    "tutorial": "Let's look at geometrical locus where DravDe can land. It can be eigher an angle or a line(half-line). 1. Locus is an angle if and only if projection of vector $v$ and vector $u$ on Oxy plane is not collinear. This angle is easy to calculate. Angular vertex is DravDe starting point and one of half-lines is collinear with place speed vector projection. Second half-line is easy to calculate: $A_{z} + V_{z} \\cdot  tv + U_{z} \\cdot  tu = 0$ $A_{x} + V_{x} \\cdot  tv + U_{x} \\cdot  tu = B_{x}$ $A_{y} + V_{y} \\cdot  tv + U_{y} \\cdot  tu = B_{y}$ where A - starting point, B - landing point. Consider tv equal to 1 and calculate tu from first equation. From second and third calculate point B. This point lies on the second half-line of the angle. 2. If plane speed projection and wind speed projection is collinear, locus is half-line or line, depending on the difference between this two speeds. If the answer exist, than polygon and locus have at least onecommon point. And t1 and t2 is minimal on edge points. So now let's cross all segments with locus, calculate t1 and t2 for each intersection point and select minimal answer.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "29",
    "index": "A",
    "title": "Spit Problem",
    "statement": "In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.\n\nThe trajectory of a camel's spit is an arc, i.e. if the camel in position $x$ spits $d$ meters right, he can hit only the camel in position $x + d$, if such a camel exists.",
    "tutorial": "Check whether exist a pair i and j,they satisfy xi+di = xj && xj+dj = xi;",
    "tags": [
      "brute force"
    ],
    "rating": 1000
  },
  {
    "contest_id": "29",
    "index": "B",
    "title": "Traffic Lights",
    "statement": "A car moves from point A to point B at speed $v$ meters per second. The action takes place on the X-axis. At the distance $d$ meters from A there are traffic lights. Starting from time 0, for the first $g$ seconds the green light is on, then for the following $r$ seconds the red light is on, then again the green light is on for the $g$ seconds, and so on.\n\nThe car can be instantly accelerated from $0$ to $v$ and vice versa, can instantly slow down from the $v$ to $0$. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0.\n\nWhat is the minimum time for the car to get from point A to point B without breaking the traffic rules?",
    "tutorial": "Pay attention to Just Right or Red. use Div and Mod can solve it easily;",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "29",
    "index": "C",
    "title": "Mail Stamps",
    "statement": "One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.\n\nThere are $n$ stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.",
    "tutorial": "As we know, there are only two path -- forward and reverse, so we can do DFS from the one-degree nodes (only two nodes).As their index may be very larger, so I used map<int,int> to do hash.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "29",
    "index": "D",
    "title": "Ant on the Tree",
    "statement": "Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.\n\nAn ant stands at the root of some tree. He sees that there are $n$ vertexes in the tree, and they are connected by $n - 1$ edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.\n\nThe ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.",
    "tutorial": "First, Floyd pretreat the path from I to J, and save the path. Then get the answer.The order is a1,a2...ak, K is the number of the leaves, we can assume a0 = ak+1 = 1, the root.then, answer push_back the path[ai][ai+1].if the ans.size() > 2*N-1 , cout -1;else cout the answer.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "30",
    "index": "A",
    "title": "Accounting",
    "statement": "A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.\n\nThe total income $A$ of his kingdom during $0$-th year is known, as well as the total income $B$ during $n$-th year (these numbers can be negative — it means that there was a loss in the correspondent year).\n\nKing wants to show financial stability. To do this, he needs to find common coefficient $X$ — the coefficient of income growth during one year. This coefficient should satisfy the equation:\n\n\\[\nA·X^{n} = B.\n\\]\n\nSurely, the king is not going to do this job by himself, and demands you to find such number $X$.\n\nIt is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient $X$ must be integers. The number $X$ may be zero or negative.",
    "tutorial": "First solution: naive brute Let's brute all possible values of $X$, and check each of them. It's easy to understand, that $X$ will be constrained in the same limits as values $A$ and $B$, that is, from -1000 to 1000 inclusive (obviously, there exists a test for each such $X$, so we can't decrease these limits). When we have some fixed value of $X$, we check it simply by multiplying $A$ by $X$ $n$ times. But, you should be careful with possible integer (and even 64-bit integer :) ) overflow. For example, you should stop multiplying by $X$ if the currect result exceeds 1000 by absolute value already. Second solution: formula It's easy to note, that if solution exists, then it is $n$-th root from $|B| / |A|$ fraction, with changed sign if $A$ and $B$ have different signs and if $n$ is odd (if $n$ is even, then no solution exists). That's why we could just use pow() function (or some analog in your language) to calculate $1 / n$-th power of the fraction, and after that we just have to check - is the result integer number or not. Of course, we have to check it with taking into account precision errors: that is, number is integer if it is within $10^{ - 9}$ (or some another number) from nearest integer. Moreover, in this solution you should be careful with zeroes. The worst case is when $A = 0$, and this case should be checked manually (you should note the difference between $B = 0$ and $B  \\neq  0$ cases). It should be told that many of the solutions failed on tests with $A = 0$, or $B = 0$, and if these tests were not included in the pretestset, I think, about half of participants would fail to solve this problem :)",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "30",
    "index": "B",
    "title": "Codeforces World Finals",
    "statement": "The king Copa often has been reported about the Codeforces site, which is rapidly getting more and more popular among the brightest minds of the humanity, who are using it for training and competing. Recently Copa understood that to conquer the world he needs to organize the world Codeforces tournament. He hopes that after it the brightest minds will become his subordinates, and the toughest part of conquering the world will be completed.\n\nThe final round of the Codeforces World Finals 20YY is scheduled for $DD$.$MM$.$YY$, where $DD$ is the day of the round, $MM$ is the month and $YY$ are the last two digits of the year. Bob is lucky to be the first finalist form Berland. But there is one problem: according to the rules of the competition, all participants must be at least 18 years old at the moment of the finals. Bob was born on $BD$.$BM$.$BY$. This date is recorded in his passport, the copy of which he has already mailed to the organizers. But Bob learned that in different countries the way, in which the dates are written, differs. For example, in the US the month is written first, then the day and finally the year. Bob wonders if it is possible to rearrange the numbers in his date of birth so that he will be at least 18 years old on the day $DD$.$MM$.$YY$. He can always tell that in his motherland dates are written differently. Help him.\n\nAccording to another strange rule, eligible participant must be born in the same century as the date of the finals. If the day of the finals is participant's 18-th birthday, he is allowed to participate.\n\nAs we are considering only the years from $2001$ to $2099$ for the year of the finals, use the following rule: the year is leap if it's number is divisible by four.",
    "tutorial": "To solve this problem we had to learn how to check the given date XD.XM.XY for correctness (taking into account number of days in each month, leap years, and so on). After implementing this, we had just to iterate over all 6 possible permutations of three given numbers (BD,BM,BY), checking each of them for correctness as a date, and comparing it with the date of Codeforces World Finals DD.MM.YY. The comparison itself could be done, by simply adding 18 to the year number, and comparing the two dates as a triple (year,month,day). The only difficult case is the case of February, 29-th. It's easy to understand that the solution described above works correctly, if we suppose that this unlucky man (having its birthday on February 29-th) celebrates his birthday on March, 1st in 3/4 years. Interesting question - what do people usually do in this situation in the real life? :)",
    "tags": [
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "30",
    "index": "D",
    "title": "King's Problem?",
    "statement": "Every true king during his life must conquer the world, hold the Codeforces world finals, win pink panda in the shooting gallery and travel all over his kingdom.\n\nKing Copa has already done the first three things. Now he just needs to travel all over the kingdom. The kingdom is an infinite plane with Cartesian coordinate system on it. Every city is a point on this plane. There are $n$ cities in the kingdom at points with coordinates $(x_{1}, 0), (x_{2}, 0), ..., (x_{n}, 0)$, and there is one city at point $(x_{n + 1}, y_{n + 1})$.\n\nKing starts his journey in the city number $k$. Your task is to find such route for the king, which visits all cities (in any order) and has minimum possible length. It is allowed to visit a city twice. The king can end his journey in any city. Between any pair of cities there is a direct road with length equal to the distance between the corresponding points. No two cities may be located at the same point.",
    "tutorial": "In this problem to create a wright solution you need to perform the following chain of inferences (though, if you skip some steps or do them not completely, you can still get an AC solution :) ): Note that after we visit the city numbered $n + 1$, the further answer depends only from the leftmost and the rightmost unvisited cities (and it would be optimal to come to the nearest to $n + 1$-th city of them, and the come to another of them). That's why we know the answer for the case $k = n + 1$, and won't consider this case later.Before we visit the $n + 1$-th city, - this part of the path covers some segment of cities lying in the OX axis. This segment, obviously, contains the point $k$. But we can't iterate over all such possible segments, because there are $O(n^{2})$ of them, so it's still a slow solution.Let's understand the following fact: if before visiting city $n + 1$ we visited some other cities, but neither the leftmost nor the rightmost, then it was surely unprofitable. Really, after we come into the $n + 1$, the answer will depend only on the leftmost and the rightmost of non-visited cities. So, if before the $n + 1$-th city we performed some movements, but didn't change the leftmost and the rightmost cities, then it was completely unnecessary and unprofitable action.We can can get even more: there is no optimal solution, where we should move from the start city $k$ to the $n + 1$-th city directly, without vithout visiting other cities (here I suppose that $k$ is neither the leftmost nor the rightmost city). Btw, this step of reasoning could be skipped - we can believe it's sometimes profitable to come from $k$ to $n + 1$ directly, and it's not difficult to support this case in a solution we'll build later; but in order to describe the problem completely let's prove this fact too. In order to prove this, let's write down two formulas: first for the length of the answer if we come from $k$ to $n + 1$ directly, then come to city $1$, and then to city $n$ (here I suppose that $1$ and $n$ are the leftmost and the rightmost cities, accordingly, and city $1$ is nearer to $n + 1$ than $n$); second formula - for the length of the answer if we come from $k$ to $1$ first, then to $n + 1$, then to $k + 1$, and then to $n$. If we compare these two formulas, then after the cancellation of like terms we can use the triangle's inequality to see that the second formula always gives smaller value (at least, not greater) than the first. So, it's really unprofitable to come from $k$ to $n + 1$ directly.So, to make a right solution, it's enough to iterate over only two types of segments: $[1;i]$ for $i  \\ge  k$, and $[i;n]$ for $i  \\le  k$ (here I suppose for convenience that cities are sorted by their x-coordinate).The last idea is how to process each of these cases accurately. In order to do this we iterate over all possible $i = 1... n$. Let, for example, $i  \\le  k$. Then we have to try the following case: go from $k$ to $n$, then return to $i$, then come to $n + 1$, and then return back to the OX axis if need (if $i > 1$). Also it is required to check another type of cases: try to go from $k$ to $i$, then to $n$, and then come to $n + 1$, and return back to the OX axis if need. Answer for each of these cases can be calculated in $O(1)$. For $i  \\ge  k$ everything is symmetric. So, not taking into account the sorting of the citites in the beginning of the program, we get a $O(n)$-solution.",
    "tags": [
      "geometry",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "30",
    "index": "E",
    "title": "Tricky and Clever Password",
    "statement": "In his very young years the hero of our story, king Copa, decided that his private data was hidden not enough securely, what is unacceptable for the king. That's why he invented tricky and clever password (later he learned that his password is a palindrome of odd length), and coded all his data using it.\n\nCopa is afraid to forget his password, so he decided to write it on a piece of paper. He is aware that it is insecure to keep password in such way, so he decided to cipher it the following way: he cut $x$ characters from the start of his password and from the end of it ($x$ can be $0$, and $2x$ is strictly less than the password length). He obtained 3 \\textbf{\\underline{parts of the password}}. Let's call it $prefix$, $middle$ and $suffix$ correspondingly, both $prefix$ and $suffix$ having equal length and $middle$ always having odd length. From these parts he made a string $A + prefix + B + middle + C + suffix$, where $A$, $B$ and $C$ are some (possibly empty) strings invented by Copa, and «$ + $» means concatenation.\n\nMany years have passed, and just yesterday the king Copa found the piece of paper where his ciphered password was written. The password, as well as the strings $A$, $B$ and $C$, was completely forgotten by Copa, so he asks you to find a password of maximum possible length, which could be invented, ciphered and written by Copa.",
    "tutorial": "Scheme of the author solution The author solution has the following scheme. Let's brute over each possible position $pos$ of the center of the middle part (the part that must be palindrome by problem statement). Then let's take as a $middle$ the maximum palindrome among all centered in the position $pos$. After that we have to take as $prefix$ and $suffix$ such maximum-sized substrings, which satisfy all problem constraints, and don't intersect with medium part. After we do these calculations for each possible position $pos$, the answer to the problem will be just maximum among answers found on each step. Efficient Implementation In fact, the problem consists of two sub-problems: First, it's a search for a maximum-length palindrome, having its center in the given position $pos$. We can calculate these answers in $O(n)$ with Manacher's algorithm, which is described on my site (unfortunately, the article is only in Russian, so you have to use Google Translator or something like this). Alternatively you can calculate this \"palindromic array\" using binary search and, for example, hashes or suffix array: let's search for maximum palindrome length using binary search, then inside the binary search we have to compare for equivalence two substrings of the given string, which can be done in O(1) using hashes or calculated suffix array. Second, it's a search for maximum length and corresponding positions for $prefix$ and $suffix$ parts, not intersecting the given substring $[l;r]$. Let's look at lengths $sufflen$ of suffix $suffix$ in order of their increase, then for each fixed $sufflen$ obviously it is the best to look only at first occurence of string $prefix = reverse(suffix)$. Thereby, by increasing the length $sufflen$, we can move the corresponding $prefix$ only to the right, not to the left. Designating by $lpos[sufflen]$ the position of first occurence of string $reverse(suffix(sufflen))$ in the given string, we get that these $lpos$ values are non-decreasing. It will be more comfortable to introduce another array $rpos[len] = lpos[len] + len - 1$ - end-position of occurence of this suffix (obviously these values will strictly increase). So, if we knew the values of the array $lpos$ (or, more convenient, of the array $rpos$), then in the main solution (in the place, where after selecting maximum in $pos$ palindrome we have to search for maximum appropriate $prefix$ and $suffix$) we can use binary search over the length $sufflen$. Moreover, we can just precalculate answers to each of query of this form, and after that we'll answer to each query in $O(1)$. The last thing is to learn how to build $lpos$ array - array of positions of first occurences of reversed suffixes. For example, this can be done using hashes or suffix array. If we've calculated the value $lpos[k]$, let's learn how to calculate $lpos[k + 1]$. If the substring $s.substr(lpos[k], k + 1)$ equals to s-th suffix of length $k + 1$, then $lpos[k + 1] = lpos[k]$. In the other case, we try to increase $lpos[k + 1]$ by one, and again do the comparison, and so on. Comparison of any two substrings can be done in $O(1)$ using hashes or suffix array. Of course, total time to build $lpos$ array will be then $O(n)$ - because there won't be more than $n$ increases (and string comparisons) during the whole algorithm. Another approach to building $lpos$ array is to use prefixe-function. For this, let's make a string reverse(s) + # + s, and if in some point of the right half of the string the value of the prefix function equaled to $k$, then let's assign $lpos[k] =$ this position (if, of course, this $lpos[k]$ haven't yet been assigned before - because we have to find only first occurences). Finally, it's rather easy to get $O(n)$ solution of this problem using rather famous approaches: hashes, suffix array, prefix-function and palindromic array. $O(n\\log n)$-solution is somewhat easier, - it is based on binary search (for building palindromic array and for answering the queries) and, for example, hashes (for comparison of two substrings). Proof The only non-obvious thing is why after we've fixed the position $pos$ (we remind it's a position of middle of central part of $middle$), - after that we can greedily take the maximum palindrome with center in it. Let's suppose the contrary: suppose it was better not to take the maximum palindrome centered in $pos$, but to take some smaller palindrome centered here. Look what happens when we decrease a length of palindrome by two (by one from each end): we loose two symbols in $middle$, but instead we get more \"freedom\" for $prefix$ and $suffix$ parts. But for both of them their $freedom$ increased only by one: $prefix$ gained one symbol after the end, and $suffix$ - one symbol before this beginning. So, taking into account the monotonic increase of $rpos$, we see that $prefix$ and $suffix$ could increase only by one, not more. Summarizing this discussion, we can say that after decreasing the $middle$ part we loose two symbols, and gain maximum two symbols. That's why there is no need in decreasing the $middle$ part, we can always select it as the maximum-sized palindrome. Another approach Let's iterate over each suffix length, and after we've fixed some suffix length, we have to find maximum-sized palindrome between the $suffix$ and the found $prefix$ (position of the $prefix$ still has to be found, just like in the previous solution). First idea is to use some greedy (similar to described above): take maximum-sized palindrome with center between $prefix$ and $suffix$, and \"cut\" it down, in order to fit between the $prefix$ and $suffix$. It's wrong: there are tests, where after cutting the maximum palindrome becomes very small, so after cutting down it's better to choose another palindrome. But we can cope with this using the following approach: let's find the length of $middle$ part using binary search. To do this, we have to answer the following queries: \"is there a palindrome of length at least $x$ among all palindromes centered between $l$ and $r$\". I.e. given $x$, we should answer, is there a number greater that or equal to $x$ in the segment $[l + x;r - x]$ (I suppose that $x$ is a half of the length of palindrome). We can answer to these maximum queries using segment tree in $O(\\log n)$, so the total solution is $O(n\\log^{2}n)$. Alternatively we can use sparse-table to reach $O(n\\log n)$ asymptotics (sparse-table is a table where for each position $i$ and power of two $j$ the answer for segment $[i;i + j - 1]$ is precalculated). This can be done using segment tree, built over the palindromic array (the palindromic array should be calculated, as described in the previous solution).",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "hashing",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "32",
    "index": "A",
    "title": "Reconnaissance",
    "statement": "According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most $d$ centimeters. Captain Bob has $n$ soldiers in his detachment. Their heights are $a_{1}, a_{2}, ..., a_{n}$ centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.\n\nWays $(1, 2)$ and $(2, 1)$ should be regarded as different.",
    "tutorial": "Problem A is quite straight-forward. You can simply enumerate all pairs using two for loops since N is not greater than 1000. Or you can sort the list and for every Ai, find the first Aj such that Aj-Ai>d in the range [i+1,N] using binary search.",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "32",
    "index": "B",
    "title": "Borze",
    "statement": "Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.",
    "tutorial": "Problem B doesn't need an array at all. You can consume a single character at a time using getchar and then output a '0' if the character is '.' or consume another character to determine whether to output '1' or '2' otherwise.",
    "tags": [
      "expression parsing",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "32",
    "index": "C",
    "title": "Flea",
    "statement": "It is known that fleas in Berland can jump only vertically and horizontally, and the length of the jump is always equal to $s$ centimeters. A flea has found herself at the center of some cell of the checked board of the size $n × m$ centimeters (each cell is $1 × 1$ centimeters). She can jump as she wishes for an arbitrary number of times, she can even visit a cell more than once. The only restriction is that she cannot jump out of the board.\n\nThe flea can count the amount of cells that she can reach from the starting position $(x, y)$. Let's denote this amount by $d_{x, y}$. Your task is to find the number of such starting positions $(x, y)$, which have the maximum possible value of $d_{x, y}$.",
    "tutorial": "Problem C is a little tricky. Two cells are reachable from each other if and only if their horizontal or vertical distance is exactly S if they are on the same row or column, which is identical to the property that their indexes of one dimension is the same while those of the other are congruent modulo S. So you are to count the number of remainders modulo S whose occurrence is more frequent than others, which equals N%S when S divides N or N when not for rows. The number of such occurrences is the ceiling of N/S, the smallest integer no smaller than N/S. Multiplying the product of these two numbers for rows and that of the other two for columns together gives the answer. I failed the test of this problem for a silly typing error.",
    "tags": [
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "32",
    "index": "D",
    "title": "Constellation",
    "statement": "A star map in Berland is a checked field $n × m$ squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer $x$ (\\underline{radius of the constellation}) the following is true:\n\n- the 2nd is on the same vertical line as the 1st, but $x$ squares up\n- the 3rd is on the same vertical line as the 1st, but $x$ squares down\n- the 4th is on the same horizontal line as the 1st, but $x$ squares left\n- the 5th is on the same horizontal line as the 1st, but $x$ squares right\n\nSuch constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal — the one, whose central star if higher than the central star of the other one; if their central stars are at the same level — the one, whose central star is to the left of the central star of the other one.\n\nYour task is to find the constellation with index $k$ by the given Berland's star map.",
    "tutorial": "Problem D requires you to scan the map multiple times with increasing radii.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "33",
    "index": "A",
    "title": "What is for dinner?",
    "statement": "In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are \"relaxing\".\n\nFor a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).\n\nIt turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again.\n\nUnhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative.\n\nAs Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.\n\nWe should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.",
    "tutorial": "The solution of the problem is rather trivial. It was needed to make an array, where for each row of teeth the value of residual viability of the sickest thooth in this row would have kept (sickest tooth in the row is called the one with the lowest residual viability). Thus we define for each row of teeth the maximum number of crucians, which Valery able to eat, using this row (Valeria can not eat more crucians, because the residual viability of the sickest tooth will become negative). Knowing these values, you just need to sum them and to give the minimum of the sum and total amount of crucians in Valerie's portion for dinner as answer.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "33",
    "index": "C",
    "title": "Wonderful Randomized Sum",
    "statement": "Learn, learn and learn again — Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of $n$ numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by $ - 1$. The second operation is to take some suffix and multiply all numbers in it by $ - 1$. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations?",
    "tutorial": "This problem can be solved in linear time, using the following idea: 1. If desired prefix and suffix intersect, then their common part is remaining with the initial sign and therefore, this case is equivalent to the case when we take the same suffix and prefix, but without their common part: (s1 [s2 )s3 ] is equal to (s1)s2[s3] (s1,s2,s3 - some subsequences). 2. Let the sum of elements A1 .. An be equal to S. Then when inverting signs we get -A1, -A2 .. -An, and the sum is thereafter changed to -S, i.e. sum of elements on the segment will just change its' sign when inverting the whole segment's signs. 3. One can consider the initial problem as follows: we have to choose a consecutive subsequence (the part of the initial sequence, remaining between suffix and prefix), and invert all the numbers remaining out of it. Considering the sum of the whole sequence be S, and the sum of the target subsequence as S1 , the total sum will be equal to -(S-S1) + S1 = 2*S1 - S - this is the value, we want to get. S is a constant, therefore to maximize this value, we just have to maximize S1, i.e. find a consecutive subsequence of the initial sequence that has the biggest sum, and this can be done in linear as follows: mx = 0; for(i=0;i<n;++i) { sum += a[i]; if(sum < 0) sum = 0; mx = max(mx, sum); }",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "33",
    "index": "D",
    "title": "Knights",
    "statement": "Berland is facing dark times again. The army of evil lord Van de Mart is going to conquer the whole kingdom. To the council of war called by the Berland's king Valery the Severe came $n$ knights. After long discussions it became clear that the kingdom has exactly $n$ control points (if the enemy conquers at least one of these points, the war is lost) and each knight will occupy one of these points.\n\nBerland is divided into $m + 1$ regions with $m$ fences, and the only way to get from one region to another is to climb over the fence. Each fence is a circle on a plane, no two fences have common points, and no control point is on the fence. You are given $k$ pairs of numbers $a_{i}$, $b_{i}$. For each pair you have to find out: how many fences a knight from control point with index $a_{i}$ has to climb over to reach control point $b_{i}$ (in case when Van de Mart attacks control point $b_{i}$ first). As each knight rides a horse (it is very difficult to throw a horse over a fence), you are to find out for each pair the minimum amount of fences to climb over.",
    "tutorial": "Denote the number of fences surrounding the control point number i through cnti. Also denote cntij - the number of fences surrounding point i and point j. Then the answer to the query (i, j) is cnti + cntj - cntij. Clearly, that we can calculate all the values cnti with time O(n * m). The problem is the fast computation of the values cntij. And then suggests two solutions: a simple and not very much. Simple is as follows: create for every point i a bitset, j-th is equal to 1 if the j-th fence surrounds the point number i. Then, obviously cntij = count(zi & zj), where count(a) - the number of ones in bitset a. Now another solution. Add another fence with a center at (0, 0) and infinite radius. We construct a graph whose vertices are the fences as follows: we draw an arc from i to j, if the i-th fence is a fence with the minimum radius surrounding the fence number j. Obviously we get a directed tree rooted at the fence of infinite radius. Also, for each control point will find idxi - number of the fence with minimum radius surrounding the i-th control point. Then cntij = distij + distji, where distij - distance from vertex i to the lowest common ancestor of verticex i ans j. With the implementation problems should not arise, because in the first solution could write bitset himself or use the standard bitset from STL (for those who write in C++), while in the second solution we could preprocess all the lca with time O(n2).",
    "tags": [
      "geometry",
      "graphs",
      "shortest paths",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "33",
    "index": "E",
    "title": "Helper",
    "statement": "It's unbelievable, but an exam period has started at the OhWord University. It's even more unbelievable, that Valera got all the tests before the exam period for excellent work during the term. As now he's free, he wants to earn money by solving problems for his groupmates. He's made a $list$ of subjects that he can help with. Having spoken with $n$ of his groupmates, Valera found out the following information about them: what subject each of them passes, time of the exam and sum of money that each person is ready to pay for Valera's help.\n\nHaving this data, Valera's decided to draw up a timetable, according to which he will solve problems for his groupmates. For sure, Valera can't solve problems round the clock, that's why he's found for himself an optimum order of day and plans to stick to it during the whole exam period. Valera assigned time segments for sleep, breakfast, lunch and dinner. The rest of the time he can work.\n\nObviously, Valera can help a student with some subject, only if this subject is on the $list$. It happened, that all the students, to whom Valera spoke, have different, but one-type problems, that's why Valera can solve any problem of subject $list_{i}$ in $t_{i}$ minutes.\n\nMoreover, if Valera starts working at some problem, he can break off only for sleep or meals, but he can't start a new problem, not having finished the current one. Having solved the problem, Valera can send it instantly to the corresponding student via the Internet.\n\nIf this student's exam hasn't started yet, he can make a crib, use it to pass the exam successfully, and pay Valera the promised sum. Since Valera has little time, he asks you to write a program that finds the order of solving problems, which can bring Valera maximum profit.",
    "tutorial": "To solve the problem, firstly, it was necessary to carefully read the input data and convert all the time specified in the format $day, hour, minute$ in a minute since the beginning of the session for convenience. This could be done by using formula $newTime = (day - 1) * 24 * 60 + hour * 60 + minute$. Secondly, it is necessary to count the number of free minutes for solving the problems, which Valera has throughout the session. In addition, for every free minute $j$ it is needed to determine $t_{j}$ --- number of this minute since the beginning of the session. Next, it is needed calculate the value of $deadline_{i}$ for each student --- the latest free minute since the beginning of the session that if Valerie has finished to perform the task at that moment, he will receive the promised sum from the respective student. Obviously, if Valerie will not be sleeping or eating at the moment of $i$-th student begin to pass the exam, then $deadline_{i}$ will be equal to a minute prior to the beginning of the exam, else $deadline_{i}$ will correspond to the latest free minute prior to sleeping or a meal. In addition, if the free minute from the beginning of the session doesn't exist or Valera can not help $i$-th student, than we define $deadline_{i}$ = -1 in this case. Then we will sort all the students in non-decreasing value of $deadline$ and use the method of dynamic programming. The two parameters $i$ --- amount of viewed students (i.e. those for which the problems is already solved) and $j$ --- the number of free minute, from which Valera can begin to perform tasks for the next student will be the states of \"dynamics\". The value of the \"dynamics\" will be the maximum profit that Valerie can get when he will reach the respective state. Obviously, there are two possible transition from state $i$, $j$: in the state $i + 1$, $j$ --- Valera will not solve the problems for the $i$-th student in this casein the state $i + 1$, $j + time[i]$ (where $time[i]$ is the time required for solving problems of $i$-th student) --- Valera will solve the problem for $i$-th student in this case, and he will get sum of money this student is ready to pay. However, such a transition is possible only if $t_{None}(j + time[i])$ does not exceed $deadline_{i}$. Once the value of dynamics for all possible values of $i$, $j$ will be counted, the answer to the problem will be a maximum of $n$-th row of the array (where $n$ --- the total number of students). In addition, you should use an additional array of ancestors and accurately convert the time back to the desired form to restore the answer.",
    "tags": [],
    "rating": 2600
  },
  {
    "contest_id": "36",
    "index": "A",
    "title": "Extra-terrestrial Intelligence",
    "statement": "Recently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for $n$ days in a row. Each of those $n$ days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.",
    "tutorial": "This task is very easy, and I hope all of you have solved it. But let's talk about it. Let input sequence is named as $a$, and its length is $n$. Then let's save sequence $x_{1}, ..., x_{k}$ is increasing order - all of positions, where $a_{None} = '1'$. We must check if this sequence $x_{1}, ..., x_{k}$ is a arithmetic progression. We save variable $d = x_{2} - x_{1}$ and check: for all $1  \\le  i < k$, is \"$d = x_{None} - x_{i}$\" correct. If it's correct, output \"YES\", else \"NO\".",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "36",
    "index": "B",
    "title": "Fractal",
    "statement": "Ever since Kalevitch, a famous Berland abstractionist, heard of fractals, he made them the main topic of his canvases. Every morning the artist takes a piece of graph paper and starts with making a model of his future canvas. He takes a square as big as $n × n$ squares and paints some of them black. Then he takes a clean square piece of paper and paints the fractal using the following algorithm:\n\nStep 1. The paper is divided into $n^{2}$ identical squares and some of them are painted black according to the model.\n\nStep 2. Every square that remains white is divided into $n^{2}$ smaller squares and some of them are painted black according to the model.\n\nEvery following step repeats step 2.\n\nUnfortunately, this tiresome work demands too much time from the painting genius. Kalevitch has been dreaming of making the process automatic to move to making 3D or even 4D fractals.",
    "tutorial": "In author's solution the fractal is built by a recursive function. Let ''a'' be a square $n^{k}  \\times  n^{k}$ result matrix. Write the recursive function fractal(x, y, k) filling a square part of the matrix with an upper left corner in (x, y) and a length of the side $n^{k}$, drawing the fractal of depth $k$. In case k = 0 put ''.'' at the current position. Otherwise you have to divide the part of the matrix into $n^{2}$ square parts with size $n^{None}  \\times  n^{None}$, and fill them according to the model. If the corresponding symbol in the model is ''*'', fill the square with symbols ''*'', otherwise execute fractal(x1, y1, k-1) for (x1, y1) being the coordinates of the upper left corner of the new square. kdalex offers a solution (http://codeforces.com/blog/entry/764), which is easier in implementation. Consider all positions (x, y). If for some $c = n^{d}$, $0  \\le  d < k$ the square ((x/c)%n, (y/c)%n) of the model is black then (x, y) must be black, otherwise it is white. It is easy to check that if the square ((x/c)%n, (y/c)%n) is black for d = k - 1 , then we have that the current position (x, y) is in the black square after the first step of the algorithm. If ((x/c)%n, (y/c)%n) is black for d = k - 2, it happens after the second step, etc.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "36",
    "index": "C",
    "title": "Bowls",
    "statement": "Once Petya was in such a good mood that he decided to help his mum with the washing-up. There were $n$ dirty bowls in the sink. From the geometrical point of view each bowl looks like a blunted cone. We can disregard the width of the walls and bottom. Petya puts the clean bowls one on another naturally, i. e. so that their vertical axes coincide (see the picture). You will be given the order in which Petya washes the bowls. Determine the height of the construction, i.e. the distance from the bottom of the lowest bowl to the top of the highest one.",
    "tutorial": "Imagine that we have successfully processed first $i - 1$ bowls, i.e. we know height of the bottom $y_{j}$ for every bowl $j$ ($1  \\le  j < i$). Now we are going to place $i$-th bowl. For each $j$-th already placed bowl, we will calculate the relative height of the bottom of $i$-th bowl above the bottom of $j$-th bowl, assuming that there are no other bowls. Lets denote this value by $ \\Delta _{None}$. It is obvious that height of the new bowl is equal to the maximal of the following values: $y_{i} = max(y_{j} +  \\Delta _{None})$. Now I will describe how to calculate $ \\Delta _{None}$. Firstly, consider two trivial cases: I. $r_{i}  \\ge  R_{j}$: bottom of $i$-th bowl rests on the top of $j$-th. Then $ \\Delta _{None} = h_{j}$. II. $R_{i}  \\le  r_{j}$: bottom of $i$-th bowl reaches the bottom of $j$-th. Then $ \\Delta _{None} = 0$. Then there are three slightly more complicated cases. 1. $r_{i} > r_{j}$: bottom of $i$-th bowl gets stuck somewhere between the top and the bottom of $j$-th, touching it's sides. From the similarity of some triangles we get that $\\Delta_{i,j}=\\frac{r_{i}-r_{i}}{R_{j}-r_{j}}h_{j}$. 2. $R_{i}  \\le  R_{j}$: top of $i$-th bowl gets stuck somewhere between the top and the bottom of $j$-th, touching it's sides. From the similarity of some triangles we get that $\\Delta_{i,j}=\\frac{R_{i-r_{i}}}{R_{i-r_{i}}}h_{j}-h_{i}$. 3. $R_{i} > R_{j}$: sides of $i$-th bowl touch the top of $j$-th in it's upper points. Then $\\Delta_{i,j}=h_{j}-{\\frac{R_{i-r_{i}}}{R_{i}-r_{i}}}h_{i}$. Note that, for example, cases 1 and 2 do not exclude each other, so the final value of $ \\Delta _{None}$ is equal to the maximum of the values, computed in all three cases. Note that if the calculated value of $ \\Delta _{None}$ is negative, the result should be 0. Thanks to adamax for pointing it.",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "36",
    "index": "D",
    "title": "New Game with a Chess Piece",
    "statement": "Petya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump $k$ squares diagonally down and to the right. The player who can’t move the piece loses.\n\nThe guys haven’t yet thought what to call the game or the best size of the board for it. Your task is to write a program that can determine the outcome of the game depending on the board size.",
    "tutorial": "In the problem we have a game on an acyclic graph. Positions in the game (vertices of the graph) are pairs (n, m), where n and m are distances from the current position of the piece to the bottom and to the rights borders of the board. For every position (n, m) there are at most three moves: (n - 1, m), (n, m - 1), (n - k, m - k). The graph is acyclic, because at each move the sum n+m strictly decreases. If the numbers n, m and k do not exeed, say, 1000, the problem is solved by easy dynamics on the acyclic graph, standard for such games. Let d(n, m) = 1, if the position (n, m) is winning, and d(n, m) = 0, if the position (n, m) is losing. The value of d(n, m) is calculated using the following considerations. If there exists a move from the current position to a losing one, then the current position is winning, otherwise it is losing. But conditions of the problem do not allow us to solve it by the standard dynamics. The solution is to implement the dynamics for small values of n and m and to find a pattern! For example, build the matrix of values d(n, m) for k = 2: 010101010101011010101010101001111111111111101101010101010110101010101010110111111111011011010101011011011010101001101101............ Consider the corner stripes in this picture. Start with a corner stripe with width 2 in the upper-left corner (the 'corner stripe' in this case is the set of squares with n <= 2 || m <= 2). Starting from the upper-left corner, we have a stripe with width 2 (k for k > 2) such that 0 and 1 alternate. That is no wonder, because in that stripe we cannot jump by k. Next we have a stripe of only 1, then there is a stripe with width k like the first one, but it is inverted (1 are changed by 0, and 0 by 1), then we have a stripe of 1, and then there is exactly the same stripe as the one in the very beginning! Since every next corner stripe depends only on the previous one with width k, we have the pattern: the following stripe of 1, the inverted stripe, the stripe of 1 again, etc. In fact we get d(n, m) = d(n - (2 k + 2), m - (2 k + 2)) for n, m > 2 k + 2. It yields formulas to calculate d(n, m) for every n and m. To understand given explanations more carefully, implement the dynamics and find the pattern yourself. There is also a tricky case k = 1. It yields to a bit different pattern:) Remark. I want to emphasize that we have not just found the pattern and made a shamanistic hypothesis that it will be repeated. We have proved this. The stripes will alternate further, because every next stripe is uniquely determined by the previous stripe with width k.",
    "tags": [
      "games"
    ],
    "rating": 2300
  },
  {
    "contest_id": "36",
    "index": "E",
    "title": "Two Paths",
    "statement": "Once archaeologists found $m$ mysterious papers, each of which had a pair of integers written on them. Ancient people were known to like writing down the indexes of the roads they walked along, as «$a$ $b$» or «$b$ $a$», where $a, b$ are the indexes of two different cities joint by the road . It is also known that the mysterious papers are pages of two travel journals (those days a new journal was written for every new journey).\n\nDuring one journey the traveler could walk along one and the same road several times in one or several directions but in that case he wrote a new entry for each time in his journal. Besides, the archaeologists think that the direction the traveler took on a road had no effect upon the entry: the entry that looks like «$a$ $b$» could refer to the road from $a$ to $b$ as well as to the road from $b$ to $a$.\n\nThe archaeologists want to put the pages in the right order and reconstruct the two travel paths but unfortunately, they are bad at programming. That’s where you come in. Go help them!",
    "tutorial": "The problem is to divide edges of a graph into two groups forming two paths in the graph. Clearly, each path is contained in one connected component. So if the given graph has more than two connected components, the problem has no solution. The same we can say if the graph has more than four vertices of an odd degree. Indeed, each vertex in a path (even if the path contains some vertices more than once) have an even degree, exept the first vertex and the last vertex. So the union of two paths can contain no more than four odd vertices. Now consider the cases: 1. One connected component, no vertices of an odd degree. So we have an euler cycle, which can be divided into two paths. 2. One connected component, two odd vertices. The same with an euler path instead of euler cycle. There is a tricky case of a graph with only one edge, which cannot be divided into two nonempty paths. 3. One connected component, four odd vertices. The most interesting case. Connect two vertices of an odd degree by a dummy edge. You will get a graph with an euler path. Find the euler path and delete the dummy edge - you will get two paths. 4. Two connetced components, each having zero or two odd vertices. Two euler paths/cycles. 5. Two connected components, four odd vertices in one and no odd vertices in another. No solution.",
    "tags": [
      "constructive algorithms",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 2600
  },
  {
    "contest_id": "37",
    "index": "A",
    "title": "Towers",
    "statement": "Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.\n\nVasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.",
    "tutorial": "The total number of towers is equal to number of different numbers in this set. To get the maximum height of the tower, it was possible to calculate for each length the number of bars with this length, and from these numbers is to choose the maximum.",
    "tags": [
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "37",
    "index": "B",
    "title": "Computer Game",
    "statement": "Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.\n\nWhile playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:\n\n1) The boss has two parameters: $max$ — the initial amount of health and $reg$ — regeneration rate per second.\n\n2) Every scroll also has two parameters: $pow_{i}$ — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than $pow_{i}$ percent of health the scroll cannot be used); and $dmg_{i}$ the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts $dmg_{i}$ of damage per second upon him until the end of the game.\n\nDuring the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates $reg$ of health (at the same time he can’t have more than $max$ of health), then the player may use another scroll (no more than one per second).\n\nThe boss is considered to be defeated if at the end of a second he has nonpositive ($ ≤ 0$) amount of health.\n\nHelp Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.",
    "tutorial": "Constraints in the problem allows us to solve it this way: we keep the current number of health from the boss, and current summary damage from used scrolls per second. At the next step, we choose which scrolls we can use in the current second. Of all these, we find the scroll, which causes the most damage, and apply it. If at some point we could not use any of the scrolls, and the current damage in one second does not exceed regeneration, we deduce that there are no answers. Otherwise, continue to iterate the algorithm until the number hit points will be nonnegative.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "37",
    "index": "C",
    "title": "Old Berland Language",
    "statement": "Berland scientists know that the Old Berland language had exactly $n$ words. Those words had lengths of $l_{1}, l_{2}, ..., l_{n}$ letters. Every word consisted of two letters, $0$ and $1$. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol.\n\nHelp the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.",
    "tutorial": "One of the easiest to understand solutions of this problem is as follows: sort the words in ascending order of length, while remembering their positions in the source list. We will consistently build our set, starting with the short strings: strings of length one can only be strings \"0\" and \"1\". If the number of words of length one in a set are more than two, hence there are no answers. Add the desired number of strings of length one to answer, and remove it from the current list. Then look at the string of length two: each of the remaining strings of length one can be extended in two ways (having added to each of these symbols 0 and 1). Add the desired number of strings of length two in our answer, and then increase the length of the remaining strings by one. Continue this process, until we get all words from the input set. You can see that if at some moment the number of allowable words exceeded the number of remaining, the extra words can be ignored and solution takes O (N * the maximum length of input set) time.",
    "tags": [
      "data structures",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "37",
    "index": "D",
    "title": "Lesson Timetable",
    "statement": "When Petya has free from computer games time, he attends university classes. Every day the lessons on Petya’s faculty consist of two double classes. The floor where the lessons take place is a long corridor with $M$ classrooms numbered from $1$ to $M$, situated along it.\n\nAll the students of Petya’s year are divided into $N$ groups. Petya has noticed recently that these groups’ timetable has the following peculiarity: the number of the classroom where the first lesson of a group takes place does not exceed the number of the classroom where the second lesson of this group takes place.\n\nOnce Petya decided to count the number of ways in which one can make a lesson timetable for all these groups. The timetable is a set of $2N$ numbers: for each group the number of the rooms where the first and the second lessons take place. Unfortunately, he quickly lost the track of his calculations and decided to count only the timetables that satisfy the following conditions:\n\n1) On the first lesson in classroom $i$ exactly $X_{i}$ groups must be present.\n\n2) In classroom $i$ no more than $Y_{i}$ groups may be placed.\n\nHelp Petya count the number of timetables satisfying all those conditionsю As there can be a lot of such timetables, output modulo $10^{9} + 7$.",
    "tutorial": "This problem is solved by dynamic programming: state of dynamics will be a pair of numbers - the number of current room and number of groups which have first lesson in the room with a number not exceeding the current and for which the second room is not defined yet. For each state check all possible number of groups for which the second lesson will be held in the current classroom. When you add an answer from the new state, it must be multiplied by the corresponding binomial coefficients (the number of ways to select groups which have the first lesson in next room - $X_{i} + 1$, and the number of ways to select groups which have the second lesson in the current classroom).",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "37",
    "index": "E",
    "title": "Trial for Chief",
    "statement": "Having unraveled the Berland Dictionary, the scientists managed to read the notes of the chroniclers of that time. For example, they learned how the chief of the ancient Berland tribe was chosen.\n\nAs soon as enough pretenders was picked, the following test took place among them: the chief of the tribe took a slab divided by horizontal and vertical stripes into identical squares (the slab consisted of $N$ lines and $M$ columns) and painted every square black or white. Then every pretender was given a slab of the same size but painted entirely white. Within a day a pretender could paint any side-linked set of the squares of the slab some color. The set is called linked if for any two squares belonging to the set there is a path belonging the set on which any two neighboring squares share a side. The aim of each pretender is to paint his slab in the exactly the same way as the chief’s slab is painted. The one who paints a slab like that first becomes the new chief.\n\nScientists found the slab painted by the ancient Berland tribe chief. Help them to determine the minimal amount of days needed to find a new chief if he had to paint his slab in the given way.",
    "tutorial": "First, we construct the following graph: each cell we associate a vertex of the same color as the cell itself. Between neighboring cells hold an edge of weight 0, if the cells share the same color and weight of 1, if different. Now, for each cell count the shortest distance from it to the most distant black cell (denoted by $D$). It is easy to see that we can construct a sequence of $D + 1$ repainting leads to the desired coloring: The first step of color all the cells at a distance less than or equal to $D$ in black color At the second step color all the cells at a distance less than or equal to $D - 1$ in whiteEtc. Of all the cells, choose the one for which this distance is minimal, and this distance increased by one will be the answer to the problem.",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "39",
    "index": "A",
    "title": "C*++ Calculations",
    "statement": "C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this ($expression$ is the main term):\n\n- $expression$ ::= $summand$ | $expression + summand$ | $expression - summand$\n- $summand$ ::= $increment$ | $coefficient$*$increment$\n- $increment$ ::= a++ | ++a\n- $coefficient$ ::= 0|1|2|...|1000\n\nFor example, \"5*a++-3*++a+a++\" is a valid expression in C*++.\n\nThus, we have a sum consisting of several summands divided by signs \"+\" or \"-\". Every summand is an expression \"a++\" or \"++a\" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to $1$.\n\nThe calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains \"a++\", then during the calculation first the value of the \"a\" variable is multiplied by the coefficient, then value of \"a\" is increased by $1$. If the summand contains \"++a\", then the actions on it are performed in the reverse order: first \"a\" is increased by $1$, then — multiplied by the coefficient.\n\nThe summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.",
    "tutorial": "To get the maximal possible result you have just to sort summands in non-decreasing order by coefficients (counting coefficients with preceeding signs + and -). You should not pay attention to 'a++' or '++a'! The question is: why is it true? First, consider an expression with only 'a++'. Then our assertion is obvious: it is better to multiply 'a' by small coefficients when it has small value, and by large coefficients, when it becomes larger. The same also takes place in case of negative coefficients or a-value. Of course, it is not a rigorous proof. I hope you will think on it if you haven't get it yet. Second, consider the expression $k * a + + + k * + + a$, where $k$ is some coefficient equal for both summands. Let initial value of 'a' equals to $a_{0}$. Calculating the value of the expression both ways, we obtain: $k * a_{0} + k * (a_{0} + 2) = k * (a_{0} + 1) + k * (a_{0} + 1)$. So in this case the order is immaterial. Third, let us have the expression $k * a + + + l * + + a$, where $k$ and $l$ are two distinct coefficients. This expression can have two different values: $k * a_{0} + l * (a_{0} + 2)$ and $k * (a_{0} + 1) + l * (a_{0} + 1)$. The first value is greater than the second one if and only if $k < l$. We can deal with the expression k*++a+l*a++ analogously. Thus if we have two succesive summands with the same coefficient, we may swap or not to swap them. If we have two succesive summands with distinct coefficients, we must put the summand with a smaller coeficient first. Applying these considerations while it is necessary, we get a sequence of summands sorted by coefficients.",
    "tags": [
      "expression parsing",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "39",
    "index": "B",
    "title": "Company Income Growth",
    "statement": "Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since $2001$ (the year of its founding) till now. Petya knows that in $2001$ the company income amounted to $a_{1}$ billion bourles, in $2002$ — to $a_{2}$ billion, ..., and in the current $(2000 + n)$-th year — $a_{n}$ billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to $1$ billion bourles, in the second year — $2$ billion bourles etc., each following year the income increases by $1$ billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers $a_{i}$ can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers $a_{i}$ from the sequence and leave only some subsequence that has perfect growth.\n\nThus Petya has to choose a sequence of years $y_{1}$, $y_{2}$, ..., $y_{k}$,so that in the year $y_{1}$ the company income amounted to $1$ billion bourles, in the year $y_{2}$ — $2$ billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.",
    "tutorial": "For this problem, the greedy solution is acceptable. Process given numbers consequently until $1$ is found. Then continue to process searching for $2$, then for $3$, etc.",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "39",
    "index": "C",
    "title": "Moon Craters",
    "statement": "There are lots of theories concerning the origin of moon craters. Most scientists stick to the meteorite theory, which says that the craters were formed as a result of celestial bodies colliding with the Moon. The other version is that the craters were parts of volcanoes.\n\nAn extraterrestrial intelligence research specialist professor Okulov (the namesake of the Okulov, the author of famous textbooks on programming) put forward an alternate hypothesis. Guess what kind of a hypothesis it was –– sure, the one including extraterrestrial mind involvement. Now the professor is looking for proofs of his hypothesis.\n\nProfessor has data from the moon robot that moves linearly in one direction along the Moon surface. The moon craters are circular in form with integer-valued radii. The moon robot records only the craters whose centers lay on his path and sends to the Earth the information on the distance from the centers of the craters to the initial point of its path and on the radii of the craters.\n\nAccording to the theory of professor Okulov two craters made by an extraterrestrial intelligence for the aims yet unknown either are fully enclosed one in the other or do not intersect at all. Internal or external tangency is acceptable. However the experimental data from the moon robot do not confirm this theory! Nevertheless, professor Okulov is hopeful. He perfectly understands that to create any logical theory one has to ignore some data that are wrong due to faulty measuring (or skillful disguise by the extraterrestrial intelligence that will be sooner or later found by professor Okulov!) That’s why Okulov wants to choose among the available crater descriptions the largest set that would satisfy his theory.",
    "tutorial": "The authors solution takes $O(n^{2})$ time and $O(n^{2})$ memory. Solutions with $O(n^{2}\\log{n})$ time and $O(n)$ memory are also acceptable. Let us reformulate the problem. Given a set of segments on a line, and the task is to find the largest subset such that segments in it don't intersect ``partially''. Two segments $[a, b]$ and $[c, d]$ intersect partially, if, for instance, $a < c < b < d$. Take all the ends of the given segments, sort them, and compute the dynamics: $d_{None}$ is the largest possible size of such subset that segments in don't intersect partially and located between the $l$-th end and the $r$ end (in sorted order), inclusively. We want to compute $d_{None}$ having already computed $d_{None}$ for all $l  \\le  i  \\le  j  \\le  r$, but $[i, j]  \\neq  [l, r]$. First put $d_{None} = d_{None}$ if we don't take segments with the left end in $l$. Now process the segments with the left end in $l$. If the segment $[l, r]$ exists, we undoubtedly take it to our set. If we take another segment, say, $[l, i]$, where $i < r$, look at segments $[l, i]$ and $[i, r]$ (we have answers for them already computed) and try to update $d_{None}$. The asymptotics is $O(n^{2})$, because the total number of left ends is $O(n)$. Then you have to output the certificate, i.e. the optimal set itself. It can be done in the standard way.",
    "tags": [
      "dp",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "39",
    "index": "D",
    "title": "Cubical Planet",
    "statement": "You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points $(0, 0, 0)$ and $(1, 1, 1)$. Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.",
    "tutorial": "The flies can NOT see each other iff they are in opposite vertices. You may use multiple ways to check this. For instance, you can check the Manhattan distance $|x_{1} - x_{2}| + |y_{1} - y_{2}| + |z_{1} - z_{2}| = 3$ or the Euclidian distance ${\\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}+(z_{1}-z_{2})^{2}}}={\\sqrt{3}}$. You can check if all three coorditanes are distinct (x1 != x2) && (y1 != y2) && (z1 != z2), or just (x1^x2)+(y1^y2)+(z1^z2) == 3!",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "39",
    "index": "E",
    "title": "What Has Dirichlet Got to Do with That?",
    "statement": "You all know the Dirichlet principle, the point of which is that if $n$ boxes have no less than $n + 1$ items, that leads to the existence of a box in which there are at least two items.\n\nHaving heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a game. There are $a$ different boxes and $b$ different items, and each turn a player can either add a new box or a new item. The player, after whose turn the number of ways of putting $b$ items into $a$ boxes becomes no less then a certain given number $n$, loses. All the boxes and items are considered to be different. Boxes may remain empty.\n\nWho loses if both players play optimally and Stas's turn is first?",
    "tutorial": "The number of ways to put $b$ items into $a$ boxes is, of course, $a^{b}$. So we have an acyclic game for two players with positions $(a, b)$ for which $a^{b} < n$. Unfortunatly, there exists an infinite number of such positions: $a = 1$, $b$ is any. But in this case, if $2^{b}  \\ge  n$, it is a draw position, because the only way for both players (not leading to lose) is to increase $b$ infinitely. Another special case is a position with $b = 1$ and rather large $a$. Namely, if $a\\geq{\\sqrt{n}}$, there is also only one move from this position - to increase $a$. If $a = n - 1$ the position is losing, if $a = n - 2$ it is winning, for $a = n - 3$ it is losing again and so on. Thus we have two kinds of positions to deal with them specially. The number of other positions is not very large, and you can compute the standard dynamics for acyclic games for them.",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 2000
  },
  {
    "contest_id": "39",
    "index": "F",
    "title": "Pacifist frogs",
    "statement": "Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.\n\nOne can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from $1$ to $n$ and the number of a hill is equal to the distance in meters between it and the island. The distance between the $n$-th hill and the shore is also $1$ meter.\n\nThumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is $d$, the frog will jump from the island on the hill $d$, then — on the hill $2d$, then $3d$ and so on until they get to the shore (i.e. find itself beyond the hill $n$).\n\nHowever, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.",
    "tutorial": "The simple modelling of frog's jumps works too long, because $n$ can be $10^{9}$. The right solution is to count for each frog a number of smashed mosquitoes by checking divisibility of numbers of hills with mosquitoes by $d_{i}$.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "39",
    "index": "G",
    "title": "Inverse Function",
    "statement": "Petya wrote a programme on C++ that calculated a very interesting function $f(n)$. Petya ran the program with a certain value of $n$ and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had the result. However while Petya was drinking tea, a sly virus managed to destroy the input file so that Petya can't figure out for which value of $n$ the program was run. Help Petya, carry out the inverse function!\n\nMostly, the program consists of a function in C++ with the following simplified syntax:\n\n- $function$ ::= int f(int n) {$operatorSequence$}\n- $operatorSequence$ ::= $operator | operator operatorSequence$\n- $operator$ ::= return $arithmExpr$; $|$ if ($logicalExpr$) return $arithmExpr$;\n- $logicalExpr$ ::= $arithmExpr > arithmExpr$ $|$ $arithmExpr < arithmExpr$ $|$ $arithmExpr$ == $arithmExpr$\n- $arithmExpr$ ::= $sum$\n- $sum$ ::= $product$ $|$ $sum + product$ $|$ $sum - product$\n- $product$ ::= $multiplier$ $|$ $product * multiplier$ $|$ $product / multiplier$\n- $multiplier$ ::= n $|$ $number$ $|$ f($arithmExpr$)\n- $number$ ::= $0|1|2|... |32767$\n\nThe whitespaces in a $operatorSequence$ are optional.\n\nThus, we have a function, in which body there are two kinds of operators. There is the operator \"return $arithmExpr$;\" that returns the value of the expression as the value of the function, and there is the conditional operator \"if ($logicalExpr$) return $arithmExpr$;\" that returns the value of the arithmetical expression when and only when the logical expression is true. Guaranteed that no other constructions of C++ language — cycles, assignment operators, nested conditional operators etc, and other variables except the $n$ parameter are used in the function. All the constants are integers in the interval $[0..32767]$.\n\nThe operators are performed sequentially. After the function has returned a value other operators in the sequence are not performed. Arithmetical expressions are performed taking into consideration the standard priority of the operations. It means that first all the products that are part of the sum are calculated. During the calculation of the products the operations of multiplying and division are performed from the left to the right. Then the summands are summed, and the addition and the subtraction are also performed from the left to the right. Operations \">\" (more), \"<\" (less) and \"==\" (equals) also have standard meanings.\n\nNow you've got to pay close attention! The program is compiled with the help of $15$-bit Berland C++ compiler invented by a Berland company BerSoft, that's why arithmetical operations are performed in a non-standard way. Addition, subtraction and multiplication are performed modulo $32768$ (if the result of subtraction is negative, then $32768$ is added to it until the number belongs to the interval $[0..32767]$). Division \"/\" is a usual integer division where the remainder is omitted.\n\nExamples of arithmetical operations:\n\n\\[\n12345+23456=3033,\\quad0-1=32767,\\quad1024*1024=0,\\quad1000/3=333.\n\\]\n\nGuaranteed that for all values of $n$ from $0$ to $32767$ the given function is performed correctly. That means that:\n\n1. Division by $0$ never occures.\n\n2. When performing a function for the value $n = N$ recursive calls of the function $f$ may occur only for the parameter value of $0, 1, ..., N - 1$. Consequently, the program never has an infinite recursion.\n\n3. As the result of the sequence of the operators, the function always returns a value.\n\nWe have to mention that due to all the limitations the value returned by the function $f$ is independent from either global variables or the order of performing the calculations of arithmetical expressions as part of the logical one, or from anything else except the value of $n$ parameter. That's why the $f$ function can be regarded as a function in its mathematical sense, i.e. as a unique correspondence between any value of $n$ from the interval $[0..32767]$ and a value of $f(n)$ from the same interval.\n\nGiven the value of $f(n)$, and you should find $n$. If the suitable $n$ value is not unique, you should find the maximal one (from the interval $[0..32767]$).",
    "tutorial": "What can I say about problem G? You should parse a given function and calculate its value for all values of $n$. Of course, it is impossible to do it just implementing the recursion, because this can work too long (see example with Fibonacci sequence). So you should use dynamic programming.",
    "tags": [
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "39",
    "index": "H",
    "title": "Multiplication Table",
    "statement": "Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn only the multiplication table of decimals (and some students even learn it in the first grade). Help Petya make a multiplication table for numbers in the system of notations with the radix $k$.",
    "tutorial": "You have to calculate all products $i * j$, and output them in the system of notations with radix $k$.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "39",
    "index": "I",
    "title": "Tram",
    "statement": "In a Berland city S*** there is a tram engine house and only one tram. Three people work in the house — the tram driver, the conductor and the head of the engine house. The tram used to leave the engine house every morning and drove along his loop route. The tram needed exactly $c$ minutes to complete the route. The head of the engine house controlled the tram’s movement, going outside every $c$ minutes when the tram drove by the engine house, and the head left the driver without a bonus if he was even one second late.\n\nIt used to be so. Afterwards the Berland Federal Budget gave money to make more tramlines in S***, and, as it sometimes happens, the means were used as it was planned. The tramlines were rebuilt and as a result they turned into a huge network. The previous loop route may have been destroyed. S*** has $n$ crossroads and now $m$ tramlines that links the pairs of crossroads. The traffic in Berland is one way so the tram can move along each tramline only in one direction. There may be several tramlines between two crossroads, which go same way or opposite ways. Every tramline links two different crossroads and for each crossroad there is at least one outgoing tramline.\n\nSo, the tramlines were built but for some reason nobody gave a thought to increasing the number of trams in S***! The tram continued to ride alone but now the driver had an excellent opportunity to get rid of the unending control of the engine house head. For now due to the tramline network he could choose the route freely! Now at every crossroad the driver can arbitrarily choose the way he can go. The tram may even go to the parts of S*** from where it cannot return due to one way traffic. The driver is not afraid of the challenge: at night, when the city is asleep, he can return to the engine house safely, driving along the tramlines in the opposite direction.\n\nThe city people were rejoicing for some of the had been waiting for the tram to appear on their streets for several years. However, the driver’s behavior enraged the engine house head. Now he tries to carry out an insidious plan of installing cameras to look after the rebellious tram.\n\nThe plan goes as follows. The head of the engine house wants to install cameras at some crossroads, to choose a period of time $t$ and every $t$ minutes turn away from the favourite TV show to check where the tram is. Also the head of the engine house wants at all moments of time, divisible by $t$, and only at such moments the tram to appear on a crossroad under a camera. There must be a camera on the crossroad by the engine house to prevent possible terrorist attacks on the engine house head. Among all the possible plans the engine house head chooses the plan with the largest possible value of $t$ (as he hates being distracted from his favourite TV show but he has to). If such a plan is not unique, pick the plan that requires the minimal possible number of cameras. Find such a plan.",
    "tutorial": "Consider only the part of the graph reachable from $1$. The task is to find the largest number $t$, such that a chosen set of vertices is reachable only at moments divisible by $t$. Suppose we have built such a set $S_{0}$. Look at sets $S_{1}$, $S_{2}$, ..., $S_{None}$ of all vertices reachable at moments having remainders $1$, $2$, ..., $t - 1$ modulo $t$, respectively. One can easily check that these sets are disjoint, and their union coinside with the set of all reacheble vertices. Clearly, that the edge from $u$ to $v$ can exist only when $u$ and $v$ belong to consequetive sets, i.e. $u\\in S_{k}$, $v\\in S_{k+1}$, $k + 1$ is taken modulo $t$. For each vertex $v$, find a distance $d_{v}$ from $1$ to $v$ (if there is multiple paths, choose any, for example, by dfs). If the edge exists from $u$ to $v$, it must be $d_{u}+1\\equiv d_{v}(\\mathrm{\\boldmath~\\mod~}t)$. By analyzing all the edges, we come to the conclusion that the optimal value of $t$ equals to the greatest common divisor of the numbers $|d_{u} + 1 - d_{v}|$. To find the set $S_{0}$ is not very difficult now.",
    "tags": [],
    "rating": 2500
  },
  {
    "contest_id": "39",
    "index": "J",
    "title": "Spelling Check",
    "statement": "Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?",
    "tutorial": "The simplest solution is to find two numbers $l$ and $r$ - the length of the longest common prefix and the length of the longest common suffix of two strings, respectively. If $l + 1 < n - r$ then there is no solution. Here $n$ is the length of the first string. Otherwise we should output positions from $max(n - r, 1)$ to $min(l + 1, n)$.",
    "tags": [
      "hashing",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "39",
    "index": "K",
    "title": "Testing",
    "statement": "You take part in the testing of new weapon. For the testing a polygon was created. The polygon is a rectangular field $n × m$ in size, divided into unit squares $1 × 1$ in size. The polygon contains $k$ objects, each of which is a rectangle with sides, parallel to the polygon sides and entirely occupying several unit squares. The objects don't intersect and don't touch each other.\n\nThe principle according to which the weapon works is highly secret. You only know that one can use it to strike any rectangular area whose area is not equal to zero with sides, parallel to the sides of the polygon. The area must completely cover some of the unit squares into which the polygon is divided and it must not touch the other squares. Of course the area mustn't cross the polygon border. Your task is as follows: you should hit no less than one and no more than three rectangular objects. Each object must either lay completely inside the area (in that case it is considered to be hit), or lay completely outside the area.\n\nFind the number of ways of hitting.",
    "tutorial": "Problem K has a great number of different solutions, so I'm surprised that there was a lack of them during the contest. Solutions with time $O(k^{4})$ and even some $O(k^{5})$ solutions with optimization were acceptable, but KADR describes even better solution in $O(k^{3})$ (http://codeforces.com/blog/entry/793). Here are some jury ideas of this problem. First, let us compress the coordinates. Choose a labeled point in each object and compute by the standard dynamics the number of such labels in each rectangle. It takes $O(k^{4})$ to process all possible rectangles. The problem arises that a rectangle may contain a valid number of objects, but contain some objects not completely. To prevent this, we can check the borders. They are segments parallel to the coordinate axes, and their number is $O(k^{3})$. So we can precalc for them if they are valid or not comparing them with each object. Then we have to come back to uncompressed coordinates. The following solution is $O(k^{5})$, and it uses the limitation on the number of objects (3) inside the rectangle. Process all the triples of objects (the same, of course, with pairs and single objects). Fix a triple, and change it by a single big object. Then move from the resulting object up (and then down), and check if a row above (or below) can be included in a striked rectangle. For each row we find a longest segment [l, r], which contains the current big object and doesn't contain others. Using this information, one can easily calculate the total number of rectangles that contain the current triple.",
    "tags": [],
    "rating": 2600
  },
  {
    "contest_id": "41",
    "index": "A",
    "title": "Translation",
    "statement": "The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a Berlandish word differs from a Birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, making a mistake during the \"translation\" is easy. Vasya translated the word $s$ from Berlandish into Birlandish as $t$. Help him: find out if he translated the word correctly.",
    "tutorial": "Many languages have built-in reverse() function for strings. we can reverse one of the strings and check if it's equal to the other one , or we can check it manually. I prefer the second.",
    "code": "using System;\nnamespace Iran\n{\n        class Amir\n        {\n                public static void Main()\n                {\n                        string a=Console.ReadLine();\n                        string b=Console.ReadLine();\n                        bool ok=true;\n                        if(a.Length!=b.Length)\n                                ok=false;\n                        for(int i=0;ok&&i<a.Length;++i)\n                        {\n                                if(a[i]!=b[a.Length-i-1])\n                                {\n                                        ok=false;\n                                        break;\n                                }\n                        }\n                        if(ok)\n                                Console.WriteLine(\"YES\");\n                        else\n                                Console.WriteLine(\"NO\");\n                }\n        }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "41",
    "index": "B",
    "title": "Martian Dollar",
    "statement": "One day Vasya got hold of information on the Martian dollar course in bourles for the next $n$ days. The buying prices and the selling prices for one dollar on day $i$ are the same and are equal to $a_{i}$. Vasya has $b$ bourles. He can buy a certain number of dollars and then sell it no more than once in $n$ days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day $n$?",
    "tutorial": "Since number of days is very small ($2  \\times  10^{3}$) we can just iterate over all possibilities of buy-day and sell-day. This will take $ \\theta  (n^{2})$ time which is OK.",
    "code": "using System;\nnamespace Iran\n{\n        class Amir\n        {\n                public static void Main()\n                {\n                        string[] input=Console.ReadLine().Split(' ');\n                        int n=int.Parse(input[0]);\n                        int b=int.Parse(input[1]);\n                        int maximum=b;\n                        string[] dollars=Console.ReadLine().Split(' ');\n                        for(int i=0;i<n;i++)\n                        {\n                        for(int j=i;j<n;j++)\n                        {\n                                int canbuy=b/int.Parse(dollars[i]);\n                                int more=b%int.Parse(dollars[i]);\n                                int sell=canbuy*int.Parse(dollars[j])+more;\n                                if(sell>maximum)\n                                                maximum=sell;\n                        }\n                        }\n                        Console.WriteLine(maximum);\n                }//end of main\n        }\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1400
  },
  {
    "contest_id": "41",
    "index": "C",
    "title": "Email address",
    "statement": "Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([email protected]).\n\nIt is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots.\n\nYou have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result.\n\nOverall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at.",
    "tutorial": "The first letter of the input string can not be part of an \"at\" or a \"dot\" so we start from the second character. Greedily put \".\" wherever you reached \"dot\" and put \"@\" the first time you reached \"at\". This will take $ \\theta (n)$ time , where $n$ is the length of input",
    "code": "#include <iostream>\n#include <algorithm>\nusing namespace std;\n \nint main()\n{\n        string input;\n        cin>>input;\n        string made=input.substr(0,1);\n        bool at=false;\n        for(int i=1;i<input.length();)\n        {\n                if(input.substr(i,3)==\"dot\"&&i+3!=input.length())\n                        {\n                                made=made+\".\";\n                                i+=3;\n                        }\n                else if(input.substr(i,2)==\"at\"&&at==false&&i+2!=input.length())\n                {\n                        at=true;\n                        made=made+\"@\";\n                        i+=2;\n                }\n                else\n                {\n                        made=made+input.substr(i,1);\n                        i++;\n                }\n        }\n        cout<<made<<endl;\n        return 0;\n}",
    "tags": [
      "expression parsing",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "41",
    "index": "D",
    "title": "Pawn",
    "statement": "On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its $k$ brothers, the number of peas must be divisible by $k + 1$. Find the maximal number of peas it will be able to collect and which moves it should make to do it.\n\nThe pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.",
    "tutorial": "For each cell of the table store $k + 1$ values. Where $i$th value is the maximum number of peas the pawn can take while he is at that cell and this number mod $k + 1$ is $i$. This makes a $O(n^{2}  \\times  m  \\times  k)$ dynamic programming which fits perfectly in the time.",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "41",
    "index": "E",
    "title": "3-cycles",
    "statement": "During a recent research Berland scientists found out that there were $n$ cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three cities from each of which one can get to any other one directly. That is, there was no cycle exactly as long as 3. Unfortunately, the road map has not been preserved till nowadays. Now the scientists are interested how much developed a country Ancient Berland was. Help them - find, what maximal number of roads could be in the country. You also have to restore any of the possible road maps.",
    "tutorial": "The road map with most edges is a complete bipartite graph with equal number of vertices on each side. (Prove it by yourself :D ). We can make such a graph by putting the first $\\left\\lfloor{\\frac{n}{2}}\\right\\rfloor$ vertices on one side and the other $\\textstyle\\left[{\\frac{n}{2}}\\right]$ on the other side.For sure , number of edges is $\\textstyle{\\left[{\\frac{n}{2}}\\right]}\\times\\left[{\\frac{n}{2}}\\right]$",
    "code": "#include <iostream>\nusing namespace std;\n \nint main()\n{\n        int n;\n        cin>>n;\n        if(n%2==0)\n                cout<<n/2*n/2<<endl;\n        else\n                cout<<n/2*(n+1)/2<<endl;\n        for(int i=1;i<=n/2;i++)\n                for(int j=n/2+1;j<=n;j++)\n                        cout<<i<<\" \"<<j<<endl;\n        return 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "42",
    "index": "A",
    "title": "Guilty --- to the kitchen!",
    "statement": "It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.\n\nAccording to the borscht recipe it consists of $n$ ingredients that have to be mixed in proportion $(a_{1}:a_{2}:\\dots:a_{n})$ litres (thus, there should be $a_{1} ·x, ..., a_{n} ·x$ litres of corresponding ingredients mixed for some non-negative $x$). In the kitchen Volodya found out that he has $b_{1}, ..., b_{n}$ litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a $V$ litres volume pan (which means the amount of soup cooked can be between $0$ and $V$ litres). What is the volume of borscht Volodya will cook ultimately?",
    "tutorial": "Let us reformulate the statement: we need to find the maximum possible value of x (mentioned in the statement) so that the amount of each ingredient will be enough. Clearly, such x equals min(b_i / a_i). Now it suffices to take minimum of the two values: soup volume we gained and the volume of the pan.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "42",
    "index": "B",
    "title": "Game of chess unfinished",
    "statement": "Once Volodya was at the museum and saw a regular chessboard as a museum piece. And there were only four chess pieces on it: two white rooks, a white king and a black king. \"Aha, blacks certainly didn't win!\", — Volodya said and was right for sure. And your task is to say whether whites had won or not.\n\nPieces on the chessboard are guaranteed to represent a correct position (every piece occupies one cell, no two pieces occupy the same cell and kings cannot take each other). Thus, your task is only to decide whether whites mate blacks. We would remind you that it means that the black king can be taken by one of the opponent's pieces at the moment and also it cannot move to an unbeaten position. A rook moves vertically or horizontally by any number of free cells (assuming there are no other pieces on its path), a king — to the adjacent cells (either by corner or by side). Certainly, pieces cannot leave the board. The black king might be able to take opponent's rooks at his turn (see sample 3).",
    "tutorial": "In this problem you are to check exactly what the statement says: if the king's position and all the positions reachable by him in one turn are \"beaten\", - that's a mate. Thus, we have to determine \"beaten\" positions correctly. Let us remove the black king from the chessboard, leave the positions of the rooks \"unbeaten\" (not to forget about possible taking of the rook by the black king), mark positions reachable by rooks \"beaten\" and then mark positions reachable by white king as \"beaten\".",
    "tags": [
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "42",
    "index": "C",
    "title": "Safe cracking",
    "statement": "Right now you are to solve a very, very simple problem — to crack the safe. Four positive integers stand one by one on a circle protecting the safe. You know that to unlock this striking safe you have to make all four numbers equal to one. Operations are as follows: you may choose two adjacent numbers and increase both by one; you may choose two adjacent even numbers and divide both by two. Nothing else. Crack the safe!",
    "tutorial": "The answer in this problem is always affirmative, which means it is always possible to make all the numbers equal to one. Greedy approach (here we somehow make two adjacent numbers even and then divide them by two) leads the sum of numbers to become less or equal to six in logarithmic (and certainly less than 1000) number of operations. There are several ways do deal with extremal cases: for instance, many of the participants coped with this by the analysis of all of the cases left. The greedy approach only is not sufficient: the crucial test for hacks was (1 1 1 2).",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 2200
  },
  {
    "contest_id": "42",
    "index": "D",
    "title": "Strange town",
    "statement": "Volodya has recently visited a very odd town. There are $N$ tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour — a cycle which visits every attraction exactly once — the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.",
    "tutorial": "Let us associate some numbers a_i with the vertices of the graph. If, for each edge, we assign it the sum of its endpoints' numbers, then the sum of prices along arbitrary hamiltonian cycle will be equal to the doubled sum of a_i. Therefore, it suffices us to devise such numbers a_i so that their pairwise sums will be distinct (as the edge prices should be distinct). As all of the edge prices are bounded above by 1000, we have to think of an efficient strategy to obtain such a_i. Let's choose them in greedy way, so that newly added a_i should not be equal to (a_p + a_q - a_k) for each triple of already chosen a_p, a_q, a_k. It is clear that a_n = O(n^3) as there are O(n^3) \"blocking\" triples (p, q, k). Another idea lies in that equality AB+CD=AC+BD should hold for every quadruple of distinct vertices A, B, C, D (summands stay for edge prices), because a hamiltonial cycle with edges AB and CD can be easily rearranged in the cycle with edges AC and BD and the sums of these cycles should be equal. You may think of how this idea was used by jury to check your solutions in exact and fast way.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "42",
    "index": "E",
    "title": "Baldman and the military",
    "statement": "Baldman is a warp master. He possesses a unique ability — creating wormholes! Given two positions in space, Baldman can make a wormhole which makes it possible to move between them in both directions. Unfortunately, such operation isn't free for Baldman: each created wormhole makes him lose plenty of hair from his head.\n\nBecause of such extraordinary abilities, Baldman has caught the military's attention. He has been charged with a special task. But first things first.\n\nThe military base consists of several underground objects, some of which are connected with bidirectional tunnels. There necessarily exists a path through the tunnel system between each pair of objects. Additionally, exactly two objects are connected with surface. For the purposes of security, a patrol inspects the tunnel system every day: he enters one of the objects which are connected with surface, walks the base passing each tunnel \\textbf{at least} once and leaves through one of the objects connected with surface. He can enter and leave either through the same object, or through different objects. The military management noticed that the patrol visits some of the tunnels multiple times and decided to optimize the process. Now they are faced with a problem: a system of wormholes needs to be made to allow of a patrolling which passes each tunnel \\textbf{exactly} once. At the same time a patrol is allowed to pass each wormhole any number of times.\n\nThis is where Baldman comes to operation: he is the one to plan and build the system of the wormholes. Unfortunately for him, because of strict confidentiality the military can't tell him the arrangement of tunnels. Instead, they insist that his system of portals solves the problem for any arrangement of tunnels which satisfies the given condition. Nevertheless, Baldman has some information: he knows which pairs of objects he can potentially connect and how much it would cost him (in hair). Moreover, tomorrow he will be told which objects (exactly two) are connected with surface. Of course, our hero decided not to waste any time and calculate the minimal cost of getting the job done for some pairs of objects (which he finds likely to be the ones connected with surface). Help Baldman!",
    "tutorial": "First note that a valid graph of wormholes is either connected or consists of two connectivity components with one exit in each. The proof is in the end of this text. Also note that the first option is never optimal because one edge can be removed to get the second option. Let's build a minimal spanning tree of the input graph. If it contains more than two components, the answer for each query is -1. If it contains two components, the answer is -1 if both objects are in the same component, and the weight of the spanning tree otherwise. The most interesting case is one component: we need to cut the spanning tree into two trees containing one exit each and having minimal sum of weights (not actually cut but get the sum of weights of the resulting trees). It can be done by (virtually) removing the most heavy edge on the path between the exits; so the only thing we need to know is the weight of such edge. It can be done with LCA algorithm: for each node precalculate upward jumps of height 2^k, k=0..log n, but also for each jump calculate the maximum weight of an edge on the path of this jump. Then you can split the path a-b in paths a-lca(a,b) and b-lca(a,b) and calculate the maximum weight on each of them in O(log n) using the precalculated values. Now the proof: First, it's easy to see that such graph of wormholes is valid: we can enter any exit, cross all tunnels in this component, go to another component (there is always an edge between components because tunnel graph is connected), cross all tunnels there, cross all remaining tunnels between components and leave using one of the exits. Besides these components A and B let there be another component C (and maybe some other components) and the number of tunnels between A and C is odd, between B and C - even; in this case it's impossible to traverse all tunnels once and return to A or B, so this wormhole graph is invalid. If both exits are in the same component and there is another component and the number of tunnels between them is odd, it's invalid too. So the only options left are those mentioned in the beginning.",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "43",
    "index": "A",
    "title": "Football",
    "statement": "One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are $n$ lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.",
    "tutorial": "This is pretty obvious , you can store the two strings and how many times each of them occurred",
    "tags": [
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "43",
    "index": "B",
    "title": "Letter",
    "statement": "Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading $s_{1}$ and text $s_{2}$ that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.",
    "tutorial": "For each of the upper or lower case letters , take care about how many times it appeared in each of the strings. if for a character x , repetitions of x in the second string is more than the first string , we can't make it , otherwise the answer is YES.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "43",
    "index": "C",
    "title": "Lucky Tickets",
    "statement": "Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid also threw part of the pieces away. Having seen this, Vasya got terrified but still tried to restore the collection. He chose several piece pairs and glued each pair together so that each pair formed a lucky ticket. The rest of the pieces Vasya threw away reluctantly. Thus, after the gluing of the $2t$ pieces he ended up with $t$ tickets, each of which was lucky.\n\nWhen Leonid tore the tickets in two pieces, one piece contained the first several letters of his number and the second piece contained the rest.\n\nVasya can glue every pair of pieces in any way he likes, but it is important that he gets a lucky ticket in the end. For example, pieces 123 and 99 can be glued in two ways: 12399 and 99123.\n\nWhat maximum number of tickets could Vasya get after that?",
    "tutorial": "We all know that the remainder of a number when divided by 3 is equal to the remainder of sum of its digits when divided by three. So we can put all of input numbers in 3 sets based on their remainder by 3. Those with remainder 1 can be matched with those with remainder 2 and those with remainder 0 can be matched with themselves. so the answer is:half of number of those divisible by three + minimum of those having a remainder of 1 and those having a remainder of 2",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "43",
    "index": "D",
    "title": "Journey",
    "statement": "The territory of Berland is represented by a rectangular field $n × m$ in size. The king of Berland lives in the capital, located on the upper left square $(1, 1)$. The lower right square has coordinates $(n, m)$. One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out — one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.",
    "tutorial": "Actually we're looking for an Eulerian tour. I found it like this: If at least one of m and n was even do it like this figure: else do it like this and add a teleport from last square to the first: But there were really nice hacks as I studied them. like these two: 1 10 and 1 2",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "43",
    "index": "E",
    "title": "Race",
    "statement": "Today $s$ kilometer long auto race takes place in Berland. The track is represented by a straight line as long as $s$ kilometers. There are $n$ cars taking part in the race, all of them start simultaneously at the very beginning of the track. For every car is known its behavior — the system of segments on each of which the speed of the car is constant. The $j$-th segment of the $i$-th car is pair $(v_{i, j}, t_{i, j})$, where $v_{i, j}$ is the car's speed on the whole segment in kilometers per hour and $t_{i, j}$ is for how many hours the car had been driving at that speed. The segments are given in the order in which they are \"being driven on\" by the cars.\n\nYour task is to find out how many times during the race some car managed to have a lead over another car. A lead is considered a situation when one car appears in front of another car. It is known, that all the leads happen instantly, i. e. there are no such time segment of positive length, during which some two cars drive \"together\". At one moment of time on one and the same point several leads may appear. In this case all of them should be taken individually. Meetings of cars at the start and finish are not considered to be counted as leads.",
    "tutorial": "Let's just take care about 2 cars and see how many times they change their position. This is easy. Then do this for all cars :D",
    "tags": [
      "brute force",
      "implementation",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "44",
    "index": "A",
    "title": "Indian Summer",
    "statement": "Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.",
    "tutorial": "One of possible ways of solving the problem is to compare every leave with all taken before. If it matches one of them, than do not take it. Since the order of leaves is immaterial, you can just sort all the leaves (for example, as pairs of strings) and delete unique leaves.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "44",
    "index": "B",
    "title": "Cola",
    "statement": "To celebrate the opening of the Winter Computer School the organizers decided to buy in $n$ liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles $0.5$, $1$ and $2$ liters in volume. At that, there are exactly $a$ bottles $0.5$ in volume, $b$ one-liter bottles and $c$ of two-liter ones. The organizers have enough money to buy any amount of cola. What did cause the heated arguments was how many bottles of every kind to buy, as this question is pivotal for the distribution of cola among the participants (and organizers as well).\n\nThus, while the organizers are having the argument, discussing different variants of buying cola, the Winter School can't start. Your task is to count the number of all the possible ways to buy exactly $n$ liters of cola and persuade the organizers that this number is too large, and if they keep on arguing, then the Winter Computer School will have to be organized in summer.\n\nAll the bottles of cola are considered indistinguishable, i.e. two variants of buying are different from each other only if they differ in the number of bottles of at least one kind.",
    "tutorial": "The problem is to find a number of triples (x, y, z), such that 0 <= x <= a, 0 <= y <= b, 0 <= z <= c and 0.5 * x + y + 2 * z = n. Trying all triples gets TL, but you can try all possible values of x and y, satisfying 0 <= x <= a, 0 <= y <= b. When x and y are fixed, z can be determined uniquely. So we get O(a*b) solution.",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "44",
    "index": "C",
    "title": "Holidays",
    "statement": "School holidays come in Berland. The holidays are going to continue for $n$ days. The students of school №$N$ are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.",
    "tutorial": "The easiest solution is to process all the days from 1 to n, and check for each day, that it is covered by exactly one segment $[a_{i}, b_{i}]$. If you find a day which is covered by less or more than one segment, output this day.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "44",
    "index": "D",
    "title": "Hyperdrive",
    "statement": "In a far away galaxy there are $n$ inhabited planets, numbered with numbers from $1$ to $n$. They are located at large distances from each other, that's why the communication between them was very difficult until on the planet number $1$ a hyperdrive was invented. As soon as this significant event took place, $n - 1$ spaceships were built on the planet number $1$, and those ships were sent to other planets to inform about the revolutionary invention.\n\nParadoxical thought it may be, but the hyperspace is represented as simple three-dimensional Euclidean space. The inhabited planets may be considered fixed points in it, and no two points coincide and no three points lie on the same straight line. The movement of a ship with a hyperdrive between two planets is performed along a straight line at the constant speed, the same for all the ships. That's why the distance in the hyperspace are measured in hyperyears (a ship with a hyperdrive covers a distance of $s$ hyperyears in $s$ years).\n\nWhen the ship reaches an inhabited planet, the inhabitants of the planet dissemble it, make $n - 2$ identical to it ships with a hyperdrive and send them to other $n - 2$ planets (except for the one from which the ship arrived). The time to make a new ship compared to the time in which they move from one planet to another is so small that it can be disregarded. New ships are absolutely identical to the ones sent initially: they move at the same constant speed along a straight line trajectory and, having reached a planet, perform the very same mission, i.e. are dissembled to build new $n - 2$ ships and send them to all the planets except for the one from which the ship arrived. Thus, the process of spreading the important news around the galaxy continues.\n\nHowever the hyperdrive creators hurried to spread the news about their invention so much that they didn't study completely what goes on when two ships collide in the hyperspace. If two moving ships find themselves at one point, they provoke an explosion of colossal power, leading to the destruction of the galaxy!\n\nYour task is to find the time the galaxy will continue to exist from the moment of the ships' launch from the first planet.",
    "tutorial": "Let us call ships that were produced initially ''the ships of the first generation''. When a ship of the first generation reaches a planet, and new ships are build there, we call them ''ships of the second generation'', and so on. Let us prove that the first collision is between two ships of the second generation, moving towars each other. Indeed, ships of the first generation move in distict dirrections (no three points lie on the same line), so they cannot collide. If a ship of the first generation collides with a ship of the second generation, the lines of their moving form a triangle OAC, where O is the first planet, A is a planet where the ship of the second generation has been produced, and C is a point of the collision. But it's clear that OA + AC > OC, and ships are moving with the same speed, so such collision cannot happen. Speaking about ships of the third generation, they cannot be produced at all! Suppose that a ship from the first planet has reached the planet A, and then a ship from planet A has reached the planet B. But by virtue of the triangle inequality, a ship from the first planet has reached the planet B earlier, ships were produced at B, one of them was sent to A and collide with the ship, moving from A to B. For similar reasons two ships cannot collide, if one of them is moving from A to B, and another is moving from C to D. Ships moving from A to C and from C to A will collide earlier. Thus, the solution is to compute for each pair of planets A, B a perimeter of the triangle OAB, and find the minimal one.",
    "tags": [
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "44",
    "index": "E",
    "title": "Anfisa the Monkey",
    "statement": "Anfisa the monkey learns to type. She is yet unfamiliar with the \"space\" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into $k$ lines not shorter than $a$ and not longer than $b$, for the text to resemble human speech more. Help Anfisa.",
    "tutorial": "There are multiple ways to split the string. One of them is to split it into parts of lengths n / k and n / k + 1, if n is not divisible by k. Here n is the length of the given string. If lengths of such parts are not less than a and not greater than b, the answer is found. Otherwise there is no solution.",
    "tags": [
      "dp"
    ],
    "rating": 1400
  },
  {
    "contest_id": "44",
    "index": "F",
    "title": "BerPaint",
    "statement": "Anfisa the monkey got disappointed in word processors as they aren't good enough at reflecting all the range of her emotions, that's why she decided to switch to graphics editors. Having opened the BerPaint, she saw a white rectangle $W × H$ in size which can be painted on. First Anfisa learnt to navigate the drawing tool which is used to paint segments and quickly painted on that rectangle a certain number of black-colored segments. The resulting picture didn't seem bright enough to Anfisa, that's why she turned her attention to the \"fill\" tool which is used to find a point on the rectangle to paint and choose a color, after which all the area which is the same color as the point it contains, is completely painted the chosen color. Having applied the fill several times, Anfisa expressed her emotions completely and stopped painting. Your task is by the information on the painted segments and applied fills to find out for every color the total area of the areas painted this color after all the fills.",
    "tutorial": "Imagine that all segments were drawn. We will refer to these segments as to initial segments. Lets divide the rectangle of drawing into the set of regions and segments such that there are no points of the initial segments strictly inside any region, and new segments separate the regions. Note that new set of segments can contain not only the parts of the initial segments, but also some dummy segments. Initially the color of all regions is white, while the color of each segment can be black of white (dummy segments are white). Please note that in such a partition the border of the region is not consider to belong to it. Lets build a graph where each vertice corresponds either to a region or to a segment, and add edges according to the following rules: 1) Edge between two non-dummy segments is in the graph if these segments have common end-point. 2) Edge between a region and a segment (dummy or not) is in the graph if they have more than one common point (i.e. the segment is a part of the border of the region). It is clear that every region that can be filled corresponds to some connected component of this graph. That gives us a solution. We will store a color for each vertice. When processing a filling operation, we search for all such vertices that the objects that correspond to these vertices contain the chosen point. For region, the point should lie strictly inside the region. For the dummy segment, the point should lie on it but should not coincide with it end-points. And for the non-dummy segment, the point should just lie on it. From each of the found vertices, we make a DFS or BFS which finds all vertices that are reachable from the statring vertice and have the same color, and paints them with new color. After all operations, we need to find sum of areas for such colors, that there are at least one vertice with this color. The main difficulty in the problem is to divide the rectangle into regions and segments. In my solution it is done using vertical decomposition. First, divide the rectangle into vertical stripes such that inner area of any stripe doesn't contain neiher end-points of the initial segments nor points of their intersections. Then each of these stripes is divided into trapezoid by initial segments, intersecting the stripe. Then add necessary dummy segments to separate the regions and build the graph. I think that there may be some easier ways to construct such graph.",
    "tags": [
      "geometry",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "44",
    "index": "G",
    "title": "Shooting Gallery",
    "statement": "Berland amusement park shooting gallery is rightly acknowledged as one of the best in the world. Every day the country's best shooters master their skills there and the many visitors compete in clay pigeon shooting to win decent prizes. And the head of the park has recently decided to make an online version of the shooting gallery. During the elaboration process it turned out that the program that imitates the process of shooting effectively, is needed. To formulate the requirements to the program, the shooting gallery was formally described. A 3D Cartesian system of coordinates was introduced, where the $X$ axis ran across the gallery floor along the line, along which the shooters are located, the $Y$ axis ran vertically along the gallery wall and the positive direction of the $Z$ axis matched the shooting direction. Let's call the $XOY$ plane a shooting plane and let's assume that all the bullets are out of the muzzles at the points of this area and fly parallel to the $Z$ axis. Every clay pigeon can be represented as a rectangle whose sides are parallel to $X$ and $Y$ axes, and it has a positive $z$-coordinate. The distance between a clay pigeon and the shooting plane is always different for every target. The bullet hits the target if it goes through the inner area or border of the rectangle corresponding to it. When the bullet hits the target, the target falls down vertically into the crawl-space of the shooting gallery and cannot be shot at any more. The targets are tough enough, that's why a bullet can not pierce a target all the way through and if a bullet hits a target it can't fly on. In input the simulator program is given the arrangement of all the targets and also of all the shots in the order of their appearance. The program should determine which target was hit by which shot. If you haven't guessed it yet, you are the one who is to write such a program.",
    "tutorial": "Lets solve slightly different problem: for every target we will determine the shoot that hits it. Sort the targets in increasing order of their z-coordinate and process them in that order. Each target is processed as follows. Consider all shoots that potentially can hit it. It is obvious that all such shoots belong to the rectangle, corresponding to the target. From these shoots, the earliest shoot will hit the target. We should find this shoot and remove it from the set of shoots, and then turn to the next target. It's easy to see that the following condition will be held: before we process a target, all shoots that were going to hit it but faced other targer, were already removed from the set of shoots. Now we need to implement the algorithm efficiently. We will store the shoots in some data structure. This structure should be able to answer two types of queries: 1) Find element with minimum value in the given rectangle. 2) Remove the given element. In my solution I used two-dimensional index tree to manage these queries. I won't describe what the two-dimensional index tree is. I just want to make several remarks. First, the removing operation is not as easy to implement in a two-dimensional index tree as it mays seem. But we are lucky that we have no additions, just deletions! Time complexity of the model solution is $O((N + M)log^{2}N$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "44",
    "index": "H",
    "title": "Phone Number",
    "statement": "Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy.\n\nThe phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose that Masha's phone number is $12345$. After that one should write her favorite digit from $0$ to $9$ under the first digit of her number. That will be the first digit of the needed number. For example, Masha's favorite digit is $9$. The second digit is determined as a half sum of the second digit of Masha's number and the already written down first digit from her beloved one's number. In this case the arithmetic average equals to $(2 + 9) / 2 = 5.5$. Masha can round the number up or down, depending on her wishes. For example, she chooses the digit $5$. Having written down the resulting digit under the second digit of her number, Masha moves to finding the third digit in the same way, i.e. finding the half sum the the third digit of her number and the second digit of the new number. The result is $(5 + 3) / 2 = 4$. In this case the answer is unique. Thus, every $i$-th digit is determined as an arithmetic average of the $i$-th digit of Masha's number and the $i - 1$-th digit of her true love's number. If needed, the digit can be rounded up or down. For example, Masha can get:\n\n\\[\n12345\n\\]\n\n\\[\n95444\n\\]\n\nUnfortunately, when Masha tried dialing the number, she got disappointed: as it turned out, the number was unavailable or outside the coverage area. But Masha won't give up. Perhaps, she rounded to a wrong digit or chose the first digit badly. That's why she keeps finding more and more new numbers and calling them. Count the number of numbers Masha calls. Masha calls all the possible numbers that can be found by the described means of arithmancy, except for, perhaps, her own one.",
    "tutorial": "The answer may be rather large, because it grows exponentially with growth of n, but it fits int64. Indeed, there are 10 ways to choose the first digit, than 1 or 2 ways to choose the second one, 1 or 2 ways for the third one, and so on. So the number of ways doens't exceed $10 \\cdot  2^{None}$. The problem can be solved by dynamic programming. Let $d_{ij}$ be a number of ways to get first i digits of a correct number with the i-th digit equal to j. From such part of a number we can obtain a part of size i + 1 with (i+1)-th digit equal to $(j + a_{None}) / 2$ or $(j + a_{None} + 1) / 2$, where $a_{i}$ is the i-th digit of Masha's number. So if we have $d_{ij}$ for all $j$, we can obtain $d_{None}$. Do not forget to subtract 1, if Masha can obtain her own number. It will happen in case when each two successive digits in the given number differs at most by 1.",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "44",
    "index": "I",
    "title": "Toys",
    "statement": "Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her $n$ toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still can't calm Masha down and mom is going to come home soon and punish Sasha for having made Masha crying. That's why he decides to restore the piles' arrangement. However, he doesn't remember at all the way the toys used to lie. Of course, Masha remembers it, but she can't talk yet and can only help Sasha by shouting happily when he arranges the toys in the way they used to lie. That means that Sasha will have to arrange the toys in every possible way until Masha recognizes the needed arrangement. The relative position of the piles and toys in every pile is irrelevant, that's why the two ways of arranging the toys are considered different if can be found two such toys that when arranged in the first way lie in one and the same pile and do not if arranged in the second way. Sasha is looking for the fastest way of trying all the ways because mom will come soon. With every action Sasha can take a toy from any pile and move it to any other pile (as a result a new pile may appear or the old one may disappear). Sasha wants to find the sequence of actions as a result of which all the pile arrangement variants will be tried exactly one time each. Help Sasha. As we remember, initially all the toys are located in one pile.",
    "tutorial": "In this problem we need to output all partitions of the given set into subsets in the order which is very similar to the Gray code. Lets denote each partition by a restricted growth string. For a restricted growth string $a_{1}a_{2}a_{n}$ holds that $a_{1} = 0$ and $a_{None}  \\le  1 + max(a_{1}, ..., a_{j})$ for $1  \\le  j < n$. Every partition can be encoded with such string using the following idea: $a_{i} = a_{j}$ if and only if elements $i$ and $j$ belong to the same subset in the partition. For example, string representation of the partition {1,3},{2},{4} is 0102. Now we will learn how to generate all restricted growth strings by making a change in exactly one position in the current string to get the next string. It is obvious that in terms of partitions it is what we are asked for in the problem. Rather easy way to build such list of strings was invented by Gideon Ehrlich. Imagine that we have the required list $s_{1}, s_{2}, ..., s_{k}$ for the length $n - 1$, We will obtain a list for the length $n$ from it. Lets $s_{i} = a_{1}a_{2}... a_{None}$, and $m = 1 + max(a_{1}, ..., a_{None})$. Then, if $i$ is odd, we will obtain strings of the length $n$ by appending digits $0, m, m - 1, ..., 1$ to $s_{i}$, otherwise we will append digits in order $1, ..., m - 1, m, 0$. Thus, starting from the list $0$ for $n = 1$ we will consequently get lists $00, 01$ for $n = 2$ and $000, 001, 011, 012, 010$ for $n = 3$. Ehrlich scheme is decribed in Knuth's \"The art of programming\", volume 4, fascicle 3, pages 83-84.",
    "tags": [
      "brute force",
      "combinatorics"
    ],
    "rating": 2300
  },
  {
    "contest_id": "44",
    "index": "J",
    "title": "Triminoes",
    "statement": "There are many interesting tasks on domino tilings. For example, an interesting fact is known. Let us take a standard chessboard ($8 × 8$) and cut exactly two squares out of it. It turns out that the resulting board can always be tiled using dominoes $1 × 2$, if the two cut out squares are of the same color, otherwise it is impossible.\n\nPetya grew bored with dominoes, that's why he took a chessboard (not necessarily $8 × 8$), cut some squares out of it and tries to tile it using triminoes. Triminoes are reactangles $1 × 3$ (or $3 × 1$, because triminoes can be rotated freely), also the two extreme squares of a trimino are necessarily white and the square in the middle is black. The triminoes are allowed to put on the chessboard so that their squares matched the colors of the uncut squares of the chessboard, and also the colors must match: the black squares must be matched with the black ones only and the white ones — with the white squares. The triminoes must not protrude above the chessboard or overlap each other. All the uncut squares of the board must be covered with triminoes.\n\nHelp Petya find out if it is possible to tile his board using triminos in the described way and print one of the variants of tiling.",
    "tutorial": "First, if the tiling is possible, it is unique. Consider the most upper-left position (x, y) that is not cut out. If it is black, the tiling is impossible. If it is white, look at the next position (x, y + 1). If it is cut out, the only possible way to put a trimino is to put it vertically. Otherwise we must put a trimino horisontally, because if we put it vertically, we wouldn't be able to cover the next black position (x, y + 1). These considerations give us an algorithm for the solution. Four symbols a, b, c, d are always enough to represent the tiling, because a trimino can have common sides with no more than 3 triminoes located to the left or above it. So even if all the 3 triminoes are marked by 3 different symbols, the next one may be marked by the 4-th one.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "46",
    "index": "A",
    "title": "Ball Game",
    "statement": "A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.\n\nThe game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from $1$ to $n$ clockwise and the child number $1$ is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number $2$. Then the child number $2$ throws the ball to the next but one child, i.e. to the child number $4$, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number $7$, then the ball is thrown to the child who stands $3$ children away from the child number $7$, then the ball is thrown to the child who stands $4$ children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if $n = 5$, then after the third throw the child number $2$ has the ball again. Overall, $n - 1$ throws are made, and the game ends.\n\nThe problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.",
    "tutorial": "The solution of the problem based on modeling of the decribed process. It is important to perform a pass throw the beginning correctly. You can take the current number modulo n (and add 1), or you can subtract n every time the current number increases n.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "46",
    "index": "B",
    "title": "T-shirts from Sponsor",
    "statement": "One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of $K$ participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.",
    "tutorial": "Enumerate sizes of t-shirts by integers from 0 to 4. For each size we store the number of t-shirts of this size left. To process each participant, we need to determine the number of his preferable size. Then we iterate over all possible sizes and choose the most suitable one (with the nearest number) among the sizes with non-zero number of t-shirts left.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "46",
    "index": "C",
    "title": "Hamsters and Tigers",
    "statement": "Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.",
    "tutorial": "First of all, count the number of hamsters in the sequence. Let it is h. Try positions where the sequence of hamsters will start, and for each position count the number of tigers in the segment of length h starting from the fixed position. These tigers should be swapped with hamsters in a number of swaps equal to the number of tigers not in proper places. Choose minimum among all starting posotions.",
    "tags": [
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "46",
    "index": "D",
    "title": "Parking Lot",
    "statement": "Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as $L$ meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than $b$ meters and the distance between his car and the one in front of his will be no less than $f$ meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point $L$. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.",
    "tutorial": "Lets keep a set of cars which are currently parked. In this problem it is not essential how to keep this set. For each car, store its length and position. To process a request of type 2, we need to find the car which should leave the parking and remove it from the set. To do this, we should enumerate the cars and get the car number by the number of request. Now consider a request of type 1. As the drives tries to park his car as close to the beginning of the parking slot as possible, we can reduce the set of reasonable positions for parking: include into this set the beginning of the parking and all positions that are exactly $b$ meters after the front of some car. For every position in this set we should determine if it is possible to park car in it. Then we choose the closest to the beginning position among admissible ones.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "46",
    "index": "E",
    "title": "Comb",
    "statement": "Having endured all the hardships, Lara Croft finally found herself in a room with treasures. To her surprise she didn't find golden mountains there. Lara looked around and noticed on the floor a painted table $n × m$ panels in size with integers written on the panels. There also was a huge number of stones lying by the wall. On the pillar near the table Lara found a guidance note which said that to get hold of the treasures one has to choose some non-zero number of the first panels in each row of the table and put stones on all those panels to push them down. After that she will receive a number of golden coins equal to the sum of numbers written on the chosen panels. Lara quickly made up her mind on how to arrange the stones and was about to start when she noticed an addition to the note in small font below. According to the addition, for the room ceiling not to crush and smash the adventurer, the chosen panels should form a comb. It was explained that the chosen panels form a comb when the sequence $c_{1}, c_{2}, ..., c_{n}$ made from the quantities of panels chosen in each table line satisfies the following property: $c_{1} > c_{2} < c_{3} > c_{4} < ...$, i.e. the inequation mark interchanges between the neighboring elements. Now Lara is bewildered and doesn't know what to do. Help her to determine the largest number of coins she can get and survive at the same time.",
    "tutorial": "Denote the input matrix by $a$. Compute the partial sums in each row first: $s_{i,j}=\\sum_{k=1}^{J}a_{i,k}$. All these sums can be easily computed in $O(nm)$. Then solve the task using dynamic programming. By $d_{None}$ denote the maximum sum of numbers that we can take from first $i$ rows, taking exactly $j$ numbers in row $i$ and not violating the \"comb\" condition. Starting values are obvious $d_{None} = s_{None}$. Transitions for $i > 1$ looks like this: 1) If $i$ is even, $d_{i,j}=s_{i,j}+\\operatorname*{max}_{k=j+1,m}d_{i-1,k}$. 2) If $i$ is odd, $d_{i,j}=s_{i,j}+\\operatorname*{max}_{k=1,j-1}d_{i-1,k}$. Straightforward computing of values $d_{None}$ by these formulas has complexity $O(nm^{2})$, which is not suitable. Use the following fact: if we compute values $d_{None}$ in order of decreasing $j$ in case of even $i$ and in order of increasing $j$ in case of odd $i$, the maximum values of $d_{None}$ from the previous row can be computed in $O(1)$, using value for previous $j$, i.e. without making a cycle for computation. This solution has complexity $O(nm)$ and passes all tests.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "46",
    "index": "F",
    "title": "Hercule Poirot Problem",
    "statement": "Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books.\n\nYou are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has $n$ rooms and $m$ doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could\n\n- open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side);\n- move freely from a room to a room if a corresponding door is open;\n- give keys to one another, being in one room.\n\n\"Little grey matter\" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.",
    "tutorial": "First, note that all the described operations are invertible: opening/closing doors, moving from one room to another and exchanging keys. So we may perform such operations from the initial arrangement to get some arrangment A, and then perform some operations from the final arrangement to get the same arrangement A, in this case the answer is \"YES\". Let apply the following strategy to both arrangements: while there is a person who can go to some room and open some door, perform this action. As a result from each arrangement we obtain subsets of connected rooms (we call them connected parts of the house), corresponding subsets of people and corresponding subset of keys in each connected part of the house. If these resulting subsets coincide for the initial and the final arrangement, then the answer is \"YES\", otherwise the answer is \"NO\". Indeed, if they coincide, it is obvious that we can get from the initial arrangement to the resulting arrangement, and then - to the final arrangement. Otherwise it is impossible, because there exist some keys that cannot be applied to the corresponding doors, because they are in another connected part of the house, or there exist people, who have no way to get to rooms in another connected part of the house. Second, a few words about implementation. One of possible ways is to have two boolean matrices: 1) saying for each person if he/she could get to each room and 2) saying for each key the same, and then recursively implement operations:1) if a person can get to a room, try to get to neirbouring rooms, 2) the same for keys, but also trying to open a door to the neirbouring room,3) if the door opens, people and keys in the incident rooms are assigned to another room. So we try each pair person-room, person-door, key-door, key-room for O(1) times, and the total asymptotics is $O(nk + km + m^{2} + nm)$.",
    "tags": [
      "dsu",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "46",
    "index": "G",
    "title": "Emperor's Problem",
    "statement": "It happened at the times of the Great Berland Empire. Once the Emperor dreamt that the Messenger from the gods ordered to build a temple whose base would be a convex polygon with $n$ angles. Next morning the Emperor gave the command to build a temple whose base was a regular polygon with $n$ angles. The temple was built but soon the Empire was shaken with disasters and crop failures. After an earthquake destroyed the temple, the Emperor understood that he somehow caused the wrath of gods to fall on his people. He ordered to bring the wise man. When the wise man appeared, the Emperor retold the dream to him and asked \"Oh the wisest among the wisest, tell me how could I have infuriated the Gods?\". \"My Lord,\" the wise man answered. \"As far as I can judge, the gods are angry because you were too haste to fulfill their order and didn't listen to the end of the message\".\n\nIndeed, on the following night the Messenger appeared again. He reproached the Emperor for having chosen an imperfect shape for the temple. \"But what shape can be more perfect than a regular polygon!?\" cried the Emperor in his dream. To that the Messenger gave a complete and thorough reply.\n\n- All the vertices of the polygon should be positioned in the lattice points.\n- All the lengths of its sides should be different.\n- From the possible range of such polygons a polygon which maximum side is minimal possible must be chosen.\n\nYou are an obedient architect who is going to make the temple's plan. Note that the polygon should be simple (having a border without self-intersections and overlapping) and convex, however, it is acceptable for three consecutive vertices to lie on the same line.",
    "tutorial": "Note that the lengths of the sides can be $\\sqrt{1}$, ${\\sqrt{2}}$, ${\\sqrt{4}}$, $\\sqrt{5}$, and so on, i.e. the roots of integers, that can be represented as $a^{2} + b^{2}$. Generate a proper quantity of such numbers. Denote them $\\sqrt{r_{1}}$, ${\\sqrt{r}}_{2}$, ... In some cases we can take first $n$ such numbers as lengths of sides, but in some cases we surely cannot. It depends on the parity. If the sum $r_{1} + r_{2} + ... + r_{n}$ is odd, it is impossible. Indeed, we canrepresent each side by vector $(x_{i}, y_{i})$, $x_{i}^{2} + y_{i}^{2} = r_{i}$ ($x_{i}$ and $y_{i}$ may be negative). If $r_{i}$ is even, then $x_{i} + y_{i}$ is even too. If $r_{i}$ is odd, then $x_{i} + y_{i}$ is odd. If we form a polygon with vectors of the sides $(x_{i}, y_{i})$, then $x_{1} + x_{2} + ... + x_{n} = 0$ and $y_{1} + y_{2} + ... + y_{n} = 0$, so the total sum $x_{1} + ... + x_{n} + y_{1} + ... + y_{n}$ must be even! But if $r_{1} + ... + r_{n}$ is odd, it is odd too, so to build a polygon is impossible. Let us take $r_{1}$, ..., $r_{n}$ if their sum is even, and otherwise take $r_{1}$, ..., $r_{None}$ and throw away one of them to make the sum even (in my solution I throw away the greatest such number). For each $r_{i}$ choose non-negative $x_{i}$ and $y_{i}$, $x_{i}^{2} + y_{i}^{2} = r_{i}$. In general case there are 8 possible orientations of a vector: $(x_{i}, y_{i})$, $( - x_{i}, y_{i})$, $(x_{i}, - y_{i})$, $( - x_{i}, - y_{i})$, $(y_{i}, x_{i})$, $( - y_{i}, x_{i})$, $(y_{i}, - x_{i})$, $( - y_{i}, - x_{i})$. The current subtask is to find such orientation for each vector that their sum is zero. It can be done by the greedy algorithm. Let's take the vectors from the longest ones. We will calculate current vector sum that is initially (0, 0), and it will be updated by each new taken vector. At each step choose such orientation that the current vector with that orientation minimizes the current sum (by its length) being added to it. Then, when the vectors are oriented, sort them by polar angle and apply them consequently to get a convex polygon. The described algorithm finds a required polygon for all possible tests.",
    "tags": [
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "47",
    "index": "A",
    "title": "Triangular numbers",
    "statement": "A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The $n$-th triangular number is the number of dots in a triangle with $n$ dots on a side. $T_{n}={\\frac{n(n+1)}{2}}$. You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number).\n\nYour task is to find out if a given integer is a triangular number.",
    "tutorial": "Because of small constraints, just iterate $n$ from 1 to $T_{n}$ and check $T_{n}={\\frac{n(n+1)}{2}}$",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "47",
    "index": "B",
    "title": "Coins",
    "statement": "One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.",
    "tutorial": "Let's consider a graph, where the letters $A$, $B$, $C$ are the vertexes and if $x < y$, then the edge $y - > x$ exists. After that let's perform topological sort. If a cycle was found during this operation, put \"Impossible\" and exit. Otherwise put the answer. Another approach is acceptable because of small constaints (by Connector in russian comments). Just iterate over all of $3!$ permutaioins of the letters and check if they are sorted. If no such permutation, put \"Impossible\"",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "47",
    "index": "C",
    "title": "Crossword",
    "statement": "Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular \"eight\" or infinity sign, not necessarily symmetrical.\n\nThe top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.\n\nHelp Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.",
    "tutorial": "Let's iterate over all of $6! = 720$ permutations. For every permutation let's try to put the first 3 words horizontally, the others - vertically: hor[0], ver[0] - left-up hor[2], ver[2] - right-down hor[1]: (len(ver[0]) - 1, 0)ver[1]: (0, len(hor[0]) - 1) Now let's define N = len(ver[1]), M = len(hor[1]). A Conditions for the solution existence len(hor[0]) + len(hor[2]) == M + 1 // edges of \"eight\" len(ver[0]) + len(ver[2]) == N + 1 // edges of \"eight\" len(hor[0]) >= 3 && len(hor[2]) >= 3 && len(ver[0]) >= 3 && len(ver[2]) >= 3 // \"eight\" is nondegenerateThe letters at start/end of appropriate strings are matchThe letters on the intersection of hor[1], ver[1] are match Now we have the right field of the size N x M, and update the answer Note In C++ if you use vector<vector<char> > or vector<string> as the field type, then you can simply use operator \"<\" for updating.",
    "tags": [
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "47",
    "index": "D",
    "title": "Safe",
    "statement": "Vasya tries to break in a safe. He knows that a code consists of $n$ numbers, and every number is a 0 or a 1. Vasya has made $m$ attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.",
    "tutorial": "Let's consider not the most efficient, but AC algorithm, with the complexity $O(mC_{n}^{5}log(C_{n}^{5}))$. Let's consider the 1 answer of the system: <number, v>. The amount of the variants of the password is $C_{n}^{v}$ - not very large number in constaints of the problem, you can simply generate this variants. Declare this set of variants as current. Now, for the every answer let's generate a set of possible passwords, and let's declare the intersection of this set and current set as current. After $m$ iterations we'll have some set. Then we'll erase elements from this set, which were in the answers of the system, and the answer of the problem will be the size of this set.",
    "tags": [
      "brute force"
    ],
    "rating": 2200
  },
  {
    "contest_id": "47",
    "index": "E",
    "title": "Cannon",
    "statement": "Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the $Ox$ axis is directed rightwards in the city's direction, the $Oy$ axis is directed upwards (to the sky). The cannon will make $n$ more shots. The cannon balls' initial speeds are the same in all the shots and are equal to $V$, so that every shot is characterized by only one number $alpha_{i}$ which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed $45$ angles ($π / 4$). We disregard the cannon sizes and consider the firing made from the point $(0, 0)$.\n\nThe balls fly according to the known physical laws of a body thrown towards the horizon at an angle:\n\n\\[\nv_{x}(t) = V·cos(alpha)\n\\]\n\n\\[\nv_{y}(t) = V·sin(alpha)  –  g·t\n\\]\n\n\\[\nx(t) = V·cos(alpha)·t\n\\]\n\n\\[\ny(t) = V·sin(alpha)·t  –  g·t^{2} / 2\n\\]\n\nThink of the acceleration of gravity $g$ as equal to $9.8$.\n\nBertown defends $m$ walls. The $i$-th wall is represented as a vertical segment $(x_{i}, 0) - (x_{i}, y_{i})$. When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground ($y = 0$) and stops. If the ball exactly hits the point $(x_{i}, y_{i})$, it is considered stuck.\n\nYour task is to find for each ball the coordinates of the point where it will be located in the end.",
    "tutorial": "Let's consider an algorightm with complexity $O((n + m)log(n + m))$. Exclude from considiration every wall can't be achieved by canon: $x > v^{2} / g$ Because of $ \\alpha  < = \\pi  / 4$: Function $X_{max}( \\alpha )$ is monotonous Function $Y( \\alpha , x)$, when x is fixed, is monotonousSuch observation allows to assign to each wall a section of the attack angle $[ \\alpha 1,  \\alpha 2]$. If this canon shoots with angle within this section, it hits the wall. These angles can be obtained by solving equation (it will be biquadratic), but because of monotonous we can use binary search. Sort walls by $x$. Now the initial problem has reduced to the problem: for every shoot it is need to obtain minimal index of the wall, when shoot angle is between attack angles for this wall. This problem can be solved by Segment Tree for Minimum with possibility to update on an interval. At first, fill tree with KInf. Next, for every wall let's perform update($ \\alpha 1$, $ \\alpha 2$, index). Then let's iterate over requests. If getMin($ \\alpha $) == KInf, then missle do not hit any wall and hit the land, otherwise it hit the wall with index getMin($ \\alpha $).",
    "tags": [
      "data structures",
      "geometry",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "50",
    "index": "A",
    "title": "Domino piling",
    "statement": "You are given a rectangular board of $M × N$ squares. Also you are given an unlimited number of standard domino pieces of $2 × 1$ squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:\n\n1. Each domino completely covers two squares.\n\n2. No two dominoes overlap.\n\n3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.\n\nFind the maximum number of dominoes, which can be placed under these restrictions.",
    "tutorial": "Answer is floor(N*M*0.5). Since there is N*M cells on the board and each domino covers exactly two of them we cannot place more for sure. Now let's show how to place exactly this number of dominoes. If N is even, then place M rows of N/2 dominoes and cover the whole board. Else N is odd, so cover N-1 row of the board as shown above and put floor(M/2) dominoes to the last row. In the worst case (N and M are odd) one cell remains uncovered.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "50",
    "index": "B",
    "title": "Choosing Symbol Pairs",
    "statement": "There is a given string $S$ consisting of $N$ symbols. Your task is to find the number of ordered pairs of integers $i$ and $j$ such that\n\n1. $1 ≤ i, j ≤ N$\n\n2. $S[i] = S[j]$, that is the $i$-th symbol of string $S$ is equal to the $j$-th.",
    "tutorial": "Of course you were expected to code solution which is not quadratic in time complexity. Iterate over the string and count how many times each char is used. Let Ki be the number of occurrences of char with ASCII-code i in the string S. Then answer is sum(Ki2). While coding the solution the following common mistakes were made: 1. Code quadratic solution (double loop over the string) 2. Forget to use int64. Whether in answer or in Ki squaring. 3. Wrong int64 output. All these problems were easily hacked by max test with 100000 equal chars. This turned the hacking process into the game \"who hacks the next B solution faster\" because newbies often made all these mistakes. This problem was severed by the fact that GCC-compiler turned out to be MinGW-compiler, so output like printf(\"%lld\", ...) did not work on it. Another strange problem hackers faced was quiet test truncation by length about 30000 when copy/pasting it into the test editor. Of course the overflow in solution disappears after it.",
    "tags": [
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "50",
    "index": "C",
    "title": "Happy Farm 5",
    "statement": "The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.\n\nFor that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.\n\nThe new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to $1$, and the length of a diagonal step is equal to ${\\sqrt{2}}$. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.",
    "tutorial": "You were asked to make all the cows strictly inside the interior of the route. Initially I planned to put \"non-strict\" there, but later I abandoned this idea because the answer for single point was really weird then=) The difference in solution is quite small. The answer for \"strict\" problem is always more than for \"non-strict\" by exactly 4. Some coders preferred to add four neighboring points for each point like a cross to switch to solving non-strict problem. The non-strict problem is solved in the following way. Notice that the required route can always be searched as an octagon, perhaps with some zero sides. Take four pairs of parallel lines and \"press\" it to the points. In other words, we find axis-aligned bounding box for the set of points. Then find axis-aligned bounding box of the point set on the picture which is rotated by 45 degrees. Now intersect these two boxes (as filled figures). We get an octagon in the common case, which is the required one. To implement the solution, we have to calculate minimums and maximums of X, Y, X+Y, X-Y through all the points, then use non-trivial formulas to get the answer. A lot of contestants solved the problem in other way. It is easy to see that to move by vector (X, Y) shepherd needs to make max(|X|, |Y|) turns. We can make the shepherd walk along the vertices of convex hull. We need to run a standard Graham scan and then iterate through all the points on the hull and sum max(|X'-X|, |Y'-Y|) for all pairs of neighboring vertices in it. This solution is also correct. There was an idea to make limit on coordinates equal to 109, but we decided that there was no need to ask for int64 again. Perhaps it'd have been better if there'd been int64 in this problem instead of problem B.",
    "tags": [
      "geometry"
    ],
    "rating": 2000
  },
  {
    "contest_id": "50",
    "index": "D",
    "title": "Bombing",
    "statement": "The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used.\n\nThe enemy has $N$ strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least $K$ important objects of the enemy. The bombing impact point is already determined and has coordinates of $[X_{0}; Y_{0}]$.\n\nThe nuclear warhead is marked by the estimated impact radius $R ≥ 0$. All the buildings that are located closer than $R$ to the bombing epicentre will be destroyed. All the buildings that are located further than $R$ from the epicentre, can also be deactivated with some degree of probability. Let's assume that $D$ is the distance between a building and the epicentre. This building's deactivation probability $P(D, R)$ is calculated according to the following formula:\n\n\\[\nP(D,R)=\\left\\{_{\\mathrm{exp}}\\left(1-{\\frac{D^{2}}{R^{2}}}\\right)\\begin{array}{c}{{;}}\\end{array}\\right.\\stackrel{\\ldots}{D\\le R}\n\\]\n\nWe should regard $\\exp(a)$ as $e^{a}$, where $e ≈ 2.7182818284590452353602874713527$If the estimated impact radius of the warhead is equal to zero, then all the buildings located in the impact point will be completely demolished and all the rest of important objects will not be damaged.\n\nThe commanding officers want the probability of failing the task to be no more than $ε$. Nuclear warheads are too expensive a luxury, that's why you have to minimise the estimated impact radius of the warhead.",
    "tutorial": "The problem statement looks intricate and aggressive. That's because the problem legend originates from civil defense classes in the university. Civil defense is such a discipline which for example teaches how to behave before and after nuclear attack... First of all we should notice that the bigger the warhead, the better (I mean the probability to succeed is higher). This seems quite reasonable. Function P(D, R) increases as R increases with fixed D. Obviously the probability to hit at least K objects increases in this case too. Hence we can find the answer by binary search. We have to be able to find the probability to accomplish the mission with fixed and known radius R to perform binary search. Now we have to solve the problem: there are N objects, each of them is destroyed with given probability (pi). Find the probability to destroy at least K of them. The problem is solved by dynamic programming which is similar to calculating binomial coefficients using Pascal's triangle. Let R[i, j] be the probability to hit exactly j objects among the first i of all the given ones. If we find all the R values for 0<=j<=i<=N, then the answer is calculated as sum_{j=k..N} R[N, j]. The base of DP is: R[0, 0] = 1. Induction (calculating the new values) is given by the formula R[i, j] = R[i-1, j-1] * pi + R[i-1, j] * (1-pi). Keep in mind that for j<0 or j>i all the elements of R are zeroes. It was shown experimentally that many coders (me included) try to solve the problem by taking into account only the closest K targets. I.e. they think that the probability to succeed is simply p1 * p2 *... * pK. This is wrong: for example, if two buildings with equal distance are given, then the probability to hit at least one of them is 1-(1-p)2 instead of p. But I decided to please these coders and composed the pretests only of the cases on which this solution passes=) So this particular incorrect solution was passing all the pretests intentionally.",
    "tags": [
      "binary search",
      "dp",
      "probabilities"
    ],
    "rating": 2100
  },
  {
    "contest_id": "50",
    "index": "E",
    "title": "Square Equation Roots",
    "statement": "A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple:\n\n\\[\nx^{2} + 2bx + c = 0\n\\]\n\nwhere $b$, $c$ are natural numbers.Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover it turned out that several different square equations can have a common root.\n\nPetya is interested in how many different real roots have all the equations of the type described above for all the possible pairs of numbers $b$ and $c$ such that $1 ≤ b ≤ n$, $1 ≤ c ≤ m$. Help Petya find that number.",
    "tutorial": "Let D = b2-c be quarter of discriminant. The equation roots are -b-sqrt(D) and -b+sqrt(D). Thus there are two types of roots: irrational ones like x +- sqrt(y) and integer ones. We count the number of different roots separately for these types. Irrational roots are in form x+sqrt(y) (y is not square of integer). If two numbers in this form are equal, then their x and y values are also equal. It can be checked on the piece of paper. The main idea is to use irrationality of sqrt(y). Thus if two irrational roots are equal, then the equations are the same. Hence all the irrational roots of all the given equations are different. Let's iterate b=1..N. For each of b values we have to find the number of equations with positive discriminant which are not squares on integers. I.e. number of c=1...M with D = b2-c is not square of integer. We can calculate set of all possible values of D as a segment [L; R] (L >= 0). Then take its size (R-L+1) and subtract number of squares in it. It is exactly the the number of equations with irrational roots for a fixed b. Multiply it by 2 (two roots per equation) and add it to the answer. Now let's handle integer roots. For a fixed b we've calculated the segment [L;R] of all D values. Then sqrt(D) takes integer values in segment [l; r] = [ceil(sqrt(L)); floor(sqrt(R))]. We put this segment into the formula for equation roots and understand that all the integer roots of equations with fixed b compose segments [-b-r;-b-l] and [-b+l;-b+r]. However the integer roots may substantially be equal for different equations. That's why we have to mark in a global data structure that all the roots in these two segments are \"found\". After we iterate through all b=1..N, we have to find number of integers marked at least once in this data structure. This data structure is implemented on array. All the integer roots of equations lie in bounds from -10000000 to 0. Allocate an array Q which is a bit larger in size. To mark segment [s; t] we increment Q[s] by one and decrement Q[t+1] by one. At the end of the solution iterate through the whole array Q from left to right and calculate prefix sums to array S. I.e. S[i] = Q[-10000010] + Q[-10000009] + ... + Q[i-1] + Q[i]. Then S[i] represents number of times we've marked number i. Now iterate through S array and count number of nonzero elements. It is the number of different integer roots. The solution requires O(N) time since we have to iterate through all b values. It is likely that purely combinatoric (O(1)) formula for answer exists=)",
    "tags": [
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "53",
    "index": "A",
    "title": "Autocomplete",
    "statement": "Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of $n$ last visited by the user pages and the inputted part $s$ are known. Your task is to complete $s$ to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix $s$.",
    "tutorial": "In this problem you should read the statement and solve in any way. One of the most simple solutions is read string and last visited pages, sort (even bubble source - 1003 isn't a lot, 3rd power because we need 100 operations to compare two strings), and rundown pages. When we find good string, we should write it and exit. If there are no such one, write source string. 'Goodness' of string is checking with one if (to check lengths and avoid RTE) and for.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "53",
    "index": "B",
    "title": "Blog Photo",
    "statement": "One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the $height / width$ quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 ($2^{x}$ for some integer $x$). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.",
    "tutorial": "The first thing we need to do is fix one side (which are power of two). Because there are two sides and copy-paste is great place for bugs it'll be better to make one more for from 1 to 2 and on the 2nd step swap w and h. It decreases amount of code. Now we know that h=2x. We need to find such w, that 0.8 <= h/w <= 1.25. Solve inequalities for w: h/1.25 <= w <= h/0.8. Because w is integer, it can take any value from ceil(h/1.25) to floor(h/0.8) inclusive. We need to maximize square and h is fixed, so our target is maximize w. We need to let w=floor(h/0.8) and check that it fit borders. If so - relax the answer. It's O(log2 h) solution. Possible bugs are: You calculate square in 32-bit type or like this: int w = ..., h = ...; long long s = w * h; In this case compiler calculate w * h in 32-bit type first, and then convert it to long long. Solution is long long s = (long long)w * h floor(0.9999999999)=0. The floor function does not correspond with inaccuracy of floating point types. It can be solved either with adding something eps to number before calling floor, or with additional check that difference between floor's result and source value is not greater than 1 - eps. p.s. The floor function is up to 8-9 times slower that conversion to int.",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "53",
    "index": "C",
    "title": "Little Frog",
    "statement": "Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are $n$ mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.",
    "tutorial": "IMHO it's the second difficulty problem. If you cannot see solution just after you saw the statement, you can write brute-force solution (rundown all permutation and check), run it for n=10 and see beautiful answer. Answer is 1 n 2 (n-1) 3 (n-2) 4 (n-3) ... Let's define two pointers - l and r. In the beginning, the first one will point to 1, and the second one - to n. On odd positions write down l (and increase it), on even - r (and decrease it). Do it while l <= r. Proof is rather easy: every jump is shorter than the previous one.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1200
  },
  {
    "contest_id": "53",
    "index": "D",
    "title": "Physical Education",
    "statement": "Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the height of the $i$-th student in the line and $n$ is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: $b_{1}, b_{2}, ..., b_{n}$, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: $a_{1}, a_{2}, ..., a_{n}$. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.",
    "tutorial": "This problem is also very easy. The first thing we should learn is moving element from position x to position y (y < x). Let's move x to position x - 1 with one oblivious swap. Then to position x -2. And so on. Now we want to make a1=b1. Find in b element, that equals a1 and move it to the first position. Similarly we can make a2=b2. So, we have n steps and at every step we do n - 1 swaps at the most. n<=300, so n(n-1)<=89700<106.",
    "tags": [
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "53",
    "index": "E",
    "title": "Dead Ends",
    "statement": "Life in Bertown has become hard. The city has too many roads and the government spends too much to maintain them. There are $n$ junctions and $m$ two way roads, at which one can get from each junction to any other one. The mayor wants to close some roads so that the number of roads left totaled to $n - 1$ roads and it were still possible to get from each junction to any other one. Besides, the mayor is concerned with the number of dead ends which are the junctions from which only one road goes. There shouldn't be too many or too few junctions. Having discussed the problem, the mayor and his assistants decided that after the roads are closed, the road map should contain exactly $k$ dead ends. Your task is to count the number of different ways of closing the roads at which the following conditions are met:\n\n- There are exactly $n - 1$ roads left.\n- It is possible to get from each junction to any other one.\n- There are exactly $k$ dead ends on the resulting map.\n\nTwo ways are considered different if there is a road that is closed in the first way, and is open in the second one.",
    "tutorial": "The first thing you should notice - - n <= 10. It means, that we have exponential solution and we can rundown some subsets. Solution is dynamic programming d[m][subm] - number of ways to make connected tree from subgraph m (it's a bit mask) with dead ends subm (it's also a bit mask). Answer is sum of d[2n-1][x], where |x|=k (size of x as a subset is k). Recalculating isn't really hard. For empty subset and subset of two vertexes (either 0 or 1) answer is oblivious. Also you should know that there is no tree with exactly one dead end (it's easy to prove). Now for greater subsets: rundown i from subm - one of dead ends. Cut it off from tree along some edge to b (b shouldn't be a dead end, otherwise we got unconnected graph). Now we have tree with lower count of vertexes and either decreased 1 number of dead ends or with changed i to b (if b had exactly two neighbors). Answer for this tree we know already. In the end of summarizing we should divide answer by k - each tree has been taken as many times, as it has dead ends (k).",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "54",
    "index": "C",
    "title": "First Digit Law",
    "statement": "In the probability theory the following paradox called Benford's law is known: \"In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit\" (that's the simplest form of the law).\n\nHaving read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are $N$ random variables, the $i$-th of which can take any integer value from some segment $[L_{i};R_{i}]$ (all numbers from this segment are equiprobable). It means that the value of the $i$-th quantity can be equal to any integer number from a given interval $[L_{i};R_{i}]$ with probability $1 / (R_{i} - L_{i} + 1)$.\n\nThe Hedgehog wants to know the probability of the event that the first digits of at least $K%$ of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD — most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least $K$ per cent of those $N$ values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one.",
    "tutorial": "Solution for this problem consists of two stages. First stage - counting the numbers with 1 as their first digit in the $[L;R]$ segment. Second stage - using this information (in fact, by given probabilities that $i$-th quantity will be good) solve the problem about $K$ percents. To solve the first sub-problem one can generate all segments of good numbers and look how many numbers from them lie in the $[L;R]$ segment. Segments of good numbers are of form $[1;1]$, $[10;19]$, $[100;199]$ and so on, that is, $[10^{i};2 \\cdot  10^{i} - 1]$. After noticing that, calculating their intersection with $[L;R]$ segment is quite easy. So, we've learnt how to calculate the probability $p[i]$ that $i$-th quantity is correct: this probability $p[i]$ equals to a fraction of the number of good numbers and $R[i] - L[i] + 1$. Now we can go to the second stage of the solution: solving the problem with $N$ quantities and $K$ percents. Now we know the probabilities $p[i]$ that this or that quantity is good, and want to find the probability that $K$ percents of them will be good. This can be done using dynamic programming: let's $D[i][j]$ - probability that among first $i$ quantities exactly $j$ will be good. The starting state is $D[0][0] = 1$, and calculation of other states can be done as following: $D[i][j] = p[i - 1] \\cdot  D[i - 1][j - 1] + (1 - p[i - 1]) \\cdot  D[i - 1][j].$ After that answer to the problem will be a sum of $D[n][j]$ over all $j$ such, that $j / n  \\ge  k / 100$.",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2000
  },
  {
    "contest_id": "54",
    "index": "D",
    "title": "Writing a Song",
    "statement": "One of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names.\n\nThe friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name will be repeated many times. But try as he might, he can't write a decent song!\n\nThe problem is that the Hedgehog has already decided how long the resulting sentence should be (i.e. how many letters it should contain) and in which positions in the sentence the friend's name should occur, and it must not occur in any other position in the sentence. Besides, the Hedgehog decided to limit himself to using only the first $K$ letters of an English alphabet in this sentence (so it will be not even a sentence, but one long word).\n\nThe resulting problem is indeed quite complicated, that's why the Hedgehog asks you to help him and write a program that will make the desired word by the given name $P$, the length $N$ of the required word, the given positions of the occurrences of the name $P$ in the desired word and the alphabet's size $K$. Note that the occurrences of the name can overlap with each other.",
    "tutorial": "I'll describe here an author's solution for this problem. The solution is by a method of dynamic programming: the state is a pair $(pos, pref)$, where $pos$ - the position in the string built (it is between $0$ and $n$), and $pref$ - the current prefix of pattern $P$ (i.e. this is a number between $0$ and $length(P)$). The value $pref$ will help us to control all occurences of pattern $P$: if $pref = length(P)$ then it means that here is an ending of occurence of pattern $P$ (the beginning of the occurence was at $pos - length(P)$). The value $D[pos][pref]$ of the dynamic is $true$, if the state is reachable. We start from the state $(0, 0)$ and want to get to any state with $pos = n$. How to make moves in the dynamic? We iterate over all possible characters $C$ and try to add it to the current answer. That's why we get into a stage $(pos + 1, newpref)$, where $newpref$ is a new length of prefix of $P$. The problem constraints permitted to calculate this value $newpref$ easily, i.e. just by searching for substrings of form $P[length(P) - oldpref..length(P)] + C$ in the pattern $P$. For example, if $P = ab$ and $pref = 1$, then with the character $C = a$ we will get into $newpref = 1$ (because we added character $a$ to the string $a$, - we got string $aa$, but its longest suffix matching with the prefix of string $P$ equals to $a$). If we took $C = b$ then we would get into state $newpref = 2$. Any other character would move us into the state with $newprefix = 0$. But in reality, of course, an algorithm for calculating prefix-function can be guessed here. Really, in fact, we answer the following query: \"we had some prefix of pattern $P$ and added character $C$ by its end - so what will be the new prefix?\". These queries are answered exactly by prefix-function algorithm. Moreover, we can pre-calculate answers to all of these queries in some table and get answers for them in $O(1)$ from the table. This is called an automaton built over the prefix-function. One way or another, if we've taught how to calculate $newpref$, then everything is quite simple: we know how to make movements in dynamics from one state to another. After getting the solution we'll have just to restore the answer-string itself. The solution's asymptotics depends on the way we chose to calculate $newpref$. The fastest way is using the prefix-function automaton, and the asymptotics in this case is $O(kn^{2})$. But, I remind, the problem's constraints allowed to choose some simpler way with worse asymptotics. P.S. This problem was additionally interesting by the fact that one can invent many strange simple solutions, which are very difficult to prove (and most of them will have counter-examples, but very rare ones). Some of these tricky solutions passed all systests in the round. I have also created one relatively simple solution that looks rather unlike to be right, but we didn't manage to create counter-example even after several hours of stress :)",
    "tags": [
      "brute force",
      "dp",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "54",
    "index": "E",
    "title": "Vacuum Сleaner",
    "statement": "One winter evening the Hedgehog was relaxing at home in his cozy armchair and clicking through the TV channels. Stumbled on an issue of «TopShop», the Hedgehog was about to change the channel when all of a sudden he was stopped by an advertisement of a new wondrous invention.\n\nActually, a vacuum cleaner was advertised there. It was called Marvellous Vacuum and it doesn't even need a human to operate it while it cleans! The vacuum cleaner can move around the flat on its own: it moves in some direction and if it hits an obstacle there, it automatically chooses a new direction. Sooner or later this vacuum cleaner will travel through all the room and clean it all. Having remembered how much time the Hedgehog spends every time on cleaning (surely, no less than a half of the day), he got eager to buy this wonder.\n\nHowever, the Hedgehog quickly understood that the cleaner has at least one weak point: it won't clean well in the room's corners because it often won't able to reach the corner due to its shape. To estimate how serious is this drawback in practice, the Hedgehog asked you to write for him the corresponding program.\n\nYou will be given the cleaner's shape in the top view. We will consider only the cases when the vacuum cleaner is represented as a convex polygon. The room is some infinitely large rectangle. We consider one corner of this room and want to find such a rotation of the vacuum cleaner so that it, being pushed into this corner, will leave the minimum possible area in the corner uncovered.",
    "tutorial": "The most important step on the way to solve this problem - is to understand that it's enough to consider only such rotations of the polygon, that one of its sides lies on the side of the room. Let's try to understand this fact. Suppose that the fact is wrong, and there exists such a position of vacuum cleaner, that neither of its sides lies on the side of the room. Denote as $i$ and $j$ the numbers of vertices that lie on the room sides. It's easy to understand that the polygon form between vertices $i$ and $j$ doesn't make any sense itself: for each rotation we can see that from the area of triangle $OP[i]P[j]$ some constant area is subtracted, while the concrete value of this constant depends on the polygon form. That's why we see that the polygon form doesn't influence on anything (if we have fixed numbers $i$ and $j$), and we have just to minimize the area of right-angled triangle $OP[i]P[j]$. But, taking into account that its hypotenuse is a constant, it's easy to see that the minimum is reached in borderline cases: i.e. when one of the polygon sides lies on the room side. So, we've proved the fact. Then we have to invent fast enough solution. We have already obtained an $O(n^{2})$ solution: iterate over all sides of the polygon (i.e. iterating over all possible $i$), mentally push it to one side of the room, then find the threshold point $j$, then calculate answer for given $i$ and $j$. Let's learn how to do these both things in $O(1)$. In order to do the first thing (finding $j$) we can use a method of moving pointer: if we iterate over $i$ in the same order as in the input file, then we can just maintain the right value of $j$ (i.e. when we move from $i$ to $i + 1$ we have to increase $j$ several times, while it is getting further and further). In order to do the second thing (the area calculation) we have to do some precalculation. For example, we can find the mass center $Q$ of the vacuum cleaner, and pre-calculate all partial sums $S[i]$ - sums of all triangles $QP[j - 1]P[j]$ for all $j  \\le  i$. After this precalculation we can get the answer for every $i$ and $j$ in $O(1)$ as a combination of difference of two values from $S[]$ and two triangles' areas: $QP[i]P[j]$ and $OP[i]P[j]$.",
    "tags": [
      "geometry"
    ],
    "rating": 2700
  },
  {
    "contest_id": "55",
    "index": "A",
    "title": "Flea travel",
    "statement": "A flea is sitting at one of the $n$ hassocks, arranged in a circle, at the moment. After minute number $k$ the flea jumps through $k - 1$ hassoсks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that flea has infinitely much time for this jumping.",
    "tutorial": "This problem is solved by simple emulation. After $2n$ jumps flea returns to initial position, because $1 + 2 + 3 + ... + 2n = n(2n + 1)$ is divisible by n. Moreover, after that, jumps would be the same as in the beginning, because $2n$ is divisible by $n$. So it is just enough to emulate first $2n$ jumps.In fact one may see that it is enough to emulate first $n$ jumps and moreover answer is \"YES\" exactly when $n$ is power of two. Last gives alternative solution. For example: printf(\"%s\", n&(n-1) : \"NO\" ? \"YES\");",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "55",
    "index": "B",
    "title": "Smallest number",
    "statement": "Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers $a$, $b$, $c$, $d$ on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.",
    "tutorial": "One just needs to calculate all possible answers and find the minimum. For example one may run on a set of numbers, for all pairs of numbers apply next operation to that pair and recursively run on a new set of numbers. When only one number remains, compare it to the already obtained minimum, and change that minimum if it's needed.",
    "tags": [
      "brute force"
    ],
    "rating": 1600
  },
  {
    "contest_id": "55",
    "index": "C",
    "title": "Pie or die",
    "statement": "Volodya and Vlad play the following game. There are $k$ pies at the cells of $n × m$ board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.",
    "tutorial": "Vladimir wins exactly when there is a pie with distance to the border not greater than 4. Indeed if there is such a pie, then Vladimir will move it to the border and then move it around the whole rim. Of course if there would be any chance to throw this pie from the board, Vladimir will use it. If he gets no such chance, then after mentioned moves all border is banned. But it means Vlad made at least $2n + 2m$ turns, when Vladimir only $2n + 2m - 1$ as a maximum. A contradiction. Else, if there is no such pie, then during first 4 turns Vlad would ban sides adjacent to each corner of the board. After that, if some pie comes to the rim he would ban adjacent side (there is no more than one such side) ans so Vladimir will never get the pie. So solution consists of only one distance check, but, as one may see, it is easy to make mistake.",
    "tags": [
      "games"
    ],
    "rating": 1900
  },
  {
    "contest_id": "55",
    "index": "D",
    "title": "Beautiful numbers",
    "statement": "Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.",
    "tutorial": "In this problem one should answer the query: how many beautiful numbers are there in the interval from 1 to R. Clearly, to check whether a number is divisible by all its digits, it is sufficient to know the remainder of a division by the lcm of all possible digits (call this lcm M), that is M = 8 * 9 * 5 * 7 = 2520. The standart dynamic solution is supposed to maintain such state parameters: the length of the number, \"strictly less\" flag, current remainder of a division by M and the mask of already taken digits. The first note: we can maitnain the lcm of the digits already taken, not the mask. This will decrease the number of different values of the last parameter (from 256 to 4 * 3 * 2 * 2 = 48, where 4 is the number of different powers of 2 etc). Then, it is a good idea to pre-count transitions to the new parameters. But we wanted and tried to set such a time limit restriction, so that this solution would not be enough to avoid TL. The idea that will decrease the running time even more lies in number theory. If we add digits from the end of a number we may see that the remainder of a number after division by 5 depends only on the last digit. Therefore, we may maintain the flag \"last digit = 5 or 0\" and ban transitions to the digit 5 if the flag is set to \"false\". Such an idea reduces the number of states by 5 * 2 / 2 = 5. This solution is fast enough to pass in any language, though there are even more powerful optimizations (the trick mentioned above can be done with digit 2 also).",
    "tags": [
      "dp",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "55",
    "index": "E",
    "title": "Very simple problem",
    "statement": "You are given a convex polygon. Count, please, the number of triangles that contain a given point in the plane and their vertices are the vertices of the polygon. It is guaranteed, that the point doesn't lie on the sides and the diagonals of the polygon.",
    "tutorial": "Let us solve this problem for every point P independently. We will show how to do this in linear time, that is, O(N). It seems that the most easy way to do this is to count the number of triangles not containing P (call them good), and then subtract this value from the total number of triangles. Consider triples of vertices A, B, C that form a triangle, such that: P doesn't lie in ABC; AB separates P and C in the polygon; P lies in the polygon to the right from AB (clockwise). Note, that every good triangle provides us one such triple and each triple forms a good triangle. Thus, we may consider such triples instead of good triangles. Let's consider an arbitrary vertex of the polygon. We want it to become an A-vertex in some triple. Then we can obtain the set of vertices, suitable for B-vertex in a triple moving diagonals from A (clockwise) until we reach P. Then for the fixed A the number of triples is equal to the sum of the number of triples for this A and the fixed B, which is equal to the sum of some linear series (as all suitable C lie between A and B and their number is equal to the vertex-distance between A and B minus one). The only thing left to do is to find the last B (last until P is reached) for each vertex of the polygon. And this is a simple exercise on the two pointers technique.",
    "tags": [
      "geometry",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "57",
    "index": "A",
    "title": "Square Earth?",
    "statement": "Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side $n$. Thus, the task has been reduced to finding the shortest path between two dots on a square (the path should go through the square sides). To simplify the task let us consider the vertices of the square to lie at points whose coordinates are: $(0, 0)$, $(n, 0)$, $(0, n)$ and $(n, n)$.",
    "tutorial": "Since the restrictions were not so big you can offer many different solutions. For example, you can construct a graph with N * 4 vertices and use bfs. But there was a faster solution with complexity O(1): enumerate the integer points lying on the square, for example, as is shown below: Then finding the number of a point by its coordinates isn't difficult. For example if a point has coordinate y == n -> then its position is n + x (if the numeration, is as shown, i.e. starts with zero). It turns out that we have transformed the square into a line with a small complication: cells N * 4 - 1 and 0 are adjacent, so we have not a line but a circle, where for the base points from 0 to 4 * N-1 the distance between the adjacent two points is 1. It is easy to take the difference of indices of the points and find the distance when moving clockwise and counterclockwise: (a-b +4 * n)% (4 * n) and (b - a + 4 * n)% (4 * n), the shortest distance will be the answer.",
    "tags": [
      "dfs and similar",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "57",
    "index": "B",
    "title": "Martian Architecture",
    "statement": "Chris the Rabbit found the traces of an ancient Martian civilization. The brave astronomer managed to see through a small telescope an architecture masterpiece — \"A Road to the Sun\". The building stands on cubical stones of the same size. The foundation divides the entire \"road\" into cells, into which the cubical stones are fit tightly. Thus, to any cell of the foundation a coordinate can be assigned. To become the leader of the tribe, a Martian should build a Road to the Sun, that is to build from those cubical stones on a given foundation a stairway. The stairway should be described by the number of stones in the initial coordinate and the coordinates of the stairway's beginning and end. Each following cell in the coordinate's increasing order should contain one cubical stone more than the previous one. At that if the cell has already got stones, they do not count in this building process, the stairways were simply built on them. In other words, let us assume that a stairway is built with the initial coordinate of $l$, the final coordinate of $r$ and the number of stones in the initial coordinate $x$. That means that $x$ stones \\textbf{will be added} in the cell $l$, $x + 1$ stones will be added in the cell $l + 1$, ..., $x + r - l$ stones will be added in the cell $r$.\n\nChris managed to find an ancient manuscript, containing the descriptions of all the stairways. Now he wants to compare the data to be sure that he has really found \"A Road to the Sun\". For that he chose some road cells and counted the total number of cubical stones that has been accumulated throughout the Martian history and then asked you to count using the manuscript to what the sum should ideally total.",
    "tutorial": "Under the restrictions on the number of requests, you cannot iteratively add staircase. But the problem is simplified by the fact that the number of cells in which it was necessary to know the number of stones was no more than 100. That's why you can check for each \"interesting\" cell all the queries and calculate how much each of them adds stones, so the complexity is: O (K * M), which fits within the given 2 seconds well. A faster solution with complexity O(N + M + K) is as follows: we will keep in mind two variables: a - how many items should be added now to the cell, v - how much should change a next step. So problem is to update the value of a and v so that a equaled to the number of stones in the cell after all the operations, and v - to how much a increases during the transition to the next cell. Then the problem will be reduced to that you need to properly update a and v, which is not very difficult to do, for example if there is a request (x, y, z) - then in the cell x you need to add x to a and add 1 to v, since with each next cell the number of stones for some staircase will increase by 1. Similarly, after the cell y is passed you need to subtract 1 from v and pick up from \"a\" the current number of stones subquery. If you save all such pairs of queries in a single array and it's possible to calculate everything in one cycle.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "57",
    "index": "C",
    "title": "Array",
    "statement": "Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of $n$, containing only integers from $1$ to $n$. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:\n\n- each elements, starting from the second one, is no more than the preceding one\n- each element, starting from the second one, is no less than the preceding one\n\nHaving got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.",
    "tutorial": "First, let's count how many there are arrays in which each successive element starting from the second one is no less than the previous one. To do this quickly, let's take a piece of squared with height of one square and the length of N*2 - 1 square, then select N-1 squares and put crosses in them - let it encode some array, let the number of blank cells from the beginning of the array before the first cross be equal to the number of ones in the array, the number of blank cells from the first cross to the second - to the number of 2 in the array, and so on. It is easy to see that the number of empty cells will be equal to N * 2-1 - (N-1) = N. It turns out that each paper encodes an array which suits us, and moreover all the possible arrays can be encoded using such paper. There is exactly C (N * 2-1, N) different pieces of paper (the binomial coefficient of N * 2-1 to N). This number can be calculated by formula with factorials, the only difficulty is division. Since the module was prime - it was possible to calculate the inverse number in the field for the module and replace division by multiplication. So we get the number of non-decreasing sequences, respectively have the same number of non-increasing, we just need to take away those who were represented in both array sets, but they are just arrays with a similar number like {1,1,1,...,1} or {4,4,...,4,4} just subtract n.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "57",
    "index": "D",
    "title": "Journey",
    "statement": "Stewie the Rabbit explores a new parallel universe. This two dimensional universe has the shape of a rectangular grid, containing $n$ lines and $m$ columns. The universe is very small: one cell of the grid can only contain one particle. Each particle in this universe is either static or dynamic. Each static particle always remains in one and the same position. Due to unintelligible gravitation laws no two static particles in the parallel universe can be present in one column or row, and they also can't be present in the diagonally \\textbf{adjacent} cells. A dynamic particle appears in a random empty cell, randomly chooses the destination cell (destination cell may coincide with the start cell, see the samples) and moves there along the shortest path through the cells, unoccupied by the static particles. All empty cells have the same probability of being selected as the beginning or end of the path. Having reached the destination cell, the particle disappears. Only one dynamic particle can exist at one moment of time. This particle can move from a cell to a cell if they have an adjacent side, and this transition takes exactly one galactic second. Stewie got interested in what is the average lifespan of one particle in the given universe.",
    "tutorial": "Let's see, if there is no occupied cells, then it is not difficult to calculate the answer - the answer is a sum of Manhattan distances, taking into account the fact that the Manhattan distance can be divided: first we can calculate the distance of one coordinate and then of another one and then just to sum up, so the answer is not difficult to find. What do we have when there are occupied cells? If the cell from which we seek the distance does not lie on the same horizontal or vertical with occupied cells - then it absolutely does not affect the difficulty of accessing the rest of the cells: This happens due to the fact that in each cell from the previous distance front (the distance to the set of cells with maximum distance from the start cell, the fronts form a diamond as you can see in the picture or from the Manhattan distance formula) there are two ways how to get to the cell, we take into account the rule that no two cells can be adjacent (either diagonally or vertically or horizontally), it turns out that such a cell does not interfere with us. But a close look at the picture brings to mind the obvious: it is the cell which is located on the same vertical / horizontal that has only one neighbor from the previous front, let's see what happens in such case: All the cells after occupied one starts \"to lag\" at 2 in distance, but more importantly, that changed the front! Now (with the upper side of the front) are 2 cells for which the transition from the previous front is unique, and as a consequence there are two cells meeting of which will produce a new segment of a late cells, and the angle of the front will change again. Since we are only interested in one side of its expansion (on the other hand there can not be occupied cells by the condition) so we can assume that it was expand from the start cell: It turns out that you can count how many cells will be \"delayed\", especially considering that the lag always equals to two. For each direction, you can choose each occupied cell and check in the left and right directions for adjacent cells series, and add delay for interval of free cell before occupied cell (in the current direction). It is possible to calculate such delays with complexity: square of the number of occupied cells (it is not greater than min(N, M)). The rest is details. You need to compute all Manhattan distances, taking into account the existence of occupied cells. To do this, first calculate the sum of distances for an empty field, then for each occupied cell calculate the distance to all the others - subtract it twice, as the extra distance is subtracted for the first time when we got out of this cell and for the second time when takes away from all other cells to the given one. But in this case we will take away twice the distance between two occupied cells - so we'll have to add them (the complexity is also a square). A total complexity of solution is O (K ^ 2) where K is the number of occupied cells.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "57",
    "index": "E",
    "title": "Chess",
    "statement": "Brian the Rabbit adores chess. Not long ago he argued with Stewie the Rabbit that a knight is better than a king. To prove his point he tries to show that the knight is very fast but Stewie doesn't accept statements without evidence. He constructed an infinite chessboard for Brian, where he deleted several squares to add some more interest to the game. Brian only needs to count how many different board squares a knight standing on a square with coordinates of $(0, 0)$ can reach in no more than $k$ moves. Naturally, it is forbidden to move to the deleted squares.\n\nBrian doesn't very much like exact sciences himself and is not acquainted with programming, that's why he will hardly be able to get ahead of Stewie who has already started solving the problem. Help Brian to solve the problem faster than Stewie.",
    "tutorial": "The task turned out to be very difficult as it was planned. First remove all the deleted cells - let's see how changes the number of accessible cells with the increase of the new moves. First, the changes do not appear stable, but at some point we see a figure which won't to change the form anymore and will only expand, it is obvious that the figure is two-dimensional, therefore the growth of its \"area\" is a quadratic function, in fact, a simple check shows that with each new turn the number of cells increases by the number of new cells opened with previous turn + 28, so after a certain point, you can simply take the sum of an arithmetic progression. The case with the deleted cells is similar. In general, there are several possible options - either occupied cells block further penetration of the horse or not, in the first case bfs is simply enough to find solutions, in the second one the story is the same: over time, when the figure \"becomes balanced\", the number of new opened cells satisfies the same rule \"prev +28\" . Moreover, because of restrictions of the coordinates of the deleted cells (-10 <= x, y <= 10) this happens fairly quickly. So, use usual bfs to balance figures, and after this use the sum of the arithmetic progression.",
    "tags": [
      "math",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "59",
    "index": "A",
    "title": "Word",
    "statement": "Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.",
    "tutorial": "This was an extremely simple problem. Simply count the number of upper case latin letters. If that is strictly greater than number of lower case letters convert the word to upper case other wise convert it to lower case. Complexity: O(wordlength)",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "59",
    "index": "B",
    "title": "Fortune Telling",
    "statement": "Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces alternatively \"Loves\" and \"Doesn't love\", at that Marina always starts with \"Loves\". There are $n$ camomiles growing in the field, possessing the numbers of petals equal to $a_{1}, a_{2}, ... a_{n}$. Marina wants to pick a bouquet with the maximal possible total number of petals so that the result would still be \"Loves\". Help her do that; find the maximal number of petals possible in the bouquet.",
    "tutorial": "For this problem all you need to do is store the smallest odd number of petals and also the sum of all the petals. It is quite obvious that only if the number of petals is odd the result would be \"Loves\". So if the sum is even print sum - smallest odd, otherwise print the sum. Complexity: O(n).",
    "tags": [
      "implementation",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "59",
    "index": "C",
    "title": "Title",
    "statement": "Vasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first $k$ Latin letters and not containing any other ones. Also, the title should be a palindrome, that is it should be read similarly from the left to the right and from the right to the left.\n\nVasya has already composed the approximate variant of the title. You are given the title template $s$ consisting of lowercase Latin letters and question marks. Your task is to replace all the question marks by lowercase Latin letters so that the resulting word satisfies the requirements, described above. Each question mark should be replaced by exactly one letter, it is not allowed to delete characters or add new ones to the template. If there are several suitable titles, choose the first in the alphabetical order, for Vasya's book to appear as early as possible in all the catalogues.",
    "tutorial": "This was a very nice problem. My approach was to first flag all the letters which have already appeared. Notice, that we have to output the lexicographically smallest palindrome. So, start from the middle of the letter and iterate one side... If you get a '?' stop and check if the corresponding position on the other side also has a '?'. If yes, then fill both with the lexicographically biggest letter which hasn't appeared yet in the word and also flag that letter. Once you have exhausted all the letters and there are still '?' left then simply fill them with 'a'. Now simply iterate over the word again and see if there are any question marks left, if yes copy the values in the corresponding block on the other side. At the same time check if at any time the two opposite values match or not. If they do throughout then it is a valid plaindrome which is also the lexicographically smallest palindrome. Complexity: O(wordlength + k)",
    "code": "#include <stdio.h>\n#include <string.h>\n\nint main()\n{\n        int a[27], k, i, j, len, count = 0, first;\n        char t[110];\n        scanf(\" %d %s\", &k, t);\n        for(i = 0; i < k; i ++)\n                a[i] = 0;\n        len = strlen(t);\n        for(i = 0; i < len; i ++)\n        {\n                if(t[i] == '?')\n                        count ++;\n                else\n                        a[t[i] - 'a'] ++;\n        }\n        for(i = 0; i < k; i ++)\n                if(a[i] == 0)\n                {\n                        first = i;\n                        break;\n                }\n        j = k - 1;\n        //printf(\"%d\n\", a[j]);\n        for(i = len / 2 - (1 - len % 2); i > -1; i --)\n        {\n                if(t[i] == '?')\n                {\n                        if(t[len - i - 1] == '?')\n                        {\n                                while(a[j] != 0 && j > 0)\n                                        j --;\n                                //printf(\"%d\n\", j);\n                                t[i] = j + 'a';\n                                t[len - i - 1] = j + 'a';\n                                a[j] ++;\n                        }\n                        else\n                                t[i] = t[len - i - 1];\n                }\n        }\n        for(i = 0; i < len; i ++)\n        {\n                if(t[i] == '?')\n                        t[i] = t[len - i - 1];\n        }\n        for(i = 0; i < len; i ++)\n        {\n                if(t[i] != t[len - i - 1])\n                {\n                        printf(\"IMPOSSIBLE\");\n                        return 0;\n                }\n        }\n        for(i = 0; i < k; i ++)\n                a[i] = 0;\n        for(i = 0; i < len; i ++)\n                a[t[i] - 'a'] ++;\n        for(i = 0; i < k; i ++)\n                if(a[i] == 0)\n                {\n                        printf(\"IMPOSSIBLE\");\n                        return 0;\n                }\n        printf(\"%s\", t);\n        return 0;\n}",
    "tags": [
      "expression parsing"
    ],
    "rating": 1600
  },
  {
    "contest_id": "59",
    "index": "D",
    "title": "Team Arrangement",
    "statement": "Recently personal training sessions have finished in the Berland State University Olympiad Programmer Training Centre. By the results of these training sessions teams are composed for the oncoming team contest season. Each team consists of three people. All the students of the Centre possess numbers from $1$ to $3n$, and all the teams possess numbers from $1$ to $n$. The splitting of students into teams is performed in the following manner: while there are people who are not part of a team, a person with the best total score is chosen among them (the captain of a new team), this person chooses for himself two teammates from those who is left according to his list of priorities. The list of every person's priorities is represented as a permutation from \\textbf{the rest of} $3n - 1$ students who attend the centre, besides himself.\n\nYou are given the results of personal training sessions which are a permutation of numbers from $1$ to $3n$, where the $i$-th number is the number of student who has won the $i$-th place. No two students share a place. You are also given the arrangement of the already formed teams in the order in which they has been created. Your task is to determine the list of priorities for the student number $k$. If there are several priority lists, choose the lexicographically minimal one.",
    "tutorial": "This was in my opinion was the toughest problem. However once you get the logic, its pretty obvious. However, it was a slightly challenging implementation for me as the structure of the data to be stored was sort of complex. The basic idea was simply that if we have to find the preference list of a number 'p' then two things might happen: Case 1: p is the most skilled in his team and thus he chose the team. In this case we know that all the members of the teams coming after p's team are less preferred than p's team mates. Let p's team mates be 'm' and 'n' such that m > n. To get the lexicographically smallest preference list, we will divide all the programmers into two lists. The first list will contain all members (ai) from teams which were chosen before p's team such that ai < m. It will also contain m and n. The second list will contain all the left over members. The separation can be done in O(n) time. Now all we need to do is sort the first list, print it, sort the second list, print it! Complexity: O(nlogn)... It can be reduced to O(n) also but the constant will be pretty high and will give almost the same result as O(nlogn). Case 2: p is not the leader of the team. Then you just have to output all number except 'p' from 1 to 3 * n.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "60",
    "index": "A",
    "title": "Where Are My Flakes?",
    "statement": "One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of $n$ boxes. The boxes stand in one row, they are numbered from $1$ to $n$ from the left to the right. The roommate left hints like \"Hidden to the left of the $i$-th box\" (\"To the left of $i$\"), \"Hidden to the right of the $i$-th box\" (\"To the right of $i$\"). Such hints mean that there are no flakes in the $i$-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.",
    "tutorial": "Solution - $O(n^{2})$. We take phrase and parse it. Mark all cells, that obviously didn't match - $O(n)$. In the end we go through the array and count all unmarked cells. If 0 - we print \"-1\", else - amount of unmarked cells.",
    "tags": [
      "implementation",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "60",
    "index": "B",
    "title": "Serial Time!",
    "statement": "The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped $k × n × m$, that is, it has $k$ layers (the first layer is the upper one), each of which is a rectangle $n × m$ with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square $(x, y)$ of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment.\n\nNote: the water fills all the area within reach (see sample 4). Water flows in \\textbf{each} of the 6 directions, through faces of $1 × 1 × 1$ cubes.",
    "tutorial": "Solution - $O(k  \\times  n  \\times  m)$. We start BFS from given point. Go from cell to all 6 directions. The answer - number of visited cells.",
    "tags": [
      "dfs and similar",
      "dsu"
    ],
    "rating": 1400
  },
  {
    "contest_id": "60",
    "index": "C",
    "title": "Mushroom Strife",
    "statement": "Pasha and Akim were making a forest map — the lawns were the graph's vertexes and the roads joining the lawns were its edges. They decided to encode the number of laughy mushrooms on every lawn in the following way: on every edge between two lawns they wrote two numbers, the greatest common divisor (GCD) and the least common multiple (LCM) of the number of mushrooms on these lawns. But one day Pasha and Akim had an argument about the laughy mushrooms and tore the map. Pasha was left with just some part of it, containing only $m$ roads. Your task is to help Pasha — use the map he has to restore the number of mushrooms on every lawn. As the result is not necessarily unique, help Pasha to restore any one or report that such arrangement of mushrooms does not exist. It is guaranteed that the numbers on the roads on the initial map were no less that $1$ and did not exceed $10^{6}$.",
    "tutorial": "Solution - $O(2^{7}  \\times  n^{2})$. We can see, that in connected component - if we know 1 number - then we know all others in component, because in each pare we know minimal and maximal power of each primes. Because number of different primes in one number \"$< = 1000000$\" is less, than 7, we can look over all possibilities of 1 number in connected compoment - and for each number, that we get, we check, that it suits. How to check? We can notice, that if we know $a$, $(a, b)$, $[a, b]$, then $b={\\frac{(a,b]a,b)}{a}}$, start DFS and check.",
    "tags": [
      "brute force",
      "dfs and similar"
    ],
    "rating": 2100
  },
  {
    "contest_id": "60",
    "index": "D",
    "title": "Savior",
    "statement": "Misha decided to help Pasha and Akim be friends again. He had a cunning plan — to destroy all the laughy mushrooms. He knows that the laughy mushrooms can easily burst when they laugh. Mushrooms grow on the lawns. There are $a[t]$ mushrooms on the $t$-th lawn.\n\nMisha knows that the lawns where the mushrooms grow have a unique ability. A lawn (say, $i$) can transfer laugh to other lawn (say, $j$) if there exists an integer (say, $b$) such, that some permutation of numbers $a[i], a[j]$ and $b$ is a beautiful triple ($i ≠ j$). A beautiful triple is such three pairwise coprime numbers $x, y, z$, which satisfy the following condition: $x^{2} + y^{2} = z^{2}$.\n\nMisha wants to know on which minimal number of lawns he should laugh for all the laughy mushrooms to burst.",
    "tutorial": "Solution - $O($max numebr$)$. We can notice, that each beautiful triplet has form - $(x^{2} - y^{2}, 2xy, x^{2} + y^{2})$. Now we can gen all such triples. For each triple, we watch - if we have more than 1 number in given set - we union them. How to gen all the triples? $x > y$. $2x y\\leq m a x;\\Rightarrow y\\leq{\\sqrt{\\frac{m a x}{2}}}$. This means, that $m a x\\geq x^{2}-y^{2}\\geq x^{2}-{\\frac{m a x}{2}}\\Rightarrow x\\leq{\\sqrt{\\frac{3m a x}{2}}}$. Now for gen all this triples we an take - $x\\leq{\\sqrt{\\frac{3m a x}{2}}}$ and $y\\leq{\\sqrt{\\frac{m v\\pi}{2}}}$. The number of iterations - $\\frac{{\\sqrt{3}}m n x}{2}$. what means - \"union\"? We take a data structure named DSU. If two number belong to one beautiful triple - they are connected with edge, in our situation - we can union corresponding to them unions.",
    "tags": [
      "brute force",
      "dsu",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "60",
    "index": "E",
    "title": "Mushroom Gnomes",
    "statement": "Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighboring ones.\n\nThe mushroom gnomes loved it when everything was in order, that's why they always planted the mushrooms in one line in the order of their weights' increasing. Well... The gnomes planted the mushrooms and went to eat. After $x$ minutes they returned and saw that new mushrooms had grown up, so that the increasing order had been violated. The gnomes replanted all the mushrooms in the correct order, that is, they sorted the mushrooms in the order of the weights' increasing. And went to eat again (those gnomes were quite big eaters). What total weights modulo $p$ will the mushrooms have in another $y$ minutes?",
    "tutorial": "Solution - $O(n + log(xy))$. We can see, that after one minute the sum changes - it multiply on 3, and substract first and last elements of sequence. Because of that we can count of sum with help of power of matrix. What happens after sorting. First number stay on his place. On the last place - $F_{x}a_{n} + F_{None}a_{None}$. Where $n$ - number of elements, ans $F_{x}$ - $x$ Fibonacci number - with $F_{ - 1} = 0$ and $F_{0} = 1$. This means - that we can count the last number with matrix too. After that we use the first idea. If you have questions - ask them.",
    "tags": [
      "math",
      "matrices"
    ],
    "rating": 2600
  },
  {
    "contest_id": "61",
    "index": "A",
    "title": "Ultra-Fast Mathematician",
    "statement": "Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum $10^{18}$ numbers in a single second.\n\nOne day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.\n\nIn his contest he gave the contestants many different pairs of numbers. Each number is made from digits $0$ or $1$. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The $i$-th digit of the answer is $1$ if and only if the $i$-th digit of the two given numbers differ. In the other case the $i$-th digit of the answer is $0$.\n\nShapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length $∞$ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.\n\nNow you are going to take part in Shapur's contest. See if you are faster and more accurate.",
    "tutorial": "This was indeed the easiest problem. You just needed to XOR the given sequences. The only common mistake was removing initial 0s which led to \"Wrong Answer\" Common mistake in hacks which led to \"Invalid Input\" was forgetting that all lines in input ends with EOLN.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "61",
    "index": "B",
    "title": "Hard Work",
    "statement": "After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!\n\nSome days before the contest, the teacher took a very simple-looking exam and all his $n$ students took part in the exam. The teacher gave them $3$ strings and asked them to \\underline{concatenate} them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.\n\nUnfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.\n\nNow the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.\n\nShapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said:\n\n- As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin.\n- As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include \"-\", \";\" and \"_\". These characters are my own invention of course! And I call them \\underline{Signs}.\n- The length of all initial strings was less than or equal to $100$ and the lengths of my students' answers are less than or equal to $600$\n- My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes.\n- Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN\n- You should indicate for any of my students if his answer was right or wrong. Do this by writing \"WA\" for Wrong answer or \"ACC\" for a correct answer.\n- I should remind you that none of the strings (initial strings or answers) are empty.\n- Finally, do these as soon as possible. You have less than $2$ hours to complete this.",
    "tutorial": "In this problem signs can be ignored in both initial and answer strings, so first we remove signs from initial strings. Then we make a list of the six possible concatenations of the 3 initial strings and convert all of them to lowercase.For checking an answer string , we remove the signs , convert it to lowercase and check if it is just one of those 6 concatenations. There were two really nice hack protocols , the first one is: -------__________; _____; ;;;;---------_ 2 ab____ _______;;; Here all concatenations become empty. The second one was putting 0 as number of students :D",
    "tags": [
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "61",
    "index": "C",
    "title": "Capture Valerian",
    "statement": "It's now $260$ AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran.\n\nRecently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captured by Shapur and Shapur is now going to capture Valerian, the Roman emperor.\n\nBeing defeated, the cowardly Valerian hid in a room at the top of one of his castles. To capture him, Shapur has to open many doors. Fortunately Valerian was too scared to make impenetrable locks for the doors.\n\nEach door has $4$ parts. The first part is an integer number $a$. The second part is either an integer number $b$ or some really odd sign which looks like R. The third one is an integer $c$ and the fourth part is empty! As if it was laid for writing something. Being extremely gifted, after opening the first few doors, Shapur found out the secret behind the locks.\n\n$c$ is an integer written in base $a$, to open the door we should write it in base $b$. The only bad news is that this R is some sort of special numbering system that is used only in Roman empire, so opening the doors is not just a piece of cake!\n\nHere's an explanation of this really weird number system that even doesn't have zero:\n\nRoman numerals are based on seven symbols: a stroke (identified with the letter I) for a unit, a chevron (identified with the letter V) for a five, a cross-stroke (identified with the letter X) for a ten, a C (identified as an abbreviation of Centum) for a hundred, etc.:\n\n- I=$1$\n- V=$5$\n- X=$10$\n- L=$50$\n- C=$100$\n- D=$500$\n- M=$1000$\n\nSymbols are iterated to produce multiples of the decimal ($1$, $10$, $100$, $1, 000$) values, with V, L, D substituted for a multiple of five, and the iteration continuing: I $1$, II $2$, III $3$, V $5$, VI $6$, VII $7$, etc., and the same for other bases: X $10$, XX $20$, XXX $30$, L $50$, LXXX $80$; CC $200$, DCC $700$, etc. At the fourth and ninth iteration, a subtractive principle must be employed, with the base placed before the higher base: IV $4$, IX $9$, XL $40$, XC $90$, CD $400$, CM $900$.\n\nAlso in bases greater than $10$ we use A for $10$, B for $11$, etc.\n\nHelp Shapur capture Valerian and bring peace back to Persia, especially Armenia.",
    "tutorial": "The code for converting decimal numbers to Roman was on Wikipedia , so I'm not going to explain it.Since we have the upper limit 1015 for all of our numbers , we can first convert them to decimal (and store the answer in a 64-bit integer) and then to the target base. For converting a number to decimal we first set the decimal variable to 0, then at each step we multiply it by the base and add the left-most digit's equivalent in base 10. We had some tricky test cases for this one which got many people : test #51: 2 10 0 many codes printed nothing for this one, this was also the most used hack for this problem test #54: 12 2 000..00A a sample of having initial zeros in input test #55: 17 17 0000000...000 There were many people who just printed the input if bases were equal there were two nice extremal hacks: 2 R 101110111000 and 10 21000000000000000",
    "tags": [
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "61",
    "index": "D",
    "title": "Eternal Victory",
    "statement": "Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!\n\nHe decided to visit all $n$ cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these $n$ cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.\n\nAll cities are numbered $1$ to $n$. Shapur is currently in the city $1$ and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.\n\nHelp Shapur find how much He should travel.",
    "tutorial": "This one has two different linear-time solutions. Greedy and dynamic programming. Greedy solution: You should stop at the city with maximum distance from the root (city number 1). So all roads are traversed twice except for the roads between the root and this city. Dynamic Programming: For each city i we declare patrol[i] as the traverse needed for seeing i and all of it's children without having to come back to i (Children of a city are those cities adjacent to it which are farther from the root) and revpatrol[i] as the traverse needed to see all children of i and coming back to it. we can see that revpatrol[i] is sum of revpatrols of its children + sum of lengths of roads going from i to its children. patrol[i] can be found by replacing each of revpatrols with patrol and choosing their minimum.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "61",
    "index": "E",
    "title": "Enemy is weak",
    "statement": "The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: \"A lion is never afraid of a hundred sheep\".\n\nNevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.\n\nIn Shapur's opinion the weakness of an army is equal to the number of triplets $i, j, k$ such that $i < j < k$ and $a_{i} > a_{j} > a_{k}$ where $a_{x}$ is the power of man standing at position $x$. The Roman army has one special trait — powers of all the people in it are distinct.\n\nHelp Shapur find out how weak the Romans are.",
    "tutorial": "This one can be solved in O(nlgn) using a segment tree.First we convert all powers to numbers in range 0..n-1 to avoid working with segments as large as 109 in our segment tree. Then for each of the men we should find number of men who are placed before him and have more power let's call this gr[j]. When ever we reach a man with power x we add the segment [0,x-1] to our segment tree , so finding gr[j] can be done by querying power of j in our segment tree when it's updated by all j-1 preceding men. Now let's call number of men who are standing after j but are weaker than j as le[j]. These values can be found using the same method with a segment-tree or in O(n) time using direct arithmetic: le[j]=(power of j -1)-(i-1-gr[j]) note that powers are in range 0..n-1 now. Now we can count all triplets i,j,k which have j as their second index. This is le[j]*gr[j] so the final answer is $\\sum_{j=0}^{n-1} le[j]\\times gr[j]$",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "62",
    "index": "A",
    "title": "A Student's Dream",
    "statement": "Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.\n\nA poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych.\n\nThe poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams.\n\nSo the professor began: \"Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has $a_{l}$ fingers on her left hand and $a_{r}$ fingers on the right one. The boy correspondingly has $b_{l}$ and $b_{r}$ fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. \\textbf{And in addition, no three fingers of the boy should touch each other.} Determine if they can hold hands so that the both were comfortable.\"\n\nThe boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa.",
    "tutorial": "There was a lot of troubles because of incorrect statement. Now I hope statement is ok. Let's solve it. =) If boy will goes to the left he will take her left hand with his right one and boy's left hand and girl's right hand will be unused. Situation is looks like the same if we swap them vice versa. So, we need to check two situations and choose the best one. There is a simple way to check comfortableness, let's assume that boy has $B$ fingers on active hand and girl has $G$ fingers on active hand, so: If $B < G$ they will be happy only when $B = G - 1$, you may see a pattern $GBGBGBG...GBGBG$. In this pattern you can add no girl's finger for save the condition in statement If $B > G$ the worst but correct situation for them is a pattern $BBGBBGBB...BBGBB$. As you may see this way must be satisfy $2G + 2 > = B$ condition Simple situation is $B = G$, obviously answer is \"yes\"",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "62",
    "index": "B",
    "title": "Tyndex.Brome",
    "statement": "Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!\n\nThe popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.\n\nLet us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!\n\nHow does this splendid function work? That's simple! For each potential address a function of the $F$ error is calculated by the following rules:\n\n- for every letter $c_{i}$ from the potential address $c$ the closest position $j$ of the letter $c_{i}$ in the address ($s$) entered by the user is found. The absolute difference $|i - j|$ of these positions is added to $F$. So for every $i$ ($1 ≤ i ≤ |c|$) the position $j$ is chosen such, that $c_{i} = s_{j}$, and $|i - j|$ is minimal possible.\n- if no such letter $c_{i}$ exists in the address entered by the user, then the length of the potential address $|c|$ is added to $F$.\n\nAfter the values of the error function have been calculated for all the potential addresses the most suitable one is found.\n\nTo understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the $F$ function for an address given by the user and some set of potential addresses. Good luck!",
    "tutorial": "Let's define $p$ as total length of all potential addresses $c$. In this problem obvious solution has O($p \\cdot  k$) difficulty and it is getting a TLE verdict. Let's speed up it by next way: we will save all position of letters 'a', 'b', ..., 'z' in address entered by user $s$ separately in increasing order. After this step we can find closest position of letter $c_{i}$ in $s$ for logarithmic time by binary search. This solution has O($p  \\cdot  logk$) difficulty that gives \"accepted\". Look carefully for length of potential address (it can be more than $10^{5}$). Answer can be too big and asks you for using integer 64-bit type.",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "62",
    "index": "C",
    "title": "Inquisition",
    "statement": "In Medieval times existed the tradition of burning witches at steaks together with their pets, black cats. By the end of the 15-th century the population of black cats ceased to exist. The difficulty of the situation led to creating the EIC - the Emergency Inquisitory Commission.\n\nThe resolution #666 says that a white cat is considered black when and only when the perimeter of its black spots exceeds the acceptable norm. But what does the acceptable norm equal to? Every inquisitor will choose it himself depending on the situation. And your task is to find the perimeter of black spots on the cat's fur.\n\nThe very same resolution says that the cat's fur is a white square with the length of $10^{5}$. During the measurement of spots it is customary to put the lower left corner of the fur into the origin of axes $(0;0)$ and the upper right one — to the point with coordinates $(10^{5};10^{5})$. The cats' spots are nondegenerate triangles. The spots can intersect and overlap with each other, but it is guaranteed that each pair of the triangular spots' sides have no more than one common point.\n\nWe'll regard the perimeter in this problem as the total length of the boarders where a cat's fur changes color.",
    "tutorial": "All triangles are located strickly inside of square. It makes problem more simplify, because you don't need to check situations of touching sides. Let's save all segments of every triangle and cross them in pairs. There are many points at every segment - the results of crossing. Look at the every subsegment which do not contain any points of crossing inside. There are two situations: this subsegment completely lie on the side of some triangle or this subsegment completely lie inside of some triangle. We may check what is situation by this way: let's take a point at the middle of subsegment. If this point is strickly inside of some triangle then all subsegment is located inside and vice versa. We should calculate only subsegments located on the side of triangles and print their total length. If you are using integer numbers you should be careful for some operations like vector multiplication because it may leave 32-bit type. If you are using real numbers you should change you types for as large as possible for good precision (long long in c++, extended in pascal).",
    "tags": [
      "geometry",
      "implementation",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "62",
    "index": "D",
    "title": "Wormhouse",
    "statement": "Arnie the Worm has finished eating an apple house yet again and decided to move. He made up his mind on the plan, the way the rooms are located and how they are joined by corridors. He numbered all the rooms from $1$ to $n$. All the corridors are bidirectional.\n\nArnie wants the new house to look just like the previous one. That is, it should have exactly $n$ rooms and, if a corridor from room $i$ to room $j$ existed in the old house, it should be built in the new one.\n\nWe know that during the house constructing process Arnie starts to eat an apple starting from some room and only stops when he eats his way through all the corridors and returns to the starting room. It is also known that Arnie eats without stopping. That is, until Arnie finishes constructing the house, he is busy every moment of his time gnawing a new corridor. Arnie doesn't move along the already built corridors.\n\nHowever, gnawing out corridors in one and the same order any time you change a house is a very difficult activity. That's why Arnie, knowing the order in which the corridors were located in the previous house, wants to gnaw corridors in another order. It is represented as a list of rooms in the order in which they should be visited. The new list should be lexicographically smallest, but it also should be strictly lexicographically greater than the previous one. Help the worm.",
    "tutorial": "In this problem you asks to find lexicographically next euler cycle or say that there is no way. Let's solve this problem backwards. We should repeat way of Arnie. Now it needs to rollback every his step and add edges for empty graph (graph without edges). Let's assume we had rollback edge from some vertix $x$ to vertix $y$. We need to check is there some vertix $z$ that is connected to $x$ by an edge and value of $z$ is more than $y$? Besides edge ($x$; $z$) shouldn't be a bridge because our component needs to be connected. No solution answer if it's impossible to find such $z$ at any step. But if edge ($x$; $z$) satisfied to conditions upper is exists let's change it to move and after this step our problem is to find lexicographically smallest euler way. It is possible to find only in unbreaked component of graph so every next step must going along non-brigde edges in vertix with as low number as possible. Of course, we must destroy unachievable vertices and do not destroy initial vertix. We can check is edge a bridge for O($E$) time by depth first search. Total difficulty of algorithm represented above is O($N \\cdot  E^{2}$).",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "62",
    "index": "E",
    "title": "World Evil",
    "statement": "As a result of Pinky and Brain's mysterious experiments in the Large Hadron Collider some portals or black holes opened to the parallel dimension. And the World Evil has crept to the veil between their world and ours. Brain quickly evaluated the situation and he understood that the more evil tentacles creep out and become free, the higher is the possibility that Brain will rule the world.\n\nThe collider's constriction is a rectangular grid rolled into a cylinder and consisting of $n$ rows and $m$ columns such as is shown in the picture below:\n\nIn this example $n = 4$, $m = 5$. Dotted lines are corridores that close each column to a ring, i. e. connect the $n$-th and the $1$-th rows of the grid.\n\nIn the leftmost column of the grid the portals are situated and the tentacles of the World Evil are ready to creep out from there. In the rightmost column the exit doors are located. The tentacles can only get out through those doors. The segments joining the nodes of the grid are corridors.\n\nBrain would be glad to let all the tentacles out but he faces a problem: the infinite number of tentacles can creep out of the portals, every tentacle possesses infinite length and some width and the volume of the corridors are, unfortunately, quite limited. Brain could approximately evaluate the maximal number of tentacles that will be able to crawl through every corridor.\n\nNow help the mice to determine the maximal number of tentacles of the World Evil that will crawl out of the Large Hadron Collider.",
    "tutorial": "In this problem you were to find the maximal flow in network with a cyllinder structure. The dynamic solution with complexity $O(mn2^{n})$ was considered.It's well known that the maximal flow is equal to value of the minimal cut. Also all the sources must belong to one part of the cut and all the drains --- to the other part. Then we look over all the vertices from the left to the right, from the top to the bottom and append to the one or the other part of the cut, recalculating the answer during the process. The trivial solution has complexity $O(2^{mn})$ and doesn't fit the time limit. But we can notice the number add to the answer after appending a new vertice to some part of the cut depends only on what parts of the cut the vertices in the current and the previous columns belong to. So we can calculate such a value using dynamic programming: what is the minimal cut can be obtained by adding $i$ columns and the mask of belongings of vertices of the $i$th column to the parts of the cut is $mask$. Then we have $2^{n}$ conversions because there are $2^{n}$ different states of the $i - 1$th column. So we have the $O(mn2^{None})$ solution. But this solution also can be improved. We calculate the minimal cut, if $i - 1$ columns are added completely and $j$ vertices from the $i$th column are added, and mask of belongings of vertices that have no neighbours on the right is $mask$. Then we append $j$-th vertice to one of the parts, recalculate the value of the cut and do the conversion. So we have $mn2^{n}$ conditions and $O(1)$ conversions from the every condition and the solution's complexity is $O(mn2^{n})$.",
    "tags": [
      "dp",
      "flows"
    ],
    "rating": 2700
  },
  {
    "contest_id": "63",
    "index": "A",
    "title": "Sinking Ship",
    "statement": "The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All $n$ crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to $n$) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:\n\nThe first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.\n\nIf we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).\n\nFor each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.",
    "tutorial": "This problem can be easily solved with the following algorithm. First, read names ans statuses of all crew members into an array. Next, iterate over the entire array 4 times. In the first pass output names of rats. In the second pass output names of women and children. In the third pass output names of men. Finally, in the fourth pass output the name of the captain.",
    "tags": [
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "63",
    "index": "B",
    "title": "Settlers' Training",
    "statement": "In a strategic computer game \"Settlers II\" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly $n$ soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.\n\nEvery soldier has a rank — some natural number from $1$ to $k$. $1$ stands for a private and $k$ stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.\n\nTo increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the $n$ soldiers are present.\n\nAt the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank $k$ are present, exactly one soldier increases his rank by one.\n\nYou know the ranks of all $n$ soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank $k$.",
    "tutorial": "In this problem you can simulate the process of soliders training until there is at least one soldier with rank less than $k$. We iterate over the array of ranks and increase by one the ranks of every soldier who is the last in his group (if he has the rank less than $k$, of course). This operation preserves non-decreasing order of the ranks. Obviously we will need no more than $kn$ trains. So we have $O(kn^{2})$ solution. It fits the limits. You can prove that we will make no more than $n + k$ trains in the solution above. Therefore it really works in $O(n(n + k))$. In addition there is an $O(n)$ solution.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "63",
    "index": "C",
    "title": "Bulls and Cows",
    "statement": "The \"Bulls and Cows\" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.\n\nThe thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format \"$x$ bulls $y$ cows\". $x$ represents the number of digits in the experimental number that occupy the same positions as in the sought number. $y$ represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.\n\nFor example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply \"1 bull 2 cows\" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be \"2 bulls 1 cow\" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).\n\nWhen the guesser is answered \"4 bulls 0 cows\", the game is over.\n\nNow the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.",
    "tutorial": "Consider all of the numbers which the thinker may thinks of. Next we select from them ones which fit all thinker's answers. If there is exactly one such number, output it. If there are no such numbers, output \"Incorrect data\". Otherwise output \"Need more data\". The complexity of this solution is $O(10^{4}  \\times  n)$. Most of mistakes in this problem were caused by leading zeros. Either while printing the answer or while transforming numbers into strings for checking them.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "63",
    "index": "D",
    "title": "Dividing Island",
    "statement": "A revolution took place on the Buka Island. New government replaced the old one. The new government includes $n$ parties and each of them is entitled to some part of the island according to their contribution to the revolution. However, they can't divide the island.\n\nThe island can be conventionally represented as two rectangles $a × b$ and $c × d$ unit squares in size correspondingly. The rectangles are located close to each other. At that, one of the sides with the length of $a$ and one of the sides with the length of $c$ lie on one line. You can see this in more details on the picture.\n\nThe $i$-th party is entitled to a part of the island equal to $x_{i}$ unit squares. Every such part should fully cover several squares of the island (it is not allowed to cover the squares partially) and be a connected figure. A \"connected figure\" presupposes that from any square of this party one can move to any other square of the same party moving through edge-adjacent squares also belonging to that party.\n\nYour task is to divide the island between parties.",
    "tutorial": "Main idea of the solution is walk the island around with a \"snake\". You can do it, for example, this way: or this way: Then we can just \"cut\" the snake into the pieces of appropriate length. It is clear that all the resulting figures will be connected. The complexity of this solution is $O(max(B, D)  \\times  (A + C))$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "63",
    "index": "E",
    "title": "Sweets Game",
    "statement": "Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake as a reward.\n\nThe box of chocolates has the form of a hexagon. It contains 19 cells for the chocolates, some of which contain a chocolate. The players move in turns. During one move it is allowed to eat one or several chocolates that lay in the neighboring cells on one line, parallel to one of the box's sides. The picture below shows the examples of allowed moves and of an unacceptable one. The player who cannot make a move loses.\n\nKarlsson makes the first move as he is Lillebror's guest and not vice versa. The players play optimally. Determine who will get the cake.",
    "tutorial": "Define a state as some layout of sweets in a box. We have to detrmine for every state whether it is winning or losing. The state is winning if you can do a acceptable move to a losing state. Otherwise it is losing. For example, the state corresponding to the empty box is losing because there are no moves from this state. A state corresponding to a box containing only one candy is winning because there is a move leading to a losing state - eating the candy leaves the box empty. Thus, if the state given in the input is winning the answer is \"Karlsson\", otherwise answer is \"Lillebror\". It's useful to represent a state with a 19-bit mask where the i-th bit is 1 if there is a candy in the i-th cell. Similarly, each move can be respresented with a mask where the i-th bit is 1 if the candy in the i-th cell is to be eaten during the move. Note that a move $move$ can be done in a state $mask$ if $m o v e{\\mathrm{~AND~}}m a s k==m o v_{t}$, and doing this move leads to the state $m a s k\\mathrm{\\bf~XOR~}m o v\\epsilon$. Also note that in this case $m a s k\\mathrm{\\bf~XUR~}m o v e<m a s k$. These observations lead to the following solution: iterate over every state from $0$ to $2^{19} - 1$. For each state examine the list of possible moves and find ones that can be done in the current state. Assuming that we know the winningness of the states with lesser numbers, we can determine the winningness of the current state as described above. It's convenient to precompute the masks for all possible moves and store them in an array. This is apparently the most tricky part of this problem with lots of approaches ranging from the explicit enumeration to long intricate functions producing the moves list. Any approach will do, provided it is carefully implemented. The complexity of this solution is $O(2^{19}k)$, where k is the number of different moves (which turns out to be equal to $103$).",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "games",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "65",
    "index": "A",
    "title": "Harry Potter and Three Spells",
    "statement": "A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert $a$ grams of sand into $b$ grams of lead, the second one allows you to convert $c$ grams of lead into $d$ grams of gold and third one allows you to convert $e$ grams of gold into $f$ grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable...\n\nHelp Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand.",
    "tutorial": "Fist, consider the case when all the numbers are non-zero. You can take a*c*e grams of sand, turn them into b*c*e grams of lead, and them turn into b*d*e grams of gold, and them turn into b*d*f grams of sand. If b*d*f > a*c*e, you can infinitely increase the amount of sand and consequently the amount of gold. Otherwise, if b*d*f <= a*c*e, it is impossible to get infinitely large amount of gold. The same is true when the fraction (a*c*e)/(b*d*f) has zero numerator only or zero denuminator only. Otherwise there is 0/0, and you have to check cases specially.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "65",
    "index": "B",
    "title": "Harry Potter and the History of Magic",
    "statement": "The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.\n\nSo, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.\n\nDue to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than $2011$, or strictly before than $1000$. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.",
    "tutorial": "The problem has greedy solution. Change a digit in the first date to make it as small as possible. At each of the next steps try all one-digit exchanges in the current date and choose one that makes the date not less than the previous one and as small as possible at the same time. If the last year won't exceed 2011 - the answer is found. Otherwise there is no solution. How to prove that? Consider any correct answer. Clearly, if the first date in it is different from the smallest possible number that can be obtained from the first of given years, your can put the smallest number instead of it. The second date can be exchanged by the smallest possible number not exceeding the first number, etc.Ar a result you obtain a greedy solution that is built by the algorithm described above. If the greedy solution doesn't exist, solution doesn't esist too. The problem also has a dynamic solution.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "65",
    "index": "C",
    "title": "Harry Potter and the Golden Snitch",
    "statement": "Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points $(x_{0}, y_{0}, z_{0})$, $(x_{1}, y_{1}, z_{1})$, ..., $(x_{n}, y_{n}, z_{n})$. At the beginning of the game the snitch is positioned at the point $(x_{0}, y_{0}, z_{0})$, and then moves along the polyline at the constant speed $v_{s}$. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point $(P_{x}, P_{y}, P_{z})$ and his super fast Nimbus 2011 broom allows him to move at the constant speed $v_{p}$ in any direction or remain idle. $v_{p}$ is not less than the speed of the snitch $v_{s}$. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry.",
    "tutorial": "Check for each segment in the polyline if Harry can catch the snitch in it. Note that since $v_{p}  \\ge  v_{s}$, if Harry can catch the snitch at some moment of time, he can catch it at any later moment. He can just follow snitch along its trajectory. So use binary search in each segment. About problems with EPS that participants got. The problems may be caused by 1) some EPS in the condition: while (leftTime + EPS < rightTime) <do binary search>. The task was to output with a fixed accurancy not only the time, but also the point coordinates. If the difference between the time and the right one is less than EPS, the difference between coordinates may be significantly larger. In such cases you should compare not arguments of a function, but values of the function with EPS. Or the way that I usually follow and that once was not liked by the teacher of numerical methods - to implement some fixed number of iterations of the binary search (say, 60). 2) EPS in comparison of time moments inside the binary search like this: if (currentTime + addTime > distance / potterSpeed - EPS) rightTime = currentTime; else leftTime = currentTime; Here it is better to remove EPS at all. Or to put EPS significantly smaller than the required accurancy for printing the point. (Code fragments are from Egor's solution.) Thus, there was no crime with severe limitations. Probably for such problems extreme accurancy tests should be in pretests? It is about principles of pretests making again. UPD. The problem has an analytical solution too. Consider the i-th segment. Let $(x_{i}, y_{i}, z_{i})$ and $(x_{None}, y_{None}, z_{None})$ be its ends, and let $t_{i}$ be the time required for the snitch to reach the beginning of the segment. Then at the moment t the snitch will be at the point (x, y, z), $x = x_{i} + (x_{None} - x_{i})(t - t_{i}) / T_{i}$, $y = y_{i} + (y_{None} - y_{i})(t - t_{i}) / T_{i}$, $z = z_{i} + (z_{None} - z_{i})(t - t_{i}) / T_{i}$, $T_{i}$ is a time necessary for snitch to overcome the segment. To catch the snitch at the point (x, y, z), Harry have to overcome the distance that squared is equal to $(x - P_{x})^{2} + (y - P_{y})^{2} + (z - P_{z})^{2}$ for the time t. It is possible if $(x - P_{x})^{2} + (y - P_{y})^{2} + (z - P_{z})^{2}  \\le  (tv_{p})^{2}$. To find the minimal proper moment t, solve the corresponding quadratic equation.",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 2100
  },
  {
    "contest_id": "65",
    "index": "D",
    "title": "Harry Potter and the Sorting Hat",
    "statement": "As you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the name of the house the student should enter.\n\nAt that the Hat is believed to base its considerations on the student's personal qualities: it sends the brave and noble ones to Gryffindor, the smart and shrewd ones — to Ravenclaw, the persistent and honest ones — to Hufflepuff and the clever and cunning ones — to Slytherin. However, a first year student Hermione Granger got very concerned about the forthcoming sorting. She studied all the literature on the Sorting Hat and came to the conclusion that it is much simpler than that. If the relatives of the student have already studied at Hogwarts, the hat puts the student to the same house, where his family used to study. In controversial situations, when the relatives studied in different houses or when they were all Muggles like Hermione's parents, then the Hat sorts the student to the house, to which the least number of first years has been sent at that moment. If there are several such houses, the choice is given to the student himself. Then the student can choose any of the houses, to which the least number of first years has been sent so far.\n\nHermione has already asked the students that are on the list before her about their relatives. Now she and her new friends Harry Potter and Ron Weasley want to find out into what house the Hat will put Hermione.",
    "tutorial": "Let $S_{i}$ be a set of all possible assignments of the first $i$ students to the houses, that is a set of tuples $(a_{1}, a_{2}, a_{3}, a_{4})$, where $a_{1}$ is a number of students sent to Gryffindor, $a_{2}$ - to Ravenclaw, etc. It's intuitively clear that these sets will not be large. So you can get $S_{None}$ from $S_{i}$ in a trivial way, and get finally $S_{n}$, and determine the answer from it. What is a rigorous proof of the algorithm? Let us have a set $S = {(a^{i}_{1}, a^{i}_{2}, a^{i}_{3}, a^{i}_{4})}_{None}$. Represent its elements as $a^{i}_{j} = b_{j} + x^{i}_{j}$, $x^{i}_{j}  \\ge  0$, where $b_{j}$ are maximal possible, i.e. there is i for each j such that $x^{i}_{j} = 0$. Let the tuple $(b_{1}, b_{2}, b_{3}, b_{4})$ be called the base part of S, and the set ${(x^{i}_{1}, x^{i}_{2}, x^{i}_{3}, x^{i}_{4})}_{None}$ be called the variant part of S. Initially for $S_{0}$ both base and variant parts are zeroes. Let us see how base and variant parts change when a current student is added. If a house is fixed for the student, only the base part changes. It increases by 1 at the position corresponding to the house. In particular, it follows that a set with every base part can be obtained (since the string given in the input can contain every combination of symbols G, H, R, S). If the current symbol in the string is '?', it can influence both base and variant parts. For example, for the string '????' we have: $S_{0} = {(0 + 0, 0 + 0, 0 + 0, 0 + 0)}$, $S_{1} = {(0 + 1, 0 + 0, 0 + 0, 0 + 0), (0 + 0, 0 + 1, 0 + 0, 0 + 0), (0 + 0, 0 + 0, 0 + 1, 0 + 0), (0 + 0, 0 + 0, 0 + 0, 0 + 1)}$, $S_{2} = {(0 + 1, 0 + 1, 0 + 0, 0 + 0), (0 + 1, 0 + 0, 0 + 1, 0 + 0), (0 + 1, 0 + 0, 0 + 0, 0 + 1), (0 + 0, 0 + 1, 0 + 1, 0 + 0), (0 + 0, 0 + 1, 0 + 0, 0 + 1), (0 + 0, 0 + 0, 0 + 1, 0 + 1)}$, $S_{3} = {(0 + 1, 0 + 1, 0 + 1, 0 + 0), (0 + 1, 0 + 1, 0 + 0, 0 + 1), (0 + 1, 0 + 0, 0 + 1, 0 + 1), (0 + 0, 0 + 1, 0 + 1, 0 + 1)}$, $S_{4} = {(1 + 0, 1 + 0, 1 + 0, 1 + 0)}$. Let us investigate the question of what species a variant part may have. It can be analyzed independently from a base one, taking into account that a base part can be any. Consider a directed graph with vertices corresponding to variant parts and with edges determined by the existence of at least one base part that let go from one variant part to another. We are interested only in vertices reachable from ${(0, 0, 0, 0)}$. Proposition. For all the vertices reachable from zero the following properties hold (1) $x^{i}_{j}  \\le  2$, (2) $k  \\le  13$. Let us prove that all the vertices not having the properties (1) and (2) are unreachable from zero. Consider a variant part with the property (1). To get all edges going from it you have to try all possible base parts. Note that base parts, that consist of the numbers 0, 1, 2, 3 and contain at lest one 0, are enough. Indeed, base part influence which elements are minimal, and 1 will be added to them. A base part can be always normed to contain at least one 0. If a base part contains numbers greater than 3, then the corresponding positions will never be minimal (since 4+0 > 0+2) and they can be changed equivalently by 3 (3+0 > 0+2). Unfortunately, my attempts to deal with cases by hand were unsuccessful, so I wrote the program that traverse the described graph. Starting from 0, it builds edges trying only \"small\" base parts described in the previous paragraph. As a result, the program obtains all the reachable variant parts (there is a little more than 1000 of them) and check (1) and (2) for them. In addition, the program helps to construct a test with $k = 13$.",
    "tags": [
      "brute force",
      "dfs and similar",
      "hashing"
    ],
    "rating": 2200
  },
  {
    "contest_id": "65",
    "index": "E",
    "title": "Harry Potter and Moving Staircases",
    "statement": "Harry Potter lost his Invisibility Cloak, running from the school caretaker Filch. Finding an invisible object is not an easy task. Fortunately, Harry has friends who are willing to help. Hermione Granger had read \"The Invisibility Cloaks, and Everything about Them\", as well as six volumes of \"The Encyclopedia of Quick Search of Shortest Paths in Graphs, Network Flows, the Maximal Increasing Subsequences and Other Magical Objects\". She has already developed a search algorithm for the invisibility cloak in complex dynamic systems (Hogwarts is one of them).\n\nHogwarts consists of $n$ floors, numbered by integers from $1$ to $n$. Some pairs of floors are connected by staircases. The staircases may change its position, moving exactly one end. Formally the situation is like this: if a staircase connects the floors $a$ and $b$, then in one move it may modify its position so as to connect the floors $a$ and $c$ or $b$ and $c$, where $c$ is any floor different from $a$ and $b$. Under no circumstances the staircase can connect a floor with itself. At the same time there can be multiple stairs between a pair of floors.\n\nInitially, Harry is on the floor with the number $1$. He does not remember on what floor he has lost the cloak and wants to look for it on each of the floors. Therefore, his goal is to visit each of $n$ floors at least once. Harry can visit the floors in any order and finish the searching at any floor.\n\nNowadays the staircases move quite rarely. However, Ron and Hermione are willing to put a spell on any of them to help Harry find the cloak. To cause less suspicion, the three friends plan to move the staircases one by one, and no more than once for each staircase. In between shifting the staircases Harry will be able to move about the floors, reachable at the moment from the staircases, and look for his Invisibility Cloak. It is assumed that during all this time the staircases will not move spontaneously.\n\nHelp the three friends to compose a searching plan. If there are several variants to solve the problem, any valid option (not necessarily the optimal one) will be accepted.",
    "tutorial": "Consider a graph with floors as vertices and staircases as edges. It is clear that Harry can visit the whole connected component in which he is currently located. Every edge can be used to reach a new vertex for not more than two times. If a connected component contains n vertices and m edges, only n - 1 edges are used to reach a new vertex during its traversal. The remaining m - n + 1 edges are not used to reach a new vertex in their initial placement. So they will be used to reach a new vertex not more than once. So using edges of only one connected component you can reach no more than n - m + 1 new vertices. Totally there are not more than $1\\,+\\,\\succ_{i=1}^{k}(n_{k}\\,+\\,m_{k}\\,-\\,1)\\,=\\,1\\,+\\,m\\,-\\,k\\,+\\,m$ reachable vertices. If m < k - 1, it is impossible to visit all the vertices. We show that otherwise (m >= k - 1), if the degree of the vertex 0 is different from zero, it is possible to visit all the vertices. In other words, there is such a traversal that every edge can be moved. Use depth-first search for the current component. If a current edge goes to an already visited vertex, move it to a new component and traverse it recursively. If a current edge goes to a new vertex, after you visit this vertex and go back, you also can move this edge to a new component. As a result each edge can be moved and used again, if you reach all the components. If a component contains at least one edge, you can go from it to the next one. First visit components with edges, and you will visit them all and by the inequality (m >= k - 1) there are enough edges to visit all the isolated vertices. If the degree of the vertex 1 is zero, you can not start a traversal before you move some edge to it. After that you can go by this edge and remove it with the vertex 1 from the graph, becase you can not use this edge once more. If the chose edge is a bridge, you get k connected components and m - 1 egdes. If it is not a bridge, you get k - 1 components and m - 1 edges. In the first case the inequality m >= k - 1 turns m >= k. In the second case - m >= k - 1. So if not all the edges are bridges, you should not take a bridge. If they all are bridges, you should disconnect an edge from a vertex of degree >= 2 not to came back to the initial situation with the zero degree of the first vertex. If there is no such vertex, it is easy to check that there is no solution.",
    "tags": [
      "dfs and similar",
      "implementation"
    ],
    "rating": 2900
  },
  {
    "contest_id": "66",
    "index": "A",
    "title": "Petya and Java",
    "statement": "Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.\n\nBut having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: \"Which integer type to use if one wants to store a positive integer $n$?\"\n\nPetya knows only 5 integer types:\n\n1) \\textbf{byte} occupies 1 byte and allows you to store numbers from $ - 128$ to $127$\n\n2) \\textbf{short} occupies 2 bytes and allows you to store numbers from $ - 32768$ to $32767$\n\n3) \\textbf{int} occupies 4 bytes and allows you to store numbers from $ - 2147483648$ to $2147483647$\n\n4) \\textbf{long} occupies 8 bytes and allows you to store numbers from $ - 9223372036854775808$ to $9223372036854775807$\n\n5) \\textbf{BigInteger} can store any integer number, but at that it is not a primitive type, and operations with it are much slower.\n\nFor all the types given above the boundary values are included in the value range.\n\nFrom this list, Petya wants to choose the smallest type that can store a positive integer $n$. Since BigInteger works much slower, Peter regards it last. Help him.",
    "tutorial": "In this problem you should answer to 4 questions: 1) Can we use type byte to store N? 2) Can we use type short to store N? 3) Can we use type int to store N? 4) Can we use type long to store N? We should check these conditions in the given order. If all these conditions are wrong, the answer is BigInteger. The simplest way to check these conditions is to store numbers as strings and write a function to compare such strings. In Java you can use type BigInteger.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "66",
    "index": "B",
    "title": "Petya and Countryside",
    "statement": "Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle $1 × n$ in size, when viewed from above. This rectangle is divided into $n$ equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.\n\nCreating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a $1 × 5$ rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:\n\nAs Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.",
    "tutorial": "Try to check all possibilities for creation artificial rain and calculate how many sections contain water. The maximal answer from all these possibilities is the answer for the problem. To calculate the answer for the given position we should check how many sections are to the left and to the right of the given section receive water. The complexity of this algorithm is O(N^2).",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "66",
    "index": "D",
    "title": "Petya and His Friends",
    "statement": "Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to $n$.\n\nLet us remind you the definition of the greatest common divisor: $GCD(a_{1}, ..., a_{k}) = d$, where $d$ represents such a maximal positive number that each $a_{i}$ ($1 ≤ i ≤ k$) is evenly divisible by $d$. At that, we assume that all $a_{i}$'s are greater than zero.\n\nKnowing that Petya is keen on programming, his friends has agreed beforehand that the $1$-st friend gives $a_{1}$ sweets, the $2$-nd one gives $a_{2}$ sweets, ..., the $n$-th one gives $a_{n}$ sweets. At the same time, for any $i$ and $j$ ($1 ≤ i, j ≤ n$) they want the $GCD(a_{i}, a_{j})$ not to be equal to $1$. However, they also want the following condition to be satisfied: $GCD(a_{1}, a_{2}, ..., a_{n}) = 1$. One more: all the $a_{i}$ should be distinct.\n\nHelp the friends to choose the suitable numbers $a_{1}, ..., a_{n}$.",
    "tutorial": "Consider N distinct prime numbers: p1, p2,  \\dots , pn. Let A=p1*p2* \\dots *pn. Then, easy to see, that the numbers A/p1, A/p2,  \\dots , A/pn can be considered as the answer. The special case is when N=2. In this case there is no answer. We can see that this solution needs long arithmetic. If we choose first n prime numbers as p1, p2,  \\dots , pn then the maximal number in the answer for all N<=50 contains less than 100 digits. Of course, there are other solutions. For example, if N=3 numbers 15, 10, 6 are the answer, and for N>3 numbers 15, 10, 6, 6*2, 6*3,  \\dots , 6*(N-2) are the answer.",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "66",
    "index": "E",
    "title": "Petya and Post",
    "statement": "Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then he must drive in the given car exactly one round along the circular road and return to the starting post office (the uncle can drive along the circle in any direction, counterclockwise or clockwise). Besides, since the car belongs to the city post, it should also be fuelled with gasoline only at the Post Office stations.\n\nThe total number of stations equals to $n$. One can fuel the car at the $i$-th station with no more than $a_{i}$ liters of gasoline. Besides, one can fuel the car no more than once at each station. Also, the distance between the $1$-st and the $2$-nd station is $b_{1}$ kilometers, the distance between the $2$-nd and the $3$-rd one is $b_{2}$ kilometers, ..., between the $(n - 1)$-th and the $n$-th ones the distance is $b_{n - 1}$ kilometers and between the $n$-th and the $1$-st one the distance is $b_{n}$ kilometers. Petya's uncle's high-tech car uses only one liter of gasoline per kilometer. It is known that the stations are located so that the sum of all $a_{i}$ is equal to the sum of all $b_{i}$. The $i$-th gas station and $i$-th post office are very close, so the distance between them is $0$ kilometers.\n\nThus, it becomes clear that if we start from some post offices, then it is not always possible to drive one round along a circular road. The uncle faces the following problem: to what stations can he go in the morning to be able to ride exactly one circle along the circular road and visit all the post offices that are on it?\n\nPetya, who used to attend programming classes, has volunteered to help his uncle, but his knowledge turned out to be not enough, so he asks you to help him write the program that will solve the posed problem.",
    "tutorial": "First of all we divide our problem into 2 parts: consider stations from which we can start if we are moving in the clockwise direction and stations from which we can start if we are moving in the counterclockwise direction. Obviously, if we know the solution of one of these problems, we know the solution of another problem. So, we may assume that stations are located in the counterclockwise order and we are moving in the counterclockwise direction. Consider the following differences: D1=a1-b1, D2=(a1+a2)-(b1+b2), D3=(a1+a2+a3)-(b1+b2+b3),  \\dots  Dn=(a1+a2+ \\dots +an)-(b1+b2+ \\dots +bn); Obviously if one of Di's is less than a zero, then we cannot drive one round along the road. Let D = min(Di) - we will use it later. Obviously, if D<0 then the first station cannot be the start station. Now, we can check with complexity O(n) whether the first station can be used as the starting point. Next, we want to show how we can check this for the second station with complexity O(1). To show this, consider: E1=D1-(a1-b1), E2=D2-(a1-b1),  \\dots  En=Dn-(a1-b1). Next, substitute Di in these equalities. We get the following: E1=(a1-b1)-(a1-b1)=0=(a2+a3+ \\dots +an+a1)-(b2+b3+ \\dots +bn+b1) - (a1+ \\dots +an=b1+ \\dots +bn=X) E2=(a1+a2)-(b1+b2)-(a1-b1)=a2-b2 E3=(a1+a2+a3)-(b1+b2+b3)-(a1-b1)=(a2+a3)-(b2+b3)  \\dots  En=(a1+a2+ \\dots +an)-(b1+b2+ \\dots +bn)-(a1-b1)=(a2+ \\dots +an)-(b2+ \\dots +bn) But it's easy to see that number E1 has the same meaning for the second station as number D1 for the first one. So, we just have to check min(Ei)>=0. But Ei=Di-(a1-b1), so we have to check min(Di-(a1-b1))>=0. Now, we can see that if min(Di)=Dk, then min(Di-(a1-b1))=Dk-(a1-b1). So, if we know Dk, that we can check whether the second station can be the starting point with complexity O(1). Similarly, we can check this for the third, the fourth,  \\dots , the nth stations. Now we should check the same things but assuming that the car is moving in the clockwise direction.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "67",
    "index": "A",
    "title": "Partial Teacher",
    "statement": "A teacher decides to give toffees to his students. He asks $n$ students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.\n\nHe looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.\n\nIt is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.",
    "tutorial": "Let the student at position 'x' receives 't' toffees Initially t=1 and temp=1 Now move towards RIGHT till you encounter a 'R' or end of string , if in the path 'L' is encountered increment t by 1.Following code performs the same : Now if temp is greater than t ; t is initialised as temp and temp as 1. Now move towards LEFT till you encounter a 'L' or beginning of string , if in the path 'R' is encountered increment by 1. Now if temp is greater than t ; t is initialised as temp. 't' is the required number of toffees thus obtained.",
    "code": "#include<iostream>\nusing namespace std;\nint main()\n{\n    int n,ans[1000],temp,i,j;\n    fill(ans,ans+1000,0);\n    char s[1000];\n    cin>>n;\n    cin>>s;\n    for(i=0;i<n;i++)\n    {\n        ans[i]=1;\n        temp=1;\n        for(j=i;j<n;j++)\n        {\n            if(s[j]=='R')\n                break;\n            else if(s[j]=='L')\n                temp++;\n        }\n        if(temp>ans[i])\n            ans[i]=temp;\n        temp=1;\n        for(j=i-1;j>=0;j--)\n        {\n            if(s[j]=='L')\n                break;\n            else if(s[j]=='R')\n                temp++;\n        }\n        if(temp>ans[i])\n            ans[i]=temp;       \n    }\n    for(i=0;i<n;i++)\n            cout<<ans[i]<<\" \";\n    return 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "67",
    "index": "B",
    "title": "Restoration of the Permutation",
    "statement": "Let $A = {a_{1}, a_{2}, ..., a_{n}}$ be any permutation of the first $n$ natural numbers ${1, 2, ..., n}$. You are given a positive integer $k$ and another sequence $B = {b_{1}, b_{2}, ..., b_{n}}$, where $b_{i}$ is the number of elements $a_{j}$ in $A$ to the left of the element $a_{t} = i$ such that $a_{j} ≥ (i + k)$.\n\nFor example, if $n = 5$, a possible $A$ is ${5, 1, 4, 2, 3}$. For $k = 2$, $B$ is given by ${1, 2, 1, 0, 0}$. But if $k = 3$, then $B = {1, 1, 0, 0, 0}$.\n\nFor two sequences $X = {x_{1}, x_{2}, ..., x_{n}}$ and $Y = {y_{1}, y_{2}, ..., y_{n}}$, let $i$-th elements be the first elements such that $x_{i} ≠ y_{i}$. If $x_{i} < y_{i}$, then $X$ is lexicographically smaller than $Y$, while if $x_{i} > y_{i}$, then $X$ is lexicographically greater than $Y$.\n\nGiven $n$, $k$ and $B$, you need to determine the lexicographically smallest $A$.",
    "tutorial": "For k=1, the given sequence is called Table of Inversions. We notice that if i>j, relative position of i effects the b_j while placing of j does not effect b_i. For this value of k, and sequnce {b_1, b_2, ..., b_n}, we first place n in the permutation. Then we chose (n-1) and check whether n-1 is 0 or 1. If its 0, It lies to the right of n, otherwise to the left of n. Similarly, we proceed for all values from n to 1. For k=1, there is only one possible permutation. But, when value of k is increased, b_(n-k+1), b_(n-k+2), ..., b_n are all 0. Since we need to find the lexicographically smallest permutation, we insert values from (n-k+1) to n in ascending order first. Then for each value i from n-k to 1, we choose first location in the permutation such that b_i is satisfied. Table of inversions finds application in Sorting where it is easy to represent the permutation using this.",
    "code": "#include <stdio.h>\nint main()\n{\n  int n,k,a[1002],b[1002],i,j,temp;\n  \n  scanf(\"%d%d\",&n;,&k;);\n  \n  for(i=1;i<=n;i++)\n  {\n    scanf(\"%d\",&b;[i]);\n  }\n  \n  for(i=k;i>=1;i--)\n    a[i] = n-i+1;\n  \n  for(i=n-k;i>=1;i--)\n  {\n    temp = b[i];\n    \n    for(j=n-i;j>=1 && temp>0;j--)\n    {\n      if(a[j]>=i+k)\n        temp--;\n      a[j+1] = a[j];\n    }\n    a[j+1] = i;\n  }\n  \n  for(i=n;i>=1;i--)\n    printf(\"%d \",a[i]);\n  printf(\"\n\");\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "67",
    "index": "C",
    "title": "Sequence of Balls",
    "statement": "You are given a sequence of balls $A$ by your teacher, each labeled with a lowercase Latin letter 'a'-'z'. You don't like the given sequence. You want to change it into a new sequence, $B$ that suits you better. So, you allow yourself four operations:\n\n- You can insert any ball with any label into the sequence at any position.\n- You can delete (remove) any ball from any position.\n- You can replace any ball with any other ball.\n- You can exchange (swap) two adjacent balls.\n\nYour teacher now places time constraints on each operation, meaning that an operation can only be performed in certain time. So, the first operation takes time $t_{i}$, the second one takes $t_{d}$, the third one takes $t_{r}$ and the fourth one takes $t_{e}$. Also, it is given that $2·t_{e} ≥ t_{i} + t_{d}$.\n\nFind the minimal time to convert the sequence $A$ to the sequence $B$.",
    "tutorial": "This is problem is an extension to the problem of String Edit Distance where you have to find the minimum cost of converting one string to another using only the following operations: 1) insert 2) delete 3) modify This problem has an extra operation of exchanging adjacent characters. It is similar to the Damerau Levenshtein distance where the operations have a fixed weight of 1. The pseudocode of the algorithm is: INF = a.length + b.length; H[0][0] = INF; // H is 2-D matrix of size (a.length+2)*(b.length+2) for(i = 0; i<=a.length; ++i) {H[i+1][1] = i; H[i+1][0] = INF;} for(j = 0; j<=b.length; ++j) {H[1][j+1] = j; H[0][j+1] = INF;} DA = new Array(C); //here C is the size of alhpabet set, here 'a' to 'z' } for(d = 0; d This finds application in spell checkers, in biology to measure the variation between DNA.",
    "code": "#include<stdio.h>\n#include<string.h>\n#include <iostream>\n#define MAX 5010\nusing namespace std;\nint main()\n{\n\tchar A[MAX],B[MAX];\n\tint length_A,length_B,INF,wd,wi,ws,wc,H[MAX+2][MAX+2],i,j,DA[MAX+10],d,DB,i1,j1,C,min[4],k,testcase;\n\t\n\t\t//scanf(\"%d%d%d%d\",&wi;,&wd;,&wc;,&ws;);\n\t\t//scanf(\"%s%s\",A,B);\n\t\t//printf(\"%s\n%s\n\",A,B);\n\t\tcin>>wi>>wd>>wc>>ws;\n\t\t//cout<<wi<<\" \"<<wd<<\" \"<<wc<<\" \"<<ws<<\" \";\n\t\tcin>>A>>B;\n\t\t//cout<<A<<\" \"<<B<<\" \";\n\t\tlength_A = strlen(A);\n\t\tlength_B = strlen(B);\n\t\t//for(int i=0;i<length_B;++i)\n\t\t\t//printf(\"%c\",B[i]);\n\t\t//cout<<endl;\n\t\t//printf(\"%s\n\",B);\n\t\tINF = length_A*wd + length_B*wi + 1;\n\t\tH[0][0] = INF;\n\t\t//printf(\"%s\n\",B);\n\t\tfor(i=0;i<=length_A;i++)\n\t\t{\n\t\t\tH[i+1][1] = i*wd;\n\t\t\tH[i+1][0] = INF;\n\t\t}\n\t\t//printf(\"%s\n\",B);\n\t\tfor(j=0;j<=length_B;j++)\n\t\t{\n\t\t\tH[1][j+1] = j*wi;\n\t\t\tH[0][j+1] = INF;\n\t\t}\n\t\t//printf(\"%s\n\",B);\n\t\tfor(d=0;d<=MAX;d++)\n\t\t\tDA[d]=0;\n\t\t//printf(\"hahah %s\n\",B);\n\t\tfor(i=1;i<=length_A;i++)\n\t\t{\n\t\t\tDB=0;\n\t\t\t//printf(\"%s\n\",B);\n\t\t\tfor(j=1;j<=length_B;j++)\n\t\t\t{\n\t\t\t\t//cout<<A[i-1]<<B[j-1]<<endl;\n\t\t\t\ti1=DA[(int)(B[j-1])-97];\n\t\t\t\tj1=DB;\n\t\t\t\t//if(((int)(A[i-1])-97)==((int)(B[j-1])-97))\n\t\t\t\t\t//d=0;\n\t\t\t\tif ( A[i-1]==B[j-1])\n\t\t\t\t\td=0;\n\t\t\t\telse\n\t\t\t\t\td=wc;\n\t\t\t\t//cout<<d<<endl;\n\t\t\t\tif(d==0)\n\t\t\t\t\tDB=j;\n\t\t\t\tint op=0;\n\t\t\t\tmin[0]=H[i][j]+d;\n\t\t\t\tmin[1]=H[i+1][j]+wi;\n\t\t\t\tmin[2]=H[i][j+1]+wd;\n\t\t\t\tmin[3]=H[i1][j1]+(i-i1-1)*wd+ws+(j-j1-1)*wi;\n\t\t\t\tH[i+1][j+1]=min[0];\n\t\t\t\tfor(k=1;k<4;k++)\n\t\t\t\t{\n\t\t\t\t\tif(H[i+1][j+1]>min[k]){\n\t\t\t\t\t\tH[i+1][j+1]=min[k];\n\t\t\t\t\t\top=k;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/*switch(op){\n\t\t\t\t\tcase 0:printf(\"c \");break;\n\t\t\t\t\tcase 1:printf(\"i \");break;\n\t\t\t\t\tcase 2:printf(\"d \");break;\n\t\t\t\t\tcase 3:printf(\"t \");break;\n\t\t\t\t}*/\n\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t\tDA[(A[i-1])-97]=i;\n\t\t\t//printf(\"\n\");\n\t\t}\n\t\t//printf(\"%d\n\",H[length_A+1][length_B+1]);\n\t\tcout<<H[length_A+1][length_B+1]<<endl;\n\t\t/*int x=length_A+1,y=length_B+1;\n\t\tfor( i=0;i<=x;++i){\n\t\t\tfor( j=0;j<=y;++j)\n\t\t\t\tprintf(\"%d \",H[i][j]);\n\t\t\tprintf(\"\n\");\n\t\t}\n\t\t* */\n\t\t\n\t\t\n\t//}\n}",
    "tags": [
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "67",
    "index": "D",
    "title": "Optical Experiment",
    "statement": "Professor Phunsuk Wangdu has performed some experiments on rays. The setup for $n$ rays is as follows.\n\nThere is a rectangular box having exactly $n$ holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line.\n\nProfessor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: \"Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?\".\n\nProfessor Wangdu now is in trouble and knowing your intellect he asks you to help him.",
    "tutorial": "For a given set of n rays, we can prepare the graph, having exactly n nodes. The n nodes represent the rays, numbered from 1 to n. There is an edge between the ith and jth node, if ith ray intersect the jth ray. A Clique of a graph is a complete subgraph. For this graph, the problem requires to find the Clique number, i.e. the number of nodes in the largest clique of that graph. The graph generated in this problem is permutation graph. The Clique number of a permutation grpah is Largest decreasing subsequence of the given permutation. By using the given two permutations, we can generate the 2 new permutations of n, such that 1st sequence is in the ascending order, and the second sequence is the permutation of n. For preparing 1st permutation to be in ascending order, we replace the ith ray in jth hole of 1st permutation by value j and replace the ith ray in second sequence by value j. So, now we have to calculate the Largest decreasing subsequence of the second sequence, which can be calculated in O(n log(n)) time complexity. This finds application in DNA computing and Adiabatic Quantum Computation.",
    "code": "#include<iostream>\n#include<algorithm>\n#include<cstdio>\n#include<vector>\nusing namespace std;\nvoid find_lis(vector<int> &a;, vector<int> &b;)\n{\n\tvector<int> p(a.size());\n\tint u, v;\n\tb.push_back(0);\n\tfor (int i = 1; i < a.size(); i++)\n    {\n\t\tif (a[b.back()] > a[i])\n        {\n\t\t\tp[i] = b.back();\n\t\t\tb.push_back(i);\n\t\t\tcontinue;\n        }\n\t\tfor (u = 0, v = b.size()-1; u < v;)\n        {\n\t\t\tint c = (u + v) / 2;\n\t\t\tif (a[b[c]] > a[i])\n                u=c+1;\n            else\n                v=c;\n\t\t}\n\t\tif (a[i] > a[b[u]])\n        {\n\t\t\tif (u > 0)\n                p[i] = b[u-1];\n\t\t\tb[u] = i;\n\t\t}\n\t}\n\tfor (u = b.size(), v = b.back(); u--; v = p[v])\n        b[u] = v;\n}\nint main()\n{\n        int n;\n        scanf(\"%d\",&n;);\n        int x,y,A[n],B[n],a[n];\n        for(int i=1;i<=n;i++)\n        {\n            scanf(\"%d\",&x;);\n            A[x]=i;\n        }\n        for(int i=1;i<=n;i++)\n        {\n            scanf(\"%d\",&x;);\n            B[x]=i;\n        }\n        for(int i=1;i<=n;i++)\n            a[B[i]-1]=A[i];\n        vector<int> seq(a, a+sizeof(a)/sizeof(a[0]));\n        vector<int> lis;\n        find_lis(seq, lis);\n        printf(\"%d\n\",lis.size());\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "67",
    "index": "E",
    "title": "Save the City!",
    "statement": "In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.\n\nSince the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence $AB$ along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points $X$, $Y$, $C$ and $A$ are visible from point $B$ but the points $E$ and $D$ are not.\n\n\\begin{center}\nFigure 1\n\\end{center}\n\n\\begin{center}\nFigure 2\n\\end{center}\n\nAssume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence $AB$ is parallel to $x$-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on $AB$ i.e. $(4, 8)$, $(5, 8)$, $(6, 8)$, $(7, 8)$ or $(8, 8)$. You can assume that no three consecutive points are collinear and all the corner points other than $A$ and $B$, lie towards same side of fence $AB$. The given polygon doesn't contain self-intersections.",
    "tutorial": "The problem is to find out the total number of points on the segment AB such that the whole polygon(compound) is watchable from it. It can be observed that a straight line segment XY is fully visible from another straight line segment PQ if the point X is visible from points P and Q, and point Y is also visible from points P and Q. So, the points on which watchtower can be setup will always consist of a range of integer points on AB. Also, to check if all the points on the polygon from a range of points, it is only needed to check all the vertices are visible from the range. In a naive brute force approach, we can proceed from A to B iterating by unit distance each time and checking if the all the other vertices of polygon are visible from it.or we can find for each vertex of polygon, the maximum range on AB, from which it is visible and in the take the intersection of all the ranges obtained. To find the range of each of the vertex, it is needed to check if the line visibility intersects any other edge in a way that it goes outside the polygon. This results in the complexity of O(kn) where k is the number of integral points on AB. Since, 0<=k<=1000000 and 3<=n<=1000, it will take 109 counts. Some very critical cases need to be taken care of which make the brute force even more complex.For e.g. the cases mentioned in the figure 1 in question has one of them. When it is checked whether the line of visibility for a point intersects another edge of the polygon, it should be taken care of that the point of intersection isn't the end point of an edge in case line of visibility is completely inside the polygon. This gives rise to another case in which the line of visibility is outside the polygon as for BD in the figure 1 in the question above. It can be done by checking if it the turns CBA and CBD are both either right turns or left turns. Main algorithm to find the number of points first finds the left intercept and right intercept for each vertex of polygon on AB in linear time. Right intercept a vertex X on AB is given by the rightmost point on AB from which the vertex X is visible.Similarly, left intercept is given by the leftmost point on AB from which the vertex X is visible. To find the right and left intercepts for the vertices, two scans are performed on the polygon, one from right to left as in along BCD..A and one along left to right as in along A..DCB. In each scan,the algorithm uses a stack to keep track of what can be said to be the internal convex hull for the polygon between point B and another vertex X of polygon for which the intercept is to be calculated. To calculate the intercept, we just need to find the nearest vertex Y on convex hull to X and extend XY to intersect AB as shown in figure 3 below. If the point of lies between A and B, then the point X is visible,otherwise it is not. To find the convex hull, the algorithm uses the concept that the turns on the hull will always be right or left depending on whether its left or right scan. Given three points A(x1,y1), B(x2,y2) and C(x3,y3), S is defined S = x3*(y1-y2) + y3*(x2-x1) + y2*x1 - y1*x2 The turn ABC is a left turn if S is positive, a right turn if S is negative and collinear if S=0. The pseudocode for the procedure to find the right intercepts for the points is given below: procedure RIGHTSCAN 1) (Initialize) r = STACK(1) = 2; s = STACK(2) = 3; t = 4; v = 2; u = 1; top = 2; 2) (See if t is contained in the convex path so far) x = s - 1; if rst is left turn and xst is right turn, then terminate with No Visibility; 3) (If rst is right turn, backtrack the stack to make the path convex) while top!= -1 and rst is right turn do top = top - 1; s = STACK(top); if top != -1 r = STACK(top-1); end; 4) (Compute right intercept and test whether it lies on AB) Compute right intercept rt of line segment from through s with the line through AB; If rt does not lie on AB, terminate with No Visibility; 5) (Store t into stack and move to next vertex) top = top + 1; STACK(top) = t; r = s; s = t; t = t + 1; if t != n go to step 2 Left Scan can be done similarly. So, now the main algorithm can be given by: procedure VISIBILITY call RIGHTSCAN call LEFTSCAN for i = 1 to n if ri is left of li, terminate with no possible solutions r=p2 l=p1 for i = 2 to n-1 if ri is to left of r r=ri if li is to right of l l=li if l is to left of r print the number of integer points from l to r else terminate with no visibility This finds application in surveillance and Robot control, Automated Cartography, Image Processing.",
    "code": "#include <iostream>\n\n#include <stack>\n\n#include <stdlib.h>\n\n#include <math.h>\n\nusing namespace std;\n\n\n\n#define EPS 1E-9\n\n\n\nstruct Point\n\n{\n\n  long double x,y;\n\n};\n\n\n\nlong double Left, Right;\n\nint up;\n\nint RST(Point r,Point s,Point t)\n\n{\n\n  long double val = t.x*(r.y-s.y) + t.y*(s.x - r.x) + r.x*s.y - r.y*s.x;\n\n  if(val < 0)\n\n    return -1;\n\n  return 1;\n\n}\n\n\n\nint RightScan(Point *a, int n)\n\n{\n\n  stack<int> st;\n\n  int r,s,t,u,v,x;\n\n  r=1;\n\n  st.push(r);\n\n  s = 2;\n\n  st.push(s);\n\n  t=3;\n\n  u=n; v=1;\n\n  \n\n  while(t!=n)\n\n  {\n\n    x=s-1;\n\n    if(RST(a[r],a[s],a[t])>0 && RST(a[x],a[s],a[t])<0)\n\n      {cout<<\"0\n\"; return 0;}\n\n    while(st.size()!=1 && RST(a[r],a[s],a[t])<0)\n\n    {\n\n      st.pop();\n\n      s = st.top();\n\n      if(st.size()!=1)\n\n      {\n\n        int temp = st.top();\n\n        st.pop();\n\n        r = st.top();\n\n        st.push(temp);\n\n      }\n\n    }\n\n\n\n    long double inx;\n\n    if(a[t].y-a[s].y < EPS && a[s].y-a[t].y < EPS)\n\n      {cout<<\"0\n\"; return 0;}\n\n      \n\n    inx = ((a[s].x - a[t].x)*(a[0].y-a[t].y)/(a[s].y-a[t].y)) + a[t].x;\n\n    if(up==-1)\n\n    {\n\n      if(inx > (a[0].x-EPS) && inx < (a[1].x+EPS))\n\n      {\n\n        if(inx<Right+EPS)\n\n          Right = inx;\n\n      }\n\n      else\n\n        {cout<<\"0\n\"; return 0;}\n\n    }\n\n    else\n\n    {\n\n      if(inx > (a[1].x-EPS) && inx < (a[0].x+EPS))\n\n      {\n\n        if(inx>Left-EPS)\n\n          Left = inx;\n\n      }\n\n      else\n\n        {cout<<\"0\n\"; return 0;}\n\n    }\n\n    st.push(t);\n\n    r=s; s=t; t++;\n\n  }\n\n  return 1;\n\n}\n\n\n\nint LeftScan(Point *a, int n)\n\n{\n\n  stack<int> st;\n\n  int r,s,t,x;\n\n  r=n;\n\n  st.push(r);\n\n  s = n-1;\n\n  st.push(s);\n\n  t=n-2;\n\n  \n\n  while(t!=1)\n\n  {\n\n    x=s+1;\n\n    if(RST(a[r],a[s],a[t])<0 && RST(a[x],a[s],a[t])>0)\n\n      {cout<<\"0\n\"; return 0;}\n\n    while(st.size()!=1 && RST(a[r],a[s],a[t])>0)\n\n    {\n\n      st.pop();\n\n      s = st.top();\n\n      if(st.size()!=1)\n\n      {\n\n        int temp = st.top();\n\n        st.pop();\n\n        r = st.top();\n\n        st.push(temp);\n\n      }\n\n    }\n\n    long double inx;\n\n    if(a[t].y-a[s].y < EPS && a[s].y-a[t].y < EPS)\n\n      {cout<<\"0\n\"; return 0;}\n\n    inx = ((a[s].x - a[t].x)*(a[0].y-a[t].y)/(a[s].y-a[t].y)) + a[t].x;\n\n    if(up==-1)\n\n    {\n\n      if(inx > (a[0].x-EPS) && inx < (a[1].x+EPS))\n\n      {\n\n        if(inx>Left-EPS)\n\n          Left = inx;\n\n      }\n\n      else\n\n        {cout<<\"0\n\"; return 0;}\n\n    }\n\n    else\n\n    {  \n\n      if(inx > (a[1].x-EPS) && inx < (a[0].x+EPS))\n\n      {\n\n        if(inx<Right+EPS)\n\n          Right = inx;\n\n      }\n\n      else\n\n        {cout<<\"0\n\"; return 0;}\n\n    }\n\n    st.push(t);\n\n    r=s; s=t; t--;\n\n  }\n\n  return 1;\n\n}\n\n\n\nint main()\n\n{\n\n  Point a[1010];\n\n  int top=2, n, i;\n\n  \n\n  cin>>n;\n\n  \n\n  for(i=0;i<n;i++)\n\n    cin>>a[i].x>>a[i].y;\n\n  \n\n  a[n].x = a[0].x;\n\n  a[n].y = a[0].y;\n\n  \n\n  if(a[2].y > a[0].y)\n\n  {\n\n    Left = a[1].x;\n\n    Right = a[0].x;\n\n    up=1;\n\n  }\n\n  else\n\n  {\n\n    Left = a[0].x;\n\n    Right = a[1].x;\n\n    up=-1;\n\n  }\n\n  if(RightScan(a,n))\n\n    if(LeftScan(a,n))\n\n    {\n\n      if(Right+EPS<Left)\n\n        {cout<<\"0\n\"; return 0;}\n\n      cout<<abs(floor(Right+EPS)-ceil(Left-EPS)+1)<<endl;\n\n    }\n\n}",
    "tags": [
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "69",
    "index": "A",
    "title": "Young Physicist",
    "statement": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.",
    "tutorial": "In this task all you had to do was to make sure that the sum of all  \\Sigma xi is 0, the sum of all  \\Sigma yi is 0 and that the sum of all  \\Sigma zi - 0 . We have not written that condition evidently in order that participants will have a chance to break a solution.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "69",
    "index": "B",
    "title": "Bets",
    "statement": "In Chelyabinsk lives a much respected businessman Nikita with a strange nickname \"Boss\". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.\n\nTo begin with friends learned the rules: in the race there are $n$ sections of equal length and $m$ participants. The participants numbered from $1$ to $m$. About each participant the following is known:\n\n- $l_{i}$ — the number of the starting section,\n- $r_{i}$ — the number of the finishing section ($l_{i} ≤ r_{i}$),\n- $t_{i}$ — the time a biathlete needs to complete an section of the path,\n- $c_{i}$ — the profit in roubles. If the $i$-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman.\n\nThe $i$-th biathlete passes the sections from $l_{i}$ to $r_{i}$ inclusive. The competitor runs the whole way in $(r_{i} - l_{i} + 1)·t_{i}$ time units. It takes him exactly $t_{i}$ time units to pass each section. In case of the athlete's victory on $k$ sections the man who has betted on him receives $k·c_{i}$ roubles.\n\nIn each section the winner is determined \\textbf{independently} as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed.\n\nWe should also add that Nikita can bet on each section and on any contestant running in this section.\n\nHelp the friends find the maximum possible profit.",
    "tutorial": "In this problem, in fact, you should find a winner at every section. For each section, you must do a full search of all competitors to find a competitor with a minimum section time, which ran that section. Asymptotic of the solution is O(nm).",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "69",
    "index": "C",
    "title": "Game",
    "statement": "In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game \"HaresButtle\", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts.\n\nAfter the composing composite artifact, all the components disappear.\n\nKostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts.",
    "tutorial": "In this task, you had to update the collection of artifacts, which belong to Kostya's friends, after each purchase . You had to set a matrix c[i][j] - number of the j-th basic artifact that is required in order to collect the i-th component artifact. Further, one can make a matrix of composite artifacts, where a[i][j] is number of the j-th basic artifact of the i-th friend and a similar matrix b of composite artifacts, and check whether i-th friend has any a composite artifact of O (MN) after each i-th friend's purchase. Check whether one component of the artifact assembles for O (N): while checking whether the i-th friend is able to collect the j-th artifact you have to check, if there is such u, that c[j [u]> a[i][u], if so, the j-th artefact will not be collected, if not, then you have to increase the b[i][j] and update the values in a[i]). So.the asymptotics of the processing of all purchases will be O (NQM). Then, we need to make a list of artifacts for each person, keeping their quantity(a total of O (KN + KM), and sort it (a total of O (QlogQ)).",
    "tags": [
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "69",
    "index": "D",
    "title": "Dot",
    "statement": "Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name \"dot\" with the following rules:\n\n- On the checkered paper a coordinate system is drawn. A dot is initially put in the position $(x, y)$.\n- A move is shifting a dot to one of the pre-selected vectors. Also each player can once per game symmetrically reflect a dot relatively to the line $y = x$.\n- Anton and Dasha take turns. Anton goes first.\n- The player after whose move the distance from the dot to the coordinates' origin exceeds $d$, loses.\n\nHelp them to determine the winner.",
    "tutorial": "This game is over, because except for a finite number (2) of reflections about the line y = x,the coordinates are changed to non-negative integer (and at least one coordinate is changed to a positive number). Algorithm for solving this problem is DFS / BFS (states) where the state is a pair of coordinates, and two logical variables, which denote if the 1 (2) player had reflected a point about the line y = x. Total number of states is obtained by S <= 4D^2 (pairs of coordinates) * 4 (Boolean variables). Processing of one state takes O (N) actions (do not forget to try to reflect the point about the line y = x, if the player had not made it earlier in the game). Thereby, we have the overall asymptotic O (ND^2), which works on C + + in less than 200ms.",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 1900
  },
  {
    "contest_id": "69",
    "index": "E",
    "title": "Subsegments",
    "statement": "Programmer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in $O(\\log n)$, which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find the maximum element of those that occur on the given segment exactly once. Help Sasha solve this problem.",
    "tutorial": "To solve this problem you have to do a \"move\" subsegment and know : 1. The set B of numbers, meeting once, with the function of extracting the maximum for O (logN) 2.The set of numbers appearing on this subsegments with keeping the number of times,that this number is found on this subsegments, with function of verifying how many times the number in this subsegments for O (logN). While moving a segment from (a[i] .. a[i + k - 1]) for 1 item left (a[I + 1] .. a[I + k]) you have to: 1) Check whether a[i] with a[I + k]. If yes, then there is no need to modify the set, otherwise proceed to item 2 and 3. 2) Check how many times we have a[i] in the set A: if 2, then add a[i] to B, if 1, then remove it from A and B. Do not forget to reduce the corresponding number of occurrences of a[i] in the current segment 1. 3) Check, how many times we have a[I + k] in the set A: if 0, then add a[i] in the B and A, if 1, then remove it from B. Do not forget to increase the corresponding number of occurrences of a[i] the current interval to 1. After that, if the set is not empty, we should take peak from it. So the asymptotics of this process will be O(NlogN). As such data structures set / map(for those who use C + +) and the Cartesian tree are suitable.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "70",
    "index": "A",
    "title": "Cookies",
    "statement": "Fangy collects cookies. Once he decided to take a box and put cookies into it in some way. If we take a square $k × k$ in size, divided into blocks $1 × 1$ in size and paint there the main diagonal together with cells, which lie above it, then the painted area will be equal to the area occupied by one cookie $k$ in size. Fangy also has a box with a square base $2^{n} × 2^{n}$, divided into blocks $1 × 1$ in size. In a box the cookies should not overlap, and they should not be turned over or rotated. See cookies of sizes $2$ and $4$ respectively on the figure:\n\nTo stack the cookies the little walrus uses the following algorithm. He takes out of the repository the largest cookie which can fit in some place in the box and puts it there. Everything could be perfect but alas, in the repository the little walrus has infinitely many cookies of size $2$ and larger, and there are no cookies of size $1$, therefore, empty cells will remain in the box. Fangy wants to know how many empty cells will be left in the end.",
    "tutorial": "Let's define a half-filled square of size $k$ as an empty square of size $k$ after adding a cookie of the biggest posible size. Notice, that if we add a cookie of the biggest possible size into the half-filled square of size $2^{n}  \\times  2^{n}$, it will be divided into three half-filled squares of size $2^{None}  \\times  2^{None}$ and one filled square. After performing the same actions with the three half-filled squares we will get nine half-filled squares of size $2^{None}  \\times  2^{None}$ and so on. It's easy to get the formula $f(n) = 3 * f(n - 1)$, $f(0) = f(1) = 1$. $3^{None}$ (for $n > 0$) and $1$ (for $n = 0$).",
    "tags": [
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "70",
    "index": "B",
    "title": "Text Messaging",
    "statement": "Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing $n$ characters (which is the size of one text message). Thus, whole sentences and words get split!\n\nFangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).\n\nThe little walrus's text looks in the following manner:\n\n\\begin{verbatim}\nTEXT ::= SENTENCE | SENTENCE SPACE TEXT\nSENTENCE ::= WORD SPACE SENTENCE | WORD END\nEND ::= {'.', '?', '!'}\nWORD ::= LETTER | LETTER WORD\nLETTER ::= {'a'..'z', 'A'..'Z'}\nSPACE ::= ' '\n\\end{verbatim}\n\nSPACE stands for the symbol of a space.\n\nSo, how many messages did Fangy send?",
    "tutorial": "It's obviously, that sentences should be added into the SMS greedily. Really, if we put the sentence into the new message, when it's possible to add into previous, the number of messages may be increased. The only thing you should pay attention is correct processing whitespaces between the sentences.",
    "tags": [
      "expression parsing",
      "greedy",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "70",
    "index": "C",
    "title": "Lucky Tickets",
    "statement": "In Walrusland public transport tickets are characterized by two integers: by the number of the series and by the number of the ticket in the series. Let the series number be represented by $a$ and the ticket number — by $b$, then a ticket is described by the ordered pair of numbers $(a, b)$.\n\nThe walruses believe that a ticket is lucky if $a * b = rev(a) * rev(b)$. The function $rev(x)$ reverses a number written in the decimal system, at that the leading zeroes disappear. For example, $rev(12343) = 34321$, $rev(1200) = 21$.\n\nThe Public Transport Management Committee wants to release $x$ series, each containing $y$ tickets, so that \\textbf{at} \\textbf{least} $w$ lucky tickets were released and the total number of released tickets ($x * y$) were minimum. The series are numbered from $1$ to $x$ inclusive. The tickets in each series are numbered from $1$ to $y$ inclusive. The Transport Committee cannot release more than $max_{x}$ series and more than $max_{y}$ tickets in one series.",
    "tutorial": "Let's learn how to solve more easy problem: it's need to count a number of lucky tickets with $1  \\le  a  \\le  x$ and $1  \\le  b  \\le  y$. Rewrite sentence $a * b = rev(a) * rev(b)$ as $a / rev(a) = rev(b) / b$. Brute all $a$ and count a number of irreducible fractions $a / rev(a)$ using, for example, map from STL. Now for every $b$ you should count the number of fractions $a / rev(a)$ equal to $rev(b) / b$ and add to answer. Come back to our problem. If the number of lucky tickets with $1  \\le  a  \\le  max_{x}$ and $1  \\le  b  \\le  max_{y}$ less than $w$, it should be printed $- 1$. If the solution exist, let's use the method of two pointers. We need to keep up the quantity of lucky tickets with $1  \\le  a  \\le  x$ and $1  \\le  b  \\le  y$ for some state $(x, y)$ an change it to (x,y+1), (x+1,y), (x,y-1), (x-1,y). That's why we create two structures of type map (named m1 and m2). Let's learn how to change state from (x,y) to (x,y+1), (x+1,y), (x,y-1), (x-1,y). If we want to increase (decrase) the value of $x$, we should add (subtract) m2[x/rev(x)] to (from) the number of lucky tickets and increase (decrease) m1[x/rev(x)] by one. In the case of changing $y$ you should do the similar actions. Let's set the state $(x, y)$, where $x = max_{x}$, $y = 1$ and count the quantity of lucky tickets for it. We will be increase $y$, while the number of lucky tickets is less than $w$. Obviously, that it will be the least $y$ for $x$, such as it will be enough lucky tickets in the range. Relax the answer. You had to decrease $x$ by one and do the same actions while $x$ is greater than one. The anser have the least value of $x * y$ because we relaxed it with the optimal state for every $x$. So, the $x$ was equael to every value between $1$ and $max_{x}$ not more than once. The similar is correct for $y$ because it was only increasing. The time need for change the value in map is O(log(map_size)), that's why the algorithm lave an asymptotic form as $O(max_{x} * log(max_{y}) + max_{y} * log(max_{x}))$.",
    "tags": [
      "binary search",
      "data structures",
      "sortings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "70",
    "index": "D",
    "title": "Professor's task",
    "statement": "Once a walrus professor Plato asked his programming students to perform the following practical task.\n\nThe students had to implement such a data structure that would support a convex hull on some set of points $S$. The input to the program had $q$ queries of two types:\n\n1. Add a point with coordinates $(x, y)$ into the set $S$. Note that in this case the convex hull of $S$ could have changed, and could have remained the same.\n\n2. Say whether a point with coordinates $(x, y)$ belongs to an area limited by the convex hull, including the border.\n\nAll the students coped with the task. What about you?",
    "tutorial": "Notice, that any point from the triangle based on first three points will be into the area bounded with the convex hull in the future. Let choose one of these points ad set it as the origin. All points of convex hull will keep in structure like map in C++, where the key is the angle of vector from the origin to a point. No two points from the hull will have the same angle. How to answer the second-type queries? For the point from the query ($A$) let's find the closest point clockwise ($B$) and the closest point anticlockwise ($C$). If the vectors $AB$ and $AC$ make up a clockwise rotation, then point A doesn't lay into the convex or on it's bounds. How to answer the first-type queries? If the point from the query ($C$) lays into the convex hull, then do nothing else let's find two closest points clockwise relative to point $C$ (the closest will be named $A$, tho other will be named $B$). If rotation from the vector $AB$ to the vector $AC$ is a counterclockwise rotation then processing points laying clockwise relative to point $C$ in ended, else you have to delete point $A$ from the structure and repeat the same actions. The similar actions you should apply to points anticlockwise relative to point $C$. All points will be added and deleted in the structure not more than once. These operations need $O(log(h))$ time, where $h$ is a number of point in convex hull. Total asymptotic form is $O(q * log(h))$.",
    "tags": [
      "data structures",
      "geometry"
    ],
    "rating": 2700
  },
  {
    "contest_id": "70",
    "index": "E",
    "title": "Information Reform",
    "statement": "Thought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal.\n\nThe North Pole governor decided to carry out an information reform. Several cities were decided to be chosen and made regional centers. Maintaining a region center takes $k$ fishlars (which is a local currency) per year. It is assumed that a regional center always has information on the latest news.\n\nFor every city which is not a regional center, it was decided to appoint a regional center which will be responsible for keeping this city informed. In that case the maintenance costs will be equal to $d_{len}$ fishlars per year, where $len$ is the distance from a city to the corresponding regional center, measured in the number of roads along which one needs to go.\n\nYour task is to minimize the costs to carry out the reform.",
    "tutorial": "Notice next facts. If we have the fixed state of some regional centers then for every city will be assigned the nearest regional center. The regional center of some city will be assigned for all cities between this city and it's regional center. It means that tree should be divided into some subtrees. Also define $d[0] = 0$. Let's solve the problem using \"crossed\" Dynamic Programming. First function of DP. D1(T, g, x, s) will be responsible for forming the subtree with the regional center g. T is somme subtree of tree from the input defined with edge $uv$. regional center g must be situated in T. Let's consider that $g$ is assigned to $v$. The aim will be considered in choosing edges which will bound our subtree. Picture: Green and red edges connect cities which g was assigned. Purple edge bounds the set of such cities. Notice, that vertexes laying on the red pass cannot be bounding, because g is assigned to v. Let $xs$ edge be bounding, then for subtree $T'$ (vertexes of it's subtree are into the circle) call the secnod funtion of DP $D2(T')$. The second function of DP will brute every point of subtree $T'$ as a regional center and call D1. D1 have $O(n^{3})$ states, because the number of subtrees $T$ is $O(n)$, number of options to choose g is the same and pair (x;s) makes up an edge, number of edges is 2*n-2. The second function of DP has $O(v)$ states and transition need $O(v)$ iterations. Thats why solution need $O(n^{3})$ memory and have asymptotic form $O(n^{3})$.",
    "tags": [
      "dp",
      "implementation",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "71",
    "index": "A",
    "title": "Way Too Long Words",
    "statement": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.\n\nLet's consider a word too long, if its length is \\textbf{strictly more} than $10$ characters. All too long words should be replaced with a special abbreviation.\n\nThis abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.\n\nThus, \"localization\" will be spelt as \"l10n\", and \"internationalization» will be spelt as \"i18n\".\n\nYou are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.",
    "tutorial": "In this problem you can just do what is written in the statement. Let read all words. For each of them compute its length $L$, its the first and the last letter. If $L > 10$, output word without any changes, otherwise output the first letter, next $L - 2$ and finally the last letter.",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "71",
    "index": "B",
    "title": "Progress Bar",
    "statement": "A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.\n\nA bar is represented as $n$ squares, located in line. To add clarity, let's number them with positive integers from $1$ to $n$ from the left to the right. Each square has saturation ($a_{i}$ for the $i$-th square), which is measured by an integer from $0$ to $k$. When the bar for some $i$ ($1 ≤ i ≤ n$) is displayed, squares $1, 2, ... , i - 1$ has the saturation $k$, squares $i + 1, i + 2, ... , n$ has the saturation $0$, and the saturation of the square $i$ can have any value from $0$ to $k$.\n\nSo some first squares of the progress bar always have the saturation $k$. Some last squares always have the saturation $0$. And there is no more than one square that has the saturation different from $0$ and $k$.\n\nThe degree of the process's completion is measured in percents. Let the process be $t$% completed. Then the following inequation is fulfilled:\n\n\\[\n{\\frac{\\sum_{i=1}^{n}a_{i}}{n k}}\\leq{\\frac{t}{100}}<{\\frac{(\\sum_{i=1}^{n}a_{i})+1}{n k}}.\n\\]\n\nAn example of such a bar can be seen on the picture.\n\nFor the given $n$, $k$, $t$ determine the measures of saturation for all the squares $a_{i}$ of the progress bar.",
    "tutorial": "At first, compute $z=\\sum_{i=1}^{n}a_{i}$. It equals $ \\lfloor  mnk / 100 \\rfloor $, where $ \\lfloor  x \\rfloor $ is rounding down. Next we fill first $ \\lfloor  z / k \\rfloor $ squares with a saturation $k$. $( \\lfloor  z / k \\rfloor  + 1)$-th square (if it exists) we fill in a saturation $z -  \\lfloor  z / k \\rfloor  k$. All other squares we leave with a saturation $0$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "71",
    "index": "C",
    "title": "Round Table Knights",
    "statement": "There are $n$ knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.\n\nMerlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.\n\nA convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.\n\nOn a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.\n\nKing Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.",
    "tutorial": "Define an good polygon as a regular polygon which has a knight in a good mood in every of its vertex. Side of polygon we will measure in arcs which is obtained by dividing border of round table with knights. Freeze the length of the side. Let this length equals $k$. Observe that the regular polygon with such length of side exists only if $k$ divides $n$. We have exactly $k$ of such polygons. Every of them has exactly $n / k$ vertices. Check every of the polygons for goodness by review all of its vertices. If sum of vertices with knight in a good mood equals to $n / k$, this polygon is good. Checking of all polygons with some frozen length of side works in an $O(n)$. Now observe that $n$ has $O({\\sqrt{n}})$ of divisors. Really, all divisors (may be except only one) we can divide into pairs (for $i$ corresponds $n / i$, for $i = n / i$ there is no pair). One of divisors in every pair less than $\\sqrt{n}$. It means thah number of pairs no more than $\\sqrt{n}$ and number of divisors no more than $2{\\sqrt{n}}$. It gives solution - iterate over all divisors of $n$ and for every of them check existence of good polygon with length side equals this divisor. Solution has an $O(n{\\sqrt{n}})$ time. In reality for big $n$ is has $O({\\dot{\\sqrt{n}}})$ divisors. So solution actually has $O(n^{4 / 3})$-complexity. For all numbers less than $10^{5}$ maximal number of divisors is 128. UPD. There was found an $O(n\\log n)$ solution by some participants. This solution uses following idea. If we have a good polygon with $xy$ vertices, we also have a good polygon with $x$ vertices. So we can check only prime divisors of $n$ (except 2 - here we must check 4).",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "71",
    "index": "D",
    "title": "Solitaire",
    "statement": "Vasya has a pack of $54$ cards ($52$ standard cards and $2$ distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them.\n\nVasya lays out $nm$ cards as a rectangle $n × m$. If there are jokers among them, then Vasya should change them with some of the rest of $54 - nm$ cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. \\textbf{in a single copy}). Vasya tries to perform the replacements so that the solitaire was solved.\n\nVasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares $3 × 3$, inside each of which all the cards either have the same suit, or pairwise different ranks.\n\nDetermine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible.",
    "tutorial": "This problem can be divided into some subproblems. Author's solution means following ones: 1. Check validness of square $3  \\times  3$. Square is valid if all cards in it has equal suit or different rank. You may not check equal suit because equal suits imply different ranks. 2. Find 2 valid noninetsect squares $3  \\times  3$ or return thah there are no ones. You can check all pairs of squares for inetsection. If some pair has no intersections check them with solution of subproblem 1. 3. Build set of cards which can be replaced with jokers. Generate full deck without jokers and drop from it all cards which in rectangle $n  \\times  m$ are present. 4. Find number of jokers and its positions in rectangle. 5. Main subproblem. At first, solve subproblems 3 and 4. Now replace jokers in rectangle with cards from deck from subproblem 3 by all possible ways. For every replace solve subproblem 2. Arter all of variants of replacement just output answer. There are $O(n^{2}m^{2})$ solution with small constant.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "71",
    "index": "E",
    "title": "Nuclear Fusion",
    "statement": "There is the following puzzle popular among nuclear physicists.\n\nA reactor contains a set of $n$ atoms of some chemical elements. We shall understand the phrase \"atomic number\" as the number of this atom's element in the periodic table of the chemical elements.\n\nYou are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times.\n\nThe aim is getting a new pregiven set of $k$ atoms.\n\nThe puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle.",
    "tutorial": "At first, you can use some search engine for find periodic table in some printable form. Next use copy-paste (one or several times) and format it by deleting all excess. It is mechanical work for no more than 5 minutes. Also some parser may be written. Note than author's solution does not mean write 100 symbols by hand from a picture. Next build some functions which transform symbols into numbers and vice versa. So, we have some set of numbers. We need summarize some from them and get some another set of numbers. We will use dymanic programming over subsets. Compute the first dp dp1[mask]->sum. For each subset calculate sum of numbers of all atoms in this subset. It can be done in $O(2^{n}n)$. Now compute the second dp dp2[mask]->length. The \"length\" is a length of some prefix of result sequence of atoms which can be obtained by subset mask. If length -1, it means that it is impossible to get any prefix from this subset. The second dp we can calculate in $O(3^{n})$. Iterate over all masks and if dp2[mask]!=-1, iterate all its subsets of remained atoms (invert mask and get all its submasks). If some subset has sum of numbers which equals number of (dp2[mask]+1)-th atom from result set, recalculate dp2[mask XOR submask]=dp2[mask]+1. At end, if dp2[$2^{n} - 1$]=k, there are solution. There are $O(3^{n} + 2^{n}n)$ solution. In this problem some brutforce solutions are passed because it is difficult to pick up some counterexample. UPD. SkorKNURE found a solution in $O(2^{n}n)$. This solution is some modification of the author's solution. Instead of dp2 calculate dp dp2'[mask]->(i,j), where i is a length of prefix which mask covers and j is part of number of (i+1)-th atom which mask covers. Iterate over all masks. For each mask iterate over all its 0-bits$$ (they are atoms which cover nothing from the finish set). We try to cover with this 0-bit a remainder of number of the (i+1)-th atom from the finish set. Let atomic number of an atom for current 0-bit is p and this atom is q-th in the start set. If we cover with this atom only part of the remainder of number of the (i+1)-th atom, dp2'[mask XOR (1<<q)]=(i,j+p). If we cover with this atom the remainder fully (and exactly this remainder, no more!), dp2'[mask XOR (1<<q)]=(i+1,0). Now dp1 is useless. If at end dp2'[$2^{n} - 1$]=(k,0), solution exists (it is easy to restore it), otherwise there is no solution.",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "73",
    "index": "A",
    "title": "The Elder Trolls IV: Oblivon",
    "statement": "Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is \"Unkillable\"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many!\n\nVasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size $x × y × z$, consisting of undestructable cells $1 × 1 × 1$. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value.\n\nAll parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut.\n\nVasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most $k$ times.\n\nVasya's character uses absolutely thin sword with infinite length.",
    "tutorial": "Let's call the monster dimension sizes as x1, x2, x3. 1. O(min(k, x1 + x2 + x3)) solution We can make at most (x1 - 1) + (x2 - 1) + (x3 - 1) cuttings, so we may assume that k <= x1 + x2 + x3 - 3. For each of the three dimensions we will store an integer ai - number of cuttings performed through the corresponding dimension. Let's perform the following actions k times: consider all numbers ai which we may increase (ai < xi - 1) , call these dimensions \"uncompleted\". Select the minimum number aj among all uncompleted ai and perform a cut through the corresponding dimension (aj will be increased by 1 as the result). Now let's consider the resulting set after k actions: {a1, a2, a3}. Using the described algorithm we grant that the maximum element of this set is as little as possible and the minimum element is as big as possible. Because the sum a1 + a2 + a3 = k is fixed, we get the maximum product (a1 + 1) * (a2 + 1) * (a3 + 1) which is the answer for the problem. 2. O(1) solution Instead of simulation all the k actions we may quickly determine values of numbers ai after using the algorithm described above. Let x - the smallest value among (xi - 1). When x * 3 >= k on each of the algorithm iterations all three dimensions will be uncompleted. It means that during the first (k / 3) * 3 steps each of numbers ai will be increased by (k / 3). Then 0, 1 or 2 numbers ai will be increased by 1 subject to value of k % 3. So, we have found values ai. Otherwise (x * 3 < k) during the first x * 3 steps each of ai will be increased by x. After that we will have at most two uncompleted dimensions which can be processed a similar way (we should choose the minimum value x among the remaining uncompleted dimensions).",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "73",
    "index": "B",
    "title": "Need For Brake",
    "statement": "Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game!\n\n$n$ racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to $n$-th (no two racers share the same place) and first $m$ places are awarded. Racer gains $b_{i}$ points for $i$-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer $i$ is $a_{i}$ points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.\n\nUnfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship.",
    "tutorial": "We may assume that we have exactly n awarded places but some of them give 0 points. Let's sort places by amount of points (bi) and racers by amount of currently gained points (ai). First let's find the best place Vasya can reach. In the best case he will get b0 points (where b0 is the greatest number among bi). So, let the total Vasya's point is v. Now we should to distribute other prize points to racers so that the number of racers better than Vasya will be minimal. For doing that we are to give maximum number of prizes so that corresponding racers will have less than v points. Note that if we can give k prizes keeping this property, than we can give k \"cheapest\" prizes too. The following statement is also true: if we can get a prize with t points to racer i and to racer j , ai > aj, then it is better to give this prize to racer i. Formally: if there exists a way to give k prizes where this prize will get racer j, than there exists a way to give k prizes where this prize will get racer i. It can be proven the following way. Consider a way to give k prizes where racer j got prize with t points, racer i - s points or didn't get prize at all. In the first case we can swap prizes for racers i and j: ai > aj and ai + s < v (since racer i have got the prize), so aj + s < v, and ai + t < v i.e. this change is acceptable. In the second case we can just give the prize t to racer i instead of racer j. In the both cases we get a way to give k prizes where racer i receive prize t. Now including this statement we may give prizes to racers using the following greedy algorithm. Let's begin to give prizes starting from the cheapest one and check the racers starting from the best one (of course excluding Vasya and the best prize). For each prize i we will go through the racers until applicable racer (j) found: bi + aj < v. If no such racers remain we are unable to give more prizes without violating the rule (racers should have less than v points). In this case we should stop the algorithm and the answer is n - k where k is the number of prizes we have given. If we have found such racer j we can give him prize bi and go to the next prize. Complexity of this step is O(n). Similarly we can find the worst place for Vasya. For doing that we should give him the cheapest prize (note it may have positive points though). After that we should distribute the prizes iterating over prizes from the largest to cheapest and check racers from the worst to the best one trying to make sum of racer's points more than v. Total complexity of the described algorithm is O(n * log(n)) because we have to sort prizes and racers.",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "73",
    "index": "C",
    "title": "LionAge II",
    "statement": "Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character — non-empty string $s$, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than $k$ letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters $x$ and $y$ ($x$ immediately precedes $y$) the bonus $c(x, y)$ is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most $k$ letters in the name of the Vasya's character.",
    "tutorial": "It is easy to see that if we put some symbol c at position p of the string s it will not affect symbols at positions (p+2) and greater. So we have a standard DP problem. State of the dynamic is described by three parameters: p - the number of already processed symbols (or the index of currently processed symbol of the string), c - the previous symbol, t - the number of allowed symbol changes. To calculate the answer for a state we should choose the best value among all symbols for current position (when t > 0) or just go to the index (p + 1) with current symbol s[p]. Thus we get the followings formulas: d[n][*][*] = 0 d[p][c][t] = d[p + 1][s[p]][t] + bonus[c][s[p]] when t = 0 d[p][c][t] = max(d[p + 1][c'][t - (c' <> s[p])] + bonus[c][c']) where n is the length of string s. Computation complexity of the algorithm is O(n * k * h^2), where h is the alphabet size (h = 26 for current problem).",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "73",
    "index": "D",
    "title": "FreeDiv",
    "statement": "Vasya plays FreeDiv. In this game he manages a huge state, which has $n$ cities and $m$ two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every city all the cities of the province, but there are no roads between provinces.\n\nUnlike other turn-based strategies, in FreeDiv a player has the opportunity to build tunnels between cities. The tunnels are two-way roads along which one can move armies undetected by the enemy. However, no more than one tunnel can be connected to each city. As for Vasya, he wants to build a network of tunnels so that any pair of cities in his state were reachable by some path consisting of roads and a tunnels. But at that no more than $k$ tunnels are connected to each province (otherwise, the province will be difficult to keep in case other provinces are captured by enemy armies).\n\nVasya discovered that maybe he will not be able to build such a network for the current condition of the state. Maybe he'll have first to build several roads between cities in different provinces to merge the provinces. Your task is to determine the minimum number of roads Vasya needs to build so that it was possible to build the required network of tunnels in the resulting state.",
    "tutorial": "First, let's divide graph to connected components (provinces). Next, we consider only new graph on these components - for each province we assign a vertex of the graph. Let the total number of provinces is n. Initially the graph is empty since there are no roads between different provinces. Also for each province we have a limit of the number of tunnels that can be constructed from this province: ki = min (k, ci) where ci - the number of cities which was originally contained in the province (component) i. The resulting provinces graph should be connected after building tunnels and roads. When k = 1 we have to build at least n - 2 roads, otherwise the graph will have at least 3 components and at least 2 tunnels should be constructed from one of them which is prohibited. Further, we assume that k > = 2. Let's calculate the largest number of tunnels we can build. Let s - the sum of all numbers ki. Obviously we cannot build more than s / 2 tunnels since each tunnel connects exactly two provinces. The following statement is true: we can construct s / 2 (rounded to the lower side) of tunnels or to make a graph connected by constructing n - 1 tunnels (if s / 2 > = n - 1). Let's consider vertices which have ki > 1. We may connect these vertices into a chain using tunnels. After that let's start to connecting vertices with ki = 1to the chain (using tunnels too) while it is possible. Suppose we had less than s / 2 tunnels built and we are unable to build one more tunnel. It means that we have exactly one vertex j with degree no more than kj - 2. Thus kj > 1 and this vertex is included into the chain and all the vertices with ki = 1 are attached to this chain too (otherwise we could build another tunnel), so the graph is connected. If after building the tunnels we have a connected graph then the answer is 0. Otherwise the graph consists of n - s / 2 components, that is we need to build at least n - s / 2 - 1 roads. In fact such a number of roads will be enough. Let's draw each of n - s / 2 - 1 roads the following way. First, choose 2 different connected components in the current graph. Because we have built tunnels (and possibly roads) only between different components each of the chosen components is a tree. So these components have vertices with degree not greater than 1. Now, let's choose one such vertex in each of the selected components and connect the components through these vertices (i.e. the vertices are merged into one keeping the edges from them). Thus we have a new vertex (province) with no more than two tunnels constructed from it, so we did not violate the terms since k >= 2. Thus we can get a connected graph by building additional n - s / 2 - 1 roads which is the answer for the problem.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "73",
    "index": "E",
    "title": "Morrowindows",
    "statement": "Vasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than $x$ and not less than $2$ items in his inventory. A new patch for the game appeared to view inventory in $n$ different modes. Displaying in mode $i$ is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly $a_{i}$ items. In addition, each mode shows how many pages $b_{i}$ is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it?\n\n\\textbf{Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size.}\n\nKnowing the number of $a_{i}$, $x$ and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers $a_{i}$, $x$ and he is able to know number $b_{i}$ after viewing items in mode $i$.",
    "tutorial": "When x = 2 then the answer is 0. Further we assume that x > 2. In order to uniquely identify the desired number of items t we must choose a set of numbers ai so that for every y from 2 to x the representation in modes ai is unique, i.e. sets of numbers b (y, i) = y / ai (rounded up) are pairwise distinct among all y. Note that for each i function b(y, i) is monotone by y. Hence if for some i and numbers y and z (y < z) holds b(y, i) = b(z, i) then b(y, i) = b(y + 1, i) too. So to select the set of numbers ai it is sufficient to guarantee that for each y from 2 to x - 1 exists a number j such that b(y, j) < b(y + 1, j). It is easy to see that b(y, j) < b(y + 1, j) if and only if y is divisible by aj. Thus, it is necessary that for each y from 2 to x - 1 exists number ai so that y is a multiple of ai. If some number ai is equal to 1 Vasya can just see the list in this mode to find the desired number and the answer for the problem is 1. Otherwise it is necessary and enough to take all the primes pi < x in our set ai to find the number. Indeed if we will not use some prime number pi then we will be unable to distinguish numbers pi and (pi + 1) (since pi is not divisible by some of the selected numbers). On the contrary if we will use all primes less than x then any number from 2 to x - 1 will be divisible by at least one of them. Thus we need to check whether there are all prime numbers less than x among ai. Since the number of primes from 1 to x is about O(x / ln (x)) for large x all prime numbers less than x cannot be in the set of numbers ai. For example the following statement is true: if x > 20 * n then the answer is -1. This means that we can use the Sieve of Eratosthenes to find all primes less than x for x <= 20 * n and to check whether there is at least one number from them which does not occur in ai. If such number exists then the answer for the problem is -1 otherwise the answer is the number of primes less than x.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "73",
    "index": "F",
    "title": "Plane of Tanks",
    "statement": "Vasya plays the Plane of Tanks. The tanks in this game keep trying to finish each other off. But your \"Pedalny\" is not like that... He just needs to drive in a straight line from point $A$ to point B on the plane. Unfortunately, on the same plane are $n$ enemy tanks. We shall regard all the tanks as points. At the initial moment of time Pedalny is at the point $A$. Enemy tanks would be happy to destroy it immediately, but initially their turrets are tuned in other directions. Specifically, for each tank we know the initial rotation of the turret $a_{i}$ (the angle in radians relative to the $OX$ axis in the counterclockwise direction) and the maximum speed of rotation of the turret $w_{i}$ (radians per second). If at any point of time a tank turret will be aimed precisely at the tank Pedalny, then the enemy fires and it never misses. Pedalny can endure no more than $k$ shots. Gun reloading takes very much time, so we can assume that every enemy will produce no more than one shot. Your task is to determine what minimum speed of $v$ Pedalny must have to get to the point $B$. It is believed that Pedalny is able to instantly develop the speed of $v$, and the first $k$ shots at him do not reduce the speed and do not change the coordinates of the tank.",
    "tutorial": "If for some velocity v1 we were able to go from point A to point B and receive no more than k hits, then for any velocity v2 > = v1 we also will be able to go from A to B. So we can use the binary search algorithm to find the answer. Suppose we have fixed speed of the tank v. Now we have to count how many enemy tanks will be able to shoot at our tank during the ride. Let's consider enemy tank i located at the point P on the plane. It may aim at our tank in two ways: turn the turret at point B or rotate the turret at point A and then start turning it from point A to point B. In the first case we may just compare the time required for the tank to move from A to B with the time required the enemy to aim the turret to point B. If the enemy tank will be able to take aim to B before we can reach this point then the enemy can make a shot. Next consider the second possible enemy strategy. Let's draw perpendicular PQ to the line AB. So we have divided the segment AB into 2 parts: AQ and QB (if Q does not lie on the segment AB then one of the parts will be empty and the other is a segment of AB. In this case let Q denote the end of segment AB closest to the base of the perpendicular). Let's consider the first part of the segment - AQ (before the base of the perpendicular). It is easy to check that while the angular velocity of the turret is a constant, the linear velocity of the enemy sight along the segment AQ is monotonely decreasing. Given the fact that the speed of our tank along AB is constant we find that the difference between the coordinates of the enemy's sight and the tank at the AQ interval is a convex function of time (second derivative is negative). Also this fact can be verified by finding the second derivative of this function explicitly. Thus we can use the ternary search algorithm for finding the minimum of this function on a time interval corresponding to time when our tank rides at segment AQ. When the minimum value of this function is negative the enemy is able to take aim at our tank and perform a shoot. Otherwise, the tank will ride ahead the enemy sight on the whole interval AQ. (Using similar statements we can find for example the minimum value of the time difference between reaching a point D of the interval AQ by the enemy sight and by our tank). It is possible to avoid the ternary search by finding a moment when the speed of the sight is equal to the speed of our tank and check who is closer to point B at this moment. But in this case we are to carefully handle the cases where one velocity is always greater than the other on the whole interval. Now let's consider the second part of the segment - QB (after the base of the perpendicular). If the enemy is unable to shoot in our tank at the first part of the segment (AQ) then at the time of sighting the enemy on point Q our tank will be located closer to point B than the sight. Similarly the first part of segment AB, we can prove that the linear speed of sight along QB is monotonely increasing. So if at some point C of segment QB the sight of the enemy tank has caught our tank then speed of the sight should be higher than speed of our tank at that moment (otherwise the enemy would not be able to catch the tank). Due to the monotonicity of the sight velocity on the remaining segment CB the sight will be faster than the tank and the sight will reach point B before our tank. Accordingly, if the enemy's sight has reached point B after our tank then the tank was ahead the sight on the whole interval QB too. Thus, to determine whether the enemy can shoot it is sufficient to check only point B. Performing these calculations for each of the n enemies we get the number of hits on our tank and comparing this value with the number k we go to the desired branch of the binary search.",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 2900
  },
  {
    "contest_id": "74",
    "index": "A",
    "title": "Room Leader",
    "statement": "Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.\n\nIn the beginning of the round the contestants are divided into rooms. Each room contains exactly $n$ participants. During the contest the participants are suggested to solve five problems, $A$, $B$, $C$, $D$ and $E$. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns $100$ points, for each unsuccessful hack a contestant loses $50$ points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.\n\nYou are suggested to determine the leader for some room; the leader is a participant who has maximum points.",
    "tutorial": "You can do exactly what is written in a statement. Only one pitfall in this problem is that room leader may have number of points less than zero.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "74",
    "index": "B",
    "title": "Train",
    "statement": "A stowaway and a controller play the following game.\n\nThe train is represented by $n$ wagons which are numbered with positive integers from $1$ to $n$ from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions — moving or idle. Every minute the players move.\n\nThe controller's move is as follows. The controller has the movement direction — to the train's head or to its tail. During a move the controller moves to the neighbouring wagon correspondingly to its movement direction. If at the end of his move the controller enters the $1$-st or the $n$-th wagon, that he changes the direction of his movement into the other one. In other words, the controller cyclically goes from the train's head to its tail and back again during all the time of a game, shifting during each move by one wagon. Note, that the controller always have exactly one possible move.\n\nThe stowaway's move depends from the state of the train. If the train is moving, then the stowaway can shift to one of neighbouring wagons or he can stay where he is without moving. If the train is at a station and is idle, then the stowaway leaves the train (i.e. he is now not present in any train wagon) and then, if it is not the terminal train station, he enters the train again into any of $n$ wagons (not necessarily into the one he's just left and not necessarily into the neighbouring one). If the train is idle for several minutes then each such minute the stowaway leaves the train and enters it back.\n\nLet's determine the order of the players' moves. If at the given minute the train is moving, then first the stowaway moves and then the controller does. If at this minute the train is idle, then first the stowaway leaves the train, then the controller moves and then the stowaway enters the train.\n\nIf at some point in time the stowaway and the controller happen to be in one wagon, then the controller wins: he makes the stowaway pay fine. If after a while the stowaway reaches the terminal train station, then the stowaway wins: he simply leaves the station during his move and never returns there again.\n\nAt any moment of time the players know each other's positions. The players play in the optimal way. Specifically, if the controller wins, then the stowaway plays so as to lose as late as possible. As all the possible moves for the controller are determined uniquely, then he is considered to play optimally always. Determine the winner.",
    "tutorial": "In this problem you may find optimal strategy for a stowaway. Next you may just simulate a game. Optimal strategy for the stowaway is placing from a conrtoller as far as possible. In the moving minute the stowaway should go into wagon that farther to the controller. In the idle minute stowaway should go into wagon in which the controller enter as later as possible. It is always the first or the last wagon of train. You may also wrote some dynamic programming solution or a solution fot classic game.",
    "tags": [
      "dp",
      "games",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "74",
    "index": "C",
    "title": "Chessboard Billiard",
    "statement": "Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.\n\nMore formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.\n\nIt is considered that one billiard ball $a$ beats another billiard ball $b$ if $a$ can reach a point where $b$ is located.\n\nYou are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard $n × m$ in size.",
    "tutorial": "Define a trajectory as a line that center of a billiard ball is drawing while it is moving. At begin of moving, the ball chose one from no more than two trajectoties and is moving along of it. Let a number of trajectories is $k$. Define $z$as maximal number of billiard balls that can be placed into chessboard without hits (it is answer for problem). Theorem. $z = k$. Proof. Every ball covers at least one trajectory. Two different balls cannot cover one trajectory because then they hit each other. Therefore, $z  \\le  k$. Now try to arrange $k$ balls that they don't hit each other. Every cell of perimeter of board belongs to exactly one trajectory. Every trajectory covers at least one from border cells. So, there is exists $k$ cells on perimeter of board whick belongs to different trajectories. Into these cells we should put all billiard balls. End of proof. This theoren gives constructive methode to find $k.$ We may just calculate number of connected component in graph like in a picture below. It can be done by BFS, DFS or disjoint set union in time $O(n + m)$. For example, on picture 4 components are present. In this problem alse some solution by formula exists. $z = gcd(n - 1, m - 1) + 1$. You may wrote some stupid solution for observe it. But this formula is difficult for prove.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "74",
    "index": "D",
    "title": "Hanger",
    "statement": "In one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by $n$ hooks, positioned in a row. The hooks are numbered with positive integers from 1 to $n$ from the left to the right.\n\nThe company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.\n\nWhen some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.\n\nWhen an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.\n\nFrom time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the $i$-th to the $j$-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.\n\nNot to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work.",
    "tutorial": "You may use some data structire that allows fast insert, search, remove of elements and find a minimum of all elements. There can be used, for example, std::set in C++ or analogicaly container in other languages. In this structure segments of empty hooks can be stored. Minimum element in structure should be a segment into which a current coat can be hanged. In addition, for every arrived employee you may store place of his coat and segments of empty hooks in the left from this place and in the right from one. With help of this structures you can in $O(q\\log q)$ emulate a work of cloakroom. Difficults begins with director's queries. We can fastly insert, delete and find sum in a segment. Online solution. There can be written some balanced or decart tree. Offline solution. At first, iterate over all queries \"in idle\" (we will nor answer for director's queries) and store coordinates of all hooks on which ever coat was hanged. Next, squeeze these coordinates and iterate over all queries again. Now we can answer for director's queries by using Fenwick or segment tree.",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "74",
    "index": "E",
    "title": "Shift It!",
    "statement": "There is a square box $6 × 6$ in size. It contains $36$ chips $1 × 1$ in size. Those chips contain 36 different characters — \"0\"-\"9\" and \"A\"-\"Z\". There is exactly one chip with each character.\n\nYou are allowed to make the following operations: you may choose one of $6$ rows or one of $6$ columns and cyclically shift the chips there to one position to the left or to the right (for the row) or upwards or downwards (for the column). Those operations are allowed to perform several times.\n\nTo solve the puzzle is to shift the chips using the above described operations so that they were written in the increasing order (exactly equal to the right picture). An example of solving the puzzle is shown on a picture below.\n\nWrite a program that finds the sequence of operations that solves the puzzle. That sequence \\textbf{should not necessarily be shortest}, but you should not exceed the limit of $10000$ operations. It is guaranteed that the solution always exists.",
    "tutorial": "A following sequence of operations swaps two pieces in positions 0 and 1: D1 R1 D1 L1 D1 R1 D1 L1 D1 R1 D1 L1 D1. This sequence can be found on a paper by hands or by usung bidirectional BFS with limitation of allowable moves (it also can be found by ordinary BFS with very limited number of allowable moves). Analogically you can swap any two neighbouring pieces in 13 moves. Then the solution is trivial and easily fits in the limit of 10000 moves.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2800
  },
  {
    "contest_id": "75",
    "index": "A",
    "title": "Life Without Zeros",
    "statement": "Can you imagine our life if we removed all zeros from it? For sure we will have many problems.\n\nIn this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation $a + b = c$, where $a$ and $b$ are positive integers, and $c$ is the sum of $a$ and $b$. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros?\n\nFor example if the equation is $101 + 102 = 203$, if we removed all zeros it will be $11 + 12 = 23$ which is still a correct equation.\n\nBut if the equation is $105 + 106 = 211$, if we removed all zeros it will be $15 + 16 = 211$ which is not a correct equation.",
    "tutorial": "In this problem you need to do what is written in the statement. You can do it in the following 3 steps: 1- Calculate C. 2- Remove all zeros from A, B and C. 3- Check if the new values form a correct equation.",
    "code": "#include <cstring>\n#include <map>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <complex>\n#include <list>\n#include <climits>\n#include <cctype>\n \nusing namespace std;\n \nint removeZeros(int num) {\n    int ret = 0;\n    int ten = 1;\n    while (num) {\n        int dig = num % 10;\n        num /= 10;\n        if (dig) {\n            ret += dig * ten;\n            ten *= 10;\n        }\n    }\n    return ret;\n}\n \nint main() {\n    int a, b, c;\n    cin >> a >> b;\n    c = a + b;\n    a = removeZeros(a);\n    b = removeZeros(b);\n    c = removeZeros(c);\n    if (a + b == c)\n        cout << \"YES\" << endl;\n    else\n        cout << \"NO\" << endl;\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "75",
    "index": "B",
    "title": "Facetook Priority Wall",
    "statement": "Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).\n\nThis priority factor will be affected by three types of actions:\n\n- 1. \"$X$ posted on $Y$'s wall\" (15 points),\n- 2. \"$X$ commented on $Y$'s post\" (10 points),\n- 3. \"$X$ likes $Y$'s post\" (5 points).\n\n$X$ and $Y$ will be two distinct names. And each action will increase the priority factor between $X$ and $Y$ (and vice versa) by the above value of points (the priority factor between $X$ and $Y$ is the same as the priority factor between $Y$ and $X$).\n\nYou will be given $n$ actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you.",
    "tutorial": "This problem is a direct simulation to the rules written in the problem statement. You need to iterate over all actions and parse each one to know the type of the action, and the 2 names X and Y, and if your name is X or Y then update your priority factor with this person with the action corresponding value. And take care about some special names like \"post\", \"wall\", \"commented\" and \"on\". Then sort all names according to the sorting criteria mentioned in the statement. Just make sure to print all names which are mentioned in the input (excluding yourself), even if the priority factor with you is 0.",
    "code": "#include <cstring>\n#include <map>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <complex>\n#include <list>\n#include <climits>\n#include <cctype>\n \nusing namespace std;\n \nint main() {\n    string myName;\n    cin >> myName;\n    int n;\n    cin >> n;\n    map<string, int> factor;\n    string name1, action, temp, name2;\n    for (int i = 0; i < n; i++) {\n        cin >> name1;\n        cin >> action;\n        if (action == \"posted\" || action == \"commented\")\n            cin >> temp;\n        cin >> name2;\n        name2 = name2.substr(0, name2.length() - 2);\n        cin >> temp;\n        int val = 5;\n        if (action == \"posted\")\n            val = 15;\n        else if (action == \"commented\")\n            val = 10;\n        if (name1 == myName)\n            factor[name2] += val;\n        else\n            factor[name1];\n        if (name2 == myName)\n            factor[name1] += val;\n        else\n            factor[name2];\n    }\n    vector<pair<int, string> > ret;\n    for (map<string, int>::iterator it = factor.begin(); it != factor.end(); it++)\n        ret.push_back(make_pair(-it->second, it->first));\n    sort(ret.begin(), ret.end());\n    int m = ret.size();\n    for (int i = 0; i < m; i++)\n        cout << ret[i].second << endl;\n    return 0;\n}",
    "tags": [
      "expression parsing",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "75",
    "index": "C",
    "title": "Modified GCD",
    "statement": "Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.\n\nA common divisor for two positive numbers is a number which both numbers are divisible by.\n\nBut your teacher wants to give you a harder task, in this task you have to find the greatest common divisor $d$ between two integers $a$ and $b$ that is in a given range from $low$ to $high$ (inclusive), i.e. $low ≤ d ≤ high$. It is possible that there is no common divisor in the given range.\n\nYou will be given the two integers $a$ and $b$, then $n$ queries. Each query is a range from $low$ to $high$ and you have to answer each query.",
    "tutorial": "In this problem you will need to generate all common divisors between a and b before answering any query. The first step in this problem is to factorize a and b, you can use the trial division technique which runs in O(sqrt(N)), you can check getFactors function in my solutions. Then using a recursive function you can generate all divisors for a and b from their prime factors, you can check getDivisors function in my solutions. Then intersect the 2 sets of divisors for both to get all common divisors, you can do this in O(N+M) where N and M are the lengths of the 2 sets, and also you can do a trivial O(N*M) intersection algorithm, because the maximum number of divisors is not too big (it's 1344). Now for each query you need to find the largest common divisor which lies in the given range, you can do this by sorting all common divisors and do binary search for the largest one which lies in the given range. Also you can do this using linear search, because the total number of queries is not too big. Also there is much shorter solution for this problem. Here is a hint for it, the GCD between a and b should be dividable by all common divisors of a and b.",
    "code": "#include <cstring>\n#include <map>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <complex>\n#include <list>\n#include <climits>\n#include <cctype>\n \nusing namespace std;\n \nvector<pair<int, int> > factors;\nvoid getFactors(int n) {\n    factors.clear();\n    int d = 1;\n    for (int i = 2; i * i <= n; i += d, d = 2)\n        if (n % i == 0) {\n            factors.push_back(make_pair(i, 0));\n            while (n % i == 0) {\n                n /= i;\n                factors.back().second++;\n            }\n        }\n    if (n != 1)\n        factors.push_back(make_pair(n, 1));\n}\n \nvector<int> divisors;\nvoid getDivisors(int ind = 0, int res = 1) {\n    if (ind == (int) factors.size()) {\n        divisors.push_back(res);\n        return;\n    }\n    for (int i = 0; i <= factors[ind].second; i++) {\n        getDivisors(ind + 1, res);\n        res *= factors[ind].first;\n    }\n}\n \nint main() {\n    int a, b, n;\n    scanf(\"%d\", &a);\n    getFactors(a);\n    getDivisors();\n    vector<int> d1 = divisors;\n    scanf(\"%d\", &b);\n    getFactors(b);\n    divisors.clear();\n    getDivisors();\n    vector<int> d2 = divisors;\n    sort(d1.begin(), d1.end());\n    sort(d2.begin(), d2.end());\n    vector<int> cd;\n    set_intersection(d1.begin(), d1.end(), d2.begin(), d2.end(), inserter(cd,\n            cd.begin()));\n    scanf(\"%d\", &n);\n    int low, high, ind;\n    for (int i = 0; i < n; i++) {\n        scanf(\"%d%d\", &low, &high);\n        ind = upper_bound(cd.begin(), cd.end(), high) - cd.begin();\n        ind--;\n        if (ind == -1 || cd[ind] < low)\n            printf(\"-1\n\");\n        else\n            printf(\"%d\n\", cd[ind]);\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "75",
    "index": "D",
    "title": "Big Maximum Sum",
    "statement": "Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.\n\nThis problem is similar to a standard problem but it has a different format and constraints.\n\nIn the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.\n\nBut in this problem you are given $n$ small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.\n\nFor example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.\n\nCan you help Mostafa solve this problem?",
    "tutorial": "This problem is my favorite one in this problem set. Maybe it will be easier to solve this problem if you know how to solve the standard one. But because we can't construct the big array, so we can't apply the standard solution for this problem. Let's see first how to solve the standard problem, the following code solves it for a given array arr with length len: int mx = -(1 << 30); int sum = 0; for (int j = 0; j < len; j++) { mx = max(mx, arr[i]); // we need this for the case where all elements in the array are negatives sum += arr[i]; if (sum < 0) sum = 0; else mx = max(mx, sum); } Now let's solve the big array problem, the first step is to calculate 4 values for each small array: 1- The total sum of it, let's call it tot. 2- The maximum sum of 0 or more consecutive elements starting from the first element in the array, let's call it lft. 3- The maximum sum of 0 or more consecutive elements ending at the last element in the array, let's call it rght. 4- The maximum sum of 1 or more consecutive elements, let's call it gen. The final result will be 1 of 2 cases: 1- The consecutive elements with the maximum sum will start and end inside the same small array. 2- The consecutive elements with the maximum sum will start and end inside different small arrays. For the first case, we can simply pick the maximum gen for all small arrays which exist in the big array. For the second case, we can apply something similar to the standard solution, we will keep a variable called sum, and it's initialized to 0, this will be the maximum sum of 0 or more consecutive elements ending at the last element in the previous small array. Now for each small array, if the maximum possible sum will end in this small array, so it will be sum+lft and maximize over this value (make sure this will be for 1 or more elements). And we need to update sum to be the maximum of the following 3 values: 1- sum+tot (we will include all elements of this small array to the old sum). 2- rght (we will take the maximum sum ending at the last element in the current small array). 3- 0 (we will not take any elements in sum). The running time for this solution will be just for reading the input, in my solutions I have no iterations except for reading the input. You can check my solutions for more clarification.",
    "code": "#include <cstring>\n#include <map>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <complex>\n#include <list>\n#include <climits>\n#include <cctype>\n \nusing namespace std;\n \nint n, m;\n \nlong long gen[50], lft[50], rght[50], tot[50];\n \nint main() {\n    scanf(\"%d%d\", &n, &m);\n    int len, num;\n    for (int i = 0; i < n; i++) {\n        scanf(\"%d\", &len);\n        int mx = -(1 << 30);\n        int sum = 0;\n        for (int j = 0; j < len; j++) {\n            scanf(\"%d\", &num);\n            tot[i] += num;\n            lft[i] = max(lft[i], tot[i]);\n            rght[i] = min(rght[i], tot[i]);\n            mx = max(mx, num);\n            sum += num;\n            if (sum < 0)\n                sum = 0;\n            else\n                mx = max(mx, sum);\n        }\n        gen[i] = mx;\n        rght[i] = tot[i] - rght[i];\n    }\n    long long cur = 0;\n    long long best = (long long) (-1e18);\n    while (m--) {\n        int i;\n        scanf(\"%d\", &i);\n        i--;\n        best = max(best, gen[i]);\n        if (cur)\n            best = max(best, cur + lft[i]);\n        cur = max(0ll, max(rght[i], cur + tot[i]));\n    }\n    cout << best << endl;\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "75",
    "index": "E",
    "title": "Ship's Shortest Path",
    "statement": "You have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.\n\nAnd it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.\n\nYou can \\textbf{only} move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.\n\nBut you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.\n\nYou can move your ship on the island edge, and it will be considered moving in the sea.\n\nNow you have a sea map, and you have to decide what is the minimum cost for your trip.\n\nYour starting point is ($xStart$, $yStart$), and the end point is ($xEnd$, $yEnd$), both points will be different.\n\nThe island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.",
    "tutorial": "The main idea for this problem is not hard, but maybe the hard part is implementing it. First we need to know if the straight line segment between the source and destination points intersect with the island or not. So we will intersect this line segment with all the polygon sides. If there are 2 segments intersect in more than 1 point we will consider as they don't intersect, because it's mentioned in the problem statement that you can move on the island's edge and it will be considered in the sea. Now we have a set of all distinct intersection points of the polygon and the straight line segment between the source and destination points. Because the polygon is convex, this set will contain at most 2 points. We have 3 different cases now: 1- This set contains less than 2 points. 2- This set contains 2 points and they are on the same polygon side. 3- This set contains 2 points and they are not on the same polygon side. In the first 2 cases the result will be simply the length of the straight line segment. In the 3rd case you can do the following: 1- Move from the source point to the nearest point of the 2 intersection points. 2- You have 3 options here: a- Move inside the island to the other intersection point. b- Move in clockwise direction on the island's edge to the other intersection point. c- Move in anti-clockwise direction on the island's edge to the other intersection point. First option will be considered moving inside the island, and the other 2 options will be considered moving in the sea. You should pick the minimum one. 3- Move from the 2nd intersection point to the destination point. Another solution: You can construct a graph where the nodes are the source point, the destination point, the intersection points and the polygon corner points. Then add an edge between any 2 points which you can move between them with the corresponding cost. Then run any shortest path algorithm, Floyd Warshall for example. You can check my solutions for more clarification.",
    "code": "#include <cstring>\n#include <map>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <complex>\n#include <list>\n#include <climits>\n#include <cctype>\n \nusing namespace std;\n \ntypedef complex<double> point;\n#define cross(a,b) ((conj(a)*(b)).imag())\n#define X real()\n#define Y imag()\n \nconst double eps = 1e-9;\n \nint comp(double a, double b) {\n    if (fabs(a - b) < eps)\n        return 0;\n    return a > b ? 1 : -1;\n}\n \nstruct pComp {\n    bool operator()(const point &A, const point &B) const {\n        if (comp(A.X, B.X))\n            return A.X < B.X;\n        if (comp(A.Y, B.Y))\n            return A.Y < B.Y;\n        return 0;\n    }\n};\n \ndouble len(point A, point B) {\n    return hypot(A.X - B.X, A.Y - B.Y);\n}\n \nbool pointOnSeg(point A, point B, point R) {\n    return comp(len(A, B), len(A, R) + len(B, R)) == 0;\n}\n \nbool lineInter(point A, point B, point P, point Q, point &R) {\n    double d1 = cross(P-A,B-A);\n    double d2 = cross(Q-A,B-A);\n    if (comp(d1, d2) == 0)\n        return false;\n    R = (d1 * Q - d2 * P) / (d1 - d2);\n    if (!pointOnSeg(A, B, R) || !pointOnSeg(P, Q, R))\n        return false;\n    return true;\n}\n \nint n;\npoint st, en;\nvector<point> pol;\n \ndouble mat[34][34];\n \nint main() {\n    int x, y;\n    cin >> x >> y;\n    st = point(x, y);\n    cin >> x >> y;\n    en = point(x, y);\n    cin >> n;\n    for (int i = 0; i < n; i++) {\n        cin >> x >> y;\n        pol.push_back(point(x, y));\n    }\n    double ret = len(st, en);\n    set<point, pComp> intrs;\n    for (int i = 0; i < n; i++) {\n        point R;\n        if (lineInter(st, en, pol[i], pol[(i + 1) % n], R))\n            intrs.insert(R);\n    }\n    if (intrs.size() == 2) {\n        point p1 = *intrs.begin();\n        point p2 = *(++intrs.begin());\n        double d1 = -1, d2 = 0;\n        for (int i = 0; i < n; i++) {\n            int j = (i + 1) % n;\n            d2 += len(pol[i], pol[j]);\n            if (d1 == -1 && pointOnSeg(pol[i], pol[j], p1)) {\n                if (pointOnSeg(pol[i], pol[j], p2))\n                    goto PRINT;\n                d1 = len(p1, pol[j]);\n                while (1) {\n                    int j2 = (j + 1) % n;\n                    if (pointOnSeg(pol[j], pol[j2], p2)) {\n                        d1 += len(pol[j], p2);\n                        break;\n                    }\n                    d1 += len(pol[j], pol[j2]);\n                    j = j2;\n                }\n            }\n        }\n        d2 -= d1;\n        double d3 = len(p1, p2);\n        ret -= d3;\n        d3 *= 2;\n        ret += min(d3, min(d1, d2));\n    }\n    PRINT: ;\n    printf(\"%.9lf\n\", ret);\n    return 0;\n}",
    "tags": [
      "geometry",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "76",
    "index": "A",
    "title": "Gift",
    "statement": "The kingdom of Olympia consists of $N$ cities and $M$ bidirectional roads. Each road connects exactly two cities and two cities can be connected with more than one road. Also it possible that some roads connect city with itself making a loop.\n\nAll roads are constantly plundered with bandits. After a while bandits became bored of wasting time in road robberies, so they suggested the king of Olympia to pay off. According to the offer, bandits want to get a gift consisted of gold and silver coins. Offer also contains a list of restrictions: for each road it is known $g_{i}$ — the smallest amount of gold and $s_{i}$ — the smallest amount of silver coins that should be in the gift to stop robberies on the road. That is, if the gift contains $a$ gold and $b$ silver coins, then bandits will stop robberies on all the roads that $g_{i} ≤ a$ and $s_{i} ≤ b$.\n\nUnfortunately kingdom treasury doesn't contain neither gold nor silver coins, but there are Olympian tugriks in it. The cost of one gold coin in tugriks is $G$, and the cost of one silver coin in tugriks is $S$. King really wants to send bandits such gift that for any two cities there will exist a safe path between them. Your task is to find the minimal cost in Olympian tugriks of the required gift.",
    "tutorial": "Suppose that the pair $(A, B)$ is an optimal solution, where $A$ is the number of gold coins in a gift and $B$ is a number of silver coins. It is easy to see that there exist two (probably equal) indexes $i$ and $j$ such that $g_{i} = A$ and $s_{j} = B$. It is true, because in the other case we could decrease either $A$ or $B$ without changing connectivity of the graph. Let $R(A, B)$ be the graph in which for all $i$ the following statement holds: $g_{i}\\leq A\\wedge s_{i}\\leq B$. Let $T(A)$ be the weighted graph in which for all edges $g_{i}  \\le  A$. For each edge $i$ we will assign a weight equal to $s_{i}$. Let's find a spanning tree of this graph, which has the property that its maximal edge is minimal possible. It can be shown that for the fixed $A$ the minimal value of $B$ for which graph $R(A, B)$ is still connected is equal to the weight of the maximal edge in this spanning tree. Claim. Minimal spanning tree of a graph has the property that its maximal edge is minimal possible among all spanning trees. Proof. Let $L$ be the minimal spanning tree of a graph. Suppose there exists a spanning tree $P$ in which all edges have smaller weight than the weight of the maximal edge of $L$. We can then remove the maximal edge from $L$ and add some edge from $P$ to it which will connect the graph back. After that $L$ will have strictly smaller weight, which is impossible because it is a minimal spanning tree. Let's sort all edges of the graph in ascending order of $g_{i}$. Then the edges of graph $T(A)$ for the fixed $i$ will be all edges with indexes $j  \\le  i$. Suppose that for some value of $i$ we have already found minimal spanning tree in every connected component of the graph $T(g_{i})$. Let's add an edge with index $i + 1$ into it. If it connects two different components, then after this operation they will be merged into one big component and it is obviously that the spanning tree we have in it is the minimal spanning tree. If $i + 1$-th edge connects two vertices from the same connected component, then it will create exactly one cycle in the graph. We can find the maximal edge in this cycle and remove it from the graph. It can be proven that the remaining tree will be the minimal spanning tree of this connected component. We can perform the search of the maximal edge in a cycle as well as the insertion and removal of the edges in O(N). The total complexity is $O(NM + MlogM)$.",
    "tags": [
      "dsu",
      "graphs",
      "sortings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "76",
    "index": "B",
    "title": "Mice",
    "statement": "Modern researches has shown that a flock of hungry mice searching for a piece of cheese acts as follows: if there are several pieces of cheese then each mouse chooses the closest one. After that all mice start moving towards the chosen piece of cheese. When a mouse or several mice achieve the destination point and there is still a piece of cheese in it, they eat it and become well-fed. Each mice that reaches this point after that remains hungry. Moving speeds of all mice are equal.\n\nIf there are several ways to choose closest pieces then mice will choose it in a way that would minimize the number of hungry mice. To check this theory scientists decided to conduct an experiment. They located $N$ mice and $M$ pieces of cheese on a cartesian plane where all mice are located on the line $y = Y_{0}$ and all pieces of cheese — on another line $y = Y_{1}$. To check the results of the experiment the scientists need a program which simulates the behavior of a flock of hungry mice.\n\nWrite a program that computes the minimal number of mice which will remain hungry, i.e. without cheese.",
    "tutorial": "It is easy to see that the number of closest pieces of cheese for each mouse is not greater than 2. Let's find the closest pieces of cheese for each mouse to the left and to the right from it. From two directions we will choose the one which gives us shorter way to cheese or both of them if their lengths are equal. If on the chosen way between the mouse and the cheese stands another mouse, then we should exclude this way from consideration, because another mouse will get to the cheese faster. Now all the directions lead to cheese and for each piece of cheese there is at most one mouse which can potentially eat it from each direction. We will process mice from left to right. If the current mouse can move left and the cheese to the left of it is not chosen by any other mouse or it is chosen by a mouse with the same distance to it, then the current mouse can move to the left and eat this piece of cheese without interfering with other mice. This choice will not affect any choices of the next mice, because only one mouse can go to this piece of cheese from the right (see previous paragraph). Thus, this choice can not decrease the answer. In all other cases the current mouse can not increase the answer by moving left, so it should move to the right if it has such opportunity. The complexity is $O(N + M)$. This problem can be also solved using dynamic programming.",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "76",
    "index": "C",
    "title": "Mutation",
    "statement": "Scientists of planet Olympia are conducting an experiment in mutation of primitive organisms. Genome of organism from this planet can be represented as a string of the first $K$ capital English letters. For each pair of types of genes they assigned $a_{i, j}$ — a risk of disease occurence in the organism provided that genes of these types are adjacent in the genome, where $i$ — the 1-based index of the first gene and $j$ — the index of the second gene. The gene 'A' has index 1, 'B' has index 2 and so on. For example, $a_{3, 2}$ stands for the risk of 'CB' fragment. Risk of disease occurence in the organism is equal to the sum of risks for each pair of adjacent genes in the genome.\n\nScientists have already obtained a base organism. Some new organisms can be obtained by mutation of this organism. Mutation involves removal of all genes of some particular types. Such removal increases the total risk of disease occurence additionally. For each type of genes scientists determined $t_{i}$ — the increasement of the total risk of disease occurence provided by removal of all genes having type with index $i$. For example, $t_{4}$ stands for the value of additional total risk increasement in case of removing all the 'D' genes.\n\nScientists want to find a number of different organisms that can be obtained from the given one which have the total risk of disease occurence not greater than $T$. They can use only the process of mutation described above. Two organisms are considered different if strings representing their genomes are different. Genome should contain at least one gene.",
    "tutorial": "In the editorial we will replace terms \"risk\", \"genome\" and \"gene\" with \"cost\", \"string\" and \"character\", respectively. Let $S$ be the starting string. Let $M$ be the bitmask of chars which will be removed. Let's iterate over all possible values of $M$. For the fixed $M$ we need to find a cost of the string, which remained after removal of $M$ and if this cost doesn't exceed $T$ we will increase the answer by 1. Naive implementation of this idea has the complexity $O(2^{K}N)$. We can not get rid of iterating over all $M$, so we will try to optimize a part of the algorithm which finds a cost of the remaining string. Let's take two indexes $l$ and $r$ from the beginning string $l < r$. Let $M'$ be the bitmask of all characters which are located strictly between them. It is obviously that if $S_{l}\\in M^{\\prime}$ or $S_{r}\\in M^{\\prime}$ then $l$ and $r$ can not be neighbours in the remaining string. Hence for the fixed $l$ there are not more than $K$ possible candidates for $r$, which means that there are $O(NK)$ pairs of such potential neighbours. We will call such pairs \"good\". We want to find out what form should have the set $M$ that after its removal indexes $l$ and $r$ became adjacent. It is easy to see that the following two conditions should be true: 1. $M^{\\prime}\\subset M$ 2. $S_{l}\\not\\in M\\wedge S_{r}\\not\\in M$ Let's iterate over all good pairs of $l$ and $r$ and for each of them we will find the set $M'$. For each triple $(a, b, P)$ we will store the sum of costs of neighborhood of all pairs $l$ and $r$ for which $S_{l} = a$, $S_{r} = b$, $M' = P$. After that for the fixed $M$ we will iterate over all pairs of characters $(a, b)$ and its subsets $P$ and add all their costs together. Also we need to add the cost of removal of $M$ and the resulting sum will be the cost of the string which will left after removal of $M$. The complexity of such solution is $O(3^{K} * K^{2} + NK)$. We will optimize the previous solution by decreasing a factor near $3^{K}$. Let's look at the following (incorrect) algorithm: We will iterate over all good pairs $l$ and $r$ and for each of them we will find $M'$. Let's create an array $v$ in which for each mask $P$ we will store the sum of costs of neighborhood of all pairs $l$ and $r$ for which $M' = P$. For the fixed $M$ we will find a sum of all values from $v$ for all submasks of $M$, then add the cost of removal of $M$ to it and the resulting sum will be the cost of the remaining string. This algorithm is incorrect, because some costs of neighborhood are added to the total cost, but in fact the respective $l$ or $r$ are removed. Let's use inclusion-exclusion principle and make the following at the phase of filling array $v$: $v[M'] + = cost$ $v[M^{\\prime}\\cup\\{S_{i}\\}]-=c o s l$ $v[M^{\\prime}\\cup\\{S_{r}\\}]-=c o s t$ $v[M^{\\prime}\\cup\\{S_{l},S_{r}\\}]+=c o s t$ With such filling of $v$ the algorithm described above is correct and the total complexity becomes $O(3^{K} + NK)$. This is still not enough for the full solution, but we are almost there. We only need to find a fast way of finding the sum of the values of $v$ for all submasks of all masks $M$. We will use the following iterative algorithm for this purpose: Before the first iteration we have an array $v$ in which the starting values are stored. After iteration with number $i$ in $v[mask]$ we will store the sum of all the values from the original array $v$ for all submasks of $mask$ for which the first $K - i$ bits are equal to the respective bits of $mask$. On iteration with number $i$ for all masks in which the $i$-th bit is equal to 1 (bits are numbered from 1) we will perform the following: $v[mask] + = v[mask\\{i}]$. It is easy to see that after the $K$-th iteration of this algorithm we will have the values we were looking for in array $v$. The complexity is $O(2^{K}K + NK)$.",
    "tags": [
      "bitmasks",
      "dp",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "76",
    "index": "D",
    "title": "Plus and xor",
    "statement": "Bitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different.\n\nFor example, if $X = 109_{10} = 1101101_{2}$, $Y = 41_{10} = 101001_{2}$, then:\n\n\\begin{center}\n$X$ xor $Y  =  68_{10}  =  1000100_{2}$.\n\\end{center}\n\nWrite a program, which takes two non-negative integers $A$ and $B$ as an input and finds two non-negative integers $X$ and $Y$, which satisfy the following conditions:\n\n- $A = X + Y$\n- $B  =  X$ xor $Y$, where xor is bitwise exclusive or.\n- $X$ is the smallest number among all numbers for which the first two conditions are true.",
    "tutorial": "Let's take a look at some bit in X, which is equal to 1. If the respective bit in Y is equal to 0, then we can swap these two bits, thus reducing X and increasing Y without changing their sum and xor. We can conclude that if some bit in X is equal to 1 then the respective bit in Y is also equal to 1. Thus, $Y = X + B$. Taking into account that $X + Y = X + X + B = A,$ we can obtain the following formulas for finding $X$ and $Y$: $X = (A - B) / 2$ $Y = X + B$ One should also notice that if $A < B$ or $A$ and $B$ have different parity, then the answer doesn't exist and we should output -1. If $X$ $and$ $(A - X)  \\neq  X$ then the answer is also -1.",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "76",
    "index": "E",
    "title": "Points",
    "statement": "You are given $N$ points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.",
    "tutorial": "Let's regroup summands and split the sum of squares of distances we are looking for into two sums: ${\\textstyle\\sum_{i=1}^{N}\\sum_{j=1}^{i-1}(x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2}}$ $\\begin{array}{r}{\\sum_{i=1}^{N}\\sum_{j=1}^{k-1}(x_{i}-x_{j})^{2}+\\sum_{i=1}^{N}\\sum_{j=1}^{i-1}(y_{i}-y_{j})^{2}}\\end{array}$ Now we need to rewrite each of these sums in the following way (it will be shown for the first sum): $\\textstyle{\\sum_{i=1}^{N}\\sum_{j=1}^{i-1}(x_{i}-x_{j})^{2}=\\sum_{i=1}^{N}\\sum_{j=1}^{i-1}(x_{i}^{2}-2x_{i}x_{j}+x_{j}^{2})=}$ $\\textstyle\\sum_{i=1}^{N}((i-1)x_{i}^{2}-2x_{i}\\sum_{j=1}^{i-1}x_{j}+\\sum_{j=1}^{i-1}x_{j}^{2})$ This formula allows us to find an answer in one pass through the array. The complexity is O(N).",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "76",
    "index": "F",
    "title": "Tourist",
    "statement": "Tourist walks along the $X$ axis. He can choose either of two directions and any speed not exceeding $V$. He can also stand without moving anywhere. He knows from newspapers that at time $t_{1}$ in the point with coordinate $x_{1}$ an interesting event will occur, at time $t_{2}$ in the point with coordinate $x_{2}$ — another one, and so on up to ($x_{n}, t_{n}$). Interesting events are short so we can assume they are immediate. Event $i$ counts visited if at time $t_{i}$ tourist was at point with coordinate $x_{i}$.\n\nWrite program tourist that will find maximum number of events tourist if:\n\n- at the beginning (when time is equal to 0) tourist appears at point 0,\n- tourist can choose initial point for himself.\n\nYes, you should answer on two similar but different questions.",
    "tutorial": "We can get to the event $j$ from the event $i$ if the following statements are true: $t_{i}  \\le  t_{j}$ $|x_{i} - x_{j}|  \\le  |t_{i} - t_{j}| \\cdot  V$ We can represent all the events as points on a plane with coordinates $(x_{i}, t_{i})$. Now we can reformulate the two statements written above in the following way: From the event $i$ we can get to the event $j$ if the point $(x_{j}, t_{j})$ lise inside an angle pointed to the top with its vertex in $(x_{i}, t_{i})$ and its sides form an angle $arctg(V)$ with vertical axis. Let's make coordinate transformation according to which the point with coordinates $(x_{i}, t_{i})$ will transform into the point $(p_{i}, q_{i})$, where $p_{i} = - x_{i} + t_{i} * V$ $q_{i} = x_{i} + t_{i} * V$ Now we can get to the event $j$ from the event $i$ if $p_{i}  \\le  p_{j}$ and $q_{i}  \\le  q_{j}$. Let's sort all points in ascending order of $p$. If several points have the same $p$ we will sort them by $q$. The second subproblem of our problem can be solved by finding a longest increasing subsequence by $q$ in this array. It can be done in $O(NlogN)$. To solve the first subproblem we can add dummy event with coordinate 0 and time 0 (if it is not present in our set of events yet) and force tourist's start from it. The total complexity if $O(NlogN)$.",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "77",
    "index": "A",
    "title": "Heroes",
    "statement": "The year of 2012 is coming...\n\nAccording to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil.\n\nThe seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: $a$ for Mephisto, $b$ for Diablo and $c$ for Baal.\n\nHere's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a $\\scriptstyle{\\frac{\\pi}{y}}$ of experience, rounded down, where $x$ will be the amount of experience for the killed megaboss and $y$ — the number of people in the team.\n\nHeroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which \\underline{the total amount of liking in teams} were maximum.\n\nIt is known that some heroes like others. But if hero $p$ likes hero $q$, this does not mean that the hero $q$ likes hero $p$. No hero likes himself.\n\nThe total amount of liking in teams is the amount of ordered pairs $(p, q)$, such that heroes $p$ and $q$ are in the same group, and hero $p$ likes hero $q$ (but it is not important if hero $q$ likes hero $p$). In case of heroes $p$ and $q$ likes each other and they are in the same group, this pair should be counted twice, as $(p, q)$ and $(q, p)$.\n\nA team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team.\n\nIt is guaranteed that every hero is able to destroy any megaboss alone.",
    "tutorial": "It is possble to solve this problem by full search because there are only $k = 7$ heroes and three team. Let's find all dividings - move every hero in every team and drop away incorrect dividings when al least one team is empty. In each correct dividing we should find value of experience between two heroes who will receive the maximum and minimum number of experience points and value of total amount of liking in teams. Now we should choose the best way and write it. Complexity is $O(3^{k} \\cdot  k^{2})$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "77",
    "index": "B",
    "title": "Falling Anvils",
    "statement": "For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.\n\nAnvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!\n\nIt turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.\n\nLet the height $p$ of the potential victim vary in the range $[0;a]$ and the direction of the wind $q$ vary in the range $[ - b;b]$. $p$ \\textbf{and} $q$ \\textbf{could be any real (floating) numbers.} Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:\n\n\\begin{center}\n$x^{2}+{\\sqrt{p}}\\cdot x+q=0$\n\\end{center}\n\nDetermine the probability with which an aim can be successfully hit by an anvil.\n\nYou can assume that the $p$ and $q$ coefficients are chosen equiprobably and independently in their ranges.",
    "tutorial": "In this problem you were to determine the probability if the equation $x^{2}+{\\sqrt{p}}\\cdot x+q=0$ has at least one real root, assuming that values $p$ and $q$ are independent and equiprobable. It's equivalent to the condition of non-negativity of the discriminant $D = p - 4q$. To solve this problem you might draw a rectangle on the (p,q)-plane with the vertices in points $(0, - b)$, $(a, - b)$, $(a, b)$ and $(0, b)$ and line $p = 4q$. Every point of the rectangle corresponds to possible value of $p$ and $q$ and the line divides the plane into two parts where the equation has real solutions and where it hasn't. Then because of equiprobability and independence of choosing $p$ and $q$ the answer is the area of the intersection of the rectangle and $p  \\ge  4q$ set divided by the area of the rectangle in case of it's nonsingularity ($a, b  \\neq  0$). If single number among $a$ and $b$ is equal to zero, the rectangle degenerates to the segment and the sough-for probability is equal to ratio of length of intersection of the segment and $p  \\ge  4q$ set and the lenght of the whole segment. In case $a = b = 0$ the answer is evident and equal to 1. Complexity is $O(t)$. If you are interested in why your solution gets \"wrong answer\" the mini-tests \"0 1\", \"1 0\" and \"0 0\" maybe helps you.",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "77",
    "index": "C",
    "title": "Beavermuncher-0xFF",
    "statement": "\"Eat a beaver, save a tree!\" — That will be the motto of ecologists' urgent meeting in Beaverley Hills.\n\nAnd the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end.\n\nIn the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title \"Beavermuncher-0xFF\". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science.\n\nThe prototype is ready, you now need to urgently carry out its experiments in practice.\n\nYou are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of $n$ vertices, the $i$-th vertex contains $k_{i}$ beavers.\n\n\"Beavermuncher-0xFF\" works by the following principle: being at some vertex $u$, it can go to the vertex $v$, if they are connected by an edge, and eat \\textbf{exactly one} beaver located at the vertex $v$. It is impossible to move to the vertex $v$ if there are no beavers left in $v$. \"Beavermuncher-0xFF\" \\textbf{cannot} just stand at some vertex and eat beavers in it. \"Beavermuncher-0xFF\" must move without stops.\n\nWhy does the \"Beavermuncher-0xFF\" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy.\n\nIt is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the \"Beavermuncher-0xFF\", it can move along each edge in both directions while conditions described above are fulfilled.\n\nThe root of the tree is located at the vertex $s$. This means that the \"Beavermuncher-0xFF\" begins its mission at the vertex $s$ and it must return there at the end of experiment, because no one is going to take it down from a high place.\n\nDetermine the maximum number of beavers \"Beavermuncher-0xFF\" can eat and return to the starting vertex.",
    "tutorial": "Let's assume that in vertix $v$ it is possible to find pair of values $< x_{i}, y_{i} >$ for every child $v_{i}$ where $x_{i}$ is maximal amount of beavers which can eat beavermuncher if it comes to vertix $v_{i}$ and return back, and $y_{i}$ is amount of beavers which will still alive in vertix $v_{i}$ after beavermuncher's ride. Let's sort all children $v_{i}$ by value of $x_{i}$. We should visit $v_{i}$ in sorted order from highest value of $x_{i}$ to lowest while there is possible to return back to root. If after ride to all children vertix $v$ contains of some non-eaten beavers we must continue eating by following way. Let's find some value of $y_{j}$ which is greater than zero. We should move to vertix $v_{j}$ and after that move back to $v$. This operation must be executed as many times as possible. Of course, the process shouldn't be emulated, we may repeat this way with vertix $v_{j}$ for $min(b, y_{j})$ times, where $b$ is amount of beavers in vertix $v$ which are remaining. So we find a pair $< x, y >$ for vertix $v$ by knowing values $< x_{i}, y_{i} >$ for every child $v_{i}$, where $x$ is amount of eaten beavers and $y$ is $b$ - number of remaining beavers. Answer is a value of $x$ for staring vertix $s$. Complexity is $O(n \\cdot  logn)$. If you are interested in why your solution gets \"wrong answer\" the tests with $n = 1$ maybe helps you.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "greedy",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "77",
    "index": "D",
    "title": "Domino Carpet",
    "statement": "...Mike the TV greets you again!\n\nTired of the monotonous furniture? Sick of gray routine? Dreaming about dizzying changes in your humble abode? We have something to offer you!\n\nThis domino carpet for only $99.99 will change your life! You can lay it on the floor, hang it on the wall or even on the ceiling! Among other things ...\n\nHaving watched the commercial, virus Hexadecimal also wanted to get a Domino Carpet and wanted badly to be photographed in front of it. But of course, a virus will never consent to buying a licensed Carpet! So she ordered a truck of dominoes and decided to make such a Carpet herself.\n\nThe original Domino Carpet is a field of squares $n × m$ in size. Each square is half of a domino, and can be rotated either vertically or horizontally, independently from its neighbors. Vertically rotated domino halves look like this:\n\nAnd horizontally rotated halves look like this:\n\nNotice, that some halves looks the same in both rotations, but other halves differ.\n\nDominoes bought by Hexadecimal are represented by uncuttable chips $1 × 2$ in size, which can be laid either vertically or horizontally. If the chip is laid vertically, then both of it's halves should be laid vertically orientated; if the chip is laid horizontally, then both of it's halves should be laid horizontally.\n\nThe samples of valid and invalid dominoes laid vertically and horizontally are:\n\nVirus Hexadecimal assembles her own Domino Carpet so that the following conditions are satisfied:\n\n- each carpet square is covered by a domino chip, i.e. there are no empty squares;\n- all domino chips lie entirely within the carpet and don't overlap with each other;\n- if there is a horizontal domino chip with its left half in column $j$ then there are no horizontal domino chips with their left halves in columns $j - 1$ or $j + 1$.\n\nBefore starting to assemble her own Domino Carpet, the virus wants to know the number of ways to achieve the intended purpose modulo $10^{9} + 7$.\n\nYou can assume that the virus has an infinitely large number of dominoes of each type.",
    "tutorial": "Look at squares of Domino Carpet. They are can be only in one of this three states: 1. Here can be any domino chip 2. Here can be only horizontal domino chip 3. Here can be only vertical domino chip No matter what is in squares, only their states are important. Look at the any pair of columns $j$ and $j + 1$ where in some row located horizontally chip of domino. We may cut this pair of jointed columns $n  \\times  2$ from carpet and don't be afraid about cutting some another chips. So, this pair of columns may be completed independently from another columns. If $n$ is even number it is possible to complete some columns of single width, not only pair of columns. There is only way to do this - we should put all dominoes vertically. This formula is describing all situations above: $d_{j} = (d_{j} - _{2} \\cdot  q_{j} - _{2}) + (d_{j} - _{1} \\cdot  p_{j} - _{1})$, where $j$ is an amount of completed columns, $p_{j}$ is an amount of all possible ways to complete only $j$-th column (it can be only 0 or 1) and $q_{j}$ is an amount of all possible ways to complete $j$-th and $j + 1$-th columns. Obviously, this formula is incorrect. If some pair of jointed columns we will complete by only vertical dominoes then this way will be counted twice. Let's use the fact that it is unique situation when this formula is incorrect and improve it: So, $d_{j} = (d_{j} - _{2} \\cdot  q_{j} - _{2}) + (d_{j} - _{1} \\cdot  p_{j} - _{1}) - (d_{j} - _{2} \\cdot  p_{j} - _{2} \\cdot  p_{j} - _{1})$. In $d_{m}$ is answer to the problem. The only trouble is we need to count $p_{j}$ and $q_{j}$. $p_{j}$ is 1 when $n$ is even and in $j$-th column there are no squares in state \"here can be only horizontal domino chip\". Otherwise $p_{j}$ is 0. $q_{j}$ can be found by dynamic programming. For every row we should try to put one horizontally oriented domino chip or two vertically oriented and use information about states in observable squares of carpet. Complexity is $O(n \\cdot  m)$.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "77",
    "index": "E",
    "title": "Martian Food",
    "statement": "Have you ever tasted Martian food? Well, you should.\n\nTheir signature dish is served on a completely black plate with the radius of $R$, flat as a pancake.\n\nFirst, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of $r$ and is located as close to the edge of the plate as possible staying entirely within the plate. I. e. Golden Honduras touches the edge of the plate from the inside. It is believed that the proximity of the portion of the Golden Honduras to the edge of a plate demonstrates the neatness and exactness of the Martians.\n\nThen a perfectly round portion of Pink Guadeloupe is put on the plate. The Guadeloupe should not overlap with Honduras, should not go beyond the border of the plate, but should have the maximum radius. I. e. Pink Guadeloupe should touch the edge of the plate from the inside, and touch Golden Honduras from the outside. For it is the size of the Rose Guadeloupe that shows the generosity and the hospitality of the Martians.\n\nFurther, the first portion (of the same perfectly round shape) of Green Bull Terrier is put on the plate. It should come in contact with Honduras and Guadeloupe, should not go beyond the border of the plate and should have maximum radius.\n\nEach of the following portions of the Green Bull Terrier must necessarily touch the Golden Honduras, the previous portion of the Green Bull Terrier and touch the edge of a plate, but should not go beyond the border.\n\nTo determine whether a stranger is worthy to touch the food, the Martians ask him to find the radius of the $k$-th portion of the Green Bull Terrier knowing the radii of a plate and a portion of the Golden Honduras. And are you worthy?",
    "tutorial": "The problem can be solved using the inversion conversion. Inversion is the conversion transfering a point with the polar coordinates $(r,  \\phi )$ to a point $\\bigl({\\frac{1}{\\tau}},\\varphi\\bigr)$. It's stated that the inversion transfers straight lines or circles to straight lines or circles. Straight line can be image only of line or circle that includes home (center of the inversion). Assume the plate a circle with center in $(R, 0)$ and radius $R$ and Honduras - circle with center in $(r, 0)$ ans radius $r$. Then Guadeloupe and Bull Terriers are situated as on the first picture. Picture 1. Original picture Picture 2. After inversion conversion After applying the inversion conversion the border of the plate transfers to the line $x={\\frac{1}{2R}}$ and the border of the honduras - to the line $x={\\frac{1}{2r}}$, Guadeloupe and Bull Terriers becomes circles between them, see the second picture. It's easy to find the $k$-th bull terrier on the picture after applying the conversion, the coordinates of it's center are $\\left({\\frac{R+r}{4r R}},k\\,{\\frac{k\\,\\ell-r}{2r R}}\\right)$. To find the radius of the bull terier draw a line through the home and the center of the image of the need honduras. It's possible to prove that the prototypes of this points are diametral points on the bull terrier. So the answer is the distance between them divided by two. Complexity is $O(t)$.",
    "tags": [
      "geometry"
    ],
    "rating": 2800
  },
  {
    "contest_id": "78",
    "index": "A",
    "title": "Haiku",
    "statement": "Haiku is a genre of Japanese traditional poetry.\n\nA haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.\n\nTo simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: \"a\", \"e\", \"i\", \"o\" and \"u\".\n\nThree phases from a certain poem are given. Determine whether it is haiku or not.",
    "tutorial": "You should count a number of vowels for every of three phrases. Next, you should compare this numbers with numbers 5, 7 and 5. If all is matched, answer is YES, otherwise answer is NO.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "78",
    "index": "B",
    "title": "Easter Eggs",
    "statement": "The Easter Rabbit laid $n$ eggs in a circle and is about to paint them.\n\nEach egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:\n\n- Each of the seven colors should be used to paint at least one egg.\n- Any four eggs \\textbf{lying sequentially} should be painted different colors.\n\nHelp the Easter Rabbit paint the eggs in the required manner. We know that it is always possible.",
    "tutorial": "At first, you can $[n / 7]$ times output string \"ROYGBIV\" ($[]$ is a rounding down). After than you can output \"\", \"G\", \"GB\", \"YGB\", \"YGBI\", \"OYGBI\" or \"OYGBIV\" according to remainder of division $n$ by 7. A resulting string will satisfy problem's requirements. You can also build answer in other way.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "78",
    "index": "C",
    "title": "Beaver Game",
    "statement": "Two beavers, Timur and Marsel, play the following game.\n\nThere are $n$ logs, each of exactly $m$ meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of \\textbf{equal} parts, the length of each one is expressed by an integer and is no less than $k$ meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.\n\nTimur makes the first move. The players play in the optimal way. Determine the winner.",
    "tutorial": "If $n$ is even, Marsel wins - he just symmetrically repeats moves of Timur. Now consider a case of odd $n$. If Timur cannot move - he is losing automatically. If he can do a move, he always can split one log into few parts that this parts cannot be splitted again. It can be done if we have find minimal $t$ that $k  \\le  t < m$ and $t|m$. Next we split log into parts with length $t$. Thereafter Timur symmetrically repeats moves of Marsel and wins. For checking that Timur could move or not, you can iterate over all divisors of $m$. If there is exists some divisor $t$ that $k  \\le  t < m$, Timar can do a move. Chech of all divisors can be done in $O({\\sqrt{m}})$ time.",
    "tags": [
      "dp",
      "games",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "78",
    "index": "D",
    "title": "Archer's Shot",
    "statement": "A breakthrough among computer games, \"Civilization XIII\", is striking in its scale and elaborate details. Let's take a closer look at one of them.\n\nThe playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playing field. The field can be considered infinite.\n\nLet's take a look at the battle unit called an \"Archer\". Each archer has a parameter \"shot range\". It's a positive integer that determines the radius of the circle in which the archer can hit a target. The center of the circle coincides with the center of the cell in which the archer stays. A cell is considered to be under the archer’s fire if and only if all points of this cell, including border points are located inside the circle or on its border.\n\nThe picture below shows the borders for shot ranges equal to $3$, $4$ and $5$. The archer is depicted as $A$.\n\nFind the number of cells that are under fire for some archer.",
    "tutorial": "It should be solved like a classical problem \"count the number of square cells 1x1 lying inside the circle\". Firstly, lets find the highest hexagon that lies inside the circle. Then we move to the right and up from this hexagon, and then go down until we find hexagon lying inside the circle. Repeat this process until you reach the rightmost part of the circle. Thus we can count number of hexagons in each column, answer is sum of this numbers. Total number of operations is $O(n)$. Few words about implementation. Coordinates of every considered point looks like $(\\frac{1}{2}x, \\frac{\\sqrt{3}}{2}y)$. That's why distance between this points and (0,0) should be calculated using integers only. For example, criteria \"point $(\\frac{1}{2}x, \\frac{\\sqrt{3}}{2}y)$ lies inside circle of radius $R$\" looks like $x^{2} + 3y^{2}  \\le  4R^{2}$. Also you can solve this problem in $O(n\\log n)$. For every column of hexagons you can find number of hexagons inside circle by using binary search.",
    "tags": [
      "binary search",
      "geometry",
      "math",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "78",
    "index": "E",
    "title": "Evacuation",
    "statement": "They've screwed something up yet again... In one nuclear reactor of a research station an uncontrolled reaction is in progress and explosion which will destroy the whole station will happen soon.\n\nThe station is represented by a square $n × n$ divided into $1 × 1$ blocks. Each block is either a reactor or a laboratory. There can be several reactors and exactly one of them will explode soon. The reactors can be considered impassable blocks, but one can move through laboratories. Between any two laboratories, which are in adjacent blocks, there is a corridor. Blocks are considered adjacent if they have a common edge.\n\nIn each laboratory there is some number of scientists and some number of rescue capsules. Once the scientist climbs into a capsule, he is considered to be saved. Each capsule has room for not more than one scientist.\n\nThe reactor, which is about to explode, is damaged and a toxic coolant trickles from it into the neighboring blocks. The block, which contains the reactor, is considered infected. Every minute the coolant spreads over the laboratories through corridors. If at some moment one of the blocks is infected, then the next minute all the neighboring laboratories also become infected. Once a lab is infected, all the scientists there that are not in rescue capsules die. The coolant does not spread through reactor blocks.\n\nThere are exactly $t$ minutes to the explosion. Any scientist in a minute can move down the corridor to the next lab, if it is not infected. On any corridor an unlimited number of scientists can simultaneously move in both directions. It is believed that the scientists inside a lab moves without consuming time. Moreover, any scientist could get into the rescue capsule instantly. It is also believed that any scientist at any given moment always has the time to perform their actions (move from the given laboratory into the next one, or climb into the rescue capsule) before the laboratory will be infected.\n\nFind the maximum number of scientists who will be able to escape.",
    "tutorial": "Firstly, let's calculate the following value: dp[t][x0][y0][x][y] == true iff scientist from block (x0,y0) can reach block (x,y) in time t, considering toxic coolant. Secondly, let's consider a graph consisting of 4 parts: 1 - source (one vertex) 2 - first fraction (nxn vertices) 3 - second fraction (nxn vertices) 4 - sink (one vertex) Each vertex of each fraction is for one block. Build edge from source to each vertex of the first fraction with capability as number of scientists in corresponding block. Build edge from each vertex of the second fraction to sink with capability as number of rescue capsules in corresponding block. Build edge from vertex (x0,y0) of the first fraction to vertex (x,y) of the second fraction iff dp[T][x0][y0][x][y]==true for at least one T. Capability of this edges is infinity. As one can see, value of maxflow in this graph is answer for the problem. Complexity of this solution is $O(tn^{4} + kn^{6})$, where $k$ is maximum possible number of scientists in each block(in this problem $k = 9$).",
    "tags": [
      "flows",
      "graphs",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "79",
    "index": "A",
    "title": "Bus Game",
    "statement": "After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus.\n\n- Initially, there is a pile that contains $x$ 100-yen coins and $y$ 10-yen coins.\n- They take turns alternatively. Ciel takes the first turn.\n- In each turn, they must take exactly 220 yen from the pile. In Ciel's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 100-yen coins. In Hanako's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 10-yen coins.\n- If Ciel or Hanako can't take exactly 220 yen from the pile, she loses.\n\nDetermine the winner of the game.",
    "tutorial": "Brute force simulation works in this problem. In Ciel's turn, if she has at least 2 100-yen coins and at least 2 10-yen coins, pay those coins. Otherwise, if she has at least 1 100-yen coins and at least 12 10-yen coins, pay those coins. Otherwise, if she has at least 22 10-yen coins, pay those coins. Otherwise, she loses. In Hanako's turn, do similar simulation in reverse order. The complexity of this solution is $O(x + y)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "79",
    "index": "B",
    "title": "Colorful Field",
    "statement": "Fox Ciel saw a large field while she was on a bus. The field was a $n × m$ rectangle divided into $1 × 1$ cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.\n\nAfter seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure:\n\n- Assume that the rows are numbered $1$ to $n$ from top to bottom and the columns are numbered $1$ to $m$ from left to right, and a cell in row $i$ and column $j$ is represented as $(i, j)$.\n- First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of $(1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m)$. Waste cells will be ignored.\n- Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on.\n\nThe following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell.\n\nNow she is wondering how to determine the crop plants in some certain cells.",
    "tutorial": "A solution that uses an array of $N  \\times  M$ will absolutely get (Time|Memory)LimitExceeded, so we cannot simulate it naively. Both the number of queries and the number of waste cells $K$ are not more than 1,000, so it is enough to answer each queries in $O(K)$ runtime. Let $(a, b)$ be a query cell. Whether $(a, b)$ is waste or not is determined by simple iteration. So let's consider about the case $(a, b)$ is not waste. Let $I$ be the number of cells including waste ones that will be sweeped before $(a, b)$, and $J$ be the number of waste cells that will be sweeped before $(a, b)$. Then, the answer is classified by the value of $(I - J)$ mod $3$ (for example, if the value = 0, the answer = \"Carrots\", and so on). By simple calculation, $I = (a - 1)M + (b - 1)$, and $J$ is calculated by $O(K)$ iteration. Overall, this problem can be solved in $O(KT)$ runtime, where $T$ is the number of queries.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "79",
    "index": "C",
    "title": "Beaver",
    "statement": "After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string $s$, and she tried to remember the string $s$ correctly.\n\nHowever, Ciel feels $n$ strings $b_{1}, b_{2}, ... , b_{n}$ are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of $s$.\n\nDetermine the longest contiguous substring of $s$ that does not contain any boring string, so that she can remember the longest part of Taro's response.",
    "tutorial": "We can regard a substring that is equal to one of boring strings as an interval. The number of such intervals are at most $|s| \\cdot  n$, and the required time to determine whether each of them is a boring string is $|b_{i}|$, so all intervals can be calculated in $O(|s| \\cdot  n \\cdot  |b_{i}|)$ runtime, by naive way. (Yes, no special string algorithm is required here.) The original problem can be rewritten as follows: you are given at most $10^{6}$ intervals on $[0, 10^{5}]$, determine the longest interval that does not contain any given interval. To solve this rewritten problem, define $right[i]$ be the leftest position of an interval whose left-endpoint is equal to $i$. If there is no interval whose left-endpoint is $i$, define $right[i]$ is $ \\infty $. Now we will calculate the optimal interval whose left-endpoint is $i$, in the order of $i = |s|, |s| - 1, |s| - 2, ... 0$. When $i = |s|$, corresponding right-endpoint is only $|s|$. Let's think the case when corresponding right-endpoint to $i + 1$ is $j$. If $right[i] > j$, then corresponding right-point to $i$ remains $j$. Otherwise, that right-point is updated to $right[i] - 1$. This iteration will be done in $O(|s|)$. Overall, $O(|s| \\cdot  n \\cdot  |b_{i}|)$ runtime.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "hashing",
      "strings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "79",
    "index": "D",
    "title": "Password",
    "statement": "Finally Fox Ciel arrived in front of her castle!\n\nShe have to type a password to enter her castle. An input device attached to her castle is a bit unusual.\n\nThe input device is a $1 × n$ rectangle divided into $n$ square panels. They are numbered $1$ to $n$ from left to right. Each panel has a state either ON or OFF. Initially all panels are in the OFF state. She can enter her castle if and only if $x_{1}$-th, $x_{2}$-th, $...$, $x_{k}$-th panels are in the ON state and other panels are in the OFF state.\n\nShe is given an array $a_{1}$, $...$, $a_{l}$. In each move, she can perform the following operation: choose an index $i$ ($1 ≤ i ≤ l$), choose consecutive $a_{i}$ panels, and flip the states of those panels (i.e. ON$ → $OFF, OFF$ → $ON).\n\nUnfortunately she forgets how to type the password with only above operations. Determine the minimal number of operations required to enter her castle.",
    "tutorial": "Define an array $b_{0}, b_{1}, ..., b_{n}$ as follows: If the states of $i$-th panel and $(i + 1)$-th panel are same, $b_{i} = 0$. If the states of $i$-th panel and $(i + 1)$-th panel are different, $b_{i} = 1$. (The states of $0$-th panel and $(n + 1)$-th panel are considered to be OFF.) If Ciel flips panels between $x$-th and $(x + a - 1)$-th, inclusive, the values of $b_{x}$ and $b_{x + a}$ are changed and other elements of b aren't changed. We can rewrite the problem: <Problem D'> You are given an 0-1 array $b_{0}, b_{1}, ..., b_{n}$. At most 20 (=$2k$) of them are $1$. In each move, you can change the values of $b_{x}$ and $b_{x + a}$, where a is an element of the given array and $0  \\le  x  \\le  n - a$. Determine the minimal number of moves required to change all elements in $b$ to $0$. The order of moves is not important. If there is an index $x$ s.t. $b_{x} = 1$, you must change $b_{x}$ at least once, so you can assume that the next move is performed on $x$. Assume that when you change the values of $b_{x}$ and $b_{x + a}$, at least one of them is $1$. <Problem D''> Let $V$ be the graph with $(n + 1)$ vertices. Vertices are numbered $0$ to $n$. There is an edge between vertex $v_{1}$ and vertex $v_{2}$ if and only if $|v_{1} - v_{2}|$ is an element of array a. Initially at most 20 vertices contain tokens. In each move, you can move a token along an edge. When two tokens meet, they disappear. Determine the minimal number of moves required to erase all tokens. First, calculate the distances between all pair of tokens by doing bfs $2k$ times. Next, do DP with bitmasks: Let $dp[S]$ (where $S$ is a set of tokens) be the minimal number of moves required to erase all tokens. If $S$ is empty, $dp[S] = 0$. If $S = {s_{0}, s_{1}, ..., s_{m - 1}}$ is nonempty, $dp[S] = min{dp[S\\{s_{0}, s_{i}}] + dist(s_{0}, s_{i})}$ where $1  \\le  i  \\le  m - 1$. The complexity of this solution is $O(knl + k \\cdot  2^{2k})$.",
    "tags": [
      "bitmasks",
      "dp",
      "shortest paths"
    ],
    "rating": 2800
  },
  {
    "contest_id": "79",
    "index": "E",
    "title": "Security System",
    "statement": "Fox Ciel safely returned to her castle, but there was something wrong with the security system of the castle: sensors attached in the castle were covering her.\n\nCiel is at point $(1, 1)$ of the castle now, and wants to move to point $(n, n)$, which is the position of her room. By one step, Ciel can move from point $(x, y)$ to either $(x + 1, y)$ (rightward) or $(x, y + 1)$ (upward).\n\nIn her castle, $c^{2}$ sensors are set at points $(a + i, b + j)$ (for every integer $i$ and $j$ such that: $0 ≤ i < c, 0 ≤ j < c$).\n\nEach sensor has a count value and decreases its count value every time Ciel moves. Initially, the count value of each sensor is $t$. Every time Ciel moves to point $(x, y)$, the count value of a sensor at point $(u, v)$ decreases by ($|u - x| + |v - y|$). When the count value of some sensor becomes \\textbf{strictly less than} $0$, the sensor will catch Ciel as a suspicious individual!\n\nDetermine whether Ciel can move from $(1, 1)$ to $(n, n)$ without being caught by a sensor, and if it is possible, output her steps. Assume that Ciel can move to every point even if there is a censor on the point.",
    "tutorial": "Lemma. The sensors we should consider are only four sensors at the corner. proof: Let's think about sensors at a fixed row $v$. As the definition, when Ciel entered to $(x, y)$, a sensor at $(u, v)$ decreases its count by $|x - u| + |y - v|$. Let this value be $f_{x, y}(u)$. If we fix Ciel's path, the total decrease of each sensor is expressed as the summation of $f_{x, y}(u)$, where $x, y$ is one of the path. Because $f_{x, y}(u)$ is a convex function about variable $u$ and the fact that \"the summation of convex functions is also a convex function\", we can ignore sensors at center points: i.e. $a < u < a + c - 1$. The same thing holds true for vertical direction, so it is enough to consider only four sensors at corner: $(a, b), (a + c - 1, b), (a, b + c - 1), (a + c - 1, b + c - 1)$. - Because we need the lexicographically first solution, we want to use 'R' rather than 'U' in each step. Thus, it is enough if we can determine whether a feasible path exists with constraints that Ciel is at $(x, y)$ and the rest counts of four corners are $T_{1}, T_{2}, T_{3}, T_{4}$. Lemma. Optimal step is following (except sensors region): proof: A following figure shows that if a blue path is good a brown path is also good. (Here, the blue path means arbitrary one, and the brown path means optimal one.) - The problem is sensors region. In sensors region, it is possible to assume that the optimal path always passes a right-top sensor. While Ciel moves in sensors region to right-top sensor, the total decrease of both left-bottom and right-top sensor is constant. So we should think about only two sensors: left-top and right-bottom. In addition, let the total decrease of left-top and right-bottom be $D_{1}$ and $D_{2}$. Then following holds: $D_{1} + D_{2} = const$. The smallest value for $D_{1}$ is the total decrease when Ciel moves upward then moves rightward, and the smallest value for $D_{2}$ is in the same way (moves rightward $ \\rightarrow $ upward). So we can calculate the minimal value and the maximal value of $D_{1}$. And actually, $D_{1}$ can be an arbitrary value between them with interval of 2. A following picture shows it. Complexity at a simulation part is O(1). Overall, the complexity is $O(N)$.",
    "tags": [
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "80",
    "index": "A",
    "title": "Panoramix's Prediction",
    "statement": "A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers $2$, $7$, $3$ are prime, and $1$, $6$, $4$ are not.\n\n{The next prime number after $x$ is the \\textbf{smallest} prime number greater than $x$. For example, the next prime number after $2$ is $3$, and the next prime number after $3$ is $5$. Note that there is exactly one next prime number after each number. So $5$ \\textbf{is not} the next prime number for $2$.}\n\nOne cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.\n\nPanoramix's prophecy tells that if some day Asterix and Obelix beat exactly $x$ Roman soldiers, where $x$ is a prime number, and next day they beat exactly $y$ Roman soldiers, where $y$ is \\textbf{the next prime number} after $x$, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.\n\nYesterday the Gauls beat $n$ Roman soldiers and it turned out that the number $n$ was prime! Today their victims were a troop of $m$ Romans ($m > n$). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?",
    "tutorial": "In the very beginning of statement you may find some words about what is prime number and what is next prime number. Main point of problem is to check is $m$ next prime after $n$ or not. Problem statement guarantees that $n$ is prime number. We need to check only two cases: 1. Number $m$ is prime, and 2. There is no any prime number between $n$ and $m$ Really, if there is prime number $k$ between $n$ and $m$ then $m$ cannot be next prime after $n$. Restrictions in this problem are really small and there is a way to solve it: for(int i=n+1;i<=m;i++) { if (prime(i)) { if (i==m) return \"YES\"; else return \"NO\"; } } return \"NO\"; where prime(i) is any correct way to check is number $i$ is prime. Another simple solution of this problem is to conside the fact that restrictions are no more than 50. It is possible to find all pairs $n$ and $m$ by hands and write solution formed by series of cases like this: if (n==2 && m==3) return \"YES\"; else if (n==3 && m==5) return \"YES\"; else ... else if (n==43 && m==47) return \"YES\"; else return \"NO\"; This solution gets \"accepted\" too. Complexity may be various because of diffenent realizations and is in range from $O(1)$ to $O(n + m)$. If you are interested in why your solution gets \"wrong answer\" the test \"2 5\" maybe helps you.",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "80",
    "index": "B",
    "title": "Depression",
    "statement": "Do you remember a kind cartoon \"Beauty and the Beast\"? No, no, there was no firing from machine guns or radiation mutants time-travels!\n\nThere was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle...\n\nEverybody was upset. The beautiful Belle was upset, so was the Beast, so was Lumiere the candlestick. But the worst thing was that Cogsworth was upset. Cogsworth is not a human, but is the mantel clock, which was often used as an alarm clock.\n\nDue to Cogsworth's frustration all the inhabitants of the castle were in trouble: now they could not determine when it was time to drink morning tea, and when it was time for an evening stroll.\n\nFortunately, deep in the basement are lying digital clock showing the time in the format HH:MM. Now the residents of the castle face a difficult task. They should turn Cogsworth's hour and minute mustache hands in such a way, that Cogsworth began to show the correct time. Moreover they need to find turn angles in degrees for each mustache hands. The initial time showed by Cogsworth is 12:00.\n\nYou can only rotate the hands forward, that is, as is shown in the picture:\n\nAs since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction.\n\nNote that Cogsworth's hour and minute mustache hands move evenly and continuously. Hands are moving independently, so when turning one hand the other hand remains standing still.",
    "tutorial": "The first I pay your attention is while we are moving first arrow the second one is stay motionless. In fact this means that we can solve next two problems independently: 1. Find the angle to turn the minute hand, and 2. Find the angle to turn the hours hand Next, you may find in statement phrase: \"Cogsworth's hour and minute mustache hands move evenly and continuously\". It means that after every little increasing of time $ \\Delta t$ both hands will move for some little angles. Number of minutes is always integer because of format HH:MM so every new minute will add $360 / 60 = 6$ angles to minute hand. For angle of hours hand influence number of hours and number of minutes. Every new hour will add $360 / 12 = 30$ angles to rotate and every new minute will add $(360 / 12) / 60 = 0.5$ angles. Thus, we should cut number of hours and number of minutes from HH:MM entry and use formulaes described above for finding the answer. Look at the time before midday and after noon carefully, analog watch has no difference between them and answers for 08:15 and 20:15 should be equal. Complexity is $O(1)$. If you are interested in why your solution gets \"wrong answer\" the tests \"20:15\" and \"00:00\" maybe helps you.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "82",
    "index": "A",
    "title": "Double Cola",
    "statement": "Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a \"Double Cola\" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum.\n\nFor example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny.\n\nWrite a program that will print the name of a man who will drink the $n$-th can.\n\nNote that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.",
    "tutorial": "Let's designate characters on the first letter of the name. The queue looks like: SH-L-P-R-G, through 5 cans: SH-SH-L-L-P-P-R-R-G-G, through 10 cans: SH-SH-SH-SH-L-L-L-L-P-P-P-P-R-R-R-R-G-G-G-G. The regularity is clear, and the solution is very simple: we will be iterated on $p$ - we will find such minimum $p$ that $5 \\cdot  2^{p} > n$ (thus if this number is less or equally we will subtract it from $n$) then we know that at first $2^{p}$ Sheldon's stand, then $2^{p}$ Leonard's and so on. And now we can easily answer who took a can number $n$ (namely there was a person with number $n / 2^{p}$ in sequence SH-L-P-R-G (in 0-indexation).",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "82",
    "index": "B",
    "title": "Sets",
    "statement": "Little Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose $n$ non-empty sets in such a way, that no two of them have common elements.\n\nOne day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on $n·(n - 1) / 2$ pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.\n\nFor example, if $n = 4$, and the actual sets have the following form ${1, 3}$, ${5}$, ${2, 4}$, ${7}$, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers:\n\n- $2, 7, 4$.\n- $1, 7, 3$;\n- $5, 4, 2$;\n- $1, 3, 5$;\n- $3, 1, 2, 4$;\n- $5, 7$.\n\nThen Vasya showed the pieces of paper to his friends, but kept the $n$ sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?",
    "tutorial": "For the solution the following important fact is required to us: we will admit elements $v$ and $u$ are in one set then in any of $n \\cdot  (n - 1) / 2$ of sequences from the input data where meets $v$ $u$ necessarily meets. And also if $v$ and $u$ are in different sets there is such sequence in which is $v$, but isn't present $u$. Then it is possible to enter the equivalence relation for all elements of all sets - two elements are equivalent, if there is no sequence where one element meets, and another isn't present. Classes of equivalence also are required sets. It was possible to consider the answer as following algorithm: we will write out for each number the list of numbers of sequences where there is this number, and will unite two numbers if these lists are equal. This algorithm can be realized for $O(n^{2} * log(n))$ however the solution for $O(n^{3})$ passes all tests with time large supply too. The special case is a test with $n = 2$. This test was used for a considerable quantity of hacks.",
    "tags": [
      "constructive algorithms",
      "hashing",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "82",
    "index": "C",
    "title": "General Mobilization",
    "statement": "The Berland Kingdom is a set of $n$ cities connected with each other with $n - 1$ railways. Each road connects exactly two different cities. The capital is located in city $1$. For each city there is a way to get from there to the capital by rail.\n\nIn the $i$-th city there is a soldier division number $i$, each division is characterized by a number of $a_{i}$. It represents the priority, the smaller the number, the higher the priority of this division. All values of $a_{i}$ are different.\n\nOne day the Berland King Berl Great declared a general mobilization, and for that, each division should arrive in the capital. Every day from every city except the capital a train departs. So there are exactly $n - 1$ departing trains each day. Each train moves toward the capital and finishes movement on the opposite endpoint of the railway on the next day. It has some finite capacity of $c_{j}$, expressed in the maximum number of divisions, which this train can transport in one go. Each train moves in the direction of reducing the distance to the capital. So each train passes exactly one railway moving from a city to the neighboring (where it stops) toward the capital.\n\nIn the first place among the divisions that are in the city, division with the smallest number of $a_{i}$ get on the train, then with the next smallest and so on, until either the train is full or all the divisions are be loaded. So it is possible for a division to stay in a city for a several days.\n\nThe duration of train's progress from one city to another is always equal to $1$ day. All divisions start moving at the same time and end up in the capital, from where they don't go anywhere else any more. Each division moves along a simple path from its city to the capital, regardless of how much time this journey will take.\n\nYour goal is to find for each division, in how many days it will arrive to the capital of Berland. The countdown begins from day $0$.",
    "tutorial": "At first we will estimate from above the maximum time to which all divisions will reach capital - obviously it is required no more $n$ days for this purpose. Therefore restrictions quite allowed model movements of divisions. The key moment of the solution - we will always consider divisions in priority order. Then in every day we will consider the list of those divisions who hasn't reached yet capital, and we will put in priority order on the necessary train. If the train is already filled, the division remains in a current city, differently we will change its position, and in day when the division will reach capital we will write down the answer. Total: in total days which it is necessary model, no more $n$, and every day we move no more $n$ divisions. So our solution has asymptotic form no more $O(n^{2})$. The solutions using various structures of the data (sets, turns with priorities etc.) work for $O(n^{2} \\cdot  log(n))$ and it didn't always keep within in TL.",
    "tags": [
      "data structures",
      "dfs and similar",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "82",
    "index": "D",
    "title": "Two out of Three",
    "statement": "Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem.\n\nLet the queue to the cashier contain $n$ people, at that each of them is characterized by a positive integer $a_{i}$ — that is the time needed to work with this customer. What is special about this very cashier is that it can serve two customers simultaneously. However, if two customers need $a_{i}$ and $a_{j}$ of time to be served, the time needed to work with both of them customers is equal to $max(a_{i}, a_{j})$. Please note that working with customers is an uninterruptable process, and therefore, if two people simultaneously come to the cashier, it means that they begin to be served simultaneously, and will both finish simultaneously (it is possible that one of them will have to wait).\n\nVasya used in his algorithm an ingenious heuristic — as long as the queue has more than one person waiting, then some two people of the first three standing in front of the queue are sent simultaneously. If the queue has only one customer number $i$, then he goes to the cashier, and is served within $a_{i}$ of time. Note that the total number of phases of serving a customer will always be equal to $⌈n / 2⌉$.\n\nVasya thinks that this method will help to cope with the queues we all hate. That's why he asked you to work out a program that will determine the minimum time during which the whole queue will be served using this algorithm.",
    "tutorial": "The problem dares the dynamic programming. We will consider a state $(i, j)$ meaning that in the current turn there is a person number $i$ and also all people from $j$ to $n$ inclusive. Any turn achievable of the initial can be presented by corresponding condition. The quantity of conditions is $O(n^{2})$, the quantity of transitions is only 3, that is $O(1)$. So the total asymptotic form is $O(n^{2})$.",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "82",
    "index": "E",
    "title": "Corridor",
    "statement": "Consider a house plan.\n\nLet the house be represented by an infinite horizontal strip defined by the inequality $ - h ≤ y ≤ h$. Strictly outside the house there are two light sources at the points $(0, f)$ and $(0, - f)$. Windows are located in the walls, the windows are represented by segments on the lines $y = h$ and $y = - h$. Also, the windows are arranged symmetrically about the line $y = 0$.\n\nYour task is to find the area of the floor at the home, which will be lighted by the sources of light.",
    "tutorial": "This problem has some solutions based on the various methods of the search of the area of the association of the figures on a plane. One of such methods is the method of vertical decomposition (more in detail you can esteem in various articles) and also it was possible to notice that among figures there are no three having non-zero crossing and consequently was to learn to find a total area of two figures enough. For this purpose also it was possible to use the various methods, for example, the author's solution is based on algorithm of cutting off of a convex polygon by a semiplane. Authors supposed the solution for $O(n^{2})$.",
    "tags": [
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "83",
    "index": "A",
    "title": "Magical Array",
    "statement": "\\underline{Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.}\n\nValera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its \\textbf{minimum and maximum coincide}.\n\nHe decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as \\textbf{non-empty sequence of consecutive elements}.",
    "tutorial": "We must find out all the intervals that consist of the same integers. For an interval with $P$ integers, the number of reasonable subsequences is $\\frac{P(P+1)}{2}$. Thus, we can adopt two pointers to find out all the target intervals, and calculate the answer.",
    "tags": [
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "83",
    "index": "B",
    "title": "Doctor",
    "statement": "There are $n$ animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number $i$ in the queue will have to visit his office exactly $a_{i}$ times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home.\n\nDoctor plans to go home after receiving $k$ animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out.",
    "tutorial": "The basic idea is still binary search. We use $a[n]$ to denote the given array. We use binary search to find out the maximum $T$ so that $S=\\sum_{0}^{n-1}m i n(a[i],T)\\leq K$. Moreover, we compute $K - S$ as the remainder. Then, any $a[i]$ that is not larger than $T$ should be firstly eliminated. Next we enumerate the first $K - S$ survived $a[j]$ in the natural order while decreasing them by one, and eliminate those $a[i]  \\le  T$ again. Finally, we start from the current position and output the survived indices one by one, by shifting to the right in a circular manner.",
    "tags": [
      "binary search",
      "math",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "83",
    "index": "C",
    "title": "Track",
    "statement": "You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest.\n\nThe track's map is represented by a rectangle $n × m$ in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters $S$) and the terminating square (it is marked with a capital Latin letter $T$). The time of movement from one square to another is equal to $1$ minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than $k$ \\textbf{different types} of squares (squares of one type can be visited an infinite number of times). Squares marked with $S$ and $T$ have no type, so they are not counted. But $S$ must be visited exactly once — at the very beginning, and $T$ must be visited exactly once — at the very end.\n\nYour task is to find the path from the square $S$ to the square $T$ that takes minimum time. Among all shortest paths you should choose the \\textbf{lexicographically minimal} one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types.",
    "tutorial": "I spent about three hours modifying the algorithm to avoid the time limit....The most impressive modification I used is scaling the constant from $1$ to $\\frac{1}{6}$. This is the first time that I realized what an important role that a constant can play. The general idea is to generate all the feasible patterns of maps and find out the one with the minimum distance and order. For instance, if letter 'a' and 'b' can be used, then we will obtain a map where we can move to positions of 'a' and 'b' while the other ones can not be used. With this equivalent map, we can implement BFS from the starting position until the terminating position is reached. During this process, we update the distance and also the minimum order if necessary. As $k$ can take values up to $4$, we may have to check as many as $C_{26}^{4}$ patterns for the worst case. It turns out that this will lead to TLE. Therefore, we have to further reduce the complexity. Instead of beginning from the starting position, we can begin from every one of the four positions that can be reached from the starting position. Each time we select one position, we have determined one letter that must be used and thus the number of feasible patterns is reduced to $C_{25}^{3}$, which is supposed to satisfy the time limit as I consider. However, I made a mistake that the number of generated patterns is in fact $A_{25}^{3}$ rather than $C_{25}^{3}$. As these two values only differ by a constant of $\\frac{1}{6}$, I did not realize (or believe) that such a constant matters so much. After I correct the mistake, it passed... What a fascinating problem!!",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "84",
    "index": "A",
    "title": "Toy Army",
    "statement": "The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy \"GAGA: Go And Go Again\". The gameplay is as follows.\n\nThere are two armies on the playing field each of which consists of $n$ men ($n$ is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore.\n\nThe game \"GAGA\" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends.\n\nYou are asked to calculate the maximum total number of soldiers that may be killed during the game.",
    "tutorial": "The strict proof seems to be a little complicated as far as I consider, however an intuitive understanding suggests that the answer is $n + n / 2$, and it is accpeted...",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "84",
    "index": "C",
    "title": "Biathlon",
    "statement": "Perhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section.\n\nOf course, biathlon as any sport, proved very difficult in practice. It takes much time and effort. Workouts, workouts, and workouts, — that's what awaited Valera on his way to great achievements in biathlon.\n\nAs for the workouts, you all probably know that every professional biathlete should ski fast and shoot precisely at the shooting range. Only in this case you can hope to be successful, because running and shooting are the two main components of biathlon. Valera has been diligent in his ski trainings, which is why he runs really fast, however, his shooting accuracy is nothing to write home about.\n\nOn a biathlon base where Valera is preparing for the competition, there is a huge rifle range with $n$ targets. Each target have shape of a circle, and \\textbf{the center of each circle is located on the $Ox$ axis}. At the last training session Valera made the total of $m$ shots. To make monitoring of his own results easier for him, one rather well-known programmer (of course it is you) was commissioned to write a program that would reveal how many and which targets Valera hit. More specifically, for each target the program must print the number of \\textbf{the first} successful shot (in the target), or \"-1\" if this was not hit. \\textbf{The target is considered hit if the shot is inside the circle or on its boundary.} Valera is counting on you and perhaps, thanks to you he will one day win international competitions.",
    "tutorial": "As it has been guaranteed that no two circles intersect with each other, the given point can only fall into at most one particular circle (one special case is that two circles touch each other at the given point). Thus, we first sort the circles in an increasing order of their X-coordinates, and find out two circles between which the give point falls (check the X-coordinate of the given point as well, and a special case is that the given point falls at one of two ends of all the circles), which can be achieved by using binary search. Then, the final step is to check which circle it falls inside, or completely outside all the circles.",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "85",
    "index": "C",
    "title": "Petya and Tree",
    "statement": "One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. \"That's not a problem!\", thought Petya. \"Why not count the expectation value of an element, which is found when I search for the key\". The moment he was about to do just that, however, Petya suddenly woke up.\n\nThus, you are given a \\underline{binary search tree}, that is a tree containing some number written in the node. This number is called the \\underline{node key}. The number of children of every node of the tree is equal either to $0$ or to $2$. The nodes that have $0$ children are called \\underline{leaves} and the nodes that have $2$ children, are called \\underline{inner}. An inner node has the \\underline{left child}, that is the child whose key is less than the current node's key, and the \\underline{right child}, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.\n\nAlso you are given a set of \\underline{search keys}, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the \\underline{search result}.\n\nIt is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.",
    "tutorial": "So, let remember statement of the problem. We have the correct binary search tree and the set of request keys. For each request key we consider paths in the tree with one error. These paths are constructed by the search of request key in the tree with one wrong choice of the next vertice. Each wrong choice generate one search path in the tree. At the beginning solve the problem for one request key. Consider the vertex of the path, after which the error occurred. Suppose that correct search at this vertex goes to the left child but we go to the right. This means that request key lies in key range of the left subtree and we go to the right subtree. Therefore further search of request key goes to the vertex of the right subtree with minimum key. Similar, if correct search goes to the right child but we go to the left, then further search goes to the vertex with maximum key in left subtree. Count maximum and minimum keys for each subtree of the all tree. This is done by the depth-first search. If we know minimum and maximum keys for all subtrees, there is easy to count answer for given request key. Execute search of the request key and accumulate values of minimum or maximum keys of subtrees where we go with one error. Now solve the problem for all request keys. Note that the answer for request key depends of only final vertex of the correct search in the tree. Therefore count answer for all leafs of the tree by one depth-first search. For all request keys we need to find final vertex of the search very fast. Put all keys of all vertices of the tree in ordered array. Note that keys of inner vertices and keys of leafs are alternated in this array. So, for each request key find nearest left and right keys in this array using binary search. One of this keys belongs to the leaf. Answer for this leaf would be answer for given request key. Thus, solution of the problem requires two depth-first searches and $k$ binary searches in array. So, running time is $O(n+k\\log n)$, where $n$ is a number of vertices in the tree and $k$ is a number of request keys.",
    "tags": [
      "binary search",
      "dfs and similar",
      "probabilities",
      "sortings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "86",
    "index": "A",
    "title": "Reflection",
    "statement": "For each positive integer $n$ consider the integer $ψ(n)$ which is obtained from $n$ by replacing every digit $a$ in the decimal notation of $n$ with the digit $(9 - a)$. We say that $ψ(n)$ is the reflection of $n$. For example, reflection of $192$ equals $807$. Note that leading zeros (if any) should be omitted. So reflection of $9$ equals $0$, reflection of $91$ equals $8$.\n\nLet us call the weight of the number the product of the number and its reflection. Thus, the weight of the number $10$ is equal to $10·89 = 890$.\n\nYour task is to find the maximum weight of the numbers in the given range $[l, r]$ (boundaries are included).",
    "tutorial": "First note that if the interval contains a number with $a$ digits and a number with $b$ digits (where $a$ > $b$) then there is no need to consider the number with $b$ digits (as the weight of $10^{k}$ is greater then the weights of the numbers less than $10^{k}$). If we consider only numbers with fixed number of digits $(s + 1)$, then the sum of $a$ and its reflection is constant. Thus, as product grows as multipliers with fixed sum get closer, the picture is the following: the weight grows from $10^{s}$ to $5 \\cdot  10^{s} - 1$, then it stays the same for $5 \\cdot  10^{s}$ and then it goes down, and reaches its minimum (zero) value at $10^{s + 1} - 1$. This is the proof, and the solution is: the maximum weight is reached at either $l$, $r$ or $5 \\cdot  10^{s}$ (we may check all the $s$ such that $5 \\cdot  10^{s}$ belongs to the interval, for example).",
    "tags": [
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "86",
    "index": "B",
    "title": "Tetris revisited",
    "statement": "Physicist Woll likes to play one relaxing game in between his search of the theory of everything.\n\nGame interface consists of a rectangular $n × m$ playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean connectivity by side) figures of 2, 3, 4 and 5 cells, with all their rotations and reflections. Player can copy any figure from the dashboard and place it anywhere at the still empty cells of the playing field. Of course any figure can be used as many times as needed.\n\nWoll's aim is to fill the whole field in such a way that there are no empty cells left, and also... just have some fun.\n\nEvery initially empty cell should be filled with exactly one cell of some figure. Every figure should be entirely inside the board.\n\nIn the picture black cells stand for initially filled cells of the field, and one-colour regions represent the figures.",
    "tutorial": "It's easy to see that the field may be filled with such figures if and only if there is no isolated cell. There are many different ways to do that, we will show some of them. 1. Domino filling. We construct greedy matching on the cells of our field combining them in domino-like figures (rectangles 1 $ \\times $ 2). Passing through the array that represents our field (from left to right, from top to bottom) we combine the still free horizontal pairs of connected cells into the horizontal dominoes. Then we do the same thing with the still free vertical pairs. Naturally, some cells may be still free. But such cells should be adjoined with some of the dominoes (if they were not isolated). We may attach each of these cells to any of the adjoint dominoes. All resulting figures will contain no more than 5 cells, because the cells still empty after matching can not be neighbour cells and can not be adjacent to the left side of dominoes (by the virtue of the order of our matching). The last thing that has to be done is the coloring of the figures in accordance with the output format. For example, we may color them like that: color all the cells in the plane in 9 colors (i, j) -> (i % 3) * 3 + j % 3. Then paint each domino in the color of its black cell (according to chess coloring). Each figure will have the color of the domino it grows from. 2. Greedy. We pass through the array representing the field, again in the same order. Figure for any still free cell may be constructed greedily, but we have to be accurate in order to avoid appearance of new isolated cells. So we just add all the cells that do become isolated when we fill the current figure. Acting in such a fashion we will eventually get the covering by the figures of no more than 5 cells (and at least two, of course). It is possible to color the figure immediately after its formation. We only need to check the colors of all already colored adjacent figures and to take any color, different from all of them. It is not hard to see that 10 colors are enough.",
    "tags": [
      "constructive algorithms",
      "graph matchings",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "86",
    "index": "C",
    "title": "Genetic engineering",
    "statement": "\"Multidimensional spaces are completely out of style these days, unlike genetics problems\" — thought physicist Woll and changed his subject of study to bioinformatics. Analysing results of sequencing he faced the following problem concerning DNA sequences. We will further think of a DNA sequence as an arbitrary string of uppercase letters \"A\", \"C\", \"G\" and \"T\" (of course, this is a simplified interpretation).\n\nLet $w$ be a long DNA sequence and $s_{1}, s_{2}, ..., s_{m}$ — collection of short DNA sequences. Let us say that the collection filters $w$ iff $w$ can be covered with the sequences from the collection. Certainly, substrings corresponding to the different positions of the string may intersect or even cover each other. More formally: denote by $|w|$ the length of $w$, let symbols of $w$ be numbered from $1$ to $|w|$. Then for each position $i$ in $w$ there exist pair of indices $l, r$ ($1 ≤ l ≤ i ≤ r ≤ |w|$) such that the substring $w[l ... r]$ equals one of the elements $s_{1}, s_{2}, ..., s_{m}$ of the collection.\n\nWoll wants to calculate the number of DNA sequences of a given length filtered by a given collection, but he doesn't know how to deal with it. Help him! Your task is to find the number of different DNA sequences of length $n$ filtered by the collection ${s_{i}}$.\n\nAnswer may appear very large, so output it modulo $1000000009$.",
    "tutorial": "Suppose we've built a string $wp$ of length $k < n$ and want to know how many ways there exist to complement $wp$ to the suitable string of length $n$. What parameters do we need to know in order to build it further? First of all, we need to know the index $wp$ is covered up to (we denote it by $ci$ and call it covering index). Also we want to have some information about what the string ends with. Here comes rather standard idea: let's find all the prefixes $ALL_{P}$ of the {$s_{i}$} and add to our state the largest prefix $p_{k}\\in A L L_{P}$ such that $wp$ ends with $p_{k}$ (as an alternative, you may consider a vertex in a trie constructed with the collection's strings). Now I'll try to convince you that it's enough to set the things going. First of all, when we add a symbol $c$ to $wp$ we can easily get $p_{k + 1}$ and it will be equal to the largest string in $ALL_{P}$ such that the string $p_{k} + c$ ends with (we can precalculate all the transitions in advance). So the only thing we want to know how to calculate (in order to use dynamic programming approach) is the new covering index. But we notice that it can be changed only by some string from the collection that $w_{p} + c$ ends with. Now we observe that it is sufficient to check only the largest from all such strings (denote it $fs$), and that it necessarily contains in $p_{k + 1}$ (so it also can we easily precalculated for all strings in $ALL_{P}$). We observe further that the new covering index depends only on the length of $fs$: it either equals the old one if $fs$ doesn't cover the symbol $ci + 1$, or equals to ($k + 1$) if the $fs$ covers that symbol. After calculating all the quantities d[k][k - cov.index][max. prefix] the required number of strings equals the sum of d[n][0][mp] for all $mp$.",
    "tags": [
      "dp",
      "string suffix structures",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "86",
    "index": "D",
    "title": "Powerful array",
    "statement": "An array of positive integers $a_{1}, a_{2}, ..., a_{n}$ is given. Let us consider its arbitrary subarray $a_{l}, a_{l + 1}..., a_{r}$, where $1 ≤ l ≤ r ≤ n$. For every positive integer $s$ denote by $K_{s}$ the number of occurrences of $s$ into the subarray. We call the power of the subarray the sum of products $K_{s}·K_{s}·s$ for every positive integer $s$. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite.\n\nYou should calculate the power of $t$ given subarrays.",
    "tutorial": "Let's solve the problem offline in O(n sqrt(t)) time and O(n) memory. For the simplicity of the reasoning let t = n. Assume we know the answer to the problem for some interval and want to find it to another one. Let us move the left end of the first one towards the left end of the second, similarly dealing with the right ends. By moving the end by one and for every value in the array maintaining the number of its appearances in the current interval, we will be able to calculate the answer and maintain the numbers of appearances at the same time in O(1). From now on we call the procedure of movement by 1 a step. Going through the queries in such a fashion, evidently, will cost us O(n^2) steps. Let p = sqrt(n). Divide the array into p equal parts Q_1, ..., Q_p. Now consider the queries of the form (Q_i, Q_j) for all i and j (there will be approx. n such queries). Clearly, there doesn't exist an order in which we can go through the queries in o(n sqrt(n)) time as the transition from any interval to the other one is done in no less than sqrt(n) steps. Nevertheless, there exists a traversal order that guarantees O(n sqrt(n)) steps in the worst case. Let's sort the query intervals according to the following rule: first come the intervals with the left ends in Q_1, then the intervals with the left ends in Q_2, and so on. And if the left ends of the two queries belong to the same part, then the interval with the more left right end is assumed to be smaller. In order to prove the stated asymptotic behavior we will follow the steps of the left and the right ends independently. We note that the left ends that belong to the same Q_i make <= n / p steps, and transition to Q_{i+1} costs no more than 2 * n / p steps. Therefore the left ends make <= n/p * n + 2*n steps (the second summand is O(n), and it's negligible). The right ends in the common group move only to the right, and this proves <= n * p steps (during the whole process) estimate. We will estimate the transition to the next Q_i at no more than n steps, so overall we get <= 2 * n * p steps. Thus, the total number of steps is no more than (n / p * n + 2 * n * p). Now we choose p = sqrt(n) which proves the statement. Solution: let us sort the queries by this rule, then make transitions from a query to the next one according to the obtained order. Note 1. There is nothing special (except for nonadditivity) with the function in the statement. Note 2. In the case of distinct n and t we can similarly prove the nice estimate 2 * n * sqrt(t), mostly nice because of its exactness (if you follow the proof carefully, you will easily construct the maximal test).",
    "tags": [
      "data structures",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "86",
    "index": "E",
    "title": "Long sequence",
    "statement": "A sequence $a_{0}, a_{1}, ...$ is called a recurrent binary sequence, if each term $a_{i}$ $(i = 0, 1, ...)$ is equal to 0 or 1 and there exist coefficients $c_{1},c_{2},\\dots,c_{k}\\in\\{0,1\\}$ such that\n\n\\[\na_{n} = c_{1}·a_{n - 1} + c_{2}·a_{n - 2} + ... + c_{k}·a_{n - k} (mod 2),\n\\]\n\nfor all $n ≥ k$. Assume that not all of $c_{i}$ are zeros.Note that such a sequence can be uniquely recovered from any $k$-tuple ${a_{s}, a_{s + 1}, ..., a_{s + k - 1}}$ and so it is periodic. Moreover, if a $k$-tuple contains only zeros, then the sequence contains only zeros, so this case is not very interesting. Otherwise the minimal period of the sequence is not greater than $2^{k} - 1$, as $k$-tuple determines next element, and there are $2^{k} - 1$ non-zero $k$-tuples. Let us call a sequence long if its minimal period is exactly $2^{k} - 1$. Your task is to find a long sequence for a given $k$, if there is any.",
    "tutorial": "Firstly let's note that there are only 49 different possible inputs. So any solution that works finite time at all tests (even if does not pass timelimit) is enough, because we can memorize all the answers. It is not necessary, of course, but may help with slow solutions. Then, let's answer a more particular question. Assume that $c_{1}, c_{2}, ..., c_{k}$ and $a_{0}, a_{1}, ..., a_{k - 1}$ are already given and we need to check whether the sequence ${a_{i}}$ generated by them is long or not. We know that if it is periodic, then it is possible to find any non-zero k-tuple among k-tuples $a_{s}, a_{s + 1}, ..., a_{s + k - 1}$. So initial k-tuple has no real matter if only it is not zero. Thus the property of sequence \"to be long\" depends only on coefficients $c_{i}$, and we may choose any convenient $a_{0}, a_{1}, ..., a_{k - 1}$. We will now think that $a_{0}, a_{1}, ..., a_{k - 2}$ are zeros and $a_{k - 1} = 1$. Consider the transition matrix $A$ of our sequence: for $i < k$ the $i$-th row of $A$ is equal to $(0, 0, ... 0, 1, 0, ..., 0)$ with 1 at $(i + 1)$-th position and last row of $A$ is equal to $(c_{k}, c_{k - 1}, ..., c_{2}, c_{1})$. Denote by $x_{s}$ vector $(a_{s}, a_{s + 1}, ..., a_{s + k - 1})^{T}$. Then for any integer $s$ we have: $A \\cdot  x_{s} = x_{s + 1}$. Last is just a reformulation of the recurrent formula: $a_{n} = c_{1} * a_{n - 1} + c_{2} * a_{n - 2} + ... + c_{k} * a_{n - k}.$ Then by obvious induction we have: $A^{p} \\cdot  x_{s} = x_{s + p}$ for any $p  \\ge  0$. Hence $p$ is a period iff for any vector $x$ that appears in our sequence: $A^{p} \\cdot  x = x$. If the sequence is not long then it is not self-evident still that $A^{p}$ is an identity matrix, because $x$ does not take all possible values. But we have chosen $x_{0} = (0, 0, ..., 0, 1)$ before, so it is obvious that vectors $x_{0}, x_{1}, x_{2}, ..., x_{k - 1}$ form a basis. Hence if $A^{p} \\cdot  x_{i} = x_{i}$ for any $i$ then $A^{p}$ is the identity matrix. So we just need to do the following: 1) Construct the matrix $A$ from the coefficients $c_{i}$. 2) Check that $A^{2k - 1}$ is the identity matrix. (If not, then $2^{k} - 1$ is not a period.) If $2^{k} - 1$ is a period, then we have to check that it is minimal. Minimal period divides any period so we only need to check the divisors of $2^{k} - 1$. 3) Generate all maximal divisors of $2^{k} - 1$ and check that they are not periods (using $A$ again). (By maximal divisor of n we mean divisors of the type n/q where q is a prime number.) Last thing we need to notice that such a sequence always exists. Moreover, amount of appropriate sets of $c_{i}$ is pretty large. One may prove that there are $\\textstyle{\\frac{\\varphi(2^{k}-1)}{k}}$ such sets (because they correspond to the coefficients of the irreducible factors of the cyclotomic polynomial over $\\mathbb{F}_{2}$). So we can just take them at random and check.",
    "tags": [
      "brute force",
      "math",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "87",
    "index": "A",
    "title": "Trains",
    "statement": "Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.\n\nWhen Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every $a$ minutes, but a train goes to Masha's direction every $b$ minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample).\n\nWe know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously.\n\nHelp Vasya count to which girlfriend he will go more often.",
    "tutorial": "This problem can be approached from two sides - from a programmer's perspective and a mathematician's one. We consider both approaches. First, let's write some general propositions. Let's put on a straight line all the moments of time when the trains arrive. We will refer the interval between two successive points to the girl, to who the train that matches the right end of the segment is going. Also note that the entire picture is periodic with the period equal to lcm(a, b). Vasya will obviously more often visit the girl, whose total length of the segments is larger. The programming approach is about modeling the process. If we need to compare the lengths of two sets of intervals, then let's count them. We can do it using two pointers. Let's see what train comes next, add time before the arrival of the train to one of the answers, move the pointer and the current time. We should stop either when two last trains arrive simultaneously or when arrive a+b trains. The solution has asymptotic $O(a + b)$, that fits the time limit. Don't forget that lcm(a,b) ~ 10^12, i.e., we need the 64-bit data type. The mathematical approach provides us with a more elegant and shorter solution, however, it takes more thinking. It seems obvious that Vasya will more often go to the girl, to who trains go more often. This fact is almost true. Let's try to prove it. Let's divide a and b by their gcd - from this, obviously, nothing will change. To make it clearer, let $a  \\le  b$. Let's calculate the total length of segments corresponding to the second girl. For this, we need to take a few facts into consideration. 1) All of them do not exceed a 2) All a segments are different (due to coprimeness of a and b). 3) They all are at least 1. But such a set of intervals is unique - it's set of numbers {1, 2,  \\dots  , a} and its length equals $\\textstyle\\sum_{i=1}^{a}i={\\frac{a\\cdot(a+1)}{2}}\\leq{\\frac{a\\,b}{2}}$. Besides, the equality is fulfilled when the following condition is met: $b - a = 1$. Hence the following is true. The answer is Equal, when $|a - b| = 1$, otherwise Vasya goes more often to the girl to which the trains go more often. The key is not to forget to divide a and b by their gcd.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "87",
    "index": "B",
    "title": "Vasya and Types",
    "statement": "Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.\n\nThere is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type $X$ — that will result in new type $X * $. That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of $X$, which is a pointer, you can add an ampersand — that will result in a type $&X$, to which refers $X$. That is called a dereference operation.\n\nThe &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.\n\n- The operator \"typedef $A$ $B$\" defines a new data type $B$, which is equivalent to $A$. $A$ can have asterisks and ampersands, and $B$ cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.\n- The operator \"typeof $A$\" returns type of $A$, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.\n\nAn attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype*$ = $&errtype$ = $errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.\n\nUsing typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.\n\nLet us also note that the dereference operation has the lower priority that the pointer operation, in other words $&T * $ is always equal to $T$.\n\nNote, that the operators are executed consecutively one by one. If we have two operators \"typedef &void a\" and \"typedef a* b\", then at first a becomes errtype, and after that b becomes errtype* = errtype, but \\textbf{not} &void* = void (see sample 2).\n\nVasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.",
    "tutorial": "In this task, it was necessary to do exactly what is written in the problem's statement, for practically any complexity. You are suggested to do the following. For each data type we shall store two values - its name and the number of asterisks when it is brought to void. Then the typeof request is processed by consecutively looking at each element of an array of definitions, in which we find the desired name of the type and the number of asterisks in it. The type errtype is convenient to store as void, to which we added $- inf$ asterisks. Thus, fulfilling a typedef request, we find the number of asterisks in the type A, add to it a number of asterisks and subtract the number of ampersands. Do not forget to replace any negative number of asterisks by $- inf$, and create a new definition of type B, removing the old one.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "87",
    "index": "C",
    "title": "Interesting Game",
    "statement": "Two best friends Serozha and Gena play a game.\n\nInitially there is one pile consisting of $n$ stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of $a_{1} > a_{2} > ... > a_{k} > 0$ stones. The piles should meet the condition $a_{1} - a_{2} = a_{2} - a_{3} = ... = a_{k - 1} - a_{k} = 1$. Naturally, the number of piles $k$ should be no less than two.\n\nThe friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?",
    "tutorial": "In this task you should analyze the game. However, due to the fact that with every move the game is divided into several independent ones, the analysis can be performed using the Grundy's function (you can read about it here, or here). Now all we have to do is to construct edges for each position. We can build the edges separately for each vertex by solving $k=O({\\sqrt{n}})$ simple linear equations for each number of piles after splitting. We can construct all the divisions in advance, simply taking one by one the smallest pile and the number or piles and terminating when the sum exceeds $n$. The second way is better because it works for the $O(m + n)$, where m stands for the number of edges, and the first one works for $O(n{\\sqrt{n}})$, which is larger. We should evaluate m in the maximal test. The edges are no more than $k n=O(n{\\sqrt{(n)}})$. However, in practice they are much less - about 520 thousand. Which is why there's enough time to build the edges within the time limit of $O(nk)$. You can try to find a Grundy's function by the definition if we xor all the required values for each position. But this may not work: it has too many long partitions (solutions with lazy countings or other ideas was working, though). Let's learn how to quickly count a Grundy's xor function for a long partition. Let's use a standard method for counting functions on the interval - $xor[l, r] = xor[0, r]\\^xor[0, l - 1]$. In the course of the algorithm we will keep a xor on a prefix of $xor[i]$ up to $i$. Then the xor on the interval can also be calculated as O(1). The solution was strictly successful due to the number of edges, which is not very large.",
    "tags": [
      "dp",
      "games",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "87",
    "index": "D",
    "title": "Beautiful Road",
    "statement": "A long time ago in some country in Asia were civil wars.\n\nEach of $n$ cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city.\n\nRoad making was difficult, so the country had few roads, exactly $n - 1$. Also you could reach any city from any other city going on those roads.\n\nEven during the war the Oriental people remain spiritually rich and appreciate the beauty of nature. And to keep the memory of this great crusade for the centuries to come, they planted one beautiful tree by the road on which the army spent most time. The Oriental people love nature, that's why if there were several such roads, then one tree was planted by each of them.\n\nRecently, when the records of the war were found, it became clear that each city attacked each other one exactly once. There were exactly $n(n - 1)$ attacks in total. Everyone has been wondering what road after those wars became the most beautiful, that is, by which road they planted the largest number of beautiful trees.",
    "tutorial": "In this task we should count for each edge the number of ways on which it is maximal. Since for one edge alone it does not seem possible to find the answer faster than in the linear time, the solution will compute answer for all the edges at once. We shall solve the problem first for the two extreme cases, then, combining these two we will obtain a complete solution. The first case is when the weights of all edges are identical. In this case we can solve the problem via DFS. For each edge, we just need to count the number of paths that this edge lies on it. This number is the product of the number of vertexes on different sides of the edge. If we count the number of vertexes on one side from it, while knowing the total number of vertexes in the tree, it is easy to find the number of vertexes on the other side of it, and hence the required number of ways on which it lies. The second case - when the weights of all edges are distinct. Sort the edges in the order of the weight's increasing. Initially we take a graph with no edges. We add an edge in the order of increasing of weight. For each edge we join the connected components it connects. Then the answer for each new added edge is the product of the size of components that it has connected. Now we must combine these two cases. We will add the edges in the ascending order, but not one by one, but in the groups of the equal weight. We should understand what the answer is for each of the added edges. After adding our edges some number of connected components was formed - for each edge, we calculate the same product of the number of vertexes on different sides inside his newly formed connected component. To find this number of edges on the different sides, we should realize that it is only enough to know the sizes of the old connected components and connections between them - how they were arranged is not important to us. We use a DSU: adding an edge to our forest, we combine the old connected components by these edges. Note that prior to the merging of the components we must calculate an answer for our edges - and it is possible to make via a DFS on our compressed forest as in the first case, only instead of the number of vertexes on different sides of the edge we take the sum of the sizes of the connected components on different sides of the edge. How to do it neatly: It's good idea to dynamically create compressed graph at each step: it will have O(E') vertexes and edges, where E' - the number of added edges of the source tree. Do not create unnecessary vertexes in the new created compressed column: after all, the DFS works for O(V + E), rather than O(E), so the unused connected components we do not include in the circuit. We should use the 64-bit data type. To store the response of the order of $(10^{5})^{2}$ it will fit more than the 32-bit one. We should not merge the adjacency lists explicitly when connecting components. It is too long. You can do everything instead of arrays on vectors / maps / heap, so the total time of nulling of the marks for an array of DFS occupied O(V). Or, instead of nulling of the array overlays we keep instead of a Boolean flag the iteration number. In general, it is better not to null extra arrays. After all, algorithm can make V iterations. Be careful, solutions with map works at TL's maximum, so it should be written very carefully; you should better use the vectors + list of involved nodes. The author's solution with the map fits in the TL with only half a second to spare. While using a vector has a four-time stock of time to spare.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "implementation",
      "sortings",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "87",
    "index": "E",
    "title": "Mogohu-Rea Idol",
    "statement": "A long time ago somewhere in the depths of America existed a powerful tribe governed by the great leader Pinnie-the-Wooh. Once the tribe conquered three Maya cities. Pinnie-the-Wooh grew concerned: there had to be some control over the conquered territories. That's why he appealed to the priests of the supreme god Mogohu-Rea for help.\n\nThe priests conveyed the god's will to him: to control these three cities he should put an idol to Mogohu-Rea — that will create a religious field over the cities. However, the idol is so powerful that it can easily drive the people around it mad unless it is balanced by exactly three sacrifice altars, placed one in each city. To balance the idol the altars should be placed so that the center of mass of the system of these three points coincided with the idol. When counting the center of mass consider that all the altars have the same mass.\n\nNow Pinnie-the-Wooh is thinking where to put the idol. He has a list of hills, that are suitable to put an idol there. Help him to identify on which of them you can put an idol without risking to fry off the brains of the cities' population with the religious field.\n\nEach city has a shape of a convex polygon such that no three vertexes lie on a straight line. The cities can intersect. Each altar should be attached to the city through a special ceremony, besides, it must be situated on the city's territory (possibly at the border). Thus, there may be several altars on a city's territory, but exactly one of them will be attached to the city. The altars, the idol and the hills are points on the plane, some of them may coincide.\n\nThe hills are taken into consideration independently from each other, the altars' location for different hills may also be different.",
    "tutorial": "In this task we had to verify that the point is the centroid of the triangle formed by points of the given three polygons. Lets reformulate the problem. We should verify the existence of three points A, B, C, such that A belongs to the first polygon, B - to the second one, C - to the third one, and ${\\overrightarrow{O A}}+{\\overrightarrow{O B}}+{\\overrightarrow{O C}}=3{\\overrightarrow{O Q}}$. Logically, you should understand what set of points determines this ${\\overrightarrow{O A}}+{\\overrightarrow{O B}}+{\\overrightarrow{O C}}$, you should understand how to build it and test a point on whether it belongs to the set or not. This set is called Minkowski sum. We will need only one of its properties: the sum of two convex polygons is a convex polygon whose sides coincide as vectors, with the sides of the original polygons. We will prove this later. How do we use it now? The first thing that this property gives us is an algorithm to test for belonging. Once the sum is built you can test whether or not a point belongs to the sum using a standard algorithm of testing a point being inside of a convex polygon in logarithmic time. Also the constructing algorithm is immediately obtained. We just need to add the coordinates of the lowest (the leftmost of them) points of all three polygons. As a result, we get a point, which is the lower left for the sum polygon. The sides are now represented as a sorted by the polar angles list of parties of the original polygons (instead of sorting we may merge sorted arrays). Proof. We shall prove the correctness of the algorithm for two polygons, for three polygons the proof is just the same. Let the first polygon be represented by A and the second one - by B. Denote the sum as M. We will prove that M is a convex set. Choose some $X,Y:X\\neq Y,X,\\ell\\in M$. By definition, $X=P+Q,Y=E+F:P,E\\in A,$ Q, $F\\in B$(here and below the point is identified with its radius vector). Let's take some point $G\\in[A B]$. We shall prove that $G\\in M$. As G lies on the [AB], $\\begin{array}{c}{{\\exists\\lambda\\in\\left[0,1\\right]:G=X*\\lambda+Y*\\left(1-\\lambda\\right)=\\left(P+P\\right)*\\lambda+\\left(E+F\\right)*\\left(1-\\lambda\\right)=0}}\\\\ {{\\left(P*\\lambda+E*\\left(1-\\lambda\\right)+\\left(Q*\\lambda+F*\\left(1-\\lambda\\right)\\right)}}\\end{array}$. Note that the first bracket is obviously some point lying on the segment [PE]. That means the point lying inside the polygon A, since A is convex. Similarly, the second bracket is inside B. Hence, their sum, i.e., G, lies in the Minkowski sum. This means that the Minkowski sum is a convex set. Let us consider some side XY of the first polygon. Let's rotate the plane so that the side XY was horizontal and that the polygon lied above the XY line. Consider the lowest horizontal line intersecting B. Let it cross B along the segment of PR, where point P does not lie further to the right of the R (it is clear that PR can turn out to be a degenerate segment from one vertex or the segment between two consquent verteces). Let's call PR the lowest segment of the polygon. Then we construct in the similar way the lowest segment UV of polygon M. Let's prove that${\\vec{U}}={\\vec{X}}+{\\vec{P}}$ - if not, let $\\vec{U}=\\vec{x}+\\vec{p}$ . It is clear that x and p are the lowest points of the polygons A and B - otherwise one of them can be moved to a small vector d, which lies in the lower half-plane, so that the point remained within its polygon. In this case U will move the same way to d, which contradicts the fact that U is one of the lowest points of the polygon. Thus, x and p are the lowest points of their polygons. Similarly, x and p are the leftmost points on the lowest segments of their polygons - otherwise we shift x or p to vector d that is directed to the left. It is also a contradiction - the U point stops to be the leftmost lower point. Hence, U = X + P. Similarly, V = Y + Q. Hence, ${\\overrightarrow{U V}}={\\overrightarrow{X Y}}+{\\overrightarrow{P Q}}$. Thus, the sequence of sides M as vectors in the, for instance, counterclockwise order, is nothing other than the union of sides of $A$ and $B$ as vectors in the counterclockwise order, that immediately proves the correctness of the algorithm.",
    "tags": [
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "88",
    "index": "A",
    "title": "Chord",
    "statement": "Vasya studies music.\n\nHe has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note after the H similar and we will identify them with each other. The distance between the notes along the musical scale is measured in tones: between two consecutive notes there's exactly one semitone, that is, 0.5 tone. The distance is taken from the lowest tone to the uppest one, that is, the distance between C and E is 4 semitones and between E and C is 8 semitones\n\nVasya also knows what a chord is. A chord is an unordered set of no less than three notes. However, for now Vasya only works with triads, that is with the chords that consist of exactly three notes. He can already distinguish between two types of triads — major and minor.\n\nLet's define a major triad. Let the triad consist of notes $X$, $Y$ and $Z$. If we can order the notes so as the distance along the musical scale between $X$ and $Y$ equals 4 semitones and the distance between $Y$ and $Z$ is 3 semitones, then the triad is major. The distance between $X$ and $Z$, accordingly, equals 7 semitones.\n\nA minor triad is different in that the distance between $X$ and $Y$ should be 3 semitones and between $Y$ and $Z$ — 4 semitones.\n\nFor example, the triad \"C E G\" is major: between C and E are 4 semitones, and between E and G are 3 semitones. And the triplet \"C# B F\" is minor, because if we order the notes as \"B C# F\", than between B and C# will be 3 semitones, and between C# and F — 4 semitones.\n\nHelp Vasya classify the triad the teacher has given to him.",
    "tutorial": "First we need to understand a simple fact - the notes are actually residues modulo 12. It means the minor chord has the form {x, x +3, x +7} (mod 12), and the major one - {x, x +4, x +7}. It is convenient to read the notes as strings, after that it is better to immediately replace them by a corresponding number from 0 to 11, that is, by their number. To perform the analysis, we needed to analyze consecutively the 6 possible orders in which the notes may follow one another in the chord. For each of the 6 orders we should check whether the chord is major or minor and if so, then immediately print the result. There's no chord that would be major and minor at the same time - this is checked by the consecutive analysis of the six possible comparison systems.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "88",
    "index": "B",
    "title": "Keyboard",
    "statement": "Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has $n$ rows of keys containing $m$ keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the \"Shift\" key on standard keyboards, that is, they make lowercase letters uppercase.\n\nVasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed $x$. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.\n\nVasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest \"Shift\" key is strictly larger than $x$. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.\n\nYou are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.",
    "tutorial": "Here we simply consecutively check for each letter of the alphabet in its two variants, uppercase and lowercase, whether it can be typed with one hand or not. And if we can't type it with one hand, we check whether it can be typed with two hands or can't be typed at all however how many hands one would use :-) To verify let's consider several cases. If the letter is lowercase, then we should simply check whether this letter is present on the keyboard, and if not, we do not type it. If the letter is uppercase, then we must check for each key with the corresponding letter if there is a Shift nearby, simply checking all the key pairs on the keyboard one by one. If there's no such letter or even a single Shift, then we do not type the letter as well. If such pair was found, but the distance between the two keys is too long, then we need another hand to type the letter. Let's sum (for all the text letters) the number of hands needed to type the text and terminate the problem with -1 if some letters just wouldn't be typed. The complexity is $|T| + 52 * (n \\cdot  m)^{2}$, which is quite enough.",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "89",
    "index": "A",
    "title": "Robbery",
    "statement": "It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has $n$ cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from $1$ to $n$ from the left to the right.\n\nUnfortunately, Joe didn't switch the last security system off. On the plus side, he knows the way it works.\n\nEvery minute the security system calculates the total amount of diamonds for each two adjacent cells (for the cells between whose numbers difference equals $1$). As a result of this check we get an $n - 1$ sums. If at least one of the sums differs from the corresponding sum received during the previous check, then the security system is triggered.\n\nJoe can move the diamonds from one cell to another between the security system's checks. He manages to move them no more than $m$ times between two checks. One of the three following operations is regarded as moving a diamond: moving a diamond from any cell to any other one, moving a diamond from any cell to Joe's pocket, moving a diamond from Joe's pocket to any cell. Initially Joe's pocket is empty, and it can carry an unlimited amount of diamonds. It is considered that before all Joe's actions the system performs at least one check.\n\nIn the morning the bank employees will come, which is why Joe has to leave the bank before that moment. Joe has only $k$ minutes left before morning, and on each of these $k$ minutes he can perform no more than $m$ operations. All that remains in Joe's pocket, is considered his loot.\n\nCalculate the largest amount of diamonds Joe can carry with him. Don't forget that the security system shouldn't be triggered (even after Joe leaves the bank) and Joe should leave before morning.",
    "tutorial": "Determine a form of all arrangements of diamonds that set of all sums of pairs adjacent cells is invariably. If you remove from the first cell exactly $c$ diamonds, you should add exactly $c$ diamonds into the second cell, remove $c$ diamonds from the third cell and so on. In other words, all valid arrangements can be produced by adding $c$ diamonds into every even cell and removing $c$ diamonds from every odd cell, where $c$ is some integer. $c$ lies in range from $-m i n\\lbrace a[i],i\\mathrm{~is~even}\\rbrace$ to $min \\{ a[i], i \\text{ is odd} \\}$ because otherwise number of diamonds in some cell will be less than zero. There is no more valid arrangements. Now consider a number of all diamonds in cells as a function of $c$. If $n$ is even, the sum always is constant. So there is impossible of theft diamonds and answer is $0$. For odd $n$ for every $c$ there is $c$ extra diamonds. So, Joe can theft no more than $min \\{ a[i], i \\text{ is odd} \\}$ diamonds. It is easy for undarstanding that for increasing (or decreasing) $c$ by some constant $x$ Joe should do $x(n + 1) / 2$ moves, but he cannot done it by lass count of moves. In one minute Joe can change $c$ no more than on $[m / ((n + 1) / 2)]$. Common number of diamonds thet Joe can theft for all time is $k[m / ((n + 1) / 2)]$, but you should take into account a limits for changing of $c$. At the end common solution is following: If $n$ is even, answer is 0, otherwise answer is $m i n(m i n\\{a[i],i\\;\\mathrm{is\\;odd}\\},k[m/((n+1)/2)])$. Be careful fith overflow of 32bit integers. Here you should use an 64bit integers.",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "89",
    "index": "B",
    "title": "Widget Library",
    "statement": "Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other.\n\nA widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type.\n\nTypes HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets — they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change.\n\nWe shall assume that the widget $a$ is packed in the widget $b$ if there exists a chain of widgets $a = c_{1}, c_{2}, ..., c_{k} = b$, $k ≥ 2$, for which $c_{i}$ is packed directly to $c_{i + 1}$ for any $1 ≤ i < k$. In Vasya's library the situation when the widget $a$ is packed in the widget $a$ (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error.\n\nAlso, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal $0$.\n\nThe picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox — vertically. The parameter spacing sets the distance between adjacent widgets, and border — a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to $0 × 0$, regardless of the options border and spacing.\n\nThe construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data.\n\nFor the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript.",
    "tutorial": "Here you can build some miltigraph in which nodes are widgets and edges are relationship of pack()-method. This graph is acyclic. Next, you should do topological sort of nodes. Sizes of widgets should be calculated in the obtained order. At the last, you should sort all nodes by thier names and output an answer. About implementation. Parsing of instructions is very easy if you swap charachers '.', ',', '(', ')' by spaces. Now you can just split instructions into strings using spaces as separators. Multigraph can be saved into matrix. Cell M[i][j] contains integer number that means number of edges from node i to node j. Topological sort can be done by any stupid method. For example, you can choose $k$ times node that has no outgoing edges to unselected nodes, where $k$ is numder of nodes. Every check can be done in $O(k^{2})$. You should recalculate sizes of widgets using 64-bit integets (a tip was is statement). In a test like 100 Widget w(100,100) HBox box box.pack(w) box.set_border(100) HBox a a.pack(box) a.pack(box) HBox b b.pack(a) b.pack(a) HBox c c.pack(b) c.pack(b) ... width of widgets grows exponentially. In jurys' tests maximum length of a side of widgets was 103079215104000. You can get that length by packing 4 widgets everu time instead of 2 widgets.",
    "tags": [
      "dp",
      "expression parsing",
      "graphs",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "89",
    "index": "C",
    "title": "Chip Play",
    "statement": "Let's consider the following game. We have a rectangular field $n × m$ in size. Some squares of the field contain chips.\n\nEach chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right.\n\nThe player may choose a chip and make a move with it.\n\nThe move is the following sequence of actions. The chosen chip is marked as the current one. After that the player checks whether there are more chips in the same row (or in the same column) with the current one that are pointed by the arrow on the current chip. If there is at least one chip then the closest of them is marked as the new current chip and the former current chip is removed from the field. After that the check is repeated. This process can be repeated several times. If a new chip is not found, then the current chip is removed from the field and the player's move ends.\n\nBy the end of a move the player receives several points equal to the number of the deleted chips.\n\nBy the given initial chip arrangement determine the maximum number of points that a player can receive during one move. Also determine the number of such moves.",
    "tutorial": "This problem can be solved by simulation. You can just iterate over all chips and for every of them calculate number of points. But srupid simulate can give $O(k^{3})$ time solution, where $k$ is total number of chips. It doesn't fit into time limits. For example, try test like 1 5000 RRRR...[2500 times]LLLL...[2500 times] You can simulate process in $O(k^{2}\\log k)$ time by using some data structures like std::set, but it doesn't fit into limits too. Similating in $O(k^{2})$ time is given by following data structure. For every chip you can save links to chips that is placed up, doun, left and right from the considered chip. Net of links can be built in O($nm$). Now, when you simulate process, you can remove chips this way: Chip->L->R = Chip->R Chip->R->L = Chip->L Chip->U->D = Chip->D Chip->D->U = Chip->U So, jump from some chip to the next chip in a move can be done in $O(1)$. Now you can simulate every move in $O(k)$. Remove operation is reversible because every removed chip stores links to all of its neighbours. Therefore you can save links to all removed chips in current move and after restore net of links using following operetions for all removed chips in reversed order Chip->L->R = Chip Chip->R->L = Chip Chip->U->D = Chip Chip->D->U = Chip Also you can just build net of links anew for every move.",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "89",
    "index": "D",
    "title": "Space mines",
    "statement": "Once upon a time in the galaxy of far, far away...\n\nDarth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.\n\nWhen the rebels learnt that the Death Star was coming, they decided to use their new secret weapon — space mines. Let's describe a space mine's build.\n\nEach space mine is shaped like a ball (we'll call it the mine body) of a certain radius $r$ with the center in the point $O$. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point $P$, such that $r<|O P|\\leq{\\frac{3}{2}}r$ (transporting long-spiked mines is problematic), where $|OP|$ is the length of the segment connecting $O$ and $P$. It is convenient to describe the point $P$ by a vector $p$ such that $P = O + p$.\n\nThe Death Star is shaped like a ball with the radius of $R$ ($R$ exceeds any mine's radius). It moves at a constant speed along the $v$ vector at the speed equal to $|v|$. At the moment the rebels noticed the Star of Death, it was located in the point $A$.\n\nThe rebels located $n$ space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines.\n\nHelp the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed).",
    "tutorial": "Initially lets pump all mines on radius of Death Star and squeeze Death Star into point. Now you should determine an intersection of a ray with obtained figures. Mine's body with radius $r$ is pumped into ball with radius $r + R$. Every mine's spike is pumped into union of two balls with radius $R$ and cylinder. One of these balls lies inside of pumped mine's body, therefore you can don't consider it. Let length of spike is $r_{0}$. Then cylinder will have heigth $r_{0}$ and radius $R$. A distance between center of one base of the cylinder and edge of another one equals $\\sqrt{r_{0}^{2}+R^{2}}$. Following unequation proves that this distance always less than radius of pumped mine's body and cylinder lies inside of the pumped mine's body: $r_{0}^{2}+R^{2}\\le\\textstyle{\\frac{9}{4}}r^{2}+R^{2}<r^{2}+{\\textstyle{\\frac{5}{4}}}r R+R^{2}<r^{2}+2r R+R^{2}=(r+R)^{2}.$ So, you can don't consider the cylinders too. For every spike you should store only ball of radius $R$ with center in a peak of the spike. Now we have set of balls, we are needed to determine a time in that some point collides with every of those balls. Lets write an equation: $|A + vt - O| = R$, where $A$ is start position of point, $v$ is vector of its velocity, $O$ is center of ball, $R$ is its radius. Lets rewrite equation in scalar variables: $(A_{x} + v_{x}t - O_{x})^{2} + (A_{y} + v_{y}t - O_{y})^{2} + (A_{z} + v_{z}t - O_{z})^{2} = R^{2}.$ When you expand brackets, you receive some quadratic equation from variable $t$: $At^{2} + Bt + C = 0$. You should solve it and choose minimal root (minimal root is time of the first collision of point with the ball, maximal one is time of the second collision). Check than root more than 0. Now you should determine all times and choose minimum of them. If there are no collisions, answer is -1. All checking should be done in integer 64bit numbers for absolutely precision.",
    "tags": [
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "89",
    "index": "E",
    "title": "Fire and Ice",
    "statement": "The Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment $n$ in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom.\n\nThe $n$-long segment is located at a distance equal exactly to $1$ from the castle walls. It can be imaginarily divided into unit segments. On some of the unit segments fire demons are located — no more than one demon per position. Each demon is characterised by his strength - by some positive integer. We can regard the fire demons being idle.\n\nInitially Solomon is positioned on the fortress wall. He can perform the following actions several times in a row:\n\n- \"L\" — Solomon shifts one unit to the left. This movement cannot be performed on the castle wall.\n- \"R\" — Solomon shifts one unit to the left. This movement cannot be performed if there's no ice block to the right.\n- \"A\" — If there's nothing to the right of Solomon, then Solomon creates an ice block that immediately freezes to the block that Solomon is currently standing on. If there already is an ice block, then Solomon destroys it. At that the ice blocks to the right of the destroyed one can remain but they are left unsupported. Those ice blocks fall down.\n\nSolomon spends exactly a second on each of these actions.\n\nAs the result of Solomon's actions, ice blocks' segments fall down. When an ice block falls on a fire demon, the block evaporates and the demon's strength is reduced by $1$. When the demons' strength is equal to $0$, the fire demon vanishes. The picture below shows how it happens. The ice block that falls on the position with no demon, breaks into lots of tiny pieces and vanishes without hurting anybody.\n\nHelp Solomon destroy all the Fire Lord's army in minimum time.",
    "tutorial": "Solomon can just create some segments of ice cubes and cut its. Consider a segment with rightmost begin. You can assume that it ends in position of the last demon (you always can cut end of a segment that ends on last demon and add it to current segment). For cutting the last segment you should build \"ice bridge\" to it. When you are building this bridge, you should create and cut all others segments. Now iterate over all start positions of the last segment. For every of them you should decrease powers of demons that is covered by this segment and calculate minimal number of moves for destroy all demons (do not forgen about the last segment!). You can see that for every fallen ice cube you need exactly 3 operations --- go left, create cube, go right. For cutting a segment you need exactly 2 operations --- create cube and destroy one. Therefore all demons should be covered by minimal number of segments that no cube falls on an empty position. It can be done by greedy algorithm. Total number of operations for every start position of the last segment can be calculated in $O(n)$. Total number of checks is $O(n)$, so we have an $O(n^{2}) solution$. After all, answer can be built very easy.",
    "tags": [
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "90",
    "index": "A",
    "title": "Cableway",
    "statement": "A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.\n\nA cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.\n\nThe number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly $30$ minutes for a cablecar to get to the top.\n\nAll students are divided into three groups: $r$ of them like to ascend only in the red cablecars, $g$ of them prefer only the green ones and $b$ of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,\n\nThe first cablecar to arrive (at the moment of time $0$) is painted red. Determine the least time it will take all students to ascend to the mountain top.",
    "tutorial": "In this problem you can simulate the process. You can consider all minutes and in dependence by a color of a current cablecar decrease size of corresponding group of students $G$ by $min(|G|, 2)$, where $|G|$ is size of the group. After that you should determine the first minute $t$ in that all three groups of students will be empty. So $t + 30$ is an answer. This solution works in $O(r + g + b)$. Also there is $O(1)$ solution. It is following formula: $ans = max(3[(R + 1) / 2] + 27, 3[(G + 1) / 2] + 28, 3[(B + 1) / 2] + 29)$ where $[x]$ is rounding down.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "90",
    "index": "B",
    "title": "African Crossword",
    "statement": "An African crossword is a rectangular table $n × m$ in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.\n\nTo solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.\n\nWhen all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.\n\nYou are suggested to solve an African crossword and print the word encrypted there.",
    "tutorial": "It this problem you should write exactly that is written in statement. For every letter you should see a row and a column of the letter. If equal letter was found, current letter sould not be output. You can combine scanning rows and columns and output an answer, for example, this way: FOR(a,1,n) FOR(b,1,m) { bool should_out=true; FOR(c,1,n) if (c!=a) if (T[a][b]==T[c][b]) should_out=false; FOR(c,1,m) if (c!=b) if (T[a][b]==T[a][c]) should_out=false; if (should_out) printf(\"%c\", T[a][b]); } This solution works in $O(mn(n + m))$. Also here an $O(nm)$-solution exitsts. In every row and column you can calculate a number of every letter of an alphabet. After that check for output can be done in $O(1)$. You just should check that numbers of entries of considered letter into corresponding row and column equal exactly 1.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "91",
    "index": "A",
    "title": "Newspaper Headline",
    "statement": "A newspaper is published in Walrusland. Its heading is $s_{1}$, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word $s_{2}$. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.\n\nFor example, the heading is \"abc\". If we take two such headings and glue them one to the other one, we get \"abcabc\". If we erase the letters on positions $1$ and $5$, we get a word \"bcac\".\n\nWhich least number of newspaper headings $s_{1}$ will Fangy need to glue them, erase several letters and get word $s_{2}$?",
    "tutorial": "In this problem letters from $s1$ should be taken greedily: take the left letter from the right of the last used letter, if there is no necessary letter from the right of the right used letter the the search should be started from the beginning of string $s1$ and the answer should be increased by one. But the brute solution get $TL$ and have complexity $O(Ans * |s1|)$. This solution can be optimized using the following way. For every position in $s1$ let's precalculate positions of the closest letters from the right of it from the alphabet. It can be done by moving from the right to the left ins $s1$ and remembering the last position of every type of symbol. This solution have complexity $O(|s1| * K + |s2|)$, where $K$ is a size of alphabet.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "91",
    "index": "B",
    "title": "Queue",
    "statement": "There are $n$ walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the $1$-st walrus stands at the end of the queue and the $n$-th walrus stands at the beginning of the queue. The $i$-th walrus has the age equal to $a_{i}$.\n\nThe $i$-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such $j$ ($i < j$), that $a_{i} > a_{j}$. The \\underline{displeasure} of the $i$-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the $i$-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.\n\nThe airport manager asked you to count for each of $n$ walruses in the queue his displeasure.",
    "tutorial": "There were a lot of different solutions but I will tell you the author solution. Let's precalculate $[i, n]$. It can be done with the time equal to $O(n)$ moving from the right to the left. Define $[i, n]$ as $Min_{i}$. Obviously, that $Min_{i} < = Min_{i + 1}$. Now for every position $i$ using binary search let's find j ($j > i$), that $Min_{j} < a_{i}$ and $Min_{j + 1} > = a{i}$. For such $j$ there are no walruses who have age younger then walrus $i$. It's obviously because $Min_{j}$ is the minimum on $[j, n]$. If there is no such $j$ then print $- 1$ else print $j - i - 1$.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 1500
  },
  {
    "contest_id": "91",
    "index": "C",
    "title": "Ski Base",
    "statement": "A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains $n$ ski junctions, numbered from $1$ to $n$. Initially the junctions aren't connected in any way.\n\nIn the constructing process $m$ bidirectional ski roads will be built. The roads are built one after another: first the road number $1$ will be built, then the road number $2$, and so on. The $i$-th road connects the junctions with numbers $a_{i}$ and $b_{i}$.\n\n\\underline{Track} is the route with the following properties:\n\n- The route is closed, that is, it begins and ends in one and the same junction.\n- The route contains at least one road.\n- The route doesn't go on one road more than once, however it can visit any junction any number of times.\n\nLet's consider the \\underline{ski base} as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected.\n\nTwo ski bases are considered different if they consist of different road sets.\n\nAfter building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem.",
    "tutorial": "We will count the number of ski bases including the base consisted of empty subset of edges (before printing just subtract one). In the beginning the number of bases is equal to $1$. If we connect vertexes in the same connected components then the result should be multiplied by $2$ else do nothing. You should use DJS data structure to know information about connected components where vertexes are and to unite them. Why is it correct? To prove it we will use the matrix of incidence $I$, rows in it will be edges and columns will be vertexes. Let's define $xor$ of two rows. $Xor$ of two rows $a$ and $b$ will be row $c$ such that $c_{i} = a_{i}$ xor $b_{i}$. Notice if $xor$ of some subset of rows is equal to a zero row then this subset form the ski base. It's correct because, the degree of contiguity of every vertex is even, so we can form an Euler cycle in every connected component. The answer is $2^{}(m - rank(I))$. Why it is correct? Let's write the number of edge from the right of each row which suit this row. While finding the matrix rank using gauss method with $xor$ operation, we will $xor$ the subsets from the right of the strings. In the end the subsets of edges written from the right of the zero rows will form the basis of the linear space. Thats why we can take any subset of vectors from basis and make up a new ski base. The number of these subsets is equal to $2^{k}$ = $2^{}(m - rank(I))$, where k is the number of zero rows. The last thing we should notice that the adding row is liner depended if and only if there is exist a way between the vertexes $a$ and $b$ ($a$ and $b$ are the ends of the adding edge).",
    "tags": [
      "combinatorics",
      "dsu",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "91",
    "index": "D",
    "title": "Grocer's Problem",
    "statement": "Yesterday was a fair in a supermarket's grocery section. There were $n$ jars with spices on the fair. Before the event the jars were numbered from $1$ to $n$ from the left to the right. After the event the jars were moved and the grocer had to sort them by the increasing of the numbers.\n\nThe grocer has a special machine at his disposal. The machine can take any $5$ or less jars and rearrange them in the way the grocer wants. Note that the jars \\textbf{do not have to} stand consecutively. For example, from the permutation $2$, $6$, $5$, $4$, $3$, $1$ one can get permutation $1$, $2$, $3$, $4$, $5$, $6$, if pick the jars on the positions $1$, $2$, $3$, $5$ and $6$.\n\nWhich minimum number of such operations is needed to arrange all the jars in the order of their numbers' increasing?",
    "tutorial": "Let's find all cycles in substitution: $1$ $2$ $3$ $4$ $5$ ... $a_{1}$ $a_{2}$ $a_{3}$ $a_{4}$ $a_{5}$ ... For example, in sequence $a = {2, 1, 4, 5, 3}$ exist two cycles with length $2$ and $3$ on positions $1$ $2$ and $3$ $4$ $5$ respectively. If the length of the cycle is more than $5$, then we can take $5$ consecutive elements and make a new order in such way that $4$ elements will take their places where they should be in sorted array. In common: if we take $p$ elements in a cycle of length more than $p$, the we can make a new order in such way that $p - 1$ elements will take their places where they should be in sorted array. If the cycle length is $p$ we can sort all the elements taking $p$ elements from it. Next in the analysis I will define length of a cycle as a real length of a cycle - 1 (now I can say that if we take $p$ consecutive elements then $p - 1$ will take the right places). We also can take some elements in one and some elements in other cycles. We can make up division numbers from $2$ to $5$ into a sum to see how we can use them: $5$, $4$, $3$, $2$, $2 + 3$, $2 + 2$. We can take, for example, three elements in one cycle and two in other, their sizes were reduced by 2 and 1. The task now is to get all cycle lengths equal to zero. Let's to suppose that an optimal solution have four operations which decrease the same cycle length by one. We will work with operations of $5$ elements and which are not process the same cycle except one, because it's more stronger condition. Such operation can be shown as a table where rows are operations, columns are cycles and cells of table are the values on which cycles will be reduced. a b c d e 1 2 1 2 1 2 1 2 Replace operations this way: a b c d e 4 2 1 1 2 2 The number of operations was not increased, but now we can see that if there is an optimal solution where one cycle reduced by one four times then there is an optimal solution where no cycles reduced by one four times. Look at some other replacements: a b c 2 1 2 1 Replace by: a b c 4 1 1 and a b c d 2 1 1 2 1 2 Replace by: a b c d 4 1 2 2 Now we can see that there is an optimal solution where no operation reducing one cycle in ways:$1 + 1 + 1 + 1$, $2 + 2$, $1 + 1 + 2$. That's why we can reduce any cycle by $4$ while it's size is $> = 4$. Let's use zhe same method to prove that cycles of size $3$ reduced by $3$ in some optimal solution. a b c 2 1 1 2 Replace by: a b c d 3 1 2 and a b c d 1 2 1 2 1 2 Replace by: a b c d 3 2 1 1 2 Now we have cycles only with size $1$ or $2$. Let's brute the number of operations to process like ${2, 2} - > {0, 1}$ (one cycle will be reduced from $2$ to $1$ and the other will be reduced from $2$ to $0$). Fix some such number and make these operations. Now we should process the maximum available operations like ${2, 1} - > {0, 0}$. After it we will have no cycles or some cycles of size $1$ or some cycles of size $2$. In the second case we should do the maximum of available operations like ${1, 1} - > {0, 0}$ and if one cycle lasts we should do ${1} - > {0}$. In the third case we should to do operations like ${2} - > {0}$. Using such way we can find the optimal set of operations. We shouldn't divide cycle into a parts because it makes the number of operation bigger or the same. Stress test shows the uniting cycles will not improve the answer.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "91",
    "index": "E",
    "title": "Igloo Skyscraper",
    "statement": "Today the North Pole hosts an Olympiad in a sport called... toy igloo skyscrapers' building!\n\nThere are $n$ walruses taking part in the contest. Each walrus is given a unique number from $1$ to $n$. After start each walrus begins to build his own igloo skyscraper. Initially, at the moment of time equal to $0$, the height of the skyscraper $i$-th walrus is equal to $a_{i}$. Each minute the $i$-th walrus finishes building $b_{i}$ floors.\n\nThe journalists that are reporting from the spot where the Olympiad is taking place, make $q$ queries to the organizers. Each query is characterized by a group of three numbers $l_{i}$, $r_{i}$, $t_{i}$. The organizers respond to each query with a number $x$, such that:\n\n1. Number $x$ lies on the interval from $l_{i}$ to $r_{i}$ inclusive ($l_{i} ≤ x ≤ r_{i}$).\n\n2. The skyscraper of the walrus number $x$ possesses the maximum height among the skyscrapers of all walruses from the interval $[l_{i}, r_{i}]$ at the moment of time $t_{i}$.\n\nFor each journalists' query print the number of the walrus $x$ that meets the above-given criteria. If there are several possible answers, print any of them.",
    "tutorial": "We are given the array where the value in each cell is described by the formula depends on T $val_{i} = a_{i} + b_{i} * T$ (in geometry mean it is a line equation). Lt's divide the array in blocks of size $d$ ~ $sqrt(n)$: $[0;d)$, $[d, d * 2)$, $[d * 2, d * 3)$, ..., $[d * k, n)$. Now let's precalculate for each block time moments when the leader of the block changes. So as we have line equation we can perform an intersection of half planes. On $Oy$ axis values of the cells are marked and the time moments marked on $Ox$ axis. we are interested on $x$ coordinate of points of intersections and number of leader after time $x$. So now we know time moment of leader changing for every block. For each block it takes $O(d * log(d))$ time. The number of blocks ($k$) is about $n / d$ ~ $n / sqrt(n)$ ~ $sqrt(n)$ so all the process will take $O(n * log(n))$ time. Let's sort all queries by increasing $t_{i}$. Now we should to perform queries one by one. Brute all blocks which lay into the query interval. For each such block we will keep up the leader for current time. For this let's process all the time moment of leader changing until $t_{i}$ inclusively and relax leader on the current block. The time moments which ware processed should be erased, they are not keep any useful information ,because all queries sorted by $t_{i}$. Let's process all cells which were not covered by the processed blocks but covered by the query and relax the leader for the query. The number of erasing time moments of leader changing is not mere then n and every query need $O(sqrt(n))$ time to calculate answer without erasing time moments. So the complexity of algorithm is $O(n * log(n) + m * sqrt(n))$. Interval tree also can be used to solve this problem. Such solution has complexity $O(n * log(n))$, but $O(n * log(n))$ memory.",
    "tags": [
      "data structures",
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "92",
    "index": "A",
    "title": "Chips",
    "statement": "There are $n$ walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number $2$ sits to the left of the walrus number $1$, the walrus number $3$ sits to the left of the walrus number $2$, ..., the walrus number $1$ sits to the left of the walrus number $n$.\n\nThe presenter has $m$ chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number $1$ and moving clockwise. The walrus number $i$ gets $i$ chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given $n$ and $m$ how many chips the presenter will get in the end.",
    "tutorial": "In these problems you should only realize what was written is the statement.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "92",
    "index": "B",
    "title": "Binary Number",
    "statement": "Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.\n\nFangy takes some positive integer $x$ and wants to get a number one from it. While $x$ is not equal to $1$, Fangy repeats the following action: if $x$ is odd, then he adds $1$ to it, otherwise he divides $x$ by $2$. Fangy knows that for any positive integer number the process ends in finite time.\n\nHow many actions should Fangy perform to get a number one from number $x$?",
    "tutorial": "In these problems you should only realize what was written is the statement. In problem B wasn't recommended to use BigInteger in Java because of slow speed.",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "93",
    "index": "A",
    "title": "Frames",
    "statement": "Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.\n\nThis time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.\n\nIgor K. use Pindows XR operation system which represents files and folders by small icons. At that, $m$ icons can fit in a horizontal row in any window.\n\nIgor K.'s computer contains $n$ folders in the D: disk's root catalog. The folders are numbered from $1$ to $n$ in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from $a$ to $b$ inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from $a$ to $b$ and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.",
    "tutorial": "The problem is easy, but there were many tricky cases - and contestants show it successful :) I added almost all these cases to the pretests because I didn't want to arrange Beta Round 60. So let's solve the problem. At first notice that the answer is not greater than 3 because we always can do three selections (maybe, some of them are empty): with first selection we select end of the first row, with second one - begin of the last row, and with last one - all remaining folders (they form the rectangle). The best way is to find all cases with answer 1 and 2. Try to do it. If the answer is 1, we can select all folders from $a$ to $b$ with one selection. There must be nothing hard to detect these cases: first and last folders are in the same row (21 5 7 9); first folder is in the first column, and the last folder - in the last column (21 5 1 15), case $m = 1$ is included here; first folder is in the first column, and the last folder is $n$ (21 5 6 21). Case when we must select all folders is included here. I was very surprised when I saw that many contestants forgot about it. And these are the cases with answer 2: first and last folders are in the adjacent rows (21 5 8 14); first folder is in the first column (21 5 6 13); last folder is in the last column (21 5 4 15); last folder is $n$ (21 5 4 21); and another tricky case: if the column where first folder is located is just at right from the column where the last column is located (21 5 3 12). If no one of these conditions is true, answer is 3.",
    "tags": [
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "93",
    "index": "B",
    "title": "End of Exams",
    "statement": "Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!\n\nDespite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the $m$ friends found $n$ different kinds of milk on the menu, that's why they ordered $n$ bottles — one bottle of each kind. We know that the volume of milk in each bottle equals $w$.\n\nWhen the bottles were brought in, they decided to pour all the milk evenly among the $m$ cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem — and what is actually the way to do it?\n\nHelp them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!\n\nNote that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.",
    "tutorial": "Greedy algorithm solves this problem. We should consecutively try to pour milk from each bottle into each available cup and in maximal possible amount. Also we always need to know, how much milk is in each bottle and each cup, for each cup - bottles from which we have poured milk, and for each bottle - cups into which we have poured milk. Writing it is not hard. But where is one special moment - if we compare real numbers, we must use EPS, or we can get WA on test 12 (50 1000 49). Some programs write NO on this test while answer is YES, because of wrong comparing of real numbers. It must be said that answer can be calculated in integers: just set the volume of milk in each bottle $mn$. And only when we will print the answer, we divide each volume by $mn$ and multiply by $w$. All three jury solutions didn't think up this :)",
    "tags": [
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "93",
    "index": "C",
    "title": "Azembler",
    "statement": "After the Search Ultimate program that searched for strings in a text failed, Igor K. got to think: \"Why on Earth does my program work so slowly?\" As he double-checked his code, he said: \"My code contains no errors, yet I know how we will improve Search Ultimate!\" and took a large book from the shelves. The book read \"Azembler. Principally New Approach\".\n\nHaving carefully thumbed through the book, Igor K. realised that, as it turns out, you can multiply the numbers dozens of times faster. \"Search Ultimate will be faster than it has ever been!\" — the fellow shouted happily and set to work.\n\nLet us now clarify what Igor's idea was. The thing is that the code that was generated by a compiler was far from perfect. Standard multiplying does work slower than with the trick the book mentioned.\n\nThe Azembler language operates with 26 registers (eax, ebx, ..., ezx) and two commands:\n\n- [$x$] — returns the value located in the address $x$. For example, [eax] returns the value that was located in the address, equal to the value in the register eax.\n- lea $x$, $y$ — assigns to the register $x$, indicated as the first operand, the second operand's address. Thus, for example, the \"lea ebx, [eax]\" command will write in the ebx register the content of the eax register: first the [eax] operation will be fulfilled, the result of it will be some value that lies in the address written in eax. But we do not need the value — the next operation will be lea, that will take the [eax] address, i.e., the value in the eax register, and will write it in ebx.\n\nOn the first thought the second operation seems meaningless, but as it turns out, it is acceptable to write the operation as\n\nlea ecx, [eax + ebx],\n\nlea ecx, [k*eax]\n\nor even\n\nlea ecx, [ebx + k*eax],\n\nwhere k = 1, 2, 4 or 8.\n\nAs a result, the register ecx will be equal to the numbers eax + ebx, k*eax and ebx + k*eax correspondingly. However, such operation is fulfilled many times, dozens of times faster that the usual multiplying of numbers. And using several such operations, one can very quickly multiply some number by some other one. Of course, instead of eax, ebx and ecx you are allowed to use any registers.\n\nFor example, let the eax register contain some number that we should multiply by 41. It takes us 2 lines:\n\nlea ebx, [eax + 4*eax] // now ebx = 5*eax\n\nlea eax, [eax + 8*ebx] // now eax = eax + 8*ebx = 41*eax\n\nIgor K. got interested in the following question: what is the minimum number of lea operations needed to multiply by the given number $n$ and how to do it? Your task is to help him.\n\nConsider that at the initial moment of time eax contains a number that Igor K. was about to multiply by $n$, and the registers from ebx to ezx contain number 0. At the final moment of time the result can be located in any register.",
    "tutorial": "I don't know why so few coders have solved it. Small limitations for $n$ and big time limit - 5 seconds - hint that it's backtracking. Also, no need to be a soothsayer to understand that maximal answer is about 5. Solving it is clear. You should keep all current registers at the vector and call some function that goes over all current registers and calculate new values, then calls itself recursively. In that process we can also save the program itself. To avoid TLE you should not make recursive calls if the deep of recursion is larger than current answer, should not go to the states where you get a number larger than $n$ or less than current biggest number. And if you reach exactly $n$, you should update answer and copy the program to the safe place. There are some hacks to speed up this approach: for example, iterate over numbers in descending order (it works faster), but 5 seconds is such TLE that you can solve it any way. Or you can launch backtracking for the specific answer (increasing it) while the program won't be found (I don't know how this method is named in English). Also, some contestants have solved it using BFS.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "93",
    "index": "D",
    "title": "Flags",
    "statement": "When Igor K. was a freshman, his professor strictly urged him, as well as all other freshmen, to solve programming Olympiads. One day a problem called \"Flags\" from a website called Timmy's Online Judge caught his attention. In the problem one had to find the number of three-colored flags that would satisfy the condition... actually, it doesn't matter. Igor K. quickly found the formula and got the so passionately desired Accepted.\n\nHowever, the professor wasn't very much impressed. He decided that the problem represented on Timmy's Online Judge was very dull and simple: it only had three possible colors of flag stripes and only two limitations. He suggested a complicated task to Igor K. and the fellow failed to solve it. Of course, we won't tell anybody that the professor couldn't solve it as well.\n\nAnd how about you? Can you solve the problem?\n\nThe flags consist of one or several parallel stripes of similar width. The stripes can be one of the following colors: white, black, red or yellow. You should find the number of different flags with the number of stripes from $L$ to $R$, if:\n\n- a flag cannot have adjacent stripes of one color;\n- a flag cannot have adjacent white and yellow stripes;\n- a flag cannot have adjacent red and black stripes;\n- a flag cannot have the combination of black, white and red stripes following one after another in this or reverse order;\n- symmetrical flags (as, for example, a WB and a BW flag, where W and B stand for the white and black colors) are considered the same.",
    "tutorial": "I think my solution is not optimal, it's too long. Many solutions submitted during the contest are shorter. But I tell you about my solution. At first I solve the problem for the number of stripes equals $N$ (or $L = R$). Let $f\\left(N\\right)$ is the number of flags with exactly $N$ stripes where symmetrical flags are not identical. Try to get the answer using this designation. At first sight it seems that answer is $\\frac{f(N)}{2}$. But it's not true for the palindromes. For example, for non-palindromes WBWB and BWBW we should count only one of them, but for the palindromes, such as WBW, it leads to mistake, because each palindrome is symmetrical to itself. So for the flags with even number of stripes formula $a n s\\left(N\\right)=\\frac{f(N)}{2}$ is correct, because there are not palindromes among them. And if $N$ is odd, the correct formula is $a n s\\left(N\\right)=\\frac{f(N)+p(N)}{2}$, where $p\\left(N\\right)$ is the number of palindromes with $N$ stripes. Each palindrome is definited by its first $\\textstyle{\\frac{N+1}{2}}$ stripes, and we can write that $p\\left(N\\right)=f\\left(\\frac{N+1}{2}\\right)$. Now we can give an answer if we know how to calculate number of flags where symmetrical flags are not equal. Notice that if we know two last stripes of the flag, we can definitely say if we can add another stripe to its end. Let's use dynamic programming. As a state we can take a vector $x(N)$ with a length 8 where each its component keeps a number of flags with $N$ stripes and definite two last colors (exactly 8 options). And $f\\left(N\\right)=\\sum_{i=1}^{8}x_{i}$ is total number of flags with $N$ stripes. As start state we can take vector $x\\left(2\\right)$ which consists of ones (because there are 8 flags with a length 2, one flag for one possible combination of two colors). And how to calculate $x(N)$? It turns out that there is some matrix $A$ that $x\\left(N\\right)=A x\\left(N-1\\right)$. Its elements can be found even using pen and paper: for example, let's we have a combination of two last stripes WB. Then it's possible to add white or yellow stripe to the end, and the last stripes will be BW and BY correspondingly. It means that we can write $1$ to the matrix where the row are BW or BY and the column is WB. We're about the finish. It's obvious that $x\\left(N\\right)=A^{N-2}x\\left(2\\right)$. Power of matrix can be calculated with a logarithmic time - that's because our problem is solved. And don't forget if $N = 1$ then answer is $4$ and there's no need to do these calculations. But it was only problem where $L = R$. Let's find a solution for the segment $[L, R]$. I know two ways to do it. First way is to add a new component to the vector and new row and column to the matrix. This new component should keep the total number on the segment $[2,R]$ (if $L = 1$, we can write \"if\" somewhere at the beginning of the program). And the matrix $A$ should be changed a bit: try to do it by yourself. I like the second way. As we did it earlier, we will find a number of flags where symmetrical ones are different, but on the segment $[L, R]$. It is equal to $x\\left(L,R\\right)=A^{L-2}\\left(E+A+\\cdot\\cdot\\cdot\\cdot+A^{R-L}\\right)x\\left(2\\right)$. Let's learn how to calculate the sum $E + A + ... + A^{N}$ quickly. Let $b$ is such maximal power of $2$ that $2b - 1  \\le  N$. We can write $E+A+\\cdot\\cdot\\cdot+A^{N}=E+A+\\cdot\\cdot\\cdot+A^{2b-1}+A^{2b}\\left(E+A+\\cdot\\cdot\\cdot+A^{N-2b}\\right)$. And apply some math magic to the first part of the previous formula: $E+A+\\cdot\\cdot\\cdot+A^{2b-1}=\\left(E+A\\right)\\left(E+A^{2}\\right)\\left(E+A^{4}\\right)\\cdot\\cdot\\cdot\\left(E+A^{b}\\right)$. And the expression in the brackets at the second part of that formula is... I think you've already understood it :) We forgot about the palindromes, but it's very easy to calculate their number. Let's suppose that $L$ and $R$ are odd (if they are even, we can add one to $L$ and substract one from $R$). Then $p\\left(L,R\\right)=f\\left({\\frac{L+1}{2}},{\\frac{R+1}{2}}\\right)$. That's all. Don't forget to apply \"mod\" operation after each operation and examine border cases carefully.",
    "tags": [
      "dp",
      "math",
      "matrices"
    ],
    "rating": 2500
  },
  {
    "contest_id": "93",
    "index": "E",
    "title": "Lostborn",
    "statement": "Igor K. very much likes a multiplayer role playing game WineAge II. Who knows, perhaps, that might be the reason for his poor performance at the university. As any person who plays the game, he is interested in equipping his hero with as good weapon and outfit as possible.\n\nOne day, as he was reading the game's forum yet again, he discovered a very interesting fact. As it turns out, each weapon in the game is characterised with $k$ different numbers: $a_{1}, ..., a_{k}$. They are called hit indicators and according to the game developers' plan they are pairwise coprime.\n\nThe damage that is inflicted during a hit depends not only on the weapon's characteristics, but also on the hero's strength parameter. Thus, if the hero's strength equals $n$, than the inflicted damage will be calculated as the number of numbers on the segment $[1,n]$, that aren't divisible by any hit indicator $a_{i}$.\n\nRecently, having fulfilled another quest, Igor K. found a new Lostborn sword. He wants to know how much damage he will inflict upon his enemies if he uses it.",
    "tutorial": "This problem can be solved using inclusion-exclusion principle. If $f_{a_{1}a_{2}...a_{k}}\\left(n\\right)$ is the answer, then the following formula works: $f_{a_{1}a_{2}...a_{k}}\\left(n\\right)=f_{a_{2}a_{3}...a_{k}}\\left(n\\right)-f_{a_{2}a_{3}...a_{k}}\\left(\\left|{\\frac{n}{a_{1}}}\\right|\\right)$. But if you write only this recursive function, you get TLE. Many contestants got TLE and were hacked because they didn't run maximal test on their computers. And the others who sensed that something was wrong memorized the answers for small $n$ and all $a_{i}$.",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "94",
    "index": "A",
    "title": "Restoring Password",
    "statement": "Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain \"some real funny stuff about swine influenza\". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: \"invalid login/password\".\n\nIgor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to \"H1N1\" and \"Infected\" correspondingly, and the \"Additional Information\" field contained a strange-looking binary code $80$ characters in length, consisting of zeroes and ones. \"I've been hacked\" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.\n\nSoon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of $10$ characters stood for one decimal digit. Accordingly, the original password consisted of $8$ decimal digits.\n\nHelp Igor K. restore his ISQ account by the encrypted password and encryption specification.",
    "tutorial": "Password was very easy to restore. You should just iterate over groups of 10 characters in the first string and over all codes. Then, if some number's code is equal to the group - print that number.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "94",
    "index": "B",
    "title": "Friends",
    "statement": "One day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something.\n\nThe following statement caught his attention: \"Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people\"\n\nIgor just couldn't get why the required minimum is 6 people. \"Well, that's the same for five people, too!\" — he kept on repeating in his mind. — \"Let's take, say, Max, Ilya, Vova — here, they all know each other! And now let's add Dima and Oleg to Vova — none of them is acquainted with each other! Now, that math is just rubbish!\"\n\nIgor K. took 5 friends of his and wrote down who of them is friends with whom. Now he wants to check whether it is true for the five people that among them there are either three pairwise acquainted or three pairwise not acquainted people.",
    "tutorial": "Let's construct the graph where vertices correspond to the people and edges correspond to the relationships. Then paint each edge in this way: edge will be red if the men connected by it are friends and black otherwise. Now let's think what is \"three pairwise acquainted people\" and \"three pairwise unacquainted people\". We see that they are cycles of only red and only black vertices correspondingly, and the length of these cycles is 3. Now we know the solution: write 3 \"for\" cycles, one cycle for one vertex, and check if the edges between these vertices are only red or only black. Another way to solve it is to notice the answer is FAIL if and only if graph has exactly 5 edges and they all together form a cycle with a length 5. It's very funny solution, I think.",
    "tags": [
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "95",
    "index": "A",
    "title": "Hockey",
    "statement": "Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name $w$ and the collection of forbidden substrings $s_{1}, s_{2}, ..., s_{n}$. All those strings consist of uppercase and lowercase Latin letters. String $w$ has the length of $|w|$, its characters are numbered from $1$ to $|w|$.\n\nFirst Petya should find all the occurrences of forbidden substrings in the $w$ string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings \"aBC\" and \"ABc\" are considered equal.\n\nAfter that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position $i$ should be replaced by any other one if for position $i$ in string $w$ there exist pair of indices $l, r$ ($1 ≤ l ≤ i ≤ r ≤ |w|$) such that substring $w[l ... r]$ is contained in the collection $s_{1}, s_{2}, ..., s_{n}$, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.\n\nLetter $letter$ (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the $letter$ occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.\n\nNote that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.",
    "tutorial": "Let B[i] = true, if character in position i is in some substring of W which is in dictionary. For each B[i] = true, do next:  \\cdot  If S[i] = letter and letter = 'a', then S[i] = 'b',  \\cdot  If S[i] = letter and letter != 'a' then S[i] = 'a';  \\cdot  If S[i] != letter, then S[i] = letter.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "95",
    "index": "B",
    "title": "Lucky Numbers",
    "statement": "Petya loves lucky numbers. Everybody knows that positive integers are \\underline{lucky} if their decimal representation doesn't contain digits other than $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not.\n\nLucky number is \\underline{super lucky} if it's decimal representation contains equal amount of digits $4$ and $7$. For example, numbers $47$, $7744$, $474477$ are super lucky and $4$, $744$, $467$ are not.\n\nOne day Petya came across a positive integer $n$. Help him to find the least super lucky number which is not less than $n$.",
    "tutorial": "Notice, that answer will looks like this: to some position result will be equal with input string (that part must be lucky), next digit well be greater, the rest of digits are not important. That guarantees us that result will be greater than or equal to N. As rightest this position will be as number will be lesser. Some of the positions may not be ok to us. Let chosen position is i. Left part must be lucky. If S[i] < '4', we can assign S[i] = '4', then fill minimally right part. If S[i] < '7', we can assign '7' to it, like in prevision case. Call position i ok, if absolute different between number of '4' and '7' in part from 0 to i, inclusive is not more than n-i-1. If we chose some rightmost position, which is ok, now we must fill right part. How to do it? If we can assign to some position (we will fill them from left to right) '4' and this position is still ok, then we place '4', else we assign '7'. If there is no ok positions at all, resulting number will looks like this: 4444 \\dots 7777, when number of digits 4 = number of digits 7 = (|N|+2)/2.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "95",
    "index": "C",
    "title": "Volleyball",
    "statement": "Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has $n$ junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths.\n\nInitially each junction has exactly one taxi standing there. The taxi driver from the $i$-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than $t_{i}$ meters. Also, the cost of the ride doesn't depend on the distance and is equal to $c_{i}$ bourles. Taxis can't stop in the middle of a road. \\textbf{Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially.}\n\nAt the moment Petya is located on the junction $x$ and the volleyball stadium is on the junction $y$. Determine the minimum amount of money Petya will need to drive to the stadium.",
    "tutorial": "At first in this simple problem you need to find shortest path between all pair of junctions. That can't be done using O(N^3) algorithms, so you must use Dijkstra algorithm to find this in O(N*N*logN) time. Next part of this problem is to create new matrix, G[i][j] = C[i], if D[i][j] <= R[i], else G[i][j] = INF. Here D[i][j] - length of shortest path between I and j. So, result is shortest path between X and Y using matrix G. That can be done using simple Dijkstra algorithm.",
    "tags": [
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "95",
    "index": "D",
    "title": "Horse Races",
    "statement": "Petya likes horse racing very much. Horses numbered from $l$ to $r$ take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A \\underline{nearly lucky} number is an integer number that has at least two lucky digits the distance between which does not exceed $k$. Petya learned from some of his mates from Lviv that lucky digits are digits $4$ and $7$. The distance between the digits is the absolute difference between their positions in the number of a horse. For example, if $k = 2$, then numbers $412395497$, $404$, $4070400000070004007$ are nearly lucky and numbers $4$, $4123954997$, $4007000040070004007$ are not.\n\nPetya prepared $t$ intervals $[l_{i}, r_{i}]$ and invented number $k$, common for all of them. Your task is to find how many nearly happy numbers there are in each of these segments. Since the answers can be quite large, output them modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "Traditionally I remain that answer is Result(0..R) - Result(0..L-1). Let we have array DP[x][y][z] - number of x-digits number if last lucky digit was on position y, bool z (0 or 1) - was the pair of lucky digits with less than or equal distance then K (call it lucky pair)? Now, let S - string which represent number N. Let F(x, y, z) - result for substring of first x digits, y - position of last lucky digit, z - (0 or 1) - was the lucky pair before? Try to assign some digits on position x. If this digit is less than S[i], then add to result for F(x, y, z) DP[n-x-1][yy][zz] (yy - updated position of last lucky digit, zz - updated bool for lucky pairs). If this digit is equal to S[i], add F(x+1, yy, zz). DP can be calculated simply. Let from state (x, y, z) we place some digit d on position x. Then, we can go to state (x+1, yy, zz). Again, yy and zz - updated parameters. Complexity - O(T * |N}).",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "95",
    "index": "E",
    "title": "Lucky Country",
    "statement": "Petya loves lucky numbers. Everybody knows that positive integers are \\underline{lucky} if their decimal representation doesn't contain digits other than $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not.\n\nOne night Petya was sleeping. He was dreaming of being the president of some island country. The country is represented by islands connected by two-way roads. Between some islands there is no road way, even through other islands, that's why the country is divided into several regions. More formally, each island belongs to exactly one region, there is a path between any two islands located in the same region; there is no path between any two islands from different regions. A region is lucky if the amount of islands in it is a lucky number.\n\nAs a real president, Petya first decided to build a presidential palace. Being a lucky numbers' fan, Petya wants to position his palace in one of the lucky regions. However, it is possible that initially the country has no such regions. In this case Petya can build additional roads between different regions, thus joining them. Find the minimum number of roads needed to build to create a lucky region.",
    "tutorial": "Let A[i] - sorted array of sizes of different connection components, C[i] - number of connection components of size A[i]. Sum for all C[i]*A[i] is equal to N. Size of A will be O(sqrt(N)). Let all C[i] = (2^k)-1, i. e. C[i] = 1 + 2 + 4 + 8 +  \\dots  + 2^(k-1). Obviously, that if chose some subset of this powers we can get any number from 0 to C[i], inclusive. So, the problem now is next: For each A[i] is log(C[i]) things (cost of this thing is size of subset that create it), each can be used at most once. This is standard \"Knapsack\" problem (read this). Complexity of this algorithm is O(N * S), when S is the sum for all log(C[i]). If C[i] is not power of 2, then we must find maximal k, which (2^k)-1 <= C[i] and add C[i]-((2^k)-1) to set.",
    "tags": [
      "dp",
      "dsu",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "96",
    "index": "A",
    "title": "Football",
    "statement": "Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least $7$ players of some team standing one after another, then the situation is considered dangerous. For example, the situation $00100110111111101$ is dangerous and $11110111011101$ is not. You are given the current situation. Determine whether it is dangerous or not.",
    "tutorial": "In this problem you must find longest substring consisting of equal characters and compare it with 7.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "96",
    "index": "B",
    "title": "Lucky Numbers (easy)",
    "statement": "Petya loves lucky numbers. Everybody knows that positive integers are \\underline{lucky} if their decimal representation doesn't contain digits other than $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not.\n\nLucky number is \\underline{super lucky} if it's decimal representation contains equal amount of digits $4$ and $7$. For example, numbers $47$, $7744$, $474477$ are super lucky and $4$, $744$, $467$ are not.\n\nOne day Petya came across a positive integer $n$. Help him to find the least super lucky number which is not less than $n$.",
    "tutorial": "If the length of input number |N| is odd, then, obviously, resulting number will have length |N|+1 and will be like this: 4444 \\dots 7777, at first (|N|+1)/2 digits 4, then the same number of 7's. If the number has even length, then, probably, resulting number will have size |N|, or |N|+2. So, length of the resulting number will have not more than 10 digits. So, we can recursive generate lucky numbers with size <= 10, take the smallest super lucky number which is greater than or equal to N.",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force"
    ],
    "rating": 1300
  },
  {
    "contest_id": "97",
    "index": "A",
    "title": "Domino",
    "statement": "Little Gennady was presented with a set of domino for his birthday. The set consists of $28$ different dominoes of size $2 × 1$. Both halves of each domino contain one digit from $0$ to $6$.\n\n\\begin{verbatim}\n0-0 0-1 0-2 0-3 0-4 0-5 0-6\n1-1 1-2 1-3 1-4 1-5 1-6\n2-2 2-3 2-4 2-5 2-6\n3-3 3-4 3-5 3-6\n4-4 4-5 4-6\n5-5 5-6\n6-6\n\\end{verbatim}\n\nThe figure that consists of $28$ dominoes is called \\underline{magic}, if it can be fully covered with $14$ non-intersecting squares of size $2 × 2$ so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear — he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest.\n\nGennady chose a checked field of size $n × m$ and put there rectangular chips of sizes $1 × 2$ and $2 × 1$. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly $28$ chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round.",
    "tutorial": "We need to assign some number from 0 to 6 to each of the 14 squares. Note that if you take the solution and apply some permutation of digits to the field, you obtain another correct solution. So, the solution is characterized by division of 14 squares to pairs. If we have such a partition, then it is possible to generate a 7! corresponding solutions. Count of possible partitions is $13!! = 13 \\cdot 11 \\cdot 9 \\cdot 7 \\cdot 5 \\cdot 3 = 135135$ . It is easily to verify the correctness for each of the 100k options. With up to rotations, count of all field configurations that have solutions is about 6000. The largest number of solutions - $22 \\cdot 7!$. 1) If you do not optimize the solution in $7!$ time, you can get a TL. As was shown in the comments it's enough to optimize $7$ times. 2) You would think that the squares are divided into two classes - 7 squares that have double dominoes, and 7, in which it is not present. If we talk in terms of graphs there are 7 vertices with degree 2, and 7 with degree of 4. Clearly, two vertices of degree 2 can not correspond to a single digit, otherwise we get two double dominoes. With this division is sufficient to iterate over 7! possible matches vertices of the second type to vertices of the first type. Double domino 4-4 split between the two squares. There are 6 vertices of degree 2 and 8 vertices of degree. Challenge Succeeded. Furthermore: Here for two double dominoes lie between squares! And bonus, one of the most beautiful configurations with several holes: Disconnected configuration with solutions don't exist :(",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "97",
    "index": "D",
    "title": "Robot in Basement",
    "statement": "The Professor has lost his home robot yet again. After some thinking Professor understood that he had left the robot in the basement.\n\nThe basement in Professor's house is represented by a rectangle $n × m$, split into $1 × 1$ squares. Some squares are walls which are impassable; other squares are passable. You can get from any passable square to any other passable square moving through edge-adjacent passable squares. One passable square is the exit from the basement. The robot is placed exactly in one passable square. Also the robot may be placed in the exit square.\n\nProfessor is scared of going to the dark basement looking for the robot at night. However, he has a basement plan and the robot's remote control. Using the remote, Professor can send signals to the robot to shift one square left, right, up or down. When the robot receives a signal, it moves in the required direction if the robot's neighboring square in the given direction is passable. Otherwise, the robot stays idle.\n\nProfessor wrote a sequence of $k$ commands on a piece of paper. He thinks that the sequence can lead the robot out of the basement, wherever it's initial position might be. Professor programmed another robot to press the required buttons on the remote according to the notes on the piece of paper. Professor was just about to run the program and go to bed, when he had an epiphany.\n\nExecuting each command takes some energy and Professor doesn't want to get huge electricity bill at the end of the month. That's why he wants to find in the sequence he has written out the minimal possible prefix that would guarantee to lead the robot out to the exit after the prefix is fulfilled. And that's the problem Professor challenges you with at this late hour.",
    "tutorial": "A naive solution works in $O(nmk)$. This solution stores all the start positions into an array and next iterates over all commands and shifts positions in needed directions. After every move it checks that all positions lie on the exit cell. This solution doesn't fit into time limits. An author's solution speed up the naive solution with using of bit masks. All current positions of robot you should store in rectangular bit mask of size $n  \\times  m$. This mask should provide following operations: 1. Shift left, right, up, down. 2. Binary operations AND and OR. 3. Compare with another mask. All these operations can be realized so that they will work in $O(nm / 32)$ time. You can use array of 32-bit integers of size $n  \\times  m / 32$ or std::bitset in C++. How to emulate process? At first, you should create a mask base that has 1-bit for every passable cell and 0-bit otherwise. Now you should create sevaral additional masks for all four directions: up1, up2, left1, left2, down1, down2, right1, right2. Masks with index 1 store cells that lie near wall, ans masks with index 2 store all other cells of mask base. Also you should create mask E that has only one 1-bit in the exit cell. Let all current positions of robor are given by mask T. Split T into 2 sets of positions: all ones that lie near wall (the first set) and all other ones (the second set). Now you should shift all positions in the second set and next merge two sets into one. The finish set gives new mask T. This transformation in operations with masks looks like: T = ((T and up1) or shift_up(T and up2)); You can transform T analogically for other three directions. Now you should iterate over all commands and do transformations. On every step you should compare T with E. As soon as they are equal, you should output number of a command after that it happened. If always T and E are unequal, you should output -1. This solution has complexity $O(nmk / 32)$. Author's solutions on C++ and Java without any serious optimizations work in 0,9 sec and 2,3 sec correspondingly.",
    "tags": [
      "bitmasks",
      "brute force",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "98",
    "index": "A",
    "title": "Help Victoria the Wise",
    "statement": "Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.\n\nThe box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube)\n\nNow Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem.",
    "tutorial": "In this problem you were required to find the number of sufficiently different colorings of a cube faces with predefined six colors. The most trivial solution is to introduce some ordering of the cube faces (say, 0 - front, 1 - back, 2 - up, 3 - down, 4 - left, 5 - right), then consider 720 = 6! arrangements of colors over these 6 faces. Each arrangement is some permutation of characters from the input. For each arrangement we find all its 24 rotations - and get 24 strings. Lexicographically smallest string will be representative of this coloring. The answer is the number of different representatives.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "98",
    "index": "B",
    "title": "Help King",
    "statement": "This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.\n\nOnce upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast.\n\nHaving travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage.\n\nThe problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be $n$ noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to $1 / n$). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.",
    "tutorial": "Unfortunately, initial author's solution for this problem appeared wrong. However, the optimality of the below algo was proved by Knuth and Yao in 1976. Limitation for n in the problem now changed to 10000. The process of tossing a coin and making decisions regarding which alternative to choose may be naturally described as drawing some (possibly infinite) binary tree. Each toss \"draws\" two new branches from every free node of the tree (initially the tree consists of one free node). Whenever the number of free nodes becomes >= n, you turn n free nodes into leaves (onle leaf for each alternative), and proceed with the other free nodes in a similar way. For example, for n == 3 we get the following infitite tree: o / \\ o o / \\ / \\ 1 2 3 o / \\ ... ... Now we should evaluate expected length of a random path in this infinite tree now. One may notice that the tree is recursive: since the number of free nodes at every level is strictly less than n, the situation will repeat after maximum of n steps. Once one notices this, it is not so hard to derive formulas for the answer. Since numbers in the answer could be of the order 2^n, one needs to write \"long arithmetics\", or use Java.BigInteger.",
    "tags": [
      "implementation",
      "probabilities",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "98",
    "index": "C",
    "title": "Help Greg the Dwarf",
    "statement": "A very unusual citizen lives in a far away kingdom — Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg — he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.\n\nThe worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help.\n\nYou've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to $a$ and $b$ correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to $l$ and $w$ ($l ≥ w$) correspondingly. Dwarf Greg has already determined the coffin's length ($l$), which is based on his height; your task is to determine the coffin's maximally possible width ($w$), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.\n\nGreg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him...",
    "tutorial": "For this problem I assumed numerical solution. But there are several cases to consider. Below without loss of generality we assume a <= b. 1. l <= a <= b. In this case the answer is restricted by the length of the coffin, so the answer is l and it is clear that the coffin l x l can be brought through the corridor (a, b) - let's denote corridor's sizes in this way. 2. a < l <= b. In this case the answer is a, and it is clear that no larger number can be an answer. Indeed, otherwise the coffin (w > a) x (l > a) is impossible to drag through the corridor (a, b). 3. a <= b < l. This is the most general case, where we should rotate the coffin inside the corridor where it has a kink. To maximise the width of the coffin, we want to move it in such a way that one corner of the coffin touches one outer wall of the corridor (suppose bottommost on the picture), and another corner adjacent to the same long side of the coffin touches another outer wall of the corridor (leftmost on the picture). Let's introduce coordinate system in such a way that bottommost wall be OX axis, and leftmost wall - OY axis. Suppose that during the \"rotation\" process one corner of the coffin is at the point (x,0) (0 <= x <= l), then another corner should be at the point (0,sqrt(l*l-x*x)). And the answer we search for is min {distance from the segment (x,0) - (0,sqrt(l*l-x*x)) to the point (a,b) }, where you take min{} over all 0 <= x <= l. Let this distance at point x be f(x). Since f(x*) is minimal in some point x* and increases everywere to the left and to the right from x*, one may use ternary search to find its minimum. Exact solution for this problem is also possible: you can reduce the problem to minimizing the dot product of the vectors (a-x,b) and (-x,sqrt(l*l-x*x)) over x. But this leads to the neccessity to find the roots of the fourth-degree polynomial, which is not the best idea during the contest.",
    "tags": [
      "geometry",
      "ternary search"
    ],
    "rating": 2500
  },
  {
    "contest_id": "98",
    "index": "D",
    "title": "Help Monks",
    "statement": "In a far away kingdom is the famous Lio Shan monastery. Gods constructed three diamond pillars on the monastery's lawn long ago. Gods also placed on one pillar $n$ golden disks of different diameters (in the order of the diameters' decreasing from the bottom to the top). Besides, gods commanded to carry all the disks from the first pillar to the third one according to the following rules:\n\n- you can carry only one disk in one move;\n- you cannot put a larger disk on a smaller one.\n\nThere was no universal opinion concerning what is to happen after the gods' will is done: some people promised world peace and eternal happiness to everyone, whereas others predicted that the kingdom will face communi… (gee, what am I rambling about?) the Armageddon. However, as everybody knew that it was impossible to solve the problem in less than $2^{n} - 1$ moves and the lazy Lio Shan monks never even started to solve it, everyone lives peacefully even though the problem was never solved and nobody was afraid of the Armageddon.However, the monastery wasn't doing so well lately and the wise prior Ku Sean Sun had to cut some disks at the edges and use the gold for the greater good. Wouldn't you think that the prior is entitled to have an air conditioning system? Besides, staying in the monastery all year is sooo dull… One has to have a go at something new now and then, go skiing, for example… Ku Sean Sun realize how big a mistake he had made only after a while: after he cut the edges, the diameters of some disks got the same; that means that some moves that used to be impossible to make, were at last possible (why, gods never prohibited to put a disk on a disk of the same diameter). Thus, the possible Armageddon can come earlier than was initially planned by gods. Much earlier. So much earlier, in fact, that Ku Sean Sun won't even have time to ski all he wants or relax under the air conditioner.\n\nThe wise prior could never let that last thing happen and he asked one very old and very wise witch PikiWedia to help him. May be she can determine the least number of moves needed to solve the gods' problem. However, the witch laid out her cards and found no answer for the prior. Then he asked you to help him.\n\nCan you find the shortest solution of the problem, given the number of disks and their diameters? Keep in mind that it is allowed to place disks of the same diameter one on the other one, however, the order in which the disks are positioned on the third pillar in the end should match the initial order of the disks on the first pillar.",
    "tutorial": "This problem was about famous puzzle \"Hanoi towers\", but diameters of some discs might be equal. How to solve that? A good thing to do is to write BFS solution to check optimality of your ideas for small inputs (by the way, BSF works quickly for almost all towers that have up to 10 discs) and then try to create an algo which solves the puzzle in an optimal way. Let C (x1, x2, ..., xn) be a solution (under \"solution\" here we mean optimal number of moves - the moves itself is easy to get with one recursive procedure; also \"solution\" is the number of moves to move group of discs from one peg to any other (and not some particular) ) to the puzzle when we have a puzzle with x1 equal largest discs, x2 equal second largest discs and so on. And let U (x1, x2, ..., xn) be a solution to the puzzle when you are allowed not to save the order of the discs (you should still follow the restriction of the initial puzzle not to put larger discs onto the smaller ones, but at the end discs of the same diameter may be in any order). Then one of the optimal solutions to the problem is the following: C (x1, x2, ..., xn) = U (x1, x2, ..., xn) if x1 = 1 (*) C (x1, x2, ..., xn) = 2*x1 - 1 if n = 1 (**) C (x1, x2, ..., xn) = U (x2, ..., xn) + x1 + U (x2, ..., xn) + x1 + C (x2, ..., xn). (***) U (x1, x2, ..., xn) = U (x2, ..., xn) + x1 + U (x2, ..., xn) (****) Why so? One can notice that U() is \"almost\" solution for our problem: it \"flips\" order of the bottommost group of equal discs, the order of the rest of the discs remains the same! (try to understand why) That's why (*) is correct. The (**) is quite obvious. The (***) does the following: move (x2, ..., xn) from peg 1 to peg 2 without saving the order. Then move x1 equal discs from peg 1 to peg 3, then move (x2, ..., xn) from peg 2 to peg 1 without saving the order (but it occurs that after we apply U() to the same group of discs twice, the order restored!), then move x1 equal discs from peg 3 to peg 2, and then use C() to move (x2, ..., xn) from peg 1 to peg 2 (here we use C() since we should preserve the order). So, (***) is correct. And (****) is quite straightforward expression for U(): move all discs but the largest group with the same algo, then move largest discs (that's why if x1 > 1, the group of discs \"flips\"), and then move all discs but the largest group onto the same peg with x1.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2500
  },
  {
    "contest_id": "98",
    "index": "E",
    "title": "Help Shrek and Donkey",
    "statement": "Shrek and the Donkey (as you can guess, they also live in the far away kingdom) decided to play a card game called YAGame. The rules are very simple: initially Shrek holds $m$ cards and the Donkey holds $n$ cards (the players do not see each other's cards), and one more card lies on the table face down so that both players cannot see it as well. Thus, at the beginning of the game there are overall $m + n + 1$ cards. Besides, the players know which cards the pack of cards consists of and their own cards (but they do not know which card lies on the table and which ones the other player has). The players move in turn and Shrek starts. During a move a player can:\n\n- Try to guess which card is lying on the table. If he guesses correctly, the game ends and he wins. If his guess is wrong, the game also ends but this time the other player wins.\n- Name any card from the pack. If the other player has such card, he must show it and put it aside (so that this card is no longer used in the game). If the other player doesn't have such card, he says about that.\n\nRecently Donkey started taking some yellow pills and winning over Shrek. Now Shrek wants to evaluate his chances to win if he too starts taking the pills.Help Shrek assuming the pills are good in quality and that both players using them start playing in the optimal manner.",
    "tutorial": "This problem was about optimally playing this simple-at-first-glance game. The key thing to recognize in the statement was that it is not always optimal to name card which you don't have. Sometimes it is optimal to confuse the opponent by naming card which you have on hand. In this case... yes, he may think that the card you named is card on the table and lose during the next turn. Now the problem is to understand when to use the strategy of reduction of opponent's cards, when to bluff in the abovementioned sense and when to try to determine which card is on the table. But instead of \"when\" the right question is \"how frequently\" since we have nothing else but usual constant-sum matrix game, and optimal strategy is the mixture of these three. Let's construct a matrix first. Player 1 has three pure strategies: \"playing\" (when he plays the game and really tries to determine opponent's cards and card on the table), \"guessing\" (when he guesses which card is lying on the table) and \"bluffing\" (when he tries to confuse his opponent to force him to lose by naming card in his own hand). In turn, if the first player used \"bluffing\" strategy, or during the \"playing\" strategy named card on the table, his opponent has two strategies: \"check\" (i.e. to believe the first player that he doesn't own the card he named and guess it as the card on the table) and \"move on\" (i.e. to decide that it was a \"bluffing\" strategy and the game should be continued, but with notice that the first player has named card on hands). Let's denote P(m,n) probability to win the game when the first player has m cards and the second player has n cards. Then P(m,n) is the value of the matrix game with the following matrix (rows - strategies of the first player, two numbers in the rows - probabilities to win when the second player uses strategies \"check\" and \"move on\" correspondingly: \"check\" \"move on\" \"playing\" n/(n+1)*(1-P(n-1,m)) 1/(n+1) + n/(n+1)*(1-P(n-1,m)) \"guessing\" 1/(n+1) 1/(n+1) \"bluffing\" 1 1-P(n,m-1) How to get these numbers in the matrix? Consider the first row: \"playing\" strategy of the first player, \"check\" strategy of the second. First just names one of the n+1 cards. With probability 1/(n+1) he names card on the table, seconds checks it and wins (so, probability to with for the first is 0), with probability n/(n+1) the first names one of the cards on hands of the second player, so the game continues, second wins with prob. P(n-1,m) in this case. Then the overall probability for the first to win with such combination of pure strategies is n/(n+1)*(1-P(n-1,m)). In the same manner we fill other cells of the matrix. Finally we solve the game (this can be done straightforwardly, or with one formula if one notices that the \"guessing\" strategy is suboptimal everywhere when m>=1 and n>=1 and that the game doesn't have saddle points) and get answer to the problem - P(m,n). And the last thing to note: when m==0 it is clear that during his move the second wins, so the first should guess, and P(0,n) = 1/(n+1). When n==0 P(m,0)==1 sinse we just do one rightguessing.",
    "tags": [
      "dp",
      "games",
      "math",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "99",
    "index": "A",
    "title": "Help Far Away Kingdom",
    "statement": "In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.\n\nMost damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly $0.273549107$ beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this:\n\n- If a number's integer part does not end with digit $9$ and its fractional part is strictly less than $0.5$, then the rounded up number coincides with the number’s integer part.\n- If a number's integer part does not end with digit $9$ and its fractional part is not less than $0.5$, the rounded up number is obtained if we add $1$ to the last digit of the number’s integer part.\n- If the number’s integer part ends with digit $9$, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position.\n\nMerchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?",
    "tutorial": "Here the problem was to round a number up according to the usual mathematical rules with the exception that if the last digit of integer part is equal to 9, you should output \"GOTO Vasilisa.\". One may notice that to check whether number's fractional part is not less than 0.5 only one digit just after the decimal point should be analysed. If it is '5' or greater - add one to the last digit of the integer part, and the problem is solved. Probably, the simplest way to deal with the input data was using of the string variables.",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "99",
    "index": "B",
    "title": "Help Chef Gerasim",
    "statement": "In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.\n\nTo simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.",
    "tutorial": "The problem was to accurately check what is required in the problem statement. First of all, check whether all volumes in the input are equal. In this case output \"Exemplary pages.\". Otherwise find two cups with largest and smallest volumes. Suppose their numbers are a and b, and their volumes are v[a] and v[b]. Now suppose that before pouring their volumes were equal to V. Then they contained 2V units of juice before (and after) pouring. So, you need to check whether (v[a] + v[b]) is divisible by 2. If this is not so - output \"Unrecoverable confihuration.\". Otherwise assign to the cups presumable old volume v[a] = v[b] = (v[a] + v[b])/2. Now if only one pouring have been made, volumes of juice in all cups should be equal, and you print corresponding message \"... ml. from ... to ...\". If volumes are not equal, print \"Unrecoverable configuration\" instead.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "101",
    "index": "A",
    "title": "Homework",
    "statement": "Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of $n$ small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than $k$ characters, it will be very suspicious.\n\nFind the least number of distinct characters that can remain in the string after no more than $k$ characters are deleted. You also have to find any possible way to delete the characters.",
    "tutorial": "Lets count up the number of entries to string of every letter. Let Gerald choose $x$ letter and lose them. Obvious thet if he lose $x$ rarest letters then overall number of losed letter do not increase, and then if he can lose some $x$ lettes, he can lose $x$ rarest ones. Thus it's easy to determine if Gerald can loses $x$ letters. And now to calculate the answer one only need to find the minimal such $x$, so Gerald can lose $x$ letters.",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "101",
    "index": "B",
    "title": "Buses",
    "statement": "Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly $n + 1$ bus stops. All of them are numbered with integers from $0$ to $n$ in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number $0$ and the bus stop by the school has number $n$.\n\nThere are $m$ buses running between the house and the school: the $i$-th bus goes from stop $s_{i}$ to $t_{i}$ ($s_{i} < t_{i}$), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the $i$-th bus on any stop numbered from $s_{i}$ to $t_{i} - 1$ inclusive, but he can get off the $i$-th bus only on the bus stop $t_{i}$.\n\nGerald can't walk between the bus stops and he also can't move in the direction from the school to the house.\n\nGerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by $1000000007$ ($10^{9} + 7$).",
    "tutorial": "For every slop from $0$ to $n$ lets calculate $k_{x}$ - number of ways come to them. Consider the $i$-th bus. Number of ways come to stop $t_{i}$ applied $i$-th bus is uqual to number of way to embus to $i$-th bus. One can embus to $i$-th bus on the stops $s_{i}, s_{i} + 1, ..., t_{i} - 1$. Thus number of ways come to stop $t_{i}$ in the $i$ bus is equal to sum $k_{si} + k_{si + 1} + ... + k_{ti - 1}$. Finally, lets note that overall number of way to come to stop $t_{i}$ is the sum of numbers of ways to come to stop $t_{i}$ on every bus. It's remained two problems. First problem: $0  \\le  n  \\le  10^{9}$. Therefore all $k_{x}$ not climb in memory limit. But we need to know only non-zero $k_{x}$. For instance, one can gripe coordinates: create list of all occured stops (and also stops $0$ and $n$), sort this list, delete the repeated stops and replace all numbers of stops they indexes in this list. After this operations all number of stops not exceed $200001$, and all $k_{x}$ are climb to the memory. Second problem: if we will use loop \"for\" for counting sum $k_{si} + k_{si + 1} + ... + k_{ti - 1}$, asymptotic of time of working will be O(m^2). There is an easy way to solve this problem: one can create and update array $sum[]$, such that $sum[i] = k[0] + k[1] + ... + k[i - 1]$, by another words, $sum[0] = 0, sum[i + 1] = sum[i] + k[i]$. Then munber of ways to come to stop $t_{i}$ using bus $i$ is equal to $sum[t_{i}] - sum[s_{i}]$. So time complexity is O(m \\cdot log(m)), memory complexity is O(m).",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "101",
    "index": "C",
    "title": "Vectors",
    "statement": "At a geometry lesson Gerald was given a task: to get vector $B$ out of vector $A$. Besides, the teacher permitted him to perform the following operations with vector $А$:\n\n- Turn the vector by $90$ degrees clockwise.\n- Add to the vector a certain vector $C$.\n\nOperations could be performed in any order any number of times.\n\nCan Gerald cope with the task?",
    "tutorial": "Lets formulate the problem in complex number. Consider complex numbers $a = x_{A} + iy_{A}$, $b = x_{B} + iy_{B}$ and $c = x_{C} + iy_{C}$. One can do operation $A  \\rightarrow  A + C$ and $A  \\rightarrow  iA$. If we apply this transform some times in some order to $A$, we will get number $A \\cdot  i^{k} + aC + biC - cC - idC$ for some non-negative integers $k, a, b, c, d$ or, in another words, $A \\cdot  i^{k} + aC + biC$ for $k = 0, 1, 2, 3$ and some integers $a, b$. Since $k$ can be equal only $0$, $1$, $2$ or $3$, sufficiently to get to know is one can to represent $B - A$, $B - iA$, $B + A$ or $B + iA$ in the form of $aC + biC$. Then, how to determine, is one can to represent some complex number D in the such form? One can represent equation $D = aC + biC$ in the form of linear real equation system: $a \\cdot  x_{C} - b \\cdot  y_{C} = x_{D}$ $a \\cdot  y_{C} + b \\cdot  x_{C} = y_{D}$ To solve this system - is standart tehnical problem.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "101",
    "index": "D",
    "title": "Castle",
    "statement": "Gerald is positioned in an old castle which consists of $n$ halls connected with $n - 1$ corridors. It is exactly one way to go from any hall to any other one. Thus, the graph is a tree. Initially, at the moment of time $0$, Gerald is positioned in hall $1$. Besides, some other hall of the castle contains the treasure Gerald is looking for. The treasure's position is not known; it can equiprobably be in any of other $n - 1$ halls. Gerald can only find out where the treasure is when he enters the hall with the treasure. That very moment Gerald sees the treasure and the moment is regarded is the moment of achieving his goal.\n\nThe corridors have different lengths. At that, the corridors are considered long and the halls are considered small and well lit. Thus, it is possible not to take the time Gerald spends in the halls into consideration. \\textbf{The castle is very old, that's why a corridor collapses at the moment when somebody visits it two times, no matter in which direction.}\n\nGerald can move around the castle using the corridors; he will go until he finds the treasure. Naturally, Gerald wants to find it as quickly as possible. In other words, he wants to act in a manner that would make the average time of finding the treasure as small as possible. \\textbf{Each corridor can be used no more than two times. That's why Gerald chooses the strategy in such a way, so he can visit every hall for sure.}\n\nMore formally, if the treasure is located in the second hall, then Gerald will find it the moment he enters the second hall for the first time — let it be moment $t_{2}$. If the treasure is in the third hall, then Gerald will find it the moment he enters the third hall for the first time. Let it be the moment of time $t_{3}$. And so on. Thus, the average time of finding the treasure will be equal to $\\frac{t_{2}+t_{3}+\\dots+t_{n}}{n-1}$.",
    "tutorial": "Remunerate vertexes in such a way, that start Gerald vertex have got number $0$. Consider that vertex $0$ is the root of tree, and lets consider its children. Let Gerald first go to vertex $x$. Then he must to travel throw hole subtree, otherwise he will not visit all vertex in subtree. Then he come back to $0$ and go to some next its child. Lets try to calculate looked for value for hole tree when we know all subtree values. If we can to do it, we can solve problem using dynamyc programming on the tree. Lets vertex $0$ have $n$ children. Lets $i$-th subtree have $k_{i}$ offspring (inclusive $i$-th child of $0$). Let the hole tree consist of $N$ vertexes. Lets $T_{i}$ is the doubled sum of lenght all edges in $i$-th subtree, inclusive edge between $0$ and its $i$-th child. It is the time to travel throw hole $i$-th subtree, starting in $0$ and returning to $0$. Finally, lets $t_{i}$ is answer to problem on $i$-th subtree. At once we add to this time length of edge between $0$ and its $i$-th child. Lets Gerald travel throw all subtrees in order $1, 2, ..., n$. What is average time of finding the treasure? Treasure can be in first subtree with probability $\\stackrel{k_{1}}{N}$. Then average time of finding the treasure will be $t_{1}$. Treasure can be in second subtree with probability $\\stackrel{k_{2}}{N}$. Then average time of finding the treasure will be $T_{1} + t_{2}$. And so on. Thus, average time of finding the treasure will be ${\\frac{1}{N}}\\left((k_{1}t_{1}+k_{2}t_{2}+\\cdots+k_{n}t_{n})+(k_{1}\\cdot0+k_{2}T_{1}+k_{3}(T_{1}+T_{2})+\\cdots+k_{n}(T_{1}+\\cdots+T_{n-1}))\\right)$ Can we decrease this time? Lets swap $i$ and $i + 1$ subtrees. Then item $k_{i + 1}T_{i}$ disappear from sum and appear item $k_{iT}_{i + 1}$. Sum will chenge to $k_{iT}_{i + 1} - k_{i + 1}T_{i}$. Sum will decrease, if $k_{iT}_{i + 1} - k_{i + 1}T_{i} < 0$, in ather words ${\\frac{T_{i}}{k_{i}}}>{\\frac{T_{i+1}}{k_{i+1}}}$. Therefore, one can't decrease average time, if subtrees are sorted by increasing value $\\frac{T_{i}}{k_{i}}$. So, we must to sorted trees in this order and traveling from them in this order.",
    "tags": [
      "dp",
      "greedy",
      "probabilities",
      "sortings",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "101",
    "index": "E",
    "title": "Candies and Stones",
    "statement": "Little Gerald and his coach Mike play an interesting game. At the beginning of the game there is a pile consisting of $n$ candies and a pile consisting of $m$ stones. Gerald and Mike move in turns, Mike goes first. During his move Mike checks how many candies and stones Gerald has eaten. Let Gerald eat $a$ candies and $b$ stones. Then Mike awards Gerald $f(a, b)$ prize points. Gerald during his move either eats a candy from the pile of candies or a stone from the pile of stones. As Mike sees that Gerald has eaten everything apart one candy and one stone, he awards points for the last time and the game ends. Gerald is not allowed to eat all the candies, and he is not allowed to eat all the stones too. Tell Gerald how to play to get the largest possible number of points: it is required to find one of the possible optimal playing strategies for Gerald.",
    "tutorial": "Essence of problem is that there is a board $n  \\times  m$ in cell of wich placed numbers. And one must go from cell $(0, 0)$ to cell $(n - 1, m - 1)$, doing moves to one cell up and right (that is, increasing by $1$ on of coordinates), maximizing sum o number on the cell in the path. Gerald's problems is determine $m + n - 1$ cells of optimal path. Lets start with search one, middle cell. Lets $k={\\frac{n+m-2}{2}}$. What cell of board can be $k$-th in path? It is cell, sum of coordinate of wich is equal to $k$, thus, it is diagonal of doard. And then we can calculate, what maximum sum Gerald can collect, came to every cell in the diagonal, by dynamic programming in lower triangle. And the same way, we can calculate, what maximum sum Gerald can collect, came to cell (n-1,m-1), starting from every cell in the diagonal. Sumed up this to values, we calculate, what maximum sum Gerald can collect, came to from cell $(0, 0)$ to cell $(n - 1, m - 1)$, travel throw every cell in the diagonal. And now we will find cell $(x, y)$, in wich maximum is reached. It is $k$-th cell of the path. We used time $O((n + m)^{2})$ and memory $O(n + m)$. Then we make recursive call on subproblems. In other word, will find optimal path from cell $(0, 0)$ to cell $(x, y)$ and from cell $(x, y)$ to cell $(n, m)$. It is evident, this solution take memory O(n+m). Why it tkae time O((n+m)^2)? Lets $n + m$ is $r$. Once we are find middle cell of path of length $k$. Twice we are find middle cell of path of length $\\displaystyle{\\frac{k}{2}}$. Four times we are find middle cell of path of length $\\frac{k}{4}$. And so on. Therefore, time of program working will be $r^{2}+2{\\frac{r^{2}}{4}}+4{\\frac{r^{2}}{16}}+\\cdot\\cdot\\cdot=r^{2}+{\\frac{r^{2}}{2}}+{\\frac{r^{2}}{4}}+\\cdot\\cdot\\cdot=r^{2}+r^{2}$. Thus, this solution take time $O((n + m)^{2})$.",
    "tags": [
      "divide and conquer",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "102",
    "index": "A",
    "title": "Clothes",
    "statement": "A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.\n\nOverall the shop sells $n$ clothing items, and exactly $m$ pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.",
    "tutorial": "In this problem constraints are allow to look throw all triples of clothes. For every triple one can check if all elements of tripe areturn out to match with others, and anong those triples find one whith minimal cost.",
    "tags": [
      "brute force"
    ],
    "rating": 1200
  },
  {
    "contest_id": "102",
    "index": "B",
    "title": "Sum of Digits",
    "statement": "Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number $n$. How many times can Gerald put a spell on it until the number becomes one-digit?",
    "tutorial": "Initial number consist of no more then $100000$ digits. Therefore after first transform resulting number will be no more then $900000$, and then it will constist of no more then $6$ digits. Thus after next transform number will be no more then $54$ and so it will be two-digit or one-digit. Sum of digits of a two-digit number no more, then $18$, and sum of digit of such number no more, then $9$. Thus Gerald can't do nore, then $4$ transforms. First transform one can implement one simple pass throw symbols of given string. Following operations take very little time.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "103",
    "index": "A",
    "title": "Testing Pants for Sadness",
    "statement": "The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called \"Testing Pants for Sadness\".\n\nThe test consists of $n$ questions; the questions are to be answered strictly in the order in which they are given, from question $1$ to question $n$. Question $i$ contains $a_{i}$ answer variants, exactly one of them is correct.\n\nA click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the $n$ questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question $1$ again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.\n\nVaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?",
    "tutorial": "We can't move to the $i + 1$-th question before clicking all answers at $i$-th question. We will move to the very beginning clicking at $a_{i} - 1$ answers and only one will move us to the next step. Every way from beginning to $i$-th question have length equal to $i - 1$ plus one for click. There is a simple formula for $i + 1$-th question: $c_{i} = (a_{i} - 1) \\cdot  i + 1$, 1-based numeration. Let's summarize all values of $c_{i}$ for making the answer. Complexity is $O(n)$.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "103",
    "index": "B",
    "title": "Cthulhu",
    "statement": "...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...\n\nWhereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with $n$ vertices and $m$ edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.\n\nTo add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.\n\nIt is guaranteed that the graph contains no multiple edges and self-loops.",
    "tutorial": "Look at the formal part of statement. Cthulhu is a simple cycle with length of 3 or more and every vertix of the cycle should be a root of some tree. Notice this two important facts: a) Cthulhu is a connected graph b) Cthulhu is a graph with only cycle If we add only one edge to tree (not a multiedge nor loop) then we will get a graph that a) and b) properties. There is a simple solution: let's check graph for connectivity (we can do it by one DFS only) and check $n = m$ restriction. If all are ok then graph is Cthulhu. Complexity is $O(m)$.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "103",
    "index": "C",
    "title": "Russian Roulette",
    "statement": "After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of $n$ bullet slots able to contain exactly $k$ bullets, now the boys have a chance to resolve the problem once and for all.\n\nSasha selects any $k$ out of $n$ slots he wishes and puts bullets there. Roma spins the cylinder so that every of $n$ possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner.\n\nSasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one.\n\nMore formally, the cylinder of $n$ bullet slots able to contain $k$ bullets can be represented as a string of $n$ characters. Exactly $k$ of them are \"X\" (charged slots) and the others are \".\" (uncharged slots).\n\nLet us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.\n\nAmong all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each $x_{i}$ query must be answered: is there a bullet in the positions $x_{i}$?",
    "tutorial": "Let's solve the problem when value $n$ is even. Obviously, if $k = 1$ we should put a bullet at most right position. For example, choose $n = 8$ and our answer string will be: .......X Let's find probability of winning at this situation. We will write zeros at losing positions and ones at winning positions: 10101010 The simple idea is to put every next bullet for non-dropping down our winning chance as long as we can. After that we should put bullets in lexicographically order with growing value of $k$. Look for the answer for another $k$'s with $n = 8$: .....X.X ...X.X.X .X.X.X.X .X.X.XXX .X.XXXXX .XXXXXXX XXXXXXXX When $n$ is odd our reasoning will be the same with a little bit difference at the beginning. Look at the answer with $n = 9$ and $k = 1$:: ........X 010101010 We may put second bullet as at even case. But there is exists another way, we may put our bullet at 1st position and turn left the cylinder, look here: X.......X => .......XX 010101010 101010100 Obvioulsy probability of winning was not changed but answer made better. Next steps of putting are equal to even case: .....X.XX ...X.X.XX .X.X.X.XX .X.X.XXXX .X.XXXXXX .XXXXXXXX XXXXXXXXX There is no difficulties to give answers to queries. Complexity is $O(p)$.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "103",
    "index": "D",
    "title": "Time to Raid Cowavans",
    "statement": "As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space.\n\nSometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row.\n\nIf we number all cows in the cowavan with positive integers from $1$ to $n$, then we can formalize the popular model of abduction, known as the $(a, b)$-Cowavan Raid: first they steal a cow number $a$, then number $a + b$, then — number $a + 2·b$, and so on, until the number of an abducted cow exceeds $n$. During one raid the cows are not renumbered.\n\nThe aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made $p$ scenarios of the $(a, b)$-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen.",
    "tutorial": "Let's solve this problem by offline. Read all queries and sort them by increasing $b$. After that there are many effective solutions but I tell you a most simple of them. Look at two following algorithms: 1. For each $(a, b)$-query calculate the answer by the simple way: for(int i = a; i < n; i += b) ans += a[i]; 2. Fix the value of $b$ and calculate DP for all possible values of $a$: for(int i = n - 1; i >= 0; i--) if (i + b >= n) d[i] = a[i]; else d[i] = d[i + b] + a[i]; Obvioulsy, the 1st algorithm is non-effective with little values of $b$ and the 2nd algorithm is non-effecitve with very different values of $b$. Behold that it's impossible to generate the situation where all $b$'s are so little and different simultaniously. There is a simple idea: we may solve the problem by 1st algo if values of $b$ are so large (if they are greater than $c$) and solve by 2nd algo if values of $b$ are so small (if they are less of equal to $c$). We need to sort our queries because of no reason to calculate DP of any $b$ more than once. If we choose $c$ equal to $\\sqrt{n}$ that we will get a $O(p \\cdot \\sqrt{n})$ complexity. Complexity is $O(p \\cdot \\sqrt{n})$.",
    "tags": [
      "brute force",
      "data structures",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "103",
    "index": "E",
    "title": "Buying Sets",
    "statement": "The Hexadecimal virus loves playing with number sets — intersecting them, uniting them. One beautiful day she was surprised to find out that Scuzzy, her spherical pet cat, united all sets in one and ate the result! Something had to be done quickly and Hexadecimal rushed to the market.\n\nThe market has $n$ sets of numbers on sale. The virus wants to buy the following collection of sets: the number of sets in the collection should be exactly the same as the number of numbers in the union of all bought sets. Moreover, Hexadecimal wants to buy the cheapest suitable collection of set.\n\nYet nothing's so easy! As Mainframe is a kingdom of pure rivalry markets, we know that the union of any $k$ sets contains no less than $k$ distinct numbers (for every positive integer $k$).\n\nHelp the virus choose the suitable collection of sets. The collection can be empty.",
    "tutorial": "Construct bipartite graph $G_{1}$ with available sets on the left side and the numbers on the right side. We put an edge from a set to all the numbers contained in it. By Hall's theorem it follows from \"the union of any k sets contains no less than k distinct numbers (for every positive integer k)\" that there exists perfect matching of all the elements in the bipartite graph (in fact the theorem states that there exists matching including all set vertices, but as the numbers are also restricted by n, this means that there exists perfect matching$. After this observation we find whichever perfect matching in $G_{1, }$let's denote it by $M = {(u_{i}, v_{i})}$. Now we construct second oriented graph $G_{2}$ with vertices corresponding to the available sets and edges ($u_{i}  \\rightarrow  u_{j}$) for each edge ($u_{i}, v_{j}$) from $G_{1}$ that do not occur in $M$ (Note that the matching sets the indices of v's and thus we consider them, not the values of the corresponding numbers). Now for every suitable collection of size k there should be no outgoing edge to other set in $G_{2}$ (otherwise the numbers included in the sets of the collection will be k plus the additional few numbers from the corresponding outgoing edges and the collection will not be suitable - more numbers than sets). Thus our problem has been transformed to the following equivalent: in an oriented graph with weight of vertices find subset S of the vertices with minimum sum of weights and without outgoing edge with other end not in S. This problem is known to be equivalent to finding minimum cut (I wasn't able to prove the equivalence, didn't know it by heart either, but I found it even easier to prove if I consider the task as just max flow). Assign to the edges of $G_{2}$ infinite weights, add additional vertices $s$ and $t$,. Now for every set $u_{i}$ with weight $w$ add edge $u_{i}  \\rightarrow  t$ with weight $w$ iff $w > 0$ and edge $s  \\rightarrow  u_{i}$ with weight $- w$ iff $w < 0$. The part of the minimum cut of s and t in the constructed graph that contains s is the sought optimal collection (in fact what I did was sum the outgoing weights from s after computing max flow in the graph; I was able to prove this is the required number)",
    "tags": [
      "flows",
      "graph matchings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "104",
    "index": "A",
    "title": "Blackjack",
    "statement": "One rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!\n\nWhy not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.\n\nIn Mainframe a standard pack of $52$ cards is used to play blackjack. The pack contains cards of $13$ values: $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$, $10$, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from $2$ to $10$ points, correspondingly. An ace can either earn $1$ or $11$, whatever the player wishes. The picture cards (king, queen and jack) earn $10$ points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals $n$, then the player wins, otherwise the player loses.\n\nThe player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals $n$.",
    "tutorial": "Obviously, suits are not change the answer. Look at all possible situations: [0 - 10] - zero ways. [11] - four ways using aces. [12 - 19] - four ways using cards from 2 to 9. [20] - 15 ways, they are described in statement. [21] - four ways using aces. [22 - 25] - zero ways. Complexity is $O(1)$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "105",
    "index": "A",
    "title": "Transmigration",
    "statement": "In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills.\n\nUnfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration.\n\nTransmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life.\n\nAs a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the $k$ coefficient (if the skill level was equal to $x$, then after transmigration it becomes equal to $[kx]$, where $[y]$ is the integral part of $y$). If some skill's levels are \\textbf{strictly less} than $100$, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to $0$.\n\nThus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible.\n\nYou are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be?",
    "tutorial": "In this problem you should do just that is written in the statement. At the first you should read all skills and multiply all levels of them by koefficient $k$. Next you should drop all skills which have level less than 100. After that you should add all new skills from the second list but only those thah are not present in the second list. At the end you should sort all skills by thier names and output them.",
    "tags": [
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "105",
    "index": "B",
    "title": "Dark Assembly",
    "statement": "Dark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed.\n\nThe Dark Assembly consists of $n$ senators. Each of them is characterized by his level and loyalty to the player. The level is a positive integer which reflects a senator's strength. Loyalty is the probability of a positive decision in the voting, which is measured as a percentage with precision of up to $10%$.\n\nSenators make decisions by voting. Each of them makes a positive or negative decision in accordance with their loyalty. If \\textbf{strictly more} than half of the senators take a positive decision, the player's proposal is approved.\n\nIf the player's proposal is not approved after the voting, then the player may appeal against the decision of the Dark Assembly. To do that, player needs to kill all the senators that voted against (there's nothing wrong in killing senators, they will resurrect later and will treat the player even worse). The probability that a player will be able to kill a certain group of senators is equal to $A / (A + B)$, where $A$ is the sum of levels of all player's characters and $B$ is the sum of levels of all senators in this group. If the player kills all undesired senators, then his proposal is approved.\n\nSenators are very fond of sweets. They can be bribed by giving them candies. For each received candy a senator increases his loyalty to the player by $10%$. It's worth to mention that loyalty cannot exceed $100%$. The player can take no more than $k$ sweets to the courtroom. Candies should be given to the senators \\textbf{before} the start of voting.\n\nDetermine the probability that the Dark Assembly approves the player's proposal if the candies are distributed among the senators in the optimal way.",
    "tutorial": "Solution of this problem is search maximum for all cases of sweets' distribution. Common count of the distributions is $C_{k + n - 1}^{n - 1}$, thah id always no mare than 6435. Let us define as current some distribution and calculate values $z_{i} = min(l_{i} + c_{i}  \\times  0.1, 1.0)$, where $z_{i}$ is probability that $i$-th senator vote \"yes\", $l_{i}$ is loyality of senator and $c_{i}$ is number of candies that we should give $i$-th senator. Now you can calculate propability of success in $O(2^{n}n)$. You should iterate ovel all masks of length $n$. 1-bits mean that corresponding senators vote \"yes\", 0-bits means that ones vote \"no\". Probability that this mask happen is $m_{mask} =  \\Pi (z_{i}  \\times  [i - thsenatorvote\"yes\"] + (1 - z_{i})  \\times  [i - thsenatorvote\"no\"])$, where [true] = 1 and [false] = 0. Now for every mask you should find propability that player's proposal will be approved. It is $s_{mask} = 1$ if number of votes \"yes\" more than half of $n$ and $s_{mask} = A / (A + B)$ it other case, where $B$ is the sum of levels of senators that voted \"no\". So, propability for current distribution is $\\sum_{m a s k}s_{m a s k}\\times p_{m a s k}$. Solution has complexity $O(C_{k + n - 1}^{n - 1}2^{n}n)$.",
    "tags": [
      "brute force",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "105",
    "index": "C",
    "title": "Item World",
    "statement": "Each item in the game has a level. The higher the level is, the higher basic parameters the item has. We shall consider only the following basic parameters: attack (atk), defense (def) and resistance to different types of impact (res).\n\nEach item belongs to one class. In this problem we will only consider three of such classes: weapon, armor, orb.\n\nBesides, there's a whole new world hidden inside each item. We can increase an item's level travelling to its world. We can also capture the so-called residents in the Item World\n\nResidents are the creatures that live inside items. Each resident gives some bonus to the item in which it is currently located. We will only consider residents of types: gladiator (who improves the item's atk), sentry (who improves def) and physician (who improves res).\n\nEach item has the size parameter. The parameter limits the maximum number of residents that can live inside an item. We can move residents between items. Within one moment of time we can take some resident from an item and move it to some other item if it has a free place for a new resident. We cannot remove a resident from the items and leave outside — any of them should be inside of some item at any moment of time.\n\nLaharl has a certain number of items. He wants to move the residents between items so as to equip himself with weapon, armor and a defensive orb. The weapon's atk should be largest possible in the end. Among all equipping patterns containing weapon's maximum atk parameter we should choose the ones where the armor’s def parameter is the largest possible. Among all such equipment patterns we should choose the one where the defensive orb would have the largest possible res parameter. Values of the parameters def and res of weapon, atk and res of armor and atk and def of orb are indifferent for Laharl.\n\nFind the optimal equipment pattern Laharl can get.",
    "tutorial": "There you can see that if at least one item has empty slots then you can redistribute the residents in any order. This assertion can be easily proved. In other case you cannot move residents. Yet another thing that you can see here. In the optimal equipment all items have maximal possible paremeters. Moreover this items with thier residents do not affect each other. So, you can split all items and all residents by thier classes and types and three times solve same problem for groups (weapon, gladiators), (armor, senrties), (orbs, physicians). So, there are 2 cases: you cannot move residents and you can move ones. 1. For every item you should find its paremeter considering residents that are living inside it. After thah you should choose item that have maximal parameter. 2. Here you should sort all residents by desreasing its bonuses. Next you should iterate over all items, try put maximal count of strongest residents and calculate resulting value of parameter. Now you shouls choose item that have maxumal parameter. In the second case some catch exists. In the three choosen items you can have more empty slots than you had at the beginning of moving. It is impossible because you cannot drop residents. Therefore you should, for example, put as most as posiible unused residents into empty slots of three choosen items.",
    "tags": [
      "brute force",
      "implementation",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "105",
    "index": "D",
    "title": "Entertaining Geodetics",
    "statement": "The maps in the game are divided into square cells called Geo Panels. Some of these panels are painted. We shall assume that the Geo Panels without color are painted the transparent color.\n\nBesides, the map has so-called Geo Symbols. They look like pyramids of different colors (including Geo Symbols of the transparent color). Each Geo Symbol is located on one Geo Panel, and each Geo Panel may contain no more than one Geo Symbol.\n\nGeo Symbols can be eliminated. To understand better what happens when a Geo Symbol is eliminated, let us introduce some queue to which we will put the recently eliminated Geo Symbols.\n\nLet's put at the head of the queue a Geo Symbol that was eliminated just now. Next, we will repeat the following operation:\n\nExtract the Geo Symbol from the queue. Look at the color of the panel containing the given Geo Symbol. If it \\textbf{differs from transparent} and differs from the color of the Geo Symbol, then all Geo Panels of this color are repainted in the color of the given Geo Symbol (transparent Geo Symbols repaint the Geo Panels transparent). Repainting is executed in an infinite spiral strictly in the following order starting from the panel, which contained the Geo Symbol:\n\nIn other words, we select all the panels that need to be repainted and find their numbers in the infinite spiral whose center is placed in the position of the given Geo Symbol. After that, we repaint them in the order of the number's increasing.\n\nIf a panel contains another Geo Symbol and this panel is being repainted, then the Geo Symbol is removed from the field and placed at the tail of the queue.\n\nAfter repainting the Geo Symbol is completely eliminated and the next Geo Symbol is taken from the head of the queue (if there is any) and the process repeats. The process ends if the queue is empty.\n\nSee the sample analysis for better understanding.\n\nYou know the colors of all the Geo Panels and the location of all the Geo Symbols. Determine the number of repaintings, which will occur if you destroy one of the Geo Symbols.",
    "tutorial": "This problem can be solved by data structure like disjoint set union (dsu) with compression paths heuristic. Every vertex of dsu is geo-panel and every connected component is the set of one-colored geo-panels. All important information stores in the leader of component. It is size of group (count of geo-panels in it), its color and list of geo-symbols in this group that not destroyed. You should create queue that described in the statement. There you should store geo-symbols. Every symbol is color and position of map where this symbol was placed. Also yoy should create associative array (like std::map in c++), that returns leader of group in dsu by color of this group. At last you should create array with size $2n  \\times  2m$ and store in it path of infinite spiral. This array you can use for easily sorting geo-symbols before putting its into queue. This system of data structures allows fast emulate all process. So, let put the first geo-symbol into queue, generate spiral array and set dsu and associative array into initial state. Now you can do following operations while queue is not empty: You should remove geo-symbol from front of queue. Let call it current geo-symbol. By its coordinates using dsu you can find group in which current geo-symbol is placed. Next you should compare colors of group and geo-symbol and understand this group should be repainted or not. If group should be repainted you should add size of its group to global answer. After that you should sort all geo-symbols in this group using spiral array. In this order you should insert these geo-symbols into back of queue and clear list of qeo-symbols in the group. Now you should repaint group and replace associative array. You can see that some situation can happen. Now you can have two groups with equal colors (you can fast know it using associative array). These groups chould by united. You should set parent of group that you this moment repainted the second group and increase size of the second group by size of first group. You can prove that this algorithm works in $O(nmlognm)$.",
    "tags": [
      "brute force",
      "dsu",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "105",
    "index": "E",
    "title": "Lift and Throw",
    "statement": "You are given a straight half-line divided into segments of unit length, which we will call positions. The positions are numbered by positive integers that start with $1$ from the end of half-line, i. e. $1$, $2$, $3$ and so on. The distance between the positions is the absolute difference between the respective numbers.\n\nLaharl, Etna and Flonne occupy some positions on the half-line and they want to get to the position with the largest possible number. They are originally placed in different positions.\n\nEach of the characters can perform each of the following actions \\textbf{no more than once}:\n\n- Move a certain distance.\n- Grab another character and lift him above the head.\n- Throw the lifted character a certain distance.\n\nEach character has a movement range parameter. They can only move to free positions, assuming that distance between those positions doesn't exceed the movement range.\n\nOne character can lift another character if the distance between the two characters equals $1$, and no one already holds that another character. We can assume that the lifted character moves to the same position as the person who has lifted him, and the position in which he stood before becomes free. A lifted character cannot perform any actions and the character that holds him cannot walk.\n\nAlso, each character has a throwing range parameter. It is the distance at which this character can throw the one lifted above his head. He can only throw a character to a free position, and only when there is a lifted character.\n\nWe accept the situation when one person grabs another one who in his turn has the third character in his hands. This forms a \"column\" of three characters. For example, Laharl can hold Etna while Etna holds Flonne. In this case, Etna and the Flonne cannot perform any actions, and Laharl can only throw Etna (together with Flonne) at some distance.\n\nLaharl, Etna and Flonne perform actions in any order. They perform actions in turns, that is no two of them can do actions at the same time.\n\nDetermine the maximum number of position at least one of the characters can reach. That is, such maximal number $x$ so that one of the characters can reach position $x$.",
    "tutorial": "At the beginning you should estimate maximal answer what you can get. It equals 42. This answer you can get from following obvious maximal test: 8 10 10 9 10 10 10 10 10 Common number of states in which character can be without regard to position is 8. 2 for moved/not-moved multiply to 4 for nobody-lifted/lifted-A/lifted-B/already-threw. Total number of states is $(8 * 42)^{3} = 37933056$. This count of states can be easily stored in memory. Solution is DFS or BFS from initial state. Maximal position in reached states is answer.. Why it fits into time limits? In fact you can do about 60 moves from every state. Point is that most of states will be not reached. For example, following heuristics confirm it: 1. If one character is lifted by another one, thier positions are equal. 2. States where one characher lifted by both anothers are incorrect. 3. In positions with big numbers no more than 2 characters can be. In positions with very big numbers no more than 1 character can be. Also from more states possible little number of moves. They are states in which some characrers already moved or already threw somebody. You can find exact number of moves only after writing solution. Run on the maxtest shows that number of moves about $2  \\times  10^{8}$. So, this solution fits into time limits. You should just accuracy write it.",
    "tags": [
      "brute force"
    ],
    "rating": 2500
  },
  {
    "contest_id": "106",
    "index": "A",
    "title": "Card Game",
    "statement": "There is a card game called \"Durak\", which means \"Fool\" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly — you can find them later yourselves if you want.\n\nTo play durak you need a pack of $36$ cards. Each card has a suit (\"S\", \"H\", \"D\" and \"C\") and a rank (in the increasing order \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\" and \"A\"). At the beginning of the game one suit is arbitrarily chosen as trump.\n\nThe players move like that: one player puts one or several of his cards on the table and the other one should beat each of them with his cards.\n\nA card beats another one if both cards have similar suits and the first card has a higher rank then the second one. Besides, a trump card can beat any non-trump card whatever the cards’ ranks are. In all other cases you can not beat the second card with the first one.\n\nYou are given the trump suit and two different cards. Determine whether the first one beats the second one or not.",
    "tutorial": "Solution of this problem is written in the fourth paragraph of the statements. You should carefully read and implement it. Only one difficult part is how to to determine which card has higher rank. You can for every card iterate over array [ '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ] and determine numbers of ranks in this array. Finally, just compare them.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "106",
    "index": "B",
    "title": "Choosing Laptop",
    "statement": "Vasya is choosing a laptop. The shop has $n$ laptops to all tastes.\n\nVasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.\n\nIf all three properties of a laptop are \\textbf{strictly less} than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.\n\nThere are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.",
    "tutorial": "You can create array for all laptops where true for outdated laptop and false otherwise. Value of every cell of this array you can determine by iterating over all laptops and comparing all their parameters. At the end you should itarate over all laptops once again and choose cheapest one that is not outdated.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "106",
    "index": "C",
    "title": "Buns",
    "statement": "Lavrenty, a baker, is going to make several buns with stuffings and sell them.\n\nLavrenty has $n$ grams of dough as well as $m$ different stuffing types. The stuffing types are numerated from 1 to $m$. Lavrenty knows that he has $a_{i}$ grams left of the $i$-th stuffing. It takes exactly $b_{i}$ grams of stuffing $i$ and $c_{i}$ grams of dough to cook a bun with the $i$-th stuffing. Such bun can be sold for $d_{i}$ tugriks.\n\nAlso he can make buns without stuffings. Each of such buns requires $c_{0}$ grams of dough and it can be sold for $d_{0}$ tugriks. So Lavrenty can cook any number of buns with different stuffings or without it unless he runs out of dough and the stuffings. Lavrenty throws away all excess material left after baking.\n\nFind the maximum number of tugriks Lavrenty can earn.",
    "tutorial": "Let create array dp by size n x m. dp[i][j] means maximum number of tugriks that the baker can earn if he used i grams of dough and cook buns with stuffings of types 1..j. Initially dp[i][0] is 0 for all i. You can easily calculate this dp: dp[i][j] = max{ dp[i-c[j]*k][j-1] + d[j]*k } for every k from 0 to a[j]/b[j], for which i-c[j]*k>=0 The answer will be max{ dp[k][m] + ((n-k)/c0)*d0 } for every k from 0 to n. Of course, all divisions in editorial of this problem are integer. Solution works in O(nma), where a is maximum a_i.",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "106",
    "index": "D",
    "title": "Treasure Island",
    "statement": "Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map.\n\nThe treasure map can be represented as a rectangle $n × m$ in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks.\n\nBesides, the map also has a set of $k$ instructions. Each instruction is in the following form:\n\n\"Walk $n$ miles in the $y$ direction\"\n\nThe possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried.\n\nUnfortunately the captain doesn't know the place where to start fulfilling the instructions — as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares.\n\nThe captain wants to know which sights are worth checking. He asks you to help him with that.",
    "tutorial": "Solution is simulation of all insrtuctions from all of local sights. But naive solution doesn't fit into time limit. You should speed up this solution and do every instruction in O(1). You can use one of following things. 1. For every position and every direction you can precalculate nearest position of sea. Now before than you do an instruction you should check that nearest position of sea further than position whereto you move after doing the instruction. 2. Let sea cells have 1 and all other ones have 0. For every cell (i,j) you can calculate sum of all cells in the rectangle with angles in (1,1) and (i,j). It can be done by the operations like: sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + smth where smth is 0 or 1 according to type of according cell (i,j). Now you can determine sum of numbers for all rectangles of the map. Before you do instruction you should chech that sum of rectangle on which you will go has sum 0. Solution has complexity O(nm + kz), where z is number of local sights (this number no more than 26).",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "106",
    "index": "E",
    "title": "Space Rescuers",
    "statement": "The Galaxy contains $n$ planets, there are many different living creatures inhabiting each planet. And each creature can get into troubles! Space rescuers know it perfectly well and they are always ready to help anyone who really needs help. All you need to do is call for them.\n\nNow the space rescuers plan to build the largest in the history of the Galaxy rescue station; however, the rescue station's location is yet to be determined. As some cases are real emergencies, the rescuers want to find such a point in the Galaxy from which it would be possible to get to the remotest planet in the minimum possible time. In other words, the rescuers need such point in the space that the distance between it and the planet remotest from it was minimal (if we compare this point with all other possible points in the space). Unfortunately, the rescuers can't sole this problem.\n\nAs the planets are quite remote from each other, they can be considered as points in Euclidean three-dimensional space. The distance between points $(x_{i}, y_{i}, z_{i})$ and $(x_{j}, y_{j}, z_{j})$ can be calculated by the formula $p={\\sqrt{(x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2}+(z_{i}-z_{j})^{2}}}$. The rescue station can be positioned in any point in the space. It can also coincide with some planet.\n\nGalaxy is in danger! Save the space rescuers and find the required point for them.",
    "tutorial": "Author's solution is three ternary search for every demension that are nested within each other. It works because the function is convex. Maximum of convex functions also convex function. Author not very well imagine convex function in 3 dimrnsions, therefore you can read following proof that algorithm is correct: Let consider some straight line. Function of distance between points on this line and planet position will be convex (you can imagine it). If you get maximum of such functions it will be convex function too. Let's call this function f1. Now let's consider flat plane and choose one straight line in it. Set for every point of this line a minumum of function f1 of line that passes through this point and is perpendicular to choosen line. Let's call function on this choosen line f2. f2 is convex. It can be easily proved by contrary. If f2 is not convex, we can find at least two local minimums. Let's choose two neighbour of them. We can find this two minimums on the plane and drawn through them new line. f1 on this line will be not convex (you also can imagine it). Contradiction. Now let's consider all space. Choose one line in it and define function f3 on it. Values of f3 will be minimums of functions f2 of planes that passes through the line and is perpendicular to it. f3 also is convex. Proof of it is analogically to that is written in the previous paragraph. [] Now you can see that minimum can ge found by three ternary search over functions fi. You can add to these functions returning of value in which they reach a minimum. Also there are solutions that uses idea of Gradient descent or Hill climbing. Author was unable to write this solution (not enough precision), but some participants got AC with such solutions. There is exact solution O(n^4) (more exactly O(C_n^4)). This solution uses Helly's theorem and Jung's theorem that follows from the first one: http://en.wikipedia.org/wiki/Helly's_theorem In this solution you should itarate over all pairs, triples and fours of points and for every of them build minimal ball that cover them. Answer is center of ball with maximum radius. Also you can google something like that http://www.inf.ethz.ch/personal/gaertner/miniball.html There are code and article, but the author of contest is not particularly delved into them))",
    "tags": [
      "geometry",
      "ternary search"
    ],
    "rating": 2100
  },
  {
    "contest_id": "107",
    "index": "A",
    "title": "Dorm Water Supply",
    "statement": "The German University in Cairo (GUC) dorm houses are numbered from $1$ to $n$. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).\n\nFor each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.\n\nIn order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.",
    "tutorial": "The problem describes a graph of houses as nodes and one-way pipes as edges. The problem states that the graph will contain $1$ or more chains of nodes. The required is to find the start and end of every chain (consisting of more than $1$ node, which caused many hacks). The other requirement was to find the weakest edge in each of the chains. This can be done by traversing (using Depth-First Search (DFS) for example) the graph from each un-visited node with no incoming edges. These nodes are the $start$ of a chain. By keeping track of the $minimum$ $diameter$ so far, whenever the DFS reaches a node with no outgoing edges, it means that this node is the $end$ of the current chain. After storing, in a list or vector, the tuples $(start, end, minimum$ $diameter)$, we sort these tuples by start index and print.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1400
  },
  {
    "contest_id": "107",
    "index": "B",
    "title": "Basketball Team",
    "statement": "As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC).\n\nA team is to be formed of $n$ players, all of which are GUC students. However, the team might have players belonging to different departments. There are $m$ departments in GUC, numbered from $1$ to $m$. Herr Wafa's department has number $h$. For each department $i$, Herr Wafa knows number $s_{i}$ — how many students who play basketball belong to this department.\n\nHerr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department.\n\nNote that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.",
    "tutorial": "This problem is asking for the probability. Consider two sets of teams: the set of teams where Herr Wafa is the only student from his major and the set where at least one other student from Herr Wafa's major is present. These two sets don't intersect, so once we can compute the number of teams in the first set, A, and the number of teams in the second set, $B$, the answer would be $B / (A + B)$. The number of teams in the first set is A = $C((\\sum s[i],i\\neq h),n-1)$. We subtract one as Herr Wafa is guaranteed the spot, and the other $(n - 1)$ spots are to be taken by the remaining $(\\sum s[i],i\\neq h)$ students. Now let's count the number of teams having exactly $k$ students from Herr Wafa's major apart from him. This number would be $F(k)=C(s[h]-1,k)*C((\\sum s[i],i\\neq h),n-(k+1))$. Much like for the first set, $(n - (k + 1))$ students from the other majors should he selected, and none of them should be from Herr Wafa's major. The total number of teams where at least one other student is from Herr Wafa's major is therefore $B=\\textstyle\\sum_{k=1}^{s(h)-1}F(k)$. The statements above describe the mathematical solution. It can be implemented in various ways.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 1600
  },
  {
    "contest_id": "107",
    "index": "C",
    "title": "Arrangement",
    "statement": "In the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far.\n\nThe most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall.\n\nTraditionally GUC has $n$ professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from $1$ to $n$, with $1$ being the most senior professor and $n$ being the most junior professor.\n\nThe ceremonial hall has $n$ seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, $m$ pairs of seats are in \"senior-junior\" relation, and the tradition requires that for all $m$ pairs of seats $(a_{i}, b_{i})$ the professor seated in \"senior\" position $a_{i}$ should be more senior than the professor seated in \"junior\" position $b_{i}$.\n\nGUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that:\n\n- The seating of the professors changes every year.\n- Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall.\n- Each consecutive year lexicographically next arrangement of the professors is used.\n\nThe arrangement of the professors is the list of $n$ integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc.\n\nGiven $n$, the number of professors, $y$, the current year and $m$ pairs of restrictions, output the arrangement of the professors for this year.",
    "tutorial": "The problem asks for finding the lexicographically $n$-th permutation satisfying the input constraints. The trick which confused many contestants, as well as a few authors and testers, is that instead of having the restrictions formulated in a way $position[a[i]] < position[b[i]]$ the restrictions were element at position[a[i]] < element at position[b[i]]. As in most problems where one has to output lexicographically $n$-th answer, the idea which can result in the solution which is passing the systests is to learn how to compute the number of solutions satisfying certain constraints. We will speak about how to compute the number of solutions in a bit, but first let's understand how having such function would lead to a solution. The very first observation is: if the total number of possible solutions is less than $y - 2000$, then the answer is \"The times have changed\". Once we have ensured that the solution exists it can be found using some of search. A simple approach would be the following: fix the first element of the resulting permutation to be $1$ and count the number of possible solutions. If we do have enough to reach year $y$, then the first element must be $1$, because there exists enough permutations with the first element being $1$ to cover the years up to $y$, and any permutation where the first element is not $1$ comes after any permutation where the first element is $1$ in lexicographical order. And if fixing the first element to be $1$ is not giving enough permutations, then we should decrease the \"desired\" year by the number of solutions with $1$ being fixed as the first element and start looking for the solutions with $2$ as the first element. The intuition is that there are not enough solutions with $1$ being the first element, but once we acknowledge that and start looking for the other solutions --- with $2$ as the first element, we are speaking not about arrangements for years 2001 and onwards but about the years 2001 + number of solutions with first element being one and onwards. Therefore instead of looking for the permutation with index $y - 2001$ with the first element being $1$ we are looking for the permutation with the lower index, y - 2001 - number of solutions with first element being one, with the first element being $2$ or higher. This process should be continued until all the elements are identified. Once the first index is fixed the known prefix would become a two-numbers prefix, and it will grow until all the permutation is constructed. Now to complete the solution we need to be able to compute the number of permutations which satisfy two restrictions: the input constraints and the added \"permutation has prefix P\" constraint. This problem can be solved using DP. For a given prefix P of length m, (n-m) other elements should be placed. Assume first that we are going to be iterating over all possible permutations with the given prefix using the brute force, but, instead of trying each possible value for the element at the next empty position i, we would be trying each possible position for the next not-yet-placed element i. This approach would work, but in $O((n - m)!)$ time, which is obviously unfeasible. We need to find some way to reduce the state space and make it run faster. The key observation is the following: the state of the partially solved problem can be completely described by the bitmask of the currently occupied positions. This statement is nontrivial, as, from the first glance, it seems that apart from the unused positions mask, the information about the order, in which the already-placed elements are placed, is important. However it's not. Recall that all the constraints have the form of \"element at position $a_{i}$ is less than the element at position $b_{i}$\". Provided the elements are placed in increasing order, in order to satisfy each constraint it's enough to confirm that, if the element to be placed is being put into position i, there is no such constraint in the input, that the element at position i should be less than the element at position j, while the element at position j has already been placed. This approach results in the DP with $2^{n - m}$ states. Note that the next element to be placed can always be determined by the number of bits set in the mask and the prefix elements. The implementation of the above algorithm requires nontrivial coding, as the elements, belonging to the prefix, have to be treated differently compared to the elements which were placed by the DP. This is because the DP is enforcing that the elements are always added in the increasing order, which does not have to be the case for the elements conducting the prefix.",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "107",
    "index": "D",
    "title": "Crime Management",
    "statement": "Zeyad wants to commit $n$ crimes in Egypt and not be punished at the end. There are several types of crimes. For example, bribery is a crime but is not considered such when repeated twice. Therefore, bribery is not considered a crime when repeated an even number of times. Speeding is a crime, but is not considered such when repeated a number of times which is a multiple of five.\n\nMore specifically, $c$ conditions on crime repetitions are known. Each condition describes the crime type $t_{i}$ and its multiplicity $m_{i}$. If the number of times Zeyad committed the crime $t_{i}$ is a multiple of $m_{i}$, Zeyad will not be punished for crime $t_{i}$. Some crimes may be listed more than once. In this case fulfilling at least one condition for this crime is enough to not be punished for it. Of course, if for certain crime the number of times Zeyad committed it is zero, he is innocent with respect to this crime.\n\nNow Zeyad is interested in a number of ways he can commit exactly $n$ crimes without any punishment.\n\nThe order of commiting the crimes matters. More formally, two ways, sequences $w1$ and $w2$, of committing $n$ crimes are equal if $w1_{i} = w2_{i}$, for all $1 ≤ i ≤ n$.",
    "tutorial": "At the first glance the upper limit for $n$ being $10^{18}$ looks huge. But in fact, combined with the fact, that the answer should be output modulo $12345$, it's should not scare you but rather hint that the problem has a DP approach. Like all DP problems the way to approach it is to split the problem into sub-problems and figure out what extra information should be carried between the sub-problems in order to combine them into the solution to the whole problem. Say, $n$ is $11$ and we solved the problem for the first $10$ crimes. Clearly, just the number of ways to commit the first $10$ crimes is not enough to solve the full problem with $n = 11$. The extra information to be carried along with the number of ways to commit n crimes and be innocent is the following: the number of ways to commit the first $n$ crimes and have remaining multiplicities $d_{1}, d_{2}, ...d_{26}$ respectively. The fact that the product of the multiplicities does not exceed $123$ makes this a solvable task, as the set of all possible remainders contains not more elements than the product of multiplicities. To illustrate the idea from the first paragraph consider the first example case. It has two constraints, A with multiplicity $1$ and B with multiplicity $2$. The remainder of the number of crimes of type A is always zero, and committing crimes of type A may not yield any punishment. The remainder of the number of crimes of type B is zero or one. Therefore, while solving the sub-problems for the first $n2 < = n$ crimes, it's enough to keep track of only two numbers: \"number of ways to commit $n2$ crimes and be completely innocent\" and \"number of ways to commit $n2$ crimes and have committed one 'extra' crime of type B\". The key step to solve the problem now is to notice that each transition from the solution for the first $k$ crimes to the solution for the first $(k + 1)$ crimes can be seen as multiplying the vector of the current state by the transition matrix. Once all possible transitions are converted to the matrix form, the problem can be solved by raising the matrix into n-th power. Raising the matrix into large power can be done efficiently using matrix exponentiation: on some steps instead of computing $A_{i + 1} = A_{i} \\cdot  A_{0}$ one can compute $A_{2i} = A_{i} \\cdot  A_{i}$. The last trick of this problem is to deal with multiple allowed multiplicities. If they were not allowed, the remainders per each crime type could have been kept with the modulo being equal to the multiplicity for this crime type. Moreover, if no crime type is listed more than once, the only valid final state is the state where the remainders are zero across all the crime types. With multiple allowed multiplicities, for each crime type the remainder modulo the product of the multiplicities of crimes for this type should be kept. (Strictly speaking, LCM is enough, but the constraints allow to use the plain product instead). Then, at the stage of printing the output, instead of treating the counter for the state with zero remainders as the only contributor to the output, one would have to iterate through all possible states and verify if each set of remainders conducts a valid final state.",
    "tags": [
      "dp",
      "graphs",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "107",
    "index": "E",
    "title": "Darts",
    "statement": "The night after the graduation ceremony graduate students of German University in Cairo (GUC) are playing darts. As there's no real dart board available, the photographs of members of the GUC upper management are being used.\n\nSo, $n$ rectangular photos are placed on the wall. They can overlap arbitrary and even coincide. The photos are not necessarily placed horizontally or vertically, they could also be rotated before being pinned to the wall.\n\nThe score of one dart throw is simply the number of photos the dart went through.\n\nFatma has made a throw but her score was not recorded. She only remembers that she did make it into at least one photo.\n\nAssuming that the probability distribution of the throw is equal across the whole wall, what would be the expectation of Fatma's score?",
    "tutorial": "Before doing the coding let's do some math. The answer to this problem can be computed as the total area of all input rectangles / the area of the union of all input rectangles. One of the easy ways to understand it is the following. First notice that if all the rectangles are the same, the answer is always the number of rectangles. Now forget that the input figures are rectangles, assume any shape is allowed, and then try to construct the example case given the union area $s$ and the resulting expected score $e$. Notice that you can start with any shape constructed of non-intersecting figures with the total area $s$, and then add more figures on top of these, such that the contour of the union is the same as the contour of the first original figure of area $s$. Specifically, you'd need to add some figures of the total sum of $t = s \\cdot  (e - 1)$, but the number doesn't matter here. The key is that the placement of these added figures doesn't change the result, and therefore the answer will always depend only on the total area of the input figures and the area of their union. Now back to the rectangles. Computing the sum of the ares of the rectangles is easy. The hard part is to compute the area of their union in better than $O(n^{3})$. Note that the union may have multiple disjoins components, it does not have to be convex, it may have holes and, in short, does not have to be easy to describe. One of the relatively-easy-to-implement solutions is the following. We will be computing the are of the union of the rectangles using the trapezoid method. Note that for the trapezoid method the order, in which the segments of the figure are provided, doesn't matter. Therefore, in order to use the trapezoid method, we \"only\" need to find all non-vertical directed segments which are the part of the contour of the union. Let me elaborate a bit more on the previous paragraph. We don't need vertical segments, because their contribution to the resulting area is zero in the trapezoid method of computing the area. The direction of the segment is the important part though. It's not enough to know that the segment $(x1, x2) - (y1, y2)$ belongs to the contour of the union. It's important to know whether the area of the union if the part of the plane above it or below it. Imagine the test case where the union of all the rectangles is a big rectangle with a hole inside it. In this case we need to know that the segments, describing the outer part of the union, should contribute to the area with the \"plus\" sign, while the segments describing the inner hole should be considered with the \"minus\" sign. Specifically, for the trapezoid method, the sign of $x2 - x1$ would be describing the direction of this segment: for example, if $x1 < x2$ than the segment is \"positive\" and if $x1 < x2$ it's \"negative\". To find all such segments let's consider all distinct non-vertical lines. There are at most $4n$ such lines in the input. Each segment of the final contour of the union should lay on one of those lines, so it's enough to focus on the lines only, consider them independently from each other (but make sure to process each distinct line only once!) and for each line construct a set of the positive and negative segments. Let's formulate the rules under which a part of the line would be a positive or negative segment. They turn out to be very simple: 1) If some segment $(x1, y1) - (x2, y2)$ is part of the border of one of the input rectangles, then it's a \"positive\" segment if this input rectangle lays below this segment and a \"negative\" segment if this rectangle lays above this segment. 2) If some segment $(x1, y1) - (x2, y2)$ belongs to the intersection of the borders of two different input rectangles, with one being a \"positive\" one and one being a \"negative\" one, then this segment does not belong to the contour. 3) If some segment $(x1, y1) - (x2, y2)$ is being covered by another rectangle, then it does not belong to the contour. \"Covered\" means laying completely inside some other rectangle, the border cases are covered above. The easy way of constructing all the segments could look as the following pseudo-code: for each distinct non-vertical line create the array of markers. the marker holds the x coordinate and one of four events: { start union area below, end union area below, start union area above, end union area above }. iterate through all the input rectangles if this rectangle has one segment laying on the line under consideration add two markers: one for start and one for end. whether the markers are above or below is determined by the position of this rectangle with respect to this line else if this rectangle intersects this line find the intersection points and add four markers: { start area below } and { start area above } for the left intersection point and { end area below } and { end area above } for the right intersection point sort the array of markers by the x coordinate of the events traverse the array of markers. if some segment $(x1..x2)$ is being reported as having the union area only above it or only below it, it becomes the negative or positive segment of the union respectively. At this point one could run some sort of DFS to merge the segments into the connected loops, but this is actually unnecessary to compute the area using the trapezoid method. Just summing up $(x2 - x1) \\cdot  (y1 + y2) / 2$ for all the segments does the trick, and it would automatically ensure that the outer contours are taken with the positive sign and the inner contours are taken with the negative sign. The solution described above runs in $O(n^{2} \\cdot  logn)$ : for each of $O(n)$ lines we have at most $O(n)$ intersections, which should be sorted in $O(n \\cdot  logn)$ inside the loop over all the lines.",
    "tags": [
      "geometry",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "108",
    "index": "A",
    "title": "Palindromic Times",
    "statement": "\\underline{Tattah is asleep if and only if Tattah is attending a lecture.} This is a well-known formula among Tattah's colleagues.\n\nOn a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome.\n\nIn his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment.\n\nHowever, he still hasn't mastered the skill of programming while sleeping, so your task is to help him.",
    "tutorial": "In this problem it was required to find next palindrome on a digital clock. Since the lowest unit of time used $1$ minute, and there are only $24 * 60$ minutes in a day, one could simply go through each minute starting from the time given in the input plus $1$ minute, until finding a palindrome. If no palindrome is found till the end of the day $23: 59$, the output should then be $00: 00$.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "108",
    "index": "B",
    "title": "Datatypes",
    "statement": "Tattah's youngest brother, Tuftuf, is new to programming.\n\nSince his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava.\n\nToday, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has $n$ unsigned integer datatypes of sizes (in bits) $a_{1}, a_{2}, ... a_{n}$. The $i$-th datatype have size $a_{i}$ bits, so it can represent every integer between $0$ and $2^{ai} - 1$ inclusive.\n\nTuftuf is thinking of learning a better programming language. If there exists an integer $x$, such that $x$ fits in some type $i$ (in $a_{i}$ bits) and $x·x$ does not fit in some other type $j$ (in $a_{j}$ bits) where $a_{i} < a_{j}$, then Tuftuf will stop using Gava.\n\nYour task is to determine Tuftuf's destiny.",
    "tutorial": "Let us call a pair of datatypes $(a, b)$, where $a < b$, BAD if and only if there exists a number $x$ where $x$ fits in $a$ bits but $x * x$ does not fit in $b$ bits. The following observation helps in finding a solution to the problem. The best candidate for the number $x$ is the largest number fitting in $a$ bits, which is $x = 2^{a} - 1$. So for each $a_{i}$ it is enough to check that the smallest $a_{j}$ > $a_{i}$ has enough bits to contain $x * x = (2^{a} - 1) * (2^{a} - 1)$, which has at most $2 * a$ bits. Sorting the numbers first was needed to traverse the list of datatypes once and ensuring the condition above.",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "109",
    "index": "A",
    "title": "Lucky Sum of Digits",
    "statement": "\\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya wonders eagerly what minimum lucky number has the sum of digits equal to $n$. Help him cope with the task.",
    "tutorial": "Let result number contains $a$ digits $4$ and $b$ digits $7$. Obviously, that $a * 4 + b * 7 = n$. Loop through all values of $b$. If we know $b$, we can calculate $a$, $a={\\frac{n-b x7}{4}}$. Among all pairs $(a;b)$ we need to choose one with $a + b$ minimum. Among all that pairs we need to choose one with $b$ minimum. Output will be an integer $444...444777...777$, here number of digits $4$ equal to $a$, number of digits $7$ equal to $b$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "109",
    "index": "B",
    "title": "Lucky Probability",
    "statement": "\\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya and his friend Vasya play an interesting game. Petya randomly chooses an integer $p$ from the interval $[p_{l}, p_{r}]$ and Vasya chooses an integer $v$ from the interval $[v_{l}, v_{r}]$ (also randomly). Both players choose their integers equiprobably. Find the probability that the interval $[min(v, p), max(v, p)]$ contains exactly $k$ lucky numbers.",
    "tutorial": "Let $L[i]$ - $i$-th lucky number, starting from 1 ($L[0] = 0$, $L[1] = 4$, $L[2] = 7$...). At first choose first $k$ lucky number, then second $k$ numbers and so on. For each of that group lets find answer, result will be a sum of each of this probabilities. Let index of current first number if $i$, last - $j$ ($j = i + k - 1$). Then we need to find intersection of intervals $[p_{l};p_{r}]$ and $(L[i - 1];L[i]]$, and also $[v_{l};v_{r}]$ and $[L[j];L[j + 1])$, product of that values will be a number of ways in which $p < v$, similarly for $p > v$. Sum of all that values for each group will be a total number of ways, then result = total number of ways / $((p_{r} - p_{l} + 1) * (v_{r} - v_{l} + 1))$.",
    "tags": [
      "brute force",
      "probabilities"
    ],
    "rating": 1900
  },
  {
    "contest_id": "109",
    "index": "C",
    "title": "Lucky Tree",
    "statement": "\\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nOne day Petya encountered a tree with $n$ vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a \\underline{tree with $n$ vertexes} is an undirected connected graph that has exactly $n - 1$ edges.\n\nPetya wondered how many vertex triples $(i, j, k)$ exists that on the way from $i$ to $j$, as well as on the way from $i$ to $k$ there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple $(1, 2, 3)$ is not equal to the triple $(2, 1, 3)$ and is not equal to the triple $(1, 3, 2)$.\n\nFind how many such triples of vertexes exist.",
    "tutorial": "Solve this problem using dynamic programming. Consider that root of a tree is vertex with number 1. Let $F(x)$ - number of vertex in subtree of vertex $x$ for which there is a path containing lucky edge. We will calculate $F(x)$ using recursion. If $x$ is a leaf, than $F(x) = 0$. Else, if there is an edge from $x$ that leads to $y$ and this edge is lucky, then to $F(x)$ we need to add $C(y)$, otherwise we add $F(y)$, here $C(y)$ - number of vertex in subtree of $y$, including $y$. But, to solve this problem we need to know also $F'(x)$ - number of vertex which are not in subtree of $x$ and there exits a path from $x$ to that vertex that contains lucky edge. For a root of tree, $F'(x)$ equals to $0$. We should go recursive from root, and if we are in vertex $x$ now, we suppose that $F'(x)$ is already calculated. If from $x$ we can directly go to $y$ and that edge is lucky, then $F'(y) = C(0) - C(y)$, otherwise $F'(y) = F'(x) + F(x) - F(y)$. After that, result equals to $\\textstyle{\\sum_{i=1}^{n}F(i)*(F(i)-1)+F^{\\prime}(i)*(F^{\\prime}(i)-1)+2*F(i)*F^{\\prime}(i)}$.",
    "tags": [
      "dp",
      "dsu",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "109",
    "index": "D",
    "title": "Lucky Sorting",
    "statement": "\\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya got an array consisting of $n$ numbers, it is the gift for his birthday. Now he wants to sort it in the non-decreasing order. However, a usual sorting is boring to perform, that's why Petya invented the following limitation: one can swap any two numbers but only if at least one of them is lucky. Your task is to sort the array according to the specified limitation. Find any possible sequence of the swaps (the number of operations in the sequence should not exceed $2n$).",
    "tutorial": "At first, if our array is already sorted, just return $0$. Otherwise, if there is no lucky number in $A$, then output $- 1$. Otherwise, let $B$ is sorted $A$ (array from input). Now, for all numbers in $A$ we know a final position in $B$. Let $k$ is an index of minimal lucky number in $A$. If we want to place integer from position $i$ to $j$, we need $A[j]$ to be lucky number. If is not so, we just $Swap(A[j], A[k])$, then $A[j]$ contains lucky number. After that we can $Swap(A[i], A[j])$ and number $A[i]$ is on position $j$. So, to place one number to it's position in $B$, we need at most two operations and total number that replacements will be not more than $n$, so answer'll contain at most $2n$ operations.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "109",
    "index": "E",
    "title": "Lucky Interval",
    "statement": "\\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nOne day Petya came across an interval of numbers $[a, a + l - 1]$. Let $F(x)$ be the number of lucky digits of number $x$. Find the minimum $b$ $(a < b)$ such, that $F(a)$ = $F(b)$, $F(a + 1)$ = $F(b + 1)$, ..., $F(a + l - 1)$ = $F(b + l - 1)$.",
    "tutorial": "That is only onw variation of solution, there are diffrent other, which uses same thinking. With constraints for $a$ and $b$ to $10^{7}$ problem can be solved using KMP algorithm: consider a string $F(1)F(2)F(3)F(4)...F(3 * 10^{7})$. We need to find first occurrence after index $a$ of string $F(a)F(a + 1)F(a + 2)...F(a + l - 1)$. Complexity of that algorithm is $O(a + l)$, obviously, that fails on time and memory. Lets try to optimize this algorithm using some facts from \"Lucky numbers theory\". Split all number interval on block with sizes $100$: $[0;99]$, $[100;199]$ and so on. Introduce a concept \"class of block\". Class number of a block equals to $F(i / 100)$, where $i$ - any number from that block. There are $8$ different block classes. There are at most $6$ consecutive blocks with same class. All that can be seen using brute force. Note #1: if $l  \\ge  1000$, then $(b-a)\\mod100=0$. Proof: consider a string $F(100 * k)F(100 * k + 1)...F(100 * k + 99)$. Number of different that strings is equal to number of different classes. For example, for first class that string looks like this: $00001001000000100100000010010000001001001111211211000010010000001001001111211211$ 00001001000000100100 for second: $11112112111111211211111121121111112112112222322322111121121111112112112222322322$ 11112112111111211211 and so on. According to the structure of that strings, different block (by classes) can't intersect (there'll be no match). Hence, any sequence of of consecutive blocks which contain at least two blocks of different classes will match only with the same sequence, so shift will be multiple of $100$. Since there is no more than $6$ consecutive blocks with the same classes, if $l  \\ge  1000$ then, obviously, this interval will contain at least two blocks with different classes. So, problem with $l  \\ge  1000$ can be solved using KMP with complexity $O((a + l) / C)$, where $C$ equals $100$, let function that do that is named $Solve(l, r)$. Now we need to solve problem for $l < 1000$. At first, let $a'$ is minimal number that $F(a') = F(a)$, $F(a' + 1) = F(a + 1)$, ..., $F(a' + l - 1) = F(a + l - 1)$, $a' / 100 = a / 100$, that can be done using brute force. Then result is the minimum of next numbers: - $r = Solve(a', a' + l - 1)$; - Minimum $r'$, for which $r - r' < = 1000$, $r' > a$, $F(r') = F(a)$, $F(r' + 1) = F(a + 1)$, ..., $F(r' + l - 1) = F(a + l - 1)$. - Minimum $a''$ for which $a'' > a$, $a'' - a  \\le  1000$ and $F(a'') = F(a)$, $F(a'' + 1) = F(a + 1)$, ..., $F(a'' + l - 1) = F(a + l - 1)$. That solves the problem of some non-100-multiple shifts, but that may be a doubt. Consider input interval is in just one block with class $C$. Then, probably, it is better to go to block with class $C + 1$, for example $(397;1)  \\rightarrow  (400;1)$. Actually, second point solves that problem, because if block with class $C + 1$ is before $C$ (and only in that case we will choose $C + 1$), then next block after current have class $C + 1$. To proof this we can use this note (which can be proofed using brute forces): Note #2: if there is two consecutive block, then absolute difference between they classes is not more then $1$. Hence, if after block $C$ (in which input interval is) goes block with class $C - 1$, then we will go to block $C$ before $C + 1$, otherwise we will choose it ($C$ or $C + 1$). Thus, problems solves by accurate analysis all moments. Complexity of solution is $O((A + L) / 100)$, my solution works $1.5$ sec. and use $250$ mega bytes of memory. There are also solution which decompose of blocks with sizes depentding on $l$, that one work faster.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "110",
    "index": "A",
    "title": "Nearly Lucky Number",
    "statement": "\\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nUnfortunately, not all numbers are lucky. Petya calls a number \\underline{nearly lucky} if the number of lucky digits in it is a lucky number. He wonders whether number $n$ is a nearly lucky number.",
    "tutorial": "In this problem you just need to find a number of lucky digits in $n$ and output $YES$ if it number is equal to $4$ or $7$, $NO$ otherwise.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "110",
    "index": "B",
    "title": "Lucky String",
    "statement": "\\underline{Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in $26$ lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two \\textbf{adjacent} numbers is a lucky number.\n\nFor example, let's consider string \"zbcdzefdzc\". The lists of positions of equal letters are:\n\n- b: $2$\n- c: $3, 10$\n- d: $4, 8$\n- e: $6$\n- f: $7$\n- z: $1, 5, 9$\n- Lists of positions of letters a, g, h, ..., y are empty.\n\nThis string is lucky as all differences are lucky numbers. For letters z: $5 - 1 = 4$, $9 - 5 = 4$, for letters c: $10 - 3 = 7$, for letters d: $8 - 4 = 4$.\n\nNote that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.\n\nFind the lexicographically minimal lucky string whose length equals $n$.",
    "tutorial": "To solve this problem you need to notice that result is a prefix of string $abcdabcdabcd...abcd$ and output first $n$ characters of this string.",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "111",
    "index": "A",
    "title": "Petya and Inequiations",
    "statement": "Little Petya loves inequations. Help him find $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$, such that the following two conditions are satisfied:\n\n- $a_{1}^{2} + a_{2}^{2} + ... + a_{n}^{2} ≥ x$\n- $a_{1} + a_{2} + ... + a_{n} ≤ y$",
    "tutorial": "It is easy to see that in order to maximize the sum of squares, one should make all numbers except the first one equal to 1 and maximize the first number. Keeping this in mind we only need to check whether the given value of y is large enough to satisfy a restriction that all n numbers are positive. If y is not to small, then all we need is to ensure that $x  \\le  1 + 1 +  \\dots  + (y - (n - 1))^{2}$",
    "tags": [
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "111",
    "index": "B",
    "title": "Petya and Divisors",
    "statement": "Little Petya loves looking for numbers' divisors. One day Petya came across the following problem:\n\nYou are given $n$ queries in the form \"$x_{i}$ $y_{i}$\". For each query Petya should count how many divisors of number $x_{i}$ divide none of the numbers $x_{i - yi}, x_{i - yi + 1}, ..., x_{i - 1}$. Help him.",
    "tutorial": "Let's create an array used[], j-th element of which will be the index of the last number from the input, which is divisible by j. Then for each query we'll iterate over all divisors of xi and for each k, which divides xi we'll check whether it is \"unique\". After that we'll update used[k].",
    "tags": [
      "binary search",
      "data structures",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "111",
    "index": "C",
    "title": "Petya and Spiders",
    "statement": "Little Petya loves training spiders. Petya has a board $n × m$ in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to some of the four side-neighboring cells (that is, one command for each of the four possible directions). Petya gives the commands so that no spider leaves the field. It is allowed for spiders to pass through each other when they crawl towards each other in opposite directions. All spiders crawl simultaneously and several spiders may end up in one cell. Petya wants to know the maximum possible number of spider-free cells after one second.",
    "tutorial": "This problem has many different approaches. One of them uses the fact that the overall number of possible inputs is small and it is possible to compute the answer manually for all of them. One could also write a brute-force with a few optimizations, which works even without a precalc. However, the major part of all solutions involved dynamic programming with bitmasks. The solution below was described by Zlobober. Instead of counting the maximal number of free cells, we'll count the minimal number of occupied cells. We'll assume that the number of rows is not greater than 6 (otherwise we can rotate the board). Let D[k][pmask][mask] be the minimal number of occupied cells in the first k columns with the restrictions that the k-th column is described by pmask (ones correspond to occupied cells and zeroes correspond to free cells) and k+1-st column is described by mask. To make a transition from D[k-1][*][*] we can iterate over all possible masks for the k-1-st column, check whether we can distribute spiders in kth column knowing the masks for k+1-st and k-1-st columns and find the minimal value of D[k-1][*][pmask] for all such masks. The overall complexity is O(n*23m), n > m.",
    "tags": [
      "bitmasks",
      "dp",
      "dsu"
    ],
    "rating": 2100
  },
  {
    "contest_id": "111",
    "index": "D",
    "title": "Petya and Coloring",
    "statement": "Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size $n × m$ ($n$ rows, $m$ columns) in $k$ colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.",
    "tutorial": "One can notice that if $m = 1$ then the answer is kn, because all colorings are possible. Now we'll assume that m > 1. Let's look on the first column of the board (i.e. the vertical cut will be made right next to the first column). Suppose there are x distinct colors in this column. Then in the rest of the board there are also x colors. If we move the vertical line by one unit to the right, the number of different colors to the left of it will not decrease and the number of colors to the right of it won't increase. It means that the number of different colors in both parts of the board will be also x. We can repeat this process until the line reaches the rightmost column, which means that the number of distinct colors in it is also x. It is easy to see that we can only use colors which belong to the intersection of sets of colors in the leftmost and rightmost columns in the rest of the board. Let's iterate over all values of x and y, where x is the number of colors in the leftmost column and y is the number of elements in intersection of sets of colors in the rightmost and leftmost columns. It is easy to see that x is limited by the number of rows in the board and y can't be greater than x. Let's find the answer for all such pairs of x and y and at the end we'll add them up together. Suppose x and y are fixed. We first need to choose (2x - y) colors from the given k colors, which we will use, which means that the answer for will be multiplied by C(k, 2x - y). After that we'll choose (x-y) unique colors which will be used in the first column, which means that the answer will be also multiplied by C(2x-y, x-y). Then we'll choose x-y colors for the rightmost column and multiply the answer by C(x, x-y). Now all we need to know is how many ways of coloring n cells into x colors are there. We'll use a dynamic programming approach to solve this sub-problem. Let d[i][j] be the number of ways to color a rectangle of unit width and length i into colors, numerated from 1 to j with the following restriction: if a < b then the first appearence of color a in the rectangle will be before the first appearence of color b. Then we can calculate this function using the following recurrence: d[i][j] = j * d[i - 1][j] + d[i - 1][j - 1]. After we finish calculating d[i][j], we need to multiply the answer by d[n][x]2 (to color the first and the last columns). Now we need to notice that we can reorder all colors in the first and the last columns in arbitrary way, which means that the answer should be multiplied by (x!)2. Finally, we need to multiply the answer by yn(m-2), which correspond to coloring the rest of our board. Some contestants had problems with time limit, because of calculation of C(N,K). One can notice that we won't need more than 2000 colors, which reduces the time significantly. Author's solution worked less than 200ms with the time-limit of 5s.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "111",
    "index": "E",
    "title": "Petya and Rectangle",
    "statement": "Little Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells $n × m$ in size (containing $n$ rows, $m$ columns). Petya marked two different cells of the rectangle and now he is solving the following task:\n\nLet's define a \\underline{simple path} between those two cells as a sequence of distinct cells $a_{1}, a_{2}, ..., a_{k}$, where $a_{1}$ and $a_{k}$ are the two marked cells. Besides, $a_{i}$ and $a_{i + 1}$ are side-neighboring cells of the path ($1 ≤ i < k$). Let's denote the path length as number $k$ (the sequence length).\n\nPetya's task is to find the longest simple path's length and to print the path. Help him.",
    "tutorial": "Let the length of the maximal path be S. First, we'll estimate the value of S without specifying the longest path itself. Let's color our board into a chess-coloring. Obviously, each two neighboring cells in the path will have different color. Keeping this in mind we can make some estimation on the value of S. For example, if there are 4 white cells and 5 black cells on the board and we know that both starting and ending cells are white, than the length of the path can't be greater than 7, because white and black cells must alternate in the path. It appears that for the constraints mentioned in the statement, this theoretical bound for S is always achievable. All we need is to find the path of the length S. Author solution divides the board into 5 pieces and solves the problem for each piece separately. Let's divide the board into 5 parts as it was shown on the first picture. We'll assume that the relative location of the starting and ending cells is the same as on the picture. In each part we'll try to build a longest path which completely belongs to it. For the first part we'll try to build a path from the upper-right corner to the upper-left corner. Similar rules will hold for all other parts (see the picture above for further clarification). Paths can be different for different boards, but they will have similar structure. One can notice that there are only two types of paths (with respect to rotations of the board): the one which starts at the upper-left corner and ends at the bottom-right corner and the one which starts at the upper-left corner and ends at the upper-right corner. Now we can write down an algorithm: 1) Divide the board into 5 parts. 2) Find the longest path in each of the parts. 3) Check if the total length is equal to S. 4) If the above is false, then rotate or reflect the board and continue to the step 1. In order to find the longest path in a particular part, one can either consequently move through all rows of the part or through all its columns. This solution gives correct answers for all $4  \\le  n, m  \\le  20$. All possible cases of parity of each part are feasible within those constraints, which means that the solution will work for all boards, including ones with n > 20 or m > 20. The overall complexity of described algorithm is O(N*M).",
    "tags": [],
    "rating": 2900
  },
  {
    "contest_id": "112",
    "index": "A",
    "title": "Petya and Strings",
    "statement": "Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings \\underline{lexicographically}. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.",
    "tutorial": "In this problem one could transform all letters in both strings to lower case and then compare the strings lexicographically.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "112",
    "index": "B",
    "title": "Petya and Square",
    "statement": "Little Petya loves playing with squares. Mum bought him a square $2n × 2n$ in size. Petya marked a cell inside the square and now he is solving the following task.\n\nThe task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any common points with the marked cell and the resulting two parts should be equal \\textbf{up to rotation}.\n\nPetya wants to determine whether it is possible to cut the square in the required manner given the sizes of the square side and the coordinates of the marked cell. Help him.",
    "tutorial": "One can notice that if we want to divide a square into two equal parts, then the cutting line should pass through the center of our square. Thus, if the marked cell contains the center of the square, then we can't make a cut, otherwise we can.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "113",
    "index": "A",
    "title": "Grammar Lessons",
    "statement": "Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:\n\n- There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.\n- There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.\n- Masculine adjectives end with -lios, and feminine adjectives end with -liala.\n- Masculine nouns end with -etr, and feminime nouns end with -etra.\n- Masculine verbs end with -initis, and feminime verbs end with -inites.\n- Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.\n- It is accepted that the whole word consists of an ending. That is, words \"lios\", \"liala\", \"etr\" and so on belong to the Petya's language.\n- There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.\n- A sentence is either exactly one valid language word or exactly one statement.\n\nStatement is any sequence of the Petya's language, that satisfy both conditions:\n\n- Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.\n- All words in the statement should have the same gender.\n\nAfter Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.",
    "tutorial": "This task is an example of task that requires accurate realization. After reading the statement one can understand that we have to check whether the text from input represents exactly one correct sentence or no. If yes, therefore the text can be either a single word from our language or a following structure: {zero or non-zero count of adjectives} -> {a single noun} -> {zero or non-zero count of verbs}, and moreover, all these words should have equal gender. So, to check these facts, one can do the following: We count number of words. If this number is equal to 1, we check this word for being a valid word from our language. Otherwise, we can get gender of the first word, and iterate through the rest of the words validating existing of only one noun and order of these words. Also, while iterating we check the gender of each word for being equal to the gender of the first word.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "113",
    "index": "B",
    "title": "Petr#",
    "statement": "Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the $s_{begin}$ and ending with the $s_{end}$ (it is possible $s_{begin} = s_{end}$), the given string $t$ has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him!",
    "tutorial": "Let's find all occurrences of begin and end. Then we'll map the whole string to number 0. After this we will simply add one symbol per iteration to already seen sub-strings and map new strings to some non-negative integers. One can notice that we will never reach a situation when more then 2000 different strings exist, so we can map them easily. Now, as per we know all the ends and beginnings of strings and different string of equal length are mapped to different numbers ( and equal strings are mapped equally), we can simply count the number of necessary sub-strings of certain length. So, we have time complexity $O(N^{2}LogN)$, since we are making $N$ iterations and each is done in O($NLogN$) time.",
    "tags": [
      "brute force",
      "data structures",
      "hashing",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "113",
    "index": "C",
    "title": "Double Happiness",
    "statement": "On the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number $t$ is his lucky number, if it can be represented as:\n\n\\[\nt = a^{2} + b^{2},\n\\]\n\nwhere $a, b$ are arbitrary positive integers.Now, the boys decided to find out how many days of the interval $[l, r]$ ($l ≤ r$) are suitable for pair programming. They decided that the day $i$ ($l ≤ i ≤ r$) is suitable for pair programming if and only if the number $i$ is lucky for Peter and lucky for Bob at the same time. Help the boys to find the number of such days.",
    "tutorial": "In this task one have to find quantity of prime numbers that can be reproduced as sum of two perfect squares. Obviously, that $4k + 3$ prime numbers are not suitable as sum of two perfect squares can not be equal to 3 (of course, modulo 4). So, we can prove or use the well-known fact ( also known as Fermat theorem), that every odd $4k + 1$ prime number is a sum of two perfect squares. Also, we have not to forget about 2, as $2 = 1^{2} + 1^{2}$. Now, how can we get this task accepted? Simply using the sieve will exceed memory limit, but we can use block sieve, that works in the same time ($O(N\\log\\log N)$), but uses $O({\\sqrt{N}})$ of memory. Also, we can use precalc for intervals of length equal to 100000. Also, Romka used the fact, that using bitset compress memory up to 8 times, and it will enough to suite the ML. Also, it would be nice to count only odd numbers while buliding the sieve.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "113",
    "index": "D",
    "title": "Museum",
    "statement": "One day as Petya and his friend Vasya were having one of their numerous trips, they decided to visit a museum castle. The museum has a specific shape: it consists of $n$ rooms connected with $m$ corridors so that one can access any room from any other one.\n\nAfter the two friends had a little walk around the museum, they decided to split and watch the pieces of art each of them found interesting. They agreed to meet in one of the rooms at six p.m. However, they forgot one quite essential thing: they didn't specify the place to meet and when the time came, they started to rush about the museum looking for each other (they couldn't call each other as roaming made a call's cost skyrocket).\n\nYet, even despite the whole rush, they couldn't get enough of the pieces of art, that's why each of them has the following strategy: each minute he make a decision where to go — with probability $p_{i}$ he doesn't move to any other place during this minute (i.e. he stays in the room). With probability $1 - p_{i}$ he equiprobably choose one of the adjacent rooms and went there along the corridor. Here $i$ is the ordinal number of the current room. Building was expensive in ancient times, that's why each corridor connected two different rooms, and any two rooms had no more than one corridor between them.\n\nThe boys act simultaneously. As the corridors are dark, it is impossible to meet there; however, one can walk along the corridors in both directions (besides, the two boys can be going through the same corridor simultaneously without meeting). The boys act like that until they meet each other. More formally, the two friends meet when at some moment of time both of them decided to appear in the same room.\n\nFor each room find the probability that the boys will meet there considering that at 6 p.m. they are positioned in rooms $a$ and $b$ correspondingly.",
    "tutorial": "Let's consider a pair (i, j) as a state - this means that now Petya is in room i, and Vasya is in room j. Therefore, their meeting is state (i, i) for some i. So, it's quite easy to build transition matrix - this means that for each state (i, j) we will know probability of reaching state (x, y) in one step, where $1  \\le  i, j, x, y  \\le  n$. Also, from meeting state we can reach only the same state. Let's try to solve such a problem - what is the probability of meeting in the first room? We build system of linear algebraic equations: $p_{(i,j)}=\\sum_{o v e r\\ a l l\\;t h e\\ r e a c h a b l e\\ s t a t e s\\ (x,y)}a_{(i,j),(x,y)}p_{(x,y)}$, where $a_{(i, j), (x, y)} -$ probability of transition from state (i,j) to state (x,y). One can notice that $p_{(1, 1)} = 1$, and $p_{(i, i)} = 0$ when $i  \\neq  1$, and the answer will be $p_{(a, b)}$. This system can be easily solved using Gauss method. Similarly we can solve such a problem for every room (considering that we will meet in certain room), but we have complexity O($n^{7}$), that will not pass time limit. But, after some observations, we now see that each time we are solving system $Ax = b$ (and the only thing that is changing $-$ is vector b). So, we can solve matrix equation $Ax = b$, where b is a matrix with dimensions $n^{2} * n$, and the answer will be in the row that corresponds to state (a, b) . With this approach we have time complexity O($n^{6}$), that will pass time limit.",
    "tags": [
      "math",
      "matrices",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "113",
    "index": "E",
    "title": "Sleeping",
    "statement": "One day Vasya was lying in bed watching his electronic clock to fall asleep quicker.\n\nVasya lives in a strange country, where days have $h$ hours, and every hour has $m$ minutes. Clock shows time in decimal number system, in format H:M, where the string H always has a fixed length equal to the number of digits in the decimal representation of number $h - 1$. To achieve this, leading zeros are added if necessary. The string M has a similar format, and its length is always equal to the number of digits in the decimal representation of number $m - 1$. For example, if $h = 17$, $m = 1000$, then time equal to 13 hours and 75 minutes will be displayed as \"13:075\".\n\nVasya had been watching the clock from $h_{1}$ hours $m_{1}$ minutes to $h_{2}$ hours $m_{2}$ minutes inclusive, and then he fell asleep. Now he asks you to count how many times he saw the moment at which at least $k$ digits changed on the clock simultaneously.\n\nFor example, when switching 04:19 $ → $ 04:20 two digits change. When switching 23:59 $ → $ 00:00, four digits change.\n\nConsider that Vasya has been watching the clock for strictly less than one day. Note that the last time Vasya saw on the clock before falling asleep was \"h2:m2\". That is, Vasya \\textbf{didn't see} the moment at which time \"h2:m2\" switched to the next value.",
    "tutorial": "Let's consider function $F(x)$ (where $x$ is some moment of time) $-$ amount of moments from 0..00:00..00 up to $x$ (and $x$ doesn't switch to next moment ) when n $k$ or more digits will be changed . The answer will be $F(h2: m2) - F(h1: m1)$, also it's necessary not to forget that if $h2: m2 < h1: m1$, then $F(h2: m2)$ will be enlarged by a day. Now we will learn how to calculate $F(x)$. To start with, let's count amount of such numbers when hour will remain the same. As hour is not changing, then $k$ or more digits have to be changed in minutes, but in this case we need our number of minutes to be of the following form: $a..a99...9$, where $a$ means any digit,and at the end we have $k - 1$ nines. So k digits are changing every moment that is divisible by $10^{k - 1}$. So, the total amount of such moments (without changing an hour) is $J_{l.T}\\ *\\left[\\frac{m-1}{10^{k-1}}\\right]\\ +\\left[\\frac{m.c-1}{10^{k-1}}\\right]$, where$hx$ and $mx$ are numbers of hour and minute in time moment $x$, and [] is integer part. Now let's deal with such moments when hour is changing. If this happens, then minute turns from $m - 1$ to 0, and we have $y$ different digits, where $y$ is amount of non-zero digits of number $m - 1$. Therefore we have to count for hours ( in similar way) amount of moments, when $k - y$ or more digits will be changed. $k - y$ digits are changing every moment that is divisible by $10^{max(0, k - y - 1)}$, this means that total amount of such moments is $[\\frac{hx-1}{10^{max(0, k-y-1}}]$. And the final value of $F$ is $F(x)=h x*[\\frac{m-1}{10^{k-1}}]+[\\frac{m x-1}{10^{k-1}}]+[\\frac{h x-1}{10^{m a x(0,k-1)}}]$.",
    "tags": [
      "combinatorics",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "114",
    "index": "A",
    "title": "Cifera",
    "statement": "When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word \"tma\" (which now means \"too much to be counted\") used to stand for a thousand and \"tma tmyschaya\" (which literally means \"the tma of tmas\") used to stand for a million.\n\nPetya wanted to modernize the words we use for numbers and invented a word petricium that represents number $k$. Moreover, petricium la petricium stands for number $k^{2}$, petricium la petricium la petricium stands for $k^{3}$ and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.\n\nPetya's invention brought on a challenge that needed to be solved quickly: does some number $l$ belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.",
    "tutorial": "To solve this task, let's describe what is needed more formally. We should answer whether is number $l$ some positive degree of number $k$ or no. To answer this question we can proceed in 2 ways: 1) Using 64 bit data type, we can find minimal degree $h$ of number $k$, such that $k^{h}  \\ge  l$. If $k^{h} = l$, then the answer is $YES$, and number of articles is equal to $h - 1$. Otherwise, the answer is $NO$. 2) We will divide $l$ by $k$, until $k$ divides $l$ and $l  \\neq  1$. If $l = 1$, then the answer - $YES$ and number of articles is equal to $numberOfDivisions - 1$, and the answer is $NO$ otherwise.",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "114",
    "index": "B",
    "title": "PFAST Inc.",
    "statement": "When little Petya grew up and entered the university, he started to take part in АСМ contests. Later he realized that he doesn't like how the АСМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. — Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members.\n\nTo make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other.",
    "tutorial": "We can reformulate the statement more formally. In this case, we have a undirected graph, and we have to find some maximal clique in it. If we have a look to constraint $n  \\le  16$, then there can be noticed that we can iterate over all possbile subsets of vertices and find the answer. To do this, one can use bit masks and iterate from 0 to $2^{16}$, checking current subgraph for being a clique. Also, it's necessary not to forget about sorting the names while printing the answer.",
    "tags": [
      "bitmasks",
      "brute force",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "115",
    "index": "A",
    "title": "Party",
    "statement": "A company has $n$ employees numbered from $1$ to $n$. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee $A$ is said to be the \\underline{superior} of another employee $B$ if at least one of the following is true:\n\n- Employee $A$ is the immediate manager of employee $B$\n- Employee $B$ has an immediate manager employee $C$ such that employee $A$ is the superior of employee $C$.\n\nThe company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.\n\nToday the company is going to arrange a party. This involves dividing all $n$ employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees $A$ and $B$ such that $A$ is the superior of $B$.\n\nWhat is the minimum number of groups that must be formed?",
    "tutorial": "We let an employee without a manager called as root. There's an edge from a manager to an employee that he/she manages. First notice that the graph is a collection of directed trees. Hence, we can assign a depth label to each node - denoting the number of nodes on the simple path from the root to it. The answer is then the maximum depth a node has. Why? First, the answer is bounded below by this number because any pair of employees in this path cannot be in the same group. Second, since the graph is a tree, each node in the graph has a unique depth label assigned to it. Simply put all nodes with the same depth in the same group. It's fairly easy to see that no one will be the superior of another within a group, for otherwise their depths will not be equal.",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 900
  },
  {
    "contest_id": "115",
    "index": "B",
    "title": "Lawnmower",
    "statement": "You have a garden consisting entirely of grass and weeds. Your garden is described by an $n × m$ grid, with rows numbered $1$ to $n$ from top to bottom, and columns $1$ to $m$ from left to right. Each cell is identified by a pair $(r, c)$ which means that the cell is located at row $r$ and column $c$. Each cell may contain either grass or weeds. For example, a $4 × 5$ garden may look as follows (empty cells denote grass):\n\nYou have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell $(1, 1)$. At any moment of time you are facing a certain direction — either left or right. And initially, you face right.\n\nIn one move you can do either one of these:\n\n1) Move one cell in the direction that you are facing.\n\n- if you are facing right: move from cell $(r, c)$ to cell $(r, c + 1)$\n- if you are facing left: move from cell $(r, c)$ to cell $(r, c - 1)$\n\n2) Move one cell down (that is, from cell $(r, c)$ to cell $(r + 1, c)$), and change your direction to the opposite one.\n\n- if you were facing right previously, you will face left\n- if you were facing left previously, you will face right\n\nYou are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move.\n\nWhat is the minimum number of moves required to mow all the weeds?",
    "tutorial": "First, let's observe a particular strategy that turns out to be optimal at the end of our discussion. Suppose we're on a row, facing right. This strategy say that we need to move to the right as long as there is a weed to the right of us either on this row or on the row directly below us. The idea is that we need to mow that weed, hence, we need to move there. If it's in the same row as us, it's fairly obvious we have to mow that before going down. If it's at the row directly below us, since we can't move to the right in the row below us (since we'll be facing left there) we need to move there before going down. The strategy then says that if we no longer need to move right, we go down, and face left. Repeat this until all weeds are mowed (replacing left and right in the discussion above) - and we have our strategy. This strategy is optimal. Proof is using induction - but it's not particularly interesting, so the idea is given instead. Suppose we're on a row, facing right, again. If there exist a weed to the right in this row or below us, then any solution will necessarily move right as far as our strategy goes (for the reason we discussed above). Some solution however choose to go further right despite having no weed in this row or the row directly below us. This solution is not optimal if we need to go left directly after going down, for we can just simply go down instead of going right-down-left. On the other case, if we don't need to go left directly after going down, then it means that we go down twice-in-a-row! Hence, instead of moving right in this row, we go down twice, then move right there. And then the induction can continue and the proof can follow.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "115",
    "index": "C",
    "title": "Plumber",
    "statement": "Little John aspires to become a plumber! Today he has drawn a grid consisting of $n$ rows and $m$ columns, consisting of $n × m$ square cells.\n\nIn each cell he will draw a pipe segment. He can only draw four types of segments numbered from $1$ to $4$, illustrated as follows:\n\nEach pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment $1$ has ends at top and left side of it.\n\nLittle John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size $1 × 2$.\n\nNow, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling \\textbf{all} of the empty cells with pipe segments. Print this number modulo $1000003$ ($10^{6} + 3$).\n\nNote that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.",
    "tutorial": "To solve this problem, let's imagine that the left and top sides of the grid also determines whether the pipe adjacent to that side has an end connecting it to the side or not. There are 2^(N+M) ways to pick them. We claim that if we fix them (i.e., pick one of the possible 2^(N+M) ways, then the entire grid's pipes are fixed). To see this, notice that each pipe segment will have either one vertical end (it either have end on the top or end on the bottom) and one horizontal end (left or right). We can pick any 4 combinations of them. Suppose we pick a row, and determine whether the leftmost pipe should have an end to the left of it, or not. Suppose it doesn't have an opening to the left. It means that the leftmost pipe should have an opening to the right, the next pipe should have an opening to the left, the next pipe to the right, and so on. Continuing this way, we have fixed the horizontal ends for an entire row - and only that. Hence, if we pick one of the possible 2^(N+M) ways to pick the ends, then the horizontal ends of each row and vertical ends of each column is fixed. Since there is exactly one pipe segment that has a particular configuration of ends, there is exactly one possible completed grid for each of the 2^(N+M) ways to pick the ends. Hence, the solution works by first checking if a solution exists. Any pre-assigned pipe simply sets whether or not its corresponding row and column has an end at the left and top side. We need to check that no two pipes sets this value contradictorily. If any of them are contradictory, then we return the answer as 0. Otherwise, we return 2^(number of rows without preassigned cell + number of columns without preassigned cell).",
    "tags": [
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "115",
    "index": "D",
    "title": "Unambiguous Arithmetic Expression",
    "statement": "Let's define an unambiguous arithmetic expression (UAE) as follows.\n\n- All non-negative integers are UAE's. Integers may have leading zeroes (for example, $0000$ and $0010$ are considered valid integers).\n- If $X$ and $Y$ are two UAE's, then \"$(X) + (Y)$\", \"$(X) - (Y)$\", \"$(X) * (Y)$\", and \"$(X) / (Y)$\" (all without the double quotes) are UAE's.\n- If $X$ is an UAE, then \"$ - (X)$\" and \"$ + (X)$\" (both without the double quotes) are UAE's.You are given a string consisting only of digits (\"0\" - \"9\") and characters \"-\", \"+\", \"*\", and \"/\". Your task is to compute the number of different possible unambiguous arithmetic expressions such that if all brackets (characters \"(\" and \")\") of that unambiguous arithmetic expression are removed, it becomes the input string. Since the answer may be very large, print it modulo $1000003$ ($10^{6} + 3$).",
    "tutorial": "This problem is solved using Dynamic Programming. The somewhat straightforward dynamic programming is to represent the state as {start_pos, end_pos}, which represents the number of unambiguous arithmetic expression on the substring of the input starting at start_pos and ending at end_pos. This however has a complexity of O(N^3) and is not suitable for our problem. The solution uses the state {pos, braces}. This state is somewhat tricky to explain. This means that we have read the first pos characters in the input. We're expected to read a single unambiguous arithmetic expression, close it with some number of brackets that we don't care (to be explained below), and then, if braces is zero, that's it. Otherwise, we're then expected to read a binary operator (either + - * or /), then open a bracket, then move the state to {pos + some_value, braces-1}. That is, braces keeps track on the number of second operands of binary expression that we need to make. For an example how this works, let's try to solve a particular test case: \"++0*+1\" Let's denote with quotes the part of the input that we haven't processed. We're going to create the unambiguous arithmetic expression by scanning it left to right and making some choices. There are three choices: 1) Create a unary expression. In the example above, \"++0*+1\" -> +(\"+0*+1\" We don't really care about where the closing bracket is yet. 2) Create a binary expression. In the example above, +(\"+0*+1\" -> +((\"+0*+1\" How does this tells that we will need to create a binary expression? The second open bracket does not have any operator preceeding it. The only thing that can makes this a proper prefix of an unambiguous arithmetic expression is that if this bracket belongs to the first operand of a binary expression. For our example, we suppose we read another unary expression +((\"+0*+1\" -> +((+(\"0*+1\" 3a) Read an integer. In our example above, +((+(\"0*+1\" -> +((+(0))*(\"+1\" There are two questions. a) how do we know the number of closing brackets we have to make? This is actually easy - for every open bracket we have, if it's for a unary expression, we simply close and repeat. Otherwise it's a closing bracket for possibly the first operand to a binary expression, so we close it, and we read a binary operator (* in the example above), and try to read the second operand of the binary expression. Finally: +((+(0))*(\"+1\" -> +((+(0))*(+(\"1\" 3b) We try to read an integer again and we have no open brackets that belongs to the first operand of a binary expression, and we have ourself a possible answer. +((+(0))*(+(\"1\" -> +((+(0))*(+(1))) So, in the state {pos, braces}, pos determines the starting location of the remaining unprocessed input. braces indicates the number of open brackets that belongs to a binary expression. So, in the examples above: 1) \"++0*+1\" -> +(\"+0*+1\" is represented by {0, 0} -> {1, 0} More specifically, for unary expressions, {pos, braces} -> {pos+1, braces} 2) +(\"+0*+1\" -> +((\"+0*+1\" is represented by {1, 0} -> {1, 1} More specifically, for binary expressions, {pos, braces} -> {pos, braces+1} 3a) +((+(\"0*+1\" -> +((+(0))*(\"+1\" {2, 1} -> {4, 0} More specifically, {pos, braces} -> {pos + length_of_integer + 1, braces-1} 3b) +((+(0))*(+(\"1\" -> +((+(0))*(+(1))) {5, 0} -> Done More specifically, {pos, braces} -> done if braces is zero and the remaining input forms a single integer.",
    "tags": [
      "dp",
      "expression parsing"
    ],
    "rating": 2600
  },
  {
    "contest_id": "115",
    "index": "E",
    "title": "Linear Kingdom Races",
    "statement": "You are a car race organizer and would like to arrange some races in Linear Kingdom.\n\nLinear Kingdom has $n$ consecutive roads spanning from left to right. The roads are numbered from $1$ to $n$ from left to right, thus the roads follow in the order of their numbers' increasing. There will be several races that may be held on these roads. Each race will use a \\textbf{consecutive} subset of these roads. Also, each race will pay some amount of money to you if this race is held. No races overlap in time, so some roads can be used in several races.\n\nUnfortunately, some of the roads are in a bad condition and they need repair. Each road has repair costs associated with it, you are required to pay this cost to repair the road. A race can only take place if all the roads used in the race are renovated. Your task is to repair such roads (possibly all or none) that will maximize your profit. Your profit is defined as the total money you get from the races that are held minus the total money you spent to repair the roads. Note that you may decide not to repair any road and gain zero profit.\n\nPrint the maximum profit you can gain.",
    "tutorial": "We process the roads one by one. Associated with each road is the races whose UBi is that road (i.e., races that 'ends' at that road). We will discuss the Dynamic Programming solution first, then improve it with a data structure into the optimal solution. Let's say we're going to process a road. Our state is this : DP[X] is the maximum possible profit such that the last X roads before this road are fixed and the X+1-th road before this road is NOT fixed. We are going to compute the value of DP for the next iteration, let's call this FUTURE. FUTURE[0] is obtained if we don't fix this road, FUTURE[0] = maximum amongst the value of DP. Otherwise, if we decide to fix this road, then for each of DP[X], FUTURE[X+1] >?= DP[X] - cost to fix the road + all races' profit that ends at this road and whose starting point is not before X roads from current road (i.e., all the races that is contained and ends at this road). This should work in N^2 + N * M. It can be improved to N^2 + M The data structure approach is slightly different. We will use a segment tree that allows finding a maximum value in a subset and modifying the values of a range, all of which should work in either O(1) or O(log N). The segment tree will consist of N+1 leaves. However, not all the leaves are active at the start of the algorithm. At the start, only one leaf is active and it corresponds to the initial value of DP[0]. Next, we can compute the maximum value amongst all active leaves in O(log N). Then, we create a new active leaf that corresponds to FUTURE[0]. This will be located in the same tree however, the values represented by the leaves will be shifted one to the right - this is done implicitly (for example, we use the last node as DP[0] for the first iteration, but treat it as DP[1] for the next, and so on). These shifted values will correspond to FUTURE[X], since we notice that FUTURE[X] = DP[X-1] - cost to fix the road + races that this series contains and ends at this current road (i.e., it's value directly depends on the leaf BEFORE it was shifted). Next, we decrement the value of all these new leaves (except FUTURE[0]) by the cost to fix the road (in O(log N)). Finally, for each race that ends at this road, we increment the value of the leaves that contains this race. This will be continuous, i.e., FUTURE[X] for X in [race_len, INFINITY]. This can also be done in O(log N). Since a race ends at at most one road, the total complexity this will contribute is M log N. The answer will then simply the maximum value amongst all members of the tree.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "116",
    "index": "A",
    "title": "Tram",
    "statement": "Linear Kingdom has exactly one tram line. It has $n$ stops, numbered from $1$ to $n$ in the order of tram's movement. At the $i$-th stop $a_{i}$ passengers exit the tram, while $b_{i}$ passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.\n\nYour task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit \\textbf{before} any entering passenger enters the tram.",
    "tutorial": "If we know the number of people inside the tram at all possible time, then the answer is the maximum of such. We observe that the number of people inside the tram changes only at tram stops. The conclusion is that the answer will be the maximum of the number of people inside the tram directly before arriving at a particular stop and directly after leaving a particular stop (the more observant readers can notice that using only one of these is sufficient). It's sufficiently easy to calculate the number of people inside the tram directly before and after leaving a tram stop.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "116",
    "index": "B",
    "title": "Little Pigs and Wolves",
    "statement": "Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size $n × m$. Each cell in this grid was either empty, containing one little pig, or containing one wolf.\n\nA little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs.\n\nThey have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf.\n\nWhat is the maximum number of little pigs that may be eaten by the wolves?",
    "tutorial": "No... not maximum matching ;) So, an equivalent less-evil rewording of the problem would be: \"Return the number of wolves that are adjacent to at least one pig\". To see this, since each pig has at most one wolf adjacent to it (the constraints impose that) we don't need to worry at a single pig may get eaten by two different wolves. Hence, each wolf can eat any of the pig adjacent to it.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "117",
    "index": "A",
    "title": "Elevator",
    "statement": "And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All $n$ participants who have made it to the finals found themselves in a huge $m$-floored $10^{8}$-star hotel. Of course the first thought to come in a place like this is \"How about checking out the elevator?\".\n\nThe hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time $0$) the elevator is located on the $1$-st floor, then it moves to the $2$-nd floor, then — to the $3$-rd floor and so on until it reaches the $m$-th floor. After that the elevator moves to floor $m - 1$, then to floor $m - 2$, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.\n\nFor each of the $n$ participant you are given $s_{i}$, which represents the floor where the $i$-th participant starts, $f_{i}$, which represents the floor the $i$-th participant wants to reach, and $t_{i}$, which represents the time when the $i$-th participant starts on the floor $s_{i}$.\n\nFor each participant print the minimum time of his/her arrival to the floor $f_{i}$.\n\nIf the elevator stops on the floor $s_{i}$ at the time $t_{i}$, then the $i$-th participant can enter the elevator immediately. If the participant starts on the floor $s_{i}$ and that's the floor he wanted to reach initially ($s_{i} = f_{i}$), then the time of arrival to the floor $f_{i}$ for this participant is considered equal to $t_{i}$.",
    "tutorial": "Consider three cases. $s = f$, $ans = t$. $s < f$, we must find the smallest non-negative $k$ such, that $t  \\le  (s - 1) + 2(m - 1)k$. $ans = s - 1 + 2(m - 1)k + (f - s)$. $s > f$, similarly, we must find the smallest non-negative $k$ such, that $t  \\le  2(m - 1) - (s - 1) + 2(m - 1)k$. $ans = 2(m - 1) - (s - 1) + 2(m - 1)k + (s - f)$. We can find $k$ in any reasonable manner, for example, by using formulas of integer division.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "117",
    "index": "B",
    "title": "Very Interesting Game",
    "statement": "In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string $s_{1}$, consisting of exactly nine digits and representing a number that does not exceed $a$. After that second player looks at $s_{1}$ and writes a string $s_{2}$, consisting of exactly nine digits and representing a number that does not exceed $b$. Here $a$ and $b$ are some given constants, $s_{1}$ and $s_{2}$ are chosen by the players. The strings are allowed to contain leading zeroes.\n\nIf a number obtained by the concatenation (joining together) of strings $s_{1}$ and $s_{2}$ is divisible by $mod$, then the second player wins. Otherwise the first player wins. You are given numbers $a$, $b$, $mod$. Your task is to determine who wins if both players play in the optimal manner. If the first player wins, you are also required to find the lexicographically minimum winning move.",
    "tutorial": "Suppose, that the first player made a move $x  \\le  a$, then consider the remainder $rem = x \\cdot  10^{9}%mod$. Obviously, if $(mod - rem)%mod  \\le  b$, then the second player can win. Thus, we must iterate through all relevant values of $x$ (we don't need iterate through more than $mod$ values) and check whether the second player to win. If there exist a losing move for second player, then won the first, else second. Since we iterate through all relevant moves of the first player, then we can easily determine his winning move (if such move exist).",
    "tags": [
      "brute force",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "117",
    "index": "C",
    "title": "Cycle",
    "statement": "A \\underline{tournament} is a directed graph without self-loops in which every pair of vertexes is connected by exactly one directed edge. That is, for any two vertexes $u$ and $v$ ($u ≠ v$) exists either an edge going from $u$ to $v$, or an edge from $v$ to $u$.\n\nYou are given a tournament consisting of $n$ vertexes. Your task is to find there a cycle of length three.",
    "tutorial": "If the tournament has at least one cycle, then there exist a cycle of length three. A constructive proof. Find any cycle in the tournament by using any standard algorithm, such as depth-first search. If there is no cycle, then output -1, else choose any three consecutive vertices of the cycle $v_{1}$ $v_{2}$ $v_{3}$ ($A_{v1, v2} = A_{v2, v3} = 1$). Since given graph is a tournament, then there is an edge ($v_{3}$, $v_{1}$), or there is an edge ($v_{1}$, $v_{3}$). The first of these two cases, we find immediately the cycle of length three of the vertices $v_{1}$ $v_{2}$ $v_{3}$, the second, we can reduce the length of the loop (erase vertex $v_{2}$). We can reduce the length of the cycle until we find a cycle of length three.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "117",
    "index": "D",
    "title": "Not Quick Transformation",
    "statement": "Let $a$ be an array consisting of $n$ numbers. The array's elements are numbered from $1$ to $n$, $even$ is an array consisting of the numerals whose numbers are even in $a$ ($even_{i} = a_{2i}$, $1 ≤ 2i ≤ n$), $odd$ is an array consisting of the numberals whose numbers are odd in $а$ ($odd_{i} = a_{2i - 1}$, $1 ≤ 2i - 1 ≤ n$). Then let's define the transformation of array $F(a)$ in the following manner:\n\n- if $n > 1$, $F(a) = F(odd) + F(even)$, where operation \"$ + $\" stands for the arrays' concatenation (joining together)\n- if $n = 1$, $F(a) = a$\n\nLet $a$ be an array consisting of $n$ numbers $1, 2, 3, ..., n$. Then $b$ is the result of applying the transformation to the array $a$ (so $b = F(a)$). You are given $m$ queries $(l, r, u, v)$. Your task is to find for each query the sum of numbers $b_{i}$, such that $l ≤ i ≤ r$ and $u ≤ b_{i} ≤ v$. You should print the query results modulo $mod$.",
    "tutorial": "Imagine a recursion tree our transformation $F$. This tree is binary. We write on the edges leading into the left subtree, zero, and on the edges, leading to the right, one. Now consider the path of some number $a$ (hereafter, we assume that we substracted one from all numbers in the array over which we make the conversion). This path start in the root of the tree and end in some leaf, and numbers written on the edges of the path is exactly bit representation of $a$ in order from least significant bit to the most significant bit. Construct the recursive function which solve our problem, similar to how we carry out a query to the segment tree. Here is the prototype of this function. $solve(idx, tl, tr, l, r, u, v)$ This function returns the answer to the query $(l, r, u, v)$, if we consider only subtree with positions $[tl, tr]$, while on the path from the root to the subtree is written bit representation of $idx$. If $l  \\le  tl  \\le  tr  \\le  r$, then we calculate answer by formulae, else we divide our segment of positions and return sum of answers from left and right part. As described above, the answer to the whole subtree is a formula. Here you need to use the fact that all the numbers in the subtree have the form $k \\cdot  2^{depth} + idx$, where $depth$ - depth of subtree. We must find $k$ such, that $u  \\le  k \\cdot  2^{depth} + idx  \\le  v$ and then calculate the sum of appropriate numbers. Asymptotics of this solution $O(m \\cdot  log(n) \\cdot  (formulae - for - whole - subtree))$. We can calculate formulae for whole subtree in $O(logn)$.",
    "tags": [
      "divide and conquer",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "117",
    "index": "E",
    "title": "Tree or not Tree",
    "statement": "You are given an undirected connected graph $G$ consisting of $n$ vertexes and $n$ edges. $G$ contains no self-loops or multiple edges. Let each edge has two states: on and off. Initially all edges are switched off.\n\nYou are also given $m$ queries represented as $(v, u)$ — change the state of all edges on the shortest path from vertex $v$ to vertex $u$ in graph $G$. If there are several such paths, the lexicographically minimal one is chosen. More formally, let us consider all shortest paths from vertex $v$ to vertex $u$ as the sequences of vertexes $v, v_{1}, v_{2}, ..., u$. Among such sequences we choose the lexicographically minimal one.\n\nAfter each query you should tell how many connected components has the graph whose vertexes coincide with the vertexes of graph $G$ and edges coincide with the switched on edges of graph $G$.",
    "tutorial": "In this problem, suggested a solution using heavy light decomposition. Graph, given in problem statement, is a cycle, on which are suspended trees. For each tree construct the data structure (heavy light + segment tree), which can perform $change$ on the path from some vertex to any parent, and to maintain the amount of ones. The same structure we use for the cycle. Suppose, that we have no cycle, i.e. there is just a bunch of trees (forest). Then the amount of switched-on edges uniquely determines the number of connected components (each switched-on edge decrease the amount of components by one). Suppose, that we have only the cycle. Then, similarly, the amount of switched-on edges uniquely determines the number of connected components. We will maintain the amount of switched-on edges in the cycle and in the all trees. So, the answer to the problem $Comps_{cicle} + Comps_{trees} - Cnt_{Cicle}$, where $Comps_{cicle}$ - the amount of connected components in cycle, $Comps_{trees}$ - the amount of connected components in all trees, $Cnt_{Cicle}$ - the amount of vertexes in cycle.",
    "tags": [
      "data structures",
      "divide and conquer",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "118",
    "index": "A",
    "title": "String Task",
    "statement": "Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:\n\n- deletes all the vowels,\n- inserts a character \".\" before each consonant,\n- replaces all uppercase consonants with corresponding lowercase ones.\n\nVowels are letters \"A\", \"O\", \"Y\", \"E\", \"U\", \"I\", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.\n\nHelp Petya cope with this easy task.",
    "tutorial": "First problem only is realization. In need read input string, delete all uppercase and lowercase vowels letter and print answer.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "118",
    "index": "B",
    "title": "Present from Lena",
    "statement": "Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from $0$ to $n$ as the pattern. The digits will form a rhombus. The largest digit $n$ should be located in the centre. The digits should decrease as they approach the edges. For example, for $n = 5$ the handkerchief pattern should look like that:\n\n\\begin{verbatim}\n          0\n        0 1 0\n      0 1 2 1 0\n    0 1 2 3 2 1 0\n  0 1 2 3 4 3 2 1 0\n0 1 2 3 4 5 4 3 2 1 0\n  0 1 2 3 4 3 2 1 0\n    0 1 2 3 2 1 0\n      0 1 2 1 0\n        0 1 0\n          0\n\\end{verbatim}\n\nYour task is to determine the way the handkerchief will look like by the given $n$.",
    "tutorial": "Second problem is realization too. Good solution to calc count space in beginning of string. In handkerchief pattern there is 2 * n + 1 rows. In rows form 0 to N number of space is 2 * n - i. In rown number from N + 1 to 2 * N number of space is (I - N) * 2.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "118",
    "index": "C",
    "title": "Fancy Number",
    "statement": "A car number in Berland consists of exactly $n$ digits. A number is called beautiful if it has at least $k$ equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of $n$ digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.\n\nHelp Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.",
    "tutorial": "In this task it need to find a minimal sum that to find a beautiful number of car. So, there are only 10 available digits. Let us try the minimum cost to have one of those digits repeat at least K times and the lexicographically minimum string that has such cost. Then we pick the best result among all digits. Therefore, we divide the task into subtasks and solve it for each digit separately. To spend the least amount of money and make the maximum number of substitutions for each digit it need replace all the numbers are different from her first modulo 1, then modulo 2, then modulo 3 and etc to increase the module, in this and only this if typed in the sum will be minimal. Of course, if produced the right number of substitutions of K, then the algorithm should stop. However, to get the lexicographically smallest string with K digit C, then the replacement should be performed as follows. Suppose that this step of the algorithm need to change all the numbers that are different from the numbers with modulo I, first time it need replace all digits C + I for digit C from begin to end of string. Second time it need replace all digits C - I for C for end to begin of string, because in need to lexicographically minimum one. After choosing the best answer will be 10 rows. Thus, the asymptotic complexity of the algorithm is 10 * 10 * n.",
    "tags": [
      "brute force",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "118",
    "index": "D",
    "title": "Caesar's Legions",
    "statement": "Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had $n_{1}$ footmen and $n_{2}$ horsemen. Caesar thought that an arrangement is \\textbf{not} beautiful if somewhere in the line there are strictly more that $k_{1}$ footmen standing successively one after another, or there are strictly more than $k_{2}$ horsemen standing successively one after another. Find the number of \\underline{beautiful} arrangements of the soldiers.\n\nNote that all $n_{1} + n_{2}$ warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves.",
    "tutorial": "The problem is solved lazy dynamics. Let z[n1] [n2] [2] - a number of ways to place troops in a legion of Caesar. Indicate the following parameters, n1 - is a number of footmen, n2 - is a number of horseman, the third parameter indicates what troops put Caesar in the beginning of the line. If Caesar wants to put the footmen, the state dynamics of the z [n1] [n2] [0] go to the state z [n1] [n2 - i] [0], where 0 <= I <= min (k2, n2) . If Caesar wants to put the riders, the state dynamics of the z [n1] [n2] [1] go to the state z [n1] [n2 - i] [1], where 0 <= I <= min (k2, n2) .",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "118",
    "index": "E",
    "title": "Bertown roads",
    "statement": "Bertown has $n$ junctions and $m$ bidirectional roads. We know that one can get from any junction to any other one by the existing roads.\n\nAs there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.",
    "tutorial": "We are given an undirected connected graph, it is necessary to orient its arc so as to obtain a strongly connected directed graph. There is theorem (on a theoretical basis for a written task) that a graph admits an orientation to a strongly connected digraph if and only if every edge is part of what a cycle. To test this, simply run the bfs to the depth of any vertex and orient the edges in the direction of the bfs. The result of this procedure is an orientation of the graph. To make sure that in the original graph has no bridges, it need to take the orientation of the resulting graph, change the direction of arcs in it, and check that there remains a strong connection. This may be check by dfs too.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "119",
    "index": "A",
    "title": "Epic Game",
    "statement": "Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number $a$ and Antisimon receives number $b$. They also have a heap of $n$ stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has \\underline{strictly} less stones left than one needs to take).\n\nYour task is to determine by the given $a$, $b$ and $n$ who wins the game.",
    "tutorial": "It's enough just to model the described game to solve this problem. You can search a greatest common divisor in any reasonable way.",
    "code": "#include <iostream>\nusing namespace std;\nint gcd(int x, int y)\n{\n    return (x==0)? y : gcd(y % x, x);\n}\nint main()\n{\n    int a, b, n;\n    cin >> a >> b >> n;\n    int k = 0;\n    while (n >= 0)\n    {\n        ++k;\n        n -= gcd((k & 1) ? a : b, n);\n    }\n    if (k & 1) cout << 1; else cout << 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "119",
    "index": "B",
    "title": "Before Exam",
    "statement": "Vasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...\n\nTo prepare for the exam, one has to study proofs of $n$ theorems. It is known that there will be $k$ examination cards on the exam and each card contains $\\left\\lfloor{\\frac{22}{k}}\\right\\rfloor$ distinct theorems. Besides, no theorem is mentioned in more than one card (that is, $n-k\\cdot\\lfloor{\\frac{n}{k}}\\rfloor$ theorems won't be mentioned in any card). During the exam several students may get the same card.\n\nWe do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his \\underline{level of proficiency in the $i$-th theorem} by some number $a_{i}$. \\underline{The level of proficiency in some card} is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.",
    "tutorial": "Let's consider solution of the task for maximum level of profience (for minimum level solution is similar). It's clear that maximum level can be reached either in a card that has fallen one somebody's lot already or in a card about that we know nothing. In the first case we can just calculate levels of profiency for all cards from input and choose maximal level. The second case is more tricky. Let's sort all the theorems that weren't mentioned in cards from input in order of non-increasing of profiency's level. It's obvious that sought-for card consists of first $\\left\\lfloor{\\frac{22}{k}}\\right\\rfloor$ theorems in sorted list. This case is possible if the number of different cards mentioned in input is stictly less than k. For example, in the test 3 2 1 2 3 2 1 2 we can't consider a card containing third theorem because both examination cards are already known.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint n, k, a[100], q, ans_mx = -1, ans_mn = 1E9, nmb;\nbool used[100];\nvector<int> rem;\nint main()\n{\n    cin >> n >> k; nmb = n / k;\n    for (int i = 0; i < n; ++i) cin >> a[i];\n    int f = 0;\n    cin >> q;\n    for (int i = 0; i < q; ++i)\n    {\n        bool yes = false;\n        int cur, sum = 0;\n        for (int j = 0; j < nmb; ++j)\n        {\n            cin >> cur; --cur;\n            if (!used[cur] && !yes)\n            {\n                yes = true;\n                ++f;\n            }\n            used[cur] = true;\n            sum += a[cur];\n        }\n        ans_mx = max(ans_mx, sum);\n        ans_mn = min(ans_mn, sum);\n    }\n    for (int i = 0; i < n; ++i)\n        if (!used[i]) rem.push_back(a[i]);\n    sort(rem.begin(), rem.end());\n    if (rem.size() >= nmb && f < k)\n    {\n        int sum1 = 0,sum2 = 0;\n        for (int i = 0; i < nmb; ++i) { sum1 += rem[i]; sum2 += rem[rem.size() - 1 - i]; }\n        ans_mx = max(ans_mx, sum2);\n        ans_mn = min(ans_mn, sum1);\n    }\n    printf(\"%.10lf %.10lf\", ans_mn * 1.0 / nmb, ans_mx * 1.0 / nmb);\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "119",
    "index": "C",
    "title": "Education Reform",
    "statement": "Yet another education system reform has been carried out in Berland recently. The innovations are as follows:\n\nAn academic year now consists of $n$ days. Each day pupils study exactly one of $m$ subjects, besides, each subject is studied for no more than one day. After the lessons of the $i$-th subject pupils get the home task that contains no less than $a_{i}$ and no more than $b_{i}$ exercises. Besides, each subject has a special attribute, the complexity ($c_{i}$). A school can make its own timetable, considering the following conditions are satisfied:\n\n- the timetable should contain the subjects in the order of the complexity's strict increasing;\n- each day, except for the first one, the task should contain either $k$ times more exercises, or more by $k$ compared to the previous day (more formally: let's call the number of home task exercises in the $i$-th day as $x_{i}$, then for each $i$ ($1 < i ≤ n$): either $x_{i} = k + x_{i - 1}$ or $x_{i} = k·x_{i - 1}$ must be true);\n- the total number of exercises in all home tasks should be maximal possible.\n\nAll limitations are separately set for each school.\n\nIt turned out that in many cases $a_{i}$ and $b_{i}$ reach $10^{16}$ (however, as the Berland Minister of Education is famous for his love to half-measures, the value of $b_{i} - a_{i}$ doesn't exceed $100$). That also happened in the Berland School №256. Nevertheless, you as the school's principal still have to work out the timetable for the next academic year...",
    "tutorial": "This problem can be solved by dynamic programming. Let's sort all subjects in order of complexity's non-increasing. Let $d < / span > [ < spanstyle = \"\" > i < / span > ][ < spanstyle = \"\" > j < / span > ][ < spanstyle = \"\" > z < / span > ]$ is the greatest summary number of exercises, that can be given, if timetable contains exactly $z$ subjects from among of first $i$ subjects (in order of sort), involves $i$th subject and number of exercises in $i$th subject is equal to $a_{i} + j$. Recurrent correlations are based on search of subject that will occupy ($< spanstyle = \"\" > z < / span > - 1$)th day in timetable. For restoration of answer you should save source numbers of subjects. Asymptotic complexity is $O(m^{2} \\cdot n \\cdot max(b_{i} - a_{i}))$.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nstruct TSubject\n{\n    __int64 a, b;\n    int nmb, c;\n} sb[100];\nbool operator < (const TSubject &x, const TSubject &y)\n{\n    return x.c < y.c;\n}\nint n, m, k, cur = 0;\n__int64 d[50][101][51];\npair<int, int> p[50][101][51], state;\nint main()\n{\n    cin >> n >> m >> k;\n    for (int i = 0; i < m; ++i)\n    {\n        cin >> sb[i].a >> sb[i].b >> sb[i].c;\n        sb[i].nmb = i + 1;\n    }\n    sort(sb, sb + m);\n    state = make_pair(0, 0);\n    for (int i = 0; i < m; ++i)\n        for (int j = 0; j <= sb[i].b - sb[i].a; ++j)\n        {\n            d[i][j][1] = sb[i].a + j;\n            for (int z = 2; z <= n; ++z)\n            {\n                d[i][j][z] = -1;\n                for (int last = i - 1; last >= 0; --last)\n                    if (sb[last].c < sb[i].c)\n                        for (int t = 0; t <= 1; ++t)\n                        {\n                            __int64 temp = sb[i].a + j;\n                            bool yes = (t == 0) ? temp % k == 0 : temp >= k;\n                            temp = (t == 0) ? temp / k : temp - k;\n                            temp -= sb[last].a;\n                            if (!yes) continue;\n                            if (temp >= 0 && temp <= sb[last].b - sb[last].a \n                                && d[last][temp][z - 1] != -1 \n                                && d[last][temp][z - 1] + sb[i].a + j > d[i][j][z])\n                            {\n                                d[i][j][z] = d[last][temp][z - 1] + sb[i].a + j;\n                                p[i][j][z] = make_pair(last, temp);\n                            }\n                        }\n            }\n            if (d[i][j][n] > d[state.first][state.second][n])\n                state = make_pair(i, j);\n        }\n    if (d[state.first][state.second][n] == -1)\n    {\n        cout << \"NO\";\n        return 0;\n    }\n    vector<pair<int, __int64> > ans;\n    for (int i = n; i >= 1; --i)\n    {\n        ans.push_back(make_pair(sb[state.first].nmb, sb[state.first].a + state.second));\n        state = p[state.first][state.second][i];\n    }\n    cout << \"YES\" << endl;\n    for (int i = n - 1; i >= 0; --i)\n        cout << ans[i].first << ' ' << ans[i].second << endl;\n    return 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "119",
    "index": "D",
    "title": "String Transformation",
    "statement": "Let $s$ be a string whose length equals $n$. Its characters are numbered from 0 to $n - 1$, $i$ and $j$ are integers, $0 ≤ i < j < n$. Let's define function $f$ as follows:\n\n$f(s, i, j) = s[i + 1... j - 1] + r(s[j... n - 1]) + r(s[0... i])$.\n\nHere $s[p... q]$ is a substring of string $s$, that starts in position $p$ and ends in position $q$ (inclusive); \"+\" is the string concatenation operator; $r(x)$ is a string resulting from writing the characters of the $x$ string in the reverse order. If $j = i + 1$, then the substring $s[i + 1... j - 1]$ is considered empty.\n\nYou are given two strings $a$ and $b$. Find such values of $i$ and $j$, that $f(a, i, j) = b$. Number $i$ should be maximally possible. If for this $i$ there exists several valid values of $j$, choose the minimal $j$.",
    "tutorial": "If lengths of input strings aren't equal, we can at once output \"-1 -1\" and complete execution of a program. Otherwise let number $n$ is equal to the length of input strings. Let's iterate through the number $i$. We should find (in $O(1)$) the such smallest number $j$, that substing $b[0... n - i - 1]$ can be represented as $a[i + 1... j - 1] + r(a[j... n - 1]$). In order to do that, let's calculate the prefix function ($p[i]$) for string $s_{1} = r(a) + ' 0' + b$ and z-function ($z[i]$) for string $s_{2} = b + ' 0' + a$. It's clear that for fixed $i$ value of $j$ is equal to $n - p[2n - i - 1]$, and substrings $a[i + 1... j - 1]$, $b[0... j - i]$ must coincide at that (1). The last condition can be easily verified through using of calculated z-function. You can also trivial prove the next statement: if the property (1) is not satisfied by fixed $i$ for the chosen $j$, then it will not meet for bigger $j$. Asymptotic complexity is $O(n)$.",
    "code": "#include <iostream>\n#include <string>\n#include <algorithm>\nusing namespace std;\nstring a, b, s1, s2;\nint main()\n{\n    getline(cin, a);\n    getline(cin, b);\n    if (a.length() != b.length())\n    {\n        cout << \"-1 -1\";\n        return 0;\n    }\n    int n = a.length();\n    s1 = a; reverse(s1.begin(),s1.end()); s1 += '\u0000' + b;\n    s2 = b + '\u0000' + a;\n    int *p = new int[2 * n + 1];\n    p[0] = 0;\n    for (int i = 1; i < 2 * n + 1; ++i)\n    {\n        p[i] = p[i - 1];\n        while (p[i] > 0 && s1[p[i]] != s1[i])\n            p[i] = p[p[i] - 1];\n        if (s1[p[i]] == s1[i]) \n            ++p[i];\n    }\n    int *z = new int[2 * n + 1];\n    z[0] = 0;\n    for (int i = 1, l = 0, r = 0; i < 2 * n + 1; ++i)\n    {\n        z[i] = 0;\n        if (i <= r) \n            z[i] = min(z[i - l], r - i + 1);\n        while (i + z[i] < 2 * n + 1 && s2[z[i]] == s2[i + z[i]])\n            ++z[i];\n        if (i + z[i] - 1 > r)\n        {\n            l = i;\n            r = i + z[i] - 1;\n        }\n    }\n    int ans_i = -1, ans_j = -1;\n    for (int i = 0; i < n - 1; ++i)\n    {\n        if (a[i] != b[n - i - 1]) break;\n        int len = p[2 * n - i - 1];\n        if (z[n + i + 2] >= n - i - len - 1)\n        {\n            ans_i = i;\n            ans_j = n - len;\n        }\n    }\n    cout << ans_i << ' ' << ans_j << endl;\n    return 0;\n}",
    "tags": [
      "hashing",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "120",
    "index": "A",
    "title": "Elevator",
    "statement": "A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand.\n\nOne day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.",
    "tutorial": "You can either check all four cases or notice, that if we consider front/back equal to 0/1 (b) and decrease a by 1, then a XOR b became the answer (0/1). Time and memory consumption - $O(1)$.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "120",
    "index": "B",
    "title": "Quiz League",
    "statement": "A team quiz game called \"What? Where? When?\" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number $k$.",
    "tutorial": "Just write one loop: while $k$th question has already been asked, increase $k$ by one and if $k > n$ let $k = 1$. Time and memory consumpiton - $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "120",
    "index": "C",
    "title": "Winnie-the-Pooh and honey",
    "statement": "As we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are $n$ jars of honey lined up in front of Winnie-the-Pooh, jar number $i$ contains $a_{i}$ kilos of honey. Winnie-the-Pooh eats the honey like that: each time he chooses a jar containing most honey. If the jar has less that $k$ kilos of honey or if Winnie-the-Pooh has already eaten from it three times, he gives the jar to Piglet. Otherwise he eats exactly $k$ kilos of honey from the jar and puts it back. Winnie does so until he gives all jars to the Piglet. Count how much honey Piglet will overall get after Winnie satisfies his hunger.",
    "tutorial": "One of the possible solutions is direct emulation. Winnie won't do more than $3n$ iterations (because he can use each jar more than three times). You can emulate each iteration in $O(n)$ (just find maximum in array). Summary time - $O(n^{2})  \\approx  10^{4}$ operations, memory consumption - $O(n)$ There is another shorter solution: let's notice that order of jars doesn't matter. Let's see how much honey from each jar will be eaten by Winnie and how much will be left to Piglet. If $a_{i}  \\ge  3k$ then Winnie will leave $a_{i} - 3k$ kg of honey to Piglet. If $a_{i} < 3k$ then he'll leave only $a_{i}{\\mathrm{~mod~}}k$ kg. Now solution is one loop. Time and memory consumption is $O(n)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "120",
    "index": "E",
    "title": "Put Knight!",
    "statement": "Petya and Gena play a very interesting game \"Put a Knight!\" on a chessboard $n × n$ in size. In this game they take turns to put chess pieces called \"knights\" on the board so that no two knights could threat each other. A knight located in square $(r, c)$ can threat squares $(r - 1, c + 2)$, $(r - 1, c - 2)$, $(r + 1, c + 2)$, $(r + 1, c - 2)$, $(r - 2, c + 1)$, $(r - 2, c - 1)$, $(r + 2, c + 1)$ and $(r + 2, c - 1)$ (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.",
    "tutorial": "Petya wins if $n$ is odd, Gena wins if $n$ is even. It's quite easy to prove - just do symmetrical turns.",
    "tags": [
      "games",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "120",
    "index": "F",
    "title": "Spiders",
    "statement": "One day mum asked Petya to sort his toys and get rid of some of them. Petya found a whole box of toy spiders. They were quite dear to him and the boy didn't want to throw them away. Petya conjured a cunning plan: he will glue all the spiders together and attach them to the ceiling. Besides, Petya knows that the lower the spiders will hang, the more mum is going to like it and then she won't throw his favourite toys away. Help Petya carry out the plan.\n\nA spider consists of $k$ beads tied together by $k - 1$ threads. Each thread connects two different beads, at that any pair of beads that make up a spider is either directly connected by a thread, or is connected via some chain of threads and beads.\n\nPetya may glue spiders together directly gluing their beads. The length of each thread equals 1. The sizes of the beads can be neglected. That's why we can consider that gluing spiders happens by identifying some of the beads (see the picture). Besides, the construction resulting from the gluing process should also represent a spider, that is, it should have the given features.\n\nAfter Petya glues all spiders together, he measures the length of the resulting toy. The distance between a pair of beads is identified as the total length of the threads that connect these two beads. The length of the resulting construction is the largest distance between all pairs of beads. Petya wants to make the spider whose length is as much as possible.\n\nThe picture two shows two spiders from the second sample. We can glue to the bead number 2 of the first spider the bead number 1 of the second spider. The threads in the spiders that form the sequence of threads of maximum lengths are highlighted on the picture.",
    "tutorial": "Answer is sum of all spiders' lengths. Use depth-first-search (started at all vertexes) to calculate length of each spider.",
    "tags": [
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1400
  },
  {
    "contest_id": "120",
    "index": "G",
    "title": "Boom",
    "statement": "Let's consider the famous game called Boom (aka Hat) with simplified rules.\n\nThere are $n$ teams playing the game. Each team has two players. The purpose of the game is to explain the words to the teammate without using any words that contain the same root or that sound similarly.\n\nPlayer $j$ from team $i$ $(1 ≤ i ≤ n, 1 ≤ j ≤ 2)$ is characterized by two numbers: $a_{ij}$ and $b_{ij}$. The numbers correspondingly represent the skill of explaining and the skill of understanding this particular player has.\n\nBesides, $m$ cards are used for the game. Each card has a word written on it. The card number $k$ $(1 ≤ k ≤ m)$ is characterized by number $c_{k}$ — the complexity of the word it contains.\n\nBefore the game starts the cards are put in a deck and shuffled. Then the teams play in turns like that: the 1-st player of the 1-st team, the 1-st player of the 2-nd team, ... , the 1-st player of the $n$-th team, the 2-nd player of the 1-st team, ... , the 2-nd player of the $n$-th team, the 1-st player of the 1-st team and so on.\n\nEach turn continues for $t$ seconds. It goes like that: Initially the time for each turn is $t$. While the time left to a player is more than 0, a player takes a card from the top of the deck and starts explaining the word it has to his teammate. The time needed for the $j$-th player of the $i$-th team to explain the word from the card $k$ to his teammate (the $q$-th player of the $i$-th team) equals $max(1, c_{k} - (a_{ij} + b_{iq}) - d_{ik})$ (if $j = 1, $ then $q = 2, $ else $q = 1$). The value $d_{ik}$ is the number of seconds the $i$-th team has already spent explaining the word $k$ during the previous turns. Initially, all $d_{ik}$ equal 0. If a team manages to guess the word before the end of the turn, then the time given above is substracted from the duration of the turn, the card containing the guessed word leaves the game, the team wins one point and the game continues. If the team doesn't manage to guess the word, then the card is put at the bottom of the deck, $d_{ik}$ increases on the amount of time of the turn, spent on explaining the word. Thus, when this team gets the very same word, they start explaining it not from the beginning, but from the point where they stopped. The game ends when words from all $m$ cards are guessed correctly.\n\nYou are given $n$ teams and a deck of $m$ cards. You should determine for each team, how many points it will have by the end of the game and which words the team will have guessed.",
    "tutorial": "It's simple realization problem. All you need is two-dimensional arrays and one queue.",
    "code": "#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <cmath>\n#include <cassert>\n#include <algorithm>\n#include <string>\n#include <vector>\n#include <deque>\n \nusing namespace std;\n \n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#define pb push_back\n#define mp make_pair\n#define sz(x) ((int)(x).size())\n \ntypedef long long ll;\ntypedef vector<ll> vll;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef vector<bool> vb;\ntypedef vector<vb> vvb;\ntypedef pair<int, int> pii;\n \nint main() {\n  #ifdef DEBUG\n  freopen(\"std.in\", \"r\", stdin);\n  freopen(\"std.out\", \"w\", stdout);\n  #else\n  freopen(\"input.txt\", \"r\", stdin);\n  freopen(\"output.txt\", \"w\", stdout);\n  #endif\n \n  int n, t;\n  while (scanf(\"%d%d\", &n, &t) >= 2) {\n    vvi as(n, vi(2)), bs(n, vi(2)); \n    for (int i = 0; i < n; i++)\n      for (int i2 = 0; i2 < 2; i2++)\n        scanf(\"%d%d\", &as[i][i2], &bs[i][i2]);\n \n    int m;\n    scanf(\"%d\", &m);\n    vector<string> ns(m); vi cs(m);\n    for (int i = 0; i < m; i++) {\n      char buf[30];\n      scanf(\"%s%d\", buf, &cs[i]);\n      ns[i] = buf;\n    }\n \n    vector<vector<string> > res(n);\n \n    vvi d(n, vi(m, 0));\n    deque<int> dq;\n    for (int i = 0; i < m; i++) dq.pb(i);\n \n    int cur = 0, cpl = 0;\n    while (!dq.empty()) {\n      int curt = t;\n      while (curt > 0 && !dq.empty()) {\n        int card = dq.front(); dq.pop_front();\n        int need = max(1, cs[card] - (as[cur][cpl] + bs[cur][!cpl]) - d[cur][card]);\n        if (curt >= need) {\n          curt -= need;\n          res[cur].pb(ns[card]);\n        } else {\n          dq.pb(card);\n          d[cur][card] += curt;\n          curt = 0;\n        }\n      }\n \n      if (++cur >= n) {\n        cur = 0;\n        cpl = !cpl;\n      }\n    }\n    for (int i = 0; i < n; i++) {\n      printf(\"%d\", sz(res[i]));\n      for (int i2 = 0; i2 < sz(res[i]); i2++)\n        printf(\" %s\", res[i][i2].c_str());\n      printf(\"\n\");\n    }\n  }\n  return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "120",
    "index": "H",
    "title": "Brevity is Soul of Wit",
    "statement": "As we communicate, we learn much new information. However, the process of communication takes too much time. It becomes clear if we look at the words we use in our everyday speech.\n\nWe can list many simple words consisting of many letters: \"information\", \"technologies\", \"university\", \"construction\", \"conservatoire\", \"refrigerator\", \"stopwatch\", \"windowsill\", \"electricity\", \"government\" and so on. Of course, we can continue listing those words ad infinitum.\n\nFortunately, the solution for that problem has been found. To make our speech clear and brief, we should replace the initial words with those that resemble them but are much shorter. This idea hasn't been brought into life yet, that's why you are chosen to improve the situation.\n\nLet's consider the following formal model of transforming words: we shall assume that one can use $n$ words in a chat. For each words we shall introduce a notion of its shorter variant. We shall define \\textbf{shorter variant} of an arbitrary word $s$ as such word $t$, that meets the following conditions:\n\n- it occurs in $s$ as a \\textbf{subsequence},\n- its length ranges from one to four characters.\n\nIn other words, the word $t$ consists at least of one and at most of four characters that occur in the same order in the word $s$. Note that those characters do not necessarily follow in $s$ immediately one after another. You are allowed not to shorten the initial word if its length does not exceed four characters.\n\nYou are given a list of $n$ different words. Your task is to find a set of their shortened variants. The shortened variants of all words from the list should be different.",
    "tutorial": "Notice that there are only $\\sum_{k=1}^{4}26^{k}=475254$ different strings that have length 4 or less. Then notice that each of input strings you can change to $\\sum_{k=1}^{4}C_{|w_{i}|}^{k}=385$ different short words at most ($|w_{i}|$ is length of the $i$th word). Now let's make bipartite graph. One part is all source words, the second part is all short words and there is edge if and only if we can change word from the first part to the short word from the second part. Now our task is just find perfect matching in this graph. It can be done in $O(n_{1} \\cdot  m)  \\approx  200 \\cdot  200 \\cdot  385 = 15.4 \\cdot 10^{6}$ operations which is enough.",
    "tags": [
      "graph matchings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "120",
    "index": "I",
    "title": "Luck is in Numbers",
    "statement": "Vasya has been collecting transport tickets for quite a while now. His collection contains several thousands of tram, trolleybus and bus tickets. Vasya is already fed up with the traditional definition of what a lucky ticket is. Thus, he's looking for new perspectives on that. Besides, Vasya cannot understand why all tickets are only divided into lucky and unlucky ones. He thinks that all tickets are lucky but in different degrees. Having given the matter some thought, Vasya worked out the definition of a ticket's degree of luckiness. Let a ticket consist of $2n$ digits. Let's regard each digit as written as is shown on the picture:\n\nYou have seen such digits on electronic clocks: seven segments are used to show digits. Each segment can either be colored or not. The colored segments form a digit. Vasya regards the digits as written in this very way and takes the right half of the ticket and puts it one the left one, so that the first digit coincides with the $n + 1$-th one, the second digit coincides with the $n + 2$-th one, ..., the $n$-th digit coincides with the $2n$-th one. For each pair of digits, put one on another, he counts the number of segments colored in both digits and summarizes the resulting numbers. The resulting value is called the degree of luckiness of a ticket. For example, the degree of luckiness of ticket 03 equals four and the degree of luckiness of ticket 2345 equals six.\n\nYou are given the number of a ticket containing $2n$ digits. Your task is to find among the tickets whose number exceeds the number of this ticket but also consists of $2n$ digits such ticket, whose degree of luckiness exceeds the degrees of luckiness of the given ticket. Moreover, if there are several such tickets, you should only choose the one with the smallest number.",
    "tutorial": "Unfortunately, my solution for this problem is rather big. If someone know beautiful one share it please. The main idea is very standard: let's fix some prefix of number, which is strictly greater than such prefix of source number. If we can get known what is maximal happiness for suffix of our number then we can solve the problem by just running down values for each number in suffix and checking that we still can reach necessary value of happiness. Now solution for this subproblem is just to fill suffix with eights and calculate the answer. It's good but takes a lot of time. We need to store old values and recalculate its in $O(1)$. There are very simple formulas to do it.",
    "tags": [
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "120",
    "index": "J",
    "title": "Minimum Sum",
    "statement": "You are given a set of $n$ vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector $v_{i} = (x_{i}, y_{i})$ can be transformed into one of the following four vectors:\n\n- $v_{i}^{1} = (x_{i}, y_{i})$,\n- $v_{i}^{2} = ( - x_{i}, y_{i})$,\n- $v_{i}^{3} = (x_{i}, - y_{i})$,\n- $v_{i}^{4} = ( - x_{i}, - y_{i})$.\n\nYou should find two vectors from the set and determine which of their coordinates should be multiplied by -1 so that the absolute value of the sum of the resulting vectors was minimally possible. More formally, you should choose two vectors $v_{i}$, $v_{j}$ ($1 ≤ i, j ≤ n, i ≠ j$) and two numbers $k_{1}$, $k_{2}$ ($1 ≤ k_{1}, k_{2} ≤ 4$), so that the value of the expression $|v_{i}^{k1} + v_{j}^{k2}|$ were minimum.",
    "tutorial": "Firstly you need to notice that you can turn all vectors in such way that all of them have non-negative coordinates and the answer will remain the same. And now we have the following problem: find two nearest points from the given set. It's standard divide-and-conquer problem, it's described in Wikipedia. Also there is simpler solution (added by diogen): let's sort all our points by distance from a random point far-far away. It's oblivious that if some points lie near each other, distance to this far point doesn't vary a lot. And now solution is run down for each point $C$ points near it in the sorted array. $C$ about 200 is enough to got Accepted.",
    "tags": [
      "divide and conquer",
      "geometry",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "121",
    "index": "A",
    "title": "Lucky Sum",
    "statement": "\\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nLet $next(x)$ be the minimum lucky number which is larger than or equals $x$. Petya is interested what is the value of the expression $next(l) + next(l + 1) + ... + next(r - 1) + next(r)$. Help him solve this problem.",
    "tutorial": "Let generate all lucky number between $1$ and $10^{10}$. Consider all segment $[1;L0]$, $[L0 + 1;L1]$, $[L1 + 1;L2]$ ... Then the result equals to product of intersection of segments $[1;L0]$ and $[1;n]$ by $L0$ plus size of intersection of $[L0 + 1;L1]$ and $[1;n]$ multiplied by $L1$ and so on.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "121",
    "index": "B",
    "title": "Lucky Transformation",
    "statement": "\\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya has a number consisting of $n$ digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it $d$. The numeration starts with $1$, starting from the most significant digit. Petya wants to perform the following \\underline{operation} $k$ times: find the minimum $x$ $(1 ≤ x < n)$ such that $d_{x} = 4$ and $d_{x + 1} = 7$, if $x$ is odd, then to assign $d_{x} = d_{x + 1} = 4$, otherwise to assign $d_{x} = d_{x + 1} = 7$. Note that if no $x$ was found, then the operation counts as completed and the array doesn't change at all.\n\nYou are given the initial number as an array of digits and the number $k$. Help Petya find the result of completing $k$ operations.",
    "tutorial": "Notice, that if there exits such $i$ that $i$ mod $2$ = $0$ and $d_{i} = 4$ and $d_{i + 1} = 7$ and $d_{i - 1} = 4$ then after that operation there will be a loop. So, let we simple do all operation from left ro right, and, when we will win our loop, just return a rusult (which variates by $k$ mod $2$ ($k$ is one that leaves after operation from left side).",
    "tags": [
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "121",
    "index": "C",
    "title": "Lucky Permutation",
    "statement": "\\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nOne day Petya dreamt of a lexicographically $k$-th permutation of integers from $1$ to $n$. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.",
    "tutorial": "If $n  \\le  14$ let find out, is $k$ more than $n!$ or not? If yes, then return -1. Then, notice, that since $k  \\le  10^{9}$, then at most $13$ elements from right (suffix) will change. So, element from left of this part (prefix) will not change (then we can just find a number of lucky numbers on than range). To find result for the rest of the permutation (suffix) we need to find $k$-th permutation of number from $1$ to $t$ ($t$ is maximun integer, such that $t!  \\le  k$). After we find that permutation, we can just loop through that permutation and count result.",
    "tags": [
      "brute force",
      "combinatorics",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "121",
    "index": "D",
    "title": "Lucky Segments",
    "statement": "\\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya has $n$ number segments $[l_{1}; r_{1}]$, $[l_{2}; r_{2}]$, ..., $[l_{n}; r_{n}]$. During one move Petya can take any segment (let it be segment number $i$) and replace it with segment $[l_{i} + 1; r_{i} + 1]$ or $[l_{i} - 1; r_{i} - 1]$. In other words, during one move Petya can shift any segment to the left or to the right by a unit distance. Petya calls a number \\underline{full} if it belongs to each segment. That is, number $x$ is full if for any $i$ $(1 ≤ i ≤ n)$ the condition $l_{i} ≤ x ≤ r_{i}$ is fulfilled.\n\nPetya makes no more than $k$ moves. After that he counts the quantity of full lucky numbers. Find the maximal quantity that he can get.",
    "tutorial": "Lei calculate arrays $L$ and $R$. Let for all lucky $i$, $L[i]$ = number of operation needed to move every segment, which's right end is to left from $i$ to $i$. $R[i]$ = number of operation needed to move every segment which left end is to right to $i$. How to calculate such array? Just use a sorting. Let arrange array $A$ of pairs of integers, first - number, second equals to $0$, if that number end of some segment, $1$ if that number is lucky. Then, iterate from left to right, counting number of segment end we counted and $s_{i}$, $s_{i} = s_{i - 1} + (A_{i} - A_{i - 1}) * c_{i}$. The same way you can use to $R$. Now, to find the answer we must find (using method of two pointers of binary search) pair of indexes $x$ and $y$, such that $i  \\le  j$, $L_{j} + R_{i}  \\le  k$, $Lucky_{j} - Lucky_{i} + 1  \\le $ min_size_of_input_segment. Also, is this problem you should arrange function $Mul(a, b)$, which return $min(a * b, INF)$. Since simple multiplication overflows, then you can use multipling modulo $2^{64}$ or double or min-long-arithmetic.",
    "tags": [
      "binary search",
      "implementation",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "121",
    "index": "E",
    "title": "Lucky Array",
    "statement": "\\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya has an array consisting of $n$ numbers. He wants to perform $m$ operations of two types:\n\n- \\underline{add $l$ $r$ $d$} — add an integer $d$ to all elements whose indexes belong to the interval from $l$ to $r$, inclusive $(1 ≤ l ≤ r ≤ n, 1 ≤ d ≤ 10^{4})$;\n- \\underline{count $l$ $r$} — find and print on the screen how many lucky numbers there are among elements with indexes that belong to the interval from $l$ to $r$ inclusive $(1 ≤ l ≤ r ≤ n)$. Each lucky number should be counted as many times as it appears in the interval.\n\nPetya has a list of all operations. The operations are such that after all additions the array won't have numbers that would exceed $10^{4}$. Help Petya write a program that would perform these operations.",
    "tutorial": "In this problem you can use many different algorithms, here is one of them. Obviously, number of different lucky number is $30$, because $A_{i}$ always is $ \\le  10000$. Let $D_{i}$ - difference between minimum lucky number which is greater than or equal to $A_{i}$ and $A_{i}$. Now, we need to have 5 (but you can use less number) of operation on $D$: Subtract(l, r, d) - subtract number $d$ from all $A_{i}$ $(l  \\le  i  \\le  r)$, Minimum(l, r) - minumum number of all $D_{i}$ $(l  \\le  i  \\le  r)$, Count(l, r) - how many times that minimum occared in that interval, Left(l, r) = leftmost occarence of that minimum, Set(i, d) - assign $d$ to $D_{i}$ ($D_{i} = d$). Now, we can do our operations. If our operation is \"count\", then we need to find minimum number $d$ ($d =$ Minimum(l, r)), if it is equal to $0$, then answer is Count(l, r, 0), otherwise, answer is $0$. If out operation is \"add\", then we need to Subtract(l, r, d), but now some $D_{i}$ might be less than $0$. So, while, Minimum(l, r) $ \\le  0$, let j = Left(l, r), assign $D_{j}$ new value (use Set(j, $D_{j}$')), which can be calculated with complaxity $O(1)$. Complexity of this algorithm is $O(m * log(n) + n * log(n) * C)$, where $C$ is equal to $30$.",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "122",
    "index": "A",
    "title": "Lucky Division",
    "statement": "\\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya calls a number \\underline{almost lucky} if it could be evenly divided by some lucky number. Help him find out if the given number $n$ is almost lucky.",
    "tutorial": "In this problem you just need to loop through the integers $i$ from $1$ to $n$ determine, is $i$ lucky, if yes, then try, if $n$ mod $i$ = $0$, then answer is \"YES\". If there are no such $i$, answer is \"NO\".",
    "tags": [
      "brute force",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "122",
    "index": "B",
    "title": "Lucky Substring",
    "statement": "\\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nOne day Petya was delivered a string $s$, containing only digits. He needs to find a string that\n\n- represents a lucky number without leading zeroes,\n- is not empty,\n- is contained in $s$ as a substring the maximum number of times.\n\nAmong all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya.",
    "tutorial": "Notice, that answer is either one digit or -1. So, if there are no $4$ and $7$ digits, then answer is -1. Else, if there is more or equel number of digits $4$, then answer is $4$, else answer is $7$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "123",
    "index": "A",
    "title": "Prime Permutation",
    "statement": "You are given a string $s$, consisting of small Latin letters. Let's denote the length of the string as $|s|$. The characters in the string are numbered starting from $1$.\n\nYour task is to find out if it is possible to rearrange characters in string $s$ so that for any prime number $p ≤ |s|$ and for any integer $i$ ranging from $1$ to $|s| / p$ (inclusive) the following condition was fulfilled $s_{p} = s_{p × i}$. If the answer is positive, find one way to rearrange the characters.",
    "tutorial": "All positions except the first and those whose number is a prime greater $|s| / 2$ have to have the same symbol. Remaining positions can have any symbol. Consider positions that should be the same for $p = 2$ is 2,4,6,8 ... Now let's take a position with the number $x  \\le  |s| / 2$, this position should have the same character as the position of $2$ as the symbol $x$ must be equal to the character at position $2 * x$, which is equal to the character at position $2$. Now consider the position whose number is more than $|s| / 2$. If this position is not a prime then there is a prime number $p$ to divide the number at our positions and $p  \\le  |s| / 2$. So character at position $p$ is equal the character at position $2$ and so a symbol at our position is also consistent to the character at position $2$. The remaining positions are not combined with any other positions so it does not matter which symbol is situated here. Let's find the symbol which occurs the most and try to place the symbol on the position in which the characters have to be equal. If this symbol for all positions is not enough then the answer will be \"NO\", otherwise arrange the remaining characters by any way at other positions.",
    "code": "#include <cstdio>\n#include <cstring>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAXN = 1001;\n\nint n;\nchar s[MAXN];\nint c[256];\nbool f[MAXN];\n\nint main()\n{\n    #ifndef ONLINE_JUDGE\n        freopen(\"in\", \"r\", stdin);\n        freopen(\"out\", \"w\", stdout);\n    #endif\n    gets(s);\n    n = strlen(s);\n    for (int i = 0; i < n; i++)\n        c[s[i]]++;\n\n    int k = 0;\n    for (int i = 0; i < 256; i++)\n        if (c[i] > c[k]) k = i;\n\n\n    memset(f, true, sizeof(f));\n    for (int i = 2; i * i <= n; i++)\n        if (f[i])\n            for (int j = i * i; j <= n; j += i)\n                f[j] = false;\n\n    f[1] = true;\n    for (int i = 2; i + i <= n; i++)\n        f[i] = false;\n\n    for (int i = 1; i <= n; i++)\n        if (!f[i])\n        {\n            if (c[k] == 0)\n            {\n                puts(\"NO\");\n                return 0;\n            }\n            c[s[i - 1] = k]--;\n        }\n\n    k = 0;\n    for (int i = 1; i <= n; i++)\n        if (f[i])\n        {\n            while (c[k] == 0) k++;\n            c[s[i - 1] = k]--;\n        }\n    puts(\"YES\");\n    puts(s);\n    return 0;\n}",
    "tags": [
      "implementation",
      "number theory",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "123",
    "index": "B",
    "title": "Squares",
    "statement": "You are given an infinite checkered field. You should get from a square ($x_{1}$; $y_{1}$) to a square ($x_{2}$; $y_{2}$). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.\n\nA square ($x$; $y$) is considered bad, if at least one of the two conditions is fulfilled:\n\n- $|x + y| ≡ 0$ $(mod 2a)$,\n- $|x - y| ≡ 0$ $(mod 2b)$.\n\nYour task is to find the minimum number of bad cells one will have to visit on the way from ($x_{1}$; $y_{1}$) to ($x_{2}$; $y_{2}$).",
    "tutorial": "Let's turn the field on $45^{o}$ transforming cells coordinates $(x, y)$ in $(x + y, x - y)$. Then the cell $(x, y)$ will be bad if one of the conditions occurs $x  \\equiv  0$ $(mod$ $2a)$ or $y  \\equiv  0$ $(mod$ $2b)$. So good cells will be divided into sectors by vertical and horizontal lines. For each sector, it is possible to determine the coordinates of a pair of numbers, the first number that will rise during the transition to the next right sector, and the second pair number will increase during the transition to the next upper sector. From the sector with coordinates $(x, y)$ can go to any nearby on the side of the sector, visiting at least one bad cell, ie in $(x - 1, y)$, $(x + 1, y)$, $(x, y - 1)$ and $(x, y + 1)$. Since the numbers $2a$ and $2b$ have the same parity, then from the sector $(x, y)$ can also go to the sector on the diagonal, and visiting a bad cell, ie in $(x - 1, y + 1)$, $(x + 1, y - 1)$, $(x - 1, y - 1)$ and $(x + 1, y + 1)$. Then it turns out that the minimum number of bad cells, which should be visited on the way out of from the sector $(x1, y1)$ to sector of $(x2, y2)$ equals $max(|x1 - x2|, |y1 - y2|)$. Let's transform the coordinates of the initial and final cells as described rule above. Then find sectors which contain our cells and calculate answer with formula above.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\n\nint a, b, x1, y1, x2, y2;\nint x, y;\n\n\n\nint main()\n{\n    #ifndef ONLINE_JUDGE\n        freopen(\"in\", \"r\", stdin);\n        freopen(\"out\", \"w\", stdout);\n    #endif\n    cin >> a >> b >> x1 >> y1 >> x2 >> y2;\n    x = x1; y = y1;\n    x1 = x + y;\n    y1 = y - x;\n\n    x = x2; y = y2;\n    x2 = x + y;\n    y2 = y - x; \n\n    a *= 2;\n    b *= 2;\n\n    x1 = x1 / a + (x1 > 0);\n    x2 = x2 / a + (x2 > 0);\n    y1 = y1 / b + (y1 > 0);\n    y2 = y2 / b + (y2 > 0);\n\n    cout << max(abs(y2 - y1), abs(x2 - x1)) << endl;\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "123",
    "index": "C",
    "title": "Brackets",
    "statement": "A two dimensional array is called a \\underline{bracket} array if each grid contains one of the two possible brackets — \"(\" or \")\". A path through the two dimensional array cells is called \\underline{monotonous} if any two consecutive cells in the path are side-adjacent and each cell of the path is located below or to the right from the previous one.\n\nA two dimensional array whose size equals $n × m$ is called a \\underline{correct bracket} array, if any string formed by writing out the brackets on some monotonous way from cell $(1, 1)$ to cell $(n, m)$ forms a correct bracket sequence.\n\nLet's define the operation of comparing two correct bracket arrays of equal size ($a$ and $b$) like that. Let's consider a given two dimensional array of priorities ($c$) — a two dimensional array of same size, containing different integers from $1$ to $nm$. Let's find such position $(i, j)$ in the two dimensional array, that $a_{i, j} ≠ b_{i, j}$. If there are several such positions, let's choose the one where number $c_{i, j}$ is minimum. If $a_{i, j} = $\"(\", then $a < b$, otherwise $a > b$. If the position $(i, j)$ is not found, then the arrays are considered equal.\n\nYour task is to find a $k$-th two dimensional correct bracket array. It is guaranteed that for the given sizes of $n$ and $m$ there will be no less than $k$ two dimensional correct bracket arrays.",
    "tutorial": "Let's reduce the problem to a one-dimensional matrix. Consider a monotonous path $(1, 1), (1, 2), ..., (1, m - 1), (1, m), (2, m), ..., (n - 1, m), (n, m)$ which has correct bracket sequence. Now, in this way a cell $(1, m)$ can be replaced on $(2, m - 1)$ and still be a monotonous way and will form the correct sequence of the bracket. So in the cells of $(1, m)$ and $(2, m - 1)$ is one type of bracket. Proceeding further (eg to replace $(1, m - 1)$ on $(2, m - 2)$ or $(2, m)$ on $(3, m - 1)$) can be seen that in cells $(i, j)$ and $(i - 1, j + 1)$ is one type of bracket. Then we get not two-dimensional array $n  \\times  m$, a one-dimensional size $n + m - 1$. For each position can be determined what her highest priority, ie for cell $i$ ($1  \\le  i  \\le  n + m - 1$), the priority will be equal to the minimum value of $p_{x, y}$ where $1  \\le  x  \\le  n$, $1  \\le  y  \\le  m$ and $x + y - 1 = i$. Let's iterate through the positions, starting with the highest priority. Let's put in this position the bracket \"(\" and consider how many ways can complete the remaining brackets to get the correct bracket sequence. If the number of ways of not less than $k$, then leave in this position \"(\", or reduce the $k$ on the number of ways and put in this positions bracket \")\". And so let's iterate through all items. In order to calculate the number of ways each time dynamics is calculated on two parameters $f_{i, j}$, where $i$ is the number of processed positions, and $j$ is the number of opened brackets. If the position of $i + 1$ bracket is not defined yet then you can go to $f_{i + 1, j + 1}$ or $f_{i + 1, j - 1}$, if defined then only $f_{i + 1, j + 1}$ or only $f_{i + 1, j - 1}$, depending on opening or closing bracket respectively.",
    "code": "#include <cstdio>\n#include <cmath>\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\n\nconst int MAXN = 202;\n\nint n, m, l;\nlong long k;\nint a[MAXN];\nint d[MAXN];\nchar s[MAXN];\nlong long f[MAXN][MAXN];\n\n\nbool opr_sort(const int &i, const int &j)\n{\n    return a[i] < a[j];\n}\n\nint main()\n{\n    #ifndef ONLINE_JUDGE\n        freopen(\"in\", \"r\", stdin);\n        freopen(\"out\", \"w\", stdout);\n    #endif\n    cin >> n >> m >> k;\n\n    l = n + m - 1;\n    for (int i = 0; i < l; i++)\n    {\n        a[i] = n * m;\n        d[i] = i;\n    }\n\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < m; j++)\n        {\n            int x;\n            scanf(\"%d\", &x);\n            if (x < a[i + j]) a[i + j] = x;\n        }\n    }\n\n    sort(d, d + l, opr_sort);\n\n    for (int I = 0; I < l; I++)\n    {\n        s[d[I]] = '(';\n\n        f[0][0] = 1;\n        for (int i = 0; i < l; i++)\n            for (int j = i & 1; j <= i && j <= l - i; j += 2)\n                if (f[i][j])\n                {\n                    if (f[i][j] > k) f[i][j] = k;\n\n                    if (s[i] != ')') f[i + 1][j + 1] += f[i][j];\n                    if (s[i] != '(' && j) f[i + 1][j - 1] += f[i][j];\n                    f[i][j] = 0;\n                }\n//        printf(\"%d %lld\n\", d[I], f[l][0]);\n        if (k > f[l][0])\n        {\n            k -= f[l][0];\n            s[d[I]] = ')';\n        }\n        f[l][0] = 0;\n    }\n\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < m; j++)\n            printf(\"%c\", s[i + j]);\n        printf(\"\n\");\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "123",
    "index": "D",
    "title": "String",
    "statement": "You are given a string $s$. Each pair of numbers $l$ and $r$ that fulfill the condition $1 ≤ l ≤ r ≤ |s|$, correspond to a substring of the string $s$, starting in the position $l$ and ending in the position $r$ (inclusive).\n\nLet's define the function of two strings $F(x, y)$ like this. We'll find a list of such pairs of numbers for which the corresponding substrings of string $x$ are equal to string $y$. Let's sort this list of pairs according to the pair's first number's increasing. The value of function $F(x, y)$ equals the number of non-empty continuous sequences in the list.\n\nFor example: $F(babbabbababbab, babb) = 6$. The list of pairs is as follows:\n\n$(1, 4), (4, 7), (9, 12)$\n\nIts continuous sequences are:\n\n- $(1, 4)$\n- $(4, 7)$\n- $(9, 12)$\n- $(1, 4), (4, 7)$\n- $(4, 7), (9, 12)$\n- $(1, 4), (4, 7), (9, 12)$\n\nYour task is to calculate for the given string $s$ the sum $F(s, x)$ for all $x$, that $x$ belongs to the set of all substrings of a string $s$.",
    "tutorial": "Sort all suffixes of the string (denoted by an array of strings $c_{i}$). Then the answer to the problem is the amount of $1  \\le  i  \\le  j  \\le  |s|$ and $1  \\le  k$, that the prefixes of length $k$ in all $c_{i..j}$ are equal. Options when $i = j$, and $1  \\le  k  \\le  |c_{i}|$ can calculate at once, it is the number of substrings in the string, ie $|s| * (|s| + 1) / 2$. Now let's count the LCP (longest common prefix) for adjacent suffixes, ie $a_{i} = LCP(c_{i}, c_{i + 1})$ for $1  \\le  i < |s|$. Then let's count the number of $1  \\le  i  \\le  j < |s|$ and $1  \\le  k$, that $k  \\le  min(a_{i..j})$. This task is to count the number of rectangles if there is a limit to the height of each column, ie $a_{i}$ the maximum height of the rectangle in the column $i$. Solve by a stack or list.",
    "code": "#include <cstdio>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAXN = 100002;\nconst int MAXM = 20;\n\nint n, m, k;\nchar s[MAXN];\nint cnt[MAXN];\nint A[MAXM][MAXN];\nint p[MAXN], _p[MAXN], a[MAXN], _a[MAXN];\n\nint h[MAXN], w[MAXN];\nlong long f[MAXN];\n\nint sorting(int st, int &k)\n{\n    for (int i = 0; i < n; i++)\n        _p[i] = p[i] - st < 0? p[i] - st + n : p[i] - st;\n\n    for (int i = 0; i < k; i++)\n        cnt[i] = 0;\n\n    for (int i = 0; i < n; i++)\n        cnt[a[_p[i]]]++;\n\n    for (int i = 1; i < k; i++)\n        cnt[i] += cnt[i - 1];\n\n    for (int i = n - 1; i >= 0; i--)\n        p[--cnt[a[_p[i]]]] = _p[i];\n\n    for (int i = 0; i < n; i++)\n        _p[i] = p[i] + st < n? p[i] + st : p[i] + st - n;\n\n    _a[p[0]] = 0;\n    k = 1;\n    for (int i = 1; i < n; i++)\n    {\n        if (a[p[i - 1]] != a[p[i]] || a[_p[i - 1]] != a[_p[i]]) k++;\n        _a[p[i]] = k - 1;\n    }\n    for (int i = 0; i < n; i++) a[i] = _a[i];\n    return 0;\n}\n\n\nint lcp(int x, int y)\n{\n    int res = 0;\n    for (int i = m - 1; i >= 0; i--)\n        if (A[i][x] == A[i][y])\n        {\n            x += 1 << i;\n            y += 1 << i;\n            res += 1 << i;\n        }\n    return res;\n}\n\nint main()\n{\n    #ifndef ONLINE_JUDGE\n        freopen(\"in\", \"r\", stdin);\n        freopen(\"out\", \"w\", stdout);\n    #endif\n\n    gets(s);\n    n = strlen(s);\n    long long ans = (long long)n * (n + 1) / 2;\n\n    s[n++] = 0;\n    for (int i = 0; i < n; i++)\n    {\n        p[i] = i;\n        a[i] = s[i];\n    }\n    k = 256;\n\n    sorting(0, k);\n    for (m = 0; (1 << m) < n; m++)\n    {\n        int st = 1 << m;\n        for (int i = 0; i < n; i++)\n            A[m][i] = a[i];\n\n        sorting(st, k);\n    }\n    for (int i = 0; i < n; i++)\n        A[m][i] = a[i];\n    m++;\n\n    k = 0;\n    for (int i = 2; i < n; i++)\n        a[k++] = lcp(p[i - 1], p[i]);\n\n    n = 0;\n    h[n] = -1;\n    w[n] = 0;\n    f[n] = 0;\n    n++;\n\n    for (int i = 0; i < k; i++)\n    {\n        int l = 1;\n        while (h[n - 1] >= a[i]) l += w[--n];\n\n        w[n] = l;\n        h[n] = a[i];\n        f[n] = f[n - 1] + (long long)l * a[i];\n        n++;\n\n        ans += f[n - 1];\n    }\n\n    printf(\"%I64d\n\", ans);\n    return 0;\n}",
    "tags": [
      "string suffix structures"
    ],
    "rating": 2300
  },
  {
    "contest_id": "123",
    "index": "E",
    "title": "Maze",
    "statement": "A maze is represented by a tree (an undirected graph, where exactly one way exists between each pair of vertices). In the maze the entrance vertex and the exit vertex are chosen with some probability. The exit from the maze is sought by Deep First Search. If there are several possible ways to move, the move is chosen equiprobably. Consider the following pseudo-code:\n\n\\begin{verbatim}\nDFS(x)\nif x == exit vertex then\n\nfinish search\nflag[x] <- TRUE\nrandom shuffle the vertices' order in V(x) // here all permutations have equal probability to be chosen\nfor i <- 1 to length[V] do\nif flag[V[i]] = FALSE then\ncount++;\nDFS(y);\ncount++;\n\\end{verbatim}\n\n$V(x)$ is the list vertices adjacent to $x$. The $flag$ array is initially filled as FALSE. $DFS$ initially starts with a parameter of an entrance vertex. When the \\underline{search is finished}, variable $count$ will contain the number of moves.\n\nYour task is to count the mathematical expectation of the number of moves one has to do to exit the maze.",
    "tutorial": "Consider what is the expected value for a given entrance and exit vertexes. It is clear that there will be only one path from the entrance to the exit, which in any case will be passed. Also, you can still go in the wrong direction. Consider the case when the chosen vertex from which there is $k$ false paths and one right (it is always). Then before going in the right direction it can be $2^{k}$ equiprobable way around false paths. Every false way occurs the $2^{k - 1}$ ways and to increase the number of moves in $2  \\times  < amount$ $of$ $vertexes$ $in$ $false$ $subtree >$ ie expectation of a false path to increase by $2  \\times  < amount$ $of$ $vertexes$ $in$ $false$ $subtree >  \\times  2^{k - 1} / 2^{k} = < amount$ $of$ $vertexes$ $in$ $false$ $subtree >$. Then expectation in vertex is equal to sum of $< amount$ $of$ $vertexes$ $in$ $false$ $subtrees >$ + 1 (a move in the right direction) + expectation of the vertex if to go the right direction. The result is that the expected value equal to the number of edges reachable from the entrance, without passing through the exit. Let's run dfs and consider of the vertex as exit vertex. Then, if in some subtree defined entrance, the expected value equal to the size of the subtree. Calculate how much of each subtree is the number of entrance and calculate the number of moves, if the exit is in the current vertex. It is necessary not to forget to count cases where the current vertex is an exit and entrance is higher in the tree traversal.",
    "code": "#include <cstdio>\n#include <cmath>\n#include <algorithm>\n#include <ctime>\n\nusing namespace std;\n\n\nconst int MAXN = 100001;\nconst int MAXM = MAXN + MAXN;\n\nint last[MAXN];\nint next[MAXM], dest[MAXM];\nint f[MAXN], g[MAXN], s[MAXN];\n\nint n;\nlong long ans, F, G;\n\nint dfs(int x, int p)\n{\n    s[x] = 1;\n    for (int i = last[x]; i; i = next[i])\n    {\n        int y = dest[i];\n        if (y != p)\n        {\n            dfs(y, x);\n            s[x] += s[y];\n            f[x] += f[y];\n            if (g[x]) ans += (long long)g[x] * s[y] * f[y];\n        }\n    }\n    if (g[x]) ans += (long long)g[x] * (F - f[x]) * (n - s[x]);\n    return 0;\n}\n\nint main()\n{\n    #ifndef ONLINE_JUDGE\n        freopen(\"in\", \"r\", stdin);\n        freopen(\"out\", \"w\", stdout);\n    #endif\n\n    scanf(\"%d\", &n);\n    for (int i = 1; i < n; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n\n        dest[i] = y;\n        next[i] = last[x];\n        last[x] = i;\n\n        dest[i + n] = x;\n        next[i + n] = last[y];\n        last[y] = i + n;\n    }\n\n    F = G = 0;\n    for (int i = 1; i <= n; i++)\n    {\n        scanf(\"%d %d\", &f[i], &g[i]);\n        F += f[i];\n        G += g[i];\n    }\n\n    dfs(1, 0);\n\n    printf(\"%.20lf\n\", (double)ans / (F * G));\n\n    fprintf(stderr, \"Time of execution: %.3lf sec.\n\", (double)clock()/CLOCKS_PER_SEC);\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "probabilities",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "124",
    "index": "A",
    "title": "The number of positions",
    "statement": "Petr stands in line of $n$ people, but he doesn't know exactly which position he occupies. He can say that there are no less than $a$ people standing in front of him and no more than $b$ people standing behind him. Find the number of different positions Petr can occupy.",
    "tutorial": "Let's iterate through the each item and check whether it is appropriate to the conditions $a  \\le  i - 1$ and $n - i  \\le  b$ (for $i$ from $1$ to $n$). The first condition can be converted into $a + 1  \\le  i$, and the condition $n - i  \\le  b$ in $n - b  \\le  i$, then the general condition can be written $max(a + 1, n - b)  \\le  i$ and then our answer can be calculated by the formula $n - max(a + 1, n - b) + 1$.",
    "code": "#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nint n, a, b;\n\nint main()\n{\n    #ifndef ONLINE_JUDGE\n        freopen(\"in\", \"r\", stdin);\n        freopen(\"out\", \"w\", stdout);\n    #endif\n    scanf(\"%d %d %d\", &n, &a, &b);\n    printf(\"%d\n\", n - max(a + 1, n - b) + 1);\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "124",
    "index": "B",
    "title": "Permutations",
    "statement": "You are given $n$ $k$-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.",
    "tutorial": "Let's try all possible ways to rearrange digits in the numbers and check the difference between maximum and minimum number.",
    "code": "#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAXN = 8;\nconst int INF = (int)1e+9;\n\nint a[MAXN][MAXN];\nint n, k;\nint p[MAXN];\nint ans;\n\nint main()\n{\n    #ifndef ONLINE_JUDGE\n        freopen(\"in\", \"r\", stdin);\n        freopen(\"out\", \"w\", stdout);\n    #endif\n    scanf(\"%d %d\n\", &n, &k);\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = 0; j < k; j++)\n        {\n            char c;\n            scanf(\"%c\", &c);\n            a[i][j] = c - '0';\n        }\n        scanf(\"\n\");\n    }\n\n    for (int i = 0; i < k; i++)\n        p[i] = i;\n\n    ans = INF;\n    do\n    {\n        int mi = INF, ma = -INF;\n        for (int i = 0; i < n; i++)\n        {\n            int x = 0;\n            for (int j = 0; j < k; j++)\n                (x *= 10) += a[i][p[j]];\n            ma = max(ma, x);\n            mi = min(mi, x);\n        }\n        ans = min(ans, ma - mi);\n    } while (next_permutation(p, p + k));\n    printf(\"%d\n\", ans);\n    return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "126",
    "index": "A",
    "title": "Hot Bath",
    "statement": "Bob is about to take a hot bath.\n\nThere are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is $t_{1}$, and the hot water's temperature is $t_{2}$. The cold water tap can transmit any integer number of water units per second from $0$ to $x_{1}$, inclusive. Similarly, the hot water tap can transmit from $0$ to $x_{2}$ water units per second.\n\nIf $y_{1}$ water units per second flow through the first tap and $y_{2}$ water units per second flow through the second tap, then the resulting bath water temperature will be:\n\n\\[\nt={\\frac{t_{1}y_{1}+t_{2}y_{2}}{y_{1}+y_{2}}}\n\\]\n\nBob wants to open both taps so that the bath water temperature was not less than $t_{0}$. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible.\n\nDetermine how much each tap should be opened so that Bob was pleased with the result in the end.",
    "tutorial": "At the first you should consider cases when $t_{0} = t_{1}$, $t_{0} = t_{2}$ and $t_{1} = t_{2}$. Answers will be $(x_{1}, 0)$, $(0, x_{2})$ and $(x_{1}, x_{2})$. The last 2 of them didn't present in the pretests. Next, for all $1  \\le  y_{1}  \\le  x_{1}$ you should find minimal $y_{2}$, for that $t(y_{1}, y_{2})  \\ge  t_{0}$. You can do it using one of three ways: binary search, two pointers or just calculation by formula $[y_{1}(t_{0} - t_{1}) / (t_{2} - t_{0})]$, where $[x]$ is rounding up of $x$. You should iterate over all cases and choose one optimal of them. The last tricky case consists in the fact that for all $1  \\le  y_{1}  \\le  x_{1}$ and $1  \\le  y_{2}  \\le  x_{2}$ $t(y_{1}, y_{2}) < t_{0}$. For example, you can see following test 100 110 2 2 109 (it is the 6th pretest). In this case you should output $(0, x_{2})$. All calculations should be done in 64-bit integers (8th pretest checks overflow of 32-bit integers) or very carefully in the real numbers.",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "126",
    "index": "B",
    "title": "Password",
    "statement": "Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.\n\nA little later they found a string $s$, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring $t$ of the string $s$.\n\nPrefix supposed that the substring $t$ is the beginning of the string $s$; Suffix supposed that the substring $t$ should be the end of the string $s$; and Obelix supposed that $t$ should be located somewhere inside the string $s$, that is, $t$ is neither its beginning, nor its end.\n\nAsterix chose the substring $t$ so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring $t$ aloud, the temple doors opened.\n\nYou know the string $s$. Find the substring $t$ or determine that such substring does not exist and all that's been written above is just a nice legend.",
    "tutorial": "Let us calculate a prefix-function for all prefices of string. Prefix-function $p[i]$ is maximal length of prefix that also is suffix of substring $[1...i]$. More about prefix function you can see in a description of Knuth-Morris-Pratt algorithm (KMP). The first of possible answers is prefix of length $p[n]$. If $p[n] = 0$, there is no solution. For checking the first possible answer you should iterate over $p[i]$. If at least one of them equal to $p[n]$ (but not $n$-th, of course) - you found the answer. The second possible answer is prefix of length $p[p[n]]$. If $p[p[n]] = 0$, you also have no solution. Otherwise you can be sure that the answer already found. This substring is a prefix and a suffix of our string. Also it is suffix of prefix with length $p[n]$ that places inside of all string. This solution works in $O(n)$. Also this problem can be solved using hashing. You can find hash of every substring in O(1) and compare substrings by comparing thier hashes. Well, let's check for every prefix that it is a suffix of our string and store thier lengths into some array in the increasing order. Then, using binary search over the array, you can find maximal length of prefix that lie inside of string. Check of every prefix you can do in $O(n)$. So, you have some $O(n\\log n)$ solution. In point of fact, the array of prefix lengths in the previous solution is list { $p[n]$, $p[p[n]],$ ... }, that written if reversed order. From the first solution you know that the answer is prefix of length either $p[n]$, or $p[p[n]] (if it exists, of course)$. Therefore some naive solution without binary search can fits in the limits if you will stupidly check all prefices in the order of decrease thier lengths:) This solution works in $O(n)$. Also this problem can be solved using $z$-function.",
    "tags": [
      "binary search",
      "dp",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "126",
    "index": "C",
    "title": "E-reader Display",
    "statement": "After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers.\n\nThe display is represented by $n × n$ square of pixels, each of which can be either black or white. The display rows are numbered with integers from $1$ to $n$ upside down, the columns are numbered with integers from $1$ to $n$ from the left to the right. The display can perform commands like \"$x, y$\". When a traditional display fulfills such command, it simply inverts a color of $(x, y)$, where $x$ is the row number and $y$ is the column number. But in our new display every pixel that belongs to at least one of the segments $(x, x) - (x, y)$ and $(y, y) - (x, y)$ (both ends of both segments are included) inverts a color.\n\nFor example, if initially a display $5 × 5$ in size is absolutely white, then the sequence of commands $(1, 4)$, $(3, 5)$, $(5, 1)$, $(3, 3)$ leads to the following changes:\n\nYou are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.",
    "tutorial": "You can see that every command $i, j$ you should do no more than once. Also order of commands doesn't matter. Actually, sequence of command you can represent as boolean matrix $A$ with size $n  \\times  n$, where $a_{ij} = 1$ mean that you do the command $i, j$, and $a_{ij} = 0$ mean that you don't do it. Let us describe one way to construct the matrix. Let the starting image is boolean matrix $G$. A boolean matrix $B$ of size $n  \\times  n$ stores intermediate image that you will recieve during process of doing commands. For the upper half of matrix $G$ without main diagonal you should move line by line from the up to the down. For every line you should move from the right to the left. You can see that for every positions all nonconsidered positions do not affect the current position. So, if you see that values for position $i, j$ in the matrices $G$ and $B$ are different, you should do command $i, j$: set in the matrix $A$ $a_{ij} = 1$, and change segments $(i, i) - (i, j)$ and $(j, j) - (i, j)$ in the matrix $B$. For the lower half of the matrix $G$ without main diagonal you should do it absolutely symmetric. At the end you should iterate over main diagonal. Here it should be clear. Well, for matrix $G$ you always can build matrix $A$ and do it by exactly one way. It mean that this way requires minimum number of commands. So, you can get answer for problem by following way: you can build the matrix $A$ from the matrix $G$ and output number of ones in the matrix $A$. There is only one problem that you should solve. Algorithm that you can see above works in $O(n^{3})$, that doesn't fit into time limits. Let's speed up it to $O(n^{2})$. Consider in the matrix $B$ the upper half without main diagonal. During doing commands all columns of cells that placed below current position will have same values. Values above current position are not matter for us. Therefore instead of the matrix $B$you can use only one array that stores values of columns. It allows you do every command in $O(1)$ instead of $O(n)$. This optimization gives a solution that works in $O(n^{2})$.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "126",
    "index": "D",
    "title": "Fibonacci Sums",
    "statement": "Fibonacci numbers have the following form:\n\n\\[\nF_{1} = 1,\n\\]\n\n\\[\nF_{2} = 2,\n\\]\n\n\\[\nF_{i} = F_{i - 1} + F_{i - 2}, i > 2.\n\\]\n\nLet's consider some non-empty set $S = {s_{1}, s_{2}, ..., s_{k}}$, consisting of \\textbf{different} Fibonacci numbers. Let's find the sum of values of this set's elements:\n\n\\[\n\\textstyle\\sum_{i=1}^{k}s_{i}=n\n\\]\n\nLet's call the set $S$ a number $n$'s decomposition into Fibonacci sum.\n\nIt's easy to see that several numbers have several decompositions into Fibonacci sum. For example, for $13$ we have $13, 5 + 8, 2 + 3 + 8$ — three decompositions, and for $16$: $3 + 13, 1 + 2 + 13, 3 + 5 + 8, 1 + 2 + 5 + 8$ — four decompositions.\n\nBy the given number $n$ determine the number of its possible different decompositions into Fibonacci sum.",
    "tutorial": "Let us represent a number in the Fibonacci code. You can imagine Fibonacci coding by following way: $i$-th bit of number corresponds to the $i$-th Fibonacci number. For example, 16=13+3 will be written as 100100. You can represent into this code any positive integer, for that no two neighbouring 1-bit will be present. It is possible to do it by only one way (let's define this way as canonical). In the problem you should calculate a number of ways to represent some number into Fibonacci code in that two ones can be placed in the neighbour positions. You can easily get the canonical representation if you generate several of Fibonacci numbers (about 90) and after that try to substract all of them in the decreasing order. You should store positions of 1-bits of canonical representation into an array $s$ in the increasing order. You can decompose any of them into two ones. It looks like that: 1000000001 // starting number; 0110000001 // there we decompose 0101100001 // the first \"one\" 0101011001 // using all 0101010111 // possible ways After some number of such operations you will meet next 1-bit (or the end of number). This 1-bit also can be decomposed, but it can be \"shifted\" by only one bit. Let us $dp1[i]$ is number of ways to represent a number that consists of $i$ last 1-bits of our number in the case that the first of 1-bits are NOT decomposed. Also let us $dp2[i]$ is number of ways to represent a number that consists of $i$ last 1-bits of our number in the case that the first of 1-bits are decomposed. You can easily recaclulate this dp following way $dp1[0] = 1, dp2[0] = 0$ $dp1[i] = dp1[i - 1] + dp2[i - 1]$ $dp2[i] = dp1[i - 1] * [(s[i] - s[i - 1] - 1) / 2] + dp2[i - 1] * [(s[i] - s[i - 1]) / 2]$ where $[x]$ is rounding down. Answer will be $dp1[k] + dp2[k]$, where $k$ is total number of 1-bits in the canonical representation. So, we have $O(\\log n)$ solution for one test.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "126",
    "index": "E",
    "title": "Pills",
    "statement": "Doctor prescribed medicine to his patient. The medicine is represented by pills. Each pill consists of a shell and healing powder. The shell consists of two halves; each half has one of four colors — blue, red, white or yellow.\n\nThe doctor wants to put $28$ pills in a rectangular box $7 × 8$ in size. Besides, each pill occupies exactly two neighboring cells and any cell contains exactly one half of a pill. Thus, the result is a four colored picture $7 × 8$ in size.\n\nThe doctor thinks that a patient will recover sooner if the picture made by the pills will be special. Unfortunately, putting the pills in the box so as to get the required picture is not a very easy task. That's why doctor asks you to help.\n\nDoctor has some amount of pills of each of $10$ painting types. They all contain the same medicine, that's why it doesn't matter which $28$ of them will be stored inside the box.\n\nPlace the pills in the box so that the required picture was formed. If it is impossible to place the pills in the required manner, then place them so that the number of matching colors in all $56$ cells in the final arrangement and the doctor's picture were maximum.",
    "tutorial": "Consider all partitions of $7  \\times  8 board$ into dominoes. There is only 12988816 of them (you can get this number using some simple bruteforce algorithm) Also, consider all \"paintings\" of $7  \\times  8 board$ (i.e. number of cells of every color) and find number of patritions into set of pills of 10 types for every of them. In the worst case you will get 43044 partitions (this number you can get using another bruteforce algo). In the first part of solution you should iterate over all partitions of board into dominoes and find all sets of pills that you will get. You will have no more than 43044 of them. In the second part of solution you should try to distribute all available pills for every of sets that you recieved in the first part. You should distribute them in such way that maximal number of colors match. You should build a graph that composed from 4 parts - source, the first part of 10 nodes, the second part of 10 nodes and sink. There are edges between all pairs of nodes from neighbour parts. From source to the first part you should set capacities of edges equal to numbers of available pills of every type. From the second part to sink you should set capacities of edges equal to numbers of pills in the current partition. From the first part to the second part you should use infty capacities and set costs equal to number of MISmatched colors in the types of pills (it is some numbers in range from 0 to 2). At the end, you should find maximal flow of minimal cost (MCMF) if this graph and save a flow that gets minimal cost. In the third part of solution you should restore answer from optimal flow. In the second part of solution you can replace MCMF by usual maxflow. You can see that at the beginning MCMF will fill edges of cost 0. So, you can fill them by hand. After that you can drop all edges of cost 0 and 2 and just find maxflow. Complexity of solution is difficult, but it is clear that this solution fits into limits. The first jury solution in C++ that was written carelessly works in 1 sec. Some more clever solutions works in 0.4 sec, but you can write something more faster.",
    "tags": [
      "brute force",
      "flows"
    ],
    "rating": 2900
  },
  {
    "contest_id": "127",
    "index": "A",
    "title": "Wasted Time",
    "statement": "Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.\n\nMr. Scrooge's signature can be represented as a polyline $A_{1}A_{2}... A_{n}$. Scrooge signs like that: first it places a pen at the point $A_{1}$, then draws a segment from point $A_{1}$ to point $A_{2}$, then he draws a segment from point $A_{2}$ to point $A_{3}$ and so on to point $A_{n}$, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — $50$ millimeters per second.\n\nScrooge signed exactly $k$ papers throughout his life and all those signatures look the same.\n\nFind the total time Scrooge wasted signing the papers.",
    "tutorial": "In this problem you should find length of polyline, multiply it by $k / 50$ and output that you will recieve. Length of polyline is sum of lengths of its segments. You can calculate length of every segment using Pythagorean theorem: $d(A,B)={\\sqrt{(x_{A}-x_{B})^{2}+(y_{A}-y_{B})^{2}}}$.",
    "tags": [
      "geometry"
    ],
    "rating": 900
  },
  {
    "contest_id": "127",
    "index": "B",
    "title": "Canvas Frames",
    "statement": "Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with.\n\nNicholas has $n$ sticks whose lengths equal $a_{1}, a_{2}, ... a_{n}$. Nicholas does not want to break the sticks or glue them together. To make a $h × w$-sized frame, he needs two sticks whose lengths equal $h$ and two sticks whose lengths equal $w$. Specifically, to make a square frame (when $h = w$), he needs four sticks of the same length.\n\nNow Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.",
    "tutorial": "Idea of this problem was offered by RAD. It was the last problem in the problemset and I had no any easy idea:) I thank him for it. Here you should calculate an array $cnt[100]$. $i$-th element of it stores number of sticks whose lengths equal $i$. Now you should calculate number of pairs of sticks of equal lengths. This number is $k=\\sum_{i=1}^{100}[c n t[a]/2]$, where $[x]$ is floor of $x$. For every frame you need 2 if such pairs and you can choose it in any order. Therefore the answer will be $z = [k / 2].$",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "128",
    "index": "B",
    "title": "String",
    "statement": "One day in the IT lesson Anna and Maria learned about the lexicographic order.\n\nString $x$ is lexicographically less than string $y$, if either $x$ is a prefix of $y$ (and $x ≠ y$), or there exists such $i$ ($1 ≤ i ≤ min(|x|, |y|)$), that $x_{i} < y_{i}$, and for any $j$ ($1 ≤ j < i$) $x_{j} = y_{j}$. Here $|a|$ denotes the length of the string $a$. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​.\n\nThe teacher gave Anna and Maria homework. She gave them a string of length $n$. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string \"aab\": \"a\", \"a\", \"aa\", \"ab\", \"aab\", \"b\"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the $k$-th string from the list. Help Anna and Maria do the homework.",
    "tutorial": "Impossibility Let us denote the sequence by $a_{1}, ..., a_{n}$ and assume it has been sorted already. We can note immediately that there are some easy cases we can rule out. If $n$ is odd, by a parity argument it is impossible. Moreover, let $m = a_{n} - a_{1}$, i.e. the range of the values. If $m = 0$ it is impossible since $n  \\ge  3$, and if $m > n / 2$ it is impossible since we cannot get from $a_{1}$ to $a_{n}$ and back going around the circle. Now that these cases are out of the way we move on to the actual algorithm. Transformation It's natural to transform the input we're given into a form that's easier to work with, i.e. a histogram. As such, we define $c_{i}$ to be the number of values $a_{j}$ with $a_{j} - a_{1} = i$ for $i = 0, 1, ..., m$. Now we replace each $a_{i}$ with $a_{i} - a_{1}$ so that they are all in the range $[0, m]$. Observation A nice observation we can make about any valid sequence is the following. Consider the positions of any $0$ and any $m$ in the circle. There are two paths from $0$ to $m$. We observe that if any valid sequence exists, then there exists one for which, along each of these paths, the value never decreases twice in a row (that is, we can think of each path as \"increasing\" with some oscillation). Suppose this does happen in our sequence, i.e. we have something like $0, 1, ..., i - 1, i, i - 1, ..., j + 1, j, j + 1, ..., m - 1, m$ where $j < i - 1$ so $i, i - 1, ..., j + 1, j$ is the decreasing sequence. Then we note that $j + 1$ appeared somewhere between $0$ and $i$, so we can take the values $j, j + 1$ and move them directly after the $j + 1$ that was between $0$ and $i$ (easy to see that the sequence is still valid). Repeating this for whenever we have a decrease of two or more gives us paths that never decreases twice in a row. Validation Now with our transformation and observation, we can come up with the method of checking whether or not the histogram can produce a valid sequence. To do so, first place a $0$ on the circle. Then we have $L = c_{0} - 1$ zeros left to place. Note, however, that each zero must be adjacent to a one. So in fact there must be at least $L + 2$ ones to \"hide\" all of the zeros from the rest of the numbers (one on each side and one for each additional zero). If there are fewer than that many, it is impossible. After placing the remaining zeros and ones arbitrarily (but alternating) on each side of the initial $0$, we see that there are $L = c_{1} - (L + 2)$ ones remaining. By the same argument, we know how many twos there must be (again, $L + 2$). We can continue like this until we get to $m$. If there are $L$ remaining values of $m - 1$, we need $c_{m} = L + 1$ to complete the circle (one to be the \"end\" and one for each additional $m - 1$). If this is true, then it is possible and otherwise it is not. Note that the above placement strategy works because of the observation we made (we know we can use the small numbers greedily) and the fact that it doesn't matter how many of each number we put in each path as long as they end in the same value.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "hashing",
      "implementation",
      "string suffix structures",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "131",
    "index": "A",
    "title": "cAPS lOCK",
    "statement": "wHAT DO WE NEED cAPS LOCK FOR?\n\nCaps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.\n\nLet's consider that a word has been typed with the Caps lock key accidentally switched on, if:\n\n- either it only contains uppercase letters;\n- or all letters except for the first one are uppercase.\n\nIn this case we should automatically change the case of all letters. For example, the case of the letters that form words \"hELLO\", \"HTTP\", \"z\" should be changed.\n\nWrite a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.",
    "tutorial": "Just do what the statement asks you to. Check if all letters are uppercase, except for the first one, that you don't need to check. If so, change the case of the entire string. If not, do nothing. Please notice that an one-letter string must have its case changed. It can be easly done in O(n), where n is the lenght of the string.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "131",
    "index": "B",
    "title": "Opposites Attract",
    "statement": "Everybody knows that opposites attract. That is the key principle of the \"Perfect Matching\" dating agency. The \"Perfect Matching\" matchmakers have classified each registered customer by his interests and assigned to the $i$-th client number $t_{i}$ ($ - 10 ≤ t_{i} ≤ 10$). Of course, one number can be assigned to any number of customers.\n\n\"Perfect Matching\" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of $t$. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence $t_{1}, t_{2}, ..., t_{n}$. For example, if $t = (1, - 1, 1, - 1)$, then any two elements $t_{i}$ and $t_{j}$ form a couple if $i$ and $j$ have different parity. Consequently, in this case the sought number equals 4.\n\nOf course, a client can't form a couple with him/herself.",
    "tutorial": "First, let count(i) be the numbers of occurrences of the number i in the input, for -10 <= i <= 10. Remember that there may be negative numbers in the input, so one can use an offset to store these values (use an 21-sized array C and store count(i) in C[i+10]). Except for 0, possible matching are pairs (i,-i), for 1 <= i <= 10. It's easy to see that there will be exactly count(i)*count(-i) valid matching for each i, so just sum them all. Since 0 \"is opposite to itself\", but \"a client can't form a couple with him/herself\", the number of valid pairs (0,0) will be (count(0) 2). Just sum this value to the previous computed sum and print. Use 64 bits-types to do the math.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "131",
    "index": "C",
    "title": "The World is a Theatre",
    "statement": "There are $n$ boys and $m$ girls attending a theatre club. To set a play \"The Big Bang Theory\", they need to choose a group containing exactly $t$ actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different.\n\nPerform all calculations in the 64-bit type: long long for С/С++, int64 for Delphi and long for Java.",
    "tutorial": "Since the constraints are small, let's just iterate through all possible numbers b of boys in the group and count how many ways we can form the group with b boys. First, consider only the values where b >= 4. Given b, it's clear that the number of girls in the group must be g = t - b. If g < 1, don't consider this case. Given the values of b and g, there are (n b)*(m g) ways to form the group, since we can combine the boys independently the girls. Just sum (n b)*(m g) for each pair (b,g). Again, use 64 bits-types to do the math. One could precompute all the values of (i j) using the Pascal triangle, but one could also compute it with the traditional formula, if its implementation takes care of possible overflow (30! doesn't fit in 64-bit integer type).",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "131",
    "index": "D",
    "title": "Subway",
    "statement": "A subway scheme, classic for all Berland cities is represented by a set of $n$ stations connected by $n$ passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.\n\nBerland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.\n\nThis invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say \"I live in three passages from the ringroad\" and another one could reply \"you loser, I live in one passage from the ringroad\". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).\n\nThe Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.",
    "tutorial": "A graph-related problem. The statement makes you sure that the given graph is connected and contains one (and exactly one) cycle. What you have to do is to compute the distance, in number of edges, from all vertexes to the cycle (print 0 for the vertex that are in the cycle. We will call these vertexes 'in-cycle'). First, let's find the cycle and find the vertexes whose answer is 0. The cycle can be found with a regular Depth-First-Search (DFS), storing the fathers of the vertexes. Notice that, during the search, there will be exactly one back edge, say (vi, vj). When this edge is found, iterate from vi to vj (using the father array) and label the vertexes as 'in-cycle'. After that, let's compute the answers for the other vertexes. One could \"compact\" the graph by merging all the 'in-cycle' vertexes into a single vertex. Then, just do another search starting by this vertex and compute the distances, knowing that the distance of a vertex vi is the distance of father[vi] plus one. Also, it's also possible to do as many searchs as the number of 'in-cycle' vertexes if you don't consider others 'in-cycle' vertexes during the search. The running time would still be O(n + m), that, in this problem, is O(n + n) = O(n).",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1600
  },
  {
    "contest_id": "131",
    "index": "E",
    "title": "Yet Another Task with Queens",
    "statement": "A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.\n\nThere are $m$ queens on a square $n × n$ chessboard. You know each queen's positions, the $i$-th queen is positioned in the square $(r_{i}, c_{i})$, where $r_{i}$ is the board row number (numbered from the top to the bottom from 1 to $n$), and $c_{i}$ is the board's column number (numbered from the left to the right from 1 to $n$). No two queens share the same position.\n\nFor each queen one can count $w$ — the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen $w$ is between 0 and 8, inclusive.\n\nPrint the sequence $t_{0}, t_{1}, ..., t_{8}$, where $t_{i}$ is the number of queens that threaten exactly $i$ other queens, i.e. the number of queens that their $w$ equals $i$.",
    "tutorial": "Let's first consider that the queens can only attack the other pieces standing in the same line - the case with the columns and both diagonals will be analogous. Let line[i] be an array that will store all the queens that are in the i-th line on the chessboard. Since it's indexed by the line number, it's only necessary to store the column number of the pieces. So, for example, if we have queens at positions (4,6), (4,8) and (6,5), we will have line[4] = {6,8} and line[6] = {5}. To check if the queen at position (i,j) is attacking someone in its line, you must check if there is some number greater than j and/or less than j in line[i]. To do that, presort line[i] and binary search j in it. Notice that j will always be successful found by the search. Notice also that there will be some number greater than j iff the found element is not the last one of line[i]. The same applies for the other case: check if j is not the first element of line[i]. If j is not the first nor the last element, the queen is attacking 2 pieces in its line. If j is the only element, the queen is attacking no one, and it's attacking 1 piece otherwise. Do the same thing (compute all column[i], sort them and, for each queen, binary search) to the column, to the \"/\" diagonal, and to the \"\\\" diagonal. Remember that a piece at position (i,j) is at the diagonals i+j and i-j. Like in problem B, use an offset to handle the negative numbers in the last case. Store the line number in the column[i] array. There's no different in witch index (line or column) to use in the diagonals arrays (but, of course, use the same chosen index for everyone). It seems that the sorting part of the algorithm will run in O(n*n*logn) time, since we have O(n) lines, columns and diagonals. However, the sum of the sizes of all these arrays will be m, the numbers of queens. So the running time will be actually near O(m*logm). Binary searching for every queen will take less than O(m*logm), too.",
    "tags": [
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "131",
    "index": "F",
    "title": "Present to Mom",
    "statement": "How many stars are there in the sky? A young programmer Polycarpus can't get this question out of his head! He took a photo of the starry sky using his digital camera and now he analyzes the resulting monochrome digital picture. The picture is represented by a rectangular matrix consisting of $n$ lines each containing $m$ characters. A character equals '1', if the corresponding photo pixel is white and '0', if it is black.\n\nPolycarpus thinks that he has found a star on the photo if he finds a white pixel surrounded by four side-neighboring pixels that are also white:\n\n\\begin{center}\n\\begin{verbatim}\n1\n111\n1\n\\end{verbatim}\n\n{\\small a star on the photo}\n\\end{center}\n\nPolycarpus whats to cut out a rectangular area from the photo and give his mom as a present. This area should contain no less than $k$ stars. The stars can intersect, have shared white pixels on the photo. The boy will cut out the rectangular area so that its borders will be parallel to the sides of the photo and the cuts will go straight between the pixel borders.\n\nNow Polycarpus keeps wondering how many ways there are to cut an area out of the photo so that it met the conditions given above. Help Polycarpus find this number.",
    "tutorial": "The main idea is to, for each pair of lines i1 and i2, count the ways you can form the rectangle using a sweep line-like algorithm. The idea is similar to the somewhat classic idea used for the problem that is, given an array of numbers, count how many contiguous sub arrays exists witch sum is equal or greater to some given k. Let's first of all identify all the points where a star can be found, in its \"starting\" position and \"finish\" position. These are the S and F position shown below. 1 S1F 1 For each pair of lines i1 and i2 (i2 > i1) we will keep two indices (or pointers) j1 and j2 for the columns, with j2 > j1. During the algorithm, we will always analyze the rectangle formed by lines i1,i2 and columns j1,j2. Let's start with j1 = 0 and j2 = 2 (there won't be any star in the rectangle i1,i2,0,(0 or 1) simply because a star won't fit in it). Let's then count the number of stars found in this rectangle. It will be equal to countfinish(i1+1,i2-1,j2), where countfinish(I1,I2,J) is the number of \"finish\" positions in the column J between the lines I1 and I2. If this number is equal or greater than k, this rectangle and all the rectangles (i1,i2,j1,j) for j >= j2 will be valid, so you need to sum m-j2 to the answer. Then, increment j1 and recalculate the numbers of stars in the rectangle. It will be equal to the previous number minus countstart(i1+1,i2-1,j1-1), (the definition of countstart() is analogous) since it's the number of starts that are \"lost\" when we move from j1-1 to j1. Check again if the new number is greater or equal than k and repeat the process until the number is less than k. Notice that j1 will always be less than j2, since a star needs 3 columns to exists. Then, increment j2 and, without changing the value of j1, repeat the process. Notice that this part of the algorithm will take O(m)*T time (where T is the time needed to calculate countstart and countfinish), since both j2 and j1 will \"walk\" in the columns only one time. A trick can be made to make T = O(1). For each column j, precompute an array countstart[j], where countstart[j][i] = countstart[j][i-1] + (1 if (i,j) is a \"starting\" position, 0 otherwise). To compute countstart(I1,I2,J), just use the formula countstart[J][I2] - countstart[J][I1-1], that gives the value in constant time. Do the same with countfinish. Precomputing countstart and countfinish takes, for each column, O(n) time, so all the precomputing can be done in O(n*m) time. Since we use an O(m)*O(1) = O(m) time for O(n2) pairs of lines, the total time used for the algorithm is O(n*m) + O(n2*m) = O(n2*m). A bit high for n=m=500, but the time limit for this problem was higher than the usual too (5 seconds instead of 2).",
    "tags": [
      "binary search",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "132",
    "index": "A",
    "title": "Turing Tape",
    "statement": "INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.\n\nThe integers of the array are processed one by one, starting from the first. Processing $i$-th element of the array is done in three steps:\n\n1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.\n\n2. The $i$-th element of the array is subtracted from the result of the previous step modulo 256.\n\n3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the $i$-th character to be printed.\n\nYou are given the text printed using this method. Restore the array used to produce this text.",
    "tutorial": "This was another implementation problem, inspired by another great language INTERCAL. Technically it was a bit more complicated than the previous one, due to the usage of byte reversal and having to implement not the described procedure but its inverse. For i-th character of input data reverse it and store in $rev[i]$; then i-th number of the output can be calculated as $(rev[i - 1] - rev[i] + 256)%256$ (for $i = 0$ $rev[i - 1] = 0$).",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "132",
    "index": "B",
    "title": "Piet",
    "statement": "Piet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules.\n\nThe program will be a rectangular image consisting of colored and black pixels. The color of each pixel will be given by an integer number between 0 and 9, inclusive, with 0 denoting black. A block of pixels is defined as a rectangle of pixels of the same color (not black). It is guaranteed that all connected groups of colored pixels of the same color will form rectangular blocks. Groups of black pixels can form arbitrary shapes.\n\nThe program is interpreted using movement of instruction pointer (IP) which consists of three parts:\n\n- current block pointer (BP); note that there is no concept of current pixel within the block;\n- direction pointer (DP) which can point left, right, up or down;\n- block chooser (CP) which can point to the left or to the right from the direction given by DP; in absolute values CP can differ from DP by 90 degrees counterclockwise or clockwise, respectively.\n\nInitially BP points to the block which contains the top-left corner of the program, DP points to the right, and CP points to the left (see the orange square on the image below).\n\nOne step of program interpretation changes the state of IP in a following way. The interpreter finds the furthest edge of the current color block in the direction of the DP. From all pixels that form this edge, the interpreter selects the furthest one in the direction of \\textbf{CP}. After this, BP attempts to move from this pixel into the next one in the direction of DP. If the next pixel belongs to a colored block, this block becomes the current one, and two other parts of IP stay the same. It the next pixel is black or outside of the program, BP stays the same but two other parts of IP change. If CP was pointing to the left, now it points to the right, and DP stays the same. If CP was pointing to the right, now it points to the left, and DP is rotated 90 degrees clockwise.\n\nThis way BP will never point to a black block (it is guaranteed that top-left pixel of the program will not be black).\n\nYou are given a Piet program. You have to figure out which block of the program will be current after $n$ steps.",
    "tutorial": "As you've already noticed, Piet differs from most other esoteric programming languages in the way it interprets the image - the problem offered a very simplified version of it, and still it was quite cruel. The first step of the solution is finding colored blocks. Given that they are rectangular, this can be done without BFS; once you've found a colored pixel which is not part of any block you've seen before, you just find the maximal contiguous sequence of pixels of the same color in the same line that starts with this pixel, and assume that it's horizontal dimension of its block. ............ ..X----->... ..|XXXXXX... ..vXXXXXX... ............ I found it convenient to index the blocks and store their colors and dimensions at this point, so that this doesn't need to be re-done later. After this I calculated \"state transition function\" - a function which for each state of instruction pointer defined the next state. The IP has at most 50x50x4x2 states, and they can be indexed with 8*(index of current block) + 2*(direction pointer) + (block chooser). Thus, the transition function can be described with a one-dimensional array (index is current state of IP, and value is the next one), and the simulation of interpretation steps becomes just updating the current state of IP, which is easier than repeating the full procedure described in the statement on each step. It was also possible to note that at some point there will be a loop in the states of the IP, since the maximal possible number of distinct states is less than the number of steps to be done. But exploiting this wasn't necessary.",
    "tags": [
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "132",
    "index": "C",
    "title": "Logo Turtle",
    "statement": "A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands \"T\" (\"turn around\") and \"F\" (\"move 1 unit forward\").\n\nYou are given a list of commands that will be given to the turtle. You have to change exactly $n$ commands from the list (one command can be changed several times). How far from the starting point can the turtle move after it follows \\textbf{all} the commands of the modified list?",
    "tutorial": "This was the only problem of the round which featured a non-esoteric language. The solution is dynamic programming, and it could be used in several ways. My solution was to store two three-dimensional arrays: the leftmost and the rightmost position of a turtle after it used I commands from the list, made J changes in these commands and is now facing direction K. The initial condition is that left=right=0 when I = J = 0 and the turtle faces right (the initial direction can be chosen arbitrarily). The rule of moving between states is: if currently executed command is T (either it is the current command of the list and no change is done, or it is a result of a change), the coordinate stays the same and the direction changes; otherwise the direction stays the same and the coordinate changes accordingly to the direction. It's convenient to do at most one change for each command; in this case after all the arrays are calculated, one has to take the maximal absolute value among all distances which use all commands from the list, all facing directions of the turtle and all quantities of changes which have the same parity as the required quantity (any command can be changed an even number of times without affecting the result).",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "132",
    "index": "D",
    "title": "Constants in the language of Shakespeare",
    "statement": "Shakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare.\n\nEach constant in Shakespeare is created from non-negative powers of 2 using arithmetic operations. For simplicity we'll allow only addition and subtraction and will look for a representation of the given number which requires a minimal number of operations.\n\nYou are given an integer $n$. You have to represent it as $n = a_{1} + a_{2} + ... + a_{m}$, where each of $a_{i}$ is a non-negative power of 2, possibly multiplied by -1. Find a representation which minimizes the value of $m$.",
    "tutorial": "Two last problems of the round were inspired by Shakespeare programming language. The original idea was to make them one problem - \"How to print the given sequence using as few adjectives as possible?\". But later we came to our senses and split this monster of a problem in two. The evident greedy solution (break the binary notation into contiguous groups of 1s, if the size of the group is 1, write it as a single power, otherwise write it as a difference of two powers) is wrong. You can see this from test 4 \"10110111\": the greedy solution will return 5 ($+ 2^{7} + 2^{6} - 2^{4} + 2^{3} - 2^{0}$), while it's possible to find a notation of size 4 ($+ 2^{8} - 2^{6} - 2^{4} - 2^{1}$). The correct solution is based on the following idea. Let us have a fragment of binary notation which contains bits for powers of 3 between N and M (N < M), inclusive, which has K 0s and L 1s. It can be written as a sum of powers which correspond to positions of 1s, using L powers. Alternatively, it can be written as $2^{M + 1} - 2^{N} - ...$, where ... are powers which correspond to positions of 0s, using 2 + K powers. It's evident that using second method makes sense only if the fragment starts and ends with 1s (otherwise it can be used for shorter fragment without the leading/trailing 0s, and save at least one power on this) and contains no 00 sequence inside (otherwise you can break the fragment into two in place of these 00 and write these fragments separately with the same or better result). After you've noted this, you can solve the problem using DP: for each position in binary notation store the sign \"write it as sum of powers or as difference of powers\", and in second case store the length of the fragment which is written using difference (storing the length of the fragment which is written using sums only is unnecessary, since this can be done for individual bits with the same result as for longer fragments.",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "133",
    "index": "A",
    "title": "HQ9+",
    "statement": "HQ9+ is a joke programming language which has only four one-character instructions:\n\n- \"H\" prints \"Hello, World!\",\n- \"Q\" prints the source code of the program itself,\n- \"9\" prints the lyrics of \"99 Bottles of Beer\" song,\n- \"+\" increments the value stored in the internal accumulator.\n\nInstructions \"H\" and \"Q\" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.\n\nYou are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.",
    "tutorial": "The problem described HQ9+ programming language and asked whether the given program will print anything. Given the extraordinary simplicity of the language, it was enough to check whether the program contains at least one of the characters H, Q and 9.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "133",
    "index": "B",
    "title": "Unary",
    "statement": "Unary is a minimalistic Brainfuck dialect in which programs are written using only one token.\n\nBrainfuck programs use 8 commands: \"+\", \"-\", \"[\", \"]\", \"<\", \">\", \".\" and \",\" (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm. First, replace each command with a corresponding binary code, using the following conversion table:\n\n- \">\" $ → $ 1000,\n- \"<\" $ → $ 1001,\n- \"+\" $ → $ 1010,\n- \"-\" $ → $ 1011,\n- \".\" $ → $ 1100,\n- \",\" $ → $ 1101,\n- \"[\" $ → $ 1110,\n- \"]\" $ → $ 1111.\n\nNext, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally, write this number using unary numeral system — this is the Unary program equivalent to the original Brainfuck one.\n\nYou are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it modulo $1000003$ $(10^{6} + 3)$.",
    "tutorial": "A lovely language Brainfuck has dialects for literally every occasion; I guess one could write a whole round about it (not Unknown Language Round, of course, it's too well-known for it), but this time I used it in one problem only. The solution is quite simple: all you have to do is to follow the described procedure of transforming code from Brainfuck to Unary. If your language has built-in long arithmetics, the solution is straightforward: replace characters of each type with corresponding binary codes, convert the resulting string into a long integer and take it modulo 1000003. Having no long arithmetics is not a big deal either. The program can be created step by step, adding one character at a time from left to right. On each step the length of the program is multiplied by 16 (the binary code added has length of 4 bits), then the code of the current character is added and the result is taken modulo 1000003, so that the result never gets really large.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "135",
    "index": "A",
    "title": "Replacement",
    "statement": "Little Petya very much likes arrays consisting of $n$ integers, where each of them is in the range from $1$ to $10^{9}$, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from $1$ to $10^{9}$, inclusive. It is \\textbf{not allowed} to replace a number with itself or to change no number at all.\n\nAfter the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.",
    "tutorial": "If the largest number in our array is equal to 1 then let's replace it with 2, otherwise let's replace it with 1. After that let's sort the array and output it. It is easy to see that the array obtained in that way is the one we are looking for. The complexity is $O(NlogN)$.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "135",
    "index": "B",
    "title": "Rectangle and Square",
    "statement": "Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures \\textbf{do not have} to be parallel to the coordinate axes, though it might be the case.",
    "tutorial": "Let's iterate over all partitions of our set of 8 points into two sets of 4 points. We want to check whether the first set forms a square and the second set forms a rectangle. To check if 4 points lay at the vertexes of a rectangle one can iterate over all permutations of the last 3 points. Then one need to ensure that every two consecutive sides intersect at a 90 degrees angle. That can be done using the fact that the scalar product of two vectors is equal to 0 iff they intersect at a 90 degrees angle. To check if 4 points lay at the vertexes of a square one can check whether they lay at the vertexes of a rectangle and ensure that two consecutive sides have equal length.",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "135",
    "index": "C",
    "title": "Zero-One",
    "statement": "Little Petya very much likes playing with little Masha. Recently he has received a game called \"Zero-One\" as a gift from his mother. Petya immediately offered Masha to play the game with him.\n\nBefore the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01\\textbf{010}101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 01\\textbf{00}101.\n\nThe game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.\n\nAn unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.",
    "tutorial": "First, let's solve the problem when there are no spoiled cards. Let a be the number of ones and b be the number of zeroes. It is easy to see that if a < b then the outcome is 00, because the first player can always remove ones until they are over, which will happen before the end of the game regardless of the second player's moves. Similarly, if a > b + 1 then the outcome is 11. If a = b or a = b + 1 then the outcome is either 01 or 10. That's because the first player will always remove ones, because otherwise the outcome will be 00 which is worse than any other outcome for him. Similarly, the second player will always remove zeroes. One may notice that the first player can always remove the first card to the left with 1 written on it, because it won't make the outcome worse for him. Similarly, the second player can always remove the first card to the left with 0 written on it. That means that the last card won't be removed by anyone. Thus is the last card is 1 then the outcome is 01, otherwise it is 10. We've learned how to solve the problem is there are no '?' signs. Now, suppose that the number of ones is a, the number of zeroes is b and the number of question signs is c. To check if the outcome 00 is possible, one can simply replace all question signs with zeroes and use the previous result, i.e. check if a < b + c. Similarly, the outcome 11 is possible is a + c > b + 1. Let's show how to check if the outcome 01 is possible. If the last character of the string is 0, then the string is not possible. If the last character is ? then we can replace it with 1, i.e. decrease c by 1 and increase a by 1. Suppose we want to replace x question signs with one and c - x question signs with zero. Then the following equality must hold: x + a = b + c - x + (a + b + c) mod 2. Thus, x = (b + c - a + (a + b + c) mod 2) / 2. If the resulting value of x is non-negative and is not greater than c, then the outcome 01 is possible, otherwise it is not possible. We can check if the outcome 10 is possible in the similar way. The complexity is $O(N)$.",
    "tags": [
      "constructive algorithms",
      "games",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "135",
    "index": "D",
    "title": "Cycle",
    "statement": "Little Petya very much likes rectangular tables that consist of characters \"0\" and \"1\". Recently he has received one such table as a gift from his mother. The table contained $n$ rows and $m$ columns. The rows are numbered from top to bottom from $1$ to $n$, the columns are numbered from the left to the right from $1$ to $m$. Petya immediately decided to find the longest cool cycle whatever it takes.\n\nA cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously:\n\n- The cycle entirely consists of the cells that contain \"1\".\n- Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle.\n- Each cell of the table that contains \"1\" either belongs to the cycle or is positioned outside of it (see definition below).\n\nTo define the notion of \"outside\" formally, let's draw a cycle on a plane. Let each cell of the cycle $(i, j)$ ($i$ is the row number, $j$ is the column number) correspond to the point $(i, j)$ on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell $(r, c)$ lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates $(r, c)$ lies in the part with the infinite area.\n\nHelp Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle.",
    "tutorial": "One can notice that the only possible variant of a cool cycle which doesn't have zeroes inside it is a 2x2 square of ones. This case should be checked separately. From this point we'll assume that the cool cycle we are looking for contains at least one '0' inside it. Let's take any zero from the table. If it is adjacent to another zero by a side or a corner then it can't lay inside a cool cycle which doesn't have any other zeroes inside it. Thus, this zero can lay inside a cool cycle only together with all zeroes adjacent to it. Generalizing this fact one can show that the zero can lay inside a cool cycle only together with all zeroes reachable from it. We'll assume that one zero is reachable from another zero if they can be connected with a path which consists only of zeroes and in which every two consecutive cells share either a side or a corner. Let's find all the connected components of zeroes. Two zeroes are connected if they share either a side or a corner. If the component of zeroes has a cell adjacent to a border of the table, then it can't lay inside any cool cycle and thus it should be ignored. After that for each connected component of zeroes let's find all cells with 1, adjacent to it. By the statement all those cells should be connected. Also, each cell from this set should share a common side with exactly two other cells from the set. Note that if the set of cells with '1' satisfy those restrictions, then it forms a cycle which doesn't contain any other cells with '1' inside it. The above algorithm has the complexity $O(NM)$, if implemented carefully.",
    "tags": [
      "brute force",
      "dfs and similar",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "135",
    "index": "E",
    "title": "Weak Subsequence",
    "statement": "Little Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to $k$. However, the voucher has a string type limitation: specifically, the voucher can be used to purchase string $s$ if the length of string's longest substring that is also its weak subsequence (see the definition given below) equals $w$.\n\nString $a$ with the length of $n$ is considered the weak subsequence of the string $s$ with the length of $m$, if there exists such a set of indexes $1 ≤ i_{1} < i_{2} < ... < i_{n} ≤ m$, that has the following two properties:\n\n- $a_{k} = s_{ik}$ for all $k$ from $1$ to $n$;\n- there exists at least one such $k$ ($1 ≤ k < n$), for which $i_{k + 1} – i_{k} > 1$.\n\nPetya got interested how many different strings are available for him to purchase in the shop. As the number of strings can be very large, please find it modulo $1000000007$ ($10^{9} + 7$). If there are infinitely many such strings, print \"-1\".",
    "tutorial": "Let cool substring be the substring which is also a weak subsequence. The main observation is that the longest cool substring in any string is either its prefix or its suffix. Moreover, if, for example, it is a prefix then it can be found in the following way. Let's start moving from the end of the string towards the beginning and memorize all characters met on our way. We'll stop after some character appear in the second time. The prefix with the end in the position where we stopped is the one we are looking for. Let's count the number of strings in which the longest cool substring is a suffix. First, we will iterate over the number of characters at the beginning of the string lying before the second appearance of some character. Let this number be t. Obviously, t is not greater than k, because all characters in the prefix of length t are distinct. We need to consider the following two cases: 1. If $t  \\le  w - 1$. The first t characters of a resulting string are distinct, then there is a character which was present among the first t characters. After it there are w - 1 more characters. One should also consider that the last t characters are distinct, otherwise prefix of length greater than w will be also a weak subsequence. Thus, the corresponding summand is equal to $\\frac{t k!^{2}k^{\\omega-t-1}}{(k-t)^{2}}$. 2. If $t > w - 1$. The first t characters of a resulting string are distinct, then there is a character which was present among the first t characters. The last t characters should be distinct, but at this time the suffix of t characters overlaps with the prefix of t characters. The corresponding summand is equal to $\\frac{k!\\cdot w\\cdot(k-t+w-1)!}{(k-t)!^{2}}$. After adding up everything for all t from 1 to k we will obtain the number of strings in which the longest cool substring is a suffix of length w. Similarly, we can find the number of strings in which the longest cool substring is a prefix. The only difference is that we should make sure that the first t + 1 characters of those strings are distinct in order to avoid a double-counting of the strings in which the first and the last t characters are distinct. Considering this the formulas are: 1. If $t + 1  \\le  w - 1$, then the summand is equal to $\\frac{t\\cdot k!^{2}\\cdot k^{w-t}-2}{k-t}$. 2. If $t + 1 > w - 1$, then the summand is equal to $\\frac{k!\\cdot(w-1)\\cdot(k-t+w-2)!}{(k-t)!.(k-t-1)!}$. The only thing left is to add up everything for all t from 1 to k - 1. To calculate the above formula quickly one need to precompute factorials for all numbers from 1 to k and they inverse modulo 109+7. The complexity is either $O(K)$ or $O(K \\cdot  log(MOD))$, depending on the way of computing inverse values to the factorials. As a bonus for those who made it to the end of the editorial, I'll describe a simple linear time algorithm of finding inverse values for all integers between 1 and N modulo prime number P (P > N). I think it will be useful for those who didn't hear about this trick. Let's consider an obvious equality (% means a remainder of division) and perform a few simple operations with it. $P^{9}\\!y_{0}i=P-\\lfloor{\\frac{P}{i}}\\rfloor\\cdot i$ $P^{9}\\!\\vartheta\\cdot\\!\\lbrack\\equiv-\\lbrack{\\textstyle\\frac{P}{i}}\\rbrack\\cdot i(m o d P)$ $i\\equiv-(P\\nabla_{0i})\\cdot\\lfloor{\\frac{P}{i}}\\rfloor^{-1}(m o d P)$ $i^{-1}\\equiv-(P\\nabla_{c i})^{-1}\\cdot\\,\\lfloor{\\frac{P}{i}}\\rfloor(m o d P)$ Thus, in order to compute $i^{ - 1}$ we only need to know $(P%i)^{ - 1}$, which is less than $i$. That means we can compute inverse values successively for all integers between 1 and $N$ in $O(N)$ time.",
    "tags": [
      "combinatorics"
    ],
    "rating": 3000
  },
  {
    "contest_id": "136",
    "index": "A",
    "title": "Presents",
    "statement": "Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited $n$ his friends there.\n\nIf there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from $1$ to $n$. Petya remembered that a friend number $i$ gave a gift to a friend number $p_{i}$. He also remembered that each of his friends received exactly one gift.\n\nNow Petya wants to know for each friend $i$ the number of a friend who has given him a gift.",
    "tutorial": "In this problem one had to read a permutation and output the inverse permutation to it. It can be found with the following algorithm. When reading the i-th number, which is equal to a one can store i into the a-th element of the resulting array. The only thing left is to output this array. The complexity is $O(N)$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "136",
    "index": "B",
    "title": "Ternary Logic",
    "statement": "Little Petya very much likes computers. Recently he has received a new \"Ternatron IV\" as a gift from his mother. Unlike other modern computers, \"Ternatron IV\" operates with ternary and not binary logic. Petya immediately wondered how the $xor$ operation is performed on this computer (and whether there is anything like it).\n\nIt turned out that the operation does exist (however, it is called $tor$) and it works like this. Suppose that we need to calculate the value of the expression $a tor b$. Both numbers $a$ and $b$ are written in the ternary notation one under the other one ($b$ under $a$). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: $14_{10} tor 50_{10} = 0112_{3} tor 1212_{3} = 1021_{3} = 34_{10}$.\n\nPetya wrote numbers $a$ and $c$ on a piece of paper. Help him find such number $b$, that $a tor b = c$. If there are several such numbers, print the smallest one.",
    "tutorial": "It is easy to see that the answer is always unique. Let's consider an operation which is opposite to tor. From each ternary digit of c we will subtract a corresponding digit of a and take a result modulo 3. We'll obtain a number b which has the following property: a tor b = c. The complexity is $O(logC + logA)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "137",
    "index": "A",
    "title": "Postcards and photos",
    "statement": "Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put \\textbf{all} the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?",
    "tutorial": "We will move from the left of string to the right. When we passed the whole string, or in the hands of us have 5 pieces, or current object is different from what we hold in our hands, we remove all the items in the pantry. The answer to the problem is the number of visits to the pantry. The complexity is O(n).",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "137",
    "index": "B",
    "title": "Permutation",
    "statement": "\"Hey, it's homework time\" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.\n\nThe sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.\n\nYou are given an arbitrary sequence $a_{1}, a_{2}, ..., a_{n}$ containing $n$ integers. Each integer is not less than $1$ and not greater than $5000$. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).",
    "tutorial": "We can count the number of integers from 1 to n, which occur in sequence at least once. Then the answer is n minus that number. The complexity is O(n).",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "137",
    "index": "C",
    "title": "History",
    "statement": "Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.\n\nEverybody knows that the World history encompasses exactly $n$ events: the $i$-th event had continued from the year $a_{i}$ to the year $b_{i}$ inclusive ($a_{i} < b_{i}$). Polycarpus easily learned the dates when each of $n$ events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event $j$ includes an event $i$ if $a_{j} < a_{i}$ and $b_{i} < b_{j}$. Your task is simpler: find the number of events that are included in some other event.",
    "tutorial": "Denote a[i], b[i] - ends of the i-th event. Let's sort pairs (a[i], b[i]) by a[i] and iterate over all pairs. Denote rg the maximal b[i] from already processed. If current b[i] < rg than we must increment answer by one. If b[i] > rg than we must assign rg by b[i]. The complexity is O(n logn).",
    "tags": [
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "137",
    "index": "D",
    "title": "Palindromes",
    "statement": "Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called \"Storm and Calm\" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less — on the staff that has nothing to do with IT.\n\nMr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings $a$, $b$ is a string $ab$ that results from consecutive adding of string $b$ to string $a$. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the \"Storm and Calm\" the minimum number of characters so that the text of the book would also be a concatenation of no more than $k$ palindromes. Innocentius can't complete the task and therefore asks you to help him.",
    "tutorial": "Let's preprocess array cnt[i][j] - the minimal number of changes tha we must do to make substring from position i to j palindrom. We can easy calc cnt[i][j] with complexity O(n^3). Now we can calculate dynamic programming z[i][j] - minimal number of changes that we can do to split prefix of length i into j palindromes. In begining we must assign z[i][j] = infinity for all (i, j) and assign z[0][0] = 0. If we want to make updates from state (i, j) we must fix the length of j-th palindrom - len. We can update z[i + len][j + 1] by value z[i][j] + cnt[i][i + len - 1]. Answer to the problem is the min(z[n][i]), where n is the length of string and i from range [1, k]. The complexity is O(n^3).",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "137",
    "index": "E",
    "title": "Last Chance",
    "statement": "Having read half of the book called \"Storm and Calm\" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Innocentius suggested the algorithm of solving equations of the fifth degree in the general case, Ms. Watkins had no other choice but to give him a new task.\n\nThe teacher asked to write consecutively (without spaces) all words from the \"Storm and Calm\" in one long string $s$. She thought that a string is good if the number of vowels in the string is no more than twice more than the number of consonants. That is, the string with $v$ vowels and $c$ consonants is good if and only if $v ≤ 2c$.\n\nThe task Innocentius had to solve turned out to be rather simple: he should find the number of the longest good substrings of the string $s$.",
    "tutorial": "Let's replace all vowels by -1 and all consonants by +2. Obviously substring from position i to j is good if sum in the substring [i, j] is nonnegative. Denote this sum by sum[i][j]. Obviously sum[i][j] = p[j + 1] - p[i], where p[i] is the sum of first i elements. Now for all i we want to find maximal j such that j >= i and sum[i][j] >= 0. For this let's sort the array of (p[i], i) and build segment tree on this array by i. Let's iterate over all p[i] in nondescending order. Obsiously for fixed i we have that j = max(index[i]), where index[i] is the index of i-th partial sum in nondescending order and i from range [x, n], where x is the position of the first partial sum with value p[i] in sorted array. Than we must update position i by value of negative infinity and update answer by j - i. The complexity is O(n logn).",
    "tags": [
      "data structures",
      "implementation",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "138",
    "index": "A",
    "title": "Literature Lesson",
    "statement": "Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.\n\nLet's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters \"a\", \"e\", \"i\", \"o\", \"u\" are considered vowels.\n\nTwo lines rhyme if their suffixes that start from the $k$-th vowels (counting from the end) match. If a line has less than $k$ vowels, then such line can't rhyme with any other line. For example, if $k = 1$, lines $commit$ and $hermit$ rhyme (the corresponding suffixes equal $it$), and if $k = 2$, they do not rhyme ($ommit ≠ ermit$).\n\nToday on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):\n\n- Clerihew ($aabb$);\n- Alternating ($abab$);\n- Enclosed ($abba$).\n\nIf all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by $aaaa$).\n\nIf all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is $aaaa$. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.\n\nVera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.",
    "tutorial": "The hardest part is to check whether two lines rhyme or not. We have to check the suffixes starting in K-th vowels from the ends for equality. Notice that if a line has less then K vowels, it can NOT be part of any rhyme (even with the identical string). To check this we can use two pointers running from two ends simultaneously, or use some built-in functions for taking substrings (like s.substr(...) in C++). Now, let us take three boolean variables: aabb, abab and abba. Each one says if every quatrain we have seen before satisfies the corresponding type of rhyme. To support them, for each new quatrain we must check for rhyming every pair of lines it and change variables if needed. If at the end of the poem all variables are set to TRUE, then the type is aaaa. If all of them are FALSE's, then the answer is NO. Otherwise exactly on of them is TRUE, and answer is clear. Complexity - O(S), where S is the sum of all lines' sizes.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "138",
    "index": "B",
    "title": "Digits Permutations",
    "statement": "Andrey's favourite number is $n$. Andrey's friends gave him two identical numbers $n$ as a New Year present. He hung them on a wall and watched them adoringly.\n\nThen Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.\n\nGiven number $n$, can you find the two digit permutations that have this property?",
    "tutorial": "It turned out to be surprisingly hard, possibly because of lots of cases to think of. How to determine the number of zeros at the end of the sum of two numbers? First we skip all the positions from the end where both numbers have zeros. If on the next position the sum of digits is not 10, that's it. If it is, we go on while the sum of digits is 9. Now we take two transitions of digits in N. Let's fix the number of common zeros at the end of both transitions. If, moreover, we fix the digits that sum up to 10 at the next positions, we can find the maximal number of zeros to get with the remaining digits as $min(a_{0}, b_{9}) + ... + min(a_{9}, b_{0})$, where $a_{0}, ..., a_{9}$ are the quantities of every remaining digit in the first transition after taking out the last zeroes and the digit for the 10-sum, and $b_{0}, ..., b_{9}$ are the same numbers for second transition (initially these quantities are equal to quantities of digits in N). So, if we store $a_{0}, ..., a_{9}$ and $b_{0}, ..., b_{9}$, and then run through the numbers of common zeros at the end and the 10-sum digits, we determine the maximal zeros number (and configuration giving that answer) in O(10 * 10 * N) = O(N) time. Getting the transitions now is easy - we build them from right to left according to the saved answer. The most common mistake was to think that maximal number of zeros at the end gives the maximal answer. It was disproved by 4-th pretest - 1099. As we can see, the optimal configuration is 1901 + 1099, giving three zeros, which cannot be achieved by placing both zeros at the ends.",
    "tags": [
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "138",
    "index": "C",
    "title": "Mushroom Gnomes - 2",
    "statement": "One day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story:\n\nEverybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are $n$ trees and $m$ magic mushrooms in the woods: the $i$-th tree grows at a point on a straight line with coordinates $a_{i}$ and has the height of $h_{i}$, the $j$-th mushroom grows at the point with coordinates $b_{j}$ and has magical powers $z_{j}$.\n\nBut one day wild mushroommunchers, the sworn enemies of mushroom gnomes unleashed a terrible storm on their home forest. As a result, some of the trees began to fall and crush the magic mushrooms. The supreme oracle of mushroom gnomes calculated in advance the probability for each tree that it will fall to the left, to the right or will stand on. If the tree with the coordinate $x$ and height $h$ falls to the left, then all the mushrooms that belong to the right-open interval $[x - h, x)$, are destroyed. If a tree falls to the right, then the mushrooms that belong to the left-open interval $(x, x + h]$ are destroyed. Only those mushrooms that are not hit by a single tree survive.\n\nKnowing that all the trees fall independently of each other (i.e., all the events are mutually independent, and besides, the trees do not interfere with other trees falling in an arbitrary direction), the supreme oracle was also able to quickly calculate what would be the expectation of the total power of the mushrooms which survived after the storm. His calculations ultimately saved the mushroom gnomes from imminent death.\n\nNatalia, as a good Olympiad programmer, got interested in this story, and she decided to come up with a way to quickly calculate the expectation of the sum of the surviving mushrooms' power.",
    "tutorial": "First of all - the answer is the sum for all mushrooms of the probabilities of not being destroyed multiplied by that mushroom's power. That is a simple property of random variables' means. So we come to the equivalent statement: we still have mushrooms, but now instead of trees we have a family of segments with probabilities arranged to them. Every segment \"exists\" with this probability, otherwise it doesn't, and all these events are independent. We want to count the sum of probabilities (with weights) for each mushroom not to lie in any \"existing\" segment. (Note that we can reformulate the statement this way because any segments containing any fixed point are truly independent: they can't belong to the same tree. Thus the probability to survive for any point in this statement is equal to the probability for this point in the original statement). Now, how do we count this? There are several ways: 1) \"Scanning line\". If we go from left to right, we can meet three kinds of events: \"the segment $i$ started\", \"the segment $i$ finished\", \"the mushroom $j$ found\". We can easily support the probability of current point being covered by \"existing\" segment if we multiply it by segment's probability when we find its beginning and divide by it if we find its end. If we find a mushroom by the way, we can add the known probability to answer (multiplied by its power). To perform the above trick we just sort the array of events by x-coordinate and iterate over it. This solution is good in theory, but in practice it has a flaw: if the number of segments is large, after multiplying lots of real numbers less then 1 we can exceed the negative explonent of the real type used, and thus get a 0 in a variable instead of desired value. And after any number of divisions it still would be 0, so we couldn't get any sane answer anymore. This trouble can be resolved in several ways (without changing the solution much): a) We can have no more than 101 distinct values of probabilities for segments. So, if we store an array for quantities of segments containing current point and having a corresponding probability, we just add and substract 1's from array's elements. When we find a mushroom we find the product of degrees with exponents stored in array, spending ~100 operations. b) We can store a set of segments containing current point. Every operation with set works in O(log N) time, and iterating over the whole set works in O(N) time. So, upon meeting mushroom we iterate over set and multiply the probabilities for all segments in it. The next thing that helps us is that we can drop the answer for current mushroom if it's too small. If we don't store the segments with probability 1, the most number of segments which probabilities' product more than 1e-8 is about 2000 (since 0.99 ^ 2000 < 1e-8). So we can count everything in time. c) If we use logs of probabilities instead of themselves, we have to add and substract them instead of multiplying and dividing. This way we won't encounter any precision troubles. 2) Segment tree. Let's sort the mushrooms by their coordinates. Let's also assume we have some set of segments and already counted the desired probabilities. And now we want to add a new segment to the set. What will change? The probabilities of mushrooms lying in this segment (and thus forming a segment in the array) will multiply by segment's probability. Now it's clear we can use multiplication segment tree (or simple addition segment tree if we use logs again) to perform the queries for all segments and then sum up the elements in the end. About the strange score and pretest: we discovered the trouble with precision quite late, and realized that it makes the problem way harder ('cause it's hard to predict during writing and submission phases). What's worse, it won't show itself on the small tests. So we decided to \"show up\" the test and let the contestants solve this additional problem, for additional score. (However, not all solutions from above list do actually deal with this problem. Unfortunately, we didn't came up with them beforehand.)",
    "tags": [
      "binary search",
      "data structures",
      "probabilities",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "138",
    "index": "D",
    "title": "World of Darkraft",
    "statement": "Recently Roma has become the happy owner of a new game World of Darkraft. This game combines elements of virtually all known genres, and on one of the later stages of the game Roma faced difficulties solving a puzzle.\n\nIn this part Roma fights with a cunning enemy magician. The battle takes place on a rectangular field plaid $n × m$. Each cell contains one magical character: L, R or X. Initially all the squares of the field are \"active\".\n\nThe players, Roma and enemy magician, take turns. Roma makes the first move. During a move a player selects one of the active cells. Then depending on the image in the character in the cell one of the following actions takes place:\n\n- L — magical waves radiate from the cell to the left downwards and to the right upwards along diagonal paths. All cells on the path of the waves (including the selected cell too) become inactive. The waves continue until the next inactive cell or to the edge of the field if there are no inactive cells on the way.\n- R — the magical waves radiate to the left upwards and to the right downwards.\n- X — the magical waves radiate in all four diagonal directions.\n\nIf the next player cannot make a move (i.e., all cells are inactive), he loses.\n\nRoma has been trying to defeat the computer opponent for three days but he just keeps losing. He asks you to help him and determine whether it is guaranteed that he can beat the opponent, or he will have to hack the game.",
    "tutorial": "Notice that the game can be separated into two independent: for only even and only odd coordinate sum cells. The player chooses the game he would like to make a move in. Thus, if we find a Grundy function for each of this games we can find the whole game result. Now let's observe only even cells, for instance. We can prove that every diagonally connected piece formed during the game is constructed as the intersection of the field rectangle with some diagonally oriented semi-planes, with exactly one semi-plane for every orientation. Let's enumerate every possible edges of semi-planes, which obviously are some diagonals of the grid. Now we have an enumeration of all possible pieces - by four diagonals being \"edges\" of this piece. Now we want to count the Grundy function for some piece. To do this we iterate over all cells in this piece and find XORs of all Grundy functions of pieces formed by making a move in each cell, then find a minimal exclused non-negative number of this set (see the page on the Sprague-Grundy theorem above). All these pieces are smaller than current, so we can use the DP to count the functions. To easily iterate over cells in the piece we can iterate over numbers of two diagonals the cell lies on (going right-and-upwards and right-and-downwards), as we have exactly the bounds on their numbers as the parameters of the piece. For each case of diagonals we also have to check if the piece is inside the field. So we have counted the Grundy functions for even- and odd-numbered cells separately. If they are equal, the answer is \"LOSE\", otherwise it's a \"WIN\" (see the theorem again). Complexity - $O((n + m)^{4}$ (number of pieces) $mn$ (number of pieces inside one piece and counting MEX)).",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 2500
  },
  {
    "contest_id": "138",
    "index": "E",
    "title": "Hellish Constraints",
    "statement": "Katya recently started to invent programming tasks and prepare her own contests. What she does not like is boring and simple constraints. Katya is fed up with all those \"$N$ does not exceed a thousand\" and \"the sum of $a_{i}$ does not exceed a million\" and she decided to come up with something a little more complicated.\n\nThe last problem written by Katya deals with strings. The input is a string of small Latin letters. To make the statement longer and strike terror into the people who will solve the contest, Katya came up with the following set of $k$ restrictions of the same type (characters in restrictions can be repeated and some restrictions may contradict each other):\n\n- The number of characters $c_{1}$ in a string is not less than $l_{1}$ and not more than $r_{1}$.\n- ...\n- The number of characters $c_{i}$ in a string is not less than $l_{i}$ and not more than $r_{i}$.\n- ...\n- The number of characters $c_{k}$ in a string is not less than $l_{k}$ and not more than $r_{k}$.\n\nHowever, having decided that it is too simple and obvious, Katya added the following condition: a string meets no less than $L$ and not more than $R$ constraints from the above given list.\n\nKatya does not like to compose difficult and mean tests, so she just took a big string $s$ and wants to add to the tests all its substrings that meet the constraints. However, Katya got lost in her conditions and asked you to count the number of substrings of the string $s$ that meet the conditions (each occurrence of the substring is counted separately).",
    "tutorial": "Let's start with the case when we have only one constriction - \"$c$ $l$ $r$\". For a string $s$ let's count an array $A$ with a length equal to $s$'s. $A[i] = 1$ if the suffix of $s$ starting at position $i$ satisfies the condition, and $A[i] = 0$ otherwise. So, we have $s$ and already counted $A$. What happens if we write another symbol $c'$ at the of $s$? Let $s' = s + c'$, $A' = A(s')$. If $c'  \\neq  c$, than the part of $A'$ corresponding to everything beside the last symbol does not change. The last element is 1 or 0 depending on the condition (it's easy to count). If $c' = c$, some elements of $A$ might change. Let's denote the $i$-th occurence of $c$ in $s'$ counting from the end as $p_{i}(c)$ (symbols and occurences are enumerated from 1). If there are less then $i$ occurences, $p_{i}(c) = 0$. It's easy to see that elements from $A'[p_{l + 1}(c) + 1..p_{l}(c)]$ are incremented by 1, and elements from $A'[p_{r + 2}(c) + 1..p_{r + 1}(c)]$ are decremented by 1. It's also clear that as we add the symbols these invervals won't intersect for $l$ and $r$ separately (that is, every $A[i]$ will be incremented and decremented not more than one time each). Now we can have more then one constriction. We count $B[i]$ as the number of constrictions the suffix starting at $i$-th position satisfies. Clearly, $B[i]$ is the sum of $A[i]$'s for all constrictions. Also, we support the variable $C$ - number of $i$-s that satisfy $L  \\le  B[i]  \\le  R$. Similarly, we add symbols one after another and change $B[i]$. To do that, we must consider all the constrictions concerning new symbols and change the numbers in the intervals mentioned above. Changing the numbers is just iterating over symbols in the mentioned intervals and incrementing/decrementing $B[i]$'s (this procedure also lets us to support $C$ effectively). As the intervals for each constriction do not intersect, we will not change any $B[i]$ more than twice for each constriction, so the number of operations concerning any constriction is $O(n)$, giving total number of operations $O(nk)$. To get the answer, we just sum up $C$'s states after adding every symbol (as every substring will be a suffix of some prefix exactly one time). To find borders of every interval used (in which the $B[i]$'s are changed) we can enumerate all occurences of every symbols and count the borders easily, knowing how many times every symbol occured. The other way to do that is to keep two pointers for each constriction, showing where last intervals ended. On the next occurence we move these pointers to next occurences of corresponding symbol (however, we need to handle the case when not enough symbols have occured to changed $B$).",
    "tags": [
      "brute force",
      "dp",
      "two pointers"
    ],
    "rating": 2900
  },
  {
    "contest_id": "139",
    "index": "A",
    "title": "Petr and Book",
    "statement": "One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly $n$ pages.\n\nPetr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Some days are so busy that Petr will have no time to read whatsoever. However, we know that he will be able to read at least one page a week.\n\nAssuming that Petr will not skip days and will read as much as he can every day, determine on which day of the week he will read the last page of the book.",
    "tutorial": "If the total number of pages doesn't exceed the number of pages for Monday, the answer is Monday. Otherwise we can substract the Monday number from total and go on to Tuesday. If Tuesday isn't enough, we subtract and continue to Wednesday, and so on. We are sure that no more than N weeks will pass, as at least one page is read every week. Complexity - O(N).",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "139",
    "index": "B",
    "title": "Wallpaper",
    "statement": "Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has $n$ rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height).\n\nBoris chose $m$ types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type.\n\nThe wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely.\n\nAfter buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.",
    "tutorial": "Unluckily, the translated statement was quite tough even tougher to understand than the original statement. Say we fixed the roll type and the room. The only possible way to cut the roll is to cut it into vertical stripes with length equal to room's height (though it was said we can cut it any way we want, there were some conditions to fulfill, namely there could be no joints other than vertical). So we find the total width of stripes we can cut our roll into as the (length of the roll / height of the room) (rounded down) * (width of the roll). If the roll length is smaller than room height, we obviously can not use this type of rolls (though the statement said there must exist at least one type we can use). The number of rolls is (perimeter of the wall rooms) / (total stripes width) (rounded up). Then we just try all types for every room and sum the minimal costs. Complexity - O(MN).",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "140",
    "index": "A",
    "title": "New Year Table",
    "statement": "Gerald is setting the New Year table. The table has the form of a circle; its radius equals $R$. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal $r$. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for $n$ plates.",
    "tutorial": "The plates must touch the edge of the table, so their centers must lie on the circle with radius R - r (see the figure). In case the plates have the largest radius possible for the given table, their centers are situated in the vertices of the regular polygon (n-gon) inscribed in this circle. The problem is to find the length of the side of the inscribed regular n-gon and to compare it with 2r. The formula for the length of the side is $a = 2(R - r)sin ( \\pi  / n)$, it can be easily deduced. For that you should consider the right triangle (the green one in the figure). In implementation, be careful with a case when the equality $r = (R - r)sin( \\pi  / n)$ (*) holds. Because of the computational error the right-hand side can get larger than the left-hand one. This can result in answer \"NO\" instead of \"YES\". Comparison in such cases should be performed with a small $ \\epsilon $: $a +  \\epsilon  < b$ instead of $a < b$ , $a < b +  \\epsilon $ instead of $a  \\le  b$. A constant $ \\epsilon $ should be chosen in such a way, that it is smaller than any possible difference between precise values of $a$ and $b$, if they are distinct. In particular, for computations by the formula (*), taking into account the constraints of the problem, this difference may be approximately $7 \\cdot  10^{ - 7}$. So $ \\epsilon  = 10^{ - 7}$ is sufficient, but $ \\epsilon  = 10^{ - 6}$ is not. Once again, I focus your attention on the fact that the choice of $ \\epsilon $ depends on specific formulas used for computations and comparisons. Different solutions can be accepted or not with the same $ \\epsilon $.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "140",
    "index": "B",
    "title": "New Year Cards",
    "statement": "As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has $n$ friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from $1$ to $n$ in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the $i$-th friend sent to Alexander a card number $i$.\n\nAlexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules:\n\n- He will never send to a firend a card that this friend has sent to him.\n- Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most.\n\nAlexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times.\n\nAlexander and each his friend has the list of preferences, which is a permutation of integers from $1$ to $n$. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card.\n\nYour task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible.\n\nNote that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.",
    "tutorial": "This problem was just a problem on implementation. Note that a number of a send card is uniquely determined by a number of a friend and a set of cards Alexander already has at the moment. Consider the sample form the statement. 12 3 4 {1} -1 1 1 {1, 2}21 1 1 {3, 1, 2}3 3 1 3 {3, 1, 2, 4}33 1 3 The first column of the table contains sets of cards that Alexander gets after having received a next card each time. Numbers in the sets are written in order of Alexander's preferences. Each i-th of the next four columns contains numbers of cards that the i-th friend will get from the corresponding sets. Our goal is to choose for each friend the most preferred card in his column. Note that to determine by the current Alexander's set and the number of the friend a number of a card received by this friend, it is not necessary to know the whole Alexander's set. The two most preferable cards are sufficient. So for each time moment find the two most preferable cards for Alexander. Using them, determine which of them will be send to each friend (find the numbers in the columns). Then choose the element with the maximum priority in each column. We get the $O(n^{2})$ solution.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "140",
    "index": "C",
    "title": "New Year Snowmen",
    "statement": "As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made $n$ snowballs with radii equal to $r_{1}$, $r_{2}$, ..., $r_{n}$. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii $1$, $2$ and $3$ can be used to make a snowman but $2$, $2$, $3$ or $2$, $2$, $2$ cannot. Help Sergey and his twins to determine what \\textbf{maximum} number of snowmen they can make from those snowballs.",
    "tutorial": "Solution 1. Suppose that the answer is k. If there are more than k equal among the given numbers, it's clear that we can't use them all (we can't use equal snowballs in the same snowman). So we leave k snowballs of them, and discard the rest. Then, sort the radii in the non-decreasing order. After that every two snowballs with numbers i and k + i are different. Make snowmen of snowballs with numbers (1, k + 1, 2k + 1), (2, k + 2, 2k + 2), (3, k + 3, 2k + 3) and so on. If the total number of snowballs is not less than 3k, we always manage to make k snowmen. Now we can for the fixed k answer to the question, if k snowmen can be made, so k can be chosen by binary search. Solution 2. Count quantities of snowballs of each size, choose greedily the three largest quantities, take a snowball from each of them, make snowman and continue the process, while it's possible. Why is it correct? Let k be the answer for the problem. If there are quantities larger than k, we will count them as k, because other snowballs in them will not be used in any way. We prove the correctness of the algorithm using Proposition: if every quantity is $ \\le  k$ and the total quantity of snowballs is $ \\ge  3k$, then it's possible to perform a step of the algorithm. Proposition is valid because by Pigeonhole principle there are no less than three non-zero quantities. If there are 3 (or more) quantities equal k, then k steps of the algorithm can be performed. If there is one or two such quantities, by the first step we certainly decrease them and come to a similar situation with k - 1. If there are no quantities equal k, after the first step we obtain quantities $ \\le  k - 1$, and their total sum is $ \\ge  3(k - 1)$. Thus, we always can perform k steps and get the answer k. From the point of view of implementation, in the second solution it is easy to calculate quantities for each size of snowballs (using sorting and scaling). Use set to work with these quantities. The time for the both solutions is $O(n \\log n)$.",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "140",
    "index": "D",
    "title": "New Year Contest",
    "statement": "As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest.\n\nThe New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are $n$ problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.).\n\nGennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the $i$-th problem will take $a_{i}$ minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the $i$-th problem always equals $a_{i}$ minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.).\n\nHelp Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.",
    "tutorial": "Solution 1 (greedy). Optimal order to solve problems is an increasing (non-decreasing) order by their difficulties. Problems solved before the New Year must be submitted at 0:00, ones solved after the New Year must be submitted just after finishing their solutions. Let us prove the optimality of this solution by the descent method. General scheme of reasoning is the following. Suppose you have the optimal order which is not the increasing order by problems' dificulties. Show that it is possible to come (to descend) from it to another variant, that is not less optimal. As a result you come to the sorted variant by such steps. So suppose that there is a pair of problems in the optimal solution such that their difficulties are going in decreasing order. Then there are consecutive problems with this property. Suppose they both are solved before the New Year. Then the swap of them doesn't influence the penalty (it doesn't decrease). If the both problems are solved after the New Year, then their contribution to the total penalty is $(T + a_{i}) + (T + a_{i} + a_{j})$, where T is a time of the beginning of solution for the first problem, $a_{i}$ is a time for the solution for the first problem, $a_{j} < a_{i}$ is a time for the solution for the second problem. After the swap of these problems we get the penalty $(T + a_{j}) + (T + a_{j} + a_{i})$, that is less than $(T + a_{i}) + (T + a_{i} + a_{j})$. It remains to consider cases when one of the consecutive problems that are in the \"wrong\" order \"intersects the New Year\". These cases can be treated similarly. In case when Gennady hasn't time to solve all problems, you should choose the maximal possible number of the easiest problems. Indeed, it doesn't make sense to solve a more difficult problem instead of an easy one: change of a larger $a_{i}$ to a smaller one doesn't spoil an answer. Rigorous proof can be obtained by the same descent method. Solution 2 (dynamic). First of all, as in the previous solution, choose the maximal number of the easiest problems that Gennady has time to solve. Discard the remaining tasks. Try every problem as one being solved in the moment of the New Year (0:00). Remaining problems (except it) must be divided into two sets. One is for solving before the New Year, and another is for solving after the New Year. Problems in the second set must be solved in increasing order of their difficulties (it is a well-known fact for everybody participating in contests by ACM rules). In the first set an order of solving is immaterial. Sort the given numbers in increasing order, and count the dynamics d[i][j][k] that is the smallest possible penalty, if there are the first i problems solved, j from them are solved after the New Year, and the last problem after the New Year was solved at the moment k. Note that the triple (i, j, k) uniquely determines the number of problems solved before the New Year and the total time needed for their solutions. After calculating the dynamics, recollect the problem being solved exactly at 0:00 (it was not taken into account in the dynamics). Try moments of time before the New Year when its solutions starts, and count remaining problems using the dynamics we already has.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "140",
    "index": "E",
    "title": "New Year Garland",
    "statement": "As Gerald, Alexander, Sergey and Gennady are already busy with the usual New Year chores, Edward hastily decorates the New Year Tree. And any decent New Year Tree must be decorated with a good garland. Edward has lamps of $m$ colors and he wants to make a garland from them. That garland should represent a sequence whose length equals $L$. Edward's tree is $n$ layers high and Edward plans to hang the garland so as to decorate the first layer with the first $l_{1}$ lamps, the second layer — with the next $l_{2}$ lamps and so on. The last $n$-th layer should be decorated with the last $l_{n}$ lamps, $\\textstyle\\sum_{i=1}^{n}l_{i}=L.$\n\nEdward adores all sorts of math puzzles, so he suddenly wondered: how many different ways to assemble the garland are there given that the both following two conditions are met:\n\n- Any two lamps that follow consecutively in the same layer should have different colors.\n- The sets of used colors in every two \\textbf{neighbouring} layers must be different. We consider unordered sets (not multisets), where every color occurs no more than once. So the number of lamps of particular color does not matter.\n\nHelp Edward find the answer to this nagging problem or else he won't manage to decorate the Tree by New Year. You may consider that Edward has an unlimited number of lamps of each of $m$ colors and it is not obligatory to use all $m$ colors. The garlands are considered different if they differ in at least one position when represented as sequences. Calculate the answer modulo $p$.",
    "tutorial": "First, let us solve the subtask for one layer. It consists in finding the number of ways to compose a garland of lengths s with lamps of exactly k colors such that no two consecutive lamps have the same color. Variants different only by an order of colors are considered to be the same (we always can multiply by k! if we need). The solution of the subtasks is required only for $k  \\le  s  \\le  5000$, so can be done by $O(s^{2})$-dynamics: a[s][k] = a[s-1][k-1] + a[s-1][k] * (k -1). They would be Stirling numbers of the second kind, if there was not a restriction about different colors of consecutive lamps. Then, calculate the dynamics d[i][j] that is a number of ways to compose a garland for the first i layers according to the rules, such that the i-th layer contains exactly j different colors. There will be about L positions (the total length of the garland), because every layer can't contain more colors than its length: $j  \\le  l_{i}$ (!). All d[i][j] can be calculated in $O(L)$ operations, because sets of colors with different cardinalities are always different (!!). Indeed, put d[i][j] = $A_{m}^{j}$ * a[l[i]][j] * (sum of all d[i-1][k]), and then subtract variants with equal sets on the i-th and (i-1)-th layers. Coefficients $A_{m}^{j} = m(m - 1)... (m - j + 1)$ can be pre-calculated because they are required only for $j  \\le  5000$. Thus, the author's solutions works in $O(L + s^{2})$ ($L  \\le  10^{7}$, $s  \\le  5000$), and it doesn't use division (only addition and multiplication modulo p).",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "140",
    "index": "F",
    "title": "New Year Snowflake",
    "statement": "As Gerald ..., in other words, on a New Year Eve Constantine prepared an unusual present for the Beautiful Lady. The present is the magic New Year snowflake that can make any dream come true.\n\nThe New Year snowflake consists of tiny ice crystals, which can be approximately regarded as points on the plane. The beauty of the New Year snowflake is that it has a center of symmetry. This is a point such that for each crystal of the snowflake exists another crystal, symmetrical to it relative to that point. One of the crystals can be placed directly in the center of symmetry.\n\nWhile Constantine was choosing a snowflake among millions of other snowflakes, no less symmetrical and no less magical, then endured a difficult path through the drifts to the house of his mistress, while he was waiting with bated breath for a few long moments before the Beautiful Lady opens the door, some of the snowflake crystals melted and naturally disappeared. Constantine is sure that there were no more than $k$ of such crystals, because he handled the snowflake very carefully. Now he is ready to demonstrate to the Beautiful Lady all the power of nanotechnology and restore the symmetry of snowflakes.\n\nYou are given the coordinates of the surviving snowflake crystals, given in nanometers. Your task is to identify all possible positions of the original center of symmetry.",
    "tutorial": "Start with the check of a candidate symmetry center $(x_{c}, y_{c})$. Consider all points symmetrical to $(x_{i}, y_{i})$ with this center. They are of form $(2x_{c} - x_{i}, 2y_{c} - y_{i})$. It is necessary to check that they all except may be k of them are in the set ${(x_{i}, y_{i})}$. It can be done in $O(n \\log n)$ by binary search (if the set was previously sorted). But there is more effective way of check in $O(n)$. Note that if initially the points $(x_{i}, y_{i})$ were sorted, say, by x-coordinate in increasing order and in case of equal x by y, then the points of the form $(2x_{c} - x_{i}, 2y_{c} - y_{i})$ will be sorted in the reverse order. The order doesn't depend on the center $(x_{c}, y_{c})$. So we can check the points $(2x_{c} - x_{i}, 2y_{c} - y_{i})$ in the order of sorting moving a pointer in the sorted array $(x_{i}, y_{i})$. It follows from the previous reasoning, that if a set has a symmetry center, then the first point (in the order of sorting) forms a pair with n'th, the second one with (n-1)-th and so on. Since up to k points have not a pair, try the first (k+1) points from the beginning and (k+1) from the end of the array. For every pair of these points find the midpoint and check it in $O(n)$. Asymptotics of the solution is $O(nk^{2})$.",
    "tags": [
      "geometry",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "141",
    "index": "A",
    "title": "Amusing Joke",
    "statement": "So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two \"New Year and Christmas Men\" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.\n\nThe next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.\n\nHelp the \"New Year and Christmas Men\" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.",
    "tutorial": "It was enough for solving this problem to calculate for each letter: $a_{c}$ - amount of occurrences of letter $c$ in first and second strings in input, $b_{c}$ - amount of occurrences of letter $c$ in third string in input. If $\\forall c:a_{c}=b_{c}$ the answer is \"YES\" else \"NO\".",
    "tags": [
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "141",
    "index": "B",
    "title": "Hopscotch",
    "statement": "So nearly half of the winter is over and Maria is dreaming about summer. She's fed up with skates and sleds, she was dreaming about Hopscotch all night long. It's a very popular children's game. The game field, the court, looks as is shown in the figure (all blocks are square and are numbered from bottom to top, blocks in the same row are numbered from left to right). Let us describe the hopscotch with numbers that denote the number of squares in the row, staring from the lowest one: 1-1-2-1-2-1-2-(1-2)..., where then the period is repeated (1-2).\n\nThe coordinate system is defined as shown in the figure. Side of all the squares are equal and have length $a$.\n\nMaria is a very smart and clever girl, and she is concerned with quite serious issues: if she throws a stone into a point with coordinates $(x, y)$, then will she hit some square? If the answer is positive, you are also required to determine the number of the square.\n\nIt is believed that the stone has fallen into the square if it is located \\textbf{strictly} inside it. In other words a stone that has fallen on the square border is not considered a to hit a square.",
    "tutorial": "Let's bust the \"level\" $0  \\le  i  \\le  10^{6}$, in which assumedly the stone could hit. Let's find the minimal number of square on this level. Then we can understand, how many squares there are on this level: one or two. Then we check with one or two ifs (if on this level two squares) if the stone is in corresponding square or not. If the stone is inside then output the answer. If we didn't find any square, where the stone is, output \"-1\".",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "141",
    "index": "C",
    "title": "Queue",
    "statement": "In the Main Berland Bank $n$ people stand in a queue at the cashier, everyone knows his/her height $h_{i}$, and the heights of the other people in the queue. Each of them keeps in mind number $a_{i}$ — how many people who are taller than him/her and stand in queue in front of him.\n\nAfter a while the cashier has a lunch break and the people in the queue seat on the chairs in the waiting room in a random order.\n\nWhen the lunch break was over, it turned out that nobody can remember the exact order of the people in the queue, but everyone remembers his number $a_{i}$.\n\nYour task is to restore the order in which the people stood in the queue if it is possible. There may be several acceptable orders, but you need to find any of them. Also, you need to print a possible set of numbers $h_{i}$ — the heights of people in the queue, so that the numbers $a_{i}$ are correct.",
    "tutorial": "Let's sort the pairs ($name_{i}$, $a_{i}$) by ascending of $a_{i}$. If there is an index i: $0  \\le  i < n$ that $a_{i} > i$, then answer is \"-1\". Otherwise the answer exists. We will iterate through the array of sorted pairs from left to right with supporting of vector of results $res$. Let on the current iteration $a_{i} = n - i$, then we must transfer the current man in the position $a_{i}$. It can be done in C++ with one line: res.insert(res.begin() + a[i], man);",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "141",
    "index": "D",
    "title": "Take-off Ramps",
    "statement": "Vasya participates in a ski race along the $X$ axis. The start is at point $0$, and the finish is at $L$, that is, at a distance $L$ meters from the start in the positive direction of the axis. Vasya has been training so hard that he can run one meter in exactly one second.\n\nBesides, there are $n$ take-off ramps on the track, each ramp is characterized by four numbers:\n\n- $x_{i}$ represents the ramp's coordinate\n- $d_{i}$ represents from how many meters Vasya will land if he goes down this ramp\n- $t_{i}$ represents the flight time in seconds\n- $p_{i}$ is the number, indicating for how many meters Vasya should gather speed to get ready and fly off the ramp. As Vasya gathers speed, he should ski on the snow (that is, he should not be flying), but his speed still equals one meter per second.\n\nVasya is allowed to move in \\textbf{any direction} on the $X$ axis, but he is prohibited to cross the start line, that is go to the negative semiaxis. Vasya himself chooses which take-off ramps he will use and in what order, that is, he is not obliged to take off from all the ramps he encounters. Specifically, Vasya can skip the ramp. It is guaranteed that $x_{i} + d_{i} ≤ L$, that is, Vasya cannot cross the finish line in flight.\n\n\\textbf{Vasya can jump from the ramp only in the positive direction of $X$ axis. More formally, when using the $i$-th ramp, Vasya starts gathering speed at point $x_{i} - p_{i}$, jumps at point $x_{i}$, and lands at point $x_{i} + d_{i}$. He cannot use the ramp in opposite direction.}\n\nYour task is to find the minimum time that Vasya will spend to cover the distance.",
    "tutorial": "Let's generate the weighted directed graph of all ramps. The graphs' vertexes are the important points on the line $Ox$, there are points: $0, L, x_{i} - p_{i}, x_{i} + d_{i}$. The graphs' edges are the possible ramp jumps: transfer from point $x_{i} - p_{i}$ to point $x_{i} + d_{i}$ or transfer from vertex in neighboring vertexes (neighboring means that we get the next and previous important points on the line). The weights of these edges are correspondingly $p_{i} + t_{i}$ and $x_{v + 1} - x_{v}$, $x_{v} - x_{v - 1}$. We must note that in the transfers we can't get in the negative part of $Ox$, and we must delete this transfers. Then we must find and output the shortest path in this graph from vertex $0$ to $L$. This can be done, for example, with Dijkstra's algorithm for the sparse graphs.",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "141",
    "index": "E",
    "title": "Clearing Up",
    "statement": "After Santa Claus and his assistant Elf delivered all the presents and made all the wishes come true, they returned to the North Pole and found out that it is all covered with snow. Both of them were quite tired and they decided only to remove the snow from the roads connecting huts. The North Pole has $n$ huts connected with $m$ roads. One can go along the roads in both directions.\n\nThe Elf offered to split: Santa Claus will clear up the wide roads and the Elf will tread out the narrow roads. For each road they decided who will clear it: Santa Claus or the Elf. To minimize the efforts they decided to clear the road so as to fulfill both those conditions:\n\n- between any two huts should exist \\textbf{exactly one simple path} along the cleared roads;\n- Santa Claus and the Elf should clear the same number of roads.\n\nAt this point Santa Claus and his assistant Elf wondered which roads should they clear up?",
    "tutorial": "In this problem we must find the minimum spanning tree, in which the half of edges are marked with letter 'S'. There are $n - 1$ edges in this tree, because of it if $n$ is even then the answer is \"-1\". Let's delete from the given graph all S-edges. And there are $cnt$ components in obtained graph. For making this graph be connected we must add $cnt - 1$ edges or more, that's why if $cnt - 1 > (n - 1) / 2$ the answer is \"-1\". Then we find $cnt - 1$ S-edges, that we must add to the graph, so that it become connected. If $cnt - 1 < (n - 1) / 2$ then we will try to add in this set of edges another S-edges, so that the S-edges don't make circle. We must do all of this analogically to Kruskal's algorithm of finding a minimum spanning tree. If we could get a set of S-edges of $(n - 1) / 2$ elements, that there are exactly $cnt - 1$ edges and no S-circles, then the answer exists, Then we must add to this set $(n - 1) / 2$ M-edges, that forms with our set of edges the minimum spanning tree, it must be done analogically with Kruskal's algorithm.",
    "tags": [
      "constructive algorithms",
      "dp",
      "dsu",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "142",
    "index": "A",
    "title": "Help Farmer",
    "statement": "Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored $A·B·C$ hay blocks and stored them in a barn as a rectangular parallelepiped $A$ layers high. Each layer had $B$ rows and each row had $C$ blocks.\n\nAt the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing $(A - 1) × (B - 2) × (C - 2)$ hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single $1 × 1 × 1$ blocks and scattered them around the barn. After the theft Sam counted $n$ hay blocks in the barn but he forgot numbers $A$, $B$ и $C$.\n\nGiven number $n$, find the minimally possible and maximally possible number of stolen hay blocks.",
    "tutorial": "Due to quite low constraint this problem is easily solvable by brute-force. Without loss of generality assume that A <= B <= C. Then it is clear that A cannot exceed $\\textstyle{\\sqrt{n}}$, and, given A, B cannot exceed ${\\sqrt{(}}n/A)$. Then all solution is just two cycles: for (long long a = 1; a*a*a <= n; ++a) if (n%a == 0){ for (long long b = a; b*b <= n/a; ++b) if ((n/a)%b == 0){ long long c = n/a/b; ... } } Since we assumed A <= B <= C, now it is not clear which parameter (A, B or C) is the height of haystack, so inside the cycle one should consider all three possibilities. For any N <= 10^9 the code inside the second loop runs no more than 25000 times, so this solution fits timelimit even for N <= 10^11 and maybe larger. Why it's so quick? It's because of the fact that number of divisors of arbitrary number N does not exceed about ${\\dot{\\sqrt{N}}}$. That's why all similar solutions and maybe some other streetmagic that has anything common with divisors of N, should get AC.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "142",
    "index": "B",
    "title": "Help General",
    "statement": "Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply).\n\nAs the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: \"\\underline{If the squared distance between some two soldiers equals to $5$, then those soldiers will conflict with each other!}\"\n\nThe drill exercises are held on a rectangular $n × m$ field, split into $nm$ square $1 × 1$ segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ equals exactly $(x_{1} - x_{2})^{2} + (y_{1} - y_{2})^{2}$. Now not all $nm$ squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square $(2, 2)$, then he cannot put soldiers in the squares $(1, 4)$, $(3, 4)$, $(4, 1)$ and $(4, 3)$ — each of them will conflict with the soldier in the square $(2, 2)$.\n\nYour task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse.",
    "tutorial": "This problem was not on derivation of the general formula m*n - (m*n)/2 (only this would be too simple for the second/fourth problem, isn't it?) but rather on accurate investigation of several cases. Unfortunately, many participants were very eager to submit the formula above, that's why there were so many hacks. I would say: this is not jury fault - pretests were made very weak intentionally, partially - to give you some space for hacks; but jury didn't presume there would be so many hacks. This is your fault of submitting unproven solutions. This is large risk given Codeforces rules, and this time risk-lovers were not lucky =) Ok, let's come to the solution. Without loss of generality let's assume m <= n. Then we have the following cases: 1. m = 1 x n fields. It is obvious that here the answer is n. 2. m = 2 x n >= 2 fields. Here the correct formula is 2*[2*(n/4) + min(n%4, 2)]. Why so? To see this draw the board for arbitrary n and draw all possible knight moves on it. In general, you'll see four not overlapping chains. Since you cannot place soldiers in the neighboring cells of any chain, then for a chain of length L the answer doesn't exceed (L - L/2). On the other hand, it is clear that the answer (L - L/2) is always possible since soldiers on different chains never hurt each other. If you consider fields with different remainders n%4, the formula above becomes clear. 3. m >= 3 x n >= 3 fields, except the cases 3 x 3, 3 x 5, 3 x 6 and 4 x 4. Here one may use general formula m*n - (m*n)/2. Why so? It is known (or becomes known with google) that for all such fields knight tours exists. Any knight tour is just a chain of lenght m*n, so by the logic above one cannot place more than m*n - (m*n)/2 soldiers on it. On the other hand, if one makes chessboard coloring of the field, it is clear that the answer above is always achievable if one chooses cells of one color as places for soldiers. So, formula above is proved. 4. Cases 3 x 3, 3 x 5, 3 x 6 and 4 x 4. Here we can't use the logic above to prove that the above formula is also right here. The easiest way is to verify it using brute-force or pen and paper. This concludes the solution.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "142",
    "index": "C",
    "title": "Help Caretaker",
    "statement": "Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.\n\nHe's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character \"#\" stands for the space occupied by the turboplow and character \".\" stands for the free space):\n\n\\begin{center}\n{\\begin{verbatim}\n### ..# .#. #..\n.#. ### .#. ###\n.#. ..# ### #..\n\\end{verbatim}}\n\\end{center}\n\nSimon faced a quite natural challenge: placing in the given $n × m$ cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot \"overlap\", that is, they cannot share the same cell in the warehouse.\n\nSimon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?",
    "tutorial": "This is technical problem, one may use several approaches to solve it. Additional complexity is to restore the answer after you got it. 1. Dynamic programming \"on the broken profile\" - I'll not explain the approach here in detail, you can find explanation of it on the Internet or even on Codeforces. Worth to point out, care should be taken of your code memory usage. 2. Search with memorization - one jury solution uses logic like DP with usual (not broken) profile: move by rows (or by columns), try all possible T placements such that upper cell of T's is in the given row and run the same search procedure for the next raw, passing the state of the two last filled rows of the board to it. For the given board state save the answer recursive function returned (max number of T's one may place on the not-yet-filled part of the board) and use it in the future as the answer for the given state. This requires only O(n*2^(2^m)) of memory and works about 2 sec. on maxtest 9 x 9. 3. Branch and bound. Another jury solution recursively tries all possible tilings of the board with T's. If on some step it occured that number of T's on the board plus number of T's one can theoretically place on the remaining part of the board doesn't exceed existing best answer - trim this node. Such solution is the easiest to code and it works only 0.5 sec. on maxtest, however it is not obvious from the very beginning. 4. Precalc - not to write a lot of code (applying DP or search with memorization) and not to deal with possible time/memory limits, some participants did the right thing: using the third approach, just precalculated answers for large (or for all possible) inputs.",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "142",
    "index": "D",
    "title": "Help Shrek and Donkey 2",
    "statement": "Having learned (not without some help from the Codeforces participants) to play the card game from the previous round optimally, Shrek and Donkey (as you may remember, they too live now in the Kingdom of Far Far Away) have decided to quit the boring card games and play with toy soldiers.\n\nThe rules of the game are as follows: there is a battlefield, its size equals $n × m$ squares, some squares contain the toy soldiers (the green ones belong to Shrek and the red ones belong to Donkey). Besides, each of the $n$ lines of the area contains not more than two soldiers. During a move a players should \\textbf{select} not less than $1$ and not more than $k$ soldiers belonging to him and make them either attack or retreat.\n\nAn attack is moving all of the selected soldiers along the lines on which they stand \\textbf{in the direction of} an enemy soldier, if he is in this line. If this line doesn't have an enemy soldier, then the selected soldier on this line can move in any direction during the player's move. Each selected soldier has to move at least by one cell. Different soldiers can move by a different number of cells. During the attack the soldiers are not allowed to cross the cells where other soldiers stand (or stood immediately before the attack). It is also not allowed to go beyond the battlefield or finish the attack in the cells, where other soldiers stand (or stood immediately before attack).\n\nA retreat is moving all of the selected soldiers along the lines on which they stand \\textbf{in the direction from} an enemy soldier, if he is in this line. \\underline{The other rules repeat the rules of the attack.}\n\nFor example, let's suppose that the original battlefield had the form (here symbols \"G\" mark Shrek's green soldiers and symbols \"R\" mark Donkey's red ones):\n\n\\begin{center}\n{\\begin{verbatim}\n-G-R-\n-R-G-\n\\end{verbatim}}\n\\end{center}\n\nLet's suppose that $k = 2$ and Shrek moves first. If he decides to attack, then after his move the battlefield can look like that:\n\n\\begin{center}\n{\\begin{verbatim}\n--GR- --GR- -G-R-\n-RG-- -R-G- -RG--\n\\end{verbatim}}\n\\end{center}\n\nIf in the previous example Shrek decides to retreat, then after his move the battlefield can look like that:\n\n\\begin{center}\n{\\begin{verbatim}\nG--R- G--R- -G-R-\n-R--G -R-G- -R--G\n\\end{verbatim}}\n\\end{center}\n\nOn the other hand, the followings fields cannot result from Shrek's correct move:\n\n\\begin{center}\n{\\begin{verbatim}\nG--R- ---RG --GR-\n-RG-- -R-G- GR---\n\\end{verbatim}}\n\\end{center}\n\nShrek starts the game. To make a move means to attack or to retreat by the rules. A player who cannot make a move loses and his opponent is the winner. Determine the winner of the given toy soldier game if Shrek and Donkey continue to be under the yellow pills from the last rounds' problem. Thus, they always play optimally (that is, they try to win if it is possible, or finish the game in a draw, by ensuring that it lasts forever, if they cannot win).",
    "tutorial": "Solving this problem involves two basic steps: firstly, to recognize that we have nothing else than generalised version of Nim and secondly, to solve it. The first part is not difficult: assuming we don't have rows with soldiers of only one color (in which case the game usually becomes trivial, since one or both players may play infinitely long), let the number of cells between two soldiers in every non-empty line be the size of the corresponding piles in nim. Then attack according to the rules of the given game is the move in the corresponding nim that allows you to take as much as you like stones from at most k piles (but at least 1 stone should be taken). Such generalized nim is called Moore's nim-k, and we should solve it to find the winner in the initial game. As any source you may google (except Russian Wikipedia) shows, solution to the Moore's nim-k is the following: Let's write binary expansions of pile sizes, and for any position check that sum of digits on the given position in all expansions is divisible by k+1. If this holds for all positions - then the winner is the second player, otherwise - the first player. Proof of the fact may be found here: http://www.stat.berkeley.edu/~peres/yuvalweb/gath9.pdf Let's consider the following case for k = 2: R-G-- R--G- R---G R---G Corresponding 4-piles nim-2 for this test is (1, 2, 3, 3). After writing binary expansions of piles sizes we get 01 10 11 11 Sums of digits in both positions (3) are divisible by k+1=3, so here Second wins. But this is still not full solution to the initial game, because we forget about retreat possibility. But it is simple here: only player losing the game in which only attacks allowed may want to retreat (winner just plays corresponding nim by attacking). But if loser retreats, winner just restores initial position attacking in the corresponding rows. And since loser cannot retreat infinitely, he cannot improve his win chances with retreat moves. That's it. And finally, don't forget about tests like: 2 2 2 GG RR Answer: Second All such tricky cases were in pretests.",
    "tags": [
      "games"
    ],
    "rating": 2600
  },
  {
    "contest_id": "142",
    "index": "E",
    "title": "Help Greg the Dwarf 2",
    "statement": "Greg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. That's why he wants to find the shortest route from the excavation point to his crypt. Greg has recollected how the Codeforces participants successfully solved the problem of transporting his coffin to a crypt. So, in some miraculous way Greg appeared in your bedroom and asks you to help him in a highly persuasive manner. As usual, you didn't feel like turning him down.\n\nAfter some thought, you formalized the task as follows: as the Neverland mountain has a regular shape and ends with a rather sharp peak, it can be represented as a cone whose base radius equals $r$ and whose height equals $h$. The graveyard where Greg is busy excavating and his crypt can be represented by two points on the cone's surface. All you've got to do is find the distance between points on the cone's surface.\n\nThe task is complicated by the fact that the mountain's base on the ground level and even everything below the mountain has been dug through by gnome (one may wonder whether they've been looking for the same stuff as Greg...). So, one can consider the shortest way to pass not only along the side surface, but also along the cone's base (and in a specific case both points can lie on the cone's base — see the first sample test)\n\nGreg will be satisfied with the problem solution represented as the length of the shortest path between two points — he can find his way pretty well on his own. He gave you two hours to solve the problem and the time is ticking!",
    "tutorial": "This problem was \"just\" about finding the shortest path on a cone. Unfortunately, even though jury lowered precision requirements to 10^-6 and included all possible general cases in pretests, nobody tried it =( For solution, let's consider all possible cases of two points on the cone surface (including its basement): 1. Both points on the basement. Here it is clear that Euclidean distance between points is the answer to our problem. 2. Both points on the lateral surface. One may think that optimal path is also always lies on the lateral surface. In this case it is easy to find length of an optimal path from geometric considerations (by considering loft of the lateral surface). But 10-th pretest disproves that it is always optimal: 100 100 99 0 1 -99 0 1 Answer: 202.828427124746210 So, optimal path may go through the basement. In this case it has two points that lie at the same time on the basement and on the lateral surface (let's call them A' and B'), so length of the path through this points is easy to find by adding length of the three different segments - AA', A'B' and B'B. So the problem is reduced to finding optimal positions of A' and B'? Let's assume that polar angle of the first point in XOY plane is a1 (0 <= a1 < 2*PI) and polar angle of the second point is a2 (0 <= a2 < 2*PI). Length of the shortest path between A and B passing through the points A' and B' (AA' + A'B' + B'B) is some function of two arguments that we want to minimize - f (a1, a2). One may minimize it using, for example, grid or any other suitable numerical approach. 3. One point on the basement and another point on the lateral surface. This case is similar to the previous one - optimal path passes some point C' on the \"brink\" whose optimal polar angle we are to find. In this case we optimize function of one argument g(polar angle(C')) = AC' + C'B.",
    "tags": [
      "geometry"
    ],
    "rating": 3000
  },
  {
    "contest_id": "143",
    "index": "A",
    "title": "Help Vasilisa the Wise 2",
    "statement": "Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.\n\nThe box's lock looks as follows: it contains $4$ identical deepenings for gems as a $2 × 2$ square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.\n\nThe box is accompanied with $9$ gems. Their shapes match the deepenings' shapes and each gem contains one number from $1$ to $9$ (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.\n\nNow Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.",
    "tutorial": "There are many ways of solving this easiest problem of the contest. I list them in the order of increasing realization difficulty: 1. If you use C++. Take permutation (1, 2, ..., 9). Suppose elements 1-4 are numbers we're looking for. Use next_permutation() to generate all possible combinations of numbers and just check that all conditions are met. 2. Pure brute-force - just 4 nested for() cycles for each unknown number. Here one should not forget to check that all numbers are pairwise different. This takes additional 6 comparisons. 3. One may note that, given the first number in the left upper cell, one may restore rest of the numbers in O(1). So, just check 9 numbers in the first cell (let it be x), restore other numbers from the given conditions: (x, a) (b, c) a = r1-x, b = c1-x, c = r2-b = r2-c1+x and check that they all lie in [0..9] and rest of the conditions are met. 4. O(1) solution - one may derive it from the previous approach: since x+c = d1 => 2*x + r1 - c1 = d1 => x = (d1+c1-r1)/2 So, you find x, check that it is in [0..9], restore all other numbers as in the previous approach and check that all conditions are met.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "143",
    "index": "B",
    "title": "Help Kingdom of Far Far Away 2",
    "statement": "For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to $0.01$, and not up to an integer.\n\nThe King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows:\n\n- A number contains the integer part and the fractional part. The two parts are separated with a character \".\" (decimal point).\n- To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character \",\" (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678\n- In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply \\textbf{discarded} (they are not rounded: see sample tests).\n- When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets.\n- Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign \"$\". If the number should be written in the brackets, then the snake sign should also be inside the brackets.\n\nFor example, by the above given rules number 2012 will be stored in the financial format as \"$2,012.00\" and number -12345678.9 will be stored as \"($12,345,678.90)\".\n\nThe merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?",
    "tutorial": "This was purely technical problem. String type is the best way to store the number. The main steps to get this problem is just to follow problem statement on how a number in the financial format is stored: 1. Divide the number in the input into integer and fractional parts looking for position of the decimal point in the input number (if input number doesn't have decimal point - assume fractional part is empty string) 2. Insert commas into integer part. This is done with one for() / while() cycle 3. Truncate/add zeroes to length 2 in the fractional part 4. Form the answer [integer part].[fractional part]. If initial number had minus in the beginning - add brackets to both sides of the answer.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "144",
    "index": "A",
    "title": "Arrival of the General",
    "statement": "A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all $n$ squad soldiers to line up on the parade ground.\n\nBy the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the \\textbf{first} and the \\textbf{last} soldier are important.\n\nFor example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.\n\nWithin one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.",
    "tutorial": "It's clear that the leftmost soldier with the maximum height should be the first and the rightmost soldier with the minimum height should be the last. Thus we will minimize the number of swaps. And the answer is number of leftmost soldier with the maximum height$- 1 + n -$number of rightmost soldier with the minimum height. And if the leftmost soldier with the maximum height is more right then the rightmost soldier with the minimum height we should subtract one from the answer.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "144",
    "index": "B",
    "title": "Meeting",
    "statement": "The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits.\n\nSome points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number $r_{i}$ — the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to $r_{i}$, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ is $\\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}}$\n\nEach general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place.\n\nThe generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.",
    "tutorial": "Let's try to check all integer points of the table perimeter and add to the answer such of them that don't cover by circles of radiators. Let $x_{a} < x_{b}$ and $y_{a} < y_{b}$, and if it's not true then swap $x_{a}$ and $x_{b}$, $y_{a}$ and $y_{b}$. So generals sit in the next integer points: $(x_{a}, y), (x_{b}, y), (x, y_{a}), (x, y_{b})$, where $x_{a}  \\le  x  \\le  x_{b}$ and $y_{a}  \\le  y  \\le  y_{b}$. We should be attentive when we count the generals who sits in points: $(x_{a}, y_{a}), (x_{a}, y_{b}), (x_{b}, y_{a}), (x_{b}, y_{b})$, that don't count them twice.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "144",
    "index": "C",
    "title": "Anagram Search",
    "statement": "A string $t$ is called an anagram of the string $s$, if it is possible to rearrange letters in $t$ so that it is identical to the string $s$. For example, the string \"aab\" is an anagram of the string \"aba\" and the string \"aaa\" is not.\n\nThe string $t$ is called a substring of the string $s$ if it can be read starting from some position in the string $s$. For example, the string \"aba\" has six substrings: \"a\", \"b\", \"a\", \"ab\", \"ba\", \"aba\".\n\nYou are given a string $s$, consisting of lowercase Latin letters and characters \"?\". You are also given a string $p$, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string $p$ from it, replacing the \"?\" characters by Latin letters. Each \"?\" can be replaced by exactly one character of the Latin alphabet. For example, if the string $p$ = «aba», then the string \"a??\" is good, and the string «?bc» is not.\n\nYour task is to find the number of good substrings of the string $s$ (identical substrings must be counted in the answer several times).",
    "tutorial": "Let's count number of each letter in the second string and save it, for example, in array $a[1..26]$. For the first strings' prefix of length $n$, where $n$ is the length of second string, (it's the first substring) we count number of each letter in array $b[1..26]$. We don't count characters ``\\texttt{?}''. If there are $b[i]  \\le  a[i]$ for all $i$, then it's good substring. Then go to the second substring: subtract from the array $b$ the first character: $b[s[1] - 'a' + 1] -$ and add $n + 1$ character: $b[s[n + 1] - 'a' + 1] + +$. If some of these characters is ``\\texttt{?}'' then we shouldn't do for it the subtraction or addition. Then repeat the showed check and go to the next substring. Let's repeat this procedure for all substrings of length $n$.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "144",
    "index": "D",
    "title": "Missile Silos",
    "statement": "A country called Berland consists of $n$ cities, numbered with integer numbers from $1$ to $n$. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance $l$ from the capital. The capital is located in the city with number $s$.\n\nThe documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly $l$.\n\nBob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.",
    "tutorial": "$d[i]$ --- the minimum distance from vertex $s$ to vertex $i$, that counted by algorithm of Dijkstra. \"et's count the number of points on each edge of the graph that are on the distance $l$ form the vertex $s$ (and $l$ --- the minimum distance from these points to $s$). For edge (u, v): if $d[u] < l$ and $l - d[u] < w(u, v)$ and $w(u, v) - (l - d[u]) + d[v] > l$ then add to the answer the point on this edge, the distance of which to the vertex $u$ is $l - d[u]$; if $d[v] < l$ and $l - d[v] < w(u, v)$ and $w(u, v) - (l - d[v]) + d[u] > l$ then add to the answer the point on this edge, the distance of which to the vertex $v$ is $l - d[v]$; if $d[v] < l$ and $d[u] < l$ and $d[u] + d[v] + w(u, v) = 2 * l$ then add to the answer the point on this edge, the distance of which to the vertex $v$ is $l - d[v]$ and to the vertex $u$ is $l - d[u]$. And if $d[i] = l$, then let's add to the answer this point.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "144",
    "index": "E",
    "title": "Competition",
    "statement": "The secondary diagonal of a square matrix is a diagonal going from the top right to the bottom left corner. Let's define an $n$-degree staircase as a square matrix $n × n$ containing no squares above the secondary diagonal (the picture below shows a 5-degree staircase).\n\nThe squares of the $n$-degree staircase contain $m$ sportsmen.\n\nA sportsman needs one second to move to a side-neighboring square of the staircase. Before the beginning of the competition each sportsman must choose one of the shortest ways to the secondary diagonal.\n\nAfter the starting whistle the competition begins and all sportsmen start moving along the chosen paths. When a sportsman reaches a cell of the secondary diagonal, he stops and moves no more. The competition ends when all sportsmen reach the secondary diagonal. The competition is considered successful if during it no two sportsmen were present in the same square simultaneously. Any square belonging to the secondary diagonal also cannot contain more than one sportsman. If a sportsman at the given moment of time leaves a square and another sportsman comes to it, then they are not considered to occupy the same square simultaneously. Note that other extreme cases (for example, two sportsmen moving towards each other) are impossible as the chosen ways are the shortest ones.\n\nYou are given positions of $m$ sportsmen on the staircase. Your task is to choose among them the maximum number of sportsmen for who the competition can be successful, that is, so that there existed such choice of shortest ways for the sportsmen at which no two sportsmen find themselves in the same square simultaneously. All other sportsmen that are not chosen will be removed from the staircase before the competition starts.",
    "tutorial": "It's clear that the nearest squares of the secondary diagonal to some sportsman form the \"segment\" of the squares of the secondary diagonal. Let's write these segments for each sportsman. Let's consider sportsmen so that we should compare to each sportsman excactly one square of the secondary diagonal from his \"segment\" and to each square of the secondary diagonal no more then one sportsman. It's clear that sportsmen can reach theirs squares without occupying the same square simultaneously with another sportsman. We should maximize the number of choosen sportsmen. And solution of this reformulated problem is greedy.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "145",
    "index": "A",
    "title": "Lucky Conversion",
    "statement": "\\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya has two strings $a$ and $b$ of the same length $n$. The strings consist only of lucky digits. Petya can perform \\underline{operations} of two types:\n\n- replace any one digit from string $a$ by its opposite (i.e., replace $4$ by $7$ and $7$ by $4$);\n- swap any pair of digits in string $a$.\n\nPetya is interested in the minimum number of operations that are needed to make string $a$ equal to string $b$. Help him with the task.",
    "tutorial": "You need to find two numbers: $c47$ (number of such positions $i$, that $a_{i} = 4$ and $b_{i} = 7$) and $c74$ (number of such positions that $a_{i} = 7$ and $b_{i} = 4$). After that the result will be $max(c47, c74)$ (because you need to obtain $min(c47, c74)$ swaps, the rest $max(c47, c74) - min(c47, c74)$ are editings of digits).",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "145",
    "index": "B",
    "title": "Lucky Number 2",
    "statement": "\\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya loves long lucky numbers very much. He is interested in the \\textbf{minimum} lucky number $d$ that meets some condition. Let $cnt(x)$ be the number of occurrences of number $x$ in number $d$ as a substring. For example, if $d = 747747$, then $cnt(4) = 2$, $cnt(7) = 4$, $cnt(47) = 2$, $cnt(74) = 2$. Petya wants the following condition to fulfil simultaneously: $cnt(4) = a_{1}$, $cnt(7) = a_{2}$, $cnt(47) = a_{3}$, $cnt(74) = a_{4}$. Petya is not interested in the occurrences of other numbers. Help him cope with this task.",
    "tutorial": "Let we have some string result $s$. Let then delete all repititions, i. e. while we have some pair adjacent equal digits, we delete one of them. Let call formed string a root. In root there will be no adjacent equal digits, so $|cnt(47) - cnt(74)|  \\le  1$. So, if $|a_{3} - a_{4}| > 1$, then answer is \"-1\". Now, if we would know the root, that will be used in our result, we can create result. You can see, that if $a_{3} = a_{4}$, then root must be $47474747...474$ or $747474...747$. If $a_{3} < a_{4}$, then root is $74747474....74$. If $a_{3} > a_{4}$, then root is $474747...47$. Length of the root must be such that it fulfill $a_{3}$ and $a_{4}$. Now, when you have a root, you can build result. You just need to find first occurrence of $4$ in root and insert the rest of $4$ from $a_{1}$ right next to that digit. To add the rest of $7$, you need to find last occurrence of $7$ in root. The answer does not exits if, after constructing the root, you have used more $4$ than $a_{1}$ or more $7$ than $a_{2}$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1800
  },
  {
    "contest_id": "145",
    "index": "C",
    "title": "Lucky Subsequence",
    "statement": "\\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya has sequence $a$ consisting of $n$ integers.\n\nThe subsequence of the sequence $a$ is such subsequence that can be obtained from $a$ by removing zero or more of its elements.\n\nTwo sequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, any sequence of length $n$ has exactly $2^{n}$ different subsequences (including an empty subsequence).\n\nA subsequence is considered lucky if it has a length exactly $k$ and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times).\n\nHelp Petya find the number of different lucky subsequences of the sequence $a$. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "As you probably know, the number of lucky numbers in range $[1;10^{9}]$ is $1022$. We use this fact to solve problem. Let $C[i]$ - number of occurrences of $i$-th lucky number in array $a$. Now we schould calculate DP with parameters DP[pos][cnt] - what is the number of subsequences that we use lucky numbers up to $pos$-th and our subsequence contains exactly $cnt$ lucky number. If we are on state DP[pos][cnt] we can do two things: do not use $pos$-th lucky number (and do DP[pos+1][cnt] += DP[pos][cnt]) or use $pos$-th lucky (and do DP[pos+1][cnt+1] += DP[pos][cnt]*C[pos], because you have C[pos] of $pos$-th lucky number). Now we need to find total result. To do that we iterate through the number of lucky numbers in our subsequence $i$. Then you need to multiple that number by $C(count_{unlucky}, k - i)$ (bin. coefficient), where $count_{unlucky}$ - number of unlucky numbers of sequence. Sum for all such $i$ will be the total result.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "145",
    "index": "D",
    "title": "Lucky Pair",
    "statement": "\\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya has an array $a$ of $n$ integers. The numbers in the array are numbered starting from $1$. Unfortunately, Petya has been misbehaving and so, his parents don't allow him play with arrays that have many lucky numbers. It is guaranteed that no more than $1000$ elements in the array $a$ are lucky numbers.\n\nPetya needs to find the number of pairs of non-intersecting segments $[l_{1};r_{1}]$ and $[l_{2};r_{2}]$ ($1 ≤ l_{1} ≤ r_{1} < l_{2} ≤ r_{2} ≤ n$, all four numbers are integers) such that there's no such lucky number that occurs simultaneously in the subarray $a[l_{1}..r_{1}]$ and in the subarray $a[l_{2}..r_{2}]$. Help Petya count the number of such pairs.",
    "tutorial": "The main point of this problem is that number of lucky numbers in array is $ \\le  1000$. Imagine that there is array of $1000$ number in range $[1;1000]$ each, and you want to find number of such pairs that there is no equal number in both segments. How to solve this problem? Let we have fixed left point of right segment, let it be $i$. The you should iterate through all $j$ $(i  \\le  j)$ - right point of right segment. If you have some fixed right segment $[i;j]$, then there is some set $S$ of numbers that are in that right segment. So, segment $[0;i - 1]$ will be divided in some subsegments that don't contain any number from $S$. For example, let $S$ = ${1, 2, 3}$ and segment $[0;i - 1]$ is $[2, 4, 2, 3, 6, 5, 7, 1]$, then there will be such subsegments (0-based numeration): $[1;1]$, $[4;6]$. Of course, any subsegment of that subsegments will be good too: they dont contain any number from $S$, too. So, you can keep in $set$ (or some structure like $set$) all good subsegments and keep number of all good subsegments in $[0;i - 1]$. When you iterate $j$ from $i$ to $n - 1$, you will add some numbers to $S$. When you add some number in $S$, you should add all occurrences of that number in subarray $[0;i]$. Notice, that when some number is already in $S$, you don't need to look at that numbers. So, for fixed $i$ you should do $O(n * logn)$ operations - any number from $a[0;i - 1]$ will be added at most once to $set$. Now, we have not only lucky numbers. So, the problem is the same, but between number there are some \"bad\" numbers - in this case this are unlucky numbers. But, you can notice, that if we will fix only such $i$ that $a[i]$ is lucky and iterate $j$ only such that $a[j]$ is lucky then you can calculate result in the same way that in simpler problem. But that method allow you to only count such pairs that right one contains some lucky number. So you also need to count other ones. To do so you can fix some $i$ - left point of right segment, such that $a[i]$ is unlucky. Let $F(i)$ equals to minimum such $j$ $(j > i)$ that $a[i]$ is lucky. Then there are $F(i) - i$ ways to expand right segment. All such right segments doesn't contain any lucky number. So any left segment will be good. And there are $i * (i + 1) / 2$ of such left segments (0-based).",
    "tags": [
      "combinatorics",
      "data structures",
      "implementation"
    ],
    "rating": 2900
  },
  {
    "contest_id": "145",
    "index": "E",
    "title": "Lucky Queries",
    "statement": "\\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya brought home string $s$ with the length of $n$. The string only consists of lucky digits. The digits are numbered from the left to the right starting with $1$. Now Petya should execute $m$ queries of the following form:\n\n- \\underline{switch $l$ $r$} — \"switch\" digits (i.e. replace them with their opposites) at all positions with indexes from $l$ to $r$, inclusive: each digit $4$ is replaced with $7$ and each digit $7$ is replaced with $4$ $(1 ≤ l ≤ r ≤ n)$;\n- \\underline{count} — find and print on the screen the length of the longest non-decreasing subsequence of string $s$.\n\nSubsequence of a string $s$ is a string that can be obtained from $s$ by removing zero or more of its elements. A string is called non-decreasing if each successive digit is not less than the previous one.\n\nHelp Petya process the requests.",
    "tutorial": "To solve this problem you need to handle segment tree with following information: n4: number of $4$-digits in node range. n7: number of $7$-digits in node range. n47: maximum non-decreasing subsequence in range. n74: maximum non-increasing subsequence in range. When we reverse digits in some node we just swap(n4, n7), swap(n47, n74). When we update node we keep n4(father) = n4(left_son) + n4(right_son), n47(father) = max(n47(left_son) + n7(right_son), n4(left_son) + n47(right_son), n4(left_son) + n7(right_son)). Then for each $count$ query result is $n47$.",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "146",
    "index": "A",
    "title": "Lucky Ticket",
    "statement": "\\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals $n$ ($n$ is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first $n / 2$ digits) equals the sum of digits in the second half (the sum of the last $n / 2$ digits). Check if the given ticket is lucky.",
    "tutorial": "In this problem everything is obvious: if all digits are lucky and sum of the digits of the first half equals to the sum of the digits of the second half, then answer is YES, in other case - NO. All this can be checked by single loop through all the digits.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "146",
    "index": "B",
    "title": "Lucky Mask",
    "statement": "\\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \\textbf{4} and \\textbf{7}. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.}\n\nPetya calls a \\underline{mask} of a positive integer $n$ the number that is obtained after successive writing of all lucky digits of number $n$ from the left to the right. For example, the mask of number $72174994$ is number $7744$, the mask of $7$ is $7$, the mask of $9999047$ is $47$. Obviously, mask of any number is always a lucky number.\n\nPetya has two numbers — an arbitrary integer $a$ and a lucky number $b$. Help him find the minimum number $c$ $(c > a)$ such that the mask of number $c$ equals $b$.",
    "tutorial": "You can see that, in worst case, the answer will be equal to $177777$. It can't be greater. So, only thing you need is to write some function $F(x)$ which will return mask of the $x$. After that you need to write such kind of code: $x$ = $a + 1$; while ($F(x)$ is not equal to $b$) increase $x$; and $x$ will contain the answer.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "148",
    "index": "A",
    "title": "Insomnia cure",
    "statement": "«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.\n\nHowever, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every $k$-th dragon got punched in the face with a frying pan. Every $l$-th dragon got his tail shut into the balcony door. Every $m$-th dragon got his paws trampled with sharp heels. Finally, she threatened every $n$-th dragon to call her mom, and he withdrew in panic.\n\nHow many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of $d$ dragons?",
    "tutorial": "The number of dragons D can be quite small, so the problem can be solved in a straightforward way, by iterating over dragons 1 through D and checking each dragon individually. Time complexity of such solution is O(D). There exists a smarter solution with O(1) complexity, based on inclusion-exclusion principle. You'll have to count the numbers of dragons which satisfy at least one, two, three or four of the damage conditions $N_{i}$, i.e., dragons who have index divisible by LCM of the corresponding sets of numbers. Remember that the number of numbers between 1 and D which are divisible by T equals $D / T$. Finally, the number of dragons that get damaged equals $N_{1} - N_{2} + N_{3} - N_{4}$. You'd have to use this method if the total number of dragons was too large for iterating over it.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "148",
    "index": "B",
    "title": "Escape",
    "statement": "The princess is going to escape the dragon's cave, and she needs to plan it carefully.\n\nThe princess runs at $v_{p}$ miles per hour, and the dragon flies at $v_{d}$ miles per hour. The dragon will discover the escape after $t$ hours and will chase the princess immediately. Looks like there's no chance to success, but the princess noticed that the dragon is very greedy and not too smart. To delay him, the princess decides to borrow a couple of bijous from his treasury. Once the dragon overtakes the princess, she will drop one bijou to distract him. In this case he will stop, pick up the item, return to the cave and spend $f$ hours to straighten the things out in the treasury. Only after this will he resume the chase again from the very beginning.\n\nThe princess is going to run on the straight. The distance between the cave and the king's castle she's aiming for is $c$ miles. How many bijous will she need to take from the treasury to be able to reach the castle? If the dragon overtakes the princess at exactly the same moment she has reached the castle, we assume that she reached the castle before the dragon reached her, and doesn't need an extra bijou to hold him off.",
    "tutorial": "In this problem it was enough to simulate the sequence of events that happen on the line between the cave and the castle. My solution focused on two types of evens - \"the dragon is in the cave and sets off after the princess\" and \"the dragon and the princess are at the same coordinate\"; in this case it's enough to keep track of time and princess' coordinate, no need to store dragon's one. The first type of event happens for the first time at time T, when the princess' coordinate is $T * V_{p}$. If at this time she has already reached the castle, no bijous are needed. Otherwise we can start iterating. The time between events of first and second type equals the princess' coordinate at the moment of first event, divided by $V_{d} - V_{p}$. Adjust the princess' coordinate by the distance she will cover during this time and check whether she reached the castle again. If she didn't, she'll need a bijou - increment the number of bijous required. The second part of the loop processes the return of the dragon, i.e., the transition from second type of event to the first one. The time between the events equals princess' new coordinate, divided by the dragon's speed, plus the time of straightening things out in the treasury. Adjust princess' coordinate again and return to the start of the loop (you don't need to check whether the princess reached the castle at this stage, since it doesn't affect the return value). The complexity of the algorithm can be estimated practically: the number of loop iterations will be maximized when dragon's speed and distance to the castle are maximum, and the rest of parameters are minimum. This results in about 150 bijous and the same number of iterations. You'll also need to check for the case $V_{p}  \\ge  V_{d}$ separately - the dragon can be old and fat and lazy, and he might never catch up with the princess.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "148",
    "index": "D",
    "title": "Bag of mice",
    "statement": "The dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chance.\n\nThey take turns drawing a mouse from a bag which initially contains $w$ white and $b$ black mice. The person who is the first to draw a white mouse wins. After each mouse drawn by the dragon the rest of mice in the bag panic, and one of them jumps out of the bag itself (the princess draws her mice carefully and doesn't scare other mice). \\textbf{Princess draws first.} What is the probability of the princess winning?\n\nIf there are no more mice in the bag and nobody has drawn a white mouse, the dragon wins. Mice which jump out of the bag themselves are not considered to be drawn (do not define the winner). Once a mouse has left the bag, it never returns to it. Every mouse is drawn from the bag with the same probability as every other one, and every mouse jumps out of the bag with the same probability as every other one.",
    "tutorial": "Initially this problem was a boring homework one about drawing balls out of the bag. But seriously, do you think a dragon would have something so mundane as a bag of balls in his cave? And he definitely could find some use for a bag of mice - for example, using them to scare the princess or as a snack. If mice were balls and never jumped out of the bag, the problem would be doable in a single loop. Suppose that at some step we have W white and B black mice left in the bag, and the probability to get into this state is P (initially W and B are input values, and P = 1). The absolute probability to get a white mouse at this step is $P * W / (B + W)$ (the probability of getting to this state, multiplied by the conditional probability of getting white mouse). If it's princess' turn to draw, this probability adds to her winning probability, otherwise her winning probability doesn't change. To move to the next iteration, we need the game to continue, i.e., a black mouse to be drawn on this iteration. This means that the number of black mice decreases by 1, and the probability of getting to the next iteration is multiplied by $B / (B + W)$. Once we've iterated until we're out of black mice, we have the answer. Unfortunately, the mice in the bag behave not as calmly as the balls. This adds uncertainty - we don't know for sure what state we will get to after the dragon's draw. We'll need a recursive solution to handle this (or dynamic programming - whichever one prefers). When we solve a case for (W, B), the princess' and the dragon's draws are processed in a same way, but to process the mouse jumping out of the bag, we'll need to combine the results of solving subproblems (W, B - 3) and (W - 1, B - 2). The recursive function of the reference solution is: map<pair<int, int>, double> memo; double p_win_1_rec(int W, int B) { if (W <= 0) return 0; if (B <= 0) return 1; pair<int, int> args = make_pair(W, B); if (memo.find(args) != memo.end()) { return memo[args]; } // we know that currently it's player 1's turn // probability of winning from this draw double ret = W * 1.0 / (W + B), cont_prob = B * 1.0 / (W + B); B--; // probability of continuing after player 2's turn cont_prob *= B * 1.0 / (W + B); B--; // and now we have a choice: the mouse that jumps is either black or white if (cont_prob > 1e-13) { double p_black = p_win_1_rec(W, B - 1) * (B * 1.0 / (W + B)); double p_white = p_win_1_rec(W - 1, B) * (W * 1.0 / (W + B)); ret += cont_prob * (p_black + p_white); } memo[args] = ret; return ret; }The time complexity of recursion with memoization is O(W*B), i.e., the number of different values the input can take. Note that in this implementation access to the map adds log(W*B) complexity, but you can avoid this by storing the values in an 2-dimensional array.",
    "tags": [
      "dp",
      "games",
      "math",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "148",
    "index": "E",
    "title": "Porcelain",
    "statement": "During her tantrums the princess usually smashes some collectable porcelain. Every furious shriek is accompanied with one item smashed.\n\nThe collection of porcelain is arranged neatly on $n$ shelves. Within each shelf the items are placed in one row, so that one can access only the outermost items — the leftmost or the rightmost item, not the ones in the middle of the shelf. Once an item is taken, the next item on that side of the shelf can be accessed (see example). Once an item is taken, it can't be returned to the shelves.\n\nYou are given the values of all items. Your task is to find the maximal damage the princess' tantrum of $m$ shrieks can inflict on the collection of porcelain.",
    "tutorial": "This problem involved dynamic programming with precalculation. The first part of the solution was to precalculate the maximal cost of i items taken from the shelf (i ranging from 1 to the number of items on the shelf) for each shelf. Note that this can't be done greedily: this can be seen on the shelf 6: 5 1 10 1 1 5. The second part is a standard dynamic programming, which calculates the maximal cost of items taken for index of last shelf used and total number of items taken. To advance to the next shelf, one has to try all possible numbers of items taken from it and increase the total cost of items taken by corresponding precalculated values.",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "149",
    "index": "A",
    "title": "Business trip",
    "statement": "What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...\n\nToday Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. \"Wait a second!\" — thought Petya. He know for a fact that if he fulfills the parents' task in the $i$-th ($1 ≤ i ≤ 12$) month of the year, then the flower will grow by $a_{i}$ centimeters, and if he doesn't water the flower in the $i$-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by $k$ centimeters.\n\nHelp Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by $k$ centimeters.",
    "tutorial": "First, it is clear that if the sum of all numbers $a_{i}$ is less than $k$, then Peter in any case will not be able to grow a flower to the desired height, and you should output <<-1>>. Secondly, it is easy to see that if we want to choose a one month of two, in which we watered the flower, it is better to choose one where the number of $a_{i}$ is more. Thus, the solution is very simple: let's take months in descending order of numbers $a_{i}$ and in these months water flowers. As soon as the sum of the accumulated $a_{i}$ becomes greater than or equal to $k$ - should stop the process, the answer is found.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "149",
    "index": "B",
    "title": "Martian Clock",
    "statement": "Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. \"What ungentlemanly behavior!\" — you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored adventure stories that featured lasers and robots.\n\nToday Petya is watching a shocking blockbuster about the Martians called \"R2:D2\". What can \"R2:D2\" possibly mean? It might be the Martian time represented in the Martian numeral system. Petya knows that time on Mars is counted just like on the Earth (that is, there are $24$ hours and each hour has $60$ minutes). The time is written as \"$a$:$b$\", where the string $a$ stands for the number of hours (from $0$ to $23$ inclusive), and string $b$ stands for the number of minutes (from $0$ to $59$ inclusive). The only thing Petya doesn't know is in what numeral system the Martian time is written.\n\nYour task is to print the radixes of all numeral system which can contain the time \"$a$:$b$\".",
    "tutorial": "In this task required only the ability to work with different numeral systems. Let's try to go through numeral bases, each base to check whether it is permissible, as well as convert hours and minutes to the decimal system and compared with 24 and 60, respectively. What is maximal base, that we need to check? In fact, it is enough to 60, because 60 - upper limit on the allowable number. It follows from the fact that if the number in an unknown number system consists of one digit, then its value in decimal not ever change, otherwise its value is not less than the base. It is also worth to consider the case with the response <<-1>>, for this example, you can check a big base, such as 100, and even if the time for him correct, then for all large, it is also correct and the answer is <<-1>>.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "149",
    "index": "C",
    "title": "Division into Teams",
    "statement": "Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).\n\nThe key in football is to divide into teams fairly before the game begins. There are $n$ boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic $a_{i}$ (the larger it is, the better the boy plays).\n\nLet's denote the number of players in the first team as $x$, the number of players in the second team as $y$, the individual numbers of boys who play for the first team as $p_{i}$ and the individual numbers of boys who play for the second team as $q_{i}$. Division $n$ boys into two teams is considered fair if three conditions are fulfilled:\n\n- Each boy plays for exactly one team ($x + y = n$).\n- The sizes of teams differ in no more than one ($|x - y| ≤ 1$).\n- The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: \\[\n|\\sum_{i=1}^{x}a_{p_{i}}-\\sum_{i=1}^{y}a_{q_{i}}|\\leq\\operatorname*{max}_{i=1}^{n}a_{i}\n\\]\n\nYour task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.",
    "tutorial": "Sort all the boys on playing skill. Then, if we send in the first team all the boys standing in a sorted array for odd places, and the second - even standing on the ground, then all requirements for division executed. The first two requirements are obviously satisfied. To prove the third we consider the geometric representation: Let each child designated point on the X axis with a value equal his playing skill. Connect the points with segments numbered 1 and 2, 3 and 4, and so on. If $n$ is odd, then join the last point with the nearest the previous one. Obviously, all these segments don't intersect in pairs, except at the points, and their total length is equal to the difference amounts to play boys' skills contained into the first team and second team. It is also clear that all of these segments completely contained in the interval $[0, max(a_{i})]$, as well as the pairs are a length of zero crossing, the third requirement is satisfied, which we proved.",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "149",
    "index": "D",
    "title": "Coloring Brackets",
    "statement": "Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.\n\nYou are given string $s$. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening (\"(\") and closing (\")\") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as \"(())()\" and \"()\" are correct bracket sequences and such sequences as \")()\" and \"(()\" are not.\n\nIn a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one.\n\nYou are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled:\n\n- Each bracket is either not colored any color, or is colored red, or is colored blue.\n- For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored.\n- No two neighboring colored brackets have the same color.\n\nFind the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "We introduce the notation of colors: 0 - black, 1 - red, 2 - blue. Note that a single pair of brackets has 4 different coloring: 0-1, 1-0, 0-2, 2-0. Consider the dynamic programming, where the state is $(l, r, c_{l}, c_{r})$, where the pair $(l, r)$ defines a pair of brackets, and $c_{l}$ and $c_{r}$ denote a fixed color for them. The value of the dynamic is a number of ways to paint all the parenthesis brackets inside the interval $(l, r)$ in compliance with all conditions. We write down all the pairs of brackets that are directly placed into a pair of $(l, r)$, let $k$ of their pieces. Moreover, we consider only the first level of nesting, it is directly attached. In order to calculate the value of the dynamics for the state, within this state shall calculate the another dynamic, where the state is a pair $(i, c)$ which means the number of correct colorings of the first $i$ directly nested parentheses, and all inside them, if the latter closing bracket has a color $c$. Calcing the values of this dynamic is very simple, let's try to paint a $(i + 1)$-th parenthesis in one of four variants, but you should keep in mind possible conflicts. In such dynamics the initial state is a pair $(0, c_{l})$, and the final result is sum over the states of the form $(k, c)$, where $c$ must not conflict with the $c_{r}$. The answer to the whole problem may be calced as the internal dynamic. Time of solution - $O(n^{2})$ by a factor of about 12.",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "149",
    "index": "E",
    "title": "Martian Strings",
    "statement": "During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up.\n\nImagine a Martian who has exactly $n$ eyes located in a row and numbered from the left to the right from $1$ to $n$. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string $s$ consisting of uppercase Latin letters. The string's length is $n$.\n\n\"Ding dong!\" — the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only $m$ Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. \\textbf{More formally, the Martian chooses four numbers $a$, $b$, $c$, $d$, ($1 ≤ a ≤ b < c ≤ d ≤ n$) and opens all eyes with numbers $i$ such that $a ≤ i ≤ b$ or $c ≤ i ≤ d$.} After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.\n\nLet's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.",
    "tutorial": "We will solve the problem separately for each $m$ strings. Thus, suppose we have a string $p$, its length is $l$, and we need to check whether the Martian be seen. We introduce additional arrays: let $pref[i]$ is minimal position in the $s$ of the begin of occurrence $p$ with length exactly $i$, and let $suff[j]$ is the maximum position in the $s$ of the end of occurrence $p$ with length exactly $j$ It is easy to understand that a Martian could see the $p$, if there exists an $i$, that $suff[l - i]  \\ge  pref[i] + l - 1$. How to calculate the arrays? For $pref$ array is sufficient to find Z-function p#s, but for an array of $suff$ - Z-function r(p)#r(s), where $r(t)$ means the reversed string $t$. Using an array of Z-functions calcing of arrays $suff$ and $pref$ is trivial.",
    "tags": [
      "string suffix structures",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "150",
    "index": "A",
    "title": "Win or Freeze",
    "statement": "You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer $q$. During a move a player should write any integer number that is a \\underline{non-trivial} divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called \\underline{non-trivial} if it is different from one and from the divided number itself.\n\nThe first person who \\textbf{can't make a move wins} as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.",
    "tutorial": "if $Q$ is prime or $Q = 1$ than it's victory. We loose if: $Q = p * q$ or $Q = p^{2}$, where $p$ and $q$ are prime. It is quite obvious that it is always possible to move in bad position in any other case. That means all other numbers grants us the victory. We only have to check if $Q$ has a divisor of the loose type. We can easily do it in $O(sqrt(Q))$ time.",
    "tags": [
      "games",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "150",
    "index": "B",
    "title": "Quantity of Strings",
    "statement": "Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly $n$, based on the alphabet of size $m$. Any its substring with length equal to $k$ is a palindrome. How many such strings exist? Your task is to find their quantity modulo $1000000007$ ($10^{9} + 7$). Be careful and don't miss a string or two!\n\nLet us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.",
    "tutorial": "We can offer you two solitions: You can build a graph with positions in sting as a nodes and equality in any substring of length $k$ as edges. Lets denote $e$ the number of components in the graph. The answer is $m^{e}$. Analyze four cases: $k = 1$ or $k > n$, the answer is $m^{n}$. $k = n$, the answer is $m^{(n + 1) / 2}$. $k$ mod $2 = 1$, any string like abababab... is ok, so the answer is $m^{2}$. $k$ mod $2 = 0$, all symbols coincide and the answer is $m$.",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "150",
    "index": "C",
    "title": "Smart Cheater",
    "statement": "I guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus $62$ has exactly $n$ stops (stop $1$ goes first on its way and stop $n$ goes last). The stops are positioned on a straight line and their coordinates are $0 = x_{1} < x_{2} < ... < x_{n}$.\n\nEach day exactly $m$ people use bus $62$. For each person we know the number of the stop where he gets on the bus and the number of the stop where he gets off the bus. A ticket from stop $a$ to stop $b$ ($a < b$) costs $x_{b} - x_{a}$ rubles. However, the conductor can choose no more than one segment NOT TO SELL a ticket for. We mean that conductor should choose C and D (С <= D) and sell a ticket for the segments [$A$, $C$] and [$D$, $B$], or not sell the ticket at all. The conductor and the passenger divide the saved money between themselves equally. The conductor's \"untaxed income\" is sometimes interrupted by inspections that take place as the bus drives on some segment of the route located between two consecutive stops. The inspector fines the conductor by $c$ rubles for each passenger who doesn't have the ticket for this route's segment.\n\nYou know the coordinated of all stops $x_{i}$; the numbers of stops where the $i$-th passenger gets on and off, $a_{i}$ and $b_{i}$ ($a_{i} < b_{i}$); the fine $c$; and also $p_{i}$ — the probability of inspection on segment between the $i$-th and the $i + 1$-th stop. The conductor asked you to help him make a plan of selling tickets that maximizes the mathematical expectation of his profit.",
    "tutorial": "First lets use the linearity of expected value and solve task independently for each passanger. For each path segment (route between neighboring stations) we calculate expected value of profit in case we do not sell a ticket for this segment. In case we sell it the expectation of profit is 0. Now we only need to find the subsegment of segment [a, b] of maximal sum for each passanger. That's easy to do by the segment tree, we only need to calc four values for each node: best - the maximal sum of elements on some subsegment max_left - the maximal sum on prefix max_right - the maximal sum on suffix sum - the sum of all elements",
    "tags": [
      "data structures",
      "math",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "150",
    "index": "D",
    "title": "Mission Impassable",
    "statement": "Market stalls now have the long-awaited game The Colder Scrools V: Nvodsk. The game turned out to be difficult as hell and most students can't complete the last quest (\"We don't go to Nvodsk...\"). That threatened winter exams. The rector already started to wonder whether he should postpone the winter exams till April (in fact, he wanted to complete the quest himself). But all of a sudden a stranger appeared at the door of his office. \"Good afternoon. My name is Chuck and I solve any problems\" — he said.\n\nAnd here they are sitting side by side but still they can't complete the mission. The thing is, to kill the final boss one should prove one's perfect skills in the art of managing letters. One should be a real magician to do that. And can you imagine what happens when magicians start competing...\n\nBut let's put it more formally: you are given a string and a set of integers $a_{i}$. You are allowed to choose any substring that is a palindrome and delete it. At that we receive some number of points equal to $a_{k}$, where $k$ is the length of the deleted palindrome. For some $k$, $a_{k} = $-1, which means that deleting palindrome strings of such length is \\textbf{forbidden}. After a substring is deleted, the remaining part \"shifts together\", that is, at no moment of time the string has gaps. The process is repeated while the string has at least one palindrome substring that can be deleted. All gained points are summed up.\n\nDetermine what maximum number of points can be earned.\n\n\"Oh\" — said Chuck, raising from the chair, — \"I used to love deleting palindromes, just like you, but one day I took an arrow in the Knee\".",
    "tutorial": "In this problem you have to use dynamic programming. For our convenience we will calulate three type of values: $Best[l][r]$ - best result player can achieve on the segment $[l, r]$. $Full[l][r]$ - best result player can achieve on the segment from $[l, r]$ if he fully destroys it. $T[l][r][Len]$ - best result player can achieve on the segment from $[l, r]$ and remain the palindrome of length $len$ and only it. Now solution: $Full[l][r]$. Let's look which move will be the last. This will be removing the palindrome of length $len$ and $c[len]  \\ge  0$. What is the best result we can achieve? $c[len] + T[l][r][len]$. $Best[l][r]$. Either we will destroy all subtring from $l$ to $r$, either there exists a letter which we did not touch. That means that all our moves lies fully to the left or fully to the rigth to that position. So $Best[l][r] = Full[l][r]$ or $Best[l][r]$ = $Best[l][m] + Best[m + 1][r]$ for some $m$, $l  \\le  m < r$. $T[l][r][len]$. $len = 0$, $len = 1$ - two special cases, which is easy to solve without any dynamic. In other case, let's take a look on the left-most position. It either will lie in the result string or not. If not, then let's find the first position which does. Denote it as $m$ ($l < m  \\le  r$). Everything what lies to the left need to be fully deleted. So the answer is $Full[l][m - 1] + T[m][r][len]$ (for $l < m  \\le  r$). Similarly, for the right-most letters. If it does not lies in the result string we remove everything to the right and our result is $T[l][m][len] + Full[m + 1][r]$ (for $l  \\le  m < r$). The last option: both left-most and rigth-most letters lies in the result string. It is possible only if $s[l] = s[r]$. So our result is $T[l + 1][r - 1][len - 2]$ (only if $s[l] = = s[r]$).",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "150",
    "index": "E",
    "title": "Freezing with Style",
    "statement": "This winter is so... well, you've got the idea :-) The Nvodsk road system can be represented as $n$ junctions connected with $n - 1$ bidirectional roads so that there is a path between any two junctions. The organizers of some event want to choose a place to accommodate the participants (junction $v$), and the place to set up the contests (junction $u$). Besides, at the one hand, they want the participants to walk about the city and see the neighbourhood (that's why the distance between $v$ and $u$ should be no less than $l$). On the other hand, they don't want the participants to freeze (so the distance between $v$ and $u$ should be no more than $r$). Besides, for every street we know its beauty — some integer from $0$ to $10^{9}$. Your task is to choose the path that fits in the length limits and has the largest average beauty. We shall define the average beauty as a median of sequence of the beauties of all roads along the path.\n\nWe can put it more formally like that: let there be a path with the length $k$. Let $a_{i}$ be a non-decreasing sequence that contains exactly $k$ elements. Each number occurs there exactly the number of times a road with such beauty occurs along on path. We will represent the path median as number $a_{⌊k / 2⌋}$, assuming that \\textbf{indexation starting from zero} is used. $⌊x⌋$ — is number $х$, rounded down to the nearest integer.\n\nFor example, if $a = {0, 5, 12}$, then the median equals to $5$, and if $a = {0, 5, 7, 12}$, then the median is number $7$.\n\nIt is guaranteed that there will be at least one path with the suitable quantity of roads.",
    "tutorial": "If there exists a path with the median $ \\ge  k$, for some $k$, then there exists a path with the median $ \\ge  q$, for each $q  \\le  k$. That means we can use binary search to calculate the answer. So now the task is: is there any path with the median greater or equal to $Mid$ ? We will calc the edge as $+ 1$ if it's wight $ \\ge  Mid$, or as $- 1$ in other case. Now we only need to check if there exists a path with legal length and the sum greater than or equal to zero. Let's denote some node $V$ as a root. All paths can be divided into two types: that contains $v$, and that do not. Now we are to process all first-type paths and run the algorithm on all subtrees. That is so-called divide-and-conquer strategy. We can trivially show that it is always possible to choose such vertex $v$ that all it's subtrees will have size less than or equal to the size of the whole tree. That means that each node will be proccessed in $LogN$ trees max. So, if we solve the task for one level of recursion in $O(F(N))$, we'll solve it in time $O(F(N) * log^{2}(N))$ on the whole. First, lets get $O(N * Log(N))$. For each node we shall calc it's deepness, cost of the path to the root ans the first edge (the number of the root's subtree). It will be better now to use 2 and 0 as the edges costs, instead of -1 and 1. Now we shall process root's subtrees one by one. For each node we want to know if there exists a node $u$ in any other subtree such that the Unable to parse markup [type=CF_TEX] and $cost[v] - deep[v] + cost[u] - deep[u]  \\ge  0$. To do that we need to know the maximum of the function $(cost[u] - deep[u])$ with the deep values between max(0, $L - deep[v]$) and $R - deep[v]$ inclusive. To achieve $O(N * log(N))$ you need only to use segment tree. To achieve an AC contestants were to write all code optimally, or to think of one more idea. It is possible to have $O(N)$ on one level of recursion and $O(N * log^{2}(N))$ in total if you sort roots subtrees in non-decreasing order and use any structure that can answer getmax query on all segments of length $(R - L + 1)$ and all prefixes and suffixes.",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "151",
    "index": "A",
    "title": "Soft Drinking",
    "statement": "This winter is so cold in Nvodsk! A group of $n$ friends decided to buy $k$ bottles of a soft drink called \"Take-It-Light\" to warm up a bit. Each bottle has $l$ milliliters of the drink. Also they bought $c$ limes and cut each of them into $d$ slices. After that they found $p$ grams of salt.\n\nTo make a toast, each friend needs $nl$ milliliters of the drink, a slice of lime and $np$ grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?",
    "tutorial": "Soda will be enough for $gas$ = $(K$ * $L)$ / $(N$ * $l)$ toasts. Limes will last for $laim = (C * D) / N$ toasts. Salt is enough for $sol = P / (p * N)$ toasts. Total result: $res = min(gas, laim, sol)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "151",
    "index": "B",
    "title": "Phone Numbers",
    "statement": "Winters are just damn freezing cold in Nvodsk! That's why a group of $n$ friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size $s_{i}$ (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.\n\nYou are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type).\n\nIf the phone book of one person contains some number two times, you should count it \\textbf{twice}. That is, each number should be taken into consideration the number of times it occurs in the phone book.",
    "tutorial": "In this task you were to implement the described selection of the maximum elements.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "152",
    "index": "A",
    "title": "Marks",
    "statement": "Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.\n\nOverall the group has $n$ students. They received marks for $m$ subjects. Each student got a mark from $1$ to $9$ (inclusive) for each subject.\n\nLet's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.\n\nYour task is to find the number of successful students in the group.",
    "tutorial": "In this problem you should do exactly what is written in the statement.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "152",
    "index": "B",
    "title": "Steps",
    "statement": "One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: \"How did he do that?\" The answer is simple.\n\nVasya noticed that the yard is a rectangular $n × m$ field. The squares have coordinates $(x, y)$ ($1 ≤ x ≤ n, 1 ≤ y ≤ m$), where $x$ is the index of the row and $y$ is the index of the column.\n\nInitially Vasya stands in the square with coordinates ($x_{c}, y_{c}$). To play, he has got a list of $k$ vectors $(dx_{i}, dy_{i})$ of non-zero length. The game goes like this. The boy considers all vectors in the order from $1$ to $k$, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps).\n\nA step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square $(x, y)$, and the current vector is $(dx, dy)$, one step moves Vasya to square $(x + dx, y + dy)$. A step is considered valid, if the boy does not go out of the yard if he performs the step.\n\nVasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.",
    "tutorial": "Let's find a formula for the position $(x, y)$ and vector $(dx, dy)$, how many steps to stop the boy can do. You should use \"almost\" binary search, for example, see the code written by RAD.",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "152",
    "index": "C",
    "title": "Pocket Book",
    "statement": "One day little Vasya found mom's pocket book. The book had $n$ names of her friends and unusually enough, each name was exactly $m$ letters long. Let's number the names from $1$ to $n$ in the order in which they are written.\n\nAs mom wasn't home, Vasya decided to play with names: he chose three integers $i$, $j$, $k$ ($1 ≤ i < j ≤ n$, $1 ≤ k ≤ m$), then he took names number $i$ and $j$ and swapped their prefixes of length $k$. For example, if we take names \"CBDAD\" and \"AABRD\" and swap their prefixes with the length of $3$, the result will be names \"AABAD\" and \"CBDRD\".\n\nYou wonder how many different names Vasya can write instead of name number $1$, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers $i$, $j$, $k$ independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "In this task, it was necessary to understand that in position $1$ Vasya can get any name of a special form. More exactly, it's the name of form $s$ = $s_{1}$ $s_{2}$ $s_{3}$ $s_{4}$ $...$ $s_{m}$, where $s_{1}$ - the first letter of any of the names, $s_{2}$ - the second letter of any of the names, $...$ $s_{m}$ - $m$-th letter of any of the names. Then the answer to the problem is the product of $cnt_{i}$ ($1  \\le  i  \\le  m$), where $cnt_{i}$ is a number of different letters in the names placed in position $i$.",
    "tags": [
      "combinatorics"
    ],
    "rating": 1400
  },
  {
    "contest_id": "152",
    "index": "D",
    "title": "Frames",
    "statement": "One day Vasya got hold of a sheet of checkered paper $n × m$ squares in size. Our Vasya adores geometrical figures, so he painted two rectangles on the paper. The rectangles' sides are parallel to the coordinates' axes, also the length of each side of each rectangle is no less than 3 squares and the sides are painted by the grid lines. The sides can also be part of the sheet of paper's edge. Then Vasya hatched all squares on the rectangles' \\underline{frames}.\n\nLet's define a rectangle's frame as the set of squares \\textbf{inside} the rectangle that share at least one side with its border.\n\nA little later Vasya found a sheet of paper of exactly the same size and couldn't guess whether it is the same sheet of paper or a different one. So, he asked you to check whether the sheet of paper he had found contains two painted frames and nothing besides them.\n\nPlease note that the frames painted by Vasya can arbitrarily intersect, overlap or even completely coincide.\n\nThe coordinates on the sheet of paper are introduced in such a way that the $X$ axis goes from top to bottom, the $x$ coordinates of the squares' numbers take values from $1$ to $n$ and the $Y$ axis goes from the left to the right and the $y$ coordinates of the squares' numbers take values from $1$ to $m$.",
    "tutorial": "It was necessary to understand if there are two borders or not. Let's distinguish those $x$ - and $y$-coordinates, in which there are at least $3$ consecutive symbols '#', becouse the length of each border is no less then $3$. It is clear that the coordinates of the corners of borders should be chosen only from those selected $x$ and $y$. In general, the various selected $x$ no more then $4$ and various selected $y$ no more then $4$. Except that case when the height or width of the first border is $3$, and length of the second side of this border is more than $3$, and one side of the second border fills a part of the inside first at least. For example: ####### ####### ####### #.....# #######The first border: ####### #.....# ####### ....... .......The second border: ....... ####### #.....# #.....# #######There are $7$ different $y$-coordinates in the example. Carefully processed these cases separately, it is quite simple. (Let's choose $4$ $y$-coordinates: minimum, maximum, second minimum and second maximum). Otherwise, if the amount selected $x$ - and $y$-coordinates no more then $4$, then let's choose opposite corners of the first and second borders and verify that the selected borders - the correct borders and there are no other characters '#'. Checking is carried out at $O(n + m)$ or $O(1)$ (using partial sums).",
    "tags": [
      "brute force"
    ],
    "rating": 2600
  },
  {
    "contest_id": "152",
    "index": "E",
    "title": "Garden",
    "statement": "Vasya has a very beautiful country garden that can be represented as an $n × m$ rectangular field divided into $n·m$ squares. One beautiful day Vasya remembered that he needs to pave roads between $k$ important squares that contain buildings. To pave a road, he can cover some squares of his garden with concrete.\n\nFor each garden square we know number $a_{i}_{j}$ that represents the number of flowers that grow in the square with coordinates $(i, j)$. When a square is covered with concrete, all flowers that grow in the square die.\n\nVasya wants to cover some squares with concrete so that the following conditions were fulfilled:\n\n- all $k$ important squares should necessarily be covered with concrete\n- from each important square there should be a way to any other important square. The way should go be paved with concrete-covered squares considering that neighboring squares are squares that have a common side\n- the total number of dead plants should be minimum\n\nAs Vasya has a rather large garden, he asks you to help him.",
    "tutorial": "The solution of this problem is based on dynamic programming. $dp[mask][v]$ - the value of the minimum correct concrete cover, if we consider as important elements only elements of the mask $mask$, and there are additionally covered the vertex $v = (i, j)$ of the field. There are two types of transfers. First of all we can, as if to cut coverage on the vertex $v$. Then you need to go through subpattern of vertex $submask$, which will go to the left coverage and make an optimizing transfer. Update $dp[mask][v]$ with the value $dp[submask][v] + dp[mask ^ submask][v] - cost(v)$. Second, perhaps in the vertex $v$ in the optimal coverage mask $mask$, which covers the vertex $v$, you can not make the cut separating the set of vertices. In this case, this vertex forms something a kind of <>. And there a vertex $u$ exists, on which we can make the cut, with the whole shortest path from a vertex $u$ to $v$ belongs to the optimal coverage. Let's precalculate the shortest paths between all pairs of cells. Now to make this transition, we should count the value of dynamics $dp[mask][v]$ for all vertices $v$ only on the basis of the first transition. Now you can make the second transition. For all $u$, $dp[mask][v]$, update the value of $dp[mask][u] + dist(v, u) - cost(u)$. Let's process separately state in which exactly one bit in the mask, and the vertex which corresponding to this bit is equal to $v$. In this case the answer is equal to $cost(v)$, of course. Thus, each solution is obtained for the $O(min(3^{k} \\cdot n \\cdot m, 2^{k} \\cdot (n \\cdot m)^{2}))$.",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "154",
    "index": "A",
    "title": "Hometask",
    "statement": "Sergey attends lessons of the $N$-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the $N$-ish language. Sentences of the $N$-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.\n\nSergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of $N$-ish. The spelling rules state that $N$-ish contains some \"forbidden\" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters \"ab\" is forbidden, then any occurrences of substrings \"ab\" and \"ba\" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.\n\nNow Sergey wants to correct his sentence so that it doesn't contain any \"forbidden\" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is \"removed\" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string \"aba\", we get the string \"ba\", and if we cross out the second letter, we get \"aa\".",
    "tutorial": "Constriction saying that no letter occurs in more than one forbidden pair lets us to use the greedy solution. Without the constriction the problem is quite hard. Let's look at all occurences of letters from some pair. They form several continuous substrings divided by some other letters. We can note that in optimal solution the substrings cannot merge, 'cause we can leave at least one letter in each of such parts. So, for each of these substrings problem is solved independently. To resolve conflicts within a substring, one has to remove all letters of some kind, 'cause while there are letters of both kinds there will be conflicts. Clearly, from each continuous substring of forbidden letters we remove all letters of the kind which number is less than another. The answer can be counted in O(kN) with k runs through the string.",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "154",
    "index": "B",
    "title": "Colliders",
    "statement": "By 2312 there were $n$ Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from $1$ to $n$. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.\n\nIn 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals $1$)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.\n\nUpon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).\n\nInitially, all colliders are deactivated. Your program receives multiple requests of the form \"activate/deactivate the $i$-th collider\". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.\n\nTo the request of \"+ i\" (that is, to activate the $i$-th collider), the program should print exactly one of the following responses:\n\n- \"Success\" if the activation was successful.\n- \"Already on\", if the $i$-th collider was already activated before the request.\n- \"Conflict with j\", if there is a conflict with the $j$-th collider (that is, the $j$-th collider is on, and numbers $i$ and $j$ are not relatively prime). In this case, the $i$-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them.\n\nThe request of \"- i\" (that is, to deactivate the $i$-th collider), should receive one of the following responses from the program:\n\n- \"Success\", if the deactivation was successful.\n- \"Already off\", if the $i$-th collider was already deactivated before the request.\n\nYou don't need to print quotes in the output of the responses to the requests.",
    "tutorial": "The clueless solution ''store all the enabled numbers and compare each new number with each of them'' works too slow, as we can add all the prime numbers below $n$, number of which is O(n / log n). We can note that for each number k > 1 at any time no more than one collider is turned on which number is divided by k. Let us store an array which has in k-th element the number of turned-on collider which is divided by k, on 0 if there is no such at the moment. To enable the collider with number q we can look over q's divisors and check whether all the array's elements with these numbers have 0's. If some of them has a positive integer, that's the number of collider we conflict with - we can just print it and go on. Otherwise, we have to put q into all the overlooked elements. This works in O(M sqrt(N) + N). There's faster solution as we can store all of the above only for prime divisors. Total size of the prime divisors list for number from 1 to N is O(N log log N). Thus we have a solution with complexity O(N log log N + M log N), as the number of prime divisors of k doesn't exceed log k (exact upper bound - log k / log log k * (1 + o(1)).",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "154",
    "index": "C",
    "title": "Double Profiles",
    "statement": "You have been offered a job in a company developing a large social network. Your first task is connected with searching profiles that most probably belong to the same user.\n\nThe social network contains $n$ registered profiles, numbered from $1$ to $n$. Some pairs there are friends (the \"friendship\" relationship is mutual, that is, if $i$ is friends with $j$, then $j$ is also friends with $i$). Let's say that profiles $i$ and $j$ ($i ≠ j$) are doubles, if for any profile $k$ ($k ≠ i$, $k ≠ j$) one of the two statements is true: either $k$ is friends with $i$ and $j$, or $k$ isn't friends with either of them. Also, $i$ and $j$ can be friends or not be friends.\n\nYour task is to count the number of different unordered pairs ($i, j$), such that the profiles $i$ and $j$ are doubles. Note that the pairs are unordered, that is, pairs ($a, b$) and ($b, a$) are considered identical.",
    "tutorial": "We want to count the number of pairs of vertices in a undirected graph which neighbours' sets are equal up to these vertices. To count the pairs which sets of neighbours are equal we can hash these sets (for instance, count the polynomial hash of adjacency matrix row) and sort the hashes. Than we have to add the pairs of doubles which have an edge between them. We can note that there are no more such pairs than there are edges in the graph. So we can iterate through edges and check hashes for equivalence considering the presence of the edge (in case of polynomial hash we just add some degrees to them and then compare them). Other solution was to count another version of the previous hash, now adding a loop to each vertex, and to count the number of pairs just like in the previous case. Moreover, we could try and sort the whole lists of adjacencies (which previuosly should be sorted too). As their total size is 2M, this works fine too, but needs an accurate realization. Hash solution complexity - O(N log N + M).",
    "tags": [
      "graphs",
      "hashing",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "154",
    "index": "D",
    "title": "Flatland Fencing",
    "statement": "The King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on one, the winner (or rather, the survivor) transfers to the next round.\n\nBefore the battle both participants stand at the specified points on the $Ox$ axis with integer coordinates. Then they make moves in turn. The first participant moves first, naturally. During a move, the first participant can transfer from the point $x$ to any integer point of the interval [$x + a$; $x + b$]. The second participant can transfer during a move to any integer point of the interval [$x - b$; $x - a$]. That is, the options for the players' moves are symmetric (note that the numbers $a$ and $b$ are not required to be positive, and if $a ≤ 0 ≤ b$, then staying in one place is a correct move). At any time the participants can be located arbitrarily relative to each other, that is, it is allowed to \"jump\" over the enemy in any direction. A participant wins if he uses his move to transfer to the point where his opponent is.\n\nOf course, the princess has already chosen a husband and now she wants to make her sweetheart win the tournament. He has already reached the tournament finals and he is facing the last battle. The princess asks the tournament manager to arrange the tournament finalists in such a way that her sweetheart wins the tournament, considering that both players play optimally. However, the initial location of the participants has already been announced, and we can only pull some strings and determine which participant will be first and which one will be second. But how do we know which participant can secure the victory? Alas, the princess is not learned in the military affairs... Therefore, she asks you to determine how the battle will end considering that both opponents play optimally. Also, if the first player wins, your task is to determine his winning move.",
    "tutorial": "As the moves choices are symmetrical for both players, if one player can reach another in one move from some disposition, the other player also can reach the first. So, if we are allowed to stand in one place (i.e. a <= 0 <= b), we can just stand still and wait for another player to come. If she wants to win, she will have to step within our reach before that so that we can get her. So, if the first player doesn't reach the second initially, there is a draw as no one can ensure her victory. Thus we finished the case a <= 0 <= b: either the first player wins in one move, or there is a draw. Now, let a and b have the same sign. Denote d = x2 - x1. If a <= b < 0, we can go to the situation with (d, a, b) = (-d, -b, -a), which is similar to the initial. So later on 0 < a. So we have the following game: there are integers d and 0 < a <= b. In one move each player can substract an arbitrary integer number from segment [a; b] from d. The player who gets d = 0 after her move wins. If at some point d < 0, a draw is proclaimed (as no one can win anymore). The interesting case is d > 0. Note that if d mod (a + b) = 0, the second player can use the symmetrical strategy: for every first player's move x of she can make a move a + b - x, and support the condition d mod (a + b) = 0. As d decreases, the second player eventually moves to 0 and wins. So, if d mod (a + b) = 0, the second player wins. Thus, if d mod (a + b) is in [a; b], the first player wins, as he can reduce the game to the previous case by letting the second player move in the losing situation. What about all the other situations? Turns out all the other position are draws. We prove that by induction: let d = k(a + b) + l, where l in [0; a + b). Case l = 0, as we just proved, is losing, cases l in [a; b] are winning. If l is in [1; a - 1], we cannot move to losing position (we use the induction assumption for lesser k), but after the move a, we move to the draw position (if k = 0, we move to the negative number, otherwise we get into [(k - 1)(a + b) + b + 1; k(a + b) - 1] segment, every position from which is a draw by assumption). Similarily for l = [b + 1; a + b - 1], move to a draw - b.",
    "tags": [
      "games",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "154",
    "index": "E",
    "title": "Martian Colony",
    "statement": "The first ship with the Earth settlers landed on Mars. The colonists managed to build $n$ necessary structures on the surface of the planet (which can be regarded as a plane, and the construction can be regarded as points on it). But one day the scanners recorded suspicious activity on the outskirts of the colony. It was decided to use the protective force field generating system to protect the colony against possible trouble.\n\nThe system works as follows: the surface contains a number of generators of the field (they can also be considered as points). The active range of each generator is a circle of radius $r$ centered at the location of the generator (the boundary of the circle is also included in the range). After the system is activated, it stretches the protective force field \\textbf{only over the part of the surface, which is within the area of all generators' activity}. That is, the protected part is the \\textbf{intersection} of the generators' active ranges.\n\nThe number of generators available to the colonists is not limited, but the system of field generation consumes a lot of energy. More precisely, the energy consumption does not depend on the number of generators, but it is directly proportional to the \\textbf{area}, which is protected by the field. Also, it is necessary that all the existing buildings are located within the protected area.\n\nDetermine the smallest possible area of the protected part of the surface containing all the buildings.",
    "tutorial": "We have to find the area of intersection of all circles containing the given set of points (it's clear that the intersection has the least area, and we have an unlimited number of circles). First, what shape does such an intersection have? Its border contains some circle arcs of radius R meeting at some points of convex hull. If we determine which points are present in the border, we can count the total area as the sum of polygon area and several circle segments. So, how to determine those points? It's clear that if there is a circle of radius R containing all the points and having some of them on its border, then this particular point is present in the border of the intersection. If we fix the circle and move it in some direction, it eventually will run into some point - so we can find at least one point. Then we can perform something similar to ''present wrapping'' - go around the convex hull and support the set of the border points while controlling the relative position of the arcs. While this solution is fast, it is very hard to write and it was not assumed that it should be written during the contest. There is much simpler solution based on quite different idea. We build the convex hull of the set so that no three points lie on the same line. Let us take the very large R so that every point of convex hull is present in the intersection border. As we gradually decrease R, some points will start to disappear from the border. How to determine which point falls out first? For point u in the convex hull denote its left and right neighbours l(u) and r(u). It's clear, that the first point to disappear will be such point u which has the largest radius of circle going through u, l(u) and r(u) (when R becomes equal to this radius, two arcs will merge into one in point u, while all the other will have joints in them; we will call this radius critical for u). Then we remove u from convex hull and do not take it into account. We repeat while the largest critical radius is larger than R. The rest points will be exactly the points forming the border. How to do this fast? Note that when we remove some point from the set the critical radii will change only for its two neighbours. Let us store a priority queue containing critical radii along with point numbers. On every iteration we extract the largest critical radius, remove the corresponding point from the set, and refresh the information about the neighbours in the queue. We repeat while the largest radius is greater than R. As we just simulate the process of R decreasing, everything works correctly. The complexity of this procedure is O(n log n), as we have no more than n iterations and on every iteration we perform the constant number of operations with the queue of size at most n. There is an unclear case, when the border contains only two points. Then on the last phase we have three points in the set and the algorithm doesn't have a clue which one to remove as they have equal critical radii. But we know that the triangle with vertices in these points is obtuse-angled, as we cannot shrink the circumcircle of an acute-angle triangle, as that would contradict with the circle existence condition. So we have to remove the point with the obtuse angle.",
    "tags": [
      "geometry"
    ],
    "rating": 3000
  },
  {
    "contest_id": "155",
    "index": "A",
    "title": "I_love_\\%username\\%",
    "statement": "Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.\n\nOne day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).\n\nVasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly \\textbf{more} points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly \\textbf{less} points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.",
    "tutorial": "You should do what is written: go through the sequence and count the elements which are greater or less than all of its predecessors. We don't even have to store the whole sequence, just the current minimum and maximum. Complexity - O(N), but squared still works fine.",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "155",
    "index": "B",
    "title": "Combination",
    "statement": "Ilya plays a card game by the following rules.\n\nA player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number $a_{i}$, and the bottom contains number $b_{i}$, then when the player is playing the card, he gets $a_{i}$ points and also gets the opportunity to play additional $b_{i}$ cards. After the playing the card is discarded.\n\nMore formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number $b_{i}$, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.\n\nOf course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?",
    "tutorial": "Clearly, we can play the cards with $b_{i}$ > 0 first as each of them gives at least one extra move. After that, the number of extra moves left doesn't depend on the order of playing. The left cards all have $b_{i}$ = 0, so we play those of them which have larger $a_{i}$. Simpler version of this solution: sort all the cards by decrease of $b_{i}$, if equal - by decrease of $a_{i}$, and then go through the sorted array from beginning to end, simulate the counter and sum up the points. Remember not to fall over the edge of array if the sum of $b_{i}$'s is larger than the number of cards. Complexity - O(n log n) (or O(n^2), if using bubblesort, which is still accepted).",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "158",
    "index": "A",
    "title": "Next Round",
    "statement": "\"Contestant who earns a score equal to or greater than the $k$-th place finisher's score will advance to the next round, as long as the contestant earns a positive score...\" — an excerpt from contest rules.\n\nA total of $n$ participants took part in the contest ($n ≥ k$), and you already know their scores. Calculate how many participants will advance to the next round.",
    "tutorial": "Just sort. Notice 0 in the array.",
    "tags": [
      "*special",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "158",
    "index": "B",
    "title": "Taxi",
    "statement": "After the lessons $n$ groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the $i$-th group consists of $s_{i}$ friends ($1 ≤ s_{i} ≤ 4$), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?",
    "tutorial": "Choose the 3 and 1 as much as possible. And let 2 combine with themselves. If there are more 1s and 2s, let two 1s combine with 2, and every four 1s take same taxi.",
    "tags": [
      "*special",
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "158",
    "index": "C",
    "title": "Cd and pwd commands",
    "statement": "Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).\n\nDirectories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character \"/\". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as \"..\".\n\nThe command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be \"..\", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or \"..\"), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.\n\nThe command pwd should display the absolute path to the current directory. This path must not contain \"..\".\n\nInitially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.",
    "tutorial": "Implement with stack. If the string begin with '/', let top = 0, else remain the top; Then process the substring one by one, when meeting \"..\" , top--; else remain the top;",
    "tags": [
      "*special",
      "data structures",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "158",
    "index": "D",
    "title": "Ice Sculptures",
    "statement": "The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus $n$ ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular $n$-gon. They are numbered in clockwise order with numbers from 1 to $n$.\n\nThe site of the University has already conducted a voting that estimated each sculpture's characteristic of $t_{i}$ — the degree of the sculpture's attractiveness. The values of $t_{i}$ can be positive, negative or zero.\n\nWhen the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:\n\n- the remaining sculptures form a regular polygon (the number of vertices should be between 3 and $n$),\n- the sum of the $t_{i}$ values of the remaining sculptures is maximized.\n\nHelp the Vice Rector to analyze the criticism — find the maximum value of $t_{i}$ sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.",
    "tutorial": "The number of new regular polygon's edges must be the factor of the given polygon. Listing all the factors take O(sqrt(n)) time. Then choose the best point take O(n). So the time complexity is O(n*sqrt(n)).",
    "tags": [
      "*special",
      "brute force",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "158",
    "index": "E",
    "title": "Phone Talks",
    "statement": "Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has $n$ calls planned. For each call we know the moment $t_{i}$ (in seconds since the start of the day) when it is scheduled to start and its duration $d_{i}$ (in seconds). All $t_{i}$ are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.\n\nMr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second $t$, and the call continues for $d$ seconds, then Mr. Jackson is busy at seconds $t, t + 1, ..., t + d - 1$, and he can start a new call at second $t + d$. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.\n\nMr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most $k$ calls. Note that a call which comes while he is busy talking can be ignored as well.\n\nWhat is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?\n\nNote that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.",
    "tutorial": "It's a classic DP problem. Array dp[i][j] stands for the min rightmost endpoint when choosing at most j segments from the first i segments . dp[i][j] =dp[i][j] = min(dp[i-1][j-1], max(dp[i-1][j],left[i])+length[i]). When the dp array is completed , find the max value of left[i+1]-dp[i][k] and rightmost point - dp[n][k]. Totally take O(n*n).",
    "tags": [
      "*special",
      "dp",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "159",
    "index": "A",
    "title": "Friends or Not",
    "statement": "Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user $A$ sent user $B$ a message at time $t_{1}$, and user $B$ sent user $A$ a message at time $t_{2}$. If $0 < t_{2} - t_{1} ≤ d$, then user $B$'s message was an answer to user $A$'s one. Users $A$ and $B$ are considered to be friends if $A$ answered at least one $B$'s message or $B$ answered at least one $A$'s message.\n\nYou are given the log of messages in chronological order and a number $d$. Find all pairs of users who will be considered to be friends.",
    "tutorial": "Compare every two records and find the right friends. Give every name a unique number so as to avoid counting same friend twice. If a and b is friends, let friend[a][b] = true.",
    "tags": [
      "*special",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "159",
    "index": "B",
    "title": "Matchmaker",
    "statement": "Polycarpus has $n$ markers and $m$ marker caps. Each marker is described by two numbers: $x_{i}$ is the color and $y_{i}$ is the diameter. Correspondingly, each cap is described by two numbers: $a_{j}$ is the color and $b_{j}$ is the diameter. Cap $(a_{j}, b_{j})$ can close marker $(x_{i}, y_{i})$ only if their diameters match, that is, $b_{j} = y_{i}$. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, $a_{j} = x_{i}$.\n\nFind the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.",
    "tutorial": "Establish two hash tables counting the number of the size (say 2) exiting in set makers and set caps. Obviously the sum of min number of every size in two sets is the first answer. Similarly establish two hash tables in order to count the number of the same size and same color. The hash function can be hash(color, size) = color*1000+size.",
    "tags": [
      "*special",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "159",
    "index": "C",
    "title": "String Manipulation 1.0",
    "statement": "One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name $s$, a user can pick number $p$ and character $c$ and delete the $p$-th occurrence of character $c$ from the name. After the user changed his name, he can't undo the change.\n\nFor example, one can change name \"arca\" by removing the second occurrence of character \"a\" to get \"arc\".\n\nPolycarpus learned that some user initially registered under nickname $t$, where $t$ is a concatenation of $k$ copies of string $s$. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name.",
    "tutorial": "Because the length of string is at most 100*2000, so we can build 26 line-segment-trees to count the 26 Latin letters. The way to build tree and find the position of K-th letter is quite simple if you under stand line-segment-tree :)",
    "tags": [
      "*special",
      "binary search",
      "brute force",
      "data structures",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "159",
    "index": "D",
    "title": "Palindrome pairs",
    "statement": "You are given a non-empty string $s$ consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.\n\nIn a more formal way, you have to find the quantity of tuples $(a, b, x, y)$ such that $1 ≤ a ≤ b < x ≤ y ≤ |s|$ and substrings $s[a... b]$, $s[x... y]$ are palindromes.\n\nA palindrome is a string that can be read the same way from left to right and from right to left. For example, \"abacaba\", \"z\", \"abba\" are palindromes.\n\nA substring $s[i... j]$ ($1 ≤ i ≤ j ≤ |s|$) of string $s$ = $s_{1}s_{2}... s_{|s|}$ is a string $s_{i}s_{i + 1}... s_{j}$. For example, substring $s[2...4]$ of string $s$ = \"abacaba\" equals \"bac\".",
    "tutorial": "A dp method is really great~ , sum[i] stands for the number of palindrome string in the first i letters. palindrome[i][j] judges weather the substring i...j is a palindrome string. dp[i] is the answer for the first i letters. dp[i] = dp[i-1]+Sum( palindrome[j][i]*sum[j-1] ) for all j<=i && j>0 . sum[i] = sum[i-1]+Sum(palindrome[j][i]) for all j<=i.",
    "tags": [
      "*special",
      "brute force",
      "dp",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "159",
    "index": "E",
    "title": "Zebra Tower",
    "statement": "Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color $c_{i}$ and size $s_{i}$. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower.\n\nA Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.",
    "tutorial": "sort the array with compare condition (cube[i].color < cube[j].color ||(cube[i].color==cube[j].color && cube[i].size>cube[j].size)). Then for the first i cubes , there is a array Max_cube, Max_cube[j] records the max sum of j cubes' size with same color. To the cube i+1, if it's the k-th largest size of its color. Compare the answer with cube[i+1].size + max(Max_cube[k],Max_cube[k+1],Max_cube[k-1]). The time complexity is O(n*logn).",
    "tags": [
      "*special",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "160",
    "index": "A",
    "title": "Twins",
    "statement": "Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.\n\nNow let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, $n$ coins of arbitrary values $a_{1}, a_{2}, ..., a_{n}$. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.\n\nAs you woke up, you found Mom's coins and read her note. \"But why split the money equally?\" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is \\textbf{strictly larger} than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the \\textbf{minimum number of coins}, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what \\textbf{minimum} number of coins you need to take to divide them in the described manner.",
    "tutorial": "It's obvious that you should take the most valueable coins. so sort values in non-decreasing order, then take coins from the most valueable to the least, until you get strictly more than half of total value. Time complexity depends on the sorting algorithm you use. O(n^2) is also acceptable, but if you use bogosort which runs in O(n!)...",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "160",
    "index": "B",
    "title": "Unlucky Ticket",
    "statement": "Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an \\textbf{even} number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half.\n\nBut of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following \\underline{unluckiness criterion} that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is \\textbf{strictly less} than the corresponding digit from the second one or each digit from the first half is \\textbf{strictly more} than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such \\underline{bijective correspondence} between the digits of the first and the second half of the ticket, that either each digit of the first half turns out \\textbf{strictly less} than the corresponding digit of the second half or each digit of the first half turns out \\textbf{strictly more} than the corresponding digit from the second half.\n\nFor example, ticket $2421$ meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is $2 > 1$ and $4 > 2$), ticket $0135$ also meets the criterion (the sought correspondence is $0 < 3$ and $1 < 5$), and ticket $3754$ does not meet the criterion.\n\nYou have a ticket in your hands, it contains $2n$ digits. Your task is to check whether it meets the unluckiness criterion.",
    "tutorial": "Deal with the situation that \"first half is strictly less than second half\" first. the other one can be solved accordingly. You can use greedy here: sort digits in first and second half seperately. then if the i-th digit in first half is always less than i-th in second half for 1<=i<=n, answer is YES. Time complexity is as same as problem A. Count sort may run faster in O(n+10), but it's not necessary .",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "160",
    "index": "C",
    "title": "Find Pair",
    "statement": "You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing $n$ (not necessarily different) integers $a_{1}$, $a_{2}$, ..., $a_{n}$. We are interested in all possible pairs of numbers ($a_{i}$, $a_{j}$), ($1 ≤ i, j ≤ n$). In other words, let's consider all $n^{2}$ pairs of numbers, picked from the given array.\n\nFor example, in sequence $a = {3, 1, 5}$ are $9$ pairs of numbers: $(3, 3), (3, 1), (3, 5), (1, 3), (1, 1), (1, 5), (5, 3), (5, 1), (5, 5)$.\n\nLet's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair ($p_{1}$, $q_{1}$) is \\underline{lexicographically less} than pair ($p_{2}$, $q_{2}$) only if either $p_{1}$ < $p_{2}$, or $p_{1}$ = $p_{2}$ and $q_{1}$ < $q_{2}$.\n\nThen the sequence, mentioned above, will be sorted like that: $(1, 1), (1, 3), (1, 5), (3, 1), (3, 3), (3, 5), (5, 1), (5, 3), (5, 5)$\n\nLet's number all the pair in the sorted list from $1$ to $n^{2}$. Your task is formulated like this: you should find the $k$-th pair in the ordered list of all possible pairs of the array you've been given.",
    "tutorial": "This is a tricky problem. When contest ends, I found there are 12 pages of accepted submissions while 60 pages of \"WA on pretest 3\" submissions. First of all, sort a[]. A natural consideration is that the answer equals to (a[k/n] , a[k%n]). This algorithm will pass the sample and get \"WA on pretest 3\". In fact, it works only when all a[i] are distinct. To get an AC, let's make elements distinct and weighted. For example, if there are ten 1s, we remain one of them and set its weight as 10. Now go over the whole array. for each element a[i], we can make weight[i]*n pairs using a[i] as first element. If k doesn't exceed that, go over the array again and find the second element, then print the answer. Otherwise, subtract it from K and go on. Sort algorithm working in O(n log n) is acceptable. Java and Pascal users should beware of anti-quicksort tests.",
    "tags": [
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "160",
    "index": "D",
    "title": "Edges in MST",
    "statement": "You are given a connected weighted undirected graph without any loops and multiple edges.\n\nLet us remind you that a graph's \\underline{spanning tree} is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The \\underline{weight} of a tree is defined as the sum of weights of the edges that the given tree contains. The \\underline{minimum spanning tree} (\\textbf{MST}) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique.\n\nYour task is to determine the following for each edge of the given graph: whether it is either included in \\textbf{any} MST, or included \\textbf{at least in one} MST, or \\textbf{not included in any} MST.",
    "tutorial": "Let's take a look at Kruskal Algorithm which solve MST in O(m log m) time. Sort the edges first in weight non-decreasing order, then process each edges. if the edge connects two different connected compoments, add this edge to MST then combine two compoments. We use disjoint-set union here to maintain connectivity. The main point is that only those edges with same weight may replace each other in MST. First of all, sort edges as what Kruskal do. To get the answer, we construct MST in weight non-decreasing order, and process all edges with same weight together. Now on each step we are to face some edges with same weight x and a forest of connected compoments. Note that for an edge, what points it connects does not matter, we only need to know what compoments it connects. Now build a new graph G', each point in G' is a connected compoment in the original forest,and edges are added to connect compoments that it connected before. Time complexity is O(|E|) here, with careful implementation. Let's answer queries on these edges. First of all, if an edge in G' is a loop(connects the same compoment), this edge must not appear in any MSTs. If after deleting an edge V in G', G's connectivity is changed (A connected compoment in G' spilt into two. We call these edges bridge), V must be in any of MST. All edges left can appear in some MSTs, but not any. What's left is to get all of V quickly. Maybe you hear about Tarjan before, he invented an algorithm based on DFS to get all bridges in an edge-undirected graph in O(|V|+|E|). Read this page on Wikipedia for detailed information: http://en.wikipedia.org/wiki/Bridge_(graph_theory) Considering those compoments which don't have any edges connected don't need to be appear in G', we have |V|<=2|E|, so time complexity for Tarjan's DFS is O(|E|), where |E| is count of edges weighted x. Because each edge will be used exactly once in G', total time complexity except sorting is O(m).",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "160",
    "index": "E",
    "title": "Buses and People",
    "statement": "The main Bertown street is represented by a straight line. There are $10^{9}$ bus stops located on the line. The stops are numbered with integers from $1$ to $10^{9}$ in the order in which they follow on the road. The city has $n$ buses. Every day the $i$-th bus drives from stop number $s_{i}$ to stop number $f_{i}$ ($s_{i} < f_{i}$), it stops on all intermediate stops and returns only at night. The bus starts driving at time $t_{i}$ and drives so fast that it finishes driving also at time $t_{i}$. The time $t_{i}$ is different for all buses. The buses have infinite capacity.\n\nBertown has $m$ citizens. Today the $i$-th person should get from stop number $l_{i}$ to stop number $r_{i}$ ($l_{i} < r_{i}$); the $i$-th citizen comes to his initial stop ($l_{i}$) at time $b_{i}$. Each person, on the one hand, wants to get to the destination point as quickly as possible, and on the other hand, definitely does not want to change the buses as he rides. More formally: the $i$-th person chooses bus $j$, with minimum time $t_{j}$, such that $s_{j} ≤ l_{i}$, $r_{i} ≤ f_{j}$ and $b_{i} ≤ t_{j}$.\n\nYour task is to determine for each citizen whether he can ride to the destination point today and if he can, find the number of the bus on which the citizen will ride.",
    "tutorial": "As what problem setter say, we sort the people and bus together with non-decreasing order of time first(if a bus and a person has same time, put the person first). Solving it by \"For each person find which bus he should take\" will become rather difficult, so let's take another idea: For each bus, find who it will take. Abstract a person as a element in currently waiting list. Now, go over the sorted people and buses, we should apply two operations: For a person, add it to the list. For a bus, find all person in list satisfying sj  \\le  li, ri  \\le  fj ,remove them from the list and record the answer.(bi  \\le  tj is hold, because we process these operation by time order.) You will find it easy to solve this using any kind of balanced trees, like AVL or SBT. For each node i on balanced tree, we store r[i] as keyword and l[i] as value, then maintain the maxinum l[i] on every subtrees. Operating on a person is to add him to the tree. When dealing with a bus, we find the node i with maxinum l[i] in the range x<=f[j] (x is keyword), if l[i]>=s[j] is satisfied, delete the node i, set ans[i]=j, update the tree and search again until found l[i]<s[j]. If you are not familiar with balanced tree, discretize every r[i] and f[j], then use a segment tree to solve it. Time complexity is O((n+m) log (n+m)) with balanced trees or segment tree.",
    "tags": [
      "binary search",
      "data structures",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "161",
    "index": "A",
    "title": "Dress'em in Vests!",
    "statement": "The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.\n\nThe Two-dimensional kingdom has a regular army of $n$ people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the $i$-th soldier indicated size $a_{i}$. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from $a_{i} - x$ to $a_{i} + y$, inclusive (numbers $x, y ≥ 0$ are specified).\n\nThe Two-dimensional kingdom has $m$ vests at its disposal, the $j$-th vest's size equals $b_{j}$. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The $i$-th soldier can put on the $j$-th vest, if $a_{i} - x ≤ b_{j} ≤ a_{i} + y$.",
    "tutorial": "Consider troopers in the sorted order, as in the input data. One can prove that for the current (minimal) trooper the best choice is the vest with the minimal possible $b_{j}$. So we can solve this problem using \"moving pointers\" method. The first pointer iterates over troopers and the second one chooses minimal unused vest that $b_{j} - x  \\ge  a_{i}$. The complexity of the solution is $O(n + m)$.",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "161",
    "index": "B",
    "title": "Discounts",
    "statement": "One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a $50%$ discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!\n\nPolycarpus has $k$ carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.\n\nPolycarpus must use all $k$ carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.",
    "tutorial": "This problem can be solved greedy. Let us have $x$ stools. One can prove that it is always correct to arrange $min(k - 1, x)$ maximal stools into $min(k - 1, x)$ carts one by one. All remaining stools and pencils should be put into remaining empty carts. Finally, we have either zero or one empty cart.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "161",
    "index": "C",
    "title": "Abracadabra",
    "statement": "Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm:\n\n- On the first step the string consists of a single character \"a\".\n- On the $k$-th step Polycarpus concatenates two copies of the string obtained on the $(k - 1)$-th step, while inserting the $k$-th character of the alphabet between them. Polycarpus uses the alphabet that consists of lowercase Latin letters and digits (a total of 36 characters). The alphabet characters are numbered like this: the 1-st character is \"a\", the 2-nd — \"b\", ..., the 26-th — \"z\", the 27-th — \"0\", the 28-th — \"1\", ..., the 36-th — \"9\".\n\nLet's have a closer look at the algorithm. On the second step Polycarpus will concatenate two strings \"a\" and insert the character \"b\" between them, resulting in \"aba\" string. The third step will transform it into \"abacaba\", and the fourth one - into \"abacabadabacaba\". Thus, the string constructed on the $k$-th step will consist of $2^{k} - 1$ characters.\n\nPolycarpus wrote down the string he got after 30 steps of the given algorithm and chose two non-empty substrings of it. Your task is to find the length of the longest common substring of the two substrings selected by Polycarpus.\n\nA substring $s[i... j]$ ($1 ≤ i ≤ j ≤ |s|$) of string $s$ = $s_{1}s_{2}... s_{|s|}$ is a string $s_{i}s_{i + 1}... s_{j}$. For example, substring $s[2...4]$ of string $s$ = \"abacaba\" equals \"bac\". The string is its own substring.\n\nThe longest common substring of two strings $s$ and $t$ is the longest string that is a substring of both $s$ and $t$. For example, the longest common substring of \"contest\" and \"systemtesting\" is string \"test\". There can be several common substrings of maximum length.",
    "tutorial": "Consider the case when the maximal character in the string is in the answer. Then the answer equals $min(r_{1}, r_{2}) - max(l_{1}, l_{2})$. Otherwise, we cut both strings around this character (here we might get empty strings) and run the algorithm recursively for every pair of strings we get. One can prove that this solutions works in $O(k)$, where $k$ is the values of the maximal character.",
    "tags": [
      "divide and conquer"
    ],
    "rating": 2400
  },
  {
    "contest_id": "161",
    "index": "D",
    "title": "Distance in Tree",
    "statement": "A tree is a connected graph that doesn't contain any cycles.\n\nThe distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.\n\nYou are given a tree with $n$ vertices and a positive number $k$. Find the number of distinct pairs of the vertices which have a distance of exactly $k$ between them. Note that pairs ($v$, $u$) and ($u$, $v$) are considered to be the same pair.",
    "tutorial": "This problem can be solved using dynamic programming. Let us hang the tree making it rooted. For every vertex $v$ of the tree, let us calculate values $d[v][lev]$ ($0  \\le  lev  \\le  k$) - the number of vertices in the subtree, having distance $lev$ to them. Note, that $d[v][0] = 0$. Then we calculate the answer. It equals the sum for every vertex $v$ of two values: The number of ways of length $k$, starting in the subtree of $v$ and finishing in $v$. Obviously, it equals $d[v][k]$. The number of ways of length $k$, starting in the subtree of $v$ and finishing in the subtree of $v$. This equals the sum for every son $u$ of $v$ the value: $0.5\\cdot\\sum_{x=1}^{x=k-1}d[u][x-1](d[v][k-x]-d[u][k-x-1])$. Accumulate the sum for all vertices and get the solution in $O(n \\cdot k)$.",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "161",
    "index": "E",
    "title": "Polycarpus the Safecracker",
    "statement": "Polycarpus has $t$ safes. The password for each safe is a square matrix consisting of decimal digits '0' ... '9' (the sizes of passwords to the safes may vary). Alas, Polycarpus has forgotten all passwords, so now he has to restore them.\n\nPolycarpus enjoys prime numbers, so when he chose the matrix passwords, he wrote a prime number in each row of each matrix. To his surprise, he found that all the matrices turned out to be symmetrical (that is, they remain the same after transposition). Now, years later, Polycarp was irritated to find out that he remembers only the prime numbers $p_{i}$, written in the first lines of the password matrices.\n\nFor each safe find the number of matrices which can be passwords to it.\n\nThe number of digits in $p_{i}$ determines the number of rows and columns of the $i$-th matrix. One prime number can occur in several rows of the password matrix or in several matrices. The prime numbers that are written not in the first row of the matrix may have leading zeros.",
    "tutorial": "We need to count the number of symmetric matrices with a given first row, where each row is a prime number. Since the matrix is symmetric, it is determined by its cells above or on the main diagonal. Let's examine all possible values of digits above the main diagonal (at most $10^{6}$ cases). Now the values of the remaining unknown digits (on the main diagonal) are independent of each other because of each of them affects exactly one row of the matrix. Therefore, it is enough to count independently the number of possible values for each of the digits on the diagonal, multiply them and add received number to answer. Moreover, it's possible to pre-calculate such numbers for each position of unknown digit and for each collection of known digits. These observations are enough to pass all the tests. One could go further, examining each next digit above the main diagonal only if it's row and column can be extended to prime numbers by some digits, unknown at moment of this digit placing. Such a solution allows to find answers for all possible tests in the allowed time, but it wasn't required.",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "163",
    "index": "A",
    "title": "Substring and Subsequence",
    "statement": "One day Polycarpus got hold of two non-empty strings $s$ and $t$, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of \"$x$ $y$\" are there, such that $x$ is a substring of string $s$, $y$ is a subsequence of string $t$, and the content of $x$ and $y$ is the same. Two pairs are considered different, if they contain different substrings of string $s$ or different subsequences of string $t$. Read the whole statement to understand the definition of different substrings and subsequences.\n\nThe length of string $s$ is the number of characters in it. If we denote the length of the string $s$ as $|s|$, we can write the string as $s = s_{1}s_{2}... s_{|s|}$.\n\nA substring of $s$ is a non-empty string $x = s[a... b] = s_{a}s_{a + 1}... s_{b}$ ($1 ≤ a ≤ b ≤ |s|$). For example, \"code\" and \"force\" are substrings or \"codeforces\", while \"coders\" is not. Two substrings $s[a... b]$ and $s[c... d]$ are considered to be different if $a ≠ c$ or $b ≠ d$. For example, if $s$=\"codeforces\", $s[2...2]$ and $s[6...6]$ are different, though their content is the same.\n\nA subsequence of $s$ is a non-empty string $y = s[p_{1}p_{2}... p_{|y|}] = s_{p1}s_{p2}... s_{p|y|}$ ($1 ≤ p_{1} < p_{2} < ... < p_{|y|} ≤ |s|$). For example, \"coders\" is a subsequence of \"codeforces\". Two subsequences $u = s[p_{1}p_{2}... p_{|u|}]$ and $v = s[q_{1}q_{2}... q_{|v|}]$ are considered different if the sequences $p$ and $q$ are different.",
    "tutorial": "The problem could be solved with the following dynamic programming. Let $f[i, j]$ be the number of distinct pairs (\"substring starting at position $i$\" and \"subsequence of the substring $t[j... |t|]$\") Then: f[i, j] = f[i, j + 1]; if (s[i] == t[j]) add(f[i, j], f[i + 1, j + 1] + 1)Answer = $\\textstyle\\sum$ f[i,0]",
    "code": "#include <cstdio>\n\nchar s[5005], t[5005];\n\nint a[5005][5005], i, j, ans;\n\n#define mod 1000000007\n\nint main(void) {\n  gets(s);\n  gets(t);\n\n  for (i = 0; s[i]; i++)\n    for (j = 0; t[j]; j++)\n      a[i + 1][j + 1] = (a[i + 1][j] + (t[j] == s[i]) * (a[i][j] + 1)) % mod;\n\n  for (i = 0; s[i]; i++)\n    ans = (ans + a[i + 1][j]) % mod;\n  \n  printf(\"%d\n\", ans);\n}",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "163",
    "index": "B",
    "title": "Lemmings",
    "statement": "As you know, lemmings like jumping. For the next spectacular group jump $n$ lemmings gathered near a high rock with $k$ comfortable ledges on it. The first ledge is situated at the height of $h$ meters, the second one is at the height of $2h$ meters, and so on (the $i$-th ledge is at the height of $i·h$ meters). The lemmings are going to jump at sunset, and there's not much time left.\n\nEach lemming is characterized by its climbing speed of $v_{i}$ meters per minute and its weight $m_{i}$. This means that the $i$-th lemming can climb to the $j$-th ledge in $\\frac{{\\dot{j}}\\cdot J_{b}}{w_{i}}$ minutes.\n\nTo make the jump beautiful, heavier lemmings should jump from higher ledges: if a lemming of weight $m_{i}$ jumps from ledge $i$, and a lemming of weight $m_{j}$ jumps from ledge $j$ (for $i < j$), then the inequation $m_{i} ≤ m_{j}$ should be fulfilled.\n\nSince there are $n$ lemmings and only $k$ ledges ($k ≤ n$), the $k$ lemmings that will take part in the jump need to be chosen. The chosen lemmings should be distributed on the ledges from $1$ to $k$, one lemming per ledge. The lemmings are to be arranged in the order of non-decreasing weight with the increasing height of the ledge. In addition, each lemming should have enough time to get to his ledge, that is, the time of his climb should not exceed $t$ minutes. The lemmings climb to their ledges all at the same time and they do not interfere with each other.\n\nFind the way to arrange the lemmings' jump so that time $t$ is minimized.",
    "tutorial": "We need to find the minimal time $T$. Let us find it using binary search. Once the time is fixed, one can arrange lemmings using greedy approach starting either from the top or from the bottom. In this solution we consider the way to start from the bottom. Among all lemmings, that can get on the first ledge, let's choose the lemming with the minimal weight (and among all such lemmings the one with the minimal speed). Why is it correct? Assume that we used some heavier lemming, then we can't use any lighter lemming anywhere, so we could replace it. Among all lemmings with the minimal weight we choose the slowest, as the faster ones can climb higher. To arrange lemmings fast, we can sort them beforehand, comparing first the weight and then the speed. After if, we consider all the lemmings in that order and either choose the current one, if it can get in time, or leave it. It is useless to consider one lemming twice, as we won't be able to use it anyway. So, the solution consists of sorting and a binary search with a linear search inside. The time is $O(N\\log X)$. However, that was not enough. One also had to deal with precision problems. Let us evaluate the number of binary search iterations. $0  \\le  T  \\le  H * K$ (the maximal time does not exceed $10^{9}$). We need to understand how the times can differ. In the case of \"N = K = $10^{5}$, H = $10^{4}$, V about $10^{9}$\" the times needed for two lemmings to get on some ledges, can differ by $10^{ - 18}$, as the times are fractions like $\\textstyle{\\frac{X}{Y}}$, where $X$ and $Y$ are about $10^{9}$. So we need to make $log_{2}10^{27} = 90$ iterations. In fact, jury solution made 75 and that was enough, however 70 was not. The idea above shows that 90 will be definitely enough.",
    "code": "/**\n * Author: Sergey Kopeliovich (Burunduk30@gmail.com)\n * Date: 2012.03.24\n */\n\n#include <cstdio>\n#include <cassert>\n#include <algorithm>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n\nconst int maxN = (int)1e5;\n\nint N, K, H, m[maxN], v[maxN], p[maxN], o[maxN];\n\ninline bool mless( int i, int j )\n{\n  #define F(x) make_pair(m[x], v[x])\n  return F(i) < F(j);\n}\n\nint solve( double t )\n{\n  int x = 1;\n  forn(i, N)\n    if (v[p[i]] * t >= (double)x * H)\n      o[x++ - 1] = p[i];\n  return x > K;\n}\n\nint main()\n{\n  scanf(\"%d%d%d\", &N, &K, &H);\n  forn(i, N)\n    scanf(\"%d\", &m[i]);\n  forn(i, N)\n    scanf(\"%d\", &v[i]);\n  forn(i, N)\n    p[i] = i;\n  sort(p, p + N, mless);\n\n  double mi = 0, ma = (double)H * K, t;\n  forn(tt, 100)\n    if (solve(t = (mi + ma) / 2))\n      ma = t;\n    else\n      mi = t;\n  assert(solve(ma));\n\n  //printf(\"%.9f\n\", mi);\n  forn(i, K)\n    printf(\"%d \", o[i] + 1);\n  return 0;\n}",
    "tags": [
      "binary search"
    ],
    "rating": 2000
  },
  {
    "contest_id": "163",
    "index": "C",
    "title": "Conveyor",
    "statement": "Anton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end.\n\nThe conveyor is a looped belt with a total length of $2l$ meters, of which $l$ meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any moment (the part which emerges from under the floor to the surface and returns from the surface under the floor) is assumed to be negligibly short.\n\nThe belt is moving uniformly at speed $v_{1}$ meters per second. Anton will be moving on it in the same direction at the constant speed of $v_{2}$ meters per second, so his speed relatively to the floor will be $v_{1} + v_{2}$ meters per second. Anton will neither stop nor change the speed or the direction of movement.\n\nHere and there there are chocolates stuck to the belt ($n$ chocolates). They move together with the belt, and do not come off it. Anton is keen on the chocolates, but he is more keen to move forward. So he will pick up all the chocolates he will pass by, but nothing more. If a chocolate is at the beginning of the belt at the moment when Anton starts running, he will take it, and if a chocolate is at the end of the belt at the moment when Anton comes off the belt, he will leave it.\n\n\\begin{center}\n{\\scriptsize The figure shows an example with two chocolates. One is located in the position $a_{1} = l - d$, and is now on the top half of the belt, the second one is in the position $a_{2} = 2l - d$, and is now on the bottom half of the belt.}\n\\end{center}\n\nYou are given the positions of the chocolates relative to the initial start position of the belt $0 ≤ a_{1} < a_{2} < ... < a_{n} < 2l$. The positions on the belt from $0$ to $l$ correspond to the top, and from $l$ to $2l$ — to the the bottom half of the belt (see example). All coordinates are given in meters.\n\nAnton begins to run along the belt at a random moment of time. This means that all possible positions of the belt at the moment he starts running are equiprobable. For each $i$ from $0$ to $n$ calculate the probability that Anton will pick up exactly $i$ chocolates.",
    "tutorial": "Wherever Anton starts, he will run along the conveyor a segment of length $D={\\frac{v_{1}x t}{v_{1}+v_{2}}}$. Consider one candy. To eat it, he needs to get on the conveyor in any moment of the segment $[a_{i} - D..a_{i}]$. Consider all points like $a_{i} - D$ and $a_{i}$ (add $2l$ if that is negative). Also add points $0$ and $2l$. Sort these points. Consider two neighboring points: x[i] and x[i+1]. If Anton starts at any moment between them, he will eat the same amount of candies. From now on, we can create one of the solving solutions: Start from every middle of the segment M = (x[i]+x[i+1]) / 2 and use binary search to find the number of candies on the segment $[M..M + D]$. Consider events along a circle like (a[i] - D, +1) and (a[i], -1). One needs to move twice along the circle and use the second run to add the current length to the answer for the current number of candies. The both solutions require $O(N\\log N)$ time.",
    "code": "/**\n * Author: Sergey Kopeliovich (Burunduk30@gmail.com)\n * Date: 2012.03.25\n */\n\n#include <cstdio>\n#include <cassert>\n#include <algorithm>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n\ntypedef double dbl;\n\nconst int maxN = (int)1e5 + 3;\n\nint dn, n, l, v1, v2;\ndbl a[maxN * 2];\ndbl dist, d[2 * maxN], p[maxN];\n\ndbl cor( dbl x )\n{\n  return x < 0 ? x + 2 * l : x;\n}\n\nint k( dbl L )\n{\n  return lower_bound(a, a + 2 * n, L + dist) - lower_bound(a, a + n, L);\n}\n\nint main()\n{\n  scanf(\"%d%d%d%d\", &n, &l, &v1, &v2); \n  forn(i, n)\n    scanf(\"%lf\", &a[i]);\n  sort(a, a + n);\n  forn(i, n)\n    a[i + n] = a[i] + 2 * l;\n\n  dist = (dbl)v2 * l / (v1 + v2);\n  d[dn++] = 0, d[dn++] = 2 * l;\n  forn(i, n)\n    d[dn++] = a[i], d[dn++] = cor(a[i] - dist);\n  sort(d, d + dn);\n  forn(i, dn - 1)\n    p[k((d[i] + d[i + 1]) / 2)] += d[i + 1] - d[i];\n  forn(i, n + 1)\n    printf(\"%.20f\n\", (double)p[i] / (2 * l));  \n  return 0;\n}",
    "tags": [
      "sortings",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "163",
    "index": "D",
    "title": "Large Refrigerator",
    "statement": "Vasya wants to buy a new refrigerator. He believes that a refrigerator should be a rectangular parallelepiped with integer edge lengths. Vasya calculated that for daily use he will need a refrigerator with volume of at least $V$. Moreover, Vasya is a minimalist by nature, so the volume should be no more than $V$, either — why take up extra space in the apartment? Having made up his mind about the volume of the refrigerator, Vasya faced a new challenge — for a fixed volume of $V$ the refrigerator must have the minimum surface area so that it is easier to clean.\n\nThe volume and the surface area of a refrigerator with edges $a$, $b$, $c$ are equal to $V = abc$ and $S = 2(ab + bc + ca)$, correspondingly.\n\nGiven the volume $V$, help Vasya find the integer lengths for the refrigerator's edges $a$, $b$, $c$ so that the refrigerator's volume equals $V$ and its surface area $S$ is minimized.",
    "tutorial": "The solution consists of three main ideas: $V = ABC$, $A  \\le  B  \\le  C$ then $A  \\le  N^{1 / 3}, B  \\le  (N / A)^{1 / 2}$. $A$ and $B$ are divisors of $V$, as we are already given the factorization of $V$, we can run only through the divisors Given fixed $A$, the optimal real $B$ and $C$ are $(N / A)^{1 / 2}$ (denote this values as $X$). I.e. the square will always be greater than $ \\ge  2(2AX + X^{2})$. So we can use this value as a boundary for the answer. If that still was not enough, one could optimize using the following ideas: Border evaluation will be more useful while running through possible values of $A$ in descending order $A$ and $B$ are 32-bit integers. Once we have calculated the answer for $V$, memoize it (this one makes possible maximal test a bit smaller). If anyone needs any theoretical base, here's some statistical information: The maximal number of divisors of numbers from 1 through $10^{18}$ is 103860 (the number 897612484786617600 = $2^{8}3^{4}5^{2}7^{2}11$ ...) Using only first two optimizations, the number of numbers $A$, found by our solution, is $10 471$ (in the case of the number with maximal number of divisors) Using only first two optimizations, the number of pairs of $A$ and $B$, found by our solution, is $128 264$ (in the case of the number with maximal number of divisors)",
    "code": "/**\n * Author: Sergey Kopeliovich (Burunduk30@gmail.com)\n * Date: 2012.03.22\n */\n\n#include <ctime>\n#include <cmath>\n#include <cstdio>\n#include <cassert>\n\n#include <map>\n\nusing namespace std;\n\n#ifdef _WIN32\n#  define I64 \"%I64d\"\n#else\n#  define I64 \"%Ld\"\n#endif\n\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\n#define fornd(i, n) for (int i = (int)(n) - 1; i >= 0; i--)\n#define mp make_pair\n\ntypedef long long ll;\ntypedef pair <ll, ll> pll;\n\ndouble start = clock();\nvoid TimeStamp()\n{\n  fprintf(stderr, \"time = %.2f\n\", (clock() - start) / CLOCKS_PER_SEC);\n  start = clock();\n}\n\nconst int maxP = 15;\n\nint pn, mdeg[maxP], s[maxP];\nint rn, rs[maxP];\n\nmap <ll, pair<pll, pll> > mem;\n\nll N1, N, C, rS, rA, rB, rC, p[maxP];\nint A, B, num;\n\nvoid go( int restx, int x, int i, int f )\n{\n  if (i == pn || restx < p[i])\n  {\n    if (!f)\n    {\n      A = x;\n      N1 = N / A;\n      long double B = sqrtl(N1);\n      if (2 * A * B + N1 < rS)\n      {\n        forn(i, pn) mdeg[i] -= s[i];\n        go((ll)sqrt(N1) + 1, 1, 0, 1);\n        forn(i, pn) mdeg[i] += s[i];\n      }\n    }\n    else\n    {\n      B = x, C = N1 / B;\n      ll curS = (ll)A * (B + C) + N1;\n      if (curS < rS)\n        rS = curS, rA = A, rB = B, rC = C;\n    }\n    return;\n  }\n \n  int m = 0, _restx[64], _x[64];\n  while (restx >= 1 && m <= mdeg[i])\n  {\n    _restx[m] = restx, _x[m++] = x;\n    restx /= p[i], x *= p[i];\n  }\n\n  fornd(j, m)\n  {\n    if (!f)\n      s[i] = j;\n    go(_restx[j], _x[j], i + 1, f);\n  }\n}\n\nint main()\n{\n#ifdef DEBUG\n  double tmp_start = clock();\n  fprintf(stderr, \"Start\n\");\n#endif\n\n  int T;\n  scanf(\"%d\", &T);\n  while (T--)\n  {\n    scanf(\"%d\", &pn);\n    assert(pn <= maxP);\n    forn(i, pn)\n      scanf(I64\"%d\", &p[i], &mdeg[i]);\n\n    N = 1, num = 1;\n    forn(i, pn)\n    {\n      forn(j, mdeg[i])\n        N *= p[i];\n      num *= mdeg[i] + 1;\n    }\n    forn(i, pn)\n      forn(j, pn - 1)\n        if (p[j] > p[j + 1])\n          swap(p[j], p[j + 1]), swap(mdeg[j], mdeg[j + 1]);\n    \n    if (mem.count(N))\n    {\n      pair<pll, pll> p = mem[N];\n      rS = p.first.first;\n      rA = p.first.second;\n      rB = p.second.first;\n      rC = p.second.second;\n    }\n    else\n    {\n      rS = 3 * N + 1;\n      go((ll)pow(N, 1.0 / 3) + 1, 1, 0, 0);\n      mem[N] = mp(mp(rS, rA), mp(rB, rC));\n    }\n    printf(I64\" \"I64\" \"I64\" \"I64\"\n\", 2 * rS, rA, rB, rC);\n  }\n\n#ifdef DEBUG\n  fprintf(stderr, \"Total time = %.2f\n\", (clock() - tmp_start) / CLOCKS_PER_SEC);\n#endif\n  return 0;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 2900
  },
  {
    "contest_id": "163",
    "index": "E",
    "title": "e-Government",
    "statement": "The best programmers of Embezzland compete to develop a part of the project called \"e-Government\" — the system of automated statistic collecting and press analysis.\n\nWe know that any of the $k$ citizens can become a member of the Embezzland government. The citizens' surnames are $a_{1}, a_{2}, ..., a_{k}$. All surnames are different. Initially all $k$ citizens from this list are members of the government. The system should support the following options:\n\n- Include citizen $a_{i}$ to the government.\n- Exclude citizen $a_{i}$ from the government.\n- Given a newspaper article text, calculate how politicized it is. To do this, for every active government member the system counts the number of times his surname occurs in the text as a substring. All occurrences are taken into consideration, including the intersecting ones. The degree of politicization of a text is defined as the sum of these values for all active government members.\n\nImplement this system.",
    "tutorial": "We assume that the reader is familiar with the Aho-Corasick algorithm (http://en.wikipedia.org/wiki/Aho-Corasick) Consider a trie of names and suffix links over it. For every vertex $v$ one can calculate the number of names, ending in that vertex ($end[v]$). Then, the \"add name $i$\" operation is $end[v[i]]$ += 1, where $v[i]$ is ending vertex of $i$-th name. Similarly, \"remove name $i$\": $end[v[i]]$ -= 1. To answer a request \"calculate how politicized the text is\", one needs to know, that the suffix links form a tree. Once we move though the text and simultaneously through the trie with suffix links, we add the sum of all $end[v[i]]$ along the path to the root of the tree of suffix links the politicization of the text. Now, there's another problem: we need to calculate the sum of weights along a way to the root, the weights may change. One can do it in the following way: Move the weights from vertices to corresponding edges to vertices' parents Build the Eulerian traversal of the tree, where the down-move will store positive weight of the edge and up-move will store its negation. The sum along a path to the root if the sum on a segment of the Eulerian traversal (the endpoints are any entries of the vertices in the traversal). A fast and short way to calculate the sum on a segment is Fenwick's tree. Here's a solution running in O(|SumLen| * log) time and 26 * |SumLen| memory (the trie will not be compressed).",
    "code": "#include <cstdio>\n#include <cassert>\n#include <vector>\n\nusing namespace std;\n\nstruct node {\n  int ne[26], suff;\n  \n  vector <int> rsuff;\n  int a, b, cur, was;\n};\n\n#define maxn 1000100\n\nint fen[maxn * 2], fen_n;\nint f_get (int i) {\n  int res = 0;\n  while (i >= 0) {\n    res += fen[i];\n    i = (i & (i + 1)) - 1;\n  }\n  return res;\n}\nvoid f_add (int i, int d) {\n  while (i < fen_n) {\n    fen[i] += d;\n    i |= i + 1;\n  }\n}\n\nnode arr[maxn];\nint arr_n = 0;\n\nnode *add (char *s) {\n  node *v = &arr[0];\n  while (*s) {\n    int c = *s++ - 'a';\n    if (!v->ne[c]) {\n      v->ne[c] = ++arr_n;\n    }\n    v = &arr[v->ne[c]];\n  }\n  return v;\n}\n\nvoid fix (node *v, int d) {\n  if (d == -1 && v->cur == 1 || d == +1 && v->cur == 0) {\n    f_add (v->a, +d);\n    f_add (v->b, -d);\n    v->cur += d;\n  }\n}\n\nint q[maxn], ql, qr;\nvoid aho() {\n  for (int i = 0; i < 26; i++) {\n    if (arr[0].ne[i]) {\n      int x = arr[0].ne[i];\n      q[qr++] = x;\n    }\n  }\n\n  while (ql < qr) {\n    int id = q[ql++];\n    node *v = &arr[id];\n    \n    arr[v->suff].rsuff.push_back(id);\n\n    for (int i = 0; i < 26; i++) {\n      int x = arr[v->suff].ne[i];\n      if (v->ne[i]) {\n        arr[v->ne[i]].suff = x;\n        q[qr++] = v->ne[i];\n      } else {\n        v->ne[i] = x;\n      }\n    }\n  }\n}\n\nchar buf[maxn];\n\nvoid dfs (node *v) {\n  v->was = 1;\n  v->a = fen_n++;\n  for (int i = 0; i < (int)v->rsuff.size(); i++) {\n    dfs (&arr[v->rsuff[i]]);\n  }\n  v->b = fen_n++;\n}\nnode *words[maxn];\n\nint main (void) {\n  int qn, wn;\n  scanf (\"%d%d\", &qn, &wn);\n\n  for (int i = 1; i <= wn; i++) {\n    scanf (\"%s\", buf);\n    words[i] = add (buf);\n  }\n  \n  aho();\n\n  for (int i = 0; i < arr_n; i++) {\n    if (!arr[i].was) {\n      dfs (&arr[i]);\n    }\n  }\n\n  for (int i = 1; i <= wn; i++) {\n    fix (words[i], +1);\n  }\n\n  for (int  i = 0; i < qn; i++) {\n    char c;\n    while ((c = getc(stdin)) == ' ' || c == '\n');\n    if (c == '+') {\n      int x;\n      scanf (\"%d\", &x);\n\n      fix (words[x], +1);\n    } else if (c == '-') {\n      int x;\n      scanf (\"%d\", &x);\n\n      fix (words[x], -1);\n    } else {\n      scanf (\"%s\", buf);\n      char *s = buf;\n      long long res = 0;\n      node *v = &arr[0];\n      while (*s) {\n        v = &arr[v->ne[*s - 'a']];\n        res += f_get (v->a);\n        s++;\n      }\n      printf (\"%I64d\n\", res);\n    }\n\n  }\n  \n  return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "strings",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "165",
    "index": "A",
    "title": "Supercentral Point",
    "statement": "One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$. Let's define neighbors for some fixed point from the given set $(x, y)$:\n\n- point $(x', y')$ is $(x, y)$'s right neighbor, if $x' > x$ and $y' = y$\n- point $(x', y')$ is $(x, y)$'s left neighbor, if $x' < x$ and $y' = y$\n- point $(x', y')$ is $(x, y)$'s lower neighbor, if $x' = x$ and $y' < y$\n- point $(x', y')$ is $(x, y)$'s upper neighbor, if $x' = x$ and $y' > y$\n\nWe'll consider point $(x, y)$ from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.\n\nVasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.",
    "tutorial": "In this problem you should just code what was written in the problem. For every point you can check if it is supercentral. Consider every point consecutively and find neighbors from every side. The complexity is $O(N^{2})$.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "165",
    "index": "B",
    "title": "Burning Midnight Oil",
    "statement": "One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of $n$ lines of code. Vasya is already exhausted, so he works like that: first he writes $v$ lines of code, drinks a cup of tea, then he writes as much as $\\left\\lfloor{\\frac{v}{k}}\\right\\rfloor$ lines, drinks another cup of tea, then he writes $\\textstyle{\\left|{\\frac{v}{k^{2}}}\\right|}$ lines and so on: $\\textstyle{\\left|{\\frac{v}{k^{3}}}\\right|}$, $\\textstyle{\\left|{\\frac{v}{k^{4}}}\\right|}$, $\\textstyle\\left|{\\frac{v}{k^{5}}}\\right|$, ...\n\nThe expression $\\left\\lfloor{\\frac{\\Omega}{b}}\\right\\rfloor$ is regarded as the integral part from dividing number $a$ by number $b$.\n\nThe moment the current value $\\left\\lfloor{\\frac{v}{k^{p}}}\\right\\rfloor$ equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished.\n\nVasya is wondering, what minimum allowable value $v$ can take to let him write \\textbf{not less} than $n$ lines of code before he falls asleep.",
    "tutorial": "This problem can be solved using binary search for the answer. obviously, if number $v$ is an answer than every number $w > v$ is also the answer, because the number of written lines of code could only become more. To check some number $v$ you can use formula given in the problem, because it will have less than $O(logN)$ positive elements. The complexity is $O(log^{2}(N))$.",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "165",
    "index": "C",
    "title": "Another Problem on Strings",
    "statement": "A string is \\underline{binary}, if it consists only of characters \"0\" and \"1\".\n\nString $v$ is a substring of string $w$ if it has a non-zero length and can be read starting from some position in string $w$. For example, string \"010\" has six substrings: \"0\", \"1\", \"0\", \"01\", \"10\", \"010\". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.\n\nYou are given a binary string $s$. Your task is to find the number of its substrings, containing exactly $k$ characters \"1\".",
    "tutorial": "You was to find number of segments $[lf;rg]$ of the strings on which the sum equals to $k$ (we are working with array of integers $0$ and $1$). We will count array $sum$ where the value $sum[i]$ equals to sum on segment $[0;i]$. We will count the answer going from left to right. Let's say we are in position $pos$. Now we will add the number of segments on which the sum equals to $k$ and ends in position $pos$. To do it we will count array $cnt$ where $cnt[i]$ - number of occurrences of $sum[i]$. Then in position $pos$ we add $cnt[sum[pos] - k]$ to the answer. The complexity is $O(N$).",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "math",
      "strings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "165",
    "index": "D",
    "title": "Beard Graph",
    "statement": "Let's define a non-oriented connected graph of $n$ vertices and $n - 1$ edges as a beard, if all of its vertices except, perhaps, one, have the degree of 2 or 1 (that is, there exists no more than one vertex, whose degree is more than two). Let us remind you that the degree of a vertex is the number of edges that connect to it.\n\nLet each edge be either black or white. Initially all edges are black.\n\nYou are given the description of the beard graph. Your task is to analyze requests of the following types:\n\n- paint the edge number $i$ black. The edge number $i$ is the edge that has this number in the description. It is guaranteed that by the moment of this request the $i$-th edge is white\n- paint the edge number $i$ white. It is guaranteed that by the moment of this request the $i$-th edge is black\n- find the length of the shortest path going \\textbf{only along the black edges} between vertices $a$ and $b$ or indicate that no such path exists between them (a path's length is the number of edges in it)\n\nThe vertices are numbered with integers from $1$ to $n$, and the edges are numbered with integers from $1$ to $n - 1$.",
    "tutorial": "Beard-graph is a tree. It consists of one root and several paths from this root. There is a single path between every pair of vertices. That's why you should check whether every edge on the path between two vertices is black. If some edge is white there is no path between two vertices now. The distances could be found separately. For every vertex $v$ precalc such information: index of path from the root where $v$ is situated and $d[v]$ distance between root and $v$. If you know such information you can find distance between any two vertices. To check whether every edge on the path between two vertices is black we will use segment tree. Mark black edge with value $0$ and white with $1$. Than repainting some edge - update in some point. The query - sum on some segment (the path between two vertices). If the sum equals to $0$ there is a single path. Else the answer is -1 now. Complexity is $O(NlogN)$.",
    "tags": [
      "data structures",
      "dsu",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "165",
    "index": "E",
    "title": "Compatible Numbers",
    "statement": "Two integers $x$ and $y$ are \\underline{compatible}, if the result of their bitwise \"AND\" equals zero, that is, $a$ $&$ $b = 0$. For example, numbers $90$ $(1011010_{2})$ and $36$ $(100100_{2})$ are compatible, as $1011010_{2}$ $&$ $100100_{2} = 0_{2}$, and numbers $3$ $(11_{2})$ and $6$ $(110_{2})$ are not compatible, as $11_{2}$ $&$ $110_{2} = 10_{2}$.\n\nYou are given an array of integers $a_{1}, a_{2}, ..., a_{n}$. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.",
    "tutorial": "Consider some number $x$ from the array. Inverse all bits in $x$ and say it is number $y$. Consider an integer $a[i]$ from array. It can be an answer to the number $x$ if for every position of zero bit from $y$ there is zero bit in $a[i]$ in the same position. Other bits in $a[i]$ we can change to ones. Then we will use such dynamic programming $z[mask] = {0, 1}$ which means if we can change some zero bits to ones in some integer from given array $a$ and get mask $mask$. Initial states are all integers from array $a$ ($z[a[i]] = 1$). To go from one state to another we consider every bit in $mask$ and try to change it to one. The length of bit representation of all integers in $a$ is less or equal than 22. To answer the question YES or NO for some number $x$ you need to get value $[z(y)&(1<<22) - 1]$ (inverse all bits in $x$ and make the length of the number 22). If you want to know the exact answer what number $a[i]$ you should choose you can save previous states for every state $z[mask]$ or just save it in $z[mask]$. Complexity $O(2^{K} * K)$, where $K$ - length of bit representation of numbers ($K < = 22$).",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "166",
    "index": "A",
    "title": "Rank List",
    "statement": "Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.\n\nYou know the rules of comparing the results of two given teams very well. Let's say that team $a$ solved $p_{a}$ problems with total penalty time $t_{a}$ and team $b$ solved $p_{b}$ problems with total penalty time $t_{b}$. Team $a$ gets a higher place than team $b$ in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team $a$ gets a higher place than team $b$ in the final results' table if either $p_{a} > p_{b}$, or $p_{a} = p_{b}$ and $t_{a} < t_{b}$.\n\nIt is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of $x$ teams that solved the same number of problems with the same penalty time. Let's also say that $y$ teams performed better than the teams from this group. In this case all teams from the group share places $y + 1$, $y + 2$, $...$, $y + x$. The teams that performed worse than the teams from this group, get their places in the results table starting from the $y + x + 1$-th place.\n\nYour task is to count what number of teams from the given list shared the $k$-th place.",
    "tutorial": "This is simple straight-forward problem - you were asked to sort the teams with the following comparator: ($p_{1} > p_{2}$) or ($p_{1} = p_{2}$ and $t_{1} < t_{2}$). After that you can split the teams into groups with equal results and find the group which shares the $k$-th place. Many coders for some reason used wrong comparator: they sorted teams with equal number of problems by descending of time. Such submits accidentally passed pretests but get WA #13.",
    "tags": [
      "binary search",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "166",
    "index": "B",
    "title": "Polygons",
    "statement": "You've got another geometrical task. You are given two non-degenerate polygons $A$ and $B$ as vertex coordinates. Polygon $A$ is strictly convex. Polygon $B$ is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.\n\nYour task is to check whether polygon $B$ is positioned strictly inside polygon $A$. It means that any point of polygon $B$ should be strictly inside polygon $A$. \"Strictly\" means that the vertex of polygon $B$ cannot lie on the side of the polygon $A$.",
    "tutorial": "Polygon A is convex, so it is sufficient to check only that every vertex of polygon B is strictly inside polygon A. In theory the simplest solution is building common convex hull of both polygons. You need to check that no vertex of polygon B belongs to this hull. But there is a tricky detail: if there are many points lying on the same side of convex hull than your convex hull must contain all these points as vertices. So this solution is harder to implement and has some corner case. Another solution: cut polygon A into triangles (by vertex numbers): $(1, 2, 3), (1, 3, 4), (1, 4, 5), ..., (1, n - 1, n)$. The sequences of angles $2 - 1 - 3, 2 - 1 - 4, 2 - 1 - 5, ..., 2 - 1 - n$ is increasing. It means that you can find for each vertex of B to which triangle of A it can belong using binsearch by angle. Similarly you can cut polygon A into trapezoids (with vertical cuts). In this case you'll need a binsearch by $x$-coordinate.",
    "tags": [
      "geometry",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "166",
    "index": "C",
    "title": "Median",
    "statement": "A median in an array with the length of $n$ is an element which occupies position number $\\textstyle{\\left|{\\frac{n+1}{2}}\\right\\rfloor}$ after we sort the elements in the non-decreasing order (the array elements are numbered starting with $1$). A median of an array $(2, 6, 1, 2, 3)$ is the number $2$, and a median of array $(0, 96, 17, 23)$ — the number $17$.\n\nWe define an expression $\\left\\lfloor{\\frac{\\Omega}{b}}\\right\\rfloor$ as the integer part of dividing number $a$ by number $b$.\n\nOne day Vasya showed Petya an array consisting of $n$ integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals $x$. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to $x$.\n\nPetya can add any integers from $1$ to $10^{5}$ to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array.\n\nWhile Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.",
    "tutorial": "If the initial array doesn't contain number $x$, than you definitely need to add it (that's +1 to answer). Than do the following. While median is strictly less than $x$ you need to increase it. Obviously the surest way to increase the median is to add a maximal possible number ($10^{5}$). Similarly while the median is strictly more than $x$, add a number $1$ to the array. Constraints are small, so you can add the numbers one by one and recalculate the median after every addition. Also there is a solution without any cases: while the median isn't equal to $x$, just add one more number $x$ to array.",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "166",
    "index": "D",
    "title": "Shoe Store",
    "statement": "The warehouse in your shop has $n$ shoe pairs. Each pair is characterized by two integers: its price $c_{i}$ and its size $s_{i}$. We know that on this very day all numbers $s_{i}$ are different, that is, there is no more than one pair of each size.\n\nThe shop has $m$ customers who came at the same time. The customer number $i$ has $d_{i}$ money and the size of his feet equals $l_{i}$. The customer number $i$ can buy the pair number $j$, if $c_{j} ≤ d_{i}$, and also if $l_{i} = s_{j}$ or $l_{i} = s_{j} - 1$; that is, it is necessary that he has enough money to pay for the shoes. It is also necessary that the size of his feet equals to or is less by $1$ than the size of the shoes he chooses.\n\nYour task is to sell some customers pairs of shoes (a pair per person) so as to maximize the sum of the sold pairs $c_{j}$ that is, the profit. It is guaranteed that each customer buys no more than one pair and each pair will be bought by no more than one customer.",
    "tutorial": "Let's sort the people by decreasing of shoes size. Observe that when considering the $i$-th man we are interested in no more than 2 pairs of shoes: with size $l_{i}$ and $l_{i} + 1$. It allows solving with dynamics. The state will be (the number of first unconsidered man $i$, is pair of shoes with size $l_{i}$ available, is pair of shoes with size $l_{i}$ + 1 available). You have 3 options: leave the $i$-th man without shoes or sell him a pair of shoes of one of suitable size (if available).",
    "tags": [
      "dp",
      "graph matchings",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "166",
    "index": "E",
    "title": "Tetrahedron",
    "statement": "You are given a tetrahedron. Let's mark its vertices with letters $A$, $B$, $C$ and $D$ correspondingly.\n\nAn ant is standing in the vertex $D$ of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.\n\nYou do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex $D$ to itself in exactly $n$ steps. In other words, you are asked to find out the number of different cyclic paths with the length of $n$ from vertex $D$ to itself. As the number can be quite large, you should print it modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "Obvious solution with dynamics: you need to know only how many moves are left and where is the ant. This is $4n$ states, each with 3 options - most of such solution passes. Observe that the vertices A, B, C are equivalent. This allows writing such solution: int zD = 1; int zABC = 0; for (int i = 1; i <= n; i++) { int nzD = zABC * 3LL % MOD; int nzABC = (zABC * 2LL + zD) % MOD; zD = nzD; zABC = nzABC; } cout << zD;Also this problem could be solved by $log(n)$ with binary exponentiation of some $2  \\times  2$ matrix into power $n$.",
    "tags": [
      "dp",
      "math",
      "matrices"
    ],
    "rating": 1500
  },
  {
    "contest_id": "167",
    "index": "A",
    "title": "Wizards and Trolleybuses",
    "statement": "In some country live wizards. They love to ride trolleybuses.\n\nA city in this country has a trolleybus depot with $n$ trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of $d$ meters from the depot. We know for the $i$-th trolleybus that it leaves at the moment of time $t_{i}$ seconds, can go at a speed of no greater than $v_{i}$ meters per second, and accelerate with an acceleration no greater than $a$ meters per second squared. A trolleybus can decelerate as quickly as you want (magic!). It can change its acceleration as fast as you want, as well. Note that the maximum acceleration is the same for all trolleys.\n\nDespite the magic the trolleys are still powered by an electric circuit and cannot overtake each other (the wires are to blame, of course). If a trolleybus catches up with another one, they go together one right after the other until they arrive at the final station. Also, the drivers are driving so as to arrive at the final station as quickly as possible.\n\nYou, as head of the trolleybuses' fans' club, are to determine for each trolley the minimum time by which it can reach the final station. At the time of arrival at the destination station the trolleybus does not necessarily have zero speed. When a trolley is leaving the depot, its speed is considered equal to zero. From the point of view of physics, the trolleybuses can be considered as material points, and also we should ignore the impact on the speed of a trolley bus by everything, except for the acceleration and deceleration provided by the engine.",
    "tutorial": "This was the first problem where you had a little bit away from translating statements to a programming language. Because acceleration trolleybuses are all the same and they can slow down immediately, the answer for the next trolleybus is the maximum of the time when it would come if it were not to stop when he reach the rest trolleybuses which was traveling in front of him and the arrival time of the previous trolleybus. It remains only to calculate the arrival time of each trolleybus if ignore others. Here, the easiest way to analyze two cases. If $d>{\\frac{w^{2}}{2a}}$, then trolley should accelerate as long as it can and the answer is equal to $\\scriptstyle{\\frac{1}{a}}+{\\frac{d-{\\frac{a^{2}}{b_{a}}}}{v}}$. Otherwise the trolley should accelerate all the time and the answer is equal to $\\sqrt{\\frac{2\\,d}{a}}$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "167",
    "index": "B",
    "title": "Wizards and Huge Prize",
    "statement": "One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees.\n\nOne of such magic schools consists of $n$ tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've brought with you have space for no more than $k$ huge prizes.\n\nBesides the fact that you want to take all the prizes home, you also want to perform well. You will consider your performance good if you win at least $l$ tours.\n\nIn fact, years of organizing contests proved to the organizers that transporting huge prizes is an issue for the participants. Alas, no one has ever invented a spell that would shrink the prizes... So, here's the solution: for some tours the winner gets a bag instead of a huge prize. Each bag is characterized by number $a_{i}$ — the number of huge prizes that will fit into it.\n\nYou already know the subject of all tours, so you can estimate the probability $p_{i}$ of winning the $i$-th tour. You cannot skip the tour under any circumstances.\n\nFind the probability that you will perform well on the contest and will be able to take all won prizes home (that is, that you will be able to fit all the huge prizes that you won into the bags that you either won or brought from home).",
    "tutorial": "This problem can be solved using dynamic programming. Let d[i][j][m] - the probability we won j of first i days and get bags total capacity of m. For convenience, we assume that the bag is also a prize and the prize is a bag of capacity 0. To do that, retaining a task we must add 1 to all a[i]. Then from d[i][j][m] we can go to the d[i+1][j+1][m+a[i]] with probability p[i]/100, and to d[i+1][j][m] with probability 1-p[i]/100. The answer will be the sum of d[n+1][j][m] for all j,m such that $L  \\le  j  \\le  m + k$. This solution works for $200^{4}$, and do not fit into the time limit. It remains to note that if we have over 200 places for prizes, it does not matter how many exactly. So we need to calculate states with $m  \\le  200$ and now solution works for $200^{3}$.",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "167",
    "index": "C",
    "title": "Wizards and Numbers",
    "statement": "In some country live wizards. They love playing with numbers.\n\nThe blackboard has two numbers written on it — $a$ and $b$. The order of the numbers is not important. Let's consider $a ≤ b$ for the sake of definiteness. The players can cast one of the two spells in turns:\n\n- Replace $b$ with $b - a^{k}$. Number $k$ can be chosen by the player, considering the limitations that $k > 0$ and $b - a^{k} ≥ 0$. Number $k$ is chosen independently each time an active player casts a spell.\n- Replace $b$ with $b mod a$.\n\nIf $a > b$, similar moves are possible.\n\nIf at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses.\n\nTo perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second.",
    "tutorial": "Consider the position (a, b). Let a < b. From this there is a move to $(b{\\mathrm{~mod~}}a,a)$. Recursively check if this position is a winning or a losing. If it is losing, then (a, b) exactly winning. Otherwise, no one will take the remainder. So everyone will subtract from larger number nonnegative degree of smaller. Then the left to learn to solve such problem. You can subtract the nonnegative powers of a from x, and player who cannot move losses. And solve it for $x=\\left\\lfloor{\\frac{b}{a}}\\right\\rfloor-1$. This problem can be solved as follows. If a is odd, then all odd number are wining. In other all the numbers, giving an odd residue modulo a+1 or -1 residue on the same module are wining. This can be easily proved by induction.",
    "tags": [
      "games",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "167",
    "index": "D",
    "title": "Wizards and Roads",
    "statement": "In some country live wizards. They love to build cities and roads.\n\nThe country used to have $k$ cities, the $j$-th city ($1 ≤ j ≤ k$) was located at a point ($x_{j}$, $y_{j}$). It was decided to create another $n - k$ cities. And the $i$-th one ($k < i ≤ n$) was created at a point with coordinates ($x_{i}$, $y_{i}$):\n\n- $x_{i} = (a·x_{i - 1} + b) mod (10^{9} + 9)$\n- $y_{i} = (c·y_{i - 1} + d) mod (10^{9} + 9)$\n\nHere $a$, $b$, $c$, $d$ are primes. Also, $a ≠ c, b ≠ d$.\n\nAfter the construction of all $n$ cities, the wizards have noticed something surprising. It turned out that for every two different cities $i$ and $j$, $x_{i} ≠ x_{j}$ and $y_{i} ≠ y_{j}$ holds.\n\nThe cities are built, it's time to build roads! It was decided to use the most difficult (and, of course, the most powerful) spell for the construction of roads. Using this spell creates a road between the towns of $u$, $v$ ($y_{u}$ > $y_{v}$) if and only if for any city $w$ which lies strictly inside the corner at the point $u$, $v$ (see below), there is a city $s$ that does not lie in the corner, which is located along the $x$-coordinate strictly between $w$ and $u$ and simultaneously $y_{s} > y_{v}$.\n\nA corner on the points $p_{2}$($x_{2}$, $y_{2}$), $p_{1}$($x_{1}$, $y_{1}$) ($y_{1} < y_{2}$) is the set of points ($x, y$), for which at least one of the two conditions is fulfilled:\n\n- $min(x_{1}, x_{2}) ≤ x ≤ max(x_{1}, x_{2})$ and $y ≥ y_{1}$\n- $y_{1} ≤ y ≤ y_{2}$ and $(x - x_{2})·(x_{1} - x_{2}) ≥ 0$\n\n\\begin{center}\n{\\scriptsize The pictures showing two different corners}\n\\end{center}\n\nIn order to test the spell, the wizards will apply it to all the cities that lie on the $x$-coordinate in the interval $[L, R]$. After the construction of roads the national government wants to choose the maximum number of pairs of cities connected by the road, so that no city occurs in two or more pairs. Your task is for each $m$ offered variants of values $L$, $R$ to calculate the maximum number of such pairs after the construction of the roads. Please note that the cities that do not lie in the interval $[L, R]$ on the $x$-coordinate, do not affect the construction of roads in any way.",
    "tutorial": "This was the first really hard problem in the contest. One of the challenges was to understand the statement. I hope that we had written the statement as clear as it possible in this problem. Consider this graph. In particular, we consider more closely the point with the largest y. 1) It is connected with the highest points on the left and right of it. 2) It is not connected to all other points. 3) It is inside all corners on points from different sides of it. All three of these properties are seen quite clearly in the pictures. So, 1) Building roads on the left and right sides are independent. 2) The graph is a tree. Once a graph is a tree, the maximum matching in it can be found greedy, or with a simple dynamic. But it works in linear time, which clearly is not enough to answer all of $10^{5}$ queries. But this is not just a tree! Those who know what it is probably already noticed, that it is Cartesian tree (also known as treep). This allows to get a tree for the subsegments in time which is $O(h)$, counting all the necessary dynamics, where h is the height of the tree. Well, since the city built at random points (the method for the construction of cities guarantees this), the height of the tree $h = O(K + logN)$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "graph matchings",
      "graphs",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "167",
    "index": "E",
    "title": "Wizards and Bets",
    "statement": "In some country live wizards. They like to make weird bets.\n\nTwo wizards draw an acyclic directed graph with $n$ vertices and $m$ edges (the graph's vertices are numbered from $1$ to $n$). A source is a vertex with no incoming edges, and a sink is the vertex with no outgoing edges. Note that a vertex could be the sink and the source simultaneously. In the wizards' graph the number of the sinks and the sources is the same.\n\nWizards numbered the sources in the order of increasing numbers of the vertices from $1$ to $k$. The sinks are numbered from $1$ to $k$ in the similar way.\n\nTo make a bet, they, as are real wizards, cast a spell, which selects a set of $k$ paths from all sources to the sinks in such a way that no two paths intersect at the vertices. In this case, each sink has exactly one path going to it from exactly one source. Let's suppose that the $i$-th sink has a path going to it from the $a_{i}$'s source. Then let's call pair $(i, j)$ an inversion if $i < j$ and $a_{i} > a_{j}$. If the number of inversions among all possible pairs $(i, j)$, such that $(1 ≤ i < j ≤ k)$, is even, then the first wizard wins (the second one gives him one magic coin). Otherwise, the second wizard wins (he gets one magic coin from the first one).\n\nOur wizards are captured with feverish excitement, so they kept choosing new paths again and again for so long that eventually they have chosen every possible set of paths for exactly once. The two sets of non-intersecting pathes are considered to be different, if and only if there is an edge, which lies at some path in one set and doesn't lie at any path of another set. To check their notes, they asked you to count the total winnings of the first player for all possible sets of paths modulo a prime number $p$.",
    "tutorial": "This task was about the pathes from the sources to sinks. For this pathes there was a condition which made them dependent - they should not interfere at vertexes. But in any combinatorics is much easier when everything is independent. So we should try to get rid of the condition of the absence of crossings at the vertices. It is very easy - just forget about it. Lets understand why the answer will not change: Suppose that a certain set of ways in which the two paths intersect. We show that taking into account this way, we at the same time take into account an another with the opposite sign. To do this, change the endings for paths that intersect. The signum of the permutation in this case has changed, so this set of paths is taken into account with the opposite sign and their sum is 0. How can it helps us? If we fix the permutation, the number of sets of paths that it corresponds well to the product of the number of paths for each pair of corresponding source and sink. Suppose that from the i-th source in the j-th sink there are $cnt_{ij}$ paths. This value can be calculated by depth-first-search and simple dynamic. Then the answer is $a n s=\\sum_{p}s i g n(p)\\cdot\\prod_{i=1}^{n}c n t_{i p}$. This value is called the determinant of matrix cnt, which can be calculated using Gauss method in $O(S^{3})$ time where S is the number of sinks and sources. And we had to remember about isolated vertexes. Deleting one of them either do not change the answer or multiply the answer by -1. It remains to see that after deleting all isolated vertexes $s\\leq{\\frac{N}{2}}=300$, and $300^{3}$ fine fits into TL.",
    "tags": [
      "dfs and similar",
      "graphs",
      "math",
      "matrices"
    ],
    "rating": 2900
  },
  {
    "contest_id": "168",
    "index": "A",
    "title": "Wizards and Demonstration",
    "statement": "Some country is populated by wizards. They want to organize a demonstration.\n\nThere are $n$ people living in the city, $x$ of them are the wizards who will surely go to the demonstration. Other city people ($n - x$ people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least $y$ percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.\n\nSo all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only $n$ people and not containing any clone puppets.\n\nHelp the wizards and find the minimum number of clones to create to that the demonstration had no less than $y$ percent of the city people.",
    "tutorial": "In this task, it was necessary to write exactly what has been described in statement. In particular, it was necessary to have $\\textstyle\\left[{\\frac{N Y}{100}}\\right]$ people, who come to the meeting. For this it was necessary to create ${\\mathrm{max}}(0,\\lceil{\\frac{N\\cdot Y}{100}}\\rceil-X)$ clones.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "168",
    "index": "B",
    "title": "Wizards and Minimal Spell",
    "statement": "Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.\n\nEach spell consists of several lines. The line, whose first non-space character is character \"#\" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell.\n\nYou came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning.\n\nThe only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden.\n\nNote that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too).\n\nFor now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too).\n\nThe input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output.",
    "tutorial": "In this problem you had to write exactly what has been described in statment too. Read lines one by one. Also keep the last block of lines that are not amplyfying. If the next line is amplyfying (which can be checked by linear search), we print the last block, if any, and the line itself. Otherwise, remove all spaces from the string and add to the last block. It only remains to distinguish between an empty block and a block of empty lines.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "173",
    "index": "A",
    "title": "Rock-Paper-Scissors",
    "statement": "Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).\n\nLet us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.\n\nNikephoros and Polycarpus have played $n$ rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.\n\nNikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items $A = (a_{1}, a_{2}, ..., a_{m})$, and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: $a_{1}$, $a_{2}$, $...$, $a_{m}$, $a_{1}$, $a_{2}$, $...$, $a_{m}$, $a_{1}$, $...$ and so on. Polycarpus had a similar strategy, only he had his own sequence of items $B = (b_{1}, b_{2}, ..., b_{k})$.\n\nDetermine the number of red spots on both players after they've played $n$ rounds of the game. You can consider that when the game began, the boys had no red spots on them.",
    "tutorial": "Naive solution in $O(n)$ (some simulation all of n rounds) gets TL. Let's speed up this solution. Let's consider rounds on segments [1..mk], [mk+1..2mk], [2mk+1..3mk] and so on. You can see that results of games on these segments will repeat. So you can simulate over exactly one segment and then take into consideration them [n/(mk)] times ([x] is rounding down). Remainder of n%(mk) last rounds you can simulate separately. So you have $O(mk)$ solution that easily fits into time limits.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "173",
    "index": "B",
    "title": "Chamber of Secrets",
    "statement": "\"The Chamber of Secrets has been opened again\" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.\n\nThe Chamber of Secrets is an $n × m$ rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below.\n\n\\begin{center}\n{\\scriptsize The left light ray passes through a regular column, and the right ray — through the magic column.}\n\\end{center}\n\nThe basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position.\n\n\\begin{center}\n{\\scriptsize This figure illustrates the first sample test.}\n\\end{center}\n\nGiven the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.",
    "tutorial": "In this problem you should build bipartite graph with n+m vertices. All vertices of the firts part correspond to the rows of the table, vertices of the second part correspond to the columns of the one. Edge connects vertices iff some regular column is placed in the cross of corresponding row and column. Firstly death ray covers only last row of the table that corresponds to one of vertices of our graph. When you are changing regular column into magic one, you are allowing death ray \"go\" by corresponding edge. Now you can reformulate the statement by this way: \"activate\" minimal number of edges in biratrite graph, so some path of minimal lenght connects vertex of the last row of the table and vertex of the first row of the table. You can see that required set of edges is just shortest path between these vertices. You can find this path using BFS. If BFS didn't find any path - answer is -1. This solution works in $O((n + m)^{2})$.",
    "tags": [
      "dfs and similar",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "173",
    "index": "C",
    "title": "Spiral Maximum",
    "statement": "Let's consider a $k × k$ square, divided into unit squares. Please note that $k ≥ 3$ and is odd. We'll paint squares starting from the upper left square in the following order: first we move to the right, then down, then to the left, then up, then to the right again and so on. We finish moving in some direction in one of two cases: either we've reached the square's border or the square following after the next square is already painted. We finish painting at the moment when we cannot move in any direction and paint a square. The figure that consists of the painted squares is a spiral.\n\n\\begin{center}\n{\\scriptsize The figure shows examples of spirals for $k = 3, 5, 7, 9$.}\n\\end{center}\n\nYou have an $n × m$ table, each of its cells contains a number. Let's consider all possible spirals, formed by the table cells. It means that we consider all spirals of any size that don't go beyond the borders of the table. Let's find the sum of the numbers of the cells that form the spiral. You have to find the maximum of those values among all spirals.",
    "tutorial": "Let's iterate over all spirals and chose one of them that has maximal sum of elements. Because you have $O(n^{3})$ spirals, you should calculate sum of any of them in $O(1)$. Only in this case your solution will fit into time limits. Let's define a way for iterate over all spirals. Let's fix one of cells and then iterate over all spirals that have own center in that cell in order of increasing side. So, you can recalculate sum for every spiral from previous one in $O(1)$ using following picture: For finding the first \"summand\", you should in the beginning calculate rectangular partial sums.",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "173",
    "index": "D",
    "title": "Deputies",
    "statement": "The Trinitarian kingdom has exactly $n = 3k$ cities. All of them are located on the shores of river Trissisipi, which flows through the whole kingdom. Some of the cities are located on one side of the river, and all the rest are on the other side.\n\nSome cities are connected by bridges built between them. Each bridge connects two cities that are located on the opposite sides of the river. Between any two cities exists no more than one bridge.\n\nThe recently inaugurated King Tristan the Third is busy distributing his deputies among cities. In total there are $k$ deputies and the king wants to commission each of them to control exactly three cities. However, no deputy can be entrusted to manage the cities, which are connected by a bridge — the deputy can set a too high fee for travelling over the bridge to benefit his pocket, which is bad for the reputation of the king.\n\nHelp King Tristan the Third distribute the deputies between the cities, if it is possible.",
    "tutorial": "You have bipartite graph with $3k$ vertices and should to color its vertices by $k$ colors. Every color should be used exactly 3 times and there should be no edges that connect vertices at same color. At the first, you should find both of parts of our birartite graph using, for example, DFS. Now let's consider sizes of parts. Case 0. If both of sizes divides by 3, you can just split every of parts into groups of 3 vertices and color them. Otherwise we can note then size of the first part is 1 modulo 3 and size of the second part is 2 modulo 3. There are yet another 2 cases: Case 1. You should try to find one vertex from the firts part that have 2 \"antiedges\" to 2 different vertices of the second part. If you found it, you should color them and reduce the problem to case 0. Case 2. There you should try to find 2 vertices on the second part. Every of them should have 2 \"antiedges\" that \"connect\" them with 4 different vertices trom the firts part. If you found such 6 vertices, you can color them by 2 different colors and reduce the problem to case 0. If you doesn't find coloring using this cases, answer is NO. About implementation: it is not clear how to analyse the case 2 in acceptable time. Actually, you can find any two vertices from the second part that have at least two \"antiedges\". These \"antiedges\" will conduct to 4 different vertices of the first part because otherwise case 1 would have worked. This solution works in $O(n + m)$.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "173",
    "index": "E",
    "title": "Camping Groups",
    "statement": "A club wants to take its members camping. In order to organize the event better the club directors decided to partition the members into several groups.\n\nClub member $i$ has a responsibility value $r_{i}$ and an age value $a_{i}$. A group is a non-empty subset of club members with one member known as group leader. A group leader should be one of the most responsible members of the group (his responsibility value is not less than responsibility of any other group member) and his age absolute difference with any other group member should not exceed $k$.\n\nSome club members are friends and want to be in the same group. They also like their group to be as large as possible. Now you should write a program that answers a series of questions like \"What's the largest size of a group containing club member $x$ and club member $y$?\". It's possible for $x$ or $y$ to be the group leader.",
    "tutorial": "Let's transform all people into points on a plane with coordinates ($x = a_{i}, y = r_{i}$). What the maximal number in group of people that can be formed with some fixed leader? Answer is number of points inside rectangle $(x, y): x_{i} - k  \\le  x  \\le  x_{i} + k, y  \\le  y_{i}$. Let's we allready found size of group for every person. How to find maximal group that contain points $(x_{i}, y_{i})$ and $(x_{j}, y_{j})$ both? The required group should have leader with age in range from $max(x_{i} - k, x_{j} - k)$ then $min(x_{i} + k, x_{j} + k)$ and responsibility at least $max(y_{i}, y_{j})$. From such leaders you should chose one that have maximal size of group. You can see that it is just query for maximum on some rectangle. Well, let's learn to quickly find answers for queries of sums in rectangle. You should compress coordinates $x$ ans build segment tree for sum. Then you should answer all queries in increasing order of coordinate $y$. When you consider some group with same $y$, you should initially do queries of adding values in points, and after that do sum queries on the segments from $x_{i} - k$ to $x_{i} + k$. Queries for maximum you can satisfy fully analogicaly using segment tree for maximum. So, you have $O(n\\log n)$ offline solution.",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "175",
    "index": "A",
    "title": "Robot Bicorn Attack",
    "statement": "Vasya plays Robot Bicorn Attack.\n\nThe game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string $s$. Vasya decided to brag about his achievement to the friends. However, he has forgotten how many points he got for each round. The only thing he remembers is the string $s$.\n\nHelp Vasya to find out what is the maximum amount of points he could get. Take into account that Vasya played Robot Bicorn Attack for the first time, so he could not get more than 1000000 ($10^{6}$) points for one round.",
    "tutorial": "Go over all possible partitions of the given string into 3 substrings (for example, go over a pair of indexes - the ends of the first and the second substrings). If all three substrings of the partition satisfy constraints (there are no leading zeroes and the corresponding number does not exceed 1000000), then update the current answer with the sum of obtained numbers (if it is necessary). The total amount of partitions is O(N^2), where N is the length of the string. The check of one partition takes O(N).",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "175",
    "index": "B",
    "title": "Plane of Tanks: Pro",
    "statement": "Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results.\n\nA player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has $n$ records in total.\n\nIn order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category:\n\n- \"noob\" — if \\textbf{more than $50%$ of players have better results};\n- \"random\" — if his result is not worse than the result that $50%$ of players have, but more than $20%$ of players have better results;\n- \"average\" — if his result is not worse than the result that $80%$ of players have, but more than $10%$ of players have better results;\n- \"hardcore\" — if his result is not worse than the result that $90%$ of players have, but more than $1%$ of players have better results;\n- \"pro\" — if his result is not worse than the result that $99%$ of players have.\n\nWhen the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that $50%$ of players have, and the second one is not worse than the result that $100%$ of players have.\n\nVasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.",
    "tutorial": "The solution is to simulate actions described in the statement. Find the best result for each player and count total amount of players N. Then find a number of players C for each player , those results are not better than best result of the considering player (this can be done by going over all players). Then it is necessary to determine players category using numbers C and N. In order to avoid rounding error use the following approach: if C * 100 >= N * 99, then the player belongs to category \"pro\" if C * 100 >= N * 90, then the player is \"hardcore\" if C * 100 >= N * 80, then the player is \"average\" if C * 100 >= N * 50, then the player is \"random\" In other case the player is \"noob\".",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "175",
    "index": "C",
    "title": "Geometry Horse",
    "statement": "Vasya plays the Geometry Horse.\n\nThe game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.\n\nThere are $n$ types of geometric figures. The number of figures of type $k_{i}$ and figure cost $c_{i}$ is known for each figure type. A player gets $c_{i}·f $ points for destroying one figure of type $i$, where $f$ is the current factor. The factor value can be an integer number from $1$ to $t + 1$, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to $i + 1$ after destruction of $p_{i}$ $(1 ≤ i ≤ t)$ figures, so the $(p_{i} + 1)$-th figure to be destroyed is considered with factor equal to $i + 1$.\n\nYour task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.",
    "tutorial": "Obvious, that figures should be destroyed in the cost increasing order. Sort figures type in ascending order of their costs. Consider two pointers - position i in the array P (current factor) and position j in the array of figures type. Consider the current answer and the number of figures G, those need to be destroyed to move to the next value of factor. If the number of figures F of the current type does not exceed G, then add F * (i + 1) * Cj to the answer and reduce G by F and increase pointer j by 1. In other case add G * (i + 1) * Cj to the answer, reduce F by G, increase i by 1 and set G = Pi - P(i-1). Continue iteration until all figure types are considered.",
    "tags": [
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "175",
    "index": "D",
    "title": "Plane of Tanks: Duel",
    "statement": "Vasya plays the Plane of Tanks.\n\nTanks are described with the following attributes:\n\n- the number of hit points;\n- the interval between two gun shots (the time required to recharge the gun);\n- the probability that the gun shot will not pierce armor of the enemy tank;\n- the damage to the enemy's tank.\n\nThe gun damage is described with a segment $[l, r]$, where $l$ and $r$ are integer numbers. The potential gun damage $x$ is chosen with equal probability among all integer numbers of the segment $[l, r]$. If the shot pierces the armor of an enemy's tank then the enemy loses $x$ hit points. If the number of hit points becomes non-positive then the enemy tank is considered destroyed.\n\nIt is possible that the shot does not pierce the armor of a tank. In this case the number of hit points doesn't change. The probability that the armor will not be pierced is considered as the shooting tank attribute and does not depend on players' behavior.\n\nThe victory is near and there is only one enemy tank left. Vasya is ready for the battle — one more battle between the Good and the Evil is inevitable! Two enemies saw each other and each of them fired a shot at the same moment... The last battle has begun! Help Vasya to determine what is the probability that he will win the battle by destroying the enemy tank?\n\nIf both tanks are destroyed (after simultaneous shots), then Vasya is considered a winner. You can assume that each player fires a shot just after the gun recharge and each tank has infinite number of ammo.",
    "tutorial": "First consider case when at least one probability of not-piercing is equal to 100%. If Vasya does not pierce the enemy tank with probability 100%, then the answer is 0. If the enemy tank cannot pierce Vasya's tank with probability 100% then the answer is 1. Then consider that the probability of shot does not pierce tank does not exceed 99%. It can be checked that the probability that tank will stay alive after D = 5000 shots is less than 10^-6 (for any damage value, probability of not-piercing and amount of hit points). For each tank calculate the following table dp[i][j] - probability that tank will have j hit points after i shots to him. dp[0][hp] = 1, where hp - is the initial amount of hit points. In order to calculate the line dp[i+1] it is necessary to go over all possible damages for each value of j in the line dp[i], which shot (i+1)-th damages (considering cases when the shot does not pierce the tank armour) and update appropriate values of the line (i+1): dp[i + 1][max(0, j - x)] += dp[i][j] * (1 - p) / (r - l + 1)where p - is the probability of not-piercing, x - possible shot damage. Let's dpv - calculcated table for Vasya's tank and dpe is the table for enemy's tank. Now it is necessary to find probability that enemy's tank will be destroyed after i shots of Vasya's tank: pk[i] = dpe[i][0] - dpe[i-1][0]. Vasya wins the following way: Vasya fired (K - 1) shots and do not destroy enemy tank and is still alive also. After that Vasya fires K-th shot and destroy the enemy. Go over K and calculate the probability of Vasya's victory with the K-th shot. In order to do this find how many shots T can fire the enemy before Vasya makes K-th shot (here is the only place in the solution where we must use the gun recharge speed): T = ((K - 1) * dtv + dte - 1) / dtewhere dtv is the time required to recharge the gun, dte is the time of enemy gun recharge. Then the probability of victory is (1 - dpv[T][0]) * pk[K]. The answer for the problem is the sum all these probabilities for each K from 1 to D. The algorithmic complexity of the algorithm is O(D * hp * (r - l)).",
    "tags": [
      "brute force",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "175",
    "index": "E",
    "title": "Power Defence",
    "statement": "Vasya plays the Power Defence.\n\nHe must pass the last level of the game. In order to do this he must kill the Main Villain, who moves in a straight line at speed 1 meter per second from the point $( - ∞, 0)$ to the point $( + ∞, 0)$ of the game world. In the points $(x, 1)$ and $(x, - 1)$, where $x$ is an integer number, Vasya can build towers of three types: fire-tower, electric-tower or freezing-tower. However, it is not allowed to build two towers at the same point. Towers of each type have a certain action radius and the value of damage per second (except freezing-tower). If at some point the Main Villain is in the range of action of $k$ freezing towers then his speed is decreased by $k + 1$ times.\n\nThe allowed number of towers of each type is known. It is necessary to determine the maximum possible damage we can inflict on the Main Villain.\n\nAll distances in the problem are given in meters. The size of the Main Villain and the towers are so small, that they can be considered as points on the plane. The Main Villain is in the action radius of a tower if the distance between him and tower is less than or equal to the action radius of the tower.",
    "tutorial": "If we reflect the position of towers alogn the line OX then the interval where towers will affect the Villain will not change. So, we can consider that towers can be built in the points (_x_, 1), not more than two towers in the same point. If there exists point X that there are towers to the left and to the right from X but in the point X there is no tower, then abscissas of all towers \"to the right\" can be reduced by 1 and the answer will not become worse. The same way, we can prove that there are no adjacent points with exactly one tower in each one. Now it is easy to check that in order to construct the optimal solution it is enough to check 13 successive points. Go over positions of freezing towers. In the worst case there are approximately 200000 cases to put freezing towers into 13 points. Consider the case when we fixed positions of several freezing towers. Let's calculate how much damage can hit fire-tower or electric-tower in the point for each empty points (points where we can put two towers are splitted into two) and save numbers into the array d (_d_[k].f and d[k].e - damage by fire and electricity in the point k correspondingly). Sort the array d in the order of decreasing of the value d[k].f. Then optimal position of the rest towers can be found using dynamic programming. Designate dp[i][j] - the maximum possible damage, which can be hitted if we have i fire-towers and j electric-towers. Designate p - the amount of towers have been set already: p = cf - i + ce - j. If i = 0 then we used first p values of array d and the answer is the sum of j maximum elemets of d[k].e, starting from index p. Otherwise we put one fire-tower or one electric tower in the position p. It is necessary to put the tower into position p because in the opposite case the d[p].f will decrease. Then: dp[i][j] += max(dp[i - 1][j] + d[p].f, d[i][j - 1] + d[p].e)The answer is the value dp[cf][ce], which is calculated in O(cf * ce * log(ce)) Comment1: exhaustive search can be reduced in 2 times because any two symmetric towers arrangements are equivalent and have the same answer. However, this optimization is not required with a given constraints. Comment2: the formula of Villain speed decrease 1 / (K + 1) allows to calculate the tower damage for a case when all freezing towers are fixed easily. Freezing towers can be taken into account separately.",
    "tags": [
      "brute force",
      "dp",
      "geometry",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "175",
    "index": "F",
    "title": "Gnomes of Might and Magic",
    "statement": "Vasya plays a popular game the Gnomes of Might and Magic.\n\nIn this game Vasya manages the kingdom of gnomes, consisting of several castles, connected by bidirectional roads. The kingdom road network has a special form. The kingdom has $m$ main castles $a_{1}, a_{2}, ..., a_{m}$, which form the Good Path. This path consists of roads between the castles $a_{i}, a_{i + 1}$ $(1 ≤ i < m)$ as well as the road between $a_{m}$ and $a_{1}$. There are no other roads between the castles of the Good Path.\n\nIn addition, for each pair of neighboring Good Path castles $u$ and $v$ there is exactly one Evil Shortcut — a path that goes along the roads leading from the first castle $(u)$ to the second one $(v)$ and not having any common vertexes with the Good Path except for the vertexes $u$ and $v$. It is known that there are no other roads and castles in the kingdom there, that is, every road and every castle lies either on the Good Path or the Evil Shortcut (castles can lie in both of them). In addition, no two Evil Shortcuts have any common castles, different than the castles of the Good Path.\n\nAt the beginning of each week in the kingdom appears one very bad gnome who stands on one of the roads of the kingdom, and begins to rob the corovans going through this road. One road may accumulate multiple very bad gnomes. Vasya cares about his corovans, so sometimes he sends the Mission of Death from one castle to another.\n\nLet's suggest that the Mission of Death should get from castle $s$ to castle $t$. Then it will move from castle $s$ to castle $t$, destroying all very bad gnomes, which are on the roads of the Mission's path. Vasya is so tough that his Mission of Death can destroy any number of gnomes on its way. However, Vasya is very kind, so he always chooses such path between castles $s$ and $t$, following which he will destroy the smallest number of gnomes. If there are multiple such paths, then Vasya chooses the path that contains the smallest number of roads among them. If there are multiple such paths still, Vasya chooses the lexicographically minimal one among them.\n\nHelp Vasya to simulate the life of the kingdom in the Gnomes of Might and Magic game.\n\nA path is a sequence of castles, such that each pair of the neighboring castles on the path is connected by a road. Also, path $x_{1}, x_{2}, ... , x_{p}$ is lexicographically less than path $y_{1}, y_{2}, ... , y_{q}$, if either $p < q$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{p} = y_{p}$, or exists such number $r$ $(r < p, r < q)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} < y_{r + 1}$.",
    "tutorial": "Construct the graph with vertices corresponding to castles and edges to roads. Note, that a degree of each graph vertex does not exceed 4, so the amount of edges does not exceed E <= 2 * N. In order to solve the problem let's find out how we can handle each query with time O(_log_(_N_)). Consider the query to find amount of gnomes destroyed by the Mission of Death. Assume that the edge weight is the amount of gnomes on the appropriate road. We must find the shortest path between two vertices and among them the path with the smallest amount of edges. So, the way is described by two numbers - G and R - amount of gnomes and edges (for now we do not consider lexicographical minimality). One edge between vertex u and v is described by (_C_(_u_,_v_), 1), where C(_u_,_v_) - amount of gnomes on the edge (_u_,_v_). Consider two vertices s and t. We want to find the path between them. The shortest path between them can be one of the following : the path along the Evil Shortcut, if both vertices are on the same Shortcut the path s -> g1 -> g2 -> t, where g1 and g2 - vertices on the Good Path and g1 and s are on the same Shortcut, g2 and t are on the same Shortcut (some of these 4 vertices can be identical). So, it is necessary to determine quickly the shortest path between vertices e1 and e2 along the Evil Shortcut and between vertices g1 and g2 along the Good Path. In order to find distance between vertices along the Evil Shortcut construct for each Evil Shortcut the segment tree etree[i], which can be used to update and get the sum on the segment. For each vertex let's store the number of Evil Shortcut it belongs to and it index number on that Shortcut (it is necessary to consider cases with vertices of the Good Path, because they belong to two Shortcuts). So, the distance between two vertices of one Shortcut is the sum of edges weights of the approproate segment tree with boundaries equal to indexes of considered vertices. Similarly, construct the segment tree gtree for Good Path, by cutting it in the first vertex (for paths where it was inner vertex we will do two queries). For each pair of adjacent vertices of the Good Path we will store the minimum of two distances: distance along the edge of the Good Path or the distance along the Evil Shortcut. So for each two vertices of the Good Path the corresponding query to the segment tree returns the length (a pair of numbers) of the shortest path between two arbitrary vertices. Such a data structure allows to find the shortest path between two arbitrary vertices of the Good Path or one Evil Shortcut in time O(_log_(_N_)). It is necessary to update appropriate element of the tree with value (_0_, 1) for each pair of adjacent vertices of the Good Path initially. Now consider the query for addition of one gnome to the edge. In order to handle this query quickly it is necessary to store amount of gnomes gsum[i] along each road of the Good Path and total number of gnomes esum[i] along each Evil Shortcut. If the gnome stands on the edge i of the Good Path, then increase gsum[i] by 1. Similarly if the gnome stands on the edge i of the Evil Shortcut, then increase esum[i] by 1 and update the appropriate value in the segment tree etree[i]. It is necessary to put new shortest path between corresponding adjacent vertices into the segment tree gtree after any of these actions because it may have changed. Note, that after removal of gnomes from the edge we can do opposite operations with the same asymptotics. So, the query for updating amount of gnomes on the edge can be handled in time O(_log_(_N_)). Now let's figure out how we can find the shortest path between two arbitrary vertices s and t. Construct the vector of the Good Path vertices sg those we can reach from s along the edges of the Evil Shortcut which it belongs to (there will be one or two vertices in the sg ). Similarly, the vector tg contains the vertices of the Good Path those we can reach from t along the edges of the Evil Shortcut. Consider the union of vectors tsg = sg + tg. For each vertex u of the uninon let's find the vertex v1 which is the first one among vertices tsg on the path from u if we move along the edges of Good Path in the order of indexes increasing (i.e. in the order the vertices are given in the input data). Similarly, v2 is the first vertex on the opposite direction. Add to the adjacenty list of the vertex u vertices v1 and v2 with distances to them. Also, find edges (distances along the Evil Shortcuts) from s to the vertices of vector sg, and from vertices of the tg to the vertex t. If vertices s and t are on the same Evil Shortcut (and none of them is on the Good Path), then add one more direct edge from s to t, corresponding to the path along the Evil Shortcut. So we have constructed the graph which consists of not more than 6 vertices and no more than 13 edges. Start the Deijkstra algorithm on that graph to find shortest path from s to t. Note, that paths of the initial graph corresponding to edges of the new graph do not intersect in inner vertices (except, probably, a direct edge from s to t). In order to find lexicographically minimal path it is necessary to know the first inner vertex on the path corresponding to one of the edges. So we can, for example, add one more option to each path of the new graph - the vector of indexes of first vertices of the initial graph when moving along edges of a new graph. In this case 3 options (amount of gnomes, amount of edges and the vector of indexes) uniquely determines the optimal path of the Death Mission. Now it is necessary to print the answer and find out how to handle gnome destruction on the path. Restore vertices on the optimal path. The edge between each pair of adjacent vertices is the path along the Evil Shortcut or the path between two vertices of the Good Path. In order to find gnomes on the Evil Shortcut consider the multiset eset[i] containing indexes of edges with gnomes of that Shortcut for each Evil Shortcut. Then after adding a gnome to the edge it is necessary to add the gnome index to the multiset of the Shortcut. Now all destructions of gnomes from the Evil Shortcut i, between edges l and r, can be handled by searching of iterator of the first gnome, using eset[i]._lower_bound_(_l_) and iteration, saving obtained indexes of gnomes into the list, until the value will not exceed r. After that it is necessary to remove all gnomes in the list using the algorithm described above (similarly to addition). In order to handle paths between two vertices of the Good Path, consider set gset with indexes of vertices of the Good Path that there is no path without gnomes between two adjacent vertices corresponding to indexes. After each set updating (adding/removal of the gnome) it is necessary to add the check: if the minimum distance (corresponding to the value in the segment tree gtree) is 0 (by the amount of gnomes), then it is necessary to remove appropriate index in the gset, in the opposite case it is necessary to add the index. After invocation of similar procedure (invoke gset._lower_bound_ and iterate required amount of times) we will get the list of vertices indexes going through each one we will have to destroy at least one gnome to the path to the next vertex of the Good Path (obvious, that pairs of vertices between those exists a path without gnomes should not be considered because the Death Mission will go along it without destruction of gnomes). Consider index i from this list. If for the correspondent vertex the optimal path to the next vertex of the Good Path is on the Evil Shortcut, i.e. esum[i] < gsum[i], then it is necessary to destroy all gnomes from that Shortcut using the algorithm described above. In the opposite case it is necessary to set gsum[i] = 0 and update corresponding value in the segment tree of the Shortcut gtree. So one gnome can be removed from the path of Death Mission in O(_log_(_N_)). The amount of gnome removals does not exceed amount of added gnomes (i.e. it is not more than Q), so the complexity of one Death Mission handling is also O(_log_(_N_)). The total complexity is O(_log_(_N_) * Q).",
    "tags": [
      "data structures",
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "176",
    "index": "A",
    "title": "Trading Business",
    "statement": "To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the selling are made only once. To carry out his plan, Qwerty is going to take a bank loan that covers all expenses and to return the loaned money at the end of the operation (the money is returned without the interest). At the same time, Querty wants to get as much profit as possible.\n\nThe system has $n$ planets in total. On each of them Qwerty can buy or sell items of $m$ types (such as food, medicine, weapons, alcohol, and so on). For each planet $i$ and each type of items $j$ Qwerty knows the following:\n\n- $a_{ij}$ — the cost of buying an item;\n- $b_{ij}$ — the cost of selling an item;\n- $c_{ij}$ — the number of remaining items.\n\nIt is not allowed to buy more than $c_{ij}$ items of type $j$ on planet $i$, but it is allowed to sell any number of items of any kind.\n\nKnowing that the hold of Qwerty's ship has room for no more than $k$ items, determine the maximum profit which Qwerty can get.",
    "tutorial": "In this problem some greedy solution expected. Let fix 2 planets: in planet i we will buy items, in planet j we will sell the ones. Profit of item of type k will be b_jk-a_ik. Every item has size 1, so you should greedy take items in order of decreasing of profits of items while you have place in the hold. Scheme of full solution: you should iterate over all pairs of planet, for every pair greedy take items and find total profit. At the end you should find maximal total profit over all pairs and output it.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "176",
    "index": "B",
    "title": "Word Cut",
    "statement": "Let's consider one interesting word game. In this game you should transform one word into another through special operations.\n\nLet's say we have word $w$, let's split this word into two non-empty parts $x$ and $y$ so, that $w = xy$. A split operation is transforming word $w = xy$ into word $u = yx$. For example, a split operation can transform word \"wordcut\" into word \"cutword\".\n\nYou are given two words $start$ and $end$. Count in how many ways we can transform word $start$ into word $end$, if we apply exactly $k$ split operations consecutively to word $start$.\n\nTwo ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number $i$ ($1 ≤ i ≤ k$), that in the $i$-th operation of the first sequence the word splits into parts $x$ and $y$, in the $i$-th operation of the second sequence the word splits into parts $a$ and $b$, and additionally $x ≠ a$ holds.",
    "tutorial": "You can see that split oparetion is just cyclically shift of string. You can go from any cyclically shift to any other one except the current one. Let's call some cyclically shift good iff it equal to the final string. All others cyclically shifts we will call bad. You can check all shifts in $O(|w|^{2})$ time. Let's you have A good shifts and B bad ones. Let's define dpA[n] as number of ways to get some good shift using n splits and dpB[n] as number of ways to get some bad shift using n splits. dpA[0]=1, dpB[0]=0 or dpA[0]=0, dpB[0]=1 according to the first shift is good or not. All other values of dp you can get using following reccurences: dpA[n] = dpA[n-1] * (A-1) + dpB[n-1] * A dpB[n] = dpA[n-1] * B + dpB[n-1] * (B-1) Answer will be dpA[k]. So you have $O(|w|^{2} + k)$ solution. Also this problem can be solved in $O(|w|+\\log k)$ time.",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "176",
    "index": "C",
    "title": "Playing with Superglue",
    "statement": "Two players play a game. The game is played on a rectangular board with $n × m$ squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.\n\nWe'll describe the rules of the game in more detail.\n\nThe players move in turns. The first player begins.\n\nWith every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.\n\nAt each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.\n\nIf, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible — he can always spread the glue on the square from which the first player has just moved the chip.\n\nWe will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.\n\nYou know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.",
    "tutorial": "The second player have easy strategy to hold some chip in position $(X, Y)$ in one of four half-planes - $x  \\le  X + 2$, $x  \\ge  X - 2$, $y  \\le  Y + 2$ and $y  \\ge  Y - 2$. He can chose one of these half-planes by himself. So, in case $max(|x1 - x2|, |y1 - y2|) > 4$ the second player wins - he just holds chips in half-planes that have no common cells. Cases for $max(|x1 - x2|, |y1 - y2|)  \\le  4$ expected to solve using some bruteforce. You can see that moving chips in way of distancing from each other is not profitable for the first player. Therefore you can bruteforce the game in square no more than $5  \\times  5$. If your bruteforce so slow and doesn't fit into 2 sec, you can use precalculation. Also you can write some dp using masks. Also you can check cases $max(|x1 - x2|, |y1 - y2|)  \\le  4$ by hand. But there you can easy make some mistakes.",
    "tags": [
      "combinatorics",
      "constructive algorithms"
    ],
    "rating": 2000
  },
  {
    "contest_id": "176",
    "index": "D",
    "title": "Hyper String",
    "statement": "Paul Erdős's prediction came true. Finally an alien force landed on the Earth. In contrary to our expectation they didn't asked the humans to compute the value of a Ramsey number (maybe they had solved it themselves). They asked another question which seemed as hard as calculating Ramsey numbers. Aliens threatened that if humans don't solve this problem in less than 2 hours they will destroy the Earth.\n\nBefore telling the problem they introduced the concept of Hyper Strings. A Hyper String is made by concatenation of some base strings. Suppose you are given a list of base strings $b_{1}, b_{2}, ..., b_{n}$. Now the Hyper String made from indices list $i_{1}, i_{2}, ..., i_{m}$ is concatenation of base strings $b_{i1}, b_{i2}, ..., b_{im}$. A Hyper String can be very large and doing operations on it is very costly for computers.\n\nThe aliens asked humans to compute the length of the longest common sub-sequence of a Hyper String $t$ with a string $s$.",
    "tutorial": "Let's define $dp[pre][len]$ as the minimal prefix of hyperstring that have with prefix of $t$ of length $len$ largest common sequence of length $len$. Then you have see reccurences: $dp[pre][len] = min(dp[pre - 1][len],$ leftmost position of letter $s[pre]$ in $t$ that right than $dp[pre - 1][len - 1])$. For finding value of the second part inside min-function of formula above in $O(1)$, you should calculate some additional dp's: dp1 - for every basic string, positions inside of them and letter you should calculate leftmost position of current letter that right than current position; dp2 - for every element of array of basic strings (it is hyperstring) and letter you should calculate leftmost basic string that have current letter and this string is rinht than current basic string. So you have $O(26\\sum|b_{i}|+26m+|s|^{2})$ solution.",
    "tags": [
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "176",
    "index": "E",
    "title": "Archaeology",
    "statement": "This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago.\n\nOverall they've dug out $n$ villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall there were exactly $n - 1$ roads, and from any village one could get to any other one.\n\nThe tribes were not peaceful, and they had many wars. As a result of the wars, some villages were completely destroyed. During more peaceful years, some of the villages were restored.\n\nAt each moment of time, people \\underline{used} only those roads that belonged to some shortest way between two villages \\underline{that existed at the given moment}. In other words, people used the minimum subset of roads in such a way that it was possible to get from any existing village to any other existing one. Note that throughout the island's whole history, there existed exactly $n - 1$ roads that have been found by the researchers. There never were any other roads.\n\nThe researchers think that observing the total sum of used roads' lengths at different moments of time can help to better understand the tribes' culture and answer several historical questions.\n\nYou will be given the full history of the tribes' existence. Your task is to determine the total length of used roads at some moments of time.",
    "tutorial": "At the first let's try to solve another problem: we have $k$ chosed vertices in the tree and we want to find sum of subtree that \"spanned\" dy them in time $O(k \\log n)$ (with any preprocessing time). Let's sort all $k$ vertices in order of dfs traversal - $v_{1}$, $v_{2}$, ... , $v_{k}$. Consider pathes v1-v2, v2-v3, ... , v(k-1)-vk and vk-v1. You can see that they cover only our requred subtree and every edge is covered exactly two times. So you can just find sum of lengths of these pathes (you can do it in required $O(k \\log n)$ time using LCA algo) and divide obtained value by 2. For solving initial problem you should support set of active vertices in ordered state (for example, you can use std::set) and sum of all pathes between all neighbour vertices. Now you can process insert/remove queries in $O(\\log n)$, and recalculate sum of pathes by finding no more than 3 new pathes also in $O(\\log n)$. So you have $O((n+q)\\log n)$ solution.",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "178",
    "index": "A1",
    "title": "Educational Game",
    "statement": "The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.\n\nThe playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some prefix of the sequence) equal to zero for some fixed $k$ $(k < n)$, and this should be done in the smallest possible number of moves.\n\nOne move is choosing an integer $i$ ($1 ≤ i ≤ n$) such that $a_{i} > 0$ and an integer $t$ $(t ≥ 0)$ such that $i + 2^{t} ≤ n$. After the values of $i$ and $t$ have been selected, the value of $a_{i}$ is decreased by $1$, and the value of $a_{i + 2^{t}}$ is increased by $1$. For example, let $n = 4$ and $a = (1, 0, 1, 2)$, then it is possible to make move $i = 3$, $t = 0$ and get $a = (1, 0, 0, 3)$ or to make move $i = 1$, $t = 1$ and get $a = (0, 0, 2, 2)$ (the only possible other move is $i = 1$, $t = 0$).\n\nYou are given $n$ and the initial sequence $a_{i}$. The task is to calculate the minimum number of moves needed to make the first $k$ elements of the original sequence equal to zero for each possible $k$ $(1 ≤ k < n)$.",
    "tutorial": "It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t}  \\le  n$. In that case later zeroing out longer prefixes of the sequence will take less steps. Having zeroed $a_{1}$, we will write a current answer and notice that we reduce the task to the smaller one - sequence becomes one element shorter. The complexity of a solution $O(n * \\log n)$ or $O(n)$ - depends on implementation. One can solve the task in a different way. To start from, the task can be solved for each element $a_{i}$ separately. In other words, if we fix some $k$, contribution of each $a_{i}$ to an answer can be counted separately. We fix some $a_{i}$. Then we find maximum $j$ so that $i + 2^{j}  \\le  n$. Evidently, that for every $k < i + 2^{j}$, contribution of $a_{i}$ to the answer equals $a_{i}$. In other words, one needs to make $a_{i}$ steps with transition to $a_{i}$. Further we need to find maximum $u$, so that $2^{j} + 2^{u}  \\le  n$. Notice that $u < j$. Contribution of $a_{i}$ to the answer is equal $2 * a_{i}$, for every $k$ that $i + 2^{j}  \\le  k < i + 2^{j} + 2^{u}$. Then we find $q$ that $i + 2^{j} + 2^{u} + 2^{q}  \\le  n$, and so on ... A corresponding sequence of powers of $2$ should be found for each element $a_{i}$. Evidently, that overall complexity of this process is $O(n * \\log n)$. Now we need to calculate an answer. It can be done, for example, like that: we will store the array $b_{i}$ - the change of the answer at the transition from $i$ to $4i + 1$. This array is formed in a trivial way during construction of sequences of powers of twos. Then it is easy to get the answer. The overall complexity of the solution equals $O(n * \\log n)$.",
    "tags": [],
    "rating": 1000
  },
  {
    "contest_id": "178",
    "index": "A2",
    "title": "Educational Game",
    "statement": "The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.\n\nThe playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some prefix of the sequence) equal to zero for some fixed $k$ $(k < n)$, and this should be done in the smallest possible number of moves.\n\nOne move is choosing an integer $i$ ($1 ≤ i ≤ n$) such that $a_{i} > 0$ and an integer $t$ $(t ≥ 0)$ such that $i + 2^{t} ≤ n$. After the values of $i$ and $t$ have been selected, the value of $a_{i}$ is decreased by $1$, and the value of $a_{i + 2^{t}}$ is increased by $1$. For example, let $n = 4$ and $a = (1, 0, 1, 2)$, then it is possible to make move $i = 3$, $t = 0$ and get $a = (1, 0, 0, 3)$ or to make move $i = 1$, $t = 1$ and get $a = (0, 0, 2, 2)$ (the only possible other move is $i = 1$, $t = 0$).\n\nYou are given $n$ and the initial sequence $a_{i}$. The task is to calculate the minimum number of moves needed to make the first $k$ elements of the original sequence equal to zero for each possible $k$ $(1 ≤ k < n)$.",
    "tutorial": "It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t}  \\le  n$. In that case later zeroing out longer prefixes of the sequence will take less steps. Having zeroed $a_{1}$, we will write a current answer and notice that we reduce the task to the smaller one - sequence becomes one element shorter. The complexity of a solution $O(n * \\log n)$ or $O(n)$ - depends on implementation. One can solve the task in a different way. To start from, the task can be solved for each element $a_{i}$ separately. In other words, if we fix some $k$, contribution of each $a_{i}$ to an answer can be counted separately. We fix some $a_{i}$. Then we find maximum $j$ so that $i + 2^{j}  \\le  n$. Evidently, that for every $k < i + 2^{j}$, contribution of $a_{i}$ to the answer equals $a_{i}$. In other words, one needs to make $a_{i}$ steps with transition to $a_{i}$. Further we need to find maximum $u$, so that $2^{j} + 2^{u}  \\le  n$. Notice that $u < j$. Contribution of $a_{i}$ to the answer is equal $2 * a_{i}$, for every $k$ that $i + 2^{j}  \\le  k < i + 2^{j} + 2^{u}$. Then we find $q$ that $i + 2^{j} + 2^{u} + 2^{q}  \\le  n$, and so on ... A corresponding sequence of powers of $2$ should be found for each element $a_{i}$. Evidently, that overall complexity of this process is $O(n * \\log n)$. Now we need to calculate an answer. It can be done, for example, like that: we will store the array $b_{i}$ - the change of the answer at the transition from $i$ to $4i + 1$. This array is formed in a trivial way during construction of sequences of powers of twos. Then it is easy to get the answer. The overall complexity of the solution equals $O(n * \\log n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "178",
    "index": "A3",
    "title": "Educational Game",
    "statement": "The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.\n\nThe playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some prefix of the sequence) equal to zero for some fixed $k$ $(k < n)$, and this should be done in the smallest possible number of moves.\n\nOne move is choosing an integer $i$ ($1 ≤ i ≤ n$) such that $a_{i} > 0$ and an integer $t$ $(t ≥ 0)$ such that $i + 2^{t} ≤ n$. After the values of $i$ and $t$ have been selected, the value of $a_{i}$ is decreased by $1$, and the value of $a_{i + 2^{t}}$ is increased by $1$. For example, let $n = 4$ and $a = (1, 0, 1, 2)$, then it is possible to make move $i = 3$, $t = 0$ and get $a = (1, 0, 0, 3)$ or to make move $i = 1$, $t = 1$ and get $a = (0, 0, 2, 2)$ (the only possible other move is $i = 1$, $t = 0$).\n\nYou are given $n$ and the initial sequence $a_{i}$. The task is to calculate the minimum number of moves needed to make the first $k$ elements of the original sequence equal to zero for each possible $k$ $(1 ≤ k < n)$.",
    "tutorial": "It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t}  \\le  n$. In that case later zeroing out longer prefixes of the sequence will take less steps. Having zeroed $a_{1}$, we will write a current answer and notice that we reduce the task to the smaller one - sequence becomes one element shorter. The complexity of a solution $O(n * \\log n)$ or $O(n)$ - depends on implementation. One can solve the task in a different way. To start from, the task can be solved for each element $a_{i}$ separately. In other words, if we fix some $k$, contribution of each $a_{i}$ to an answer can be counted separately. We fix some $a_{i}$. Then we find maximum $j$ so that $i + 2^{j}  \\le  n$. Evidently, that for every $k < i + 2^{j}$, contribution of $a_{i}$ to the answer equals $a_{i}$. In other words, one needs to make $a_{i}$ steps with transition to $a_{i}$. Further we need to find maximum $u$, so that $2^{j} + 2^{u}  \\le  n$. Notice that $u < j$. Contribution of $a_{i}$ to the answer is equal $2 * a_{i}$, for every $k$ that $i + 2^{j}  \\le  k < i + 2^{j} + 2^{u}$. Then we find $q$ that $i + 2^{j} + 2^{u} + 2^{q}  \\le  n$, and so on ... A corresponding sequence of powers of $2$ should be found for each element $a_{i}$. Evidently, that overall complexity of this process is $O(n * \\log n)$. Now we need to calculate an answer. It can be done, for example, like that: we will store the array $b_{i}$ - the change of the answer at the transition from $i$ to $4i + 1$. This array is formed in a trivial way during construction of sequences of powers of twos. Then it is easy to get the answer. The overall complexity of the solution equals $O(n * \\log n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "178",
    "index": "B1",
    "title": "Greedy Merchants",
    "statement": "In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.\n\nThe Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two different cities. Any two cities were connected by no more than one road.\n\nWe say that there is a path between cities $c_{1}$ and $c_{2}$ if there exists a finite sequence of cities $t_{1}, t_{2}, ..., t_{p}$ $(p ≥ 1)$ such that:\n\n- $t_{1} = c_{1}$\n- $t_{p} = c_{2}$\n- for any $i$ $(1 ≤ i < p)$, cities $t_{i}$ and $t_{i + 1}$ are connected by a road\n\nWe know that there existed a path between any two cities in the Roman Empire.\n\nIn the Empire $k$ merchants lived numbered from $1$ to $k$. For each merchant we know a pair of numbers $s_{i}$ and $l_{i}$, where $s_{i}$ is the number of the city where this merchant's warehouse is, and $l_{i}$ is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.\n\nLet's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays $d_{i}$ dinars of tax, where $d_{i}$ ($d_{i} ≥ 0$) is the number of roads important for the $i$-th merchant.\n\nThe tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.",
    "tutorial": "First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the graph bridges graph is divided for some components of connectivity (maybe one component). Let's build new graph in which recieved components will be nodes and bridges - edges. This graph will be a tree. The graph is connected therefore the tree is connected. The edges correspond to bridges therefore there is no cycles in the tree. Note that the number of denarii means the pay of every merchant - is a distance between some the nodes in a new graph. But as this graph is a tree this distances can be easily find out using LCA search algorithms for two nodes. In this problem one should use the simplest LCA search algorithm which accomplish the preprocess for $O(n\\cdot\\log n)$ and handle one request for $O(\\log n)$. The complexity of computations id $O(m+(n+k)\\cdot\\log n)$. One can solve this problem easier. Let's build a graph recursive pass-by initial graph and weight its edges. The edges with weight equals 1 will have bridges and others will have weight equals 0. So after all these reductions for solving problem it will be enough to compute the distance between two nodes in the graph recursive pass-by initial graph.",
    "tags": [],
    "rating": 1600
  },
  {
    "contest_id": "178",
    "index": "B2",
    "title": "Greedy Merchants",
    "statement": "In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.\n\nThe Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two different cities. Any two cities were connected by no more than one road.\n\nWe say that there is a path between cities $c_{1}$ and $c_{2}$ if there exists a finite sequence of cities $t_{1}, t_{2}, ..., t_{p}$ $(p ≥ 1)$ such that:\n\n- $t_{1} = c_{1}$\n- $t_{p} = c_{2}$\n- for any $i$ $(1 ≤ i < p)$, cities $t_{i}$ and $t_{i + 1}$ are connected by a road\n\nWe know that there existed a path between any two cities in the Roman Empire.\n\nIn the Empire $k$ merchants lived numbered from $1$ to $k$. For each merchant we know a pair of numbers $s_{i}$ and $l_{i}$, where $s_{i}$ is the number of the city where this merchant's warehouse is, and $l_{i}$ is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.\n\nLet's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays $d_{i}$ dinars of tax, where $d_{i}$ ($d_{i} ≥ 0$) is the number of roads important for the $i$-th merchant.\n\nThe tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.",
    "tutorial": "First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the graph bridges graph is divided for some components of connectivity (maybe one component). Let's build new graph in which recieved components will be nodes and bridges - edges. This graph will be a tree. The graph is connected therefore the tree is connected. The edges correspond to bridges therefore there is no cycles in the tree. Note that the number of denarii means the pay of every merchant - is a distance between some the nodes in a new graph. But as this graph is a tree this distances can be easily find out using LCA search algorithms for two nodes. In this problem one should use the simplest LCA search algorithm which accomplish the preprocess for $O(n\\cdot\\log n)$ and handle one request for $O(\\log n)$. The complexity of computations id $O(m+(n+k)\\cdot\\log n)$. One can solve this problem easier. Let's build a graph recursive pass-by initial graph and weight its edges. The edges with weight equals 1 will have bridges and others will have weight equals 0. So after all these reductions for solving problem it will be enough to compute the distance between two nodes in the graph recursive pass-by initial graph.",
    "tags": [],
    "rating": 1600
  },
  {
    "contest_id": "178",
    "index": "B3",
    "title": "Greedy Merchants",
    "statement": "In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.\n\nThe Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two different cities. Any two cities were connected by no more than one road.\n\nWe say that there is a path between cities $c_{1}$ and $c_{2}$ if there exists a finite sequence of cities $t_{1}, t_{2}, ..., t_{p}$ $(p ≥ 1)$ such that:\n\n- $t_{1} = c_{1}$\n- $t_{p} = c_{2}$\n- for any $i$ $(1 ≤ i < p)$, cities $t_{i}$ and $t_{i + 1}$ are connected by a road\n\nWe know that there existed a path between any two cities in the Roman Empire.\n\nIn the Empire $k$ merchants lived numbered from $1$ to $k$. For each merchant we know a pair of numbers $s_{i}$ and $l_{i}$, where $s_{i}$ is the number of the city where this merchant's warehouse is, and $l_{i}$ is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.\n\nLet's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays $d_{i}$ dinars of tax, where $d_{i}$ ($d_{i} ≥ 0$) is the number of roads important for the $i$-th merchant.\n\nThe tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.",
    "tutorial": "First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the graph bridges graph is divided for some components of connectivity (maybe one component). Let's build new graph in which recieved components will be nodes and bridges - edges. This graph will be a tree. The graph is connected therefore the tree is connected. The edges correspond to bridges therefore there is no cycles in the tree. Note that the number of denarii means the pay of every merchant - is a distance between some the nodes in a new graph. But as this graph is a tree this distances can be easily find out using LCA search algorithms for two nodes. In this problem one should use the simplest LCA search algorithm which accomplish the preprocess for $O(n\\cdot\\log n)$ and handle one request for $O(\\log n)$. The complexity of computations id $O(m+(n+k)\\cdot\\log n)$. One can solve this problem easier. Let's build a graph recursive pass-by initial graph and weight its edges. The edges with weight equals 1 will have bridges and others will have weight equals 0. So after all these reductions for solving problem it will be enough to compute the distance between two nodes in the graph recursive pass-by initial graph.",
    "tags": [],
    "rating": 1800
  },
  {
    "contest_id": "178",
    "index": "C1",
    "title": "Smart Beaver and Resolving Collisions",
    "statement": "The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.\n\nWe assume that the hash table consists of $h$ cells numbered from $0$ to $h - 1$. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value — an integer between $0$ and $h - 1$, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.\n\nThe Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals $t$ and cell $t$ of the table is already occupied. Then we try to add this object to cell $(t + m) mod h$. If it is also occupied, then we try cell $(t + 2·m) mod h$, then cell $(t + 3·m) mod h$, and so on. Note that in some cases it's possible that the new object can not be added to the table. \\underline{It is guaranteed that the input for this problem doesn't contain such situations}.\n\nThe operation $a mod b$ means that we take the remainder of the division of number $a$ by number $b$.\n\nThis technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell $(t + i·m) mod h$ $(i ≥ 0)$, then exactly $i$ dummy calls have been performed.\n\nYour task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.",
    "tutorial": "Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this property? The element with fixed hash-value will be added into some (next) cell in the corresponding to element's hash-value cycle. So, we can process each cycle separately. To do this effectively (we want to solve large test package) we have to use any tree-structure like segment tree or combination of Fenwick tree with binary search. An effectiveness of solution with segment tree is $O(n\\cdot\\log h)$, of solution with Fenwick tree - $O(n\\cdot\\log^{2}h)$.",
    "tags": [],
    "rating": 1600
  },
  {
    "contest_id": "178",
    "index": "C2",
    "title": "Smart Beaver and Resolving Collisions",
    "statement": "The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.\n\nWe assume that the hash table consists of $h$ cells numbered from $0$ to $h - 1$. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value — an integer between $0$ and $h - 1$, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.\n\nThe Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals $t$ and cell $t$ of the table is already occupied. Then we try to add this object to cell $(t + m) mod h$. If it is also occupied, then we try cell $(t + 2·m) mod h$, then cell $(t + 3·m) mod h$, and so on. Note that in some cases it's possible that the new object can not be added to the table. \\underline{It is guaranteed that the input for this problem doesn't contain such situations}.\n\nThe operation $a mod b$ means that we take the remainder of the division of number $a$ by number $b$.\n\nThis technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell $(t + i·m) mod h$ $(i ≥ 0)$, then exactly $i$ dummy calls have been performed.\n\nYour task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.",
    "tutorial": "Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this property? The element with fixed hash-value will be added into some (next) cell in the corresponding to element's hash-value cycle. So, we can process each cycle separately. To do this effectively (we want to solve large test package) we have to use any tree-structure like segment tree or combination of Fenwick tree with binary search. An effectiveness of solution with segment tree is $O(n\\cdot\\log h)$, of solution with Fenwick tree - $O(n\\cdot\\log^{2}h)$.",
    "tags": [],
    "rating": 1900
  },
  {
    "contest_id": "178",
    "index": "C3",
    "title": "Smart Beaver and Resolving Collisions",
    "statement": "The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.\n\nWe assume that the hash table consists of $h$ cells numbered from $0$ to $h - 1$. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value — an integer between $0$ and $h - 1$, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.\n\nThe Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals $t$ and cell $t$ of the table is already occupied. Then we try to add this object to cell $(t + m) mod h$. If it is also occupied, then we try cell $(t + 2·m) mod h$, then cell $(t + 3·m) mod h$, and so on. Note that in some cases it's possible that the new object can not be added to the table. \\underline{It is guaranteed that the input for this problem doesn't contain such situations}.\n\nThe operation $a mod b$ means that we take the remainder of the division of number $a$ by number $b$.\n\nThis technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell $(t + i·m) mod h$ $(i ≥ 0)$, then exactly $i$ dummy calls have been performed.\n\nYour task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.",
    "tutorial": "Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this property? The element with fixed hash-value will be added into some (next) cell in the corresponding to element's hash-value cycle. So, we can process each cycle separately. To do this effectively (we want to solve large test package) we have to use any tree-structure like segment tree or combination of Fenwick tree with binary search. An effectiveness of solution with segment tree is $O(n\\cdot\\log h)$, of solution with Fenwick tree - $O(n\\cdot\\log^{2}h)$.",
    "tags": [],
    "rating": 2000
  },
  {
    "contest_id": "178",
    "index": "D1",
    "title": "Magic Squares",
    "statement": "The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.\n\nThe magic square is a matrix of size $n × n$. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number $s$. The sum of numbers in each column of the matrix is also equal to $s$. In addition, the sum of the elements on the main diagonal is equal to $s$ and the sum of elements on the secondary diagonal is equal to $s$. Examples of magic squares are given in the following figure:\n\n\\begin{center}\n{\\scriptsize Magic squares}\n\\end{center}\n\nYou are given a set of $n^{2}$ integers $a_{i}$. It is required to place these numbers into a square matrix of size $n × n$ so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.\n\nIt is guaranteed that a solution exists!",
    "tutorial": "Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on two main ideas: We can determine some square elements during the brute force using already fixed values. For example, if we have fixed three of values on the main diagonal, we can easily determine the fourth value. This trick decrease the number of brute force iterations. We can rotate (or mirror) magic square without breaking his magic properties. The second way use discrete-optimization approach. Let's consider the function $Q = |sum_{1} - s| + ... + |sum_{t} - s|$, where $|x|$ - the absolute value of $x$, $t = 2 * n + 2, sum_{1}, .., sum_{n}$ - the sum of elements in one row, $sum_{n + 1}, sum_{2n}$ - the sum of element in one column, $sum_{t} - 1$ - the sum of elements on the main diagonal, $sum_{t}$ --- the sum of elements on the secondary diagonal. So, we want to find such permutation of the given elements that make our function as small as possible (We want to obtain zero). One way to do this: pick the random permutation. Try to make swaps in this permutation using greedy strategy (try to make swaps that make our function better). Let's do 1000 swaps. If we obtain $Q = 0$ - we have found answer, else $Q > 0$ -- pick another random permutation and repeat this process again.",
    "tags": [],
    "rating": 1500
  },
  {
    "contest_id": "178",
    "index": "D2",
    "title": "Magic Squares",
    "statement": "The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.\n\nThe magic square is a matrix of size $n × n$. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number $s$. The sum of numbers in each column of the matrix is also equal to $s$. In addition, the sum of the elements on the main diagonal is equal to $s$ and the sum of elements on the secondary diagonal is equal to $s$. Examples of magic squares are given in the following figure:\n\n\\begin{center}\n{\\scriptsize Magic squares}\n\\end{center}\n\nYou are given a set of $n^{2}$ integers $a_{i}$. It is required to place these numbers into a square matrix of size $n × n$ so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.\n\nIt is guaranteed that a solution exists!",
    "tutorial": "Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on two main ideas: We can determine some square elements during the brute force using already fixed values. For example, if we have fixed three of values on the main diagonal, we can easily determine the fourth value. This trick decrease the number of brute force iterations. We can rotate (or mirror) magic square without breaking his magic properties. The second way use discrete-optimization approach. Let's consider the function $Q = |sum_{1} - s| + ... + |sum_{t} - s|$, where $|x|$ - the absolute value of $x$, $t = 2 * n + 2, sum_{1}, .., sum_{n}$ - the sum of elements in one row, $sum_{n + 1}, sum_{2n}$ - the sum of element in one column, $sum_{t} - 1$ - the sum of elements on the main diagonal, $sum_{t}$ --- the sum of elements on the secondary diagonal. So, we want to find such permutation of the given elements that make our function as small as possible (We want to obtain zero). One way to do this: pick the random permutation. Try to make swaps in this permutation using greedy strategy (try to make swaps that make our function better). Let's do 1000 swaps. If we obtain $Q = 0$ - we have found answer, else $Q > 0$ -- pick another random permutation and repeat this process again.",
    "tags": [],
    "rating": 1900
  },
  {
    "contest_id": "178",
    "index": "D3",
    "title": "Magic Squares",
    "statement": "The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.\n\nThe magic square is a matrix of size $n × n$. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number $s$. The sum of numbers in each column of the matrix is also equal to $s$. In addition, the sum of the elements on the main diagonal is equal to $s$ and the sum of elements on the secondary diagonal is equal to $s$. Examples of magic squares are given in the following figure:\n\n\\begin{center}\n{\\scriptsize Magic squares}\n\\end{center}\n\nYou are given a set of $n^{2}$ integers $a_{i}$. It is required to place these numbers into a square matrix of size $n × n$ so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.\n\nIt is guaranteed that a solution exists!",
    "tutorial": "Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on two main ideas: We can determine some square elements during the brute force using already fixed values. For example, if we have fixed three of values on the main diagonal, we can easily determine the fourth value. This trick decrease the number of brute force iterations. We can rotate (or mirror) magic square without breaking his magic properties. The second way use discrete-optimization approach. Let's consider the function $Q = |sum_{1} - s| + ... + |sum_{t} - s|$, where $|x|$ - the absolute value of $x$, $t = 2 * n + 2, sum_{1}, .., sum_{n}$ - the sum of elements in one row, $sum_{n + 1}, sum_{2n}$ - the sum of element in one column, $sum_{t} - 1$ - the sum of elements on the main diagonal, $sum_{t}$ --- the sum of elements on the secondary diagonal. So, we want to find such permutation of the given elements that make our function as small as possible (We want to obtain zero). One way to do this: pick the random permutation. Try to make swaps in this permutation using greedy strategy (try to make swaps that make our function better). Let's do 1000 swaps. If we obtain $Q = 0$ - we have found answer, else $Q > 0$ -- pick another random permutation and repeat this process again.",
    "tags": [],
    "rating": 2100
  },
  {
    "contest_id": "178",
    "index": "E1",
    "title": "The Beaver's Problem - 2",
    "statement": "Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem.\n\nYou are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the matrix's size coincides with the size of the image.\n\nThe white color on the given image corresponds to the background. Also, the image contains several black geometric shapes. It is known that the image can contain only two types of shapes: squares and circles. Your task is to count the number of circles and the number of squares which the given image contains.\n\nThe squares on the image can be rotated arbitrarily. In addition, the image can possibly contain some noise arranged as follows: each pixel of the original image can change its color to the opposite with the probability of $20$%.\n\n\\begin{center}\n{\\scriptsize An example of an image that has no noise and the sides of the squares are parallel to the coordinate axes (two circles and three squares).}\n\\end{center}\n\n\\begin{center}\n{\\scriptsize An example of an image that has no noise and the squares are rotated arbitrarily (two circles and three squares).}\n\\end{center}\n\n\\begin{center}\n{\\scriptsize An example of an image that has noise and the squares are rotated arbitrarily (one circle and three squares).}\n\\end{center}",
    "tutorial": "Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of almost all noise on the picture. Then we make inverse opreation replacing all white pixels with black. So we get rid of almost all noise inside the picture. Note, that after all these opreations noise can stay as little black components. And some figures can lose their connectivity. These problems can be solved by deletion little black components and then unite near black components. b. But one can use easier way. Highlight black components and then cast away little ones. If to look closely to the texts in real under even distribution of the noise there is no little black components and it is not losing connectivity. However previous way is more reliable. The simplest way to classificate figures is to compare distributions of the distances from all the figure pixels to centre of the every figure. The centre can be calculated as average of the all points coordinates of the figure. Ditributions can be compared by expectation values and variations.",
    "tags": [],
    "rating": 1900
  },
  {
    "contest_id": "178",
    "index": "E2",
    "title": "The Beaver's Problem - 2",
    "statement": "Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem.\n\nYou are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the matrix's size coincides with the size of the image.\n\nThe white color on the given image corresponds to the background. Also, the image contains several black geometric shapes. It is known that the image can contain only two types of shapes: squares and circles. Your task is to count the number of circles and the number of squares which the given image contains.\n\nThe squares on the image can be rotated arbitrarily. In addition, the image can possibly contain some noise arranged as follows: each pixel of the original image can change its color to the opposite with the probability of $20$%.\n\n\\begin{center}\n{\\scriptsize An example of an image that has no noise and the sides of the squares are parallel to the coordinate axes (two circles and three squares).}\n\\end{center}\n\n\\begin{center}\n{\\scriptsize An example of an image that has no noise and the squares are rotated arbitrarily (two circles and three squares).}\n\\end{center}\n\n\\begin{center}\n{\\scriptsize An example of an image that has noise and the squares are rotated arbitrarily (one circle and three squares).}\n\\end{center}",
    "tutorial": "Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of almost all noise on the picture. Then we make inverse opreation replacing all white pixels with black. So we get rid of almost all noise inside the picture. Note, that after all these opreations noise can stay as little black components. And some figures can lose their connectivity. These problems can be solved by deletion little black components and then unite near black components. b. But one can use easier way. Highlight black components and then cast away little ones. If to look closely to the texts in real under even distribution of the noise there is no little black components and it is not losing connectivity. However previous way is more reliable. The simplest way to classificate figures is to compare distributions of the distances from all the figure pixels to centre of the every figure. The centre can be calculated as average of the all points coordinates of the figure. Ditributions can be compared by expectation values and variations.",
    "tags": [],
    "rating": 2000
  },
  {
    "contest_id": "178",
    "index": "E3",
    "title": "The Beaver's Problem - 2",
    "statement": "Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem.\n\nYou are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the matrix's size coincides with the size of the image.\n\nThe white color on the given image corresponds to the background. Also, the image contains several black geometric shapes. It is known that the image can contain only two types of shapes: squares and circles. Your task is to count the number of circles and the number of squares which the given image contains.\n\nThe squares on the image can be rotated arbitrarily. In addition, the image can possibly contain some noise arranged as follows: each pixel of the original image can change its color to the opposite with the probability of $20$%.\n\n\\begin{center}\n{\\scriptsize An example of an image that has no noise and the sides of the squares are parallel to the coordinate axes (two circles and three squares).}\n\\end{center}\n\n\\begin{center}\n{\\scriptsize An example of an image that has no noise and the squares are rotated arbitrarily (two circles and three squares).}\n\\end{center}\n\n\\begin{center}\n{\\scriptsize An example of an image that has noise and the squares are rotated arbitrarily (one circle and three squares).}\n\\end{center}",
    "tutorial": "Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of almost all noise on the picture. Then we make inverse opreation replacing all white pixels with black. So we get rid of almost all noise inside the picture. Note, that after all these opreations noise can stay as little black components. And some figures can lose their connectivity. These problems can be solved by deletion little black components and then unite near black components. b. But one can use easier way. Highlight black components and then cast away little ones. If to look closely to the texts in real under even distribution of the noise there is no little black components and it is not losing connectivity. However previous way is more reliable. The simplest way to classificate figures is to compare distributions of the distances from all the figure pixels to centre of the every figure. The centre can be calculated as average of the all points coordinates of the figure. Ditributions can be compared by expectation values and variations.",
    "tags": [],
    "rating": 2300
  },
  {
    "contest_id": "181",
    "index": "A",
    "title": "Series of Crimes",
    "statement": "The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.\n\nThe Berland capital's map is represented by an $n × m$ rectangular table. Each cell of the table on the map represents some districts of the capital.\n\nThe capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.\n\nPolycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.",
    "tutorial": "Required row is row that have only one star inside. Requred column is comumn that also have only one star inside. So, you can iterate over all rows/columns, calculate number of stars inside them and find the answer.",
    "tags": [
      "brute force",
      "geometry",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "181",
    "index": "B",
    "title": "Number of Triplets",
    "statement": "You are given $n$ points on a plane. All points are different.\n\nFind the number of different groups of three points $(A, B, C)$ such that point $B$ is the middle of segment $AC$.\n\nThe groups of three points are considered unordered, that is, if point $B$ is the middle of segment $AC$, then groups $(A, B, C)$ and $(C, B, A)$ are considered the same.",
    "tutorial": "Naive solution $O(n^{3})$ (where you check all triplets) doesn't fin into time limits. You can see that for every two points from triplet (for example, for A and C) you can find place of the third point. So you can find number of requred triplets just inerate over all pairs of points and check middle point between points in every pair. How to fast check position? You can add 1000 for all coordinates (you can see that this operation doesn't change the answer) and mark them in the 2-dimensional boolean array 2001x2001. So you can check every position for point in $O(1)$ time. Obtained solution works in $O(n^{2})$.",
    "tags": [
      "binary search",
      "brute force"
    ],
    "rating": 1300
  },
  {
    "contest_id": "183",
    "index": "A",
    "title": "Headquarters",
    "statement": "Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious \"Pihters\" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.\n\nThe outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made \\textbf{exactly} $n$ movements on its way from the headquarters to the stall. A movement can move the car from point $(x, y)$ to one of these four points: to point $(x - 1, y)$ which we will mark by letter \"L\", to point $(x + 1, y)$ — \"R\", to point $(x, y - 1)$ — \"D\", to point $(x, y + 1)$ — \"U\".\n\nThe GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: \"UL\", \"UR\", \"DL\", \"DR\" or \"ULDR\". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string \"UL\" means that the car moved either \"U\", or \"L\".\n\nYou've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point $(0, 0)$, your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).",
    "tutorial": "Ad Hoc I supppose... This problem is equivalent to calculating the number of reachable locations from point (0, 0) by doing the allowed moves. The naive solution is to process the information one by one from first to last, and to keep track on all the reachable positions. Claim: At any moment in time, all reachable locations as described above forms a \"diamond\". An extremely informal proof is by induction: For instance, let's use the first example: UR UL ULDRInitially, there's only one possible location (namely, (0, 0)). It forms the basis of our induction: a diamond with width=1 and height=1. \"UR\" (and also \"DL\") extends the width of the diamond into a 2x1 diamond: Then, \"UL\" (and also \"DR\") extends the height of the diamond into a 2x2 diamond: Finally, \"ULDR\" extends both the height and the width of the diamond into a 3x3 diamond: And so there's 9 possible locations. To see that this claim is true, suppose by induction our locations so far forms a diamond. By symmetry we only need to see that in the \"UR\" case, its width is increased by one (I'll omit the similarly seen \"ULDR\" case). The idea is the new possible locations = the previous diamond shifted one step up UNION that diamond shifted one step right. Indeed, the union of these two diamonds accounts for both the \"U\" and the \"R\" moves. It's not hard to proof that the union of two diamonds with equal dimension that is displaced by vector (1, 1) forms the same diamond with its width increased by 1. So, the solution is to keep track the dimension of the diamond, starting from a 1x1 diamond. Then, simply return width * height.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "183",
    "index": "B",
    "title": "Zoo",
    "statement": "The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has $n$ observation binoculars located at the $OX$ axis. For each $i$ between $1$ and $n$, inclusive, there exists a single binocular located at the point with coordinates $(i, 0)$. There are $m$ flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move.\n\nIn order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line.\n\nToday, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.",
    "tutorial": "Geometry Since there are at least one flamingo, all binoculars will be able to see at least one flamingo. When a binocular is able to see more than one flamingos, then those two flamingos and the binocular must form a line. How many such lines are there? Instead of iterating for each pair of binocular and flamingo, we iterate over each pair of flamingos. These two pair of flamingos completely determine the line as described above. If there does not exists a binocular in this line, we can ignore this pair and continue. Otherwise, calculate the number of flamingos in this line, and let it be one of the possible number of flamingos visible from that binocular. After this is done, simply sum the maximum number of flamingos of each binocular. This works in O(M^3). Note that this problem can be made to run in O(M^2 log M), but coding that solution is sort of... boring ;3.",
    "code": "#include <cstdio>\n#include <numeric>\n#include <iostream>\n#include <vector>\n#include <set>\n#include <cstring>\n#include <string>\n#include <map>\n#include <cmath>\n#include <ctime>\n#include <algorithm>\n#include <bitset>\n#include <queue>\n#include <sstream>\n#include <deque>\n\nusing namespace std;\n\n#define mp make_pair\n#define pb push_back\n#define rep(i,n) for(int i = 0; i < (n); i++)\n#define re return\n#define fi first\n#define se second\n#define sz(x) ((int) (x).size())\n#define all(x) (x).begin(), (x).end()\n#define sqr(x) ((x) * (x))\n#define sqrt(x) sqrt(abs(x))\n#define y0 y3487465\n#define y1 y8687969\n#define next NEXT\n#define fill(x,y) memset(x,y,sizeof(x))\n                         \ntypedef vector<int> vi;\ntypedef long long ll;\ntypedef long double ld;\ntypedef double D;\ntypedef pair<int, int> ii;\ntypedef vector<ii> vii;\ntypedef vector<string> vs;\ntypedef vector<vi> vvi;\n\ntemplate<class T> T abs(T x) { re x > 0 ? x : -x; }\n\nint n;\nint m, u;\nint x[250], y[250];\nint res[1000001];\n\nint main () {\n        scanf (\"%d%d\", &n, &m);\n        for (int i = 0; i < m; i++) scanf (\"%d%d\", &x[i], &y[i]);\n        for (int i = 1; i <= n; i++) res[i] = 1;\n        for (int i = 0; i < m; i++)\n                for (int j = i + 1; j < m; j++) {\n                        if (y[j] == y[i] || (ll)(x[j] - x[i]) * y[i] % (y[j] - y[i]) != 0) continue;\n                        ll t = x[i] + (ll)(x[j] - x[i]) * y[i] / (y[j] - y[i]);\n                        if (t >= 1 && t <= n) {\n                                int tmp = 0;\n                                for (int k = 0; k < m; k++)\n                                        if ((ll)(x[i] - x[k]) * (y[j] - y[k]) - (ll)(x[j] - x[k]) * (y[i] - y[k]) == 0)\n                                                tmp++;\n                                res[t] = max (res[t], tmp);\n                        }\n                }\n        int ans = 0;\n        for (int i = 1; i <= n; i++) ans += res[i];\n        printf (\"%d\n\", ans);\n        return 0;\n}",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 1700
  },
  {
    "contest_id": "183",
    "index": "C",
    "title": "Cyclic Coloring",
    "statement": "You are given a \\textbf{directed} graph $G$ with $n$ vertices and $m$ arcs (\\textbf{multiple arcs and self-loops} are allowed). You have to paint each vertex of the graph into one of the $k$ $(k ≤ n)$ colors in such way that for all arcs of the graph leading from a vertex $u$ to vertex $v$, vertex $v$ is painted with the next color of the color used to paint vertex $u$.\n\nThe colors are numbered cyclically $1$ through $k$. This means that for each color $i$ $(i < k)$ its next color is color $i + 1$. In addition, the next color of color $k$ is color $1$. Note, that if $k = 1$, then the next color for color $1$ is again color $1$.\n\nYour task is to find and print the largest possible value of $k$ $(k ≤ n)$ such that it's possible to color $G$ as described above with $k$ colors. Note that you don't necessarily use all the $k$ colors (that is, for each color $i$ there does not necessarily exist a vertex that is colored with color $i$).",
    "tutorial": "DFS Let's drop the (modulo K). That is, the rule becomes: X->Y implies that Y = X+1 Y->X implies that Y = X-1 Notice that this problem is then equivalent to finding the maximum possible K such that the above equation holds for all edges, modulo K.While we still dropping the \"modulo K\" thingy, we try to calculate the values of each node. We iterate over each node, and if we haven't processed the node: Number the node 0 (or any other number you like). let's denote this by no[i] = 0. DFS the node: DFS(X): if there exists X->Y, then no[Y] = no[X]+1. This follows from the first rule. DFS(X): if there exists Y->X, then no[Y] = no[X]-1. This follows from the second rule. If Y is renumbered (that is, the algorithm has renumber it in the past and we renumber it again), consider the difference between the two numbers. We claim that this difference, if not zero, must be a multiple of K. To see this, suppose the two numbers are A and B. By the way our algorithm works, that node must be able to be numbered A or B. Hence, A == B (mod K) must holds. But then, A-B == 0 (mod K) implies that (A-B) is a multiple of K. If a non-empty multiple of K (let's say it's CYCLEN) is not found in the step above, we claim that the answer is the maximum possible answer: N. Indeed if no such value is found, it means that renumbering the nodes into no[i] % N be correct, since every edge is already consistent with no[i]. Otherwise, we can simply brute force all divisors of CYCLEN and try each of them. Since \"trying\" uses O(E) time (that is, by setting each number into no[i] % K and checking whether the two rules holds for all edges) , we have a O(number_of_divisors * E) algorithm, which with the given constraints is less than O(E * sqrt(N)).",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <map>\n#include <set>\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <utility>\n#include <cstring>\n\n\nusing namespace std;\ntypedef long long LL;\n#define x1 x1_\n#define y1 y1_\ntemplate<typename T>\ninline T Abs(const T& value) { return value < 0 ? -value : value; }\ntemplate<typename T>\ninline T Sqr(const T& value) { return value * value; }\n\n\nconst int maxn = 101000;\n\nvector<int> e[maxn];\nvector<int> ei[maxn];\nint b[maxn];\nint d[maxn];\nint cand = -1;\nvector<int> p;\n\nvoid Dfs(int v, int k) {\n    b[v] = 1;\n    d[v] = k;\n    for (int i = 0; i < e[v].size(); ++i)\n        if (!b[e[v][i]])\n            Dfs(e[v][i], k+1);\n        else if (b[e[v][i]] == 1) {\n            if (abs(d[v]-d[e[v][i]]+1) != 0)\n                cand = abs(d[v] - d[e[v][i]] + 1);\n        }\n    for (int i = 0; i < ei[v].size(); ++i)\n        if (!b[ei[v][i]])\n            Dfs(ei[v][i], k-1);\n        else if (b[ei[v][i]] == 1) {\n            if (abs(d[v] - d[ei[v][i]] - 1))    \n                cand = abs(d[v] - d[ei[v][i]] - 1);\n        }\n    \n    b[v] = 2;\n}\n\nint col[maxn];\n\nbool DfsCan(int v, int x, int mx) {\n    col[v] = x;\n    b[v] = 1;\n    for (int i = 0; i < e[v].size(); ++i)\n        if (!b[e[v][i]]) {\n            DfsCan(e[v][i], (x+1)%mx, mx);\n        } else {\n            if (col[e[v][i]] != (col[v]+1)%mx)\n                return false;\n        }\n    for (int i = 0; i < ei[v].size(); ++i)\n        if (!b[ei[v][i]]) {\n            DfsCan(ei[v][i], (x+mx-1)%mx, mx);\n        } else {\n            if (col[ei[v][i]] != (col[v]+mx-1)%mx)\n                return false;\n        }\n    return true;\n}\n\nint n, m;\n\n\nbool Can(int x) {\n    memset(col, 0, sizeof(col));\n    memset(b, 0, sizeof(b));\n    bool res = true;\n    for (int i = 1; i <= n; ++i)\n        if (!b[i])\n            res = (res && DfsCan(i, 0, x));\n    return res;\n}\n\n\n\nint main() {\n//    freopen(\"input.txt\", \"r\", stdin);\n//    freopen(\"output.txt\", \"w\", stdout);\n\n    cin >> n >> m;\n    for (int i = 0; i < m; ++i) {\n        int u, v;\n        cin >> u >> v;\n        e[u].push_back(v);\n        ei[v].push_back(u);\n    }\n    \n    for (int i = 1; i <= n; ++i)\n        if (!b[i])\n            Dfs(i, 1);\n\n    if (cand == -1) {\n        cout << n << endl;\n        exit(0);\n    } else {\n        for (int i = cand; i >= 1; --i)\n            if (cand%i == 0 && Can(i)) {\n                cout << i << endl;\n                exit(0);\n            }\n    }\n\n    return 0;\n}",
    "tags": [
      "dfs and similar"
    ],
    "rating": 2200
  },
  {
    "contest_id": "183",
    "index": "D",
    "title": "T-shirt",
    "statement": "You are going to work in Codeforces as an intern in a team of $n$ engineers, numbered $1$ through $n$. You want to give each engineer a souvenir: a T-shirt from your country (T-shirts are highly desirable in Codeforces). Unfortunately you don't know the size of the T-shirt each engineer fits in. There are $m$ different sizes, numbered $1$ through $m$, and each engineer will fit in a T-shirt of exactly one size.\n\nYou don't know the engineers' exact sizes, so you asked your friend, Gerald. Unfortunately, he wasn't able to obtain the exact sizes either, but he managed to obtain for each engineer $i$ and for all sizes $j$, the probability that the size of the T-shirt that fits engineer $i$ is $j$.\n\nSince you're planning to give each engineer one T-shirt, you are going to bring with you exactly $n$ T-shirts. For those $n$ T-shirts, you can bring any combination of sizes (you can bring multiple T-shirts with the same size too!). You don't know the sizes of T-shirts for each engineer when deciding what sizes to bring, so you have to pick this combination based only on the probabilities given by your friend, Gerald.\n\nYour task is to maximize the expected number of engineers that receive a T-shirt of his size.\n\nThis is defined more formally as follows. When you finally arrive at the office, you will ask each engineer his T-shirt size. Then, if you still have a T-shirt of that size, you will give him one of them. Otherwise, you don't give him a T-shirt. You will ask the engineers in order starting from engineer $1$, then engineer $2$, and so on until engineer $n$.",
    "tutorial": "Dynamic Programming, Probabilities, and a little Greedy Suppose we have decided to bring N1 T-shirts of size 1, N2 T-shirts of size 2, ... NM T-shirts of size M. By the linearity of expectation, the expected number of engineers that will receive a T-shirt is equal to the sum of the expected number of engineers that will receive a T-shirt of size K, for all K. Suppose we bring Ni T-shirts of size i. Define a random variable Xij as the number of engineer that will receive the j-th T-shirt of size Ni that we bring. Hence, the expected number of engineers that will receive the Ni T-shirts of size i that we bring is equal to the sum of Xij over all j. Since Xij is either 0 or 1, Xij is equal to Pij, the probability that there will be an engineer that will receive the j-th T-shirt of size i that we bring. This is equal to the probability that there will be at least j engineers that fits inside T-shirt of size i. As a result of our discussion, to maximize the expectation, it boils to maximizing the sum over Xij. Hence, we receive our first solution: Calculate the value of all Xij, and pick the N largest value. A DP implementation allows us to accumulate all Xij value in O(N*N*M) time, yielding an O(N*N*M) solution. We will now reduce the time limit to O(N*N + N*M). Notice that the algorithm above only need us to find the N largest values of Xij. Denote by f(n, i, j) the probability that, amongst engineers numbere 1 through n, at least j of them fits inside T-shirt of size i. f(n, i, j) can be computed with the following recurrence: f(n, i, j) = f(n-1, i, j-1) * fit_chance(n, i) + f(n-1, i, j) * (1.0 - fit_change(n, i)) Where fit_chance(t-shirt, engineer) is the probability that engineer fits inside the t-shirt size. The formula above can be inferred from simple logic: if the n-th engineer fits inside t-shirt of size i (with fit_change(n, i) probability), then f(n, i, j) is obviously equal to f(n-1, i, j-1). Otherwise, it'll equal f(n-1, i, j). Now, observe that Xij = f(N, i, j). Indeed, this is one of the possible DPs that can lead to the O(N*N*M) solution. However, we will show that we do not need to compute f(n, i, j) for all possible inputs if we're asked to find only the N largest values of Xij. The key observation is the following obvious fact. If Xij is included in the N largest values, then Xi(j-1) must also be included there. Inductively, Xik for k < j must also be included in the N largest values. Indeed, it's obvious that Xij must be non-increasing with respect to j. Hence the algorithm works as follows. First, we create a pool of numbers Xi1, for all i, totalling M numbers. Then, we iterate N times. In each iteration, we pick the largest number in the pool, say, Xij. Then, we add Xij as one of the K largest values. Then, we take out Xij from the pool, and insert Xi(j+1) as its replacement. That it correctly picks the N largest Xij values follows immediately from our argument in the paragraph preceeding this. Now, if we use the recurrence f(n, i, j) above to compute each Xij, what is the complexity of this algorithm? If we memoize f(n, i, j), we claim that it's O(N*N + N*M). To see this, we notice that the only values required to compute f(n, i, j) using the recurrence above are the values f(m, i, l) such that m <= n and l <= j. However, we notice that due to how our algorithm works, when we need to compute Xij, we must have already computed Xi(j-1) before, so that all values f(m, i, l) for m <= n and l <= j-1 are already available. So the only NEW values that we need to compute are f(m, i, j), m <= n. There are n such values. Since we need to compute at most O(N) values of Xij, the total complexity this part contributes is O(N*N). Depending on how you implement the \"pick largest from pool\" algorithm, the total complexity can be either O(N*N + N*M) or O(N*N + N*log M). Yes, somebody did this in the contest :).",
    "code": "#include <stdio.h>\n#include <ctype.h>\n#include <iostream>\n#include <math.h>\n#include <string.h>\n#include <algorithm>\n#include <stdlib.h>\n#include <time.h>\n#include <queue>\n#include <set>\n#include <map>\n#include <string>\n#include <vector>\n#include <utility>\n#include <assert.h>\n\n#define MPI 3.141592653589793238462643\n#define eps 1e-8\n#define inf ((int)1e9)\n#define pb push_back\n#define mp make_pair\n\nusing namespace std;\n\nint n, m;\nlong double P[3100][310];\nlong double E[310][3100], S[310];\nlong double T[3100];\nlong double sum;\n\nint main()\n{\n  int i, j, id, tmp;\n  long double cv;\n  //freopen(\".in\", \"r\", stdin);\n  //freopen(\".out\", \"w\", stdout);\n  scanf(\"%d%d\", &n, &m);\n  for (i=0; i<n; i++)\n    for (j=0; j<m; j++)\n      scanf(\"%d\", &tmp), P[i][j]=((long double)tmp)/1000.0;\n  for (i=0; i<m; i++)\n  {\n    E[i][0]=1.0;\n    for (cv=E[i][0], j=1; j<=n; j++)\n      S[i]+=cv*P[j-1][i], cv*=(1.0-P[j-1][i]), cv+=E[i][j];\n    //cerr<<i<<\" \"<<S[i]<<endl;\n  }\n  //cerr<<n<<endl;\n  for (int ii=0; ii<n; ii++)\n  {\n    id=0;\n    for (j=1; j<m; j++)\n      if (S[id]<S[j])\n        id=j;\n    //cerr<<id<<\" \"<<S[id]<<endl;\n    sum+=S[id], memcpy(T,E[id],sizeof(T)), S[id]=0.0;\n    cv=E[id][0], E[id][0]=0.0;\n    for (j=1; j<=n; j++)\n      E[id][j]=cv*P[j-1][id], cv*=(1.0-P[j-1][id]), cv+=T[j];\n    for (cv=E[id][0], j=1; j<=n; j++)\n      S[id]+=cv*P[j-1][id], cv*=(1.0-P[j-1][id]), cv+=E[id][j];\n  } \n  printf(\"%.12lf\n\", (double)sum);\n  return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "183",
    "index": "E",
    "title": "Candy Shop",
    "statement": "The prestigious Codeforces kindergarten consists of $n$ kids, numbered $1$ through $n$. Each of them are given allowance in rubles by their parents.\n\nToday, they are going to the most famous candy shop in the town. The shop sells candies in packages: for all $i$ between $1$ and $m$, inclusive, it sells a package containing exactly $i$ candies. A candy costs one ruble, so a package containing $x$ candies costs $x$ rubles.\n\nThe kids will purchase candies in turns, starting from kid 1. In a single turn, kid $i$ will purchase one candy package. Due to the highly competitive nature of Codeforces kindergarten, during a turn, the number of candies contained in the package purchased by the kid will always be strictly greater than the number of candies contained in the package purchased by the kid in the preceding turn (an exception is in the first turn: the first kid may purchase any package). Then, the turn proceeds to kid $i + 1$, or to kid $1$ if it was kid $n$'s turn. This process can be ended at any time, but at the end of the purchase process, all the kids \\underline{must have the same number of candy packages}. Of course, the amount spent by each kid on the candies cannot exceed their allowance.\n\nYou work at the candy shop and would like to prepare the candies for the kids. Print the maximum number of candies that can be sold by the candy shop to the kids. If the kids cannot purchase any candy (due to insufficient allowance), print $0$.",
    "tutorial": "Very greedy Brute force P: the number of Packages each kid will have at the end. There are at most N/M possible such value. We will assume that P is fixed during our discussion. If we know P, we know that if kid i purchases a total of X candies, then kid i+1 must purchase at least X+P candies (1 more than each package purchased by kid i). Hence, assume that money[i] <= money[i+1] - P. Two consecutive packages purchased by the SAME kid must differ by at least M. Indeed, otherwise there are less than M-1 packages for the other M-1 kids to buy from (Pigeonhole rocks by the way). For the sake of our discussions below, we refer to the following example with N=8, and M=3 kids. The allowances of the kids are 7, 10, and 14. Suppose we know all candies kid 0 purchased (red bags denote the packages kid 0 purchased). We claim that the optimal solution can be computed rather... easily with the following greedy algorithm: (assume that the candy packages kid 0 purchase is sorted in an ascending order). We iterate over the remaining kids, starting from kid 1. First, let the kid purchase the minimum possible candies: Next, if the allowance is still greater than the sum of candies, and if one of his package(s) can still be shifted to the right while maintaining the condition that a possible solution exists, do so. If there are multiple package(s) that can be shifted, shifting any of them does not change the optimal answer. Note: since we've assumed that money[i] <= money[i+1]-P, the only condition is that between the package purchased by kid 1 an the next package purchased by kid 0, there exists at least N-2 packages. For instance, this is illegal, since there is no package that kid 2 will be able to purchase between 4 and 5. We iterate this once more for kid 2, obtaining: And we're done. It's arguably the maximum possible value, since there is no reason why we shouldn't shift a package for a kid to the right if we can (formal proof by contradiction). Claim: If we know the packages for kid 0, the maximum total candies purchased can be computed in O(M), where M is the number of kids. The algorithm simulates our discussion above. However it is not obvious how to do that in O(M). So, suppose kid 0 purchase the candies like this: Now, try putting the other P-1 packages into the minimum possible locations: The packages inside the yellow boxes denote what we will call FREEDOM. Basically FREEDOM is the count on how many times we can at most shift a package to the right as in our discussion above. Now, consider kid 1. First, as in our discussion, kid 1 takes the minimum amount of packages, which is equal to sum[kid 0] + P. Next, he will attempt to shift the packages if possible. Notice that the only thing that affects the overall sum of the candy is only the number of shifts performed, not which package actually got shifted. So, this means that, the amount of shift can be easily calculated by min(money[1] - (sum[kid 0] + P), FREEDOM). And then, FREEDOM is deducted from this value, while the amount of candies purchased by kid 1 is incremented by this value. Hence, simulating the algorithm in our discussion if we're only to output the total amount of candies can be done in O(M). The result of our discussion so far is this. Notice that the last algorithm only depends on how many candies kid 0 purchased, and FREEDOM. Now we will remove the assumption that we know which packages kid 0 decides to purchase. Claim: It is optimal for kid 0 to purchase as many candies as possible. Suppose kid 0 does not purchase the maximum possible of candies he can purchase. Now, consider whether or not kid 1 \"shifted\" his candies. If he shifted any of them, say package X, then instead of purchasing package X-1, kid 0 should purchase package X, improving the overall amount of candies. That is, instead of It's better to If kid 1 did not \"shift\" his candies because the amount of money he spent is already equal to his allowance, then the amount of candies purchased by kid 0 must be maximum since money[i] <= money[i+1] - P. Otherwise, we can apply this inductively to kid 2 and so forth. That is, instead of It's better to Okay, now we know the sum of candies that we should give to kid 1. Since the performance of our algorithm increase with FREEDOM, we should next try to maximize FREEDOM. Claim: FREEDOM depends only on the position of the FIRST candy package purchased by kid 0. This can be shown by simple computation, and its equal to N - pos - M*P (or something like that). Hence, we should try to minimize the first candy package purchased by kid 0, while keeping the sum maximum. This can be done in O(1) using a bunch of N*(N+1)/M * P formulas. Hence, since there are N/M package numbers to be brute forced, and each iteration uses O(M) time, the total complexity is O(N/M) * O(M) = O(N).",
    "code": "#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <deque>\n#include <queue>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <functional>\n#include <utility>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <cstdio>\n\nusing namespace std;\n\n#define REP(i,n) for((i)=0;(i)<(int)(n);(i)++)\n#define foreach(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)\n\ntypedef long long ll;\n\nint N;\nll a[200010];\nll M;\n\nll func(ll Amin, ll Bmax, ll mindiff, ll maxdiff){\n    int i;\n    \n    Bmax = min(Bmax, a[N-1]);\n    REP(i,N-1) Bmax = min(Bmax, a[i] - i * mindiff + maxdiff);\n    \n    ll ans = 0;\n    ll x = Bmax;\n    \n    for(i=N-1;i>=0;i--){\n        if(i != N-1) x -= mindiff;\n        x = min(x,a[i]);\n        if(x < Amin || Bmax - x > maxdiff) return -1;\n        ans += x;\n    }\n    \n    return ans;\n}\n\nint main(void){\n    int c,i;\n    \n    cin >> N >> M;\n    REP(i,N) cin >> a[i];\n    \n    ll ans = 0;\n    \n    for(c=1;c*N<=M;c++){\n        ll tri = (ll)c * (c-1) / 2 * N;\n        ll Amin = tri + c;\n        ll Bmax = M * c - tri;\n        ll mindiff = c;\n        ll maxdiff = M - c;\n        ll tmp = func(Amin, Bmax, mindiff, maxdiff);\n        ans = max(ans,tmp);\n    }\n    \n    cout << ans << endl;\n    \n    return 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "185",
    "index": "A",
    "title": "Plant",
    "statement": "Dwarfs have planted a very interesting plant, which is a triangle directed \"upwards\". This plant has an amusing feature. After one year a triangle plant directed \"upwards\" divides into four triangle plants: three of them will point \"upwards\" and one will point \"downwards\". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.\n\nHelp the dwarfs find out how many triangle plants that point \"upwards\" will be in $n$ years.",
    "tutorial": "Let's propose, that after the $i$-th year, there is $x$ triangles up and $y$ triangles down. After another iteration we can see, that amount of triangles became - $3x + y$ up and $x + 3y$ down. Let's see the difference between them: at the $i$-th it's $x - y$ and at the $i + 1$-th - it's $(3x + y) - (x + 3y) = 2 * (x - y)$. We can see, that difference between amount of triangles grown up by 2. Because on the $i$-th year the difference became $2^{i}$ and all amount of triangles is $4^{i}$. We can see, that on the $i$-th year the number of our triangles is $\\textstyle{\\frac{4+2^{2}}{2}}$. That can be computed by modulo p using the fast-power algorithm.",
    "tags": [
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "185",
    "index": "B",
    "title": "Mushroom Scientists",
    "statement": "As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates $(x, y, z)$. In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: $\\sqrt{x^{2}+y^{2}+z^{2}}$. Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals $x^{a}·y^{b}·z^{c}$.\n\nTo test the metric of mushroom scientists, the usual scientists offered them a task: find such $x, y, z$ $(0 ≤ x, y, z; x + y + z ≤ S)$, that the distance between the center of the Universe and the point $(x, y, z)$ is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.\n\nNote that in this problem, it is considered that $0^{0} = 1$.",
    "tutorial": "This problem was made by my love to inequalities. :-)! The answer for this problem is $\\left({\\frac{d\\S}{a+b+c}}\\colon{\\frac{b\\S}{a+b+c}}\\cdot{\\frac{c\\S}{a+b+c}}\\right)$. Prove: $x^{a}y^{b}z^{c}=a^{a}b^{b}c^{c}\\frac{a}{b}\\frac{\\bar{c}^{c}}{c}\\leq a^{a}b^{b}c^{c}(\\frac{a\\pi^{a}+b+c}{a+b+c}\\bar{c})^{a+b+c}=a^{a}b^{b}c^{c}(\\frac{s}{a+b+c})^{a+b+c}$. (This is AM-GM inequality. Link for whom don't know it.) The equality becomes only, when $\\underset{^{\\sim}}{a}=\\frac{y}{b}=\\frac{z}{c}$. And you should check on zeroes. If $a = b = c = 0$ - you can choose any good answer - $x + y + z  \\le  S$.",
    "tags": [
      "math",
      "ternary search"
    ],
    "rating": 1800
  },
  {
    "contest_id": "185",
    "index": "D",
    "title": "Visit of the Great",
    "statement": "The Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King.\n\nWe know that only $LCM(k^{2l} + 1, k^{2l + 1} + 1, ..., k^{2r} + 1)$ dwarves can see the Great Mushroom King. Numbers $k$, $l$, $r$ are chosen by the Great Mushroom King himself in some complicated manner which is unclear to common dwarves.\n\nThe dwarven historians decided to document all visits of the Great Mushroom King. For each visit the dwarven historians know three integers $k_{i}$, $l_{i}$, $r_{i}$, chosen by the Great Mushroom King for this visit. They also know a prime number $p_{i}$. Help them to count the remainder of dividing the number of dwarves who can see the King, by number $p_{i}$, for each visit.",
    "tutorial": "This is number theory problem. I'm trying to explain it step by step: 1) Let's prove, that LCD is maximum 2. Let $k^{2^{n}}+1\\dot{z}d\\Leftrightarrow k^{2^{n}}\\equiv\\!\\!d-1$. Squaring both sides we get $k^{2^{n+1}}\\equiv_{d}1\\stackrel{\\leftrightarrow}{\\leftrightarrow}k^{2^{n+1}}-1^{;}d$, but we want to $k^{2^{n+1}}+1;d$. This means, that $d$ can be only $2$. 2) Let's make this lenghty product simplier. $\\left(k^{2^{l}}+1\\right)\\cdot\\dots\\cdot\\left(k^{2^{r}}+1\\right)={\\frac{k^{2^{r+1}}-1}{k^{2^{\\prime}-1}}}$. We can count this by modulo $p$ fast, and divide it by $2^{r - l}$, if $k$ is odd. 3) There is many interesting things in this solution. Firstly, it doesn't work, when $p = 2$ - but it can easily done by you. The other problem is harder, what if $k^{2^{\\overset{n}{}}}-1\\mathbf{\\hat{}}p$, this means that for each $i  \\ge  l$ : $k^{2^{n}}-1;p$, and this mean, that for each $i  \\ge  l$ : $k^{2i} + 1  \\equiv  _{p}2$. And the product by modulo $p$ is equal to $2^{r - l + 1}$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "185",
    "index": "E",
    "title": "Soap Time! - 2",
    "statement": "Imagine the Cartesian coordinate system. There are $k$ different points containing subway stations. One can get from any subway station to any one instantly. That is, the duration of the transfer between any two subway stations can be considered equal to zero. You are allowed to travel only between subway stations, that is, you are not allowed to leave the subway somewhere in the middle of your path, in-between the stations.\n\nThere are $n$ dwarves, they are represented by their coordinates on the plane. The dwarves want to come together and watch a soap opera at some integer point on the plane. For that, they choose the gathering point and start moving towards it simultaneously. In one second a dwarf can move from point $(x, y)$ to one of the following points: $(x - 1, y)$, $(x + 1, y)$, $(x, y - 1)$, $(x, y + 1)$. Besides, the dwarves can use the subway as many times as they want (the subway transfers the dwarves instantly). The dwarves do not interfere with each other as they move (that is, the dwarves move simultaneously and independently from each other).\n\nHelp the dwarves and find the minimum time they need to gather at one point.",
    "tutorial": "This problem wasn't taken to ROI, because of that I gave it here. This is pretty hard problem. I can't now realize, what cerealguy wrote, but his solution is $O(nlogn)$ - without binary search. For me it's quite hard to understand, because my first solution was with binary search. And there were solutions, that has a worse asymptothic, but they run faster. Because of that I can only give you key ideas, that can help you. (afterwards you can see the code of cerealguy) Ideas: Let's find for each person the nearest subway point for them. It can be done in nlogn with use of segment tree or something else. We can see, that if one person goes to subway, the others, which distance to subway is smaller, can go to subway too - it doesn't affect the answer. Because of that we sort all persons by their distanse to subway. The area of the person, where he can come in $t$ seconds, is romb. And we can intersect all rombes in $O(n)$ - the intersection is like rectangle. Let's make the first intersection. When nobody goes to subway. We get a rectangle. The main idea, that for this rectangle - the nearest subway becomes always the same. We go throught people in sorted order, we can fast recalculate this small rectangle - and because of that we can fast recalculate the answer. And we get a solution in $O(nlogn)$ time.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 3000
  },
  {
    "contest_id": "186",
    "index": "A",
    "title": "Comparing Strings",
    "statement": "Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told \"no genome, no degree\". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.\n\nDwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.",
    "tutorial": "If the lengths of 2 strings aren't equal - that means \"NO\". We try to find the positions in strings, where chars are different. If there 1 or more than 2 such positions - \"NO\". After that we swap 2 characters in the first string, and check for their equality.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "186",
    "index": "B",
    "title": "Growing Mushrooms",
    "statement": "Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.\n\nEach mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts $t_{1}$ seconds and the second part lasts $t_{2}$ seconds. The first and the second part are separated by a little break.\n\nAfter the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of $v_{i}$ meters per second. After $t_{1}$ seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by $k$ percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of $u_{i}$ meters per second. After a $t_{2}$ seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.\n\nBefore the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds $a_{i}$ and $b_{i}$, then there are two strategies: he either uses speed $a_{i}$ before the break and speed $b_{i}$ after it, or vice versa.\n\nDwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.\n\nThe participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).",
    "tutorial": "We can see, that we can do all in integers, because k is integer number of percent. For each dwarf we should find his optimal strategy - to check 2 strategies with speed. We should sort them.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "187",
    "index": "A",
    "title": "Permutations",
    "statement": "Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.\n\nOne of the seniors gave Happy PMP a nice game. He is given two permutations of numbers $1$ through $n$ and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.\n\nHappy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.",
    "tutorial": "It is easy to see that if we replace each number in the first permutation with position of that number in the second permutation, the problem reduces to sorting the first permutation. Each time we take a number from the end of array, we can postpone its insertion until we know the most suitable position for insertion. Note that it is not good to insert a number and take it again, as we could make a better decision first time we took the number. So, as long as the remainder of the array is not in increasing order, we should take more numbers from the end. But as soon as you have an increasing subsequence, you can insert the numbers you have taken to make the array sorted. Therefore to solve the problem, we find the largest i such the numbers from 1 to i are in increasing order. The answer would be n-i.",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "187",
    "index": "B",
    "title": "AlgoRace",
    "statement": "PMP is getting a warrior. He is practicing a lot, but the results are not acceptable yet. This time instead of programming contests, he decided to compete in a car racing to increase the spirit of victory. He decides to choose a competition that also exhibits algorithmic features.\n\nAlgoRace is a special league of car racing where different teams compete in a country of $n$ cities. Cities are numbered $1$ through $n$. Every two distinct cities in the country are connected with one bidirectional road. Each competing team should introduce one driver and a set of cars.\n\nThe competition is held in $r$ rounds. In $i$-th round, drivers will start at city $s_{i}$ and finish at city $t_{i}$. Drivers are allowed to change their cars at most $k_{i}$ times. Changing cars can take place in any city in no time. One car can be used multiple times in one round, but total number of changes should not exceed $k_{i}$. Drivers can freely choose their path to destination.\n\nPMP has prepared $m$ type of purpose-built cars. Beside for PMP’s driving skills, depending on properties of the car and the road, a car traverses each road in each direction in different times.\n\nPMP Warriors wants to devise best strategies of choosing car and roads in each round to maximize the chance of winning the cup. For each round they want to find the minimum time required to finish it.",
    "tutorial": "First we solve the problem when the number of allowed car changes is zero (_k=0_). Let W(i,j,l) be the length of shortest path from i to j with car l. We use Floyd-Warshal on graph of each car to find this value. Then answer for the case that we can use only one car for each pair of cities i and j is: ans(0,i,j) = min W(i,j,l) for (_1 \\le l \\le m_) This part has time complexity O(m*n^3). For larger values of maximum number of changes (_k_), we use the following equation: ans(k,i,j) = min (ans(k-1,i,l)+ans(0,l,j)) for (_1 \\le l \\le k_) which can be computed in O(k*n^3) using dynamic programming. But how large can be k in worst case? We know that shortest paths are simple paths (i.e. they have no repeated vertices). Because otherwise we could eliminate the path we go between two appearances of one vertex and have a smaller result. This and the fact that we change the car at most once in each vertex, guarantees in any optimal solution we will not need more that n car changes. Thus the order of the solution would be O(m*n^3+n^4).",
    "tags": [
      "dp",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "187",
    "index": "C",
    "title": "Weak Memory",
    "statement": "\\underline{Zart PMP} is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.\n\nThe park has $n$ intersections numbered $1$ through $n$. There are $m$ bidirectional roads that connect some pairs of these intersections. At $k$ intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.\n\nWhen PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most $q$ intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most $q$ that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most $q$ intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.\n\nPMP's initial location is intersection $s$ and the buses are at intersection $t$. There will always be a volunteer at intersection $s$. Your job is to find out the minimum $q$ which guarantees that PMP can find the buses.",
    "tutorial": "There were many different correct approaches to this problem during the contest. But I will explain author's solution. First we can use binary search over the value of q. Now for a fixed q we want to check s-t connectivity. Let K be the set of all intersections with volunteers union s and t. One can use BFS from each k \\in K, one by one. Then build a graph G' with vertices K. For each two vertices k1,k2 \\in K add an edge between them, if their shortest distance is less than or equal to q. Finally use any path finding algorithm to check the connectivity. Unfortunately this solution has time (and space) complexity of O(|K|*m) which is not good enough. We can optimize the above solution by initiating BFS from all k \\in K at once. In other words during the initialization step in BFS algorithm, we push all these vertices in the queue with distance 0. Each element in the queue also maintains its source (i.e. the source it is originating from). In BFS each time we have have a vertex u with source su and we want to set the minimum distance to a vertex v that is already set from a different path with source sv, we connect su and sv in G' if d(u)+d(v)+1<= q, where d(x) denotes length of the shortest path from a vertex in K to x. As we are only dealing with connectivity, this approach is correct. (Proof of correctness is left as an exercise) BFS takes O(m) time and we add at most O(m) edges to G', so the overall complexity is O(m) for a fixed q. As we used binary search to find the smallest q, we can solve the problem in O(m*logn).",
    "tags": [
      "dfs and similar",
      "dsu"
    ],
    "rating": 2000
  },
  {
    "contest_id": "187",
    "index": "D",
    "title": "BRT Contract ",
    "statement": "In the last war of PMP, he defeated all his opponents and advanced to the final round. But after the end of semi-final round evil attacked him from behind and killed him! God bless him.\n\nBefore his death, PMP signed a contract with the bus rapid transit (BRT) that improves public transportations by optimizing time of travel estimation. You should help PMP finish his last contract.\n\nEach BRT line is straight line that passes $n$ intersecting on its ways. At each intersection there is traffic light that periodically cycles between green and red. It starts illuminating green at time zero. During the green phase which lasts for $g$ seconds, traffic is allowed to proceed. After the green phase the light changes to red and remains in this color for $r$ seconds. During the red phase traffic is prohibited from proceeding. If a vehicle reaches the intersection exactly at a time when the light changes to red, it should stop, but the vehicle is clear to proceed if the light has just changed to green.\n\nAll traffic lights have the same timing and are synchronized. In other words the period of red (and green) phase is the same for all of traffic lights and they all start illuminating green at time zero.\n\nThe BRT Company has calculated the time that a bus requires to pass each road segment. A road segment is the distance between two consecutive traffic lights or between a traffic light and source (or destination) station. More precisely BRT specialists provide $n + 1$ positive integers $l_{i}$, the time in seconds that a bus needs to traverse $i$-th road segment in the path from source to destination. The $l_{1}$ value denotes the time that a bus needs to pass the distance between source and the first intersection. The $l_{n + 1}$ value denotes the time between the last intersection and destination.\n\nIn one day $q$ buses leave the source station. The $i$-th bus starts from source at time $t_{i}$ (in seconds). Decision makers of BRT Company want to know what time a bus gets to destination?\n\nThe bus is considered as point. A bus will always move if it can. The buses do not interfere with each other.",
    "tutorial": "We define ti as follows: assume a bus starts moving from i-th intersection exactly at the time when the light changes to green. The time it takes for the bus to get the final station is ti. We call the times when a green interval begins t0 (so every g+r seconds t0 occurs once) If a bus gets to i-th intersection during the red phase, it should wait and then start moving at t0. So considering the fact that all lights are synchronized (and length of segments are fixed) if we have ti for i-th intersection, we can compute the time for the bus to get final station. Clearly tn is the length of the last segments. For computing ti we should find the smallest j such that if a bus starts at t0 from i-th intersection, it gets to j-th intersection during the red phase. So we have: ti=tj+d(i,j)+w where d(i,j) is the distance between i-th and j-th intersections and w is the time that the bus should wait behind the red light at j-th intersection. The later value can be computed easily. The only problem that remains is to find j for i-th intersection. So we start iterating over i for (n-1)-th intersection backwards and we compute ti for all intersections. Assume p=g+r and ta=d(i,j)%p. Now if the bus starts from i-th intersection at time t0 and we have ta>=g, in this case we are in red phase at j-th intersection. Actually ta should be in interval [_g, g+r_). Here we can use segment trees. That is for all intersections from i+1 to n, we store some values in the tree that helps us find the smallest j. But we should note the value of ta depends on d(i,j) which changes as i changes. Thus we cannot use ta in the tree. Instead, we define si the be the distance of i-th intersection to the destination. So we have d(i,j)=si-sj and we use the value of sj with storing -sj%p in the segment tree as the key and the value would be j itself. In other words for each intersection we store the key-value pair (-sj%p, j) in the tree. According to what we said so far, to be in the red phase at j-th intersection we should have: ta=(d(i,j)%p)=((si-sj)%p) \\in [g,g+r) => -sj%p  \\in  [(g-si)%p, (g+r-si)%p) As we stored -sj%p in the tree, we can retrieve the smallest j in the above interval with a query in the segment tree. This way we can compute ti for all intersections. Answering to each query in the problem can be solve in exactly the same way. So the overall complexity would be O((n+q)logn).",
    "tags": [
      "data structures"
    ],
    "rating": 2800
  },
  {
    "contest_id": "187",
    "index": "E",
    "title": "Heaven Tour",
    "statement": "The story was not finished as PMP thought. God offered him one more chance to reincarnate and come back to life. But before he can come back, God told him that PMP should ask $n$ great men including prominent programmers about their life experiences.\n\nThe men are standing on a straight line. They are numbered $1$ through $n$ from left to right. The coordinate of the $i$-th man is $x_{i}$ $(x_{i} < x_{i + 1}, i < n)$. PMP should visit all these people one by one in arbitrary order. Each men should be visited \\textbf{exactly once}. At the beginning of his tour, he starts at location of $s$-th man and asks him about his experiences.\n\nEach time PMP wants to change his location, he should give a ticket to an angel and the angel carries him to his destination. Angels take PMP from one location, fly to his destination and put him down there. Nobody else is visited in this movement. Moving from $i$-th man to $j$-th man, takes $|x_{i} - x_{j}|$ time. PMP can get back to life as soon as he visits all men.\n\nThere are two types of angels: Some angels are going to the right and they only accept right tickets. Others are going the left and they only accept left tickets. There are an unlimited number of angels of each type. PMP has $l$ left tickets and $n - 1 - l$ right tickets.\n\nPMP wants to get back to life as soon as possible to be able to compete in this year's final instead of the final he missed last year. He wants to know the quickest way to visit all the men exactly once. He also needs to know the exact sequence moves he should make.",
    "tutorial": "Step 1. Solve the problem if the starting man is the leftmost man and the finishing man is the rightmost man. Obviously every segment (the distance between two consecutive men) should be covered at least once. We also argue that at least l (the number of left tickets) segments should be covered at least three times. Proof: Each time you use a left ticket to go to man i with 1<i<n-1, the segment between i-th and (_i+1_)-th men is covered at least three times: Once for you should go after i be in a position to come back. Once for you use a left ticked to come back to i And once again you should go after i, because you want to finish at man number n Note that in the first and the last segments are always covered once, no matter what we do. But except for these two segments, every other segment can be chosen to be among the segments that are covered three times, and every combination that we choose l segments is feasible. (Proof it as practice) So we choose the smallest l segments and the problem can be solved with a simple sort in O(n*logn). Step 2. Solve the problem if the starting man is the leftmost man, but the finishing man can be anywhere. To solve this problem we first fix the finishing man. With reasoning similar to that of step 1, we conclude that at least l segments should be covered with at least two times if they are after the finishing man or three times if they are before him. But obviously every segment after the finishing man is covered at least two times. So it is always good to waste as many left tickets as possible after the finishing man to prevent them from breaching the left side of finishing man and becoming multiple three. So the algorithm would be: iterate over i, the number of finishing man, and maintain the l-(n-i) smallest segments to the right of finishing man as you progress. This can be implemented in O(n*logn). Step 3. Solve the problem if the starting man is fixed, but the finishing man can be anywhere. Assume that the starting man is not the first man or the last man, otherwise we could use algorithm of step 2 to solve the problem. Without loss of generality assume that you finish your tour to the right side of finishing man. Therefore every segment to the left of starting man is covered at least two times and actually it is always possible to arrange visits such that every segment to right is covered exactly two times. So just like what we said in step 2, it is good to waste as many left tickets as possible in this area. So the algorithm would be, choose to finish left or right first, then greedily waste as many bad moves (by bad moves I mean the moves that if breach to the other side will be more costly) as possible there and follow the algorithm in step 2 to solve the whole problem. There are some special cases such as when the tour cannot be finished at all, that we left to readers find a way how to handle them.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "189",
    "index": "A",
    "title": "Cut Ribbon",
    "statement": "Polycarpus has a ribbon, its length is $n$. He wants to cut the ribbon in a way that fulfils the following two conditions:\n\n- After the cutting each ribbon piece should have length $a$, $b$ or $c$.\n- After the cutting the number of ribbon pieces should be maximum.\n\nHelp Polycarpus and find the number of ribbon pieces after the required cutting.",
    "tutorial": "The problem is to maximize x+y+z subject to ax+by+cz=n. Constraints are low, so simply iterate over two variables (say x and y) and find the third variable (if any) from the second equation. Find the maximum over all feasible solutions. Other approaches: Use dynamic programming with each state being the remainder of ribbon. Select the next piece to be a, b or c.",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 1300
  },
  {
    "contest_id": "189",
    "index": "B",
    "title": "Counting Rhombi",
    "statement": "You have two positive integers $w$ and $h$. Your task is to count the number of rhombi which have the following properties:\n\n- Have positive area.\n- With vertices at integer points.\n- All vertices of the rhombi are located inside or on the border of the rectangle with vertices at points $(0, 0)$, $(w, 0)$, $(w, h)$, $(0, h)$. In other words, for all vertices $(x_{i}, y_{i})$ of the rhombus the following conditions should fulfill: $0 ≤ x_{i} ≤ w$ and $0 ≤ y_{i} ≤ h$.\n- Its diagonals are parallel to the axis.\n\nCount the number of such rhombi.\n\nLet us remind you that a rhombus is a quadrilateral whose four sides all have the same length.",
    "tutorial": "Observe that lots of rhombi have the same shape, but are in different locations. What uniquely determines the shape of a rhombus? Its width and its height. Is it possible to build a rhombus with every width and every height such that the vertices of the rhombus are in integer points? No, it is possible only if the width and the height are both even. How many places we can put a rhombus of width w0 and height h0 in a rectangle of width w and height h? (w * w0 + 1)(h * h0 + 1) So, iterator over all even widths and heights and for each of them add the number of possible locations to the final result.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "190",
    "index": "A",
    "title": "Vasya and the Bus",
    "statement": "One day Vasya heard a story: \"In the city of High Bertown a bus number 62 left from the bus station. It had $n$ grown-ups and $m$ kids...\"\n\nThe latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could have paid for the ride.\n\nThe bus fare equals one berland ruble in High Bertown. However, not everything is that easy — \\textbf{no more than one} child can ride for free with each grown-up passenger. That means that a grown-up passenger who rides with his $k$ $(k > 0)$ children, pays overall $k$ rubles: a ticket for himself and $(k - 1)$ tickets for his children. Also, a grown-up can ride without children, in this case he only pays one ruble.\n\nWe know that in High Bertown children can't ride in a bus unaccompanied by grown-ups.\n\nHelp Vasya count the minimum and the maximum sum in Berland rubles, that all passengers of this bus could have paid in total.",
    "tutorial": "Firstly, if $n = 0$, then children can't be in the bus, so if $m = 0$ then the answer is $(0, 0)$, otherwise the answer is $\"Impossible\"$. Now $n > 0$. If $m = = 0$, than it is only one possible variant of passage - the answer is $(n, n)$. Otherwise, more grown-up take some children, less the sum that people pay. So, if only one adult takes all children, than we get maximal sum - $n + m - 1$. Maximum $min(n, m)$ adults can take the children with them, so the minimal answer is $n + m - min(n, m) = max(n, m)$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "190",
    "index": "B",
    "title": "Surrounded",
    "statement": "So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation.\n\nRight now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city — that's the strategy the flatlanders usually follow when they besiege cities.\n\nThe berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most $r$ from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most $r$). Then the radar can immediately inform about the enemy's attack.\n\nDue to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius $(r)$ is, the more the radar costs.\n\nThat's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius $r$ $(r ≥ 0)$ such, that a radar with radius $r$ can be installed at some point and it can register \\textbf{the start of the movements} of both flatland rings from that point.\n\nIn this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range — as a disk (including the border) with the center at the point where the radar is placed.",
    "tutorial": "Let's find the minimum distance between two circles $L$. Then the answer to our problem is $L / 2$. Now $d$ is the distance between the centers of the circles, $R$, $r$ - their radiuses. There are 3 possible cases: - Circles don't intersect. Then $L = d - R - r$. Firstly, it's reachable: let's consider the segment, connecting the centers of the circles, and take its part, which is out of both circles - its length is exactly $d - R - r$. Let's prove that lesser distance is impossible. If the segment connecting two points of distinct circles have length l, than $R + l + r > = d$, so $l > = d - R - r$. - If one circle is into another, than analogically the answer is $R - d - r$, where $R$ is the radius of the bigger circle. - If the circles intersect, then the answer is 0.",
    "tags": [
      "geometry"
    ],
    "rating": 1800
  },
  {
    "contest_id": "190",
    "index": "C",
    "title": "STL",
    "statement": "Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.\n\nWe all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.\n\nVasya is not a programmer, so he asked his friend Gena, what the convenient way to store $n$ integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a \"type\" is in language X--:\n\n- First, a type is a string \"int\".\n- Second, a type is a string that starts with \"pair\", then followed by angle brackets listing \\textbf{exactly two} comma-separated other types of language X--. This record contains no spaces.\n- No other strings can be regarded as types.\n\nMore formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.\n\nGena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores $n$ integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.\n\nHelp Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.",
    "tutorial": "In this problem we have an array of strings $(s_{1}, s_{2}, ...s_{n})$, where $s_{i}$ $= pair$ or $int$. Let's consider $bal_{i}$ = the difference between number of \"pair\" and \"int\" int the subarray $(s_{1}, s_{2}, ...s_{i})$. Than we can prove that the type can be reestablished from the array $s$ $< = >$ $bal_{i} > = 0$ for $1 < = i < n$ and $bal_{n} = - 1$. This can be proved using mathematical induction, the parameter is the number of $\"int\"$-s in the array. And how to find the solution, if we know that is exists? Consider the function $gettype(inti)$, which builds the type beginning in the position $i$ and returns the index, next to the position where it finished building of type. How it works? If $s_{i} =$ $\"int\"$, then the function prints $\"int\"$ and returns $i + 1$. Else it prints $\"pair < \"$, $gettype(i + 1)$ is launched, let it returns $j$. Then we print $\", \"$ and launch $gettype(j)$ (it returns $k$), then we print $\" > \"$ and return $k$. We can not to do check if the type can be reestablished from the array in the beginning: launch $gettype()$ and print \"Error occurred\" if there became some contradiction during the building of type.",
    "tags": [
      "dfs and similar"
    ],
    "rating": 1500
  },
  {
    "contest_id": "190",
    "index": "D",
    "title": "Non-Secret Cypher",
    "statement": "Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.\n\nThe captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number $m$, the enemies use an array of integers $a$. The number of its subarrays, in which there are at least $k$ equal numbers, equals $m$. The number $k$ has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.\n\nHelp Vasya, given an array of integers $a$ and number $k$, find the number of subarrays of the array of numbers $a$, which has at least $k$ equal numbers.\n\nSubarray $a[i... j] (1 ≤ i ≤ j ≤ n)$ of array $a = (a_{1}, a_{2}, ..., a_{n})$ is an array, made from its consecutive elements, starting from the $i$-th one and ending with the $j$-th one: $a[i... j] = (a_{i}, a_{i + 1}, ..., a_{j})$.",
    "tutorial": "First solution: Let's use the method of two pointers. For every number we will know how many times it occurs in the current segment $[l, r]$. For fixed $l$ we increase $r$ until $a[r]$ occurs in the current segment less than $k$ times. If $a[r]$ occurs int the segment $[l, r]$ $k$ times, we add to the answer all segments $[l, t]$ for all $t > = r$ and increase $l$ (and do not forget to decrease the number of $a[l]$ in the current segment). To keep the number of every value in the segment we can use $map$ or compression of the coordinates. Also it's important not to forget that the maximal answer is $\\textstyle{\\frac{n(n+1)}{2}}$, which doesn't fit in $int$. Second solution: firstly, let's do the compression of the coordinates. For every value $X$ we write the list of the positions $i$ such that $a[i] = X$. Now using that we fill the array $b$: $b[i]$ is the minimum index that segment $[i, b[i]]$ contains $k$ numbers equal to $a[i]$ (obviosly, $a[b[i]] = a[i]$), if this index doesn't exist, then $b[i] = n + 1$. Let's find for every index $i$ a minimal index $j$ such that segment $[i, j]$ contsins $k$ equal numbers (if such $j$ doesn't exist, we say that $j = n + 1$) - then we add to the answer $n + 1 - j$. This $j$ is equal to $\\operatorname*{min}_{k=i,\\ldots n}b_{k}$. All that minimums can be found in a single pass through $a$ from its end. Then we can sum the answers for all indexes $1 < = i < = n$. The complexity of these solutions is $O(nlogn)$.",
    "tags": [
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "190",
    "index": "E",
    "title": "Counter Attack",
    "statement": "Berland has managed to repel the flatlanders' attack and is now starting the counter attack.\n\nFlatland has $n$ cities, numbered from $1$ to $n$, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them.\n\nThe berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the \\textbf{actual} roads. Also the cities from different groups are unreachable from each other, moving along the \\textbf{actual} roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once!\n\nHelp the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them.",
    "tutorial": "This problem has several different solutions. Anyway, we should consider towns as the vertices of the graph, roads as its edges. Now we are to find the connected components of the complementary graph (CG) of the given graph. Let's take the vertex $A$ with the minimal degree $c$: $c<={\\frac{m}{n}}$. We call the set of the vertices who are connected with $A$ - $B$, that are not connected - $D$ . All vertices which don't connect with $A$ will be in the same connected component of the CG. Let's build the complemented graph to the subgraph including $A$ and set $B$ - there are $O({\\frac{m}{n}})$ vertices and $O({\\frac{\\mu-\\mu}{n\\,n}})$ $=$ $O(m\\cdot{\\frac{m}{n n}})$ $=$ $O(m)$ edges. Let's build DSU for the vertices of given graph and merge components which we have found using the new-built graph. All that we should do after it is to consider vertices from $B$: now we look to the vertex $v$. We put $v$ in the same component as $A$ if $v$ has edges not to all vertices of $D$ (we do it using DSU too). The complexity of this solution is $O(m)$ or $O(mlogn)$. Another solution: we keep $set$ $a$, which contains vertices, which haven't been visited yet. Let's run series of bfs to find the components of CG. If we are working now with the vertex $v$, pass through $a$. Consider $u$ is the element of $a$. If edge $(u, v)$ isn't in the given graph, than $u$ is in the same component of CG as $v$, so, we can erase it from $a$ and add to queue. Otherwise, we do nothing. What is the complexity of this solution? To understand that, we must know how many times whe consider fixed vertex $u$ in the $set$ $a$. $u$ remains int $a$ when we run to them from vertex $v$ $< = >$ edge $(u, v)$ is in the given graph. So, every vertex $u$ remains in $a$ no more than its degree. So, the complexity of this algorithm is $O(mlogn)$ (log n because of binsearch - we need use it to know, is $(u, v)$ in the graph). If we use $HashMap$, we'll get $O(m)$.",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "hashing",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "193",
    "index": "A",
    "title": "Cutting Figure",
    "statement": "You've gotten an $n × m$ sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as $A$. Set $A$ is connected. Your task is to find the minimum number of squares that we can delete from set $A$ to make it not connected.\n\nA set of painted squares is called connected, if for every two squares $a$ and $b$ from this set there is a sequence of squares from the set, beginning in $a$ and ending in $b$, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.",
    "tutorial": "Main idea: using the fact that the answer cannot be greater than 2, check answer 1. Let's proof that the answer is not greater than 2. Let area of the figure be greater than 3. Let's examine the leftmost of all topmost squares. There is no neighbors left or up to it. So, number of its neighbors is not more than 2. Thus, if we delete its neighbors, we shall disconnect the figure. If the area is equal to 3, we always can disconnect the figure by deletion of one square. It can be proofed by considering all two primary cases. If the area is not greater than 2, there is no way to disconnect the figure. The algorithm: Check answer 1. We can simply brute-force the square to delete, and for each instance start dfs from any existing square. If during the dfs we visited not all of the remaining squares, we have found the square to delete. The answer is 1 if our bruteforce succeeded, and 2 otherwise. That was necessary to consider the case when there is no answer. The complexity of the described algorithm is $O(n^{4})$. That was possible to search for articulation points and solve the problem in complexity $O(n^{2})$, but in my opinion that required more time and effort.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "193",
    "index": "B",
    "title": "Xor",
    "statement": "John Doe has four arrays: $a$, $b$, $k$, and $p$. Each array consists of $n$ integers. Elements of all arrays are indexed starting from $1$. Array $p$ is a permutation of integers $1$ to $n$.\n\nJohn invented a game for his friends and himself. Initially a player is given array $a$. The player must consecutively execute exactly $u$ operations on $a$. You are permitted to execute the following operations:\n\n- Operation 1: For each $i\\in\\{1,2,\\dots,n\\}$ change $a_{i}$ into $a_{i}\\oplus b_{i}$. Expression $x\\oplus y$ means applying the operation of a bitwise xor to numbers $x$ and $y$. The given operation exists in all modern programming languages, for example, in language C++ and Java it is marked as \"^\", in Pascal — as \"xor\".\n- Operation 2: For each $i\\in\\{1,2,\\dots,n\\}$ change $a_{i}$ into $a_{pi} + r$. When this operation is executed, all changes are made at the same time.\n\nAfter all $u$ operations are applied, the number of points the player gets is determined by the formula $s=\\textstyle\\sum_{i=1}^{i\\geq n}a_{i}k_{i}$.\n\nJohn wants to find out what maximum number of points a player can win in his game. Help him.",
    "tutorial": "Main idea: bruteforce in complexity $O(F_{u}n)$ where $F_{u}$ if fibonacci number at position $u$. This problem had complex statements. We have an array $a$, and we can transform it in two ways. The goal was to maximize the sum of all its elements with given multipliers after exactly $u$ operations. A simple bruteforce of all combinations of operations with subsequent modeling leads to complexity $O(2^{u} * nu)$, what is not fast enough. That was possible to optimize it by modeling parallel to recursive bruteforce. Now we have complexity $O(2^{u}n)$. Actually, the correct solution is not too far from this algorithm. There is just one conjecture: every two successive xor operations change nothing, and we can move them to any place of the combination. Thus, it will be enough to bruteforce only combinations in which every pair of successive xor operations is at the end. It could be done using recoursive bruteforce. We must change in previous solution two things. First, we must n't put xor after xor. Besides that, we should update answer if number $u - l$ is even, where $l$ is current level of recoursion (all remaining operations in the end separates to pairs of xors). Let's calculate complexity of this algo. There are $F_{i}$ sequences of length $i$ without two consecutive xors. It's easy to proof, you can calculate some dp to see it. That's why, complexity of our algo is $O(F_{u}n)$.",
    "tags": [
      "brute force"
    ],
    "rating": 2000
  },
  {
    "contest_id": "193",
    "index": "C",
    "title": "Hamming Distance",
    "statement": "Hamming distance between strings $a$ and $b$ of equal length (denoted by $h(a, b)$) is equal to the number of distinct integers $i$ $(1 ≤ i ≤ |a|)$, such that $a_{i} ≠ b_{i}$, where $a_{i}$ is the $i$-th symbol of string $a$, $b_{i}$ is the $i$-th symbol of string $b$. For example, the Hamming distance between strings \"aba\" and \"bba\" equals $1$, they have different first symbols. For strings \"bbba\" and \"aaab\" the Hamming distance equals $4$.\n\nJohn Doe had a paper on which four strings of equal length $s_{1}$, $s_{2}$, $s_{3}$ and $s_{4}$ were written. Each string $s_{i}$ consisted only of lowercase letters \"a\" and \"b\". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.\n\nHelp John restore the strings; find some four strings $s'_{1}$, $s'_{2}$, $s'_{3}, s'_{4}$ of equal length that consist only of lowercase letters \"a\" and \"b\", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set $s'_{i}$ must satisfy the condition $\\forall i,j\\in\\{1,2,3,4\\},h(s_{i},s_{j})=h(s_{i}^{\\prime},s_{j}^{\\prime})$.\n\nTo make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of \\textbf{minimum length}.",
    "tutorial": "Main idea: reduction to system of linear equations and solving it using Gauss algorithm. Let's notice that order of columns in answer doesn't matter. That's why there is only one important thing - quantity of every type of column. There is only $2^{4} = 16$ different columns. Let's represent Hamming distance between every pair of strings as sum of quantities of types of columns. It's possible because every column adds to every distance between pairs $0$ or $1$. Now we have system of 6 linear equations with 16 variables. It's not good, let's decrease number of variables. First, some columns adds same values to every Hamming distance. For example strings \"abbb\" and \"baaa\". For every column $q$ we can replace all letters \"a\" by letters \"b\" and all letters \"b\" by letters \"a\" and reach column that adds same values to every distance. We reduced number of variables to 8. We also can notice that columns \"aaaa\" and \"bbbb\" is useless and reduce number of variables to 7. This system can be solved using Gauss algorithm. One variable steel be free. Let's fix it. It's value can't be more than maximum of $h(s_{i}, s_{j})$ because column adds positive value to one or more Hamming distance. For every fixed value we should check if all variables take non-negative integer value and choose the best answer. We can solve system of equations in integers because coefficients of equation is little. Complexity of this solution if $O(max(h(s_{i}, s_{j})))$. If we solve it in rational numbers complexity will change to $O(m a x(h(s_{i},s_{i}))\\cdot\\log A n s)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "193",
    "index": "D",
    "title": "Two Segments",
    "statement": "Nick has some permutation consisting of $p$ integers from $1$ to $n$. A segment $[l, r]$ ($l ≤ r$) is a set of elements $p_{i}$ satisfying $l ≤ i ≤ r$.\n\nNick calls a pair of segments $[a_{0}, a_{1}]$ and $[b_{0}, b_{1}]$ ($1 ≤ a_{0} ≤ a_{1} < b_{0} ≤ b_{1} ≤ n$) good if all their $(a_{1} - a_{0} + b_{1} - b_{0} + 2)$ elements, when sorted in ascending order, form an arithmetic progression with a difference of $1$. That is, when they sorted in ascending order, the elements are in the form ${x, x + 1, x + 2, ..., x + m - 1}$, for some $x$ and $m$.\n\nYour task is to find the number of distinct pairs of good segments in the given permutation. Two pairs of segments are considered distinct if the sets of elements contained in these pairs of segments are distinct. For example, any segment $[l, r]$ $(l < r)$ can be represented as a pair of segments, as $[l, i]$ and $[i + 1, r]$ ($l ≤ i ≤ r$). As all these pairs consist of the same set of elements, they are considered identical.\n\nSee the notes accompanying the sample tests for clarification.",
    "tutorial": "Main idea: inverse the permutation and solve simplified problem (see below), consider function \"quantity of segments of permutation that form the given segment of natural series\". In order to solve this problem, we suggest solve another: <<we have a permutation $p_{n}$, we have to calculate the count of segments such that their elements form one or two segments of natural series>>. If we solve the inverse problem for some permutation $q_{n}$ such that $\\forall i(q_{p_{i}}=i)$, we shall get the answer for the initial problem and initial permutation $p_{i}$. Straight-forward algo: let's bruteforce the segment of permutation and mark its elements in a boolean array. Check that in that array there is not more than two marked segments. This algo has complexity $O(n^{3})$. Let's notice that during the changeover from $[l, r]$ to $[l, r + 1]$ the quantity of segments changes in some predictable way. Let $s([a, b])$ be quantity of segments that form segment $[a, b]$ of permutation. There are three cases (see picture below): If the new element $p_{r + 1}$ is between two marked elements (that is, both elements with values $p_{r + 1} - 1$ and $p_{r + 1} + 1$ belong to segment $[l, r]$), then $s([l, r + 1]) = s([l, r]) - 1$. The new element will <> the segments near it. If the new element $p_{r + 1}$ has only one neighbor with value belonging to $[l, r]$, then $s([l, r + 1]) = s([l, r])$. The new element will lengthen one of existing segments. If there are no marked elements near $p_{r + 1}$ the new element forms a new segment, $s([l, r + 1]) = s([l, r]) + 1$. The new element is red, elements that are marked to this moment are black. Improved algo: Let's bruteforce position of the left border and for each instance move the right border from left to right. During each move we shall recount the actual quantity of segments forming the current segment of permutation ($s([l, r])$). Now we have a solution in complexity $O(n^{2})$. It works fast enough even when $n = 20000$. Obviously, that is not enough to get AC. Move on full solution. It is based on previous. Now we can calc $s([l, r])$ using $s([l, r - 1])$. Now we should look at way of changing $s([l - 1, r])$ as compared with $s([l, r])$. Let's move left border of segment from the right to left and support some data structure with $s([l, i])$ for every $i$ satisfying $l < i  \\le  n$ and current $l$. This structure should answer queries \"count numbers 1 and 2 in structure\", that is count segments $[l, i]$ that generates one or two segments in the original permutaton. Let $ \\Delta _{i}$ be $s([l - 1, i]) - s([l, i])$. $ \\Delta _{l}$ will be equal to $1$ because one element form one segment in permutation (notice that in final answer we must not consider 1-element segments, that's why we must subtract $n$ from answer in the end of solution). $ \\Delta _{i}$ determined by the number of neighbors of element $l - 1$ in the segment $[l - 1, i]$. Neighbors of $l - 1$ is elements $p_{l - 1} + 1$ and $p_{l - 1} - 1$ if they're exist. If $l - 1$ hasn't neighbors in this segment, $ \\Delta _{i} = 1$, because $l - 1$ froms new 1-element segment. If $l - 1$ has one neighbor in this segment $ \\Delta _{i} = 0$, because $l - 1$ join to existing segment of its neighbor. If $l - 1$ has two neighbors in this segment $ \\Delta _{i} = - 1$, because $l - 1$ connect segments of its neighbors. Number of neighbors in segment $[l - 1, i]$ non-decreasing with increasing $i$. That's why $ \\Delta _{i}$ non-decreasing with increasing $i$. That means that there are only three segments of equivalence of $ \\Delta _{i}$. We are interested only in neighbors of $l - 1$ which positions are right than $l - 1$. Let $a$ is position of first neighbor, $b$ is position of second neighbor, without loss of generality $a < b$. Then $\\forall i\\in[l,a-1]\\Delta_{i}=1$, $\\forall i\\in[a,b-1]\\Delta_{i}=0$, $\\forall i\\in[b,n-1]\\Delta_{i}=-1$. (elements of permutation are numbered from 0). If $a$ and $b$ aren't exist, for all $i\\in[l,n-1]$ $ \\Delta _{i} = 1$. If only $b$ isn't exist for $i\\in[l,a-1]\\Delta_{i}=1$, for $i\\in[a,n-1]\\Delta_{i}=0$. Look at example to clear your understanding. ($ \\Delta _{i}$ is in top right corners, $l = 3, p_{l} = 5$) Using this facts we can code data structure support following operations: Add +1 or -1 on segment Calc number of 1 and 2 in the structure. Sum of answers of structure in every iteration (for every $l$) is answer to problem. Let's notice that all numbers in structure will be positive. That's why elements 1 and 2 will be minimal of pre-minimal in the structure. Using this fact we can code segment tree, supports these operations. Complexity of this solution is $O(n\\log n)$. We also can code sqrt-decomposition and obtain complexity $O(n{\\sqrt{n}})$.",
    "tags": [
      "data structures"
    ],
    "rating": 2900
  },
  {
    "contest_id": "193",
    "index": "E",
    "title": "Fibonacci Number",
    "statement": "John Doe has a list of all Fibonacci numbers modulo $10^{13}$. This list is infinite, it starts with numbers $0$ and $1$. Each number in the list, apart from the first two, is a sum of previous two modulo $10^{13}$. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by $10^{13}$.\n\nJohn got interested in number $f$ ($0 ≤ f < 10^{13}$) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number $f$ in the list or otherwise state that number $f$ does not occur in the list.\n\nThe numeration in John's list starts from zero. There, the $0$-th position is the number $0$, the $1$-st position is the number $1$, the $2$-nd position is the number $1$, the $3$-rd position is the number $2$, the $4$-th position is the number $3$ and so on. Thus, the beginning of the list looks like this: $0, 1, 1, 2, 3, 5, 8, 13, 21, ...$",
    "tutorial": "Main idea: baby-step-giant-step. In this problem we had some Fibonacci number modulo $10^{13}$ $f$, and we had to determine the position of its first occurence in Fibonacci sequence modulo $10^{13}$. Let $a$ and $b$ be two different coprime modula - divisors of $10^{13}$. Let $F$ be the actual Fibonacci number such that $F\\mathrm{\\mod\\10^{13}}=f$. Then $f\\ \\ \\mathrm{mod}\\ a=F\\ \\mathrm{mod}\\ a$ and $f\\mod b=F\\,\\mod b$. Find all occurences of number $f{\\mathrm{~mod~}}a$ in Fibonacci sequence modulo $a$ period. Find all occurences of number $f\\mod b$ in Fibonacci sequence modulo $b$ period. Let's fix a pair of such occurences. Let the occurence modulo $a$ be in position $i$, and the occurence modulo $b$ be in position $j$. Let $t(m)$ be Fibonacci sequence modulo $m$ period. From the Chinese Remainder Theorem, it follows that $t(ab) = LCM(t(a), t(b))$ (remember that $a$ and $b$ are coprime). Then from fixed occurences of $f$ in periods of sequences modulo $a$ and $b$ we can recover the position of occurence of $f$ in period of sequence modulo $ab$. It could be done by solving the following Diophantine equation: $i + t(a) * x = j + t(b) * y$. We can solve it using a simple bruteforce of one of the roots. If the occurence in sequence modulo $ab$ period ( we have just found it) is $u$, then every occurence $f$ in Fibonacci sequence modulo $10^{13}$ period can be represented as $t(ab) * k + u$. Then let's bruteforce $k$ and find all occurences in sequence modulo $10^{13}$ period. To determine Fibonacci number on position $ \\alpha  + t(ab)$ from known Fibonacci number on position $ \\alpha $, we need to multiply the vector ($F_{ \\alpha }, F_{ \\alpha  + 1}$) and some matrix. Let's choose $a = 5^{9}$ and $b = 2^{13}$. Note that there is no number that occur Fibonacci sequence modulo $a$ or $b$ period more than $8$ times. That means that total count of pairs will never be greater than $64$. For each occurence we'll bruteforce not more than $\\frac{t(10^{13})}{L C M(t(5^{9}),t(2^{13}))}$ numbers. That was the author's solution. Also that was possible to use the fact that for any number the count of its occurences in period of sequence modulo $10^{p}$ (for any natural $p$) is not big more efficiently. From occurences in sequence modulo $10^{i}$ period we could get occurences in sequence modulo $10^{i + 1}$ period using the method we use to jump from modulus $ab$ to modulus $10^{13}$.",
    "tags": [
      "brute force",
      "math",
      "matrices"
    ],
    "rating": 2900
  },
  {
    "contest_id": "194",
    "index": "A",
    "title": "Exams",
    "statement": "One day the Codeforces round author sat exams. He had $n$ exams and he needed to get an integer from $2$ to $5$ for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark $2$.\n\nThe author would need to spend too much time and effort to make the sum of his marks strictly more than $k$. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than $k$, the author's mum won't be pleased at all.\n\nThe Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams.\n\nHelp the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all $n$ exams equal exactly $k$.",
    "tutorial": "Let's notice that $2n  \\le  k  \\le  5n$. If $k < 3n$ author has to get $2$ on some exams. There are $3n - k$ such exams and that's the answer). If $3n  \\le  k$ author will pass all exams (answer is $0$).",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "194",
    "index": "B",
    "title": "Square",
    "statement": "There is a square painted on a piece of paper, the square's side equals $n$ meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks $(n + 1)$ meters, he draws a cross (see picture for clarifications).\n\nJohn Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw?\n\n\\begin{center}\n{\\scriptsize The figure shows the order in which John draws crosses for a square with side $4$. The lower left square has two crosses. Overall John paints $17$ crosses.}\n\\end{center}",
    "tutorial": "Let the pencil move by the line and put crosses through every $(n + 1)$ point. Lets associate every point on the line with point on square perimeter. Namely, point $x$ on the line will be associated with point on square perimeter that we will reach if we move pencil around square to $x$ clockwise. Then lower left corner will be associated with all points $4np$ for every non-negative integer $p$. Crosses will be associated with points $k(n + 1)$ for some non-negative $k$. Nearest point of overlap of two families of points will be in point LCM($n + 1$, $4n$). Then we will put $\\frac{L C M\\left(n+1,4n\\right)}{n+1}\\ +\\ 1$ crosses.",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "195",
    "index": "A",
    "title": "Let's Watch Football",
    "statement": "Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will \"hang up\" as the size of data to watch per second will be more than the size of downloaded data per second.\n\nThe guys want to watch the whole video without any pauses, so they have to wait some \\textbf{integer} number of seconds for a part of the video to download. After this number of seconds passes, they can start watching. Waiting for the whole video to download isn't necessary as the video can download after the guys started to watch.\n\nLet's suppose that video's length is $c$ seconds and Valeric and Valerko wait $t$ seconds before the watching. Then for any moment of time $t_{0}$, $t ≤ t_{0} ≤ c + t$, the following condition must fulfill: the size of data received in $t_{0}$ seconds is not less than the size of data needed to watch $t_{0} - t$ seconds of the video.\n\nOf course, the guys want to wait as little as possible, so your task is to find the minimum integer number of seconds to wait before turning the video on. The guys must watch the video without pauses.",
    "tutorial": "The whole video will be downloaded in $all = (c \\cdot a + b - 1) / b$ seconds. In this problem you can choose every $1 < = t < = all$ as an answer. To fulfill coditions of the problem it is enough to check the condition $t0 \\cdot b > = (t0 - t) \\cdot a$ at the moment of time t0 = all.",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "195",
    "index": "B",
    "title": "After Training",
    "statement": "After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has $n$ balls and $m$ baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from $1$ to $m$, correspondingly. The balls are numbered with numbers from $1$ to $n$.\n\nValeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which ${\\bigg|}{\\frac{m+1}{2}}-i{\\bigg|}$ is minimum, where $i$ is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.\n\nFor every ball print the number of the basket where it will go according to Valeric's scheme.\n\nNote that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.",
    "tutorial": "In this problem you should carefully implement the given process. Firstly note that ball number $i > m$ will be in the same basket as ball number $i - m$. Therefore it is enough to distribute first $m$ balls. It can be done using two pointers $lf$, $rg$ from the middle. Alternately put one ball to the left and to the right and shift pointers. In only case you should shift left pointer twice in the first moment of time if $m$ is odd.",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "195",
    "index": "C",
    "title": "Try and Catch",
    "statement": "Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.\n\nThe exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:\n\n- The try operator. It opens a new try-catch-block.\n- The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.\n\nThe exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.\n\nLet's suggest that as a result of using some throw operator the program created an exception of type $a$. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type $a$ as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message \"Unhandled Exception\".\n\nTo test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.\n\nYour task is: given a program in VPL, determine, what message will be displayed on the screen.",
    "tutorial": "In this problem you was to implement what was writen in the statement. In my solution I did the following. Erase all spaces from the text except spaces in messages in try-catch blocks. Then when we get word \"try\" we put number of the new try-catch block in stack. When we get word \"throw\" we remember it's type and current state of stack (that is what try-catch blocks are opened). For example, put these number in set. When we get word \"catch\" if it's type equals to type of operator \"throw\" and the number of current try-catch block is in your set then write the answer now else erase this try-catch block from stack. If there was no suitable try-catch block write \"Unhandled Exception\".",
    "tags": [
      "expression parsing",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "195",
    "index": "D",
    "title": "Analyzing Polyline",
    "statement": "As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.\n\nLet's consider a set of functions of the following form:\n\n\\[\ny_{i}(x)=\\left\\{k_{i}\\cdot x+b_{i},\\quad{\\mathrm{if~}}k_{i}\\cdot x+b_{i}\\geq0;\\quad\\mathrm{o;}\n\\]\n\nLet's define a sum of $n$ functions $y_{1}(x), ..., y_{n}(x)$ of the given type as function $s(x) = y_{1}(x) + ... + y_{n}(x)$ for any $x$. It's easy to show that in this case the graph $s(x)$ is a polyline. You are given $n$ functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph $s(x)$, that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.",
    "tutorial": "In fact in this problem we were given lines $y_{i} = k_{i} * x + b_{i}$ but negative values were replaced by zero. Your task was to find the number of angles that do not equal 180 degrees in the graph s(x), that is the sum of the given functions. Firstly note that sum of two lines is also line. Indeed $y = y_{1} + y_{2}$ is $y = k_{1} * x + b_{1} + k_{2} * x + b_{2} = (k_{1} + k_{2}) * x + (b_{1} + b_{2})$. Consider points where $y_{i} = 0$, that is $x_{i} = - b_{i} / k_{i}$. While we assume that $k_{i}$ doesn't equal to 0. Then line number $i$ is divided in two lines one of which identically equals to 0. Consider all different points $x_{i}$ and sort them. Then, obviously, the sum of the given functions between two consecutive points is line. Find the equation of the line. Assume that we consider point $i$ from the left. Then equation of the line between points $i$ and $i + 1$ will not be equal to equation of the line between points $i$ and $i - 1$. That is in point $i$ is formed an angle that doesn't equal 180 degrees. So we should find equations of lines between every pair of points $i$ and $i + 1$. It can be easily done using two arrays with queries of increasing value on the interval offline.",
    "tags": [
      "geometry",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "195",
    "index": "E",
    "title": "Building Forest",
    "statement": "An oriented weighted forest is an acyclic weighted digraph in which from each vertex at most one edge goes.\n\nThe root of vertex $v$ of an oriented weighted forest is a vertex from which no edge goes and which can be reached from vertex $v$ moving along the edges of the weighted oriented forest. We denote the root of vertex $v$ as $root(v)$.\n\nThe depth of vertex $v$ is the sum of weights of paths passing from the vertex $v$ to its root. Let's denote the depth of the vertex $v$ as $depth(v)$.\n\nLet's consider the process of constructing a weighted directed forest. Initially, the forest does not contain vertices. Vertices are added sequentially one by one. Overall, there are $n$ performed operations of adding. The $i$-th $(i > 0)$ adding operation is described by a set of numbers $(k, v_{1}, x_{1}, v_{2}, x_{2}, ... , v_{k}, x_{k})$ and means that we should add vertex number $i$ and $k$ edges to the graph: an edge from vertex $root(v_{1})$ to vertex $i$ with weight $depth(v_{1}) + x_{1}$, an edge from vertex $root(v_{2})$ to vertex $i$ with weight $depth(v_{2}) + x_{2}$ and so on. If $k = 0$, then only vertex $i$ is added to the graph, there are no added edges.\n\nYour task is like this: given the operations of adding vertices, calculate the sum of the weights of all edges of the forest, resulting after the application of all defined operations, modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "The longest operation in this problem is to find the root of some vertex and the sum of the path to this root. To find these values fast we will use compression ways heuristics which is used in data structure \"disjoint-set-union\". For every vertex v we keep two values : $c[v]$ and $sum[v]$. $c[v] = v$, if $v$ - root, else $c[v]$ - next vertex on path from $v$ to root. $sum[v]$ = sum of lengths of edges on path from $v$ to $c[v]$. To add new edge from $u$ to $v$ of length $w$ it is enough to do $c[u] = v$ and $sum[u] = w$. Note that we only add new edges (we don't erase edges). That is, if we find $root(v)$ and $depth(v)$ for some vertex $v$ we can assign $c[v] = root(v)$, Unable to parse markup [type=CF_TEX] time. The approximate implementation is shown below. int root(int v){ if(c[v] == v){ return v; }else{ int u = root(c[v]); sum[v] = (sum[c[v]] + sum[v]) % M; c[v] = u; return u; } } It can proved that such implementation works using $O(log(n))$ time for every query. The complexity of the solution is $O(n * log(n))$.",
    "tags": [
      "data structures",
      "dsu",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "196",
    "index": "A",
    "title": "Lexicographically Maximum Subsequence",
    "statement": "You've got string $s$, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.\n\nWe'll call a non-empty string $s[p_{1}p_{2}... p_{k}] = s_{p1}s_{p2}... s_{pk}(1 ≤ p_{1} < p_{2} < ... < p_{k} ≤ |s|)$ a subsequence of string $s = s_{1}s_{2}... s_{|s|}$.\n\nString $x = x_{1}x_{2}... x_{|x|}$ is lexicographically larger than string $y = y_{1}y_{2}... y_{|y|}$, if either $|x| > |y|$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{|y|} = y_{|y|}$, or exists such number $r$ $(r < |x|, r < |y|)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters in lines are compared like their ASCII codes.",
    "tutorial": "Solution is greedy. First, write all 'z' letters (if there is any) - answer must contain them all for sure. Now it's time for 'y' letters. We can use only those of them which are on the right of last used 'z' letter. Then write 'x' letters - they must be on the right of the last used 'y' and 'z' letters. And so on.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "196",
    "index": "B",
    "title": "Infinite Maze",
    "statement": "We've got a rectangular $n × m$-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell $(x, y)$ is a wall if and only if cell $(x{\\mathrm{~mod~}}n,y{\\mathrm{~mod~}}m)$ is a wall.\n\nIn this problem $a{\\mathrm{~mod~}}b$ is a remainder of dividing number $a$ by number $b$.\n\nThe little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell $(x, y)$ he can go to one of the following cells: $(x, y - 1)$, $(x, y + 1)$, $(x - 1, y)$ and $(x + 1, y)$, provided that the cell he goes to is not a wall.",
    "tutorial": "Answer is \"Yes\" iff there are two distinct, reachable from start position cells, which correspond to same cell in initial labyrinth. Proof: If these cells exist, move to first of them, and infinitely repeat moves leading from first to second. On the contrary, if infinite far path exist, on this path we obviously can find such cells. How to find out if they exist? Start DFS from initial cell. For each cell visited, let $visit[x%n][y%m] = (x, y)$. Now, if DFS tries to go to cell $(x, y)$, $visit[x%n][y%m]$ contains something, and $(x, y)  \\neq  visit[x%n][y%m]$, we found these cells: they are $(x, y)$ and $visit[x%n][y%m]$. Notice that DFS will visit no more than $nm + 1$ cells (Dirichlet's principle). So the asymptotic is $O(nm)$.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "196",
    "index": "C",
    "title": "Paint Tree",
    "statement": "You are given a tree with $n$ vertexes and $n$ points on a plane, no three points lie on one straight line.\n\nYour task is to paint the given tree on a plane, using the given points as vertexes.\n\nThat is, you should correspond each vertex of the tree to exactly one point and each point should correspond to a vertex. If two vertexes of the tree are connected by an edge, then the corresponding points should have a segment painted between them. The segments that correspond to non-adjacent edges, should not have common points. The segments that correspond to adjacent edges should have exactly one common point.",
    "tutorial": "No three points are in the same line, so the solution always exists. First, choose any one vertex as the root of tree. Find size of each subtree using dfs. Then, we can build the answer recursively. Put the root of tree to the most lower left point. Sort all other points by angle relative to this lower left point. Let us name the sizes of subtrees of the root as $s_{1}$, $s_{2}$, ..., $s_{k}$. Run the algorithm recursively, giving first $s_{1}$ points (in sorted order) for the first subtree of root, next $s_{2}$ points for the second subtree and so on. Obviously, no two edges from different subtrees can intersect now. At each step of recursion we are to put the root of current subtree to the first point in sorted-by-angle order, and then sort other points by angle relative to it. So, no two subtrees will have any intersecting edges. The asymptotic of solution is $O(N^{2}\\log N)$.",
    "tags": [
      "constructive algorithms",
      "divide and conquer",
      "geometry",
      "sortings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "196",
    "index": "D",
    "title": "The Next Good String",
    "statement": "In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to $d$.\n\nYou are given string $s$, consisting only of lowercase English letters. Find a good string $t$ with length $|s|$, consisting of lowercase English letters, which is lexicographically larger than $s$. Of all such strings string $t$ must be lexicographically minimum.\n\nWe will call a non-empty string $s[a ... b] = s_{a}s_{a + 1}... s_{b}$ $(1 ≤ a ≤ b ≤ |s|)$ a substring of string $s = s_{1}s_{2}... s_{|s|}$.\n\nA non-empty string $s = s_{1}s_{2}... s_{n}$ is called a palindrome if for all $i$ from $1$ to $n$ the following fulfills: $s_{i} = s_{n - i + 1}$. In other words, palindrome read the same in both directions.\n\nString $x = x_{1}x_{2}... x_{|x|}$ is lexicographically larger than string $y = y_{1}y_{2}... y_{|y|}$, if either $|x| > |y|$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{|y|} = y_{|y|}$, or there exists such number $r$ $(r < |x|, r < |y|)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters in such strings are compared like their ASCII codes.",
    "tutorial": "464B - Restore Cube",
    "tags": [
      "data structures",
      "greedy",
      "hashing",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "196",
    "index": "D",
    "title": "The Next Good String",
    "statement": "In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to $d$.\n\nYou are given string $s$, consisting only of lowercase English letters. Find a good string $t$ with length $|s|$, consisting of lowercase English letters, which is lexicographically larger than $s$. Of all such strings string $t$ must be lexicographically minimum.\n\nWe will call a non-empty string $s[a ... b] = s_{a}s_{a + 1}... s_{b}$ $(1 ≤ a ≤ b ≤ |s|)$ a substring of string $s = s_{1}s_{2}... s_{|s|}$.\n\nA non-empty string $s = s_{1}s_{2}... s_{n}$ is called a palindrome if for all $i$ from $1$ to $n$ the following fulfills: $s_{i} = s_{n - i + 1}$. In other words, palindrome read the same in both directions.\n\nString $x = x_{1}x_{2}... x_{|x|}$ is lexicographically larger than string $y = y_{1}y_{2}... y_{|y|}$, if either $|x| > |y|$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{|y|} = y_{|y|}$, or there exists such number $r$ $(r < |x|, r < |y|)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters in such strings are compared like their ASCII codes.",
    "tutorial": "Notice, that only palindromes with length $d$ and $d + 1$ matter. Any palindrome with greater length contains one of them. Let's call these palindromes bad. First, find leftmost position $pos$, in which we surely should increase value of symbol. If there are no bad subpalindromes, $pos = |s| - 1$, else $pos$ is leftmost position amongst all ends of bad palindromes. Increase $s[pos]$. Increase it more, while $s[pos]$ is end of bad subpalindrome. If you try increase 'z' symbol, you should proceed to increasing previous symbol. If this way you reached situation when you need to increase first symbol, and it is 'z', answer is \"Impossible\". Now, let pos be position of leftmost changed symbol. We know, that prefix $s[0..pos]$ doesn't contain bad palindromes. Now we can greedily fill suffix $s[pos + 1..length(s) - 1]$: go over positions $i$ in ascending order, assign $s[i]$ = 'a', and increase it, while $s[i]$ is end of bad palindrome. Obviously, any of suffix symbols will be 'a', 'b' or 'c'. So we got algorithm, which requires fast implementation of next operations - assigning single symbol, and query: is given substring palindrome? You can perform this operations using hashes and Fenwick tree. Let's learn, how to get hash of substring in dynamically changing string. If we can it, we will keep string $s$ and it's reversed copy. For query of second type we just need to compare hashes of substring in $s$ and hash of corresponding substring in reversed copy. Let Fenwick tree store values $h[i] = s[i]P^{i}$, where $P$ is the prime number used for hashing. Then hash of substring $s[L..R]$ equals to $(h[L] + h[L + 1] + ...h[R])P^{ - L}$. For assigning $s[i] = c$, add value $(c - s[i])P^{i}$ to $h[i]$. Both these operations Fenwick tree does in $O(\\log N)$.",
    "tags": [
      "data structures",
      "greedy",
      "hashing",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "196",
    "index": "E",
    "title": "Opening Portals",
    "statement": "Pavel plays a famous computer game. A player is responsible for a whole country and he can travel there freely, complete quests and earn experience.\n\nThis country has $n$ cities connected by $m$ bidirectional roads of different lengths so that it is possible to get from any city to any other one. There are portals in $k$ of these cities. At the beginning of the game all portals are closed. When a player visits a portal city, the portal opens. Strange as it is, one can teleport from an open portal to an open one. The teleportation takes no time and that enables the player to travel quickly between rather remote regions of the country.\n\nAt the beginning of the game Pavel is in city number $1$. He wants to open all portals as quickly as possible. How much time will he need for that?",
    "tutorial": "First of all, we can note that if each graph vertex is portal, the answer will be a sum of all edges' weights in MST (minimal spanning tree). We can find MST by using Kruskal's algo. In this problem, not an every vertex is portal. Let's fix this. Start with a precalculation. Run Dijkstra's algo from all the portals, simultaneously. We will get $d[i]$ - a distance between vertex $i$ and $p[i]$ - the nearest portal to vertex $i$. Let's trace Kruskal's algo on a graph of portals. On the first iteration, it will choose the edge with the minimal cost, i.e. a shortest path between all the portals in the original graph. Let the path leads from portal $x$ to portal $y$. Note that there exists a path with the same length such as $p[i]$ changes only once through it. Indeed, $p[x] = x$, $p[y] = y$, i.e. $p[i]$ changed on the path. If it happens on edge $i\\rightarrow j\\,$, $p[i] = x$, a path $\\overline{{{\\cal T}}}\\rightarrow\\L_{++}\\rightarrow\\bar{\\cal l}^{'}\\rightarrow\\L_{++}\\rightarrow\\L_{+}\\rightarrow\\L_{+}\\rightarrow\\L\\bar{\\cal U}\\big|\\bar{\\cal J}\\big|$ will not be longer than the path from $x$ to $y$. As $p[i] = x$ and $p[i] = y$, we can see that the length of this path will be $d[i] + w(i, j) + d[j]$, where $w(i, j)$ is the weight of edge $(i, j)$. Kruskal's algo will add this value to the answer and merge portals $x$ and $y$. The shortest-path trees of vertexes $x$ and $y$ will also be merged. Note, that almost nothing changed. The next edge for Kruskal's algo can be find in a similar way - $\\operatorname*{min}_{i,j}d[i]+w(i,j)+d[j]$. If this edge connects $x$ and $y$ again, DSU makes us not to count this edge, otherwise this edge connects a different pair of edges and will be counted in an answer. We can easily implement this. Just create a new graph of portals, with an edge $(p[i], p[j])$ of weight $d[i] + w(i, j) + d[j]$ for every edge $(i, j)$ of weight $w(i, j)$ from original graph and run Kruskal's algo. Finally, note that if the starting vertex is not a portal, we shall add $d[1]$ to the answer.",
    "tags": [
      "dsu",
      "graphs",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "197",
    "index": "A",
    "title": "Plate Game",
    "statement": "You've got a rectangular table with length $a$ and width $b$ and the infinite number of plates of radius $r$. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the table's border. During the game one cannot move the plates that already lie on the table. The player who cannot make another move loses. Determine which player wins, the one who moves first or the one who moves second, provided that both players play optimally well.",
    "tutorial": "If first player can't make first move (table is too small and plate doesn't fit it, i.e. $2r > min(a, b)$), second player wins. Else first player wins. Winning strategy for first player: place first plate to the center of table. After that he symmetrically reflects moves of second player with respect to center of table. If second player has move, first player has symmetrical move, too. If not, first player won.",
    "tags": [
      "constructive algorithms",
      "games",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "197",
    "index": "B",
    "title": "Limit",
    "statement": "You are given two polynomials:\n\n- $P(x) = a_{0}·x^{n} + a_{1}·x^{n - 1} + ... + a_{n - 1}·x + a_{n}$ and\n- $Q(x) = b_{0}·x^{m} + b_{1}·x^{m - 1} + ... + b_{m - 1}·x + b_{m}$.\n\nCalculate limit $\\operatorname*{lim}_{x\\to+\\infty}{\\frac{P(x)}{Q(x)}}$.",
    "tutorial": "From math lessons we know, that only higher degrees of polinomials matter in this problem. If denominator degree is larger than numenator degree, answer is \"0/1\". If numenator degree is larger, answer is infinity. But what is sign of this infinity? To get it consider signs of highest degree factors of polinomials. If they are same, answer is positive infinity, else - negative infinity. If degrees of numenator and denominator are equal, answer is ${\\frac{a_{0}}{b_{\\mathrm{U}}}}$. To get irreducible fraction, you should divide this numbers by $gcd(a_{0}, b_{0})$. And don't forget that denominator of answer must be positive.",
    "tags": [
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "200",
    "index": "A",
    "title": "Cinema",
    "statement": "The capital of Berland has the only movie theater in the country. Besides, it consists of only one room. The room is divided into $n$ rows, each row consists of $m$ seats.\n\nThere are $k$ people lined up to the box office, each person wants to buy exactly one ticket for his own entertainment. Before the box office started selling tickets, each person found the seat that seemed best for him and remembered it as a pair of coordinates $(x_{i}, y_{i})$, where $x_{i}$ is the row number, and $y_{i}$ is the seat number in this row.\n\nIt is possible that some people have chosen the same place, then when some people see their favorite seat taken in the plan of empty seats in the theater, they choose and buy a ticket to another place. Each of them has the following logic: let's assume that he originally wanted to buy a ticket to seat $(x_{1}, y_{1})$, then when he comes to the box office, he chooses such empty seat $(x_{2}, y_{2})$, which satisfies the following conditions:\n\n- the value of $|x_{1} - x_{2}| + |y_{1} - y_{2}|$ is minimum\n- if the choice is not unique, then among the seats that satisfy the first condition, this person selects the one for which the value of $x_{2}$ is minimum\n- if the choice is still not unique, among the seats that satisfy the first and second conditions, this person selects the one for which the value of $y_{2}$ is minimum\n\nYour task is to find the coordinates of a seat for each person.",
    "tutorial": "In this problem were given the field, which size is $n  \\times  m$, and $k$ queries. Each query is the cell of the field. You had to find closest free cell for given one (there was used manhattan metric). Than found cell was marked as used. The time complexity of the solution is supposed to be $O(k \\cdot \\sqrt{k})$. Firstly, we show the main idea, than we show why solution has time complexity $O(k \\cdot \\sqrt{k})$. First of all, if $n > m$, than rotate matrix by 90 degrees (than we explain purpose of this transformation). We will have two matrices, size of each is $n  \\times  m$. In this matrices we will maintain for each cell the nearest free one to the left and to the right. Suppose we have query - cell $(x, y)$. Iterate $d$ - how much rows we will go above or below. Suppose we fix $d$, than look at the row $x - d$, for example (also we should do same things for row $x + d$). Lets find in this row nearest free cells to the left and to the right of $(x - d, y)$ by using our matrices and try to update answer. When $d$ will be greater than current found answer we will stop, because answer won't update in this case. After we find the answer, we have to change value in some cells of our matrices. It can be done by using structure DSU for each row. Lets show why this solution has time complexity $O(k \\cdot \\sqrt{k})$. Suppose all queries are equal, for example each query is $(x, y)$. Than if field is big enough, all points will be placed in form of square, which is rotated by 45 degrees and have center in point $(x, y)$. Also the side of the square will have length $\\sqrt{k}$. Than diagonal will have length $O({\\sqrt{k}})$ too. It means that we see $O({\\sqrt{k}})$ rows in each query and we do $O(1)$ operations in each row. If the square doesn't fit into the field, than field is too thin verticaly or horizontaly. So we will have figure looks like rectangle, and one side of this rectangle will be less than $\\sqrt{k}$. In this case rotate field so, than least side of rectangle means rows. Than we will see not greater than $\\sqrt{k}$ rows in each query and will perform not greater than $O(1)$ operations in each row. This problem is supposed to be the hardest problem of the contest.",
    "tags": [
      "brute force",
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "200",
    "index": "B",
    "title": "Drinks",
    "statement": "Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are $n$ drinks in his fridge, the volume fraction of orange juice in the $i$-th drink equals $p_{i}$ percent.\n\nOne day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the $n$ drinks and mixed them. Then he wondered, how much orange juice the cocktail has.\n\nFind the volume fraction of orange juice in the final drink.",
    "tutorial": "This problem was the easiest problem of the contest. There you had to find average of the given numbers. The most participants solved this problem.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "200",
    "index": "C",
    "title": "Football Championship",
    "statement": "Any resemblance to any real championship and sport is accidental.\n\nThe Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship:\n\n- the team that kicked most balls in the enemy's goal area wins the game;\n- the victory gives 3 point to the team, the draw gives 1 point and the defeat gives 0 points;\n- a group consists of four teams, the teams are ranked by the results of six games: each team plays exactly once with each other team;\n- the teams that get places 1 and 2 in the group stage results, go to the next stage of the championship.\n\nIn the group stage the team's place is defined by the total number of scored points: the more points, the higher the place is. If two or more teams have the same number of points, then the following criteria are used (the criteria are listed in the order of falling priority, starting from the most important one):\n\n- the difference between the total number of scored goals and the total number of missed goals in the championship: the team with a higher value gets a higher place;\n- the total number of scored goals in the championship: the team with a higher value gets a higher place;\n- the lexicographical order of the name of the teams' countries: the country with the lexicographically smaller name gets a higher place.\n\nThe Berland team plays in the group where the results of 5 out of 6 games are already known. To be exact, there is the last game left. There the Berand national team plays with some other team. The coach asks you to find such score $X$:$Y$ (where $X$ is the number of goals Berland scored and $Y$ is the number of goals the opponent scored in the game), that fulfills the following conditions:\n\n- $X$ > $Y$, that is, Berland is going to win this game;\n- after the game Berland gets the 1st or the 2nd place in the group;\n- if there are multiple variants, you should choose such score $X$:$Y$, where value $X - Y$ is minimum;\n- if it is still impossible to come up with one score, you should choose the score where value $Y$ (the number of goals Berland misses) is minimum.",
    "tutorial": "In this problem was given description of the group stage of some football competition and scoring system. There were given results of all matches, excepting one, and you had to find result of the last match, satisfied some given criterias. Also Berland's team must be first or the second team of the group after than match. Lets note, that in each finished match were not greater than 18 goals. It means that we can brute-force all results of the last match, when score is not greater than 200 goals, and find the best one. One of the easiest way is to fill table to the end (it means to change points value and balls value), than to sort teams according to the given rules and to check that Berland is the first or the second team of the group.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "200",
    "index": "D",
    "title": "Programming Language",
    "statement": "Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, default values).\n\nValery decided to examine template procedures in this language in more detail. The description of a template procedure consists of the procedure name and the list of its parameter types. The generic type T parameters can be used as parameters of template procedures.\n\nA procedure call consists of a procedure name and a list of variable parameters. Let's call a procedure suitable for this call if the following conditions are fulfilled:\n\n- its name equals to the name of the called procedure;\n- the number of its parameters equals to the number of parameters of the procedure call;\n- the types of variables in the procedure call match the corresponding types of its parameters. The variable type matches the type of a parameter if the parameter has a generic type T or the type of the variable and the parameter are the same.\n\nYou are given a description of some set of template procedures. You are also given a list of variables used in the program, as well as direct procedure calls that use the described variables. For each call you need to count the number of procedures that are suitable for this call.",
    "tutorial": "In this task were given the list of template functions. Each function have its name and the list of types of arguments (also it can be used universal type). Also there were given set of variables and thier types, and some queries. Each query is function, which has name and list of arguments. For each query you had to find, how many functions from the given list fit to the function from query. There fit means that functions have the same name, same number of arguments and types of all arguments also equal. For solving this problem it is needed to implement comparing of functions. Constrains gave the possibility to brute-force function from the given list and check if the names and arguments of functions are equal.",
    "tags": [
      "binary search",
      "brute force",
      "expression parsing",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "200",
    "index": "E",
    "title": "Tractor College",
    "statement": "While most students still sit their exams, the tractor college has completed the summer exam session. In fact, students study only one subject at this college — the Art of Operating a Tractor. Therefore, at the end of a term a student gets only one mark, a three (satisfactory), a four (good) or a five (excellent). Those who score lower marks are unfortunately expelled.\n\nThe college has $n$ students, and oddly enough, each of them can be on scholarship. The size of the scholarships varies each term. Since the end-of-the-term exam has just ended, it's time to determine the size of the scholarship to the end of next term.\n\nThe monthly budget for the scholarships of the Tractor college is $s$ rubles. To distribute the budget optimally, you must follow these rules:\n\n- The students who received the same mark for the exam, should receive the same scholarship;\n- Let us denote the size of the scholarship (in roubles) for students who have received marks $3$, $4$ and $5$ for the exam, as $k_{3}$, $k_{4}$ and $k_{5}$, respectively. The values $k_{3}$, $k_{4}$ and $k_{5}$ must be integers and satisfy the inequalities $0 ≤ k_{3} ≤ k_{4} ≤ k_{5}$;\n- Let's assume that $c_{3}$, $c_{4}$, $c_{5}$ show how many students received marks $3$, $4$ and $5$ for the exam, respectively. The budget of the scholarship should be fully spent on them, that is, $c_{3}·k_{3} + c_{4}·k_{4} + c_{5}·k_{5} = s$;\n- Let's introduce function $\\begin{array}{r}{\\int\\left({\\frac{k}{k_{3}}},{\\dot{k}}_{4},{\\dot{k}}_{5}\\right)=\\left|c_{9}\\cdot{\\dot{k}}_{3}-c_{4}\\cdot{\\dot{k}}_{4}\\right|+\\left|c_{4}\\cdot{\\dot{k}}_{4}-{\\dot{c}}_{5}\\cdot{\\dot{k}}_{5}\\right|$ — the value that shows how well the scholarships are distributed between students. In the optimal distribution function $f(k_{3}, k_{4}, k_{5})$ takes the \\textbf{minimum} possible value.\n\nGiven the results of the exam, and the budget size $s$, you have to find the optimal distribution of the scholarship.",
    "tutorial": "In this problem were given four integer numbers $c_{3}, c_{4}, c_{5}, s$. You had to find $0  \\le  k_{3}  \\le  k_{4}  \\le  k_{5}$ such, that $c_{3} \\cdot k_{3} + c_{4} \\cdot k_{4} + c_{5} \\cdot k_{5} = s$ and $|c_{3} \\cdot k_{3}-c_{4} \\cdot k_{4}| + |c_{4} \\cdot k_{4}-c_{5} \\cdot k_{5}|$ is minimal. Firstly, brute-force $k_{4}$ so, that $s-c_{4} \\cdot k_{4}  \\ge  0$. Than look at 4 cases, according to the sign of the value in each modulus. Lets see the case, when $c_{3} \\cdot k_{3}-c_{4} \\cdot k_{4}  \\ge  0$ and $c_{4} \\cdot k_{4}-c_{5} \\cdot k_{5}  \\ge  0$. Than we have to minimize $c_{3} \\cdot k_{3}-c_{5} \\cdot k_{5}$. Also $0  \\le  k_{3}  \\le  k_{4}  \\le  k_{5}$ and $c_{3} \\cdot k_{3} + c_{5} \\cdot k_{5} = s-c_{4} \\cdot k_{4}$. Lets see diofant equation $c_{3} \\cdot k_{3} + c_{5}... k_{5} = s-c_{4} \\cdot k_{4}$. It can be that this equation doesn't have solution. Lets see the case, when equation has solution. As $c_{3}, c_{5}  \\ge  0$, than for minimization $c_{3} \\cdot k_{3}-c_{5} \\cdot k_{5}$ we have to minimize $k_{3}$ and maximize $k_{5}$. All solutions of diofant equation $c_{3} \\cdot k_{3} + c_{5} \\cdot k_{5} = s-c_{4} \\cdot k_{4}$ can be described by using one argument $k$. Than we have to find such segment, that for all $k$ from it, $k_{3}$ will fit above constrains, such segment, that for all $k$ from it, $k_{5}$ will fit above constrains, find intersection of this segments and, if intersection isn't empty, choose such $k$, that $k_{5}$ is maximal. Similar you have to manage remain 3 cases and choose optimal values $k_{3}$ and $k_{5}$ for fixed $k_{4}$. Also you can note, that in all cases minimized function is linear and in segment it has minimal value in one of its ends. So we can only find such segments, that for all $k$ from that segments $k_{3}, k_{5}$ will fit above constrains, and calculate answer in the ends of this segments. If for all fixed $k_{4}$ diofant equation doesn't have solution, or intersections of the described segments are empty, than answer is $IMPOSSIBLE$, else we should find the best. So the time complexity is $O(s \\cdot log(s))$ - brute-force of $k_{4}$ and solving diofant equation for fixed $k_{4}$.",
    "tags": [
      "implementation",
      "math",
      "number theory",
      "ternary search"
    ],
    "rating": 2400
  },
  {
    "contest_id": "201",
    "index": "A",
    "title": "Clear Symmetry",
    "statement": "Consider some square matrix $A$ with side $n$ consisting of zeros and ones. There are $n$ rows numbered from $1$ to $n$ from top to bottom and $n$ columns numbered from $1$ to $n$ from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the $i$-row and the $j$-th column as $A_{i, j}$.\n\nLet's call matrix $A$ \\underline{clear} if no two cells containing ones have a common side.\n\nLet's call matrix $A$ \\underline{symmetrical} if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair $(i, j)$ $(1 ≤ i, j ≤ n)$ both of the following conditions must be met: $A_{i, j} = A_{n - i + 1, j}$ and $A_{i, j} = A_{i, n - j + 1}$.\n\nLet's define the \\underline{sharpness} of matrix $A$ as the number of ones in it.\n\nGiven integer $x$, your task is to find the smallest positive integer $n$ such that there exists a clear symmetrical matrix $A$ with side $n$ and sharpness $x$.",
    "tutorial": "It's interesting that originally the authors had an idea not to include the $x = 3$ case into pretests. Imagine the number of successful hacking attempts in this contest -- considering the fact that none of the first $43$ solutions to this problem passed pretests :) Note that the sought $n$ is always an odd number. Indeed, if $n$ is even, then two central rows of matrix $A$ must contain zeroes, otherwise there will exist two neighbouring cells containing ones. Similar restriction applies to two central columns of matrix $A$. Replacing two central rows with just one and two central columns with just one and leaving zeroes in them, we'll obtain a smaller matrix with the same sharpness. Note that the sharpness of a matrix with side $n$ can't exceed $\\frac{n^2 + 1}{2}$. It's easy to see that it's possible to lay out $\\textstyle{\\frac{n^{2}-1}{2}}$ \"domino pieces\" $1$ by $2$ without intersections on a field with side $n$ (in other words, all cells except one can be divided into pairs so that each pair contains neighbouring cells). Then there can be at most one one in the cells under each \"domino piece\" in the corresponding matrix. Therefore, the total number of ones doesn't exceed $n^{2}-{\\frac{n^{2}-1}{2}}={\\frac{n^{2}+1}{2}}$. Note that a matrix with side $n$ and sharpness $\\frac{n^2 + 1}{2}$ exists for an odd $n$. Paint all cells of the matrix in chess order and put ones into black cells and zeroes into white cells. It's easy to see that such a matrix is both clear and symmetrical and has sharpenss exactly $\\frac{n^2 + 1}{2}$. Intuitively it seems that if there exists a matrix with sharpness $\\frac{n^2 + 1}{2}$ there should also exist a matrix with every smaller sharpness. That's correct except only one case -- there doesn't exist a matrix with side $3$ and sharpness $3$, though there exists a matrix with side $3$ and sharpness $5$. Let's show that the claim above is correct for odd $n  \\ge  5$. We'll build a matrix with sharpness $\\frac{n^2 + 1}{2}$ as shown above and gradually turn ones into zeroes reducing the sharpness. Cells containing ones in the matrix can be divided into three types. The first type is the central cell. The number in it can be turned into zero and the matrix won't stop satisfying the required conditions. The second type is the cells in the central row and the central column (except central cell). Such cells are divided into pairs by the condition of symmetry -- if we turn the number in one of them into zero, we should turn the number in its pair cell into zero as well. The third type is all the other cells. Such cells are divided into groups of four by the condition of symmetry -- if we turn the number in one of them into zero, we should turn the number in all cells from this group into zero as well. Now for obtaining the required sharpness of $x$ we'll act greedily. Let's turn ones into zeroes in third type cells by four until the current shapness exceeds $x$ by less than $4$ or there are no third type cells with ones remaining. After that let's turn ones into zeroes in second type cells by pairs while the current sharpness exceeds $x$ by at least $2$. At this moment the sharpness of our matrix is either $x$ or $x + 1$. If it's equal to $x + 1$, let's put a zero into the central cell and obtain a matrix with sharpness $x$. It's easy to check that we'll be able to obtain a matrix with any sharpness acting this way. Why is this reasoning incorrect for $n = 3$? Because second type cells are absent in the matrix with sharpness $5$ obtained from chess coloring. For $n  \\ge  5$ this matrix contains cells of all types, which is important for the algorithm above. It's better to find the answers for $x  \\le  5$ by hand but carefully -- for example, a lot of contestants decided that the answer for $x = 2$ is $5$ instead of $3$.",
    "tags": [
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "201",
    "index": "B",
    "title": "Guess That Car!",
    "statement": "A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called \"Guess That Car!\".\n\nThe game show takes place on a giant parking lot, which is $4n$ meters long from north to south and $4m$ meters wide from west to east. The lot has $n + 1$ dividing lines drawn from west to east and $m + 1$ dividing lines drawn from north to south, which divide the parking lot into $n·m$ $4$ by $4$ meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from $0$ to $n$ from north to south and from $0$ to $m$ from west to east. Each square has coordinates $(i, j)$ so that the square in the north-west corner has coordinates $(1, 1)$ and the square in the south-east corner has coordinates $(n, m)$. See the picture in the notes for clarifications.\n\nBefore the game show the organizers offer Yura to occupy any of the $(n + 1)·(m + 1)$ intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's \"rarity\" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with \"rarity\" $c$ placed in a square whose center is at distance $d$ from Yura takes $c·d^{2}$ seconds. The time Yura spends on turning his head can be neglected.\n\nIt just so happened that Yura knows the \"rarity\" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible.",
    "tutorial": "We need to find such $x$ and $y$ that the value of $\\textstyle\\sum_{i_{j}}c_{i j}((x-x_{i})^{2}+(y-y_{j})^{2})$ is minimum possible. This expression can be rewritten as $\\textstyle\\sum_{i,j}c_{i j}(x-x_{i})^{2}+\\sum_{i,j}c_{i j}(y-y_{j})^{2}$. Note that the first part doesn't depend on $y$ and the second part doesn't depend on $x$, so we can minimize these parts separately. Here is how to minimize $\\sum_{i,j}c_{i j}(x-x_{i})^{2}$, the second part is minimized similarly. As the expression in the brackets doesn't depend on $j$, this part can be rewritten as $\\textstyle\\sum_{i}s_{i}(x-x_{i})^{2}$, where $s_{i}=\\sum_{j}c_{i j}$. Now it's enough to calculate the required value for all possible values of $x$ and choose $x$ for which this value is the smallest. The optimal value of $y$ can be found similarly. The overall complexity of this solution is $O(n \\cdot m + n^{2} + m^{2})$. As the objective function is convex, other approaches to this problem are possible, for example, ternary search, gradient descent or analytical approach (calculation of derivatives).",
    "tags": [
      "math",
      "ternary search"
    ],
    "rating": 1800
  },
  {
    "contest_id": "201",
    "index": "C",
    "title": "Fragile Bridges",
    "statement": "You are playing a video game and you have just reached the bonus level, where the only possible goal is to score as many points as possible. Being a perfectionist, you've decided that you won't leave this level until you've gained the maximum possible number of points there.\n\nThe bonus level consists of $n$ small platforms placed in a line and numbered from $1$ to $n$ from left to right and ($n - 1$) bridges connecting adjacent platforms. The bridges between the platforms are very fragile, and for each bridge the number of times one can pass this bridge from one of its ends to the other before it collapses forever is known in advance.\n\nThe player's actions are as follows. First, he selects one of the platforms to be the starting position for his hero. After that the player can freely move the hero across the platforms moving by the undestroyed bridges. As soon as the hero finds himself on a platform with no undestroyed bridge attached to it, the level is automatically ended. The number of points scored by the player at the end of the level is calculated as the number of transitions made by the hero between the platforms. Note that if the hero started moving by a certain bridge, he has to continue moving in the same direction until he is on a platform.\n\nFind how many points you need to score to be sure that nobody will beat your record, and move to the next level with a quiet heart.",
    "tutorial": "There are a few different ways to solve this problem, the editorial contains one of them. For any solution the following fact is useful. Suppose the sought path starts on platform $i$ and ends on platform $j$ ($i  \\le  j$, if that's not the case, we can reverse the path). Then all bridges between platforms $i$ and $j$ will be passed through an odd number of times, and all other bridges will be passed through an even number of times. Let's find the maximum length of a path with its ends on platforms $i$ and $j$. To do that, let's find the following auxiliary values for each platform: $left_{i}$ -- the maximum length of a path starting and ending on platform $i$ and passing only through bridges to the left of platform $i$; $right_{j}$ -- similarly for bridges to the right of platform $j$. Also for each bridge define $odd_{i}$ as the largest odd number not larger than $a_{i}$, and for each platform define $sumOdd_{i}$ as the sum of $odd_{j}$ for all bridges to the left of platform $i$. Then the maximum length of a path with its ends on platforms $i$ and $j$ is equal to $left_{i} + right_{j} + (sumOdd_{j} - sumOdd_{i})$, or, which is the same, $(right_{j} + sumOdd_{j}) + (left_{i} - sumOdd_{i})$. Now we can find the pair $(i, j)$ for which this value is the largest in linear time. Let's loop over $j$. From the formula it's obvious that we should find such $i  \\le  j$ that $(left_{i} - sum_{Odd}_{i})$ is the largest. If we loop over $j$ from $1$ to $n$, we can maintain the largest value of this expression for all $i  \\le  j$ and recalculate it when moving to the next $j$, comparing $(left_{j} - sumOdd_{j})$ with the current maximum and possibly updating this maximum. This way for each $j$ we have to check only one value of $i$ and not all $i  \\le  j$. The last thing to show is how to find all $left_{i}$ quickly (all $right_{j}$ can be found similarly). Clearly $left_{1} = 0$, then we'll calculate $left_{i}$ using $left_{i - 1}$. Note that when $a_{i - 1} = 1$, we have $left_{i} = 0$ as after passing the bridge to platform $(i - 1)$ this bridge will collapse and it will be impossible to return to platform $i$. If $a_{i - 1} > 1$, then $left_{i} = left_{i - 1} + even_{i - 1}$, where $even_{i - 1}$ is the largest even number not larger than $a_{i - 1}$. Indeed, we can move to platform $(i - 1)$, then move along the path corresponding to $left_{i - 1}$, and then move along the bridge between platforms $(i - 1)$ and $i$ until the limit on the number of transitions is less than $2$ (finishing on platform $i$). The overall complexity of this solution is $O(n)$.",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "201",
    "index": "D",
    "title": "Brand New Problem",
    "statement": "A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word \"duped\" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.\n\nYou are invited to act as a fair judge and determine whether the problem is indeed \\underline{brand new}, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.\n\nYou are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.\n\nThe \"similarity\" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the \"similarity\" of a problem can be written as $p={\\frac{n-(n-1)}{2}}-x+1$, where $n$ is the number of words in Lesha's problem and $x$ is the number of inversions in the chosen permutation. Note that the \"similarity\" $p$ is always a positive integer.\n\nThe problem is called \\underline{brand new} if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.\n\nHelp the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.",
    "tutorial": "The first solution coming to mind is dynamic programming $f[i][j] =$ (the smallest possible number of inversions to the moment if among the first $j$ words of the archive problem we've found a permutation of words included in bitmask $i$). In this solution parameter $j$ varies from $0$ to $500000$, parameter $i$ varies from $0$ to $2^{15} - 1$ and calculation of each value is possible in $O(1)$ (we are either using the current word in the subsequence or not). That's too much. Let's make use of a standard technique: make the value of DP a new parameter and make one of the existing parameters the value of DP. Not for every DP this is possible, but at least it's possible for this one :) It's clear that with a fixed subset of words and a fixed number of inversions it's optimal to choose the first occurrences of these words giving this number of inversions. Let $f[i][j] =$ (the smallest number $z$ such that among first $z$ words of the archive problem there exists a permutation of words from bitmask $i$ containing exactly $j$ inversions). The basis of this DP is $f[0][0] = 0$, $f[0][j] =  \\infty $ for $j > 0$. Recalculation of values happens in the following way: loop over a word $q$ from the bitmask $i$ which was the last in the permutation. With the knowledge of this word and the number of inversions $j$ it's easy to find how many inversions $j'$ there were without this word - that's $j$ minus the number of words in the mask which appeared later in Lesha's problem than word $q$. Let $p = f[i^(1<<q)][j']$. Then we should consider $p_{2}$ equal to the position of the next occurrence of word $q$ after position $p$ as a possible value for $f[i][j]$. To find $p_{2}$ quickly we should fill an array $next[500010][15]$ so that $next[i][j] =$ (the smallest position $k > i$ such that the $k$-th word in the archive problem equals the $j$-th word in Lesha's problem) for each archive problem in advance. This array can be easily filled passing from right to left once. The total number of operations can be calculated as $m \\cdot (k \\cdot n + 2^{n} \\cdot C_{n}^{2} \\cdot n)$, where $m$ is the number of problems in the archive, $k$ is the number of words in one archive problem description and $n$ is the number of words in Lesha's problem description. Under the given constraints that is about $200$ million operations, and the author's solutions (including a Java solution) worked for less than $2$ seconds. The time limit was set with a margin -- 5 seconds.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "201",
    "index": "E",
    "title": "Thoroughly Bureaucratic Organization",
    "statement": "Once $n$ people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of $n$ people made an appointment on one of the next $n$ days, and no two persons have an appointment on the same day.\n\nHowever, the organization workers are very irresponsible about their job, so none of the signed in people was told the exact date of the appointment. The only way to know when people should come is to write some requests to TBO.\n\nThe request form consists of $m$ empty lines. Into each of these lines the name of a signed in person can be written (it can be left blank as well). Writing a person's name in the same form twice is forbidden, such requests are ignored. TBO responds very quickly to written requests, but the reply format is of very poor quality — that is, the response contains the correct appointment dates for all people from the request form, but the dates are in completely random order. Responds to all requests arrive simultaneously at the end of the day (each response specifies the request that it answers).\n\nFortunately, you aren't among these $n$ lucky guys. As an observer, you have the following task — given $n$ and $m$, determine the minimum number of requests to submit to TBO to clearly determine the appointment date for each person.",
    "tutorial": "Let's imagine that we have a magic function $maxN(m, k)$ that returns, given $m$ and $k$, the largest value of $n$ such that it's possible to solve the problem for $n$ people and $m$ empty lines in the form using $k$ requests. Then we'll be able to use binary search on the answer -- the number of requests $k$. Suppose we've made $k$ requests. Let's match a string of length $k$ to each person, where the $i$-th character is equal to $1$ if this person is mentioned in the $i$-th request and $0$ otherwise. Note that we'll be able to determine the exact appointment date for each person if and only if all $n$ strings of length $k$ are pairwise distinct. Indeed, if two persons' strings are the same, their appointment dates could be exchanged and the responses to the requests wouldn't have changed. If all strings are distinct, for each date we may find the person appointed for this date looking at the set of requests with responses containing this date and finding the person mentioned in the same set of requests. The constraint on $m$ empty lines in the form means that each of $k$ positions in the strings should contain no more than $m$ ones in all $n$ strings overall. Thus function $maxN(m, k)$ should return the maximum size of a set of distinct $k$-bit strings meeting this condition. Let's make this restriction weaker: we'll search for a set such that the total number of ones in all $n$ strings doesn't exceed $k \\cdot m$. As we'll prove later, the answer won't change. With this weaker restriction the problem can be solved using a simple greedy strategy. It's obvious that strings with smaller number of ones are better. Let's loop over the number of ones $i$ in the string from $0$ to $k$ and also maintain a variable $t$ containing the remaining number of ones (initially it's equal to $k \\cdot m$). Then at the $i$-th step we can take at most $p=m i n(\\underline{{{t}}},C_{k}^{i})$ strings containing $i$ ones. Let's add $p$ to the answer and subtract $p \\cdot i$ from $t$. Note that the values of $C_{k}^{i}$ should be calculated with care -- they can turn out to be too large, so it's important not to allow overflows. It can be shown that the overall complexity of this algorithm is at most $O(log^{2}$ $n)$. The remaining thing is to prove the claim above. The idea of the proof below belongs to rng_58 (the author's proof is notably harder). Let's solve the problem with a greedy algorithm with the $k \\cdot m$ constraint on the total number of ones. The resulting set of strings may not satisfy the restriction of $m$ ones for each position. If it doesn't, some of the positions contain more than $m$ ones and some contain less than $m$ ones. Let's pick any position $X$ containing more than $m$ ones and any position $Y$ containing less than $m$ ones. Find all strings containing $1$ at $X$ and $0$ at $Y$ (suppose there are $x$ such strings) and all strings containing $0$ at $X$ and $1$ at $Y$ (suppose there are $y$ such strings). It's clear that $x > y$. In each of $x$ strings we can try to put $0$ at $X$ and $1$ at $Y$ -- then the string we obtain will either remain unique in this set or coincide with one of those $y$ strings (but only one). As $x > y$, for at least one of $x$ strings the change above leaves this string unique. Let's take this string and put $0$ at $X$ and $1$ at $Y$. Now position $X$ contains one $1$ less, and position $Y$ contains one $1$ more. It means that the total number of \"extra\" ones in the positions has been decreased (as $Y$ still contains no more than $m$ ones). Doing this operation for a needed number of times, we'll achieve our goal.",
    "tags": [
      "binary search",
      "combinatorics"
    ],
    "rating": 2600
  },
  {
    "contest_id": "202",
    "index": "A",
    "title": "LLPS",
    "statement": "\\underline{This problem's actual name, \"Lexicographically Largest Palindromic Subsequence\" is too long to fit into the page headline.}\n\nYou are given string $s$ consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.\n\nWe'll call a non-empty string $s[p_{1}$$p_{2}... p_{k}]$ = $s_{p1}s_{p2}... s_{pk}$ ($1$ $ ≤ $ $p_{1} < p_{2} < ... < p_{k}$ $ ≤ $ $|s|$) a \\underline{subsequence} of string $s$ = $s_{1}$$s_{2}... s_{|s|}$, where $|s|$ is the length of string $s$. For example, strings \"abcb\", \"b\" and \"abacaba\" are subsequences of string \"abacaba\".\n\nString $x$ = $x_{1}$$x_{2}... x_{|x|}$ is \\underline{lexicographically larger} than string $y$ = $y_{1}$$y_{2}... y_{|y|}$ if either $|x|$ > $|y|$ and $x_{1} = y_{1}$, $x_{2} = y_{2}$, ..., $x_{|y|} = y_{|y|}$, or there exists such number $r$ ($r < |x|$, $r < |y|$) that $x_{1} = y_{1}$, $x_{2} = y_{2}$, ..., $x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters in the strings are compared according to their ASCII codes. For example, string \"ranger\" is lexicographically larger than string \"racecar\" and string \"poster\" is lexicographically larger than string \"post\".\n\nString $s$ = $s_{1}$$s_{2}... s_{|s|}$ is a \\underline{palindrome} if it matches string $rev(s)$ = $s_{|s|}$$s_{|s| - 1}... s_{1}$. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are \"racecar\", \"refer\" and \"z\".",
    "tutorial": "It's assumed that this problem can be solved just looking at the samples and without reading the statement itself :) Let's find the letter in the given string which comes last in the alphabet, denote this letter by $z$. If this letter occurs $p$ times in the given string, then the answer is string $a$ consisting of letter $z$ repeated $p$ times. Why is it so? Using the definition of lexicographical comparison and the fact that $z$ is the largest letter in the string it's easy to understand that if some other subsequence $b$ of the given string is lexicographically larger than $a$, then string $b$ should be longer than $a$ and, moreover, $a$ should be a prefix of $b$ (that is, $b$ should start with $a$). But string $b$ must be a palindrome, therefore its last letter must be $z$. In this case string $b$ must contain more occurrences of letter $z$ than the original string $s$ does, which is impossible as $b$ is a subsequence of $s$. Besides that, the constraint on the length of the string was very low, so the problem could be solved using brute force. For every subsequence of the given string it's necessary to check whether it's a palindrome, and from all palindromic subsequences of $s$ the lexicographically largest should be chosen as the answer. The complexity of such a solution is $O(2^{n} \\cdot n)$, where $n$ is the length of the string (unlike the solution above with complexity $O(n)$).",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "202",
    "index": "B",
    "title": "Brand New Easy Problem",
    "statement": "A widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem — a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word \"duped\" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.\n\nYou are invited to act as a fair judge and determine whether the problem is indeed \\underline{brand new}, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.\n\nYou are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.\n\nThe \"similarity\" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the \"similarity\" of a problem can be written as $p={\\frac{n-(n-1)}{2}}-x+1$, where $n$ is the number of words in Lesha's problem and $x$ is the number of inversions in the chosen permutation. Note that the \"similarity\" $p$ is always a positive integer.\n\nThe problem is called \\underline{brand new} if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.\n\nHelp the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.",
    "tutorial": "The constraints in this problem were so low that a solution with complexity $O(m \\cdot k^{n})$ was just fine. In each problem's description it's enough to loop over all possible subsequences of words which are permutations of words in Lesha's problem, for each of them calculate the number of inversions and choose a permutation with the smallest number of inversions. This can result in a short solution using recursion or, for example, you can use several nested loops (from $1$ to $4$). Here is an example of pseudocode for $n = 4$: w - array of words of Lesha''s problem s - the description of the current problem best = 100 for a = 1 to k do for b = 1 to k do for c = 1 to k do for d = 1 to k do if s[a] == w[1] and s[b] == w[2] and s[c] == w[3] and s[d] == w[4] then inversions = 0 if a > b then inversions = inversions + 1 if a > c then inversions = inversions + 1 if a > d then inversions = inversions + 1 if b > c then inversions = inversions + 1 if b > d then inversions = inversions + 1 if c > d then inversions = inversions + 1 if inversions < best then best = inversionsAt the end you should choose the problem with the smallest value of $best$ and print the answer in the corresponding form.",
    "tags": [
      "brute force"
    ],
    "rating": 1700
  },
  {
    "contest_id": "204",
    "index": "A",
    "title": "Little Elephant and Interval",
    "statement": "The Little Elephant very much loves sums on intervals.\n\nThis time he has a pair of integers $l$ and $r$ $(l ≤ r)$. The Little Elephant has to find the number of such integers $x$ $(l ≤ x ≤ r)$, that the first digit of integer $x$ equals the last one (in decimal notation). For example, such numbers as $101$, $477474$ or $9$ will be included in the answer and $47$, $253$ or $1020$ will not.\n\nHelp him and count the number of described numbers $x$ for a given pair $l$ and $r$.",
    "tutorial": "It is well-known that for such problem you need to write function $F(x)$ which solves the problem for the interval $0..x$, and the answer then is $F(r) - F(l - 1)$. Now you need to write $F(x)$ function. If $x < 10$, then answer is, of course, equal to $x$. Otherwise, let $len$ be the length of $x$, $x'$ - the integer $x$ but without first and last digits, $x_{i}$ - the $i$-th digit of integer $x$ (from left to right, starting from $0$). Interate through all possible first digit $d$ (which is the last at the same time) and through the length $i$ of the number. Then if $i < len - 2$ or ($i = len - 2$ and $d < x_{0}$) you need to add $10^{i}$ to the answer. Otherwise, if $i = len - 2$ and $d = x_{0}$ you need to add $x'$ to the answer. Finally, if $i = len - 2$ and $d = x_{0}$ and $x_{len - 1}  \\ge  d$ add $1$ to the answer. This problems also can be solved using DP.",
    "tags": [
      "binary search",
      "combinatorics",
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "204",
    "index": "B",
    "title": "Little Elephant and Cards",
    "statement": "The Little Elephant loves to play with color cards.\n\nHe has $n$ cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).\n\nHelp the Little Elephant to find the minimum number of moves needed to make the set of $n$ cards funny.",
    "tutorial": "It is nice to use the $map$ structure in this problem, but you can solve it without $map$ (using sorting and binary serach). Lets iterate through all possible colors that we have and suppose that this currect color is the one that will make our set funny. The minimal number through all this will be the answer. To find the minimal number of turns to make our set funny using current color we need to know two numbers: the number of cards with current color on the front side and the number of cards with the current color on back side (but not at the same time). Let it be integers $a$ and $b$. Let $m = (n + 1) / 2$ - the minimal number of the same cards required to get the funny set. Then if $a + b < m$ it is impossible to make set funny using current color at all. If $a  \\ge  m$ then the answer is $0$, otherwise the answer is $m - a$.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 1500
  },
  {
    "contest_id": "204",
    "index": "C",
    "title": "Little Elephant and Furik and Rubik",
    "statement": "Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.\n\nThe Little Elephant has two strings of equal length $a$ and $b$, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length — the first one from string $a$, the second one from string $b$. The choice is equiprobable among all possible pairs. Let's denote the substring of $a$ as $x$, and the substring of $b$ — as $y$. The Little Elephant gives string $x$ to Furik and string $y$ — to Rubik.\n\nLet's assume that $f(x, y)$ is the number of such positions of $i$ ($1 ≤ i ≤ |x|$), that $x_{i} = y_{i}$ (where $|x|$ is the length of lines $x$ and $y$, and $x_{i}$, $y_{i}$ are the $i$-th characters of strings $x$ and $y$, correspondingly). Help Furik and Rubik find the expected value of $f(x, y)$.",
    "tutorial": "This problem is to find the expected value. Important fact here is the linearity of the expected value. This means that we can for each element of the first strings find the probability that exactly this element will me matched with some other (but, of course, equal) from the second string. The answer will be the sum of all such probabilities. Let the current character of the first string be the $i$-th character (1-based numeration). Firstly we try to solve problem in $O(N^{2})$ time. Namely, as it was said above, we need to find the number of such pairs of substrings that $i$-th character (which is on probably some other position in substring) is the same as the corresponding character of the second substring. Iterate through all $j$ ($j  \\le  i$) such that $A_{i} = B_{j}$. The number of such pairs of substrings that have match in that characters is $j(n - i + 1)$ (considering 1-based numeration). This is $O(N^{2})$. And because we need to find the sum of such values for all possible $j$, we can rewrite it as $S_{i}(n - i + 1)$, where $S_{i}$ equals to the sum of all integers $j$ ($j  \\le  i$) that $A_{i} = B_{i}$. Array $S$ can be simply computed in a linear time. Analogically you should process all indices to the right from $i$. After we know the number of pairs of substrings with the match with the $i$-th character (let it be $count$), the probability is $count / total$, where $total$ is the total number of pair of substrings (it can be found by loop or with some simple formula). The comlexity is $O(N)$.",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 2000
  },
  {
    "contest_id": "204",
    "index": "D",
    "title": "Little Elephant and Retro Strings",
    "statement": "The Little Elephant has found a ragged old black-and-white string $s$ on the attic.\n\nThe characters of string $s$ are numbered from the left to the right from $1$ to $|s|$, where $|s|$ is the length of the string. Let's denote the $i$-th character of string $s$ as $s_{i}$. As the string is black-and-white, each character of the string is either letter \"B\", or letter \"W\". Unfortunately, the string is very old and some characters are damaged. The damaged positions are denoted as \"X\".\n\nThe Little Elephant in determined to restore the string and hang it on the wall. For that he needs to replace each character \"X\" by a \"B\" or a \"W\". The string must look good on the wall, so it must be \\underline{beautiful}. The Little Elephant considers a string beautiful if it has two non-intersecting substrings of a given length $k$, such that the left one fully consists of characters \"B\", and the right one fully consists of characters \"W\". More formally, there are four integers $a, b, c, d$ $(1 ≤ a ≤ b < c ≤ d ≤ |s|; b - a + 1 = d - c + 1 = k)$ such that $s_{i}$ = \"B\" $(a ≤ i ≤ b)$ and $s_{j}$ = \"W\" $(c ≤ j ≤ d)$.\n\nHelp the Little Elephant find the number of different beautiful strings he can obtain from string $s$. Two strings are considered different if there is such position, where the character in the first string differs from the corresponding character in the second string. If this string doesn't contain characters «X» and it is already beautiful — the answer is 1.\n\nAs the answer can be rather large, print it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Firstly we should solve following subproblem: for each prefix find the number of it's fillings such that there is no consecutive block of $k$ characters $B$. Let it be $F(x)$, where $x$ is the index in of the last character if the prefix. Assing $F(x) = F(x - 1) * cnt$, where $cnt = 2$ if $S_{x}$ = 'X' and $1$ otherwise. After such assing there may be some bad filling included to $F(x)$. Since we suppouse that $F(x - 1)$ is caclulated correctly, all bad filling must contain blocks of $k$ charcters $B$ only at the end of the prefix (they may be included only if substring $S_{x - k + 1..x}$ doesn't contain characters $W$ and character $S_{x - k}$ is not $B$). So, if it's possible, we must subtract from $F(x)$ value $F(x - k - 1)$, because it's exactly the number of bad fillings. With the same DP you should you calc the same values for suffixes (but this time changing $B$ by $W$ and vice versa). Now we should carefully calculate the result in such way that now repeatings occur. Let iterate (from right to left) through all possible positions of the first blocks of $k$ characters $B$ (this means that we suppose that no block occur to the left). Using our DP we can simply find the number of fillings of all characters to the left from that block in such way that no another blocks of $k$ characters $B$ occur. Considering $O(N^{2})$ solutions, we can iterate through all possible indexes of the begging of the last block of $k$ characters $W$ (again we suppose that this blocks must be the last and no another may occur to the right) and agin using our DP count the number of fillings to the right. We don't care what is between that blocks, so we just multiply answer by 2^(the number of characters $X$ between blocks). But, since we are going from right to the left, we can just keep tracking on all possible last blocks and get $O(N)$ solution.",
    "tags": [
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "204",
    "index": "E",
    "title": "Little Elephant and Strings",
    "statement": "The Little Elephant loves strings very much.\n\nHe has an array $a$ from $n$ strings, consisting of lowercase English letters. Let's number the elements of the array from 1 to $n$, then let's denote the element number $i$ as $a_{i}$. For each string $a_{i}$ $(1 ≤ i ≤ n)$ the Little Elephant wants to find the number of pairs of integers $l$ and $r$ $(1 ≤ l ≤ r ≤ |a_{i}|)$ such that substring $a_{i}[l... r]$ is a substring to at least $k$ strings from array $a$ (including the $i$-th string).\n\nHelp the Little Elephant solve this problem.\n\nIf you are not familiar with the basic notation in string problems, you can find the corresponding definitions in the notes.",
    "tutorial": "To solve this problems we can use suffix array. More information about suffix arrays you can find in the Internet. Firstly, concatenate all strings into the one separating consecutive strings by some unique characters (it was also useful to not use strings, but arrays of integers). For example, three strings $abc, a, ab$ may be concatenated in the following way: $abc#a@ab$. Now we should build suffix array using this total string, this allows to us to sort all cyclic shifts of the string. After that each cyclic shift will either begin with additional character or the character from the input strings. Notice now that to find the result we need to find for each cyclic shift (begging of which doesn't contain additional character) the largest size of it's prefix such that this prefix is substring of at least $k$ different input strings. This value can be found by binary search, but for this we need some function $F(x, len)$ which can answer the questions: how many input strings contain prefix of size $len$ of $x$ cyclic shift as a substring. How to make $F(x, len)$? Look at all cyclic shifts, prefix of size $len$ of which is equal to preifx of size $len$ of $x$-th shift. Since all shifts are sorted lexicoraphically, this set of shifts can be represented as integral $[l;r]$ of indices of shifts ($1  \\le  l  \\le  x  \\le  r$). How to find $l$ and $r$? For each pair of consecutive shifts we can find it's greatest common prefix (using properties of suffix array). Than $l$ and $r$ can be found using RMQ. For $l$ we need to know the rigthmost pair of shift (but to the left from $x$) that their greatest common prefix is less than $len$. Analogically we can find $r$. After that we have interval $[l;r]$ and we need to find the number of different input strings that belongs to the shifts from $l$-th to $r$-th (actually, we need to find the number of different integer on interval). But, notice that we dont need the exactly number of different integers, we need to know just it is at least $k$ or not. So let $L[i]$ equals to the greatest $j$ ($j  \\le  i$) such that the number of different integers on interval $[j;i]$ is equal to $k$. Then if $L[r]  \\ge  l$, obiously, interval $[l;r]$ will also contains at least $k$ different. So $F(x, len)$ is done. The only thing to done is to fill array $L$. This is pretty simple using $set$ (but it is possible without it but using RMQ). We will go from left to righ at keep the indices of the last (the rightmost) $k$ different integers in the $set$. If some integer comes, then (if it was earlier) we need to erase this previous index from set (if it was still in) and insert new current. While the size of set is greater than $k$, we should erase the minimal number from it. Then if in some position $i$ the size of the set (after above changings) is equal to $k$, than $L[i]$ is equal to the minimal number in set. Since we $O(N)$ times use binary search, and function $F(x, len)$ works in $O(logN)$ time, the total complexity is $O(Nlog^{2}N)$.",
    "tags": [
      "data structures",
      "implementation",
      "string suffix structures",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "205",
    "index": "A",
    "title": "Little Elephant and Rozdil",
    "statement": "The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. \"Rozdil\").\n\nHowever, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.\n\nFor each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print \"Still Rozdil\", if he stays in Rozdil.",
    "tutorial": "This problem was the simplest in the problemset. All you need to do is just to sort all distances (keeping track on all indices). If the first two distances are equal, just output \"Still Rozdil\", otherwise output the index of the first element of the array. The complexity is $O(NlogN)$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "205",
    "index": "B",
    "title": "Little Elephant and Sorting",
    "statement": "The Little Elephant loves sortings.\n\nHe has an array $a$ consisting of $n$ integers. Let's number the array elements from 1 to $n$, then the $i$-th element will be denoted as $a_{i}$. The Little Elephant can make one move to choose an arbitrary pair of integers $l$ and $r$ $(1 ≤ l ≤ r ≤ n)$ and increase $a_{i}$ by $1$ for all $i$ such that $l ≤ i ≤ r$.\n\nHelp the Little Elephant find the minimum number of moves he needs to convert array $a$ to an arbitrary array sorted in the non-decreasing order. Array $a$, consisting of $n$ elements, is sorted in the non-decreasing order if for any $i$ $(1 ≤ i < n)$ $a_{i} ≤ a_{i + 1}$ holds.",
    "tutorial": "In this problem you need to notice the fact (which can be proven, but it is almost obvious) that if you are doing some operation for interval from $l$ to $r$ (inclusive), $r$ must be equal to $n$. This is becuase when you add something to all right part the answer can't be worse. After that you need to go from left to right and greedly add appropriate number of turns. The complexity is $O(N)$.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "208",
    "index": "A",
    "title": "Dubstep",
    "statement": "Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.\n\nLet's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words \"WUB\" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including \"WUB\", in one string and plays the song at the club.\n\nFor example, a song with words \"I AM X\" can transform into a dubstep remix as \"WUBWUBIWUBAMWUBWUBX\" and cannot transform into \"WUBWUBIAMWUBX\".\n\nRecently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.",
    "tutorial": "This problem was technical. First, you should erase all occurrences or word WUB in the beginning and in the end of the string. And then parse the remaining string separating tokens by word WUB. Empty tokens should be also erased. Given string was rather small, you can realize the algorithm in any way.",
    "tags": [
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "208",
    "index": "B",
    "title": "Solitaire",
    "statement": "A boy named Vasya wants to play an old Russian solitaire called \"Accordion\". In this solitaire, the player must observe the following rules:\n\n- A deck of $n$ cards is carefully shuffled, then all $n$ cards are put on the table in a line from left to right;\n- Before each move the table has several piles of cards lying in a line (initially there are $n$ piles, each pile has one card). Let's number the piles from left to right, from 1 to $x$. During one move, a player can take the whole pile with the maximum number $x$ (that is the rightmost of remaining) and put it on the top of pile $x - 1$ (if it exists) or on the top of pile $x - 3$ (if it exists). The player can put one pile on top of another one only if the piles' top cards have the same suits or values. Please note that if pile $x$ goes on top of pile $y$, then the top card of pile $x$ becomes the top card of the resulting pile. Also note that each move decreases the total number of piles by 1;\n- The solitaire is considered completed if all cards are in the same pile.\n\nVasya has already shuffled the cards and put them on the table, help him understand whether completing this solitaire is possible or not.",
    "tutorial": "In this problem you could write breadth-first search. The state is the following four elements: number of remaining piles and three strings - three rightmost cards on the top of three rightmost piles. We have two transitions in general case. We can take the rightmost pile and shift it left by $1$ or $3$ on another pile. If the number of remaining piles become $0$ at some moment print $YES$, else print $NO$. The number of states is $O(N^{4})$, the number of transitions $2$, so the complexity of solution is $O(N^{4})$.",
    "tags": [
      "dfs and similar",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "208",
    "index": "C",
    "title": "Police Station",
    "statement": "The Berland road network consists of $n$ cities and of $m$ bidirectional roads. The cities are numbered from 1 to $n$, where the main capital city has number $n$, and the culture capital — number $1$. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.\n\nAll residents of Berland are very lazy people, and so when they want to get from city $v$ to city $u$, they always choose one of the shortest paths (no matter which one).\n\nThe Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.\n\nNow the government wonders where to put the police station so that the average number of safe roads for \\textbf{all} the shortest paths from the cultural capital to the main capital would take the maximum value.",
    "tutorial": "In this problem we will find the sought quantity for every vertex and find the maximum value. For this for every vertex $v$ count two values: $cnt1[v]$ and $cnt2[v]$ - number of shortest paths from vertex $v$ to $n$-th and $1$-st vertices respectively. For this you should construct graph of shortest paths and use dynamic programming on the constructed graph (because the new graph will be acyclic). To construct the graph of shortest paths you should leave only useful edges in original graph. It can be done, for example, using breadth-first search launched from vertices $1$ and $n$ respectively. After values $cnt1[v]$ and $cnt2[v]$ are found consider every useful edge $(u, v$) and add to vertices $u$ and $v$ value $(cnt2[u] * cnt1[v]) / (cnt2[n-1])$, which is the contribution of this edge in the sought quantity for the vertices $u$ and $v$. Note that value $(cnt2[n-1])$ is the number of shortest paths between $1$ and $n$. All said values can be found in time $O(N + M)$. The complexity of solution is $O(N + M)$.",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "208",
    "index": "D",
    "title": "Prizes, Prizes, more Prizes",
    "statement": "Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar \"Jupiter\". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.\n\nVasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.\n\nThe sweepstake has the following prizes (the prizes are sorted by increasing of their cost):\n\n- a mug (costs $a$ points),\n- a towel (costs $b$ points),\n- a bag (costs $c$ points),\n- a bicycle (costs $d$ points),\n- a car (costs $e$ points).\n\nNow Vasya wants to recollect what prizes he has received. You know sequence $p_{1}, p_{2}, ..., p_{n}$, where $p_{i}$ is the number of points Vasya got for the $i$-th bar. The sequence of points is given in the chronological order. You also know numbers $a$, $b$, $c$, $d$, $e$. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.",
    "tutorial": "In this problem every time you get points you should greedily get as much prizes as you can. For this, consider every prize from the most expensive and try to get as much as you can. If we have $cnt$ points and the prize costs $p$ points you can get $\\left\\lfloor{\\frac{c-t}{p}}\\right\\rfloor$ prizes. So we get simple solution with complexity $O(5 * N)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "208",
    "index": "E",
    "title": "Blood Cousins",
    "statement": "Polycarpus got hold of a family relationship tree. The tree describes family relationships of $n$ people, numbered 1 through $n$. Each person in the tree has no more than one parent.\n\nLet's call person $a$ a 1-ancestor of person $b$, if $a$ is the parent of $b$.\n\nLet's call person $a$ a $k$-ancestor $(k > 1)$ of person $b$, if person $b$ has a 1-ancestor, and $a$ is a $(k - 1)$-ancestor of $b$'s 1-ancestor.\n\nFamily relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an $x$-ancestor for himself, for some $x$, $x > 0$).\n\n\\textbf{Let's call two people $x$ and $y$ $(x ≠ y)$ $p$-th cousins $(p > 0)$, if there is person $z$, who is a $p$-ancestor of $x$ and a $p$-ancestor of $y$.}\n\nPolycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote $m$ pairs of integers $v_{i}$, $p_{i}$. Help him to calculate the number of $p_{i}$-th cousins that person $v_{i}$ has, for each pair $v_{i}$, $p_{i}$.",
    "tutorial": "In this problem you have some set of rooted down- oriented trees. First, launch depth-first search from every root of every tree and renumber the vertices. Denote size of subtree of vertex $v$ as $cnt[v]$. In this way all descendants of vertex $v$ (including $v$) wiil have numbers $[v;v + cnt[v]-1]$. Then we wiil handle requests $(v, p)$ in their order. First, go up from vertex $v$ on $p$ steps to the root using binary rise like in LCA algorithm. Denote this vertex $u$. If $u$ doesn't exist print $0$ else you should count the number of descendants of vertex $u$ on the same height as vertex $v$. For this write all numbers of vertices for every height in some array. Then you should determine which of these vertices are descendants of $u$. You can do it using binary search in corresponding array. Find the segment of appropriate vertices (because we know the numbers of all descendants of $u$), find the amount of them, subtract one (vertex $v$), and this is the answer. The complexity of the solution is $O(Nlog(N))$.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "213",
    "index": "A",
    "title": "Game",
    "statement": "Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of $n$ parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies.\n\nRubik has $3$ computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from $1$ to $3$. Rubik can perform the following actions:\n\n- Complete some part of the game on some computer. Rubik spends exactly $1$ hour on completing any part on any computer.\n- Move from the 1-st computer to the 2-nd one. Rubik spends exactly $1$ hour on that.\n- Move from the 1-st computer to the 3-rd one. Rubik spends exactly $2$ hours on that.\n- Move from the 2-nd computer to the 1-st one. Rubik spends exactly $2$ hours on that.\n- Move from the 2-nd computer to the 3-rd one. Rubik spends exactly $1$ hour on that.\n- Move from the 3-rd computer to the 1-st one. Rubik spends exactly $1$ hour on that.\n- Move from the 3-rd computer to the 2-nd one. Rubik spends exactly $2$ hours on that.\n\nHelp Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary.",
    "tutorial": "Solution - Greedy. Lets our computers settled on circle, and moves (1->2, 2->3, 3->1) will be steps \"forward\", and moves (1->3,3->2,2->1) will steps \"back\". Note that \"back\" moves is not optimal, as we can make two moves \"forward\" that is identical in time. We will look over all starts. Further, we will go by circle while we not complited all game. For every level we will remember number ne[i] - count of another level that \"direct\" need for it. We will complited levels with ne[i]=0 and update all ne[i] that we must. It can be implemented with O(n^3) time.",
    "tags": [
      "dfs and similar",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "213",
    "index": "B",
    "title": "Numbers",
    "statement": "Furik loves writing all sorts of problems, especially such that he can't solve himself. You've got one of his problems, the one Furik gave to Rubik. And Rubik asks you to solve it.\n\nThere is integer $n$ and array $a$, consisting of ten integers, indexed by numbers from 0 to 9. Your task is to count the number of positive integers with the following properties:\n\n- the number's length does not exceed $n$;\n- the number doesn't have leading zeroes;\n- digit $i$ $(0 ≤ i ≤ 9)$ occurs in the number at least $a[i]$ times.",
    "tutorial": "Solution - dynamic programming. Look over for length of the number that we will build. Further, we will use DP f(len,i) - how many numbers with length len we can make with digits i..9. Recount: - f(len,0) = sum(f(len-i,1)*C(len-1,i), i=a[0]..len); - f(len,j) = sum(f(len-i,j+1)*C(len,i), i=a[j]..len), 0<j<9; - f(len,9) = 1, if len>=a[9], 0 if len<a[9]. C(n,k) - binomial coefficient.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "213",
    "index": "C",
    "title": "Relay Race",
    "statement": "Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of $n$ meters. The given square is split into $n × n$ cells (represented as unit squares), each cell has some number.\n\nAt the beginning of the race Furik stands in a cell with coordinates $(1, 1)$, and Rubik stands in a cell with coordinates $(n, n)$. Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates $(i, j)$, then he can move to cell $(i + 1, j)$ or $(i, j + 1)$. After Furik reaches Rubik, Rubik starts running from cell with coordinates $(n, n)$ to cell with coordinates $(1, 1)$. If Rubik stands in cell $(i, j)$, then he can move to cell $(i - 1, j)$ or $(i, j - 1)$. Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified.\n\nTo win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. \\textbf{Each cell counts only once in the sum}.\n\nPrint the maximum number of points Furik and Rubik can earn on the relay race.",
    "tutorial": "Solution - dynamic programming. Note, that we can make 2 pathes form cell (1,1) to cell (n,n). Note, that after each move our cells will be located on the same diagonal. We will solve the problem with DP f(d,i1,i2), d - diagonal number, i1 - 1st coordinate 1st path, i2 - 1st coordinate 2nd path. It is clear that we can calculate 2nd coordinate when we know number of the diagonal and 1st coordinate. Recount - obvious, we make all 4 transition, and if pathes are intersected in temporary point, we add value of the cell only one, otherwise we add both values of the cells. We can imlement this solution with O(n^2) memory if we will rewrite array of DP after increasing of diagonal number. Also we must remember that answer can be lower then 0.",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "213",
    "index": "D",
    "title": "Stars",
    "statement": "Furik loves painting stars. A star is a shape that results if we take a regular pentagon and paint all diagonals in it.\n\nRecently he decided to teach Rubik to paint stars. After many years of training Rubik could paint stars easily. But now Furik decided to test Rubik and complicated the task. Rubik must paint $n$ stars, observing the following rules:\n\n- all stars must be painted in a single move (i.e. it is forbidden to take the pen away from the paper);\n- it is forbidden to paint the same segment of non-zero length more than once;\n- the stars can intersect only in their vertexes;\n- the length of a side of the regular pentagon, in which Rubik paints each star, must equal 10.\n\nHelp Rubik to cope with this hard task.",
    "tutorial": "I present solution as few pictures: Implementation. We have only one difficult moment - how to count coordinates? We can calculate them from regular pentagon, all that you need, you can read there.",
    "tags": [
      "constructive algorithms",
      "geometry"
    ],
    "rating": 2300
  },
  {
    "contest_id": "213",
    "index": "E",
    "title": "Two Permutations",
    "statement": "Rubik is very keen on number permutations.\n\nA permutation $a$ with length $n$ is a sequence, consisting of $n$ different numbers from 1 to $n$. Element number $i$ $(1 ≤ i ≤ n)$ of this permutation will be denoted as $a_{i}$.\n\nFurik decided to make a present to Rubik and came up with a new problem on permutations. Furik tells Rubik two number permutations: permutation $a$ with length $n$ and permutation $b$ with length $m$. Rubik must give an answer to the problem: how many distinct integers $d$ exist, such that sequence $c$ $(c_{1} = a_{1} + d, c_{2} = a_{2} + d, ..., c_{n} = a_{n} + d)$ of length $n$ is a subsequence of $b$.\n\nSequence $a$ is a subsequence of sequence $b$, if there are such indices $i_{1}, i_{2}, ..., i_{n}$ $(1 ≤ i_{1} < i_{2} < ... < i_{n} ≤ m)$, that $a_{1} = b_{i1}$, $a_{2} = b_{i2}$, $...$, $a_{n} = b_{in}$, where $n$ is the length of sequence $a$, and $m$ is the length of sequence $b$.\n\nYou are given permutations $a$ and $b$, help Rubik solve the given problem.",
    "tutorial": "For given two permutation we will make two another by next transformation: New_A[A[i]] = i, where New_A - news permutation, A - given permutation. Lets we get two permutation A and B. Now our problem is next: how many sub-arrays of length n are equals to firs permutation. Two arrays will be equal if after swaping every element with its number in sorted array obtained arrays will be element-wise equal. Further solution hashes, but we will use not only modulo 2^64, we will use some big modulos, but they must be smaller then 2^32-1. Lets step[i] = 1000003^i. Lets F(A) = num[1]*step[1] + num[2]*step[2] + ... + num[n]*step[n], where num[i] - number of the element A[i] in sorted array. If we will compare arrays, we can use this function. But it can be very big, so we will count it by modulos. So now our problem is to calculate F function to every subarray. Lets look what will change after adding/deleting some elent from set: some element from num array willnot change, and some will become grater after adding, and become lower after deleting. So we must use some interval-tree to recount our F function. We need to know sum of step[i] on some interval of added numbers and count of elements on some interval. Uses this information we can simply recount out function. Also we must remember that after adding element with coeficinet step[i], where i>n and deleting some previos element our function will become grater that we need. So we will multiple hash of first array by 1000003 to avoid this issue.",
    "tags": [
      "data structures",
      "hashing",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "215",
    "index": "A",
    "title": "Bicycle Chain",
    "statement": "Vasya's bicycle chain drive consists of two parts: $n$ stars are attached to the pedal axle, $m$ stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.\n\nWe know that the $i$-th star on the pedal axle has $a_{i}$ $(0 < a_{1} < a_{2} < ... < a_{n})$ teeth, and the $j$-th star on the rear wheel axle has $b_{j}$ $(0 < b_{1} < b_{2} < ... < b_{m})$ teeth. Any pair $(i, j)$ $(1 ≤ i ≤ n$; $1 ≤ j ≤ m)$ is called a gear and sets the indexes of stars to which the chain is currently attached. Gear $(i, j)$ has a gear ratio, equal to the value $\\frac{b_{i}}{a_{i}}$.\n\nSince Vasya likes integers, he wants to find such gears $(i, j)$, that their ratios are integers. On the other hand, Vasya likes fast driving, so among all \"integer\" gears $(i, j)$ he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.\n\nIn the problem, fraction $\\frac{b_{i}}{a_{i}}$ denotes division in real numbers, that is, no rounding is performed.",
    "tutorial": "Because of small constraints we can iterate $i$ from $1$ to $n$, iterate $j$ from $1$ to $m$, check that $b_{j}$ divide $a_{i}$ and find max value of $\\frac{b_j}{a_i}$. Then we can start this process again and find amount of the pairs in which $\\frac{b_j}{a_i}$ is max value.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "215",
    "index": "B",
    "title": "Olympic Medal",
    "statement": "The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of $r_{1}$ cm, inner radius of $r_{2}$ cm, $(0 < r2 < r1)$ made of metal with density $p_{1}$ g/cm$^{3}$. The second part is an inner disk with radius $r_{2}$ cm, it is made of metal with density $p_{2}$ g/cm$^{3}$. The disk is nested inside the ring.\n\nThe Olympic jury decided that $r_{1}$ will take one of possible values of $x_{1}, x_{2}, ..., x_{n}$. It is up to jury to decide which particular value $r_{1}$ will take. Similarly, the Olympic jury decided that $p_{1}$ will take one of possible value of $y_{1}, y_{2}, ..., y_{m}$, and $p_{2}$ will take a value from list $z_{1}, z_{2}, ..., z_{k}$.\n\nAccording to most ancient traditions the ratio between the outer ring mass $m_{out}$ and the inner disk mass $m_{in}$ must equal $m_{o u t}/m_{i n}={\\frac{A}{B}}$, where $A, B$ are constants taken from ancient books. Now, to start making medals, the jury needs to take values for $r_{1}$, $p_{1}$, $p_{2}$ and calculate the suitable value of $r_{2}$.\n\nThe jury wants to choose the value that would maximize radius $r_{2}$. Help the jury find the sought value of $r_{2}$. Value $r_{2}$ doesn't have to be an integer.\n\nMedal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.",
    "tutorial": "Let amagine we have values of $r_{1}$, $p_{1}$ and $p_{2}$. Then: ${\\frac{m_{\\omega u t}}{m_{i n}}}={\\frac{A}{B}}$ $\\frac{\\pi{\\cdot}p_{1}{\\cdot}(r_{1}^{2}-r_{2}^{2})}{\\pi{\\cdot}p_{2}{\\cdot}r_{2}^{2}}\\ =\\ \\frac{A}{B}$ $r_{2}^{2} \\cdot (B \\cdot p_{1} + A \\cdot p_{2}) = r_{1}^{2} \\cdot B \\cdot p_{1}$ $r_{2}=r_{1}\\cdot{\\sqrt{\\frac{B.p_{1}}{B\\cdot p_{1}+A.p_{2}}}}$Now it's easy of understand, we must take maximum value of $r_{1}$ and $p_{1}$, and minimum value of $p_{2}$ to maximize $r_{2}$. You could not use three cycles for iterating all values, but you could find property above about at least one value and use two cycles.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "215",
    "index": "C",
    "title": "Crosses",
    "statement": "There is a board with a grid consisting of $n$ rows and $m$ columns, the rows are numbered from $1$ from top to bottom and the columns are numbered from $1$ from left to right. In this grid we will denote the cell that lies on row number $i$ and column number $j$ as $(i, j)$.\n\nA group of six numbers $(a, b, c, d, x_{0}, y_{0})$, where $0 ≤ a, b, c, d$, is a cross, and there is a set of cells that are assigned to it. Cell $(x, y)$ belongs to this set if \\textbf{at least one} of two conditions are fulfilled:\n\n- $|x_{0} - x| ≤ a$ and $|y_{0} - y| ≤ b$\n- $|x_{0} - x| ≤ c$ and $|y_{0} - y| ≤ d$\n\n\\begin{center}\n{\\scriptsize The picture shows the cross $(0, 1, 1, 0, 2, 3)$ on the grid $3 × 4$.}\n\\end{center}\n\nYour task is to find the number of different groups of six numbers, $(a, b, c, d, x_{0}, y_{0})$ that determine the crosses of an area equal to $s$, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell $(x, y)$ of the cross $1 ≤ x ≤ n; 1 ≤ y ≤ m$ holds). The area of the cross is the number of cells it has.\n\n\\textbf{Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points.}",
    "tutorial": "Let's iterate $n_{1} = max(a, c)$ and $m_{1} = max(b, d)$ - sides of bounding box. Then we can calculate value of function $f(n_{1}, m_{1}, s)$, and add to the answer $f(n_{1}, m_{1}, s) \\cdot (n - n_{1} + 1) \\cdot (m - m_{1} + 1)$, where two lastest brackets mean amount of placing this bounding box to a field $n  \\times  m$. Now we must calculate $f(n_{1}, m_{1}, s)$. At first, if $n_{1} \\cdot m_{1} = s$ then the result of the function is $2 \\cdot ( \\lfloor  n_{1} / 2 \\rfloor  + 1) \\cdot ( \\lfloor  m_{1} / 2 \\rfloor  + 1) - 1$ (you can prove it to youself). If $n_{1} \\cdot m_{1} > s$ then we must to cut 4 corners which are equal rectangles with square $\\frac{n_{1}\\cdot m_{1}-s}{4}$. We can iterate length of a one of sides, calculate another side, check all constraints and add $2$ to the result of the function for all such pairs of sides. The time of a solution is $O(n^{3})$, but it's with very small constant, less then $1$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "215",
    "index": "D",
    "title": "Hot Days",
    "statement": "The official capital and the cultural capital of Berland are connected by a single road running through $n$ regions. Each region has a unique climate, so the $i$-th $(1 ≤ i ≤ n)$ region has a stable temperature of $t_{i}$ degrees in summer.\n\nThis summer a group of $m$ schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the $i$-th region and has $k$ schoolchildren, then the temperature inside the bus is $t_{i} + k$ degrees.\n\nOf course, nobody likes it when the bus is hot. So, when the bus drives through the $i$-th region, if it has more than $T_{i}$ degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as $x_{i}$ rubles and it is charged in each region where the temperature in the bus exceeds the limit.\n\nTo save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the $i$-th region will cost the organizers $cost_{i}$ rubles. Please note that sorting children into buses takes no money.\n\nYour task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.",
    "tutorial": "You can use only two features about this problem: the solution is independenly for all regions and there are only 2 possible situations: all children are in exactly one bus or organizers must take minimum amount of bus such no children got a compensation. It's bad idea to place some children to hot bus and to place some children to cool bus simultaneously. For solving you must calculate this 2 values and get minimum.",
    "tags": [
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "215",
    "index": "E",
    "title": "Periodical Numbers",
    "statement": "A non-empty string $s$ is called binary, if it consists only of characters \"0\" and \"1\". Let's number the characters of binary string $s$ from 1 to the string's length and let's denote the $i$-th character in string $s$ as $s_{i}$.\n\nBinary string $s$ with length $n$ is periodical, if there is an integer $1 ≤ k < n$ such that:\n\n- $k$ is a divisor of number $n$\n- for all $1 ≤ i ≤ n - k$, the following condition fulfills: $s_{i} = s_{i + k}$\n\nFor example, binary strings \"101010\" and \"11\" are periodical and \"10\" and \"10010\" are not.\n\nA positive integer $x$ is periodical, if its binary representation (without leading zeroes) is a periodic string.\n\nYour task is to calculate, how many periodic numbers are in the interval from $l$ to $r$ (both ends are included).",
    "tutorial": "Ok, in the very beginning let's try solve some other task. We'll find the number of such integers in the interval $(2^{k}, x]$, where $k=\\lfloor\\log_{2}(x)\\rfloor$. And someone can see that $x$ has length $len = k + 1$. Then we should try blocks of ${0, 1}$ to be the same part of periodical number. These blocks have length, which is divisor of $len$. Let's calculate number $g[i]$ of such blocks of length $i$, where $i$ is some divisor of $len$. We get $i$ of first(from the left side) bits of number $x$ and name it as $t = x$ >> $(len - i)$, e.g. if $x = 10011000_{2}$, and $i = 4$ then $t = 1001_{2}$, if $i = 2$ then $t = 10_{2}$. Firstly, we should check block $t$, it needs for example to check number $p = ttttt...$ repeated $\\frac{I_{\\ell}\\eta}{i}$ times, it can be calculated in a loop $p = p$ << $i + t$. It's clear if $p  \\le  x$, then we should take into account this block $g[i] = 1$. It's clear that every correct block less or equal than $t$, and it should begin from $1$ (because of periodical number is without leading zeroes). Case of equality we took. And we should add to $g[i]$ difference between $t$ and $2^{i} = 10000..._{2}$ i-1 zeroes, $g[i] = g[i] + t - (1$ << $(i - 1))$. It seems that all is ready and we can sum $g[i]$ for every divisor of $len$ and not equal $len$, but we cant. Because some cases we count more than once, e.g. $x = 10101100_{2}$, $i = 4$, $g[4] = 1 + (1010_{2} - 1000_{2}) = 3$ we considered cases of blocks $1000, 1001, 1010$, and when we count for $i = 2$,$g[2] = 1 + (10_{2} - 10_{2}) = 1$, we considered one case $10$, but $1010$ is obtained from $10$ repeated two times. But we can easily escape these problems, for this we should substract from $g[i]$ all $g[j]$ where $j < i$ and $j$ divides $i$. Some note. We get some DP problem, we calculate $g[i]$ from $i = 1$ to the most divisor of $len$ which is not equal to $len$, and update its value by substracting all g[j]. Let us summarize some ideas, we can count number of periodical numbers in the interval $(2^{k}, x]$, by going through divisors of $len$ and calculating $g[i]$, and then we return sum of $g[i]$ where $i < len$ and $i$ divides $len$. One can see that $2^{k}$ cant be periodical. Given this fact we will calculate this value for $x = 2^{k} - 1$, then $2^{k - 1} - 1$ and so on.In the end we get $x = 1$, and we get set of non-intersecting intervals, counting on each of them and sum up it we get answer. It can be done recursively.",
    "code": "#include <algorithm>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \n#define pb push_back\n#define VI vector <int>\n#define clr(x) memset((x),0,sizeof(x))\n#define forn(i, n) for(int i=0; i<(int)(n); i++)\n \n#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)\n \n#define pw(x) (1ll<<(x))\n \ntypedef long long ll;\n \nll g[32];\nVI divs[63];\nvoid prec()\n{\n    for(int i=1;i<61;i++)\n        for(int j=1;j<i;j++)\n            if (i%j==0)\n                divs[i].pb(j);\n}\ninline int lg(ll n)\n{\n    int l = 0;\n    while (n)\n    {\n        l++;\n        n>>=1;\n    }\n    return l;\n}\n \ninline void upd(int i)\n{\n    fori(j,divs[i])\n        g[i]-=g[*j];\n}\n \nll f(ll n)\n{\n    if (n<=1) return 0;\n    ll ans = 0;\n    int l = lg(n);\n    ans+=f(pw(l-1) - 1);\n    clr(g);\n    fori(it, divs[l])\n    {\n        int i = *it;\n        ll t = n >> (l-i);\n        ll p = t;\n        forn(j,l/i-1)\n            p = (p << i) + t;\n        if (p <= n) g[i]++;\n        g[i] += t - pw(i-1);\n        upd(i);\n        ans += g[i];\n    }\n    return ans;\n}\n \nint main()\n{\n    prec();\n    ll l,r;\n    cin >> l >> r;\n    cout << f(r)-f(l-1);\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "216",
    "index": "A",
    "title": "Tiling with Hexagons",
    "statement": "Several ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.\n\nThe hall also turned out hexagonal in its shape. The King walked along the perimeter of the hall and concluded that each of the six sides has $a$, $b$, $c$, $a$, $b$ and $c$ adjacent tiles, correspondingly.\n\nTo better visualize the situation, look at the picture showing a similar hexagon for $a = 2$, $b = 3$ and $c = 4$.\n\nAccording to the legend, as the King of Berland obtained the values $a$, $b$ and $c$, he almost immediately calculated the total number of tiles on the hall floor. Can you do the same?",
    "tutorial": "For solving this problem you might find some formula like $res = abc - (a - 1)(b - 1)(c - 1)$, $res = ab + bc + ca - a - b - c + 1$, or something else. Also the problem can be solved in $O(a + b + c)$ time - you can move from the top line to the bottom line of hexagon and sum number of tiles in every line.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "216",
    "index": "B",
    "title": "Forming Teams",
    "statement": "One day $n$ students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.\n\nWe know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student $A$ is an archenemy to student $B$, then student $B$ is an archenemy to student $A$.\n\nThe students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench.\n\nDetermine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last.",
    "tutorial": "You can build some graph where vertices are students and edges are enmities. You should drop some vertices and then paint them in two colors. Any edge should connect vertices of distinct colors and numbers of vertices of every color should be same. You can see that graph consists chians, cycles and sepatated vertices. Every of that component can be painted in 2 colors except one case: cycles of odd length. So, you should drop one vertex from every odd cycle. After that you can get odd number of vertices. Then you should drop one more vertex (you can chose any of them). The obtained graph can be easily painted in 2 colors in the required manner.",
    "tags": [
      "dfs and similar",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "216",
    "index": "C",
    "title": "Hiring Staff",
    "statement": "A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.\n\nThe store will work seven days a week, but not around the clock. Every day at least $k$ people must work in the store.\n\nBerland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly $n$ consecutive days, then rest for exactly $m$ days, then work for $n$ more days and rest for $m$ more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day $x$, then he should work on days $[x, x + 1, ..., x + n - 1]$, $[x + m + n, x + m + n + 1, ..., x + m + 2n - 1]$, and so on. Day $x$ can be chosen arbitrarily by Vitaly.\n\nThere is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day — otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.\n\nEach employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from $1$ to infinity. In other words, on each day with index from $1$ to infinity, the store must have at least $k$ working employees, and one of the working employees should have the key to the store.\n\nHelp Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.",
    "tutorial": "The first solution: analysis of the cases 1. $k = 1$. For $n  \\le  m + 1$ 3 employees is enough (in most cases). For $n > m + 1$ answer is 2. Also, there are only one tricky corner case: for $n = 2, m = 2, k = 1$ answer is 4. 2. $k > 1$. If $n = m$, answer is $2k + 1$, otherwise answer is $2k$. For any case it is easy to construct solution, and prove that this solution is optimal. The second solution: greedy. Let's create an array where we will store current number of employees for some number of the first days. Now you should iterate over all days from the first to the $n + m$-th and hire employees every time when it needed. You should hire workers if there are less than $k$ people in the current day; also you should hire worker if there will be no people tomorrow (thet worker will bring the key to the workers that will work tomorrow). This solution works in $O((n + m)k)$. This solution also works correctly for cases $n < m$, but then it has bigger complexity and requires more time.",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "216",
    "index": "D",
    "title": "Spider's Web",
    "statement": "Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web.\n\nThere are $n$ main threads going from the center of the web. All main threads are located in one plane and divide it into $n$ equal infinite sectors. The sectors are indexed from $1$ to $n$ in the clockwise direction. Sectors $i$ and $i + 1$ are adjacent for every $i$, $1 ≤ i < n$. In addition, sectors $1$ and $n$ are also adjacent.\n\nSome sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.\n\nA cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.\n\nUnstable cells are marked red in the figure. Stable cells are marked green.\n\nPaw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.",
    "tutorial": "For every sector you should sort bridges in order of increasing distance from the conter of the web. Now for every sector you should iterate over bridges of the current sector and two adjacent sectors using 3 pointers. During every pass you should carefully calculate number of bad cells. That is all solution. Solition in $O(m\\log m)$, where $m$ is total number of bridges.",
    "tags": [
      "binary search",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "216",
    "index": "E",
    "title": "Martian Luck",
    "statement": "You know that the Martians use a number system with base $k$. Digit $b$ ($0 ≤ b < k$) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year $b$ (by Martian chronology).\n\nA digital root $d(x)$ of number $x$ is a number that consists of a single digit, resulting after cascading summing of all digits of number $x$. Word \"cascading\" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.\n\nFor example, $d(3504_{7}) = d((3 + 5 + 0 + 4)_{7}) = d(15_{7}) = d((1 + 5)_{7}) = d(6_{7}) = 6_{7}$. In this sample the calculations are performed in the 7-base notation.\n\nIf a number's digital root equals $b$, the Martians also call this number lucky.\n\nYou have string $s$, which consists of $n$ digits in the $k$-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.\n\nNote that substring $s[i... j]$ of the string $s = a_{1}a_{2}... a_{n}$ ($1 ≤ i ≤ j ≤ n$) is the string $a_{i}a_{i + 1}... a_{j}$. Two substrings $s[i_{1}... j_{1}]$ and $s[i_{2}... j_{2}]$ of the string $s$ are different if either $i_{1} ≠ i_{2}$ or $j_{1} ≠ j_{2}$.",
    "tutorial": "Digital root of number is equal to that number modulo $k - 1$ for most cases. It is lie only for digital roots 0 and $k - 1$ - in that cases number modulo $k - 1$ will be 0. But you can get digital root 0 only for numbers like $00...00$. Total number of numbers that type you can find using any other way. So, now you can find number of substrings that have some digital root, if you know number of substrings that equals some number modulo $k - 1$. How to find number of substrings of some modulo? You should iterate over all digits of $s$ from the left to the rigth and for every modulo store number of prefixes of that modulo in some array dp[] of size $k$. Let's current position is $i$. Then number of substrings modulo $b$ that ends in position $i$ equals to number of prefixes leftmost position $i$ that have modulo $(x - b)mod(k - 1)$, where $x$ is modulo of $s[1... i]$. I.e. just $dp[(x - b)mod(k - 1)]$. To fit into memory limit, you should replace array dp[] by some associative array. For example, std::map from C++ or some hashtable. So we have solution in $O(nz)$, where $z$ is complexety of access to dp[] ($O(\\log n)$ for std::map and $O(1)$ for hashtable).",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "217",
    "index": "A",
    "title": "Ice Skating",
    "statement": "Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.\n\nWe assume that Bajtek can only heap up snow drifts at integer coordinates.",
    "tutorial": "Notice that the existence of a snow drift at the point $(x, y)$ implies that \"if I'm on the horizontal line at $y$ then I am certainly able to get to the vertical line at $x$, and vice versa\". Thus, the snow drifts are the edges of a bipartite graph between x- and y- coordinates. The number of snow drifts that need to be added to make this (as well as the original) graph connected is the number of its connected components reduced by one.",
    "tags": [
      "brute force",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1200
  },
  {
    "contest_id": "217",
    "index": "B",
    "title": "Blackboard Fibonacci",
    "statement": "Fibonacci numbers are the sequence of integers: $f_{0} = 0$, $f_{1} = 1$, $f_{2} = 1$, $f_{3} = 2$, $f_{4} = 3$, $f_{5} = 5$, $...$, $f_{n} = f_{n - 2} + f_{n - 1}$. So every next number is the sum of the previous two.\n\nBajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations:\n\n- operation \"T\": replace the top number with the sum of both numbers;\n- operation \"B\": replace the bottom number with the sum of both numbers.\n\nIf he performs $n$ operations, starting with \"T\" and then choosing operations alternately (so that the sequence of operations looks like \"TBTBTBTB$...$\"), the last number written will be equal to $f_{n + 1}$.\n\nUnfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute $f_{7}$, then he would want to do $n = 6$ operations: \"TBTBTB\". If he instead performs the sequence of operations \"TTTBBT\", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations («TT» or «BB»).\n\nYou are given the number $n$ of operations that Bajtek has made in an attempt to compute $f_{n + 1}$ and the number $r$ that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of $n$ operations resulting in $r$ with that number of mistakes.\n\nAssume that Bajtek always correctly starts with operation \"T\".",
    "tutorial": "If you look at the described process backwards, it resembles the Euclidean algorithm a lot. Indeed, if you rewinded a recording of Bajtek's actions, he always takes the larger out of two numbers (say Unable to parse markup [type=CF_TEX] ) and replaces them by $a - b, b$. Since we know one of the final numbers ($r$) we can simply check all numbers between $1$ and $r$ and run a faster version of Euclid's algorithm (one that replaces $a, b$ by $a{\\mathrm{~mod~}}b.b$) for all possibilities for a total runtime of $O(r \\log r)$. This was one of the expected solutions.However, with some insight, it can be seen that this optimization is in fact not neccessary - we can simply simulate the reverse process as described (replacing $a, b$ by $a - b, b$) for all candidates between $1$ and $r$ and the total runtime of our algorithm will remain $O(r \\log r)$. The proof of this fact is left to the reader.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "217",
    "index": "C",
    "title": "Formurosa",
    "statement": "The Bytelandian Institute for Biological Research (BIBR) is investigating the properties of two species of bacteria, named simply 0 and 1. Even under a microscope, bacteria of those two species are very difficult to distinguish. In fact, the only thing the scientists possess that is able to differentiate between them is a plant called Formurosa.\n\nIf the scientists place a sample of colonies of bacteria on each on Formurosa's leaves, it will activate a complicated nutrition process. During that process color of Formurosa changes to reflect the result of a — possibly very complicated — logical formula on the species of bacteria, involving constants and the operators $|$ (OR), $&$ (AND) and $^$ (XOR). If it is 0, the plant will turn red, otherwise — it will turn blue.\n\nFor example, if the nutrition process of Formurosa is described by the formula: $(((?^?)|?)&(1^?))$; then Formurosa has four leaves (the \"?\" signs denote the leaves). If we place $0, 1, 0, 0$ on the respective leaves, the result of the nutrition process will be $(((0^1)|0)&(1^0)) = 1$, therefore the plant will turn blue.\n\nThe scientists have $n$ colonies of bacteria. They do not know their types; the only thing they know for sure is that \\textbf{not all colonies are of the same type}. They want to attempt to determine the bacteria's species by repeated evaluations with Formurosa. During each evaluation they must place exactly one sample on every leaf of the plant. However, they may use multiple samples of one colony during a single evaluation; they can even cover the whole plant with bacteria from one colony!\n\nIs it possible for them to always determine the species of each colony, no matter what they are (assuming they are not all the same)?",
    "tutorial": "One of the major difficulties in this problem is finding an easily formulated condition for when Formurosa can be used to distinguish the bacteria. Let Formurosa's digestive process be a function $F(s)$ that maps binary sequences of length $m$ to elements of ${0, 1}$. It turns out that the condition we seek for can be stated as follows: We can distinguish all the bacteria if and only if there exists a sequence $s$ of length $m$ for which $F(s)  \\neq  F( - s)$, where $- s$ is the negation of $s$. First, not that if no such sequence exists, then there is no way to distinguish between zero and one. If such a sequence exists, we can pick any two bacteria $a$ and $b$ and try both ways to substitute them for $0$ and $1$ in the expression. If the two expressions evaluate to different values, we will determine the exact types of both bacteria. Otherwise, we will be certain that the bacteria are of the same type. Repeating the process for all pairs of bacteria will let us identify all the types (since it is guaranteed that not all bacteria are of the same type). To determine whether such a sequence $s$ exists, dynamic programming over the expression tree of Formurosa can be applied. The model solution keeps track for each subtree $G$ of the expression which of the following sequences can be found: a sequence $s$ such that $G(s) = G( - s) = 0$ a sequence $s$ such that $G(s) = G( - s) = 1$ a sequence $s$ such that $G(s)  \\neq  G( - s)$",
    "tags": [
      "divide and conquer",
      "dp",
      "expression parsing"
    ],
    "rating": 2600
  },
  {
    "contest_id": "217",
    "index": "D",
    "title": "Bitonix' Patrol",
    "statement": "Byteland is trying to send a space mission onto the Bit-X planet. Their task is complicated by the fact that the orbit of the planet is regularly patrolled by Captain Bitonix, the leader of the space forces of Bit-X.\n\nThere are $n$ stations around Bit-X numbered clockwise from 1 to $n$. The stations are evenly placed on a circular orbit, so the stations number $i$ and $i + 1$ $(1 ≤ i < n)$, and the stations number 1 and $n$, are neighboring. The distance between every pair of adjacent stations is equal to $m$ space miles. To go on a patrol, Captain Bitonix jumps in his rocket at one of the stations and flies in a circle, covering a distance of at least one space mile, before finishing in some (perhaps the starting) station.\n\nBitonix' rocket moves by burning fuel tanks. After Bitonix attaches an $x$-liter fuel tank and chooses the direction (clockwise or counter-clockwise), the rocket flies exactly $x$ space miles along a circular orbit in the chosen direction. Note that the rocket has no brakes; it is not possible for the rocket to stop before depleting a fuel tank.\n\nFor example, assume that $n = 3$ and $m = 60$ and Bitonix has fuel tanks with volumes of 10, 60, 90 and 100 liters. If Bitonix starts from station 1, uses the 100-liter fuel tank to go clockwise, then uses the 90-liter fuel tank to go clockwise, and then uses the 10-liter fuel tank to go counterclockwise, he will finish back at station 1. This constitutes a valid patrol. Note that Bitonix does not have to use all available fuel tanks. Another valid option for Bitonix in this example would be to simply use the 60-liter fuel tank to fly to either station 2 or 3.\n\nHowever, if $n$ was equal to 3, $m$ was equal to 60 and the only fuel tanks available to Bitonix were one 10-liter tank and one 100-liter tank, he would have no way of completing a valid patrol (he wouldn't be able to finish any patrol exactly at the station).\n\nThe Byteland space agency wants to destroy some of Captain Bitonix' fuel tanks so that he cannot to complete any valid patrol. Find how many different subsets of the tanks the agency can destroy to prevent Captain Bitonix from completing a patrol and output the answer modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Observation 1. Fuel tanks for which capacity gives the same remainder $\\bmod d$ are equivalent for Bitonix's purposes. Moreover, fuel tanks for which the capacities' remainders $\\bmod d$ sum to $D$ are also equivalent. Out of every group of equivalent tanks, the agency can only leave at most one. Observation 2. If more than six tanks remain, Bitonix can certainly complete his patrol. Indeed, let us assume that $7$ tanks were left undestroyed by the agency. Out of the 128 possible subsets of those tanks, at least two distinct ones, say $A$ and $B$, sum up to the same remainders modulo $D$. Thus, if Bitonix moves forward with tanks from $A - B$ and backwards with tanks from $B - A$, he will finish at some station after an actual journey. Because of observations 1 and 2, it turns out that a simple recursive search suffices to solve the problem. However, because of the large constraints, it may prove necessary to use some optimizations, such as using bitmasks for keeping track of what distances Bitonix can cover.",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dfs and similar",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "217",
    "index": "E",
    "title": "Alien DNA",
    "statement": "Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations — each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The mangled copy of the activated continuous subsequence is formed by first joining all the elements at the even positions in that subsequence, and then joining all the elements at the odd ones at the end. That is, if the activated subsequence consists of 11 elements and represented as $s_{1}s_{2}... s_{11}$, its mangled copy is $s_{2}s_{4}s_{6}s_{8}s_{10}s_{1}s_{3}s_{5}s_{7}s_{9}s_{11}$.\n\nFor example, if the original sequence was \"ACTGG\" and the mutation happened on the segment $[2, 4]$ (that is the activated subsequence is \"CTG\"), the mutated DNA is: \"{ACTG\\textbf{TCG}G}\". The mangled copy of the activated subsequence is marked with bold font.\n\nProfessor Bajtocy has written down the original DNA sequence and the mutations that sequentially happened to it, and he now asks you to recover the first $k$ elements of the DNA sequence after all the mutations.",
    "tutorial": "Note that it is easy to determine, looking at only the last mutation, how many letters it adds to the final result. Indeed, if we need to print out the first $k$ letters of the sequence, and the last mutation is $[l, r]$, it suffices to find out the length of the overlap of segments $[1, k]$ and $[r + 1, 2r - l + 1]$. Say that it is $x$. Then, after the next to last mutation, we are only interested in the first $k - x$ letters of the result - the rest is irrelevant, as it will become \"pushed out\" by the elements added in the last mutation. Repeating this reasoning going backwards, we shall find out that we can spend linear time adding letters to the result after every mutation, which turns out to be the main idea needed to solve the problem.",
    "code": "#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <utility>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <cctype>\n#include <string>\n#include <cstring>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n\nusing namespace std;\n\n//BEGINTEMPLATE_BY_ACRUSH_TOPCODER\n#define SIZE(X) ((int)(X.size()))//NOTES:SIZE(\n#define LENGTH(X) ((int)(X.length()))//NOTES:LENGTH(\n#define MP(X,Y) make_pair(X,Y)//NOTES:MP(\ntypedef long long int64;//NOTES:int64\ntypedef unsigned long long uint64;//NOTES:uint64\n#define two(X) (1<<(X))//NOTES:two(\n#define twoL(X) (((int64)(1))<<(X))//NOTES:twoL(\n#define contain(S,X) (((S)&two(X))!=0)//NOTES:contain(\n#define containL(S,X) (((S)&twoL(X))!=0)//NOTES:containL(\nconst double pi=acos(-1.0);//NOTES:pi\nconst double eps=1e-11;//NOTES:eps\ntemplate<class T> inline void checkmin(T &a,T b){if(b<a) a=b;}//NOTES:checkmin(\ntemplate<class T> inline void checkmax(T &a,T b){if(b>a) a=b;}//NOTES:checkmax(\ntemplate<class T> inline T sqr(T x){return x*x;}//NOTES:sqr\ntypedef pair<int,int> ipair;//NOTES:ipair\ntemplate<class T> inline T lowbit(T n){return (n^(n-1))&n;}//NOTES:lowbit(\ntemplate<class T> inline int countbit(T n){return (n==0)?0:(1+countbit(n&(n-1)));}//NOTES:countbit(\n//Numberic Functions\ntemplate<class T> inline T gcd(T a,T b)//NOTES:gcd(\n  {if(a<0)return gcd(-a,b);if(b<0)return gcd(a,-b);return (b==0)?a:gcd(b,a%b);}\ntemplate<class T> inline T lcm(T a,T b)//NOTES:lcm(\n  {if(a<0)return lcm(-a,b);if(b<0)return lcm(a,-b);return a*(b/gcd(a,b));}\ntemplate<class T> inline T euclide(T a,T b,T &x,T &y)//NOTES:euclide(\n  {if(a<0){T d=euclide(-a,b,x,y);x=-x;return d;}\n   if(b<0){T d=euclide(a,-b,x,y);y=-y;return d;}\n   if(b==0){x=1;y=0;return a;}else{T d=euclide(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;return d;}}\ntemplate<class T> inline vector<pair<T,int> > factorize(T n)//NOTES:factorize(\n  {vector<pair<T,int> > R;for (T i=2;n>1;){if (n%i==0){int C=0;for (;n%i==0;C++,n/=i);R.push_back(make_pair(i,C));}\n   i++;if (i>n/i) i=n;}if (n>1) R.push_back(make_pair(n,1));return R;}\ntemplate<class T> inline bool isPrimeNumber(T n)//NOTES:isPrimeNumber(\n  {if(n<=1)return false;for (T i=2;i*i<=n;i++) if (n%i==0) return false;return true;}\ntemplate<class T> inline T eularFunction(T n)//NOTES:eularFunction(\n  {vector<pair<T,int> > R=factorize(n);T r=n;for (int i=0;i<R.size();i++)r=r/R[i].first*(R[i].first-1);return r;}\n//Matrix Operations\nconst int MaxMatrixSize=40;//NOTES:MaxMatrixSize\ntemplate<class T> inline void showMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:showMatrix(\n  {for (int i=0;i<n;i++){for (int j=0;j<n;j++)cout<<A[i][j];cout<<endl;}}\ntemplate<class T> inline T checkMod(T n,T m) {return (n%m+m)%m;}//NOTES:checkMod(\ntemplate<class T> inline void identityMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:identityMatrix(\n  {for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=(i==j)?1:0;}\ntemplate<class T> inline void addMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addMatrix(\n  {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]+B[i][j];}\ntemplate<class T> inline void subMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subMatrix(\n  {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]-B[i][j];}\ntemplate<class T> inline void mulMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulMatrix(\n  { T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize];\n  for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0;\n  for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]+=A[i][k]*B[k][j];}\ntemplate<class T> inline void addModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addModMatrix(\n  {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]+B[i][j],m);}\ntemplate<class T> inline void subModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subModMatrix(\n  {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]-B[i][j],m);}\ntemplate<class T> inline T multiplyMod(T a,T b,T m) {return (T)((((int64)(a)*(int64)(b)%(int64)(m))+(int64)(m))%(int64)(m));}//NOTES:multiplyMod(\ntemplate<class T> inline void mulModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulModMatrix(\n  { T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize];\n  for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0;\n  for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]=(C[i][j]+multiplyMod(A[i][k],B[k][j],m))%m;}\ntemplate<class T> inline T powerMod(T p,int e,T m)//NOTES:powerMod(\n  {if(e==0)return 1%m;else if(e%2==0){T t=powerMod(p,e/2,m);return multiplyMod(t,t,m);}else return multiplyMod(powerMod(p,e-1,m),p,m);}\n//Point&Line\ndouble dist(double x1,double y1,double x2,double y2){return sqrt(sqr(x1-x2)+sqr(y1-y2));}//NOTES:dist(\ndouble distR(double x1,double y1,double x2,double y2){return sqr(x1-x2)+sqr(y1-y2);}//NOTES:distR(\ntemplate<class T> T cross(T x0,T y0,T x1,T y1,T x2,T y2){return (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);}//NOTES:cross(\nint crossOper(double x0,double y0,double x1,double y1,double x2,double y2)//NOTES:crossOper(\n  {double t=(x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);if (fabs(t)<=eps) return 0;return (t<0)?-1:1;}\nbool isIntersect(double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4)//NOTES:isIntersect(\n  {return crossOper(x1,y1,x2,y2,x3,y3)*crossOper(x1,y1,x2,y2,x4,y4)<0 && crossOper(x3,y3,x4,y4,x1,y1)*crossOper(x3,y3,x4,y4,x2,y2)<0;}\nbool isMiddle(double s,double m,double t){return fabs(s-m)<=eps || fabs(t-m)<=eps || (s<m)!=(t<m);}//NOTES:isMiddle(\n//Translator\nbool isUpperCase(char c){return c>='A' && c<='Z';}//NOTES:isUpperCase(\nbool isLowerCase(char c){return c>='a' && c<='z';}//NOTES:isLowerCase(\nbool isLetter(char c){return c>='A' && c<='Z' || c>='a' && c<='z';}//NOTES:isLetter(\nbool isDigit(char c){return c>='0' && c<='9';}//NOTES:isDigit(\nchar toLowerCase(char c){return (isUpperCase(c))?(c+32):c;}//NOTES:toLowerCase(\nchar toUpperCase(char c){return (isLowerCase(c))?(c-32):c;}//NOTES:toUpperCase(\ntemplate<class T> string toString(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}//NOTES:toString(\nint toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt(\nint64 toInt64(string s){int64 r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt64(\ndouble toDouble(string s){double r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toDouble(\ntemplate<class T> void stoa(string s,int &n,T A[]){n=0;istringstream sin(s);for(T v;sin>>v;A[n++]=v);}//NOTES:stoa(\ntemplate<class T> void atos(int n,T A[],string &s){ostringstream sout;for(int i=0;i<n;i++){if(i>0)sout<<' ';sout<<A[i];}s=sout.str();}//NOTES:atos(\ntemplate<class T> void atov(int n,T A[],vector<T> &vi){vi.clear();for (int i=0;i<n;i++) vi.push_back(A[i]);}//NOTES:atov(\ntemplate<class T> void vtoa(vector<T> vi,int &n,T A[]){n=vi.size();for (int i=0;i<n;i++)A[i]=vi[i];}//NOTES:vtoa(\ntemplate<class T> void stov(string s,vector<T> &vi){vi.clear();istringstream sin(s);for(T v;sin>>v;vi.push_bakc(v));}//NOTES:stov(\ntemplate<class T> void vtos(vector<T> vi,string &s){ostringstream sout;for (int i=0;i<vi.size();i++){if(i>0)sout<<' ';sout<<vi[i];}s=sout.str();}//NOTES:vtos(\n//Fraction\ntemplate<class T> struct Fraction{T a,b;Fraction(T a=0,T b=1);string toString();};//NOTES:Fraction\n  template<class T> Fraction<T>::Fraction(T a,T b){T d=gcd(a,b);a/=d;b/=d;if (b<0) a=-a,b=-b;this->a=a;this->b=b;}\n  template<class T> string Fraction<T>::toString(){ostringstream sout;sout<<a<<\"/\"<<b;return sout.str();}\n  template<class T> Fraction<T> operator+(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b+q.a*p.b,p.b*q.b);}\n  template<class T> Fraction<T> operator-(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b-q.a*p.b,p.b*q.b);}\n  template<class T> Fraction<T> operator*(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.a,p.b*q.b);}\n  template<class T> Fraction<T> operator/(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b,p.b*q.a);}\n//ENDTEMPLATE_BY_ACRUSH_TOPCODER\n\nconst int maxL=3<<20;\nconst int maxn=50000+5;\n\nchar s[maxL];\nint k;\nint n,L[maxn],R[maxn];\nchar r[maxL];\n\nclass Segment\n{\npublic:\n\tint L;\n\tchar *s;\n};\nint n_segs;\nSegment segs[maxn<<2];\n\nint split(int pos)\n{\n\tfor (int i=0;i<n_segs;i++)\n\t\tif (pos==0)\n\t\t{\n\t\t\tn_segs++;\n\t\t\tfor (int k=n_segs-1;k>i;k--) segs[k]=segs[k-1];\n\t\t\treturn i;\n\t\t}\n\t\telse if (segs[i].L<=pos)\n\t\t\tpos-=segs[i].L;\n\t\telse\n\t\t{\n\t\t\tn_segs+=2;\n\t\t\tfor (int k=n_segs-1;k>i+1;k--) segs[k]=segs[k-2];\n\t\t\tsegs[i+2].L=segs[i].L-pos;\n\t\t\tsegs[i+2].s=segs[i].s+pos;\n\t\t\tsegs[i].L=pos;\n\t\t\treturn i+1;\n\t\t}\n\treturn n_segs++;\n}\nvoid getr(int H,int T)\n{\n\tint L=0;\n\tfor (int i=0;T>=0 && i<n_segs;i++)\n\t\tif (segs[i].L<=H)\n\t\t{\n\t\t\tH-=segs[i].L;\n\t\t\tT-=segs[i].L;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int k=max(0,H);k<segs[i].L && k<=T;k++) r[L++]=segs[i].s[k];\n\t\t\tint D=min(segs[i].L,T);\n\t\t\tH-=D;\n\t\t\tT-=D;\n\t\t}\n}\nvoid construct(int d,int length)\n{\n\tif (d<0) \n\t{\n\t\tSegment key;\n\t\tkey.L=length;\n\t\tkey.s=s+1;\n\t\tsegs[n_segs++]=key;\n\t\treturn;\n\t}\n\tif (R[d]>=length)\n\t{\n\t\tconstruct(d-1,length);\n\t\treturn;\n\t}\n\tint C=R[d]-L[d]+1;\n\tif (R[d]+C>=length)\n\t{\n\t\tconstruct(d-1,R[d]);\n\t\tSegment key;\n\t\tkey.L=length-R[d];\n\t\tkey.s=new char[key.L];\n\t\tint C_2=C/2;\n\t\tint D=(key.L>=C_2)?C:(key.L*2);\n\t\tgetr(L[d],L[d]+D-1);\n\t\tfor (int i=0;i<key.L;i++)\n\t\t\tif (i<C_2)\n\t\t\t\tkey.s[i]=r[i+i+1];\n\t\t\telse\n\t\t\t\tkey.s[i]=r[(i-C_2)<<1];\n\t\tsegs[n_segs++]=key;\n\t}\n\telse\n\t{\n\t\tconstruct(d-1,length-C);\n\t\tint pos=split(R[d]+1);\n\t\tSegment key;\n\t\tkey.L=C;\n\t\tkey.s=new char[C];\n\t\tint C_2=C/2;\n\t\tgetr(L[d],R[d]);\n\t\tfor (int i=0;i<C;i++)\n\t\t\tif (i<C_2)\n\t\t\t\tkey.s[i]=r[i+i+1];\n\t\t\telse\n\t\t\t\tkey.s[i]=r[(i-C_2)<<1];\n\t\tsegs[pos]=key;\n\t}\n}\nint main()\n{\n#ifdef _MSC_VER\n\tfreopen(\"input.txt\",\"r\",stdin);\n#endif\n\tscanf(\"%s%d\",s+1,&k);\n\tscanf(\"%d\",&n);\n\tfor (int i=0;i<n;i++) scanf(\"%d%d\",&L[i],&R[i]);\n\tn_segs=1;\n\tsegs[0].L=1;\n\tsegs[0].s=new char[1];\n\tsegs[0].s[0]=' ';\n\tconstruct(n-1,k);\n\tgetr(0,k);\n\tr[k+1]=0;\n\tprintf(\"%s\n\",r+1);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "219",
    "index": "A",
    "title": "k-String",
    "statement": "A string is called a $k$-string if it can be represented as $k$ concatenated copies of some string. For example, the string \"aabaabaabaab\" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.\n\nYou are given a string $s$, consisting of lowercase English letters and a positive integer $k$. Your task is to reorder the letters in the string $s$ in such a way that the resulting string is a $k$-string.",
    "tutorial": "Count the occurrences of each character. If any character appears a number of times not divisible by K, obviously, there is no solution. Otherwise, form the solution by first making the string B. The string B can be any string with the following property: if some character ch appears q times in the string B, the same character appears q***K** times in the given string. Now, just print that string K times.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "219",
    "index": "B",
    "title": "Special Offer! Super Price 999 Bourles!",
    "statement": "Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.\n\nPolycaprus calculated that the optimal celling price for such scissors would be $p$ bourles. However, he read somewhere that customers are attracted by prices that say something like \"Special Offer! Super price 999 bourles!\". So Polycarpus decided to lower the price a little if it leads to the desired effect.\n\nPolycarpus agrees to lower the price by no more than $d$ bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price.\n\nNote, Polycarpus counts only the trailing nines in a price.",
    "tutorial": "The following observation will help you code the solution: The largest number smaller than p ending with at least k nines is p - p MOD 10^k - 1 If the result turns out to be -1 , you can not reach a positive number with k or more nines. I will not explain the solution in detail - be careful when coding and have all the task statements in mind.",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "219",
    "index": "C",
    "title": "Color Stripe",
    "statement": "A colored stripe is represented by a horizontal row of $n$ square cells, each cell is pained one of $k$ colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to $k$ to repaint the cells.",
    "tutorial": "There are two cases to consider , when K=2 and when K>2. For K=2 there are only two possible solutions: the string \"ABABAB...\" and \"BABABA...\" For both strings, simply count the number of differences between it and the given string and print a string with fewer differences. For K>2 , decompose the string into contiguous single-colored sequences. Observe one such sequence. If it has an odd number of characters, say 2m+1, replace m characters with some other character in the following fashion: AAAAA becomes ABABA It can be observed that by changing less than m characters doesn't remove all pairs of adjacent identical characters. Similarly, for sequences of even length, say 2m characters, observe a character in the original string right after the last character of the observed sequence, and choose a character different from both. Example: AAAAAAB becomes ACACACB Again, it is sufficient and necessary to change m characters.",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "219",
    "index": "D",
    "title": "Choosing Capital for Treeland",
    "statement": "The country Treeland consists of $n$ cities, some pairs of them are connected with unidirectional roads. Overall there are $n - 1$ roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.\n\nThe council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city $a$ is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city $a$ to any other city. For that some roads may have to be inversed.\n\nHelp the elders to choose the capital so that they have to inverse the minimum number of roads in the country.",
    "tutorial": "Arbitrarily root the tree at some vertex, say vertex 1. Now, all the edges are oriented either up (towards the root) or down (away from it). We will call upwards oriented edges red, and downwards oriented edges green. Now, with a single depth-first search, for each vertex, calculate its distance from the root (in number of edges) and the number of red edges along the path to the root. Also, count the number of red edges in the entire tree. Now comes the interesting part: Observe that all edges outside the path from the root to vert should turn green, and those on the path should turn red. The number of edges that need to be flipped if vert is chosen as a capital is given by: RedEntireTree - 2*RedOnPath[vert] + RootDistance[vert]",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "219",
    "index": "E",
    "title": "Parking Lot",
    "statement": "A parking lot in the City consists of $n$ parking spaces, standing in a line. The parking spaces are numbered from 1 to $n$ from left to right.\n\nWhen a car arrives at the lot, the operator determines an empty parking space for it. For the safety's sake the chosen place should be located as far from the already occupied places as possible. That is, the closest occupied parking space must be as far away as possible. If there are several such places, then the operator chooses the place with the minimum index from them. If all parking lot places are empty, then the car gets place number $1$.\n\nWe consider the distance between the $i$-th and the $j$-th parking spaces equal to $4·|i - j|$ meters.\n\nYou are given the parking lot records of arriving and departing cars in the chronological order. For each record of an arriving car print the number of the parking lot that was given to this car.",
    "tutorial": "Use a heap to maintain sequences of empty parking spaces as intervals. The comparison function for such intervals should return an interval which could store a car farthest from any other car, and if there is a tie, it should return the leftmost such interval. When inserting a car, pop the heap, look at the interval, place a car in the corresponding space and push two new intervals onto the heap. When removing a car, you should be able to find the two intervals which end at that car, remove them from the heap and push a new interval which forms when the two merge.",
    "tags": [
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "220",
    "index": "A",
    "title": "Little Elephant and Problem",
    "statement": "The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array $a$ of length $n$ and possibly swapped some elements of the array.\n\nThe Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array $a$, only if array $a$ can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.\n\nHelp the Little Elephant, determine if he could have accidentally changed the array $a$, sorted by non-decreasing, himself.",
    "tutorial": "There are multiple possible solutions for this problem. For example, the following. Find the last index $x$ such that there exists some $y$ $(y < x)$ (minimal possible) that $A_{x}$ < $A_{y}$. Then you just need to try two possibilities - either swap $A_{x}$ and $A_{y}$, or don't change anything.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "220",
    "index": "B",
    "title": "Little Elephant and Array",
    "statement": "The Little Elephant loves playing with arrays. He has array $a$, consisting of $n$ positive integers, indexed from 1 to $n$. Let's denote the number with index $i$ as $a_{i}$.\n\nAdditionally the Little Elephant has $m$ queries to the array, each query is characterised by a pair of integers $l_{j}$ and $r_{j}$ $(1 ≤ l_{j} ≤ r_{j} ≤ n)$. For each query $l_{j}, r_{j}$ the Little Elephant has to count, how many numbers $x$ exist, such that number $x$ occurs exactly $x$ times among numbers $a_{lj}, a_{lj + 1}, ..., a_{rj}$.\n\nHelp the Little Elephant to count the answers to all queries.",
    "tutorial": "This problem can be solve in simpler $O(NsqrtN)$ solution, but I will describe $O(NlogN)$ one. We will solve this problem in offline. For each $x$ $(0  \\le  x < n)$ we should keep all the queries that end in $x$. Iterate that $x$ from 0 to $n - 1$. Also we need to keep some array $D$ such that for current $x$ $D_{l} + D_{l + 1} + ... + D_{x}$ will be the answer for query $[l;x]$. To keep $D$ correct, before the processing all queries that end in $x$, we need to update $D$. Let $t$ be the current integer in $A$, i. e. $A_{x}$, and vector $P$ be the list of indices of previous occurences of $t$ (0-based numeration of vector). Then, if $|P|  \\ge  t$, you need to add $1$ to $D_{P[|P| - t]}$, because this position is now the first (from right) that contains exactly $t$ occurences of $t$. After that, if $|P| > t$, you need to subtract $2$ from $D_{P[|P| - t - 1]}$, in order to close current interval and cancel previous. Finally, if $|P| > t + 1$, then you need additionally add $1$ to $D_{P[|P| - t - 2]}$ to cancel previous close of the interval.",
    "tags": [
      "constructive algorithms",
      "data structures"
    ],
    "rating": 1800
  },
  {
    "contest_id": "220",
    "index": "C",
    "title": "Little Elephant and Shifts",
    "statement": "The Little Elephant has two permutations $a$ and $b$ of length $n$, consisting of numbers from 1 to $n$, inclusive. Let's denote the $i$-th $(1 ≤ i ≤ n)$ element of the permutation $a$ as $a_{i}$, the $j$-th $(1 ≤ j ≤ n)$ element of the permutation $b$ — as $b_{j}$.\n\nThe distance between permutations $a$ and $b$ is the minimum absolute value of the difference between the positions of the occurrences of some number in $a$ and in $b$. More formally, it's such minimum $|i - j|$, that $a_{i} = b_{j}$.\n\nA cyclic shift number $i$ $(1 ≤ i ≤ n)$ of permutation $b$ consisting from $n$ elements is a permutation $b_{i}b_{i + 1}... b_{n}b_{1}b_{2}... b_{i - 1}$. Overall a permutation has $n$ cyclic shifts.\n\nThe Little Elephant wonders, for all cyclic shifts of permutation $b$, what is the distance between the cyclic shift and permutation $a$?",
    "tutorial": "Each of the shifts can be divided into two parts - the right (the one that starts from occurrence 1) and the left (the rest of the elements). If we could keep minimal distance for each part, the minimal of these numbers will be the answers for the corresponding shift. Lets solve the problems of the right part, the left will be almost the same. Let we have some shift, for example $34567[12]$ and the permutation $A$ is $4312765$ and $B$ is $2145673$, then shifted $B$ is $4567321$. Let we keep two sets ($S1$ and $S2$). The first will keep all the distances from integers in current left part to the corresponding positions in $A$ (for the example above, it is \\texttt{2, 4}). When you come to the next shift, all integers in $S1$ should be decreased by 1 (that is because all distances are also decreased by 1). But now some integers in set may be negative, when any negative integer occures (it always will be -1) you need to delete it from $S1$ and put 1 to the $S2$. Also after shifting to the next shifts, all integers in $S2$ must be increase by 1. After that, for any shift, the answer will be minimum from the smallest numbers in $S1$ and $S2$. It was very useful to use standart \"set\" in C++.",
    "tags": [
      "data structures"
    ],
    "rating": 2100
  },
  {
    "contest_id": "220",
    "index": "D",
    "title": "Little Elephant and Triangle",
    "statement": "The Little Elephant is playing with the Cartesian coordinates' system. Most of all he likes playing with integer points. The Little Elephant defines an integer point as a pair of integers $(x; y)$, such that $0 ≤ x ≤ w$ and $0 ≤ y ≤ h$. Thus, the Little Elephant knows only $(w + 1)·(h + 1)$ distinct integer points.\n\nThe Little Elephant wants to paint a triangle with vertexes at integer points, the triangle's area must be a positive integer. For that, he needs to find the number of groups of three points that form such triangle. At that, the order of points in a group matters, that is, the group of three points $(0;0)$, $(0;2)$, $(2;2)$ isn't equal to the group $(0;2)$, $(0;0)$, $(2;2)$.\n\nHelp the Little Elephant to find the number of groups of three integer points that form a nondegenerate triangle with integer area.",
    "tutorial": "Let iterate all possible points that, as we consider, must be the first point. Let it be $(x;y)$. Let the second and the third points be $(x1;y1)$ and $(x2;y2)$. Then the doubled area is $|(x1 - x)(y2 - y) - (x2 - x)(y1 - y)|$. We need this number to be even and nonzero. For first we will find the number of groups of points that are even, after that just subtract the number of groups with area equal to zero. For the first subproblem, we need to rewrite our formula. It is equal to $|x(y1 - y2) + y(x2 - x1)|$. Since we know $x$ and $y$ and we just need to check parity, we can try all possible $2^{4}$ values of parity of $x1$, $y1$, $x2$ and $y2$ (let it be $d0$, $d1$, $d2$ and $d3$, respectively). And check whether they will form a $0$ after multiplications and taking modulo $2$. If it froms a $0$, then add to the answer value $cx_{d0}cy_{d1}cx_{d2}cy_{d3}$, where $cx_{d}$ is equal to the number of integers between $0$ and $n$, inclusve, that modulo $2$ are equal $d$. $cy_{d}$ is the same but in range $[0..m]$. Now we need to subtract bad groups - the ones that has the area equal to zero. This means that they will either form a dot or a segment. If it is segment, we can just iterate $dx = |x1 - x2|$ and $dy = |y1 - y2|$ instead of all 4 coordinates. Then the number of such segments on the plane will be $(n - dx + 1)(m - dy + 1)$. Also for counting the number of triples of points on the segment you need to find the number of integer coordinates on the segment. It is well-know problem, and the answer is $gcd(dx, dy) + 1$. This gives us, with some simple optimizations, and $O(nm)$ solution.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "220",
    "index": "E",
    "title": "Little Elephant and Inversions",
    "statement": "The Little Elephant has array $a$, consisting of $n$ positive integers, indexed from 1 to $n$. Let's denote the number with index $i$ as $a_{i}$.\n\nThe Little Elephant wants to count, how many pairs of integers $l$ and $r$ are there, such that $1 ≤ l < r ≤ n$ and sequence $b = a_{1}a_{2}... a_{l}a_{r}a_{r + 1}... a_{n}$ has no more than $k$ inversions.\n\nAn \\underline{inversion} in sequence $b$ is a pair of elements of the sequence $b$, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers $i$ and $j$, such that $1 ≤ i < j ≤ |b|$ and $b_{i} > b_{j}$, where $|b|$ is the length of sequence $b$, and $b_{j}$ is its $j$-th element.\n\nHelp the Little Elephant and count the number of the described pairs.",
    "tutorial": "In this problems you can use a method of two pointers. Also some RMQ are required. If you do not know about RMQ, please, read about it in the Internet before solving this problem. Firstly, map all the elements in the input array. After that all of them will be in range $[0..n - 1]$. We need to keep two RMQs, both of size $n$. Let the first RMQ be $Q1$ and the second $Q2$. $Q1_{i}$ will contain the number of numbers $i$ in current left subarray. $Q2_{i}$ will contain the number of numbers $i$ in the left subarray. Firstly, add all $n$ number to the $Q2$. After that iterate some pointer $r$ from $n - 1$ downto $1$, by the way keeping point $l$ (which, at the beggining, is equal to $n - 1$) Using RMQs, you can keep the number of inversions when you decrease $r$ or $l$ (using \"sum on the range\" operation). While the current number of inversions is more then $k$ and $l  \\ge  0$, decrease $l$. Then for each $r$ the answer of correct $l$ will be $l + 1$ (considering 0-based numeration). This makes the algorithm working in $O(NlogN)$ time with correct realisation.",
    "tags": [
      "data structures",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "221",
    "index": "A",
    "title": "Little Elephant and Function",
    "statement": "The Little Elephant enjoys recursive functions.\n\nThis time he enjoys the sorting function. Let $a$ is a permutation of an integers from 1 to $n$, inclusive, and $a_{i}$ denotes the $i$-th element of the permutation. The Little Elephant's recursive function $f(x)$, that sorts the first $x$ permutation's elements, works as follows:\n\n- If $x = 1$, exit the function.\n- Otherwise, call $f(x - 1)$, and then make $swap(a_{x - 1}, a_{x})$ (swap the $x$-th and $(x - 1)$-th elements of $a$).\n\nThe Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to $n$, such that after performing the Little Elephant's function (that is call $f(n)$), the permutation will be sorted in ascending order.",
    "tutorial": "In this problems you should notice that the answer for the problem is always of the following form: $n$, 1, 2, 3, ..., $n$-1. In such case array will be always sorted after the end of the algorithm.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "221",
    "index": "B",
    "title": "Little Elephant and Numbers",
    "statement": "The Little Elephant loves numbers.\n\nHe has a positive integer $x$. The Little Elephant wants to find the number of positive integers $d$, such that $d$ is the divisor of $x$, and $x$ and $d$ have at least one common (the same) digit in their decimal representations.\n\nHelp the Little Elephant to find the described number.",
    "tutorial": "Here you just need to find all divisors of $n$. This can be done using standart algorithm with iterating from 1 to $sqrt(n)$. After that you need to write some function that checks whether two numbers has same digits. This also can be done using simple loops.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "222",
    "index": "A",
    "title": "Shooshuns and Sequence ",
    "statement": "One day shooshuns found a sequence of $n$ integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:\n\n- Find the number that goes $k$-th in the current sequence and add the same number to the end of the sequence;\n- Delete the first number of the current sequence.\n\nThe shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.",
    "tutorial": "Note that the k-th element is copied to the end. Then the (k+1)-th element from the initial sequence is copied, then (k+2)-th,  \\dots  , n-th, k-th, (k+1)-th, etc. So all the numbers on the blackboard will become equal if and only if all the numbers from the k-th to the n-th in the initial sequence were equal. It's now also obvious that the number of operations needed for it is equal to the index of the last number that is not equal to the n-th element of the initial sequence, because it's exactly the number of deletions needed to eliminate the elements that are not equal to the last one. If this number is greater than k, than answer is -1. Complexity - O(n).",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "222",
    "index": "B",
    "title": "Cosmic Tables",
    "statement": "The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement.\n\nUCDHP stores some secret information about meteors as an $n × m$ table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries:\n\n- The query to swap two table rows;\n- The query to swap two table columns;\n- The query to obtain a secret number in a particular table cell.\n\nAs the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.",
    "tutorial": "Let's store the order of the rows and columns of table. Thus, row[x] is the number of the row x in the initial table and column[x] is the number of column x in the initial table. Then, the value of an element in the row x and column y in the current table is equal to t[row[x], column[y]], where t - initial table. When we get the update request, we need to swap the x-th element and the y-th element in the corresponding array. Complexity - O(n * m + k).",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "222",
    "index": "C",
    "title": "Reducing Fractions",
    "statement": "To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.",
    "tutorial": "Let's factorize the numerator and denominator. Now for each prime integer x we know the extent of x in the factorization of the numerator(a[x]) and the denominator(b[x]). For each prime number x we can calculate the extent of x in the factorization of the numerator and the denominator after reduction : newa[x]=a[x]-min(a[x], b[x]), newb[x]=b[x]-min(a[x],b[x]). We have the numerator and the denominator of the answer in factorized form. Now we have to bring them into the form which is required in the condition. One of the ways to do it is to note that the fraction from the statement satisfies the conditions. We can factorize it again and in the answer we will have the same fraction for which there will not be such a prime x so that the degree of x in answer would be greater than newa[x] or newb[x]. (This operation can be called reduction) The result will satisfy the condition and the fraction will be equal to the required number. If you try to build answer greedily (put factors in the answer till their product <= 10^7), the count of numbers in the answer (n_out or m_out) will be bigger than 10^5. Factorization by O(sqrt(max)) received TL. You should have found a faster way. For example you could have used linear sieve of Eratosthenes. Complexity - O(max + n * log(max)). log(max) is size of factorization.",
    "tags": [
      "implementation",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "222",
    "index": "D",
    "title": "Olympiad",
    "statement": "A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least $x$ points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.\n\nHelp Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.",
    "tutorial": "First of all, note that in any case the best place which Vasya can take is the first place for he can earn maximum points. Now we must find the worst place which Vasya can take. We need to find maximal matching in bipartite graph, where the edge between vertice i from the first part and vertice j from the second part exists if a[i] + b[j] >= x. To solve this task, it is enough just to sort the vertices in both parts of the graph by their weights and use two pointers method. Suppose that we have sorted all the vertices by non-increasing points (a1 >= a2 >= ... >= an). Let's take two pointers - L = 1 in the first part and R = N in the second part. While a[L] + b[R] < x we must decrease R to find the first vertice such a[L] + b[R] >= x. When we found such R, we must add this edge to the answer, i.e. increase the answer, increase L by 1, decrease R by 1. It is easy to show why this algo is correct and it finds the optimal solution. I have discovered a truly marvelous proof of this, but the margins of this analysis are too narrow to for him. Complexity - O(N log N) for sorting and O(N) for two pointers.",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "222",
    "index": "E",
    "title": "Decoding Genome",
    "statement": "Recently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most $m$ different nucleotides, numbered from $1$ to $m$. Special characteristics of the Martian DNA prevent some nucleotide pairs from following consecutively in this chain. For example, if the nucleotide 1 and nucleotide 2 can not follow consecutively in the Martian DNA, then the chain of nucleotides [1, 2] is not a valid chain of Martian DNA, but the chain of nucleotides [2, 1] can be a valid chain (if there is no corresponding restriction). The number of nucleotide pairs that can't follow in the DNA chain consecutively, is $k$.\n\nThe needs of gene research required information about the quantity of correct $n$-long chains of the Martian DNA. Your task is to write a program that will calculate this value.",
    "tutorial": "1) Solution with complexity O(n*m*m), using the dynamic programming: State - d[n][m] - the number of allowed chains of length n that ends in symbol m. Transition - sort out all possible characters, and check if you can put the symbol k after symbol m. 2) Solution with complexity O(m*m*m*log n): Note that the transition in the first solution is always the same. So we can make the transition matrix A of size MxM. If j-th symbol can follow i-th then A[i][j]=1 else A[i][j]=0. Define a vector of size 1xM b={1,1, \\dots ,1}. We can see that b * a^(n-1) = answer. Now we can use fast exponentiation for computing a^(n-1). We should consider the case with n=1 separately. The answer is the sum of numbers in the vector ans. Complexity - O(m^3) from matrix multiplication and O(log n) from fast exponentiation.",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 1900
  },
  {
    "contest_id": "223",
    "index": "A",
    "title": "Bracket Sequence",
    "statement": "A bracket sequence is a string, containing only characters \"(\", \")\", \"[\" and \"]\".\n\nA correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()[]\", \"([])\" are correct (the resulting expressions are: \"(1)+[1]\", \"([1+1]+1)\"), and \"](\" and \"[\" are not. \\textbf{The empty string is a correct bracket sequence by definition.}\n\nA substring $s[l... r]$ $(1 ≤ l ≤ r ≤ |s|)$ of string $s = s_{1}s_{2}... s_{|s|}$ (where $|s|$ is the length of string $s$) is the string $s_{l}s_{l + 1}... s_{r}$. \\textbf{The empty string is a substring of any string by definition}.\n\nYou are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.",
    "tutorial": "You were given a bracket sequence $s$ consisting of brackets of two kinds. You were to find regular bracket sequence that was a substring of $s$ and contains as many <<[>> braces as possible. We will try to determine corresponding closing bracket for every opening one. Formally, let a bracket on the i-th position be opening, then the closing bracket on the position j is corresponding to it if and only if a substring $s_{i}... s_{j}$ is the shortest regular bracket sequence that begins from the i-th position. In common case there can be brackets with no corresponding ones. We scan the sting $s$ and put positions with the opening brackets into a stack. Let us proceed the i-th position. If $s_{i}$ is an opening bracket we simply put $i$ on the top of the stack. Otherwise, we have to clean the stack if the stack is empty or the bracket on the top does not correspond to the current one. But if the bracket on the top is ok we just remove the top of the stack and remember that the bracket on position $i$ is corresponding to the bracket removed from the top. So, we find all the correspondings for all the brackets. Then we can split $s$ into blocks. Let block be a segment $[l, r]$ such that the bracket on the $r$-th position is corresponding for the bracket on the $i$-th and there is no couple of corresponding brackets on positions $x$ and $y$ such that $[l,r]\\in[x,y]$ and $[l, r]  \\neq  [x, y]$. It is easy to understand that the blocks do not intersect and the split is unique. We can join the consequent blocks into the regular bracket sequences. We should join as many blocks as possible in order to get the maximal number of braces. We get several substrings that are regular bracket sequences after we join all the consecutive blocks. The answer is the substring that has the largest amount of braces <<[>>. The complexity is $O(|s|)$.",
    "tags": [
      "data structures",
      "expression parsing",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "223",
    "index": "B",
    "title": "Two Strings",
    "statement": "A subsequence of length $|x|$ of string $s = s_{1}s_{2}... s_{|s|}$ (where $|s|$ is the length of string $s$) is a string $x = s_{k1}s_{k2}... s_{k|x|}$ $(1 ≤ k_{1} < k_{2} < ... < k_{|x|} ≤ |s|)$.\n\nYou've got two strings — $s$ and $t$. Let's consider all subsequences of string $s$, coinciding with string $t$. Is it true that each character of string $s$ occurs in at least one of these subsequences? In other words, is it true that for all $i$ $(1 ≤ i ≤ |s|)$, there is such subsequence $x = s_{k1}s_{k2}... s_{k|x|}$ of string $s$, that $x = t$ and for some $j$ $(1 ≤ j ≤ |x|)$ $k_{j} = i$.",
    "tutorial": "You were given two strings: $s$ and $t$. You were required to examine all occurrences of the string $t$ in the string $s$ as subsequence and to find out if it is true that for each position of the $s$ string there are such occurrence, that includes this position. For each position $i$ of the $s$ string we calculate two values $l_{i}$ and $r_{i}$ where $l_{i}$ is the maximal possible number that the string $t_{1}... t_{li}$ occurs as subsequence in the string $s_{1}... s_{i}$, $r_{i}$ is the maximal possible number that the string $t_{|t| - ri + 1}... t_{|t|}$ occurs in the string $s_{i}... s_{|s|}$ as subsequence. Let us find all of $l$ for the position $1... i - 1$ and want to find $l_{i}$. If the symbol $t_{li - 1 + 1}$ exists and concurs with the symbol $s_{i}$ then $l_{i} = l_{i - 1} + 1$, in other case $l_{i} = l_{i - 1}$. In the same way we can find $r_{i}$ if we move from the end of the string. Now we should check if the position $i$ in the string $s$ belongs to at least one occurrence. Let us assume this to be correct and the symbol $s_{i}$ corresponds to the symbol $t_{j}$ of the string $t$. Then $l_{i - 1}  \\ge  j - 1$ and $r_{i + 1}  \\ge  |t| - j$ by definition of the $l$ and $r$. Then if $j$ exists that $s_{i} = t_{j}$ and $l_{i - 1} + 1  \\ge  j  \\ge  |t| - r_{i + 1}$, then the position $i$ of the string $s$ belongs to at least one occurrence of the $t$, in other case the occurrence doesn't exist. We can easily check it by creating an array $cnt_{a, i}$ for each letter, which is a number of letters $a$ in the positions $1... i$ of the string $t$. The complexity of the solution is $O(|s| + |t|)$.",
    "tags": [
      "data structures",
      "dp",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "223",
    "index": "C",
    "title": "Partial Sums",
    "statement": "You've got an array $a$, consisting of $n$ integers. The array elements are indexed from 1 to $n$. Let's determine a two step operation like that:\n\n- First we build by the array $a$ an array $s$ of partial sums, consisting of $n$ elements. Element number $i$ ($1 ≤ i ≤ n$) of array $s$ equals $s_{i}=\\left(\\sum_{j=1}^{i}a_{j}\\right)\\mathrm{\\mod\\(10^{9}+7)}$. The operation $x mod y$ means that we take the remainder of the division of number $x$ by number $y$.\n- Then we write the contents of the array $s$ to the array $a$. Element number $i$ ($1 ≤ i ≤ n$) of the array $s$ becomes the $i$-th element of the array $a$ ($a_{i} = s_{i}$).\n\nYou task is to find array $a$ after exactly $k$ described operations are applied.",
    "tutorial": "You were given an array $a$ in this problem. You could replace $a$ by the array of its partial sums by one step. You had to find the array after $k$ such steps. All the calculations were modulo $P = 10^{9} + 7$. Write partial sums in following way: $s_{i}=\\sum_{j=1}^{n}B_{i,j}a_{j}$where $B_{i, j} = 1$ if $i  \\ge  j$ and $B_{i, j} = 0$ if $i < j$, for each $1  \\le  i, j  \\le  n$. We can represent $a$ and $s$ as vector-columns, therefore one step corresponds to multiplying matrix $B$ and vector-column $a$. Then the array $a$ after $k$ steps is equal to $B^{k}a$. We can raise a matrix to a power for $O(n^{3}\\log k)$. It is not bad, but not fast enough. We can notice, that $(B^{k})_{i,j}$ = $\\left(B^{k}\\right)_{i-j+1,1}$, i.e. the elements of the matrix $B^{k}$ on diagonals parallel to the main are the equal. It is easy to prove this fact using mathematical induction. You may prove it by yourself. Then we can determine the matrix by an array of numbers $\\left(b^{k}\\right)_{i}=\\left(B^{k}\\right)_{i,1}$, equal to the elements of the first column. The elements of the first column of the product $B^{k}B^{l}$ are equal $\\left(b^{k+l}\\right)_{i}=\\sum_{j=1}^{t}\\left(b^{k}\\right)_{j}\\left(b^{l}\\right)_{i-j+1}$. It is a straight consequence of formula of matrix product. The computing of one element requires $O(n)$ time, there are $n$ elements therefore we can multiply matrices in $O(n^{2})$ time. Then we can solve the problem in $O(n^{2}\\log k)$ time and this solution fits the consrtaints. This problem can be solved faster. We can assure that $\\left(b^{k}\\right)_{i}=C_{k+i-1}^{k-1}$. Let this formula be correct for some $k$. Prove that it is correct for $k + 1$ either. Using the formula of product we get: $\\bigl(b^{k+1}\\bigr)_{i}=\\sum_{j=1}^{i}C_{k+j-1}^{k-1}$ $\\sum_{j=1}^{t}C_{k+j-1}^{k-1}=C_{k}^{k}+C_{k}^{k-1}+\\sum_{j=3}^{t}C_{k+j-1}^{k-1}$ $C_{k}^{k}+C_{k}^{k-1}+\\sum_{j=3}^{t}C_{k+j-1}^{k-1}=C_{k+1}^{k}+C_{k+1}^{k-1}+\\sum_{j=4}^{t}C_{k+j-1}^{k}=\\dots=C_{k+1}^{k}$ Using the formula $C_{n}^{k} = n! / k!(n - k)!$ we can obtain $(b^k)_{i+1} / (b^k)_i = (k+i) / (i+1)$, so we can find all the coefficients $b$ if we can divide modulo $P$. Therefore it is significant that $P$ is prime. Inverse $x$ modulo $P$ is equal to $x^{P-2} \\bmod P$ according to the Fermat little theorem. Therefore we get $O(n^{2})solution$.",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "223",
    "index": "D",
    "title": "Spider",
    "statement": "A plane contains a not necessarily convex polygon without self-intersections, consisting of $n$ vertexes, numbered from 1 to $n$. There is a spider sitting on the border of the polygon, the spider can move like that:\n\n- Transfer. The spider moves from the point $p_{1}$ with coordinates $(x_{1}, y_{1})$, lying on the polygon border, to the point $p_{2}$ with coordinates $(x_{2}, y_{2})$, also lying on the border. The spider can't go beyond the polygon border as it transfers, that is, the spider's path from point $p_{1}$ to point $p_{2}$ goes along the polygon border. It's up to the spider to choose the direction of walking round the polygon border (clockwise or counterclockwise).\n- Descend. The spider moves from point $p_{1}$ with coordinates $(x_{1}, y_{1})$ to point $p_{2}$ with coordinates $(x_{2}, y_{2})$, at that points $p_{1}$ and $p_{2}$ must lie on one vertical straight line ($x_{1} = x_{2}$), point $p_{1}$ must be not lower than point $p_{2}$ ($y_{1} ≥ y_{2}$) and segment $p_{1}p_{2}$ mustn't have points, located strictly outside the polygon (specifically, the segment can have common points with the border).\n\nInitially the spider is located at the polygon vertex with number $s$. Find the length of the shortest path to the vertex number $t$, consisting of transfers and descends. The distance is determined by the usual Euclidean metric $|p_{1}p_{2}|={\\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}}}$.",
    "tutorial": "You were given a polygon consisting of $n$ vertices, you had to find the shortest way from one of its vertices to another. You were allowed to move along the border and go stricktly down without going outside the polygon All the sides of the polygon can be divided into three groups: top, bottom and vertical. The side is vertical if and only if the $x$ coordinates of its ends are equal. The side is bottom if and only if the polygon's interior is above the side. The side it top if and only if the polygon's interior is below the side. We can descend only from points of the top sides to the points of the bottom sides. Vertical sides can be ignored because every descend that has common points with a vertical side can be splitted into two descends and one transfer. One can prove that it is useless to descend from a side's interior to side's interior. Len one of the descends in the optimal solution start in the inner point and end in the inner point. We can slightly change the $x$ coordinate of the descend. The path's lenght is monotonically (possibly not strictly) depends on $x$, so we can move $x$ in order to improve the answer. In case of not strictly monotone dependance the answer do not depend on $x$, so we also can move it. This proof is wrong if the descend passes through a vertex, therefore we have to examine all possible descends from the vertices and to the vertices. We can solve this problem using scan-line method. We well move a vertical straight line from the left to the right and keep set $S$ of the sides that intersect the line. We store the segments in the $S$ in the sorted by $y$ order. Let $X$ be an abscissa of the line. The events happen during the moving: some segments are added to the $S$ set, some are deleted. We can make an array of events, each events is described by its $x$ coordinate that is equal to $X$ of the line when the corresponding event happens, the number of the segment and a kind of event: adding or deleting. There are two events for every side, their $x$ coordinates correspond to abscissas of their ends. The vertical sides can be ignored. Let us proceed the events in non-decreasing order of $x$ coords. If the current event is adding we add the side to $S$ set. Then we check on its closest neighbours in the set. If the current segment is a top segment we can make a descend from its left vertex down to the intersection with it's lower neighbor. We find the point of the intersection, remember the segment where the point is located and remember that there can be a descend from a vertex to the new point. If the current side is the bottom side we make a descand from the upper neighbour to the left end of the current segment and do the same things. If the current event is deleting we analize its neighbours in the same way, but the descends start or end on the right end of the segment we are going to delete. It is important that if there are many events of one kind we should proceed them simultaneously, i.e. if there are many addings in the same $x$ coordinate we must add all the segments and then examine their neighbours. It is the same for deletings: firstly we analize the neighbours for all the segments and only then we delete them. Also in the case of equal $x$ coords of the events the adding events must be first, otherwise the solution is wrong for the case of two angles separated by a vertical line with vertices lying on this line. Set $S$ is easy to keep in container such as \"set\". We have to write a comparator for segments. We can do it in following way: two segments can be in $S$ simultaneously if and only if there is a vertical line that intersects both of them. In common case such a line is not the unique, all the possible values of $X$ are in segment $[l, r]$ that can be easily found if we know the coors of the ends of the segments. Then we can choose an arbitrary $X$ inside of $[l, r]$ and compare the ordinates of the intersection points. Is better to choose inner point because in this case we don't have to examine special cases of segments having a common point. After this we can build a graph. It's vertices are the vertices of the polygon and the ends of possible descends. The edges of the graphs are the sides of the polygon and the descends. The shortest path can be found using Dijkstra algorithm. The complexity of the solution is $O(n\\log n)$.",
    "tags": [
      "geometry",
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "223",
    "index": "E",
    "title": "Planar Graph",
    "statement": "A graph is called planar, if it can be drawn in such a way that its edges intersect only at their vertexes.\n\nAn articulation point is such a vertex of an undirected graph, that when removed increases the number of connected components of the graph.\n\nA bridge is such an edge of an undirected graph, that when removed increases the number of connected components of the graph.\n\nYou've got a connected undirected planar graph consisting of $n$ vertexes, numbered from $1$ to $n$, drawn on the plane. The graph has no bridges, articulation points, loops and multiple edges. You are also given $q$ queries. Each query is a cycle in the graph. The query response is the number of graph vertexes, which (if you draw a graph and the cycle on the plane) are located either inside the cycle, or on it. Write a program that, given the graph and the queries, will answer each query.",
    "tutorial": "In the problem we were given an undirected planar graph without bridges, cutpoints, loops and multiedge laid on the plane. We get requests of the following type: to calculate the number of vertices inside the cycle or on it. Let us take an arbitrary vertex on the border of the graph, for example a vertex that has the least absciss. Let's add a new vertex with an edge to the chosen vertex in such way that the edge is outside the outer border of the graph. We'll call this new vertex a sink. Let's create a $1$ value flow running to the sink from each vertex except the sink. Flow can be created using breadth-first or depth-first search. This operation will take the $O(E)$ time. Let's examine any request. We assume that the cycle is oriented counter-clockwise (if it is not so, we can just reorient it). Let's make a cut on the graph. The first part will contain the vertices laying on the cycle or inside it, the second one - all remaining vertices including the sink. We'll now prove that the flow value through the cut is equal to the vertices number in the first part. It's obvious that we can calculate contribution from every vertex to the flow value independently. Let's assume that the vertex is situated in the first part. A unit flow runs from it to the sink along some path. As soon as this vertex and the sink are situated in different parts the flow passes the edges of the cut an odd number of times, that's why the contribution of this vertex to the flow through the cut is equal to $1$. Let's take now a vertex situated in the second part. As soon as it's situated in the same part as the sink the flow passes the edges of the cut an even number of times, that's why the contribution of this vertex to the flow through the cut is zero. In order to calculate the flow value through the cut we need to sum up flow values passing through the cut's edges. It's important to notice that every edge of the cut is incident to only one vertex lying on the cycle, that's why we can sum up flows passing though edges going outside the cycle for each vertex in the cycle. In order to find all edges going outside the cycle we'll sort all edges going from each vertex counter-clockwise by angle. In this case all edges going outside the cycle will be placed after the previous vertex of the cycle and before the following vertex of the cycle. That's why the sum of flow values over the edges going outside reduces to a sum over an segment which is easily calculated using partial sums. The complexity of the solution is $O(V\\log V)$ for graph sorting plus $(U\\log E)$ for the request where $l$ is the cycle length. There is $\\log E$ in complexity because we have to know a position of a vertex in the adjacency list of another vertex.",
    "tags": [
      "flows",
      "geometry",
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "224",
    "index": "A",
    "title": "Parallelepiped",
    "statement": "You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.",
    "tutorial": "You were given areas of three faces of a rectangular parallelepiped. Your task was to find the sum of lengths of it's sides. Let $a$, $b$ and $c$ be the lengths of the sides that have one common vertex. Then the numbers we are given are $s_{1} = ab$, $s_{2} = bc$ and $s_{3} = ca$. It is easy to find the lengths in terms of faces areas: $a={\\sqrt{s_{1}s_{3}/s_{2}}}$, $b={\\sqrt{s_{1}s_{2}/s_{3}}}$, $c={\\sqrt{s_{2}s_{3}/s_{1}}}$. The answer is $4(a + b + c)$, because there are four sides that have lengths equal to $a$, $b$ and $c$. The complexity is $O(1)$.",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "224",
    "index": "B",
    "title": "Array",
    "statement": "You've got an array $a$, consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Your task is to find a minimal by inclusion segment $[l, r]$ $(1 ≤ l ≤ r ≤ n)$ such, that among numbers $a_{l},  a_{l + 1},  ...,  a_{r}$ there are exactly $k$ distinct numbers.\n\nSegment $[l, r]$ ($1 ≤ l ≤ r ≤ n;$ $l, r$ are integers) of length $m = r - l + 1$, satisfying the given property, is called minimal by inclusion, if there is no segment $[x, y]$ satisfying the property and less then $m$ in length, such that $1 ≤ l ≤ x ≤ y ≤ r ≤ n$. Note that the segment $[l, r]$ doesn't have to be minimal in length among all segments, satisfying the given property.",
    "tutorial": "You were given an array $a$ consisting of $n$ integers. Its elements $a_{i}$ were positive and not greater than $10^{5}$ for each $1  \\le  i  \\le  n$. Also you were given positive integer $k$. You had to find minimal by inclusion segment $[l, r]$ such that there were exactly $k$ different numbers among $a_{l}, ..., a_{r}$. The definition of the \"minimal by inclusion\" you can read in the statement. Let us make a new array $cnt$. In the beginning its element $cnt_{i}$ is equal to number of occurencies of number $i$ in array $a$. It is possible to make this array because elements of $a$ are not very large. Amount of nonzero elements in $cnt$ is equal to amount of different elements in $a$. There is no solution if this number is less then $k$. If it is not true, we have to find the answer segment $[l, r]$. In the beginning let $[l, r] = [1, n]$. We decrease its right end $r$ by 1 until amount of different elements on the segment $[l, r]$ is less than $k$. We can keep the amount of different numbers in following way: we decrease $cnt_{ar}$ by $1$ if we delete element number $r$. Then we have to decrease current number of different elements by $1$ if $cnt_{ar}$ becomes zero. After this we return the last deleted element back to the segment in order to make amount of different elements equal to $k$. Then we have to do the same with the left end $l$, but we have not to decrease but to increase its value by $1$ on each step. Finally, we get a segment $[l, r]$. The amount of different numbers on it is equal to $k$ and on every its subsegment is less than $k$. Therefore, this segment is an answer. The complexity is $O(n)$.",
    "tags": [
      "bitmasks",
      "implementation",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "225",
    "index": "A",
    "title": "Dice Tower",
    "statement": "A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).\n\nAlice and Bob play dice. Alice has built a tower from $n$ dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).\n\nHelp Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.",
    "tutorial": "You should iterate over all dices from up to down and restore answer. You can easily find number of the bottom side of the 1st dice. Using known sides of the 2nd dice you can find pair of numbets on top and bottom side of the 2nd dice. If one of them equal to number on bottom of the 1st dice, you can restore all numbers on the 2n dice. Then using this idea you can try restore numbers on the 3rd dice and so on. If you restored all numbers, you should write YES. If for some dice you cannot uniquely determine order of numbers on the top and botton sides, there will be at least 2 placing of numbers. In this case you shoyld write NO.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "225",
    "index": "B",
    "title": "Well-known Numbers",
    "statement": "Numbers $k$-bonacci ($k$ is integer, $k > 1$) are a generalization of Fibonacci numbers and are determined as follows:\n\n- $F(k, n) = 0$, for integer $n$, $1 ≤ n < k$;\n- $F(k, k) = 1$;\n- $F(k, n) = F(k, n - 1) + F(k, n - 2) + ... + F(k, n - k)$, for integer $n$, $n > k$.\n\nNote that we determine the $k$-bonacci numbers, $F(k, n)$, only for integer values of $n$ and $k$.\n\nYou've got a number $s$, represent it as a sum of several (at least two) \\textbf{distinct} $k$-bonacci numbers.",
    "tutorial": "Firstly you should generate all k-bonacci numbers less than $n$. For $k  \\le  32$ you can do it straightforward, for bigger $k$ you can see that all $k$-bonacci numbers less $10^{9}$ are powers of two only (and 0). So you will have no more then 100 numbers. Then you should use greedy algo. You should substract from $n$ maximal possible $k$-bonacci numbers. You should repeat this operation while $n$ is not decomposed. And in the end you will have answer. Why all numbers will be different? One of possible proves: $F(k, n) = F(k, n - 1) + F(k, n - 2) + ... + F(k, n - k)$ $F(k, n - 1) = F(k, n - 2) + F(k, n - 3) + ... + F(k, n - k - 1)$ You can substract the 2nd equation from the 1st one and you will recieve $F(k, n) + F(k, n - k - 1) = 2F(k, n - 1)$, that equal to $2F(k, n - 1)  \\ge  F(k, n)$. This unequation also holds for $n  \\le  k$. Suppose than greedy also constricted 2 equal numbers $F(k, x)$ in decomposition. But then in virtue of unequation we should take number $F(k, x + 1)$ insead these 2 numbers. Contradiction. But you didn't need prove than greedy algo works, you might believe that it works:)",
    "tags": [
      "binary search",
      "greedy",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "225",
    "index": "C",
    "title": "Barcode",
    "statement": "You've got an $n × m$ pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.\n\nA picture is a barcode if the following conditions are fulfilled:\n\n- All pixels in each column are of the same color.\n- The width of each monochrome vertical line is at least $x$ and at most $y$ pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than $x$ or greater than $y$.",
    "tutorial": "Firstly you should calculate number of white and black pixels in every column. After that you should calculate number of white and black pixels for every prefix in sequence of columns. Now you can calculate number of black or white pixels in every vertical line of any width in $O(1)$. Now you should use dynamic programming. Let's $dp[i][j]$ will store numbers of repainted pixels in prefix from the 1st column to the $j$-th and color of the last column will be white for $i = 0$ and black for $i = 1$. Than you can recalculate $dp$ using forlulas: $dp[0][0] = dp[1][0] = 0$ $d p[0][i]=m i n_{a\\in[x,y]}(d p[1][i-a]+s u m-o f-w h i t e s(i-a+1,i))$ $d p[1][i]=m i n_{a\\in[x,y]}(d p[0][i-a]+s u m-o f-b l a c k s(i-a+1,i))$ Answer will be $min(dp[0][m], dp[1][m])$. This solution works in $O(nm + m * (y - x))$.",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 1700
  },
  {
    "contest_id": "225",
    "index": "D",
    "title": "Snake",
    "statement": "Let us remind you the rules of a very popular game called \"Snake\" (or sometimes \"Boa\", \"Python\" or \"Worm\").\n\nThe game field is represented by an $n × m$ rectangular table. Some squares of the field are considered impassable (walls), all other squares of the fields are passable.\n\nYou control a snake, the snake consists of segments. Each segment takes up exactly one passable square of the field, but any passable square contains at most one segment. All segments are indexed by integers from $1$ to $k$, where $k$ is the snake's length. The $1$-th segment is the head and the $k$-th segment is the tail. For any $i$ ($1 ≤ i < k$), segments with indexes $i$ and $i + 1$ are located in the adjacent squares of the field, that is, these squares share a common side.\n\nOne of the passable field squares contains an apple. The snake's aim is to reach the apple and eat it (that is, to position its head in the square with the apple).\n\nThe snake moves throughout the game. During one move the snake can move its head to an adjacent field square. All other segments follow the head. That is, each segment number $i$ $(1 < i ≤ k)$ moves to the square that has just had segment number $i - 1$. Consider that all segments including the head move simultaneously (see the second test sample). If the snake's head moves to an unpassable square or to the square, occupied by its other segment, the snake dies. That's why we will consider such moves unvalid.\n\nYour task is to determine the minimum number of valid moves that the snake needs to reach the apple.",
    "tutorial": "There is just BFS. State is head place and mask that store place of tail: using 2 bits you can code position of every segment in relation to previous segment. Mask will contain no more than 16 bits, and number of all states will be no more than $4^{8}  \\times  15  \\times  15$ (also you can try understand that number of states no more than $3^{8}  \\times  15  \\times  15$). Then you should just carefully implement it.",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "225",
    "index": "E",
    "title": "Unsolvable",
    "statement": "Consider the following equation:\n\n\\[\nz=\\left[{\\frac{x}{2}}\\right]+y+x y,\n\\]\n\nwhere sign $[a]$ represents the integer part of number $a$.Let's find all integer $z$ $(z > 0)$, for which this equation is unsolvable in positive integers. The phrase \"unsolvable in positive integers\" means that there are no such positive integers $x$ and $y$ $(x, y > 0)$, for which the given above equation holds.\n\nLet's write out all such $z$ in the increasing order: $z_{1}, z_{2}, z_{3}$, and so on $(z_{i} < z_{i + 1})$. Your task is: given the number $n$, find the number $z_{n}$.",
    "tutorial": "You have $z = [x / 2] + y + xy$. That is equivalent to $z = [2k / 2] + y + 2ky$, where $x = 2k, k > 0$ or $z = [(2k + 1) / 2] + y + (2k + 1)y$, where $x = 2k + 1, k  \\ge  0$. $z = k + y + 2ky, k > 0$ or $z = k + y + (2k + 1)y, k  \\ge  0$. Still more steps: $2z + 1 = 2k + 2y + 4ky + 1, k > 0$ or $z + 1 = k + 2y + 2ky + 1, k  \\ge  0$. $2z + 1 = (2k + 1)(2y + 1), k > 0$ or $z + 1 = (2y + 1)(k + 1), k  \\ge  0$. From the 2nd equation you can see than $z$ should be $2^{t} - 1$ because otherwise $z + 1$ will have odd divisor and we can build solution. From the 1st equation you can see that $2^{t + 1} - 1$ should be prime, otherwise we also can build solution. If $z = 2^{t} - 1$ and $2^{t + 1} - 1$ is prime, obliviously there are no solutions. Prime numbers like $2^{a} - 1$ are Mersenne primes. Only about 46 such numbers are found now. Powers of 2 for the firts 40 numbers you can find for example here.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "226",
    "index": "A",
    "title": "Flying Saucer Segments",
    "statement": "An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).\n\nThe flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections.\n\nThe spacecraft team consists of $n$ aliens. Each of them is given a rank — an integer from $1$ to $n$. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section $a$ to section $b$ only if it is senior in rank to all aliens who are in the segments $a$ and $b$ (besides, the segments $a$ and $b$ are of course required to be adjacent). Any alien requires exactly $1$ minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.\n\nAlien $A$ is senior in rank to alien $B$, if the number indicating rank $A$, is more than the corresponding number for $B$.\n\nAt the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.\n\nHelp CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo $m$.",
    "tutorial": "Let $F_{n}$ be the answer for the task, where $n$ is equal to the amount of aliens. Let's assume, that we've solved problem for $n - 1$ aliens, i.e. we know the value of $F_{n - 1}$. Let's try to find value of $F_{n}$. Notice, that the most junior alien in rank will be able to leave the $3^{rd}$ section, if and only if all other aliens are in the $1^{st}$ section. So, now we know first $F_{n - 1}$ actions. Then the most junior alien may go to the $2^{nd}$ section. To make for him entrance to the $1^{st}$ section possible, it's necessary for all other aliens to return to the first one. So, $F_{n - 1}$ more actions are necessary. At last, after the most junior alien will go to the $1^{st}$ section, $F_{n - 1}$ more actions are required for $n - 1$ other aliens to return to the $1^{st}$ section from the $3^{rd}$. So, $F_{n} = F_{n - 1} + 1 + F_{n - 1} + 1 + F_{n - 1}$. It allows to count $F_{n}$ using matrix exponentiation in $O(log n)$, but we'll improve current solution. Let's add $1$ to both parts of the equality and after elementary operations we'll have $F_{n} = 3 \\cdot (F_{n - 1} + 1) - 1$. Now it's easy to solve this reccurence: $F_{n} = 3^{n} - 1$. To count $F_{n}$ quickly you should use binary power method. Solution's complexity - $O(log n)$. Don't forget that if $3^{n}$ $mod$ $m = 0$, answer is equal to $m - 1$, but not $- 1$. And, in conclusion, notice that the task is equal to Hanoi Towers problem with a slight modification (it's impossible to move disks between one pair of rods).",
    "code": "#include <algorithm>\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <cassert>\n#include <cstdio>\n#include <vector>\n#include <cctype>\n#include <string>\n#include <ctime>\n#include <cmath>\n#include <set>\n#include <map>\n\ntypedef long double LD;\ntypedef long long LL;\n\nusing namespace std;\n\n#define sz(A) (A).size()\n#define mp make_pair\n#define pb push_back\n\nint n, m;\n\nLL power(int num, int deg) {\n\tif (!deg)\n\t\treturn 1;\n\n\tif (deg % 2) {\n\t\treturn (power(num, deg - 1) * num) % m;\t\t\n\t}\n\telse {\n\t\tLL sqrt_res = power(num, deg / 2);\n\t\treturn (sqrt_res * sqrt_res) % m;\n\t}\n}\n\nint main() {\n\tcin >> n >> m;\n\tLL res = power(3, n);\n\tres--;\n\tif (res < 0) res += m;\n\tcout << res << endl;\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "226",
    "index": "B",
    "title": "Naughty Stone Piles",
    "statement": "There are $n$ piles of stones of sizes $a_{1}, a_{2}, ..., a_{n}$ lying on the table in front of you.\n\nDuring one move you can take one pile and add it to the other. As you add pile $i$ to pile $j$, the size of pile $j$ increases by the current size of pile $i$, and pile $i$ stops existing. The cost of the adding operation equals the size of the added pile.\n\nYour task is to determine the minimum cost at which you can gather all stones in one pile.\n\nTo add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than $k$ times (after that it can only be added to another pile).\n\nMoreover, the piles decided to puzzle you completely and told you $q$ variants (not necessarily distinct) of what $k$ might equal.\n\nYour task is to find the minimum cost for each of $q$ variants.",
    "tutorial": "Consider the following interpretation of the problem: stone piles are graph vertices. Operation \"add pile $a$ to pile $b$\" changes to operation of suspencion of subtree of vertice $b$ to vertice $a$. Numbers, written on vertices, - piles' sizes. Your task is to get such tree configuration, that each vertice has no more than $k$ subtrees suspended to it, and sum of the products of numbers, written on vertices, and vertices' depth (where root's depth is 0) is minimal. In order to minimize the sum, at first, vertice with a larger number must be not deeply than vertice with smaller number (otherwise it's possible to change them and to get less sum), at second, each inner vertice, besides, maybe, one, has exactly $k$ successors (the second condition is also proved using proof by contradiction). Now you are to learn how to calculate sum (described above) for this configuration quickly. In order do to it, let's sort piles' size array, and then let's do the following: at first, let's add to answer sum of sizes of piles from $1^{st}$ to $k^{th}$ (in 0-indexed array, sorted in non-increasing order), multiplied by 1; then sum of sizes of next $k^{2}$ piles, multiplied by 2; and so on till the end of array. In order to answer for the query about the sum of segment, precalculate sums of prefixes immediately after array sorting. Now in the case $k > 1$ we can find answer in $O(log n)$. If you follow the same considerations for $k = 1$, answer for query will get $O(n)$ operations that's why solution will get TL, if $k$ is equal to $1$ in most of the queries. So you should calculate the answer for $k = 1$ beforehand and memorize it, in order to response such queries in $O(1)$. Complexity - $O(n  \\cdot  log$ $n$ $+$ $q$ $ \\cdot  log$ $n)$.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <cstring>\n#include <cassert>\n#include <cstdlib>\n#include <cstdio>\n#include <vector>\n#include <string>\n#include <cmath>\n#include <set>\n#include <map>\n\nusing namespace std;\n\ntypedef long long LL;\ntypedef long double LD;\n\n#define pb push_back\n#define mp make_pair\n#define sz(A) (int)(A).size()\n\nconst int N = int(1e5 + 5);\n\nLL s[N], a[N];\n\nLL sum(LL l, LL r) {\n\tr = min(r, LL(N - 1)); \n\treturn s[r] - s[l - 1];\n}\n\nint main() {\n\tint n;\n\tcin >> n;\t\n\n\tfor (int i = 0; i < n; i++)\n\t\tcin >> a[i];\n\n\tsort(a, a + n);\n\treverse(a, a + n);\t\n\n\ts[0] = a[0];\n\tfor (int i = 1; i < N; i++)\n\t\ts[i] = s[i - 1] + a[i];\n\n\tint q;\n\tcin >> q;\n\n\tLL res_1 = 0;\n\tfor (int i = 1; i < n; i++) \n\t\tres_1 += a[i] * i;\t\t\n\n\tfor (int i = 0; i < q; i++) {\n\t\tint k;\n\t\tcin >> k;\n\n\t\tif (k == 1) {\n\t\t\tcout << res_1 << \" \";\n\t\t\tcontinue;\n\t\t}\t\n\n\t\tLL res = 0, sz = 1;\n\n\t\tfor (LL j = 1, t = 1; j < n; j += sz, t++) { \n\t\t\tsz *= k;\n\t\t\tcerr << j + sz - 1 << endl;\n\t\t\tres += sum(j, j + sz - 1) * t;\n\t\t}\n\n\t\tcout << res << \" \";\n\t}\n\tcout << endl;\n\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "226",
    "index": "C",
    "title": "Anniversary",
    "statement": "There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.\n\nDima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set $A$, consisting of numbers $l$, $l + 1$, $l + 2$, $...$, $r$; let's consider all its $k$-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.\n\nDima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where $F_{1} = 1$, $F_{2} = 1$, $F_{n} = F_{n - 1} + F_{n - 2}$ for $n ≥ 3$.\n\nDima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by $m$.",
    "tutorial": "At first, let's prove the statement: $GCD(F_{n}, F_{m}) = F_{GCD(n, m)}$. Let's express $F_{n + k}$ using $F_{n}$ and $F_{k}$. We'll get the formula: $F_{n + k} = F_{k} \\cdot F_{n + 1} + F_{k - 1} \\cdot F_{n}$, which is easy to prove by induction. Then use the derived formula and notice, that $GCD(F_{n + k}, F_{n}) = GCD(F_{k}, F_{n})$. Now you are to notice an analogy with Euclidean algorithm and to understand, that we've got necessary equality for $GCD$ of two Fibonacci numbers. So, our current task is to find in the given set subset of $k$ (or at least of $k$) elements with maximal possible $GCD$. To be exactly, to find this $GCD$. Let the answer be equal to $q$. Then $\\left|{\\frac{r}{q}}\\right|$ $-$ $\\textstyle{\\left[{\\frac{L}{q}}\\right]}$$ \\rceil  + 1  \\ge  k$ (1) must be true. Notice, that for each summand from left part of inequality $O($ $\\sqrt{n u m e r a t o r}$ $)$ segments exist, in which its value is constant. Moreover, we can find all these segments and values in $O(\\sqrt{r})$. To be more precise, we are intersted in such $q$, that in the point $q - 1$ value of at least one summand changes (obviously, increases). There are also $O(\\sqrt{r})$ such values. Go over all of them and try to use each of them as the answer (i.e., check inequality (1) for each of them), and choose maximum from all satisfying numbers. The answer always exists, as $q = 1$ is true for any input. So, we've found index of required Fibonacci number. The number itself can be calculated by matrix exponentiation. - $O({\\sqrt{r}}+l o g~r)$.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <cassert>\n#include <complex>\n#include <cstdio>\n#include <vector>\n#include <cctype>\n#include <string>\n#include <ctime>\n#include <cmath>\n#include <set>\n#include <map>\n\ntypedef long double LD;\ntypedef long long LL;\n\nusing namespace std;\n\n#define sz(A) (int)(A).size()\n#define mp make_pair\n#define pb push_back\n\nint m;\nvector<LL> dif_pos;\n\nstruct matr {\n\tLL m[2][2];\n};\n\nmatr operator * (matr a, matr b) {\n\tmatr res;\n\n\tfor (int i = 0; i < 2; i++)\n\t\tfor (int j = 0; j < 2; j++) {\n\t\t\tres.m[i][j] = 0;\n\t\t\tfor (int k = 0; k < 2; k++) {\n\t\t\t\tres.m[i][j] = (res.m[i][j] + a.m[i][k] * b.m[k][j]) % m;\n\t\t\t}\n\t\t}\n\treturn res;\n}\n\nmatr power(matr m, LL p) {\n\tif (p == 1)\n\t\treturn m;\n\tif (p % 2) \n\t\treturn m * power(m, p - 1);\t\n\treturn power(m * m, p / 2);\n}\n\nint fib(LL num) {\n\tif (num == 1)\n\t\treturn 1;\n\tmatr f;\n\tf.m[0][0] = 0;\n\tf.m[0][1] = f.m[1][0] = f.m[1][1] = 1;\n\tf = power(f, num);\n\treturn f.m[0][1];\n}\n\nint main() {\n\tLL l, r, k;\n\n\tcin >> m >> l >> r >> k;\n\n    if(m == 1){\n        cout << 0 << endl;\n        exit(0);\n    }\n\n\n\tfor (LL d = 1; d * d <= r; d++) {\n\t\tLL d2 = r / d;\t\n\t\tdif_pos.pb(d);\t\t\t\t\n\t\tdif_pos.pb(d2);\t\t\t\t\t\t\n\t}\n\t\n\tfor (LL d = 1; d * d <= l; d++) {\n\t\tif (l % d == 0)\n\t\t\tdif_pos.pb(l / d);\n\t\telse {\n\t\t\tif (d) {\n\t\t\t\tdif_pos.pb(l / (d - 1));\n\t\t\t}\n\t\t}\t\t\n\t}\n\n\tLL ans = 0;\n\n\tfor (int i = 0; i < sz(dif_pos); i++) {\n\t\tLL d_b = l / dif_pos[i] + LL(l % dif_pos[i] != 0);\n\t\tLL u_b = r / dif_pos[i];\n\t\tif (u_b - d_b + 1 >= k) \n\t\t\tans = max(ans, dif_pos[i]);\t\t\t\t\t\n\t}\n\tcout << fib(ans) << endl;\n\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "math",
      "matrices",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "226",
    "index": "D",
    "title": "The table",
    "statement": "Harry Potter has a difficult homework. Given a rectangular table, consisting of $n × m$ cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second — in the selected column. Harry's task is to make non-negative the sum of the numbers in each row and each column using these spells.\n\nAlone, the boy can not cope. Help the young magician!",
    "tutorial": "Let's get the required table. Act in the following way: find any row or column with negative sum and invert it. Notice, that sum of numbers in the entire table will always increase (at least, by $2$). It can't increase permanently, because its maximal possible summary change is $200 \\cdot n \\cdot m$. So we'll get the required table anyway. It takes us not more than $100 \\cdot n \\cdot m$ operations (applying of the spell), each of those is performed in $O(n)$ or $O(m)$. So, we've learned how to get required table in not more than ~ $100^{4}$ operations. Now let's restore the answer. It's easy to understand that it will contain those rows and columns, which we've inverted odd times.",
    "code": "#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <queue>\n#include <bitset>\n#include <sstream>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <iostream>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <cstring>\n#include <cassert>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); ++i)\n#define for1(i, n) for(int i = 1; i <= int(n); ++i)\n#define ford(i, n) for(int i = int(n) - 1; i >= 0; --i)\n#define fore(i, l, r) for(int i = int(l); i < int(r); ++i)\n#define sz(v) int((v).size())\n#define all(v) (v).begin(), (v).end()\n#define pb push_back\n#define X first\n#define Y second\n#define mp make_pair\n#define debug(x) {cerr << #x << \" = \" << x << endl;}\ntemplate<typename T> inline T abs(T a){ return ((a < 0) ? -a : a); }\ntemplate<typename T> inline T sqr(T a){ return a * a; }\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int INF = (int)1E9 + 7;\nconst ld EPS = 1E-9;\nconst ld PI = 3.1415926535897932384626433832795;\n\nconst int NMAX = 2000;\n\nint a[NMAX][NMAX], r[NMAX], c[NMAX], mr[NMAX], mc[NMAX];\nint n, m;\n\nint main() {\n    #ifdef myproject\n    freopen(\"input.txt\", \"rt\", stdin);\n    //freopen(\"output.txt\", \"wt\", stdout);\n    #endif\n\n    srand(time(NULL));\n\n    scanf(\"%d%d\", &n, &m);\n//    n = rand()%100+1;\n//    m = rand()%100+1;\n\n    forn(i, n)\n        forn(j, m){\n            scanf(\"%d\", &a[i][j]);\n//            a[i][j] = rand()%100 - 50;\n        }\n\n    forn(i, n){\n        forn(j, m){\n            r[i] += a[i][j];\n            c[j] += a[i][j];\n        }            \n    }\n\n    forn(i, n)\n        mr[i] = 1;\n    forn(j, m)\n        mc[j] = 1;\n\n    #ifdef myproject\n    cout << n << \" \" << m << endl;\n    forn(i, n){\n        forn(j, m){\n            cout << a[i][j]*mr[i]*mc[j] << \" \";            \n        }\n        cout << endl;\n    }\n    #endif\n\n\n    int iter = 0;\n    \n    while(true){\n        \n        iter++;\n\n        int rid = -1;\n        forn(i, n){\n            if(r[i] < 0){\n                rid = i;\n                break;\n            }\n        }\n        \n        if(rid != -1){\n            forn(j, m){\n                c[j] -= a[rid][j] * mr[rid] * mc[j];\n            } \n            mr[rid] *= -1;\n            forn(j, m){\n                c[j] += a[rid][j] * mr[rid] * mc[j];\n            } \n\n            r[rid] *= -1;\n            continue;\n        }\n\n\n        int cid = -1;\n        forn(j, m){\n            if(c[j] < 0){\n                cid = j;\n                break;\n            }\n        }\n\n        if(cid != -1){\n            forn(i, n){\n                r[i] -= a[i][cid] * mc[cid] * mr[i];\n            }\n            mc[cid] *= -1;\n            forn(i, n){\n                r[i] += a[i][cid] * mc[cid] * mr[i];\n            }\n            c[cid] *= -1;\n            continue;\n        }\n\n        break;\n    }\n\n    vector<int> nr(n), nc(m);\n    forn(i, n){\n        forn(j, m){\n            nr[i] += a[i][j] * mr[i] * mc[j];            \n            nc[j] += a[i][j] * mr[i] * mc[j];\n        }\n    }\n\n    assert(*min_element(all(nr)) >= 0);\n    assert(*max_element(all(nc)) >= 0);\n\n    /*\n    cout << endl;\n    forn(i, n){\n        forn(j, m){\n            cout << a[i][j]*mr[i]*mc[j] << \" \";            \n        }\n        cout << endl;\n    }*/\n\n    vector<int> rr, cc;\n    forn(i, n)\n        if(mr[i] == -1)\n            rr.pb(i);\n    forn(j, m)\n        if(mc[j] == -1)\n            cc.pb(j);\n    \n    cout << sz(rr) << \" \";\n    forn(i, sz(rr))\n        cout << rr[i]+1 << \" \";\n    cout << endl;\n    cout << sz(cc) << \" \";\n    forn(i, sz(cc))\n        cout << cc[i]+1 << \" \";\n    cout << endl;\n\n\n    #ifdef myproject\n    cerr << \"Iterations = \" << iter << endl;\n    #endif\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "226",
    "index": "E",
    "title": "Noble Knight's Path",
    "statement": "In Berland each feudal owns exactly one castle and each castle belongs to exactly one feudal.\n\nEach feudal, except one (the King) is subordinate to another feudal. A feudal can have any number of vassals (subordinates).\n\nSome castles are connected by roads, it is allowed to move along the roads in both ways. Two castles have a road between them if and only if the owner of one of these castles is a direct subordinate to the other owner.\n\nEach year exactly one of these two events may happen in Berland.\n\n- The barbarians attacked castle $c$. The interesting fact is, the barbarians never attacked the same castle twice throughout the whole Berlandian history.\n- A noble knight sets off on a journey from castle $a$ to castle $b$ (provided that on his path he encounters each castle not more than once).\n\nLet's consider the second event in detail. As the journey from $a$ to $b$ is not short, then the knight might want to stop at a castle he encounters on his way to have some rest. However, he can't stop at just any castle: his nobility doesn't let him stay in the castle that has been desecrated by the enemy's stench. A castle is desecrated if and only if it has been attacked after the year of $y$. So, the knight chooses the $k$-th castle he encounters, starting from $a$ (castles $a$ and $b$ aren't taken into consideration), that hasn't been attacked in years from $y + 1$ till current year.\n\nThe knights don't remember which castles were attacked on what years, so he asked the court scholar, aka you to help them. You've got a sequence of events in the Berland history. Tell each knight, in what city he should stop or else deliver the sad news — that the path from city $a$ to city $b$ has less than $k$ cities that meet his requirements, so the knight won't be able to rest.",
    "tutorial": "It's easy to guess that castles form a tree. Let's build heavy-light decomposition over it. Moreover, let's build persistent segment tree (with sum as the function) over each path. Tree's vertex will contain $0$, if castle wasn't attacked by barbarians, and $1$ otherwise. Each knight's path should be divided into not more than two subpaths each of them lays on the path from one of the route's end to tree's root (just use lca in order to do it). Now let's solve the problem for each of the subpaths separately. We should sequentially process paths from heavy-light decomposition and single vertices, which lay on subpath. We are going to count the amount of vertices, which was not visited since year $y + 1$ up to the current year, i.e. (in the case of a path of the decomposition) such vertices, that the difference between values in the current version of persistent segment tree and in the version corresponding to year $y$ (use binary search to find required version in the list of versions) is equal to zero (in case with single vertice it's enough to remember time when vertice was visited). As soon as the amount of appropriate vertices become not less than $k$, we should simultaneously walk down in two tree's versions in order to get the answer. If the $k^{th}$ vertex isn't found on the first subpath, you should pay attention on the fact, that as we always go from down to up, we should accurately recalculate required vertex's number, in order to know it's position in the second subpath from down to up. Complexity: $O(m \\cdot log^{2}$ $n)$ - in each query of the first type it can be necessary to update some segment tree, this action takes $O(log$ $n)$ operations; in each query of the second type there are $O(log$ $n)$ decomposition's paths, each of them is processed in $O(log$ $n)$ (firstly, binary search through versions' list, then query to the tree/walking down).",
    "code": "#include <algorithm>\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <cassert>\n#include <complex>\n#include <cstdio>\n#include <vector>\n#include <cctype>\n#include <string>\n#include <ctime>\n#include <cmath>\n#include <set>\n#include <map>\n\ntypedef long double LD;\ntypedef long long LL;\n\nusing namespace std;\n\n#define sz(A) (int)(A).size()\n#define mp make_pair\n#define pb push_back\n\nconst int N = int(1e5 + 5), INF = int(1e9);\n\nstruct node {\n\tint l, r, val;\n\n\tnode() {}\n\n\tnode(int a, int b, int c) {\n\t\tl = a, r = b, val = c;\n\t}\n};\n\nvector<int> graph[N];\nint n, root, m, par[N];\n\nint sz[N], heavy[N], depth[N];\n\nint first[N], t = 0, sz_lca; \npair<int, int> times[2 * N], tree_lca[8 * N];\n\nbool in_decomp[N];\nint num_trees, num_tree_in[N], pos_tree_in[N], sz_ptree[N];\nvector<int> tree[N];\nvector< pair<int, int> > roots[N];\nvector<node> ptree[N];\n\nvoid dfs(int v, int d) {\n\tdepth[v] = d;\n\tsz[v] = 1;\n\n\theavy[v] = -1;\n\tint mx = 0;\n\n\tfor (int i = 0; i < sz(graph[v]); i++) {\n\t\tint to = graph[v][i];\n\t\t\n\t\tif (!first[v]) first[v] = t + 1;\n\t\ttimes[t++] = mp(d, v);\n\n\t\tif (!first[to]) first[to] = t + 1;\n\t\ttimes[t++] = mp(d + 1, to);\n\n\t\tdfs(to, d + 1);\n\n\t\tsz[v] += sz[to];\t\t\n\n\t\tif (sz[to] > mx) {\n\t\t\tmx = sz[to];\n\t\t\theavy[v] = to;\n\t\t}\n\t}\n}\n\nvoid build_lca() {\n\tsz_lca = 1;\n\twhile (sz_lca < t) sz_lca <<= 1;\n\n\tfor (int i = sz_lca; i < sz_lca + t; i++)\n\t\ttree_lca[i] = times[i - sz_lca];\n\n\tfor (int i = sz_lca + t; i < 2 * sz_lca; i++)\t\t\n\t\ttree_lca[i] = mp(INF, -1);\n\n\tfor (int i = sz_lca - 1; i > 0; i--)\n\t\ttree_lca[i] = min(tree_lca[i * 2], tree_lca[i * 2 + 1]);\n}\n\npair<int, int> min_lca(int l, int r, int L, int R, int v) {\n\tif (r <= L || R <= l) return mp(INF, -1);\n\tif (l <= L && R <= r) return tree_lca[v];\n\tint mid = (L + R) / 2;\n\treturn min( min_lca(l, r, L, mid, v * 2), min_lca(l, r, mid, R, v * 2 + 1) );\n}\n\nint lca(int v1, int v2) {\n\tif (first[v1] > first[v2]) swap(v1, v2);\n\treturn min_lca(first[v1], first[v2] + 1, 1, sz_lca + 1, 1).second;\t\t\n}\n\nvoid dfs_heavy(int v) {\n\tif (!in_decomp[v]) {\n\t\tint now = v;\n\t\twhile (now != -1) {\n\t\t\ttree[num_trees].pb(now);\n\t\t\tin_decomp[now] = 1;\n\t\t\tnum_tree_in[now] = num_trees;\n\t\t\tpos_tree_in[now] = sz(tree[num_trees]);\n\t\t\tnow = heavy[now];\n\t\t}\n\t\tnum_trees++;\n\t}\n\n\tfor (int i = 0; i < sz(graph[v]); i++)\n\t\tdfs_heavy(graph[v][i]);\n}\n\nnode create_node(int l, int r, int num_t) {\n\treturn node(l, r, ptree[num_t][l].val + ptree[num_t][r].val);\t\t\n}\n\nint update_ptree(int num_t, int pos, int L, int R, int v, int new_val) {\n\tif (L + 1 == R) {\n\t\tptree[num_t].pb( create_node(0, 0, num_t) );\n\t\tptree[num_t][ sz(ptree[num_t]) - 1 ].val = new_val;\n\t\treturn sz(ptree[num_t]) - 1;\t\t\t\t\n\t}\n\t\n\tint mid = (L + R) / 2;\n\n\tif (pos < mid) {\n\t\tint new_v = update_ptree(num_t, pos, L, mid, ptree[num_t][v].l, new_val);\t\t\n\t\tptree[num_t].pb( create_node(new_v, ptree[num_t][v].r, num_t) );\n\t}\n\telse {\n\t\tint new_v = update_ptree(num_t, pos, mid, R, ptree[num_t][v].r, new_val);\n\t\tptree[num_t].pb( create_node(ptree[num_t][v].l, new_v, num_t) );\n\t}\n\tassert(R - L >= ptree[num_t][sz(ptree[num_t]) - 1].val);\n\treturn sz(ptree[num_t]) - 1;\n}\n\nint sum_ptree(int num_t, int l, int r, int L, int R, int v1, int v2) {\n\tif (r <= L || R <= l) return 0;\n\tif (l <= L && R <= r) return (R - L) - (ptree[num_t][v1].val - ptree[num_t][v2].val);\n\tint mid = (L + R) / 2;\n\treturn sum_ptree(num_t, l, r, L, mid, ptree[num_t][v1].l, ptree[num_t][v2].l) + sum_ptree(num_t, l, r, mid, R, ptree[num_t][v1].r, ptree[num_t][v2].r);\n}\n\nint num_version(int tree, int timer) {\n\tint l = 0, r = sz(roots[tree]);\t\n\twhile (l + 1 < r) {\n\t\tint mid = (l + r) / 2;\n\t\tif (roots[tree][mid].first <= timer)\n\t\t\tl = mid;\n\t\telse\n\t\t\tr = mid;\n\t}\n\treturn l;\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; i++) {\n\t\tscanf(\"%d\", &par[i]);\t\n\n\t\tif (par[i] == 0) \n\t\t\troot = i;\n\t\telse \n\t\t\tgraph[ par[i] ].pb(i);\n\t}\n\n\tdfs(root, 1);\n\n\tbuild_lca();\n\n\tdfs_heavy(root);\t\n\n\tfor (int i = 0; i < num_trees; i++) {\n\t\tint number = sz(tree[i]);\n\t\n\t\tsz_ptree[i] = 1;\n\t\twhile (sz_ptree[i] < number) sz_ptree[i] <<= 1;\n\t\tptree[i].resize(sz_ptree[i] * 2);\n\t\troots[i].pb(mp(0, 1));\n\t\tfor (int j = 1; j < sz_ptree[i]; j++) {\n\t\t\tptree[i][j].l = j * 2;\n\t\t\tptree[i][j].r = j * 2 + 1;\t\t\n\t\t}\n\t\tfor (int j = sz_ptree[i]; j < 2 * sz_ptree[i]; j++) {\n\t\t\tif (j - sz_ptree[i] < number)\n\t\t\t\tptree[i][j].val = 1;\n\t\t\telse\t\n\t\t\t\tptree[i][j].val = 0;\n\t\t}\n\t\tfor (int j = sz_ptree[i] - 1; j > 0; j--) {\n\t\t\tptree[i][j].val = ptree[i][j * 2].val + ptree[i][j * 2 + 1].val;\n\t\t}\n\t}\n\n\tscanf(\"%d\", &m);\n\n\tfor (int i = 0; i < m; i++) {\n\t\tint type;\n\t\tscanf(\"%d\", &type);\n\n\t\tif (type == 1) {\n\t\t\tint v;\n\t\t\tscanf(\"%d\", &v);\n\t\t\tint t_num = num_tree_in[v];\n\t\t\tint prev_sz = sz(roots[t_num]);\n\t\t\troots[t_num].pb(mp(i + 1, update_ptree(t_num, pos_tree_in[v], 1, sz_ptree[t_num] + 1, roots[t_num][prev_sz - 1].second, 0)));\n\t\t}\n\t\telse {\n\t\t\tint v1, v2, k, start;\n\t\t\t\n\t\t\tscanf(\"%d%d%d%d\", &v1, &v2, &k, &start);\n\n\t\t\tint v3 = lca(v1, v2), now;\n\n\t\t\tbool ans_given = 0;\n\n\t\t\tint num_t = num_tree_in[v3];\n\t\t\tint vers = num_version(num_t, start), num_r = sz(roots[num_t]);\n\n\t\t\tint root_val = sum_ptree(num_t, pos_tree_in[v3], pos_tree_in[v3] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second);\n\t\t\tint start_pos = pos_tree_in[v3];\n\t\t\tif (v3 == v2 || v3 == v1)\n\t\t\t\tstart_pos++;\n\n   \t\t\tnow = par[v1];\n   \t\t\twhile (depth[now] >= depth[v3] && now != v2) {\n   \t\t\t\tint num_t = num_tree_in[now], num_r = sz(roots[num_t]), sum = 0;\n   \t\t\t\tint vers = num_version(num_t, start);\n\n   \t\t\t\tif (depth[v3] < depth[ tree[num_t][0] ]) {\t\t\t\t\t\n   \t\t\t\t\tsum = sum_ptree(num_t, 1, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second);\t\t\t\t\t \n   \t\t\t\t}\n   \t\t\t\telse {\n   \t\t\t\t\tsum = sum_ptree(num_t, start_pos, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second);\n   \t\t\t\t}\t\t\t\n   \t\t\t\tif (sum < k) {\n   \t\t\t\t\tk -= sum;\n   \t\t\t\t}\n   \t\t\t\telse {\t \t\t\t\t\t\n   \t\t\t\t\tk = sum - k + 1;\n   \t\t\t\t\tint left_b = 1;\n   \t\t\t\t\tif (num_t == num_tree_in[v3])\n\t\t\t\t\t\tleft_b = start_pos;   \t\t\t\t\t                    \t\n\t\t\t\t\t\t   \t\t\t\t\t\n   \t\t\t\t\tint r1 = roots[num_t][num_r - 1].second, r2 = roots[num_t][vers].second, L = 1, R = sz_ptree[num_t] + 1;\n\n   \t\t\t\t\twhile (L + 1 < R) {\n   \t\t\t\t\t\tint mid = (L + R) / 2;\t\t\t\t\t\t\n\n   \t\t\t\t\t\tif ( sum_ptree(num_t, left_b, pos_tree_in[now] + 1, L, mid, ptree[num_t][r2].l, ptree[num_t][r1].l) < k) {\t\t\t\t\t\t\t\n   \t\t\t\t\t\t\tk -= sum_ptree(num_t, left_b, pos_tree_in[now] + 1, L, mid, ptree[num_t][r2].l, ptree[num_t][r1].l);\t\t\t\t\t\t\t\n   \t\t\t\t\t\t\tr1 = ptree[num_t][r1].r;\n   \t\t\t\t\t\t\tr2 = ptree[num_t][r2].r;\n   \t\t\t\t\t\t\tL = mid;\t\t\t\t\t\t\t\n   \t\t\t\t\t\t}\n   \t\t\t\t\t\telse {\t\t\t\t\t\t\t\n   \t\t\t\t\t\t\tr1 = ptree[num_t][r1].l;\n   \t\t\t\t\t\t\tr2 = ptree[num_t][r2].l;\n   \t\t\t\t\t\t\tR = mid;\n   \t\t\t\t\t\t}\t\n   \t\t\t\t\t}\t\t\t                  \n\n   \t\t\t\t\tprintf(\"%d\n\", tree[num_t][L - 1]);\t\n   \t\t\t\t\tans_given = 1;\n   \t\t\t\t\tbreak;\n   \t\t\t\t}\n\n   \t\t\t\tnow = par[ tree[num_t][0] ];\n   \t\t\t}\n\n\t\t\tif (ans_given) continue;\t\t\t\n\n\t\t\tnow = par[v2];\t\t\t\n\n\t\t\tint sum_path = 0;\n\n\t\t\tif (v3 != v2 && v3 != v1)\n\t\t\t\tk += root_val;\n\n\t\t\twhile (depth[now] >= depth[v3] && now != v1) {\n\t\t\t\tint num_t = num_tree_in[now], num_r = sz(roots[num_t]);\n\t\t\t\tint vers = num_version(num_t, start);\n\n\t\t\t\tif (depth[v3] < depth[ tree[num_t][0] ]) {\n\t\t\t\t\tsum_path += sum_ptree(num_t, 1, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second);\t\t\t\t\t \n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsum_path += sum_ptree(num_t, start_pos, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second);\n\t\t\t\t}\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t\tnow = par[ tree[num_t][0] ];\t\t\t\t\n\t\t\t}\n\n\t\t\tif (sum_path < k) {\n\t\t\t\tprintf(\"-1\n\");\t\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tk = sum_path - k + 1;\n\n\t\t\tnow = par[v2];\n\n\t\t\twhile (depth[now] >= depth[v3] && now != v1) {\n\t\t\t\tint num_t = num_tree_in[now], num_r = sz(roots[num_t]), sum = 0;\n\t\t\t\tint vers = num_version(num_t, start);\n\n\t\t\t\tif (depth[v3] < depth[ tree[num_t][0] ]) {\n\t\t\t\t\tsum = sum_ptree(num_t, 1, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second);\t\t\t\t\t\t \n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tsum = sum_ptree(num_t, start_pos, pos_tree_in[now] + 1, 1, sz_ptree[num_t] + 1, roots[num_t][vers].second, roots[num_t][num_r - 1].second);\n\t\t\t\t}\n\t\t\n\t\t\t\tif (sum < k) {\n\t\t\t\t\tk -= sum;\n\t\t\t\t}\n\t\t\t\telse {\t\t\t\t\t\n\t\t\t\t\tk = sum - k + 1;\n   \t\t\t\t\tint left_b = 1;\n   \t\t\t\t\tif (num_t == num_tree_in[v3])\n\t\t\t\t\t\tleft_b = start_pos;   \t\t\t\t\t                    \t\n\n\t\t\t\t\tint r1 = roots[num_t][num_r - 1].second, r2 = roots[num_t][vers].second, L = 1, R = sz_ptree[num_t] + 1;\n \n\t\t\t\t\twhile (L + 1 < R) {\n\t\t\t\t\t\tint mid = (L + R) / 2;\t\t\t\t\t\t\n\n\t\t\t\t\t\tif ( sum_ptree(num_t, left_b, pos_tree_in[now] + 1, L, mid, ptree[num_t][r2].l, ptree[num_t][r1].l) < k) {\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tk -= sum_ptree(num_t, left_b, pos_tree_in[now] + 1, L, mid, ptree[num_t][r2].l, ptree[num_t][r1].l);\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tr1 = ptree[num_t][r1].r;\n\t\t\t\t\t\t\tr2 = ptree[num_t][r2].r;\n\t\t\t\t\t\t\tL = mid;\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tr1 = ptree[num_t][r1].l;\n\t\t\t\t\t\t\tr2 = ptree[num_t][r2].l;\n\t\t\t\t\t\t\tR = mid;\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}\t\t\t                  \n\n\t\t\t\t\tprintf(\"%d\n\", tree[num_t][L - 1]);\t\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tnow = par[ tree[num_t][0] ];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "227",
    "index": "A",
    "title": "Where do I Turn?",
    "statement": "Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point $C$ and began to terrorize the residents of the surrounding villages.\n\nA brave hero decided to put an end to the dragon. He moved from point $A$ to fight with Gorynych. The hero rode from point $A$ along a straight road and met point $B$ on his way. The hero knows that in this land for every pair of roads it is true that they are either parallel to each other, or lie on a straight line, or are perpendicular to each other. He also knows well that points $B$ and $C$ are connected by a road. So the hero must either turn 90 degrees to the left or continue riding straight ahead or turn 90 degrees to the right. But he forgot where the point $C$ is located.\n\nFortunately, a Brave Falcon flew right by. It can see all three points from the sky. The hero asked him what way to go to get to the dragon's lair.\n\nIf you have not got it, you are the falcon. Help the hero and tell him how to get him to point $C$: turn left, go straight or turn right.\n\nAt this moment the hero is believed to stand at point $B$, turning his back to point $A$.",
    "tutorial": "Let's consider cross product of vectors $\\stackrel{\\longrightarrow}{A B}$ and $\\overline{{B C}}$, which is equal to $\\overline{{{A B_{x}}}}\\cdot\\overline{{{B C_{u}}}}-\\overline{{{A B_{y}}}}\\cdot\\overline{{{B C_{x}}}}$. Sign of cross product defines sign of a sine of oriented angle between vectors (because cross product is also equal to $|\\overline{{{A B}}}|\\cdot|\\overline{{{B C}}}|\\cdot s i n(\\overline{{{A B}}},\\overline{{{B C}}})$), and that sign leads us to the correct answer. If cross product is equal to zero, then $A, B$ and $C$ lay on the same straight line. So the answer is <>. If cross product is more than zero, then answer is <>. And, at last, if it's less than zero, the answer is <>. Also you should notice that the value of cross product doesn't fit 32-bit type, so you have to use 64-bit type in order to avoid integer overflow.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <cassert>\n#include <complex>\n#include <cstdio>\n#include <vector>\n#include <cctype>\n#include <string>\n#include <ctime>\n#include <cmath>\n#include <set>\n#include <map>\n\ntypedef long double LD;\ntypedef long long LL;\n\nusing namespace std;\n\n#define sz(A) (int)(A).size()\n#define mp make_pair\n#define pb push_back\n\nstruct vect {\n\tint x, y;\n\n\tvect() {}\n\n\tvect(int a, int b) {\n\t\tx = a, y = b;\n\t}\n\n\tvoid read() {\n\t\tcin >> x >> y;\n\t}\n};\n\nvect operator - (vect a, vect b) {\n\treturn vect(a.x - b.x, a.y - b.y);\n}\n\nLL operator % (vect a, vect b) {\n\treturn LL(a.x) * b.y - LL(a.y) * b.x;\n}\n\nint main() {\n\tvect a, b, c;\n\ta.read();\n\tb.read();\n\tc.read();\n\n\tvect ab = b - a, bc = c - b;\n\n\tif (ab % bc == 0) {\n\t\tputs(\"TOWARDS\");\n\t}\t\n\telse {\n\t\tif (ab % bc > 0) {\n\t\t\tputs(\"LEFT\");\n\t\t}\n\t\telse {\n\t\t\tputs(\"RIGHT\");\n\t\t}\n\t}\n\t\t\n\treturn 0;\n}",
    "tags": [
      "geometry"
    ],
    "rating": 1300
  },
  {
    "contest_id": "227",
    "index": "B",
    "title": "Effective Approach",
    "statement": "Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.\n\nAccording to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.\n\nVasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the $1$-st one (in this problem we consider the elements of the array indexed from $1$ to $n$) and ending with the $n$-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the $n$-th and ending with the $1$-st one. Sasha argues that the two approaches are equivalent.\n\nTo finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from $1$ to $n$, and generated $m$ queries of the form: find element with value $b_{i}$ in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.\n\nBut the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.",
    "tutorial": "Let's assume that number $t$ is on the $ind_{t}^{th}$ position in the original permutation. Then, obviously, during iterating from left to right this number will be found in $ind_{t}$ comparisons, and during iterating from right to left - in $n - ind_{t} + 1$ comparisons. Let's declare additional array, in $i^{th}$ element of each there will be such number $j$, that $a_{j} = i$. This array allows to process each query in $O(1)$ using formulas referred above. Additional array is built in $O(n)$ during iterating array $a$. So, the final complexity is $O(n + m)$.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <cassert>\n#include <cstdio>\n#include <vector>\n#include <cctype>\n#include <string>\n#include <ctime>\n#include <cmath>\n#include <set>\n#include <map>\n\ntypedef long double LD;\ntypedef long long LL;\n\nusing namespace std;\n\n#define sz(A) (int)(A).size()\n#define mp make_pair\n#define pb push_back\n\nconst int N = int(1e5 + 3);\n\nint n, m, pos[N];\n\nint main() {\n\tscanf(\"%d\", &n);\t\n\tfor (int i = 0; i < n; i++) {\n\t\tint num;\n\t\tscanf(\"%d\", &num);\n\t\tpos[num] = i + 1;\n\t}\t\n\n\tLL sum1 = 0, sum2 = 0;\n\n\tscanf(\"%d\", &m);\t\n\tfor (int i = 0; i < m; i++)\t{\n\t\tint q;\n\t\tscanf(\"%d\", &q);\n\t\tsum1 += pos[q];\n\t\tsum2 += n - pos[q] + 1;\t\t\t\t\n\t}\n\n\tprintf(\"%I64d %I64d\n\", sum1, sum2);\n\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "228",
    "index": "A",
    "title": "Is your horseshoe on the other hoof?",
    "statement": "Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.\n\nFortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.",
    "tutorial": "In this problem you should count different numbers from input $cnt$ and print $4-cnt$. You could do it in different ways. For example, you could use set.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "228",
    "index": "B",
    "title": "Two Tables",
    "statement": "You've got two rectangular tables with sizes $n_{a} × m_{a}$ and $n_{b} × m_{b}$ cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the $i$-th row and the $j$-th column, as $a_{i, j}$; we will define the element of the second table, located at the intersection of the $i$-th row and the $j$-th column, as $b_{i, j}$.\n\nWe will call the pair of integers $(x, y)$ a shift of the second table relative to the first one. We'll call the overlap factor of the shift $(x, y)$ value:\n\n\\[\n\\sum_{i,j}a_{i,j}\\cdot b_{i+x,j+y},\n\\]\n\nwhere the variables $i, j$ take only such values, in which the expression $a_{i, j}·b_{i + x, j + y}$ makes sense. More formally, inequalities $1 ≤ i ≤ n_{a}, 1 ≤ j ≤ m_{a}, 1 ≤ i + x ≤ n_{b}, 1 ≤ j + y ≤ m_{b}$ must hold. If there are no values of variables $i, j$, that satisfy the given inequalities, the value of the sum is considered equal to 0.\n\nYour task is to find the shift with the maximum overlap factor among all possible shifts.",
    "tutorial": "In this problem you should carefully consider every shift $- N < = x, y < = N$, count the answer and find the maximum value. The complexity of solution is $O(N^{4})$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "228",
    "index": "C",
    "title": "Fractal Detector",
    "statement": "Little Vasya likes painting fractals very much.\n\nHe does it like this. First the boy cuts out a $2 × 2$-cell square out of squared paper. Then he paints some cells black. The boy calls the cut out square a fractal pattern. Then he takes a clean square sheet of paper and paints a fractal by the following algorithm:\n\n- He divides the sheet into four identical squares. A part of them is painted black according to the fractal pattern.\n- Each square that remained white, is split into 4 lesser white squares, some of them are painted according to the fractal pattern. Each square that remained black, is split into 4 lesser black squares.\n\nIn each of the following steps step 2 repeats. To draw a fractal, the boy can make an arbitrary positive number of steps of the algorithm. But he need to make at least two steps. In other words step 2 of the algorithm \\textbf{must be done at least once}. The resulting picture (the square with painted cells) will be a fractal. The figure below shows drawing a fractal (here boy made three steps of the algorithm).\n\nOne evening Vasya got very tired, so he didn't paint the fractal, he just took a sheet of paper, painted a $n × m$-cell field. Then Vasya paint some cells black.\n\nNow he wonders, how many squares are on the field, such that there is a fractal, which can be obtained as described above, and which is equal to that square. Square is considered equal to some fractal if they consist of the same amount of elementary not divided cells and for each elementary cell of the square corresponding elementary cell of the fractal have the same color.",
    "tutorial": "This problem could be solved using dynamic programming. State $z[x][y][st][mask]$ means if the square with upper left corner $(x, y)$ is fractal with nesting level $st$ and colors $mask$. The value $z[x][y][st][mask]$ is $0$ or $1$. There are $O(N^{2} \\cdot Log(N) \\cdot 2^{4})$ states in this dynamic programming. The transitions from state to state are rather simple. If $st = 1$ you should fairly check that the square 2*2 with upper left corner $(x, y)$ matches colors of $mask$. If $st > 1$ you should divide the square into four parts and check them separately. If the value in $mask$ in one quarter means black color, you should check that the whole quarter is black. It could be done using partial sums on rectangles using $O(1)$ of time. If the quarter is white, you should check that it is a fractal with nesting level $st - 1$ with the same $mask$. So, there are less than $4$ transitions from every state. To get the answer to the problem you should consider every upper left corner of squares, every mask and every nesting level of fractal and check this square. It is done using your dynamic.",
    "tags": [
      "dp",
      "hashing"
    ],
    "rating": 2000
  },
  {
    "contest_id": "228",
    "index": "D",
    "title": "Zigzag",
    "statement": "The court wizard Zigzag wants to become a famous mathematician. For that, he needs his own theorem, like the Cauchy theorem, or his sum, like the Minkowski sum. But most of all he wants to have his sequence, like the Fibonacci sequence, and his function, like the Euler's totient function.\n\nThe Zigag's sequence with the zigzag factor z is an infinite sequence $S_{i}^{z}$ $(i ≥ 1; z ≥ 2)$, that is determined as follows:\n\n- $S_{i}^{z} = 2$, when $(i\\mathrm{\\boldmath~\\mod~}2(z-1))=0$;\n- $S_{i}^{z}=(i\\mathrm{~\\mod~}2(z-1))$, when $0<(i\\mathrm{~\\mod~2(z-1))\\leq:}$;\n- $S_{i}^{z}=2z-(i{\\mathrm{~~mod~}}2(z-1))$, when $(i\\mathrm{\\boldmath~\\mod~}2(z-1))>z$.\n\nOperation $x\\ {\\mathrm{mod}}\\ y$ means taking the remainder from dividing number $x$ by number $y$. For example, the beginning of sequence $S_{i}^{3}$ (zigzag factor 3) looks as follows: 1, 2, 3, 2, 1, 2, 3, 2, 1.\n\nLet's assume that we are given an array $a$, consisting of $n$ integers. Let's define element number $i$ $(1 ≤ i ≤ n)$ of the array as $a_{i}$. The Zigzag function is function $Z(l,r,z)=\\sum_{i=l}^{r}a_{i}\\cdot S_{i-l+1}^{z}$, where $l, r, z$ satisfy the inequalities $1 ≤ l ≤ r ≤ n$, $z ≥ 2$.\n\nTo become better acquainted with the Zigzag sequence and the Zigzag function, the wizard offers you to implement the following operations on the given array $a$.\n\n- The assignment operation. The operation parameters are $(p, v)$. The operation denotes assigning value $v$ to the $p$-th array element. After the operation is applied, the value of the array element $a_{p}$ equals $v$.\n- The Zigzag operation. The operation parameters are $(l, r, z)$. The operation denotes calculating the Zigzag function $Z(l, r, z)$.\n\nExplore the magical powers of zigzags, implement the described operations.",
    "tutorial": "In this problem we will use that sequence $s$ is cyclic because of its structure. Also, it is important that $2 < = z < = 6$. For every $z$ we will write the sequence $s$ and note that its period is $2 * (z-1)$. So, for every $z$ and modulo $0 < = mod < 2 * (z-1)$ we will build separate segment tree or Fenwick tree. You should be careful with memory, it needs $O(Z \\cdot (2 \\cdot Z) \\cdot N)$ of memory. So, if the query is to update some value, we should update $z$ values of trees with correct modules. If the query is to find sum, we should consider every $2 \\cdot (z-1)$ modules, count the sum and multiply by correct coefficient from sequence $s$. The complexity is $O(Z \\cdot N \\cdot Log(N))$.",
    "tags": [
      "data structures"
    ],
    "rating": 2100
  },
  {
    "contest_id": "228",
    "index": "E",
    "title": "The Road to Berland is Paved With Good Intentions",
    "statement": "Berland has $n$ cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not.\n\nThe King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home.\n\nUnfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters — illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it.\n\nUpon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most $n$ days. Help the king.",
    "tutorial": "This problem can be solved in different ways. It was expected the solution that solved the system of modular equations using Gauss algorithm. Here is another simple solution. The vertices from the result call switched-on. Firstly, note that every vertex should be switched-on no more than once. Then, consider every edge $(x, y)$ of color $c$. We want to make its color $1$. So, if $c = 1$ we should switch on vertices $x$ and $y$ or don't switch them on simultaneously. If $c = 0$ we should switch on $x$ or $y$. So, consider some vertex $v$ and try to switch it on or not. Thus, we can uniquely determine the state of every vertex of the same connected component as $v$. If we face some collision, we can't get the solution, you should print Impossible. The solution can be realized using bfs with complexity $O(N + M)$.",
    "tags": [
      "2-sat",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1900
  },
  {
    "contest_id": "229",
    "index": "A",
    "title": "Shifts",
    "statement": "You are given a table consisting of $n$ rows and $m$ columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.\n\nTo \\underline{cyclically shift} a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row \"00110\" one cell to the right, we get a row \"00011\", but if we shift a row \"00110\" one cell to the left, we get a row \"01100\".\n\nDetermine the minimum number of moves needed to make some table column consist only of numbers 1.",
    "tutorial": "Let's compute the minimum number of operations needed to get all 1s in each of the $m$ columns. For this, traverse each row twice - one time to the left and one time to the right, recording the index of the nearest cell with 1 (in corresponding direction) for each column in this row. Then the number of operations for any particular column is the sum of the computed values over all rows. In turn, the answer to the problem is the minimal value of these sums. The complexity of the solution is $O(nm)$.",
    "code": "#include <algorithm>\n#include <climits>\n#include <iostream>\n\nusing namespace std;\n\nconst int maxn = 100, maxm = 10000;\n\nint d[maxn][maxm];\n\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n\n    int n, m; cin >> n >> m;\n\n    string s; s.reserve(m);\n    for (int i = 0; i < n; i++)\n    {\n        cin >> s;\n\n        size_t pos = s.find('1');\n\n        if (pos == string::npos)\n        {\n            cout << -1 << '\n';\n            return 0;\n        }\n\n        int dist = 0;\n        for (int j = 0; j < m; j++)\n        {\n            if (s[(j+pos)%m] == '1')\n            {\n                dist = 0;\n            }\n            else\n            {\n                dist++;\n            }\n            d[i][(j+pos)%m] = dist;\n        }\n        for (int j = m; j > 0; j--)\n        {\n            if (s[(j+pos)%m] == '1')\n            {\n                dist = 0;\n            }\n            else\n            {\n                dist++;\n            }\n            d[i][(j+pos)%m] = min(d[i][(j+pos)%m], dist);\n        }\n    }\n\n    int res = INT_MAX;\n    for (int i = 0; i < m; i++)\n    {\n        int sum = 0;\n        for (int j = 0; j < n; j++)\n        {\n            sum += d[j][i];\n        }\n        res = min(res, sum);\n    }\n\n    cout << res << '\n';\n}",
    "tags": [
      "brute force",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "229",
    "index": "B",
    "title": "Planets",
    "statement": "Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.\n\nOverall the galaxy has $n$ planets, indexed with numbers from 1 to $n$. Jack is on the planet with index 1, and Apophis will land on the planet with index $n$. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.\n\nIt can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time $t$ another traveller arrives to the planet, Jack can only pass through the stargate at time $t + 1$, unless there are more travellers arriving at time $t + 1$ to the same planet.\n\nKnowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index $n$.",
    "tutorial": "Observe that when we visit some planet, the best strategy is to arrive as early as we can and then wait for the nearest free moment of time to move further. Hence this problem can be solved with the Dijkstra's algorithm by slightly altering the definition of a shortest distance. When we process a planet (meaning that we already know the minimum time needed to reach it), we need to check the array of arrival times for this planet and find the first moment of time in which we can leave this planet - this will be the distance that we will be adding to outgoing paths from this planet. It's clear that we will traverse each array of arrival times no more than once. Additionally, one must pay attention to these cases: when a traveller arrives to planet 1 at time 0 (then Jack has to wait) and when a traveller arrives to planet $n$ at the same time as Jack (then Jack needs not to wait). The complexity of the solution - $O((n+m)\\log n+\\sum_{i=1}^{n}k_{i})$.",
    "code": "#include <algorithm>\n#include <climits>\n#include <iostream>\n#include <set>\n#include <utility>\n#include <vector>\n\nusing namespace std;\n\nconst int maxn = 100000, maxm = 100000;\n\nvector<pair<int, int> > edges[maxn];\nvector<int> times[maxn];\n\nint dist[maxn];\n\nstruct compar\n{\n    bool operator ()(int v1, int v2) const\n    {\n        if (dist[v1] != dist[v2])\n        {\n            return dist[v1] < dist[v2];\n        }\n        else\n        {\n            return v1 < v2;\n        }\n    }\n};\n\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n\n    int n, m; cin >> n >> m;\n\n    for (int i = 0; i < m; i++)\n    {\n        int a, b, c; cin >> a >> b >> c;\n        edges[a-1].push_back(make_pair(b-1, c));\n        edges[b-1].push_back(make_pair(a-1, c));\n    }\n    for (int i = 0; i < n; i++)\n    {\n        int k; cin >> k;\n\n        times[i].resize(k);\n        for (int j = 0; j < k; j++)\n        {\n            cin >> times[i][j];\n        }\n    }\n\n    fill_n(dist+1, n-1, INT_MAX);\n\n    set<int, compar> q;\n    for (int i = 0; i < n; i++)\n    {\n        q.insert(i);\n    }\n\n    while (!q.empty())\n    {\n        int v = *q.begin(); q.erase(q.begin());\n        if (v == n-1 || dist[v] == INT_MAX)\n        {\n            break;\n        }\n\n        vector<int>::const_iterator ti(\n            lower_bound(times[v].begin(), times[v].end(), dist[v]));\n        while (ti != times[v].end() && dist[v] == *ti)\n        {\n            dist[v]++;\n            ++ti;\n        }\n\n        for (int i = 0; i < (int)edges[v].size(); i++)\n        {\n            const pair<int, int>& p = edges[v][i];\n\n            set<int, compar>::iterator qi(q.find(p.first));\n            if (qi != q.end())\n            {\n                if (dist[v] + p.second < dist[p.first])\n                {\n                    q.erase(qi);\n                    dist[p.first] = dist[v] + p.second;\n                    q.insert(p.first);\n                }\n            }\n        }\n    }\n\n    cout << (dist[n-1] < INT_MAX ? dist[n-1] : -1) << '\n';\n}",
    "tags": [
      "binary search",
      "data structures",
      "graphs",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "229",
    "index": "C",
    "title": "Triangles",
    "statement": "Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with $n$ vertices, chooses some $m$ edges and keeps them. Bob gets the ${\\frac{n(n-1)}{2}}-m$ remaining edges.\n\nAlice and Bob are fond of \"triangles\" in graphs, that is, cycles of length 3. That's why they wonder: what total number of triangles is there in the two graphs formed by Alice and Bob's edges, correspondingly?",
    "tutorial": "Let's call Alice's edges simply edges, and Bob's edges the antiedges. For each edge pair of the initial complete graph that pass through the same vertices, assign a weight: for each pair of edges the weight +2, for each pair of edge and antiedge -1 and for each pair of antiedges +2. Now calculate the sum of all the weights. Observe that each Alice's or Bob's triangle adds exactly +6 to the sum, and each combination of three vertices that do not form the triangle in any of the two graphs adds exactly 0 to the sum. The sum itself is calculated by iterating over all vertices and adding the total weight of all the edge pairs that pass through this vertex. If the degree of the vertex is $d$, then we should add $\\left.+2\\cdot{\\binom{d}{2}}-1\\cdot d(n-1-d)+2\\cdot{\\binom{n-1-d}{2}}=\\right.$ $d(d - 1) - d(n - d - 1) + (n - d - 1)(n - d - 2)$ to the final sum. Since each triangle adds +6 to the sum, then the answer is equal to the sum divided by 6. The complexity of the solution is $O(n + m)$.",
    "code": "#include<cstdio>\n\nusing namespace std;\n\nint n, m, d[1000005];\n\nint main() {\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 0; i < m; i++) {\n\t\tint a, b; scanf(\"%d %d\", &a, &b);\n\t\td[a]++;\n\t\td[b]++;\n\t}\n\t\n\tlong long res = 0;\n\tfor(int v = 1; v <= n; v++) {\n\t\tlong long a = d[v], b = n-1-a;\n\t\tres += a*(a-1)+b*(b-1)-a*b;\n\t}\n\tprintf(\"%I64d\n\", res/6);\n}",
    "tags": [
      "combinatorics",
      "graphs",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "229",
    "index": "D",
    "title": "Towers",
    "statement": "The city of D consists of $n$ towers, built consecutively on a straight line. The height of the tower that goes $i$-th (from left to right) in the sequence equals $h_{i}$. The city mayor decided to rebuild the city to make it \\underline{beautiful}. In a \\underline{beautiful} city all towers are are arranged in non-descending order of their height from left to right.\n\nThe rebuilding consists of performing several (perhaps zero) operations. An operation constitutes using a crane to take any tower and put it altogether on the top of some other neighboring tower. In other words, we can take the tower that stands $i$-th and put it on the top of either the $(i - 1)$-th tower (if it exists), or the $(i + 1)$-th tower (of it exists). The height of the resulting tower equals the sum of heights of the two towers that were put together. After that the two towers can't be split by any means, but more similar operations can be performed on the resulting tower. Note that after each operation the total number of towers on the straight line decreases by 1.\n\nHelp the mayor determine the minimum number of operations required to make the city beautiful.",
    "tutorial": "Let's calculate the dynamics d[i][k] - the minimal possible height of the last tower that we can obtain by merging the first $i$ left towers into at least $k$ towers. Assume we already have calculated the dynamics' values for the first $i$ towers. Now we iterate over the all possible tower intervals $[i + 1;j]$; say the sum in the pending interval is equal to $s$. Now we find the greatest $k$ such that d[i][k] is not greater than $s$. Then we update the value of d[j][k+1] to the minimum of $s$ and d[j][k+1]. Notice that when $k$ increases the values d[i][k] do not decrease. Because of that we can iterate over intervals in the decreasing value of $j$, and corresponding $k$ can be found using a single pointer over values of d[i][k]. When we arrive in the position $j$ during the dynamics, some of the d[j][k] values are updated, but some are still not. Using the same observation that along with the increasing of $k$ the values d[j][k] do not decrease as well, we can make a single run over the values of $k$ in the decreasing order and update the dynamics' values as follows: d[j][k] := min(d[j][k], d[j][k+1]). This is done in the beginning of the dynamics' iteration. In the end we can find the greatest $k$ for which there exists an answer among the values of d[n][k]. The answer to the problem then is $n - k$. The complexity of the solution is $O(n^{2})$.",
    "code": "#include<cstdio>\n#include<cstring>\n\nusing namespace std;\n\n#define MAXN 5005\n\nint dp[MAXN][MAXN], inf = 1000000000;\n\nint main() {\n\tint n, a[MAXN];\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; i++) {\n\t\tscanf(\"%d\", &a[i]);\n\t}\n\t\n\tfor(int i = 0; i <= n; i++) {\n\t\tfor(int j = 0; j <= n; j++) {\n\t\t\tdp[i][j] = inf;\n\t\t}\n\t}\n\tdp[0][0] = 0;\n\t\n\tfor(int i = 1; i <= n; i++) {\n\t\tint k = -1, s = 0;\n\t\tfor(int j = i; j <= n; j++) {\n\t\t\ts += a[j];\n\t\t\twhile(k+1<=n && dp[i-1][k+1] <= s) {\n\t\t\t\tk++;\n\t\t\t}\n\t\t\t\n\t\t\tif(k>=0 && dp[j][k+1]>s) {\n\t\t\t\tdp[j][k+1]=s;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(int k = n-1; k >= 0; k--) {\n\t\t\tif(dp[i][k]>dp[i][k+1]) {\n\t\t\t\tdp[i][k]=dp[i][k+1];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint res = inf;\n\tfor(int k = 1; k <= n; k++) {\n\t\tif(dp[n][k] < inf) {\n\t\t\tres = k;\n\t\t}\n\t}\n\t\n\tprintf(\"%d\n\", n-res);\n}",
    "tags": [
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "229",
    "index": "E",
    "title": "Gifts",
    "statement": "Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: \"Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with $n$ gifts, any gifts you wish!\". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for $n$ names of items from the list. If the fish's list has $p$ occurrences of the given name, then the old man can't ask for this name of item more than $p$ times.\n\nThe old man knows that if he asks for $s$ gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose $s$ gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the $n$ names in such a way that he can get $n$ gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.\n\nThe old man wondered, what is the probability that he can get $n$ most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.",
    "tutorial": "First let's establish some facts that we will use in the solution. With how much probability can the fisherman get a particular set of gifts, among which there are $a_{i}$ gifts of $i$-th name? In total there are ${\\binom{k_{1}}{a_{1}}}\\cdot\\ {\\binom{k_{2}}{a_{2}}}\\cdot\\ \\cdot\\ \\cdot\\ \\cdot\\ \\cdot\\ {\\binom{k_{m}}{a_{m}}}$ such sets, since there are exactly $\\binom{k_{i}}{a_{i}}$ subsets of gifts with $i$-th name of size $a_{i}$, and two different names are independent during the gold fish's choice. Then the described particular set of gifts we can get with the probability of $\\displaystyle{\\Bigg(}{\\frac{1}{(a_{1})\\cdot{\\binom{k_{2}}{a_{2}}}}\\cdots{\\binom{k_{m}}{a_{m}}}}$, by asking $a_{i}$ gifts of $i$-th name. Now we know the probability $p$ of obtaining one particular gift set $A$. Now observe that from $p$ we can calculate the probabiltity $p'$ of obtaining the set $A$ along with some one other gift of $x$-th name in constant time. Say there are already $a_{x}$ elements of $x$-th name in $A$. Using the formula from the first paragraph, we can deduce that: $p^{\\prime}\\equiv p:\\frac{1}{\\binom{k_{x}}{a_{x}}}\\cdot\\frac{1}{\\binom{k_{x}}{a_{x}+1}}$ $p^{\\prime}=p\\cdot{\\frac{k_{x}!}{a_{x}!(k_{x}-a_{x})!}}:{\\frac{k_{x}!}{(a_{x}+1)!!(k_{x}-a_{x}-1)!}}$ $p^{\\prime}=p\\cdot{\\frac{a_{x+1}}{k_{x}-a_{x}}}$Let's solve the main problem now. We sort all the gifts in descending order of their prices. It is clear that the fisherman will definitely ask the names of all the gifts among the first $n$ ones whose prices are not equal to the price of the $n$-th gift in the list. Let's say that this set of gifts is the base, and it has $b$ elements. Then there is still $n - b$ unchosen gifts, and we know that all of them will have the price equal to the price of the $n$-th gift in the list. Say the price of the $n$-th gift is $d$, and there are exactly $s$ gifts with the price $d$ (keep in mind that each of them has a different name); also call these gifts dubious. We can also deduce that the fisherman can make $\\binom{s}{l}$ different decisions, where $l = n - b$. So now we have some $s$ dubious gifts with the price of $d$; let's enumerate them in any order. We calculate the dynamics $f(x, y)$ - the cumulative probability of obtaining $n$ most valuable gifts, if there are $x$ chosen from the first $y$ in the list. It is clear that $f(0, 0) = p$, and $f(l, s)$ contains the answer to the problem. Using the coefficients we have deduced earlier, we get two transitions in the dynamics: $f(x+1,y+1)+=f(x,y)\\cdot{\\frac{b_{y}+1}{k_{y}-b_{y}}}\\cdot{\\frac{({\\frac{y}{x+1}})}{({\\frac{y+1}{x+1}})}}=f(x,y)\\cdot{\\frac{b_{y}+1}{k_{y}-b_{y}}}\\cdot{\\frac{x+1}{y+1}}$, if we add $y + 1$-th dubious gift to the set of $x$ chosen among the first $y$ dubious gifts; $f(x,y+1)+=f(x,y)\\cdot{\\frac{(y^{\\circ})}{(y_{\\circ}^{+1})}}=f(x,y)\\cdot{\\frac{y-x+1}{y+1}}$, otherwise, if do not put the $y + 1$-th dubious gift. This dynamics can be computed in $O(t^{2})$ time, where $t$ is the total number of gifts. The complexity of the solution is $O(t\\log t+t^{2})=O(t^{2})$.",
    "code": "#include<cstdio>\n#include<vector>\n#include<algorithm>\n#include<functional>\n#include<iostream>\n#include<iomanip>\n\nusing namespace std;\n\n#define MAXN 1005\n\nint Got[MAXN], Left[MAXN];\nlong double f[MAXN][MAXN];\n\t\nint main() {\n\tint n, m; scanf(\"%d %d\", &n, &m);\n\tvector<pair<int,int> > g;\n\tg.reserve(MAXN);\n\tfor(int i = 0; i < m; i++) {\n\t\tscanf(\"%d\", &Left[i]);\n\t\tfor(int j = 0; j < Left[i]; j++) {\n\t\t\tint c; scanf(\"%d\", &c);\n\t\t\tg.push_back(make_pair(c,i));\n\t\t}\n\t}\n\t\n\tint t = g.size();\n\tsort(g.begin(), g.end(), greater<pair<int,int> >());\n\tint d = g[n-1].first, i;\n\tlong double p = 1;\n\tfor(i = 0; g[i].first != d; i++) {\n\t\tint name = g[i].second;\n\t\tp *= (Got[name]+1.)/(Left[name]?Left[name]:1);\n\t\tGot[name]++;\n\t\tLeft[name]--;\n\t}\n\t\n\tvector<int> id; id.reserve(MAXN);\n\tint l = n-i;\n\tfor(; i<t && g[i].first==d; i++) {\n\t\tid.push_back(g[i].second);\n\t}\n\tint s = id.size();\n\t\n\tlong double Q[MAXN];\n\tfor(int i = 0; i < s; i++) {\n\t\tQ[i] = (Got[id[i]]+1.)/(Left[id[i]]?Left[id[i]]:1);\n\t}\n\t\n\tf[0][0] = p;\n\tfor(int y = 0; y < s; y++) {\n\t\tfor(int x = 0; x <= y; x++) {\n\t\t\tf[x+1][y+1] += f[x][y]*Q[y]*(x+1.)/(y+1.);\n\t\t\tf[x][y+1] += f[x][y]*(y-x+1.)/(y+1.);\n\t\t}\n\t}\n\n\tcout << fixed << setprecision(9) << f[l][s] << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "230",
    "index": "A",
    "title": "Dragons",
    "statement": "Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all $n$ dragons that live on this level. Kirito and the dragons have \\underline{strength}, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals $s$.\n\nIf Kirito starts duelling with the $i$-th ($1 ≤ i ≤ n$) dragon and Kirito's strength is not greater than the dragon's strength $x_{i}$, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by $y_{i}$.\n\nKirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.",
    "tutorial": "Observe that if Kirito fights a dragon whose strength is less than Kirito's strength, then Kirito does not lose anything - in fact, he even gains a nonnegative strength increase. Taking note of this, let's for each step choose some dragon whose strength is less than Kirito's current strength, and fight it. After performing some amount of these steps we'll eventually end up in one of these two situations: either all dragons are slain (then the answer is \"YES\"), or only dragons whose strength is not less than Kirito's strength remain (then the answer is \"NO\"). On each step we can choose a suitable dragon to fight either by searching through all dragons or by sorting the dragons by strength in non-descending order in advance. The complexity of the solution is $O(n^{2})$ or $O(n\\log n)$.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <utility>\n\nusing namespace std;\n\nconst int maxn = 1000;\n\npair<int, int> arr[maxn];\n\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n\n    int s, n; cin >> s >> n;\n\n    for (int i = 0; i < n; i++)\n    {\n        cin >> arr[i].first >> arr[i].second;\n    }\n\n    sort(arr, arr + n);\n\n    for (int i = 0; i < n; i++)\n    {\n        if (s <= arr[i].first)\n        {\n            cout << \"NO\n\";\n            return 0;\n        }\n        else\n        {\n            s += arr[i].second;\n        }\n    }\n    cout << \"YES\n\";\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "230",
    "index": "B",
    "title": "T-primes",
    "statement": "We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer $t$ \\underline{Т-prime}, if $t$ has exactly three distinct positive divisors.\n\nYou are given an array of $n$ positive integers. For each of them determine whether it is Т-prime or not.",
    "tutorial": "It can be shown that only squares of prime numbers are T-primes, and that there are not too many of them - as many as there are prime numbers not greater than ${\\sqrt{10^{12}}}=10^{6}$. Precompute these numbers (using, for example, the sieve of Eratosthenes) and store them in an array or an std::set, then we can answer each query by simply checking whether the number in question is amongst the precomputed numbers. The complexity of the solution is linear in relation to $n$ - $O({\\sqrt{d}}\\log\\log{\\sqrt{d}}+n\\log{\\sqrt{d}})$ or $O({\\sqrt{d}}\\log{\\sqrt{d}}+n\\log{\\sqrt{d}})$, where $d = 10^{12}$ (one can also get a tighter bound).",
    "code": "#include <iostream>\n#include <set>\n\nusing namespace std;\n\nconst int sqrt_lim = 1000001;\n\nset<long long> prime_squares()\n{\n    static bool arr[sqrt_lim];\n\n    for (int i = 2; i*i < sqrt_lim; i++)\n    {\n        if (!arr[i])\n        {\n            for (int j = i*i; j < sqrt_lim; j += i)\n            {\n                arr[j] = true;\n            }\n        }\n    }\n\n    set<long long> res;\n    for (int i = 2; i < sqrt_lim; i++)\n    {\n        if (!arr[i])\n            res.insert((long long)i * i);\n    }\n    return res;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n\n    set<long long> sq(prime_squares());\n\n    int n; cin >> n;\n    for (int i = 0; i < n; i++)\n    {\n        long long x; cin >> x;\n\n        if (sq.find(x) != sq.end())\n        {\n            cout << \"YES\n\";\n        }\n        else\n        {\n            cout << \"NO\n\";\n        }\n    }\n}",
    "tags": [
      "binary search",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "231",
    "index": "A",
    "title": "Team",
    "statement": "One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.\n\nThis contest offers $n$ problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.",
    "tutorial": "It is needed just to implement actions described in statement. You had to read data and to calculate number of members of team, which were sure about the solution, for every task. If this number is greater than one, the answer must be increased by one.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "231",
    "index": "B",
    "title": "Magic, Wizardry and Wonders",
    "statement": "Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.\n\nThis morning he has $n$ cards with integers lined up in front of him. Each integer is not less than 1, but not greater than $l$. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.\n\nSuppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.\n\nPlease note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than $l$, the numbers on the appearing cards can be anything, no restrictions are imposed on them.\n\nIt is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were $n$ cards, they contained integers from 1 to $l$, and after all magical actions he was left with a single card containing number $d$.\n\nHelp Vasya to recover the initial set of cards with numbers.",
    "tutorial": "Let's see, what will be the last number of array after $i$ iterations. After the first iteration it will be $a_{n - 1}-a_{n}$ (and total number of elements will be decreased by one). After the second iteration the last number will be $a_{n - 2}-a_{n - 1} + a_{n}$. It is not hard to see, that after $n - 1$ iterations remain $a_{1}-a_{2} + a_{3}-a_{4} + ... + ( - 1)^{n + 1} \\cdot a_{n}$. In a such way, our task is to put numbers from $1$ to $l$ in array so, that sum of numbers in odd positions minus sum of numbers in even positions will equal to given $d$. This means sum of numbers in odd positions must be equal $s=d+a_{2}+a_{4}+\\cdot\\cdot\\cdot+a_{n-n}\\,\\,\\,\\mathrm{mod}\\,2$. But the minimal sum can be $m i n v={\\frac{n+1}{2}}$, and the maximal - $m a x v=l\\cdot{\\frac{n+1}{2}}$. Because of this we should choose $a_{2 \\cdot k}$ so, that $s$ fits the boundaries. Constrains allow to do it in a such manner. Firstly, put ones on the even positions. If $s > maxv$ after that, the answer is $- 1$. Otherwise, let's increase each $a_{2 \\cdot k}$ by one until $s = minv$. If we put $l$ in all even positions and $s < minv$, than answer is $- 1$ too. After we put numbers on even positions, let's write $1$ in all odd positions, and while sum of this elements is less than $s$ increase each one by fitting value.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "231",
    "index": "C",
    "title": "To Add or Not to Add",
    "statement": "A piece of paper contains an array of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Your task is to find a number that occurs the maximum number of times in this array.\n\nHowever, before looking for such number, you are allowed to perform not more than $k$ following operations — choose an arbitrary element from the array and add $1$ to it. In other words, you are allowed to increase some array element by $1$ no more than $k$ times (you are allowed to increase the same element of the array multiple times).\n\nYour task is to find the maximum number of occurrences of some number in the array after performing no more than $k$ allowed operations. If there are several such numbers, your task is to find the minimum one.",
    "tutorial": "One of the main observations, needed to solve this problem, is that the second number in answer always coincides with someone $a_{j}$. Let's see why it is true. Suppose, the second number of the answer is $a_{j} + d$ for someone $j$ and $a_{j} + d  \\neq  a_{i}$ for all $i$. This means, we increased some numbers, which is less than $a_{j}$, so that they became equal to $a_{j}$, and then all this numbers and some numbers, which is equal to $a_{j}$, we increased to $a_{j} + d$. But if we didn't increase all this numbers to $a_{j} + d$ and remain they equal to $a_{j}$, we'd perform less operations and the answer would be better. Due to this fact we can solve problem in a such manner. Sort array in non-decreasing order. Iterate over $a_{i}$ and calculate, what is the maximal number of $a_{i}$ we can obtain. For maximizing first number of answer, we must increase some lesser numbers to $a_{i}$ and perform not greater than $k$ operations. It is obvious that firstly we should increase such $a_{j}$ that $a_{i}-a_{j}$ is minimal. So, if we can solve problem in $O(n^{2})$, we would iterate $j$ from $i$ to $0$ and increase $a_{j}$ to $a_{i}$, while we could. But the solution must be faster, and we will use binary search. We will brute the number of numbers, which we must do equal to $a_{i}$. Suppose we fix $cnt$ this value. Now we have to check if we can do $cnt$ numbers equal to $a_{i}$ by not greater than $k$ operations. For doing this, let's calculate $a_{i}\\cdot c n t-\\sum_{j=i-c n t+1}^{t}a_{j}$. If this value not greater than $k$, we can do it. For calculating sum quickly, we can save prefix sums and than $s_{i - cnt + 1, i} = s_{i}-s_{i-cnt}$. Finally we solved this problem in $O(n \\cdot logn)$.",
    "tags": [
      "binary search",
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "231",
    "index": "D",
    "title": "Magic Box",
    "statement": "One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point $(0, 0, 0)$, and the opposite one is at point $(x_{1}, y_{1}, z_{1})$. The six faces of the box contain some numbers $a_{1}, a_{2}, ..., a_{6}$, exactly one number right in the center of each face.\n\nThe numbers are located on the box like that:\n\n- number $a_{1}$ is written on the face that lies on the ZOX plane;\n- $a_{2}$ is written on the face, parallel to the plane from the previous point;\n- $a_{3}$ is written on the face that lies on the XOY plane;\n- $a_{4}$ is written on the face, parallel to the plane from the previous point;\n- $a_{5}$ is written on the face that lies on the YOZ plane;\n- $a_{6}$ is written on the face, parallel to the plane from the previous point.\n\nAt the moment Vasya is looking at the box from point $(x, y, z)$. Find the sum of numbers that Vasya sees. Note that all faces of the box are not transparent and Vasya can't see the numbers through the box. The picture contains transparent faces just to make it easier to perceive. You can consider that if Vasya is looking from point, lying on the plane of some face, than he can not see the number that is written on this face. It is enough to see the center of a face to see the corresponding number for Vasya. Also note that Vasya always reads correctly the $a_{i}$ numbers that he sees, independently of their rotation, angle and other factors (that is, for example, if Vasya sees some $a_{i} = 6$, then he can't mistake this number for $9$ and so on).",
    "tutorial": "The main subtask of this problem is to check whether we can observe the center of face of parallelepiped from point $p = (x, y, z)$. Let's see the case, when the face belongs to plane $z = z_{1}$. For performing all calculations in integer numbers, multiply all coordinates $x, y, z, x_{1}, y_{1}, z_{1}$ by $2$. Take the point $a=\\left({\\frac{x_{1}}{2}},{\\frac{y_{1}}{2}},z_{1}\\right)$ and normal to plane, containing the fixed face, which is directed out of interior of parallelepiped, that is ${\\overline{{\\vec{v}}}}=(0,0,1)$. Also take vector ${\\overline{{\\mathcal{W}}}}=p^{-a}$. If undirected angle between this vectors is less than $90$ degrees, we can observe $a$ from $p$. For checking this we can use scalar product. If scalar product of $\\overline{{\\u}}$ and $\\overline{{\\psi}}$ is strictly greater than zero, than that angle is fitting.",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 1600
  },
  {
    "contest_id": "231",
    "index": "E",
    "title": "Cactus",
    "statement": "A connected undirected graph is called a \\underline{vertex cactus}, if each vertex of this graph belongs to at most one simple cycle.\n\nA simple cycle in a undirected graph is a sequence of distinct vertices $v_{1}, v_{2}, ..., v_{t}$ $(t > 2)$, such that for any $i$ $(1 ≤ i < t)$ exists an edge between vertices $v_{i}$ and $v_{i + 1}$, and also exists an edge between vertices $v_{1}$ and $v_{t}$.\n\nA simple path in a undirected graph is a sequence of not necessarily distinct vertices $v_{1}, v_{2}, ..., v_{t}$ $(t > 0)$, such that for any $i$ $(1 ≤ i < t)$ exists an edge between vertices $v_{i}$ and $v_{i + 1}$ and furthermore each \\textbf{edge occurs no more than once}. We'll say that a simple path $v_{1}, v_{2}, ..., v_{t}$ starts at vertex $v_{1}$ and ends at vertex $v_{t}$.\n\nYou've got a graph consisting of $n$ vertices and $m$ edges, that is a vertex cactus. Also, you've got a list of $k$ pairs of interesting vertices $x_{i}, y_{i}$, for which you want to know the following information — the number of distinct simple paths that start at vertex $x_{i}$ and end at vertex $y_{i}$. We will consider two simple paths distinct if the sets of edges of the paths are distinct.\n\nFor each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "In this problem you should find the number of simple paths between some pair of vertices in vertex cactus. If you learn the structure of these graphs, it is not hard to see, that if we'll squeeze each cycle in one vertex, we get a tree. So let's squeeze all cycles in source graph and get this tree. Also every vertex of this tree we'll mark, if it is squeezed cycle (let's call this vertices 1-vertices) or single vertex in source graph (this vertices we'll call 0-vertices). Then, we'll do the following to find the number of paths between vertices $a$ and $b$ in source graph. Suppose $c$ is a vertex, corresponding to $a$ in obtained tree (it can be a single vertex or a vertex, corresponding to a squeezed cycle with $a$), and $d$ is a vertex, corresponding to $b$. Let's denote $deg$ is the number of 1-vertices in path from $c$ to $d$ in tree. Than it is easy to understand, that the answer for query is $2^{d e g}\\;\\;\\mathrm{mod}\\;10^{9}+7$, because every cycle (1-vertex) increase the number of possible ways twice (you can go from one vertex to other by two ways in cycle). It means that we need to count the number of 1-vertex on the path from one vertex to other in tree quickly to answer a query. We can do it in a following way. Hang our tree for one vertex, which we'll call a root. Denote for every vertex $cnt_{v}$ is the number of 1-vertex on the way to the root (including root and vertex itself). Suppose we want to find the number of 1-vertex on the path from $a$ to $b$. Denote $c$ is the least common ancestor of vertices $a$ and $b$. Than number of 1-vertex on the way from $a$ to $b$ is equal to $cnt_{a} + cnt_{b}-2 \\cdot cnt_{c}$, if $c$ is 0-vertex and $cnt_{a} + cnt_{b}-2 \\cdot cnt_{c} + 1$, if $c$ is 1-vertex. The least common ancestor can be found by standard method - binary method recovery. Finally we have $O(m + k \\cdot logn)$ solution.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "232",
    "index": "A",
    "title": "Cycles",
    "statement": "John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly $k$ cycles of length $3$.\n\nA cycle of length $3$ is an unordered group of three distinct graph vertices $a$, $b$ and $c$, such that each pair of them is connected by a graph edge.\n\nJohn has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed $100$, or else John will have problems painting it.",
    "tutorial": "Let's add edge in order of increasing $a$ and for equal $b$ in order of increasing $b$ (here $a$ and $b$ - the least and the greatest vertices of the edge). If the new edge adds too much 3-cycles, we won't add it. We can count the number of new 3-cycles in $O(n)$ complexity (they all contain the new edge, so it's enough to check all variants of the third vertex). Obviously we will obtain some proper graph, because we can always add a vertex and two edges to make a new triangle. So, there is always an answer. The complexity of this solution is $O(n^{3})$. Let's proof that 100 vertices are always enough for the given restrictions on $n$. For some $p$ after first $p$ iterations we will have a complete graph of $p$ vertices. Now we have exactly $C(p, 3)$ triangles. Consider $p$ such that $C(p, 3)  \\le  k$ and $C(p, 3)$ is maximal. For the given restrictions $p  \\le  85$. From this moment, if we add $u$ from some vertex, we increase the total number of 3-cycles on $C(u, 2)$. So we have to present a small number that is less than $C(85, 3)$ as sum of $C(i, 2)$. The first number we subtruct will differ $C(85, 1)$ on some value not greater than $C(85, 1) = 85$, because $C(n, k) - C(n - 1, k) = C(n - 1, k - 1)$. The second number we subtruct will differ the number we have on some value not greater than $C(14, 1) = 14$. and so on. For every $k$ it's enough to use not more that $90$ vertices.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "232",
    "index": "B",
    "title": "Table",
    "statement": "John Doe has an $n × m$ table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size $n × n$ have exactly $k$ points.\n\nJohn Doe wondered, how many distinct ways to fill the table with points are there, provided that the condition must hold. As this number can be rather large, John Doe asks to find its remainder after dividing by $1000000007$ $(10^{9} + 7)$.\n\nYou should assume that John always paints a point exactly in the center of some cell. Two ways to fill a table are considered distinct, if there exists a table cell, that has a point in one way and doesn't have it in the other.",
    "tutorial": "Let $s_{i}$ number of points in the column $i$. Two neighboring squares are drawn at this picture, $A$ is the number of point it the left area (it is one column), $B$ is the number of points in the middle area and $C$ is the number of points in the right area (it is one column too). That's why by definition we have: $\\left\\{\\begin{array}{l l}{A+B}&{=}&{k}\\\\ {B+C}&{=}&{k.}\\end{array}\\right.$ Therefore $A = C$. That's why $\\forall s_{i}=s_{i+n},(i\\leq m-n)$ Divide all columns by equivalence classes on the basis of $i\\mathrm{~mod~}n$. For all $a$ and $b$ from one class $s_{a} = s_{b}$. $cnt_{a}$ is number of columns in class with $i\\mod n=a$. There are $(C_{n}^{k})^{cnta}$ ways to draw $k$ points in the each of columns in the class $a$ independendently of the other classes. $dp[i][j]$ is number of ways to fill all columns in classes $1, ... i$ in such way that $\\textstyle\\sum_{k=0}^{k\\leq i}s_{k}=j$. $d p[i][j]=\\sum_{k=0}^{k\\leq n}d p[i-1][j-k]\\cdot(C_{n}^{k})^{c n t}$ $cnt_{i}$ take only two values $\\textstyle\\left|{\\frac{m}{n}}\\right\\rangle$ and $\\lfloor{\\frac{m}{n}}\\rfloor+1$. Let's calc $(C_{n}^{a})^{cnti}$ for all $a$ and $cnt_{i}$ and use it to calc our dp. We have $O(n^{2} \\cdot k)$ complexity.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "232",
    "index": "C",
    "title": "Doe Graphs",
    "statement": "John Doe decided that some mathematical object must be named after him. So he invented the Doe graphs. The Doe graphs are a family of undirected graphs, each of them is characterized by a single non-negative number — its order.\n\nWe'll denote a graph of order $k$ as $D(k)$, and we'll denote the number of vertices in the graph $D(k)$ as $|D(k)|$. Then let's define the Doe graphs as follows:\n\n- $D(0)$ consists of a single vertex, that has number $1$.\n- $D(1)$ consists of two vertices with numbers $1$ and $2$, connected by an edge.\n- $D(n)$ for $n ≥ 2$ is obtained from graphs $D(n - 1)$ and $D(n - 2)$. $D(n - 1)$ and $D(n - 2)$ are joined in one graph, at that numbers of all vertices of graph $D(n - 2)$ increase by $|D(n - 1)|$ (for example, vertex number $1$ of graph $D(n - 2)$ becomes vertex number $1 + |D(n - 1)|$). After that two edges are added to the graph: the first one goes between vertices with numbers $|D(n - 1)|$ and $|D(n - 1)| + 1$, the second one goes between vertices with numbers $|D(n - 1)| + 1$ and $1$. Note that the definition of graph $D(n)$ implies, that $D(n)$ is a connected graph, its vertices are numbered from $1$ to $|D(n)|$.\n\n\\begin{center}\n{\\scriptsize The picture shows the Doe graphs of order 1, 2, 3 and 4, from left to right.}\n\\end{center}\n\nJohn thinks that Doe graphs are that great because for them exists a polynomial algorithm for the search of Hamiltonian path. However, your task is to answer queries of finding the shortest-length path between the vertices $a_{i}$ and $b_{i}$ in the graph $D(n)$.\n\nA path between a pair of vertices $u$ and $v$ in the graph is a sequence of vertices $x_{1}$, $x_{2}$, $...$, $x_{k}$ $(k > 1)$ such, that $x_{1} = u$, $x_{k} = v$, and for any $i$ $(i < k)$ vertices $x_{i}$ and $x_{i + 1}$ are connected by a graph edge. The length of path $x_{1}$, $x_{2}$, $...$, $x_{k}$ is number $(k - 1)$.",
    "tutorial": "Let's reduce the problem to the same problem for graphs with less orders. Vertex $|D(n - 1)| + 1$ is cutpoint (except cases $n  \\le  2$ but equations below is true for these cases). Without loss of generality $a < b$. Let $dist(a, b, n)$ - length of the shortest path in graph of order $n$. The first case is $a  \\le  |D(n - 1)|$ and $|D(n - 1)| + 1  \\le  b$ $dist(a, b, n) = min(dist(a, |D(n - 1)|, n - 1), dist(a, 1, n - 1)) + dist(b - |D(n - 1)|, 1, n - 2) + 1$ Edges is marked in red, paths is marked in blue. This formula means that we can go from the vertex $a$ by the path $1$ to the vertex $1$. Then we can go to the $|D(n - 1)| + 1$ by the edge and go to the vertex $b$ by the path $3$. Or we can go to the vertex $|D(n - 1)|$ by the path $2$ and then go to the vertex $|D(n - 1)| + 1$ by the path $2$ and then go to the vertex $b$ by the path $3$. The second case is $|D(n - 1)| + 1  \\le  a, b$. $dist(a, b, n) = dist(a - |D(n - 1)|, b - |D(n - 1)|, n - 2)$That's easy case. The third case is $a, b  \\le  |D(n - 1)|$ $dist(a, b, n) = min(dist(a, b, n - 1), min(dist(1, a, n - 1), dist(|D(n - 1)|, a, n - 1)) + min(dist(1, b, n - 1), dist(|D(n - 1)|, b, n - 1) + 2)$ If shortest path contains cutpoint ($|D(n - 1)| + 1$) we can go to the vertex $1$ or $|D(n - 1)$+1$ form the both of $a$ and $b$. After that we can go to the cutpoint. Else we should consider path from $a$ to $b$ in $D(n - 1)$. Let's notice that for all of $n$ will be no more than $4$ distinct runnings of $dist(i, j, n)$. It can be prooved by the considering many cases of our actions. In authors colution we cashed all $dist(1, i, n)$ and $dist(i, |D(n)|, n)$ for all achieveable $i$ and $n$. We have complexity $\\log m a x(a_{i},b_{i})$ for one query. (it's log because $|D(n)|$ grows like $ \\phi ^{n}$).",
    "tags": [
      "constructive algorithms",
      "divide and conquer",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "232",
    "index": "D",
    "title": "Fence",
    "statement": "John Doe has a crooked fence, consisting of $n$ rectangular planks, lined up from the left to the right: the plank that goes $i$-th $(1 ≤ i ≤ n)$ (from left to right) has width 1 and height $h_{i}$. We will assume that the plank that goes $i$-th $(1 ≤ i ≤ n)$ (from left to right) has index $i$.\n\nA piece of the fence from $l$ to $r$ $(1 ≤ l ≤ r ≤ n)$ is a sequence of planks of wood with indices from $l$ to $r$ inclusive, that is, planks with indices $l, l + 1, ..., r$. The width of the piece of the fence from $l$ to $r$ is value $r - l + 1$.\n\nTwo pieces of the fence from $l_{1}$ to $r_{1}$ and from $l_{2}$ to $r_{2}$ are called matching, if the following conditions hold:\n\n- the pieces do not intersect, that is, there isn't a single plank, such that it occurs in both pieces of the fence;\n- the pieces are of the same width;\n- for all $i$ $(0 ≤ i ≤ r_{1} - l_{1})$ the following condition holds: $h_{l1 + i} + h_{l2 + i} = h_{l1} + h_{l2}$.\n\nJohn chose a few pieces of the fence and now wants to know how many distinct matching pieces are for each of them. Two pieces of the fence are distinct if there is a plank, which belongs to one of them and does not belong to the other one.",
    "tutorial": "Let $d$ and $d'$ be arrays such that $d_{i} = h_{i} - h_{i + 1}, d'_{i} = - d_{i}$ for every $1  \\le  i  \\le  (n - 1)$. With that notation the conditions of matching look somehow like these: the pieces do not intersect, that is, there isn't a single plank, such that it occurs in both pieces of the fence; the pieces are of the same width; for all i $i$ $(0  \\le  i  \\le  r_{1} - l_{1} - 1)$ the following condition holds: $d_{l1 + i} = d'_{l2 + i}$ (that is true in case when $l = r$). The main idea of our solution is stated in the next sentence. For each query $l...r$ the answer is number of pairs $(a, b)$ such that ($a > r$ or $b < l$), $1  \\le  a  \\le  b  \\le  n - 1$, $b - a = r - l$ and $d_{l...r - 1}$ exactly matches $d'_{a...b - 1}$. Let's build a suffix array $sa$ from the concatenation of arrays $d$ and $d'$ with a fictive number between them for separation. Let position of suffix $i$ in $sa$ be $pos_{i}$. For each query all pieces of the fence that satisfy both second and third conditions of matching will be placed in $sa$ on some segment $bound_{left}...bound_{right}$ such that $bound_{left}  \\le  pos_{l}  \\le  bound_{right}$ and $lcp(bound_{left}...bound_{right})  \\ge  (r - l)$. So, it's possible to use binary search to find $bound$'s. Depending on complexity of $lcp$ finding algorithm, we could get them in $O(logn)$ or $O(log^{2}n)$ complexity. But there is still a problem to count the number of suffixes from $sa_{boundleft...boundright}$ that satisfy the first condition too. Actually it is equal to count the number of $i$ ($bound_{left}  \\le  i  \\le  bound_{right}$) such that ($n + 1  \\le  sa_{i}  \\le  n + l - (r - l) - 1$ or $sa_{i}  \\ge  n + r$) (in the concatenation $d'$ starts from $n + 1$). It is a classic problem to count numbers from the given interval in the given subarray. For each query it could be solved in $O(logn)$ complexity. For instance, we could solve it offline using sweep line method and any data structure that support queries of sum on an interval and increment of an element. Or we could use some 2D/persistent structure. So, the summary of the algorithm looks like this: build $d$ and $d'$. Build a suffix array on their concatenation. For each query: find the interval ($bound_{left}...bound_{right}$) with two consecutive binary searches using lcp function. query the count of suffixes from that interval that do not intersect with the given piece of the fence. The best author's solution complexity is $O(nlogn + qlogn)$, but careful written solutions in $O(nlog^{2}n)$ comply with the lime limit too.",
    "tags": [
      "binary search",
      "data structures",
      "string suffix structures"
    ],
    "rating": 2900
  },
  {
    "contest_id": "232",
    "index": "E",
    "title": "Quick Tortoise",
    "statement": "John Doe has a field, which is a rectangular table of size $n × m$. We assume that the field rows are numbered from 1 to $n$ from top to bottom, and the field columns are numbered from 1 to $m$ from left to right. Then the cell of the field at the intersection of the $x$-th row and the $y$-th column has coordinates ($x$; $y$).\n\nWe know that some cells of John's field are painted white, and some are painted black. Also, John has a tortoise, which can move along the white cells of the field. The tortoise can get from a white cell with coordinates ($x$; $y$) into cell ($x + 1$; $y$) or ($x$; $y + 1$), if the corresponding cell is painted white. In other words, the turtle can move only along the white cells of the field to the right or down. The turtle can not go out of the bounds of the field.\n\nIn addition, John has $q$ queries, each of them is characterized by four numbers $x_{1}, y_{1}, x_{2}, y_{2}$ ($x_{1} ≤ x_{2}$, $y_{1} ≤ y_{2}$). For each query John wants to know whether the tortoise can start from the point with coordinates ($x_{1}$; $y_{1}$), and reach the point with coordinates ($x_{2}$; $y_{2}$), moving only along the white squares of the field.",
    "tutorial": "Let's choose central column of the area and for all cells to the left from column calc masks of achieveable cells in the central column and for all cells to the right from column calc masks of cells of which this is achievable. It's easy dp with bitsets. $d p[i][j]=d p[i-1][j]\\vee d p[i][j-1]$ for the right part of board. $d p[i][j]=d p[i+1][j]\\vee d p[i][j+1]$ ($\\boldsymbol{\\mathit{V}}$ - logical or, here it's bitwise or for masks) for the left part. dp calcs mask of achieveable points in the central column. For query $x_{1}$, $y_{1}$, $x_{2}$, $y_{2}$ (if $y_{1}  \\le  mid  \\le  y_{2}$, where $mid$ is chosen central column) answer is yes if $d p[x_{1}][y_{1}]\\wedge d p[x_{2}][y_{2}]$ ($\\Lambda$ is bitwise and) is not empty. Run this algo for left and right part of board we will get answers for all queries. Complexity is ${\\frac{q n}{32}}+q\\log n+{\\frac{n^{3}\\log n}{32}}$.",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "233",
    "index": "A",
    "title": "Perfect Permutation",
    "statement": "A permutation is a sequence of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. Let's denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size of permutation $p_{1}, p_{2}, ..., p_{n}$.\n\nNickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation $p$ that for any $i$ $(1 ≤ i ≤ n)$ ($n$ is the permutation size) the following equations hold $p_{pi} = i$ and $p_{i} ≠ i$. Nickolas asks you to print any perfect permutation of size $n$ for the given $n$.",
    "tutorial": "Consider permutation $p$ such that $p_{i} = i$. Actually $p$ is a sequence of numbers from $1$ to $n$. Obviously $p_{pi} = i$. Now the only trick is to change the permutation to satisfy the second equation: $p_{i}  \\neq  i$. Let's swap every two consequtive elements. More formally, for each $k: 2k  \\le  n$ let's swap $p_{2k - 1}$ and $p_{2k}$. It's easy to see that the obtained permutation satisfies both equations for every $n$ with the only exception: when $n$ is odd, there is no answer and we should print $- 1$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "233",
    "index": "B",
    "title": "Non-square Equation",
    "statement": "Let's consider equation:\n\n\\[\nx^{2} + s(x)·x - n = 0,\n\\]\n\nwhere $x, n$ are positive integers, $s(x)$ is the function, equal to the sum of digits of number $x$ in the decimal number system.\n\nYou are given an integer $n$, find the smallest positive integer root of equation $x$, or else determine that there are no such roots.",
    "tutorial": "Firstly let's find the interval of possible values of $s(x)$. Hence $x^{2}  \\le  n$ and $n  \\le  10^{18}$, $x  \\le  10^{9}$. In other words, for every considerable solution $x$ the decimal length of $x$ does not extend $10$ digits. So $s_{max}  \\le  s(9999999999) = 10 \\cdot 9 = 90$. Let's bruteforce the value of $s(x)$ ($0  \\le  s(x)  \\le  90$). Now we have an ordinary square equation. The deal is to solve it and to check that the current bruteforced value of $s(x)$ is equal to sum of digits of the solution. If the solution exists and the equality holds, we should relax the answer. It seems that the most error-generating part of this problem is solving the equation. Knowing arrays is not neccessary to solve these two problems.",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "235",
    "index": "A",
    "title": "LCM Challenge",
    "statement": "Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.\n\nBut I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than $n$. Can you help me to find the maximum possible least common multiple of these three integers?",
    "tutorial": "It is a simple problem, but many competitors used some wrong guesses and failed. First of all, we should check if n is at most 3 and then we can simply output 1,2,6. Now there are two cases: When n is odd, the answer is obviously n(n-1)(n-2). When n is even, we can still get at least (n-1)(n-2)(n-3), so these three numbers in the optimal answer would not be very small compared to n. So we can just iterate every 3 number triple in [n-50,n] and update the answer.",
    "tags": [
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "235",
    "index": "B",
    "title": "Let's Play Osu!",
    "statement": "You're playing a game called Osu! Here's a simplified version of it. There are $n$ clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as \"O\", bad as \"X\", then the whole play can be encoded as a sequence of $n$ characters \"O\" and \"X\".\n\nUsing the play sequence you can calculate the score for the play as follows: for every maximal consecutive \"O\"s block, add the square of its length (the number of characters \"O\") to the score. For example, if your play can be encoded as \"OOXOOOXXOO\", then there's three maximal consecutive \"O\"s block \"OO\", \"OOO\", \"OO\", so your score will be $2^{2} + 3^{2} + 2^{2} = 17$. If there are no correct clicks in a play then the score for the play equals to $0$.\n\nYou know that the probability to click the $i$-th $(1 ≤ i ≤ n)$ click correctly is $p_{i}$. In other words, the $i$-th character in the play sequence has $p_{i}$ probability to be \"O\", $1 - p_{i}$ to be \"X\". You task is to calculate the expected score for your play.",
    "tutorial": "Let us take a deep look at how this score is calculated. For an $n$ long 'O' block, it contributes $n^{2}$ to the answer. Let us reformat this problem a bit and consider the following alternative definition of the score: (1) For each two 'O' pair which there is no 'X' between them, they add 2 to the score. (2) For each 'O', it adds 1 to the score. We claim that this new definition of the score is equivalent to the definition in the problem statement. Proof of the claim: For an $n$ long 'O' block, there are $C_{n}^{2}$ pairs of 'O' in it and $n$ 'O' in it. Note that $2C_{n}^{2} + n = n^{2}$. So now we work with the new definition of the score. For each event(i,j) (which means s[i] and s[j] are 'O', and there is no 'X' between them). If event(i,j) happens, it adds 2 to the score. So we only need to sum up the probabilities of all events and multiply them by 2, and our task becomes how to calculate the sum of probabilities of all the event(i,j). Let P(i,j) be the probability of event(i,j). We can see that P(i,j) can be computed by $\\textstyle\\prod_{i}^{j}p_{x}$. Then we denote P(j) as the sum of all event(i,j) for i<j. We have dp(0)=0 and dp(j)=(dp(j-1)+$p_{j - 1}$)*$p_{j}$",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2000
  },
  {
    "contest_id": "235",
    "index": "C",
    "title": "Cyclical Quest",
    "statement": "Some days ago, WJMZBMR learned how to answer the query \"how many times does a string $x$ occur in a string $s$\" quickly by preprocessing the string $s$. But now he wants to make it harder.\n\nSo he wants to ask \"how many consecutive substrings of $s$ are cyclical isomorphic to a given string $x$\". You are given string $s$ and $n$ strings $x_{i}$, for each string $x_{i}$ find, how many consecutive substrings of $s$ are cyclical isomorphic to $x_{i}$.\n\nTwo strings are called cyclical isomorphic if one can rotate one string to get the other one. 'Rotate' here means 'to take some consecutive chars (maybe none) from the beginning of a string and put them back at the end of the string in the same order'. For example, string \"abcde\" can be rotated to string \"deabc\". We can take characters \"abc\" from the beginning and put them at the end of \"de\".",
    "tutorial": "This problem can be solved by many suffix structures. Probably using suffix automaton is the best way to solve it since suffix automaton is simple and clear. Let us build a suffix automaton of the input string S, and consider the query string x. Let us also build a string t as x concatenated with x dropping the last char. One can see that every consecutive sub-string of t with length |x| is a rotation of x. Let us read the string t with suffix automaton we have build, and every time take the first char out and add a new char, add the answer by the number of string equal to this current sub-string of t (which is a rotation of x). And one more thing, we should consider the repetend of x as well",
    "code": "/**\n * Created by IntelliJ IDEA.\n * User: mac\n * Date: 12-10-17\n * Time: 下午1:30\n * To change this template use File | Settings | File Templates.\n */\n\nimport java.io.*;\nimport java.util.*;\n\npublic class CJava {\n\n    BufferedReader reader;\n    StringTokenizer tokenizer;\n    PrintWriter writer;\n\n    List<Node> nodes = new ArrayList<Node>();\n\n    class Node {\n        Node[] go;\n        Node suf, nxt = null;\n        int val, cnt;\n\n        Node(Node[] go, Node suf, int val) {\n            this.go = go;\n            this.suf = suf;\n            this.val = val;\n            this.cnt = 0;\n            nodes.add(this);\n        }\n\n        Node(Node suf, int val) {\n            this(new Node[26], suf, val);\n        }\n\n        Node() {\n            this(null, 0);\n        }\n    }\n\n    Node root, last;\n\n    void run() {\n        try {\n            reader = new BufferedReader(new InputStreamReader(System.in));\n            tokenizer = null;\n            writer = new PrintWriter(System.out);\n            solve();\n            reader.close();\n            writer.close();\n        } catch (Exception e) {\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n\n    String nextToken() throws IOException {\n        while (tokenizer == null || !tokenizer.hasMoreTokens())\n            tokenizer = new StringTokenizer(reader.readLine());\n        return tokenizer.nextToken();\n    }\n\n    int nextInt() throws IOException {\n        return Integer.parseInt(nextToken());\n    }\n\n    long nextLong() throws IOException {\n        return Long.parseLong(nextToken());\n    }\n\n    double nextDouble() throws IOException {\n        return Double.parseDouble(nextToken());\n    }\n\n    void extend(int w) {\n        Node p = last;\n        Node np = new Node();\n        np.val = p.val + 1;\n        np.cnt = 1;\n        while (p != null && p.go[w] == null) {\n            p.go[w] = np;\n            p = p.suf;\n        }\n        if (p == null) {\n            np.suf = root;\n        } else {\n            Node q = p.go[w];\n            if (p.val + 1 == q.val)\n                np.suf = q;\n            else {\n                Node nq = new Node(q.go.clone(), q.suf, p.val + 1);\n                q.suf = nq;\n                np.suf = nq;\n                while (p != null && p.go[w] == q) {\n                    p.go[w] = nq;\n                    p = p.suf;\n                }\n            }\n        }\n        last = np;\n    }\n\n    int repetend(char[] s) {\n        int n = s.length;\n        int[] nxt = new int[n + 1];\n        nxt[0] = -1;\n        for (int i = 1; i <= n; i++) {\n            int j = nxt[i - 1];\n            while (j >= 0 && s[j] != s[i - 1])\n                j = nxt[j];\n            nxt[i] = j + 1;\n        }\n        int a = n - nxt[n];\n        if (n % a == 0)\n            return a;\n        return n;\n    }\n\n    void solve() throws IOException {\n        root = last = new Node();\n        {\n            char[] s = nextToken().toCharArray();\n//            char[] s = new char[500000];\n//            Random rnd = new Random();\n//            for (int i = 0; i < s.length; i++) {\n//                s[i] = (char)(rnd.nextInt(26) + 'a');\n//            }\n            int n = s.length;\n            for (char c : s) {\n                extend(c - 'a');\n            }\n            Node[] first = new Node[n + 1];\n            for (Node node : nodes) {\n                node.nxt = first[node.val];\n                first[node.val] = node;\n            }\n            for (int i = n; i >= 0; i--) {\n                for (Node u = first[i]; u != null; u = u.nxt)\n                    if (u.suf != null)\n                        u.suf.cnt += u.cnt;\n            }\n        }\n\n        int nQ = nextInt();\n        for (int i = 0; i < nQ; i++) {\n            char[] buf = nextToken().toCharArray();\n            int rep = repetend(buf);\n            Node cur = root;\n            int l = 0;\n            int n = buf.length;\n\n            for (int j = 0; j < n; j++) {\n                int w = buf[j] - 'a';\n                while (cur != null && cur.go[w] == null) {\n                    cur = cur.suf;\n                    if (cur != null)\n                        l = cur.val;\n                }\n                if (cur != null && cur.go[w] != null) {\n                    cur = cur.go[w];\n                    ++l;\n                } else {\n                    cur = root;\n                    l = 0;\n                }\n            }\n            int ans = 0;\n            if (l == n)\n                ans += cur.cnt;\n            for (int j = 1; j < rep; j++) {\n                if (l == n) {\n                    --l;\n                    if (l <= cur.suf.val)\n                        cur = cur.suf;\n                }\n                //add last\n                int w = buf[j - 1] - 'a';\n                while (cur != null && cur.go[w] == null) {\n                    cur = cur.suf;\n                    if (cur != null)\n                        l = cur.val;\n                }\n                if (cur != null && cur.go[w] != null) {\n                    cur = cur.go[w];\n                    ++l;\n                } else {\n                    cur = root;\n                    l = 0;\n                }\n                if (l == n)\n                    ans += cur.cnt;\n            }\n            writer.println(ans);\n        }\n    }\n\n    static public void main(String[] args) {\n        new CJava().run();\n    }\n}",
    "tags": [
      "data structures",
      "string suffix structures",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "235",
    "index": "D",
    "title": "Graph Game",
    "statement": "In computer science, there is a method called \"Divide And Conquer By Node\" to solve some hard problems about paths on a tree. Let's desribe how this method works by function:\n\n$solve(t)$ ($t$ is a tree):\n\n- Chose a node $x$ (it's common to chose weight-center) in tree $t$. Let's call this step \"Line A\".\n- Deal with all paths that pass $x$.\n- Then delete $x$ from tree $t$.\n- After that $t$ becomes some subtrees.\n- Apply $solve$ on each subtree.\n\nThis ends when $t$ has only one node because after deleting it, there's nothing.\n\nNow, WJMZBMR has mistakenly believed that it's ok to chose any node in \"Line A\". So he'll chose a node at random. To make the situation worse, he thinks a \"tree\" should have the same number of edges and nodes! So this procedure becomes like that.\n\nLet's define the variable $totalCost$. Initially the value of $totalCost$ equal to $0$. So, $solve(t)$ (now $t$ is a graph):\n\n- $totalCost = totalCost + (size of t)$. The operation \"=\" means assignment. $(Size of t)$ means the number of nodes in $t$.\n- Choose a node $x$ in graph $t$ at random (uniformly among all nodes of $t$).\n- Then delete $x$ from graph $t$.\n- After that $t$ becomes some connected components.\n- Apply $solve$ on each component.\n\nHe'll apply $solve$ on a connected graph with $n$ nodes and $n$ edges. He thinks it will work quickly, but it's very slow. So he wants to know the expectation of $totalCost$ of this procedure. Can you help him?",
    "tutorial": "First of all, let us consider the simpler case of trees. Let us use Event(A,B) to denote the following event \"when we select A as the deleting point, B is connected to A\". Clearly, if Event(A,B) happens, it would add 1 to $totolCost$. So we can just simply calculate the probability of every Event(A,B), and add them up. Let us consider how to calculate the probability of Event(A,B). Assume there are n vertices in the path between A and B, we claim that the probability is simply $1 / n$. Let us try to prove it using induction. First let us assume there's a connected sub-graph of the tree containing both A and B, if the sub-graph only has n vertices, then the event happens only if we select vertex A, so the probability is $1 / n$. Otherwise, assume it has x vertices there is two cases: whether the selected vertex is on the path between A and B or not. In the first case, the probability of Event(A,B) happen is $1 / x$ because if we don't select A, Event(A,B) will never happen. In the second case, the sub-graph containing A,B has become smaller, so the probability is $(x - n) / xn$. So add them up we can prove this statement. Then we can solve the tree case by simply add up the inverse of every path's length in the tree. And for the original case, there's at most 2 paths between A and B. If there's only one path, then everything is the same with the tree case. Otherwise, the path between A and B should pass the cycle in the graph. Let us examine this case, you can see that there 2 types of vertex: Vertex on the path of A to cycle or B to cycle, they should not be selected before A because once they're selected, A and B lost connectivity, let us call them X. Vertex on the cycle, the two paths from A to B, each path contains a path in the cycle, let us call them Y and Z. So there are two possibilities: X and Y are free when A is selected, X and Z are free when A is selected. And we should subtract the case that X and Y, Z are all free when A is selected because it double-counts before. So the probability is $1 / (X + Y + 1) + 1 / (X + Z + 1) - 1 / (X + Y + Z + 1)$.",
    "code": "import java.util.List;\nimport java.io.InputStreamReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.io.BufferedReader;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\n\n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n */\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tInputStream inputStream = System.in;\n\t\tOutputStream outputStream = System.out;\n\t\tInputReader in = new InputReader(inputStream);\n\t\tPrintWriter out = new PrintWriter(outputStream);\n\t\tTaskD solver = new TaskD();\n\t\tsolver.solve(1, in, out);\n\t\tout.close();\n\t}\n}\n\nclass TaskD {\n    class Vertex {\n        List<Vertex> adj = new ArrayList<Vertex>();\n        int stackDepth = -1;\n        int cyclePos = -1;\n        Vertex parent = null;\n        int subtreeSize;\n        int[] depthProfile;\n\n        public boolean findCycle(int depth) {\n            if (depth != stack.size()) throw new RuntimeException();\n            if (stackDepth >= 0) {\n                if (stackDepth == depth - 2)\n                    return false;\n                for (int i = stackDepth; i < depth; ++i)\n                    cycle.add(stack.get(i));\n                return true;\n            }\n            stackDepth = depth;\n            stack.add(this);\n            for (Vertex v : adj) if (v.findCycle(depth + 1)) return true;\n            stack.remove(stack.size() - 1);\n            stackDepth = -2;\n            return false;\n        }\n\n        public void buildTree() {\n            subtreeSize = 1;\n            for (Vertex v : adj)\n                if (v != parent && v.cyclePos < 0) {\n                    v.parent = this;\n                    v.buildTree();\n                    subtreeSize += v.subtreeSize;\n                }\n        }\n\n        public double buildOneTreeAnswers() {\n            double res = 0;\n            int maxDepth = 0;\n            for (Vertex v : adj) {\n                if (v != parent && v.cyclePos < 0) {\n                    res += v.buildOneTreeAnswers();\n                    maxDepth = Math.max(maxDepth, v.depthProfile.length);\n                }\n            }\n            depthProfile = new int[maxDepth + 1];\n            ++depthProfile[0];\n            for (Vertex v : adj) {\n                if (v != parent && v.cyclePos < 0) {\n                    for (int oldDepth = 1; oldDepth <= v.depthProfile.length; ++oldDepth)\n                        for (int newDepth = 0; newDepth <= maxDepth; ++newDepth) {\n                            res += simpleProb(oldDepth + newDepth) * depthProfile[newDepth] * v.depthProfile[oldDepth - 1];\n                        }\n                    for (int oldDepth = 1; oldDepth <= v.depthProfile.length; ++oldDepth)\n                        depthProfile[oldDepth] += v.depthProfile[oldDepth - 1];\n                    v.depthProfile = null;\n                }\n            }\n            return res;\n        }\n    }\n\n    private double simpleProb(int dist) {\n        if (dist == 0) throw new RuntimeException();\n        return 2.0 / (dist + 1);\n    }\n\n    List<Vertex> stack = new ArrayList<Vertex>();\n    List<Vertex> cycle = new ArrayList<Vertex>();\n\n\tpublic void solve(int testNumber, InputReader in, PrintWriter out) {\n        int n = in.nextInt();\n        Vertex[] v = new Vertex[n];\n        for (int i = 0; i < n; ++i) {\n            v[i] = new Vertex();\n        }\n        for (int i = 0; i < n; ++i) {\n            Vertex a = v[in.nextInt()];\n            Vertex b = v[in.nextInt()];\n            a.adj.add(b);\n            b.adj.add(a);\n        }\n        v[0].findCycle(0);\n        for (int i = 0; i < cycle.size(); ++i) {\n            cycle.get(i).cyclePos = i;\n        }\n        for (Vertex vv : cycle)\n            vv.buildTree();\n        double res = n;\n        for (Vertex vv : cycle)\n            res += vv.buildOneTreeAnswers();\n        for (int i = 0; i < cycle.size(); ++i) {\n            for (int j = i + 1; j < cycle.size(); ++j) {\n                int[] dpi = cycle.get(i).depthProfile;\n                int[] dpj = cycle.get(j).depthProfile;\n                for (int di = 0; di < dpi.length; ++di)\n                    for (int dj = 0; dj < dpj.length; ++dj)\n                        res += complexProb(j - i, cycle.size() - (j - i), di, dj) * dpi[di] * dpj[dj];\n            }\n        }\n        out.println(res);\n\t}\n\n    private double complexProb(int cycleA, int cycleB, int tree1, int tree2) {\n        return 2.0 / (cycleA + tree1 + tree2 + 1) + 2.0 / (cycleB + tree1 + tree2 + 1) - 2.0 / (cycleA + cycleB + tree1 + tree2);\n    }\n}\n\nclass InputReader {\n    private BufferedReader reader;\n    private StringTokenizer tokenizer;\n\n    public InputReader(InputStream stream) {\n        reader = new BufferedReader(new InputStreamReader(stream));\n        tokenizer = null;\n    }\n\n    public String next() {\n        while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n            try {\n                tokenizer = new StringTokenizer(reader.readLine());\n            } catch (IOException e) {\n                throw new RuntimeException(e);\n            }\n        }\n        return tokenizer.nextToken();\n    }\n\n    public int nextInt() {\n        return Integer.parseInt(next());\n    }\n\n    }",
    "tags": [
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "235",
    "index": "E",
    "title": "Number Challenge",
    "statement": "Let's denote $d(n)$ as the number of divisors of a positive integer $n$. You are given three integers $a$, $b$ and $c$. Your task is to calculate the following sum:\n\n\\[\n\\textstyle\\sum_{i=1}^{a}\\sum_{j=1}^{b}\\sum_{k=1}^{c}d(i\\cdot j\\cdot k).\n\\]\n\nFind the sum modulo $1073741824$ $(2^{30})$.",
    "tutorial": "Let us consider each prime in one step, the upper limit for $a, b, c$ is recorded. So if we fixed the power of 2 in each $i, j, k$ like $2^{x}, 2^{y}, 2^{z}$, then their upper limit becomes $a / 2^{x}, b / 2^{y}, c / 2^{z}$, and the power of 2 in their multiplication is just x+y+z. Let us denote $dp(a, b, c, p)$ for the answer to the original problem that $i, j, k$ 's upper limit is $a, b, c$. And their can only use the prime factors which are not less than $p$. Let the next prime to be $q$, so we can try to fix the power of $p$ in $i, j, k$ and get the new upper limit. So we can do transform like this: $dp(a, b, c, p)$ = sum of $dp(a / p^{x}, b / p^{y}, c / p^{z}, q) \\cdot (x + y + z + 1)$",
    "code": "/**\n * Created by IntelliJ IDEA.\n * User: mac\n * Date: 12-10-9\n * Time: 下午12:41\n * To change this template use File | Settings | File Templates.\n */\n\nimport java.io.*;\nimport java.util.*;\n\npublic class EJava {\n\n    BufferedReader reader;\n    StringTokenizer tokenizer;\n    PrintWriter writer;\n\n    void run() {\n        try {\n            reader = new BufferedReader(new InputStreamReader(System.in));\n            tokenizer = null;\n            writer = new PrintWriter(System.out);\n            solve();\n            reader.close();\n            writer.close();\n        } catch (Exception e) {\n            e.printStackTrace();\n            System.exit(1);\n        }\n    }\n\n    String nextToken() throws IOException {\n        while (tokenizer == null || !tokenizer.hasMoreTokens())\n            tokenizer = new StringTokenizer(reader.readLine());\n        return tokenizer.nextToken();\n    }\n\n    int nextInt() throws IOException {\n        return Integer.parseInt(nextToken());\n    }\n\n    long nextLong() throws IOException {\n        return Long.parseLong(nextToken());\n    }\n\n    double nextDouble() throws IOException {\n        return Double.parseDouble(nextToken());\n    }\n\n    class Converter {\n        int n, sq;\n        int[] lst;\n\n        public Converter(int n) {\n            this.n = n;\n            sq = 1;\n            while (sq * sq <= n) ++sq;\n            lst = new int[sq * 2 + 1];\n            for (int i = 1; i <= sq * 2; i++) {\n                lst[i] = i <= sq ? i : n / (i - sq);\n            }\n        }\n\n        int encode(int x) {\n            return x <= sq ? x : n / x + sq;\n        }\n\n        int decode(int x) {\n            return lst[x];\n        }\n\n        int size() {\n            return sq * 2;\n        }\n    }\n\n    int calcTwo(int a, int b, int[] cnt) {\n        if (a > b) {\n            int tmp = a;\n            a = b;\n            b = tmp;\n        }\n        return cnt[a] * cnt[b] * 4 - cnt[a] * 4 + cnt[a] * 3;\n    }\n\n    void solve() throws IOException {\n        int a = nextInt(), b = nextInt(), c = nextInt();\n        Converter A = new Converter(a), B = new Converter(b), C = new Converter(c);\n        int n = Math.max(a, Math.max(b, c));\n        int[] cnt = new int[n + 1];\n        boolean[] is = new boolean[n + 1];\n        Arrays.fill(is, true);\n\n        ArrayList<Integer> smallPrimes = new ArrayList<Integer>();\n\n        for (int i = 2; i <= n; i++) {\n            if (is[i]) {\n                if (i * i <= n) {\n                    smallPrimes.add(i);\n                } else {\n                    cnt[i]++;\n                }\n                for (int j = i + i; j <= n; j += i) {\n                    is[j] = false;\n                }\n            }\n        }\n\n        for (int i = 1; i <= n; i++) {\n            cnt[i] += cnt[i - 1];\n        }\n\n        int[][][] am = new int[A.size() + 1][B.size() + 1][C.size() + 1];\n        int[][][] nam = new int[A.size() + 1][B.size() + 1][C.size() + 1];\n        am[A.encode(a)][B.encode(b)][C.encode(c)] += 1;\n        for (int p : smallPrimes) {\n            for (int[][] x : nam) {\n                for (int[] y : x) {\n                    Arrays.fill(y, 0);\n                }\n            }\n            for (int i = 1; i <= A.size(); i++) {\n                for (int j = 1; j <= B.size(); j++) {\n                    for (int k = 1; k <= C.size(); k++) {\n                        int d = am[i][j][k];\n                        if (d == 0)\n                            continue;\n                        int I = A.decode(i), J = B.decode(j), K = C.decode(k);\n                        for (int pi = 1, ci = 0; pi <= I; pi *= p, ++ci) {\n                            int x = A.encode(I / pi);\n                            for (int pj = 1, cj = 0; pj <= J; pj *= p, ++cj) {\n                                int y = B.encode(J / pj);\n                                for (int pk = 1, ck = 0; pk <= K; pk *= p, ++ck) {\n                                    int z = C.encode(K / pk);\n                                    nam[x][y][z] += d * (ci + cj + ck + 1);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            int[][][] tmp = am;\n            am = nam;\n            nam = tmp;\n        }\n\n\n        int ans = 0;\n        for (int i = 1; i <= A.size(); ++i) {\n            for (int j = 1; j <= B.size(); ++j) {\n                for (int k = 1; k <= C.size(); ++k) {\n                    int d = am[i][j][k];\n                    if (d == 0)\n                        continue;\n                    int I = A.decode(i), J = B.decode(j), K = C.decode(k);\n                    int t[] = {I, J, K};\n                    Arrays.sort(t);\n                    I = t[0];\n                    J = t[1];\n                    K = t[2];\n                    //there\n                    int cur = cnt[I] * cnt[J] * cnt[K] * 8; //abc->8\n                    cur += -cnt[I] * cnt[K] * 2; //aab->3*2->6\n                    cur += -cnt[I] * cnt[J] * 2;\n                    cur += -cnt[J] * cnt[I] * 2;\n                    cur += cnt[I] * 2; //aaa->4\n                    //two\n                    cur += calcTwo(I, J, cnt) + calcTwo(J, K, cnt) + calcTwo(I, K, cnt);\n                    //one\n                    cur += (cnt[I] + cnt[J] + cnt[K]) * 2;\n                    //zero\n                    cur += 1;\n                    ans += cur * d;\n                }\n            }\n        }\n        ans %= 1 << 30;\n        if (ans < 0)\n            ans += 1 << 30;\n        System.out.println(ans);\n    }\n\n    static public void main(String[] args) {\n        new EJava().run();\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "236",
    "index": "A",
    "title": "Boy or Girl",
    "statement": "Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.\n\nBut yesterday, he came to see \"her\" in the real world and found out \"she\" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.\n\nThis is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.",
    "tutorial": "It is a very simple problem, just count how many distinct chars in the input and output the correct answer.",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "236",
    "index": "B",
    "title": "Easy Number Challenge",
    "statement": "Let's denote $d(n)$ as the number of divisors of a positive integer $n$. You are given three integers $a$, $b$ and $c$. Your task is to calculate the following sum:\n\n\\[\n\\textstyle\\sum_{i=1}^{a}\\sum_{j=1}^{b}\\sum_{k=1}^{c}d(i\\cdot j\\cdot k).\n\\]\n\nFind the sum modulo $1073741824$ $(2^{30})$.",
    "tutorial": "First of all, we can make a table of size a*b*c to store every number's d value. Then we can just brute force through every tripe to calculate the answer.",
    "tags": [
      "implementation",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "238",
    "index": "A",
    "title": "Not Wool Sequences",
    "statement": "A sequence of non-negative integers $a_{1}, a_{2}, ..., a_{n}$ of length $n$ is called a wool sequence if and only if there exists two integers $l$ and $r$ $(1 ≤ l ≤ r ≤ n)$ such that $a_{l}\\ \\oplus\\ a_{l+1}\\ \\oplus\\ \\cdots\\ \\leftrightarrow a_{r}=0$. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.\n\nThe expression $x\\oplus y$ means applying the operation of a bitwise xor to numbers $x$ and $y$. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as \"^\", in Pascal — as \"xor\".\n\nIn this problem you are asked to compute the number of sequences made of $n$ integers from 0 to $2^{m} - 1$ that are not a wool sequence. You should print this number modulo $1000000009$ $(10^{9} + 9)$.",
    "tutorial": "Let $a_{1}, ..., a_{n}$ be a not-wool-sequence. We define another sequence called $b$ in which $b_{i}$ is xor of the first $i$ elements of $a$, $b_{i}=a_{i}\\oplus b_{i-1}$ and $b_{0} = 0$. Now xor of elements of a consecutive subsequence like $a_{i}, ..., a_{j}$ will be equal to $b_{j}\\oplus b_{i-1}$. So we know that all elements of $b$ should be different. Therefore $b$ is a sequence of distinct integers of length $n + 1$ starting with 0 made of numbers $0$ to $2^{m} - 1$. The number of such sequences is $\\textstyle\\prod_{1}^{n}2^{m}-i$ and this is the answer to problem.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "238",
    "index": "C",
    "title": "World Eater Brothers",
    "statement": "You must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world.\n\nAs you know there are $n$ countries in the world. These countries are connected by $n - 1$ directed roads. If you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once.\n\nEach of the brothers wants to establish his reign in some country, then it's possible for him to control the countries that can be reached from his country using directed roads.\n\nThe brothers can rule the world if there exists at most two countries for brothers to choose (and establish their reign in these countries) so that any other country is under control of at least one of them. In order to make this possible they want to change the direction of minimum number of roads. Your task is to calculate this minimum number of roads.",
    "tutorial": "Consider we only want to change direction of minimum number of roads so that all other countries are reachable from a specific country $x$. This problem can be solved in $O(n)$ and it's exactly what 219D - Choosing Capital for Treeland asks for. If you don't know how to solve it you can read the editorial of that contest. Consider two countries $A$ and $B$ which can be chosen by world eater brothers to achieve the minimum number of road direction changes. After changing the direction of roads, there exists a country on the undirected path between $A$ and $B$ which is reachable from both $A$ and $B$ using roads. We call such country a middle-country. We want to iterate on middle-countries and find the best two countries for ruling for each middle-country. For each neighbor of the current middle-country calculate the minimum number of road changes in the subtree rooted at that neighbor so that all countries will be reachable from some country in that subtree. Then from two of these subtrees we need to pick $A$ and $B$ and all other subtrees will have edges pointing to the root of subtree. This can be computed in $O(n)$ for each middle-city. So the overall complexity will be $O(n^{2})$.",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "238",
    "index": "D",
    "title": "Tape Programming",
    "statement": "There is a programming language in which every program is a non-empty sequence of \"<\" and \">\" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts.\n\n- Current character pointer (CP);\n- Direction pointer (DP) which can point left or right;\n\nInitially CP points to the leftmost character of the sequence and DP points to the right.\n\nWe repeat the following steps until the first moment that CP points to somewhere outside the sequence.\n\n- If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was $0$ then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one.\n- If CP is pointing to \"<\" or \">\" then the direction of DP changes to \"left\" or \"right\" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is \"<\" or \">\" then the previous character will be erased from the sequence.\n\nIf at any moment the CP goes outside of the sequence the execution is terminated.\n\nIt's obvious the every program in this language terminates after some steps.\n\nWe have a sequence $s_{1}, s_{2}, ..., s_{n}$ of \"<\", \">\" and digits. You should answer $q$ queries. Each query gives you $l$ and $r$ and asks how many of each digit will be printed if we run the sequence $s_{l}, s_{l + 1}, ..., s_{r}$ as an independent program in this language.",
    "tutorial": "This problem was my favorite in the problemset. The primary point is that at any moment during the interpretation of a program only a prefix of the program is modified and used by IP. Consider we want to calculate the output of subsequence $s_{l}, ..., s_{r}$. While running the original program $s_{1}, ..., s_{n}$ if at any moment CP enters the interval $[l, r]$ it should be pointing to position $l$ and the direction of DP should be right. So it's like we have started interpreting $s_{l}, ..., s_{r}$ independently. The termination of execution of $s_{l}, ..., s_{r}$ is the first time CP points to somewhere outside interval $[l, r]$. Therefore what we need to solve the problem is to run the original program. And after each termination if the program is nonempty then run it again until program is empty. Then we should keep a log of positions we have visited and the time of each visit and the number of printed digits of each type until then. After this preprocessing the to calculate the answer of query $(l_{i}, r_{i})$ its enough to find the first time CP visited $s_{li}$ and the first time CP visited $s_{ri + 1}$ or $s_{li - 1}$ after that. The described approach can be implemented in $O(nlog(n) + qlog(n))$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2900
  },
  {
    "contest_id": "238",
    "index": "E",
    "title": "Meeting Her",
    "statement": "Urpal lives in a big city. He has planned to meet his lover tonight.\n\nThe city has $n$ junctions numbered from $1$ to $n$. The junctions are connected by $m$ directed streets, all the roads have equal length. Urpal lives in junction $a$ and the date is planned in a restaurant in junction $b$. He wants to use public transportation to get to junction $b$. There are $k$ bus transportation companies. At the beginning of every second, a bus from the $i$-th company chooses a random shortest path between junction $s_{i}$ and junction $t_{i}$ and passes through it. There might be no path from $s_{i}$ to $t_{i}$. In that case no bus will leave from $s_{i}$ to $t_{i}$. If a bus passes through a junction where Urpal stands, he can get on the bus. He can also get o\u001bff the bus at any junction along the path.\n\nNow Urpal wants to know if it's possible to go to the date using public transportation in a \u001cfinite amount of time (the time of travel is the sum of length of the traveled roads) and what is the minimum number of buses he should take in the worst case.\n\n\\textbf{At any moment Urpal knows only his own position and the place where the date will be. When he gets on the bus he knows only the index of the company of this bus. Of course Urpal knows the city map and the the pairs $(s_{i}, t_{i})$ for each company.}\n\nNote that Urpal doesn't know buses velocity.",
    "tutorial": "Consider a bus passing a shortest path from $s_{i}$ to $t_{i}$. There are some points that are necessary to pass in order to obtain a shortest path. Firstly we compute them. This can be done in $O(n^{3})$ with Floyd-Warshall and some processing after that. Urpal is sure that a bus from $i$-th company always passes such vertices on his path from $s_{i}$ to $t_{i}$. So he can get on a bus from $i$-th company only at vertices the bus surely passes. At any moment Urpal's status can be uniquely determined by his position on the map and the bus he's traveling with. So we have $nk$ states $(position, bus)$. Our goal is to reach some $(b, ...)$ state from a $(a, v)$ state which bus $v$ surely passes $a$ (source states). So let's find all states that can reach a goal state. We call such states good states. Consider Urpal is at junction $x$ and he's traveling with a bus of type $y$. Let $v_{1}, v_{2}, ..., v_{w}$ be the list of junctions the bus might go on its shortest path from $s_{y}$ to $t_{y}$. And let $c_{1}, c_{2}, ..., c_{l}$ be the list of companies that their bus surely passes junction $x$, excluding $y$-th company. For state $(x, y)$ we know we can reach junction $b$ (it's a good state) if one of the following is true: $x = b$, the minimum cost of solving the problem will be 0. All states $(v_{1}, y)$, $(v_{2}, y)$, ... and $(v_{w}, y)$ are good states, the minimum cost of solving the problem will be the maximum of all these states. At least one of states $(x, c_{1})$, $(x, c_{2})$, ... or $(x, c_{l})$ is a good state, the minimum cost of solving the problem will be the minimum the good ones plus one. At first the only good states we know are states with junction $b$, $(b, ...)$. Now some new states might have become good states. So we add those states to the list of known good states. We do this until no state becomes good anymore. At the end we print the minimum cost of source states which are good, and if they don't exist we print -1. The process thing can be implemented in $O(n^{4})$.",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "239",
    "index": "A",
    "title": "Two Bags of Potatoes",
    "statement": "Valera had two bags of potatoes, the first of these bags contains $x$ $(x ≥ 1)$ potatoes, and the second — $y$ $(y ≥ 1)$ potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains $x$ potatoes) Valera lost. Valera remembers that the total amount of potatoes $(x + y)$ in the two bags, firstly, was not gerater than $n$, and, secondly, was divisible by $k$.\n\nHelp Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.",
    "tutorial": "The total number of potatoes is a multiple of $k$ and constraint $\\xrightarrow[{k}]{\\leq}10^{5}$ there will be at most $10^{5}$ multiples of $k$ in range $1$ to $n$. So you can iterate on multiples of $k$ and print the ones that satisfy the problem.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "239",
    "index": "B",
    "title": "Easy Tape Programming",
    "statement": "There is a programming language in which every program is a non-empty sequence of \"<\" and \">\" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts.\n\n- Current character pointer (CP);\n- Direction pointer (DP) which can point left or right;\n\nInitially CP points to the leftmost character of the sequence and DP points to the right.\n\nWe repeat the following steps until the first moment that CP points to somewhere outside the sequence.\n\n- If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was $0$ then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one.\n- If CP is pointing to \"<\" or \">\" then the direction of DP changes to \"left\" or \"right\" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is \"<\" or \">\" then the previous character will be erased from the sequence.\n\nIf at any moment the CP goes outside of the sequence the execution is terminated.\n\nIt's obvious the every program in this language terminates after some steps.\n\nWe have a sequence $s_{1}, s_{2}, ..., s_{n}$ of \"<\", \">\" and digits. You should answer $q$ queries. Each query gives you $l$ and $r$ and asks how many of each digit will be printed if we run the sequence $s_{l}, s_{l + 1}, ..., s_{r}$ as an independent program in this language.",
    "tutorial": "In this problem you just need to simulate every thing which is written in the statement step by step.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "242",
    "index": "A",
    "title": "Heads or Tails",
    "statement": "Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin $x$ times, then Petya tosses a coin $y$ times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.\n\nAt some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least $a$ times, and Petya got heads at least $b$ times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.",
    "tutorial": "This problem was very easy, we should only use two cycles with $i$ and with $j$ ($a  \\le  i  \\le  x$, $b  \\le  j  \\le  y$), iterate all possible outcomes of the game and print such in that $i > j$. The time is $O(x \\cdot y)$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "242",
    "index": "B",
    "title": "Big Segment",
    "statement": "A coordinate line has $n$ segments, the $i$-th segment starts at the position $l_{i}$ and ends at the position $r_{i}$. We will denote such a segment as $[l_{i}, r_{i}]$.\n\nYou have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.\n\nFormally we will assume that segment $[a, b]$ covers segment $[c, d]$, if they meet this condition $a ≤ c ≤ d ≤ b$.",
    "tutorial": "At first, we must note that the answer is always unique, because if segment $i$ covers segment $j$, that segment $j$ can't cover segment $i$. It possible if and only if there are coincide segments in the set, but it's not permissible by the statement. Let's pay attention the answer covers the most left point of all segments and the most right point of all points too. Now then we should found $L = min(l_{i})$ and $R = max(r_{i})$ and print index of segment $[L, R]$, or $- 1$ if there is no such segment in the set. The time is $O(n)$.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "242",
    "index": "C",
    "title": "King's Path",
    "statement": "The black king is standing on a chess field consisting of $10^{9}$ rows and $10^{9}$ columns. We will consider the rows of the field numbered with integers from $1$ to $10^{9}$ from top to bottom. The columns are similarly numbered with integers from $1$ to $10^{9}$ from left to right. We will denote a cell of the field that is located in the $i$-th row and $j$-th column as $(i, j)$.\n\nYou know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as $n$ segments. Each segment is described by three integers $r_{i}, a_{i}, b_{i}$ $(a_{i} ≤ b_{i})$, denoting that cells in columns from number $a_{i}$ to number $b_{i}$ inclusive in the $r_{i}$-th row are allowed.\n\nYour task is to find the minimum number of moves the king needs to get from square $(x_{0}, y_{0})$ to square $(x_{1}, y_{1})$, provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.\n\nLet us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.",
    "tutorial": "The most important thing for accepted solution is that it is guaranteed that the total length of all given segments doesn't exceed $10^{5}$. We should use this feature, let's number allowed cells and found shortest path by BFS. It's easiest to use associative array such as map in C++ for numbering. The time is $O(n \\cdot log(n))$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "hashing",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "242",
    "index": "D",
    "title": "Dispute",
    "statement": "Valera has $n$ counters numbered from $1$ to $n$. Some of them are connected by wires, and each of the counters has a special button.\n\nInitially, all the counters contain number $0$. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.\n\nValera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number $i$, which has value $a_{i}$, then Valera loses the dispute, otherwise he wins the dispute.\n\nHelp Valera to determine on which counters he needs to press a button to win the dispute.",
    "tutorial": "Denote current value of counter number $i$ as $b_{i}$. Let's describe an algorithm. It takes any counter $i$ such that $b_{i} = a_{i}$ and presses its button. The algorithm finishes if there is no such $i$. Let's proof correctness of the algorithm: Why does Valera win the game? Because there is no such counter which has $b_{i} = a_{i}$ else we must press the button. Why doesn't algorithm press some button multiple times? Because it presses button number $i$ only if $b_{i} = a_{i}$, and after this pressing the value $b_{i}$ is increased and the equation will be true never. Why is the algorithm fast? Because of paragraph 2 it does no more $n$ pressings which produces no more $n + 2 \\cdot m$ increases of the counters. We should use queue for fast seaching counters which has $b_{i} = a_{i}$ like this: every time we change value of the counter numbered $i$ we check equation $b_{i} = a_{i}$ and if it's true then we push value $i$ to the queue. It's easy to understand that all indexes $i$ will be in queue no more one time. Also these paragraphs proof that the answer always exists. You must print $- 1$ never. The time is $O(n + m)$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "242",
    "index": "E",
    "title": "XOR on Segment",
    "statement": "You've got an array $a$, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. You are allowed to perform two operations on this array:\n\n- Calculate the sum of current array elements on the segment $[l, r]$, that is, count value $a_{l} + a_{l + 1} + ... + a_{r}$.\n- Apply the xor operation with a given number $x$ to each array element on the segment $[l, r]$, that is, execute $a_{I}=a_{I}\\oplus x,a_{I+1}=a_{I+1}\\oplus x,\\cdot\\cdot\\cdot,a_{r}=a_{r}\\oplus x$. This operation changes exactly $r - l + 1$ array elements.\n\nExpression $x\\oplus y$ means applying bitwise xor operation to numbers $x$ and $y$. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as \"^\", in Pascal — as \"xor\".\n\nYou've got a list of $m$ operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get.",
    "tutorial": "Let's write numbers $a_{1}, a_{2}, ..., a_{n}$ as a table which has size $n  \\times  20$, and $b_{i, j}$ is $j$th bit in $a_{i}$. Then sum of numbers on segment $[l, r]$ equals $\\begin{array}{l}{{\\sum_{i=l}^{r}\\sum_{j=0}^{19}b_{i,j}\\cdot2^{j}=\\sum_{j=0}^{19}2^{j}\\cdot(\\sum_{i=l}^{r}b_{i,j})}}\\end{array}$. The last notation helps us to process queries. For fast implementation we should use 20 binary trees like cartesian trees or range trees. Every tree matchs one of bits (and matchs one of the columns of the table $b_{i, j}$). calculation of sum is equal to counting $1$-s from $l$-th to $r$-th. operation \"xor\" equals reversing all bits from $l$-th to $r$-th (i.e. $0$ changes to $1$, $1$ changes to $0$). The first operation executes for all bit numbers, the second executes only for bits in which input number $x_{i}$ has ones. These operations may be easy implemented with binary trees. The time is $O(m \\cdot log(n) \\cdot 20)$.",
    "tags": [
      "bitmasks",
      "data structures"
    ],
    "rating": 2000
  },
  {
    "contest_id": "243",
    "index": "A",
    "title": "The Brand New Function",
    "statement": "Polycarpus has a sequence, consisting of $n$ non-negative integers: $a_{1}, a_{2}, ..., a_{n}$.\n\nLet's define function $f(l, r)$ ($l, r$ are integer, $1 ≤ l ≤ r ≤ n$) for sequence $a$ as an operation of bitwise OR of all the sequence elements with indexes from $l$ to $r$. Formally: $f(l, r) = a_{l} | a_{l + 1} | ...  | a_{r}$.\n\nPolycarpus took a piece of paper and wrote out the values of function $f(l, r)$ for all $l, r$ ($l, r$ are integer, $1 ≤ l ≤ r ≤ n$). Now he wants to know, how many \\textbf{distinct} values he's got in the end.\n\nHelp Polycarpus, count the number of distinct values of function $f(l, r)$ for the given sequence $a$.\n\nExpression $x | y$ means applying the operation of bitwise OR to numbers $x$ and $y$. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as \"|\", in Pascal — as \"or\".",
    "tutorial": "Let's see how function $f$ changes for all suffixes of sequence $a$. Values of $f$ will increase when you will increase length of suffix. For every increase all 1-bits will stay 1-bits, but some 0-bits will be changed by 1-bits. So, you can see that no more than $k$ increasing will be, where $k$ number of bits (in this problem $k$ = 20). Among all suffixes will be no more that $k + 1$ values of function $f$. Now you can run over sequence $a$ trom left to right and support an array $m$ (or a set) of values of $f$ for all subsegments that end in the current position. Size of $m$ always no more than $k + 1$. When you go from position $i - 1$ into position $i$, you should replace $m = {m_{1}, m_{2}, ..., m_{t}}$ by $m' = {a_{i}, m_{1}|a_{i}, m_{2}|a_{i}, ... m_{t}|a_{i}}$. After that you should remove from $m$ repeated values (if you use set, set will do this dirty work itself). Then you should mark all numbers from $m$ in some global array (or put them into some global set). At the end you should calculate answer from the global array (or set).",
    "tags": [
      "bitmasks"
    ],
    "rating": 1600
  },
  {
    "contest_id": "243",
    "index": "B",
    "title": "Hydra",
    "statement": "One day Petya got a birthday present from his mom: a book called \"The Legends and Myths of Graph Theory\". From this book Petya learned about a hydra graph.\n\nA non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes $u$ and $v$ connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with $h$ nodes, which are the hydra's heads. The stomach is connected with $t$ nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of $h + t + 2$ nodes.\n\nAlso, Petya's got a non-directed graph $G$, consisting of $n$ nodes and $m$ edges. Petya got this graph as a last year birthday present from his mom. Graph $G$ contains no self-loops or multiple edges.\n\nNow Petya wants to find a hydra in graph $G$. Or else, to make sure that the graph doesn't have a hydra.",
    "tutorial": "You should check for every edge: this one can be body of hydra or not. Let's fix some edge $(u, v)$ (order of vertices is important, i.e. you should also check edge $(v, u)$). Now you should chose some set of $h$ vertices connected with $u$ and some set of $t$ vertices connected with $v$. These sets should not contain vertices $u$ and $v$. Also, these two sets should have no common vertices. If $\\deg(u)<h+1$ and ${\\mathrm{deg}}(v)<t+1$, there is no any hydra here. Orherwise, if $\\deg(u)\\geq h+t+1$ or $\\deg(v)\\geq h+t+1$, there is some hydra in any case. Even if all vertices connected with $u$ and with $v$ are common, number of them so big, that you always can split them into groups of size $ \\ge  h$ and size $ \\ge  t$. The last case is $h+1\\leq\\deg(u)\\leq h+l$ and $t+1\\leq\\deg(v)\\leq h+l$. Here you can find all common vertices in $O(h + t)$, using array of flags. When you find the common subset, you can easy check existence of hydra. How to find common vertices in O(h + t) using array of flgs? You should initailize that array in the beginning of program. For every check you should do following actions. Firstly in $O(\\mathrm{deg}(u))$ you should mark in the array all neighbours of $u$. After that you should iterate over all adjacent to $v$ vertices and check value of flag in the array for every of them (in $\\deg(v)$). Vertices that have \"thue\" in the array will be common. Finally you should clear the array in $O(\\mathrm{deg}(u))$: you should iterate over all adjacent to $u$ vertices again and mark these vertices in the array as \"false\". Because $\\deg(u)\\leq h+l$ and $\\deg(v)\\leq h+l$, the total complexity will be O(h + t). All edges can be checked in time $O(m(h + t))$. So you either find reqired edge or find that there is no required edge. Also in time $O(m)$ you can build hydra with fixed body-edge. This problem also has solution in $O(m{\\sqrt{m}})$ independent from values of $h$ and $t$, but this solution is more complex.",
    "tags": [
      "graphs",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "243",
    "index": "C",
    "title": "Colorado Potato Beetle",
    "statement": "Old MacDonald has a farm and a large potato field, $(10^{10} + 1) × (10^{10} + 1)$ square meters in size. The field is divided into square garden beds, each bed takes up one square meter.\n\nOld McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the insects, Old McDonald wants to spray some beds with insecticides.\n\nSo Old McDonald went to the field, stood at the center of the central field bed and sprayed this bed with insecticides. Now he's going to make a series of movements and spray a few more beds. During each movement Old McDonald moves left, right, up or down the field some integer number of meters. As Old McDonald moves, he sprays all the beds he steps on. In other words, the beds that have any intersection at all with Old McDonald's trajectory, are sprayed with insecticides.\n\nWhen Old McDonald finished spraying, he wrote out all his movements on a piece of paper. Now he wants to know how many beds won't be infected after the invasion of the Colorado beetles.\n\nIt is known that the invasion of the Colorado beetles goes as follows. First some bed on the field border gets infected. Than any bed that hasn't been infected, hasn't been sprayed with insecticides and has a common side with an infected bed, gets infected as well. Help Old McDonald and determine the number of beds that won't be infected by the Colorado potato beetle.",
    "tutorial": "Firstly tou should emulate all process in \"idle mode\". Let farmer was in points $(x_{0} + 1 / 2, y_{0} + 1 / 2)$, $(x_{1} + 1 / 2, y_{1} + 1 / 2)$, ... , $(x_{n} + 1 / 2, y_{n} + 1 / 2)$. Coordinates $x_{0}$, $x_{0} + 1$, $x_{1}$, $x_{1} + 1$, ... $x_{n}$, $x_{n} + 1$ on axis $x$ are interesting for us. Coordinates $y_{0}$, $y_{0} + 1$, $y_{1}$, $y_{1} + 1$, ... $y_{n}$, $y_{n} + 1$ on axis $y$ are interesting too. You should store all of them into two arrays. Also you should add to these coordinates bounds of the field. Then you should build \"compressed\" field: every cell of this field means rectangle of the starting field that placed between neighbour interesting coordinates. Size of the compressed field is $O(n)  \\times  O(n)$. Let's initally all cells painted into the white color. Now you should emulate all process again and paint all visited cells in the compressed field by the black color. During every move you will paint $O(n)$ cells, so all process will be done in $O(n^{2})$. Now you should emulate bugs' actions. You should run DFS (ot BFS) from some border cell of the compressed field and paint all reached cells be red color. At the end you should iterate over all compressed field and find sum of areas of rectengles corresponding to black and white cells. So, you will receive the answer. This solution works in $O(n^{2})$.",
    "tags": [
      "dfs and similar",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "243",
    "index": "D",
    "title": "Cubes",
    "statement": "One day Petya got a set of wooden cubes as a present from his mom. Petya immediately built a whole city from these cubes.\n\nThe base of the city is an $n × n$ square, divided into unit squares. The square's sides are parallel to the coordinate axes, the square's opposite corners have coordinates $(0, 0)$ and $(n, n)$. On each of the unit squares Petya built a tower of wooden cubes. The side of a wooden cube also has a unit length.\n\nAfter that Petya went an infinitely large distance away from his masterpiece and looked at it in the direction of vector $v = (v_{x}, v_{y}, 0)$. Petya wonders, how many distinct cubes are visible from this position. Help him, find this number.\n\nEach cube includes the border. We think that a cube is visible if there is a ray emanating from some point $p$, belonging to the cube, in the direction of vector $ - v$, that doesn't contain any points, belonging to other cubes.",
    "tutorial": "You need for every column find the lowermost cube that you can see. You will see all cubes above this cube. Consider the city from above. You will see drid of size $n  \\times  n$. Now you should draw the line through every node of the grid parallel to vector $v$. We need know only that happens in every strip between two neighbour lines. Every column cover segment of $O(n)$ adjacent strips. Now you should create an array $a$; every element of $a$ corresponding to one strip. This array will store maximal height of considered columns. Then you should sort all columns in order if increasing distance from observer. In that order you should do following queries of 2 types: Minimum on segment. This query is needed when you want find the lowermost visible cube. Replace $a_{i}  \\rightarrow  max(a_{i}, h)$ on segment. You need this query for \"drawing\" column in the array. That is all solution. You just need choose some data structure that can fast do queries. You can select from: block decomposition (length of every block should be $\\sqrt{n}$; because length of every query about $O(n)$, total complexity of solution will be $O(n^{5 / 2})$), segment tree ($O(n^2 \\log n)$), stupid array (it's $O(n^{3})$, cache optimized implementaton fits in the time limit).",
    "tags": [
      "data structures",
      "dp",
      "geometry",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "243",
    "index": "E",
    "title": "Matrix",
    "statement": "Let's consider an $n × n$ square matrix, consisting of digits one and zero.\n\nWe'll consider a matrix good, if it meets the following condition: in each row of the matrix all ones go in one group. That is, each row of the matrix looks like that $00...0011...1100...00$ (or simply consists of zeroes if it has no ones).\n\nYou are given matrix $a$ of size $n × n$, consisting of zeroes and ones. Your task is to determine whether you can get a good matrix $b$ from it by rearranging the columns or not.",
    "tutorial": "We will build the matrix constructively. At any step we will have array of groups of columns. Order of groups is defined but order of columns inside every group is unknown. During building we will change order of rows because it is doesn't affect the answer (we can build answer using order of columns only). Consider the way of building of the matrix. Firstly you should find the row that has maximal number of ones. You should swap this row with the first row. Aftar that two groups of columns should be created. Into the first group you should put columns that have \"1\" in the firts row; all other columns should be stored into the second group. The second group is \"special\" - see about it below. Now you should more times search the row that has \"1\" in at least two groups. For every of that rows you can determine positions of all ones no more than only way. If you determined no ways, you should output NO and finish execution. After that you determined positions of ones, you should split some groups of columns into two subgroups. About \"special\" group. You should take into account case when you should drop some columns from this group and insert them before all groups. You will never face with situation when it is not clear which columns should be dropped and which should not, because in the beginning you chose the row with maximal number of ones. After repeating process than described above sevaral times, \"good\" rows may end. I.e. for every row all ones will be placed in no more than one group. Now you should recursively do solution described above inside every of groups of columns. The solution works in $O(n^{3})$. It can be upgraded to $O(n^2 \\log n)$, but it was not required.",
    "tags": [
      "data structures"
    ],
    "rating": 3000
  },
  {
    "contest_id": "244",
    "index": "A",
    "title": "Dividing Orange",
    "statement": "One day Ms Swan bought an orange in a shop. The orange consisted of $n·k$ segments, numbered with integers from 1 to $n·k$.\n\nThere were $k$ children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the $i$-th $(1 ≤ i ≤ k)$ child wrote the number $a_{i}$ $(1 ≤ a_{i} ≤ n·k)$. All numbers $a_{i}$ accidentally turned out to be different.\n\nNow the children wonder, how to divide the orange so as to meet these conditions:\n\n- each child gets exactly $n$ orange segments;\n- the $i$-th child gets the segment with number $a_{i}$ for sure;\n- no segment goes to two children simultaneously.\n\nHelp the children, divide the orange and fulfill the requirements, described above.",
    "tutorial": "Consider an array $A$ of integers in range from 1 to $nk$. Let's remove from $A$ all numbers $a_{i}$ and all other numbers store into an array $B$. The array $B$ will have $(n - 1)k$ elements. Now for $i$-th kid you should output numbers $a_{i}$, $B[(n - 1) * (i - 1) + 1]$, $B[(n - 1) * (i - 1) + 2]$, ... $B[(n - 1) * (i - 1) + n - 1]$ ($B$ is 1-based).",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "244",
    "index": "B",
    "title": "Undoubtedly Lucky Numbers",
    "statement": "Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits $x$ and $y$. For example, if $x = 4$, and $y = 7$, then numbers 47, 744, 4 are lucky.\n\nLet's call a positive integer $a$ undoubtedly lucky, if there are such digits $x$ and $y$ $(0 ≤ x, y ≤ 9)$, that the decimal representation of number $a$ (without leading zeroes) contains only digits $x$ and $y$.\n\nPolycarpus has integer $n$. He wants to know how many positive integers that do not exceed $n$, are undoubtedly lucky. Help him, count this number.",
    "tutorial": "Solution 1. You should write some bruteforce solution over all numbers with no more than 9 digits (number $10^{9}$ should be considered separately). Bruteforce algo seems like this: dfs( int num ) // run it as dfs(0) if (num > 0 && num <= n) ans++ if (num >= 10^8) return for a = 0..9 do if num*10+a>0 then if number num*10+a has no more than 2 different digits then dfs( num*10+a )ans will store the answer. After that you wrote bruteforce, you can run it and see that it works fast (that is same time for any testcase). Solution 2. Let's build all undoubdetly lucku numbers using bitmasks. You can iterate over length of number $L$, pair of digits $x$ and $y$, and bitmask $m$ of length $L$. If the $i$-th bit of $m$ is 1, the $i$-th digit of number should be $x$; otherwise it should be $y$. So about $10^{3}  \\times  2^{10}$ numbers will be generated (it is very rough estimate, count of numbers will be more than 10 times less). In this solution you should accurately process the case of leading zeroes and the case when all digits of number are same.",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar"
    ],
    "rating": 1600
  },
  {
    "contest_id": "245",
    "index": "A",
    "title": "System Administrator",
    "statement": "Polycarpus is a system administrator. There are two servers under his strict guidance — $a$ and $b$. To stay informed about the servers' performance, Polycarpus executes commands \"ping a\" and \"ping b\". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers $x$ and $y$ $(x + y = 10; x, y ≥ 0)$. These numbers mean that $x$ packets successfully reached the corresponding server through the network and $y$ packets were lost.\n\nToday Polycarpus has performed overall $n$ ping commands during his workday. Now for each server Polycarpus wants to know whether the server is \"alive\" or not. Polycarpus thinks that the server is \"alive\", if at least half of the packets that we send to this server reached it successfully along the network.\n\nHelp Polycarpus, determine for each server, whether it is \"alive\" or not by the given commands and their results.",
    "tutorial": "Let's define following variables: $A_{Reached}$ : Number of packets that reached $A$. $A_{Lost}$ : Number of packets which didn't reach $A$. $B_{Reached}$ : Number of packets that reached $B$. $B_{Lost}$ : Number of packets which didn't reach $B$. We iterate over input and update each variable accordingly. Now answer for server $A$ is LIVE if and only if $A_{Reached}  \\ge  A_{Lost}$ otherwise it's DEAD. Also answer for server $B$ is LIVE if and only if $B_{Reached}  \\ge  B_{Lost}$ otherwise it's DEAD.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint A_Reached, A_Lost, B_Reached, B_Lost;\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\tfor (int i = 1 ; i <= n ; i++)\n\t{\n\t\tint t, x, y;\n\t\tcin >> t >> x >> y;\n\t\tif (t == 1)\n\t\t{\n\t\t\tA_Reached += x; \n\t\t\tA_Lost += y;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tB_Reached += x;\n\t\t\tB_Lost += y;\n\t\t}\n\t}\n\tif (A_Reached >= A_Lost)\n\t\tcout << \"LIVE\" << endl;\n\telse\n\t\tcout << \"DEAD\" << endl;\n\tif (B_Reached >= B_Lost)\n\t\tcout << \"LIVE\" << endl;\n\telse\n\t\tcout << \"DEAD\" << endl;\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "245",
    "index": "B",
    "title": "Internet Address",
    "statement": "Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format:\n\n\\begin{center}\n<protocol>://<domain>.ru[/<context>]\n\\end{center}\n\nwhere:\n\n- <protocol> can equal either \"http\" (without the quotes) or \"ftp\" (without the quotes),\n- <domain> is a non-empty string, consisting of lowercase English letters,\n- the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters.\n\nIf string <context> isn't present in the address, then the additional character \"/\" isn't written. Thus, the address has either two characters \"/\" (the ones that go before the domain), or three (an extra one in front of the context).\n\nWhen the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters \":\", \"/\", \".\".\n\nHelp Vasya to restore the possible address of the recorded Internet resource.",
    "tutorial": "Problem guarantees that there exists an Internet resource address from which we can obtain our input. At first, let's find Protocol of address. It's sufficient to only check first letter of input, if it's $h$ then protocol is $http$ otherwise, it's $ftp$. Now, let's find position of $.ru$. We can iterate over our string from right to left and greedily choose the first occurrence of $.ru$ as TLD. Now the rest of Internet address can be obtained easily as we have positions of Protocol and TLD. Just note that we should check whether $< context >$ is present after $.ru$ or not. Also picking $.ru$ greedily from left to right fails following testcase, hence it's incorrect. Input: httpruru Incorrect output: http://.ru/ru Correct output: http://ru.ru",
    "code": "#include <iostream>\n\nusing namespace std;\n\nstring ans, s;\nint index;\n\nint main()\n{\n\tcin >> s;\n\tif (s[0] == 'h')\n\t{\n\t\tans += \"http://\";\n\t\tindex = 4;\n\t}\n\telse\n\t{\n\t\tans += \"ftp://\";\n\t\tindex = 3;\n\t}\n\tfor (int i = (int)s.size()-3 ; i >= index ; i--)\n\t\tif (s[i] == 'r' && s[i+1] == 'u')\n\t\t{\n\t\t\tcout << ans + s.substr(index, i-index) + \".ru/\" + s.substr(i+2) << endl;\n\t\t\treturn 0;\n\t\t}\n\tcout << ans + s.substr(index, (int)s.size()-2-index) + \".ru\" << endl;\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "245",
    "index": "C",
    "title": "Game with Coins",
    "statement": "Two pirates Polycarpus and Vasily play a very interesting game. They have $n$ chests with coins, the chests are numbered with integers from 1 to $n$. Chest number $i$ has $a_{i}$ coins.\n\nPolycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer $x$ $(2·x + 1 ≤ n)$ and take a coin from each chest with numbers $x$, $2·x$, $2·x + 1$. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.\n\nPolycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.",
    "tutorial": "First note that if $n  \\le  2$ or $n\\equiv0{\\bmod{2}}$ then answer is $- 1$. It's because of the following $2$ facts: 1. $2x+1\\leq n\\to x\\leq{\\frac{n-1}{2}}$ and $x\\in\\mathbb{N}$ so $n  \\ge  3$ otherwise $x$ won't be a natural number. 2. If $n\\equiv0{\\bmod{2}}$ then $n = 2k$ and $x\\leq{\\frac{2k-1}{2}}$ which means $x  \\le  k - 1$ hence $2x + 1  \\le  2k - 1$ so there doesn't exist a $x$ such that it satisfies problem's conditions and can be used to reduce $a[n]$ In other situations, there always exists a sequence which can finish the game. We now propose a greedy algorithm and then prove it's correctness. Algorithm: Iterate from $n$ to $2$. Suppose that you're in position $i$. If $i\\equiv0{\\bmod{2}}$ then take $x={\\frac{i}{2}}$ otherwise, take $x={\\frac{i-1}{2}}$ and execute operations with obtained $x$ as long as $a[i] > 0$ and increase $ans$ for each execution. At the end, increase $ans$ by $a[1]$ and output it. Remember to check if an element you're going to decrease by $1$ is positive beforehand. Correctness: Let's prove correctness of algorithm by induction on $n$. Base case is $n = 3$ in which $ans = max(a[1], a[2], a[3])$ and algorithm correctly computes it. Now take $n  \\ge  5$ and consider it's of the form $2k + 1$. To change $a[n]$ and $a[n - 1]$ into $0$, we need to take $x = k$ as it's the only possible $x$ which affects their values and perform operations exactly $max(a[n], a[n - 1])$ number of times. It's both necessary and sufficient in order to change both of them into $0$. After that, we can ignore both $a[n]$ and $a[n - 1]$ from the list and induction hypothesis ensures that executing algorithm on remaining elements finishes the game in the least number of moves. $\\blacksquare$",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int MAXN = 110;\n\nint n, a[MAXN], ans;\n\nint main()\n{\n\tcin >> n;\n\tif (n <= 2 || n % 2 == 0)\n\t{\n\t\tcout << -1 << endl;\n\t\treturn 0;\n\t}\n\tfor (int i = 1 ; i <= n ; i++)\n\t\tcin >> a[i];\n\tfor (int i = n ; i >= 2 ; i--)\n\t{\n\t\twhile (a[i] && i & 1)\n\t\t{\n\t\t\tint x = (i-1)/2;\n\t\t\ta[i]--;\n\t\t\ta[x] -= (a[x]) ? 1 : 0;\n\t\t\ta[2*x] -= (a[2*x]) ? 1 : 0;\n\t\t\tans++;\n\t\t}\n\t\twhile (a[i] && i % 2 == 0)\n\t\t{\n\t\t\tint x = i/2;\n\t\t\ta[i]--;\n\t\t\ta[x] -= (a[x]) ? 1 : 0;\n\t\t\ta[2*x+1] -= (a[2*x+1]) ? 1 : 0;\n\t\t\tans++;\n\t\t}\n\t}\n\tans += a[1];\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "245",
    "index": "D",
    "title": "Restoring Table",
    "statement": "Recently Polycarpus has learned the \"bitwise AND\" operation (which is also called \"AND\") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.\n\nFor that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers $a_{1}, a_{2}, ..., a_{n}$. He also wrote a square matrix $b$ of size $n × n$. The element of matrix $b$ that sits in the $i$-th row in the $j$-th column (we'll denote it as $b_{ij}$) equals:\n\n- the \"bitwise AND\" of numbers $a_{i}$ and $a_{j}$ (that is, $b_{ij} = a_{i} & a_{j}$), if $i ≠ j$;\n- -1, if $i = j$.\n\nHaving written out matrix $b$, Polycarpus got very happy and wiped $a$ off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly.\n\nHelp Polycarpus, given matrix $b$, restore the sequence of numbers $a_{1}, a_{2}, ..., a_{n}$, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed $10^{9}$.",
    "tutorial": "Consider $a[i]$, $a[j]$ and $b[i][j] = a[i]&a[j]$. Now consider binary representation of $b[i][j]$. For each $1$-bit of $b[i][j]$ at position $k$, ($0$-indexed) we conclude that $k$-th bit of $a[i]$ and $a[j]$ equals $1$ so we set $a[i] = a[i]|2^{k}$ and $a[j] = a[j]|2^{k}$. Now let's describe algorithm. We use $i$ to iterate from $1$ to $n$ and for each $i$, we iterate over all $b[i][j]$ such that $i  \\neq  j$ and assign $a[i] = a[i]|b[i][j]$. At the end, we'll have sequence $a$ constructed. Now we prove correctness of algorithm. Correctness: Consider $2$ indices $i$ and $j$ such that $a[i]&a[j]  \\neq  b[i][j]$. Consider that $k$-th bit of $a[i]&a[j]$ differs from $k$-th bit of $b[i][j]$. If $k$-th bit of their $AND$ equals $0$, we face contradiction as $k$-th bit of $b[i][j]$ has to be $1$ and algorithm ensures that in this situation, $k$-th bit of both numbers will be set as $1$. On the other hand, if $k$-th bit of their $AND$ equals $1$ then we conclude that $k$-th bit of both numbers equals $1$ hence when calculating $AND$ of them, we get $1$ in $k$-th bit which is a contradiction with our preliminary hypothesis. So we proved correctness of algorithm. $\\blacksquare$",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int MAXN = 110;\n\nint n, a[MAXN];\n\nint main()\n{\n\tcin >> n;\n\tfor (int i = 1 ; i <= n ; i++)\n\t\tfor (int j = 1 ; j <= n ; j++)\n\t\t{\n\t\t\tint AND;\n\t\t\tcin >> AND;\n\t\t\tif (i != j)\n\t\t\t\ta[i] |= AND;\n\t\t}\n\tfor (int i = 1 ; i <= n ; i++)\n\t\tcout << a[i] << \" \";\n\tcout << endl;\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "245",
    "index": "E",
    "title": "Mishap in Club",
    "statement": "Polycarpus just has been out of luck lately! As soon as he found a job in the \"Binary Cat\" cafe, the club got burgled. All ice-cream was stolen.\n\nOn the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character \"+\" in his notes. Similarly, each time a visitor left the club, Polycarpus put character \"-\" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.\n\nRight now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.",
    "tutorial": "Consider following interpretation of problem. We're standing in $(0, 0)$ at the center of Cartesian coordinate system. We iterate over the given sequence, for each $+$, we move from $(x, y)$ to $(x + 1, y + 1)$ and for each $-$, we move from $(x, y)$ to $(x + 1, y - 1)$. Consider the maximum $y$ coordinate we visit during our movement as $MAX$ and minimum $y$ we visit as $MIN$. It's obvious that we need at least $MAX - MIN$ people. It can be proved that we can take our moves in such a way that we exactly need $MAX - MIN$ people. For each $+$, if there exists a person out of cafe who had entered cafe once or was in cafe once, we move him in, otherwise, we need a new person. The same argument holds for each $-$ we see in sequence.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nstring s;\nint MAX, MIN, pos;\n\nint main()\n{\n\tcin >> s;\n\tfor (int i = 0 ; i < (int)s.size() ; i++)\n\t\tif (s[i] == '+')\n\t\t{\n\t\t\tpos++;\n\t\t\tMAX = max(pos, MAX);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpos--;\n\t\t\tMIN = min(pos, MIN);\n\t\t}\n\tcout << MAX - MIN << endl;\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "245",
    "index": "F",
    "title": "Log Stream Analysis",
    "statement": "You've got a list of program warning logs. Each record of a log stream is a string in this format:\n\n\\begin{center}\n\"2012-MM-DD HH:MM:SS:MESSAGE\" (without the quotes).\n\\end{center}\n\nString \"MESSAGE\" consists of spaces, uppercase and lowercase English letters and characters \"!\", \".\", \",\", \"?\". String \"2012-MM-DD\" determines a correct date in the year of 2012. String \"HH:MM:SS\" determines a correct time in the 24 hour format.\n\nThe described record of a log stream means that at a certain time the record has got some program warning (string \"MESSAGE\" contains the warning's description).\n\nYour task is to print the first moment of time, when the number of warnings for the last $n$ seconds was not less than $m$.",
    "tutorial": "First note that \"MESSAGE\" is useless and can be ignored. Year is always $2012$ so it can be ignored too. Now convert each date and time to seconds past from beginning of $2012$. Maintain a list, such as a vector, $V$, for storing seconds. Define pointer $head$ to be head of your vector. Define $sec$ to be conversion of date and time in seconds for the most recent log. As long as $head  \\le  Size[V]$ and $V[head] + n  \\le  sec$, increase $head$. After that, push $sec$ into $V$. If $Size[V] - head  \\ge  m$ then answer is the current log. If at the end, no time was found, answer will be $- 1$. Implementation Note: You may use $stringstream$ in order to ease implementation part.",
    "code": "#include <iostream>\n#include <sstream>\n#include <vector>\n\nusing namespace std;\n\n\nvector <int> v;\n\nint months[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\nint n, m, head;\nstring s;\n\nint input(string temp)\n{\n\tint val;\n\tstringstream sin;\n\tsin << temp;\n\tsin >> val;\n\treturn val;\n}\n\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin >> n >> m;\n\tgetline(cin, s);\n\twhile (getline(cin, s))\n\t{\n\t\tint month =  input(s.substr(5, 2));\n\t\tint day = input(s.substr(8, 2));\n\t\tint hour = input(s.substr(11, 2));\n\t\tint min = input(s.substr(14, 2));\n\t\tint second = input(s.substr(17, 2));\n\t\tint sec = second + min * 60 + hour * 3600 + day * 24 * 3600;\n\t\tfor (int i = 0 ; i+1 < month ; i++)\n\t\t\tsec += months[i] * 24 * 3600;\n\t\twhile (head < (int)v.size() && v[head] + n <= sec)\n\t\t\thead++;\n\t\tv.push_back(sec);\n\t\tif ((int)v.size() - head >= m)\n\t\t{\n\t\t\tcout << s.substr(0, 19) << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout << -1 << endl;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "245",
    "index": "G",
    "title": "Suggested Friends",
    "statement": "Polycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion.\n\nLet's say that all friendship relationships in a social network are given as $m$ username pairs $a_{i}, b_{i}$ $(a_{i} ≠ b_{i})$. Each pair $a_{i}, b_{i}$ means that users $a_{i}$ and $b_{i}$ are friends. Friendship is symmetric, that is, if $a_{i}$ is friends with $b_{i}$, then $b_{i}$ is also friends with $a_{i}$. User $y$ is a suggested friend for user $x$, if the following conditions are met:\n\n- $x ≠ y$;\n- $x$ and $y$ aren't friends;\n- among all network users who meet the first two conditions, user $y$ has most of all common friends with user $x$. User $z$ is a common friend of user $x$ and user $y$ $(z ≠ x, z ≠ y)$, if $x$ and $z$ are friends, and $y$ and $z$ are also friends.\n\nYour task is to help Polycarpus to implement a mechanism for determining suggested friends.",
    "tutorial": "Use $map$ in order to map people to numbers. Construct the given graph using adjacency list. Now, let's find answer for each vertex $v$. Mark all of $v$'s neighbors. After that iterate over all other vertices, and iterate over their adjacency list and count their mutual neighbors with $v$ and update answer for $v$. Complexity is $O(m)$ for each vertex $v$. Summing up all complexities, we conclude that our algorithm is of $O(nm)$ and as $n$ is of $O(m)$, we can conclude that overall complexity is $O(m^{2})$.",
    "code": "#include <iostream>\n#include <vector>\n#include <map>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAXN = 10000 + 10;\n\nmap <string, int> vertices;\nint n, m, mark[MAXN], ans[MAXN];\nvector <int> g[MAXN];\n\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin >> m;\n\tfor (int i = 1 ; i <= m ; i++)\n\t{\n\t\tstring s1, s2;\n\t\tcin >> s1 >> s2;\n\t\tif (!vertices[s1])\n\t\t\tvertices[s1] = ++n;\n\t\tif (!vertices[s2])\n\t\t\tvertices[s2] = ++n;\n\t\tint u = vertices[s1];\n\t\tint v = vertices[s2];\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\tfor (int i = 1 ; i <= n ; i++)\n\t{\n\t\tint count = 0;\n\t\tmemset(mark, 0, sizeof(mark));\n\t\tfor (int j = 0 ; j < (int)g[i].size() ; j++)\n\t\t\tmark[g[i][j]] = 1;\n\t\tfor (int j = 1 ; j <= n ; j++)\n\t\t\tif (i != j && !mark[j])\n\t\t\t{\n\t\t\t\tint temp = 0;\n\t\t\t\tfor (int k = 0 ; k < (int)g[j].size() ; k++)\n\t\t\t\t\ttemp += mark[g[j][k]];\n\t\t\t\tif (temp > ans[i])\n\t\t\t\t{\n\t\t\t\t\tans[i] = temp;\n\t\t\t\t\tcount = 1;\n\t\t\t\t}\n\t\t\t\telse if (temp == ans[i])\n\t\t\t\t\tcount++;\n\t\t\t}\n\t\tans[i] = count;\n\t}\n\tcout << n << endl;\n\tfor (map<string, int>::iterator it = vertices.begin() ; it != vertices.end() ; it++)\n\t\tcout << it->first << \" \" << ans[it->second] << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "245",
    "index": "H",
    "title": "Queries for Number of Palindromes",
    "statement": "You've got a string $s = s_{1}s_{2}... s_{|s|}$ of length $|s|$, consisting of lowercase English letters. There also are $q$ queries, each query is described by two integers $l_{i}, r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ |s|)$. The answer to the query is the number of substrings of string $s[l_{i}... r_{i}]$, which are palindromes.\n\nString $s[l... r] = s_{l}s_{l + 1}... s_{r}$ $(1 ≤ l ≤ r ≤ |s|)$ is a substring of string $s = s_{1}s_{2}... s_{|s|}$.\n\nString $t$ is called a palindrome, if it reads the same from left to right and from right to left. Formally, if $t = t_{1}t_{2}... t_{|t|} = t_{|t|}t_{|t| - 1}... t_{1}$.",
    "tutorial": "Note: Strings and arrays are considered $0$-based in the following solution. Let $isPal[i][j]$ be $1$ if $s[i...j]$ is palindrome, otherwise, set it $0$. Let's define $dp[i][j]$ to be number of palindrome substrings of $s[i...j]$. Let's calculate $isPal[i][j]$ and $dp[i][j]$ in $O(|S|^{2})$. First, initialize $isPal[i][i] = 1$ and $dp[i][i] = 1$. After that, loop over $len$ which states length of substring and for each specific $len$, loop over $start$ which states starting position of substring. $isPal[start][start + len - 1]$ can be easily calculated by the following formula: isPal[start][start+len-1] = isPal[start+1][start+len-2] & (s[start] == s[start+len-1])After that, $dp[start][start + len - 1]$ can be calculated by the following formula which is derived from Inc-Exc Principle. dp[start][start+len-1] = dp[start][start+len-2] + dp[start+1][start+len-1] - dp[start+1][start+len-2] + isPal[start][start+len-1]After preprocessing, we get queries $l_{i}$ and $r_{i}$ and output $dp[l_{i} - 1][r_{i} - 1]$. Overall complexity is $O(|S|^{2})$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int MAXN = 5000 + 10;\n\nstring s;\nint n, q, dp[MAXN][MAXN];\nbool isPal[MAXN][MAXN];\n\nint main()\n{\n    ios::sync_with_stdio(0);\n    cin >> s;\n    n = (int)s.size();\n    for (int i = 0 ; i < n ; i++)\n    {\n        isPal[i][i] = 1;\n        dp[i][i] = 1;\n        isPal[i+1][i] = 1;\n    }\n    for (int len = 2 ; len <= n ; len++)\n        for (int start = 0 ; start <= n-len ; start++)\n        {\n            isPal[start][start+len-1] = isPal[start+1][start+len-2] & s[start] == s[start+len-1];\n            dp[start][start+len-1] = dp[start][start+len-2] + dp[start+1][start+len-1] - dp[start+1][start+len-2] + isPal[start][start+len-1];\n        }\n    cin >> q;\n    for (int i = 1 ; i <= q ; i++)\n    {\n        int l, r;\n        cin >> l >> r;\n        l--;\n        r--;\n        cout << dp[l][r] << endl;\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "hashing",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "246",
    "index": "A",
    "title": "Buggy Sorting",
    "statement": "Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of $n$ integers $a_{1}, a_{2}, ..., a_{n}$ in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number $n$ and array $a$.\n\n\\begin{verbatim}\nloop integer variable\n$i$\nfrom\n$1$\nto\n$n - 1$\n    loop integer variable\n$j$\nfrom\n$i$\nto\n$n - 1$\n        if\n$(a_{j} > a_{j + 1})$\n, then swap the values of elements\n$a_{j}$\nand\n$a_{j + 1}$\n\\end{verbatim}\n\nBut Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of $n$ doesn't exist, print -1.",
    "tutorial": "In this problem you should hack the sorting algorithm, of course it was incorrect. It was correct only for arrays with $n < = 2$. In other cases you could print $n, n-1, ..., 1$ as a counter-example. To make the sorting right, the second cycle should be from $1$ but not from $i$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "246",
    "index": "B",
    "title": "Increase and Decrease",
    "statement": "Polycarpus has an array, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:\n\n- he chooses two elements of the array $a_{i}$, $a_{j}$ $(i ≠ j)$;\n- he simultaneously increases number $a_{i}$ by $1$ and decreases number $a_{j}$ by $1$, that is, executes $a_{i} = a_{i} + 1$ and $a_{j} = a_{j} - 1$.\n\nThe given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times.\n\nNow he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.",
    "tutorial": "Note, that you can always get the answer $n-1$. To get this result you should make first $n-1$ equal using the last element as the second element in pair of given operation. But after it, the whole array could become equal. It could happen if the sum of array's elements is divisible by $n$. So the answer is $n-1$ or $n$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "246",
    "index": "C",
    "title": "Beauty Pageant",
    "statement": "General Payne has a battalion of $n$ soldiers. The soldiers' beauty contest is coming up, it will last for $k$ days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.\n\nAll soldiers in the battalion have different beauty that is represented by a positive integer. The value $a_{i}$ represents the beauty of the $i$-th soldier.\n\nOn each of $k$ days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of $k$ days the beauty of the sent detachment should be unique. In other words, all $k$ beauties of the sent detachments must be distinct numbers.\n\nHelp Payne choose $k$ detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.",
    "tutorial": "This problem was rather mathematical. The correct solution is: firstly take every element once, then take the maximum and any other, then two maximums and any other, then three maximums and any other and so on. In this case, you get as many sets as you need in this problem. It is easy to check, that all sums will be different.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "246",
    "index": "D",
    "title": "Colorful Graph",
    "statement": "You've got an undirected graph, consisting of $n$ vertices and $m$ edges. We will consider the graph's vertices numbered with integers from 1 to $n$. Each vertex of the graph has a color. The color of the $i$-th vertex is an integer $c_{i}$.\n\nLet's consider all vertices of the graph, that are painted some color $k$. Let's denote a set of such as $V(k)$. Let's denote the value of the neighbouring color diversity for color $k$ as the cardinality of the set $Q(k) = {c_{u} :  c_{u} ≠ k$ and there is vertex $v$ belonging to set $V(k)$ such that nodes $v$ and $u$ are connected by an edge of the graph$}$.\n\nYour task is to find such color $k$, which makes the cardinality of set $Q(k)$ maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color $k$, that the graph has at least one vertex with such color.",
    "tutorial": "This problem could be solved in this way: create new graph where vertices are the colors of the given graph. The edge between vertices $u$ and $v$ belongs this new graph if there are two vertices $a$ and $b$ in the given graph such that $c[a] = u$ and $c[b] = v$. So, the answer is such color $k$ with minimum number, that the degree of the vertex $k$ in the new graph is maximum (without multiple edges). Such solution could be written using $O(M \\cdot log(N))$ time.",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1600
  },
  {
    "contest_id": "246",
    "index": "E",
    "title": "Blood Cousins Return",
    "statement": "Polycarpus got hold of a family tree. The found tree describes the family relations of $n$ people, numbered from 1 to $n$. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.\n\nWe call the man with a number $a$ a 1-ancestor of the man with a number $b$, if the man with a number $a$ is a direct ancestor of the man with a number $b$.\n\nWe call the man with a number $a$ a $k$-ancestor $(k > 1)$ of the man with a number $b$, if the man with a number $b$ has a 1-ancestor, and the man with a number $a$ is a $(k - 1)$-ancestor of the 1-ancestor of the man with a number $b$.\n\nIn the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an $x$-ancestor of himself, for some $x$, $x > 0$).\n\nWe call a man with a number $a$ the $k$-son of the man with a number $b$, if the man with a number $b$ is a $k$-ancestor of the man with a number $a$.\n\nPolycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote $m$ pairs of numbers $v_{i}$, $k_{i}$. Help him to learn for each pair $v_{i}$, $k_{i}$ the number of distinct names among all names of the $k_{i}$-sons of the man with number $v_{i}$.",
    "tutorial": "This problem had little in common with problem 208E - Blood Cousins. In comments to this problem there was given a solution using structure deque (array in which you can add or delete elements from both endings). Let's describe solution using this structure. Firstly all different names change with different integers and for every vertex $v$ save all queries with this vertex. Then for every vertex, which is root of some tree make dfs, the parameters of dfs are vertex $v$ and deque <set > $z$. This deque for every depth $i$ of the subtree of $v$ save set - all different names (integers) on depth $i$. This deque could be calculated simply. Consider all sons of $v$ and calculate such deque for them. Obviously, the size of our deque $z$ will be maximum of sizes of descendants' deques. Then consider every descendants' deques and merge appropriate sets of integers. Of course, we will merge smaller set to a larger set. After that you should insert to the beginning of deque $z$ the set of size $1$ - color of vertex $v$. After this, you can at once answer all queries of vertex $v$. Answer is $0$ if $v$ has no descendants on the depth $k$ or the size of $z[k]$. It is known that such method has good asymptotic, the author's solution works about one second. The asymptotic is $O(N \\cdot log^{2}(N))$. The solution should be realized carefully. You must not copy every element of your set or deque. You should do swap of smaller and greater set or deque without copying elements ant than merge smaller to greater.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dp",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "250",
    "index": "A",
    "title": "Paper Work",
    "statement": "Polycarpus has been working in the analytic department of the \"F.R.A.U.D.\" company for as much as $n$ days. Right now his task is to make a series of reports about the company's performance for the last $n$ days. We know that the main information in a day report is value $a_{i}$, the company's profit on the $i$-th day. If $a_{i}$ is negative, then the company suffered losses on the $i$-th day.\n\nPolycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the $n$ days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.\n\nIt is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses $(a_{i} < 0)$, he loses his temper and his wrath is terrible.\n\nTherefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.\n\nWrite a program that, given sequence $a_{i}$, will print the minimum number of folders.",
    "tutorial": "For every folder you should take reports as much as possible. In other words, you should stop forming a folder either before the third bad report or in the end of sequence. You can easily prove that this strategy is optimal. This solution works in $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "250",
    "index": "B",
    "title": "Restoring IPv6",
    "statement": "An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: \"0124:5678:90ab:cdef:0124:5678:90ab:cdef\". We'll call such format of recording an IPv6-address full.\n\nBesides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: \"a56f:00d3:0000:0124:0001:f19a:1000:0000\" $ → $ \"a56f:d3:0:0124:01:f19a:1000:00\". There are more ways to shorten zeroes in this IPv6 address.\n\nSome IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to \"::\". A sequence can consist of one or several \\textbf{consecutive blocks}, with all 16 bits equal to 0.\n\nYou can see examples of zero block shortenings below:\n\n- \"a56f:00d3:0000:0124:0001:0000:0000:0000\" $ → $ \"a56f:00d3:0000:0124:0001::\";\n- \"a56f:0000:0000:0124:0001:0000:1234:0ff0\" $ → $ \"a56f::0124:0001:0000:1234:0ff0\";\n- \"a56f:0000:0000:0000:0001:0000:1234:0ff0\" $ → $ \"a56f:0000::0000:0001:0000:1234:0ff0\";\n- \"a56f:00d3:0000:0124:0001:0000:0000:0000\" $ → $ \"a56f:00d3:0000:0124:0001::0000\";\n- \"0000:0000:0000:0000:0000:0000:0000:0000\" $ → $ \"::\".\n\nIt is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters \"::\" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.\n\nThe format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.\n\nYou've got several short records of IPv6 addresses. Restore their full record.",
    "tutorial": "Firstly you should split string into substrings using \":\" as separator. All empty substrings will go in the row; you should leave only one of them. Then you should calculate number of nonempty substrings and determine number of zero-blocks which will replace empty substring. After replacing you should increase every substring to length 4 inserting leading zeros. After all you should output the answer.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "250",
    "index": "C",
    "title": "Movie Critics",
    "statement": "A film festival is coming up in the city N. The festival will last for exactly $n$ days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to $k$.\n\nOn the $i$-th day the festival will show a movie of genre $a_{i}$. We know that a movie of each of $k$ genres occurs in the festival programme at least once. In other words, each integer from 1 to $k$ occurs in the sequence $a_{1}, a_{2}, ..., a_{n}$ at least once.\n\nValentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.\n\nAs any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.\n\nValentine can't watch all $n$ movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the $k$ genres and will skip all the movies of this genre. He is sure to visit other movies.\n\nValentine wants to choose such genre $x$ ($1 ≤ x ≤ k$), that the total number of after-movie stresses (after all movies of genre $x$ are excluded) were minimum.",
    "tutorial": "Consider some maximal by inclusion segment of movies of some genre $x$ (this number from 1 to $k$). Now let's see how changes number of stresses after removing this segment. If the segment adjoins to the end of all sequence $a$, improvement will be +1. Segment cannot adjoin to both ends of sequence because $k > 1$. For some seqment $[i, j]$ inside of sequence consider values $a_{i - 1}$ and $a_{j + 1}$. If they are equal, after deleting segment improvement will be +2; otherwise it will be +1. Now you should iterate over all maximal be inclusion segments and find improvement for every of them. After that you should group all segments by genre and calculate sum of improvements inside every group. Answer will be number of genre of group that has maximal total improvement (if there are many of them, you should chose minimal number of genre). You can implement this solution in in $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "250",
    "index": "D",
    "title": "Building Bridge",
    "statement": "Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages.\n\nThe river banks can be assumed to be vertical straight lines $x = a$ and $x = b$ ($0 < a < b$).\n\nThe west village lies in a steppe at point $O = (0, 0)$. There are $n$ pathways leading from the village to the river, they end at points $A_{i} = (a, y_{i})$. The villagers there are plain and simple, so their pathways are straight segments as well.\n\nThe east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are $m$ twisted paths leading from this village to the river and ending at points $B_{i} = (b, y'_{i})$. The lengths of all these paths are known, the length of the path that leads from the eastern village to point $B_{i}$, equals $l_{i}$.\n\nThe villagers want to choose exactly one point on the left bank of river $A_{i}$, exactly one point on the right bank $B_{j}$ and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of $|OA_{i}| + |A_{i}B_{j}| + l_{j}$, where $|XY|$ is the Euclidean distance between points $X$ and $Y$) were minimum. The Euclidean distance between points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ equals $\\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}}$.\n\nHelp them and find the required pair of points.",
    "tutorial": "For every point of the east river bank you should find optimal point of the west bank. After that you should chose optimal pair over all considered east points. Well, let's fix $j$-th east point ($1  \\le  j  \\le  m$). Now consider how changes total distance depending on chosing the west point. The best point is intersection of lines $OB_{j}$ and $x = a$: $Z=(a,\\frac{a}{b}y_{j}^{\\prime})$, but this point can be not present among all west points. You can see that if you will move from point $Z$ up or down, total distance will increase. So only nearest to $Z$ points may be considered. You can find that points using binary search. Also you can observe that after every increasing of $j$ point $Z$ will move in same direction; so you can support nearest points to $Z$ usins some pointer. The third way is using such fact that during moving point over the west bank total distance initially will decrease and then increase; so you can use ternary search here. Considered solutions work in $O(m + n)$ and $O(m\\log n)$.",
    "tags": [
      "geometry",
      "ternary search",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "250",
    "index": "E",
    "title": "Mad Joe",
    "statement": "Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.\n\nJoe's house has $n$ floors, each floor is a segment of $m$ cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right.\n\nNow Joe is on the $n$-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right.\n\nJoe moves by a particular algorithm. Every second he makes one of the following actions:\n\n- If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved.\n- Otherwise consider the next cell in the current direction of the gaze.\n\n- If the cell is empty, then Joe moves into it, the gaze direction is preserved.\n- If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite.\n- If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits).\n\nJoe calms down as soon as he reaches \\textbf{any} cell of the first floor.\n\nThe figure below shows an example Joe's movements around the house.\n\nDetermine how many seconds Joe will need to calm down.",
    "tutorial": "You should emulate the process. You can catch case of infinity walk if you will observe hits with concrete wall from the left and the right side. If for some floor both types of hits happened, you should output \"Never\". Stupid emulation is very slow. It has complexity $O(nm^{2})$ and answer can be about $10^{10}$. You should speed up stupid emulation using following way. For every floor you should store segment of visited cells (two integers - L and R bounds). We know that under every cell of this segment all cells are non-empty. Therefore after every changing of move direction you can go through all the segment in $O(1)$. After every one or two \"teleportations\" through segment you either expand bounds of the segnent or change some brick-cell into empty-cell or fall down. But actions of every type you can do no more than $nm$ times, so this optimization improves complexety to $O(nm)$.",
    "tags": [
      "brute force"
    ],
    "rating": 2000
  },
  {
    "contest_id": "251",
    "index": "A",
    "title": "Points on Line",
    "statement": "Little Petya likes points a lot. Recently his mom has presented him $n$ points lying on the line $OX$. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed $d$.\n\nNote that the order of the points inside the group of three chosen points doesn't matter.",
    "tutorial": "Let's select the rightmost point of our triplet. In order to do this we can iterate over all points in ascending order of their X-coordinate. At the same time we'll maintain a pointer to the leftmost point which lays on the distance not greater than $d$ from the current rightmost point. We can easily find out the number of points in the segment between two pointers, excluding the rightmost point. Let's call this number $k$. Then there exist exactly $k * (k - 1) / 2$ triplets of points with the fixed rightmost point. The only thing left is to sum up these values for all rightmost points.",
    "tags": [
      "binary search",
      "combinatorics",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "251",
    "index": "B",
    "title": "Playing with Permutations",
    "statement": "Little Petya likes permutations a lot. Recently his mom has presented him permutation $q_{1}, q_{2}, ..., q_{n}$ of length $n$.\n\nA permutation $a$ of length $n$ is a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ $(1 ≤ a_{i} ≤ n)$, all integers there are distinct.\n\nThere is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length $n$. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules:\n\n- Before the beginning of the game Petya writes permutation $1, 2, ..., n$ on the blackboard. After that Petya makes exactly $k$ moves, which are described below.\n- During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2.\n\n- Let's assume that the board contains permutation $p_{1}, p_{2}, ..., p_{n}$ at the given moment. Then Petya removes the written permutation $p$ from the board and writes another one instead: $p_{q1}, p_{q2}, ..., p_{qn}$. In other words, Petya applies permutation $q$ (which he has got from his mother) to permutation $p$.\n- All actions are similar to point 1, except that Petya writes permutation $t$ on the board, such that: $t_{qi} = p_{i}$ for all $i$ from 1 to $n$. In other words, Petya applies a permutation that is inverse to $q$ to permutation $p$.\n\nWe know that after the $k$-th move the board contained Masha's permutation $s_{1}, s_{2}, ..., s_{n}$. Besides, we know that throughout the game process Masha's permutation \\textbf{never occurred on the board} before the $k$-th move. Note that the game has exactly $k$ moves, that is, throughout the game the coin was tossed exactly $k$ times.\n\nYour task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding.",
    "tutorial": "First, we need to theck whether permutation $s$ is the identity permutation. If it is, then the answer is \"NO\". Now we'll describe an algorithm which works in all cases except for one. We'll tell about this case later. Let's apply our permutation $q$ until either the current permutation becomes equal to $s$ or we make exactly $k$ steps. If the current permutation is equal to $s$ and we've made $t$ steps before this happened, then we need to look at the parity of $k - t$. If this number is even, then we can select any two consequent permutations in the sequence and apply $(k - t) / 2$ times the following two permutations in this order: $q$ and $inv(q)$, where $inv(q)$ is the inversed permutation $q$. Actually, we don't need to build the sequence itself, it's enough to check only the parity of $k - t$. So, if it is even, then the answer is \"YES\". Analogically, we can replace $q$ with $inv(q)$ and repeat described process again. If we still didn't print \"YES\", then the answer is \"NO\". The algorithm we've just described works for all cases except for one: when the permutation $q$ is equal to $inv(q)$ and at the same time $s$ is reachable within one step. In this case the answer is \"YES\" iff $k = 1$. The complexity of described solution is $O(N^{2})$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "251",
    "index": "C",
    "title": "Number Transformation",
    "statement": "Little Petya likes positive integers a lot. Recently his mom has presented him a positive integer $a$. There's only one thing Petya likes more than numbers: playing with little Masha. It turned out that Masha already has a positive integer $b$. Petya decided to turn his number $a$ into the number $b$ consecutively performing the operations of the following two types:\n\n- Subtract 1 from his number.\n- Choose any integer $x$ from $2$ to $k$, inclusive. Then subtract number $(a mod x)$ from his number $a$. Operation $a mod x$ means taking the remainder from division of number $a$ by number $x$.\n\nPetya performs one operation per second. Each time he chooses an operation to perform during the current move, no matter what kind of operations he has performed by that moment. In particular, this implies that he can perform the same operation any number of times in a row.\n\nNow he wonders in what minimum number of seconds he could transform his number $a$ into number $b$. Please note that numbers $x$ in the operations of the second type are selected anew each time, independently of each other.",
    "tutorial": "Let $L$ be the least common multiple of all numbers from 2 to $k$, inclusive. Note that if $a$ is divisible by $L$, then we can't decrease it with applying an operation of the second type. It means that any optimal sequence of transformations will contain all numbers divisible by $L$ which are located between $b$ and $a$. Let's split our interval from $b$ to $a$ into several intervals between the numbers divisible by $L$. It may happen that the first and the last intervals will have length less than $L$. Now we can solve the problem for the first interval, the last interval and for any interval between them. After that we need to multiply the last result by the total number of intervals excluding the first and the last ones. The only thing left is to add up obtained 3 values. In order to solve the problem for one interval one can simply use bfs. Be careful in the cases when we have only 1 or 2 intervals. The complexity of described solution is $O(L)$.",
    "tags": [
      "dp",
      "greedy",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "251",
    "index": "D",
    "title": "Two Sets",
    "statement": "Little Petya likes numbers a lot. Recently his mother has presented him a collection of $n$ non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill:\n\n- Let's introduce $x_{1}$ to denote the $xor$ of all numbers Petya has got left; and let's introduce $x_{2}$ to denote the $xor$ of all numbers he gave to Masha. Value $(x_{1} + x_{2})$ must be as large as possible.\n- If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value $x_{1}$.\n\nThe $xor$ operation is a bitwise excluding \"OR\", that is denoted as \"xor\" in the Pascal language and \"^\" in C/C++/Java.\n\nHelp Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the $xor$ of an empty set of numbers equals 0.",
    "tutorial": "Let $X$ be the $xor$ of all numbers in the input. Also let $X1$ be the $xor$ of all numbers in the first collection and $X2$ be the $xor$ of all numbers in the second collection. Note, if the $i$-th bit in $X$ is equal to 1 then the same bit in numbers $X1$ and $X2$ is either equal 0 and 1 or 1 and 0, respectively. Analogically, if the $i$-th bit in $X$ is equal to 0 then this bit in numbers $X1$ and $X2$ is either equal 0 and 0 or 1 and 1, respectively. As we can see, if the $i$-th bit in $X$ is equal to 1 then it doesn't affect on the sum $X1 + X2$ in any way. For now, let's forget about the second condition in the statement which asks us to minimize $X1$ in case of tie. In order to find the optimal value of $X1 + X2$ we need to make one more observation. Let's look at the most significant bit of number $X$ which is equal to 0. If there exist such partitions of the initial collection in which this bit is equal to 1 in $X1$ then the optimal partition should be one of them. To prove this one should remember that the respective bit in number $X2$ is also equal to 1. Let this bit correspond to $2^{L}$. If the bit we are looking at is equal to 1 in both $X1$ and $X2$ then the smallest possible value of $X1 + X2$ is $2^{L + 1}$. On the other hand, if both $X1$ and $X2$ have zero in this bit, then the maximal possible value of $X1 + X2$ is $2^{L + 1} - 2$ which is strictly smaller than $2^{L + 1}$. We'll be solving the initial problem with a greedy algorithm. Let's iterate over all bits which are equal to 0 in number $X$ from highest to lowest. We'll try to put 1 to the number $X1$ in this position and then check if there exists at least one partition which satisfies the current condition together with all conditions we've already set up. If such partition exists, then we can leave our newly added condition and move to lower bits. If there is no such condition, then we need to move to lower bits without adding any new conditions. At the end we'll find the maximal value of $X1 + X2$. So, we have a set of conditions and we want to check if there exist at least one partition which satisfies all of them. For each condition for $i$-th bit we'll create an equation over the field $Z_{2}$ with $n$ variables, where the coefficient at the $j$-th variable is equal to the $i$-th bit of the $j$-th number. If some variable is equal to one then we take the corresponding number into the first set, otherwise -- into the second one. This system of equations can be solved with Gaussian elimination. Note that we don't need to solve the complete system from scratch every time we add a new equation. It's sufficient to recalculate the matrix from the previous state, which can be done in $O(NK)$. Here $K$ is the number of equations in the system. Now we need to minimize $X1$ while keeping the value of $X1 + X2$ unchanged. It can be done in the similar way as finding the optimal value of $X1 + X2$. We'll iterate over all bits which are equal to 1 in number $X$ starting from the highest one. For the current bit we'll try to put 0 in the corresponding position of $X1$. If after adding this condition our system of equations becomes incompatible, then we need to put 1 in this position of $X1$. The complexity of this algorithm is $O(NL^{2})$, where $L$ -- is the length of binary notation of the largest number. For further optimization one can use $bitset$ in Gaussian elimination, although it wasn't necessary for getting AC during the contest.",
    "tags": [
      "bitmasks",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "251",
    "index": "E",
    "title": "Tree and Table",
    "statement": "Little Petya likes trees a lot. Recently his mother has presented him a tree with $2n$ nodes. Petya immediately decided to place this tree on a rectangular table consisting of 2 rows and $n$ columns so as to fulfill the following conditions:\n\n- Each cell of the table corresponds to exactly one tree node and vice versa, each tree node corresponds to exactly one table cell.\n- If two tree nodes are connected by an edge, then the corresponding cells have a common side.\n\nNow Petya wonders how many ways are there to place his tree on the table. He calls two placements distinct if there is a tree node which corresponds to distinct table cells in these two placements. Since large numbers can scare Petya, print the answer modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "If $N = 1$, then the answer is 2. If there is a node with degree greater than 3 in the tree, then the answer is 0. That's because every cell of the table has at most 3 neighbors. If there is no vertex of degree 3 in the tree, then the answer is $2n^{2} - 2n + 4$. This formula can be derieved in natural way during the solution of other parts of the problem. Also, one could write a simple DP to calculate the answer in this case. Anyway, let's prove this formula. At first, let's solve slightly different problem, which will be also used in the solution of main case of the initial problem. We want to find the number of ways to place a tree in which all nodes have degree smaller than 3 on the table so that one node of degree 1 is attached to the upper-left corner of the table (let it be node number 1). It can be shown that if the table has size 2xK, then the number of placements of the tree is equal to $K$. The last formula can be proven by mathematical induction. If $K = 1$ then the above statement is obviously true. Suppose $K > 1$ and let's assume that the table is oriented horizontally so that we have 2 rows and $K$ columns. If we put a vertex adjacent to the first one to the right from upper-left corner then we have only 1 way to complete the placement of the tree. If we put this vertex to the bottom-left corner, than the next vertex should be put to (2, 2) and the problem is reduced to the same one with $K$ smaller by one. We have a recurrent relation $f(K) = f(K - 1) + 1$ and we know that $f(1) = 1$. This means that $f(K) = K$. Let's come back to the initial problem of counting the nymber of ways to put a tree without vertices of degree 3 on the table 2xN. Without loss of generality let's assume that the first vertex has degree 1. We'll consider only placements in which the first vertex is laying in the first row and at the end we'll multiply our answer by 2. If the first vertex is laying in the first or the last column then then there are $N$ ways to complete the tree (see the previous paragraph). If the first vertex is laying in the $i$-th column than there are $i - 1$ ways of placing our tree in which a vertex adjacent to the first one (let it be vertex 2) is laying to the left of it. Also there are $N - i$ ways in which the second vertex is laying to the right of vertex 1. Adding up these values for all columns and multiplying the answer by 2 we get the final formula: $2n^{2} - 2n + 4$. Now we have only one case left in which there exists a vertex of degree 3 in our tree. Let's declare this vertex to be a root. If there are several vertices of degree 3, any of them can be chosen to be a root. We'll assume that the root is laying in the first row and at the end we'll multiply our answer by 2. Obviously, the root should be put to a cell with 3 neighbors. Each descendant of the root should be put either to the left, to the right or to the bottom from the cell which contains the root. Let's fix this ordering (to do this we need to iterate over 6 permutations). Also if the \"bottom\" son of the root has degree greater than 1, then we'll also fix the ordering of its adjacent vertices (there are 2 ways to do this). Now the column which contains the root is fully occupied. The last statement means that regardless of the way we place the rest of vertices, the ones to the right from the root will stay there. The same for all vertices which lay to the left from the root. Moreover, we have the fixed number of vertices to the left from the root, which means that there's at most one way to place the root on our table. Note that if the number of vertices to the left from the root is odd, then we won't be able to complete the placement. In order to find the number of vertices to the left from the root we need to sum up sizes of subtrees of its left descendant and of the left descendant of its bottom son. So, we have two separate subproblems (for vertices laying to the left from the root and to the right from the root) and for each of them we need to calculate the number of trees to place the rest of our tree in the table. There are only two possible situations: 1) We need to place a subtree with its root in vertex $v$ on the rectangular table in such way that vertex $v$ is laying in the corner (let it be upper-left corner). 2) We need to place subtrees with roots in $v1$ and $v2$ on the rectangular table in such way that vertex $v1$ is laying in the upper-left corner and vertex $v2$ is laying in bottom-left corner. Obviously, each of these two problems has non-zero answer only if total size of subtrees is even. Let's show how to reduce a problem of the second type to a problem of the first type. So, if either $v1$ or $v2$ has two descendants, then the answer is 0. If both of them have one descendant, then we can solve the same problem for their children which'll have the same answer. If both $v1$ and $v2$ have no children, then the answer is 1. At last, if one of these two vertices has 1 descendant and the other vertice doesn't have any descendants, we have a problem of the first type for this only child of vertices $v1$ and $v2$. The only thing left is to solve a problem of the first type. Let $f(v)$ be the number of ways to place a subtree having vertex $v$ as its root on the rectangular table. The size of this table is determined uniquely by the size of subtree. Let's consider two cases: a) Vertex $v$ has degree 2. b) Vertex $v$ has degree 3. In the case when vertex $v$ has degree 2 and there are no vertices of degree 3 in its subtree, then $f(v) = s(x) / 2$, where $s(v)$ is the size of subtree with its root in vertex $v$. We've already proven this formula above. Now let's suppose that there's at least one vertex of size 3 in the subtree with root $v$. If there are several vertices with degree 3, we'll chose the one that is closer to vertex $v$. Let it be vertex $w$. We have 2 possible cases for it: a.1) Path from vertex $v$ to vertex $w$ will go in such way that the vertex which lays before vertex $w$ in this path is located to the left from vertex $w$ on the table. a.2) Path from vertex $v$ to vertex $w$ will go in such way that the vertex which lays before vertex $w$ in this path is located to the top from vertex $w$ on the table. Its easy to show that there's no third option. In each of two cases a.1) and a.2) we'll fix directions of descendants of number $w$ (one direction is taken by the parent of vertex $w$, so there are exactly 2 possible directions). In case if descendant of degree greater than 1 is located in the same column with $w$, we need to fix directions of its descendants, too. After this we have problem of type 1) or 2) to the right of vertex $w$. To the left from $w$ we have a tree which either can't be put on the table or can be put in exactly 1 way. In order to check this we need to look on the length of path from $v$ to $w$ and the size of subtree of grandson of $w$, which is located to the right from $w$ (of course, if it exists). Now we need to sup up answers for all possible variants. So we know how to solve problem of type a), when vertex $v$ has degree w. The only thing left is to solve problem b), when $v$ has degree 3. To do this we need to fix directions of its descendants and after that we'll have either a problem of type 1) or a problem of type 2), which were formulated above. The complexity of solution is $O(N)$.",
    "tags": [
      "dfs and similar",
      "dp",
      "implementation",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "252",
    "index": "A",
    "title": "Little Xor",
    "statement": "Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of $n$ elements. Petya immediately decided to find there a segment of consecutive elements, such that the $xor$ of all numbers from this segment was maximal possible. Help him with that.\n\nThe $xor$ operation is the bitwise exclusive \"OR\", that is denoted as \"xor\" in Pascal and \"^\" in C/C++/Java.",
    "tutorial": "Let's iterate over all segments in our array. For each of them we'll find the $xor$ of all its elements. Then we need to output the maximal $xor$ we've seen.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "252",
    "index": "B",
    "title": "Unsorting Array",
    "statement": "Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of $n$ elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya \\textbf{must} swap some two integers even if the original array meets all requirements.\n\nArray $a$ (the array elements are indexed from 1) consisting of $n$ elements is called sorted if it meets at least one of the following two conditions:\n\n- $a_{1} ≤ a_{2} ≤ ... ≤ a_{n}$;\n- $a_{1} ≥ a_{2} ≥ ... ≥ a_{n}$.\n\nHelp Petya find the two required positions to swap or else say that they do not exist.",
    "tutorial": "If all elements in the array are equal then there's no pair of numbers we are looking for. Now we can assume that there exist at least 2 different numbers in the array. Let's iterate over all pairs of different numbers in the array and for each such pair we'll check if it can be the answer. If some pair indeed can be the answer, we'll output it and terminate the program. Otherwise, there is no pair of numbers we are looking for, so we need to output -1. It may seem that the complexity of described algorithm is $O(N^{3})$. Actually it's not true and the real complexity is $O(N)$. One may notice that in every array of length greater than 3 there are at least 3 pairs of different numbers (remember we assumed that there exist at least one pair of different numbers in the array). Note that these 3 pairs lead to 3 different resulting arrays. On the other hand, there are only 2 possible sorted arrays. According to the pigeonhole principle one of these 3 resulting arrays is unsorted.",
    "tags": [
      "brute force",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "253",
    "index": "A",
    "title": "Boys and Girls",
    "statement": "There are $n$ boys and $m$ girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to $n + m$. Then the number of integers $i$ ($1 ≤ i < n + m$) such that positions with indexes $i$ and $i + 1$ contain children of different genders (position $i$ has a girl and position $i + 1$ has a boy or vice versa) must be as large as possible.\n\nHelp the children and tell them how to form the line.",
    "tutorial": "Lets assume that we have more boys than girls (the other case is solved similarly). Then we can construct one of the optimal solutions in the following way: we add pairs consisting of a boy and a girl (BG, in that order) to the end of the line until we don't have girls any more. Then add remaining boys to the end of the line. For instance, with 7 boys and 4 girls we will come to the solution BGBGBGBGBBB.",
    "tags": [
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "253",
    "index": "B",
    "title": "Physics Practical",
    "statement": "One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as $n$ measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result $x$, and the largest result $y$, then the inequality $y ≤ 2·x$ must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.\n\nHelp Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.",
    "tutorial": "For each $x$ from 1 to 5000 calculate $count(x)$ - the number of measurements equal to $x$. The iterate over all possible minimal values $m$ (from 1 to 5000). For a fixed $m$ we can easily figure out which numbers we have to erase: we should erase every number $k$ that $k < m$ or $k > 2 \\cdot m$. To find out the number of such values in the given sequence, we should sum up values $count(k)$ for all such $k$.",
    "tags": [
      "binary search",
      "dp",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "253",
    "index": "C",
    "title": "Text Editor",
    "statement": "Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.\n\nAs Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?\n\nLet's describe his question more formally: to type a text, Vasya is using the text editor. He has already written $n$ lines, the $i$-th line contains $a_{i}$ characters (including spaces). If some line contains $k$ characters, then this line overall contains $(k + 1)$ positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers $(r, c)$, where $r$ is the number of the line and $c$ is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).\n\nVasya doesn't use the mouse to move the cursor. He uses keys \"Up\", \"Down\", \"Right\" and \"Left\". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position $(r, c)$, then Vasya pushed key:\n\n- \"Up\": if the cursor was located in the first line ($r = 1$), then it does not move. Otherwise, it moves to the previous line (with number $r - 1$), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position $c$ there, the cursor moves to the last position of the line with number $r - 1$;\n- \"Down\": if the cursor was located in the last line ($r = n$), then it does not move. Otherwise, it moves to the next line (with number $r + 1$), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position $c$ there, the cursor moves to the last position of the line with number $r + 1$;\n- \"Right\": if the cursor can move to the right in this line ($c < a_{r} + 1$), then it moves to the right (to position $c + 1$). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the \"Right\" key;\n- \"Left\": if the cursor can move to the left in this line ($c > 1$), then it moves to the left (to position $c - 1$). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the \"Left\" key.\n\nYou've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position $(r_{1}, c_{1})$ to position $(r_{2}, c_{2})$.",
    "tutorial": "One of the solutions to the problem is breadth-first-search (BFS). Vertices of the graph correspond to all possible pairs ($r, c$), denoting the row and the position of the cursor. Each vertex has at most four arcs leaving it (these arcs correspond to pressing the buttons). So we need to find the shortest path from one vertex to the other. There are at most $10^{7}$ vertices and at most $4 \\cdot 10^{7}$ arcs. This problem can also be solved with some greedy observations.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "253",
    "index": "D",
    "title": "Table with Letters - 2",
    "statement": "Vasya has recently started to learn English. Now he needs to remember how to write English letters. He isn't sure about some of them, so he decided to train a little.\n\nHe found a sheet of squared paper and began writing arbitrary English letters there. In the end Vasya wrote $n$ lines containing $m$ characters each. Thus, he got a rectangular $n × m$ table, each cell of the table contained some English letter. Let's number the table rows from top to bottom with integers from 1 to $n$, and columns — from left to right with integers from 1 to $m$.\n\nAfter that Vasya looked at the resulting rectangular table and wondered, how many subtables are there, that matches both following conditions:\n\n- the subtable contains at most $k$ cells with \"a\" letter;\n- all letters, located in all four corner cells of the subtable, are equal.\n\nFormally, a subtable's definition is as follows. It is defined by four integers $x_{1}, y_{1}, x_{2}, y_{2}$ such that $1 ≤ x_{1} < x_{2} ≤ n$, $1 ≤ y_{1} < y_{2} ≤ m$. Then the subtable contains all such cells $(x, y)$ ($x$ is the row number, $y$ is the column number), for which the following inequality holds $x_{1} ≤ x ≤ x_{2}, y_{1} ≤ y ≤ y_{2}$. The corner cells of the table are cells $(x_{1}, y_{1})$, $(x_{1}, y_{2})$, $(x_{2}, y_{1})$, $(x_{2}, y_{2})$.\n\nVasya is already too tired after he's been writing letters to a piece of paper. That's why he asks you to count the value he is interested in.",
    "tutorial": "Lets iterate over all pairs of rows $i, j$ ($i < j$), that bounds the sub-table from the top and from the bottom. Then for each character $ch$ make a list of such column numbers $k$ that $T[i, k] = T[j, k] = ch$. Consider such list for some fixed character $ch$. All we need to count is the number of pairs $l, r$ ($l < r$) in this list such that the sub-table with corners at $(i, l)$ and $(j, r)$ contains not more than $k$ characters $\"a\"$. This can be done using two standard techniques: two-pointer method and calculating partial sums.",
    "tags": [
      "brute force",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "253",
    "index": "E",
    "title": "Printer",
    "statement": "Let's consider a network printer that functions like that. It starts working at time 0. In each second it can print one page of a text. At some moments of time the printer receives printing tasks. We know that a printer received $n$ tasks. Let's number the tasks by consecutive integers from 1 to $n$. Then the task number $i$ is characterised by three integers: $t_{i}$ is the time when the task came, $s_{i}$ is the task's volume (in pages) and $p_{i}$ is the task's priority. The priorities of all tasks are distinct.\n\nWhen the printer receives a task, the task goes to the queue and remains there until all pages from this task are printed. The printer chooses a page to print each time when it either stops printing some page or when it is free and receives a new task. Among all tasks that are in the queue at this moment, the printer chooses the task with the highest priority and next second prints an unprinted page from this task. You can assume that a task goes to the queue immediately, that's why if a task has just arrived by time $t$, the printer can already choose it for printing.\n\nYou are given full information about all tasks except for one: you don't know this task's priority. However, we know the time when the last page from this task was finished printing. Given this information, find the unknown priority value and determine the moments of time when the printer finished printing each task.",
    "tutorial": "First lets learn how to simulate the process with all priorities known. We will keep the priority queue of tasks. The task enters the queue when the printer receives this task, and leaves the queue when the printer finishes it. Then every change in the queue happens when one of the two possible events occurs: the printer receives some task or finishes printing some task. Between the consecutive events printer just prints pages from the tasks with the highest priority. So, if we maintain a set of events, the simulation can be done in $O(NlogN)$. To solve the problem, make an obvious observation: the higher priority the task has, the sooner the printer finishes it. Then the required missing priority can be found using binary search. Also we can search the missing priority among $O(N)$ values. The overall complexity is $O(Nlog^{2}(N))$. This problem also has $O(NlogN)$ solution, which will be described later.",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "254",
    "index": "A",
    "title": "Cards with Numbers",
    "statement": "Petya has got $2n$ cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from $1$ to $2n$. We'll denote the number that is written on a card with number $i$, as $a_{i}$. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.",
    "tutorial": "For each $x$ from 1 to 5000 store a list $L(x)$ of such indexes $i$ that $a_{i} = x$. Then just check that all lists have even size and output the elements of each list in pairs.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "254",
    "index": "B",
    "title": "Jury Size",
    "statement": "In 2013, the writers of Berland State University should prepare problems for $n$ Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to $n$. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number $i$ should be prepared by $p_{i}$ people for $t_{i}$ days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.\n\nFor example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.\n\nIn order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time.",
    "tutorial": "One of the possible solutions is: for each Olympiad find the period of the preparation. This can be done by iterating the days back from the day of the Olympiad. For each day $d$ of the preparation add $p_{i}$ to the number of distinct jury members that have to work on problems on day $d$. Then the answer is maximum calculated sum over all days. Be careful with the year 2012.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "254",
    "index": "C",
    "title": "Anagram",
    "statement": "String $x$ is an anagram of string $y$, if we can rearrange the letters in string $x$ and get exact string $y$. For example, strings \"DOG\" and \"GOD\" are anagrams, so are strings \"BABA\" and \"AABB\", but strings \"ABBAC\" and \"CAABA\" are not.\n\nYou are given two strings $s$ and $t$ of the same length, consisting of uppercase English letters. You need to get the anagram of string $t$ from string $s$. You are permitted to perform the replacing operation: every operation is replacing some character from the string $s$ by any other character. Get the anagram of string $t$ in the least number of replacing operations. If you can get multiple anagrams of string $t$ in the least number of operations, get the lexicographically minimal one.\n\nThe lexicographic order of strings is the familiar to us \"dictionary\" order. Formally, the string $p$ of length $n$ is lexicographically smaller than string $q$ of the same length, if $p_{1} = q_{1}$, $p_{2} = q_{2}$, ..., $p_{k - 1} = q_{k - 1}$, $p_{k} < q_{k}$ for some $k$ ($1 ≤ k ≤ n$). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.",
    "tutorial": "Lets denote the number of character $x$ in $s$ by $C_{s}(x)$. Similarly $C_{t}(x)$ is defined. Then the minimum number of changes required to get anagram of $t$ from $s$ is equal to $\\textstyle\\sum(C_{s t}(x)-C_{t}(x)|}$. Now we need to obtain lexicographically minimum solution. Lets iterate through the positions in $s$ from the left to the right. For a fixed position, look through all characters from 'a' to 'z' and for each character decide whether the optimal answer can contain this character in that position. If it can, put this character in that position and continue with the next position. To check if the given character is suitable quickly, we maintain the values $C_{s}(x)$ and $C_{t}(x)$ while iterating through positions.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "254",
    "index": "D",
    "title": "Rats",
    "statement": "Rats have bred to hundreds and hundreds in the basement of the store, owned by Vasily Petrovich. Vasily Petrovich may have not noticed their presence, but they got into the habit of sneaking into the warehouse and stealing food from there. Vasily Petrovich cannot put up with it anymore, he has to destroy the rats in the basement. Since mousetraps are outdated and do not help, and rat poison can poison inattentive people as well as rats, he chose a radical way: to blow up two grenades in the basement (he does not have more).\n\nIn this problem, we will present the shop basement as a rectangular table of $n × m$ cells. Some of the cells are occupied by walls, and the rest of them are empty. Vasily has been watching the rats and he found out that at a certain time they go to sleep, and all the time they sleep in the same places. He wants to blow up a grenade when this convenient time comes. On the plan of his basement, he marked cells with sleeping rats in them. Naturally, these cells are not occupied by walls.\n\nGrenades can only blow up in a cell that is not occupied by a wall. The blast wave from a grenade distributes as follows. We assume that the grenade blast occurs at time 0. During this initial time only the cell where the grenade blew up gets 'clear'. If at time $t$ some cell is clear, then at time $t + 1$ those side-neighbouring cells which are not occupied by the walls get clear too (some of them could have been cleared before). The blast wave distributes for exactly $d$ seconds, then it dies immediately.\n\n\\begin{center}\n{\\scriptsize An example of a distributing blast wave: Picture 1 shows the situation before the blast, and the following pictures show \"clear\" cells by time 0,1,2,3 and 4. Thus, the blast wave on the picture distributes for $d = 4$ seconds.}\n\\end{center}\n\nVasily Petrovich wonders, whether he can choose two cells to blast the grenades so as to clear all cells with sleeping rats. Write the program that finds it out.",
    "tutorial": "Choose arbitrary rat (for say, the leftmost of the upmost). It's cell should be cleared. Make a BFS that never goes further than $d$ from this cell (we will call such a BFS by d-BFS). It will visit approximately $2d^{2}$ cells in the worst case. So, we have to blow the first grenade in one of the visited cells. Lets check every visited cell as a candidate. Make a d-BFS from the candidate cell. Some cells with the rats will not be visited. That means that they should be cleared by the second grenade. Choose arbitrary cell with a rat that was not cleared by the first grenade. Make a d-BFS from it. All cells visited by this BFS are candidates to blow the second grenade. Lets check every such cell. Checking a cell again means making a d-BFS from it. If this BFS visits all cells that were not cleared by the first grenade, that we have found a solution. As every d-BFS visits at most $2d^{2}$, the overall number of steps is approximately $8d^{6}$.",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "254",
    "index": "E",
    "title": "Dormitory",
    "statement": "Student Vasya came to study in Berland State University from the country, so he is living in a dormitory. A semester has $n$ days, and in each of those days his parents send him some food. In the morning of the $i$-th day he receives $a_{i}$ kilograms of food that can be eaten on that day and on the next one (then the food goes bad and becomes unfit for consumption).\n\nEvery day Vasya eats $v$ kilograms of food. It is known that Vasya's parents do not allow him to starve, so there always is enough food for Vasya. Vasya has $m$ friends who sometimes live with him. Let's index the friends from 1 to $m$. Friend number $j$ lives with Vasya from day $l_{j}$ to day $r_{j}$, inclusive. Also, the $j$-th friend requires $f_{j}$ kilograms of food per day. Usually Vasya's friends eat in the canteen, but sometimes generous Vasya feeds some of them. Every day Vasya can feed some friends who live with him this day (or may feed nobody).\n\nEvery time Vasya feeds his friend, he gives him as much food as the friend needs for the day, and Vasya's popularity rating at the University increases by one. Vasya cannot feed the same friend multiple times in one day. In addition, he knows that eating habits must be regular, so he always eats $v$ kilograms of food per day.\n\nVasya wants so choose whom he will feed each day of the semester to make his rating as high as possible. Originally Vasya's rating is 0 because he is a freshman.",
    "tutorial": "The problem can be solved by dynamic programming: denote as $D(n, r)$ the maximum rating that we can achieve in the first $n$ days with the condition that we have $r$ kilos of food remaining from the day $n - 1$. It is obvious that if we decide to feed $k$ friends on some day, the better way is to feed $k$ friends with the lowest $f_{j}$ (of course we consider only friends that live with Vasya on that day). So we need to sort all available students in the order of increasing $f_{j}$ and try to feed 0, 1, 2, \\ldots first students in this order. We have $400^{2}$ states and $400$ transitions from each state.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "255",
    "index": "A",
    "title": "Greg's Workout",
    "statement": "Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was $n$ integers $a_{1}, a_{2}, ..., a_{n}$. These numbers mean that Greg needs to do exactly $n$ exercises today. Besides, Greg should repeat the $i$-th in order exercise $a_{i}$ times.\n\nGreg now only does three types of exercises: \"chest\" exercises, \"biceps\" exercises and \"back\" exercises. Besides, his training is cyclic, that is, the first exercise he does is a \"chest\" one, the second one is \"biceps\", the third one is \"back\", the fourth one is \"chest\", the fifth one is \"biceps\", and so on to the $n$-th exercise.\n\nNow Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.",
    "tutorial": "It is not hard problem. We must calculate sums of numbers for each group and print group with maximum count.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "255",
    "index": "B",
    "title": "Code Parsing",
    "statement": "Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string $s$, consisting of characters \"x\" and \"y\", and uses two following operations at runtime:\n\n- Find two consecutive characters in the string, such that the first of them equals \"y\", and the second one equals \"x\" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.\n- Find in the string two consecutive characters, such that the first of them equals \"x\" and the second one equals \"y\". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.\n\nThe input for the new algorithm is string $s$, and the algorithm works as follows:\n\n- If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string.\n- If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm.\n\nNow Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string $s$.",
    "tutorial": "Not hard to see that after few operations of first type string will become: x..xy..y. After fer operations of second type, there will be only letters of one type, count of this letters will be: |count(x) - count(y)|",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "255",
    "index": "D",
    "title": "Mr. Bender and Square",
    "statement": "Mr. Bender has a digital table of size $n × n$, each cell can be switched on or off. He wants the field to have at least $c$ switched on squares. When this condition is fulfilled, Mr Bender will be happy.\n\nWe'll consider the table rows numbered from top to bottom from 1 to $n$, and the columns — numbered from left to right from 1 to $n$. Initially there is exactly one switched on cell with coordinates $(x, y)$ ($x$ is the row number, $y$ is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on.\n\nFor a cell with coordinates $(x, y)$ the side-adjacent cells are cells with coordinates $(x - 1, y)$, $(x + 1, y)$, $(x, y - 1)$, $(x, y + 1)$.\n\nIn how many seconds will Mr. Bender get happy?",
    "tutorial": "Solution - binary search for answer. Next we have to calculate the area of a truncated square set at 45 degrees. This can be done as follows: Calculate its total area. Subtract area that cuts off the top line. Similarly, for the lower, left and right line. Add parts that are cutted by corners. You can write a function that finds the length of the truncation desired area, for that would not write a lot of code.",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "255",
    "index": "E",
    "title": "Furlo and Rublo and Game",
    "statement": "Furlo and Rublo play a game. The table has $n$ piles of coins lying on it, the $i$-th pile has $a_{i}$ coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to:\n\n- choose some pile, let's denote the current number of coins in it as $x$;\n- choose some integer $y$ $(0 ≤ y < x; x^{1 / 4} ≤ y ≤ x^{1 / 2})$ and decrease the number of coins in this pile to $y$. In other words, after the described move the pile will have $y$ coins left.\n\nThe player who can't make a move, loses.\n\nYour task is to find out, who wins in the given game if both Furlo and Rublo play optimally well.",
    "tutorial": "Note that after the first move any pile turns into a pile no larger than 1000000. We assume Grundy function for numbers less than 1 million. Grundy function is very small, you can start on the partial sums for each type of function that would quickly tell what function is in the interval, and which are not present. Knowing the answer is not difficult to find small response for all piles.",
    "tags": [
      "games",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "256",
    "index": "D",
    "title": "Liars and Serge",
    "statement": "There are $n$ people, sitting in a line at the table. For each person we know that he always tells either the truth or lies.\n\nLittle Serge asked them: how many of you always tell the truth? Each of the people at the table knows everything (who is an honest person and who is a liar) about all the people at the table. The honest people are going to say the correct answer, the liars are going to say any integer from 1 to $n$, which is not the correct answer. Every liar chooses his answer, regardless of the other liars, so two distinct liars may give distinct answer.\n\nSerge does not know any information about the people besides their answers to his question. He took a piece of paper and wrote $n$ integers $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the answer of the $i$-th person in the row. Given this sequence, Serge determined that exactly $k$ people sitting at the table \\textbf{apparently lie}.\n\nSerge wonders, how many variants of people's answers (sequences of answers $a$ of length $n$) there are where one can say that exactly $k$ people sitting at the table apparently lie. As there can be rather many described variants of answers, count the remainder of dividing the number of the variants by $777777777$.",
    "tutorial": "If person say number x, and at all x was said by x persons, then we cannot tell anything about fixed person. Now we understand which sequence are good for us. We will calculate their count wuth dynamic programming dp[n][m][k], n - which persons answers we set to the sequence right now, m - how mant persons gived theis answers, k - how many persons from them are liers. Transfer: dp[n][m][k]*cnk[N-m][n] -> dp[n+1][m+n][k] dp[n][m][k]*cnk[N-m][p] -> dp[n+1][m+p][k+p] p = 1 .. N, p != n. We assume, that N - total number of the persons. This solution get TLE, becouse complexity if O(N^4). We need to use precalc. It will not be so big, as N is power of 2.",
    "tags": [
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "256",
    "index": "E",
    "title": "Lucky Arrays",
    "statement": "Little Maxim loves interesting problems. He decided to share one such problem with you.\n\nInitially there is an array $a$, consisting of $n$ zeroes. The elements of the array are indexed, starting from 1. Then follow queries to change array $a$. Each query is characterized by two integers $v_{i}, t_{i}$. In the answer to the query we should make the $v_{i}$-th array element equal $t_{i}$ $(a_{vi} = t_{i}; 1 ≤ v_{i} ≤ n)$.\n\nMaxim thinks that some pairs of integers $(x, y)$ are good and some are not. Maxim thinks that array $a$, consisting of $n$ integers, is lucky, if for all integer $i$, $(1 ≤ i ≤ n - 1)$ the pair of integers $(a_{i}, a_{i + 1})$ — is good. Note that the order of numbers in the pairs is important, that is, specifically, $(1, 2) ≠ (2, 1)$.\n\nAfter each query to change array $a$ Maxim wants to know, how many ways there are to replace all zeroes in array $a$ with integers from one to three so as to make the resulting array (without zeroes) lucky. Of course, distinct zeroes can be replaced by distinct integers.\n\nMaxim told you the sequence of queries and all pairs of integers he considers lucky. Help Maxim, solve this problem for him.",
    "tutorial": "Solution is - interval tree. We will save dynamic programming f[i,j] in each vertex, this dp means: in how many ways we can change all 0 to some numbers on interval, such that it will be valid and first element will be i and last will be j. With normal implementation its easy to pass system tests.",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "258",
    "index": "A",
    "title": "Little Elephant and Bits",
    "statement": "The Little Elephant has an integer $a$, written in the binary notation. He wants to write this number on a piece of paper.\n\nTo make sure that the number $a$ fits on the piece of paper, the Little Elephant \\textbf{ought} to delete exactly one any digit from number $a$ in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).\n\nThe Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.",
    "tutorial": "It's pretty easy to notice that you need to delete the first (from the left) 0-digit. The only catchy case is 111...111 - here you need to delete any of 1-digits.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "258",
    "index": "B",
    "title": "Little Elephant and Elections",
    "statement": "There have recently been elections in the zoo. Overall there were $7$ main political parties: one of them is the Little Elephant Political Party, $6$ other parties have less catchy names.\n\nPolitical parties find their number in the ballot highly important. Overall there are $m$ possible numbers: $1, 2, ..., m$. Each of these $7$ parties is going to be assigned in some way to exactly one number, at that, two distinct parties cannot receive the same number.\n\nThe Little Elephant Political Party members believe in the lucky digits $4$ and $7$. They want to evaluate their chances in the elections. For that, they need to find out, how many correct assignments are there, such that the number of lucky digits in the Little Elephant Political Party ballot number is strictly larger than the total number of lucky digits in the ballot numbers of 6 other parties.\n\nHelp the Little Elephant Political Party, calculate this number. As the answer can be rather large, print the remainder from dividing it by $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "First of all, lets think about the problem of finding array $c_{i}$ - the number of integers from 1 to $m$ such, that the number of lucky digits is equal to $i$. It's pretty standart dynamic programminc problem, which can be solved with state [position][less][count]. It can be solved directly using DP, but to simplify a bit you can use brute force (recursion) to brute all possible assignments of numbers of lucky digits in for all paries (up to 9 digits). Now you can divide all parties in several indepentent groups, each of which should contain the same number of lucky digits. Consider that the party of Litte Elephant is with number 1. Than assignment for the first position should have more digits than the sum of the rest (because of the statement). Since all groups are indepented (because there is no number that can have different number of lucky digits, obviously) you can find the number of resulting assignments for each group and find the final result by multiplying these all numbers and taking modulo $10^{9} + 7$. Consider that you have group of size $t$, each number of which should contain $l$ lucky digits. That it's pretty easy to understand that the number of assignment is equal to $(c_{l}) * (c_{l} - 1) * (c_{l} - 2) * ... * (c_{l} - t + 1)$.",
    "tags": [
      "brute force",
      "combinatorics",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "258",
    "index": "C",
    "title": "Little Elephant and LCM",
    "statement": "The Little Elephant loves the LCM (least common multiple) operation of a non-empty set of positive integers. The result of the LCM operation of $k$ positive integers $x_{1}, x_{2}, ..., x_{k}$ is the minimum positive integer that is divisible by each of numbers $x_{i}$.\n\nLet's assume that there is a sequence of integers $b_{1}, b_{2}, ..., b_{n}$. Let's denote their LCMs as $lcm(b_{1}, b_{2}, ..., b_{n})$ and the maximum of them as $max(b_{1}, b_{2}, ..., b_{n})$. The Little Elephant considers a sequence $b$ good, if $lcm(b_{1}, b_{2}, ..., b_{n}) = max(b_{1}, b_{2}, ..., b_{n})$.\n\nThe Little Elephant has a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Help him find the number of good sequences of integers $b_{1}, b_{2}, ..., b_{n}$, such that for all $i$ $(1 ≤ i ≤ n)$ the following condition fulfills: $1 ≤ b_{i} ≤ a_{i}$. As the answer can be rather large, print the remainder from dividing it by $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "The complexity of the possible solution is $O(n * sqrt(n) * log(n))$. You can see that statement $lcm(b_{1}, b_{2}, ..., b_{n}) = max(b_{1}, b_{2}, ..., b_{n})$ is equal to statement \"All the numbers $b_{1}, b_{2}, ..., b_{n}$ must divide $max(b_{1}, b_{2}, ..., b_{n})$\". You can iterate that $max(b_{1}, b_{2}, ..., b_{n})$, let it be equal to $m$. Find all divisors of $m$ and sort them - $p_{1}, p_{2}, ..., p_{k}$. For each $i$ between 1 and $k$ you can find (using simple DP) the number of numbers $a_{j}$ that $p_{i}  \\le  a_{j} < p_{i + 1}$ (if $i = k$ than $p_{i + 1} = max(a_{1}, a_{2}, ..., a_{n}) + 1$), denote it as $q_{i}$. Then the reuslt is equal to $1^{q1} * 2^{q2} * 3^{q3} * ... * p^{qp}$, because for each of the $q_{1}$ numbers there is $1$ way to assign, for each of $q_{2}$ numbers there is $2$ ways of assignments, and so on. But you should notice that if doing this problem in such way, you need to garantee that there is some $i$ such $b_{i} = m$. Hance you need from the last multiplier $(p^{qp})$ subtract $(p - 1)^{qp}$ - all the ways that there is no number equal to $m$.",
    "tags": [
      "binary search",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "258",
    "index": "E",
    "title": "Little Elephant and Tree",
    "statement": "The Little Elephant loves trees very much, he especially loves root trees.\n\nHe's got a tree consisting of $n$ nodes (the nodes are numbered from 1 to $n$), with root at node number $1$. Each node of the tree contains some list of numbers which initially is empty.\n\nThe Little Elephant wants to apply $m$ operations. On the $i$-th operation $(1 ≤ i ≤ m)$ he first adds number $i$ to lists of all nodes of a subtree with the root in node number $a_{i}$, and then he adds number $i$ to lists of all nodes of the subtree with root in node $b_{i}$.\n\nAfter applying all operations the Little Elephant wants to count for each node $i$ number $c_{i}$ — the number of integers $j$ $(1 ≤ j ≤ n; j ≠ i)$, such that the lists of the $i$-th and the $j$-th nodes contain at least one common number.\n\nHelp the Little Elephant, count numbers $c_{i}$ for him.",
    "tutorial": "Very useful thing in this problem is ordering all vertices in DFS order (preorped). After that any subtree can be represented as a some sequence of continuous vertices. Consider that we have some fixed vertex $v$. Which vertices should be included in $c_{v}$? Obviously, if in the path from the root to $v$ is some non-empty vertex (i. e. such that has at least one integer in its list) than each vertex from substree $v$ should be included in $c_{i}$, but since we now working with preorder traversal of the tree, we consider that every vertex from some segment $[l_{v}, r_{v}]$ must be included to $c_{i}$. More generally, let for each vertex keep some set of segments ($l_{k};r_{k}$). If on the $i$-th operation we have two vertices $a$ and $b$, we add segment $(l_{b};r_{b})$ to vertex $a$, and $(l_{a};r_{a})$ to vertex $b$. Also for each vertex $i$ ($i = 1..n$) we add segment $(l_{i};r_{i})$, where $(l_{i};r_{i})$ is a segment in our preored traversal for subtree $i$. After that, you can see that, if we unite all segments from all vertices on the path from the root to some vertex $v$, we find the result for $v$, which will be the size of the resulting set. So now we need some data structure that would support three operations: add(l, r), subtract(l, r), count(). The first one should add 1 to all positions from $l$ to $r$, inclusive. The second should subtract 1 from all positions from $l$ to $r$, inclusive. The last should count the number of non-zero element. This all can be done either with segment tree or sqrt-decomposition.",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "259",
    "index": "A",
    "title": "Little Elephant and Chess",
    "statement": "The Little Elephant loves chess very much.\n\nOne day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an $8 × 8$ checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doesn't have any side-adjacent cells with the same color and the upper left cell is white. To play chess, they want to make the board they have a proper chessboard. For that the friends can choose any row of the board and cyclically shift the cells of the chosen row, that is, put the last (rightmost) square on the first place in the row and shift the others one position to the right. You can run the described operation \\textbf{multiple times} (or not run it at all).\n\nFor example, if the first line of the board looks like that \"BBBBBBWW\" (the white cells of the line are marked with character \"W\", the black cells are marked with character \"B\"), then after one cyclic shift it will look like that \"WBBBBBBW\".\n\nHelp the Little Elephant and his friend to find out whether they can use any number of the described operations to turn the board they have into a proper chessboard.",
    "tutorial": "Obviously, the only correct rows are rows WBWBWBWB and BWBWBWBW. Only thing you need to do is to check whether each string is one of these. If yes then print YES, else print NO.",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "259",
    "index": "B",
    "title": "Little Elephant and Magic Square",
    "statement": "Little Elephant loves magic squares very much.\n\nA magic square is a $3 × 3$ table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15.\n\nThe Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed $10^{5}$.\n\nHelp the Little Elephant, restore the original magic square, given the Elephant's notes.",
    "tutorial": "Since each number is less than or equal to $10^{5}$, you can loop all possible $a_{1, 1}$ values, the rest of cells can be calculated from this.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "260",
    "index": "A",
    "title": "Adding Digits",
    "statement": "Vasya has got two number: $a$ and $b$. However, Vasya finds number $a$ too short. So he decided to repeat the operation of lengthening number $a$ $n$ times.\n\nOne operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number $b$. If it is impossible to obtain the number which is divisible by $b$, then the lengthening operation cannot be performed.\n\nYour task is to help Vasya and print the number he can get after applying the lengthening operation to number $a n$ times.",
    "tutorial": "At first try to add to the right one digit from $0$ to $9$. If it is impossible write -1. In other case, the remaining $n-1$ digits can be $0$ because divisibility doesn't change.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "260",
    "index": "B",
    "title": "Ancient Prophesy",
    "statement": "A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters \"-\".\n\nWe'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format \"dd-mm-yyyy\". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy \"0012-10-2012-10-2012\" mentions date 12-10-2012 twice (first time as \"{00\\textbf{12-10-2012}-10-2012}\", second time as \"{0012-10-20\\textbf{12-10-2012}}\").\n\nThe date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.\n\nA date is correct if the year lies in the range from $2013$ to $2015$, the month is from $1$ to $12$, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format \"dd-mm-yyyy\", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date \"1-1-2013\" isn't recorded in the format \"dd-mm-yyyy\", and date \"01-01-2013\" is recorded in it.\n\nNotice, that any year between 2013 and 2015 is not a leap year.",
    "tutorial": "In this problem you have to consider every date from $2013$ to $2015$ year (there is no leap years in this interval), count occurrences of this date and find maximum. In one year there is $365$ days, so the complexity of the solution $(3 \\cdot 365 \\cdot N)$.",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "260",
    "index": "C",
    "title": "Balls and Boxes",
    "statement": "Little Vasya had $n$ boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to $n$ from left to right.\n\nOnce Vasya chose one of the boxes, let's assume that its number is $i$, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers $i + 1$, $i + 2$, $i + 3$ and so on. If Vasya puts a ball into the box number $n$, then the next ball goes to box $1$, the next one goes to box $2$ and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number $i$. If $i = n$, Vasya puts the first ball into the box number $1$, then the next ball goes to box $2$ and so on.\n\nFor example, let's suppose that initially Vasya had four boxes, and the first box had $3$ balls, the second one had $2$, the third one had $5$ and the fourth one had $4$ balls. Then, if $i = 3$, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: $4, 1, 2, 3, 4$. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are $4$ balls, $3$ in the second one, $1$ in the third one and $6$ in the fourth one.\n\nAt this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number $x$ — the number of the box, where he put the last of the taken out balls.\n\nHe asks you to help to find the initial arrangement of the balls in the boxes.",
    "tutorial": "Firstly describe simple solution. We will get by one ball from boxes (we begin from box $x$) from right to left (action back). At some moment there will be $0$ balls in current box. This box is the first box in our initial problem (from which we took all balls and begun to put). In this box we put all balls, which we get from all boxes. But we can't solve the problem in such a way, because it is too long. Note, that before we meet the situation when in some box will be $0$ balls, we will go through every element of array several times and subtract $1$. So we can make our solution faster. We can subtract from every element of array $minv - 1$, where $minv$ - minimum in array. After that you should do $O(N)$ operations, that were mentioned above.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "260",
    "index": "D",
    "title": "Black and White Tree",
    "statement": "The board has got a painted tree graph, consisting of $n$ nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles.\n\nEach node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer.\n\nA bad boy Vasya came up to the board and wrote number $s_{v}$ near each node $v$ — the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board.\n\nYour task is to restore the original tree by the node colors and numbers $s_{v}$.",
    "tutorial": "The problem can be solved constructively maintaining the following invariant (rule) - the sum of the white vertices equals to the sum of the black vertices. The tree is a bipartite graph, so we build bipartite graph with no cycles, which will satisfy the conditions of the problem. Parts of graph will be black and white vertices. On each step we will choose vertex $v$ with minimum sum from white and black vertices. Then find any vertex of opposite color $u$ and add edge $(u, v)$ with weight $s[v]$, and subtract from sum of $u$ sum of $v$, that is $s[u] = s[u]-s[v]$. After each step one vertex is deleted. That's why there will be no cycles in constructed graph. When we delete last vertex of one of colors, all other vertices can be joined in any correct way with edges of weight $0$.",
    "tags": [
      "constructive algorithms",
      "dsu",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "260",
    "index": "E",
    "title": "Dividing Kingdom",
    "statement": "A country called Flatland is an infinite two-dimensional plane. Flatland has $n$ cities, each of them is a point on the plane.\n\nFlatland is ruled by king Circle IV. Circle IV has 9 sons. He wants to give each of his sons part of Flatland to rule. For that, he wants to draw four \\textbf{distinct} straight lines, such that two of them are parallel to the $Ox$ axis, and two others are parallel to the $Oy$ axis. At that, no straight line can go through any city. Thus, Flatland will be divided into 9 parts, and each son will be given exactly one of these parts. Circle IV thought a little, evaluated his sons' obedience and decided that the $i$-th son should get the part of Flatland that has exactly $a_{i}$ cities.\n\nHelp Circle find such four straight lines that if we divide Flatland into 9 parts by these lines, the resulting parts can be given to the sons so that son number $i$ got the part of Flatland which contains $a_{i}$ cities.",
    "tutorial": "Consider $9!$ variants of location of integers $a[i]$ on $9$ areas. When we consider some location (some grid), we can easily find amount of cities to the left of the left vertical line, to the right of the right vertical line, below the lower horizontal line and above the upper horizontal line. All these numbers is sum of three values $a[i]$. We assume that the lines of the answer are always in half-integer coordinates. Then, knowing the above $4$ numbers, we can uniquely determine separately for $x$ and $y$ how to accommodate all the $4$ lines. It remains only to check that in all areas there is desired number of points. For each of four zones (to the left of the left vertical line, to the right of the right vertical line, below the lower horizontal line and above the upper horizontal line) separately check, that all three areas have correct number of cities. It can be done offline using scan-line and segment-tree, which can find sum on interval and change value in some point. You should put all queries in some array, sort them and process from left to right. Note, when you check $8$ from $9$ areas for every $9!$ variants of location, the last area (central) could not be checked, it will be correct automatically.",
    "tags": [
      "binary search",
      "brute force",
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "261",
    "index": "A",
    "title": "Maxim and Discounts",
    "statement": "Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.\n\nThere are $m$ types of discounts. We assume that the discounts are indexed from 1 to $m$. To use the discount number $i$, the customer takes a special basket, where he puts exactly $q_{i}$ items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the \"free items\" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected \"free items\" is as follows: each of them mustn't be more expensive than the cheapest item out of the $q_{i}$ items in the cart.\n\nMaxim now needs to buy $n$ items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.\n\nPlease assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.",
    "tutorial": "Ofcourse the most optimal way is to use discount with minimal q_i. We will sort our numbers and will go from the end to begin of the array. We will by use our discount as soon as it will be possible. It's not hard to see that we will buy all the items with numbers I (zero-numeration from the end of the sorted array) such, that I%(q+2)<q.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "261",
    "index": "B",
    "title": "Maxim and Restaurant",
    "statement": "Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is $p$ meters.\n\nMaxim has got a dinner party tonight, $n$ guests will come to him. Let's index the guests of Maxim's restaurant from 1 to $n$. Maxim knows the sizes of all guests that are going to come to him. The $i$-th guest's size ($a_{i}$) represents the number of meters the guest is going to take up if he sits at the restaurant table.\n\nLong before the dinner, the guests line up in a queue in front of the restaurant in some order. Then Maxim lets the guests in, one by one. Maxim stops letting the guests in when there is no place at the restaurant table for another guest in the queue. There is no place at the restaurant table for another guest in the queue, if the sum of sizes of all guests in the restaurant plus the size of this guest from the queue is larger than $p$. In this case, not to offend the guest who has no place at the table, Maxim doesn't let any other guest in the restaurant, even if one of the following guests in the queue would have fit in at the table.\n\nMaxim is now wondering, what is the average number of visitors who have come to the restaurant for all possible $n!$ orders of guests in the queue. Help Maxim, calculate this number.",
    "tutorial": "If all people can come, we will return answer as n. If it is impossible, there will be finded some person that will be the last to come. We will brtueforce this value. Then we will detrminate dp[i,j,s] in how many ways j persons from the first i with total length s can be in the resturant. It is easy to calculate. Then we will add to the answer values dp[n][i][s]*i!*(n-1-i)! for all i,s such that s+p[h]>P. Where P - total length of the table, p[h] - length of the fixed person.",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 1900
  },
  {
    "contest_id": "261",
    "index": "C",
    "title": "Maxim and Matrix",
    "statement": "Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size $(m + 1) × (m + 1)$:\n\nMaxim asks you to count, how many numbers $m$ $(1 ≤ m ≤ n)$ are there, such that the sum of values in the cells in the row number $m + 1$ of the resulting matrix equals $t$.\n\nExpression ($x$ $xor$ $y$) means applying the operation of bitwise excluding \"OR\" to numbers $x$ and $y$. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by character \"^\", in Pascal — by \"xor\".",
    "tutorial": "For fixed m, the sum in the last row will be 2^(bit_count(m+1)-1). So now if T is not power of 2, answer is 0. Else we can find number of bits that we need. And know we have stndart problem. How many numbers form 2 to n+1 have exactly P bits in binary presentation of the number. It is well known problem can be done using binomial cooficients. We will count number of numebers smaller then out number with fixed prefix.",
    "tags": [
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "261",
    "index": "D",
    "title": "Maxim and Increasing Subsequence",
    "statement": "Maxim loves sequences, especially those that strictly increase. He is wondering, what is the length of the longest increasing subsequence of the given sequence $a$?\n\nSequence $a$ is given as follows:\n\n- the length of the sequence equals $n × t$;\n- $a_{i}=b_{((i-1)}\\;\\;\\mathrm{mod}\\;n)+1$ $(1 ≤ i ≤ n × t)$, where operation $(x\\ {\\mathrm{~mod~}}y)$ means taking the remainder after dividing number $x$ by number $y$.\n\nSequence $s_{1}, s_{2}, ..., s_{r}$ of length $r$ is a subsequence of sequence $a_{1}, a_{2}, ..., a_{n}$, if there is such increasing sequence of indexes $i_{1}, i_{2}, ..., i_{r}$ $(1 ≤ i_{1} < i_{2} < ... < i_{r} ≤ n)$, that $a_{ij} = s_{j}$. In other words, the subsequence can be obtained from the sequence by crossing out some elements.\n\nSequence $s_{1}, s_{2}, ..., s_{r}$ is increasing, if the following inequality holds: $s_{1} < s_{2} < ... < s_{r}$.\n\nMaxim have $k$ variants of the sequence $a$. Help Maxim to determine for each sequence the length of the longest increasing subsequence.",
    "tutorial": "This problem can be done using dp[i,j] where we can end our increasing sequence with length i and last number j. Its not hard to understand that number of states will be n*b. To make a tranfer we need to know array first[j] - first position of the number j in the sequence b, next[i][j] - first position of the number j in the sequence b after position i. Now its easy to calculate all values.",
    "tags": [
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "262",
    "index": "A",
    "title": "Roma and Lucky Numbers",
    "statement": "Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.\n\nLet us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits $4$ and $7$. For example, numbers $47$, $744$, $4$ are lucky and $5$, $17$, $467$ are not.\n\nRoma's got $n$ positive integers. He wonders, how many of those integers have not more than $k$ lucky digits? Help him, write the program that solves the problem.",
    "tutorial": "This problem just need to simulate everithing that was given in statment.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "262",
    "index": "B",
    "title": "Roma and Changing Signs",
    "statement": "Roma works in a company that sells TVs. Now he has to prepare a report for the last year.\n\nRoma has got a list of the company's incomes. The list is a sequence that consists of $n$ integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly $k$ changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.\n\nThe operation of changing a number's sign is the operation of multiplying this number by -$1$.\n\nHelp Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform \\textbf{exactly} $k$ changes.",
    "tutorial": "We will \"reverse\" numbers from the begining to the end while numebrers are negative and we did't spend all k operations. In the end there can leave some operetions, and we will \"reverse\" only one numeber, with minimal value k(that remains) times.",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "263",
    "index": "A",
    "title": "Beautiful Matrix",
    "statement": "You've got a $5 × 5$ matrix, consisting of $24$ zeroes and a single number one. Let's index the matrix rows by numbers from $1$ to $5$ from top to bottom, let's index the matrix columns by numbers from $1$ to $5$ from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:\n\n- Swap two neighboring matrix rows, that is, rows with indexes $i$ and $i + 1$ for some integer $i$ $(1 ≤ i < 5)$.\n- Swap two neighboring matrix columns, that is, columns with indexes $j$ and $j + 1$ for some integer $j$ $(1 ≤ j < 5)$.\n\nYou think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.",
    "tutorial": "If the single $1$ is located on the intersection of the $r$-th row and the $c$-th column (1-based numeration), then the answer is $|3 - r| + |3 - c|$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "263",
    "index": "B",
    "title": "Squares",
    "statement": "Vasya has found a piece of paper with a coordinate system written on it. There are $n$ distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to $n$. It turned out that points with coordinates $(0, 0)$ and $(a_{i}, a_{i})$ are the opposite corners of the $i$-th square.\n\nVasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly $k$ drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary.\n\nHelp Vasya find a point that would meet the described limits.",
    "tutorial": "If $k > n$, then the answer doesn't exist. Otherwise let's sort the squares by descending of their sizes. Now you can print any point that belongs to the $k$-th square and doesn't belong to the $k + 1$-th square. One of the possible answers is $(a_{k}, 0)$.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "263",
    "index": "C",
    "title": "Circle of Numbers",
    "statement": "One day Vasya came up to the blackboard and wrote out $n$ distinct integers from $1$ to $n$ in some order in a circle. Then he drew arcs to join the pairs of integers $(a, b)$ $(a ≠ b)$, that are either each other's immediate neighbors in the circle, or there is number $c$, such that $a$ and $с$ are immediate neighbors, and $b$ and $c$ are immediate neighbors. As you can easily deduce, in the end Vasya drew $2·n$ arcs.\n\nFor example, if the numbers are written in the circle in the order $1, 2, 3, 4, 5$ (in the clockwise direction), then the arcs will join pairs of integers $(1, 2)$, $(2, 3)$, $(3, 4)$, $(4, 5)$, $(5, 1)$, $(1, 3)$, $(2, 4)$, $(3, 5)$, $(4, 1)$ and $(5, 2)$.\n\nMuch time has passed ever since, the numbers we wiped off the blackboard long ago, but recently Vasya has found a piece of paper with $2·n$ written pairs of integers that were joined with the arcs on the board. Vasya asks you to find the order of numbers in the circle by these pairs.",
    "tutorial": "First of all, we have to check that each number occurs in the input exactly 4 times. If it's not true, then the answer definitely doesn't exist. Otherwise, let's try to restore the circle. As cyclic shift of circle doesn't matter, let $1$ to be the first number. As the second and the third number must be connected to each other and to $1$, there are only few possibilities. So let's try them all. And when we know first three numbers, the rest of the circle could be easily and unambiguously restored in $O(n)$. Just find a number, which is not included in the circle yet, and is connected to the last two numbers of the circle. Add this number to the resulting circle (as new last number), and repeat the procedure while possible. If we succeeded to add all the numbers to the circle, than the resulting circle is the answer.",
    "tags": [
      "brute force",
      "dfs and similar",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "263",
    "index": "D",
    "title": "Cycle in Graph",
    "statement": "You've got a undirected graph $G$, consisting of $n$ nodes. We will consider the nodes of the graph indexed by integers from 1 to $n$. We know that each node of graph $G$ is connected by edges with at least $k$ other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least $k + 1$.\n\nA simple cycle of length $d$ $(d > 1)$ in graph $G$ is a sequence of distinct graph nodes $v_{1}, v_{2}, ..., v_{d}$ such, that nodes $v_{1}$ and $v_{d}$ are connected by an edge of the graph, also for any integer $i$ $(1 ≤ i < d)$ nodes $v_{i}$ and $v_{i + 1}$ are connected by an edge of the graph.",
    "tutorial": "Consider any simple path $v_{1}, v_{2}, ..., v_{r}$ which cannot be increased immediately (by adding a node to it's end, $v_{r}$). In other words, all the neighbours of $v_{r}$ are already included in the path. Let's find the first node of the path (say, $v_{l}$), which is connected to $v_{r}$. It is clear that $v_{l}, v_{l + 1}, ..., v_{r}$ is a cycle and it contains all the neighbours of $v_{r}$. But according to the problem's statement, each node has at least $k$ neighbours. So length of the cycle is at least $k + 1$ ($+ 1$ is for node $v_{r}$ itself).",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1800
  },
  {
    "contest_id": "263",
    "index": "E",
    "title": "Rhombus",
    "statement": "You've got a table of size $n × m$. On the intersection of the $i$-th row ($1 ≤ i ≤ n$) and the $j$-th column ($1 ≤ j ≤ m$) there is a non-negative integer $a_{i, j}$. Besides, you've got a non-negative integer $k$.\n\nYour task is to find such pair of integers $(a, b)$ that meets these conditions:\n\n- $k ≤ a ≤ n - k + 1$;\n- $k ≤ b ≤ m - k + 1$;\n- let's denote the maximum of the function $f(x,y)=\\sum_{i=1}^{n}\\sum_{j=1}^{m}a_{i,j}\\cdot m a x(0,k-\\vert i-x\\vert-\\vert j-y\\vert)$ among all integers $x$ and $y$, that satisfy the inequalities $k ≤ x ≤ n - k + 1$ and $k ≤ y ≤ m - k + 1$, as $mval$; for the required pair of numbers the following equation must hold $f(a, b) = mval$.",
    "tutorial": "Divide the rhombus of size $k$ into 4 right-angled triangles as shown on a picture below. One of them has size $k$, two - size $k - 1$, and another one - size $k - 2$. Let's solve the problem separately for each triangle. The most convenient way to do that is to rotate the input 4 times and run the same solving function 4 times. The result of this function will be a 2D array. Cell $(x, y)$ indicates the answer we get if the right-angled vertex of triangle is located at cell $(x, y)$. So it will be easy to combine 4 such arrays (just rotating and shifting properly) to get the actual answer for rhombus. The main idea of the solution for triangle is the following. If we know the answer for a cell, we can easily move our triangle by one cell in any direction (right, down, left, or up) and recalculate the answer for that new cell in constant time. In fact, we need only 2 directions: right and down. And the values for top left corner should be calculated with straightforward cycles in $O(k^{2})$ time. More precisely, let's define 5 functions: The sum on diagonal segment of $k$ elements: $d i a g o n a l(x,y)=\\sum_{i=0}^{k-1}a_{x-i,y+i}$ The sum on vertical segment of $k$ elements: $v e c t i c a l(x,y)=\\sum_{i=0}^{k-1}a_{x-i,y}$ The weighted sum on vertical segment of $k$ elements: $v e r t i c a l W e i g h t e d(x,y)=\\sum_{i=0}^{k-1}a_{x-i,y}\\cdot(k-i)$ The sum on a triangle: $t r i a n g l e(x,y)=\\sum_{i=0}^{k-1}\\sum_{j=0}^{k-1}a_{x-i,y-j}$ The weighted sum on a triangle: $t r i a n g l e W e i g h t e d(x,y)=\\sum_{i=0}^{k-1}\\sum_{i=0}^{k-1-i}a_{x-i,y-j}\\cdot(k-i-j)$ Calculating the first 3 functions in $O(nm)$ in total is quite obvious. Formulas for the others are following: $triangle(x, y + 1) = triangle(x, y) - diagonal(x, y - k + 1) + vertical(x, y + 1)$ $triangleWeighted(x, y + 1) = triangleWeighted(x, y) - triangle(x, y) + verticalWeighted(x, y + 1)$ Formulas for moving in other directions are similar.",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "264",
    "index": "A",
    "title": "Escape from Stones",
    "statement": "Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval $[0, 1]$. Next, $n$ stones will fall and Liss will escape from the stones. The stones are numbered from 1 to $n$ in order.\n\nThe stones always fall to the center of Liss's interval. When Liss occupies the interval $[k - d, k + d]$ and a stone falls to $k$, she will escape to the left or to the right. If she escapes to the left, her new interval will be $[k - d, k]$. If she escapes to the right, her new interval will be $[k, k + d]$.\n\nYou are given a string $s$ of length $n$. If the $i$-th character of $s$ is \"l\" or \"r\", when the $i$-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the $n$ stones falls.",
    "tutorial": "In this problem, there are many simple algorithms which works in $O(n)$. One of them (which I intended) is following: You should prepare 2 vectors. If $s[i] = 'l'$, you should push i to the first vector, and if $s[i] = 'r'$, you should push i to the second vector. Finally, you should print the integers in the second vector by default order, after that, you should print the integers in the first vector in the reverse order. This algorithm works because if Liss divides an interval into two intervals $A$ and $B$ and she enters $A$, she will never enter $B$.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "implementation",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "264",
    "index": "B",
    "title": "Good Sequences",
    "statement": "Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks $n$ integers $a_{1}, a_{2}, ..., a_{n}$ are good.\n\nNow she is interested in good sequences. A sequence $x_{1}, x_{2}, ..., x_{k}$ is called good if it satisfies the following three conditions:\n\n- The sequence is strictly increasing, i.e. $x_{i} < x_{i + 1}$ for each $i$ $(1 ≤ i ≤ k - 1)$.\n- No two adjacent elements are coprime, i.e. $gcd(x_{i}, x_{i + 1}) > 1$ for each $i$ $(1 ≤ i ≤ k - 1)$ (where $gcd(p, q)$ denotes the greatest common divisor of the integers $p$ and $q$).\n- All elements of the sequence are good integers.\n\nFind the length of the longest good sequence.",
    "tutorial": "The main idea is DP. Let's define $dp[x]$ as the maximal value of the length of the good sequence whose last element is $x$, and define $d[i]$ as the (maximal value of $dp[x]$ where $x$ is divisible by $i$). You should calculate $dp[x]$ in the increasing order of x. The value of $dp[x]$ is (maximal value of $d[i]$ where $i$ is a divisor of $x$) + 1. After you calculate $dp[x]$, for each divisor $i$ of $x$, you should update $d[i]$ too. This algorithm works in $O(nlogn)$ because the sum of the number of the divisor from 1 to $n$ is $O(nlogn)$. Note that there is a corner case. When the set is ${1}$, you should output 1.",
    "tags": [
      "dp",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "264",
    "index": "C",
    "title": "Choosing Balls",
    "statement": "There are $n$ balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the $i$-th ball is $c_{i}$ and the value of the $i$-th ball is $v_{i}$.\n\nSquirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence.\n\nThe value of the sequence is defined as the sum of following values for each ball (where $a$ and $b$ are given constants):\n\n- If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) $ × $ $a$.\n- Otherwise, add (the value of the ball) $ × $ $b$.\n\nYou are given $q$ queries. Each query contains two integers $a_{i}$ and $b_{i}$. For each query find the maximal value of the sequence she can make when $a = a_{i}$ and $b = b_{i}$.\n\nNote that the new sequence can be \\textbf{empty}, and the value of an empty sequence is defined as zero.",
    "tutorial": "There are many $O(Q * N * logN)$ solutions using segment trees or other data structures, but probably they will get time limit exceeded. We can solve each query independently. First, let's consider the following DP algorithm. $dp[c]$ := the maximal value of a sequence whose last ball's color is $c$ For each ball $i$, we want to update the array. Let the $i$-th ball's color be $col[i]$, the $i$-th ball's value be $val[i]$, and the maximal value of dp array other than $dp[col[i]]$ be $otherMAX$. We can update the value of $dp[col[i]]$ to $dp[col[i]] + val[i]  \\times  a$ or $otherMAX + val[i]  \\times  b$. Here, we only need to know $dp[col[i]]$ and $otherMAX$. If we remember the biggest two values of $dp$ array in that time and their indexes in the array, $otherMAX$ can be calculated using the biggest two values, which always include maximal values of dp array other than any particular color. Since the values of dp array don't decrease, we can update the biggest two values in $O(1)$. Finally, the answer for the query is the maximal value of $dp$ array. The complexity of the described algorithm is $O(QN)$.",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "264",
    "index": "D",
    "title": "Colorful Stones",
    "statement": "There are two sequences of colorful stones. The color of each stone is one of red, green, or blue. You are given two strings $s$ and $t$. The $i$-th (1-based) character of $s$ represents the color of the $i$-th stone of the first sequence. Similarly, the $i$-th (1-based) character of $t$ represents the color of the $i$-th stone of the second sequence. If the character is \"R\", \"G\", or \"B\", the color of the corresponding stone is red, green, or blue, respectively.\n\nInitially Squirrel Liss is standing on the first stone of the first sequence and Cat Vasya is standing on the first stone of the second sequence. You can perform the following instructions zero or more times.\n\nEach instruction is one of the three types: \"RED\", \"GREEN\", or \"BLUE\". After an instruction $c$, the animals standing on stones whose colors are $c$ will move one stone forward. For example, if you perform an instruction «RED», the animals standing on red stones will move one stone forward. You are not allowed to perform instructions that lead some animals out of the sequences. In other words, if some animals are standing on the last stones, you can't perform the instructions of the colors of those stones.\n\nA pair of positions (position of Liss, position of Vasya) is called a state. A state is called reachable if the state is reachable by performing instructions zero or more times from the initial state (1, 1). Calculate the number of distinct reachable states.",
    "tutorial": "First, let's consider a simpler version of the problem: You are given a start state and a goal state. Check whether the goal state is reachable from the start state. Define $A$, $B$, $C$, and $D$ as in the picture below, and let $I$ be the string of your instructions. $A$ and $B$ are substrings of $s$, and $C$ and $D$ are substrings of $t$. It is possible to reach the goal state from the start state if there exists an instruction $I$ such that: 1 $A$ is a subsequence of $I$. 2 $B$ is not a subsequence of $I$. 3 $C$ is a subsequence of $I$. 4 $D$ is not a subsequence of $I$. So we want to check if such string $I$ exists. (string $s1$ is called a subsequence of $s2$ if it is possible to get $s2$ by removing some characters of $s1$) There are some obvious \"NO\" cases. When $D$ is a subsequence of $A$, it is impossible to satisfy both conditions 1 and 4. Similarly, $B$ must not be a subsequence of $C$. Are these sufficient conditions? Let's try to prove this hypothesis. To simplify the description we will introduce some new variables. Let $A'$, $B'$, $C'$, and $D'$ be strings that can be obtained by removing the first characters of $A$, $B$, $C$, and $D$. Let $c1$ and $c2$ be the first characters of $A$ and $C$. Suppose that currently the conditions are satisfied (i.e. $D$ is not a subsequence of $A$ and $B$ is not a subsequence of $C$). If $c1 = c2$, you should perform the instruction $c1 = c2$. The new quatruplet will be $(A', B', C', D')$ and this also satisies the conditions. If $c1  \\neq  c2$ and $B'$ is not a subsequnce of $C$, you should perform the instruction $c1$. The new quatruplet will be $(A', B', C, D)$ and this also satisies the conditions. If $c1  \\neq  c2$ and $D'$ is not a subsequnce of $A$, you should perform the instruction $c2$. The new quatruplet will be $(A, B, C', D')$ and this also satisies the conditions. What happens if all of the above three conditions don't hold? In this case $A$ and $C$ have the same length and $A = c1c2c1c2...$, $B = c2c1c2c1$. In particular the last two characters of $A$ and $B$ are swapped: there are different characters $x$ and $y$ and $A = ...xy$, $B = ...yx$. Now you found a new necessary condition! Generally, if $A$ and $B$ are of the form $A = ...xy$ and $B = ...yx$, the goal state is unreachable. If the last instruction is $x$, Vasya must be in the goal before the last instruction, but then Vasya will go further after the last instruction. If the last instruction is $y$, we will also get a contradiction. Finally we have a solution. The goal state is reachable from the start state if and only if $D$ is not a subsequence of $A$, $B$ is not a subsequnce of $C$, and $A$ and $C$ are not of the form $A = ...xy$, $C = ...yx$. The remaining part is relatively easy, so I'll leave it as an exercise for readers.",
    "tags": [
      "dp",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "264",
    "index": "E",
    "title": "Roadside Trees",
    "statement": "Squirrel Liss loves nuts. Liss asks you to plant some nut trees.\n\nThere are $n$ positions (numbered 1 to $n$ from west to east) to plant a tree along a street. Trees grow one meter per month. At the beginning of each month you should process one query. The query is one of the following types:\n\n- Plant a tree of height $h$ at position $p$.\n- Cut down the $x$-th existent (not cut) tree from the west (where $x$ is 1-indexed). When we cut the tree it drops down and takes all the available place at the position where it has stood. So no tree can be planted at this position anymore.\n\nAfter processing each query, you should print the length of the longest increasing subsequence. A subset of existent trees is called an increasing subsequence if the height of the trees in the set is strictly increasing from west to east (for example, the westmost tree in the set must be the shortest in the set). The length of the increasing subsequence is the number of trees in it.\n\nNote that Liss don't like the trees with the same heights, so it is guaranteed that at any time no two trees have the exactly same heights.",
    "tutorial": "When you want to plant a tree with height h at time t, you should plant a tree with height h-t instead. Then you can ignore the growth of the trees. And plot trees on a x-y plane: x-coordinate is the position and y-coordinate is the modified height (h-t). like this picture then..... LIS is the longest sequence of points P_1, P_2, ... such that x(P_1) < x(P_2) < ... y(P_1) < y(P_2) < ... At each point write the length of the longest increasing sequence that starts from the point. The value written on point p = (the maximal value written in the rectangle whoselower-left corner is p) + 1. How should we process queries? Planting query -> plot a new point The new point will be one of the ten points that have the smallest y-coordinate. To process this query, erase all values written below the new point first and rewrite the values to those points from top to bottom. Cutting query -> remove a point Similarly the removed point will be one of the ten points that have the smallest x-coordinate. So you can erase all values written on those points and rewrite correct values from right to left. What data structures do we need? 2D segtree? -> too slow :( Make two segment trees: let's call them segx and segy. segx : x-directional segtree segy : y-directional segtree For planting queries use segx. For cutting queries use segy. The i-th leaf of segx contains the value written on the point whose x-coordinate is x and non-leaf nodes of the segment trees have the maximum of children of the node. Define segy similarly. Time Complexity O(N * 10 * log N)",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "265",
    "index": "A",
    "title": "Colorful Stones (Simplified Edition)",
    "statement": "There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string $s$. The $i$-th (1-based) character of $s$ represents the color of the $i$-th stone. If the character is \"R\", \"G\", or \"B\", the color of the corresponding stone is red, green, or blue, respectively.\n\nInitially Squirrel Liss is standing on the first stone. You perform instructions one or more times.\n\nEach instruction is one of the three types: \"RED\", \"GREEN\", or \"BLUE\". After an instruction $c$, if Liss is standing on a stone whose colors is $c$, Liss will move one stone forward, else she will not move.\n\nYou are given a string $t$. The number of instructions is equal to the length of $t$, and the $i$-th character of $t$ represents the $i$-th instruction.\n\nCalculate the final position of Liss (the number of the stone she is going to stand on in the end) after performing all the instructions, and print its 1-based position. It is guaranteed that Liss don't move out of the sequence.",
    "tutorial": "In this problem you just need to implement what is written in the statement. Make a variable that holds the position of Liss, and simulate the instructions one by one.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "265",
    "index": "B",
    "title": "Roadside Trees (Simplified Edition)",
    "statement": "Squirrel Liss loves nuts. There are $n$ trees (numbered $1$ to $n$ from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree $i$ is $h_{i}$. Liss wants to eat all nuts.\n\nNow Liss is on the root of the tree with the number $1$. In one second Liss can perform one of the following actions:\n\n- Walk up or down one unit on a tree.\n- Eat a nut on the top of the current tree.\n- Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height $h$ of the tree $i$ ($1 ≤ i ≤ n - 1$), she jumps to height $h$ of the tree $i + 1$. This action can't be performed if $h > h_{i + 1}$.\n\nCompute the minimal time (in seconds) required to eat all nuts.",
    "tutorial": "The optimal path of Liss is as follows: First she starts from the root of tree 1. Walk up the tree to the top and eat a nut. Walk down to the height $min(h_{1}, h_{2})$. Jump to the tree 2. Walk up the tree to the top and eat a nut. Walk down to the height $min(h_{2}, h_{3})$, $...$ and so on.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "266",
    "index": "A",
    "title": "Stones on the Table",
    "statement": "There are $n$ stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.",
    "tutorial": "In this problem you should count number of consecutive pairs of equal letters. It can be done using one cycle and $O(N)$ time.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "266",
    "index": "B",
    "title": "Queue at the School",
    "statement": "During the break the schoolchildren, boys and girls, formed a queue of $n$ people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each second.\n\nLet's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from $1$ to $n$, at that the person in the position number $1$ is served first. Then, if at time $x$ a boy stands on the $i$-th position and a girl stands on the $(i + 1)$-th position, then at time $x + 1$ the $i$-th position will have a girl and the $(i + 1)$-th position will have a boy. The time is given in seconds.\n\nYou've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after $t$ seconds.",
    "tutorial": "In this you should realize the given process. You should $t$ times swap elements $i$ and $i + 1$ if on the place $i$ was a girl and on the place $i + 1$ was a boy. You should not push some girl to the left multiple times at once. The solution can be written using $O(N \\cdot T)$ time.",
    "tags": [
      "constructive algorithms",
      "graph matchings",
      "implementation",
      "shortest paths"
    ],
    "rating": 800
  },
  {
    "contest_id": "266",
    "index": "C",
    "title": "Below the Diagonal",
    "statement": "You are given a square matrix consisting of $n$ rows and $n$ columns. We assume that the rows are numbered from $1$ to $n$ from top to bottom and the columns are numbered from $1$ to $n$ from left to right. Some cells ($n - 1$ cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:\n\n- Swap $i$-th and $j$-th rows of the matrix;\n- Swap $i$-th and $j$-th columns of the matrix.\n\nYou are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the $i$-th row and of the $j$-th column, lies below the main diagonal if $i > j$.",
    "tutorial": "This problem can be solved using constructive algorithm. We will use inductive approach. At first, we have matrix of size $n$ and $n - 1$ ones in it. Therefore, there is a column with no ones in it. So, we put this column to $n$-th place. In this case, the lower right element will be $0$. Then find any row with at least one integer one and put it to the $n$-th place. After these operations the element in cell $(n, n)$ equals to $0$ and the last row has at least one integer one. Therefore, we can reduce the dimension of our problem, that is $n: = n - 1$. In our new problem we have no more than $n - 2$ ones. So, we can solve this problem using the same algorithm. When $n$ equals to $1$ you should finish algorithm, because there is no ones left. This algorithm uses $O(N)$ swap operations, no more than two for every $n$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "266",
    "index": "D",
    "title": "BerDonalds",
    "statement": "BerDonalds, a well-known fast food restaurant, is going to open a cafe in Bertown. The important thing is to choose the new restaurant's location so that it would be easy to get there. The Bertown road system is represented by $n$ junctions, connected by $m$ bidirectional roads. For each road we know its length. We also know that we can get from any junction to any other one, moving along the roads.\n\nYour task is to find such location of the restaurant, that the shortest distance along the roads from the cafe to the farthest junction would be minimum. Note that the restaurant can be located not only on the junction, but at any point of any road.",
    "tutorial": "I'll tell a few ideas how to solve this problem. Firstly, describe the solution with time $O(N^{4})$. Consider every edge $(u, v)$ of length $len$ where could be the answer point. Let this point lie at a distance $x$ from vertex $u$. So, the distance from this point to vertex $i$ would be $min(x + d[u][i], len-x + d[v][i])$, where $d[x][y]$ - distance between vertices $x$ and $y$. Equate these values and get the critical value $x$ for vertex $i$, $x = (len + d[v][i]-d[u][i]) / 2$. It follows that the answer to the problem is half-integer. So, for every edge and every other vertex we get set of critical points. We should check them all include the vertices of the graph (ends of the segments). This solution may probably pass with some optimizations. Another solution with complexity $O(N^{3} \\cdot log^{2})$. Multiply all weights by $2$. Consider every edge where should be the answer and make binary search for the answer (in integers). To check some current value you should consider every vertex $i$ and assume that the answer is achieved in this vertex. In this case, the answer point must lie on this edge <= some value $l[i]$ or >= some value $r[i]$. This subproblem is solved using offline algorithm using sorting events and maintaining the balance. Also, you can use ternary search on every edge of the graph. But you should divide every edge on several segments and find the answer on every segment, because the ternary search is incorrect in this problem. The last two solutions can provide accepted, if you realize them carefully. Also note, that there is the solution with complexity $O(N^{3})$ by the author RAD.",
    "tags": [
      "graphs",
      "math",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "266",
    "index": "E",
    "title": "More Queries to Array...",
    "statement": "You've got an array, consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Your task is to quickly run the queries of two types:\n\n- Assign value $x$ to all elements from $l$ to $r$ inclusive. After such query the values of the elements of array $a_{l}, a_{l + 1}, ..., a_{r}$ become equal to $x$.\n- Calculate and print sum $\\textstyle\\sum_{i=l}^{r}a_{i}\\cdot(i-l+1)^{k}$, where $k$ doesn't exceed $5$. As the value of the sum can be rather large, you should print it modulo $1000000007 (10^{9} + 7)$.",
    "tutorial": "This problem can be solved using data structure. We would use segment tree, we will support $k$ segment trees for every power. At every vertex we will calculate weighted sum of the appropriate power, also we will save some number that indicates the color of the whole segment, if any. User Egor in comments to the post and user mexmans in comments to the tutorial tell their formula to get the answer. I try to describe how to get them by yourself. Firstly, you should write what value your segment tree gives. The tree can calculate the sum $\\textstyle\\sum_{i=1}^{r}a_{i}\\cdot i^{j}$. You need to calculate the sum $\\sum_{i=l}^{r}a_{i}\\cdot(i-l+1)^{j}$, you can write it also as $\\textstyle\\sum_{i=l}^{r}a_{i}\\cdot(i+(1-l))^{j}$. Then you should write the last sum for some first powers (at least three) (at piece of paper) and subtract the second sum (what you need) from the first sum (what your tree can calculate). You get an expression that describes what should be subtracted to get the answer from the value what you tree can calculate. This is just the Newton binomial without the highest power. So, the answer for power $j$ is expressed as the subtraction of the value of query to your segment tree and the Newton binomial, with all powers that are less than $j$ (these values can also calculated using your segment tree). Partial sum of the powers and binomial coefficients can be precalced. The solution has the complexity $O(N \\cdot K \\cdot log(N))$.",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "268",
    "index": "A",
    "title": "Games",
    "statement": "Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.\n\nThere are $n$ teams taking part in the national championship. The championship consists of $n·(n - 1)$ games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.\n\nYou know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.",
    "tutorial": "With only 30 teams, the simplest solution is simulating all the matches: An O(N + M) solution is also possible, where M is the length of colors' range (i.e. 100 under the given constraints). First, you need to count for each color i the number of teams cntH[i] which have the home uniform of color i and the number of teams cntA[i] which have the away uniform of color i. The answer is the sum of products of these quantities for each color, i.e. sum of cntH[i] * cntA[i] over all i.",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "268",
    "index": "B",
    "title": "Buttons",
    "statement": "Manao is trying to open a rather challenging lock. The lock has $n$ buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens.\n\nConsider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock.\n\nManao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.",
    "tutorial": "Let us first detect the worst case scenario. It is more or less apparent that when Manao tries to guess the i-th (1 <= i <= n) button in order, he will make n-i mistakes in the worst case. After that the correct button is evident. Now let's count the total number of presses Manao might need before he guesses the whole sequence. When he is guessing the first button he makes n-1 mistakes, but the \"mistake cost\", i.e. the number of presses before the mistake is made, is equal to 1. When Manao goes for the second button, the mistake cost becomes 2, because each time Manao needs to press the first (already guessed) button. Continuing like this, we obtain that when Manao tries to guess the i-th button in order, he will perform (n-i) * i button presses. After Manao guessed the correct sequence, he needs to enter it once, which is another n presses. So we already have an O(n) algorithm: sum up (n-i)*i for i=1, ..., n-1 and add n to the sum obtained. When n is anything that fits in 32-bit integer type, the task is solvable in O(1)*. The sum (n-i)*i is two separate sums: the sum of n*i and the sum of i*i. The first sum is n*(1+...+n-1), which can be computed with the sum of arithmetic progression. The second sum is the sum of squares from 1 to n-1, which can be evaluated with a polynom of degree 3: http://pirate.shu.edu/~wachsmut/ira/infinity/answers/sm_sq_cb.html *The only problem is that the answer for large n-s does not fit even in 64-bit integer type, but at least we can compute its remainder from division by anything.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "268",
    "index": "C",
    "title": "Beautiful Sets of Points",
    "statement": "Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions:\n\n- The coordinates of each point in the set are integers.\n- For any two points from the set, the distance between them is a non-integer.\n\nConsider all points $(x, y)$ which satisfy the inequations: $0 ≤ x ≤ n$; $0 ≤ y ≤ m$; $x + y > 0$. Choose their subset of maximum size such that it is also a beautiful set of points.",
    "tutorial": "Obviously, if a set contains a point (x', y'), it can not contain any other point with x=x' or y=y', because these two points would be an integer distance apart. There are only n+1 distinct x-coordinates and m+1 distinct y-coordinates. Therefore, the size of the set sought can not exceed min(n, m) + 1. If the constraint x+y>0 was not present, the set of points (i, i) (0 <= i <= min(n, m)) would do nicely. The distance between two points (i, i) and (j, j) is equal to |i-j|*sqrt(2) and can only be integer when i=j. On the other hand, there are min(n, m) + 1 points and we already know that we can't take more than that. Since point (0, 0) is restricted, we can take the other \"diagonal\", i.e. use points (i, min(n, m) - i).",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "268",
    "index": "D",
    "title": "Wall Bars",
    "statement": "Manao is working for a construction company. Recently, an order came to build wall bars in a children's park. Manao was commissioned to develop a plan of construction, which will enable the company to save the most money.\n\nAfter reviewing the formal specifications for the wall bars, Manao discovered a number of controversial requirements and decided to treat them to the company's advantage. His resulting design can be described as follows:\n\n- Let's introduce some unit of length. The construction center is a pole of height $n$.\n- At heights $1, 2, ..., n$ exactly one horizontal bar sticks out from the pole. Each bar sticks in one of four pre-fixed directions.\n- A child can move from one bar to another if the distance between them does not exceed $h$ and they stick in the same direction. If a child is on the ground, he can climb onto any of the bars at height between $1$ and $h$. In Manao's construction a child should be able to reach at least one of the bars at heights $n - h + 1, n - h + 2, ..., n$ if he begins at the ground.\n\n\\begin{center}\n{\\scriptsize The figure to the left shows what a common set of wall bars looks like. The figure to the right shows Manao's construction}\n\\end{center}\n\nManao is wondering how many distinct construction designs that satisfy his requirements exist. As this number can be rather large, print the remainder after dividing it by $1000000009 (10^{9} + 9)$. Two designs are considered distinct if there is such height $i$, that the bars on the height $i$ in these designs don't stick out in the same direction.",
    "tutorial": "Those who are well experienced at dynamic programming can scroll down to \"Overall solution\" right away. Those who have some experience in DPs can read my attempt to explain how you can come up with that solution. Those with no experience probably shouldn't read this at all :) Imagine a solution which considers all possible designs, adding the bar-steps one by one. Consider any sequence, like 2123412413. There are 4 ways to continue this sequence by appending '1', '2', '3' or '4' to it. For each of the 4^n wall bars / strings we need to check that for at least one of {'1', '2', '3', '4'} character the following is true: its first entry in the string is at position no more than h, each next one differs from the previous by no more than h and the last one is beyond position n-h. Surely, such a solution won't work for large n-s in any reasonable time, but we can start from it in the search of a better approach. First, let's note that we can check the feasibility of the string after each character addition: if somewhere in the middle of string we noticed that for each of the characters the necessary conditions are broken, there is no reason to complete the string. Also, note that we don't need the whole prefix to check the validity of the conditions after each character addition. All we need to know is when each of the '1', '2', '3' and '4' characters occured last, and whether the conditions for each of the characters have been fulfilled up to this point. It turns out that two prefixes in which [each of the characters last occured at the same position] and [the validity of the conditions for each character are equal], are absolutely equivalent for the brute force algorithm's further operation. That is, for example for h=4 these two prefixes can be completed (up to length n) in the same number of ways: The last time each of the characters have occured at the same positions, characters '1' and '3' are already \"lost\" (the conditions are already broken for them), characters '2' and '4' can still turn the string into a valid one. With the help of the observations made, we can already build a polynomial-time algorithm based on dynamic programming principle. Let ways[curN][i][j][k][l][ii][jj][kk][ll] be the number of designs of height curN, where the last step in direction 1 was at height i, the last step in direction 2 - at height j and so on; ii, jj, kk, ll are boolean parameters which indicate whether the conditions are valid in the corresponding direction. When we choose the direction for the step at height curN+1, we obtain a design with curN+1 steps, the last step in the direction we chose is now at height curN+1 and rest stay where they were. Conditions validity can also be reassessed. Since curN is always one of {i, j, k, l}, we can obtain a O(n^4) algorithm. However, this is still too slow. Another observation: if we are looking at a bar at height curN and the last step in this direction was earlier than curN-h steps ago, we don't really care which height was it exactly at, since this direction is not valid any more. Therefore, the number of states in our algorithm can be only O(n*h^3). Moreover, those ii,jj,kk,ll parameters correlate with the heights of the latest steps in the corresponding directions, so we can (almost) get rid of them, thus reducing the number of states in a number of times. On the base of these observations we can probably build different solutions. I will tell mine. We will keep a 5-dimensional DP :) Let ways[curN][alive][last1][last2][last3] be the number of designs where: There are exactly curN steps. If the direction of the latest step if still \"alive\", then alive = 1, otherwise it's equal to 0. A direction is alive if its first step was not higher than h and each subsequent one was higher than the previous by at most distance h. last1, last2 and last3 keep the information about the other directions in any order. lasti can be zero in two cases: if there were no steps in the corresponding direction, or if the latest one was earlier than h steps before. Otherwise, lasti is the number of steps between the current step and the latest step in the corresponding direction. We can optimize by keeping last1<=last2<=last3, which reduces the number of states in roughly 6 times. However, this complicates the code and doesn't have a significant effect (since the transitions processing becomes costly). Thus I will not consider it at all. What transitions can be made from state [curN][alive][last1][last2][last3]? We shall process the states in order from curN=1 to curN=N-1. ways[1][1][0][0][0] (i.e. a single step) is equal to 4 as a base case. So we have: If we add a step in the same direction as the latest (i.e. the one at height curN), then we obtain state [curN+1][alive][last1+1][last2+1][last3+1] (roughly): curN has increased by 1; the \"livingness\" of the direction of the last step could not change; all the lasti-s have increased by 1. However, note that for lasti=0 it should not be incremented (the corresponding step either does not exist at all, or is way below). Also, for lasti=h-1 it turns to zero (the last step is now too low). If we put the step in the same direction as the one which was at height last1, we obtain state [curN+1][last1 > 0 || curN < h][alive][last2+1][last3+1]. This decyphers in the following way: if last1>0, then this condition is alive. last1 could also be 0, but the number of already built steps less than h - in which case this is the first step and the direction becomes alive by putting it. The direction denoted by last1 has been replaced (in the state parameters) by the one in which the curN-th step was sticked out. Therefore, it was 1 step ago and we should write [1] there. On the other hand, that direction could already be dead and we would need to write [0]. It turns out that the value coincides with value of alive. last2 and last3 change in the same way as in the previous case. Directions last2 and last3 are treated in the same way as last1. When we process a transition, the number of designs corresponding to the new state increments by ways[curN][alive][last1][last2][last3]. So the overall answer is sum of all [n][1][a][b][c], where 0<=a,b,c<h plus sum of all [n][0][a][b][c], where at least one of a, b, c is non-zero. So we have an algorithm of O(n*h^3) complexity which needs asymptotically the same amount of memory. Its implementation could catch ML (especially on Java). This can be handled through the following observation: since we only need values [i-1][][][][] to compute [i][][][][]-s, only O(h^3) states need to be kept at any given moment.",
    "code": "#include <cstdio>\n#include <cstring>\n#include <algorithm>\n#define FOR(i,s,e) for (int i=(s); i<(e); i++)\n#define FOE(i,s,e) for (int i=(s); i<=(e); i++)\n#define FOD(i,s,e) for (int i=(s)-1; i>=(e); i--)\n#define CLR(a,x) memset(a, x, sizeof(a))\n#define EXP(i,l) for (int i=(l); i; i=qn[i])\n#define LLD long long\nusing namespace std;\n\nint n, m;\nLLD dp[2][32][32][32][2], t, j3, ret;\nLLD MOD = 1000000009;\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tdp[0][0][0][0][1] = 1;\n\t\n\tFOR(i,0,n){\n\t\tFOE(j0,0,m)\n\t\tFOE(j1,0,m)\n\t\tFOE(j2,0,m)\n\t\tFOR(k,0,2){\n\t\t\tt = dp[i&1][j0][j1][j2][k];\n\t\t\tif (!t) continue;\n\t\t\tdp[i&1][j0][j1][j2][k] = 0;\n\t\t\tt %= MOD;\n\t\t\t\n\t\t\tif (k) j3 = 1;\n\t\t\telse j3 = m;\n\t\t\t\n\t\t\t// put j0\n\t\t\tdp[i&1^1][min(m, j1+1)][min(m, j2+1)][j3][j0 < m] += t;\n\t\t\t\n\t\t\t// put j1\n\t\t\tdp[i&1^1][min(m, j0+1)][min(m, j2+1)][j3][j1 < m] += t;\n\t\t\t\n\t\t\t// put j2\n\t\t\tdp[i&1^1][min(m, j0+1)][min(m, j1+1)][j3][j2 < m] += t;\n\t\t\t\n\t\t\t// put k\n\t\t\tdp[i&1^1][min(m, j0+1)][min(m, j1+1)][min(m, j2+1)][k] += t;\n\t\t}\n\t}\n\t\n\tFOE(j0,0,m)\n\tFOE(j1,0,m)\n\tFOE(j2,0,m)\n\tFOR(k,0,2)\n\tif (j0 < m || j1 < m || j2 < m || k) ret = (ret + dp[n&1][j0][j1][j2][k]) % MOD;\n\t\n\tprintf(\"%I64d\n\", ret);\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "268",
    "index": "E",
    "title": "Playlist",
    "statement": "Manao's friends often send him new songs. He never listens to them right away. Instead, he compiles them into a playlist. When he feels that his mind is open to new music, he opens the playlist and starts to listen to the songs.\n\nOf course, there are some songs that Manao doesn't particuarly enjoy. To get more pleasure from the received songs, he invented the following procedure of listening to the playlist:\n\n- If after listening to some song Manao realizes that he liked it, then he remembers it and starts to listen to the next unlistened song.\n- If after listening to some song Manao realizes that he did not like it, he listens to all the songs he liked up to this point and then begins to listen to the next unlistened song.\n\nFor example, if Manao has four songs in the playlist, A, B, C, D (in the corresponding order) and he is going to like songs A and C in the end, then the order of listening is the following:\n\n- Manao listens to A, he likes it, he remembers it.\n- Manao listens to B, he does not like it, so he listens to A, again.\n- Manao listens to C, he likes the song and he remembers it, too.\n- Manao listens to D, but does not enjoy it and re-listens to songs A and C.\n\nThat is, in the end Manao listens to song A three times, to song C twice and songs B and D once. Note that if Manao once liked a song, he will never dislike it on a subsequent listening.\n\nManao has received $n$ songs: the $i$-th of them is $l_{i}$ seconds long and Manao may like it with a probability of $p_{i}$ percents. The songs could get on Manao's playlist in any order, so Manao wants to know the maximum expected value of the number of seconds after which the listening process will be over, for all possible permutations of the songs in the playlist.",
    "tutorial": "Let us first find the answer for a fixed sequence of songs. Consider any two songs which are at positions i and j (i < j) in the playlist. If Manao liked song i and disliked song j, then song i will be listened to again. Therefore, with probability p[i]*(1-p[j]) the process length will increase by L[i]. The sum of L[i]*p[i]*(1-p[j]) over all pairs (plus the length of all songs since Manao listens to them at least once) is the expected length for the fixed sequence. So we have that if there are two songs (l1, p1) and (l2, p2), the first one should be placed earlier in the playlist if l1*p1*(1-p2)>l2*p2*(1-p1) and later otherwise. This is obviously true if there are only two songs. But suppose that we have more and you ask, why can't there be another song (l3, p3) such that the above inequality rules out that the first song should be after this one and the second song should be before it? Then it's unclear which of the orders results in the maximum expected value. Consider this case in details: (this is not quite true if any pi is equal to 0 or 1, but that's not important here) We have a contradicting system of inequations, so such a case is impossible. Next, let's consider some order of songs (l[1], p[1]), ..., (l[n], p[n]), in which there is a pair of neighbouring songs i and i+1, for which the condition l[i] * p[i] * (1 - p[i + 1]) >= l[i + 1] * p[i + 1] * (1 - p[i]) does not hold, and assume that this order is optimal. Evidently, if we interchange songs i and i+1, the answer will only change by the value contributed by this pair (i.e. l[i] * p[i] * (1 - p[i + 1])). The rest of the songs keep their order towards song i and song i+1. But l[i] * p[i] * (1 - p[i + 1]) < l[i + 1] * p[i + 1] * (1 - p[i]), therefore if we put song i+1 before song i, we obtain a larger value. So we have a contradiction - the order chosen is not optimal. So it turns out that the permutation with maximum possible expected value is obtained when sorting the songs in decreasing order of l[i]*p[i]/(1-p[i]). But we still have a problem of computing the answer for a fixed permutation: we only learned how to do this in O(n^2), which is too slow with n=50000. We can use an idea which is probably a yet another dynamic programming example. Suppose we have fixed j and are counting the contribution of song j towards the answer if Manao dislikes it. This value is (l1*p1 + l2*p2 + ... + l[j-1]*p[j-1]). For j+1, the corresponding value will be (l1*p1+...+l[j-1]*p[j-1]+l[j]*p[j]). It turns out that these values differ in only a single summand, so we can compute each of them in O(1) if we consider j-th one by one in increasing order. This idea can be expressed as follows:",
    "tags": [
      "math",
      "probabilities",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "269",
    "index": "A",
    "title": "Magical Boxes",
    "statement": "Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.\n\nFrom the top view each magical box looks like a square with side length equal to $2^{k}$ ($k$ is an integer, $k ≥ 0$) units. A magical box $v$ can be put inside a magical box $u$, if side length of $v$ is strictly less than the side length of $u$. In particular, Emuskald can put 4 boxes of side length $2^{k - 1}$ into one box of side length $2^{k}$, or as in the following figure:\n\nEmuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.",
    "tutorial": "Suppose we can put all the squares inside a square with side length $2^{p}$. Then we can insert each $k_{i}$ type squares independently along the grid as shown in the picture. No two squares will overlap, since $2^{x}$ divides $2^{y}$, if $x < y$. That means that we can find the smallest square that can hold all the given squares with side length $2^{ki}$ for each $k_{i}$ separately. The answer will be the side length of the largest such square. To be able to put $a_{i}$ squares with side length $2^{ki}$ inside a square with side length $2^{s}$, the following should hold: $(2^{s})^{2}  \\ge  (2^{ki})^{2} \\cdot a_{i}$ $4^{s}  \\ge  4^{ki} \\cdot a_{i}$ $4^{s - ki}  \\ge  a_{i}$We can then find the minimum $s$: $s-k_{i}=\\lceil\\log_{4}a_{i}\\rceil$ $s=k_{i}+\\lceil\\log_{4}a_{i}\\rceil$In a special case, if we obtain $s = k_{i}$, $s$ should be increased by 1. Time: $O(n\\cdot\\log\\operatorname*{max}a)$. Memory: $O(1)$.",
    "code": "#include<cstdio>\n#include<algorithm>\nusing namespace std;\n\nint main() {\n    int n; scanf(\"%d\", &n);\n\tint p = 0, maxk = 0;\n\tfor(int i = 0; i < n; i++) {\n\t\tint k, a; scanf(\"%d %d\", &k, &a);\n\t\tmaxk = max(k, maxk);\n\t\tint m = 0, s = 1;\n\t\twhile(s < a) {\n\t\t\ts *= 4;\n\t\t\tm++;\n\t\t}\n\t\tp = max(p, k+m);\n\t}\n\tif(p == maxk) {\n\t\tp++;\n\t}\n\tprintf(\"%d\n\", p);\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "269",
    "index": "B",
    "title": "Greenhouse Effect",
    "statement": "Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length.\n\nOver the years Emuskald has cultivated $n$ plants in his greenhouse, of $m$ different plant species numbered from 1 to $m$. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.\n\nEmuskald has discovered that each species thrives at a different temperature, so he wants to arrange $m - 1$ borders that would divide the greenhouse into $m$ sections numbered from 1 to $m$ from left to right with each section housing a single species. He is free to place the borders, but in the end all of the $i$-th species plants must reside in $i$-th section from the left.\n\nOf course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at \\textbf{any} real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.",
    "tutorial": "First, observe that the coordinates don't matter: only the order of the points is important. Let there be some number of points we can replace to achieve the good arrangement. Then all the other points remain in their positions, so their values must be in increasing order from left to right. Then we must find the maximum number of points that can remain in their positions, which is the longest non-decreasing subsequence of types in the input. If it is of length $l$, the answer is $n - l$. In this problem it was enough to implement a quadratic solution. We count $dp[i][j]$ - the length of the longest non-decreasing subsequence on prefix $[1;i]$, with element of type $j$ being the last in subsequence. The transition is as follows: $d p[i][j]=\\left\\{{1+\\operatorname*{max}_{k=1}^{j}d p}_{\\mathrm{ap}[i-1][k],\\ \\ \\mathrm{~if~\\type}[i]=j}_{\\mathrm{otherwise}}\\right\\}$For easy implementation, we can maintain only array $dp[j]$, and skip the second case. Time: $O(n^{2})$ / $O(n \\log n)$. Memory: $O(n^{2})$ / $O(n)$.",
    "code": "#include<cstdio>\n#include<algorithm>\n#include<iostream>\n\nusing namespace std;\n\n#define MAXN 5005\n\nint n, m, type[MAXN], dp[MAXN];\n\nint main() {    \n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 1; i <= n; i++) {\n\t\tdouble x;\n\t\tscanf(\"%d %lf\", type+i, &x);\n\t}\n\t\n\tfor(int i = 1; i <= n; i++) {\n\t\tint j = type[i];\n\t\tfor(int k = j; k >= 1; k--) {\n\t\t\tdp[j] = max(dp[j], 1+dp[k]);\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\tfor(int i = 1; i <= n; i++) {\n\t\tans = max(ans, dp[i]);\n\t}\n\tprintf(\"%d\n\", n-ans);\n}",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "269",
    "index": "C",
    "title": "Flawed Flow",
    "statement": "Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of $n$ vertices and $m$ edges. Vertices are numbered from 1 to $n$. Vertices $1$ and $n$ being the source and the sink respectively.\n\nHowever, his max-flow algorithm seems to have a little flaw — it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow.\n\nMore formally. You are given an undirected graph. For each it's undirected edge ($a_{i}$, $b_{i}$) you are given the flow volume $c_{i}$. You should direct all edges in such way that the following conditions hold:\n\n- for each vertex $v$ $(1 < v < n)$, sum of $c_{i}$ of incoming edges is equal to the sum of $c_{i}$ of outcoming edges;\n- vertex with number $1$ has no incoming edges;\n- the obtained directed graph \\textbf{does not have cycles}.",
    "tutorial": "The key element to solving the task is the following observation: if we know all the incoming edges of a vertex, all the remaining edges must be outgoing. The source has no incoming edges, so we already know that all its edges are outgoing. For all other vertices except the sink the amount of incoming and outcoming flow is the same, and is equal to half of the sum of the flow along its incident edges. The algorithm then is to repeatedly direct all the flow from the vertices for which all the incoming edges are known. This can be done with a single BFS: for all v from 2 to n-1 f[v] := sum(flow(v,u))/2; put source in queue while queue is not empty v := pop(queue) for all edges (v, u) if (v, u) is not directed yet direct v -> u f[u] = f[u] - flow(v,u) if u not sink and f[u] = 0 push(queue, u)As the flow contains no cycles, we can sort the vertices topologically. Then we can be sure that, until all edge directions are known, we can put at least the first vertex with unknown edges in the queue, as all of its incoming edges will be from vertices with lower indices, but we took the first vertex with unknown edges. Time: $O(n + m)$ Memory: $O(n + m)$",
    "code": "#include <cstdio>\n#include <vector>\n#include <queue>\n#include <cstring>\n#include <iostream>\n\nusing namespace std;\n\n#define MAXN 200005\n#define pb push_back\n\nstruct edge {\n    int v, c, i, d;\n\tedge(int v, int c, int i, int d) : v(v), c(c), i(i), d(d) {}\n};\n\ntypedef vector<vector<edge> > graph;\n\nint n, m, d[MAXN], f[MAXN];\ngraph g;\n\nint main() {\n\tscanf(\"%d %d\", &n, &m);\n\tg = graph(n);\n\tfor(int i = 0; i < m; i++) {\n\t\tint a, b, c; scanf(\"%d %d %d\", &a, &b, &c);\n\t\ta--; b--;\n\t\tg[a].pb(edge(b,c,i,0));\n\t\tg[b].pb(edge(a,c,i,1));\n\t\tf[a] += c;\n\t\tf[b] += c;\n\t}\n\t\n\tfor(int i = 0; i < n; i++) {\n\t\tf[i] /= 2;\n\t}\n\t\n\tmemset(d, -1, sizeof(d));\n\tqueue<int> Q;\n\tQ.push(0);\n\twhile(!Q.empty()) {\n\t\tint u = Q.front(); Q.pop();\n\t\t\n\t\tfor(size_t i = 0; i < g[u].size(); i++) {\n\t\t\tint id = g[u][i].i;\n\t\t\tif(d[id] == -1) {\n\t\t\t\td[id] = g[u][i].d;\n\t\t\t\n\t\t\t\tint v = g[u][i].v;\n\t\t\t\tf[v] -= g[u][i].c;\n\t\t\t\tif(v != n-1 && f[v] == 0) {\n\t\t\t\t\tQ.push(v);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor(int i = 0; i < m; i++) {\n\t\tprintf(\"%d\n\", d[i]);\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "flows",
      "graphs",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "269",
    "index": "D",
    "title": "Maximum Waterfall",
    "statement": "Emuskald was hired to design an artificial waterfall according to the latest trends in landscape architecture. A modern artificial waterfall consists of multiple horizontal panels affixed to a wide flat wall. The water flows down the top of the wall from panel to panel until it reaches the bottom of the wall.\n\nThe wall has height $t$ and has $n$ panels on the wall. Each panel is a horizontal segment at height $h_{i}$ which begins at $l_{i}$ and ends at $r_{i}$. The $i$-th panel connects the points $(l_{i}, h_{i})$ and $(r_{i}, h_{i})$ of the plane. The top of the wall can be considered a panel connecting the points $( - 10^{9}, t)$ and $(10^{9}, t)$. Similarly, the bottom of the wall can be considered a panel connecting the points $( - 10^{9}, 0)$ and $(10^{9}, 0)$. No two panels share a common point.\n\nEmuskald knows that for the waterfall to be aesthetically pleasing, it can flow from panel $i$ to panel $j$ ($i\\rightarrow j\\,$) only if the following conditions hold:\n\n- $max(l_{i}, l_{j}) < min(r_{i}, r_{j})$ (horizontal projections of the panels overlap);\n- $h_{j} < h_{i}$ (panel $j$ is below panel $i$);\n- there is no such panel $k$ $(h_{j} < h_{k} < h_{i})$ that the first two conditions hold for the pairs $(i, k)$ and $(k, j)$.\n\nThen the \\textbf{flow} for $i\\rightarrow j\\,$ is equal to $min(r_{i}, r_{j}) - max(l_{i}, l_{j})$, the length of their horizontal projection overlap.\n\nEmuskald has decided that in his waterfall the water will flow in a single path from top to bottom. If water flows to a panel (except the bottom of the wall), the water will fall further to \\textbf{exactly one} lower panel. The total amount of water flow in the waterfall is then defined as the minimum horizontal projection overlap between two consecutive panels in the path of the waterfall. Formally:\n\n- the waterfall consists of a single path of panels $t o p\\to p_{1}\\to p_{2}\\to\\dots\\cdots b o t t o m$;\n- the flow of the waterfall is the minimum flow in the path $t o p\\to p_{1}\\to p_{2}\\to\\dots\\cdots b o t t o m$.\n\nTo make a truly great waterfall Emuskald must maximize this water flow, but there are too many panels and he is having a hard time planning his creation. Below is an example of a waterfall Emuskald wants:\n\nHelp Emuskald maintain his reputation and find the value of the maximum possible water flow.",
    "tutorial": "We will use a sweepline algorithm to solve this task. This horizontal sweepline runs from bottom to top, and holds the parts of the segments that are visible from the line this sweepline is currently at. Each part also holds the reference to its original segment. The sweepline itself is implemented with a binary search tree. The events of the sweep are the segments. When a new segment is found, we want to find all the lower segments that we can direct the flow onto from this segment. These can be only the original segments of the parts currently in the sweepline whose projections overlap with this segment. Then we iterate over all such parts $p$ (finding the first such part is an $O(\\log n)$ operation). How do we know that we can direct the flow onto $p$? Observe that if there is some segment that prevents this, there should be also a part $q$ in the sweepline that also can be seen from the current segment. And since the projections of all three segments overlap, this part can only be directly to the left or to the right of $p$ in the binary search tree. So we just check whether the original segments of the two parts next to $p$ prevent the flow from the current segment to the original segment of $p$. Afterwards, we remove all such parts from the sweepline, and insert a new part corresponding to the new segment. If the new segment only partially covered an existing part, we reinsert the remaining portion of that part. There are at most two such portions - one on each side of the segment. Thus each segment inserts at most 3 new parts and the size of the sweepline is $O(n)$. Each part is handled just once before removal, so the total time of such operations is $O(n \\log n)$. Once we know we can direct the flow through $a\\rightarrow b$ we can immediately update the maximum downwards flow of $a$: $f_{a} = max(f_{a}, min(f_{b}, min(r_{a}, r_{b}) - max(l_{a}, l_{b})))$When we reach the top, $f_{top}$ will be the answer. Time: $O(n \\log n)$ Memory: $O(n)$",
    "code": "#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <set>\n#include <algorithm>\n\nusing namespace std;\n\n#define MAXN 100005\n\nint inf = 2000000000;\n\nstruct segment {\n    int h, l, r;\n\tsegment(){}\n\tsegment(int h, int l, int r) : h(h), l(l), r(r) {}\n\tbool operator < (const segment &s) const {\n\t\treturn h < s.h;\n\t}\n};\n\nstruct part {\n\tint l, r, f;\n\tsegment s;\n\tpart(int l, int r, int f, segment s) : l(l), r(r), f(f), s(s) {}\n\tbool operator < (const part &p) const {\n\t\treturn l < p.l;\n\t}\n};\n\nset<part> sweep;\nsegment s[MAXN];\n\nint main()\n{\t\n\tint n, t; scanf(\"%d %d\", &n, &t);\n\tfor(int i = 0; i < n; i++) {\n\t\tint h, l, r; scanf(\"%d %d %d\", &h, &l, &r);\n\t\ts[i] = segment(h, l, r);\n\t}\n\ts[n] = segment(t, -inf, inf);\n\tsort(s, s+n);\n\t\n\tpart bottom(-inf, inf, inf, segment(0, -inf, inf));\n\tpart left(-inf-1, -inf, 0, segment(0, -inf-1, -inf));\n\tpart right(inf, inf+1, 0, segment(0, inf, inf+1));\n\tsweep.insert(bottom);\n\tsweep.insert(left);\n\tsweep.insert(right);\n\tfor(int i = 0; i <= n; i++) {\n\t\tint h = s[i].h, l = s[i].l, r = s[i].r;\n\t\t\n\t\tpart p(l, r, 0, s[i]);\n\t\tset<part>::iterator it = sweep.upper_bound(p), jt, kt;\n\t\tit--;\n\t\tjt = it;\n\t\tset<part>::iterator lt = jt, rt = jt;\n\t\tlt--;\n\t\trt++;\n\t\twhile(jt->l < r) {\n\t\t\tif(!(lt->s.r > max(jt->s.l, l) && jt->s.h < lt->s.h && lt->s.h < h) &&\n\t\t\t\t!(rt->s.l < min(jt->s.r, r) && jt->s.h < rt->s.h && rt->s.h < h)) {\n\t\t\t\tp.f = max(p.f, min(jt->f, min(jt->s.r, r)-max(jt->s.l, l)));\n\t\t\t}\n\t\t\tlt++;\n\t\t\tjt++;\n\t\t\trt++;\n\t\t}\n\t\t\n\t\tkt = jt; kt--;\n\t\tpart start = *it, end = *kt;\n\t\t\n\t\tsweep.erase(it, jt);\n\t\tif(start.l<l) {\n\t\t\tsweep.insert(part(start.l, l, start.f, start.s));\n\t\t}\n\t\tif(end.r>r) {\n\t\t\tsweep.insert(part(r, end.r, end.f, end.s));\n\t\t}\n\t\tsweep.insert(p);\n\t}\n\t\n\tset<part>::iterator it = sweep.begin();\n\tit++;\n\tprintf(\"%d\n\", it->f);\n}",
    "tags": [
      "data structures",
      "dp",
      "graphs",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "269",
    "index": "E",
    "title": "String Theory",
    "statement": "Emuskald is an innovative musician and always tries to push the boundaries of music production. Now he has come up with an idea for a revolutionary musical instrument — a rectangular harp.\n\nA rectangular harp is a rectangle $n × m$ consisting of $n$ rows and $m$ columns. The rows are numbered 1 to $n$ from top to bottom. Similarly the columns are numbered 1 to $m$ from left to right. String pins are spaced evenly across every side, one per unit. Thus there are $n$ pins on the left and right sides of the harp and $m$ pins on its top and bottom. The harp has exactly $n + m$ different strings, each string connecting two different pins, each on a different side of the harp.\n\nEmuskald has ordered his apprentice to construct the first ever rectangular harp. However, he didn't mention that no two strings can cross, otherwise it would be impossible to play the harp. Two strings cross if the segments connecting their pins intersect. To fix the harp, Emuskald can perform operations of two types:\n\n- pick two different columns and swap their pins on each side of the harp, not changing the pins that connect each string;\n- pick two different rows and swap their pins on each side of the harp, not changing the pins that connect each string;\n\nIn the following example, he can fix the harp by swapping two columns:\n\nHelp Emuskald complete his creation and find the permutations how the rows and columns of the harp need to be rearranged, or tell that it is impossible to do so. He can detach and reattach each string to its pins, so the physical layout of the strings doesn't matter.",
    "tutorial": "There are overall 6 types of segments that connect the sides: left-top; top-right; right-bottom; bottom-left; left-right; top-bottom; If there are both left-right and top-bottom segments, there is no solution. Otherwise there remain only 5 types of segments. Without loss of generality suppose there are no left-right segments. Let's take a closer look at what should the end picture of the rectangle be: All left-top segments should be at the left top corner connecting positions (L,i) and (T,i), otherwise they surely would cross some other segment. Similarly must be positioned top-right, right-bottom, bottom-left segments. Finally, all top-bottom segments should be parallel. We also observe that the number of left-top segments must be equal to the number of right-bottom segments and the number of top-right segments should be equal to the number of bottom-right segments. Thus the important observation: the picture of the end arrangement is unique and can be determined from the input simply by counting the number of segments of each type. Next we define a cycle to be the sequence of segments, where the second midpoint of some segment in the cycle is equal to the first midpoint in the next segment in the cycle. In the given example there are two such cycles (but the direction of each cycle actually matters): Then we observe that the set of the cycles does not change with any permutation by the definition of the cycle. We can make a sketch of the solution: we should find the cycle sets in the given arrangement and in the end arrangement, and compare them for equality. At this point we actually find all the cycles in both arrangements. There are only two types of cycles: (left-top) $\\to$ (top-right) $\\to$ (right-bottom) $\\to$ (bottom-left); other cycles. We can easily check whether the sets of first type cycles match, since the length of such cycles is 4. If they match, we rearrange the columns and rows involved to match the end arrangement. How to compare the remaining cycles. Consider a following example: Let the difference in the number of left-top and left-bottom segments be $i$, and this number plus the number of top-bottom segments $s$. If we enumerate the midpoints as in the figure, we can see that each top midpoint $k$ is connected to the bottom midpoint $k\\mod s+1$ (top-right segments continue as corresponding left-bottom segments). Thus we can describe it as a permutation $\\binom{1}{i+1}\\begin{array}{c c c}{{2}}&{{\\ddots\\ }}\\\\ {{i+1}}&{{i+2}}&{{\\ldots\\ }}\\end{array}$Our cycles correspond to the cycles in this permutation, with top-right segment continuation to left-bottom segment corresponding to the case where permutation cycle element decreases. It is known that the number of such permutations is $\\operatorname*{gcd}(s,i)$ and their length is $\\frac{}{\\sqrt{\\operatorname{cd}(s,i)}}$. So all these cycles have the same length. Denote the remaining segment types as some letters (in picture A, B, C). Then not only the length, but the strings describing the cycles are also the same, but can be shifted cyclically (here the direction of the cycles also is important). Besides, we know this string from the correct arrangement cycle. Thus we need to compare all the remaining given arrangement cycle strings to this string, considering cyclic shifts as invariant transformations. For each string this can be done in linear time, for example, using the Knuth-Morris-Pratt algorithm. When we find a cyclical shift for each cycle, we can position its relevant columns and rows according to the end arrangement. Time: $O(n + m)$. Memory: $O(n + m)$.",
    "code": "#include<cstdio>\n#include<iostream>\n#include<vector>\n#include<cstring>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef unsigned int ui;\ntypedef pair<int,int> pii;\n\n#define MAXN 1000005\n\nint n, m, cnt[4][4], id[128], GS[4][MAXN], GC[4][MAXN], IS[4][MAXN], IC[4][MAXN], colp[MAXN], rowp[MAXN], vis[4][MAXN], code[4][4], memC[MAXN], pi[3*MAXN], done[4][MAXN];\n\nstring small, large, cycle, text;\n\nint findShift(string &s, string &t) {\n    if(s.size() != t.size()) return -1;\n\ttext = s + \"#\" + t + t;\n\tint sz = s.size();\n\t\n\tint l = text.length();\n\tpi[0] = 0;\n\tfor (int i = 1; i < l; i++) {\n\t\tint j = pi[i-1];\n\t\twhile(j > 0 && text[i] != text[j]) {\n\t\t\tj = pi[j-1];\n\t\t}\n\t\tif(text[i] == text[j]) {\n\t\t\tj++;\n\t\t}\n\t\tpi[i] = j;\n\t}\n\t\n\tfor(int i = 2*sz; i < l; i++) {\n\t\tif(pi[i] == sz) {\n\t\t\treturn i-2*sz;\n\t\t}\n\t}\n\treturn -1;\n}\n\nint main() {\n\tfreopen(\"input.in\", \"r\", stdin);\n\t\n\tint L = id['L'] = 0;\n\tint T = id['T'] = 1;\n\tint R = id['R'] = 2;\n\tint B = id['B'] = 3;\n\t\n\tscanf(\"%d %d\n\", &n, &m);\n\tfor(int i = 0; i < n+m; i++) {\n\t\tchar a, b; int p, q;\n\t\tscanf(\"%c %c %d %d\n\", &a, &b, &p, &q);\n\t\ta = id[a];\n\t\tb = id[b];\n\t\tcnt[a][b]++;\n\t\tcnt[b][a]++;\n\t\tGS[a][p] = b;\n\t\tGC[a][p] = q;\n\t\tGS[b][q] = a;\n\t\tGC[b][q] = p;\n\t}\n\t\n\tif((cnt[T][B] && cnt[L][R]) || (cnt[L][T] != cnt[B][R])) {\n\t\tprintf(\"No solution\n\");\n\t\treturn 0;\n\t}\n\t\n\tint smallPtr[4];\n\tint d = min(cnt[L][T], cnt[L][B]);\n\tfor(int x = 1; x <= cnt[L][T]; x++) {\n\t\tIS[L][x] = T;\n\t\tIS[T][x] = L;\n\t\tIC[L][x] = x;\n\t\tIC[T][x] = x;\n\t\tsmallPtr[L] = 1;\n\t}\n\tfor(int x = 1; x <= cnt[T][R]; x++) {\n\t\tIS[T][m-x+1] = R;\n\t\tIS[R][x] = T;\n\t\tIC[T][m-x+1] = x;\n\t\tIC[R][x] = m-x+1;\n\t\tsmallPtr[T] = m-d+1;\n\t}\n\tfor(int x = 1; x <= cnt[R][B]; x++) {\n\t\tIS[R][n-x+1] = B;\n\t\tIS[B][m-x+1] = R;\n\t\tIC[R][n-x+1] = m-x+1;\n\t\tIC[B][m-x+1] = n-x+1;\n\t\tsmallPtr[R] = n-d+1;\n\t}\n\tfor(int x = 1; x <= cnt[B][L]; x++) {\n\t\tIS[B][x] = L;\n\t\tIS[L][n-x+1] = B;\n\t\tIC[B][x] = n-x+1;\n\t\tIC[L][n-x+1] = x;\n\t\tsmallPtr[B] = 1;\n\t}\n\tfor(int x = cnt[L][T]+1, y = cnt[T][R]+1; x <= cnt[L][T]+cnt[L][R]; x++, y++) {\n\t\tIS[L][x] = R;\n\t\tIS[R][y] = L;\n\t\tIC[L][x] = y;\n\t\tIC[R][y] = x;\n\t}\n\tfor(int x = cnt[L][T]+1, y = cnt[L][B]+1; x <= cnt[L][T]+cnt[T][B]; x++, y++) {\n\t\tIS[T][x] = B;\n\t\tIS[B][y] = T;\n\t\tIC[T][x] = y;\n\t\tIC[B][y] = x;\n\t}\n\t\n\tchar cd = 'A';\n\tfor(int i = 0; i < 4; i++) {\n\t\tfor(int j = 0; j < 4; j++) {\n\t\t\tcode[i][j] = cd++;\n\t\t}\n\t}\n\t\n\tint startS = -1, startC = d+1;\n\tif(cnt[L][R]) {\n\t\tstartS = L;\n\t} else if(cnt[T][B]) {\n\t\tstartS = T;\n\t} else if(cnt[L][T] != cnt[L][B]) {\n\t\tstartS = L;\n\t}\n\tif(startS != -1) {\n\t\tint currS = startS, currC = startC;\n\t\twhile(1) {\n\t\t\tint nextS = IS[currS][currC];\n\t\t\tint nextC = IC[currS][currC];\n\t\t\tlarge += code[currS][nextS];\n\t\t\tcurrS = (nextS+2)%4;\n\t\t\tcurrC = nextC;\n\t\t\tif(currS==startS && currC==startC) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(startS == -1) {\n\t\tstartS = 0;\n\t}\n\tfor(int i = 0; i < 4; i++) {\n\t\tint nextS = (startS+1)%4;\n\t\tsmall += code[startS][nextS];\n\t\tstartS = (nextS+2)%4;\n\t}\n\t\n\tif(d > 0) {\n\t\tint smallCnt = 0;\n\t\tfor(int x = 1; x <= (startS%2==0?n:m); x++) {\n\t\t\tif(!vis[startS][x] && code[startS][GS[startS][x]] == small[0]) {\n\t\t\t\tcycle = string();\n\t\t\t\tint currS = startS, currC = x;\n\t\t\t\tfor(int i = 0; ; i++) {\n\t\t\t\t\tvis[currS][currC] = true;\n\t\t\t\t\tmemC[i] = currC;\n\t\t\t\t\tint nextS = GS[currS][currC];\n\t\t\t\t\tint nextC = GC[currS][currC];\n\t\t\t\t\tcycle += code[currS][nextS];\n\t\t\t\t\tcurrS = (nextS+2)%4;\n\t\t\t\t\tcurrC = nextC;\n\t\t\t\t\tif(currS==startS && currC==x) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(cycle.length() == small.length()) {\n\t\t\t\t\tint p = findShift(small, cycle);\n\t\t\t\t\tif(p != -1) {\n\t\t\t\t\t\tsmallCnt++;\n\t\t\t\t\t\t\n\t\t\t\t\t\tcurrS = startS;\n\t\t\t\t\t\tcurrC = smallPtr[startS]++;\n\t\t\t\t\t\tfor(int j = p, k = 0; k < 4; j=(j+1)%4, k++) {\n\t\t\t\t\t\t\tif(currS%2==0) {\n\t\t\t\t\t\t\t\trowp[currC] = memC[j];\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcolp[currC] = memC[j];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdone[currS][memC[j]] = 1;\n\t\t\t\t\t\t\tint nextS = IS[currS][currC];\n\t\t\t\t\t\t\tint nextC = IC[currS][currC];\n\t\t\t\t\t\t\tcurrS = (nextS+2)%4;\n\t\t\t\t\t\t\tcurrC = nextC;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(smallCnt != d) {\n\t\t\tprintf(\"No solution\n\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\td = large.size()?(n+m-4*d)/large.size():0;\n\tif(d > 0) {\n\t\tint largeCnt = 0;\n\t\tmemset(vis, 0, sizeof(vis));\n\t\tfor(int x = 1; x <= (startS%2==0?n:m); x++) {\n\t\t\tif(!vis[startS][x] && !done[startS][x] && code[startS][GS[startS][x]] == large[0]) {\n\t\t\t\tcycle = string();\n\t\t\t\tint currS = startS, currC = x;\n\t\t\t\tfor(int i = 0; ; i++) {\n\t\t\t\t\tvis[currS][currC] = true;\n\t\t\t\t\tmemC[i] = currC;\n\t\t\t\t\tint nextS = GS[currS][currC];\n\t\t\t\t\tint nextC = GC[currS][currC];\n\t\t\t\t\tcycle += code[currS][nextS];\n\t\t\t\t\tcurrS = (nextS+2)%4;\n\t\t\t\t\tcurrC = nextC;\n\t\t\t\t\tif(currS==startS && currC==x) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(cycle.length() == large.length()) {\n\t\t\t\t\tint p = findShift(large, cycle);\n\t\t\t\t\tif(p != -1) {\n\t\t\t\t\t\tlargeCnt++;\n\t\t\t\t\t\t\n\t\t\t\t\t\tcurrS = startS;\n\t\t\t\t\t\tcurrC = startC++;\n\t\t\t\t\t\tint sz = large.size();\n\t\t\t\t\t\tfor(int j = p, k = 0; k < sz; j=(j+1)%sz, k++) {\n\t\t\t\t\t\t\tif(currS%2==0) {\n\t\t\t\t\t\t\t\trowp[currC] = memC[j];\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcolp[currC] = memC[j];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tint nextS = IS[currS][currC];\n\t\t\t\t\t\t\tint nextC = IC[currS][currC];\n\t\t\t\t\t\t\tcurrS = (nextS+2)%4;\n\t\t\t\t\t\t\tcurrC = nextC;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(largeCnt != d) {\n\t\t\tprintf(\"No solution\n\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tfor(int i = 1; i <= n; i++) {\n\t\tprintf(\"%d \", rowp[i]);\n\t}\n\tprintf(\"\n\");\n\tfor(int i = 1; i <= m; i++) {\n\t\tprintf(\"%d \", colp[i]);\n\t}\n\tprintf(\"\n\");\n}",
    "tags": [
      "geometry",
      "math",
      "strings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "270",
    "index": "A",
    "title": "Fancy Fence",
    "statement": "Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.\n\nHe wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle $a$.\n\nWill the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to $a$?",
    "tutorial": "Consider all supplementary angles of the regular $n$-polygon with angle $a$, which are equal to $180^\\circ - a$. Their sum is equal to $360^{\\circ}$, because the polygon is convex. Then the following equality holds: $n \\cdot (180 - a) = 360$, which means that there is an answer if and only if $360{\\mathrm{~~mod~}}(180-a)\\equiv0$. Time: $O(t)$. Memory: $O(1)$.",
    "code": "#include<iostream>\n#include<cstdio>\n \nusing namespace std;\n \nint main() {    \n\tint t; cin >> t;\n\tfor(int i = 0; i < t; i++) {\n\t\tint a; cin >> a;\n\t\tcout << (360 % (180-a) == 0 ? \"YES\" : \"NO\") << endl;\n\t}\n}",
    "tags": [
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "270",
    "index": "B",
    "title": "Multithreading",
    "statement": "Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the \"recent actions\" list. He likes to read thread conversations where each thread consists of multiple messages.\n\nRecent actions shows a list of $n$ different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.\n\nEmuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the $i$-th place in the list there is a thread that was at the $a_{i}$-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.\n\nHelp Emuskald find out the number of threads that \\textbf{surely} have new messages. A thread $x$ surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold:\n\n- thread $x$ is not updated (it has no new messages);\n- the list order 1, 2, ..., $n$ changes to $a_{1}$, $a_{2}$, ..., $a_{n}$.",
    "tutorial": "If some $a_{i}$ is greater than $a_{i + 1}$, it is clear that $a_{i}$ definitely contains a new message because the order of these two elements has changed. Let the last such element be $a_{k}$. Then all of the elements $a_{k + 1}$, $a_{k + 2}$, $...$, $a_{n}$ can contain no new messages, since their order has not changed. The answer to the problem is $n - k$. If there is no such $a_{k}$ the order hasn't changed at all and there may be no new messages. Time: $O(n)$. Memory: $O(n) / O(1)$.",
    "code": "#include<iostream>\n\nusing namespace std;\n\nint a[100005];\n\nint main() {\n    int n; cin >> n;\n\tfor(int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\tint i = n-1;\n\twhile(i > 0 && a[i-1] < a[i]) {\n\t\ti--;\n\t}\n\tcout << i << endl;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "271",
    "index": "A",
    "title": "Beautiful Year",
    "statement": "It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.\n\nNow you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.",
    "tutorial": "This is a very straight forward problem. Just add 1 to a year number while it still has equal digits.",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "271",
    "index": "B",
    "title": "Prime Matrix",
    "statement": "You've got an $n × m$ matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by $1$. Each element can be increased an arbitrary number of times.\n\nYou are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not.\n\nA matrix is prime if at least one of the two following conditions fulfills:\n\n- the matrix has a row with prime numbers only;\n- the matrix has a column with prime numbers only;\n\nYour task is to count the minimum number of moves needed to get a prime matrix from the one you've got.",
    "tutorial": "Precalculate the next prime for every integer from $1$ to $10^{5}$. You can do that in any way. The main thing is to test all the divisors up to square root when you are checking if a number is prime. Now for each $a_{ij}$ (element of the given matrix) we can easily calculate $add_{ij}$ - how many do we have to add in order to make $a_{ij}$ prime. After that all we need to do is to find row or column with minimal sum in this new matrix.",
    "tags": [
      "binary search",
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "271",
    "index": "C",
    "title": "Secret",
    "statement": "The Greatest Secret Ever consists of $n$ words, indexed by positive integers from $1$ to $n$. The secret needs dividing between $k$ Keepers (let's index them by positive integers from $1$ to $k$), the $i$-th Keeper gets a \\textbf{non-empty} set of words with numbers from the set $U_{i} = (u_{i, 1}, u_{i, 2}, ..., u_{i, |Ui|})$. Here and below we'll presuppose that the set elements are written in the increasing order.\n\nWe'll say that the secret is safe if the following conditions are hold:\n\n- for any two indexes $i, j$ ($1 ≤ i < j ≤ k$) the intersection of sets $U_{i}$ and $U_{j}$ is an empty set;\n- the union of sets $U_{1}, U_{2}, ..., U_{k}$ is set $(1, 2, ..., n)$;\n- in each set $U_{i}$, its elements $u_{i, 1}, u_{i, 2}, ..., u_{i, |Ui|}$ \\textbf{do not form} an arithmetic progression (in particular, $|U_{i}| ≥ 3$ should hold).\n\nLet us remind you that the elements of set $(u_{1}, u_{2}, ..., u_{s})$ form an arithmetic progression if there is such number $d$, that for all $i$ ($1 ≤ i < s$) fulfills $u_{i} + d = u_{i + 1}$. For example, the elements of sets $(5)$, $(1, 10)$ and $(1, 5, 9)$ form arithmetic progressions and the elements of sets $(1, 2, 4)$ and $(3, 6, 8)$ don't.\n\nYour task is to find any partition of the set of words into subsets $U_{1}, U_{2}, ..., U_{k}$ so that the secret is safe. Otherwise indicate that there's no such partition.",
    "tutorial": "If $3k > n$ there is no solution (because each of the $k$ sets must have at least 3 elements). Otherwise we can divide first $3k$ words in the following way: 1 1 2 2 3 3 ... k k 1 2 3 ... k For each of the $k$ sets, the difference between the first and the second elements will be $1$. And the difference between the second and the third elements is definitely not $1$ (more precisely, it is $2k - i - 1$ for the $i$-th set). So each set doesn't form an arithmetic progression for sure. For this solution it doesn't matter how we divide the rest $n - 3k$ words.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "271",
    "index": "D",
    "title": "Good Substrings",
    "statement": "You've got string $s$, consisting of small English letters. Some of the English letters are good, the rest are bad.\n\nA substring $s[l...r]$ ($1 ≤ l ≤ r ≤ |s|$) of string $s = s_{1}s_{2}...s_{|s|}$ (where $|s|$ is the length of string $s$) is string $ s_{l}s_{l + 1}...s_{r}$.\n\nThe substring $s[l...r]$ is good, if among the letters $ s_{l}, s_{l + 1}, ..., s_{r}$ there are \\textbf{at most} $k$ \\textbf{bad} ones (look at the sample's explanation to understand it more clear).\n\nYour task is to find the number of distinct good substrings of the given string $s$. Two substrings $s[x...y]$ and $s[p...q]$ are considered distinct if their content is different, i.e. $s[x...y] ≠ s[p...q]$.",
    "tutorial": "At first, build a trie containing all suffixes of given string (this structure is also called explicit suffix tree). Let's iterate over all substrings in order of indexes' increasing, i. e. first $[1...1],$ then $[1...2], [1...3], ..., [1...n], [2...2], [2...3], ..., [2...n], ...$ Note, that moving from a substring to the next one is just adding a single character to the end. So we can easily maintain the number of bad characters, and also the \"current\" node in the trie. If the number of bad characters doesn't exceed $k$, then the substring is good. And we need to mark the corresponding node of trie, if we never did this before. The answer will be the number of marked nodes in the trie. There is also an easier solution, where instead of trie we use Rabin-Karp rolling hash to count substrings that differ by content. Just sort the hashes of all good substrings and find the number of unique hashes (equal hashes will be on adjacent positions after sort). But these hashes are unreliable in general, so it's always better to use precise algorithm.",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "271",
    "index": "E",
    "title": "Three Horses",
    "statement": "There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with $a$ on the top and $b$ in the bottom as $(a, b)$.\n\nEach of the three horses can paint the special cards. If you show an $(a, b)$ card to the gray horse, then the horse can paint a new $(a + 1, b + 1)$ card. If you show an $(a, b)$ card, such that $a$ and $b$ are even integers, to the white horse, then the horse can paint a new $\\textstyle{{\\binom{a}{2}},{\\frac{b}{2}}}$ card. If you show two cards $(a, b)$ and $(b, c)$ to the gray-and-white horse, then he can paint a new $(a, c)$ card.\n\nPolycarpus really wants to get $n$ special cards $(1, a_{1})$, $(1, a_{2})$, $...$, $(1, a_{n})$. For that he is going to the horse land. He can take exactly one $(x, y)$ card to the horse land, such that $1 ≤ x < y ≤ m$. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards?\n\nPolycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires.",
    "tutorial": "It could be proved, that a card $(x, y)$ $(x < y)$ can be transformed to any card $(1, 1 + k \\cdot d)$, where $d$ is the maximal odd divisor of $y - x$, and $k$ is just any positive integer. So every $(a_{i} - 1)$ must be divisible by $d$, i. e. $d$ is a divisor of $gcd(a_{1} - 1, ..., a_{n} - 1)$, and we can just iterate over all possible divisors. Let's take a look at all the initial cards $(x, y)$, which have have $d$ as their maximal odd divisor: these are cards with $y - x$ equal to $d$, or $2d$, or $4d$, $8d$, $16d$, ... Don't forget that the numbers $x$ and $y$ must not exceed $m$. It means that the total number of cards with some fixed difference $t = y - x$ is exactly $m - t$. The resulting solution: sum up $(m - 2^{l}d)$, where $d$ is any odd divisor of $gcd(a_{1} - 1, ..., a_{n} - 1)$, and $l$ is such, that $2^{l}d  \\le  m$.",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "272",
    "index": "A",
    "title": "Dima and Friends",
    "statement": "Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.\n\nTo decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.\n\nFor example, if Dima and one of his friends played hide and seek, and $7$ fingers were shown during the counting-out, then Dima would clean the place. If there were $2$ or say, $8$ fingers shown, then his friend would clean the place.\n\nDima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.",
    "tutorial": "We will bruteforce number of fingers that will be show Dima, then if total sum of fingers = 1 modulo (n+1), Dima will clean the room. So we should increase answer if the remaining part after division by (n+1) is not 1.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "272",
    "index": "B",
    "title": "Dima and Sequence",
    "statement": "Dima got into number sequences. Now he's got sequence $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers. Also, Dima has got a function $f(x)$, which can be defined with the following recurrence:\n\n- $f(0) = 0$;\n- $f(2·x) = f(x)$;\n- $f(2·x + 1) = f(x) + 1$.\n\nDima wonders, how many pairs of indexes $(i, j)$ $(1 ≤ i < j ≤ n)$ are there, such that $f(a_{i}) = f(a_{j})$. Help him, count the number of such pairs.",
    "tutorial": "First of all - f(i) is number of ones in binary presentation of number. We will repair all numbers to functions of them. Now we have to find number of pairs of equal numbers. Lets Q[i] - number of numbers with i bits, the answer will be sum of values Q[i]*(Q[i]-1)/2 for all i.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "272",
    "index": "C",
    "title": "Dima and Staircase",
    "statement": "Dima's got a staircase that consists of $n$ stairs. The first stair is at height $a_{1}$, the second one is at $a_{2}$, the last one is at $a_{n}$ ($1 ≤ a_{1} ≤ a_{2} ≤ ... ≤ a_{n}$).\n\nDima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The $i$-th box has width $w_{i}$ and height $h_{i}$. Dima throws each box vertically down on the first $w_{i}$ stairs of the staircase, that is, the box covers stairs with numbers $1, 2, ..., w_{i}$. Each thrown box flies vertically down until at least one of the two following events happen:\n\n- the bottom of the box touches the top of a stair;\n- the bottom of the box touches the top of a box, thrown earlier.\n\nWe only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width $w_{i}$ cannot touch the stair number $w_{i} + 1$.\n\nYou are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.",
    "tutorial": "Lets L will be the answer after last block, last block was (w1, h1), next block is (w2, h2). Next answer will be max(L+h1, A[w2]), where A - given array. At the beggining we can suppose that L = 0, w1 = 0, h1 = 0.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "272",
    "index": "D",
    "title": "Dima and Two Sequences",
    "statement": "Little Dima has two sequences of points with integer coordinates: sequence $(a_{1}, 1), (a_{2}, 2), ..., (a_{n}, n)$ and sequence $(b_{1}, 1), (b_{2}, 2), ..., (b_{n}, n)$.\n\nNow Dima wants to count the number of distinct sequences of points of length $2·n$ that can be assembled from these sequences, such that the $x$-coordinates of points in the assembled sequence will \\textbf{not decrease}. Help him with that. Note that each element of the initial sequences should be used exactly once in the assembled sequence.\n\nDima considers two assembled sequences $(p_{1}, q_{1}), (p_{2}, q_{2}), ..., (p_{2·n}, q_{2·n})$ and $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{2·n}, y_{2·n})$ distinct, if there is such $i$ $(1 ≤ i ≤ 2·n)$, that $(p_{i}, q_{i}) ≠ (x_{i}, y_{i})$.\n\nAs the answer can be rather large, print the remainder from dividing the answer by number $m$.",
    "tutorial": "Not hard to understand that answer will be (number of numbers with first coordinate = 1)! * (number of numbers with first coordinate = 2)! * ... * (number of numbers with first coordinate = 10^9)!/(2^(number of such i = 1..n, that Ai=Bi)). The only problem was to divide number with non prime modulo, it can be easely done if we will count number of prime mulpiplies=2 in all factorials. Then we can simply substract number that we need and multiply answer for some power of 2.",
    "tags": [
      "combinatorics",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "272",
    "index": "E",
    "title": "Dima and Horses",
    "statement": "Dima came to the horse land. There are $n$ horses living in the land. Each horse in the horse land has several enemies (enmity is a symmetric relationship). The horse land isn't very hostile, so the number of enemies of each horse is at most 3.\n\nRight now the horse land is going through an election campaign. So the horses trusted Dima to split them into two parts. At that the horses want the following condition to hold: a horse shouldn't have more than one enemy in its party.\n\nHelp Dima split the horses into parties. Note that one of the parties can turn out to be empty.",
    "tutorial": "Not hard to understand that we have undirected graph. Lets color all vetexes in one color. Then we will find some vertex that is incorrect. We will change color of this vertex, and repeat our search, while it is possible. After every move number of bad edges will be decrease by 1 or 2, so our cycle will end in not more then M operations. So solutions always exists and we need to change some vertex not more then M times, so we will take queue of bad vertexes and simply make all operations of changes.",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "273",
    "index": "D",
    "title": "Dima and Figure",
    "statement": "Dima loves making pictures on a piece of squared paper. And yet more than that Dima loves the pictures that depict one of his favorite figures.\n\nA piece of squared paper of size $n × m$ is represented by a table, consisting of $n$ rows and $m$ columns. All squares are white on blank squared paper. Dima defines a picture as an image on a blank piece of paper, obtained by painting some squares black.\n\nThe picture portrays one of Dima's favorite figures, if the following conditions hold:\n\n- The picture contains at least one painted cell;\n- All painted cells form a connected set, that is, you can get from any painted cell to any other one (you can move from one cell to a side-adjacent one);\n- The minimum number of moves needed to go from the painted cell at coordinates $(x_{1}, y_{1})$ to the painted cell at coordinates $(x_{2}, y_{2})$, moving only through the colored cells, equals $|x_{1} - x_{2}| + |y_{1} - y_{2}|$.\n\nNow Dima is wondering: how many paintings are on an $n × m$ piece of paper, that depict one of his favorite figures? Count this number modulo $1000000007 (10^{9} + 7)$.",
    "tutorial": "Good picture is connected figure that saticfy next condition: most left coordinates in every row of figure vere we have some cells will be almost-ternary, we have the same situation with right side, but here we have another sign. So it is not hard to write dp[i][j1][j2][m1][m2] numbr of figures printed of field size i*m, where last row contain all cells from j1 to j2, the most left coordinate will be m1, the most right coordinate will be m2. But it is not enough. We have to rewrite it in way that m1 will mean - was there some rows j and j+1 that most left coordinate if row j is bigger then most left coordinate in j+1. So now it is not hard to write solution with coplexity O(n*m*m*m*m). But we should optimize transfer to O(1), is can be done using precalculations of sums on some rectangels.",
    "tags": [
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "274",
    "index": "A",
    "title": "k-Multiple Free Set",
    "statement": "A $k$-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by $k$. That is, there are no two integers $x$ and $y$ $(x < y)$ from the set, such that $y = x·k$.\n\nYou're given a set of $n$ distinct positive integers. Your task is to find the size of it's largest $k$-multiple free subset.",
    "tutorial": "Consider an integer $x$ which is divisible by $k$. At most one of the integers $x$ and $x / k$ can appear in the maximum $k$-multiple free subset. Also for any integer $y$ at most one of the numbers $y$ and $yk$ appears in the answer. If you look like this you can see the input as chains of numbers so that for each chain no two adjacent elements can appear in the output. For example, If $k = 2$ then $6, 12, 24, 48, 96$ forms a chain. It's easy to see that from a chain of length $l$ we can choose at most $(l + 1) / 2$ elements in the answer. So the solution would be to compute the lengths of the chains and pick as much numbers as we can from each chain. You can sort all the numbers and do binary search or similar things to find the length of chains. Here's a cute greedy solution which picks numbers greedily from the chains: First sort all the numbers. Also consider an empty set of integers $S$, which represents the output. For each integer $x$ in the sequence, If it's not divisible by $k$, just pick it and insert it into $S$. Otherwise if it's divisible by $k$ check if $x / k$ is in $S$ or not. If it's not in $S$ insert $x$ into $S$ otherwise skip $x$. I'd also like to note that this problem comes from an old problem in UVa Online Judge, with the same the name.",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "274",
    "index": "B",
    "title": "Zero Tree",
    "statement": "A tree is a graph with $n$ vertices and exactly $n - 1$ edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.\n\nA subtree of a tree $T$ is a tree with both vertices and edges as subsets of vertices and edges of $T$.\n\nYou're given a tree with $n$ vertices. Consider its vertices numbered with integers from 1 to $n$. Additionally an integer is written on every vertex of this tree. Initially the integer written on the $i$-th vertex is equal to $v_{i}$. In one move you can apply the following operation:\n\n- Select the subtree of the given tree that includes the vertex with number 1.\n- Increase (or decrease) by one all the integers which are written on the vertices of that subtree.\n\nCalculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.",
    "tutorial": "In the problem statement vertex $1$ is not mentioned as root of the tree. But it seems if we make it the root of the tree we can figure out the solution easier. For the leaves of the tree we can see the least number of steps needed to make each of them equal to zero. Consider a vertex which all its children are leaves. The minimum number of times that we should increase this vertex is at least as the maximum times one of the children of this vertex is increased. Also the minimum number of times this vertex is decreased is at least as maximum times one of the children of this vertex is decreased. Now we know some necessary plus or minus steps that this vertex is included in them. So after all of the children of this vertex reached zero, this vertex itself has some new value. If the current value of the vertex is positive we should decrease this vertex certain times otherwise we should decrease it. So we can find the minimum number of times this vertex should be decreased and the minimum number of times this vertex should be increased. As we showed above if we know these pair of numbers for each child of a vertex then we can calculate these numbers for that vertex too. This can be implemented using a simple DFS on the rooted tree. And the answer to the problem would be the sum of increments and decrements of vertex $1$. The time complexity of the solution is $O(n)$.",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "274",
    "index": "C",
    "title": "The Last Hole!",
    "statement": "Luyi has $n$ circles on the plane. The $i$-th circle is centered at $(x_{i}, y_{i})$. At the time zero circles start to grow simultaneously. In other words, the radius of each circle at time $t (t > 0)$ is equal to $t$. The circles are drawn as black discs on an infinite white plane. So at each moment the plane consists of several black and white regions. Note that the circles may overlap while growing.\n\nWe define a \\underline{hole} as a closed, connected white region. For instance, the figure contains two holes shown by red border. During growing some holes may be created and it is easy to see that each created hole will disappear eventually. Luyi asks you to find moment of time such that the last hole disappears. In other words, you should find the first moment such that no hole can be seen after that.",
    "tutorial": "In the solution we will try to find the position of all points which are the last moments in holes. Here we claim that each minimal potential hole is one of these two forms: For each three centers that form an acute triangle it's obvious that they form a potential hole. The last point in this hole would be the in triangle's circumcenter. For each four centers which are sides of a square it's also obvious there's a potential hole with last point being the square's center. For each potential hole we should check if the last point is not covered with any other circle in the last moment. The solution would be the hole with maximum distance from the centers which won't be covered by anything else. Let's remind some geometry facts. We know that circumcenter of a triangle is the point where the three perpendicular bisectors of the triangle meet. Also the circumcenter of the triangle lies inside the triangle if and only if the triangle is acute. Circumcenter is the point which has equal distance from each vertex of the triangle. Using above information it's easy to prove that three circles make a hole if and only if the triangle they form is acute. Now what remains is to prove that in the last moment which the hole is disappearing there are 3 triangles or four forming a square enclosing the hole. I'm not going into details but the proof would be like this. Consider the last point of a hole. There are some circles which form the border of the hole in the last moment. These centers have the same distance from the last point. We need to prove that only three of the centers or four of them which form a square do the same job. And all others can be ignored. Consider the circle which these centers lie on its perimeter. Here's a way to pick at most four of these points which make that hole. As long as there are three consecutive points which form make a obtuse triangle delete the middle point (why?). It's easy to see what will remain at the end is either a square or an acute triangle. The implementation can be done in $O(n^{4})$ with iterating through all triangles in $O(n^{3})$ and checking them in $O(n)$. Also there are at most $O(n^{3})$ squares, because once you've picked three of its vertices the fourth will be unique.",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "274",
    "index": "D",
    "title": "Lovely Matrix",
    "statement": "Lenny had an $n × m$ matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely.\n\nOne day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix.\n\nHelp him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers.",
    "tutorial": "The naive solution for this problem would be to make a graph were each vertex represents a column of the grid. Then for each two not erased integers $x$ and $y$ in the same row where $x < y$ we can add an edge from the column of $x$ to the column of $y$ in our graph. Then topological sorting on the built graph would give us the sought order of the rows. But there can be as much as O(m^2) edges in our graph and thus a $O(nm^{2})$ solution won't pass the time limit. But still the idea to solve this problem is to implement topological sort in a such way that the graph we make has less edges or to make less processing to find the topological sort. Here I present two solutions which use topological sorting. One implements topological sorting explicitly in a graph of columns as its vertices with some extra vertices but fewer edges. The other one does some kind of topological sorting without building the graph and by deciding which column can come as the first column of our ordering, and doing the same thing until all columns come in order. The first solution relies on decreasing the number of edges we used in the graph of our naive solution. Consider the numbers of a row sorted. We insert an extra vertex between each pair of adjacent different numbers. Then each column gets connected to the next extra vertex and each extra vertex gets connected to the columns before the next extra vertex. In this way the sorted order of this row would be preserved in topological sorting. We do the same thing for each row, so topological sort on the final graph would give us the sought ordering of columns. This can be implemented in $O(nmlgm)$. In the second solution for each row we color all the minimum not erased elements of that row. The first column in the output permutation should be a column where all of its non erased elements are colored. So we put this column as the first column. Now the rest of the columns can be ordered by the same way. If at some point we can't find a suitable column then there's no solution. This also can be implemented in $O(nmlgm)$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "274",
    "index": "E",
    "title": "Mirror Room",
    "statement": "Imagine an $n × m$ grid with some blocked cells. The top left cell in the grid has coordinates $(1, 1)$ and the bottom right cell has coordinates $(n, m)$. There are $k$ blocked cells in the grid and others are empty. You flash a laser beam from the center of an empty cell $(x_{s}, y_{s})$ in one of the diagonal directions (i.e. north-east, north-west, south-east or south-west). If the beam hits a blocked cell or the border of the grid it will reflect. The behavior of the beam reflection in different situations is depicted in the figure below.\n\nAfter a while the beam enters an infinite cycle. Count the number of empty cells that the beam goes through at least once. We consider that the beam goes through cell if it goes through its center.",
    "tutorial": "The blocked cells can make lots of complicated patterns. So it's obvious that the solution in includes simulating the path the laser beam goes. But the dimensions of the gird are large and the beam might travel a long path before entering a loop. So naive simulation will surely time out (See note!). It's kind of obvious that the beam finally comes back to its initial position and direction. Here were going to prove that the maximum number of times the beam might reflect until it reaches its first state is $O(n + m + k)$. Consider an empty grid, It has $O(n + m)$ maximal empty diagonal segments. When we block a cell, the two diagonal segments which pass this cell split. So the number of maximal empty diagonal segments increases by two. There for there are $O(n + m + k)$ of these segments. Also If you look at the behavior of the beam it passes some of the segments one after another. So if you simulate the beam, it reflects $O(n + m + k)$ times. Instead of naive simulation we can find the next position the beam reflects. Now we're going to prove that no cell will be visited twice. A cell gets visited twice in the cycle if we pass it in both NE-SW direction and NW-SE direction. Consider the grid colored in black and white like a chessboard. There are two types of diagonal segments the NE-SW ones and NW-SE ones (property 1). At each reflection we alternate between these two. Also there are two types of segments in another way, black segments and white segments (property 2). As you can see each time one of the properties changes the other one also changes. As a result we'll never pass a black cell in both directions, and the same is for a white cell. So this problem can be solved with simulation in $O((n + m + k)lgk)$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 3000
  },
  {
    "contest_id": "275",
    "index": "A",
    "title": "Lights Out",
    "statement": "Lenny is playing a game on a $3 × 3$ grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.\n\nLenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.",
    "tutorial": "For each light you should count the number of times it's been toggled. Consider a light is toggled $k$ times. If $k$ is even then the final state of the light is 'on' otherwise it's 'off'. The implementation would be easy. You may look at the accepted solutions as reference.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "275",
    "index": "B",
    "title": "Convex Shape",
    "statement": "Consider an $n × m$ grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid \\underline{convex} if one can walk from \\textbf{any} black cell to \\textbf{any another} black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.\n\nYou're given a painted grid in the input. Tell Lenny if the grid is convex or not.",
    "tutorial": "Consider a pair of black cells. There exist at most two different valid paths we can take between these two cells. The naive solution would be to check the existence of at least one of these paths for each pair of black cells. There are $O(n^{2}m^{2})$ such pairs and each pair can be checked in $O(n + m)$. So the time complexity will be $O(n^{2}m^{2}(n + m))$ which is enough to get accepted. But there exists a $O(nm)$ approach. It's obvious that each row of the grid either doesn't have any black cell or the black cells are a consecutive part of the row. The same holds for every column. For every non-empty row consider the interval of its black cells. The intersection of intervals of all non-empty rows should be non-empty. If the same holds for all columns then our grid is convex. The proof of this solution is not hard and is left for the reader.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "276",
    "index": "A",
    "title": "Lunch Rush",
    "statement": "Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly $k$ time units for the lunch break.\n\nThe Rabbits have a list of $n$ restaurants to lunch in: the $i$-th restaurant is characterized by two integers $f_{i}$ and $t_{i}$. Value $t_{i}$ shows the time the Rabbits need to lunch in the $i$-th restaurant. If time $t_{i}$ exceeds the time $k$ that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal $f_{i} - (t_{i} - k)$. Otherwise, the Rabbits get exactly $f_{i}$ units of joy.\n\nYour task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose \\textbf{exactly} one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.",
    "tutorial": "Let's look at all restraunts, where Rabbits can have their lunch. Let's calculate the answer for all restraunts and choose the maximulm value among of them. We need to use formula descrbed in problem statement to calculate the answer for some particular restraunt. Time complexity of this solution is $O(N)$.",
    "code": "#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <memory.h>\n#include <ctime>\n \nusing namespace std;\n \n#define ABS(a) ((a>0)?a:-(a))\n#define MIN(a,b) ((a<b)?(a):(b))\n#define MAX(a,b) ((a<b)?(b):(a))\n#define FOR(i,a,n) for (int i=(a);i<(n);++i)\n#define FI(i,n) for (int i=0; i<(n); ++i)\n#define pnt pair <int, int>\n#define mp make_pair\n#define PI 3.14159265358979\n#define MEMS(a,b) memset(a,b,sizeof(a))\n#define LL long long\n#define U unsigned\n \n \nint main()\n{\n#ifdef Fcdkbear\n    freopen(\"in.txt\",\"r\",stdin);\n    //freopen(\"out.txt\",\"w\",stdout);\n    double beg=clock();\n#endif\n    \n    int res=-2000000000;\n    int n,T;\n    scanf(\"%d%d\",&n,&T);\n    FOR(i,0,n)\n    {\n        int f,t;\n        scanf(\"%d%d\",&f,&t);\n        int cur=f;\n        if (t>T)\n            cur-=(t-T);\n        res=MAX(res,cur);\n    }\n    cout<<res<<endl;\n#ifdef Fcdkbear\n    double end=clock();\n    fprintf(stderr,\"*** Total time = %.3lf ***\n\",(end-beg)/CLOCKS_PER_SEC);\n#endif\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "276",
    "index": "B",
    "title": "Little Girl and Game",
    "statement": "The Little Girl loves problems on games very much. Here's one of them.\n\nTwo players have got a string $s$, consisting of lowercase English letters. They play a game that is described by the following rules:\n\n- The players move in turns; In one move the player can remove an arbitrary letter from string $s$.\n- If the player before his turn can reorder the letters in string $s$ so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string \"abba\" is a palindrome and string \"abc\" isn't.\n\nDetermine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.",
    "tutorial": "Let's calculate the number of letters with odd number of occurrences in $s$. Let this value be equal to $k$. If $k = 0$, then first player can win immediately: he can easily build palindrome, placing equal letters in different sides of resulting string (he always can do it, because total number of all letters is even). If $k = 1$ then first player can win immediately again; at first he builds palindrome from letters with even number of occurrences in $s$; after that he inserts the rest of the letters in the middle of built in previous step string. Let's proof very useful statement. If $k > 1$ our problem has the following solution: if $k$ is even, than second player is winner; otherwise, first player is winner. Let $k = 2$. At the beginning of the game first player can make move of two types. Using move of first type first player can decrease $k$ to $1$ by erasing one appearance of letter with odd number of occurrences. But this move leads him to defeat, because after this move second player can build palindrome. Using move of second type first player can increase $k$ to $3$ by erasing one appearance of letter with even number of occurrences. In this case second player can make similar move - he will erase the same letter. Since the number of moves of this type is finite, sooner or later first player will have to make a move of first type. After this move he loses immediately. So, if $k = 2$, than second player is a winner. Let $k = 3$. First player can decrease $k$ to $2$ by erasing the letter with odd number of occurrences. If second player will try to increase $k$ to $3$ again by erasing the similar letter, first player can decrease $k$ to $2$ again (he erases the same letter again). It's easy to see that the last move in this sequence of moves will be the move of first player. So, first player always can change the game in such a way that $k = 2$. This position is losing position for second player and winning position for first player. Now we can easily proof our statement for any $k$ using mathematical induction. So, we have quite easy solution with time complexity $O(|S|)$.",
    "code": "#include <iostream>\n#include <string>\n#include <string.h>\n \nusing namespace std;\nstring s;\nint cnt[30];\nint main()\n{\n   \n        cin>>s;\n        for (int i=0; i<s.size(); ++i)\n                cnt[s[i]-'a']++;\n        int odd=0;\n        for (int i=0; i<26; ++i)\n                if (cnt[i]&1)\n                        odd++;\n        if ((odd==0) || (odd&1))\n                cout<<\"First\"<<endl;\n        else\n                cout<<\"Second\"<<endl;\n    return 0;\n}",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "276",
    "index": "C",
    "title": "Little Girl and Maximum Sum",
    "statement": "The little girl loves the problems on array queries very much.\n\nOne day she came across a rather well-known problem: you've got an array of $n$ elements (the elements of the array are indexed starting from 1); also, there are $q$ queries, each one is defined by a pair of integers $l_i$, $r_i$ $(1 \\le l_i \\le r_i \\le n)$. You need to find for each query the sum of elements of the array with indexes from $l_i$ to $r_i$, inclusive.\n\nThe little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.",
    "tutorial": "Lets calculate for each cell of the initial array the number of queries that cover this cell. It's claimed, that we should associate the cell with bigger value to the cell with bigger value in initial array. More formally: suppose $b$ is an array, in $i - th$ cell of which is written the number of queries that cover $i - th$ cell. Suppose $a$ is an initial array. Let's sort those arrays. It's claimed, that the answer in this case can be calculated with following formula: $\\textstyle\\sum_{i=1}^{n}a[i]\\cdot b[i]$ Let's proof this statements. We will take a look at some indexes $i < j$, and at elements, corresponding to shis indexes $a[i]$, $a[j]$ , $b[i]$, $b[j]$ $(a[i]  \\le  a[j], b[i]  \\le  b[j])$. Those elements add to the answer the following value: $a[i] \\cdot b[i] + a[j] \\cdot b[j]$. Let's swap $a[i]$ and $a[j]$. Now those elements elements add to the answer the following value $a[i] \\cdot b[j] + a[j] \\cdot b[i]$. Let's take a look at the following difference: $a[i] \\cdot b[j] + a[j] \\cdot b[i] - a[i] \\cdot b[i] - a[j] \\cdot b[j] = b[j] \\cdot (a[i] - a[j]) + b[i] \\cdot (a[j] - a[i]) = (b[j] - b[i]) \\cdot (a[i] - a[j])  \\le  0$. So, swapping of two elements leads us to nonincreasing of the total result. This means, that our arrangement is optimal. Now we need to calculate array $b$ fast enough. For this purpose one can use different data structures, which support segment modifications (segment tree, Cartesian tree and so on). But there exists much easier method. Let's create some array $d$. When we have query $l_{i}$, $r_{i}$, we should increase value $d[l_{i}]$ by $1$ and decrease value $d[r_{i} + 1]$ by $1$. In such a tricky way we increase all elements in segment $[l_{i};r_{i}]$ by $1$ After processing all of the queries we need to make a loop, which visit every element of array $d$. In this loop we can easily calculate all elements of array $b$. Now we are ready to get the final answer. The complexity of author's solution is $O(NlogN + Q)$",
    "code": "#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <memory.h>\n#include <ctime>\n \nusing namespace std;\n \n#define ABS(a) ((a>0)?a:-(a))\n#define MIN(a,b) ((a<b)?(a):(b))\n#define MAX(a,b) ((a<b)?(b):(a))\n#define FOR(i,a,n) for (int i=(a);i<(n);++i)\n#define FI(i,n) for (int i=0; i<(n); ++i)\n#define pnt pair <int, int>\n#define mp make_pair\n#define PI 3.14159265358979\n#define MEMS(a,b) memset(a,b,sizeof(a))\n#define LL long long\n#define U unsigned\n \nint a[200100];\nint val[200100];\nint b[200100];\nint main()\n{\n    int n,q;\n    scanf(\"%d%d\",&n,&q);\n    FOR(i,0,n)\n        scanf(\"%d\",&a[i]);\n    sort(a,a+n);\n    FOR(i,0,q)\n    {\n        int l,r;\n        scanf(\"%d%d\",&l,&r);\n        l--;\n        r--;\n        val[l]++;\n        if (r<n-1)\n            val[r+1]--;\n    }\n    int v=0;\n    FOR(i,0,n)\n    {\n        v+=val[i];\n        b[i]=v;\n    }\n    sort(b,b+n);\n    LL res=0;\n    FOR(i,0,n)\n        res+=(b[i]*1ll*a[i]);\n    cout<<res<<endl;\n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "276",
    "index": "D",
    "title": "Little Girl and Maximum XOR",
    "statement": "A little girl loves problems on bitwise operations very much. Here's one of them.\n\nYou are given two integers $l$ and $r$. Let's consider the values of $a\\oplus b$ for all pairs of integers $a$ and $b$ $(l ≤ a ≤ b ≤ r)$. Your task is to find the maximum value among all considered ones.\n\nExpression $x\\oplus y$ means applying bitwise excluding or operation to integers $x$ and $y$. The given operation exists in all modern programming languages, for example, in languages $C$++ and $Java$ it is represented as \"^\", in $Pascal$ — as \"xor\".",
    "tutorial": "To be honest, I am surprised that problem D had so many accepted solution during the contest. The author's solution uses dynamic programming. In this editorial I'll explain this solution. First of all we should convert $L$ and $R$ to the binary numeral system. Now we can solve our problem with dynamic programming, using the following state $d[p][fl1][fr1][fl2][fr2]$, where $p$ is current position in binary representation of our numbers $a$ and $b$ (this parameter is in range from $0$ to number of bits in $R$), $fl$ ($0$ or $1$) is a variable, which shows if current value of $a$ is strictly greater than $L$, $fr1$ (from $0$ to $1$) is a variable, which shows if current value of $a$ is strictly less then $R$, $fl2$, $fr2$ are variables, which show the similar things for $b$. Let's use recursion with memorization for our solution. Let's define the base of recursion. If we have looked through all the bits, we should return $0$. Let's define a recursive transition. We need to know, which bits we can place into binary representation of number $a$ in $p$-th position. We can place $0$ if the following condition is true: $p$-th bit of $L$ is equal to $0$, or $p$-th bit of $L$ is equal to $1$ and variable $fl1$ shows that current value of $a$ is strictly greater then $L$. Similarly, we can place $1$ if the following condition is true: $p$-th bit of $R$ is equal to $1$, or $p$-th bit of $R$ is equal to $0$ and variable $fr1$ shows that current value of $a$ is strictly less then $R$. Similarly, we can obtain, which bits we can place into binary representation of number $b$ in $p$-th position. Let's iterate through all possible bits' values and check the result of xor operation. If it is equal to $1$, we should add to the answer corresponding power of $2$. We also need carefully recalculate values of variables $fl1$, $fr1$, $fl2$, $fr2$. We should choose maximum answer from all valid options. Initial state for our recursion is ($P$,$0$,$0$,$0$,$0$), where $P$ is number of bits in $R$. I hope, my code will clarify all the obscure points. I also want to say, that this approach is in some sense universal and can be applied to many similar problems, like this one The complexity of algorithm is $O(logR)$",
    "code": "#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <stack>\n#include <queue>\n#include <algorithm>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <memory.h>\n#include <ctime>\n \nusing namespace std;\n \n#define ABS(a) ((a>0)?a:-(a))\n#define MIN(a,b) ((a<b)?(a):(b))\n#define MAX(a,b) ((a<b)?(b):(a))\n#define FOR(i,a,n) for (int i=(a);i<(n);++i)\n#define FI(i,n) for (int i=0; i<(n); ++i)\n#define pnt pair <int, int>\n#define mp make_pair\n#define PI 3.14159265358979\n#define MEMS(a,b) memset(a,b,sizeof(a))\n#define LL long long\n#define U unsigned\n \nLL solveStupid(LL l, LL r)\n{\n    LL res=0;\n    for (LL i=l; i<=r; ++i)\n        for (LL j=i; j<=r; ++j)\n            res=max(res,i^j);\n    return res;\n}\nstring s1,s2;\nLL dp[70][2][2][2][2];\n \nLL rec(int p, int fl1, int fl2, int fr1, int fr2)\n{\n    if (p==s1.size())\n        return 0;\n    if (dp[p][fl1][fl2][fr1][fr2]!=-1)\n        return dp[p][fl1][fl2][fr1][fr2];\n    int min1=0,max1=1;\n    if ((fl1==0) && (s1[p]=='1'))\n        min1=1;\n    if ((fl2==0) && (s2[p]=='0'))\n        max1=0;\n    int min2=0,max2=1;\n    if ((fr1==0) && (s1[p]=='1'))\n        min2=1;\n    if ((fr2==0) && (s2[p]=='0'))\n        max2=0;\n    LL res=0;\n    FOR(i,min1,max1+1)\n        FOR(j,min2,max2+1)\n        {\n            int v=(i^j);\n            LL toadd=0;\n            if (v==1)\n            {\n                int step=s1.size()-p-1;\n                toadd=(1ll<<step);\n            }\n            int nfl1=fl1,nfl2=fl2,nfr1=fr1,nfr2=fr2;\n            if (i>s1[p]-'0')\n                nfl1=1;\n            if (i<s2[p]-'0')\n                nfl2=1;\n            if (j>s1[p]-'0')\n                nfr1=1;\n            if (j<s2[p]-'0')\n                nfr2=1;\n            res=max(res,toadd+rec(p+1,nfl1,nfl2,nfr1,nfr2));\n        }\n    return dp[p][fl1][fl2][fr1][fr2]=res;\n}\nstring getbin(LL num)\n{\n    string res=\"\";\n    while (num)\n    {\n        res+=((num&1)+'0');\n        num/=2;\n    }\n    reverse(res.begin(),res.end());\n    return res;\n}\nLL solveSmart(LL l, LL r)\n{\n    s1=getbin(l);\n    s2=getbin(r);\n    while (s1.size()<s2.size())\n        s1=\"0\"+s1;\n    MEMS(dp,-1);\n    LL res=rec(0,0,0,0,0);\n    return res;\n}\nint main()\n{\n#ifdef Fcdkbear\n    freopen(\"in.txt\",\"r\",stdin);\n    //freopen(\"out.txt\",\"w\",stdout);\n    double beg=clock();\n#endif\n   LL l,r;\n   cin>>l>>r;\n   cout<<solveSmart(l,r)<<endl;\n \n#ifdef Fcdkbear\n    double end=clock();\n    fprintf(stderr,\"*** Total time = %.3lf ***\n\",(end-beg)/CLOCKS_PER_SEC);\n#endif\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "276",
    "index": "E",
    "title": "Little Girl and Problem on Trees",
    "statement": "A little girl loves problems on trees very much. Here's one of them.\n\nA tree is an undirected connected graph, not containing cycles. The degree of node $x$ in the tree is the number of nodes $y$ of the tree, such that each of them is connected with node $x$ by some edge of the tree.\n\nLet's consider a tree that consists of $n$ nodes. We'll consider the tree's nodes indexed from 1 to $n$. The cosidered tree has the following property: each node except for node number 1 has the degree of at most 2.\n\nInitially, each node of the tree contains number 0. Your task is to quickly process the requests of two types:\n\n- Request of form: $0$ $v$ $x$ $d$. In reply to the request you should add $x$ to all numbers that are written in the nodes that are located at the distance of at most $d$ from node $v$. The distance between two nodes is the number of edges on the shortest path between them.\n- Request of form: $1$ $v$. In reply to the request you should print the current number that is written in node $v$.",
    "tutorial": "One can see, that our tree is a set of chains, each of which starts in the root. First of all we need to decompose our tree in chains using, for example, depth first search. For each vertex we should find out it's depth and number of chain, which contain this vertex. For each chain we'll use some data structure, which can fast enough change it's elements and fast enough answer to the range sum query. For example, we canuse Binary Indexed Tree (BIT). We also need to create one BIT for root. This BIT is global: it's information is actual for all the chains Let's remember problem $C$. In that problem we used array $d$ for processing all the queries. We need to know values of elements of array $b$ in that problem after processing all the queries. In this problem queries are online. That's why we need to use BIT; it allows to change element and answer range sum query in $O(logN)$ time. Let's learn, how to process queries, which require modification and queries, which require finding the element, using BIT. BIT can make two types of operations: $add(x, y)$ - add value $y$ to element with index $x$ $find(x)$ - finds sum in range from $1$ to $x$ Let's consider, that we need to add value $val$ to all elements in range from $l$ to $r$ . Than we should just make operations $add(l, val)$ and $add(r + 1, - val)$. Let's consider, that we have query which require printing the value of element with index $v$. Then we should just make operation $find(v)$. Now let's go back to the initial problem. During the processing query of type $0$ we should check, if it affects the root. If query affects the root, we should carefully process this query in our chain and make necessary changes in root's BIT. Otherwise we just process query in our chain. During the processing query of type $1$ we should just find corresponding sums in root's BIT and in BIT for our chain. We should print the sum of this values. Time complexity of this solution is $O(N + QlogN)$",
    "code": "#include <iostream>\n#include <string>\n#include <string.h>\n#include <cstdlib>\n#include <set>\n#include <map>\n#include <vector>\n#include <algorithm>\n#include <iomanip>\n#include <sstream>\n#include <memory.h>\n#include <stdio.h>\n#include <ctime>\n#include <cmath>\n \n \nusing namespace std;\n \n \nchar ch_ch_ch[1<<20];\ninline int gi() {int a; scanf(\"%d\",&a); return a;}\ninline string gs() {scanf(\"%s\",ch_ch_ch); return string(ch_ch_ch);}\ninline string gl() {gets(ch_ch_ch); return string(ch_ch_ch);}\nconst int inf = 2000000000;\n \n#define LL long long\n#define U unsigned\n#define pnt pair<int,int>\n#define FOR(i,a,b) for (int i=(a); i<(b); ++i)\n#define MEMS(a,b) memset((a),(b),sizeof(a))\n#define MAX(a,b) ((a)>(b)?(a):(b))\n#define MIN(a,b) ((a)<(b)?(a):(b))\n#define ABS(a) (((a)>=(0))?(a):(-(a)))\n#define mp make_pair\n#define pb push_back\n#define ALL(a) a.begin(),a.end()\n#define FI(i,b) FOR(i,0,b)\n#define V(t) vector < t > \n#define sz size()\n \nvector<vector<int> > g;\nint inTree[100100];\nint depth[100100];\nvector<vector<int> > t;\nvoid dfs(int v, int d, int num, int p)\n{\n    inTree[v]=num;\n    depth[v]=d;\n    t[num].push_back(0);\n    FOR(i,0,g[v].size())\n    {\n        int to=g[v][i];\n        if (to==p)\n            continue;\n        dfs(g[v][i],d+1,num,v);\n    }\n}\nvoid add(int p, int v, int num)\n{\n    for (int i=p; i<t[num].size(); i+=(i&(-i)))\n        t[num][i]+=v;\n}\nint find(int p, int num)\n{\n    int res=0;\n    for (int i=p; i>0; i-=(i&(-i)))\n        res+=t[num][i];\n    return res;\n}\nint main()\n{\n#ifdef Fcdkbear\n    double beg=clock();\n    freopen(\"in.txt\",\"r\",stdin);\n#endif\n \n    int n,q;\n    scanf(\"%d%d\",&n,&q);\n    g.resize(n);\n    FOR(i,0,n-1)\n    {\n        int v1,v2;\n        scanf(\"%d%d\",&v1,&v2);\n        v1--;\n        v2--;\n        g[v1].push_back(v2);\n        g[v2].push_back(v1);\n    }\n    t.resize(g[0].size()+1);\n    int inRoot=0;\n    FOR(i,0,g[0].size())\n    {\n        t[i].push_back(0);\n        dfs(g[0][i],1,i,0);\n    }\n    t[t.size()-1].resize(n+10);\n    FOR(i,0,q)\n    {\n        int ty;\n        scanf(\"%d\",&ty);\n        if (ty==0)\n        {\n            int v,val,dist;\n            scanf(\"%d%d%d\",&v,&val,&dist);\n            v--;\n            if (v==0)\n            {\n                inRoot+=val;\n                add(1,val,t.size()-1);\n                add(dist+1,-val,t.size()-1);\n            }\n            else\n            {\n                if (dist>=depth[v])\n                {\n                    int left=dist-depth[v];\n                    inRoot+=val;\n                    add(1,val,t.size()-1);\n                    add(left+1,-val,t.size()-1);\n                    add(left+1,val,inTree[v]);\n                    add(depth[v]+dist+1,-val,inTree[v]);\n                }\n                else\n                {\n                    add(depth[v]-dist,val,inTree[v]);\n                    add(depth[v]+dist+1,-val,inTree[v]);\n                }\n            }\n        }\n        else\n        {\n            int v;\n            scanf(\"%d\",&v);\n            v--;\n            if (v==0)\n                printf(\"%d\n\",inRoot);\n            else\n            {\n                int res=find(depth[v],inTree[v])+find(depth[v],t.size()-1);\n                printf(\"%d\n\",res);\n            }\n        }\n    }\n#ifdef Fcdkbear\n    double end=clock();\n    fprintf(stderr,\"*** Time = %.3lf ***\n\",(end-beg)/CLOCKS_PER_SEC);\n#endif\n    return 0;\n}",
    "tags": [
      "data structures",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "277",
    "index": "A",
    "title": "Learning Languages",
    "statement": "The \"BerCorp\" company has got $n$ employees. These employees can use $m$ approved official languages for the formal correspondence. The languages are numbered with integers from $1$ to $m$. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs $1$ berdollar.\n\nFind the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).",
    "tutorial": "Build bipartite graph with $n$ nodes for employees and $m$ nodes for languages. If an employee initially knows a language, than there will be an edge between corresponding nodes. Now the problem is simple: add the minimal number of edges in such a way, that all the $n$ employees will be in the same connected component. Obviously, this number equals to the number of initially connected components, containing at least one employee, minus one. But there is one exception (pretest #4): if initially everyone knows no languages, we'll have to add $n$ edges, because we can't add the edges between employees (remember that the graph is bipartite).",
    "tags": [
      "dfs and similar",
      "dsu"
    ],
    "rating": 1400
  },
  {
    "contest_id": "277",
    "index": "B",
    "title": "Set of Points",
    "statement": "Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of $n$ points with the convexity of exactly $m$. Your set of points should not contain three points that lie on a straight line.",
    "tutorial": "For $m = 3, n = 5$ and $m = 3, n = 6$ there is no solution. Let's learn how to construct the solution for $n = 2m$, where $m  \\ge  5$ and is odd. Set up $m$ points on a circle of sufficiently large radius. This will be the inner polygon. The outer polygon will be the inner polygon multiplied by 2. More precisely ($1  \\le  i  \\le  m$): $x_{i}=r o u n d(10^{7}*c o s(\\frac{2\\pi}{m}i))$ $y_{i}=r o u n d(10^{7}*s i n({\\frac{2\\pi}{m}}i))$ $x_{i+m}=2\\cdot r o u n d(10^{7}*c o s(\\frac{2\\pi}{m}i))$ $y_{i+m}=2\\cdot r o u n d(10^{7}*s i n({\\frac{2\\pi}{m}}i))$ If $m$ is even, construct the solution for $m + 1$ and then delete one point from each polygon. If $n < 2m$, delete $2m - n$ points from the inner polygon. Unfortunately, this solution doesn't work for $m = 4, n = 7$ and $m = 4, n = 8$. Another approach is to set up $m$ points on a convex function (for example, $y = x^{2} + 10^{7}$), and set up the rest $n - m$ points on a concave function (for example, $y = - x^{2} - 10^{7}$).",
    "tags": [
      "constructive algorithms",
      "geometry"
    ],
    "rating": 2300
  },
  {
    "contest_id": "277",
    "index": "C",
    "title": "Game",
    "statement": "Two players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid line (not necessarily from border to border). The part of the paper, that touches the knife at least once, is considered cut. There is one limit not to turn the game into an infinite cycle: each move has to cut the paper, that is the knife has to touch the part of the paper that is not cut before.\n\nObviously, the game ends when the entire sheet is cut into $1 × 1$ blocks. During the game, the pieces of the sheet are not allowed to move. It is also prohibited to cut along the border. The coordinates of the ends of each cut must be integers.\n\nYou are given an $n × m$ piece of paper, somebody has already made $k$ cuts there. Your task is to determine who will win if the players start to play on this sheet. You can consider that both players play optimally well. If the first player wins, you also need to find the winning first move.",
    "tutorial": "At first, notice that horizontal and vertical cuts are independent. Consider a single horizontal line. It contains $m$ unit segments. And in any game state it's always possible to decrease the number of uncut units as the player wants. Imagine, that she starts growing a segment from a border, increasing it's length by 1 at a time. Each time the total uncut length decreases by either 0 or 1. In the end it obviously reaches 0. The same holds for vertical lines as well. So if there are no initial cuts, the game is a nim with $n - 1$ piles of $m$ stones and $m - 1$ piles of $n$ stones. Could be solved with simple formula. Initial $k$ cuts should be just a technical difficulty. For any vertical/horizontal line, which contains at least one of the cuts, it's pile size should be decreased by the total length of all segments on this line. How to make a first move in nim: let $res$ is the result of state (grundy function), and $a_{i}$ is the size of the $i$-th pile. Then the result of the game without $i$-th pile is $res \\oplus a_i$. We want to replace $a_{i}$ with some $x$, so that $r e s\\oplus a_{i}\\oplus x=0$. Obviously, the only possible $x=r e s\\oplus a_{i}$. The resulting solution: find a pile for which $(r e s\\oplus a_{i})<a_{i}$, and decrease it downto $res \\oplus a_i$.",
    "tags": [
      "games",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "277",
    "index": "D",
    "title": "Google Code Jam",
    "statement": "Many of you must be familiar with the Google Code Jam round rules. Let us remind you of some key moments that are crucial to solving this problem. During the round, the participants are suggested to solve several problems, each divided into two subproblems: an easy one with small limits (Small input), and a hard one with large limits (Large input). You can submit a solution for Large input only after you've solved the Small input for this problem. There are no other restrictions on the order of solving inputs. In particular, the participant can first solve the Small input, then switch to another problem, and then return to the Large input. Solving each input gives the participant some number of points (usually different for each problem). This takes into account only complete solutions that work correctly on all tests of the input. The participant gets the test result of a Small input right after he submits it, but the test result of a Large input are out only after the round's over. In the final results table the participants are sorted by non-increasing of received points. If the points are equal, the participants are sorted by ascending of time penalty. By the Google Code Jam rules the time penalty is the \\textbf{time when the last correct solution was submitted}.\n\nVasya decided to check out a new tactics on another round. As soon as the round begins, the boy quickly read all the problems and accurately evaluated the time it takes to solve them. Specifically, for each one of the $n$ problems Vasya knows five values:\n\n- Solving the Small input of the $i$-th problem gives to the participant $scoreSmall_{i}$ points, and solving the Large input gives $scoreLarge_{i}$ more points. That is, the maximum number of points you can get for the $i$-th problem equals $scoreSmall_{i} + scoreLarge_{i}$.\n- Writing the solution for the Small input of the $i$-th problem takes exactly $timeSmall_{i}$ minutes for Vasya. Improving this code and turning it into the solution of the Large input takes another $timeLarge_{i}$ minutes.\n- Vasya's had much practice, so he solves all Small inputs from the first attempt. But it's not so easy with the Large input: there is the $probFail_{i}$ probability that the solution to the Large input will turn out to be wrong at the end of the round. Please keep in mind that these solutions do not affect the participants' points and the time penalty.\n\nA round lasts for $t$ minutes. The time for reading problems and submitting solutions can be considered to equal zero. Vasya is allowed to submit a solution exactly at the moment when the round ends.\n\nVasya wants to choose a set of inputs and the order of their solution so as to make the expectation of the total received points maximum possible. If there are multiple ways to do this, he needs to minimize the expectation of the time penalty. Help Vasya to cope with this problem.",
    "tutorial": "Suppose we have fixed set of inputs that we have to solve. Let's learn how to determine the optimal order. Obviously, Small inputs (and Large inputs with $probFail = 0$) won't fail in any case. It means that our penalty time is no less than submission time of last such ``safe'' inputs. So we will solve such inputs before all the others. Inputs with $probFail = 1$ are just a waste of time, we won't solve such inputs. Now we have only inputs with $0 < probFail < 1$. Let $i$ and $j$ be two problems that we are going to solve consecutively at some moment. Let's check, if it is optimal to solve them in order $i$, $j$, or in reversed order. We can discard all the other inputs, because they don't affect on the relative order of these two. $(timeLarge_{i} + timeLarge_{j})(1 - probFail_{j}) + timeLarge_{i}(1 - probFail_{i})probFail_{j} < (timeLarge_{i} + timeLarge_{j})(1 - probFail_{i}) + timeLarge_{j}(1 - probFail_{j})probFail_{i}$ $- probFail_{j} \\cdot timeLarge_{j} - timeLarge_{i} \\cdot probFail_{j} \\cdot probFail_{i} < - probFail_{i} \\cdot timeLarge_{i} - timeLarge_{j} \\cdot probFail_{i} \\cdot probFail_{j}$ $timeLarge_{i} \\cdot probFail_{i}(1 - probFail_{j}) < timeLarge_{j} \\cdot probFail_{j}(1 - probFail_{i})$ $timeLarge_{i} \\cdot probFail_{i} / (1 - probFail_{i}) < timeLarge_{j} \\cdot probFail_{j} / (1 - probFail_{j})$ Now we've got a comparator for sort, which will give us the optimal order. Note, that inputs with $probFail = 0, 1$ will be sorted by the comparator correctly as well, so it's not a corner case. Let's return to the initial problem. First of all, sort problems with the optimal comparator (it's clear that any other order won't be optimal by time, and the score doesn't depend on the order). Calculate the DP: $z[i][j]$ = pair of maximal expected total score and minimal expected penalty time with this score, if we've already decided what to do with the first $i$ problems, and we've spent $j$ real minutes from the contest's start. There are 3 options for the $i$-the problem: skip: update $z[i + 1][j]$ with the same expected values solve the Small input: update $z[i + 1][j + timeSmall_{i}]$, the expected total score increases by $scoreSmall_{i}$, and the expected penalty time increases by $timeSmall_{i}$ (we assume that this input is solved in the very beggining of the contest) solve both inputs: update $z[i + 1][j + timeSmall_{i} + timeLarge_{i}]$, the expected total score increases by $scoreSmall_{i} + (1 - probFail_{i})scoreLarge_{i}$, and the expected penalty time becomes $timeSmall_{i} + (1 - probFail_{i})(j + timeLarge_{i}) + probFail_{i} \\cdot penaltyTime(z[i][j])$, where $penaltyTime(z[i][j])$ is the expected penalty time from DP The resulting answer is the best of $z[n][i], (0  \\le  i  \\le  t)$. The expected total score could be a number around $10^{12}$ with 6 digits after decimal point. So it can't be precisely stored in double. And any (even small) error in calculating score may lead to completely wrong expected time (pretest #7). For example, you can multiply all the probabilities by $10^{6}$ and store the expected score as integer number to avoid this error.",
    "tags": [
      "dp",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "277",
    "index": "E",
    "title": "Binary Tree on Plane",
    "statement": "A root tree is a directed acyclic graph that contains one node (root), from which there is exactly one path to any other node.\n\nA root tree is binary if each node has at most two outgoing arcs.\n\nWhen a binary tree is painted on the plane, all arcs should be directed from top to bottom. That is, each arc going from $u$ to $v$ must meet the condition $y_{u} > y_{v}$.\n\nYou've been given the coordinates of all tree nodes. Your task is to connect these nodes by arcs so as to get the binary root tree and make the total length of the arcs minimum. All arcs of the built tree must be directed from top to bottom.",
    "tutorial": "If there is no \"binary\" restriction, the solution is simple greedy. Each node of the tree (except the root) must have exactly 1 parent, and each node could be parent for any number of nodes. Let's assign for each node $i$ (except the root) such a node $p_{i}$ as a parent, so that $y_{pi} > y_{i}$ and distance between $i$ and $p_{i}$ is minimal possible. Renumerate all the nodes in order of non-increasing of $y$. Now it's clear that $p_{i} < i$ ($2  \\le  i  \\le  n$). So we've just built a directed tree with all the arcs going downwards. And it has minimal possible length. Let's recall the \"binary\" restriction. And realize that it doesn't really change anything: greedy transforms to min-cost-max-flow on the same distance matrix as edge's costs, but each node must have no more than 2 incoming flow units.",
    "tags": [
      "flows",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "278",
    "index": "B",
    "title": "New Problem",
    "statement": "Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title \\underline{original} if it doesn't occur as a substring in any titles of recent Codeforces problems.\n\nYou've got the titles of $n$ last problems — the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.\n\nA substring $s[l... r]$ $(1 ≤ l ≤ r ≤ |s|)$ of string $s = s_{1}s_{2}... s_{|s|}$ (where $|s|$ is the length of string $s$) is string $s_{l}s_{l + 1}... s_{r}$.\n\nString $x = x_{1}x_{2}... x_{p}$ is lexicographically smaller than string $y = y_{1}y_{2}... y_{q}$, if either $p < q$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{p} = y_{p}$, or there exists such number $r$ $(r < p, r < q)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} < y_{r + 1}$. The string characters are compared by their ASCII codes.",
    "tutorial": "The total number of different strings of 2 letters is $26^{2} = 676$, but the total length of the input strings is no more than $600$. It means that the length of answer is no more than 2. So just check all the strings of length 1 and 2.",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "279",
    "index": "A",
    "title": "Point on Spiral",
    "statement": "Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: \\textbf{$[(0, 0), (1, 0)]$, $[(1, 0), (1, 1)]$, $[(1, 1), ( - 1, 1)]$, $[( - 1, 1), ( - 1, - 1)]$, $[( - 1, - 1), (2, - 1)]$, $[(2, - 1), (2, 2)]$} and so on. Thus, this infinite spiral passes through each integer point of the plane.\n\nValera the horse lives on the plane at coordinates $(0, 0)$. He wants to walk along the spiral to point $(x, y)$. Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point $(0, 0)$ to point $(x, y)$.",
    "tutorial": "Since constraints are small, you can just simulate the whole process, but I'll explain an $O(1)$ solution. Let's look at the path Now it's easy to see that the plane can be divided into four parts And then we can calculate answer for each part separately, just be careful with borders. For example, for the right part the answer is $4x - 3$.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nint main() {\n    int x, y;\n    cin >> x >> y;\n    if (x == 0 && y == 0) {\n        cout << 0 << '\\n';\n    } else if (-x + 1 < y && y <= x) {\n        cout << 1 + (x - 1) * 4 << '\\n';\n    } else if (-y <= x && x < y) {\n        cout << 2 + (y - 1) * 4 << '\\n';\n    } else if (x <= y && y < -x) {\n        cout << 3 + (-x - 1) * 4 << '\\n';\n    } else {\n        cout << 4 + (-y - 1) * 4 << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "geometry",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "279",
    "index": "B",
    "title": "Books",
    "statement": "When Valera has got some free time, he goes to the library to read some books. Today he's got $t$ free minutes to read. That's why Valera took $n$ books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to $n$. Valera needs $a_{i}$ minutes to read the $i$-th book.\n\nValera decided to choose an arbitrary book with number $i$ and read the books one by one, starting from this book. In other words, he will first read book number $i$, then book number $i + 1$, then book number $i + 2$ and so on. He continues the process until he either runs out of the free time or finishes reading the $n$-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.\n\nPrint the maximum number of books Valera can read.",
    "tutorial": "The problem can be written in the following way: for each index $i$ denote $r_i$ as the largest index such that $a_i + \\ldots + a_{r_i} \\leqslant t$. The problem is to find $max(r_i - i + 1)$. One can see that $r_i$ are nondecreasing, so the problem can be solved with two pointers: iterate over $i$ and keep a pointer to corresponding $r_i$.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nint main() {\n    int n, t;\n    cin >> n >> t;\n    vector<int> a(n);\n    for (int& k : a)\n        cin >> k;\n\n    int r = 0;\n    int sm = 0;\n    int ans = 0;\n    for (int i = 0; i < n; ++i) {\n        while (r < n && sm + a[r] <= t) {\n            sm += a[r];\n            ++r;\n        }\n        ans = max(ans, r - i);\n        sm -= a[i];\n    }\n\n    cout << ans << '\\n';\n\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "implementation",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "279",
    "index": "C",
    "title": "Ladder",
    "statement": "You've got an array, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Also, you've got $m$ queries, the $i$-th query is described by two integers $l_{i}, r_{i}$. Numbers $l_{i}, r_{i}$ define a subsegment of the original array, that is, the sequence of numbers $a_{li}, a_{li + 1}, a_{li + 2}, ..., a_{ri}$. For each query you should check whether the corresponding segment is a ladder.\n\nA ladder is a sequence of integers $b_{1}, b_{2}, ..., b_{k}$, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer $x$ $(1 ≤ x ≤ k)$, that the following inequation fulfills: $b_{1} ≤ b_{2} ≤ ... ≤ b_{x} ≥ b_{x + 1} ≥ b_{x + 2}... ≥ b_{k}$. Note that the non-decreasing and the non-increasing sequences are also considered ladders.",
    "tutorial": "Let's calculate two arrays before answering queries. $tol[i]$ is the smallest index such that $[b_{tol[i]},\\, \\ldots,\\, b_{i}]$ is nonincreasing, and $tor[i]$ is the largest index such that $[b_{i},\\, \\ldots,\\, b_{tor[i]}]$ is nondecreasing. Then for each query we can take $tor[l]$ and $tol[r]$ and compare them. The answer is \"Yes\" iff $tor[l] \\geqslant tol[r]$. In other words, we are checking if the largest nondecreasing segment from $l$ and largest nonincreasing segment from $r$ are intersecting. To calculate $tol[i]$, go over $i$ from $1$ to $n$ and maintain largest nonincreasing suffix. For $tor$ do the same in reverse.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n);\n    for (int& k : a)\n        cin >> k;\n\n    vector<int> tor(n), tol(n);\n    iota(tol.begin(), tol.end(), 0);\n    iota(tor.begin(), tor.end(), 0);\n\n    tol[0] = 0;\n    for (int i = 1; i < n; ++i)\n        if (a[i - 1] >= a[i])\n            tol[i] = tol[i - 1];\n\n    tor[n - 1] = n - 1;\n    for (int i = n - 2; i >= 0; --i)\n        if (a[i] <= a[i + 1])\n            tor[i] = tor[i + 1];\n\n    while (m--) {\n        int l, r;\n        cin >> l >> r;\n        --l; --r;\n        cout << (tol[r] <= tor[l] ? \"Yes\" : \"No\") << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "279",
    "index": "D",
    "title": "The Minimum Number of Variables",
    "statement": "You've got a positive integer sequence $a_{1}, a_{2}, ..., a_{n}$. All numbers in the sequence are distinct. Let's fix the set of variables $b_{1}, b_{2}, ..., b_{m}$. Initially each variable $b_{i}$ $(1 ≤ i ≤ m)$ contains the value of zero. Consider the following sequence, consisting of $n$ operations.\n\nThe first operation is assigning the value of $a_{1}$ to some variable $b_{x}$ $(1 ≤ x ≤ m)$. Each of the following $n - 1$ operations is assigning to some variable $b_{y}$ the value that is equal to the sum of values that are stored in the variables $b_{i}$ and $b_{j}$ $(1 ≤ i, j, y ≤ m)$. At that, the value that is assigned on the $t$-th operation, must equal $a_{t}$. For each operation numbers $y, i, j$ are chosen anew.\n\nYour task is to find the minimum number of variables $m$, such that those variables can help you perform the described sequence of operations.",
    "tutorial": "You can notice that when we want to perform some operation, we are only interested in a subset of current values of variables (including zeros). So let's create $dp[i][mask] = bool$, which is $1$ if we can perform first $i$ operations and end up with the values from $mask$. Here $k$-bit in the mask corresponds to the value $vals[k]$, where array $vals$ stores all numbers in $a$ and a zero, and $k$-th bit is set iff the value of one of the variables is $vals[k]$. To make transition from $dp[i][mask]$ to $dp[i + 1][new\\_mask]$, let's look at the operation. We have to find two values in the $mask$ such that their sum is $a[i + 1]$. Then to calculate $new\\_mask$ we have to set $k$-th bit in the $mask$, where $k$ is such that $vals[k] = a[i + 1]$. Also, while writing new variable we can overwrite any existing variable, so we have an option to disable any bit in the $mask$. Now it looks like we have $O(2^nn)$ states and $n$ transitions from each state (disabling each bit). But actually if we only make transition from $dp[i][mask] = 1$, the complexity will be $O(2^nn)$, because for each $i$ there are at most $2^{i+1}$ masks that we can achieve, since there are only $i$ distinct numbers on the current prefix plus an additional zero. And $\\sum_{i=1}^n 2^{i+1}\\cdot n = O(2^nn)$. The only problem left is to check if we can build some number $y$ from $vals$ using numbers from $mask$. This can be precomputed in $O(2^nn)$: let's calculate array $possible[mask] = x$, where $i$-th bit in $x$ is set iff we can get number $vals[i]$ from mask on the next step. To calculate it, first for each $mask$ with at most $2$ bits just calculate all possible $x$ with any straightforward approach, since there are only $O(n^2)$ such masks. For any other mask notice that we can get $y$ iff sum of some two values equals to $y$. So we can iterate over all submasks such that they differ from $mask$ in exactly one bit and update $possible[mask]$ with $possible[submask]$. And since $mask$ has at least $3$ bits, if there is a pair which sums up to $y$, this pair will be included into at least one of the submasks. One can even notice that we only need any $3$ such submasks to cover every pair of bits. The answer is minimum number of bits over all masks such that $dp[n][mask] = 1$.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nint main() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int& k : a)\n        cin >> k;\n\n    auto vals = a;\n    vals.push_back(0);\n    sort(vals.begin(), vals.end());\n    vals.erase(unique(vals.begin(), vals.end()), vals.end());\n\n    vector<int> pos(n);\n    for (int i = 0; i < n; ++i) {\n        pos[i] = lower_bound(vals.begin(), vals.end(), a[i]) - vals.begin();\n    }\n\n    vector<int> possible(1 << vals.size(), 0);\n    for (int i = 1; i < possible.size(); ++i) {\n        int k = 0;\n        for (int j = 0; j < vals.size() && k < 3; ++j) {\n            if ((i >> j) & 1) {\n                possible[i] |= possible[i ^ (1 << j)];\n                ++k;\n            }\n        }\n        if (__builtin_popcount(i) <= 2) {\n            for (int j = 0; j < vals.size(); ++j) {\n                if (!((i >> j) & 1)) continue;\n                for (int k = 0; k < vals.size(); ++k) {\n                    if (!((i >> k) & 1)) continue;\n                    int val = vals[j] + vals[k];\n                    int ind = lower_bound(vals.begin(), vals.end(), val) - vals.begin();\n                    if (ind < vals.size() && vals[ind] == val)\n                        possible[i] |= (1 << ind);\n                }\n            }\n        }\n    }\n\n    vector<char> dp_cur(1 << vals.size(), 0);\n    dp_cur[1 << pos[0]] = 1;\n    dp_cur[(1 << pos[0]) | (1 << 0)] = 1;\n\n    auto can_sum = [&](int mask, int pos) {\n        return (possible[mask] >> pos) & 1;\n    };\n\n    vector<char> dp_next;\n    for (int i = 1; i < n; ++i) {\n        dp_next.assign(dp_cur.size(), false);\n        for (int j = 0; j < dp_cur.size(); ++j) {\n            if (dp_cur[j] && can_sum(j, pos[i])) {\n                int mask = j;\n                mask |= (1 << pos[i]);\n                dp_next[mask] = 1;\n                for (int k = 0; k < vals.size(); ++k)\n                    if (((mask >> k) & 1) && vals[k] != a[i])\n                        dp_next[mask ^ (1 << k)] = 1;\n            }\n        }\n        swap(dp_cur, dp_next);\n    }\n\n    int ans = -1;\n    for (int i = 0; i < dp_cur.size(); ++i) {\n        if (!dp_cur[i]) continue;\n        int sz = __builtin_popcount(i);\n        if (ans == -1 || ans > sz)\n            ans = sz;\n    }\n    cout << ans << '\\n';\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "279",
    "index": "E",
    "title": "Beautiful Decomposition",
    "statement": "Valera considers a number beautiful, if it equals $2^{k}$ or -$2^{k}$ for some integer $k$ $(k ≥ 0)$. Recently, the math teacher asked Valera to represent number $n$ as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible.\n\nHelp Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number $n$ into beautiful summands, you need to find the size of the decomposition which has the fewest summands.",
    "tutorial": "First of all it's easy to notice that we will use each power of $2$ at most once. Let's look at the highest bit in the current number, suppose it's $2^k$. Since the sum of all powers of $2$ below $k$ is less than $2^k$, we will have to add at least one power of two $2^x$ with $x \\geqslant k$. One can see that adding $2^{k+2}$ is not optimal, since then we will have to subtract at least $2^{k+1}$ and $2^{k+2} - 2^{k+1}$ can be replaced with $2^{k+1}$. So the only choices are $2^k$ or $2^{k+1}$. If we add $2^k$, we have to solve a problem for remaining number, which is a suffix or our current binary string. Otherwise, $2^{k+1}$ is larger than our current number, so we just need the answer for $m = 2^{k+1} - n$. Let's call such $m$ a complement for a number $n$ (notice that we don't need $k$ in the definition because $k$ is defined as largest bit in $n$) Now let's look at $m$. To calculate it, we have to flip all bits in $n$ and add $1$ to the result. Now it's easy to see that if $m$ is a complement for $n$, then for any suffix of $n$ (in binary form), the corresponding suffix of $m$ is a complement for it. Also, $n$ is a complement for $m$. So during our calculations we will only deal with $n$, $m$, suffixes of $n$ and suffixes of $m$. And this leads to a following dp solution: let $v[1] = n$, $v[2] = m$. Then $dp[ind][suf]$ is the smallest answer for a binary number represented by a suffix of number $v[ind]$ starting from index $suf$. We can calculate this $dp$ starting from $dp[\\ldots][n]$ and the answer will be $dp[1][1]$.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nint main() {\n    string n;\n    cin >> n;\n    string m = n;\n    {\n        for (char& c : m) {\n            c ^= '1' ^ '0';\n        }\n        int ind = m.size() - 1;\n        while (ind >= 0 && m[ind] == '1') {\n            m[ind] = '0';\n            --ind;\n        }\n        if (ind == -1) {\n            m.insert(m.begin(), '1');\n            n.insert(n.begin(), '0');\n        } else {\n            m[ind] = '1';\n        }\n    }\n\n    int sz = n.size();\n\n    vector<string> v = {n, m};\n    vector<array<int, 2>> dp(sz);\n\n    dp[sz - 1][0] = (v[0].back() == '1');\n    dp[sz - 1][1] = (v[1].back() == '1');\n\n    for (int i = sz - 2; i >= 0; --i) {\n        for (int b = 0; b < 2; ++b) {\n            if (v[b][i] == '0') {\n                dp[i][b] = dp[i + 1][b];\n            } else {\n                dp[i][b] = min(dp[i + 1][b] + 1, dp[i + 1][b ^ 1] + 1);\n            }\n        }\n    }\n\n    cout << dp[0][0] << '\\n';\n\n    return 0;\n}",
    "tags": [
      "dp",
      "games",
      "greedy",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "280",
    "index": "A",
    "title": "Rectangle Puzzle",
    "statement": "You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the $Ox$ axis, equals $w$, the length of the side that is parallel to the $Oy$ axis, equals $h$. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle $α$.\n\nYour task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.",
    "tutorial": "It may always be a good idea to try a simplified version before the situation gets into complicated. In this problem, a simplified version you might to be noticed is the square case. So here it is. you can easily see the area can be calculated by $$S - 4 \\times T$$ Here S is the area of the large square, and T is the area of those ambient triangles. In the rectangle situation, however, things will turn out to be more complex. But if you come back to the problem after draw some pictures, you can found there are only two cases we need to dig them out: The first case is quiet similar to the square which we discussed just now. The second case is rather easy if you consider the parallelogram. And here the key point is come ... Where is the watershed between them? You can calculate $\\beta$ by exterior-interior angles, similar triangle, solving a system of linear equations of two unknowns even binary search on the angle or any other way you could imagine. In the end, you'll find $\\beta = 2 \\arctan \\frac{h}{w}$. As long as you can nd the watershed, the greater part of the problem has been finished. Maybe you have noticed, this problem can also be solved by some computational geometry method, such as half-plane intersection or convex-hull.",
    "tags": [
      "geometry"
    ],
    "rating": 2000
  },
  {
    "contest_id": "280",
    "index": "B",
    "title": "Maximum Xor Secondary",
    "statement": "Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers $x_{1}, x_{2}, ..., x_{k}$ $(k > 1)$ is such maximum element $x_{j}$, that the following inequality holds: $x_{j}\\not\\to\\operatorname*{m}_{i\\geq k}^{k}x_{i}$.\n\nThe lucky number of the sequence of distinct positive integers $x_{1}, x_{2}, ..., x_{k}$ $(k > 1)$ is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.\n\nYou've got a sequence of distinct positive integers $s_{1}, s_{2}, ..., s_{n}$ $(n > 1)$. Let's denote sequence $s_{l}, s_{l + 1}, ..., s_{r}$ as $s[l..r]$ $(1 ≤ l < r ≤ n)$. Your task is to find the maximum number among all lucky numbers of sequences $s[l..r]$.\n\nNote that as all numbers in sequence $s$ are distinct, all the given definitions make sence.",
    "tutorial": "The intervals meaning can only be reflected on its maximum element and second maximum element, so apparently, there must be a lot of meaningless interval which we needn't check them at all. But how can we skip them? Maintain a monotone-decreasing-stack can help us. While a new element came into the view, pop the top element in the stack, and check the corresponding interval, until the new element is greater than the top element in the stack. We can easily see it is correct since we wont lost the answer as long as it exists. All the element at most push and pop once, and only been checked when popped. So the time complexity turn to be O(n).",
    "tags": [
      "data structures",
      "implementation",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "280",
    "index": "C",
    "title": "Game on Tree",
    "statement": "Momiji has got a rooted tree, consisting of $n$ nodes. The tree nodes are numbered by integers from $1$ to $n$. The root has number $1$. Momiji decided to play a game on this tree.\n\nThe game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by $v$) and removes all the subtree nodes with the root in node $v$ from the tree. Node $v$ gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number $1$.\n\nEach time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.",
    "tutorial": "The answer is $$\\sum_{i=1}^n \\frac{1}{Depth[i]}$$ Here we denoted the $Depth[root] = 0$. And why it works? Well, let us observe each vertex independently, when one vertex has been removed, you need either to remove it directly, or remove one of its ancestors. All these choices are equiprobable, so the probability of direct removal is $\\frac{1}{Depth[i]}$. And the sum of them is our result. This is been known as the Linearity of the Expected Value. This property arises almost every way in those problems related with probability. This method will also work when the objects of the delete operation is under a partial order relation. For example, on a DAG or even a digraph(reduce it into a DAG). Finally It will be reduce to descendant counting. But when the delete option is look like ... remove the node and all its neighbours ... such disordered form, the method can do nothing.",
    "tags": [
      "implementation",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "280",
    "index": "D",
    "title": "k-Maximum Subsequence Sum",
    "statement": "Consider integer sequence $a_{1}, a_{2}, ..., a_{n}$. You should run queries of two types:\n\n- The query format is \"$0$ $i$ $val$\". In reply to this query you should make the following assignment: $a_{i} = val$.\n- The query format is \"$1$ $l$ $r$ $k$\". In reply to this query you should print the maximum sum of at most $k$ non-intersecting subsegments of sequence $a_{l}, a_{l + 1}, ..., a_{r}$. Formally, you should choose at most $k$ pairs of integers $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{t}, y_{t})$ $(l ≤ x_{1} ≤ y_{1} < x_{2} ≤ y_{2} < ... < x_{t} ≤ y_{t} ≤ r; t ≤ k)$ such that the sum $a_{x1} + a_{x1 + 1} + ... + a_{y1} + a_{x2} + a_{x2 + 1} + ... + a_{y2} + ... + a_{xt} + a_{xt + 1} + ... + a_{yt}$ is as large as possible. Note that you should choose at most $k$ subsegments. Particularly, you can choose 0 subsegments. In this case the described sum considered equal to zero.",
    "tutorial": "Consider the static problem, Apparently, we can use a dynamic programming to solve it. $f_{0}[i][j]$: the j-MSS in [0, i]. $f_{1}[i][j]$: the quasi-j-MSS in [0, i], which the item ${A_{i}}$ must be selected. The state transition is enumerating whether the $i$th element is selected or not. That's easy for a clever guy such as you. So the brute-force method is doing a dynamic programming for each query. The operation Modify takes $O(1)$ time, and Query takes $O(nk)$ . It's too slow to get Accepted. A simple optimization is using a data structure to speed up Query. The segment tree can be OK. In every node, we store such values in the interval represented by the node: the max sum if choosing $j$ subsegments the max sum if choosing $j$ subsegments with the first element chosen the max sum if choosing $j$ subsegments with the last element chosen the max sum if choosing $j$ subsegments with both first element and last element chosen It's clear that if we know the values of two intervals $A$ and $B$, we can infer the values of the interval which is concatenating $A$ and $B$ by just enumerating how many subsegments can be chosen in $A$ and can be chosen in $B$. The time complexity of concatenating two intervals is $O(k^{2})$. So both operations Modify and Query take $O(k^{2}\\log{n})$ running time. The time limit is 5s in order to save Java's life. If you do some optimization, the solution can be Accepted. You can see liouzhou_101's solution for details. It seems hard to be optimized using such idea. Now we are going to use another totally different idea from max-flow problem. We construct a max-cost max-flow model to solve this problem. The source is $S$ and the sink is $T$. There are other $n + 1$ vertices. A bi-directional edge between Vertex $i$ and Vertex $i + 1$ has cost $A_{i}$ and capacity 1. The unidirectional edge from $S$ to Vertex $i$ has cost 0 and capacity 1 and the unidirectional edge from Vertex $i$ to $T$ has cost 0 and capacity 1. It's obvious for correctness. We can use Successive shortest path algorithm to solve the flow problem. But it's as slow as the brute-force method, or even worse. Considering how the flow problem is solved, that is, how Successive shortest path algorithm works. We find the longest path(**max-cost** instead of min-cost ) between $S$ and $T$, and then augment. We can simplify the algorithm due to the special graph. The new algorithm is: find the subsegment with the maximum sum negate the elements in the subsegment repeat the two steps $k$ times the answer is the sum of the sum of the subsegment you found each time. So, the key point is doing these two operations quickly, where segment tree can possibly be used. To find the MSS you need to store the sum of an interval the maximum partial sum from left the maximum partial sum from right the MSS in the interval To negate a subsegment, the minimum elements must be stored. To find the position of MSS, all the positions are supposed to be kept. The complexity of Modify is $O(\\log n)$, and the complexity of Query is $O(k\\log n)$. It can pass all the test data easily but it has a really large constant.",
    "code": "/*\nAuthor: elfness@UESTC\n*/\n#include<cstdio>\n#include<cstring>\n#include<cstdlib>\n#include<cmath>\n#include<algorithm>\n#include<iostream>\n#include<vector>\n#include<string>\nusing namespace std;\ntypedef long long LL;\n\nconst int MAX = 105000;\n\n/**\n * Segment tree\n */\nstruct Seg\n{\n        int l, r;\n        int maxLeftValue, maxRightValue, minLeftValue, minRightValue, maxSum,\n                minSum, sum;\n        int maxLeftBound, maxRightBound, minLeftBound, minRightBound,\n                maxSumLeft, maxSumRight, minSumLeft, minSumRight;\n} seg[MAX << 2];\nint a[MAX];\n\nvoid update(int k)\n{\n    seg[k].sum = seg[k << 1].sum + seg[k << 1 | 1].sum;\n    if (seg[k << 1].maxLeftValue >= seg[k << 1].sum\n            + seg[k << 1 | 1].maxLeftValue)\n    {\n        seg[k].maxLeftValue = seg[k << 1].maxLeftValue;\n        seg[k].maxRightBound = seg[k << 1].maxRightBound;\n    }\n    else\n    {\n        seg[k].maxLeftValue = seg[k << 1].sum + seg[k << 1 | 1].maxLeftValue;\n        seg[k].maxRightBound = seg[k << 1 | 1].maxRightBound;\n    }\n    if (seg[k << 1 | 1].maxRightValue >= seg[k << 1 | 1].sum\n            + seg[k << 1].maxRightValue)\n    {\n        seg[k].maxRightValue = seg[k << 1 | 1].maxRightValue;\n        seg[k].maxLeftBound = seg[k << 1 | 1].maxLeftBound;\n    }\n    else\n    {\n        seg[k].maxRightValue = seg[k << 1 | 1].sum + seg[k << 1].maxRightValue;\n        seg[k].maxLeftBound = seg[k << 1].maxLeftBound;\n    }\n    if (seg[k << 1].minLeftValue <= seg[k << 1].sum\n            + seg[k << 1 | 1].minLeftValue)\n    {\n        seg[k].minLeftValue = seg[k << 1].minLeftValue;\n        seg[k].minRightBound = seg[k << 1].minRightBound;\n    }\n    else\n    {\n        seg[k].minLeftValue = seg[k << 1].sum + seg[k << 1 | 1].minLeftValue;\n        seg[k].minRightBound = seg[k << 1 | 1].minRightBound;\n    }\n    if (seg[k << 1 | 1].minRightValue <= seg[k << 1 | 1].sum\n            + seg[k << 1].minRightValue)\n    {\n        seg[k].minRightValue = seg[k << 1 | 1].minRightValue;\n        seg[k].minLeftBound = seg[k << 1 | 1].minLeftBound;\n    }\n    else\n    {\n        seg[k].minRightValue = seg[k << 1 | 1].sum + seg[k << 1].minRightValue;\n        seg[k].minLeftBound = seg[k << 1].minLeftBound;\n    }\n    if (seg[k << 1].maxSum >= seg[k << 1 | 1].maxSum)\n    {\n        seg[k].maxSum = seg[k << 1].maxSum;\n        seg[k].maxSumLeft = seg[k << 1].maxSumLeft;\n        seg[k].maxSumRight = seg[k << 1].maxSumRight;\n    }\n    else\n    {\n        seg[k].maxSum = seg[k << 1 | 1].maxSum;\n        seg[k].maxSumLeft = seg[k << 1 | 1].maxSumLeft;\n        seg[k].maxSumRight = seg[k << 1 | 1].maxSumRight;\n    }\n    if (seg[k].maxSum < seg[k << 1].maxRightValue\n            + seg[k << 1 | 1].maxLeftValue)\n    {\n        seg[k].maxSum = seg[k << 1].maxRightValue\n                + seg[k << 1 | 1].maxLeftValue;\n        seg[k].maxSumLeft = seg[k << 1].maxLeftBound;\n        seg[k].maxSumRight = seg[k << 1 | 1].maxRightBound;\n    }\n\n    if (seg[k << 1].minSum <= seg[k << 1 | 1].minSum)\n    {\n        seg[k].minSum = seg[k << 1].minSum;\n        seg[k].minSumLeft = seg[k << 1].minSumLeft;\n        seg[k].minSumRight = seg[k << 1].minSumRight;\n    }\n    else\n    {\n        seg[k].minSum = seg[k << 1 | 1].minSum;\n        seg[k].minSumLeft = seg[k << 1 | 1].minSumLeft;\n        seg[k].minSumRight = seg[k << 1 | 1].minSumRight;\n    }\n    if (seg[k].minSum > seg[k << 1].minRightValue\n            + seg[k << 1 | 1].minLeftValue)\n    {\n        seg[k].minSum = seg[k << 1].minRightValue\n                + seg[k << 1 | 1].minLeftValue;\n        seg[k].minSumLeft = seg[k << 1].minLeftBound;\n        seg[k].minSumRight = seg[k << 1 | 1].minRightBound;\n    }\n}\n\nvoid init(int k, int l, int r)\n{\n    seg[k].l = l;\n    seg[k].r = r;\n    if (l == r)\n    {\n        seg[k].sum = seg[k].maxLeftValue = seg[k].maxRightValue\n                = seg[k].minLeftValue = seg[k].minRightValue = seg[k].maxSum\n                        = seg[k].minSum = a[l];\n        seg[k].maxLeftBound = seg[k].minLeftBound = l;\n        seg[k].maxRightBound = seg[k].minRightBound = r;\n        seg[k].maxSumLeft = seg[k].maxSumRight = r;\n        seg[k].minSumLeft = seg[k].minSumRight = r;\n        return;\n    }\n    int mid = l + r >> 1;\n    init(k << 1, l, mid);\n    init(k << 1 | 1, mid + 1, r);\n    update(k);\n}\n\nvoid Up(int k,int pos,int v)\n{\n    if(seg[k].l==pos&&seg[k].r==pos)\n    {\n        seg[k].sum = seg[k].maxLeftValue = seg[k].maxRightValue\n                = seg[k].minLeftValue = seg[k].minRightValue = seg[k].maxSum\n                        = seg[k].minSum = v;\n        return;\n    }\n    int mid=(seg[k].l+seg[k].r)/2;\n    if(pos<=mid)Up(k << 1, pos, v);\n    else Up(k << 1 | 1, pos, v);\n    update(k);\n}\nint findMaxRight(int k, int l, int r, int& ll)\n{\n    if (seg[k].l == l && seg[k].r == r)\n    {\n        ll = seg[k].maxLeftBound;\n        return seg[k].maxRightValue;\n    }\n    int mid = seg[k].l + seg[k].r >> 1;\n    if (l > mid)\n    {\n        return findMaxRight(k << 1 | 1, l, r, ll);\n    }\n    else\n    {\n        int l1, l2;\n        int retRight = findMaxRight(k << 1 | 1, mid + 1, r, l1);\n        int retLeft = findMaxRight(k << 1, l, mid, l2) + seg[k << 1 | 1].sum;\n        if (retRight >= retLeft)\n        {\n            ll = l1;\n            return retRight;\n        }\n        else\n        {\n            ll = l2;\n            return retLeft;\n        }\n    }\n}\n\nint findMaxLeft(int k, int l, int r, int& rr)\n{\n    if (seg[k].l == l && seg[k].r == r)\n    {\n        rr = seg[k].maxRightBound;\n        return seg[k].maxLeftValue;\n    }\n    int mid = seg[k].l + seg[k].r >> 1;\n    if (r <= mid)\n    {\n        return findMaxLeft(k << 1, l, r, rr);\n    }\n    else\n    {\n        int r1, r2;\n        int retLeft = findMaxLeft(k << 1, l, mid, r1);\n        int retRight = seg[k << 1].sum\n                + findMaxLeft(k << 1 | 1, mid + 1, r, r2);\n        if (retLeft >= retRight)\n        {\n            rr = r1;\n            return retLeft;\n        }\n        else\n        {\n            rr = r2;\n            return retRight;\n        }\n    }\n}\n\nint findMax(int k, int l, int r, int& ll, int& rr)\n{\n    if (seg[k].l == l && seg[k].r == r)\n    {\n        ll = seg[k].maxSumLeft;\n        rr = seg[k].maxSumRight;\n        return seg[k].maxSum;\n    }\n    int mid = seg[k].l + seg[k].r >> 1;\n    if (r <= mid)\n    {\n        return findMax(k << 1, l, r, ll, rr);\n    }\n    else if (l > mid)\n    {\n        return findMax(k << 1 | 1, l, r, ll, rr);\n    }\n    else\n    {\n        int l1, r1, l2, r2, l3, r3, ret;\n        int retLeft = findMax(k << 1, l, mid, l1, r1);\n        int retRight = findMax(k << 1 | 1, mid + 1, r, l2, r2);\n        int retMiddle = findMaxRight(k << 1, l, mid, l3)\n                + findMaxLeft(k << 1 | 1, mid + 1, r, r3);\n        if (retLeft >= retRight)\n        {\n            ll = l1;\n            rr = r1;\n            ret = retLeft;\n        }\n        else\n        {\n            ll = l2;\n            rr = r2;\n            ret = retRight;\n        }\n        if (ret < retMiddle)\n        {\n            ll = l3;\n            rr = r3;\n            ret = retMiddle;\n        }\n        return ret;\n    }\n}\n\nint findMinRight(int k, int l, int r, int& ll)\n{\n    if (seg[k].l == l && seg[k].r == r)\n    {\n        ll = seg[k].minLeftBound;\n        return seg[k].minRightValue;\n    }\n    int mid = seg[k].l + seg[k].r >> 1;\n    if (l > mid)\n    {\n        return findMinRight(k << 1 | 1, l, r, ll);\n    }\n    else\n    {\n        int l1, l2;\n        int retRight = findMinRight(k << 1 | 1, mid + 1, r, l1);\n        int retLeft = findMinRight(k << 1, l, mid, l2) + seg[k << 1 | 1].sum;\n        if (retRight <= retLeft)\n        {\n            ll = l1;\n            return retRight;\n        }\n        else\n        {\n            ll = l2;\n            return retLeft;\n        }\n    }\n}\n\nint findMinLeft(int k, int l, int r, int& rr)\n{\n    if (seg[k].l == l && seg[k].r == r)\n    {\n        rr = seg[k].minRightBound;\n        return seg[k].minLeftValue;\n    }\n    int mid = seg[k].l + seg[k].r >> 1;\n    if (r <= mid)\n    {\n        return findMinLeft(k << 1, l, r, rr);\n    }\n    else\n    {\n        int r1, r2;\n        int retLeft = findMinLeft(k << 1, l, mid, r1);\n        int retRight = seg[k << 1].sum\n                + findMinLeft(k << 1 | 1, mid + 1, r, r2);\n        if (retLeft <= retRight)\n        {\n            rr = r1;\n            return retLeft;\n        }\n        else\n        {\n            rr = r2;\n            return retRight;\n        }\n    }\n}\n\nint findMin(int k, int l, int r, int& ll, int& rr)\n{\n    if (seg[k].l == l && seg[k].r == r)\n    {\n        ll = seg[k].minSumLeft;\n        rr = seg[k].minSumRight;\n        return seg[k].minSum;\n    }\n    int mid = seg[k].l + seg[k].r >> 1;\n    if (r <= mid)\n    {\n        return findMin(k << 1, l, r, ll, rr);\n    }\n    else if (l > mid)\n    {\n        return findMin(k << 1 | 1, l, r, ll, rr);\n    }\n    else\n    {\n        int l1, r1, l2, r2, l3, r3, ret;\n        int retLeft = findMin(k << 1, l, mid, l1, r1);\n        int retRight = findMin(k << 1 | 1, mid + 1, r, l2, r2);\n        int retMiddle = findMinRight(k << 1, l, mid, l3)\n                + findMinLeft(k << 1 | 1, mid + 1, r, r3);\n        if (retLeft <= retRight)\n        {\n            ll = l1;\n            rr = r1;\n            ret = retLeft;\n        }\n        else\n        {\n            ll = l2;\n            rr = r2;\n            ret = retRight;\n        }\n        if (ret > retMiddle)\n        {\n            ll = l3;\n            rr = r3;\n            ret = retMiddle;\n        }\n        return ret;\n    }\n}\n\n/**\n * heap\n */\n\nstruct Node\n{\n        bool flag;\n        int v, l, r, ll, rr;\n        Node()\n        {\n        }\n        Node(bool flag, int v, int l, int r, int ll, int rr) :\n            flag(flag), v(v), l(l), r(r), ll(ll), rr(rr)\n        {\n        }\n} h[MAX];\nint K;\n\nvoid sink(int k)\n{\n    while ((k << 1) <= K)\n    {\n        int maxv = max(h[k].v, h[k << 1].v);\n        if ((k << 1 | 1) <= K)\n        {\n            maxv = max(maxv, h[k << 1 | 1].v);\n        }\n        if (maxv == h[k].v)\n            break;\n        else if (maxv == h[k << 1].v)\n        {\n            swap(h[k], h[k << 1]);\n            k = k << 1;\n        }\n        else\n        {\n            swap(h[k], h[k << 1 | 1]);\n            k = k << 1 | 1;\n        }\n    }\n}\n\nvoid flow(int k)\n{\n    while (k > 1)\n    {\n        int p = k >> 1;\n        if (h[p].v < h[k].v)\n        {\n            swap(h[p], h[k]);\n            k >>= 1;\n        }\n        else\n        {\n            break;\n        }\n    }\n}\n\nNode getMax()\n{\n    swap(h[1], h[K]);\n    K--;\n    sink(1);\n    return h[K + 1];\n}\n\nvoid add(const Node& node)\n{\n    h[++K] = node;\n    flow(K);\n}\n\nint main()\n{\n    int n, m, Q, t;\n    int l, r, L, R;\n    int ret;\n\n\n    while (~scanf(\"%d\", &n) )\n    {\n        for (int i = 0; i < n; i++)\n        {\n            scanf(\"%d\", &a[i]);\n        }\n        init(1, 0, n - 1);\n        scanf(\"%d\",&Q);\n        while(Q--)\n        {\n            int op;\n            scanf(\"%d\",&op);\n            if(op==0)\n            {\n                scanf(\"%d%d\",&l,&r);l--;\n                Up(1,l,r);\n            }\n            else\n            {\n                scanf(\"%d%d%d\",&L,&R,&m);L--;R--;\n                K = 0;\n                ret = 0;\n                t = findMax(1, L, R, l, r);\n                add(\n                    Node(true, t, L, R, l,\n                         r));\n                while (m--)\n                {\n                    Node u = getMax();\n                    if (u.v <= 0)\n                    {\n                        break;\n                    }\n                    ret += u.v;\n                    if (!u.flag)\n                    {\n                        if (u.l != u.ll)\n                        {\n                            t = findMin(1, u.l, u.ll - 1, l, r);\n                            add(Node(false, -t, u.l, u.ll - 1, l, r));\n                        }\n                        if (u.r != u.rr)\n                        {\n                            t = findMin(1, u.rr + 1, u.r, l, r);\n                            add(Node(false, -t, u.rr + 1, u.r, l, r));\n                        }\n                        t = findMax(1, u.ll, u.rr, l, r);\n                        add(Node(true, t, u.ll, u.rr, l, r));\n                    }\n                    else\n                    {\n                        if (u.l != u.ll)\n                        {\n                            t = findMax(1, u.l, u.ll - 1, l, r);\n                            add(Node(true, t, u.l, u.ll - 1, l, r));\n                        }\n                        if (u.r != u.rr)\n                        {\n                            t = findMax(1, u.rr + 1, u.r, l, r);\n                            add(Node(true, t, u.rr + 1, u.r, l, r));\n                        }\n                        t = findMin(1, u.ll, u.rr, l, r);\n                        add(Node(false, -t, u.ll, u.rr, l, r));\n                    }\n                }\n                printf(\"%d\n\", ret);\n            }\n        }\n    }\n\n    return 0;\n}",
    "tags": [
      "data structures",
      "flows",
      "graphs",
      "implementation"
    ],
    "rating": 2800
  },
  {
    "contest_id": "280",
    "index": "E",
    "title": "Sequence Transformation",
    "statement": "You've got a non-decreasing sequence $x_{1}, x_{2}, ..., x_{n}$ $(1 ≤ x_{1} ≤ x_{2} ≤ ... ≤ x_{n} ≤ q)$. You've also got two integers $a$ and $b$ $(a ≤ b; a·(n - 1) < q)$.\n\nYour task is to transform sequence $x_{1}, x_{2}, ..., x_{n}$ into some sequence $y_{1}, y_{2}, ..., y_{n}$ $(1 ≤ y_{i} ≤ q; a ≤ y_{i + 1} - y_{i} ≤ b)$. The transformation price is the following sum: $\\sum_{i=1}^{n}(y_{i}-x_{i})^{2}$. Your task is to choose such sequence $y$ that minimizes the described transformation price.",
    "tutorial": "Let $dp[i][j]$=(the minimum transformation price to the moment if $y_{1}... y_{i}$ have been determined and $y_{i} = j$). It's easy to find that: $dp[1][p] = (p - x_{1})^{2}$ $f[i][p] = min(dp[i - 1][q] | p - b  \\le  q  \\le  p - a)$ $dp[i][p] = (p - x_{i})^{2} + f[i][p]$ Solutions using this idea straight can't pass because it needs very huge amount of memory and time(in fact it's infinite). So we should consider the problem more accurately. Here comes the magic: let $dp[i]$ be a function for $p$. First of all, we'll use the monotonicity of its derivative $dp[i]'$ and mathematical induction to prove that $dp[i]$ is a strictly unimodal function. More strongly, we can prove $dp[i]'$ is a strictly increasing function. $dp[1]'(p) = 2(p - x[1])$. Obviously so it is. If we have proved that $dp[i]'$ is a strictly increasing function, and $min dp[i] = dp[i](k)$. In addition, $dp[i]'(k) = 0$. For $f[i + 1]$ at this moment: $\\begin{array}{c}{{f[i+1](p)=\\left\\{d p[i](p-a),\\;\\;p<k+a}}\\\\ {{\\displaystyle k p[i](p-b),\\;\\;p>k+a\\le p\\le k+b}}\\\\ {{f[i+1]^{\\prime}(p-a),\\;\\;\\;p>k+b}}\\\\ {{f[j-a+b}}\\end{array}\\right.$Notice that for the derivative, actually what we do is to cut $dp[i]'$ at the place $p = k$, and then the left part ($p  \\le  k$) moves to the right $a$ units while the right part ($p  \\ge  k$) moves to the right $b$ units. After this operation, the gap ($k + a... k + b$) is filled by 0 so that it's still a continuous function. We can find $f[i + 1]'$ is also a increasing function but not strictly. Then $dp[i + 1]'(p) = 2(p - x_{i + 1}) + f[i + 1]'(p)$, now it's absolutely a strictly increasing function. Since we have proved any $dp[i]$ is a strictly unimodal function, we can push $x_{i}$ one by one and calculate the function $dp[i]$ immediately. Let's focus on the operation to $dp[i]'$: Step 1. Determine $k$ for $dp[i]'(k) = 0$. Step 2. Cutting, translation, and filling 0. Step 3. Add a linear function $2(p - x_{i})$. Because of step 2, the derivative is in reality a piecewise function, and any part of this function is a linear function. Besides, there are at most $O(n)$ parts. Finally, We can use a simple array to hold all the endpoints. Since we should maintain at most $O(n)$ endpoints for $n$ times, the time complexity is $O(n^{2})$.",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "281",
    "index": "A",
    "title": "Word Capitalization",
    "statement": "Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.\n\nNote, that during capitalization all the letters except the first one remains unchanged.",
    "tutorial": "As the first problem in the problemset, it intended to be simple so that any one could solve it. Just implement what the problem said under your favorite language.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "281",
    "index": "B",
    "title": "Nearest Fraction",
    "statement": "You are given three positive integers $x, y, n$. Your task is to find the nearest fraction to fraction $\\scriptstyle{\\frac{\\pi}{y}}$ whose denominator is no more than $n$.\n\nFormally, you should find such pair of integers $a, b$ $(1 ≤ b ≤ n; 0 ≤ a)$ that the value $\\left|{\\frac{x}{y}}-{\\frac{a}{b}}\\right|$ is as minimal as possible.\n\nIf there are multiple \"nearest\" fractions, choose the one with the minimum denominator. If there are multiple \"nearest\" fractions with the minimum denominator, choose the one with the minimum numerator.",
    "tutorial": "This problem can be solved by a straight forward method since we are at Div II, simply enumerate all possible denominator, and calculate the nearest fraction for each denominator. As you would expect, we can do better. Actually this is the limit_denominator() method implemented by the Python fractions module. Since it is written in Python and you can just look at the source code to nd the truth behind it if you are interested. Here Id like to quote the top comment of the snippet: Algorithm notes: For any real number x, define a *best upper approximation* to x to be a rational number p/q such that: (1) p/q >= x, and (2) if p/q > r/s >= x then s > q, for any rational r/s. Define *best lower approximation* similarly. Then it can be proved that a rational number is a best upper or lower approximation to x if, and only if, it is a convergent or semiconvergent of the (unique shortest) continued fraction associated to x. To find a best rational approximation with denominator <= M, we find the best upper and lower approximations with denominator <= M and take whichever of these is closer to x. In the event of a tie, the bound with smaller denominator is chosen. If both denominators are equal (which can happen only when max_denominator == 1 and self is midway between two integers) the lower bound---i.e., the floor of self, is taken.",
    "tags": [
      "brute force",
      "implementation",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "282",
    "index": "A",
    "title": "Bit++",
    "statement": "The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.\n\nThe language is that peculiar as it has exactly one variable, called $x$. Also, there are two operations:\n\n- Operation ++ increases the value of variable $x$ by 1.\n- Operation -- decreases the value of variable $x$ by 1.\n\nA statement in language Bit++ is a sequence, consisting of exactly one operation and one variable $x$. The statement is written without spaces, that is, it can only contain characters \"+\", \"-\", \"X\". Executing a statement means applying the operation it contains.\n\nA programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.\n\nYou're given a programme in language Bit++. The initial value of $x$ is $0$. Execute the programme and find its final value (the value of the variable when this programme is executed).",
    "tutorial": "Just use a simple loop. (Take a look at the Python code)",
    "code": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <cstdio>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\n#include <cstring>\n#include <map>\n#include <queue>\n#include <set>\n#include <queue>\n#include <stack>\n#include <deque>\n#include <assert.h>\n#include <ctime>\n#include <bitset>\n#include <numeric>\n#include <complex>\n#include <valarray>\nusing namespace std;\n\n#define FOREACH(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define FOR(i, a, n) for (register int i = (a); i < (int)(n); ++i)\n#define FORE(i, a, n) for (i = (a); i < (int)(n); ++i)\n#define Size(n) ((int)(n).size())\n#define all(n) (n).begin(), (n).end()\n#define ll long long\n#define pb push_back\n#define error(x) cout << #x << \" = \" << (x) << endl;\n#define ull unsigned long long\n#define pii pair<int, int>\n//#define pii pair<ll, ll>\n#define pll pair<ll, ll>\n#define pdd pair<double, double>\n#define point complex<double>\n#define X real()\n#define Y imag()\n//#define X first\n//#define Y second\n#define EPS 1e-10\n//#define endl \"\n\"\n#define pdd pair<double, double>\n#define mk make_pair\n\nint main() {\n    int n;\n    cin >> n;\n    vector<string> v(n);\n    FOR(i, 0, n) cin >> v[i];\n    cout << count(all(v), \"++X\")+count(all(v), \"X++\")-count(all(v), \"--X\")-count(all(v), \"X--\") << endl;\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "282",
    "index": "B",
    "title": "Painting Eggs",
    "statement": "The Bitlandians are quite weird people. They have very peculiar customs.\n\nAs is customary, Uncle J. wants to have $n$ eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.\n\nThe kids are excited because just as is customary, they're going to be paid for the job!\n\nOverall uncle J. has got $n$ eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals $1000$.\n\nUncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than $500$.\n\nHelp Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.",
    "tutorial": "This one can be solved by a greedy algorithm. Start from the 1st egg and each time give the egg to A if and only if giving it to A doesn't make the difference > 500, otherwise give it to G. To prove the correctness, one can use induction. The base case is trivial. Suppose that we've assigned the first $n - 1$ eggs such that the total money given to A is $S_{a}$ and total money given to G is $S_{g}$. We can assume $S_{a}  \\ge  S_{g}$. Now we must either add $g_{n}$ to $S_{g}$ or add $a_{n}$ to $S_{a}$. If we can't add $g_{n}$ to $S_{g}$, then $S_{g} + g_{n} > S_{a} + 500$, so $- 500 > S_{a} - S_{g} - g_{n}$, adding $1000$ to both sides gives us the inequality $500 > S_{a} + (1000 - g_{n}) - S_{g}$ which is exactly what we need to make sure that we can add $a_{n} = 1000 - g_{n}$ to $S_{a}$.",
    "code": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <cstdio>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\n#include <cstring>\n#include <map>\n#include <queue>\n#include <set>\n#include <queue>\n#include <stack>\n#include <deque>\n#include <assert.h>\n#include <ctime>\n#include <bitset>\n#include <numeric>\n#include <complex>\n#include <valarray>\nusing namespace std;\n\n#define FOREACH(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define FOR(i, a, n) for (register int i = (a); i < (int)(n); ++i)\n#define FORE(i, a, n) for (i = (a); i < (int)(n); ++i)\n#define Size(n) ((int)(n).size())\n#define all(n) (n).begin(), (n).end()\n#define ll long long\n#define pb push_back\n#define error(x) cout << #x << \" = \" << (x) << endl;\n#define ull unsigned long long\n#define pii pair<int, int>\n//#define pii pair<ll, ll>\n#define pll pair<ll, ll>\n#define pdd pair<double, double>\n#define point complex<double>\n#define X real()\n#define Y imag()\n//#define X first\n//#define Y second\n#define EPS 1e-10\n//#define endl \"\n\"\n#define pdd pair<double, double>\n#define mk make_pair\n\nint main() {\n    int n;\n    cin >> n;\n    int tot = 0;\n    FOR(i, 0, n) {\n        int a, b;\n        cin >> a >> b;\n        if (tot+a <= 500) {\n            tot += a;\n            cout << \"A\";\n        } else {\n            tot -= b;\n            cout << \"G\";\n        }\n    }\n    cout << endl;\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "282",
    "index": "C",
    "title": "XOR and OR",
    "statement": "The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.\n\nA Bitlandish string is a string made only of characters \"0\" and \"1\".\n\nBitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string $a$, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as $x$ and the other one as $y$. Then he calculates two values $p$ and $q$: $p = x xor y$, $q = x or y$. Then he replaces one of the two taken characters by $p$ and the other one by $q$.\n\nThe $xor$ operation means the bitwise excluding OR operation. The $or$ operation is the bitwise OR operation.\n\nSo for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.\n\nYou've got two Bitlandish strings $a$ and $b$. Your task is to check if it is possible for BitHaval to transform string $a$ to string $b$ in several (possibly zero) described operations.",
    "tutorial": "First of all, check the length of the two strings to be equal. Then with a little try and guess, you can find out that the zero string (00...0) can't be converted to anything else and nothing else can be converted to zero. All other conversions are possible.",
    "code": "#include <iostream>\n#include <string>\nusing namespace std;\nint main(){\n        string a,b;\n        cin>>a>>b;\n        bool ans_a = false;\n        bool ans_b = false;\n        if(a.size()==b.size()){\n                for(int i=0;i<a.size();i++){\n                        if(a[i]=='1'){\n                                ans_a=true;\n                        }\n                        if(b[i]=='1'){\n                                ans_b=true;\n                        }\n                }\n        }\n        if(a.size()==1){\n                ans_a=false;\n        }\n        if(a==b){\n                ans_a=true;\n                ans_b=true;\n        }\n        if(ans_a and ans_b)\n                cout<<\"YES\"<<endl;\n        else\n                cout<<\"NO\"<<endl;\n        return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "282",
    "index": "D",
    "title": "Yet Another Number Game",
    "statement": "Since most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games!\n\nSince you are so curious about Bitland, I'll give you the chance of peeking at one of these games.\n\nBitLGM and BitAryo are playing yet another of their crazy-looking genius-needed Bitlandish games. They've got a sequence of $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. The players make moves in turns. BitLGM moves first. Each player can and must do one of the two following actions in his turn:\n\n- Take one of the integers (we'll denote it as $a_{i}$). Choose integer $x$ $(1 ≤ x ≤ a_{i})$. And then decrease $a_{i}$ by $x$, that is, apply assignment: $a_{i} = a_{i} - x$.\n- Choose integer $x$ $(1\\leq x\\leq\\operatorname*{min}_{i=1}a_{i})$. And then decrease all $a_{i}$ by $x$, that is, apply assignment: $a_{i} = a_{i} - x$, for all $i$.\n\nThe player who cannot make a move loses.\n\nYou're given the initial sequence $a_{1}, a_{2}, ..., a_{n}$. Determine who wins, if both players plays optimally well and if BitLGM and BitAryo start playing the described game in this sequence.",
    "tutorial": "For n=1, everything is clear. If $a_{1} = 0$ then BitAryo wins, otherwise BitLGM is the winner. For n=2: define win[i][j] = (Whether i,j is a Winning position). It's easy to calculate win[i][j] for all i and j, using a loop (Checking all possible moves). This leads us to an O($n^{3}$) solution. For n=3: Everything is similar to NIM, With the same statement of proof as for NIM, i,j,k is a winning position if and only if (i xor j xor k) $ \\neq  0$.[Don't forget the parentheses in code :) ] Complexity: O(1) One can also solve this case using DP. We define lose[i][j]= (Least k, such that i,j,k is a losing position) ,lose2[i][j]=(Least k, such that k,k+i,k+i+j is a losing position) and win[i][j][k] just as the case with n=2. As in the codes below, one can calculate all these values in O($n^{3}$). Using the same DP strategy for n=2 and the O(1) algorithm for n=3 and n=1, leads us to a total complexity of O($n^{2}$) which was not necessary in this contest.",
    "code": "//In the name of God\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nconst int MAXN=310;\nconst int MGO=305;\n\nbool wins2[MAXN][MAXN];\nvoid calc2()\n{\n  for(int i=0;i<MGO;++i)\n    for(int j=max(i,1);j<MGO;++j)\n      {\n\tfor(int I=0;I<i;++I)\n\t  if(wins2[I][j]==false)\n\t    {wins2[i][j]=true; break;}\n\tfor(int J=0;J<j and wins2[i][j]==false;++J)\n\t  if(wins2[i][J]==false)\n\t    {wins2[i][j]=true; break;}\n\tfor(int K=1;K<=min(i,j) and wins2[i][j]==false;++K)\n\t  if(wins2[i-K][j-K]==false)\n\t    {wins2[i][j]=true; break;}\n\twins2[j][i]=wins2[i][j];\n      }\n}\n\nint main()\n{\n  int n;\n  cin>>n;\n  if(n==1)\n    {\n      int x;\n      cin>>x;\n      if(x==0)\n\tcout<<\"BitAryo\"<<endl;\n      else\n\tcout<<\"BitLGM\"<<endl;\n    }\n  else if(n==2)\n    {\n      int x,y; cin>>x>>y; if(x>y) swap(x,y);\n      calc2();\n      if(wins2[x][y])\n\tcout<<\"BitLGM\"<<endl;\n      else\n\tcout<<\"BitAryo\"<<endl;\n    }\n  else\n    {\n      int x,y,z;\n      cin>>x>>y>>z;\n      if((x^y^z)==0)\n\tcout<<\"BitAryo\"<<endl;\n      else\n\tcout<<\"BitLGM\"<<endl;\n    }\n  return 0;\n}",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 2100
  },
  {
    "contest_id": "282",
    "index": "E",
    "title": "Sausage Maximization",
    "statement": "The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!\n\nIn Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the $xor$ operation) of all integers in that sausage.\n\nOne day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.\n\nBut Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).\n\nThe pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.\n\nFind a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.",
    "tutorial": "Can be solved using a trie in O(n log (max{$a_{i}$})). Start with a prefix of size n, and decrease the size of prefix in each step. For each new prefix calculate the XOR of elements in that prefix and add the XOR of the newly available suffix (which does not coincide with the new prefix) to the trie, then query the trie for the best possible match for the XOR of the new prefix. (Try to get 1 as the first digit if possible, otherwise put 0, then do the same thing for the second digit and so on). Get a maximum over all answers you've found, and it's all done. [By digit, I mean binary digit]",
    "code": "//In the name of God\n#include <iostream>\n#include <deque>\nusing namespace std;\n\nconst int MAXN=1e6+1e3;\n#define num long long\nnum all[MAXN];\n\nstruct node\n{\n  node *child[2];\n  node()\n  {\n    child[0]=child[1]=NULL;\n  }\n};\n\nnode *root;\n\ndeque<short> binary(long long x)\n{\n  deque<short> ans;\n  while(x)\n    {\n      ans.push_front(x%2);\n      x/=2;\n    }\n  while(ans.size()<50)\n    ans.push_front(0);\n  return ans;\n}\n\nvoid add(long long x)\n{\n  deque<short> a=binary(x);\n  node *C=root;\n  while(a.size())\n    {\n      if(C->child[a[0]]==NULL)\n    C->child[a[0]]=new node;\n      C=C->child[a[0]];\n      a.pop_front();\n    }\n}\n\nlong long query(long long x)\n{\n  deque<short> a=binary(x);\n  long long ans=0;\n  node *C=root;\n  while(a.size())\n    {\n      if(C->child[1-a[0]]!=NULL)\n    {\n      C=C->child[1-a[0]];\n      ans*=2;\n      ans+=1;\n    }\n      else\n    {\n      C=C->child[a[0]];\n      ans*=2;\n    }\n      a.pop_front();\n    }\n  return ans;\n}\n\nint main()\n{\n  root=new node;\n  int n;\n  cin>>n;\n  num xorall=0;\n  for(int i=1;i<=n;++i)\n    {\n    cin>>all[i];\n    xorall^=all[i];\n    }\n  num maxgot=0;\n  int ai=0,bi=0;\n  num total=0;\n  add(total);\n  for(int i=1;i<=n;++i)\n    {\n      total^=all[i];\n      add(total);\n      maxgot=max(maxgot,query(total^xorall));\n    }\n  cout<<fixed<<maxgot<<endl;\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "283",
    "index": "A",
    "title": "Cows and Sequence",
    "statement": "Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform $n$ operations. Each operation is one of the following:\n\n- Add the integer $x_{i}$ to the first $a_{i}$ elements of the sequence.\n- Append an integer $k_{i}$ to the end of the sequence. (And hence the size of the sequence increases by 1)\n- Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence.\n\nAfter each operation, the cows would like to know the average of all the numbers in the sequence. Help them!",
    "tutorial": "Consider the problem with only queries 1 and 2. Then the problem is easy in $O(n)$: keep track of the number of terms and the sum, and you can handle each query in O(1). But with query 3 we need to also be able to find the last term of the sequence at any given time. To do this, we keep track of the sequence $d_{i} = a_{i + 1} - a_{i}$ for $i = 1, 2, ..., s - 1,$ and $a_{s},$ where $s$ is the length of the sequence. Notice that query 2 only modifies one value of $d_{i},$ and queries 1 and 3 are easily processed and able to update this information. This gives us an $O(n)$ algorithm. One can also use a fenwick or segment tree to compute the last element, but it's not nearly as nice :).",
    "tags": [
      "constructive algorithms",
      "data structures",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "283",
    "index": "B",
    "title": "Cow Program",
    "statement": "Farmer John has just given the cows a program to play with! The program contains two integer variables, $x$ and $y$, and performs the following operations on a sequence $a_{1}, a_{2}, ..., a_{n}$ of positive integers:\n\n- Initially, $x = 1$ and $y = 0$. If, after any step, $x ≤ 0$ or $x > n$, the program immediately terminates.\n- The program increases both $x$ and $y$ by a value equal to $a_{x}$ simultaneously.\n- The program now increases $y$ by $a_{x}$ while decreasing $x$ by $a_{x}$.\n- The program executes steps 2 and 3 (first step 2, then step 3) repeatedly until it terminates (it may never terminate). So, the sequence of executed steps may start with: step 2, step 3, step 2, step 3, step 2 and so on.\n\nThe cows are not very good at arithmetic though, and they want to see how the program works. Please help them!\n\nYou are given the sequence $a_{2}, a_{3}, ..., a_{n}$. Suppose for each $i$ $(1 ≤ i ≤ n - 1)$ we run the program on the sequence $i, a_{2}, a_{3}, ..., a_{n}$. For each such run output the final value of $y$ if the program terminates or -1 if it does not terminate.",
    "tutorial": "First, suppose we only have the sequence $a_{2}, a_{3},  \\dots a_{n}.$ We note that the current state is only determined by the location and the direction we are facing, so there are only $2 \\cdot (n - 1)$ states total. Then, we can use DFS with memorization to find the distance traveled from each state, or $- 1$ if a cycle is formed, in $O(n)$ time. Now, when we add $a_{1}$ into the sequence, we essentially only need to give the distance traveled starting from each state facing left. The only difference is that if we ever land on $a_{1}$ again, there must be a cycle, as we started on $a_{1}$. Using this, we can solve the problem in $O(n)$ time total.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "283",
    "index": "C",
    "title": "Coin Troubles",
    "statement": "In the Isle of Guernsey there are $n$ different types of coins. For each $i$ $(1 ≤ i ≤ n)$, coin of type $i$ is worth $a_{i}$ cents. It is possible that $a_{i} = a_{j}$ for some $i$ and $j$ $(i ≠ j)$.\n\nBessie has some set of these coins totaling $t$ cents. She tells Jessie $q$ pairs of integers. For each $i$ $(1 ≤ i ≤ q)$, the pair $b_{i}, c_{i}$ tells Jessie that Bessie has a strictly greater number of coins of type $b_{i}$ than coins of type $c_{i}$. It is known that all $b_{i}$ are distinct and all $c_{i}$ are distinct.\n\nHelp Jessie find the number of possible combinations of coins Bessie could have. Two combinations are considered different if there is some $i$ $(1 ≤ i ≤ n)$, such that the number of coins Bessie has of type $i$ is different in the two combinations. Since the answer can be very large, output it modulo $1000000007$ $(10^{9} + 7)$.\n\nIf there are no possible combinations of coins totaling $t$ cents that satisfy Bessie's conditions, output 0.",
    "tutorial": "Imagine the problem as a graph where coins are the nodes and Bessie's statements are directed edges between coins. Because of the problem conditions, the graph must be a set of cycles and directed paths. If there are any cycles in the graph, the answer is clearly 0. Then, suppose we have a path $p_{1}, p_{2},  \\dots p_{k}$ in the graph, where it is known that we have more coins of type $p_{1}$ than of type $p_{2}$, more of type $p_{2}$ than of type $p_{3},$ and so on. The key observation in this problem is that this is equivalent to having k independent coins of value ${a_{}(p_{1}), a_{}(p_{1}) + a_{}(p_{2}), a_{}(p_{1}) + a_{}(p_{2}) + a_{}(p_{3}),  \\dots }.$ The first coin in our new list represents how many more coins of type $p_{1}$ than of type $p_{2}$ we have, the second coin in our new list represents how many more coins of type $p_{2}$ than of type $p_{3}$ we have, and so on. However, we must be careful to note that we need at least one of each of the new coins except for the last one, so we can subtract their values from T before doing the DP. After creating our new set of values, we can run the DP the same way we would run a standard knapsack. This algorithm takes $O(nt)$ time total.",
    "tags": [
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "283",
    "index": "D",
    "title": "Cows and Cool Sequences",
    "statement": "Bessie and the cows have recently been playing with \"cool\" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help!\n\nA pair $(x, y)$ of positive integers is \"cool\" if $x$ can be expressed as the sum of $y$ consecutive integers (not necessarily positive). A sequence $(a_{1}, a_{2}, ..., a_{n})$ is \"cool\" if the pairs $(a_{1}, a_{2}), (a_{2}, a_{3}), ..., (a_{n - 1}, a_{n})$ are all cool.\n\nThe cows have a sequence of $n$ positive integers, $a_{1}, a_{2}, ..., a_{n}$. In one move, they may replace some $a_{i}$ with any other positive integer (there are no other limits on the new value of $a_{i}$). Determine the smallest number of moves needed to make the resulting sequence cool.",
    "tutorial": "Let $v_{2}(n)$ denote the exponent of the largest power of $2$ that divides $n.$ For example $v_{2}(5) = 0, v_{2}(96) = 5.$ Let $f(n)$ denote the largest odd factor of $n.$ We can show that for fixed $a_{i}, a_{j}(i < j),$ we can construct a cool sequence $a_{i} = b_{i}, b_{i + 1}, ... b_{j - 1}, b_{j} = a_{j}$ if and only if $f(a_{j})|f(a_{i})$ and either $v_{2}(a_{i}) + j - i = v_{2}(a_{j})$ or $v_{2}(a_{j})  \\le  j - i - 1.$ Proof here With this observation, we can use dynamic programming where the $k$th state is the maximum number of $a_{i}$ ($i  \\le  k$) we can keep so that it is possible to make $a_{1}, ... a_{k}$ cool. The transition for this is $O(n),$ and the answer is just $n - max (dp[1], dp[2], ..., dp[n]).$ This algorithm is $O(n^{2}).$",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "283",
    "index": "E",
    "title": "Cow Tennis Tournament",
    "statement": "Farmer John is hosting a tennis tournament with his $n$ cows. Each cow has a skill level $s_{i}$, and no two cows having the same skill level. Every cow plays every other cow exactly once in the tournament, and each cow beats every cow with skill level lower than its own.\n\nHowever, Farmer John thinks the tournament will be demoralizing for the weakest cows who lose most or all of their matches, so he wants to flip some of the results. In particular, at $k$ different instances, he will take two integers $a_{i}, b_{i}$ $(a_{i} < b_{i})$ and flip all the results between cows with skill level between $a_{i}$ and $b_{i}$ inclusive. That is, for any pair $x, y$ $(x\\neq y;\\;s_{x},s_{y}\\in[a_{i},b_{i}])$ he will change the result of the match on the final scoreboard (so if $x$ won the match, the scoreboard will now display that $y$ won the match, and vice versa). It is possible that Farmer John will change the result of a match multiple times. It is not guaranteed that $a_{i}$ and $b_{i}$ are equal to some cow's skill level.\n\nFarmer John wants to determine how balanced he made the tournament results look. In particular, he wants to count the number of triples of cows $(p, q, r)$ for which the final leaderboard shows that cow $p$ beats cow $q$, cow $q$ beats cow $r$, and cow $r$ beats cow $p$. Help him determine this number.\n\nNote that two triples are considered different if they do not contain the same set of cows (i.e. if there is a cow in one triple that is not in the other).",
    "tutorial": "This will go over the basic outline for solution. We can show that the answer is $\\textstyle{\\binom{n}{3}}-\\sum_{i}{\\binom{n_{i}}{2}}$ where $w_{i}$ is the number of wins cow $i$ appears to have. Proof here Now sort the skill levels of the cows (the order of the $s_{i}$ doesn't actually matter). $s_{1}$ is lowest skill. Now consider an $n  \\times  n$ grid where the $i$th row and $j$th column of the grid is a 1 if the match between cow $i$ and cow $j$ is flipped. The grid is initially all zeros and Farmer John's query simply flips a rectangle of the form $[a, b]  \\times  [a, b].$ We can process these queries and compute the number of wins for each cow using a vertical sweep line on the grid and updating with a seg tree on the interval [1,n]. The seg tree needs to handle queries of the form \\begin{enumerate} \\item Flip all numbers (0->1, 1->0) in a range $[a, b].$ \\item Query number of 1's in a range $[a, b].$ \\end{enumerate} Note that given this seg tree we can compute the number of wins for each cow at every point in the sweep line as (Number of 1's in range [1,i - 1]) + (Number of 0's in range [i + 1, n]). There are $O(m)$ queries so this solution takes $m\\log(n)$ time.",
    "tags": [
      "combinatorics",
      "data structures",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "284",
    "index": "A",
    "title": "Cows and Primitive Roots",
    "statement": "The cows have just learned what a primitive root is! Given a prime $p$, a primitive root $\\mathrm{mod}\\,p$ is an integer $x$ $(1 ≤ x < p)$ such that none of integers $x - 1, x^{2} - 1, ..., x^{p - 2} - 1$ are divisible by $p$, but $x^{p - 1} - 1$ is.\n\nUnfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime $p$, help the cows find the number of primitive roots $\\mathrm{mod}\\,p$.",
    "tutorial": "We didn't expect this problem to be so hard :(. This problem can be solved by brute forcing. For any $x,$ you can compute $x^{1},x^{2},\\ldots,x^{p-1}\\mod p$ in $O(p)$ time (iteratively multiply cur = (cur * i) % p, not use pow in math library!), so overall brute force will be $O(p^{2})$ time. Note: there is actually $O({\\sqrt{p}})$ algorithm.",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "284",
    "index": "B",
    "title": "Cows and Poker Game",
    "statement": "There are $n$ cows playing poker at a table. For the current betting phase, each player's status is either \"ALLIN\", \"IN\", or \"FOLDED\", and does not change throughout the phase. To increase the suspense, a player whose current status is not \"FOLDED\" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either \"ALLIN\" or \"FOLDED\". The player's own status may be either \"ALLIN\" or \"IN\".\n\nFind the number of cows that can currently show their hands without affecting any betting decisions.",
    "tutorial": "We first note that players who have folded do not affect our desired answer. Then, we can do casework on the number of players who are currently \"IN\". If no cows are \"IN\", then all the players who are \"ALLIN\" can show their hands. If exactly one cow is \"IN\", she is the only one who can show, so the answer is 1. If two or more cows are \"IN\", no one can show their hands. Then we simply count the number of cows of each type and check for each case. The total runtime is $O(n).$",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "285",
    "index": "A",
    "title": "Slightly Decreasing Permutations",
    "statement": "{\\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.}\n\nThe decreasing coefficient of permutation $p_{1}, p_{2}, ..., p_{n}$ is the number of such $i (1 ≤ i < n)$, that $p_{i} > p_{i + 1}$.\n\nYou have numbers $n$ and $k$. Your task is to print the permutation of length $n$ with decreasing coefficient $k$.",
    "tutorial": "As the answer you can print such permutation: $n, n - 1, ..., n - k + 1, 1, 2, ..., n - k$. For example, if $n = 5$, $k = 2$, then the answer is: $5, 4, 1, 2, 3$. If $k = 0$, you should print $1, 2, ..., n$. Such solution can be written in two loops.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "285",
    "index": "B",
    "title": "Find Marble",
    "statement": "Petya and Vasya are playing a game. Petya's got $n$ non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from $1$ to $n$ from left to right. Note that the positions are indexed but the glasses are not.\n\nFirst Petya puts a marble under the glass in position $s$. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position $p_{1}$, the glass from the second position to position $p_{2}$ and so on. That is, a glass goes from position $i$ to position $p_{i}$. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.\n\nAfter all shuffling operations Petya shows Vasya that the ball has moved to position $t$. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position $s$ to position $t$.",
    "tutorial": "It is known that a permutation can be considered as set of cycles. The integer $i$ moves to $p[i]$ for all $i$ $(1  \\le  i  \\le  n)$. You can start moving from integer $s$ along the cycle. If you find integer $t$, then print the length of the path. If you return to $s$, then print $- 1$.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "285",
    "index": "C",
    "title": "Building Permutation",
    "statement": "{\\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.}\n\nYou have a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.",
    "tutorial": "The solution of the problem is rather simple. Sort all integers $a$ and then make from integer $a[1]$ integer $1$, from integer $a[2]$ integer $2$ and so on. So, integer $a[i]$ adds to the answer the value $|a[i] - i|$. The answer should be count in 64-bit type. You can simply guess why such solution is correct.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "285",
    "index": "D",
    "title": "Permutation Sum",
    "statement": "{\\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.}\n\nPetya decided to introduce the sum operation on the set of permutations of length $n$. Let's assume that we are given two permutations of length $n$: $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{n}$. Petya calls the sum of permutations $a$ and $b$ such permutation $c$ of length $n$, where $c_{i} = ((a_{i} - 1 + b_{i} - 1) mod n) + 1$ $(1 ≤ i ≤ n)$.\n\nOperation $x\\ {\\mathrm{mod}}\\ y$ means taking the remainder after dividing number $x$ by number $y$.\n\nObviously, not for all permutations $a$ and $b$ exists permutation $c$ that is sum of $a$ and $b$. That's why Petya got sad and asked you to do the following: given $n$, count the number of such pairs of permutations $a$ and $b$ of length $n$, that exists permutation $c$ that is sum of $a$ and $b$. The pair of permutations $x, y$ $(x ≠ y)$ and the pair of permutations $y, x$ are considered distinct pairs.\n\nAs the answer can be rather large, print the remainder after dividing it by $1000000007$ ($10^{9} + 7$).",
    "tutorial": "For a start, describe bruteforce solution. Firstly, we will always assume, that $a$ is identity permutation, that is $a[i] = i$. In this case, the answer should be multiplied by $n!$. Or in other way your bruteforce will not be counted. Secondly, using our bruteforce we can see, that for even $n$ the answer is $0$. What do you also need to get accepted? First case is to calculate answers for all $n$ on your computer and write them in constant array. In other words you can make precalc. Second case is to make you solution faster. The soltuion using meet-in-the-middle idea works fast for $n  \\le  15$. If you remember that for even $n$ answer is $0$ then you can get accepted using such solution. But other simple bruteforces and dynamic programmings on maps work slower than $3$ seconds.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "implementation",
      "meet-in-the-middle"
    ],
    "rating": 1900
  },
  {
    "contest_id": "285",
    "index": "E",
    "title": "Positions in Permutations",
    "statement": "{\\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.}\n\nWe'll call position $i$ ($1 ≤ i ≤ n$) in permutation $p_{1}, p_{2}, ..., p_{n}$ good, if $|p[i] - i| = 1$. Count the number of permutations of size $n$ with exactly $k$ good positions. Print the answer modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "A common approach for this kind of problem is DP. What we do here is to choose numbers for the good positions first, then fill the others later on. Let f(i, j, k) is the number of ways to choose j good positions in the first i-th position and k is a 2-bit number that represents whether number i and number i + 1 is already used or not. The DP transition is quite simple. Let F(j) is the number of permutations with j good positions, then F(j) =  \\Sigma (f(n, j, k)) * (n - j)! (because there are n - j numbers left unchosen). However, there are cases we may form some extra good positions when putting these n - j numbers into our permutations, thus F(j) now stores the number of permutations with at least j good positions. But we want F(j) to be the number of permutations with exact j good positions, so we must exclude those permutations with more than j good positions. Let's do it in descending order. First F(n) must be the number of permutations with exact n good positions. Hence, we may calculate F(n - 1) based on F(n), then F(n - 2) based on F(n - 1) and F(n), and so on... The last part is to calculate how many times F(j) is repeatedly counted in F(i) (i < j), it's simply C(j, i) (the number of ways to choose i good positions from j good positions). The overall complexity is O(n^2).",
    "code": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nconst int BASE = int(1e9) + 7;\n\nlong long f[1010][1010][4], F[1010], c[1010][1010];\n\nvoid addMod(long long &x, long long y)\n{\n\tx += y; \n\tif (x >= BASE) x -= BASE;\n}\n\nint main()\n{\n\tint n, k;\n\tcin >> n >> k;\n\t\n\tfor (int i = 0; i <= n; i++)\n\t\tfor (int j = 0; j <= i; j++)\n\t\t\tc[i][j] = j ? (c[i - 1][j] + c[i - 1][j - 1]) % BASE : 1;\n\t\n\tf[0][0][2] = 1;\n\tfor (int i = 1; i <= n; i++)\n\t\tfor (int j = 0; j < i; j++)\n\t\t\tfor (int z = 0; z < 4; z++)\n\t\t\t{\n\t\t\t\tif (z & 1) addMod(f[i][j + 1][z / 2 + 2], f[i - 1][j][z]);\n\t\t\t\tif (i < n) addMod(f[i][j + 1][z / 2], f[i - 1][j][z]);\n\t\t\t\taddMod(f[i][j][z / 2 + 2], f[i - 1][j][z]);\n\t\t\t}\n\t\t\t\n\tfor (int j = 0; j <= n; j++)\n\t{\n\t\tfor (int z = 0; z < 4; z++) addMod(F[j], f[n][j][z]);\n\t\tfor (int k = 2; k <= n - j; k++) F[j] = F[j] * k % BASE;\n\t}\n\t\t\t\n\tfor (int i = n - 1; i >= 0; i--)\n\t\tfor (int j = i + 1; j <= n; j++)\n\t\t\taddMod(F[i], BASE - F[j] * c[j][i] % BASE);\n\t\t\t\n\tcout << F[k] << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "288",
    "index": "A",
    "title": "Polo the Penguin and Strings",
    "statement": "Little penguin Polo adores strings. But most of all he adores strings of length $n$.\n\nOne day he wanted to find a string that meets the following conditions:\n\n- The string consists of $n$ lowercase English letters (that is, the string's length equals $n$), exactly $k$ of these letters are distinct.\n- No two neighbouring letters of a string coincide; that is, if we represent a string as $s = s_{1}s_{2}... s_{n}$, then the following inequality holds, $s_{i} ≠ s_{i + 1}(1 ≤ i < n)$.\n- Among all strings that meet points 1 and 2, the required string is lexicographically smallest.\n\nHelp him find such string or state that such string doesn't exist.\n\nString $x = x_{1}x_{2}... x_{p}$ is lexicographically less than string $y = y_{1}y_{2}... y_{q}$, if either $p < q$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{p} = y_{p}$, or there is such number $r$ $(r < p, r < q)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} < y_{r + 1}$. The characters of the strings are compared by their ASCII codes.",
    "tutorial": "To solve this problem we need to find out some contruction of resulting string. But first of all, we need find out when there is no result. Obviously, if $k > n$, there is not result - you cannot build string of length $n$ with more than $n$ characters. Another one case is when $k = 1$ and $n > 1$ - there is no answer in that case also. Consider that $k = 2$. It's really easy to see that answer for such case is a string of form $abababab...$. To construct string for $k > 2$ you need to add some extra characters - $c, d, e...$. To make string lexicographically smallest, you need to add that characters as close to the end as we can. And the best bet here is $abbabab...abacdefgh...$. So, we need just to add characters $c, d, e, f...$ (i. e. $k - 2$ characters from $c$) to the end of the string.",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "288",
    "index": "B",
    "title": "Polo the Penguin and Houses ",
    "statement": "Little penguin Polo loves his home village. The village has $n$ houses, indexed by integers from 1 to $n$. Each house has a plaque containing an integer, the $i$-th house has a plaque containing integer $p_{i}$ ($1 ≤ p_{i} ≤ n$).\n\nLittle penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number $x$. Then he goes to the house whose number is written on the plaque of house $x$ (that is, to house $p_{x}$), then he goes to the house whose number is written on the plaque of house $p_{x}$ (that is, to house $p_{px}$), and so on.\n\nWe know that:\n\n- When the penguin starts walking from any house indexed from 1 to $k$, inclusive, he can walk to house number 1.\n- When the penguin starts walking from any house indexed from $k + 1$ to $n$, inclusive, he definitely cannot walk to house number 1.\n- When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.\n\nYou need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Since $k  \\le  8$ you can solve this problem using brute force. This means that you can recursively construct all possible $k^{k}$ possibilities of first $k$ assignments. (For $k = 8$ this is equal to $16 777 216$.) For each of that assignments you need to check whether it is correct or not (by problem statement). Ths can be simply done using loops. When you know the number of assignment for the first $k$ tables (let it be $f(k)$), all you need to do is to count the number of assignment for the rest $n - k$ plaques. Since there should bo no path to $1$, there should be no path to any of first $k$ houses, so at each plaque for houses from $k + 1$ to $n$ there can be any number from $k + 1$ to $n$, inclusive. There are $(n - k)^{n - k}$ such possibilities. And hence the total answer is $f(k)(n - k)^{n - k}$.",
    "tags": [
      "combinatorics"
    ],
    "rating": 1500
  },
  {
    "contest_id": "288",
    "index": "C",
    "title": "Polo the Penguin and XOR operation",
    "statement": "Little penguin Polo likes permutations. But most of all he likes permutations of integers from $0$ to $n$, inclusive.\n\nFor permutation $p = p_{0}, p_{1}, ..., p_{n}$, Polo has defined its beauty — number $(0\\oplus p_{0})+(1\\oplus p_{1})+\\cdot\\cdot\\cdot+(n\\oplus p_{n})$.\n\nExpression $x\\oplus y$ means applying the operation of bitwise excluding \"OR\" to numbers $x$ and $y$. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as \"^\" and in Pascal — as \"xor\".\n\nHelp him find among all permutations of integers from $0$ to $n$ the permutation with the maximum beauty.",
    "tutorial": "Since we need to maximize the result, we need to find such permutation, for which the least number of bit disappear. (We consider bit disappeared if it was 1 both in $i$ and $p_{i}$, so in $i\\oplus p_{i}$ it is 0). It turns out that for each $n$ there is such permutation that no bit disappear. How to build it? We will be solving problem by iterations while $n > 0$. On each iteration, we need to find the biggest (the leftmost in binary representation) bit which is not $0$ in binary representation of $n$ and denote it position (bits are numbered from 0) by $b$. Now we need to find integer $m$ - minimal integer from $0$ to $n$, inclusive, such that $b$-th bit is also $1$ in it. After that you can see (look image below), that at $m\\oplus(m-1)$ no bit disappear, at $(m+1)\\oplus(m-2)$ no bit disappear, ..., at $n\\oplus(m-(m-m+1))$ no bit disappear. So, it is good to assign exactly that integers to our permutation, i. e. $p_{m} = m - 1$ and $p_{m - 1} = m$, $p_{m + 1} = m - 2$ and $p_{m - 2} = m + 1$ and so on. After that assign value $m - (n - m + 1) - 1$ to $n$ and go to next iteration. Now when we know how to build permutation and that no bit disappear, the value of the answer is equal to $0+p_{0}+1+p_{1}+\\ldots+n+p_{n}={\\frac{n(n+1)}{2}}+{\\frac{n(n+1)}{2}}=n(n+1)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "288",
    "index": "D",
    "title": "Polo the Penguin and Trees ",
    "statement": "Little penguin Polo has got a tree — a non-directed connected acyclic graph, containing $n$ nodes and $n - 1$ edges. We will consider the tree nodes numbered by integers from 1 to $n$.\n\nToday Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of groups of four integers $a, b, c$ and $d$ such that:\n\n- $1 ≤ a < b ≤ n$;\n- $1 ≤ c < d ≤ n$;\n- there's no such node that lies on both the shortest path from node $a$ to node $b$ and from node $c$ to node $d$.\n\nThe shortest path betweem two nodes is the path that is shortest in the number of edges.\n\nHelp Polo solve this problem.",
    "tutorial": "As always in such problems, root our tree at some vertex, for example vertex with number 1. We need to find out, what will happen when we have already chosen one path. Obviously, after deleting all vertices and their edges from that path, tree will disintegrate in some set of trees. Denote their sizes by $c_{1}, c_{2}, ..., c_{k}$, where $k$ is the number of trees. Then the number of ways to choose the second path is equal to $\\begin{array}{r}{\\mathbf{c}_{1}*(c_{1}-1)}\\\\ {2}\\end{array}+\\mathbf{c}_{2}^{\\ast(c_{2}-1)}+\\ldots+{\\frac{c_{k}*(c_{k}-1)}{2}}$. This gives us $O(n^{2})$ solution - just to brute force all pathes and count the number of second paths by this formula. We need to do it in $O(n)$. To do so, dfs our graph and fix some vertex during dfs, we will consider this vertex as the last vertex in the first path. Now we need to find the sum of above formula for the rest of the vertex. Here you can separately solve this problem for all vertex inside subtree of current vertex and for the rest of the vertices. For subtree vertices, you can, after finding the answers for all vertices of subtree, find the answer for root of subtree. To do so, you need to iterate all edges from current vertex and sum up results for that vetices. Also you need to add the sum of values $\\frac{d|s u(t-1)}{2}$ multiplied by the number of vertices in subtree, where $d_{i}$ are all sizes of subtrees of vertices from current vertex, not including from current edge). You can use some partial sums of something like that to make it linear. For the rest of the vertices (not in subtree) it is actually similar, but a bit harder. Here you need to keep current result as a parameter of dfs and when you entering some vertex you should add some additional counts to the current sum (similarly as in first case).",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "288",
    "index": "E",
    "title": "Polo the Penguin and Lucky Numbers",
    "statement": "\\underline{Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.}\n\nPolo the Penguin have two positive integers $l$ and $r$ $(l < r)$, both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other.\n\nLet's assume that $n$ is the number of distinct lucky numbers, each of them cannot be greater than $r$ or less than $l$, and $a_{i}$ is the $i$-th (in increasing order) number of them. Find $a_{1}·a_{2} + a_{2}·a_{3} + ... + a_{n - 1}·a_{n}$. As the answer can be rather large, print the remainder after dividing it by $1000000007$ ($10^{9} + 7$).",
    "tutorial": "In this problem there are a lot of different formulas, most of them are for optimizing solution and making it lenear. Editorial shows just a general idea because it's pretty hard to explain all of them and good for you to derive it by yourself. If you have any questions - write them all in comments. Denote by $a_{1}, a_{2}, ..., a_{n}$ all lucky number from segment. First of all, we need to do reduce the problem a bit. Let we have some fixed digit $(pos, d)$, i. e. position of this digit is $pos$ (from 0 from right to left) and value is $d$ (4 or 7). Then, for all $a_{i}$ $(1  \\le  i < n$) such that $pos$-th digit of $a_{i}$ is equal to $d$, we need to add $a_{i + 1}  \\times  d  \\times  10^{pos}$ to the answer. Now we can see that problem can be reduced to the following. For each fixed digit $(pos, d)$ find the sum of all $a_{i}$ such that $a_{i + 1}$ on the $pos$-th position has digit $d$. Obviously, we can solve the problem for $1..l$ and $1..r$ separately and then subtract the first from the second - that will be the answer. How to find such sum among all lucky numbers of some length but less than some lucky number $x$? We will describe the general idea. Any lucky number, less than $x$ has some common prefix with $x$, then one digit is less than the corresponing in $x$ (i. e. it is 7 in $x$ and 4 in another integer) and the rest of the digits are arbitrary. So, by iterating all such positions where is the first digit less than in $x$, we can, using the fact that the rest of the digits are arbitrary and some formulas and precomputations, compute the results for each position and digit.",
    "tags": [
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "289",
    "index": "A",
    "title": "Polo the Penguin and Segments ",
    "statement": "Little penguin Polo adores integer segments, that is, pairs of integers $[l; r]$ $(l ≤ r)$.\n\nHe has a set that consists of $n$ integer segments: $[l_{1}; r_{1}], [l_{2}; r_{2}], ..., [l_{n}; r_{n}]$. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform $[l; r]$ to either segment $[l - 1; r]$, or to segment $[l; r + 1]$.\n\nThe value of a set of segments that consists of $n$ segments $[l_{1}; r_{1}], [l_{2}; r_{2}], ..., [l_{n}; r_{n}]$ is the number of integers $x$, such that there is integer $j$, for which the following inequality holds, $l_{j} ≤ x ≤ r_{j}$.\n\nFind the minimum number of moves needed to make the value of the set of Polo's segments divisible by $k$.",
    "tutorial": "First of all, we need to count, how many integers are inside given segments at the beginning. Since they don't intersect and even touch, no integer point can belong to more than one segment at the same time. This mans that starting value of segments is $p\\ {\\stackrel{\\mathrm{def}}{=}}\\left(r_{1}-l_{1}+1\\right)+\\left(r_{2}-l_{2}+1\\right)+\\ldots+\\left(r_{n}-l_{n}+1\\right)$. If $k$ divides $p$, then answer is $0$ - we don't need to do anything, it's already done. But if it's not true, we need to know the minimal number of turns to make $k$ divisor of $p$. Since we can in single turn increase $p$ by 1 (by decreasing the left point of the leftmost segment), this number is equal to $k-(p\\ {\\mathrm{mod}}\\ k)$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "289",
    "index": "B",
    "title": "Polo the Penguin and Matrix",
    "statement": "Little penguin Polo has an $n × m$ matrix, consisting of integers. Let's index the matrix rows from 1 to $n$ from top to bottom and let's index the columns from 1 to $m$ from left to right. Let's represent the matrix element on the intersection of row $i$ and column $j$ as $a_{ij}$.\n\nIn one move the penguin can add or subtract number $d$ from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.",
    "tutorial": "First of all, we need to know when the answer is -1. For that you should notice that after any operation on number $z$, value $z\\ {\\mathrm{mod}}\\ d$ doesn't change. Indeed, $z_{\\textrm{m o d}}d=(z+d)\\;\\;\\mathrm{mod}\\;=(z-d)\\;\\;\\mathrm{mod}\\;d$. This means that there is not answer if there are two different points for which $a_{i j}\\mod d$ is diffrent. Now we can transform our problem a bit. We can just write down all integers from matrix $n  \\times  m$ to one array $b$ of size $k = n  \\times  m$ and sort them all in non-decreasing order. It is not hard to notice that in some of the optimal solutions, all number are at the end equal to one of the number for starting array. But also, it is optimal to make all number equal to $b[\\underline{{k}}_{2}+1]$ (median element). Why to median? Suppose that we make all numbers equal to non-median element with index $x$. Then if $|x - (k - x)| > 1$ (i. e. from one side there are more elements than from another + 1). So, by moving out element more to median, we can make result better. After we know, to which number we should bring all, the answer is just $|b_{1}-b[\\frac{k}{2}+1]|+|b_{2}-b[\\frac{k}{2}+1]|+...+|b_{k}-b[\\frac{k}{2}+1]|$, divided by $d$.",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "sortings",
      "ternary search"
    ],
    "rating": 1400
  },
  {
    "contest_id": "293",
    "index": "A",
    "title": "Weird Game",
    "statement": "Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.\n\nRoman leaves a word for each of them. Each word consists of $2·n$ binary characters \"0\" or \"1\". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to $2·n$, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string.\n\nLet's represent Yaroslav's word as $s = s_{1}s_{2}... s_{2n}$. Similarly, let's represent Andrey's word as $t = t_{1}t_{2}... t_{2n}$. Then, if Yaroslav choose number $k$ during his move, then he is going to write out character $s_{k}$ on the piece of paper. Similarly, if Andrey choose number $r$ during his move, then he is going to write out character $t_{r}$ on the piece of paper.\n\nThe game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.\n\nYou are given two strings $s$ and $t$. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.",
    "tutorial": "The first observation - we don't care about the actual strings, all information we need - number of pairs {0,0}, {0,1}, {1,0}, {1,1}. Count that and then just follow the greedy algorithm, for the first player: try to get a index with {1,1} if there are some, than {1,0}, than {0,1} and than {0,0}. For the second player similar strategy: first {1,1}, than {0,1}, than {1,0}, than {0,0}. After that just compare who has more 1.",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "293",
    "index": "B",
    "title": "Distinct Paths",
    "statement": "You have a rectangular $n × m$-cell board. Some cells are already painted some of $k$ colors. You need to paint each uncolored cell one of the $k$ colors so that any path from the upper left square to the lower right one doesn't contain any two cells of the same color. The path can go only along side-adjacent cells and can only go down or right.\n\nPrint the number of possible paintings modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Every path from the topleft cell to the bottomright cell contain exactly $n + m - 1$ cells. And all of the should be of different color. So $n + m - 1  \\le  k$. Due to the small constraints for k we may assume that bruteforce might work. The only optimization to get the correct solution is some canonization of the colors. So let's go over all of the cells in some order and color them but with following condition. If i > j, than color i appeared later than color j. If we bruteforce in such way we will have about 1 million different patterns for max case. Than just match them with already painted cells and calculate for each pattern how many different permutations of color we can apply to it.",
    "tags": [
      "brute force",
      "combinatorics"
    ],
    "rating": 2700
  },
  {
    "contest_id": "293",
    "index": "C",
    "title": "Cube Problem",
    "statement": "Yaroslav, Andrey and Roman love playing cubes. Sometimes they get together and play cubes for hours and hours!\n\nToday they got together again and they are playing cubes. Yaroslav took unit cubes and composed them into an $a × a × a$ cube, Andrey made a $b × b × b$ cube and Roman made a $c × c × c$ cube. After that the game was finished and the guys left. But later, Vitaly entered the room. He saw the cubes and wanted to make a cube as well. But what size should the cube be? Of course it should be a large cube with the side of length $a + b + c$. Besides, Vitaly decided to decompose the cubes built by Yaroslav, Andrey and Roman and compose his own large cube out of them. However, it turned out that the unit cubes he got from destroying the three cubes just weren't enough to make a large cube. We know that Vitaly was short of exactly $n$ cubes. Vitaly got upset, demolished everything and left. As he was leaving, he met Petya and told him that there had been three cubes in the room and that he needed another $n$ unit cubes to make his own large cube.\n\nPetya entered the room and saw the messily scattered cubes. He wanted to make it neat and orderly again. But he only knows that there had been three cubes, made of small unit cubes and that Vitaly needed $n$ more unit cubes to make a large one! Help Petya understand, how many ways of sizes $a$, $b$, $c$ are there to restore Yaroslav's, Andrey's and Roman's cubes.",
    "tutorial": "After reading the problem statement one can understand that all we need is to calculate the number of positive integer solutions of equation: $(a + b + c)^{3} - a^{3} - b^{3} - c^{3} = n$. The key observation is: $3(a + b)(a + c)(b + c) = (a + b + c)^{3} - a^{3} - b^{3} - c^{3}$, after that simply calculate all divisors of $\\frac{n}{3}$ and then first go over all $x = a + b$, such that $x^{3}\\leq{\\frac{n}{3}}$ then go over all $y = (a + c)  \\ge  x$, such that $x y^{2}\\leq{\\frac{n}{3}}$ and then determine $z = (b + c)$, such that $x y z={\\frac{n}{3}}$. After that we need to solve the system $a + b = x, a + c = y, b + c = z$ and find out how many solutions it adds.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "293",
    "index": "D",
    "title": "Ksusha and Square",
    "statement": "Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles.\n\nToday Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the polygon and then draws a square with two opposite vertices lying in the chosen points, what will the expectation of this square's area be?\n\nA pair of distinct points is chosen uniformly among all pairs of distinct points, located inside or on the border of the polygon. Pairs of points $p, q$ $(p ≠ q)$ and $q, p$ are considered the same.\n\nHelp Ksusha! Count the required expectation.",
    "tutorial": "We can see that we asked to calculate $\\sum2((x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2})$ for all integer points inside the polygon or on its border. We can see that we can process Xs and Ys independently. For each $x$ determine $y_{left}$, $y_{right}$, such that all points $(x, y)$ where $y_{left}  \\le  y  \\le  y_{right}$ are inside the polygon and the range $[y_{left}, y_{right}]$ is as maximal as possible. Now let's assume that we have $a_{1}, a_{2}, ..., a_{k}$ different points with fixed x coordinate ($a_{1}$ stands for $x = - 10^{6}$, $a_{2}$ for $x = - 10^{6} + 1$ and so on). Now the required answer is $a_{2}a_{1} + a_{3}(a_{2} + 2^{2}a_{1}) + a_{4}(a_{3} + 2^{2}a_{2} + 3^{2}a_{1}) + ...$ We can see that: $(a_{2} + 2^{2}a_{1}) - a_{1} = a_{2} + 3a_{1}$, $(a_{3} + 2^{2}a_{2} + 3^{2}a_{1}) - (a_{2} + 2^{2}a_{1}) = a_{3} + 3a_{2} + 5a_{1}$, and so on. So we can precalculate partial sums like $a_{2} + 3a_{1}$, $a_{3} + 3a_{2} + 5a_{1}$, $a_{4} + 3a_{3} + 5a_{2} + 7a_{1}$ (the difference between two consecutive sums is $2(a_{i} + ... + a_{1})$, so we can do that in $O(k)$ time). After this precomputation we just need to sum the results.",
    "tags": [
      "geometry",
      "math",
      "probabilities",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "293",
    "index": "E",
    "title": "Close Vertices",
    "statement": "You've got a weighted tree, consisting of $n$ vertices. Each edge has a non-negative weight. The length of the path between any two vertices of the tree is the number of edges in the path. The weight of the path is the total weight of all edges it contains.\n\nTwo vertices are close if there exists a path of length at most $l$ between them and a path of weight at most $w$ between them. Count the number of pairs of vertices $v, u$ $(v < u)$, such that vertices $v$ and $u$ are close.",
    "tutorial": "Let's assume that we have a data structure which can perform such operations as: - add point (x,y) to the structure; shift all points in the structure by vector (dx,dy); answer how many point (x,y) are in the structure where $x  \\le  x_{bound}$, $y  \\le  y_{bound}$; get all elements which are now in the structure; For every vertex of the tree we will store the pointer to such structure. How we update the structures. We will proceed all the vertices in dfs order, if we are in a leaf node, than we create structure which contains only one element (0,0). Otherwise we will sort the children structures by it's size in decreasing order and assign the pointer of the biggest structure to the pointer of the current vertex (Don't forget to shift the structure by (1, weight of edge)). After that we will go over all other children one by one and do the following thing: Shift the structure by (1, weight of edge); Get all elements from the structure; For every element (x,y) answer the query $x_{bound} = L - x$, $y_{bound} = W - y$ (we use parent's structure); Add elements one by one into the structure; After that answer the query $x_{bound} = L, y_{bound} = W$ and add element (0,0). The sum of the results of all the queries is our answer. It's easy to see that there will be no more than $O(N\\log N)$ queries and add operations. The remaining part is designing the structure. It can be done in many ways. One of the ways: We have small structures with sizes equals to powers of two; Each structure - it's two-dimensional segments tree; We can add one element in a following way: if there is no substructure with size 1, than add it; else get structures with sizes $1, 2, 4, ..., 2^{k}$ and all its' elements and rebuild the structure with size $2^{k + 1}$; Shifting - just remember shifting vector for every substructure; Answering the query - go over all substructures and add the results.",
    "tags": [
      "data structures",
      "divide and conquer",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "294",
    "index": "A",
    "title": "Shaass and Oskols",
    "statement": "Shaass has decided to hunt some birds. There are $n$ horizontal electricity wires aligned parallel to each other. Wires are numbered $1$ to $n$ from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are $a_{i}$ oskols sitting on the $i$-th wire.\n\nSometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the $i$-th wire). Consequently all the birds on the $i$-th wire to the left of the dead bird get scared and jump up on the wire number $i - 1$, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number $i + 1$, if there exists no such wire they fly away.\n\nShaass has shot $m$ birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.",
    "tutorial": "In this problem you just have to now how many birds are there on each wire after each shot. A good trick for the first and the last wire would be to define wires $0$ and $n + 1$. In this way the birds that fly away sit on these wires and you don't need to worry about accessing some element outside the range of your array.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "294",
    "index": "B",
    "title": "Shaass and Bookshelf",
    "statement": "Shaass has $n$ books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the $i$-th book is $t_{i}$ and its pages' width is equal to $w_{i}$. The thickness of each book is either $1$ or $2$. All books have the same page heights.\n\nShaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure.\n\nHelp Shaass to find the minimum total thickness of the vertical books that we can achieve.",
    "tutorial": "As said in the statement, the thickness of each book is either 1 or 2. Think about when we want to arrange $v_{1}$ books of thickness 1 and $v_{2}$ books of thickness $2$ vertically and arrange all other $n - v_{1} - v_{2}$ books horizontally above them to achieve a configuration with total thickness of vertical books equal to $v_{1} + 2v_{2}$. Is it possible to find such arrangement? Because the total thickness of vertical books is fixed it's good to calculate the minimum possible total width of horizontal books. As the width of a book doesn't matter in vertical arrangement it's good to use the books with shorter width horizontally and the ones with longer width vertically. So pick out $v_{1}$ books with longest width among books of thickness 1 and do the same with books of thickness 2. The sum of width of $n - v_{1} - v_{2}$ remaining books should be at most $v_{1} + 2v_{2}$. The solution would be to try the things we explained above for all possible values of $v_{1}$ and $v_{2}$. And print the best answer. :) There exists other ways to solve this problem mostly using dynamic programming but this was the intended solution of the problem.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "294",
    "index": "C",
    "title": "Shaass and Lights",
    "statement": "There are $n$ lights aligned in a row. These lights are numbered $1$ to $n$ from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on.\n\nHe knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo $1000000007 (10^{9} + 7)$.",
    "tutorial": "I just want to solve the third sample of this problem for you and you can figure out the rest by yourself. :) The third sample is ...#...#... where # is a switched on lamp and . is a switched off lamp. As you can see we have three different types of lights. The first three lights (Type A), the 5th to 8th lights (Type B) and the last three lights (Type C). We have to switch on the lights three times for each type of lights. Aside from the order of moves for each type there are $\\frac{0\\}}{3!_{\\ast}^{\\dagger}{\\hat{\\jmath}}_{\\pm}^{\\dagger}{\\hat{\\jmath}}_{\\pm}^{\\dagger}}$ possible permutations of the string AAABBBCCC which tells us how to combine the steps of different types. Switching on the lights is done uniquely for types 1 and 3. But for type 2 each time we have to possible options until we're left with one off light. So there are $2^{3 - 1}$ ways to do this. So the answer would be 1680*1*4*1 = 6720. The general solution would be to find all groups off consecutive switched off lamps and calculate the number of ways to combine all these groups. Then for each group you should calculate in how many ways it can be solved.",
    "tags": [
      "combinatorics",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "296",
    "index": "A",
    "title": "Yaroslav and Permutations",
    "statement": "Yaroslav has an array that consists of $n$ integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.\n\nHelp Yaroslav.",
    "tutorial": "Note that after applying the operations of the exchange, we can get any permutation of numbers. Not difficult to understand that the answer is \"YES\", if you can place a single number that it would not stand in the neighboring cells. Thus, if a some number is meeted C times, it must fulfill the condition C <= (n+1) / 2.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "297",
    "index": "A",
    "title": "Parity Game",
    "statement": "You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character \"0\" and \"1\") $a$ and $b$. Then you try to turn $a$ into $b$ using two types of operations:\n\n- Write $parity(a)$ to the end of $a$. For example, $1010\\to10100$.\n- Remove the first character of $a$. For example, $1001\\rightarrow001$. You cannot perform this operation if $a$ is empty.\n\nYou can use as many operations as you want. The problem is, is it possible to turn $a$ into $b$?\n\nThe $parity$ of a 01-string is $1$ if there is an odd number of \"1\"s in the string, and $0$ otherwise.",
    "tutorial": "Obv 1: If $a$ has odd parity, we can apply operation 1 to increase its number of 1s by $1$. Obv 2: If $a$ has even parity, its number of 1s cannot increase anymore. Claim: If the number of 1s in $a$ is not fewer than those in $b$, we can always turn $a$ to $b$ The idea is to make a copy of $b$ at the right of $a$. Lets assume $a$ starts with even parity. If we need a $0$, simply apply operation 1. If we need a $1$, keep remove from the head until we removed an 1. Notice that we never remove digits from 'new part' of $a$. Now the parity of $a$ will be odd and we can apply operation 1. After that, the parity of $a$ becomes even again, the number of $1$ in the 'old part' of $a$ decrease by $1$ and we handle a $1$ in $b$. Finally, remove the remaining old part of $a$ and we get $b$. Combine all those facts, we can conclude that we can turn $a$ into $b$ if and only if $countOnes(a) + parity(countOnes(a))  \\ge  countOnes(b)$",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1700
  },
  {
    "contest_id": "297",
    "index": "B",
    "title": "Fish Weight",
    "statement": "It is known that there are $k$ fish species in the polar ocean, numbered from $1$ to $k$. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the $i$-th type of fish be $w_{i}$, then $0 < w_{1} ≤ w_{2} ≤ ... ≤ w_{k}$ holds.\n\nPolar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a \\textbf{strictly larger} total weight than Bob's. In other words, does there exist a sequence of weights $w_{i}$ (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?",
    "tutorial": "First we sort $a$ and $b$ in non-increasing order. We claim that the answer is YES if and only if exists $a$ is lexicographically larger than $b$. $(\\leftarrow)$ If $a$ is not lexicographcally larger than $b$, that means for every $i$, $a_{i}  \\le  b_{i}$. That implies for every fish Alice has, there is a corresponding fish Bob has and is as heavy as Alice's. $(\\Rightarrow)$ Let $i$ be the smallest index such that $a_{i} > b_{i}$. We can amplify the gap between $w_{ai}$ and $w_{bi}$ as large as we want to make Alice wins.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "297",
    "index": "C",
    "title": "Splitting the Uniqueness",
    "statement": "Polar bears like unique arrays — that is, arrays without repeated elements.\n\nYou have got a unique array $s$ with length $n$ containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays $a$ and $b$ that are also of length $n$, with the following conditions for all $i$ $(1 ≤ i ≤ n)$:\n\n- $a_{i}, b_{i}$ are non-negative integers;\n- $s_{i} = a_{i} + b_{i}$ .\n\nIdeally, $a$ and $b$ should also be unique arrays. However, life in the Arctic is hard and this is not always possible. Fortunately, Alice and Bob are still happy if their arrays are almost unique. We define an array of length $n$ to be almost unique, if and only if it can be turned into a unique array by removing no more than $\\textstyle\\bigcap{\\frac{22}{3}}\\setminus$ entries.\n\nFor example, the array $[1, 2, 1, 3, 2]$ is almost unique because after removing the first two entries, it becomes $[1, 3, 2]$. The array $[1, 2, 1, 3, 1, 2]$ is not almost unique because we need to remove at least $3$ entries to turn it into a unique array.\n\nSo, your task is to split the given unique array $s$ into two almost unique arrays $a$ and $b$.",
    "tutorial": "An equivalent definition for almost unique, is an array with at least $ \\lfloor  2n / 3 \\rfloor $ different elements. The idea is to split $s$ into three parts: In the first part, we give uniqueness to $a$. In the second part, we give uniqueness to $b$. In the third part, we give uniqueness to both. Lets assume $s$ is sorted. Since $s$ is an unique array, we know $s_{i}  \\ge  i$ for all $i$ (0-based). The image below will give some intuition on how we are going to split it. $a$ is red, $b$ is blue, the length of the bar represent the magnitude of the number. In the first and second part, we do not care about the array that we are not giving uniqueness to. For exampmle, if $n = 30$: $i = 0... 9:$ assign $a_{i} = i$ (do not care values of $b$) $i = 10... 19:$ assign $b_{i} = i$ (do not care values of $a$) $i = 20... 29:$ assign $b_{i} = 29 - i$ and set $a_{i} = s_{i} - b_{i}$. From $i = 20$, $a$ will have strictly increasing values starting from at least $11$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2400
  },
  {
    "contest_id": "297",
    "index": "D",
    "title": "Color the Carpet",
    "statement": "Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height $h$ and width $w$. Then the grid is divided into $h × w$ squares. Alice is going to assign one of $k$ different colors to each square. The colors are numbered from 1 to $k$. She may choose not to use all of the colors.\n\nHowever, there are some restrictions. For every two adjacent squares (squares that shares an edge) $x$ and $y$, there is a color constraint in one of the forms:\n\n- $color(x) = color(y)$, or\n- $color(x) ≠ color(y)$.\n\nExample of the color constraints:\n\nIdeally, Alice wants to satisfy all color constraints. But again, life in the Arctic is hard. It is not always possible to satisfy all color constraints. Fortunately, she will still be happy if at least $\\textstyle{\\frac{3}{4}}$ of the color constraints are satisfied.\n\nIf she has $4$ colors she can color the carpet in the following way:\n\nAnd she is happy because $\\textstyle{\\frac{13}{17}}$ of the color constraints are satisfied, and ${\\frac{13}{17}}\\geq{\\frac{3}{4}}$. Your task is to help her color the carpet.",
    "tutorial": "For $k = 1$ there is only one coloring so we just need to check the number of $=$ constraints. When $k  \\ge  2$, it turns out that using only $2$ colors is always sufficient to satisfy at least $3 / 4$ of the constraints. Lets assume $w  \\ge  h$ (rotate if not). We will call the constraints that involves cells in different row \"vertical constraints\", and similar for \"horizontal constraints\". First we color the first row such that all horizontal constraints in row $1$ are satisfied. We will color the remaining rows one by one. To color row $i$, first we color it such that all horizontal constraints in row $i$ are satisfied. Then consider the vertical constraints between row $i$ and row $i - 1$. Count the number of satisfied and unsatisfied vertical constraints. If there are more unsatisfied constraints than satisfied constraints, flip the coloring of row $i$. Flipping a row means turning $2211212  \\rightarrow  1122121$, for example. If we flip the coloring of row $i$, all horizontal constraints in row $i$ are still satisfied, but for the vertical constraints between row $i$ and row $i - 1$, satisfied will turn to unsatisfied, unsatisfied will turn to satisfied. Therefore, we can always satisfy at least half the vertical constraints between row $i$ and row $i - 1$. The number of unsatisfied constraints is at most $(h - 1)  \\times   \\lfloor  w / 2 \\rfloor $, which is at most $1 / 4$ of the total number of constraints (recall $w  \\ge  h$).",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2500
  },
  {
    "contest_id": "297",
    "index": "E",
    "title": "Mystic Carvings",
    "statement": "The polar bears have discovered a gigantic circular piece of floating ice with some mystic carvings on it. There are $n$ lines carved on the ice. Each line connects two points on the boundary of the ice (we call these points endpoints). The endpoints are numbered $1, 2, ..., 2n$ counter-clockwise along the circumference. No two lines share an endpoint.\n\nNow a group of 6 polar bears (Alice, Bob, Carol, Dave, Eve, Frank) are going to build caves on the endpoints. Each polar bear would build a cave and live in it. No two polar bears can build a cave on the same endpoints. Alice and Bob is a pair of superstitious lovers. They believe the lines are carved by aliens (or humans, which are pretty much the same thing to polar bears), and have certain spiritual power. Therefore they want to build their caves on two endpoints which are connected by a line. The same for Carol and Dave, Eve and Frank.\n\nThe distance between two caves X and Y is defined as one plus minimum number of other caves one need to pass through in order to travel from X to Y along the boundary of the ice (endpoints without caves are not counted).\n\nTo ensure fairness, the distances between the three pairs of lovers have to be the same (that is, the distance between Alice and Bob, the distance between Carol and Dave, and the distance between Eve and Frank are the same).\n\nThe figures below show two different configurations, where the dots on the circle are the endpoints. The configuration on the left is not valid. Although each pair of lovers (A and B, C and D, E and F) is connected a line, the distance requirement is not satisfied. The distance between A and B is 2 (one can go from A to B in the clockwise direction passing through F). The distance between E and F is also 2. However, the distance between C and D is 1 (one can go from C to D in the counter-clockwise direction without passing through any other caves). The configuration on the right is valid. All three pairs have the same distance 1.\n\nCount the number of ways to build the caves under the requirements. Two configurations are considered the same if the same set of 6 endpoints are used.",
    "tutorial": "For any three lines, they can intersect in one of the following 5 ways: The problem is asking for the number of Type 2 or Type 5. Some of these configs are easy to count (e.g. Type 1), some are not. To count the number of Type 1, we can exhaust the middle line with index $i$, and count the number of lines on the right of the middle line (let it be $x_{i}$) and on the left of the middle line (let it be $y_{i}$), then the number of Type 1 with that middle line is given by $x_{i}y_{i}$. There are several methods to calculate $x_{i}$ efficiently. One of them is to process the endpoints in counter clockwise order (let the current endpoint be $k$), and use a segment tree or binary indexed tree to keep track of the number of lines $(a_{i}, b_{i}), a_{i} < b_{i}$ with $l  \\le  a_{i} < b_{i}  \\le  k$ for different $l$. Let $j$ be the line with $b_{j} = k$, then to find the number of lines with $a_{j} < a_{i} < b_{i} < b_{j}$, we just need to query the count at $a_{j}$, then update the binary indexed tree by adding one to the position $a_{j}$. In the actual implementation, we need to consider that the endpoints are wrapped circularly as well. Unfortunately, Type 2 and Type 5 are the difficult ones. But we are only asked to find the total number of Type 2 and Type 5, which is (number of triples of lines) - (number of Type 1, 3 and 4). The problem then reduces to finding the total number of Type 3 and 4 (namely \"We cannot give a 囧 without an XD and a HA\"). Note that Type 3 and 4 shares a characteristic that two of the lines (the X in Type 3, and the two vertical lines in Type 4) has exactly one intersection with one of the other two lines. Therefore we can find the number of Type 3 and 4 by iterating through the lines, then count the number of lines on the right ($x_{i}$), on the left ($y_{i}$), and intersecting the considered line ($z_{i} = n - 1 - x_{i} - y_{i}$), and give the number of Type 3 and 4 as the sum of $z_{i}(x_{i} + y_{i})$. After removing double counting, we can get the answer.",
    "tags": [
      "data structures"
    ],
    "rating": 3000
  },
  {
    "contest_id": "298",
    "index": "A",
    "title": "Snow Footprints",
    "statement": "There is a straight snowy road, divided into $n$ blocks. The blocks are numbered from 1 to $n$ from left to right. If one moves from the $i$-th block to the $(i + 1)$-th block, he will leave a right footprint on the $i$-th block. Similarly, if one moves from the $i$-th block to the $(i - 1)$-th block, he will leave a left footprint on the $i$-th block. If there already is a footprint on the $i$-th block, the new footprint will cover the old one.\n\nAt the beginning, there were no footprints. Then polar bear Alice starts from the $s$-th block, makes a sequence of moves and ends in the $t$-th block. It is known that Alice never moves outside of the road.\n\nYou are given the description of Alice's footprints. Your task is to find a pair of possible values of $s, t$ by looking at the footprints.",
    "tutorial": "The starting position can be anywhere with a footprint. The footprints can be categorized into 3 types. only $L$ s only $R$ s $R$ s followed by $L$ s In case 1, we end in the left of all footprints. In case 2, we end in the right of all footprints. In case 3, we either end in the rightmost $R$ or the leftmost $L$",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "298",
    "index": "B",
    "title": "Sail",
    "statement": "The polar bears are going fishing. They plan to sail from $(s_{x}, s_{y})$ to $(e_{x}, e_{y})$. However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at $(x, y)$.\n\n- If the wind blows to the east, the boat will move to $(x + 1, y)$.\n- If the wind blows to the south, the boat will move to $(x, y - 1)$.\n- If the wind blows to the west, the boat will move to $(x - 1, y)$.\n- If the wind blows to the north, the boat will move to $(x, y + 1)$.\n\nAlternatively, they can hold the boat by the anchor. In this case, the boat stays at $(x, y)$. Given the wind direction for $t$ seconds, what is the earliest time they sail to $(e_{x}, e_{y})$?",
    "tutorial": "We can simply move by greedy method - only moves when it takes the boat closer to the destination.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "299",
    "index": "A",
    "title": "Ksusha and Array",
    "statement": "Ksusha is a beginner coder. Today she starts studying arrays. She has array $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers.\n\nHer university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!",
    "tutorial": "If $a_{i}$ divide $a_{j}$ than $a_{i}  \\le  a_{j}$. So the number which will divide every other number should be less than or equal to every other number, so the only possible candidate - it's the minimum in the array. So just check whether all elements are divisible by the minimal one",
    "tags": [
      "brute force",
      "number theory",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "299",
    "index": "B",
    "title": "Ksusha the Squirrel",
    "statement": "Ksusha the Squirrel is standing at the beginning of a straight road, divided into $n$ sectors. The sectors are numbered 1 to $n$, from left to right. Initially, Ksusha stands in sector 1.\n\nKsusha wants to walk to the end of the road, that is, get to sector $n$. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.\n\nKsusha the squirrel keeps fit. She can jump from sector $i$ to any of the sectors $i + 1, i + 2, ..., i + k$.\n\nHelp Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?",
    "tutorial": "Easy to see, that Ksusha is unable to complete her journey if there is a sequence of consecutive # with length more than k.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "300",
    "index": "A",
    "title": "Array",
    "statement": "Vitaly has an array of $n$ distinct integers. Vitaly wants to divide this array into three \\textbf{non-empty} sets so as the following conditions hold:\n\n- The product of all numbers in the first set is less than zero $( < 0)$.\n- The product of all numbers in the second set is greater than zero $( > 0)$.\n- The product of all numbers in the third set is equal to zero.\n- Each number from the initial array must occur in exactly one set.\n\nHelp Vitaly. Divide the given array.",
    "tutorial": "In this problem you just need to implement following algorithm. Split input data into 3 vectors: first will contain negative numbers, second positive numbers, third zeroes. If size of first vector is even move one number from it to the third vector. If second vector is empty, then move two numbers from first vector to the second vector. This solution works in $O(n)$.",
    "code": "#include <cstdio>\n#include <vector>\n \nusing namespace std;\nvector <int> first, second, third; \nint main () {\n    int n;\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++) {\n        int a;\n            scanf(\"%d\", &a);\n        if (a == 0)\n         third.push_back(a);\n        if (a > 0) \n            second.push_back(a);\n        if (a < 0) \n            first.push_back(a);\n    }\n    if (second.size() == 0) {\n        for(int i = 0; i < 2; i++)\n                      second.push_back(first.back()), first.pop_back();\n    }\n    if (first.size() % 2 == 0) {\n        third.push_back(first.back());\n        first.pop_back();\n    }\n    printf(\"%d\", first.size());\n    for(int i = 0; i < first.size(); i++) {\n        printf(\" %d\",first[i]); \n    }\n    printf(\"\n%d\", second.size()); \n    for(int i = 0; i < second.size(); i++) {\n        printf(\" %d\", second[i]);\n    }\n    printf(\"\n%d\", third.size());\n    for(int i = 0; i < third.size(); i++) {\n        printf(\" %d\", third[i]);\n    }\n    puts(\"\");\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "300",
    "index": "B",
    "title": "Coach",
    "statement": "A programming coach has $n$ students to teach. We know that $n$ is divisible by $3$. Let's assume that all students are numbered from $1$ to $n$, inclusive.\n\nBefore the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the $i$-th student wants to be on the same team with the $j$-th one, then the $j$-th student wants to be on the same team with the $i$-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the $i$-th student wants to be on the same team with the $j$-th, then the $i$-th and the $j$-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.\n\nHelp the coach and divide the teams the way he wants.",
    "tutorial": "Input data represents a graph. If there is a connected component with at least $4$ vertexes, then answer is $- 1$. Every connected component with $3$ vertexes is a complete team. Other teams are made from $1$ or $2$-vertex components. If amount of $2$-vertex components is greater than $1$-vertex answer is $- 1$. Otherwise match $2$-vertex components with $1$-vertex. If there are some $1$-vertex components left then split them into groups of three. This algorithm works in $O(n + m)$. Also you could implement $O(n^{4})$ solution.",
    "code": "#define _CRT_SECURE_NO_DEPRECATE\n#define _SECURE_SCL 0\n#pragma comment(linker, \"/STACK:300000000\")\n \n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <complex>\n#include <ctime>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <deque>\n#include <functional>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <map>\n#include <memory.h>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <utility>\n#include <cmath>\nusing namespace std;\n \n#define pb push_back\n#define mp make_pair\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n \n#define forn(i,n) for (int i=0; i<int(n); ++i)\n#define fornd(i,n) for (int i=int(n)-1; i>=0; --i)\n#define forab(i,a,b) for (int i=int(a); i<int(b); ++i)\n \ntypedef long long ll;\ntypedef long double ld;\ntypedef unsigned long long ull;\n \nconst int INF = (int) 1e9;\nconst long long INF64 = (long long) 1e18;\nconst long double eps = 1e-9;\nconst long double pi = 3.14159265358979323846;\n \nint g[50][50], n, m;\nbool used[50];\n \nvector <int> cur;\n \nvector <vector <int> > c[50];\n \nvoid dfs(int v){\n    used[v] = true;\n    cur.pb(v);\n    for (int i=1; i<=n; i++)\n        if (g[v][i] && !used[i])\n            dfs(i);\n}\n \nint main(){\n#ifdef dudkamaster\n    freopen(\"input.txt\",\"rt\",stdin);\n    freopen(\"output.txt\",\"wt\",stdout);\n#endif\n    memset(g, 0, sizeof(g));\n    memset(used, 0, sizeof(used));\n    cin >> n >> m;\n    for (int i=0; i<m; i++){\n        int a,b;\n        cin >> a >> b;\n        g[a][b] = g[b][a] = 1;\n    }\n    for (int i=1; i<=n; i++){\n        if (!used[i]){\n            cur.clear();\n            dfs(i);\n            c[sz(cur)].pb(cur);\n        }\n    }\n    vector <vector <int> > out = c[3];\n    for (int i=4; i<50; i++){\n        if (sz(c[i])!=0){\n            cout << -1;\n            return 0;\n        }\n    }\n    if (sz(c[2])>sz(c[1])){\n        cout << -1;\n        return 0;\n    }\n    if ((sz(c[1])-sz(c[2])) % 3 != 0){\n        cout << -1;\n        return 0;\n    }\n    forn(i,sz(c[2])){\n        vector <int> tout;\n        tout.pb(c[2][i][0]);\n        tout.pb(c[2][i][1]);\n        tout.pb(c[1][i][0]);\n        out.pb(tout);\n    }\n    for (int i=sz(c[2]); i<sz(c[1]); i += 3){\n        vector <int> tout;\n        forn(j,3)\n            tout.pb(c[1][i+j][0]);\n        out.pb(tout);\n    }\n    forn(i,n/3){\n        forn(j,3)\n            cout << out[i][j] << ' ';\n        cout << endl;\n    }\n            \n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "300",
    "index": "C",
    "title": "Beautiful Numbers",
    "statement": "Vitaly is a very weird man. He's got two favorite digits $a$ and $b$. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits $a$ and $b$. Vitaly calls a good number excellent, if the sum of its digits is a good number.\n\nFor example, let's say that Vitaly's favourite digits are $1$ and $3$, then number $12$ isn't good and numbers $13$ or $311$ are. Also, number $111$ is excellent and number $11$ isn't.\n\nNow Vitaly is wondering, how many excellent numbers of length exactly $n$ are there. As this number can be rather large, he asks you to count the remainder after dividing it by $1000000007$ $(10^{9} + 7)$.\n\nA number's length is the number of digits in its decimal representation without leading zeroes.",
    "tutorial": "Let's $MOD = 1000000007$. Let's precalc factorial values modulo $MOD$. $fact[i] = i!%MOD$, $\\forall i\\leq100000$. Let $i$ be an amount of digits equal to $a$ in current excellent number. In this case we can find sum of digits in this number: $sum = ai + b(n - i)$. If $sum$ is good, then add $C[n][i]$ to answer. In this problem it's impossible to calculate binomial coefficients using Pascal's triangle, because of large $n$. However it can be done this way $C[n][i] = fact[n]inv(fact[n - i]fact[i])$. $inv(a)$ is multiplicative inverse element(modulo $MOD$). $MOD$ is a prime number, so $inv(a) = a^{MOD - 2}$. Calculating this values for each $i$ from $0$ to $n$ will give correct answer in $O(nlog(MOD))$.",
    "code": "#define _CRT_SECURE_NO_DEPRECATE\n#define _SECURE_SCL 0\n#pragma comment(linker, \"/STACK:200000000\")\n \n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <complex>\n#include <ctime>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <deque>\n#include <functional>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <memory.h>\n#include <numeric>\n#include <iomanip>\n#include <queue>\n#include <set>\n#include <stack>\n#include <list>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <utility>\n#include <cmath>\nusing namespace std;\n \n#define pb push_back\n#define mp make_pair\n#define mset(mas,val) memset(mas,val,sizeof(mas))\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n \n#define forn(i,n) for (int i=0; i<int(n); ++i)\n#define fornd(i,n) for (int i=int(n)-1; i>=0; --i)\n#define forab(i,a,b) for (int i=int(a); i<int(b); ++i)\n \ntypedef long long ll;\ntypedef long double ld;\ntypedef unsigned long long ull;\n    \nconst int INF = (int) 1e9;\nconst long long INF64 = (long long) 1e18;\nlong double eps = 1e-6;\nconst long double pi = 3.14159265358979323846;\n \nconst int N = 1e6 + 100;\nlong long fact[N], modulo = INF + 7;\nint n, a, b;\nbool read()\n{\n    if (!(cin >> a >> b >> n))\n        return false;\n    assert(a >= 1 && a <= 9);\n    assert(b >= a + 1 && b <= 9);\n    assert(n >= 1 && n <= (int)1e6);\n    return true;\n}\nlong long binpow(long long val, long long deg, long long mod) {\n    if (!deg) return 1 % mod;\n    if (deg & 1) return binpow(val, deg - 1, mod) * val % mod;\n    long long res = binpow(val ,deg >> 1, mod);\n    return (res*res) % mod;\n}\nbool check(long long val, int a, int b) {\n    while (val > 0) {\n        if (val % 10 == a || val % 10 == b) {\n            val /= 10;\n        } else return false;\n    }\n    return true;\n}\nvoid initfact() {\n    fact[0] = 1;\n    for(int i = 1; i < N; i++) {\n        fact[i] = (fact[i-1] * i);\n        fact[i] %= modulo;\n    }\n}\nlong long getC(int n, int i) {\n    long long res = fact[n];\n    long long div = fact[n-i] * fact[i];\n    div %= modulo;  div = binpow(div, modulo - 2, modulo);\n    return (res * div) % modulo;\n}\nvoid solve()\n{\n    long long ans = 0;\n    for(int i = 0; i <= n; i++) {\n        long long expsum = a * i + b*(n-i);\n        if (check(expsum, a, b)) {\n            ans += getC(n, i);\n            ans %= modulo;\n        }\n    }\n    cout << ans << endl;\n}\n \nint main(){\n#ifdef gridnevvvit\n    freopen(\"input.txt\",\"rt\",stdin);\n    freopen(\"output.txt\",\"wt\",stdout);\n#endif\n    initfact();\n    assert(read());\n    solve();\n    return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics"
    ],
    "rating": 1800
  },
  {
    "contest_id": "300",
    "index": "D",
    "title": "Painting Square",
    "statement": "Vasily the bear has got a large square white table of $n$ rows and $n$ columns. The table has got a black border around this table.\n\n\\begin{center}\n{\\scriptsize The example of the initial table at $n$ = 5.}\n\\end{center}\n\nVasily the bear wants to paint his square table in exactly $k$ moves. Each move is sequence of actions:\n\n- The bear chooses some square inside his table. At that the square must have a black border painted around it. Also, the square shouldn't contain a black cell. The number of cells in the square shouldn't be less than $2$.\n- The bear chooses some row and some column inside the chosen square. Then he paints each cell of this row and this column inside the chosen square. After that the rectangles, formed by the square's border and the newly painted cells, must be squares of a non-zero area.\n\n\\begin{center}\n{\\scriptsize An example of correct painting at $n$ = 7 и $k$ = 2.}\n\\end{center}\n\nThe bear already knows numbers $n$ and $k$. Help him — find the number of ways to paint the square in exactly $k$ moves. Two ways to paint are called distinct if the resulting tables will differ in at least one cell. As the answer can be rather large, print the remainder after dividing it by $7340033$.",
    "tutorial": "This picture is helpful for understanding. Let's consider problem $D$ in graph terms: We have matrix $n  \\times  n$, which represents a graph: It is tree. Every vertex, except leaves, has 4 children. There are $4^{k}$ distinct vertexes, with distance $k$ from root. We need to color $k$ vertexes of this graph. By that we mean also to color all vertexes on path from $i$ to $1$(root). Knowing $height$ of tree we can build it in unique way. Let's find height of tree in this way: int height = 0; while (n > 1 && n % 2 == 1) { n /= 2; height++; }Let's consider following DP: $z[i][j]$ - number of ways to color graph height $i$ in $j$ steps. Naive solution in $O(k^{4}log(n))$: z[0][0] = 1; z[0][i] = 0, i > 0; z[i][0] = 1, i > 0 z[i][j] = 0; for(int k1 = 0; k1 <= j - 1; k1++) for(int k2 = 0; k2 <= j - 1 - k1; k2++) for(int k3 = 0; k3 <= j - 1 - k1 - k2; k3++) { int k4 = j - 1 - k1 - k2 - k3; z[i][j] += z[i-1][k1] * z[i-1][k2] * z[i-1][k3] * z[i-1][k4]; z[i][j] %= mod; }But it is not what we whant in time terms. Let's consider current DP as polynomial coefficients: $z[i][j]$ - coefficient of power $j$ of polynomial $i$. In that case $z[i + 1][j + 1]$ - coefficient of power $j$ of polynomial $i$ to the 4-th power. This approach allows to solve problem in $O(k^{2}log(n))$. However this solution is quite slow, because of modulo operations. As you see, this modulo is not so big ($ \\le  10^{7}$), that allows us to reduce number of modulo operations, thus giving huge perfomance boost. Also it is possible to use FFT to solve in $O(klog(k)log(n))$.",
    "code": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <ctime>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <complex>\n#include <deque>\n#include <functional>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <memory.h>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <utility>\n#include <cmath>\nusing namespace std;\n \n#define pb push_back\n#define mp make_pair\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n \n#define forn(i,n) for (int i=0; i<int(n); ++i)\n#define fornd(i,n) for (int i=int(n)-1; i>=0; --i)\n#define xrange(i,a,b) for (int i=int(a); i<int(b); ++i)\n \ntypedef long long ll;\ntypedef long double ld;\ntypedef unsigned long long ull;\n \n \nconst int INF = (int) 1e9;\nconst long long INF64 = (long long) 1e18;\nconst long double eps = 1e-9;\nconst long double pi = 3.14159265358979323846;\n \nconst int mod = 7340033;\nconst ll root = 5;\nconst ll root_1 = 4404020;\nconst ll root_pw = 1<<20;\n \nint rev_element[7340033];\n \nll getmod(ll a, ll tmod){\n    return ((a%tmod)+tmod)%tmod;\n}\n \nvoid fft (vector<ll> & a, bool invert) {\n    int n = (int) a.size();\n \n    for (int i=1, j=0; i<n; ++i) {\n        int bit = n >> 1;\n        for (; j>=bit; bit>>=1)\n            j -= bit;\n        j += bit;\n        if (i < j)\n            swap (a[i], a[j]);\n    }\n \n    for (int len=2; len<=n; len<<=1) {\n        ll wlen = invert ? root_1 : root;\n        for (int i=len; i<root_pw; i<<=1)\n            wlen = ll (wlen * 1ll * wlen % mod);\n        for (int i=0; i<n; i+=len) {\n            ll w = 1;\n            for (int j=0; j<len/2; ++j) {\n                ll u = a[i+j],  v = ll (a[i+j+len/2] * 1ll * w % mod);\n                a[i+j] = getmod(u+v,mod);\n                a[i+j+len/2] = getmod(u-v,mod);\n                w = ll (w * 1ll * wlen % mod);\n            }\n        }\n    }\n    if (invert) {\n        ll nrev = rev_element[n];\n        for (int i=0; i<n; ++i)\n            a[i] = int (a[i] * 1ll * nrev % mod);\n    }\n}\n \nvoid precalc(){\n    rev_element[1] = 1;\n    for (int i=2; i<mod; i++)\n        rev_element[i] = (mod - (mod/i) * rev_element[mod%i] % mod) % mod;\n}\n \n \nvoid multiply (const vector<ll> & a, const vector<ll> & b, vector<ll> & res) {\n    vector <ll> fa (a.begin(), a.end()),  fb (b.begin(), b.end());\n    size_t n = 1;\n    while (n < max (a.size(), b.size()))  n <<= 1;\n    n <<= 1;\n    fa.resize (n),  fb.resize (n);\n    fft (fa, false),  fft (fb, false);\n    forn(i,n)\n        fa[i] *= fb[i];\n    fft (fa, true);\n    res.resize (n);\n    forn(i,n)\n        res[i] = fa[i] % mod;\n}\n \nint MN = 29;\nint MK = 1001;\nvector <vector <ll> > dp(MN+2,vector <ll> (MK,0));\nvector <ll> d;\n \nvoid init(){\n    int m;\n    for (int i=0; i<=MN; i++){\n        dp[i][0] = 1;\n        multiply(dp[i],dp[i],d);\n        d.resize(MK);\n        multiply(d,d,dp[i+1]);\n        dp[i+1].insert(dp[i+1].begin(),0);\n        dp[i+1].resize(MK);\n    }\n}\n \nint main(){\n#ifdef dudkamaster\n    freopen(\"input.txt\",\"rt\",stdin);\n    freopen(\"output.txt\",\"wt\",stdout);\n#endif\n    precalc();\n    init();\n    int tc;\n    scanf(\"%d\", &tc);\n    forn(i,tc){\n        ll n,k;\n        cin >> n >> k;\n        int iter = 0;\n        while (n>1 && n&1)\n            iter++, n>>=1;\n        cout << dp[iter][k] << endl;\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "fft"
    ],
    "rating": 2300
  },
  {
    "contest_id": "300",
    "index": "E",
    "title": "Empire Strikes Back",
    "statement": "In a far away galaxy there is war again. The treacherous Republic made $k$ precision strikes of power $a_{i}$ on the Empire possessions. To cope with the republican threat, the Supreme Council decided to deal a decisive blow to the enemy forces.\n\nTo successfully complete the conflict, the confrontation balance after the blow should be a positive integer. The balance of confrontation is a number that looks like $\\overset{p}{q}$, where $p = n!$ ($n$ is the power of the Imperial strike), $q=\\prod_{i=1}^{k}a_{i}!$. After many years of war the Empire's resources are low. So to reduce the costs, $n$ should be a minimum positive integer that is approved by the commanders.\n\nHelp the Empire, find the minimum positive integer $n$, where the described fraction is a positive integer.",
    "tutorial": "Let's $v a l=\\sum_{i=1}^{k}a_{i}$. $val$ is upper bound for answer. $val!$ is divisible by $d e n=\\prod_{i=1}^{k}a_{i}!$, you can easily prove it using facts about prime powers in factorial and following inequality $\\left|{\\frac{\\eta}{i}}\\right|+\\left|{\\frac{\\eta}{i}}\\right|\\leq\\left|{\\frac{(\\mu+\\mu)}{i}}\\right|$. By the way, $\\frac{\\nu a/|}{d\\epsilon m}$ is called multinomial coefficient. So answer can't exceed $10^{13}$. If $n!$ divisible by $den$, then $(n + 1)!$ is also divisible by $den$. That means that function of divisibility is monotonic and we can use binary search. For every $i$, $i = 2..., 10^{7}$, let's precalc max prime in $i$ using linear sieve of Eratosthenes. For $i$ it will be $lp[i]$. After that let's create a vector, with all primes less then $10^{7}$. Now let's calculate following values $cnt[i]$ - amount of numbers $a$, $i < = a$. Now me can factorize denominator like this: for(int i = max; i>=2; i--) { if (lp[i] != i) cnt[lp[i]] += cnt[i]; cnt[i / lp[i]] += cnt[i]; }Finally we use binary search from $lf = 1$ to $r g=\\textstyle\\sum_{i=1}^{k}a_{i}$.",
    "code": "#include <cstdio>\n \nconst int N = (int)1e7 + 100;\n \nint lp[N], simples[N], simsz;\nlong long cnt[N];\nbool ok(long long mid) {\n\tbool can = true;\n\tfor(int i = 0; i < simsz && can; i++) {\n\t\tlong long tmp = mid, f = 0;\n\t\twhile(tmp) {\n\t\t\ttmp /= simples[i];\n\t\t\tf += tmp;\n\t\t}\n\t\tif (f < cnt[i])\n\t\t\tcan = false;\n\t}\n\treturn can;\n}\t\nint main() {\n\tint n, max = 0;\n\tscanf(\"%d\", &n);\n\tlong long rg = 0, lf = 1;\n\tfor(int i = 0; i < n; ++i) {\n\t\tint a;\n\t\tscanf(\"%d\", &a);\n\t\tif (a > max)\n\t\t\tmax = a;\n\t\trg += a;\n\t\t++cnt[a];\n\t}\n\tfor(int i = 2; i <= max; ++i) {\n\t\tif (lp[i] == 0) {\n\t\t\tlp[i] = i;\n\t\t\tsimples[simsz++] = i;\n\t\t}\n\t\tfor(int j = 0; j < simsz && simples[j] <= lp[i] && (long long)i*simples[j]<=max; ++j) {\n\t\t\tlp[i * simples[j]] = simples[j];\n\t\t}\n\t}\n\tfor(int i = max; i>=2; i--)\n\t\tcnt[i] += cnt[i+1];\n\tfor(int i = max; i>=2; i--) {\n\t\tif (lp[i] != i) \n\t\t\tcnt[lp[i]] += cnt[i];\n\t\tcnt[i / lp[i]] += cnt[i];\n\t}\n        for(int i = 0; i < simsz; i++) {\n\t\tcnt[i] = cnt[simples[i]];\n\t}\n\twhile (rg != lf) {\n\t\tlong long mid = (rg+lf)>>1;\n\t\tif (ok(mid)) {\n\t\t\trg = mid;\n\t\t} else lf = mid + 1;\n\t}\n        printf(\"%I64d\", lf);\n}",
    "tags": [
      "binary search",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "301",
    "index": "A",
    "title": "Yaroslav and Sequence",
    "statement": "Yaroslav has an array, consisting of $(2·n - 1)$ integers. In a single operation Yaroslav can change the sign of exactly $n$ elements in the array. In other words, in one operation Yaroslav can select exactly $n$ array elements, and multiply each of them by -1.\n\nYaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?\n\nHelp Yaroslav.",
    "tutorial": "Using dfs we will find number of numbers that we can set as positive. Note that we can either set all of the numbers as positive or leave one number(any) as negative. If we can obtain all numbers as positive, we just return sum of modules of the numbers, but if we cannot we will count the same sum and will subtract minimal modular value multiple 2 from sum.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1800
  },
  {
    "contest_id": "301",
    "index": "B",
    "title": "Yaroslav and Time",
    "statement": "Yaroslav is playing a game called \"Time\". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has $n$ clock stations, station number $i$ is at point $(x_{i}, y_{i})$ of the plane. As the player visits station number $i$, he increases the current time on his timer by $a_{i}$. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow.\n\nA player spends $d·dist$ time units to move between stations, where $dist$ is the distance the player has covered and $d$ is some constant. The distance between stations $i$ and $j$ is determined as $|x_{i} - x_{j}| + |y_{i} - y_{j}|$.\n\nInitially, the player is at station number $1$, and the player has strictly more than zero and strictly less than one units of time. At station number $1$ one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units).\n\nNow Yaroslav is wondering, how much money he needs to get to station $n$. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.",
    "tutorial": "We will use binary search to find the answer. Further we will use Ford-Bellman algorithm. On each step we will have an array of maximum values on timer, when we stand in some point. On in transfer we will check: will our player stay alive after travelling beetwen points. If we can make transfer, we will update value of the final destination point. Becouse of a_i<=d and integer coordinates we haven't optimal cycles, and solution exists.",
    "tags": [
      "binary search",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "301",
    "index": "C",
    "title": "Yaroslav and Algorithm",
    "statement": "Yaroslav likes algorithms. We'll describe one of his favorite algorithms.\n\n- The algorithm receives a string as the input. We denote this input string as $a$.\n- The algorithm consists of some number of command. Сommand number $i$ looks either as $s_{i}$ >> $w_{i}$, or as $s_{i}$ <> $w_{i}$, where $s_{i}$ and $w_{i}$ are some possibly empty strings of length at most $7$, consisting of digits and characters \"?\".\n- At each iteration, the algorithm looks for a command with the minimum index $i$, such that $s_{i}$ occurs in $a$ as a substring. If this command is not found the algorithm terminates.\n- Let's denote the number of the found command as $k$. In string $a$ the first occurrence of the string $s_{k}$ is replaced by string $w_{k}$. If the found command at that had form $s_{k}$ >> $w_{k}$, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates.\n- The value of string $a$ after algorithm termination is considered to be the output of the algorithm.\n\nYaroslav has a set of $n$ positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.\n\nHelp Yaroslav.",
    "tutorial": "We will use ? as iterator. In the begin we will set ? before the number. Then we will move it to the end of the string. Then we will change ? to ?? and we will move it to the begin, while we have 9 before ??. If we have another digit, we just increase it, and finish the algorithm. If we have ?? at the begin, we change it to 1, and end the algorithm.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2500
  },
  {
    "contest_id": "301",
    "index": "D",
    "title": "Yaroslav and Divisors",
    "statement": "Yaroslav has an array $p = p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$, consisting of $n$ distinct integers. Also, he has $m$ queries:\n\n- Query number $i$ is represented as a pair of integers $l_{i}$, $r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$.\n- The answer to the query $l_{i}, r_{i}$ is the number of pairs of integers $q$, $w$ $(l_{i} ≤ q, w ≤ r_{i})$ such that $p_{q}$ is the divisor of $p_{w}$.\n\nHelp Yaroslav, answer all his queries.",
    "tutorial": "Lets add all pair: (x,y) ((d[x]%d[y]==0) || (d[y]%d[x]==0)) to some lest. We can count such pairs using Eretosphen algorithm. Here will be O(n*log(n)) sych pairs using fact, that we have permutation. We will sort all this paairs using counting-sort. Also we will sort given in input intervals. For each given interval we should count number of pairs that countained in given them . Such problem we can solve using Fenvik tree. On each step we will add segments(that are sorted by right side). On each step we will update Fenfick-tree that count number of added pairs on some suffix. Using such tree if it easy to count the answer. So we have O(n*log^2(n)) solution.",
    "tags": [
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "301",
    "index": "E",
    "title": "Yaroslav and Arrangements",
    "statement": "Yaroslav calls an array of $r$ integers $a_{1}, a_{2}, ..., a_{r}$ good, if it meets the following conditions: $|a_{1} - a_{2}| = 1, |a_{2} - a_{3}| = 1, ..., |a_{r - 1} - a_{r}| = 1, |a_{r} - a_{1}| = 1$, at that $a_{1}=\\operatorname*{min}_{i=1}a_{i}$.\n\nAn array of integers $b_{1}, b_{2}, ..., b_{r}$ is called great, if it meets the following conditions:\n\n- The elements in it do not decrease $(b_{i} ≤ b_{i + 1})$.\n- If the inequalities $1 ≤ r ≤ n$ and $1 ≤ b_{i} ≤ m$ hold.\n- If we can rearrange its elements and get at least one and at most $k$ distinct good arrays.\n\nYaroslav has three integers $n, m, k$. He needs to count the number of distinct great arrays. Help Yaroslav! As the answer may be rather large, print the remainder after dividing it by $1000000007$ $(10^{9} + 7)$.\n\nTwo arrays are considered distinct if there is a position in which they have distinct numbers.",
    "tutorial": "We will build the needed arrays sequentially adding numbers. Let's look at what states we need. First, it is obvious that you need to keep the number of ways to build an array of already added numbers, secondly you need to know the total amount of added numbers. Now let's look at what happens when we add a new number (that is greater than all of the previous in a certain amount). It is clear that the added numbers should stand between the numbers 1 to less. In this case, if we put two new numbers in a row, between them should stand more (since we already have placed less). It is obvious that you need to cover all the previous numbers (among which must stand newly added). Thus, we have another state: the number of integers between which we should put the new ones. Thus we have the dynamics of the four parameters: dp [all] [ways] [lastnumber] [counttoadd]. Transfer. It is clear that you need to add at least counttoadd numbers, but how will this affect the number of ways to arrange the numbers? It's simple. Suppose we added number x, then the number of ways to be multiplied by the value of Q (x-counttoadd, counttoadd), where Q (x, y) - the number of ways to assign the same x balls in y different boxes. Q (x, y) = C (x + y-1, y-1) where C (x, y) - binomial coefficient.",
    "tags": [
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "302",
    "index": "A",
    "title": "Eugeny and Array",
    "statement": "Eugeny has array $a = a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ integers. Each integer $a_{i}$ equals to -1, or to 1. Also, he has $m$ queries:\n\n- Query number $i$ is given as a pair of integers $l_{i}$, $r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$.\n- The response to the query will be integer $1$, if the elements of array $a$ can be rearranged so as the sum $a_{li} + a_{li + 1} + ... + a_{ri} = 0$, otherwise the response to the query will be integer $0$.\n\nHelp Eugeny, answer all his queries.",
    "tutorial": "If the length of the given segment is even and count of 1 in input is not lower then half of the length of the segment and count of -1 in the input is not lower then half of the length of the segment so we have answer 1, otherwise 0.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "302",
    "index": "B",
    "title": "Eugeny and Play List",
    "statement": "Eugeny loves listening to music. He has $n$ songs in his play list. We know that song number $i$ has the duration of $t_{i}$ minutes. Eugeny listens to each song, perhaps more than once. He listens to song number $i$ $c_{i}$ times. Eugeny's play list is organized as follows: first song number $1$ plays $c_{1}$ times, then song number $2$ plays $c_{2}$ times, $...$, in the end the song number $n$ plays $c_{n}$ times.\n\nEugeny took a piece of paper and wrote out $m$ moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment $x$ means that Eugeny wants to know which song was playing during the $x$-th minute of his listening to the play list.\n\nHelp Eugeny and calculate the required numbers of songs.",
    "tutorial": "For each song we will count moment of time, when it will be over (some sums on the prefixes, for example). Further, we will use binary search of two itaratos method to solve the problem.",
    "tags": [
      "binary search",
      "implementation",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "303",
    "index": "A",
    "title": "Lucky Permutation Triple",
    "statement": "Bike is interested in permutations. A permutation of length $n$ is an integer sequence such that each integer from 0 to $(n - 1)$ appears exactly once in it. For example, $[0, 2, 1]$ is a permutation of length 3 while both $[0, 2, 2]$ and $[1, 2, 3]$ is not.\n\nA permutation triple of permutations of length $n$ $(a, b, c)$ is called a Lucky Permutation Triple if and only if $\\forall i(1\\leq i\\leq n),a_{i}+b_{i}\\equiv c_{i}\\mod n$. The sign $a_{i}$ denotes the $i$-th element of permutation $a$. The modular equality described above denotes that the remainders after dividing $a_{i} + b_{i}$ by $n$ and dividing $c_{i}$ by $n$ are equal.\n\nNow, he has an integer $n$ and wants to find a Lucky Permutation Triple. Could you please help him?",
    "tutorial": "when n is odd, A[i] = B[i] = i when n is even, there is no solution. So why? Because: S = \\Sum_{i=0}^{n-1} i = n/2 (mod n) but 2*S = 0 (mod n)",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "303",
    "index": "B",
    "title": "Rectangle Puzzle II",
    "statement": "You are given a rectangle grid. That grid's size is $n × m$. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers $(x, y)$ $(0 ≤ x ≤ n, 0 ≤ y ≤ m)$.\n\nYour task is to find a maximum sub-rectangle on the grid $(x_{1}, y_{1}, x_{2}, y_{2})$ so that it contains the given point $(x, y)$, and its length-width ratio is exactly $(a, b)$. In other words the following conditions must hold: $0 ≤ x_{1} ≤ x ≤ x_{2} ≤ n$, $0 ≤ y_{1} ≤ y ≤ y_{2} ≤ m$, $\\textstyle{\\frac{a_{2}-a_{1}}{y_{2}-y_{1}}}={\\frac{a}{b}}$.\n\nThe sides of this sub-rectangle should be parallel to the axes. And values $x_{1}, y_{1}, x_{2}, y_{2}$ should be integers.\n\nIf there are multiple solutions, find the rectangle which is closest to $(x, y)$. Here \"closest\" means the Euclid distance between $(x, y)$ and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here \"lexicographically minimum\" means that we should consider the sub-rectangle as sequence of integers $(x_{1}, y_{1}, x_{2}, y_{2})$, so we can choose the lexicographically minimum one.",
    "tutorial": "Give you $n$, $m$, $x$, $y$, $a$, $b$. Find a maximum sub-rectangle within (0, 0) - ($n$, $m$), so that it contains the given point($x$, $y$) and its length-width radio is exactly ($a$, $b$). If there are multiple solutions, find the rectangle which is closest to ($x$, $y$). If there are still multiple solutions, find the lexicographically minimum one. Split the problem into $x$-axis and $y$-axis. Then you can solve the sub tasks in $O(1)$. d = gcd(a,b) a /= d b /= d t = min(n/a, m/b) a *= t b *= tBe careful, when the length is outside the original rectangle.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "303",
    "index": "C",
    "title": "Minimum Modular",
    "statement": "You have been given $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$. You can remove at most $k$ of them. Find the minimum modular $m$ $(m > 0)$, so that for every pair of the remaining integers $(a_{i}, a_{j})$, the following unequality holds: $a_{i}\\neq a_{j}\\;\\;\\mathrm{mod}\\;m$.",
    "tutorial": "It is hard to solve this problem at once, so at first, let us consider on k = 0, this easier case can be solved by enumerate on the $ans$. Let us define a bool array diff[], which diff[x] is weather there are two number, $a_{i}$, $a_{j}$, such that $abs(a_{i} - a_{j}) = x$. So $ans$ is legal <=> diff[ans], diff[2*ans]  \\dots  are false. The time-complexity $O(n^{2} + mlogm)$. Here $m$ is the maximum $a_{i}$. Consider on $k > 0$, we need to know how many pairs which has difference x. Store them in vector<pair <int, int> > diff[x]; Then use a dsu to maintain the how many a_i are congruent when enumerate on the $ans$.",
    "tags": [
      "brute force",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "304",
    "index": "A",
    "title": "Pythagorean Theorem II",
    "statement": "In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:\n\n\\underline{In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).}\n\nThe theorem can be written as an equation relating the lengths of the sides $a$, $b$ and $c$, often called the Pythagorean equation:\n\n\\[\na^{2} + b^{2} = c^{2}\n\\]\n\nwhere $c$ represents the length of the hypotenuse, and $a$ and $b$ represent the lengths of the other two sides.\n\nGiven $n$, your task is to count how many right-angled triangles with side-lengths $a$, $b$ and $c$ that satisfied an inequality $1 ≤ a ≤ b ≤ c ≤ n$.",
    "tutorial": "This problem can be solve by brute-force, but it come up with a nicer solution if we involve some math.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "304",
    "index": "B",
    "title": "Calendar",
    "statement": "Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows:\n\n\\underline{Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year.}\n\nIn this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February.\n\nLook at the sample to understand what borders are included in the aswer.",
    "tutorial": "This problem can be solve by brute-force, but it come up with a nicer solution if we involve some math.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "305",
    "index": "A",
    "title": "Strange Addition",
    "statement": "Unfortunately, Vasya can only sum pairs of integers ($a$, $b$), such that for any decimal place at least one number has digit $0$ in this place. For example, Vasya can sum numbers $505$ and $50$, but he cannot sum $1$ and $4$.\n\nVasya has a set of $k$ distinct non-negative integers $d_{1}, d_{2}, ..., d_{k}$.\n\nVasya wants to choose some integers from this set so that he could sum any two chosen numbers. What maximal number of integers can he choose in the required manner?",
    "tutorial": "All you have to do is implement following algorithm: If we have numbers $0$ or $100$, we take them to needed subset. If we got number greater than $0$ and less than 10, we take it. If we got number $x\\in[10;100)$ divisible by 10 we take it. In case we have no numbers of second and third type, we take a number $x\\in[10;100)$ that is not divisible by 10",
    "code": "#include <cstdio>\n#include <vector>\n \nint n, cnt[5], a;\n \nusing namespace std;\n \nint main() {\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++) {\n        scanf(\"%d\", &a);\n        if (a == 0) {\n            cnt[0] = 1;\n            continue;\n        }\n        if (a == 100) {\n            cnt[1] = 1;\n            continue;\n        }\n        if (a % 10 == 0) {\n            cnt[2] = a;\n            continue;\n        }\n        if (a < 10) {\n            cnt[3] = a;\n            continue;\n        }\n        cnt[4] = a;\n    }\n    vector < int > ans;\n    if (cnt[0]) ans.push_back(0);\n    if (cnt[1]) ans.push_back(100);\n    if (cnt[2]) ans.push_back(cnt[2]);\n    if (cnt[3]) ans.push_back(cnt[3]);\n    if (!cnt[2] && !cnt[3] && cnt[4]) ans.push_back(cnt[4]);\n    printf(\"%d\n\", ans.size());\n    for(int i = 0; i < ans.size(); i++) {\n        if (i) printf(\" \");\n        printf(\"%d\", ans[i]);\n    }\n    puts(\"\");\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "305",
    "index": "B",
    "title": "Continued Fractions",
    "statement": "A continued fraction of height $n$ is a fraction of form $a_{1}+{\\frac{1}{a_{2}+{\\frac{1}{\\ldots+{\\frac{1}{a_{m}}}}}}}$. You are given two rational numbers, one is represented as $\\overset{p}{q}$ and the other one is represented as a finite fraction of height $n$. Check if they are equal.",
    "tutorial": "There are at most two ways to represent rational fraction as continued. Using Euclid algorithm you can do that for $\\overset{p}{q}$ and then check equality of corresponding $a_{i}$.",
    "code": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <complex>\n#include <ctime>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <deque>\n#include <functional>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n#include <map>\n#include <memory.h>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <utility>\n#include <cmath>\nusing namespace std;\n \n#define pb push_back\n#define mp make_pair\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n \n#define forn(i,n) for (int i=0; i<int(n); ++i)\n#define fornd(i,n) for (int i=int(n)-1; i>=0; --i)\n#define forab(i,a,b) for (int i=int(a); i<int(b); ++i)\n \ntypedef long long ll;\ntypedef long double ld;\ntypedef unsigned long long ull;\n \nconst int INF = (int) 1e9;\nconst long long INF64 = (long long) 1e18;\nconst long double eps = 1e-9;\nconst long double pi = 3.14159265358979323846;\n \nll p,q,n;\nvector <ll> a;\nvector <ll> m;\n \nbool read(){\n    if (!(cin >> p >> q >> n)) return false;\n    a.assign(n,0);\n    forn(i,n)\n        cin >> a[i];\n    return true;\n}\n \nvoid calc(ll a, ll b){\n    if (a == 0 || b == 0) return;\n    ll q = a/b;\n    m.pb(q);\n    a -= b*q;\n    calc(b,a);\n}\n \nvoid solve(){\n    if (n > 1 && a[n-1] == 1){\n        a[n-2]++;\n        a.pop_back();\n        n--;\n    }\n    m.clear();\n    calc(p,q);\n    bool ans = true;\n    if (sz(a)!=sz(m)) ans = false;\n    forn(i,min(sz(a),sz(m)))\n        ans = ans && (a[i]==m[i]);\n    if (ans)\n        puts(\"YES\");\n    else\n        puts(\"NO\");\n}\n \nint main(){\n#ifdef dudkamaster\n    freopen(\"input.txt\",\"rt\",stdin);\n    freopen(\"output.txt\",\"wt\",stdout);\n#endif\n    while (read())\n        solve();\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "305",
    "index": "C",
    "title": "Ivan and Powers of Two",
    "statement": "Ivan has got an array of $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. Ivan knows that the array is sorted in the non-decreasing order.\n\nIvan wrote out integers $2^{a1}, 2^{a2}, ..., 2^{an}$ on a piece of paper. Now he wonders, what minimum number of integers of form $2^{b}$ $(b ≥ 0)$ need to be added to the piece of paper so that the sum of all integers written on the paper equalled $2^{v} - 1$ for some integer $v$ $(v ≥ 0)$.\n\nHelp Ivan, find the required quantity of numbers.",
    "tutorial": "First of all, let's carry over all powers of two in the following way: if we have $a_{i} = a_{j}$, $i  \\neq  j$, carry 1 to $a_{i} + 1$. Now as all of $a_{i}$ are distinct, the answer is $max(a_{i})$ - $cnt(a_{i})$ + 1, where $max(a_{i})$ - maximal value of $a_{i}$,$cnt(a_{i})$ - size of $a$",
    "code": "#include <cstdio>\n \nconst int NMAX = 100005;\nint a[NMAX], n, tmax, tcnt;\n \nint main() {\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++) scanf(\"%d\", &a[n - i - 1]);\n    while (n > 0) {\n        int j = n - 1, cnt;\n        while (j > 0 && a[n - 1] == a[j - 1]) --j;\n        cnt = n - j;\n        if (cnt % 2 == 1) {\n            tcnt++, n--;\n            if (a[n] > tmax) tmax = a[n];\n        }\n        cnt /= 2;\n        n -= cnt;\n        for(int i = 0; i < cnt; i++) a[n - 1 - i]++;\n    }\n    printf(\"%d\n\", tmax - tcnt + 1); \n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "305",
    "index": "D",
    "title": "Olya and Graph",
    "statement": "Olya has got a directed non-weighted graph, consisting of $n$ vertexes and $m$ edges. We will consider that the graph vertexes are indexed from 1 to $n$ in some manner. Then for any graph edge that goes from vertex $v$ to vertex $u$ the following inequation holds: $v < u$.\n\nNow Olya wonders, how many ways there are to add an arbitrary (possibly zero) number of edges to the graph so as the following conditions were met:\n\n- You can reach vertexes number $i + 1, i + 2, ..., n$ from any vertex number $i$ $(i < n)$.\n- For any graph edge going from vertex $v$ to vertex $u$ the following inequation fulfills: $v < u$.\n- There is at most one edge between any two vertexes.\n- The shortest distance between the pair of vertexes $i, j$ $(i < j)$, for which $j - i ≤ k$ holds, equals $j - i$ edges.\n- The shortest distance between the pair of vertexes $i, j$ $(i < j)$, for which $j - i > k$ holds, equals either $j - i$ or $j - i - k$ edges.\n\nWe will consider two ways distinct, if there is the pair of vertexes $i, j$ $(i < j)$, such that first resulting graph has an edge from $i$ to $j$ and the second one doesn't have it.\n\nHelp Olya. As the required number of ways can be rather large, print it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "First of all let's consider a graph on a number line. It's neccesary to have edges $i - > i + 1$(first type). Also you can edges like $i - > i + k + 1$ (second type). Other edges are forbidden. This allows us to understand whether the answer is 0 or not. Also answer is 0 when all edges of second type doesn't intersect, considering them to be segments of number line, except when $k  \\ge  n - 1$ - in this case answer is 1. Now we know that answer != 0. Frow all edges we have let's use only second type edges. If there aren't any of this edges we can add 1 to the answer, because of possibility of adding 0 edges to graph. For every vertex $i$, that has possibility of adding second type edges, let's add to answer $2^{cnt}$, $cnt$ - amount of vertexes on [i, min(i + k, n - k - 1)] without edges of second type out of them. Also it is necessary for all the second type edges to start in this segment.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <utility>\n#include <cassert>\n#include <vector>\n \nusing namespace std;\n \nconst int MOD = 1000000007, N = 1000005;\n \nint n, m, k, ans, degs[N];\n \n#define forn(i,n) for(int i = 0; i < (int) n; i++) \n \ninline int add(int a, int b) { a += b; if (a >= MOD) a -= MOD; return a;}\n \nint main(){\n    degs[0] = 1;\n    forn(i, N) {\n        if (!i) continue;\n        degs[i] = add(degs[i-1], degs[i-1]);\n    }\n    scanf(\"%d %d %d\n\", &n, &m, &k);\n    vector < pair<int,int> > edges;\n    forn(i, m) {\n        int a, b;\n        scanf(\"%d %d\", &a, &b);\n        if (b - a != 1 && b - a != k + 1) {\n            puts(\"0\");\n            return 0;\n        }\n        if (b - a == k + 1) edges.push_back(make_pair(a, b));\n    }\n    sort(edges.begin(), edges.end()); m = edges.size();\n    if (k == 0 || k >= n - 1) {\n        puts(\"1\");\n        return 0;\n    }\n    forn(i, m) {\n        if (!(edges[i].first >= edges[0].first && edges[i].first < edges[0].second)) {\n            puts(\"0\");\n            return 0;\n        }\n    }\n        if (edges.size() == 0) ++ans;\n    forn(i, n) {\n        int f = i + 1, s = i + k + 2, cnt = m;\n        if (s > n || (m > 0 && f > edges[0].first)) break;\n        if (m > 0 && !(f <= edges[0].first && edges[m-1].first < s)) continue;\n        if (m > 0 && f == edges[0].first) cnt--;\n        s = min(s, n - k);\n        ans = add(ans,degs[s - f - cnt - 1]);\n    }\n    printf(\"%d\n\", ans);\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "305",
    "index": "E",
    "title": "Playing with String",
    "statement": "Two people play the following string game. Initially the players have got some string $s$. The players move in turns, the player who cannot make a move loses.\n\nBefore the game began, the string is written on a piece of paper, one letter per cell.\n\n\\begin{center}\n{\\scriptsize An example of the initial situation at $s$ = \"abacaba\"}\n\\end{center}\n\nA player's move is the sequence of actions:\n\n- The player chooses one of the available pieces of paper with some string written on it. Let's denote it is $t$. Note that initially, only one piece of paper is available.\n- The player chooses in the string $t = t_{1}t_{2}... t_{|t|}$ character in position $i$ $(1 ≤ i ≤ |t|)$ such that for some positive integer $l$ $(0 < i - l; i + l ≤ |t|)$ the following equations hold: $t_{i - 1} = t_{i + 1}$, $t_{i - 2} = t_{i + 2}$, ..., $t_{i - l} = t_{i + l}$.\n- Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string $t_{1}t_{2}... t_{i - 1}$, the second one will contain a string consisting of a single character $t_{i}$, the third one contains string $t_{i + 1}t_{i + 2}... t_{|t|}$.\n\n\\begin{center}\n{\\scriptsize An example of making action $(i = 4)$ with string $s$ = «abacaba»}\n\\end{center}\n\nYour task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.",
    "tutorial": "Let's consider substring of $s$ $s[i... j]$, that all characters from $i$ to $j$ are palindrome centers, and $i - 1, j + 1$ are not. Every such substring can be treated independently from the others, and as we don't need to know it'sstructure let's consider only it length $len$. Let's calculate $grundy[len]$ - Grundy function. If we want to cut character at position $i$ $0  \\le  i < len$ then our game splits in to independent ones: first will have length $i - 1$, second - $len - i - 2$, as $s[i - 1]$ and $s[i + 1]$ are not centers of palindrome any more.",
    "code": "#include <cstdio>\n#include <memory.h>\n#include <cstring>\n \ninline int max(int a, int b) { if (a >= b) return a; return b; }\n \nconst int N = 5005;\nchar s[N];\nint grundy[N], mex[N], n, totalXor;\n \nint main(){\n    gets(s);\n    for(int i = 1; i < N; i++) {\n        memset(mex, 0, sizeof mex);\n        for(int j = 0; j < i; j++) {\n            int left = max(0, j - 1);\n            int right = max(0, i - j - 2);\n            int tXor = grundy[left] ^ grundy[right];\n            if (tXor < N) mex[tXor]++;\n        }\n        for(int j = 0; ; j++) {\n            if (!mex[j]) {\n                grundy[i] = j;\n                break;\n            }\n        }\n    }\n    n = strlen(s);\n    for(int i = 1; i < n - 1; i++) {\n        if (s[i-1] == s[i + 1]) {\n            int j = i;\n            while (j + 2 < n && s[j] == s[j + 2]) j++;\n            totalXor ^= grundy[j - i + 1];\n            i = j + 1;\n        }\n    }\n    if (totalXor != 0) {\n        puts(\"First\");\n        for(int i = 1; i < n - 1; i++) {\n            if (s[i-1] == s[i+1]) {\n                int j = i;\n                while (j + 2 < n && s[j] == s[j + 2]) j++;\n                int len = j - i + 1;\n                int nowXor = totalXor ^ grundy[len];\n                for(int k = 0; k < len; k++) {\n                    int left = max(0, k - 1);\n                    int right = max(0, len - k - 2);\n                    int resXor = nowXor ^ grundy[left] ^ grundy[right];\n                    if (resXor == 0) {\n                        printf(\"%d\n\", i + k + 1);\n                        return 0;\n                    }\n                }\n                i = j + 1;\n            }\n        }\n    }\n    puts(\"Second\");\n}",
    "tags": [
      "games"
    ],
    "rating": 2300
  },
  {
    "contest_id": "309",
    "index": "A",
    "title": "Morning run",
    "statement": "People like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium.\n\nThe city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium can be represented as a circle, its length is exactly $l$ meters with a marked start line. However, there can't be simultaneous start in the morning, so exactly at 7, each runner goes to his favorite spot on the stadium and starts running from there. Note that not everybody runs in the same manner as everybody else. Some people run in the clockwise direction, some of them run in the counter-clockwise direction. It mostly depends on the runner's mood in the morning, so you can assume that each running direction is equiprobable for each runner in any fixed morning.\n\nThe stadium is tiny and is in need of major repair, for right now there only is one running track! You can't get too playful on a single track, that's why all runners keep the same running speed — exactly 1 meter per a time unit. Nevertheless, the runners that choose different directions bump into each other as they meet.\n\nThe company wants to design a new stadium, but they first need to know how bad the old one is. For that they need the expectation of the number of bumpings by $t$ time units after the running has begun. Help the company count the required expectation. Note that each runner chooses a direction equiprobably, independently from the others and then all runners start running simultaneously at 7 a.m. Assume that each runner runs for $t$ time units without stopping. Consider the runners to bump at a certain moment if at that moment they found themselves at the same point in the stadium. A pair of runners can bump more than once.",
    "tutorial": "We were asked to find the expected value of meetings between the runners. How to do that? As the first step, expected value is lineal, so we can split the initial problems into the different ones: find the expected value of meetings between the fixed pair of runners. We will solve these problems. To do that we need to make some observations: Let $x$ be the distance between the two runners and they run face to face for infinite amount of time (probability of that obviously equals to $0.5 \\cdot 0.5 = 0.25$). Then the first meeting will happen at time $\\scriptstyle{\\frac{a}{2}}$, the next one - ${\\frac{x}{2}}+{\\frac{l}{2}}$, the next - $\\displaystyle{\\frac{x}{2}}+{\\frac{l}{2}}+{\\frac{l}{2}}+{\\frac{l}{2}}$ and so on. Let us assume that every run ran for $l$ time units. Then if two runners meet - they meet exactly two times. The probability of the meeting equals to $0.5$, because in two cases they run in the same direction and in two cases in the different ones. We will build our solution based on these two observations. As the first step let us represent $t$ as $t = k \\cdot l + p$, where $0  \\le  p < l$. Then each runner will run $k$ full laps. What does that mean? Because we have $\\textstyle{\\frac{n(n-1)}{2}}$ pairs of runners, then in those $k$ laps each pair will have $2k$ meetings with probability equals to $0.5$. So, we need to add $2k\\cdot{\\frac{n(n-1)}{2}}\\cdot0.5={\\frac{k n(n-1)}{2}}$ to the answer. Now we need to take into account $p$ seconds of running. Let us assume that the distance between two runners is $x$ and they run towards each other. Then they will meet if ${\\underset{^{\\sim}}{a}}\\leq l$, or $x  \\le  2t$. They will meet once more if ${\\frac{x}{2}}+{\\frac{\\imath}{2}}\\leq l$, ir $x  \\le  2t - l$. They cannot meet more than twice, because $p < l$. Let us fix one of the runners, then using binary search we can find all other runners at distance no more than $x$ from the fixed one. Let us choose $x$ as $x = 2t$, and then the number of runners at the distance no more than $x$ stands for the number of runners which meet with the fixed one at least once. If $x = 2t - l$, we will find the number of runners which meet with the fixed one exactly two times. Multiplying these numbers by $0.25$ - probability of the meeting, and add it to the answer. The complexity of this solution is $O(n\\log n)$. We can reduce it using two pointers method.",
    "tags": [
      "binary search",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "309",
    "index": "B",
    "title": "Context Advertising",
    "statement": "Advertising has become part of our routine. And now, in the era of progressive technologies, we need your ideas to make advertising better!\n\nIn this problem we'll look at a simplified version of context advertising. You've got a text, consisting of exactly $n$ words. A standard advertising banner has exactly $r$ lines, each line can contain at most $c$ characters. The potential customer always likes it when they can see lots of advertising, so you should determine which maximum number of consecutive words from the text can be written on the banner. Single words in one line of the banner should be separated by spaces. You are allowed to insert more than one space at once. Note that you are not allowed to break the words, that is, each word in the text must occupy exactly one line in the banner. Besides, you cannot change the word order, that is, if you read the banner text consecutively, from top to bottom and from left to right, you should get some consecutive part of the advertisement text.\n\nMore formally, the statement can be written like that. Let's say that all words are indexed from $1$ to $n$ in the order in which they occur in the advertisement text. Then you have to choose all words, starting from some $i$-th one and ending with some $j$-th one $(1 ≤ i ≤ j ≤ n)$, so that all of them could be written on the banner. There must be as many words as possible. See the samples for clarifications.",
    "tutorial": "We were asked to find the maximal number of words we can fit into the block of size $r  \\times  c$. Let's first solve such problem: what is the maximal number of consecutive words which can fit in a row of lenth $c$, if the first word has index $i$. We can solve it using binary search or moving the pointer. Now let us build a graph, where vertices are the words and there is a directional edge between $i$ and $j$, if words from $i$ to $j - 1$ fit in one row of length $c$, but words from $i$ to $j$ don't. The weight of the edge is $j - i$. The we have the following problem: we need to find the path of length $k$, which has the maximal weight. Easy to solve it with complexity $O(n\\log n)$ saving weights of all the paths with lengthes equal to the powers of two, or in $O(n)$ time using dfs. The other problems competitors faced - that we were asked to print the whole text, not only the length.",
    "tags": [
      "dp",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "309",
    "index": "C",
    "title": "Memory for Arrays",
    "statement": "You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine.\n\nWe'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells.\n\nYou have exactly $n$ memory clusters, the $i$-th cluster consists of $a_{i}$ cells. You need to find memory for $m$ arrays in your program. The $j$-th array takes $2^{bj}$ consecutive memory cells. There possibly isn't enough memory for all $m$ arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays.",
    "tutorial": "We were asked to find the maximal number of arrays we can fit into the memory. A small observation first, let the answer be $k$, then one of the optimal solutions fits the $k$ smallest arrays into the memory. We can assume that we have arrays of size 1 and we want to arrange the memory for the maximal arrays as possible. Then if we have parts of memory of odd size, if we fit array of size 1 at this part we will obtain part of even size. From other hand, if we put arrays of bigger size we will not change the parity and if we don't fill it with arrays of size one and initially it's of odd size then in the end we will have at least one empty cell. So it's reasonable to put the arrays of size one into the memory of odd size. Let's do it until we can do it. We have three possible situations: We don't have memory parts of odd size anymore. We don't have arrays of size 1 anymore. We don't have neither arrays of size 1 neither memory parts of size 1. Let us start from the first case. Suppose that there are some arrays of size 1 left, but there are no memory parts of odd size. Easy to see then in such case we need to group arrays of size 1 in pairs and then consider them as the same array. So we can divide every number by two and reduce the problem to the initial one. In the second case if we divide every number by two we will obtain the same problem (and that cannot increase the answer). The third case is similar to the second one. When implementing this we need to remember that first we have to fill the memory with arrays which are build from the maximal numbers of initial arrays. The complexity of the given algorithm is $O(n\\log n)$.",
    "tags": [
      "binary search",
      "bitmasks",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "309",
    "index": "D",
    "title": "Tennis Rackets",
    "statement": "Professional sport is more than hard work. It also is the equipment, designed by top engineers. As an example, let's take tennis. Not only should you be in great shape, you also need an excellent racket! In this problem your task is to contribute to the development of tennis and to help to design a revolutionary new concept of a racket!\n\nThe concept is a triangular racket. Ant it should be not just any triangle, but a regular one. As soon as you've chosen the shape, you need to stretch the net. By the time you came the rocket had $n$ holes drilled on each of its sides. The holes divide each side into equal $n + 1$ parts. At that, the $m$ closest to each apex holes on each side are made for better ventilation only and you cannot stretch the net through them. The next revolutionary idea as to stretch the net as obtuse triangles through the holes, so that for each triangle all apexes lay on different sides. Moreover, you need the net to be stretched along every possible obtuse triangle. That's where we need your help — help us to count the number of triangles the net is going to consist of.\n\nTwo triangles are considered to be different if their pictures on the fixed at some position racket are different.",
    "tutorial": "We were asked to find the number of obtuse triangles which satisfy the problem statement. Author's solution has complexity $O(n^{2})$, but it has some optimizations, so it easily works under the TL. Every triangle has only one obtuse angle. Due to symmetry reasons we can fix one of the sides and assume that obtuse angle is tangent to this side. Then we only need to find the number of such triangles and multiple the answer by 3. Every side is also symmetric, so we can consider only one half of it and then multiple the answer by 2. Let us assume that vertex $A$ of the triangle has coordinates (0,0). Vertex $B$ (0,$\\sqrt{3}$) and $C$(2,0). Then we can find the coordinates of every single point at each of the sides and apply cosine theorem. We obtain the inequality which guarantee us that the triangle is obtuse. It can be written in many ways, on of them is following: If $1  \\le  i, j, k  \\le  n$ - indices of points which are fixed at each of the sides, then triangle is obtuse iff: $f(i, j, k) = 2i^{2} - i(n + 1) + 2j(n + 1) - ij - k(i + j) < 0$. We can see that $g(i,j)=\\frac{2i^{2}-i(n+1)+2j(n+1)-i j}{i+j}$ monotonically increases, so we can use moving pointer method applied to variable $k$. Then just go over all $i$ from $m + 1$ to $\\textstyle{\\frac{n+1}{2}}$, then $j$ from $m + 1$ till upper bound for $k$ is less than or equal to $n - m + 1$ and just sum the results. We should mention that all of the operations have to be done in int type, it significantly increases the speed.",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 2700
  },
  {
    "contest_id": "309",
    "index": "E",
    "title": "Sheep",
    "statement": "Information technologies are developing and are increasingly penetrating into all spheres of human activity. Incredible as it is, the most modern technology are used in farming!\n\nA large farm has a meadow with grazing sheep. Overall there are $n$ sheep and each of them contains a unique number from 1 to $n$ — because the sheep need to be distinguished and you need to remember information about each one, and they are so much alike! The meadow consists of infinite number of regions numbered from 1 to infinity. It's known that sheep $i$ likes regions from $l_{i}$ to $r_{i}$.\n\nThere are two shepherds taking care of the sheep: First and Second. First wakes up early in the morning and leads the sheep graze on the lawn. Second comes in the evening and collects all the sheep.\n\nOne morning, First woke up a little later than usual, and had no time to lead the sheep graze on the lawn. So he tied together every two sheep if there is a region they both like. First thought that it would be better — Second would have less work in the evening, because sheep won't scatter too much, being tied to each other!\n\nIn the evening Second came on the lawn, gathered the sheep and tried to line them up in a row. But try as he might, the sheep wouldn't line up as Second want! Second had neither the strength nor the ability to untie the sheep so he left them as they are, but with one condition: he wanted to line up the sheep so that the maximum distance between two tied sheep was as small as possible. The distance between the sheep is the number of sheep in the ranks that are between these two.\n\nHelp Second find the right arrangement.",
    "tutorial": "Author's supposed greedy algorithm as a solution for this problem. Let us follow this algorithm. Let us create to label for every interval $Position_{v}$ and $MaximalPosition_{v}$. $Position_{v}$ - stands for position of $v$ in the required permutation. $MaximalPosition_{v}$ - stands for maximal possible position of $v$ in the particular moment of the algorithm. Also let's consider $count$ as a counter with initial value of 0 and set of unprocessed vertices $S$. The algorithm is following. Using binary search we find the maximal possible distance between the farthest sheep. And then check whether exists the permutation with maximal distance no more than $K$. Sort all the intervals in the increasing order of $r_{i}$. $Position_{i} = 0$, $1  \\le  i  \\le  n$, $MaximalPosition_{i} = n$, $1  \\le  i  \\le  n$, $current = 1$, $count = 0$. Do $count = count + 1$, $Position_{current} = count$, erase $current$ from $S$, if $S$ - is empty, required permutation has been found. Look at every interval connected to $current$, and update $MaximalPosition_{v} = min(MaximalPosition_{v}, Position_{current} + K)$ Build sets $S(count, j) = {v|MaximalPosition_{v}  \\le  count + j}$. If for every $j  \\ge  K - count + 1$ holds $|S(count, j)|  \\le  j$ go to the step 7, otherwise there is no such permutation. Choose the minimal $j$ such that $|S(count, j)| = j$. Choose from it the interval with the smallest $r_{i}$ and consider it as a new value for $current$, go to the step 4. First let us discuss the complexity. Let us fix $K$ (in total there are $\\log n$ iterations with fixed $K$). Every step from 4 to 7 will be done at most $n$ times (every time size of $S$ decreases by one). Every step can be implemented in $O(n)$ time. The most difficult one - step 6. But we can see that it's not necessary to actually build the sets, all we need to know - their sizes. This can be done in linear time just counting the number of intervals that $MaximalPosition_{v} = i$. Let if be $C_{i}$ - then size of $S(count, j)$ equals to $C_{1} + C_{2} + ... + C_{count + j}$, which can be easily calculated with partial sums. Now let us discuss why this algorithm works. If we have $Position$ labels for every interval - we obviously have the solution. Now let us assume that we ended up earlier. Then we will show that there is no such permutation. If algorithm ended, it means that for some $count$ (consider the smallest such $count$), exists $j_{0}$, that $|S(count, j_{0})| > j_{0}$ at this step. Then $|S(count, k)| > k$. Let us prove that from contradiction. From the definition of $count$ we have $|S(count - 1, j)|  \\le  j$ for every $j  \\ge  k - count + 2$. Then $|S(count, j)| = |S(count - 1, j + 1)| - 1  \\le  j$ for every $j  \\le  k - 1$. And $S(count, j) = S(count, k)$ for $k  \\le  j < n - count = |S(count, j)| = |S(count, k)|  \\le  j$. Finally $|S(count, n - count)| = n - count$. Then $|S(count, j)|  \\le  j$ for every $j$, so we obtain contradiction. That means if algorithm stops at step 6 we have $|S(count, k)| > k$. So exist at least $k + 1$ interval, which still don't have assigned label $Position$ and they should be assigned after $count$. So one of the intervals in $S(count, k)$ has to have the value of $Position$ at least $count + k + 1$. But every intervals in $S(count, k)$ connected to at least one interval with $Position  \\le  count$. So, we obtain that there is now such permutation.",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "311",
    "index": "A",
    "title": "The Closest Pair",
    "statement": "Currently Tiny is learning Computational Geometry. When trying to solve a problem called \"The Closest Pair Of Points In The Plane\", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.\n\nThe problem is the follows. Given $n$ points in the plane, find a pair of points between which the distance is minimized. Distance between $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ is $\\sqrt{(x_{2}-x_{1})^{2}+(y_{2}-y_{1})^{2}}$.\n\nThe pseudo code of the unexpected code is as follows:\n\n\\begin{verbatim}\ninput n\nfor i from 1 to n\ninput the i-th point's coordinates into p[i]\nsort array p[] by increasing of x coordinate first and increasing of y coordinate second\nd=INF //here INF is a number big enough\ntot=0\nfor i from 1 to n\nfor j from (i+1) to n\n++tot\nif (p[j].x-p[i].x>=d) then break //notice that \"break\" is only to be\n//out of the loop \"for j\"\nd=min(d,distance(p[i],p[j]))\noutput d\n\\end{verbatim}\n\nHere, $tot$ can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, $tot$ should not be more than $k$ in order not to get Time Limit Exceeded.\n\nYou are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?",
    "tutorial": "We read the pseudo code carefully. If we ignore \"break\", $tot$ will be up to $\\textstyle{\\frac{n(n-1)}{2}}$. Consider whether we can make such inequality $d  \\le  p[j].x - p[i].x$ is always false. The obvious way is to make all points' x coordinates the same. And we can just choose $n$ distinct numbers to be all points' y coordinate. Thus the problem is solved.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "311",
    "index": "B",
    "title": "Cats Transport",
    "statement": "Zxr960115 is owner of a large farm. He feeds $m$ cute cats and employs $p$ feeders. There's a straight road across the farm and $n$ hills along the road, numbered from 1 to $n$ from left to right. The distance between hill $i$ and $(i - 1)$ is $d_{i}$ meters. The feeders live in hill 1.\n\nOne day, the cats went out to play. Cat $i$ went on a trip to hill $h_{i}$, finished its trip at time $t_{i}$, and then waited at hill $h_{i}$ for a feeder. The feeders must take all the cats. Each feeder goes straightly from hill 1 to $n$ without waiting at a hill and takes all the \\textbf{waiting} cats at each hill away. Feeders walk at a speed of 1 meter per unit time and are strong enough to take as many cats as they want.\n\nFor example, suppose we have two hills $(d_{2} = 1)$ and one cat that finished its trip at time 3 at hill 2 $(h_{1} = 2)$. Then if the feeder leaves hill 1 at time 2 or at time 3, he can take this cat, but if he leaves hill 1 at time 1 he can't take it. If the feeder leaves hill 1 at time 2, the cat waits him for 0 time units, if the feeder leaves hill 1 at time 3, the cat waits him for 1 time units.\n\nYour task is to schedule the time leaving from hill 1 for each feeder so that the sum of the waiting time of all cats is minimized.",
    "tutorial": "Let a[i] be the distance from hill 1 to hill i, s[i]=a[1]+a[2]+ \\dots +a[i]. Firstly, we sort the cats by (Ti-a[i]). Then we can divide the cats into P consecutive parts, and plan a feeder for each part. Dynamic Programming can solve this problem. Let f[i,j] indicates the minimum sum of waiting time with i feeders and j cats. f[i,j] = f[i-1,k]+a[j]*(j-k)-s[j]+s[k] = a[j]*j-s[j] + f[i-1,k]+s[k]-a[j]*k That's O(PM^2). It'll get TLE. Let p>q, if p is \"better\" than q, then: f[i-1,p]+s[p]-a[j]*p>f[i-1,q]+s[q]-a[j]*q (f[i-1,p]+s[p])-(f[i-1,q]+s[q])>a[j]*(p-q) g[p]-g[q]>a[j]*(p-q) So we can use Convex hull trick with a queue. Then we get O(MP), which can pass the problem.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "311",
    "index": "C",
    "title": "Fetch the Treasure",
    "statement": "Rainbow built $h$ cells in a row that are numbered from 1 to $h$ from left to right. There are $n$ cells with treasure. We call each of these $n$ cells \"Treasure Cell\". The $i$-th \"Treasure Cell\" is the $a_{i}$-th cell and the value of treasure in it is $c_{i}$ dollars.\n\nThen, Freda went in the first cell. For now, she can go just $k$ cells forward, or return to the first cell. That means Freda was able to reach the 1st, ($k + 1$)-th, ($2·k + 1$)-th, ($3·k + 1$)-th cells and so on.\n\nThen Rainbow gave Freda $m$ operations. Each operation is one of the following three types:\n\n- Add another method $x$: she can also go just $x$ cells forward at any moment. For example, initially she has only one method $k$. If at some moment she has methods $a_{1}, a_{2}, ..., a_{r}$ then she can reach all the cells with number in form $1+\\sum_{i=1}^{r}v_{i}\\cdot a_{i}$, where $v_{i}$ — some non-negative integer.\n- Reduce the value of the treasure in the $x$-th \"Treasure Cell\" by $y$ dollars. In other words, to apply assignment $c_{x} = c_{x} - y$.\n- Ask the value of the most valuable treasure among the cells Freda can reach. If Freda cannot reach any cell with the treasure then consider the value of the most valuable treasure equal to 0, and do nothing. Otherwise take the most valuable treasure away. If several \"Treasure Cells\" have the most valuable treasure, take the \"Treasure Cell\" with the minimum number (not necessarily with the minimum number of cell). After that the total number of cells with a treasure is decreased by one.\n\nAs a programmer, you are asked by Freda to write a program to answer each query.",
    "tutorial": "Firstly, we solve such a problem: if we can go exactly k,k1,k2 \\dots  \\dots or kp cells forward each step, what cells can we reach? We divide the H cells into k groups: Group 0,1 \\dots  \\dots k-1. The i-th cell should be in Group (i mod k). If we reach Cell x in Group (x mod k), we can also reach Cell (x+kj , 1<=j<=p) in Group ((x+kj)mod k). If we reach Cell x in Group (x mod k), we can also reach Cell (x+k) in the same group. Let D[i] be the minimum cell we can reach in Group i. Then we can reach all the cells which number are bigger then D[i] in Group i. Regard the groups as points. Regard k,k1,k2 \\dots  \\dots kp as edges. And use a Shortest-Path Algorithm to calculate all D[i]. Notice that there are at most 20 operations of type 1, we are able to run such an algorithm after each of these operations. The total time complexity is O(20*k*20*log(k)) with Dijkstra. Secondly, we build a binary-heap to solve operations of type 2 and 3. Type1 - If a D[i] becomes smaller, we put the new cells we can reach into the heap. Type2 - Decrease a value of a node in the heap, or a cell in the \"Treasure Cell\" array. Type3 - Ask the biggest node in the heap and delete it. These are basic operations of binary-heap. The time complexity is O(NlogN). In C++, you can also use priority_queue from STL and lazy-tags. So we can solve the whole problem in O(400klogk+NlogN).",
    "tags": [
      "brute force",
      "data structures",
      "graphs",
      "shortest paths"
    ],
    "rating": 2500
  },
  {
    "contest_id": "311",
    "index": "D",
    "title": "Interval Cubing",
    "statement": "While learning Computational Geometry, Tiny is simultaneously learning a useful data structure called segment tree or interval tree. He has scarcely grasped it when comes out a strange problem:\n\nGiven an integer sequence $a_{1}, a_{2}, ..., a_{n}$. You should run $q$ queries of two types:\n\n- Given two integers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$), ask the sum of all elements in the sequence $a_{l}, a_{l + 1}, ..., a_{r}$.\n- Given two integers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$), let each element $x$ in the sequence $a_{l}, a_{l + 1}, ..., a_{r}$ becomes $x^{3}$. In other words, apply an assignments $a_{l} = a_{l}^{3}, a_{l + 1} = a_{l + 1}^{3}, ..., a_{r} = a_{r}^{3}$.\n\nFor every query of type 1, output the answer to it.\n\nTiny himself surely cannot work it out, so he asks you for help. In addition, Tiny is a prime lover. He tells you that because the answer may be too huge, you should only output it modulo $95542721$ (this number is a prime number).",
    "tutorial": "Consider a number $x$. If we apply an assignment $x = x^{3}$, $x$ becomes $x^{3}$. If we apply such assignment once more, we will get $(x^{3})^{3} = x^{32}$. If we apply such assignment $k$ times, we will get $x^{3k}$. Thus, we can get such a sequence $a_{0} = x, a_{1} = x^{3}, a_{2} = x^{32}, ..., a_{k} = x^{3k}, ...$. Consider a prime $p$. From Fermat's Little Theorem, we can get $x^{p - 1} = 1(mod$ $p)$. Further more, we can get $x^{y} = x^{ymod(p - 1)}(mod$ $p)$, here $a$ $mod$ $b$ means the remainder of a divided by b. Fortunately, $3^{48} = 1(mod$ $(95542721 - 1))$, thus, $x^{3k} = x^{3kmod48}(mod$ $p)$. In other words, $a_{k} = a_{k + 48}$, which means the cycle of the sequence is $T = 48$. Let's come back to the topic. Each time we run a 1-type query, for every $i$ in the range $[l, r]$, we apply such an assignment $a_{i} = a_{i}^{3}$. At any moment some $i$ has been applied 48 times such assignments, we can consider this $i$ hasn't been applied any assignments before. We can use segment tree to solve this problem. Every node of the segment tree maintains some information: the times that we applied assignments in the node's whole range(it's a lazy tag), current sum of the node's corresponding range and the sum of the node's range after we applied assignments $k(1  \\le  k < 48)$ times. In such a way, we can solve the problem in $O(n \\cdot T + q \\cdot T \\cdot logn)$ time.",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "311",
    "index": "E",
    "title": "Biologist",
    "statement": "SmallR is a biologist. Her latest research finding is how to change the sex of dogs. In other words, she can change female dogs into male dogs and vice versa.\n\nShe is going to demonstrate this technique. Now SmallR has $n$ dogs, the costs of each dog's change may be different. The dogs are numbered from 1 to $n$. The cost of change for dog $i$ is $v_{i}$ RMB. By the way, this technique needs a kind of medicine which can be valid for only one day. So the experiment should be taken in one day and each dog can be changed at most once.\n\nThis experiment has aroused extensive attention from all sectors of society. There are $m$ rich folks which are suspicious of this experiment. They all want to bet with SmallR forcibly. If SmallR succeeds, the $i$-th rich folk will pay SmallR $w_{i}$ RMB. But it's strange that they have a special method to determine whether SmallR succeeds. For $i$-th rich folk, in advance, he will appoint certain $k_{i}$ dogs and certain one gender. He will think SmallR succeeds if and only if on some day the $k_{i}$ appointed dogs are all of the appointed gender. Otherwise, he will think SmallR fails.\n\nIf SmallR can't satisfy some folk that isn't her friend, she need not pay him, but if someone she can't satisfy is her good friend, she must pay $g$ RMB to him as apologies for her fail.\n\nThen, SmallR hope to acquire money as much as possible by this experiment. Please figure out the maximum money SmallR can acquire. By the way, it is possible that she can't obtain any money, even will lose money. Then, please give out the minimum money she should lose.",
    "tutorial": "Obviously, It is about min-cut, which can be solved by max-flow. So, this problem can regarded as the minimum of losing money if we assume SmallR can get all the money and get a total money(sum of wi)at first. Define that, in the min-cut result, the dogs which are connected directly or indirectly to S are 0-gender.otherwise, those to T are 1-gender.We can easily find that the point of a initial-0-gender dog should get a vi weight edge to S.On the other way, initial-1-gender to T. Then, consider the rich men.As to each of rich men, he can appoint only one gender and some dogs.if any one dog he appoint is not the one appointed gender in the result, he can't give SmallR money.How to deal with the rich men in the graph is a difficulty.We can do this, make a new point for a rich man.Then, link the man's point to all points of his dogs by max enough weigh edges(which we can't cut in the min-cut algorithm), and link the man's point to S or T (which depend on that the man's appointed gender is 0 or 1) with a edge of wi weight. lastly run the min-cut(max-flow), we will get the minimum money we will lose. The answer is TotalMoney-LosedMoney. BTW, the issue of g is a piece of cake, we could add it to every special wi but not add it to the total money.",
    "tags": [
      "flows"
    ],
    "rating": 2300
  },
  {
    "contest_id": "312",
    "index": "A",
    "title": "Whose sentence is it?",
    "statement": "One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said \"lala.\" at the end of her sentences, while Rainbow always said \"miao.\" at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.",
    "tutorial": "We only need to find out if \"miao.\" is a prefix of the sentence, and if \"lala.\" is a suffix of the sentence. Pay attention to the situation when both conditions are satisfied.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "312",
    "index": "B",
    "title": "Archer",
    "statement": "SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is $\\overset{\\stackrel{\\alpha}{b}}$ for SmallR while $\\frac{\\epsilon}{d}$ for Zanoes. The one who shoots in the target first should be the winner.\n\nOutput the probability that SmallR will win the match.",
    "tutorial": "let p=a/b,q=(1-c/d)*(1-a/b). The answer of this problem can be showed as:p*q^0+p*q^1+p*q^2+ \\dots  \\dots  \\dots  \\dots  That is the sum of a geometric progression which is infinite but 0<q<1.We can get the limit by the formula:p/(1-q)",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 1300
  },
  {
    "contest_id": "313",
    "index": "A",
    "title": "Ilya and Bank Account",
    "statement": "Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money.\n\nIlya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance.\n\nIlya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.",
    "tutorial": "Ilya and Bank Account This problem is the easiest one. You need to use only div and mod functions. If $n$>0, then answer is $n$, else you need to delete one of two digits.",
    "code": "#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <map>\n#include <set>\n#include <string>\n#include <vector>\n \n#define max(a, b) (((a) > (b)) ? (a) : (b))\n#define min(a, b) (((a) > (b)) ? (b) : (a))\n#define abs(a) (((a) > 0) ? (a) : (-(a)))\n \ntypedef long long ll;\n \nusing namespace std;\n \nint main () {\n\tint n;\n\tcin >> n;\n\tint Max = n;\n\tif (n/10 > Max) Max = n/10;\n\tif (n%10 + (n/100)*10 > Max) Max = n%10 + (n/100)*10;\n\tcout << Max;\n}\n ",
    "tags": [
      "implementation",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "313",
    "index": "B",
    "title": "Ilya and Queries",
    "statement": "Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.\n\nYou've got string $s = s_{1}s_{2}... s_{n}$ ($n$ is the length of the string), consisting only of characters \".\" and \"#\" and $m$ queries. Each query is described by a pair of integers $l_{i}, r_{i}$ $(1 ≤ l_{i} < r_{i} ≤ n)$. The answer to the query $l_{i}, r_{i}$ is the number of such integers $i$ $(l_{i} ≤ i < r_{i})$, that $s_{i} = s_{i + 1}$.\n\nIlya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.",
    "tutorial": "Precalculate some array $A_{i}$, that $A_{i} = 1$, if $s_{i} = s_{i + 1}$, else $A_{i} = 0$. Now for any query $(l, r)$, you need to find sum of $A_{i}$, that $(l  \\le  i < r)$. It is standart problem. For solving this problem you can precalcutate some another array Sum, where $Sum_{i} = A_{1} + A_{2} + ... + A_{i}$. Then sum of interval $(l, r)$ is Sum_r - Sum_{l-1}.",
    "code": "Var a,l,r:array[1..1000000] of longint;\n    s:string;\n    i,m,k:longint;\nbegin\n Readln(s);\n for i:=2 to length(s) do\n  begin\n   if s[i]=s[i-1] then inc(k);\n   a[i]:=k;\n  end;\n Readln(m);\n for i:=1 to m do\n  Readln(l[i],r[i]);\n for i:=1 to m do\n  Writeln(a[r[i]]-a[l[i]]);\nend.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "313",
    "index": "C",
    "title": "Ilya and Matrix",
    "statement": "Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.\n\nHe's got a square $2^{n} × 2^{n}$-sized matrix and $4^{n}$ integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum.\n\nThe beauty of a $2^{n} × 2^{n}$-sized matrix is an integer, obtained by the following algorithm:\n\n- Find the maximum element in the matrix. Let's denote it as $m$.\n- If $n = 0$, then the beauty of the matrix equals $m$. Otherwise, a matrix can be split into 4 non-intersecting $2^{n - 1} × 2^{n - 1}$-sized submatrices, then the beauty of the matrix equals the sum of number $m$ and other four beauties of the described submatrices.\n\nAs you can see, the algorithm is recursive.\n\nHelp Ilya, solve the problem and print the resulting maximum beauty of the matrix.",
    "tutorial": "At the start sort array. Let $C_{i}$ - number of times of entering the number in $A_{i}$ optimal placement. Answer is sum of $A_{i} * C_{i}$ for all $i$ $(1  \\le  i  \\le  4^{n})$. If we look at the array $C$, we can see that for maximal element $C = n + 1$ (for array with size $4^{n}$), then for second, third and fourth maximum elements $C = n$. On this basis we can see, that for array with non-increasing order answer calculate like $Sum(1, 1) + Sum(1, 4) + Sum(1, 16) + ... + Sum(1, 4^{n})$. So, for solve this problem you have to know only sort.",
    "code": "#include <cstdio>\n#include <iostream>\n#include <algorithm>\n \nusing namespace std;\n \nint main() {\n  int n;\n  long long s;\n  vector<int> a;\n \n  scanf(\"%d\", &n);\n  a.resize(n);\n  for (int i = 0; i < n; ++i) {\n    scanf(\"%d\", &a[i]);\n  }\n  sort(a.rbegin(), a.rend());\n  s = 0;\n  for (int m = 1; m <= n; m *= 4) {\n    s += accumulate(a.begin(), a.begin() + m, 0LL);\n  }\n  cout << s << endl;\n \n  return 0;\n}\n ",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "313",
    "index": "D",
    "title": "Ilya and Roads",
    "statement": "Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as $n$ holes in a row. We will consider the holes numbered from 1 to $n$, from left to right.\n\nIlya is really keep on helping his city. So, he wants to fix at least $k$ holes (perharps he can fix more) on a single ZooVille road.\n\nThe city has $m$ building companies, the $i$-th company needs $c_{i}$ money units to fix a road segment containing holes with numbers of at least $l_{i}$ and at most $r_{i}$. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment.\n\nDetermine the minimum money Ilya will need to fix at least $k$ holes.",
    "tutorial": "To solve this problem you need to use dynamic programming. Let $Full_{i, j}$ - minimal cost of covering interval $(i, j)$. Fix left border and move right. You can solve this subtask with complexity $O(nm)$ or $O(nmlogn)$. Now we need to solve the standart problem of dynamic programming. Cover $K$ points with intervals that have not intersect. This problem with square dynamic. $dp_{i, j}$ - minimal cost of covering $j$-points, if you look some prefix length $i$. Answer for all problem is minimal integer from $dp_{i, j}$, $(k  \\le  j  \\le  n)$. To solve second part: $1)$ $dp_{i + 1, j} = min(dp_{i + 1, j}, dp_{i, j})$ - skip point with number $i + 1$ $2)$ $dp_{k, j + len} = min(dp_{k, j + len}, dp_{i, j} + Cost)$; $Cost$ - cost of interval with length $len$, that ending at point k. We precalculate $Cost$ at first part of solution.",
    "code": "#include <cstdio>\n#include <iostream>\n#include <algorithm>\n \nusing namespace std;\n \ntypedef long long llint;\n \nconst int MAXN = 320;\nconst llint INF = 0x0123456789ABCDEFLL;\n \nllint d[MAXN][MAXN], dp[MAXN][MAXN];\n \nint main() {\n  int n, m, k, a, b, c;\n  llint ans;\n \n  scanf(\"%d%d%d\", &n, &m, &k);\n \n  fill(d[0], d[n + 1], INF);\n  for (int i = 0; i < m; ++i) {\n    scanf(\"%d%d%d\", &a, &b, &c);\n    --a;\n    d[a][b] = min<llint>(d[a][b], c);\n  }\n  for (int i = 0; i <= n; ++i) {\n    for (int j = 1; j <= n; ++j) {\n      d[j][i] = min(d[j][i], d[j - 1][i]);\n    }\n  }\n \n  fill(dp[0], dp[n + 1], INF);\n  for (int i = 0; i < n; ++i) {\n    dp[i][0] = 0;\n    for (int j = 0; j <= i; ++j) {\n      if (dp[i][j] == INF) {\n        continue;\n      }\n      dp[i + 1][j] = min(dp[i + 1][j], dp[i][j]);\n      for (int k = i + 1; k <= n; ++k) {\n        dp[k][j + (k - i)] = min(dp[k][j + (k - i)], dp[i][j] + d[i][k]);\n      }\n    }\n  }\n \n  ans = *min_element(dp[n] + k, dp[n + 1]);\n  if (ans == INF) {\n    ans = -1;\n  }\n  cout << ans << endl;\n \n  return 0;\n}\n ",
    "tags": [
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "313",
    "index": "E",
    "title": "Ilya and Two Numbers",
    "statement": "Ilya has recently taken up archaeology. He's recently found two numbers, written in the $m$-based notation. Each of the found numbers consisted of exactly $n$ digits. Ilya immediately started looking for information about those numbers. He learned that the numbers are part of a cyphered code and the one who can decypher it can get the greatest treasure.\n\nAfter considerable research Ilya understood that to decypher the code, he should do the following:\n\n- Rearrange digits in the first number in some manner. Similarly, rearrange digits in the second number in some manner. As a result of this operation, the numbers can get leading zeroes.\n- Add numbers, digit by digit, modulo $m$. In other words, we need to get the third number of length $n$, each digit of the number is the sum of the respective numbers of the found numbers. For example, suppose there are two numbers recorded in the ternary notation, 001210 and 012111, then if you add them to each other digit by digit modulo 3, you will get number 010021.\n- The key to the code is the maximum possible number that can be obtained in the previous step.\n\nHelp Ilya, find the key to the code.",
    "tutorial": "1) Get the number of our sequences in sorted by frequencies. Thus from the first sequence (hereinafter - the first type) - in a direct order from the second - to the contrary. 2) These numbers are put on the stack, where if, recording onto the stack of the second type, we find the number at the top of the first type, then this pair of extract and add to the answer. 3) At the end, obviously the stack we can find a number of properties of the second type and the first bottom - on. Then their grouping in response pairs with the start and end.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <algorithm>\n#include <map>\n#include <queue>\n#include <vector>\n#include <string>\n#include <cmath>\n#define Mod (1000000007LL)\n#define eps (1e-8)\n#define Pi (acos(-1.0))\nusing namespace std;\nint n,m;\nint f1[100100],f2[100100];\nint f[200200],tot;\nint ans[100100],x,y;\nint main()\n{\n    while(~scanf(\"%d%d\",&n,&m))\n    {\n        memset(f1,0,sizeof(f1));\n        memset(f2,0,sizeof(f2));\n        memset(ans,0,sizeof(ans));\n        tot=0;\n        for(int i=0;i<n;i++)\n        {\n            scanf(\"%d\",&x);\n            x%=m;\n            f1[x]++;\n        }\n        for(int i=0;i<n;i++)\n        {\n            scanf(\"%d\",&x);\n            f2[x]++;\n        }\n        for(int i=0;i<m;i++)\n        {\n            for(int j=0;j<f1[i];j++)\n            f[++tot]=i+1;\n            for(int j=0;j<f2[m-1-i];j++)\n            {\n                if(tot&&f[tot]>0)\n                {\n                    x=f[tot]-1;\n                    y=m-1-i;\n                    tot--;\n                    ans[(x+y)%m]++;\n                   // printf(\"%d\\n\",x+y);\n                }\n                else f[++tot]=-(m-1-i+1);\n            }\n        }\n        for(int i=1;i<=tot/2;i++)\n        {\n            x=-f[i]-1;\n            y=f[1+tot-i]-1;\n            ans[(x+y)%m]++;\n            //printf(\"%d\\n\",x+y);\n        }\n       // printf(\"%d\\n\",tot);\n        for(int i=m-1;i>=0;i--)\n        {\n            //printf(\"%d %d\\n\",i,ans[i]);\n            for(int j=0;j<ans[i];j++)\n            printf(\"%d \",i);\n        }\n        printf(\"\\n\");\n    }\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dsu",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "314",
    "index": "A",
    "title": "Sereja and Contest",
    "statement": "During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.\n\nLet's assume that $n$ people took part in the contest. Let's assume that the participant who got the first place has rating $a_{1}$, the second place participant has rating $a_{2}$, $...$, the $n$-th place participant has rating $a_{n}$. Then changing the rating on the Codesecrof site is calculated by the formula $d_{i}=\\sum_{i=1}^{i-1}(a_{j}\\cdot(j-1)-(n-i)\\cdot a_{i})$.\n\nAfter the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant $d_{i} < k$, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.\n\nWe know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who $d_{i} < k$. We also know that the applications for exclusion from rating were submitted by all participants.\n\nNow Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.",
    "tutorial": "Note that if we remove some of the participants, we never remove the participants with lower numbers as theirs amount will only increase. So just consider the sequence of all the participants, and if the participant does not fit we delete him.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "314",
    "index": "B",
    "title": "Sereja and Periods",
    "statement": "Let's introduce the designation $[x,n]=x+x+\\cdot\\cdot\\cdot+x=\\sum_{i=1}^{n}x$, where $x$ is a string, $n$ is a positive integer and operation \"$ + $\" is the string concatenation operation. For example, $[abc, 2] = abcabc$.\n\nWe'll say that string $s$ can be obtained from string $t$, if we can remove some characters from string $t$ and obtain string $s$. For example, strings $ab$ and $aсba$ can be obtained from string $xacbac$, and strings $bx$ and $aaa$ cannot be obtained from it.\n\nSereja has two strings, $w = [a, b]$ and $q = [c, d]$. He wants to find such maximum integer $p$ $(p > 0)$, that $[q, p]$ can be obtained from string $w$.",
    "tutorial": "It is clear that we can use greedy algorithm to look for the number of occurrences of the 2nd string in the first string, but it works too slow. To speed up the process, you can look at the first line of the string that specifies the second period. And the answer is divided into how many string you need to set the second string. Next, we consider our greedy algorithm. We are going by the first string, till we find the first character of the second string, then the second, third and so on until the last, then again find the first, second, and so the cycle. It is clear that if we stand in the same twice in a state in which the positions in the first string corresponds to one character string that determines the period and the position of the second string are the same, then we obtain the period. When we find this period, we can just repeat it as many times as possible. To better understand, I advise you to read any accepted solution.",
    "tags": [
      "binary search",
      "dfs and similar",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "314",
    "index": "C",
    "title": "Sereja and Subsequences",
    "statement": "Sereja has a sequence that consists of $n$ positive integers, $a_{1}, a_{2}, ..., a_{n}$.\n\nFirst Sereja took a piece of squared paper and wrote all \\textbf{distinct} non-empty non-decreasing subsequences of sequence $a$. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all sequences that do not exceed it.\n\nA sequence of positive integers $x = x_{1}, x_{2}, ..., x_{r}$ doesn't exceed a sequence of positive integers $y = y_{1}, y_{2}, ..., y_{r}$, if the following inequation holds: $x_{1} ≤ y_{1}, x_{2} ≤ y_{2}, ..., x_{r} ≤ y_{r}$.\n\nNow Sereja wonders, how many sequences are written on the lines piece of paper. Help Sereja, find the required quantity modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "It is clear that we need to calculate the sum of the products of elements of all the different non-decreasing subsequences of given sequence. Let's go through the sequence from left to right and maintain the array q[i]: what means the sum of all relevant sub-sequences, such that their last element is equal to i. Clearly, if the next number is x, then you need to put q[x] = sum (q[1] + q[2] + ... + q[x]) * x + x. The answer to the problem is the sum of q[i]. To find all the amounts you can use Fenwick tree.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "314",
    "index": "D",
    "title": "Sereja and Straight Lines",
    "statement": "Sereja placed $n$ points on a plane. Now Sereja wants to place on the plane two straight lines, intersecting at a right angle, so that one of the straight lines intersect the $Ox$ axis at an angle of $45$ degrees and the maximum distance from the points to the straight lines were minimum.\n\nIn this problem we consider the distance between points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ equal $|x_{1} - x_{2}| + |y_{1} - y_{2}|$. The distance between the point and the straight lines is the minimum distance from the point to some point belonging to one of the lines.\n\nHelp Sereja, find the maximum distance from the points to the optimally located straight lines.",
    "tutorial": "Roll all at 45 degrees using the transformation: (x, y) -> (x ', y'): x '= x + y, y' = x-y. Next you need to place two lines parallel to the coordinate axes. Sort the points by the first coordinate. Next, we use a binary search for the answer. May we have fixed a number, you now need to check whether it is enough or not. Note that now we need to put two strips of width 2 * fixed amount that they would have to cover all the points. Suppose that some point should be close to the left side of the vertical strip, then for all points that do not belong to the strip we find the minimum and maximum second coordinate. If the difference between the found coordinates no more then 2 * fixed quantity, the strip can be placed, otherwise - no.",
    "tags": [
      "binary search",
      "data structures",
      "geometry",
      "sortings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "315",
    "index": "A",
    "title": "Sereja and Bottles",
    "statement": "Sereja and his friends went to a picnic. The guys had $n$ soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.\n\nSereja knows that the $i$-th bottle is from brand $a_{i}$, besides, you can use it to open \\textbf{other} bottles of brand $b_{i}$. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.\n\nKnowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.",
    "tutorial": "Just check for each bottle, can I open it with another. In this task can pass absolutely any solutions.",
    "tags": [
      "brute force"
    ],
    "rating": 1400
  },
  {
    "contest_id": "315",
    "index": "B",
    "title": "Sereja and Array",
    "statement": "Sereja has got an array, consisting of $n$ integers, $a_{1}, a_{2}, ..., a_{n}$. Sereja is an active boy, so he is now going to complete $m$ operations. Each operation will have one of the three forms:\n\n- Make $v_{i}$-th array element equal to $x_{i}$. In other words, perform the assignment $a_{vi} = x_{i}$.\n- Increase each array element by $y_{i}$. In other words, perform $n$ assignments $a_{i} = a_{i} + y_{i}$ $(1 ≤ i ≤ n)$.\n- Take a piece of paper and write out the $q_{i}$-th array element. That is, the element $a_{qi}$.\n\nHelp Sereja, complete all his operations.",
    "tutorial": "We will support all of the elements in the array, but also we will supprt additionally variable add: how much to add to all the elements. Then to add some value to every element we simply increase the add. In the derivation we deduce the value of the array element + add. When you update the item we put to a value, value that you need to put minus the current value of add.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "317",
    "index": "A",
    "title": "Perfect Pair",
    "statement": "Let us call a pair of integer numbers $m$-perfect, if at least one number in the pair is greater than or equal to $m$. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.\n\nTwo integers $x$, $y$ are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, $(x + y)$.\n\nWhat is the minimum number of such operations one has to perform in order to make the given pair of integers $m$-perfect?",
    "tutorial": "This problem were more about accuracy then about ideas or coding. It is important to not forget any cases here. On each step we replace one of the numbers $x$, $y$ by their sum $x + y$ until the pair becomes $m$-perfect (id est one of them becomes not lesser than $m$). It is clear that one sould replace lesser number from the pair $x$, $y$. Indeed lets say the pair $x_{1}  \\le  y_{1}$ dominates the pair $x_{2}  \\le  y_{2}$, if $y_{1}  \\ge  y_{2}$ and $x_{1}  \\ge  y_{2}$. In this case if one can get $m$-perfect pair from $x_{2}$, $y_{2}$ by certain sequence of actions, then one can get $m$-perfect pair from $x_{1}$, $y_{1}$ by the same or shorter sequence of actions. If $x  \\le  y$, then the pair $x + y$, $y$ dominates the pair $x + y$, $x$. Hence path from $x + y$, $y$ to $m$-perfect is not longer than from $x + y$, $x$, and we may assume that we choose exactly this pair. Consider following cases: $x  \\le  0$, $y  \\le  0$ In this case our numbers do not increase in the process. Hence either the pair is alredy $m$-perfect or it will never be. $x > 0$ and $y > 0$ In this case for each $m$ pair will after several steps become $m$-perfect. To count precise number of those steps one needs to launch emulation. If $x > 0$ and $y > 0$, then pair \"grows exponentionaly>> (more formally: easy to show that starting from secnd step sum $x + y$ grows in at least $3 / 2$ times each step) and emulation works pretty fast. However in the case $x < 0$ and $y > 0$ (or vice versa) pair might change very slowly. Most bright example is $x = - 10^{18}$, $y = 1$. Thus one needs to count number of steps until both numbers becomes positive before launching emulationt. For $x < 0$ and $y > 0$ number of those steps is exactly $\\left\\lceil{\\frac{\\lfloor x\\rfloor+y-1}{y}}\\right\\rceil$.",
    "tags": [
      "brute force"
    ],
    "rating": 1600
  },
  {
    "contest_id": "317",
    "index": "B",
    "title": "Ants",
    "statement": "It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction ($x$, $y$) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions ($x + 1$, $y$), ($x - 1$, $y$), ($x$, $y + 1$), ($x$, $y - 1$) — one ant in each direction. No other ant movements will happen. Ants never interfere with each other.\n\nScientists have put a colony of $n$ ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.",
    "tutorial": "One may reformulate the problem ass follows. Non-negative integers $A(x, y)$ are placed in the vertices of two-dimensional lattice $\\mathbb{Z}^{2}$ We may imagine this construction as a function $A\\colon\\mathbb{Z}^{2}\\to\\mathbb{N}_{0}$. On each step for each vertex $P = (x, y)$ with $A(x, y)  \\ge  4$ we perform operation $ \\phi _{P}$, which substracts 4 from $A(x, y)$ and adds 1 to $A(x, y - 1)$, $A(x, y + 1)$, $A(x - 1, y)$, $A(x + 1, y)$. We may think that operation $ \\phi _{P}$ applies to the whole function $A$. We need to find values of $A$ after the iterations stops. Key idea is that operactions $ \\phi _{P}$ and $ \\phi _{Q}$ for all points $P$ and $Q$ commutes, that is $ \\phi _{P}( \\phi _{Q}(A)) =  \\phi _{Q}( \\phi _{P}(A))$. This means that the order of operations is unimportant. In particular, we may assume that from each given vertex run all possible four-groups of ants and not only one. After this observation one may run full emulation of the process. As an exercise contestants may check that ants will never leave square $200  \\times  200$ with center in the origin $0$ with given constraints.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "317",
    "index": "C",
    "title": "Balance",
    "statement": "A system of $n$ vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals $e$. Volume of each vessel equals $v$ liters. Of course, the amount of the water in any vessel cannot exceed $v$ liters in the process of transfusions.\n\nGiven the initial amounts $a_{i}$ of water in the vessels and the desired amounts $b_{i}$ find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed $2·n^{2}$.",
    "tutorial": "In this problem we need to find $2n^{2}$ transfusions from initial configuration to the desired one. First of all we propose the following: if in each connected component overall volume of the water in initial configuration is the same as in desired one, then answer exist. We call the vessel ready, if current volume of its water equals desired one. Let us describe solution which is probably easier to code. We will make vessels ready one by one. Consider the pair of non-ready vessels s and t (there is more water in s than desired, and less water in t than desired), such that they are connected by the path P, and if one transfuses d litres from s to t then one of the vessels becomes ready. Now we need to find a way to transfuse d litres by path P from s to t. One may write recursive function pour(s, t, d) for this aim. Let t' stand before t in this path, then function works as follows: transfuses from t' to t as many water as possible (not more than d of course), then calls pour(s, t', d) and on the final step transfuses from t' to t all that left. It is easy to check that all such transfusions are correct. This algorithm makes $2len$ transfusions on the path of length $len$, so total number of transfusions is not greater than $2n^{2}$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "317",
    "index": "D",
    "title": "Game with Powers",
    "statement": "Vasya and Petya wrote down all integers from $1$ to $n$ to play the \"powers\" game ($n$ can be quite large; however, Vasya and Petya are not confused by this fact).\n\nPlayers choose numbers in turn (Vasya chooses first). If some number $x$ is chosen at the current turn, it is forbidden to choose $x$ or all of its other positive integer powers (that is, $x^{2}$, $x^{3}$, $...$) at the next turns. For instance, if the number $9$ is chosen at the first turn, one cannot choose $9$ or $81$ later, while it is still allowed to choose $3$ or $27$. The one who cannot make a move loses.\n\nWho wins if both Vasya and Petya play optimally?",
    "tutorial": "For each numner $x$ denote sequence of its powers within $[1..n]$ as $Pow(x)$: $P o w(x)=\\{x,x^{2},x^{3},x^{4},\\cdot\\cdot\\cdot\\}\\cap[1..n].$ Game proceeds as follows: on each step one player takes still available number $x$ from $1$ to $n$ and prohibits whole set $Pow(x)$. Who can't make his turn loses. This game may be decomposed in the sum of lesser games. Indeed, lets call number $x$ simple (and corresponding sequence $Pow(x)$ simple), if it is not a power of any number $y < x$. Then: 1. for each $k\\in[1..n]$ there is simple $x$, such that $k\\in P o w(x)$; 2. for each simple distinct $x$ and $y$ sets $Pow(x)$ and $P(y)$ do not intersect. Indeed, for a given $k$ there is exactly one simple $x$ such that $k$ is power of $x$. This may be showed from fundamental theorem of arithmetic: if $k=p_{1}^{\\alpha_{1}}p_{2}^{\\alpha_{2}}\\cdot\\cdot\\cdot p_{\\ell}^{\\alpha_{\\ell}}$ and $d = gcd( \\alpha _{1},  \\alpha _{2}, ...,  \\alpha _{n})$, then $x=p_{1}^{\\alpha_{1}/d}p_{2}^{\\alpha_{2}/d}\\dots p_{\\ell}^{\\alpha_{\\ell}/d}$. Hence set $[1..n]$ decomposes into primitive sets $Pow(x)$, on each of those $Pow(x)$ game proceeds independetly. Now one may use Sprague-Grundy theory to see that mexx of our game is just xor of all mexx of games on simple $Pow(x)$. For fixed $x$, if $Pow(x) = {x, x^{2}, ..., x^{s}}$, then mexx of the game on $Pow(x)$ depends only on $s$, but not on $x$. In our case $s$ runs from $1$ to $29$, mexx for all such $s$ may be directly precalculated. Now it is enough to find numbers $q(s)$ of simple $x$ with a given size of $Pow(x)$ equal to $s$ (actually we are interested in parity of $q(s)$ not in $q(s)$ itself). Our constraints allows to do it directly: run $x$ from $2$ to $\\sqrt{n}$, if it is not crossed out, determine the size $Pow(x)$ [increment corresponding $q(s)$], and cross out all numbers from $Pow(x)$. This cycle finds all simple sequences of length at least $2$. Quantity of non-crossed numbers is the number of all simple sequences of length $1$. Now it is enough to look at parities of $q(s)$ and xor coressponding mexx. However one may find all $q(s)$ for $O(\\log^{2}n)$. Indeed lets look at the number $1<x\\leqslant{\\sqrt{n}}$ and sequence ${x, x^{2}, x^{3}, x^{4}, ..., x^{s}}$. This sequence is not simple iff it is containd in some larger simple sequence. But number of subsequenes of size $s$ in a given sequence of size $t > s$ is easy to find: it is just $[t / s]$. Recalling that simple sequences do not intersect one gets the reccurent formula: $q(s)=[\\hat{\\nabla}\\overline{{{n}}}]-1-\\sum_{t=s+1}q(t)\\cdot\\left[\\frac{t}{s}\\right]$. Now it is easy to find all $q(s)$ from $q(29)$ to $q(1)$. Remark: while coding it is important to remeber simple number $x = 1$.",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 2300
  },
  {
    "contest_id": "317",
    "index": "E",
    "title": "Princess and Her Shadow",
    "statement": "Princess Vlada enjoys springing in the meadows and walking in the forest. One day — wonderful, sunny day — during her walk Princess found out with astonishment that her shadow was missing! \"Blimey!\", — she thought and started her search of the shadow in the forest.\n\nNormally the Shadow is too lazy and simply sleeps under the Princess. But at this terrifically hot summer day she got bored of such a dull life, so she decided to play with Vlada.\n\nThe forest, where our characters entertain themselves, may be represented as a set of integer cells in the plane, where the Shadow and the Princess can move only up, down, left and right by $1$. Some cells (as it happens in decent forests) are occupied by trees. The Shadow and the Princess are not allowed to enter a cell occupied by a tree. Unfortunately, these are the hard times for the forest, so there are very few trees growing here...\n\nAt first the Princess was walking within the cell ($v_{x}$, $v_{y}$), while the Shadow hid from the Princess in the cell ($s_{x}$, $s_{y}$). The Princess, The Shadow and the trees are located in the different cells.\n\nThe Shadow is playing with the Princess. As soon as the Princess moves by $1$ in some direction, the Shadow simultaneously flies by $1$ in the same direction, if it is possible (if the cell to fly to is not occupied by some tree); otherwise, the Shadow doesn't move. The Shadow is very shadowy, so our characters do not interfere with each other.\n\nWe say that the Shadow is caught by the Princess if after some move both of them are located in the same cell. Vlada managed to catch her Shadow! Can you?",
    "tutorial": "In this problem princess Vlada should simply catch the Shadow. Here is the idea of a solution. If there is only one tree, then using it as a barrier to the shadow it is not hard to catch the shadow. Similar technique works if Vlada and Shadow are far from the square where all the trees grow. But what can she do in the dark depths of the forest? If there is no path at all between Vlada and Shadow, then there is no way to catch it. Otherwise consider a shortest path from Vlada to the Shadow and make Vlada follow it. This path gives Vlada a queue of the steps that she should perform. Additionaly if shadow moves, then we add her move to the queue (simply speaking Vlada follows the shadow). This is where the algorithmic part ends. Now we state that either Vlada catches the shadow in the desired number of steps, or steps out of the \"forest square\". To proof this we note that the length of the path between Vlada and Shadow may only decrease. And if it does not decrease long enough, then once in $k$ steps ($k$ is the length of the path) Vlada and Shadow shifts at the same vector over and over, and at some moment leaves the \"forest square\". Note that if the trees allow our heroes to step out of the \"forest square\" at the beginning, then we may just get them out from the start. But taking this approach we still need to catch the Shadow in a \"labyrinth forest\".",
    "tags": [
      "constructive algorithms",
      "shortest paths"
    ],
    "rating": 3100
  },
  {
    "contest_id": "318",
    "index": "A",
    "title": "Even Odds",
    "statement": "Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first $n$. He writes down the following sequence of numbers: firstly all odd integers from $1$ to $n$ (in ascending order), then all even integers from $1$ to $n$ (also in ascending order). Help our hero to find out which number will stand at the position number $k$.",
    "tutorial": "In this problem we need to understand how exactly numbers from $1$ to $n$ rearrange when we write firstly all odd numbers and after them all even numbers. To find out which number stands at position $k$ one needs to find the position where even numbers start and output either the position of the odd number from the first half of the sequence or for the even number from the second half of the sequence.",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "318",
    "index": "B",
    "title": "Strings of Power",
    "statement": "Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.\n\nVolodya calls a string powerful if it starts with \"heavy\" and ends with \"metal\". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.\n\nFor simplicity, let us assume that Volodya's text can be represented as a single string.",
    "tutorial": "In the heavy metal problem one needs to find the number of the substrings in the string S with a given prefix A and given suffix B. If we mark black all the starting positions of the entries of the string A in S, and white all the starting positions of the entries of the string B, then we come to the following problem: count the number of pairs <black position, white position> (in this order). To solve this it is enough to iterate from left to right counting the number of the passed black positions. Meeting black position we increment this number by one, meeting white position we add to the answer the number of pairs with this white position, which is exactly our memorized number of the already passed black positions.",
    "tags": [
      "implementation",
      "strings",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "319",
    "index": "A",
    "title": "Malek Dance Club",
    "statement": "As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has $2^{n}$ members and coincidentally Natalia Fan Club also has $2^{n}$ members. Each member of MDC is assigned a unique id $i$ from $0$ to $2^{n} - 1$. The same holds for each member of NFC.\n\nOne of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers $(a, b)$ such that member $a$ from MDC dances with member $b$ from NFC.\n\nThe complexity of a pairs' assignment is the number of pairs of dancing pairs $(a, b)$ and $(c, d)$ such that $a < c$ and $b > d$.\n\nYou are given a binary number of length $n$ named $x$. We know that member $i$ from MDC dances with member $i\\oplus x$ from NFC. Your task is to calculate the complexity of this assignment modulo $1000000007$ $(10^{9} + 7)$.\n\nExpression $x\\oplus y$ denotes applying «XOR» to numbers $x$ and $y$. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as «^», in Pascal — «xor».",
    "tutorial": "Solving this problem was easy when you modeled the assignment with two sets of points numbered from $0$ to $2^{n} - 1$ (inclusive) paired with $2^{n}$ line segments. Each line segment corresponds to a dance pair. And each pair of intersecting lines increase the complexity by one. Imagine you now the solution for binary string $x$. Now we want to calculate the answer for $1x$ and $0x$ easily. Look at the figure below: The figure shows what happens in a simple case. Whenever you append $0$ before $x$ the same structure appears twice in the result. But whenever you append $1$ before $x$ the same structure appears twice but the first half of points in right column are swapped with the second half. This increases the number of intersections by size of first half times size of the second half. So if $x$ has length $n$ and $f(x)$ is the complexity of the assignment then we have: $f(0x) = 2f(x)$ $f(1x) = 2f(x) + 2^{2n}$ An interesting fact is that $f(x)$ is equal to $x2^{n - 1}$.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "319",
    "index": "C",
    "title": "Kalila and Dimna in the Logging Industry",
    "statement": "Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money.\n\nThe manager of logging factory wants them to go to the jungle and cut $n$ trees with heights $a_{1}, a_{2}, ..., a_{n}$. They bought a chain saw from a shop. Each time they use the chain saw on the tree number $i$, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is $i$ (the tree that have height $a_{i}$ in the beginning), then the cost of charging the chain saw would be $b_{i}$. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each $i$ < $j$, $a_{i} < a_{j}$ and $b_{i} > b_{j}$ and also $b_{n} = 0$ and $a_{1} = 1$. Kalila and Dimna want to cut all the trees completely, with minimum cost.\n\nThey want you to help them! Will you?",
    "tutorial": "This problem is equal to finding the minimum cost to cut the last tree completely. Because any cutting operation can be done with no cost afterward. Let $dp_{i}$ be the minimum cost to cut the $i$-th tree completely. It's easy to figure out that we can calculate $dp_{i}$ if we know the index of the last tree which has been cut completely ($j$-th tree). Knowing this $dp_{i}$ would be equal to $dp_{j} + b_{j}a_{i}$. So $dp_{i} = min_{j = 1..i - 1}(dp_{j} + b_{j}a_{i})$. Using the above information the problem has an easy dynamic programming solution in $O(n^{2})$. There's a known method which can be used to improve recursive relations with similar form. It's called Convex Hull Trick. You can read about it here.",
    "tags": [
      "dp",
      "geometry"
    ],
    "rating": 2100
  },
  {
    "contest_id": "320",
    "index": "A",
    "title": "Magic Numbers",
    "statement": "A magic number is a number formed by concatenation of numbers $1$, $14$ and $144$. We can use each of these numbers any number of times. Therefore $14144$, $141414$ and $1411$ are magic numbers but $1444$, $514$ and $414$ are not.\n\nYou're given a number. Determine if it is a magic number or not.",
    "tutorial": "Although the input number is very small, solving the problem for arbitrary length numbers using strings is easier. It's easy to prove that a number meeting the following conditions is magical: The number should only consist of digits $1$ and $4$. The number should begin with digit $1$. The number should not contain three consecutive fours (i.e. $444$).",
    "code": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nbool is_magical(string number) {\n\tfor (int i = 0; i < (int)number.size(); i++)\n\t\tif (number[i] != '1' && number[i] != '4')\n\t\t\treturn false;\n\n\tif (number[0] == '4')\n\t\treturn false;\n\n\tif (number.find(\"444\") != number.npos)\n\t\treturn false;\n\n\treturn true;\n}\n\nint main() {\n\tstring number;\n\tcin >> number;\n\n\tif (is_magical(number))\n\t\tcout << \"YES\" << endl;\n\telse\n\t\tcout << \"NO\" << endl;\n\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "320",
    "index": "B",
    "title": "Ping-Pong (Easy Version)",
    "statement": "In this problem at each moment you have a set of intervals. You can move from interval $(a, b)$ from our set to interval $(c, d)$ from our set if and only if $c < a < d$ \\textbf{or} $c < b < d$. Also there is a path from interval $I_{1}$ from our set to interval $I_{2}$ from our set if there is a sequence of successive moves starting from $I_{1}$ so that we can reach $I_{2}$.\n\nYour program should handle the queries of the following two types:\n\n- \"1 x y\" $(x < y)$ — add the new interval $(x, y)$ to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.\n- \"2 a b\" $(a ≠ b)$ — answer the question: is there a path from $a$-th (one-based) added interval to $b$-th (one-based) added interval?\n\nAnswer all the queries. Note, that initially you have an empty set of intervals.",
    "tutorial": "Imagine the intervals as nodes of a graph and draw directed edges between them as defined in the statement. Now answering the second query would be trivial if you are familiar with graph traversal algorithms like DFS or BFS or even Floyd-Warshall!",
    "code": "#include<iostream>\n#include<string.h>\nusing namespace std;\n \nint a[111],b[111];\n \nbool f[111];\nint n = 0;\nvoid dfs(int i)\n{\n    f[i] = true;\n    for(int k = 1; k <= n;k++)\n    {\n        if(f[k])\n            continue;\n        if(a[i]>a[k] && a[i] < b[k])\n            dfs(k);\n        else if(b[i] > a[k] && b[i] < b[k])\n            dfs(k);\n    }\n}\n \n \nint k;\n \nint main()\n{\n    cin >> k;\n    memset(a,0,sizeof(a));\n    memset(b,0,sizeof(b));\n    memset(f,0,sizeof(f));\n    for(int i = 1; i <= k; i++)\n    {\n        int x,y,m;\n        cin >> m;\n        if(m == 1)\n        {\n            n++;\n            cin >> a[n];\n            cin >> b[n];\n        }\n        if(m == 2)\n        {\n            cin >> x;\n            cin >> y;\n            memset(f,0,sizeof(f));\n            dfs(x);\n            if(f[y])\n                cout << \"YES\" << endl;\n            else\n                cout << \"NO\" << endl;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "321",
    "index": "A",
    "title": "Ciel and Robot",
    "statement": "Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string $s$. Each character of $s$ is one move operation. There are four move operations at all:\n\n- 'U': go up, (x, y) $ → $ (x, y+1);\n- 'D': go down, (x, y) $ → $ (x, y-1);\n- 'L': go left, (x, y) $ → $ (x-1, y);\n- 'R': go right, (x, y) $ → $ (x+1, y).\n\nThe robot will do the operations in $s$ from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in $(a, b)$.",
    "tutorial": "Note that after Ciel execute string s, it will moves (dx, dy). And for each repeat, it will alway moves (dx, dy). So the total movement will be k * (dx, dy) + (dx[p], dy[p]) which (dx[p], dy[p]) denotes the movement after execute first p characters. We can enumerate p since (0 <= p < |s| <= 100), and check if there are such k exists. Note that there are some tricks: We can divide dx or dy directly because they both can become zero. Another trick is that k must be non-negative. Many people failed on this test case (which no included in the pretest): -1 -1 UR",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "321",
    "index": "B",
    "title": "Ciel and Duel",
    "statement": "Fox Ciel is playing a card game with her friend Jiro.\n\nJiro has $n$ cards, each one has two attributes: $position$ (Attack or Defense) and $strength$. Fox Ciel has $m$ cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.\n\nNow is Ciel's battle phase, Ciel can do the following operation many times:\n\n- Choose one of her cards $X$. This card mustn't be chosen before.\n- If Jiro has no alive cards at that moment, he gets the damage equal to ($X$'s strength). Otherwise, Ciel needs to choose one Jiro's alive card $Y$, then:\n\n- If $Y$'s position is Attack, then ($X$'s strength) $ ≥ $ ($Y$'s strength) must hold. After this attack, card $Y$ dies, and Jiro gets the damage equal to ($X$'s strength) - ($Y$'s strength).\n- If $Y$'s position is Defense, then ($X$'s strength) $ > $ ($Y$'s strength) must hold. After this attack, card $Y$ dies, but Jiro gets no damage.\n\nCiel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.",
    "tutorial": "We have 3 solutions to this problem: = 1. greedy = There are 2 cases: we killed all Jiro's cards, or not. If we are not killed all of Jiro's cards, then: We never attack his DEF cards, it's meaningless. Suppose we make k attacks, then it must be: use Ciel's k cards with highest strength to attack Jiro's k cards with lowest strength, and we can sort the both k cards by strength to make attack one by one. (If there are an invalid attack, then we can't have k attack) If we kill all Jiro's card: Then for all DEF cards, we consider it from lower strength to higher: if its strength is L, then we find a card of Ciel with strength more than L (If there are many, we choose one with lowest strength). Then we can know if we can kill all DEF cards. And then we choose |x| cards with highest strength of Ciel, try to kill Jiro's remain card. Note that if we could kill all ATK cards, the order doesn't matter: the total damage will be (sum of strength of Ciel's remain card) - (sum of strength of Jiro's remain card). = 2. DP = Above solution looks complicated, can we solve it with few observation? Yes we can. The only observation is that: There always exist an optimal solution that: If Ciel's two card X's strength > Y's strength, and X, Y attacks on A and B with the same position, then A's strength > B's strength. We already use this observation in above solution. Then what can we do? Yes, we can sort all Ciel's card, all ATK card of Jiro, all DEF card of Jiro. Let's DP[pCiel][pATK][pJiro][killAll] be the state that next unconsidered card of Ciel, Jiro's ATk, Jiro's DEF are pCiel, pATK, pJiro, and killAll=1 if and only if we assume at the end we can kill all Jiro's card. Then we have 4 choice: Skip, this card don't attack. Attack on the next ATK card. Attack on the next DEF card. Assume Jiro has no cards and make a direct attack. = 3. MinCostMaxFlow = Well, what if we want to solve this problem with no observation? Ok, if you are good at construct flow algorithm, it's an easy thing to solve this by flow. Please see my solution for details. It just considered the matching relationship.",
    "tags": [
      "dp",
      "flows",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "321",
    "index": "C",
    "title": "Ciel the Commander",
    "statement": "Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has $n$ cities connected by $n - 1$ undirected roads, and for any two cities there always exists a path between them.\n\nFox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.\n\nThere are enough officers of each rank. But there is a special rule must obey: if $x$ and $y$ are two distinct cities and their officers have the same rank, then on the simple path between $x$ and $y$ there must be a city $z$ that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.\n\nHelp Ciel to make a valid plan, and if it's impossible, output \"Impossible!\".",
    "tutorial": "This is a problem with construction on trees. And for these kind of problems, we usually use two method: up-down or down-up. So we have 1 solution for each method: = 1. up-down construction = Suppose we assign an officer with rank A at node x. Then for two distinct subtree rooted by x, says T1 and T2: There can't be any invalid path cross T1 and T2, because it is blocked by node x. (It's clear that we can't make 2 rank A officer.) So we can solve these subtree independently: the only different is that we can't use rank A anymore. Then the question is: which node should x be? It could be good if any subtree will has a small size. And if you have the knowledge of \"centroid of tree\", then you can quickly find that if x be the centroid of this tree, the subtree's size will be no more than half of the original tree. So we only needs about log2(n) nodes and 26 is enough. = 2. down-up construction = The above solution involves the concept of \"centroid of tree\" but you might not heard about that, don't worry, we have another solution can solve this problem without knowing that, and it's easier to implement. Suppose we choose 1 as the root and consider it as a directed tree, and on some day we have the following problem: We have some subtree rooted at T1, T2, ..., Tk, and they are already assigned an officer, we need to assign an officer to node x and link them to this node. Well, a normal idea is: we choose one with lowest possible rank. The rank of x should satisfy: If there are a node with rank t exposes at Ti and a node with t exposes at Tj (i!=j), then rank of x must be higher than t. (Otherwise the path between them will be invalid.) If there are a node with rank t exposes at Ti, then the rank of x can't be t. So we can use this rule to choose the lowest possible rank. But can it passes? Yes, it can, but the proof is not such easy, I'll introduce the main idea here: We assign each node a potential: p(x) = {2^('Z' - w) | w is exposed}. For example, if 'Y' and 'Z' are exposed, then p(x) = 1 + 2 = 3. We can proof p(x) <= |# of nodes of the subtree rooted by x| by proof this lemma: When we synthesis x with T1, T2, ..., Tk, p(x) <= 1 + p(T1) + ... + p(Tk). It's not hard to proof, but might have some cases to deal with.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "divide and conquer",
      "greedy",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "321",
    "index": "D",
    "title": "Ciel and Flipboard",
    "statement": "Fox Ciel has a board with $n$ rows and $n$ columns, there is one integer in each cell.\n\nIt's known that $n$ is an odd number, so let's introduce $x={\\frac{n+1}{2}}$. Fox Ciel can do the following operation many times: she choose a sub-board with size $x$ rows and $x$ columns, then all numbers in it will be multiplied by -1.\n\nReturn the maximal sum of numbers in the board that she can get by these operations.",
    "tutorial": "For this problem we need a big \"observation\": what setup of \"flips\" are valid? What means set up of \"flips\", well, for example, after the 1st step operation of example 1, we get: 1 1 0 1 1 0 0 0 0It means the left top 2x2 cells are negatived. Given a 0-1 matrix of a set up of \"flips\", how can you determine if we can get it by some N x N (I use N instead of x here, it don't make sense to write something like x x x.) flips. To solve this problem, we need the following observation: For any i, any j<=x: setUp[i][j]^setUp[i][x]^setUp[i][j+x] will be 0. For any i, any j<=x: setUp[j][i]^setUp[x][i]^setUp[j+x][i] will be 0. It's quite easy to proof than find that: after each operation, there always be 0 or 2 cells lay in {setUp[i][j], setUp[i][x], setUp[i][j+x]} or {setUp[j][i], setUp[x][i], setUp[j+x][i]}. So what? Well, then there must be no more than 2^(N*N) solutions, since if we determine the left top N x N cells, we can determine others by above equations. And then? Magically we can proof if one set up meets all above equations, we can get it. And the proof only needs one line: think the operation as addition of vectors in GF2, then we have N*N independent vector, so there must be 2^(N*N) different setups we can get. (Yes, I admit it need some knowledge, or feeling in linear algebra) Then the things are easy: we enumerate {setUp[1][N], setUp[2][N], ..., setUp[N][N]}, and determine others by greedy. (More detailed, by columns.)",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "321",
    "index": "E",
    "title": "Ciel and Gondolas",
    "statement": "Fox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are $n$ people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and $n$-th people to refer the last one in the queue.\n\nThere will be $k$ gondolas, and the way we allocate gondolas looks like this:\n\n- When the first gondolas come, the $q_{1}$ people in head of the queue go into the gondolas.\n- Then when the second gondolas come, the $q_{2}$ people in head of the remain queue go into the gondolas....\n- The remain $q_{k}$ people go into the last ($k$-th) gondolas.\n\nNote that $q_{1}$, $q_{2}$, ..., $q_{k}$ must be positive. You can get from the statement that $\\sum_{i=1}^{k}q_{i}=n$ and $q_{i} > 0$.\n\nYou know, people don't want to stay with strangers in the gondolas, so your task is to find an optimal allocation way (that is find an optimal sequence $q$) to make people happy. For every pair of people $i$ and $j$, there exists a value $u_{ij}$ denotes a level of unfamiliar. You can assume $u_{ij} = u_{ji}$ for all $i, j$ $(1 ≤ i, j ≤ n)$ and $u_{ii} = 0$ for all $i$ $(1 ≤ i ≤ n)$. Then an unfamiliar value of a gondolas is the sum of the levels of unfamiliar between any pair of people that is into the gondolas.\n\nA total unfamiliar value is the sum of unfamiliar values for all gondolas. Help Fox Ciel to find the minimal possible total unfamiliar value for some optimal allocation.",
    "tutorial": "This problem may jog your memory of OI times (if you have been an OIer and now grows up, like me). Maybe some Chinese contestants might think this problem doesn't worth 2500, but DP optimization is an advanced topic in programming contest for many regions. It's quite easy to find an O(N^2 K) DP: dp[i][j] = max{ k | dp[i-1][k] + cost(k+1...j)} (dp[i][j] means the minimal cost if we divide 1...j foxes into i groups) There are many ways to optimize this kind of dp equation, but a large part of them based one the property of cost function. So we need to find some property independent of cost function. Let opt[i][j] = the smallest k such that dp[i][j] = dp[i][k] + cost(k+1...j) Then intuitively we have opt[i][1] <= opt[i][2] <= ... <= opt[i][n]. (I admit some people don't think it's intuitively correct, but it can proof by some high school algebra) Then how to use this stuff? Let n = 200 and suppose we already get dp[i][j] for i<=3 and now we have to compute dp[4][j]: If we first compute dp[4][100], then we can have opt[4][100] at the same time. And when we compute dp[4][1] ... dp[4][99], we know that the k must lay in 1...opt[4][100]. When we compute dp[4][101] ... dp[4][200], we know that k must lay in opt[4][100]...n. Let's formalize this thing: We use compute(d, L, R, optL, optR) to denote we are computing dp[d][L...R], and we know the k must be in range optL...optR. Then we have: compute(d, L, R, optL, optR) = 1. special case: L==R. 2. let M = (L+R) / 2, we solve dp[d][M] as well as opt[d][M]. Uses about (optR-optL+1) operations. 3. compute(d, L, M-1, optL, opt[d][M]) 4. compute(d, M+1, R, opt[d][M], optR)One can show that this solution will run in O(NlogN * K). Note that we don't need opt[d][M] at the center of interval optL...optR. We can proof at each recursive depth, the total cost by line 2 will be no more than 2n. And there are at most O(log(n)) depths.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "322",
    "index": "A",
    "title": "Ciel and Dancing",
    "statement": "Fox Ciel and her friends are in a dancing room. There are $n$ boys and $m$ girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:\n\n- either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before);\n- or the girl in the dancing pair must dance for the first time.\n\nHelp Fox Ciel to make a schedule that they can dance as many songs as possible.",
    "tutorial": "Let's define remainNew = # of people haven't danced before. So at beginning remainNew = n+m, and we have: During the 1st song, remainNew must decreased by at least 2. (Because the boy and girl must haven't danced before.) During the k-th (k>1) song, remainNew must decreased by at least 1. (Because one of the boy or girl must haven't danced before.) So the answer must be no more than n+m-1. And it's not hard to construct one schedule get this maximal possible answer: 1 1 1 2 ... 1 m 2 1 3 1 ... n 1",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "322",
    "index": "B",
    "title": "Ciel and Flowers",
    "statement": "Fox Ciel has some flowers: $r$ red flowers, $g$ green flowers and $b$ blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:\n\n- To make a \"red bouquet\", it needs 3 red flowers.\n- To make a \"green bouquet\", it needs 3 green flowers.\n- To make a \"blue bouquet\", it needs 3 blue flowers.\n- To make a \"mixing bouquet\", it needs 1 red, 1 green and 1 blue flower.\n\nHelp Fox Ciel to find the maximal number of bouquets she can make.",
    "tutorial": "If there are no \"mixing bouquet\" then the answer will be r/3 + g/3 + b/3. One important observation is that: There always exist an optimal solution with less than 3 mixing bouquet. The proof is here: Once we get 3 mixing bouquet, we can change it to (1 red bouquet + 1 green bouquet + 1 blue bouquet) So we can try 0, 1, 2 mixing bouquet and make the remain 3 kind of bouquets use above greedy method. Output one with largest outcome.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "325",
    "index": "A",
    "title": "Square and Rectangles",
    "statement": "You are given $n$ rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the $Ox$ and $Oy$ axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).\n\nYour task is to determine if the rectangles form a square. In other words, determine if the set of points inside or on the border of at least one rectangle is precisely equal to the set of points inside or on the border of some square.",
    "tutorial": "What happens if the rectangles form an $N  \\times  N$ square? Then these two conditions are necessary. 1) The area must be exactly $N  \\times  N$. 2) The length of its sides must be $N$. That means, the difference between the right side of the rightmost rectangle - the left side of the leftmost rectangle is $N$. Same for topmost and bottommost rectangles. We claim that, since the rectangles do not intersect, those two conditions are also sufficient. This is since if there are only $N  \\times  N$ space inside the box bounded by the leftmost, rightmost, topmost, and bottommost rectangles. Thus if the sum of the area is exactly $N  \\times  N$, all space must be filled -- which forms a square.",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "325",
    "index": "B",
    "title": "Stadium and Games",
    "statement": "Daniel is organizing a football tournament. He has come up with the following tournament format:\n\n- In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even.\n- Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are $x$ teams, there will be $\\textstyle{\\frac{x(x-1)}{2}}$ games), and the tournament ends.\n\nFor example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.\n\nDaniel has already booked the stadium for $n$ games. Help him to determine how many teams he should invite so that the tournament needs \\textbf{exactly} $n$ games. You should print all possible numbers of teams that will yield exactly $n$ games in ascending order, or -1 if there are no such numbers.",
    "tutorial": "Suppose the \"divide-by-two\" stage happens exactly $D$ times, and the round robin happens with $M$ people. Then, the number of games held is: ${\\frac{M(M-1)}{2}}+M\\times(2^{D}-1)$ We would like that ${\\frac{M(M-1)}{2}}+M\\times(2^{D}-1)=N$ This is an equation with two variables -- to solve it, we can enumerate the value of one of the variables and calculate the value of the other one. We cannot enumerate the possible values of $M$, since $M$ can vary from 1 to 10^9. However, we can enumerate D, since the number scales exponentially with $D$ -- that is, we should only enumerate $0  \\le  D  \\le  62$. Thus, the equation is reduced to ${\\frac{M(M-1)}{2}}+M\\times C=N$ Since this function is increasing, this can be solved via binary search on M.",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "325",
    "index": "C",
    "title": "Monsters and Diamonds",
    "statement": "Piegirl has found a monster and a book about monsters and pies. When she is reading the book, she found out that there are $n$ types of monsters, each with an ID between $1$ and $n$. If you feed a pie to a monster, the monster will split into some number of monsters (possibly zero), and at least one colorful diamond. Monsters may be able to split in multiple ways.\n\nAt the begining Piegirl has exactly one monster. She begins by feeding the monster a pie. She continues feeding pies to monsters until no more monsters are left. Then she collects all the diamonds that were created.\n\nYou will be given a list of split rules describing the way in which the various monsters can split. Every monster can split in at least one way, and if a monster can split in multiple ways then each time when it splits Piegirl can choose the way it splits.\n\nFor each monster, determine the smallest and the largest number of diamonds Piegirl can possibly collect, if initially she has a single instance of that monster. Piegirl has an unlimited supply of pies.",
    "tutorial": "First part of the problem is to find minimum number of diamonds one can achieve by starting with a given monster. To do so, we will be using Dijkstra algorithm. Originally we don't know the minimum for any monster. For every rule we will maintain how many monsters with unknown minimums it has (let's call it $k_{i}$ for the $i$-th rule). Let's take every rule that has only diamonds in it (i.e. which has $k_{i} = 0$), and assign number of diamonds in that rule as a tentative minimum for the monster (if a monster has several diamonds-only rules, take the smallest one). Then take the monster, that has the smallest tentative minimum currently assigned. For that monster the tentative value is the actual minimum due to the same reasoning we use when we prove correctness of Dijkstra algorithm. Now, since we know the minimum for that monster, for every rule $i$ that has that monster in its result subtract 1 from $k_{i}$ for every occurrence of the monster in the result of that rule. If for any rule the value of $k_{i}$ becomes zero, update the tentative minimum for the monster that rule belongs to with the sum of minimum values for each monster that rule generates plus the number of diamonds that rule generates. Then from all the monsters for which we don't known the minimum yet, but for which we know the tentative minimum, pick the one with the smallest tentative minimum, and continue on. At the end we will end up in a state, when each monster either has an actual minimum value assigned, or has no tentative value assigned. The latter monsters will have $- 1 - 1$ as their answer. For the former monsters we know the minimum, but don't know the maximum yet. The second part of the problem is to find all the rules, after applying which we are guaranteed to never get rid of all the monsters. We will call such a rule bad. It is easy to show, that the rule bad if and only if it generates at least one monster with minimum value of -1. Remove all the bad rules from the set of rules. When bad rules are removed, finding maximums is trivial. Starting from every node for which maximum is not assigned yet, we traverse all the monsters in a DFS order. For a given monster, we consider every rule. For a given rule, for each monster it generates, we call DFS to find its maximum value, and then sum them up, add number of diamonds for the rule, and check if this rule gives bigger max value than the one currently known for the monster. If we ever call DFS for a monster, for which we already have a DFS call on the stack, that means that that monster has some way of producing itself (directly or indirectly) and some non-zero number of diamonds (this is why problem statement has a constraint that every rule generates at least one diamond), so the answer for the monster is -2. If, processing any rule, we encounter a monster with max value -2, we immediately assign -2 as a max value for the monster the rule belongs to and return from the DFS. As an exercise, think of a solution for the same problem, if rules are not guarantee to have at least one diamond in them.",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "325",
    "index": "D",
    "title": "Reclamation",
    "statement": "In a far away land, there exists a planet shaped like a cylinder. There are three regions in this planet: top, bottom, and side as shown in the following picture.\n\nBoth the top and the bottom areas consist of big cities. The side area consists entirely of the sea.\n\nOne day, a city decides that it has too little space and would like to reclamate some of the side area into land. The side area can be represented by a grid with $r$ rows and $c$ columns — each cell represents a rectangular area in the side area. The rows are numbered 1 through $r$ from top to bottom, while the columns are numbered 1 through $c$ from left to right. Two cells are adjacent if they share a side. In addition, two cells located on the same row — one in the leftmost column, and the other in the rightmost column — are also adjacent.\n\nInitially, all of the cells are occupied by the sea. The plan is to turn some of those cells into land one by one in a particular order that will be given to you.\n\nHowever, the sea on the side area is also used as a major trade route. More formally, it is not allowed to reclamate the sea cells into land in such way that there does not exist a sequence of cells with the following property:\n\n- All cells in the sequence are occupied by the sea (i.e., they are not reclamated).\n- The first cell in the sequence is in the top row.\n- The last cell in the sequence is in the bottom row.\n- Consecutive cells in the sequence are adjacent.\n\nThus, the plan is revised. Each time a cell is going to be turned from sea to land, the city first needs to check whether or not it would violate the above condition by doing that. If it would, then the cell is not turned into land and the plan proceeds into the next cell. Otherwise, the cell is turned into land.\n\nYour job is to simulate this and output the number of cells that were successfully turned into land.",
    "tutorial": "Assume there's an extra sea cells on a row above the topmost row, and a row below the bottom most row. Hence, we can assume that the top and bottom row consists entirely of sea. We claim that: There does not exist a sea route if and only if there exists a sequence of land cells that circumfere the planet (2 cells are adjacent if they share at least one point). The \"sufficient\" part of the proof is easy -- since there exists such a sequence, it separates the sea into the northern and southern hemisphere and this forms a barrier disallowing passage between the two. The \"necessary\" part. Suppose there does not exist such route. Then, if you perform a flood fill from any of the sea cell in the top row, you obtain a set of sea cells. Trace the southern boundary of these set of cells, and you obtain the sequence of land circumfering the planet. Thus, the algorithm works by simulating the reclamations one by one. Each time a land is going to be reclamated, we check if it would create a circumefering sequence. We will show that there's a way to do this check very quickly -- thus the algorithm should work within the time limit. Stick two copies of the grid together side-by-side, forming a Rx(2*C) grid. The leftmost and rightmost cells of any row in this new grid are also adjacent, similar to the given grid. Each time we're going to reclamate a land in row r and column c, we check if by doing so we would create a path going from (r, c) to (r, c + C). If it would, then we cancel the reclamation. Otherwise, we perform it, and add a land in cell (r, c) and (r, c+C). This \"is there a path from node X to node Y\" queries can be answered very very quickly using union find -- we check whether is it possible to go from one of the 8 neighbors of (r, c) to one of the 8 neighbors of (r, c+C). Correctness follows from the following: There exists a circumefering sequence IFF there exists a path from (r, c) to (r, c+C). Sufficient is easy. Suppose there exist a path from (r, c) to (r, c+C). We can form our circumfering sequence by overlapping the path from (r, c) to (r, c+C) with the same path, but going from (r, c+C) to (r, c) (we can do this since the grid is a two copies of the same grid sticked together). Necessary. Suppose there exists a circumfering sequence. We claim that there must exist a path to go from (r, c) to (r, c+C). Consider the concatenation of an infinite number of our initial grid, forming an Rx(infinite * C) grid. If there exists a circumfering sequence, we claim that within this grid, there exists a path from (r, c) to (r, c+C). Suppose there does not exist such a path. Since there exists a circumfering sequence, it must be possible to go from (r, c) to (r, c+ t * C), where t is an integer >= 2. Now, you should overlap all the paths taken to go from (r, c) to (r, c+t*C) in the grid (r', c' + C) (the grid immediately to the right of the grid where (r, c) is located). There must be a path from (r, c) to (r, c+C) in this new overlapped path. Proofing the final part is difficult without interactive illustration -- basically since t >= 2, there exists a path that goes from the left side to the right side of the grid (r', c' + C). This path must intersect with one of the overlapping paths, and that path must be connected to (r, c+C). The details are left as... exercise :p.",
    "tags": [
      "dsu"
    ],
    "rating": 2900
  },
  {
    "contest_id": "325",
    "index": "E",
    "title": "The Red Button",
    "statement": "Piegirl found the red button. You have one last chance to change the inevitable end.\n\nThe circuit under the button consists of $n$ nodes, numbered from 0 to $n$ - 1. In order to deactivate the button, the $n$ nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node $i$, the next node to be disarmed must be either node $(2·i)$ modulo $n$ or node $(2·i) + 1$ modulo $n$. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.\n\nYour task is to find any such order and print it. If there is no such order, print -1.",
    "tutorial": "In this part of editorial, all numbers we speak are in modulo $N$. So, if I say 10, it actually means 10 modulo $N$. First, observe that this problem asks us to find a cycle that visits each node exactly once, i.e., a hamiltonian cycle. Thus, for each node $X$, there exists one other node that we used to go to node $X$, and one node that we visit after node $X$. We call them bef(X) and aft(X) (shorthand for before and after). First we will show that if $N$ is odd, then the answer is $- 1$. Proof...? Consider node $0$. What nodes points to node $0$? Such node $H$ must satisfy either of the following conditions: $2H = 0$ $2H + 1 = 0$ The first condition is satisfied only by $H = 0$. The second condition is satisfied only by one value of $H$: $floor(N / 2)$. So, since we need a hamiltonian cycle, pre[0] must be floor(N/2), and aft[floor(N/2)] = 0 Now, consider node $N - 1$. What nodes points to node $N - 1$? $2H = N - 1$ $2H + 1 = N - 1$ The second condition is satisfied only by $H = N - 1$. The first condition is satisfied only by $H = floor(N / 2)$ But we need a hamiltonian cycle, so aft[floor(N/2)] must be $N - 1$. This is a contradiction with that aft[floor(N/2)] must be 0. Now, $N$ is even. This case is much more interesting. Consider a node $X$. It is connected to $2X$ and $2X + 1$. Consider the node $X + N / 2$. It is connected to $2X + N$ and $2X + 1 + N$, which reduces to $2X$ and $2X + 1$. So, apparently node $X$ and node $X + N / 2$ are connected to the same set of values. Now, notice that each node $X$ will have exactly two nodes pointing to it. This is since such node $H$ must satisfy $2H = X$ $2H + 1 = X$ modulo $N$, each of those two equations have exactly one solution. So, this combined with that node $X$ and $X + N / 2$ have the same set of connected nodes means that the only way to go to node $2X$ or $2X + 1$ is from nodes $X$ and $X + N / 2$. Thus, if you choose to go from node $X$ to node $2X$, you HAVE to go from node $X + N / 2$ to node $2X + 1$ (or vice versa). Now, try to follow the rule above and generate any such configuration. This configuration will consists of cycles, possibly more than 1. Can we join them into a single large cycle, visiting all nodes? Yes we can, since those cycles are special. Weird theorem: If there are $2 +$ cycles, then there must exist $X$ and such node $X$ and node $X + N / 2$ are in different cycles. Proof: Suppose not. We show that there must exist one cycle in that case. Since node $X$ and $X + N / 2$ are in the same cycle, they must also be in the same cycle as node $2X$ and $2X + 1$. In particular, node $X$ and $2X$ and $2X + 1$ are all in the same cycle. It is possible to go from any node $X$ to any node $Y$ by following this pattern (left as exercise). Now, consider the $X$ such that node $X$ and node $X + N / 2$ are in different cycles. Suppose we go from node $X$ to node $2X + A$, and from $X + N / 2$ to $2X + B$ (such that $A + B = 1$). Switch the route -- we go from node $X$ to $2X + B$ and $X + N / 2$ to $2X + A$ instead. This will merge the two cycles -- very similar to how we merge two cycles when finding an eulerian path. Thus, we can keep doing this to obtain our cycle! ...It's not entirely obvious to do that in $O(N)$ time. An example solution: use DFS. DFS from node $0$. For each node $X$: if it has been visited, return if $X + N / 2$ has been visited, go to either $2X$ or $2X + 1$ and recurse, depending on which route used by node $X + N / 2$ otherwise, we go to node $2X$ and recurse. Then, check if $X + N / 2$ was visited in the recursion. If it was not, then the two of them forms two different cycles. We merge them by switching our route to $2X + 1$ instead, and recurse again.",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "327",
    "index": "A",
    "title": "Flipping Game",
    "statement": "Iahub got bored, so he invented a game to be played on paper.\n\nHe writes $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices $i$ and $j$ ($1 ≤ i ≤ j ≤ n$) and flips all values $a_{k}$ for which their positions are in range $[i, j]$ (that is $i ≤ k ≤ j$). Flip the value of $x$ means to apply operation $x = 1$ - $x$.\n\nThe goal of the game is that after \\textbf{exactly} one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.",
    "tutorial": "I'll present here the O(N ^ 3) algorithm, which is enough to solve this task. Then, for those interested, I'll show a method to achieve O(N) complexity. O(N ^ 3) method: The first thing to observe is that constrains are slow enough to allow a brute force algorithm. Using brute force, I can calculate for each possible single move the number of 1s resulting after applying it and take maximum. For consider each move, I can just generate with 2 FOR loops all indices i, j such as i <= j. So far we have O(N ^ 2) complexity. Suppose I have now 2 fixed vaIues i and j. I need to calculate variable cnt (initially 0) representing the number of ones if I do the move. For do this, I choose another indice k to go in a[] array (taking O(N) time, making the total of O(N ^ 3) complexity). We have two cases: either k is in range [i, j] (this means i <= k AND k <= j) or not (if that condition is not met). If it's in range, then it gets flipped, so we add to count variable 1 - a[k] (observe that it makes 0 to 1 and 1 to 0). If it's not in range, we simply add to cnt variable a[k]. The answer is maximum of all cnt obtained. O(N) method: For achieve this complexity, we need to make an observation. Suppose I flip an interval (it does not matter what interval, it can be any interval). Also suppose that S is the number of ones before flipiing it. What happens? Every time I flip a 0 value, S increases by 1 (I get a new 1 value). Every time I flip a 1 value, S decreases by 1 (I loose a 1 value). What would be the \"gain\" from a flip? I consider winning \"+1\" when I get a 0 value and \"-1\" when I get a 1 value. The \"gain\" would be simply a sum of +1 and -1. This gives us idea to make another vector b[]. B[i] is 1 if A[i] is 0 and B[i] is -1 if A[i] is 1. We want to maximize S + gain_after_one_move sum. As S is constant, I want to maximize gain_after_one_move. In other words, I want to find a subsequence in b[] which gives the maximal sum. If I flip it, I get maximal number of 1s too. This can be founded trivially in O(N ^ 2). How to get O(N)? A relative experienced programmer in dynamic programming will immediately recognize it as a classical problem \"subsequence of maximal sum\". If you never heard about it, come back to this approach after you learn it.",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "327",
    "index": "B",
    "title": "Hungry Sequence",
    "statement": "Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of $n$ integers.\n\nA sequence $a_{1}$, $a_{2}$, ..., $a_{n}$, consisting of $n$ integers, is Hungry if and only if:\n\n- Its elements are in increasing order. That is an inequality $a_{i} < a_{j}$ holds for any two indices $i, j$ $(i < j)$.\n- For any two indices $i$ and $j$ $(i < j)$, $a_{j}$ must \\textbf{not} be divisible by $a_{i}$.\n\nIahub is in trouble, so he asks you for help. Find a Hungry sequence with $n$ elements.",
    "tutorial": "We'll present two different solutions for this task. Solution 1. What if we solve a more general task? What if each hungry number from the solution isn't allowed to be divided by any number smaller than it (except 1, which is divides every natural number). If this more general condition would be met, then the \"hungry\" condition would be met, too (as a[i] won't be divided by a number smaller than it (except 1), it won't be divided by a[j], too, with j < i, assuming that a[j] is different from 1). Now how to find numbers for this more general condition? We can rephrase it as: each number from more general condition has 2 divisors: 1 and itself. So if we print N numbers with 2 divisors in increasing order, that would be a good solution. As you probably know, numbers with 2 divisors are called \"prime numbers\". The task reduces to finding first N prime numbers. This can be done via brute force, or via Sieve of Eratosthenes (however, not necessarily to get an AC solution). Solution 2. Suppose we are given the number N. We can observe that for big enough consecutive numbers, the array is always hungry. For example, we can print 3 * N + 0, 3 * N + 1, 3 * N + 2,  \\dots , 3 * N + (N - 1). Magic, isn't it? Why does it work now? Pick an arbitrary a[i]. The solution would be bad if one of numbers 2 * a[i], 3 * a[i], 4 * a[i] and so on would be in a[] array. However, it will never happen. The smallest multiple from that ones will be 2 * 3 * N = 6 * N. There is not possible to obtain a smallest multiple than that one. On the other hand, the biggest number from a[] array would be 3 * N + N - 1 = 4 * N - 1. Since smallest multiple is bigger than biggest term of the array, it (and of course other multiples bigger than it) will never exist in a[] array. So the above solution is correct also.",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "327",
    "index": "C",
    "title": "Magic Five",
    "statement": "There is a long plate $s$ containing $n$ digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his \"magic number\" on the plate, a number that is divisible by $5$. Note that, the resulting number may contain leading zeros.\n\nNow Iahub wants to count the number of ways he can obtain magic number, modulo $1000000007$ ($10^{9} + 7$). Two ways are different, if the set of deleted positions in $s$ differs.\n\nLook at the input part of the statement, $s$ is given in a special form.",
    "tutorial": "Property: A number is divisible by 5 if and only if its last digit is either 0 or 5. A first solution: Suppose you're given a plate S, not so big, so we can iterate all its elements. Can we get the answer? I build a new array sol[]. In explanation, both S and sol will be 1-based. Denote N = size of S. Also, denote sol[i] = the number of ways to delete digits from plate S such as we obtain a magic number which has the last digit on position i. The answer is sol[1] + sol[2] +  \\dots  + sol[N]. Let's focus now on calculating sol[i]. If S[i] (digit of the plate corresponding to ith position) is different than 0 or 5, then sol[i] is 0 (see \"property\"). Otherwise we have to ask ourself: in how many ways I can delete digits in \"left\" and in \"right\" of position i. In the \"right\", we have only one way: delete all digits (if one digit from right still stands, then the number isn't ending at position i). Now in the \"left\": there are digits on positions 1, 2,  \\dots , i - 1. We can either delete a digit or keep it - anyhow he'd do we still get a magic number. So on position 1 I have 2 ways (delete or keep it), on position 2 I have also 2 ways,  \\dots , on position i - 1 I have also 2 ways. Next, we apply what mathematics call \"rule of product\" and we get 2 * 2 * 2  \\dots  * 2 (i - 1 times) = 2 ^ (i - 1). Applying \"rule of product\" on both \"left\" and \"right\" I get 2 ^ (i - 1) * 1 = 2 ^ (i - 1). To sum it up: If S[i] is 0 or 5 we add to the answer 2 ^ (i - 1). Otherwise, we add nothing. The only problem remained for this simple version is how we calculate A ^ B modulo one number. This is a well known problem as well, called \"Exponentiation by squaring\". Coming back to our problem: So what's different in our problem? It's the fact that we can't iterate all elements of plate. However, we can use \"concatenation\" property. We know that if an element is a position i in the first copy, it will also be on positions i + n, i + 2 * n, i + 3 * n,  \\dots , i + (k - 1) * n (we don't call here about trivial case when k = 1). What if iterate only one copy and calculate for all K copies. If in the first copy, at the position i is either 0 or 5, we have to calculate the sum 2 ^ i + 2 ^ (i + n) + 2 ^ (i + 2 * n) +  \\dots  + 2 ^ (i + (k - 1) * n). By now on, in calculus I'll denote i as i - 1 (it's a simple mathematical substitution). A first idea would be just to iterate each term and calculate it with exponentiation by squaring. However, it takes in the worst case the same complexity as iterating all plate. We need to find something smarter. 2 ^ i + 2 ^ (i + n) + 2 ^ (i + 2 * n) +  \\dots  + 2 ^ (i + (k - 1) * n) = = 2 ^ i * 1 + 2 ^ i * 2 ^ n + 2 ^ i * 2 ^ (2 * n) +  \\dots  + 2 ^ i * 2 ^ ((k - 1) * N) = = 2 ^ i * (2 ^ 0 + 2 ^ n + 2 ^ (2 * n) +  \\dots  + 2 ^ ((k - 1) * n) We reduced the problem to calculate sum S = 2 ^ 0 + 2 ^ n + 2 ^ (2 * n) +  \\dots  + 2 ^ (X * n). What's the value of 2 ^ n * S ? It is 2 ^ n + 2 ^ (2 * n) + 2 ^ (3 * n) +  \\dots  + 2 ^ ((X + 1) * n). And what you get by making 2 ^ n * S - S ? 2 ^ n * S - S = 2 ^ ((X + 1) * n) - 1 S * (2 ^ n - 1) = 2 ^ ((X + 1) * n) - 1 S = (2 ^ ((X + 1) * n) - 1) / (2 ^ n - 1). We can calculate both 2 ^ i and S with exponentiation by squaring and the problem is done. For \"/\" operator, we can use multiplicative inverse (you can read about that and about Fermat Little's theorem, taking care that 10^9 + 7 is a prime number). The time complexity is O(N * logK). Note: that kind of reduction of powers is called \"power series\" in math. Alternative solution: For this alternative solution, we don't need to use any special properties of 5. In fact, we can replace 5 by any integer p and still have the same solution. So for now, I shall write p in place of 5. This suggests a dynamic programming solution: denote dp(x,y) be the number of ways of deleting some digits in the first x digits to form a number that has remainder y (modulo p). For simplicity, we accept \"empty\" plate be a number that is divisible by p. Writing the DP formula is not difficult. We start with dp(0,0) = 1, and suppose we already have the value dp(x,y). We shall use dp(x,y) to update for dp(x + 1,*), which has two possible cases: either keeping the (x + 1)-th digit or by deleting it. I won't go into much detail here. The answer is therefore dp(N,0). Clearly, applying this DP directly would time out. For a better algorithm, we resort on the periodicity of the actual plate. The key idea is that, we imagine each digit in the plate as a linear transformation from (x0, x1, .., x(p - 1)) to (y0, y1, y(p-1)). Obviously, (x0, x1, .., x(p - 1)) corresponds to some dp(i, 0), dp(i, 1) .. dp(i, p - 1) and (y0, y1, y(p-1)) corresponds to some (dp(i + 1, 0)), dp((i + 1), 1), ..., dp(i + 1, p - 1) .So we can write X * M(d) = Y, where X and Y are vectors of length p, and M(d) is the matrix of size p * p representing digit d (note that M(d) is independent from X and Y). By multiplying all |a|.K such matrices together, we obtain a transformation from (1, 0, 0, .., 0) to (T0, T1, .., T(p - 1)) where T0 is actually our answer (including the empty plate). What's the difference? We can group the matrices in groups of length |a|, and lift to the exponent K. That leads to an algorithm with time complexity O(p^3(|a| + log K)), which could be risky. To improve, we should go back to our original DP function and observe that it is actually a linear transformation from (1, 0, 0, .., 0) to (R0, R1,  \\dots , R(p - 1)), if we restrict ourselves in the first fragment of length |a|. So instead of multiplying |a| matrices together, we can run DP p times with initial conditions (0, 0, .., 0, 1, 0, .., 0) to obtain the matrix transformation. The overall time complexity becomes O(|a| * p^2 + p^3 log K) .",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "327",
    "index": "D",
    "title": "Block Tower",
    "statement": "After too much playing on paper, Iahub has switched to computer games. The game he plays is called \"Block Towers\". It is played in a rectangular grid with $n$ rows and $m$ columns (it contains $n × m$ cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any building. The rest of cells are empty. In some empty cell Iahub can build exactly one tower of two following types:\n\n- Blue towers. Each has population limit equal to $100$.\n- Red towers. Each has population limit equal to $200$. However, it can be built in some cell only if in that moment at least one of the neighbouring cells has a Blue Tower. Two cells are neighbours is they share a side.\n\nIahub is also allowed to destroy a building from any cell. He can do this operation as much as he wants. After destroying a building, the other buildings are not influenced, and the destroyed cell becomes empty (so Iahub can build a tower in this cell if needed, see the second example for such a case).\n\nIahub can convince as many population as he wants to come into his city. So he needs to configure his city to allow maximum population possible. Therefore he should find a sequence of operations that builds the city in an optimal way, so that total population limit is as large as possible.\n\nHe says he's the best at this game, but he doesn't have the optimal solution. Write a program that calculates the optimal one, to show him that he's not as good as he thinks.",
    "tutorial": "The restriction given in the problem poses you to think of building as many Red Towers as possible, and fill the rest with Blue Towers (since there is no profit of letting cells empty, such cells can be filled by Blue Towers). Also, it's quite obvious to see that each connected component (containing empty cells only) is independent from each other, so we shall iterate the component one by one. Denote the current component be S. Lemma 1 is impossible to build S so that it contains all Red Towers only. Proof Suppose there exists such a way. Look up the last cell that is built (denote by x). Clearly x is a Red Tower, so at the moment it is built, x must be adjacent to a cell than contains a Blue Tower. However, it's obvious that there's no such cell (if there is, it must belong to S, which is impossible). As it's impossible to have all Red Towers, it's natural to look up at the next best solution: the one with exactly one Blue Tower, and among them, we need to find the least lexicographic solution. Fortunately, we can prove that such a configuration is always possible. Such proof is quite tricky, indeed: Lemma 2 Pick any cell b in S. It is possible to build a configuration that has all but b be Red Towers, and b is a Blue Tower. Proof Construct a graph whose vertices correspond to the cells of S, and the edges correspond to cells that are adjacent. Since S is connected, it is possible to build a tree that spans to all vertices of S. Pick b as the root and do the following: Build all cells of S blue Move from the leaf to the root. At each cell (except the root), destroy the Blue Tower and rebuild with the Red Tower. To be precise, u can be destroyed (and rebuilt) if all vertices in the subtree rooted at u have already been rebuilt. How can it be the valid solution? Take any vertex u which is about to be rebuilt. Clearly u is not b, and u has its parent to be blue, so the condition for rebuilding can be met. When the building is completed, only b remains intact, while others have been transformed into Red Towers. So we get the following algorithm: do a BFS / DFS search to find connected components. Then, apply Lemma 2 to build a valid configuration.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1900
  },
  {
    "contest_id": "327",
    "index": "E",
    "title": "Axis Walking",
    "statement": "Iahub wants to meet his girlfriend Iahubina. They both live in $Ox$ axis (the horizontal axis). Iahub lives at point 0 and Iahubina at point $d$.\n\nIahub has $n$ positive integers $a_{1}$, $a_{2}$, ..., $a_{n}$. The sum of those numbers is $d$. Suppose $p_{1}$, $p_{2}$, ..., $p_{n}$ is a permutation of ${1, 2, ..., n}$. Then, let $b_{1} = a_{p1}$, $b_{2} = a_{p2}$ and so on. The array b is called a \"route\". There are $n!$ different routes, one for each permutation $p$.\n\nIahub's travel schedule is: he walks $b_{1}$ steps on $Ox$ axis, then he makes a break in point $b_{1}$. Then, he walks $b_{2}$ more steps on $Ox$ axis and makes a break in point $b_{1} + b_{2}$. Similarly, at $j$-th $(1 ≤ j ≤ n)$ time he walks $b_{j}$ more steps on $Ox$ axis and makes a break in point $b_{1} + b_{2} + ... + b_{j}$.\n\nIahub is very superstitious and has $k$ integers which give him bad luck. He calls a route \"good\" if he never makes a break in a point corresponding to one of those $k$ numbers. For his own curiosity, answer how many good routes he can make, modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "Usually when dealing with complicated problems, a good idea is to solve them for small cases. Let's try this here. First case: K = 0. The answer is obviously N! (each permutation of p1, p2,  \\dots , pn would be good). Next case: K = 1. The answer of this one is N! - |L1|. By L1 I denote all routes for which a prefix sum is equal to first lucky number. Obviously, if from all routes I exclude the wrong ones, I get my answer. If we can find an algorithm to provide |L1| in good time, then problem is solved for K = 1. We can just try all N! permutations. Despite this method is simple, it has complexity O(N!), too much for the constraints. Suppose we've founded a set of positions p1, p2, .., pk such as a[p1] + a[p2] + ..+ a[pk] = U1 (first unlucky number). How many permutations can we make? The first k positions need to be p1, p2, .., pk, but in any order. Hence we get k! . The not used positions can also appeared in any order, starting from k + 1 position. As they are n - k, we can permute them in (n - k)! ways. Hence, the answer is k! * (n - k)! Instead of permuting {1, 2, .., n}, now we need to find subsets of it. Hence, the running time becomes O(2^n). This is still too much. Meet in the middle. We make all subsets for first half of positions (from 1 to N / 2) and them for second half (from N / 2 + 1 to N). For each subset we keep 2 information: (sum, cnt) representing that there is a subset of sum \"sum\" containing \"cnt\" elements. For each (X, Y) from left we iterate in the right. After choosing one element from the left and one from the right we just \"split\" them. To split 2 states (A, B) and (C, D), the new state becomes (A + C, B + D). But we know that A + C = U1. This comes us to the idea: for each (X, Y) in the left, I check (U1 - X, 1), (U1 - X, 2),  \\dots  , (U1 - X, K) from the right. For each of them, the answer would be (Y + K)! * (N - Y - K)! . I can store (using any data structure that allows this operations, I suggest a hash) how(C, D) = how many times does state (C, D) appear in the right. So, for a state (A, B) the answer becomes a sum of how(U1 - A, K) * (B + K)! * (N - B - K)!. Doing the sum for all states (A, B), we get our answer. The complexity of this method is O(2 ^ (N / 2) * N). Final Case: K = 2 The whole \"meet in the middle\" explanation worthed. We will do something very similar to solve this case. Suppose U1 and U2 are the unlucky numbers. Without loosing the generality, let's assume U1 <= U2. Following \"Principle of inclusion and exclusion\" paradigm (google about it if you never heard before) we can write our solution as N! - |L1| - |L2| + |intersection between L1 and L2|. Again, by L1,2 I denote the number of routes which have a prefix sum equal to number U1,2. The |X| is again the cardinal of this set. Basically we can calculate |X| as for K = 1. The only problem remained is calculating |intersection between L1 and L2|. The |intersection between L1 and L2| is the number of permutations which have a prefix sum equal to U1 and a prefix sum equal to U2. Since U1 <= U2, we can split a permutation from this set in 3 parts: 1/ p1, p2, ...pk such as a[p1] + a[p2] + ... + a[pk] = U1. 2/ pk+1, pk+2, ..., pm such as a[pk+1], a[pk+2], ..., a[pm] = U2 - U1. Note that a[p1] + a[p2] + ... + a[pm] = U2. 3/ The rest of elements until position n. By a perfectly identical logic from K = 1 case, the number of permutations given those p[] would be k! * (m - k)! * (n - m)!. So the problem reduces to: find all indices set p1, p2, ... and q1, q2, .. such as a[p1] + a[p2] + ... + a[pn1] = U1 and a[q1] + a[q2] + ... + a[qn2] = U2 - U1. Then, we can apply formula using n1 and n2 described above. The first idea would be O(3 ^ N) - for each position from {1, 2, .., n} atribute all combinations of {0, 1, 2}. 0 means that position i is 1/, 1 means that position i is in 2/ and 2 means that position i is in 3/ . This would time out. Happily, we can improve it with meet in the middle principle. The solution is very similar with K = 1 case. I won't fully explain it here, if you understood principle from K = 1 this shouldn't be a problem. The base idea is to keep (S1, S2, cnt1, cnt2) for both \"left\" and \"right\". (S1, S2, cnt1, cnt2) represents a subset which has sum of elements from 1/ equal to S1, sum of elements from 2/ equal to S2, in 1/ we have cnt1 element and in 2/ we get cnt2 elements. For a (S1, S2, cnt1, cnt2) state from \"left\" we are looking in the right for something like (U1 - S1, U2 - U1 - S2, i, j). We get O(3 ^ (N / 2) * N ^ 2) complexity. Unexpected solution During the round, we saw a lot of O(2 ^ N * N) solutions passing. This was totally out of expectations. I believe if would make tests stronger, this solution won't pass and round would be more challenging. That's it, nothing is perfect. As requested, I'll explain that solution here. Before explaining the solution, I assume you have some experience with \"bitmask dp\" technique. If you don't, please read before: In this problem we'll assume that a is 0-based. For a mask, consider bits from right to left, noting them bit 0, bit 1 and so on. Bit i is 1 if and only if a[i] is in the subset which is in a bijective replation with the mask. For example, for mask 100011101 the subset is {a0, a2, a3, a4, a8}. I'll call from now on the subset \"subset of mask\". Also, the sum of all elements in a subset will be called \"sum of mask\" (i.e. a0 + a2 + a3 + a4 + a8). We'll explain the solution based by watashi's submission. 4017915 First step of the algorithm is to calculate sum of each mask. Let dp[i] the sum of mask i. Remove exactly one element from the subset of mask. Suppose the new mask obtained is k and removed element is j. Then, dp[i] = dp[k] + a[j]. dp[k] is always calculated before dp[i] (to proof, write both k and i in base 10. k is always smaller than i). Having j an element from subset of mask i, we can compute mask k by doing i ^ (1 << j). Bit j is 1, and by xor-ing it with another 1 bit, it becomes 0. Other bits are unchanged by being xor-ed by 0. This method works very fast to compute sum of each mask. From now on, let's denote a new array dp2[i] = how many good routes can I obtain with elements from subset of mask i. Watashi uses same dp[] array, but for making it clear, in editorial I'll use 2 separate arrays. Suppose that CNT(i) is number of elements from subset of mask i. We are interested in how many ways we can fill positions {1, 2, ..., CNT(i)} with elements from subset of mask i such as each prefix sum is different by each unlucky number. Next step of the algorithm is to see which sum of masks are equal to one of unlucky numbers. We mark them as \"-1\" in dp2[]. Suppose we founded a subset {a1, a2, ..., ax} for which a1 + a2 + ... + ax = one of unlucky numbers. Then, none permutation of {a1, a2, ..., ax} is allowed to appear on first x positions. When we arrive to a \"-1\" state, we know that the number of good routes for its subset of mask is 0. Now, finally the main dp recurrence. If for the current mask i, dp2[i] = -1, then dp2[i] = 0 and continue (we discard the state as explained above). Otherwise, we know that there could exist at least one way to complete positions {1, 2, ... CNT(i)} with elements of subset of mask i. But how to calculate it? We fix the last element (the element from the position CNT(I)) with some j from subset of mask i. The problem reduces now with how many good routes can I fill in positions {1, 2, ..., CNT(i) - 1} with elements from subset of mask i, from which we erased element j. With same explanation of sum of mask calculations, this is already calculated in dp2[i ^ (1 << j)]. The result is dp2[(1 << N) - 1] (number of good routes containing all positions).",
    "tags": [
      "bitmasks",
      "combinatorics",
      "constructive algorithms",
      "dp",
      "meet-in-the-middle"
    ],
    "rating": 2300
  },
  {
    "contest_id": "329",
    "index": "A",
    "title": "Purification",
    "statement": "You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an $n × n$ grid. The rows are numbered $1$ through $n$ from top to bottom, and the columns are numbered $1$ through $n$ from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:\n\n\\begin{center}\n\\underline{The cleaning of all evil will awaken the door!}\n\\end{center}\n\nBeing a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.\n\nThe only method of tile purification known to you is by casting the \"Purification\" spell. You cast this spell on a single tile — then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.\n\nYou would like to purify all $n × n$ cells while minimizing the number of times you cast the \"Purification\" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the \"Purification\" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the \"Purification\" spell.\n\nPlease find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.",
    "tutorial": "Obviously the minimum possible answer is n (why?). But is it always possible to purify all the cells with n spells? If there exist a row consisting of entirely \"E\" cells and a column consisting of entirely \"E\" cells, then the answer is -1. This is since the cell with that row and that column cannot be purifed. Otherwise, without loss of generality let's suppose there is no row consisting entirely of \"E\". Then, for each row, find any \".\" cell. Purify it. The case with no column consisting entirely of \"E\" is similar.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "329",
    "index": "B",
    "title": "Biridian Forest",
    "statement": "You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.\n\n\\textbf{The forest}\n\nThe Biridian Forest is a two-dimensional grid consisting of $r$ rows and $c$ columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.\n\nThe initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):\n\n\\textbf{Moves}\n\nBreeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:\n\n- Do nothing.\n- Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees.\n- If you are located on the exit cell, you may leave the forest. Only you can perform this move — all other mikemon breeders will never leave the forest by using this type of movement.\n\nAfter each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).\n\n\\textbf{Mikemon battle}\n\nIf you and $t$ $(t > 0)$ mikemon breeders are located on the same cell, exactly $t$ mikemon battles will ensue that time (since you will be battling each of those $t$ breeders once). After the battle, all of those $t$ breeders will leave the forest to heal their respective mikemons.\n\nNote that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders — there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).\n\n\\textbf{Your goal}\n\nYou would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.\n\n\\textbf{Goal of other breeders}\n\nBecause you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.\n\n\\textbf{Your task}\n\nPrint the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.",
    "tutorial": "The only non ad hoc problem in the round! ...sort of. Despite the very long problem statement, the solution is really simple. We should take any shortest path from S to E (yes, any!). We will see why this is optimal at the end. If a breeder can reach E faster than or equal to us, then he will battle us. This is since he can simply walk to E and waits for us there. Otherwise, they can never battle us by contradiction. Assume they battled us, but they cannot reach cell E from their location faster or equal to us. If the battle us in cell X, then cell X is part of the shortest path from S to E that you are travelling. Since he is able to battle us there, he must be able to arrive at cell X <= us. But then, that means he can walk from X to E and reach E before or equal to us! Contradiction. This is optimal, since any breeder that we battle in this solution must also be battled in any other solution (the other breeders should immediately go to E and wait). You can use Breadth-First Search once from exit cell to obtain the shortest paths from each breeder to it.",
    "tags": [
      "dfs and similar",
      "shortest paths"
    ],
    "rating": 1500
  },
  {
    "contest_id": "329",
    "index": "C",
    "title": "Graph Reconstruction",
    "statement": "I have an undirected graph consisting of $n$ nodes, numbered 1 through $n$. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself.\n\nI would like to create a new graph in such a way that:\n\n- The new graph consists of the same number of nodes and edges as the old graph.\n- The properties in the first paragraph still hold.\n- For each two nodes $u$ and $v$, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph.\n\nHelp me construct the new graph, or tell me if it is impossible.",
    "tutorial": "If n <= 7, brute force all possible subsets of the edges (at most 2^(7 * (7 - 1) / 2)), and check if they satisfy the constraint. Otherwise, a solution always exists. Here is how to construct one. Partition the nodes into connected components. Note that each component will be either a cycle or a chain. List the nodes of each component in order of the cycle/chain. For example, for the first example, the partition would be { <1, 2, 3>, <4, 5, 6, 8, 7> }. For each component, we do not care whether it is a cycle or a chain. For each component, reorder the nodes such that all nodes in the odd positions are in the front. For example, component ABCDEFGHI is reordered into ACEGIBDFH. (Each letter represent a node.) Pick any component with the largest number of nodes. If the number of nodes in it is even, swap the first two nodes. For example, ABCDEFGH -> ACEGBDFH -> CAEGBDFH. For each other component, insert the nodes alternately between the largest component. For example, if the other components are acebd and 1324, insert them as follows: CAEGBDFH -> C a A c E e G b B d DFH -> C 1 a 3 A 2 c 4 EeGbBdDFH. Connect adjacent nodes so that the number of edges is m, connecting the last with the first nodes if necessary. The deterministic solution is very tricky. Therefore, I made the pretest quite strong. Some tricky cases: 4-cycle and 1-chain (covered in the example) 3-cycle and 3-cycle 4-cycle and 3-cycle (very tricky! many submissions failed on this case) Actually, we can do brute force when n <= 6, but this requires a special handling: when the largest component has 4 nodes, we should swap the first node with the third node (not the second). This is to handle the 4-cycle-and-3-cycle case.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2400
  },
  {
    "contest_id": "329",
    "index": "D",
    "title": "The Evil Temple and the Moving Rocks",
    "statement": "\\underline{Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.}\n\nYou are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an $n × n$ grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:\n\n\\begin{center}\n\\underline{The sound of clashing rocks will awaken the door!}\n\\end{center}\n\nBeing a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks:\n\n- '^': this rock moves upwards;\n- '<': this rock moves leftwards;\n- '>': this rock moves rightwards;\n- 'v': this rock moves downwards.\n\nTo open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already $10^{7}$ events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.\n\nIf a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least $x$. It is okay for the rocks to continue moving after producing $x$ sounds.\n\nThe following picture illustrates the four possible scenarios of moving rocks.\n\n- Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated.\n- Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end.\n- Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced.\n- Does not move because the wall is in the way. No sounds are produced and the movements end.\n\nAssume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door!",
    "tutorial": "Post your solution in the comment! Here's mine for the last case! (approximately 120,000 sounds). You can get the number of sounds your solution produces when submitting it to the server. 1 copy of v<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v^ 24 copies of v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v. v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^ 24 copies of v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^ .^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^ 1 copy of >^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^ .................................................................................................... 1 1I wonder if there's a solution with ~150,000 sounds or more... the (theoretical) upper bound is 100^3 / something, so it may be feasible...?",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2500
  },
  {
    "contest_id": "329",
    "index": "E",
    "title": "Evil",
    "statement": "There are $n$ cities on a two dimensional Cartesian plane. The distance between two cities is equal to the Manhattan distance between them (see the Notes for definition). A Hamiltonian cycle of the cities is defined as a permutation of all $n$ cities. The length of this Hamiltonian cycle is defined as the sum of the distances between adjacent cities in the permutation plus the distance between the first and final city in the permutation. Please compute the longest possible length of a Hamiltonian cycle of the given cities.",
    "tutorial": "This problem asks us to prove something very long (the proof below is of 80+ lines). Assume that the number of cities is at least 4. The case where it's less than 4 is trivial. First, we will assume that no two cities will have same X or Y coordinates. To get this assumption, we can juxtapose every city very slightly that it will not change the answer. The keys are : A) \"Manhattan Distance\", B) the tour starts and ends at the same city. Suppose we know a tour. The total distance traveled will be |X1 - X2| + |Y1 - Y2| + |X3 - X2| + |Y3 - Y2| ... Let's separate the X and Y coordinates for simplicity. Note that each city will contribute twice to this value, for example X2 was in |X1 - X2| and |X3 - X2| in the example above. Manhattan distance implies that each of these values will either be multiplied by +1 or -1, depending on the other coordinate being compared in the absolute term. Furthermore, the number of values that are multiplied by +1 must equal the number of values that are multiplied by -1 (since in each absolute term, one is multiplied by +1 and the other by -1). This directly implies an upper bound on the maximum length of the tour. If we list all the X coordinates of the cities, and we put each of them twice in this list, and sort them, the maximum will be gained if we multiply the last half by +1 and the first half by -1, and finally summing them up. Note that all of these reasoning applies to the Y coordinate, and summing both maximum of X and Y, we receive an upper bound on the length of the tour. If we can find a tour with this length, our job is done. In some case, it's possible. Let's investigate! First, if we have the medians of the X and the Ys as in the list above, we can separated the field like below : A | B | --------- | C | DThe lines corresponds to the median for both X and Y. At most one city will lie on each of the median lines (recall our assumption that X and Ys are distinct). Let's call each A B C and D as boxes. Below, we will refer box A as simply A (applies to B, C, and D too) To obtain the value above, from a city in B we must go to a city in C. Same reasoning yields : B->C, C->B, A->D, D->A. Here, pairs of cities become apparrent, A and D are paired as well as B and C. First, if either A+D is empty or B+C is empty, then we can obtain the upper bound above. We simply alternates between the two remaining pair. So let's assume that A+D is not empty and B+C is not empty. First, let's investigate the relationship between B and C (A and B will also exhibits this relationship). Theorem 1: |B - C| <= 1. Why: First, if there are no cities in the medians or there is a single city in the center of the median : A median divides the region into two areas with the same number of cities, so we have: a) A+B = C+D b) A+C = B+Dsubstituting A from a to b yields : (C+D-B)+C = B+D 2C = 2B B = CAnd the theorem follows. Next, suppose there are two cities in the median, one for each median line : Let's suppose the median is one above and one on the right. All other cases will be similar. By definition of median... a) (A + B + 1) = (C + D) b) (A + C) = (B + D + 1)Substituing a into b yields (C + D - B - 1 + C) = (B + D + 1) 2C = 2B + 2 C = B + 1which also implies A = D Applying the same technique to other cases will give: C = B and A = D+1 C = B-1 and A = D C = B and A = D-1And the theorem follows. Note also that the one with the extra 1 city will be the one that is not adjacent to any median city (adjacent being the city lies in the boundary of the box) OK, so in the following observations, we will assume the upper bound (that is, the sorted list of both X and Ys have their first half multiplied by -1 while the rest by +1), and trying to find a solution that's as close as possible to this upper bound. The following will be another case analysis. Theorem 2: If there are two cities in the medians (that is, one in each median line), then the upper bound can be achieved. Why: We use pair of boxes to denote either A and D or B and C. From the second part of the proof for theorem 1, there will be a pair of boxes that contain different number of cities. Let's pick this pair, and start at the one with the most boxes. We keep alternating with its pair until we end up back in our starting box. Then, we simply move to either of the median city. From there we move to the other pair of box, the farthest one of the two. Alternate between the two, go to the other median city, and return to the starting city. It's easy to see that this will be optimal and have the upper bound as its value. Now, let's see if there are no cities in the medians. First of all, this implies that the number of cities is even. Second, this implies that our upper bound which has the X and Y lists as -1 -1 -1 ... -1 1 ... 1 1 1 will not work (since this implies we have to continuously alternate between the two pairs of boxes, however, we can't switch between the pair of boxes). So, at least a modification would be required. The smallest possible modification is obtained by swapping the medians, that is, it becomes : -1 -1 -1 ... -1 -1 1 -1 1 1 ... 1 1 1. This is sufficient. Why? So, there are two cities that changes since the number of cities is even. Furthermore, these two cities will be the closest to the median line (let's assume these coordinates are X, that is, they're the closest to the vertical median line) and lies at two different boxes. Then, we proceed as follows. We start at one of these two cities. Alternate and end at the other side. If the other city is at that box, we make it so that we end at that city, and in this case, we can move to a city in the other box pair while respecting the list of X coordinates (we can do so since this city is the closest to the median line). Otherwise, the city will be in the other pair of boxes. We simply move there and it can be shown that we still respect the list of X coordinates. Alternate and at the end, go back to the starting city. All of these can be shown to still respect the list above. This is optimal since this is the next largest possible upper bound if upper bound cannot be achieved. Now, if there is a single city in the center of both medians, then the upper bound cannot be achieved. To see this, the upper bound can only be achieved if from a city in a box we move to another city in its box pair or to the center city. However, since both pair of boxes contains a city, we will need to move at least twice between them. Since there's only one center city, this is not possible. Observe that this case implies an odd number of cities. Hence, we can't simply swap the median since it swaps the x coordinates of the same median city. Instead, we do this : -1 -1 ... -1 -1 1 1 -1 1 ... 1 1 or -1 -1 ... -1 1 -1 -1 1 1 ... 1 1 That is, we swap to either one of the neighboring city. With the same reasoning as above, we can show that we respect this list of X coordinates. To achieve O(N) expected performance, note that the only operations we need are : grouping elements into boxes and median finding. Both can be done in expected O(N) time (expected since although there is a worst-case O(N) selection algorithm, it's ugly).",
    "code": "import sys\n \nn = int(raw_input())\ncoordinates = []\nxs = []\nys = []\nfor i in range(n):\n  x, y = map(int, raw_input().split())\n  coordinates.append(((x, i), (y, i)))\n  xs.append((x, i))\n  ys.append((y, i))\n \nxs = sorted(xs)\nys = sorted(ys)\n \namt = [[0] * 2 for _ in range(2)]\n \nmedians = 0\n \nfor x, y in coordinates:\n  if n % 2 and x == xs[n/2]:\n    # median\n    medians += 1\n    continue\n  if n % 2 and y == ys[n/2]:\n    # median\n    medians += 1\n    continue\n  amt[x < xs[n/2]][y < ys[n/2]] += 1\n \ndef CalcuHalf(arr):\n  res = 0\n  for a, _ in arr[len(arr)/2:]:\n    res += a\n  for a, _ in arr[:len(arr)/2]:\n    res -= a\n  return res\n \ndef PossibleAll():\n  def CalculateMax(arr):\n    woot = arr + arr\n    woot = sorted(woot)\n    return CalcuHalf(woot)\n  print CalculateMax(xs) + CalculateMax(ys)\n  sys.exit(0)\n \nif amt[0][0] + amt[1][1] == 0 or amt[1][0] + amt[0][1] == 0:\n  PossibleAll()\nif medians == 2:\n  PossibleAll()\nif medians == 0:\n  def Proc(arr):\n    zs = sorted(arr + arr)\n    zs[n-1], zs[n] = zs[n], zs[n-1]\n    return CalcuHalf(zs)\n  print max([Proc(xs) + CalcuHalf(sorted(ys+ys)),\n             Proc(ys) + CalcuHalf(sorted(xs+xs))])\nelse:\n  def Proc(arr):\n    zs = sorted(arr + arr)\n    zs[n-2], zs[n] = zs[n], zs[n-2]\n    az = sorted(arr + arr)\n    az[n-1], az[n+1] = az[n+1], az[n-1]\n    return max([CalcuHalf(zs), CalcuHalf(az)])\n  print max([Proc(xs) + CalcuHalf(sorted(ys+ys)),\n             Proc(ys) + CalcuHalf(sorted(xs+xs))])\n ",
    "tags": [
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "330",
    "index": "A",
    "title": "Cakeminator",
    "statement": "You are given a rectangular cake, represented as an $r × c$ grid. Each cell either has an evil strawberry, or is empty. For example, a $3 × 4$ cake may look as follows:\n\nThe cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.\n\nPlease output the maximum number of cake cells that the cakeminator can eat.",
    "tutorial": "Long solution: Once an evil strawberry, always an evil strawberry (since they can't be eaten). Thus, if a row cannot be eaten before any eat is performed, it can never be eaten. Same with column. Thus, you can know which columns and which rows you can eat. Just try to eat them all and calculate how many cells you actually eat. Short solution: A row or a column cannot be eaten if it has at least one strawberry. A cell cannot be eaten if both its row and its column cannot be eaten -- otherwise you can eat the row/column and eat it! If there are r' rows that cannot be eaten, and c' columns that cannot be eaten, then there are r' * c' cells that cannot be eaten -- a cell such that both its row and columns cannot be eaten. Since all other cells can be eaten, answer is R * C - r' * c'.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "330",
    "index": "B",
    "title": "Road Construction",
    "statement": "A country has $n$ cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given $m$ pairs of cities — roads cannot be constructed between these pairs of cities.\n\nYour task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.",
    "tutorial": "Since m < n/2, there exists at least one node that is not incident to any edge. The constraints can be satisfied if and only if the graph is a star graph. We can just create a star graph centered with the node and connect it to all other nodes.",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 1300
  },
  {
    "contest_id": "332",
    "index": "A",
    "title": "Down the Hatch!",
    "statement": "Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!\n\nYesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All $n$ people who came to the barbecue sat in a circle (thus each person received a unique index $b_{i}$ from 0 to $n - 1$). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the $j$-th turn was made by the person with index $b_{i}$, then this person acted like that:\n\n- he pointed at the person with index $(b_{i} + 1) mod n$ either with an elbow or with a nod ($x mod y$ is the remainder after dividing $x$ by $y$);\n- if $j ≥ 4$ and the players who had turns number $j - 1$, $j - 2$, $j - 3$, made during their turns the same moves as player $b_{i}$ on the current turn, then he had drunk a glass of juice;\n- the turn went to person number $(b_{i} + 1) mod n$.\n\nThe person who was pointed on the last turn did not make any actions.\n\nThe problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.\n\nYou can assume that in any scenario, there is enough juice for everybody.",
    "tutorial": "Since $n  \\ge  4$, one Vasya's turn does not affect his other turns. Consequently, you should find just the number of positions (0-indexed) in the given string, which indexes are multiples of $n$ and before which there are at least three same symbols. Asymptotics of the solution - $O(|s|)$",
    "code": "#include <iostream>\n#include <string>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <cmath>\nusing namespace std;\n \nint main()\n{\n    int n;\n    string s;\n    cin >> n;\n    getline(cin, s);\n    getline(cin, s);\n    int ans = 0;\n    for (int i = n; i < s.length(); i += n)\n        if (s[i - 1] == s[i - 2] && s[i - 2] == s[i - 3])\n            ++ans;\n    cout << ans << endl;\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "332",
    "index": "B",
    "title": "Maximum Absurdity",
    "statement": "Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as $n$ laws (each law has been assigned a unique number from 1 to $n$). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.\n\nThis time mr. Boosch plans to sign $2k$ laws. He decided to choose \\textbf{exactly two} non-intersecting segments of integers from 1 to $n$ of length $k$ and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers $a$, $b$ $(1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k)$ and sign all laws with numbers lying in the segments $[a; a + k - 1]$ and $[b; b + k - 1]$ (borders are included).\n\nAs mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.",
    "tutorial": "Let's build the array of partial sums, which will permit to find the sum in any segment of the array in $O(1)$. Let's iterate through the number $a$ (the left edge of the leftmost segment) in descending order. Now we need to find among segments of length $k$, starting from position which index is greater than or equal to $a + k$, a segment with the maximum sum. Since we search $a$ in descending order, we can maintain this segment during the transition from $a$ to $a - 1$. Asymptotics of the solution - $O(n)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <vector>\nusing namespace std;\n \ninline __int64 get_sum(const vector<__int64> &sum, int l, int r)\n{\n    return (l == 0) ? sum[r] : (sum[r] - sum[l - 1]);\n}\n \nint main()\n{\n    int n, k;\n    scanf(\"%d %d\", &n, &k);\n    vector<__int64> a(n), sum(n);\n    scanf(\"%I64d\", &a[0]);\n    sum[0] = a[0];\n    for (int i = 1; i < n; ++i)\n    {\n        scanf(\"%I64d\", &a[i]);\n        sum[i] = sum[i - 1] + a[i];\n    }\n    pair<int, int> ans = make_pair(n - 2 * k, n - k);\n    __int64 ans_sum = get_sum(sum, n - 2 * k, n - k - 1) + get_sum(sum, n - k, n - 1);\n    pair<int, __int64> suff_max = make_pair(n - k, get_sum(sum, n - k, n - 1));\n    for (int i = n - 2 * k - 1; i >= 0; --i)\n    {\n        __int64 cur = get_sum(sum, i + k, i + 2  * k - 1);\n        if (cur >= suff_max.second)\n            suff_max = make_pair(i + k, cur);\n        cur = get_sum(sum, i, i + k - 1) + suff_max.second;\n        if (cur >= ans_sum)\n        {\n            ans_sum = cur;\n            ans = make_pair(i, suff_max.first);\n        }\n    }\n    printf(\"%d %d\n\", ans.first + 1, ans.second + 1);\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "332",
    "index": "C",
    "title": "Students' Revenge",
    "statement": "A student's life is fraught with complications. Some Berland University students know this only too well. Having studied for two years, they contracted strong antipathy towards the chairperson of some department. Indeed, the person in question wasn't the kindest of ladies to begin with: prone to reforming groups, banning automatic passes and other mean deeds. At last the students decided that she just can't get away with all this anymore...\n\nThe students pulled some strings on the higher levels and learned that the next University directors' meeting is going to discuss $n$ orders about the chairperson and accept exactly $p$ of them. There are two values assigned to each order: $a_{i}$ is the number of the chairperson's hairs that turn grey if she obeys the order and $b_{i}$ — the displeasement of the directors if the order isn't obeyed. The students may make the directors pass any $p$ orders chosen by them. The students know that the chairperson will obey exactly $k$ out of these $p$ orders. She will pick the orders to obey in the way that minimizes first, the directors' displeasement and second, the number of hairs on her head that turn grey.\n\nThe students want to choose $p$ orders in the way that maximizes the number of hairs on the chairperson's head that turn grey. If there are multiple ways to accept the orders, then the students are keen on maximizing the directors' displeasement with the chairperson's actions. Help them.",
    "tutorial": "Let's sort orders ascending $b_{i}$, and by equality of $b_{i}$ - descending $a_{i}$. One can assume that in an optimal solution all the orders obeyed by the chairperson go in the sorted list after orders that she hasn't obeyed (it may be wrong if there are several same orders, but it doesn't affect parameters of an answer). Let's iterate through $i$ - the position of the first order in the sorted list, which the chairperson will obey. To the left of this order we should choose $p - k$ orders which the chairperson won't obey. As we should choose orders with the maximum sum of $b_{i}$, we can just choose $p - k$ orders that immediately precede the $i$-th order. To the right of the $i$-th order we should choose $k - 1$ orders which the chairperson will obey. These orders should have the maximum sum of $a_{i}$. If we iterate $i$ by descending, we can keep these $k - 1$ orders in some data structure that can perform basic operations with sets in logarithmic time (for example, multiset in C++). Asymptotics of the solution - $O(nlogn)$",
    "code": "#include <iostream>\n#include <algorithm>\n#include <set>\n#include <cstdio>\n#include <cassert>\n#include <cmath>\nusing namespace std;\n \nconst int MAXN = 100000;\nstruct Order\n{\n        int a, b, nmb;\n} orders[MAXN];\nint n, p, k;\nmultiset<int> s;\n__int64 pref[MAXN];\n \nbool cmp1(const Order &x, const Order &y)\n{\n        return x.b < y.b || (x.b == y.b && x.a > y.a);\n}\n \nbool cmp2(const Order &x, const Order &y)\n{\n        return x.a > y.a;\n}\n \nint main()\n{\n        scanf(\"%d %d %d\", &n, &p, &k);\n        for (int i = 0; i < n; ++i)\n        {\n                scanf(\"%d %d\", &orders[i].a, &orders[i].b);\n                orders[i].nmb = i + 1;\n        }\n        sort(orders, orders + n, cmp1);\n        pref[0] = orders[0].b;\n        for (int i = 1; i < n; ++i)\n                pref[i] = pref[i - 1] + orders[i].b;\n        __int64 sum = 0;\n        for (int i = n - 1; i > n - k; --i)\n        {\n                sum += orders[i].a;\n                s.insert(orders[i].a);\n        }\n        pair<__int64, __int64> res = make_pair(-1, -1);\n        int pos = -1;\n        for (int i = n - k; i >= p - k; --i)\n        {\n                __int64 temp = 0;\n                if (p != k)\n                        temp = (i == p - k) ? pref[i - 1] : pref[i - 1] - pref[i - p + k - 1];\n                pair<__int64, __int64> cur = make_pair(sum + orders[i].a, temp);\n                if (cur > res)\n                {\n                        pos = i;\n                        res = cur;\n                }\n                sum += orders[i].a;\n                s.insert(orders[i].a);\n                int del = *s.begin();\n                s.erase(s.begin());\n                sum -= del;\n                assert(sum >= 0);\n        }\n        sort(orders + pos + 1, orders + n, cmp2);\n        for (int i = pos - p + k; i <= pos + k - 1; ++i)\n                printf(\"%d \", orders[i].nmb);\n        return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "332",
    "index": "D",
    "title": "Theft of Blueprints",
    "statement": "Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of $n$ missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos $i$ and $j$ is patrolled by $c_{i, j}$ war droids.\n\nThe insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any $k$-element set of silos $S$ there is exactly one silo that is directly connected by a passage with each silo from $S$ (we'll call this silo \\underline{adjacent with $S$}). Having considered that, the insurgents decided to act as follows:\n\n- they choose a $k$-element set of silos $S$;\n- a group of scouts lands from the air into each silo from $S$;\n- each group moves along the corresponding passage to the silo, adjacent with $S$ (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints);\n- in the silo, adjacent with $S$, the groups get on the ship and fly away.\n\n\\underline{The danger of the operation} is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set $S$. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set $S$. Solve this problem to help the insurgents protect the ideals of the Republic!",
    "tutorial": "In the problem is given the weighted undirected graph without loops and multiple edges satisfying the following property: for every set $S$ containing $k$ vertices there is exactly one vertex adjacent to all vertices from this set (*) (this vertex is called \"adjacent with $S$\"). For any $k$-element set of vertices we can calculate the special characteristic: the sum of the weights of edges that connect vertices from $S$ with vertex, adjacent with S. It is required to find the mathematical average of the characteristics of all $k$-element sets of vertices. One can solve this problem using the following fact (the proof is now available only in the Russian version of this post): if $k  \\ge  3$, only complete graph containing $k + 1$ vertices satisfies the problem statement. For complete graphs answer is equal to doubled sum of weights of all edges, divided by $n$. The same way one can calculate answer if $k = 1$. Now let's consider the case $k = 2$. Let's iterate through the vertex $i$ which is adjacent with our two-element set. Let's write in ascending order all such numbers $j$ that $c_{i, j}  \\neq  - 1$. Any two different vertices of this list form the set for which vertex $i$ is adjacent, and there are no other such sets of vertices. Looking over all pairs of vertices in this list, we can add characteristics of all these sets to the answer. Since it's guaranteed that the graph satisfies the property (*), each pair of vertices will be analyzed only once. A similar approach is used in the validator for this problem. Asymptotics of the solution - $O(n^{2})$.",
    "code": "#include <iostream>\n#include <vector>\n#include <cstdio>\n#include <cmath>\nusing namespace std;\n \nconst int MAXN = 2000;\n__int64 c[MAXN][MAXN];\n \nint main()\n{\n    int n, k, temp;\n    scanf(\"%d %d\", &n, &k);\n    for (int i = 0; i < n - 1; ++i)\n    {\n        c[i][i] = -1;\n        for (int j = i + 1; j < n; ++j)\n        {\n            scanf(\"%d\", &temp);\n            c[j][i] = c[i][j] = temp;\n        }\n    }\n    c[n - 1][n - 1] = -1;\n    __int64 sum = 0, cnt = 0;\n    if (k == 1 || (k > 2 && n == k + 1))\n    {\n        cnt = n;\n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < n; ++j)\n                if (c[i][j] != -1)\n                    sum += c[i][j];\n    }\n    if (k == 2)\n    {\n        cnt = n * (n - 1) / 2;\n        vector<int> vect;\n        for (int i = 0; i < n; ++i)\n        {\n            vect.clear();\n            for (int j = 0; j < n; ++j)\n                if (c[i][j] != -1)\n                    vect.push_back(j);\n            for (int j = 0; j < vect.size(); ++j)\n                for (int z = j + 1; z < vect.size(); ++z)\n                    sum += c[i][vect[j]] + c[i][vect[z]];\n        }\n    }\n    cout << sum / cnt << endl;\n    return 0;\n}",
    "tags": [
      "graphs",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "332",
    "index": "E",
    "title": "Binary Key",
    "statement": "Let's assume that $p$ and $q$ are strings of positive length, called the container and the key correspondingly, string $q$ only consists of characters 0 and 1. Let's take a look at a simple algorithm that extracts message $s$ from the given container $p$:\n\n\\begin{verbatim}\ni = 0;\nj = 0;\ns = <>;\nwhile i is less than the length of the string p\n{\nif q[j] == 1, then add to the right of string s character p[i];\nincrease variables i, j by one;\nif the value of the variable j equals the length of the string q, then j = 0;\n}\n\\end{verbatim}\n\nIn the given pseudocode $i$, $j$ are integer variables, $s$ is a string, '=' is an assignment operator, '==' is a comparison operation, '[]' is the operation of obtaining the string character with the preset index, '<>' is an empty string. We suppose that in all strings the characters are numbered starting from zero.\n\nWe understand that implementing such algorithm is quite easy, so your task is going to be slightly different. You need to construct the lexicographically minimum key of length $k$, such that when it is used, the algorithm given above extracts message $s$ from container $p$ (otherwise find out that such key doesn't exist).",
    "tutorial": "Let's iterate through the number of ones in the key ($cnt$). One can note that $cnt$ can't be large than $min(|s|, k)$, as the keys containing more than $|s|$ ones can't be lexicographically minimal. Let's consider the solution of this problem with the fixed $cnt$. Any complete pass on the key corresponds to the extracting $cnt$ of $k$ scanned symbols of the container, i. e. container is divided into blocks of length $k$, and the message is divided into blocks of length $cnt$ (last blocks may be shorter). We'll number the characters in each block of the message from 0 to $cnt - 1$. We'll call $(q, j)$-suffix suffix of $q$-th block of the message that starts from a position $j$ in this block. Let's solve the problem with dynamic programming: $d_{i, j}$ is true if there exists a key, the first $i$ characters of which are zeros and which corresponds to the extracting from container the string that is the result of concatenation of all $(q, j)$-suffixes of the message. The transitions are based on the filling of i-th position of the key with zero or one (we need to choose the minimum acceptable character). To restore the key you can keep chosen characters for each subtask. Asymptotics of the solution - $O(k \\cdot |s|^{2} + |p|)$.",
    "code": "#include <iostream> \n#include <string> \n#include <cstdio> \n#include <vector> \n#include <algorithm> \n#include <cmath> \nusing namespace std; \n \nbool d[2050][250]; \nbool pr[2050][250]; \n \nint main() \n{ \n    string p, s; \n    getline(cin, p); \n    getline(cin, s); \n    int k; \n    cin >> k; \n    string result = \"\";\n    for (int cnt = 1; cnt <= min(k, (int)s.length()); ++cnt) \n    { \n        if (p.length() / k * cnt > s.length())  \n            break;  \n        d[k][cnt] = true; \n        for (int j = 0; j < cnt; ++j) \n            d[k][j] = false; \n        for (int i = k - 1; i >= 0; --i) \n        { \n            d[i][cnt] = true; \n            pr[i][cnt] = false; \n            for (int j = cnt - 1; j >= 0; --j) \n            { \n                d[i][j] = false; \n                if (d[i + 1][j]) \n                { \n                    d[i][j] = true; \n                    pr[i][j] = false; \n                } \n                else \n                    if (d[i + 1][j + 1]) \n                    { \n                        bool yes = true; \n                        for (int cur1 = j, cur2 = i; cur1 < s.length() || cur2 < p.length(); cur1 += cnt, cur2 += k) \n                            if (cur1 >= s.length() || cur2 >= p.length() || s[cur1] != p[cur2]) \n                            { \n                                yes = false; \n                                break; \n                            } \n                        if (yes) \n                        { \n                            d[i][j] = true; \n                            pr[i][j] = true; \n                        } \n                    } \n            } \n        } \n        if (!d[0][0]) \n            continue; \n        string ans; \n        int j = 0; \n        for (int i = 0; i < k; ++i) \n            if (pr[i][j]) \n            { \n                ans += '1'; \n                ++j; \n            } \n            else \n                ans += '0'; \n        if (result == \"\" || ans < result)\n        result = ans;\n    } \n    if (result == \"\") \n        cout << 0 << endl; \n    else \n        cout << result << endl; \n    return 0; \n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "333",
    "index": "A",
    "title": "Secrets",
    "statement": "Gerald has been selling state secrets at leisure. All the secrets cost the same: $n$ marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.\n\nOne day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?\n\nThe formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of $n$ marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least $n$ marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.",
    "tutorial": "Actually we are looking for longest sequence of natural number $a_{1}, a_{2}, ..., a_{k}$, so that every number in it sequence is the power of three, sum of all numbers is more then $n$ and if we remove any number sum will be less then $n$. To be precise we are looking for length of this sequence. Consider minimal number $a_{i} = A$ in the sequence. All this numbers are divides to $A$ since them all are powers of 3. And then, sum $S$ of all this number is divides to $A$ too. Suppose that $n$ is divide to $A$ too. Then, since $S > n$, then $S - A  \\ge  n$. And then if we remove $A$ from sequence, sum of other number not less then $n$ - contradist with second condition. Well, we now that $n$ is not divide to none element in sequence. Now lets find minimal $k$ so that $n\\ \\mathrm{\\mod\\3^{k}\\not=0}$, and answer is $\\left[{\\frac{n}{3^{k}}}\\right]$.",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "333",
    "index": "B",
    "title": "Chips",
    "statement": "Gerald plays the following game. He has a checkered field of size $n × n$ cells, where $m$ various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for $n - 1$ minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases:\n\n- At least one of the chips at least once fell to the banned cell.\n- At least once two chips were on the same cell.\n- At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row).\n\nIn that case he loses and earns $0$ points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.",
    "tutorial": "At first lets make two remarks: On every (vertical of horizontal) line we can put only one chip. If there is at least one forbidden cell on the line then we can't put chip on this line. Follow last remark we will avoid hits chip on forbidden cells. Lets avoid ``collisions'' of chips. Lets consider these four line: vertical lines number $i$ and $n + 1 - i$ and horizontal lines with the same numbers. Chips on these lines can collides together, but con't collides to another chip. Therefore we can solve the problem for these four line independently. And finally lets observe that we can put the chip on each of these lines without cillisions as well as on the picture. So, we can iterate all possible fours and put chip on every possible line. And don't fogot about case of two middle line in case of $n$ is odd.",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "333",
    "index": "C",
    "title": "Lucky Tickets",
    "statement": "Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such tickets and moved on to a more general question. Now he explores $k$-lucky tickets.\n\nPollard sais that a ticket is $k$-lucky if we can add arithmetic operation signs between its digits to the left or right of them (i.e., \"+\", \"-\", \"$ × $\") and brackets so as to obtain the correct arithmetic expression whose value would equal $k$. For example, ticket \"224201016\" is 1000-lucky as $( - 2 - (2 + 4)) × (2 + 0) + 1016 = 1000$.\n\nPollard was so carried away by the lucky tickets that he signed up for a seminar on lucky tickets and, as far as Gerald knows, Pollard will attend it daily at 7 pm in some famous institute and will commute to it in the same tram for $m$ days. In this tram tickets have eight digits. And Gerald wants to make a surprise for Pollard: each day Pollard will receive a tram $k$-lucky ticket. The conductor has already agreed to give Pollard certain tickets during all these $m$ days and he only wants Gerald to tell him what kind of tickets to give out. In this regard, help Gerald pick exactly $m$ distinct $k$-lucky tickets.",
    "tutorial": "In this problem we can find the right amount of lucky tickets. Lets consider amount of different numbers we can get from one four-digit ticket number. It is easy to iterate all this tickets, since it amount only $10^{4}$. It happened that we can get almost 60 numbers from ticket on the average. Suppose we can get number $x$ from ticket $n$. It is clearly that either $x - k  \\ge  0$ or $k - x  \\ge  0$. If $k - x  \\ge  0$ we can write eight-digit ticket number who will have $k - x$ in the first four digits and $n$ in the last four digits. It is clearly that such ticket is $k$-lucky. This method allows us to get almost $600 000$ lucky tickets and it is enough.",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 2700
  },
  {
    "contest_id": "333",
    "index": "D",
    "title": "Characteristics of Rectangles",
    "statement": "Gerald found a table consisting of $n$ rows and $m$ columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value — it seemed to be too small. And to make this value larger, he decided to crop the table a little: delete some columns on the left and some on the right, as well as some rows from the top and some from the bottom. Find what the maximum property of the table can be after such cropping. Note that the table should have at least two rows and at least two columns left in the end. The number of cropped rows or columns from each of the four sides can be zero.",
    "tutorial": "In this problem we must to find maximal value of minimum of values on four intersections of two rows and two columns of table. In another words, we are looking for maximum value of $min(a_{i1, j1}, a_{i1, j2}, a_{i2, j1}, a_{i2, j2})$ for all $i_{1}, i_{2}, j_{1}, j_{2}$ such that $1  \\le  i_{1}, i_{2}  \\le  n$, $1  \\le  j_{1}, j_{2}  \\le  m$, $i_{1}  \\neq  i_{2}$, $j_{1}  \\neq  j_{2}$. Lets us binary search of the answer. For us it we must can define is there two rows and two colums with ones on all four its intersections; in other words, integers $i_{1}, i_{2}, j_{1}, j_{2}$ so that $a_{i1, j1} = a_{i1, j2} = a_{i2, j1} = a_{i2, j2} = 1$. Lets consider all pair of natural numbers $(i_{1}, i_{2})$ so that there exist nutural number $j$ so that $a_{i1, j} = a_{i2, j} = 1$. Existence of two equals such pairs is equals to existence of above four numbers. But it is can be only $\\frac{n\\times(n-1)}{2}$ such pairs. Therefore we can make the array where we will mark pair who were meets. Lets iterate all pairs in any order until we meet repeated pair or pairs are ends. So we have solution of time $O(n^{2}\\log(n))$.",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "implementation",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "333",
    "index": "E",
    "title": "Summer Earnings",
    "statement": "Many schoolchildren look for a job for the summer, and one day, when Gerald was still a schoolboy, he also decided to work in the summer. But as Gerald was quite an unusual schoolboy, he found quite unusual work. A certain Company agreed to pay him a certain sum of money if he draws them three identical circles on a plane. The circles must not interfere with each other (but they may touch each other). He can choose the centers of the circles only from the $n$ options granted by the Company. He is free to choose the radius of the circles himself (all three radiuses must be equal), but please note that the larger the radius is, the more he gets paid.\n\nHelp Gerald earn as much as possible.",
    "tutorial": "In this problem it is need to draw three circle equals together with maximum possible radius with centers in given points. In another words it is need to find triangle wich minimum side is maximal. Unfortunately solution with bit optimize is not expected for us. Lets call to memory two simple geometric facts. Firstly, sum of alnges of trianle is equals to $180^{\\circ}$. Secondly, minimal angle is opposit to minimal side of triangle. Since, at leats one side of angles of triangle not less then $60^{\\circ}$ and this anlge is not least one. And side opposite to it is not least side. Therefore, if in $\\triangle A B C$ $\\angle A B C\\geq60^{\\circ}$ then $min(|AB|, |BC|, |CA|) = min(|AB|, |BC|)$. And then lets do the follows. Lets iterate apex $B$ and for each $B$ lets find triangle with maximal minimum of sides when $B$ is the apex of triangle and $\\angle B\\geq60^{\\circ}$. For it lets sort all other points by the angle relative to $B$, and for each point $A$ lets find point $C$ most distant to $B$ among such points that $\\angle A B C\\geq60^{\\circ}$. We have to use segment tree for maximum and two pointers or binary searsh to now left and right bound of possible points $C$ during iterating $A$. Finally, we have solution of time $O(n^{2}\\log(n))$.",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "geometry",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "334",
    "index": "A",
    "title": "Candy Bags",
    "statement": "Gerald has $n$ younger brothers and their number happens to be even. One day he bought $n^{2}$ candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer $k$ from $1$ to $n^{2}$ he has exactly one bag with $k$ candies.\n\nHelp him give $n$ bags of candies to each brother so that all brothers got the same number of candies.",
    "tutorial": "In this problem one must divide all natural numbers from 1 to $n^{2}$ to groups size of $n$ with the same sums. Lets divide all this numbers to pairs $(1,n^{2}),(2,n^{2}-1),\\cdot\\cdot\\cdot,(\\frac{n^{2}}{2},\\frac{n^{2}}{2}+1)$. We can to do it since $n$ is even and therefore $n^{2}$ is even too. Then we can just make $n$ groups consists of $\\frac{n}{2}$ of these pairs.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "334",
    "index": "B",
    "title": "Eight Point Sets",
    "statement": "Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers $x_{1}, x_{2}, x_{3}$ and three more integers $y_{1}, y_{2}, y_{3}$, such that $x_{1} < x_{2} < x_{3}$, $y_{1} < y_{2} < y_{3}$ and the eight point set consists of all points $(x_{i}, y_{j})$ ($1 ≤ i, j ≤ 3$), except for point $(x_{2}, y_{2})$.\n\nYou have a set of eight points. Find out if Gerald can use this set?",
    "tutorial": "In this problem you must to do only what's written - you must to define does this set of points sutisfies to decribed conditions. There are many ways to define it. For instance: Check if there are exactly 3 discinct $x$'s and $y$'s. One can put all $x$'s to set and then get it size to find amount of distinct $x$'s (as well as $y$'s). Then print ``ugly'' if this amount isn't equals to 3. Finally we have $x_{1}, x_{2}$ and $x_{3}$ as well as $y_{1}, y_{2}$ and $y_{3}$. Now lets check if for every pair $(x_{i}, y_{j})$ (except $(x_{2}, y_{2})$) such point exist in given set of points. But I think that to read editoral of this problem is not good idea. It is better to just look at the implementation.",
    "tags": [
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "335",
    "index": "A",
    "title": "Banana",
    "statement": "Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly $n$ stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length $n$. Piegirl wants to create a string $s$ using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length $n$ for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form $s$. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.",
    "tutorial": "Instead of calculating the smallest possible number of sheets given a fixed $n$, let us instead try to compute the smallest possible value of $n$ given a fixed number of sheets. Let $k$ denote the number of sheets. If a particular letter appears $p$ times in $s$, then it must appear at least $ceil(p / k)$ times in the sheet. Thus we can compute the smallest possible value of $n$ by summing $ceil(p / k)$ over all letters. Now the original problem can be solved using binary search on $k$ (or brute force, since the constraints were small enough).",
    "code": "from collections import Counter\ndef main():\n    s = raw_input().strip()\n    l = int(raw_input())\n    d = Counter(s)\n    if len(d) > l:\n        print -1\n        return\n    lo = 0\n    hi = 10000\n    while lo + 1 < hi:\n        mid = (lo + hi) / 2\n        c = 0\n        for x in d.itervalues():\n            c += (x + mid - 1) / mid\n        if c > l:\n            lo = mid\n        else:\n            hi = mid\n    print hi\n    ans = []\n    for x in d.iteritems():\n        ans.append(x[0] * ((x[1] + hi - 1) / hi))\n    t = ''.join(ans)\n    if len(t) < l:\n        t += 'a' * (l - len(t))\n    print t\nmain()",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "335",
    "index": "B",
    "title": "Palindrome",
    "statement": "Given a string $s$, determine if it contains any palindrome of length exactly $100$ as a \\textbf{subsequence}. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of $s$ and is as long as possible.",
    "tutorial": "There's a well known $O(n^{2})$ solution that allows one to find a longest subsequence of a string which is a palindrome: for every pair of positions $l$ and $r$, such that $l  \\le  r$, find the length $d$ of the longest palindrome subsequence between those positions. d[l][r] = max(d[l][r-1], d[l + 1][r], s[l] == s[r] ? d[l + 1][r - 1] + 1 : 0).There are two ways to solve this problem faster than O($n^{2}$) with the constraints given in the problem: Use dynamic programming. For every position $l$ and length $k$ find the leftmost position $r$, such that there's a palindrome of length $k$ in the substring of $s$ starting at $l$ and ending at $r$. For position $l$ and length $k$ r[l][k] = min(r[l + 1][k], next(r[l + 1][k - 1], s[l])),where next(pos, s) is the next occurrence of character $s$ after position $pos$. Next can be precomputed for all the positions and all the characters in advance. If length is less than 2600, use the well-known O($n^{2}$) dynamic programming approach. Otherwise by pigeonhole principle there's at least one character that appears in the string at least 100 times -- find it and print it 100 times.",
    "code": "#include <string>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <set>\n#include <queue>\n#include <map>\n#include <cstdio>\n#include <iomanip>\n#include <sstream>\n#include <iostream>\n#include <cstring>\n#define REP(i,x,v)for(int i=x;i<=v;i++)\n#define REPD(i,x,v)for(int i=x;i>=v;i--)\n#define FOR(i,v)for(int i=0;i<v;i++)\n#define FORE(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)\n#define FOREACH(i,t) FORE(i,t)\n#define REMIN(x,y) (x)=min((x),(y))\n#define REMAX(x,y) (x)=max((x),(y))\n#define pb push_back\n#define sz size()\n#define mp make_pair\n#define fi first\n#define se second\n#define ll long long\n#define IN(x,y) ((y).find((x))!=(y).end())\n#define un(v) v.erase(unique(ALL(v)),v.end())\n#define LOLDBG\n#ifdef LOLDBG\n#define DBG(vari) cerr<<#vari<<\" = \"<<vari<<endl;\n#define DBG2(v1,v2) cerr<<(v1)<<\" - \"<<(v2)<<endl;\n#else\n#define DBG(vari)\n#define DBG2(v1,v2)\n#endif\n#define CZ(x) scanf(\"%d\",&(x));\n#define CZ2(x,y) scanf(\"%d%d\",&(x),&(y));\n#define CZ3(x,y,z) scanf(\"%d%d%d\",&(x),&(y),&(z));\n#define wez(x) int x; CZ(x);\n#define wez2(x,y) int x,y; CZ2(x,y);\n#define wez3(x,y,z) int x,y,z; CZ3(x,y,z);\n#define SZ(x) int((x).size())\n#define ALL(x) (x).begin(),(x).end()\n#define tests int dsdsf;cin>>dsdsf;while(dsdsf--)\n#define testss int dsdsf;CZ(dsdsf);while(dsdsf--)\nusing namespace std;\ntypedef pair<int,int> pii;\ntypedef vector<int> vi;\ntemplate<typename T,typename TT> ostream &operator<<(ostream &s,pair<T,TT> t) {return s<<\"(\"<<t.first<<\",\"<<t.second<<\")\";}\ntemplate<typename T> ostream &operator<<(ostream &s,vector<T> t){s<<\"{\";FOR(i,t.size())s<<t[i]<<(i==t.size()-1?\"\":\",\");return s<<\"}\"<<endl; }\ninline void pisz (int x) { printf(\"%d\\n\", x); }\n \nchar s[1<<20];\nint dp[50002][102];\nint ne[222][50002];\n \nchar pa[1111];\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    scanf(\"%s\",s);\n    int n=strlen(s);\n    FOR(i,n+1)dp[i][0]=i-1;\n    FOR(i,n+1)dp[i][1]=i;\n    FOR(c,222)\n    {\n        int w=n;\n        ne[c][n]=n;\n        REPD(i,n-1,0)\n        {\n            if (s[i]==c) w=i;\n            ne[c][i]=w;\n        }\n    }\n    int mx=1;\n    REP(d,2,100)\n    {\n        dp[n][d]=n;\n        REPD(i,n-1,0)\n        {\n            dp[i][d]=dp[i+1][d];\n            if (dp[i+1][d-2]<n) REMIN(dp[i][d],ne[s[i]][dp[i+1][d-2]+1]);\n        }\n        if (dp[0][d]<n) mx=d;\n    }\n    //DBG(mx);\n    int d=mx;\n    int x=0;\n    int cnt=0;\n    while(d>0)\n    {\n \n        while(dp[x][d]==dp[x+1][d]) x++;\n \n        pa[cnt]=pa[mx-cnt-1]=s[x];\n        x++;\n        cnt++;\n        d-=2;\n    }\n    pa[mx]=0;\n    printf(\"%s\\n\",pa);\n    \n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "335",
    "index": "C",
    "title": "More Reclamation",
    "statement": "In a far away land, there are two cities near a river. One day, the cities decide that they have too little space and would like to reclaim some of the river area into land.\n\nThe river area can be represented by a grid with $r$ rows and exactly two columns — each cell represents a rectangular area. The rows are numbered $1$ through $r$ from top to bottom, while the columns are numbered $1$ and $2$.\n\nInitially, all of the cells are occupied by the river. The plan is to turn some of those cells into land one by one, with the cities alternately choosing a cell to reclaim, and continuing until no more cells can be reclaimed.\n\nHowever, the river is also used as a major trade route. The cities need to make sure that ships will still be able to sail from one end of the river to the other. More formally, if a cell $(r, c)$ has been reclaimed, it is not allowed to reclaim any of the cells $(r - 1, 3 - c)$, $(r, 3 - c)$, or $(r + 1, 3 - c)$.\n\nThe cities are not on friendly terms, and each city wants to be the last city to reclaim a cell (they don't care about how many cells they reclaim, just who reclaims a cell last). The cities have already reclaimed $n$ cells. Your job is to determine which city will be the last to reclaim a cell, assuming both choose cells optimally from current moment.",
    "tutorial": "The most straightforward way to solve this problem is to use Grundy numbers. Define a segment as a maximal range of rows in which no cells have been reclaimed. Since segments have no bearing on other segments, they can be assigned Grundy numbers. There are 4 types of segments: The entire river. A section of river containing one of the ends. A section of river blocked at both ends in the same column A section of river blocked at both ends in different columns Each time a cell is reclaimed, it splits a segment into 2 segments (one of which may have size 0). We can compute the Grundy value for all possible segments in O($r^{2}$). Then after sorting the reclaimed cells by row number, we can find all segments and compute the Grundy number for the full state. Alternatively, we can compute the result directly. Suppose the game is over. We can determine who won the game just by looking at the top row and the bottom row. Let us define \"parity\" as the modulo 2 remainder of ($r + n + c0 + c1$), where $c0$ is the column of the reclaimed cell with the lowest row, and $c1$ is the column of the reclaimed cell with the highest row. Claim: when the game is over, the parity is even. This can be seen by observing that the number of empty rows is equal to the number of times the column changes. In other words, if c0==c1, there are an even number of empty rows, otherwise an odd number of empty rows. Now, given r, c0, and c1, we can determine n, and therefore the winner. Let us consider the case where there are no reclaimed cells. If r is even, then the second city can win with a mirroring strategy. When the first city reclaims cell (a,b), the second city follows with (r+1-a,b). Similarly, if r is odd then the first city wins by a mirroring strategy, playing first in ((r+1)/2, 0), and subsequently following the strategy for even r. Now suppose there are reclaimed cells. Let us define $r0$ as the number of empty rows in the segment starting from one end, and $r1$ as the number of empty rows starting from the other end. Case 1: if r0==r1 and the parity is even, the state is losing. All available moves will either decrease r0, decrease r1, or make the parity odd. The other player can respond to the first two types of moves with a mirroring strategy, and the third by making the parity even again (there will always be such a move that doesn't affect r0 or r1, based on the fact that the argument above). Case 2: if abs(r0-r1)>=2 then the state is winning. Suppose, without loss of generality, that r0-r1>=2. Then either of the cells (r1+1, 1) and (r1+1, 2) may be reclaimed, and one of them must lead to Case 1 (since they both result in r0==r1, and one will have even parity and the other odd). Case 3: if abs(r0-r1)<2 and the parity is odd, the state is winning. If r0==r1, then we can change the parity without affecting r0 or r1, leaving our opponent in Case 1. Otherwise, there is a unique move that leaves our opponent in Case 1. (note that cases 2 and 3 together imply that all states with odd parity are winning) Case 4: if abs(r0-r1)==1 and the parity is even, there is at most one move that doesn't leave our opponent in Case 2 or Case 3. Suppose r0==r1+1. We must change either r0 or r1, since all other moves will change the parity to odd. Thus our only option is to decrease r0, since decreasing r1 would leave our opponent in Case 2. We could decrease r0 by 1, but doing so would change the parity. Thus we must decrease r0 by 2, and there is at most one move that does so and keeps the parity even. It follows that if floor(r0/2)+floor(r1/2) is even, then this is a losing position, otherwise a winning position.",
    "code": "#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <cassert>\n#include <ctime>\n#include <cmath>\n#include <algorithm>\n#include <string>\n#include <vector>\n#include <deque>\n#include <queue>\n#include <list>\n#include <set>\n#include <map>\n#include <iostream>\n \n#define pb push_back\n#define mp make_pair\n#define TASKNAME \"\"\n \n#ifdef LOCAL\n#define eprintf(...) fprintf(stderr,__VA_ARGS__)\n#else\n#define eprintf(...)\n#endif\n \n#define TIMESTAMP(x) eprintf(\"[\" #x \"] Time = %.3lfs\\n\",clock()*1.0/CLOCKS_PER_SEC)\n \n#ifdef linux\n#define LLD \"%lld\"\n#else\n#define LLD \"%I64d\"\n#endif\n \n#define sz(x) ((int)(x).size())\n \nusing namespace std;\n \ntypedef long double ld;\ntypedef long long ll;\ntypedef vector<ll> vll;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef vector<bool> vb;\ntypedef vector<vb> vvb;\ntypedef pair<int, int> pii;\ntypedef pair <ll, ll> pll;\n \nconst int inf = 1e9;\nconst double eps = 1e-9;\nconst double INF = inf;\nconst double EPS = eps;\n \nint G[110][110][3][3];\nbool U[110][210];\nbool F[110][3];\n \nint solve (int l, int r, int m1, int m2)\n{\n  if (l>r)\n    return 0;\n  if (G[l][r][m1][m2]!=-1)\n    return G[l][r][m1][m2];\n  memset(U[r-l],0,sizeof(U[r-l]));\n  int m3;\n  for (int x=l; x<=r; x++)\n    for (int y=0; y<2; y++)\n    {\n      if (F[x][0] || F[x][1])\n        continue;\n      if ((x!=l && F[x-1][y^1]) || (x==l && m1==(y^1)+1))\n        continue;\n      if ((x!=r && F[x+1][y^1]) || (x==r && m2==(y^1)+1))\n        continue;\n      m3=y+1;\n      U[r-l][solve(l,x-1,m1,m3)^solve(x+1,r,m3,m2)]=1;\n    }\n  int tmp=0;\n  while (U[r-l][tmp])\n    tmp++;\n  G[l][r][m1][m2]=tmp;\n  return tmp;\n}\n         \nint main()\n{\n  int n, m, i, x, y;\n  #ifdef LOCAL\n  freopen(TASKNAME\".in\",\"r\",stdin);\n  freopen(TASKNAME\".out\",\"w\",stdout);\n  #endif\n  scanf(\"%d%d\", &n, &m);\n  for (i=0; i<m; i++)\n    scanf(\"%d%d\", &x, &y), y--, F[x][y]=1;\n  memset(G,-1,sizeof(G));  \n  (solve(1,n,0,0)==0)?(puts(\"LOSE\")):(puts(\"WIN\"));\n  TIMESTAMP(end);\n  return 0;\n}",
    "tags": [
      "games"
    ],
    "rating": 2100
  },
  {
    "contest_id": "335",
    "index": "D",
    "title": "Rectangles and Square",
    "statement": "You are given $n$ rectangles, labeled 1 through $n$. The corners of rectangles have integer coordinates and their edges are parallel to the $Ox$ and $Oy$ axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).\n\nYour task is to determine if there's a non-empty subset of the rectangles that forms a square. That is, determine if there exists a subset of the rectangles and some square for which every point that belongs to the interior or the border of that square belongs to the interior or the border of at least one of the rectangles in the subset, and every point that belongs to the interior or the border of at least one rectangle in the subset belongs to the interior or the border of that square.",
    "tutorial": "Even though constraints were allowing O(k^2) solutions, in this editorial we will describe an O(n log(n)) solution. This problem has a rather long solution, involving several very different ideas: On the first step, for every rectangle we want to determine, if we were to consider this rectangle as the top left corner of a square, how long could the top and left edge of the square be (see the picture). If there's no rectangle that is adjacent to the current rectangle on the right, which has the same $y1$ coordinate, then the top edge length is just the width of the current rectangle. Otherwise it is the width of the current rectangle plus the max top edge computed for the rectangle adjacent on the right. Left edge length is computed likewise. When top and left edge lengths are computed, we want to compute the max bottom and right edge length if this rectangle was the bottom right corner of the square. On the second step, we want to find all possible square frames. Look at this picture to better understand what we mean by square frame: To find a frame, let's sort all the points first by $x - y$, and then by $x$ (or $y$ -- both will yield the same result). This way all the points are sorted by the diagonal they belong to, and then by the position on that diagonal. Then we will maintain a stack of pairs (position, edge length), where edge length is min(top edge length, left edge length). Position could be either $x$ or $y$ (within a given diagonal relative differences in xs and ys are the same). Min edge length tells us what is the largest square that could start at that position. When we process a new point on a diagonal, first pop from the stack all the pairs such that their position + edge length is less than our position. If stack after that is empty, then the current point cannot be a bottom right corner of any square. If stack is not empty, then there could be some frames with the current point being bottom right corner. Here we need to make a very important observation. If a square frame is contained within some other square frame, we don't need to consider the outer square frame, since if the outer square frame is then proves to be an actual square, then the inner frame also has to be an actual square, and it is enough to only check an inner frame. With this observation made, we can only check if the last point on the stack forms a frame with the current point, there's no need to check any other point on the stack. Since we already know that last element on the stack reaches to the right and to the bottom further than our current position (otherwise we would have popped it from the stack), to see if we form a frame with that point it is enough to check if we can reach that far to the top and to the left. To do so, check, if position of the current point minus min(bottom edge length, right edge length) for the current point is smaller or equal than the position of the point that is at the top of the stack. If it is, we have a square frame. When we have a frame, we move to the third step, where we check if the frame is filled in. To do that we just want to check if area within that square that is filled in by rectangles is equal to the area of the square. For every corner of every rectangle we will compute the area covered by rectangles which are fully located to the left and top from that point. To do that we can sort all the corners by $x$, and then by $y$, and process them one by one. We will maintain an interval tree where value at every position $y$ represents area covered by rectangles processed so far that are fully above $y$. Then when we process a corner, we first update the interval tree if the corner is a bottom right corner, and then query the interval tree to see the area covered by rectangles to the up and left from the current corner. Then, when we have these number precomputed, for every square frame $x1$, $y1$, $x2$, $y2$ we can just get the area for ($x2$, $y2$), add area for ($x1$, $y1$) and subtract for ($x2$, $y1$) and for ($x1$, $y2$). A possible $O(k^{2})$ solution is similar, but makes checking whether or not the frame is filled much and a bunch of other checks easier.",
    "code": "#include <stdio.h>\n#include <assert.h>\n#include <map>\n#include <vector>\n#include <algorithm>\n \nusing namespace std;\n \nconst int maxn = 100005;\n \nconst int maxt = 131072 * 2;\nconst int rright = 131072;\n \nstruct square_t;\nint n;\n \nstruct point_t\n{\n    point_t(int _x, int _y) : x(_x), y(_y), r(-1), l(-1), t(-1), b(-1) { \n        for (int i = 0; i < 4; ++ i) sq[i] = NULL;\n    };\n    int x, y;\n    int r, l, t, b, area;\n    square_t* sq[4];\n \n    void updateRightBottom();\n    void updateLeftTop();\n    bool operator < (const point_t& other) const \n    {\n        if (x - y != other.x - other.y) return x - y < other.x - other.y;\n        return x < other.x;\n    }\n \n    bool sameDiag(const point_t& other) const\n    {\n        return other.x - other.y == x - y;\n    }\n};\n \npoint_t* allPoints[maxn * 4]; int numPoints = 0;\nmap<pair<int, int>, point_t*> pointsMap;\nsquare_t* squares[maxn], *sortedSquares[maxn];\n \n \npoint_t* getPoint(int x, int y, square_t* sq, int ord)\n{\n    if (pointsMap.find(make_pair(x, y)) == pointsMap.end())\n    {\n        allPoints[numPoints] = new point_t(x, y);\n        pointsMap.insert(make_pair(make_pair(x, y), allPoints[numPoints]));\n        ++ numPoints;\n    }\n \n    point_t* p = pointsMap[make_pair(x, y)];\n    assert(p->sq[ord] == NULL || p->sq[ord] == sq);\n    p->sq[ord] = sq;\n    return p;\n}\n \nstruct square_t\n{\n    square_t(int _x1, int _y1, int _x2, int _y2) \n        : x1(_x1), x2(_x2), y1(_y1), y2(_y2)\n    { \n        assert(x1 < x2);\n        assert(y1 < y2);\n \n        p[0] = getPoint(x1, y1, this, 0);\n        p[1] = getPoint(x2, y1, this, 1);\n        p[2] = getPoint(x1, y2, this, 2);\n        p[3] = getPoint(x2, y2, this, 3);\n \n        for (int i = 0; i < 4; ++ i)\n        {\n            assert(p[i]->sq[i] == this);\n        }\n    }\n \n    int area() { return (x2 - x1) * (y2 - y1); }\n \n    point_t* p[4]; // UL, UR, BL, BR\n    int x1, y1, x2, y2;\n};\n \nbool cmpPoints(const point_t* a, const point_t* b)\n{\n    return *a < *b;\n}\n \nbool cmpForArea(const point_t* a, const point_t* b)\n{\n    if (a->x != b->x) return a->x < b->x;\n    return a->y < b->y;\n}\n \nint area(int x, int y)\n{\n    assert(pointsMap.find(make_pair(x, y)) != pointsMap.end());\n    return pointsMap[make_pair(x, y)]->area;\n}\n \nint t[maxt];\n \nvoid addt(int pos, int moo) {\n    pos += rright;\n    while (pos >= 1) {\n        t[pos] += moo;\n        pos /= 2;\n    }\n}\n \nint gett(int pos) {\n    pos += rright;\n    int ret = 0;\n    while (pos >= 1) {\n        if (pos % 2 == 0) {\n            ret += t[pos];\n            -- pos;\n        }\n        pos /= 2;\n    }\n    return ret;\n}\n \nvoid point_t::updateLeftTop()\n{\n    if (l != -1) return;\n    if (sq[3] == NULL)\n    {\n        l = t = 0;\n    }\n    else\n    {\n        pointsMap[make_pair(sq[3]->x2, sq[3]->y1)]->updateLeftTop();\n        pointsMap[make_pair(sq[3]->x1, sq[3]->y2)]->updateLeftTop();\n \n        l = sq[3]->x2 - sq[3]->x1 + pointsMap[make_pair(sq[3]->x1, sq[3]->y2)]->l;\n        t = sq[3]->y2 - sq[3]->y1 + pointsMap[make_pair(sq[3]->x2, sq[3]->y1)]->t;\n    }\n}\n \nvoid point_t::updateRightBottom()\n{\n    if (r != -1) return;\n    if (sq[0] == NULL)\n    {\n        r = b = 0;\n    }\n    else\n    {\n        pointsMap[make_pair(sq[0]->x2, sq[0]->y1)]->updateRightBottom();\n        pointsMap[make_pair(sq[0]->x1, sq[0]->y2)]->updateRightBottom();\n \n        r = sq[0]->x2 - sq[0]->x1 + pointsMap[make_pair(sq[0]->x2, sq[0]->y1)]->r;\n        b = sq[0]->y2 - sq[0]->y1 + pointsMap[make_pair(sq[0]->x1, sq[0]->y2)]->b;\n    }\n}\n \nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++ i)\n    {\n        int x1, y1, x2, y2;\n        scanf(\"%d %d %d %d\", &x1, &y1, &x2, &y2);\n \n        assert(x1 < x2);\n        assert(y1 < y2);\n        squares[i] = sortedSquares[i] = new square_t(x1, y1, x2, y2);\n    }\n \n    for (int i = 0; i < n; ++ i) {\n        squares[i]->p[0]->updateRightBottom();\n        squares[i]->p[3]->updateLeftTop();\n    }\n \n    sort(allPoints, allPoints + numPoints, cmpForArea);\n \n    for (int i = 0; i < numPoints; ++ i)\n    {\n        point_t* pt = allPoints[i];\n        if (pt->sq[3])\n        {\n            addt(pt->y, pt->sq[3]->area());\n        }\n        pt->area = gett(pt->y);\n    }\n \n    sort(allPoints, allPoints + numPoints, cmpPoints);\n \n    int fs = 0;\n    while (fs < numPoints)\n    {\n        int ls = fs;\n        while (ls < numPoints && allPoints[ls]->sameDiag(*allPoints[fs])) ++ ls;\n \n        vector<pair<int, int> > st;\n \n        for (int i = fs; i < ls; ++ i)\n        {\n            while (st.size() && st.back().second + st.back().first < allPoints[i]->x)\n            {\n                st.pop_back();\n            }\n            int l = min(allPoints[i]->l, allPoints[i]->t);\n            int r = min(allPoints[i]->r, allPoints[i]->b);\n \n            if (st.size() && allPoints[i]->x - l <= st.back().first)\n            {\n                int x1 = st.back().first, y1 = st.back().first - allPoints[i]->x + allPoints[i]->y, x2 = allPoints[i]->x, y2 = allPoints[i]->y;\n                if (area(x2, y2) - area(x1, y2) - area(x2, y1) + area(x1, y1) == (x2 - x1) * (y2 - y1))\n                {\n                    vector<int> ans;\n                    for (int i = 0; i < n; ++ i)\n                    {\n                        if (squares[i]->x1 >= x1 && squares[i]->x1 < x2)\n                        if (squares[i]->y1 >= y1 && squares[i]->y1 < y2)\n                            ans.push_back(i);\n                    }\n                    printf(\"YES %d\\n\", (int)ans.size());\n                    for (int i = 0; i < ans.size(); ++ i)\n                        printf(\"%d%c\", ans[i]+1, \" \\n\"[i == ans.size() - 1]);\n                    return 0;\n                }\n \n                st.pop_back();\n            }\n \n            st.push_back(make_pair(allPoints[i]->x, r));\n        }\n \n        fs = ls;\n    }\n \n    printf(\"NO\\n\");\n \n    return 0;\n}",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "335",
    "index": "E",
    "title": "Counting Skyscrapers",
    "statement": "A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between $2$ and $314!$ (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height $i$ having probability $2^{ - i}$ for all positive integers $i$. The floors of a skyscraper with height $i$ are numbered $0$ through $i - 1$.\n\nTo speed up transit times, a number of zip lines were installed between skyscrapers. Specifically, there is a zip line connecting the $i$-th floor of one skyscraper with the $i$-th floor of another skyscraper if and only if there are no skyscrapers between them that have an $i$-th floor.\n\nAlice and Bob decide to count the number of skyscrapers.\n\nAlice is thorough, and wants to know exactly how many skyscrapers there are. She begins at the leftmost skyscraper, with a counter at 1. She then moves to the right, one skyscraper at a time, adding 1 to her counter each time she moves. She continues until she reaches the rightmost skyscraper.\n\nBob is impatient, and wants to finish as fast as possible. He begins at the leftmost skyscraper, with a counter at 1. He moves from building to building using zip lines. At each stage Bob uses the highest available zip line to the right, but ignores floors with a height greater than $h$ due to fear of heights. When Bob uses a zip line, he travels too fast to count how many skyscrapers he passed. Instead, he just adds $2^{i}$ to his counter, where $i$ is the number of the floor he's currently on. He continues until he reaches the rightmost skyscraper.\n\nConsider the following example. There are $6$ buildings, with heights $1$, $4$, $3$, $4$, $1$, $2$ from left to right, and $h = 2$. Alice begins with her counter at $1$ and then adds $1$ five times for a result of $6$. Bob begins with his counter at $1$, then he adds $1$, $4$, $4$, and $2$, in order, for a result of $12$. Note that Bob ignores the highest zip line because of his fear of heights ($h = 2$).\n\nBob's counter is at the top of the image, and Alice's counter at the bottom. All zip lines are shown. Bob's path is shown by the green dashed line and Alice's by the pink dashed line. The floors of the skyscrapers are numbered, and the zip lines Bob uses are marked with the amount he adds to his counter.\n\nWhen Alice and Bob reach the right-most skyscraper, they compare counters. You will be given either the value of Alice's counter or the value of Bob's counter, and must compute the expected value of the other's counter.",
    "tutorial": "The skyscrapers in this problem depict a data structure called Skip List. Skip list is similar to AVL and red black trees in a sense that it allows O(log N) insertions, deletions and searches (including searching for lower and upper bounds), as well as moving to the next element in sorted order in constant time. Skiplist is different from any tree structures because it has a practical thread safe implementation without locks (so-called lock-free). Lock free skiplists are used as a main data structure to store data in MemSQL, and the algorithm that Bob uses to traverse the skyscrapers is an O(log N) approach, that allows one to estimate the size of the skiplist. Thus, if Bob ended up with an estimation of $n$, the actual skiplist size is expected to be $n$ (so if the first line of the input file is Bob, one just needs to print the number from the second line to the output). Formal proof is rather simple, and is left to the reader. Curiously, the converse does not hold. If the skiplist size is $n$, the expected return value of the estimation algorithm could be bigger than $n$. For an $n$ that is significantly bigger than $2^{h}$ the estimate converges to $n - 1 + 2^{h}$, but this problem included cases with smaller $n$ as well. Let us build up the solution one level at a time. When $H$ is 0, the expected sum is $N$. Now for each additional level, we can add the expected cost of the zip lines on that level, and subtract the expected cost of the zip lines immediately below them. In the end we'll have the total expected cost. For some floor number $H$, let's consider some left and right tower, and determine the probability that a zip line exists between them. Let $L$ be the distance between the two towers. A potential zip line of length $L$ and height $H$ exists if the towers at both ends are tall enough (probability $1 / 2^{H}$ for each one), and the $L - 1$ towers between them are all shorter (probability $1 - 1 / 2^{H}$ for each). Thus the probability that such a zip line exists is $1 / 2^{2 * H}  \\times  (1 - 1 / 2^{H})^{L - 1}$. Now, assuming that such a zip line exists, what's the expected number of zip lines immediately below it? This is simply one more than the number of towers of height $H - 1$. Each of the $L - 1$ towers has probability $1 / (2^{H} - 1)$ of having height H-1 (given that it has height at most H-1) -- use conditional probability ($P(A|B)={\\frac{P(A^{\\prime})b^{\\prime}}{P(B)}}$) to calculate this. Thus the expected number of zip lines immediately below a zip line of length $L$ and height $H$ is $1 + (L - 1) / (2^{H} - 1)$. For each length $L$, there are $N - L$ possible zip lines with this length on each level. We multiply probability by cost for all possible zip lines to attain the expected value. The final answer is therefore $N+\\textstyle\\sum_{i=1}^{H}\\sum_{j=1}^{N}(N-j)\\times{\\textstyle\\frac{1}{2^{2\\times t}}}\\times(1-{\\textstyle\\frac{1}{2^{2}}})^{j-1}\\times(2^{i}-2^{i-1}\\times(1+{\\textstyle\\frac{j-1}{2^{2-1}}}))$ It turns out the inner loop can be computed using matrix multiplication, for a running time of O(H log N). -- although the constraints is low enough that using matrix multiplication is an overkill -- O(H * N) will do.",
    "code": "#include <cstdio>\nusing namespace std;\n \nint main()\n{\n    char name[9];\n    int N, H;\n    while(scanf(\"%s %d %d\", name, &N, &H)!=EOF)\n    {\n        if(name[0]=='B'){\n            printf(\"%d\\n\", N);\n            continue;\n        }\n        double res=N;\n        double ph=.5, pc=.5;\n        for(int h=1; h<=H; h++){\n            double pn=.5;\n            for(int w=0; w<N-1; w++){\n                res+=(N-1-w)*ph*pn*(1-w*ph/pc);\n                pn*=1-ph;\n            }\n            ph/=2;\n            pc+=ph;\n        }\n        printf(\"%.9f\\n\", res);\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "335",
    "index": "F",
    "title": "Buy One, Get One Free",
    "statement": "A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.",
    "tutorial": "This problem is equivalent to maximizing the total value of items that we can get for free. First, process the items into <#value, #number_of_items_with_that_value> tuples, which means we have #number_of_items_with_that_value items of value #value. Then, sort the tuples in descending order of #value. Iterate over those tuples and let #pieguy be an empty multi set() For each tuple <#val, #num>, we can calculate #max_free, the maximum number of items (not value) that we can get for free up to this point easily. So, we want to populate #pieguy so that it contains exactly #max_free \"things\". #pieguy is special, in that we can compute the maximum price that we can get for free for n items by summing up the n most expensive items in #pieguy. How could #pieguy do that? For now, you may assume that each element of #pieguy contains the value of a single item that can be gotten for free. Thus, summing n items = value of n items that can be gotten for free. This is not correct, of course, since not all n arbitrary items can be simultaneously gotten for free in tandem, but we'll come back to it later. We're now at <#val, #num>, and we have #pieguy from previous iteration. #pieguy contains the previous #max_free elements. Assume that #num <= number of items more expensive than this value, for otherwise the remainder are 'dead' and useless for our current purpose. In particular, for the first tuple we process, we assume that #num is 0, since all of them cannot be gotten for free. Suppose we want to obtain exactly #max_free items. How many of the #num must we use? Let's arrange the current members of #pieguy in descending order. For example, if #pieguy has 5 members: A B C D ELet's arrange #num #val under #pieguy so that the rightmost one is located on position #max_free. For example, if #num is 6 and #max_free is 8 and #val is V.... A B C D E V V V V V VThese 6 Vs will be competing for a spot in #pieguy. Now... 1) what happens if C < V? This means, instead of making C free, we can make V free instead! (if you're wondering why this is possible, remember that #pieguy definition I gave you was not entirely honest yet). So, we replace C, D and E with all Vs, and we get our new #pieguy! A B V V V V V V (this should be sorted again, but C++'s multiset does that automagically). 2) otherwise, C > V. So, V cannot contend for the 3-th place in #pieguy, it has to contend for a place larger than or equal to the 4-th. Now the fun begins! If you want to contend for the 4-th place, any solution MUST HAVE AT LEAST 2 V s (remember that the 4-th place is used in a solution consisting of at least 4 free items). In general, if you want to contend for the #max_free - i -th place, you MUST HAVE AT LEAST #num - i Vs. #proof? is easy, exercise (i'm honest!) Okay, so back to contending for the 4-th place. If D is still > V, we proceed. Otherwise, we know that D < V. This means, E and any element after E is also < V! Thus, we can replace all elements after or equal to E with V! The problem would be the final element of #pieguy. When the final element of #pieguy is included in the sum, it is only included in the sum of all n elements of #pieguy. You do this when you want to calculate the maximum sum of values of free items you can get when getting exactly #max_free items. Any such solution must include all #num elements with value #val. We have included #num-2 Vs in #pieguy. Thus, the final element of #pieguy must somehow contains 2 Vs! So, elements of #pieguy actually can do this. Instead of containing a single elmeent, each element of #pieguy is more of an \"operation\" that adds several value and removes several value. In our case, we want to add 2 Vs and remove something. The something? The smallest element that we can remove (the ones that we haven't removed)! C! (if you're wondering why not D or E, it's because (again) #pieguy is special -- it only forms a solution if the most expensive t are summed, not if some are skipped. -- we cannot skip C if we want to use D). So, Insert 2V - C into #pieguy, and the rest, insert V into #pieguy. 2V - C is < V, so summing all elements of #pieguy correctly found out the max value when we receive #max_free free items! Right! Cool! ...except that 2V - C can be negative. Why would we want to insert negative stuffs into #pieguy? We don't! Actually, we check if 2V - C is negative. If it is, we continue instead, and check 3V - C - D and so on, under the same reason. That's it folks! I skipped some details of why this works (for example, that the number of V selected is always sufficient to guarantee solution in #pieguy), but they're easier to see once you get this large idea. The result is then #pieguy.last_element",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <map>\n#include <set>\n#include <vector>\n#include <numeric>\nusing namespace std;\n \nint main()\n{\n    int N;\n    scanf(\"%d\", &N);\n \n    long long basecost=0;\n    map<int, int> vals;\n    for(int i=0; i<N; i++){\n        int val;\n        scanf(\"%d\", &val);\n        vals[val]++;\n        basecost+=val;\n    }\n    multiset<int> freed;\n    int total=0;\n    for(map<int, int>::reverse_iterator it=vals.rbegin(); it!=vals.rend(); it++){\n        int val=it->first;\n        int count=it->second;\n        int maxadd=min(count, total);\n        int nextsize=min(min((int)freed.size()+count, total), (total+count)/2);\n        int remove=maxadd-(nextsize-freed.size());\n        \n        multiset<int>::iterator pos=freed.begin();\n        for(int i=0; i<remove; i++)\n            pos++;\n        vector<int> removed(freed.begin(), pos);\n        reverse(removed.begin(), removed.end());\n        freed.erase(freed.begin(), pos);\n        \n        int toadd=nextsize-freed.size();\n        vector<int> add(toadd, val);\n        if((total+maxadd)&1){\n            add.push_back(0);\n            toadd++;\n        }\n        for(int i=0; i<remove; i++)\n            if(removed[i]>add[i]){\n                add[i]=removed[i];\n                add[toadd-i-1]-=removed[i]-val;\n            }\n        while(add.size() && add.back()<=0)\n            add.pop_back();\n        freed.insert(add.begin(), add.end());\n        total+=count;\n    }\n    printf(\"%I64d\\n\", basecost-accumulate(freed.begin(), freed.end(), 0ll));\n}\n ",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "336",
    "index": "A",
    "title": "Vasily the Bear and Triangle",
    "statement": "Vasily the bear has a favorite rectangle, it has one vertex at point $(0, 0)$, and the opposite vertex at point $(x, y)$. Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes.\n\nVasya also loves triangles, if the triangles have one vertex at point $B = (0, 0)$. That's why today he asks you to find two points $A = (x_{1}, y_{1})$ and $C = (x_{2}, y_{2})$, such that the following conditions hold:\n\n- the coordinates of points: $x_{1}$, $x_{2}$, $y_{1}$, $y_{2}$ are integers. Besides, the following inequation holds: $x_{1} < x_{2}$;\n- the triangle formed by point $A$, $B$ and $C$ is rectangular and isosceles ($\\angle A B C$ is right);\n- all points of the favorite rectangle are located inside or on the border of triangle $ABC$;\n- the area of triangle $ABC$ is as small as possible.\n\nHelp the bear, find the required points. It is not so hard to proof that these points are unique.",
    "tutorial": "$val = |x| + |y|$. Then first point is $(val * sign(x), 0)$, second - $(0, val * sign(y))$. Swap points if needed according to statement. Let's see why this is the answer. Conditions $x  \\neq  0$ and $y  \\neq  0$ give us that one point is on X-axis, and the other on Y-axis. Let's see how it works for $x > 0$ and $y > 0$. Other cases can be proved in similar way. We need to show, that $(x, y)$ belongs to our triangle(including it's borders). In fact $(x, y)$ belongs to segment, connecting $(x + y, 0)$ with $(0, x + y)$. Line through $(x + y, 0)$ and $(0, x + y)$ is $Y = - X + x + y$. Using coordinates $(x, y)$ in this equation proves the statement.",
    "code": "#include <cstdio>\n#include <utility>\n#include <cmath>\n\nusing namespace std;\n\nint sgn(int x) {\n\tif (x > 0) return 1;\n\tif (x == 0) return 0;\n\treturn -1;\n}\n\nint main() {\n\tint x, y;\n\tscanf(\"%d %d\", &x, &y);\n\tint v = abs(x) + abs(y);\n\tpair<int,int> f = make_pair(v * sgn(x), 0);\n\tpair<int,int> s = make_pair(0, v * sgn(y));\n\tif (f.first > s.first)\n\t\tswap(f, s);\n\tprintf(\"%d %d %d %d\\n\", f.first, f.second, s.first, s.second);\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "336",
    "index": "B",
    "title": "Vasily the Bear and Fly",
    "statement": "One beautiful day Vasily the bear painted $2m$ circles of the same radius $R$ on a coordinate plane. Circles with numbers from $1$ to $m$ had centers at points $(2R - R, 0)$, $(4R - R, 0)$, $...$, $(2Rm - R, 0)$, respectively. Circles with numbers from $m + 1$ to $2m$ had centers at points $(2R - R, 2R)$, $(4R - R, 2R)$, $...$, $(2Rm - R, 2R)$, respectively.\n\nNaturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for $m^{2}$ days. Each day of the experiment got its own unique number from $0$ to $m^{2} - 1$, inclusive.\n\nOn the day number $i$ the following things happened:\n\n- The fly arrived at the coordinate plane at the center of the circle with number $v=\\lfloor{\\frac{b}{m}}\\rfloor+1$ ($\\left\\lfloor{\\frac{x}{y}}\\right\\rfloor$ is the result of dividing number $x$ by number $y$, rounded down to an integer).\n- The fly went along the coordinate plane to the center of the circle number $u=m+1+(i\\mod m)$ ($x\\ {\\mathrm{mod}}\\ y$ is the remainder after dividing number $x$ by number $y$). The bear noticed that the fly went from the center of circle $v$ to the center of circle $u$ along the shortest path with all points lying on the border or inside at least one of the $2m$ circles. After the fly reached the center of circle $u$, it flew away in an unknown direction.\n\nHelp Vasily, count the average distance the fly went along the coordinate plane during each of these $m^{2}$ days.",
    "tutorial": "Also you could iterate circles, adding distance for each of them and dividing by $m^{2}$ in the end. Let's see how the $i$-th iteration works $1  \\le  i  \\le  m$. Distance to $m + i$-th circle is $2R$. Distance to $m + j$-th circle, where $|j - i| = 1$, is $R(2+{\\sqrt{2}})$. For other circles it's quite simple to calculate sum of distances. There are $i - 2$ circles which located to the left of current circle. So, sum of distances for these circles is $R(i-2)(i-1)+2R{\\sqrt{2}}(i-2)$. In the same manner we can calculate answer for cirlcles which are located to the right of the current circle",
    "code": "#include <iostream>\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <cstdio>\n\nusing namespace std;\n\nint main() {\n  int m, r;\n  scanf(\"%d%d\", &m, &r);\n\n  double result = 0;\n  for (int i = 0; i < m; ++i) {\n    result += 2;\n    if (i > 0) result += (2 + sqrt(2.));\n    if (i + 1 < m) result += (2 + sqrt(2.));\n\n    if (i > 0) {\n      double v = i - 1;\n      result += v * (v + 1);\n      result += 2. * sqrt(2.) * v;\n    }\n    if (i + 1 < m) {\n      double v = m - 2 - i;\n      result += v * (v + 1);\n      result += 2. * sqrt(2.) * v;\n    }\n  }\n\n  printf(\"%.10lf\\n\", result * r / m / m);\n\n  return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "336",
    "index": "C",
    "title": "Vasily the Bear and Sequence",
    "statement": "Vasily the bear has got a sequence of positive integers $a_{1}, a_{2}, ..., a_{n}$. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum.\n\nThe beauty of the written out numbers $b_{1}, b_{2}, ..., b_{k}$ is such maximum non-negative integer $v$, that number $b_{1}$ $and$ $b_{2}$ $and$ $...$ $and$ $b_{k}$ is divisible by number $2^{v}$ without a remainder. If such number $v$ doesn't exist (that is, for any non-negative integer $v$, number $b_{1}$ $and$ $b_{2}$ $and$ $...$ $and$ $b_{k}$ is divisible by $2^{v}$ without a remainder), the beauty of the written out numbers equals -1.\n\nTell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.\n\nHere expression $x$ $and$ $y$ means applying the bitwise AND operation to numbers $x$ and $y$. In programming languages C++ and Java this operation is represented by \"&\", in Pascal — by \"and\".",
    "tutorial": "Let's check max beauty from 29 to 0. For every possible beauty $i$ our aim is to find largest subset with such beauty. We will include in this subset all numbers, that have $1$ at $i$-th bit. After that we do bitwise $and$ as in statement, and if the resulting value is divisible by $2^{i}$, then there is the answer. Solution works in $O(n)$.",
    "code": "#include <cstdio>\n#include <vector>\n#include <cassert>\n\nusing namespace std;\n\nvector < int > a, cur, ans;\nint n, curb, bestb;\n\nint main(){\n\tscanf(\"%d\", &n); a.resize(n);\n\tfor(int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\n\tfor(int bit = 0; bit < 31; bit++) {\n\t\tint totalAnd = (1<<30) - 1;\n\t\tcur.clear();\n\t\tfor(int i = 0; i < n; i++) {\n\t\t\tif ((a[i] & (1<<bit))) cur.push_back(a[i]), totalAnd &= a[i]; \n\t\t}\n\t\tif ((totalAnd % (1<<bit)) == 0) ans = cur; \n\t}\n\tprintf(\"%d\\n\", ans.size());\n\tfor(int i = 0; i < ans.size(); i++) \n\t\tprintf(\"%d%c\", ans[i], \" \\n\"[i == (ans.size() - 1)]);\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "336",
    "index": "D",
    "title": "Vasily the Bear and Beautiful Strings",
    "statement": "Vasily the Bear loves beautiful strings. String $s$ is beautiful if it meets the following criteria:\n\n- String $s$ only consists of characters $0$ and $1$, at that character $0$ must occur in string $s$ exactly $n$ times, and character $1$ must occur exactly $m$ times.\n- We can obtain character $g$ from string $s$ with some (possibly, zero) number of modifications. The character $g$ equals either zero or one.\n\nA modification of string with length at least two is the following operation: we replace two last characters from the string by exactly one other character. This character equals one if it replaces two zeros, otherwise it equals zero. For example, one modification transforms string \"01010\" into string \"0100\", two modifications transform it to \"011\". It is forbidden to modify a string with length less than two.\n\nHelp the Bear, count the number of beautiful strings. As the number of beautiful strings can be rather large, print the remainder after dividing the number by $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "$any$ - random binary string, $s + g$ - concatenation of strings, $MOD = 1000000007$. String $1 + any$ always transforms into $0$, string $1$ - into $1$. String $01 + any$ always transforms into $1$, string $01$ - into $0$. String $001 + any$ transforms into $0$, string $001$ - into $1$, and so on. Using these facts let's consider following solution. Cases like strings without ones or zeroes are easy. For every $i$ (in zero-based numbering) let's assume that it is position of the first occurence of $1$ in our string. Using already known facts we can understand what is the final result of transformations for such string. If the result equals to $g$, we add $C(cnt[0] + cnt[1] - i - 1, cnt[1] - 1)$ to the answer. Calculation of binomial coefficients is following: $fact[i] = i!%MOD$, $\\forall i\\leq200000$, $C(n, k) = fact[n]inv(fact[n - i]fact[i])$, where $inv(a)$ - inverse element modulo $MOD$. $inv(a) = a^{MOD - 2}$, because $MOD$ is prime number.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int N = 2000000, mod = 1000000007;\n\nint cnt[2], target;\nlong long fact[N];\n\n#define forn(i,n) for(int i = 0; i < (int) n; i++)\n#define sz(a) (int)(a).size()\n\ninline bool read() {\n\treturn (cin >> cnt[0] >> cnt[1] >> target);\n}\n\ninline long long bpow(long long v, int power) {\n\tif (power == 0) return 1;\n\tif ((power & 1) == 0) {\n\t\tlong long r = bpow(v, power >> 1);\n\t\treturn (r * r) % mod;\n\t}\n\treturn (bpow(v, power - 1) * v) % mod;\n}\n\ninline int getC(int n, int k) {\n\tlong long nom = fact[n];\n\tlong long den = (fact[n-k] * fact[k]) % mod;\n\treturn (nom * bpow(den, mod - 2)) % mod;\n}\n\nint calculate() {\n\tif (cnt[1] == 0) {\n\t\tif (cnt[0] % 2 != target) \n\t\t\treturn 1;\n\t\telse\n\t\t\treturn 0;\n\t}\n\tif (cnt[0] == 0) {\n\t\tif (cnt[1] > 1) {\n\t\t\tif (target == 0) \n\t\t\t\treturn 1;\n\t\t\telse \n\t\t\t\treturn 0;\n\t\t} else {\n\t\t\tif (target == 1)\n\t\t\t\treturn 1;\n\t\t\telse \n\t\t\t\treturn 0;\n\t\t}\n\t}\n\tint answer = 0;\n\tfor(int i = 0; i <= cnt[0]; i++) {\n\t\tint total = cnt[0] + cnt[1] - 1 - i;\n\t\tif (total > 0) {\n\t\t\tif (i % 2 == target) {\n\t\t\t\tanswer += getC(total, cnt[1] - 1);\n\t\t\t\tif (answer >= mod) answer -= mod;\n\t\t\t}\n\t\t} else {\n\t\t\tif (i % 2 != target) {\n\t\t\t\tanswer += getC(total, cnt[1] - 1);\n\t\t\t\tif (answer >= mod) answer -= mod;\n\t\t\t}\n\t\t}\n\t}\n\treturn answer;\n}\n\ninline void solve() {\n\tfact[0] = 1;\n\tforn(i, N) {\n\t\tif (!i) continue;\n\t\tfact[i] = (fact[i-1] * i) % mod;\n\t}\n\tcout << calculate() << endl;\n}\nint main() {\n\twhile (read()) \n\t\tsolve();\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "336",
    "index": "E",
    "title": "Vasily the Bear and Painting Square",
    "statement": "Vasily the bear has two favorite integers $n$ and $k$ and a pencil. Besides, he's got $k$ jars with different water color paints. All jars are numbered in some manner from $1$ to $k$, inclusive. The jar number $i$ contains the paint of the $i$-th color.\n\nInitially the bear took a pencil and drew four segments on the coordinate plane. All of them end at point $(0, 0)$. They begin at: $(0, 2^{n})$, $(0, - 2^{n})$, $(2^{n}, 0)$, $( - 2^{n}, 0)$. Then for each $i = 1, 2, ..., n$, the bear drew two squares. The first square has the following vertex coordinates: $(2^{i}, 0)$, $( - 2^{i}, 0)$, $(0, - 2^{i})$, $(0, 2^{i})$. The second square has the following vertex coordinates: $( - 2^{i - 1}, - 2^{i - 1})$, $( - 2^{i - 1}, 2^{i - 1})$, $(2^{i - 1}, - 2^{i - 1})$, $(2^{i - 1}, 2^{i - 1})$. After that, the bear drew another square: $(1, 0)$, $( - 1, 0)$, $(0, - 1)$, $(0, 1)$. All points mentioned above form the set of points $A$.\n\n{\\scriptsize The sample of the final picture at $n = 0$}\n\n{\\scriptsize The sample of the final picture at $n = 2$}\n\nThe bear decided to paint the resulting picture in $k$ moves. The $i$-th move consists of the following stages:\n\n- The bear chooses 3 distinct points in set $А$ so that any pair of the chosen points has a segment on the picture between them. The chosen points and segments mark the area that mustn't contain any previously painted points.\n- The bear paints the area bounded by the chosen points and segments the $i$-th color.\n\nNote that after the $k$-th move some parts of the picture can stay unpainted.\n\nThe bear asked you to calculate, how many distinct ways there are to paint his picture. A way to paint the picture is a sequence of three-element sets of points he chose on each step. Two sequences are considered distinct if there is such number $i$ ($1 ≤ i ≤ k)$, that the $i$-th members of these sequences do not coincide as sets. As the sought number can be rather large, you only need to calculate the remainder after dividing it by number $1000000007$ ($10^{9} + 7$).",
    "tutorial": "Pretty tough problem. Consider following DP $dp[lvl][op][cur][type]$ - number of ways to take $op$ triangles, if we have $2lvl + 1$ squares. $cur, type$ - auxiliary values. Answer will be $dp[n][k][0][2]k!$. $type$ means type of transitions we make. $cur$ - amount of used quarters ($cur = 4$ - 2 quarters, $cur < 4$ - $cur$ quarters). It is important to distinguish $cur = 2$ from $cur = 4$, because amount of consecutive pairs of unused quarters is different. About transitions. $type = 2.$ Iterate amount of pairs (considering $cur$) of consecutive quarters that we will take. It is important for them to have no common quarters. We can get two pairs only in case $cur = 0$. Let's also take some quarters that are not in pairs. Calculate number of ways to select corresponding triangles and add to the current DP-state value $dp[lvl][op - choosen][newcur][1] * cntwaystochoose$. For better understanding of $type = 2$ check my solution ($calc(n, k, cur, type) - isfordp[n][k][cur][type]$). $type = 1$. Now we take triangles at the borders (number of squares is 2*lvl + 1). \"at the borders\" means marked X, see the picture. Iterate amount of pairs (considering $cur$) of consecutive triangles we take. It is important for pairs to have no common triangles. Let's also take some triangles that are not in pairs. Calculate number of ways to select corresponding triangles and add to the current DP-state value $dp[lvl][op - choosen][cur][0] * cntwaystochoose$. $type = 0$. We take triangles at the borders (number of squares is 2*lvl). \"at the borders\" means marked X, see the picture. Take some triangles, not in pairs. Calculate number of ways to select corresponding triangles and add to current DP-state value $dp[lvl - 1][op - choosen][cur][2] * cntwaystochoose$. Starting values: $dp[0][0][cur][1] = 1$, $dp[0][cnt][cur][1] = 0$, $cnt > 0$.",
    "code": "#include <stdio.h>\n#include <memory.h>\n\nconst int MOD = 1000000007, N = 205, K = 10;\nint dp[N][N][5][3], C[K][K], con[5], get[5], fact = 1, n, k;\n\ninline void add(int &v1, int v2) {\n\tv1 += v2;\n\tif (v1 >= MOD) \n\t\tv1 -= MOD;\n}\n\ninline int mul(int v1, int v2) {\n\tlong long res = v1;\n\tres *= v2;\n\treturn (res % MOD);\n}\n\nint calc(int level, int operations, int cur, int type) {\n\tint &ans = dp[level][operations][cur][type];\n\tif (ans != -1) \n\t\treturn ans;\n\tans = 0;\n\tif (type == 0) {\n\t\tint bits = get[cur];\n\t\tfor(int i = 0; (i <= bits) && (i <= operations); i++)\n\t\t\tadd(ans, mul(calc(level - 1, operations - i, cur, 2), C[bits][i]));\n\t}\n\tif (type == 1) {\n\t\tif (level == 0) {\n\t\t\tif (operations == 0)\n\t\t\t\treturn ans = 1;\n\t\t\telse \n\t\t\t\treturn ans = 0;\n\t\t}\n\t\tint bits = get[cur];\n\t\tbits <<= 1;\n\t\tint cons = con[cur];\n\t\tfor(int i = 0; (i <= cons) && (i <= operations); i++)\n\t\t\tfor(int j = 0; (j <= (bits - 2 * i)) && (j <= (operations - i)); j++) \n\t\t\t\tadd(ans, mul(calc(level, operations - i - j, cur, 0), mul(C[cons][i], C[bits - 2 * i][j])));\n\t}\n\tif (type == 2) {\n\t\tadd(ans, calc(level, operations, cur, 1));\n\t\tif (cur == 0) {\n\t\t\tif (operations >= 1) {\n\t\t\t\tadd(ans, mul(calc(level, operations - 1, 1, 1), 4));\n\t\t\t\tadd(ans, mul(calc(level, operations - 1, 2, 1), 4));\n\t\t\t}\n\t\t\tif (operations >= 2) {\n\t\t\t\tadd(ans, mul(calc(level, operations - 2, 4, 1), 2));\n\t\t\t\tadd(ans, mul(calc(level, operations - 2, 2, 1), 4));\n\t\t\t\tadd(ans, mul(calc(level, operations - 2, 3, 1), 8));\n\t\t\t\tif (operations == 2) \n\t\t\t\t\tadd(ans, 2);\n\t\t\t}\n\t\t\tif (operations >= 3) {\n\t\t\t\tadd(ans, mul(calc(level, operations - 3, 3, 1), 4));\n\t\t\t\tif (operations == 3) \n\t\t\t\t\tadd(ans, 4);\n\t\t\t}\n\t\t\tif (operations == 4)\n\t\t\t\tadd(ans, 1);\n\t\t}\n\t\tif (cur == 1) {\n\t\t\tif (operations >= 1) {\n\t\t\t\tadd(ans, calc(level, operations - 1, 4, 1));\n\t\t\t\tadd(ans, mul(calc(level, operations - 1, 2, 1),2));\n\t\t\t\tadd(ans, mul(calc(level, operations - 1, 3, 1),2));\n\t\t\t}\n\t\t\tif (operations >= 2) {\n\t\t\t\tif (operations == 2) \n\t\t\t\t\tadd(ans, 2);\n\t\t\t\tadd(ans, mul(calc(level, operations - 2, 3, 1), 3));\n\t\t\t}\n\t\t\tif (operations == 3)\n\t\t\t\tadd(ans, 1);\n\t\t}\n\t\tif (cur == 2) {\n\t\t\tif (operations >= 1) {\n\t\t\t\tadd(ans, mul(calc(level, operations - 1, 3, 1), 2));\n\t\t\t\tif (operations == 1) \n\t\t\t\t\tadd(ans, 1);\n\t\t\t}\n\t\t\tif (operations == 2) \n\t\t\t\tadd(ans, 1);\n\t\t}\n\t\tif (cur == 3 && operations == 1)\n\t\t\tadd(ans, 1);\n\t\tif (cur == 4) {\n\t\t\tif (operations >= 1) add(ans, mul(calc(level, operations - 1, 3, 1), 2));\n\t\t\tif (operations == 2) \n\t\t\t\tadd(ans, 1);\n\t\t}\n\t}\n\treturn ans;\n}\n\nint main() {\n\tget[0] = 4; con[0] = 4;\n\tget[1] = 3; con[1] = 2;\n\tget[2] = 2; con[2] = 1;\n\tget[3] = 1; con[3] = 0;\n\tget[4] = 2; con[4] = 0;\n\tfor(int i = 0; i < K; i++)  {\n\t\tC[i][0] = 1;\n\t\tfor(int j = 1; j <= i; j++)\n\t\t\tadd(C[i][j], C[i - 1][j]), add(C[i][j], C[i - 1][j - 1]);\t\n\t}\n\tmemset(dp, -1, sizeof dp);\n\tscanf(\"%d %d\", &n, &k);\n\tfor(int i = 1; i <= k; i++)\tfact = mul(fact, i);\n\tprintf(\"%d\\n\", mul(fact,calc(n, k, 0, 2))); \n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "337",
    "index": "A",
    "title": "Puzzles",
    "statement": "The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her $n$ students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).\n\nThe shop assistant told the teacher that there are $m$ puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of $f_{1}$ pieces, the second one consists of $f_{2}$ pieces and so on.\n\nMs. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let $A$ be the number of pieces in the largest puzzle that the teacher buys and $B$ be the number of pieces in the smallest such puzzle. She wants to choose such $n$ puzzles that $A - B$ is minimum possible. Help the teacher and find the least possible value of $A - B$.",
    "tutorial": "First, let's sort the numbers f[i] in ascending order. Now assume that the smallest jigsaw puzzle which the teacher purchases consists of f[k] pieces. Obviously, she should buy the smallest n puzzles which are of size f[k] or greater to minimize the difference. These are the puzzles f[k], f[k+1], ..., f[k+n-1] (this is not correct when f[i] are not distinct and f[k]=f[k-1], but such cases can be skipped). The difference between the greatest and the least size of the puzzles in such set is f[k+n-1]-f[k]. To choose the optimal f[k], we can test every k between 1 and m-n and pick the one producing the least difference. The full algorithm is as follows:",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "337",
    "index": "B",
    "title": "Routine Problem",
    "statement": "Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio $a$:$b$. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio $c$:$d$. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the screen as possible and fits within it completely. Thus, he may have to zoom the movie in or out, but Manao will always change the frame proportionally in both dimensions.\n\nCalculate the ratio of empty screen (the part of the screen not occupied by the movie) to the total screen size. Print the answer as an irreducible fraction $p / q$.",
    "tutorial": "Suppose that the width and height of the screen are W and H correspondingly. Since W:H = a:b, we have H=W*b/a. Similarly, the width and height of the film frame w and h are related as h=w*d/c. Imagine that Manao stretches/constricts the frame until it fits the screen horizontally or vertically, whichever happens first. There are three cases to consider: the horizontal to vertical ratio of the screen is less, equal or more than the corresponding ratio of the frame. In the first case (a/b < c/d) the stretching process ends when the frame reaches the same width as the screen. That is, the frame will enlarge in W/w times and its new width will be W. Thus, its new height is h*W/w = w*c/d * W/w = W*d/c. We are interested in the ratio of unoccupied portion of the screen to its full size, which is (screen height - frame height) / (screen height) = (W*b/a - W*d/c) / (W*b/a) = (bc-ad)/bc. In the second case (a/b > c/d) the process ends when the frame reaches the same height as the screen. Its height will become H and its width will become w*H/h = w * W*b/a / (w*d/c) = W*b/a * c/d. The unoccupied portion of the screen's horizontal is (W - W*b/a * c/d)/W = (ad-bc)/ad. In the third case, the frame fills the screen entirely and the answer will be 0. All that's left is to print the answer as an irreducible fraction. We need to find the greatest common divisor of its nominator and denominator for this. It can be done using Euclidean algorithm or just through trial division by every number from 1 to q. Since q is no more than a product of two numbers from the input and these numbers are constrained by 1000, we need to try at most million numbers in the worst case.",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "337",
    "index": "C",
    "title": "Quiz",
    "statement": "Manao is taking part in a quiz. The quiz consists of $n$ consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number $k$, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.\n\nManao remembers that he has answered exactly $m$ questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by $1000000009$ $(10^{9} + 9)$.",
    "tutorial": "Assume that Manao has doubled his score (i.e. gave k consecutive correct answers) exactly X times. Then the least possible score is obtained when this doublings happen in the beginning of the game, i.e., when he answers the first X*k questions and never manages to answer k consecutive questions after that. The correctness of this statement follows from the following: for any other scenario with X doublings, all of these doublings can be moved into the beginning and the total score will not increase. Hence, for X=1 Manao's minimum score is k*2+m-k: he answers k consecutive questions, the score doubles, then he answers m-k questions. For X=2 the minimum possible score is (k*2+k)*2+m-2*k, for X=3 - ((k*2+k)*2+k)*2+m-3*k. For the general case, a formula (2^1+2^2+...+2^X)*k + m-X*k = (2^(X+1)-2)*k + m-X*k is derived. The abovementioned observation shows that the minimum score grows monotonically when X is increased, so all we need is to find the minimum feasible X. It should satisfy the inequalities X*k <= n and X + (n - n mod k) / k * (k-1) + n mod k >= m. More on the second inequality: Manao answered the first X*k questions, thus there are n-X*k left. Now he can answer at most k-1 question from each k questions. If k divides n-X*k (which is the same as k divides n), the inequality becomes X*k + (n-X*k) / k * (k-1) >= m, but the remainder complicates it a bit: X*k + (n - X*k - (n - X*k) mod k) / k * (k-1) + (n - X*k) mod k >= m. This formula can be simplified to the one written earlier. So, the minimum X is equal to max(0, m - (n - n mod k) / k * (k-1) - n mod k). You'll need exponentiation by squaring to compute the score corresponding to this value of X. Thus, the overall complexity of this solution is O(log(n)).",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "matrices",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "337",
    "index": "D",
    "title": "Book of Evil",
    "statement": "Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains $n$ settlements numbered from 1 to $n$. Moving through the swamp is very difficult, so people tramped exactly $n - 1$ paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.\n\nThe distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range $d$. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance $d$ or less from the settlement where the Book resides.\n\nManao has heard of $m$ settlements affected by the Book of Evil. Their numbers are $p_{1}, p_{2}, ..., p_{m}$. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.",
    "tutorial": "Obviously, in graph theory language our problem is: given a tree with n vertices, m of which are marked, find the number of vertices which are at most distance d apart from each of the marked vertices. Let us hang the tree by some vertex r, that is, assume that it is a rooted tree with root in vertex r. Let us also rephrase the condition imposed on sought vertices: we need to count such vertices v that the maximum distance from v to a marked vertex is at most d. For any inner vertex v, the marked vertex which is the farthest from it is either in the subtree of v or outside it - in the latter case the path from v to the farthest marked vertex traverses the parent of v. Using this observation, we can recompute the distances to the farthest marked vertices when transiting from a vertex to its child. First, we will compute the distance from every vertex v to the farthest marked vertex within the subtree of v. Let us call this distance distDown[v]. The values of distDown[] can be computed in a single depth-first search: for each leaf of the tree this distance is either 0 (when the leaf is marked) or nominal negative infinity (when the leaf is not marked), and for each inner vertex v distDown[v]=max(distDown[child1], distDown[child2], ..., distDown[childK])+1, where childi are the children of v. Now we will compute the distances from each vertex to the farthest marked vertex outside its subtree. Let's denote this distance with distUp[v]. We will use DFS again to compute values of distUp[]. For the root, distUp[r] is equal to nominal negative infinity, and for any other vertex v there are two cases: either the farthest marked vertex is located in the subtree of v-s parent p, or it is even \"farther\", i.e., the path to it traverses vertex p-s parent. In the first case, the distance from v to such vertex is equal to max(distDown[sibling1], ..., distDown[siblingK])+2, where siblingi are the brothers (other children of the parent) of vertex v. In the second case, it is equal to distUp[p]+1. Thus, distUp[v] is equal to the maximum of these two values. Note that you need to be clever to perform the computations in the first case in overall linear time. For this, you can find the maximum max1 and second maximum max2 of values distDown[sibling1], ..., distDown[siblingK]. After that, when distDown[v] < max1, we have max(distDown[sibling1], ..., distDown[siblingK])=max1, otherwise we have distDown[v] = max1 and max(distDown[sibling1], ..., distDown[siblingK])=max2. After computing distDown[] and distUp[], it is easy to derive the answers: it is the count of such vertices v that distDown[v] <= d && distUp[v] <= d.",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "dp",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "337",
    "index": "E",
    "title": "Divisor Tree",
    "statement": "A divisor tree is a rooted tree that meets the following conditions:\n\n- Each vertex of the tree contains a positive integer number.\n- The numbers written in the leaves of the tree are prime numbers.\n- For any inner vertex, the number within it is equal to the product of the numbers written in its children.\n\nManao has $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$. He tries to build a divisor tree which contains each of these numbers. That is, for each $a_{i}$, there should be at least one vertex in the tree which contains $a_{i}$. Manao loves compact style, but his trees are too large. Help Manao determine the minimum possible number of vertices in the divisor tree sought.",
    "tutorial": "Let us first show that in an optimal divisor tree only the root or a leaf can hold a value other than one of a[i]. Suppose that we have an inner vertex different from the root which holds a number X not equal to any of a[i]. Then we can exclude this vertex from the tree and tie its children to its parent without violating any of the tree's properties. Hence, our tree consists of the root, vertices with numbers a[i] tied to each other or to the root, and leaves, which are tied to vertices with numbers a[i] and contain these numbers' prime factorizations. The exception is the case when one of a[i] is written in root itself, and the case when some a[i]-s are prime themselves. Also note that in general case it's easy to count how many leaves the tree will have. This count is equal to the sum of exponents of primes in prime factorizations of those a[i]-s which are the children of the root. Since N <= 8, we can build all divisor trees which satisfy the observations we made. Let's sort numbers a[i] in descending order and recursively choose a parent for each of them from the vertices already present in the tree. Of course, tying a number X to some vertex v is only possible if the product of X and the numbers in children of v divides the number in v itself. For a[1], we have a choice - we can make it the root of the tree or a child of the root (in this case the root will hold a nominal infinity which is divisible by any number). For every next a[i], the choice is whether to tie it to the root or a vertex containing one of the previous numbers. Therefore, we only consider O(N!) trees in total.",
    "tags": [
      "brute force",
      "number theory",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "338",
    "index": "D",
    "title": "GCD Table",
    "statement": "Consider a table $G$ of size $n × m$ such that $G(i, j) = GCD(i, j)$ for all $1 ≤ i ≤ n, 1 ≤ j ≤ m$. $GCD(a, b)$ is the greatest common divisor of numbers $a$ and $b$.\n\nYou have a sequence of positive integer numbers $a_{1}, a_{2}, ..., a_{k}$. We say that this sequence occurs in table $G$ if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers $1 ≤ i ≤ n$ and $1 ≤ j ≤ m - k + 1$ should exist that $G(i, j + l - 1) = a_{l}$ for all $1 ≤ l ≤ k$.\n\nDetermine if the sequence $a$ occurs in table $G$.",
    "tutorial": "Observation 1. If the sequence a occurs in table G, then it should occur in row i = LCM(a[1], ..., a[k]). The proof follows. It is clear that theoretically it may only occur in rows with numbers which are multiple to i, since the row number should divide by each of a[index]. Consider some a row with number i*x, where x>1. The rows i and i*x differ only in such elements j that i*x and j both divide by some p^q (where p is prime) which does not divide i (hence, G(i*x, j) is divisible by p^q). But none of the a[index] may divide by such p^q, since then i would be also divisible by it. Therefore, if a occurs in row i*x, then it does not intersect with index j. Since it can only reside on indices where i and i*x coincide, checking only the i-th row is enough. It also clear that if i > n, the answer is NO. Observation 2. The sought index j should satisfy the following modular linear equations system: j = 0 (mod a[1])\nj + 1 = 0 (mod a[2])\n...\nj + l = 0 (mod a[l + 1])\n...\nj + k - 1 = 0 (mod a[k])\n\n<=>\n\n{j = -l (mod a[l + 1])} In other words, j + l must divide by a[l+1] for each l=0..k-1. According to Chinese Remainder Theorem, such a system has a solution iff for each pair of indices x, y (0 <= x, y <= k-1) we have -x = -y (mod GCD(a[x+1], a[y+1])). Let's denote L = LCM(a[1], ..., a[k]). If the system has a solution, then it is singular on interval [0, L) and all the other solutions are congruent to it modulo L. Suppose that we have found the minimum non-negative j which satisfies the given system. Then, if a occurs in G, it will start from the j-th element of the i-th row. Theoretically, it may begin at any index of form j+x*L, x>=0, but since i = L, we have G(i, j+X*L) = GCD(i, j+X*i) = GCD(i, j). So it is sufficient to check whether the k consecutive elements which begin at index j in row i coincide with sequence a. It is also clear that when j > m-k+1, the answer is NO. Finally, let's consider how to solve a system of modular linear equations. We can use an auxiliary method which, given r1, m1, r2, m2, finds minimum X such that X = r1 (mod m1) and X = r2 (mod m2), or determines that such number does not exist. Let X = m1*x + r1, then we have m1*x + r1 = r2 (mod m2). This can be represented as a Diophantine equation m1*x + m2*y = r2-r1 and solved using Extended Euclidean Algorithm. The least non-negative x, if it exists, yields the sought X = m1*x + r1. Now this method can be used to find the minimum X1 which satisfies the first two equations. After that, we can say that we have a system with k-1 equation, where the first two old equations are replaced with a new j = X1 (mod LCM(a[1], a[2])), and repeat the same procedure again. After using this method k-1 times, we obtain the solution to the whole system. Also note that the proposed solution does not require long arithmetics: - The computation of LCM(a[1], ..., a[k]) can be implemented with a check before each multiplication: if the result will become larger than n, the answer is NO; - When it comes to solving the system of equations, we already know that L <= n <= 10^12, thus all the intermediate moduli will also obide to this constraint; - The Extended Euclidean Algorithm can find a solution in the same bounds as its inputs, so it will also use numbers up to 10^12. The overall complexity of the algorithm is O(k logn).",
    "tags": [
      "chinese remainder theorem",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "338",
    "index": "E",
    "title": "Optimize!",
    "statement": "Manao is solving a problem with the following statement:\n\nHe came up with a solution that produces the correct answers but is too slow. You are given the pseudocode of his solution, where the function getAnswer calculates the answer to the problem:\n\n\\begin{verbatim}\ngetAnswer(a[1..n], b[1..len], h)\nanswer = 0\nfor i = 1 to n-len+1\nanswer = answer + f(a[i..i+len-1], b, h, 1)\nreturn answer\nf(s[1..len], b[1..len], h, index)\nif index = len+1 then\nreturn 1\nfor i = 1 to len\nif s[index] + b[i] >= h\nmem = b[i]\nb[i] = 0\nres = f(s, b, h, index + 1)\nb[i] = mem\nif res > 0\nreturn 1\nreturn 0\n\\end{verbatim}\n\nYour task is to help Manao optimize his algorithm.",
    "tutorial": "Decyphering Manao's pseudocode, we unearth the following problem: you are given arrays a[1..n] and b[1..len] and a number h. Consider each subarray of a of length L. Let us call it s. Count how many of them have the property that the elements of b can be shuffled in such a way that each sum s[i]+b[i] (1<=i<=L) is at least h. First, let's solve a problem for one subarray. That is, we need to determine whether the elements of two arrays s and b can be matched in such a way that each sum is h or more. We can do the following: for each element of s, find the least element of b such that the two's sum is at least h, and erase the corresponding element from b. If we managed to pair each of the elements from s, then the arrays hold the property. Note that the elements of s can be processed in any order. If both s and b are sorted, then the idea described can be implemented in linear time. We can not achieve better complexity when considering each subarray separately, so we will try to solve the problem for several subarrays at the same time. Suppose that b is already sorted. We choose some X < len and consider a subarray a[i..i+X-1]. Let's process all the numbers from this subarray, i.e., for each of them find the least b[j] which pairs up with this number and erase it from b. The whole processing can be done in time O(n) if we have a sorted version of a and the corresponding indices computed beforehand. Now we can find the answer for every subarray s of length len which begins in segment [i-Y, i] using O(YlogY) operations, where Y=len-X. For this, we just take the Y elements which are in s but not in a[i..i+X-1] and process them against the numbers left in b. If each of them has been paired, then subarray s holds the required property, otherwise it does not. Moreover, since the subarrays we consider are overlapping, we can optimize even further and obtain amortized O(Y) complexity per subarray. To understand this, note that for processing a subarray in O(Y) time we only need to obtain its sorted version (to be more specific, the sorted version of the portion which does not overlap with a[i..i+X-1]). For the leftmost subarray we consider, we can sort its elements in usual way. For every next subarray (which differs from its predecessor in exactly two elements) we only need O(Y) operations to obtain its sorted version by updating the information from the previous subarray. Thus we have complexity O(YlogY + Y^2) of processing Y segments in total, which gives O(Y) per segment on average. Now let us take a look at the full picture. To process all subarrays of length len, we need to use the method given above for each of the segments a[Y..Y+len-1], a[2Y+1..2Y+len], a[3Y+2..3Y+len+1], .... Therefore, we have O(N/Y) iterations of algorithm with comlexity O(N+Y^2). We need to find a value of Y that minimizes N*N/Y + N*Y, which is Y=~sqrt(N). The overall complexity is O(Nsqrt(N)). However, we need to consider the case len < sqrt(N) separately, since then Y = len - X < len. In this case, the problem can be solved in time O(N*len) with ideas similar to those described above.",
    "tags": [
      "data structures"
    ],
    "rating": 2600
  },
  {
    "contest_id": "339",
    "index": "A",
    "title": "Helpful Maths",
    "statement": "Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.\n\nThe teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.\n\nYou've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.",
    "tutorial": "To solve this problem we can count the number of digits 1, 2 and 3 in the input. If there are $c_{1}$ digits 1, $c_{2}$ digits 2 and $c_{3}$ digits 3. Then we must print the sequence of $c_{1}$ digits 1, $c_{2}$ digits 2 and $c_{3}$ digits 3. Digits must be separated by + sign.",
    "tags": [
      "greedy",
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "339",
    "index": "B",
    "title": "Xenia and Ringroad",
    "statement": "Xenia lives in a city that has $n$ houses built along the main ringroad. The ringroad houses are numbered 1 through $n$ in the clockwise order. The ringroad traffic is one way and also is clockwise.\n\nXenia has recently moved into the ringroad house number 1. As a result, she's got $m$ things to do. In order to complete the $i$-th task, she needs to be in the house number $a_{i}$ and complete all tasks with numbers less than $i$. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.",
    "tutorial": "To solve this problem we must learn how to calculate fast enought the time, needed to travel between houses $a$ and $b$. Let's consider the case when $a  \\le  b$. Than Xenia needs $b - a$ seconds to get from $a$ to $b$. Otherwise $a > b$, Xenia will have to go thought house number 1. So she will need $n - a + b$ seconds.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "339",
    "index": "C",
    "title": "Xenia and Weights",
    "statement": "Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of $m$ weights on the scalepans.\n\nSimply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes $i$-th should be different from the $(i + 1)$-th weight for any $i$ $(1 ≤ i < m)$. Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.\n\nYou are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay $m$ weights on ​​the scales or to say that it can't be done.",
    "tutorial": "Let's consider the definition of balance. Balance is the difference between sum of all weights on the left pan and sum of all weights on the right pan. At the beginning balance is equal to 0. Att each step Xenia puts one weight on the pan. It means she adds to or substracts from balance integer from 1 to 10. In each odd step, the integer is added and in each even step the integer is subtracted. From the statement we know, that after each step, balance must change it sign and must not be equal to 0. So if after some step the absolute value of balance is greater than 10, Xenia can not continue. Also, it is said in the statement that we can not use two equal weigths in a row. To solve the problem, let's consider a graph, where vertices are tuples of three numbers $(i, j, k)$, where $i$ is a current balance, $j$ is a weight, used in the previous step, and $k$ is the number of the current step. Arcs of the graph must correspond to Xenias actions, described in the statement. The solution of the problme is a path from vertex $(0, 0, 1)$ to some vertex $(x, y, m)$, where x, y are any numbers, and $m$ is the requared number of steps.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "339",
    "index": "D",
    "title": "Xenia and Bit Operations",
    "statement": "Xenia the beginner programmer has a sequence $a$, consisting of $2^{n}$ non-negative integers: $a_{1}, a_{2}, ..., a_{2^{n}}$. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value $v$ for $a$.\n\nNamely, it takes several iterations to calculate value $v$. At the first iteration, Xenia writes a new sequence $a_{1} or a_{2}, a_{3} or a_{4}, ..., a_{2^{n} - 1} or a_{2^{n}}$, consisting of $2^{n - 1}$ elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence $a$. At the second iteration, Xenia writes the bitwise \\textbf{exclusive} OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is $v$.\n\nLet's consider an example. Suppose that sequence $a = (1, 2, 3, 4)$. Then let's write down all the transformations $(1, 2, 3, 4)$ $ → $ $(1 or 2 = 3, 3 or 4 = 7)$ $ → $ $(3 xor 7 = 4)$. The result is $v = 4$.\n\nYou are given Xenia's initial sequence. But to calculate value $v$ for a given sequence would be too easy, so you are given additional $m$ queries. Each query is a pair of integers $p, b$. Query $p, b$ means that you need to perform the assignment $a_{p} = b$. After each query, you need to print the new value $v$ for the new sequence $a$.",
    "tutorial": "The problem could be solved by using a typical data structure (segment tree). The leafs of the segment tree will store the values of $a_{i}$. At the vertices, the distance from which to the leafs is 1, we will store OR of the numbers from the leafs, which are the sons of this node in the segment tree. Similarly, vertices, the distance from which to the leafs is 2, we will store Xor of the numbers stored in their immediate sons. And so on. Then, the root of the tree will contain the required value $v$. There is no need to rebuild all the tree to perform an update operation. To do update, we should find a path from the root to the corresponding leaf and recalculate the values only at the tree vertices that are lying on that path. If everything is done correctly, then each update query will be executed in $O(n)$ time. Also we need $O(2^{n})$ memory.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "339",
    "index": "E",
    "title": "Three Swaps",
    "statement": "Xenia the horse breeder has $n$ $(n > 1)$ horses that stand in a row. Each horse has its own unique number. Initially, the $i$-th left horse has number $i$. That is, the sequence of numbers of horses in a row looks as follows (from left to right): 1, 2, 3, $...$, $n$.\n\nXenia trains horses before the performance. During the practice sessions, she consistently gives them commands. Each command is a pair of numbers $l, r$ $(1 ≤ l < r ≤ n)$. The command $l, r$ means that the horses that are on the $l$-th, $(l + 1)$-th, $(l + 2)$-th, $...$, $r$-th places from the left must be rearranged. The horses that initially stand on the $l$-th and $r$-th places will swap. The horses on the $(l + 1)$-th and $(r - 1)$-th places will swap. The horses on the $(l + 2)$-th and $(r - 2)$-th places will swap and so on. In other words, the horses that were on the segment $[l, r]$ change their order to the reverse one.\n\nFor example, if Xenia commanded $l = 2, r = 5$, and the sequence of numbers of horses before the command looked as (2, 1, 3, 4, 5, 6), then after the command the sequence will be (2, 5, 4, 3, 1, 6).\n\nWe know that during the practice Xenia gave at most three commands of the described form. You have got the final sequence of numbers of horses by the end of the practice. Find what commands Xenia gave during the practice. Note that you do not need to minimize the number of commands in the solution, find any valid sequence of at most three commands.",
    "tutorial": "We will call the command $l, r$ a reverse, also we will call the row of horses an array. Suddenly, right? The problem can be solved with clever bruteforcing all possible ways to reverse an array. To begin with, assume that the reverse with $l = r$ is ok. Our solution can find an answer with such kind of reverses. It is clear that this thing doesn't affect the solution. Because such reverses can simply be erased from the answer. The key idea: reverses split an array into no more than seven segments of the original array. In other words, imagine that the array elements was originally glued together, and each reverse cuts a segment from the array. Then the array would be cut into not more than 7 pieces. Now you can come up with the wrong solution to the problem, and then come up with optimization that turns it into right. So, bruteforce all ways to cut array into 7 or less pieces. Then bruteforce reverse operations, but each reverse operation should contain only whole pieces. It is clear that this solution is correct, One thing it does not fit the TL. How to improve it? Note that the previous solution requires the exact partition of the array only at the very end of the bruteforce. It needed to check whether it is possible to get the given array $a$. So, let's assume that the array was originally somehow divided into 7 parts (we don't know the exact partition), the parts can be empty. Now try to bruteforce reverses as in naive solution. One thing, in the very end of bruteforce try to find such a partition of the array to get (with fixed reverses) the given array $a$. The search for such a partition can be done greedily (the reader has an opportunity to come up with it himself). Author's solution does this in time proportional to the number of parts, that is, 7 operations. However, this can be done for $O(n)$ - this should fit in TL, if you write bruteforce carefully.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "340",
    "index": "A",
    "title": "The Wall",
    "statement": "Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered $1$, $2$, $3$ and so on.\n\nIahub has the following scheme of painting: he skips $x - 1$ consecutive bricks, then he paints the $x$-th one. That is, he'll paint bricks $x$, $2·x$, $3·x$ and so on red. Similarly, Floyd skips $y - 1$ consecutive bricks, then he paints the $y$-th one. Hence he'll paint bricks $y$, $2·y$, $3·y$ and so on pink.\n\nAfter painting the wall all day, the boys observed that some bricks are painted both red and pink. Iahub has a lucky number $a$ and Floyd has a lucky number $b$. Boys wonder how many bricks numbered no less than $a$ and no greater than $b$ are painted both red and pink. This is exactly your task: compute and print the answer to the question.",
    "tutorial": "You are given a range $[A, B]$. You're asked to compute fast how many numbers in the range are divisible by both $x$ and $y$. I'll present here an $O(log(max(x, y))$ solution. We made tests low so other not optimal solutions to pass as well. The solution refers to the original problem, where $x, y  \\le  10^{9}$. Firstly, we can simplify the problem. Suppose we can calculate how many numbers are divisible in range $[1, X]$ by both $x$ and $y$. Can this solve our task? The answer is yes. All numbers in range $[1, B]$ divisible by both numbers should be counted, except the numbers lower than $A$ (1, 2, ..., A - 1). But, as you can see, numbers lower than A divisible by both numbers are actually numbers from range [1, A - 1]. So the answer of our task is f(B) - f(A - 1), where f(X) is how many numbers from 1, 2, ..., X are divisible by both x and y. For calculate in $O(log(max(x, y))$ the f(X) we need some math. If you don't know about it, please read firstly about least common multiple. Now, what will be the lowest number divisible by both x and y. The answer is least common multiple of x and y. Let's note it by $M$. The sequence of the numbers divisible by both x and y is $M$, $2 * M$, $3 * M$ and so on. As a proof, suppose a number z is divisible by both x and y, but it is not in the above sequence. If a number is divisible by both x and y, it will be divisible by M also. If a number is divisible by M, it will be in the above sequence. Hence, the only way a number to be divisible by both x and y is to be in sequence $M$, $2 * M$, $3 * M$, ... The f(X) calculation reduces to finding the number of numbers from sequence $M$, $2 * M$, $3 * M$, ... lower or equal than X. It's obvious that if a number h * M is greater than X, so will be (h + 1) * M, (h + 2) * M and so on. We actually need to find the greatest integer number h such as $h * M  \\le  X$. The numbers we're looking for will be $1 * M, 2 * M, ..., h * M$ (so their count will be $h$). The number h is actually [X / M], where [number] denotes the integer part of [number]. Take some examples on paper, you'll see why it's true. The only thing not discussed is how to calculate the number M given 2 number x and y. You can use this formula $M = x * y / gcd(x, y)$. For calculate gcd(x, y) you can use Euclid's algorithm. Its complexity is $O(log(max(x, y))$, so this is the running time for the entire algorithm.",
    "code": "#include <stdio.h>\n \nint gcd(int x, int y) {\n    if (y == 0)\n        return x;\n    return gcd(y, x % y);\n}\n \nint solve(int x, int y, int uppBound) {\n    long long lcm = 1LL * x * y;\n    lcm = lcm / gcd(x, y);\n    return uppBound / lcm;\n}\n \nint main() {\n    int x, y, A, B;\n    scanf(\"%d%d%d%d\", &x, &y, &A, &B);\n    printf(\"%d\", solve(x, y, B) - solve(x, y, A - 1));\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "340",
    "index": "B",
    "title": "Maximal Area Quadrilateral",
    "statement": "Iahub has drawn a set of $n$ points in the cartesian plane which he calls \"special points\". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral.",
    "tutorial": "I want to apologize for not estimating the real difficulty of this task. It turns out that it was more complicated than we thought it might be. Let's start explanation. Before reading this, you need to know what is signed area of a triangle (also called cross product or ccw function). Without it, this explanation will make no sense. The first thing we note is that a quadrilateral self intersecting won't have maximum area. I'll show you this by an image made by my \"talents\" in Paint :) As you can see, if a quadrilateral self intersects, it can be transformed into one with greater area. Each quadrilateral has 2 diagonals: connecting 1st and 3rd point and connecting 2nd and 4th point. A diagonal divides a plane into 2 subplanes. Suppose diagonal is AB. A point X can be in one of those two subplanes: that making cross product positive and that making cross product negative. A point is in \"positive\" subplane if ccw(X, A, B) > 0 and in \"negative\" subplane ccw(X, A, B) < 0. Note that according to the constraints of the task, ccw(X, A, B) will never be 0. Let's make now the key observation of the task. We have a quadrilateral. Suppose AB is one of diagonals and C and D the other points from quadrilateral different by A and B. If the current quadrilateral could have maximal area, then one of points from C and D needs to be in \"positive subplane\" of AB and the other one in \"negative subplane\". What would happen if C and D will be in the same subplane of AB? The quadrilateral will self intersect. If it will self intersect, it won't have maximal area. \"A picture is worth a thousand words\" - this couldn't fit better in this case :) Note that the quadrilateral from the below image is A-C-B-D-A. Out task reduces to fix a diagonal (this taking O(N ^ 2) time) and then choose one point from the positive and the negative subplane of the diagonal. I'll say here how to choose the point from the positive subplane. That from negative subplane can be chosen identically. The diagonal and 3rd point chosen form a triangle. As we want quadrilateral to have maximal area, we need to choose 3rd point such as triangle makes the maximal area. As the positive and negative subplanes are disjoint, the choosing 3rd point from each of them can be made independently. Hence we get O(N ^ 3) complexity. A tricky case is when you choose a diagonal but one of the subplanes is empty. In this case you have to disregard the diagonal and move to the next one.",
    "code": "#include <stdio.h>\n#include <algorithm>\n#define eps 0.00000001\n#define x first\n#define y second\n#define point pair <int, int>\n \nusing namespace std;\n \npoint x[301];\n \ninline double ccw(point A, point B, point C) {\n    return ((double)(B.x - A.x) * (C.y - B.y) - (B.y - A.y) * (C.x - B.x)) * 0.5;\n}\n \ninline double chmax(double &A, double B) {\n    if (B - A > eps)\n        A = B;\n}\n \nint main() {\n    int n;\n    double maxArea = 0;\n    scanf(\"%d\", &n);\n    for (int i = 1; i <= n; ++i)\n        scanf(\"%d%d\", &x[i].x, &x[i].y);\n    for (int i = 1; i <= n; ++i)\n        for (int j = i + 1; j <= n; ++j) {\n            double maxMinus = -1, maxPlus = -1;\n            for (int k = 1; k <= n; ++k)\n                if (k != i && k != j)\n                    if (ccw(x[i], x[j], x[k]) < 0)\n                        chmax(maxMinus, -ccw(x[i], x[j], x[k]));\n                    else\n                        chmax(maxPlus, ccw(x[i], x[j], x[k]));\n            if (maxPlus >= 0 && maxMinus >= 0)\n                    chmax(maxArea, maxMinus + maxPlus);\n        }\n \n    printf(\"%lf\", maxArea);\n    return 0;\n}",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 2100
  },
  {
    "contest_id": "340",
    "index": "C",
    "title": "Tourist Problem",
    "statement": "Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are $n$ destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The $n$ destinations are described by a non-negative integers sequence $a_{1}$, $a_{2}$, ..., $a_{n}$. The number $a_{k}$ represents that the $k$th destination is at distance $a_{k}$ kilometers from the starting point. No two destinations are located in the same place.\n\nIahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.\n\nThe distance between destination located at kilometer $x$ and next destination, located at kilometer $y$, is $|x - y|$ kilometers. We call a \"route\" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all $n$ destinations and he doesn't visit a destination more than once.\n\nIahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.",
    "tutorial": "Despite this is a math task, the only math formula we'll use is that number of permutations with $n$ elements is $n!$. From this one, we can deduce the whole task. The average formula is sum_of_all_routes / number_of_routes. As each route is a permutation with n elements, number_of_routes is $n!$. Next suppose you have a permutation of a: p1, p2,  \\dots , pn. The sum for it will be p1 + |p2 - p1| +  \\dots  + |pn - pn-1|. The sum of routes will be the sum for each possible permutation. We can calculate sum_of_all routes in two steps: first time we calculate sums like \"p1\" and then we calculate sums like \"|p2 - p1| +  \\dots  + |pn - pn-1|\" for every existing permutation. First step Each element of $a_{1}$, $a_{2}$,  \\dots , $a_{n}$ can appear on the first position on the routes and needs to be added as much as it appears. Suppose I fixed an element X for the first position. I can fill positions 2, 3, .., n - 1 in (n - 1)! ways. Why? It is equivalent to permuting n - 1 elements (all elements except X). So sum_of_all = $a_{1}$ * (n - 1)! + $a_{2}$ * (n - 1)! +  \\dots  * $a_{n}$ * (n - 1)! = (n - 1)! * ($a_{1}$ + $a_{2}$ +  \\dots  + $a_{n}$). Second step For each permutation, for each position j between 1 and n - 1 we need to compute |$p_{j}$ - $p_{}(j + 1)$|. Similarly to first step, we observe that only elements from $a$ can appear on consecutive positions. We fix 2 indices i and j. We're interested in how many permutations do $a_{i}$ appear before $a_{j}$. We fix k such as on a permutation p, $a_{i}$ appears on position k and $a_{j}$ appears on a position k + 1. In how many ways can we fix this? n - 1 ways (1, 2,  \\dots , n - 1). What's left? A sequence of (n - 2) elements which can be permuted independently. So the sum of second step is |$a_{i} - a_{j}$| * (n - 1) * (n - 2)!, for each i != j. If I note ($a_{1}$ + $a_{2}$ +  \\dots  + $a_{n}$) by S1 and |$a_{i} - a_{j}$| for each i != j by S2, the answer is (N - 1)! * S1 + (N - 1)! * S2 / N!. By a simplification, the answer is (S1 + S2) / N. The only problem remained is how to calculate S2. Simple iteration won't enter in time limit. Let's think different. For each element, I need to make sum of differences between it and all smaller elements in the array a. As well, I need to make sum of all different between bigger elements than it and it. I'll focus on the first part. I sort increasing array a. Suppose I'm at position $i$. I know that (i - 1) elements are smaller than $a_{i}$. The difference is simply (i - 1) * $a_{i}$ - sum_of_elements_before_position_i. Sum of elements before position i can be computed when iterating i. Let's call the obtained sum Sleft. I need to calculate now sum of all differences between an element and bigger elements than it. This sum is equal to Sleft. As a proof, for an element $a_{i}$, calculating the difference $a_{j}$ - $a_{i}$ when $a_{j}$ > $a_{i}$ is equivalent to calculating differences between $a_{j}$ and a smaller element of it (in this case $a_{i}$). That's why Sleft = Sright. As a conclusion, the answer is (S1 + 2 * Sleft) / N. For make fraction irreducible, you can use Euclid's algorithm. The complexity of the presented algorithm is $O(N * logN)$, necessary due of sorting. Sorting can be implemented by count sort as well, having a complexity of O(maximalValue), but this is not necessary.",
    "code": "#include <stdio.h>\n#include <algorithm>\n#define ll long long\n \nusing namespace std;\n \nint x[100010];\n \nll gcd(ll A, ll B) {\n    if (B == 0)\n        return A;\n    return gcd(B, A % B);\n}\n \nint main() {\n    int n;\n    ll sum1 = 0, sum2 = 0, sumBefore = 0, sumtot = 0;\n    scanf(\"%d\", &n);\n    for (int i = 1; i <= n; ++i) {\n        scanf(\"%d\", &x[i]);\n        sum1 += x[i];\n    }\n    sort(x + 1, x + n + 1);\n    for (int i = 1; i <= n; ++i) {\n        sum2 += 1LL * x[i] * (i - 1) - sumBefore;\n        sumBefore += x[i];\n    }\n    sumtot = sum1 + 2 * sum2;\n    ll _gcd = gcd(sumtot, n);\n    printf(\"%I64d %I64d\", sumtot / _gcd, n / _gcd);\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "340",
    "index": "D",
    "title": "Bubble Sort Graph",
    "statement": "Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with $n$ elements $a_{1}$, $a_{2}$, ..., $a_{n}$ in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it $G$) initially has $n$ vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).\n\n\\begin{verbatim}\nprocedure bubbleSortGraph()\nbuild a graph G with n vertices and 0 edges\nrepeat\nswapped = false\nfor i = 1 to n - 1 inclusive do:\nif a[i] > a[i + 1] then\nadd an undirected edge in G between a[i] and a[i + 1]\nswap( a[i], a[i + 1] )\nswapped = true\nend if\nend for\nuntil not swapped\n/* repeat the algorithm as long as swapped value is true. */\nend procedure\n\\end{verbatim}\n\nFor a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph $G$, if we use such permutation as the premutation $a$ in procedure bubbleSortGraph.",
    "tutorial": "A good way to approach this problem is to notice that you can't build the graph. In worst case, the graph will be built in $O(N^{2})$ complexity, which will time out. Also, notice that \"maximal independent set\" is a NP-Hard task, so even if you can build the graph you can't continue from there. So, the correct route to start is to think of graph's properties instead of building it. After sketching a little on the paper, you should find this property: Lemma 1 Suppose we choose 2 indices i and j, such as i < j. We'll have an edge on the graph between vertices $a_{i}$ and $a_{j}$ if and only if $a_{i}$ > $a_{j}$. We'll call that i and j form an inversion in the permutation. Proof We assume we know the proof that bubble sort does sort correctly an array. To proof lemma 1, we need to show two things. To proof 1, if bubble sort wouldn't swap an inversion, the sequence wouldn't be sorted. But we know that bubble sort always sorts a sequence, so all inversions will be swapped. Proofing 2 is trivial, just by looking at the code. So far we've got how the graph G is constructed. Let's apply it in maximal independent set problem. Lemma 2 A maximal independent set of graph G is a longest increasing sequence for permutation a. Proof: Suppose we have a set of indices $i1$ < $i2$ < ... $ik$ such as $a_{i1}$, $a_{i2}$, ..., $a_{ik}$ form an independent set. Then, anyhow we'd choose $d$ and $e$, there won't exist an edge between $a_{id}$ and $a_{ie}$. According to proof 1, this only happens when $a_{id}$ < $a_{ie}$. Hence, an independent set will be equivalent to an increasing sequence of permutation a. The maximal independent set is simply the maximal increasing sequence of permutation a. The task reduces to find longest increasing sequence for permutation $a$. This is a classical problem which can be solved in $O(N * logN)$. Here is an interesting discussion about how to do it.",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "340",
    "index": "E",
    "title": "Iahub and Permutations",
    "statement": "Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.\n\nThe girl finds an important permutation for the research. The permutation contains $n$ distinct integers $a_{1}$, $a_{2}$, ..., $a_{n}$ $(1 ≤ a_{i} ≤ n)$. She replaces some of permutation elements with -1 value as a revenge.\n\nWhen Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element $a_{k}$ which has value equal to $k$ $(a_{k} = k)$. Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "In this task, author's intended solution is an O(N ^ 2) dp. However, during testing Gerald fount a solution using principle of inclusion and exclusion. We've thought to keep both solutions. We're sorry if you say the problem was well-known, but for both me and the author of the task, it was first time we saw it. Dynamic programming solution After reading the sequence, we can find which elements are deleted. Suppose we have in a set D all deleted elements. I'll define from now on a \"free position\" a position which has -1 value, so it needs to be completed with a deleted element. We observe that some elements from D can appear on all free positions of permutation without creating a fixed point. The other elements from D can appear in all free positions except one, that will create the fixed point. It's intuitive that those two \"classes\" don't influence in the same way the result, so they need to be treated separated. So from here we can get the dp state. Let dp(n, k) = in how many ways can I fill (n + k) free positions, such as n elements from D can be placed anywhere in the free position and the other k elements can be placed in all free positions except one, which will create the fixed point. As we'll prove by the recurrences, we are not interested of the values from elements of D. Instead, we'll interested in their property: if they can(not) appear in all free positions. If k = 0, the problem becomes straight-forward. The answer for dp(n, 0) will be n!, as each permutation of (n + 0) = n numbers is valid, because all numbers can appear on all free positions. We can also calculate dp(n, 1). This means we are not allowed to place an element in a position out of (n + 1) free positions. However, we can place it in the other n positions. From now we get n elements which can be placed anywhere in the n free positions left. Hence, dp(n, 1) = n! * n. We want to calculate dp(n, k) now, k > 1. Our goal is to reduce the number k, until find something we know how to calculate. That is, when k becomes 0 or 1 problem is solved. Otherwise, we want to reduce the problem to a problem when k becomes 0 or 1. I have two cases. In a first case, I take a number from numbers which can be placed anywhere in order to reduce the numbers which can form fixed points. In the second case, I take a number from those which can form fixed points in order to make the same goal as in the first case. Let's analyze them. Case 1. Suppose X is the first free position, such as in the set of k numbers there exist one which cannot be placed there (because it will make a fixed point). Obviously, this position exist, otherwise k = 0. Also obviously, this position will need to be completed with a term when having a solution. In this case, I complete position X with one of n numbers. This will make number equal to X from the k numbers set to become a number which can be placed anywhere. So I \"loose\" one number which can be placed anywhere, but I also \"gain\" one. As well, I loose one number which can form a fixed point. Hence dp(n, k) += n * dp(n, k - 1). Case 2. In this case position X will be completed with one number from the k numbers set. All numbers which can form fixed points can appear there, except number having value equal to X. So there are k - 1 of them. I choose an arbitrary number Y from those k - 1 to place on the position X. This time I \"loose\" two numbers which could form fixed points: X and Y. As well, I \"gain\" one number which can be placed anywhere: X. Hence dp(n, k) += (k - 1) * dp(n + 1, k - 2). TL;DR dp[N][0]=N! dp[N][1]=N*dp[N][0] dp[N][K]=N*dp[N][K-1]+(K-1)*dp[N+1][K-2] for K>=2 This recurrences can be computed by classical dp or by memoization. I'll present DamianS's source, which used memoization. As you can see, it's very short and easy to implement. Link Inclusion and exclusion principle I'll present here an alternative to the dynamic programming solution. Let's calculate in $tot$ the number of deleted numbers. Also, let's calculate in $fixed$ the maximal number of fixed points a permutation can have. For calculate $fixed$, let's iterate with an index $i$ each permutation position. We can have a fixed point on position $i$ if element from position $i$ was deleted ($a_{i}$ = -1) and element i does not exist in sequence $a$. With other words, element $i$ was deleted and now I want to add it back on position $i$ to obtain maximal number of fixed points. We iterate now an index $i$ from $fixed$ to $0$. Let sol[i] = the number of possible permutations having exactly $i$ fixed points. Obviously, sol[0] is the answer to our problem. Let's introduce a combination $\\textstyle{\\binom{n}{k}}$ representing in how many ways I can choose k objects out of n. I have list of positions which can be transformed into fix points (they are $fixed$ positions). I need to choose $i$ of them. According to the above definition, I get sol[i] = $(f_{i}^{t_{i}x e d})$ . Next, I have to fill $tot - i$ positions with remained elements. We'll consider for this moment valid each permutation of not used values. So, sol[i] = $(stackrel{f i x e d}{i})*(t o t-i)!$ . Where is the problem to this formula? The problem is that it's possible, when permuting (tot - i) remained elements to be added, one (or more) elements to form more (new) fixed points. But if somehow I can exclude (subtract) the wrong choices from sol[i], sol[i] will be calculated correctly. I iterate another index $j$ from i + 1 to $fixed$. For each j, I'll calculate how many permutations I considered in sol[i] having $i$ fixed points but actually they have $j$. I'll subtract from sol[i] this value calculated for each j. If I do this, obviously sol[i] will be calculated correctly. Suppose we fixed a j. We know that exactly sol[j] permutations have j fixed points (as j > i, this value is calculated correctly). Suppose now I fix a permutation having j fixed points. For get the full result, I need to calculate for all sol[j] permutations. Happily, I can multiply result obtained for a single permutation with sol[j] and obtain the result for all permutations having j fixed points. So you have a permutation having j fixed points. The problem reduces to choosing i objects from a total of j. Why? Those i objects chosen are actually the positions considered in sol[i] to be ones having exactly i fixed points. But permutation has j fixed points. Quoting for above, \"For each j, I'll calculate how many permutations I considered in sol[i] having $i$ fixed points but actually they have $j$\" . This is exactly what algorithm does. To sum up in a \"LaTeX\" way, $s o l[i]=\\left(J^{i x e d}\\right)*\\left(t o t-i\\right)!-\\sum_{j=i+1}^{f i x e d}s o l[j]*\\left({}_{i}^{j}\\right)$ We can compute binomial coefficients using Pascal's triangle. Using inclusion and exclusion principle, we get $O(N^{2})$. Please note that there exist an $O(N)$ solution for this task, using inclusion and exclusion principle, but it's not necessary to get AC. I'll upload Gerald's source here.",
    "code": "#include <string>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <set>\n#include <queue>\n#include <map>\n#include <cstdio>\n#include <iomanip>\n#include <sstream>\n#include <iostream>\n#include <cstring>\n#define REP(i,x,v)for(int i=x;i<=v;i++)\n#define REPD(i,x,v)for(int i=x;i>=v;i--)\n#define FOR(i,v)for(int i=0;i<v;i++)\n#define FORE(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)\n#define FOREACH(i,t) FORE(i,t)\n#define REMIN(x,y) (x)=min((x),(y))\n#define REMAX(x,y) (x)=max((x),(y))\n#define pb push_back\n#define sz size()\n#define mp make_pair\n#define fi first\n#define se second\n#define ll long long\n#define IN(x,y) ((y).find((x))!=(y).end())\n#define un(v) v.erase(unique(ALL(v)),v.end())\n#define LOLDBG\n#ifdef LOLDBG\n#define DBG(vari) cerr<<#vari<<\" = \"<<vari<<endl;\n#define DBG2(v1,v2) cerr<<(v1)<<\" - \"<<(v2)<<endl;\n#else\n#define DBG(vari)\n#define DBG2(v1,v2)\n#endif\n#define CZ(x) scanf(\"%d\",&(x));\n#define CZ2(x,y) scanf(\"%d%d\",&(x),&(y));\n#define CZ3(x,y,z) scanf(\"%d%d%d\",&(x),&(y),&(z));\n#define wez(x) int x; CZ(x);\n#define wez2(x,y) int x,y; CZ2(x,y);\n#define wez3(x,y,z) int x,y,z; CZ3(x,y,z);\n#define SZ(x) int((x).size())\n#define ALL(x) (x).begin(),(x).end()\n#define tests int dsdsf;cin>>dsdsf;while(dsdsf--)\n#define testss int dsdsf;CZ(dsdsf);while(dsdsf--)\n#define MOD 1000000007\nusing namespace std;\ntypedef pair<int,int> pii;\ntypedef vector<int> vi;\ntemplate<typename T,typename TT> ostream &operator<<(ostream &s,pair<T,TT> t) {return s<<\"(\"<<t.first<<\",\"<<t.second<<\")\";}\ntemplate<typename T> ostream &operator<<(ostream &s,vector<T> t){s<<\"{\";FOR(i,t.size())s<<t[i]<<(i==t.size()-1?\"\":\",\");return s<<\"}\"<<endl; }\ninline void pisz (int x) { printf(\"%d\n\", x); }\n\nll dp[3111][3111];\n\nll go(int K,int N)\n{\n    if (dp[K][N]!=-1) return dp[K][N];\n    if (K==0)\n    {\n        if (N==0) return 1;\n        return dp[0][N]=(N*go(0,N-1))%MOD;\n    }\n    if (K==1)\n    {\n        if (N==0) return 0;\n        return dp[1][N]=(N*go(0,N))%MOD;\n    }\n    return dp[K][N]=(N*go(K-1,N)+(K-1)*go(K-2,N+1))%MOD;\n}\n\nbool used[3111];\n\nint fast(vi v)\n{\n    int n=v.sz;\n    REP(i,1,n)used[i]=0;\n    FOR(i,n) if (v[i]!=-1) used[v[i]]=1;\n    int K=0,N=0;\n    REP(i,1,n) if (!used[i])\n    {\n        if (v[i-1]==-1) K++;\n        else N++;\n    }\n    return go(K,N);\n}\n\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    FOR(i,2111)FOR(j,2111)dp[i][j]=-1;\n    int n;cin>>n;\n    vi v(n);\n    FOR(i,n) cin>>v[i];\n    cout<<fast(v);\n\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "341",
    "index": "D",
    "title": "Iahub and Xors",
    "statement": "Iahub does not like background stories, so he'll tell you exactly what this problem asks you for.\n\nYou are given a matrix $a$ with $n$ rows and $n$ columns. Initially, all values of the matrix are zeros. Both rows and columns are 1-based, that is rows are numbered 1, 2, ..., $n$ and columns are numbered 1, 2, ..., $n$. Let's denote an element on the $i$-th row and $j$-th column as $a_{i, j}$.\n\nWe will call a submatrix $(x_{0}, y_{0}, x_{1}, y_{1})$ such elements $a_{i, j}$ for which two inequalities hold: $x_{0} ≤ i ≤ x_{1}$, $y_{0} ≤ j ≤ y_{1}$.\n\nWrite a program to perform two following operations:\n\n- Query($x_{0}$, $y_{0}$, $x_{1}$, $y_{1}$): print the xor sum of the elements of the submatrix $(x_{0}, y_{0}, x_{1}, y_{1})$.\n- Update($x_{0}$, $y_{0}$, $x_{1}$, $y_{1}$, $v$): each element from submatrix $(x_{0}, y_{0}, x_{1}, y_{1})$ gets xor-ed by value $v$.",
    "tutorial": "The motivation of the problem is that x ^ x = 0. x ^ x ^ x \\dots  ^ x (even times) = 0 Update per range, query per element When dealing with complicated problems, it's sometimes a good idea to try solving easier versions of them. Suppose you can query only one element each time (x0 = x1, y0 = y1). To update a submatrix (x0, y0, x1, y1), I'll do following operations. A[x0][y0] ^= val. A[x0][y1 + 1] ^= val. A[x1 + 1][y0] ^= val. A[x1 + 1][y1 + 1] ^= val. To query about an element (X, Y), that element's value will be the xor sum of submatrix A(1, 1, X, Y). Let's take an example. I have a 6x6 matrix and I want to xor all elements from submatrix (2, 2, 3, 4) with a value. The below image should be explanatory how the method works: Next, by (1, 1, X, Y) I'll denote xor sum for this submatrix. \"White\" cells are not influenced by (2, 2, 3, 4) matrix, as matrix (1, 1, X, Y) with (X, Y) a white cell will never intersect it. \"Red\" cells are from the submatrix, the ones that need to be xor-ed. Note that for a red cell, (1, 1, X, Y) will contain the value we need to xor (as it will contain (2, 2)). Next, \"blue\" cells. For this ones (1, 1, X, Y) will contain the value we xor with, despite they shouldn't have it. This is why both (2, 5) and (4, 2) will be xor-ed again by that value, to cancel the xor of (2, 2). Now it's okay, every \"blue\" cell do not contain the xor value in their (1, 1, X, Y). Finally, the \"green\" cells. These ones are intersection between the 2 blue rectangles. This means, in their (1, 1, X, Y) the value we xor with appears 3 times (this means it is contained 1 time). For cancel this, we xor (4, 5) with the value. Now for every green cell (1, 1, X, Y) contains 4 equal values, which cancel each other. You need a data structure do to the following 2 operations: Both operations can be supported by a Fenwick tree 2D. If you don't know this data structure, learn it and come back to this problem after you do this. Coming back to our problem Now, instead of finding an element, I want xor sum of a submatrix. You can note that xor sum of (x0, y0, x1, y1) is (1, 1, x1, y1) ^ (1, 1, x0 - 1, y1) ^ (1, 1, x1, y0 - 1) ^ (1, 1, x0 - 1, y0 - 1). This is a classical problem, the answer is (1, 1, x1, y1) from which I exclude what is not in the matrix: (1, 1, x0 - 1, y1) and (1, 1, x1, y0 - 1). Right now I excluded (1, 1, x0 - 1, y0 - 1) 2 times, so I need to add it one more time. How to get the xor sum of submatrix (1, 1, X, Y)? In brute force approach, I'd take all elements (x, y) with 1 <= x <= X and 1 <= y <= Y and xor their values. Recall the definition of the previous problem, each element (x, y) is the xor sum of A(1, 1, x, y). So the answer is xor sum of all xor sums of A(1, 1, x, y), with 1 <= x <= X and 1 <= y <= Y. We can rewrite that long xor sum. A number A[x][y] appears in exactly (X - x + 1) * (Y - y + 1) terms of xor sum. If (X - x + 1) * (Y - y + 1) is odd, then the value A[x][y] should be xor-ed to the final result exactly once. If (X - x + 1) * (Y - y + 1) is even, it should be ignored. Below, you'll find 4 pictures. They are matrixes with X lines and Y columns. Each picture represents a case: (X odd, Y odd) (X even, Y even) (X even Y odd) (X odd Y even). Can you observe a nice pattern? Elements colored represent those for which (X - x + 1) * (Y - y + 1) is odd. Yep, that's right! There are 4 cases, diving the matrix into 4 disjoint areas. When having a query of form (1, 1, X, Y) you only need specific elements sharing same parity with X and Y. This method works in O(4 * logN * logN) for each operation and is the indented solution. We keep 4 Fenwick trees 2D. We made tests such as solutions having complexity greater than O(4 * logN * logN) per operation to fail.",
    "code": "#include <stdio.h>\n \nint n;\nlong long F[4][1024][1024];\n \ninline int lsb(int X) {\n    return X & -X;\n}\n \nint parity(int x0, int y0) {\n    int res = 0;\n    if (x0 % 2)\n        res += 1;\n    if (y0 % 2)\n        res += 2;\n    return res;\n}\n \nlong long query(int x0, int y0) {\n    long long res = 0;\n    int which = parity(x0, y0);\n    for (int i = x0; i > 0; i -= lsb(i))\n        for (int j = y0; j > 0; j -= lsb(j))\n            res ^= F[which][i][j];\n    return res;\n}\n \nvoid update(int x0, int y0, long long val) {\n    int which = parity(x0, y0);\n    for (int i = x0; i <= n; i += lsb(i))\n        for (int j = y0; j <= n; j += lsb(j))\n            F[which][i][j] ^= val;\n}\n \nint main() {\n    int m;\n    scanf(\"%d%d\", &n, &m);\n    while (m--) {\n        int type;\n        scanf(\"%d\", &type);\n        if (type == 1) {\n            int x0, y0, x1, y1;\n            scanf(\"%d%d%d%d\", &x0, &y0, &x1, &y1);\n            long long res = query(x1, y1);\n            res ^= query(x0 - 1, y1);\n            res ^= query(x1, y0 - 1);\n            res ^= query(x0 - 1, y0 - 1);\n            printf(\"%I64d\\n\", res);\n        } else {\n            int x0, y0, x1, y1;\n            long long val;\n            scanf(\"%d%d%d%d%I64d\", &x0, &y0, &x1, &y1, &val);\n            update(x0, y0, val);\n            update(x0, y1 + 1, val);\n            update(x1 + 1, y0, val);\n            update(x1 + 1, y1 + 1, val);\n        }\n    }\n \n    return 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "341",
    "index": "E",
    "title": "Candies Game",
    "statement": "Iahub is playing an uncommon game. Initially, he has $n$ boxes, numbered 1, 2, 3, $...$, $n$. Each box has some number of candies in it, described by a sequence $a_{1}$, $a_{2}$, $...$, $a_{n}$. The number $a_{k}$ represents the number of candies in box $k$.\n\nThe goal of the game is to move all candies into \\textbf{exactly} two boxes. The rest of $n - 2$ boxes must contain \\textbf{zero} candies. Iahub is allowed to do several (possible zero) moves. At each move he chooses two different boxes $i$ and $j$, such that $a_{i} ≤ a_{j}$. Then, Iahub moves from box $j$ to box $i$ exactly $a_{i}$ candies. Obviously, when two boxes have equal number of candies, box number $j$ becomes empty.\n\nYour task is to give him a set of moves such as Iahub to archive the goal of the game. If Iahub can't win the game for the given configuration of boxes, output -1. Please note that in case there exist a solution, you don't need to print the solution using minimal number of moves.",
    "tutorial": "Key observation Suppose you have 3 boxes containing A, B, C candies (A, B, C all greater than 0). Then, there will be always possible to empty one of boxes using some moves. Proof We can suppose that A <= B <= C. We need some moves such as the minimum from A, B, C will be zero. If we always keep the numbers in order A <= B <= C, it's enough some moves such as A = 0. I'll call this notation (A, B, C). How can we prove that always exist such moves? We can use reductio ad absurdum to prove it. Let's suppose, starting from (A, B, C) we can go to a state (A2, B2, C2). We suppose A2 (A2 > 0) is minimal from every state we can obtain. Since A2 is minimal number of coins that can be obtained and A2 is not zero, the statement is equivalent with we can't empty one chest from configuration (A, B, C). Then, we can prove that from (A2, B2, C2) we can go to a state (A3, B3, C3), where A3 < A2. Obviously, this contradicts our assumption that A2 is minimal of every possible states. If A2 would be minimal, then there won't be any series of moves to empty one chest. But A2 isn't minimal, hence there always exist some moves to empty one chest. Our algorithm so far: void emptyOneBox(int A, int B, int C) { if A is 0, then exit function. Make some moves such as to find another state (A2, B2, C2) with A2 < A. emptyOneBox (A2, B2, C2); } The only problem which needs to be proven now is: given a configuration (A, B, C) with A > 0, can we find another one (A2, B2, C2) such as A2 < A? The answer is always yes, below I'll prove why. Firstly, let's imagine we want to constantly move candies into a box. It doesn't matter yet from where come the candies, what matters is candies arrive into the box. The box has initially X candies. After 1 move, it will have 2 * X candies. After 2 moves, it will have 2 * (2 * X) candies = 4 * X candies. Generally, after K moves, the box will contain 2^K * X candies. We have A < B < C (if 2 numbers are equal, we can make a move and empty 1 box). If we divide B by A, we get from math that B = A * q + r. (obviously, always r < A). What if we can move exactly A * q candies from B to A? Then, our new state would be (r, B2, C2). We have now a number A2 = r, such as A2 < A. How can we move exactly A * q coins? Let's write q in base 2. Making that, q will be written as a sum of powers of 2. Suppose lim is the maximum number such as 2 ^ lim <= q. We get every number k from 0 to lim. For each k, I push into the first box (the box containing initially A candies) a certain number of candies. As proven before, I'll need to push (2 ^ k) * A candies. Let's take a look at the k-th bit from binary representation of q. If k-th bit is 1, B will be written as following: B = A * (2 ^ k + 2 ^ (other_power_1) + 2 ^ (other_power_2) + ...) + r. Hence, I'll be able to move A * (2 ^ k) candies from \"B box\" to \"A box\". Otherwise, I'll move from \"C box\" to \"A box\". It will be always possible to do this move, as C > B and I could do that move from B, too. The proposed algorithm may look abstract, so let's take an example. Suppose A = 3, B = 905 and C = 1024. Can we get less than 3 for this state? B = 3 * 301 + 2. B = 3 * (100101101)2 + 2. K = 0: we need to move (2^0) * 3 coins into A. 0th bit of q is 1, so we can move from B to A. A = 6, B = 3 * (100101100)2 + 2 C = 1024 K = 1: we need to move (2 ^ 1) * 3 coins into A. Since 1th bit of q is already 0, we have to move from C. A = 12, B = 3 * (100101100)2 + 2 C = 1018 K = 2: we need to move (2 ^ 2) * 3 coins into A. 2nd bit of q is 1, so we can move from B. A = 24, B = 3 * (100101000)2 + 2 C = 1018 K = 3: we need to move (2 ^ 3) * 3 coins into A. 3nd bit of q is 1, so we can move from B. A = 48, B = 3 * (100100000)2 + 2 C = 1018 K = 4. we need to move (2 ^ 4) * 3 coins into A. 4th bit of q is 0, we need to move from C. A = 96, B = 3 * (100100000)2 + 2 C = 970 K = 5. we need to move (2 ^ 5) * 3 coins into A. 5th bit of q is 1, so we need to move from B. A = 192, B = 3 * (100000000)2 + 2 C = 970 K = 6 we need to move (2 ^ 6) * 3 coins into A. We mve them from C. A = 384 B = 3 * (100000000)2 + 2 C = 778 K = 7 we need to move (2 ^ 7) * 3 coins into A. We move them from C A = 768 B = 3 * (100000000)2 + 2 C = 394 K=8 Finally, we can move our last 1 bit from B to A. A = 1536 B = 3 * (000000000)2 + 2 C = 394 A = 1536 B = (3 * 0 + 2) C = 394 In the example, from (3, 905, 1024) we can arrive to (2, 394, 1536). Then, with same logic, we can go from (2, 394, 1536) to (0, X, Y), because 394 = 2 * 197 + 0. This is how you could write emptyOneBox() procedure. The remained problem is straight-forward: if initially there are zero or one boxes having candies, the answer is \"-1\". Otherwise, until there are more than 2 boxes having candies, pick 3 boxes arbitrary and apply emptyOneBox().",
    "code": "#include <stdio.h>\n#include <vector>\n#include <algorithm>\n#define mp make_pair\n#define x first\n#define y second\n#define pi pair <int, int>\n \nusing namespace std;\n \npi goodA, goodB, x[1024];\nvector <pi> ans;\n \nvoid emptyOneBox(pi A, pi B, pi C) {\n    if (A.x > B.x)\n        swap(A, B);\n    if (A.x > C.x)\n        swap(A, C);\n    if (B.x > C.x)\n        swap(B, C);\n    if (A.x == 0) {\n        goodA = B;\n        goodB = C;\n        return ;\n    }\n    int val = B.x / A.x;\n    for (int pw = 0; (1 << pw) <= val; ++pw)\n        if (val & (1 << pw)) {\n            ans.push_back(mp(A.y, B.y));\n            B.x -= A.x; A.x *= 2;\n        }\n        else {\n            ans.push_back(mp(A.y, C.y));\n            C.x -= A.x; A.x *= 2;\n        }\n     emptyOneBox(A, B, C);\n}\n \nint main() {\n    int i, n, zero = 0;\n    scanf(\"%d\", &n);\n    for (i = 1; i <= n; ++i) {\n        scanf(\"%d\", &x[i].x);\n        if (x[i].x == 0)\n            ++zero;\n        x[i].y = i;\n    }\n \n    if (n == 3 && x[1].x == 3 && x[2].x == 6 && x[3].x == 9) {\n        printf(\"2\\n2 3\\n1 3\\n\");\n        return 0;\n    }\n \n    if (zero > n - 2) {\n        printf(\"-1\");\n        return 0;\n    }\n \n    sort(x + 1, x + n + 1);\n \n    for (i = 1; x[i].x == 0; ++i);\n    for (; i <= n - 2; ++i) {\n        emptyOneBox(x[i], x[i + 1], x[i + 2]);\n        x[i + 1] = goodA;\n        x[i + 2] = goodB;\n    }\n \n    printf(\"%d\\n\", ans.size());\n    for (i = 0; i < ans.size(); ++i)\n        printf(\"%d %d\\n\", ans[i].x, ans[i].y);\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "342",
    "index": "A",
    "title": "Xenia and Divisors",
    "statement": "Xenia the mathematician has a sequence consisting of $n$ ($n$ is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three $a, b, c$ the following conditions held:\n\n- $a < b < c$;\n- $a$ divides $b$, $b$ divides $c$.\n\nNaturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has $\\frac{\\eta}{\\lambda}$ groups of three.\n\nHelp Xenia, find the required partition or else say that it doesn't exist.",
    "tutorial": "In this problem you should guess that exists only three valid groups of three 1) 1, 2, 4 2) 1, 2, 6 3) 1, 3, 6 (You can see that integers 5 and 7 are bad). So, we will greedy take these groups of three. If some integers will be not used, the answer is -1. In other case, print found answer.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "342",
    "index": "B",
    "title": "Xenia and Spies",
    "statement": "Xenia the vigorous detective faced $n$ $(n ≥ 2)$ foreign spies lined up in a row. We'll consider the spies numbered from 1 to $n$ from left to right.\n\nSpy $s$ has an important note. He has to pass the note to spy $f$. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is $x$, he can pass the note to another spy, either $x - 1$ or $x + 1$ (if $x = 1$ or $x = n$, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.\n\nBut nothing is that easy. During $m$ steps Xenia watches some spies attentively. Specifically, during step $t_{i}$ (steps are numbered from 1) Xenia watches spies numbers $l_{i}, l_{i} + 1, l_{i} + 2, ..., r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$. Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.\n\nYou've got $s$ and $f$. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy $s$ to spy $f$ as quickly as possible (in the minimum number of steps).",
    "tutorial": "The problem is solved by greedy algorithm. We will pass the note only in correct direction. Also, if we can pass the note at the current moment of time, we do it. In other case, we will hold it and don't give it to neighbors (we can make this action at any moment of time). Obviously this algorithm is correct. You should only implement it carefully.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "342",
    "index": "C",
    "title": "Cupboard and Balloons",
    "statement": "A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius $r$ (the cupboard's top) and two walls of height $h$ (the cupboard's sides). The cupboard's depth is $r$, that is, it looks like a rectangle with base $r$ and height $h + r$ from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right).\n\nXenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius $\\scriptstyle{\\frac{r}{2}}$. Help Xenia calculate the maximum number of balloons she can put in her cupboard.\n\nYou can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin.",
    "tutorial": "In the problem you should carefully get formula. The optimal solution put marbles by two in a row. And then put one marble upon others if it possible. The most difficulties were to deal with this last phase. In comments to the post were given formulas how to put the last marble (exactly in the middle). And there was a good beautiful illustration, which describes the situation.",
    "tags": [
      "geometry"
    ],
    "rating": 1900
  },
  {
    "contest_id": "342",
    "index": "D",
    "title": "Xenia and Dominoes",
    "statement": "Xenia likes puzzles very much. She is especially fond of the puzzles that consist of domino pieces. Look at the picture that shows one of such puzzles.\n\nA puzzle is a $3 × n$ table with forbidden cells (black squares) containing dominoes (colored rectangles on the picture). A puzzle is called correct if it meets the following conditions:\n\n- each domino occupies exactly two non-forbidden cells of the table;\n- no two dominoes occupy the same table cell;\n- exactly one non-forbidden cell of the table is unoccupied by any domino (it is marked by a circle in the picture).\n\nTo solve the puzzle, you need multiple steps to transport an empty cell from the starting position to some specified position. A move is transporting a domino to the empty cell, provided that the puzzle stays correct. \\textbf{The horizontal dominoes can be moved only horizontally, and vertical dominoes can be moved only vertically. You can't rotate dominoes.} The picture shows a probable move.\n\nXenia has a $3 × n$ table with forbidden cells and a cell marked with a circle. Also, Xenia has very many identical dominoes. Now Xenia is wondering, how many distinct correct puzzles she can make if she puts dominoes on the existing table. Also, Xenia wants the circle-marked cell to be empty in the resulting puzzle. The puzzle must contain at least one move.\n\nHelp Xenia, count the described number of puzzles. As the described number can be rather large, print the remainder after dividing it by $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "In the problem you can count number of correct puzzles or substract number of incorrect puzzles from number of all puzzles. In any case you should count DP, where the state is $(j, mask)$ - $j$ - number of the last full column, $mask$ - mask of the last column. This problem is equivalent to the well known problem about domino tiling or the problem about parquet. To get the solution of the whole problem I did the following. I try to attach one domino to each of 4 directions, then paint all three cells in black and count the number of correct puzzles. But in this case you will count some solutions several number of times. So you need to use inclusion exclusion formula for these 4 directions.",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "342",
    "index": "E",
    "title": "Xenia and Tree",
    "statement": "Xenia the programmer has a tree consisting of $n$ nodes. We will consider the tree nodes indexed from 1 to $n$. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.\n\nThe distance between two tree nodes $v$ and $u$ is the number of edges in the shortest path between $v$ and $u$.\n\nXenia needs to learn how to quickly execute queries of two types:\n\n- paint a specified blue node in red;\n- calculate which red node is the closest to the given one and print the shortest distance to the closest red node.\n\nYour task is to write a program which will execute the described queries.",
    "tutorial": "The problem can be solved in different ways. The most easy idea is sqrt-optimization. Split all queries into $sqrt(m)$ blocks. Each block we will process separately. Before processing each block, we should calculate minimum distances from every node to the closest red node using bfs. To answer the query we should update this value by shortest distances to red nodes in current block. The solution becomes simple. Every $sqrt(m)$ queries we make simple bfs and for every node $v$ WE calculate value $d[v]$ - the shortest distance to some red node from node $v$. Then to answer the query of type 2 you should calculate $min(d[v], dist(v, u))$, where $u$ - every red node, which becomes red in current block of length $sqrt(m)$. Distance between two nodes $dist(u, v)$ can be got using preprocessing for lca.",
    "tags": [
      "data structures",
      "divide and conquer",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "343",
    "index": "A",
    "title": "Rational Resistance",
    "statement": "Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.\n\nHowever, all Mike has is lots of identical resistors with unit resistance $R_{0} = 1$. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:\n\n- one resistor;\n- an element and \\textbf{one} resistor plugged in sequence;\n- an element and \\textbf{one} resistor plugged in parallel.\n\nWith the consecutive connection the resistance of the new element equals $R = R_{e} + R_{0}$. With the parallel connection the resistance of the new element equals $\\begin{array}{l}{{R=}}\\\\ {{\\frac{1}{\\pi_{c}}+\\frac{1}{\\pi_{0}}}}\\end{array}$. In this case $R_{e}$ equals the resistance of the element being connected.\n\nMike needs to assemble an element with a resistance equal to the fraction $\\overset{\\stackrel{\\wedge}{a}}{b}$. Determine the smallest possible number of resistors he needs to make such an element.",
    "tutorial": "If a fraction $\\overset{\\stackrel{\\rightarrow}}{b}$ can be obtained with $k$ resistors, then it is simple to calculate that we can obtain fractions $\\frac{a+b}{b}$ and $\\frac{a}{a+b}$ with $k + 1$ resistors. So adding one resistor means performing one operation backwards in Euclidean algorithm. That means that the answer is equal to the number of steps in standard Euclidean algorithm. Solution complexity: $O(\\log(\\operatorname*{max}(a,b)))$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "343",
    "index": "B",
    "title": "Alternating Current",
    "statement": "Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.\n\nThe device is powered by two wires \"plus\" and \"minus\". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view):\n\nMike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the \"plus\" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and \\textbf{without moving} the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.\n\nTo understand the problem better please read the notes to the test samples.",
    "tutorial": "Let us solve the following problem first: we are given a string of symbols A and B. If the $i$-th symbol is $A$, then at the $i$-th step the upper wire (see figure) is being put over the lower wire. If the $i$-th symbol is $B$, the lower wire is being put over the upper wire at $i$-th step. Observe that if some two symbols $A$ and $B$ are adjacent, we can untangle this place, throw the symbols out and obtain the string of length two symbols less. So the wires can be untangled iff the number of A's and B's in the string is the same. The given problem can be reduced to the described in a following fashion: in each odd position we change - to B and + to A. In each even position we change - to A and + to B. The reduction is correct, since on each even position the order of - and + are always swapped, and in each odd position their order is the same as in the beginning. Solution complexity: $O(n)$.",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "343",
    "index": "C",
    "title": "Read Time",
    "statement": "Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but $n$ different heads that can read data in parallel.\n\nWhen viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the $i$-th reading head is above the track number $h_{i}$. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered \\underline{read} if at least one head has visited this track. In particular, all of the tracks numbered $h_{1}$, $h_{2}$, $...$, $h_{n}$ have been read at the beginning of the operation.\n\nMike needs to read the data on $m$ distinct tracks with numbers $p_{1}$, $p_{2}$, $...$, $p_{m}$. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.",
    "tutorial": "Let's search the answer $t$ with the binary search. Fix some value of $t$. Look at the first head from the left $h[i]$ that can read track $p[0]$. If $p[0] > h[i]$, then $h[i]$ goes to the right $t$ seconds and reads all tracks on its way. Otherwise if $p[0]  \\le  h[i]$, then the head has two choices: Obviously, for $h[i]$ it is more advantageous to visit the track positioned as much as possible to the right. So we choose by $\\operatorname*{max}({\\frac{t-(h[i]-p(0])}{2}},t-2\\cdot(h[i]-p[0]))$. Then we move the pointer onto the first unread track, and repeat the algorithm for $h[i + 1]$, and so on with each head. Solution complexity: $O((n+m)\\log\\operatorname*{max}(h[i],p[i]))$.",
    "tags": [
      "binary search",
      "greedy",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "343",
    "index": "D",
    "title": "Water Tree",
    "statement": "Mad scientist Mike has constructed a rooted tree, which consists of $n$ vertices. Each vertex is a reservoir which can be either empty or filled with water.\n\nThe vertices of the tree are numbered from 1 to $n$ with the root at vertex 1. For each vertex, the reservoirs of its children are located below the reservoir of this vertex, and the vertex is connected with each of the children by a pipe through which water can flow downwards.\n\nMike wants to do the following operations with the tree:\n\n- Fill vertex $v$ with water. Then $v$ and all its children are filled with water.\n- Empty vertex $v$. Then $v$ and all its ancestors are emptied.\n- Determine whether vertex $v$ is filled with water at the moment.\n\nInitially all vertices of the tree are empty.Mike has already compiled a full list of operations that he wants to perform in order. Before experimenting with the tree Mike decided to run the list through a simulation. Help Mike determine what results will he get after performing all the operations.",
    "tutorial": "Let's learn how to color a whole subtree. For that enumerate all vertices in post-order DFS. Then each subtree covers a single continious vertex number segment. For each vertex we store the bounds of such segment for a subtree with a root in this vertex. Then to color a subtree means to color a segment in a segment tree. Then create a segment tree that has a following property: if a vertex $v$ was emptied, and is still empty, then this vertex is colored in the segment tree. In the beginning \"empty\" all the vertices. That is, color all the vertices in the segment tree. With this tree we can efficiently process the queries: Fill a vertex $v$. Clean the interval for the subtree of $v$. If before that some vertex of a subtree was empty, color the parent of $v$. Empty a vertex $v$. Color the vertex $v$ in the segment tree. Reply whether a vertex $v$ is filled. If in the segment tree at least one vertex is colored, then there is such a descendant of $v$ that is empty now, so the vertex $v$ is not filled. Shtrix noted that essentially the same solution can be implemented with only a single set. Solution complexity: $O(q\\log n)$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "343",
    "index": "E",
    "title": "Pumping Stations",
    "statement": "Mad scientist Mike has applied for a job. His task is to manage a system of water pumping stations.\n\nThe system consists of $n$ pumping stations, which are numbered by integers from 1 to $n$. Some pairs of stations are connected by bidirectional pipes through which water can flow in either direction (but only in one at a time). For each pipe you know its bandwidth — the maximum number of liters of water that can flow through it in one hour. Each pumping station can pump incoming water from some stations to other stations through the pipes, provided that in one hour the total influx of water to the station is equal to the total outflux of water from the station.\n\nIt is Mike's responsibility to pump water between stations. From station $a$ to station $b$ through the pipes (possibly through other stations) within one hour one can transmit a certain number of liters of water according to the rules described above. During this time, water from other stations can not flow into station $a$, and can not flow out of the station $b$. However, any amount of water can flow out of station $a$ or in station $b$. If a total of $x$ litres of water flows out of the station $a$ in an hour, then Mike gets $x$ bollars more to his salary.\n\nTo get paid, Mike needs to work for $n - 1$ days, according to the contract. On the first day he selects two stations $v_{1}$ and $v_{2}$, and within one hour he pumps a certain amount of water from $v_{1}$ to $v_{2}$. Next, on the $i$-th day Mike chooses a station $v_{i + 1}$ that has been never selected before, and pumps a certain amount of water out of the station $v_{i}$ to station $v_{i + 1}$ for one hour. The quantity of water he pumps on the $i$-th day \\textbf{does not depend} on the amount of water pumped on the $(i - 1)$-th day.\n\nMike needs to earn as much bollars as he can for his projects. Help Mike find such a permutation of station numbers $v_{1}$, $v_{2}$, $...$, $v_{n}$ so Mike will be able to earn the highest possible salary.",
    "tutorial": "In this problem we are asked to find such graph vertex permutation that maximizes the sum of the maximum flows sent between each two consequtive vertices in the permutation. The problem can be solved with Gomory-Hu tree data structure. For a given weighted graph the tree has the following properties: Surprisingly, such a tree exists for any weighted graph, and can be built in $O(n \\cdot maxFlow)$. It appears that the answer to the problem is equal to the sum of the edge weights in this tree. We prove this statement by induction on the number of the tree vertices. Pick the edge $(u, v)$ with the smallest weight in the tree. Consider that in an optimal permutation more than one path between two adjacent verteces in the permutation passes through this edge. Erase all these paths, then each of the $u$ and $v$ subtrees holds a set of disjoint remaining paths from the permutation. For each set, join all the paths in one chain, obtaining two chains. These chains we join by a path $s$ that goes trough the edge $(u, v)$. Thus we have built a permutation that is not worse than the considered one. For a path $s$ the edge $(u, v)$ is the smallest, so the flow along this path is equal to the weight of this edge. It follows from the induction that in subtrees $u$ and $v$ the answer is equal to the sum of edges. By adding the weight of edge $(u, v)$, we get the desired result. From the last paragraph it is clear how to build such a permutation: take the smallest edge, obtain two chains from the vertex subtrees recursively, and add them together to form a one chain. Since there are not many vertices, we can do this part in $O(n^{2})$. Solution complexity: $O(n \\cdot maxFlow)$.",
    "tags": [
      "brute force",
      "dfs and similar",
      "divide and conquer",
      "flows",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "344",
    "index": "A",
    "title": "Magnets",
    "statement": "Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a \"plus\") and negative (a \"minus\"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.\n\nMike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.\n\nMike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.",
    "tutorial": "By the definition each block consists of a number of consequent and equally oriented dominoes. That means that in places where adjacent dominoes are not oriented equally, one block ends and another block starts. So, if there are $x$ such places, the answer is equal to $x + 1$. Solution complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "344",
    "index": "B",
    "title": "Simple Molecules",
    "statement": "Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.\n\nA molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form \\textbf{one or multiple} bonds with any other atom, but it cannot form a bond with itself. The number of bonds of an atom in the molecule must be equal to its valence number.\n\nMike knows valence numbers of the three atoms. Find a molecule that can be built from these atoms according to the stated rules, or determine that it is impossible.",
    "tutorial": "First solution. First, the sum $a + b + c$ should be even, since each bond adds 2 to the sum. Now let $x$, $y$, $z$ be the number of bonds between 1st and 2nd, 2nd and 3rd, 3rd and 1st atoms, accordingly. So we have to solve the system $x + z = a$, $y + x = b$, $z + y = c$. Now observe that the solution to the system is the length of the tangents on the triangle with sides of length $a$, $b$, $c$ to its inscribed circle, and are equal to $\\textstyle{\\frac{b+c-a}{2}}$, $\\textstyle{\\frac{c+a-b}{2}}$, $\\textstyle{\\frac{b+a-c}{2}}$. If the problem asked only the possibility of building such a molecule, we could just check if there exists (possibly degenerate) triangle with sides $a$, $b$, $c$. Second solution. Bruteforce all $x$ values. For a fixed $x$ values of $y$ and $z$ are defined uniquely: $y = b - x$, $z = a - x$. Solution complexity: $O(1) / O(n)$.",
    "tags": [
      "brute force",
      "graphs",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "346",
    "index": "A",
    "title": "Alice and Bob",
    "statement": "It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of $n$ distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers $x$ and $y$ from the set, such that the set doesn't contain their absolute difference $|x - y|$. Then this player adds integer $|x - y|$ to the set (so, the size of the set increases by one).\n\nIf the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.",
    "tutorial": "First, no matter what happend, the number set we get at the very endding will be same all the time. Let's say $d = gcd{x_{i}$}. Then the set in the endding will be some things like {$d$, $2d$, $3d$, ... $max{x_{i}$}}. So there is always $max{x_{i}} / d$ - $n$ rounds. And what we should do rest is to check the parity of this value.",
    "tags": [
      "games",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "346",
    "index": "B",
    "title": "Lucky Common Subsequence",
    "statement": "In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.\n\nYou are given two strings $s_{1}$, $s_{2}$ and another string called $virus$. Your task is to find the longest common subsequence of $s_{1}$ and $s_{2}$, such that it doesn't contain $virus$ as a substring.",
    "tutorial": "This is a rather classical problem, let's say if there is no virus, then it is the classical **LCS ** problem. You can solve this by a $O(n^{2})$ dynamic programing. When consider about the virus, we should add 1 more dimension on the state to trace the growth of the virus. It can be done by wheather Aho-Corasick automation, or KMP when there is only one virus in this case. The overall time complexity is $O(n^{3})$.",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "346",
    "index": "C",
    "title": "Number Transformation II",
    "statement": "You are given a sequence of positive integers $x_{1}, x_{2}, ..., x_{n}$ and two non-negative integers $a$ and $b$. Your task is to transform $a$ into $b$. To do that, you can perform the following moves:\n\n- subtract 1 from the current $a$;\n- subtract $a$ mod $x_{i}$ $(1 ≤ i ≤ n)$ from the current $a$.\n\nOperation $a$ mod $x_{i}$ means taking the remainder after division of number $a$ by number $x_{i}$.\n\nNow you want to know the minimum number of moves needed to transform $a$ into $b$.",
    "tutorial": "I bet there is a few people know the greedy method even if he/she have solved the early version before. Codeforces #153 Div 1. Problem C. Number Transformation Let dp[k] denotes the minimum number of steps to transform b+k to b. In each step, you could only choose i which makes b+k-(b+k) mod x[i] minimal to calc dp[k]. It works bacause dp[0..k-1] is a monotone increasing function. Proof: - Say dp[k]=dp[k-t]+1.If t==1, then dp[0..k] is monotone increasing obviously.Otherwise dp[k-1]<=dp[k-t]+1=dp[k] (there must exist a x[i] makes b+k-1 also transform to b+k-t,and it is not necessarily the optimal decision of dp[k-1]). So dp[k] is a monotone increasing function, we can greedily calc dp[a-b]. In the first glance, it looks like something which will run in square complexity. But actually is linear. That is because, we could cut exactly max{$x_{i}$} in each 2 step. It can be proof by induction. So the remians work is to delete those same $x_{i}$, and watch out some situation could cause degeneration. Many of us failed in this last step and got TLE",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "346",
    "index": "D",
    "title": "Robot Control",
    "statement": "The boss of the Company of Robot is a cruel man. His motto is \"Move forward Or Die!\". And that is exactly what his company's product do. Look at the behavior of the company's robot when it is walking in the directed graph. This behavior has been called \"Three Laws of Robotics\":\n\n- Law 1. The Robot will destroy itself when it visits a vertex of the graph which it has already visited.\n- Law 2. The Robot will destroy itself when it has no way to go (that is when it reaches a vertex whose out-degree is zero).\n- Law 3. The Robot will move randomly when it has multiple ways to move (that is when it reach a vertex whose out-degree is more than one). Of course, the robot can move only along the directed edges of the graph.\n\nCan you imagine a robot behaving like that? That's why they are sold at a very low price, just for those who are short of money, including mzry1992, of course. mzry1992 has such a robot, and she wants to move it from vertex $s$ to vertex $t$ in a directed graph safely without self-destruction. Luckily, she can send her robot special orders at each vertex. A special order shows the robot which way to move, if it has multiple ways to move (to prevent random moving of the robot according to Law 3). When the robot reaches vertex $t$, mzry1992 takes it off the graph immediately. So you can see that, as long as there exists a path from $s$ to $t$, she can always find a way to reach the goal (whatever the vertex $t$ has the outdegree of zero or not).\n\n\\begin{center}\nSample 2\n\\end{center}\n\nHowever, sending orders is expensive, so your task is to find the minimum number of orders mzry1992 needs to send in the worst case. Please note that mzry1992 can give orders to the robot \\textbf{while it is walking} on the graph. Look at the first sample to clarify that part of the problem.",
    "tutorial": "Let's dp from t to s. dp[u] = min(min(dp[v]) + 1 , max(dp[v])) | u->v Here dp[u] means, the minimum number of orders mzry1992 needs to send in the worst case. The left-hand-side is sending order while the right-hand side is not. At the beginning, we have dp[t] = 1, and dp[s] will be the answer. We can see there is circular dependence in this equation, in this situation, one standard method is using Bellman-Ford algorithm to evaluate the dp function. But it is not appropriate for this problem. (In fact, we add a part of targeted datas in pretest, these datas are enough to block most of our Bellman-Ford algorithm, although there is still a few participator can get accepted by Bellman-Ford algorithm during the contest. Check rares.buhai's solution dp[u] = min(min(dp[v]) + 1 , max(dp[v])) | u->v The expected solution is evaluating the dp function as the increased value of dp[u] itself. Further analysis shows, wheather we decided sending order or not in u can be judged as the out-degree of u. while (!Q.empty()) { u = Q.front(), Q.pop_front() for each edge from v to u --out_degree[v] if (out_degree[v] == 0) { relax dp[v] by dp[u] if success, add v to the front of Q } else{ relax dp[v] by dp[u] + 1 if success, add v to the back of Q } }",
    "code": "#include <cstdio>\n#include <vector>\n#include <memory.h>\nusing namespace std;\nconst int MX=1000100,MD=2*MX;\nint n,m,i,j,k,x,y,z,fi,fr,v[MX],p[MX],q[2*MD];\nvector<int> g[MX],o[MX];\nbool u[MX];\nint main() {\n  scanf(\"%d%d\",&n,&m);\n  for (i=0; i<m; i++) {\n    scanf(\"%d%d\",&x,&y);\n\tg[x].push_back(y);\n\to[y].push_back(x);\n\tv[x]++;\n  }\n  scanf(\"%d%d\",&x,&y);\n  memset(p,255,sizeof(p));\n  p[y]=0; q[MD]=y; fi=MD; fr=fi+1;\n  while (fi<fr) {\n    i=q[fi++];\n\tif (i==x) break;\n\tif (u[i]) continue;\n\tu[i]=true;\n\tfor (j=0; j<o[i].size(); j++) {\n\t  y=o[i][j];\n\t  if (--v[y]==0) {\n\t\tif (p[i]<p[y] || p[y]==-1) {\n\t\t  p[y]=p[i];\n\t\t  q[--fi]=y;\n\t\t}\n\t  } else if (p[y]==-1) {\n\t    p[y]=p[i]+1;\n\t\tq[fr++]=y;\n\t  }\n\t}\n  }\n  printf(\"%d\\n\",p[x]);\n  return 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "346",
    "index": "E",
    "title": "Doodle Jump",
    "statement": "\\underline{In Doodle Jump the aim is to guide a four-legged creature called \"The Doodler\" up a never-ending series of platforms without falling. — Wikipedia.}\n\nIt is a very popular game and xiaodao likes it very much. One day when playing the game she wondered whether there exists a platform that the doodler couldn't reach due to the limits of its jumping ability. Consider the following problem.\n\nThere are $n$ platforms. The height of the $x$-th ($1 ≤ x ≤ n$) platform is $a·x$ mod $p$, where $a$ and $p$ are positive co-prime integers. The maximum possible height of a Doodler's jump is $h$. That is, it can jump from height $h_{1}$ to height $h_{2}$ ($h_{1} < h_{2}$) if $h_{2} - h_{1} ≤ h$. Initially, the Doodler is on the ground, the height of which is 0. The question is whether it can reach the highest platform or not.\n\nFor example, when $a = 7$, $n = 4$, $p = 12$, $h = 2$, the heights of the platforms are $7$, $2$, $9$, $4$ as in the picture below. With the first jump the Doodler can jump to the platform at height $2$, with the second one the Doodler can jump to the platform at height $4$, but then it can't jump to any of the higher platforms. So, it can't reach the highest platform.\n\nUser xiaodao thought about the problem for a long time but didn't solve it, so she asks you for help. Also, she has a lot of instances of the problem. Your task is solve all of these instances.",
    "tutorial": "Take $a$ =5, $p$ =23 for example ... Divided the numbers in group. 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16 21 3 8 13 18We start a new group when the number > P We found the difference between the elements of the first group is 5, The subsequent is filling some gap between the them ... After some observation we could found that we should only consider into one gap ...(e.g. [0, 5] or [15, 20] or [20, 25] ... ) 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16That says .. $a$ =5, $p$ =23 is roughly equal to some things in small scale? So let's check it in detail. Lemma 1. In any case, the gap after 20 won't better than any gap before it. 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16For example, in this case, the gap after 20 is: 20, 22 And it has 16 in [15, 17] but no 21. Is there any chance that [20, 23] is better than [15, 20]? No, that is because, when there is no 21, then (19+5)%23 = 1, go to next floor. and there is no corresponding gap after 20 ([22, 24]) for this gap ([17, 19]) So we only need to consider [15, 20] ... and we found [15, 20] is roughly equal to [0, 5] e.g. : 15 20 17 19 16 18 equal: 0 5 2 4 1 3we say 'roughly' because we havn't check some boundary case like there is 3 but on 18 ... 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16 21 3 8 13 If it happend, we should remove the number 3. .. If we can remove the element 5, then we can from a=5, p=23 to a'=2, p'=5 ...(n' = an/p, a' = a-p%a, if there is 3 but no 18, n'=n'-1) The rest things is to discuss wheather 5 is necessary or not. Let's we have: 0 2 4 1 3If the 2*n'<5, then there is only one floor, the answer is max(2, 5-2*n'). If there is more than one floor, we could conclude that 5 is useless. Proof: Elemets in 1st floor is: 0 a 2a 3a ...Let's say the maximum elements in 1st floor is x, then the minimum element in the 2nd floor is b0 = x+a-p, because b0 - a = x-p, so the difference between b0 and a is equal to the difference between x and p. That is, we can consider [b0, a] rather than [x, p], when there is a element insert in [b0, a], there must be some element insert in [x, p] in the same position. So we have have succeeded to transform our original problem into a small one. Of couse, this problem havn't been solved, we haven't consider the time complexity. Says a' = a - p%a, when p = a+1, then a' = a-1, but we have $a$ equal to 10^9, it won't work. But, let's we have A1, A2, ... An ... and we subtract $d$ from all of them, the answer won't be changed. So we can use p%a substitute for a-p%a, this is equivalent to we subtract %p% from all of them ... So we set a' = min(a-p%a, p%a), so a'<=a/2, therefore, the final time complexity is $O(logn)$.",
    "code": "import java.io.InputStreamReader;\nimport java.io.IOException;\nimport java.io.BufferedReader;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.util.StringTokenizer;\nimport java.math.BigInteger;\nimport java.io.InputStream;\n \n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n */\npublic class Main {\n\tpublic static void main(String[] args) {\n\t\tInputStream inputStream = System.in;\n\t\tOutputStream outputStream = System.out;\n\t\tInputReader in = new InputReader(inputStream);\n\t\tPrintWriter out = new PrintWriter(outputStream);\n\t\tTaskE solver = new TaskE();\n\t\tint testCount = Integer.parseInt(in.next());\n\t\tfor (int i = 1; i <= testCount; i++)\n\t\t\tsolver.solve(i, in, out);\n\t\tout.close();\n\t}\n}\n \nclass TaskE {\n    int firstSmallMultiple(int mult, int modulo, int upto) {\n        mult %= modulo;\n        if (mult <= upto)\n            return 1;\n        if (upto == 0)\n            return modulo;\n        return (int) ((firstLargeMultiple(modulo, mult, mult - upto) * (long) modulo + mult - 1) / mult);\n    }\n \n    private int firstLargeMultiple(int mult, int modulo, int atleast) {\n        mult %= modulo;\n        if (atleast == 0) throw new RuntimeException();\n        if (mult == 0)\n            return modulo;\n        if ((atleast + mult - 1) / mult * mult <= modulo)\n            return (atleast + mult - 1) / mult;\n        return (int) ((firstSmallMultiple(modulo, mult, modulo - atleast) * (long) modulo + atleast - modulo + mult - 1) / mult);\n    }\n \n    public void solve(int testNumber, InputReader in, PrintWriter out) {\n        int a = in.nextInt();\n        int n = in.nextInt();\n        int p = in.nextInt();\n        int h = in.nextInt();\n        a %= p;\n        int left = firstSmallMultiple(a, p, h);\n        int right = firstSmallMultiple(p - a, p, h);\n        int atleast = Math.max(0, n - left + 1);\n        int atmost = Math.min(n, right - 1);\n        if (atleast < atmost) {\n            out.println(\"NO\");\n            return;\n        }\n        if (atleast > atmost) {\n            out.println(\"YES\");\n            return;\n        }\n        int max = p - firstSmallMultiple(BigInteger.valueOf(p - a).modInverse(BigInteger.valueOf(p)).intValue(), p, n);\n        if ((atleast * (long) a) % p == max) {\n            out.println(\"YES\");\n        } else {\n            out.println(\"NO\");\n        }\n    }\n}\n \nclass InputReader {\n    public BufferedReader reader;\n    public StringTokenizer tokenizer;\n \n    public InputReader(InputStream stream) {\n        reader = new BufferedReader(new InputStreamReader(stream));\n        tokenizer = null;\n    }\n \n    public String next() {\n        while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n            try {\n                tokenizer = new StringTokenizer(reader.readLine());\n            } catch (IOException e) {\n                throw new RuntimeException(e);\n            }\n        }\n        return tokenizer.nextToken();\n    }\n \n    public int nextInt() {\n        return Integer.parseInt(next());\n    }\n \n    }\n ",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 3000
  },
  {
    "contest_id": "348",
    "index": "A",
    "title": "Mafia",
    "statement": "One day $n$ friends gathered together to play \"Mafia\". During each round of the game some player must be the supervisor and other $n - 1$ people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the $i$-th person wants to play $a_{i}$ rounds. What is the minimum number of rounds of the \"Mafia\" game they need to play to let each person play at least as many rounds as they want?",
    "tutorial": "In the problem you need to find out how many games you need to play in order to make all people happy. It means that each of them played as many games as he wanted. Let the answer be $x$ games. Notice that $max(a_{1}, a_{2},  \\dots , a_{n})  \\le  x$. Then $i$-th player can be game supervisor in $x-a_{i}$ games. If we sum up we get $(x-a_{1})+(x-a_{2})+\\ldots+(x-a_{n})=n\\cdot x-\\sum a_{i}$ - it's the number of games in which players are ready to be supervisor. This number must be greater or equal to $x$ - our answer. $x\\leq n\\cdot x-\\sum a_{i}$ $\\sum a_{i}\\leq x\\cdot(n-1)$ ${\\frac{\\sum_{a=1}^{a_{i}}}{n!}}\\leq x$ $x=\\textstyle\\bigcap_{n-1}^{\\sum_{i}}\\left|$ Don't forget about that condition: $max(a_{1}, a_{2},  \\dots , a_{n})  \\le  x$.",
    "tags": [
      "binary search",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "348",
    "index": "B",
    "title": "Apple Tree",
    "statement": "You are given a rooted tree with $n$ vertices. In each leaf vertex there's a single integer — the number of apples in this vertex.\n\nThe weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.\n\nA tree is balanced if for every vertex $v$ of the tree all its subtrees, corresponding to the children of vertex $v$, are of equal weight.\n\nCount the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.",
    "tutorial": "In the problem you need to find out minimal number of apples that you need to remove in order to make tree balanced. Notice, that if we know the value in the root then we know values in all other vertices. The value in the leaf is equal to the value in the root divided to the product of the powers of all vertices on the path between root and leaf. For every vertex let's calculate $d_{i}$ - minimal number in that vertex (not zero) in order to make tree balanced. For leaves $d_{i} = 1$, for all other vertices $d_{i}$ is equal to $k \\cdot lcm(d_{j}_{1}, d_{j}_{2}, ..., d_{j}_{k})$, where $j_{1}, j_{2}, ..., j_{k}$ - sons of the vertex $i$. Let's calculate $s_{i}$ - sum in the subtree of the vertex $i$. All that can be done using one depth first search from the root of the tree. Using second depth first search one can calculate for every vertex maximal number that we can write in it and satisfty all conditions. More precisely, given vertex $i$ and $k$ of its sons $j_{1}, j_{2}, ..., j_{k}$. Then if $m = min(s_{j}_{1}, s_{j}_{2}, ..., s_{j}_{k})$ and $t={\\frac{d\\mathbf{t}}{k}}$ - minimal number, that we can write to the sons of vertex $i$, then it's worth to write numbers $x=\\left\\lfloor{\\frac{m}{t}}\\right\\rfloor\\cdot t$ to the sons of vertex $i$. Remains $\\sum s_{j}-k\\cdot x$ we add to the answer.",
    "tags": [
      "dfs and similar",
      "number theory",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "348",
    "index": "C",
    "title": "Subset Sums",
    "statement": "You are given an array $a_{1}, a_{2}, ..., a_{n}$ and $m$ sets $S_{1}, S_{2}, ..., S_{m}$ of indices of elements of this array. Let's denote $S_{k} = {S_{k, i}} (1 ≤ i ≤ |S_{k}|)$. In other words, $S_{k, i}$ is some element from set $S_{k}$.\n\nIn this problem you have to answer $q$ queries of the two types:\n\n- Find the sum of elements with indices from set $S_{k}$: $\\sum_{i=1}^{N_{k}}a_{S_{k,i}}$. The query format is \"? k\".\n- Add number $x$ to all elements at indices from set $S_{k}$: $a_{Sk, i}$ is replaced by $a_{Sk, i} + x$ for all $i$ $(1 ≤ i ≤ |S_{k}|)$. The query format is \"+ k x\".\n\nAfter each first type query print the required sum.",
    "tutorial": "This problem is about data structures. First step of the solution is to divide sets to heavy and light. Light ones are those that contains less than $\\sqrt{n}$ elements. All other sets are heavy. Key observation is that every light set contains less than $\\sqrt{n}$ elements and number of heavy sets doesn't exceed $\\sqrt{n}$ because we have upper bound for sum of the sizes of all sets. In order to effectively answer queries, for every set (both light and heavy) we calculate size of the intersection of this set and each heavy set. It can be done with time and memory $O(n{\\sqrt{n}})$. For every heavy set we create boolean array of size $O(n)$. In $i$-th cell of this array we store how many elements $i$ in given set. Then for each element and each heavy set we can check for $O(1)$ time whether element is in the set. Now let's consider 4 possible cases: Add to the light set. Traverse all numbers in the set and add the value from the query to each of them. Then traverse all heavy sets and add (size of intersection * the value from the query). Time is $2\\cdot{\\sqrt{n}}=O(\\sqrt{n})$. Add to the heavy set. Just update the counter for the heavy set. Time is $O(1)$. Answer to the query for the light set. Traverse all numbers in the set and add values to the answer. Then traverse all heavy sets and add to the answer (answer for this heavy set * size of intersection with the set in the query). Time is $2\\cdot{\\sqrt{n}}=O(\\sqrt{n})$. Answer to the query for the heavy set. Take already calculated answer, then traverse all heavy sets and add (answer for this heavy set * size of intersection with the set in the query). Time is $2\\cdot{\\sqrt{n}}=O(\\sqrt{n})$. We have $O(n)$ queries so total time is $O(n{\\sqrt{n}})$.",
    "tags": [
      "brute force",
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "348",
    "index": "D",
    "title": "Turtles",
    "statement": "You've got a table of size $n × m$. We'll consider the table rows numbered from top to bottom 1 through $n$, and the columns numbered from left to right 1 through $m$. Then we'll denote the cell in row $x$ and column $y$ as $(x, y)$.\n\nInitially cell $(1, 1)$ contains two similar turtles. Both turtles want to get to cell $(n, m)$. Some cells of the table have obstacles but it is guaranteed that there aren't any obstacles in the upper left and lower right corner. A turtle (one or the other) can go from cell $(x, y)$ to one of two cells $(x + 1, y)$ and $(x, y + 1)$, as long as the required cell doesn't contain an obstacle. The turtles have had an argument so they don't want to have any chance of meeting each other along the way. Help them find the number of ways in which they can go from cell $(1, 1)$ to cell $(n, m)$.\n\nMore formally, find the number of pairs of non-intersecting ways from cell $(1, 1)$ to cell $(n, m)$ modulo $1000000007$ $(10^{9} + 7)$. Two ways are called non-intersecting if they have exactly two common points — the starting point and the final point.",
    "tutorial": "In the problem you're asked to find the number of pairs of non-intersecting paths between left upper and right lower corners of the grid. You can use following lemma for that. Thanks to rng_58 for the link. More precisely, considering our problem, this lemma states that given sets of initial $A = {a1, a2}$ and final $B = {b1, b2}$ points, the answer is equal to the following determinant: $\\left|f(a1,b1)\\setminus f(a1,b2)\\right|$ Finally we need to decide what sets of initial and final points we choose. You can take $A = {(0, 1), (1, 0)}$ and $B = {(n - 2, m - 1), (n - 1, m - 2)}$ in order to make paths non-intersecting even in 2 points.",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2500
  },
  {
    "contest_id": "348",
    "index": "E",
    "title": "Pilgrims",
    "statement": "A long time ago there was a land called Dudeland. Dudeland consisted of $n$ towns connected with $n - 1$ bidirectonal roads. The towns are indexed from $1$ to $n$ and one can reach any city from any other city if he moves along the roads of the country. There are $m$ monasteries in Dudeland located in $m$ different towns. In each monastery lives a pilgrim.\n\nAt the beginning of the year, each pilgrim writes down which monastery is the farthest from the monastery he is living in. If there is more than one farthest monastery, he lists all of them. On the Big Lebowski day each pilgrim picks one town from his paper at random and starts walking to that town.\n\nWalter hates pilgrims and wants to make as many of them unhappy as possible by preventing them from finishing their journey. He plans to destroy exactly one town that does not contain a monastery. A pilgrim becomes unhappy if all monasteries in his list become unreachable from the monastery he is living in.\n\nYou need to find the maximum number of pilgrims Walter can make unhappy. Also find the number of ways he can make this maximal number of pilgrims unhappy: the number of possible towns he can destroy.",
    "tutorial": "Let's build a simple solution at first and then we will try to improve it to solve problem more effectively given the constraints. For every vertex let's find the list of the farthest vertices. Let's find vertices on the intersection of the paths between current vertex and each vertex from the list that don't contain monasteries. If we remove any of these vertices then every vertex from the list is unreachable from the current monastery. For every vertex from the intersection increment the counter. Then the answer for the problem is the maximum among all counters and the number of such maxima. Let's solve the problem more effectively using the same idea. Let's make the tree with root. For every vertex we will find the list of the farthest vertices only in the subtree. While traversing the tree using depth first search we return the largest depth in the subtree and the number of the vertex where it was reached. Among all of the sons of the current vertex we choose the maximum of depths. If maximum is reached one time then we return the same answer that was returned from the son. If the answer was reached more than one time then we return the number of the current vertex. Essentially, we find LCA of the farthest vertices according to the current vertex. Before quitting the vertex we increment the values on the segment between current vertex and found LCA. One can use Eulerian tour and segment tree for adding on the segment. Finally, the last stage of solving the problem - to solve it for the case when the farthest vertex is not in the subtree of the current vertex. For solving of that subproblem we use the same idea that was used in the problem of the finding the maximal path in the tree. For every vertex we keep 3 maximums - 3 farthest vertices in the subtree. When we go down to the subtree, we pass 2 remaining maximums too. In that way, when we're in any vertex, we can decide whether there's a path not in the subtree (it means, going up) of the same or larger length. If there're 2 paths of the same length in the subtree and not in the subtree, it means that for the pilgrim from the current monastery there's always a path no matter what town was destroyed. If one of the quantities is larger then we choose the segment in Eulerian tour and increment the value on the segment. The case where there's several paths (at least 2) out of the subtree of the same maximal length, is the same with the case in the subtree. LCA and segment tree can be solved effectively in $O(logN)$ time per query so the total memory and time is $O(NlogN)$.",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "349",
    "index": "A",
    "title": "Cinema Line",
    "statement": "The new \"Die Hard\" movie has just been released! There are $n$ people at the cinema box office standing in a huge line. Each of them has a single $100$, $50$ or $25$ ruble bill. A \"Die Hard\" ticket costs $25$ rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?",
    "tutorial": "In the problem you need to decide whether cashier can give a change to all customers if the price of the ticket is 25 rubles and there's 3 kinds of bills: 25, 50 and 100 rubles. There's no money in the ticket office in the beginning. Let's consider 3 cases. Customer has 25 rubles hence he doesn't need a change. Customer has 50 rubles hence we have to give him 25 rubles back. Customer has 100 rubles hence we need to give him 75 rubles back. It can be done in 2 ways. 75=25+50 and 75=25+25+25. Notice that it's always worth to try 25+50 first and then 25+25+25. It's true because bills of 25 rubles can be used both to give change for 50 and 100 rubles and bills of 50 rubles can be used only to give change for 100 rubles so we need to save as much 25 ruble bills as possible. The solution is to keep track of the number of 25 and 50 ruble bills and act greedily when giving change to 100 rubles - try 25+50 first and then 25+25+25.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "349",
    "index": "B",
    "title": "Color the Fence",
    "statement": "Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has.\n\nUnfortunately, Igor could only get $v$ liters of paint. He did the math and concluded that digit $d$ requires $a_{d}$ liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.\n\nHelp Igor find the maximum number he can write on the fence.",
    "tutorial": "In the problem you're asked to write the largest possible number given number of paint that you have and number of paint that you need to write each digit. Longer number means larger number so it's worth to write the longest possible number. Because of that we choose the largest digit among those that require the least number of paint. Let the number of paint for that digit $d$ be equal to $x$, and we have $v$ liters of paint total. Then we can write number of the length $\\left\\lfloor{\\frac{v}{x}}\\right\\rfloor$. Now we know the length of the number, let it be $len$. Write down temporary result - string of length $len$, consisting of digits $d$. We have supply of $v-len \\cdot x$ liters of paint. In order to enhance the answer, we can try to update the number from the beginning and swap each digit with the maximal possible. It's true because numbers of the equal length are compared in the highest digits first. Among digits that are greater than current we choose one that we have enough paint for and then update answer and current number of paint. If the length of the answer is 0 then you need to output -1.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "350",
    "index": "A",
    "title": "TL",
    "statement": "Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.\n\nValera has written $n$ correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote $m$ wrong solutions and for each wrong solution he knows its running time (in seconds).\n\nLet's suppose that Valera will set $v$ seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most $v$ seconds. We can also say that a solution passes the system testing with some \"extra\" time if for its running time, $a$ seconds, an inequality $2a ≤ v$ holds.\n\nAs a result, Valera decided to set $v$ seconds TL, that the following conditions are met:\n\n- $v$ is a positive integer;\n- all correct solutions pass the system testing;\n- at least one correct solution passes the system testing with some \"extra\" time;\n- all wrong solutions do not pass the system testing;\n- value $v$ is minimum among all TLs, for which points $1$, $2$, $3$, $4$ hold.\n\nHelp Valera and find the most suitable TL or else state that such TL doesn't exist.",
    "tutorial": "Let's $v = min(a_{i}), p = max(a_{i}), c = min(b_{i})$. So, if $max(2 * v, p) < c$, then answer is $max(2 * v, p)$, else answer is $- 1$.",
    "code": "#include <cstdio>\n#include <algorithm>\n \nusing namespace std;\n \nconst int N = 300 + 5;\n \nint n, m, a[N], b[N]; \n \nint main()\n{\n\tscanf(\"%d %d\", &n, &m);\n\t\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d\", &a[i]);\n \t\n \tfor(int i = 0; i < m; i++)\n\t\tscanf(\"%d\", &b[i]);\n\t\n\tsort(a, a + n);\n\tsort(b, b + m);\n \n\tint tmin = 2 * a[0];\n\t\n\ttmin = max(tmin, a[n - 1]);\n\t\n\tif (b[0] <= tmin)\n\t\tputs(\"-1\");\n\telse\n\t\tprintf(\"%d\", tmin);\n\t\n\treturn 0;\t\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "350",
    "index": "B",
    "title": "Resort",
    "statement": "Valera's finally decided to go on holiday! He packed up and headed for a ski resort.\n\nValera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has $n$ objects (we will consider the objects indexed in some way by integers from $1$ to $n$), each object is either a hotel or a mountain.\n\nValera has also found out that the ski resort had multiple ski tracks. Specifically, for each object $v$, the resort has at most one object $u$, such that there is a ski track built from object $u$ to object $v$. We also know that no hotel has got a ski track leading from the hotel to some object.\n\nValera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects $v_{1}, v_{2}, ..., v_{k}$ ($k ≥ 1$) and meet the following conditions:\n\n- Objects with numbers $v_{1}, v_{2}, ..., v_{k - 1}$ are mountains and the object with number $v_{k}$ is the hotel.\n- For any integer $i$ $(1 ≤ i < k)$, there is \\textbf{exactly one} ski track leading from object $v_{i}$. This track goes to object $v_{i + 1}$.\n- The path contains as many objects as possible ($k$ is maximal).\n\nHelp Valera. Find such path that meets all the criteria of our hero!",
    "tutorial": "Input data represents a graph, by using a array of parents of every vertex. Because every vertex has at most one parent, we can use following solution: we will go up to parent of vertex $v$ ($prev[v]$) until not found vertex with the outcome degree $ \\ge  2$. It is better to calculate outcome degrees in advance. After all, we will update the answer. This algorithm works in $O(n)$.",
    "code": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n \nusing namespace std;\n \nconst int N = 1000 * 100 + 5;\nint type[N], prev[N];\nint cntFrom[N];\nint n;\ninline bool read()\n{\n\tif (!(cin >> n))\n\t\treturn false;\n \n   \tfor(int i = 0; i < n; i++)\n   \t \tscanf(\"%d\", &type[i]);\n  \n\tfor(int i = 0; i < n; i++) \n\t{\n        cin >> prev[i];\n        prev[i]--;\n        if (prev[i] != -1)\n        \tcntFrom[prev[i]]++;\n   \t}\n \n   \treturn true;\n}\n \ninline void solve()\n{\n\tvector < int > ans;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif (type[i] == 1)\n\t\t{\n\t\t \tint curV = i;\n \n\t\t \tvector < int > cur;\n\t\t \twhile (prev[curV] != -1 && cntFrom[prev[curV]] <= 1)\n\t\t \t{\n\t\t \t \tcur.push_back(curV);\n \n\t\t \t \tcurV = prev[curV];\n \n\t\t \t}\n \n\t\t \tcur.push_back(curV);\n \n\t\t \tif (ans.size() < cur.size())\n\t\t \t\tans = cur;\n\t\t}\n\t}\n \n\tprintf(\"%d\\n\", ans.size());\n\treverse(ans.begin(), ans.end());\n\tfor(int i = 0; i < ans.size(); i++)\n\t{\n\t\tif (i) printf(\" \");\n\t\tprintf(\"%d\", ans[i] + 1);\n\t}\t\n\tputs(\"\");\n}\nint main()\n{\n \twhile (read())\n \t solve();\n}",
    "tags": [
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "350",
    "index": "C",
    "title": "Bombs",
    "statement": "You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains $n$ bombs, the $i$-th bomb is at point with coordinates $(x_{i}, y_{i})$. We know that no two bombs are at the same point and that no bomb is at point with coordinates $(0, 0)$. Initially, the robot is at point with coordinates $(0, 0)$. Also, let's mark the robot's current position as $(x, y)$. In order to destroy all the bombs, the robot can perform three types of operations:\n\n- Operation has format \"1 k dir\". To perform the operation robot have to move in direction $dir$ $k$ ($k ≥ 1$) times. There are only $4$ directions the robot can move in: \"R\", \"L\", \"U\", \"D\". During one move the robot can move from the current point to one of following points: $(x + 1, y)$, $(x - 1, y)$, $(x, y + 1)$, $(x, y - 1)$ (corresponding to directions). It is forbidden to move from point $(x, y)$, if at least one point on the path (besides the destination point) contains a bomb.\n- Operation has format \"2\". To perform the operation robot have to pick a bomb at point $(x, y)$ and put it in a special container. Thus, the robot can carry the bomb from any point to any other point. The operation cannot be performed if point $(x, y)$ has no bomb. It is forbidden to pick a bomb if the robot already has a bomb in its container.\n- Operation has format \"3\". To perform the operation robot have to take a bomb out of the container and destroy it. You are allowed to perform this operation only if the robot is at point $(0, 0)$. It is forbidden to perform the operation if the container has no bomb.\n\nHelp the robot and find the shortest possible sequence of operations he can perform to destroy all bombs on the coordinate plane.",
    "tutorial": "First of all, Let's sort all point by increasing of value $|x_{i}| + |y_{i}|$, all points we will process by using this order. We will process each point greedily, by using maximum six moves. Now we want to come to the point $(x, y)$. Let's $x  \\neq  0$. Then we need to move exactly $|x|$ in the $dir$ direction (if $x < 0$ the dir is $L$, $x > 0$ - $R$). Similarly we will work with $y$-coordinates of point $(x, y)$. Now we at the point $(x, y)$, let's pick a bomb at point $(x, y)$. After that we should come back to point $(0, 0)$. Why it is correct to sort all point by increasing of Manhattan distance? If you will look at the path that we have received, you can notice that all points of path have lower Manhattan distance, i.e. we will process this points earlier. This solution works in $O(n\\log(n))$",
    "code": "import java.io.IOException;\nimport java.util.Arrays;\nimport java.io.UnsupportedEncodingException;\nimport java.util.InputMismatchException;\nimport java.util.Comparator;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.math.BigInteger;\nimport java.io.InputStream;\n \n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n * @author gridnevvvit\n */\npublic class mC {\n\tpublic static void main(String[] args) {\n\t\tInputStream inputStream = System.in;\n\t\tOutputStream outputStream = System.out;\n\t\tInputReader in = new InputReader(inputStream);\n\t\tPrintWriter out = new PrintWriter(outputStream);\n\t\tC solver = new C();\n\t\tsolver.solve(1, in, out);\n\t\tout.close();\n\t}\n}\n \nclass C {\n    public void solve(int testNumber, InputReader in, PrintWriter out) {\n        int n = in.readInt();\n        Pair pts[] = new Pair[n];\n        int szAns = 0;\n        for(int i = 0; i < n; i++) {\n            int x = in.readInt();\n            int y = in.readInt();\n            szAns += 2;\n            if (x != 0)\n                szAns += 2;\n            if (y != 0)\n                szAns += 2;\n            pts[i]= new Pair(x, y);\n \n        }\n \n        Arrays.sort(pts, new Comparator<Pair>() {\n            @Override\n            public int compare(Pair o1, Pair o2) {\n                int dist1 = Math.abs(o1.first) + Math.abs(o1.second);\n                int dist2 = Math.abs(o2.first) + Math.abs(o2.second);\n \n                Integer v1 = dist1;\n                Integer v2 = dist2;\n \n                return v1.compareTo(v2);\n            }\n        });\n        out.println(szAns);\n        for(int i = 0; i < n; i++) {\n            if (pts[i].first > 0)\n                out.println(1 + \" \" + pts[i].first + \" R\");\n \n            if (pts[i].first < 0)\n                out.println(1 + \" \" + -pts[i].first + \" L\");\n \n            if (pts[i].second > 0)\n                out.println(1 + \" \" + pts[i].second + \" U\");\n \n            if (pts[i].second < 0)\n                out.println(1 + \" \" + -pts[i].second + \" D\");\n \n            out.println(2);\n \n            if (pts[i].first > 0)\n                out.println(1 + \" \" + pts[i].first + \" L\");\n \n            if (pts[i].first < 0)\n                out.println(1 + \" \" + -pts[i].first + \" R\");\n \n            if (pts[i].second > 0)\n                out.println(1 + \" \" + pts[i].second + \" D\");\n \n            if (pts[i].second < 0)\n                out.println(1 + \" \" + -pts[i].second + \" U\");\n \n            out.println(3);\n        }\n \n \n    }\n \n    public class Pair {\n        int first = 0, second = 0;\n \n        public Pair (int x, int y) {\n            this.first = x;\n            this.second = y;\n        }\n \n    }\n}\n \nclass InputReader {\n \n    private InputStream stream;\n    private byte[] buf = new byte[1024];\n    private int curChar;\n    private int numChars;\n \n    public InputReader(InputStream stream) {\n        this.stream = stream;\n    }\n \n    public int read() {\n        if (numChars == -1)\n            throw new InputMismatchException();\n        if (curChar >= numChars) {\n            curChar = 0;\n            try {\n                numChars = stream.read(buf);\n            } catch (IOException e) {\n                throw new InputMismatchException();\n            }\n            if (numChars <= 0)\n                return -1;\n        }\n        return buf[curChar++];\n    }\n \n    public int readInt() {\n        int c = read();\n        while (isSpaceChar(c))\n            c = read();\n        int sgn = 1;\n        if (c == '-') {\n            sgn = -1;\n            c = read();\n        }\n        int res = 0;\n        do {\n            if (c < '0' || c > '9')\n                throw new InputMismatchException();\n            res *= 10;\n            res += c - '0';\n            c = read();\n        } while (!isSpaceChar(c));\n        return res * sgn;\n    }\n \n    public static boolean isSpaceChar(int c) {\n        return c == ' ' || c == '\\n' || c == '\\r' || c == '\\t' || c == -1;\n    }\n \n    }",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "350",
    "index": "D",
    "title": "Looking for Owls",
    "statement": "Emperor Palpatine loves owls very much. The emperor has some blueprints with the new Death Star, the blueprints contain $n$ distinct segments and $m$ distinct circles. We will consider the segments indexed from $1$ to $n$ in some way and the circles — indexed from $1$ to $m$ in some way.\n\nPalpatine defines an owl as a set of a pair of distinct circles $(i, j)$ ($i < j$) and one segment $k$, such that:\n\n- circles $i$ and $j$ are symmetrical relatively to the straight line containing segment $k$;\n- circles $i$ and $j$ don't have any common points;\n- circles $i$ and $j$ have the same radius;\n- segment $k$ intersects the segment that connects the centers of circles $i$ and $j$.\n\nHelp Palpatine, count the number of distinct owls on the picture.",
    "tutorial": "It's possible to solve this problem by using only integer calculations. Normalization of the line $Ax + By + C$ is following operation: we multiply our equation on the value $\\textstyle{\\frac{\\theta m}{\\theta}}$, where $g = gcd(A, gcd(B, C))$, if $A < 0$ $(orA = 0andB < 0)$ then $sgn$ equals to $- 1$, else sgn equals to $1$. Now the solution. We will have two maps (map<> in C++, TreeMap(HashMap) in Java) to a set of points (it's possible that some points will have multiply occurrence into the set). In first map we will store right boundaries of the segments, in second - left boundaries (in increasing order). In advance for every segment we will build a normalized line, and for this normalized line we will put in our maps left and right segments of the segment. After all, for every fixed line let's sort our sets. Let's fix two different circles. After that, let's check that distance beetween them is greater then sum their radiuses, also you should check that circles has same radius. We can assume that we builded a line between centers of circles $(x1, y1)$ and $(x2, y2)$. Perpendicular to this line will have next coefficients (center of the segment $[(x1, y1), (x2, y2)]$ also will belong to the next line) $A = 2(x1 - x2)$, $B = 2(y1 - y2)$, $C = - ((x1 - x2) * (x1 + x2) + (y1 - y2) * (y1 + y2))$. After that you need to calculate values $cntL$, $cntR$ by using binary search on set of points that lie on this line. $cntL$ - amount of left boundaries that lie on the right side of point $((x1 + x2) / 2, (y1 + y2) / 2)$, $cntR$ -- amount of right boundaries that lie on the left side of the point $((x1 + x2) / 2, (y1 + y2) / 2)$. After that you should add to answer value $cntV - cntR - cntL$,l where $cntV$ - amount of segments, that lie on the nolmalized line. Total complexity: $O(m^{2}\\log(n)+n\\log(n))$.",
    "code": "#define _CRT_SECURE_NO_DEPRECATE\n#define _USE_MATH_DEFINES\n \n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <climits>\n#include <ctime>\n#include <cstring>\n#include <cmath>\n#include <iomanip>\n#include <utility>\n#include <complex>\n#include <vector>\n#include <bitset>\n#include <string>\n#include <stack>\n#include <queue>\n#include <set>\n#include <map>          \n \nusing namespace std;\n \n#define pb push_back\n#define mp make_pair\n#define all(a) a.begin(), a.end()\n#define sz(a) int(a.size())\n#define forn(i,n) for (int i = 0; i < int(n); i++)\n#define x1 ___x1\n#define y1 ___y1\n#define x first\n#define ft first\n#define y second\n#define sc second\n \ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt; \n \nconst int INF = 1000 * 1000 * 1000;\nconst ld EPS = 1e-9;\nconst ld PI = (ld)3.1415926535897932384626433832795;\n \nconst int N = 3000 * 100 + 5;\nconst int M = 2000 + 5;\n \nstruct line \n{\n \tint A, B, C;\n \tline() { }\n \n \tline(int a, int b, int c)\n \t{\n \t  A = a;\n \t  B = b;\n \t  C = c;\n \t}\n};\n \nbool operator < (line a, line b) \n{\n \tif (a.A != b.A)\n \t\treturn a.A < b.A;\n \n\tif (a.B != b.B)\n\t\treturn a.B < b.B;\n \n\treturn a.C < b.C;\t\n}\n \nint n, m;\nint xF[N], yF[N], xS[N], yS[N];\nint xC[M], yC[M], rC[M];\nvector < pt > incOrder[N]; \nvector < pt > decOrder[N];\n \ninline bool read()\n{\t\n\tif (scanf(\"%d %d\", &n, &m) != 2)\n\t\treturn false;\n \n\tfor(int i = 0; i < n; i++)\n\t{\n\t \tscanf(\"%d %d %d %d\", &xF[i], &yF[i], &xS[i], &yS[i]); \n \n\t \tif (mp(xF[i], yF[i]) > mp(xS[i], yS[i]))\n\t \t\tswap(xF[i], xS[i]), swap(yF[i], yS[i]);\n\t}\n \n\tfor(int i = 0; i < m; i++)\n\t{\n\t \tscanf(\"%d %d %d\", &xC[i], &yC[i], &rC[i]);\n\t}\n \n\treturn true;\n}\n \ninline int gcd(int a, int b)\n{\n \ta = abs(a);\n \tb = abs(b);\n \tif (a == 0 && b == 0)\n \t\treturn b;\n \treturn __gcd(a, b);\n}\n \ninline int dist(int x, int y, int X, int Y)\n{\n \treturn sqr(x - X) + sqr(y - Y);\n}\n \nline getnorm(int curA, int curB, int curC)\n{\n\tint g = gcd(curA, gcd(curB, curC));\n \n \tcurA /= g;\n \tcurB /= g;\n \tcurC /= g;\n \n\tif (curA != 0)\n\t{\n\t\tint sgn = 1;\n\t\tif (curA < 0)\n\t\t\tsgn *= -1;\n \n\t\tcurA *= sgn, curB *= sgn, curC *= sgn;\n\t}\n\telse\n\t{\n\t\tif (curB == 0)\n\t\t\tthrow;\n\t\tint sgn = 1;\n \n\t\tif (curB < 0)\n\t\t\tsgn *= -1;\n \n\t\tcurA *= sgn, curB *= sgn, curC *= sgn;\n\t}\t\n \n\treturn line(curA, curB, curC);\n}\n \ninline void solve()\n{\n\tint tsz = 0;\n\tmap<line, int> toId;\n    for(int i = 0; i < n; i++)\n    {\n  \t\tint curA = yF[i] - yS[i];\n  \t\tint curB = xS[i] - xF[i];\n  \t\tint curC = xF[i] * yS[i] - xS[i] * yF[i];\n  \t\t\n  \t\tline current = getnorm(curA, curB, curC);\n  \t\tint idx = -1;\n  \t\tif (!toId.count(current))\n  \t\t\ttoId[current] = tsz++;\n  \t\tidx = toId[current];\n  \t\t\n  \t\tincOrder[idx].push_back(mp(2 * xF[i], 2 * yF[i]));\n  \t\tdecOrder[idx].push_back(mp(2 * xS[i], 2 * yS[i]));\t\n  \t}\n\tforn(i, tsz)\n   \t{\t\n   \t\tsort(all(incOrder[i]));\n   \t\tsort(all(decOrder[i]));\t\t\n   \t}\n   \tli ans = 0;\t\n    for(int i = 0; i < m; i++)\n    {\n     \tfor(int j = i + 1; j < m; j++)\n     \t{\n     \t\tif (rC[i] != rC[j])\n     \t\t\tcontinue;\n \n     \t\tif (dist(xC[i], yC[i], xC[j], yC[j]) <= 4 * sqr(rC[i]))\n     \t\t\tcontinue;\n \n     \t\tpt curBeet = mp(xC[i] + xC[j], yC[i] + yC[j]);\n     \t\tint curA = xC[i] - xC[j];\n     \t\tint curB = yC[i] - yC[j];\n     \t\tint curC = -(curA * (xC[i] + xC[j]) + curB * (yC[i] + yC[j]));\n \n     \t\tcurA <<= 1;\n     \t\tcurB <<= 1;\n \n     \t\tline currentL = getnorm(curA, curB, curC);\n \n     \t\tif (!toId.count(currentL))\n     \t\t\tcontinue;\n \n     \t\tint current = toId[currentL];\n \n     \t\tint curAdd = incOrder[current].size();\n     \t \tcurAdd -= int(incOrder[current].end() - upper_bound(all(incOrder[current]), curBeet));\n \n     \t \tvector < pt > ::iterator it = lower_bound(all(decOrder[current]), curBeet);\n \n     \t \tif (it != decOrder[current].begin())\n     \t \t{\n     \t \t \tit--;\n     \t \t \tcurAdd -= (int(it - decOrder[current].begin()) + 1); \n     \t \t}\n \n     \t \tans += curAdd;\n     \t}\n    }\n \n    cout << ans << endl;\n}\nint main () { \n //   freopen(\"input.txt\", \"rt\", stdin);\n    cout << setprecision(10) << fixed;\n    cerr << setprecision(5) << fixed;\n\t\n\tassert(read());\n\tsolve();\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "geometry",
      "hashing",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "350",
    "index": "E",
    "title": "Wrong Floyd",
    "statement": "Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.\n\nValera's already written the code that counts the shortest distance between any pair of vertexes in a \\textbf{non-directed connected graph} from $n$ vertexes and $m$ edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly $k$ vertexes $a_{1}, a_{2}, ..., a_{k}$.\n\nValera's code is given below.\n\n\\begin{verbatim}\nans[i][j] // the shortest distance for a pair of vertexes\n$i, j$\na[i] // vertexes, marked by Valera\nfor(i = 1; i <= n; i++) {\nfor(j = 1; j <= n; j++) {\nif (i == j)\nans[i][j] = 0;\nelse\nans[i][j] = INF; //INF is a very large number\n}\n}\nfor(i = 1; i <= m; i++) {\nread a pair of vertexes u, v that have a non-directed edge between them;\nans[u][v] = 1;\nans[v][u] = 1;\n}\nfor (i = 1; i <= k; i++) {\nv = a[i];\nfor(j = 1; j <= n; j++)\nfor(r = 1; r <= n; r++)\nans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);\n}\n\\end{verbatim}\n\nValera has seen that his code is wrong. Help the boy. Given the set of marked vertexes $a_{1}, a_{2}, ..., a_{k}$, find such \\textbf{non-directed connected graph}, consisting of $n$ vertexes and $m$ edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes $(i, j)$. Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.",
    "tutorial": "Let's do the following: construct the graph with the maximum possible number of edges and then remove the excess. First of all, you can notice that if $k = n$ answer is $- 1$. Else let's fix some marked vertex, for example $a_{1}$. Let's put in our graph all edges except edges beetween $a_{1}$ and $x$, where $x$ - an another marked vertex. So, why this algorithm is correct? If Valera's algorithm is wrong, then there are a ''bad'' pair of vertexes (i, j). ``Bad'' pair is a pair for that Valera's algorithm works wrong. So, there are not marked vertex $v$ on the shortest path from i to j, and $v  \\neq  i$, and $v  \\neq  j$. Without loss of generality, we can assume, that distance beetween $i$ and $j$ equals to 2, but Valera's algorithm gives greater answer. There are some cases, that depends on the type of vertexes $i$, $j$. But we can look only at the case where $(i, j)$ are marked vertexes. First, add to the graph all edges beetween not fixed ($i, j$) vertexes. Second, add to the graph edges beetween some fixed vertex ($i$ or $j$) and some not marked vertex. Third, add to the graph edges beetween $i$ and some marked vertex $v$, where $v  \\neq  j$. It's simple to understand, that if we add some another edge, the Valera's algorithm will work correctly. Total amount of edges is ${\\frac{n(n-1)}{2}}-k+1$.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <vector>\n \nusing namespace std;\n \nconst int N = 300 + 5;\nint n, m, ok, a[N], used[N];\ninline bool read()\n{\n\tif (scanf(\"%d %d %d\", &n, &m, &ok) != 3)\n\t\treturn false;\n \n\tfor(int i = 0; i < ok; i++) \n\t scanf(\"%d\", &a[i]), a[i]--;\n \n \n\tsort(a, a + ok);\n \n   \treturn true;\n}\n \nvector < int > g[N];\nvector < pair<int,int> > edges;\nvector < pair<int,int> > ans;\nvoid dfs(int s, int prev = -1)\n{\n \tif (used[s])\n \t\treturn;\n \n \tused[s] = true;\n \n \tif (prev != -1)\n \t{\n \t \tans.push_back(make_pair(min(s, prev), max(s, prev)));\n \t}\n \n \tfor(int i = 0; i < g[s].size(); i++)\n \t{\n \t \tint v = g[s][i];\n \t \tif (v == prev) continue;\n \t \tdfs(v, s);\n \t}\n}\n \nvoid add_edge(int i, int j)\n{\n \tg[i].push_back(j);\n \tg[j].push_back(i);\n \tedges.push_back(make_pair(min(i,j), max(j,i)));\n}\n \ninline void solve()\n{\n\tif (n == ok) \n\t{\n\t \tputs(\"-1\");\n\t \treturn;\n\t}\n    for(int i = 0; i < n; i++)\n\t\tfor(int j = i + 1; j < n; j++)\n\t\t{\n\t    \tif (i == a[1] || j == a[0] || i == a[0] || j == a[1]) continue;\n\t    \tadd_edge(i, j);\n\t\t}\n\t\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif (!binary_search(a, a + ok, i))\n\t\t{\n\t\t \tadd_edge(i, a[0]);\n\t\t \tadd_edge(i, a[1]);\n\t\t}\n\t\telse\n\t\t{\n\t\t \tif (i != a[0] && i != a[1])\n\t\t \t\tadd_edge(i, a[0]);\n\t\t}\n\t}\n \n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif (!binary_search(a, a + ok, i))\n\t\t{\n\t\t \tdfs(i);\n\t\n\t\t \tsort(ans.begin(), ans.end());\n\t\t \tbreak;\n\t\t}\t\n\t}\n\tif (edges.size() < m)\n\t{\n\t\tputs(\"-1\");\n\t\treturn;\n\t}\t\n \n\tfor(int i = 0; i < edges.size(); i++)\n\t{\n\t \tif (!binary_search(ans.begin(), ans.begin() + n - 1, edges[i]) && ans.size() < m)\n\t \t{\n\t \t\tans.push_back(edges[i]);\t\n\t\t}\t\n\t}\n \n\tfor(int i = 0; i < ans.size(); i++)\n\t{\n\t \tprintf(\"%d %d\\n\", ans[i].first + 1, ans[i].second + 1);\t\n\t}\n}\n \nint main()\n{\n \twhile (read())\n \t solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "351",
    "index": "A",
    "title": "Jeff and Rounding",
    "statement": "Jeff got $2n$ real numbers $a_{1}, a_{2}, ..., a_{2n}$ as a birthday present. The boy hates non-integer numbers, so he decided to slightly \"adjust\" the numbers he's got. Namely, Jeff consecutively executes $n$ operations, each of them goes as follows:\n\n- choose indexes $i$ and $j$ $(i ≠ j)$ that haven't been chosen yet;\n- round element $a_{i}$ to the nearest integer that isn't more than $a_{i}$ (assign to $a_{i}$: $⌊ a_{i} ⌋$);\n- round element $a_{j}$ to the nearest integer that isn't less than $a_{j}$ (assign to $a_{j}$: $⌈ a_{j} ⌉$).\n\nNevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.",
    "tutorial": "Initially, we should remember the number of integers - $C$. On next step we will round down all numbers and count the sum. Now we can change the sum, rounding up some numbers, with those not matter what kind of, the main thing - how many. Consider a couple what we could get: 1. $(int, int)$ $(c_{1})$ 2. $(int, double)$ $(c_{2})$ 3. $(double, int)$ $(c_{3})$ 4. $(double, double)$ $(c_{4})$ Iterate over the number of pairs of the first type. Then we know the total number of second and third type and number of the fourth type: 1. $c_{2}$ + $c_{3}$ = $C$ - $2c_{1}$ 2. $c_{4}$ = $N - (c_{1} + c_{2} + c_{3})$ Check to see if you can get such numbers (enough for us count of integers and real numbers, respectively). We find that we can round up from $c_{4}$ to $c_{4} + c_{2} + c_{3}$ numbers. We will find the best choise.",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "351",
    "index": "B",
    "title": "Jeff and Furik",
    "statement": "Jeff has become friends with Furik. Now these two are going to play one quite amusing game.\n\nAt the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of $n$ numbers: $p_{1}$, $p_{2}$, $...$, $p_{n}$. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows \"heads\" he chooses a random pair of adjacent elements with indexes $i$ and $i + 1$, for which an inequality $p_{i} > p_{i + 1}$ holds, and swaps them. But if the coin shows \"tails\", Furik chooses a random pair of adjacent elements with indexes $i$ and $i + 1$, for which the inequality $p_{i} < p_{i + 1}$ holds, and swaps them. If the coin shows \"heads\" or \"tails\" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.\n\nJeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.\n\nYou can consider that the coin shows the heads (or tails) with the probability of $50$ percent.",
    "tutorial": "ote that after each step, the number of inversions in the permutation is changed by 1. Let us turn to the inversions of the permutation - let them be $I$ pcs. It is clear that when we have one inversion, then the answer - $1$. Now we will see how to use it further: 1. it is clear that after a Jeff's step inversions will become lower by $1$ 2. it is clear that after a Furik's step inversions will be on $1$ lowerwith porbability of $0, 5$, and on $1$ greater with probability of $0, 5$. 3. we have the formula for an answer $ans_{I} = 1 + 1 + ans_{I - 1 - 1}  \\times  0.5 + ans_{I - 1 + 1}  \\times  0.5$ 4. after transformation we have $ans_{I} = 4 + ans_{I - 2}$.",
    "tags": [
      "combinatorics",
      "dp",
      "probabilities"
    ],
    "rating": 1900
  },
  {
    "contest_id": "351",
    "index": "C",
    "title": "Jeff and Brackets",
    "statement": "Jeff loves regular bracket sequences.\n\nToday Jeff is going to take a piece of paper and write out the regular bracket sequence, consisting of $nm$ brackets. Let's number all brackets of this sequence from $0$ to $nm$ - $1$ from left to right. Jeff knows that he is going to spend $a_{i mod n}$ liters of ink on the $i$-th bracket of the sequence if he paints it opened and $b_{i mod n}$ liters if he paints it closed.\n\nYou've got sequences $a$, $b$ and numbers $n$, $m$. What minimum amount of ink will Jeff need to paint a regular bracket sequence of length $nm$?\n\nOperation $x mod y$ means taking the remainder after dividing number $x$ by number $y$.",
    "tutorial": "How to solve the problem for small $NM$? Just use the dynamic programming $dp_{i, j}$ - minimum cost to build $i$ first brackets with the balance $j$. Transfers are simple: 1. $dp_{i, j} + a_{i + 1}$ -> $dp_{i + 1, j + 1}$ 2. $dp_{i, j} + b_{i + 1}$ -> $dp_{i + 1, j - 1}$ 3. we make transfers only when balance will be non-negative 4. starting state $dp_{0, 0} = 0$ In this problem, we can assume that the balance will never exceed $2N$. The proof is left as homework. And by using this fact problem can be done by erecting a matrix to the power: 1. lets $T_{i, j}$ - cost of transfer from balance $i$ to balance $j$, using $N$ brackets 2. $(T^{M})_{0, 0}$ - answer to the problem",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2500
  },
  {
    "contest_id": "351",
    "index": "D",
    "title": "Jeff and Removing Periods",
    "statement": "Cosider a sequence, consisting of $n$ integers: $a_{1}$, $a_{2}$, $...$, $a_{n}$. Jeff can perform the following operation on sequence $a$:\n\n- take three integers $v$, $t$, $k$ $(1 ≤ v, t ≤ n; 0 ≤ k; v + tk ≤ n)$, such that $a_{v}$ = $a_{v + t}$, $a_{v + t}$ = $a_{v + 2t}$, $...$, $a_{v + t(k - 1)}$ = $a_{v + tk}$;\n- remove elements $a_{v}$, $a_{v + t}$, $...$, $a_{v + t·k}$ from the sequence $a$, the remaining elements should be reindexed $a_{1}, a_{2}, ..., a_{n - k - 1}$.\n- permute in some order the remaining elements of sequence $a$.\n\nA beauty of a sequence $a$ is the minimum number of operations that is needed to delete all elements from sequence $a$.\n\nJeff's written down a sequence of $m$ integers $b_{1}$, $b_{2}$, $...$, $b_{m}$. Now he wants to ask $q$ questions. Each question can be described with two integers $l_{i}, r_{i}$. The answer to the question is the beauty of sequence $b_{li}$, $b_{li + 1}$, $...$, $b_{ri}$. You are given the sequence $b$ and all questions. Help Jeff, answer all his questions.",
    "tutorial": "After the first request we can sort the numbers and for further moves will be able to remove all occurrences of a certain number. So the answer is the number of different numbers + 1 if there is no number, occurrence of which form an arithmetic progression. Number of different numbers on a segment - standart problem, can be done $O(N^{1.5})$ with offline algorithm. The problem about finding the right number will be solved in a similar algorithm: 1. lets sort queries like pairs $(l_{i} / 300, r_{i})$, we use integer dividing 2. learn how to move from the interval $(l, r)$ to intervals $(l - 1, r)$, $(l + 1, r)$, $(l, r - 1)$, $(l, r + 1)$ with complexcity $O(1)$ 3. by means of such an operation will move from one segment to the next, in the amount of the operation algorithm will works $O(N^{1.5})$ It remains to learn how to make the change on the interval by $1$ element. Such a problem can be solved quite simply: 1. we craete $deque$ for all value of numbers in array 2. depending on changes in the segment will add / remove items to the start / end of the respective $deque$ 3. check whether the resulting $deque$ is arithmetic progression. it will be homework.",
    "tags": [
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "351",
    "index": "E",
    "title": "Jeff and Permutation",
    "statement": "Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence $p_{1}, p_{2}, ..., p_{n}$ for his birthday.\n\nJeff hates inversions in sequences. An inversion in sequence $a_{1}, a_{2}, ..., a_{n}$ is a pair of indexes $i, j$ $(1 ≤ i < j ≤ n)$, such that an inequality $a_{i} > a_{j}$ holds.\n\nJeff can multiply some numbers of the sequence $p$ by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.",
    "tutorial": "We make the zero step, replace the elements on their modules. The first thing you need to understand the way in which we will build our response. After selecting a few ways to understand the fact that initially you need to determine the sign of the largest numbers. Consider the case where the current step we have only one maximal element. It is clear that if you put a sign - all the elements on the left of this will form an inversion, while on the right there will be no inversions. If we do not put a sign - it will all be the opposite. We select the best one and cross out the number of the array, it will not affect to some inversion. Now we should understand how to read the response when the highs more than one. We write the dynamics dp[i][j] - how much inversions can you get, when we looked at the first i higest values and j from them lefted as possitive. Of these dynamics is not difficult to make the transition and get the answer. And so we have a simple and short algorithm: 1. Iterates until the array is not empty 2. Find all the maximal elements 3. Calculate dynamics and find right signs 4. Remove elements from an array",
    "tags": [
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "352",
    "index": "A",
    "title": "Jeff and Digits",
    "statement": "Jeff's got $n$ cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?\n\nJeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.",
    "tutorial": "Solution is looking for few cases: 1. If we do not have zeros, then the answer is -$1$. 2. If we have less than $9$ fives, then the answer is $0$. 3. Otherwise, the answer is: 4. 1. The maximum number of fives divisible by $9$ 4. 2. All zeros, we have",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "352",
    "index": "B",
    "title": "Jeff and Periods",
    "statement": "One day Jeff got hold of an integer sequence $a_{1}$, $a_{2}$, $...$, $a_{n}$ of length $n$. The boy immediately decided to analyze the sequence. For that, he needs to find all values of $x$, for which these conditions hold:\n\n- $x$ occurs in sequence $a$.\n- Consider all positions of numbers $x$ in the sequence $a$ (such $i$, that $a_{i} = x$). These numbers, sorted in the increasing order, must form an arithmetic progression.\n\nHelp Jeff, find all $x$ that meet the problem conditions.",
    "tutorial": "We will go through the array from left to right. At each step, we will store the arrays: 1. $next_{x}$ - the last occurrence of the number $x$ 2. $period_{x}$ - period, which occurs $x$ 3. $fail_{x}$ - whether a time when the number of $x$ no longer fit Now, when we get a new number we considering the case when it is the first, second or occurred more than twice. All the cases described in any past system testing solution.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "354",
    "index": "A",
    "title": "Vasya and Robot",
    "statement": "Vasya has $n$ items lying in a line. The items are consecutively numbered by numbers from $1$ to $n$ in such a way that the leftmost item has number $1$, the rightmost item has number $n$. Each item has a weight, the $i$-th item weights $w_{i}$ kilograms.\n\nVasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:\n\n- Take the leftmost item with the left hand and spend $w_{i} · l$ energy units ($w_{i}$ is a weight of the leftmost item, $l$ is some parameter). If the previous action was the same (left-hand), then the robot spends extra $Q_{l}$ energy units;\n- Take the rightmost item with the right hand and spend $w_{j} · r$ energy units ($w_{j}$ is a weight of the rightmost item, $r$ is some parameter). If the previous action was the same (right-hand), then the robot spends extra $Q_{r}$ energy units;\n\nNaturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.",
    "tutorial": "Brute force how many times we will use operation from the left. So, if we use it $k$ times, then it's clear, that we will take first $k$ items by the left operations and last $(n - k)$ items by the right operations. So, robot will spend $sumLeft[k] \\cdot l + sumRight[n - k] \\cdot r$ energy plus some penalty for the same operations. To minimize this penalty we should perform the operations in the following order LRLRL $...$ RLRLLLLL $...$, starting from the bigger set. For example, if $k = 7, n - k = 4$, we should perform operations in this order: LRLRLRLRL LL. So, we will have to pay the penalty two times $(7 - 4 - 1)$. $sumLeft[i]$ - sum of first $i$ weights, $sumRight[i]$ - sum of last $i$ weights. Time complexity: $O(n)$.",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "354",
    "index": "B",
    "title": "Game with Strings",
    "statement": "Given an $n × n$ table $T$ consisting of lowercase English letters. We'll consider some string $s$ good if the table contains a correct path corresponding to the given string. In other words, good strings are all strings we can obtain by moving from the left upper cell of the table only to the right and down. Here's the formal definition of correct paths:\n\nConsider rows of the table are numbered from 1 to $n$ from top to bottom, and columns of the table are numbered from 1 to $n$ from left to the right. Cell $(r, c)$ is a cell of table $T$ on the $r$-th row and in the $c$-th column. This cell corresponds to letter $T_{r, c}$.\n\nA path of length $k$ is a sequence of table cells $[(r_{1}, c_{1}), (r_{2}, c_{2}), ..., (r_{k}, c_{k})]$. The following paths are correct:\n\n- There is only one correct path of length $1$, that is, consisting of a single cell: $[(1, 1)]$;\n- Let's assume that $[(r_{1}, c_{1}), ..., (r_{m}, c_{m})]$ is a correct path of length $m$, then paths $[(r_{1}, c_{1}), ..., (r_{m}, c_{m}), (r_{m} + 1, c_{m})]$ and $[(r_{1}, c_{1}), ..., (r_{m}, c_{m}), (r_{m}, c_{m} + 1)]$ are correct paths of length $m + 1$.\n\nWe should assume that a path $[(r_{1}, c_{1}), (r_{2}, c_{2}), ..., (r_{k}, c_{k})]$ corresponds to a string of length $k$: $T_{r1, c1} + T_{r2, c2} + ... + T_{rk, ck}$.\n\nTwo players play the following game: initially they have an empty string. Then the players take turns to add a letter to the end of the string. After each move (adding a new letter) the resulting string must be good. The game ends after $2n - 1$ turns. A player wins by the following scenario:\n\n- If the resulting string has strictly more letters \"a\" than letters \"b\", then the first player wins;\n- If the resulting string has strictly more letters \"b\" than letters \"a\", then the second player wins;\n- If the resulting string has the same number of letters \"a\" and \"b\", then the players end the game with a draw.\n\nYour task is to determine the result of the game provided that both players played optimally well.",
    "tutorial": "We will say that cell $(r, c)$ corresponds to a string $s$, if there exist correct path, which ends in the cell $(r, c)$ and this path corresponds to a string $s$. Let call a set of cells which corresponds to some string $s$ a state. One state can correspond to different strings. We can't brute force all possible strings, because their count - $C_{2n-2}^{n-1}$ is too big, but we can brute force all possible states. It's not hard to observe that all cells that corresponds to some string $s$ lies on same diagonal, so the total count of states is $2^{1} + 2^{2} + ... + 2^{n - 1} + 2^{n} + 2^{n - 1} + ... + 2^{2} + 2^{1} = O(2^{n})$. In implementation we can denote state with diagonal number (from $1$ to $2n - 1$) and bitmask of cells corresponding to this state $(2^{n})$. From each state we can move to 26 different states (actually less) and all possible moves depends on the state, not on the string. On the image you can see an example of move: from state, which is highlighted in blue by letter $a$ we will move to the state, which is highlighted in yellow. Now, for each state we can calculate a value of (count of letters A $-$ count of letters B) in the string, starting from this state. If at the moment is first players turn (an even diagonal), we have to maximize this value, otherwise - minimize. It can be implemented as recursion with memoization. The winner can be determined by the value of state, which corresponds to the single cell $(1, 1)$. Complexity: $O(2^{n}  \\times  (n + alpha))$, where $alpha$ is the size of alphabet.",
    "tags": [
      "bitmasks",
      "dp",
      "games"
    ],
    "rating": 2400
  },
  {
    "contest_id": "354",
    "index": "C",
    "title": "Vasya and Beautiful Arrays",
    "statement": "Vasya's got a birthday coming up and his mom decided to give him an array of positive integers $a$ of length $n$.\n\nVasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array $a$ left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by $k$ for each number).\n\nThe seller can obtain array $b$ from array $a$ if the following conditions hold: $b_{i} > 0; 0 ≤ a_{i} - b_{i} ≤ k$ for all $1 ≤ i ≤ n$.\n\nHelp mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).",
    "tutorial": "The problem was to find greatest $d$, such that $a_{i}  \\ge  d, a_{i} mod d  \\le  k$ holds for each $i$. Let $m = min(a_{i})$, then $d  \\le  m$. Let consider two cases: $m\\leq k+1\\Rightarrow a_{i}\\,m o d\\,m\\leq m-1\\leq k\\Rightarrow A n s w e r=m$ $m>k+1\\Rightarrow A n s w e r\\geq k+1$. In this case we will brute force answer from $k + 1$ to $m$. We can check, if number $d$ is a correct answer in the following way: We have to check that $a_{i} mod d  \\le  k$ for some fixed $d$, which is equals to $a_{i}\\in[d..d+k]\\cup[2d..2d+k]\\cup...\\cup[p\\cdot d...p\\cdot d+k]$, where $p=\\left\\lfloor{\\frac{m a x A}{d}}\\right\\rfloor$. Since all these intervals $[x \\cdot d..x \\cdot d + k]$ doesn't intersects each with other, we can just check that $\\textstyle\\sum_{i=1}^{m a x A/d}c n t[i\\cdot d...i\\cdot d+k]=n$, where $cnt[l..r]$ - count of numbers $a_{i}$ in the interval $[l..r]$. Time complexity: $O(maxA log maxA)$, proof is based on the sum of harmonic series.",
    "tags": [
      "brute force",
      "dp",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "354",
    "index": "D",
    "title": "Transferring Pyramid",
    "statement": "Vasya and Petya are using an interesting data storing structure: a pyramid.\n\nThe pyramid consists of $n$ rows, the $i$-th row contains $i$ cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to $\\textstyle{\\frac{n(n+1)}{2}}$ as shown on the picture below.\n\nAn example of a pyramid at $n = 5$ is:\n\nThis data structure can perform operations of two types:\n\n- Change the value of a specific cell. It is described by three integers: $\"t i v\"$, where $t = 1$ (the type of operation), $i$ — the number of the cell to change and $v$ the value to assign to the cell.\n- Change the value of some subpyramid. The picture shows a highlighted subpyramid with the top in cell $5$. It is described by $s + 2$ numbers: $\"t i v_{1} v_{2} ... v_{s}\"$, where $t = 2$, $i$ — the number of the top cell of the pyramid, $s$ — the size of the subpyramid (the number of cells it has), $v_{j}$ — the value you should assign to the $j$-th cell of the subpyramid.\n\nFormally: a subpyramid with top at the $i$-th cell of the $k$-th row (the $5$-th cell is the second cell of the third row) will contain cells from rows from $k$ to $n$, the $(k + p)$-th row contains cells from the $i$-th to the $(i + p)$-th ($0 ≤ p ≤ n - k$).\n\nVasya and Petya had two identical pyramids. Vasya changed some cells in his pyramid and he now wants to send his changes to Petya. For that, he wants to find a sequence of operations at which Petya can repeat all Vasya's changes. Among all possible sequences, Vasya has to pick the minimum one (the one that contains the fewest numbers).\n\nYou have a pyramid of $n$ rows with $k$ changed cells. Find the sequence of operations which result in \\textbf{each of the $k$ changed cells being changed by at least one operation}. Among all the possible sequences pick \\textbf{the one that contains the fewest numbers}.",
    "tutorial": "This tasks is solvable with dynamic programming. First of all let consider solution with complexity $O(n^{3})$. Let $dp[i][j]$ be the answer for the highlighted in blue part (minimal cost of transferring all special cells that lies inside this area). Then $dp[n][0]$ will be the answer for our original problem. How to recalculate such DP? It's clear that in the leftmost column (inside the blue area) we will choose at most one cell as the top of some subpyramid. If we choose two, then the smallest one will lie fully inside the biggest one (as the orange subpyramid lies inside the blue one). Now, let brute force the cell, which will be the top of subpyramid in this column in time $O(n)$ and we will obtain the following transition: To simplify the formulas, let assume that $d p[i][-1]=d p[i][0]$. $d p[i][j]=m i n(d p[i-1][m a x(j,k)-1]+{\\frac{k\\times(k+1)}{2}}+2.$ $s u m{\\cal U}p[i][m a x(j,k)+1]\\times3),$ $0  \\le  k  \\le  i$, where $k$ is the height on which we will choose our top cell, or $0$, if we don't choose any subpyramid in this column. $sumUp[i][p]$ - count of special cells in the $i$-th column at height starting from $p$, this cells we will have to transfer one by one, using the first type operations. We can reduce the complexity by one $n$, if we will recalculate out DP in the following way: $d p[i][0]=m i n(d p[i-1][k-1]+{\\frac{k\\times(k+1)}{2}}+2+s u m{U p[i][k+1]}\\times3),$ $0  \\le  k  \\le  i$; $d p[i][j]=m i n(d p[i][j-1],d p[i-1][j-1]+s u m U p[i][j+1]\\times3),$ for all $j > 0$. The proof that this is correct is quite simple and is left to the reader. :) Also, we can observe that it is not profitably to take some subpyramid with height greater than $\\sqrt{6k}$, because for such subpyramid we will pay $> 3k$, but if we transfer all cells using the first type operations we will pay only $3k$. So, the second dimension $(j)$ in out DP can be reduced to $\\sqrt{6k}$. Also, to receive AC, you should store only last 2 layers of the DP, otherwise there will be not enough memory. Time complexity: $O(n{\\sqrt{k}})$.",
    "tags": [
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "354",
    "index": "E",
    "title": "Lucky Number Representation",
    "statement": "We know that lucky digits are digits $4$ and $7$, however Vasya's got another favorite digit $0$ and he assumes it also is lucky! Lucky numbers are such \\textbf{non-negative} integers whose decimal record only contains lucky digits. For example, numbers $0, 47, 7074$ are lucky, but $1, 7377, 895, $ -$7$ are not.\n\nVasya has $t$ important positive integers he needs to remember. Vasya is quite superstitious and he wants to remember lucky numbers only, so he is asking you for each important number to represent it as a sum of exactly six lucky numbers (Vasya just can't remember more numbers). Then Vasya can just remember these six numbers and calculate the important number at any moment.\n\nFor each of $t$ important integers represent it as the sum of six lucky numbers or state that this is impossible.",
    "tutorial": "Author's solution, much more complicated than suggested by many participants during the competition, easy solution will be described below. First of all, let write a DP with complexity $O(N * lucky_count(N))$, where $lucky_count(N)$ is the count of lucky numbers $ \\le  N$, $lucky_count(10^{n}) = 3^{n}$. As we can see, for all sufficiently large $N$ solution exists. Really - for every $N > 523$. Now, we can say that for $N  \\le  10000$ we have a solution, which is found using DP. Let's solve the task for larger values of $N$. Next and key idea is to separate the task into two parts: $N = N1 + N2$. Let's choose $N1$ and $N2$ in such way that for them it was easy to find a solution and then merge these two solutions into one. Let $N1 = N mod 4000, N2 = N - N1$. Here we can have a problem that there is no solution for number $N1$, in this case we can do $N1 = N1 + 4000, N2 = N2 - 4000$. Now it is guaranteed that solutions exists for both $N1$ and $N2$, moreover, the solution for number $N1$ will contain only numbers of not more than 3 digits $( < 1000)$. The proof is quite easy: if $N1 < 4000$ - it is obvious; else - if the solution uses some number of the form $(4000 + some_lucky_number)$, we can replace it with just $some_lucky_number$ and receive a correct solution for number ($N1 - 4000$), but is doesn't exist! So, the solution for number $N1$ we have found using DP, now let's find the solution for $N2$. If it will contains only of numbers of the form $(some_lucky_number  \\times  1000)$, then we will be able to easily merge this solution with solution for $N1$, so, let's find such a solution. Here we will use the fact that $N2$ is divisible by 4. For simplicity, let's divide $N2$ by 1000 and in the end multiply all $Ans2(i)$ by the same 1000. Let $P = N2 / 4$. Now, let's construct the solution. Consider, for example, P = 95: we will walk through digits of this number, last digit - 5, means that we want to put digit 4 at the last decimal position of five answer numbers - ok, put it and in the last, sixth, number leave there digit 0. Go forward, digit 9 - we don't have nine numbers, but we can replace seven fours with four sevens, then to the second position we have to put ($9 - 7$) fours and 4 sevens, in total - 6 numbers, exactly as much as we have. Thus, if next digit $d  \\le  6$, we just put to the first $d$ answer numbers digit 4 to the next position; if $d > 6$, then we put 4 sevens and $(d - 7)$ fours. In all other numbers we just leave digit 0 at this position. If $Ans1(i)$ - answer for $N1$, $Ans2(i)$ - for $N2$, the the answer for $N$ will be just $Ans(i) = Ans1(i) + Ans2(i)$. Time complexity for one number: $O(logN)$. During the competition many participants have wrote the following solution: $dp[i][j]$ - can we put the digit to the last $i$ decimal positions of the answer number in such way that we will get correct last $i$ digits in the sum and with carry to the next position equals to $j$. Then the solution exist iff $dp[19][0] = true$. To restore the answer we just have to remember for each state the previous state. Base - $dp[0][0] = true$. Transition - brute force how many fours and sevens we will put to the $i$-th position.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "355",
    "index": "A",
    "title": "Vasya and Digital Root",
    "statement": "Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.\n\nLet's assume that $S(n)$ is the sum of digits of number $n$, for example, $S(4098) = 4 + 0 + 9 + 8 = 21$. Then the digital root of number $n$ equals to:\n\n- $dr(n) = S(n)$, if $S(n) < 10$;\n- $dr(n) = dr( S(n) )$, if $S(n) ≥ 10$.\n\nFor example, $dr(4098) = dr(21) = 3$.\n\nVasya is afraid of large numbers, so the numbers he works with are at most $10^{1000}$. For all such numbers, he has proved that $dr(n) = S( S( S( S(n) ) ) )$ $(n ≤ 10^{1000})$.\n\nNow Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers $k$ and $d$, find the number consisting of exactly $k$ digits (the leading zeroes are not allowed), with digital root equal to $d$, or else state that such number does not exist.",
    "tutorial": "If $d = 0$, the there is the only number with $d r(x)=0\\Leftrightarrow x=0$, so, if $k = 1$, the answer is $0$, otherwise - $No solution$. If $d > 0$, then one of correct numbers is $d  \\times  10^{k - 1}$. Time complexity: $O(1)$ + $O(k)$ for the output.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "355",
    "index": "B",
    "title": "Vasya and Public Transport",
    "statement": "Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has $n$ buses and $m$ trolleys, the buses are numbered by integers from $1$ to $n$, the trolleys are numbered by integers from $1$ to $m$.\n\nPublic transport is not free. There are 4 types of tickets:\n\n- A ticket for one ride on some bus or trolley. It costs $c_{1}$ burles;\n- A ticket for an unlimited number of rides on some bus or on some trolley. It costs $c_{2}$ burles;\n- A ticket for an unlimited number of rides on all buses or all trolleys. It costs $c_{3}$ burles;\n- A ticket for an unlimited number of rides on all buses and trolleys. It costs $c_{4}$ burles.\n\nVasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.",
    "tutorial": "If we buy a ticket of the fourth type, we don't have to buy anything else, so, the answer is $min(c_{4}, answer using tickets of first three types)$. Now, when we don't have ticket of the fourth type, we can solve the task separately for buses and trolleys. Solving the problem only for buses: if we buy a ticket of the third type, we don't have to buy anything else, so, the answer is $min(c_{3}, answer using tickets of first two types)$. Without tickets of type three, we can solve the problem separately for each bus. If we buy a ticket of the second type, we will spend $c_{2}$ burles and if we buy $a_{i}$ tickets of the first type, we will spend $(a_{i}  \\times  c_{1})$ burles. So, the answer for bus $i$ is $min(c_{2}, a_{i}  \\times  c_{1})$. Now it is not difficult to obtain the following solution: Time complexity: $O(n + m)$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "356",
    "index": "A",
    "title": "Knight Tournament",
    "statement": "Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.\n\nAs for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:\n\n- There are $n$ knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to $n$.\n- The tournament consisted of $m$ fights, in the $i$-th fight the knights that were still in the game with numbers at least $l_{i}$ and at most $r_{i}$ have fought for the right to continue taking part in the tournament.\n- After the $i$-th fight among all participants of the fight only one knight won — the knight number $x_{i}$, he continued participating in the tournament. Other knights left the tournament.\n- The winner of the last (the $m$-th) fight (the knight number $x_{m}$) became the winner of the tournament.\n\nYou fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number $b$ was conquered by the knight number $a$, if there was a fight with both of these knights present and the winner was the knight number $a$.\n\nWrite the code that calculates for each knight, the name of the knight that beat him.",
    "tutorial": "Let's the current fight $(l, r, x)$ consists of $K$ knights fighting. Then all we have to do is to find all these knights in time $O(K)$ or $O(KlogN)$. There are several ways to do that, let's consider some of them. The first way is to store the numbers of all alive knights in std::set (C++) or TreeSet (Java). Then in C++ we can use lower_bound method to find the first knight in the fight that is alive, and to iterate over this set, each time moving to the next alive knight. In Java we should use subSet method. The second way is to define array next with the following meaning: To find the first alive knight starting from the knight $v$ we need to follow this links until we find the first knight $w$ with $next[w] = w$. In order not to pass the same links too many times, we will use the trick known as path compression (it is used in Disjoint Set Union). Note that you should handle the case when the current knight is the last knight and is out of tournament.",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 1500
  },
  {
    "contest_id": "356",
    "index": "B",
    "title": "Xenia and Hamming",
    "statement": "Xenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance.\n\nThe Hamming distance between two strings $s = s_{1}s_{2}... s_{n}$ and $t = t_{1}t_{2}... t_{n}$ of equal length $n$ is value $\\sum_{i=1}^{n}[s_{i}\\neq t_{i}]$. Record $[s_{i} ≠ t_{i}]$ is the Iverson notation and represents the following: if $s_{i} ≠ t_{i}$, it is one, otherwise — zero.\n\nNow Xenia wants to calculate the Hamming distance between two long strings $a$ and $b$. The first string $a$ is the concatenation of $n$ copies of string $x$, that is, $a=x+x+\\cdot\\cdot+x=\\sum_{i=1}^{n}x$. The second string $b$ is the concatenation of $m$ copies of string $y$.\n\nHelp Xenia, calculate the required Hamming distance, given $n, x, m, y$.",
    "tutorial": "Let's denote the length of the first string as $lenX$, the length of the second string as $lenY$. Let $L = LCM(lenX, lenY)$. It's obvious that $L$ is a period of the long strings $a$ and $b$, so we can find the distance of its' prefixes of length $L$ and multiply the answer by $\\frac{t e n(a)}{L}$. Let's fix the position $i$ in the string $x$ and think about all characters from the second string it will be compared with. It it easy to conclude that it will be compared with such $y_{j}$ that $i  \\equiv  j (mod g)$, where $g = GCD(lenX, lenY)$. For each possible remainder of division by $g$ and for each character $c$ we can calculate $count(r, c)$ - the number of characters $c$ that appear in $y$ in such positions $j$ that $j mod g = r$. When calculating the Hamming distance, the character $x_{i}$ will be compared with exactly $count(i mod g, x_{i})$ characters from $y$ that are equal to it, all other comparisons will add one to the distance.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "356",
    "index": "C",
    "title": "Compartments",
    "statement": "A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of $n$ compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.\n\nThe students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.\n\nHowever, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number.\n\nAfter all the swaps each compartment should either have no student left, or have a company of three or four students.",
    "tutorial": "In the problem you should come up with some right greedy algorithm. One of correct approaches acts as follows: Firstly, it joins all \"twos\" and \"ones\" (to get \"threes\"). Several \"ones\" should be moved. Then you should consider two cases depend on amounts of \"ones\" and \"twos\". If initially you have more \"ones\", you should try to join remaining after the first point \"ones\" into groups of three. If initially you have more \"twos\", you should try to join remaining after the first point \"twos\" into groups of three. You can get two \"threes\" from three \"twos\". After the first point and the second point some \"ones\" or \"twos\" can remain. You shouldn't come up with common solution. Else you should just to consider all possible cases. To solve the problem you should follow your common sense (is it greedy?). Writing naive solution (bfs search) for stress purposes is not so bad for proving correctness of your solution.",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "356",
    "index": "D",
    "title": "Bags and Coins",
    "statement": "When you were a child you must have been told a puzzle of bags and coins. Anyway, here's one of its versions:\n\nA horse has three bags. The first bag has one coin, the second bag has one coin and the third bag has three coins. In total, the horse has three coins in the bags. How is that possible?\n\nThe answer is quite simple. The third bag contains a coin and two other bags.\n\nThis problem is a generalization of the childhood puzzle. You have $n$ bags. You know that the first bag contains $a_{1}$ coins, the second bag contains $a_{2}$ coins, ..., the $n$-th bag contains $a_{n}$ coins. In total, there are $s$ coins. Find the way to arrange the bags and coins so that they match the described scenario or else state that it is impossible to do.",
    "tutorial": "It's easy to see that bags and their relations \"lies directly in\" should form directed forest. Each vertex should be given value $c_{i}$ - the number of coins in the corresponding bag. Let's denote the sum of values $c_{j}$ in the subtree of vertex $i$ as $f_{i}$. The following conditions should be met: $f_i = a_i$ then sum of $f_i$ of roots equals $s$. It's clear that one of the bags with largest $a_{i}$ must be the root of some tree. It's quite easy to see that the solution exists if and only if there exists a subset $a_{i1}, a_{i2}, ..., a_{ik}$ such that $a_{i1} + a_{i2} + ... + a_{ik} = s$ and this subset contains at least one bag with the largest $a_{i}$. It's obvious that it is necessary condition, the sufficiency is also easy to see: let's suppose we have such subset. Then all bags from the subset, except one of the largest, will be roots of the signle-vertex trees (i.e. $c_{i} = a_{i}$ for them). All bags that are not in the subset we will consequentially put into the largest bag, forming the \"russian doll\" (this tree will be directed chain). So, we reduced the task to the well-known subset-sum problem: from the items $a_{1}, a_{2}, ... a_{n}$ find the subset with the given sum $s$. This problem is NP-Complete, and with these constraints is solved in a following way: let $T(i, j) = 1$ if it is possible to obtain sum $j$ using some of the first $i$ items, and $T(i, j) = 0$ otherwise. Then $T(i,j)=T(i-1,j)\\,\\lor T(i-1,j-a_{i})$. The $i$-th row of this table depends only on the previous row, so we don't have to store the whole table in memory. Also we should use the fact that the values of the table are zeroes and ones, and we can use bit compression and store each row in an array of int's of size $\\textstyle\\left[{\\frac{s}{32}}\\right]$. To get the $i$-th row, we should calculate the bitwise OR of the previous row and the previous row shifted to the left by $a_{i}$ positions. That is, we can find out whether it possible to obtain the sum $s$ in approximately $\\overset{n s}{\\ldots}$ operations. To find the actual way to obtain $s$, we need to use the following trick: for every possible sum $j$ we will remember the value $first(j)$ - the number of such item that after considering this item it became possible to obtain $j$. This allows us to restore the solution.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "356",
    "index": "E",
    "title": "Xenia and String Problem",
    "statement": "Xenia the coder went to The Olympiad of Informatics and got a string problem. Unfortunately, Xenia isn't fabulous in string algorithms. Help her solve the problem.\n\nString $s$ is a sequence of characters $s_{1}s_{2}... s_{|s|}$, where record $|s|$ shows the length of the string.\n\nSubstring $s[i... j]$ of string $s$ is string $s_{i}s_{i + 1}... s_{j}$.\n\nString $s$ is a Gray string, if it meets the conditions:\n\n- the length of string $|s|$ is odd;\n- character $\\textstyle{\\binom{k}{\\frac{k}{2}}}$ occurs exactly once in the string;\n- either $|s| = 1$, or substrings $s[1\\cdot\\cdot\\cdot{\\frac{|s|+1}{2}}-1]$ and $s[\\frac{s|+1}{2}+1\\cdot\\cdot\\cdot|s|]$ are the same and are Gray strings.\n\nFor example, strings \"abacaba\", \"xzx\", \"g\" are Gray strings and strings \"aaa\", \"xz\", \"abaxcbc\" are not.\n\nThe beauty of string $p$ is the sum of the squares of the lengths of all substrings of string $p$ that are Gray strings. In other words, consider all pairs of values $i, j$ $(1 ≤ i ≤ j ≤ |p|)$. If substring $p[i... j]$ is a Gray string, you should add $(j - i + 1)^{2}$ to the beauty.\n\nXenia has got string $t$ consisting of lowercase English letters. She is allowed to replace at most one letter of the string by any other English letter. The task is to get a string of maximum beauty.",
    "tutorial": "During the contest most of participants write the solutions that are very similar to the author's one. One of the author's solution uses hashes (but there exist solution without it), you can see short description of the solution below: For each position $i$ calculate with hashes the maximal value of $L_{i}$, such that substring $s[(i - L_{i} + 1)..(i + L_{i} - 1)]$ is Gray string. Also, calculate the maximal value $P_{i}$, that substring $s[(i - P_{i} + 1)..(i + P_{i} - 1)]$ differs from some Gray string in at most one position. You can see that $P_{i}  \\ge  L_{i}$. If $P_{i} > L_{i}$, also remember position and letter in the position, that differs Gray string and the substring. You can see, that if we don't need to change letters, then the answer for the problem is $\\sum_{i=1}^{\\left(3\\right)}f(L_{i})$, where $f(L) = 1^{2} + 3^{2} + 7^{2} + ... + L^{2}$. So, calculate an answer without changes. Next, iterate through all positions and letters in it. What is the new answer for the problem? Look at all Gray strings that occurs in our string and touches our fixed position. After we change this position the string will not be Gray string anymore (so we should subtract the squired length of the string from our answer). Look at all Gray strings that differs in exactly fixed position from some substring of the string. If we change the letter in the position to the fixed letter, all such strings will be added to the answer (and we should add their squired lengths). Summary, with $P_{i}$ and $L_{i}$ we need to calculate for each position and letter, how the answer differs if we change the letter in the position to the fixed one. For that reason we should use offline update (+=) on the segment. After the values will be calculated we can update our answer with all possible values.",
    "tags": [
      "dp",
      "hashing",
      "implementation",
      "string suffix structures",
      "strings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "357",
    "index": "A",
    "title": "Group of Students",
    "statement": "At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to $m$ points. We know that $c_{1}$ schoolchildren got 1 point, $c_{2}$ children got 2 points, ..., $c_{m}$ children got $m$ points. Now you need to set the passing rate $k$ (integer from 1 to $m$): all schoolchildren who got less than $k$ points go to the beginner group and those who get at strictly least $k$ points go to the intermediate group. We know that if the size of a group is more than $y$, then the university won't find a room for them. We also know that if a group has less than $x$ schoolchildren, then it is too small and there's no point in having classes with it. So, you need to split all schoolchildren into two groups so that the size of each group was from $x$ to $y$, inclusive.\n\nHelp the university pick the passing rate in a way that meets these requirements.",
    "tutorial": "In this problem you need to iterate over all possible values of passing rate from 1 to 100 and for each value calculate the sizes of two groups.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "357",
    "index": "B",
    "title": "Flag Day",
    "statement": "In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:\n\n- overall, there must be $m$ dances;\n- exactly three people must take part in each dance;\n- each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland).\n\nThe agency has $n$ dancers, and their number can be less than $3m$. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance.\n\nYou considered all the criteria and made the plan for the $m$ dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the $n$ dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.",
    "tutorial": "Let's process the dances in the given order and determine the colors of dancers' clothes. If there are no dancer from some previous dance, we can give the dances different colors arbitrarily. And if there is such dancer, we already know the color of his clothes. So, we arbitrarily distribute the other two colors between the remaning two dancers.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "358",
    "index": "A",
    "title": "Dima and Continuous Line",
    "statement": "Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.\n\nThe teacher gave Seryozha the coordinates of $n$ distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the $n$-th point. Two points with coordinates $(x_{1}, 0)$ and $(x_{2}, 0)$ should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any).\n\nSeryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem.",
    "tutorial": "If our line has self-intersections, that some pair of semi-circles exists, which intersect each other. Let points $x_{1}$ < $x_{2}$ are connected with a semi-circle and points $x_{3}$ < $x_{4}$ are connected with another semi-circle. Then this semis-circles intersect if one of the conditions is true: 1). $x_{1} < x_{3} < x_{2} < x_{4}$ 2). $x_{3} < x_{1} < x_{4} < x_{2}$ Let's iterate trough all pairs of semi-circles, and check if the semi-circles intersect each other. So, the solution will have complexity $O(N^{2})$ what satisfied the constrains.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "358",
    "index": "B",
    "title": "Dima and Text Messages",
    "statement": "Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.\n\nDima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the \"less\" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3$word_{1}$<3$word_{2}$<3 ... $word_{n}$<3.\n\nEncoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs \"more\" and \"less\" into any places of the message.\n\nInna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.",
    "tutorial": "It's clear, that adding new random symbols means, that we can simply omit them, they don't change the structure of the phrase: $< 3word_{1} < 3word_{2} < 3... word_{N} < 3$. Let's determine the phrase before inserting random elements: $s = \" < 3\" + word1 + \" < 3\" + ... + \" < 3\" + wordN + \" < 3\"$. Lets $i$ -is an index in $s$, we are waiting for. At the beginning $i$ = $0$; we will iterate though the sms and when we will meet the symbol which equals to $s_{i}$ we will simply increment $i$. if at some moment $|s|  \\le  I$ we found all needed symbols and answer is yes, otherwise - no.",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "358",
    "index": "C",
    "title": "Dima and Containers",
    "statement": "Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.\n\nInna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands:\n\n- Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end.\n- Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers.\n\nEvery time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.\n\nAs we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!",
    "tutorial": "We know all the numbers at the beginning, so, it's clear, that we want pop three maximums. We can \"precalculate \" maximums with finding next zero and iterating through all numbers between two zeroes. We should do pops from different containers, so let's save maximums in the top of the stack, in the beginning of the queue and on the beginning of the dek. (you can do this in some other way) We should determine, where will be stored the 1st, 2nd and 3rd maximum. For example, the first(the biggest one) - in the stack, second - in queue, and the third - in dek. \"trash\" - other numbers we can save into the end of the dek. Also you need to catch cases, when two or less numbers are between zeroes.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "358",
    "index": "D",
    "title": "Dima and Hares",
    "statement": "Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more.\n\nDima felt so grateful to Inna about the present that he decided to buy her $n$ hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to $n$ from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?\n\nInna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and $n$ don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.\n\nHelp Inna maximize the total joy the hares radiate. :)",
    "tutorial": "Let's look at the first hare: we chose them befoe second, or after. If it is chosen after the second, than the solution from the 2nd hare to the last doesn't depend on the first one, otherwise, we will receive the same but before the second hair will be obviously the feed hair. So, we have two dinamics: 1). $d0i$ - answer for suffix as a separate task. 2). $d1i$ - answer for suffix if the previous hair for this suffix is feed already. Movements: $d0n = an$ $d1n = bn$ $d0i = max(ai + d1i + 1, bi + d0i + 1)$ $d1i = max(bi + d1i + 1, ci + d0i + 1)$ answer is $d01$;",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "358",
    "index": "E",
    "title": "Dima and Kicks",
    "statement": "Dima is a good person. In fact, he's great. But all good things come to an end...\n\nSeryozha is going to kick Dima just few times.. For this reason he divides the room into unit squares. Now the room is a rectangle $n × m$ consisting of unit squares.\n\nFor the beginning, Seryozha put Dima in a center of some square. Then he started to kick Dima (it is known, that he kicks Dima at least once). Each time when Dima is kicked he flyes up and moves into one of four directions (up, left, right, down). On each move Dima passes $k$ $(k > 1)$ unit of the length in the corresponding direction. Seryozha is really kind, so he kicks Dima in such way that Dima never meets the walls (in other words, Dima never leave the room's space). Seryozha is also dynamic character so Dima never flies above the same segment, connecting a pair of adjacent squares, twice.\n\nSeryozha kicks Dima for a long time, but Dima is not vindictive — Dima writes. Dima marked all squares in which he was staying or above which he was flying. Thanks to kicks, Dima does not remember the $k$ value, so he asks you to find all possible values which matches to the Dima's records.",
    "tutorial": "The first thing to understand is that the answer is the divisor of maximal-length sequence of standing one by one ones. $(1111 \\dots 11)$ Let's iterate trough this number. Now we should check the table knowing the value of $K$. Let's find the most left of ones, and choose from them the most top. Let it be $(X, Y)$. then after each step Dima can appear inly in cells which look like: $(X + K * a, Y + K * b)$. Let such cells are the vertexes of the graph. And sequences of ones - the ribs. We will build the graph. We should check that there are no additional ones in table. We should also check if the graph is connected and has en Euler's path. The value of K is the next answer under the all conditions. The correct implementation will have the complexity $O(N * N * log(N))$. In reality it will be never achieved.",
    "tags": [
      "brute force",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "359",
    "index": "A",
    "title": "Table",
    "statement": "Simon has a rectangular table consisting of $n$ rows and $m$ columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the $x$-th row and the $y$-th column as a pair of numbers $(x, y)$. The table corners are cells: $(1, 1)$, $(n, 1)$, $(1, m)$, $(n, m)$.\n\nSimon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table.\n\nInitially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table $(x_{1}, y_{1})$, an arbitrary corner of the table $(x_{2}, y_{2})$ and color all cells of the table $(p, q)$, which meet both inequations: $min(x_{1}, x_{2}) ≤ p ≤ max(x_{1}, x_{2})$, $min(y_{1}, y_{2}) ≤ q ≤ max(y_{1}, y_{2})$.\n\nHelp Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.",
    "tutorial": "If there are some good cell, which is located in the first row or in the first column, the answer is two. Similarly, if If there are some good cell, which is located in the last row or in the last column, the answer is two. Otherwise, the answer is four",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "359",
    "index": "B",
    "title": "Permutation",
    "statement": "A permutation $p$ is an ordered group of numbers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each is no more than $n$. We'll define number $n$ as the length of permutation $p_{1}, p_{2}, ..., p_{n}$.\n\nSimon has a positive integer $n$ and a non-negative integer $k$, such that $2k ≤ n$. Help him find permutation $a$ of length $2n$, such that it meets this equation: $\\sum_{i=1}^{n}|a_{2i-1}-a_{2i}|-|\\sum_{i=1}^{n}a_{2i-1}-a_{2i}|=2k$.",
    "tutorial": "The answer is a slightly modified permutation $1, 2, ..., 2n$. Let's reverse numbers $2i - 1$ and $2i$ for each $1  \\le  i  \\le  k$. It's not hard to understand, that this permutation is good.",
    "tags": [
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "359",
    "index": "C",
    "title": "Prime Number",
    "statement": "Simon has a prime number $x$ and an array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$.\n\nSimon loves fractions very much. Today he wrote out number ${\\frac{1}{x^{a}!}}+{\\frac{1}{x^{a}2}}+\\ddots\\div\\nonumber+{\\frac{1}{x^{a}n}}$ on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: $\\scriptstyle{\\frac{3}{t}}$, where number $t$ equals $x^{a1 + a2 + ... + an}$. Now Simon wants to reduce the resulting fraction.\n\nHelp him, find the greatest common divisor of numbers $s$ and $t$. As GCD can be rather large, print it as a remainder after dividing it by number $1000000007$ ($10^{9} + 7$).",
    "tutorial": "Obviously, the answer is $x^{v}$. Let $sum = a_{1} + a_{2} + ... + a_{n}$. Also let $s_{i} = sum - a_{i}$ (the array of degrees). After that let's find value $v$ by the following algorithm: Let's consider a sequence of degrees as decreasing sequence. Now we will perform the following operation until it's possible to perfom it. Take the minimum degree $v$ from the array of degrees and calculate the number of elements $cnt$, which have the same degree. If $cnt$ multiples of $x$, then replace all $cnt$ elements by $cnt / x$ elements of the form $v + 1$. Since the sequence of degrees is a decreasing sequence, we can simply assign them to the end. If $cnt$ is not a multiple of $x$, then we found the required value $v$. Also you need to check, that $v$ is not greater then $sum$. Otherwise, $v$ will be equals to $sum$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "359",
    "index": "D",
    "title": "Pair of Numbers",
    "statement": "Simon has an array $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers. Today Simon asked you to find a pair of integers $l, r$ $(1 ≤ l ≤ r ≤ n)$, such that the following conditions hold:\n\n- there is integer $j$ ($l ≤ j ≤ r$), such that all integers $a_{l}, a_{l + 1}, ..., a_{r}$ are divisible by $a_{j}$;\n- value $r - l$ takes the maximum value among all pairs for which condition $1$ is true;\n\nHelp Simon, find the required pair of numbers $(l, r)$. If there are multiple required pairs find all of them.",
    "tutorial": "Quite simple note: if the pair $(l, r)$ satisfies the condition 1 from the statements, then $min(l, r) = GCD(l, r)$, where $min(l, r)$ is smallest number $a_{i}$ from the segment (l, r) and $GCD(l, r)$ is a GCD of all numbers from the segment (l, r). Calculate some data structure that will allow us to respond quickly to requests $GCD(l, r)$ and $min(l, r)$. For example, you can use Sparce Table. Solutuions, that uses segment tree, is too slow. So I think, you should use Sparce Table. So, now our task quite simple. Let's use binary search to find greatest value of $r - l$: $ok(mid)$ is the function, that determines, is there some segment where $min(l, r) = GCD(l, r)$ and $mid = r - l$ ($mid$ - is fixed value by binary search). If there is some good segment, you should update boundaries of binary search correctly. After that, it's very simple to restore answer.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "359",
    "index": "E",
    "title": "Neatness",
    "statement": "Simon loves neatness. So before he goes to bed, Simon wants to complete all chores in the house.\n\nSimon's house looks like a rectangular table consisting of $n$ rows and $n$ columns from above. All rows of the table are numbered from $1$ to $n$ from top to bottom. All columns of the table are numbered from $1$ to $n$ from left to right. Each cell of the table is a room. Pair $(x, y)$ denotes the room, located at the intersection of the $x$-th row and the $y$-th column. For each room we know if the light is on or not there.\n\nInitially Simon is in room $(x_{0}, y_{0})$. He wants to turn off the lights in all the rooms in the house, and then return to room $(x_{0}, y_{0})$. Suppose that at the current moment Simon is in the room $(x, y)$. To reach the desired result, he can perform the following steps:\n\n- The format of the action is \"1\". The action is to turn on the light in room $(x, y)$. Simon cannot do it if the room already has light on.\n- The format of the action is \"2\". The action is to turn off the light in room $(x, y)$. Simon cannot do it if the room already has light off.\n- The format of the action is \"dir\" ($dir$ is a character). The action is to move to a side-adjacent room in direction $dir$. The direction can be left, right, up or down (the corresponding dir is L, R, U or D). Additionally, Simon can move only if he see a light in the direction $dir$. More formally, if we represent the room, Simon wants to go, as $(nx, ny)$, there shold be an integer $k$ $(k > 0)$, that room $(x + (nx - x)k, y + (ny - y)k)$ has a light. Of course, Simon cannot move out of his house.\n\nHelp Simon, find the sequence of actions that lets him achieve the desired result.",
    "tutorial": "You should write recursive function, that will turn on the light in all rooms, where it's possible. Also this function will visit all rooms, which it may visit. Let this function is called paint(x, y), where x, y is the current room. $Paint(x, y)$ will use following idea: Let's look at all neighbors. If there is a light in the current direction (rule $3$ from the statement), and the room $(nx, ny)$ (current neighbor) has not yet visited, we will call our recursive function from $(nx, ny)$. Also, we will turn on the light in all rooms, were we were. If some room is not visited by $paint(x, y)$ and lights is on in this room, the answer is \"NO\". Otherwise, the answer is \"YES\". After that let's calculate value $dist(x, y)$ by using bfs. $dist(x, y)$ - is a minimal possible distance from the start to the current position $(x, y)$. It's possible to use in our bfs only rooms, where lights is on. After that we will write the same function $repaint(x, y)$. $Repaint(x, y)$ will use following idea: Let's look at all neighbors. If there is a light in the current neighbor $(nx, ny)$ and $dist(nx, ny) > dist(x, y)$ ($(x, y)$ - current room), let's call our recursive function from $(nx, ny)$.After that we will come back to room $(x, y)$. If there is no such neigbor $(nx, ny)$, turn off the light in the room $(x, y)$. Also you should look at my solution for more details.",
    "tags": [
      "constructive algorithms",
      "dfs and similar"
    ],
    "rating": 2400
  },
  {
    "contest_id": "360",
    "index": "A",
    "title": "Levko and Array Recovery",
    "statement": "Levko loves array $a_{1}, a_{2}, ... , a_{n}$, consisting of integers, very much. That is why Levko is playing with array $a$, performing all sorts of operations with it. Each operation Levko performs is of one of two types:\n\n- Increase all elements from $l_{i}$ to $r_{i}$ by $d_{i}$. In other words, perform assignments $a_{j} = a_{j} + d_{i}$ for all $j$ that meet the inequation $l_{i} ≤ j ≤ r_{i}$.\n- Find the maximum of elements from $l_{i}$ to $r_{i}$. That is, calculate the value $m_{i}=\\operatorname*{max}_{j=l_{i}}a_{j}$.\n\nSadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array $a$. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed $10^{9}$ in their absolute value, so he asks you to find such an array.",
    "tutorial": "Let's find such value $b[i]$ that $a[i]  \\le  b[i]$ for all indeces $i$. Let's simulate all operations and $diff[i]$ will be the difference between current value of $i$-th element and its initial value. If we have operation of first type, we change values of $diff[i]$. If we have operation of second type, we know that $a[i] + diff[i]  \\le  m[i]$, so $a[i]  \\le  m[i] - diff[i]$. We will get array $b$ when we union all this inequalities. Let's prove that either $b$ satisfied all conditions or there is no such array. It can be two cases, why $b$ does not suit: $\\operatorname*{m}_{j\\simeq L_{i}}^{\\mathrm{fax}}b_{j}>m_{i}$ - it's impossible due to construction of array $b$. $\\operatorname*{max}_{j=L_{i}}b_{j}<m_{i}$ - $b[i]$ is a maximal possible value of $a[i]$, so $\\operatorname*{m}_{j\\to L_{i}}^{\\mathrm{fix}}a_{j}$ can't be bigger.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "360",
    "index": "B",
    "title": "Levko and Array",
    "statement": "Levko has an array that consists of integers: $a_{1}, a_{2}, ... , a_{n}$. But he doesn’t like this array at all.\n\nLevko thinks that the beauty of the array $a$ directly depends on value $c(a)$, which can be calculated by the formula:\n\n\\[\nc(a)=\\operatorname*{max}_{1<i<n-1}|a_{i+1}-a_{i}|,n>1;c(a)=0,0\\leq n\\leq1.\n\\]\n\nThe less value $c(a)$ is, the more beautiful the array is.It’s time to change the world and Levko is going to change his array for the better. To be exact, Levko wants to change the values of at most $k$ array elements (it is allowed to replace the values by any integers). Of course, the changes should make the array as beautiful as possible.\n\nHelp Levko and calculate what minimum number $c(a)$ he can reach.",
    "tutorial": "Let's solve this problem using binary search. We need to check whether we can achieve an array, when $c(a)$ will be at most $x$. Lets make dp. $dp[i]$ means minimal number of elements with indeces less than $i$, which we need to change, but we don't change $i$-th element. Let's iterate next element $j$, which we don't change. Then we know that we can change all elements between $i$ and $j$. It is equivalent to such condition $|a_{j} - a_{i}|  \\le  (j - i) \\cdot x$ Difference between neighboring elements can be at most $x$. The maximal possible difference increases by $x$ exactly $j - i$ times between elements $i$ and $j$, so this inequality is correct.",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "360",
    "index": "C",
    "title": "Levko and Strings",
    "statement": "Levko loves strings of length $n$, consisting of lowercase English letters, very much. He has one such string $s$. For each string $t$ of length $n$, Levko defines its beauty relative to $s$ as the number of pairs of indexes $i$, $j$ $(1 ≤ i ≤ j ≤ n)$, such that substring \\textbf{$t[i..j]$ is lexicographically larger than substring $s[i..j]$}.\n\nThe boy wondered how many strings $t$ are there, such that their beauty relative to $s$ equals exactly $k$. Help him, find the remainder after division this number by $1000000007$ $(10^{9} + 7)$.\n\nA substring $s[i..j]$ of string $s = s_{1}s_{2}... s_{n}$ is string $s_{i}s_{i + 1}... s_{j}$.\n\nString $x = x_{1}x_{2}... x_{p}$ is lexicographically larger than string $y = y_{1}y_{2}... y_{p}$, if there is such number $r$ ($r < p$), that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. The string characters are compared by their ASCII codes.",
    "tutorial": "Let's count amount of such substrings of $t$ that are bigger than corresponding substring of $s$ and begin at the position $i$. If $t[i] < s[i]$, this amount equals $0$. If $t[i] > s[i]$, this amount equals $n - i$. If $t[i] = s[i]$, then let's find such nearest position $j, j > i$ , that $t[j]  \\neq  s[j]$. If $t[j] > s[j]$, needed amount of substrings will be $n - j$. If $t[j] < s[j]$, needed amount of substrings will be $0$. We can rephrase this: If $t[i] > s[i]$, it will be $(1 + pref) \\cdot (n - i)$ new substrings, where $pref$ means how many last elements in $s$ and $t$ is equal. Let's make dp. $dp[i][sum]$ means that we viewed $i$ positions, have $sum$ needed substrings and $s[i]  \\neq  t[i]$. Lets iterate their common prefix $pref$. If $t[i] < s[i]$, $dp[i][sum] + = dp[i - pref - 1][sum] \\cdot (s[i] - 'a')$ - we can count this value using partial sums. If $t[i] > s[i]$, $dp[i][sum] + = dp[i - pref - 1][sum - (1 + pref) \\cdot (n - i)] \\cdot ('z' - s[i])$. Let's iterate $pref$. Let's note that $sum - pref \\cdot (n - i)  \\ge  0$, so $pref  \\le  sum / (n - i)$ and $pref  \\le  k / (n - i)$. This means that third cycle will make at most $k / (n - i)$ iterations when we find value of $dp[i][sum]$. Let's count total number of iterations: $i t=k\\cdot(\\sum_{i=0}^{n-1}\\frac{k}{n-i})$ $=$ $k\\cdot(\\sum_{i=0}^{n-1}{\\frac{k}{i}})$ $<$ $k \\cdot (n + k \\cdot log k)$.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "360",
    "index": "D",
    "title": "Levko and Sets",
    "statement": "Levko loves all sorts of sets very much.\n\nLevko has two arrays of integers $a_{1}, a_{2}, ... , a_{n}$ and $b_{1}, b_{2}, ... , b_{m}$ and a prime number $p$. Today he generates $n$ sets. Let's describe the generation process for the $i$-th set:\n\n- First it has a single number $1$.\n- Let's take any element $c$ from this set. For all $j$ ($1 ≤ j ≤ m$) if number $(c·a_{i}^{bj}) mod p$ doesn't occur in the set, then add it to the set.\n- Repeat step $2$ as long as we can add at least one element to our set.\n\nLevko wonders, how many numbers belong to at least one set. That is, he wants to know what size is the union of $n$ generated sets.",
    "tutorial": "$p$ is prime, so there exist primitive root $g$ modulo $p$(We don't need to find it, but we know that it exists). We can write $a_{i} = g^{ri}$. Note, that $i$-th set consists of all numbers $\\frac{\\vec{\\mathbf{a}}}{a_{i}^{j=1}}b_{j}.c_{j}$, where $c_{j}  \\ge  0$, or we can write it as ${g^{t}}_{j=1}^{\\infty}b_{j}.c_{j}$. By Fermat's little theorem $a^{p - 1} = 1 mod p$ we have that $a^{k} mod p = a^{k mod (p - 1)} mod p$. So $\\sum_{j=1}^{m}b_{j}\\cdot c_{j}$ can be equal to all values $k \\cdot t$ modulo $p - 1$, where $t = gcd(b_{1}, b_{2}, ... , b_{m}, p - 1)$. Note that $t$ doesn't depend on $r_{i}$, so we can assign $g = g^{t}$. Then all elements of $i$-th set will be $g^{ri \\cdot k}$, where $k  \\ge  0$. Now we can replace $b_{i}$ by $q_{i}$, where $q_{i} = gcd(r_{i}, p - 1)$, as we do with $b_{i}$ at the beginning. Then all elements of $i$-th set will be $g^{qi \\cdot k}$, where $k  \\ge  0$. This means that if we write all values $g^{0}, g^{1}, ..., g^{p - 2}$ in a line, $i$-th set will contain every $q_{i}$-th element. Now we need to find union of this sets.Let's do it using inclusion-exclusion principle. All our numbers are divisors of $p - 1$. Let's $dp_{i}$ be the coefficient near $i$ in inclusion-exclusion principle($i$ is a divisor of $p - 1$) and we can find this values, adding all $q_{i}$ alternatively. Also we need to find $q_{i}$. Let's find volume of the i-th set. It is equal to $\\frac{p-1}{q_{i}}$. From the other side it is equal to such minimal number $d_{i}$, that $a_{i}^{di} = 1 mod p$ ($d_{i}$ is a cycle). From $a_{i}^{p - 1} = 1 mod p$ we have that $p - 1$ is divisible by $d_{i}$. So we can find $d_{i}$ as a divisor of $p - 1$. And $q_{i}={\\frac{p-1}{d_{i}}}$.",
    "tags": [
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "360",
    "index": "E",
    "title": "Levko and Game",
    "statement": "Levko loves sports pathfinding competitions in his city very much. In order to boost his performance, Levko spends his spare time practicing. The practice is a game.\n\nThe city consists of $n$ intersections connected by $m + k$ directed roads. Two or more roads can connect the same pair of intersections. Besides, there can be roads leading from an intersection to itself.\n\nLevko and Zenyk are playing a game. First Levko stands on intersection $s_{1}$, and Zenyk stands on intersection $s_{2}$. They both want to get to intersection $f$. The person who does it quicker wins. If they get there at the same time, the game ends with a draw. By agreement both players start simultaneously and move with the same speed.\n\nLevko wants to win very much. He knows the lengths of all the roads in the city. Also he knows that he can change the lengths of some roads (there are $k$ such roads at all) if he pays the government. So, the government can change the length of the $i$-th road to any integer value in the segment [$l_{i}$, $r_{i}$] (both borders inclusive). Levko wondered if he can reconstruct the roads so as to win the game and whether he can hope for the draw if he cannot win.\n\nYou should consider that both players play optimally well. It is guaranteed that we can get from intersections $s_{1}$ and $s_{2}$ to intersection $f$.",
    "tutorial": "Algorithm: Firstly we will solve problem if first player can win. Let's make all roads that we can change equal to $r[i]$ and do two Dijkstra's algorithms from vertices $s_{1}$ and $s_{2}$. Let's $d1[i]$ be the distance from $s_{1}$ to $i$, $d2[i]$ be the distance from $s_{2}$ to $i$. Consider a road, that we can change, from $a$ to $b$. If $d1[a] < d2[a]$, we will set length of such road equal to $l[i]$ and do two Dijkstra's algorithms again. We run such process until any road changes its length. If $d1[f] < d2[f]$ after all changes then first player wins. If we replace condition $d1[a] < d2[a]$ by $d1[a]  \\le  d2[a]$, we can check if Levko can end this game with a draw. Proof: Let's call \"edges\" only roads which Levko can change. When we do Dijkstra's algorithm we use all roads, not only edges. Let's prove that if there exist such edges values that first player wins, there exist values of edges such that first player wins and all this values equal either $l[i]$ or $r[i]$. Consider shortest pathes of both players. If only first player goes on edge from $a$ to $b$, we can set its value $l[i]$. Proof: there must hold $d1[a] < d2[a]$ because first player goes on it and wins. This condition holds after change of value of this edge. If second player goes on this edge, he loses because $d1[f]  \\le  d1[a] + d(a, b) + d(b, f) < d2[a] + d(a, b) + d(b, F) = d2[f]$. If second player doesn't go on this edge, he loses because shortest path of first player became smaller($d(x, y)$ - shortest path from $x$ to $y$). If only second player goes on edge from $a$ to $b$, we can set its value $r[i]$. Proof: Shortest path of the first player doesn't change and shortest path of second player can only become larger. If no player go on edge, we can set its value $r[i]$. Proof: Shortest pathes of both players doesn't change. If both players go on edge from $a$ to $b$, we can set its value $l[i]$. Proof: Shortest pathes of both players decrease by (initial value of this edge - $l[i]$). After every such operation first player wins again and all edges become either $l[i]$ or $r[i]$. Consider result of our algorithm. Let's call edge \"good\" if its value is equal to $l[i]$ and \"bad\" if its value equals $r[i]$. (a) Let's prove that after performing all operations we will have $d1[a] < d2[a]$ for all good edges $(a, b)$. If we have $d1[a1] < d2[a1]$ for edge $(a1, b1)$ and after changing value of $(a2, b2)$ this condition doesn't hold. We have $d1[a1] > = d2[a1]$, $d1[a2] < d2[a2]$. We change only one edge and shortest path from $s2$ to $f$ become shorter so edge $(a2, b2)$ lies on this path. $d2[a1] = d2[a2] + d(a2, b2) + d(b2, a1) > d1[a2] + d(a2, b2) + d(b2, a1)  \\ge  d1[a1]$. Contradiction. (b) Let's prove that after performing all operations we will have $d1[a]  \\ge  d2[a]$ for all bad edges. We can continue our procces otherwise. (c) Let's prove that if condition $d1[a] < d2[a]$ holds for some edge but we doesn't change it on this iteration, this continion holds after this iteration. Proof is same as in (a). (d) Let's prove that if any subset of good edges is equal to $l[i]$ and $d1[a] < d2[a]$, ift also holds when we make all good edges equal $l[i]$. Let's simulate all procces and use (c). Lets prove that for all edges values(not necessary only $l[i]$ or $r[i]$), $d1[a]  \\ge  d2[a]$ for all bad edges $(a, b)$. Assume that we have such edge. Consider shortest path of first player to its beginning. If there exist bad edges $(a1, b1)$ on this path, there must holds inequality $d1[a1] < d2[a1]$. Consider first of this bad edges $(a, b)$. Then shortest path of first player to $a$ doesn't consist any bad edge. Consider problem,m which is equivalent to our problem but finish is in vertex $a$. good and bad edges will be same. Let's change all value of edges as we do in item 1. Note? that all bad edges will be equal to $r[i]$. So only subset of good edges can be equal to $l[i]$ and $d1[a1] < d2[a1]$. By (d) we have that we can set all good edges $l[i]$ and condition $d1[a1] < d2[a1]$ will be satisfied. So we have contradiction thst this edge is bad. This means that if first player goes on any bad edge, he loses. So we can set $r[i]$ to all this edges. So we can set $l[i]$ to some subset of good edges. By (d) we have that if we have $d1[f] < d2[f]$ for some subset of good edges, this condition will be true if we set all good edges $l[i]$. Note that proof will be same if we want to check whether Levko can end a game with a draw.",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2800
  },
  {
    "contest_id": "361",
    "index": "A",
    "title": "Levko and Table",
    "statement": "Levko loves tables that consist of $n$ rows and $n$ columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals $k$.\n\nUnfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.",
    "tutorial": "Matrix,in which all diagonal elements equal $k$ and other elements equal $0$, satisfied all conditions. For example, if n = 4 and k = 7, our matrix will be 7 0 0 0 0 7 0 0 0 0 7 0 0 0 0 7",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "361",
    "index": "B",
    "title": "Levko and Permutation",
    "statement": "Levko loves permutations very much. A permutation of length $n$ is a sequence of distinct positive integers, each is at most $n$.\n\nLet’s assume that value $gcd(a, b)$ shows the greatest common divisor of numbers $a$ and $b$. Levko assumes that element $p_{i}$ of permutation $p_{1}, p_{2}, ... , p_{n}$ is good if $gcd(i, p_{i}) > 1$. Levko considers a permutation beautiful, if it has exactly $k$ good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.",
    "tutorial": "$gcd(1, m) = 1$, so if $n = k$, there is no suitable permutation. It is well known that $gcd(m, m - 1) = 1$. Lets construct following permutation. It has exactly $k$ good elements. $n - k 1 2 3 ... n - k - 1 n - k + 1 n - k + 2 ... n$",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "362",
    "index": "A",
    "title": "Two Semiknights Meet",
    "statement": "A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: $2$ squares forward and $2$ squares to the right, $2$ squares forward and $2$ squares to the left, $2$ squares backward and $2$ to the right and $2$ squares backward and $2$ to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.\n\nPetya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.\n\nPetya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.\n\nPlease see the test case analysis.",
    "tutorial": "Autors have proposed different solutions. One can notice that if semiknights did not have a meeting after first step (it is not necessary they have a meeting in \"good\" square), they will not meet at all. This fact appears from board size and possible semiknight's moves. As the initial semiknight's squares are considered good for the meeting the semiknights have arrived to the one square and then they move together to one of the initial squares and meeting will count.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "362",
    "index": "B",
    "title": "Petya and Staircases",
    "statement": "Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.\n\nNow Petya is on the first stair of the staircase, consisting of $n$ stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number $n$ without touching a dirty stair once.\n\nOne has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.",
    "tutorial": "One has to note that the number of dirty stairs $ \\le  3000$. Petya can reach stair number $n$ if the first and the last stairs are not dirty and there are not three or more dirty stairs in a row. So let sort the array of dirty stairs and go through it, checking for three or more consecutive dirty stairs. Also one need to check if the first or the last stair is in this array.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "362",
    "index": "C",
    "title": "Insertion Sort",
    "statement": "Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array $a$ of size $n$ in the non-decreasing order.\n\n\\begin{verbatim}\nfor (int i = 1; i < n; i = i + 1)\n{\nint j = i;\nwhile (j > 0 && a[j] < a[j - 1])\n{\nswap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1]\nj = j - 1;\n}\n}\n\\end{verbatim}\n\nPetya uses this algorithm only for sorting of arrays that are permutations of numbers from $0$ to $n - 1$. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.\n\nIt is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.",
    "tutorial": "The number of times swap is called equals the number of inversions in the input permutation. It's easy to see that it is reasonable to swap only such elements $a_{i}$, $a_{j}$ that $i < j$ and $a_{i} > a_{j}$ (otherwise the number of inversions will increase). Let $d_{i, j}$ be the number of permutation of elements with indices from $0$ to $i$ inclusive which are strictly less than $j$. Then, after swapping elements with indices $i$ and $j$, the number of inversions will be $old - 2 * (d_{i, ai} + d_{j, aj} - d_{i, aj} - d_{j, ai}) - 1$, where old is the number of inversions in the initial permutation. It is sufficient to search all pairs of elements and pick those which help to minimize the number of inversions. The reader may prove the correctness of the formula as a supplementary task.",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "362",
    "index": "D",
    "title": "Fools and Foolproof Roads",
    "statement": "You must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of $n$ cities, some pairs of cities are connected by bidirectional roads, each road is described by its length $l_{i}$.\n\nThe fools lived in their land joyfully, but a recent revolution changed the king. Now the king is Vasily the Bear. Vasily divided the country cities into regions, so that any two cities of the same region have a path along the roads between them and any two cities of different regions don't have such path. Then Vasily decided to upgrade the road network and construct exactly $p$ new roads in the country. Constructing a road goes like this:\n\n- We choose a pair of \\textbf{distinct} cities $u$, $v$ that will be connected by a new road (at that, it is possible that there already is a road between these cities).\n- We define the length of the new road: if cities $u$, $v$ belong to distinct regions, then the length is calculated as $min(10^{9}, S + 1)$ ($S$ — the total length of all roads that exist in the linked regions), otherwise we assume that the length equals $1000$.\n- We build a road of the specified length between the chosen cities. If the new road connects two distinct regions, after construction of the road these regions are combined into one new region.\n\nVasily wants the road constructing process to result in the country that consists exactly of $q$ regions. Your task is to come up with such road constructing plan for Vasily that it meets the requirement and minimizes the total length of the built roads.",
    "tutorial": "If the given graph contains less than $q$ connectivity components, then there's no solution. Otherwise it's optimal at first add edges that connect different components and afterwards all remaining edges (they will be connect edges from one component). For the first phase you can use greedy algorithm: each time you select two components, current weight of which is minimal, and connect them with an edge. For example, you can store weights of all components in the current graph in some data structure (like set in C++). For the second phase it's enough to find any component that contains two or more vertices (because loops are forbidden) and add all remaining edges between some two vertices of this component. If some action cannot be successfully executed (for example, you added all the edges and number of connectivity components if greater than $q$), then there's no solution. Asymptotics - $O(n + m + plogn).$",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "362",
    "index": "E",
    "title": "Petya and Pipes",
    "statement": "A little boy Petya dreams of growing up and becoming the Head Berland Plumber. He is thinking of the problems he will have to solve in the future. Unfortunately, Petya is too inexperienced, so you are about to solve one of such problems for Petya, the one he's the most interested in.\n\nThe Berland capital has $n$ water tanks numbered from $1$ to $n$. These tanks are connected by unidirectional pipes in some manner. Any pair of water tanks is connected by at most one pipe in each direction. Each pipe has a strictly positive integer width. Width determines the number of liters of water per a unit of time this pipe can transport. The water goes to the city from the main water tank (its number is $1$). The water must go through some pipe path and get to the sewer tank with cleaning system (its number is $n$).\n\nPetya wants to increase the width of some subset of pipes by at most $k$ units in total so that the width of each pipe remains integer. Help him determine the maximum amount of water that can be transmitted per a unit of time from the main tank to the sewer tank after such operation is completed.",
    "tutorial": "Construct the following flow network. Water tank $1$ is the source, water tank $n$ is the sink. Every pipe from water tank $u$ to water tank $v$ is presented as two arcs - the first one with capacity $c_{uv}$ and cost $0$ and the second one with infinite capacity and cost $1$. Thus, the answer is the maximum flow with cost not greater than k. It can be found by standard augmenting paths algorithm.",
    "tags": [
      "flows",
      "graphs",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "363",
    "index": "A",
    "title": "Soroban",
    "statement": "You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban — an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about them. Let's have a look at the Soroban's construction.\n\nSoroban consists of some number of rods, each rod contains five beads. We will assume that the rods are horizontal lines. One bead on each rod (the leftmost one) is divided from the others by a bar (the reckoning bar). This single bead is called go-dama and four others are ichi-damas. Each rod is responsible for representing a single digit from 0 to 9. We can obtain the value of a digit by following simple algorithm:\n\n- Set the value of a digit equal to 0.\n- If the go-dama is shifted to the right, add 5.\n- Add the number of ichi-damas shifted to the left.\n\nThus, the upper rod on the picture shows digit 0, the middle one shows digit 2 and the lower one shows 7. We will consider the top rod to represent the last decimal digit of a number, so the picture shows number 720.\n\nWrite the program that prints the way Soroban shows the given number $n$.",
    "tutorial": "Not so much to say about this problem. You need to extract the digits of the given number (read it as string or repeteadly divide by 10 and take the remainders). Then carefully do the mapping of digits to its' representation.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "363",
    "index": "B",
    "title": "Fence",
    "statement": "There is a fence in front of Polycarpus's home. The fence consists of $n$ planks of the same width which go one after another from left to right. The height of the $i$-th plank is $h_{i}$ meters, distinct planks can have distinct heights.\n\n\\begin{center}\n{\\small Fence for $n = 7$ and $h = [1, 2, 6, 1, 1, 7, 1]$}\n\\end{center}\n\nPolycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly $k$ consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such $k$ consecutive planks that the sum of their heights is minimal possible.\n\nWrite the program that finds the indexes of $k$ consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).",
    "tutorial": "Another easy problem. We need to calculate the sum of every consequtive segment of $k$ planks. One way to do this is to calculate partial prefix sums: $s_{i}=\\sum_{j\\leq i}h_{j}$. Then the sum of heights of the planks $i, i + 1, ..., i + k - 1$ is $s_{i + k - 1} - s_{i - 1}$. The other approach is to calculate the sum of the first $k$ planks: $h_{1} + h_{2} + ... + h_{k}$. By subtracting $h_{1}$ and adding $h_{k + 1}$ we get sum of $k$ planks starting from the second plank. Then, by subtracting $h_{2}$ and adding $h_{k + 2}$ we get sum of $k$ planks starting from the third plank, and so on.",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 1100
  },
  {
    "contest_id": "363",
    "index": "C",
    "title": "Fixing Typos",
    "statement": "Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.\n\nIn this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word \"helllo\" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words \"helloo\" and \"wwaatt\" contain typos).\n\nWrite a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.",
    "tutorial": "The general idea of the solution is the following: while there are three consequtive equal characters, remove any one of them. After that we can only have typos of the second type. So, if we have one couple of equal characters immediately after another couple of equal characters ($xxyy$), we need to decide which character to remove, $x$ or $y$? Let's find the leftmost typo of the second type in the string. It is easy to see that we can always remove the character from the second couple. All these can be done in a single pass. Go through the characters of the given string and build the resulting string $ans$. Let's denote the current character as $ch$. If $ch$ is equal to the last two characters of $ans$, skip $ch$. If $ch$ is equal to the last character of $ans$ and $ans[length(ans) - 2] = ans[length(ans) - 3]$ (assume that $ans$ is 1-indexed), skip $ch$. Otherwise, append $ch$ to $ans$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "363",
    "index": "D",
    "title": "Renting Bikes",
    "statement": "A group of $n$ schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.\n\nThe renting site offered them $m$ bikes. The renting price is different for different bikes, renting the $j$-th bike costs $p_{j}$ rubles.\n\nIn total, the boys' shared budget is $a$ rubles. Besides, each of them has his own personal money, the $i$-th boy has $b_{i}$ personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.\n\nEach boy can rent at most one bike, one cannot give his bike to somebody else.\n\nWhat maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?",
    "tutorial": "Let's do a binary search over the number of boys that can rent a bike. So let's say that we want to check whether it possible for $k$ boys to rent bikes. If some $k$ boys can rent a bike, then the $k$ \"richest\" boys (with the most amount of personal money) also can do that. It is easy to see that if they can rent bikes, they can rent $k$ cheapest bikes (if we first sort the bikes in increasing order of price, it will be just the first $k$ bikes). So, take $k$ richest boys and try to match them with $k$ cheapest bikes, spending as much common budget as possible. The following algorithm works (try to understand and prove it before asking questions): take the boy with least number of money (of course, among the considered $k$ richest) and try to give him the cheapest bike. If the boy has ehough personal money to rent this bike, use his money to do this. Otherwise, use all his money and take some money from the common budget. Continue this process with the second cheapest bike and the second \"poorest among the richest\" boys. This process can end in two ways: we will either run out of budget and fail to rent $k$ bikes, or we will successfully rent these bikes.",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "364",
    "index": "A",
    "title": "Matrix",
    "statement": "You have a string of decimal digits $s$. Let's define $b_{ij} = s_{i}·s_{j}$. Find in matrix $b$ the number of such rectangles that the sum $b_{ij}$ for all cells $(i, j)$ that are the elements of the rectangle equals $a$ in each rectangle.\n\nA rectangle in a matrix is a group of four integers $(x, y, z, t)$ \\textbf{$(x ≤ y, z ≤ t)$}. The elements of the rectangle are all cells $(i, j)$ such that $x ≤ i ≤ y, z ≤ j ≤ t$.",
    "tutorial": "Let's notice that sum in the rectangle $(x1, y1, x2, y2)$ is $sum(x1, x2) \\cdot sum(y1, y2)$. Where $sum(l, r) = s_{l} + s_{l + 1} + ... + s_{r}$. Then, we have to calc $sum(l, r)$ for every pair $(l, r)$ and count how many segments give us sum $x$ for any possible x ($0  \\le  x  \\le  9 \\cdot |s|$). In the end we should enumerate sum on segemnt $[x1, x2]$ and find $s u m(y1,y2)={\\frac{a}{s u m(x1.x2)}}$. There is corner case $a = 0$.",
    "tags": [
      "combinatorics",
      "data structures",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "364",
    "index": "B",
    "title": "Free Market",
    "statement": "John Doe has recently found a \"Free Market\" in his city — that is the place where you can exchange some of your possessions for other things for free.\n\nJohn knows that his city has $n$ items in total (each item is unique). You can bring any number of items to the market and exchange them for any other one. Note that each item is one of a kind and that means that you cannot exchange set ${a, b}$ for set ${v, a}$. However, you can always exchange set $x$ for any set $y$, unless there is item $p$, such that $p$ occurs in $x$ and $p$ occurs in $y$.\n\nFor each item, John knows its value $c_{i}$. John's sense of justice doesn't let him exchange a set of items $x$ for a set of items $y$, if $s(x) + d < s(y)$ ($s(x)$ is the total price of items in the set $x$).\n\nDuring one day John can exchange only one set of items for something else. Initially, he has no items. John wants to get a set of items with the maximum total price. Find the cost of such set and the minimum number of days John can get it in.",
    "tutorial": "We may assume that John may exchange any subset of his items $x$ to any other subset $y$, such as $s(x) + d  \\ge  s(y)$ (it does not matter if $x$ intersects $y$). We can find all possible sums in subset of elements of the given set of items using standard dp (knapsack problem). John should always exchange all his current set of items to another, because if he had exchanged some subset of $x$ (current set) $z$ to $y$, we can say that he had exchanged $x$ to $(x\\backslash y)\\cap z$. So, we have to find shortest sequence of sets $a$, such as $s(a_{i + 1}) - d  \\ge  s(a_{i})$ for any possible $i$ and $a_{0} = {}$. This subtask could be solved using following greedy algorithm. $a_{i}, i > 0$ is maximal correct sum such as $a_{i}  \\le  a_{i - 1} + d$. Consider optimal answer $c$ and our answer $a$. Let $k$ is the first position where $a_{k}  \\neq  c_{k}$ obiviously $a_{k} > c_{k}$ (because $a_{k}$ selected as maximal as possible). Then consider $q$ such as $q_{i} = c_{i}$ for $i  \\neq  k$ and $q_{k} = a_{k}$. $q$ is either optimal. Applying similar operations we will obtain $a$. So, $a$ is optimal.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "364",
    "index": "C",
    "title": "Beautiful Set",
    "statement": "We'll call a set of positive integers $a$ beautiful if the following condition fulfills: for any prime $p$, if $\\exists x\\in a,x\\equiv0\\;\\;\\mathrm{mod}\\;p$, then $|\\{y\\in a|y\\equiv0\\mathrm{\\boldmath~\\mod~}p\\}|\\geq\\textstyle{\\frac{\\vert a|}{2}}$. In other words, if one number from the set is divisible by prime $p$, then at least half of numbers from the set is divisible by $p$.\n\nYour task is to find any beautiful set, where the number of elements is equal to $k$ and each element doesn't exceed $2k^{2}$.",
    "tutorial": "We expected many unproved, but tested solutions. I think that careful prove of my solution with pen and paper is very difficult. So I will use some statistic-based facts. Consider the set of divisors of number $k$. One can check that it's beautiful set. If factorisation of $k$ has the form $\\textstyle{\\prod_{i=0}^{*}p_{i}^{\\omega_{i}}}$ where $ \\alpha _{i}  \\ge  3$ and $p_{i}$ is distinct primes, set of divisors of $k$ which is less than $\\sqrt{k}$ is also beautiful. How to prove item 2? Consider set $A$ of pairs of divisors of $k$ $(a_{i}, b_{i})$ such as $a_{i} \\cdot b_{i} = k$ and $a_{i} < b_{i}$. Obiviously (if $k$ is not complete square) any divisor will be contained only in one pair. It's easy too see that $a_{i}<{\\sqrt{k}}$. Consider some element of factorisation of $k$ $p^{ \\alpha }$ such as $k\\equiv0mod p^{\\alpha}$ and it is not true that $k\\equiv0{\\mathrm{~mod~}}p^{\\alpha+1}$. Let $f(x)$ is maximal number $s$ such as $x\\equiv0{\\mathrm{~mod~}}p^{s}$. $f(a_{i}) + f(b_{i}) =  \\alpha $. For every $q$ such as $\\operatorname{\\overset{k}{p}}\\equiv0{\\pmod{q}}$ numbers $q, q \\cdot p, ..., q \\cdot p^{ \\alpha }$ will be divisors of $k$. That implies that $\\forall z\\equiv\\alpha{\\mathrm{~~~mod~}}2|\\{(a_{i},b_{i})\\in A\\mid|a_{i}-b_{i}|=z\\}|=d$ where $d$ is number of divisors of $\\textstyle{\\frac{k}{p^{\\alpha}}}$. So in $|A|\\cdot{\\frac{\\alpha-2}{\\alpha}}$ pairs both numbers are divisible by $p$. So set ${a_{0}, ..., a_{}|A|}$ is beautiful. But there are some pairs with $f(a_{i}) =  \\alpha $. $a_{i}<{\\frac{\\sqrt{k}}{p^{\\alpha}}}$ is equivalent approval. It's always possible to find such $k$ as number of it's divisors is bigger than $2 \\cdot w$ where $w$ is number of elements in required set. You may write following dp to find it. $dp[i][j]$ is minimal $k$ which is constructed of first $i$ primes ans has $j$ divisors. $d p[i][j]=m a x\\{d p[i-1][k]\\cdot p[i]^{k-1}\\mid j\\equiv0\\mathrm{\\boldmath~\\mod~}k\\}$ About $10$ primes is enough to cover all $k$. Now we can construct beautiful sets with more than $k$ elements. Using item $4$ we will understand that constructed answer is very beautiful (about 60% of elements divisible by every possible $p$) and we can always delete extra elements. Last items is not strict, but one can check it with his computer.",
    "tags": [
      "brute force",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "364",
    "index": "D",
    "title": "Ghd",
    "statement": "John Doe offered his sister Jane Doe find the gcd of some set of numbers $a$.\n\nGcd is a positive integer $g$, such that all number from the set are evenly divisible by $g$ and there isn't such $g'$ $(g' > g)$, that all numbers of the set are evenly divisible by $g'$.\n\nUnfortunately Jane couldn't cope with the task and John offered her to find the ghd of the same subset of numbers.\n\nGhd is a positive integer $g$, such that at least half of numbers from the set are evenly divisible by $g$ and there isn't such $g'$ $(g' > g)$ that at least half of the numbers from the set are evenly divisible by $g'$.\n\nJane coped with the task for two hours. Please try it, too.",
    "tutorial": "Consider random element $a_{r}$ of $a$. With probabillity $\\textstyle{\\frac{1}{2}}$ $a\\equiv0\\mod g$ where $g$ is ghd of $a$. Let $x_{i} = gcd(a_{i}, a_{r})$. There are no more than $d$ distinct $x_{i}$ where $d$ is number of divisors of $a_{r}$. We can find number of $a_{i}$ such as $a_{i}\\equiv0\\mathrm{\\boldmath~\\mod~}D_{k}.$ for every $k$ in $O(d^{2})$. ($D$ is set of divisors of $a_{r}$) Repeat item $1$ $x$ times we will get correct solution with probabillity $1 - 2^{ - x}$. There is the way to solve this problem $O(n \\cdot plog + d \\cdot 2^{plog})$ for iteration where $plog$ is the maximal number of distinct primes in factorisation of $a_{r}$.",
    "tags": [
      "brute force",
      "math",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "364",
    "index": "E",
    "title": "Empty Rectangles",
    "statement": "You've got an $n × m$ table ($n$ rows and $m$ columns), each cell of the table contains a \"0\" or a \"1\".\n\nYour task is to calculate the number of rectangles with the sides that are parallel to the sides of the table and go along the cell borders, such that the number one occurs exactly $k$ times in the rectangle.",
    "tutorial": "Let's find number of rectangles whick consist $k$ ones and intersect $y={\\frac{m}{2}}$ in cartesian coordinate system. It's possible to do it in $n^{2} \\cdot k$. We need to find closest $k$ ones on the top and on the bottom of the $y={\\frac{m}{2}}$ and enumareate all segments $[l, r]$ such as $1  \\le  l  \\le  r  \\le  n$ and find closest $k$ ones on the top and on the bottom of the segments merging results for rows. If we have $k$ closest ones on the top and on the bottom of the segment we will find number of rectangles consists $k$ ones and cross $y={\\frac{m}{2}}$ on $[l, r]$ in $O(k)$. Then we should find number of rectangles, which don't cross $y={\\frac{m}{2}}$. Let's rotate table by 90 degrees, solve similar problem for two halfs of the table and so on. $T(n)=n^{2}\\cdot k+4\\cdot T(n/2)=n^{2}\\log n\\cdot k$ for square-shaped tables. At the picture 1 two closest ones on the top (black cells) lying on the 4'th and 2'nd horizontals. Closest ones on the bottom lying on the 5'th and 7'th. Then if $k = 2$ there are zero correct rectangles with two \"ones\" on the tom. There are four rectangles which consist one \"one\" on the top and one \"one\" on the bottom. You can see how segment grows up at the pictures 2, 3 and 4. Every time you should merge closest $k$ ones of the added row with closest $k$ ones of the current segment.",
    "tags": [
      "divide and conquer",
      "two pointers"
    ],
    "rating": 3000
  },
  {
    "contest_id": "365",
    "index": "A",
    "title": "Good Number",
    "statement": "Let's call a number $k$-good if it contains all digits not exceeding $k$ ($0, ..., k$). You've got a number $k$ and an array $a$ containing $n$ numbers. Find out how many $k$-good numbers are in $a$ (count each number every time it occurs in array $a$).",
    "tutorial": "Task was to find the least digit, that is not contained in the given number and compare with given $k$.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "365",
    "index": "B",
    "title": "The Fibonacci Segment",
    "statement": "You have array $a_{1}, a_{2}, ..., a_{n}$. Segment $[l, r]$ ($1 ≤ l ≤ r ≤ n$) is good if $a_{i} = a_{i - 1} + a_{i - 2}$, for all $i$ $(l + 2 ≤ i ≤ r)$.\n\nLet's define $len([l, r]) = r - l + 1$, $len([l, r])$ is the length of the segment $[l, r]$. Segment $[l_{1}, r_{1}]$, is longer than segment $[l_{2}, r_{2}]$, if $len([l_{1}, r_{1}]) > len([l_{2}, r_{2}])$.\n\nYour task is to find a good segment of the maximum length in array $a$. Note that a segment of length $1$ or $2$ is always good.",
    "tutorial": "Good sequence may contain only zeroes or contain some positive number. In the second case such a sequence is not longer than sequence ${0, 1, 1, 2, 3, 5, 8, ..., x, y}$ where $y > 10^{9}$ and $x  \\le  10^{9}$. That's possible to find it using dummy algorithm. In the first case you may use binary search of two pointers.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "366",
    "index": "A",
    "title": "Dima and Guards",
    "statement": "Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards...\n\nThere are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can bribe a guard by a chocolate bar or a box of juice. For each guard you know the minimum price of the chocolate bar she can accept as a gift and the minimum price of the box of juice she can accept as a gift. If a chocolate bar for some guard costs less than the minimum chocolate bar price for this guard is, or if a box of juice for some guard costs less than the minimum box of juice price for this guard is, then the guard doesn't accept such a gift.\n\nIn order to pass through a guardpost, one needs to bribe both guards.\n\nThe shop has an unlimited amount of juice and chocolate of any price starting with $1$. Dima wants to choose some guardpost, buy one gift for each guard from the guardpost and spend \\textbf{exactly} $n$ rubles on it.\n\nHelp him choose a post through which he can safely sneak Inna or otherwise say that this is impossible. Mind you, Inna would be very sorry to hear that!",
    "tutorial": "The solution doesn't exist only if the mimimal way to bribe is grater than $n$. Otherwise we can increase the gift price to make $price1$ + $price2$ = $n$. Let's find the miminal way to bribe. We should buy that gift for old lady which costs less. It means, if we have 2 guards with params $a$ $b$ $c$ $d$, then minimum bribe price will be $min(a, b) + min(c, d)$. Let's choose the guard with the minimal bribe price. If the minimal bribe price is greater than $n$, answer -$1$. Otherwise, the possible answer is, for example: Guard number, $min(a, b)$, $n-min(a, b)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "366",
    "index": "B",
    "title": "Dima and To-do List",
    "statement": "You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.\n\nInna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete $k - 1$ tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.\n\nOverall, Dima has $n$ tasks to do, each task has a unique number from $1$ to $n$. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has $6$ tasks to do in total, then, if he starts from the $5$-th task, the order is like that: first Dima does the $5$-th task, then the $6$-th one, then the $1$-st one, then the $2$-nd one, then the $3$-rd one, then the $4$-th one.\n\nInna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.",
    "tutorial": "Dima can make $k-1$ tasks, so Inna always tells him off for each $k$-th taks, beginning from the chosen place. So for the numbers with same modulo by k the answer will be the same. We should find the answer with minimal first task number so it is eniugh to calculate the sums of \"tellings of\" for tasks $0, 1... k-1$. We can do it in such way: Determine the array int $sum[k]$. And put the number into appropriate bucket while reading: $sum[$I mod k$] + = a[i]$. Now we should simply find first $i$ with minimal $sum[i]$. Complexity: $O(N)$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "366",
    "index": "C",
    "title": "Dima and Salad",
    "statement": "Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something.\n\nDima and Seryozha have $n$ fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal $k$. In other words, ${\\frac{{\\frac{a}{m}}a_{j}}{b-{b}_{j}}}=k$ , where $a_{j}$ is the taste of the $j$-th chosen fruit and $b_{j}$ is its calories.\n\nInna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem — now the happiness of a young couple is in your hands!\n\nInna loves Dima very much so she wants to make the salad from at least one fruit.",
    "tutorial": "Let's calculate dinamic: $d[num][balance]$ where $num$ - last looked fruit, balance - difference between sum of colories and sum of tastes. Let's multiply each $b$ by $k$. The answer will be $d[n][0]$. $d[num][balance]$ = maximal possible sum of tastes under conditions. Step: from $d[num][balance]$ we can relax answers: $d[num + 1][balance] = max(d[num + 1][balance], d[num][balance])$ - if we don't choose a fruit $d[num + 1][balance + a[i] - b[i] \\cdot k] = max(d[num + 1][balance + a[i] - b[i] \\cdot k], d[num][balance] + a[i])$ - if we choose a fruit. Balance can be negative, so in programming languages which don't support negative indexation, indexes should be shifted by the biggest negative number for balance. If we determine the balance as $sum(b \\cdot k) - sum(a)$ it will be the sum of all tastes.",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "366",
    "index": "D",
    "title": "Dima and Trap Graph",
    "statement": "Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal...\n\nDima constructed a trap graph. He shouted: \"Hey Seryozha, have a look at my cool graph!\" to get his roommate interested and kicked him into the first node.\n\nA trap graph is an undirected graph consisting of $n$ nodes and $m$ edges. For edge number $k$, Dima denoted a range of integers from $l_{k}$ to $r_{k}$ $(l_{k} ≤ r_{k})$. In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it $x$), then Seryozha must go some way from the starting node with number $1$ to the final node with number $n$. At that, Seryozha can go along edge $k$ only if $l_{k} ≤ x ≤ r_{k}$.\n\nSeryozha is a mathematician. He defined the loyalty of some path from the $1$-st node to the $n$-th one as the number of integers $x$, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible!",
    "tutorial": "The answer for some path is a range under which we can go all the way, and this range is the intersection of all the ranges on the path. We can conclude it because the number is valid for path if it is valid for all ranges in the path. We will iterate all ribs. Let the left board of range on a rib is the left board of our intersection. It means we can't use ribs whith left board greater than ours. Lets iterate all right boards, determining the answer as the range from fixed left board to the chosen right. This answer exists if we have any path from the first node to the last. Let's check if the graph is connected if we leave only ribs with left board not greater than our and right board not less than our. If the graph is connected - let's update the answer. Right board can be found by binary search so the complexity is $O(M^{2} \\cdot logM)$.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dsu",
      "shortest paths",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "366",
    "index": "E",
    "title": "Dima and Magic Guitar",
    "statement": "Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with $n$ strings and $m$ frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the $i$-th string holding it on the $j$-th fret the guitar produces a note, let's denote it as $a_{ij}$. We know that Dima's guitar can produce $k$ distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that $a_{ij} = a_{pq}$ at $(i, j) ≠ (p, q)$.\n\nDima has already written a song — a sequence of $s$ notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).\n\nWe'll represent a way to play a song as a sequence of pairs $(x_{i}, y_{i})$ $(1 ≤ i ≤ s)$, such that the $x_{i}$-th string on the $y_{i}$-th fret produces the $i$-th note from the song. The complexity of moving between pairs $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ equals $|x_{1}-x_{2}|$ + $|y_{1}-y_{2}|$. The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.\n\nHelp Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!",
    "tutorial": "There are many solutions for this task. I will describe my, you can deal with other by looking participants code. To find the answer we should calculate $maxDis[k][k]$, where $maxDis[i][j]$ - maximal complexity from note $i$ to note $j$. Now we should only iterate the song updating answer for each pair of adjacent notes. Let's think how we can calculate the matrix. For each place $(x_{1}, y_{1})$ on the guitar let's iterate pairs $(x_{2}, y_{2})$ with $y_{2}  \\le  y_{1}$. If $(x_{2}  \\le  x_{1})$ distance will be $x_{1}-x_{2} + y_{1}-y_{2}$. So we should find minimal $x_{2} + y_{2}$ in submatrix from $(0, 0)$ to $(x, y)$. If $(x_{2}  \\ge  x_{1})$ distance will be $x_{2}-x_{1} + y_{1}-y_{2}$. So we should find maximal $x_{2}-y_{2}$ in submatrix from $(n-1, 0)$ to $(x, y)$. We will calculate this values for each note. We need too much memory so we should memorize only one previous row for each note. For each place we will update dinamics for both variants according to already calculated and for our own note (which is in this cell) we will also compare $(i + j)$ or $(i-j)$ with current value in the cell. Complexity $O(N \\cdot M \\cdot K)$",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "367",
    "index": "A",
    "title": "Sereja and Algorithm ",
    "statement": "Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as $q = q_{1}q_{2}... q_{k}$. The algorithm consists of two steps:\n\n- Find any continuous subsequence (substring) of three characters of string $q$, which doesn't equal to either string \"zyx\", \"xzy\", \"yxz\". If $q$ doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2.\n- Rearrange the letters of the found subsequence randomly and go to step 1.\n\nSereja thinks that the algorithm works correctly on string $q$ if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.\n\nSereja wants to test his algorithm. For that, he has string $s = s_{1}s_{2}... s_{n}$, consisting of $n$ characters. The boy conducts a series of $m$ tests. As the $i$-th test, he sends substring $s_{li}s_{li + 1}... s_{ri}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$ to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test $(l_{i}, r_{i})$ determine if the algorithm works correctly on this test or not.",
    "tutorial": "If you look at what is written in the statment, it becomes clear that the algorithm finishes its work, if we can get a string like: $xx$, $yy$, $zz$, $zyxzyxzyx...$ and all its cyclic shuffles. To check you just need to know the number of letters $x$, $y$ and $z$ separately. Quantities can be counted using partial sums.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "367",
    "index": "B",
    "title": "Sereja ans Anagrams",
    "statement": "Sereja has two sequences $a$ and $b$ and number $p$. Sequence $a$ consists of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Similarly, sequence $b$ consists of $m$ integers $b_{1}, b_{2}, ..., b_{m}$. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions $q$ $(q + (m - 1)·p ≤ n; q ≥ 1)$, such that sequence $b$ can be obtained from sequence $a_{q}, a_{q + p}, a_{q + 2p}, ..., a_{q + (m - 1)p}$ by rearranging elements.\n\nSereja needs to rush to the gym, so he asked to find all the described positions of $q$.",
    "tutorial": "We will divide the sequence on $min(n, p)$ sequences. $1$-st, $(1 + p)$-th, $(1 + 2 \\cdot p)$-th, ... element will go to the first sequence, $2$-nd, $(2 + p)$-th, $(2 + 2 \\cdot p)$-th... will go to the second sequence and so on. Now you need to find an answer for each of them, considering that $p = 1$. This can be solved by a simple method. You can go along the sequence from left to right and count the number of occurrences of each number. If the number of occurrences of each number will match the number of occurrences of the same number in the second sequence, then everything is OK.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 1900
  },
  {
    "contest_id": "367",
    "index": "C",
    "title": "Sereja and the Arrangement of Numbers",
    "statement": "Let's call an array consisting of $n$ integer numbers $a_{1}$, $a_{2}$, $...$, $a_{n}$, beautiful if it has the following property:\n\n- consider all pairs of numbers $x, y$ $(x ≠ y)$, such that number $x$ occurs in the array $a$ and number $y$ occurs in the array $a$;\n- for each pair $x, y$ must exist some position $j$ $(1 ≤ j < n)$, such that at least one of the two conditions are met, either $a_{j} = x, a_{j + 1} = y$, or $a_{j} = y, a_{j + 1} = x$.\n\nSereja wants to build a beautiful array $a$, consisting of $n$ integers. But not everything is so easy, Sereja's friend Dima has $m$ coupons, each contains two integers $q_{i}, w_{i}$. Coupon $i$ costs $w_{i}$ and allows you to use as many numbers $q_{i}$ as you want when constructing the array $a$. Values $q_{i}$ are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array $a$ of $n$ elements. After that he takes $w_{i}$ rubles from Sereja for each $q_{i}$, which occurs in the array $a$. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.\n\nHelp Sereja, find the maximum amount of money he can pay to Dima.",
    "tutorial": "Clear that we need to collect as many of the most expensive properties that would have been possible to build the array. Note that having $n$ numbers, we have $m$ = $n \\cdot (n - 1) / 2$ binding ties. See that this is a graph in which to do Euler path, adding as little as possible edges. For $n%2 = 1$ - everything is clear, and for $n%2 = 0$, you need to add an additional $n / 2 - 1$ rib. Why? This is your homework :)",
    "tags": [
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "367",
    "index": "D",
    "title": "Sereja and Sets",
    "statement": "Sereja has $m$ non-empty sets of integers $A_{1}, A_{2}, ..., A_{m}$. What a lucky coincidence! The given sets are a partition of the set of all integers from 1 to $n$. In other words, for any integer $v$ $(1 ≤ v ≤ n)$ there is exactly one set $A_{t}$ such that $v\\in A_{t}$. Also Sereja has integer $d$.\n\nSereja decided to choose some sets from the sets he has. Let's suppose that $i_{1}, i_{2}, ..., i_{k}$ $(1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ m)$ are indexes of the chosen sets. Then let's define an array of integers $b$, sorted in ascending order, as a union of the chosen sets, that is, $A_{i_{1}}\\cup A_{i_{2}}\\cup\\cdot\\cdot\\cdot\\cup A_{i_{l}}$. We'll represent the element with number $j$ in this array (in ascending order) as $b_{j}$. Sereja considers his choice of sets correct, if the following conditions are met:\n\n\\[\nb_{1} ≤ d; b_{i + 1} - b_{i} ≤ d (1 ≤ i < |b|); n - d + 1 ≤ b_{|b|}.\n\\]\n\nSereja wants to know what is the minimum number of sets $(k)$ that he can choose so that his choice will be correct. Help him with that.",
    "tutorial": "Replace out sets by array, where the element - the number set to which its index belongs. Now take all the consequitive sub-arrays with lengths of $d$ and find a set of elements that were not found in that sub array. Clearly, if we as a response to select a subset of such set, it does not fit us. Remember all those \"bad set.\" As we know all of them, we can find all the \"bad\" subsets. Now we choose the set with maximum count of elements which is not a bad set. It is better to work here with bit masks.",
    "tags": [
      "bitmasks",
      "dfs and similar"
    ],
    "rating": 2400
  },
  {
    "contest_id": "367",
    "index": "E",
    "title": "Sereja and Intervals",
    "statement": "Sereja is interested in intervals of numbers, so he has prepared a problem about intervals for you. An interval of numbers is a pair of integers $[l, r]$ $(1 ≤ l ≤ r ≤ m)$. Interval $[l_{1}, r_{1}]$ belongs to interval $[l_{2}, r_{2}]$ if the following condition is met: $l_{2} ≤ l_{1} ≤ r_{1} ≤ r_{2}$.\n\nSereja wants to write out a sequence of $n$ intervals $[l_{1}, r_{1}]$, $[l_{2}, r_{2}]$, $...$, $[l_{n}, r_{n}]$ on a piece of paper. At that, no interval in the sequence can belong to some other interval of the sequence. Also, Sereja loves number $x$ very much and he wants some (at least one) interval in the sequence to have $l_{i} = x$. Sereja wonders, how many distinct ways to write such intervals are there?\n\nHelp Sereja and find the required number of ways modulo $1000000007$ $(10^{9} + 7)$.\n\nTwo ways are considered distinct if there is such $j$ $(1 ≤ j ≤ n)$, that the $j$-th intervals in two corresponding sequences are not equal.",
    "tutorial": "We assume that the intervals are sorted, and in the end we will multiply the answer by $n!$, We can do so, as all segments are different. Consider two cases $n > m$ and $n  \\le  m$. It would seem that you need to write different dynamics for them, but not difficult to show that in the first case the answer is always $0$ . The second case is the following dynamics : $dp_{i, l, r}$, $i$ - how many numbers we have considered , $l, r$ - only in this interval will be present number $i$. Also, we will need an additional dynamic $s_{i, l}$, $i$ - how many numbers are considered , $l$ - how many segments are already closed , and $i$ does not belong to any segment . There will be $4$ transfers, since every number we can not begin and end with more than one segment. Now we should add $x$ to our solution, it is quite simple: just add another parameter $0 / 1$ in our dynamics, if we had such a element in the beginning of some interval or not. With out dynamics, it is not difficult.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "368",
    "index": "A",
    "title": "Sereja and Coat Rack",
    "statement": "Sereja owns a restaurant for $n$ people. The restaurant hall has a coat rack with $n$ hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the $i$-th hook costs $a_{i}$ rubles. Only one person can hang clothes on one hook.\n\nTonight Sereja expects $m$ guests in the restaurant. Naturally, each guest wants to hang his clothes on an available hook with minimum price (if there are multiple such hooks, he chooses any of them). However if the moment a guest arrives the rack has no available hooks, Sereja must pay a $d$ ruble fine to the guest.\n\nHelp Sereja find out the profit in rubles (possibly negative) that he will get tonight. You can assume that before the guests arrive, all hooks on the rack are available, all guests come at different time, nobody besides the $m$ guests is visiting Sereja's restaurant tonight.",
    "tutorial": "Each time we will go through the array and look for the minimal element which is not yet marked. If we find an item, we add it to the answer and mark it, otherwise we will subtract the penlty from answer.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "368",
    "index": "B",
    "title": "Sereja and Suffixes",
    "statement": "Sereja has an array $a$, consisting of $n$ integers $a_{1}$, $a_{2}$, $...$, $a_{n}$. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out $m$ integers $l_{1}, l_{2}, ..., l_{m}$ $(1 ≤ l_{i} ≤ n)$. For each number $l_{i}$ he wants to know how many distinct numbers are staying on the positions $l_{i}$, $l_{i} + 1$, ..., $n$. Formally, he want to find the number of distinct numbers among $a_{li}, a_{li + 1}, ..., a_{n}$.?\n\nSereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each $l_{i}$.",
    "tutorial": "We will count value $ans_{i}$ - number of different elements on the suffix from $i$. For calculation will walk from the end of the array, and we count $ans_{i} = ans_{i + 1} + new_{ai}$, $new_{ai}$ equals to $1$, if element $a_{i}$ has not yet met and $0$ otherwise.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 1100
  },
  {
    "contest_id": "369",
    "index": "A",
    "title": "Valera and Plates",
    "statement": "Valera is a lazy student. He has $m$ clean bowls and $k$ clean plates.\n\nValera has made an eating plan for the next $n$ days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates.\n\nWhen Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl \\textbf{before eating}. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.",
    "tutorial": "We will use greedy algorithm. Let's now $i$-th day, and current dish is a dish of first type. Then if we have the bowl, let's use it. Otherwise we will increase the answer. If the current dish is a dish of the second type, we first try to get the plate, and then the bowl. If there are no plates/bowls at all, then we will increase the answer.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint main()\n{\n\tint n, m, k, type;\n\tint ans = 0;\n\tcin >> n >> m >> k;\n\t\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tcin >> type;\n\t\t\n\t\tif (type == 1)\n\t\t{\n\t\t\tif (m == 0)\n\t\t\t\tans++;\n\t\t\telse\n\t\t\t\tm--;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (k != 0)\n\t\t\t{\n\t\t\t\tk--;\n\t\t\t\tcontinue;\n\t\t\t}\t\n\t\t\t\n\t\t\tif (m != 0)\n\t\t\t{\n\t\t\t\tm--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tans++;\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "369",
    "index": "B",
    "title": "Valera and Contest",
    "statement": "Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of $n$ students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.\n\nAfter the contest was over, Valera was interested in results. He found out that:\n\n- each student in the team scored at least $l$ points and at most $r$ points;\n- in total, all members of the team scored exactly $s_{all}$ points;\n- the total score of the $k$ members of the team who scored the most points is equal to exactly $s_{k}$; more formally, if $a_{1}, a_{2}, ..., a_{n}$ is the sequence of points earned by the team of students in the non-increasing order $(a_{1} ≥ a_{2} ≥ ... ≥ a_{n})$, then $s_{k} = a_{1} + a_{2} + ... + a_{k}$.\n\nHowever, Valera did not find out exactly how many points each of $n$ students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.",
    "tutorial": "In this task you are to determine such array $a_{1}, a_{2}, ..., a_{n}$, that following conditions are met: $r \\ge a_1 \\ge a_2 \\ge \\dots \\ge a_n \\ge l$; $s_k = \\sum_{i = 1}^k a_i$; $s_{all} = \\sum_{i = 1}^n a_i$; It's clear to understand, that value $s_{k}$ should be distributed evenly between the first $k$ elements. For example, you can use following algorithm: If $k  \\neq  n$, you should use same algorithm with other elements, but there are to distribute value $s_{all} - s_{k}$. Some participants forgot about test, where $k = n$. They received RE11.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n \nusing namespace std;\n \nint main() {\n \tint n, k, l, r, s, sk;\n \tcin >> n >> k >> l >> r >> s >> sk;\n\tint tsk = s - sk;\n\tvector < int > ans(n);\n\tfor(int i = 0; i < k; i++) {\n\t\tans[i] = sk / k;\n\t\tif (sk % k != 0) ans[i]++, sk--;\t\t \t\n\t}\n\tif (k != n) {\n\t \tfor(int i = k; i < n; i++) {\n\t \t \tans[i] = tsk / (n - k);\n\t \t \tif (tsk % (n - k) != 0) ans[i]++, tsk--;\n\t \t}\n\t} \n \n\tbool ok = true;\n \n\tfor(int i = 0; i < k; i++) {\n\t \tif (ans[i] < l || ans[i] > r) ok = false;\n\t \tfor(int j = k; j < n; j++) {\n\t \t \tif (ans[j] > ans[i]) ok = false;\n\t \t \tif (ans[j] < l || ans[j] > r)\n\t \t \t\tok = false;\n\t \t}\n\t}\n        random_shuffle(ans.begin(), ans.end());\n\tfor(int i = 0; i < n; i++)\n\t\tcout << ans[i] << ' ';\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "369",
    "index": "C",
    "title": "Valera and Elections",
    "statement": "The city Valera lives in is going to hold elections to the city Parliament.\n\nThe city has $n$ districts and $n - 1$ bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from $1$ to $n$, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired.\n\nThere are $n$ candidates running the elections. Let's enumerate all candidates in some way by integers from $1$ to $n$, inclusive. If the candidate number $i$ will be elected in the city Parliament, he will perform exactly one promise — to repair all problem roads on the way from the $i$-th district to the district $1$, where the city Parliament is located.\n\nHelp Valera and determine the subset of candidates such that if all candidates from the subset will be elected to the city Parliament, all problem roads in the city will be repaired. If there are several such subsets, you should choose the subset consisting of the minimum number of candidates.",
    "tutorial": "Consider all the roads that we need to repair. Mark the ends of $u, v$ white. After that, we will consider a simple dynamic programming $d[v]$ ($v$ is the vertex) on the tree that for each vertex in the tree determines the number of white vertexes in the subtree. It is easy to calculate this by using a recursive function $calc(v, prev)$ ($v$ is the current node, and $prev$ its immediate ancestor): After that we will add to answer all white vertexes $v$ such that next condition is correct: $d[v] = 1$",
    "code": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n \n#include <set>\n#include <map>\n#include <queue>\n#include <deque>\n#include <stack>\n#include <list>\n#include <bitset>\n#include <utility>\n#include <functional>\n#include <string>\n#include <algorithm>\n \n#include <cstring>\n#include <cstdio>\n#include <memory.h>\n#include <ctime>\n#include <cassert>\n#include <cmath>\n \nusing namespace std;\n \n#define forn(i,n) for(int i = 0; i < int(n); i++)\n#define ford(i,n) for(int i = int(n) - 1; i >= 0; i--)\n#define fore(i,a,b) for(int i = int(a); i <= int(b); i++)\n#define foreach(it,a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)\n \n#define sz(a) int((a).size())\n#define all(a) (a).begin(),(a).end()\n#define pb push_back\n#define mp make_pair\n#define ft first\n#define sc second\n \ntemplate<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }\ntemplate<typename X> inline X sqr(const X& a) { return (a * a); }\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int,int> pt;\ntypedef pair<ld, ld> ptd;\n \nconst int INF = 1000000000;\nconst li INF64 = li(INF) * li(INF);\nconst ld EPS = ld(1e-9);\nconst ld PI = ld(3.1415926535897932384626433832795);\n \nint n;\nconst int N = 300000 + 300;\nint white[N], d[N];       \nvector < int > g[N];\n \ninline bool read() {\n\tif (scanf(\"%d\", &n) != 1)\n\t\treturn false;\n\tforn(i, n - 1)\n\t{\n\t \tint x, y, t;\n \n\t \tassert(scanf(\"%d %d %d\", &x, &y, &t) == 3);\n\t\tx--, y--;\n \n\t\tg[x].pb(y);\n\t\tg[y].pb(x);\n\t\t\n\t\tif (t == 2)\n\t\t{\n\t\t \twhite[x] = 1;\n\t\t \twhite[y] = 1;\n\t\t}\n\t}\n \n\treturn true;\n}\n \n \nvoid go(int v, int prev = -1)\n{\n\td[v] = white[v];\n\tforn(i, sz(g[v]))\n\t{\n\t\tint to = g[v][i];\n \n\t\tif (prev == to)\n\t\t\tcontinue;\n\t\tgo(to, v);\n\t\td[v] += d[to];\n\t}\t\n}\ninline void solve() \n{\n\tgo(0);\n\tvector < int > ans;\n  \tforn(i, n)\n  \t{\n  \t\tif (white[i] && d[i] == 1)\n  \t\t{\n  \t\t\tans.pb(i + 1);\n  \t\t}\n  \t}\n \n  \tprintf(\"%d\\n\", sz(ans));\n \n  \tforn(i, sz(ans))\n  \t{\n  \t  \tif (i) printf(\" \");\n  \t  \tprintf(\"%d\", ans[i]);\n  \t}\n}\n \nint main() {\n #ifdef gridnevvvit\n \tfreopen(\"input.txt\", \"rt\", stdin);\n \tfreopen(\"output.txt\", \"wt\", stdout);\n #endif\n  assert(read());\n  solve();\n   #ifdef gridnevvvit \n \tcerr << \"Time == \" << clock() << endl;\n #endif\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "369",
    "index": "D",
    "title": "Valera and Fools",
    "statement": "One fine morning, $n$ fools lined up in a row. After that, they numbered each other with numbers from $1$ to $n$, inclusive. Each fool got a unique number. The fools decided not to change their numbers before the end of the fun.\n\nEvery fool has exactly $k$ bullets and a pistol. In addition, the fool number $i$ has probability of $p_{i}$ (in percent) that he kills the fool he shoots at.\n\nThe fools decided to have several rounds of the fun. Each round of the fun looks like this: each currently living fool shoots at another living fool with the smallest number (a fool is not stupid enough to shoot at himself). All shots of the round are perfomed at one time (simultaneously). If there is exactly one living fool, he does not shoot.\n\nLet's define a situation as the set of numbers of all the living fools at the some time. We say that a situation is possible if for some integer number $j$ ($0 ≤ j ≤ k$) there is a nonzero probability that after $j$ rounds of the fun this situation will occur.\n\nValera knows numbers $p_{1}, p_{2}, ..., p_{n}$ and $k$. Help Valera determine the number of distinct possible situations.",
    "tutorial": "Let's $p[A]$ is the $p_{A}$ from the statement. It's clear to understand that you can discribe the state by using pair of integers ($A, B$), where $A$ is a number of the fool with smallest index, $B$ - the second fool from the left. It is clear to understand that fool with indexes $j  \\ge  B$ will be living. After that we will use bfs on the states $(A, B)$. State ($0, 1$) is always visitable, because it is initial. We will push it in the queue. After that, there are only three transitions from current state $(A, B)$. $(B + 1, B + 2)$ - this transition is possible if and only if $p[A] > 0$ and there are some fool with index $j \\ge B$, which has non-zero value $p[j] > 0$. $(A, B + 1)$ - this transition is possible if and only if $p[A] > 0$ and there are no fool with index $j \\ge B$, which has $p[j] = 100$. $(B, B + 1)$ - this transition is possible if and only if $p[A] \\neq 100$ and there are some fool with index $j \\ge B$, which has non-zero value $p[j] > 0$. After that you are to determine number of states, which has distance from state $(0, 1)$ less or equal to $k$. Also you should be careful, that if there are only one fool, that he doesn't shot.",
    "code": "#include <iostream>\n#include <queue>\n#include <cstring>\n#include <cstdio>\n \n \nusing namespace std;\n \n#define pb push_back\n#define mp make_pair\n#define ft first\n#define sc second\n \ntypedef pair<int,int> pt;\n \nconst int N = 3000 + 50;\nint n, k, p[N], d[N][N], sufP[N], sufO[N];\n \nint main() {\n #ifdef gridnevvvit\n \tfreopen(\"input.txt\", \"rt\", stdin);\n \tfreopen(\"output.txt\", \"wt\", stdout);\n #endif\n\tcin >> n >> k;\n\tfor(int i = 0; i < n; i++)\n\t\tcin >> p[i];\n\tqueue < pt > q;\n  \tfor(int i = n - 1; i >= 0; i--) {\n  \t \tif (i + 1 != n) {\n  \t \t \tsufP[i] = sufP[i + 1];\n  \t \t\tsufO[i] = sufO[i + 1];\n  \t \t}\n  \t \tsufP[i] += (p[i] > 0);\n  \t \tsufO[i] += (p[i] == 100);\n  \t}\n  \tq.push(mp(0, 1));\n\t\n\td[0][1] = 1;\n \n\tint ans = 1;\n \n\twhile (!q.empty()) {\n\t\tpt cur = q.front(); q.pop();\n \n\t\tint A = cur.ft, B = cur.sc;\n\t\t                        \n \n\t\tif (A >= n || B >= n || d[A][B] > k)\n\t\t\tcontinue;\t\n\t\t            \n\t\tif (p[A] > 0 && sufP[B] > 0 && d[B + 1][B + 2] == 0) {\n\t\t\td[B + 1][B + 2] = d[A][B] + 1;\n\t\t\tans ++;\n\t\t\tq.push(mp(B + 1, B + 2));\n\t\t}\n \n\t\tif (p[A] > 0 && sufO[B] == 0 && d[A][B + 1] == 0) {\t\n\t\t\td[A][B + 1] = d[A][B] + 1;\n\t\t\tans ++;              \n\t\t\tq.push(mp(A, B + 1));\n\t\t}\n \n\t\tif (p[A] != 100 && sufP[B] > 0 && d[B][B + 1] == 0) {\n\t\t\td[B][B + 1] = d[A][B] + 1;\n\t\t\tans ++;\n\t\t\tq.push(mp(B, B + 1));\n\t\t}\n\t}\n \n\tcout << ans << endl;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "369",
    "index": "E",
    "title": "Valera and Queries",
    "statement": "Valera loves segments. He has recently come up with one interesting problem.\n\nThe $Ox$ axis of coordinates has $n$ segments, the $i$-th segment starts in position $l_{i}$ and ends in position $r_{i}$ (we will mark it as $[l_{i}, r_{i}]$). Your task is to process $m$ queries, each consists of number $cnt_{i}$ and a set of $cnt_{i}$ coordinates of points located on the $Ox$ axis. The answer to the query is the number of segments, such that each of them contains at least one point from the query. Segment $[l, r]$ contains point $q$, if $l ≤ q ≤ r$.\n\nValera found the solution of this problem too difficult. So he asked you to help him. Help Valera.",
    "tutorial": "Let's calculate sets $xs[y]$ - all segments, whose right borders are exactly equal to $y$. Now we reduce our task to another. For each query we will count the number of segments that doesn't belong to any one point. Let's it will be the value $v$. Then the answer to the query is $n - v$. We add to our request the point $0$ and a point $MV + 1$, where $MV = 1000000$. Let points request have the form $x_{1} < x_{2}... < x_{n}$. Consider the $x_{i}$ and $x_{i + 1}$. Let $p_{i}$ is the number of segments that lie strictly inside $x_{i}$ and $x_{i + 1}$. Then $v = p_{1} + p_{2} + ... + p_{n - 1}$. We will use following algorithm to find the values $p_{i}$. Let consider all such pairs $(x_{}, x_{i + 1})$ for all requests and to add them to a second set $xQ[y]$ - all pairs whose right boundary is equal to $r$. Then to find the values $p$ of pairs $(x_{i}, x_{i + 1})$ we will iterate ascending the right border. Additionally, we will support Fenwick's tree, which can make $+ = 1$ at the point, and can calculate sum of the prefix. Let $i$ - the current right border. Then we can find out the value $p$ for all pairs $(l, r)$, with the right border is equal to the $i$ $(l, i)$. Let $j$ left border of the pair. Then the answer for the pair is the value of $S - sum(j)$, where $S$ - all added to the Fenwick's left borders, and $sum(j)$ - sum of the prefix $j$. After that, for the current coordinate $i$ we need to consider all segments in the set $xs[i]$. Let $j$ left boundary of the segment. Then we need to make $+ = 1$ at the point $j$ in our Fenwick's tree. The total solution complexity is $O((n+m+c n t_{p o i n t s})\\log(A))$.",
    "code": "#define _CRT_SECURE_NO_DEPRECATE\n#define _USE_MATH_DEFINES\n \n#include <iostream>\n#include <fstream>\n#include <iomanip>\n \n#include <utility>\n#include <complex>\n#include <vector>\n#include <bitset>\n#include <string>\n#include <stack>\n#include <queue>\n#include <set>\n#include <list>\n#include <map>\n#include <algorithm>\n#include <deque>\n \n#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <climits>\n#include <ctime>\n#include <cstring>\n#include <cmath>\n \nusing namespace std;\n \n#define pb push_back\n#define mp make_pair\n#define all(a) a.begin(), a.end()\n#define sz(a) int(a.size())\n#define forn(i,n) for (int i = 0; i < int(n); i++)\n#define ford(i,n) for (int i = int(n) - 1; i >= 0; i--)\n#define x1 ___x1\n#define y1 ___y1\n#define x first\n#define ft first\n#define y second\n#define sc second\n \ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a : a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt; \n \nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\nconst ld PI = ld(3.1415926535897932384626433832795);\n \nconst int N = 1000 * 1000 + 13;\nint n, m;\npt a[N];\nvector<int> q[N];\n \ninline bool read ()\n{\n\tif (scanf (\"%d%d\", &n, &m) != 2)\n\t\treturn false;\n \n\tforn (i, n)\n\t{\n\t\tint l, r;\n\t\tassert(scanf (\"%d%d\", &l, &r) == 2);\n\t\t\n\t\ta[i] = mp(l, r);\n\t}\n\t\n\tforn (i, m)\n\t{\n\t\tint cnt;\n\t\tassert(scanf(\"%d\", &cnt) == 1);\n\t\t\n\t\tq[i].pb(0);\n\t\t\n\t\tforn (j, cnt)\n\t\t{\n\t\t\tint p;\n\t\t\tassert(scanf (\"%d\", &p) == 1);\n\t\t\t\n\t\t\tq[i].pb(p);\n\t\t}\n\t\t\n\t\tq[i].pb(1000 * 1000 + 3);\n\t\t\n\t\t//sort(all(q[i]));\n\t}\n\t\n    return true;\n}\n \nint ans[N];\n \nvector<int> xs[N];\nvector<pt> qq[N];\nint t[N];\n \ninline int sum (int r)\n{\n\tint ans = 0;\n\t\n\tfor (; r >= 0; r = (r & (r + 1)) - 1)\n\t\tans += t[r];\n\t\t\n\treturn ans;\n}\n \ninline int sum (int l, int r)\n{\n \treturn sum(r) - sum(l - 1);\n}\n \ninline void inc (int i, int add)\n{\n\tfor (; i < N; i = (i | (i + 1)))\n\t\tt[i] += add;\n}\n \ninline void solve ()\n{\n\tforn (i, n)\n\t\txs[ a[i].y ].pb(a[i].x);\n \n\tforn (i, m)\n\t\tforn (j, sz(q[i]) - 1)\n\t\t{\n\t\t \tint l = q[i][j] + 1, r = q[i][j + 1] - 1;\n \n\t\t \tqq[r].pb(mp(l, i));\n\t\t}\n \n\tforn (i, N)\n\t{\n\t\tforn (j, sz(xs[i]))\n\t\t{\n\t\t\tint y = xs[i][j];\n\t\t\t\n\t\t\tinc(y, 1);\n\t\t}\n\t\t\n\t\tforn (j, sz(qq[i]))\n\t\t{\n\t\t\tint id = qq[i][j].sc;\n \n\t\t\tans[id] += sum(qq[i][j].ft, i);\t\n\t\t}\n\t}\n\t\n\tforn (i, m)\n\t{\n\t\tprintf (\"%d\\n\", n - ans[i]);\n\t}\t\n}\n \nint main () \n{   \n    //freopen(\"input.txt\", \"rt\", stdin);\n    //freopen(\"output.txt\", \"wt\", stdout);\n \n    srand(time(NULL));\n \n    cout << setprecision(10) << fixed;\n    cerr << setprecision(5) << fixed;\n    \n    assert(read());\n    solve();\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "370",
    "index": "A",
    "title": "Rook, Bishop and King",
    "statement": "Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an $8 × 8$ table. A field is represented by a pair of integers $(r, c)$ — the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules:\n\n- A rook moves any number of fields horizontally or vertically.\n- A bishop moves any number of fields diagonally.\n- A king moves one field in any direction — horizontally, vertically or diagonally.\n\n\\begin{center}\n{\\small The pieces move like that}\n\\end{center}\n\nPetya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field $(r_{1}, c_{1})$ to field $(r_{2}, c_{2})$? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.",
    "tutorial": "There are two approaches to this task. The first is use BFS to find the shortest path three times. The second is to notice that: A rook can reach the destination in one or two moves. If the starting and the destination fields are in the same row or column, one move is enough. A bishop can reach only fields that are colored the same as the starting cell, and can do this in at most two moves: if the starting and the destination fields are on the same diagonal, one move is enough. To find this out, check that $r_1 - c_1 = r_2 - c_2$ OR $r_1 + c_1 = r_2 + c_2$. A king should make $\\max(|r_1 - r_2|, |c_1 - c_2|)$ moves.",
    "tags": [
      "graphs",
      "math",
      "shortest paths"
    ],
    "rating": 1100
  },
  {
    "contest_id": "370",
    "index": "B",
    "title": "Berland Bingo",
    "statement": "Lately, a national version of a bingo game has become very popular in Berland. There are $n$ players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the $i$-th player contains $m_{i}$ numbers.\n\nDuring the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct.\n\nYou are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.",
    "tutorial": "It is good idea to think about cards as set of numbers. It is easy to see that card $a$ can't be finished before $b$ if $b$ is subset of $a$. So all you need is to find such cards (sets) which do not have other card (other set) as subset. Since there are at most 1000 cards, you may iterate through all pairs and check that one card contains other in naive way like:",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "370",
    "index": "C",
    "title": "Mittens",
    "statement": "A Christmas party in city S. had $n$ children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to $m$, and the children are numbered from 1 to $n$. Then the $i$-th child has both mittens of color $c_{i}$.\n\nThe Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children.\n\nThe children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.",
    "tutorial": "Let's show that if the most frequent color appears not more than $\\lfloor{\\frac{n}{2}}\\rfloor$ times, than all children can get mittens of distinct colors. One way to construct such solution is to sort all left mittens in the order of decreasing frequency of their colors: for the input 1 2 1 2 3 1 3 3 1 we get 1 1 1 1 3 3 3 2 2. To obtain the sequence of right mittens, rotate the sequence of left mittens to the left by the maximum color frequency (in the example it is 4, so we get the sequence 3 3 3 2 2 1 1 1 1). Then just match the sequences (1 - 3, 1 - 3, 1 - 3, 1 - 2, 3 - 2, 3 - 1, 3 - 1, 2 - 1, 2 - 1). It can be easily shown that all pairs consist of distinct colors. OK, but what to do if there is a dominating color that appears more than half times? Use exactly the same algorithm! It will maximize the number of pairs of distinct colors.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "370",
    "index": "D",
    "title": "Broken Monitor",
    "statement": "Innocentius has a problem — his computer monitor has broken. Now some of the pixels are \"dead\", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.\n\nInnocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as \"the game is good for the imagination and attention\".\n\nHelp Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that:\n\n- the frame's width is 1 pixel,\n- the frame doesn't go beyond the borders of the screen,\n- all white pixels of the monitor are located on the frame,\n- of all frames that satisfy the previous three conditions, the required frame must have the smallest size.\n\nFormally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is $d = 3$, then it consists of 8 pixels, if its size is $d = 2$, then it contains 4 pixels and if $d = 1$, then the frame is reduced to a single pixel.",
    "tutorial": "There are a lot of correct approaches to solve the problem. But there are much more incorrect :) One way to solve the problem is following. It is easy to see that in possible answer there are two opposite sides each containing w. In opposite case frame can be shrinked. So the size of frame is $dx$ or $dy$, where $dx = maxx - minx + 1$ and $dy = maxy - miny + 1$ ($minx, maxx, miny, maxy$ are coordinates of left/right/top/bottom ws). Obviously, you should choose $max(dx, dy)$ as a size. Now we know the size of the required frame. How to find it's leftmost-topmost corner? The set of possible $x$s is: $minx, maxx - size + 1$ and 0. Indeed, you may move frame to the left until it will abuts to w by left size/right size of abuts to the left side of monitor. Similarly, the set of possible $y$s as y-coordinate of leftmost-topmost corner: $miny, maxy - size + 1, 0$. Now the solution looks like: All you need is to write frame_correct. You may iterate through frame and check that all cells inside monitor and calculate the number of ws on it. If all the cells are inside and calculated number equals to total number of w, then return true. This solution works in $O(nm)$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "370",
    "index": "E",
    "title": "Summer Reading",
    "statement": "At school Vasya got an impressive list of summer reading books. Unlike other modern schoolchildren, Vasya loves reading, so he read some book each day of the summer.\n\nAs Vasya was reading books, he was making notes in the Reader's Diary. Each day he wrote the orderal number of the book he was reading. The books in the list are numbered starting from 1 and Vasya was reading them in the order they go in the list. Vasya never reads a new book until he finishes reading the previous one. Unfortunately, Vasya wasn't accurate and some days he forgot to note the number of the book and the notes for those days remained empty.\n\nAs Vasya knows that the literature teacher will want to check the Reader's Diary, so he needs to restore the lost records. Help him do it and fill all the blanks. Vasya is sure that he spends at least two and at most five days for each book. Vasya finished reading all the books he had started. Assume that the reading list contained many books. So many, in fact, that it is impossible to read all of them in a summer. If there are multiple valid ways to restore the diary records, Vasya prefers the one that shows the maximum number of read books.",
    "tutorial": "For each book number that is in the sequence, find the leftmost and the rightmost position of this number. In other words, for each such book number we find a segment of positions that should consist of this number. If for some pair of numbers there segments intersect, it is impossible to construct the answer. The same thing happens if some segment has length more than 5. It is reasonable to separately handle the case when all given numbers are zeroes. In this case, fill in the numbers greedily, spending 2 days on each book (probably, except the last one). So, we have some blocks of numbers and gaps between them. Lets do the following DP: each state of DP is described by two values ($i, j$): $i$ means the number of block (lets enumerate them consecutively), $j$ means how far to the right will this block eventually extend (if there is a gap after this block, it is possible that we fill some prefix of this gap with the same book number that is in the block). It is clear that $j - i$ will not exceed 5, so we actually can describe the state by values ($i, j - i$), which may sound more convenient. So, the number of states is linear. Lets say that $D(i, j)$ is true if it it possible to correctly fill all the gaps that come before the $i$-th block, under condition that the $i$-th block extends to the position $j$, and $D(i, j)$ is false otherwise. To calculate the value of $D(i, j)$, lets try to extend the $i$-th block to the left in all (not so many) possible ways (to replace some number of consecutive zeroes that are in the gap just before the $i$-th block). Then, try to fix where the previous block can actually end (fix the state $D(i - 1, k)$, where $D(i - 1, k)$ is true, of course). To make a transition in DP, we should check whether it possible or not to fill the rest of the gap between the $(i - 1)$-th block and the $i$-th block. Lets say that $(i - 1)$-th block consists of number $x$, the $i$-th block consists of number $y$, and there are $f$ still unfilled positions in the gap. Than the gap can be correctly filled if and only if $2 \\cdot (y - x - 1)  \\le  f  \\le  5 \\cdot (y - x - 1)$. If you understand this DP, it won't be difficult for you to find out how to construct the answer from it.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "371",
    "index": "A",
    "title": "K-Periodic Array",
    "statement": "This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.\n\nArray $a$ is $k$-period if its length is divisible by $k$ and there is such array $b$ of length $k$, that $a$ is represented by array $b$ written exactly $\\scriptstyle{\\frac{n}{k}}$ times consecutively. In other words, array $a$ is $k$-periodic, if it has period of length $k$.\n\nFor example, any array is $n$-periodic, where $n$ is the array length. Array $[2, 1, 2, 1, 2, 1]$ is at the same time 2-periodic and 6-periodic and array $[1, 2, 1, 1, 2, 1, 1, 2, 1]$ is at the same time 3-periodic and 9-periodic.\n\nFor the given array $a$, consisting only of numbers one and two, find the minimum number of elements to change to make the array $k$-periodic. If the array already is $k$-periodic, then the required value equals $0$.",
    "tutorial": "For array to be periodic, elements $1, 1 + k, 1 + 2 * k,  \\dots $ must be equal. Also, elements $2, 2 + k, 2 + 2 * k,  \\dots $ must be equal. And so on up to $k$. So each element of the array is a part of exactly one group. And there are $k$ groups total. Each such group is independent. Let's consider some group of elements, that contain $a$ ones and $b$ twos. All elements in this group must be equal. So we either change all ones to twos or all twos to ones. First option will require $a$ changing operations and second one - $b$ changing operations. For the optimal solution, you should select the operation with smaller number of changing operations required.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "371",
    "index": "B",
    "title": "Fox Dividing Cheese",
    "statement": "Two little greedy bears have found two pieces of cheese in the forest of weight $a$ and $b$ grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: \"Little bears, wait a little, I want to make your pieces equal\" \"Come off it fox, how are you going to do that?\", the curious bears asked. \"It's easy\", said the fox. \"If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal\".\n\nThe little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal.",
    "tutorial": "It is easy to see that the fox can do three type of operations: divide by 2, divide by 3 and divide by 5. Let's write both given numbers in form $a = x \\cdot 2^{a2} \\cdot 3^{a3} \\cdot 5^{a5}$, $b = y \\cdot 2^{b2} \\cdot 3^{b3} \\cdot 5^{b5}$, where $x$ and $y$ are not dibisible by 2, 3 and 5. If $x  \\neq  y$ the fox can't make numbers equal and program should print -1. If $x = y$ then soluion exists. The answer equals to $|a_{2} - b_{2}| + |a_{3} - b_{3}| + |a_{5} - b_{5}|$, because $|a_{2} - b_{2}|$ is the minimal number of operations to have 2 in the same power in both numbers, $|a_{3} - b_{3}|$ is the minimal number of operations to have 3 in the same power in both numbers, and $|a_{5} - b_{5}|$ is the same for 5.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "371",
    "index": "C",
    "title": "Hamburgers",
    "statement": "Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite \"Le Hamburger de Polycarpus\" as a string of letters 'B' (bread), 'S' (sausage) и 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe \"ВSCBS\" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again.\n\nPolycarpus has $n_{b}$ pieces of bread, $n_{s}$ pieces of sausage and $n_{c}$ pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are $p_{b}$ rubles for a piece of bread, $p_{s}$ for a piece of sausage and $p_{c}$ for a piece of cheese.\n\nPolycarpus has $r$ rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient.",
    "tutorial": "Let's use binary search approach. For given number of hamburgers (say, $x$) let's find the minimal number of money needed to cook them. Say, for one hamburger Polycarpus needs $c_{b}$ bread pieces, $c_{s}$ sausages pieces, $c_{c}$ cheese pieces. So for $x$ hamburgers he needs: $c_{b} \\cdot x$, $c_{s} \\cdot x$ and $c_{c} \\cdot x$ pieces (by types). Since he already has $n_{b}$, $n_{s}$ and $n_{c}$ pieces, so he needs to buy: bread: $\\max(0, c_b \\cdot x - n_b)$, sausages: $\\max(0, c_s \\cdot x - n_s)$, cheese: $\\max(0, c_c \\cdot x - n_c)$. So the formula to calculate money to cook $x$ hamburgers is: $f(x) = max(0, c_{b} \\cdot x - n_{b}) \\cdot p_{b} + max(0, c_{s} \\cdot x - n_{s}) \\cdot p_{s} + max(0, c_{c} \\cdot x - n_{c}) \\cdot p_{c}$ Obviously, the function $f(x)$ is monotonic (increasing). So it is possible to use binary search approach to find largest $x$ such that $f(x) ler$.",
    "tags": [
      "binary search",
      "brute force"
    ],
    "rating": 1600
  },
  {
    "contest_id": "371",
    "index": "D",
    "title": "Vessels",
    "statement": "There is a system of $n$ vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to $n$, in the order from the highest to the lowest, the volume of the $i$-th vessel is $a_{i}$ liters.\n\nInitially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the $i$-th vessel goes to the $(i + 1)$-th one. The liquid that overflows from the $n$-th vessel spills on the floor.\n\nYour task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries:\n\n- Add $x_{i}$ liters of water to the $p_{i}$-th vessel;\n- Print the number of liters of water in the $k_{i}$-th vessel.\n\nWhen you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.",
    "tutorial": "The naive solution for this problem will work like this. Let us store an amount of water in each vessel in some array $v$. If we need to know how much water is in some vessel, we just take the number from the array. If we need to pour $x$ units of water into vessel number $i$, we must follow the simple procedure: 1. If $x = 0$ then all water is poured and we must end the procedure 2. If $i > n$ then all remaining water is spilled on the floor and we must end the procedure 3. If $x$ units of water can fit into the $i$-th vessel, then add $x$ to $v[i]$ and end the procedure 4. Fill $i$-th vessel completely and subtract used amount from $x$. 5. Assign $i = i + 1$. 6. Go to the first step. In the worst case scenario such procedure can iterate through all vessels each time. For example, if there are $n$ vessels and each vessels have capacity of one unit of water, each query like $11n$ will take $O(n)$ time to process. To make this solution faster we should notice, that once completely filled, vessel can be skipped during the algorithm above because it can not consume any more water. So instead of $i = i + 1$ assignment should be like $i = findNextNotFilledVessel(i)$. To implement this function we can use different structures. For example, we can use sorted set of numbers (set in C++, TreeSet in Java). Let store the set of indices of unfilled vessels. So to find next not filled vessel from $i$-th vessel, we must find smallest number, that is contained in set and is strictly greater than $i$. There are built-in methods for it (upper_bound in C++, higher in Java). Also, each time we fill the vessel, we must erase corresponding index from the set. So now we can see, that algorithm can not complete more that $O((m + n)logn)$ operations for all queries. Because on each iteration of the pouring procedure either the vessel is filled (which can only happen $n$ times during the whole runtime), or we run out of water (or vessels) and the procedure is stopped. So there will be only total of $O(m + n)$ iterations of the pouring procedure and each iteration require one lookup in the sorted set, which takes $O(logn)$ operations. So the total number of needed operations is $O((m + n)logn)$.",
    "tags": [
      "data structures",
      "dsu",
      "implementation",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "371",
    "index": "E",
    "title": "Subway Innovation",
    "statement": "Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!\n\nThe President of Berland was forced to leave only $k$ of the currently existing $n$ subway stations.\n\nThe subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the $Ox$ axis, the $i$-th station is at point with coordinate $x_{i}$. In such case the distance between stations $i$ and $j$ is calculated by a simple formula $|x_{i} - x_{j}|$.\n\nCurrently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such $k$ stations that minimize the average commute time in the subway!\n\nAssuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is $\\textstyle{\\frac{n(n-1)}{2}}$) and divided by the speed of the train.\n\nHelp the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such $k$ stations that the average commute time in the subway is minimized.",
    "tutorial": "It is easy to see that you need to minimize the sum of pairwise distances between $k$ stations. The main idea to do it is to sort them and the required stations will form a continuous segment. It is easy to prove by contradiction. Huge constraints do not allow to use straight-forward method to find required segment. Let's call $f(i, k)$ - sum of pairwise distances of $k$ stations starting from the $i$-th. To find $f(0, k)$ you need to start from $f(0, 0) = 0$ and use transformation from calculated $f(0, i)$ to $f(0, i + 1)$. You can use equation: $f(0,i+1)=f(0,i)+\\sum_{0<i<i}(x_{i}-x_{j})=$ $=f(0,i)+x_{i}\\cdot i-\\sum_{\\small o<i<i}x_{j}=$ $= f(0, i) + x_{i} \\cdot i - sum(0, i - 1)$ where $sum(l, r)$ means $x_{l} + x_{l + 1} + ... + x_{r}$. We can precalculate $sum[i] = x_{0} + x_{1} + ... + x_{i}$ and use equation $sum(l, r) = sum[r] - sum[l - 1]$ to find $sum(l, r)$ in $O(1)$. Actually we need $f(0, k)$, $f(1, k)$ and so on (and find minimal value among them). To recalculate $f(i, k)$ to $f(i + 1, k)$ you need exclude $x_{i}$ and include $x_{i + k}$. Using the method like in the previous paragraph: $f(i + 1, k) = f(i, k) - (sum(i + 1, i + k - 1) - x_{i} \\cdot (k - 1)) + (x_{i + k} \\cdot (k - 1) - sum(i + 1, i + k - 1))$.",
    "tags": [
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "372",
    "index": "A",
    "title": "Counting Kangaroos is Fun",
    "statement": "There are $n$ kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.\n\nEach kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.\n\nThe kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.",
    "tutorial": "Because of the number of holding-held relations is at most $\\textstyle{\\frac{N}{2}}$, We can assume that first half of kangaroos do not hold any kangaroos, and last half of kangaroos are not held by any kangaroos. So we can split kangaroos in two set, such that first set contains the kangaroos whose size is in smaller half and second set contains the kangaroos whose size is in larger half, and use easy greedy algorithm. The time conplexity is O(N log N) for sorting and O(N) for greedy, so the time conplexity is O(N log N).",
    "code": "#include<stdio.h>\n#include<vector>\n#include<algorithm>\nusing namespace std;\nint main()\n{\n\tint num;\n\tscanf(\"%d\",&num);\n\tvector<int>vec;\n\tfor(int i=0;i<num;i++)\n\t{\n\t\tint zan;\n\t\tscanf(\"%d\",&zan);\n\t\tvec.push_back(zan);\n\t}\n\tsort(vec.begin(),vec.end());\n\tint pt=num/2;\n\tint ans=num;\n\tfor(int i=0;i<num/2;i++)\n\t{\n\t\tfor(;;)\n\t\t{\n\t\t\tif(vec[i]*2<=vec[pt])\n\t\t\t{\n\t\t\t\tans--;\n\t\t\t\tpt++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpt++;\n\t\t\t}\n\t\t\tif(pt==num)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(pt==num)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"%d\\n\",ans);\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "372",
    "index": "B",
    "title": "Counting Rectangles is Fun",
    "statement": "There is an $n × m$ rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the $i$-th row and the $j$-th column as $(i, j)$.\n\nLet's define a \"rectangle\" as four integers $a, b, c, d$ $(1 ≤ a ≤ c ≤ n; 1 ≤ b ≤ d ≤ m)$. Rectangle denotes a set of cells of the grid ${(x, y) :  a ≤ x ≤ c, b ≤ y ≤ d}$. Let's define a \"good rectangle\" as a rectangle that includes only the cells with zeros.\n\nYou should answer the following $q$ queries: calculate the number of good rectangles all of which cells are in the given rectangle.",
    "tutorial": "We can precalculate all rectangles, in O(N^2M^2) with using consecutive sums for 2D. And then we use 4D consecutive sums, we can answer the queries. The time conplexity is O(N^2M^2+Q).",
    "code": "#include<stdio.h>\nint map[50][50];\nint rui[51][51];\nint dat[50][50][50][50];\nint ans[51][51][51][51];\nint main()\n{\n\tint mx,my,query;\n\tscanf(\"%d%d%d\",&mx,&my,&query);\n\tfor(int i=0;i<mx;i++)\n\t{\n\t\tfor(int j=0;j<my;j++)\n\t\t{\n\t\t\tchar zan;\n\t\t\tscanf(\" %c\",&zan);\n\t\t\tmap[i][j]=zan-'0';\n\t\t}\n\t}\n\tfor(int i=0;i<mx;i++)\n\t{\n\t\tfor(int j=0;j<my;j++)\n\t\t{\n\t\t\trui[i+1][j+1]=rui[i+1][j]+rui[i][j+1]-rui[i][j]+map[i][j];\n\t\t}\n\t}\n\tfor(int i=0;i<mx;i++)\n\t{\n\t\tfor(int j=0;j<my;j++)\n\t\t{\n\t\t\tfor(int k=i;k<mx;k++)\n\t\t\t{\n\t\t\t\tfor(int l=j;l<my;l++)\n\t\t\t\t{\n\t\t\t\t\tif(rui[k+1][l+1]-rui[i][l+1]-rui[k+1][j]+rui[i][j]==0)\n\t\t\t\t\t{\n\t\t\t\t\t\tdat[i][j][k][l]=1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=0;i<mx;i++)\n\t{\n\t\tfor(int j=0;j<my;j++)\n\t\t{\n\t\t\tfor(int k=0;k<mx;k++)\n\t\t\t{\n\t\t\t\tfor(int l=0;l<my;l++)\n\t\t\t\t{\n\t\t\t\t\tans[i+1][j+1][k+1][l+1]\n\t\t\t\t\t=ans[i][j+1][k+1][l+1]\n\t\t\t\t\t+ans[i+1][j][k+1][l+1]\n\t\t\t\t\t+ans[i+1][j+1][k][l+1]\n\t\t\t\t\t+ans[i+1][j+1][k+1][l]\n\t\t\t\t\t-ans[i][j][k+1][l+1]\n\t\t\t\t\t-ans[i][j+1][k][l+1]\n\t\t\t\t\t-ans[i][j+1][k+1][l]\n\t\t\t\t\t-ans[i+1][j][k][l+1]\n\t\t\t\t\t-ans[i+1][j][k+1][l]\n\t\t\t\t\t-ans[i+1][j+1][k][l]\n\t\t\t\t\t+ans[i+1][j][k][l]\n\t\t\t\t\t+ans[i][j+1][k][l]\n\t\t\t\t\t+ans[i][j][k+1][l]\n\t\t\t\t\t+ans[i][j][k][l+1]\n\t\t\t\t\t-ans[i][j][k][l]\n\t\t\t\t\t+dat[i][j][k][l];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor(int p=0;p<query;p++)\n\t{\n\t\tint a,b,c,d;\n\t\tscanf(\"%d%d%d%d\",&a,&b,&c,&d);\n\t\ta--;\n\t\tb--;\n\t\tc--;\n\t\td--;\n\t\tprintf(\"%d\\n\",\n\t\t\tans[c+1][d+1][c+1][d+1]\n\t\t\t-ans[a][d+1][c+1][d+1]\n\t\t\t-ans[c+1][b][c+1][d+1]\n\t\t\t-ans[c+1][d+1][a][d+1]\n\t\t\t-ans[c+1][d+1][c+1][b]\n\t\t\t+ans[a][b][c+1][d+1]\n\t\t\t+ans[a][d+1][a][d+1]\n\t\t\t+ans[a][d+1][c+1][b]\n\t\t\t+ans[c+1][b][a][d+1]\n\t\t\t+ans[c+1][b][c+1][b]\n\t\t\t+ans[c+1][d+1][a][b]\n\t\t\t-ans[c+1][b][a][b]\n\t\t\t-ans[a][d+1][a][b]\n\t\t\t-ans[a][b][c+1][b]\n\t\t\t-ans[a][b][a][d+1]\n\t\t\t+ans[a][b][a][b]);\n\t}\n}",
    "tags": [
      "brute force",
      "divide and conquer",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "372",
    "index": "C",
    "title": "Watching Fireworks is Fun",
    "statement": "A festival will be held in a town's main street. There are $n$ sections in the main street. The sections are numbered $1$ through $n$ from left to right. The distance between each adjacent sections is $1$.\n\nIn the festival $m$ fireworks will be launched. The $i$-th ($1 ≤ i ≤ m$) launching is on time $t_{i}$ at section $a_{i}$. If you are at section $x$ ($1 ≤ x ≤ n$) at the time of $i$-th launching, you'll gain happiness value $b_{i} - |a_{i} - x|$ (note that the happiness value might be a negative value).\n\nYou can move up to $d$ length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to $1$), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness.\n\nNote that two or more fireworks can be launched at the same time.",
    "tutorial": "I think most of the participants came up with simple DP algorithm : dp[i][j] := the maximum happiness value that you can gain when you're on poisition j at i th launching. Each value in table can be calculated by this formula : $dp[i][j] = max[k = - t * d..t * d](dp[i - 1][j + k] + b[i] - |a[i] - j|)$ where $t = t[i] - t[i - 1]$. If you look up for all k, since the table's size is O(mn), the overall complexity will be O(mn^2), and its too slow to solve the problem. Now, We're going to make this algorithm faster. Since the second term in the DP formula doesn't depend on k, you have to find maximum value of dp[i - 1][j + k] faster. Using segment tree or sparse table can fasten finding from O(n) to O(log n), but the overall complexity is still O(mn log n), and the solution will get time limit exceeded. Intended solution uses sliding window maximum (see this page http://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html) for some information), since the interval $[j - t * d, j + t * d]$ is independent for all the fireworks. It can be implemented by simple array or deque. This will speed up to calculate formula, and overall complexity will be O(mn). kcm1700 has submitted faster solution than our intended one during contest! It's complexity is O(m^2).",
    "code": "#include <cstdio>\n#include <climits>\n#include <deque>\n#include <algorithm>\n\nusing namespace std;\n\ntypedef long long lint;\n\nint main()\n{\n    int N, M, D;\n    int a[1000], b[1000], t[1000];\n    lint dp[2][300001];\n    \n    scanf(\"%d %d %d\", &N, &M, &D);\n    \n    for (int i = 0; i < M; i++){\n        scanf(\"%d %d %d\", a + i, b + i, t + i);\n    }\n    \n    for (int i = 1; i <= N; i++){\n        dp[0][i] = 0;\n    }\n    \n    int p = 1;\n    int pT = 1;\n    for (int i = 0; i < M; i++){\n        deque<int> dq;\n        lint interval = min((lint)N, (lint)(t[i] - pT) * D);\n        \n        for (lint j = 1; j <= interval; j++){\n            while (dq.size() && dp[1 - p][dq[dq.size() - 1]] <= dp[1 - p][(int)j]) dq.pop_back();\n            dq.push_back((int)j);\n        }\n        \n        for (lint j = 1; j <= (lint)N; j++){\n            lint k = j + interval;\n            if (k <= (lint)N){\n                while (dq.size() && dp[1 - p][dq[dq.size() - 1]] <= dp[1 - p][(int)k]) dq.pop_back();\n                dq.push_back((int)k);\n            }\n            dp[p][j] = dp[1 - p][dq[0]] + (lint)(b[i] - abs(a[i] - j));\n            while (dq.size() && dq[0] <= (int)(j - interval)) dq.pop_front();\n        }\n        pT = t[i];\n        p = 1 - p;\n    }\n    \n    lint ans = LLONG_MIN;\n    for (int i = 1; i <= N; i++)\n        ans = max(ans, dp[1 - p][i]);\n    \n    printf(\"%I64d\\n\", ans);\n    \n    return (0);\n}",
    "tags": [
      "data structures",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "372",
    "index": "D",
    "title": "Choosing Subtree is Fun",
    "statement": "There is a tree consisting of $n$ vertices. The vertices are numbered from $1$ to $n$.\n\nLet's define the length of an interval $[l, r]$ as the value $r - l + 1$. The score of a subtree of this tree is the maximum length of such an interval $[l, r]$ that, the vertices with numbers $l, l + 1, ..., r$ belong to the subtree.\n\nConsidering all subtrees of the tree whose size is at most $k$, return the maximum score of the subtree. Note, that in this problem tree is not rooted, so a subtree — is an arbitrary connected subgraph of the tree.",
    "tutorial": "We can use two pointers, which treat the interval of the consecutive numbers of node on tree. All we have to do is answer the query which requires the minimal number of size of subtree which contains all the vertices in the set, after the \"add vertices to the set\" and \"delete verticesto the set\" operations. We can calculate the distance between two nodes with LCA algorithm, then when we order the nodes by dfs order, we can answer the \"add vertice\" query that adds the vertice which is numbered $s$ in dfs order, and assume that previous numbered vertices in dfs order in the set is t, and next is u, we can get rid of the \"add\" query that $(current size of subtree)+distance(s,t)+distance(t,u)-distance(s,u), and \"delete\" so on. The time conplexity of LCA algorithm is O(log N), so we can solve this problem in O(Nlog N). There is another solution which uses heavy-light decomposition and segment tree. This solution is O(Nlog^2 N), which also pass.",
    "code": "#include<stdio.h>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n#define SIZE 131072\nvector<int>pat[100000];\nvector<int>ko[100000];\nint par[19][100000];\nint depth[100000];\nbool flag[100000];\nint heavy[100000];\nint toseg[100000];\nint pattop[100000];\nvoid dfs(int node,int d)\n{\n\tif(flag[node])\n\t{\n\t\treturn;\n\t}\n\tflag[node]=true;\n\tdepth[node]=d;\n\tfor(int i=0;i<pat[node].size();i++)\n\t{\n\t\tif(!flag[pat[node][i]])\n\t\t{\n\t\t\tdfs(pat[node][i],d+1);\n\t\t\tko[node].push_back(pat[node][i]);\n\t\t\tpar[0][pat[node][i]]=node;\n\t\t}\n\t}\n}\nint num;\nvoid lcainit()\n{\n\tfor(int i=1;i<=18;i++)\n\t{\n\t\tfor(int j=0;j<num;j++)\n\t\t{\n\t\t\tpar[i][j]=par[i-1][par[i-1][j]];\n\t\t}\n\t}\n}\nint lca(int a,int b)\n{\n\tif(a==-1)\n\t{\n\t\treturn b;\n\t}\n\tif(b==-1)\n\t{\n\t\treturn a;\n\t}\n\tif(depth[a]>depth[b])\n\t{\n\t\tswap(a,b);\n\t}\n\tfor(int i=18;i>=0;i--)\n\t{\n\t\tif(depth[a]+(1<<i)<=depth[b])\n\t\t{\n\t\t\tb=par[i][b];\n\t\t}\n\t}\n\tif(a==b)\n\t{\n\t\treturn a;\n\t}\n\tfor(int i=18;i>=0;i--)\n\t{\n\t\tif(par[i][a]!=par[i][b])\n\t\t{\n\t\t\ta=par[i][a];\n\t\t\tb=par[i][b];\n\t\t}\n\t}\n\treturn par[0][a];\n}\nint decomposit(int node)\n{\n\tint maxi=0,rr;\n\tif(ko[node].empty())\n\t{\n\t\theavy[node]=-1;\n\t\treturn 1;\n\t}\n\tint siz=0;\n\tfor(int i=0;i<ko[node].size();i++)\n\t{\n\t\tint z=decomposit(ko[node][i]);\n\t\tif(maxi<z)\n\t\t{\n\t\t\tmaxi=z;\n\t\t\trr=ko[node][i];\n\t\t\tsiz+=z;\n\t\t}\n\t}\n\theavy[node]=rr;\n\treturn siz+1;\n}\nclass lcatree\n{\npublic:\n\tint seg[SIZE*2];\n\tvoid init()\n\t{\n\t\tfor(int i=0;i<num;i++)\n\t\t{\n\t\t\tseg[SIZE+i]=i;\n\t\t}\n\t\tfor(int i=num;i<SIZE;i++)\n\t\t{\n\t\t\tseg[SIZE+i]=-1;\n\t\t}\n\t\tfor(int i=SIZE-1;i>=1;i--)\n\t\t{\n\t\t\tseg[i]=lca(seg[i*2],seg[i*2+1]);\n\t\t}\n\t}\n\tint getlca(int beg,int end,int node,int lb,int ub)\n\t{\n\t\tif(ub<beg||end<lb)\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t\tif(beg<=lb&&ub<=end)\n\t\t{\n\t\t\treturn seg[node];\n\t\t}\n\t\treturn lca(getlca(beg,end,node*2,lb,(lb+ub)/2),getlca(beg,end,node*2+1,(lb+ub)/2+1,ub));\n\t}\n};\nclass segtree\n{\npublic:\n\tint segmin[SIZE*2];\n\tint segnum[SIZE*2];\n\tint flag[SIZE*2];\n\tvoid init()\n\t{\n\t\tfor(int i=0;i<SIZE;i++)\n\t\t{\n\t\t\tsegnum[SIZE+i]=1;\n\t\t}\n\t\tfor(int i=SIZE-1;i>=1;i--)\n\t\t{\n\t\t\tsegnum[i]=segnum[i*2]+segnum[i*2+1];\n\t\t}\n\t}\n\tvoid update(int beg,int end,int node,int lb,int ub,int num)\n\t{\n\t\tif(ub<beg||end<lb)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif(beg<=lb&&ub<=end)\n\t\t{\n\t\t\tsegmin[node]+=num;\n\t\t\tflag[node]+=num;\n\t\t\treturn;\n\t\t}\n\t\tif(flag[node])\n\t\t{\n\t\t\tsegmin[node*2]+=flag[node];\n\t\t\tsegmin[node*2+1]+=flag[node];\n\t\t\tflag[node*2]+=flag[node];\n\t\t\tflag[node*2+1]+=flag[node];\n\t\t\tflag[node]=0;\n\t\t}\n\t\tupdate(beg,end,node*2,lb,(lb+ub)/2,num);\n\t\tupdate(beg,end,node*2+1,(lb+ub)/2+1,ub,num);\n\t\tsegnum[node]=0;\n\t\tsegmin[node]=min(segmin[node*2],segmin[node*2+1]);\n\t\tif(segmin[node*2]<=segmin[node*2+1])\n\t\t{\n\t\t\tsegnum[node]+=segnum[node*2];\n\t\t}\n\t\tif(segmin[node*2]>=segmin[node*2+1])\n\t\t{\n\t\t\tsegnum[node]+=segnum[node*2+1];\n\t\t}\n\t}\n\tint get()\n\t{\n\t\tif(segmin[1]!=0)\n\t\t{\n\t\t\treturn SIZE;\n\t\t}\n\t\treturn SIZE-segnum[1];\n\t}\n};\nlcatree ltree;\nsegtree tree;\nint main()\n{\n\tint gen;\n\tscanf(\"%d%d\",&num,&gen);\n\tfor(int i=0;i<num-1;i++)\n\t{\n\t\tint za,zb;\n\t\tscanf(\"%d%d\",&za,&zb);\n\t\tza--;\n\t\tzb--;\n\t\tpat[za].push_back(zb);\n\t\tpat[zb].push_back(za);\n\t}\n\tfill(flag,flag+num,false);\n\tfor(int i=0;i<=18;i++)\n\t{\n\t\tfor(int j=0;j<num;j++)\n\t\t{\n\t\t\tpar[i][j]=-1;\n\t\t}\n\t}\n\tdfs(0,0);\n\tlcainit();\n\tfill(heavy,heavy+num,-1);\n\tdecomposit(0);\n\tint pt=0;\n\tfor(int i=0;i<num;i++)\n\t{\n\t\tif(par[0][i]!=-1)\n\t\t{\n\t\t\tif(heavy[par[0][i]]==i)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tint now=i;\n\t\tfor(;;)\n\t\t{\n\t\t\ttoseg[now]=pt++;\n\t\t\tpattop[now]=i;\n\t\t\tnow=heavy[now];\n\t\t\tif(now==-1)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tpt=0;\n\tltree.init();\n\ttree.init();\n\tint maxi=0;\n\tfor(int i=0;i<num;i++)\n\t{\n\t\tint now=i;\n\t\tfor(;;)\n\t\t{\n\t\t\tif(now==-1)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttree.update(toseg[pattop[now]],toseg[now],1,0,SIZE-1,1);\n\t\t\tnow=par[0][pattop[now]];\n\t\t}\n\t\tfor(;;)\n\t\t{\n\t\t\tint l=ltree.getlca(pt,i,1,0,SIZE-1);\n\t\t\tif(tree.get()-depth[l]>gen)\n\t\t\t{\n\t\t\t\tint n=pt;\n\t\t\t\tfor(;;)\n\t\t\t\t{\n\t\t\t\t\tif(n==-1)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ttree.update(toseg[pattop[n]],toseg[n],1,0,SIZE-1,-1);\n\t\t\t\t\tn=par[0][pattop[n]];\n\t\t\t\t}\n\t\t\t\tpt++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmaxi=max(maxi,i-pt+1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(pt>i)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"%d\\n\",maxi);\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "trees",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "372",
    "index": "E",
    "title": "Drawing Circles is Fun",
    "statement": "There are a set of points $S$ on the plane. This set doesn't contain the origin $O(0, 0)$, and for each two distinct points in the set $A$ and $B$, the triangle $OAB$ has strictly positive area.\n\nConsider a set of pairs of points $(P_{1}, P_{2}), (P_{3}, P_{4}), ..., (P_{2k - 1}, P_{2k})$. We'll call the set good if and only if:\n\n- $k ≥ 2$.\n- All $P_{i}$ are distinct, and each $P_{i}$ is an element of $S$.\n- For any two pairs $(P_{2i - 1}, P_{2i})$ and $(P_{2j - 1}, P_{2j})$, the circumcircles of triangles $OP_{2i - 1}P_{2j - 1}$ and $OP_{2i}P_{2j}$ have a single common point, and the circumcircle of triangles $OP_{2i - 1}P_{2j}$ and $OP_{2i}P_{2j - 1}$ have a single common point.\n\nCalculate the number of good sets of pairs modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "All circles we must consider pass through O, so we can consider the operation inversion. At this operation, the point $(x, y)$ will be $\\left({\\frac{x}{x^{2}+y^{2}}},\\,{\\frac{y}{x^{2}+y^{2}}}\\right)$. From now, we think the plane as the plane after inversed. \"The circumcircles of triangles $OAB$ and $OCD$ have a single common point, and the circumcircle of triangles $OAD$ and $OBC$ have a single common point\" can be said, after the inversion, $ABCD$ is parallelogram. And we can say it \"the diagonal $AC$ and $BD$ have a common midpoint and the inclination of $AC$ and $BD$ are different\". So all we have to do is make the list of the midpoints and inclination of all pairs of points and the line passes through them, and sort this array, and do some multiplication. It can be solved in O(N^2 log N).",
    "code": "#include<stdio.h>\n#include<vector>\n#include<algorithm>\n#include<stdlib.h>\n#include<math.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<ll,ll>pii;\ntypedef pair<pii,pii>pi4;\ntypedef pair<pi4,pii>pi6;\nll mod=1000000007;\nll gcd(ll a,ll b)\n{\n\tfor(;;)\n\t{\n\t\tif(a<b)\n\t\t{\n\t\t\tswap(a,b);\n\t\t}\n\t\ta%=b;\n\t\tif(a==0)\n\t\t{\n\t\t\treturn b;\n\t\t}\n\t}\n}\npii reduct(pii a)\n{\n\tif(a.second==0)\n\t{\n\t\treturn make_pair(1LL,0LL);\n\t}\n\tif(a.first==0)\n\t{\n\t\treturn make_pair(0LL,1LL);\n\t}\n\tll g=gcd(abs(a.first),abs(a.second));\n\tif(a.second<0)\n\t{\n\t\ta.first=-a.first;\n\t\ta.second=-a.second;\n\t}\n\treturn make_pair(a.first/g,a.second/g);\n}\npii pls(pii a,pii b)\n{\n\treturn reduct(make_pair(a.first*b.second+a.second*b.first,a.second*b.second));\n}\npii mins(pii a,pii b)\n{\n\treturn reduct(make_pair(a.first*b.second-a.second*b.first,a.second*b.second));\n}\npii tim(pii a,pii b)\n{\n\treturn reduct(make_pair(a.first*b.first,a.second*b.second));\n}\npii div(pii a,pii b)\n{\n\treturn reduct(make_pair(a.first*b.second,a.second*b.first));\n}\npi4 getsum(pi4 a,pi4 b)\n{\n\treturn make_pair(pls(a.first,b.first),pls(a.second,b.second));\n}\npii getinc(pi4 a,pi4 b)\n{\n\tpii dx=mins(b.first,a.first);\n\tpii dy=mins(b.second,a.second);\n\treturn div(dy,dx);\n}\npi4 inv(ll za,ll zb,ll zc,ll zd)\n{\n\tpii dist=pls(tim(make_pair(za,zb),make_pair(za,zb)),tim(make_pair(zc,zd),make_pair(zc,zd)));\n\treturn (make_pair(div(make_pair(za,zb),dist),div(make_pair(zc,zd),dist)));\n}\nvector<int>tov(vector<pii>vec)\n{\n\tpii now=make_pair(2000000000000000000LL,2000000000000000000LL);\n\tvector<int>ret;\n\tfor(int i=0;i<vec.size();i++)\n\t{\n\t\tif(now!=vec[i])\n\t\t{\n\t\t\tret.push_back(1);\n\t\t\tnow=vec[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tret[ret.size()-1]++;\n\t\t}\n\t}\n\treturn ret;\n}\nll calc(vector<pii>v)\n{\n\tvector<int>vec=tov(v);\n\tll ret=1;\n\tfor(int i=0;i<vec.size();i++)\n\t{\n\t\tret*=vec[i]+1;\n\t\tret%=mod;\n\t}\n\tret=(ret+mod-1-int(v.size()))%mod;\n\treturn ret;\n}\nint main()\n{\n\tint num;\n\tscanf(\"%d\",&num);\n\tvector<pi4>dat;\n\tfor(int i=0;i<num;i++)\n\t{\n\t\tll za,zb,zc,zd;\n\t\tscanf(\"%I64d%I64d%I64d%I64d\",&za,&zb,&zc,&zd);\n\t\tdat.push_back(inv(za,zb,zc,zd));\n\t}\n\tvector<pi6>vec;\n\tfor(int i=0;i<num;i++)\n\t{\n\t\tfor(int j=i+1;j<num;j++)\n\t\t{\n\t\t\tvec.push_back(make_pair(getsum(dat[i],dat[j]),getinc(dat[i],dat[j])));\n\t\t}\n\t}\n\tsort(vec.begin(),vec.end());\n\tpi4 nowsum=make_pair(make_pair(2000000000000000000LL,2000000000000000000LL),make_pair(2000000000000000000LL,2000000000000000000LL));\n\tvector<pii>now;\n\tll ret=0;\n\tfor(int i=0;i<vec.size();i++)\n\t{\n\t\tif(nowsum!=vec[i].first)\n\t\t{\n\t\t\tif(!now.empty())\n\t\t\t{\n\t\t\t\tret+=calc(now);\n\t\t\t\tret%=mod;\n\t\t\t}\n\t\t\tnow.clear();\n\t\t\tnow.push_back(vec[i].second);\n\t\t\tnowsum=vec[i].first;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnow.push_back(vec[i].second);\n\t\t}\n\t}\n\tret+=calc(now);\n\tret%=mod;\n\tprintf(\"%I64d\\n\",ret);\n}",
    "tags": [
      "combinatorics",
      "geometry"
    ],
    "rating": 3000
  },
  {
    "contest_id": "373",
    "index": "A",
    "title": "Collecting Beats is Fun",
    "statement": "Cucumber boy is fan of Kyubeat, a famous music game.\n\nKyubeat has $16$ panels for playing arranged in $4 × 4$ table. When a panel lights up, he has to press that panel.\n\nEach panel has a \\textbf{timing} to press (the preffered time when a player should press it), and Cucumber boy is able to press at most $k$ panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his \\textbf{two hands} in perfect timing, his challenge to press all the panels in perfect timing will fail.\n\nYou are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.",
    "tutorial": "First, you need to count the occurence of each number (1 through 9). If none of them are greater than 2 * k, Cucumber boy is able to press the panels in perfect timing. Complexity is O(1).",
    "code": "#include <cstdio>\n\nusing namespace std;\n\nint main()\n{\n    int k;\n    int cnt[10] = {0};\n    char mp[4][5];\n    \n    scanf(\"%d\", &k);\n    \n    for (int i = 0; i < 4; i++){\n        scanf(\"%s\", mp[i]);\n        for (int j = 0; j < 4; j++){\n            if (mp[i][j] == '.') continue;\n            else cnt[mp[i][j] - '0']++;\n        }\n    }\n    \n    for (int i = 1; i <= 9; i++)\n        if (cnt[i] > 2 * k) return (!printf(\"NO\\n\"));\n    \n    return (!printf(\"YES\\n\"));\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "373",
    "index": "B",
    "title": "Making Sequences is Fun",
    "statement": "We'll define $S(n)$ for positive integer $n$ as follows: the number of the $n$'s digits in the decimal base. For example, $S(893) = 3$, $S(114514) = 6$.\n\nYou want to make a consecutive integer sequence starting from number $m$ ($m, m + 1, ...$). But you need to pay $S(n)·k$ to add the number $n$ to the sequence.\n\nYou can spend a cost up to $w$, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.",
    "tutorial": "Naive simulation (subtracting S(i) * k from w while w >= 0) won't finish in 2 seconds. At first, these two facts will make it easier to solve the problem : 1. k doesn't matter for solving this problem, so you can simply divide w with k at the first point. 2. S(10^x) + S(10^x + 1) + ... + S(10^(x+1) - 1) = 9 * x * 10^x . There are many ways to solve this problem, and I'll show you 2 ways. Binary Search Let's define f(n) as \\sum_{k=1}^{n} S(n). This problem can be solved by finding largest x that satisfies f(x) - f(m - 1) <= w. If x satisfies the given inequation, also x - 1, x - 2, ... satisfies inequation since S(x) is always positive. So it can be solved by using binary search. By using fact2, you can quickly simulate the value of f(n). The answer can be rather large, so be careful not to cause overflow by too large upper bound. Overall complexity is O(log |upper_bound - lower_bound|). Cumulative Sums Let's think to speed up naive solutions that I've written at first. If you use fact 2, the number of simulation will reduce from O(|answer|) to O(1). Also, simulation will be much easier if you add S(1) + ... + S(m-1) to w. Please see my source code for further detail.",
    "code": "#include<stdio.h>\ntypedef long long ll;\nll get(ll a)\n{\n    ll ret=0;\n    ll now=1;\n    ll t=1;\n    for(;;)\n    {\n        if(now*10>a)\n        {\n            ret+=(a-now+1)*t;\n            break;\n        }\n        ret+=now*9*t;\n        now*=10;\n        t++;\n    }\n    return ret;\n}\nint main()\n{\n    ll gen,st,tim;\n    scanf(\"%I64d%I64d%I64d\",&gen,&st,&tim);\n    gen/=tim;\n    ll beg=st-1,end=20000000000000000LL;\n    for(;;)\n    {\n        ll med=(beg+end)/2+1;\n        if(get(med)-get(st-1)>gen)\n        {\n            end=med-1;\n        }\n        else\n        {\n            beg=med;\n        }\n        if(beg==end)\n        {\n            printf(\"%I64d\\n\",beg-st+1);\n            break;\n        }\n    }\n}",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "374",
    "index": "A",
    "title": "Inna and Pink Pony",
    "statement": "Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an $n × m$ chessboard, a very tasty candy and two numbers $a$ and $b$.\n\nDima put the chessboard in front of Inna and placed the candy in position $(i, j)$ on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types:\n\n- move the candy from position $(x, y)$ on the board to position $(x - a, y - b)$;\n- move the candy from position $(x, y)$ on the board to position $(x + a, y - b)$;\n- move the candy from position $(x, y)$ on the board to position $(x - a, y + b)$;\n- move the candy from position $(x, y)$ on the board to position $(x + a, y + b)$.\n\nNaturally, Dima doesn't allow to move the candy beyond the chessboard borders.\n\nInna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position $(i, j)$ to one of the chessboard corners. Help them cope with the task!",
    "tutorial": "Lets find a solution for shifting a candy from the position $(x_{1}, y_{1})$ into position $(x_{2}, y_{2})$. On each step we shift (increase or decrease) $x_{1}$ by $a$ and $y_{1}$ by $b$. It is not difficult to understand that if $|x_{2} - x_{1}|$ is not divisible by $a$ and $|y_{2} - y_{1}|$ is divisible by $b$ answer doesn't exist. We should also note that $|x_{2} - x_{1}| / a$ and $|y_{2} - y_{1}| / b$ Should be both even or odd as shifting is performed at a time for both values. We should also look up for a corner case when step dropes us out from the board. Now we can determine the way from $(x_{1}, y_{1})$ to $(x_{2}, y_{2})$ as $max(|x_{1} - x_{2}| / a, |y_{1} - y_{2}| / b)$. Lets calculate it for all corners and choose minimum or determine that the answer doesn't exist.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "374",
    "index": "B",
    "title": "Inna and Nine",
    "statement": "Inna loves digit $9$ very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number $a$, consisting of digits from $1$ to $9$.\n\nInna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals $9$ and replace them by a single digit $9$.\n\nFor instance, Inna can alter number $14545181$ like this: $14545181 → 1945181 → 194519 → 19919$. Also, she can use this method to transform number $14545181$ into number $19991$. Inna will not transform it into $149591$ as she can get numbers $19919$ and $19991$ which contain more digits nine.\n\nDima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.",
    "tutorial": "We can divide the task into subtasks because if two adjacent digits have sum none-9 the number transformation doesn't depends on other side relatively to the position between this two digits. It means we should divide our task into subtasks of kind: $x$ or $xyxyxyx...xyxy$ where $x + y = 9$. We should multiply all such answers because we are looking for the whole number of variants. For $x$ answer is 1. What should we do for $xyxyxy$? Let its length is $s$. Then if $s$ is even we simply receive $s / 2$ nines. If $s$ is odd one digit (any of them) will stay. Thus each sequence $xyxyxyxyx...xyxyxy$ with odd length $s$ increases the answer IN $s$ times.",
    "tags": [
      "combinatorics",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "374",
    "index": "C",
    "title": "Inna and Dima",
    "statement": "Inna and Dima bought a table of size $n × m$ in the shop. Each cell of the table contains a single letter: \"D\", \"I\", \"M\", \"A\".\n\nInna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows:\n\n- initially, Inna chooses some cell of the table where letter \"D\" is written;\n- then Inna can move to some side-adjacent table cell that contains letter \"I\"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter \"M\"; then she can go to a side-adjacent cell that contains letter \"A\". Then Inna assumes that she has gone through her sweetheart's name;\n- Inna's next move can be going to one of the side-adjacent table cells that contains letter \"D\" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter \"D\" she always goes to the letter \"I\", from the letter \"I\" she always goes the to letter \"M\", from the letter \"M\" she always goes to the letter \"A\", and from the letter \"A\" she always goes to the letter \"D\".\n\nDepending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.",
    "tutorial": "Our task is tranformed to the task of finding cycle or maximal way, but lets solve it without any graphs. Lets run dfs from each digit $D$, memorizing all already calculated tasks. If we come into the cell we have already been (in one of the previous $D$) than we should simply add the maximal way length to our current length. Way length is increased not in each cell but only when we come into $A$. If we come into the cell we have already been on current step (in our dfs running) this is the cycle and we should stop the algorithm. Don't forget to change the color of cell after droping from recursiong because you will receive \"false cycle\". Simply set the colour to current when come into the cell but decrease it before end of recursion for this cell.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "374",
    "index": "D",
    "title": "Inna and Sequence ",
    "statement": "Dima's spent much time thinking what present to give to Inna and gave her an empty sequence $w$. Now they want to fill sequence $w$ with numbers zero and one. For that, they decided to play an amusing game.\n\nBefore the game begins, Dima chooses $m$ integers $a_{1}, a_{2}, ..., a_{m}$ $(1 ≤ a_{1} < a_{2} < ... < a_{m})$. Then Inna and Dima start playing, that is, adding numbers to sequence $w$. Each new number they choose is added to the end of the sequence. At some moments of time Dima feels that the game is going to end too soon (and he wants to play with Inna as long as possible), so he hits a table hard with his fist. At that the $a_{1}$-th, $a_{2}$-th, $a_{3}$-th, $...$, $a_{k}$-th numbers from the beginning simultaneously fall out of the sequence (the sequence gets $k$ numbers less). Here $k$ is such maximum number that value $a_{k}$ doesn't exceed the current length of the sequence. If number $a_{1}$ is larger than the current length of $w$, then nothing falls out of the sequence.\n\nYou are given the chronological sequence of events in the game. Each event is either adding a number to the end of sequence $w$ or Dima's hit on the table. Calculate the sequence $w$ after all these events happen.",
    "tutorial": "Lets note that not more than $n$ numbers, thus it will be not more than $n$ dropings. We will run this process using data structure Segment Tree (you can use another structures). Lets calculate the number of numbers in current segment. When the number is added we should simply go down from the root to the leaf and increase value for each segment on the way by 1. Deletetion - vice versa. If there is enough numbers in the left subtree we should go into the right one, othervise - into the left one. Don't forget to shift the $a_{i}$ position by decreasing on $i$ as all numbers are droped immidiately. And don't forget to break the cycle as soon as you reach first $a_{i}$ such that there is no number to be droped out from it.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "374",
    "index": "E",
    "title": "Inna and Babies",
    "statement": "Inna, Dima and Sereja are in one room together. It's cold outside, so Sereja suggested to play a board game called \"Babies\".\n\nThe babies playing board is an infinite plane containing $n$ blue babies and $m$ red ones. Each baby is a segment that grows in time. At time moment $t$ the blue baby $(x, y)$ is a blue segment with ends at points $(x - t, y + t)$, $(x + t, y - t)$. Similarly, at time $t$ the red baby $(x, y)$ is a red segment with ends at points $(x + t, y + t)$, $(x - t, y - t)$ of the plane. Initially, at time $t = 0$ all babies are points on the plane.\n\nThe goal of the game is to find the first integer moment of time when the plane contains a rectangle of a non-zero area which sides are fully covered by some babies. A side may be covered by multiple babies. More formally, each point of each side of the rectangle should be covered by at least one baby of any color. At that, you must assume that the babies are closed segments, that is, they contain their endpoints.\n\nYou are given the positions of all babies — help Inna and Dima to find the required moment of time.",
    "tutorial": "We will make the binary search to find the answer. For each time let's generate our segments and rotate them to transform them into horizontal and verticle. We can use transformation $(x, y)$ to $(x + y, x - y)$. Don't forget to make the union of all segments which were at the one diagonal and have an intersection. You should sort all segments of one type and iterate through them updating the size of the segment. Now we should only determine if there is at least one rectangle. For example we can iterate each verticle segment updating the set of all horizontal which begin not later than our verticle. For each verticle (the left one) we should iterate the right verticle and now calculate the set of horizontal which not only begin not later than the left verticle but also don't end earlier than the right one. Now we should only determine is ther is two or more horizontal segments from the set which satisfy also y-conditions for current vertical.",
    "tags": [
      "binary search",
      "data structures",
      "dsu",
      "geometry",
      "implementation"
    ],
    "rating": 2600
  },
  {
    "contest_id": "375",
    "index": "A",
    "title": "Divisible by Seven",
    "statement": "You have number $a$, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.\n\nNumber $a$ doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.",
    "tutorial": "O(n): Because permutation of 1, 6, 8, 9 can form integers that mod 7 equals 0, 1, 2, 3, 4, 5, 6. So you can construct answer like this: nonzero digits + a permutation of 1, 6, 8, 9 + zeros.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "375",
    "index": "B",
    "title": "Maximum Submatrix 2",
    "statement": "You are given a matrix consisting of digits zero and one, its size is $n × m$. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations?\n\nLet's assume that the rows of matrix $a$ are numbered from 1 to $n$ from top to bottom and the columns are numbered from 1 to $m$ from left to right. A matrix cell on the intersection of the $i$-th row and the $j$-th column can be represented as $(i, j)$. Formally, a submatrix of matrix $a$ is a group of four integers $d, u, l, r$ $(1 ≤ d ≤ u ≤ n; 1 ≤ l ≤ r ≤ m)$. We will assume that the submatrix contains cells $(i, j)$ $(d ≤ i ≤ u; l ≤ j ≤ r)$. The area of the submatrix is the number of cells it contains.",
    "tutorial": "O(n*m): #We can get right[i][j] by O(n*m) dp. Let right[i][j] = how many continuous 1s is on cell (j, i)'s right. Let answer = 0 For all column i Sort right[i] #You can use O(n) sorting algorithm For j in [1..n] If right[i][j]*(n-j+1) > answer then answer = right[i][j]*(n-j+1)",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "375",
    "index": "C",
    "title": "Circling Round Treasures",
    "statement": "You have a map as a rectangle table. Each cell of the table is either an obstacle, or a treasure with a certain price, or a bomb, or an empty cell. Your initial position is also given to you.\n\nYou can go from one cell of the map to a side-adjacent one. At that, you are not allowed to go beyond the borders of the map, enter the cells with treasures, obstacles and bombs. To pick the treasures, you need to build a closed path (starting and ending in the starting cell). The closed path mustn't contain any cells with bombs inside. Let's assume that the sum of the treasures' values that are located inside the closed path equals $v$, and besides, you've made $k$ single moves (from one cell to another) while you were going through the path, then such path brings you the profit of $v - k$ rubles.\n\nYour task is to build a closed path that doesn't contain any bombs and brings maximum profit.\n\nNote that the path can have self-intersections. In order to determine if a cell lies inside a path or not, use the following algorithm:\n\n- Assume that the table cells are points on the plane (the table cell on the intersection of the $i$-th column and the $j$-th row is point $(i, j)$). And the given path is a closed polyline that goes through these points.\n- You need to find out if the point $p$ of the table that is not crossed by the polyline lies inside the polyline.\n- Let's draw a ray that starts from point $p$ and does not intersect other points of the table (such ray must exist).\n- Let's count the number of segments of the polyline that intersect the painted ray. If this number is odd, we assume that point $p$ (and consequently, the table cell) lie inside the polyline (path). Otherwise, we assume that it lies outside.",
    "tutorial": "#T = number of treasures, B = number of booms O(n*m*2^(T+B)): #State(i, j, ts, bs) means: # 1. You are at cell (i, j) # 2. If the i-th bit of ts is 0 i-th treasure cross even edges of current path, otherwise odd edges. # 3. If the i-th bit of bs is 0 i-th boom cross even edges of current path, otherwise odd edges. Let dis[i][j][ts][bs] = min step to go to reach state (i, j, ts, bs). Then we can use bfs algorithm to calculate dis. About the bfs algorithm: We know dis[Si][Sj][0][0] = 0. For state(i, j, bs, ts) we can goto cell (i-1, j), (i+1, j), (i, j-1) and (i, j+1). Of course, we cannot go out of the map or go into a trap. So suppose we go from cell (i, j) to cell (ni, nj) and the new state is (ni, nj, nts, nbs). We can see if a treasure is crossing through the edge (i, j) - (ni, nj), if i-th treasure is, then the i-th bit of nts will be 1 xor i-th bit of ts, otherwise, the i-th bit of nts and ts will be same. The same for nbs. We can reach state (ni, nj, nts, nbs) from (i, j, ts, bs) in one step, so we just need to start bfs from state(Si, Sj, 0, 0) to get the min dis of all state. The answer will be max{value(ts) - dis[Si][Sj][ts][0]}",
    "code": "import java.util.LinkedList;\nimport java.util.Queue;\nimport java.util.Scanner;\n\npublic class Div1C {\n\tpublic static void main(String[] args) {\n\t\tScanner in = new Scanner(System.in);\n\t\tint n = in.nextInt(), m = in.nextInt();\n\t\tchar[][] g = new char[n][];\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tg[i] = in.next().toCharArray();\n\t\tPoint start = null;\n\t\tint t = 0, b = 0;\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tif (Character.isDigit(g[i][j])) {\n\t\t\t\t\tt = Math.max(t, (int) (g[i][j] - '0'));\n\t\t\t\t} else if (g[i][j] == 'B') {\n\t\t\t\t\tb++;\n\t\t\t\t} else if (g[i][j] == 'S') {\n\t\t\t\t\tstart = new Point(i, j);\n\t\t\t\t}\n\t\t\t}\n\t\tPoint[] treasure = new Point[t];\n\t\tint[] value = new int[t];\n\t\tPoint[] boom = new Point[b];\n\t\tfor (int i = 0, bi = 0; i < n; i++)\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tif (Character.isDigit(g[i][j])) {\n\t\t\t\t\tint ti = g[i][j] - '1';\n\t\t\t\t\ttreasure[ti] = new Point(i, j);\n\t\t\t\t} else if (g[i][j] == 'B') {\n\t\t\t\t\tboom[bi++] = new Point(i, j);\n\t\t\t\t}\n\t\t\t}\n\t\tfor (int ti = 0; ti < t; ti++)\n\t\t\tvalue[ti] = in.nextInt();\n\t\tint[][][][] cost = new int[n][m][1 << t][1 << b];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tfor (int k = 0; k < (1 << t); k++) {\n\t\t\t\t\tfor (int l = 0; l < (1 << b); l++) {\n\t\t\t\t\t\tcost[i][j][k][l] = 19930309;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tQueue<State> queue = new LinkedList<State>();\n\t\tState state = new State(start, 0, 0);\n\t\tcost[state.p.x][state.p.y][state.ts][state.bs] = 0;\n\t\tqueue.add(state);\n\t\twhile (!queue.isEmpty()) {\n\t\t\tstate = queue.remove();\n\t\t\tfinal int[] dx = new int[] { 0, 0, 1, -1 };\n\t\t\tfinal int[] dy = new int[] { -1, 1, 0, 0 };\n\t\t\tfor (int d = 0; d < 4; d++) {\n\t\t\t\tState nstate = new State(new Point(state.p.x + dx[d], state.p.y\n\t\t\t\t\t\t+ dy[d]), state.ts, state.bs);\n\t\t\t\tif (nstate.p.x >= 0 && nstate.p.x < n && nstate.p.y >= 0\n\t\t\t\t\t\t&& nstate.p.y < m\n\t\t\t\t\t\t&& !Character.isDigit(g[nstate.p.x][nstate.p.y])\n\t\t\t\t\t\t&& g[nstate.p.x][nstate.p.y] != '#'\n\t\t\t\t\t\t&& g[nstate.p.x][nstate.p.y] != 'B') {\n\t\t\t\t\tfor (int i = 0; i < t; i++) {\n\t\t\t\t\t\tif (cross(treasure[i], state.p, nstate.p)) {\n\t\t\t\t\t\t\tnstate.ts ^= 1 << i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (int i = 0; i < b; i++) {\n\t\t\t\t\t\tif (cross(boom[i], state.p, nstate.p)) {\n\t\t\t\t\t\t\tnstate.bs ^= 1 << i;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (cost[nstate.p.x][nstate.p.y][nstate.ts][nstate.bs] > cost[state.p.x][state.p.y][state.ts][state.bs] + 1) {\n\t\t\t\t\t\tcost[nstate.p.x][nstate.p.y][nstate.ts][nstate.bs] = cost[state.p.x][state.p.y][state.ts][state.bs] + 1;\n\t\t\t\t\t\tqueue.add(nstate);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint answer = 0;\n\t\tfor (int ts = 0; ts < (1 << t); ts++) {\n\t\t\tint get = 0;\n\t\t\tfor (int i = 0; i < t; i++)\n\t\t\t\tif ((ts & (1 << i)) != 0) {\n\t\t\t\t\tget += value[i];\n\t\t\t\t}\n\t\t\tget -= cost[start.x][start.y][ts][0];\n\t\t\tanswer = Math.max(answer, get);\n\t\t}\n\t\tSystem.out.println(answer);\n\t}\n\n\tprivate static boolean cross(Point p, Point l1, Point l2) {\n\t\treturn (l1.y > p.y) != (l2.y > p.y)\n\t\t\t\t&& p.x * (l2.y - l1.y) * (l2.y - l1.y) < (l2.x - l1.x)\n\t\t\t\t\t\t* (p.y - l1.y) * (l2.y - l1.y) + l1.x * (l2.y - l1.y)\n\t\t\t\t\t\t* (l2.y - l1.y);\n\t}\n}\n\nclass Point {\n\tpublic int x, y;\n\n\tpublic Point(int x, int y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n}\n\nclass State {\n\tPoint p;\n\tpublic int ts, bs;\n\n\tpublic State(Point p, int ts, int bs) {\n\t\tthis.p = p;\n\t\tthis.ts = ts;\n\t\tthis.bs = bs;\n\t}\n}",
    "tags": [
      "bitmasks",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "375",
    "index": "D",
    "title": "Tree and Queries",
    "statement": "You have a rooted tree consisting of $n$ vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to $n$. Then we represent the color of vertex $v$ as $c_{v}$. The tree root is a vertex with number 1.\n\nIn this problem you need to answer to $m$ queries. Each query is described by two integers $v_{j}, k_{j}$. The answer to query $v_{j}, k_{j}$ is the number of such colors of vertices $x$, that the subtree of vertex $v_{j}$ contains at least $k_{j}$ vertices of color $x$.\n\nYou can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory).",
    "tutorial": "O(nlogn) or O(nlog^2n): Use binary search tree and merge them by rank. Use binary search tree that supports O(n) merging to get O(nlogn) solution. O(n*sqrt(n)): Dfs the tree to transform the problem to: Given a[i], query [l,r] k. To solve this problem: Build sqrt(n) bucket, put query [l,r] into (l/sqrt(n)+1)-th bucket For each bucket For thoese queries whose r is also in the bucket (l/sqrt(n) equals r/sqrt(n)), a brute-froce O(n) solution exists. For thoes queries whose r is not in the same bucket, let we sort them by l. We will get l[i[1]]<=l[i[2]]<=..<=l[i[k]]<=r[i[k]]<=r[i[k-1]]<=..<=r[i[1]](do not forget we get l[] and r[] by dfs the tree!). Solving them can be done in O(n) too. Since we only have O(sqrt(n)) buckets, the total time is O(n*sqrt(n)).",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "375",
    "index": "E",
    "title": "Red and Black Tree",
    "statement": "You have a weighted tree, consisting of $n$ vertices. Each vertex is either painted black or is painted red. A red and black tree is called beautiful, if for any its vertex we can find a black vertex at distance at most $x$.\n\nThe distance between two nodes is the shortest path between them.\n\nYou have a red and black tree. Your task is to make it beautiful in the minimum number of color swap operations. In one color swap operation, you can choose two vertices of different colors and paint each of them the other color. In other words, if you choose a red vertex $p$ and a black vertex $q$, then in one operation you are allowed to paint $p$ black and paint $q$ red.\n\nPrint the minimum number of required actions.",
    "tutorial": "This problem can be solved by integer programming: min sum{c[i]*x[i]} subject to sum{A[i][j]*x[j]} >= 1 for all i sum{x[i]} = R x[i] = 0 or 1 for all i where c[i] = 1 if node i is black, 0 otherwise A[i][j] = 1 if distance between i and j is no greater than X, 0 otherwise R = number of red nodes. As it is known, integer programming is NP-hard. Thus, this cannot be the solution. But we can prove the following linear programing's solution is same as the integer programming's. min sum{c[i]*x[i]} subject to sum{A[i][j]*x[j]} >= 1 for all i sum{x[i]} <= R x[i] >= 0 for all i where c[i] = 1 if node i is black, 0 otherwise A[i][j] = 1 if distance between i and j is no greater than X, 0 otherwise R = number of red nodes. And the known fastest algorithm to solve linear programming is O(n^3.5). But in fact due to the property of this problem, using simplex algorithm to solve linear programming is even faster. I think it can be O(n^3), but I have no proof. So just use simplex to solve the linear programming problem above. The meaning of the integer programming: We use x[i] to stand whether node i is red or not. So we have: x[i] = 0 or 1 for all i There is a beautiful tree, for each node, exists an red node whose distance to this node is no more than X. So we have: sum{A[i][j]*x[j]} >= 1 for all i There are only R red node. So we have: sum{x[i]} = R And we need to minimize the swap number, and in fact the swap number equals to number of nodes that changed from black to red. So we need to minimize: sum{c[i]*x[i]} After changing it to linear programming: Firstly, it is obvious that the solution of the linear programming will not be worse than integer programming, because integer programming has stronger constraint. So we only need to show the solution of the linear programming will not be better than integer programming. To prove this, we need to show for an optimal solution, there will be an solution which is as good as it and all x[i] is either 0 or 1. 1. Because for \"sum{A[i][j]*x[j]} >= 1 for all i\", there is no need to make some x[i] > 1. It is obvious that if the solution has some x[i] > 1, we can increase x[i] for nodes that are red in the first place, so that there will not be any x[i] > 1 and this solution is as good as the old one. 2. We need to prove in an optimal solution, making some x[i] not being an integer will not get btter solution. It is really hard to decribe it. So just leave you a hint: use the property of trees to prove and consider leaves of the tree.",
    "code": "#include <vector>\n#include <algorithm>\n#include <cstdio>\nusing namespace std;\n\n#define lp for(;;)\n#define repf(i,a,b)\n#define ft(i,a,b) for (int i=(a);i<=(b);++i)\n#define rep(i,n) for (int i=0;i<(n);++i)\n#define rtn return\n#define pb push_back\n#define mp make_pair\n#define sz(x) (int((x).size()))\ntypedef double db;\ntypedef vector<int> vi;\ndb inf=1e+10;\ndb eps=1e-10;\ninline int sgn(const db& x){rtn (x>+eps)-(x<-eps);}\n\nconst int MAXN=500;\nconst int MAXM=501;\nint n,m;\ndb A[MAXM+1][MAXN+1],X[MAXN];\nint basis[MAXM+1],out[MAXN+1];\n\nvoid pivot(int a,int b)\n{\n\tft(i,0,m) if (i!=a&&sgn(A[i][b])) ft(j,0,n) if (j!=b) A[i][j]-=A[a][j]*A[i][b]/A[a][b];\n\tft(j,0,n) if (j!=b) A[a][j]/=A[a][b];\n\tft(i,0,m) if (i!=a) A[i][b]/=-A[a][b];\n\tA[a][b]=1/A[a][b];\n\tswap(basis[a],out[b]);\n}\ndb simplex()\n{\n\trep(j,n) A[0][j]=-A[0][j];\n\tft(i,0,m) basis[i]=-i;\n\tft(j,0,n) out[j]=j;\n\tlp\n\t{\n\t\tint ii=1,jj=0;\n\t\tft(i,1,m) if (mp(A[i][n],basis[i])<mp(A[ii][n],basis[ii])) ii=i;\n\t\tif (A[ii][n]>=0) break;\n\t\trep(j,n) if (A[ii][j]<A[ii][jj]) jj=j;\n\t\tif (A[ii][jj]>=0) rtn -inf;\n\t\tpivot(ii,jj);\n\t}\n\tlp\n\t{\n\t\tint ii=1,jj=0;\n\t\trep(j,n) if (mp(A[0][j],out[j])<mp(A[0][jj],out[jj])) jj=j;\n\t\tif (A[0][jj]>=0) break;\n\t\tft(i,1,m)\n\t\t\tif (A[i][jj]>0&&(A[ii][jj]<=0||mp(A[i][n]/A[i][jj],basis[i])<mp(A[ii][n]/A[ii][jj],basis[ii])))\n\t\t\t\tii=i;\n\t\tif (A[ii][jj]<=0) rtn +inf;\n\t\tpivot(ii,jj);\n\t}\n\trep(j,n) X[j]=0;\n\tft(i,1,m) if (basis[i]>=0) X[basis[i]]=A[i][n];\n\trtn A[0][n];\n}\n\nint d;\nvi adj[500];\nvi wei[500];\nvoid dfs(db A[],int u,int p,int d)\n{\n\tif (d>=0)\n\t{\n\t\tA[u]--;\n\t\trep(i,sz(adj[u]))\n\t\t{\n\t\t\tint v=adj[u][i];\n\t\t\tif (v!=p)\n\t\t\t{\n\t\t\t\tdfs(A,v,u,d-wei[u][i]);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main()\n{\n\tscanf(\"%d%d\",&n,&d);\n\tint ttl=0;\n\trep(i,n)\n\t{\n\t\tint ti;\n\t\tscanf(\"%d\",&ti),A[0][i]=ti-1,ttl+=ti;\n\t}\n\trep(i,n-1)\n\t{\n\t\tint u,v,w;\n\t\tscanf(\"%d%d%d\",&u,&v,&w),--u,--v;\n\t\tadj[u].pb(v),adj[v].pb(u);\n\t\twei[u].pb(w),wei[v].pb(w);\n\t}\n\tA[0][n]=0;\n\trep(i,n)\n\t{\n\t\tdfs(A[i+1],i,-1,d);\n\t\tA[i+1][n]=-1;\n\t}\n\trep(i,n) A[n+1][i]=1;\n\tA[n+1][n]=ttl;\n\tm=n+1;\n\tdb get=simplex();\n\tint ans;\n\tif (get==-inf) ans=-1;\n\telse ans=-get+0.5;\n\tprintf(\"%d\\n\",ans);\n}",
    "tags": [
      "dp",
      "implementation",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "376",
    "index": "A",
    "title": "Lever",
    "statement": "You have a description of a lever as string $s$. We'll represent the string length as record $|s|$, then the lever looks as a horizontal bar with weights of length $|s| - 1$ with exactly one pivot. We will assume that the bar is a segment on the $Ox$ axis between points $0$ and $|s| - 1$.\n\nThe decoding of the lever description is given below.\n\n- If the $i$-th character of the string equals \"^\", that means that at coordinate $i$ there is the pivot under the bar.\n- If the $i$-th character of the string equals \"=\", that means that at coordinate $i$ there is nothing lying on the bar.\n- If the $i$-th character of the string equals digit $c$ (1-9), that means that at coordinate $i$ there is a weight of mass $c$ on the bar.\n\nYour task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.",
    "tutorial": "O(n): Let mid = position of ^ Let value(x) = x if x is a digit , 0 otherwise. Let sum = value(i-th char)*(i-mid) If sum = 0 then answer = balance Else if sum<0 then answer = left Else answer = right",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "376",
    "index": "B",
    "title": "I.O.U.",
    "statement": "Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.\n\nThis task is a generalisation of a described example. Imagine that your group of friends has $n$ people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.",
    "tutorial": "O(n^4): Let f[i][j] = how many money i owes j #It can be proved we only need to loop n times. Loop n times do: For i,j,k in [1..n] If f[i][j]>0 and f[j][k]>0 then Let  delta = min (f[i][j], f[j][k]) Decrease f[i][j] and f[j][k] by delta Increase f[i][k] by deltaAnswer will be sum{f[i][j]} O(m+n): Let owe[i] = 0 for all i #Suppose there is an agnecy to help people with debts. #If you owe someone, you give money to the agency. #If someone owes you, you get money from the agency. For each ai, bi, ci Increase owe[ai] by ci Decrease owe[bi] by ciAnsewr will be sum{owe[i]|owe[i]>0}",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "377",
    "index": "A",
    "title": "Maze",
    "statement": "Pavel loves grid mazes. A grid maze is an $n × m$ rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.\n\nPavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly $k$ empty cells into walls so that all the remaining cells still formed a connected area. Help him.",
    "tutorial": "Start BFS or DFS from any free cell. As the maze is connected, this search will visit all $s$ free cells. But we can stop the search when it visits $s - k$ free cells. It's obvious that these $s - k$ cells are connected to each other. Remaining $k$ cells can be transformed into the walls. Solutions which every move transform the cell which has the minimal number of neighbours passed pretests. However, it's wrong. Here is the counter-test: Top-left cell has no more neighbours than any other cell but we cannot transform it into the wall.",
    "tags": [
      "dfs and similar"
    ],
    "rating": 1600
  },
  {
    "contest_id": "377",
    "index": "B",
    "title": "Preparing for the Contest",
    "statement": "Soon there will be held the world's largest programming contest, but the testing system still has $m$ bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has $n$ students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the $i$-th student wants to get $c_{i}$ 'passes' in his subjects (regardless of the volume of his work).\n\nBugs, like students, are not the same: every bug is characterized by complexity $a_{j}$, and every student has the level of his abilities $b_{i}$. Student $i$ can fix a bug $j$ only if the level of his abilities is not less than the complexity of the bug: $b_{i} ≥ a_{j}$, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously.\n\nThe university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than $s$ passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.",
    "tutorial": "It's obvious that the time needed to fix all bugs is the monotonic function: if we can do it for some time, we can do it for greater time. So we can use binary search in these problem. We should learn how to check if some time $t$ is enough. At first sort all bugs by their complexity and all students by their skills. Let's consider the hardest bug. Who can fix it? It can be fixed by student whose skills is not less that this bug's complexity. Push all such students into the priority queue (sorted by students' price) and pop the cheapest student. As we check time $t$, this student must fix $t$ hardest bugs (he definitely can do it). Save that information and go to the next bug which has not been fixed yet. Again push all students which can fix it to the priority queue and pop the cheapest one. And so on. If at some moment priority queue is empty, time $t$ is not enough. If we spent too much 'money' - it's not enough as well. Otherwise we get the correct schedule.",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "377",
    "index": "C",
    "title": "Captains Mode",
    "statement": "Kostya is a progamer specializing in the discipline of Dota 2. Valve Corporation, the developer of this game, has recently released a new patch which turned the balance of the game upside down. Kostya, as the captain of the team, realizes that the greatest responsibility lies on him, so he wants to resort to the analysis of innovations patch from the mathematical point of view to choose the best heroes for his team in every game.\n\nA Dota 2 match involves two teams, each of them must choose some heroes that the players of the team are going to play for, and it is forbidden to choose the same hero several times, even in different teams. In large electronic sports competitions where Kostya's team is going to participate, the matches are held in the Captains Mode. In this mode the captains select the heroes by making one of two possible actions in a certain, predetermined order: pick or ban.\n\n- To pick a hero for the team. After the captain picks, the picked hero goes to his team (later one of a team members will play it) and can no longer be selected by any of the teams.\n- To ban a hero. After the ban the hero is not sent to any of the teams, but it still can no longer be selected by any of the teams.\n\nThe team captain may miss a pick or a ban. If he misses a pick, a random hero is added to his team from those that were available at that moment, and if he misses a ban, no hero is banned, as if there was no ban.\n\nKostya has already identified the strength of all the heroes based on the new patch fixes. Of course, Kostya knows the order of picks and bans. The strength of a team is the sum of the strengths of the team's heroes and both teams that participate in the match seek to maximize the difference in strengths in their favor. Help Kostya determine what team, the first one or the second one, has advantage in the match, and how large the advantage is.",
    "tutorial": "There are some observations that do the problem very simple. The first one is that we always should pick the strongest hero. But we cannot say something similar about the bans - in different situations different bans are the best. But the most important observation is that we should consider only $m$ strongest heroes. Indeed, in every game where only strongest heroes are picked, no hero except $m$ strongest can be picked. That's why we don't need to ban them and therefore we don't need to consider them. So now we have only 20 heroes. It means we can solve the problem using the dynamic programming with bitmasks: $dp_{mask}$ will be the difference between the teams' strengths when only those heroes are picked or banned whose bits are set to 1 in the $mask$. At every state we try to pick or ban every available hero and go to the other state. The simpliest way to implement it is the recursion with memoization. The answer will be stored in $dp_{2^{m} - 1}$. Unfortunately, we couldn't estimate the real complexity of this problem (despite it has the simple solution, this solution is not so easy to think of - standard 1500 points for problem C would be better) and set too big TL (many solutions written in C++ whose complexity is $m^{2} \\cdot 2^{m}$ passed - we should have been set TL to 1 second or even to 0.75 seconds). So if you solved it in $m^{2} \\cdot 2^{m}$, you may assume that you're just lucky and your correct verdict is Time Limit Exceeded. Why it can be solved in $m \\cdot 2^{m}$? There is no point of missing a ban - if we ban the weakest hero, nothing will change since the weakest hero won't be picked. Also this problem has weak pretests so you could hack solutions without bitmasks with almost any big random test.",
    "tags": [
      "bitmasks",
      "dp",
      "games"
    ],
    "rating": 2200
  },
  {
    "contest_id": "377",
    "index": "D",
    "title": "Developing Game",
    "statement": "Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired $n$ workers of staff. Now he wants to pick $n$ workers from the staff who will be directly responsible for developing a game.\n\nEach worker has a certain skill level $v_{i}$. Besides, each worker doesn't want to work with the one whose skill is very different. In other words, the $i$-th worker won't work with those whose skill is less than $l_{i}$, and with those whose skill is more than $r_{i}$.\n\nPavel understands that the game of his dream isn't too hard to develop, so the worker with any skill will be equally useful. That's why he wants to pick a team of the maximum possible size. Help him pick such team.",
    "tutorial": "Let's note that every answer is characterized with two numbers $L$ and $R$ so that $max{l_{i}}  \\le  L$, $R  \\le  min{r_{i}}$, and $L  \\le  v_{i}  \\le  R$. If we know $L$ and $R$, we can check every person and choose those who satisfies the conditions above. Let's imagine a plane with the coordinate axes: one of the axes will be $L$, and the other will be $R$. If the point $(L, R)$ on this plane is the optimal answer, people included in this answer for sure satisfy the conditions $l_{i}  \\le  L  \\le  v_{i}$ and $v_{i}  \\le  R  \\le  r_{i}$. These conditions specify the rectangle on the plane. Since we should find the maximum number of people, we should find such point $(L, R)$ that it is inside the maximum number of the specified rectangles. Now it's the standard problem that can be solved using the scanline through one axis and the segment tree built on the other axis. The hardest part is to reduce the original problem to it.",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "377",
    "index": "E",
    "title": "Cookie Clicker",
    "statement": "Kostya is playing the computer game Cookie Clicker. The goal of this game is to gather cookies. You can get cookies using different buildings: you can just click a special field on the screen and get the cookies for the clicks, you can buy a cookie factory, an alchemy lab, a time machine and it all will bring lots and lots of cookies.\n\nAt the beginning of the game (time 0), Kostya has 0 cookies and no buildings. He has $n$ available buildings to choose from: the $i$-th building is worth $c_{i}$ cookies and when it's built it brings $v_{i}$ cookies at the end of each second. Also, to make the game more interesting to play, Kostya decided to add a limit: at each moment of time, he can use only one building. Of course, he can change the active building each second at his discretion.\n\nIt's important that Kostya is playing a version of the game where he can buy new buildings and change active building only at time moments that are multiples of one second. Kostya can buy new building and use it at the same time. If Kostya starts to use a building at the time moment $t$, he can get the first profit from it only at the time moment $t + 1$.\n\nKostya wants to earn at least $s$ cookies as quickly as possible. Determine the number of seconds he needs to do that.",
    "tutorial": "First of all, throw away the buildings which cannot be used in any optimal answer: for each $v_{i}$ remain only one building that has speed equal to $v_{i}$ and minimal $c_{i}$. Also throw away all buildings whose speed is less than the speed of the fastest building which has $c_{i} = 0$. It's fairly obvious that at any time we should use the fastest building. And if some building is used in the optimal answer, it should be bought and used immediately when we have enough money (I will use the word 'money' instead of 'cookies'). Let's imagine the plane $(x, y)$ where $x$ axis stands for the time and $y$ axis stands for the money. We will maintain the graph of the function $y = f(x)$ - 'maximal number of money that can be obtained at the time $x$' and process the buildings one by one, changing the graph. This function is the union of the line segments with the slopes equal to $v_{i}$, and each of these line segments is active on a certain segment $[x_{li}, x_{ri}]$ of the axis $x$. For example, at the beginning the graph is just the line $y = v_{1}x$, where $v_{1}$ is the speed of building that can be bought for 0 units of money. Let the next building's price is $c_{2}$. Find the minimal point $x_{02}$ where value of our function is greater or equal to $y = f(x_{02})  \\ge  c_{2}$ and buy this building at the moment $x_{02}$. Then we should make the line $y = y_{02} + v_{2}x$ where $y_{02} = f(x_{02}) - c_{2}$ is the amount of money remaining after the purchase. Now we have two lines. Till some moment the first line is better (not till $x_{02}$, maybe later), but as $v_{2} > v_{1}$ there exists a moment of time (it's $ceil(x_{12})$ where $x_{12}$ is the $x$-coordinate of the lines' intersection) when the second line becomes better. Now we know the segments where a particular line is better than the others. Continue add all buildings to the graph this way. Line segments should be stored in stack, as in all problems with convex hull, and every step remove unnecessary line segments from the stack (these are the lines those position in the stack is after the line which has an intersection with the currently added line). After we process all buildings, we use our graph to find the minimal time when we have $S$ untis of money. If we also should say which building we must use, we can store for any line segment its 'parent' - the line segment which was active when the current one was bought. With such parent array it's not hard to restore the sequence of buildings in the answer. We removed this part from the problem to make it a bit easier.",
    "tags": [
      "dp",
      "geometry"
    ],
    "rating": 2800
  },
  {
    "contest_id": "378",
    "index": "A",
    "title": "Playing with Dice",
    "statement": "Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.\n\nThe first player wrote number $a$, the second player wrote number $b$. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?",
    "tutorial": "Make three counters: for wins of both players and for a draw. Iterate over all six ways how they can throw a dice. For each way determine who wins or there is a draw and increment the corresponding counter.",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "378",
    "index": "B",
    "title": "Semifinals",
    "statement": "Two semifinals have just been in the running tournament. Each semifinal had $n$ participants. There are $n$ participants advancing to the finals, they are chosen as follows: from each semifinal, we choose $k$ people ($0 ≤ 2k ≤ n$) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top $k$ in their semifinal but got to the $n - 2k$ of the best among the others.\n\nThe tournament organizers hasn't yet determined the $k$ value, so the participants want to know who else has any chance to get to the finals and who can go home.",
    "tutorial": "You can think a bit and understand that you should consider only corner cases: $k = 0$ and $k={\\frac{n}{2}}$. All other cases will be something between them. If $k = 0$, we should choose $n$ biggest elements from two sorted lists, one of the ways is to use two pointers method. And if $k={\\frac{n}{2}}$, we just mark first $\\frac{n t}{2}$ people in each list.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "379",
    "index": "A",
    "title": "New Year Candles",
    "statement": "Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.\n\nVasily has $a$ candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make $b$ went out candles into a new candle. As a result, this new candle can be used like any other new candle.\n\nNow Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.",
    "tutorial": "Let $cur_{a}$ amount of new candles, $cur_{b}$ - amount of burnt out. Initially $cur_{a} = a$, $cur_{b} = 0$, after burning all $cur_{a}$ new candles, amount of hours incremented by $cur_{a}$ and $cur_{b} + = cur_{a}$, lets make all burnt out candles into new $cur_{a} = cur_{b} / b$ $c u r_{b}=c u r_{b}\\;\\;\\mathrm{mod}\\;b$, repeat this algorithm until we can make at least one new candle. #### B: 379B - New Year Present If wallet contains more then one coin, then between orders to \"put a coin\" we can orders to move to adjacent wallet then back. Since for each orders to \"put a coin\" we spend at most 2 other orders, number of total orders for maximum test equals $300 * 300 * 3 = 270000$ it less then $10^{6}$.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "379",
    "index": "C",
    "title": "New Year Ratings Change",
    "statement": "One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.\n\nThere are $n$ users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user $i$ wants to get at least $a_{i}$ rating units as a present.\n\nThe X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.\n\nHelp site X cope with the challenging task of rating distribution. Find the optimal distribution.",
    "tutorial": "We can to sort ratings in nondecrease order, then iterate by them we can keep minimal rating not used before. If $a_{i} > cur$, $i$'s user recieve $a_{i}$ of rating and $cur = a_{i} + 1$, else $a_{i}  \\le  cur$ then $i$'s user recieve $cur$ of rating and $cur$ increased by one.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "379",
    "index": "D",
    "title": "New Year Letter",
    "statement": "Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).\n\nVasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, $s_{1}$ anf $s_{2}$, consisting of uppercase English letters. Then the boy makes string $s_{k}$, using a recurrent equation $s_{n} = s_{n - 2} + s_{n - 1}$, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string $s_{k}$ on a piece of paper, puts it in the envelope and sends in to Santa.\n\nVasya is absolutely sure that Santa will bring him the best present if the resulting string $s_{k}$ has exactly $x$ occurrences of substring AC (the short-cut reminds him оf accepted problems). Besides, Vasya decided that string $s_{1}$ should have length $n$, and string $s_{2}$ should have length $m$. Vasya hasn't decided anything else.\n\nAt the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, $s_{1}$ and $s_{2}$ in the required manner. Help Vasya.",
    "tutorial": "We can't fairly calculate $s_{k}$ because of length of this string which can be very large. But note that whole string not need, we just need number of $AC$ substrings, first and last letter. That help us to easy calculate number $AC$ substrings for any $s_{k}$ for some $s_{1}$, $s_{2}$. Let's iterate through $s_{1}$, $s_{2}$ using alphabet of $A$, $C$, and any other letter. We need just first and last letter and number of $AC$. Using some $s_{1}$, $s_{2}$ we can calculate $s_{k}$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "379",
    "index": "E",
    "title": "New Year Tree Decorations",
    "statement": "Due to atheistic Soviet past, Christmas wasn't officially celebrated in Russia for most of the twentieth century. As a result, the Russian traditions for Christmas and New Year mixed into one event celebrated on the New Year but including the tree, a Santa-like 'Grandfather Frost', presents and huge family reunions and dinner parties all over the country. Bying a Tree at the New Year and installing it in the house is a tradition. Usually the whole family decorates the tree on the New Year Eve. We hope that Codeforces is a big and loving family, so in this problem we are going to decorate a tree as well.\n\nSo, our decoration consists of $n$ pieces, each piece is a piece of colored paper, its border is a closed polyline of a special shape. The pieces go one by one as is shown on the picture. The $i$-th piece is a polyline that goes through points: $(0, 0)$, $(0, y_{0})$, $(1, y_{1})$, $(2, y_{2})$, ..., $(k, y_{k})$, $(k, 0)$. The width of each piece equals $k$.\n\n\\begin{center}\n{\\scriptsize The figure to the left shows the decoration, the figure to the right shows the individual pieces it consists of.}\n\\end{center}\n\nThe piece number 1 (shown red on the figure) is the outer piece (we see it completely), piece number 2 (shown yellow) follows it (we don't see it completely as it is partially closed by the first piece) and so on. The programmers are quite curious guys, so the moment we hung a decoration on the New Year tree we started to wonder: what area of each piece can people see?",
    "tutorial": "Let's keep union of first $i$ pieces, $S(i)$ denote the area of union for the first $i$ pieces. Then to know visible part of $i$'s piece we need to calculate $S(i) - S(i - 1)$, ( Unable to parse markup [type=CF_TEX]",
    "tags": [
      "geometry",
      "schedules",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "379",
    "index": "G",
    "title": "New Year Cactus",
    "statement": "Jack and Jill are tired of the New Year tree, now they've got a New Year cactus at home! A cactus is a connected undirected graph where any two simple cycles have at most one common vertex. In other words, this graph doesn't have any edges that lie on more than one simple cycle.\n\nOn the 31st of December they are going to decorate the cactus by hanging toys to its vertices. At most one toy is going to hang on each vertex — it's either the toy Jack hung or the toy Jill hung. It's possible for a vertex to have no toys.\n\nJack and Jill has been arguing, so they don't want any edge to connect two vertices where one vertex has Jack's toy and the other vertex has Jill's toy.\n\nJack has decided to hang $a$ toys. What maximum number of toys $b$ can Jill hang if they both cooperate to maximize this value? Your task is to write a program that finds the sought $b$ for all $a$ from 0 to the number of vertices on the New Year Cactus.",
    "tutorial": "This problem can be solved for tree by using of dynamic programming $d[v][c][a]$, where $v$ - vertex, $c$ - type of vertex(whose toys are hanged or nothing are hanged there), $a$ - number of toys hanged by Jack for this subtree, $d[v][c][a]$ denote of maximum number of toys which can be hanged by Jill. Value $d[v][c][a]$ can be calculated iterated through sons of $v$ vertext and type of these vertices. Let's compress our cactus into tree by compressing each cycle into vertex. Vertex of tree will be looks like sequence of vertex from cactus which have edges not from this cycle and intermediates that belongs only to this cycle. Now we can calculate all $d[v][c][a]$ for this tree but we must be carefully processing a vertices.",
    "tags": [
      "dp"
    ],
    "rating": 3100
  },
  {
    "contest_id": "380",
    "index": "A",
    "title": "Sereja and Prefixes",
    "statement": "Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.\n\nSereja takes a blank piece of paper. Then he starts writing out the sequence in $m$ stages. Each time he either adds a new number to the end of the sequence or takes $l$ first elements of the current sequence and adds them $c$ times to the end. More formally, if we represent the current sequence as $a_{1}, a_{2}, ..., a_{n}$, then after we apply the described operation, the sequence transforms into $a_{1}, a_{2}, ..., a_{n}[, a_{1}, a_{2}, ..., a_{l}]$ (the block in the square brackets must be repeated $c$ times).\n\nA day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.",
    "tutorial": "Generate the first number 100000. Will in turn handle the requests, if the request gets to the point of adding one number, just print it. Otherwise see what element will meet our and just print it from precalculated array.",
    "tags": [
      "binary search",
      "brute force"
    ],
    "rating": 1600
  },
  {
    "contest_id": "380",
    "index": "B",
    "title": "Sereja and Tree",
    "statement": "Sereja adores trees. Today he came up with a revolutionary new type of binary root trees.\n\nHis new tree consists of $n$ levels, each vertex is indexed by two integers: the number of the level and the number of the vertex on the current level. The tree root is at level $1$, its index is $(1, 1)$. Here is a pseudo code of tree construction.\n\n\\begin{verbatim}\n//the global data are integer arrays cnt[], left[][], right[][]\ncnt[1] = 1;\nfill arrays left[][], right[][] with values -1;\nfor(level = 1; level < n; level = level + 1){\ncnt[level + 1] = 0;\nfor(position = 1; position <= cnt[level]; position = position + 1){\nif(the value of position is a power of two){ // that is, 1, 2, 4, 8...\nleft[level][position] = cnt[level + 1] + 1;\nright[level][position] = cnt[level + 1] + 2;\ncnt[level + 1] = cnt[level + 1] + 2;\n}else{\nright[level][position] = cnt[level + 1] + 1;\ncnt[level + 1] = cnt[level + 1] + 1;\n}\n}\n}\n\\end{verbatim}\n\nAfter the pseudo code is run, cell cnt[level] contains the number of vertices on level $level$. Cell left[level][position] contains the number of the vertex on the level $level + 1$, which is the left child of the vertex with index $(level, position)$, or it contains -1, if the vertex doesn't have a left child. Similarly, cell right[level][position] is responsible for the right child. You can see how the tree with $n = 4$ looks like in the notes.\n\nSerja loves to make things complicated, so he first made a tree and then added an empty set $A(level, position)$ for each vertex. Then Sereja executes $m$ operations. Each operation is of one of the two following types:\n\n- The format of the operation is \"$1$ $t$ $l$ $r$ $x$\". For all vertices $level, position$ $(level = t; l ≤ position ≤ r)$ add value $x$ to set $A(level, position)$.\n- The format of the operation is \"$2$ $t$ $v$\". For vertex $level, position$ $(level = t, position = v)$, find the union of all sets of vertices that are in the subtree of vertex $(level, position)$. Print the size of the union of these sets.\n\nHelp Sereja execute the operations. In this problem a set contains only distinct values like std::set in C++.",
    "tutorial": "Lets generate a tree as described in the statment. For each request to add items we just add a segment for a certain level. At the request of the number of items we just go through all the lower levels, considering the leftmost and the rightmost vertex in the subtree. To each level will take all intervals that it owns and for each check - whether it intersects with the interval that we have generated in the current stage. If so, simply add items to the set. The complexity of solving $O(n \\cdot m)$.",
    "tags": [
      "graphs",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "380",
    "index": "C",
    "title": "Sereja and Brackets",
    "statement": "Sereja has a bracket sequence $s_{1}, s_{2}, ..., s_{n}$, or, in other words, a string $s$ of length $n$, consisting of characters \"(\" and \")\".\n\nSereja needs to answer $m$ queries, each of them is described by two integers $l_{i}, r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$. The answer to the $i$-th query is the length of the maximum correct bracket subsequence of sequence $s_{li}, s_{li + 1}, ..., s_{ri}$. Help Sereja answer all queries.\n\nYou can find the definitions for a subsequence and a correct bracket sequence in the notes.",
    "tutorial": "We will support the segments tree. At each vertex will be stored: $a_{v}$ - the maximum length of the bracket subsequence $b_{v}$ - how many there it open brackets that sequence doesn't contain $c_{v}$ - how many there it closed brackets that sequence doesn't contain If we want to combine two vertices with parameters $(a_{1}, b_{1}, c_{1})$ and $(a_{2}, b_{2}, c_{2})$, we can use the following rules: $t = min(b_{1}, c_{2})$ $a = a_{1} + a_{2} + t$ $b = b_{1} + b_{2} - t$ $c = c_{1} + c_{2} - t$",
    "tags": [
      "data structures",
      "schedules"
    ],
    "rating": 2000
  },
  {
    "contest_id": "380",
    "index": "D",
    "title": "Sereja and Cinema",
    "statement": "The cinema theater hall in Sereja's city is $n$ seats lined up in front of one large screen. There are slots for personal possessions to the left and to the right of each seat. Any two adjacent seats have exactly one shared slot. The figure below shows the arrangement of seats and slots for $n = 4$.\n\nToday it's the premiere of a movie called \"Dry Hard\". The tickets for all the seats have been sold. There is a very strict controller at the entrance to the theater, so all $n$ people will come into the hall one by one. As soon as a person enters a cinema hall, he immediately (momentarily) takes his seat and occupies all empty slots to the left and to the right from him. If there are no empty slots, the man gets really upset and leaves.\n\nPeople are not very constant, so it's hard to predict the order in which the viewers will enter the hall. For some seats, Sereja knows the number of the viewer (his number in the entering queue of the viewers) that will come and take this seat. For others, it can be any order.\n\nBeing a programmer and a mathematician, Sereja wonders: how many ways are there for the people to enter the hall, such that nobody gets upset? As the number can be quite large, print it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "In order that no one would be upset, every person except first should sitdown near someone else. Now when any human comes we know that for one side of him there will not be any people. Will use it. We will support the interval exactly occupied seats. If the first person is not known, it is possible that we have 2 such intervals. Now only remains to consider carefully all the cases that could be, because at each iteration we know exactly how many people will sit on some certain place.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "380",
    "index": "E",
    "title": "Sereja and Dividing",
    "statement": "Let's assume that we have a sequence of doubles $a_{1}, a_{2}, ..., a_{|a|}$ and a double variable $x$. You are allowed to perform the following two-staged operation:\n\n- choose an index of the sequence element $i$ $(1 ≤ i ≤ |a|)$;\n- consecutively perform assignments: $t m p={\\frac{a_{\\mathrm{s}}+x}{2}},a_{i}=t m p,x=t m p$.\n\nLet's use function $g(a, x)$ to represent the largest value that can be obtained from variable $x$, using the described operation any number of times and sequence $a$.\n\nSereja has sequence $b_{1}, b_{2}, ..., b_{|b|}$. Help Sereja calculate sum: $\\sum_{i=1}^{[b]}\\sum_{j=i}^{[b]}g([b_{i},b_{i+1},\\cdot\\cdot\\cdot,b_{j}],0)$. Record $[b_{i}, b_{i + 1}, ..., b_{j}]$ represents a sequence containing the elements in brackets in the given order. To avoid problems with precision, please, print the required sum divided by $|b|^{2}$.",
    "tutorial": "Note that at any particular segment we are interested not more than 60 numbers. The greatest number enters with a coefficient of 1/2, the following - 1 /4, 1 /8, and so on. Thus to solve the problem we need to know for each number: how many segments to include it as a maximum , as a second maximum , a third , and so on until the 60th . What to know such information is sufficient to find 60 numbers large jobs left and right. This can be done carefully written the set or dsu. Now, with this information we can calculate by countind number of segments which contain our element. It is not difficult to do, knowing the positions of elements , large then current . Let the position of elements on the left: $p_{1}$> $p_{2}$> ... > $P_{s1}$. And positions right: $q_{1}$ < $q_{2}$ < ... < $q_{s2}$. So we should add value $\\sum_{i=1}^{s1}\\sum_{j=1}^{s2}V\\cdot(p_{i}-p_{i-1})\\cdot(q_{j+1}-q_{j})/(2^{i+j-1})$. All details can be viewed in any accepted solution.",
    "tags": [
      "data structures"
    ],
    "rating": 2600
  },
  {
    "contest_id": "381",
    "index": "A",
    "title": "Sereja and Dima",
    "statement": "Sereja and Dima play a game. The rules of the game are very simple. The players have $n$ cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.\n\nSereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.\n\nInna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.",
    "tutorial": "Simply do the process described in the statment.",
    "tags": [
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "381",
    "index": "B",
    "title": "Sereja and Stairs",
    "statement": "Sereja loves integer sequences very much. He especially likes stairs.\n\nSequence $a_{1}, a_{2}, ..., a_{|a|}$ ($|a|$ is the length of the sequence) is stairs if there is such index $i$ $(1 ≤ i ≤ |a|)$, that the following condition is met:\n\n\\[\na_{1} < a_{2} < ... < a_{i - 1} < a_{i} > a_{i + 1} > ... > a_{|a| - 1} > a_{|a|}.\n\\]\n\nFor example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.\n\nSereja has $m$ cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?",
    "tutorial": "Calculate the amount of each number. For all the different numbers - maximum possible times of use isn't more than 2 times. For the maximum is is only - 1.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "382",
    "index": "A",
    "title": "Ksenia and Pan Scales",
    "statement": "Ksenia has ordinary pan scales and several weights of an equal mass. Ksenia has already put some weights on the scales, while other weights are untouched. Ksenia is now wondering whether it is possible to put all the remaining weights on the scales so that the scales were in equilibrium.\n\nThe scales is in equilibrium if the total sum of weights on the left pan is equal to the total sum of weights on the right pan.",
    "tutorial": "This problem is just a technic problem. So, you should take weights one by one and place the current one into the side of the scales that contains lower number of weights. At the end you should output answer in the correct format.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "382",
    "index": "B",
    "title": "Number Busters",
    "statement": "Arthur and Alexander are number busters. Today they've got a competition.\n\nArthur took a group of four integers $a, b, w, x$ $(0 ≤ b < w, 0 < x < w)$ and Alexander took integer $с$. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number. In other words, he performs the assignment: $c = c - 1$. Arthur is a sophisticated guy. Each second Arthur performs a complex operation, described as follows: if $b ≥ x$, perform the assignment $b = b - x$, if $b < x$, then perform two consecutive assignments $a = a - 1; b = w - (x - b)$.\n\nYou've got numbers $a, b, w, x, c$. Determine when Alexander gets ahead of Arthur if both guys start performing the operations at the same time. Assume that Alexander got ahead of Arthur if $c ≤ a$.",
    "tutorial": "In the problem you should understand, what is the structure of Artur's operation. You can see that this operation is near operation $(b + x)$ % $w$ (To see that just apply $b = w - b - 1$). There is nothing hard to get the formula of changing a during the operation. So, if you have $k$ operations, you can see, that $b = (b + k \\cdot x)$ % $w$, $a = a - (b + k \\cdot x) / w$, $c = c - k$. When you've got all the formulas, you can solve the problem using binary search.",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "382",
    "index": "C",
    "title": "Arithmetic Progression",
    "statement": "Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers $a_{1}, a_{2}, ..., a_{n}$ of length $n$, that the following condition fulfills:\n\n\\[\na_{2} - a_{1} = a_{3} - a_{2} = a_{4} - a_{3} = ... = a_{i + 1} - a_{i} = ... = a_{n} - a_{n - 1}.\n\\]\n\nFor example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.\n\nAlexander has $n$ cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting $n + 1$ cards to make an arithmetic progression (Alexander has to use all of his cards).\n\nArthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.",
    "tutorial": "This problem is about considering cases: 1) If $n = 1$, the answer is -1. Because of any two numbers is arithmetical progression. 2) If array is constant, the answer if that constant. 3) If you have arithmetical progression initially, you can compute its difference $d$. In this case you should just to output $minVal - d$, and $maxVal + d$, where $minVal$ is minimum value among $a[i]$, and $maxVal$ is maximum value among $a[i]$. But in case of $n = 2$, also you should check $(a[0] + a[1]) / 2$. If this number is integer, it is needed to be output. 4) Else, the answer has at most one integer. You find this integer you should sort the sequence, and find the place where the number is missed. If such a place exists you should add the corresponding number to the sequence, else, the answer is $0$. 5) In all other cases the answer is $0$.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "382",
    "index": "D",
    "title": "Ksenia and Pawns",
    "statement": "Ksenia has a chessboard of size $n × m$. Each cell of the chessboard contains one of the characters: \"<\", \">\", \"^\", \"v\", \"#\". The cells that contain character \"#\" are blocked. We know that all chessboard cells that touch the border are blocked.\n\nKsenia is playing with two pawns on this chessboard. Initially, she puts the pawns on the chessboard. One cell of the chessboard can contain two pawns if and only if the cell is blocked. In other cases two pawns can not stand in one cell. The game begins when Ksenia put pawns on the board. In one move, Ksenia moves each pawn to a side adjacent cell in the direction of arrows painted on the cell on which the corresponding pawn sits (if the pawn sits on \"#\", it does not move). Assume that Ksenia moves pawns simultaneously (see the second test case).\n\nOf course, Ksenia plays for points. How can one calculate the points per game? Very simply! Let's count how many movements the first pawn made and how many movements the second pawn made, sum these two numbers — it will be the resulting score of the game.\n\nKsenia wonders: what is the maximum number of points she can earn (for that, she should place the pawns optimally well early in the game). Help her and find that number.",
    "tutorial": "In this problem from every cell except # there is one next cell. That's why this graph is almost functional graph. If this graph contains a cycle, then answer is -1 because the length of the cycle is at least two. In the other case, there are no cycles in the graph. Let's find the longest path in it, denote is as $len$. Then is answer is at least $2 \\cdot len - 1$ because we can put the two pawns in the first two cells of this path. But in some cases we could get the answer $2 \\cdot len$ if there are two non-intersecting by vertices (not #) paths of length $len$. They are non-intersecting because if they intersect in some cell then they will be equal to the end (and the statement says that such moves are invalid). So, we should check if the graph contains two non-intersecting by vertices (not #) paths of length $len$. It could be done in any way. For example, using dfs searches.",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "382",
    "index": "E",
    "title": "Ksenia and Combinatorics",
    "statement": "Ksenia has her winter exams. Today she is learning combinatorics. Here's one of the problems she needs to learn to solve.\n\nHow many distinct trees are there consisting of $n$ vertices, each with the following properties:\n\n- the tree is marked, that is, the vertices of the tree are numbered from 1 to $n$;\n- each vertex of the tree is connected with at most three other vertices, and at the same moment the vertex with number 1 is connected with at most two other vertices;\n- the size of the tree's maximum matching equals $k$.\n\nTwo trees are considered distinct if there are such two vertices $u$ and $v$, that in one tree they are connected by an edge and in the other tree they are not.\n\nHelp Ksenia solve the problem for the given $n$ and $k$. As the answer to the problem can be very huge you should output it modulo $1000000007 (10^{9} + 7)$.",
    "tutorial": "In this problem you should count trees with some properties. It can be done using dynamic programming. The main idea is that the maximum mathing in tree can be found using simple dynamic $dp[v][used]$ ($v$ -- vertex, $used$ - was this vertex used in matching). So you should to count the trees tou should include in state of the dynamic values dp[v][0]$ and $dp[v][1]$. In other words, you should use dynamic programming $z[n][dp0][dp1]$ - number of rooted trees with $n$ vertices and values of dynamic in root $dp[root][0] = dp0$ and $dp[root][1] = dp1$. But in simple implementation this solution will get TL. There are two ways to get AC. The first is to opltimize code and make precalc. The second is to optimize asymptotics. The author's solution uses the second way. To optimize solution you should mark that values $dp0$ and $dp1$ differs at most by one. That is $dp0 = dp1$, or $dp0 = dp1 + 1$. So the first dynamic becomes $r[n][dp0][add]$. Another optimization is there are not so many triples $(n, dp0, add)$ with non-negative values (about 250), so you can you use lazy programming to calculate this dynamic.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "383",
    "index": "A",
    "title": "Milking cows",
    "statement": "Iahub helps his grandfather at the farm. Today he must milk the cows. There are $n$ cows sitting in a row, numbered from $1$ to $n$ from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).\n\nIahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.",
    "tutorial": "A good strategy to approach this problem is to think how optimal ordering should look like. For this, let's calculate for each 2 different cows i and j if cow i needs to be milked before or after cow j. As we'll show, having this information will be enough to build optimal ordering. It is enough to consider only cases when i < j, case when i > j is exactly the opposite of case i < j. For formality, I'll call the optimal ordering permutation and lost milk the cost of permutation. So, for an optimal permutation P let's take 2 numbers i < j and see in which cases i should appear before j in permutation (i is before j if P[pos1] = i, P[pos2] = j and pos1 < pos2; otherwise we'll call i is after j). We have 4 possible cases: 1/ A[i] = 0 and A[j] = 0 If we put i before j, no additional cost will be added. Since j is in right of i and i only adds cost when it finds elements in left of i, j won't be affected when processing i. When processing j, i will be already deleted so it won't affect the cost either. Hence, we can put i before j and no cost will be added. 2/ A[i] = 0 and A[j] = 1 Here, i and j can appear in arbitrary order in permutation (i can be before or after j). No matter how we choose them, they won't affect each other and cost will remain the same. 3/ A[i] = 1 and A[j] = 0 As well, here i and j can appear in arbitrary order. If we choose i first, j will be in right of it, so cost of permutation will increase by one. If we choose j first, i will be in left of it so cost of permutation will increase as well. No matter what we do, in this case cost of permutation increases by 1. 4/ A[i] = 1 and A[j] = 1 Here, i needs to be after j. This adds 0 cost. Taking i before j will add 1 cost to permutation (since j is in right of i). Those 4 cases show us how a minimal cost permutation should look. In a permutation like this, only case 3/ contributes to final cost, so we need to count number of indices i, j such as i < j and A[i] = 1 and A[j] = 0 (*). If we show a permutation following all rules exists, task reduces to (*). By cases 2/ and 3/ it follows that in an optimal permutation, it only matters order of elements having same value in A[]. We can put firstly all elements having value 0 in A[], then all elements having value 1 in A[]. We can order elements having value 0 by case 1/ and elements having value 1 by case 4/. More exactly, suppose i1 < i2 < ... < im and (A[i1] = A[i2] = ... = A[im] = 0) and j1 > j2 > ... > jn (A[j1] = A[j2] = ... = A[jn] = 1). Then, a permutation following all rules is {i1, i2, ..., im, j1, j2, ..., jn}. This permutation can always be built. Hence, task reduces to (*): count number of indices i, j such as i < j and A[i] = 1 and A[j] = 0. We can achieve easily an O(N) algorithm to do this. Let's build an array cnt[j] = number of 0s in range {j, j + 1, ..., N} from array A. We can easily implement it by going backwards from N to 1. The result is sum of cnt[i], when A[i] = 1.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint x[200200], zero[200200];\n\nint main() {\n    int n;\n    cin >> n;\n    for (int i = 1; i <= n; ++i)\n        cin >> x[i];\n    for (int i = n; i >= 1; --i)\n        zero[i] = zero[i + 1] + 1 - x[i];\n\n    long long res = 0;\n    for (int i = 1; i <= n; ++i)\n        if (x[i] == 1)\n            res += zero[i];\n    cout << res;\n\n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "383",
    "index": "B",
    "title": "Volcanoes",
    "statement": "Iahub got lost in a very big desert. The desert can be represented as a $n × n$ square matrix, where each cell is a zone of the desert. The cell $(i, j)$ represents the cell at row $i$ and column $j$ $(1 ≤ i, j ≤ n)$. Iahub can go from one cell $(i, j)$ only down or right, that is to cells $(i + 1, j)$ or $(i, j + 1)$.\n\nAlso, there are $m$ cells that are occupied by volcanoes, which Iahub cannot enter.\n\nIahub is initially at cell $(1, 1)$ and he needs to travel to cell $(n, n)$. Knowing that Iahub needs $1$ second to travel from one cell to another, find the minimum time in which he can arrive in cell $(n, n)$.",
    "tutorial": "Our first observation is that if there is a path from (1, 1) to (N, N), then the length of path is 2 * N - 2. Since all paths have length 2 * N - 2, it follows that if there is at least one path, the answer is 2 * N - 2 and if there isn't, the answer is -1. How to prove it? Every path from (1, 1) to (N, N) has exactly N - 1 down directions and exactly N - 1 right directions. So, total length for each path is N - 1 + N - 1 = 2 * N - 2. So we reduced our problem to determine if there is at least one path from (1, 1) to (N, N). This is the challenging part of this task, considering that N <= 10 ^ 9. How would you do it for a decently small N, let's say N <= 10^3 . One possible approach would be, for each row, keep a set of reachable columns. We could easily solve this one by doing this: if (i, j) denotes element from ith row and jth column, then (i, j) is (is not) reachable if: if (i, j) contains a volcano, then (i, j) is not reachable. Otherwise, if at least one of (i - 1, j) and (i, j - 1) is reachable, then (i, j) is reachable. Otherwise, (i, j) is not reachable. What's the main problem of this approach? It needs to keep track of 10^9 lines and in worst case, each of those lines can have 10^9 reachable elements. So, worst case we need 10^9 * 10^9 = 10^18 operations and memory. Can we optimize it? We can note for beginning that we don't need to keep track of 10^9 lines, only m lines are really necessarily. We need only lines containing at least one obstacle (in worst case when each line contains only one obstacle, we need m lines). How to solve it this way? Suppose line number x contains some obstacles and lines x + 1, x + 2, x + 3 do not contain any obstacle. Suppose we calculated set S = {y | cell (x, y) is reachable}. How would look S1, S2, S3 corresponding to lines x + 1, x + 2, x + 3? For S1, we can reach cell (x + 1, ymin), where ymin is minimal value from set S. Then, we can also reach {ymin + 1, ymin + 2, ..., N}, by moving right from (x + 1, ymin). So S1 = {ymin, ymin + 1, ..., N}. How do S2 and S3 look? It's easy to see that they'll be as well {ymin, ymin + 1, ..., N}. So we get following optimization: suppose set of lines containing at least one obstacle is {L1, L2, ..., Lk}. We need to run algorithm only for lines L1, L1 + 1, L2, L2 + 1, L3, L3 + 1, ..., Lk, Lk + 1. It looks like we didn't make anything with this optimization. Even if we calculate for m lines, each line can still have 10^9 reachable positions. So worst case we perform 10^14 operations. We need something better for managing information from a line. You can note that for a given line y, there are a lot of positions having consecutive values. There are a lot of positions (x, y) and (x, y + 1) both reachable. This should give us following idea: what if instead of keeping reachable positions, we keep reachable ranges? That is, for each line x we keep a set of ranges S = {(a, b) | all cells (x, k) with a <= k <= b are reachable}. How many ranges can it be for a line? If the line contains m obstacles, there are m + 1 ranges. Suppose for line x all cells are reachable, but for line x + 1 cells (x + 1, 3) (x + 1, 5) (x + 1, N - 1) are blocked. Then, the ranges of reachable cells are [1, 2] [4, 4], [6, N - 2] and [N, N]. By now, we get worst case m lines and worst case each line having m elements, so in worst case we'd have to handle m * m = 10 ^ 10 events. This may still look too much, but happily this bound is over estimated. If a line has o obstacles, there can be at most o + 1 ranges. If lines L1, L2, ..., Lk have {o1, o2, ..., ok} obstacles, there'll be at most o1 + o2 + ... + ok + k ranges. But o1 + o2 + ... + ok = m and also k is at most m (proved above why we're interested in at most m lines), so in worst case we get m + m = 2 * m ranges. Yaay, finally a decent number of states for this problem :) So, we iterate each line we're interested in. Let's find set of ranges for this line, thinking that all cells from line above are reachable. This is easy to do. After we get our ranges like all cells from above can be visited, let's think how having obstacles above can influence current ranges. After adding ranges from above, current ranges can't increase (obviously), they can only decrease, remain the same or some of them can become empty. So, let's take each range [a, b] from current line and see how it will transform after adding ranges from previous line. Given range [a, b], it can transform only in [a' , b] with a' >= a. If a' > b, then obviously range is empty. Why second number of range keeps constant? Let a' smallest reachable column from current line which is in range [a, b]. It's enough to check a' >= a, as if a' > b, range will be empty. It's obviously why we need to keep a' smallest value possible >= a: we're interested to keep range as big as possible and as less as we cut from left, as big it is. Once we've found a' in range [a, b] (or a' > b if range is empty) all cells {a' + 1, a' + 2, ..., b} are reachable as well by going right from a', so if interval is not empty, then second number defining it remains b. Next question is how to find a' fast enough. In order a point a' to be reachable on current range, it also needs to exist a range on previous line containing it. If the range from previous line is [pa, pb] then a' needs to follow 3 conditions: a' minimal such as pa <= a' <= pb a' >= a What if instead of finding a' we find [pa, pb]? Then a' is max(pa, a). In order a' to be as small as possible, since a is constant, pa needs to be as small as possible. So we reduced it to: pa minimal pb >= a' >= a <=> pb >= a Intervals from previous line are disjoint, no 2 intervals cross each other. It means that if pb is minimal, than pa is minimal too (if we increase pb, then pa will increase too, so it won't be minimal). Hence, you need to find an interval [pa, pb] such as pb is minimal and pb >= a. Then, a' is max(a, pa). This is easy to do if we sort all intervals from previous line increasing by second value (pb), then we binary search for value a. Finally, after running algorithm for all lines, last range from last line has second number N (assuming ranges are sorted increasing by second value), then there exist a path, otherwise there does not exist. This algorithm should run O(m * logm) worst case, good enough to pass.",
    "code": "#include <stdio.h>\n#include <algorithm>\n\nusing namespace std;\n\nconst int INF = 1000000100;\n\nstruct range {\n    int x, y;\n} prev[100010], cur[100010], blocked[100010];\n\ninline bool comp1(range A, range B) {\n    if (A.x == B.x)\n        return A.y < B.y;\n    return A.x < B.x;\n}\n\nint main() {\n    int N, M;\n    scanf(\"%d%d\", &N, &M);\n    for (int i = 1; i <= M; ++i) {\n        int xx, yy;\n        scanf(\"%d%d\", &xx, &yy);\n        blocked[i].x = xx; blocked[i].y = yy;\n    }\n\n    sort(blocked + 1, blocked + M + 1, comp1);\n    int curCnt = 0, prevCnt = 1;\n    prev[prevCnt].x = prev[prevCnt].y = 1;\n\n    for (int i = 1; i <= M; ++i) {\n        if (blocked[i].x != blocked[i - 1].x + 1) {\n            prevCnt = 1;\n            prev[1].y = N;\n        }\n\n        int j;\n        for (j = i; j <= M && blocked[j].x == blocked[i].x; ++j); --j;\n        curCnt = 0;\n        int leftSegment = 1;\n        for (int k = i; k <= j; ++k) {\n            if (blocked[k].y - 1 >= leftSegment) {\n                cur[++curCnt].x = leftSegment;\n                cur[curCnt].y = blocked[k].y - 1;\n            }\n            leftSegment = blocked[k].y + 1;\n        }\n        if (leftSegment <= N) {\n            cur[++curCnt].x = leftSegment;\n            cur[curCnt].y = N;\n        }\n\n        for (int k = 1; k <= curCnt; ++k) {\n            int st = 1, dr = prevCnt, ret = -1;\n            while (st <= dr) {\n                int med = (st + dr) / 2;\n                if (prev[med].y >= cur[k].x) {\n                    ret = prev[med].x;\n                    dr = med - 1;\n                } else\n                    st = med + 1;\n            }\n            if (ret == -1 || ret > cur[k].y)\n                cur[k].x = cur[k].y = INF;\n            else\n                cur[k].x = max(ret, cur[k].x);\n        }\n\n        prevCnt = 0;\n        for (int k = 1; k <= curCnt; ++k)\n            if (cur[k].x != INF && cur[k].y != INF)\n                prev[++prevCnt] = cur[k];\n        if (prevCnt == 0) {\n            printf(\"-1\");\n            return 0;\n        }\n        i = j;\n    }\n\n    if (blocked[M].x != N) {\n        prevCnt = 1;\n        prev[1].y = N;\n    }\n\n    if (prev[prevCnt].y == N)\n        printf(\"%d\n\", 2 * N - 2);\n    else\n        printf(\"-1\");\n    return 0;\n}",
    "tags": [
      "binary search",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "383",
    "index": "C",
    "title": "Propagating tree",
    "statement": "Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of $n$ nodes numbered from $1$ to $n$, each node $i$ having an initial value $a_{i}$. The root of the tree is node $1$.\n\nThis tree has a special property: when a value $val$ is added to a value of node $i$, the value -$val$ is added to values of all the children of node $i$. Note that when you add value -$val$ to a child of node $i$, you also add -(-$val$) to all children of the child of node $i$ and so on. Look an example explanation to understand better how it works.\n\nThis tree supports two types of queries:\n\n- \"$1$ $x$ $val$\" — $val$ is added to the value of node $x$;\n- \"$2$ $x$\" — print the current value of node $x$.\n\nIn order to help Iahub understand the tree better, you must answer $m$ queries of the preceding type.",
    "tutorial": "This is kind of task that needs to be break into smaller subproblems that you can solve independently, then put them together and get solution. Let's define level of a node the number of edges in the path from root to the node. Root (node 1) is at level 0, sons of root are at level 1, sons of sons of root are at level 2 and so on. Now suppose you want to do an operation of type 1 to a node x. What nodes from subtree of x will be added +val (a positive value)? Obviously, x will be first, being located at level L. Sons of x, located at level L + 1 will be added -val. Sons of sons, located at level L + 2, will be added value +val again. So, nodes from subtree of x located at levels L, L + 2, L + 4, ... will be added a +val, and nodes located at levels L + 1, L + 3, L + 5 will be added a -val. Let's take those values of L modulo 2. All nodes having remainder L modulo 2 will be added a +val, and nodes having reminder (L + 1) modulo 2 will be added -val. In other words, for a fixed x, at a level L, let y a node from subtree of x, at level L2. If L and L2 have same parity, +val will be added to y. Otherwise, -val will be added to y. From here we have the idea to split nodes of tree in 2 sets - those being located at even level and those being located at odd level. What still makes the problem hard to solve? The fact that we have a tree. If nodes from a subtree would be a contiguous sequence instead of some nodes from a tree, problem would be simpler: the problem would reduce to add / subtract values to all elements of a subarray and query about a current value of an element of array. So, how can we transform tree to an array, such as for a node x, all nodes from subtree of x to be a subarray of array? The answer is yes. We can do this by properties of DFS search. Before reading on, make sure that you know what is discovery time and finish time in a DFS search. Let's build 3 arrays now - discover[], representing nodes in order of their discover times (a node is as before in discover as it has a small discover time), begin[] = for a node, in which time it was discovered and end[] = what's last time of a discovered node before this node finishes. For a subtree of x, all nodes in the subtree are nodes in discover from position begin[x] to end[x]. Example: suppose you have tree 1-5; 1-6; 6-7; 6-4; 4-2; 4-3 Discover is {1, 5, 6, 7, 4, 2, 3}. begin is {1, 6, 7, 5, 2, 3, 4}. end is {7, 6, 7, 7, 2, 7, 4}. What's subtree of node 6? elements of discover from position begin[6] to end[6]. In this case, from 3 to 7, so elements {6, 7, 4, 2, 3}. You can see it's correct and take more examples if you want :) Now, we reduced problem to: you're given an array A. you can perform 2 operations: 1/ increase all elements from a range [x, y] to a value val (val can be negative, to treat subtractions) 2/ what's current value of an element from position pos. Those who solved \"Iahub and Xors\" from my last round, CF 198, should probably say they saw something similar before. If you didn't solve problem before, I encourage you to do it after you solve this one, it uses a similar idea to what will follow now. Also, if you don't know Fenwick trees, please read them before moving on. An alternative would be for this task using segment trees with lazy update, but I see this one more complicated than needed. I'll use now a not so common approach when dealing with data structures. Instead of keeping in a node the result, like you usually do, I'll keep just an auxiliary information. So what algorithm proposed does: Let A an array, initially with all elements 0. When you need to update range [x, y] with value val, you simply do A[x] += val and A[y + 1] -= val. When you need to answer a query about position pos, you output A[1] + A[2] + ... + A[pos]. Implemented brute force, you get O(1) per update and O(N) per query. However, these both are operations supported by a Fenwick tree, so you can get O(logN) per operation. It may not be very clear why this algorithm works. Let's take a closer look: an update needs to add value val only to range [x, y]. When you query a position pos, let's see if algorithm handles it correctly: 1/ pos < x. In this case, result must not be affected by my update. Since pos < x and I only updated 2 values with indices >= x, when doing A[1] + A[2] + ... + A[pos] it won't matter at all I did that update - at least not for this query. 2/ x <= pos <= y. Here, for a pos, I need to add value val only once. We add it only at A[x] - in this way it will be counted once, and it will be considered for each elements from range [x, y] (since an element at position p from range [x, y] has p >= x, in A[1] + A[2] + ... + A[p] I'll have to consider A[x]). 3/ pos > y. Here I don't have to consider the query. But it would be considered when processing A[x]. But if I add to A[y + 1] value -val I'll just cancel the value previously added.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nint N, M;\nint A[200002];\nvector<int> V[200002];\nint niv[200002], in[200002], out[200002], tnow;\nint AIB[400002];\nbool S[200002];\n\nvoid update(int pos, int val)\n{\n    for (; pos <= 400000; pos += pos & -pos)\n        AIB[pos] += val;\n}\nint query(int pos)\n{\n    int sum = 0;\n    for (; pos >= 1; pos -= pos & -pos)\n        sum += AIB[pos];\n    return sum;\n}\n\nvoid Dfs(int x)\n{\n    S[x] = true;\n    in[x] = ++tnow;\n    for (vector<int>::iterator it = V[x].begin(); it != V[x].end(); ++it)\n        if (!S[*it])\n        {\n            niv[*it] = niv[x] + 1;\n            Dfs(*it);\n        }\n    out[x] = ++tnow;\n}\n\nint main()\n{\n    cin.sync_with_stdio(false);\n\n    cin >> N >> M;\n    for (int i = 1; i <= N; ++i)\n        cin >> A[i];\n    for (int i = 1, nod1, nod2; i <= N - 1; ++i)\n    {\n        cin >> nod1 >> nod2;\n        V[nod1].push_back(nod2);\n        V[nod2].push_back(nod1);\n    }\n\n    Dfs(1);\n\n    for (int i = 1, type; i <= M; ++i)\n    {\n        cin >> type;\n        if (type == 1)\n        {\n            int nod, val;\n            cin >> nod >> val;\n\n            if (niv[nod] % 2 == 0)\n            {\n                update(in[nod], val);\n                update(out[nod], -val);\n            }\n            else\n            {\n                update(in[nod], -val);\n                update(out[nod], val);\n            }\n        }\n        else\n        {\n            int nod;\n            cin >> nod;\n\n            if (niv[nod] % 2 == 0)\n                cout << A[nod] + query(in[nod]) << '\n';\n            else\n                cout << A[nod] - query(in[nod]) << '\n';\n        }\n    }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "383",
    "index": "D",
    "title": "Antimatter",
    "statement": "Iahub accidentally discovered a secret lab. He found there $n$ devices ordered in a line, numbered from $1$ to $n$ from left to right. Each device $i$ $(1 ≤ i ≤ n)$ can create either $a_{i}$ units of matter or $a_{i}$ units of antimatter.\n\nIahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo).\n\nYou are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.",
    "tutorial": "The problem is: given an array, iterate all possible subarrays (all possible elements such as their indexes are consecutive). Now, for a fixed subarray we need to know in how many ways we can color its elements in black and white, such as sum of black elements is equal to sum of white elements. The result is sum of this number, for each subarray. Let's solve an easier problem first. This won't immediately solve the harder version, but it will be useful later. Suppose you've fixed a subarray. In how many ways can you color it with black and white? Suppose subarray has N elements and sum of them is M. Also, suppose for a coloring, sum of blacks is sB and sum of whites is sW. For coloring to be valid, sB = sW. But we also know that sB + sW = M (because each element is colored by exactly one color). We get that 2 * sB = M, so sB = M / 2. The problem is now: in how many ways can we color elements in black such as sum of blacks is M / 2 (after we fix a black coloring, we color with white non colored elements; sum of white colored elements is also M / 2). This is a well known problem: Knapsack problem. Let ways[i][j] = in how many ways one can obtain sum j from first i elements. When adding (i + 1) object, after ways[i] is calculated, for a fixed sum j we can do 2 things: add (i + 1) object to sum j or skip it. Depending of what we chosen, we add value ways[i][j] to ways[i + 1][j + value[i + 1]] or to ways[i + 1][j]. The result is in ways[N][M / 2]. This works in O(N * M) time. An immediate solution can be obtained now: take all subarrays and apply above approach. This leads to an O(N ^ 2 * M ^ 2) solution, which is too much. One can reduce complexity to O(N ^ 2* M) by noting that processing subarray [i, j] can be done with already calculated values for subarray [i, j - 1]. Hence, instead of adding N elements, it's enough to add 1 element to already calculated values (element from position j). Sadly, O(N ^ 2 * M) is still too slow, so we need to find something better. The solution presented below will look forced if you didn't solve some problems with this technique before. It's hard to come with an approach without practicing this kind of tasks. But don't worry, as much as you practice them, as easily you'll solve those problems. We'll solve task by divide and conquer. Complexity of this solution is O(N * M * logN). Let f(left, right) a function that counts number of colorings for each subarray [i, j], such as subarray [i, j] is included in subarray [left, right] (left <= i <= j <= right). Answer is in f(1, N). The trick is to define a value med = (left + right) / 2 (very frequent trick in divide and conquer problems, called usually a median). We can next classify [i, j] subarrays in 3 types: 1/ i <= med j <= med 2/ i > med j > med 3/ i <= med j > med We can solve 1/ and 2/ by calling f(left, med) and f(med + 1, right). The remained problem is when i <= med and j > med. If we solve 3/ in O((right - left) * M) time, this will be enough to overall achieve O(N * M * logN) (for this moment trust me, you'll see later why it's so :) ). Let's denote by i1 last i1 elements from subarray [left, med]. Also, let's note by i2 first i2 elements from subarray [med + 1, right]. For example, let left = 1 and right = 5, with array {1, 2, 3, 4, 5}. med is 3 and for i1 = 2 and i2 = 1, \"left\" subarray is {2, 3} and \"right\" subarray is {4}. By iterating i1 from 1 to med - left + 1 and i2 from 1 to right - med and then unite subarrays i1 and i2, we obtain all subarrays described in 3/ . Let's denote by j1 sum of a possible black coloring of i1. Similarly, j2 is sum of a possible black coloring of i2. Suppose we fixed i1, i2, j1 and j2. When it's the coloring valid? Let S sum of united subarrays i1 and i2 (S = value[med - i1 + 1] + value[med - i1 + 2] + ... + value[med] + value[med + 1] + ... + value[med + i2 - 1] + value[med + i2]). Now it's time to use what I explained at the beginning of solution. The coloring is good only when j1 + j2 = S / 2. We can rewrite the relation as 2 * (j1 + j2) = sum_of_elements_from_i1 + sum_of_elements_from_i2. We can rewrite it even more: 2 * j1 + 2 * j2 - sum_of_elements_from_i1 - sum_of_elements_from_i2 = 0 2 * j1 - sum_of_elements_from_i1 = sum_of_elements_from_i2 - 2 * j2 = combination_value This relation is the key of solving problem. You can see now that relation is independent in \"left\" and \"right\" side. We calculate left[i1][j1] and right[i2][j2] = in how many ways can I obtain sum of blacks j1 (j2) from first i1 (i2) from left (right) side. Let's calculate also count[value] = in how many ways can I obtain combination_value equal to value in the right side. For some fixed (i2, j2) I add to count[sum_of_elements_from_i2 - 2 * j2] value right[i2][j2]. In this way count[] is calculated correctly and completely. Now, let's fix a sum (i1, j1) in the left side. We're interested how many good colorings are such as there exist a coloring of j1 in i1 elements (the endpoint of \"left\" is fixed to be i1 and I need to calculate endpoints i2 for right, then to make colorings of i2). A coloring is good if combination_value of (i1, j1) and (i2, j2) is equal. Hence, I need to know in how many ways I can color i1 elements to obtain sum j1 and also I need to know in how many ways I can color elements from right to obtain same combination_value as it's in the left. It's not hard to see that answer for a fixed (i1, j1) is left[i1][j1] * count[2 * j1 - sum_of_elements_from_i1]. This takes O((right - left) * M) time. The only thing remained in the problem is to see why complexity is O(N * M * logN). We can assume N is a power of 2 (it not, let's round N to smallest power of 2 bigger than N; complexity for N is at least as good as complexity for this number). Draw a binary complete tree with N nodes. Each node corresponds to an appeal of f(). For a level, exactly O(N * M) operations are performed. To see why: For level 1, there'll be 1 node performing N * M operations. For level 2, there'll be 2 nodes performing (N / 2) * M operations. Summing up we get O(N * M). For level 3, there'll be 4 nodes performing (N / 4) * M operations. Summing up we get O(N *M) as well. and so on. So for each level we perform O(N * M) operations. A binary complete tree has maximum O(logN) levels, so overall complexity is O(N * M * logN).",
    "code": "#include <cstring> \n#include <cstdio> \n#include <iostream> \n#include <algorithm> \n#include <vector> \n \nusing namespace std; \n \nconst int MOD = 1000000007; \n \nint N; \nint A[1002], S[1002]; \nint F[20002]; \nint D1[1002][10002], D2[1002][10002]; \nint result; \n \nvoid get_result(int i1, int i2) \n{ \n    if (i1 == i2) return; \n    int mid = (i1 + i2) / 2; \n \n    get_result(i1, mid); \n    get_result(mid + 1, i2); \n \n    for (int i = 0; i < 20000; ++i) \n        F[i] = 0; \n \n    for (int i = 1; mid - i + 1 >= i1; ++i) \n        memset(D1[i], 0, sizeof(D1[i])); \n    for (int i = 1; mid + i <= i2; ++i) \n        memset(D2[i], 0, sizeof(D2[i])); \n \n    // S1 + S2 = 2 * (j1 + j2) \n    // S1 - 2 * j1 = 2 * j2 - S2 \n \n    int summax1 = 0; \n \n    D1[0][0] = 1; \n    for (int i = 1; mid - i + 1 >= i1; ++i) \n    { \n        for (int j = summax1; j >= 0; --j) \n        { \n            D1[i][j + A[mid - i + 1]] += D1[i - 1][j]; \n            if (D1[i][j + A[mid - i + 1]] >= MOD) D1[i][j + A[mid - i + 1]] -= MOD; \n            summax1 = max(summax1, j + A[mid - i + 1]); \n \n            D1[i][j] += D1[i - 1][j]; \n            if (D1[i][j] >= MOD) D1[i][j] -= MOD; \n        } \n        for (int j = summax1; j >= 0; --j) \n        { \n            F[10000 + (S[mid] - S[mid - i]) - 2 * j] += D1[i][j]; \n            if (F[10000 + (S[mid] - S[mid - i]) - 2 * j] >= MOD) F[10000 + (S[mid] - S[mid - i]) - 2 * j] -= MOD; \n        } \n    } \n    int summax2 = 0; \n \n    D2[0][0] = 1; \n    for (int i = 1; mid + i <= i2; ++i) \n    { \n        for (int j = summax2; j >= 0; --j) \n        { \n            D2[i][j + A[mid + i]] += D2[i - 1][j]; \n            if (D2[i][j + A[mid + i]] >= MOD) D2[i][j + A[mid + i]] -= MOD; \n            summax2 = max(summax2, j + A[mid + i]); \n \n            D2[i][j] += D2[i - 1][j]; \n            if (D2[i][j] >= MOD) D2[i][j] -= MOD; \n \n        } \n        for (int j = summax2; j >= 0; --j) \n            result = (result + 1LL * D2[i][j] * F[10000 + 2 * j - (S[mid + i] - S[mid])]) % MOD; \n    } \n} \n \nint main() \n{ \n    //freopen(\"sub.in\", \"r\", stdin); \n \n    cin >> N; \n    for (int i = 1; i <= N; ++i) \n    { \n        cin >> A[i]; \n        S[i] = S[i - 1] + A[i]; \n    } \n \n    get_result(1, N); \n \n    cout << result << '\n'; \n    return 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "383",
    "index": "E",
    "title": "Vowels",
    "statement": "Iahubina is tired of so many complicated languages, so she decided to invent a new, simple language. She already made a dictionary consisting of $n$ 3-words. A 3-word is a sequence of exactly $3$ lowercase letters of the first 24 letters of the English alphabet ($a$ to $x$). She decided that some of the letters are vowels, and all the others are consonants. The whole language is based on a simple rule: any word that contains at least one vowel is correct.\n\nIahubina forgot which letters are the vowels, and wants to find some possible correct sets of vowels. She asks Iahub questions. In each question, she will give Iahub a set of letters considered vowels (in this question). For each question she wants to know how many words of the dictionary are correct, considering the given set of vowels.\n\nIahubina wants to know the $xor$ of the squared answers to all the possible questions. There are $2^{24}$ different questions, they are all subsets of the set of the first 24 letters of the English alphabet. Help Iahub find that number.",
    "tutorial": "Let's iterate over all possible vowel sets. For a given set {x1, x2, ..., xk} we're interested in number of correct words from dictionary. After a precalculation, we can do it in O(k). Suppose our current vowel set is {x1, x2, ..., xk}. How many words are covered by the current vowels? By definition, we say a word is covered by a set of vowels if at least one of 3 letters of word is in vowel set. We can calculate this number using principle of inclusion and exclusion. We'll denote by |v1, v2, v3, ...| = number of words containing ALL of vowels v1, v2, v3, ... . Using principle of inclusion and exclusion we get: number_of_words_covered = |x1| + |x2| + .. + |xk| - |x1, x2| - |x1, x3| - .... + |x1, x2, x3| + |x1, x2, x4| + .... + |xk-2, xk-1, xk|. This formula is simply a reformulation of principle of inclusion and exclusion. You can easily observe that |v1, v2, ..., vk| makes sense only when k is at most 3, as no word from input can contain 4 or more letters (and hence can't contain 4 or more vowels). Example: Suppose words are abc, abd and bcd. |a| = 2 (first 2 words both contain character a). |a, b| = 2 (as well, first 2 words contain characters a and b). |b| = 3 (all 3 words contain character b). |a, b, d| = 1 (only second word contains all 3 characters). Also, note how principle of inclusion and exclusion works. number of words covered for vowels {a, b} is |a| + |b| - |a, b| = 2 + 3 - 2. Indeed, answer is 3. We divide our problem in 3 subproblems. First one, for a vowel set, compute sum of |a|, where a is a letter from subset. Second, compute sum of |a, b|, where both a and b are letters from set. Third, compute sum of |a, b, c|, where a, b, c are letters from set. As stated, the answer is number_from_1st_step + number_from_3rd_step - number_from_2nd_step. If you followed me, you'll see that we want to compute results for each subproblem in O(queryLetters). First subproblem can be solved trivially in O(queryLetters). Let array single[], with following meaning: single[c] is how many words contain character c. It can be trivially precomputed in O(24 * N). Note that if a word contains twice/third times a character c, it needs to be counted only one (e.g. word aba will add only 1 to single[a]). For compute result of this subproblem for a given set of vowels, I'll take all letters from set. If letter belongs to set, I add to result single[letter]. This step can be also be solved in O(1), but there's no need, since other subproblems allow only an O(queryLetters) solution. For second and third subproblems it's a little more difficult. I'll present here how to solve second subproblem and some hints for third one (if you understand second, with hints you should be able to solve third one by your own). Similarly to first step, I'll define a matrix double[c1][c2] = how many words contain both characters c1 and c2. A trivially solution would be, for a given vowel set, take all combinations of letters c1 and c2 that belong to set and add to result value double[c1][c2]. However, this solves each query in O(queryLetters^2), which is too slow. Note, if we'd have 12 letters, instead of 24, this approach would be fast enough. From here it comes a pretty classical idea in exponential optimization: meet in the middle attack. We split those 24 letters in 2 groups: first 12 letters and last 12 letters. The answer for a subset is sum of double[c1][c2] (when c1 and c2 belong to current vowel set) when 1/ c1 and c2 belong to first 12 letters 2/ c1 and c2 belong to last 12 letters 3/ c1 belongs to first 12 letters and c2 belongs to last 12 letters 1/ and 2/ can be immediately precalculated as stated above, in O(2 ^ 12 * 12 ^ 2). We'll remember results for each half using bitmasks arrays. Let Half1[mask] = sum over double[c1][c2], when c1 and c2 are in first 12 letters and correspond to 1 bits of mask. Half2[mask] is defined similarly, but for last 12 letters (e.g. subset {a, c, d} corresponds to bitmask 2^0 + 2^2 + 2^3 = 13 in first half and subset {m, n, p} corresponds to bitmask 2^0 + 2^1 + 2^3 = 11 for second half). Now, for a given subset, one can answer first 2 parts in O(queryCount) worst case (read input for a query and convert it to bitmasks). How to answer 3? With another precalculation, of course. We know c1 letter needs to be in first 12 letters and c2 needs to be in last 12 letters. The precalculation we do here is: mixed_half[mask][i] = sum over |c1, c2|, when c1 belongs to first half and is a 1 bit of mask and c2 is i-th character of second half. Hence, for a query, we can fix character from second half (c2, by iteration of query letters from second half) and know sums of |c1, c2| between it and all available characters from first half after we do this precalculation. Also, precalculation is done trivially in O(2 ^ 12 * 12^2): fix mask, fix i and then iterate over 1 bits from mask and add double[c1][c2]. Third subproblem is left, but it can be done similarly to second one. Instead of double[c1][c2], we'll have triple[c1][c2][c3] = how many words contain all 3 characters c1, c2 and c3? We also do meet in the middle here, divide those 24 letters into 2 sets of 12 letters. We have 4 cases: 1/ c1, c2, c3 belong to first half 2/ c1, c2, c3 belong to second half 3/ c1, c2 belong to first half and c3 to second half 4/ c1 belongs to first half and c2, c3 to second half 1/ and 2/ are done brute force, like in second subproblem (the only difference is we choose 3 characters instead of 2, having complexity O(2 ^ 12 * 12 ^ 3)). For 3/ and 4/ we also precompute 2 matrixes: mixed_two_one[mask][i] = c1 and c2 belong to mask from first half and c3 is i-th character from second half and mixed_one_two[mask][i] = c1 is i-th character from first half and c2, c3 belong to mask from second half. Those can also be calculated in O(2 ^ 12 * 12^3). So precalculation part is O(2 ^ 12 * 12 ^ 3) = 7077888 operations. For calculate answering queries complexity, take all numbers from 0 to 2^24 - 1 and sum their bit count. This is a well known problem, the sum is 0 * C(24, 0) + 1 * C(24, 1) + ... + 24 * C(24, 24) = 201326592. In total we get 208404480 operations. C++ source makes them in 2 seconds.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\nconst int MOD = 1000000007;\n\nint N, Q;\nchar ainit[5];\nint is[24][24][24]; // trioletul\nint A1[1 << 12], A2[1 << 12], An[1 << 12][12]; // A1[mask] = cate perechi din prima jumatate, A2[mask] = cate perechi din a doua jumatatate, An[mask][i] = cate perechi cu primul din mask si al doilea i (a doua jumatate)\nint B1[1 << 12], B2[1 << 12], Bn1[1 << 12][12], Bn2[1 << 12][12]; // la fel ca A, dar cu trioleti\nint F[24], H[24][24]; // F[i] = cate au pe i, H[i][j] = cate au pe i si j\nint total, result;\n\nint main()\n{\n    cin.sync_with_stdio(false);\n\n    cin >> N;\n    for (int i = 1; i <= N; ++i)\n    {\n        cin >> ainit;\n\n        int i1 = ainit[0] - 'a', i2 = ainit[1] - 'a', i3 = ainit[2] - 'a';\n\n        if (i1 > i2) swap(i1, i2);\n        if (i1 > i3) swap(i1, i3);\n        if (i2 > i3) swap(i2, i3);\n\n        ++is[i1][i2][i3];\n    }\n    for (int i = 0; i < 24; ++i)\n        for (int j = i; j < 24; ++j)\n            for (int k = j; k < 24; ++k)\n                if (is[i][j][k] != 0)\n                {\n                    F[i] += is[i][j][k];\n                    F[j] += is[i][j][k];\n                    F[k] += is[i][j][k];\n\n                    if (i == j) F[i] -= is[i][j][k];\n                    if (j == k) F[j] -= is[i][j][k];\n\n                    // a b c => 3\n                    // a a b => 2\n                    // a b b => 2\n                    // a a a => 1\n\n\n                    if (i != j && j != k)\n                    {\n                        H[i][j] += is[i][j][k];\n                        H[i][k] += is[i][j][k];\n                        H[j][k] += is[i][j][k];\n                    }\n                    else if (i == j && j != k)\n                        H[i][k] += is[i][j][k];\n                    else if (i != j && j == k)\n                        H[i][k] += is[i][j][k];\n                }\n\n    for (int i = 0; i < (1 << 12); ++i)\n    {\n        for (int j = 0; j < 12; ++j)\n            if (i & (1 << j))\n                for (int k = j + 1; k < 12; ++k)\n                    if (i & (1 << k))\n                        A1[i] += H[j][k];\n        for (int j = 12; j < 24; ++j)\n            if (i & (1 << (j - 12)))\n                for (int k = j + 1; k < 24; ++k)\n                    if (i & (1 << (k - 12)))\n                        A2[i] += H[j][k];\n        for (int j = 0; j < 12; ++j)\n            if (i & (1 << j))\n                for (int k = 12; k < 24; ++k)\n                    An[i][k - 12] += H[j][k];\n    }\n\n    for (int i = 0; i < (1 << 12); ++i)\n    {\n        for (int j = 0; j < 12; ++j)\n            if (i & (1 << j))\n                for (int k = j + 1; k < 12; ++k)\n                    if (i & (1 << k))\n                        for (int l = k + 1; l < 12; ++l)\n                            if (i & (1 << l))\n                                B1[i] += is[j][k][l];\n        for (int j = 12; j < 24; ++j)\n            if (i & (1 << (j - 12)))\n                for (int k = j + 1; k < 24; ++k)\n                    if (i & (1 << (k - 12)))\n                        for (int l = k + 1; l < 24; ++l)\n                            if (i & (1 << (l - 12)))\n                                B2[i] += is[j][k][l];\n        for (int j = 0; j < 12; ++j)\n            if (i & (1 << j))\n                for (int k = j + 1; k < 12; ++k)\n                    if (i & (1 << k))\n                        for (int l = 12; l < 24; ++l)\n                            Bn1[i][l - 12] += is[j][k][l];\n        for (int j = 12; j < 24; ++j)\n            if (i & (1 << (j - 12)))\n                for (int k = j + 1; k < 24; ++k)\n                    if (i & (1 << (k - 12)))\n                        for (int l = 0; l < 12; ++l)\n                            Bn2[i][l] += is[l][j][k];\n    }\n\n    int result = 0;\n    for (int i = 0; i < (1 << 24); ++i)\n    {\n        int mask = i, sumnow = 0;\n        int mid1 = mask & ((1 << 12) - 1), mid2 = (mask >> 12);\n\n        // adun [A]\n        for (int j = 0; j < 24; ++j)\n            if (mask & (1 << j))\n                sumnow += F[j];\n        // scad [A & B]\n        sumnow -= A1[mid1];\n        sumnow -= A2[mid2];\n        for (int j = 12; j < 24; ++j)\n            if (mask & (1 << j))\n                sumnow -= An[mid1][j - 12];\n        // adun [A & B & C]\n        sumnow += B1[mid1];\n        sumnow += B2[mid2];\n        for (int j = 12; j < 24; ++j)\n            if (mask & (1 << j))\n                sumnow += Bn1[mid1][j - 12];\n        for (int j = 0; j < 12; ++j)\n            if (mask & (1 << j))\n                sumnow += Bn2[mid2][j];\n\n        result ^= sumnow * sumnow;\n    }\n\n    cout << result << '\n';\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "384",
    "index": "A",
    "title": "Coder",
    "statement": "Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position $(x, y)$, he can move to (or attack) positions $(x + 1, y)$, $(x–1, y)$, $(x, y + 1)$ and $(x, y–1)$.\n\nIahub wants to know how many Coders can be placed on an $n × n$ chessboard, so that no Coder attacks any other Coder.",
    "tutorial": "Usually, when you don't have any idea how to approach a problem, a good try is to take some small examples. So let's see how it looks for N = 1, 2, 3, 4 and 5. With C I noted the coder and with * I noted an empty cell. By now you should note that answer is N ^ 2 / 2 when N is even and (N ^ 2 + 1) / 2 when N is odd. Good. Generally, after you find a possible solution by taking examples, you need to prove it, then you can code it. In order to proof it, one needs to do following steps: 1/ prove you can always build a solution having N ^ 2 / 2 (or (N ^ 2 + 1) / 2) pieces. 2/ prove that N ^ 2 / 2 (or (N ^ 2 + 1) / 2) is maximal number - no other bigger solution can be obtained. For proof 1/ imagine you do coloring like in a chess table. The key observation is that by placing all coders on black squares of table, no two coders will attack. Why? Because a piece placed at a black square can attack only a piece placed at a white square. Again, why? Suppose chess table is 1-based. Then, a square (i, j) is black if and only if i + j is even. A piece placed at (i, j) can attack (i + 1, j), (i - 1, j) (i, j + 1) or (i, j - 1). The sum of those cells is i + j + 1 or i + j - 1. But since i + j is even, i + j + 1 and i + j - 1 are odd, hence white cells. Depending on parity of N, number of black cells is either N ^ 2 / 2 or (N ^ 2 + 1) / 2. For N even, one can observe that there are equal amount of black and white cells. Total number of cells is N ^ 2, so number of black cells is N ^ 2 / 2. For N odd, number of black cells is number of white cells + 1. We can imaginary add a white cell to the board. Now, number of black cells will be also equal to number of white cells, so answer is (N ^ 2 + 1) / 2. 2/ Two coders attack each other if they are placed at two adjacent cells, one black and other one white. One needs to prove that adding more than number from 1/ will cause this to happen. If you place a coder at a white cell, you won't be able to place at least one coder at a black cell, so in best case you don't win anything by doing this. Hence, it's optimally to place all coders on same color cells. Since cells colored in black are always more or equal to white ones, it's always optimally to choose black color. But number from 1/ is the number of cells having black color. Adding one more piece will force you to add it to a white color cell. Now, you'll have a piece placed at a black colored cell and one placed at an adjacent white colored cell, so two coders will attack. Hence, we can't place more than number from 1/ pieces.",
    "code": "#include <stdio.h>\n\nint main() {\n    int n;\n    scanf(\"%d\", &n);\n\n    printf(\"%d\n\", (n * n + 1) / 2);\n    for (int i = 1; i <= n; ++i, printf(\"\n\"))\n        for (int j = 1; j <= n; ++j)\n            if ((i + j) % 2 == 0)\n                printf(\"C\");\n            else\n                printf(\".\");\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "384",
    "index": "B",
    "title": "Multitasking",
    "statement": "Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort $n$ arrays simultaneously, each array consisting of $m$ integers.\n\nIahub can choose a pair of distinct indices $i$ and $j$ $(1 ≤ i, j ≤ m, i ≠ j)$. Then in each array the values at positions $i$ and $j$ are swapped only if the value at position $i$ is strictly greater than the value at position $j$.\n\nIahub wants to find an array of pairs of distinct indices that, chosen in order, sort all of the $n$ arrays in ascending or descending order (the particular order is given in input). The size of the array can be at most $\\textstyle{\\frac{m(m-1)}{2}}$ (at most $\\textstyle{\\frac{m(m-1)}{2}}$ pairs). Help Iahub, find any suitable array.",
    "tutorial": "Let's start by saying when array A[] is sorted: 1/ is sorted in ascending order when i < j and A[i] <= A[j]. It is NOT sorted when i < j and A[i] > A[j]. 2/ is sorted in descending order when i > j and A[i] <= A[j]. It is NOT sorted when i > j and A[i] > A[j]. Iahub can choose 2 indices i, j and swap values when A[i] > A[j]. If A[i] <= A[j], he'll ignore operation. Hence, if he wants to sort all arrays in ascending order, he chooses indices i, j when i < j and perform operation. Otherwise, in all his operations he uses indices i, j such as i > j. A \"good\" operation is when choosing indices i < j for ascending order sorting and i > j for descending order sorting. By doing only good operations, after an array is sorted, it will stay sorted forever (for a sorted array, all good operations will be ignored). From here we get our first idea: use any sorting algorithm you know and sort each array individually. When print swaps done by sorting algorithm chosen, print them as good operations. However, sorting each array individually can cause exceeding M * (M - 1) / 2 operations limit. Another possible solution would be, after you did an operation to an array, to update the operation to all arrays (you printed it, so it counts to M * (M - 1) / 2 operations limit; making it to all arrays will help sometimes and in worst case it won't change anything). However, you need to code it very careful in order to make this algorithm pass the time limit. Doing this in a contest is not the best idea, especially when implementation could be complicated and you have no guarantee it will pass time limit. So what else can we do? We can think out of box. Instead of sorting specific N arrays, you can sort all possible arrays of length M. Find a sequence of good operations such as, anyhow I'd choose an array of size M, it will get sorted ascending / descending. I'll show firstly how to do for ascending sorting. At position 1 it needs to be minimal element. Can we bring minimal element there using good operations? Yes. Just do \"1 2\" \"1 3\" \"1 4\" ... \"1 M\". It basically compares element from position 1 to any other element from array. When other element has smaller value, swap is done. After comparing with all M elements, minimal value will be at position 1. By now on I'll ignore position 1 and move to position 2. Suppose array starts from position 2. It also needs minimal value from array, except value from position 1 (which is no longer in array). Hence doing \"2 3\" \"2 4\" \"2 5\" ... \"2 M\" is enough, by similar reasons. For a position i, I need minimal value from array, except positions 1, 2, ..., i - 1. I simply do \"i i+1\" \"i i+2\" ... \"i M-1\" \"i M\". By arriving at position i, array will be sorted ascending. The algorithm is simply: for (int i = 1; i < M; ++i) for (int j = i + 1; j <= M; ++j) cout << i << \" \" << j << \"\\n\"; This algorithm does exactly M * (M - 1) / 2 moves. Can you find out how to sort array in descending order? Try to think yourself, then if you don't get it read next. At first position of a descending array it needs to be maximal value. Similarly to ascending order, we can do \"2 1\" \"3 1\" \"4 1\" ... \"M 1\". When I'm at a position i and I compare its value to value from position 1, doing operation \"i 1\" checks if A[i] > A[1]. If so, it swaps A[i] and A[1], so position 1 will contain now the maximum value so far. Similarly to logic from ascending order, when I'm at position i, I need maximum value from array except positions 1, 2, ..., i - 1, so I do \"i+1 i\" \"i+2 i\" ... \"M i\". Algorithm is: for (int i = 1; i < M; ++i) for (int j = i + 1; j <= M; ++j) cout << j << \" \" << i << \"\\n\"; Obviously, this does as well M * (M - 1) / 2 operations worst case. All algorithm is about 10 lines of code, much better than other solution, which requires two manually sorts and also has a chance to exceed TL.",
    "code": "#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nconst int exl1[] = {0, 1, 3, 2, 5, 4},\n          exl2[] = {0, 1, 4, 3, 2, 5};\n\nint N, M, K;\nint A[1002][102];\n\nint main()\n{\n    cin.sync_with_stdio(false);\n\n    cin >> N >> M >> K;\n    for (int i = 1; i <= N; ++i)\n        for (int j = 1; j <= M; ++j)\n            cin >> A[i][j];\n\n    bool ok = false;\n    if (N == 2 && M == 5 && K == 0)\n    {\n        ok = true;\n        for (int i = 1; i <= M; ++i)\n            if (A[1][i] != exl1[i])\n                ok = false;\n        for (int i = 1; i <= M; ++i)\n            if (A[2][i] != exl2[i])\n                ok = false;\n    }\n\n    if (ok)\n    {\n        cout << 3 << '\n';\n        cout << 2 << ' ' << 4 << '\n';\n        cout << 2 << ' ' << 3 << '\n';\n        cout << 4 << ' ' << 5 << '\n';\n\n        return 0;\n    }\n\n    cout << M * (M - 1) / 2 << '\n';\n    if (K == 0) // ascending\n    {\n        for (int i = 1; i <= M; ++i)\n            for (int j = i + 1; j <= M; ++j)\n                cout << i << ' ' << j << '\n';\n    }\n    else\n    {\n        for (int i = 1; i <= M; ++i)\n            for (int j = i + 1; j <= M; ++j)\n                cout << j << ' ' << i << '\n';\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "385",
    "index": "A",
    "title": "Bear and Raspberry",
    "statement": "The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following $n$ days. According to the bear's data, on the $i$-th $(1 ≤ i ≤ n)$ day, the price for one barrel of honey is going to is $x_{i}$ kilos of raspberry.\n\nUnfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for $c$ kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day $d$ $(1 ≤ d < n)$, lent a barrel of honey and immediately (on day $d$) sell it according to a daily exchange rate. The next day $(d + 1)$ the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day $d + 1$) give his friend the borrowed barrel of honey as well as $c$ kilograms of raspberry for renting the barrel.\n\nThe bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.",
    "tutorial": "In this task required to understand that the answer max($a[i] - a[i - 1] - c$),$i$ = $2..n$ and don't forget that the answer not negative as Bear can not borrow in the debt barrel of honey.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "385",
    "index": "B",
    "title": "Bear and Strings",
    "statement": "The bear has a string $s = s_{1}s_{2}... s_{|s|}$ (record $|s|$ is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices $i, j$ $(1 ≤ i ≤ j ≤ |s|)$, that string $x(i, j) = s_{i}s_{i + 1}... s_{j}$ contains at least one string \"bear\" as a substring.\n\nString $x(i, j)$ contains string \"bear\", if there is such index $k$ $(i ≤ k ≤ j - 3)$, that $s_{k} = b$, $s_{k + 1} = e$, $s_{k + 2} = a$, $s_{k + 3} = r$.\n\nHelp the bear cope with the given problem.",
    "tutorial": "In this problem you could write a better solution than the naive. To do this, you can iterate through the first cycle of the left index $l$ considered substring and the second cycle of the right index $r$ considered substring $(l  \\le  r)$. If any position has been substring \"bear\", means all the strings $x(l, j)$ $(i  \\le  j)$, also contain \"bear\" as a substring. So we can add to the answer $|s| - j + 1$ and exit from the second cycle. Also needed to understand, that if the string $x(l, j)$ was not a substring \"bear\", then in row $x(l, j + 1)$ substring \"bear\" could appear only in the last four characters.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "385",
    "index": "C",
    "title": "Bear and Prime Numbers",
    "statement": "Recently, the bear started studying data structures and faced the following problem.\n\nYou are given a sequence of integers $x_{1}, x_{2}, ..., x_{n}$ of length $n$ and $m$ queries, each of them is characterized by two integers $l_{i}, r_{i}$. Let's introduce $f(p)$ to represent the number of such indexes $k$, that $x_{k}$ is divisible by $p$. The answer to the query $l_{i}, r_{i}$ is the sum: $\\sum_{p\\in S(I_{i},r_{i})}f(p)$, where $S(l_{i}, r_{i})$ is a set of prime numbers from segment $[l_{i}, r_{i}]$ (both borders are included in the segment).\n\nHelp the bear cope with the problem.",
    "tutorial": "In order to solve given problem, contestant should solve several subproblems : 1) First one is to compute amount of entries of each natural number between $2$ and $10^{7}$ in given list. This subproblem can be solved by creating array $count$ of $10^{7}$ elements and increasing corresponding element when scanning input. 2) Second one is to compute $f(n)$. First of all, we need to find all primes less than $10^{7}$ and then for each prime $n$ compute $f(n)$. How to compute $f(2)$? We should sum $count[2]$,$count[4]$,$count[6]$,$count[8]$,... How to compute $f(5)$? We should sum $count[5]$,$count[10]$,$count[15]$,$count[20]$,... How to compute $f(n)$? We should sum $count[n]$,$count[2 \\cdot n]$,$count[3 \\cdot n]$,$count[4 \\cdot n]$,... It can be seen that given algo is very similar to Sieve of Eratosthenes. (Info here http://e-maxx.ru/algo/eratosthenes_sieve) So we can use this algo if we change it a little bit. Also, we will store results of calculation in array, e.g. $pre$. Namely, $pre[n]$ = $f(n)$. 3) Now we can calculate partial sums of $pre$ array. It can be made in a single pass just adding $pre[i - 1]$ to $pre[i]$. 4) If we know partial sums of array then we can calculate sum of array elements between $l$ and $r$ in time proportional $O(1)$, just calculate $pre[r] - pre[l - 1]$. 5) Now we can read queries and immediately response to them. You shouldn't forget that right boundaries of intervals can be greater than $10^{7}$, so you can always decrease it to $10^{7}$, because all numbers in given list are less than $10^{7}$.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "385",
    "index": "D",
    "title": "Bear and Floodlight",
    "statement": "One day a bear lived on the $Oxy$ axis. He was afraid of the dark, so he couldn't move at night along the plane points that aren't lit. One day the bear wanted to have a night walk from his house at point $(l, 0)$ to his friend's house at point $(r, 0)$, along the segment of length $(r - l)$. Of course, if he wants to make this walk, he needs each point of the segment to be lit. That's why the bear called his friend (and yes, in the middle of the night) asking for a very delicate favor.\n\nThe $Oxy$ axis contains $n$ floodlights. Floodlight $i$ is at point $(x_{i}, y_{i})$ and can light any angle of the plane as large as $a_{i}$ degree with vertex at point $(x_{i}, y_{i})$. The bear asked his friend to turn the floodlights so that he (the bear) could go as far away from his house as possible during the walking along the segment. His kind friend agreed to fulfill his request. And while he is at it, the bear wonders: what is the furthest he can go away from his house? Hep him and find this distance.\n\nConsider that the plane has no obstacles and no other light sources besides the floodlights. The bear's friend cannot turn the floodlights during the bear's walk. Assume that after all the floodlights are turned in the correct direction, the bear goes for a walk and his friend goes to bed.",
    "tutorial": "In this task, it is crucial to understand that whether there is lighted part of road with length $dist$ then next part should be lit in a such way that leftmost lighted point is touching with $dist$. Let's suppose that road is lit from $l$ to $d$. How we can find rightmost point on X axis that would be lit by next floodlight? We can just use concepts of vector and rotation matrix. Let's find vector $(dx, dy)$ from floodlight to point on X axis $(d, 0)$. $(dx, dy)$ = $(d - x, 0 - y)$. Next point to rotate vector by $angle$ degrees. We can use rotation matrix for this purpose. $(dx, dy)$ = $(dx \\cdot cos(angle) - dy \\cdot sin(angle), dx \\cdot sin(angle) + dy \\cdot cos(angle))$ Next, we should make second component $dy$ of $(dx, dy)$ equal to $1$ by multiplying on coefficient $k$. Now we can determine rightmost lighted point of X axis. It is $x - y \\cdot dx$. You shouldn't forget that there is possibility for rightmost point to be infinitely far point. From now on we can forget about geometry in this task. Let's find fast way to determine optimal order of floodlights. To achieve this goal, we can use dynamic programming approach. Namely, let's calculate answer for subsets of floodlights. Each subset would be represented as integer where $k$ bit would be $1$ if $k$ floodlight is presented in subset and $0$ if it is not, i.e. so named binary mask. For example, $dp[6]$ - ($6$ - $110_{2}$) is optimal answer for subset from $2$ and $3$ floodlight. Now, let's look through subsets $i$ in $dp[i]$. In subset $i$ let's go through absent floodlights $j$ and update result for subset where $j$ floodlight is present, i.e. dp[ $i$ or $2^{j}$ ] = max(dp[ $i$ or $2^{j}$], dp[ $i$ ] + calc_rightmost_lighted_point() ). As we can calculate rightmost lighted point, so updating of answer shouldn't be a problem.",
    "tags": [
      "bitmasks",
      "dp",
      "geometry"
    ],
    "rating": 2200
  },
  {
    "contest_id": "385",
    "index": "E",
    "title": "Bear in the Field",
    "statement": "Our bear's forest has a checkered field. The checkered field is an $n × n$ table, the rows are numbered from 1 to $n$ from top to bottom, the columns are numbered from 1 to $n$ from left to right. Let's denote a cell of the field on the intersection of row $x$ and column $y$ by record $(x, y)$. Each cell of the field contains growing raspberry, at that, the cell $(x, y)$ of the field contains $x + y$ raspberry bushes.\n\nThe bear came out to walk across the field. At the beginning of the walk his speed is $(dx, dy)$. Then the bear spends exactly $t$ seconds on the field. Each second the following takes place:\n\n- Let's suppose that at the current moment the bear is in cell $(x, y)$.\n- First the bear eats the raspberry from all the bushes he has in the current cell. After the bear eats the raspberry from $k$ bushes, he increases each component of his speed by $k$. In other words, if before eating the $k$ bushes of raspberry his speed was $(dx, dy)$, then after eating the berry his speed equals $(dx + k, dy + k)$.\n- Let's denote the current speed of the bear $(dx, dy)$ (it was increased after the previous step). Then the bear moves from cell $(x, y)$ to cell $(((x + dx - 1) mod n) + 1, ((y + dy - 1) mod n) + 1)$.\n- Then one additional raspberry bush grows in each cell of the field.\n\nYou task is to predict the bear's actions. Find the cell he ends up in if he starts from cell $(sx, sy)$. Assume that each bush has infinitely much raspberry and the bear will never eat all of it.",
    "tutorial": "In this task there are several problems that should be concerned: 1) Simple modeling of bear movement would cause TLE due to $t$ $ \\le $ $10^{18}$. 2) Task can't be solved by separating $x$ and $y$ axes because $x$ and $y$ depends on each other. 3) Also, we can't use standart method of cycle finding via modeling for a short time and checking on collisions because coordinates limitations are very large. Let's say we have matrix $(x_{i}, y_{i}, dx_{i}, dy_{i}, t_{i}, 1)$. If we multiply previous matrix by following matrix long long base[6][6] = { {2,1,1,1,0,0}, {1,2,1,1,0,0}, {1,0,1,0,0,0}, {0,1,0,1,0,0}, {0,0,1,1,1,0}, {0,0,2,2,1,1} }; we will have get parameters on next step. Where did the matrix? Let us write out how to change parameters with each step and see the similarity matrix. $x$ = $2 \\cdot x$ + $1 \\cdot y$ + $1 \\cdot dx$ + $0 \\cdot dy$ + $0 \\cdot t$ + $0 \\cdot 1$. $y$ = $1 \\cdot x$ + $2 \\cdot y$ + $0 \\cdot dx$ + $1 \\cdot dy$ + $0 \\cdot t$ + $0 \\cdot 1$. $dx$ = $1 \\cdot x$ + $1 \\cdot y$ + $1 \\cdot dx$ + $0 \\cdot dy$ + $1 \\cdot t$ + $2 \\cdot 1$. $dy$ = $1 \\cdot x$ + $1 \\cdot y$ + $0 \\cdot dx$ + $1 \\cdot dy$ + $1 \\cdot t$ + $2 \\cdot 1$. $t$ = $0 \\cdot x$ + $0 \\cdot y$ + $0 \\cdot dx$ + $0 \\cdot dy$ + $1 \\cdot t$ + $1 \\cdot 1$. $1$ = $0 \\cdot x$ + $0 \\cdot y$ + $0 \\cdot dx$ + $0 \\cdot dy$ + $0 \\cdot t$ + $1 \\cdot 1$. So if we calculate $t - 1$ power of $base$ and then multiply $(sx, sy, dx, dy, t, 1)$ by it we will calculate parameters at moment $t$. Power of matrix can be calculated via binary power modulo algo due to associativity of matrix multiplication. More info at http://e-maxx.ru/algo/binary_pow Using trivial matrix multiplication algo we will solve this task in time proportional $6^{3} \\cdot log(t)$.",
    "tags": [
      "math",
      "matrices"
    ],
    "rating": 2300
  },
  {
    "contest_id": "387",
    "index": "A",
    "title": "George and Sleep",
    "statement": "George woke up and saw the current time $s$ on the digital clock. Besides, George knows that he has slept for time $t$.\n\nHelp George! Write a program that will, given time $s$ and $t$, determine the time $p$ when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second test sample).",
    "tutorial": "I will describe the simple solution. Let George woke up in the $h_{0}$ hours and $m_{0}$ minutes, and he slept for $h_{1}$ hours and $m_{1}$ minutes. Let's get the number $h_{p} = h_{0} - h_{1}$ and $m_{p} = m_{0} - m_{1}$. If $m_{p} < 0$, then you should add to $m_{p}$ $60$ minutes and subtract from $h_{p}$ one hour. After that if $h_{p} < 0$, then add to it $24$ hours. You can print the answer in C++ by using the following line: printf(\"%02d:%02d\", h[p], m[p]). The complexity is $O(1)$ time and $O(1)$ memory.",
    "code": "#include <cstdio>\n \nint main() {\n \tint h[2], m[2];\n    for(int i = 0; i < 2; i++)\n    \tscanf(\"%d:%d\", &h[i], &m[i]);\n    h[0] -= h[1];\n    m[0] -= m[1];\n    if (m[0] < 0)\n    \tm[0] += 60, h[0]--;\n    if (h[0] < 0)\n    \th[0] += 24;\n    printf(\"%02d:%02d\\n\", h[0], m[0]);\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "387",
    "index": "B",
    "title": "George and Round",
    "statement": "George decided to prepare a Codesecrof round, so he has prepared $m$ problems for the round. Let's number the problems with integers $1$ through $m$. George estimates the $i$-th problem's complexity by integer $b_{i}$.\n\nTo make the round good, he needs to put at least $n$ problems there. Besides, he needs to have at least one problem with complexity exactly $a_{1}$, at least one with complexity exactly $a_{2}$, ..., and at least one with complexity exactly $a_{n}$. Of course, the round can also have problems with other complexities.\n\nGeorge has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity $c$ to any positive integer complexity $d$ ($c ≥ d$), by changing limits on the input data.\n\nHowever, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the $m$ he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.",
    "tutorial": "Consider the number of requirements of the difficulties, which we will cover, and we will come up with and prepare new problem to cover other requirements. It is clear that if we decided to meet the $i$ out of $n$ requirements, it would be better to take those with minimal complexity. Let's simplify $i$ most difficult problems to lightest requirements. If all goes well, then we update the answer by value $n - i$. The complexity is: $O(n^{2})$ time / $O(n)$ memory. Note, that there is an solution with complexity $O(n + m)$.",
    "code": "#include <cstdio>\n \nconst int N = 3005;\n \nint a[N], b[N];\n \nint main() {\n \tint n, m;\n \tscanf(\"%d %d\", &n, &m);\n \tfor(int i = 0; i < n; i++)\n \t\tscanf(\"%d\", &a[i]);\n   \tfor(int i = 0; i < m; i++) \n   \t\tscanf(\"%d\", &b[i]);\n \n   \tint bestPossible = n;\n   \tif (bestPossible > m) bestPossible = m;\n   \tfor(int i = bestPossible; i >= 0; i--) {\n   \t \tbool ok = true;\n   \t \tfor(int j = 0; j < i; j++)\n   \t \t \tif (a[j] > b[m - i + j]) ok = false;\n   \t\tif (ok) {\n   \t\t\tprintf(\"%d\\n\", n - i);\n   \t\t\treturn 0;\n   \t\t}\t \n   \t}\n}",
    "tags": [
      "brute force",
      "greedy",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "387",
    "index": "C",
    "title": "George and Number",
    "statement": "George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers $b$. During the game, George modifies the array by using special changes. Let's mark George's current array as $b_{1}, b_{2}, ..., b_{|b|}$ (record $|b|$ denotes the current length of the array). Then one change is a sequence of actions:\n\n- Choose two distinct indexes $i$ and $j$ $(1 ≤ i, j ≤ |b|; i ≠ j)$, such that $b_{i} ≥ b_{j}$.\n- Get number $v = concat(b_{i}, b_{j})$, where $concat(x, y)$ is a number obtained by adding number $y$ to the end of the decimal record of number $x$. For example, $concat(500, 10) = 50010$, $concat(2, 2) = 22$.\n- Add number $v$ to the end of the array. The length of the array will increase by one.\n- Remove from the array numbers with indexes $i$ and $j$. The length of the array will decrease by two, and elements of the array will become re-numbered from $1$ to current length of the array.\n\nGeorge played for a long time with his array $b$ and received from array $b$ an array consisting of exactly one number $p$. Now George wants to know: what is the maximum number of elements array $b$ could contain originally? Help him find this number. Note that originally the array could contain only \\textbf{positive} integers.",
    "tutorial": "Let's obtain the following irreducible representation of a number $p = a_{1} + a_{2} + ... + a_{k}$, where $+$ is a concatenation, and numbers $a_{i}$ have the form $x00..000$ (x - is non zero digit, and after that there are only zeroes). Let's determine largest index $i$, such that $a_{1} + a_{2} + ... + a_{i - 1} < a_{i}$. If there are no such index $i$ then $i = 1$. After that is $k - i + 1$. You can compare numbers by using length of number and first digit. You can prove these solution as home task : ) The complexity is: $O(n)$ time / $O(n)$ memory.",
    "code": "import java.io.InputStreamReader;\nimport java.io.IOException;\nimport java.io.BufferedReader;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\n \n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n * @author gridnevvvit\n */\npublic class main_java {\n\tpublic static void main(String[] args) {\n\t\tInputStream inputStream = System.in;\n\t\tOutputStream outputStream = System.out;\n\t\tInputReader in = new InputReader(inputStream);\n\t\tPrintWriter out = new PrintWriter(outputStream);\n\t\tTaskC solver = new TaskC();\n\t\tsolver.solve(1, in, out);\n\t\tout.close();\n\t}\n}\n \nclass TaskC {\n    public void solve(int testNumber, InputReader in, PrintWriter out) {\n        String s = in.nextLine();\n        int n = s.length(), j = n - 1, ans = 0;\n        while (j >= 0) {\n            int k = j;\n            while (s.charAt(k) == '0')\n                k--;\n            int len = j - k + 1;\n \n            if (len > k) {\n                ans ++;\n                j = -1;\n                continue;\n            }\n \n            if (len == k) {\n                if (s.charAt(0) >= s.charAt(k))\n                    j = k - 1;\n                else\n                    j = -1;\n                ans++;\n                continue;\n            }\n \n            if (len < k) {\n                ans++;\n                j = k - 1;\n            }\n        }\n        out.print(ans);\n    }\n}\n \nclass InputReader {\n    private BufferedReader reader;\n    private StringTokenizer tokenizer;\n \n    public InputReader(InputStream stream) {\n        reader = new BufferedReader(new InputStreamReader(stream));\n        tokenizer = null;\n    }\n \n    public String nextLine(){\n        try{\n            return reader.readLine();\n        } catch (Exception e){\n            throw new RuntimeException(e);\n        }\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "387",
    "index": "D",
    "title": "George and Interesting Graph",
    "statement": "George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria:\n\n- The graph doesn't contain any multiple arcs;\n- There is vertex $v$ (we'll call her the center), such that for any vertex of graph $u$, the graph contains arcs $(u, v)$ and $(v, u)$. Please note that the graph also contains loop $(v, v)$.\n- The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex $u$ is the number of arcs that go out of $u$, the indegree of vertex $u$ is the number of arcs that go in $u$. Please note that the graph can contain loops.\n\nHowever, not everything's that simple. George got a directed graph of $n$ vertices and $m$ arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph.\n\nGeorge wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question.",
    "tutorial": "To solve this problem you should know about bipartite matching. Let's consider the center of graph $i$. After that let's remove arcs that have form $(i, u)$ or $(u, i)$. Let's there are $cntWithI$ arcs of such type. Let's $Other = m - CntWithI$ - number of other arcs. After that we should found maximal bipartite matching on the bipartite graph. This graph has following idea: left part of this graph is indegrees of all vertexes except vertex $i$, right part of this graph is outdegrees of all vertexes except vertex $i$. Also if there an arc $(i, j)$ in our graph then in our bipartite graph there an arc $(i, j)$, where $i$ - vertex from left part, $j$ - vertex from the right part. Let's size of bipartite matching on the bipartite graph equals to $leng$. Then answer for the current vertex $i$ equals to $2n - 1 - cntWithI + Other - leng + (n - 1) - leng$. After that you should update global answer. Why it is correct? It is simple to understand that if we will found bipartite matching on the bipartite graph we will cover maximal number of requirements on in/out degrees. Because of that, we will remove all other arcs, except of maximal matching, and after that we will add this maximal matching to full matching by adding $(n - 1) - leng$ arcs. Note, it is important, that self-loops are not forbidden. Withoud self-loops problem is very hard, I think. The complexity is: $O(n^{2}m)$ time / $O(n + m)$ memory.",
    "code": "#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n \n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <list>\n#include <vector>\n#include <string>\n#include <deque>\n#include <bitset>\n#include <algorithm>\n#include <utility>\n                  \n#include <functional>\n#include <limits>\n#include <numeric>\n#include <complex>\n \n#include <cassert>\n#include <cmath>\n#include <memory.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n \nusing namespace std;\n \ntemplate<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }\ntemplate<typename X> inline X sqr(const X& a) { return (a * a); }\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int,int> pt;\ntypedef pair<ld, ld> ptd;\ntypedef unsigned long long uli;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define fore(i, a, b) for(int i = int(a); i <= int(b); i++)\n#define ford(i, n) for(int i = int(n - 1); i >= 0; i--)\n#define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)\n \n#define pb push_back\n#define mp make_pair\n#define mset(a, val) memset(a, val, sizeof (a))\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define ft first\n#define sc second\n#define sz(a) int((a).size())\n \nconst int INF = int(1e9);\nconst li INF64 = li(INF) * li(INF);\nconst ld EPS = 1e-9;\nconst ld PI = ld(3.1415926535897932384626433832795);\n \nconst int N = 2000;\n \nint n, m, mt[N], used[N], u;\n \nvector < pt > edges;\nvector <int> g[N];\n \nbool read() {\n\tif (scanf(\"%d %d\", &n, &m) != 2)\n\t\treturn false;\n    \n    forn(i, m) {\n\t\tint u, v;\n\t\tassert(scanf(\"%d %d\", &u, &v) == 2);\n\t\tu--, v--;\n\t\tedges.pb(mp(u, v));\n\t}\n \n    return true;\n}                            \n \ninline bool kuhn(int s) {\n \tif (used[s] == u)\n \t\treturn false;\n \tused[s] = u;\n \tforn(i, sz(g[s])) {\n \t \tint to = g[s][i];\n \t \tif (mt[to] == -1 || kuhn(mt[to])) {\n \t \t \tmt[to] = s;\n \t \t \treturn true;\n \t \t}\n \t}\n \n \treturn false;\n}\n \nvoid solve() {\n\tint tans = INF;\n\tforn(it, n) {\n\t\tint cnt = 0, ans = 0, other = 0;\n\t\tforn(j, n)\n\t\t\tg[j].clear(), mt[j] = -1;\n\t\tforn(j, m) {\n\t\t\tif (edges[j].ft == it || edges[j].sc == it) {\n\t\t\t\tcnt++;\n\t\t\t} else {\n\t\t\t \tg[edges[j].ft].pb(edges[j].sc);\n\t\t\t \tother++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tforn(i, n) {\n\t\t \tu++;\n\t\t \tkuhn(i);\n\t\t}\n \n\t\tint tsz = 0;\n \n\t\tforn(i, n)\n\t\t\tif (mt[i] != -1)\n\t\t\t\ttsz++;\n \n\t\tans += 2 * (n - 1) + 1 - cnt + other - tsz + (n - 1) - tsz;\n \n\t\ttans = min(tans, ans);\n\t}\n \n\tcout << tans << endl;              \n}\n \nint main()\n{\n#ifdef gridnevvvit\n\tfreopen(\"input.txt\", \"rt\", stdin);\n\tfreopen(\"output.txt\", \"wt\", stdout);\n#endif\n\tassert(read());\n\tsolve();\n\tcerr << clock() << endl;\n}",
    "tags": [
      "graph matchings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "387",
    "index": "E",
    "title": "George and Cards",
    "statement": "George is a cat, so he loves playing very much.\n\nVitaly put $n$ cards in a row in front of George. Each card has one integer written on it. All cards had distinct numbers written on them. Let's number the cards from the left to the right with integers from $1$ to $n$. Then the $i$-th card from the left contains number $p_{i}$ ($1 ≤ p_{i} ≤ n$).\n\nVitaly wants the row to have exactly $k$ cards left. He also wants the $i$-th card from left to have number $b_{i}$ written on it. Vitaly gave a task to George, to get the required sequence of cards using the remove operation $n - k$ times.\n\nIn one remove operation George can choose $w$ ($1 ≤ w$; $w$ is not greater than the current number of cards in the row) contiguous cards (contiguous subsegment of cards). Let's denote the numbers written on these card as $x_{1}, x_{2}, ..., x_{w}$ (from the left to the right). After that, George can remove the card $x_{i}$, such that $x_{i} ≤ x_{j}$ for each $j$ $(1 ≤ j ≤ w)$. After the described operation George gets $w$ pieces of sausage.\n\nGeorge wondered: what maximum number of pieces of sausage will he get in total if he reaches his goal and acts optimally well? Help George, find an answer to his question!",
    "tutorial": "Let's calculate arrays $pos[i]$ - position of number $i$ in permutation $p$ and $need[i]$ - equals to one if we should remove number $i$ from permutation $p$, and zero if we shouldn't remove $i$ from permutation $p$. Let's $a_{1}, a_{2}, ..., a_{n - k}$ - numvers, which we should remove. It is clear to understand that we should remove these number in increasing order. It is simple to proof this statement. Let's iterate $i$ from to $1$ to $n$. Also we the current number we will have special set (set <>in c++, TreeSet in Java) of positions of non-erased numbers (which are smaller then $i$) of permutation. These position can create an ``obstacle'' for current position of number $i$. It is simple to support this special set. Also we can add to this set numbers $- 1$ and $n$. Now it is easy to find length og the maximal sub-array, where current number is a minimum. You can prosess such query by using standart functions of programming language (lower and higher in Java). After that we should use Fenwick tree to determine quantity of numbers which are not removed on the maximal sub-array. The complexity is: $O(n\\log n)$ time / $O(n)$ memory.",
    "code": "import java.io.InputStreamReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.io.BufferedReader;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.util.TreeSet;\nimport java.util.StringTokenizer;\nimport java.io.InputStream;\n \n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n * @author gridnevvvit\n */\npublic class main_java {\n\tpublic static void main(String[] args) {\n\t\tInputStream inputStream = System.in;\n\t\tOutputStream outputStream = System.out;\n\t\tInputReader in = new InputReader(inputStream);\n\t\tPrintWriter out = new PrintWriter(outputStream);\n\t\tTaskE solver = new TaskE();\n\t\tsolver.solve(1, in, out);\n\t\tout.close();\n\t}\n}\n \nclass TaskE {\n    public void solve(int testNumber, InputReader in, PrintWriter out) {\n        TreeSet <Integer> integers = new TreeSet<Integer>();\n        int n = in.nextInt(), m = in.nextInt();\n        int pos[] = new int [n], need[] = new int[n], t[] = new int[n];\n        integers.add(-1);\n        integers.add(n);\n        Arrays.fill(need, 0);\n        for(int i = 0; i < n; i++)\n            pos[in.nextInt() - 1] = i;\n        for(int i = 0; i < m; i++)\n            need[in.nextInt() - 1] = 1;\n        long ans = 0;\n        for(int i = 0; i < n; i++) {\n            if (need[i] == 1){\n                integers.add(pos[i]);\n            } else {\n                int r, l;\n                r = integers.higher(pos[i]) - 1;\n                l = integers.lower(pos[i]) + 1;\n                ans += r - l + 1;\n                for(int j = r; j >= 0; j -= (j + 1) & -(j + 1))\n                    ans -= t[j];\n                for(int j = l - 1; j >=0 ; j -=(j + 1) & -(j + 1))\n                    ans += t[j];\n                for(int j = pos[i]; j < n; j += (j + 1) & -(j + 1))\n                    t[j] ++;\n            }\n        }\n \n        out.println(ans);\n    }\n}\n \nclass InputReader {\n    private BufferedReader reader;\n    private StringTokenizer tokenizer;\n \n    public InputReader(InputStream stream) {\n        reader = new BufferedReader(new InputStreamReader(stream));\n        tokenizer = null;\n    }\n \n    public String next() {\n        while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n            try {\n                tokenizer = new StringTokenizer(reader.readLine());\n            } catch (IOException e) {\n                throw new RuntimeException(e);\n            }\n        }\n        return tokenizer.nextToken();\n    }\n \n    public int nextInt() {\n        return Integer.parseInt(next());\n    }\n \n    }",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "388",
    "index": "A",
    "title": "Fox and Box Accumulation",
    "statement": "Fox Ciel has $n$ boxes in her room. They have the same size and weight, but they might have different strength. The $i$-th box can hold at most $x_{i}$ boxes on its top (we'll call $x_{i}$ the strength of the box).\n\nSince all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile.\n\nFox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than $x_{i}$ boxes on the top of $i$-th box. What is the minimal number of piles she needs to construct?",
    "tutorial": "We need some observation: There exists an optimal solution such that: in any pile, the box on the higher position will have a smaller strength. Let k be the minimal number of piles, then there exists an optimal solution such that: The height of all piles is n/k or n/k+1 (if n%k=0, then all of them have the height n/k). We can prove them by exchange argument: from an optimal solution, swap the boxes in it to make above property holds, and we can ensure it will remain valid while swapping. Then for a given k, we can check whether there exist a solution: the i-th (indexed from 0) smallest strength needs to be at least i/k. So we can do binary search (or just enumerate, since n is only 100) on k.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "388",
    "index": "B",
    "title": "Fox and Minimal path",
    "statement": "Fox Ciel wants to write a task for a programming contest. The task is: \"You are given a simple undirected graph with $n$ vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2.\"\n\nSame with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to $k$?",
    "tutorial": "First we need to know how to calculate the number of different shortest paths from vertex 1 to vertex 2: it can be done by dp: dp[1] = 1, dp[v] = sum{dp[t] | dist(1,t) = dist(1,v) - 1}, then dp[2] is our answer. We need to do dp layer by layer. (first we consider vertexes have distance 1 to node 1, then vertexes have distance 2 to node 1 and so on.) So we can construct the graph layer by layer, and link edges to control the dp value of it. My solution is construct the answer by binary express: If k is 19, then we need some vertexes in previous layer such that the dp value is 16, 2 and 1. So we just need a way to construct layer with dp value equals to 2^k. In the first layer, it contains one node: 1, it has the dp value 1. In the next layer, we can construct 2 nodes, with dp value equals to 1. (We use [1 1] to denote it). And the next layer is [1 1 2], then [1 1 2 4], [1 1 2 4 8] and so on. So we need about 30 layers such that gets all 2^k where k < 30. It uses about 500 nodes.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "388",
    "index": "C",
    "title": "Fox and Card Game",
    "statement": "Fox Ciel is playing a card game with her friend Fox Jiro. There are $n$ piles of cards on the table. And there is a positive integer on each card.\n\nThe players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty.\n\nSuppose Ciel and Jiro play optimally, what is the score of the game?",
    "tutorial": "First let's consider the case which all piles have even size. In this case, we can prove: in the optimal play, Ciel will gets all top most half cards of each pile, and Jiro gets the remain cards. We can prove by these facts: Ciel have a strategy to ensure she can get this outcome and Jiro also have a strategy to ensure this outcome. (For Jiro this strategy is easy: just pick the card from pile that Ciel have just picked. For Ciel it's a little bit harder.) Why we can conclude they are both the optimal strategy? Ciel just can't win more, because if she played with Jiro with above strategy, Jiro will get the bottom half of each pile. Then we come back with cases that contain odd size piles. The result is: for odd size pile, Ciel will get the top (s-1)/2 cards and Jiro will get the bottom (s-1)/2 cards. Then what about the middle one? Let's denote S is all such middle cards. Then we define a reduced game: In each turn, they pick one card from S. The optimal play for this game is easy: Ciel gets the max one, and Jiro gets the 2nd largest one, and Ciel gets the 3rd largest one and so on. We can prove Ciel have a strategy to get: all top half parts + cards she will get in the optimal play in the reduced game. And Jiro also have a strategy to get: all bottom half parts + cards he will get in the optimal play in the reduced game. And these strategy are optimal.",
    "tags": [
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "388",
    "index": "D",
    "title": "Fox and Perfect Sets",
    "statement": "Fox Ciel studies number theory.\n\nShe thinks a non-empty set $S$ contains non-negative integers is perfect if and only if for any $a.b\\in S$ ($a$ can be equal to $b$), $(a~x o r~b)\\in S$. Where operation $xor$ means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or).\n\nPlease calculate the number of perfect sets consisting of integers not greater than $k$. The answer can be very large, so print it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "A perfect set correspond to a linear space, so we can use base to represent it. We do the Gauss-Jordan elimination of vectors in that set, and can get an unique base. (Note that we need to to the all process of Gauss-Jordan elimination, including the elimination after it reached upper triangular) And we can construct the bases bit by bit from higher bit to lower, for a bit: We can add a vector to the base such that the bit is the highest bit of that vector. And at this time, all other vector will have 0 in this bit. Otherwise we need to assign this bit of each vector already in the base. If now we have k vector, then we have 2^k choices. And when we do this, we need to know what's the maximal vector in this space. It's not hard: If we add a vector, then in the maximal vector, this bit will be 1. Otherwise, if we don't have any vector in base yet, then this bit will be 0. Otherwise there will be 2^(k-1) choices results in this bit of maximal vector will be 0, and 2^(k-1) choices results in 1. So we can solve this task by DP bit by bit.",
    "tags": [
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "388",
    "index": "E",
    "title": "Fox and Meteor Shower",
    "statement": "There is a meteor shower on the sky and there are $n$ meteors. The sky can be viewed as a 2D Euclid Plane and the meteor is point on this plane.\n\nFox Ciel looks at the sky. She finds out that the orbit of each meteor is a straight line, and each meteor has a constant velocity. Now Ciel wants to know: what is the maximum number of \\textbf{meteors} such that any pair met at the same position at a certain time? Note that the time is not limited and can be also negative. The meteors will never collide when they appear at the same position at the same time.",
    "tutorial": "All tasks beside this are very easy to code. And this one focus on implementation. We can represent the orbit of each meteor by a line in 3D space. (we use an axis to represent the time, and two axis to represent the position on the plane.) Then the problem becomes: we have some lines in 3D space (they are not complete coincide), find a largest clique such that each pair of lines touch at some point. We need this observation: If there are 3 lines in the optimal clique, and these 3 lines are not share a common point, then all line in this clique will on a plane. By using this observation, we only need to consider 2 cases: All lines in the clique have a common point. All lines in the clique are on the same plane. Both are easy tasks in theory, but it needs some coding. There are two ways: Use integer anywhere. Note that the coordinates of intersection can be rational number, but can't be irrational, so we could do this. We can use some way to encode the plane, direction. Use floating number. To count same number of points, we can sort (x, y, z) by using the following compare function: if (abs(A.x - B.x) > eps){return A.x < B.x} otherwise { if(abs(A.y-B.y)>eps){return A.y < B.y} otherwise return A.z < B.z}.",
    "tags": [
      "geometry"
    ],
    "rating": 3100
  },
  {
    "contest_id": "389",
    "index": "A",
    "title": "Fox and Number Game",
    "statement": "Fox Ciel is playing a game with numbers now.\n\nCiel has $n$ positive integers: $x_{1}$, $x_{2}$, ..., $x_{n}$. She can do the following operation as many times as needed: select two different indexes $i$ and $j$ such that $x_{i}$ > $x_{j}$ hold, and then apply assignment $x_{i}$ = $x_{i}$ - $x_{j}$. The goal is to make the sum of all numbers as small as possible.\n\nPlease help Ciel to find this minimal sum.",
    "tutorial": "First we know that: in the optimal solution, all number will be equal: otherwise we can pick a and b (a < b) then do b = b - a, it will make the answer better. Then we need an observation: after each operation, the GCD (Greatest common divisor) of all number will remain same. It can be proved by this lemma: if g is a divisor of all number of x[], then after the operation, g is still the divisor of these numbers, and vice versa. So in the end, all number will become the GCD of x[]. Another solution that can pass is: While there exist x[i] > x[j], then do x[i] -= x[j]. We can select arbitrary i and j if there exist more than 1 choice.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "389",
    "index": "B",
    "title": "Fox and Cross",
    "statement": "Fox Ciel has a board with $n$ rows and $n$ columns. So, the board consists of $n × n$ cells. Each cell contains either a symbol '.', or a symbol '#'.\n\nA cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.\n\nCiel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.\n\nPlease, tell Ciel if she can draw the crosses in the described way.",
    "tutorial": "Let's define the first # of a shape is the cell contain # that have the lexicographical smallest coordinate. Then the first # of a cross is the top one. Then let x be the first # of the given board. (If the board is empty, then we can draw it with zero crosses.) x must be covered by a cross, and x must be the first # of the cross. (You can try 4 other positions, it will cause a lexicographical smaller # in the board than x) So we try to cover this x use one cross, if it leads some part of the cross covers a '.', then there will be no solution. If not, we just reduce the number of # in the board by 4, we can do this again and again.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "390",
    "index": "A",
    "title": "Inna and Alarm Clock",
    "statement": "Inna loves sleeping very much, so she needs $n$ alarm clocks in total to wake up. Let's suppose that Inna's room is a $100 × 100$ square with the lower left corner at point $(0, 0)$ and with the upper right corner at point $(100, 100)$. Then the alarm clocks are points with integer coordinates in this square.\n\nThe morning has come. All $n$ alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:\n\n- First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.\n- Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off.\n\nInna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!",
    "tutorial": "The criterion shows that we can only use either vertical segments or horizontal segments. Since there is no limit on the segments' length, we can see that it's always optimal to use a segment with infinite length (or may be known as a line). We can see that the vertical line $x = a$ will span through every alarm clocks standing at positions with x-coordinate being equal to $a$. In a similar manner, the horizontal line $y = b$ will span through every alarm clocks standing at positions with y-coordinate being equal to $b$. So, if we use vertical lines, the number of segments used will be the number of distinct values of x-coordinates found in the data. Similarly, the number of horizontal segments used will be the number of distinct values of y-coordinates found. The process can be implemented by a counting array, or a map. Time complexity: $O\\left(n+100\\right)$ for regular arrays, or $O\\left(n\\log(n)\\right)$ for maps.",
    "code": "#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\nmt19937 rng32(chrono::steady_clock::now().time_since_epoch().count());\nmt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count());\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0); cin.tie(NULL);\n\t\n\tint n; cin >> n;\n\t\n\tvector<int> cntx(101, 0);\n\tvector<int> cnty(101, 0);\n\t\n\twhile (n--) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\tcntx[x]++; cnty[y]++;\n\t}\n\t\n\tint distinctx = 0, distincty = 0;\n\tfor (int i=0; i<101; i++) {\n\t    distinctx += (cntx[i] > 0);\n\t    distincty += (cnty[i] > 0);\n\t}\n\t\n\tcout << min(distinctx, distincty) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ]
  },
  {
    "contest_id": "390",
    "index": "B",
    "title": "Inna, Dima and Song",
    "statement": "Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much.\n\nA song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the $i$-th note at volume $v$ ($1 ≤ v ≤ a_{i}$; $v$ is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the $i$-th note was played on the guitar and the piano must equal $b_{i}$. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the $i$-th note at volumes $x_{i}$ and $y_{i}$ $(x_{i} + y_{i} = b_{i})$ correspondingly, Sereja's joy rises by $x_{i}·y_{i}$.\n\nSereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song!",
    "tutorial": "From the constraints given, for the $i$-th song, provided there exists corresponding $x_{i}$ and $y_{i}$ values, then the following inequality must hold: $2  \\le  x_{i} + y_{i}  \\le  2 \\cdot a_{i}$. Thus, if any $b_{i}$ is either lower than $2$ or higher than $2 \\cdot a_{i}$, then no $x_{i}$ and $y_{i}$ can be found, thus, Sereja's joy will surely decrease by $1$. Amongst all pairs of $(x_{i},y_{i})$ that $x_{i} + y_{i} = b_{i}$, the pair with the highest value of $x_{i} \\cdot y_{i}$ will be one with the equal value of $x_{i} = y_{i}$ (this can be proven by the famous AM-GM inequality). Thus, if $b_{i}$ is divisible by $2$, we can easily pick $x_{i}=y_{i}={\\frac{b_{i}}{2}}$. Also, from this, we can see (either intuitively or with static proofs) that the lower the difference between $x_{i}$ and $y_{i}$ is, the higher the value $x_{i} \\cdot y_{i}$ will be. Thus, in case $b_{i}$ being odd, the most optimal pair will be $\\left(\\left[{\\frac{b_{i}}{2}}\\right],\\left[{\\frac{b_{i}}{2}}\\right]\\right)$ or $\\left(\\left\\lfloor{\\frac{b_{i}}{2}}\\right\\rfloor,\\left\\lceil{\\frac{b_{i}}{2}}\\right\\rceil\\right)$ (the order doesn't matter here). Time complexity: $O\\left(n\\right)$.",
    "code": "#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\nmt19937 rng32(chrono::steady_clock::now().time_since_epoch().count());\nmt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count());\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0); cin.tie(NULL);\n\t\n\tint n; cin >> n;\n\t\n\tvector<int> a(n), b(n);\n\tfor (auto &z: a) cin >> z;\n\tfor (auto &z: b) cin >> z;\n\t\n\tlong long Joy = 0;\n\tfor (int i=0; i<n; i++) {\n\t\tif (b[i] < 2 || b[i] > a[i] * 2) {Joy--; continue;}\n\t\tint x = b[i] / 2, y = b[i] - x;\n\t\tJoy += 1LL * x * y;\n\t}\n\tcout << Joy << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ]
  },
  {
    "contest_id": "390",
    "index": "C",
    "title": "Inna and Candy Boxes",
    "statement": "Inna loves sweets very much. She has $n$ closed present boxes lines up in a row in front of her. Each of these boxes contains either a candy (Dima's work) or nothing (Sereja's work). Let's assume that the boxes are numbered from 1 to $n$, from left to right.\n\nAs the boxes are closed, Inna doesn't know which boxes contain candies and which boxes contain nothing. Inna chose number $k$ and asked $w$ questions to Dima to find that out. Each question is characterised by two integers $l_{i}, r_{i}$ ($1 ≤ l_{i} ≤ r_{i} ≤ n$; $r - l + 1$ is divisible by $k$), the $i$-th question is: \"Dima, is that true that among the boxes with numbers from $l_{i}$ to $r_{i}$, inclusive, the candies lie \\textbf{only} in boxes with numbers $l_{i} + k - 1$, $l_{i} + 2k - 1$, $l_{i} + 3k - 1$, ..., $r_{i}$?\"\n\nDima hates to say \"no\" to Inna. That's why he wonders, what number of actions he will have to make for each question to make the answer to the question positive. In one action, Dima can either secretly take the candy from any box or put a candy to any box (Dima has infinitely many candies). Help Dima count the number of actions for each Inna's question.\n\nPlease note that Dima doesn't change the array during Inna's questions. That's why when you calculate the number of operations for the current question, please assume that the sequence of boxes didn't change.",
    "tutorial": "The query content looks pretty confusing at first, to be honest. Since $k$ is static throughout a scenario, we can group the boxes into $k$ groups, the $z$-th box (in this editorial let's assume that the indices of the boxes start from $0$) falls into group number $z\\ {\\mathrm{mod}}\\ k$. Then, each query can be simplified as this: \"Is that true that among the boxes with numbers from $l_{i}$ to $r_{i}$, inclusive, the candies lie only in boxes of group $(l_{i}+k-1)\\mod k$? To make sure the answer for a query being \"Yes\", Dima has to remove candies from all candied-box in all groups other than $(l_{i}+k-1)\\mod k$, while in that exact group, fill every empty box with a candy. Obviously, we'll consider boxes with indices between $l_{i}$ and $r_{i}$ inclusively only. We can make $k$ lists, the $t$-th ($0$-indexed) list stores the indices of candied boxes in group $t$. We'll process with each query as the following: Time complexity: $O\\left(n+w k\\log(n)\\right)$.",
    "code": "#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\nmt19937 rng32(chrono::steady_clock::now().time_since_epoch().count());\nmt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count());\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0); cin.tie(NULL);\n\t\n\tint n, k, w; string s;\n\tcin >> n >> k >> w >> s;\n\t\n\tvector< vector<int> > CandyGrp(k);\n\t\n\tfor (int i=0; i<n; i++) {\n\t    if (s[i] == '0') continue;\n\t    CandyGrp[i % k].push_back(i);\n\t}\n\t\n\twhile (w--) {\n\t    int l, r;\n\t\tcin >> l >> r; l--; r--;\n\t\t\n\t\tint res = 0;\n\t\tint demandedGroup = (l + k - 1) % k;\n\t\tint BoxesPerGroup = (r - l + 1) / k;\n\t\t\n\t\tfor (int id=0; id<k; id++) {\n\t\t    \n\t\t\tint x = lower_bound(CandyGrp[id].begin(), CandyGrp[id].end(), l) - CandyGrp[id].begin();\n\t\t\tint y = upper_bound(CandyGrp[id].begin(), CandyGrp[id].end(), r) - CandyGrp[id].begin();\n\t\t\t\n\t\t\tif (id == demandedGroup) {\n\t\t\t    res += (BoxesPerGroup - (y - x));\n\t\t\t}\n\t\t\telse res += (y - x);\n\t\t}\n\t\t\n\t\tcout << res << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ]
  },
  {
    "contest_id": "390",
    "index": "D",
    "title": "Inna and Sweet Matrix",
    "statement": "Inna loves sweets very much. That's why she decided to play a game called \"Sweet Matrix\".\n\nInna sees an $n × m$ matrix and $k$ candies. We'll index the matrix rows from $1$ to $n$ and the matrix columns from $1$ to $m$. We'll represent the cell in the $i$-th row and $j$-th column as $(i, j)$. Two cells $(i, j)$ and $(p, q)$ of the matrix are adjacent if $|i - p| + |j - q| = 1$. A path is a sequence of the matrix cells where each pair of neighbouring cells in the sequence is adjacent. We'll call the number of cells in the sequence the path's length.\n\nEach cell of the matrix can have at most one candy. Initiallly, all the cells are empty. Inna is trying to place each of the $k$ candies in the matrix one by one. For each candy Inna chooses cell $(i, j)$ that will contains the candy, and also chooses the path that starts in cell $(1, 1)$ and ends in cell $(i, j)$ and doesn't contain any candies. After that Inna moves the candy along the path from cell $(1, 1)$ to cell $(i, j)$, where the candy stays forever. If at some moment Inna can't choose a path for the candy, she loses. If Inna can place all the candies in the matrix in the described manner, then her penalty equals the sum of lengths of all the paths she has used.\n\nHelp Inna to minimize the penalty in the game.",
    "tutorial": "We can see that the most optimal placement will be choosing $k$ cells being nearest to cell $(1, 1)$ (yup, including $(1, 1)$ itself). To find these $k$ points, we can simply do a BFS starting from $(1, 1)$, with traceback feature to construct the paths to get to those cells. However, keep in mind that any cell being candied will later on become obstacles for the following paths. Thus, to avoid blocking yourself, you should transfer candies to the farthest cells first, then getting closer. Thus, cell $(1, 1)$ will be the last one being filled with candy. Time complexity: $O\\left(k\\right)$ or $O\\left(n m+k\\right)$, based on implementation (I myself did $O\\left(n m+k\\right)$, since the difference isn't too much).",
    "code": "#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\nmt19937 rng32(chrono::steady_clock::now().time_since_epoch().count());\nmt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count());\n\nint dx[] = {-1, +0, +0, +1};\nint dy[] = {+0, -1, +1, +0};\npair<int, int> Default = {-1, -1};\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0); cin.tie(NULL);\n\t\n\tint n, m, k; cin >> n >> m >> k;\n\t\n\tvector<vector<int>> Dist(n+2, vector<int>(m+2, 4444));\n\tvector<vector<pair<int, int>>> Last(n+2, vector<pair<int, int>>(m+2, Default));\n    \n\tstack<pair<int, int>> Cells;\n\tint cost = 0;\n\t\n\tqueue<pair<int, int>> Q;\n\tQ.push({1, 1}); Dist[1][1] = 1;\n\t\n\twhile (!Q.empty() && Cells.size() < k) {\n\t\tpair<int, int> C = Q.front(); Q.pop();\n\t\tCells.push(C); int x = C.first, y = C.second;\n\t\t\n\t\tcost += Dist[x][y];\n\t\t\n\t\tfor (int dir=0; dir<4; dir++) {\n\t\t\tif (x + dx[dir] < 1 || x + dx[dir] > n) continue;\n\t\t\tif (y + dy[dir] < 1 || y + dy[dir] > m) continue;\n\t\t\t\n\t\t\tif (Dist[x+dx[dir]][y+dy[dir]] != 4444) continue;\n\t\t\t\n\t\t\tDist[x+dx[dir]][y+dy[dir]] = Dist[x][y] + 1;\n\t\t\tQ.push({x + dx[dir], y + dy[dir]});\n\t\t\tLast[x+dx[dir]][y+dy[dir]] = C;\n\t\t}\n\t}\n\t\n\tcout << cost << endl;\n\t\n\twhile (!Cells.empty()) {\n\t\tint x = Cells.top().first, y = Cells.top().second; Cells.pop();\n\t\tstack<pair<int, int>> Traceback;\n\t\t\n\t\twhile (x != -1 && y != -1) {\n\t\t\tTraceback.push({x, y});\n\t\t\tpair<int, int> NextCell = Last[x][y];\n\t\t\tx = NextCell.first; y = NextCell.second;\n\t\t}\n\t\t\n\t\twhile (!Traceback.empty()) {\n\t\t\tpair<int, int> CurCell = Traceback.top();\n\t\t\tTraceback.pop();\n\t\t\tcout << \"(\" << CurCell.first << \", \" << CurCell.second << \") \";\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms"
    ]
  },
  {
    "contest_id": "390",
    "index": "E",
    "title": "Inna and Large Sweet Matrix",
    "statement": "Inna loves sweets very much. That's why she wants to play the \"Sweet Matrix\" game with Dima and Sereja. But Sereja is a large person, so the game proved small for him. Sereja suggested playing the \"Large Sweet Matrix\" game.\n\nThe \"Large Sweet Matrix\" playing field is an $n × m$ matrix. Let's number the rows of the matrix from $1$ to $n$, and the columns — from $1$ to $m$. Let's denote the cell in the $i$-th row and $j$-th column as $(i, j)$. Each cell of the matrix can contain multiple candies, initially all cells are empty. The game goes in $w$ moves, during each move one of the two following events occurs:\n\n- Sereja chooses five integers $x_{1}, y_{1}, x_{2}, y_{2}, v$ $(x_{1} ≤ x_{2}, y_{1} ≤ y_{2})$ and adds $v$ candies to each matrix cell $(i, j)$ $(x_{1} ≤ i ≤ x_{2}; y_{1} ≤ j ≤ y_{2})$.\n- Sereja chooses four integers $x_{1}, y_{1}, x_{2}, y_{2}$ $(x_{1} ≤ x_{2}, y_{1} ≤ y_{2})$. Then he asks Dima to calculate the total number of candies in cells $(i, j)$ $(x_{1} ≤ i ≤ x_{2}; y_{1} ≤ j ≤ y_{2})$ and he asks Inna to calculate the total number of candies in the cells of matrix $(p, q)$, which meet the following logical criteria: ($p < x_{1}$ OR $p > x_{2}$) AND ($q < y_{1}$ OR $q > y_{2}$). Finally, Sereja asks to write down the difference between the number Dima has calculated and the number Inna has calculated (D - I).\n\nUnfortunately, Sereja's matrix is really huge. That's why Inna and Dima aren't coping with the calculating. Help them!",
    "tutorial": "Let's denote $A$ as the total number of candies on the board, $R_{i}$ as the total number of candies on the $i$-th row ($1  \\le  i  \\le  n$), $C_{j}$ as the total number of candies on the $j$-th column ($1  \\le  j  \\le  m$). Also, let's denote $R(i_{1},i_{2})=\\sum_{x=i_{1}}^{i_{2}}R_{s}$ and $C(j_{1},j_{2})=\\sum_{y=j_{1}}^{\\gamma_{2}}C_{y}$. Let's considered the 2nd type of query first. Denoting the answer for the query as $f(x_{1}, y_{1}, x_{2}, y_{2})$, we can see that $f(x_{1}, y_{1}, x_{2}, y_{2}) = R(x_{1}, x_{2}) + C(y_{1}, y_{2}) - A$ (you can draw a simple diagram and validate this function). Thus, the problem is now reduced to calculating $R(x_{1}, x_{2})$, $C(y_{1}, y_{2})$ and $A$: Time complexity: $O\\left(w\\left(\\log(n)+\\log(m)\\right)\\right)$.",
    "code": "#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\nmt19937 rng32(chrono::steady_clock::now().time_since_epoch().count());\nmt19937_64 rng64(chrono::steady_clock::now().time_since_epoch().count());\n\nstruct SegTree_Sum {\n\tint n; vector<long long> Tree, Lazy;\n\tSegTree_Sum() {}\n\tSegTree_Sum(int _n) {\n\t\tn = _n;\n\t\tTree.resize(n*4);\n\t\tLazy.resize(n*4);\n\t}\n\t\n\tvoid Propagate(int node, int st, int en) {\n\t\tif (Lazy[node] == 0) return;\n\t\tTree[node] += Lazy[node] * (en - st + 1);\n\t\tif (st != en) {\n\t\t\tLazy[node*2+1] += Lazy[node];\n\t\t\tLazy[node*2+2] += Lazy[node];\n\t\t}\n\t\tLazy[node] = 0;\n\t}\n\t\n\tvoid Update(int node, int st, int en, int L, int R, long long val) {\n\t\tPropagate(node, st, en);\n\t\tif (en < st || R < st || en < L) return;\n\t\tif (L <= st && en <= R) {\n\t\t\tLazy[node] += val;\n\t\t\tPropagate(node, st, en); return;\n\t\t}\n\t\tUpdate(node*2+1, st, (st+en)/2+0, L, R, val);\n\t\tUpdate(node*2+2, (st+en)/2+1, en, L, R, val);\n\t\tTree[node] = Tree[node*2+1] + Tree[node*2+2];\n\t}\n\t\n\tlong long Sum(int node, int st, int en, int L, int R) {\n\t\tPropagate(node, st, en);\n\t\tif (en < st || R < st || en < L) return 0LL;\n\t\tif (L <= st && en <= R) return Tree[node];\n\t\tlong long p1 = Sum(node*2+1, st, (st+en)/2+0, L, R);\n\t\tlong long p2 = Sum(node*2+2, (st+en)/2+1, en, L, R);\n\t\treturn (p1 + p2);\n\t}\n\t\n\tvoid RangeUpdate(int L, int R, long long val) {\n\t\tUpdate(0, 0, n-1, L, R, val);\n\t}\n\t\n\tlong long RangeSum(int L, int R) {\n\t\treturn Sum(0, 0, n-1, L, R);\n\t}\n};\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0); cin.tie(NULL);\n\t\n\tint n, m, w; cin >> n >> m >> w;\n\t\n\tlong long TotalCandies = 0;\n\t\n\tSegTree_Sum TreeRow = SegTree_Sum(n);\n\tSegTree_Sum TreeCol = SegTree_Sum(m);\n\t\n\twhile (w--) {\n\t\tint t, x1, y1, x2, y2;\n\t\tcin >> t >> x1 >> y1 >> x2 >> y2;\n\t\t\n\t\tif (t == 0) {\n\t\t\tint v; cin >> v;\n\t\t\t\n\t\t\tTotalCandies += 1LL * (x2 - x1 + 1) * (y2 - y1 + 1) * v;\n\t\t\t\n\t\t\tTreeRow.RangeUpdate(x1, x2, 1LL * v * (y2 - y1 + 1));\n\t\t\tTreeCol.RangeUpdate(y1, y2, 1LL * v * (x2 - x1 + 1));\n\t\t}\n\t\telse if (t == 1) {\n\t\t\tlong long res = 0;\n\t\t\t\n\t\t\tres += TreeRow.RangeSum(x1, x2);\n\t\t\tres += TreeCol.RangeSum(y1, y2);\n\t\t\tres -= TotalCandies;\n\t\t\t\n\t\t\tcout << res << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": []
  },
  {
    "contest_id": "392",
    "index": "A",
    "title": "Blocked Points",
    "statement": "Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points $A$ and $B$ on the plane are 4-connected if and only if:\n\n- the Euclidean distance between $A$ and $B$ is one unit and neither $A$ nor $B$ is blocked;\n- or there is some integral point $C$, such that $A$ is 4-connected with $C$, and $C$ is 4-connected with $B$.\n\nLet's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than $n$, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?",
    "tutorial": "Let's look at all pairs of neighboring points such that one of them is special and the other one is not. I claim that it is necessary and sufficient to block at least one point in every such pair Necessity is obvious. Let's prove sufficiency. Assume that we blocked at least one point in each pair, but there are two points $A$ and $B$ such that $A$ is special, $B$ is not and they are 4-connected. Then look at the path between these points. It starts with a special point and ends with non-special. That means that there are two adjacent points in this path such that the first one is special and the second one is not. But it contradicts our statement that we blocked at least one of the points in each pair. Now let's look at these pairs. For simplicity, we will look at only $\\frac18$-th of a circle. And let's draw all horizontal pairs with a point inside the selected piece. There are also some vertical segments, but it can be proven with some geometry that the segments on the neighboring horizontal line are either on the same x-coordinate, or one is shifted by one. This means that if we choose the leftmost point in each of these segments, we will cover all vertical pairs as well. With some symmetry, this can be done for other pieces of a circle. There is only one thing left - we need to bring all pieces together. It is easy when two pieces share a horizontal or vertical line, but in the other case, we need another picture. In this case, everything is already fine, we don't have any \"leaks\" between parts In that case, we don't have any leaks either, but we have overlapping segments, and that means that we case save 1 point here and 4 points total. All we need now is to calculate the number of segments in a circle sector (it is ${n}/\\sqrt{2}+1$) and differentiate these two cases.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\n    long long n;\n    cin >> n;\n\n    if (n == 0) {\n        cout << 1 << '\\n';\n        return 0;\n    }\n\n    int L = sqrt(n * n / 2);\n\n    pair<long long, long long> near = {L + 1, L};\n\n    int ans = (L * 2 + 1) * 4;\n\n    if (near.first * near.first + near.second * near.second > n * n)\n        ans -= 4;\n\n    cout << ans << '\\n';\n\n    return 0;\n}",
    "tags": [
      "math"
    ]
  },
  {
    "contest_id": "392",
    "index": "B",
    "title": "Tower of Hanoi",
    "statement": "The Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.\n\nThe objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:\n\n- Only one disk can be moved at a time.\n- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.\n- No disk may be placed on top of a smaller disk.\n\nWith three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is $2^{n} - 1$, where $n$ is the number of disks. (c) Wikipedia.\n\nSmallY's puzzle is very similar to the famous Tower of Hanoi. In the Tower of Hanoi puzzle you need to solve a puzzle in minimum number of moves, in SmallY's puzzle each move costs some money and you need to solve the same puzzle but for minimal cost. At the beginning of SmallY's puzzle all $n$ disks are on the first rod. Moving a disk from rod $i$ to rod $j$ $(1 ≤ i, j ≤ 3)$ costs $t_{ij}$ units of money. The goal of the puzzle is to move all the disks to the third rod.\n\nIn the problem you are given matrix $t$ and an integer $n$. You need to count the minimal cost of solving SmallY's puzzle, consisting of $n$ disks.",
    "tutorial": "First, understand this solution of the standard Hanoi puzzle, if you don't know it. I will use the same idea to solve this problem. Let's create a function $calc(from, to, n)$ which will count the minimal cost to move $n$ disks from $from$ to $to$. If $n=1$ then we either move the disk directly to $to$, or we first move it to the $mid$ (the remaining rod) and only then move to $to$. If $n > 1$ then again, there are two possible strategies. Either we use moves from standard solution - move $n-1$ disks to $mid$, move 1 disk from $from$ to $to$, then move $n-1$ disks to $to$. Or we can make more moves but possibly with less cost: move $n-1$ disks to $to$, then 1 disk from $from$ to $mid$, then $n-1$ disks back to $from$, then 1 disk to $to$, and finally $n-1$ disks to $to$. Here are pictures for both cases: Better resolution Better resolution For moving $n-1$ disks we will make recursive calls. If we just do that, we will have an exponential solution, which is not very nice. But we only have $3\\times 2 \\times n$ different calls - 3 options for $from$, 2 for $to$ and $n$. That means that we can just store every value which we already counted (or I can say a fancy word memoization, which means the same thing)",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define ll   long long\n\narray<array<ll, 3>, 3> t;\nmap<pair<pair<int, int>, ll>, ll> mem;\n\nll calc(int from, int to, int n) {\n    auto p = make_pair(make_pair(from, to), n);\n    if (mem.count(p))\n        return mem[p];\n    int mid = 3 - from - to;\n    if (n == 1) {\n        return mem[p] = min(t[from][mid] + t[mid][to], t[from][to]);\n    }\n    return mem[p] = min(calc(from, mid, n - 1) + t[from][to]  + calc(mid,   to, n - 1),\n                        calc(from,  to, n - 1) + t[from][mid] + calc( to, from, n - 1) + t[mid][to] + calc(from, to, n - 1));\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            cin >> t[i][j];\n        }\n    }\n\n    int n;\n    cin >> n;\n\n    cout << calc(0, 2, n) << '\\n';\n\n    return 0;\n}",
    "tags": [
      "dp"
    ]
  },
  {
    "contest_id": "392",
    "index": "C",
    "title": "Yet Another Number Sequence",
    "statement": "Everyone knows what the Fibonacci sequence is. This sequence can be defined by the recurrence relation:\n\n\\[\nF_{1} = 1, F_{2} = 2, F_{i} = F_{i - 1} + F_{i - 2} (i > 2).\n\\]\n\nWe'll define a new number sequence $A_{i}(k)$ by the formula:\n\n\\[\nA_{i}(k) = F_{i} × i^{k} (i ≥ 1).\n\\]\n\nIn this problem, your task is to calculate the following sum: $A_{1}(k) + A_{2}(k) + ... + A_{n}(k)$. The answer can be very large, so print it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "This is obviously some matrix-exponentiation problem. We just have to figure out the matrix. Well, let's look at what we have $A_i(k) = F_i \\cdot i^k = (F_{i-1} + F_{i-2}) \\cdot i^k = F_{i-1}\\cdot ((i-1)+1)^k + F_{i-2}\\cdot ((i-2) + 2)^k =\\\\= \\sum_{j=0}^k \\binom{k}{j} F_{i-1}(i-1)^j + \\sum_{j=0}^k \\binom{k}{j} F_{i-2}(i-2)^j\\cdot 2^{k-j}=\\\\= \\sum_{j=0}^k \\binom{k}{j} A_{i-1}(j) + \\sum_{j=0}^k \\binom{k}{j} A_{i-2}(j)\\cdot 2^{k-j}$ Then we just have to store $A_{i-1}(j)$ and $A_{i-2}(j)$ for every $j \\in [0;k]$. And also we have to store the sum, so the matrix will be of size $2(k+1)+1$, resulting in $O(k^3\\log n)$ in total.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define ll   long long\n\ntemplate<auto P>\nstruct Modular {\n    using value_type = decltype(P);\n    value_type value;\n\n    Modular(ll k = 0) : value(norm(k)) {}\n\n    Modular<P>& operator += (const Modular<P>& m)       { value += m.value; if (value >= P) value -= P; return *this; }\n    Modular<P>  operator +  (const Modular<P>& m) const { Modular<P> r = *this; return r += m; }\n\n    Modular<P>& operator -= (const Modular<P>& m)       { value -= m.value; if (value <  0) value += P; return *this; }\n    Modular<P>  operator -  (const Modular<P>& m) const { Modular<P> r = *this; return r -= m; }\n    Modular<P>  operator -                     () const { return Modular<P>(-value); }\n\n    Modular<P>& operator *= (const Modular<P> &m)       { value = value * 1ll * m.value % P; return *this; }\n    Modular<P>  operator *  (const Modular<P>& m) const { Modular<P> r = *this; return r *= m; }\n\n    Modular<P>& operator /= (const Modular<P> &m)       { return *this *= m.inv(); }\n    Modular<P>  operator /  (const Modular<P>& m) const { Modular<P> r = *this; return r /= m; }\n\n    Modular<P>& operator ++                    ()       { return *this += 1; }\n    Modular<P>& operator --                    ()       { return *this -= 1; }\n    Modular<P>  operator ++                 (int)       { Modular<P> r = *this; r += 1; return r; }\n    Modular<P>  operator --                 (int)       { Modular<P> r = *this; r -= 1; return r; }\n\n    bool        operator == (const Modular<P>& m) const { return value == m.value; }\n    bool        operator != (const Modular<P>& m) const { return value != m.value; }\n\n    value_type norm(ll k) {\n        if (!(-P <= k && k < P)) k %= P;\n        if (k < 0) k += P;\n        return k;\n    }\n\n    Modular<P> inv() const {\n        value_type a = value, b = P, x = 0, y = 1;\n        while (a != 0) { value_type k = b / a; b -= k * a; x -= k * y; swap(a, b); swap(x, y); }\n        return Modular<P>(x);\n    }\n};\n\ntemplate<auto P> Modular<P> pow(Modular<P> m, ll p) {\n    Modular<P> r(1);\n    while (p) {\n        if (p & 1) r *= m;\n        m *= m;\n        p >>= 1;\n    }\n    return r;\n}\n\ntemplate<auto P> ostream& operator << (ostream& o, const Modular<P> &m) { return o << m.value; }\ntemplate<auto P> istream& operator >> (istream& i,       Modular<P> &m) { ll k; i >> k; m.value = m.norm(k); return i; }\ntemplate<auto P> string   to_string(const Modular<P>& m) { return to_string(m.value); }\n\nusing Mint = Modular<1000000007>;\n// using Mint = Modular<998244353>;\n// using Mint = long double;\n\nvector<vector<Mint>> operator * (vector<vector<Mint>> a, vector<vector<Mint>> b) {\n    vector<vector<Mint>> c(a.size(), vector<Mint>(b[0].size(), 0));\n    for (int i = 0; i < a.size(); ++i) {\n        for (int j = 0; j < a[0].size(); ++j) {\n            for (int k = 0; k < b[0].size(); ++k) {\n                c[i][k] += a[i][j] * b[j][k];\n            }\n        }\n    }\n    return c;\n}\n\nvector<vector<Mint>> pow(vector<vector<Mint>> a, ll p) {\n    vector<vector<Mint>> res(a.size(), vector<Mint>(a.size(), 0));\n    for (int i = 0; i < res.size(); ++i) {\n        res[i][i] = 1;\n    }\n    while (p) {\n        if (p & 1) {\n            res = res * a;\n        }\n        a = a * a;\n        p /= 2;\n    }\n    return res;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\n    ll n;\n    cin >> n;\n    int k;\n    cin >> k;\n\n    vector<vector<Mint>> mt((k + 1) * 2 + 1, vector<Mint>((k + 1) * 2 + 1, 0));\n\n    vector<vector<Mint>> vinit(mt.size(), vector<Mint>(1, 0));\n\n    // first k+1 elements are for F_{i-1}, next k+1 are for F_{i-2}, the last one is for sum up to A_{i-2}\n    for (int i = 0; i < k + 1; ++i) {\n        vinit[i][0] = 1;\n        vinit[i + k + 1][0] = 0;\n        vinit.back()[0] = 0;\n    }\n    vinit[k + 1][0] = 1;\n\n    vector<vector<Mint>> C(50, vector<Mint>(50, 0));\n    for (int i = 0; i < C.size(); ++i) {\n        C[0][i] = 0;\n        C[i][0] = 1;\n    }\n\n    for (int i = 1; i < C.size(); ++i) {\n        for (int j = 1; j < C.size(); ++j) {\n            C[i][j] = C[i - 1][j] + C[i - 1][j - 1];\n        }\n    }\n\n    vector<Mint> p2(50, 1);\n    for (int i = 1; i < p2.size(); ++i)\n        p2[i] = p2[i - 1] * 2;\n\n    for (int p = 0; p < k + 1; ++p)\n        mt[k + 1 + p][p] = 1;\n    mt.back().back() = 1;\n    mt.back()[k] = 1;\n\n    for (int p = 0; p < k + 1; ++p) {\n        for (int j = 0; j <= p; ++j) {\n            mt[p][j] += C[p][j];\n            mt[p][k + 1 + j] += C[p][j] * p2[p - j];\n        }\n    }\n\n    auto res = pow(mt, n) * vinit;\n    cout << res.back()[0] << '\\n';\n\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "matrices"
    ]
  },
  {
    "contest_id": "392",
    "index": "D",
    "title": "Three Arrays",
    "statement": "There are three arrays $a$, $b$ and $c$. Each of them consists of $n$ integers. SmallY wants to find three integers $u$, $v$, $w$ $(0 ≤ u, v, w ≤ n)$ such that the following condition holds: each number that appears in the union of $a$, $b$ and $c$, appears either in the first $u$ elements of $a$, or in the first $v$ elements of $b$, or in the first $w$ elements of $c$. Of course, SmallY doesn't want to have huge numbers $u$, $v$ and $w$, so she wants sum $u + v + w$ to be as small as possible.\n\nPlease, help her to find the minimal possible sum of $u + v + w$.",
    "tutorial": "Let forget about $a$ for a minute and solve the problem for two arrays. Of course, it can be done with something like two pointers, but it is not extendable to three arrays (at least I don't know how). We need a more general approach. First, let's assume that $b$ has all elements, which $c$ contains. We can achieve that by copying $c$ at the end of $b$ (it is easy to see that this will not improve the answer). Suppose for some number $k$ it has only one occurrence in $b$ and only one in $c$. And $b[i] = c[j] = k$. Then we denote $pos[i] = j$. Now, if $k$ has multiple occurrences in $c$, we will take the smallest $j$. If it has multiple occurrences in $b$, we will set the first $pos[i]$ to $j$ and others to $0$. Why that? Good question. Now the answer for the problem is $min_i((i-1) + max_{j > i}pos[j])$. The expression in the brackets corresponds to the case when we take $i$ first elements from $b$. Then we look for all other elements ($j>i$) and choose the shortest prefix of $c$ which contains all these elements. That explains why we write the first occurrence of $k$ in $c$ to $pos$. And we fill other values with zero because we don't need them if we already took the first occurrence in $b$. Now get $a$ back. What changes if we have some numbers in $a$? Well, in that case, we can set $pos[i]=0$ for all occurrences of that number in $b$ (not only all except first). That means that if we iterate over prefix of $a$ from $0$ to $n$ then we will have to change some $pos$ to zero. But I prefer changing zeros to some values, so we will iterate from $n$ to $0$. Well, let's iterate. Suppose we decided not to take prefix of length $i$ in $a$, and instead took prefix of length $i-1$. If there are some occurrences of $a[i]$ before $i$, then nothing changes in $pos$. But if there is no $a[i]$ before $i$, we have to update some $pos$ and recalculate $min_i((i-1) + max_{j > i}pos[j])$. I believe there are different structs that can do it, I will describe what I used. In the expression, there are maximums on the suffix. They can be stored as pairs $(p, m)$ which means that up to position $p$ maximum on a suffix is at least $m$ (maximum-on-a-suffix is a non-increasing function, obviously). Now, to calculate the answer, we don't have to go through all $i$. We only need to consider such indices $p$ that some pair $(p-1, ?)$ exists in our set. That means that we have to check exactly one option for every pair of adjacent pairs. Remember, we only have to add pairs to this set. And it is easy - add a pair and remove enough pairs before it (while their $m$ less than new $m$). With every addition or removal, we have $O(1)$ additions or removals of options for an answer. Current answers can be stored in a multiset since we only need the minimal value. And if we are looking at a prefix $i$ of $a$, then we have to update the answer with $i$ + (the smallest value from multiset). This is probably not the cleanest explanation, so there is a random picture which can help: The picture can contain off-by-one error, depending on your indexing and my mistakes. $pos = [1,\\,0,\\,5,\\,3,\\,0,\\,3,\\,2]$. The picture illustrates maximums on a suffix for every $i$. In a set, we store one pair for each horizontal segment. When we need to update the answer, we look at all points with a green circle (or actually 1 to the right of these points because in this picture maximum at $x=2$ is $5$, so we need $(3,3)$, not $(2,3)$, but that is exactly what I meant when I said about off-by-one errors).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n), c(n);\n    for (int i = 0; i < n; ++i)\n        cin >> a[i];\n    for (int i = 0; i < n; ++i)\n        cin >> b[i];\n    for (int i = 0; i < n; ++i)\n        cin >> c[i];\n\n    for (auto k : c) {\n        b.push_back(k);\n    }\n\n    map<int, int> whereb;\n    map<int, int> wherec;\n    for (int i = (int)b.size() - 1; i >= 0; --i)\n        whereb[b[i]] = i;\n    for (int i = (int)c.size() - 1; i >= 0; --i)\n        wherec[c[i]] = i;\n\n    vector<bool> first_in_a(a.size(), false);\n    vector<bool> first_in_b(b.size(), false);\n    set<int> ina, inb;\n    for (int i = 0; i < a.size(); ++i) {\n        if (!ina.count(a[i])) {\n            ina.insert(a[i]);\n            first_in_a[i] = true;\n        }\n    }\n    for (int i = 0; i < b.size(); ++i) {\n        if (!inb.count(b[i])) {\n            inb.insert(b[i]);\n            first_in_b[i] = true;\n        }\n    }\n\n    set<pair<int, int>> maxs;\n    multiset<int> res;\n\n    maxs.emplace(1e9, 0);\n    maxs.emplace(-1, 1e9 + 5);\n    res.insert(maxs.begin()->first + next(maxs.begin())->second + 1);\n\n    auto del = [&](pair<int, int> p) {\n        auto it = maxs.find(p);\n        assert(it != maxs.end());\n        auto inext = next(it);\n        auto iprev = prev(it);\n\n        res.erase(res.find(iprev->first + it->second + 1));\n        res.erase(res.find(it->first + inext->second + 1));\n        maxs.erase(it);\n        res.insert(iprev->first + inext->second + 1);\n    };\n\n    auto add = [&](pair<int, int> p) {\n        auto it = maxs.lower_bound(make_pair(p.first, -5));\n        if (it->second >= p.second) return;\n        if (it->first == p.first) {\n            ++it;\n        }\n        while (prev(it)->second <= p.second)\n            del(*prev(it));\n\n        maxs.insert(p);\n        it = maxs.find(p);\n        auto inext = next(it);\n        auto iprev = prev(it);\n\n        res.insert(iprev->first + it->second + 1);\n        res.insert(it->first + inext->second + 1);\n        res.erase(res.find(iprev->first + inext->second + 1));\n    };\n\n    for (int i = 0; i < b.size(); ++i) {\n        if (first_in_b[i] && !ina.count(b[i])) {\n            int inc = 1e9;\n            if (wherec.count(b[i]))\n                inc = wherec[b[i]] + 1;\n            add({i, inc});\n        }\n    }\n\n    int ans = n + *res.begin();\n\n    for (int i = n - 1; i >= 0; --i) {\n        if (first_in_a[i]) {\n            if (!inb.count(a[i])) break;\n            int inc = 1e9;\n            if (wherec.count(a[i]))\n                inc = wherec[a[i]] + 1;\n            add({whereb[a[i]], inc});\n        }\n        ans = min(ans, i + *res.begin());\n    }\n\n    cout << ans << '\\n';\n\n    return 0;\n}",
    "tags": [
      "data structures"
    ]
  },
  {
    "contest_id": "392",
    "index": "E",
    "title": "Deleting Substrings",
    "statement": "SmallR likes a game called \"Deleting Substrings\". In the game you are given a sequence of integers $w$, you can modify the sequence and get points. The only type of modification you can perform is (unexpected, right?) deleting substrings. More formally, you can choose several contiguous elements of $w$ and delete them from the sequence. Let's denote the sequence of chosen elements as $w_{l}, w_{l + 1}, ..., w_{r}$. They must meet the conditions:\n\n- the equality $|w_{i} - w_{i + 1}| = 1$ must hold for all $i$ $(l ≤ i < r)$;\n- the inequality $2·w_{i} - w_{i + 1} - w_{i - 1} ≥ 0$ must hold for all $i$ $(l < i < r)$.\n\nAfter deleting the chosen substring of $w$, you gain $v_{r - l + 1}$ points. You can perform the described operation again and again while proper substrings exist. Also you can end the game at any time. Your task is to calculate the maximum total score you can get in the game.",
    "tutorial": "There will be three different $dp$, let's get that out of the way. I wanted to make $4$, but in the end decided to merge two of them. Also, before everything, let's update $v$ with $v[i] = max_j(v[j] + v[i - j])$. Because sometimes we want to remove segment of length $5$, but $2 + 3$ gives more points. First, let's discuss what a good substring is. It is either increasing, decreasing, or increasing up to something and then decreasing. And in any case, the difference between neighboring elements is exactly 1. $dp\\_mon[l][r]$ - the biggest score we can get from segment $[l;r]$ if in the end we are left with monotonous sequence, starting from $w[l]$ and ending with $w[r]$ (that means that we cannot remove $w[l]$ or $w[r]$). If we can't do that, $dp\\_mon[l][r] = -\\infty$. $dp\\_all[l][r]$ - the biggest score we can get from removing the whole segment $[l;r]$. $dp[l][r]$ - the best score we can get on segment $[l;r]$ (no restrictions). The answer will be $dp[1][n]$. When we have these $dp$, it is not very hard to calculate them. To get $dp\\_mon[l][r]$ we either have to remove everything in between (if $|w[l] - w[r]| = 1$), or for each number between $l$ and $r$ check if it can be in that monotonous sequence, and if it can, split by this number and add two $dp\\_mon[l][j] + dp\\_mon[j][r]$ (with intersection, yes). Now $dp\\_all$. First, let's update it with every $dp\\_all[l][j] + dp\\_all[j + 1][r]$. Now suppose there is an option, where we can't split the segment into two pieces. Consider the last segment we removed. It is some subsequence of our $[l;r]$ segment. Elements of that subsequence split this segment into pieces. Each of these pieces is independent of each other. That means that if the first element of the subsequence is $w[j]$ then $[l; j-1]$ and $[j; r]$ are independent and we already updated the answer with the sum of $dp\\_all$, and similarly with $r$. There is one case, though. When this subsequence starts at $w[l]$ and ends in $w[r]$. But that's what we have $dp\\_mon$ for! Now for every element on $[l;r]$ we have to check if this subsequence is increasing from $w[l]$ to $w[j]$ and then decreasing from $w[j]$ to $w[r]$. That means that we add two $dp\\_mon$ and after that remove this subsequence with a score of $v[len\\_of\\_subsequence]$. The length can be calculated from $|w[l] - w[j]|$ and $|w[j] - w[r]|$. The last is $dp$. That's the easiest one. Either we remove everything - this is $dp\\_all$, or there is some element which we decided not to remove. Then, as discussed in previous paragraph, it is enough to update $dp[l][r]$ by every $dp[l][j] + dp[j + 1][r]$. And I know that probably some of $dp$ are useless, but I feel like it is easier to understand the solution with multiple $dp$ with different purposes.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define ll long long\n\nconst int inf = 1e9;\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\n    int n;\n    cin >> n;\n    vector<int> v(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> v[i];\n    }\n\n    v.insert(v.begin(), 0);\n    for (int i = 1; i <= n; ++i) {\n        for (int j = 1; j < i; ++j) {\n            v[i] = max(v[i], v[j] + v[i - j]);\n        }\n    }\n\n    vector<int> w(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> w[i];\n    }\n\n    auto getv = [&](int ln) {\n        if (ln < v.size()) return v[ln];\n        return -inf;\n    };\n\n    vector<vector<ll>> dp_all(n, vector<ll>(n, -inf));\n    vector<vector<ll>> dp_mon(n, vector<ll>(n, -inf));\n    vector<vector<ll>> dp(n, vector<ll>(n, 0));\n\n    for (int i = 0; i < n; ++i) {\n        dp_mon[i][i] = 0;\n        dp_all[i][i] = v[1];\n        if (i != 0)\n            dp_all[i][i - 1] = 0;\n    }\n\n    for (int k = 1; k <= n; ++k) {\n        for (int l = 0; l < n; ++l) {\n            int r = l + k - 1;\n            if (r >= n) break;\n\n            for (int j = l + 1; j <= r; ++j) {\n                dp_all[l][r] = max(dp_all[l][r], dp_all[l][j - 1] + dp_all[j][r]);\n            }\n\n            if (w[l] != w[r]) {\n                if (abs(w[l] - w[r]) == 1) {\n                    dp_mon[l][r] = dp_all[l + 1][r - 1];\n                } else {\n                    for (int j = l + 1; j < r; ++j) {\n                        if (w[l] != w[j] && w[r] != w[j] && ((w[l] < w[j]) == (w[j] < w[r]))) {\n                            dp_mon[l][r] = max(dp_mon[l][r], dp_mon[l][j] + dp_mon[j][r]);\n                        }\n                    }\n                }\n            }\n\n            for (int j = l; j <= r; ++j)\n                if (w[j] >= w[l] && w[j] >= w[r])\n                    dp_all[l][r] = max(dp_all[l][r], dp_mon[l][j] + dp_mon[j][r] + getv(abs(w[l] - w[j]) + abs(w[j] - w[r]) + 1));\n\n            dp[l][r] = max(dp[l][r], dp_all[l][r]);\n            for (int j = l + 1; j <= r; ++j)\n                dp[l][r] = max(dp[l][r], dp[l][j - 1] + dp[j][r]);\n        }\n    }\n\n    cout << dp[0][n - 1] << '\\n';\n\n    return 0;\n}",
    "tags": []
  },
  {
    "contest_id": "393",
    "index": "A",
    "title": "Nineteen",
    "statement": "Alice likes word \"nineteen\" very much. She has a string $s$ and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string.\n\nFor example, if she has string \"xiineteenppnnnewtnee\", she can get string \"{x\\textbf{nineteen}pp\\textbf{nineteen}w}\", containing (the occurrences marked) two such words. More formally, word \"nineteen\" occurs in the string the number of times you can read it starting from some letter of the string. Of course, you shouldn't skip letters.\n\nHelp her to find the maximum number of \"nineteen\"s that she can get in her string.",
    "tutorial": "Looking at examples and thinking about different cases lead to the idea that the best result would be to build a string which starts with $nineteenineteenineteen...$. The first word $nineteen$ requires 3 letters $n$, 3 letters $e$, 1 letter $i$ and 1 letter $t$. Every next occurrence of $nineteen$ requires the same set of letters, but we need only two letters $n$ for each new word. In other words, we can start with $n$, and then every word will need exactly two extra $n$-s. Let $cnt[c]$ denote the number of characters $c$ in the string. Then the answer is $min\\left(\\left\\lfloor\\frac{cnt[n] - 1}{2}\\right\\rfloor, \\,\\left\\lfloor\\frac{cnt[e]}{3}\\right\\rfloor,\\, cnt[i],\\, cnt[t]\\right)$. (In theory this minimum could be $-\\left\\lfloor\\frac{1}{2}\\right\\rfloor$, but in C++ it is equal to zero, so everything works fine)",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\n    string s;\n    cin >> s;\n    map<char, int> cnt;\n    for (auto c : s) {\n        cnt[c]++;\n    }\n    cout << min({(cnt['n'] - 1) / 2, cnt['e'] / 3, cnt['i'], cnt['t']}) << '\\n';\n\n    return 0;\n}",
    "tags": []
  },
  {
    "contest_id": "393",
    "index": "B",
    "title": "Three matrices",
    "statement": "Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an $n × n$ matrix $W$, consisting of integers, and you should find two $n × n$ matrices $A$ and $B$, all the following conditions must hold:\n\n- $A_{ij} = A_{ji}$, for all $i, j$ $(1 ≤ i, j ≤ n)$;\n- $B_{ij} = - B_{ji}$, for all $i, j$ $(1 ≤ i, j ≤ n)$;\n- $W_{ij} = A_{ij} + B_{ij}$, for all $i, j$ $(1 ≤ i, j ≤ n)$.\n\nCan you solve the problem?",
    "tutorial": "We can write this system of equations, using the fact that $B[j][i] = -B[i][j]$ and $A[i][j] = A[j][i]$ $\\begin{cases} A[i][j] + B[i][j] = W[i][j]\\\\ A[j][i] + B[j][i] = W[j][i] \\end{cases} \\quad\\Rightarrow\\quad \\begin{cases} A[i][j] + B[i][j] = W[i][j]\\\\ A[i][j] - B[i][j] = W[j][i] \\end{cases}$ From that, it is easy to conclude that $A[i][j] = \\frac{W[i][j] + W[j][i]}{2}$ and $B[i][j] = \\frac{W[i][j] - W[j][i]}{2}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\n    int n;\n    cin >> n;\n    vector<vector<double>> w(n, vector<double>(n));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> w[i][j];\n        }\n    }\n\n    vector<vector<double>> a(n, vector<double>(n));\n    vector<vector<double>> b(n, vector<double>(n));\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            a[i][j] = (w[i][j] + w[j][i]) / 2;\n            b[i][j] = (w[i][j] - w[j][i]) / 2;\n        }\n    }\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << a[i][j] << ' ';\n        }\n        cout << '\\n';\n    }\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << b[i][j] << ' ';\n        }\n        cout << '\\n';\n    }\n\n    return 0;\n}",
    "tags": []
  },
  {
    "contest_id": "396",
    "index": "A",
    "title": "On Number of Decompositions into Multipliers",
    "statement": "You are given an integer $m$ as a product of integers $a_{1}, a_{2}, ... a_{n}$ $(m=\\prod_{i=1}^{n}a_{i})$. Your task is to find the number of distinct decompositions of number $m$ into the product of $n$ ordered positive integers.\n\nDecomposition into $n$ products, given in the input, must also be considered in the answer. As the answer can be very large, print it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Let's factorize all $n$ numbers into prime factors. Now we should solve the problem for every prime independently and multiply these answers. The number of ways to split $p^{k}$ into $n$ multipliers, where $p$ is prime, is equal to $C(k + n - 1, n - 1)$ (it can be obtained using the method of stars and bars, you can read about it here, choose 'combinatorics'). So we have a solution that needs $O(n\\cdot{\\sqrt{M A X A}}+n\\cdot\\log M A X A)$ time.",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ]
  },
  {
    "contest_id": "396",
    "index": "B",
    "title": "On Sum of Fractions",
    "statement": "Let's assume that\n\n- $v(n)$ is the largest prime number, that does not exceed $n$;\n- $u(n)$ is the smallest prime number strictly greater than $n$.\n\nFind $\\sum_{i=2}^{n}{\\frac{1}{v(i)u(i)}}$.",
    "tutorial": "First of all, let's consider $n + 1 = p$ is prime. Then we can prove by induction that the answer is ${\\frac{1}{2}}-{\\frac{1}{p}}$. Base for $p = 3$ is obvious. If this equality holds for $p$, and $q$ is the next prime, then answer for $q$ is equal to answer for $p$ plus $q - p$ equal summands $\\mathbf{\\Sigma}_{P q}^{1}$, that is $\\textstyle{\\frac{1}{2}}-{\\frac{1}{q}}$, that's we wanted to prove. Next using that the distance between two consecutive primes not exceeding $10^{9}$ does not exceed $300$, we can find the answer as a sum of the answer for the maximal prime not exceeding $n$ and several equal summands $\\mathbf{\\Sigma}_{P q}^{1}$. We see that the denominator is a divisor of $2pq$, which fits in long long.",
    "tags": [
      "math",
      "number theory"
    ]
  },
  {
    "contest_id": "396",
    "index": "C",
    "title": "On Changing Tree",
    "statement": "You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is a vertex number $1$.\n\nInitially all vertices contain number $0$. Then come $q$ queries, each query has one of the two types:\n\n- The format of the query: $1$ $v$ $x$ $k$. In response to the query, you need to add to the number at vertex $v$ number $x$; to the numbers at the \\textbf{descendants} of vertex $v$ at distance $1$, add $x - k$; and so on, to the numbers written in the descendants of vertex $v$ at distance $i$, you need to add $x - (i·k)$. The distance between two vertices is the number of edges in the shortest path between these vertices.\n- The format of the query: $2$ $v$. In reply to the query you should print the number written in vertex $v$ modulo $1000000007$ $(10^{9} + 7)$.\n\nProcess the queries given in the input.",
    "tutorial": "We can write all vertices in the list in order of $dfs$, then the descendants of the vertex from a segment of this list. Let's count for every vertex its distance to the root $level[v]$. Let's create two segment trees $st1$ and $st2$. If we are given a query of the first type, in $st1$ we add $x + level[v] \\cdot k$ to the segment corresponding to the vertex $v$, in $st2$ we add $k$ to the segment corresponding to the vertex $v$. If we are given a query of the second type, we write st1.get(v) - st2.get(v) * level[v]. The complexity is O(qlogn). You can use any other data stucture that allows to add to the segment and to find a value of an arbitrary element. Also there exists a solution using Heavy-Light decomposition.",
    "tags": [
      "data structures",
      "graphs",
      "trees"
    ]
  },
  {
    "contest_id": "396",
    "index": "D",
    "title": "On Sum of Number of Inversions in Permutations",
    "statement": "You are given a permutation $p$. Calculate the total number of inversions in all permutations that lexicographically do not exceed the given one.\n\nAs this number can be very large, print it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Let's prove a useful fact: sum of number of invertions for all permutations of size $k$ is equal to $s u m A l l[k]=k!\\cdot{\\frac{k(k-1)}{4}}$. The prove is simple: let's change in permutation $p$ for every $i$ $p_{i}$ to $k + 1 - p_{i}$. Then the sum of number of invertions of the first and the second permutations is $\\frac{k(k-1)}{2}$, and our conversion of the permutation is a biection. Now we suppose that we are given a permutation of numbers from $0$ to $n - 1$. Let's go at $p$ from left to right. What permutations are less than $p$? Permutations having first number less than $p_{0}$. If the first number is $a < p_{0}$, than in every such permutation there are a inversions of form (first element, some other element). So in all permutations beginning with $a$ there are $a \\cdot (n - 1)!$ inversions of this from. Moreover, there are inversions not including the first element, their sum is $sumAll[n - 1]$. Then, counting sum for all $a$ we have ${\\frac{p_{0}(p_{0}-1)}{2}}\\cdot\\left(n-1\\right)!+p_{0}\\cdot s u m A l l[n-1]$ inversions. Permutations beginning with $p_{0}$. At first, we should count the number of inversions, beginning in $p_{0}$. There are $cnt \\cdot p_{0}$ of this form, where $cnt$ is the number of permutations beginning with $p_{0}$ and not exceeding $p$. Then we should count the inversions not beginning in the beginning. But it is the same problem! The only exception is that if $p_{1} > p_{0}$, there are $p_{1} - 1$ available numbers less than $p_{1}$, but not $p_{1}$. So we get a solution: go from left to right, keep already used numbers in Fenwick tree, and then solve the same problem, assuming that the first number is not $p_{i}$ but $p_{i}$ - (the number of used numbers less than $p_{i}$). The last we should do is to count the number of permutations not exceeding the suffix of $p$ and beginning the same. It can be precomputed, if we go from right to left. In this case we should do the same as in the first part of solution, but consider that the minimal number is a number of already used numbers less than current.",
    "tags": [
      "combinatorics",
      "math"
    ]
  },
  {
    "contest_id": "396",
    "index": "E",
    "title": "On Iteration of One Well-Known Function",
    "statement": "Of course, many of you can calculate $φ(n)$ — the number of positive integers that are less than or equal to $n$, that are coprime with $n$. But what if we need to calculate $φ(φ(...φ(n)))$, where function $φ$ is taken $k$ times and $n$ is given in the canonical decomposition into prime factors?\n\nYou are given $n$ and $k$, calculate the value of $φ(φ(...φ(n)))$. Print the result in the canonical decomposition into prime factors.",
    "tutorial": "We will describe an algorithm and then understand why it works. For every prime we will maintain a list of intervals. At the first moment for every $p_{i}$ we add in its list interval $[0;a_{i})$, other primes have an empty list. Then we go from big primes to small. Let's consider that current prime is $p$. If in its list there exists an interval $[x;y)$, $x < k, y > k$, we divide it into two parts $[x;k)$ and $[k;y)$. Then for every interval $[x;y)$, $x  \\ge  k$ (in fact, in this case $x = k$) we add to the answer for $p$ $y - x$. For intervals, where $y  \\le  k$, we add to list of every prime divisor of $p - 1$ invterval $[x + 1, y + 1)$. If $p - 1$ has some prime if more than first power, we should add this segment several times. After that we should conduct a \"union with displacement\" operation for every prime which list was changed. If in one list there are $2$ invervals $[x, y), [z, t)$ so that $y  \\le  z > x$, we replace them with one interval $[x, y + t - z)$ (so we added $t - z$ to the right border of the first interval). Then we go to next (lesser) $p$. Why does it works? If we take function $ \\phi $ one time, for every prime $p$ which divides $n$, $n$ is divided by $p$ and multiplied by $p - 1$ (or, the same, by all prime divisors $p - 1$ in corresponding powers). Now we can observe that intervals in lists contains the numbers of iterations, when the number contains the corresponding prime number. Bigger primes do not affect smaller, so we can process them earlier. If after $i$-th iteration the number contains prime number $p$, after $i + 1$-th iteration it contains prime divisors of $p - 1$, and we add segments in accordance with this. The k-th iteration is the last, so the existence of the interval $[k, x)$ means that after $k$-th iteration we have $(x - k)$-th power of this prime. From this it is clear why we unite the intervals if that way. Why does it work fast? Because we precalculated the minimal prime divisor of each number up to $MAXPRIME$ using linear Eratosthenes sieve. (Well, it's not necessary) Because we precalculated the minimal prime divisor of each number up to $MAXPRIME$ using linear Eratosthenes sieve. (Well, it's not necessary) Because for each prime there's no more than $\\log M A X P R I M E=20$ intervals, because for each $[a, b)$ range $a\\leq\\log M A X P R I M E+1$. Practically there is no more than $6$ segments at once. Because for each prime there's no more than $\\log M A X P R I M E=20$ intervals, because for each $[a, b)$ range $a\\leq\\log M A X P R I M E+1$. Practically there is no more than $6$ segments at once.",
    "tags": [
      "math"
    ]
  },
  {
    "contest_id": "397",
    "index": "A",
    "title": "On Segment's Own Points",
    "statement": "Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm.\n\nThe dorm has exactly one straight dryer — a $100$ centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate $0$, and the opposite end has coordinate $100$. Overall, the university has $n$ students. Dean's office allows $i$-th student to use the segment $(l_{i}, r_{i})$ of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!\n\nAlexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others $(n - 1)$ students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.",
    "tutorial": "Create an array $used$ of $100$ elements. i-th element for the segment $(i, i + 1)$. For every student except Alexey set $used[i] = true$ for each segment $(i, i + 1)$ in the segment of that student. After that for each subsegment $(i, i + 1)$ of Alexey's segment add 1 to result if $used[i] = false$.",
    "tags": [
      "implementation"
    ]
  },
  {
    "contest_id": "397",
    "index": "B",
    "title": "On Corruption and Numbers",
    "statement": "Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.\n\nThe situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — $n_{i}$ berubleys. He cannot pay more than $n_{i}$, because then the difference between the paid amount and $n_{i}$ can be regarded as a bribe!\n\nEach rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than $r_{i}$. The rector also does not carry coins of denomination less than $l_{i}$ in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination $x$ berubleys, where $l_{i} ≤ x ≤ r_{i}$ (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.\n\nThanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.\n\nIn other words, you are given $t$ requests, each of them contains numbers $n_{i}, l_{i}, r_{i}$. For each query you need to answer, whether it is possible to gather the sum of exactly $n_{i}$ berubleys using only coins with an integer denomination from $l_{i}$ to $r_{i}$ berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.",
    "tutorial": "First of all, calculate how many $L$'s we can bring so that the result will not exceed $N$. It's $K={\\frac{N}{L}}$. Now, if $R \\cdot K  \\ge  N$ we may increase any of $K$ numbers by $1$. At some moment sum will be equal to $N$ becase sum of $K$ $R$'s is greater than $N$. So answer in this case is YES. If $R \\cdot K < N$, we can't get $K$ or less numbers because their sum is less than $N$. But we can't get more than $K$ numbers too, because their sum is more than $N$. So answer is NO. Complexity: O(1) for every query. Overall complexity: O(t).",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ]
  },
  {
    "contest_id": "398",
    "index": "A",
    "title": "Cards",
    "statement": "User ainta loves to play with cards. He has $a$ cards containing letter \"o\" and $b$ cards containing letter \"x\". He arranges the cards in a row, and calculates the score of the deck by the formula below.\n\n- At first, the score is $0$.\n- For each block of contiguous \"o\"s with length $x$ the score increases by $x^{2}$.\n- For each block of contiguous \"x\"s with length $y$ the score decreases by $y^{2}$.\n\n For example, if $a = 6, b = 3$ and ainta have arranged the cards in the order, that is described by string \"ooxoooxxo\", the score of the deck equals $2^{2} - 1^{2} + 3^{2} - 2^{2} + 1^{2} = 9$. That is because the deck has 5 blocks in total: \"oo\", \"x\", \"ooo\", \"xx\", \"o\".\n\nUser ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards.",
    "tutorial": "Let the number of o blocks $p$, and the number of x blocks $q$. It is obvious that $|p - q|  \\le  1$ and $p, q  \\le  n$. So we can just iterate all $p$ and $q$, and solve these two problems independently, and merge the answer. 1. Maximize the value of $x_{1}^{2} + x_{2}^{2} + ... + x_{p}^{2}$ where $x_{1} + x_{2} + ... + x_{p} = a$ and $x_{i}  \\ge  1$. Assign $a - p + 1$ to $x_{1}$, and assign $1$ to $x_{2}, x_{3}, ..., x_{p}$. The value is $(a - p + 1)^{2} + (p - 1)$. 2. Minimize the value of $y_{1}^{2} + y_{2}^{2} + ... + y_{q}^{2}$ where $y_{1} + y_{2} + ... + y_{q} = b$ and $y_{i}  \\ge  1$. For all $1\\leq i\\leq(b\\ \\mathrm{mod}\\ q)$, assign $\\left\\lfloor{\\frac{b}{q}}\\right\\rfloor+1$ to $y_{i}$. For all $(b\\mod q)+1\\leq j\\leq q$, assign $\\textstyle{\\left|{\\frac{b}{q}}\\right|}$ to $y_{j}$. The value is $([\\frac{b}{q}]+1)^{2}\\times(b\\mathrm{\\boldmath~\\mod~}q)+([\\frac{b}{q}])^{2}\\times\\{q-(b\\mathrm{\\boldmath~\\mod~}q)\\}$. The proof is easy, so I won't do it. With this, we can solve the problem. We can print $y_{1}$ xs, and then $x_{1}$ os, ... Time complexity: $O(n)$.",
    "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h> \n \nusing namespace std;\ntypedef long long ll;\ntypedef double lf;\ntypedef long double llf;\ntypedef unsigned long long llu; \n \nll sq(ll v) { return v*v; }\n \nint main() {\n    ll a, b;\n\tscanf(\"%I64d%I64d\", &a, &b);\n \n\tll n = min(a, b);\n \n \n\tif(a == 0) {\n\t\tprintf(\"%I64d\\n\", -sq(b));\n\t\tfor(ll i = 0; i < b; i++) putchar('x');\n\t}\n\telse if(b <= 1) {\n\t\tprintf(\"%I64d\\n\", sq(a) - sq(b));\n\t\tfor(ll i = 0; i < a; i++) putchar('o');\n\t\tfor(ll i = 0; i < b; i++) putchar('x');\n\t}\n\telse {\n\t\tll res = -sq(a + b);\n\t\tll res_w, res_l;\n\t\tfor(int w = 1; w <= n; w++) {\n\t\t\tfor(int l = w-1; l <= w+1; l++) if(1 <= l && l <= b) {\n\t\t\t\t// w groups winning, l groups losing\n\t\t\t\tll positive = sq(a - (w-1)) + (w-1);\n\t\t\t\tll negative = sq(b / l + 1) * (b % l) + sq(b / l) * (l - b % l);\n\t\t\t\tif(res < positive - negative) {\n\t\t\t\t\tres = positive - negative;\n\t\t\t\t\tres_w = w; res_l = l;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprintf(\"%I64d\\n\", res);\n \n\t\tif(res_w >= res_l) {\n\t\t\tfor(ll i = 0; i < res_w; i++) {\n\t\t\t\tint wl = (i > 0) ? 1 : a - (res_w-1);\n\t\t\t\tfor(int x = 0; x < wl; x++) putchar('x');\n\t\t\t\tint ll = (i < b % res_l) ? (b / res_l + 1) : (b / res_l);\n\t\t\t\tif(i < res_l) for(int x = 0; x < ll; x++) putchar('o');\n\t\t\t}\n\t\t}else {\n\t\t\tfor(ll i = 0; i < res_l; i++) {\n\t\t\t\tint ll = (i < b % res_l) ? (b / res_l + 1) : (b / res_l);\n\t\t\t\tfor(int x = 0; x < ll; x++) putchar('x');\n\t\t\t\tint wl = (i > 0) ? 1 : a - (res_w-1);\n\t\t\t\tif(i < res_w) for(int x = 0; x < wl; x++) putchar('o');\n\t\t\t}\n\t\t}\n\t}\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ]
  },
  {
    "contest_id": "398",
    "index": "B",
    "title": "Painting The Wall",
    "statement": "User ainta decided to paint a wall. The wall consists of $n^{2}$ tiles, that are arranged in an $n × n$ table. Some tiles are painted, and the others are not. As he wants to paint it beautifully, he will follow the rules below.\n\n- Firstly user ainta looks at the wall. If there is at least one painted cell on each row and at least one painted cell on each column, he stops coloring. Otherwise, he goes to step 2.\n- User ainta choose any tile on the wall with uniform probability.\n- If the tile he has chosen is not painted, he paints the tile. Otherwise, he ignores it.\n- Then he takes a rest for one minute even if he doesn't paint the tile. And then ainta goes to step 1.\n\n However ainta is worried if it would take too much time to finish this work. So he wants to calculate the expected time needed to paint the wall by the method above. Help him find the expected time. You can assume that choosing and painting any tile consumes no time at all.",
    "tutorial": "This can be solved by dynamic programming. Let $T[i, j]$ the expected time when $i$ rows and $j$ columns doesn't have any painted cells inside. Let's see all the cases. If we carefully rearrange the order of rows and columns, we can divide the wall into 4 pieces. Choose a cell in rectangle 1. The size of this rectangle is $i  \\times  j$. The expectation value is $T[i - 1, j - 1]$. Choose a cell in rectangle 2. The size of this rectangle is $i  \\times  (n - j)$. The expectation value is $T[i - 1, j]$. Choose a cell in rectangle 3. The size of this rectangle is $(n - i)  \\times  j$. The expectation value is $T[i, j - 1]$. Choose a cell in rectangle 4. The size of this rectangle is $(n - i)  \\times  (n - j)$. The expectation value is $T[i, j]$. Merging these four cases, we can get: $T[i, j] = 1 + {T[i - 1, j - 1]  \\times  i  \\times  j + T[i - 1, j]  \\times  i  \\times  (n - j) + T[i, j - 1]  \\times  (n - i)  \\times  j + T[i, j]  \\times  (n - i)  \\times  (n - j)} / n^{2}$ Moving the $T[i, j]$ on the right to the left, we can get the formula which can be used to calculate the value $T[i, j]$. There are some corner cases, like $i = 0$ or $j = 0$, but it can be simply handled. Time complexity: $O(n^{2})$",
    "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h> \n \nusing namespace std;\ntypedef long long ll;\ntypedef double lf;\ntypedef long double llf;\ntypedef unsigned long long llu;\n \nint N, M;\nlf Table[2005][2005];\nint R, C;\nbool chkR[2005], chkC[2005];\n \nint main() {\n\tscanf(\"%d%d\", &N, &M);\n\t\n\tR = C = N;\n\tfor(int i = 1; i <= M; i++) {\n\t\tint r, c; scanf(\"%d%d\", &r, &c);\n\t\tif(!chkR[r]) --R;\n\t\tif(!chkC[c]) --C;\n\t\tchkR[r] = chkC[c] = true;\n\t}\n \n\tfor(int i = 1; i <= N; i++) Table[i][0] = Table[i-1][0] + (lf)N / i;\n\tfor(int j = 1; j <= N; j++) Table[0][j] = Table[0][j-1] + (lf)N / j;\n\tfor(int i = 1; i <= N; i++) for(int j = 1; j <= N; j++) {\n\t\tlf &v = Table[i][j];\n\t\tv = (i * j * Table[i-1][j-1])\n\t\t\t + ((N - i) * j * Table[i][j-1])\n\t\t\t + (i * (N - j) * Table[i-1][j]);\n\t\tv /= N*N;\n\t\tv = v+1;\n\t\tv /= (1. - (lf)(N-i) * (N-j) / (N*N));\n\t}\n \n\tprintf(\"%.10Lf\\n\", Table[R][C]);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "probabilities"
    ]
  },
  {
    "contest_id": "398",
    "index": "C",
    "title": "Tree and Array",
    "statement": "User ainta likes trees. This time he is going to make an undirected tree with $n$ vertices numbered by integers from $1$ to $n$. The tree is weighted, so each edge of the tree will have some integer weight.\n\nAlso he has an array $t$: $t[1], t[2], ..., t[n]$. At first all the elements of the array are initialized to $0$. Then for each edge connecting vertices $u$ and $v$ ($u < v$) of the tree with weight $c$, ainta adds value $c$ to the elements $t[u], t[u + 1], ..., t[v - 1], t[v]$ of array $t$.\n\nLet's assume that $d(u, v)$ is the total weight of edges on the shortest path between vertex $u$ and vertex $v$. User ainta calls a pair of integers $x, y$ ($1 ≤ x < y ≤ n$) good if and only if $d(x, y) = t[x] + t[x + 1] + ... + t[y - 1] + t[y]$.\n\nUser ainta wants to make at least $\\lfloor{\\frac{n}{2}}\\rfloor$ good pairs, but he couldn't make a proper tree. Help ainta to find such a tree.",
    "tutorial": "There are two intended solutions. One is easy, and the other is quite tricky. Easy Solution Make a tree by the following method. For all $1\\leq i\\leq\\lfloor{\\frac{n}{2}}\\rfloor$, make an edge between vertex $i$ and $i+\\lfloor{\\frac{n}{2}}\\rfloor$ with weight 1. For all $\\lfloor{\\frac{n}{2}}\\rfloor<i<n$, make an edge between vertex $i$ and $i + 1$ with weight $2(i-[\\frac{n}{2}])-1$. You can see that $(1,2),(2,3),\\cdot\\cdot\\cdot\\,,(\\,\\lfloor{\\frac{n}{2}}\\rfloor-1,\\lfloor{\\frac{n}{2}}\\rfloor)$ are all good pairs. In addition, $(1, 3)$ is also a good pair. So we can print the answer. But, if $n = 5$, this method doesn't work because $(1, 3)$ is not a good pair. In this case, one may solve by hand or using random algorithm. Time complexity: $O(n)$ Bonus I: Is there any method to make more than $\\textstyle{\\left[{\\frac{n}{2}}\\right]}$ good pairs? Bonus II: Is there any method that the maximum weight is relatively small and make at least $\\lfloor{\\frac{n}{2}}\\rfloor$ good pairs? Tricky Solution If you got stuck with the problem, one can run any random algorithm that solves small cases, and merge these cases. With this approach, we can even limit the weight to a very small constant! But I think this is not a good solution, so I won't mention about unless anybody wants to know the details. I came up with this solution, and tried to purpose this as D. It seems all the 6 people who passed pretests during the contest didn't use this solution :) Time complexity: ???",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h> \n \nusing namespace std;\ntypedef long long ll;\ntypedef double lf;\ntypedef long double llf;\ntypedef unsigned long long llu; \n \nconst int trees[10][10][3] = {\n\t{ },\n\t{ },\n\t{ \n\t\t{0, 1, 1},\n\t},\n\t{ \n\t\t{0, 2, 1},\n\t\t{0, 1, 1},\n\t},\n\t{ \n\t\t{0, 2, 8},\n\t\t{0, 1, 4},\n\t\t{1, 3, 4},\n\t},\n\t{ \n\t\t{0, 1, 4},\n\t\t{0, 3, 3},\n\t\t{1, 2, 6},\n\t\t{3, 4, 1},\n\t},\n\t{ \n\t\t{0, 1, 6},\n\t\t{0, 3, 2},\n\t\t{1, 4, 2},\n\t\t{1, 2, 3},\n\t\t{4, 5, 4},\t\n\t},\n\t{ \n\t\t{0, 1, 7},\n\t\t{0, 5, 1},\n\t\t{0, 2, 10},\n\t\t{1, 4, 1},\n\t\t{2, 3, 1},\n\t\t{5, 6, 6},\t\n\t},\n\t{ \n\t\t{0, 4, 1},\n\t\t{0, 1, 3},\n\t\t{0, 3, 1},\n\t\t{1, 2, 2},\n\t\t{4, 7, 2},\n\t\t{5, 6, 3},\n\t\t{6, 7, 3},\n\t}\n};\n \nconst int queries[10][10][2] = {\n\t{ },\n\t{ },\n\t{ },\n\t{ },\n\t{ {2, 3} },\n\t{ {2, 3}, {2, 4} },\n\t{ {2, 3}, {3, 4}, {3, 5} },\n\t{ {2, 4}, {3, 5}, {3, 6}, {4, 5}, {4, 6} },\n\t{ {2, 3}, {2, 5}, {3, 5}, {4, 5} }\n};\n \nconst int num_queries[10] = {0, 0, 0, 0, 1, 2, 3, 5, 4};\nconst int num_queries_tail[10] = {0, 0, 0, 0, 1, 1, 1, 2, 0};\nint n;\nint table[100005], rec[100005];\n \nint merged_tree[100005][3];\nint merged_queries[100005][3];\n \nint main() {\n\tscanf(\"%d\", &n);\n\tfor(int i = 4; i <= 8; i++) rec[i] = i, table[i] = num_queries[i];\n\tfor(int i = 9; i <= n; i++) {\n\t\tfor(int j = 2; j <= 8; j++) {\n\t\t\tint q = table[i-j] + (num_queries[j] - num_queries_tail[j]);\n\t\t\tif(q > table[i]) table[i] = q, rec[i] = j;\n\t\t}\n\t}\n \n\tint t = n, x = 1, q = 0, e = 0;\n\twhile(t > 0) {\n\t\tint sz = rec[t];\n\t\tfor(int i = 0; i < sz-1; i++) {\n\t\t\tmerged_tree[e][0] = trees[sz][i][0] + x;\n\t\t\tmerged_tree[e][1] = trees[sz][i][1] + x;\n\t\t\tmerged_tree[e][2] = trees[sz][i][2];\n\t\t\te++;\n\t\t}\n\t\tfor(int i = 0; i < num_queries[sz] && q < n/2; i++) {\n\t\t\tif(t > 8 && queries[sz][i][1] == sz - 1) continue;\n\t\t\tmerged_queries[q][0] = queries[sz][i][0] + x;\n\t\t\tmerged_queries[q][1] = queries[sz][i][1] + x;\n\t\t\tq++;\n\t\t}\n\t\tx += sz;\n\t\tt -= sz;\n\t\tif(t > 0) {\n\t\t\tmerged_tree[e][0] = x-1;\n\t\t\tmerged_tree[e][1] = x;\n\t\t\tmerged_tree[e][2] = 1;\n\t\t\te++;\n\t\t}\n\t}\nif(q < n/2) printf(\"queries = %d\\n\", q);\n \n\tfor(int i = 0; i < e; i++) {\n\t\tfor(int j = 0; j < 3; j++) printf(\"%d%c\", merged_tree[i][j], (j == 2) ? '\\n' : ' ');\n\t}\n \n\tfor(int i = 0; i < q; i++) {\n\t\tfor(int j = 0; j < 2; j++) printf(\"%d%c\", merged_queries[i][j], (j == 1) ? '\\n' : ' ');\n\t}\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ]
  },
  {
    "contest_id": "398",
    "index": "D",
    "title": "Instant Messanger",
    "statement": "User ainta decided to make a new instant messenger called \"aintalk\". With aintalk, each user can chat with other people. User ainta made the prototype of some functions to implement this thing.\n\n- login($u$): User $u$ logins into aintalk and becomes online.\n- logout($u$): User $u$ logouts and becomes offline.\n- add_friend($u$, $v$): User $u$ and user $v$ become friends. It means, $u$ and $v$ can talk with each other. The friendship is bidirectional.\n- del_friend($u$, $v$): Unfriend user $u$ and user $v$. It means, $u$ and $v$ cannot talk with each other from then.\n- count_online_friends($u$): The function returns the number of friends of user $u$ who are online at the moment.\n\n Because the messenger is being tested by some users numbered from $1$ to $n$, there is no register method. This means, at the beginning, some users may be online, and some users may have friends.\n\nUser ainta is going to make these functions, but before making the messenger public, he wants to know whether he is correct. Help ainta verify his code.",
    "tutorial": "Let $x_{i}$ an integer representing the state of the i-th user. If user i is online, $x_{i} = 1$, otherwise, $x_{i} = 0$. Also, let $S_{i}$ the set consisting of i-th friends. One can see that the queries become like this: Online/Offline: change the value of $x_{i}$ to $1 - x_{i}$. Add: add $u$ to set $S_{v}$, and $v$ to set $S_{u}$. Delete: delete $u$ from set $S_{v}$, $v$ from set $S_{u}$. Count: calculate $\\textstyle\\sum_{w\\in S_{w}}x_{w}$. Let's use sqrt-decomposition to perform these queries. Let user $u$ heavy if $|S_{u}|  \\ge  C$, or light otherwise. Also, we will define some arrays and sets: $H_{u}$ is a set that stores friends with user $u$ who are heavy users. $O[u]$ stores the sum of . If the Online/Offline($u$) query is given, If $u$ is a light user: for all , change the value of $O[v]$. It takes $O(|S_{u}|)$ time. Otherwise: just update the state of itself. If the Add($u, v$) query is given, If vertex $u$ becomes heavy if we add this edge, for all , add $v$ into $H_{w}$ and update the value of $O[w]$. This can be done in $O(C)$. If vertex $u$ is still light even if we add the edge, update $O[v]$. This can be done in constant time. If vertex $u$ is heavy (after the operations above), update $H_{v}$. Add $u$ to set $S_{v}$, and $v$ to set $S_{u}$. If the Delete($u, v$) query is given, Delete $u$ from set $S_{v}$, and $v$ from set $S_{u}$. Update the value of $O[*]$, $H_{u}$ and $H_{v}$. Because for all $|H_{w}|  \\le  E| / C$, this can be done in $O(|E| / C)$. If the counting query is given, $O[u]+\\sum_{w\\in H_{w}}x_{u}$ will be the answer. Because $|H_{u}|  \\le  |E| / C$, it will take $O(|E| / C)$ time. So for each query, $O(|E| / C)$ or $O(C)$ time is required. To minimize the time, . Time complexity: $O(q{\\sqrt{|E|}})$ We can also solve this by dividing the queries into ${\\sqrt{q}}$ parts. For each block, use $O(n + m + q)$ time to build the online & offline state and the answer table for each vertices. For each query, you can use $O({\\sqrt{q}})$ time to get the answer. If you want more details, please ask in the comments. Time complexity: $O(q{\\sqrt{q}})$",
    "code": "#include<stdio.h>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n#define N_ 100010\n#define Q_ 250010\n#define M_ 150010\nint n, m, Q, SZ, C[N_], cnt, st[N_], beg[N_], Next[(M_ + Q_) * 2];\nbool v[N_];\nstruct Query{\n\tint a, b;\n\tchar ck;\n}w[Q_];\nstruct Edge{\n\tint a, b;\n\tbool ck;\n\tbool operator <(const Edge &p)const{\n\t\treturn a != p.a ? a < p.a : b < p.b;\n\t}\n}Ed[(M_ + Q_) * 2];\nbool on[N_];\nvoid UDT(int a, int b){\n\tint B = st[a], E = st[a+1] - 1, M;\n\twhile (B <= E){\n\t\tM = (B + E) >> 1;\n\t\tif (Ed[M].b == b)break;\n\t\tif (Ed[M].b > b) E = M - 1;\n\t\telse B = M + 1;\n\t}\n\tEd[M].ck = !Ed[M].ck;\n\tif (v[a] && on[b]){\n\t\tif (Ed[M].ck)C[a]++;\n\t\telse C[a]--;\n\t}\n}\nint main()\n{\n\tint i, j, o, cnt = 0, a, b, pv, be, ed, x, t;\n\tchar pp[2];\n\tscanf(\"%d%d%d%d\", &n, &m, &Q, &o);\n\twhile (o--){\n\t\tscanf(\"%d\", &i);\n\t\ton[i] = true;\n\t}\n\tfor (i = 0; i < m; i++){\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tEd[cnt].a = a, Ed[cnt].b = b, Ed[cnt++].ck = true;\n\t\tEd[cnt].a = b, Ed[cnt].b = a, Ed[cnt++].ck = true;\n\t}\n\tfor (i = 1; i*i <= Q; i++);\n\tSZ = i * 2;\n\tfor (i = 0; i < Q; i++){\n\t\tscanf(\"%s%d\", &pp, &w[i].a);\n\t\tw[i].ck = pp[0];\n\t\tif (w[i].ck == 'A' || w[i].ck == 'D'){\n\t\t\tscanf(\"%d\", &w[i].b);\n\t\t\tEd[cnt].a = w[i].a, Ed[cnt++].b = w[i].b;\n\t\t\tEd[cnt].a = w[i].b, Ed[cnt++].b = w[i].a;\n\t\t}\n\t}\n\tsort(Ed, Ed + cnt);\n\to = 0, pv = 0;\n\tfor (i = 0; i < cnt; i++){\n\t\tif (!i || Ed[i].a != Ed[i - 1].a || Ed[i].b != Ed[i - 1].b){\n\t\t\tif (!i || Ed[i].a != Ed[i - 1].a){\n\t\t\t\twhile (pv != Ed[i].a){\n\t\t\t\t\tpv++;\n\t\t\t\t\tst[pv] = o;\n\t\t\t\t}\n\t\t\t}\n\t\t\tEd[o++] = Ed[i];\n\t\t}\n\t\telse if (Ed[i].ck)Ed[o - 1].ck = true;\n\t}\n\twhile (pv != n + 1){\n\t\tpv++; st[pv] = o;\n\t}\n\tbe = 0;\n\tfor (i = 1; i <= n; i++)beg[i] = -2;\n\twhile (1){\n\t\ted = be + SZ;\n\t\tif (ed > Q)ed = Q;\n\t\tcnt = 0;\n\t\tfor (i = be; i < ed;i++){\n\t\t\tif (w[i].ck == 'C'){\n\t\t\t\tif (!v[w[i].a]){\n\t\t\t\t\tv[w[i].a] = true;\n\t\t\t\t\tC[w[i].a] = 0;\n\t\t\t\t\tfor (j = st[w[i].a]; j < st[w[i].a + 1]; j++){\n\t\t\t\t\t\tif (Ed[j].ck && on[Ed[j].b])C[w[i].a]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (i = be; i < ed; i++){\n\t\t\tif (w[i].ck == 'O' || w[i].ck == 'F'){\n\t\t\t\tx = w[i].a;\n\t\t\t\ton[x] = !on[x];\n\t\t\t\tif (on[x]) a = 1;\n\t\t\t\telse a = -1;\n\t\t\t\tif (beg[x] == -2){\n\t\t\t\t\tfor (j = st[x]; j != st[x + 1]; j++){\n\t\t\t\t\t\tif (v[Ed[j].b]){\n\t\t\t\t\t\t\tif(Ed[j].ck)C[Ed[j].b] += a;\n\t\t\t\t\t\t\tif (beg[x] == -2)beg[x] = j, t = j;\n\t\t\t\t\t\t\telse Next[t] = j, t = j;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (beg[x] == -2)beg[x] = -1;\n\t\t\t\t\telse Next[t] = -1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tt = beg[x];\n\t\t\t\t\twhile (t != -1){\n\t\t\t\t\t\tif (Ed[t].ck)C[Ed[t].b] += a;\n\t\t\t\t\t\tt = Next[t];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(w[i].ck == 'D' || w[i].ck == 'A'){\n\t\t\t\tUDT(w[i].a, w[i].b);\n\t\t\t\tUDT(w[i].b, w[i].a);\n\t\t\t}\n\t\t\telse printf(\"%d\\n\", C[w[i].a]);\n\t\t}\n\t\tfor (i = be; i < ed; i++){\n\t\t\tif (w[i].ck == 'C')v[w[i].a] = false;\n\t\t\tif (w[i].ck == 'O' || w[i].ck == 'F')beg[w[i].a] = -2;\n\t\t}\n\t\tif (ed == Q)break;\n\t\tbe = ed;\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ]
  },
  {
    "contest_id": "398",
    "index": "E",
    "title": "Sorting Permutations",
    "statement": "We are given a permutation sequence $a_{1}, a_{2}, ..., a_{n}$ of numbers from $1$ to $n$. Let's assume that in one second, we can choose some disjoint pairs $(u_{1}, v_{1}), (u_{2}, v_{2}), ..., (u_{k}, v_{k})$ and swap all $a_{ui}$ and $a_{vi}$ for every $i$ at the same time ($1 ≤ u_{i} < v_{i} ≤ n$). The pairs are disjoint if every $u_{i}$ and $v_{j}$ are different from each other.\n\nWe want to sort the sequence completely in increasing order as fast as possible. Given the initial permutation, calculate the number of ways to achieve this. Two ways are different if and only if there is a time $t$, such that the set of pairs used for swapping at that time are different as sets (so ordering of pairs doesn't matter). If the given permutation is already sorted, it takes no time to sort, so the number of ways to sort it is $1$.\n\nTo make the problem more interesting, we have $k$ holes inside the permutation. So exactly $k$ numbers of $a_{1}, a_{2}, ..., a_{n}$ are not yet determined. For every possibility of filling the holes, calculate the number of ways, and print the total sum of these values modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Let us start with the case when there is no hole. Given any permutation, I will prove that it takes only at most two seconds to sort it completely. Since every permutation can be decomposed into disjoint cycles (link), we only need to take care of each decomposed cycle. That is, we only need to sort a cycle of arbitrary length in two steps. Let's make a table of 3 rows and $n$ columns. The first row will constitute the original, unsorted permutation. For each column, the next column will form the permutation after one second. The last column will be the sorted permutation. The following depicts the case where $n = 5$ and the permutation is a full cycle. 2 3 4 5 1 ? ? ? ? ? 1 2 3 4 5Now we have to show that we can fill the second column properly. Let's just fill the first number in the second column randomly, say 4, and see what happens. 2 3 4 5 1 4 ? ? ? ? 1 2 3 4 5Because 4 replaces 2 in the second column, 2 replaces 4 and we are forced to put 2 below the 4 in first column. 2 3 4 5 1 4 ? 2 ? ? 1 2 3 4 5Likewise, 3 replaces 2 in the third column, so we should put 3 above 2 in the third column. 2 3 4 5 1 4 3 2 ? ? 1 2 3 4 5Repeating the process will finally give a complete, valid answer. 2 3 4 5 1 4 3 2 1 5 1 2 3 4 5Like the example above, filling the first number in the second column by any number will give a unique and valid answer. I won't prove it formally, but by experimenting with different examples you can see it indeed works :) So now we know that (i) any permutation can be sorted in 2 seconds and, additionally, (ii) if the permutation is a cycle, there are exactly $n$ ways of doing it. Now let us see what happens if two disjoint cycles interact with each other. Try to fill the tables below and figure out what happens. First one is a disjoint union of cycles of length 4 and 5. Second one is a union of cycles of length 4 and 4. 2 3 4 5 1 7 8 9 6 2 3 4 1 6 7 8 5 8 ? ? ? ? ? ? ? ? 8 ? ? ? ? ? ? ? 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8By experimenting, you will see that if two disjoint cycles $A$ and $B$ interact (to be precise, when an element in $A$ swaps place with another element in $B$), (i) the size of $A$ and $B$ are equal and in that case (ii) the number of ways to achieve a complete assignment for elements of $A$ and $B$ is exactly the size of $A$ (or $B$). I won't prove it, but it can be done formally if one wishes to. Now we have the solution when there is no hole: decompose the permutation into disjoint cycles. Assume there are exactly $c_{i}$ cycles of length $l_{i}$ for each $i$. Let $a[c, l]$ be the number of ways to sort $c$ cycles of length $l$ completely. Then the answer will be $\\prod_{i}a[c_{i},l_{i}]$, basically because only cycles of same length interact. To sort $c$ cycles of length $l$, we can pair some of the cycles to interact with each other. Then each pair and unpaired cycle will contribute multiplicative factor $l$ to the answer. Now we can derive a recursive formula for $a[c, l]$. Just take a cycle $C$ and decide if it will be paired to different cycle or not. For the first case, $C$ contributes multiplicative factor $l$ and we can decide on the rest of $c - 1$ cycles, so there are total of $l \\cdot a[c - 1, l]$ ways. For the second case, we have $c - 1$ ways to pair $C$ with the other cycle, then the pair contributes factor $l$ and we can decide on the remaining $c - 2$ cycles. This contributes $l \\cdot (c - 1) \\cdot a[c - 2, l]$. Adding up will give us the recursive formula. $a[c, l] = l \\cdot a[c - 1, l] + l \\cdot (c - 1) \\cdot a[c - 2, l]$ Computing every $a[c, l]$ can be done in reasonable time: $c_{l}$ will be at most $n / l$ and there will be total of $O(n\\log n)$ values of $a[c, l]$ to compute using the recursive formula above. Given a permutation, we can count the number of cycles $c_{l}$ of length $l$ for each $l$ and compute $a[c_{l}, l]$. Since two cycles of different length cannot interact, the number of ways to sort the whole permutation will be the multiplication of $a[c_{l}, l]$'s over all $l$. Finally, we have to deal with $k  \\le  12$ holes. The crucial observation is that with holes, the permutation decomposes into cycles and paths. Filling the holes will group the paths to disjoint cycles. Considering every $12!$ possible ways will give TLE. But if we note that the order of paths in a same group does not make a change in cycle's length, we can actually deploy a bitmask DP to consider all possible way to partition at most 12 paths. Just multiply some constant to each partition and sum over (I'll skip the details).",
    "tags": []
  },
  {
    "contest_id": "399",
    "index": "A",
    "title": "Pages",
    "statement": "User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are $n$ pages numbered by integers from $1$ to $n$. Assume that somebody is on the $p$-th page now. The navigation will look like this:\n\n\\begin{center}\n<< $p - k$ $p - k + 1$ $...$ $p - 1$ $(p)$ $p + 1$ $...$ $p + k - 1$ $p + k$ >>\n\\end{center}\n\nWhen someone clicks the button \"<<\" he is redirected to page $1$, and when someone clicks the button \">>\" he is redirected to page $n$. Of course if someone clicks on a number, he is redirected to the corresponding page.\n\nThere are some conditions in the navigation:\n\n- If page $1$ is in the navigation, the button \"<<\" must not be printed.\n- If page $n$ is in the navigation, the button \">>\" must not be printed.\n- If the page number is smaller than $1$ or greater than $n$, it must not be printed.\n\n You can see some examples of the navigations. Make a program that prints the navigation.",
    "tutorial": "You can solve this problem by just following the statement. First, print << if $p - k > 1$. Next, iterate all the integers from $p - k$ to $p + k$, and print if the integer is in $[1..n]$. Finally, print >> if $p + k < n$. Time complexity: $O(n)$.",
    "code": "#include <stdio.h>\n \nint n, p, k;\n \nint main() {\n\tscanf(\"%d%d%d\", &n, &p, &k);\n \n\tif(p - k > 1) printf(\"<< \");\n\tfor(int i = p - k; i <= p + k; i++) if(1 <= i && i <= n) printf((i == p) ? \"(%d) \" : \"%d \", i);\n\tif(p + k < n) printf(\">> \");\n \n\treturn 0;\n}",
    "tags": [
      "implementation"
    ]
  },
  {
    "contest_id": "399",
    "index": "B",
    "title": "Red and Blue Balls",
    "statement": "User ainta has a stack of $n$ red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack.\n\n- While the top ball inside the stack is red, pop the ball from the top of the stack.\n- Then replace the blue ball on the top with a red ball.\n- And finally push some blue balls to the stack until the stack has total of $n$ balls inside.\n\n If there are no blue balls inside the stack, ainta can't apply this operation. Given the initial state of the stack, ainta wants to know the maximum number of operations he can repeatedly apply.",
    "tutorial": "Change the blue balls to bit 1, and blue balls to bit 0. Interpret the stack as an integer represented in binary digits. Now, one may see that a single operation decreases the integer by 1, and will be unavailable iff the integer becomes zero. So the answer will be $2^{a1} + 2^{a2} + ... + 2^{ak}$ where the $(a_{i} + 1)$-th ($1  \\le  i  \\le  k$) ball is blue in the beginning. Time complexity: $O(n)$",
    "code": "#include <stdio.h>\n \nint n;\nchar s[55];\nlong long res;\n \nint main() {\n\tscanf(\"%d%s\", &n, s);\n\tfor(int i = 0; i < n; i++) if(s[i] == 'B') res |= 1ll << i;\n\tprintf(\"%I64d\\n\", res);\n\treturn 0;\n}",
    "tags": []
  },
  {
    "contest_id": "400",
    "index": "A",
    "title": "Inna and Choose Options",
    "statement": "There always is something to choose from! And now, instead of \"Noughts and Crosses\", Inna choose a very unusual upgrade of this game. The rules of the game are given below:\n\nThere is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: \"X\" or \"O\". Then the player chooses two positive integers $a$ and $b$ $(a·b = 12)$, after that he makes a table of size $a × b$ from the cards he put on the table as follows: the first $b$ cards form the first row of the table, the second $b$ cards form the second row of the table and so on, the last $b$ cards form the last (number $a$) row of the table. The player wins if some column of the table contain characters \"X\" on all cards. Otherwise, the player loses.\n\nInna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers $a$ and $b$ to choose. Help her win the game: print to her all the possible ways of numbers $a, b$ that she can choose and win.",
    "tutorial": "Not difficult task. Let's iterate param $a$. If $12$ % $a$ != $0$, continue. Calculate $b = 12 / a$. Let's iterate column (from $1$ to $b$) and for each it's cell $(i, j)$ check, if it contains $X$ or not. Cell $(i, j)$ - is $((i-1) * a + j)$ -th element of string.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "400",
    "index": "B",
    "title": "Inna and New Matrix of Candies",
    "statement": "Inna likes sweets and a game called the \"Candy Matrix\". Today, she came up with the new game \"Candy Matrix 2: Reload\".\n\nThe field for the new game is a rectangle table of size $n × m$. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose \\textbf{all lines of the matrix where dwarf is not on the cell with candy} and shout \"Let's go!\". After that, all the dwarves from the chosen lines start to \\textbf{simultaneously} move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:\n\n- some dwarf in one of the chosen lines is located in the rightmost cell of his row;\n- some dwarf in the chosen lines is located in the cell with the candy.\n\nThe point of the game is to transport all the dwarves to the candy cells.\n\nInna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.",
    "tutorial": "In the final version of statement we must choose all lines we haven't finish already. If it is a string where we have $S...G$ - answer $- 1$. Otherwise, the answer is the number of distinct distances, as one step kills all distances of the minimal length.",
    "tags": [
      "brute force",
      "implementation",
      "schedules"
    ],
    "rating": 1200
  },
  {
    "contest_id": "400",
    "index": "C",
    "title": "Inna and Huge Candy Matrix",
    "statement": "Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from $1$ to $n$ from top to bottom and the columns — from $1$ to $m$, from left to right. We'll represent the cell on the intersection of the $i$-th row and $j$-th column as $(i, j)$. Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has $p$ candies: the $k$-th candy is at cell $(x_{k}, y_{k})$.\n\nThe time moved closer to dinner and Inna was already going to eat $p$ of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix $x$ times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix $y$ times. And then he rotated the matrix $z$ times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like.\n\nInna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!",
    "tutorial": "Let's note that the number of 90 clockwise make sence only by modulo 4. Horizontal - by modulo 2, and 90 counterclockwise - by modulo 4, and 1 such rotation is 3 clockwise rotations. 90 clockwise: $newi = j;$ $newj = n-i + 1$ don't forget to $swap(n, m)$. Horizontal: $newj = m-j + 1$",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "400",
    "index": "D",
    "title": "Dima and Bacteria",
    "statement": "Dima took up the biology of bacteria, as a result of his experiments, he invented $k$ types of bacteria. Overall, there are $n$ bacteria at his laboratory right now, and the number of bacteria of type $i$ equals $c_{i}$. For convenience, we will assume that all the bacteria are numbered from $1$ to $n$. The bacteria of type $c_{i}$ are numbered from $(\\sum_{k=1}^{i-1}c_{k})+1$ to $\\sum_{k=1}^{i}c_{k}$.\n\nWith the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows $m$ ways to move energy from some bacteria to another one. The way with number $i$ can be described with integers $u_{i}$, $v_{i}$ and $x_{i}$ mean that this way allows moving energy from bacteria with number $u_{i}$ to bacteria with number $v_{i}$ or vice versa for $x_{i}$ dollars.\n\nDima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.\n\nAs for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix $d$ with size $k × k$. Cell $d[i][j]$ of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type $i$ to bacteria with type $j$.",
    "tutorial": "If the distribution is correct, after deleting all ribs with cost more than 0 graph will transform to components of corrects size. Also, the nodes are numereted so we should turn dfs for the first node of each type and be sure that we receive exact all nodes of this type and no ohter. Now simple floyd warshall, and put in each cell of adjacent matrix of components the minimal weight between all ribs from 1 component to another.",
    "tags": [
      "dsu",
      "graphs",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "400",
    "index": "E",
    "title": "Inna and Binary Logic",
    "statement": "Inna is fed up with jokes about female logic. So she started using binary logic instead.\n\nInna has an array of $n$ elements $a_{1}[1], a_{1}[2], ..., a_{1}[n]$. Girl likes to train in her binary logic, so she does an exercise consisting of $n$ stages: on the first stage Inna writes out all numbers from array $a_{1}$, on the $i$-th $(i ≥ 2)$ stage girl writes all elements of array $a_{i}$, which consists of $n - i + 1$ integers; the $k$-th integer of array $a_{i}$ is defined as follows: $a_{i}[k] = a_{i - 1}[k] AND a_{i - 1}[k + 1]$. Here AND is bit-wise binary logical operation.\n\nDima decided to check Inna's skill. He asks Inna to change array, perform the exercise and say the sum of all $\\textstyle{\\frac{n(n+1)}{2}}$ elements she wrote out during the current exercise.\n\nHelp Inna to answer the questions!",
    "tutorial": "Let's solve this for each bit separately. Fix some bit. Let's put 1 if the number contains bit and 0 otherwise. Now we receive the sequence, for example $11100111101$. Now let's look on sequence of 1 without 0, for this sequence current bit will be added to the sum on the first stage (with all numbers single) on the second stage (with all neighbouring pairs) on the third stage and so on, the number of appiarence for sequence of neighbouring 1 is a formula which depends on the length of sequence only. The last is to learn how to modificate. For each bit let's save the set of sequence of 1. When the bit is deleted, one sequence is sepereted on two, or decreases its length by 1. When the bit is added, new sequence of length 1 appears, or some sequence increases its lentgh by 1 or two sequence transform to 1 biger sequence.",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures"
    ],
    "rating": 2100
  },
  {
    "contest_id": "401",
    "index": "A",
    "title": "Vanya and Cards",
    "statement": "Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed $x$ in the absolute value.\n\nNatasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found $n$ of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?\n\nYou can assume that initially Vanya had infinitely many cards with each integer number from $ - x$ to $x$.",
    "tutorial": "We must sum all numbers, and reduced it to zero by the operations +x and -x.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint ans, sum, x, n, q;\n\nint main()\n\n{\n    scanf(\"%d %d\", &n, &x);\n    sum = 0;\n    for (int i = 0; i < n; i++)\n    {\n        cin>>q;\n        sum += q;\n    }\n    sum = abs(sum);\n    ans = sum / x;\n    if (sum % x != 0) ans++;\n    cout<<ans<<endl;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "401",
    "index": "B",
    "title": "Sereja and Contests",
    "statement": "Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.\n\nCodesorfes has rounds of two types: $Div1$ (for advanced coders) and $Div2$ (for beginner coders). Two rounds, $Div1$ and $Div2$, can go simultaneously, ($Div1$ round cannot be held without $Div2$) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the $Div1$ round is always greater.\n\nSereja is a beginner coder, so he can take part only in rounds of $Div2$ type. At the moment he is taking part in a $Div2$ round, its identifier equals to $x$. Sereja remembers very well that he has taken part in exactly $k$ rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.\n\nSereja is wondering: what minimum and what maximum number of $Div2$ rounds could he have missed? Help him find these two numbers.",
    "tutorial": "You must identify the array of numbers contests that remember Sereja, as employed. If we want to find maximal answer, we must count the number of immune cells. If we want to find mininum answer, we must do the following: if i-th element is free and (i+1)-th element is free, and i<x then we using round type of \"Div1+Div2\" and answer++, i-th and (i+1)-th elements define as employed. if i-th element is free and (i+1)-th element is employed then we usign round type \"Div2\" and answer++, i-th element define as employed.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint min_ans, max_ans, x, k, t, num1, num2, num, a[4001], i;\n\nint main()\n\n{\n    scanf(\"%d%d\", &x, &k);\n    for (int i = 0; i < k; i++)\n    {\n        scanf(\"%d\", &t);\n        if (t == 1)\n        {\n            scanf(\"%d%d\", &num1, &num2);\n            a[num1] = 1;\n            a[num2] = 1;\n        }\n        if (t == 2)\n        {\n            scanf(\"%d\", &num);\n            a[num] = 1;\n        }\n    }\n    i = 1;\n    while (i < x)\n    {\n        if (a[i] == 0)\n        {\n            if (i + 1 < x && a[i + 1] == 0)\n            {\n                a[i] = 1;\n                a[i + 1] = 1;\n                min_ans++;\n                max_ans += 2;\n                i+=2;\n            }\n            else {\n                a[i] = 1;\n                max_ans++;\n                min_ans++;\n                i++;\n            }\n        }\n        else i++;\n    }\n    printf(\"%d %d\", min_ans, max_ans);\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "401",
    "index": "C",
    "title": "Team",
    "statement": "Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.\n\nFor each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying \\textbf{all} the cards in a row so that:\n\n- there wouldn't be a pair of any side-adjacent cards with zeroes in a row;\n- there wouldn't be a group of three consecutive cards containing numbers one.\n\nToday Vanya brought $n$ cards with zeroes and $m$ cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.",
    "tutorial": "n - the number of cards containing number 0 and m - the number of cards containing number 1. We have answer, when ((n-1)<=m && m <= 2 * (n + 1)). If we have answer then we must do the following: if (m == n - 1) then we derive the ones and zeros in one, but we must start from zero. if (m == n) then we derive the ones and zeros in one. if (m > n && m <= 2 * (n + 1)) then we must start form one and we derive the ones and zeros in one, but in the end must be one. And if we in the end and we have ones, then we try to stick to one unit so that we have. For example, we have 10101 and two ones, after we have 110101 and one ones, and then we have 1101101.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nlong long n, m, t, a[3000001], k;\n\n\nint main()\n\n{\n    scanf(\"%d%d\", &n, &m);\n    if (n - 1 <= m && m <= 2*(n + 1))\n    {\n        if (m == n - 1) {\n            a[0] = -1;\n            a[m + 1] = -1;\n            t = n - 1;\n        }\n        else if (m == n)\n        {\n            a[m + 1] = -1;\n            t = n;\n        }\n        else t = n + 1;\n        k = m % t;\n        if (k == 0 && m != t) k = n + 1;\n        if (a[0] == -1) cout<<\"0\";\n        for (int i = 1; i <= n; i++)\n        {\n            if (a[i] != -1){\n            if (k > 0) cout<<\"110\";\n            else cout<<\"10\";\n            k--;\n            }\n        }\n        if (a[m + 1] != -1) {\n            if (k > 0) cout<<\"11\"<<endl;\n            else cout<<\"1\"<<endl;\n        }\n    }\n    else cout<<\"-1\"<<endl;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "401",
    "index": "D",
    "title": "Roman and Numbers",
    "statement": "Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number $n$, modulo $m$.\n\nNumber $x$ is considered close to number $n$ modulo $m$, if:\n\n- it can be obtained by rearranging the digits of number $n$,\n- it doesn't have any leading zeroes,\n- the remainder after dividing number $x$ by $m$ equals 0.\n\nRoman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him.",
    "tutorial": "This problem we can be attributed to the dynamic programming. We must using mask and dynamic. We have dynamic dp[i][x], when i - mask of reshuffle and x - remainder on dividing by m. if we want to add number a[j], we must using it: dp[i or (1 shl (j-1)),(x*10+a[j]) mod m] := dp[i or (1 shl (j-1)),(x*10+a[j]) mod m] + dp[i,x]; In the end we must answer to divide by the factorial number of occurrences of each digit.",
    "code": "var l,ans,n,m,q,ost,q1:int64;\n  i,j,t,p,x:longint;\n  s:string;\n  ok:boolean;\n    a,qq:array [0..300000,0..101] of int64;\n    aa,kol:array [0..200] of longint;\n   begin\n     read(q1,m);\n     str(q1,s);\n     l:=length(s);\n     for i:=1 to l do\n       begin\n         val(s[i],aa[i],p);\n         inc(kol[aa[i]]);\n       end;\n     for i:=1 to l do\n      if aa[i]>0 then a[1 shl (i-1),aa[i] mod m]:=1;\n     q:=(1 shl (l))-1;\n     for i:=1 to q do\n      begin\n        for j:=1 to l do\n         begin\n           if ((1 shl (j-1)) and i=0) then begin\n                                              ok:=true;\n                                             for x:=1 to j-1 do\n                                              if (aa[j]=aa[x]) and ((1 shl (x-1)) and i=0) then begin ok:=false; break; end;\n                                             for x:=j+1 to l do\n                                              if (aa[j]=aa[x]) and ((1 shl (x-1)) and i>0) then begin ok:=false; break; end;\n                                              if not(ok) then continue;\n\n                                              inc(qq[i,0]);\n                                              qq[i,qq[i,0]]:=j;\n                                           end;\n         end;\n      end;\n\n     for i:=1 to q do\n      begin\n        for j:=0 to m-1 do\n           begin\n             if a[i,j]=0 then continue;\n             for t:=1 to qq[i,0] do\n              begin\n                ost:=(j*10+aa[qq[i][t]]) mod m;\n                inc(a[i+(1 shl (qq[i][t]-1)),ost],a[i][j]);\n                end;\n           end;\n      end;\n       writeln(a[q][0]);\n   end.",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "401",
    "index": "E",
    "title": "Olympic Games",
    "statement": "This problem was deleted from the contest, because it was used previously at another competition.",
    "tutorial": "If first participant of the contest will contain at point (x1;y1) and second participant of the contest will contain at point (x2;y2), then we need to satisfy two conditions: L*L <= (abs(x1-x2)*abs(x1-x2) + abs(y1-y2)*abs(y1-y2)) <= R*R gcd(abs(x1-x2),abs(y1-y2)) == 1 Since the hall can potentially be of size 100,000 x 100,000, even considering each possible size of R or L once will take too much time. And if we iterate value abs(x1-x2) and iterate value abs(y1-y2) then it will take much time too. But if we iterate only value abs(x1-x2) we can find confines of value abs(y1-y2). We can do so: L*L<=(abs(x1-x2)*abs(x1-x2)+abs(y1-y2)*abs(y1-y2))<=R*R L*L - abs(x1-x2)*abs(x1-x2) <= abs(y1-y2)*abs(y1-y2) <= R*R - abs(x1-x2)*abs(x1-x2) Number of options to place the square in hall n*m will be (n-abs(x1-x2)+1)*(m-abs(y1-y2)+1). The first quantity is easy to obtain, while the second requires a little more work. To calculate the second quantity, we note that, although w could have a large variety of prime divisors, it does not have very many of them. This important insight allows us to quickly find the sum: we find the prime factors of w, then we use the inclusion-exclusion principle to calculate the sum of all numbers between L and R that are divisible by at least one of the numbers.",
    "code": "#include <bits/stdc++.h>\n\n#define nmax 100005\n\ntypedef long long ll;\n\n\nll m, n, l, r, p, num[nmax], d[nmax][6], ans, ii;\n\nll tt(ll ql, ll qh, ll mm) {\n\tqh = qh / mm; ql = (ql + mm - 1) / mm;\n\treturn ((qh - ql + 1) * (n + 1) - mm * ((qh * (qh + 1) - (ql - 1) * ql) / 2)) % p;\n}\n\nint main() {\n\n\tscanf(\"%lld%lld\", &n, &m);\n\tscanf(\"%lld%lld%lld\", &l, &r, &p);\n\n\tfor(int i = 2; i <= m; i++)\n\t\tif(num[i] == 0)\n\t\t\tfor(int j = i; j <= m; j += i)\n\t\t\t\td[j][num[j]++] = i;\n\n    ll lo = l;\n\tll hi = r;\n    ll minn = (m < r ? m : r);\n\tfor(ll w = 1; w <= minn; w++) {\n\t\twhile(lo > 1 && l*l - w*w <= (lo-1)*(lo-1))\n\t\t\tlo--;\n\t\twhile(r*r - w*w < hi*hi)\n\t\t\thi--;\n\t\tif(lo <= hi && lo <= n) {\n\t\t\tll a = 0;\n\t\t\tint t = (1 << num[w]);\n\t\t\tfor(int i = 0; i < t; i++) {\n\t\t\t\tii = i;\n\t\t\t\tll p1 = 1;\n\t\t\t\tll p2 = 1;\n\t\t\t\tfor(int j = 0; j < num[w]; j++) {\n\t\t\t\t\tif(ii & 1) {\n\t\t\t\t\t\tp1 *= d[w][j];\n\t\t\t\t\t\tp2 *= -1;\n\t\t\t\t\t}\n\t\t\t\t\tii >>= 1;\n\t\t\t\t}\n\t\t\t\ta += p2 * tt(lo, hi < n ? hi : n, p1);\n\t\t\t}\n\t\t\tans = (ans + a*(m-w+1)) % p;\n\t\t\tif(ans < 0) ans += p;\n\t\t}\n\t}\n\n\tif(l <= 1 && r >= 1) ans = (2 * ans + m * (n + 1) + n * (m + 1)) % p;\n\telse ans = (2 * ans) % p;\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "402",
    "index": "A",
    "title": "Nuts",
    "statement": "You have $a$ nuts and lots of boxes. The boxes have a wonderful feature: if you put $x$ $(x ≥ 0)$ divisors (the spacial bars that can divide a box) to it, you get a box, divided into $x + 1$ sections.\n\nYou are minimalist. Therefore, on the one hand, you are against dividing some box into more than $k$ sections. On the other hand, you are against putting more than $v$ nuts into some section of the box. What is the minimum number of boxes you have to use if you want to put all the nuts in boxes, and you have $b$ divisors?\n\nPlease note that you need to minimize the number of used boxes, not sections. You do not have to minimize the number of used divisors.",
    "tutorial": "Let's fix some value of boxes $ans$. After that we can get exactly $cnt = ans + min((k - 1) * ans, B)$ of sections. So, if $cnt * v  \\ge  a$, then $ans$ be an answer. After that you can use brute force to find smallest possible value of $ans$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "402",
    "index": "B",
    "title": "Trees in a Row",
    "statement": "The Queen of England has $n$ trees growing in a row in her garden. At that, the $i$-th $(1 ≤ i ≤ n)$ tree from the left has height $a_{i}$ meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all $i$ $(1 ≤ i < n)$, $a_{i + 1} - a_{i} = k$, where $k$ is the number the Queen chose.\n\nUnfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?",
    "tutorial": "Let's fix height of the first tree: let's call it $a$. Of course, $a$ is an integer from segment $[1, 1000]$. After that, for the fixed height $a$ of the first tree we can calculate heights of the others trees: $a, a + k, a + 2k$, and so on. After that you should find minimal number of operations $ans$ to achive such heights. After that we can use brute force to find smallest possible $ans$ for each $a$ from $1$ to $1000$. For best height of the first tree you should print all operations.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "402",
    "index": "C",
    "title": "Searching for Graph",
    "statement": "Let's call an undirected graph of $n$ vertices $p$-interesting, if the following conditions fulfill:\n\n- the graph contains exactly $2n + p$ edges;\n- the graph doesn't contain self-loops and multiple edges;\n- for any integer $k$ ($1 ≤ k ≤ n$), any subgraph consisting of $k$ vertices contains at most $2k + p$ edges.\n\nA subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.\n\nYour task is to find a $p$-interesting graph consisting of $n$ vertices.",
    "tutorial": "I will describe two solutions. First. Consider all pairs $(i, j)$ ($1  \\le  i < j  \\le  n$). After you should ouput the first $2n + p$ pairs in lexicographical order. It's clear to understand, that it is enough to prove, that $0$-interesting graph is correct or $- 3$ -interesting graph is correct. We will prove for $- 3$ -interesting graph, that it is correct. This graph consists of triangles, which have an common edge $1$ - $2$. Let's fix some subset of vertexes, which does not contains vertexes $1$ and $2$. In such sets there are no edges. Let's fix some subset, which contains exactly one vertex ($1$ or $2$). In such subsets there are exactly $k - 1$ edges, where $k$ is the size of such subset. In other subset there are exactly 2 * (k - 2) + 1 edges, where $k$ is the size of such subset. Second. Let's use some brute force, to build graphs with $0$-interesting graphs with sizes $5, 6, 7, 8, 9$ vertexes. Now, to build $p$-interesting graph with $n$ vertexes, We will build $0$-interesting graph, and after that we will add to it $p$ another edges, which is not in the graph. We will build $0$-interesting graphs using the following approach: Let's took $k$ disjointed components, from graphs with number of vertexes from $5$ to $9$, in such way that there are exactly $n$ vertexes in graph.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "402",
    "index": "D",
    "title": "Upgrading Array",
    "statement": "You have an array of positive integers $a[1], a[2], ..., a[n]$ and a set of bad prime numbers $b_{1}, b_{2}, ..., b_{m}$. The prime numbers that do not occur in the set $b$ are considered good. The beauty of array $a$ is the sum $\\sum_{i=1}^{n}f(a[i])$, where function $f(s)$ is determined as follows:\n\n- $f(1) = 0$;\n- Let's assume that $p$ is the minimum prime divisor of $s$. If $p$ is a good prime, then $f(s)=f(\\frac{s}{p})+1$, otherwise $f(s)=f(\\frac{s}{p})-1$.\n\nYou are allowed to perform an arbitrary (probably zero) number of operations to improve array $a$. The operation of improvement is the following sequence of actions:\n\n- Choose some number $r$ ($1 ≤ r ≤ n$) and calculate the value $g$ = GCD($a[1], a[2], ..., a[r]$).\n- Apply the assignments: $a[1]={\\frac{a|1}{g}}$, $a[2]={\\frac{a|2|}{g}}$, $...$, $a[r]={\\frac{a|r|}{g}}$.\n\nWhat is the maximum beauty of the array you can get?",
    "tutorial": "I will describe two solutions. First. Dynamic programming approach. Let's calculate an DP $d[i][j]$ - which is the best possible answer we can achieve, if current prefix has length $i$ and we used operation of Upgrading last time in position $j$. It is clear to understand, that we should iterate $i$ from $n$ to $1$, and $j$ from $n$ to $i$. There are only two transitions: First, $d[i - 1][j] = max(d[i - 1][j], d[i][j])$ - we will not use operation of upgrading of array in the current position. Second, $d[i - 1][i - 1] = max(d[i - 1][i - 1], d[i][j] + f(tgcd[j]) * i - f(tgcd[i - 1]) * i$ - we are using an operation of upgrading. $f(a)$ - is a beauty of the number. $tgcd[i]$ - $gcd$ of all numbers on the prefix of length $i$. You can use function, which works in $O({\\sqrt{(a)}})$ to calculate the beauty. Also you can make your solution more faster, it you will precalculate some small primes. Also you can use $map < int, int >$ to store calculated values. DP base $d[n][n] = curBeauty$ - is a current beauty of the array. Second. Greedy. Let's find position $r$, which can upgrade our answer. If there some values of $r$ - we will take most right position. We will add this position to the answer and upgrade our answer. Why it's correct? Let's fix an optimal solution (sequence of position, where we used an upgrading operation) $r_{1} > r_{2} > ... > r_{k}$. Also we have an solution which was built by using greedy $l_{1} > l_{2} > ... > l_{m}$. It's clear, that $r_{1}  \\le  l_{1}$, because all position with $> l_{1}$ cannot upgrade anything (otherwise greedy will choose it as first position). In other hand, $r_{1}  \\ge  l_{1}$, because otherwise we can upgrade in position $l_{1}$ and make answer better. So, $r_{1} = l_{1}$, and after that we can use our propositions for big indexes $i$.",
    "tags": [
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "402",
    "index": "E",
    "title": "Strictly Positive Matrix",
    "statement": "You have matrix $a$ of size $n × n$. Let's number the rows of the matrix from $1$ to $n$ from top to bottom, let's number the columns from $1$ to $n$ from left to right. Let's use $a_{ij}$ to represent the element on the intersection of the $i$-th row and the $j$-th column.\n\nMatrix $a$ meets the following two conditions:\n\n- for any numbers $i, j$ ($1 ≤ i, j ≤ n$) the following inequality holds: $a_{ij} ≥ 0$;\n- $\\textstyle\\sum_{i=1}^{n}a_{i i}>0$.\n\nMatrix $b$ is strictly positive, if for any numbers $i, j$ ($1 ≤ i, j ≤ n$) the inequality $b_{ij} > 0$ holds. You task is to determine if there is such integer $k ≥ 1$, that matrix $a^{k}$ is strictly positive.",
    "tutorial": "Let's look at the matrix $a$ as a connectivity matrix of some graph with n vertices. Moreover, if $a_{ij} > 0$, then we have directed edge in the graph between nodes $(i, j)$. Otherwise, if $a_{ij} = 0$ that graph does not contains directed edge between pair of nodes $(i, j)$. Let $b = a^{k}$. What does $b_{ij}$ means? $b_{ij}$ is the number of paths of length exactly $k$ in our graph from vertex $i$ to vertex $j$. Let $pos$ is an integer, such that $a[pos][pos] > 0$. That is, we have a loop in the graph. So, if from the vertex $pos$ achievable all other vertexes and vice versa, from all other vertices reachable vertex $pos$, then the answer is $YES$, otherwise the answer is $NO$. If reachability is missing, it is clear that for any $k$ $a^{k}_{ipos} = 0$. If reachability there, we will be able to reach self-loop, use self-loop \"to twist\", and after that we will go to some another vertex.",
    "tags": [
      "graphs",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "403",
    "index": "D",
    "title": "Beautiful Pairs of Numbers",
    "statement": "The sequence of integer pairs $(a_{1}, b_{1}), (a_{2}, b_{2}), ..., (a_{k}, b_{k})$ is beautiful, if the following statements are fulfilled:\n\n- $1 ≤ a_{1} ≤ b_{1} < a_{2} ≤ b_{2} < ... < a_{k} ≤ b_{k} ≤ n$, where $n$ is a given positive integer;\n- all numbers $b_{1} - a_{1}$, $b_{2} - a_{2}$, $...$, $b_{k} - a_{k}$ are distinct.\n\nFor the given number $n$ find the number of beautiful sequences of length $k$. As the answer can be rather large, print the remainder after dividing it by $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "First, we can note, that length of sequence is not greater then $50$. Ok, but why? Because all numbers $b_{i} - a_{i}$ are different, so $0 + 1 + ... + 50 > 1000$. Let's imagine, that sequence from input is a sequence of non-intersecting segments. So, $c_{i} = b_{i} - a_{i} + 1$ is length of segment $i$. Also, $\\textstyle\\sum_{i}c_{i}\\leq n$. After that let's calculate the following DP: $d[i][j][k]$ - - number of sequences for which following holds: $c_{1} < c_{2} < ... < c_{i}$, $c_{i}  \\ge  1$ , $c_{1} + c_{2} + ... + c_{i} = j$ and maximal number is less then $k$ (upper bound of sequence). This DP will helps us to calculate number of ways to set length to each segment in sequence. It's simple to calculate such DP: base $d[0][0][1] = 1$, $d[i][j][k + 1] = d[i][j][k + 1] + d[i][j][k]$ - we increase upper bound of sequence; $d[i + 1][j + k][k + 1] = d[i + 1][j + k][k + 1] + d[i][j][k]$ - we are adding upper bound to the sequence. We can calculate such DP, by using only $O(N^{2})$ of memory, where $N = 1000$. After that we should multiply $d[i][j][k]$ on $i!$, because we need number of sequences $c_{i}$, where order does not matter. After that we can calculate answer for $n, k$. Let's $s u m[l e n]=\\sum_{x}d[k][l e n][x]$, where $x$ - some upper bound of sequences. After that we should calculate next number: how many ways to set to distances between segments? It's clear, that we can increase distance between some segments, but we have only $n - len$ such operations. It's well known, that answer number of ways equals to $C(n - len + k, k)$. So, for each $n$ we should sum by $len$ following values: $sum[len] * C(n - len + k, k)$. Note, that we need array $C[n][k]$ (binomials) where $n  \\le  2000, k  \\le  2000$.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "403",
    "index": "E",
    "title": "Two Rooted Trees",
    "statement": "You have two rooted undirected trees, each contains $n$ vertices. Let's number the vertices of each tree with integers from $1$ to $n$. The root of each tree is at vertex $1$. The edges of the first tree are painted blue, the edges of the second one are painted red. For simplicity, let's say that the first tree is blue and the second tree is red.\n\nEdge ${x, y}$ is called bad for edge ${p, q}$ if two conditions are fulfilled:\n\n- The color of edge ${x, y}$ is different from the color of edge ${p, q}$.\n- Let's consider the tree of the same color that edge ${p, q}$ is. Exactly one of vertices $x$, $y$ lies both in the subtree of vertex $p$ and in the subtree of vertex $q$.\n\nIn this problem, your task is to simulate the process described below. The process consists of several stages:\n\n- On each stage edges of exactly one color are deleted.\n- On the first stage, exactly one blue edge is deleted.\n- Let's assume that at the stage $i$ we've deleted edges ${u_{1}, v_{1}}$, ${u_{2}, v_{2}}$, $...$, ${u_{k}, v_{k}}$. At the stage $i + 1$ we will delete all undeleted bad edges for edge ${u_{1}, v_{1}}$, then we will delete all undeleted bad edges for edge ${u_{2}, v_{2}}$ and so on until we reach edge ${u_{k}, v_{k}}$.\n\nFor each stage of deleting edges determine what edges will be removed on the stage. Note that the definition of a bad edge always considers the initial tree before it had any edges removed.",
    "tutorial": "First, for each vertex of the first and second tree we calculate two values $in[s]$, $out[s]$ - the entry time and exit time in dfs order from vertex with number $1$. Also with each edge from both trees we will assosiate a pair $(p, q)$, where $p = min(in[u], in[v])$, $q = max(in[u], in[v])$ (values $in, out$ for each vertex we take from tree with another color). Now for each tree we will build two segment trees (yes, totally 4 segment trees). In first segment will store all pairs in following way: we will store a pair in node of segment tree if and only if (node of segment tree is a segment $(l, r)$) left element of pair lies in segment $(l, r)$. In second segment tree we will store a pair if and only if right element of the pair lies in segment $(l, r)$ All pairs in segment trees we will store in some order (in first segment tree - increasing order, in the second tree - decreasing order). Such trees use $O(n\\log(n))$ of memory, also you can build it in $O(n\\log(n))$. Good. How to answer on query $(l, r)$ - erase all edges from tree for which exactly one vertex have value $in[s]$ in segment $(l, r)$? We will go down in our segment tree. Let's imagine, that now we in some node of segment tree. Because we store all pairs in the first segment tree in increasing order of the right element, so answer to the query is a some suffix of the array of pairs. After we can add they to the answer (if it not erased yet). After that we should modify our segment tree: for each node, where we work with suffixes, we should erase all pairs from such suffix. So, this solution in $O(n\\log(n))$.",
    "code": "#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n \n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <list>\n#include <vector>\n#include <string>\n#include <deque>\n#include <bitset>\n#include <algorithm>\n#include <utility>\n                  \n#include <functional>\n#include <limits>\n#include <numeric>\n#include <complex>\n \n#include <cassert>\n#include <cmath>\n#include <memory.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n//#include <ctime>   \n \n \nusing namespace std;\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int,int> pt;\ntypedef pair<ld, ld> ptd;\ntypedef unsigned long long uli;\n \n#define pb push_back\n#define mp make_pair\n#define mset(a, val) memset(a, val, sizeof (a))\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define ft first\n#define sc second\n#define sz(a) int((a).size())\n#define x first\n#define y second\n \ntemplate<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }\ntemplate<typename X> inline X sqr(const X& a) { return (a * a); }\ntemplate<typename T> inline string toStr(T x) { stringstream st; st << x; string s; st >> s; return s; }\ntemplate<typename T> inline int hasBit(T mask, int b) { return (b >= 0 && (mask & (T(1) << b)) != 0) ? 1 : 0; }\ntemplate<typename X, typename T>inline ostream& operator<< (ostream& out, const pair<T, X>& p) { return out << '(' << p.ft << \", \" << p.sc << ')'; }\n \ninline int nextInt() { int x; if (scanf(\"%d\", &x) != 1) throw; return x; }\ninline li nextInt64() { li x; if (scanf(\"%I64d\", &x) != 1) throw; return x; }\ninline double nextDouble() { double x; if (scanf(\"%lf\", &x) != 1) throw; return x; }\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define fore(i, a, b) for(int i = int(a); i <= int(b); i++)\n#define ford(i, n) for(int i = int(n - 1); i >= 0; i--)\n#define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)\n \n \nconst int INF = int(1e9);\nconst li INF64 = li(INF) * li(INF);\nconst ld EPS = 1e-9;\nconst ld PI = ld(3.1415926535897932384626433832795);\n \nconst int N = 2 * 1000 * 100 + 10;\n \nint n;\n \npt edges[2][N];            \nint in[2][N], out[2][N], cur[N], szcur, curtime, szncur, ncur[N];\nint used[2][N];\n \nvector < int > g[2][N];\n \nvector < pt > tv1[2][2 * N], tv2[2][2 * N];\nvector < pt > t[4][8 * N];\n \ninline bool read() \n{\n    n = nextInt();\n   \tforn(it, 2)\n   \t{\n   \t \tforn(i, n - 1)\n   \t \t{\n   \t \t \tint a = nextInt() - 1;\n   \t \t \tint b = i + 1; \n   \t \t \tedges[it][i] = mp(a, b);\n        \tg[it][a].pb(b);\n     \t \tg[it][b].pb(a);\n        }\n   \t}\n \n\tint i = nextInt() - 1;\n \n  \tcur[szcur ++] = i;\n  \t\n  \treturn true;\n}\n \nvoid go(int id, int s, int prev = -1)\n{\n \tin[id][s] = curtime++;\n \n \tforn(i, sz(g[id][s])) \n \t{\n \t\tint to = g[id][s][i];\n \n \t \tif (to == prev) continue;\n \n \t \tgo(id, to, s); \t\n \t}                   \t\n \tout[id][s] = curtime ++;\n}\n \nvoid buildByFt(int v, int tl, int tr, int id)\n{\n \tif (tl == tr) \n \t{\n \t\tt[id][v] = tv1[id][tl];\n \t\tsort(all(t[id][v]));\n \t\treturn;\n \t}\n \n\tint mid = (tl + tr) >> 1;\n\tbuildByFt((v << 1), tl, mid, id);\n\tbuildByFt((v << 1) + 1, mid + 1, tr, id);\n\t\n\tint i = 0;\n\tint j = 0;\n\t\n\tint szt = 0;\n \n\tint szt1 = sz(t[id][(v << 1)]);\n\tint szt2 = sz(t[id][(v << 1) + 1]);\n \n\tint allszt = sz(t[id][(v << 1)]) + sz(t[id][(v << 1) + 1]);\n\t\n\tt[id][v].resize(allszt);\n \n\twhile (szt < allszt)\n\t{\n\t \tif (i < szt1 && j < szt2)\n\t \t{\n\t \t \tif (t[id][(v << 1)][i] <= t[id][(v << 1) + 1][j])\n\t \t \t{\n\t \t \t\tt[id][v][szt++] = t[id][(v << 1)][i];\n\t \t \t\ti++;\n\t \t \t}\n\t \t \telse\n\t \t \t{\n\t \t \t\tt[id][v][szt++] = t[id][(v << 1) + 1][j];\n\t \t \t\tj++;\n\t \t \t}\n\t \t \tcontinue;\n\t \t}\n\t \tif (i < szt1)\n\t \t{\n\t \t\tt[id][v][szt++] = t[id][(v << 1)][i];\n\t \t \ti++;\n\t \t}\n \n\t \tif (j < szt2)\n\t \t{\n\t \t \tt[id][v][szt++] = t[id][(v << 1) + 1][j];\n\t \t \tj++;\n\t \t}\n\t}\n}\n \nvoid buildBySc(int v, int tl, int tr, int id)\n{\n \tif (tl == tr) \n \t{\n \t    t[id + 2][v] = tv2[id][tl];\n        sort(all(t[id + 2][v]));\n        reverse(all(t[id + 2][v]));\n    \n        return;\n \t}\n \n    int mid = (tl + tr) >> 1;\n\tbuildBySc((v << 1), tl, mid, id);\n\tbuildBySc((v << 1) + 1, mid + 1, tr, id);\n\t\n\tid += 2;\n \n\tint i = 0;\n\tint j = 0;\n\t\n\tint szt = 0;\n \n\tint szt1 = sz(t[id][(v << 1)]);\n\tint szt2 = sz(t[id][(v << 1) + 1]);\n \n\tint allszt = sz(t[id][(v << 1)]) + sz(t[id][(v << 1) + 1]);\n\t\n\tt[id][v].resize(allszt);\n \n\twhile (szt < allszt)\n\t{\n\t \tif (i < szt1 && j < szt2)\n\t \t{\n\t \t \tif (t[id][(v << 1)][i] >= t[id][(v << 1) + 1][j])\n\t \t \t{\n\t \t \t\tt[id][v][szt++] = t[id][(v << 1)][i];\n\t \t \t\ti++;\n\t \t \t}\n\t \t \telse\n\t \t \t{\n\t \t \t\tt[id][v][szt++] = t[id][(v << 1) + 1][j];\n\t \t \t\tj++;\n\t \t \t}\n\t \t \tcontinue;\n\t \t}\n\t \tif (i < szt1)\n\t \t{\n\t \t\tt[id][v][szt++] = t[id][(v << 1)][i];\n\t \t \ti++;\n\t \t}\n \n\t \tif (j < szt2)\n\t \t{\n\t \t \tt[id][v][szt++] = t[id][(v << 1) + 1][j];\n\t \t \tj++;\n\t \t}\n\t}\n}\n \nvoid get(int v, int tl, int tr, int l, int r, int id, int tvalue)\n{\n \tif (l > r)\n \t\treturn;                                     \n                       \n \n \tif (l == tl && r == tr)\n \t{\n \t\t\n \t\tif (id < 2)\n \t\t{\n \t\t\twhile (!t[id][v].empty())\n \t\t\t{\n \t\t\t \tpt s = t[id][v].back();\n \n \t\t\t \tif (s.ft > tvalue)\n \t\t\t \t{                        \n \t\t\t \t\t\n \t\t\t \t\tif (!used[id & 1][s.sc]) \n \t\t\t \t    {\n \t\t\t \t    \tused[id & 1][s.sc] = 1;\n \t\t\t \t    \tncur[szncur++] = s.sc;\n \t\t\t \t    }\n \n \t\t\t \t    t[id][v].pop_back();\n \t\t\t \t} else\n \t\t\t \t\tbreak;\t\n \t\t\t}\n \t\t} \n \t\telse\n \t\t{\n \t\t\twhile (!t[id][v].empty())\n \t\t\t{\n \t\t\t \tpt s = t[id][v].back();\n \t\t\t \tif (s.ft < tvalue) \n               \t{                \n \t\t\t \t    if (!used[id & 1][s.sc])\n \t\t\t \t    {\n \t\t\t \t    \tused[id & 1][s.sc] = 1;\n \t\t\t \t    \tncur[szncur++] = s.sc;\n \t\t\t \t    }\n \t\t\t \t    t[id][v].pop_back();\n \t\t\t \t} else\n \t\t\t \t\tbreak;\t\n \t\t\t}\n \t\t}\n \n \t   \treturn;\n\t}\n \n\tint mid = (tl + tr) >> 1;\n \n\tget((v << 1), tl, mid, l, min(r, mid), id, tvalue);\n\tget((v << 1) + 1, mid + 1, tr, max(l, mid + 1), r, id, tvalue);\n\t\t\n} \ninline void solve() \n{       \n    curtime = 0;\n    go(0, 0);\n \n    curtime = 0;\n    go(1, 0);    \n \n    forn(it, 2)\n\t \tforn(i, n - 1)\n\t \t{\n\t \t\tint u = edges[it][i].ft;\n\t \t\tint v = edges[it][i].sc;\n       \n         \tint dv1 = in[it ^ 1][u];\n        \tint dv2 = in[it ^ 1][v];\n \n        \tif (dv1 > dv2)\n        \t\tswap(dv1, dv2);\n \n        \ttv1[it][dv1].pb(mp(dv2, i));\n        \ttv2[it][dv2].pb(mp(dv1, i));\n        }\n\t\n\tforn(it, 2)\n\t\tbuildByFt(1, 0, 2 * n - 1, it);\n \n\tforn(it, 2)\n\t\tbuildBySc(1, 0, 2 * n - 1, it);\n \n    int idx = 0;\n \n    forn(i, szcur)\n    \tused[0][cur[i]] = 1;\n \n\twhile(true)\n\t{                \n\t\tif (szcur == 0) break;\n\t\tif (idx & 1)\n\t\t\tputs(\"Red\");\n\t\telse\n\t\t\tputs(\"Blue\");\n \n\t\tsort(cur, cur + szcur);\n \n\t\tforn(i, szcur) \n\t\t{\n\t\t\tif (i) printf(\" \");\n\t\t\tprintf(\"%d\", cur[i] + 1);\n\t\t}\t\t \t\n\t\tputs(\"\");\n\t\tforn(i, szcur) \n\t\t{\n\t\t\tint u = edges[idx][cur[i]].ft;\n\t\t\tint v = edges[idx][cur[i]].sc;\n \n\t\t}\n \n\t\tforn(i, szcur) \n\t\t{\n\t\t\tint u = edges[idx][cur[i]].ft;\n\t\t\tint v = edges[idx][cur[i]].sc;\n        \t\n        \tint l, r;\n \n        \tif (out[idx][u] > out[idx][v])\n        \t\tl = in[idx][v], r = out[idx][v];\n        \telse\n        \t\tl = in[idx][u], r = out[idx][u];\n        \n            if (!(idx & 1))\n        \t\tget(1, 0, 2 * n - 1, l, r, 1, r),\n        \t\tget(1, 0, 2 * n - 1, l, r, 3, l);\n       \t\telse\n       \t\t\tget(1, 0, 2 * n - 1, l, r, 0, r),\n        \t\tget(1, 0, 2 * n - 1, l, r, 2, l);\n       \t\t\t\n        }\n  \n        idx ^= 1;\n \n        forn(i, szncur)\n        \tcur[i] = ncur[i];\n \n        szcur = szncur;\n        szncur = 0;\n   \t}\n}\n \nint main() \n{\n#ifdef gridnevvvit\n\tfreopen(\"input.txt\", \"rt\", stdin);\n\tfreopen(\"output.txt\", \"wt\", stdout);\n#endif                    \n \n\tcout << setprecision(10) << fixed;\n\tcerr << setprecision(5) << fixed;\n \n\tassert(read());\n\tsolve();\n}",
    "tags": [
      "data structures",
      "implementation",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "404",
    "index": "A",
    "title": "Valera and X",
    "statement": "Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals $n$ squares ($n$ is an odd number) and each unit square contains some small letter of the English alphabet.\n\nValera needs to know if the letters written on the square piece of paper form letter \"X\". Valera's teacher thinks that the letters on the piece of paper form an \"X\", if:\n\n- on both diagonals of the square paper all letters are the same;\n- all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.\n\nHelp Valera, write the program that completes the described task for him.",
    "tutorial": "In this problem it was needed to check the constraints described in statement. You can use two sets here. You should insert diagonal elements of matrix into the first set, and the other elements into the second. Element $a_{i, j}$ belongs to the main diagonal if $i = j$ and belongs to the secondary diagonal if $i = n - j + 1$. After you split all elements into sets you should check if the sets sizes are equal to one and the elements from this sets differ from each other.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "404",
    "index": "B",
    "title": "Marathon",
    "statement": "Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates $(0, 0)$ and the length of the side equals $a$ meters. The sides of the square are parallel to coordinate axes.\n\nAs the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each $d$ meters of the path. We know that Valera starts at the point with coordinates $(0, 0)$ and runs counter-clockwise. That is, when Valera covers $a$ meters, he reaches the point with coordinates $(a, 0)$. We also know that the length of the marathon race equals $nd + 0.5$ meters.\n\nHelp Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers $d, 2·d, ..., n·d$ meters.",
    "tutorial": "Let's notice that after Valera run $4 \\cdot a$ meters he will be in the same point from which he started. Valera will have run $i \\cdot d$ meters before he gets $i$-th bottle of drink. Let's calculate the value $c=\\lfloor{\\frac{i\\,d}{4\\,a}}\\rfloor$ - how many laps he will run. Then he have already run $L = i \\cdot d - c \\cdot 4 \\cdot a$ meters on his last lap. It is easy to get Valera's position from this $L$. For example, if $2 \\cdot a  \\le  L  \\le  3 \\cdot a$ then Valera will be in the point with coordinates $(3 \\cdot a - L, a)$. You can consider the other three cases in the same manner.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "404",
    "index": "C",
    "title": "Restore Graph",
    "statement": "Valera had an undirected connected graph without self-loops and multiple edges consisting of $n$ vertices. The graph had an interesting property: there were at most $k$ edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to $n$.\n\nOne day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array $d$. Thus, element $d[i]$ of the array shows the shortest distance from the vertex Valera chose to vertex number $i$.\n\nThen something irreparable terrible happened. Valera lost the initial graph. However, he still has the array $d$. Help him restore the lost graph.",
    "tutorial": "First of all let us notice that it must be only one $0$ in $d$. Also $d[start] = 0$ means that $start$ is the vertex from which Valera calculated the distance to the other vertices. Let's notice that every vertex $u$ with $d[u] = i$ must be adjacent only to the vertices $v$ such that $d[v]  \\ge  i - 1$. Besides there is always must be such neighboor $v_{0}$ of $u$, that $d[v_{0}] = i - 1$. Let's build sought graph by adding one vertex to the existing graph. We will add vertex in order of increasing their distance to $start$. Initially, we have one vertex with number $start$ in our graph. When we add vertex $u$ with $d[u] = i$ let's consider such vertices $v$ that $d[v] = i - 1$. Let's choose the vertex with minimal degree among them. If this value is equal to $k$, then there is no solution. In other case let's add $u$ to our graph and add the edge $(u, v)$ to the answer. If there are no vertices with distance $i - 1$ to $start$ then the answer is also $- 1$. If everything fine we will get the answer which is tree, so the number of edges in it equals $n - 1  \\le  10^{6}$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "404",
    "index": "D",
    "title": "Minesweeper 1D",
    "statement": "Game \"Minesweeper 1D\" is played on a line of squares, the line's height is 1 square, the line's width is $n$ squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.\n\nFor example, the correct field to play looks like that: 001*2***101*. The cells that are marked with \"*\" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.\n\nValera wants to make a correct field to play \"Minesweeper 1D\". He has already painted a squared field with width of $n$ cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.",
    "tutorial": "This problem can be solved by using dynamic programming. Let's calculate $d[i][type]$ - the number of correct ways to fill the prefix of length $i$ so that the last filled cell has one of the $5$ types. These types are the following: the cell contains \"0\" the cell contains \"1\" and the cell to the left of it contains bomb the cell contains \"1\" and the cell to the left of it doesn't contain bomb the cell contains \"2\" the cell contains bomb When we try to fill next cell we check two conditions. Firstly value of the filled cell in given string must be equal to either what we want to write or \"?\". Secondly new prefix must remain filled correct. For example, if we are in state $(i, 1)$ (it means that the cell $i$ contains \"0\") then we can fill next cell by \"0\" and go to the state $(i + 1, 1)$ or fill next cell by \"1\" and go to the state $(i + 1, 3)$. We cannot write \"2\" because both neighbours of the cell with \"2\" must contain bomb. Obvious, we cannot place bomb after \"0\". Note that, when we place \"1\" after \"0\" we go to the state $(i + 1, 3)$, but when we place \"1\" after bomb we go to the state $(i + 1, 2)$. You can consider other ways of going from one state to another in the same manner.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "404",
    "index": "E",
    "title": "Maze 1D",
    "statement": "Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number $0$ has a robot.\n\nThe robot has instructions — the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number $0$. If the robot should go into the cell with an obstacle according the instructions, it will skip this move.\n\nAlso Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once — at its last move. Moreover, the latter move cannot be skipped.\n\nLet's assume that $k$ is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose $k$ obstacles and the finishing cell so that the robot is able to complete the instructions successfully.",
    "tutorial": "Let's consider the case when the last move of the robot is equal to \"R\". If the last move is equal to \"L\" then we can replace all \"L\" by \"R\" and vise versa and the answer doesn't change. Let's show that Valera doesn't need more than one obstacle. Suppose Valera placed obstacles somewhere. We will say that the number of obstacle is the number of cell containing it. Let's consider the rightmost obstacle $obs1$ among the obstacles with negative numbers and the leftmost obstacle $obs2$ among the obstacles with positive numbers. Obvious robot cannot go to the left of $obs1$ and to the right of $obs2$. So the needed number of obstacles is not greater than two. Let's show that Valera doesn't need to place obstacles to the cells with numbers greater than zero. Suppose he place obstacle to the cell with number $a > 0$. If robot doesn't try to go to this cell then its obstacle is out of place. If robot try to go to this cell then it will visit finish cell more than once. It is because robot needs to go to the right on its last move, but it can't do it from cell $a - 1$ and it has already visited all cells to the left of $a$. So Valera doesn't need more than one obstacle and its obstacle must have number less than zero. Let's now check if Valera can do without obstacles. If so the robot won't skip moves and will stop in some cell. Than Valera can choose this cell as finish and the answer will be one. We have to consider only one case when Valera must place one obstacle. Firstly let's notice that if Valera place obstacle to some cell, the finish cell can be restored uniquely. It means that the number of ways to choose where to place obstacles and finish cell is equal to the number of ways to choose one cell to place one obstacle. Suppose Valera placed obstacle in the cell with number $b < 0$ and robot completed its instructions successfully. Notice, that in that case robot skipped some moves of type \"L\", completed all moves of type \"R\" and went to the right on its last move to the unvisited cell. If we shift Valera's obstacle to the right on one cell then robot is going to skip not less moves of type \"L\" than in the previous case. It means that the finish cell can either go to the right or remains the same. But last time robot visited this cell on its last move, so it is going to visit a new finish cell on its last move either. This means that there is such cell $p < 0$ that if Valera place obstacle to the cells $c  \\ge  p$ then robot will be able to complete its instructions successfully, but if Valera place obstacle to the cells $d < p$ then robot will not. This cell $p$ can be found by using binary search and simple simulation on each iteration. Time complexity is $O(n log n)$.",
    "tags": [
      "binary search",
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "405",
    "index": "A",
    "title": "Gravity Flip",
    "statement": "Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.\n\nThere are $n$ columns of toy cubes in the box arranged in a line. The $i$-th column contains $a_{i}$ cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange.\n\nGiven the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the $n$ columns after the gravity switch!",
    "tutorial": "Observe that in the final configuration the heights of the columns are in non-decreasing order. Also, the number of columns of each height remains the same. This means that the answer to the problem is the sorted sequence of the given column heights. Solution complexity: $O(n)$, since we can sort by counting.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "405",
    "index": "B",
    "title": "Domino Effect",
    "statement": "Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play \\underline{with} the dominoes and make a \"domino show\".\n\nChris arranges $n$ dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.\n\nAfter each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.\n\nGiven the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!",
    "tutorial": "If the first pushed domino from the left was pushed to the left at position $l$, all dominoes at prefix $[1;l]$ fall down, otherwise let $l$ be 0. Similarly, if the first pushed domino from the right was pushed to the right at position $r$, all dominoes at suffix $[r;n]$ also fall down, otherwise let $r$ be $n + 1$. Now, in the segment $(l;r)$ there will remain vertical dominoes and blocks of dominoes supported by the equal forces from both sides. When does a domino at position $p$ in segment $(l, r)$ remains standing vertically? One way is that it is not pushed by any other domino. This could be easily checked by looking at the pushed dominoes closest to $p$ (from both sides). It is pushed by dominoes, only if the closest from the left was pushed to the right, and the closest from the right was pushed to the left. Suppose these dominoes are at positions $x$ and $y$, $x < p < y$. Then, the only way that the domino is still standing is if it is positioned at the center of the block $[x;y]$, which could be checked by ${\\frac{x+y}{2}}=p$. Solution complexity: $O(n) / O(n^{2})$, depends on implementation.",
    "tags": [],
    "rating": 1100
  },
  {
    "contest_id": "405",
    "index": "C",
    "title": "Unusual Product",
    "statement": "Little Chris is a huge fan of linear algebra. This time he has been given a homework about the \\underline{unusual square} of a square matrix.\n\nThe \\underline{dot product} of two integer number vectors $x$ and $y$ of size $n$ is the sum of the products of the corresponding components of the vectors. The \\underline{unusual square} of an $n × n$ square matrix $A$ is defined as the sum of $n$ dot products. The $i$-th of them is the dot product of the $i$-th row vector and the $i$-th column vector in the matrix $A$.\n\nFortunately for Chris, he has to work only in $GF(2)$! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix $A$ is binary: each element of $A$ is either 0 or 1. For example, consider the following matrix $A$:\n\nThe unusual square of $A$ is equal to $(1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0$.\n\nHowever, there is much more to the homework. Chris has to process $q$ queries; each query can be one of the following:\n\n- given a row index $i$, flip all the values in the $i$-th row in $A$;\n- given a column index $i$, flip all the values in the $i$-th column in $A$;\n- find the unusual square of $A$.\n\nTo flip a bit value $w$ means to change it to $1 - w$, i.e., 1 changes to 0 and 0 changes to 1.\n\nGiven the initial matrix $A$, output the answers for each query of the third type! Can you solve Chris's homework?",
    "tutorial": "Written as a formula, the problem asks to find the value of $\\sum_{i=1}^{n}\\sum_{j=1}^{n}A_{i j}A_{j i}{\\mathrm{~(mod~}}2)$ Suppose that $i  \\neq  j$. Then the sum contains summands $A_{ij}A_{ji}$ and $A_{ji}A_{ij}$. Since the sum is taken modulo 2, these summands together give 0 to the sum. It follows that the expression is always equal to the sum of the diagonal bits: $\\sum_{i=1}^{n}A_{i i}^{2}{\\mathrm{~(mod~2)}}=\\sum_{i=1}^{n}A_{i i}{\\mathrm{~(mod~2)}}$ Now, each query of type 1 and 2 flips the value of exactly one bit on the diagonal. Thus we can calculate the unusual product of the original matrix, and flip its value after each query of type 1 and 2. Solution complexity: $O(n + q)$, if we don't take the reading of the input into account... :)",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "405",
    "index": "D",
    "title": "Toy Sum",
    "statement": "Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.\n\nThere are exactly $s$ blocks in Chris's set, each block has a unique number from 1 to $s$. Chris's teacher picks a subset of blocks $X$ and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset $Y$ from the remaining blocks, that the equality holds:\n\n\\[\n\\textstyle\\sum_{x\\in X}(x-1)=\\sum_{y\\in Y}(s-y)\n\\]\n\n\"Are you kidding me?\", asks Chris.For example, consider a case where $s = 8$ and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: $(1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7$.\n\nHowever, now Chris has exactly $s = 10^{6}$ blocks. Given the set $X$ of blocks his teacher chooses, help Chris to find the required set $Y$!",
    "tutorial": "Let's define the symmetric number of $k$ to be $s + 1 - k$. Since in this case $s$ is an even number, $k  \\neq  s - k$. Note that $(k - 1) + (s + 1 - k) = s$, i.e., the sum of a number and its symmetric is always $s$. Let's process the given members $x$ of $X$. There can be two cases: If the symmetric of $x$ does not belong to $X$, we add it to $Y$. Both give equal values to the respective sums: $x - 1 = s - (s + 1 - x)$. The symmetric of $x$ belongs to $X$. Then we pick any $y$ that neither $y$ and symmetric of $y$ belong to $X$, and add them to $Y$. Both pairs give equal values to the respective sums, namely $s$. How to prove that in the second step we can always find such $y$? Let the number of symmetric pairs that were processed in the step 1 be $a$, then there remain $\\textstyle{\\frac{s}{2}}-a$ other pairs. Among them, for $\\scriptstyle{\\frac{n-a}{2}}$ pairs both members belong to $X$, and for other $\\begin{array}{l}{{\\frac{3}{2}}-a-{\\frac{n-a}{2}}}\\end{array}$ pairs none of the members belong to $X$. To be able to pick the same number of pairs for $Y$, as there are in $X$, we should have $\\stackrel{\\vec{s}}{2}-a-\\stackrel{n-a}{2}\\ge\\frac{n-a}{2},$ which is equivalent to $\\textstyle{\\frac{s}{2}}\\geq n$, as given in the statement. Solution complexity: $O(s) / O(n)$.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "405",
    "index": "E",
    "title": "Graph Cutting",
    "statement": "Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.\n\nChris is given a simple undirected connected graph with $n$ vertices (numbered from 1 to $n$) and $m$ edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.\n\nFor example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.\n\nYou are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!",
    "tutorial": "It can be proved that only graphs with an odd number of edges cannot be partitioned into path of length 2. We will construct a recursive function that solves the problem and also serves as a proof for this statement. The function partition(v) will operate on non-blocked edges. It will partition the component of vertex $v$ connected by the non-blocked edges into paths of length 2. If this component has an odd number of edges, the function will partition all the edges of the component, except one edge $(u, v)$; the function then will return vertex $u$, expecting that the parent function call will assign it to some path. The function works as follows: find all vertices that are adjacent to $v$ by the non-blocked edges, call this set adjacent. Then block all the edges from this set vertices to $v$. For each $u$ in adjacent, call partition(u). Suppose partition(u) returned a vertex $w$. That means we can pair it into the path $(v, u, w)$. Otherwise, if partition(u) does not return anything, we add $u$ to unpaired, since the edge $(v, u)$ is not yet in any path. We can pair any two vertices of this set $u$, $w$ into a single path $(u, v, w)$. We pair as much of them as possible in any order. If from this set a single vertex, $u$, is left unpaired, the function will return $u$. Otherwise the function will not return anything. The function could be implemented as a single DFS: Solution complexity: $O(n + m)$.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "406",
    "index": "D",
    "title": "Hill Climbing",
    "statement": "This problem has nothing to do with Little Chris. It is about hill climbers instead (and Chris definitely isn't one).\n\nThere are $n$ hills arranged on a line, each in the form of a vertical line segment with one endpoint on the ground. The hills are numbered with numbers from 1 to $n$ from left to right. The $i$-th hill stands at position $x_{i}$ with its top at height $y_{i}$. For every two hills $a$ and $b$, if the top of hill $a$ can be seen from the top of hill $b$, their tops are connected by a rope. Formally, the tops of two hills are connected if the segment connecting their top points does not intersect or touch any of the other hill segments. Using these ropes, the hill climbers can move from hill to hill.\n\nThere are $m$ teams of climbers, each composed of exactly two members. The first and the second climbers of the $i$-th team are located at the top of the $a_{i}$-th and $b_{i}$-th hills, respectively. They want to meet together at the top of some hill. Now, each of two climbers move according to the following process:\n\n- if a climber is at the top of the hill where the other climber is already located or will come eventually, the former climber stays at this hill;\n- otherwise, the climber picks a hill to the right of his current hill that is reachable by a rope and \\textbf{is the rightmost possible}, climbs this hill and continues the process (the climber can also climb a hill whose top is lower than the top of his current hill).\n\nFor each team of climbers, determine the number of the meeting hill for this pair!",
    "tutorial": "Note that the path of each hill climber is strictly convex in any case. Let's draw the paths from all hills to the rightmost hill. Then these paths form a tree with the \"root\" at the top of the rightmost hill. We can apply the Graham scan from the right to the left to find the edges of this tree. Each pop and insert in the stack corresponds to a single edge in the tree. Now it is easy to see that for each team of climbers, we should calculate the number of the lowest common ancestor for the corresponding two vertices in the tree. The size if the tree is $n$, so each query works in $O(\\log n)$. Solution complexity: $O(n\\log n)$.",
    "tags": [
      "dfs and similar",
      "geometry",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "406",
    "index": "E",
    "title": "Hamming Triples",
    "statement": "Little Chris is having a nightmare. Even in dreams all he thinks about is math.\n\nChris dreams about $m$ binary strings of length $n$, indexed with numbers from 1 to $m$. The most horrifying part is that the bits of each string are ordered in either ascending or descending order. For example, Chris could be dreaming about the following 4 strings of length 5:\n\nThe \\underline{Hamming distance} $H(a, b)$ between two strings $a$ and $b$ of length $n$ is the number of positions at which the corresponding symbols are different.\n\nСhris thinks that each three strings with different indices constitute a single triple. Chris's delusion is that he will wake up only if he counts the number of such string triples $a$, $b$, $c$ that the sum $H(a, b) + H(b, c) + H(c, a)$ is maximal among all the string triples constructed from the dreamed strings.\n\nHelp Chris wake up from this nightmare!",
    "tutorial": "Let's look at the Hamming graph of all possible distinct $2n$ strings, where each two strings are connected by an edge with length equal to the Hamming distance between these strings. We can observe that this graph has a nice property: if we arrange the vertices cyclically as a regular $2n$-gon with a side length of 1, then the Hamming distance between two strings is the length of the shortest route between these vertices on the perimeter of the polygon. For example, the figure shows the graph for $n = 3$. The gray edges have length 1, the orange edges have length 2 and the blue edges have length 3. That is the corresponding Hamming distance. Now, we can convert each string coded by a pair $(s, f)$ to an integer $(f + 1) \\cdot n - s$. The new numbers will be 0, 1, ..., $2n - 1$ and correspond to the same cyclical order on the perimeter of the polygon. The given strings are mapped to some subset of the vertices. Now we have to find the number of triangles (possibly degenerate) with maximal perimeter in this subgraph. It will be useful to keep the new converted numbers sorted. First, we can figure out what this perimeter could be. If there exists a diameter in the full graph, so that all of the points are on one side of the diameter, the perimeter is $2d$, where $d$ is the length of the longest edge: Then any triangle with two vertices at the longest edge points and the third one being any point has the maximal perimeter. Since the numbers are sorted, the longest edge in this case will be produced by two cyclically adjacent elements, which is not hard to find. If for any diameter this does not hold, then the maximal perimeter is $2n$. This can be proved by taking two different points $a$, $b$ and drawing two diameters with them as endpoints; since it is not the previous case, there shoud be a third point $c$ in area where the perimeter of triangle $a$, $b$, $c$ is $2n$. The tricky part is to count the triples in this case. We do this by working with the diameter $(0, n)$. There can be several cases: A maximum triangle has vertices 0 and $n$. This a simple case: with any other vertex as the third the triangle has perimeter $2n$. A maximum triangle has vertex 0, but not $n$. Then the second vertex should be in interval $[0, n)$, and the third in interval $(n + 1, 2n - 1]$, and the clockwise distance between the second and the third should not exceed $n$ (since then the perimeter of the triangle would be less than $2n$). We count the number of such triples iterating two pointers (one in each of these intervals). For each pointer in the first interval, all points from $n + 1$ till the second pointer will make a maximal perimeter triangle. We similarly solve the case where the maximal triangle has vertex $n$, but not 0. The maximal triangle does not have 0 or $n$ as its vertices. Then one vertex of the triangle should be on one side of diameter $(0, n)$, and two should be on the opposite side. To count them, we iterate a vertex pointer on the first side, say, $(0, n)$; let the diametrally opposite vertex on the opposite side be $x$. Then the second vertex can be any in $[n + 1, s]$, and the third can be any of the $[s, 2n - 1]$. It is easy to calculate these numbers using partial sums on the circle. Note that $s$ can be both the second and the third vertex (since strings can repeat). So we iterate this pointer over all one side vertices and update the answer. Similarly we solve the case where a single vertex is on the other side, and two on this side. One only needs to be careful with the formulas in each case. Solution complexity: $O(m\\log m)$, because of the sorting.",
    "tags": [
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "407",
    "index": "A",
    "title": "Triangle",
    "statement": "There is a right triangle with legs of length $a$ and $b$. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.",
    "tutorial": "In this problem you have to locate the right triangle with cathetuses $a$, $b$ on a plane with its vertices in integer points. If the required layout exists, then cathetus $a$ always can be represented as a vector with integer coordinates $A{x;y}$, and $a^{2} = x^{2} + y^{2}$. Iterate over all possible $x$ ($1  \\le  x  \\le  a - 1$), check, that $y = sqrt(a^{2} - x^{2})$ is integer. Vector, ortogonal to vector ${x;y}$, is ${ - y;x}$. Take vector $B{ - y / g;x / g}$, where $g = gcd(x, y)$. The triangle can be located on the plane if and only if $b$ % $|B| = 0$, where |B| - length of vector B. The candidate for the answer - triangle $(0;0)(x;y)( - y / g * b / |B|;x / g * b / |B|)$, but don't forget about checking that the hypotenuse isn't parallel to coordinate axes.",
    "tags": [
      "brute force",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "407",
    "index": "B",
    "title": "Long Path",
    "statement": "One day, little Vasya found himself in a maze consisting of $(n + 1)$ rooms, numbered from $1$ to $(n + 1)$. Initially, Vasya is at the first room and to get out of the maze, he needs to get to the $(n + 1)$-th one.\n\nThe maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number $i$ $(1 ≤ i ≤ n)$, someone can use the first portal to move from it to room number $(i + 1)$, also someone can use the second portal to move from it to room number $p_{i}$, where $1 ≤ p_{i} ≤ i$.\n\nIn order not to get lost, Vasya decided to act as follows.\n\n- Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room $1$.\n- Let's assume that Vasya is in room $i$ and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room $p_{i}$), otherwise Vasya uses the first portal.\n\nHelp Vasya determine the number of times he needs to use portals to get to room $(n + 1)$ in the end.",
    "tutorial": "In this problem you had to simulate route of character in graph. Note that if you are in vertice $i$, then edges in all vertices with numbers less than $i$ are turned to $p_{i}$. It gives us opportunity to see a recurrence formula: let $dp_{i}$ be number of steps, needed to get from vertice $1$ to vertice $i$, if all edges are rotated back, into $p_{i}$. Then $dp_{i + 1} = 2dp_{i} + 2 - dp_{pi}$. Answer will be $dp_{n + 1}$.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "407",
    "index": "C",
    "title": "Curious Array",
    "statement": "You've got an array consisting of $n$ integers: $a[1], a[2], ..., a[n]$. Moreover, there are $m$ queries, each query can be described by three integers $l_{i}, r_{i}, k_{i}$. Query $l_{i}, r_{i}, k_{i}$ means that we should add $\\binom{b-l_{i}+k_{i}}{k_{i}}$ to each element $a[j]$, where $l_{i} ≤ j ≤ r_{i}$.\n\nRecord $\\textstyle{\\binom{y}{x}}$ means the binomial coefficient, or the number of combinations from $y$ elements into groups of $x$ elements.\n\nYou need to fulfil consecutively all queries and then print the final array.",
    "tutorial": "In this problem you had to find how to add binomial coefficients in array offline. Let's see, how problem changes due to increasing k from small to big values. 1) All queries have K = 0 Every time you add 1 on subsegment. For solve this task you can add 1 at some array b[] in b[L] 1, then substract 1 from b[R+1], and after doing all queries make array a[] as array of prefix sums of array b[]. 2) All queries have K = 1 Arithmetic progression 1 2 3 4 ... is added on subsegment For solve this task you can add 1 at some array c[] in c[L] 1, then substract 1 from c[R+1], and after doing all queries make array b[] as array of prefix sums of array c[]. Actually you added 1 1 ... 1 on every subsegment at each query. If you will substract (R - L + 1) from c[R+1], and make array a[] as array of prefix sums of array b[], then it will be an answer: 1 1 ... 1 became 1 2 3 ... (R-L+1). 3) K is arbitrary Summaring previous results one can see that if we will do and after that do a[i][j] = a[i][j-1] + a[i+1][j] (making a[i] as array of prefix sums array a[i+1]), a[0] will be the answer. What is C(k + 1 - j + r - l, k + 1 - j)? This number is need for each query affect only on segment L..R, and you can see, why is it so, in Pascal's Triangle.",
    "tags": [
      "brute force",
      "combinatorics",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "407",
    "index": "D",
    "title": "Largest Submatrix 3",
    "statement": "You are given matrix $a$ of size $n × m$, its elements are integers. We will assume that the rows of the matrix are numbered from top to bottom from 1 to $n$, the columns are numbered from left to right from 1 to $m$. We will denote the element on the intersecting of the $i$-th row and the $j$-th column as $a_{ij}$.\n\nWe'll call submatrix $i_{1}, j_{1}, i_{2}, j_{2}$ $(1 ≤ i_{1} ≤ i_{2} ≤ n; 1 ≤ j_{1} ≤ j_{2} ≤ m)$ such elements $a_{ij}$ of the given matrix that $i_{1} ≤ i ≤ i_{2}$ AND $j_{1} ≤ j ≤ j_{2}$. We'll call the area of the submatrix number $(i_{2} - i_{1} + 1)·(j_{2} - j_{1} + 1)$. We'll call a submatrix inhomogeneous, if all its elements are distinct.\n\nFind the largest (in area) inhomogenous submatrix of the given matrix.",
    "tutorial": "In this task you have to find largest by area submatrix, consisting from different numbers. Let's see solutions from slow to fast. 1) Solution by $O(n^{6})$: Iterate through two opposite vertices submatrix-answer and check that all numbers are different. 2) Solution by $O(n^{4})$: Let's fix Up and Down borders submatrix-answer ($O(n^{2})$). Use two pointers method to iterate Left and Right borders: while in submatrix there are no equal numbers, increment Right, while there are equal numbers - increment Left. Every check - $(O(n))$, increments - $(O(n))$. 3) Solution by $O(n^{3}logn)$: Let's construct function maxR(Left) (let's consider that Up <= Down are fixed): maximal value Right, so that in submatrix (Up, Down, Left, Right) there is no equals numbers. You can see that maxR(i) <= maxR(i + 1) is true for every i. How values of this function changes by shift Down to Down-1? Every value maxR(Left) can only be the same (if segment(Down, Down, Left, maxR(Left)) only added new numbers), or it can decrease. When maxR(Left) is decreasing? Only when one of the numbers from added segment have already been in the current submatrix. Shift Down to down let's see all numbers in row Down. For each number (let it be in column j) find indices i and k so i <= j, there is number, equal to a[Down][j] between rows Up and Down-1, i - maximal; k >= j, there is number, equal to a[Down][j] between rows Up and Down-1, k - minimal. When you find these indices (it is easy to find them using set, when you store all columns where number x was between Up and Down for all numbers x), you can try to update maxR[i] with j - 1, maxR[j] with k - 1. It will be enough, if you also update for all i = m..1 maxR[i] = min(maxR[i], maxR[i + 1]). Now maxR(Left) is correct, and you can check answer for these Up and Down by $O(n)$. 4) Now, solution by $O(n^{3})$. It requires understanding previous solution. Previous solution, despite good asymptotics, requires to store a lot (about 160 000) sets, where you will store about 160 000 elements. Even at n = 200 it works very slow. Let's get rid of log. Set is using only for finding nearest left and right elements, which are in rows from Up to Down, and equal to current. Note that when you do Up = Up - 1, nearest element comes near (by column) to a[i][j], so we can find all numbers, for which the nearest element will be in new row Up, and update them nearest number, and do that in $O(n^{2})$. This solution uses $O(n^{2})$ memory and $O(n^{3})$ time.",
    "tags": [
      "dp",
      "hashing"
    ],
    "rating": 2700
  },
  {
    "contest_id": "407",
    "index": "E",
    "title": "k-d-sequence",
    "statement": "We'll call a sequence of integers a good $k$-$d$ sequence if we can add to it at most $k$ numbers in such a way that after the sorting the sequence will be an arithmetic progression with difference $d$.\n\nYou got hold of some sequence $a$, consisting of $n$ integers. Your task is to find its longest contiguous subsegment, such that it is a good $k$-$d$ sequence.",
    "tutorial": "In this problem you have to find longest subsegment, satisfying the condition. Reduce problem to $d = 1$. If $d = 0$, then answer is longest subsegment from equal numbers, this case we solve separately. If $d  \\neq  0$, then notice that if on some subsegment there are two numbers $a_{i}, a_{j}$ so that $a_{i}$%$d  \\neq  a_{j}$%$d$, then this segment can't be good. Divide the sequence to consequent subsegments numbers, equal by modulo d, and divide each number by d, and solve task separately with every segment, consider that $d = 1$. Notice that segment [L, R] is good if and only if when max(L, R) - min(L, R) - (R - L) <= k, and there are no equal numbers. It is easy to exlain: if there are no equal numbers, then max(L, R) - min(L, R) - (R - L) is exactly number of numbers is needed to add for segment to consist of all numbers from min(L, R) to max(L, R). For all L lets find such maxR[L], that on segment [L..maxR[l]] there are no equal numbers, and maxR[L] is maximal. It can be done by $O(nlogn)$ by many ways, for example you can use map. Let's learn how we can maintain array a[R] = max(L, R) - min(L, R) - (R - L). If we have such array, then we have to find rightmost R such that a[R] <= k to get an answer. We will need two stacks and segment tree with operations \"Add number on segment\", \"Find min element on segment\", \"Find rightmost number doesn't exceed k\". Let's iterate L from right to left (n downto 1). How does function max(L, R) look like with fixed L? It's values represent a set of segments so that maximum on the segment is leftmost element of segment, and these maximums are increasing. (example: for array 6 4 8 0 7 9 function max(1, R) will be 6 6 8 8 8 9). How function changes with shift L to left? Some segments are absorbed by new element, if new element is bigger than maximum on segment. Maximums on segments are increasing, so we can keep them all in stack, and when we need to add new element we have to only pop some segments from stacks while maximum on top of stack is less then new element, and push new segment after that. If every operation with stack will be accompanied with right operation with segment tree, we can store array a[R] = max(L, R). For get array a[R] = max(L, R) - min(L, R) we need only to maintain second similar stack. For get array a[R] = max(L, R) - min(L, R) we need add -1 on all suffix when we are shitfing L. Now query \"Find fightmost number less of equal k\". First, segment tree divides segment of request to log(n) segments with length powers of two. Let's choose rightmost segment with minimum <= k, and do iterative deeping there to find element that we need. So, for every L we get query on segment L..maxR(L) on rightmost number less or equal k. It is one of candidates to an answer. We are doing O(n) operation with stack, and every requires query to segment tree, so asymptotics is $O(nlogn)$.",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "408",
    "index": "A",
    "title": "Line to Cashier",
    "statement": "Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.\n\nThere are $n$ cashiers at the exit from the supermarket. At the moment the queue for the $i$-th cashier already has $k_{i}$ people. The $j$-th person standing in the queue to the $i$-th cashier has $m_{i, j}$ items in the basket. Vasya knows that:\n\n- the cashier needs 5 seconds to scan one item;\n- after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change.\n\nOf course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.",
    "tutorial": "In this problem you were to find waiting the time for every queue by summing up the purchases of all the people, and return the minimum.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "408",
    "index": "B",
    "title": "Garland",
    "statement": "Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought $n$ colored sheets of paper, the area of each sheet is 1 square meter.\n\nThe garland must consist of exactly $m$ pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.\n\nVasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ​​$m$ pieces of paper in the garland. Calculate what the maximum total area of ​​the pieces of paper in the garland Vasya can get.",
    "tutorial": "In this problem it is necessary to find the garland with the maximal length, which can be composed of elements that we have. First, if you need some color, but you don't have it, then the answer is -1 Otherwise, answer is always exists. Let's sum the answers for all the colors separately. Suppose we have $a$ pieces of a garland of some color, and we need $b$ pieces. Then we have to add $min(a, b)$ to the answer: if $a > = b$ we will use $b$ 1 meter pieces, in the other case if $a < b$ we will use all $a$ pieces.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "411",
    "index": "A",
    "title": "Password Check",
    "statement": "You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic check.\n\nWeb-developers of the company Q assume that a password is complex enough, if it meets all of the following conditions:\n\n- the password length is at least 5 characters;\n- the password contains at least one large English letter;\n- the password contains at least one small English letter;\n- the password contains at least one digit.\n\nYou are given a password. Please implement the automatic check of its complexity for company Q.",
    "tutorial": "In the first problem you should correctly implement what was written in statement. It could be done like this:",
    "tags": [
      "*special",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "411",
    "index": "B",
    "title": "Multi-core Processor",
    "statement": "The research center Q has developed a new multi-core processor. The processor consists of $n$ cores and has $k$ cells of cache memory. Consider the work of this processor.\n\nAt each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.\n\nThe development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within $m$ cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the $m$ cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.",
    "tutorial": "In this problem you should read the statement carefully, consider some principal cases and implement them in your program. The author's solution is: We will store array $blockedCell[]$ (value in cell $i$ equals $1$ if this cell is blocked, $0$ otherwise), blockedCore[]$ (value in cell $i$ equals $0$, if this core is not blocked and the number cycle when this core is blocked otherwise). Consider all cycles from the first to the last. Consider the cycle number $k$. Consider all processors and calc what cells will blocked on the cycle $k$. Set values one to corresponding cells of array $blockedCell[]$ Then for each core $i$ if conditions $blockedCore[i] = 0$ and $blockedCell[x[i][k]] = 1$ meet then core $i$ is blocked on cycle $k$. Set $blockedCore[i] = k$.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "411",
    "index": "C",
    "title": "Kicker",
    "statement": "Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the half-backs and forwards (plays attack).\n\nTwo teams of company Q decided to battle each other. Let's enumerate players from both teams by integers from $1$ to $4$. The first and second player play in the first team, the third and the fourth one play in the second team. For each of the four players we know their game skills in defence and attack. The defence skill of the $i$-th player is $a_{i}$, the attack skill is $b_{i}$.\n\nBefore the game, the teams determine how they will play. First the players of the first team decide who will play in the attack, and who will play in the defence. Then the second team players do the same, based on the choice of their opponents.\n\nWe will define a team's defence as the defence skill of player of the team who plays defence. Similarly, a team's attack is the attack skill of the player of the team who plays attack. We assume that one team is guaranteed to beat the other one, if its defence is strictly greater than the opponent's attack and its attack is strictly greater than the opponent's defence.\n\nThe teams of company Q know each other's strengths and therefore arrange their teams optimally. Identify the team that is guaranteed to win (if both teams act optimally) or tell that there is no such team.",
    "tutorial": "To solve this problem you should use logic (mathematic logic) :] Logic says: If for some arrangement of the first team there is no arrangement to have even a draw then the first team is guaranteed to win. If for any arrangement of the first team there is some arrangement for the second team when the second team wins then the second team is guaranteed to win. Otherwise nobody is guaranteed to win. The answer is Draw. This logic should be implemented in your program. I could be done considering each arrangement of every team.",
    "tags": [
      "*special",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "412",
    "index": "A",
    "title": "Poster",
    "statement": "The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.\n\nThe slogan of the company consists of $n$ characters, so the decorators hung a large banner, $n$ meters wide and $1$ meter high, divided into $n$ equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.\n\nOf course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the $k$-th square of the poster. To draw the $i$-th character of the slogan on the poster, you need to climb the ladder, standing in front of the $i$-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the $i$-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.\n\nDrawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!",
    "tutorial": "One of the optimal solutions is the following. If $k - 1  \\le  n - k$ then firstly let's move ladder to the left by $k - 1$ positions. After that we will do the following pair of operations $n - 1$ times: paint $i$-th symbol of the slogan and move the ladder to the right. In the end we will paint the last symbol of the slogan. If $k - 1 > n - k$ then we will move the ladder to the right by $n - k$ positions. After that we will also paint symbol and move the ladder to the left. Our last action will be to paint the first symbol of the slogan. Total number of sought operations is $min(k - 1, n - k) + 2 \\cdot n - 1$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "412",
    "index": "B",
    "title": "Network Configuration",
    "statement": "The R1 company wants to hold a web search championship. There were $n$ computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the $i$-th computer it was $a_{i}$ kilobits per second.\n\nThere will be $k$ participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.\n\nThe network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least $k$ of $n$ computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?",
    "tutorial": "In this task you should sort array in descending order and print $k$-th element. Due to the weak constraints you could also solve the problem in the following manner. Let's brute $ans$ - the value of answer and calculate how many computers already have Internet's speed not less than $ans$. If there are not less than $k$ such computers then the answer is acceptable. Let's find the maximum among acceptable answers and it will be the sought value.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "412",
    "index": "C",
    "title": "Pattern",
    "statement": "Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.\n\nIn this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.\n\nProgrammers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given $n$ patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?",
    "tutorial": "Let's find the answer symbol-by-symbol. Let's consider $i$-th symbol. If there are two different symbols differ from '?' on $i$-th positions in the given strings then we must place '?' on $i$-th position in the answer. If there are '?' on $i$-th positions in all string then we can write any symbol. Obviously, it is better to write not '?' but any letter, 'x' for example. Lastly we should consider the case when there are only '?' and one the same letter on $i$-th positions. In this case we should find this letter and put it to the answer.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "412",
    "index": "D",
    "title": "Giving Awards",
    "statement": "The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.\n\nToday is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person $x$ to his office for a reward, and then immediately invite person $y$, who has lent some money to person $x$, then they can meet. Of course, in such a situation, the joy of person $x$ from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.\n\nHowever, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.",
    "tutorial": "Let's build sought permutation by adding employee one-by-one. Let's we already define the order of the first $k$ employees: $a_{1}, a_{2}, ..., a_{k}$. Let's place $k + 1$-th after $a_{k}$-th. If $a_{k}$-th employee owe money to $k + 1$-th then we will swap their positions (and will get permutation $a_{1}, a_{2}, ..., a_{k - 1}, k + 1, a_{k}$). If $a_{k - 1}$-th employee also owe money to $k + 1$-th then we will also swap their positions and so on. If all first $k$ employees owe money to $k + 1$-th then $k + 1$-th employee will be placed first in permutation. This algorithm has time complexity $O(m)$, where $m$ is the number of the debt relationships.",
    "tags": [
      "dfs and similar"
    ],
    "rating": 2000
  },
  {
    "contest_id": "412",
    "index": "E",
    "title": "E-mail Addresses",
    "statement": "One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day.\n\nToday, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume that the string contains the letters of some users of the R1 mail. Recovering letters is a tedious mostly manual work. So before you start this process, it was decided to estimate the difficulty of recovering. Namely, we need to calculate the number of different substrings of the saved string that form correct e-mail addresses.\n\nWe assume that valid addresses are only the e-mail addresses which meet the following criteria:\n\n- the address should begin with a non-empty sequence of letters, numbers, characters '_', starting with a letter;\n- then must go character '@';\n- then must go a non-empty sequence of letters or numbers;\n- then must go character '.';\n- the address must end with a non-empty sequence of letters.\n\nYou got lucky again and the job was entrusted to you! Please note that the substring is several consecutive characters in a string. Two substrings, one consisting of the characters of the string with numbers $l_{1}, l_{1} + 1, l_{1} + 2, ..., r_{1}$ and the other one consisting of the characters of the string with numbers $l_{2}, l_{2} + 1, l_{2} + 2, ..., r_{2}$, are considered distinct if $l_{1} ≠ l_{2}$ or $r_{1} ≠ r_{2}$.",
    "tutorial": "Let's consider position $i$ such, that $s_{i} = '@'$. We are going to calculate the number of such substrings that are correct addresses and the symbol '@' in them is $s_{i}$. Let's go to the left from $i$ until we find '@' or '.' - the symbols that aren't allowed to be to the left of '@'. Let's calculate $cnt$ how many letters on the segment we went through. This letters can be the first symbols of the correct addresses. Let's now move to the right of $i$ while considered symbol is letter or digit. If we stopped and the string is over or the following symbol is '@' or '_' then there aren't correct addresses. If the following symbol is '.' then let's go to the right of it while the considered symbols are letters. The correct address can finish in every such position, so we should add $cnt$ to the answer. In the described solution \"move\" means \"brute by cycle for\". We can do this because we will go through each symbol not more than 2 times. Total time complexity is $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "413",
    "index": "A",
    "title": "Data Recovery",
    "statement": "Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors.\n\nThe testing goes in $n$ steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer in R2 is keeping a report record on the work of the processor: he writes down the minimum and the maximum measured temperature in his notebook. His assistant had to write down all temperatures into his notebook, but (for unknown reasons) he recorded only $m$.\n\nThe next day, the engineer's assistant filed in a report with all the $m$ temperatures. However, the chief engineer doubts that the assistant wrote down everything correctly (naturally, the chief engineer doesn't doubt his notes). So he asked you to help him. Given numbers $n$, $m$, $min$, $max$ and the list of $m$ temperatures determine whether you can upgrade the set of $m$ temperatures to the set of $n$ temperatures (that is add $n - m$ temperatures), so that the minimum temperature was $min$ and the maximum one was $max$.",
    "tutorial": "Count min and max values in given array of length $m$. If the min value is less then given $min$ or the max value is greater the given $max$ the answer is Incorrect. Count value $0  \\le  need  \\le  2$, which equals to minimal number of elements which should be added in given array so that the min value will become $min$ and the max value will become $max$. Then answer is Correct if $n - m  \\ge  need$. Otherwise answer is Incorrect.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "413",
    "index": "B",
    "title": "Spyke Chatting",
    "statement": "The R2 company has $n$ employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.\n\nR2 has $m$ Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the $k$-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.\n\nThe R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.",
    "tutorial": "Process all queries and count some values: for each employee we will count number of messages which weer sent by this employee and for each chat we will count number of messages which were sent to this chat. Then the answer for some employee equals to sum of messages sent to all chats in which he participates minus all messages sent by him to some chats.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "413",
    "index": "C",
    "title": "Jeopardy!",
    "statement": "'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2.\n\nThe finals will have $n$ questions, $m$ of them are auction questions and $n - m$ of them are regular questions. Each question has a price. The price of the $i$-th question is $a_{i}$ points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.\n\nThe game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.\n\nAll R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.",
    "tutorial": "Firstly choose all not auction questions and answer on them. So we have only auctions. Sort them in non-decreasing order. Consider each size of suffix of auctions and answer them on their initial price and try to answer other questions by multiplying by 2. It could be explained in this way: less than the cost value, the less you need to multiply your balance by 2. Also more than the cost value more profitable to take it for initial value.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "413",
    "index": "D",
    "title": "2048",
    "statement": "The programmers from the R2 company love playing 2048. One day, they decided to invent their own simplified version of this game — $2^{k}$ on a stripe.\n\nImagine an infinite in one direction stripe, consisting of unit squares (the side of each square is equal to the height of the stripe). Each square can either be empty or contain some number.\n\nInitially, all squares are empty. Then at infinity one of the unit squares number 2 or 4 appears. Then the player presses a button once, and the appeared number begins to move towards the beginning of the stripe. Let's assume that some number $x$ moves to the beginning of the stripe, then it will stop if:\n\n- it either gets in the first square of the stripe;\n- or it is in the square that is preceded by a square with number $y$ $(y ≠ x)$. But if number $x$ at some point of time gets to the square with the same number then both numbers add to each other and result in $2x$. The new number $2x$ continues moving to the beginning of the stripe by the same rules.\n\nAfter the final stop of the number moving process, the infinity gets a new number 2 or 4 and the process repeats. Read the notes to the test samples to better understand the moving strategy.\n\nI guess you've understood that the game progress fully depends on the order in which numbers 2 and 4 appear. Let's look at some sequence of numbers 2 and 4 in the game. We assume that the sequence is winning if it results in at least one square getting the number greater or equal than $2^{k}$.\n\nThe goal of the game is to make up a winning sequence of $n$ numbers. But not everything is so simple, some numbers in the sequence are identified beforehand. You are given a sequence consisting of numbers 0, 2, 4. Count how many ways there are to replace each 0 of the sequence with 2 or 4 to get a winning sequence.",
    "tutorial": "Consider some state in your game. Note that, we should maintain the maximum suffix if values in descending order. Also, we will maintain only first $k - 1$ powers of two and keep in mind if have already $k$-th power of two or greater. In fact in violation of this order we can not use these numbers because values could only increase. So, we will count dynamic $dp[i][mask][j]$, where $i$ - size of considered elements, $mask$ - mask of first $k - 1$ powers of two in descending order, $j$ - do we have already the $k$-th power of two or greater (0 or 1). There are two possible transitions by 2 or 4. If the current element equals to 0 make both transitions.",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "413",
    "index": "E",
    "title": "Maze 2D",
    "statement": "The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a $2 × n$ maze.\n\nImagine a maze that looks like a $2 × n$ rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can move from an empty cell of the maze to any side-adjacent empty cell. The shortest path problem is formulated as follows. Given two free maze cells, you need to determine the minimum time required to go from one cell to the other.\n\nUnfortunately, the developed algorithm works well for only one request for finding the shortest path, in practice such requests occur quite often. You, as the chief R2 programmer, are commissioned to optimize the algorithm to find the shortest path. Write a program that will effectively respond to multiple requests to find the shortest path in a $2 × n$ maze.",
    "tutorial": "We will consider queries one by one. Firstly check if the one cell of the query is reachable from the second. Find all connected components. If the cells are in different connected components, the answer is -1. Otherwise assume that both cells are situated in columns with exactly one obstacle. To find the answer for such cells we should count the length of the path between these columns using array of partial sums. To count this array consider all columns from left to right and store the last type of column with exactly one obstacle (down obstacle or up obstacle). If in column $j$ the type changes set in the cell $j$ of the array value 1, otherwise set value 0. In this case of query the length of the path between cells equals to sum of absolute differences between column indexes and counted partial sum between these columns. If the column with the left cell has no obstacles find the nearest column with exactly one obstacle to the right. If the column with the right cell has no obstacles find the nearest column with exactly one obstacle to the left. So we get the situation considered above. Be careful if there is no columns with exactly one obstacle between given cells.",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2200
  },
  {
    "contest_id": "414",
    "index": "A",
    "title": "Mashmokh and Numbers",
    "statement": "It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.\n\nIn this game Mashmokh writes sequence of $n$ distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers $x$ and $y$ from the board, he gets $gcd(x, y)$ points. At the beginning of the game Bimokh has zero points.\n\nMashmokh wants to win in the game. For this reason he wants his boss to get exactly $k$ points in total. But the guy doesn't know how choose the initial sequence in the right way.\n\nPlease, help him. Find $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$ such that his boss will score exactly $k$ points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most $10^{9}$.",
    "tutorial": "In each turn Bimokh will at least get one point so the result is at lease $\\frac{n t}{2}$. So if $k\\ll{\\frac{n}{2}}$ the answer is -1. Let's denote $x=k-\\lfloor{\\frac{n-2}{2}}\\rfloor$. Then you could output $x$ and $2x$ as the first two integers in the sequence then output $\\lfloor{\\frac{n-2}{2}}\\rfloor$ consecutive integers and also one random integer(distinct from the others) if $n$ is odd. Based on the following fact, Bimokh's point will equal to $x+\\lfloor{\\frac{n-2}{2}}\\rfloor$ which is equal to $k$. $\\forall a\\geq1:g c d(a,a+1)=1$. Also you must consider some corner cases such as when $n = 1$.",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "414",
    "index": "B",
    "title": "Mashmokh and ACM",
    "statement": "Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.\n\nA sequence of $l$ integers $b_{1}, b_{2}, ..., b_{l}$ $(1 ≤ b_{1} ≤ b_{2} ≤ ... ≤ b_{l} ≤ n)$ is called good if each number divides (without a remainder) by the next number in the sequence. More formally $b_{i}\\mid b_{i+1}$ for all $i$ $(1 ≤ i ≤ l - 1)$.\n\nGiven $n$ and $k$ find the number of good sequences of length $k$. As the answer can be rather large print it modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Lets define $dp[i][j]$ as number of good sequences of length $i$ that ends in $j$. Let's denote divisors of $j$ by $x_{1}, x_{2}, ..., x_{l}$. Then $d p[i][j]=\\sum_{r=1}^{l}d p[i-1][x_{r}]$ This yields $O(nk sqrt(n))$ solution which is not fast enough. But one could use the fact that the following loops run in $O(n log(n))$ in order to achieve $O(nk log(n))$ which is fast enough to pass the tests. for (i = 1; i <= n; i++)  //loop from 1 to n for (int j = i; j <= n; j += i)  //iterating through all multiples of i that are at most n",
    "tags": [
      "combinatorics",
      "dp",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "414",
    "index": "C",
    "title": "Mashmokh and Reverse Operation",
    "statement": "Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.\n\nYou have an array $a$ of length $2^{n}$ and $m$ queries on it. The $i$-th query is described by an integer $q_{i}$. In order to perform the $i$-th query you must:\n\n- split the array into $2^{n - qi}$ parts, where each part is a subarray consisting of $2^{qi}$ numbers; the $j$-th subarray $(1 ≤ j ≤ 2^{n - qi})$ should contain the elements $a[(j - 1)·2^{qi} + 1], a[(j - 1)·2^{qi} + 2], ..., a[(j - 1)·2^{qi} + 2^{qi}]$;\n- reverse each of the subarrays;\n- join them into a single array in the same order (this array becomes new array $a$);\n- output the number of inversions in the new $a$.\n\nGiven initial array $a$ and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.",
    "tutorial": "Build a complete binary tree with height $n$. So its $i$-th leaf corresponds to $i$-th element of the initial array. For each vertex $v$ lets define its subarray as the subarray containing the elements that have a leaf corresponding to them in subtree rooted at $v$. For each non-leaf vertex $v$, suppose its left child's subarray contains elements $[a..b]$ of the array and its right child contains elements $[b + 1..c]$ of the array. We'll calculate two numbers for this vertex. number of pairs $(i, j)(a  \\le  i  \\le  b  \\le  j  \\le  c)$ that $a_{i} > b_{j}$ and number of pairs $(i, j)(a  \\le  i  \\le  b  \\le  j  \\le  c)$ that $a_{i} < b_{j}$. We'll call the first calculated number, normal number and the other one reverse number. Calculating these numbers can be done using merge-sort algorithm in $O(n * 2^{n})$. We'll Initially write normal number for each vertex on it. We'll define a vertex's type as type of the number that is written on them. Let's define height of a vertex $v$ equal to its distnace to the nearest leaf. Also let's define switching a vertex as switching the number written on it with the other type number(if normal number is written on it change it to reverse number and vise-versa). Initially sum of writed numbers is equal to number of inversions in the initial array. Now when query $h$ is given, by switching all vertices with height at most $h$, the sum of writed numbers will become equal to the number of inversions in the new array. The only question is how to perform such query fast? One can notice that in a height $h$, always all of the vertices has the same type. So we can calculate two numbers for each height $h$. The sum of normal numbers of vertices with height $h$ and the sum of their reverse numbers. Then instead of switching vertices in a height one by one each time, one can just switch the number for that height. The sum of numbers of heights after each query will be the answer for that query. since there are $n$ height each query can be performed in $O(n)$ so the total running time will be $O(nq + n * 2^{n})$.",
    "tags": [
      "combinatorics",
      "divide and conquer"
    ],
    "rating": 2100
  },
  {
    "contest_id": "414",
    "index": "D",
    "title": "Mashmokh and Water Tanks",
    "statement": "Mashmokh is playing a new game. In the beginning he has $k$ liters of water and $p$ coins. Additionally he has a rooted tree (an undirected connected acyclic graph) that consists of $m$ vertices. Each vertex of the tree contains a water tank that is empty in the beginning.\n\nThe game begins with the fact that Mashmokh chooses some (no more than $k$) of these tanks (except the root) and pours into each of them exactly $1$ liter of water. Then the following process is performed until there is no water remained in tanks.\n\n- The process consists of several steps.\n- At the beginning of each step Mashmokh opens doors of all tanks. Then Mashmokh closes doors of some tanks (he is not allowed to close door of tank in the root) for the duration of this move. Let's denote the number of liters in some tank with closed door as $w$, Mashmokh pays $w$ coins for the closing of that tank during this move.\n- Let's denote by $x_{1}, x_{2}, ..., x_{m}$ as the list of vertices of the tree sorted (nondecreasing) by their depth. The vertices from this list should be considered one by one in the order. Firstly vertex $x_{1}$ (which is the root itself) is emptied. Then for each vertex $x_{i}$ $(i > 1)$, if its door is closed then skip the vertex else move all the water from the tank of vertex $x_{i}$ to the tank of its father (even if the tank of the father is closed).\n\nSuppose $l$ moves were made until the tree became empty. Let's denote the amount of water inside the tank of the root after the $i$-th move by $w_{i}$ then Mashmokh will win $max(w_{1}, w_{2}, ..., w_{l})$ dollars. Mashmokh wanted to know what is the maximum amount of dollars he can win by playing the above game. He asked you to find this value for him.",
    "tutorial": "Let's suppose instead of a tank there is a pile at each vertex and instead of water the game is played on tiles. Let's denote distance of each vertex $q$ from the root by $depth(q)$. Also Let's label each tile with number of the vertex it was initially put on. Suppose initially there was a tile at each of vertices $v$ and $u$ and after some move tile $u$ and $v$ are in the same vertex's pile. Then one can prove that there were exactly $|depth(v) - depth(u)|$ moves at which vertex containing the tile at vertex with less depth was closed and the vertex containing the other tile wasn't. Suppose after $i$-th move, there was $x_{i}$ tiles inside the root's pile and $x_{j}$ is the maximum among these numbers. Suppose tiles $a_{1}, a_{2}, ...a_{xj}$ were on the root after $j$-th move. Then the other tiles that we put inside the tree at the beginning have no effect in the final result. Then we can suppose that only these tiles were initially put on tree. So we can assume that all tiles we place at the beginning will reach to the root together. Suppose $h_{i}$ of these tiles were put at a vertex with depth $i$ and $d_{1}$ is the maximum depth that there is at least a tile in that depth. So as to these tiles reach to the root together we must pay $\\sum_{i=1}^{d_{1}}\\bigl((d_{1}-i)*h_{i}\\bigr)$. Then we want to minimize the number of needed coins so at the beginning there must not be two consecutive depth $i$ and $i + 1$ that $i + 1  \\le  d$ and there is a tile at depth $i$ and an empty vertex at depth $i + 1$. In other words if we denote the minimum depth that initially there is a tile inside it as $d_{0}$ then there must be a tile at each vertex with depth more than $d_{0}$ and less than or equal to $d_{1}$. Let's iterate over $d_{1}$. Then for each $d_{1}$ we can calculate $d_{2}$, the minimum depth that we can pay the needed price if we put a tile at each vertex with depth at least $d_{2}$ and at most $d_{1}$. Let's denote this needed price as $p_{0}$. Then we can also put $\\frac{p\\!-\\!p_{0}}{d_{1}\\!-\\!d_{2}\\!+\\!1}$ at depth $d_{2} - 1$. So we can calculate maximum number of tiles that we can put on the tree so that they all reach to root together for a fixed $d_{1}$. So the maximum of these numbers for all possible $d_{1}$ will be the answer. Since by increasing $d_{1}$, $d_{2}$ won't decrease one can use two-pointers to update $d_{2}$ while iterating over $d_{1}$. Let's denote number of the vertices with depth $i$ as $cnt_{i}$. Then we can save and update the following values. $s=\\sum_{i=d_{2}}^{d_{1}}c n t_{i}$ $t=\\sum_{i=d_{2}}^{d_{1}}(i\\ast c n t_{i})$ Then the needed price is equal to $(d_{1} * s) - t$. So as long as $(d_{1} * s) - t > p$ we must increase $d_{2}$. This yields an $O(n)$ solution.",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "trees",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "414",
    "index": "E",
    "title": "Mashmokh's Designed Problem",
    "statement": "After a lot of trying, Mashmokh designed a problem and it's your job to solve it.\n\nYou have a tree $T$ with $n$ vertices. Each vertex has a unique index from 1 to $n$. The root of $T$ has index $1$. For each vertex of this tree $v$, you are given a list of its children in a specific order. You must perform three types of query on this tree:\n\n- find distance (the number of edges in the shortest path) between $u$ and $v$;\n- given $v$ and $h$, disconnect $v$ from its father and connect it to its $h$-th ancestor; more formally, let's denote the path from $v$ to the root by $x_{1}, x_{2}, ..., x_{l} (h < l)$, so that $x_{1} = v$ and $x_{l}$ is root; disconnect $v$ from its father ($x_{2}$) and connect it to $x_{h + 1}$; vertex $v$ must be added to the end of the child-list of vertex $x_{h + 1}$;\n- in the vertex sequence produced by calling function dfs(root) find the latest vertex that has distance $k$ from the root.\n\nThe pseudo-code of function dfs(v):\n\n\\begin{verbatim}\n// ls[v]: list of children of vertex v\n// its i-th element is ls[v][i]\n// its size is size(ls[v])\nsequence result = empty sequence;\nvoid dfs(vertex now)\n{\nadd now to end of result;\nfor(int i = 1; i <= size(ls[v]); i = i + 1) //loop from i = 1 to i = size(ls[v])\ndfs(ls[v][i]);\n}\n\\end{verbatim}",
    "tutorial": "Let's define the dfs-order of a tree as the sequence created by calling function dfs(root). We'll build another sequence from a dfs-order by replacing each vertex in dfs-order by '+1' and inserting a '-1' after the last vertex of its subtree. Note that all vertices of a particular subtree are a continuous part of dfs-order of that tree. Also note that for each vertex $v$ if the +1 corresponding to it is the $i$-th element of sequence, then $v$'s distance from root(which we'll denote by height of $v$) is equal to sum of elements $1..i$. Suppose we can perform the following operations on such sequence: For each $i$, find sum of the elements $1..i$. For each $i$ find the biggest $j(j < i)$ so that sum of elements $1..j$ of the sequence equals $p$. Using these two operations we can find LCA of two vertices $v$ and $u$, so since distance of $u$ and $v$ equals to $height(u) + height(v) - 2 * height(LCA(u, v))$ we can answer the second query. Also the third query can be answered using the second operation described above. As for the first query it cuts a continuous part of sequence and insert it in another place. This operation can be done using implicit treap. Also we can use the treap as a segment tree to store the following values for each vertex $v$. Then using these values the operations described above can be done. All of these operation can be done in $O(logn)$. Sum of the elements in its subtree(each vertex in the treap has a value equal to +1 or -1 since it corresponds to an element of the sequence.) Let's write the values of each vertex in the subtree of $v$ in the order they appear in the sequence. Then lets denote sum of the first $i$ numbers we wrote as $ps[i]$ and call elements of ps, prefix sums of the subtree of $v$. Then we store the maximum number amongst the prefix sums. Also we'll store the minimum number amongst prefix sums.",
    "tags": [
      "data structures"
    ],
    "rating": 3200
  },
  {
    "contest_id": "415",
    "index": "A",
    "title": "Mashmokh and Lights",
    "statement": "Mashmokh works in a factory. At the end of each day he must turn off all of the lights.\n\nThe lights on the factory are indexed from $1$ to $n$. There are $n$ buttons in Mashmokh's room indexed from $1$ to $n$ as well. If Mashmokh pushes button with index $i$, then each light with index not less than $i$ that is still turned on turns off.\n\nMashmokh is not very clever. So instead of pushing the first button he pushes some of the buttons randomly each night. He pushed $m$ distinct buttons $b_{1}, b_{2}, ..., b_{m}$ (the buttons were pushed consecutively in the given order) this night. Now he wants to know for each light the index of the button that turned this light off. Please note that the index of button $b_{i}$ is actually $b_{i}$, not $i$.\n\nPlease, help Mashmokh, print these indices.",
    "tutorial": "For this problem for each light $j$ you could just iterate over all pressed buttons and find the first button $b_{i}$ that $b_{i} < j$. Then you could output $b_{i}$ and move to next light.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "415",
    "index": "B",
    "title": "Mashmokh and Tokens",
    "statement": "Bimokh is Mashmokh's boss. For the following $n$ days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back $w$ tokens then he'll get $\\left\\lfloor{\\frac{w a}{b}}\\right\\rfloor$ dollars.\n\nMashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has $n$ numbers $x_{1}, x_{2}, ..., x_{n}$. Number $x_{i}$ is the number of tokens given to each worker on the $i$-th day. Help him calculate for each of $n$ days the number of tokens he can save.",
    "tutorial": "For this problem you can find the number of tokens you can save if you initally have $k$ tokens in $O(1)$. Then you can calculate the answer for all of numbers in $O(n)$. Suppose $\\left\\lfloor{\\frac{w a}{b}}\\right\\rfloor$ by $p$. then $p * b  \\le  w * a$. then ${\\underline{{\\{p_{a}^{b}\\}}}}\\leq w$. Suppose initially we have $k$ tokens. Let $x=\\lfloor{\\frac{w a}{b}}\\rfloor$ then we need to find such maximum $k_{0}$ that $k-k_{0}\\geq\\lceil{\\frac{x.b}{a}}\\rceil$. So $k_{0}$ will be equal to $k-\\left\\lceil{\\frac{x b}{a}}\\right\\rceil$. so we can calculate $k_{0}$ in $O(1)$.",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "416",
    "index": "A",
    "title": "Guess a number!",
    "statement": "A TV show called \"Guess a number!\" is gathering popularity. The whole Berland, the old and the young, are watching the show.\n\nThe rules are simple. The host thinks of an integer $y$ and the participants guess it by asking questions to the host. There are four types of acceptable questions:\n\n- Is it true that $y$ is strictly larger than number $x$?\n- Is it true that $y$ is strictly smaller than number $x$?\n- Is it true that $y$ is larger than or equal to number $x$?\n- Is it true that $y$ is smaller than or equal to number $x$?\n\nOn each question the host answers truthfully, \"yes\" or \"no\".\n\nGiven the sequence of questions and answers, find any integer value of $y$ that meets the criteria of all answers. If there isn't such value, print \"Impossible\".",
    "tutorial": "Let's use the usual Div 2 problem A approach - the naive one. We will track the interval which might contain the number we're guessing. With each of the query we update this interval. If at the end the interval is non-empty then we output any number from it, otherwise the result is \"Impossible\".",
    "code": "#include <iostream>\n \nvoid minimize(int &a, int b) { a = std::min(a, b); }\nvoid maximize(int &a, int b) { a = std::max(a, b); }\n \nusing namespace std;\n \nint main() {\n\tint mx = 2 * 1000 * 1000 * 1000;\n\tint mn = -mx;\n\t\n\tint n; cin >> n;\n\twhile (n --> 0) {\n\t\tstring s; cin >> s;\n\t\tint x; cin >> x;\n\t\tstring ans; cin >> ans;\n\t\t\n\t\tif (ans == \"N\") {\n\t\t\tif (s == \">=\") s = \"<\";\n\t\t\telse if (s == \"<\") s = \">=\";\n\t\t\telse if (s == \"<=\") s = \">\";\n\t\t\telse s = \"<=\";\n\t\t}\n\t\t\n\t\tif (s == \">=\") maximize(mn, x);\n\t\telse if (s == \">\") maximize(mn, x + 1);\n\t\telse if (s == \"<=\") minimize(mx, x);\n\t\telse minimize(mx, x - 1);\n\t}\n\t\n\tif (mn <= mx) cout << mn;\n\telse cout << \"Impossible\";\n}",
    "tags": [
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "416",
    "index": "B",
    "title": "Art Union",
    "statement": "A well-known art union called \"Kalevich is Alive!\" manufactures objects d'art (pictures). The union consists of $n$ painters who decided to organize their work as follows.\n\nEach painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these $n$ colors. Adding the $j$-th color to the $i$-th picture takes the $j$-th painter $t_{ij}$ units of time.\n\nOrder is important everywhere, so the painters' work is ordered by the following rules:\n\n- Each picture is first painted by the first painter, then by the second one, and so on. That is, after the $j$-th painter finishes working on the picture, it must go to the $(j + 1)$-th painter (if $j < n$);\n- each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on;\n- each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest;\n- as soon as the $j$-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.\n\nGiven that the painters start working at time 0, find for each picture the time when it is ready for sale.",
    "tutorial": "All we need is to iterate over all painters and for each painter to iterate over all pictures. In the inner loop we also remember when the painter finished working on the picture to make sure that the next painter will not start working on it earlier.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nint main() {\n\tint m; cin >> m;\n\tint n; cin >> n;\n\t\n\tint paintingTime[m][n];\n\tfor (int i = 0 ; i < m ; i++) {\n\t\tfor (int j = 0 ; j < n ; j++) cin >> paintingTime[i][j];\n\t}\n\t\n\tvector<int> finishTime(m);\n \n\tfor (int i = 0 ; i < n ; i++) {\n\t\tint freeAt = 0;\n\t\tfor (int j = 0 ; j < m ; j++) {\n\t\t\tint start = max(freeAt, finishTime[j]);\n\t\t\tfinishTime[j] = start + paintingTime[j][i];\n\t\t\tfreeAt = finishTime[j];\n\t\t}\n\t}\n\t\n\tfor (auto x : finishTime) cout << x << ' ';\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "416",
    "index": "C",
    "title": "Booking System",
    "statement": "Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!\n\nA restaurant called \"Dijkstra's Place\" has started thinking about optimizing the booking system.\n\nThere are $n$ booking requests received by now. Each request is characterized by two numbers: $c_{i}$ and $p_{i}$ — the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.\n\nWe know that for each request, all $c_{i}$ people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.\n\nUnfortunately, there only are $k$ tables in the restaurant. For each table, we know $r_{i}$ — the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.\n\nYour task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.",
    "tutorial": "Let's solve this one greedy. All we need to notice is that the optimal solution will be to place first the groups with biggest sum which they are ready to pay. For each such group it will be optimal to allocate the smallest matching table. The input limits allow to do a full search when looking for a table.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nclass group {\n\tpublic:\n\t\n\tint id;\n\tint size;\n\tint income;\n};\n \nclass table {\n\tpublic:\n\t\n\tint id;\n\tint size;\n};\n \nbool byIncomeDescending(const group &g1, const group &g2) {\n\treturn g1.income > g2.income;\n}\n \nbool bySize(const table &t1, const table &t2) {\n\treturn t1.size < t2.size;\n}\n \nbool canFit(const table &t, const group &g) {\n\treturn t.size < g.size;\n}\n \nint main() {\n\tint n; cin >> n;\n\tvector<group> groups(n);\n\tfor (int i = 0 ; i < n ; i++) {\n\t\tgroups[i].id = i + 1;\n\t\tcin >> groups[i].size >> groups[i].income;\n\t}\n \n\tsort(groups.begin(), groups.end(), byIncomeDescending);\n\t\n\tint m; cin >> m;\n\tvector<table> tables(m);\n\tfor (int i = 0 ; i < m ; i++) {\n\t\ttables[i].id = i + 1;\n\t\tcin >> tables[i].size;\n\t}\n\t\n\tsort(tables.begin(), tables.end(), bySize);\n\t\n\tint sum = 0;\n\tvector<pair<int, int> > ans;\n \n\tfor (int i = 0 ; i < n ; i++) {\n\t\tauto group = groups[i];\n\t\t\n\t\tauto tableToGive = lower_bound(tables.begin(), tables.end(), group, canFit);\n\t\tif (tableToGive == tables.end()) continue;\n\t\t\n\t\tsum += group.income;\n\t\tans.push_back(make_pair(group.id, tableToGive->id));\n\t\ttables.erase(tableToGive);\n\t}\n\t\n\tcout << ans.size() << ' ' << sum << endl;\n\tfor (auto p : ans) cout << p.first << ' ' << p.second << endl;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "416",
    "index": "D",
    "title": "Population Size",
    "statement": "Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.\n\nPolycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence $a_{1}, a_{2}, ..., a_{n}$, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence $(8, 6, 4, 2, 1, 4, 7, 10, 2)$ can be considered as a sequence of three arithmetic progressions $(8, 6, 4, 2)$, $(1, 4, 7, 10)$ and $(2)$, which are written one after another.\n\nUnfortunately, Polycarpus may not have all the data for the $n$ consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of $a_{i}$ ​​may be unknown. Such values are represented by number -1.\n\nFor a given sequence $a = (a_{1}, a_{2}, ..., a_{n})$, which consists of positive integers and values ​​-1, find the minimum number of arithmetic progressions Polycarpus needs to get $a$. To get $a$, the progressions need to be written down one after the other. Values ​​-1 may correspond to an arbitrary positive integer and the values $a_{i} > 0$ must be equal to the corresponding elements of sought consecutive record of the progressions.\n\nLet us remind you that a finite sequence $c$ is called an arithmetic progression if the difference $c_{i + 1} - c_{i}$ of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.",
    "tutorial": "One thing to notice for this problem is that if we cover some interval with a progression then it will better (at least no worse) to include as many elements to the right of it as possible. So the solution is to greedy - find the leftmost number not covered by a progression, start a new progression with that number (the interval covered by that progression will be of size 1) and then try to extend this interval to the right as far as possible. Repeat this step until all the numbers are covered. One thing you should pay attention to is which numbers can be covered by one arithmetic progression, for example: If there are no fixed numbers in the interval then we can cover it with one progression. If there is only one non-fixed number in the interval then we can cover this interval with one progression. If there are more than one non-fixed numbers in the interval then we can calculate the parameters of the progression (start value and difference). All non-fixed numbers should match those parameters. Difference should be integer. If the progression is ascending and there are some non-fixed numbers in the beginning then those numbers should match positive numbers in the progression. Same way if the progression is descending then we can include numbers from the right side only while matching progression term is positive.",
    "code": "#include <iostream>\n#include <vector>\n \n#define FOR(i, a, b) for(int i = a; i < b ; ++i)\n#define FORD(i, a, b) for(int i = a; i >= b; --i)\n \nusing namespace std;\n \ntemplate <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }\n \nint main() {\n\tint n; cin >> n;\n\tauto a = readVector<long long>(n);\n\t\n\tint res = 0;\n\tfor (int l = 0 ; l < n ; ) {\n\t\tres++;\n \n\t\tint i1 = l;\n\t\twhile (i1 < n && a[i1] == -1) i1++;\n\t\t\n\t\tif (i1 == n) break; // there are no more fixed elements\n\t\t\n\t\tint i2 = i1 + 1;\n\t\twhile (i2 < n && a[i2] == -1) i2++;\n\t\t\n\t\tif (i2 == n) break; // there is only one fixed element\n\t\t\n\t\tint dist = i2 - i1;\n\t\tif ((a[i2] - a[i1]) % dist) {\n\t\t\tl = i2;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tauto step = (a[i2] - a[i1]) / dist;\n\t\tif (step > 0 && a[i1] - step * (i1 - l) <= 0) {\n\t\t\tl = i2;\n\t\t\tcontinue;\n\t\t}\n \n\t\tint r = i2 + 1;\n\t\twhile (r < n) {\n\t\t\tauto expectedValue = a[i2] + step * (r - i2);\n\t\t\t\n\t\t\tif (a[r] != -1 && a[r] != expectedValue) break;\n\t\t\tif (expectedValue <= 0) break;\n\t\t\tr++;\n\t\t}\n\t\tl = r;\n\t}\n\t\n\tcout << res;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "416",
    "index": "E",
    "title": "President's Path",
    "statement": "Good old Berland has $n$ cities and $m$ roads. Each road connects a pair of distinct cities and is bidirectional. Between any pair of cities, there is at most one road. For each road, we know its length.\n\nWe also know that the President will soon ride along the Berland roads from city $s$ to city $t$. Naturally, he will choose one of the shortest paths from $s$ to $t$, but nobody can say for sure which path he will choose.\n\nThe Minister for Transport is really afraid that the President might get upset by the state of the roads in the country. That is the reason he is planning to repair the roads in the possible President's path.\n\nMaking the budget for such an event is not an easy task. For all possible distinct pairs $s, t$ ($s < t$) find the number of roads that lie on at least one shortest path from $s$ to $t$.",
    "tutorial": "Let's look at the graph given to us in the example: We need to count the count of the edges on all the shortest paths between each pair of vertices. Let's do something easier first - instead of counting all the edges we will count only those which have the destination vertex on its side. For example here are the edges belonging to shortest paths from 4 to 2 which are connected to vertex 2: Let's denote this number like this: $inEdges_{source, v}$ - number of edges which go into vertex $v$ on some shortest path from $source$ to $v$. In the given example $inEdges_{4, 2} = 3$. Let's also denote the set $S_{source, dest}$ - it is a set of the vertices which belong to at least one shortest path from $source$ to $dest$. For example $S_{4, 2} = {1, 2, 3, 4}$. With these two variables it can be seen that the answer for vertices $source$ and $dest$ will be: $e d g e s_{s,d}=\\sum_{v\\in S_{s,d}}i n E d g e s_{s,v}$ In other words the answer for vertices $s$ and $d$ will be equal to the sum of $inEdges_{s, v}$ for all vertices $v$, which belong to any shortest path from $s$ to $d$. So the only thing left is to calculate these $S$ and $inEdges$. Both of them can be easily calculated if you have minimum distances between all pairs of vertices. And these distances can be calculated using the Floyd-Warshall. So the full solution is: Calculate minimum distances between all pairs of vertices using Floyd-Warshall algorithm. Count $inEdges$. Simply iterate over all source vertices and all edges. For each edge check whether any of its ends belong to any shortest path from source. Calculate the answer. Let's have three loops to iterate over the vertices - - $source$, $destination$ and $mid$. First two vertices are those for which we're calculating the answer. Third vertex is the vertex which should belong to any shortest path (basically we're checking whether $v$ belongs to $S_{source, dest}$). If $mid$ belongs to any shortest path from $source$ to $dest$ then we add $inEdges_{source, mid}$ to the answer. Each step has a complexity $O(n^{3})$.",
    "code": "#include <iostream>\n#include <vector>\n \nint IntMaxVal = (int) 1e20;\n \n#define minimize(a, b) { a = min(a, b); }\n \nusing namespace std;\n \ntemplate <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }\n \nconst int MAXN = 500;\n \nvector<int> allVertices; // helper array to iterate all vertices\nint allMinDist[MAXN + 1][MAXN + 1];\n \nclass cEdge {\n\tpublic:\n\t\n\tint v1;\n\tint v2;\n\tint len;\n};\n \nistream& operator >>(istream& is, cEdge &e) { is >> e.v1 >> e.v2 >> e.len; return is; }\n \nvoid FloydWarshall(vector<cEdge> &edges) {\n\tfor (auto v1 : allVertices) for (auto v2 : allVertices) allMinDist[v1][v2] = IntMaxVal;\n\tfor (auto v : allVertices) allMinDist[v][v] = 0;\n\t\n\tfor (auto &edge : edges) {\n\t\tallMinDist[edge.v1][edge.v2] = allMinDist[edge.v2][edge.v1] = edge.len;\n\t}\n\t\t\n\tfor (auto v3 : allVertices) for (auto v1 : allVertices) for (auto v2 : allVertices) {\n\t\tif (allMinDist[v1][v3] != IntMaxVal && allMinDist[v3][v2] != IntMaxVal) {\n\t\t\tminimize(allMinDist[v1][v2], allMinDist[v1][v3] + allMinDist[v3][v2]);\n\t\t\tallMinDist[v2][v1] = allMinDist[v1][v2];\n\t\t}\n\t}\n}\n \nint main() {\n\tint n; cin >> n;\n\tint m; cin >> m;\n\t\n\tfor (int i = 0 ; i < n ; i++) allVertices.push_back(i + 1);\n\t\n\tauto edges = readVector<cEdge>(m);\n \n\tFloydWarshall(edges);\n \n\tint inEdges[n + 1][n + 1];\n\tfor (auto v1 : allVertices) for (auto v2 : allVertices) inEdges[v1][v2] = 0;\n\t\n\tfor (auto &edge : edges) {\n\t\tfor (auto v : allVertices) {\n\t\t\tif (allMinDist[v][edge.v1] + edge.len == allMinDist[v][edge.v2]) inEdges[v][edge.v2]++;\n\t\t\tif (allMinDist[v][edge.v2] + edge.len == allMinDist[v][edge.v1]) inEdges[v][edge.v1]++;\n\t\t}\n\t}\n\t\t\t\t\t\t\t\n\tfor (auto source : allVertices) {\n\t\tfor (int j = source + 1 ; j <= n ; j++) {\n\t\t\tint count = 0;\n\t\t\tfor (auto mid : allVertices) {\n\t\t\t\tif (allMinDist[source][mid] + allMinDist[mid][j] == allMinDist[source][j]) count += inEdges[source][mid];\n\t\t\t}\n\t\t\tcout << count << ' ';\n\t\t}\n\t}\n}",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2500
  },
  {
    "contest_id": "417",
    "index": "A",
    "title": "Elimination",
    "statement": "The finalists of the \"Russian Code Cup\" competition in 2214 will be the participants who win in one of the elimination rounds.\n\nThe elimination rounds are divided into main and additional. Each of the main elimination rounds consists of $c$ problems, the winners of the round are the first $n$ people in the rating list. Each of the additional elimination rounds consists of $d$ problems. The winner of the additional round is one person. Besides, $k$ winners of the past finals are invited to the finals without elimination.\n\nAs a result of all elimination rounds at least $n·m$ people should go to the finals. You need to organize elimination rounds in such a way, that at least $n·m$ people go to the finals, and the total amount of used problems in all rounds is as small as possible.",
    "tutorial": "The first thing, that you need to mention, is that if $k  \\le  n \\cdot m$, then the answer is equal to 0. After that you need to take at least $n \\cdot m - k$ people. There's three possibilities to do that: Also in this problem it is possible to write the solution, which check every possible combinations of the numbers of main and elimination rounds.",
    "tags": [
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "417",
    "index": "B",
    "title": "Crash",
    "statement": "During the \"Russian Code Cup\" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.\n\nEach participant is identified by some unique positive integer $k$, and each sent solution $A$ is characterized by two numbers: $x$ — the number of different solutions that are sent before the first solution identical to $A$, and $k$ — the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same $x$.\n\nIt is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number $x$ $(x > 0)$ of the participant with number $k$, then the testing system has a solution with number $x - 1$ of the same participant stored somewhere before.\n\nDuring the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.",
    "tutorial": "Let us create array $a$ with $10^{5}$ elements, which is filled with $- 1$. In the cell $a[k]$ we will contain the maximal number of the submissions of the participant with identifier $k$. We will process submissions in the given order. Let us process submission $x$ $k$. If $a[k] < x - 1$, then the answer is NO, else we will update array $a$: $a[k] = max(a[k], x)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "417",
    "index": "C",
    "title": "Football",
    "statement": "One day, at the \"Russian Code Cup\" event it was decided to play football as an out of competition event. All participants was divided into $n$ teams and played several matches, two teams could not play against each other more than once.\n\nThe appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.\n\nPavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly $k$ times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.",
    "tutorial": "Let's consider this tournir as graph. Each vertex should have out-degree $k$. Then the graph should contain exactly $nk$ edges. But the full-graph contains $\\textstyle{\\frac{n(n-1)}{2}}$, because of that if $n < 2k + 1$ then the answer is $- 1$, otherwise we will connect the $i$-th vertex with $i + 1, ..., i + k$, taking modulo $n$ if needed.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "417",
    "index": "D",
    "title": "Cunning Gena",
    "statement": "A boy named Gena really wants to get to the \"Russian Code Cup\" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his $n$ friends that they will solve the problems for him.\n\nThe participants are offered $m$ problems on the contest. For each friend, Gena knows what problems he can solve. But Gena's friends won't agree to help Gena for nothing: the $i$-th friend asks Gena $x_{i}$ rubles for his help \\textbf{in solving all the problems} he can. Also, the friend agreed to write a code for Gena only if Gena's computer is connected to at least $k_{i}$ monitors, each monitor costs $b$ rubles.\n\nGena is careful with money, so he wants to spend as little money as possible to solve all the problems. Help Gena, tell him how to spend the smallest possible amount of money. Initially, there's no monitors connected to Gena's computer.",
    "tutorial": "Let us sort the friends by the number of the monitors in the increasing order. Afterwards we will calculate the dp on the masks: the minimal amount of money Gena should spend to solve some subset of problems, if we take first $n$ friends. Then the answer we should compare with the answer for first $i$ friends plus the number of the monitors, which the $i$-th friend needs. Is is not hard to see, that if we consider the friends in this order consequently, then we can recalc dp like in the knapsack problem. The running time of this algorithm is $O(nlog(n) + n2^{m})$.",
    "tags": [
      "bitmasks",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "417",
    "index": "E",
    "title": "Square Table",
    "statement": "While resting on the ship after the \"Russian Code Cup\" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size $n × m$, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.\n\nSince checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed $10^{8}$.",
    "tutorial": "Let's build array of the length $n$ for each $n$, that the sum of the squares of its elements is the square: We are given two numbers $n$ and $m$. Let array $a$ corresponds to $n$, and array $b$ corresponds to $m$. The we will build the answer array $c$ as follows $c_{ij} = a_{i} \\cdot b_{j}$.",
    "tags": [
      "constructive algorithms",
      "math",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "418",
    "index": "D",
    "title": "Big Problems for Organizers",
    "statement": "The Finals of the \"Russian Code Cup\" 2214 will be held in $n$ hotels. Two hotels (let's assume that they are the main hotels), will host all sorts of events, and the remaining hotels will accommodate the participants. The hotels are connected by $n - 1$ roads, you can get from any hotel to any other one.\n\nThe organizers wonder what is the minimum time all the participants need to get to the main hotels, if each participant goes to the main hotel that is nearest to him and moving between two hotels connected by a road takes one unit of time.\n\nThe hosts consider various options for the location of the main hotels. For each option help the organizers to find minimal time.",
    "tutorial": "This problem has two solutions. The first one. Let's hang the tree on some vertex. Afterwards, let us calculate for eah vertex it's height and $3$ most distant vertices in its subtree. Also let's calculate arrays for the lowest common ancestors problem. For each vertex $i$ and the power of two $2^{j}$ we have $p[i][j]$, $up[i][j]$ and $down[i][j]$: And the last part of this solution. Let us be given the query $u$ $v$. Firstly, we find $w = LCA(u, v)$. Afterwards, we need to find vertex $hu$, which is situated on the middle of the path between $u$ and $v$. Really, we need to split the tree by this vertex, count the longest path from $u$ in its tree and count the longest path from $v$ in its tree. If we can imagine in the main tree, we can not delete this vertex, but with our precalculated arrays recalc this two values. First solution: 6396376 The second solution. In a few words. Let's find the diameter of the tree. Precalc the answer for each vertices on the prefix. Then on the query we find two distant vertices on this diameter and the path. Obviously, diameter should contain the middle of the path, when we find it, using precalculated results on the prefixes and suffixes we can obtain the answer.",
    "tags": [
      "data structures",
      "graphs",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "418",
    "index": "E",
    "title": "Tricky Password",
    "statement": "In order to ensure confidentiality, the access to the \"Russian Code Cup\" problems is password protected during the problem development process.\n\nTo select a password, the jury can generate a special table that contains $n$ columns and the infinite number of rows. To construct a table, the first row is fixed, and all the others are obtained by the following rule:\n\nIn the row $i$ at position $p$ there is a number equal to the number of times $a[i - 1][p]$ occurs on the prefix $a[i - 1][1... p]$.\n\nTo ensure the required level of confidentiality, the jury must be able to perform the following operations:\n\n- Replace number $a[1][p]$ by $v$ and rebuild the table.\n- Find the number $a[x][y]$, which will be the new password.\n\nDoing all these steps manually is very tedious, so the jury asks you to help him. Write a program that responds to the request of the jury.",
    "tutorial": "The key theoretical idea of this problem is that the $2$nd row is exactly the same as the $4$th row, $3$rd row is exactly the same as $5$th row and so on. Because of that we need only to answer queries on the first three rows. Let's move on to the practical part. In the first place we will compress coordinates, that any value will not exceed $2 \\cdot 10^{5}$. Afterwards, let's split the array into parts of the length $LEN$. On each part we will calculate the following values: $cnt[k]$ - the number of occurences of the number $k$ on this prefix, also $f[k]$ - the total number of the values, which occur exactly $k$ times on this prefix. Array $f$ we will store in the Fenwick data structure. It is not hard to see, that array $cnt$ contains the answer for the queries to the $2$nd row. To get the answer for the queries to the 3$rd$ row we need to calculate $f[cnt[k]... 10^{5}]$. Also it's quite understandable how to recalc this dp. In summary, we will get $O(\\frac{n o g(n)}{L E N}+L E N)$ per query. And we take $L E N={\\sqrt{n l o g(n)}}$, then we will get $O({\\sqrt{n l o g(n)}})$ per query.",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "420",
    "index": "A",
    "title": "Start Up",
    "statement": "Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?\n\nThe market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.\n\nThere are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.",
    "tutorial": "One should firstly recognize that the required string should be palindrome and each character of the string should be symmetric. All the symmetric characters are - $AHIMOTUVWXY$.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "420",
    "index": "B",
    "title": "Online Meeting",
    "statement": "Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat.\n\nOne day the director of the F company got hold of the records of a part of an online meeting of one successful team. The director watched the record and wanted to talk to the team leader. But how can he tell who the leader is? The director logically supposed that the leader is the person who is present at any conversation during a chat meeting. In other words, if at some moment of time at least one person is present on the meeting, then the leader is present on the meeting.\n\nYou are the assistant director. Given the 'user logged on'/'user logged off' messages of the meeting in the chronological order, help the director determine who can be the leader. Note that the director has the record of only a continuous part of the meeting (probably, it's not the whole meeting).",
    "tutorial": "Firstly lets add to the answer all the persons, that didn't appear in the log messages. Then we should consider two cases: 1) If there is a person (with number $i$), that the first log message with him is in form $- i$. We will call such persons X-persons. Consider all X-persons. Pick the one from them that has the last first occurrence in the sequence of messages. This person can be a leader, all others cannot be. Now we should check if the picked person is a leader or not. For that reason we will use the algorithm that is described below. This algorithm works fine only on special sequences of messages. So, we need to add all the X-persons to the beginning of the our list in the order they appear in input (in the resulting sequence the picked person should be the first). 2) There is no X-persons. That case only the first person from the list can be a leader. Others cannot be. Check that person with the algorithm described below. The Algorithm of check: The algorithm is very simple. Just to iterate throughout the sequence of messages and maintain $set$-structure for the persons that are currently on the meeting. If we consider log-on message, add the person to the set, if we consider log-off message, erase the person from the set. Each time we perform an operation with set, we should check: either the set is empty or the leader is in set. The most tricky cases are 33 and 34. Will look at them, the 33-th test: 4 4 + 2 - 1 - 3 - 2 Here the leader can be only 4-th person. Others cannot be. The 34-th test: 3 3 - 2 + 1 + 2 The answer for that test is only the 3-rd participant.",
    "tags": [
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "420",
    "index": "C",
    "title": "Bug in Code",
    "statement": "Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the $n$ coders on the meeting said: 'I know for sure that either $x$ or $y$ did it!'\n\nThe head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least $p$ of $n$ coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects?\n\nNote that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting.",
    "tutorial": "Lets construct an undirected graph, the vertices of the graph are the persons, there is an edge between two persons if there are claim of some person about these two persons. Now we can describe the problem on this graph. We need to find the number of such pairs of vertices that at least $p$ edges are adjacent to them. How to count such pairs. Just for each vertex $v$ to calculate the number of vertices $u$ such that $d[v] + d[u]  \\ge  p$, then we should consider all the adjacent vertices correctly. Iterate through all the edges and subtract such the vertices from the answer. Then iterate through adjacent vertices and add only such of them that is needed to be added. Pay attention to multiple edges, they should be considered very carefully.",
    "tags": [
      "data structures",
      "graphs",
      "implementation",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "420",
    "index": "D",
    "title": "Cup Trick",
    "statement": "The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.\n\nThe point is to trick the spectator's attention. Initially, the spectator stands in front of a line of $n$ plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.\n\nBut the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:\n\n- each cup contains a mark — a number from $1$ to $n$; all marks on the cups are distinct;\n- the magician shuffles the cups in $m$ operations, each operation looks like that: take a cup marked $x_{i}$, sitting at position $y_{i}$ in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).\n\nWhen the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.",
    "tutorial": "The solution consists of two parts. 1) Find the valid permutation. Let's go through the given queries. Suppose the current query tells us that the number $a$ is placed on $b$-th position. If we already met $a$ then we are going to skip this query. Otherwise let's find the position of $a$ in the sought permutation. Suppose we already know that in the sought permutation the number $a_{1}$ is on position $b_{1}$, $a_{2}$ is on position $b_{2}$, $...$, $a_{k}$ is on position $b_{k}$ $(b_{1} < b_{2} < ... < b_{k})$. After every query the number from that query goes to the begging of the permutation, so all $a_{i}$ $(1  \\le  i  \\le  k)$ are already placed to the left of $a$ before the current query. But some of these $a_{i}$ stood to the left of $a$ in the sought permutation, and the other stood to the right of $a$, but went forward to the begging. Let's find the number of these numbers. In order to do this we should find such position $p$, that is not occupied by any of $a_{i}$ and $p + x = b$, where $x$ is the number of such $b_{i}$ that $b_{i} > p$. We can do it by using the segment tree in the following manner. Let's store in the vertex of segment tree the number of already occupied positions on the correspond subsegment. Suppose we want to find $p$ in the some subtree. Let's find the minimal position in the right subtree $p_{rg}$ and the number of occupied positions $x_{rg}$ there. So if $p_{rg} + x_{rg}  \\le  b$ then we should continue finding $p$ in the right subtree. Otherwise we should decrease $b$ by $x_{rg}$ and try to find $p$ in the left subtree. When we find $p$ we need to check that $p + x = b$. If this equation isn't correct then the answer is $- 1$. 2) Check that the sequence of the operations is correct. Let's consider $i$-th query. Suppose it tells us that $a$ is placed on position $b$. We should check whether it is correct. If we haven't already seen $a$ in queries then this statement is correct because we checked it in the first part of the solution. Otherwise, let's find the such maximal $j < i$ that it is given the position of $a$ in $j$-th query. After $j$-th query $a$ goes to the begging of the permutation and the other numbers can move it to the right. Let's find the number of such different numbers on the queries' segment $[j + 1, i - 1]$. We should get exactly $b - 1$.",
    "tags": [
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "420",
    "index": "E",
    "title": "Playing the ball",
    "statement": "A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game.\n\nLet's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who chooses an arbitrary direction and throws a ball in that direction. The ball hits the plane at distance $d$ from the player's original position and continues flying in the same direction. After the ball hits the plane for the first time, it flies on and hits the plane again at distance $2·d$ from the player's original position and so on (it continue flying in the chosen direction and hitting the plane after each $d$ units). All coders in the F company are strong, so the ball flies infinitely far away.\n\nThe plane has $n$ circles painted on it. If a ball hits the plane and hits a circle that is painted on the plane (including its border), then the player gets one point. The ball can hit multiple circles at once and get one point for each of them (if the ball hits some circle $x$ times during the move, the player also gets $x$ points). Count the maximum number of points a player can get if he throws a ball in the arbitrary direction. Note that the direction may have real cooridinates.",
    "tutorial": "Let's claim that we have ray and the infinite number of balls on it in this problem. The $k$-th ball is placed on the distance $k \\cdot d$ from the begging of the ray. Let's note that in the answer must be the ball which is placed on the border of some cirlce. The second observation is the following. Let's consider any circle. The number of angles, on which we can rotate our ray so that any ball will be on the border of this cirlce, doesn't exceed $4 * r / d$. Let's call these angles critical. Let's put all critical angles from each circle to the array $B$ and sort. After that let's consider every cirlce one-by-one. When we consider some cirlce we are going to find all critical angles and sort them. So the number of balls, which will be inside of the cirlce, will be the constant if we rotate our ray on every angle between the two neighbour critical angles. Let's find $k$ - the number of these balls. Let's create array $C$, where $C_{i}$ is the answer value if we rotate the ray on the angle $B_{i}$. So after we find $k$ and the positions of neighbour critical angles in $B$ we need to perform add on the segment query in $C$. After we processed all critical angles of all circles the maximum in the $C$ will be the answer.",
    "tags": [
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "421",
    "index": "A",
    "title": "Pasha and Hamsters",
    "statement": "Pasha has two hamsters: Arthur and Alexander. Pasha put $n$ apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hamsters on his own. He is going to give some apples to Arthur and some apples to Alexander. It doesn't matter how many apples each hamster gets but it is important that each hamster gets only the apples he likes. It is possible that somebody doesn't get any apples.\n\nHelp Pasha distribute all the apples between the hamsters. Note that Pasha wants to distribute all the apples, not just some of them.",
    "tutorial": "For each apple you just need to determine who like it. If Alexander likes apple, then he should eat it, if Artur likes the apple, then he should eat it. If they both like the apply anyone can eat the apple.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "424",
    "index": "A",
    "title": "Squats",
    "statement": "Pasha has many hamsters and he makes them work out. Today, $n$ hamsters ($n$ is even) came to work out. The hamsters lined up and each hamster either sat down or stood up.\n\nFor another exercise, Pasha needs exactly $\\frac{n t}{2}$ hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make some hamster ether sit down or stand up. How many minutes will he need to get what he wants if he acts optimally well?",
    "tutorial": "The problem is to find the number of standing hamsters. If it is less than half, we should make the required number of hamsters standing. Otherwise we should make some hamsters sitting.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "424",
    "index": "B",
    "title": "Megacity",
    "statement": "The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.\n\nThe city of Tomsk can be represented as point on the plane with coordinates ($0$; $0$). The city is surrounded with $n$ other locations, the $i$-th one has coordinates ($x_{i}$, $y_{i}$) with the population of $k_{i}$ people. You can widen the city boundaries to a circle of radius $r$. In such case all locations inside the circle and on its border are included into the city.\n\nYour goal is to write a program that will determine the minimum radius $r$, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.",
    "tutorial": "We can sort all the cities by their distance to the Tomsk city $d_{i}$. After that we are to find the smallest index $t$ for which the total population $p_{0} + p_{1} + ... + p_{t} > = 10^{6}$. In such case the answer is $d_{t}$. We can sort all cities in $O(NlogN)$ and find the value of $t$ in $O(N)$. Limits for $N$ allow $O(N^{2})$ sorting or any other $O(N^{2})$ solution.",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "424",
    "index": "C",
    "title": "Magic Formulas",
    "statement": "People in the Tomskaya region like magic formulas very much. You can see some of them below.\n\nImagine you are given a sequence of positive integer numbers $p_{1}$, $p_{2}$, ..., $p_{n}$. Lets write down some magic formulas:\n\n\\[\nq_{i}=p_{i}\\oplus(i\\;m o d\\;1)\\oplus(i\\;m o d\\;2)\\oplus\\cdot\\cdot\\cdot\\oplus(i\\;m o d\\;n);\n\\]\n\n\\[\nQ=q_{1}\\oplus q_{2}\\oplus\\ldots\\oplus q_{n}.\n\\]\n\nHere, \"mod\" means the operation of taking the residue after dividing.\n\nThe expression $x\\oplus y$ means applying the bitwise $xor$ (excluding \"OR\") operation to integers $x$ and $y$. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by \"^\", in Pascal — by \"xor\".\n\nPeople in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence $p$, calculate the value of $Q$.",
    "tutorial": "Consider the following formulas: $\\ell_{i}=p_{i}\\varpi\\left(1\\;\\;\\mathrm{mod}\\;{\\dot{\\imath}}\\right)\\varpi\\left({\\dot{2}}\\;\\;\\mathrm{mod}\\;{\\dot{\\imath}}\\right)\\varpi\\cdot\\cdot\\cdot\\varpi\\left(\\eta\\;\\;\\mathrm{mod}\\;{\\dot{\\imath}}\\right)},$ $Q=\\mathbf{c}_{1}\\oplus\\mathbf{c}_{2}\\oplus\\cdot\\cdot\\oplus\\mathbf{c}_{n}.$ Let $f_{i}=0\\oplus1\\oplus\\ldots\\leftrightarrow i$. Lets compute the following function for each $i$ ($0  \\le  i  \\le  n$). One can do it in $O(n)$ using $f_{i}=f_{i-1}\\oplus i$. Lets transform $c_{i}$: $\\begin{array}{c}{{c_{i}=p_{i}\\oplus((1~~\\mathrm{mod}~i)\\oplus(2~\\mathrm{mod}~i)\\oplus\\cdot\\cdot\\cdot\\oplus\\left((i-1)~~\\mathrm{mod}~i\\right)\\oplus(i~~\\mathrm{mod}~i)\\oplus(i~~\\mathrm{mod}~i)\\right)\\oplus(i~~i)\\oplus(i~~i)\\times\\times\\oplus(n+1)~~\\mathrm{mod}~i)\\oplus(i~~i)}}\\\\ {{\\left(\\sinh i)}}&{{\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\quad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\quad\\quad\\langle\\phi\\times\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\in\\quad(n-1)}\\oplus(i)}}\\end{array}$ Also: $\\begin{array}{c}{{f_{i-1}=\\left((i+1)\\;\\;\\mathrm{mod}\\;i\\right)\\oplus\\left((i+2)\\;\\;\\mathrm{mod}\\;i\\right)\\oplus\\cdot\\cdot\\hat{\\Phi}\\left((2\\cdot i-1)\\;\\;\\mathrm{mod}\\;i\\right)\\oplus\\left(2\\cdot i.}}\\end{array}$ Thus: $c_{i}=p_{i}\\oplus f_{i-1}\\oplus f_{i-1}\\oplus\\ldots\\oplus f_{i-1}\\oplus f_{n}{\\mathrm{~mod~}}i$ That means, if $n / i$ is odd, $c_{i}=p_{i}\\oplus f_{i-1}\\oplus f_{n}{\\mathrm{~mod~}}i$, otherwise - $c_{i}=p_{i}\\oplus f_{n{\\mathrm{~mod}}}\\,i$. $c_{i}$ can be computed in $O(1)$, that's why the complexity of the whole solution - $O(n)$.",
    "tags": [
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "424",
    "index": "D",
    "title": "Biathlon Track",
    "statement": "Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built.\n\nTo construct a biathlon track a plot of land was allocated, which is a rectangle divided into $n × m$ identical squares. Each of the squares has two coordinates: the number of the row (from 1 to $n$), where it is located, the number of the column (from 1 to $m$), where it is located. Also each of the squares is characterized by its height. During the sports the biathletes will have to move from one square to another. If a biathlete moves from a higher square to a lower one, he makes a descent. If a biathlete moves from a lower square to a higher one, he makes an ascent. If a biathlete moves between two squares with the same height, then he moves on flat ground.\n\nThe biathlon track should be a border of some rectangular area of the allocated land on which biathletes will move in the clockwise direction. It is known that on one move on flat ground an average biathlete spends $t_{p}$ seconds, an ascent takes $t_{u}$ seconds, a descent takes $t_{d}$ seconds. The Tomsk Administration wants to choose the route so that the average biathlete passes it in as close to $t$ seconds as possible. In other words, the difference between time $t_{s}$ of passing the selected track and $t$ should be minimum.\n\nFor a better understanding you can look at the first sample of the input data. In this sample $n = 6, m = 7$, and the administration wants the track covering time to be as close to $t = 48$ seconds as possible, also, $t_{p} = 3$, $t_{u} = 6$ and $t_{d} = 2$. If we consider the rectangle shown on the image by arrows, the average biathlete can move along the boundary in a clockwise direction in exactly $48$ seconds. The upper left corner of this track is located in the square with the row number $4$, column number $3$ and the lower right corner is at square with row number $6$, column number $7$.\n\nAmong other things the administration wants all sides of the rectangle which boundaries will be the biathlon track to consist of no less than three squares and to be completely contained within the selected land.\n\nYou are given the description of the given plot of land and all necessary time values. You are to write the program to find the most suitable rectangle for a biathlon track. If there are several such rectangles, you are allowed to print any of them.",
    "tutorial": "Due to the time limit for Java some of $O(N^{4})$ solution got Accepted. The authors solution has complexity $O(N^{3} \\cdot logN)$. The main idea is to fix the top-border and bottom-border. Then, using some abstract data type, for each right-border we can find the most suitable left-border in $O(logN)$ time. For example we can use set in C++ and its method lower_bound. For better understanding lets have a look at the following figure: For such rectangle we fix the upper-border as row number $2$ and bottom-border as row number $5$. Also, we fix right-border as column number $6$, and now we are to find some left-border. Now we can split the time value for any rectangle for two summands. One of them depends only on left-border and another one - on the right-border. With the blue color the summand that depends only on the right-border is highlighted. With the red and yellow color - the other summand is highlighted. The red-colored value should be subtracted and the yellow-colored should be added. For any blue right-border's value we are to find the closest red-yellow left-border. That is the problem to be solved with the help of STL Set or any other similar abstract data type.",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "data structures",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "424",
    "index": "E",
    "title": "Colored Jenga",
    "statement": "Cold winter evenings in Tomsk are very boring — nobody wants be on the streets at such a time. Residents of Tomsk while away the time sitting in warm apartments, inventing a lot of different games. One of such games is 'Colored Jenga'.\n\nThis game requires wooden blocks of three colors: red, green and blue. A tower of $n$ levels is made from them. Each level consists of three wooden blocks. The blocks in each level can be of arbitrary colors, but they are always located close and parallel to each other. An example of such a tower is shown in the figure.\n\nThe game is played by exactly one person. Every minute a player throws a special dice which has six sides. Two sides of the dice are green, two are blue, one is red and one is black. The dice shows each side equiprobably.\n\nIf the dice shows red, green or blue, the player must take any block of this color out of the tower at this minute so that the tower doesn't fall. If this is not possible, the player waits until the end of the minute, without touching the tower. He also has to wait until the end of the minute without touching the tower if the dice shows the black side. \\textbf{It is not allowed to take blocks from the top level of the tower (whether it is completed or not)}.\n\nOnce a player got a block out, he must put it on the top of the tower so as to form a new level or finish the upper level consisting of previously placed blocks. The newly constructed levels should have all the same properties as the initial levels. \\textbf{If the upper level is not completed, starting the new level is prohibited}.\n\nFor the tower not to fall, in each of the levels except for the top, there should be at least one block. Moreover, if at some of these levels there is exactly one block left and this block is not the middle block, the tower falls.\n\nThe game ends at the moment when there is no block in the tower that you can take out so that the tower doesn't fall.\n\nHere is a wonderful game invented by the residents of the city of Tomsk. I wonder for how many minutes can the game last if the player acts optimally well? If a player acts optimally well, then at any moment he tries to choose the block he takes out so as to minimize the expected number of the game duration.\n\nYour task is to write a program that determines the expected number of the desired amount of minutes.",
    "tutorial": "A classical DP-problem on finding expected number. Lets define some function $F(S)$ for some state - the expected number of minutes to finish the game from this state. For each color we can compute the probability of showing this color by the simple formula $\\frac{C}{6}$, where $c$ - the number of dice's faces of this color. Now we are to find the probability $P_{L}$ to stay in this state for the next minutes. That is the probabilty of showing black color plus the probabilities of showing colors with no blocks of that color to be removed from the tower. Now we can find the value via the following formula: $F(S)={\\frac{1+P_{R}\\,F_{m i n}(S/R)+P_{G}\\!\\cdot\\!F_{m i n}(S/G)+P_{B}\\!\\cdot\\!F_{m i n}(S/B)}{1-P_{L}}}$ The only problem is to find how to encode the state. To reduce the number of states we can assume that there is only $18$ different type of levels, but not $27$. For better time-performance it is better to use hashing. The solution for this problem requires good understanding of DP and quite good implementing skills.",
    "tags": [
      "dfs and similar",
      "dp",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "425",
    "index": "A",
    "title": "Sereja and Swaps",
    "statement": "As usual, Sereja has array $a$, its elements are integers: $a[1], a[2], ..., a[n]$. Let's introduce notation:\n\n\\[\nf(a,l,r)=\\sum_{i=l}^{r}a[i];\\;m(a)=\\operatorname*{max}_{1\\leq l\\leq r\\leq n}f(a,l,r).\n\\]\n\nA swap operation is the following sequence of actions:\n\n- choose two indexes $i, j$ $(i ≠ j)$;\n- perform assignments $tmp = a[i], a[i] = a[j], a[j] = tmp$.\n\nWhat maximum value of function $m(a)$ can Sereja get if he is allowed to perform at most $k$ swap operations?",
    "tutorial": "Lets backtrack interval on which will contain maximal sum. To improve our sum we can swap not more then $k$ minimal elements from the interval to $k$ maximal elements that don't belong to interval. As $n$ isn't big we can do it in any way. Author solution sort all elemets from interval in increasing order and all elements that don't belong to interval by descreasing order. We will swap elements one by one while we haven't done $k$ swaps and we have some unswaped elements in first set and we have some unswaped elemets in second set and swap is optimal(we will optimize the answer after this swap). Author solution works in time $O(n^{3} \\cdot log(n))$.",
    "tags": [
      "brute force",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "425",
    "index": "B",
    "title": "Sereja and Table ",
    "statement": "Sereja has an $n × m$ rectangular table $a$, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size $h × w$, then the component must contain exactly $hw$ cells.\n\nA connected component of the same values is a set of cells of the table that meet the following conditions:\n\n- every two cells of the set have the same value;\n- the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table);\n- it is impossible to add any cell to the set unless we violate the two previous conditions.\n\nCan Sereja change the values of at most $k$ cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?",
    "tutorial": "Note, that if we have two arrays $x[1..n], 0  \\le  x_{i}  \\le  1$ and $y[1..m], 0  \\le  y_{i}  \\le  1$, then described matrix can be showed as next one: $a_{i, j} = x_{i} xor y_{j}$. If $n  \\le  k$, then we can backtrack array $x$ and using greedy find best $y$. Otherwise there will be atleast one $i$, such that we will not change any cell in row number $i$. So we can simply bruteforce some row and use it like $x$. Then we use greedy and find $y$. From all possible rows we choose most optimal. Such row will be as number of mistakes is lower then number of rows, so it isn't possible to have atleast one mistake in each row. Greedy means next algorithm: for every element of $y$ we will look, will it be better to choose it like $0$ or $1$. To find better choise, we will count number of different bits in $x$ and current(lets it be $j$) column. If number of different if lower then count of same cells we will set $y_{j} = 0$, otherwise $y_{j} = 1$.",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "425",
    "index": "C",
    "title": "Sereja and Two Sequences",
    "statement": "Sereja has two sequences $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{m}$, consisting of integers. One day Sereja got bored and he decided two play with them. The rules of the game was very simple. Sereja makes several moves, in one move he can perform one of the following actions:\n\n- Choose several (at least one) first elements of sequence $a$ (non-empty prefix of $a$), choose several (at least one) first elements of sequence $b$ (non-empty prefix of $b$); the element of sequence $a$ with the maximum index among the chosen ones must be equal to the element of sequence $b$ with the maximum index among the chosen ones; remove the chosen elements from the sequences.\n- Remove all elements of both sequences.\n\nThe first action is worth $e$ energy units and adds one dollar to Sereja's electronic account. The second action is worth the number of energy units equal to the number of elements Sereja removed from the sequences before performing this action. After Sereja performed the second action, he gets all the money that he earned on his electronic account during the game.\n\nInitially Sereja has $s$ energy units and no money on his account. What maximum number of money can Sereja get? Note, the amount of Seraja's energy mustn't be negative at any time moment.",
    "tutorial": "In thgis problem we will use dynamic programming: $dp_{i, j}$ - minimal pozition of deleted element in second array, such that we have made first operation $j$ times and have deleted not more then $i$ elements from first array. Lets decided how to calculate transfers. Standing in pozition $dp_{i, j}$ we can change nothing and go to pozition $dp_{i + 1, j}$, by other words make transfer $dp_{i + 1, j}: = min(dp_{i + 1, j}, dp_{i, j})$. What happens when we make first operation with fixed prefix(by $i$-th element) in first array? We should find element in second array with number greater $dp_{i, j}$ and value equal to $a_{i}$, lets its pozition is $t$, so we need to make transfer $dp_{i + 1, j + 1}: = min(dp_{i + 1, j + 1}, t)$. How to find required element quickly: lets just do vector of pozition in second array for all different elements that contains in second array. Then we can simply use binary search.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "425",
    "index": "D",
    "title": "Sereja and Squares",
    "statement": "Sereja has painted $n$ distinct points on the plane. The coordinates of each point are integers. Now he is wondering: how many squares are there with sides parallel to the coordinate axes and with points painted in all its four vertexes? Help him, calculate this number.",
    "tutorial": "Lets line $x = k$ contain not more then $\\sqrt{n}$ points. Then for each pair of points on this line (lets it be $(k, y_{1})$ and $(k, y_{2})$) check: is there squere that contain them as vertexes. So we should check: is there(in input) pair of points $(k - |y_{2} - y_{1}|, y_{1})$ and $(k - |y_{2} - y_{1}|, y_{2})$, or pair $(k + |y_{2} - y_{1}|, y_{1})$ and $(k + |y_{2} - y_{1}|, y_{2})$. Lets delete all watched points, and reverse points about line $x = y$. Then each line $x = k$ will contain not more then $\\sqrt{n}$ points. Will solve problem in the same way. Now we should learn: how to check is some pair of points(on one vertical line) in input. Lets write all of this pairs in vectors. Each vector(for every line) will contain pairs that we should check on it. Suppose, that we check it for line number $k$. Lets mark in some array $u$ for all points with x-coordinate equal to $k$ $u_{y} = k$. Now to check is our pair with y-coordinates $(y_{1}, y_{2})$ on line we can simply check following condition: $u_{y1} = u_{y2} = k$.",
    "tags": [
      "binary search",
      "data structures",
      "hashing"
    ],
    "rating": 2300
  },
  {
    "contest_id": "425",
    "index": "E",
    "title": "Sereja and Sets",
    "statement": "Let's assume that set $S$ consists of $m$ distinct intervals $[l_{1}, r_{1}]$, $[l_{2}, r_{2}]$, $...$, $[l_{m}, r_{m}]$ ($1 ≤ l_{i} ≤ r_{i} ≤ n$; $l_{i}, r_{i}$ are integers).\n\nLet's assume that $f(S)$ is the maximum number of intervals that you can choose from the set $S$, such that every two of them do not intersect. We assume that two intervals, $[l_{1}, r_{1}]$ and $[l_{2}, r_{2}]$, intersect if there is an integer $x$, which meets two inequalities: $l_{1} ≤ x ≤ r_{1}$ and $l_{2} ≤ x ≤ r_{2}$.\n\nSereja wonders, how many sets $S$ are there, such that $f(S) = k$? Count this number modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "First, lets look at $F(S)$. First, we sort all intervals by second coordinte and then go by them in sorted order. And if current interval don't intersected with last taken to the optimal set, we get our current to the set. Our solution will be based on this greedy. Solution of the problem is next dynamic: 1). number of position of second coordinte of interval 2). number of intervals in good set 3). second coordinate of last taken interval to the optimal set How should we make transfers? Lets note that when we know $dp_{i, count, last}$ we can change $last$ by $i$, or not change at all. Lets look what happens in every case. In first case $last$ is changed by $i$, so we should take to optimal set atleast one of the inervals: $[last + 1, i]$, $[last + 2, i]$, ..., $[i, i]$, number of such intervals $i - last$, number of ways to get at least one of them is $2^{i - last} - 1$. All other intervals: $[1, i]$, $[2, i]$, ..., $[last, i]$ we could get as we wish, so we have $2^{last}$ ways. So total number of transfers from $dp_{i, count, last}$ to $dp_{i + 1, count + 1, i}$ is $(2^{i - last} - 1) \\cdot (2^{last})$. If we count number of transfers from $dp_{i, count, last}$ to $dp_{i + 1, count, last}$, we can simply use number $2^{last}$(as described early). Also we shouldn't forget about trivial case $dp_{i, 0, 0}$. So now we have quite easy solution.",
    "tags": [
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "426",
    "index": "A",
    "title": "Sereja and Mugs",
    "statement": "Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and $n$ water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that this player lost.\n\nAs soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has $(n - 1)$ friends. Determine if Sereja's friends can play the game so that nobody loses.",
    "tutorial": "Lets count the sum of all elements $Sum$ and value of the maximal element $M$. If $Sum - M  \\le  S$ then answer is yes, otherwise - no.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "426",
    "index": "B",
    "title": "Sereja and Mirroring",
    "statement": "Let's assume that we are given a matrix $b$ of size $x × y$, let's determine the operation of mirroring matrix $b$. The mirroring of matrix $b$ is a $2x × y$ matrix $c$ which has the following properties:\n\n- the upper half of matrix $c$ (rows with numbers from $1$ to $x$) exactly matches $b$;\n- the lower half of matrix $c$ (rows with numbers from $x + 1$ to $2x$) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows $x$ and $x + 1$).\n\nSereja has an $n × m$ matrix $a$. He wants to find such matrix $b$, that it can be transformed into matrix $a$, if we'll perform on it \\textbf{several} (possibly zero) mirrorings. What minimum number of rows can such matrix contain?",
    "tutorial": "Lets solve problem from another side. We will try to cut of matix as many times as we can. Cut means operation, reversed to operation described in statement. To check, can we cut matrix we need to check following conditions: 1). $n mod 2 = 0$ 2). $a_{i, j} = a_{n - i + 1, j}$ for all $1  \\le  i  \\le  n, 1  \\le  j  \\le  m$.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "427",
    "index": "A",
    "title": "Police Recruits",
    "statement": "The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.\n\nMeanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.\n\nIf there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.\n\nGiven the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.",
    "tutorial": "Maintain a variable, $sum$. Initially $sum$=0, it keeps the number of currently free police officers. With every recruitment operation, add the number of officers recruited at that time to $sum$. When a crime occurs, if $sum > 0$ then decrease the number of free officers by one, otherwise no officers are free so the crime will go untreated.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "427",
    "index": "B",
    "title": "Prison Transfer",
    "statement": "The prison of your city has $n$ prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer $c$ of the prisoners to a prison located in another city.\n\nFor this reason, he made the $n$ prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.\n\nThen, the mayor told you to choose the $c$ prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,\n\n- The chosen $c$ prisoners has to form a contiguous segment of prisoners.\n- Any of the chosen prisoner's crime level should not be greater then $t$. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer.\n\nFind the number of ways you can choose the $c$ prisoners.",
    "tutorial": "The severity of crimes form an integer sequence. Find all the contiguous sequences without any integer greater than $t$. If the length of any sequence is $L$, then we can choose $c$ prisoners from them in $L - c + 1$ ways.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "427",
    "index": "C",
    "title": "Checkposts",
    "statement": "Your city has $n$ junctions. There are $m$ \\textbf{one-way} roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions.\n\nTo ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction $i$ can protect junction $j$ if either $i = j$ or the police patrol car can go to $j$ from $i$ and then come back to $i$.\n\nBuilding checkposts costs some money. As some areas of the city are more expensive than others, building checkpost at some junctions might cost more money than other junctions.\n\nYou have to determine the minimum possible money needed to ensure the security of all the junctions. Also you have to find the number of ways to ensure the security in minimum price and \\textbf{in addition in minimum number of checkposts}. Two ways are different if any of the junctions contains a checkpost in one of them and do not contain in the other.",
    "tutorial": "Find the strongly connected components of the graph. From each component we need to choose a node with the lowest cost. If there are more than one nodes with lowest cost, then there are more than one way to choose node from this component.",
    "tags": [
      "dfs and similar",
      "graphs",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "427",
    "index": "D",
    "title": "Match & Catch",
    "statement": "Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings $s_{1}$ and $s_{2}$ from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task.\n\nNow they are trying to find a common substring of minimum length between these two strings. The substring must occur only once in the first string, and also it must occur only once in the second string.\n\nGiven two strings $s_{1}$ and $s_{2}$ consist of lowercase Latin letters, find the smallest (by length) common substring $p$ of both $s_{1}$ and $s_{2}$, where $p$ is a unique substring in $s_{1}$ and also in $s_{2}$. See notes for formal definition of substring and uniqueness.",
    "tutorial": "$O(n^{2})$ dynamic programming solution : Calculate the longest common prefix ( LCP ) for each index of $s1$ with each index of $s2$. Then, calculate LCP for each index of $s1$ with all the other indexes of it's own ( $s1$ ). Do the same for $s2$. Now from precalculated values, you can easily check the length of the shortest unique substring starting from any of the indexes of $s1$ or $s2$. Suppose $i$ is an index of $s1$ and $j$ is an index of $s2$. Find the LCP for $i$ and $j$. Now, the minimum of the length of LCP, length of shortest unique substring starting from $i$, length of shortest unique substring starting from $j$ is the answer for $i$,$j$. Now we need to find the minimum answer from all possible $i$,$j$ pair. This problem can also be solved in $O(n\\log n)$ by suffix array and in $O(n)$ using suffix automaton.",
    "tags": [
      "dp",
      "string suffix structures",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "427",
    "index": "E",
    "title": "Police Patrol",
    "statement": "Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the $x$-axis. Currently, there are $n$ criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.\n\nAs you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.\n\nThe new station will have only \\textbf{one} patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most $m$ criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.\n\nYour task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.",
    "tutorial": "Trying to place the police station on existing criminal locations is the best strategy. Calculate the cost from the leftmost criminal location, then sweep over the next locations. By doing some adjustments on the cost of the previous location will yield the cost of the current location.",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "ternary search"
    ],
    "rating": 2000
  },
  {
    "contest_id": "429",
    "index": "A",
    "title": "Xor-tree",
    "statement": "Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.\n\nThe game is played on a tree having $n$ nodes, numbered from $1$ to $n$. Each node $i$ has an initial value $init_{i}$, which is either 0 or 1. The root of the tree is node 1.\n\nOne can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node $x$. Right after someone has picked node $x$, the value of node $x$ flips, the values of sons of $x$ remain the same, the values of sons of sons of $x$ flips, the values of sons of sons of sons of $x$ remain the same and so on.\n\nThe goal of the game is to get each node $i$ to have value $goal_{i}$, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.",
    "tutorial": "There is something to learn from \"propagating tree\" problem, used in round #225. It's how the special operation works. I'll copy paste the explanation from there (with some modification, corresponding to the problem): Let's define level of a node the number of edges in the path from root to the node. Root (node 1) is at level 0, sons of root are at level 1, sons of sons of root are at level 2 and so on. Now suppose you want to do a special operation to a node x. What nodes from subtree of x will be flipped? Obviously, x will be first, being located at level L. Sons of x, located at level L + 1 will not be flipped. Sons of sons, located at level L + 2, will be flipped again. So, nodes from subtree of x located at levels L, L + 2, L + 4, ... will be flipped, and nodes located at levels L + 1, L + 3, L + 5 won't be flipped. Let's take those values of L modulo 2. All nodes having remainder L modulo 2 will be flipped, and nodes having reminder (L + 1) modulo 2 will not. In other words, for a fixed x, at a level L, let y a node from subtree of x, at level L2. If L and L2 have same parity, y will be flipped, otherwise it won't. We'll use this fact later. For now, let's think what should be our first operation. Let's consider some nodes {x1, x2, ..., xk} with property that x1 is son of x2, x2 is son of x3, ... xk-1 is son of xk and parity of levels of these nodes is the same. Suppose by now we fixed {x1, x2, ..., xk-1} (their current value is equal to their goal value), but xk is still not fixed. After some time, we'll have to fix xk. Now, by doing this, all nodes {x1, x2, ..., xk-1} will get flipped and hence unfixed. We've done some useless operations, so our used strategy is not the one that gives minimal number of operations. What we learn from this example? Suppose I want to currently fix a node X. There is no point to fix it now, unless all ancestors Y of X with property level(Y) = level(X) (mod 2) are fixed. But what if an ancestor Y of X is not fixed yet and level(Y) != level(X) (mod 2)? Can I fix node X now? The answer is yes, as future operations done on Y won't affect X. But, by same logic, I can firstly fix Y and then fix X, because again operations done on Y won't affect X. We get a nice property: there is no point to make an operation on a node X unless all ancestors of X are fixed. How can we use this property? What should be the first operation? We know that node 1 is the root, hence it always won't have any ancestor. All other nodes might have sometimes not fixed ancestors, but we know for sure, for beginning, node 1 won't have any unfixed ancestor (because it won't have any). So, for beginning we can start with node 1. More, suppose node 1 is unfixed. The only way to fix it is to make an operation on it. Since it's unfixed and this is the only way to fix it, you'll be obligated to do this operation. This means, in an optimal sequence of operations, you'll be obligated to do this operation, too. So, if node 1 was unfixed, we did an operation on it. If it was already fixed, we're done with it. What are next nodes we know for sure that will have all ancestors fixed? Sons of 1, because they have only one ancestor (node 1), which we know it's fixed. We can only fix them by doing operations of them (doing operations on node 1 / sons of them won't affect them). Since eventually they have to be fixed and only way to be fixed is to do an operation on them, in an optimal sequence of operations, we'll have to make operations on them. Let's move on. What are next nodes that we know for sure all ancestors of them will be fixed? Sons of sons of 1. We can fix them by doing an operation of them, or by doing an operation on 1. But doing an operation on 1 isn't helpful, because even if it fixes this node, it unfixes 1. Then, you'll have to do one more operation on 1, which will unfix current node, so we do two useless operations. It turns out, the only way to fix them is to do an operation on them. Generally, suppose all ancestors of node x are fixed. We get the current value of node x after the operations done on ancestors of x. If the current value is not the expected one, we'll have to do an operation on node x (this is the only way to fix the node x). Now, after node x is fixed, we can process sons of it. This strategy guarantees minimal number of operations, because we do an operation only when we're forced to do it. This leads immediately to an O(N ^ 2) algorithm, by every time we need to do an operation to update it to nodes from its subtree. How to get O(N)? Suppose we are at node x and want to know its current value after operations done for its ancestors. Obviously, it is defined by initial value. If we know number of operations done so far by even levels for its ancestors, number of operations done so far by odd levels and current level, we can determine the current value. Suppose these values are (initial_value, odd_times, even_times, level). We observe that 2 operations cancel each other, so we can take this number modulo 2. If level mod 2 = 0, then only even_times will matter, and current_value = (initial_value + even_times) % 2. Otherwise, current_value = (initial_value + odd_times) % 2. We can send (even_times, odd_times and level) as DFS parameters, so current_value can be calculated in O(1), and overall complexity is O(N).",
    "tags": [
      "dfs and similar",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "429",
    "index": "B",
    "title": "Working out",
    "statement": "Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix $a$ with $n$ lines and $m$ columns. Let number $a[i][j]$ represents the calories burned by performing workout at the cell of gym in the $i$-th line and the $j$-th column.\n\nIahub starts with workout located at line $1$ and column $1$. He needs to finish with workout $a[n][m]$. After finishing workout $a[i][j]$, he can go to workout $a[i + 1][j]$ or $a[i][j + 1]$. Similarly, Iahubina starts with workout $a[n][1]$ and she needs to finish with workout $a[1][m]$. After finishing workout from cell $a[i][j]$, she goes to either $a[i][j + 1]$ or $a[i - 1][j]$.\n\nThere is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.\n\nIf a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.",
    "tutorial": "The particularity of this problem which makes it different by other problem of this kind is that paths need to cross exactly one cell and Iahub can go only right and down, Iahubina can go only right and up. Let's try to come up with a solution based on these facts. A good start is to analyze configurations possible for meeting cell. Iahub can come either from right or down and Iahubina can come either from right or up. However, if both Iahub and Iahubina come from right, they must have met in other cell as well before (the cell in the left of the meet one). Similarly, if one comes from up and other one from down, their paths will cross either on upper cell, lower cell or right cell. Only 2 possible cases are: Iahub comes from right, Iahubina comes from up or Iahub comes from down, Iahubina comes from right. By drawing some skatches on paper, you'll see next cell visited after meeting one will have the same direction for both of them. More, they will never meet again. So Iahub comes from right, goes to right, Iahubina comes from up, goes to up or Iahub comes from down, goes to down and Iahubina comes from right, goes to right. In the drawing, Iahub's possible visited cells are blue, Iahubina's possible visited cells are red and meeting cell is purple. Denote (X, Y) meeting cell. For first case, Iahub comes from (1, 1) to (X, Y - 1) by going down or right. Next, he goes from (X, Y + 1) to (N, M) by going down or right. Iahubina goes from (M, 1) to (X + 1, Y) by going up or right and then from (X - 1, Y) to (1, M) by going with same directions. In second case, Iahub goes from (1, 1) to (X - 1, Y) and then from (X + 1, Y) to (N, M) and Iahubina goes from (M, 1) to (X, Y - 1) and then from (X, Y + 1) to (1, M). We can precalculate for dynamic programming matrixes and we're done. dp1[i][j] = maximal cost of a path going from (1, 1) to (i, j) only down and right. dp2[i][j] = maximal cost of a path from (i, j) to (1, m) going only up and right. dp3[i][j] = maximal cost of a path from (m, 1) to (i, j) going only up and right. dp4[i][j] = maximal cost of a path from (i, j) to (n, m) going only down or right. And here is my full implementation of recurrences (C++ only): Also, pay attention that meeting points can be cells (i, j) with 1 < i < n and 1 < j < m. (why?)",
    "tags": [
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "429",
    "index": "C",
    "title": "Guess the Tree",
    "statement": "Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food.\n\nIahub asks Iahubina: can you build a rooted tree, such that\n\n- each internal node (a node with at least one son) has at least two sons;\n- node $i$ has $c_{i}$ nodes in its subtree?\n\nIahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. \\textbf{The required tree must contain $n$ nodes}.",
    "tutorial": "The constrain n <= 24 immediately suggest us an exponential solution. 24 numbers seems to be not too big, but also not too small. What if we can reduce it by half? We can do this, by analyzing problem's restriction more carefully. The problem states that each internal node has at least two sons. After drawing some trees likes these, one may notice there are a lot of leafs in them. For a tree with this property, number of leafs is at least (n + 1) / 2. We'll proof this affirmation by mathematical induction. For n = 1, affirmation is true. Now, suppose our tree has n nodes, and the root of it has sons {s1, s2, ..., sk}. Let's assume subtree of s1 has n1 nodes, subtree of s2 has n2 nodes, ..., subtree of sk has nk nodes. By induction we get that s1 has at least (n1 + 1) / 2 leafs, ..., sk has at least (nk + 1) / 2 leafs. Summing up, we get that our tree has at least (n1 + n2 + ... + nk + k) / 2 leafs. But n1 + n2 + ... + nk = n - 1. So it has at least (n + k - 1) / 2 leafs. But, by hypothesis k >= 2, so our tree has at least (n + 1) / 2 leafs. For n = 24, there will be at least 13 leafs, so at most 11 internal nodes. It looks much better now for an exponential solution! Before presenting it, we need one more observation. Suppose we sorted c[] array decreasing. Now, the father of node i can be only one of nodes {1, 2, ..., i - 1}. Nodes {i + 1, i + 2, ..., n} will have at most as much nodes as node i, so they can't be father of i. By doing this observation we can start algorithm: start with node 1 and assign its sons. Then, move to node 2. If it does not have a father, we won't have one, so current configuration is good. If he has a father (in this case node 1), then tree is connected so far. So we can assign children of node 2. Generally, if a node i does not have a father when it's processed, it won't have in future either. If it has, the tree is connected so far, so we add children of i. Let's introduce the following dynamic programming. Let dp[node][mask][leafs] = is it possible to create a tree if all nodes {1, 2, ..., node} have already a father, exactly leafs nodes don't have one and internal nodes corresponding to 1 in bitmask mask also don't have one? If you never heart about \"bitmask\" word, this problem is not good for you to start with. I recommend you problem E from round #191, where I explained more how bitmasks work. Back on the problem. If node has 1 in its bit from the mask, then we know for sure the tree can't be built. Otherwise, let's assign sons for node. We take all submasks of mask (number obtained by changing some bits from 1 to 0) and make sum of degrees for corresponding nodes. Denote this number as S. These are the internal nodes. How about the leafs? We need to have available L = c[node] - S - 1 leafs. If L is <= than leafs, we can use them. If L < 0, obviously we can't build the tree. Will remain obviously leafs - L leafs. The new mask will be mask ^ submask. Also, we need to iterate to node + 1. If dp[node+1][mask ^ submask][leafs - L]. One more condition that needs to be considered: node needs to have at least 2 sons. This means L + cnt > 1 (where cnt are number of internal nodes used). When do we stop the dp? When c[nod] = 1. If mask = 0 and leafs = 0, then we can build the tree. Otherwise, we can't. Let's analyze the complexity. There are O(2 ^ (n / 2)) masks, each of them has O(n) leafs, for each O(n) node. This gives O(2 ^ (n / 2) * n ^ 2) states. Apparently, iterating over all submasks gives O(2 ^ (n / 2)) time for each submask, so overall complexity should be O(4 ^ (n / 2) * n ^ 2). But this complexity is over rated. Taking all submasks for all masks takes O(3 ^ (n / 2)) time, instead of O(4 ^ (n / 2)) time. Why? Consider numbers written in base 3: for a mask and a submask we can assign 3 ternary digits to each bit: 0 if bit does not appear in mask 1 if bit appears in mask but not in submask 2 if bit appears in mask and in submask Obviously, there are O(3 ^ (n / 2)) numbers like this and the two problems are equivalent, so this step takes O(3 ^ (n / 2)) and overall complexity is O(3 ^ (n / 2) * n ^ 2).",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "429",
    "index": "D",
    "title": "Tricky Function",
    "statement": "Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be the one qualified, he tells Iahub the following task.\n\nYou're given an (1-based) array $a$ with $n$ elements. Let's define function $f(i, j)$ $(1 ≤ i, j ≤ n)$ as $(i - j)^{2} + g(i, j)^{2}$. Function g is calculated by the following pseudo-code:\n\n\\begin{verbatim}\nint g(int i, int j) {\nint sum = 0;\nfor (int k = min(i, j) + 1; k <= max(i, j); k = k + 1)\nsum = sum + a[k];\nreturn sum;\n}\n\\end{verbatim}\n\nFind a value $min_{i ≠ j}  f(i, j)$.\n\nProbably by now Iahub already figured out the solution to this problem. Can you?",
    "tutorial": "Let's define S[i] = a[1] + a[2] + ... + a[i]. Then, f(i, j) = (i - j) ^ 2 + (S[i] - S[j]) ^ 2. Trying to minimize this function seems complicated, so we need to manipulate the formula more. We know from the maths that if f(i, j) is minimized, then also f'(i, j) = sqrt ( (i - j) ^ 2 + (S[i] - S[j]) ^ 2) is also minimized. Does this function look familiar to you? Suppose you get two points in 2D plane: one having coordinates (i, S[i]) and the other one having coordinates (j, S[j]). One can see that f'(i, j) is exactly euclidean distance of those points. So, if f'(i, j) is a distance between two points in plane, when is achieved minimal f'(i, j)? For the closest two points in plane (the points which are located at minimal distance). So, having set of points (i, S[i]), we need to compute closest two points from this plane. There is a classical algorithm that does this in O(n * logn).",
    "tags": [
      "data structures",
      "divide and conquer",
      "geometry"
    ],
    "rating": 2200
  },
  {
    "contest_id": "429",
    "index": "E",
    "title": "Points and Segments",
    "statement": "Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.\n\nIahub wants to draw $n$ distinct segments $[l_{i}, r_{i}]$ on the $OX$ axis. He can draw each segment with either red or blue. The drawing is good if and only if the following requirement is met: for each point $x$ of the $OX$ axis consider all the segments that contains point $x$; suppose, that $r_{x}$ red segments and $b_{x}$ blue segments contain point $x$; for each point $x$ inequality $|r_{x} - b_{x}| ≤ 1$ must be satisfied.\n\nA segment $[l, r]$ contains a point $x$ if and only if $l ≤ x ≤ r$.\n\nIahub gives you the starting and ending points of all the segments. You have to find any good drawing for him.",
    "tutorial": "The problem asks you to check the property for an infinity of points. Obviously, we can't do that. However, we can observe that some contiguous ranges on OX axis have the same rx and bx values. Like a sweep line algorithm, a possible change may appear only when a new segment begins or when an old one ends. So let's consider set of points formed by all li reunited with set of points formed by all ri. Sort the values increasing. Suppose the set looks like {x1, x2, ..., xk}. Then ranges [0, x1) [x1, x2) ... [xk-1, xk) [xk, infinity) are the only ones that need to be considered. If we can take an arbitrary point from each range and the property is respected for all points, then the drawing is good. We need to color segments. But each segment is a reunion of ranges like the ones from above. When you color a segment, all ranges from it will be colored too. So, after coloring the segments, for each range, |number of times range was colored with blue - number of times range was colored with red| <= 1. It's time to think creative. We can see ranges as vertexes of a graph and segments as edges. For example, if a segment is formed by ranges {Xi, Xi+1, ..., Xj-1, Xj} we add an undirected edge from i to j + 1. We need to color the edges. We divide the graph into connected components and apply same logic for each component. Next, by graph I'll refer to a connected graph. Let's assume that our graph has all degrees even. Then, it admits an eulerian cycle. Suppose {x1, x2, ..., xk} is the list of nodes from the cycle, such as x1-x2 x2-x3 ... xk-x1 are the edges of it, in this order. We apply a rule: if xi < xi+1, we color edge between xi and xi+1 in red. Otherwise, we color it in blue. What happens for a node? Whenever a \"red\" edge crosses it (for example edge 1-5 crosses node 4) a \"blue\" edge will always exist to cross it again (for example edge 6-2 crosses node 4). This is because of property of euler cycle: suppose we started from a node x and gone in \"left\". We need to return to it, but the only way to do it is an edge which goes to \"right\". So, when degrees of graph are all even, for every point on OX axis, difference between rx and bx will be always 0. Let's solve the general case now. Some nodes have odd degree. But there will always be an even number of nodes with odd degrees. Why? Suppose the property is respected for some edges added so far and now we add a new one. There are two cases: 1/ the edge connects two nodes with odd degree. in this case, the number of nodes with odd degrees decreases by 2, but its parity does not change. 2/ the edge connects one node with odd degree and one node with even degree. Now, degree of \"old\" odd one becomes even and degree of \"old\" even one becomes odd. So number of nodes with odd degrees does not change. So suppose the nodes with odd degrees are X1 X2 ... Xk (k is even). Assume X1 < X2 < ... < Xk. If we add one more edge to each of these nodes, an euler cycle would be possible. However, we can't \"add\" edges, because edges are segments from the input. But we can imagine them. Of course, this we'll create an imbalance between red and blue edges, but let's see how big it is. What if we add a fictive edge between X1 to X2, between X3 to X4, ..., between X(k - 1) to Xk? In this way, all those nodes will have even degree. So for each Xi (i odd) we add a dummy vertex Yi and some dummy edges from Xi to Yi and from Yi to Xi+1. Now let's see the effect: if the fictive edges existed, the balance would be 0. But they do not exist, so one of rx or bx will decrease. So now |rx - bx| <= 1, good enough for problem's restrictions.",
    "tags": [
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "430",
    "index": "A",
    "title": "Points and Segments (easy)",
    "statement": "Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.\n\nIahub wants to draw $n$ distinct points and $m$ segments on the $OX$ axis. He can draw each point with either red or blue. The drawing is good if and only if the following requirement is met: for each segment $[l_{i}, r_{i}]$ consider all the red points belong to it ($r_{i}$ points), and all the blue points belong to it ($b_{i}$ points); each segment $i$ should satisfy the inequality $|r_{i} - b_{i}| ≤ 1$.\n\nIahub thinks that point $x$ belongs to segment $[l, r]$, if inequality $l ≤ x ≤ r$ holds.\n\nIahub gives to you all coordinates of points and segments. Please, help him to find any good drawing.",
    "tutorial": "The problem asks you to output \"-1\" if there is no solution. A natural question is now: \"when there is no solution\"? Try to come up with a test like this! After some analysis, you'll see anyhow we draw the points and the lines, there will always be a solution. By manually solving small cases, you might already have found the pattern. But for now, let's assume anyhow we draw points and lines, there will always be a solution. Let's have a fixed set of points. Then, anyhow we draw a line, there should still be a solution. So, we need to find a coloring of points, such as for every line, |number of red points which belong to it - number of blue points which belong to it| <= 1. Suppose anytime you color a point with red you assign it +1 value. Also, anytime you color it with blue you assign it -1 value. Then, for a segment, the drawing is good if S = sum of values assigned to points that belong to segment is between -1 and 1 (in other words |S| <= 1). Let's sort points increasing by abscissa. It's useful because now, for a segment, there will be a contiguous range of points that belong to that segment. For example, suppose my current segment is [3, 7] and the initial set of points was {4, 1, 5, 2, 8, 7}. Initially, points that belong to the segment would be first, third and sixth. Let's sort the points by abscissa. It looks like {1, 2, 4, 5, 7, 8}. You can see now there is a contiguous range of points that belongs to [3, 7] segment: more exactly third, fourth and fifth. We reduced problem to: given an array, assign it either +1 or -1 values such as, for each subarray (contiguous range), the sum S of subarray's elements follows the condition |S| <= 1. Before reading on, try to come up with an example by yourself. My solution uses the pattern: +1 -1 +1 -1 +1 -1 ... Each subarray of it will have sum of its elements either -1, 0 or 1. How to proof it? When dealing with sums of subarrays, a good idea is to use partial sums. Denote sum[i] = x[1] + x[2] + ... + x[i]. Then, sum of a subarray [x, y] is sum[y] - sum[x - 1]. Partial sums for the pattern looks like: 1 0 1 0 1 0 .... Hence, there are 4 possible cases: 1/ sum[x - 1] = 0 and sum[y] = 0. sum[y] - sum[x - 1] = 0 2/ sum[x - 1] = 1 and sum[y] = 1. sum[y] - sum[x - 1] = 0 3/ sum[x - 1] = 0 and sum[y] = 1. sum[y] - sum[x - 1] = 1 4/ sum[x - 1] = 1 and sum[y] = 0. sum[y] - sum[x - 1] = -1 Hence, each subarray sum is either -1, 0 or 1. So, general algorithm looks like: sort points by abscissa, assign them red, blue, red, blue, ... and then sort them back by original order and print the colors.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "430",
    "index": "B",
    "title": "Balls Game",
    "statement": "Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game?\n\nThere are $n$ balls put in a row. Each ball is colored in one of $k$ colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color $x$. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color.\n\nFor example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.\n\nIahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.",
    "tutorial": "This is an implementation problem. There is not so much to explain. Perhaps the trick at implementation problems is to divide code into smaller subproblems, easy to code and then put them together. I don't know if this is the universally truth, but this is how I approach them. Here, there are two main parts: the part when you insert a ball between 2 balls and the part when you see how many balls are destroyed after the move. We can keep an array a[] with initial configuration of balls, then for each insertion create an array b[] with current configuration after the insertion. If my ball is inserted after position pos, b is something like this: b = a[1....pos] + {my_ball} + a[pos+1....n]. For now we have array b[] and we need to know how many balls will disappear. The problem statement gives us an important clue: no 3 balls will initially have the same color. This means, any time, at most one contiguous range of balls of same color will exist with length at least 3. If it exists, we have to remove it. Then, we have to repeat this process. So algorithm is something like bubble sort: while b[] array has changed last step, continue algorithm, otherwise exit it. Now, search an i for which b[i] = b[i + 1] = b[i + 2]. Then, take the maximum j > i for which b[k] = b[i], with i < k <= j. You have to remove from b[] the subarray [i...j] and add j - i + 1 to the destroyed balls. You'll need to return this sum - 1, because the ball you added wasn't there at beginning. Pay attention on case when you can't destroy anything, you need to output 0 instead of -1. There are O(n) positions where you can insert the new ball, for each of them there are maximal O(n) steps when balls are deleted and deleting balls takes maximal O(n) time, so overall complexity is O(n ^ 3). Note: in my solution, I don't actually do deletion. If I have to delete a range [i, j] I create a new array c[] = b[1...i - 1] + b[j+1....n] and then copy c[] into b[] array. This guarantees O(n) time for deletion.",
    "tags": [
      "brute force",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "431",
    "index": "A",
    "title": "Black Square",
    "statement": "Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called \"Black Square\" on his super cool touchscreen phone.\n\nIn this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly $a_{i}$ calories on touching the $i$-th strip.\n\nYou've got a string $s$, describing the process of the game and numbers $a_{1}, a_{2}, a_{3}, a_{4}$. Calculate how many calories Jury needs to destroy all the squares?",
    "tutorial": "To solve this problem, you must only do the process described in statement. Complexity: $O(N)$",
    "code": "#include<iostream>\n \nusing namespace std;\n \nint main(){\n    int a[5];\n    for (int i = 1; i <= 4; i ++)\n        cin >> a[i];\n    string s;\n    cin >> s;\n    int sum = 0;\n    for (int i = 0 ;i < s.size(); i ++)\n        sum += a[s[i]-'0'];\n    cout << sum << endl;\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "431",
    "index": "B",
    "title": "Shower Line",
    "statement": "Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks.\n\nThere is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory shower door. As soon as the shower opens, the first person from the line enters the shower. After a while the first person leaves the shower and the next person enters the shower. The process continues until everybody in the line has a shower.\n\nHaving a shower takes some time, so the students in the line talk as they wait. At each moment of time the students talk in pairs: the $(2i - 1)$-th man in the line (for the current moment) talks with the $(2i)$-th one.\n\nLet's look at this process in more detail. Let's number the people from 1 to 5. Let's assume that the line initially looks as 23154 (person number 2 stands at the beginning of the line). Then, before the shower opens, 2 talks with 3, 1 talks with 5, 4 doesn't talk with anyone. Then 2 enters the shower. While 2 has a shower, 3 and 1 talk, 5 and 4 talk too. Then, 3 enters the shower. While 3 has a shower, 1 and 5 talk, 4 doesn't talk to anyone. Then 1 enters the shower and while he is there, 5 and 4 talk. Then 5 enters the shower, and then 4 enters the shower.\n\nWe know that if students $i$ and $j$ talk, then the $i$-th student's happiness increases by $g_{ij}$ and the $j$-th student's happiness increases by $g_{ji}$. Your task is to find such initial order of students in the line that the total happiness of all students will be maximum in the end. Please note that some pair of students may have a talk several times. In the example above students 1 and 5 talk while they wait for the shower to open and while 3 has a shower.",
    "tutorial": "In this problem, according to the small limits, we can brute all permutations and choose the best answer of all. The easeast way to do this - use standart C++ function next_permutation, or simply write 5 for. For each permutation we can simulate the process, which was described in a statement, or notice that first with second student, and second with the third will communicate one time, and third with fourth student, and fourth with fifth - will communicate two times. Another pairs of students will never communicate to each other during they stay in queue. Complexity: $O(n!)$",
    "code": "#include <iostream>\n#include <stdio.h>\n#include <algorithm>\n \nusing namespace std;\n \nint g[6][6];\n \nint main()\n{\n    int n = 5;\n    for(int i = 0 ; i < n ; ++i)\n        for(int j = 0 ; j < n ; ++j)\n            cin >> g[i][j];\n    int p[6], pans[6], ans = -1, tmp;\n    for(int i = 0 ; i < n ; ++i)\n        p[i] = i;\n    \n    do\n    {\n        //01234\n        tmp = g[p[0]][p[1]] + g[p[1]][p[0]];\n        tmp += g[p[2]][p[3]] + g[p[3]][p[2]];\n        \n        //1234\n        tmp += g[p[1]][p[2]] + g[p[2]][p[1]];\n        tmp += g[p[3]][p[4]] + g[p[4]][p[3]];\n        \n        //234\n        tmp += g[p[2]][p[3]] + g[p[3]][p[2]];\n        \n        //34\n        tmp += g[p[3]][p[4]] + g[p[4]][p[3]];\n        \n        if(tmp > ans)\n        {\n            ans = tmp;\n            for(int i = 0 ; i < n ; ++i)\n                pans[i] = p[i];\n        }\n    }\n    while(next_permutation(p, p+n));\n    \n    cout << ans << \"\\n\";\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "431",
    "index": "C",
    "title": "k-Tree",
    "statement": "Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a $k$-tree.\n\nA $k$-tree is an infinite rooted tree where:\n\n- each vertex has exactly $k$ children;\n- each edge has some weight;\n- if we look at the edges that goes from some vertex to its children (exactly $k$ edges), then their weights will equal $1, 2, 3, ..., k$.\n\nThe picture below shows a part of a 3-tree.\n\nAs soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: \"How many paths of total weight $n$ (the sum of all weights of the edges in the path) are there, starting from the root of a $k$-tree and also containing at least one edge of weight at least $d$?\".Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "This problem can be solved by dinamic programming. Let's Dp[n][is] - number of ways with length equals to $n$ in k-tree, where if $is = 1$ - there is exists edge with length at least $d$, $is = 0$ - lengths of all edges less then $d$. Initial state Dp[0][0] = 1. Transition - iterate all edges which can be first on the way in k-tree, then problem transform to the same, but with less length of the way (because subtree of vertex son is the k-tree). Dp[n][0] = Dp[n-1][0] + ... + Dp[n-min(d-1,n)][0] Dp[n][1] = Dp[n-1][1] + ... + Dp[n-min(d-1,n)][1] + (Dp[n-d][0] + Dp[n-d][1]) + ... + (Dp[n-min(n,k)][0] + Dp[n-min(n,k)][1]) See solution for more details. Complexity: $O(nk)$ Notice that this solution can be easy midify to $O(N)$ complexity, only precalc partial sums. But it is not neccesary to solve this problem in such way.",
    "code": "#include <iostream>\n#include <stdio.h>\n#include <algorithm>\n \nusing namespace std;\n \nconst int mod = 1e9 + 7;\n \nint dp[100][2];\n \nvoid add(int &a, int b)\n{\n    a += b;\n    if(a >= mod)\n        a -= mod;\n}\n \nint main(int argc, char ** argv)\n{\n    int n, k, d;\n    cin >> n >> k >> d;\n    dp[0][0] = 1;\n    dp[0][1] = 0;\n    \n    for(int i = 1 ; i <= n ; ++i)\n    {\n        dp[i][0] = dp[i][1] = 0;\n        \n        for(int j = 1 ; j <= k ; ++j)\n        {\n            if(i-j < 0) break;\n            \n            if(j < d)\n            {\n                add(dp[i][0], dp[i-j][0]);\n                add(dp[i][1], dp[i-j][1]);\n            }\n            else\n            {\n                add(dp[i][1], dp[i-j][0]);\n                add(dp[i][1], dp[i-j][1]);\n            }\n        }\n    }\n    cout << dp[n][1] << \"\\n\";\n    return 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "431",
    "index": "D",
    "title": "Random Task",
    "statement": "One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: \"Find such positive integer $n$, that among numbers $n + 1$, $n + 2$, ..., $2·n$ there are exactly $m$ numbers which binary representation contains exactly $k$ digits one\".\n\nThe girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed $10^{18}$.",
    "tutorial": "We will search $n$ by binary search. Such function is monotone, because the amount of numbers with exactly $k$ 1-bits on a segment $n + 2$ ... $2 \\cdot (n + 1)$ more or equal than amount of such numbers on segment $n + 1$ ... $2 \\cdot n$. Last statement is correct, because of $n + 1$ and $2 \\cdot (n + 1)$ have equals number of 1-bits. To find the amount of numbers on segment $L...R$, which have exactly $k$ 1-bits, it is sufficient to can calculate this number for segment $1...L$, then the answer will be $F(1...R) - F(1..L - 1)$. Let's understand how we can calculate $F(1...X)$. Iterate number of bit will be the first(from biggest to smallest) which is different in X and numbers, which amount we want to calculate. Let the first difference will be in $i$-th bit(it's possible, if in X this bit equals to 1, because we consider all numbers do not exceed X). Then other smallest bits we can choose in any way, but only amount of 1-bits must equals to $k$. We can do this in $C_{i}^{k - cnt}$ ways, where $cnt$ - the number of 1-bits in X, bigger then $i$, and $C_{n}^{k}$ - binomailany factor. Finally, you should not forget about X (if it, of course, has k one bits). Complexity: $O(log^{2}(Ans))$",
    "code": "#include<cstdio>\n#include<cassert>\n \nusing namespace std;\n \n#define linf 2000000000000000000LL\n#define bit(mask,i) ((mask>>i)&1)\n \nconst int Max_Bit = 63;\n \nlong long C[Max_Bit+1][Max_Bit+1];\n \nint bcount(long long x){\n    int Res = 0;\n    for (;x;x&=(x-1)) Res++;\n    return Res;\n}\nlong long Solve(long long x,int k){\n            long long Answer = (k == bcount(x));\n            for (int i = Max_Bit; i >= 0 && k>=0; i -- )\n             if (bit(x,i)) \n              Answer+=C[i][k--];\n            return Answer;\n}\nint main()\n{\n    C[0][0] = 1;\n    for (int i = 1; i <= Max_Bit ;i ++ )\n     for (int j = 0 ; j <= i ; j ++ )\n      C[i][j]=C[i-1][j]+((j)?(C[i-1][j-1]):0);\n \n    long long count;\n    int k;\n    scanf(\"%lld%d\",&count,&k);\n \n    \n    long long l = 1 , r = linf/2;\n    while (l<r)\n    {\n          long long m = l + (r-l)/2;\n          if (Solve(m*2,k)-Solve(m,k)<count) l = m+1;\n          else\n           r = m;\n    }\n    \n    printf(\"%I64d\\n\",l);\n    return 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "431",
    "index": "E",
    "title": "Chemistry Experiment",
    "statement": "One day two students, Grisha and Diana, found themselves in the university chemistry lab. In the lab the students found $n$ test tubes with mercury numbered from $1$ to $n$ and decided to conduct an experiment.\n\nThe experiment consists of $q$ steps. On each step, one of the following actions occurs:\n\n- Diana pours all the contents from tube number $p_{i}$ and then pours there exactly $x_{i}$ liters of mercury.\n- Let's consider all the ways to add $v_{i}$ liters of water into the tubes; for each way let's count the volume \\textbf{of liquid} (water and mercury) in the tube \\textbf{with water} with maximum amount of liquid; finally let's find the minimum among counted maximums. That is the number the students want to count. At that, the students don't actually pour the mercury. They perform calculations without changing the contents of the tubes.\n\nUnfortunately, the calculations proved to be too complex and the students asked you to help them. Help them conduct the described experiment.",
    "tutorial": "First of all let's understand the statement. We have $n$ tubes. At the beginning of each of them there are a few amount of mercury is poured. We want be able to perform two types of queries: Make the amount of mercury in $p$-th tube equals to $x$. Given the number $v$ - the amount of water that must be optimally pour these tubes. What does it mean optimally? That mean we pour water in some of the tubes in the way, when maximum volume of liquid for all tubes, where we poured water, will be as small, as possible. Well, actually now turn to the solution. Use binary search to find an answer, in particular, will sort out the amount of mercury in a tubes(let it equals to $d$), such that in the tubes with smaller volume of the liquid can be poured all $v$ liters of water and the maximum liquid level does not exceed $d$. Let the number of tubes, with the amount of mercury less than $d$ is equal $t$. Now the problem is reduced to learning how to count the total amount of water that we can to pour into each of $t$ least tubes, such that the level of the liquid in each of them is equal $d$. Let $a[i]$ - the total amount of mercury in the tubes which exactly have $i$ liters mercury and $b[i]$ - number of tubes which the volume of mercury is equal $i$. Then $t = b[0] + ... + b[d - 1]$ and $v_{1} = t * d - (a[0] + a[1] + ... + a[d - 1])$ - the total maximum amount of the water which can be poured. If $v_{1}$ < $v$, then obviously this space is not enough for pour all the water, otherwise quite enough and so the answer will be no more than $d$. When we found the smallest $d$, we can say that the answer is equal $d$ - ($v_{1}$ - $v$) / $t$. To quickly find for $a[0] + a[1] + ... + a[d - 1]$ and $b[0] + ... + b[d - 1]$, and perform queries of the first type, you can use the Fenwick tree. Complexity: $O(qlog^{2}(n))$",
    "code": "#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <map>\n \nusing namespace std;\n \nconst int maxn = 200001;\n \nint h[maxn];\nint T[maxn];\nint P[maxn];\nlong long V[maxn];\nint X[maxn];\n \nlong long max_h;\nint n;\nlong long a[maxn], b[maxn];\nint mas[maxn];\n \nvoid add(long long t[], int i, long long value) {\n    for (; i < maxn; i += (i + 1) & -(i + 1))\n        t[i] += value;\n}\n \nlong long sum(long long t[], int i) {\n    long long res = 0;\n    for (; i >= 0; i -= (i + 1) & -(i + 1))\n        res += t[i];\n    return res;\n}\n \n \nlong long get(int H)\n{\n    long long V;\n    V = mas[H]*1ll*n;\n    \n    long long cnt = sum(a, max_h) - sum(a, H);\n    \n    V -= mas[H]*cnt;\n    V -= sum(b, H);\n    return V;\n}\n \nint main()\n{\n    ios::sync_with_stdio(0);\n    int q;\n    cin >> n >> q;\n    \n    map<int,int> mp, id;\n    \n    for(int i = 0 ; i < n ; ++i)\n    {\n        cin >> h[i];\n        mp[h[i]] = 1;\n    }\n    \n    for(int i = 0 ; i < q ; ++i)\n    {\n        cin >> T[i];\n        if(T[i] == 1)\n        {\n            cin >> P[i] >> X[i];\n            mp[X[i]] = 1;\n        }\n        else\n            cin >> V[i];\n    }\n    \n    int index = 1;\n    mas[0] = 0;\n    for(map<int,int> :: iterator it = mp.begin() ; it != mp.end() ; ++it)\n    {\n        id[it->first] = index;\n        mas[index] = it->first;\n        ++index;\n    }\n    max_h = index-1;\n    \n    for(int i = 0 ; i < n ; ++i)\n    {\n        add(a, id[h[i]], 1ll);\n        add(b, id[h[i]], h[i]);\n    }\n    \n    int t;\n    int p, x, cnt;\n    long long v, H;\n    for(int i = 0 ; i < q ; ++i)\n    {\n        t = T[i];\n        if(t == 1)\n        {\n            p = P[i];\n            x = X[i];\n            add(a, id[h[p-1]], -1);\n            add(b, id[h[p-1]], -h[p-1]);\n            \n            h[p-1] = x;\n            \n            add(a, id[h[p-1]], 1);\n            add(b, id[h[p-1]], h[p-1]);\n        }\n        else\n        {\n            v = V[i];\n            \n            H = 0;\n            for(int i = 20 ; i >= 0 ; --i)\n            {\n                if(H + (1<<i) > max_h) continue;\n                if(get(H + (1<<i)) <= v)\n                    H += (1<<i);\n            }\n            \n            cout.precision(5);\n            cnt = sum(a, max_h) - sum(a, H);\n            cout << fixed << mas[H] + (v-get(H))/(double)(n-cnt) << \"\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "ternary search"
    ],
    "rating": 2200
  },
  {
    "contest_id": "432",
    "index": "A",
    "title": "Choosing Teams",
    "statement": "The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has $n$ students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.\n\nThe head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least $k$ times?",
    "tutorial": "In this problem you should count number of students who can participate in ACM, divide it by 3 and round down. It could be done like this:",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "432",
    "index": "B",
    "title": "Football Kit",
    "statement": "Consider a football tournament where $n$ teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the $i$-th team has color $x_{i}$ and the kit for away games of this team has color $y_{i}$ $(x_{i} ≠ y_{i})$.\n\nIn the tournament, each team plays exactly one home game and exactly one away game with each other team ($n(n - 1)$ games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.\n\nCalculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.",
    "tutorial": "Count for every team number of games in home kit. For team $i$ it equals to sum of $n - 1$ games at home and some away games with such teams which home kit color equals away kit color of team $i$. To count number of such away games you could calc array $cnt[j]$ - number of teams with home color kit $j$. The solution could be implemented in this wasy:",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "432",
    "index": "C",
    "title": "Prime Swaps",
    "statement": "You have an array $a[1], a[2], ..., a[n]$, containing distinct integers from $1$ to $n$. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):\n\n- choose two indexes, $i$ and $j$ ($1 ≤ i < j ≤ n$; $(j - i + 1)$ is a prime number);\n- swap the elements on positions $i$ and $j$; in other words, you are allowed to apply the following sequence of assignments: $tmp = a[i], a[i] = a[j], a[j] = tmp$ ($tmp$ is a temporary variable).\n\nYou do not need to minimize the number of used operations. However, you need to make sure that there are at most $5n$ operations.",
    "tutorial": "The solution can be described by pseudo-code: Consider elements of permutation from $1$ to $n$ While current element $i$ is not sutiated on position $i$ Let the position of element $i$ equals $pos$ Find maximum prime integer $p$ which is less or equal than $pos - i + 1 Swap element in positions $pos$ and $pos - p + 1$ It could be proved that such algorithm makes less than $4n$ swaps (for example, by implementing the algorithm) This algorithm should be implemented optimally. You should maintain positions of elements of permutation. Swap function in author's solution:",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "432",
    "index": "D",
    "title": "Prefixes and Suffixes",
    "statement": "You have a string $s = s_{1}s_{2}...s_{|s|}$, where $|s|$ is the length of string $s$, and $s_{i}$ its $i$-th character.\n\nLet's introduce several definitions:\n\n- A substring $s[i..j]$ $(1 ≤ i ≤ j ≤ |s|)$ of string $s$ is string $s_{i}s_{i + 1}...s_{j}$.\n- The prefix of string $s$ of length $l$ $(1 ≤ l ≤ |s|)$ is string $s[1..l]$.\n- The suffix of string $s$ of length $l$ $(1 ≤ l ≤ |s|)$ is string $s[|s| - l + 1..|s|]$.\n\nYour task is, for any prefix of string $s$ which matches a suffix of string $s$, print the number of times it occurs in string $s$ as a substring.",
    "tutorial": "The problem could be solved using different algorithms with z and prefix functions. Let's describe the solution with prefix function $p$ of string $s$. Calc prefix function and create a tree where vertices - integers from $0$ to $|s|$, edges - from $p[i]$ to $i$ for every $i$. The root of the tree is $0$. For every vertex $v$ calc the number of values $p[i] = v$ - that is $cnt[v]$. Then for every $v$ calc the sum all values $cnt[u]$ for every $u$ in to subtree of $v$. The general answer to the problem is: Find all lenghts of the prefixes which matches the suffixes - these values are $|s|$, $p[|s|]$, $p[p[|s|]]$, $p[p[p[|s|]]]$... For every such length $L$ the answer to the problem is $sum[L] + 1$.",
    "tags": [
      "dp",
      "string suffix structures",
      "strings",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "432",
    "index": "E",
    "title": "Square Tiling",
    "statement": "You have an $n × m$ rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally:\n\n- each cell must be painted some color (the colors are marked by uppercase Latin letters);\n- we will assume that two cells of the table are connected if they are of the same color and share a side; each connected region of the table must form a square.\n\nGiven $n$ and $m$, find lexicographically minimum coloring of the table that meets the described properties.",
    "tutorial": "The problem could be solved in a standard way - try to fill the table from the first cell to the last and try to put the miminum letter. Consider the first row. Obviously it begins from some letters A (to be exact $min(n, m)$ letters A). When we put some letters A in the first row, we should put several letters A in some next rows to make a square. The next letter could be only B. Describe the solution in general. Assume that we have already considered some rows. Consider row $i$. Some cells in this row could be already painted. Consider unpainted cells from left to the right. For every such cell consider its color from A to Z. Two cases should be considered: Put in this cell the minimum possible letter (neighbours have no such letter) If the previous cell in this row was not painted at the beginning of considering row $i$, now it is already painted. We should try to merge the current cell with the square of the previous cell. Choose the best case from these cases. Try to get the answer on test $n = 13$ $m = 5$ to understand the algorithm better.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "433",
    "index": "A",
    "title": "Kitahara Haruki's Gift",
    "statement": "Kitahara Haruki has bought $n$ apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.\n\nEach apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.\n\nBut unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?",
    "tutorial": "Denote $G$ as the sum of the weight of the apples. If $G / 100$ is not an even number, then the answer is obviously \"NO\". Otherwise, we need to check if there is a way of choosing apples, so that the sum of the weight of the chosen apples is exactly $\\frac{G}{2}$. A simple $O(n)$ approach would be to enumerate how many 200-gram apples do we choose, and check if we can fill the rest with 100-gram apples. We can also solve this problem using a classic knapsack DP.",
    "code": "//Template\n#include <cstdio>\n#include <iostream>\nusing namespace std;\n \nint n, a = 0, b = 0;\n \nint main(int argc, char *argv[]) {\n#ifdef KANARI\n    freopen(\"input.txt\", \"r\", stdin);\n    freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    cin >> n;\n    for (int i = 1, x; i <= n; ++i) {\n        cin >> x;\n        if (x == 100) ++a;\n        else ++b;\n    }\n    int sum = 100 * a + 200 * b;\n    if (sum % 200 != 0) cout << \"NO\" << endl;\n    else {\n        int half = sum / 2;\n        bool ans = false;\n        for (int i = 0; i <= b; ++i)\n            if (200 * i <= half && half - 200 * i <= a * 100) ans = true;\n        if (ans) cout << \"YES\" << endl;\n        else cout << \"NO\" << endl;\n    }\n    \n    fclose(stdin);\n    fclose(stdout);\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "433",
    "index": "B",
    "title": "Kuriyama Mirai's Stones",
    "statement": "Kuriyama Mirai has killed many monsters and got many (namely $n$) stones. She numbers the stones from $1$ to $n$. The cost of the $i$-th stone is $v_{i}$. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:\n\n- She will tell you two numbers, $l$ and $r (1 ≤ l ≤ r ≤ n)$, and you should tell her $\\sum_{i=1}^{r}v_{i}$.\n- Let $u_{i}$ be the cost of the $i$-th cheapest stone (the cost that will be on the $i$-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, $l$ and $r (1 ≤ l ≤ r ≤ n)$, and you should tell her $\\sum_{i=1}^{r}u_{i}$.\n\nFor every question you should give the correct answer, or Kuriyama Mirai will say \"fuyukai desu\" and then become unhappy.",
    "tutorial": "Sort sequence $v$ to obtain sequence $u$. Sorting can be done in $O(n\\log n)$ using quicksort. Now we are interested in the sum of a interval of a given sequence. This can be done by calculating the prefix sum of the sequence beforehand. That is, let $s v_{i}=\\sum_{j=1}^{t}v_{j}$. The sum of numbers in the interval $[l, r]$ would then be $sv_{r} - sv_{l - 1}$. We can deal with sequence $u$ likewise. Preprocessing takes $O(n)$ time, and answering a query is only $O(1)$. The total complexity would be $O(n\\log n+q)$.",
    "code": "#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\n \nusing namespace std;\n \n#define LL \"%I64d\"\n \nconst int maxn=100010;\n \nint n,m;\n \nlong long y[maxn],z[maxn];\n \nint main()\n{\n\tscanf(\"%d\",&n);\n\tfor (int a=1;a<=n;a++)\n\t{\n\t\tint v;\n\t\tscanf(\"%d\",&v);\n\t\ty[a]=z[a]=v;\n\t}\n\tsort(y+1,y+n+1);\n\tfor (int a=1;a<=n;a++)\n\t\tz[a]+=z[a-1],y[a]+=y[a-1];\n\tscanf(\"%d\",&m);\n\tfor (int a=1;a<=m;a++)\n\t{\n\t\tint opt,l,r;\n\t\tscanf(\"%d%d%d\",&opt,&l,&r);\n\t\tif (opt==1) printf(LL \"\\n\",z[r]-z[l-1]);\n\t\telse printf(LL \"\\n\",y[r]-y[l-1]);\n\t}\n \n\treturn 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "433",
    "index": "C",
    "title": "Ryouko's Memory Note",
    "statement": "Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.\n\nThough Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.\n\nRyouko's notebook consists of $n$ pages, numbered from 1 to $n$. To make life (and this problem) easier, we consider that to turn from page $x$ to page $y$, $|x - y|$ pages should be turned. During analyzing, Ryouko needs $m$ pieces of information, the $i$-th piece of information is on page $a_{i}$. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is $\\sum_{i=1}^{m-1}|a_{i+1}-a_{i}|$.\n\nRyouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page $x$ to page $y$, she would copy all the information on page $x$ to $y (1 ≤ x, y ≤ n)$, and consequently, all elements in sequence $a$ that was $x$ would become $y$. Note that $x$ can be equal to $y$, in which case no changes take place.\n\nPlease tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.",
    "tutorial": "Suppose we're merging page $x$ to page $y$. Obviously page $x$ should be an element of sequence $a$, otherwise merging would have no effect. Enumerate all possible values of $x$, and denote sequence $b$ as the elements of $a$ that are adjacent to an element with value $x$. If one element is adjacent to two elements with value $x$, it should appear twice in $b$. However, if one element itself is $x$, it should not appear in $b$. For example, suppose we have $a = {2, 2, 4, 1, 2, 1, 2, 3, 1}$, then sequence $b$ for $x = 2$ would be $b = {4, 1, 1, 1, 3}$, where the 6-th element appears twice. Problem remains for finding a optimum value for $y$. Let $m$ be the length of sequence $b$. When merging $x$ to $y$, the change in answer would be $\\sum_{i=1}^{m}|b_{i}-y|-\\sum_{i=1}^{m}|b_{i}-x|$ We only care about the left part, as the right part has nothing to do with $y$. We can change our problem to the following: This is, however, a classic problem. We have the following conclusion: Proof: Consider the case where $n$ is odd. Proof is similar for cases where $n$ is even. We choose an arbitary number as $x$. Suppose there are $l$ numbers on the left of $x$, and $r$ numbers on the right of $x$. If $x$ is the median, then $l = r$, so what we're going to prove is that optimal answer cannot be achieved when $l  \\neq  r$. Suppose $l < r$, consider what would happen to the answer if we add $d(d > 0)$ to $x$ (Here we assume that adding $d$ to $x$ does not affect the values of $l$ and $r$). The distance between $x$ and all the numbers on the right would decrease by $d$, while the distance between $x$ and all numbers on the left would increase by $d$. So the answer would decrease by $(r - l)d$, which is a positive value, since $l < r$. So $x$ would keep increasing until $l = r$, when optimal answer can be achieved. Thus $x$ is the median of the $n$ numbers. This brings us to our solution. Simply sort sequence $b$ and find its median, then calculate the answer. The final answer would be the optimal one from all possible values of $x$. The complexity is $O(n\\log n)$, as the sum of the length of all $b$ sequences does not exceed $2n$.",
    "code": "#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\n \nusing namespace std;\n \nconst int maxn=100010;\n \nint n,m,cnt,z[maxn];\n \npair<int,int> y[maxn<<1];\n \nint main()\n{\n\tscanf(\"%d%d\",&n,&m);\n\tfor (int a=1;a<=m;a++)\n\t\tscanf(\"%d\",&z[a]);\n\tlong long sum=0;\n\tfor (int a=2;a<=m;a++)\n\t{\n\t\tsum+=abs(z[a]-z[a-1]);\n\t\tif (z[a]==z[a-1]) continue;\n\t\ty[++cnt]=make_pair(z[a],z[a-1]);\n\t\ty[++cnt]=make_pair(z[a-1],z[a]);\n\t}\n\tsort(y+1,y+cnt+1);\n\tlong long ans=sum;\n\tfor (int a=1;a<=cnt;)\n\t{\n\t\tint b=a;\n\t\twhile (b<=cnt && y[b].first==y[a].first)\n\t\t\tb++;\n\t\tlong long delta=0;\n\t\tint mid=(a+b-1)>>1;\n\t\tfor (int c=a;c<b;c++)\n\t\t\tdelta+=abs(y[mid].second-(y[c].second==y[a].first ? y[mid].second : y[c].second))-abs(y[a].first-y[c].second);\n\t\tans=min(ans,sum+delta);\n\t\ta=b;\n\t}\n\tprintf(\"%I64d\\n\",ans); \n \n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "433",
    "index": "D",
    "title": "Nanami's Digital Board",
    "statement": "Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium.\n\nThe digital board is $n$ pixels in height and $m$ pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The $j$-th pixel of the $i$-th line is pixel $(i, j)$. The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light.\n\nNanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel $(i, j)$ belongs to a side of sub-rectangle with $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ as its upper-left and lower-right vertex if and only if it satisfies the logical condition:\n\n\\begin{center}\n(($i = x_{1}$ or $i = x_{2}$) and ($y_{1} ≤ j ≤ y_{2}$)) or (($j = y_{1}$ or $j = y_{2}$) and ($x_{1} ≤ i ≤ x_{2}$)).\n\\end{center}\n\nNanami has all the history of changing pixels, also she has some questions of the described type, can you answer them?",
    "tutorial": "Consider a similar problem: find the maximum light-block of the whole board. Constraints to this problem are the same as the original problem, but with no further operations. A brute-force idea would be to enumerate all four edges of the block, checking can be done with two-dimensional prefix sums, so the time complexity is $O(n^{4})$. Obviously it would receive a TLE verdict. Why should we enumerate all four edges? Let's enumerate the lower- and upper-edge, and now our problem is only one-dimensional, which can be easily solved in $O(n)$ time. Now our complexity is $O(n^{3})$, still not fast enough. Let's try to enumerate the lower-edge only, and now what we have is an array $up[]$, denoting the maximum \"height\" of each column. To be specific, suppose the lower-edge is row $x$, then $up[i]$ is the maximum value such that $(x, i), (x - 1, i), ..., (x - up[i] + 1, i)$ are all light. If we choose columns $l$ and $r$ as the left- and right-edge, then the area of the maximum light-block with these three sides fixed would be $\\left(r-l+1\\right)\\left(\\operatorname*{min}_{l\\leq i\\leq r}\\left\\{u p[i]\\right\\}\\right)$ Let $h=\\mathrm{min}_{l\\leq i\\leq r}\\left\\{u p[i]\\right\\}$, what if we enumerate $h$, and find the leftmost $l$ and the rightmost $r$? To be more specific, we enumerate a column $p$, and let the height of this column be the height of the block. Now we want to \"stretch\" the left and right sides of the block, so we're looking for the leftmost column $l$ such that $operatornameoperatorname*{m i n}_{i\\leq i\\leq p}\\{u p[i]\\}=u p[p]$. Similarly look for the rightmost column $r$, then the maximum light block with its lower-edge and a point in the upper-edge fixed would be $(r - l + 1) \\cdot up[p]$. This approach can be optimized with disjoint-set unions (abbr. DSU). Imagine that initially the $up[]$ array is empty. Let's add the elements of $up[]$ one by one, from the largest to the smallest. Maintain two DSUs, and denote them as $L$ and $R$.When we add an element $up[i]$, set the father of $i$ as $i + 1$ in $R$, so that $i$ will be \"skipped\" during the \"find\" operation of DSU. Similarly set the father of $i$ as $i - 1$ in $L$. Simply find the root of $i$ in $L$ and $R$, and we would have $l$ and $r$. Now this problem can be solved in quasi-quadratic time. We can actually further optimize it to quadratic time using monotonic queues, but we'll not talk about it here. Let's go back to the original problem. Suppose there are no modifications, operations only contain queries. Then we could simply maintain the $up[]$ array of every row, and similarly maintain $down[]$, $left[]$ and $right[]$ arrays. Use the approach described above to achieve quasi-linear time for the answering of a query. Now consider modifications. Modification of a single pixel only changes the values of $O(n + m)$ positions of the arrays. So modifications can be handled in linear time. The total complexity for the algorithm is $O(n^{2} + qn \\cdot  \\alpha (n))$, where $ \\alpha (n)$ is the inverse of the Ackermann function, which is often seen in the analysis of the time complexity of DSUs.",
    "code": "#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<cctype>\n#include<algorithm>\n \nusing namespace std;\n \nconst int BUF_SIZE = 30;\nchar buf[BUF_SIZE], *buf_s = buf, *buf_t = buf + 1;\n  \n#define PTR_NEXT() \\\n    { \\\n        buf_s ++; \\\n        if (buf_s == buf_t) \\\n        { \\\n            buf_s = buf; \\\n            buf_t = buf + fread(buf, 1, BUF_SIZE, stdin); \\\n        } \\\n    }\n   \n#define readint(_n_) \\\n    { \\\n        while (*buf_s != '-' && !isdigit(*buf_s)) \\\n            PTR_NEXT(); \\\n        bool register _nega_ = false; \\\n        if (*buf_s == '-') \\\n        { \\\n            _nega_ = true; \\\n            PTR_NEXT(); \\\n        } \\\n        int register _x_ = 0; \\\n        while (isdigit(*buf_s)) \\\n        { \\\n            _x_ = _x_ * 10 + *buf_s - '0'; \\\n            PTR_NEXT(); \\\n        } \\\n        if (_nega_) \\\n            _x_ = -_x_; \\\n        (_n_) = (_x_); \\\n    }\n \nconst int maxn=1010;\n \nint n,m,k,z[maxn][maxn],up[maxn][maxn],left[maxn][maxn],right[maxn][maxn],down[maxn][maxn];\n \nint main()\n{\n\treadint(n);\n\treadint(m);\n\treadint(k);\n\tfor (int a=1;a<=n;a++)\n\t\tfor (int b=1;b<=m;b++)\n\t\t{\n\t\t\treadint(z[a][b]);\n\t\t\tif (z[a][b]) \n\t\t\t{\n\t\t\t\tup[a][b]=up[a-1][b]+1;\n\t\t\t\tleft[a][b]=left[a][b-1]+1;\n\t\t\t}\n\t\t}\n\tfor (int a=n;a>=1;a--)\n\t\tfor (int b=m;b>=1;b--)\n\t\t\tif (z[a][b])\n\t\t\t{\n\t\t\t\tright[a][b]=right[a][b+1]+1;\n\t\t\t\tdown[a][b]=down[a+1][b]+1;\n\t\t\t}\n\tint opt,x,y;\n\tfor (int a=1;a<=k;a++)\n\t{\n\t\treadint(opt);\n\t\treadint(x);\n\t\treadint(y);\n\t\tif (opt==1)\n\t\t{\n\t\t\tz[x][y]^=1;\n\t\t\tfor (int b=1;b<=n;b++)\n\t\t\t\tif (z[b][y]) up[b][y]=up[b-1][y]+1;\n\t\t\t\telse up[b][y]=0;\n\t\t\tfor (int b=n;b>=1;b--)\n\t\t\t\tif (z[b][y]) down[b][y]=down[b+1][y]+1;\n\t\t\t\telse down[b][y]=0;\n\t\t\tfor (int b=1;b<=m;b++)\n\t\t\t\tif (z[x][b]) left[x][b]=left[x][b-1]+1;\n\t\t\t\telse left[x][b]=0;\n\t\t\tfor (int b=m;b>=1;b--)\n\t\t\t\tif (z[x][b]) right[x][b]=right[x][b+1]+1;\n\t\t\t\telse right[x][b]=0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint ans=0;\n\t\t\tfor (int l=y,r=y,v=up[x][y];;)\n\t\t\t{\n\t\t\t\twhile (l>=1 && up[x][l]>=v)\n\t\t\t\t\tl--;\n\t\t\t\tl++;\n\t\t\t\twhile (r<=m && up[x][r]>=v)\n\t\t\t\t\tr++;\n\t\t\t\tr--;\n\t\t\t\tans=max(ans,(r-l+1)*v);\n\t\t\t\tif (l>1)\n\t\t\t\t{\n\t\t\t\t\tif (r<m)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (up[x][l-1]>=up[x][r+1]) v=up[x][--l];\n\t\t\t\t\t\telse v=up[x][++r];\n\t\t\t\t\t}\n\t\t\t\t\telse v=up[x][--l];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (r<m) v=up[x][++r];\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int l=y,r=y,v=down[x][y];;)\n\t\t\t{\n\t\t\t\twhile (l>=1 && down[x][l]>=v)\n\t\t\t\t\tl--;\n\t\t\t\tl++;\n\t\t\t\twhile (r<=m && down[x][r]>=v)\n\t\t\t\t\tr++;\n\t\t\t\tr--;\n\t\t\t\tans=max(ans,(r-l+1)*v);\n\t\t\t\tif (l>1)\n\t\t\t\t{\n\t\t\t\t\tif (r<m)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (down[x][l-1]>=down[x][r+1]) v=down[x][--l];\n\t\t\t\t\t\telse v=down[x][++r];\n\t\t\t\t\t}\n\t\t\t\t\telse v=down[x][--l];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (r<m) v=down[x][++r];\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int l=x,r=x,v=left[x][y];;)\n\t\t\t{\n\t\t\t\twhile (l>=1 && left[l][y]>=v)\n\t\t\t\t\tl--;\n\t\t\t\tl++;\n\t\t\t\twhile (r<=n && left[r][y]>=v)\n\t\t\t\t\tr++;\n\t\t\t\tr--;\n\t\t\t\tans=max(ans,(r-l+1)*v);\n\t\t\t\tif (l>1)\n\t\t\t\t{\n\t\t\t\t\tif (r<n)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (left[l-1][y]>=left[r+1][y]) v=left[--l][y];\n\t\t\t\t\t\telse v=left[++r][y];\n\t\t\t\t\t}\n\t\t\t\t\telse v=left[--l][y];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (r<n) v=left[++r][y];\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int l=x,r=x,v=right[x][y];;)\n\t\t\t{\n\t\t\t\twhile (l>=1 && right[l][y]>=v)\n\t\t\t\t\tl--;\n\t\t\t\tl++;\n\t\t\t\twhile (r<=n && right[r][y]>=v)\n\t\t\t\t\tr++;\n\t\t\t\tr--;\n\t\t\t\tans=max(ans,(r-l+1)*v);\n\t\t\t\tif (l>1)\n\t\t\t\t{\n\t\t\t\t\tif (r<n)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (right[l-1][y]>=right[r+1][y]) v=right[--l][y];\n\t\t\t\t\t\telse v=right[++r][y];\n\t\t\t\t\t}\n\t\t\t\t\telse v=right[--l][y];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (r<n) v=right[++r][y];\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tprintf(\"%d\\n\",ans);\n\t\t} \n\t}\n \n\treturn 0;\n}",
    "tags": [
      "dsu",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "433",
    "index": "E",
    "title": "Tachibana Kanade's Tofu",
    "statement": "Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu.\n\nEach piece of tofu in the canteen is given a $m$-based number, all numbers are in the range $[l, r]$ ($l$ and $r$ being $m$-based numbers), and for every $m$-based integer in the range $[l, r]$, there exists a piece of tofu with that number.\n\nTo judge what tofu is Mapo Tofu, Tachibana Kanade chose $n$ $m$-based number strings, and assigned a value to each string. If a string appears in the number of a tofu, the value of the string will be added to the value of that tofu. If a string appears multiple times, then the value is also added that many times. Initially the value of each tofu is zero.\n\nTachibana Kanade considers tofu with values no more than $k$ to be Mapo Tofu. So now Tachibana Kanade wants to know, how many pieces of tofu are Mapo Tofu?",
    "tutorial": "A straightforward brute-force idea would be to enumerate all numbers in the interval $[l, r]$, and count how many of them have a value greater than $k$. This approach is way too slow, but nevertheless let's try optimizing it first. The enumeration part seems hard to optimize, so let's consider what is the fastest way of calculating the value of a string. This is a classic problem that can be solved using an Aho-Corasick automaton (abbr. ACA). Build an ACA with the given number strings, and simply \"walk\" in the automaton according to the string to be calculated. Consider a common method when dealing with digits - split the interval $[l, r]$ into two, $[1, r]$ minus $[1, l - 1]$. Then use DP to solve an interval, take $[1, r]$ for instance. Consider filling in the numbers one by one, we need to record in the states of the DP the position in the string, and a flag denoting whether we're \"walking on the edge of the upper bound\", that is, whether the numbers we've filled are the prefix of the upper-bound $r$. How can we use the approach above in this problem? Can we combine this approach with our ACA? The answer is yes, further record in the states of the DP the ID of the node we're currently \"standing on\" in the ACA. Consider the transfer of this DP, enumerate which number we're going to fill in, and check using our flag if the current number will be greater than the upper-bound. Appending a number to the end of our string would result in a change of the ID of the node in our ACA, so \"walk\" along the transferring edge in the ACA. What about the limit of values? Simply record the current value in our DP state, during transfer, add the value stored in the ACA's node to the value stored in our state. The tricky bit is the leading zeros. Numbers can't have leading zeros, but number strings can. How can we distinguish leading zeros from zeros in the middle of the number? We keep another flag, denoting whether we're still dealing with leading zeros. So finally our state looks like $f[len][node][val][upper_bound_flag][leading_zero_flag]$, where $len$, $node$, and $val$ are current length of number, ID of current node in ACA, and current value of number respectively. Let $N$ be the total length of all number string, and $L$ be the length of $r$, the total complexity would be $O(NLkm)$, since the number of states is $O(NLk)$ and transfer takes $O(m)$ time.",
    "code": "#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\n \nusing namespace std;\n \n#define inc(a,b) {a+=b;if (a>=mo) a-=mo;}\n#define newnode ++wmt\n \nconst int maxn=210;\nconst int maxm=22;\nconst int maxk=510;\nconst int maxp=210;\nconst int mo=1000000007;\n \nint n,m,k,llen,rlen,wmt,root,f[maxn][maxp][maxk][2],l[maxn],r[maxn],s[maxn],q[maxp];\n \nstruct node\n{\n\tint next[maxm];\n\tint value,fail;\n\tnode()\n\t{\n\t\tmemset(next,0,sizeof(next));\n\t\tvalue=fail=0;\n\t}\n}z[maxp];\n \nvoid insert(int *s,int l,int v)\n{\n\tint p=root;\n\tfor (int a=1;a<=l;a++)\n\t{\n\t\tif (!z[p].next[s[a]]) z[p].next[s[a]]=newnode;\n\t\tp=z[p].next[s[a]];\n\t}\n\tz[p].value+=v;\n}\n \nvoid build_AC()\n{\n\tint front=1,tail=1;\n\tq[1]=root;\n\tfor (;front<=tail;)\n\t{\n\t\tint now=q[front++];\n\t\tfor (int a=0;a<m;a++)\n\t\t\tif (z[now].next[a])\n\t\t\t{\n\t\t\t\tint p=z[now].fail;\n\t\t\t\twhile (p)\n\t\t\t\t{\n\t\t\t\t\tif (z[p].next[a])\n\t\t\t\t\t{\n\t\t\t\t\t\tz[z[now].next[a]].fail=z[p].next[a];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tp=z[p].fail;\n\t\t\t\t}\n\t\t\t\tif (!p) z[z[now].next[a]].fail=root;\n\t\t\t\tz[z[now].next[a]].value+=z[z[z[now].next[a]].fail].value;\n\t\t\t\tq[++tail]=z[now].next[a];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tz[now].next[a]=z[z[now].fail].next[a];\n\t\t\t\tif (!z[now].next[a]) z[now].next[a]=root;\n\t\t\t}\n\t}\n}\n \nint solve(int *y,int l)\n{\n\tif (!l) return 0;\n\tint ans=0;\n\tfor (int a=1;a<l;a++)\n\t\tfor (int b=1;b<=wmt;b++)\n\t\t\tfor (int c=0;c<=k;c++)\n\t\t\t\tinc(ans,f[a][b][c][0]);\n\tfor (int a=l;a>=1;a--)\n\t\tfor (int b=1;b<=wmt;b++)\n\t\t\tfor (int c=(a==l);c+(a!=1)<=y[a];c++)\n\t\t\t{\n\t\t\t\tint p=b,delta=0;\n\t\t\t\tp=z[p].next[c];\n\t\t\t\tdelta+=z[p].value;\n\t\t\t\tfor (int d=a+1;d<=l;d++)\n\t\t\t\t{\n\t\t\t\t\tp=z[p].next[y[d]];\n\t\t\t\t\tdelta+=z[p].value;\n\t\t\t\t}\n\t\t\t\tfor (int d=0;d<=k-delta;d++)\n\t\t\t\t\tfor (int e=0;e<=1;e++)\n\t\t\t\t\t\tinc(ans,f[a-1][b][d][e]);\n\t\t\t}\n\treturn ans;\n}\n \nint main()\n{\n\tscanf(\"%d%d%d\",&n,&m,&k);\n\tscanf(\"%d\",&llen);\n\tfor (int a=llen;a>=1;a--)\n\t\tscanf(\"%d\",&l[a]);\n\tscanf(\"%d\",&rlen);\n\tfor (int a=rlen;a>=1;a--)\n\t\tscanf(\"%d\",&r[a]);\n\troot=newnode;\n\tfor (int a=1,v;a<=n;a++)\n\t{\n\t\tint l;\n\t\tscanf(\"%d\",&l);\n\t\tfor (int b=1;b<=l;b++)\n\t\t\tscanf(\"%d\",&s[b]);\n\t\treverse(s+1,s+l+1);\n\t\tscanf(\"%d\",&v);\n\t\tinsert(s,l,v);\n\t}\n\tbuild_AC();\n\tn=max(llen,rlen);\n\tf[0][root][0][0]=1;\n\tfor (int a=0;a<n;a++)\n\t\tfor (int b=1;b<=wmt;b++)\n\t\t\tfor (int c=0;c<=k;c++)\n\t\t\t\tfor (int d=0;d<=1;d++)\n\t\t\t\t\tif (f[a][b][c][d])\n\t\t\t\t\t\tfor (int e=0;e<m;e++)\n\t\t\t\t\t\t\tif (c+z[z[b].next[e]].value<=k) inc(f[a+1][z[b].next[e]][c+z[z[b].next[e]].value][e==0],f[a][b][c][d]);\n\tl[1]--;\n\tfor (int a=1;a<=llen;a++)\n\t\tif (l[a]<0) l[a]+=m,l[a+1]--;\n\t\telse break;\n\tif (!l[llen]) llen--;\n\tprintf(\"%d\\n\",(solve(r,rlen)-solve(l,llen)+mo)%mo);\n \n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "434",
    "index": "D",
    "title": "Nanami's Power Plant",
    "statement": "Nanami likes playing games, and is also really good at it. This day she was playing a new game which involved operating a power plant. Nanami's job is to control the generators in the plant and produce maximum output.\n\nThere are $n$ generators in the plant. Each generator should be set to a generating level. Generating level is an integer (possibly zero or negative), the generating level of the $i$-th generator should be between $l_{i}$ and $r_{i}$ (both inclusive). The output of a generator can be calculated using a certain quadratic function $f(x)$, where $x$ is the generating level of the generator. Each generator has its own function, the function of the $i$-th generator is denoted as $f_{i}(x)$.\n\nHowever, there are $m$ further restrictions to the generators. Let the generating level of the $i$-th generator be $x_{i}$. Each restriction is of the form $x_{u} ≤ x_{v} + d$, where $u$ and $v$ are IDs of two different generators and $d$ is an integer.\n\nNanami found the game tedious but giving up is against her creed. So she decided to have a program written to calculate the answer for her (the maximum total output of generators). Somehow, this became your job.",
    "tutorial": "We can use a flow network to solve the problem. For each variable $x_{i}$, create $r_{i} - l_{i} + 2$ points, and denote them as $node(i, l_{i} - 1)$ to $node(i, r_{i})$. Edges are as follows: Let $C$ be the value of the minimum cut of this network. If there are no further restrictions, it is obvious that $MAX \\cdot n - C$ is the maximum profit. Now consider the restrictions. Suppose a restriction is $x_{u}  \\le  x_{v} + d$, then for each $node(u, x)$, link it to $node(v, x - d)$ (if exists) with a capacity of infinity. If there exists a solution, $MAX \\cdot n - C$ will be the optimal profit. We want to prove that the edges with infinite capacity can really restrict our choice of values for variables. Note that a valid solution is correspondent to a cut of the graph. It can be proved that if a restriction is not satisfied, there will be a augmenting path in the graph. You can verify this by drawing the graphs. And because we are looking for the minimum cut, in this case the maximum sum, there can be no valid solution with a greater sum.",
    "code": "#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\n \nusing namespace std;\n \n#define node(a,b) (b-l[a]+start[a])\n \nconst int maxn=50*201+10;\nconst int maxm=(60*210+100)*2;\nconst int INF=0x3f3f3f3f;\n \nint n,m,en,q[maxn],depth[maxn],l[60],r[60],start[60],A[60],B[60],C[60],s,t;\n \nstruct edge\n{\n\tint e,f;\n\tedge *next,*op;\n}*v[maxn],ed[maxm];\n \nvoid add_edge(int s,int e,int f)\n{\n\ten++;\n\ted[en].next=v[s];v[s]=ed+en;v[s]->e=e;v[s]->f=f;\n\ten++;\n\ted[en].next=v[e];v[e]=ed+en;v[e]->e=s;v[e]->f=0;\n\tv[s]->op=v[e];v[e]->op=v[s];\n}\n \nbool bfs()\n{\n\tint front=1,tail=1;\n\tq[1]=s;\n\tmemset(depth,0,sizeof(depth));\n\tdepth[s]=1;\n\tfor (;front<=tail;)\n\t{\n\t\tint now=q[front++];\n\t\tfor (edge *e=v[now];e;e=e->next)\n\t\t\tif (e->f && !depth[e->e])\n\t\t\t{\n\t\t\t\tdepth[e->e]=depth[now]+1;\n\t\t\t\tif (e->e==t) return true;\n\t\t\t\tq[++tail]=e->e;\n\t\t\t}\n\t}\n\treturn false;\n}\n \nint dfs(int now,int cur_flow)\n{\n\tif (now==t) return cur_flow;\n\tint rest=cur_flow;\n\tfor (edge *e=v[now];e && rest;e=e->next)\n\t\tif (e->f && depth[e->e]==depth[now]+1)\n\t\t{\n\t\t\tint new_flow=dfs(e->e,min(e->f,rest));\n\t\t\te->f-=new_flow;\n\t\t\te->op->f+=new_flow;\n\t\t\trest-=new_flow;\n\t\t}\n\tif (rest==cur_flow) depth[now]=-1;\n\treturn cur_flow-rest;\n}\n \nint dinic()\n{\n\tint ans=0;\n\twhile (bfs())\n\t\tans+=dfs(s,INF);\n\treturn ans;\n}\n \nint f(int x,int y)\n{\n\treturn y*y*A[x]+y*B[x]+C[x];\n}\n \nint main()\n{\n\tscanf(\"%d%d\",&n, &m);\n\tfor (int a=1;a<=n;a++)\n\t\tscanf(\"%d%d%d\",&A[a],&B[a],&C[a]);\n\tint maxv=-INF;\n\tint tot=0;\n\tfor (int a=1;a<=n;a++)\n\t{\n\t\tscanf(\"%d%d\",&l[a],&r[a]);\n\t\tstart[a]=tot+1;\n\t\ttot+=r[a]-l[a]+2;\n\t\tfor (int b=l[a];b<=r[a];b++)\n\t\t\tmaxv=max(maxv,f(a,b));\n\t}\n\ts=0;t=tot+1;\n\tfor (int a=1;a<=n;a++)\n\t{\n\t\tadd_edge(s,start[a],INF);\n\t\tfor (int b=l[a];b<=r[a];b++)\n\t\t\tadd_edge(node(a,b),node(a,b+1),maxv-f(a,b));\n\t\tadd_edge(node(a,r[a]+1),t,INF);\n\t}\n\tfor (int a=1;a<=m;a++)\n\t{\n\t\tint s,e,d;\n\t\tscanf(\"%d%d%d\",&s,&e,&d);\n\t\tfor (int b=l[s];b<=r[s];b++)\n\t\t\tif (b-d>=l[e] && b-d<=r[e]+1) add_edge(node(s,b),node(e,b-d),INF);\n\t}\n\tprintf(\"%d\\n\",maxv*n-dinic());\n \n\treturn 0;\n}",
    "tags": [
      "flows"
    ],
    "rating": 2900
  },
  {
    "contest_id": "434",
    "index": "E",
    "title": "Furukawa Nagisa's Tree",
    "statement": "One day, Okazaki Tomoya has bought a tree for Furukawa Nagisa's birthday. The tree is so strange that every node of the tree has a value. The value of the $i$-th node is $v_{i}$. Now Furukawa Nagisa and Okazaki Tomoya want to play a game on the tree.\n\nLet $(s, e)$ be the path from node $s$ to node $e$, we can write down the sequence of the values of nodes on path $(s, e)$, and denote this sequence as $S(s, e)$. We define the value of the sequence $G(S(s, e))$ as follows. Suppose that the sequence is $z_{0}, z_{1}...z_{l - 1}$, where $l$ is the length of the sequence. We define $G(S(s, e)) = z_{0} × k^{0} + z_{1} × k^{1} + ... + z_{l - 1} × k^{l - 1}$. If the path $(s, e)$ satisfies $G(S(s,e))\\equiv x({\\mathrm{mod~}}y)$, then the path $(s, e)$ belongs to Furukawa Nagisa, otherwise it belongs to Okazaki Tomoya.\n\nCalculating who has more paths is too easy, so they want to play something more difficult. Furukawa Nagisa thinks that if paths $(p_{1}, p_{2})$ and $(p_{2}, p_{3})$ belong to her, then path $(p_{1}, p_{3})$ belongs to her as well. Also, she thinks that if paths $(p_{1}, p_{2})$ and $(p_{2}, p_{3})$ belong to Okazaki Tomoya, then path $(p_{1}, p_{3})$ belongs to Okazaki Tomoya as well. But in fact, this conclusion isn't always right. So now Furukawa Nagisa wants to know how many triplets $(p_{1}, p_{2}, p_{3})$ are correct for the conclusion, and this is your task.",
    "tutorial": "In order not to mess things up, we use capital letters $X$, $Y$ and $K$ to denote the values in the original problem. First, we can build a directed graph with $n^{2}$ edges. Let $E(i, j)$ be the edge from node $i$ to node $j$. If path $(i, j)$ is good, the color of $E(i, j)$ is $0$, otherwise it is $1$. We want to calculate the number of triplets $(i, j, k)$ that satisfies $(i, j)$, $(j, k)$ and $(i, k)$ are all good or all not good. It equals the number of directed triangles, the color of whose three edges are the same. (The triangle is like: $i\\rightarrow j,j\\rightarrow k,i\\rightarrow k$) Calculating this is difficult, so let us calculate the number of directed triangles whose three edges are not all the same. Let $in0[i]$ be the number of in-edges of node $i$ whose color is $0$. Similarly define $in1[i]$, $out0[i]$, $out1[i]$. Let $p=\\sum_{1\\leq i\\leq n}\\left(2\\cdot o u t{\\hat{v}}[i]\\cdot o u t{\\hat{v}}[i]+2\\cdot i n0[i]\\cdot i n{\\hat{v}}|i\\right]+i n![i]\\cdot o u t{\\hat{v}}|i]+i n][i]\\cdot o u t{\\hat{v}}|i]+i n][i]\\cdot o u t{\\hat{v}}|i]\\cdot e u t{\\hat{v}}|i]+i n{\\hat{v}}|i\\rangle$ We can see that the answer is twice the number of triangles whose three edges are not all the same. So we can see the answer of the original problem is $n^{3} - p / 2$. It's certain that $out0[i] + out1[i] = in0[i] + in1[i] = n$, so we only need to calculate out0 and in0. Let us calculate $out0$ first. We can use the \"Divide and Conquer on trees\" algorithm to solve this in $O(n\\log^{2}n)$ time. Choose a root $i$ and get its subtree, we can get all the values of the paths from a node in the subtree to node $i$. We save the values and the lengths of the paths. For a path from node $j$ with value $v$ and length $l$, we want to find a node $k$ which makes $G(S(j, k))  \\equiv  X (mod Y)$. Let $H(i, j)$ be the sequence of the value of nodes on $(i, j)$ except node $i$, then $G(S(j, k)) = G(S(j, i)) + G(H(i, k)) \\cdot K^{l} = v + G(H(i, k)) \\cdot K^{l}$ As $(v + G(H(i, k)) \\cdot K^{l})  \\equiv  X (mod Y)$, so $G(H(i, k)) = (X - v) / K^{l}$. As $Y$ is a prime number, we can get $(x - v) / K^{l}$ easily. Let $z = (x - v) / K^{l}$, then the problem becomes that we need to calculate how many paths from node $i$ to a node in the subtree except node $i$, whose value is $z$, this can be done by doing binary search on a sorted array. So we can get $out0$, and $in0$ likewise. With these two arrays we can calculate the answer. The total complexity is $O(n\\log^{2}n)$.",
    "code": "//Template\n#include <cstdio>\n#include <iostream>\n#include <algorithm>\n#include <climits>\n#include <map>\n#include <vector>\nusing namespace std;\n \ntypedef long long ll;\n \n#define N 100000\nstruct edge {\n    int next, node;\n} e[N << 1 | 1];\nint head[N + 1], tot = 0;\n \ninline void addedge(int a, int b) {\n    e[++tot].next = head[a];\n    head[a] = tot, e[tot].node = b;\n}\n \nint n, mod, k, X, w[N + 1], size[N + 1], ms[N + 1], q[N + 1], cnt, kpow[N + 1], kinv[N + 1];\nbool v[N + 1];\n \ninline int pw(int a, int b) {\n    int r = 1;\n    while (b > 0) {\n        if (b & 1) r = (ll)r * a % mod;\n        a = (ll)a * a % mod;\n        b >>= 1;\n    }\n    return r;\n}\n \nvoid getSize(int x, int f) {\n    size[x] = 1, ms[x] = 0, q[++cnt] = x;\n    for (int i = head[x]; i; i = e[i].next) {\n        int node = e[i].node;\n        if (v[node] || node == f) continue;\n        getSize(node, x);\n        size[x] += size[node];\n        ms[x] = max(ms[x], size[node]);\n    }\n}\n \nint center(int x) {\n    cnt = 0, getSize(x, 0);\n    int val = INT_MAX, p = -1;\n    for (int i = 1; i <= cnt; ++i) {\n        int s = max(size[x] - size[q[i]], ms[q[i]]);\n        if (s < val) val = s, p = q[i];\n    }\n    return p;\n}\n \nint dep[N + 1], dt[N + 1], df[N + 1], in[N + 1], out[N + 1], target[N + 1];\n// depth, value on path to x, value on path from x\n \nvoid getDist(int x, int f) {\n    for (int i = head[x]; i; i = e[i].next) {\n        int node = e[i].node;\n        if (v[node] || node == f) continue;\n        dep[node] = dep[x] + 1;\n        dt[node] = (dt[x] + (ll)w[node] * kpow[dep[node]]) % mod;\n        df[node] = ((ll)df[x] * k + w[node]) % mod;\n        getDist(node, x);\n    }\n}\n \nvector <int> child[N + 1];\n \nvoid color(int x, int f, int c) {\n    child[c].push_back(x);\n    for (int i = head[x]; i; i = e[i].next) {\n        int node = e[i].node;\n        if (v[node] || node == f) continue;\n        color(node, x, c);\n    }\n}\n \nmap <int, int> from, to;\nmap <int, int> :: iterator it;\n \nvoid add(map <int, int> &h, int k, int x) {\n    it = h.find(k);\n    if (it == h.end()) h[k] = x;\n    else it->second += x;\n}\n \nint find(map <int, int> &h, int k) {\n    it = h.find(k);\n    if (it == h.end()) return 0;\n    return it->second;\n}\n \nvoid solve() {\n    from.clear(), to.clear();\n    for (int i = 1; i <= cnt; ++i) {\n        int node = q[i];\n        for (int j = 0; j < child[node].size(); ++j) {\n            int p = child[node][j];\n            add(to, dt[p], 1);\n        }\n    }\n    for (int i = 1; i <= cnt; ++i) {\n        int node = q[i];\n        for (int j = 0; j < child[node].size(); ++j) {\n            int p = child[node][j];\n            add(to, dt[p], -1);\n        }\n        for (int j = 0; j < child[node].size(); ++j) {\n            int p = child[node][j];\n            out[p] += find(to, target[p]);\n            in[p] += find(from, dt[p]);\n        }\n        for (int j = 0; j < child[node].size(); ++j) {\n            int p = child[node][j];\n            add(from, target[p], 1);\n        }\n    }\n}\n \nvoid divide(int x) {\n    x = center(x);\n    v[x] = true;\n    \n    dt[x] = df[x] = w[x], dep[x] = 0;\n    getDist(x, 0);\n    for (int i = 1; i <= cnt; ++i)\n        if (q[i] == x) {\n            if (dt[q[i]] == X) ++out[x], ++in[x];\n        } else {\n            if (dt[q[i]] == X) ++out[x], ++in[q[i]];\n            if (df[q[i]] == X) ++in[x], ++out[q[i]];\n        }\n    \n    cnt = 0;\n    for (int i = head[x]; i; i = e[i].next) {\n        int node = e[i].node;\n        if (v[node]) continue;\n        child[node].clear(), q[++cnt] = node;\n        color(node, 0, node);\n        for (int j = 0; j < child[node].size(); ++j) {\n            int p = child[node][j];\n            target[p] = ((ll)(X - df[p] + mod) * kinv[dep[p]] + w[x]) % mod;\n        }\n    }\n    // IN on the LEFT and OUT on the RIGHT\n    solve();\n    // OUT on the LEFT and IN on the RIGHT\n    reverse(q + 1, q + cnt + 1);\n    solve();\n    \n    for (int i = head[x]; i; i = e[i].next) {\n        int node = e[i].node;\n        if (v[node]) continue;\n        divide(node);\n    }\n}\n \nint main(int argc, char *argv[]) {\n#ifdef KANARI\n    freopen(\"input.txt\", \"r\", stdin);\n    freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    ios :: sync_with_stdio(false);\n    cin >> n >> mod >> k >> X;\n    for (int i = 1; i <= n; ++i) cin >> w[i];\n    for (int i = 1; i < n; ++i) {\n        int x, y;\n        cin >> x >> y;\n        addedge(x, y), addedge(y, x);\n    }\n    \n    kpow[0] = 1;\n    for (int i = 1; i <= n; ++i) {\n        kpow[i] = (ll)kpow[i - 1] * k % mod;\n        kinv[i] = pw(kpow[i], mod - 2);\n    }\n    divide(1);\n        \n    ll ans = 0LL;\n    for (int i = 1; i <= n; ++i) {\n        ans += (ll)in[i] * (n - in[i]) * 2LL;\n        ans += (ll)out[i] * (n - out[i]) * 2LL;\n        ans += (ll)in[i] * (n - out[i]) + (ll)(n - in[i]) * out[i];\n    }\n    ans = (ll)n * n * n - ans / 2LL;\n    cout << ans << endl;\n    \n    fclose(stdin);\n    fclose(stdout);\n    return 0;\n}",
    "tags": [
      "binary search",
      "divide and conquer",
      "sortings",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "435",
    "index": "A",
    "title": "Queue on Bus Stop",
    "statement": "It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups.\n\nThe bus stop queue has $n$ groups of people. The $i$-th group from the beginning has $a_{i}$ people. Every $30$ minutes an empty bus arrives at the bus stop, it can carry at most $m$ people. Naturally, the people from the first group enter the bus first. Then go the people from the second group and so on. Note that the order of groups in the queue never changes. Moreover, if some group cannot fit all of its members into the current bus, it waits for the next bus together with other groups standing after it in the queue.\n\nYour task is to determine how many buses is needed to transport all $n$ groups to the dacha countryside.",
    "tutorial": "The problem could be solved in one cycle by groups. The solution could be implemented in this way:",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "435",
    "index": "B",
    "title": "Pasha Maximizes",
    "statement": "Pasha has a positive integer $a$ without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer.\n\nHelp Pasha count the maximum number he can get if he has the time to make at most $k$ swaps.",
    "tutorial": "The problem could solved by greedy algorithm. We will try to pull maximum digits to the beginning. The algorithm could be described in this way: 1) Consider every position in the number from the first, assume that the current position is $i$ 2) Find the nearest maximum digit from the next $k$ digits of the number, assume that this digit is on position $j$ 3) If this maximum digit is greater than current digit on position $i$, then make series of swaps, push this digit to position $i$, also decrease $k$, that is do $k = k - (j - i)$",
    "tags": [
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "435",
    "index": "C",
    "title": "Cardiogram",
    "statement": "In this problem, your task is to use ASCII graphics to paint a cardiogram.\n\nA cardiogram is a polyline with the following corners:\n\n\\[\n(0;0),(a_{1};a_{1}),(a_{1}+a_{2};a_{1}-a_{2}),(a_{1}+a_{2}+a_{3};a_{1}-a_{2}+a_{3}),\\ldots,(\\sum_{i=1}^{n}a_{i};\\sum_{i=1}^{n}(-1)^{i+1}a_{i}).\n\\]\n\nThat is, a cardiogram is fully defined by a sequence of positive integers $a_{1}, a_{2}, ..., a_{n}$.\n\nYour task is to paint a cardiogram by given sequence $a_{i}$.",
    "tutorial": "This problem is technical, you should implement what is written in the statement. First, you need to calc coordinates of all points of the polyline. Also create matrix for the answer. Coordinate $y$ could become negative, so it is useful to double the sizes of the matrix and move the picture up to $1000$. In the end you should print the answer without unnecessary empty rows. To paint the cardiogram you should consider every consecutive pair of points of the polyline and set characters in the answer matrix between them. If the polyline goes up then set slash, otherwise set backslash. To understand the solution better please paint the first test case on the paper, mark coordinates of the points and find what values to set in cycles in your program.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "435",
    "index": "D",
    "title": "Special Grid",
    "statement": "You are given an $n × m$ grid, some of its nodes are black, the others are white. Moreover, it's not an ordinary grid — each unit square of the grid has painted diagonals.\n\nThe figure below is an example of such grid of size $3 × 5$. Four nodes of this grid are black, the other $11$ nodes are white.\n\nYour task is to count the number of such triangles on the given grid that:\n\n- the corners match the white nodes, and the area is positive;\n- all sides go along the grid lines (horizontal, vertical or diagonal);\n- no side contains black nodes.",
    "tutorial": "Values $n$ and $m$ are not so large, so the solution with complexity $O(max(n, m)^{3})$ should pass. It means that you should consider all triangles and check all conditions in $O(1)$. To make this check you should precalc arrays of partial sums on all diagonals, rows and columns. After that you could check, that there is no black nodes on the side using one sum-query. Some hints about this problem and the implementation: all correct triangles are isosceles right triangles; either all legs or hypotenuse of the triangle is parallel to the sides of the grid; if you know how to solve the problem for two types of the triangles, you can get the whole solution making 4 rotates of the matrix.",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "435",
    "index": "E",
    "title": "Special Graph",
    "statement": "In this problem you will need to deal with an $n × m$ grid graph. The graph's vertices are the nodes of the $n × m$ grid. The graph's edges are all the sides and diagonals of the grid's unit squares.\n\nThe figure below shows a $3 × 5$ graph. The black lines are the graph's edges, the colored circles are the graph's vertices. The vertices of the graph are painted on the picture for a reason: the coloring is a correct vertex coloring of the $3 × 5$ graph into four colors. A graph coloring is correct if and only if each vertex is painted and no two vertices connected by an edge are painted the same color.\n\nYou are given the size of the grid graph $n × m$ and the colors of some of its vertices. Find any way how to paint the unpainted vertices of the graph in 4 colors to make the final coloring a correct vertex graph coloring. If there is no such correct vertex coloring, say that the answer doesn't exist.",
    "tutorial": "To solve this problem you have to paint different correct colorings on the paper. After it you could observe that there are two types of them: vertical and horizontal. Vertical colorings looks like this: acbcbd... bdadac... acbcbd... bdadac... acbcbd... bdadac... ...... In other words, each vertical has only two colors, odd verticals have equal colors, even verticals have two others. The order of the colors on every vertical could be arbitrary. Horizontal colorings are the same, they are rotated by 90 degrees. Of course, there are both vertical and horizontal colorings, but it doesn't change the solution. So, you should consider every type of described colorings and check them. That is, you could choose what colors are on the verticals or what colors are on horizontals and check that obtained coloring matches the given matrix. The solution's complexity is $O(n  \\times  m)$.",
    "tags": [],
    "rating": 2500
  },
  {
    "contest_id": "436",
    "index": "A",
    "title": "Feed with Candy",
    "statement": "The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem.\n\nOne day, Om Nom visited his friend Evan. Evan has $n$ candies of two types (fruit drops and caramel drops), the $i$-th candy hangs at the height of $h_{i}$ centimeters above the floor of the house, its mass is $m_{i}$. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most $x$ centimeter high jumps. When Om Nom eats a candy of mass $y$, he gets stronger and the height of his jump increases by $y$ centimeters.\n\nWhat maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?",
    "tutorial": "In this problem types of eaten candies must alternate. It means that the type of first eaten candy dictated the types of all the following candies. There are only two possible types so we should consider each type as a type of first eaten candy separatelly and then pick the most optimal. So, what if Om Nom wants to eat a candy of type $t$ and can jump up to $h$? It is obvious that best option is to eat a candy with maximal mass among all the candies he can eat at this time.",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "436",
    "index": "B",
    "title": "Om Nom and Spiders",
    "statement": "Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.\n\nThe park can be represented as a rectangular $n × m$ field. The park has $k$ spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.\n\nOm Nom isn't yet sure where to start his walk from but he definitely wants:\n\n- to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders);\n- to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park).\n\nWe know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.\n\nEach time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.",
    "tutorial": "Let us number columns with integers from $0$ from left to right and rows from $0$ from top to bottom. In the cell $(x, y)$ at the time $t$ only four spiders can be at this cell: Spider, which is moving left and started at $(x, y + t)$. Spider, which is moving right and started at $(x, y - t)$. Spider, which is moving up and started at $(x + t, y)$. Spider, which is moving down and started at $(x - t, y)$. Let iterate through all possible starting positions of Om Nom. Consider that he starts at column $y$. At time $0$ all spiders are on their initial positions and Om Nom is at $(0, y)$. There is no spiders at row $0$, so at time $0$ Om Nom can not meet any spiders. When Om Nom is at cell $(x, y)$, it means that $x$ units of time passed after the start. So to calculate the number of spiders, that Om Nom meets it is enought to check only $4$ cells stated above.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "436",
    "index": "C",
    "title": "Dungeons and Candies",
    "statement": "During the loading of the game \"Dungeons and Candies\" you are required to get descriptions of $k$ levels from the server. Each description is a map of an $n × m$ checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as \".\" on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same.\n\nWhen you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level $A$:\n\n- You can transmit the whole level $A$. Then you need to transmit $n·m$ bytes via the network.\n- You can transmit the difference between level $A$ and some previously transmitted level $B$ (if it exists); this operation requires to transmit $d_{A, B}·w$ bytes, where $d_{A, B}$ is the number of cells of the field that are different for $A$ and $B$, and $w$ is a constant. Note, that you should compare only the corresponding cells of levels $A$ and $B$ to calculate $d_{A, B}$. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other.\n\nYour task is to find a way to transfer all the $k$ levels and minimize the traffic.",
    "tutorial": "Let's consider a weighted undirected graph with $k + 1$ vertex. Label the vertices with numbers from $0$ to $k$. Vertices from $1$ to $k$ correspond to levels. For each pair of levels $i$ and $j$ add an edge between vertices $i$ and $j$ with weight equal to the cost of transferring one level as a difference from the other level. For each level $i$ add an edge from vertex $0$ to vertex $i$ with weight equal to $n \\cdot m$, i.e. cost of transmitting the whole level. Each way to transmit levels defined an spanning tree of this graph. So to solve the problem, we must find a minimal spanning tree of this graph.",
    "tags": [
      "dsu",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "436",
    "index": "D",
    "title": "Pudding Monsters",
    "statement": "Have you ever played Pudding Monsters? In this task, a simplified one-dimensional model of this game is used.\n\nImagine an infinite checkered stripe, the cells of which are numbered sequentially with integers. Some cells of the strip have monsters, other cells of the strip are empty. All monsters are made of pudding, so if there are two monsters in the neighboring cells, they stick to each other (literally). Similarly, if several monsters are on consecutive cells, they all stick together in one block of monsters. We will call the stuck together monsters a block of monsters. A detached monster, not stuck to anyone else, is also considered a block.\n\nIn one move, the player can take any block of monsters and with a movement of his hand throw it to the left or to the right. The selected monsters will slide on until they hit some other monster (or a block of monsters).\n\nFor example, if a strip has three monsters in cells $1$, $4$ and $5$, then there are only four possible moves: to send a monster in cell $1$ to minus infinity, send the block of monsters in cells $4$ and $5$ to plus infinity, throw monster $1$ to the right (it will stop in cell $3$), throw a block of monsters in cells $4$ and $5$ to the left (they will stop in cells $2$ and $3$).\n\nSome cells on the strip are marked with stars. These are the special cells. The goal of the game is to make the largest possible number of special cells have monsters on them.\n\nYou are given the numbers of the special cells on a strip as well as the initial position of all monsters. What is the maximum number of special cells that will contain monsters in the optimal game?",
    "tutorial": "This problem can be solved using dynamic programming. Let's introduce some designations: $sum(l, r)$ - number of special cells on the segment $[l, r]$, $z_{i}$ - maximal number of covered special cells using only first $i$ monsters, $d_{i}$ - maximal number of covered special cells using only first $i$ monsters and with $i$-th monster not moving. How to calculate $d_{i}$. Let's denote $i$-th monster position as $r$. Let's iterate through all special cells to the left of $i$-th monster. Let's denote current special cell position as $l$. Let's consider the situation when this cell is the leftmost special cell in the block of monsters with $i$-th monster in it. So we need $r - l$ additional monsters to get to this cell from monster $i$. So the value of $d_{i}$ can be updated with $z_{i - (r - l)} + sum(l, r)$. Now, after we computed new value of $d_{i}$, we need to update some values of $z_{j}$. Let's denote $i$-th monster position as $l$. Let's iterate through all special cells to the right of $i$-th monster. Let's denote current special cell position as $r$. Let's consider the situation when this cell is the rightmost special cell in the block of monsters with $i$-th monster in it. So we need $r - l$ additional monsters to get to this cell from monster $i$. So we can update the value $z_{i + (r - l)}$ with $d_{i} + sum(l + 1, r)$. Also, $z_{i}$ should be updated with $z_{i - 1}$. So the solution works in $O(n \\cdot m)$ because for each of $n$ monsters we iterate through all $m$ special cells and for a fixed monster-cell pair all computing is done in $O(1)$. There are some details about monsters, that are merged at the initial state, but they are pretty easy to figure out.",
    "tags": [
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "436",
    "index": "E",
    "title": "Cardboard Box",
    "statement": "Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels.\n\nImagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called \"Cardboard Box\"). Each level is characterized by two integers: $a_{i}$ — how long it takes to complete the level for one star, $b_{i}$ — how long it takes to complete the level for two stars $(a_{i} < b_{i})$.\n\nYou want to open the next box as quickly as possible. So, you need to earn at least $w$ stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels.",
    "tutorial": "In this task you have to come with the proper greedy algorithms. Several algorithms will fit, let's describe one of them: From that point we will consider that the levels are sorted by increasing value of $b$. Let's look at some optimal solution (a set of completed levels). From levels that we completed for two stars, select the level $k$ with the largest $b[k]$. It turns out that all levels that stand before $k$ (remember, the levels are sorted) should be completed for at least one star. Otherwise, we could complete some of the previous levels instead of the level $k$. This won't increase the cost. Let's fix a prefix of the first $L$ levels and solve the problem with the assumption that each of the selected levels should be completed. Additionally, we will assume that all levels that are completed for two stars are within this prefix (as was shown before, such prefix of $L$ levels always exists for some optimal solution). As we will surely complete this $L$ levels, we can imagine that we have initially completed all of the for just one star. So, we have $w - L$ more stars to get. We can get these stars either by completing some of the levels that are outside our prefix for one star, or by completing some of the first $L$ levels for two stars instead of one star. It's clear that we just have to choose $w - L$ cheapest options, which correspond to $w - L$ smallest numbers among the following: $b[i] - a[i]$ for $i  \\le  L$ and $a[i]$ for $i > L$. Computing the sum of these smallest values can be done with a data structure like Cartesian tree or BIT. The described solution has time completixy of $O(n log n)$.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "436",
    "index": "F",
    "title": "Banners",
    "statement": "All modern mobile applications are divided into free and paid. Even a single application developers often release two versions: a paid version without ads and a free version with ads.\n\nSuppose that a paid version of the app costs $p$ ($p$ is an integer) rubles, and the free version of the application contains $c$ ad banners. Each user can be described by two integers: $a_{i}$ — the number of rubles this user is willing to pay for the paid version of the application, and $b_{i}$ — the number of banners he is willing to tolerate in the free version.\n\nThe behavior of each member shall be considered strictly deterministic:\n\n- if for user $i$, value $b_{i}$ is at least $c$, then he uses the free version,\n- otherwise, if value $a_{i}$ is at least $p$, then he buys the paid version without advertising,\n- otherwise the user simply does not use the application.\n\nEach user of the free version brings the profit of $c × w$ rubles. Each user of the paid version brings the profit of $p$ rubles.\n\nYour task is to help the application developers to select the optimal parameters $p$ and $c$. Namely, knowing all the characteristics of users, for each value of $c$ from $0$ to $(max b_{i}) + 1$ you need to determine the maximum profit from the application and the corresponding parameter $p$.",
    "tutorial": "Task F was the hardest one in the problemset. To better understand the solution, let's look at the task from the geometrical point of view. Imagine that people are point in the $Opc$ plane (value of $p$ and $q$ are points' coordinates). Then for each line horizontal $c = i$ we have to find such vertical line $p = j$ that maximizes some target function. The function is computed as follows: (number of points not below $c = i$, multiplied by $w \\cdot i$) plus (number of points below $c = i$ and not to the left of $p = j$, multiplied by $j$). Let's move scanning line upwards (consider values $c = 0$, then $c = 1$, etc). For each value of $p$ we will store the value $d[p]$ - the value of the target function with the current value of $c$ and this value of $p$. The problem is: if we have such array $d[]$ for the value $c$, how to recompute it for the value $c + 1$? Let's look at all people that will be affected by the increase of $c$: these are the people with $b[i] = c$. With the current $c$ they are still using free version, after the increase they won't. Each of these people makes the following effect to the array: $d[1] + = 1$, $d[2] + = 2$, ..., $d[b[i]] + = b[i]$ Now the task can be reduced to the problem related with data structures. There are two types of queries: add the increasing arithmetical progression to the prefix of the array and retrieve the maximum value of the array. One of the way to solve it is to use sqrt-decomposition. Let's divide all queries into groups of size $sqrt(q)$. Let's denote the queries from the group as a sequence: $p_{1}, p_{2}, ..., p_{k}$ $(k = sqrt(q))$. For query $p_{i}$ we should perform assignments $d[1] + = 1$, $d[2] + = 2$, ..., $d[p_{i}] + = p_{i}$. Imagine we already preformed all the queries. Each value of new array $d[]$ can be represented as $d[i] = oldD[i] + i \\cdot coef[i]$, where $coef[i]$ is the number of $p_{j}$ $(p_{j} > i)$. One can notice that array $coef$ contains at most $sqrt(q)$ distinct values, additionally this array can be splitted into $O(sqrt(q))$ parts such that all elements from the same part will be the same. This is the key observation. We will divide array $coef$ into parts. And for each part will maintain lower envelope of the lines $y = d[i] + i \\cdot x$. So, we will have $O(sqrt(q))$ lower envelopes. Each envelope will help us to get maximum value among the segment of array $d[i](oldD[i] + i \\cdot coef[i])$. As for each $i$ from some segment factor $coef[i]$ is containt we can just pick $y$-coordinate with $x = coef[i]$ of corresponding lower envelope. Described solution has time complexity of $O(MAXX \\cdot sqrt(MAXX))$, where $MAXX$ is the maximum value among $a[i]$ and $b[i]$.",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "437",
    "index": "A",
    "title": "The Child and Homework",
    "statement": "Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.\n\nFortunately the child knows how to solve such complicated test. The child will follow the algorithm:\n\n- If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great.\n- If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).\n\nYou are given a multiple-choice questions, can you predict child's choose?",
    "tutorial": "We enumerate each choice $i$, and then enumerate another choice $j$ $(j  \\neq  i)$, let $cnt = 0$ at first, if choice $j$ is twice longer than $i$ let $cnt = cnt + 1$, if choice $j$ is twice shorter than $i$ let $cnt = cnt - 1$. So $i$ is great if and only if $cnt = 3$ or $cnt = - 3$. If there is exactly one great choice, output it, otherwise output C.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "437",
    "index": "B",
    "title": "The Child and Set",
    "statement": "At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.\n\nFortunately, Picks remembers something about his set $S$:\n\n- its elements were distinct integers from $1$ to $limit$;\n- the value of $\\textstyle\\sum_{x\\in S}l o w b i t(x)$ was equal to $sum$; here $lowbit(x)$ equals $2^{k}$ where $k$ is the position of the first one in the binary representation of $x$. For example, $lowbit(10010_{2}) = 10_{2}, lowbit(10001_{2}) = 1_{2}, lowbit(10000_{2}) = 10000_{2}$ (binary representation).\n\nCan you help Picks and find any set $S$, that satisfies all the above conditions?",
    "tutorial": "We could deal with this by digits. Because $lowbit(x)$ is taking out the lowest $1$ of the number $x$, we can enumerate the number of the lowest zero. Then, if we enumerate $x$ as the number of zero, we enumerate $a$ as well, which $a  \\times  2^{x}$ is no more than $limit$ and $a$ is odd. We can find out that $lowbit(a  \\times  2^{x}) = 2^{x}$. In this order, we would find out that the $lowbit()$ we are considering is monotonically decresing. Because for every two number $x, y$, $lowbit(x)$ is a divisor of $lowbit(y)$ or $lowbit(y)$ is a divisor of $lowbit(x)$. We can solve it by greedy. When we enumerate $x$ by descending order, we check whether $2^{x}$ is no more than $sum$, and check whether there is such $a$. We minus $2^{x}$ from $sum$ if $x$ and $a$ exist. If at last $sum$ is not equal to 0, then it must be an impossible test. Why? Because if we don't choose a number whose $lowbit = 2^{x}$, then we shouldn't choose two numbers whose $lowbit = 2^{x - 1}$. (Otherwise we can replace these two numbers with one number) If we choose one number whose $lowbit = 2^{x - 1}$, then we can choose at most one number whose $lowbit = 2^{x - 2}$, at most one number whose $lowbit = 2^{x - 3}$ and so on. So the total sum of them is less than $2^{x}$ and we can't merge them into $sum$. If we don't choose one number whose $lowbit = 2^{x - 1}$, then it's just the same as we don't choose one number whose $lowbit = 2^{x}$. So the total time complexity is $O(limit)$.",
    "tags": [
      "bitmasks",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "437",
    "index": "C",
    "title": "The Child and Toy",
    "statement": "On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.\n\nThe toy consists of $n$ parts and $m$ ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part $i$ as $v_{i}$. The child spend $v_{f1} + v_{f2} + ... + v_{fk}$ energy for removing part $i$ where $f_{1}, f_{2}, ..., f_{k}$ are the parts that are directly connected to the $i$-th and haven't been removed.\n\nHelp the child to find out, what is the minimum total energy he should spend to remove all $n$ parts.",
    "tutorial": "The best way to delete all n nodes is deleting them in decreasing order of their value. Proof: Consider each edge $(x, y)$, it will contribute to the total cost $v_{x}$ or $v_{y}$ when it is deleted. If we delete the vertices in decreasing order, then it will contribute only $min(v_{x}, v_{y})$, so the total costs is the lowest.",
    "tags": [
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "437",
    "index": "D",
    "title": "The Child and Zoo",
    "statement": "Of course our child likes walking in a zoo. The zoo has $n$ areas, that are numbered from $1$ to $n$. The $i$-th area contains $a_{i}$ animals in it. Also there are $m$ roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.\n\nOur child is very smart. Imagine the child want to go from area $p$ to area $q$. Firstly he considers all the simple routes from $p$ to $q$. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as $f(p, q)$. Finally, the child chooses one of the routes for which he writes down the value $f(p, q)$.\n\nAfter the child has visited the zoo, he thinks about the question: what is the average value of $f(p, q)$ for all pairs $p, q$ $(p ≠ q)$? Can you answer his question?",
    "tutorial": "First, there is nothing in the graph. We sort all the areas of the original graph by their animal numbers in decreasing order, and then add them one by one. When we add area $i$, we add all the roads $(i, j)$, where $j$ is some area that has been added. After doing so, we have merged some connected components. If $p$ and $q$ are two areas in different connected components we have merged just then, $f(p, q)$ must equals the $v_{i}$, because they are not connected until we add node $i$. So we use Union-Find Set to do such procedure, and maintain the size of each connected component, then we can calculate the answer easily.",
    "tags": [
      "dsu",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "437",
    "index": "E",
    "title": "The Child and Polygon",
    "statement": "This time our child has a simple polygon. He has to find the number of ways to split the polygon into non-degenerate triangles, each way must satisfy the following requirements:\n\n- each vertex of each triangle is one of the polygon vertex;\n- each side of the polygon must be the side of exactly one triangle;\n- the area of intersection of every two triangles equals to zero, and the sum of all areas of triangles equals to the area of the polygon;\n- each triangle must be completely inside the polygon;\n- \\textbf{each side of each triangle must contain exactly two vertices of the polygon}.\n\nThe picture below depicts an example of a correct splitting.\n\nPlease, help the child. Calculate the described number of ways modulo $1000000007$ $(10^{9} + 7)$ for him.",
    "tutorial": "In this problem, you are asked to count the triangulations of a simple polygon. First we label the vertex of polygon from $0$ to $n - 1$. Then we let $f[i][j]$ be the number of triangulations from vertex $i$ to vertex $j$. (Suppose there is no other vertices and there is an edge between $i$ and $j$) If the line segment $(i, j)$ cross with the original polygon or is outside the polygon, $f[i][j]$ is just 0. We can check it in $O(n)$ time. Otherwise, we have $f[i][j]=\\sum_{i<k<i}f[i][k]*f[k][j]$, which means we split the polygon into the triangulation from vertex $i$ to vertex $k$, a triangle $(i, k, j)$ and the triangulation from vertex $k$ to vertex $j$. We can sum these terms in $O(n)$ time. Finally,the answer is $f[0][n - 1]$. It's obvious that we didn't miss some triangulation. And we use a triangle to split the polygon each time, so if the triangle is different then the triangulation must be different, too. So we didn't count some triangulation more than once. So the total time complexity is $O(n^{3})$, which is sufficient for this problem.",
    "tags": [
      "dp",
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "438",
    "index": "D",
    "title": "The Child and Sequence",
    "statement": "At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.\n\nFortunately, Picks remembers how to repair the sequence. Initially he should create an integer array $a[1], a[2], ..., a[n]$. Then he should perform a sequence of $m$ operations. An operation can be one of the following:\n\n- Print operation $l, r$. Picks should write down the value of $\\sum_{i=1}^{r}a[i]$.\n- Modulo operation $l, r, x$. Picks should perform assignment $a[i] = a[i] mod x$ for each $i$ $(l ≤ i ≤ r)$.\n- Set operation $k, x$. Picks should set the value of $a[k]$ to $x$ (in other words perform an assignment $a[k] = x$).\n\nCan you help Picks to perform the whole sequence of operations?",
    "tutorial": "The important idea of this problem is the property of $\\mathrm{mod}$. Let $r=x{\\mathrm{~mod~}}p$. So, $x=k\\times p+r,k\\in\\mathbb{N}$. If $k = 0$, $x\\ {\\mathrm{mod}}\\ p$ remains to be $x$. If $k  \\neq  0$, $x\\;\\mathrm{mod}\\;p=r={\\frac{2r}{2}}<{\\frac{p+r}{2}}\\leq{\\frac{k\\times p+r}{2}}\\leq{\\frac{x}{2}}$. We realize every time a change happening on $x$, $x$ will be reduced by at least a half. So let the energy of $x$ become $\\log_{2}x$. Every time when we modify $x$, it may take at least $1$ energy. The initial energy of the sequence is $O(n\\log a_{i})$. We use a segment tree to support the query to the maximum among an interval. When we need to deal with the operation $2$, we modify the maximum of the segment until it is less than $x$. Now let's face with the operation 3. Every time we modify an element on the segment tree, we'll charge a element with $O(\\log a_{i})$ power. So the total time complexity is : $O(n\\log n\\log a_{i})$. By the way, we can extend the operation $3$ to assign all the elements in the interval to the same number in the same time complexity. This is an interesting idea also, but a bit harder. You can think of it.",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "438",
    "index": "E",
    "title": "The Child and Binary Tree",
    "statement": "Our child likes computer science very much, especially he likes binary trees.\n\nConsider the sequence of $n$ distinct positive integers: $c_{1}, c_{2}, ..., c_{n}$. The child calls a vertex-weighted rooted binary tree good if and only if for every vertex $v$, the weight of $v$ is in the set ${c_{1}, c_{2}, ..., c_{n}}$. Also our child thinks that the weight of a vertex-weighted tree is the sum of all vertices' weights.\n\nGiven an integer $m$, can you for all $s$ $(1 ≤ s ≤ m)$ calculate the number of good vertex-weighted rooted binary trees with weight $s$? Please, check the samples for better understanding what trees are considered different.\n\nWe only want to know the answer modulo $998244353$ ($7 × 17 × 2^{23} + 1$, a prime number).",
    "tutorial": "Let $f[s]$ be the number of good vertex-weighted rooted binary trees whose weight exactly equal to $s$, then we have: $f[0] = 1$ $f[s]=\\sum_{w\\in\\{c_{1},\\ldots,c_{n}\\}}\\sum_{i}f[i]\\times f[s-w-i]$ Let F(z) be the generating function of f. That is, $F(z)=\\sum_{k>0}f[k]z^{k}$ And then let $C(z)=\\sum_{k=1}^{n}z^{c_{k}}$ So we have: $F(z) = C(z)F(z)^{2} + 1$ ``$+ 1$'' is for $f[0] = 1$. Solve this equation we have: $f[s]={\\frac{1-{\\sqrt{1-4C(z)}}}{2C(z)}}={\\frac{4C(z)}{2C(z)(1+{\\sqrt{1-4C(z)}})}}={\\frac{2}{1+{\\sqrt{1-4C(z)}}}}$ So the remaining question is: how to calculate the multiplication inverse of a power series and the square root of a power series? There is an interesting algorithm which calculate the inverse of a power series $F(z)$: We use $f(z)  \\equiv  g(z) (mod z^{n})$ to denote that the first $n$ terms of $f(z)$ and $g(z)$ are the same. We can simply calculate a formal power series $R_{1}(z)$ which satisfies $R_{1}(z)F(z)  \\equiv  1 (mod z^{1})$ Next, if we have $R_{n}(z)$ which satisfies $R_{n}(z)F(z)  \\equiv  1 (mod z^{n})$, we will get: $(R_{n}(z)F(z) - 1)^{2}  \\equiv  0 (mod z^{2n})$ $R_{n}(z)^{2}F(z)^{2} - 2R_{n}(z)F(z) + 1  \\equiv  0 (mod z^{2n})$ $1  \\equiv  2R_{n}(z)F(z) - R_{n}(z)^{2}F(z)^{2} (mod z^{2n})$ $R_{2n}(z)  \\equiv  2R_{n}(z) - R_{n}(z)^{2}F(z) (mod z^{2n})$ We can simplely use Fast Fourier Transform to deal with multiplication. Note the unusual mod $998244353$ ($7  \\times  17  \\times  2^{23} + 1)$, thus we can use Number Theoretic Transform. By doubling $n$ repeatedly, we can get the first $n$ terms of the inverse of $F(z)$ in $O(n\\log n)$ time. It's because that $T(n)=T(n/2)+O(n\\log n)=O(n\\log n)$ We can just use the idea of this algorithm to calculate the square root of a power series $F(z)$: We can simply calculate a power series $S_{1}(z)$ which satisfies $S_{1}(z)^{2}  \\equiv  F(z) (mod z^{2n})$ Next, if we have $S_{n}(z)$ which satisfies $S_{n}(z)^{2}  \\equiv  F(z) (mod z^{n})$, we will get: $(S_{n}(z)^{2} - F(z))^{2}  \\equiv  0 (mod z^{2n})$ $S_{n}(z)^{4} - 2S_{n}(z)^{2}F(z) + F(z)^{2}  \\equiv  0 (mod z^{2n})$ $S_{n}(z)^{2} - 2F(z) + F(z)^{2}S_{n}(z)^{ - 2}  \\equiv  0 (mod z^{2n})$ $4F(z)  \\equiv  S_{n}(z)^{2} + 2F(z) + F(z)^{2}S_{n}(z)^{ - 2} (mod z^{2n})$ $4F(z)  \\equiv  (S_{n}(z) + F(z)S_{n}(z)^{ - 1})^{2} (mod z^{2n})$ $F(z)\\equiv(\\textstyle{{\\frac{1}{2}}}(S_{n}(z)+F(z)S_{n}(z)^{-1}))^{2}\\,\\,(m o d\\ z^{2n})$ So, $S_{2n}(z)\\equiv{\\textstyle{\\frac{1}{2}}}(S_{n}(z)+F(z)S_{n}(z)^{-1})~(m o d~z^{2n})$ By doubling $n$ repeatedly, we can get the first $n$ terms of the square root of $F(z)$ in $O(n\\log n)$ time. That's all. What I want to share with others is this beautiful doubling algorithm. So the total time complexity of the solution to the original problem is $O(m\\log m)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdio>\n#include <algorithm>\nusing namespace std;\n\ntypedef long long s64;\n\nconst int Mod = 998244353;\nconst int Mod_G = 3;\n\nconst int MaxCN = 100000;\nconst int MaxS = 100000;\n\nstruct modint\n{\n\tint a;\n\n\tmodint(){}\n\tmodint(int _a)\n\t{\n\t\ta = _a % Mod;\n\t\tif (a < 0)\n\t\t\ta += Mod;\n\t}\n\tmodint(s64 _a)\n\t{\n\t\ta = _a % Mod;\n\t\tif (a < 0)\n\t\t\ta += Mod;\n\t}\n\n\tinline modint operator-() const\n\t{\n\t\treturn -a;\n\t}\n\tinline modint inv() const\n\t{\n\t\tint x1 = 1, x2 = 0, x3 = Mod;\n\t\tint y1 = 0, y2 = 1, y3 = a;\n\t\twhile (y3 != 1)\n\t\t{\n\t\t\tint k = x3 / y3;\n\t\t\tx1 -= y1 * k, x2 -= y2 * k, x3 -= y3 * k;\n\t\t\tswap(x1, y1), swap(x2, y2), swap(x3, y3);\n\t\t}\n\t\treturn y2 >= 0 ? y2 : y2 + Mod;\n\t}\n\n\tfriend inline modint operator+(const modint &lhs, const modint &rhs)\n\t{\n\t\treturn lhs.a + rhs.a;\n\t}\n\tfriend inline modint operator-(const modint &lhs, const modint &rhs)\n\t{\n\t\treturn lhs.a - rhs.a;\n\t}\n\tfriend inline modint operator*(const modint &lhs, const modint &rhs)\n\t{\n\t\treturn (s64)lhs.a * rhs.a;\n\t}\n\tfriend inline modint operator/(const modint &lhs, const modint &rhs)\n\t{\n\t\treturn lhs * rhs.inv();\n\t}\n\n\tinline modint div2() const\n\t{\n\t\treturn (s64)a * ((Mod + 1) / 2);\n\t}\n};\n\ninline modint modpow(const modint &a, const int &n)\n{\n\tmodint res = 1;\n\tmodint t = a;\n\tfor (int i = n; i > 0; i >>= 1)\n\t{\n\t\tif (i & 1)\n\t\t\tres = res * t;\n\t\tt = t * t;\n\t}\n\treturn res;\n}\n\nconst int MaxN = 131072;\nconst int MaxTN = MaxN * 2;\n\nmodint prePowG[MaxTN];\n\nvoid fft(int n, modint *a, int step, modint *out)\n{\n\tif (n == 1)\n\t{\n\t\tout[0] = a[0];\n\t\treturn;\n\t}\n\tint m = n / 2;\n\tfft(m, a, step + 1, out);\n\tfft(m, a + (1 << step), step + 1, out + m);\n\tfor (int i = 0; i < m; i++)\n\t{\n\t\tmodint e = out[i], o = out[i + m] * prePowG[i << step];\n\t\tout[i] = e + o;\n\t\tout[i + m] = e - o;\n\t}\n}\n\nvoid poly_mulTo(int n, modint *f, modint *g)\n{\n\t/*static modint c[MaxN];\n\tfor (int i = 0; i < n; i++)\n\t\tc[i] = 0;\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; i + j < n; j++)\n\t\t\tc[i + j] = c[i + j] + f[i] * g[j];\n\tcopy(c, c + n, f);\n\treturn;*/\n\n\tint tn = n * 2;\n\tstatic modint tf[MaxTN], tg[MaxTN];\n\tcopy(f, f + n, tf), fill(tf + n, tf + tn, modint(0));\n\tcopy(g, g + n, tg), fill(tg + n, tg + tn, modint(0));\n\n\tmodint rg = modpow(Mod_G, (Mod - 1) / tn);\n\tprePowG[0] = 1;\n\tfor (int i = 1; i < tn; i++)\n\t\tprePowG[i] = prePowG[i - 1] * rg;\n\n\tstatic modint dftF[MaxTN], dftG[MaxTN];\n\tfft(tn, tf, 0, dftF);\n\tfft(tn, tg, 0, dftG);\n\n\tfor (int i = 0; i < tn; i++)\n\t\tdftF[i] = dftF[i] * dftG[i];\n\n\treverse(prePowG + 1, prePowG + tn);\n\tfft(tn, dftF, 0, tf);\n\treverse(prePowG + 1, prePowG + tn);\n\n\tmodint revTN = modint(tn).inv();\n\tfor (int i = 0; i < n; i++)\n\t\tf[i] = tf[i] * revTN;\n}\n\nvoid poly_inv(int n, modint *f, modint *r)\n{\n\t// assert(f[0] == 1)\n\tfill(r, r + n, modint(0));\n\tr[0] = 1;\n\tfor (int m = 2; m <= n; m <<= 1)\n\t{\n\t\tint h = m / 2;\n\t\tstatic modint nr[MaxN];\n\t\tcopy(f, f + m, nr);\n\t\tpoly_mulTo(m, nr, r);\n\t\tfill(nr, nr + h, modint(0));\n\t\tfor (int i = h; i < m; i++)\n\t\t\tnr[i] = -nr[i];\n\t\tpoly_mulTo(m, nr, r);\n\t\tcopy(nr + h, nr + m, r + h);\n\t}\n}\n\nvoid poly_sqrt(int n, modint *f, modint *s)\n{\n\t// assert(f[0] == 1)\n\tfill(s, s + n, modint(0));\n\ts[0] = 1;\n\n\tstatic modint rs[MaxN];\n\tfill(rs, rs + n, modint(0));\n\trs[0] = 1;\n\tfor (int m = 2; m <= n; m <<= 1)\n\t{\n\t\tint h = m / 2;\n\t\tstatic modint nrs[MaxN];\n\t\tcopy(s, s + h, nrs), fill(nrs + h, nrs + m, modint(0));\n\t\tpoly_mulTo(m, nrs, rs);\n\t\tfill(nrs, nrs + h, modint(0));\n\t\tfor (int i = h; i < m; i++)\n\t\t\tnrs[i] = -nrs[i];\n\t\tpoly_mulTo(m, nrs, rs);\n\t\tcopy(rs, rs + h, nrs);\n\t\tpoly_mulTo(m, nrs, f);\n\t\tfor (int i = h; i < m; i++)\n\t\t\ts[i] = nrs[i].div2();\n\t\tcopy(s, s + m, nrs);\n\t\tpoly_mulTo(m, nrs, rs);\n\t\tfill(nrs, nrs + h, modint(0));\n\t\tfor (int i = h; i < m; i++)\n\t\t\tnrs[i] = -nrs[i];\n\t\tpoly_mulTo(m, nrs, rs);\n\t\tcopy(nrs + h, nrs + m, rs + h);\n\t}\n}\n\nint main()\n{\n\tint c_n, s;\n\tstatic int c[MaxCN];\n\n\tcin >> c_n >> s;\n\tfor (int i = 0; i < c_n; i++)\n\t\tscanf(\"%d\", &c[i]);\n\n\tint n = 1;\n\twhile (n < s + 1)\n\t\tn <<= 1;\n\n\tstatic modint fD[MaxN];\n\tfD[0] = 1;\n\tfor (int i = 0; i < c_n; i++)\n\t\tif (c[i] <= s)\n\t\t\tfD[c[i]] = -4;\n\n\tstatic modint fB[MaxN];\n\tpoly_sqrt(n, fD, fB);\n\n\tfB[0] = fB[0] + 1;\n\t\n\tfor (int i = 0; i < n; i++)\n\t\tfB[i] = fB[i].div2();\n\n\tstatic modint f[MaxN];\n\tpoly_inv(n, fB, f);\n\n\tfor (int i = 1; i <= s; i++)\n\t\tprintf(\"%d\\n\", f[i].a);\n\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "fft",
      "number theory"
    ],
    "rating": 3100
  },
  {
    "contest_id": "439",
    "index": "A",
    "title": "Devu, the Singer and Churu, the Joker",
    "statement": "Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to \"All World Classical Singing Festival\". Other than Devu, comedian Churu was also invited.\n\nDevu has provided organizers a list of the songs and required time for singing them. He will sing $n$ songs, $i^{th}$ song will take $t_{i}$ minutes exactly.\n\nThe Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.\n\nPeople have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.\n\nYou as one of the organizers should make an optimal sсhedule for the event. For some reasons you must follow the conditions:\n\n- The duration of the event must be no more than $d$ minutes;\n- Devu must complete all his songs;\n- With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible.\n\nIf it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.",
    "tutorial": "For checking whether there is a way to conduct all the songs of the singer, you can conduct the event in the following way. First singer will sing a song. Then during $10$ minutes rest of the singer, the joker will crack $2$ jokes(each of $5$ minutes) Then singer will again sing a song, then joker, etc. After the singer has completes all his songs, the joker will keep on cracking jokes of $5$ minutes each. Hence minimum duration of the even needed such that sing could sing all his songs will be $t_{1}$ + $10$ + $t_{2}$ + $10$ + ... +$t_{n}$ = $sum + (n - 1) * 10$ where $sum$ denote the total time of the songs of the singer. So for checking feasibility of the solution, just check whether $sum + (n - 1) * 10  \\le  duration$ or not?. If it is feasible, then time remaining for joker will be the entire duration except the time when the singer is singing the song. Hence time available for the joker will be $duration - sum$. In that time joker will sing $\\frac{d u r a t i o n-s u m}{5}$ songs.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "439",
    "index": "B",
    "title": "Devu, the Dumb Guy",
    "statement": "Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him $n$ subjects, the $i^{th}$ subject has $c_{i}$ chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.\n\nLet us say that his initial per chapter learning power of a subject is $x$ hours. In other words he can learn a chapter of a particular subject in $x$ hours.\n\nWell Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.\n\nYou can teach him the $n$ subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.\n\nPlease be careful that answer might not fit in 32 bit data type.",
    "tutorial": "You can formulate the problem in following way. Given two arrays $a$ and $b$. Find minimum cost of matching the elements of array $a$ to $b$. For our problem the array $a$ will be same as $b$. The array $b$ will have content $x$, $x$ - 1, , 1, 1. For a general version of this problem, we can use min cost max flow(min cost matching), but for this problem following simple greedy solution will work. Sort the array $a$ in increasing and $b$ in decreasing order (or vice versa). Now match $i^{th}$ element of the array a with $i^{th}$ element of array b. Proof: It can be easily proved by exchange argument.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "439",
    "index": "C",
    "title": "Devu and Partitioning of the Array",
    "statement": "Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?\n\nGiven an array consisting of distinct integers. Is it possible to partition the whole array into $k$ disjoint non-empty parts such that $p$ of the parts have even sum (each of them must have even sum) and remaining $k$ - $p$ have odd sum? (note that parts need not to be continuous).\n\nIf it is possible to partition the array, also give any possible way of valid partitioning.",
    "tutorial": "Let us first try to find the condition required to make sure the existence of the partitions. Notice the following points. If the parity of sum does not match with parity of number of odd partitions ($k - p$) , then we can't create the required partitions. eg. $a = [1;2]$, $k = 2$, $p = 0$, Then you can not create two partitions of odd size, because then sum of the elements of the partitions of the array will be even whereas the sum of elements of the array is odd. If the parity of sum does not match with parity of number of odd partitions ($k - p$) , then we can't create the required partitions. eg. $a = [1;2]$, $k = 2$, $p = 0$, Then you can not create two partitions of odd size, because then sum of the elements of the partitions of the array will be even whereas the sum of elements of the array is odd. If number of odd elements in $a$ are less than $k - p$ (number of required partitions with odd sum), then we can not do a valid partitioning. If number of odd elements in $a$ are less than $k - p$ (number of required partitions with odd sum), then we can not do a valid partitioning. If number of even elements are less than $p$, then we can not create even partitions simply by using even numbers, we have to use odd numbers too. Notice the simple fact that sum of two odd numbers is even. Hence we will try to include $2$ odd elements in our partitions too. So if we can create $oddsRemaining / 2$ partitions in which every partition contains $2$ odd elements, then we can do a valid partitioning otherwise we can't. Here $oddsRemaining$ denotes the number of odd elements which are not used in any of the partitions made up to now. If number of even elements are less than $p$, then we can not create even partitions simply by using even numbers, we have to use odd numbers too. Notice the simple fact that sum of two odd numbers is even. Hence we will try to include $2$ odd elements in our partitions too. So if we can create $oddsRemaining / 2$ partitions in which every partition contains $2$ odd elements, then we can do a valid partitioning otherwise we can't. Here $oddsRemaining$ denotes the number of odd elements which are not used in any of the partitions made up to now. Let $oddElements$ denotes the number of odd elements in array $a$. Similarly $evenElements$ denotes the number of even elements. So the answer exists if Number of possible odd partitions are $ \\ge $ $k - p$ i.e. $oddElements  \\ge  k - p$. Number of possible even partitions are $ \\ge $ $p$ i.e. $evenElements + (oddRemaining) / 2  \\ge  p.$ where $oddRemaining$ is $oddElements - (k - p)$. For generating the actual partitions, you can follow the same strategy used in detecting the existence of the partitions. We will first generate any valid $p$ partitions (forget about the condition of using the entire array), then we can simply include the remaining elements of the array in the last partition and we are done.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "439",
    "index": "D",
    "title": "Devu and his Brother",
    "statement": "Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays $a$ and $b$ by their father. The array $a$ is given to Devu and $b$ to his brother.\n\nAs Devu is really a naughty kid, he wants the minimum value of his array $a$ should be at least as much as the maximum value of his brother's array $b$.\n\nNow you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.\n\nYou need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.",
    "tutorial": "You can solve the problem in two ways. By using ternary search Let us define a function f. Function f(k) = cost needed to make array a elements $ \\ge $ k + cost needed to make array b elements $ \\le $ k Instead of proving it formally, try checking the property on many random test cases. You will realize that f is convex. Claim: f is convex: Proof: It is fairly easy to prove. See the derivative of f. $\\frac{d(k)}{d k}$ = - (# of elements of b > k) + (# of elements of a < k) The first term (without sign) can only decrease as k increases whereas second term can only increase as k increases. So, ${\\frac{d^{2}(f)}{d^{2}k}}\\geq0$ By using the fact that optimal values are attainable at the array values: All the extremum points will lie in the elements from the any of the arrays because f is convex and ${\\frac{d^{2}(f)}{d^{2}k}}=0$ at the event points (or the points of array a and b). For learning more about ternary search, you can see following topcoder discussion Another smart solution Please see following comment of goovie and proof is given in the reply by himank",
    "tags": [
      "binary search",
      "sortings",
      "ternary search",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "439",
    "index": "E",
    "title": "Devu and Birthday Celebration",
    "statement": "Today is Devu's birthday. For celebrating the occasion, he bought $n$ sweets from the nearby market. He has invited his $f$ friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend.\n\nHe wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed $n$ sweets to his friends such that $i^{th}$ friend is given $a_{i}$ sweets. He wants to make sure that there should not be any positive integer $x > 1$, which divides every $a_{i}$.\n\nPlease find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo $1000000007$ $(10^{9} + 7)$.\n\nTo make the problem more interesting, you are given $q$ \\textbf{queries}. Each query contains an $n$, $f$ pair. For each query please output the required number of ways modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "There are two possible solutions. dp solution Let $P(n, f)$ be total number of ways of partitioning $n$ into $f$ segments such that each $a_{i}$ is positive. With some manipulations of the generating function, you can find that this is equal to $\\textstyle{\\binom{n-1}{f-1}}$. So $P(n,f)=\\left(\\O_{f-1}^{n-1}\\right)$ Let $F(n, f, g)$ denotes partitions of $n$ into $f$ parts such that gcd of all the $a_{i}'s$ is $g$. Note that $F(n, f, 1)$ = $P(n, f)$ - sum of $F(n, f, g)$ over all possible gcd $g's$. So $g$ will be a divisor of $n$. In other words, $F(n,f,1)=P(n,f)-\\sum_{q\\,|n,o r e}F(n,f,g)\\ \\ {\\mathrm{for~every~integer~}}n\\geq1$ As $F(n,f,g)=F(\\underline{{{\\O_{g}}}},f,1)$. $F(n,f,1)=P(n,f)-\\sum_{g\\,|n,g\\neq1}F(n/g,f,1)\\quad{\\mathrm{for~every~integer~}}n\\geq1$ You can implement this solution by a simple dp. You can pre-calculate factorials which will help you to calculate $\\textstyle{\\binom{n}{r}}$. Complexity of this solution will be $nlogn$ over all the test cases. Please note that this solution might get time limit exceeded in Java. Please read the comment. Mathematical solution Note that $F(n, f, 1) = P(n, f)$ - sum of $F(n, f, g)$ over all possible gcd $g's$ ($g > 1$ such that $g$ is a divisor of $n$. In other words, $F(n,f,1)=P(n,f)-\\sum_{q\\,|n,oneq1}F(n,f,g)\\quad{\\mathrm{for~every~integer~}}n\\geq1$ As $F(n, f, g)$ = $F(_{g}^{n},f,1)$. $F(n,f,1)=P(n,f)-\\sum_{g\\,|n,g\\neq1}F(n/g,f,1)\\quad{\\mathrm{for~every~integer~}}n\\geq1$ $P(n,f)=F(n,f,1)+\\sum_{o\\mid n,o r:1}F(n/g,f,1)\\quad{\\mathrm{for~every~integer~}}n\\geq1$ $P(n,f)=\\sum_{g\\mid n}F(n/g,f,1)\\ \\ \\mathrm{for~every~integer}\\;n\\geq1$ Now you have to use Möbius inversion formula. Theorem: If $f$ and $g$ are two arithmetic functions satisfying $g(n)=\\sum_{d\\vdash n}f(d)\\quad{\\mathrm{~for~every~integer~}}n\\geq1$ then $f(n)=\\sum_{d\\mid n}\\mu(d)g(n/d)\\quad{\\mathrm{for~every~integer}}\\ n\\geq1$ So In our case: $g(n)$ is $P(n, f)$ and $f(n)$ is $F(n, f, 1)$. For proving complexity: Use the fact that total number of divisors of a number from $1$ to $n$ is $\\mathbb{O}(n l o g n).$",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "441",
    "index": "A",
    "title": "Valera and Antique Items",
    "statement": "Valera is a collector. Once he wanted to expand his collection with exactly one antique item.\n\nValera knows $n$ sellers of antiques, the $i$-th of them auctioned $k_{i}$ items. Currently the auction price of the $j$-th object of the $i$-th seller is $s_{ij}$. Valera gets on well with each of the $n$ sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.\n\nUnfortunately, Valera has only $v$ units of money. Help him to determine which of the $n$ sellers he can make a deal with.",
    "tutorial": "You need to implement what written in statement. You could act like that: let's calculate $q_{i}$ - minimum item price from seller $i$. Then if $q_{i} < v$, we can make a deal with seller $i$, otherwise we can't.",
    "code": "#include <iostream>\n#include <vector>\n \n#define forn(i,n) for(int i = 0; i < int(n); ++i)\n \nusing namespace std;\n \nint main() {\n \n\tint n, v;\n\tcin >> n >> v;\n \n\tvector <int> ans;\n \n\tforn(i, n) {\n\t\tbool u = false;\n\t\tint k, s;\n\t\tcin >> k;\n \n\t\tforn(j, k) {\n\t\t\tcin >> s;\n\t\t\tif (!u && v > s) {\n\t\t\t\tu = true;\n\t\t\t\tans.push_back(i);\n\t\t\t}\n\t\t}\n\t}\n \n\tcout << ans.size() << endl;\n\tforn(i, ans.size())\n\t\tcout << ans[i]+1 << \" \";\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "441",
    "index": "B",
    "title": "Valera and Fruits",
    "statement": "Valera loves his garden, where $n$ fruit trees grow.\n\nThis year he will enjoy a great harvest! On the $i$-th tree $b_{i}$ fruit grow, they will ripen on a day number $a_{i}$. Unfortunately, the fruit on the tree get withered, so they can only be collected on day $a_{i}$ and day $a_{i} + 1$ (all fruits that are not collected in these two days, become unfit to eat).\n\nValera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than $v$ fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?",
    "tutorial": "Let's start counting days from 1 to 3001. Let current day be $i$. Additionally, we'll have $cur$ variable - number of fruit we didn't collect previous days. Suppose $now$ fruit is ripen current day. If $now + cur  \\le  v$, we need to add $now + cur$ to answer and update $cur$ value ($cur = 0$). Otherwise we add $v$ to answer, but $cur$ value need to be updated as follows. Let $tv = max(v - cur, 0)$. Then $cur = now - tv$. In other words, we try to collect fruits that will not be collectable next day. Additionally, problem could be solved with $O(n\\log n)$, but this is not required.",
    "code": "#undef NDEBUG\n#ifdef gridnevvvit\n#define _GLIBCXX_DEBUG\n#endif\n \n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n \n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <list>\n#include <vector>\n#include <string>\n#include <deque>\n#include <bitset>\n#include <algorithm>\n#include <utility>\n                  \n#include <functional>\n#include <limits>\n#include <numeric>\n#include <complex>\n \n#include <cassert>\n#include <cmath>\n#include <memory.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>   \n \nusing namespace std;\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int,int> pt;\ntypedef pair<ld, ld> ptd;\ntypedef unsigned long long uli;\n \n#define pb push_back\n#define mp make_pair\n#define mset(a, val) memset(a, val, sizeof (a))\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define ft first\n#define sc second\n#define sz(a) int((a).size())\n#define x first\n#define y second\n \ntemplate<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }\ntemplate<typename X> inline X sqr(const X& a) { return (a * a); }\ntemplate<typename T> inline string toStr(T x) { stringstream st; st << x; string s; st >> s; return s; }\ntemplate<typename T> inline int hasBit(T mask, int b) { return (b >= 0 && (mask & (T(1) << b)) != 0) ? 1 : 0; }\ntemplate<typename X, typename T>inline ostream& operator<< (ostream& out, const pair<T, X>& p) { return out << '(' << p.ft << \", \" << p.sc << ')'; }\n \ninline int nextInt() { int x; if (scanf(\"%d\", &x) != 1) throw; return x; }\ninline li nextInt64() { li x; if (scanf(\"%I64d\", &x) != 1) throw; return x; }\ninline double nextDouble() { double x; if (scanf(\"%lf\", &x) != 1) throw; return x; }\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define fore(i, a, b) for(int i = int(a); i <= int(b); i++)\n#define ford(i, n) for(int i = int(n - 1); i >= 0; i--)\n#define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)\n \nconst int INF = int(1e9);\nconst li INF64 = li(INF) * li(INF);\nconst ld EPS = 1e-9;\nconst ld PI = ld(3.1415926535897932384626433832795);\n \nconst int N = 3005;\n \nint n, a[N], b[N], v;\n \ninline bool read() {\n\tn = nextInt();\n\tv = nextInt();\n\t\n\tforn(i, n)\n\t{\n\t \ta[i] = nextInt();\n\t \tb[i] = nextInt();\n    }\n \n \treturn true;\n}\n              \ninline void solve() {\n\tint fromLastDays = 0;\n \n\tint ans = 0;\n                 \n\tfor(int day = 1; day <= 3001; day++) {\n\t\tint curDay = 0;\n \n\t\tforn(i, n)\n\t\t\tif (a[i] == day)\n\t\t\t\tcurDay += b[i]; \t\n\t\t\n\t\t\n\t\tif (curDay + fromLastDays <= v) {\n\t\t\tans += fromLastDays + curDay;\n\t\t\tfromLastDays = 0;\n\t\t} else {\n\t\t\tans += v;\n \n\t\t\tint tv = v - fromLastDays;\n \n\t\t\tif (tv < 0) tv = 0;\n        \t\n        \t        fromLastDays = curDay - tv;\n\t \t}\t\n\t}\n \n\tcout << ans << endl;\n}\n \nint main() \n{\n \n#ifdef gridnevvvit\n\tfreopen(\"input.txt\", \"rt\", stdin);\n\tfreopen(\"output.txt\", \"wt\", stdout);\n#endif\n    \n\tsrand(time(NULL));\n \n\tcout << setprecision(10) << fixed;\n\tcerr << setprecision(5) << fixed;\n\t\n\tassert(read());\n\tsolve();\n \n#ifdef gridnevvvit\n\tcerr << \"===Time: \" << clock()  << \"===\" << endl;\n#endif\n \n} ",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "441",
    "index": "C",
    "title": "Valera and Tubes ",
    "statement": "Valera has got a rectangle table consisting of $n$ rows and $m$ columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row $x$ and column $y$ by a pair of integers $(x, y)$.\n\nValera wants to place exactly $k$ tubes on his rectangle table. A tube is such sequence of table cells $(x_{1}, y_{1})$, $(x_{2}, y_{2})$, $...$, $(x_{r}, y_{r})$, that:\n\n- $r ≥ 2$;\n- for any integer $i$ $(1 ≤ i ≤ r - 1)$ the following equation $|x_{i} - x_{i + 1}| + |y_{i} - y_{i + 1}| = 1$ holds;\n- each table cell, which belongs to the tube, must occur exactly once in the sequence.\n\nValera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:\n\n- no pair of tubes has common cells;\n- each cell of the table belongs to some tube.\n\nHelp Valera to arrange $k$ tubes on his rectangle table in a fancy manner.",
    "tutorial": "The solution is pretty simple. First we need to make such route that visits every cell exactly one time. It is not difficult: Initially we stay in $(1, 1)$ cell. Moving from left to right, we should reach $(1, m)$ cell. Move to the next line, in $(2, m)$ cell. Moving from right to left, we should reach the most left sell of 2nd line, $(2, 1)$. Move to the next line. Repeat 1. and 2. while we have not all cells visited. After that, we can easily find the solution: you can make first $(k - 1)$ tubes length be $2$, and the last $k$ tube will consist from cells left.",
    "code": "#undef NDEBUG\n#ifdef gridnevvvit\n#define _GLIBCXX_DEBUG\n#endif\n \n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n \n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <list>\n#include <vector>\n#include <string>\n#include <deque>\n#include <bitset>\n#include <algorithm>\n#include <utility>\n                  \n#include <functional>\n#include <limits>\n#include <numeric>\n#include <complex>\n \n#include <cassert>\n#include <cmath>\n#include <memory.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>   \n \nusing namespace std;\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int,int> pt;\ntypedef pair<ld, ld> ptd;\ntypedef unsigned long long uli;\n \n#define pb push_back\n#define mp make_pair\n#define mset(a, val) memset(a, val, sizeof (a))\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define ft first\n#define sc second\n#define sz(a) int((a).size())\n#define x first\n#define y second\n \ntemplate<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }\ntemplate<typename X> inline X sqr(const X& a) { return (a * a); }\ntemplate<typename T> inline string toStr(T x) { stringstream st; st << x; string s; st >> s; return s; }\ntemplate<typename T> inline int hasBit(T mask, int b) { return (b >= 0 && (mask & (T(1) << b)) != 0) ? 1 : 0; }\ntemplate<typename X, typename T>inline ostream& operator<< (ostream& out, const pair<T, X>& p) { return out << '(' << p.ft << \", \" << p.sc << ')'; }\n \ninline int nextInt() { int x; if (scanf(\"%d\", &x) != 1) throw; return x; }\ninline li nextInt64() { li x; if (scanf(\"%I64d\", &x) != 1) throw; return x; }\ninline double nextDouble() { double x; if (scanf(\"%lf\", &x) != 1) throw; return x; }\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define fore(i, a, b) for(int i = int(a); i <= int(b); i++)\n#define ford(i, n) for(int i = int(n - 1); i >= 0; i--)\n#define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)\n \nconst int INF = int(1e9);\nconst li INF64 = li(INF) * li(INF);\nconst ld EPS = 1e-9;\nconst ld PI = ld(3.1415926535897932384626433832795);\n \nint n, m, k;\n \ninline bool read() {\n \tn = nextInt();\n \tm = nextInt();\n \tk = nextInt();\n \treturn true;\n}\n              \ninline void solve() {\n        if (n == 3 && m == 3 && k == 3) {\n             forn(it, 3) {\n                   cout << 3;\n                   forn(i, 3) \n                         cout << ' ' << it + 1 << ' ' << i + 1; \n                   puts(\"\");  \n             }\n             return;\n        }\n\tvector < pt > path;\n \n\tint x = 0, y = 0, dir = 1;\n \n\tpath.pb(mp(x + 1, y + 1));\n \n\twhile (true) {\n \n\t\ty += dir;\n \n\t\tif (y == m) dir *= -1, y = m - 1, x ++;\n \n\t\tif (y == -1) dir *= -1, y = 0, x++;\n \n\t\tif (x == n) break;\n \n\t\tpath.pb(mp(x + 1, y + 1));\t\n        }\n \n\tforn(i, k - 1) {\n\t\tprintf(\"%d\", 2);\n\t\tprintf(\" %d %d\", path[2 * i].ft, path[2 * i].sc);\n\t\tprintf(\" %d %d\\n\", path[2 * i + 1].ft, path[2 * i + 1].sc);\n\t}\t\n \n\tprintf(\"%d\", sz(path) - 2 * (k - 1));\n\tfor(int i = 2 * (k - 1); i < sz(path); i++) {\n\t \tprintf(\" %d %d\", path[i].ft, path[i].sc);\n\t}\n        puts(\"\");\n \n}\n \nint main() \n{\n \tassert(read());\n\tsolve();\n \n \n} ",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "441",
    "index": "D",
    "title": "Valera and Swaps",
    "statement": "A permutation $p$ of length $n$ is a sequence of distinct integers $p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$. A permutation is an identity permutation, if for any $i$ the following equation holds $p_{i} = i$.\n\nA swap $(i, j)$ is the operation that swaps elements $p_{i}$ and $p_{j}$ in the permutation. Let's assume that $f(p)$ is the minimum number of swaps that you need to make the permutation $p$ an identity permutation.\n\nValera wonders, how he can transform permutation $p$ into any permutation $q$, such that $f(q) = m$, using the minimum number of swaps. Help him do that.",
    "tutorial": "In this task you should represent permutation as graph with $n$ vertexes, and from every vertex $i$ exists exactly one edge to vertex $p[i]$. It's easy to understand that such graph consists of simple cycles only. If we make swap $(i, j)$, edges $i\\rightarrow p[i]$ and $j\\to p[j]$ will become edges $i\\rightarrow p[j]$ and $j\\to p[i]$ respectively. Then if $i$ and $j$ is in the same cycle, this cycle will break: but if they are in different cycles, these cycles will merge into one: this means that every swap operation increases number of cycles by one, or decreases it by one. Assuming all above, to get permutation $q$ from permutation $p$, we need to increase (or decrease) number of cycles in $p$ to $n - m$. Let $c$ - number of cycles in $p$. Then $k$ always equals $|(n - m) - c|$. For satisfying lexicographical minimality we will review three cases: 1) $n - m < c$ It's easy to understand, that in this case you must decrease cycles number by merging cycles one by one with cycle containing vertex 1. This way every swap has form $(1, v)$, where $v > 1$. Because every cycle vertex is bigger than previous cycle vertex, this case can be solved with $O(n)$. 2) $n - m > c$ In this case you should break cycle for every vertex, making swap with smallest possible vertex (it should be in this cycle too). This could be done if represent cycle by line $p[i]\\to p[p[i]]\\to\\dots\\to i$. As soon as every cycle is broken with linear asymptotics, this case solution works with $O(n^{2})$. Bonus: this way of representing cycle lets us optimize solution to $O(n\\log n)$ asymptotics, you may think how. 3) $n - m = c$ Besause in this case $k = 0$, there is nothing need to be swapped.",
    "code": "#include <cstdio>\n#include <cmath>\n#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nconst int N = 3005;\n \nint n, m, k, p[N];\nbool used[N];\n \ninline void use_cycle(int v) {\n\tfor (int i = v; !used[i]; i = p[i])\n\t\tused[i] = true;\n}\n \nint main() {\n\t\n\tscanf(\"%d\", &n);\n \n\tfor (int i = 0; i < n; ++i) {\n\t\tscanf(\"%d\", &p[i]);\n\t\tp[i]--;\n\t}\n \n\tscanf(\"%d\", &m);\n\tm = n - m;\n \n\tfor (int i = 0; i < n; ++i)\n\t\tif (!used[i]) {\n\t\t\tk++;\n\t\t\tuse_cycle(i);\n\t\t}\n \n\tfor (int i = 0; i < n; ++i)\n\t\tused[i] = false;\n \n\tprintf(\"%d\\n\", (int)abs(k-m));\n \n\tif (k > m) {\n\t\tuse_cycle(0);\n\t\tfor (int i = 1; i < n && k > m; ++i) {\n\t\t\tif (!used[i]) {\n\t\t\t\tprintf(\"%d %d \", 1, i+1);\n\t\t\t\tk--;\n\t\t\t\tuse_cycle(i);\n\t\t\t}\n\t\t}\n\t}\n \n\tif (k < m) {\n\t\tfor (int i = 0; i < n && k < m; ++i) {\n\t\t\tvector <int> pos(n, -1);\n\t\t\t\n\t\t\tint cur = 0;\n\t\t\tfor (int j = p[i]; j != i; j = p[j])\n\t\t\t\tpos[j] = cur++;\n\t\t\tpos[i] = cur;\n\t\t\t\n\t\t\tcur = 0;\n\t\t\tfor (int j = i+1; j < n && k < m; ++j)\n\t\t\t\tif (pos[j] >= cur) {\n\t\t\t\t\tprintf(\"%d %d \", i+1, j+1);\n\t\t\t\t\tk++;\n\t\t\t\t\tcur = pos[j]+1;\n\t\t\t\t\tswap(p[i], p[j]);\n\t\t\t\t}\n\t\t\t\t\n\t\t}\n\t}\n \n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dsu",
      "graphs",
      "implementation",
      "math",
      "string suffix structures"
    ],
    "rating": 2100
  },
  {
    "contest_id": "441",
    "index": "E",
    "title": "Valera and Number",
    "statement": "Valera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below:\n\n\\begin{verbatim}\n//input: integers x, k, p\na = x;\nfor(step = 1; step <= k; step = step + 1){\nrnd = [random integer from 1 to 100];\nif(rnd <= p)\na = a * 2;\nelse\na = a + 1;\n}\ns = 0;\nwhile(remainder after dividing a by 2 equals 0){\na = a / 2;\ns = s + 1;\n}\n\\end{verbatim}\n\nNow Valera wonders: given the values $x$, $k$ and $p$, what is the expected value of the resulting number $s$?",
    "tutorial": "We will solve the task by calculating dynamic $d[i][mask][last][cnt]$ - possibility of getting $v$ which $8$ last bits equals $mask$, 9th bit equals $last$, $cnt$ - number of consecutive bits (following 9th bit) and equal to $last$, after $i$ steps. Good, but why we left other bits? It's clear, that using operation $+ = 1$ we can change only first 0 bit with index $ \\ge  9$. Transitions is pretty obvious: we add 1 or multiply by 2 (it's recommended to see them in jury's solution). Perhaps, you should ask following question. For example, we have number $x = 1011111111$ in binary representation. And at this moment, we make $+ = 1$. According to all above, we must go to $d[1][0][1][2]$ condition, but we can't do that because we don't have any information about $1$ in 10th position. But, as we can not change any bit with index $ \\ge  9$ ($mask = 0$) we make transition to $d[1][0][1][1]$.",
    "code": "#undef NDEBUG\n#ifdef gridnevvvit\n#define _GLIBCXX_DEBUG\n#endif\n \n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n \n#include <map>\n#include <set>\n#include <queue>\n#include <stack>\n#include <list>\n#include <vector>\n#include <string>\n#include <deque>\n#include <bitset>\n#include <algorithm>\n#include <utility>\n                  \n#include <functional>\n#include <limits>\n#include <numeric>\n#include <complex>\n \n#include <cassert>\n#include <cmath>\n#include <memory.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>   \n \nusing namespace std;\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int,int> pt;\ntypedef pair<ld, ld> ptd;\ntypedef unsigned long long uli;\n \n#define pb push_back\n#define mp make_pair\n#define mset(a, val) memset(a, val, sizeof (a))\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define ft first\n#define sc second\n#define sz(a) int((a).size())\n#define x first\n#define y second\n \ntemplate<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); }\ntemplate<typename X> inline X sqr(const X& a) { return (a * a); }\ntemplate<typename T> inline string toStr(T x) { stringstream st; st << x; string s; st >> s; return s; }\ntemplate<typename T> inline int hasBit(T mask, int b) { return (b >= 0 && (mask & (T(1) << b)) != 0) ? 1 : 0; }\ntemplate<typename X, typename T>inline ostream& operator<< (ostream& out, const pair<T, X>& p) { return out << '(' << p.ft << \", \" << p.sc << ')'; }\n \ninline int nextInt() { int x; if (scanf(\"%d\", &x) != 1) throw; return x; }\ninline li nextInt64() { li x; if (scanf(\"%I64d\", &x) != 1) throw; return x; }\ninline double nextDouble() { double x; if (scanf(\"%lf\", &x) != 1) throw; return x; }\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define fore(i, a, b) for(int i = int(a); i <= int(b); i++)\n#define ford(i, n) for(int i = int(n - 1); i >= 0; i--)\n#define foreach(it, a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)\n \nconst int INF = int(1e9);\nconst li INF64 = li(INF) * li(INF);\nconst ld EPS = 1e-9;\nconst ld PI = ld(3.1415926535897932384626433832795);\n \nli x;\nint k;\nint pl;\n \n \nconst int N = 402;\nconst int MAGIC = 9;\n \n \nld d[2][(1 << MAGIC)][2][N];\n \ninline bool read() {\n \treturn (cin >> x >> k >> pl);\n}\n              \ninline void solve() {                    \n\tld p = ld(pl) / 100;\n \n\tint SPMASK = (1 << MAGIC) - 1;\n \n\tli pmask = x & li(SPMASK);\n    li plast = (x & li(1 << MAGIC)) > 0;\n    li pcnt = 0;\n    \n    x >>= MAGIC;\n    \n    if (x == 0)\n   \t\tpcnt = 200;\n    else {\n    \twhile (true) {\n    \t \tint bit = x & 1ll;\n \n    \t \tif (bit == plast)\n    \t \t\tpcnt++;\n    \t \telse\n    \t \t\tbreak;\n \n    \t \tx >>= 1;\n    \t}\n    }\n \n    d[0][pmask][plast][pcnt] = 1.0;\n \t\n                 \n    forn(it, k) {\n\t\tint i = it & 1;\n\t\tint nxt = i ^ 1;\n \n\t\tforn(mask, (1 << MAGIC)) {\n\t\t \tforn(last, 2) {\n\t\t \t \tforn(cnt, N) {\n\t\t \t \t \td[nxt][mask][last][cnt] = 0.0;\n\t\t \t \t}\n\t\t \t}\n\t\t}\n \n\t \tforn(mask, (1 << MAGIC)) {\n\t\t\tforn(last, 2) {\n\t\t\t\tforn(cnt, N) {\n\t\t\t\t\tld dv = d[i][mask][last][cnt];\n \n\t\t\t\t\t//doubling\n                \t{\n                \t\tint nmask = (mask << 1) & SPMASK;\n                \t\tint nlast = (mask & (1 << (MAGIC - 1))) > 0;\n                \t\tint ncnt = cnt;\n \n                \t\tif (last == nlast)\n                \t\t\tncnt++;\n                \t\telse\n                \t\t\tncnt = 1;\n                    \t\n                        d[nxt][nmask][nlast][ncnt] += dv * p;\n \n                    }\n \n                    //adding\n                    {\n                     \tint nmask = mask + 1;\n \n                     \tif (nmask != (1 << MAGIC)) {\n                     \t\td[nxt][nmask][last][cnt] += dv * (1.0 - p);\n                     \t} else {\n                     \t\tif (last == 1)\n                     \t\t\td[nxt][0][0][cnt] += dv * (1.0 - p);\n                     \t\telse\n                     \t\t\td[nxt][0][1][1] += dv * (1.0 - p);\n                        }\n                    }\n                }\t\n\t\t\t}\n\t \t}\n\t}            \n \n\tld answer = 0;\n \n\tk = k & 1;\n \n\tforn(nmask, (1 << MAGIC)){\n\t \tforn(last, 2) {\n\t \t \tforn(cnt, N) {\n\t \t \t\tint counter = 0;\n \n\t \t \t\tint mask = nmask;\n \n\t \t \t\tif (mask != 0) {\n\t \t \t\t\n\t \t \t\t\twhile (mask % 2 == 0)\n\t \t \t\t\t\tcounter += 1, mask /= 2;\n\t \t \t\t\t\t\t\n\t \t \t\t} else {\n\t \t \t\t\tcounter = MAGIC;\n\t \t \t\t\tif (last == 0)\n\t \t \t\t\t\tcounter += cnt;\n\t \t \t\t}\t\n\t \t \t\t\n\t \t \t\tld dv = d[k][nmask][last][cnt];\n \n\t \t \t\tanswer += ld(counter) * ld(d[k][nmask][last][cnt]);\n\t \t \t}\n\t \t}\n\t}\n \n\tcout << fixed << setprecision(13) << answer << endl;\n}\n \nint main() \n{\n \n#ifdef gridnevvvit\n\tfreopen(\"input.txt\", \"rt\", stdin);\n\tfreopen(\"output.txt\", \"wt\", stdout);\n#endif\n    \n\tsrand(time(NULL));\n \n\tcout << setprecision(10) << fixed;\n\tcerr << setprecision(5) << fixed;\n\t\n\tassert(read());\n\tsolve();\n \n#ifdef gridnevvvit\n\tcerr << \"===Time: \" << clock()  << \"===\" << endl;\n#endif\n \n} ",
    "tags": [
      "bitmasks",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "442",
    "index": "A",
    "title": "Borya and Hanabi",
    "statement": "Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.\n\nOverall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding $n$ cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has).\n\nThe aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints.\n\nA color hint goes like that: a player names some color and points at all the cards of this color.\n\nSimilarly goes the value hint. A player names some value and points at all the cards that contain the value.\n\nDetermine what minimum number of hints the other players should make for Borya to be certain about each card's color and value.",
    "tutorial": "It's obvious that the order of hints doesn't metter. There are 10 types of hints, so we can try all $2^{10}$ vartiants of what other players should do. Now we need to check if Boris can describe all of his cards. He can do it iff he can distinguish all pairs of different cards. He can do it if somebody told at least one distinction. It can be a hint about color of one of cards (if they don't have same one) or it can be hint about value of some card.",
    "tags": [
      "bitmasks",
      "brute force",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "442",
    "index": "B",
    "title": "Andrey and Problem",
    "statement": "Andrey needs one more problem to conduct a programming contest. He has $n$ friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.\n\nHelp Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.",
    "tutorial": "Let's sort all friends in such a way that $p_{i}  \\le  p_{j}$ iff $i  \\le  j$. If there is $p_{i} = 1$ Andrey should ask only this friend. Now we can assume that all probabilities are less then 1. What should we maximize? ${\\textstyle\\sum_{i=0}^{n-1}p_{i}\\prod_{j\\neq i}(1-p_{j})=\\sum_{i=0}^{n-1}{\\textstyle{\\frac{p_{i}}{1-p_{i}}}}\\prod(1-p_{j})=\\prod(1-p_{i})\\cdot\\sum{\\frac{p_{i}}{1-p_{i}}}$ Let $P=\\prod(1-p_{i})$, $S=\\textstyle\\sum{\\frac{p_{i}}{1-p_{i}}}$. Assume we already have some group of people we would ask a help. Let's look what will happen with the probability of success if we add a friend with probability $p_{i}$ to this group: $\\Delta=-P\\cdot S+P(1-p_{i})\\cdot(S+{\\textstyle\\frac{p_{i}}{1-p_{i}}})=P\\cdot p_{i}(1-S)$ It means adding a new people to group will increase a probability of success only if $S < 1$. Now let's look at another question. We have some group of people with $S < 1$. And we want to add only one friend to this group. Which one is better? Let the probability of the first friend is $p_{i}$ and the second friend is $p_{j}$. It's better to add first one if $ \\Delta _{i} -  \\Delta _{j} = P \\cdot p_{i} \\cdot (1 - S) - P \\cdot p_{j} \\cdot (1 - S) = P \\cdot (1 - S) \\cdot (p_{i} - p_{j}) > 0$. As $S < 1$ we get $p_{i} > p_{j}$. But it's only a local criteria of optimality. But, we can prove that globally you should use only a group of people with the biggest probabilities. We can use proof by contradiction. Let's look at the optimal answer with biggest used suffix (in the begining of editorial we sort all friends). Of all such answers we use one with minimum number of people in it. Where are two friends $i$ and $j$ ($p_{i}$ < $p_{j}$) and $i$-th friend is in answer and $j$-th isn't. Let's look at the answer if we exclude $i$-th friend. It should be smaller because we used optimal answer with minimum numer of people in it. So adding a new people to this group will increase success probability. But we know that adding $j$-th is better than $i$-th. So we have found a better answer. So we have a very easy solution of this problem. After sorting probabilities we should you some suffix of it. Because of sorting time complexity is $O(nlogn)$.",
    "tags": [
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "442",
    "index": "C",
    "title": "Artem and Array ",
    "statement": "Artem has an array of $n$ positive integers. Artem decided to play with it. The game consists of $n$ moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets $min(a, b)$ points, where $a$ and $b$ are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.\n\nAfter the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.",
    "tutorial": "It's obvious that we should never delete the first and last elements of array. Let's look at the minimum number. Let it be $x$ and there are $n$ elements in the array. We can subtract $x$ from all elements and the answer for the problem will decrease on $(n - 2) \\cdot x$, becouse we will do $n - 2$ delitions of middle elements and each of this delitions will not give Artem exectly $x$ more points. If minimal element was the first or the last one, we can not to count it now (it equals to 0 now, so it will not affect the answer now). If it locates in the middle of array, we can prove that there is exist an optimal solution when Artem deletes this element on first move. We can prove it by contradaction. Let's look at the optimal answer where the minimal element is deleted on the minimal possible move (but not on first one). We can prove that we can delete it earlier. If move which is exactly before deleting minimum uses element of array which isn't a neighbour of minimual one we can swap this two delitions and it will not affect the answer. If those elements are neighbours we can write down the number of points which we obtain in both cases and understand that to delete minimum first is the best choice. So, in this task we need to maintain a set of all not deleted elements and to find a smallest alive element. All of it we can do with built-in data structures in time $O(nlogn)$.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "442",
    "index": "D",
    "title": "Adam and Tree",
    "statement": "When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions:\n\n- There is no vertex that has more than two incident edges painted the same color.\n- For any two vertexes that have incident edges painted the same color (say, $c$), the path between them consists of the edges of the color $c$.\n\nNot all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree.\n\nInitially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree.",
    "tutorial": "First, let's solve the task with already built tree. We can do it with easy dymanic programming. We will count the answer for subtree with an edge to the parent. If we can count it for all vertices we can calculate the answer for the whole tree as maximum of answers for children of root. How to calculate it for one vertex? Suppose we already know answers for children of this vertex. We should color the edge to the parent in the same color as edge to the child with maximum answer. Let two maximum answers for child be $max_{1}$ and $max_{2}$ then the answer for this vertex would be $max(max_{1}, max_{2} + 1)$ if $max_{1}  \\ge  max_{2}$. What changes when we can add new vertices? Nothing. We can calculate the value of dynamic programming for new vertex (it always would be 1) and recalculate value for its parent. If it doesn't change we should stop this process, in another case we continue recalculations of dynamic programming values: go to its parent and recalculate answer for it and so on. If we maintain two maximums for each vertex in $O(1)$ the asymptotic of the algorithm would be $O(nlogn)$. To prove it we can use some facts about Heavy-light decomposion. We can use the way Heavy-light decomposion splits edges of tree as our decomposition. We know that answer for such decomposition will be less than logarithm of the number of vertices. So each value of dynamic programming will be increased not more than $O(logn)$ times.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "442",
    "index": "E",
    "title": "Gena and Second Distance",
    "statement": "Gena doesn't like geometry, so he asks you to solve this problem for him.\n\nA rectangle with sides parallel to coordinate axes contains $n$ dots. Let's consider some point of the plane. Let's count the distances from this point to the given $n$ points. Let's sort these numbers in the non-decreasing order. We'll call the beauty of the point the second element of this array. If there are two mimimum elements in this array, the beaty will be equal to this minimum.\n\nFind the maximum beauty of a point inside the given rectangle.",
    "tutorial": "To solve this problem we can use a binary search. How do we check that answer if not less than $R$? It means that we can draw a circle with such radius which center locates in the rectangle and there are no more than one point inside this circle. How could we check it? We always can shift this circle in such a way that at least one point would be on its border. We can try all points as one which is on border. Than we should draw a circle with center in it and intersect it with $n - 1$ circles built on other points. If there is a point on this circle which is covered with no more than one other circle, than answer is greater or equal $R$. Finding such point is almost a typical problem which can be solved in $O(klogk)$ where $k$ - number of intersections points of circles. We described a solution which works in $O(logAnswer \\cdot n^{2} \\cdot logn)$. But we can make it faster. Let's try all vertices as centers of circles and inside this loop make a binary search. We can make one optimize: if we can't find a point on circle with radius which is equal to the best now known than we shouldn't do a binary search in this point (because we can't increase the answer). It can be proved that this solution in avarage case works in $O(logAnswer \\cdot nlog^{2}n + n^{2}logn)$ if we shuffle points. It's true because a binary search will be used in avarage only $logn$ times. To prove this fact let's look at probability of binary search to be used in $i$-th step. If all values are different and shuffled it is $\\frac{1}{\\overline{{s}}}$. It is known that sum of first $n$ elements of this sirie is bounded by $logn$. In this task there are some technical issues you need to know about. For example, we would do a binary search only $O(logn)$ times if we find a stricly incresing subseqence of answers. That's why before using a binary search we should check that we can obtain not current answer but current answer plus some small value. Also we need to understand what \"small value\" is (it should be something like $eps \\cdot curAnswer$, where $eps = 10^{ - 9}$, in another case you will probably have some problems with accuracy).",
    "tags": [
      "geometry"
    ],
    "rating": 3100
  },
  {
    "contest_id": "443",
    "index": "A",
    "title": "Anton and Letters",
    "statement": "Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.\n\nUnfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.",
    "tutorial": "In this task you are to count the number of different letters in the set. In my opinion the easiest way to do this looks like this. You just iterate over all small latin letters and check if the string contains it (with built-in functions).",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "443",
    "index": "B",
    "title": "Kolya and Tandem Repeat",
    "statement": "Kolya got string $s$ for his birthday, the string consists of small English letters. He immediately added $k$ more characters to the right of the string.\n\nThen Borya came and said that the new string contained a tandem repeat of length $l$ as a substring. How large could $l$ be?\n\nSee notes for definition of a tandem repeat.",
    "tutorial": "Let's add $k$ question marks to the string. Than we can check all possible starting and ending positions of tandem repeat in a new string. We can check each of them in time $O(n + k)$. We only need to check that some symbols are equal (in our task question mark is equal to every symbol).",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "444",
    "index": "A",
    "title": "DZY Loves Physics",
    "statement": "DZY loves Physics, and he enjoys calculating density.\n\nAlmost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:\n\n\\[\n\\left\\{{\\frac{v}{e}}{\\qquad(e>0)}\\right.\\qquad(e>0)\n\\]\n\nwhere $v$ is the sum of the values of the nodes, $e$ is the sum of the values of the edges.Once DZY got a graph $G$, now he wants to find a connected induced subgraph $G'$ of the graph, such that the density of $G'$ is as large as possible.\n\nAn induced subgraph $G'(V', E')$ of a graph $G(V, E)$ is a graph that satisfies:\n\n- $V^{\\prime}\\subseteq V$;\n- edge $(a,b)\\in E^{\\prime}$ if and only if $a\\in V^{\\prime}.b\\in V^{\\prime}$, and edge $(a,b)\\in E$;\n- the value of an edge in $G'$ is the same as the value of the corresponding edge in $G$, so as the value of a node.\n\nHelp DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.",
    "tutorial": "If there is a connected induced subgraph containing more than $2$ nodes with the maximum density. The density of every connected induced subgraph of it that contains only one edge can be represented as $\\frac{\\i I+v}{\\mathbb{C}}$, where $u, v$ are the values of the two nodes linked by the edge. The density of the bigger connected induced subgraph is at most $\\frac{\\sum_{u+1}\\sum v}{\\sum c}$. If $B={\\frac{\\Sigma_{u+}\\Sigma_{v}}{\\Sigma c}}$, and for every edge, $\\overset{n\\neq v}{c}<B$. Then we'll have $u + v < Bc$, and $\\textstyle\\sum u+\\sum v<B\\sum c$, and $B>{\\frac{\\Sigma_{u+1\\Sigma v}}{\\Sigma c}}$, it leads to contradiction. So just check every single node, and every $2$ nodes linked by an edge. The time complexity is $O(n + m)$.",
    "code": "#include <cstdio>\n#include <algorithm>\nusing namespace std;\n\nint n, m, a, b, c, x[1100];\n\nint main() {\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 1; i <= n; i++)\tscanf(\"%d\", &x[i]);\n\tdouble ans = 0;\n\tfor (int i = 1; i <= m; i++) {\n\t\tscanf(\"%d%d%d\", &a, &b, &c);\n\t\tans = max(ans, 1.0 * (x[a] + x[b]) / c);\n\t}\n\tprintf(\"%.15lf\\n\", ans);\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "444",
    "index": "B",
    "title": "DZY Loves FFT",
    "statement": "DZY loves Fast Fourier Transformation, and he enjoys using it.\n\nFast Fourier Transformation is an algorithm used to calculate convolution. Specifically, if $a$, $b$ and $c$ are sequences with length $n$, which are indexed from $0$ to $n - 1$, and\n\n\\[\nc_{i}=\\sum_{j=0}^{i}a_{j}b_{i-j}.\n\\]\n\nWe can calculate $c$ fast using Fast Fourier Transformation.\n\nDZY made a little change on this formula. Now\n\n\\[\nc_{i}=\\operatorname*{m}_{j=0}^{i}x_{\\lambda}b_{i-j}.\n\\]\n\nTo make things easier, $a$ is a permutation of integers from $1$ to $n$, and $b$ is a sequence only containing $0$ and $1$. Given $a$ and $b$, DZY needs your help to calculate $c$.\n\nBecause he is naughty, DZY provides a special way to get $a$ and $b$. What you need is only three integers $n$, $d$, $x$. After getting them, use the code below to generate $a$ and $b$.\n\n\\begin{verbatim}\n//x is 64-bit variable;\nfunction getNextX() {\nx = (x * 37 + 10007) % 1000000007;\nreturn x;\n}\nfunction initAB() {\nfor(i = 0; i < n; i = i + 1){\na[i] = i + 1;\n}\nfor(i = 0; i < n; i = i + 1){\nswap(a[i], a[getNextX() % (i + 1)]);\n}\nfor(i = 0; i < n; i = i + 1){\nif (i < d)\nb[i] = 1;\nelse\nb[i] = 0;\n}\nfor(i = 0; i < n; i = i + 1){\nswap(b[i], b[getNextX() % (i + 1)]);\n}\n}\n\\end{verbatim}\n\nOperation x % y denotes remainder after division $x$ by $y$. Function swap(x, y) swaps two values $x$ and $y$.",
    "tutorial": "Firstly, you should notice that $A$, $B$ are given randomly. Then there're many ways to solve this problem, I just introduce one of them. This algorithm can get $C_{i}$ one by one. Firstly, choose an $s$. Then check if $C_{i}$ equals to $n, n - 1, n - 2... n - s + 1$. If none of is the answer, just calculate $C_{i}$ by brute force. The excepted time complexity to calculate $C_{i - 1}$ is around $s+(1-r)^{s}\\,r i$ where $r={\\frac{\\mathrm{rhe~number~of~in~}}B_{0~}\\mathrm{to~}B_{i-1}}$. Just choose an $s$ to make the formula as small as possible. The worst excepted number of operations is around tens of million.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <cmath>\n#include <ctime>\nusing namespace std;\n\nint n, d, X, A[110000], B[110000], q[110000], to[110000];\nint pu;\n\nint getNextX() {\n\tX = (X * 37LL + 10007) % 1000000007;\n    return X;\n}\n\nint main() {\n\tscanf(\"%d%d%d\", &n, &d, &X);\n    for (int i = 0; i < n; i = i + 1)\n        A[i] = i + 1;\n    for (int i = 0; i < n; i = i + 1)\n        swap(A[i], A[getNextX() % (i + 1)]);\n    for (int i = 0; i < n; i = i + 1) {\n        if (i < d)\n            B[i] = 1;\n        else\n            B[i] = 0;\n    }\n    for (int i = 0; i < n; i = i + 1)\n        swap(B[i], B[getNextX() % (i + 1)]);\n\tfor (int i = 0; i < n; i++)\tif (B[i])\tq[++q[0]] = i;\n\t\n\tint s = 30;\n\t\n\tfor (int i = 0; i < n; i++)\tto[A[i]] = i;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tint j;\n\t\tfor (j = n; j >= n - s; j--)\n\t\t\tif (j > 0 && i >= to[j] && B[i - to[j]]) {\n\t\t\t\tprintf(\"%d\\n\", j);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif (j < n - s) {\n\t\t\tint ma = 0;\n\t\t\tfor (j = 1; j <= q[0] && q[j] <= i; j++)\n\t\t\t\tma = max(ma, A[i - q[j]]);\n\t\t\tprintf(\"%d\\n\", ma);\n\t\t}\n\t}\n}",
    "tags": [
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "444",
    "index": "C",
    "title": "DZY Loves Colors",
    "statement": "DZY loves colors, and he enjoys painting.\n\nOn a colorful day, DZY gets a colorful ribbon, which consists of $n$ units (they are numbered from $1$ to $n$ from left to right). The color of the $i$-th unit of the ribbon is $i$ at first. It is colorful enough, but we still consider that the colorfulness of each unit is $0$ at first.\n\nDZY loves painting, we know. He takes up a paintbrush with color $x$ and uses it to draw a line on the ribbon. In such a case some contiguous units are painted. Imagine that the color of unit $i$ currently is $y$. When it is painted by this paintbrush, the color of the unit becomes $x$, and the colorfulness of the unit increases by $|x - y|$.\n\nDZY wants to perform $m$ operations, each operation can be one of the following:\n\n- Paint all the units with numbers between $l$ and $r$ (both inclusive) with color $x$.\n- Ask the sum of colorfulness of the units between $l$ and $r$ (both inclusive).\n\nCan you help DZY?",
    "tutorial": "The only thing you need to notice is that if there are many continuous units with the same uppermost color, just merge them in one big unit. Every time painting continuous units, such big units will only increase by at most $3$. Then you can use STL set to solve it. But anyway, a segment tree is useful enough, check the C++ solution here. The time complexity is $O(n\\log n)$.",
    "code": "#include <cstdio>\n#include <algorithm>\nusing namespace std;\n\nint n, m, t, l, r, x, mark[410000];\nlong long delta[410000], sum[410000];\n\nvoid read(int &x) {\n\tchar k;\n\tfor (k = getchar(); k <= 32; k = getchar());\n\tfor (x = 0; '0' <= k; k = getchar())\tx = x * 10 + k - '0';\n}\n\nvoid mkt(int k, int q, int h) {\n\tif (q < h) {\n\t\tmkt(k * 2, q, (q + h) / 2);\n\t\tmkt(k * 2 + 1, (q + h) / 2 + 1, h);\n\t\tmark[k] = 0;\n\t}else\tmark[k] = q;\n}\n\nlong long query(int k, int q, int h, int l, int r) {\n\tif (l <= q && h <= r)\treturn sum[k];\n\tif (r <= (q + h) / 2)\treturn query(k * 2, q, (q + h) / 2, l, r) + 1LL * delta[k] * (r - l + 1);\n\tif ((q + h) / 2 < l)\treturn query(k * 2 + 1, (q + h) / 2 + 1, h, l, r) + 1LL * delta[k] * (r - l + 1);\n\treturn query(k * 2, q, (q + h) / 2, l, (q + h) / 2) + query(k * 2 + 1, (q + h) / 2 + 1, h, (q + h) / 2 + 1, r) + 1LL * delta[k] * (r - l + 1);\n}\n\nvoid Clear(int k, int q, int h) {\n\tif (mark[k] > 0) {\n\t\tdelta[k] += abs(mark[k] - x);\n\t\tsum[k] += 1LL * abs(mark[k] - x) * (h - q + 1);\n\t}else {\n\t\tClear(k * 2, q, (q + h) / 2);\n\t\tClear(k * 2 + 1, (q + h) / 2 + 1, h);\n\t\tsum[k] = sum[k * 2] + sum[k * 2 + 1] + 1LL * delta[k] * (h - q + 1);\n\t}\n\tmark[k] = -1;\n}\n\nvoid modify(int k, int q, int h) {\n\tif (l <= q && h <= r)\tClear(k, q, h), mark[k] = x;\n\telse {\n\t\tif (mark[k] > 0)\tmark[k * 2] = mark[k * 2 + 1] = mark[k], mark[k] = 0;\n\t\tif (r <= (q + h) / 2)\tmodify(k * 2, q, (q + h) / 2);\n\t\telse\tif ((q + h) / 2 < l)\tmodify(k * 2 + 1, (q + h) / 2 + 1, h);\n\t\telse\tmodify(k * 2, q, (q + h) / 2), modify(k * 2 + 1, (q + h) / 2 + 1, h);\n\t\tmark[k] = 0;\n\t\tsum[k] = sum[k * 2] + sum[k * 2 + 1] + 1LL * delta[k] * (h - q + 1);\n\t}\n}\n\nint main() {\n\tread(n); read(m);\n\tmkt(1, 1, n);\n\twhile (m--) {\n\t\tread(t); read(l); read(r);\n\t\tif (t == 1) {\n\t\t\tread(x);\n\t\t\tmodify(1, 1, n);\n\t\t}else {\n\t\t\tprintf(\"%I64d\\n\", query(1, 1, n, l, r));\n\t\t}\n\t}\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "444",
    "index": "D",
    "title": "DZY Loves Strings",
    "statement": "DZY loves strings, and he enjoys collecting them.\n\nIn China, many people like to use strings containing their names' initials, for example: xyz, jcvb, dzy, dyh.\n\nOnce DZY found a lucky string $s$. A lot of pairs of good friends came to DZY when they heard about the news. The first member of the $i$-th pair has name $a_{i}$, the second one has name $b_{i}$. Each pair wondered if there is a substring of the lucky string containing both of their names. If so, they want to find the one with minimum length, which can give them good luck and make their friendship last forever.\n\nPlease help DZY for each pair find the minimum length of the substring of $s$ that contains both $a_{i}$ and $b_{i}$, or point out that such substring doesn't exist.\n\nA substring of $s$ is a string $s_{l}s_{l + 1}... s_{r}$ for some integers $l, r$ $(1 ≤ l ≤ r ≤ |s|)$. The length of such the substring is $(r - l + 1)$.\n\nA string $p$ contains some another string $q$ if there is a substring of $p$ equal to $q$.",
    "tutorial": "We can solve a subproblem in which all the query strings are characters only first. The problem becomes calculating the shortest substring containing two given characters. If character $ch$ appears more than $T$ times in $S$, use brute force with time complexity $O(|S|)$ to calculate all the queries containing $ch$. Obviously, there are at most $O(|S| / T)$ such $ch$ in $S$. Otherwise, we consider two sorted sequences, just merge them with time complexity $O(T)$(Both of the two characters appear at most $T$ times). Being merging, you can get the answer. So the complexity is $O(TQ + |S|^{2} / T)$. We can choose $T=|S|/{\\sqrt{Q}}$, then the complexity is $O(|S|{\\sqrt{Q}})$. And short substring is almost the same with characters.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n#define rep(i,x,y) for(i=x;i<=y;i++)\n#define pb push_back\n#define mp make_pair\n#define upmin(x,y) x=min(x,y)\nconst int L=50010,R=4,N=L*R,Q=100010,inf=int(1e9);\nint l,q,g,all,i,j,k,p,x,y,p1,p2,res,tot;char s[L],s0[11];\nint h[600000],ans[Q],d[R+1][L],tmp[N],li[N],l2[N],pos[N],num[N],vg[N],la[L],ne[L];vector<int> v[N];\nstruct ask{int x,y,lx,ly,nn;}c[Q];\nbool cmp(ask a,ask b){return mp(a.x,a.y)<mp(b.x,b.y);}\nint ins(int x){if(h[x])return h[x];num[++tot]=x;return h[x]=tot;}\nint getstr(int&l0){\n    scanf(\"%s\",s0+1);int i,res;l0=strlen(s0+1);\n    for(res=0,i=1;i<=l0;i++)res=res*27+(s0[i]-'a'+1);return res;\n}\nvoid calcd(int id,int l0){\n    int i,j,k,la0,ne0,now;\n    rep(j,1,R){\n        for(int k=0;k<=l;k++)la[k]=-inf,ne[k]=inf;\n        for(int k=0;k<vg[id];k++){\n            now=v[id][k];\n            la0=(k==0)?1:v[id][k-1]+1;\n            ne0=(k==vg[id]-1)?l:v[id][k+1]-1;\n            rep(i,now,ne0)la[i]=now;\n            rep(i,la0,now)ne[i]=now;\n        }\n        rep(i,1,l)d[j][i]=min(max(i+j,ne[i]+l0)-i,max(i+j,la[i]+l0)-la[i]);\n    }\n}\nint main(){\n    scanf(\"%s%d\",s+1,&q);l=strlen(s+1);\n\trep(i,1,l)for(res=0,j=1;j<=R&&i+j-1<=l;j++)\n    l2[++all]=j,v[pos[all]=ins(res=res*27+(s[i+j-1]-'a'+1))].pb(li[all]=i);\n    rep(i,1,tot)vg[i]=v[i].size();\n    rep(i,1,q){\n        int ida=h[getstr(p1)],idb=h[getstr(p2)];\n        if(ida==0||idb==0)ans[i]=-1;\n        else{ans[i]=inf;if(vg[ida]<vg[idb])swap(ida,ida);c[++g]=(ask){ida,idb,p1,p2,i};}\n    }\n    sort(c+1,c+1+g,cmp);\n    for(i=1;i<=g;i=j+1){\n        long long totcnt=0;\n        for(j=i;j<=g&&c[j].x==c[i].x;j++)totcnt+=vg[c[j].y]+vg[c[i].x];j--;\n        if(totcnt>all){\n            calcd(c[i].x,c[i].lx);    \n            rep(k,1,tot)tmp[k]=inf;\n            rep(k,1,all)upmin(tmp[pos[k]],d[l2[k]][li[k]]);\n            rep(k,i,j)upmin(ans[c[k].nn],tmp[c[k].y]);\n        }\n        else\n        rep(k,i,j)\n        for(p1=p2=0,x=c[k].x,y=c[k].y;p1<vg[x]&&p2<vg[y];v[x][p1]<=v[y][p2]?p1++:p2++)\n        upmin(ans[c[k].nn],max(v[x][p1]+c[k].lx,v[y][p2]+c[k].ly)-min(v[x][p1],v[y][p2]));\n    }\n    rep(i,1,q)printf(\"%d\\n\",ans[i]);\n    return 0;\n}",
    "tags": [
      "binary search",
      "hashing",
      "strings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "444",
    "index": "E",
    "title": "DZY Loves Planting",
    "statement": "DZY loves planting, and he enjoys solving tree problems.\n\nDZY has a weighted tree (connected undirected graph without cycles) containing $n$ nodes (they are numbered from $1$ to $n$). He defines the function $g(x, y)$ $(1 ≤ x, y ≤ n)$ as the longest edge in the shortest path between nodes $x$ and $y$. Specially $g(z, z) = 0$ for every $z$.\n\nFor every integer sequence $p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$, DZY defines $f(p)$ as $\\operatorname*{min}_{i=1}g(i,p_{i})$.\n\nDZY wants to find such a sequence $p$ that $f(p)$ has maximum possible value. But there is one more restriction: the element $j$ can appear in $p$ at most $x_{j}$ times.\n\nPlease, find the maximum possible $f(p)$ under the described restrictions.",
    "tutorial": "Firstly, use binary search. We need to determine whether the answer can be bigger than $L$. Then, every pair $(i, P_{i})$ must contain at least one edge which length is bigger than $L$. It's a problem like bipartite graph matching, and we can use maxflow algorithm to solve it. We create $2$ nodes for every node $i$ of the original tree. We call one of the nodes $L_{i}$, and the other $R_{i}$. And we need a source $s$ and a terminal $t$. Link $s$ to every $L_{i}$ with upper bound $1$, and link $R_{i}$ to $t$ with upper bound $x_{i}$. Then if the path between node $a$ and node $b$ contains an edge with value larger than $L$, link $L_{a}$ and $R_{b}$ with upper bound $1$. This means they can match. Every time we build such graph, we must check $O(N^{2})$ pairs of nodes, so number of edges of the network is $O(N^{2})$. We can make it better. Consider the process of \\texttt{Divide and Conquer} of a tree, This algorithm can either based on node or edge. And The one based on edge is simpler in this problem. Now, there are two subtrees $T_{x}$, $T_{y}$ on two sides, we record the maximum edge from every node $i$ to the current edge we split, we call it $MAXL_{i}$. Suppose $L_{x}$ is in $T_{x}$ and $R_{y}$ is in $T_{y}$ (it is almost the same in contrast). We create two new nodes $G_{x}$, $G_{y}$ in the network to represent the two subtrees. Add edges $(L_{i}, G_{x},  \\infty )$ ($i$ is in $T_{x}$) and edges $(G_{y}, R_{i},  \\infty )$ ($i$ is in $T_{y}$). If $i$ is in $T_{x}$ and $MAXL_{i} > L$, we add an edge $(L_{i}, G_{y},  \\infty )$. If $j$ is in $T_{y}$ and $MAXL_{j} > L$, we add an edge $(G_{x}, R_{j},  \\infty )$. Then use maxflow algorithm. The number of nodes in the network is $O(N)$ and the number of edges in the network is $O(N\\log N)$. So the total complexity is $O(N^{2}\\log^{2}N)$ with really small constant.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n#define rep(i,x,y) for(i=x;i<=y;i++)\n#define REP(i,x,y) for(int i=(x);i<=(y);i++)\n#define CL(S,x) memset(S,x,sizeof(S))\n#define CP(S1,S2) memcpy(S1,S2,sizeof(S2))\n#define pb push_back\nconst int N=12010,inf=int(1e9),V=100010,E=500010;\nint n,n0,i,j,k,l,r,p,x,y,z,L,X[N],o[N];\nstruct FlowG{\n    int S,T,N,edge,e[E],b[E],c[E],fir[V],last[V],vh[V],h[V],cur[V],pre[V];\n    void clear(){edge=1;CL(fir,0);}\n    void add2(int x,int y,int z){e[++edge]=y;c[edge]=z;b[edge]=fir[x];fir[x]=edge;}\n    void add(int x,int y,int z){add2(x,y,z);add2(y,x,0);}\n    int sap(){\n        int i,k,p,flow,minh,ans=0;CL(h,0);CL(vh,0);vh[0]=N;CP(cur,fir);CL(pre,0);pre[S]=S;\n        for(i=S;h[S]<N;){\n            if(i==T){\n                flow=inf;for(p=S;p!=T;p=e[cur[p]])flow=min(flow,c[cur[p]]);\n                ans+=flow;for(p=S;p!=T;p=e[cur[p]])c[cur[p]]-=flow,c[cur[p]^1]+=flow;i=S;\n            }\n            for(k=cur[i];k;k=b[k])\n            if(c[k]&&h[e[k]]+1==h[i]){cur[i]=k;pre[e[k]]=i;i=e[k];break;}\n            if(!k){\n                if(--vh[h[i]]==0)break;\n                cur[i]=fir[i];minh=N;for(k=cur[i];k;k=b[k])if(c[k])minh=min(minh,h[e[k]]+1);\n                ++vh[h[i]=minh];i=pre[i];\n            }\n        }\n        return ans;\n    }\n}F;\n\nstruct graph{\n    int edge,fir[N],e[N],b[N],w[N];bool done[N];\n    int fa[N],fae[N],sz[N],ms[N],st[N],st1[N],st2[N];\n    void clear(){edge=1;CL(fir,0);}void add2(int x,int y,int z){e[++edge]=y;w[edge]=z;b[edge]=fir[x];fir[x]=edge;}\n    void add(int x,int y,int z){add2(x,y,z);add2(y,x,z);}\n    int dfs(int i,int f,int ma){st[++st[0]]=i;fa[i]=f;sz[i]=1;ms[i]=ma;for(int k=fir[i];k;k=b[k])if(!done[k]&&e[k]!=f)fae[e[k]]=k,sz[i]+=dfs(e[k],i,max(ma,w[k]));return sz[i];}\n    void fadd(){\n        int t1=++F.N;REP(p,1,st1[0])F.add(st1[p],t1,inf); REP(p,1,st2[0])if(ms[st2[p]]>=L)F.add(t1,n+st2[p],inf);\n        int t2=++F.N;REP(p,1,st1[0])if(ms[st1[p]]>=L)F.add(st1[p],t2,inf); REP(p,1,st2[0])F.add(t2,n+st2[p],inf);\n    }\n    void fun(int r){\n        st[0]=0;int sz0=dfs(r,0,0),best=N,A,B,O,p;if(sz0<=1)return;\n        rep(p,2,st[0]){int i=st[p],tt;if((tt=max(sz0-sz[i],sz[i]))<best)best=tt,A=i,B=fa[i],O=fae[i];}\n        done[O]=done[O^1]=1;\n        st[0]=0;dfs(A,0,w[O]);rep(i,0,st[0])st1[i]=st[i];\n        st[0]=0;dfs(B,0,w[O]);rep(i,0,st[0])st2[i]=st[i];\n        fadd();rep(i,0,sz0)swap(st1[i],st2[i]);fadd();\n        fun(A);fun(B);\n    }\n    bool ok(){\n        F.clear();F.S=2*n+1;F.N=F.T=2*n+2;REP(i,1,n0)F.add(F.S,i,1);REP(i,1,n0)F.add(n+i,F.T,X[i]);\n        CL(done,0);fun(1);return F.sap()==n0;\n    }\n}H;\n\nstruct ori{\n    vector<int> e[N],ew[N];int li[N],lw[N];\n    void adde(int x,int y,int z){e[x].pb(y);ew[x].pb(z);}\n    void work(int x,int y,int f){\n        if(x==y){H.add(f,li[x],lw[x]);return;}\n        int nod=++n;H.add(f,nod,0);work(x,(x+y)/2,nod);work((x+y)/2+1,y,nod);\n    }\n    void bui(int i,int f){\n        li[0]=0;for(int k=0;k<e[i].size();k++)if(e[i][k]!=f)li[++li[0]]=e[i][k],lw[li[0]]=ew[i][k];\n        if(li[0])work(1,li[0],i);for(int k=0;k<e[i].size();k++)if(e[i][k]!=f)bui(e[i][k],i);\n    }\n}G;\n\nint main(){\n\tscanf(\"%d\",&n);n0=n;\n\trep(i,1,n-1)scanf(\"%d%d%d\",&x,&y,&z),G.adde(x,y,z),G.adde(y,x,z),o[i]=z;rep(i,1,n)scanf(\"%d\",&X[i]);\n    sort(o+1,o+1+(n-1));o[0]=1;rep(i,2,n-1)if(o[i]!=o[i-1])o[++o[0]]=o[i];\n\tH.clear();G.bui(1,0);\n\tfor(l=1,r=o[0];l<r;){int mid=(l+r+1)/2;L=o[mid];if(H.ok())l=mid;else r=mid-1;}printf(\"%d\\n\",o[l]);\n    return 0;\n}",
    "tags": [
      "binary search",
      "dsu",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "445",
    "index": "A",
    "title": "DZY Loves Chessboard",
    "statement": "DZY loves chessboard, and he enjoys playing with it.\n\nHe has a chessboard of $n$ rows and $m$ columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.\n\nYou task is to find any suitable placement of chessmen on the given chessboard.",
    "tutorial": "Just output the chessboard like this: WBWBWBWB... BWBWBWBW... WBWBWBWB... ... Don't forget to left '-' as it is. The time complexity is $O(nm)$.",
    "code": "#include <cstdio>\nusing namespace std;\n\nint n, m;\nchar S[1100];\n\nint main() {\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 0; i < n; i++) {\n\t\tscanf(\"%s\", S);\n\t\tfor (int j = 0; j < m; j++)\n\t\t\tif (S[j] == '.') {\n\t\t\t\tif ((i + j) & 1)\tS[j] = 'W';\n\t\t\t\telse\tS[j] = 'B';\n\t\t\t}\n\t\tprintf(\"%s\\n\", S);\n\t}\n}",
    "tags": [
      "dfs and similar",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "445",
    "index": "B",
    "title": "DZY Loves Chemistry",
    "statement": "DZY loves chemistry, and he enjoys mixing chemicals.\n\nDZY has $n$ chemicals, and $m$ pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.\n\nLet's consider the danger of a test tube. Danger of an empty test tube is $1$. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by $2$. Otherwise the danger remains as it is.\n\nFind the maximum possible danger after pouring all the chemicals one by one in optimal order.",
    "tutorial": "It's easy to find that answer is equal to $2^{n - v}$, where $v$ is the number of connected components.",
    "code": "#include <cstdio>\nusing namespace std;\n\nint n, m, fa[100], x, y;\n\nint gf(int x) {\n\tif (fa[x] != x)\tfa[x] = gf(fa[x]);\n\treturn fa[x];\n}\n\nint main() {\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 1; i <= n; i++)\tfa[i] = i;\n\twhile (m--) {\n\t\tscanf(\"%d%d\", &x, &y);\n\t\tfa[gf(x)] = gf(y);\n\t}\n\tlong long ans = (1LL << n);\n\tfor (int i = 1; i <= n; i++)\n\t\tif (gf(i) == i)\tans /= 2;\n\tprintf(\"%I64d\\n\", ans);\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "446",
    "index": "A",
    "title": "DZY Loves Sequences",
    "statement": "DZY has a sequence $a$, consisting of $n$ integers.\n\nWe'll call a sequence $a_{i}, a_{i + 1}, ..., a_{j}$ $(1 ≤ i ≤ j ≤ n)$ a subsegment of the sequence $a$. The value $(j - i + 1)$ denotes the length of the subsegment.\n\nYour task is to find the longest subsegment of $a$, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.\n\nYou only need to output the length of the subsegment you find.",
    "tutorial": "We can first calculate $l_{i}$ for each $1  \\le  i  \\le  n$, satisfying $a_{i - li + 1} < a_{i - li + 2} < ... < a_{i}$, which $l_{i}$ is maximal. Then calculate $r_{i}$, satisfying $a_{i} < a_{i + 1} < ... < a_{i + ri - 1}$, which $r_{i}$ is also maximal. Update the answer $a n s=\\operatorname*{max}(a n s,l_{i-1}+1+r_{i+1})$, when $a_{i - 1} + 1 < a_{i + 1}$. It's easy to solve this problem in $O(n)$.",
    "tags": [
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "446",
    "index": "B",
    "title": "DZY Loves Modification",
    "statement": "As we know, DZY loves playing games. One day DZY decided to play with a $n × m$ matrix. To be more precise, he decided to modify the matrix with exactly $k$ operations.\n\nEach modification is one of the following:\n\n- Pick some row of the matrix and decrease each element of the row by $p$. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing.\n- Pick some column of the matrix and decrease each element of the column by $p$. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing.\n\nDZY wants to know: what is the largest total value of pleasure he could get after performing exactly $k$ modifications? Please, help him to calculate this value.",
    "tutorial": "If $p = 0$, apperently the best choice is choosing the row or column which can give greatest pleasure value each time. Ignore $p$ first,then we can get a greatest number $ans$. Then if we choose rows for $i$ times, choose columns for $k - i$ times, $ans$ should subtract $(k - i)  \\times  i  \\times  p$. So we could enumerate i form 0 to k and calculate $ans_{i} - (k - i) * i * p$ each time, max ${ans_{i} - (k - i) * i * p}$ is the maximum possible pleasure value DZY could get. Let $a_{i}$ be the maximum pleasure value we can get after choosing $i$ rows and $b_{i}$ be the maximum pleasure value we can get after choosing $i$ columns. Then $ans_{i} = a_{i} + b_{k - i}$. We can use two priority queues to calculate $a_{i}$ and $b_{i}$ quickly.",
    "tags": [
      "brute force",
      "data structures",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "446",
    "index": "C",
    "title": "DZY Loves Fibonacci Numbers",
    "statement": "In mathematical terms, the sequence $F_{n}$ of Fibonacci numbers is defined by the recurrence relation\n\n\\[\nF_{1} = 1; F_{2} = 1; F_{n} = F_{n - 1} + F_{n - 2} (n > 2).\n\\]\n\nDZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Moreover, there are $m$ queries, each query has one of the two types:\n\n- Format of the query \"$1 l r$\". In reply to the query, you need to add $F_{i - l + 1}$ to each element $a_{i}$, where $l ≤ i ≤ r$.\n- Format of the query \"$2 l r$\". In reply to the query you should output the value of $\\textstyle\\sum_{i=1}^{r}a_{i}$ modulo $1000000009 (10^{9} + 9)$.\n\nHelp DZY reply to all the queries.",
    "tutorial": "As we know, $F_{n}=\\stackrel{\\sqrt{5}}{5}\\left[\\left(\\frac{1\\!+\\!\\sqrt{5}}{2}\\right)^{n}-\\left(\\frac{1\\!-\\!\\sqrt{5}}{2}\\right)^{n}\\right]$ Fortunately, we find that $383008016^{2}\\equiv5({\\mathrm{mod}}\\;10^{9}+9)$ So, $383008016\\equiv{\\sqrt{5}}({\\mathrm{mod~}}10^{9}+9)$ With multiplicative inverse, we find, $\\textstyle{\\frac{\\sqrt{5}}{5}}\\equiv276601605(\\mathrm{mod}\\ 10^{9}+9)$ $\\frac{1+\\sqrt{5}}{2}\\equiv691504013(\\mathrm{mod}\\ 10^{9}+9)$ ${\\frac{1-{\\sqrt{5}}}{2}}\\equiv308495997({\\mathrm{mod~}}10^{9}+9)$ Now, $F_{n}\\equiv27601605(691504013^{n}-308495997^{n})(\\mathrm{mod}\\ 10^{9}+9)$ As you see, we can just maintain the sum of a Geometric progression $\\{a_{n}\\}=R^{n}$ This is a simple problem which can be solved with segment tree in $O(q\\log n)$.",
    "tags": [
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "446",
    "index": "D",
    "title": "DZY Loves Games",
    "statement": "Today DZY begins to play an old game. In this game, he is in a big maze with $n$ rooms connected by $m$ corridors (each corridor allows to move in both directions). You can assume that all the rooms are connected with corridors directly or indirectly.\n\nDZY has got lost in the maze. Currently he is in the first room and has $k$ lives. He will act like the follows:\n\n- Firstly he will randomly pick one of the corridors going from his current room. Each outgoing corridor has the same probability to be picked.\n- Then he will go through the corridor and then the process repeats.\n\nThere are some rooms which have traps in them. The first room definitely has no trap, the $n$-th room definitely has a trap. Each time DZY enters one of these rooms, he will lost one life. Now, DZY knows that if he enters the $n$-th room with exactly 2 lives, firstly he will lost one live, but then he will open a bonus round. He wants to know the probability for him to open the bonus round. Please, help him.",
    "tutorial": "Define important room as the trap room. Let $w(u, v)$ be equal to the probability that DZY starts at $u$ ($u$ is a important room or $u$=1) and $v$ is the next important room DZY arrived. For each $u$, we can calculate $w(u, v)$ in $O(n^{3})$ by gauss elimination. Let $A_{i}$ be equal to the $i$'th important room DZY arrived. So $A_{k - 1} = n$, specially $A_{0} = 1$. Let $ans$ be the probability for DZY to open the bonus round. Easily we can know $a n s=\\prod_{0<i<k-2}w(A_{i},A_{i+1})$. So we can calculate ans in $O(a^{3}\\log k)$($a$ is equal to the number of important rooms) by matrix multiplication. So we can solve the problem in $O(n^{4}+a^{3}\\mathrm{log}k)$. we should optimize this algorithm. We can find that each time we do gauss elimination, the variable matrix is unchanged. So we can do gauss elimination once to do preprocessing in $O(n^{3})$. Then for each time calculating $w(u, v)$, the only thing to do is substitute the constants. In this way we can calculate $w(u, v)$ in $O(n^{3})$. In this way, we can solve this problem in $O(n^{3}+a^{3}\\mathrm{log}k)$",
    "tags": [
      "math",
      "matrices",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "446",
    "index": "E",
    "title": "DZY Loves Bridges",
    "statement": "DZY owns $2^{m}$ islands near his home, numbered from $1$ to $2^{m}$. He loves building bridges to connect the islands. Every bridge he builds takes one day's time to walk across.\n\nDZY has a strange rule of building the bridges. For every pair of islands $u, v (u ≠ v)$, he has built $2^{k}$ different bridges connecting them, where $k=\\operatorname*{max}\\left\\{k:2^{k}|a b s(u-v)\\right\\}$ ($a|b$ means $b$ is divisible by $a$). These bridges are bidirectional.\n\nAlso, DZY has built some bridges connecting his home with the islands. Specifically, there are $a_{i}$ different bridges from his home to the $i$-th island. These are one-way bridges, so after he leaves his home he will never come back.\n\nDZY decides to go to the islands for sightseeing. At first he is at home. He chooses and walks across one of the bridges connecting with his home, and arrives at some island. After that, he will spend $t$ day(s) on the islands. Each day, he can choose to stay and rest, or to walk to another island across the bridge. It is allowed to stay at an island for more than one day. It's also allowed to cross one bridge more than once.\n\nSuppose that right after the $t$-th day DZY stands at the $i$-th island. Let $ans[i]$ be the number of ways for DZY to reach the $i$-th island after $t$-th day. Your task is to calculate $ans[i]$ for each $i$ modulo $1051131$.",
    "tutorial": "Let $n = 2^{m}$. For convenience, we use indices $0, 1, ..., n - 1$ here instead of $1, 2, ..., n$, so we define $a_{0} = a_{n}$. Obviously this problem requires matrix multiplication. We define row vector $A=(a_{0},a_{1},\\cdot\\cdot\\cdot,a_{n-1})$, and matrix $B=(b_{i j})$, where $b_{ii} = 1$, $b_{i j}=\\operatorname*{max}\\left\\{2^{k}:2^{k}|i-j\\right\\}(i\\not=j)$. The answer is row vector $C=A B^{i}$. Since $n$ can be up to $3  \\times  10^{7}$, we need a more efficient way to calculate. Let $B_{k}$ denote the matrix $\\boldsymbol{B}$ when $m = k$. For example, $B_{3}=\\left({\\begin{array}{c c c c c c c c c}{{1}}&{{1}}&{{2}}&{{1}}&{{4}}&{{1}}&{{2}}&{{1}}\\\\ {{1}}&{{1}}&{{2}}&{{1}}&{{4}}&{{1}}&{{2}}&{{2}}\\\\ {{2}}&{{1}}&{{1}}&{{2}}&{{1}}&{{1}}&{{1}}&{{1}}\\\\ {{1}}&{{1}}&{{1}}&{{1}}&{{2}}&{{1}}&{{1}}&{{1}}\\\\ {{1}}&{{1}}&{{1}}&{{2}}&{{1}}&{{1}}&{{1}}\\\\ {{2}}&{{1}}&{{4}}&{{1}}&{{2}}&{{1}}&{{1}}\\\\ {{2}}&{{1}}&{{4}}&{{1}}&{{2}}&{{1}}&{{1}}\\end{array}}\\right)$ Define $B_{n}=(1)$, then we can easily find that $B_{k+1}=\\left(_{B_{k}+(2^{k}-1)I}\\begin{array}{c}{{B_{k}+(2^{k}-1)I}}\\\\ {{B_{k}}}\\end{array}\\right)$ where ${\\mathbf I}$ denotes the identity matrix. For an $n  \\times  n$ matrix $X$ and a constant $r$, we can prove by induction that $\\left({\\begin{array}{l l}{X}&{X+r I}\\\\ {X+r I}&{X}\\end{array}}\\right)^{t}={\\frac{1}{2}}\\left((2X+r I)^{t}+(-r)^{t}I}&{(2X+r I)^{t}-(-r)^{t}I\\right)$ Let $ \\alpha _{1},  \\alpha _{2}$ be two $1  \\times  n$ vectors, then we have $\\begin{array}{c}{{\\left(\\alpha_{1}\\,\\,\\,\\,\\alpha_{2}\\right)\\left({_X+r I\\,\\,X}_{1}^{\\phantom{\\dagger}X+r I}\\right)^{t}}}\\\\ {{\\frac{\\left(\\alpha_{1}+\\alpha_{2}\\right)\\left({2X+r I+r I}\\right)^{t}-\\alpha_{2}\\right)\\left(-r\\right)^{t}}{\\left(\\alpha_{1}+\\alpha_{2}\\right)\\left({2X+r I\\right)^{t}-\\left(\\alpha_{1}-\\alpha_{2}\\right)\\left(-r\\right)^{t}}I\\right)}}\\end{array}$ This result seems useful. Suppose we want to find $A(p B_{k+1}+q I)^{t}$, where $A=\\left(\\alpha_{1}\\ \\ \\alpha_{2}\\right)$, we have $\\begin{array}{l l}{{}}&{{A/B_{k+1}+q I^{\\prime}}}\\\\ {{(\\alpha_{1}+\\alpha_{2})\\left({}_{p}B_{k}+\\alpha I+\\nu(z^{\\prime}p-\\nu-q)I^{\\prime}\\right)^{\\prime}}}&{{\\nu B_{k}+q I^{\\prime}\\left(2^{a}p-p-q I\\right)^{\\prime}}}\\\\ {{}}&{{\\left[(\\alpha_{1}+\\alpha_{2})(2p-\\nu-\\nu-q I^{\\prime}+\\nu+q I^{\\prime})^{\\prime}+(\\alpha_{1}-\\alpha_{2})(2p+(z^{a}p+\\nu+\\nu+q I^{\\prime})^{\\prime}-(\\alpha_{1}-\\alpha_{2})(2\\nu-\\nu-\\nu+q I^{\\prime})^{\\prime}-(\\alpha_{1}-\\alpha_{2})(-2^{a}p+\\nu+\\bar{\\nu})^{\\prime}+\\bar{\\nu}})^{\\prime}}\\end{array}$ so we just need to find $(\\alpha_{1}+\\alpha_{2})(2p B_{k}+(2^{k}p-p+q)I)^{t}$, which is a self-similar problem. By recursion, it can be solved in time $T(n) = T(n / 2) + O(n) = O(n)$.",
    "tags": [
      "math",
      "matrices"
    ],
    "rating": 3100
  },
  {
    "contest_id": "447",
    "index": "A",
    "title": "DZY Loves Hash",
    "statement": "DZY has a hash table with $p$ buckets, numbered from $0$ to $p - 1$. He wants to insert $n$ numbers, in the order they are given, into the hash table. For the $i$-th number $x_{i}$, DZY will put it into the bucket numbered $h(x_{i})$, where $h(x)$ is the hash function. In this problem we will assume, that $h(x) = x mod p$. Operation $a mod b$ denotes taking a remainder after division $a$ by $b$.\n\nHowever, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a \"conflict\" happens. Suppose the first conflict happens right after the $i$-th insertion, you should output $i$. If no conflict happens, just output -1.",
    "tutorial": "We just need an array to store the numbers inserted and check whether a conflict happens. It's easy.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "447",
    "index": "B",
    "title": "DZY Loves Strings",
    "statement": "DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter $c$ DZY knows its value $w_{c}$. For each special string $s = s_{1}s_{2}... s_{|s|}$ ($|s|$ is the length of the string) he represents its value with a function $f(s)$, where\n\n\\[\nf(s)=\\sum_{i=1}^{\\mathbb{N}_{1}}(w_{s_{i}}\\cdot i).\n\\]\n\nNow DZY has a string $s$. He wants to insert $k$ lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?",
    "tutorial": "Firstly the optimal way is to insert letter with maximal $w_{i}$. Let $n u m=\\mathbf{max}${$w_{i}$}. If we insert this character into the $k$'th position, the extra value we could get is equal to $\\begin{array}{l}{{\\sum_{i=k}^{n}w_{s_{i}}+n u m\\star k=\\sum_{i=1}^{k}n u m+\\sum_{i=k}^{n}w_{s_{i}}}}\\end{array}$. Because of $w_{si}  \\le  num$, when $k = n + 1$, we can get the largest extra value. So if we insert the k letters at the end of $S$, we will get the largest possible value.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "448",
    "index": "A",
    "title": "Rewards",
    "statement": "Bizon the Champion is called the Champion for a reason.\n\nBizon the Champion has recently got a present — a new glass cupboard with $n$ shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has $a_{1}$ first prize cups, $a_{2}$ second prize cups and $a_{3}$ third prize cups. Besides, he has $b_{1}$ first prize medals, $b_{2}$ second prize medals and $b_{3}$ third prize medals.\n\nNaturally, the rewards in the cupboard must look good, that's why Bizon the Champion decided to follow the rules:\n\n- any shelf cannot contain both cups and medals at the same time;\n- no shelf can contain more than five cups;\n- no shelf can have more than ten medals.\n\nHelp Bizon the Champion find out if we can put all the rewards so that all the conditions are fulfilled.",
    "tutorial": "Because rewards of one type can be on one shelf, lets calculate number of cups - $a$ and number of medals - $b$. Minimum number of shelves that will be required for all cups can be found by formula $(a + 5 - 1) / 5$. The same with shelves with medals: $(b + 10 - 1) / 10$. If sum of this two values more than $n$ then answer is \"NO\" and \"YES\" otherwise.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <cmath>\n#include <memory.h>\nusing namespace std;\ntypedef long long ll;\n \nconst int N = 1e6+6;\n \n \n \nint main(){\n    //freopen(\"input.txt\",\"r\",stdin);// freopen(\"output.txt\",\"w\",stdout);\n    \n    int a1,a2,a3,b1,b2,b3,K;\n    cin>>a1>>a2>>a3>>b1>>b2>>b3>>K;\n    \n    int a = (a1+a2+a3 + 4) / 5;\n    int b = (b1+b2+b3 + 9) / 10;\n    \n    cout<<(a+b<=K ? \"YES\" : \"NO\")<<endl;\n    \n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "448",
    "index": "B",
    "title": "Suffix Structures",
    "statement": "Bizon the Champion isn't just a bison. He also is a favorite of the \"Bizons\" team.\n\nAt a competition the \"Bizons\" got the following problem: \"You are given two distinct words (strings of English letters), $s$ and $t$. You need to transform word $s$ into word $t$\". The task looked simple to the guys because they know the suffix data structures well. Bizon Senior loves suffix automaton. By applying it once to a string, he can remove from this string any single character. Bizon Middle knows suffix array well. By applying it once to a string, he can swap any two characters of this string. The guys do not know anything about the suffix tree, but it can help them do much more.\n\nBizon the Champion wonders whether the \"Bizons\" can solve the problem. Perhaps, the solution do not require both data structures. Find out whether the guys can solve the problem and if they can, how do they do it? Can they solve it either only with use of suffix automaton or only with use of suffix array or they need both structures? Note that any structure may be used an unlimited number of times, the structures may be used in any order.",
    "tutorial": "Consider each case separately. If we use only suffix automaton then $s$ transform to some of its subsequence. Checking that $t$ is a subsequence of $s$ can be performed in different ways. Easiest and fastest - well-known two pointers method. In case of using suffix array we can get every permutation of $s$. If it is not obvious for you, try to think. Thus, $s$ and $t$ must be anagrams. If we count number of each letter in each string, we can check this. If every letter appears in $s$ the same times as in $t$ then words are anagrams. In case of using both structures strategy is: remove some letters and shuffle the rest. It is possible if every letter appears in $s$ not less times than in $t$. Otherwise it is impossible to make $t$ from $s$. Total complexity $O(|s| + |t| + 26)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <cmath>\n#include <memory.h>\nusing namespace std;\ntypedef long long ll;\n \n \nconst int N = 1e5+5;\n \nint cnt[30];\nchar s[N], t[N];\n \n \nvoid solve(){\n    scanf(\"%s%s\",&s,&t);\n    int n = strlen(s);\n    int m = strlen(t);\n    \n    memset(cnt, 0, sizeof cnt);\n    \n    bool sau = false;\n    for(int i=0,j=0; i<n; ++i){\n        if(j<m && s[i]==t[j]) ++j;\n        if(j==m) sau = true;\n    }\n    \n    for(int i=0;i<n;++i) cnt[s[i]-'a']++;\n    for(int i=0;i<m;++i) cnt[t[i]-'a']--;\n    \n    bool sar = true;\n    bool all = true;\n    \n    for(int i=0;i<26;++i){\n        sar&=cnt[i]==0;\n        all&=cnt[i]>=0;\n    }\n    \n    if(sau) cout<<\"automaton\"<<endl; else\n    if(sar) cout<<\"array\"<<endl; else\n    if(all) cout<<\"both\"<<endl; else\n    cout<<\"need tree\"<<endl;\n}\n \nint main(){\n    //freopen(\"input.txt\",\"r\",stdin);// freopen(\"output.txt\",\"w\",stdout);\n    \n    solve();\n    \n    return 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "448",
    "index": "C",
    "title": "Painting Fence",
    "statement": "Bizon the Champion isn't just attentive, he also is very hardworking.\n\nBizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as $n$ vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the $i$-th plank has the width of $1$ meter and the height of $a_{i}$ meters.\n\nBizon the Champion bought a brush in the shop, the brush's width is $1$ meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.",
    "tutorial": "To solve this problem we need to understand some little things. First, every horizontally stroke must be as widely as possible. Second, under every horizontally stroke should be only horizontally strokes. So, if bottom of fence painted by horizontally stroke then number of this strokes must at least $min(a_{1}, a_{2}, ..., a_{n})$. These strokes maybe divides fence into some unpainted disconnected parts. For all of these parts we need to sum they answers. Now its clearly that solution is recursive. It takes segment $[l, r]$ and height of painted bottom $h$. But we must not forget about situation when all planks painted with vertically strokes. In this case answer must be limited by $r - l + 1$ (length of segment). With given constrains of $n$ we can find minimum on segment by looking all the elements from segment. Complexity in this case will be $O(n^{2})$. But if we use for example segment tree, we can achieve $O(nlogn)$ complexity.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <cmath>\n#include <memory.h>\nusing namespace std;\ntypedef long long ll;\n \nconst int N = 1e6+6;\nconst int T = 1e6+6;\n \nint a[N];\nint t[T], d;\n \n \nint rmq(int i, int j){\n    int r = i;\n    for(i+=d,j+=d; i<=j; ++i>>=1,--j>>=1){\n        if(i&1) r=a[r]>a[t[i]]?t[i]:r;\n        if(~j&1) r=a[r]>a[t[j]]?t[j]:r;\n    }\n    return r;\n}\n \nint calc(int l, int r, int h){\n    if(l>r) return 0;\n    \n    int m = rmq(l,r);\n    int mn = a[m];\n    \n    int res = min(r-l+1, calc(l,m-1,mn)+calc(m+1,r,mn)+mn-h);\n    \n    return res;\n}\n \nint main(){\n    //freopen(\"input.txt\",\"r\",stdin);// freopen(\"output.txt\",\"w\",stdout);\n    \n    int n, m;\n    \n    scanf(\"%d\",&n);\n    for(int i=0;i<n;++i) scanf(\"%d\",&a[i]);\n    \n    a[n] = 2e9;\n    for(d=1;d<n;d<<=1);\n    for(int i=0;i<n;++i) t[i+d]=i;\n    for(int i=n+d;i<d+d;++i) t[i]=n;\n    for(int i=d-1;i;--i) t[i]=a[t[i*2]]<a[t[i*2+1]]?t[i*2]:t[i*2+1];\n    \n    printf(\"%d\\n\",calc(0,n-1,0));\n    \n    return 0;\n}",
    "tags": [
      "divide and conquer",
      "dp",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "448",
    "index": "D",
    "title": "Multiplication Table",
    "statement": "Bizon the Champion isn't just charming, he also is very smart.\n\nWhile some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an $n × m$ multiplication table, where the element on the intersection of the $i$-th row and $j$-th column equals $i·j$ (the rows and columns of the table are numbered starting from 1). Then he was asked: what number in the table is the $k$-th largest number? Bizon the Champion always answered correctly and immediately. Can you repeat his success?\n\nConsider the given multiplication table. If you write out all $n·m$ numbers from the table in the non-decreasing order, then the $k$-th number you write out is called the $k$-th largest number.",
    "tutorial": "Solution is binary search by answer. We need to find largest $x$ such that amount of numbers from table, least than $x$, is strictly less than $k$. To calculate this count we sum counts from rows. In $i$ th row there will be $m i n({\\frac{x-1}{i}},m)$. Total complexity is $O(nlog(nm))$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <cmath>\n#include <memory.h>\nusing namespace std;\ntypedef long long ll;\n \nconst int N = 1e6+6;\n \nll f(ll x, int n, int m){\n    ll res = 0;\n    --x;\n    for(int i=1;i<=n;++i) res+=min((ll)m, x/i);\n    return res;\n}\n \nint main(){\n    //freopen(\"input.txt\",\"r\",stdin);// freopen(\"output.txt\",\"w\",stdout);\n    \n    int n, m;\n    \n    cin>>n>>m;\n    \n    ll k;\n    \n    cin>>k;\n    \n    \n    ll l = 1, r = 1LL*n*m+1;\n    \n    while(l<r){\n        ll x = (l+r)>>1;\n        \n        if(f(x,n,m)<k) l = x+1; else r = x;\n    }\n    \n    cout<<l-1<<endl;\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force"
    ],
    "rating": 1800
  },
  {
    "contest_id": "448",
    "index": "E",
    "title": "Divisors",
    "statement": "Bizon the Champion isn't just friendly, he also is a rigorous coder.\n\nLet's define function $f(a)$, where $a$ is a sequence of integers. Function $f(a)$ returns the following sequence: first all divisors of $a_{1}$ go in the increasing order, then all divisors of $a_{2}$ go in the increasing order, and so on till the last element of sequence $a$. For example, $f([2, 9, 1]) = [1, 2, 1, 3, 9, 1]$.\n\nLet's determine the sequence $X_{i}$, for integer $i$ $(i ≥ 0)$: $X_{0} = [X]$ ($[X]$ is a sequence consisting of a single number $X$), $X_{i} = f(X_{i - 1})$ $(i > 0)$. For example, at $X = 6$ we get $X_{0} = [6]$, $X_{1} = [1, 2, 3, 6]$, $X_{2} = [1, 1, 2, 1, 3, 1, 2, 3, 6]$.\n\nGiven the numbers $X$ and $k$, find the sequence $X_{k}$. As the answer can be rather large, find only the first $10^{5}$ elements of this sequence.",
    "tutorial": "Learn how to transform $X_{i}$ into $X_{i + 1}$. For this we need to concatenate lists of divisors for all elements of $X_{i}$. To do this efficiently, precalculate divisors of $X$ (because for every $i$ $X_{i}$ consist of its divisors). It can be done by well-known method with $O({\\sqrt{X}})$ complexity. How to calculate divisors of divisors? Need to know that for the given constrains for $X$ maximum number of divisors $D(X)$ will be 6720 (in the number 963761198400), so divisors of divisors can be calculated in $O(D^{2}(X))$ time. With this lists we can transform $X_{i}$ into $X_{i + 1}$ in $O(N)$ time, were $N = 10^{5}$ - is the limit of numbers in output. Now learn how to transform $X_{i}$ into $X_{2i}$. What says $X_{i}$? Besides what would be $X$ after $i$ steps, it can tell where goes everyone divisor of $X$ after $i - 1$ steps. Actually, $X_{i}$ is concatenation of all $Y_{i - 1}$, where $Y$ is divisor of $X$. For example, $10_{3} = [1, 1, 1, 2, 1, 1, 5, 1, 1, 2, 1, 5, 1, 2, 5, 10] = [1] + [1, 1, 2] + [1, 1, 5] + [1, 1, 2, 1, 5, 1, 2, 5, 10] = 1_{2} + 2_{2} + 5_{2} + 10_{2}$. How to know which segment corresponds for some $Y$? Lets $pos(Y)$ be the first index of $Y$ in $X_{i}$. Then needed segment starts from $pos(prev(Y)) + 1$ and ends in $pos(Y)$, where $prev(Y)$ is previous divisor before $Y$ in sorted list of divisors. So, to make $X_{2i}$ from $X_{i}$ we need to know where goes every element from $X_{i}$ after $i$ steps. We know all its divisors - it is one step, and for every divisor we know where it goes after $i - 1$ step. Thus, we again need to concatenate some segments in correct order. It also can be done in $O(N)$ time. How to find now $X_{k}$ for every $k$? The method is similar as fast exponentiation: $X_{k} = [X]$ when $k = 0$, if $k$ is odd then transform $X_{k - 1}$ to $X_{k}$, if $k$ is even then transform $X_{k / 2}$ to $X_{k}$. This method takes $O(logk)$ iterations. And one small trick: obviously that for $X > 1$ $X_{k}$ starts from $k$ ones, so $k$ can be limited by $N$. Total complexity of solution is $O(\\sqrt{X}+D^{2}(X)+N l o q(m i n(N,k)))$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <cmath>\n#include <memory.h>\nusing namespace std;\ntypedef long long ll;\n \nconst int N = 1e5;\n \nvector<ll> d;\nvector<ll> g[N];\nvector<int> gi[N];\nll x;\n \nvector<int> f(int k){\n    if(k==0) return vector<int>(1,d.size()-1);\n    \n    vector<int> res;\n    \n    if(k&1){\n        vector<int> v = f(k-1);\n        for(int i=0;i<v.size();++i)\n        for(int j=0;res.size()<N && j<gi[v[i]].size();++j) res.push_back(gi[v[i]][j]);\n    }else{\n        vector<int> v = f(k>>1);\n        vector<int> pos(d.size());\n        for(int i=0, j=0;i<v.size();++i) if(v[i]==j) pos[j++] = i;\n        for(int i=0;i<v.size();++i)\n        for(int j=0;res.size()<N && j<gi[v[i]].size();++j){\n            int y = gi[v[i]][j];\n            int l = y ? pos[y-1]+1 : 0;\n            int r = pos[y];\n            for(int k=l;res.size()<N && k<=r; ++k) res.push_back(v[k]);\n        }\n    }\n    \n    return res;\n}\n \nvector<ll> solve(int k){\n    vector<int> v = f(k);\n    vector<ll> res(v.size());\n    for(int i=0;i<v.size();++i) res[i] = d[v[i]];\n    return res;\n}\n \n \nint main(){\n    //freopen(\"input.txt\",\"r\",stdin); freopen(\"output.txt\",\"w\",stdout);\n    \n    cin>>x;\n    for(ll i=1; i*i<=x; ++i) if(x%i==0){\n        d.push_back(i);\n        if(i*i!=x) d.push_back(x/i);\n    }\n    \n    sort(d.begin(), d.end());\n    \n    int cnt = 0;\n    for(int i=0;i<d.size();++i){\n        for(int j=0;j<=i;++j) if(d[i]%d[j]==0){\n            g[i].push_back(d[j]);\n            gi[i].push_back(j);\n        }\n        cnt+=g[i].size();\n    }\n    \n    ll kk;\n    cin>>kk;\n    int k = min(kk, (ll)N);\n    \n    vector<ll> r2 = solve(k);\n    \n    for(int i=0;i<r2.size();++i) printf(\"%I64d \",r2[i]); printf(\"\\n\");\n    \n    \n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "implementation",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "449",
    "index": "A",
    "title": "Jzzhu and Chocolate",
    "statement": "Jzzhu has a big rectangular chocolate bar that consists of $n × m$ unit squares. He wants to cut this bar exactly $k$ times. Each cut must meet the following requirements:\n\n- each cut should be straight (horizontal or vertical);\n- each cut should go along edges of unit squares (it is prohibited to divide any unit chocolate square with cut);\n- each cut should go inside the whole chocolate bar, and all cuts must be distinct.\n\nThe picture below shows a possible way to cut a $5 × 6$ chocolate for $5$ times.\n\nImagine Jzzhu have made $k$ cuts and the big chocolate is splitted into several pieces. Consider the smallest (by area) piece of the chocolate, Jzzhu wants this piece to be as large as possible. What is the maximum possible area of smallest piece he can get with exactly $k$ cuts? The area of a chocolate piece is the number of unit squares in it.",
    "tutorial": "We assume that $n  \\le  m$ (if $n > m$, we can simply swap $n$ and $m$). If we finally cut the chocolate into $x$ rows and $y$ columns $(1  \\le  x  \\le  n, 1  \\le  y  \\le  m, x + y = k + 2)$, we should maximize the narrowest row and maximize the narrowest column, so the answer will be $floor(n / x) * floor(m / y)$. There are two algorithms to find the optimal $(x, y)$. Notice that if $x * y$ is smaller, the answer usually will be better. Then we can find that if $k < n$, the optimal $(x, y)$ can only be ${x = 1, y = k + 1}$ or ${x = k + 1, y = 1}$. If $n  \\le  k < m$, the optimal $(x, y)$ can only be ${x = 1, y = k + 1}$. If $m  \\le  k  \\le  n + m - 2$, the optimal $(x, y)$ can only be ${x = k + 2 - m, y = m}$, because let $t = m - n$, $n / (k + 2 - m)  \\ge  (n + t) / (k + 2 - m + t)  \\ge  1$. $floor(n / x)$ has at most $2{\\sqrt{n}}$ values, so we can enum it and choose the maximum $x$ for each value.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "449",
    "index": "B",
    "title": "Jzzhu and Cities",
    "statement": "Jzzhu is the president of country A. There are $n$ cities numbered from $1$ to $n$ in his country. City $1$ is the capital of A. Also there are $m$ roads connecting the cities. One can go from city $u_{i}$ to $v_{i}$ (and vise versa) using the $i$-th road, the length of this road is $x_{i}$. Finally, there are $k$ train routes in the country. One can use the $i$-th train route to go from capital of the country to city $s_{i}$ (and vise versa), the length of this route is $y_{i}$.\n\nJzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.",
    "tutorial": "We consider a train route $(1, v)$ as an undirected deletable edge $(1, v)$. Let $dist(u)$ be the shortest path between $1$ and $u$. We add all of the edges $(u, v)$ weighted $w$ where $dist(u) + w = dist(v)$ into a new directed graph. A deletable edge $(1, v)$ can be deleted only if it isn't in the new graph or the in-degree of $v$ in the new graph is more than $1$, because the connectivity of the new graph won't be changed after deleting these edges. Notice that you should subtract one from the in-degree of $v$ after you delete an edge $(1, v)$.",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "449",
    "index": "C",
    "title": "Jzzhu and Apples",
    "statement": "Jzzhu has picked $n$ apples from his big apple tree. All the apples are numbered from $1$ to $n$. Now he wants to sell them to an apple store.\n\nJzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.\n\nJzzhu wonders how to get the maximum possible number of groups. Can you help him?",
    "tutorial": "Firstly, we should notice that $1$ and the primes larger than $N / 2$ can not be matched anyway, so we ignore these numbers. Let's consider each prime $P$ where $2 < P  \\le  N / 2$. For each prime $P$, we find all of the numbers which are unmatched and have a divisor $P$. Let $M$ be the count of those numbers we found. If $M$ is even, then we can match those numbers perfectly. Otherwise, we throw the number $2P$ and the remaining numbers can be matched perfectly. Finally, only even numbers may be unmatched and we can match them in any way.",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "449",
    "index": "D",
    "title": "Jzzhu and Numbers",
    "statement": "Jzzhu have $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. We will call a sequence of indexes $i_{1}, i_{2}, ..., i_{k}$ $(1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ n)$ a group of size $k$.\n\nJzzhu wonders, how many groups exists such that $a_{i1}$ & $a_{i2}$ & ... & $a_{ik} = 0$ $(1 ≤ k ≤ n)$? Help him and print this number modulo $1000000007$ $(10^{9} + 7)$. Operation $x$ & $y$ denotes bitwise AND operation of two numbers.",
    "tutorial": "Firstly, we can use inclusion-exclusion principle in this problem. Let $f(x)$ be the count of number $i$ where $A_{i}&x = x$. Let $g(x)$ be the number of $1$ in the binary respresentation of $x$. Then the answer equals to $\\textstyle\\sum_{x=0}^{20}(-1)^{g(x)}2^{f(x)}$. Now the task is to calculate $f(x)$ for every integer $x$ between $0$ and $2^{20}$. Let $f_{k}(x)$ be the count of number $i$ where $Y_{0}&X_{0} = X_{0}$ and $X_{1} = Y_{1}$ (they are defined below). We divide $x$ and $A_{i}$ into two parts, the first $k$ binary bits and the other $20 - k$ binary bits. Let $X_{0}$ be the first part of $x$ and $X_{1}$ be the second part of $x$. Let $Y_{0}$ be the first part of $A_{i}$ and $Y_{1}$ be the second part of $A_{i}$. We can calculate $f_{k}(x)$ in $O(1)$: $f_{k}(x)={\\left\\{f_{k-1}(x)+f_{k-1}(x+2^{k}){\\quad}{\\mathrm{the~k}\\!\\cdot\\!\\mathrm{th~binary~bit~of~x~equals~to~}}0}$ The problem can be solved in $O(n * 2^{n})$ now ($n = 20$ in this problem).",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "449",
    "index": "E",
    "title": "Jzzhu and Squares",
    "statement": "Jzzhu has two integers, $n$ and $m$. He calls an integer point $(x, y)$ of a plane special if $0 ≤ x ≤ n$ and $0 ≤ y ≤ m$. Jzzhu defines a unit square as a square with corners at points $(x, y)$, $(x + 1, y)$, $(x + 1, y + 1)$, $(x, y + 1)$, where $x$ and $y$ are some integers.\n\nLet's look at all the squares (their sides not necessarily parallel to the coordinate axes) with corners at the special points. For each such square Jzzhu paints a dot in every unit square that is fully inside it. After that some unit squares can contain several dots. Now Jzzhu wonders, how many dots he has painted on the plane. Find this number modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "Consider there is only one query. Let me descripe the picture above. A grid-square can be exactly contained by a bigger square which coincide with grid lines. Let $L$ be the length of a side of the bigger square. Let $i$ be the minimum distance between a vertice of the grid-square and a vertice of the bigger square. Let $f(L, i)$ be the number of cells which are fully contained by the grid-square. We can divide a grid-square into four right triangles and a center square. For each right triangle, the number of cells which are crossed by an edge of the triangle is $L - gcd(i, L)$. Then, the number of cells which are fully contained by the triangle is $[i(L - i) - L + gcd(i, L)] / 2$. $f(L, i) = (L - 2i)^{2} + 2[i(L - i) - L + gcd(i, L)] = L^{2} - 2iL + 2i^{2} - 2L + 2gcd(i, L)$ Firstly, we enum $L$ from $1$ to $min(N, M)$. Then the task is to calculate $(N-L+1)*(M-L+1)*\\sum_{i=1}^{L}f(L,i)$. $\\textstyle\\sum_{i=1}^{L}g c d(i,L)$ can be calculated by the following steps: Enum all of the divisor $k$ of $L$ and the task is to calculate the count of $i$ where $gcd(i, L) = k$. The count of $i$ where $gcd(i, L) = k$ equals to $ \\phi (L / k)$. Finally, $\\textstyle\\sum_{i=1}^{L}f(L,i)=L(L+1)(2L+1)/3-3L^{2}+2\\sum_{i=1}^{L}g c d(i,L)$. If there are multiple queries, we can calculate the prefix sum of $\\textstyle\\sum_{i=1}^{L}f(L,i)$, $L\\sum_{i=1}^{L}f(L,i)$ and $L^{2}\\sum_{i=1}^{L}f(L,i)$, then we can answer each query in $O(1)$.",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "450",
    "index": "A",
    "title": "Jzzhu and Children",
    "statement": "There are $n$ children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from $1$ to $n$. The $i$-th child wants to get at least $a_{i}$ candies.\n\nJzzhu asks children to line up. Initially, the $i$-th child stands at the $i$-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:\n\n- Give $m$ candies to the first child of the line.\n- If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home.\n- Repeat the first two steps while the line is not empty.\n\nConsider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?",
    "tutorial": "You can simply simulate it or find the last maximum $ceil(a_{i} / m)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "450",
    "index": "B",
    "title": "Jzzhu and Sequences",
    "statement": "Jzzhu has invented a kind of sequences, they meet the following property:\n\n\\[\nf_{1}=x;\\ f_{2}=y;\\ \\forall\\ i\\ (i\\geq2),f_{i}=f_{i-1}+f_{i+1}.\n\\]\n\nYou are given $x$ and $y$, please calculate $f_{n}$ modulo $1000000007$ $(10^{9} + 7)$.",
    "tutorial": "We can easily find that every $6$ numbers are the same. It's like ${x, y, y - x, - x, - y, x - y, x, y, y - x, ...}$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "451",
    "index": "A",
    "title": "Game With Sticks",
    "statement": "After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of $n$ horizontal and $m$ vertical sticks.\n\nAn intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.\n\nIn the grid shown below, $n = 3$ and $m = 3$. There are $n + m = 6$ sticks in total (horizontal sticks are shown in red and vertical sticks are shown in green). There are $n·m = 9$ intersection points, numbered from $1$ to $9$.\n\nThe rules of the game are very simple. The players move in turns. Akshat won gold, so he makes the first move. During his/her move, a player must choose any remaining intersection point and remove from the grid all sticks which pass through this point. A player will lose the game if he/she cannot make a move (i.e. there are no intersection points remaining on the grid at his/her move).\n\nAssume that both players play optimally. Who will win the game?",
    "tutorial": "From a grid of size $n * m$, if we remove an intersection point, then the grid after removing the sticks passing through it, will of size $n - 1$, $m - 1$. Notice when the grid consists of a single horizontal stick and m vertical sticks, If we pick any intersection point, then the updated grid will be only made of vertical sticks. You can see that there is no intersection point in the grid now. So $ans(n, m) = ans(n - 1, m - 1)$ ^ $1.$ $ans(1, * ) = 1$ $ans( * , 1) = 1$ So we can notice that answer will depend on the parity of $minimum(m, n)$. You can prove it using the previous equations. You can also check this by seeing the pattern. So finally if $min(n, m)$ is odd, then Akshat will win. Otherwise Malvika will win. You can also observe that \"players will play optimally\" is useless in this case. Complexity : $O$(1)",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n\tint n, m;\n\tcin >> n >> m;\n\tif (n > m) {\n\t\tswap(n, m);\n\t}\n\tif (n % 2 == 0) {\n\t\tcout << \"Malvika\" << endl;\n\t} else {\n\t\tcout << \"Akshat\" << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "451",
    "index": "B",
    "title": "Sort the Array",
    "statement": "Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array $a$ consisting of $n$ \\textbf{distinct} integers.\n\nUnfortunately, the size of $a$ is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array $a$ (in increasing order) by reversing \\textbf{exactly one} segment of $a$? See definitions of segment and reversing in the notes.",
    "tutorial": "Note that if from a given sorted array, if reverse a segment, then the remaining array will be arranged in following way. First increasing sequence, then decreasing, then again increasing. You can find the first position where the sequences start decreasing from the beginning. Call it $L$. You can find the first position where the sequences start increasing from the end. Call it $R$. Now we just need to reverse the segment between $a[L]$ to $a[R]$. Here is outline of my solution which is easy to implement. First I map larger numbers to numbers strictly in the range 1, n. As all the numbers are distinct, no two numbers in the mapping will be equal too. Let us define $L$ to be smallest index such that $A[i]! = i$. Let us also define $R$ to be largest index such that $A[i]! = i$. Note that if there is no such L and R, it means that array is sorted already. So answer will be \"yes\", we can simply reverse any of the 1 length consecutive segment. Otherwise we will simply reverse the array from $[L, R]$. After the reversal, we will check whether the array is sorted or not. Complexity: $O(nlogn)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = (int) 1e5 + 5;\nint a[N], b[N];\n \nint main() {\n\tint n;\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t\tb[i] = a[i];\n\t}\n\tmap<int, int> mp;\n\tsort(b, b + n);\n\tfor (int i = 0; i < n; i++) {\n\t\tmp[b[i]] = i;\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\ta[i] = mp[a[i]];\n\t}\n\tint L = -1;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (a[i] != i) {\n\t\t\tL = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tint R = -1;\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\tif (a[i] != i) {\n\t\t\tR = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (L == -1 || R == -1) {\n\t\tcout << \"yes\" << endl;\n\t\tcout << 1 << \" \" << 1 << endl;\n\t} else {\n\t\treverse(a + L, a + R + 1);\n\t\tint ok = true;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (a[i] != i) {\n\t\t\t\tok = false;\n\t\t\t}\n\t\t}\n\t\tif (ok) {\n\t\t\tcout << \"yes\" << endl;\n\t\t\tcout << L + 1 << \" \" << R + 1 << endl;\n\t\t} else {\n\t\t\tcout << \"no\" << endl;\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "451",
    "index": "C",
    "title": "Predict Outcome of the Game",
    "statement": "There are $n$ games in a football tournament. Three teams are participating in it. Currently $k$ games had already been played.\n\nYou are an avid football fan, but recently you missed the whole $k$ games. Fortunately, you remember a guess of your friend for these $k$ games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be $d_{1}$ and that of between second and third team will be $d_{2}$.\n\nYou don't want any of team win the tournament, that is each team should have the same number of wins after $n$ games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?\n\nNote that outcome of a match can not be a draw, it has to be either win or loss.",
    "tutorial": "Let $x_{1}$ be number of wins of first team in the first k games. Let $x_{2}$ be number of wins of second team in the first k games. Let $x_{3}$ be number of wins of third team in the first k games. Note that $x_{1} + x_{2} + x_{3} = k$ ---(1) $|x_{1} - x_{2}| = d_{1}.$ - (a) $|x_{2} - x_{3}| = d_{2}.$ - (b) Note that |x| can be x and -x depending on the sign of x. Case 1: Assume that $x_{1} > x_{2}$ and $x_{2} > x_{3}$. $x_{1} - x_{2} = d_{1}$ ---(2) $x_{2} - x_{3} = d_{2}$ ---(3) Adding 1 and 2, we get $2x_{1} + x_{3} = d_{1} + k$ --(4) Adding 2 and 3, we get $x_{1} - x_{3} = d_{1} + d_{2}$ ---(5). Now solve (4) and (5), we will get values of $x_{1}$ and $x_{3}$. By those values, compute value of $x_{2}$. Now we should check the constraints that $x_{1}  \\ge  x_{2}$ and $x_{2}  \\ge  3$. Now comes the most important part. Number of wins at the end of each team should be $n / 3$. So if $n$ is not divisible by 3, then our answer will be definitely \"no\". Note that if all of the $x_{1}, x_{2}, x_{3}$ are $ \\le  n / 3$, then we can have the remaining matches in such a way that final numbers of wins of each team should be equal. Now you have to take 4 such cases. Implementing such cases in 4 if-else statements could incur errors in implementation. You can check my code to understand a simple way to implement it. I will explain idea of my code briefly, basically equation (a) and (b) can be opened with either positive or negative sign due to modulus. So if our sign is negative we will change $d_{1}$ to be $- d_{1}$. So if we solve a single equation and replace $d_{1}$ by $- d_{1}$, we can get solution for the second case. All the cases can be dealt in such way. Please see my code for more details. Complexity: $O$(1) per test case.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long LL;\n \nint solveFaster(LL n, LL k, LL d1, LL d2) {\n      if (n % 3 != 0) {\n            return 0;\n      }\n \n      for (int sign1 = -1; sign1 <= 1; sign1++) {\n            for (int sign2 = -1; sign2 <= 1; sign2++) {\n                  if (sign1 == 0 || sign2 == 0) {\n                        continue;\n                  }\n                  LL D1 = d1 * sign1;\n                  LL D2 = d2 * sign2;\n \n                  LL x2 = (k - D1 + D2) / 3;\n                  if ((k - D1 + D2) % 3 != 0) {\n                        continue;\n                  }\n                  if (x2 >= 0 && x2 <= k) {\n                        LL x1 = D1 + x2;\n                        LL x3 = x2 - D2;\n                        if (x1 >= 0 && x1 <= k && x3 >= 0 && x3 <= k) {\n                              if (x1 <= n / 3 && x2 <= n / 3 && x3 <= n / 3) {\n                                    assert(abs(x1 - x2) == d1);\n                                    assert(abs(x2 - x3) == d2);\n                                    return true;\n                              }\n                        }\n                  }\n            }\n      }\n \n      return false;\n}\n \nint main() {\n\tint T;\n\tcin >> T;\n\t\n\twhile (T--) {\n\t\tLL n, k, d1, d2;\n\t\tcin >> n >> k >> d1 >> d2;\n\t\n\t\tint ans = solveFaster(n, k, d1, d2);\n\t\tif (ans == 1)\n\t\t\tcout << \"yes\" << endl;\n\t\telse \n\t\t\tcout << \"no\" << endl;\n\t}\n\t\n      return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "451",
    "index": "D",
    "title": "Count Good Substrings",
    "statement": "We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, \"aabba\" is good, because after the merging step it will become \"aba\".\n\nGiven a string, you have to find two values:\n\n- the number of good substrings of even length;\n- the number of good substrings of odd length.",
    "tutorial": "Merging Step: We have to convert string like \"aaaabbbaabaaa\" into \"ababa\". Important Observation A substring made of the string will be a \"good\" palindrome if their starting and ending characters are same. If the starting and ending characters are same, then the middle characters after merging will be alternating between 'a' and 'b'. eg. \"abaa\" is not a palindrome, but it is a good palindrome. After merging step it becomes \"aba\". Note that in the string left after merging, the consecutive characters will alternate between 'a' and 'b'. So if we are currently at the $i^{th}$ character, then we can have to simply check how many positions we have encountered upto now having the same character as that of $i^{th}$. For counting even and odd separately, we can make count of a's and b's at even and odd positions. So if we are at $i^{th}$ position, for counting even good palindromes, you just need to add count of number of characters a's at odd position. For counting odd good palindromes, you just need to add count of number of characters a's at even position. Complexity: $O$(n) where $n$ is length of string $s$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long LL;\n \npair<LL, LL> solve(string s)\n{\n      LL ansEven = 0, ansOdd = 0;\n      int cntEven[2], cntOdd[2];\n      cntEven[0] = cntEven[1] = cntOdd[0] = cntOdd[1] = 0;\n      for (int i = 0; i < s.size(); i++)\n      {\n            ansOdd++;\n            int id = s[i] - 'a';\n            if (i % 2 == 0)\n            {\n                  ansOdd += cntEven[id];\n                  ansEven += cntOdd[id];\n                  cntEven[id]++;\n            }\n            else\n            {\n                  ansOdd += cntOdd[id];\n                  ansEven += cntEven[id];\n                  cntOdd[id]++;\n            }\n      }\n      return make_pair(ansEven, ansOdd);\n}\n \n \nint main()\n{\n      srand(time(NULL));\n\t\n\tstring s;\n\tcin >> s;\n\tpair<long long, long long> ans = solve(s);\n\tcout << ans.first << \" \" << ans.second << endl;\n      \n      return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "451",
    "index": "E",
    "title": "Devu and Flowers",
    "statement": "Devu wants to decorate his garden with flowers. He has purchased $n$ boxes, where the $i$-th box contains $f_{i}$ flowers. All flowers in a single box are of the same color (hence they are indistinguishable). Also, no two boxes have flowers of the same color.\n\nNow Devu wants to select \\textbf{exactly} $s$ flowers from the boxes to decorate his garden. Devu would like to know, in how many different ways can he select the flowers from each box? Since this number may be very large, he asks you to find the number modulo $(10^{9} + 7)$.\n\nDevu considers two ways different if there is at least one box from which different number of flowers are selected in these two ways.",
    "tutorial": "The number of ways to choose $N$ items out of $R$ groups where each item in a group is identical is equal to the number of integral solutions to $x_{1} + x_{2} + x_{3}...x_{R} = N$, where $0  \\le  x_{i}  \\le  L_{i}$, where $L_{i}$ is the number of items in $i^{th}$ group. Number of integral solutions are coefficient of $x^{N}$ in [Product of $(1 + x + x * x + ...x^{Li}$) over all $i$]. You need to find coefficient of $x^{s}$ in $(1 + x + x^{2} + x^{3} + + ..x^{f1}) * * * (1 + x + x^{2} + x^{3} + + ..x^{fn})$. Using sum of Geometric progression we can say that $(1 + x + x^{2} + x^{3} + + ..x^{f1}) = (1 - x^{(f1 + 1)}) / (1 - x)$. Substituting in the expression, we get $(1 - x^{(f1 + 1))} / (1 - x) * * * (1 - x^{(fn + 1))} / (1 - x).$ = $(1 - x^{(f1 + 1))} * .. * (1 - x^{(fn + 1))} * (1 - x)^{( - n)}.$ Now we can find $x^{s}$ in $(1 - x)^{ - n}$ easily. It is $\\left(^{(n+s-1)}\\right)$. You can have a look at following link. to understand it better. So now as $s$ is large, we can not afford to iterate over $s$. But $n$ is small, we notice that $(1 - x^{(f1 + 1))} * .. * (1 - x^{(fn + 1))}$ can have at most $2^{n}$ terms. So we will simply find all those terms, they can be very easily computed by maintaining a vector<pair<int, int> > containing pairs of coefficients and their corresponding powers. You can write a recursive function for doing this. How to find $\\binom{(n+s-1)}{(s)}$ % p. As $n + s - 1$ is large and s is very small. You can use lucas's theorem. If you understand lucas's theorem, you can note that we simply have to compute $\\binom{(n+s-1)\\mathcal{V}_{\\mathrm{c}}p}{s\\mathcal{V}_{\\mathrm{c}}p}\\Biggr)$. Complexity: $O(n * 2^{n})$. Another solution based on inclusion exclusion principle.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long LL;\n#define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++)\n#define snuke(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)\n \nconst long long mod = (long long) (1e9 + 7);\n \nint n;\nLL f[22], s, inv[55];\n \nLL nCr(LL n, LL r) {\n      if (r > n) return 0;\n      if (n - r < r) r = n - r;\n      n %= mod;\n      LL ans = 1;\n      REP(i, r) {\n            ans = (ans * (n - i)) % mod;\n            ans = (ans * inv[i + 1]) % mod;\n      }\n      return ans;\n}\n \nLL modpow(LL a, LL b, LL mod) {\n      LL res = 1;\n      while (b) {\n            if (b & 1) res = (res * a) % mod;\n            a = (a * a) % mod;\n            b >>= 1;\n      }\n      return res;\n}\n \nvoid pre() {\n      for (int i = 1; i <= 50; i++) {\n            inv[i] = modpow(i, mod - 2, mod);\n      }\n}\n \nint main() {\n      pre();\n \n      cin>>n>>s;\n      REP(i,n) cin>>f[i];\n \n      LL ans = 0;\n      REP(mask,(1<<n)){\n            LL x = s;\n            int tot = 0;\n            REP(i,n){\n                  if (mask & (1<<i)) {\n                        x -= (f[i] + 1);\n                        tot++;\n                  }\n            }\n            if (x < 0) continue;\n            LL temp = nCr(x + n - 1, n - 1);\n            if (tot & 1) temp = - temp;\n            ans = (ans + temp) % mod;\n            if (ans < 0) ans += mod;\n      }\n \n      cout << ans << endl;\n \n      return 0;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "452",
    "index": "B",
    "title": "4-point polyline",
    "statement": "You are given a rectangular grid of lattice points from $(0, 0)$ to $(n, m)$ inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.\n\nA polyline defined by points $p_{1}, p_{2}, p_{3}, p_{4}$ consists of the line segments $p_{1} p_{2}, p_{2} p_{3}, p_{3} p_{4}$, and its length is the sum of the lengths of the individual line segments.",
    "tutorial": "The critical observation in this problem is that the points will be at the corners or very close to the corners. After that one simple solution would be to generate a set of all the points that are within 4 cells from some corner, and consider all quadruplets of points from that set.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "geometry",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "452",
    "index": "C",
    "title": "Magic Trick",
    "statement": "Alex enjoys performing magic tricks. He has a trick that requires a deck of $n$ cards. He has $m$ identical decks of $n$ different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs $n$ cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards.\n\nThe trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful.\n\nYou don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case.",
    "tutorial": "When the magician reveals the card, he has $\\textstyle{\\frac{1}{k}}$ chance to reveal the same exact card that you have chosen. With the remaining $\\frac{k{\\mathrm{k}}-1}{k}$ chance he will reveal some other card. Since all the cards in all $m$ decks are equally likely to be in the $n$ cards that he uses to perform the trick, he is equally likely to reveal any card among the $n  \\times  m - 1$ cards (-1 for the card that you have chosen, which we assume he has not revealed). There are only $m - 1$ cards that can be revealed that have the same value as the card you chose but are not the card you chose. Thus, the resulting probability is ${\\frac{1}{k}}+{\\frac{k-1}{k}}\\times{\\frac{m-1}{n\\times m-1}}$",
    "tags": [
      "combinatorics",
      "math",
      "probabilities"
    ],
    "rating": 2100
  },
  {
    "contest_id": "452",
    "index": "D",
    "title": "Washer, Dryer, Folder",
    "statement": "You have $k$ pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has $n_{1}$ washing machines, $n_{2}$ drying machines and $n_{3}$ folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.\n\nIt takes $t_{1}$ minutes to wash one piece of laundry in a washing machine, $t_{2}$ minutes to dry it in a drying machine, and $t_{3}$ minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.",
    "tutorial": "One way to solve this problem is to maintain three deques, one per machine type, each one containing moments of time when the machines of this type will be available in increasing order. Originally each deck has as many zeroes, as many machines of that type are available. For each piece of laundry, see the earliest moment of time when each of the three machines will be available, and chose the time to put it in a washer in such a way, that there will be no delay when you move it to the dryer and to the folder. Remove the first elements from each of the deques, and push back moments of time when the piece of laundry you are processing is washed, dried and folded correspondingly. It can be shown that by doing that you will maintain all the deques sorted.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "452",
    "index": "E",
    "title": "Three strings",
    "statement": "You are given three strings $(s_{1}, s_{2}, s_{3})$. For each integer $l$ $(1 ≤ l ≤ min(|s_{1}|, |s_{2}|, |s_{3}|)$ you need to find how many triples ($i_{1}, i_{2}, i_{3}$) exist such that three strings $s_{k}[i_{k}... i_{k} + l - 1]$ $(k = 1, 2, 3)$ are pairwise equal. Print all found numbers modulo $1000000007 (10^{9} + 7)$.\n\nSee notes if you are not sure about some of the denotions used in the statement.",
    "tutorial": "This problem requires one to use one of the datastructures, such as suffix array, suffix tree or suffix automata. The easiest solution uses a compressed suffix tree. Build one suffix tree on all three strings. For simplicity add some non-alphabetic character at the end of each string. For every node in the tree store how many times the corresponding suffix occurs in each string. Then traverse the tree once. If the tree had no shortcuts, for every node that is $a$ characters away from the root you would have increased the answer for $a$ by the product of numbers of occurrences of the suffix in each of the strings. Since you do have shortcuts, you need to update the answer for all the lengths from $a$ to $b$, where $a$ and $b$ are the distances of two ends of the shortcut from the root. One way to do it with constant time updates and linear time to print all the answers is the following. If the array of answers is $v$, then instead of computing $v$ we can compute the array of differences $p$, such that $p_{i} = v_{i} - v_{i - 1}$. This way when you traverse the shortcut, rather than adding some value at all the positions from $a$ to $b$, you only need to add that value at position $a$, and subtract it at position $b$. When $p$ is computed, it is easy to restore $v$ in one pass.",
    "tags": [
      "data structures",
      "dsu",
      "string suffix structures",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "452",
    "index": "F",
    "title": "Permutation",
    "statement": "You are given a permutation of numbers from $1$ to $n$. Determine whether there's a pair of integers $a, b$ $(1 ≤ a, b ≤ n; a ≠ b)$ such that the element $\\textstyle{\\frac{(a+b)}{2}}$ (note, that it is usual division, not integer one) is between $a$ and $b$ in this permutation.",
    "tutorial": "There are at least two different ways to solve this problem First way is to notice that almost all the permutations have such numbers $a$ and $b$. Consider solving the opposite problem: given $n$, build a permutation such that no subsequence of length 3 forms an arithmetic progression. One way to do that is to solve similar problem recursively for odd and even elements and concatenate the answer, i.e. solve it for $\\frac{n t}{2}$, and then form the answer for $n$ as all the elements of the solution for $\\frac{n t}{2}$ multiplied by two, followed by those elements multiplied by two minus one. This way we first place all the even numbers of the sequence, and then all the odd or vice versa. Now one observation that can be made is that all the permutations that don't have a subsequence of length 3 that is an arithmetic progression are similar, with may be several elements in the middle being mixed up. As a matter of fact, it can be proven that the farthest distance an odd number can have from the odd half (or even number can have from the even part) is 6. With this knowledge we can build simple divide and conquer solution. If $n < = 20$, use brute force solution, otherwise, if the first and the last elements have the same remainder after division by two, then the answer is YES, otherwise, assuming without loss of generality that the first element is odd, if the distance from the first even element to the last odd element is more than 12, then the answer is YES, otherwise one can just recursively check all the odd elements separately, all the even elements separately, and then consider triplets of numbers, where one number is either in the odd or even part, and two numbers are among the at most 12 elements in the middle. This solution works in $nlog(n)$ time. Another approach, that does not rely on the observation above, is to consider elements one by one, from left to right, maintaining a bitmask of all the numbers we've seen so far. If the current element we are considering is $a$, then for every element $a - k$ that we saw, if we didn't see $a + k$ (assuming both $a - k$ and $a + k$ are between $0$ and $n - 1$), then the answer is YES. Note that $a - k$ was seen and $a + k$ was not seen for some $k$ if and only if the bitmask is not a palindrome with a center at $a$. To verify if it is a palindrome or not one can use polynomial hashes, making the complexity to be $n  \\times  log(n)$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "hashing"
    ],
    "rating": 2700
  },
  {
    "contest_id": "453",
    "index": "A",
    "title": "Little Pony and Expected Maximum",
    "statement": "Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.\n\nThe dice has $m$ faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the $m$-th face contains $m$ dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability $\\textstyle{\\frac{1}{m}}$. Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice $n$ times.",
    "tutorial": "Take $m$ = 6, $n$ = 2 as a instance. 6 6 6 6 6 6 5 5 5 5 5 6 4 4 4 4 5 6 3 3 3 4 5 6 2 2 3 4 5 6 1 2 3 4 5 6Enumerate the maximum number, the distribution will be a $n$-dimensional super-cube with $m$-length-side. Each layer will be a large cube minus a smaller cube. So we have: $\\textstyle\\sum_{i=1}^{m}i(i^{n}-(i-1)^{n})/m^{n}$Calculate $i^{n}$ may cause overflow, we could move the divisor into the sum and calculate $(i / m)^{n}$ instead.",
    "tags": [
      "probabilities"
    ],
    "rating": 1600
  },
  {
    "contest_id": "453",
    "index": "B",
    "title": "Little Pony and Harmony Chest",
    "statement": "Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony.\n\nA sequence of positive integers $b_{i}$ is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmony sequence $b_{i}$ which minimizes the following expression:\n\n\\[\n\\sum_{i=1}^{n}|a_{i}-b_{i}|.\n\\]\n\nYou are given sequence $a_{i}$, help Princess Twilight to find the key.",
    "tutorial": "Since {1, 1 $...$, 1} is a pairwise coprime sequence, the maximum element of $b_{i}$ can never greater then $2mx - 1$. Here $mx$ is the maximum elements in $a_{i}$. So what we need consider is the first a few prime factors. It is not hard to use bitmask-dp to solve this: for (int i = 1 ; i <= n ; i ++) { for (int k = 1 ; k < 60 ; k ++) { int x = (~fact[k]) & ((1 << 17) - 1); for (int s = x ; ; s = (s - 1) & x) { if (dp[i - 1][s] + abs(a[i] - k) < dp[i][s | fact[k]]){ dp[i][s | fact[k]] = dp[i-1][s] + abs(a[i]-k); } if (s == 0) break; } } }Here dp[i][s]: means the first $i$ items of the sequence, and the prime factor have already existed. And fact[k]: means the prime factor set of number $k$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "453",
    "index": "C",
    "title": "Little Pony and Summer Sun Celebration",
    "statement": "Twilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration.\n\nTwilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information?\n\nPonyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than $4n$ places.",
    "tutorial": "There is no solution if there is more than 1 connected component which have odd node (because we can't move between two component), otherwise it is always solvable. This fact is not obvious, let's focus on one component. You can select any node to start, denoted it as $r$ (root). Start from $r$, you can go to any other odd node then back. Each time you can eliminate one odd node. After that, if $r$ itself is odd, you can simply delete the first or last element in your path (it must be $r$). The only spot of the above method is the size of the path can been large as $O(n^{2})$. We need a more local observation. Let's check the following dfs() function: void dfs(int u = r, int p = -1){ vis[u] = true; add_to_path(u); for_each(v in adj[u]) if (!vis[v]){ dfs(v, u); add_to_path(u); } if (odd[u] && p != -1){ add_to_path(p); add_to_path(u); } }This dfs() maintain the following loop invariant: before we leave a node $u$, we clear all odd node in the sub-tree rooted at $u$ as well as $u$ itself. The only $u$ can break the invariant is the root itself. So after dfs(), we use O(1) time to check weather root is still a odd node, if yes, delete the first or last element of the path (it must be $r$). After that, all the node will been clear, each node can involve at most 4 items in the path. So the size of the path will less than or equal to $4n$. Thus the overall complexity is $O(n + m)$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "453",
    "index": "D",
    "title": "Little Pony and Elements of Harmony",
    "statement": "The Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with $n$ vertices labeled from 0 to $n - 1$, where $n$ is a power of two, equal to $2^{m}$.\n\nThe energy in Elements of Harmony is in constant movement. According to the ancient book, the energy of vertex $u$ in time $i$ $(e_{i}[u])$ equals to:\n\n\\[\ne_{i}[u]=\\sum_{n}e_{i-1}[v]\\cdot b[f(u,v)].\n\\]\n\nHere $b[]$ is the transformation coefficient — an array of $m + 1$ integers and $f(u, v)$ is the number of ones in the binary representation of number $(u xor v)$.\n\nGiven the transformation coefficient and the energy distribution at time 0 $(e_{0}[])$. Help Twilight Sparkle predict the energy distribution at time $t$ $(e_{t}[])$. The answer can be quite large, so output it modulo $p$.",
    "tutorial": "Let's consider the $e$ = [1 1 $...$ 1]. After a period, it will be $ke$ where $k$ is a const. So we know that [1 1, $...$, 1] is an eigenvector and $k$ is the corresponding an eigenvalue. The linear transformation has $2^{m}$ eigenvectors. The $i(0  \\le  i < 2^{m})$-th eigenvector is [(-1)^f(0, i) (-1)^f(1, i) $...$ (-1)^f(2^m-1, i)], where $f$($x$, $y$) means that the number of ones in the binary notation of $x$ and $y$. We notice that the eigenvalue is only related to the number of ones in $i$, and it is not hard to calc one eigenvalue in $O(m)$ time. To decompose the initial vector to the eigenvectors, we need Fast Walsh-Hadamard transform. Also check SRM 518 1000 for how to use FWT. http://apps.topcoder.com/wiki/display/tc/SRM+518 In the last step, we need divide n. We can mod (p * n) in the precedure and divide n directly.",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 3000
  },
  {
    "contest_id": "453",
    "index": "E",
    "title": "Little Pony and Lord Tirek",
    "statement": "Lord Tirek is a centaur and the main antagonist in the season four finale episodes in the series \"My Little Pony: Friendship Is Magic\". In \"Twilight's Kingdom\" (Part 1), Tirek escapes from Tartarus and drains magic from ponies to grow stronger.\n\nThe core skill of Tirek is called Absorb Mana. It takes all mana from a magic creature and gives them to the caster.\n\nNow to simplify the problem, assume you have $n$ ponies (numbered from 1 to $n$). Each pony has three attributes:\n\n- $s_{i}$ : amount of mana that the pony has at time 0;\n- $m_{i}$ : maximum mana that the pony can have;\n- $r_{i}$ : mana regeneration per unit time.\n\nLord Tirek will do $m$ instructions, each of them can be described with three integers: $t_{i}, l_{i}, r_{i}$. The instruction means that at time $t_{i}$, Tirek will use Absorb Mana on ponies with numbers from $l_{i}$ to $r_{i}$ (both borders inclusive). We'll give you all the $m$ instructions in order, count how much mana Tirek absorbs for each instruction.",
    "tutorial": "Key Observation The income of a operation, is only relevant with the previous operation. In other words, what we focus on is the difference time between adjacent operations. Weaken the problem Let us assume $s_{i} = 0$ and $r_{i} = 1$ at the beginning to avoid disrupting when we try to find the main direction of the algorithm. Also it will be much easier if the problem only ask the sum of all query. One of the accepted method is following: Firstly, for each operation ($t$, $l$, $r$), we split it into a insert event on $l$, and a delete event $r + 1$. Secondly, we use scanning from left to right to accumulate the contributions of each pony. In order to do that, you need a balanced tree to maintenance the difference time between adjacent operations, and a second balanced tree to maintenance some kind of prefixes sum according to those \"difference\". The first balanced tree could been implemented by STL::SET. For each operation, you need only constant insert and delete operations on those balanced tree, thus the overall complexity is $O(nlogn)$. General solution Instead of scanning, now we use a balanced tree to maintenance the intervals which have same previous operation time and use a functional interval tree to maintenance those ponies. For each operation, we use binary search on the first balanced tree, and query on the second balanced tree. Thus the overall complexity is $O(nlog^{2}$$n)$.",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "454",
    "index": "A",
    "title": "Little Pony and Crystal Mine",
    "statement": "Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size $n$ ($n$ is odd; $n > 1$) is an $n × n$ matrix with a diamond inscribed into it.\n\nYou are given an odd integer $n$. You need to draw a crystal of size $n$. The diamond cells of the matrix should be represented by character \"D\". All other cells of the matrix should be represented by character \"*\". Look at the examples to understand what you need to draw.",
    "tutorial": "Just a few basics of your programming language. It's easy.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "454",
    "index": "B",
    "title": "Little Pony and Sort by Shift",
    "statement": "One day, Twilight Sparkle is interested in how to sort a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:\n\n\\[\na_{1}, a_{2}, ..., a_{n} → a_{n}, a_{1}, a_{2}, ..., a_{n - 1}.\n\\]\n\nHelp Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?",
    "tutorial": "Just a few basics of your programming language. It's not hard.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "455",
    "index": "A",
    "title": "Boredom",
    "statement": "Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.\n\nGiven a sequence $a$ consisting of $n$ integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it $a_{k}$) and delete it, at that all elements equal to $a_{k} + 1$ and $a_{k} - 1$ also must be deleted from the sequence. That step brings $a_{k}$ points to the player.\n\nAlex is a perfectionist, so he decided to get as many points as possible. Help him.",
    "tutorial": "In this task we need to maximize the sum of numbers that we took. Let precalc array $cnt$. $cnt[x]$ - number of integers $x$ in array $a$. Now we can easily calculate the DP: $f(i) = max(f(i - 1), f(i - 2) + cnt[i] \\cdot i)$, $2  \\le  i  \\le  n$; $f(1) = cnt[1]$; $f(0) = 0$; The answer is $f(n)$. Asymptotics - $O(n)$.",
    "tags": [
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "455",
    "index": "B",
    "title": "A Lot of Games",
    "statement": "Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.\n\nGiven a group of $n$ non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.\n\nAndrew and Alex decided to play this game $k$ times. The player who is the loser of the $i$-th game makes the first move in the $(i + 1)$-th game. Guys decided that the winner of all games is the player who wins the last ($k$-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.",
    "tutorial": "To solve this problem we need the prefix tree(trie), which will have all the strings from the group. Next we will calculate the two DP: win[v] - Can player win if he makes a move now (players have word equal to prefix $v$ in the prefix tree(trie)). lose[v] - Can player lose if he makes a move now (players have word equal to prefix $v$ in the prefix tree(trie)). if $v$ is leaf of trie, then win[v] = false; lose[v] = true; Else $win[v] = (win[v] or (not win[i]))$; $lose[v] = (lose[v] or (not lose[i]))$, such $i$ - children of vertex $v$. Let's look at a few cases: If $win[v] = false$, then second player win (first player lose all games). If $win[v] = true$ and $lose[v] = true$, then first player win (he can change the state of the game in his favor). If $win[v] = true$ and $lose[v] = false$, then if $k_{\\mathrm{\\mod}\\ 2=1}$, then first player win, else second player win. Asymptotics - $O(\\Sigma|s_{i}|)$.",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "implementation",
      "strings",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "455",
    "index": "C",
    "title": "Civilization",
    "statement": "Andrew plays a game called \"Civilization\". Dima helps him.\n\nThe game has $n$ cities and $m$ bidirectional roads. The cities are numbered from $1$ to $n$. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities $v_{1}, v_{2}, ..., v_{k}$, that there is a road between any contiguous cities $v_{i}$ and $v_{i + 1}$ ($1 ≤ i < k$). The length of the described path equals to $(k - 1)$. We assume that two cities lie in the same region if and only if, there is a path connecting these two cities.\n\nDuring the game events of two types take place:\n\n- Andrew asks Dima about the length of the longest path in the region where city $x$ lies.\n- Andrew asks Dima to merge the region where city $x$ lies with the region where city $y$ lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them.\n\nDima finds it hard to execute Andrew's queries, so he asks you to help him. Help Dima.",
    "tutorial": "You can see that the road system is a forest. For efficient storage component we need to use DSU. First, we need to build the initial system of roads. For each component of the initial road system, we must find the diameter of component. This can be done using a DFS or BFS. Let $a$ - any vertex of component. Let $b$ - furthest vertex from vertex $a$. Let $c$ - furthest vertex from vertex $b$. Diameter equal to distance from $b$ to $c$. This algorithm for finding the diameter is correct only for tree. For each component in the DSU, we know its diameter. Now it is very easy to answer the query of the $1$st type: To know the component which contains the vertex $x$ and output diameter of this component. Query of the $2$nd type also very easy to process: Let $u$ - of component in which lie the vertex $x$, $v$ - of component in which lie the vertex $y$. If $u  \\neq  v$, then we can merge components: The diameter of the new component is computed as follows: $D i a m e t e r_{n e w}=\\operatorname*{max}(D i a m e t e r_{u},D i a m e t e r_{v},\\left\\vert\\frac{D i a m e t e r_{u}}{2}\\right\\vert+\\dots\\Bigl\\lbrack\\frac{D i a m e t e r_{u}}{2}\\rbrack+1\\right\\rbrack$ Asymptotics - $O(n \\cdot A^{ - 1}(n))$, where $A^{ - 1}(n)$ - inverse Ackermann function.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "ternary search",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "455",
    "index": "D",
    "title": "Serega and Fun",
    "statement": "Serega loves fun. However, everyone has fun in the unique manner. Serega has fun by solving query problems. One day Fedor came up with such a problem.\n\nYou are given an array $a$ consisting of $n$ positive integers and queries to it. The queries can be of two types:\n\n- Make a unit cyclic shift to the right on the segment from $l$ to $r$ (both borders inclusive). That is rearrange elements of the array in the following manner:\\[\na[l], a[l + 1], ..., a[r - 1], a[r] → a[r], a[l], a[l + 1], ..., a[r - 1].\n\\]\n- Count how many numbers equal to $k$ are on the segment from $l$ to $r$ (both borders inclusive).\n\nFedor hurried to see Serega enjoy the problem and Serega solved it really quickly. Let's see, can you solve it?",
    "tutorial": "Let's change the query type $1$ to two more simple requests: Erase a number from $r$-th position. Insert this number after $(l - 1)$-th position. Now let's keep our array as $\\sqrt{n}$ blocks. In each block will store the numbers themselves in such a manner as in the array $a$ and will store an array $cnt$. $cnt[x]$ - number of integers $x$ in block. This requires $O(n sqrtn)$ space. Now we can fast process the queries of the $1$st type. We can erase number from $r$-th position in $O({\\sqrt{n}})$ operations. And we can insert this number after $(l - 1)$-th position in $O({\\sqrt{n}})$ operations. Also we can fast recalc $cnt$ after transformations. Also we can fast process the queries of the Unable to parse markup [type=CF_TEX] To keep the size of the blocks close to $\\sqrt{n}$, we need rebuild our structure after each $({\\sqrt{n}})$-th query of the $1$st type. We can rebuild structure in $O(n)$ operations. Asymptotics - $O(n{\\sqrt{n}})$.",
    "tags": [
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "455",
    "index": "E",
    "title": "Function",
    "statement": "Serega and Fedor play with functions. One day they came across a very interesting function. It looks like that:\n\n- $f(1, j) = a[j]$, $1 ≤ j ≤ n$.\n- $f(i, j) = min(f(i - 1, j), f(i - 1, j - 1)) + a[j]$, $2 ≤ i ≤ n$, \\textbf{$i ≤ j ≤ n$}.\n\nHere $a$ is an integer array of length $n$.\n\nSerega and Fedya want to know what values this function takes at some points. But they don't want to calculate the values manually. So they ask you to help them.",
    "tutorial": "In this problem you should quickly be able to compute the function described in the statement. You may notice that this task is equivalent to next task: Go through the array $a$, starting from the position of $y$, making $(x - 1)$ step. Step might be: step to the left or to stay in place. Function is calculated as follows: $f(x,y)=\\operatorname*{min}_{l=y-x+1}^{y}(\\sum_{i=l}^{y}a[i]\\cdot k_{i})$, $k_{i}$ - how many times we visited the $i$ th element of the array $a$. For a fixed $l$ is clear, it is most optimally that a minimum on the interval $[l, y]$ has been visited by $(x - (y - l))$ times, and all the other numbers once. You may notice that optimally to $a[l]$ was a minimum. From all this we can conclude that for a fixed $l$ answer is - $sum[y] - sum[l] + a[l] \\cdot (x - (y - l))$, where $sum$ - an array of prefix sums of array $a$. Above formula can be written as follows: $sum[y] - sum[l] + a[l] \\cdot (x - (y - l)) = sum[y] - sum[l] + a[l] \\cdot (x - y + l) = sum[y] - sum[l] + a[l] \\cdot l + a[l] \\cdot (x - y) = sum[y] + (a[l] \\cdot (x - y) + a[l] \\cdot l - sum[l])$ You may notice that in brackets something like the equation of the line - $K \\cdot X + B$. That's very similar to the equation of the line: $a[l] \\cdot (x - y) + a[l] \\cdot l - sum[l]$, where $K = a[l]$, $X = (x - y)$, $B = a[l] \\cdot l - sum[l]$. Now we must find minimum for all $l$ and fixed $X = (x - y)$. We have $n$ lines, i. e. for every element in array $a$ one line $(K_{i}, B_{i})$. Answer for query equal to: $f(x,y)=s u m[y]+\\operatorname*{min}_{i=y-x+1}^{y}\\left(K_{i}\\cdot X+B_{i}\\right)$, where $(K_{i}, B_{i})$ - $i$-th line. $K_{i} = a[i]$, $B_{i} = a[i] \\cdot i - sum[i]$. For fast answer calculation we must use Convex Hull Trick with segment tree. In every vertex of segment tree we keep all lines for segment of this vertex. This requires $O(n\\log n)$ space, because each line lies in $\\log n$ vertices. And we can answer query in $O(\\log^{2}n)$ operations. Because we visit $O(\\log n)$ vertices and each vertex need in $O(\\log n)$ operations. You can learn the theory about Convex Hull Trick here.",
    "tags": [
      "data structures"
    ],
    "rating": 2900
  },
  {
    "contest_id": "456",
    "index": "A",
    "title": "Laptops",
    "statement": "One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.\n\nPlease, check the guess of Alex. You are given descriptions of $n$ laptops. Determine whether two described above laptops exist.",
    "tutorial": "In this task you need to check the existense of such pair $i$ and $j$, such that $i  \\neq  j$, $a[i] < a[j]$, $b[i] > b[j]$. If such $i$ and $j$ exist, Alex is happy. There is very simple solution. Let's check that for all $i$ $a[i] = b[i]$. If this condition is true we should print \"Poor Alex\". We can easy prove it. Let's sort arrays $a$ and $b$ like pair of numbers in increasing order. We can see that Alex is happy if we have at least one inversion in array $b$, i.e there is such pair $i$ and $j$ that $b[i] > b[j]$ and $i < j$ ($i<j\\Leftrightarrow a[i]<a[j]$). i.e it means that array $b$ is not sorted and it's means that $a  \\neq  b$.",
    "tags": [
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "456",
    "index": "B",
    "title": "Fedya and Maths",
    "statement": "Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:\n\n\\[\n(1^{n} + 2^{n} + 3^{n} + 4^{n}) mod 5\n\\]\n\nfor given value of $n$. Fedya managed to complete the task. Can you? Note that given number $n$ can be extremely large (e.g. it can exceed any integer type of your programming language).",
    "tutorial": "In this task you need to calculate formula that given in the statement, but it's hard to calculate it with the naive way. But we can transform our formula to this: $\\begin{array}{c}{{\\left(1^{n}+2^{n}+3^{n}+4^{n}\\right)\\,\\mathrm{mod}\\,\\,5\\,=\\,\\left(1^{n}\\,\\,m o o d\\,\\,\\phi(n)\\,+\\,3^{n}\\,\\,m o d\\,\\,\\phi(n)\\,+\\,3^{n}\\,\\,m o d\\,\\,\\phi(n)\\,+\\,4^{n}\\,\\,\\mathrm{mod}\\,\\,\\phi(n)\\,+\\,0^{n}\\,\\,\\mathrm{mod}\\,\\,\\phi(n)\\,+\\,0,}}\\\\ {{4^{n}\\,\\,m o d\\,\\,\\phi(n)\\,\\,\\,\\,\\,\\,\\mathrm{mod}\\,\\,5=\\left(1^{n}\\,\\,m o o d\\,\\,4\\,+\\,3^{n}\\,\\,m o d\\,\\,4\\,\\,+\\,4^{n}\\,\\,m o d\\,\\,4\\,\\,+\\,4^{n}\\,\\,m o d\\,\\,4\\,\\,\\right)\\,\\,\\,\\mathrm{mod}\\,\\,5\\,}}\\end{array}$ This formula is right because $5$ is prime number and it's coprime with $1$, $2$, $3$, $4$. $ \\phi (5) = 4$ To solve this task we should be able to calculate remainder of division $n$ by $4$ and calculate formula for small $n$. Asymptotics - $O(\\log N)$. There is also another solution. It uses a fast exponentiation, but not binary exponentiation. The idea of this exponentiation is the same as that of the binary exponentiation. Let we want to fast calculate $x^{n}modP$. Algorithm is very simple. Let process digits of n moving from end to begin. Let $Result$ - current result and $K$ - $x^{(10i)}$, $i$ - number of the currently processed digit (digits are numbered from the end. Used 0-indexation). During processing of digits, we must update result: $R e s u l t=(R e s u l t+K^{c\\left[i\\right]})\\;\\;\\mathrm{mod}\\;P$, $c[i]$ - $i$-th digit of the number $n$ (digits are numbered from the end). Asymptotics - $O(\\log N)$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "457",
    "index": "A",
    "title": "Golden System",
    "statement": "Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number $q={\\frac{{\\sqrt{5}}+1}{2}}$, in particular that $q^{2} = q + 1$, and she thinks it would make a good base for her new unique system. She called it \"golden system\". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression $a_{0}a_{1}...a_{n}$ equals to $\\sum_{i=0}^{n}a_{i}\\cdot q^{n-i}$.\n\nSoon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.\n\nGiven two numbers written in golden system notation, determine which of them has larger decimal value.",
    "tutorial": "The important observation one needs to make is that $q^{n} = q^{n - 1} + q^{n - 2}$, which means that we can replace two consecutive '1' digits with one higher significance digit without changing the value. Note that sometimes the next digit may become more than '1', but that doesn't affect the solution. There are two different kinds of solutions for this problem The first kind of solution involves normalizing both numbers first. The normalization itself can be done in two ways - from the least significant digit or from the highest significant one using the replacement operation mentioned above. In either we will need $O(n)$ operations for each number and we then just need to compare them lexicographically. Other kind of solutions compare numbers digit by digit. We can start from the highest digit of the numbers, and propagate them to the lower digits. On each step we can do the following: If both numbers have ones in the highest bit, then we can replace both ones with zeroes, and move on to the next highest bit. Now only one number has one in the highest bit. Without loss of generality let's say it's the first number. We subtract one from the highest bit, and add it to the next two highest bits. Now the next two bits of the first number are at least as big as the first two bits of the second number. Let's subtract the values of these two bits of the second number from both first and second number. By doing so we will make the next two bits of the second numbers become $0$. If first number has at least one two, then it is most certainly bigger (because the sum of all the $q^{i}$ for $i$ from $0$ to $n$ is smaller than twice $q^{n + 1}$). Otherwise we still have only $0$s and $1$s, and can move on to the next highest bit, back to step (1). Since the ordinal of the highest bit is now smaller, and we only spent constant amount of time, the complexity of the algorithm is linear.",
    "tags": [
      "math",
      "meet-in-the-middle"
    ],
    "rating": 1700
  },
  {
    "contest_id": "457",
    "index": "B",
    "title": "Distributed Join",
    "statement": "Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.\n\nSuppose she wants to join two tables, $A$ and $B$. Each of them has certain number of rows which are distributed on different number of partitions. Table $A$ is distributed on the first cluster consisting of $m$ partitions. Partition with index $i$ has $a_{i}$ rows from $A$. Similarly, second cluster containing table $B$ has $n$ partitions, $i$-th one having $b_{i}$ rows from $B$.\n\nIn one network operation she can copy one row from any partition to any other partition. At the end, for each row from $A$ and each row from $B$ there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.",
    "tutorial": "One of the optimal strategies in this problem is to locate a node $a$ with the most rows, then move all the data from the cluster $a$ does not belong to onto $a$, and then for every other node $b$ in the cluster that $a$ belongs to either move all the data from $b$ onto $a$, or move all the rows from the other cluster into $b$, whichever is cheaper.",
    "tags": [
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "457",
    "index": "C",
    "title": "Elections",
    "statement": "You are running for a governor in a small city in Russia. You ran some polls and did some research, and for every person in the city you know whom he will vote for, and how much it will cost to bribe that person to vote for you instead of whomever he wants to vote for right now. You are curious, what is the smallest amount of money you need to spend on bribing to win the elections. To win elections you need to have strictly more votes than any other candidate.",
    "tutorial": "First let's consider a subproblem in which we know how many votes we will have at the end, and we want to figure out how much money we will spend. To solve this problem, one first needs to buy the cheapest votes from all the candidates who have as many or more votes. If after that we still don't have enough votes, we buy the cheapest votes overall from the remaining pool of votes until we have enough votes. Both can be done in linear time, if we maintain proper sorted lists of votes. This approach itself leads to an $O(n^{2})$ solution. There are two ways of improving it. One is to come up with a way of computing the answer for $k + 1$ votes based on the answer for $k$ votes. If for each number of votes we have a list of candidates, who have at least that many votes, and we also maintain a set of all the votes that are available for sale, then to move from $k$ to $k + 1$ we first need to return the $k$-th most expensive vote for each candidate that has at least $k$ votes (we had to buy them before, but now we do not have to anymore) back into the pool, and then get that many plus one votes from the pool (that many to cover votes we just returned, plus one because now we need $k + 1$ votes, not $k$). This solution has $nlogn$ complexity, if we use a priority queue to maintain the pool of the cheapest votes. In fact, with certain tweaks one can reduce the complexity of moving from $k$ to $k + 1$ to amortized constant, but the overall complexity will not improve, since one still needs to sort all the candidates at the beginning. Another approach is to notice that the answer for the problem first strictly decreases with the number of votes we want to buy, and then strictly increases, so one can use ternary search to find the number of votes that minimizes the cost.",
    "tags": [
      "brute force"
    ],
    "rating": 2100
  },
  {
    "contest_id": "457",
    "index": "D",
    "title": "Bingo!",
    "statement": "The game of bingo is played on a $5 × 5$ square grid filled with distinct numbers between $1$ and $75$. In this problem you will consider a generalized version played on an $n × n$ grid with distinct numbers between $1$ and $m$ $(m ≥ n^{2})$.\n\nA player begins by selecting a randomly generated bingo grid (generated uniformly among all available grids). Then $k$ distinct numbers between $1$ and $m$ will be called at random (called uniformly among all available sets of $k$ numbers). For each called number that appears on the grid, the player marks that cell. The score at the end is 2 raised to the power of (number of completely marked rows plus number of completely marked columns).\n\nDetermine the expected value of the score. The expected score may be very large. If the expected score is larger than $10^{99}$, print $10^{99}$ instead (for example as \"1e99\" without the quotes).",
    "tutorial": "The score function of a board in the problem is $2^{x}$, where $x$ is number of rows and columns fully covered. Since $2^{x}$ is the number of all the subsets of a set of size $x$ (including both a full set and an empty set), the score function is essentially the number of ways to select a set of fully covered rows and columns on the board. The problem reduces to computing the expected number of such sets. For a given set of rows $R$ and a given set of columns $C$ we define $p_{R, C}$ as a probability that those rows and columns are fully covered. Then the answer is $a=\\sum_{R\\subset C}p_{R,C}$. For two sets of rows of the same size $r$ and two sets of columns of the same size $c$ the value of $p_{R, C}$ will be the same, let's call it $q_{r, c}$. With that observation the answer can be computed as $\\theta=\\sum_{r,c}{\\binom{r}{m}}_{m}^{r}\\theta_{r,c}$. $q_{r, c}$ in turn is just the probability that $n(r + c) - rc$ numbers on the board are chosen from the $k$ numbers that were called, and the remaining $(n - c)(n - r)$ numbers on the board are chosen from the remaining $m - (n(r + c) - rc)$ numbers available.",
    "tags": [
      "combinatorics",
      "math",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "457",
    "index": "E",
    "title": "Flow Optimality",
    "statement": "There is a computer network consisting of $n$ nodes numbered 1 through $n$. There are links in the network that connect pairs of nodes. A pair of nodes may have multiple links between them, but no node has a link to itself.\n\nEach link supports unlimited bandwidth (in either direction), however a link may only transmit in a single direction at any given time. The cost of sending data across a link is proportional to the square of the bandwidth. Specifically, each link has a positive weight, and the cost of sending data across the link is the weight times the square of the bandwidth.\n\nThe network is connected (there is a series of links from any node to any other node), and furthermore designed to remain connected in the event of any single node failure.\n\nYou needed to send data from node 1 to node $n$ at a bandwidth of some positive number $k$. That is, you wish to assign a bandwidth to each link so that the bandwidth into a node minus the bandwidth out of a node is $ - k$ for node 1, $k$ for node $n$, and 0 for all other nodes. The individual bandwidths do not need to be integers.\n\nWishing to minimize the total cost, you drew a diagram of the network, then gave the task to an intern to solve. The intern claimed to have solved the task and written the optimal bandwidths on your diagram, but then spilled coffee on it, rendering much of it unreadable (including parts of the original diagram, and the value of $k$).\n\nFrom the information available, determine if the intern's solution may have been optimal. That is, determine if there exists a valid network, total bandwidth, and optimal solution which is a superset of the given information. Furthermore, determine the efficiency of the intern's solution (if possible), where efficiency is defined as total cost divided by total bandwidth.",
    "tutorial": "Let's begin by considering an arbitrary cycle in the given graph (if one exists). We could add some amount of flow to each edge in the cycle, and doing so must result in an equivalent or worse cost (otherwise the intern's solution would clearly be non-optimal). Thus if we consider the function c(x) = sum(w_i * (f_i + x)^2), it should be minimized at x=0. Since this function is continuous, a necessary condition is c'(0) = 0. This implies sum(w_i * f_i) = 0 for any cycle. Let us denote w_i * f_i as the \"potential\" of an edge. We can define the potential between two vertices in the same connected component as the sum of the potentials of the edges along any path between them. If the potential is not well defined, then the intern's solution is not optimal. Additionally, the potential from node 1 to any other node must be positive (It cannot be zero because the original graph is biconnected), and similarly the potential from any node to node N must be positive. Furthermore no potential can exceed or equal the potential between node 1 and node N (if they are connected). These conditions can be verified in linear time using a dfs, allowing us to binary search the answer in O(N log N). Alternatively, the union-find algorithm can be modified to track potentials as well as components. The true nature of the problem is revealed by making the following replacements: weight -> resistance bandwidth -> current cost -> power potential -> voltage The problem asks you to determine if the given currents in a resistor network are optimal.",
    "tags": [
      "constructive algorithms",
      "flows",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "457",
    "index": "F",
    "title": "An easy problem about trees",
    "statement": "Pieguy and Piegirl are playing a game. They have a rooted binary tree, that has a property that each node is either a leaf or has exactly two children. Each leaf has a number associated with it.\n\nOn his/her turn a player can choose any two leafs that share their immediate parent, remove them, and associate either of their values with their parent, that now became a leaf (the player decides which of the two values to associate). The game ends when only one node (the one that was the root of the tree) is left.\n\nPieguy goes first, and his goal is to maximize the value that will be associated with the root when the game ends. Piegirl wants to minimize that value. Assuming that both players are playing optimally, what number will be associated with the root when the game ends?",
    "tutorial": "The solution for this problem is a dynamic programming on a tree with O(n) complexity. In this editorial \"even tree\" means a tree in which players will make an even number of turns, while \"odd tree\" is the tree in which players will make an odd number of turns. We will be solving a slightly modified problem: one in which all the numbers on the leaves are $0$s and $1$s. Once this problem is solved, the general problem can be solved by doing a binary search on the answer, and then marking all the leaves with higher or equal value as $1$s, and all other values as $0$s. If the tree is an odd tree, then the first player makes the last turn, and it is enough that at that moment only one of the two children of the root is $1$. If the tree is an even tree, then the second player makes the last turn, so for the first player it is critical that by that time both children of the tree are $1$ if he wants to win. One simple case is the case when the tree is an odd tree, and both its immediate subtrees are even trees (by an immediate subtree, or just \"subtree' of a node, here we will mean a subtree rooted at one of the nodes' immediate children). In this case we can recursively solve each of the immediate subtrees, and if the first player wins any of them, he wins the entire tree. He does that by making his first turn into the tree that he can win, and then every time the second player makes a turn in that tree, responding with a corresponding optimal move, and every time the second player makes a turn in the other tree, making a random move there. If both immediate subtrees are odd trees, however, a similar logic will not work. If the second player sees that the first player can win one of the trees, and the first player already made a turn in that tree, the second player can force the first player to play in the other tree, in which the second player will make the last turn, after which the first player will be forced to make a turn in the first tree, effectively making himself do two consecutive turns there. So to win the game the first player needs to be able to win a tree even if the second player has an option to skip one turn. So we will need a second dimension to the dynamic programming solution that will indicate whether one of the players can skip one turn or not (we call the two states \"canskip\" if one can skip a turn and \"noskip' if such an option does not exist). It can be easily shown, that we don't need to store how many turns can be skipped, since if two turns can be skipped, and it benefits one player to skip a turn, another player will immediately use another skip, effectively making skips useless. To make the terminology easier, we will use a term \"we\" to describe the first player, and \"he\" to describe the second player. \"we can win a subtree\" means that we can win it, if we go first there, \"he can win a subtree\" means that he can win it if he goes first (so \"if one goes first\" is always assumed and omitted). If we want to say that \"we can win going second\", we will instead say \"he cannot win [going first]\" or \"he loses [going first]\", which has the same meaning Now we need to consider six cases (three possible parities of children multiplied by whether one can skip a turn or not). In all cases we assume that both children have at least two turns in them left. Cases when a child has no turns left (it is a leaf node), or when it has only one turn left (it is a node whose both children are leaves) are both corner cases and need to be handled separately. It is also important to note, that when one starts handling those corner cases, he will encounter an extra state, when the players have to skip a turn, even if it is not beneficial for whomever will be forced to do that. We call such state \"forceskip\". In the case when both subtrees have more than one turn left, forceskip and canskip are the same, since players can always agree to play in such a way, that the skip, if available, is used, without changing the outcome. Below we only describe canskip and noskip cases, in terms of transitions from canskip and noskip states. One will need, however, to introduce forceskip state when he handles corner cases, which we do not describe in this editorial. The answer for forceskip will be the same as the answer for skip in general case, but different for corner cases. even-even-noskip: the easiest case, described above, it is enough if we win any of the subtrees with no skip. even-even-canskip: this case is similar to a case when there's one odd subtree and one even subtree, and there's no skip (the skip can be just considered as an extra turn attached to one of the trees), so the transition is similar to the one for odd-even-noskip case described below. We win iff we can win one tree with canskip, and he cannot win the other with noskip. odd-even-noskip: if we can win the odd tree without a skip, and he cannot win the even tree without a skip, then we make a turn into the odd tree, and bring it into the even-even-noskip case, where he loses both trees, so we win. The other, less trivial, condition under which we win is If we can win the even tree with canskip, and he can't win the odd tree with canskip. A motivation for this case is that odd subtree with a skip is similar to an even subtree, so by making a turn into the even case, we bring our opponent to an odd-odd case, where he loses both threes with a skip, which means that no matter which tree he makes a turn into, we will be responding to that tree, and even if he uses another tree to make a skip, he will still lose the tree into which he made his first turn. Since we make the last move, we win. odd-even-skip: this is a simple case. We can consider the skip as an extra turn in the odd subtree, so as long as we can win even subtree with no skip, or odd subtree with a skip, we win. odd-odd-noskip: we need to win either of the subtrees with a skip to win. odd-odd-skip: to handle this case we can first consider immediately skipping: if he loses noskip case for the current subtree, then we win. Otherwise we win iff we can win one of trees with a skip, and he can't win the other without a skip. The more detailed motivation for each of the cases is left as an exercise.",
    "tags": [
      "dp",
      "games",
      "greedy",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "459",
    "index": "A",
    "title": "Pashmak and Garden",
    "statement": "Pashmak has fallen in love with an attractive girl called Parmida since one year ago...\n\nToday, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.",
    "tutorial": "Four vertices of a square with side length $a$ (and sides parallel to coordinate axis) are in this form: $(x_{0}, y_{0})$, $(x_{0} + a, y_{0})$, $(x_{0}, y_{0} + a)$, $(x_{0} + a, y_{0} + a)$. Two vertices are given, calculate the two others (and check the ranges). Total complexity : $O(1)$",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "459",
    "index": "B",
    "title": "Pashmak and Flowers",
    "statement": "Pashmak decided to give Parmida a pair of flowers from the garden. There are $n$ flowers in the garden and the $i$-th of them has a beauty number $b_{i}$. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!\n\nYour task is to write a program which calculates two things:\n\n- The maximum beauty difference of flowers that Pashmak can give to Parmida.\n- The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.",
    "tutorial": "If all numbers are equal then answer will be $n * (n - 1) / 2$, otherwise the answer will be $cnt_{1} * cnt_{2}$, where $cnt_{1}$ is the number of our maximum elements and $cnt_{2}$ is the number of our minimum elements. Total complexity : $O(n)$",
    "tags": [
      "combinatorics",
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "459",
    "index": "C",
    "title": "Pashmak and Buses",
    "statement": "Recently Pashmak has been employed in a transportation company. The company has $k$ buses and has a contract with a school which has $n$ students. The school planned to take the students to $d$ different places for $d$ days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all $d$ days.\n\nPlease help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.",
    "tutorial": "For each student consider a sequence of $d$ elements from $1$ to $k$ that shows the bus number which is taken by this student on each day. Obviously, there are $k^{d}$ different sequence at all, so if $n > k^{d}$, pigeonhole principle indicates that at least two of this sequences will be equal, so that two students will become close friends and no solutions exist. But if $n  \\le  k^{d}$, then we can assign a unique sequence to each student and compute the answer. For computing that, we can find the first $n$ $d$-digits numbers in $k$-based numbers. Total complexity : $O(n * d)$",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "459",
    "index": "D",
    "title": "Pashmak and Parmida's problem",
    "statement": "Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.\n\nThere is a sequence $a$ that consists of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Let's denote $f(l, r, x)$ the number of indices $k$ such that: $l ≤ k ≤ r$ and $a_{k} = x$. His task is to calculate the number of pairs of indicies $i, j$ $(1 ≤ i < j ≤ n)$ such that $f(1, i, a_{i}) > f(j, n, a_{j})$.\n\nHelp Pashmak with the test.",
    "tutorial": "First of all, we can map the given numbers to integers of range $[1, 10^{6}]$. Let $l_{i}$ be $f(1, i, a_{i})$ and let $r_{i}$ be $f(i, n, a_{i})$, we want to find the number of pairs $(i, j)$ such that $i < j$ and $l_{i} > r_{j}$. For computing $l_{i}$s, we can store an array named $cnt$ to show the number of occurence of any $i$ with $cnt[i]$. To do this, we can iterate from left to right and update $cnt[i]$s; also, $l_{i}$ would be equal to $cnt[a_{i}]$ at position $i$ ($r_{i}$ s can be computed in a similar way). Beside that, we get help from binary-indexed trees. We use a Fenwick tree and iterate from right to left. In each state, we add the number of elements less than $l_{i}$ to answer and add $r_{i}$ to the Fenwick tree. Total complexity : $O(n * logn)$ Also we can solve this problem using divide and conquer method. You can see the second sample solution to find out how to do this exactly.",
    "tags": [
      "data structures",
      "divide and conquer",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "459",
    "index": "E",
    "title": "Pashmak and Graph",
    "statement": "Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem.\n\nYou are given a weighted directed graph with $n$ vertices and $m$ edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path.\n\nHelp Pashmak, print the number of edges in the required path.",
    "tutorial": "In this problem, a directed graph is given and we have to find the length of a longest strictly-increasing trail in it. First of all consider a graph with $n$ vertices and no edges, then just sort the given edges by their weights (non-decreasingly) and add them to the graph one by one. Let $dp[v]$ be the length of a longest increasing trail which ends in the vertex $v$. In the mentioned method, when you're adding a directed edge $xy$ to the graph, set $dp[y]$ value to $max(dp[y], dp[x] + 1)$ (because of trails which ends in $y$ and use this edge). You need to take care of the situation of being some edges with equal weights; for this job we can add all edges of the same weights simultaneously. Total complexity : $O(n + m * logm)$",
    "tags": [
      "dp",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "460",
    "index": "A",
    "title": "Vasya and Socks",
    "statement": "Vasya has $n$ pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every $m$-th day (at days with numbers $m, 2m, 3m, ...$) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?",
    "tutorial": "At this problem you need to model what written in statements. Also, it can be proved, that answer can be calculated using formula: $n+{\\bigl\\lfloor}{\\frac{n-1}{m-1}}{\\bigr\\rfloor}$ , where $ \\lfloor  x \\rfloor $ is the integer part of $x$.",
    "code": "#include <iostream>\nusing namespace std;\n \nint solve(int n, int m)\n{\n    int s = 0;\n    s = n + n/(m - 1);\n    if (n%(m - 1) == 0)\n        s -= 1;\n    return s;\n}\n \nint main()\n{\n    int n, m;\n    cin >> n >> m;\n    cout << solve(n,m) << endl;\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "460",
    "index": "B",
    "title": "Little Dima and Equation",
    "statement": "Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment.\n\nFind all integer solutions $x$ $(0 < x < 10^{9})$ of the equation:\n\n\\[\nx = b·s(x)^{a} + c,\n\\]\n\nwhere $a$, $b$, $c$ are some predetermined constant values and function $s(x)$ determines the sum of all digits in the decimal representation of number $x$.\n\nThe teacher gives this problem to Dima for each lesson. He changes only the parameters of the equation: $a$, $b$, $c$. Dima got sick of getting bad marks and he asks you to help him solve this challenging problem.",
    "tutorial": "Obviously $S(x)$ can take only integer values and $1  \\le  S(x)  \\le  81$. Let's check $S(x)$ from $1$ to $81$, and calculate $B * S(x)^{A} + C$. After that if sum of digits of this number is equal to $S(x)$, it is positive and less than $10^{9}$, than it is a solution. There could be bug because of using C++ pow() function.",
    "code": "#include<iostream>\n#include<vector>\nusing namespace std;\n#define ll long long\n \nll S(ll x)\n{\n    if (x < 0)return -1;\n    ll s = 0;\n    while(x)\n    {\n        s += x%10;\n        x /= 10;\n    }\n \n    return s;\n}\n \nll poww(ll a, ll b)\n{\n    ll res = 1;\n    for(int i = 1; i<=b; ++i)\n        res *= a;\n \n    return res;\n}\n \nint main(){\n    ll A, B, C;\n    cin >> A >> B >> C;\n    int cou = 0;\n    vector<ll>ans;\n    for(ll s = 1; s <= 81; ++s)\n    {\n        ll x = B*poww(s, A) + C;\n        if (S(x) == s && x < 1000000000) \n        {\n            ans.push_back(x);\n            cou++;\n        }\n    }\n \n    cout << cou << \"\\n\";\n    for(int i = 0; i<cou; ++i)\n        cout << ans[i] << \" \";\n \n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "460",
    "index": "C",
    "title": "Present",
    "statement": "Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted $n$ flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions.\n\nThere are $m$ days left to the birthday. The height of the $i$-th flower (assume that the flowers in the row are numbered from $1$ to $n$ from left to right) is equal to $a_{i}$ at the moment. At each of the remaining $m$ days the beaver can take a special watering and water $w$ contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get?",
    "tutorial": "Note,that answer is positive integer not greater than $10^{9} + 10^{5}$. Using binary search on answer, we will find answer. Really, we can check in $O(n)$ if some height is achievable. We go from left to right. For current flower we calculate how much times it need to be watered to stand not lower than checking value. If cuurent flower need to be watered for $h$ times, we will star $h$ segments in current flower. We would keep array, in which $st[i]$ - number of segments, which starts in $i$-th flower. Also, we will keep variable, in which we will keep number of segments, which cover current flower. This variable could be updated at $O(1)$. Really, to get new value we just need to subtract $st[i - w]$, and, if we create new segments, to add $st[i]$ Also, it can be proved that simple greedy algorithm works. At every of $m$ iterations we can find the leftmost flower with the smallest height and water the segment, which begins in it. Primitive realisation works at $O(nm)$, so you need to use data structure, which can add on segment and find minimum at segment. For example, you can use segment tree with lazy updation or sqrt-decomposition. Such solutions works longer, but faster than TL Prove: Consider any optimal sequence of moves (using which max. answer reachs). Consider initially the leftmost smallest flower, and suppose all segments which covers it.(suppose, there are at least $1$ segment, because else answer is initial height of this flower, so we can put a segment to start in this flower, and answer would not change). Suppose that there are no segments, which starts from current flower. Consider the rightests of segments.(If there are more than one, than any of them). Than, we can move this segment to start in the initially leftmost smallest flower, and the answer would not change. Really, flowers, which earlier was at this segments were higher, than leftmost smallest, and were watered not least times. So, after we moved the answer had not decreased. So, new sequence is also optimal. So, there is sequence of moves, which consists the segment, which starts at the initially leftmost smallest flower. So, let use this. Similary to other of $m$ days, and it would be optimally.",
    "code": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#define lol long long\nusing namespace std;\n \nconst lol MAXVAL = 1000100000;\nlol n, m, w;\nvector<lol> a;\n \nvoid read()\n{\n    cin >> n >> m >> w; //m - number of moves,  w - width\n    a.resize(n);\n    for (lol i = 0; i < n; i++)\n        cin >> a[i];\n}\n \nbool check(lol x)\n{\n    vector<lol> st(n,0);\n    lol scurr = 0;\n    lol moves = 0;\n    for (lol i = 0; i < n; i++)\n    {\n        scurr -= i - w >= 0 ? st[i - w] : 0;\n        if (a[i] + scurr < x)\n        {\n            st[i] = x - a[i] - scurr;\n            scurr += st[i];\n            moves += st[i];\n        }\n        if (moves > m)\n            return 0;\n    }\n    return moves <= m;\n}\n \nvoid solve()\n{\n    lol l = 1;\n    lol r = MAXVAL;\n    lol x;\n    while (l <= r)\n    {\n        lol md = (l + r) >> 1;\n        if (check(md))\n        {\n            x = md;\n            l = md + 1;\n        }\n        else\n            r = md - 1;\n    }\n \n    cout << x << endl;\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    read();\n    solve();\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "460",
    "index": "D",
    "title": "Little Victor and Set",
    "statement": "Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers $S$ that has the following properties:\n\n- for all $x$ $(x\\in S)$ the following inequality holds $l ≤ x ≤ r$;\n- $1 ≤ |S| ≤ k$;\n- lets denote the $i$-th element of the set $S$ as $s_{i}$; value $f(S)=s_{1}\\oplus s_{2}\\oplus\\cdot\\cdot\\Leftrightarrow s_{1S}$ must be as small as possible.\n\nHelp Victor find the described set.",
    "tutorial": "If $r - l  \\le  4$ we can all subsets of size not greater than $k$. Else, if $k = 1$, obviously that answer is $l$. If $k = 2$, answer is $1$, because $xor$ of numbers $2x$ and $2x + 1$ equls $1$. If $k  \\ge  4$ answer is $0$ because $xor$ of to pairs with $xor$ $1$ is $0$. If $k = 3$, we can choose numbers $2x$ and $2x + 1$ with $xor$ $1$. So we need to know, if we can get $xor$ equals $0$. Suppose that there are 3 such numbers $x$, $y$ and $z$ ($r  \\ge  x > y > z  \\ge  l$) with $xor$ equals $0$. Consider the most non-zero bit of number $x$. At the same bit of $y$ it's also $1$, because $xor$ equls 0, and $y > z$. Consider the next bit of numbers. If $z$ have $0$ there, we have to do next: set the previous bit of numbers $x$ and $y$ equals $0$, and set current bit equals $1$. Obviously $xor$ still equals 0, $z$ hadn't changed and numbers $x$ and $y$ stood closer to $z$, so they are still at $[l, r]$.And $x > y$.Consider the next bit of numbers. If $z$ has zero here than we will change most bits of $x$ and $y$ at the same way and so on. $z > 0$, so somewhen we will get to bit in which $z$ has $1$. Since $xor$ equals $0$, the same bit of $x$ would be $1$ because $x > y$, and $y$ would have $0$ there. At the next bits we will change bit in $x$ to $0$, and in numbers $y$ and $z$ to $1$.Finally $z$ would be greater or equal than before, and $x$ would be less or greater than before, and $x > y > z$ would be correct. So, we have the next: if such numbers $x$, $y$ and $z$ exist than also exist numbers: $1100 \\dots 000$ $1011 \\dots 111$ $0111 \\dots 111$ with $xor$ equals $0$. There are not much such triples, so we can check them.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\n \nconst long long INF = 10000000000001;\n \nint numberOfOnes(int x)\n{\n    int num=0;\n    while (x)\n    {\n        num += x&1;\n        x >>= 1;\n    }\n    return num;\n}\n \nvoid solution1(long long a, long long b, int k)\n{\n    vector<long long> ans;\n    int indmax = 1 << (b - a + 1);\n    long long answer = INF;\n    for (int i = 1; i < indmax; i++)\n    {\n        if (numberOfOnes(i) > k)\n            continue;\n        long long currentXor=0;\n        for (int j = 0; j < b - a + 1; j++)\n            if ( i & (1<<j))\n                currentXor ^= (a + j);\n        if (currentXor < answer)\n        {\n            answer = currentXor;\n            ans.clear();\n            for (int j = 0; j < b - a + 1; j++)\n                if ( i & (1<<j))\n                    ans.push_back(a + j);\n        }\n    }\n    cout << answer << endl;\n    cout << ans.size() << endl;\n    for (int i = 0; i < ans.size(); i++)\n        cout << ans[i] << \" \";\n    cout << endl;\n}\n \nvoid solution2(long long a, long long b, int k)\n{\n    if (k == 1)\n    {\n        cout << a << endl;\n        cout << 1 << endl;\n        cout << a << endl;\n        return;\n    }\n    if (k == 2)\n    {\n        cout << 1 << endl;\n        cout << 2 << endl;\n        if (a & 1)\n            cout << a + 1 << \" \" << a + 2 << endl;\n        else\n            cout << a << \" \" << a + 1 << endl;\n        return;\n    }\n    if (k >= 4)\n    {\n        cout << 0 << endl;\n        cout << 4 << endl;\n        long long frst = a;\n        if (frst&1)\n            frst++;\n        cout << frst << \" \" << frst + 1 << \" \" << frst + 2 << \" \" << frst + 3 << endl;\n        return;\n    }\n    // 10111\n    // 11000\n    // 01111\n    //140737488355327 211106232532992\n    long long mn = 1;\n    long long mx = 3;\n    while (mx <= b)\n    {\n        if (mn >= a)\n        {\n            cout << 0 << endl;\n            cout << 3 << endl;\n            cout << mn << \" \" << mx - 1 << \" \" << mx << endl;\n            return;\n        }\n        mn<<=1;\n        mn++;\n        mx<<=1;\n    }\n    cout << 1 << endl;\n    cout << 2 << endl;\n    if (a & 1)\n        cout << a + 1 << \" \" << a + 2 << endl;\n    else\n        cout << a << \" \" << a + 1 << endl;\n    return;\n}\n \nint main()\n{\n    long long a,b;\n    int k;\n    cin >> a >> b;\n    cin >> k;\n    if (a == 8 && b == 15 && k == 3)\n    {\n        cout << 1 << endl << 2 << endl << \"10 11\" << endl;\n        return 0;\n    }\n    if (a == 8 && b == 30 && k == 7)\n    {\n        cout << 0 << endl << 5 << endl << \"14 9 28 11 16\" << endl;\n        return 0;\n    }\n    if (b - a < 5)\n        solution1(a, b, k);\n    else\n        solution2(a, b, k);\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "460",
    "index": "E",
    "title": "Roland and Rose",
    "statement": "Roland loves growing flowers. He has recently grown a beautiful rose at point $(0, 0)$ of the Cartesian coordinate system. The rose is so beautiful that Roland is afraid that the evil forces can try and steal it.\n\nTo protect the rose, Roland wants to build $n$ watch towers. Let's assume that a tower is a point on the plane at the distance of at most $r$ from the rose. Besides, Roland assumes that the towers should be built at points with integer coordinates and the sum of squares of distances between all pairs of towers must be as large as possible. Note, that Roland may build several towers at the same point, also he may build some of them at point $(0, 0)$.\n\nHelp Roland build the towers at the integer points so that the sum of squares of distances between all towers is maximum possible. Note that the distance in this problem is defined as the Euclidian distance between points.",
    "tutorial": "Formal statement: 2 natural numbers are given: $R$ - radii, and $N$ - number of points. You have to choose $N$ unnesessarily distinct points $A_{1}, A_{2}, ...A_{N}$ which are lying inside or on side of circle, such that $\\textstyle\\sum_{i<j}A_{i}A_{j}^{2}$ takes its maximal value. At first let ${\\overline{{a_{i}}}}$ be a vector from $(0, 0)$ to point $A_{i}$. Value of $\\textstyle\\sum_{i<j}A_{i}A_{j}^{2}$ is equal $\\sum_{i<j}(\\overline{{{a_{i}^{\\star}}}}-\\overline{{{a_{j}}}})^{2}$, what is equal to $\\frac{\\sum(\\vec{a}_{1}^{\\dagger}-\\vec{a}_{j}^{\\dagger})^{2}}{2}$, and it can be rewritten as $\\frac{{\\cal N}(a_{1}^{2}+a_{2}^{2}+...+a_{N}^{2})-(\\widehat{a_{1}}^{\\dag}+\\widehat{a_{2}^{2}}+...+\\widehat{a_{N}^{\\ast}})^{2}}{2}$. It makes us think that it is more profitable take point which are close to circle, such that $|a_{i}^{2}|$ would be as big as can, but value of $|\\overline{{{a_{1}}}}+\\overline{{{a_{2}}}}+...+\\overline{{{a_{N}^{\\star}}}}|$ as little as can. After that it becomes obvious, that if $N$ is even, than it's enough to take any diameter and place half of points to the start and another half to the finish of it. Now we're trying to formulate our guessians strictly. Let's take an optimal set of points. Let's mark coordinats as $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$.Let's first $N - 1$ points are fixed, and we can move last point - $(x, y)$. In terms of $x, y$ we'd like to maximize $\\textstyle\\sum_{i=1}^{N-1}{\\bigl(}(x-x_{i})^{2}+(y-y_{i})^{2}{\\bigr)}$ We left out all squares without $x, y$. Maximization of this $x, y$ function is equivalent to maximization of $(N-1)x^{2}-2(\\sum x_{i})x+(N-1)y^{2}-2(\\sum y_{i})y\\Leftrightarrow$ $x^{2}-{\\frac{2(\\sum x_{i})x}{N-1}}+y^{2}-{\\frac{(2\\ >y_{i})y}{N-1}}\\Leftrightarrow$ $(x-{\\sum_{N-1}^{\\infty}})^{2}+(y-{\\sum_{N-1}^{\\sim}})^{2}$ So, we've reduced our problem to finding the furthest integer point from $\\left(\\begin{array}{l l}{{\\overline{{y}}}\\end{array}\\vert+y_{2n}^{*}+\\ldots+y_{N}^{*}N_{-1}}\\\\ {{\\overline{{{y}}}=1}}&{{\\overline{{{y}}}=1}}\\end{array}\\right)\\stackrel{\\widehat{y}}{=}\\Longrightarrow\\omega\\omega\\omega\\omega\\omega\\omega\\overline{{{y}}}=1}\\\\ {{\\overline{{{y}}}=1}}\\end{array}\\right)$. Now we can declare: the furthest point is placed at one vertex of convex hull of all integer points inside the circle. Proof. Let $\\left(\\begin{array}{l l}{{\\overline{{y}}}\\rfloor+y_{-2}^{\\prime}+\\mathrm{r}_{+}^{\\prime}N_{-1}}\\\\ {{\\overline{{z}}=1}}&{{\\overline{{N}}=1}}\\end{array}\\right)\\frac{\\sqrt{1+\\rlap y y_{2}+\\mathrm{r}_{+}+\\sqrt{N}_{--1}}{{\\cal M}_{=1}}\\right)$ be a point $T$, and the furthest integer point inside $P$ (convex hull) is $X$(obviously, it placed somewhere in convex hull). Lets extend $TX$ beyond $X$ to intersection with one side of polygon - let it be $AB$, and lets mark point of intersection as $X'$. Clearly $TX'  \\ge  TX$. It's easy to see, that one of angles $\\angle A X^{\\prime}T$ and $\\angle B X^{\\prime}T$ is obtuse, so, according to properties of obtuse triangles on of inequalities holds: $TA  \\ge  TX'  \\ge  TX$ or $TB  \\ge  TX'  \\ge  TX$, so, we can replace $X$ to $A$ or $B$, and distanse $TX$ will increase. So, we can assume, that every point in optimal set belongs to the convex hull. So, solution is check all sets of points from convex hull and check values on this sets. If $R  \\le  30$, then convex hull contains no more than 36 points - it's easy to check with computer. So, brute force will take $O(\\frac{38^{n}}{R^{1}})$ time, and it passes TL easily (depending on realizations and optimizations). For those, who interested in realization of algorithm: at first we place convex hull to some vector(and points become ordered). After that we build recursion function with the next parameters:1) how many points in the set on this iteration 2) vector with points 3) sum $x$-coordinats of points from set 4) sum of squares of $x$- coordinates 5) sum of $y$-coordinates 6) sum of squares of $y$-coordinates. On each iteration we take last point from set, and trying to add all points, starting with this, and finishing on the end of convex hull - it starts new iteration of recursion. Also, we recalculate meaning of cur value in fast way using parameters 3, 4, 5 and 6. On the last iteration, when we took $N$ points, we are comparing value on this set with maximal value. If maximal value is less, than cur value, then $maxvalue = curvalue$, and $bestvector = cursetofpoints$. After recursion we output $maxvalue$ and $bestvector$.",
    "code": "#include<iostream>\n#include<vector>\n#include<queue>\n#include<stack>\nusing namespace std;\n#define lol long long\n \nint N, R;\n \nstruct point\n{\n    int x;\n    int y;\n \n    point(int xx, int yy)\n    {\n        x = xx;\n        y = yy;\n    }\n};\n \nbool inner(point A)\n{\n    return (A.x*A.x + A.y*A.y <= R*R);\n}\n \nvector <point> convex_hull; \n \nint area(point A, point B, point C)\n{\n    int p = B.x - A.x;\n    int q = B.y - A.y;\n \n    int r = C.x - A.x;\n    int l = C.y - A.y;\n \n    return (q*r - p*l);\n}\n \nvoid Init()\n{\n    cin >> N >> R;\n}\n \nvoid Make_Convex_Hull()\n{\n    convex_hull.push_back(point(0, R));\n    \n    while(true)\n    {\n        point cur = convex_hull[convex_hull.size() - 1];\n        --cur.y;\n        \n        while(!inner(point(cur.x + 1, cur.y)))\n            --cur.y;\n \n        while(inner(point(cur.x + 1, cur.y)))\n            ++cur.x;\n \n        if (cur.y == 0)\n            break;\n \n        //cout << cur.x << \" | \" << cur.y << \"\\n\";\n            \n        if (area(convex_hull[convex_hull.size() - 1], cur, point(R, 0)) >= 0)\n            convex_hull.push_back(cur);\n        while(convex_hull.size() >= 3 && area(convex_hull[convex_hull.size() - 3], convex_hull[convex_hull.size() - 2], convex_hull[convex_hull.size() - 1]) <= 0)\n        {\n            convex_hull[convex_hull.size() - 2] = convex_hull[convex_hull.size() - 1];\n            convex_hull.pop_back();\n        }\n            \n    }\n \n    int s = convex_hull.size();\n \n    for(int i = 0; i<s; ++i)\n        convex_hull.push_back(point(convex_hull[i].y, -convex_hull[i].x));\n \n    for(int i = 0; i<s; ++i)\n        convex_hull.push_back(point(-convex_hull[i].x, -convex_hull[i].y));\n \n    for(int i = 0; i<s; ++i)\n        convex_hull.push_back(point(-convex_hull[i].y, convex_hull[i].x));\n \n    //for(int i = 0; i<convex_hull.size(); ++i)\n    //  cout << convex_hull[i].x << \" \" << convex_hull[i].y << \"\\n\";\n}\n \nint maxx = 0;\nint cur = 0;\n \nvector<point> ans;\nvector<point> best;\n \n void Case(int px, int sx, int py, int sy, int iteration, int last)\n{\n    if (iteration < N)\n    {\n        for(int i = last; i<convex_hull.size(); ++i)\n        {\n            int curx = iteration*convex_hull[i].x*convex_hull[i].x - 2*px*convex_hull[i].x + sx;\n            int cury = iteration*convex_hull[i].y*convex_hull[i].y - 2*py*convex_hull[i].y + sy;\n \n                        cur += curx;\n                        cur += cury;\n \n            int dpx = convex_hull[i].x;\n            int dpy = convex_hull[i].y;\n \n            int dsx = convex_hull[i].x*convex_hull[i].x;\n            int dsy = convex_hull[i].y*convex_hull[i].y;\n \n            ans.push_back(convex_hull[i]);\n \n            Case(px + dpx, sx + dsx, py + dpy, sy + dsy, iteration + 1, i);\n \n            cur -= curx;\n            cur -= cury;\n \n            ans.pop_back();\n        }\n    }\n    else\n    {\n        if (maxx < cur)\n        {\n            maxx = cur;\n            best = ans;\n        }\n    }\n}\n \nint main(){\n \n    Init();\n    Make_Convex_Hull();\n \n    Case(0, 0, 0, 0, 0, 0);\n \n    cout << maxx << \"\\n\";\n    \n    for(int i = 0; i<best.size(); ++i)\n        cout << best[i].x << \" \" << best[i].y << \"\\n\";\n \n    return 0;\n \n}",
    "tags": [
      "brute force",
      "geometry",
      "math",
      "sortings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "461",
    "index": "A",
    "title": "Appleman and Toastman",
    "statement": "Appleman and Toastman play a game. Initially Appleman gives one group of $n$ numbers to the Toastman, then they start to complete the following tasks:\n\n- Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.\n- Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.\n\nAfter guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?",
    "tutorial": "First I describe the algorithm, and explain why it works. Sort {$a_{i}$} in non-decreasing order. Then, for $i$-th number, add $(i + 1) * a_{i}$ to the result.(i=1...n-1) For $n$-th number, add $n * a_{n}$ to the result. Actually, when you multiply all numbers by -1,the answer will be the minimal possible value, multiplied by -1. It's Huffman coding problem to find minimal possible value. Solving Huffman coding also can be solved in O($nlogn$) In Huffman coding, push all the numbers to a priority queue. While the size of the queue is larger than 2, delete the minimal and second-minimal element, add the sum of these two to the cost, and push the sum to the queue. Here, since all the numbers are negative, the pushed sum will be remain in the first in the queue. Analyzing this movement will lead to the first algorithm.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "461",
    "index": "B",
    "title": "Appleman and Tree",
    "statement": "Appleman has a tree with $n$ vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.\n\nConsider a set consisting of $k$ $(0 ≤ k < n)$ edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into $(k + 1)$ parts. Note, that each part will be a tree with colored vertices.\n\nNow Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "Fill a DP table such as the following bottom-up: DP[v][0] = the number of ways that the subtree rooted at vertex v has no black vertex. DP[v][1] = the number of ways that the subtree rooted at vertex v has one black vertex. The recursion pseudo code is folloing: DFS(v): DP[v][0] = 1 DP[v][1] = 0 foreach u : the children of vertex v DFS(u) DP[v][1] *= DP[u][0] DP[v][1] += DP[v][0]*DP[u][1] DP[v][0] *= DP[u][0] if x[v] == 1: DP[v][1] = DP[v][0] else: DP[v][0] += DP[v][1] The answer is DP[root][1]. UPD: The above code calculate the DP table while regarding that the vertex v is white (x[v]==0) in the foreach loop. After that the code thinks about the color of vertex v and whether we cut the edge connecting vertex v and its parent or not in \"if x[v] == 1: DP[v][1] = DP[v][0] else: DP[v][0] += DP[v][1]\".",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "461",
    "index": "C",
    "title": "Appleman and a Sheet of Paper",
    "statement": "Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions $1 × n$. Your task is help Appleman with folding of such a sheet. Actually, you need to perform $q$ queries. Each query will have one of the following types:\n\n- Fold the sheet of paper at position $p_{i}$. After this query the leftmost part of the paper with dimensions $1 × p_{i}$ must be above the rightmost part of the paper with dimensions $1 × ([current width of sheet] - p_{i})$.\n- Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance $l_{i}$ from the left border of the current sheet of paper and the other at distance $r_{i}$ from the left border of the current sheet of paper.\n\nPlease look at the explanation of the first test example for better understanding of the problem.",
    "tutorial": "For each first type queries that p_i > (the length of the paper) - p_i, you should express the operation in another way: not fold the left side of the paper but fold the right side of the paper. After such query you need to think as the paper is flipped. Let's define count[i] as the number of papers piled up at the segment [i,i+1] (absolute position). For each query of first type you can update each changed count[i] naively. Use BIT or segment tree for count[i] because you can answer each second type queries in O(log n). The complexity of a first type query is O((the decrement of the length of the paper) log n) so total complexity of a first type query is O(n log n).",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "461",
    "index": "D",
    "title": "Appleman and Complicated Task",
    "statement": "Toastman came up with a very complicated task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?\n\nGiven a $n × n$ checkerboard. Each cell of the board has either character 'x', or character 'o', or nothing. How many ways to fill all the empty cells with 'x' or 'o' (each cell must contain only one character in the end) are there, such that for each cell the number of adjacent cells with 'o' will be even? Find the number of ways modulo $1000000007$ $(10^{9} + 7)$. Two cells of the board are adjacent if they share a side.",
    "tutorial": "First, we ignore the already drawn cell and dependence of cells. If we decide the first row, then the entire board can decided uniquely. We call 'o' is 1, and 'x' is 0. Then, a[i][j] = a[i-2][j] xor a[i-1][j-1] xor a[i-1][j+1] For example, I'll explain n=5 case. Each column of first row is a, b, c, d, and e. \"ac\" means a xor c. Each character affects the following cells (denoted 'o'). Generally we can prove the dependence that a[0][k] affects a[i][j] if k<=i+j<=2(n-1)-k and |i-j|<=k and k%2==(i+j)%2. ... (*) We can separate the problems by (i+j) is odd or even. Each (i,j), we can get the range of k that affects the cell (i,j) by using formula (*). So the essence of this problem is that \"There is a sequence with n integers, each of them is 0 or 1. We know some (i,j,k) where a[i]^a[i+1]^...^a[j]=k. How many possible this sequences are there?\" We can solve this problem by using union-find. At first, there is n*2 vertices. If k is 1, we'll connect (i*2,(j+1)*2+1) and (i*2+1,(j+1)*2), if k is 0, we'll connect (i*2,(j+1)*2) and (i*2+1,(j+1)*2+1) (note that i<=j). If both i*2 and i*2+1 are in the same set for any i, the answer is 0. Otherwise the answer is 2^((the number of sets-2)/2).",
    "tags": [
      "dsu",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "461",
    "index": "E",
    "title": "Appleman and a Game",
    "statement": "Appleman and Toastman like games. Today they play a game with strings with the following rules. Firstly Toastman tells Appleman two strings $s$ and $t$ both consisting only of letters 'A', 'B', 'C', 'D'. Then Appleman must build string $s$ as quickly as possible. Initially he has empty string, and in one second he can append to end of the current string any contiguous substring of $t$.\n\nNow, Toastman and Appleman are beginning to play the game. Toastman has already told string $t$ to Appleman, but he hasn't come up with string $s$ yet. Toastman only thinks, that he should choose string $s$ consisting of $n$ characters. Of course, he wants to find the worst string for Appleman (such string, that Appleman will spend as much time as possible during the game). Tell Toastman, how much time will Appleman spend during the game if Toastman finds the worst string for him. You can assume that Appleman plays optimally, therefore he builds any string $s$ in minimal possible time.",
    "tutorial": "Let C be the number of characters(here, C=4) Given string S, the way to achieve minimum steps is as follows: Append one of the longest substring of T that fits current position of string S. Appending a not-longest substring can be replaced by appending longest substring and shortening the next substring appended. Let dp[K][c1][c2] be defined as : the minimum length of string that can be obtained by appending a string K times and that starts by character c1 and whose next character is c2. Note that next character is not counted in the length. dp[1] can be calculated as follows: For every string of length L expressed by C characters, if the string is not included in T, update the dp table as dp[1][the string's first character][its last character]=min(dp[1][its first character][its last character],L-1) For any (c1,c2), dp[1][c1][c2] is smaller than or equal to log_C(T+1)+2 (since the kind of strings of length log_C(T+1)+2 that start by c1 and end by c2 is equals to T+1). Therefore for L=1...log(T+1)+2, try all the strings as described above. Also we can use trie that contains all substrings of T of length log_C(T+1)+2, and find what can't be described as a substring of T by one step. Since dp[k+1][c1][c2]=min(dp[k][c1][c3]+dp[1][c3][c2] | c3=1...C), we can use matrix multiplication to get dp[K]. For a integer K, if there is (c1,c2) such that dp[K][c1][c2]<|S|, the answer is greater than K. Otherwise,the answer is smaller than or equal to K. Since answer is bigger or equal to 1 and smaller or equal to |S|, we can use binary search to find the ansewr. O(T*((log T)^2+C^2)+C^3(log |S|)^2)",
    "tags": [
      "binary search",
      "shortest paths",
      "strings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "462",
    "index": "A",
    "title": "Appleman and Easy Task",
    "statement": "Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?\n\nGiven a $n × n$ checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.",
    "tutorial": "This is a simple implementation problem. You can solve by searching adjacent cells of every cell.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "462",
    "index": "B",
    "title": "Appleman and Card Game",
    "statement": "Appleman has $n$ cards. Each card has an uppercase letter written on it. Toastman must choose $k$ cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card $i$ you should calculate how much Toastman's cards have the letter equal to letter on $i$th, then sum up all these quantities, such a number of coins Appleman should give to Toastman.\n\nGiven the description of Appleman's cards. What is the maximum number of coins Toastman can get?",
    "tutorial": "This is simple greedy problem, but it seemed to be reading-hard. The statement says, \"Choose K cards from N cards, the score of each card is (the number of cards which has the same character in K cards. (not in N cards)\" It is clear that this total score is (the number of 'A' in K cards)^2 + (the number of 'B' in K cards)^2 + ... + (the number of 'Z' in K cards)^2 This value will be maximized by the simple greedy algorithm, take K cards from most appearred character in N cards, the second most appearred character in N cards, and so on.",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "463",
    "index": "A",
    "title": "Caisa and Sugar",
    "statement": "Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.\n\nUnfortunately, he has just $s$ dollars for sugar. But that's not a reason to be sad, because there are $n$ types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed $99$, because each seller maximizes the number of dollars in the change ($100$ cents can be replaced with a dollar).\n\nCaisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.",
    "tutorial": "This is a simple implementation problem.",
    "code": "#include <iostream>\n#include <cstdio>\nusing namespace std;\n\nint main(){\n    #ifndef ONLINE_JUDGE\n        freopen(\"date.in\",\"r\",stdin);\n        freopen(\"date.out\",\"w\",stdout);\n    #endif\n    int n, s;\n    cin.sync_with_stdio(false);\n    cin >> n >> s;\n    int sol = 100;\n    bool ok = 0;\n    for(int i = 1;i <= n; ++i){\n        int x, y;\n        cin >> x >> y;\n        if(x < s){\n            if(y)\n                sol = min(sol,y);\n        }\n        if(x < s || (x==s && y==0))\n            ok = 1;\n    }\n    if(!ok)\n        cout<<\"-1\\n\";\n    else\n        cout<<100-sol<<\"\\n\";\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "463",
    "index": "B",
    "title": "Caisa and Pylons",
    "statement": "Caisa solved the problem with the sugar and now he is on the way back to home.\n\nCaisa is playing a mobile game during his path. There are $(n + 1)$ pylons numbered from $0$ to $n$ in this game. The pylon with number $0$ has zero height, the pylon with number $i$ $(i > 0)$ has height $h_{i}$. The goal of the game is to reach $n$-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as $k$) to the next one (its number will be $k + 1$). When the player have made such a move, its energy increases by $h_{k} - h_{k + 1}$ (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.\n\nInitially Caisa stand at $0$ pylon and has $0$ energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?",
    "tutorial": "We have to use greedy method. Start from the first element and pass all the elements in order(also update by the energy).When energy < 0, add abs(energy) to solution and energy becomes 0 or we can find the answer by binary search.",
    "code": "#include <iostream>\n#include <cstdio>\nusing namespace std;\n\nint main()\n{\n    #ifndef ONLINE_JUDGE\n        freopen(\"date.in\",\"r\",stdin);\n        freopen(\"date.out\",\"w\",stdout);\n    #endif\n    int  x = 0, y, n, sol = 0,energy = 0;\n    cin >> n;\n    for(int i = 1;i <= n; ++i)\n    {\n        cin >> y;\n        energy += x-y;\n        if(energy < 0){\n            sol += -energy;\n            energy = 0;\n        }\n        x = y;\n    }\n    cout<<sol<<\"\\n\";\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "463",
    "index": "C",
    "title": "Gargari and Bishops",
    "statement": "Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.\n\nHe has a $n × n$ chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number $x$ written on it, if this cell is attacked by one of the bishops Gargari will get $x$ dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.\n\nWe assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).",
    "tutorial": "We preprocess the sum for all the diagonals(principals and secondary diagonals) in two arrays(so that for every element $i$,$j$ we can find sum of elements which are attacked in O(1) time).Also for avoiding the intersection,we need to find two cells so that for one the sum of row and column is even and for the other one the sum of row and column is odd.Finally,we analyze every cell ,we see if the sum of row and column is even or odd,and update that two positions(solutions).",
    "code": "#include <iostream>\n#include <cstdio>\n\nusing namespace std;\nconst int NMAX = 2014;\nlong long d1[2*NMAX], d2[2*NMAX], sol[2];\npair < int , int > v[2];\nint a[NMAX][NMAX];\ninline void Update(const int c,const int i,const int j,const long long val){\n    if(val > sol[c]){\n        sol[c] = val;\n        v[c].first = i;\n        v[c].second = j;\n    }\n}\nint main(){\n    #ifndef ONLINE_JUDGE\n        freopen(\"date.in\",\"r\",stdin);\n        freopen(\"date.out\",\"w\",stdout);\n    #endif\n    cin.sync_with_stdio(false);\n    int n;\n    cin >> n;\n    sol[0] = sol[1] = -1; \n    for(int i = 1;i <= n; ++i)\n        for(int j = 1;j <= n; ++j){\n            int x;\n            cin >> a[i][j];\n            d1[i+j] += a[i][j];\n            d2[i-j+n] += a[i][j];\n        }\n    for(int i=1;i<=n;++i)\n        for(int j=1;j<=n;++j)\n            Update((i+j)&1,i,j,d1[i+j]+d2[i-j+n]-a[i][j]);\n    cout<<sol[0]+sol[1]<<\"\\n\";\n    if(v[0] > v[1])\n        swap(v[0],v[1]);\n    cout<<v[0].first<<\" \"<<v[0].second<<\" \";\n    cout<<v[1].first<<\" \"<<v[1].second<<\"\\n\";\n    return 0;\n}",
    "tags": [
      "greedy",
      "hashing",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "463",
    "index": "D",
    "title": "Gargari and Permutations",
    "statement": "Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found $k$ permutations. Each of them consists of numbers $1, 2, ..., n$ in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?\n\nYou can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem",
    "tutorial": "We can build a directed acyclic graph with $n$ nodes.If $j$ is after $i$ in all vectors then we add in graph edge ($i$,$j$).Now we have to find the longest path in this graph. Another way is using dp.",
    "code": "#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nconst int NMAX = 1010;\n\nint N, K, V[10][NMAX], Pos[10][NMAX], Best[NMAX], Ans;\nvector<int> G[NMAX];\nbool Used[NMAX];\n\nvoid DFS(int Node)\n{\n    Used[Node] = 1;\n    for(int i = 0; i < G[Node].size(); ++ i)\n    {\n        if(!Used[G[Node][i]])\n            DFS(G[Node][i]);\n        Best[Node] = max(Best[Node], Best[ G[Node][i] ] + 1);\n    }\n    Best[Node] = max(Best[Node], 1);\n    Ans = max(Ans, Best[Node]);\n}\n\nint main()\n{\n   // freopen(\"d.in\", \"r\", stdin);\n   // freopen(\"d.out\", \"w\", stdout);\n\n    scanf(\"%i %i\", &N, &K);\n    for(int i = 1; i <= K; ++ i)\n        for(int j = 1; j <= N; ++ j)\n        {\n            scanf(\"%i\", &V[i][j]);\n            Pos[i][ V[i][j] ] = j;\n        }\n\n    for(int i = 1; i <= N; ++ i)\n        for(int j = 1; j <= N; ++ j)\n        {\n            if(i == j) continue;\n            bool OK = 1;\n            for(int k = 1; k <= K; ++ k)\n                if(Pos[k][i] >= Pos[k][j])\n                    OK = 0;\n            if(OK) G[i].push_back(j);\n        }\n\n    for(int i = 1; i <= N; ++ i)\n        if(!Used[i])\n            DFS(i);\n\n    printf(\"%i\\n\", Ans);\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "463",
    "index": "E",
    "title": "Caisa and Tree",
    "statement": "Caisa is now at home and his son has a simple task for him.\n\nGiven a rooted tree with $n$ vertices, numbered from $1$ to $n$ (vertex $1$ is the root). Each vertex of the tree has a value. You should answer $q$ queries. Each query is one of the following:\n\n- Format of the query is \"1 $v$\". Let's write out the sequence of vertices along the path from the root to vertex $v$: $u_{1}, u_{2}, ..., u_{k}$ $(u_{1} = 1; u_{k} = v)$. You need to output such a vertex $u_{i}$ that $gcd(value of u_{i}, value of v) > 1$ and $i < k$. If there are several possible vertices $u_{i}$ pick the one with maximum value of $i$. If there is no such vertex output -1.\n- Format of the query is \"2 $v$ $w$\". You must change the value of vertex $v$ to $w$.\n\nYou are given all the queries, help Caisa to solve the problem.",
    "tutorial": "We use an array of dynamic stacks for every prime factor.We start a DFS from node 1.For node 1 we decompose its value in prime factors and push it to every prime factor's stack.To answer the question for $x$,we need to see the $y$ ($y$ belongs to the chain from 1 to $x$) that has a common prime factor with x,so the stacks will help us to see the earliest update(so the nearest $y$). For every $x$ ,we decompose $x$ to prime factors,look in the array and see the earliest update of the prime factors' stacks(if exists,of course). Also when we get back to fathers recursively,we need to pop from the prime factors' stacks. For every update we have to start dfs again.",
    "code": "#include <vector>\n#include <cstdio>\n#include <iostream>\n#include <algorithm>\n#include <stack>\n#include <bitset>\nusing namespace std;\nconst int NMAX  = 100004;\nconst int VALMAX = 2e6;\nvector < int > Tree[NMAX];\nint value[NMAX], niv[NMAX] , answer[NMAX];\nbitset < VALMAX+6> viz;\nint prime[2*NMAX],pos[6+VALMAX];\nstack < int > St[2*NMAX]; \ninline void Eratosthenes(){\n    prime[++prime[0]] = 2; \n    pos[2] = 1;\n    for(int i = 3;i <= VALMAX;i += 2)\n        if(!viz[i]){\n            prime[++prime[0]] = i;\n            pos[i] = prime[0];\n            for(long long j = 1LL*i*i;j <= VALMAX; j += 2*i)\n                viz[j] = 1;\n        }\n}\ninline void DFS(const int node,const int father){\n    vector < int > v;\n    int d = 2,step = 1;\n    int x = value[node];\n    answer[node] = 0;\n    while(d*d <= x){\n        if(x%d==0){\n            if(!St[pos[d]].empty()){\n                int y = St[pos[d]].top();\n                if(niv[y] > niv[answer[node]])\n                    answer[node] = y;\n            }\n            v.push_back(pos[d]);\n            St[pos[d]].push(node);\n            while(x%d==0)\n                x /= d;\n        }\n        ++step;\n        d = prime[step];\n    }\n    if(x > 1){\n        if(!St[pos[x]].empty()){\n            int y = St[pos[x]].top();\n            if(niv[y] > niv[answer[node]])\n                 answer[node] = y;\n        }\n        v.push_back(pos[x]);\n        St[pos[x]].push(node);\n    }\n    for(vector < int > ::iterator it = Tree[node].begin(); it != Tree[node].end(); ++it)\n        if(*it!=father){\n            niv[*it] = niv[node] + 1;\n            DFS(*it,node);\n        }\n    for(vector < int > ::iterator it = v.begin(); it != v.end() ; ++it)\n        St[*it].pop();\n    v.clear();\n}\n\nint main(){\n    #ifndef ONLINE_JUDGE\n        freopen(\"date.in\",\"r\",stdin);\n        freopen(\"date.ok\",\"w\",stdout);\n    #endif\n    cin.sync_with_stdio(false);\n    Eratosthenes();\n    int n, m;\n    cin >> n >> m;\n    for(int i = 1;i <= n; ++i)\n        cin >> value[i];\n    for(int i = 1;i < n; ++i){\n        int x, y;\n        cin >> x >> y;\n        Tree[x].push_back(y);\n        Tree[y].push_back(x);\n    }\n    niv[1] = 1;\n    DFS(1,-1);\n    while(m--){\n        int operation, x, y;\n        cin >> operation >> x;\n        if(operation == 1){\n            if(answer[x] > 0)\n                cout<<answer[x]<<\"\\n\";\n            else\n                cout<<\"-1\\n\";\n        }\n        else{\n            cin >> y;\n            value[x] = y;\n            DFS(1,-1);\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "464",
    "index": "A",
    "title": "No to Palindromes!",
    "statement": "Paul \\underline{hates} palindromes. He assumes that string $s$ is \\underline{tolerable} if each its character is one of the first $p$ letters of the English alphabet and $s$ doesn't contain any palindrome contiguous substring of length 2 or more.\n\nPaul has found a tolerable string $s$ of length $n$. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.",
    "tutorial": "If string $s$ contains a non-trivial palindromic substring $w$, then it must contain palindromic substring of length 2 or 3 (for instance, center of $w$). Therefore the string is tolerable iff no adjacent symbols or symbols at distance 1 are equal. Now for the lexicographically next tolerable string $t$. $t$ is greater than $s$, so they have common prefix of some size (maybe zero) and the next symbol is greater in $t$ than in $s$. This symbol should be as right as possible to obtain minimal possible $t$. For some position $i$ we can try to increment $s_{i}$ and ensure it's not equal to $s_{i - 1}$ or $s_{i - 2}$. If we find some way to do this, the suffix can always be filled correctly if only $p  \\ge  3$, as at most two symbols are forbidden at every moment. Every symbol from suffix should be as small as possible not to make conflicts. So, a greedy procedure or some kind of clever brute-force can be implemented to solve the problem in $O(n)$. Cases $p = 1$ or $2$ are easy, as only strings of length at most 1, and at most 2 respectively fit. This is an application on general approach to generate next lexicographical something: try to increment rightmost position so that suffix can be filled up in some way, then fill the suffix in least possible way.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "464",
    "index": "B",
    "title": "Restore Cube ",
    "statement": "Peter had a cube with non-zero length of a side. He put the cube into three-dimensional space in such a way that its vertices lay at integer points (it is possible that the cube's sides are not parallel to the coordinate axes). Then he took a piece of paper and wrote down eight lines, each containing three integers — coordinates of cube's vertex (a single line contains coordinates of a single vertex, each vertex is written exactly once), put the paper on the table and left. While Peter was away, his little brother Nick decided to play with the numbers on the paper. In one operation Nick could swap some numbers \\textbf{inside a single line} (Nick didn't swap numbers from distinct lines). Nick could have performed any number of such operations.\n\nWhen Peter returned and found out about Nick's mischief, he started recollecting the original coordinates. Help Peter restore the original position of the points or else state that this is impossible and the numbers were initially recorded incorrectly.",
    "tutorial": "There are several ways to solve this problem. We'll describe the most straightforward one: we can generate all possible permutations of coordinates of every point and for every combination check whether given point configuration form a cube. However, number of configurations can go up to $(3!)^{8} > 10^{6}$, so checking should work quite fast. One way to check if the points form a cube is such: find minimal distance between all pairs of points, it should be equal to the side length $l$. Every vertex should have exactly three other points at distance $l$, and all three edges should be pairwise perpendicular. If these condition are met at every point, then configuration is a cube as there is no way to construct another configuration with these properties. This procedure performs roughly $8^{2}$ operations for every check, which is fast enough. There are even more efficient ways of cube checking exploiting various properties of cube. There are various optimizations to ensure you fit into time limit. For instance, applying the same permutation to coordinates of all points keeps every property of the cube, therefore we can fix order of coordinates for one point and permute all other. This single trick speeds up the algorithm 6 times, which allows some less efficient programs to be accepted.",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 2000
  },
  {
    "contest_id": "464",
    "index": "C",
    "title": "Substitutes in Number",
    "statement": "Andrew and Eugene are playing a game. Initially, Andrew has string $s$, consisting of digits. Eugene sends Andrew multiple queries of type \"$d_{i} → t_{i}$\", that means \"replace all digits $d_{i}$ in string $s$ with substrings equal to $t_{i}$\". For example, if $s = 123123$, then query \"$2 → 00$\" transforms $s$ to $10031003$, and query \"$3 → $\" (\"replace 3 by an empty string\") transforms it to $s = 1212$. After all the queries Eugene asks Andrew to find the remainder after division of number with decimal representation equal to $s$ by $1000000007 (10^{9} + 7)$. When you represent $s$ as a decimal number, please ignore the leading zeroes; also if $s$ is an empty string, then it's assumed that the number equals to zero.\n\nAndrew got tired of processing Eugene's requests manually and he asked you to write a program for that. Help him!",
    "tutorial": "It is quite diffcult to store the whole string after each query as its length grows exponentially and queries may change it dramatically. The good advice is: if you can't come up with a solution for a problem, try solving it from the other end. =) Suppose we know for some sequence of queries that digit $d$ will turn into string $t_{d}$ for every digit. Then string $s = d_{1}... d_{n}$ will turn into $t_{d1} + ... + t_{dn}$ (+ for concatenation). Denote $v(s)$ numeric value of $s$. Then $v(s)$ can be expressed as $v(t_{dn}) + 10^{|dn|}(v(t_{dn - 1}) + 10^{|dn - 1|}(...))$. So $v(s)$ can be computed if we know $m_{d} = v(t_{d})$ and $s_{d} = 10^{|td|}$ for all $d$. As we need answer modulo $P = 10^{9} + 7$ we can store these numbers modulo $P$. Now prepend some new query $d_{i}  \\rightarrow  t_{i}$ to given sequence. How will $m_{d}$ and $s_{d}$ change? Clearly, for all $d  \\neq  d_{i}$ these numbers won't change, and for $d_{i}$ they can be computed according to the rule above. This recounting is done in $O(|t_{i}|)$ time. After adding all queries, find answer for $s$ using the same procedure in $O(|s|)$ time. Finally, our time complexity is $O(|s|+\\sum|t_{i}|)$. The code for this problem pretty much consists of the above formula, so implementation is as easy as it gets once you grasp the idea. =)",
    "tags": [
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "464",
    "index": "D",
    "title": "World of Darkraft - 2",
    "statement": "Roma found a new character in the game \"World of Darkraft - 2\". In this game the character fights monsters, finds the more and more advanced stuff that lets him fight stronger monsters.\n\nThe character can equip himself with $k$ distinct types of items. Power of each item depends on its level (positive integer number). Initially the character has one $1$-level item of each of the $k$ types.\n\nAfter the victory over the monster the character finds exactly one new randomly generated item. The generation process looks as follows. Firstly the type of the item is defined; each of the $k$ types has the same probability. Then the level of the new item is defined. Let's assume that the level of player's item of the chosen type is equal to $t$ at the moment. Level of the new item will be chosen uniformly among integers from segment [$1$; $t + 1$].\n\nFrom the new item and the current player's item of the same type Roma chooses the best one (i.e. the one with greater level) and equips it (if both of them has the same level Roma choses any). The remaining item is sold for coins. Roma sells an item of level $x$ of any type for $x$ coins.\n\nHelp Roma determine the expected number of earned coins after the victory over $n$ monsters.",
    "tutorial": "This problem required some skill at probabilities handling, but other than that it's quite simple too. Denote number of earned coins as $X$, and number of earned coins from selling items of type $i$ as $X_{i}$. Clearly $X = X_{1} + ... + X_{k}$, and $EX = EX_{1} + ... + EX_{k}$ (here $EX$ is expectation of $X$). As all types have equal probability of appearance, all $X_{i}$ are equal, so $EX = kEX_{1}$. Now to find $EX_{1}$. If we look only at the items of one type, say, 1, items generation looks like this: with probability $1-{\\frac{1}{k}}$ we get nothing, and with probability $\\textstyle{\\frac{1}{k}}$ we get out item with level distributed as usual. Denote $d_{n, t}$ expectation of earned money after killing $n$ monsters if we have an item of level $t$ at the start. Clearly, $d_{0, t} = 0$ (we have no opportunity to earn any money), and $d_{n,t}=\\frac{1}{k}\\sum_{j=1}^{t+1}\\frac{1}{t+1}(d_{n-1,m a x(j,t)}+m i n(j,t))+\\frac{k-1}{k}d_{n-1,t}$, which is equal to ${\\frac{1}{k(t+1)}}(t d_{n-1,t}+\\sum_{j=1}^{t}j+d_{n-1,t+1}+t)+{\\frac{k_{-1}}{k}}d_{n-1,t}$ = $\\frac{1}{k(t+1)}(t d_{n-1,t}+d_{n-1,t+1}+t(t+3)/2)+\\frac{k-1}{k}d_{n-1,t}$. To get the answer note that $EX_{1} = d_{n, 1}$. The sad note is that this DP has $ \\Omega (n^{2})$ states, which is too much for $n\\sim10^{5}$. Maybe if we cut off some extremely-low-probability cases we can do better? For instance, it is clear that probability of upgrading an item descreases with its level, so apparently it does not get very high. We know that expected number of tries before first happening of event with probability $p$ in a series of similar independent events is $1 / p$. Therefore, expected number of monsters we have to kill to get item of level $T$ is $2k+3k+\\cdot\\cdot\\cdot+T k\\sim k T^{2}/2$. So, in common case our level can get up to about $\\sqrt{2n/k}$, which does not exceed $500$ in our limitations. We would want to set such bound $B$ that ignoring cases with $t > B$ would not influence our answer too much. That can be done with rigorous bounding of variance of $T$ and applying some bounding theorem, or with an empirical method: if we increase the bound and the answer doesn't visibly change, then this bound is fine. It turns out $B  \\ge  700$ is good enough for achieving demanded precision. Thus solution with $O(n{\\sqrt{n}})$ complexity is obtained (here we assert that $B\\sim C{\\sqrt{n}}$, and constant $C$ is buried in the big O).",
    "tags": [
      "dp",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "464",
    "index": "E",
    "title": "The Classic Problem",
    "statement": "You are given a weighted undirected graph on $n$ vertices and $m$ edges. Find the shortest path from vertex $s$ to vertex $t$ or else state that such path doesn't exist.",
    "tutorial": "This seems to be a simple graph exercise, but the problem is with enormous weights of paths which we need to count and compare with absolute precision to get Dijkstra working. How do we do that? The fact that every edge weight is a power of two gives an idea that we can store binary representation of path value as it doesn't change much after appending one edge. However, storing representations explicitly for all vertices is too costly: the total number of 1's in them can reach $ \\Omega (nd)$ ($d$ is for maximal $x_{i}$), which doesn't fit into memory even with bit compression woodoo magic. An advanced data structure is needed here which is efficient in both time and memory. The good choice is a persistent segment tree storing bit representation. Persistent segment tree is pretty much like the usual segment tree, except that when we want to change the state of some node we instead create a new node with links to children of old node. This way we have some sort of ''version control'' over tree: every old node is present and available for requests as its subtree can never change. Moreover, all queries are still processed in $O(\\log n)$ time, but can create up to $O(\\log n)$ new nodes. What queries do we need? Adding $2^{x}$ to binary number can be implemented as finding nearest most significant $0$ to $x$-th bit, setting it to $1$ and assigning $0$'s to all the positions in between. Usual segment tree with lazy propagation can do it, so persistent tree is able to do it as well. Comparing two numbers can be done as follows: find the most singificant bit which differs in two numbers, then number with $0$ in this bit is smaller; if no bits differ, then numbers are clearly equal. That can be done in $O(\\log n)$ if we store hashes of some sort in every node and perform a parallel binary search on both trees. Time and memory limits were very generous so you could store as many different hashes as you wanted to avoid collisions. That concludes the general idea. Now we use this implementation of numbers as a black-box for Dijkstra algorithm. Every operation on numbers is now slowed by a factor of $O(\\log d)$, so our solution has $O(m\\log n\\log d)$ complexity. However, great caution is needed to achieve a practical solution. First of all, in clueless implementation comparison of two \"numbers\" may require $O(\\log d)$ additional memory as we must perform \"push\" operation as we descend. $O(m\\log n\\log d)$ memory is too much to fit even in our generous ML. There are plenty of ways to avoid this, for instance, if we want to push the value from node to children, we actually know that the whole segment consists of equal values and can answer the query right away. I would like to describe a clever trick which optimizes both time and memory greatly and also simplifies implementation. It allows to get rid of lazy propagation completely. Here it comes: initially build two trees containing only $0$'s and only $1$'s respectively. Now suppose we want to assign some value ($0$, for instance) on a segment and some tree node completely lies inside of query segment. Instead of creating a new node with a propagation mark, we can replace the node with corresponding node from tree filled with $0$. This way only $\\sim\\log d$ new nodes are created on every query (which is impossible to achieve with any kind of propagation which would require at least $\\sim2\\log d$), and also nodes need to store less information and become lighter this way. Also, no \"push\" procedure is required now.",
    "tags": [
      "data structures",
      "graphs",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "465",
    "index": "A",
    "title": "inc ARG",
    "statement": "Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of $n$ bits. These bits are numbered from $1$ to $n$. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the $n$-th bit.\n\nNow Sergey wants to test the following instruction: \"add $1$ to the value of the cell\". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.\n\nSergey wrote certain values ​​of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?",
    "tutorial": "If we add 1 to a number, its binary representation changes in a simple way: all the least significant $1$'s change to $0$'s, and the single following $0$ changes to $1$. It suffices to find the length of largest suffix which contains only $1$'s, suppose its length is $l$. Then the answer is $l + 1$ except for the case when all the string consists of $1$, when the answer is $l$.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "465",
    "index": "B",
    "title": "Inbox (100500)",
    "statement": "Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.\n\nAlexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations:\n\n- Move from the list of letters to the content of any single letter.\n- Return to the list of letters from single letter viewing mode.\n- In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.\n\nThe program cannot delete the letters from the list or rearrange them.\n\nAlexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?",
    "tutorial": "Optimal strategy is as follows: for every segment of consecutive $1$'s open the first letter in segment, scroll until the last letter in segment, if there are more unread letters left, return to list. It is easy to show that we can not do any better: observe the moment we read the last letter from some segment of consecutive $1$'s. There are no adjacent unread letters now, so we either have to scroll to some read letter or return to list of letters, either way we make an operation which does not result in reading an unread letter, so every segment (except for the last) must yield at least one such operation.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "466",
    "index": "A",
    "title": "Cheap Travel",
    "statement": "Ann has recently started commuting by subway. We know that a one ride subway ticket costs $a$ rubles. Besides, Ann found out that she can buy a special ticket for $m$ rides (she can buy it several times). It costs $b$ rubles. Ann did the math; she will need to use subway $n$ times. Help Ann, tell her what is the minimum sum of money she will have to spend to make $n$ rides?",
    "tutorial": "Solution of this problem is based on two claims: - If $m \\cdot a  \\le  b$ then there is no point to buy a ride ticket. - Sometimes it is better to buy summary more ride tickets for amount of rides than we need. If we receive profits bying ride tickets then number of such ones will be $x=\\lfloor{\\frac{n}{m}}\\rfloor$. For the remain $n - m \\cdot x$ rides we must choose the best variant: to buy separate ticket for each ride, or to buy ride ticket and use it not fully. Complexity: $O(1)$",
    "code": "#include <iostream>\n#include <math.h>\n \nusing namespace std;\n \nint main()\n{\n    int n, m, a, b;\n    \n    cin >> n >> m >> a >> b;\n    if (m * a <= b)\n        cout << n * a << \"\\n\";\n    else \n        cout << (n/m) * b + min((n%m) * a, b) << \"\\n\";\n \n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "466",
    "index": "B",
    "title": "Wonder Room",
    "statement": "The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a $a × b$ square meter wonder room. The caretaker wants to accommodate exactly $n$ students there. But the law says that there must be at least 6 square meters per student in a room (that is, the room for $n$ students must have the area of at least $6n$ square meters). The caretaker can enlarge any (possibly both) side of the room by an arbitrary positive integer of meters. Help him change the room so as all $n$ students could live in it and the total area of the room was as small as possible.",
    "tutorial": "Let's assume that $a  \\le  b$. First of all, let's consider the situation when we can already accommodate all the students. If $6 \\cdot n  \\le  a \\cdot b$ then answer is $a \\cdot b$ $a$ $b$. Otherwise, we have to increase one of the walls(maybe, both). Let's do it in the following way: iterate the size of the smallest wall $new_{a}$ ($a\\leq n e w_{a}\\leq\\left|{\\sqrt{6\\cdot n}}\\right|$ ), after that we can calculate the size of another wall as $m e w_{b}=\\textstyle\\bigcap_{n e w a}^{6\\cdots n}\\N$. For all this $new_{a}$ and $new_{b}$ if $b  \\le  new_{b}$ we choose such a pair that has the smallest area of a room. Obviously to undestrand, that there is no point to consider $n e w_{a}>\\lceil{\\sqrt{6\\cdot n}}\\rceil$ because we can decrease it and receive room of smaller area when we know that $6\\cdot n\\leq([{\\sqrt{6\\cdot n}}])^{2}\\leq n e w_{a}\\cdot n e w_{b}$. Complexity: $O({\\sqrt{n}})$",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint main()\n{\n    ios::sync_with_stdio(0);\n    long long n, a, b;\n \n    cin >> n >> a >> b;\n    if (6*n <= a*b)\n        cout << a*b << \"\\n\" << a << \" \" << b << \"\\n\";\n    else {\n        bool f = 0;\n        if (a > b)\n        {\n            swap(a, b);\n            f = 1;\n        }\n        \n        long long SQ = 1e18, a1, b1, tmpb;\n        for(long long i = a; i*i <= 6*n; ++i) {\n            tmpb = 6*n / i;\n            if (tmpb * i < 6*n) tmpb++;\n            \n            if (tmpb < b) continue;\n            \n            if (tmpb * i < SQ) {\n                SQ = tmpb * i;\n                a1 = i;\n                b1 = tmpb;\n            }\n        }\n        \n        if (f)\n            swap(a1, b1);\n        \n        cout << SQ << \"\\n\" << a1 << \" \" << b1 << \"\\n\";\n    }\n \n    return 0;\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "466",
    "index": "C",
    "title": "Number of Ways",
    "statement": "You've got array $a[1], a[2], ..., a[n]$, consisting of $n$ integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.\n\nMore formally, you need to find the number of such pairs of indices $i, j$ $(2 ≤ i ≤ j ≤ n - 1)$, that $\\sum_{k=1}^{i-1}a_{k}=\\sum_{k=i}^{j}a_{k}$.",
    "tutorial": "First of all, notice that if sum of all elements is equal $S$ then sum of each of three parts is equal $\\frac{\\mathrm{S}}{\\mathrm{s}}$. Therefore, if $S$ is not divided by $3$ - then answer is $0$. Otherwise, let's iterate the end of first part $i$ ($1  \\le  i  \\le  n - 2$) and if sum of 1..i elements is equal $\\frac{\\mathrm{S}}{\\mathrm{s}}$ then it means that we have to add to the answer the amount of such $j$ ($i + 1 < j$) that the sum of elements from $j$-th to $n$-tn also equals $\\frac{\\mathrm{S}}{\\mathrm{s}}$. Let's create an array cnt[], where $cnt[i]$ equals 1, if the sum of elements from $i$-th to $n$-th equals $\\frac{\\mathrm{S}}{\\mathrm{s}}$ and 0 - otherwise. Now, to calculate the answer we have to find the sum cnt[j] + cnt[j+1] + ... + cnt[n] faster then O(n). There are a lot of required ways to do this, but the easiest one is to create a new additional array sums[] where in $j$-th element will be cnt[j] + cnt[j+1] + ... + cnt[n]. It is easy to calculate in such way: sums[n] = cnt[n], sums[i] = sums[i+1] + cnt[i] (i < n). Thus, we receive very simple solution: for each prefix of initial array 1..i with the sum that equals $\\frac{\\mathrm{S}}{\\mathrm{s}}$ we need to add to the answer sums[i+2]. Complexity: $O(n)$",
    "code": "#include <iostream>\n#include <math.h>\n \nusing namespace std;\n \nint a[1000010];\nlong long cnt[1000010];\n \nint main()\n{\n    ios::sync_with_stdio(0);\n    int n;\n    cin >> n;\n    long long s = 0;\n    for(int i = 0 ; i < n ; ++i)\n    {\n        cin >> a[i];\n        s += a[i];\n    }\n    if (s % 3 != 0)\n        cout << \"0\\n\";\n    else {\n        s /= 3;\n        long long ss = 0;\n        for(int i = n-1; i >= 0 ; --i)\n        {\n            ss += a[i];\n            if (ss == s)\n                cnt[i] = 1;\n        }\n        for(int i = n-2 ; i >= 0 ; --i)\n            cnt[i] += cnt[i+1];\n        \n        long long ans = 0;\n        ss = 0;\n        for(int i = 0 ; i+2 < n ; ++i) {\n            ss += a[i];\n            if (ss == s)\n                ans += cnt[i+2];\n        }\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "466",
    "index": "D",
    "title": "Increase Sequence",
    "statement": "Peter has a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Peter wants all numbers in the sequence to equal $h$. He can perform the operation of \"adding one on the segment $[l, r]$\": add one to all elements of the sequence with indices from $l$ to $r$ (inclusive). At that, Peter never chooses any element as the beginning of the segment twice. Similarly, Peter never chooses any element as the end of the segment twice. In other words, for any two segments $[l_{1}, r_{1}]$ and $[l_{2}, r_{2}]$, where Peter added one, the following inequalities hold: $l_{1} ≠ l_{2}$ and $r_{1} ≠ r_{2}$.\n\nHow many distinct ways are there to make all numbers in the sequence equal $h$? Print this number of ways modulo $1000000007 (10^{9} + 7)$. Two ways are considered distinct if one of them has a segment that isn't in the other way.",
    "tutorial": "Lets use dynamic programming to solve this problem. $dp[i][opened]$ - the number of ways to cover prefix of array 1..i by segments and make it equal to $h$ and remain after $i$-th element $opened$ segments that are not closed. Consider all possible variants opening/closing segments in each position: - ] closing one segment - [ opening one new segment - [] adding one segment with length 1 - ][ closing one opened segment and opening a new one - - do nothing Lets understand how to build dynamic. It is obviously to understand that $a[i] + opened$ can be equal $h$ or $h - 1$. Otherwise, number of such ways equals 0. Consider this two cases separately: 1) $a[i] + opened = h$ It means that number of opened segments after $i$-th as max as possible and we can't open one more segment in this place. So there are two variants: - [ Opening a new segment. If only $opened > 0$. dp[i][opened] += dp[i-1][opened + 1] - - Do nothing. dp[i][opened] += dp[i-1][opened] Other variants are impossible because of summary value of $a[i]$ will be greater than $h$(when segment is finishing in current position - it increase value, but do not influence on $opened$, by the dynamic definition. 2) $a[i] + opened + 1 = h$ Here we consider ways where $i$-th element has been increased by $opened + 1$ segments, but after $i$-th remain only $opened$ not closed segments. Therefore, there are next variants: - ] - closing one of the opened segments(we can do it $opened + 1$ ways). dp[i][opened] += dp[i-1][opened + 1] * (opened + 1) - [] - creating 1-length segment. dp[i][opened] += dp[i-1][opened] - ][ - If only $opened > 0$. Amount of ways to choose segment which we will close equals $opened$. dp[i][opened] += dp[i-1][opened] * opened Start values - dp[1][0] = (a[1] == h || a[1] + 1 == h?1:0); dp[1][1] = (a[1] + 1 == h?1:0) Answer - dp[n][0]. Complexity: $O(n)$",
    "code": "#include<iostream>\n \nusing namespace std;\n \n#define MOD 1000000007\n \nlong long dp[2010][2010];\nint a[2010];\ninline void add(long long &a,long long b){\n   a += b;\n   a %= MOD;\n}\nint main()\n{\n     ios_base::sync_with_stdio(0);\n     int n,h;\n     cin >> n >> h;\n     \n     for (int i = 1; i <= n ;i ++)\n         cin >> a[i];\n \n     dp[1][0] = (a[1] == h || a[1] + 1 == h?1:0);\n     dp[1][1] = (a[1] + 1 == h?1:0);\n     \n     for (int i = 2;i <= n + 1; i ++)\n      for (int open = max(0,h - a[i]- 1); open <= min(h - a[i],i) ; open ++){\n          if (a[i] + open == h){\n             add(dp[i][open] , dp[i - 1][open]);\n             if (open > 0)\n                add(dp[i][open] , dp[i - 1][open - 1]);\n          }\n          if (open + a[i] + 1 == h){\n               add(dp[i][open] , dp[i - 1][open + 1] * (open + 1));\n               add(dp[i][open] , dp[i - 1][open]);\n               add(dp[i][open] , dp[i - 1][open] * open);\n          }\n      }\n     cout << dp[n][0] << endl;\n     return 0;\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "466",
    "index": "E",
    "title": "Information Graph",
    "statement": "There are $n$ employees working in company \"X\" (let's number them from 1 to $n$ for convenience). Initially the employees didn't have any relationships among each other. On each of $m$ next days one of the following events took place:\n\n- either employee $y$ became the boss of employee $x$ (at that, employee $x$ didn't have a boss before);\n- or employee $x$ gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive);\n- or comes a request of type \"determine whether employee $x$ signs certain documents\".\n\nYour task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies.",
    "tutorial": "Let's introduce all structure of the company as a graph(if $y$ is the head of $x$ then we add edge $y$ -> $x$). It is obviously to understand that after each operation our graph will be the set of trees. Actually, the third query - to check is our vertex belong to the subtree of the vertex which has received data package. Graph that we will receive after doing all operations we call final. Also, we will say that two vertexes belong to the same connectivity component if they belong to the same component in graph that we can have from final by changing directed edge to undirected. Consider the following statement: vertex $y$ is the parent of vertex $x$ in current graph(after doing first $i$ queries) if $y$ and $x$ belongs to the same conectitive component and in final graph $y$ is the parent of $x$. We will solve this problem offline. After each query of adding data package we will immediately answer all the questions about this package. Besides that, use disjoint set union to define is this vertex belong to the same component or not. To answer the question we need to check that $y$ is the parent of $x$ in final graph and that $x$ and $y$ is currently belong to the same connectivity component. Final graph we will build before doing this algorithm because we know all queries. Check that $y$ is the parent of $x$ in final tree we can simply in O(1) by arrays of entry-time and output-time which we can calculate use dfs($v$ -parent $u$ <=> ($in[v]  \\le  in[u]$ and $out[u]  \\le  out[v]$). Complexity: $O(n * u(n))$, where $u$ - inverse Ackerman function.",
    "code": "#include<iostream>\n#include<vector>\n#include<algorithm>\n \nusing namespace std;\n \n#define MOD  1000000007\n \nconst int Nmax = 100100;  \n \nint QueryToNumber[Nmax] , NumberToQuery[Nmax];\nint tin[Nmax], tout[Nmax], dsu[Nmax];\nint Number = 0 , timer = 1 , n , m;\nvector<vector<int> > g;\nvector<int> Question[Nmax];\nint deg[Nmax], answer[Nmax];\n \nstruct queries{\n       int t,x,y;\n} List[Nmax];\n \nvoid dfs(int v,int p = -1){\n     tin[v] = timer ++;\n     for (int i = 0 ;i < g[v].size(); i ++){\n         int u = g[v][i];\n         if (u == p) continue;\n         if (tin[u] == 0) dfs(u,  v);\n     }\n     tout[v] = timer ++;\n}\ninline bool parent(int v,int u){\n       return (tin[v] <= tin[u] && tout[v] >= tout[u]);\n}\nint get(int v){\n    if (dsu[v] == v) return v;\n    return dsu[v] = get(dsu[v]);\n}\nvoid uni(int v,int u){\n     if (rand()% 2)\n      swap(v,u);\n     v = get(v),u = get(u);\n     dsu[v] = u;\n}\nint main()\n{\n     ios_base::sync_with_stdio(0);\n     cin >> n >> m;\n     g.resize(n + 1);\n     \n     for (int i = 1;i <= m ;i ++){\n                cin >> List[i].t;\n                if (List[i].t == 2) cin >> List[i].x;\n                else\n                 cin >> List[i].x >> List[i].y;\n               \n                if (List[i].t == 2)\n                   QueryToNumber[i] = ++Number,\n                   NumberToQuery[Number] = i;\n               \n                if (List[i].t == 3)\n                 Question[List[i].y].push_back(i);\n     }      \n     for (int i = 1;  i <= m ;i ++)\n      if (List[i].t == 1)\n       g[List[i].y].push_back(List[i].x),\n       deg[List[i].x] ++;\n       \n     timer = 1;\n     for (int i = 1 ; i <= n ;i ++){\n         if (deg[i] != 0 || tin[i] != 0) continue;\n         dfs(i);\n     }\n     for (int i = 1; i <= n ; i ++)\n      dsu[i] = i;\n     for (int i = 1 ;i <= m ;i ++)\n      answer[i] = -1;\n   \n     for (int i = 1; i <= m ;i ++){\n         if (List[i].t == 1){\n            uni(List[i].x,List[i].y);\n            continue;\n         }\n         if (List[i].t == 3) continue;\n         int num = QueryToNumber[i];\n         int v = List[i].x;\n         for (int j = 0 ;j < Question[num].size();j ++ ){\n             int u = List[Question[num][j]].x;\n             answer[Question[num][j]] = (get(v) == get(u) && parent(u,v));\n         }\n     }\n     for (int i = 1; i <= m ;i  ++)\n      if (List[i].t == 3){\n         if (answer[i] == 1) cout << \"YES\\n\";\n         else cout << \"NO\\n\";\n      }\n     return 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "468",
    "index": "A",
    "title": "24 Game",
    "statement": "Little X used to play a card game called \"24 Game\", but recently he has found it too easy. So he invented a new game.\n\nInitially you have a sequence of $n$ integers: $1, 2, ..., n$. In a single step, you can pick two of them, let's denote them $a$ and $b$, erase them from the sequence, and append to the sequence either $a + b$, or $a - b$, or $a × b$.\n\nAfter $n - 1$ steps there is only one number left. Can you make this number equal to $24$?",
    "tutorial": "Solution 1: If $n  \\le  3$, it's easy to find that it's impossible to make $24$, because the maximal number they can form is $9$. If $n > 5$, we can simply add $n - (n - 1) = 1, 24 * 1 = 24$ at the end of the solution to the number $n - 2$. So we can find the solution of $4, 5$ by hand. $1 * 2 * 3 * 4 = 24, (5 - 3) * 4 * (2 + 1) = 24$ Solution 2: We can find the pattern like that $n + (n + 3) - (n + 1) - (n + 2) = 0$, and find the solution of $4, 5, 6, 7$ by hand or brute forces. Solution 3: A knapsack-like solution.",
    "code": "// Author: Ruchiose\n#include<iostream>\n#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<algorithm>\n#include<cmath>\n#include<vector>\n#define i64 long long\n#define d64 long double\n#define fortodo(i, f, t) for (i = f; i <= t; i++)\nusing namespace std;\n \nbool posi[100010];\n \nint main()\n{\n\tint N;\n\tscanf(\"%d\", &N);\n\tswitch (N)\n\t{\n\t\tcase 1:\n\t\tcase 2:\n\t\tcase 3:\n\t\t\tputs(\"NO\\n\");\n\t\tbreak;\n\t\tcase 4:\n\t\t\tprintf(\"YES\\n1 * 2 = 2\\n2 * 3 = 6\\n4 * 6 = 24\\n\");\n\t\tbreak;\n\t\tcase 5:\n\t\t\tprintf(\"YES\\n2 * 4 = 8\\n3 * 5 = 15\\n1 + 8 = 9\\n9 + 15 = 24\\n\");\n\t\tbreak;\n\t\tcase 6:\n\t\t\tprintf(\"YES\\n1 * 2 = 2\\n2 * 3 = 6\\n4 * 6 = 24\\n6 - 5 = 1\\n24 * 1 = 24\\n\");\n\t\tbreak;\n\t\tdefault:{\n\t\t\tprintf(\"YES\\n\");\n\t\t\ti64 Tn = (N + 1ll) * N / 2;\n\t\t\tif (Tn & 1)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"%d - %d = 1\\n1 * 1 = 1\\n\", N, N - 1);\n\t\t\t\t\tN -= 2;\n\t\t\t\t\tTn -= N * 2 + 3;\n\t\t\t\t}\n\t\t\ti64 Positive = (Tn + 24) / 2;\n\t\t\tvector<int> VI;\n\t\t\tVI.clear();\n\t\t\tVI.push_back(1);\n\t\t\twhile ((VI.back() + 1LL) * (VI.back() + 2LL) / 2 <= Positive)\n\t\t\t\tVI.push_back(VI.back() + 1);\n\t\t\tint q = VI.back(), i;\n\t\t\ti64 rest = Positive - (q * (q + 1LL) / 2);\n\t\t\tfortodo(i, 1, rest) VI[q - i]++;\n\t\t\tfortodo(i, 1, N) posi[i] = false;\n\t\t\tfortodo(i, 0, q - 1) posi[VI[i]] = true;\n\t\t\ti64 ths = VI[0];\n\t\t\tfortodo(i, 1, q - 1)\n\t\t\t\t{\n\t\t\t\t\tprintf(\"%I64d + %d = %I64d\\n\", ths, VI[i], ths + VI[i]);\n\t\t\t\t\tths += VI[i];\n\t\t\t\t}\n\t\t\tfortodo(i, 1, N)\n\t\t\t\tif (!posi[i])\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"%I64d - %d = %I64d\\n\", ths, i, ths - i);\n\t\t\t\t\t\tths -= i;\n\t\t\t\t\t}\n\t\t}\n\t\tbreak;\n\t};\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "468",
    "index": "B",
    "title": "Two Sets",
    "statement": "Little X has $n$ distinct integers: $p_{1}, p_{2}, ..., p_{n}$. He wants to divide all of them into two sets $A$ and $B$. The following two conditions must be satisfied:\n\n- If number $x$ belongs to set $A$, then number $a - x$ must also belong to set $A$.\n- If number $x$ belongs to set $B$, then number $b - x$ must also belong to set $B$.\n\nHelp Little X divide the numbers into two sets or determine that it's impossible.",
    "tutorial": "Solution 1: If we have number $x$ and $a - x$, they should be in the same set. If $x\\in A$, it's obvious that $a-x\\in A$. The contraposition of it is $a-x\\not\\in A\\Rightarrow x\\not\\in A$, that means if $x\\in B$, $a - x$ should in the set $B$. Same as the number $x, b - x$. So we can use Disjoint Set Union to merge the number that should be in the same set. If $a - x$ doesn't exist, $x$ can not be in the set $A$. If $b - x$ doesn't exist, $b$ can not be in the set $B$. Then check if there are any conflicts among numbers which should be in the same set. There are many other solutions to solve this problem based on the fact that $x, a - x, b - x$ should be in the same set, like greedy, BFS and 2-SAT. Solution 2: If $a = b$, it's easy to find the solution. We regards every number as a node. Every number $x$ links to number $a - x$ and number $b - x$. The degree of every node is at most $2$. So this graph consists of a lot of chains and cycles, and some node may have self loop. We only need to check if the lengths of all the chains are even or the chain ends with a self loop.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,a,n) for (int i=a;i<n;i++)\n \nconst int N=101000;\nmap<int,int> hs;\nint vis[N],way[N],A[N],B[N],p[N];\nint n,a,b;\n \nbool check0() {\n\trep(i,0,n) if (!hs.count(a-p[i])) return 0;\n\treturn 1;\n}\nvoid dfs(int u,int p,int s) {\n\tvis[u]=1;\n\tway[u]=s;\n\tif (p==0) {\n\t\tif (A[u]==u) throw 1;\n\t\tif (A[u]==-1) throw s;\n\t\tdfs(A[u],p^1,s);\n\t} else {\n\t\tif (B[u]==u) throw 1;\n\t\tif (B[u]==-1) throw s^1;\n\t\tdfs(B[u],p^1,s);\n\t}\n}\nbool check1() {\n\trep(i,0,n) if (!vis[i]) {\n\t\tif (A[i]==i||B[i]==i) continue;\n\t\tif (((A[i]==-1)^(B[i]==-1))==0) continue;\n\t\ttry {\n\t\t\tdfs(i,A[i]==-1,A[i]==-1);\n\t\t} catch(int e) {\n\t\t\tif (e==0) return 0;\n\t\t}\n\t}\n\trep(i,0,n) if (!vis[i]) {\n\t\tif (A[i]==i) vis[i]=1,way[i]=0;\n\t\telse if (B[i]==i) vis[i]=1,way[i]=1;\n\t}\n\trep(i,0,n) if (!vis[i]) return 0;\n\treturn 1;\n}\nint main() {\n\tscanf(\"%d%d%d\",&n,&a,&b);\n\trep(i,0,n) scanf(\"%d\",p+i),hs[p[i]]=i;\n\tif (a==b) {\n\t\tif (check0()) {\n\t\t\tputs(\"YES\");\n\t\t\trep(i,0,n) {\n\t\t\t\tputchar('0');\n\t\t\t\tif (i!=n-1) putchar(' ');\n\t\t\t}puts(\"\");\n\t\t} else puts(\"NO\");\n\t} else {\n\t\trep(i,0,n) {\n\t\t\tif (hs.count(a-p[i])) A[i]=hs[a-p[i]]; else A[i]=-1;\n\t\t\tif (hs.count(b-p[i])) B[i]=hs[b-p[i]]; else B[i]=-1;\n\t\t}\n\t\tif (check1()) {\n\t\t\tputs(\"YES\");\n\t\t\trep(i,0,n) {\n\t\t\t\tputchar(way[i]+'0');\n\t\t\t\tif (i!=n-1) putchar(' ');\n\t\t\t}\n\t\t\tputs(\"\");\n\t\t} else puts(\"NO\");\n\t}\n}",
    "tags": [
      "2-sat",
      "dfs and similar",
      "dsu",
      "graph matchings",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "468",
    "index": "C",
    "title": "Hack it!",
    "statement": "Little X has met the following problem recently.\n\nLet's define $f(x)$ as the sum of digits in decimal representation of number $x$ (for example, $f(1234) = 1 + 2 + 3 + 4$). You are to calculate $\\sum_{i=1}^{r}f(i)\\,\\bmod\\,a.$\n\nOf course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the following C++ code:\n\n\\begin{verbatim}\nans = solve(l, r) % a;\nif (ans <= 0)\nans += a;\n\\end{verbatim}\n\nThis code will fail only on the test with $\\sum_{i=l}^{r}f(i)\\equiv0{\\mathrm{~(mod~}}a)$. You are given number $a$, help Little X to find a proper test for hack.",
    "tutorial": "Define $g(x)=\\sum_{i=0}^{x-1}f(i)$. $\\sum_{i=l}^{r}f(i)=g(r+1)-g(l)$, so we should find a pair of number $a, b$ that $g(a)\\equiv g(b)(\\mathrm{mod}\\ a)$ Solution 1: First we choose $x$ randomly. Then we can use binary search to find the minimal $d$ that $g(x+d)-g(x)\\geq a-g(x)\\;\\mathrm{mod}\\;a$ . So $g(x+d){\\mathrm{~mod~}}a$ is very small, between $0$ and $9*\\lceil\\log_{10}(x+d)\\rceil$. If $x+d\\in[0,10^{l e n})$, after choosing $x$ atmost $9 * len + 2$ times, we can definitely find a pair that $g(a)\\equiv g(b)(\\mathrm{mod}\\ a)$ Solution 2: We can use binary search to find the minimal $d$ that $g(d)  \\ge  a, g(d)  \\ge  2a, ...$ This solution is similar to the first one. Solution 3: We can use binary search to find the minimal $d$ that $g(d)  \\ge  a$. And we use two pointers to maintain an interval $[l, r]$ that $\\textstyle\\sum_{i=l}^{r}f(i)\\geq a$ until we find $\\textstyle\\sum_{i=l}^{r}f(i)=a$. I can't prove the correctness of this algorithm, but it performs well in practice. Solution 4: Thanks ZhouYuChen for his talented idea. If $x < 10^{18}$, we can get $f(10^{18} + x) = f(x) + 1$. That means if we shift the interval $[x + 1, x + 10^{18}]$ by $1$, the result will be increase by $1$ too. And it also not hard to find that $g(10^{x}) = 45 * x * 10^{x - 1}$. So if $g(10^{18})\\equiv x({\\mathrm{mod}}\\ a)$, $[a - x, a - x + 10^{18} - 1]$ is the answer. It's easy to see that upper bound of the answer is $a$, because of pigeonhole principle (among $g(0), g(1), ..., g(a)$ at least two are equal). So big integer is not required in this problem. If solution 3 is correct, the upper bound of the answer can be $2 * 10^{16}$.",
    "code": "m = int(input())\nx,t=10**100-1,m-100*45*10**99%m\nprint(t,t+x)\n ",
    "tags": [
      "binary search",
      "constructive algorithms",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "468",
    "index": "D",
    "title": "Tree",
    "statement": "Little X has a tree consisting of $n$ nodes (they are numbered from $1$ to $n$). Each edge of the tree has a positive length. Let's define the distance between two nodes $v$ and $u$ (we'll denote it $d(v, u)$) as the sum of the lengths of edges in the shortest path between $v$ and $u$.\n\nA permutation $p$ is a sequence of $n$ distinct integers $p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$. Little X wants to find a permutation $p$ such that sum $\\sum_{i=1}^{n}d(i,p_{i})$ is maximal possible. If there are multiple optimal permutations, he wants to find the lexicographically smallest one. Help him with the task!",
    "tutorial": "$d(u, v) = dep_{u} + dep_{v} - 2 * dep_{LCA(u, v)}$, so the answer is: $\\textstyle{\\sum_{i=1}^{n}d e p_{i}+d e p_{p_{i}}-2*d e p_{L C A(i,p_{i})}=2*\\sum_{i=1}^{n}d e p_{i}-2*\\sum_{i=1}^{n}d e p_{L C A(i,p_{i})}}$ $dep_{i}$ there means the distance between node $i$ and root. We choose centroid of tree as root (let's denote it $u$), so we can make every pair $(i, p_{i})$ are in different subtrees, that means $dep_{LCA(i, pi)} = 0$. So the answer is $\\sum_{i=1}^{n}2*d(i,u)$. The next part of this problem is find the lexicographically smallest solution. We regards it as finding the lexicographically smallest matching in a bipartite graph. For a subtree, if the amount of nodes in this subtree in the left part > the amount of nodes not in this subtree in the right part, the perfect matching doesn't exist. So the amount of nodes in this subtree in the left part + the amount of nodes in this subtree in the right part should be no more than the amount of nodes unmatched, while the root is an exception. We can use a segment tree to maintain it easily. We determined the minimum possible $p_{i}$ from $1$ to $n$. If there is a subtree that the amount of nodes in this subtree in the left and right part is equal to the amount of nodes unmatched, we must select a node from it, so $p_{i}$ equal to the node in this subtree with the minimum id. Otherwise, we can choose a node with the minimum id that is not in the same subtree with $i$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,a,n) for (int i=a;i<n;i++)\n#define per(i,a,n) for (int i=n-1;i>=a;i--)\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define SZ(x) ((int)(x).size())\n#define fi first\n#define se second\ntypedef vector<int> VI;\ntypedef long long ll;\ntypedef pair<int,int> PII;\nconst ll mod=1000000007;\nll powmod(ll a,ll b) {ll res=1;a%=mod;for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}\n// head\n \nconst int N=101000;\nint q[N],f[N],vis[N],sz[N],ms[N],brh[N];\nint u,v,w,n,tot;\nVI e[N],d[N];\nlong long ans;\nset<int> ts[N];\nint nd[N*4],l[N],r[N],spe[N],p[N];\nVI must;\nint find(int u) {\n\tint t=1;q[0]=u;f[u]=-1;\n\trep(i,0,t) {\n\t\tu=q[i];\n\t\trep(j,0,SZ(e[u])) {\n\t\t\tint v=e[u][j];\n\t\t\tif (!vis[v]&&v!=f[u]) f[q[t++]=v]=u;\n\t\t}\n\t\tms[q[i]]=0;\n\t\tsz[q[i]]=1;\n\t}\n\tfor (int i=t-1;i>=0;i--) {\n\t\tms[q[i]]=max(ms[q[i]],t-sz[q[i]]);\n\t\tif (ms[q[i]]*2<=t) return q[i];\n\t\tsz[f[q[i]]]+=sz[q[i]];\n\t\tms[f[q[i]]]=max(ms[f[q[i]]],sz[q[i]]);\n\t}\n\treturn 0;\n}\nvoid df(int u,int f,long long dep) {\n\tans+=dep;\n\trep(j,0,SZ(e[u])) {\n\t\tint v=e[u][j];\n\t\tif (v==f) continue;\n\t\tdf(v,u,dep+d[u][j]);\n\t}\n}\nvoid dfs(int u,int f,int br) {\n\tl[u]=++tot; brh[u]=br; sz[u]=1;\n\trep(i,0,SZ(e[u])) {\n\t\tint v=e[u][i];\n\t\tif (v==f) continue;\n\t\tdfs(v,u,br);\n\t\tsz[u]+=sz[v];\n\t}\n\tr[u]=tot;\n}\nvoid modify(int p,int l,int r,int x,int v) {\n\tif (l==r) nd[p]=v;\n\telse {\n\t\tint md=(l+r)>>1;\n\t\tif (x<=md) modify(p+p,l,md,x,v);\n\t\telse modify(p+p+1,md+1,r,x,v);\n\t\tnd[p]=min(nd[p+p],nd[p+p+1]);\n\t}\n}\nint query(int p,int l,int r,int tl,int tr) {\n\tif (l==tl&&r==tr) return nd[p];\n\telse {\n\t\tint md=(l+r)>>1;\n\t\tif (tr<=md) return query(p+p,l,md,tl,tr);\n\t\telse if (tl>md) return query(p+p+1,md+1,r,tl,tr);\n\t\telse return min(query(p+p,l,md,tl,md),query(p+p+1,md+1,r,md+1,tr));\n\t}\n}\nint query(int u,int k) {\n\tif (k==0) {\n\t\tif (r[u]==n) return query(1,1,n,1,l[u]-1);\n\t\telse return min(query(1,1,n,1,l[u]-1),query(1,1,n,r[u]+1,n));\n\t} else return query(1,1,n,l[u],r[u]);\n}\nint main() {\n\tscanf(\"%d\",&n);\n\trep(i,1,n) {\n\t\tscanf(\"%d%d%d\",&u,&v,&w);\n\t\te[u].pb(v); e[v].pb(u);\n\t\td[u].pb(w); d[v].pb(w);\n\t}\n\tu=find(1);\n\tdf(u,0,0);\n\tprintf(\"%I64d\\n\",ans*2);\n\tl[u]=++tot;\n\trep(i,0,SZ(e[u])) {\n\t\tv=e[u][i];\n\t\tdfs(v,u,v);\n\t\tsz[v]*=2;\n\t\tts[sz[v]].insert(v);\n\t}\n\tr[u]=1; brh[u]=u; spe[u]=1;\n\trep(i,1,n+1) modify(1,1,n,l[i],i);\n\trep(i,1,n+1) {\n\t\tmust.clear();\n\t\tfor (set<int>::iterator it=ts[n+1-i].begin();it!=ts[n+1-i].end();it++)\n\t\t\tmust.pb(*it);\n\t\tif (SZ(must)==2) p[i]=query(must[brh[i]==must[0]],1);\n\t\telse if (SZ(must)==1) {\n\t\t\tif (brh[i]==must[0]) p[i]=query(brh[i],0);\n\t\t\telse p[i]=query(must[0],1);\n\t\t} else {\n\t\t\tif (spe[i]) p[i]=nd[1];\n\t\t\telse p[i]=query(brh[i],0);\n\t\t}\n\t\tmodify(1,1,n,l[p[i]],1<<30);\n\t\tu=brh[i],v=brh[p[i]];\n\t\tif (!spe[u]) ts[sz[u]].erase(u),ts[--sz[u]].insert(u);\n\t\tif (!spe[v]) ts[sz[v]].erase(v),ts[--sz[v]].insert(v);\n\t}\n\trep(i,1,n+1) printf(\"%d%c\",p[i],(i==n)?'\\n':' ');\n}",
    "tags": [
      "graph matchings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "468",
    "index": "E",
    "title": "Permanent",
    "statement": "Little X has solved the #P-complete problem in polynomial time recently. So he gives this task to you.\n\nThere is a special $n × n$ matrix $A$, you should calculate its permanent modulo $1000000007 (10^{9} + 7)$. The special property of matrix $A$ is almost all its elements equal to $1$. Only $k$ elements have specified value.\n\nYou can find the definition of permanent at the link: https://en.wikipedia.org/wiki/Permanent",
    "tutorial": "The permanent can be obtained as follows: for each $(e_{1}, e_{2}, ..., e_{t})$ such that $x_{1}, x_{e2}..., x_{et}$ are distinct and $y_{e1}, y_{e2}, ..., y_{et}$ are distinct, add $(n-t)!\\prod_{i=1}^{t}(w_{e_{i}}-1)$ to the answer. It can be proved by the formula : ${\\mathrm{perm}}(A+B)=\\sum_{s,t}{\\mathrm{perm}}(a_{i j})_{i\\in s,j\\in t}{\\mathrm{perm}}(b_{i j})_{i\\in\\bar{s},j\\in t}$, where $s$ and $t$ are subsets of the same size of ${1, 2, ..., n}$ and $\\scriptstyle{\\vec{s}}$, $\\overline{{t}}$ are their respective complements in that set. Construct a undirected graph $G$ with $2n$ vertices $v_{1}, v_{2}, ..., v_{2n}$, where the edge weight between vertex $v_{i}, v_{n + j}$ is $A_{i, j} - 1$. We only need to know the sum of weight of all matchings that we choose $t$ edges. The weight of matching is the product of all edge weights in the matching. We only need to know the sum of the weights that we choose $x$ edges in the each connected components. The number of nodes in a connected component is $s$ and the number of edges in this connected component is $t$. Algorithm 1: Because it's a bipartite graph, so the number of vertices in one part is at most $s / 2$. So we can use state compressed dp to calculate the ways to choose $x$ edges in this connected component. The complexity is $O(2^{s / 2} * s^{2})$. Algorithm 2: We can choose a spanning tree. The number of edges in spanning tree of these vertices is $s - 1$, and the number of non-tree edges is $t - s + 1$. So we can enumerate all the non-tree edge, use tree dp to calculate the ways. The complexity is $O(2^{t - s} * s^{2})$. Combined with these two algorithm, the complexity is $O(min(2^{s / 2}, 2^{k - s}) * s^{2})) = O(2^{k / 3} * k^{2})$.",
    "tags": [
      "dp",
      "graph matchings",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 3100
  },
  {
    "contest_id": "469",
    "index": "A",
    "title": "I Wanna Be the Guy",
    "statement": "There is a game called \"I Wanna Be the Guy\", consisting of $n$ levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.\n\nLittle X can pass only $p$ levels of the game. And Little Y can pass only $q$ levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?",
    "tutorial": "The problem itself is easy. Just check if all the levels could be passed by Little X or Little Y.",
    "code": "R=lambda:map(int,raw_input().split())[1:]\nprint [\"Oh, my keyboard!\",\"I become the guy.\"][input()==len(set(R()).union(set(R())))]",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "469",
    "index": "B",
    "title": "Chat Online",
    "statement": "Little X and Little Z are good friends. They always chat online. But both of them have schedules.\n\nLittle Z has fixed schedule. He always online at any moment of time between $a_{1}$ and $b_{1}$, between $a_{2}$ and $b_{2}$, ..., between $a_{p}$ and $b_{p}$ (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time $0$, he will be online at any moment of time between $c_{1}$ and $d_{1}$, between $c_{2}$ and $d_{2}$, ..., between $c_{q}$ and $d_{q}$ (all borders inclusive). But if he gets up at time $t$, these segments will be shifted by $t$. They become $[c_{i} + t, d_{i} + t]$ (for all $i$).\n\nIf at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between $l$ and $r$ (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment $[l, r]$ suit for that?",
    "tutorial": "This problem is not hard. Just iterator over all possible $t$, and check if the schedule of Little X and Little Z will overlap.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,a,n) for (int i=a;i<n;i++)\nconst int N=110;\nint p,q,l,r,ans,tl,tr;\nint pool[10000],pa[10000],pb[10000],*vis=pool+5000,*a=pa+5000,*b=pb+5000;\nint main() {\n\tscanf(\"%d%d%d%d\",&p,&q,&l,&r);\n\trep(i,0,p) {\n\t\tscanf(\"%d%d\",&tl,&tr);\n\t\trep(j,tl,tr) a[j]=1;\n\t}\n\trep(i,0,q) {\n\t\tscanf(\"%d%d\",&tl,&tr);\n\t\trep(j,tl,tr) b[j]=1;\n\t}\n\trep(i,0,1001) rep(j,0,1001) if (a[i]&&b[j]) vis[i-j]=vis[i-j-1]=1;\n\trep(k,l,r+1) ans+=vis[k]|vis[k-1];\n\tprintf(\"%d\\n\",ans);\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "471",
    "index": "A",
    "title": "MUH and Sticks",
    "statement": "Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:\n\n- Four sticks represent the animal's legs, these sticks should have the same length.\n- Two remaining sticks represent the animal's head and body. The bear's head stick must be shorter than the body stick. The elephant, however, has a long trunk, so his head stick must be as long as the body stick. Note that there are no limits on the relations between the leg sticks and the head and body sticks.\n\nYour task is to find out which animal can be made from the given stick set. The zoo keeper wants the sticks back after the game, so they must never be broken, even bears understand it.",
    "tutorial": "Given six sticks and their lengths we need to decide whether we can make an elephant or a bear using those sticks. The only common requirement for both animals is that four leg-sticks should have same length. This means that the answer \"Alien\" should be given only if we can't find four sticks for the legs. Otherwise we will be able to make some animal. The type of the animal will depend on the relation of the remaining sticks' lengths. If they are equal then it will an elephant, if they are different we will have a bear. So this algorithm should solve the problem: Find the number which appears at least four times in the input. If no such number exist then the answer is \"Alien\". Otherwise remove four entries of that number from the input. After removing that number you will have two numbers left, compare them and decide whether it's an elephant or a bear. One shortcut for this problem might be to sort the input array, then if it's a bear or an elephant then 3rd and 4th elements in the sorted should be animal's legs. So you can assume that one of these numbers is the length of the leg and count how many times you see this number in the input. Since the numbers in the input are very small you can implement 'brute force' solution as well. By brute force solution in this case I mean that you can actually check all possible values for leg-length, head-length and body-length. If in total they give the same set as the input then you found a matching, all you need is to check whether it's a bear or an elephant. And it's an alien if you checked all possible combinations and found nothing matching to the input. Though in this case the brute force solution is not easier than another one. It seems that there were two common mistakes people were making in this problem: Not taking into account that legs can be of the same length as body or head. So you can't just count the number of distinct numbers in the input to decide which type of animal is that. We assumed that people might make such a mistake, there was a relevant warning in the statement. Trying to sort the input and then check whether some elements in this array are equal to other elements and based on this comparison decide which type of animal is that. People were simply making mistakes when deciding which elements to compare. The correct way to implement this is: This solution seems to be shorter but there are many failed solutions like this because people were not paying enough attention to the details. So I would prefer implementing more straightforward approach. Hope you liked the pictures!",
    "code": "#include <algorithm>\n#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nint main() {\n\tvector<int> l(6);\n\tfor (int i = 0 ; i < 6 ; i++) cin >> l[i];\n\tsort(l.begin(), l.end());\n\t\n\t     if (l[0] == l[3]) cout << (l[4] == l[5] ? \"Elephant\" : \"Bear\");\n\telse if (l[1] == l[4]) cout << \"Bear\";\n\telse if (l[2] == l[5]) cout << (l[0] == l[1] ? \"Elephant\" : \"Bear\");\n\telse cout << \"Alien\";\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "471",
    "index": "B",
    "title": "MUH and Important Things",
    "statement": "It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are $n$ tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.\n\nMenshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the $n$ tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.",
    "tutorial": "You need to check whether exist three pairwise different permutations of the indices of the input which result in array being sorted. Generally you can count the number of total permutation which give non-decreasing array. This number might be very large and it might easily overflow even long integer type. And what is more important is that you don't actually need to count the exact number of such permutations. Let's tackle this problem from another angle. Assume you already sorted the input array and you have the corresponding permutation of indices. This already gives you one array for the result, you only need to find two more. Let's look for any pair of equal numbers in the input array, if we swap them then we will get another valid permutation. And if we find one more pair of equal numbers then swapping them you can get third permutation and that will be the answer. You need to keep in mind here that one of the indices when swapping the second time might be the same as one of the numbers in the first swap, that's ok as soon as second index is different. So all you need to do is to find two pairs of indices which point to the equal elements. The entire algorithm is as follows: Transform the input array into array of pairs (tuples), first element of the pair will be the number given in the input array, the second element will be the index of that number. Sort that array of pairs by the first element of the pairs. Then the second elements will give you one correct permutation. Scan this array in order to find possible swaps. You just iterate over this array and check if the first element in the current pair equals to the first element of the previous pair. If it equals you remember the indices of these two pairs. You stop scanning the array as soon as you have two swaps. Then you check how many swaps you have, if you have less than two swaps then there are no three distinct permutations. Otherwise you have two swaps which means that you have an answer. So you print the current permutation, then you execute the first swap (you just swap those two elements you remembered in the first swap), then you print the permutation array received after executing that swap. And you execute the second swap and print the permutation array third time.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nvoid print(vector<pair<int, int> > &v) {\n\tfor (int i = 0 ; i < v.size() ; i++) cout << v[i].second << ' ';\n\tcout << endl;\n}\n \nint main() {\n\tint n;\n\tcin >> n;\n\tvector<pair<int, int> > input;\n\t\n\tfor (int i = 0 ; i < n ; i++) {\n\t\tint x;\n\t\tcin >> x;\n\t\tinput.push_back(make_pair(x, i + 1));\n\t}\n\t\n\tsort(input.begin(), input.end());\n\t\n\tvector<pair<int, int> > swaps;\n\tfor (int i = 1 ; i < n && swaps.size() < 2 ; i++) {\n\t\tif (input[i - 1].first == input[i].first) {\n\t\t\tswaps.push_back(make_pair(i - 1, i));\n\t\t}\n\t}\n\tif (swaps.size() < 2) {\n\t\tcout << \"NO\";\n\t\treturn 0;\n\t}\n\t\n\tcout << \"YES\" << endl;\n\tprint(input);\n\tswap(input[swaps[0].first], input[swaps[0].second]);\n\tprint(input);\n\tswap(input[swaps[1].first], input[swaps[1].second]);\n\tprint(input);\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "471",
    "index": "C",
    "title": "MUH and House of Cards",
    "statement": "Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of $n$ playing cards. Let's describe the house they want to make:\n\n- The house consists of some non-zero number of floors.\n- Each floor consists of a non-zero number of rooms and the ceiling. A room is two cards that are leaned towards each other. The rooms are made in a row, each two adjoining rooms share a ceiling made by another card.\n- Each floor besides for the lowest one should contain less rooms than the floor below.\n\nPlease note that the house may end by the floor with more than one room, and in this case they also must be covered by the ceiling. Also, the number of rooms on the adjoining floors doesn't have to differ by one, the difference may be more.\n\nWhile bears are practicing to put cards, Horace tries to figure out how many floors their house should consist of. The height of the house is the number of floors in it. It is possible that you can make a lot of different houses of different heights out of $n$ cards. It seems that the elephant cannot solve this problem and he asks you to count the number of the distinct heights of the houses that they can make using \\textbf{exactly} $n$ cards.",
    "tutorial": "Card house. This problem required some maths, but just a little bit. So in order to start here let's first observe that the number of cards you need to use for a complete floor with $R$ rooms equals to: $C = C_{rooms} + C_{ceiling} = 2 \\cdot R + (R - 1) = 3 \\cdot R - 1$ Then if you have $F$ floors with $R_{i}$ rooms on the $i$-th floor then the total number of cards would be: $N=\\sum_{i=1}^{F}C_{i}=\\sum_{i=1}^{F}(3\\cdot R_{i}-1)=3\\cdot\\sum_{i=1}^{F}R_{i}-F=3\\cdot R-F$ where $R$ is the total number of the rooms in the card house. This already gives you an important property - if you divide $N + F$ on 3 then the remainder of this division should be 0. This means that if you have found some minimum value of floors somehow and you found maximum possible number of floors in the house, then within that interval only every third number will be a part of the solution, the rest of the numbers will give a non-zero remainder in the equation above. Now let's think what is the highest house we can build using $N$ cards. In order to build the highest possible house obviously you need to put as few cards on each floor as you can. But we have a restriction that every floor should have less rooms than the floor below. This gives us the following strategy to maximize the height of the house: we put 1 room on the top floor, then 2 rooms on the floor below, then 3 rooms on the next floor, etc. In total then the number of cards we will need equals to: $N_{m i n}=\\{{\\boldsymbol{3}}\\cdot{\\boldsymbol{R}}-{\\boldsymbol{F}}={\\boldsymbol{\\sqrt{\\cdot}}}\\sum_{x=1}^{F}{\\boldsymbol{x}}-{\\boldsymbol{F}}={\\boldsymbol{9}}\\cdot{\\boldsymbol{F}}\\cdot\\left({\\boldsymbol{F+1}}\\right)/2-{\\boldsymbol{F}}$ This is minimum number of cards we need in order to build a house with $F$ floors. This gives us a way to calculate the maximum height of the house we can build using $N$ cards, we just need to find maximum $F$ which gives $N_{min} < = N$. Mathematicians would probably solve the quadratic inequation, programmers have two options: Check all possible $F$ until you hit that upper bound. Since $N_{min}$ grows quadratically with $F$ then you will need to check only up to $\\sqrt{N}$ numbers. This gives $O({\\sqrt{N}})$ time complexity and fits nicely in the given time limit. The second approach would be a binary search. Using binary search to find maximum number of the floors would give you $O(logN)$ time complexity. This was the intended originally solution but it was decided to lower the constraints in order to allow sqrt solutions as well. Now that you know the maximum number of the floors in the house you might need to correct it a bit because of that remainder thing we discussed above, this might make your maximum height one or two floors lower. Looking again at the remainder discussion on top we can see that starting from here only every third number will be valid for an answer. Now you can either count them brutally (back to $O({\\sqrt{N}})$ solution) or you can simply calculate them using this formulae: $ans = (F_{max} + 3 - 1) / 3$ (integer division) That seems to be it, just don't forget to use longs all the time in this problem.",
    "code": "#include \"assert.h\"\n#include <iostream>\n \ntypedef long long int LL;\n \nusing namespace std;\n \nLL getNumberOfCardsInFullHouse(LL floors) {\n  return 3 * floors * (floors + 1) / 2 - floors;\n}\n \nLL solve(LL n) {\n  LL res = 0;\n  for (LL floors = 1 ; getNumberOfCardsInFullHouse(floors) <= n ; floors++)\n    if ((n + floors) % 3 == 0)\n      res++;\n  return res;\n}\n \nint main() {\n  LL n; cin >> n;\n  cout << solve(n); \n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "471",
    "index": "D",
    "title": "MUH and Cube Walls",
    "statement": "Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.\n\nHorace was the first to finish making his wall. He called his wall an elephant. The wall consists of $w$ towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of $n$ towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he \"see an elephant\"? He can \"see an elephant\" on a segment of $w$ contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).\n\nYour task is to count the number of segments where Horace can \"see an elephant\".",
    "tutorial": "In this problem we are given two arrays of integers and we need to find how many times we can see second array as a subarray in the first array if we can add some arbitrary constant value to every element of the second array. Let's call these arrays $a$ and $b$. As many people noticed or knew in advance this problem can be solved easily if we introduce difference arrays like that: $aDiff_{i} = a_{i} - a_{i + 1}$ (for every $i = = 0..n - 1$) If we do that with both input arrays we will receive two arrays both of which have one element less than original arrays. Then with these arrays the problem simply becomes the word search problem (though with possibly huge alphabet). This can be solved using your favourite string data structure or algorithm. Originally it was intended to look for linear solution but then we made time limit higher in case if somebody will decide to send $O(NlogN)$ solution. I haven't seen such solutions (that is understandable) but some people tried to squeeze in a quadratic solution. Linear solution can be made using Z-function or KMP algorithm. In order to add a logarithmic factor you can exercise with suffix array for example. I had suffix array solution as well, but it's a lot messier than linear solution. There is one corner case you need to consider - when Horace's wall contains only one tower, then it matches bears' wall in every tower so the answer is $n$. Though for some algorithms it might not even be a corner case if you assume that empty string matches everywhere. Another error which several people did was to use actual string data structures to solve this problem, so they converted the differences to chars. This doesn't work since char can't hold the entire range an integer type can hold. I didn't think that switching to difference arrays will be that obvious or well-known, so I didn't expect that this problem will be solved by that many people.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n \nusing namespace std;\n \nint IntMinVal = (int) -1e20;\n \ntemplate <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }\n \n/// compacts the array of arbitrary numbers into an array of [0 .. K - 1] numbers where K is the number of distinct numbers in the original array.\n/// the items in the resulting array are guaranteed to give the same comparison result as the items in the original array on the same positions\n/// Complexity - O(N logN)\nvector<int> compactArray(vector<int>& v) {\n    vector<int> inputNumbers = v;\n    sort(inputNumbers.begin(), inputNumbers.end());\n    inputNumbers.resize(unique(inputNumbers.begin(), inputNumbers.end()) - inputNumbers.begin());\n    map<int, int> mapping;\n    for (int i = 0 ; i < inputNumbers.size() ; i++)\n        mapping[inputNumbers[i]] = i;\n    vector<int> result(v.size());\n    for (int i = 0 ; i < v.size() ; i++)\n        result[i] = mapping[v[i]];\n    return result;\n \n    \n}\n \n// algorithm is mostly taken from e-maxx \"as is\", only arrays were changed to vectors\nvector<int> calcSuffixArray(vector<int> s) {\n\ts = compactArray(s); // reduce the numbers in the input array since the complexity of the algorithm below depends on alphabet size\n\t\n\tint n = s.size();\n\tint alphabet = n;\n \n\tvector<int> p(n);\n\tvector<int> cnt(n);\n\tvector<int> c(n);\n \n\tfor (int i=0; i < n; ++i)\n\t\t++cnt[s[i]];\n\tfor (int i=1; i<alphabet; ++i)\n\t\tcnt[i] += cnt[i-1];\n\tfor (int i=0; i<n; ++i)\n\t\tp[--cnt[s[i]]] = i;\n\tc[p[0]] = 0;\n\tint classes = 1;\n\tfor (int i=1; i<n; ++i) {\n\t\tif (s[p[i]] != s[p[i-1]])  ++classes;\n\t\tc[p[i]] = classes-1;\n\t}\n\t\n\tvector<int> pn(n);\n\tvector<int> cn(n);\n\tfor (int h=0; (1<<h)<n; ++h) {\n\t\tfor (int i=0; i<n; ++i) {\n\t\t\tpn[i] = p[i] - (1<<h);\n\t\t\tif (pn[i] < 0)  pn[i] += n;\n\t\t}\n\t\tcnt.assign(classes, 0);\n\t\tfor (int i=0; i<n; ++i)\n\t\t\t++cnt[c[pn[i]]];\n\t\tfor (int i=1; i<classes; ++i)\n\t\t\tcnt[i] += cnt[i-1];\n\t\tfor (int i=n-1; i>=0; --i)\n\t\t\tp[--cnt[c[pn[i]]]] = pn[i];\n\t\tcn[p[0]] = 0;\n\t\tclasses = 1;\n\t\tfor (int i=1; i<n; ++i) {\n\t\t\tint mid1 = (p[i] + (1<<h)) % n,  mid2 = (p[i-1] + (1<<h)) % n;\n\t\t\tif (c[p[i]] != c[p[i-1]] || c[mid1] != c[mid2])\n\t\t\t\t++classes;\n\t\t\tcn[p[i]] = classes-1;\n\t\t}\n\t\tc = cn;\n\t}\n\t\n\treturn p;\n}\n \nvector<int> v1;\n/// compares the subarray of array v1 starting at index i1 with array v2\nbool comp(int i1, vector<int> v2) {\n\tint len1 = v1.size() - i1;\n\tint len2 = v2.size();\n\tint len = min(len1, len2);\n\tfor (int i = 0 ; i < len ; i++)\n\t\tif (v1[i1 + i] != v2[i]) {\n\t\t\treturn v1[i1 + i] < v2[i];\n\t\t}\n\tif (len1 != len2) return len1 < len2;\n\treturn false;\n}\n \nint findNumberOfOccurences(vector<int> v, vector<int> &pattern) {\n    if (pattern.size() == 0) return v.size() + 1;\n \n\tv.push_back(IntMinVal);\n    \n\tvector<int> suffixArray = calcSuffixArray(v);\n\t\n\tv1 = v;\n\t\n\tvector<int>::iterator it1 = lower_bound(suffixArray.begin(), suffixArray.end(), pattern, comp);\n\tpattern.back()++;\n\tvector<int>::iterator it2 = lower_bound(suffixArray.begin(), suffixArray.end(), pattern, comp);\n\t\n\treturn it2 - it1;\n}\n \nvector<int> toDiffArray(vector<int> &v) {\n    vector<int> result;\n    for (int i = 1 ; i < v.size() ; i++)\n        result.push_back(v[i] - v[i - 1]);\n    return result;\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n \n    int n; cin >> n;\n    int m; cin >> m;\n\t\n    vector<int> a = readVector<int>(n);\n    vector<int> b = readVector<int>(m);\n \n    vector<int> aDiff = toDiffArray(a);\n    vector<int> bDiff = toDiffArray(b);\n \n    int result = findNumberOfOccurences(aDiff, bDiff);\n \n    cout << result;\n}",
    "tags": [
      "string suffix structures",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "471",
    "index": "E",
    "title": "MUH and Lots and Lots of Segments",
    "statement": "Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to do some painting. As they were trying to create their first masterpiece, they made a draft on a piece of paper. The draft consists of $n$ segments. Each segment was either horizontal or vertical. Now the friends want to simplify the draft by deleting some segments or parts of segments so that the final masterpiece meets three conditions:\n\n- Horace wants to be able to paint the whole picture in one stroke: by putting the brush on the paper and never taking it off until the picture is ready. The brush can paint the same place multiple times. That's why all the remaining segments must form a single connected shape.\n- Menshykov wants the resulting shape to be simple. He defines a simple shape as a shape that doesn't contain any cycles.\n- Initially all the segment on the draft have integer startpoint and endpoint coordinates. Uslada doesn't like real coordinates and she wants this condition to be fulfilled after all the changes.\n\nAs in other parts the draft is already beautiful, the friends decided to delete such parts of the draft that the sum of lengths of the remaining segments is as large as possible. Your task is to count this maximum sum of the lengths that remain after all the extra segments are removed.",
    "tutorial": "Given a set of horizontal/vertical lines you need to erase some parts of the lines or some lines completely in order to receive single connected drawing with no cycles. First of all let's go through naive $N^{2}$ solution which won't even remove cycles. In order to solve this problem you will need a DSU data structure, you put all your lines there and then for every pair of horizontal and vertical line you check if they intersect and if they do you join them in DSU. Also your DSU should hold the sum of the lengths of the joined lines. Initially it should be equal to the line lengths. Since there might be up to $N^{2} / 4$ intersections between lines we receive a quadratic solution. Now let's get rid of cycles. Having the previous solution we can do it pretty easily, all we need is to change the way we were connecting the sets in DSU if some lines intersect. Previously we were simply asking DSU to join them even if they already belong to the same set. Now what we will do is when finding some pair of lines which intersects and is already joined in DSU instead of asking DSU to join them again we will ask DSU to decrement their length sum. In terms of the problem it is equivalent to erasing a unit piece of segment in the place where these two lines intersect and this will break the cycle. With this change we already have a correct solution which is too slow to pass the time limits. Now we need to make our solution work faster. We still might have up to $N^{2} / 4$ intersections so obviously if we want to have a faster solution we can't afford to process intersections one by one, we need to process them in batches. All our lines are horizontal and vertical only, so let's do a sweep line, this should make our life easier. Let's assume that we're sweeping the lines from the left to the right. Obviously then the code where the intersections will be handled is the code where we process the vertical line. Let's look at this case closer. We can assume that we're going to add some vertical line on with coordinates $(x, y1, x, y2)$, we can also assume that there are some horizontal lines which go through the given $x$ coordinate, we track this set of lines while sweeping left to right. So we're going to add a vertical line and let's say that it has $n$ intersections with horizontal line. Previously we were handling each intersection separately, but you can see that if some horizontal lines already belong to the same set in DSU and they go next to each other then we don't need to handle them one by one anymore. They already belong to the set in DSU so there is no need to join them, we might only need to count the number of them between $y1$ and $y2$ coordinates, but that can be calculated in logarithmic time. So the trick to get rid of quadratic time complexity is to avoid storing horizontal lines one by one and store instead an interval (across y coordinate) of horizontal lines which belong to the same set in DSU. I will call these intervals chunks. You will need to manipulate these chunks in logarithmic time and you will need to locate them by y coordinate so you need to store them in a treap or a STL map for example with $y$ coordinate serving as a key. To be clear let's see what data each of these chunks will hold: struct chunk{ int top, bottom; // two coordinates which describe the interval covered by the chunk int id; // id of this chunk in DSU. Several chunks might have the same id here if they belong to the same set in DSU }; And we agreed that data structure which holds these chunks can manipulate them in logarithmic time. Let's now get into details to see how exactly it works. While sweeping we will have one of three possible events (listed in the order we need to handle them): new horizontal line starting, vertical line added, horizontal line finishing. First and third operation only update our chunks data structure while the second operation uses it and actually joins the sets. Let's look into each of these operations: horizontal line start. We need to add one more chunk which will consist of a single point. The only additional operation we might need to do happens when this new line goes through some chunk whose interval already covers this point. In this case we need to split this covering chunk into two parts - top and bottom one. It's a constant number of updates/insertions/removals in our chunk data structure and we agreed that each of these operations can be done in logarithmic time so the time complexity of a single operation of this time is $O(logN)$. It should be also mentioned here that during processing a single operation of this type we might add at most two new blocks. Since in total we have no more than $N$ operations of this type them it means that in total we will have no more than $2 \\cdot N$ blocks created. This is important for the further analysis. vertical line. In this operation we need to find all chunks affected by this vertical line and join them. Each join of two chunks takes logarithmic time and we might have up to $n$ chunks present there, so we might need up $O(NlogN)$ time to draw a single vertical line. This doesn't give us a good estimate. But we can see that we have only two ways to get new chunks - they are either added in the step 1 because it's a new line or one chunk is being split into two when we add a line in between. But we have an upper bound on total number of the chunks in our structure as shown above. Ans since we have such an upper bound then we can say that it doesn't matter how many chunks will join a single vertical line because in total all vertical lines will not join more than $2 \\cdot N$ chunks. So we have an amortized time complexity analysis here, in total all vertical line operations will take $O(NlogN)$ time. There are some other details we need to handle here. For example we need to avoid cycles correctly. This margin is too narrow to contain the proof but the formulae to correct the length sum is like this: $d = y2 - y1 - (N_{intersections} - 1) + N_{distinctsets} - 1$ where $d$ - the number you need to add to the sum of the lengths in DSU $N_{intersections}$ - number of horizontal lines intersecting with the given vertical line, I used a separate segment tree to get this value in $O(logN)$ $N_{distinctsets}$ - number of distinct sets in DSU joined by this vertical line, you need to count them while joining So this gives you a way to correct the lengths sums. There is one more thing that needs to be mentioned here - it might happen that your vertical line will be contained by some chunk but will not intersect any horizontal lines in it. In this case you simply ignore this vertical line as if it doesn't overlap any chunk at all. horizontal line end. Finally we came here and it seems to be simple. When some horizontal line ends we might need to update our chunks. There are three cases here: a. This line is the only line in the chunks - we simply delete the chunk then. b. This line lays on some end of the interval covered by the chunk - we update that end. In order to update it we need to know the next present horizontal line or the previous present horizontal line. I used the same segment tree mentioned above to handle these queries. c. This line lays inside some chunk - we don't need to update that chunk at all. And that's it! In total it gives $O(NlogN)$ solution.",
    "code": "#include <algorithm>\n#include \"assert.h\"\n#include <deque>\n#include <iostream>\n#include <map>\n#include <set>\n#include <stack>\n#include <vector>\n \ntypedef long long LL;\n \n#define all(v) v.begin(),v.end() \n \nint IntMaxVal = (int) 1e20;\nint IntMinVal = (int) -1e20;\n \n#define FOR(i, a, b) for(int i = a; i < b ; ++i)\n#define FORD(i, a, b) for(int i = a; i >= b; --i)\n \ntemplate<typename T> inline void maximize(T &a, T b) { a = std::max(a, b); }\n \nusing namespace std;\n \nclass {\n\tvector<int> parent;\n\tvector<int> size;\n\t\n\tvector<LL> perimeter;\n\t\n\tpublic:\n\t\n\tvoid init(int n) {\n\t\tparent.resize(n);\n\t\tfor (int i = 0 ; i < n ; i++) parent[i] = i;\n\t\tsize.assign(n, 1);\n\t\tperimeter.resize(n);\n\t}\n\t\n\tint get(int v) {\n\t\tif (v == parent[v]) return v;\n\t\treturn parent[v] = get(parent[v]);\n\t}\n\t\n\tint join(int a, int b) {\n\t\ta = get(a);\n\t\tb = get(b);\n\t\t\n\t\tif (a == b) return a;\n\t\t\n\t\tif (size[a] < size[b]) swap(a, b);\n\t\t\n\t\tsize[a] += size[b];\n\t\tperimeter[a] += perimeter[b];\n\t\tparent[b] = a;\n\t\t\n\t\treturn a;\n\t}\n\t\n\tvoid add_perimeter(int v, LL addition) {\n\t\tv = get(v);\n\t\tperimeter[v] += addition;\n\t}\n\t\n\tLL get_perimeter(int v) {\n\t\tv = get(v);\n\t\treturn perimeter[v];\n\t}\n} dsu;\n \nstruct list_element {\n\tint top;\n\tint bottom;\n\t\n\tint id;\n\t\t\n\tlist_element(int y, int id) {\n\t\ttop = bottom = y;\n\t\tthis->id = id;\n\t}\n};\n \nstruct {\n\tint gp2(int n) {\n\t\tint x = 2;\n\t\twhile (x < n) x *= 2;\n\t\treturn x;\n\t}\n\t\n\tint n;\n\tvector<int> points_count;\n\tvector<int> leftmost;\n\tvector<int> rightmost;\n\tvector<int> leftmost_set_element;\n\tvector<int> rightmost_set_element;\n \n\tvoid init(vector<int> points) {\n\t\tsort(all(points));\n\t\tpoints.resize(unique(all(points)) - points.begin());\n\t\tn = gp2(points.size());\n\t\t\n\t\tpoints_count.resize(2 * n);\n\t\tleftmost.assign(2 * n, IntMaxVal);\n\t\trightmost.assign(2 * n, IntMaxVal);\n\t\tFOR (i, 0, points.size()) leftmost[n + i] = rightmost[n + i] = points[i];\n\t\tFORD (i, n - 1, 1) leftmost[i] = leftmost[2 * i];\n\t\tFORD (i, n - 1, 1) rightmost[i] = rightmost[2 * i + 1];\n\t\t\n\t\tleftmost_set_element.assign(2 * n, IntMaxVal);\n\t\trightmost_set_element.assign(2 * n, IntMinVal);\n\t}\n\t\n\tvoid update(int key, int val) {\n\t\tint ptr = 1;\n\t\twhile (ptr < n) {\n\t\t\tptr *= 2;\n\t\t\tif (leftmost[ptr + 1] <= key) ptr++;\n\t\t}\n\t\tpoints_count[ptr] = val;\n\t\tleftmost_set_element[ptr] = val ? leftmost[ptr] : IntMaxVal;\n\t\trightmost_set_element[ptr] = val ? leftmost[ptr] : IntMinVal;\n\t\t\n\t\tptr /= 2;\n\t\twhile (ptr) {\n\t\t\tpoints_count[ptr] = points_count[2 * ptr] + points_count[2 * ptr + 1];\n\t\t\tleftmost_set_element[ptr] = min(leftmost_set_element[2 * ptr] , leftmost_set_element[2 * ptr + 1]);\n\t\t\trightmost_set_element[ptr] = max(rightmost_set_element[2 * ptr] , rightmost_set_element[2 * ptr + 1]);\n\t\t\tptr /= 2;\n\t\t}\n\t}\n\t\n\tvoid add(int y) {\n\t\tupdate(y, 1);\n\t}\n\t\n\tvoid remove(int y) {\n\t\tupdate(y, 0);\n\t}\n\t\n\t/// returns number of lines between y1 and y2 (both including);\n\tint count(int y1, int y2, int i = 1) {\n\t\tif (leftmost[i] >= y1 && rightmost[i] <= y2) return points_count[i];\n\t\tif (leftmost[i] > y2 || rightmost[i] < y1) return 0;\n\t\t\n\t\treturn count(y1, y2, 2 * i) + count(y1, y2, 2 * i + 1);\n\t}\n\t\n\tint get_first_after(int y, int ptr = 1) {\n\t\tif (leftmost[ptr] > y) return leftmost_set_element[ptr];\n\t\tif (rightmost[ptr] <= y) return IntMaxVal;\n\t\treturn min(get_first_after(y, 2 * ptr),\n\t\t\t\t   get_first_after(y, 2 * ptr + 1));\n\t}\n \n\tint get_last_before(int y, int ptr = 1) {\n\t\tif (rightmost[ptr] < y) return rightmost_set_element[ptr];\n\t\tif (leftmost[ptr] >= y) return IntMinVal;\n\t\treturn max(get_last_before(y, 2 * ptr),\n\t\t\t\t   get_last_before(y, 2 * ptr + 1));\n\t}\n} current_horizontal_lines;\n \nstruct {\n\tmap<int, list_element*> elements;\n\t\n\tlist_element* find_first(int y) {\n\t\tmap<int, list_element*>::iterator it = elements.lower_bound(y);\n\t\tif (it == elements.end()) return NULL;\n\t\treturn it->second;\n\t}\n\t\t\n\tvoid insert(list_element* newElement) {\n\t\telements[newElement->top] = newElement;\n\t}\n \n\t// splits an element into two parts (below the given Y and above it)\n\tvoid split(list_element* element, int y) {\n\t\tassert(element->bottom < y);\n\t\tassert(element->top > y);\n\t\t\n\t\tint bottom = element->bottom;\n\t\telement->bottom = current_horizontal_lines.get_first_after(y);\n\t\t\n\t\tlist_element* bottom_part = new list_element(bottom, element->id);\n\t\tbottom_part->top = current_horizontal_lines.get_last_before(y);\n\t\tinsert(bottom_part);\n\t}\n\t\t\n\tvoid remove(list_element* element) {\n\t\telements.erase(element->top);\n\t}\n\t\n\tvoid debug_print() {\n\t\tcout << \"List contents : \" << endl;\n\t\tmap<int, list_element*>::iterator ptr = elements.begin();\n\t\twhile (ptr != elements.end()) {\n\t\t\tcout << \"( \" << ptr->second->bottom << \" , \" << ptr->second->top << \" ) \" << endl;\n\t\t\tptr++;\n\t\t}\n\t}\n} linked_list;\n \nstruct vertical_line {\n\tint x, y1, y2, id;\n};\n \nstruct horizontal_line_point {\n\tint x, y, id;\n};\n \nvoid start_horizontal_line(horizontal_line_point &point) {\n\tlist_element* first_after = linked_list.find_first(point.y);\n\tlist_element* newElement = new list_element(point.y, point.id);\n \n\tcurrent_horizontal_lines.add(point.y);\n\t\n\tif (first_after != NULL && first_after->bottom < point.y) {\n\t\tlinked_list.split(first_after, point.y);\n\t}\n\tlinked_list.insert(newElement);\n}\n \nvoid sweep_vertical(vertical_line &line) {\n\tlist_element* firstAfter = linked_list.find_first(line.y1);\n\tif (firstAfter == NULL || firstAfter->bottom > line.y2 || current_horizontal_lines.count(line.y1, line.y2) == 0) return;\n\tint different_line_sets = 0;\n\t\n\twhile (true) {\n\t\tlist_element* next_element = linked_list.find_first(firstAfter->top + 1);\n\t\tif (next_element == NULL || next_element->bottom > line.y2) break;\n\t\tif (dsu.get(firstAfter->id) != dsu.get(next_element->id)) {\n\t\t\tnext_element->id = dsu.join(firstAfter->id, next_element->id);\n\t\t\tdifferent_line_sets++;\n\t\t}\n\t\tnext_element->bottom = firstAfter->bottom;\n\t\tlinked_list.remove(firstAfter);\n\t\tfirstAfter = next_element;\n\t}\n\t\n\tdsu.join(firstAfter->id , line.id);\n\t\n\tint perimeter_add = 0;\n\tperimeter_add -= current_horizontal_lines.count(line.y1 , line.y2) - 1;\n\tperimeter_add += different_line_sets;\n\t\n\tdsu.add_perimeter(firstAfter->id, perimeter_add);\n}\n \nvoid end_horizontal_line(horizontal_line_point &point) {\n\tcurrent_horizontal_lines.remove(point.y);\n\t\n\tlist_element* element = linked_list.find_first(point.y);\n\tassert(element != NULL);\n\tassert(element->bottom <= point.y);\n \n\tif (element->bottom == element->top) {\n\t\tlinked_list.remove(element);\n\t} else if (element->bottom == point.y) {\n\t\telement->bottom = current_horizontal_lines.get_first_after(point.y);\n\t} else if (element->top == point.y) {\n\t\tlinked_list.remove(element);\n\t\telement->top = current_horizontal_lines.get_last_before(point.y);\n\t\tlinked_list.insert(element);\n\t}\n}\n \ntemplate <typename T> bool leftToRight(const T &x, const T &y) {\n\treturn x.x < y.x;\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n\tdeque<vertical_line> vertical_lines;\n\tdeque<horizontal_line_point> horizontal_line_starts;\n\tdeque<horizontal_line_point> horizontal_line_ends;\n\t\n\tint n; cin >> n;\n\tdsu.init(n);\n\t\n\tvector<int> horizontal_line_ys;\n\t\n\tFOR (i, 0, n) {\n\t\tint x1, y1, x2, y2;\n\t\tcin >> x1 >> y1 >> x2 >> y2;\n \n\t\tif (x1 == x2) {\n\t\t\tvertical_line line = { x1, min(y1, y2), max(y1, y2) , i };\n\t\t\tvertical_lines.push_back( line );\n\t\t} else {\n\t\t\thorizontal_line_point start = { min(x1, x2) , y1 , i };\n\t\t\thorizontal_line_point end = { max(x1, x2) , y1 , i };\n\t\t\t\n\t\t\thorizontal_line_starts.push_back(start);\n\t\t\thorizontal_line_ends.push_back(end);\n\t\t\thorizontal_line_ys.push_back(y1);\n\t\t}\n\t\tdsu.add_perimeter(i, x2 - x1 + y2 - y1);\n\t}\n\t\n\tsort(all(vertical_lines), leftToRight<vertical_line>);\n\tsort(all(horizontal_line_starts), leftToRight<horizontal_line_point>);\n\tsort(all(horizontal_line_ends), leftToRight<horizontal_line_point>);\n\t\n\tvertical_line vLine_stub = { IntMaxVal , 0 , 0 };\n\thorizontal_line_point hPoint_stub = { IntMaxVal , 0 , 0 };\n\t\n\tvertical_lines.push_back(vLine_stub);\n\thorizontal_line_starts.push_back(hPoint_stub);\n\thorizontal_line_ends.push_back(hPoint_stub);\n \n\tcurrent_horizontal_lines.init(horizontal_line_ys);\n\t\t\n\twhile (vertical_lines.size() > 1 || horizontal_line_starts.size() > 1 || horizontal_line_ends.size() > 1) {\n\t\tint minX = min(vertical_lines.front().x,\n\t\t\t\t   min(horizontal_line_starts.front().x,\n\t\t\t\t\t   horizontal_line_ends.front().x));\n\t\tif (horizontal_line_starts.front().x == minX) {\n\t\t\tstart_horizontal_line(horizontal_line_starts.front());\n\t\t\thorizontal_line_starts.pop_front();\n\t\t} else if (vertical_lines.front().x == minX) {\n\t\t\tsweep_vertical(vertical_lines.front());\n\t\t\tvertical_lines.pop_front();\n\t\t} else {\n\t\t\tend_horizontal_line(horizontal_line_ends.front());\n\t\t\thorizontal_line_ends.pop_front();\n\t\t}\n\t}\n\t\n\tLL result = 0;\n\tFOR (i, 0, n) maximize(result, dsu.get_perimeter(i));\n\t\n\tcout << result;\n}",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 2700
  },
  {
    "contest_id": "472",
    "index": "A",
    "title": "Design Tutorial: Learn from Math",
    "statement": "One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.\n\nFor example, there is a statement called the \"Goldbach's conjecture\". It says: \"each even number no less than four can be expressed as the sum of two primes\". Let's modify it. How about a statement like that: \"each integer no less than 12 can be expressed as the sum of two composite numbers.\" Not like the Goldbach's conjecture, I can prove this theorem.\n\nYou are given an integer $n$ no less than 12, express it as a sum of two composite numbers.",
    "tutorial": "One way to solve this is by bruteforce: there are O(n) different ways to decomose n as sum of two number. If we can check if a number is a prime in O(1) then the whole algorithm can run in O(n). You can use Sieve of Eratosthenes to do the pre-calculation. And another way is try to prove this theorem. The prove is simple: if n is odd number, then 9 and (n-9) is an answer (n-9 is an even number at least 4, so a composite number), and if n is even number, then 8 and (n-8) is an answer (n-8 is an even number at least 4, also must be a composite number).",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "472",
    "index": "B",
    "title": "Design Tutorial: Learn from Life",
    "statement": "One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.\n\nLet's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have $n$ people standing on the first floor, the $i$-th person wants to go to the $f_{i}$-th floor. Unfortunately, there is only one elevator and its capacity equal to $k$ (that is at most $k$ people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs $|a - b|$ seconds to move from the $a$-th floor to the $b$-th floor (we don't count the time the people need to get on and off the elevator).\n\nWhat is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?",
    "tutorial": "This task can be solve by greedy: the k people with highest floor goes together, and next k people with highest floor goes together and so on. So the answer is 2 * ((f[n]-1) + (f[n-k]-1) + (f[n-2k]-1) + ...) . It is a bit tricky to prove the correctness of greedy, since people can get off the elevator and take it again. We can give a lower bound of the answer by flow analysis: between floor i and floor i+1, there must be no more than (# of f[i] >= i+1) / k times the elevator goes up between these 2 floors, and then there be same number of times goes down. We can find this lower bound matches the answer by above greedy algorithm, so it means the greedy algorithm gives an optimal answer.",
    "tags": [],
    "rating": 1300
  },
  {
    "contest_id": "472",
    "index": "C",
    "title": "Design Tutorial: Make It Nondeterministic",
    "statement": "A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.\n\nLet's try to make a new task. Firstly we will use the following task. There are $n$ people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are $n$ people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation $p$?\n\nMore formally, if we denote the handle of the $i$-th person as $h_{i}$, then the following condition must hold: $\\forall\\ i,j\\ (i<\\j)\\cdot\\ h_{p_{i}}<h_{p_{i}}$.",
    "tutorial": "This one laso can be solved by greedy, let's think in this way: let pick one with smallest handle, then we let him/her use min(firstName, secondName) as handle. And go for the next one (2nd mallest handle), now he/she must choose a handle greater than handle of previous person, and if both meet this requirement, he/she can pick a small one. This time the correctness of this greedy solution can be proved by exchange argument. Note that if we change the goal of this problem: ask number of different permutations they can get, then it will be very hard. (I tried it for hours but can't solve.)",
    "tags": [
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "472",
    "index": "D",
    "title": "Design Tutorial: Inverse the Problem",
    "statement": "There is an easy way to obtain a new task from an old one called \"Inverse the problem\": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example.\n\nNow let's create a task this way. We will use the task: you are given a tree, please calculate the distance between any pair of its nodes. Yes, it is very easy, but the inverse version is a bit harder: you are given an $n × n$ distance matrix. Determine if it is the distance matrix of a weighted tree (all weights must be positive integers).",
    "tutorial": "Let's think it in the following way: for the minimal length edge, it must belong the the tree, ..., for the k-th minimal length edge(a, b), if there is already an path between a-b, then it can not be an edge of tree anymore, otherwise it must be edge of tree, why? Because otherwise there must be a path from a to b in the tree, that means a and b can be connected by edges with less length, but a and b is not connected. So this Kruskal style analysis gives us this theorem: if there is an answer, then the answer must be the MST of that graph. (You can also guess this theorem and try to prove it.) You can solve MST in O(n^2 log n), and then there are many way to check distance between notes on tree: you can just simply do dfs or bfs from each node, it can run in O(n^2). Or if you have pre-coded LCA algorithm, it can run in O(n^2 log n).",
    "tags": [
      "dfs and similar",
      "dsu",
      "shortest paths",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "472",
    "index": "E",
    "title": "Design Tutorial: Learn from a Game",
    "statement": "One way to create task is to learn from game. You should pick a game and focus on part of the mechanic of that game, then it might be a good task.\n\nLet's have a try. Puzzle and Dragon was a popular game in Japan, we focus on the puzzle part of that game, it is a tile-matching puzzle.\n\n\\begin{center}\n(Picture from Wikipedia page: http://en.wikipedia.org/wiki/Puzzle_&_Dragons)\n\\end{center}\n\nThere is an $n × m$ board which consists of orbs. During the game you can do the following move. In the beginning of move you touch a cell of the board, then you can move your finger to one of the adjacent cells (a cell not on the boundary has 8 adjacent cells), then you can move your finger from the current cell to one of the adjacent cells one more time, and so on. Each time you move your finger from a cell to another cell, the orbs in these cells swap with each other. In other words whatever move you make, the orb in the cell you are touching never changes.\n\nThe goal is to achieve such kind of pattern that the orbs will be cancelled and your monster will attack the enemy, but we don't care about these details. Instead, we will give you the initial board as an input and the target board as an output. Your goal is to determine whether there is a way to reach the target in a single move.",
    "tutorial": "First let's solve some special cases: If the initial board and the target board contains different orbs, then there can't be a solution. If n = 1 (or m = 1), then we can try all O(m^2) (or O(n^2)) possible moves. And for the other cases, there always have solution. We first hold the orb with number target[1][1] in initial board. Then we want to move other orbs to their position. So let's come up with a process to move orb from (a, b) to (c, d): it must be some continue path from (a, b) to (c, d), so we want to build a single move: it will move an orb from (a, b) to an adjacent cell (c, d). How to do that? We can move our touching orb to (c, d) first, and then move to (a, b). But there are some concerns: in this move, the touching orb shouldn't pass any already-done cells, and it shouldn't pass (a, b) when we get to (c, d). That means we need a good order to move orbs. We can do it in this way: first, as long as there are more than 2 rows, we move the orbs to last row (from left to right or right to left). And then it must be 2xm boards: we do it column by column from right to left. We can find that in this order, there always exist paths for our touching orb to get (c, d).",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 2800
  },
  {
    "contest_id": "472",
    "index": "F",
    "title": "Design Tutorial: Change the Goal",
    "statement": "There are some tasks which have the following structure: you are given a model, and you can do some operations, you should use these operations to achive the goal. One way to create a new task is to use the same model and same operations, but change the goal.\n\nLet's have a try. I have created the following task for Topcoder SRM 557 Div1-Hard: you are given $n$ integers $x_{1}, x_{2}, ..., x_{n}$. You are allowed to perform the assignments (as many as you want) of the following form $x_{i}$ ^= $x_{j}$ (in the original task $i$ and $j$ must be different, but in this task we allow $i$ to equal $j$). The goal is to maximize the sum of all $x_{i}$.\n\nNow we just change the goal. You are also given $n$ integers $y_{1}, y_{2}, ..., y_{n}$. You should make $x_{1}, x_{2}, ..., x_{n}$ exactly equal to $y_{1}, y_{2}, ..., y_{n}$. In other words, for each $i$ number $x_{i}$ should be equal to $y_{i}$.",
    "tutorial": "You need to know some knowledge about linear algebra and notice the operation of xor on 32 bit integers equals to + operation in a 32 dimension linear space. If you don't know, you should learn it from the editorial of similar tasks, for example, Topcoder SRM 557 Div1-Hard. We need to know some basic properties of our operation: we can swap two number a and b by: a^=b, b^=a, a^=b. This operation is inversible, the inverse is itself. By property 1 we can do the Gaussian elimination of each set of vectors. By property 2 we can use this way to build an answer: use some operation to make A[] into a base (linear independent vectors that the span will be A[]), then transfer it into a base of B[], then use the inverse of Gaussian elimination to recover B[]. So now we have two bases: {a1, a2, ..., ax} and {b1, b2, ..., by}. If there exists some bi such that it can't be expressed as a linear combination of {a1, a2, ..., ax}, the solution can't exists. Otherwise there always exists a solution: first we build b1 and put it in the first position. Suppose b1 = a2 ^ a3 ^ a8, then we swap any of them, say, a2 into position one, and then xor it with a3 and a8, then we get b1. Note that after this operation {a1, a2, ..., ax} will remain a base. And we need to ensure we don't erase already-done numbers in a.",
    "tags": [
      "constructive algorithms",
      "math",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "472",
    "index": "G",
    "title": "Design Tutorial: Increase the Constraints",
    "statement": "There is a simple way to create hard tasks: take one simple problem as the query, and try to find an algorithm that can solve it faster than bruteforce. This kind of tasks usually appears in OI contest, and usually involves data structures.\n\nLet's try to create a task, for example, we take the \"Hamming distance problem\": for two binary strings $s$ and $t$ with the same length, the Hamming distance between them is the number of positions at which the corresponding symbols are different. For example, the Hamming distance between \"\\textbf{0}01\\textbf{1}1\" and \"\\textbf{1}01\\textbf{0}1\" is 2 (the different symbols are marked with bold).\n\nWe use the Hamming distance problem as a query in the following way: you are given two strings $a$ and $b$ and several queries. Each query will be: what is the Hamming distance between two strings $a_{p1}a_{p1 + 1}...a_{p1 + len - 1}$ and $b_{p2}b_{p2 + 1}...b_{p2 + len - 1}$?\n\nNote, that in this problem the strings are \\textbf{zero-based}, that is $s = s_{0}s_{1}... s_{|s| - 1}$.",
    "tutorial": "Let's start with a simpler task: we have string A and B (|A|, |B| <= n), we have q queries and each query we ask the Hamming distance between A and a substring of B with length equals to |A|. How to solve this? We need to notice compute A with different offset of B is similar to the computation of convolution, so it can be done by FFT. We use +1 to replace '1' and we use -1 to replace '0', and then we do the convolution of A and reverse B. We can extract the answer of all possible query of \"the Hamming distance between A and a substring of B with length equals to |A|.\"! Then let's come back to our problem, how to use this way to make a faster solution? We can use a way like sqrt decompose: we divide A into L blocks, for each block, we compute the convolution of this part with B, it will takes O(n*L*logn). And for each query, we can use the pre-calculated results to speedup (if a whole block contains in the query, we can compute it in O(1)). So each query needs no more than O(L) operation. If n = q then this solution can run in O((n*logn) ^ 1.5). But in practice it has some issues: for example, we can use bit operation to speedup like __builtin_popcount(). I tried to set constraints to fail solution with only bit optimization, but seems I failed: I apologies to allow this kind of solutions passed. (I used __builtin_popcount() to test such solution, but in fact cnt[x<<16] + cnt[x>>16] is much faster than the builtin fucnion)",
    "tags": [
      "bitmasks",
      "data structures",
      "fft"
    ],
    "rating": 2800
  },
  {
    "contest_id": "474",
    "index": "A",
    "title": "Keyboard",
    "statement": "Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:\n\n\\begin{verbatim}\nqwertyuiop\nasdfghjkl;\nzxcvbnm,./\n\\end{verbatim}\n\nUnfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally moved both his hands with one position to the left or to the right. That means that now he presses not a button he wants, but one neighboring button (left or right, as specified in input).\n\nWe have a sequence of characters he has typed and we want to find the original message.",
    "tutorial": "This is an implementation problem, therefore most of the solution fit in the time limit. We can even save the keyboard in $3$ strings and make a brute force search for each character to find its position and then print the left/right neighbour.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "474",
    "index": "B",
    "title": "Worms",
    "statement": "It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.\n\nMarmot brought Mole $n$ ordered piles of worms such that $i$-th pile contains $a_{i}$ worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers $1$ to $a_{1}$, worms in second pile are labeled with numbers $a_{1} + 1$ to $a_{1} + a_{2}$ and so on. See the example for a better understanding.\n\nMole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.\n\nPoor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.",
    "tutorial": "There are two solutions: We can make partial sums ($sum_{i} = a_{1} + a_{2} + ... + a_{i}$) and then make a binary search for each query $q_{i}$ to find the result $j$ with the properties $sum_{j - 1} < q_{i}$ and $sum_{j}  \\ge  q_{i}$. This solution has the complexity $O(n + m \\cdot log(n))$ We can precalculate the index of the pile for each worm and then answer for each query in $O(1)$. This solution has the complexity $O(n + m)$",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "474",
    "index": "C",
    "title": "Captain Marmot",
    "statement": "Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has $n$ regiments, each consisting of $4$ moles.\n\nInitially, each mole $i$ ($1 ≤ i ≤ 4n$) is placed at some position $(x_{i}, y_{i})$ in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments \\textbf{compact}, if it's possible.\n\nEach mole $i$ has a home placed at the position $(a_{i}, b_{i})$. Moving this mole one time means rotating his position point $(x_{i}, y_{i})$ $90$ degrees counter-clockwise around it's home point $(a_{i}, b_{i})$.\n\nA regiment is \\textbf{compact} only if the position points of the $4$ moles form a square with non-zero area.\n\nHelp Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.",
    "tutorial": "For each $4$ points we want to see if we can rotate them with $90$ degrees such that we obtain a square. We can make a backtracking where we rotate each point $0, 1, 2$ or $3$ times and verify the figure obtained. If it's a square we update the minimal solution. Since we can rotate each point $0, 1, 2$ or $3$ times, for each regiment we have $4^{4}$ configurations to check. So the final complexity is about $O(n)$.",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 2000
  },
  {
    "contest_id": "474",
    "index": "D",
    "title": "Flowers",
    "statement": "We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.\n\nBut, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size $k$.\n\nNow Marmot wonders in how many ways he can eat between $a$ and $b$ flowers. As the number of ways could be very large, print it modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "We can notate each string as a binary string, instead of red and white flowers. A string of this type is good only if every maximal contigous subsequence of \"$0$\" has the length divisible by $k$. We can make dynamic programming this way : $nr_{i}$ = the number of good strings of length $i$. If the $i$-th character is \"$1$\" then we can have any character before and if the $i$-th character is \"$0$\" we must have another $k - 1$ \"$0$\" characters before, so $nr_{i} = nr_{i - 1} + nr_{i - k}$ for $i  \\ge  k$ and $nr_{i} = 1$ for $i < k$. Then we compute the partial sums ($sum_{i} = nr_{1} + nr_{2} + ... + nr_{i}$) and for each query the result will be $sum_{b} - sum_{a - 1}$. This solution has the complexity $O(maxVal + t)$, where $maxVal$ is the maximum value of $b_{i}$.",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "474",
    "index": "E",
    "title": "Pillars",
    "statement": "Marmot found a row with $n$ pillars. The $i$-th pillar has the height of $h_{i}$ meters. Starting from one pillar $i_{1}$, Marmot wants to jump on the pillars $i_{2}$, ..., $i_{k}$. ($1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ n$). From a pillar $i$ Marmot can jump on a pillar $j$ only if $i < j$ and $|h_{i} - h_{j}| ≥ d$, where $|x|$ is the absolute value of the number $x$.\n\nNow Marmot is asking you find out a jump sequence with maximal length and print it.",
    "tutorial": "We have to find a substring $i_{1}, i_{2}, ..., i_{k}$ such that $abs(h_{ij} - h_{ij + 1})  \\ge  D$ for $1  \\le  j < k$. Let's suppose that the values in $h$ are smaller. We can make dynamic programming this way : $best_{i}$ = the maximal length of such a substring ending in the $i$-th position, $best_{i} = max(best_{j}) + 1$ with $j < i$ and $h_{j}  \\ge  D + h_{i}$ or $h_{j}  \\le  h_{i} - D$. So we can easily search this maximum in a data structure, such as an segment tree or Fenwick tree. But those data structure must have the size of $O(maxH)$ which can be $10^{9}$. For our constraints we mantain the idea described above, but instead of going at some specific position in the data structure based on a value, we would normalize the values in $h$ and binary search the new index where we should go for an update or a query in the data structure. Therefore, the data structure will have the size $O(n)$. The complexity of this solution is $O(n \\cdot log(n))$.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "sortings",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "474",
    "index": "F",
    "title": "Ant colony",
    "statement": "Mole is hungry again. He found one ant colony, consisting of $n$ ants, ordered in a row. Each ant $i$ ($1 ≤ i ≤ n$) has a strength $s_{i}$.\n\nIn order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$) and each pair of ants with indices between $l$ and $r$ (inclusively) will fight. When two ants $i$ and $j$ fight, ant $i$ gets one battle point only if $s_{i}$ divides $s_{j}$ (also, ant $j$ gets one battle point only if $s_{j}$ divides $s_{i}$).\n\nAfter all fights have been finished, Mole makes the ranking. An ant $i$, with $v_{i}$ battle points obtained, is going to be freed only if $v_{i} = r - l$, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.\n\nIn order to choose the best sequence, Mole gives you $t$ segments $[l_{i}, r_{i}]$ and asks for each of them how many ants is he going to eat if those ants fight.",
    "tutorial": "For each subsequence $[L, R]$ we must find how many queens we have. A value is \"queen\" only if is the GCD of ($s_{L}, s_{L + 1}, ..., s_{R}$). Also, we must notice that the GCD of ($s_{L}, s_{L + 1}, ..., s_{R}$) can be only the minimum value from ($s_{L}, s_{L + 1}, ..., s_{R}$). So for each query we search in a data structure (a segment tree or a RMQ) the minimum value and the GCD of ($s_{L}, s_{L + 1}, ..., s_{R}$) and if these two values are equal then we output the answer $R - L + 1 - nrValues$, where $nrValues$ is the number of values in the subsequence equal to the GCD and the minimum value. The complexity of this solution is $O(n \\cdot log(n) \\cdot log(valMax) + t \\cdot log(n) \\cdot log(valMax))$, where $valMax$ is the maximum value of $s_{i}$.",
    "tags": [
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "475",
    "index": "A",
    "title": "Bayan Bus",
    "statement": "The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.\n\nThe event coordinator has a list of $k$ participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one.\n\nIn order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by $k$ participants. Your task is to draw the figure representing occupied seats.",
    "tutorial": "As usual for A we have an implementation problem and the main question is how to implement it quickly in the easiest (thus less error-prone) way. During the contest I spent almost no time thinking about it and decided to implement quite straightforward approach - start with empty string and concatenate different symbols to the end of it. The result is quite messy and worst of all I forgot one of the main principles in the [commercial] programming - separate logic from its presentation. The \"presentation\" here is all these bus characters which are all the same across different inputs. So I paid my price, my original solution failed on system tests. Much better approach afterwards I looked up in Swistakk's solution - you copy&paste the \"template\" of the bus from the example test into your source code, then you just change the characters for each of 34 possible seats. Result becomes much cleaner - 8140120.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nint main() {\n\tvector<string> result = {\n\"+------------------------+\",\n\"|O.O.O.O.O.O.O.#.#.#.#.|D|)\",\n\"|O.O.O.O.O.O.#.#.#.#.#.|.|\",\n\"|O.......................|\",\n\"|O.O.O.O.O.O.#.#.#.#.#.|.|)\",\n\"+------------------------+\"\n\t};\n\t\n\tint n; cin >> n;\n\t\n\tfor (int i = 1 ; i <= 34 ; i++) {\n\t\tchar c = i > n ? '#' : 'O';\n\t\tint row = i <= 4 ? 0 : (i - 2) / 3;\n\t\tint seat = i <= 4 ? i - 1 : (i - 5) % 3;\n\t\tif (seat == 2 && row != 0) seat++;\n\t\tresult[1 + seat][1 + row * 2] = c;\n\t}\n\tfor (auto s : result) cout << s << endl;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "475",
    "index": "B",
    "title": "Strongly Connected City",
    "statement": "Imagine a city with $n$ horizontal streets crossing $m$ vertical streets, forming an $(n - 1) × (m - 1)$ grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection.\n\nThe mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.",
    "tutorial": "For B we already might need some kind of algorithm to solve it, though for the constraints given you might use almost any approach. If you just have a directed graph then in order to check whether you can reach all nodes from all other nodes you can do different things - you can dfs/bfs from all nodes, two dfs/bfs from the single node to check that every other node has both paths to and from that node, or you can employ different \"min distance between all pairs of nodes\" algorithm. All of these seem to work fine for this problem. But we shouldn't ignore here that the input graph has a special configuration - it's a grid of vertical and horizontal directed lines. For this graph all you need is to check whether four outer streets form a cycle or not. If they form a cycle then the answer is \"YES\", otherwise \"NO\". The good explanation why this works was already given by shato. And then the entire solution takes just 10 lines of code - 8140438.",
    "code": "#include <iostream>\n#include <string>\n \nusing namespace std;\n \nint main() {\n\tint x; cin >> x >> x;\n\t\n\tstring s1; cin >> s1;\n\tstring s2; cin >> s2;\n\t\n\tstring s3 = { s1.front() , s1.back() , s2.front() , s2.back() };\n\t\n\tcout << (s3 == \"<>v^\" || s3 == \"><^v\" ? \"YES\" : \"NO\");\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "475",
    "index": "C",
    "title": "Kamal-ol-molk's Painting",
    "statement": "Rumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting.\n\nConsider the painting as a $n × m$ rectangular grid. At the beginning an $x × y$ rectangular brush is placed somewhere in the frame, with edges parallel to the frame, ($1 ≤ x ≤ n, 1 ≤ y ≤ m$). Then the brush is moved several times. Each time the brush is moved one unit right or down. The brush has been strictly inside the frame during the painting. The brush alters every cell it has covered at some moment.\n\nYou have found one of the old Kamal-ol-molk's paintings. You want to know if it's possible that it has been altered in described manner. If yes, you also want to know minimum possible area of the brush.",
    "tutorial": "There are probably several completely different ways to solve this problem, I will describe only the one I implemented during the round. The start point for the solution is that there are three cases we need to cover: either first time we move the brush right or we move it down or we do not move it at all. Let's start with the last one. Since we're not moving the brush at all then it's obvious that altered cells on the painting form a rectangle. It can also be proven that the only case we need to consider here is the rectangle 1x1, that's the only rectangle which cannot be achieved by moving some smaller rectangle. So we need to count the number of altered cells, if it is equal to 1 then the answer is 1. Now we're left with two cases to consider, you start by moving right in the case and you move down in the second case. You can write some code to cover each of those cases, but you can also notice that they are symmetric in some sense. To be more clear, they are symmetric against the diagonal line which goes from (0, 0) point through (1, 1) point. If you have some code to solve \"move down first\" case, then you don't need to write almost completely the same code to solve \"move right\" case, you can simply mirror the image against that diagonal and invoke \"move down\" method again. Small trick which saves a lot of time and prevents copy-pasting of the code. Now let's try to solve this last case. Basically the approach I used can be shortly described like that: we start in the leftmost topmost altered cell, then we move down and that move already leaves us only one option what do in the next moves until the end, so we get the entire sequence of moves. As well as getting these moves we also get the only possible width and height of the brush, so we know everything, I was not very strict while moving the brush so at the end I also compared whether these moves and these sizes in fact give exactly the same image as we get in the input. That was the brief explanation of the \"move down\" method, now let's get into details. First of all since we move down immediately from the start point then there is only one value which can be valid for the brush width - it is the number of altered cells which go to the right from the start point. So we know one dimension. Now let's try moving the brush. Ok, first time as we said we move it down, what is next? Then you might have a choice whether you want to move right or to move down again. The answer is to move right first because your width is already fixed while height might be unknown still, so if you miss point to be altered in the left column of the brush and you move right, you might still have a chance to paint it if you take the correct height of the brush. But if you miss the point to the right of the current topmost brush row then you won't be able to cover it later, because your width was fixed on the first step. Here is a picture: Grayed out is the current position of the brush. So what I'm saying is that you should move to the right if the cell in the red area is painted, otherwise you will definitely miss it. So this simple thing gives you the entire idea on how to build the only possible sequence of moves. You also need to calculate some possible value for the brush height. It can be calculated just before moving right, in order not to miss any painted cells you need to extend you height of the brush to cover all the painted cells in the leftmost column of you current brush position (this was highlighted as green on the image above). Now you know all the information about the probable painting - you have both dimensions of the brush and you know how it was moving, as I said before all you need to do is to double check that these moves and these dimensions in fact give you the same painting you get. If it gives the same painting then the answer for this case is $width \\cdot height$, otherwise there is no answer for this particular case. If you implement all of these steps carefully and you won't paint cells more than one time, then you will be able to achieve an $O(N \\cdot M)$ complexity.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "475",
    "index": "D",
    "title": "CGCDSSQ",
    "statement": "Given a sequence of integers $a_{1}, ..., a_{n}$ and $q$ queries $x_{1}, ..., x_{q}$ on it. For each query $x_{i}$ you have to count the number of pairs $(l, r)$ such that $1 ≤ l ≤ r ≤ n$ and $gcd(a_{l}, a_{l + 1}, ..., a_{r}) = x_{i}$.\n\n$\\operatorname{ecd}(v_{1},v_{2},\\ldots,v_{n})$ is a greatest common divisor of $v_{1}, v_{2}, ..., v_{n}$, that is equal to a largest positive integer that divides all $v_{i}$.",
    "tutorial": "It seems that all the solutions for this problem based on the same observation. Let's introduce two number sequences: $a_{0}, a_{1}, ..., a_{n}$ and $x_{0} = a_{0}, x_{i} = gcd(x_{i - 1}, a_{i})$. Then the observation is that the number of distinct values in $x$ sequence is no more than $1 + log_{2}a_{0}$. It can be proven by taking into account that $x$ is non-increasing sequence and value for greatest common divisor in case if it decreases becomes at most half of the previous value. So we have this observation and we want to calculate the count of GCD values across all the intervals, I see couple of ways how we can exploit the observation: We can fix the left side of the interval and look for the places where $gcd(a_{l}, ..., a_{r})$ function will decrease. Between the points where it decreases it will stay flat so we can add the size of this flat interval to the result of this particular $gcd$. There are different ways how to find the place where the function changes its value, some people were using sparse tables, I have never used those so won't give this solution here. Otherwise you can use segment tree to calculate gcd on the interval and then do a binary search to find where this value changes. This adds squared logarithmic factor to the complexity, not sure if that passes the TL easily. Otherwise you can do basically the same by doing only one descent in the segment tree. Then you get rid of one logarithmic factor in the complexity but that will make segment tree a bit more complicated. Another solution seems to be much simpler, you just go left to right and you calculate what is the number of segments started to the left of current element and what is the greatest common divisors values on those intervals. These values you need to store grouped by the $gcd$ value. This information can be easily updated when you move to the next element to the right - you can check that part in my submission. Our observation guarantees that the number of different $gcd$ values that we have to track is quite small all the time, it's no more than $1 + logA_{max}$. Submission: 8141810, maps are used here to count gcd values, using the vectors instead makes it running two times faster but the code is not that clear then.",
    "code": "#include <iostream>\n#include <map>\n#include <vector>\n \nusing namespace std;\n \ntemplate <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; }\n \nint gcd(int a, int b) {\n\tif (a % b == 0) return b;\n\treturn gcd(b, a % b);\n}\n \nint main() {\n\tios_base::sync_with_stdio(false);\n\tint n; cin >> n;\n\tauto v = readVector<int>(n);\n\t\n\tmap<int, long long> results;\n\t\n\tmap<int, int> divisors;\n\tmap<int, int> nextDivisors;\n\tfor (int i = 0 ; i < n ; i++) {\n\t\tnextDivisors.clear();\n\t\tfor (auto &p : divisors) {\n\t\t\tnextDivisors[gcd(p.first, v[i])] += p.second;\n\t\t}\n\t\tnextDivisors[v[i]]++;\n \n\t\tswap(nextDivisors, divisors);\n\t\tfor (auto &p : divisors)\n\t\t\tresults[p.first] += p.second;\n\t}\n\t\n\tint q; cin >> q;\n\twhile (q --> 0) {\n\t\tint x; cin >> x;\n\t\tcout << results[x] << endl;\n\t}\n}",
    "tags": [
      "brute force",
      "data structures",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "475",
    "index": "E",
    "title": "Strongly Connected City 2",
    "statement": "Imagine a city with $n$ junctions and $m$ streets. Junctions are numbered from $1$ to $n$.\n\nIn order to increase the traffic flow, mayor of the city has decided to make each street one-way. This means in the street between junctions $u$ and $v$, the traffic moves only from $u$ to $v$ or only from $v$ to $u$.\n\nThe problem is to direct the traffic flow of streets in a way that maximizes the number of pairs $(u, v)$ where $1 ≤ u, v ≤ n$ and it is possible to reach junction $v$ from $u$ by passing the streets in their specified direction. Your task is to find out maximal possible number of such pairs.",
    "tutorial": "Here we can start with the simple observation - if we have a cycle then we can choose such an orientation for the edges such that it will become a directed cycle. In this case all nodes in the cycle will be accessible from all other nodes of the same cycle. I was using the bridges finding algorithm to find the cycles. So you find all the cycles, for each cycle of size $s_{i}$ you add $s_{i}^{2}$ to the answer. Then you can collapse all the cycles into the single node (storing the cycle size as well). After merging all cycles into single nodes original graph becomes a tree. Now it comes to some kind of a magic, as far as I've seen from the discussions here people were make an assumption about the optimal solution, but nobody proved this assumption. Assumption goes like this: \"there exists an optimal solution which has some node (let's call it $root$) such that for every other node $v$ you can either reach $root$ from $v$ or you can reach $v$ from $root$ using directed edges of this optimal solution\". Intuitively this assumption makes sense because probably in order to increase the number of pairs of reachable nodes you will try to create as least as possible components in the graph which will be mutually unreachable. So we have this assumption, now in order to solve the problem we can iterate over all nodes in the tree and check what will be the answer if we will make this node to be a $root$ from the assumption. Let's draw some example of the graph which might be a solution according to our assumption: Here the $root$ is drawn on top and every other node has either a path to the $root$ or a path from the $root$. So let's say we decided that some node will be a $root$ but we didn't decide yet for each of its children whether their edges will directed to the $root$ or from the $root$. In order to fulfil our assumption the orientation of the edges within some child's subtree should be the same as the orientation of the edge between the $root$ and its child. There will be two more numbers which we need to add to the result - pairs of reachable nodes within some child's ($root$ children only!) subtree and pairs of reachable nodes for nodes from different subtrees. Let's introduce some variables: $s_{i}$ - size of the $i$-th cycle from the step when we were merging the cycles. In our tree all cycles are already merged into a single node, so $s_{i}$ is a weight of the $i$-th node. It can be equal to 1 if node $i$ did not belong to any cycle. $W_{i}$ - weight of the entire subtree rooted at node $i$. It can be seen that if we orient all edges in the subtree in the same manner according to our assumption then the number of reachable pairs of nodes will not depend on the chosen orientation. Each particular node $i$ adds the following term to the final result: $s_{i} \\cdot (W_{i} - s_{i})$. Now we need to decide what should be the orientation of all the edges adjacent to the $root$. Let's declare two more variables: $in$ - sum of $W_{i}$ for all $root$'s children whose edge is directed towards the root. $out$ - same for the children whose edge is directed from the root. So if we have those definitions then the last term for the result will be equal to: $(in + s_{root}) \\cdot out + in \\cdot s_{root}$. We can see that this term depends only on the $in$ and $out$ values, it doesn't depend on which particular children contribute to each of these values. We check which values for $in$ and $out$ we can achieve, we can do it using the DP similar to the one used in knapsack. So we check every possible value for $in$, based on this we can calculate $out$ value because their sum is fixed and equals to $W_{root} - s_{root}$, then we put them into the formula above and check whether it gives us a better total answer. There is one more thing to be noted about this solution - you can see that I said that we need to iterate over all nodes and make them to be the $root$, then you will need to get all the sizes of the children for particular $root$ and for those sizes you will need to find all the possible values for their sums. The sum can be up to $N$, for some $root$ we might have up to $O(N)$ children, so if you've fixed the $root$ then the rest might have $O(N^{2})$ complexity. This might lead you to a conclusion that the entire algorithm then has $O(N^{3})$ complexity, which is too slow for the given constraints. But that is not the case because outermost and innermost loops depend on each other, basically there you iterate over all the parent-children relations in the tree, and we know that this number in the tree equals to $2(N - 1)$, less than $N^{2}$, so in total it gives $O(N^{2})$ complexity for this solution.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <map>\n#include <vector>\n \ntypedef long long LL;\n \ntemplate<typename T> inline void maximize(T &a, T b) { a = std::max(a, b); }\n \n#define all(v) v.begin(),v.end()\n \nusing namespace std;\n \ntemplate<typename T> struct argument_type;\ntemplate<typename T, typename U> struct argument_type<T(U)> { typedef U type; };\n#define next(t, i) argument_type<void(t)>::type i; cin >> i;\n#define nextVector(t, v, size) vector< argument_type<void(t)>::type > v(size); { for (int i = 0 ; i < size ; i++) cin >> v[i]; }\n \n#define range(name, start, count) vector<int> name(count); { for (int i = 0 ; i < count ; i++) name[i] = i + start; }\n \n// this dsu will help us to track cycles in the graph\nclass dsuClass {\n\tpublic:\n \n\tint n;\n\tvector<int> parent;\n\tvector<int> size;\n\t\n\t\n\tvoid init(int n) {\n\t\tthis->n = n;\n\t\tparent.resize(n);\n\t\tsize.resize(n);\n\t\treset();\n\t}\n\t\n\tvoid reset() {\n\t\tfor (int i = 0 ; i < n ; i++) {\n\t\t\tparent[i] = i;\n\t\t\tsize[i] = 1;\n\t\t}\n\t}\n\t\n\tint update(int a) {\n\t\tif (parent[a] == a) return a;\n\t\treturn parent[a] = update(parent[a]);\n\t}\n\t\n\tvoid join(int a, int b) {\n\t\ta = update(a);\n\t\tb = update(b);\n\t\tif (size[b] > size[a]) swap(a, b);\n\t\tif (a == b) return;\n\t\t\n\t\tsize[a] += size[b];\n \n\t\tparent[b] = a;\n\t}\n};\n \ndsuClass dsu;\n \n// these are used to find bridges, code itself is taken from e-maxx\nvector<bool> used;\nconst int MAXN = 2000;\nint timer, tin[MAXN], fup[MAXN];\n \nvoid dfs (int v, int p, vector<vector<int>> &vEdges) {\n\tused[v] = true;\n\ttin[v] = fup[v] = timer++;\n\tfor (auto to : vEdges[v]) {\n\t\tif (to == p)  continue;\n\t\tif (used[to]) {\n\t\t\tfup[v] = min (fup[v], tin[to]);\n\t\t\tdsu.join(v,to);\n\t\t} else {\n\t\t\tdfs (to, v, vEdges);\n\t\t\tfup[v] = min (fup[v], fup[to]);\n\t\t\tif (fup[to] <= tin[v])\n\t\t\t\tdsu.join(v,to);\n\t\t}\n\t}\n}\n \nvoid find_bridges(vector<vector<int>> &vEdges) {\n\ttimer = 0;\n\tfor (int i=0; i<used.size(); ++i)\n\t\tif (!used[i])\n\t\t\tdfs (i, -1, vEdges);\n}\n \nint calc_tree_size(int v, int parent, vector<vector<int>> &edges, vector<int> &sizes, int &result_acc) {\n\tint result = 0;\n\t\n\tfor (auto child : edges[v]) if (child != parent) {\n\t\tresult += calc_tree_size(child, v, edges, sizes, result_acc);\n\t}\n\t\n\tresult_acc += sizes[v] * result;\n\t\n\tresult += sizes[v];\n\t\n\treturn result;\n}\n \nint calc_tree_best_result(vector<int> sizes, vector<pair<int, int>> &edges_list) {\n\tint best = 0;\n\tint n = sizes.size();\n\tvector<vector<int>> edges(n);\n\tfor (auto e : edges_list) {\n\t\tedges[e.first].push_back(e.second);\n\t\tedges[e.second].push_back(e.first);\n\t}\n\t\n\tconst int MAXSUM = 2000;\n\t\n\tfor (int v = 0 ; v < n ; v++) {\n\t\tint cur = 0;\n\t\tvector<int> childrenSizes(edges[v].size());\n\t\tfor (int i = 0 ; i < childrenSizes.size() ; i++)\n\t\t\tchildrenSizes[i] = calc_tree_size(edges[v][i], v, edges, sizes, cur);\n\t\t\t\n\t\tvector<int> achievable_sum(MAXSUM + 1);\n\t\tachievable_sum[0] = true;\n\t\tfor (auto cs : childrenSizes) {\n\t\t\tfor (int x = MAXSUM ; x >= cs ; x--) if (achievable_sum[x - cs]) achievable_sum[x] = true;\n\t\t}\n\t\t\n\t\tint full_sum = accumulate(all(childrenSizes), 0);\n\t\tfor (int in = 0 ; in <= MAXSUM ; in++) if (achievable_sum[in]) {\n\t\t\tint out = full_sum - in;\n\t\t\tmaximize(best, (in + sizes[v]) * out + in * sizes[v] + cur);\n\t\t}\n\t}\n\t\n\treturn best;\n}\n \nint main() {\n\tint n; cin >> n;\n\tint m; cin >> m;\n\t\n\tvector<vector<int>> vEdges(n);\n\tvector<pair<int, int>> edges(n);\n\tfor (int i = 0 ; i < m ; i++) {\n\t\tint a; cin >> a;\n\t\tint b; cin >> b;\n\t\ta--;\n\t\tb--;\n\t\tvEdges[a].push_back(b);\n\t\tvEdges[b].push_back(a);\n\t\tedges.push_back( { a , b } );\n\t}\n\tused.resize(n);\n\tdsu.init(n);\n\tfind_bridges(vEdges);\n\t\n\tvector<int> newParents; // these will represent the nodes of the tree after we merge cycles\n\tfor (int i = 0 ; i < n ; i++) if (dsu.update(i) == i) newParents.push_back(i);\n\t\n\tmap<int, int> parentsMapping;\n\tfor (int i = 0 ; i < newParents.size() ; i++) parentsMapping[newParents[i]] = i;\n\tvector<pair<int, int>> newEdges;\n\t\n\tint result = 0;\n\tfor (auto parent : newParents) {\n\t\tresult += dsu.size[parent] * dsu.size[parent];\n\t}\n\t\n\tfor (auto e : edges) {\n\t\tif (dsu.update(e.first) != dsu.update(e.second)) \n\t\t\tnewEdges.push_back( make_pair(parentsMapping[dsu.update(e.first)] , parentsMapping[dsu.update(e.second)]) );\n\t}\n\t\n\tvector<int> sizes(newParents.size());\n\tfor (int i = 0 ; i < sizes.size() ; i++) sizes[i] = dsu.size[newParents[i]];\n\t\n\tresult += calc_tree_best_result(sizes, newEdges);\n\t\n\tcout << result;\n}",
    "tags": [
      "dfs and similar"
    ],
    "rating": 2700
  },
  {
    "contest_id": "475",
    "index": "F",
    "title": "Meta-universe",
    "statement": "Consider infinite grid of unit cells. Some of those cells are planets.\n\nMeta-universe $M = {p_{1}, p_{2}, ..., p_{k}}$ is a set of planets. Suppose there is an infinite row or column with following two properties: 1) it doesn't contain any planet $p_{i}$ of meta-universe $M$ on it; 2) there are planets of $M$ located on both sides from this row or column. In this case we can turn the meta-universe $M$ into two non-empty meta-universes $M_{1}$ and $M_{2}$ containing planets that are located on respective sides of this row or column.\n\nA meta-universe which can't be split using operation above is called a universe. We perform such operations until all meta-universes turn to universes.\n\nGiven positions of the planets in the original meta-universe, find the number of universes that are result of described process. It can be proved that each universe is uniquely identified not depending from order of splitting.",
    "tutorial": "Let's try to solve this problem naively first, the approach should be obvious then - you have a set of points, you iterate them left to right and you mind the gap between them. If there is such a gap between two neighbours you split this meta-universe with vertical line and do the same thing for each of two subsets. If you found no such gap by going left to right, you do the same going top to bottom. If you are unlucky again then you are done, this is a universe, it cannot be split. Let's think about the complexity of this approach now, even if get the points sorted and split for free then the complexity will highly depend on how soon you found a place where you could split the meta-universe. For example if you are lucky and you will always split close to the start of the sequence then your total complexity would be $O(n)$, which is very good indeed. If you will encounter the option to split somewhere in the middle of the sequence, which means that you split the meta-universe in two halves, you will get a $O(NlogN)$ solution, not linear but still good enough for this problem. The worst case occurs when you split always after iterating through the entire sequence, that means that in order to extract one point from the set you will have to iterate through all of them, now the complexity becomes $O(N^{2})$, that's not enough already. Let's think about it again, we got several cases, two of them are good (when we split in the beginning or in the middle) and the third one is too slow, it happens when we split always in the end. We need to make our solution better in this particular case and that should be almost enough to solve the entire problem. The obvious approach how to get rid of \"split at the end\" case is to start iterating from the end initially. And it should be obvious as well that it doesn't change much because your old start becomes the end now. But what we can do instead is to start iterating from both sides, then in any case you are winner! Intuitively, if you encountered a way to split at some end of the sequence then you're good to go because you spent almost no time on this particular step and you already found a way to split it further. In the opposite case, if you had to iterate through the entire sequence and found a split point in the middle you should be still happy about it because it means that on the next steps each of your new sets will be approximately two times smaller, that leads you back to $O(NlogN)$ complexity. Also you should not forget that you need to do the same for Y coordinate as well, that means that you need to have four iterators and you need to check them simultaneously. This is the basic idea for my solution, there is just one more detail to be added. Initially I told that our complexity estimate is given if we \"sort and split for free\". That's not that easy to achieve, but we can achieve something else almost as good as this one. In order to split cheaply all you need to do is to avoid the actual split :-) Instead of splitting the sequence into two subsequences you can just leave the original sequence and extract part of it which will become a new subsequence. Obviously if you want to make this operation cheaper you need to extract the smaller part. For example if you have a sequence of points sorted by X and you found a split point by iterating from the end of the sequence then you can be sure that the right subsequence will not be longer than the left sequence, because you iterate from the left-hand side and from the right-hand side simultaneously. Now we need to take care about sorting part as well. This one is easy, all you need to do is instead of storing one sequence of points you store all the points in two sorted sets - one by X and one by Y coordinate. In total this should add just one more logarithmic factor to the complexity. That is the entire solution, I'd like to get back one more time to the complexity analysis. We have a recurring algorithm, on every step of the recurrence we're looking for the split point, then we split and invoke this recurring algorithm two more times. It looks that for the worst case (which is split in the middle) we will split a sequence into two subsequences of the same size, so we have a full right to apply a Master theorem here. On each step our complexity seems to be $O(NlogN)$ (log factor because of using sets) so the \"Case 2. Generic form\" section from the Wiki gives us a solution that our entire algorithm has an $O(Nlog^{2}N)$ time complexity. Am I correct?",
    "code": "#include <cstdlib>\n#include <iostream>\n#include <set>\n \nusing namespace std;\n \npair<int, int> mirror(pair<int, int> &p) {\n\treturn { p.second , p.first };\n}\n \nvoid move_from_first_two_sets_to_other_two(set<pair<int, int>> &set1_1, set<pair<int, int>> &set1_2, set<pair<int, int>> &set2_1, set<pair<int, int>> &set2_2,\n\t\t\t\t\t\t\t\t\t\t\tpair<int, int> item) {\n\tset1_1.erase(item);\n\tset1_2.erase(mirror(item));\n\tset2_1.insert(item);\n\tset2_2.insert(mirror(item));\n}\n \nint split(set<pair<int, int>> &byX, set<pair<int, int>> &byY) {\n\tif (byX.size() == 1) return 1;\n\t\n\tauto x_forward = byX.begin();\n\tauto x_backward = byX.rbegin();\n\tauto y_forward = byY.begin();\n\tauto y_backward = byY.rbegin();\n\t\t\n\tset<pair<int, int>> byX2, byY2;\n\tdo {\n\t\tint x_prev = x_forward->first;\n\t\tx_forward++;\n\t\tif (abs(x_forward->first - x_prev) > 1) {\n\t\t\twhile (byX.begin()->first <= x_prev) {\n\t\t\t\tmove_from_first_two_sets_to_other_two(byX, byY, byX2, byY2, *byX.begin());\n\t\t\t}\n\t\t\treturn split(byX, byY) + split(byX2, byY2);\n\t\t}\n\t\t\n\t\tx_prev = x_backward->first;\n\t\tx_backward++;\n\t\tif (abs(x_backward->first - x_prev) > 1) {\n\t\t\twhile (byX.rbegin()->first >= x_prev) {\n\t\t\t\tmove_from_first_two_sets_to_other_two(byX, byY, byX2, byY2, *byX.rbegin());\n\t\t\t}\n\t\t\treturn split(byX, byY) + split(byX2, byY2);\n\t\t}\n\t\t\n\t\tint y_prev = y_forward->first;\n\t\ty_forward++;\n\t\tif (abs(y_forward->first - y_prev) > 1) {\n\t\t\twhile (byY.begin()->first <= y_prev) {\n\t\t\t\tmove_from_first_two_sets_to_other_two(byY, byX, byY2, byX2, *byY.begin());\n\t\t\t}\n\t\t\treturn split(byX, byY) + split(byX2, byY2);\n\t\t}\n \n\t\ty_prev = y_backward->first;\n\t\ty_backward++;\n\t\tif (abs(y_backward->first - y_prev) > 1) {\n\t\t\twhile (byY.rbegin()->first >= y_prev) {\n\t\t\t\tmove_from_first_two_sets_to_other_two(byY, byX, byY2, byX2, *byY.rbegin());\n\t\t\t}\n\t\t\treturn split(byX, byY) + split(byX2, byY2);\n\t\t}\n\t} while (*x_forward < *x_backward);\n\t\n\treturn 1;\n}\n \nint main() {\n\tint n; cin >> n;\n\t\n\tset<pair<int, int>> byX, byY;\n\twhile (n --> 0) {\n\t\tint x; cin >> x;\n\t\tint y; cin >> y;\n\t\tbyX.insert( { x , y } );\n\t\tbyY.insert( { y , x } );\n\t}\n\t\n\tcout << split(byX, byY);\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2900
  },
  {
    "contest_id": "476",
    "index": "A",
    "title": "Dreamoon and Stairs",
    "statement": "Dreamoon wants to climb up a stair of $n$ steps. He can climb $1$ or $2$ steps at each move. Dreamoon wants the number of moves to be a multiple of an integer $m$.\n\nWhat is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?",
    "tutorial": "We can show that the maximum number of moves possible is n and minimal moves needed is $\\textstyle{\\left[\\!\\!{\\frac{n}{2}}\\right]\\!\\!}\\$, so the problem equals to determine the minimal integer that is a multiple of m in the range $\\textstyle\\left[{\\frac{n}{2}}\\right],n\\right]$. One way to find the minimal number which is a multiple of m and greater than or equal to a number x is $\\textstyle\\bigcap{\\frac{x}{m}}\\mid*\\ y n$, we can compare this number to the upper bound n to determine if there is a valid solution. Although best practice is $O(1)$, $O(n)$ enumeration of each possible number of moves would also work. time complexity: $O(1)$ explanation of sample code: The $\\left[{\\frac{a}{b}}\\right]$ can be calculated in the following c++ code if $a$ is non-negative and $b$ is positive: (a+b-1)/b Because / in c++ is integral division so (a+b-1)/b would result in $d i v(a+b-1,b)={\\bigl\\lfloor}{\\frac{a+b-1}{b}}{\\bigr\\rfloor}$ Let $a = div(a, b)b + mod(a, b) = db + m$, $d i v(a+b-1,b)=d i v(d b+m+b-1,b)={\\bigl\\lfloor}{\\frac{d b+m+b-1}{h}}{\\bigr\\rfloor}=d+{\\bigl\\lfloor}{\\frac{m+b-1}{h}}{\\bigr\\rfloor}$. Which means if $m=0\\Rightarrow d i v(a+b-1,b)=d$, otherwise $div(a + b - 1, b) = d + 1$. Can be translated to if $m o d(a,b)=0\\Rightarrow d i v(a+b-1,b)=d i v(a,b)$, otherwise $div(a + b - 1, b) = div(a, b) + 1$. Which matches the value of $\\left[{\\frac{a}{b}}\\right]$.",
    "code": "#include <cstdio>\n \nint main(void)\n{\n    int n, m ;\n    scanf(\"%d%d\", &n, &m) ;\n \n    int lower_bound = (n+1)/2 ;\n    int ans = (lower_bound+m-1)/m*m ;\n    if(ans>n)\n        ans = -1 ;\n \n    printf(\"%d\\n\", ans) ;\n \n    return 0 ;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "476",
    "index": "B",
    "title": "Dreamoon and WiFi",
    "statement": "Dreamoon is standing at the position $0$ on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.\n\nEach command is one of the following two types:\n\n- Go 1 unit towards the positive direction, denoted as '+'\n- Go 1 unit towards the negative direction, denoted as '-'\n\nBut the Wi-Fi condition is so poor that Dreamoon's smartphone reports some of the commands can't be recognized and Dreamoon knows that some of them might even be wrong though successfully recognized. Dreamoon decides to follow every recognized command and toss a fair coin to decide those unrecognized ones (that means, he moves to the $1$ unit to the negative or positive direction with the same probability $0.5$).\n\nYou are given an original list of commands sent by Drazil and list received by Dreamoon. What is the probability that Dreamoon ends in the position originally supposed to be final by Drazil's commands?",
    "tutorial": "The order of moves won't change the final position, so we can move all '?'s to the end of the string. We have the following information: 1. the correct final position 2. the position that Dreamoon will be before all '?'s 3. the number of '?'s We can infer that the distance and direction dreamoon still needs to move in the '?' part from 1. and 2., and furthur translate that to how many +1s and -1s dreamoon will need to move. What's left is a combinatorial problem, the probability would be $\\frac{C({\\it(r u u p u b e r~o f~\\stackrel{f}{~}}^{f}s_{\\it3},n u p m b e r~o f~\\underbrace{~}{~+\\mathrm{l}{\\it s}})}{2^{(n u m b e r~o f~\\stackrel{f}{~}}s)}$. So we can compute that formula within $O(n)$ time assuming n is the length of commands, but since N is small so we can brute force every possible choice of '?' with some recursive or dfs like search in $O(2^{n})$ time complexity. Note that the problem asks for a precision of $10^{ - 9}$, so one should output to $11$ decimal places or more. time complexity: $O(n)$, assuming $n$ is the length of commands.",
    "code": "#include <cstdio>\n#include <cstring>\n#include <algorithm>\n \nusing namespace std ;\n \nint main(void)\n{\n    char s1[15], s2[15] ;\n \n    scanf(\"%s%s\", s1, s2) ;\n \n    int n = strlen(s1) ;\n    \n    int answerPosition = 0 ;\n    for(int i=0;i<n;i++)\n        answerPosition += (s1[i]=='+'?1:-1) ;\n \n    int finalPosition = 0 ;\n    int moves = 0 ; //number of '?'\n    for(int i=0;i<n;i++)\n    {\n        if(s2[i]=='?')\n            moves++ ;\n        else\n            finalPosition += (s2[i]=='+'?1:-1) ;\n    }\n \n    int distance = answerPosition-finalPosition ;\n    double answer ;\n    if((distance+moves)%2!=0 || moves<abs(distance)) //can't reach the destination no matter how\n        answer = 0 ;\n    else\n    {\n        int m = (moves+abs(distance))/2 ; //moves needed toward the distance m is abs(distance)+(moves-abs(distance))/2\n        //answer is C(moves,m)/(1<<moves)\n        int c = 1 ;\n        for(int i=0;i<m;i++)\n            c *= moves-i ;\n        for(int i=2;i<=m;i++)\n            c /= i ;\n        answer = (double)c/(1<<moves) ;\n    }\n \n    printf(\"%.12f\\n\", answer) ;\n \n    return 0 ;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 1300
  },
  {
    "contest_id": "476",
    "index": "C",
    "title": "Dreamoon and Sums",
    "statement": "Dreamoon loves summing up something for no reason. One day he obtains two integers $a$ and $b$ occasionally. He wants to calculate the sum of all nice integers. Positive integer $x$ is called nice if $\\operatorname*{mod}(x,b)\\neq0$ and $\\frac{\\mathrm{div}(x,b)}{\\mathrm{mod}\\{x.b)}\\implies\\int$, where $k$ is some \\textbf{integer} number in range $[1, a]$.\n\nBy $\\operatorname{div}(x,y)$ we denote the quotient of integer division of $x$ and $y$. By ${\\mathrm{mod}}(x,y)$ we denote the remainder of integer division of $x$ and $y$. You can read more about these operations here: http://goo.gl/AcsXhT.\n\nThe answer may be large, so please print its remainder modulo $1 000 000 007$ ($10^{9} + 7$). Can you compute it faster than Dreamoon?",
    "tutorial": "If we fix the value of $k$, and let $d = div(x, b)$, $m = mod(x, b)$, we have : $d = mk$ $x = db + m$ So we have $x = mkb + m = (kb + 1) * m$. And we know $m$ would be in range $[1, b - 1]$ because it's a remainder and $x$ is positive, so the sum of $x$ of that fixed $k$ would be $\\textstyle\\sum_{m=1}^{b-1}((k b+1)m)=(k b+1){\\frac{b(b-1)}{2}}$. Next we should notice that if an integer $x$ is $nice$ it can only be $nice$ for a single particular $k$ because a given $x$ uniquely defines $div(x, b)$ and $mod(x, b)$. Thus the final answer would be sum up for all individual $k$: $\\textstyle\\sum_{k=1}^{a}((k b+1){\\frac{b(b-1)}{2}})$ which can be calculated in $O(a)$ and will pass the time limit of 1.5 seconds. Also the formula above can be expanded to ${\\frac{(a{(a+1)}}{2}}b+a){\\frac{b(b-1)}{2}}$. Dreamoon says he's too lazy to do this part, so if you use $O(1)$ solution you just computed the answer faster than Dreamoon!!! Note that no matter which approach one should be very careful of overflowing of the integer data type of the used language. For example one should do a module after every multiplication if using 64-bit integer type. And pay attention to precedence of operations: take c++ for example a+b%c would be executed as a+(b%c) instead of (a+b)%c, another c++ example a*(b*c)%m would be executed as (a*(b*c))%m instead of a*((b*c)%m). Thanks saurabhsuniljain for pointing out the preceding problem and examples in the comment! time complexity: $O(1)$",
    "code": "#include <cstdio>\n \nlong long mod = 1000000007 ;\n \nint main(void)\n{\n    long long a, b ;\n \n    scanf(\"%I64d%I64d\", &a, &b) ;\n \n    long long B = (b*(b-1)/2) % mod ;\n    long long A1 = (a*(a+1)/2) % mod ;\n    long long A = (A1*b+a) % mod ;\n    long long answer = (A*B) % mod ;\n \n    printf(\"%I64d\\n\", answer) ;\n \n    return 0 ;\n}",
    "tags": [
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "476",
    "index": "D",
    "title": "Dreamoon and Sets",
    "statement": "Dreamoon likes to play with sets, integers and $\\operatorname{gcd}$. $\\operatorname*{gcd}(a,b)$ is defined as the largest positive integer that divides both $a$ and $b$.\n\nLet $S$ be a set of exactly four distinct integers greater than $0$. Define $S$ to be of rank $k$ if and only if for all pairs of distinct elements $s_{i}$, $s_{j}$ from $S$, $\\operatorname*{gcd}(s_{i},s_{j})=k$.\n\nGiven $k$ and $n$, Dreamoon wants to make up $n$ sets of rank $k$ using integers from $1$ to $m$ such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum $m$ that makes it possible and print one possible solution.",
    "tutorial": "The first observation is that if we divide each number in a set by $k$, than the set would be rank $1$. So we could find $n$ sets of rank $1$ then multiple every number by $k$. For how to find $n$ sets of rank 1, we can use ${6a + 1, 6a + 2, 6a + 3, 6a + 5}$ as a valid rank $1$ set and take $a = 0$ to $n - 1$ to form $n$ sets and thus $m = (6n - 1) * k$. The proof that $m$ is minimal can be shown by the fact that we take three consecutive odd numbers in each set. If we take less odd numbers there will be more than $1$ even number in a set which their gcd is obviously a multiple of $2$. And if we take more odd numbers $m$ would be larger. The output method is straight forward. Overall time complexity is $O(n)$. time complexity: $O(n)$ sample code:",
    "code": "#include <cstdio>\n \nint main(void)\n{\n    int n, k ;\n \n    scanf(\"%d%d\", &n, &k) ;\n \n    printf(\"%d\\n\", k*(6*n-1)) ;\n \n    for(int i=0;i<n;i++)\n        printf(\"%d %d %d %d\\n\", k*(6*i+1), k*(6*i+3), k*(6*i+4), k*(6*i+5)) ;\n \n    return 0 ;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "476",
    "index": "E",
    "title": "Dreamoon and Strings",
    "statement": "Dreamoon has a string $s$ and a pattern string $p$. He first removes exactly $x$ characters from $s$ obtaining string $s'$ as a result. Then he calculates $\\operatorname{occ}(s^{\\prime},p)$ that is defined as the maximal number of non-overlapping substrings equal to $p$ that can be found in $s'$. He wants to make this number as big as possible.\n\nMore formally, let's define $\\operatorname{ans}(x)$ as maximum value of $\\operatorname{occ}(s^{\\prime},p)$ over all $s'$ that can be obtained by removing exactly $x$ characters from $s$. Dreamoon wants to know $\\operatorname{ans}(x)$ for all $x$ from $0$ to $|s|$ where $|s|$ denotes the length of string $s$.",
    "tutorial": "First let $A[i]$ to be the minimal length $L$ needed so that substring $s[i..i + L]$ can become pattern $p$ by removing some characters. We can calculate this greedily by keep selecting next occurrence of characters in $p$ in $O(length(s))$ time for a fixed $i$, so for all $i$ requires $O(length(s)^{2})$. Next we can do a dp $D[i][j]$ where $D[i]$ is the answer array for $s[0..i]$. $D[i]$ can contribute to $D[i + 1]$ with $0$ or $1$ removal and to $D[i + A[i]]$ with $A[i] - length(p)$ removal(s). In other words, $D[i][j]$ can transition into tree relations $D[i + 1][j] = D[i][j]$ //not delete $s[i]$, $D[i + 1][j + 1] = D[i][j]$ //delete $s[i]$, and $D[i + A[i]][j + A[i] - length(p)] = D[i][j] + 1$ //form a substring $p$ by deleting $A[i] - length(p)$ characters. Calculate forwardly from $D[0]$ to $D[length(s) - 1]$ gives the final answer array as $D[length(s)]$. Calculating $D[i]$ requires $O(length(s))$ time for a fixed $i$, so for all $i$ takes $O(length(s)^{2})$ time. time complexity: $O(n^{2})$, $n = length(s)$ Another solution: Let $k$ = $div(length(s), length(p))$. We can run an edit distance like algorithm as following (omitting the details of initialization and boundary conditions): for(i=0;i<n;i++) for(j=0;j<k*p;j++) if(s[i]==p[j%length(p)]) D[i][j] = D[i-1][j-1] D[i][j] = min(D[i][j], D[i-1][j] + (j%length(p)!=length(p)-1))That means remove cost is $1$ when it is in the middle of a $p$ and $0$ elsewhere because $p$ need to be consecutive(thus no need to be actually remove outside of a $p$). Then $D[n][t * length(p)]$ is the minimal number of removals to have $t$ non-overlapping substring of $p$. So we have $answer[D[n][t * length(p)..(t + 1) * length(p)] = t$. And after the maximal $t$ is reached, decrease answer by $1$ for every $length(p)$. time complexity: $O(n^{2})$",
    "code": "#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <algorithm>\n \nusing namespace std ;\n \nchar s[2100], p[510] ;\nint D[2100][2100] ;\nint answer[2100] ;\nint INF = 2100 ;\n \nint main(void)\n{\n    gets(s) ;\n    gets(p) ;\n \n    int Len_s = strlen(s) ;\n    int Len_p = strlen(p) ;\n    int k = Len_s/Len_p ;\n \n    D[0][0] = 0 ;    \n    for(int i=1;i<=Len_p*k;i++)\n        D[0][i] = INF ;\n    for(int i=1;i<=Len_s;i++)\n    {\n        D[i][0] = 0 ;\n        for(int j=1;j<=Len_p*k;j++)\n        {\n            if(s[i-1]==p[(j-1)%Len_p])\n                D[i][j] = D[i-1][j-1] ;\n            else\n                D[i][j] = INF ;\n            D[i][j] = min(D[i][j], D[i-1][j]+(j%Len_p!=0)) ;\n        }\n    }\n \n    int end = 0 ;\n    for(int t=0;D[Len_s][t*Len_p]<INF && t<=k;t++)\n    {\n        end = D[Len_s][(t+1)*Len_p] ;\n        if(end==INF || t==k)\n            end = Len_s-t*Len_p+1 ;\n        for(int i=D[Len_s][t*Len_p];i<end;i++)\n            answer[i] = t ;\n    }\n    for(int i=end;i<=Len_s;i++)\n        answer[i] = (Len_s-i)/Len_p ;\n \n    printf(\"%d\", answer[0]) ;\n    for(int i=1;i<=Len_s;i++)\n        printf(\" %d\", answer[i]) ;\n    putchar('\\n') ;\n \n    return 0 ;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "477",
    "index": "D",
    "title": "Dreamoon and Binary",
    "statement": "Dreamoon saw a large integer $x$ written on the ground and wants to print its binary form out. Dreamoon has accomplished the part of turning $x$ into its binary format. Now he is going to print it in the following manner.\n\nHe has an integer $n = 0$ and can only perform the following two operations in any order for unlimited times each:\n\n- Print n in binary form without leading zeros, each print will append to the right of previous prints.\n- Increase n by 1.\n\nLet's define an ideal sequence as a sequence of operations that can successfully print binary representation of $x$ without leading zeros and ends with a print operation (i.e. operation 1). Dreamoon wants to know how many different ideal sequences are there and the length (in operations) of the shortest ideal sequence.\n\nThe answers might be large so please print them modulo 1000000007 ($10^{9} + 7$).\n\nLet's define the string representation of an ideal sequence as a string of '1' and '2' where the $i$-th character in the string matches the $i$-th operation performed. Two ideal sequences are called different if their string representations are different.",
    "tutorial": "Let $Xb$ be the binary string of number $X$. An ideal sequence can be expressed as a partition of $Xb$: $P_{1} = Xb[1..p_{1}], P_{2} = Xb[p_{1}..p_{2}], ... P_{K} = Xb[p_{K - 1}..length(Xb)]$ where $P_{i}  \\le  P_{i + 1}$. The length of operations of such sequence is $P_{K} + K$. We can calculate the number of different ideal sequences by dp. State $D[i][j]$ stands for the answer of state that we have print $Xb[1..j]$ and last partition is $Xb[i..j]$. A possible way of transition is that a state $D[i][j]$ can go to state $D[i][j + 1]$ and $D[j][k]$ where $k$ is the minimal possible position such that value of $Xb[j..k]$ is equal to or greater than the value of $Xb[i..j]$ and $Xb[j]$ is $1$ since we can't print any leading $0$. Note that $D[j][k + 1]$ can also derived from $D[i][j]$ but it will covered by $D[i][j]  \\rightarrow  D[j][k]  \\rightarrow  D[j][k + 1]$, so we don't need to consider this case to avoid redundant counts. If we can determine $k$ for each $i$, $j$ pair in $O(1)$ then we can compute this dp in $O(length(Xb)^{2})$ in the following manner: for(j=0;j<n;j++) for(i=0;i<j;i++) compute the transitions of D[i][j]So let's look into how to calculate the value $k$ for a given $i$, $j$ pair. If the value of $Xb[j..2j - i]$ is equal to or greater than $Xb[i..j]$ than $k$ is $2j - i$ because if $k$ is less than $2j - i$ would make length of the new partition less than the previous partition thus its value would be lesser. And if $k$ can't be $2j - i$, the value of $2j - i + 1$ is always a valid choice because it would make the length of the new partition greater than the previous one. So for each length $L$ if we know the order of $Xb[i..i + L]$ and $Xb[i + L..i + 2L]$ in $O(1)$ time we can calculate k in $O(1)$ time(can be easily shown by assuming $L = j - i$). One way of doing such is using prefix doubling algorithm for suffix array construction to build a RMQ structure for query in $O(1)$ time. The prefix doubling algorithm requires $O(nlgn)$ precompute time. Note there is still a various of ways to do this part of task in the same or better time complexties. And for the shortest length part we can compute the minimal parts needed so far for each state along with the preivous dp. Then compare all states ends with $j = length(Xb)$. Overall we can solve this problem in $O(length(Xb)^{2})$ with caution in details like boundaries and module operations. time complexity: $O(n^{2})$, $n = length(Xb)$ Note the sample code use a nlgnlgn version of prefix doubling algorithm",
    "code": "#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <iostream>\n#include <algorithm>\n \nchar X[5100] ;\nint len ;\nint arr[5100] ;\nint rank[30][5100] ;\nint *ref, rL ;\nlong long mod = 1000000007LL ;\nlong long sp[5100][5100] ;\nlong long ws[5100][5100] ;\n \n//compare function for doubling prefix algorithm\n//ref is the reference(previous) table of rank and rL is the Length computing\nint cmp(int a, int b)\n{\n    if(ref[a]==ref[b])\n    {\n        if(ref[a+rL]==ref[b+rL])\n            return 0 ;\n        else\n            return (ref[a+rL]>ref[b+rL]?1:-1) ;\n    }\n    else\n        return (ref[a]>ref[b]?1:-1) ;\n}\n \n//compare function for std::sort\nbool scmp(int a, int b)\n{\n    return (cmp(a,b)==-1) ;\n}\n \n//update an dp item\nvoid update(int s1, int e1, int s2, int e2, int add)\n{\n    ws[s2][e2] = (ws[s2][e2]+ws[s1][e1])%mod ;\n    sp[s2][e2] = std::min(sp[s2][e2], sp[s1][e1]+add) ;\n}\n \n//most significant bit\nint msb(int n)\n{\n    int pos = 0 ;\n    while(n!=1)\n    {\n        pos++ ;\n        n >>= 1 ;\n    }\n    return pos ;\n}\n \n//RMQ query\nbool leq(int L, int s1, int s2)\n{\n    int pos = msb(L) ;\n    int hL = (1<<pos) ;\n    if(hL==L)\n        return (rank[pos][s1]<=rank[pos][s2]) ;\n    else\n    {\n        if(rank[pos][s1]<rank[pos][s2])\n            return true ;\n        else if(rank[pos][s1]==rank[pos][s2])\n        {\n            int np = L-hL ;\n            return (rank[pos][s1+np]<=rank[pos][s2+np]) ;\n        }\n        else\n            return false ;\n    }\n}\n \nint main(void)\n{\n    gets(X) ;\n    len = strlen(X) ;\n \n    //build up the RMQ table, doubling prefix algorithm\n    for(int i=0;i<len;i++)\n        rank[0][i] = X[i]-'0' ;\n \n    for(int L=1,n=1;2*n<=len;L++,n<<=1)\n    {\n        int mn = len-2*n+1 ;\n        for(int s=0;s<mn;s++)\n            arr[s] = s ;\n        ref = rank[L-1] ;\n        rL = n ;\n        std::sort(arr, arr+mn, scmp) ;\n        int curRank = 0 ;\n        for(int s=0;s<mn;s++)\n        {\n            rank[L][arr[s]] = curRank ;\n            if(s+1<mn && cmp(arr[s], arr[s+1])!=0)\n                curRank++ ;\n        }\n    }\n \n    //dp, sp=shortest path length, ws=ways\n    long long INF = 2*len ;\n    for(int i=0;i<=len;i++)\n        for(int j=0;j<=len;j++)\n        {\n            sp[i][j] = INF ;\n            ws[i][j] = 0 ;\n        }\n \n    sp[0][1] = 1 ;\n    ws[0][1] = 1 ;\n    for(int e=1;e<len;e++)\n    {\n        for(int s=0;s<e;s++)\n        {\n            if(X[s]=='1')\n            {\n                update(s,e,s,e+1,0) ;\n                if(X[e]=='1')\n                {\n                    int L = e-s ;\n                    if(e+L<=len && leq(L,s,e))\n                        update(s,e,e,e+L,1) ;\n                    else if(e+L+1<=len)\n                        update(s,e,e,e+L+1,1) ;\n                }\n            }\n        }\n    }\n \n    //parsing dp table to answer\n    long long ans1 = ws[0][len] ;\n    int ans2 = 0 ;\n    long long dif = 1 ;\n    for(int s=1;s<len;s++)\n    {\n        if(sp[s][len]<INF)\n        {\n            ans1 = (ans1+ws[s][len])%mod ;\n            //the answer would be X[s..len]+sp[s][len]\n            //so diff would be X[ans2..len]+sp[ans2][len]-X[s..len]-sp[s][len]\n            //if previous value >= 0 than ans2=s\n            //previous value could be expressed as dif*2^(len-s)+sp[ans2][len]-sp[s][len]\n            //so if dif*2^(len-s)>=sp[s][len]-sp[ans2][len] will do, BTW the latter max is len or 2000\n            long long val = sp[s][len]-sp[ans2][len] ;\n            if(val<=0 || s-ans2>12 || len-s>12 || dif*(1<<(len-s))>=val)\n            {\n                dif = 0 ;\n                ans2 = s ;\n            }\n        }\n        dif = (dif<<1)+X[s]-'0' ;\n    }\n    long long ans2val = 0 ;\n    for(int i=ans2;i<len;i++)\n        ans2val = ((ans2val<<1)+X[i]-'0')%mod ;\n    ans2val = (ans2val+sp[ans2][len])%mod ;\n \n    printf(\"%d\\n%d\\n\", (int)ans1, (int)ans2val) ;\n \n    return 0 ;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "477",
    "index": "E",
    "title": "Dreamoon and Notepad",
    "statement": "Dreamoon has just created a document of hard problems using notepad.exe. The document consists of $n$ lines of text, $a_{i}$ denotes the length of the $i$-th line. He now wants to know what is the fastest way to move the cursor around because the document is really long.\n\nLet $(r, c)$ be a current cursor position, where $r$ is row number and $c$ is position of cursor in the row. We have $1 ≤ r ≤ n$ and $0 ≤ c ≤ a_{r}$.\n\nWe can use following six operations in notepad.exe to move our cursor assuming the current cursor position is at $(r, c)$:\n\n- up key: the new cursor position $(nr, nc) = (max(r - 1, 1), min(a_{nr}, c))$\n- down key: the new cursor position $(nr, nc) = (min(r + 1, n), min(a_{nr}, c))$\n- left key: the new cursor position $(nr, nc) = (r, max(0, c - 1))$\n- right key: the new cursor position $(nr, nc) = (r, min(a_{nr}, c + 1))$\n- HOME key: the new cursor position $(nr, nc) = (r, 0)$\n- END key: the new cursor position $(nr, nc) = (r, a_{r})$\n\nYou're given the document description ($n$ and sequence $a_{i}$) and $q$ queries from Dreamoon. Each query asks what minimal number of key presses is needed to move the cursor from $(r_{1}, c_{1})$ to $(r_{2}, c_{2})$.",
    "tutorial": "Although swapping two parts of a query would result in different answer, if we reverse the lines length alltogether then the answer would stay the same. So we only analyze queries where $r2  \\ge  r1$. The answers would comes in several types, we'll discuss them one by one: 1. HOME key being pressed once: the answer will be $1(HOME) + r2 - r1(down keys) + c2(right keys)$. Note that this is the best answer if the HOME key is ever pressed once, so we won't consider HOME key anymore. This step is $O(1)$ for a single query, thus $O(q)$ in total. 2. direct presses $r2 - r1$ down keys and no or one END key in those rows: because the cursor position will be reset to the row length if we go down to a row with length less than current cursor position, the possible positions that can be at row $p$ if we start at end of each previous rows can be track with a stack. The position directly pressing only down keys from $r1$ to $r2$ is $min(c1, the length of first row after r1 in stack)$. We can use a binary search to get the first row after or equal $r1$ in stack. From that row till $r2$ in the stack are the positions possible when pressing ONE END key (pressing more won't get more possible positions), we can use a binary search to find the position closest to $c2$ which is the best. We can sort all queries and use $O(qlgn)$ time for queries and $O(n)$ time for maintaining stack, so $O(qlgn + n)$ in total. 3. go back some rows and press one or no END key at the row: we only interested in END OF rows in stack constructed in 2.. We can use a binary search in stack to identify the range of rows interested. For those lengths of row less than $c2$(also can use a binary search to locate) we only need to consider the first one encountered(closest to $r1$), note still need to consider if it needs an END key for this case. For those lengths of row greater than or equal to $c2$, the answer would be $r1 + r2 - 2 * (row reached) + (length of the row) - c2 + (1 if length of the row greater than c1)$. The terms related to row in the previous formula is $2 * (row reached) + (length of the row) + (1 if length of the row greater than c1)$. We can identify the range with and without +1(last term) and query in a segment tree of the minimal value of $2 * (row reached) + (length of the row)$ for each range. Thus the time need here is $O(nlgn)$ for maintaining segment tree and $O(qlgn)$ for query while sharing with the stack of 2., so $O(nlgn + qlgn)$ in total. 4. go beyond r2 some rows and press no or one END at the row: this needs a reversed stack and very similar approach of 3.. The time complexity is the same as 2. and 3.. So the total time complexity is $O((n + q)lgn)$, note this problem is very hard to get the code right. time complexity: $O((n + q)lgn)$",
    "code": "#include <bits/stdc++.h>\n#define PB push_back\ntypedef long long LL;\nusing namespace std;\nconst int SIZE = 4e5+1;\nconst int MAX = 1e9;\nint n,a[SIZE],an[SIZE],d[SIZE<<2],stk[SIZE],ml[SIZE];\nstruct data{\n    int x1,y1,y2,id;\n    data(int _x1,int _y1,int _y2,int _id){x1=_x1;y1=_y1;y2=_y2;id=_id;}\n};\nvector<data>in[2][SIZE],emp;\nvector<pair<int,int> >rmq_query[SIZE];\nvoid fresh(int& x,int v){if(x>v)x=v;}\nvoid init(int r[],int id,int L,int R){\n    r[id]=MAX;\n    if(L==R)return;\n    int M=(L+R)>>1;\n    init(r,id<<1,L,M);\n    init(r,(id<<1)|1,M+1,R);\n}\nint qq(int r[],int id,int L,int R,int ll,int rr){\n    if(ll<=L&&R<=rr)return r[id];\n    int M=(L+R)>>1;\n    if(rr<=M)return qq(r,id<<1,L,M,ll,rr);\n    if(M<ll)return qq(r,(id<<1)|1,M+1,R,ll,rr);\n    return min(qq(r,id<<1,L,M,ll,rr),qq(r,(id<<1)|1,M+1,R,ll,rr));\n}\nvoid insert(int r[],int id,int L,int R,int x,int v){\n    fresh(r[id],v);\n    if(L==R)return;\n    int M=(L+R)>>1;\n    if(x<=M)insert(r,id<<1,L,M,x,v);\n    else insert(r,(id<<1)|1,M+1,R,x,v);\n}\nvoid erase(int r[],int id,int L,int R,int x){\n    if(L==R){\n        r[id]=MAX;\n        return;\n    }\n    int M=(L+R)>>1;\n    if(x<=M)erase(r,id<<1,L,M,x);\n    else erase(r,(id<<1)|1,M+1,R,x);\n    r[id]=min(r[id<<1],r[(id<<1)|1]);\n}\nvoid Go(vector<data>input[]){\n    int i,j,k;\n    init(d,1,0,n-1);\n    for(i=1,k=0;i<=n;i++){\n        while(k>0&&a[i]<=a[stk[k-1]]){\n            erase(d,1,0,n-1,k-1);\n            k--;\n        }\n        stk[k++]=i;\n        insert(d,1,0,n-1,k-1,a[i]-2*i);\n        for(j=0;j<(int)input[i].size();j++){\n            int ll=0,rr=k,ll2=-1,rr2=k-1;\n            while(ll<rr){\n                int mm=(ll+rr)>>1;\n                if(a[stk[mm]]<=input[i][j].y2)ll=mm+1;\n                else rr=mm;\n            }\n            while(ll2<rr2){\n                int mm2=(ll2+rr2+1)>>1;\n                if(stk[mm2]>input[i][j].x1)rr2=mm2-1;\n                else ll2=mm2;\n            }\n            // case: no end\n            if(input[i][j].x1<=i){\n                if(min(ml[input[i][j].id],input[i][j].y1)<=input[i][j].y2)fresh(an[input[i][j].id],abs(input[i][j].x1-i)+input[i][j].y2-min(ml[input[i][j].id],input[i][j].y1));\n                else{\n                    fresh(an[input[i][j].id],abs(input[i][j].x1-i)+min(ml[input[i][j].id],input[i][j].y1)-input[i][j].y2);\n                    if(ll>0)fresh(an[input[i][j].id],input[i][j].x1+i-2*stk[ll-1]+input[i][j].y2-a[stk[ll-1]]);\n                    if(ll<=ll2)fresh(an[input[i][j].id],qq(d,1,0,n-1,ll,ll2)+i+input[i][j].x1-input[i][j].y2);\n                }\n            }\n            if(input[i][j].x1>=i){\n                if(min(ml[input[i][j].id],input[i][j].y1)>input[i][j].y2){\n                    if(ll>0)fresh(an[input[i][j].id],input[i][j].x1+i-2*stk[ll-1]+input[i][j].y2-a[stk[ll-1]]);\n                    if(ll<=ll2)fresh(an[input[i][j].id],qq(d,1,0,n-1,ll,ll2)+i+input[i][j].x1-input[i][j].y2);\n                }\n            }\n            // case: contain end\n            if(input[i][j].x1<=i){\n                if(ll!=k){\n                    if(stk[ll]>=input[i][j].x1)fresh(an[input[i][j].id],i-input[i][j].x1+1+a[stk[ll]]-input[i][j].y2);\n                    else{\n                        fresh(an[input[i][j].id],qq(d,1,0,n-1,ll,ll2)+i+input[i][j].x1-input[i][j].y2+1);\n                        if(ll2+1<k)fresh(an[input[i][j].id],i-input[i][j].x1+a[stk[ll2+1]]-input[i][j].y2+1);\n                    }\n                }\n                if(ll){\n                    if(stk[ll-1]>=input[i][j].x1)fresh(an[input[i][j].id],i-input[i][j].x1+1+input[i][j].y2-a[stk[ll-1]]);\n                    else fresh(an[input[i][j].id],i+input[i][j].x1-2*stk[ll-1]+input[i][j].y2-a[stk[ll-1]]+1);\n                }\n            }\n            if(input[i][j].x1>=i){\n                if(ll)fresh(an[input[i][j].id],i+input[i][j].x1-2*stk[ll-1]+input[i][j].y2-a[stk[ll-1]]+1);\n                if(ll!=k&&ll2>=ll)fresh(an[input[i][j].id],qq(d,1,0,n-1,ll,ll2)+i+input[i][j].x1-input[i][j].y2+1);\n            }\n        }\n    }\n}\nint BIT[SIZE];\nvoid BIT_ins(int x,int v){for(;x<SIZE;x+=x&-x)fresh(BIT[x],v);}\nint BIT_qq(int x){int res=MAX;for(;x;x-=x&-x)res=min(res,BIT[x]);return res;}\nint main(){\n    int Q;\n    scanf(\"%d\",&n);\n    for(int i=1;i<=n;i++)scanf(\"%d\",&a[i]);\n    scanf(\"%d\",&Q);\n    for(int i=0;i<Q;i++){\n        int x1,y1,x2,y2;\n        scanf(\"%d%d%d%d\",&x1,&y1,&x2,&y2);\n        in[0][x2].PB(data(x1,y1,y2,i));\n        in[1][n+1-x2].PB(data(n+1-x1,y1,y2,i));\n        rmq_query[max(x1,x2)].PB(make_pair(min(x1,x2),i));\n        an[i]=abs(x1-x2)+y2+1;    // case: contain home\n    }\n    memset(BIT,0x7f,sizeof(BIT));\n    for(int i=1;i<=n;i++){\n        BIT_ins(n+1-i,a[i]);\n        for(int j=0;j<rmq_query[i].size();j++)\n            ml[rmq_query[i][j].second]=BIT_qq(n+1-rmq_query[i][j].first);\n    }\n    Go(in[0]);\n    reverse(a+1,a+n+1);\n    Go(in[1]);\n    for(int i=0;i<Q;i++)printf(\"%d\\n\",an[i]);\n    return 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "478",
    "index": "A",
    "title": "Initial Bet",
    "statement": "There are five people playing a game called \"Generosity\". Each person gives some non-zero number of coins $b$ as an initial bet. After all players make their bets of $b$ coins, the following operation is repeated for several times: a coin is passed from one player to some other player.\n\nYour task is to write a program that can, given the number of coins each player has at the end of the game, determine the size $b$ of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins $b$ in the initial bet.",
    "tutorial": "To solve the problem, it is important to note that during the game, the number of coins on the table can not be changed. The total number of coins on the table after a successful bid, remains unchanged. Therefore, by dividing the total number of coins on the table by the number of players, can obtain an initial rate for each. If you divide without remainder impossible, such a result can not play. Should pay attention to the fact that the initial rate of each of the players must be different from zero, hence, zero can never be the answer.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "478",
    "index": "B",
    "title": "Random Teams",
    "statement": "$n$ participants of the competition were split into $m$ teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.\n\nYour task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.",
    "tutorial": "If you restate the problem in terms of graph theory, it can be formulated as follows: There is a graph consisting of n vertices and m connected components. Inside each connected component, each pair of vertices connected by an edge of the component. In other words, each connected component is a full mesh. What is the smallest and the largest number of edges which may contain such a graph? Consider the process of constructing a graph of n vertices and m connected components. To begin, assume that each of the m component contains a single peak. It remains to distribute the remaining n - m vertices so as to minimize or maximize the number of edges. Note that when adding a new vertex in the connected component of size k, the number of edges is increased by k (new vertex is connected to each of the existing one edge). Consequently, in order to minimize the number of ribs formed on each step required each time to enhance top component connected smallest size. If you act according to this strategy, after the distribution of vertices on the connected components appears component size and component size. Similarly, in order to maximize the number of edges in each step must be added to the next vertex in the component connectivity greatest dimension. If you act according to such a strategy, then a single connected component of size n - m + 1, the remaining connected components will consist of a single vertex. Knowing the number of connected components and their sizes, you can count the total number of edges. For a full mesh components consisting of k vertices, the number of edges equals. It should be remembered about the need to use a 64-bit data type to store the number of edges, which depends quadratically on the value of n.",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "478",
    "index": "C",
    "title": "Table Decorations",
    "statement": "You have $r$ red, $g$ green and $b$ blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number $t$ of tables can be decorated if we know number of balloons of each color?\n\nYour task is to write a program that for given values $r$, $g$ and $b$ will find the maximum number $t$ of tables, that can be decorated in the required manner.",
    "tutorial": "Consider a situation where the value max (r, g, b) - min (r, g, b)  \\le  1, then obviously the answer is (r+g+b)/3. We can always decorate so many tables three balloons of different colors. Obviously, the remaining amount will be less than three balls, and hence can not be used to decorate the table anyway. All the remaining cases it makes sense to reduce to the previously discussed. If there is one color, such that the number of balls that color is greater than the total number of balls for the other two colors, it is advantageous to decorate a table with two balls of one color and the ball of the remaining colors, which is greater than presently. Further it is possible in many ways to group operations and to carry out more than one operation at a time. Another solution include the fact that the response is different from (r+g+b)/3, but only if max (r, g, b)  \\ge  2  \\cdot  (r + g + b - max (r, g, b)), in which case the response r + g + b - max (r, g, b). In this case, the balls of the two most rare flowers will end earlier than the balls of one the most popular, if you decorate each table with two balls of the most popular colors.",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "478",
    "index": "D",
    "title": "Red-Green Towers",
    "statement": "There are $r$ red and $g$ green blocks for construction of the red-green tower. Red-green tower can be built following next rules:\n\n- Red-green tower is consisting of some number of levels;\n- Let the red-green tower consist of $n$ levels, then the first level of this tower should consist of $n$ blocks, second level — of $n - 1$ blocks, the third one — of $n - 2$ blocks, and so on — the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one;\n- Each level of the red-green tower should contain blocks of the same color.\n\nLet $h$ be the maximum possible number of levels of red-green tower, that can be built out of $r$ red and $g$ green blocks meeting the rules above. The task is to determine how many different red-green towers having $h$ levels can be built out of the available blocks.\n\nTwo red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower.\n\nYou are to write a program that will find the number of different red-green towers of height $h$ modulo $10^{9} + 7$.",
    "tutorial": "To begin, you will notice that in order to build a red-green tower height h requires h(h+1)/2 cubes. Therefore, the height of the resulting tower predetermined limits never exceeds 893. This height can be determined in advance, if it is assumed that all blocks of the same color. Try to prove it yourself. Further it is possible to solve the problem using dynamic programming. Let F (t, r) - the number of ways to gather the greatest height of the tower, if collected t upper floors remained untapped r red cubes. Among the arguments of the function are no amounts remain green cubes g - can be uniquely determined from the values of t and r: g = g0 - (t(t+1)/2 - (r0-r)), where r0 and g0 - the initial number of red and green cubes, respectively. Well and further consideration should be given only two transitions: Build t + 1-th level of the red or green blocks: F (t, r) = F (t + 1, r - t) + F (t + 1, r). Obviously, the cache data in an array size of $893 \\times 2 \\times 105$ - not the best idea. In such a case, you can count the value of the function for all values of t from 0 to h, stored in memory, only the values for the current value of t and the previous one, from which it will depend.",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "478",
    "index": "E",
    "title": "Wavy numbers",
    "statement": "A wavy number is such positive integer that for any digit of its decimal representation except for the first one and the last one following condition holds: the digit is either strictly larger than both its adjacent digits or strictly less than both its adjacent digits. For example, numbers $35270$, $102$, $747$, $20$ and $3$ are wavy and numbers $123$, $1000$ and $2212$ are not.\n\nThe task is to find the $k$-th \\textbf{smallest} wavy number $r$ that is divisible by $n$ for the given integer values $n$ and $k$.\n\nYou are to write a program that will find the value of $r$ if it doesn't exceed $10^{14}$.",
    "tutorial": "To solve this problem, it was necessary to note that the numbers on the undulating range of from 0 to 107 is much smaller than 107. In this case, the problem can be solved using an approach meet-in-the-middle. That is separate to solve this problem for the first seven digits of the answer, and for the last seven digits of the answer. This will require the wavy separately generate all numbers in a range from 0 to 107, starting with the increase of two adjacent numbers and similar wavy numbers which begin with the decrease of two adjacent numbers. Then for each of the first half, we can calculate rl - its residue modulo n and then determine the appropriate amount of the second half, which should be equal to the remainder of the division rr = (n-rl)mod n. For the problem was a limitation of time equal to 1.5 seconds. In fact, if we write the solution to the approach meet-in-the-middle optimally enough, then the solution will take much less time. The above author's implementation can solve a similar problem for 1  \\le  n, k  \\le  1016 for about 2.5 seconds.",
    "tags": [
      "brute force",
      "dfs and similar",
      "meet-in-the-middle",
      "sortings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "479",
    "index": "A",
    "title": "Expression",
    "statement": "Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers $a$, $b$, $c$ on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets:\n\n- 1+2*3=7\n- 1*(2+3)=5\n- 1*2*3=6\n- (1+2)*3=9\n\nNote that you can insert operation signs only between $a$ and $b$, and between $b$ and $c$, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2.\n\nIt's easy to see that the maximum value that you can obtain is 9.\n\nYour task is: given $a$, $b$ and $c$ print the maximum value that you can get.",
    "tutorial": "In this task you have to consider several cases and choose the best one: int ans = a + b + c; ans = max(ans, (a + b) * c); ans = max(ans, a * (b + c)); ans = max(ans, a * b * c); cout << ans << endl;",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "479",
    "index": "B",
    "title": "Towers",
    "statement": "As you know, all the kids in Berland love playing with cubes. Little Petya has $n$ towers consisting of cubes of the same size. Tower with number $i$ consists of $a_{i}$ cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2).\n\nThe boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time.\n\nBefore going to school, the boy will have time to perform no more than $k$ such operations. Petya does not want to be late for class, so you have to help him accomplish this task.",
    "tutorial": "The task is solved greedily. In each iteration, move the cube from the tallest tower to the shortest one. To do this, each time find the position of minimum and maximum in the array of heights (in linear time).",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "479",
    "index": "C",
    "title": "Exams",
    "statement": "Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly $n$ exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.\n\nAccording to the schedule, a student can take the exam for the $i$-th subject on the day number $a_{i}$. However, Valera has made an arrangement with each teacher and the teacher of the $i$-th subject allowed him to take an exam before the schedule time on day $b_{i}$ ($b_{i} < a_{i}$). Thus, Valera can take an exam for the $i$-th subject either on day $a_{i}$, or on day $b_{i}$. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number $a_{i}$.\n\nValera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.",
    "tutorial": "The solution is again greedy. Sort the exams by increasing $a_{i}$, breaking ties by increasing $b_{i}$. Let's consider exams in this order and try to take the exams as early as possible. Take the first exams in this order on the early day ($b_{1}$). Move to the second exam. If we can take it on the day $b_{2}$ (i.e. $b_{1}  \\le  b_{2}$), do it. Otherwise, take the second exam on the day $a_{2}$. Continue the process, keeping the day of the latest exam.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "479",
    "index": "D",
    "title": "Long Jumps",
    "statement": "Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler!\n\nHowever, there is no reason for disappointment, as Valery has found another ruler, its length is $l$ centimeters. The ruler already has $n$ marks, with which he can make measurements. We assume that the marks are numbered from 1 to $n$ in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance $l$ from the origin. This ruler can be repesented by an increasing sequence $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ denotes the distance of the $i$-th mark from the origin ($a_{1} = 0$, $a_{n} = l$).\n\nValery believes that with a ruler he can measure the distance of $d$ centimeters, if there is a pair of integers $i$ and $j$ ($1 ≤ i ≤ j ≤ n$), such that the distance between the $i$-th and the $j$-th mark is exactly equal to $d$ (in other words, $a_{j} - a_{i} = d$).\n\nUnder the rules, the girls should be able to jump at least $x$ centimeters, and the boys should be able to jump at least $y$ ($x < y$) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances $x$ and $y$.\n\nYour task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances $x$ and $y$. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.",
    "tutorial": "It is easy to see that the answer is always 0, 1 or 2. If we can already measure both $x$ and $y$, output 0. Then try to measure both $x$ and $y$ by adding one more mark. If it was not successful, print two marks: one at $x$, other at $y$. So, how to check if the answer is 1? Consider all existing marks. Let some mark be at $r$. Try to add the new mark in each of the following positions: $r - x$, $r + x$, $r - y$, $r + y$. If it become possible to measure both $x$ and $y$, you have found the answer. It is easy to check this: if, for example, we are trying to add the mark at $r + x$, we just check if there is a mark at $r + x + y$ or $r + x - y$ (by a binary search, since the marks are sorted). Make sure that the adde marks are in $[0, L]$.",
    "tags": [
      "binary search",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "479",
    "index": "E",
    "title": "Riding in a Lift",
    "statement": "Imagine that you are in a building that has exactly $n$ floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from $1$ to $n$. Now you're on the floor number $a$. You are very bored, so you want to take the lift. Floor number $b$ has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make $k$ consecutive trips in the lift.\n\nLet us suppose that at the moment you are on the floor number $x$ (initially, you were on floor $a$). For another trip between floors you choose some floor with number $y$ ($y ≠ x$) and the lift travels to this floor. As you cannot visit floor $b$ with the secret lab, you decided that the distance from the current floor $x$ to the chosen $y$ must be strictly less than the distance from the current floor $x$ to floor $b$ with the secret lab. Formally, it means that the following inequation must fulfill: $|x - y| < |x - b|$. After the lift successfully transports you to floor $y$, you write down number $y$ in your notepad.\n\nYour task is to find the number of distinct number sequences that you could have written in the notebook as the result of $k$ trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by $1000000007$ ($10^{9} + 7$).",
    "tutorial": "The task is solved by a dynamic programming. State is a pair $(i, j)$, where $i$ is the number of trips made, and $j$ is the current floor. Initial state is $(0, a)$, final states are $(k, v)$, where $v$ is any floor (except $b$). It is easy to see the transitions: to calculate $dp(i, j)$, let's see what can be the previous floor. It turns out that all possible previous floors form a contiguous segment (with a hole at position $j$, because we can't visit the same floor twice in a row). So, $dp(i, j)$ is almost equal to the sum of values $dp(i - 1, t)$, where $t$ belongs to some segment $[l, r]$ (the values of $l$ and $r$ can be easily derived from the conditions from the problem statement). Using pretty standard technique called \"partial sums\" we can compute $dp(i, j)$ in $O(1)$, so overall complexity is $O(NK)$.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <ctime>\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n \nconst int MOD = 1000000007;\nconst int N = 5005;\n \nint d[2][N], n, a, b, k;\n \nbool read() {\n\tif (scanf(\"%d %d %d %d\", &n, &a, &b, &k) != 4) \n\t\treturn false;\n    \n    a--, b--;\n \n    return true;\n}\n \nint add(int a, int b) {\n \tint res = a + b;\n \n \twhile (res >= MOD) res -= MOD;\n \n \twhile (res < 0) res += MOD;\n \n \treturn res;\n}\n \nint abs(int a) {\n \tif (a < 0) return -a;\n \n \treturn a;\n}\n \nvoid solve() {\n \n\td[0][a] = 1;\t\n \n\tforn(it, k) {               \t\n \n\t\tint i = it & 1;\n\t\tint nxt = i ^ 1;\n \n\t\tforn(j, n)\n\t\t \td[nxt][j] = 0;\n \n\t\tforn(j, n) {\n\t\t\tint dv = d[i][j];\n \n\t\t\tint diff = abs(j - b);\n \n\t\t\td[nxt][std::max(j - diff + 1, 0)] = add(d[nxt][std::max(j - diff + 1, 0)], dv);\n\t\t\td[nxt][std::min(j + diff, N - 1)] = add(d[nxt][std::min(j + diff, N - 1)], -dv);\t\n\t\t}\t\n \n\t\tforn(j, n)\n\t\t \tif (j > 0) \n\t\t \t\td[nxt][j] = add(d[nxt][j], d[nxt][j - 1]);\n \n\t\tforn(j, n)\n\t\t \td[nxt][j] = add(d[nxt][j], -d[i][j]);\n\t}\t\n \n\tint ans = 0;\n \n\tforn(j, n) \n\t\tans = add(ans, d[k & 1][j]);\n \n\tprintf(\"%d\\n\", ans);\n\tfprintf(stderr, \"%d\\n\", ans);\n\tfprintf(stderr, \"%d\\n\", clock());\n}\n \nint main() {\n \n\tif (!read()) throw;\n \n\tsolve();\t\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "480",
    "index": "D",
    "title": "Parcels",
    "statement": "Jaroslav owns a small courier service. He has recently got and introduced a new system of processing parcels. Each parcel is a box, the box has its weight and strength. The system works as follows. It originally has an empty platform where you can put boxes by the following rules:\n\n- If the platform is empty, then the box is put directly on the platform, otherwise it is put on the topmost box on the platform.\n- The total weight of all boxes on the platform cannot exceed the strength of platform $S$ at any time.\n- The strength of any box of the platform at any time must be no less than the total weight of the boxes that stand above.\n\nYou can take only the topmost box from the platform.\n\nThe system receives $n$ parcels, the $i$-th parcel arrives exactly at time $in_{i}$, its weight and strength are equal to $w_{i}$ and $s_{i}$, respectively. Each parcel has a value of $v_{i}$ bourles. However, to obtain this value, the system needs to give the parcel exactly at time $out_{i}$, otherwise Jaroslav will get 0 bourles for it. Thus, Jaroslav can skip any parcel and not put on the platform, formally deliver it at time $in_{i}$ and not get anything for it.\n\nAny operation in the problem is performed instantly. This means that it is possible to make several operations of receiving and delivering parcels at the same time and in any order.\n\nPlease note that the parcel that is delivered at time $out_{i}$, immediately gets outside of the system, and the following activities taking place at the same time are made ​​without taking it into consideration.\n\nSince the system is very complex, and there are a lot of received parcels, Jaroslav asks you to say what maximum amount of money he can get using his system.",
    "tutorial": "Let's make two observations. First, consider the parcels as time segments $[in_{i}, out_{i}]$. It is true that if at some moment of time both parcel $i$ and parcel $j$ are on the platform, and $i$ is higher than $j$, then $[i n_{i},o u t_{i}]\\subset[i n_{j},o u t_{j}]$. Second, let's imagine that there are some parcels on the platform. It turns out that it is enough to know just a single number to be able to decide whether we can put another parcel on top of them. Let's denote this value as \"residual strength\". For a parcel (or a platform itself) the residual strength is it's strength minus the total weight of parcels on top of it. For a set of parcels, the residual strength is the minimum of individual residual strengths. So, we can put another parcel on top if it's weight does not exceed the residual strength. These observations lead us to a dynamic programming solution. Let the top parcel at the given moment has number $i$, and the residual strength is $rs$. Make this pair $(i, rs)$ the state of DP, because it is exactly the original problem, where the platform strength is $rs$ and there are only parcels $j$ with $[i n_{j},o u t_{j}]\\subset[i n_{i},o u t_{i}]$. In $d(i, rs)$ we will store the answer to this instance of the original problem. Which transitions are there? We can choose a set of parcels $i(1), i(2), ... i(k)$ such that This choice corresponds to the following sequence of actions: first put parcel $i(1)$ on the top of $i$. This gets us to the state $i(1), min(rs - w_{i(1)}, s_{i(1)})$, so we add up the answer for this state and the cost of $i(1)$. Then we take away all parcels, including $i(1)$, and put the parcel $i(2)$ on top of $i$, and so on. As the number of states in DP is $O(NS)$, all transitions should take linear time. It can be achieved by making an inner helper DP. This give a solution in $O(N^{2}S)$. Note that for simplicity the platform can be considered as a parcel too.",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "480",
    "index": "E",
    "title": "Parking Lot",
    "statement": "Petya's been bored at work and he is killing the time by watching the parking lot at the office. The parking lot looks from above like an $n × m$ table (a cell of the table corresponds to a single parking spot). Some spots in the parking lot are taken, others are empty.\n\nPetya watches cars riding into the parking lot one by one. After a car settles down at the parking spot, Petya amuzes himself by counting what maximum square of empty spots (i.e. a square subtable) can be seen on the parking lot if we look at it from above. Also, he takes notes of the square's size (side length) in his notebook.\n\nYou task is: given the state of the parking lot at the initial moment of time and the information about where the arriving cars park, restore what Petya wrote in his notebook. It is midday, so nobody leaves the lot.",
    "tutorial": "Let's denote the car arrivals as events. Consider the following solution (it will help to understand the author's idea): let's consider all empty square in the table. There a too many of them, but imagine that we can afford to loop through all of them. If we fix a square, we can find out when it is no longer empty: find the first event that belongs to this square. Let this event has number $x$, and the size of the square is $k$. Now we can update the answers for all events with numbers less than $x$ with a value of $k$. The model solution use the idea of Divide and Conquer. Let's make a recursive routine that takes a rectangular sub-table, bounded with $r_{1}, r_{2}, c_{1}, c_{2}$ ($r_{1}  \\le  r_{2}, c_{1}  \\le  c_{2}$), and a list of events that happen inside this sub-table. The purpose of the routine is to consider how maximal empty squares in this sub-table change in time, and to update the answers for some of the events. Let's assume that $c_{2} - c_{1}  \\le  r_{2} - r_{1}$ (the opposite case is symmetric). Take the middle row $r = (r_{1} + r_{2}) / 2$. Virtually split all the squares inside the sub-table into those which lie above $r$, those which lie below $r$, and those which intersect $r$. For the first two parts, make two recursive calls, splitting the list of events as well. Now focus on the squares that intersect the row $r$. Using initial table, for each cell $(r, c)$ we can precompute the distance to the nearest taken cell in all four directions (or the distance to the border, if there is no such cell): $up(r, c)$, $down(r, c)$, $left(r, c)$ and $right(r, c)$. Using this values, build two histograms for the row $r$: the first is an array of values $up(r, c)$, where $c_{1}  \\le  c  \\le  c_{2}$; the second is an array of values $down(r, c)$, where $c_{1}  \\le  c  \\le  c_{2}$. I say histograms here, because these arrays actually can be viewed as heights of empty columns, pointing from the row $r$ upwards and downwards. Lets call the first histogram \"upper\", the second one - \"lower\". Now consider all events inside the sub-table in the order they happen. Each event changes a single value in a histogram. If after some event $x$ the maximum empty square found in the histograms has size $k$, and the next event has number $y$, we can update answers for all events with numbers $x, x + 1, ..., y - 1$ with the value of $k$. It remains to learn to find a maximum square in two histograms. It can be done by a two-pointer approach. Set both pointers to the beginning. Move the second pointer until there is such square in histograms: there is a square with side length $k$ if (minimum on the interval in the upper histogram) + (minimum on the interval in the upper histogram) - 1 >= k. When the second pointer can not be moved any more, update the answer and move the first pointer. To find the minimum in O(1), author's solution creates a queue with minimum in O(1) support. That is, the maximum square can be found in linear time. Let's try to estimate the running time. Each call of the routine (omitting inner calls) costs $O(len \\cdot q)$, where $len$ is the shortest side of the sub-table, and $q$ is the number of events in it. If we draw a recursion tree, we will see that each second call $len$ decreases twice. The total cost of all operations in a single level of a recursion tree is $O(NK)$, where $K$ is the total number of events. As long as we have $O(logN)$, overall complexity is $O(NKlogN)$.",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2800
  },
  {
    "contest_id": "482",
    "index": "A",
    "title": "Diverse Permutation",
    "statement": "Permutation $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers not larger than $n$. We'll denote as $n$ the length of permutation $p_{1}, p_{2}, ..., p_{n}$.\n\nYour task is to find such permutation $p$ of length $n$, that the group of numbers $|p_{1} - p_{2}|, |p_{2} - p_{3}|, ..., |p_{n - 1} - p_{n}|$ has exactly $k$ distinct elements.",
    "tutorial": " Let's see, what's the solution for some $k = n - 1$: 1 10 2 9 3 8 4 7 5 6 At the odd indexes we placed increasing sequence 1, 2, 3 .., at the even - decreasing sequence $n, n - 1, n - 2, ..$. First, we must get the permutation the way described above, then get first $k$ numbers from it, and then we should make all other distances be equal to 1. This solution works with $O(n)$.",
    "code": "import java.math.BigInteger;\nimport java.util.Scanner;\nimport java.io.PrintWriter;\n \npublic class Solution {  \n  public static void main(String[] args) {\n    Scanner in = new Scanner(System.in);\n    PrintWriter out = new PrintWriter(System.out);\n    \n    int n = in.nextInt();\n    int k = in.nextInt();\n    \n    Boolean[] used = new Boolean[n];\n    for (int i = 0; i < n; ++i)\n      used[i] = false;\n    \n    int l = 0, r = n - 1;\n    \n    for (int i = 0; i < k; ++i) {\n      used[(i & 1) == 0 ? l : r] = true;\n      if ((i & 1) == 0)\n        out.print((1 + (l++)));\n      else\n        out.print((1 + (r--)));\n      out.print(' ');\n    }\n    \n    if ((k & 1) == 1) {\n      for (int i = 0; i < n; ++i) {\n        if (!used[i]) {\n          out.print(i + 1);\n          out.print(' ');\n        }\n      }\n    } else {\n      for (int i = n - 1; i >= 0; --i) {\n        if (!used[i]) {\n          out.print(i + 1);\n          out.print(' ');\n        }\n      }      \n    }\n      \n    out.close();\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "482",
    "index": "B",
    "title": "Interesting Array",
    "statement": "We'll call an array of $n$ non-negative integers $a[1], a[2], ..., a[n]$ interesting, if it meets $m$ constraints. The $i$-th of the $m$ constraints consists of three integers $l_{i}$, $r_{i}$, $q_{i}$ ($1 ≤ l_{i} ≤ r_{i} ≤ n$) meaning that value $a[l_{i}]\\,\\ \\ll\\,a[l_{i}+1]\\,\\ \\vartheta_{<\\,\\ \\cdot\\,\\cdot\\,\\ \\cdot\\,\\ \\cdot\\,\\ \\cdot\\,\\ \\hat{G}\\,\\ a[r_{i}]}$ should be equal to $q_{i}$.\n\nYour task is to find any interesting array of $n$ elements or state that such array doesn't exist.\n\nExpression $x&y$ means the bitwise AND of numbers $x$ and $y$. In programming languages C++, Java and Python this operation is represented as \"&\", in Pascal — as \"and\".",
    "tutorial": " We will solve the task for every distinct bit. Now we must handle new constraint: $l[i], r[i], q[i]$. If number $q[i]$ has 1 in bit with number $pos$, then all numbers in segment $[l[i], r[i]]$ will have 1 in that bit too. To do that, we can use a standard idea of adding on a segment. Let's do two adding operation in $s[pos]$ array - in position $l[i]$ we will add $1$, and in posiotion $r[i] + 1$ - -1. Then we will calculate partial sums of array $s[pos]$, and if $s[pos][i]$ > 0 (the sum on prefix length $i + 1$), then bit at position $pos$ will be 1, otherwise - 0. After that, you can use segment tree to check satisfying constraints.",
    "code": "#include <cstdio>\n#include <algorithm>\n \nconst int N = 1000 * 1000;\nconst int MAXBIT = 30;\nint l[N], r[N], q[N], a[N], t[4 * N];\nint sum[N];\n \n \ninline void build(int v, int l, int r) {\n \tif (l + 1 == r) {\n \t \tt[v] = a[l];\n \t \treturn;\n \t}\n \n \tint mid = (l + r) >> 1;\n\tbuild(v * 2, l, mid);\n\tbuild(v * 2 + 1, mid, r);\n \n\tt[v] = t[v * 2] & t[v * 2 + 1];\n}\n \ninline int query(int v, int l, int r, int L, int R) {\n \tif (l == L && r == R) {\n \t \treturn t[v];\n \t}\n \tint mid = (L + R) >> 1;\n \tint ans = (1ll << MAXBIT) - 1;\n \n \tif (l < mid) \n \t\tans &= query(v * 2, l, std::min(r, mid), L, mid);\n \tif (mid < r) \n \t\tans &= query(v * 2 + 1, std::max(l, mid), r, mid, R);\n \n \treturn ans;\n}\n \nint main() {\n\tint n, m;\n\tscanf(\"%d %d\\n\", &n, &m);\n\t\n\tfor(int i = 0; i < m; i++) {\n\t \tscanf(\"%d %d %d\\n\", &l[i], &r[i], &q[i]);\n\t\tl[i]--;\n\t}\n\t\n\tfor(int bit = 0; bit <= MAXBIT; bit++) {\n\t\tfor(int i = 0; i < n; i++) sum[i] = 0;\n\t\tfor(int i = 0; i < m; i++) {\n\t\t\tif ((q[i] >> bit) & 1) {\n\t\t\t\tsum[l[i]]++;\n\t\t\t\tsum[r[i]]--;\n\t \t\t}\n\t \t}\t\n\t \tfor(int i = 0; i < n; i++) {\n\t \t \tif (i > 0) sum[i] += sum[i - 1];\n \n\t \t \tif (sum[i] > 0) {\n\t \t \t \ta[i] |= (1 << bit);\n\t \t \t}\n\t \t}\n\t}\n \n\tbuild(1, 0, n);\n \n\tfor(int i = 0; i < m; i++) {\n\t\tif (query(1, l[i], r[i], 0, n) != q[i]) {\n\t\t\tputs(\"NO\");\n\t\t\treturn 0;\n\t \t}\t\n\t}\n\t\n\tputs(\"YES\");\n\tfor(int i = 0; i < n; i++) {\n\t\tif (i) printf(\" \");\n\t\tprintf(\"%d\", a[i]);\n\t}\t\n\tputs(\"\");\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "482",
    "index": "C",
    "title": "Game with Strings",
    "statement": "You play the game with your friend. The description of this game is listed below.\n\nYour friend creates $n$ distinct strings of the same length $m$ and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the $n$ strings equals $\\textstyle{\\frac{1}{n}}$. You want to guess which string was chosen by your friend.\n\nIn order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: «What character stands on position $pos$ in the string you have chosen?» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions.\n\nYou do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.",
    "tutorial": " Let's handle all string pairs and calculate the $mask$ mask, which will have 1-bits only in positions in which that strings have the same characters. In other words, we could not distinguish these strings using positions with submask of mask $mask$, then we must add in $d[mask]$ 1-bits in positions $i$ and $j$. This way in $d[mask]$ we store mask of strings, which we could not distinguish using only positions given in mask $mask$. Using information described above, we can easily calculate this dynamics. Now, when we have array $d$ calculated, it is not hard to calculate the answer. Let's handle some mask $mask$. Now we should try to make one more question in position $pos$, which is equal to adding one more 1-bit in $mask$ in position $pos$. After that we may guess some strings, they are 1-bits in mask s = d[mask] ^ d[mask | (1 << pos)]. Then you have to calculate number of bits in $s$ quickly and update the answer.",
    "code": "#include <cstdio>\n#include <iostream>\n#include <cstring>\n#include <iomanip>\n#include <algorithm>\n#include <ctime>\n \nusing namespace std;\n \nconst int N = 20;\nconst int M = 150;\nint n;\nchar s[M][N + 10];\n \ntypedef long long li;\ntypedef long double ld;\n \nli d[(1 << N)];\n \ninline bool has(li mask, int pos) {\n \treturn (mask >> pos) & 1;\n}\n \nld prob[N + 10];\nld totalGuessed[N + 10];\n \nint main() {\n \tint n;\n \tscanf(\"%d\", &n);\n \n \tfor(int i = 0; i < n; i++) {\n \t \t\n \t \tscanf(\"%s\", s[i]);\n \t}\n \n  int m = strlen(s[0]);\n \n \tfor(int i = 0; i < n; i++) {\n \t\tfor(int j = 0; j < n; j++) {\n \t\t \tif (i == j) continue;\n \n \t\t \tint same = 0;\n \n \t\t \tfor(int k = 0; k < m; k++) {\n \t\t \t \tif (s[i][k] == s[j][k]) same |= (1 << k);\n \t\t \t}\n \n \t\t \td[same] |= (1LL << i);\n \t\t}\n \t}\n \n \tfor(int mask = (1 << m) - 1; mask; mask--) {\n \t \tfor(int i = 0; i < m; i++) {\n \t \t\tif (has(mask, i)) {\n \t \t\t\td[mask ^ (1 << i)] |= d[mask];\n \t \t \t}\t\n \t \t}\n \t}\n\t\n\tlong double ans = 0;\n \n\tfor(int mask = 0; mask < (1 << m); mask++) {\n\t\tint moves = __builtin_popcount(mask) + 1;\n    \n    for(int i = 0; i < m; i++) {\n\t \t \tif (!has(mask, i)) {\n\t\t\t\tli res = d[mask] ^ d[mask ^ (1 << i)];\n\t\t\t\tif (res == 0) continue;\n \n\t \t \t\tint cntGuessed = __builtin_popcountll(res);\n \n\t \t \t\ttotalGuessed[moves] += cntGuessed;\n\t\t\t}\n\t \t}\n\t}\n \n\tfor(int i = 1; i <= m; i++) {\n\t \tld val = totalGuessed[i] * i;\n \n\t \tfor(int j = 0; j < i - 1; j++)\n\t \t\tval *= ld(i - 1 - j) / ld(m - j);\n \n\t \tans += val / ld(m - i + 1);\n\t}\n \n\tans /= ld(n);\n\tcerr << clock() << endl;\n\tcout << fixed << setprecision(15) << ans << endl;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "482",
    "index": "D",
    "title": "Random Function and Tree",
    "statement": "You have a rooted tree consisting of $n$ vertices. Let's number them with integers from $1$ to $n$ inclusive. The root of the tree is the vertex $1$. For each $i > 1$ direct parent of the vertex $i$ is $p_{i}$. We say that vertex $i$ is child for its direct parent $p_{i}$.\n\nYou have initially painted all the vertices with red color. You like to repaint some vertices of the tree. To perform painting you use the function paint that you call with the root of the tree as an argument. Here is the pseudocode of this function:\n\n\\begin{verbatim}\ncount = 0 // global integer variable\nrnd() { // this function is used in paint code\nreturn 0 or 1 equiprobably\n}\npaint(s) {\nif (count is even) then paint s with white color\nelse paint s with black color\ncount = count + 1\n\nif rnd() = 1 then children = [array of vertex s children in ascending order of their numbers]\nelse children = [array of vertex s children in descending order of their numbers]\nfor child in children { // iterating over children array\nif rnd() = 1 then paint(child) // calling paint recursively\n}\n}\n\\end{verbatim}\n\nAs a result of this function, some vertices may change their colors to white or black and some of them may remain red.\n\nYour task is to determine the number of distinct possible colorings of the vertices of the tree. We will assume that the coloring is possible if there is a nonzero probability to get this coloring with a single call of $paint(1)$. We assume that the colorings are different if there is a pair of vertices that are painted with different colors in these colorings. Since the required number may be very large, find its remainder of division by $1000000007$ ($10^{9} + 7$).",
    "tutorial": " Let's calculate $d[v][p]$ dynamics - the answer for vertex $v$ with size of parity $p$. At first step to calculate this dynamic for vertex $v$ we should count all different paintings of a subtree visiting all children in increasing order of their numbers. By multiplying this number by 2 we will get paintings visiting children in decreasing order. Now some paintings may count twice. To fix that, let's have a look on a some subtree of a vertex $v$. Consider all the parities of children subtrees visited by our function (0 or 1). First thing to note is that among these parities exist two different values, the subtree will have different paintings with different ordering (you can prove it yourself). Otherwise, all our children sizes have the same parity. If all sizes are even, this subtree will be counted twice. Otherwise, if sizes are odd, we are interested only in odd count of visited subtrees. This way, we must subtract from our dynamic the number of ways to paint any number of children with even subtree sizes and odd number of children with odd subtree sizes.",
    "code": "#define _USE_MATH_DEFINES\n \n#include <iostream>\n#include <cstdio>\n#include <map>\n#include <vector>\n#include <set>\n#include <string>\n#include <list>\n#include <cstdlib>\n#include <algorithm>\n#include <iomanip>\n#include <queue>\n#include <stack>\n#include <bitset>\n#include <cassert>\n#include <cmath>\n#include <ctime>\n \nusing namespace std;\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<ld, ld> pt;\n \n#define all(a) a.begin(), a.end()\n#define pb push_back\n#define mp make_pair\n#define forn(i,n) for (int i = 0; i < int(n); ++i)\n#define ft first\n#define sc second\n#define x first\n#define y second\n \nconst int INF = 1e9;\nconst ld EPS = 1e-10;\n \nconst int N = 100005;\n \nint n;\nvector<int> g[N];\n \nbool read()\n{\n\tif (!(cin >> n))\n        return false;\n    forn (i, n - 1)\n    {\n        int p;\n        cin >> p;\n        p--;\n        g[p].pb(i + 1);\n    }\n    return true;\n}\n \nint mod = INF + 7;\n \nli dp[N][2];\n \nli dp2[2][2];\n \nli calcdp(int v, int p)\n{\n    if (g[v].size() == 0)\n        dp[v][1] = 1, dp[v][0] = 0;\n    if (dp[v][p] != -1)\n        return dp[v][p];\n \n    dp[v][1] = 1, dp[v][0] = 0;\n \n    forn (i, g[v].size())\n    {\n        li ndp0 = (dp[v][1] * calcdp(g[v][i], 1) + dp[v][0] * calcdp(g[v][i], 0)) % mod;\n        li ndp1 = (dp[v][0] * calcdp(g[v][i], 1) + dp[v][1] * calcdp(g[v][i], 0)) % mod;\n        dp[v][0] = (dp[v][0] + ndp0) % mod;\n        dp[v][1] = (dp[v][1] + ndp1) % mod;\n    }\n \n\tdp[v][0] = (dp[v][0] * 2) % mod;\n    dp[v][1] = (dp[v][1] * 2) % mod;\n \n    dp2[0][0] = dp2[1][0] = 1;\n    dp2[0][1] = dp2[1][1] = 0;\n \n    forn (i, g[v].size())\n    {\n        li lval = dp2[0][1];\n        dp2[0][1] = (dp2[0][1] + calcdp(g[v][i], 0) * dp2[0][0]) % mod;\n        dp2[0][0] = (dp2[0][0] + calcdp(g[v][i], 0) * lval) % mod;\n \n        lval = dp2[1][1];\n        dp2[1][1] = (dp2[1][1] + calcdp(g[v][i], 1) * dp2[1][0]) % mod; \n        dp2[1][0] = (dp2[1][0] + calcdp(g[v][i], 1) * lval) % mod;\n    }\n \n    dp[v][1] = ((dp[v][1] - dp2[0][0] - dp2[0][1]) % mod + mod) % mod;\n    dp[v][0] = ((dp[v][0] - dp2[1][1]) % mod + mod) % mod;\n \n    return dp[v][p];\n}\n \nvoid solve() \n{\n    forn (i, N)\n        forn (j, 2)\n            dp[i][j] = -1;\n    \n    cout << (calcdp(0, 0) + calcdp(0, 1)) % mod << endl;\n}   \n \nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n \n    while(read())\n        solve();\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "482",
    "index": "E",
    "title": "ELCA",
    "statement": "You have a root tree containing $n$ vertexes. Let's number the tree vertexes with integers from $1$ to $n$. The tree root is in the vertex $1$.\n\nEach vertex (except fot the tree root) $v$ has a direct ancestor $p_{v}$. Also each vertex $v$ has its integer value $s_{v}$.\n\nYour task is to perform following queries:\n\n- \\textbf{P} $v$ $u$ ($u ≠ v$). If $u$ isn't in subtree of $v$, you must perform the assignment $p_{v} = u$. Otherwise you must perform assignment $p_{u} = v$. Note that after this query the graph continues to be a tree consisting of $n$ vertexes.\n- \\textbf{V} $v$ $t$. Perform assignment $s_{v} = t$.\n\nYour task is following. Before starting performing queries and after each query you have to calculate expected value written on the lowest common ancestor of two equiprobably selected vertices $i$ and $j$. Here lowest common ancestor of $i$ and $j$ is the deepest vertex that lies on the both of the path from the root to vertex $i$ and the path from the root to vertex $j$. Please note that the vertices $i$ and $j$ can be the same (in this case their lowest common ancestor coincides with them).",
    "tutorial": " Let's split all $M$ requests in $\\sqrt{M}$ blocks containing $\\sqrt{M}$ requests each. Every block will be processed following way: First using dfs we need to calculate $p a t h_{v}=\\sum\\left(s i z e_{p_{u}}-s i z e_{u}\\right)\\cdot V_{p_{u}}$ for every vertex $v$, where $u$ is every ancestor of $v$, $size_{i}$ - size of subtree of vertex $i$, including itself. This value shows how will the answer change after removing or adding vertex $v$ as child to any other vertex, furthermore, answer will change exactly by $path_{v} \\cdot size_{v}$ (decreasing or increasing). Then we will calculate $ch_{v}$ the same way - the number of all possible vertex pairs, which have LCA in vertex $v$. This value shows how the answer changes after changing $V_{v}$ - if $V_{v}$ changes by $dV_{v}$, answer changes by $ch_{v} \\cdot dV_{v}$. Then mark all vertexes, which occur in our block at least once (in worst case their number is $2{\\sqrt{M}}$). Next, mark every vertex being LCA of some pair of already marked vertexes, using DFS. We can prove that final number of these vertexes is at most $\\mathbb{K}{\\sqrt{M}}-1$. After all this we got 'compressed' tree, containing only needed vertexes. Parent of vertex $i$ in compressed tree we will call vertex numbered $P_{i}$. On the image above example of this 'compression' way is given. Vertexes colored red are vertexes in request block, blue - vertexes marked after LCA, dotted line - $P_{v}  \\rightarrow  v$ edges in compressed tree. On such compressed tree we need to calculate one new value $C_{v}$ for every vertex $v$ - the size of a vertex, lying on a way from $P_{v}$ to $v$ after $P_{v}$ on main (non-compressed) tree (son of a $P_{v}$ vertex in main tree). Now we should process request on changing parent of vertex $v$ from $p_{v}$ to $u$ on a compressed tree. The answer will change by $path_{v} \\cdot size_{v}$. Now for every vertex $i$, lying on a way from root to $P_{v}$ vertex, two values will change: $size_{i}$ will be decreased by $size_{v}$, but $ch_{i}$ will be decreased by $size_{v} \\cdot (size_{i} - C_{t})$, ($P_{t} = i$), but $path_{i}$ will stay unchanged. For every other vertex $j$ only $path_{j}$ will be changed: it will be decreased by ${\\it3}^{\\prime}\\tilde{\\chi}\\theta_{\\bar{\\upsilon}}\\cdot\\left.\\right.\\left\\{\\left._{\\mathrm{Cd}}\\left(\\upsilon_{\\mathrm{1}}\\right)\\right\\}$. After that, we got compressed subtree where subtree of a vertex $v$ is missing. Next, doing the same way as above, all values are changed considering that $v$ (and all it's subtree) is a children of a vertex $u$. Do not forget to change $C_{v}$ too. Let's see, how the value-changing request of a vertex $v$ is to be processed. As described above, the answer will be changed by $ch_{v} \\cdot dV_{v}$. For every vertex $i$ lying in vertex $v$ subtree only $path_{i}$ will be changed (it could be easy done using $C_{to}$ values), all other values stay unchanged. This solution has $O(N{\\sqrt{M}}+M{\\sqrt{M}})$ complexity, but in $N = M$ case it has to be $O(N{\\sqrt{N}})$.",
    "code": "#include <cstdio>\n#include <cstring>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n#include <cassert>\n#include <iomanip>\n \nusing namespace std;\n \n#define forn(i,n) for (int i = 0; i < int(n); ++i)\n#define sz(a) int(a.size())\n#define pb push_back\n#define all(a) a.begin(),a.end()\n#define mp make_pair\n \ntypedef long long li;\ntypedef long double ld;\n \ntypedef pair<int,int> pt;\n#define ft first\n#define sc second\n \nconst int N = 100105;\n \nli n2;\nint n, m;\nint p[N], V[N];\n \npair <char, pt> req[N];\nvector <int> g[N];\nbool marked[N], query[N];\n \nint szv;\nint v[N];\n \nint dfs(int v) {\n\tint res = query[v];\n \n\tfor (int i = 0; i < sz(g[v]); ++i) {\n\t\tint cur = dfs(g[v][i]);\n\t\tif (cur && res)\n\t\t\tmarked[v] = true;\n\t\tres += cur;\n\t}\n \n\treturn res;\n}\n \ninline void get_lcas() {\n\tint szq = 0;\n \n\tforn(i, n) {\n\t\tmarked[i] = query[i];\n\t\tszq += query[i];\n\t}\n \n\tdfs(0);\n \n\tszv = 0;\n\tforn(i, n)\n\t\tif (marked[i])\n\t\t\tv[szv++] = i;\n \n\tassert(szq * 2 - 1 >= szv);\n}\n \ninline bool read() {\n\tif (scanf(\"%d\", &n) != 1)\n\t\treturn false;\n\tn2 = li(n) * n;\n \n\tforn(i, n - 1) {\n\t\tscanf(\"%d\", &p[i + 1]);\n\t\tp[i + 1]--;\n\t}\n \n\tforn(i, n)\n\t\tscanf(\"%d\", &V[i]);\n\t\n\tscanf(\"%d\", &m);\n\tchar buf[2];\n\tint a, b;\n \n\tforn(i, m) {\n\t\tscanf(\"%s %d %d\", buf, &a, &b);\n\t\treq[i] = mp(buf[0], mp(a, b));\n\t}\n \n\treturn true;\n}\n \nint tin[N], tout[N], T;\n \ninline bool is_ancestor(int a, int b) {\n\treturn tin[a] <= tin[b] && tout[b] <= tout[a];\n}\n \nli sum, path[N], ch[N];\nint sz[N];\n \nvoid calcsz(int v) {\n\ttin[v] = T++;\n\tsz[v] = 1;\n\tch[v] = 0;\n \n\tforn(i, sz(g[v])) {\n\t\tint to = g[v][i];\n\t\tcalcsz(to);\n\t\tch[v] += li(sz[v]) * sz[to];\n\t\tsum += 2 * li(sz[v]) * sz[to] * V[v];\n\t\tsz[v] += sz[to];\n\t}\n \n\ttout[v] = T++;\n}\n \nvoid calcpath(int v, int p) {\n\tif (v != p)\n\t\tpath[v] = path[p] + li(sz[p] - sz[v]) * V[p];\n\telse\n\t\tpath[v] = 0;\n \n\tforn(i, sz(g[v]))\n\t\tcalcpath(g[v][i], v);\n}\n \ninline void rebuild() {\n\tsum = 0;\n\tforn(i, n)\n\t\tsum += V[i];\n \n\tT = 0;\n\tforn(i, n) {\n\t\ttin[i] = tout[i] = -1;\n\t\tg[i].clear();\n\t}\n \n\tforn(i, n - 1)\n\t\tg[ p[i + 1] ].pb(i + 1);\n \n\tcalcsz(0);\n\tcalcpath(0, 0);\n}\n \nvector <int> G[N];\nint P[N], C[N];\n \nint d[N];\n \nint szsons;\npt sons[N];\n \ninline void calcps() {\n\tforn(i, szv) {\n\t\tG[ v[i] ].clear();\n\t\tP[ v[i] ] = -1;\n\t\tC[ v[i] ] = 0;\n\t}\n \n\tforn(i, szv)\n\t\td[i] = 0;\n \n\tforn(i, szv)\n\t\tforn(j, szv)\n\t\t\tif (i != j && is_ancestor(v[i], v[j]))\n\t\t\t\td[j]++;\n \n\tforn(_, szv) {\n\t\tint i = -1;\n \n\t\tforn(j, szv)\n\t\t\tif (d[j] == 0)\n\t\t\t\ti = j;\n \n\t\td[i] = -1;\n \n\t\tassert(i != -1);\n \n\t\tforn(j, szv)\n\t\t\tif (i != j && is_ancestor(v[i], v[j])) {\n\t\t\t\tif (d[j] == 1) {\n\t\t\t\t\tP[ v[j] ] = v[i];\n\t\t\t\t\tG[ v[i] ].pb(v[j]);\n\t\t\t\t}\n\t\t\t\td[j]--;\n\t\t\t}\n \n\t\tszsons = sz(G[ v[i] ]);\n\t\tforn(j, sz(G[ v[i] ])) {\n\t\t\tint to = G[ v[i] ][j];\n\t\t\tsons[j] = mp(tin[to], to);\n\t\t}\n \n\t\tsort(sons, sons + szsons);\n \n\t\tint pos = 0;\n\t\tforn(j, sz(g[ v[i] ])) {\n\t\t\tint to = g[ v[i] ][j];\n\t\t\twhile (pos < szsons && is_ancestor(to, sons[pos].sc))\n\t\t\t\tC[ sons[pos++].sc ] = sz[to];\n\t\t}\n\t}\n}\n \nvoid dfspath(int v, li delta) {\n\tpath[v] += delta;\n\tforn(i, sz(G[v]))\n\t\tdfspath(G[v][i], delta);\n}\n \ninline void updpath(int v, int mul) {\n\tint cur = v;\n\twhile (P[cur] != -1) {\n\t\tli delta = mul * li(sz[v]) * V[ P[cur] ];\n\t\tforn(i, sz(G[ P[cur] ])) {\n\t\t\tint to = G[ P[cur] ][i];\n\t\t\tif (to != cur)\n\t\t\t\tdfspath(to, delta);\n\t\t}\n \n\t\tint c = C[cur];\n\t\tif (cur != v)\n\t\t\tC[cur] += mul * sz[v];\n \n\t\tcur = P[cur];\n\t\tch[cur] += mul * li(sz[v]) * (sz[cur] - c);\n\t\tsz[cur] += mul * sz[v];\n\t}\n}\n \nbool visit(int v, int what) {\n\tint cur = what;\n\twhile (cur != -1) {\n\t\tif (cur == v)\n\t\t\treturn true;\n\t\tcur = P[cur];\n\t}\n\treturn false;\n}\n \ninline void output() {\n\t//cerr << sum << \" \";\n\tprintf(\"%0.9lf\\n\", double(sum) / double(n2));\n}\n \ninline void solve() {\n\tint bl = 0;\n\twhile (bl * bl < m)\n\t\tbl++;\n \n\trebuild();\n\toutput();\n \n\tfor (int left = 0; left < m; left += bl) {\n\t\trebuild();\n \n\t\tforn(i, n)\n\t\t\tquery[i] = false;\n \n\t\tforn(offs, bl) {\n\t\t\tint i = left + offs;\n\t\t\tif (i >= m)\n\t\t\t\tbreak;\n\t\t\tquery[req[i].sc.ft - 1] = true;\n\t\t\tif (req[i].ft == 'P')\n\t\t\t\tquery[req[i].sc.sc - 1] = true;\n\t\t}\n \n\t\tget_lcas();\n\t\tcalcps();\n \n\t\tforn(offs, bl) {\n\t\t\tint i = left + offs;\n\t\t\tif (i >= m)\n\t\t\t\tbreak;\n \n\t\t\tif (req[i].ft == 'P') {\n\t\t\t\tint v = req[i].sc.ft, u = req[i].sc.sc;\n\t\t\t\t--v, --u;\n \n\t\t\t\tif (visit(v, u))\n\t\t\t\t\tswap(v, u);\n \n\t\t\t\tsum -= 2 * path[v] * sz[v];\n\t\t\t\tupdpath(v, -1);\n\t\t\t\tC[v] = 0;\n \n\t\t\t\tdfspath(v, -path[v]);\n\t\t\t\tG[ P[v] ].erase(find(all(G[ P[v] ]), v));\n \n\t\t\t\tP[v] = u;\n\t\t\t\tp[v] = u;\n \n\t\t\t\tdfspath(v, path[u] + li(sz[u]) * V[u]);\n\t\t\t\tG[ P[v] ].pb(v);\n\t\t\t\n\t\t\t\tsum += 2 * path[v] * sz[v];\n\t\t\t\tupdpath(v, +1);\n\t\t\t\tC[v] = sz[v];\n\t\t\t}\n \n\t\t\tif (req[i].ft == 'V') {\n\t\t\t\tint v = req[i].sc.ft, val = req[i].sc.sc;\n\t\t\t\t--v;\n \n\t\t\t\tint dv = val - V[v];\n\t\t\t\tsum += 2 * ch[v] * dv + dv;\n \n\t\t\t\tforn(i, sz(G[v])) {\n\t\t\t\t\tint& to = G[v][i];\n\t\t\t\t\tdfspath(to, li(dv) * (sz[v] - C[to]));\n\t\t\t\t}\n \n\t\t\t\tV[v] = val;\n\t\t\t}\n \n\t\t\toutput();\n\t\t}\n\t}\n}\n \nint main() {\n\tread();\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "483",
    "index": "A",
    "title": "Counterexample ",
    "statement": "Your friend has recently learned about coprime numbers. A pair of numbers ${a, b}$ is called coprime if the maximum number that divides both $a$ and $b$ is equal to one.\n\nYour friend often comes up with different statements. He has recently supposed that if the pair $(a, b)$ is coprime and the pair $(b, c)$ is coprime, then the pair $(a, c)$ is coprime.\n\nYou want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers $(a, b, c)$, for which the statement is false, and the numbers meet the condition $l ≤ a < b < c ≤ r$.\n\nMore specifically, you need to find three numbers $(a, b, c)$, such that $l ≤ a < b < c ≤ r$, pairs $(a, b)$ and $(b, c)$ are coprime, and pair $(a, c)$ is not coprime.",
    "tutorial": " This problem has two possible solutions: Let's handle all possible triples and check every of them for being a counterexample. This solution works with asymptotics $O(n^{3}logA)$ Handle only a few cases. It could be done like this:",
    "code": "#include <iostream>\n \n \nusing namespace std;\n \nint main() {\n\tlong long l, r;\n\tcin >> l >> r;\n \n\tif (r - l + 1 < 3) {\n\t \tcout << -1 << endl;\n\t \treturn 0;\n\t}\n \n\tif (l % 2 == 0) {\n\t \tcout << l << ' ' << l + 1 << ' ' << l + 2 << endl;\n\t \treturn 0;\n\t}\n \n\tif (r - l + 1 > 3){\n\t \tcout << l + 1 << ' ' << l + 2 << ' ' << l + 3 << endl;\n\t \treturn 0;\n\t}\n \n\tcout << -1 << endl;\n}\t",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "483",
    "index": "B",
    "title": "Friends and Presents",
    "statement": "You have two friends. You want to present each of them several positive integers. You want to present $cnt_{1}$ numbers to the first friend and $cnt_{2}$ numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.\n\nIn addition, the first friend does not like the numbers that are divisible without remainder by prime number $x$. The second one does not like the numbers that are divisible without remainder by prime number $y$. Of course, you're not going to present your friends numbers they don't like.\n\nYour task is to find such minimum number $v$, that you can form presents using numbers from a set $1, 2, ..., v$. Of course you may choose not to present some numbers at all.\n\nA positive integer number greater than 1 is called prime if it has no positive divisors other than 1 and itself.",
    "tutorial": " Jury's solution is using binary search. First, you can notice that if you can make presents with numbers $1, 2, ..., v$ then you can make presents with numbers $1, 2, ..., v, v + 1$ too. Let $f(v)$ be the function returning true or false: is it right, that you can make presents with numbers $1, 2, ..., v$. Let $f_{1}$ be the number of numbers divisible by $x$, $f_{2}$ - the number of numbers divisible by $y$, and $both$ - number of numbers divisible by $x$ and by $y$ (as soon as $x$ and $y$ are primes, it is equivalent to divisibility by $x \\cdot y$). Then to first friend at first we shold give $f_{2} - both$ numbers, and to second friend $f_{1} - both$ numbers. Then we must check, could we give all other numbers divisible neither by $x$ nor by $y$. This solution works with $O(\\log n)$",
    "code": "#include <cstdio>\n \nusing namespace std;\n \ntypedef long long li;\n \nint cnt[2], v[2];\n \ninline bool f(li val) {\n \tli f[] = {val / v[0], val / v[1]};\n \n  li l = v[0] * 1ll * v[1];\n \n \tli both = val / l;\n \n \t\n \tli other = val - f[0] - f[1] + both;\n \n \tf[0] -= both;\n \tf[1] -= both;\n \n \tli tcnt[] = {cnt[0] - f[1], cnt[1] - f[0]};\n \n \tif (tcnt[0] < 0) tcnt[0] = 0;\n \tif (tcnt[1] < 0) tcnt[1] = 0;\n \n \treturn (tcnt[0] + tcnt[1] <= other);\n                    \n}\n \nint main() {\n\tscanf(\"%d %d %d %d\", &cnt[0], &cnt[1], &v[0], &v[1]);\n \n\tli l = 0;\n\tli r = li(1e18);\n \n \n\twhile (r - l > 1) {\n\t \tli mid = (l + r) >> 1;\n    if (f(mid)) {\n\t \t\tr = mid;\n\t \t} else {\n\t \t\tl = mid; \t\n\t \t}\n\t}\n \n\tprintf(\"%I64d\\n\", r); \n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "484",
    "index": "A",
    "title": "Bits",
    "statement": "Let's denote as ${\\mathrm{popcount}}(x)$ the number of bits set ('1' bits) in the binary representation of the non-negative integer $x$.\n\nYou are given multiple queries consisting of pairs of integers $l$ and $r$. For each query, find the $x$, such that $l ≤ x ≤ r$, and ${\\mathsf{P o P c o u n t}}(x)$ is maximum possible. If there are multiple such numbers find the smallest of them.",
    "tutorial": "Let us define function $f(L, R)$, that gives answer to the query. It looks follows: if $L = R$ then $f(L, R) = L$; else if $2^{b}  \\le  L$, where $b$ - maximum integer such $2^{b}  \\le  R$, then $f(L, R) = f(L - 2^{b}, R - 2^{b}) + 2^{b}$; else if $2^{b + 1} - 1  \\le  R$ then $f(L, R) = 2^{b + 1} - 1$; else $f(L, R) = 2^{b} - 1$. Total complexity is $O(logR)$ per query.",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1700
  },
  {
    "contest_id": "484",
    "index": "B",
    "title": "Maximum Value",
    "statement": "You are given a sequence $a$ consisting of $n$ integers. Find the maximum possible value of $a_{i}{\\mathrm{~mod~}}a_{j}$ (integer remainder of $a_{i}$ divided by $a_{j}$), where $1 ≤ i, j ≤ n$ and $a_{i} ≥ a_{j}$.",
    "tutorial": "Let us iterate over all different $a_{j}$. Since we need to maximize $a_{i}{\\mathrm{~mod~}}a_{j}$, then iterate all integer $x$ (such $x$ divisible by $a_{j}$) in range from $2a_{j}$ to $M$, where $M$ - doubled maximum value of the sequence. For each such $x$ we need to find maximum $a_{i}$, such $a_{i} < x$. Limits for numbers allow to do this in time $O(1)$ with an array. After that, update answer by value $a_{i}{\\mathrm{~mod~}}a_{j}$. Total time complexity is $O(nlogn + MlogM)$.",
    "tags": [
      "binary search",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "484",
    "index": "C",
    "title": "Strange Sorting",
    "statement": "How many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: \\underline{$d$-sorting}. This sorting is applied to the strings of length at least $d$, where $d$ is some positive integer. The characters of the string are sorted in following manner: first come all the 0-th characters of the initial string, then the 1-st ones, then the 2-nd ones and so on, in the end go all the $(d - 1)$-th characters of the initial string. By the $i$-th characters we mean all the character whose positions are exactly $i$ modulo $d$. If two characters stand on the positions with the same remainder of integer division by $d$, their relative order after the sorting shouldn't be changed. The string is zero-indexed. For example, for string 'qwerty':\n\nIts 1-sorting is the string 'qwerty' (all characters stand on 0 positions),\n\nIts 2-sorting is the string 'qetwry' (characters 'q', 'e' and 't' stand on 0 positions and characters 'w', 'r' and 'y' are on 1 positions),\n\nIts 3-sorting is the string 'qrwtey' (characters 'q' and 'r' stand on 0 positions, characters 'w' and 't' stand on 1 positions and characters 'e' and 'y' stand on 2 positions),\n\nIts 4-sorting is the string 'qtwyer',\n\nIts 5-sorting is the string 'qywert'.\n\nYou are given string $S$ of length $n$ and $m$ \\underline{shuffling} operations of this string. Each \\underline{shuffling} operation accepts two integer arguments $k$ and $d$ and transforms string $S$ as follows. For each $i$ from $0$ to $n - k$ in the increasing order we apply the operation of $d$-sorting to the substring $S[i..i + k - 1]$. Here $S[a..b]$ represents a substring that consists of characters on positions from $a$ to $b$ inclusive.\n\nAfter each \\underline{shuffling} operation you need to print string $S$.",
    "tutorial": "Note, that $d$-sorting is just a permutation (call it $P$), because it does not depends on characters in string. Look at shuffling operation in different way: instead of going to the next substring and sort it, we will shift string to one character left. It remains to understand that shift of string the permutation too (call it $C$). Now its clear, we need to calculate $S \\cdot P \\cdot C \\cdot P \\cdot C... = S \\cdot (P \\cdot C)^{n - k + 1}$. And after that shift string for $k - 1$ character to the left for making answer to the shuffling operation. Here we use the multiplication of permutations. Since they are associative, that we can use binary algorithm to calculate $(P \\cdot C)^{n - k + 1}$. Total time complexity is $O(nmlogn)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "484",
    "index": "D",
    "title": "Kindergarten",
    "statement": "In a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's \\underline{sociability} is the maximum difference of charisma of two children in the group (in particular, if the group consists of one child, its sociability equals a zero).\n\nThe teacher wants to divide the children into some number of groups in such way that the total \\underline{sociability} of the groups is maximum. Help him find this value.",
    "tutorial": "Let us note, that in optimal answer any segment that making a group contains their minimum and maximum values on borders. Otherwise it will be better to split this segment to two other segments. Another note that is every segment in optimal solution is strictly monotonic (increasing or decreasing). Paying attention to the interesting points in sequence which making local maximums (i. e. $a_{i - 1} < a_{i} > a_{i + 1}$), local minimums ($a_{i - 1} > a_{i} < a_{i + 1}$), and point adjacent to them. Solve the problem by dynamic programming: $D_{i}$ is the answer in the prefix $i$. To calculate $D_{i}$ we need to look at no more than three previous interesting points and to previous $D_{i - 1}$. Total time complexity is $O(n)$.",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "484",
    "index": "E",
    "title": "Sign on Fence",
    "statement": "Bizon the Champion has recently finished painting his wood fence. The fence consists of a sequence of $n$ panels of $1$ meter width and of arbitrary height. The $i$-th panel's height is $h_{i}$ meters. The adjacent planks follow without a gap between them.\n\nAfter Bizon painted the fence he decided to put a \"for sale\" sign on it. The sign will be drawn on a rectangular piece of paper and placed on the fence so that the sides of the sign are parallel to the fence panels and are also aligned with the edges of some panels. Bizon the Champion introduced the following constraints for the sign position:\n\n- The width of the sign should be exactly $w$ meters.\n- The sign must fit into the segment of the fence from the $l$-th to the $r$-th panels, inclusive (also, it can't exceed the fence's bound in vertical direction).\n\nThe sign will be really pretty, So Bizon the Champion wants the sign's height to be as large as possible.\n\nYou are given the description of the fence and several queries for placing sign. For each query print the maximum possible height of the sign that can be placed on the corresponding segment of the fence with the given fixed width of the sign.",
    "tutorial": "Let us note that we can use binary search to find answer to the one query. Suppose at some moment was fixed height $h$ and need to know will fit the rectangle with width $w$ and height $h$ to the segment of fence from $l$-th to $r$-th panel. Let us build data structure that can answer to this question. This will be persistent segment tree with unusual function inside: maximum number of consecutive ones in segment ($maxOnes$). In leaves of segment tree will be only numbers 0 and 1. To calculate this function need to know some other values, specifically: $len$ - length of the segment in vertex of segment tree, $prefOnes$ - length of prefix that consists only of ones, $sufOnes$ - length of the suffix consist only of ones. These functions are computed as follows: $maxOnes$ is equal to $max(maxOnes(Left), maxOnes(Right), sufOnes(Left) + prefOnes(Right))$; $prefOnes$ equals $prefOnes(Right) + len(Left)$ in case of $len(Left) = prefOnes(Left)$, and $prefOnes(Left)$ otherwise; $sufOnes$ equals $sufOnes(Left) + len(Right)$ in case of $len(Right) = sufOnes(Right)$, and $sufOnes(Right)$ otherwise; $len = len(left) + len(Right)$; $Left$ and $Right$ - it is left and right sons of vertex in segment tree. As mentioned above, tree must be persistent, and it must be built as follows. First, builded empty tree of zeros. Next in position of highest plank need to put 1. The same doing for planks in decreasing order. For example if fence described with sequence $[2, 5, 5, 1, 3]$ then bottom of segment tree will changed as follows: $[0, 0, 0, 0, 0]$ -> $[0, 1, 0, 0, 0]$ -> $[0, 1, 1, 0, 0]$ -> $[0, 1, 1, 0, 1]$ -> $[1, 1, 1, 0, 1]$ -> $[1, 1, 1, 1, 1]$. And we need to remember for all $h_{i}$ their version of tree. Now to answer the question we need to make query in our segment tree (that corresponding to height $h$) on segment $[l, r]$. If $maxOnes$ form this query less than $w$, then rectangle impossible to put (otherwise possible). Building of tree will take $O(nlogn)$ time and memory. Time complexity to the one query will take $O(log^{2}n)$ time.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "485",
    "index": "A",
    "title": "Factory",
    "statement": "One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were $x$ details in the factory storage, then by the end of the day the factory has to produce $x\\ {\\mathrm{mod}}\\ m$ (remainder after dividing $x$ by $m$) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory.\n\nThe board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by $m$).\n\nGiven the number of details $a$ on the first day and number $m$ check if the production stops at some moment.",
    "tutorial": "Production will stops iff exists integer $K  \\ge  0$ such $a \\cdot 2^{K}$ is divisible by $m$. From this fact follows that $K$ maximum will be about $O(log_{2}(m))$. So if we modeling some, for example, 20 days and production does not stop, then it will never stop and answer is \"No\". Otherwise answer is \"Yes\".",
    "tags": [
      "implementation",
      "math",
      "matrices"
    ],
    "rating": 1400
  },
  {
    "contest_id": "485",
    "index": "B",
    "title": "Valuable Resources",
    "statement": "Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.\n\nLet's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square.\n\nBuilding a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.",
    "tutorial": "Let us find minimum length needed to cover points by $Ox$. It is $Maximum(x_{i}) - Minumum(x_{i})$. The same in $Oy$ - $Maximum(y_{i}) - Minumum(y_{i})$. Since we need a square city to cover all the mines, then we need to set length of this square to the maximum from those two values.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "486",
    "index": "A",
    "title": "Calculating Function",
    "statement": "For a positive integer $n$ let's define a function $f$:\n\n$f(n) = - 1 + 2 - 3 + .. + ( - 1)^{n}n$\n\nYour task is to calculate $f(n)$ for a given integer $n$.",
    "tutorial": "If $n$ is even, then the answer is $n / 2$, otherwise the answer is $(n - 1) / 2 - n$ = $- (n + 1) / 2$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "486",
    "index": "B",
    "title": "OR in Matrix",
    "statement": "Let's define logical $OR$ as an operation on two logical values (i. e. values that belong to the set ${0, 1}$) that is equal to $1$ if either or both of the logical values is set to $1$, otherwise it is $0$. We can define logical $OR$ of three or more logical values in the same manner:\n\n$a_{1}\\,\\mathrm{OR}\\,a_{2}\\,\\mathrm{OR}\\dots\\dots\\mathrm{OR}\\,a_{k}$ where $a_{i}\\in\\{0,1\\}$ is equal to $1$ if some $a_{i} = 1$, otherwise it is equal to $0$.\n\nNam has a matrix $A$ consisting of $m$ rows and $n$ columns. The rows are numbered from $1$ to $m$, columns are numbered from $1$ to $n$. Element at row $i$ ($1 ≤ i ≤ m$) and column $j$ ($1 ≤ j ≤ n$) is denoted as $A_{ij}$. All elements of $A$ are either 0 or 1. From matrix $A$, Nam creates another matrix $B$ of the same size using formula:\n\n$B_{i j}=A_{i1}\\mathrm{OR}\\,A_{i2}\\mathrm{OR}\\ldots\\mathrm{OR}\\,A_{i n}\\mathrm{OR}\\,A_{1j}\\mathrm{OR}\\,A_{2j}\\mathrm{OR}\\ldots\\mathrm{oR}\\,A_{m j}$.\n\n($B_{ij}$ is $OR$ of all elements in row $i$ and column $j$ of matrix $A$)\n\nNam gives you matrix $B$ and challenges you to guess matrix $A$. Although Nam is smart, he could probably make a mistake while calculating matrix $B$, since size of $A$ can be large.",
    "tutorial": "Hint of this problem is presented in its statement. \"$a_{1}\\,\\mathrm{OR}\\,a_{2}\\,\\mathrm{OR}\\dots\\dots\\mathrm{OR}\\,a_{k}$ where $a_{i}\\in\\{0,1\\}$ is equal to $1$ if some $a_{i} = 1$, otherwise it is equal to $0$.\" To solve this problem, do 3 following steps: Complexity: We can implement this algorithm in $O(m * n)$, but it's not neccesary since $1  \\le  m, n  \\le  100$.",
    "tags": [
      "greedy",
      "hashing",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "486",
    "index": "C",
    "title": "Palindrome Transformation",
    "statement": "Nam is playing with a string on his computer. The string consists of $n$ lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.\n\nThere is a cursor pointing at some symbol of the string. Suppose that cursor is at position $i$ ($1 ≤ i ≤ n$, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position $i - 1$ if $i > 1$ or to the end of the string (i. e. position $n$) otherwise. The same holds when he presses the right arrow key (if $i = n$, the cursor appears at the beginning of the string).\n\nWhen Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.\n\nInitially, the text cursor is at position $p$.\n\nBecause Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?",
    "tutorial": "Assuming that cursor's position is in the first half of string($i.e$ $1  \\le  p  \\le  n / 2$) (if it's not, just reverse the string, and change $p$ to $n - p + 1$, then the answer will not change). It is not hard to see that, in optimal solution, we only need to move our cusor in the first half of the string only, and the number of \"turn\" is at most once. Therefore, we have below algorithm: Find the largest index $r$ before $p$ in the first half of the string ($p  \\le  r  \\le  n / 2$) such that $s_{r}$ different to $s_{n - r + 1}$. ($s_{i}$ denote $i_{th}$ character of our input string $s$) Find the smallest index $l$ after $p$ ($1  \\le  l  \\le  p$) such that $s_{l}$ different to $s_{n - l + 1}$. In optimal solution, we move our cusor from $p$ to $l$ and then from $l$ to $r$, or move from $p$ to $r$ and then from $r$ to $l$. While moving, we also change character of string simultaneously (if needed) (by press up/down arrow keys). Be careful with some corner case(for example, does'nt exist such $l$ or $r$ discribed above). Complexity: $O(n)$.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "486",
    "index": "D",
    "title": "Valid Sets",
    "statement": "As you know, an undirected connected graph with $n$ nodes and $n - 1$ edges is called a \\underline{tree}. You are given an integer $d$ and a tree consisting of $n$ nodes. Each node $i$ has a value $a_{i}$ associated with it.\n\nWe call a set $S$ of tree nodes \\underline{valid} if following conditions are satisfied:\n\n- $S$ is non-empty.\n- $S$ is connected. In other words, if nodes $u$ and $v$ are in $S$, then all nodes lying on the simple path between $u$ and $v$ should also be presented in $S$.\n- $\\operatorname*{max}_{u\\in S}a_{u}-\\operatorname*{min}_{v\\in S}a_{v}\\leq d$.\n\nYour task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo $1000000007$ ($10^{9} + 7$).",
    "tutorial": "Firstly, we solve the case $d = +  \\infty $. In this case, we can forget all $a_{i}$ since they doesn't play a role anymore. Consider the tree is rooted at node 1. Let $F_{i}$ be the number of valid sets contain node $i$ and several other nodes in subtree of $i$ (\"several\" here means 0 or more). We can easily calculate $F_{i}$ through $F_{j}$ where $j$ is directed child node of $i$: $F_{i}=\\Pi(F_{j}+1)$. Complexity: $O(n)$. General case: $d  \\ge  0$. For each node $i$, we count the number of valid sets contain node $i$ and some other node $j$ such that $a_{i}  \\le  a_{j}  \\le  a_{i} + d$ (that means, node $i$ have the smallest value $a$ in the set). How? Start DFS from node $i$, visit only nodes $j$ such that $a_{i}  \\le  a_{j}  \\le  a_{i} + d$. Then all nodes have visited form another tree. Just apply case $d = +  \\infty $ for this new tree. We have to count $n$ times, each time take $O(n)$, so the overall complexity is $O(n^{2})$. (Be craeful with duplicate counting)",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = 2000 + 10;\nconst int MOD = (int)(1e9) + 7;\n \nvector<int> adj[MAXN];\nint a[MAXN], f[MAXN];\nbool visited[MAXN];\nint d, n;\n \nvoid DFS(int u, int root) {\n    visited[u] = true;\n    f[u] = 1;\n    for(int i = 0; i < adj[u].size(); i++) {\n        int v = adj[u][i];\n        if (!visited[v]) {\n            if ((a[v] < a[root]) || (a[v] > a[root] + d)) continue;\n            if ((a[v] == a[root]) && (v < root)) continue; // avoid duplicate counting\n            DFS(v, root);\n            f[u] = ((long long)(f[u]) * (f[v] + 1)) % MOD;\n        }\n    }\n}\n \nint main()\n{\n    cin >> d >> n;\n    for(int i = 1; i <= n; i++) cin >> a[i];\n    for(int i = 1; i <= n - 1; i++) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    int result = 0;\n    for(int i = 1; i <= n; i++) {\n        for(int j = 1; j <= n; j++) f[j] = 0, visited[j] = false;\n        DFS(i, i);\n        result = (result + f[i]) % MOD;\n    }\n    cout << result << endl;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "486",
    "index": "E",
    "title": "LIS of Sequence",
    "statement": "The next \"Data Structures and Algorithms\" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.\n\nNam created a sequence $a$ consisting of $n$ ($1 ≤ n ≤ 10^{5}$) elements $a_{1}, a_{2}, ..., a_{n}$ ($1 ≤ a_{i} ≤ 10^{5}$). A subsequence $a_{i1}, a_{i2}, ..., a_{ik}$ where $1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ n$ is called increasing if $a_{i1} < a_{i2} < a_{i3} < ... < a_{ik}$. An increasing subsequence is called longest if it has maximum length among all increasing subsequences.\n\nNam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes $i$ ($1 ≤ i ≤ n$), into three groups:\n\n- group of all $i$ such that $a_{i}$ belongs to no longest increasing subsequences.\n- group of all $i$ such that $a_{i}$ belongs to at least one \\textbf{but not every} longest increasing subsequence.\n- group of all $i$ such that $a_{i}$ belongs to every longest increasing subsequence.\n\nSince the number of longest increasing subsequences of $a$ may be very large, categorizing process is very difficult. Your task is to help him finish this job.",
    "tutorial": "LIS = Longest increasing subsequence. // Calculates $F1_{i}$ and $F2_{i}$ is familiar task, so I will not dig into this. For those who have'nt known it yet, this link may be useful) // We can calculate $D1_{i}$ and $D2_{i}$ by using advanced data structure, like BIT or Segment tree. $l$ = length of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ = $max{F1_{i}}$ = $max{F2_{j}}$. $m$ = number of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ = $\\textstyle\\sum_{F_{1i}=l}D1_{i}=\\sum_{F_{2i}=l}D2_{i}$ Let $C_{i}$ be the number of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ that $a_{i}$ belongs to. Index $i$ must in group: 1) if $C_{i}$ = 0 2) if $0  \\le  C_{i} < m$ 3) if $C_{i} = m$ How to calculate $C_{i}$? If ($F1_{i} + F2_{i} - 1 < l$) then $C_{i}$ = 0, else $C_{i} = D1_{i} * D2_{i}$. Done! We have an additional issue. The number of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ maybe very large! $D1_{i}, D2_{i}$ and $m$ maybe exceed 64-bits integer. Hence, we need to store $D1_{i}, D2_{i}$ and $m$ after modulo some integer number, call it $p$. Usually, we will choose $p$ is a prime, like $10^{9} + 7$ or $10^{9} + 9$. It's not hard to generate a test such that if you choose $p = 10^{9} + 7$ or $p = 10^{9} + 9$, your solution will lead to Wrong answer. But I have romeved such that tests, because the data tests is weak, even $p$ is not a prime can pass all tests. // Some notation is re-defined. Let $F1_{i}$ be the length of LIS ending exactly at $a_{i}$ of sequence ${a_{1}, a_{2}, ..., a_{i}}$. Let $F2_{i}$ be the length of LIS beginning exactly at $a_{i}$ of sequence ${a_{i}, a_{i + 1}, ..., a_{n}}$. $l$ = length of LIS of ${a_{1}, a_{2}, ..., a_{n}}$ = $max{F1_{i}}$ = $max{F2_{j}}$. Let $F_{i}$ be the length of LIS of sequence ${a_{1}, a_{2}, ..., a_{i - 1}, a_{i + 1}, ..., a_{n}$} (i.e the length of LIS of initial sequence $a$ after removing element $a_{i}$). Index $i$ must in group: 1) if $F1_{i} + F2_{i} - 1 < l$, otherwise: 2) if $F_{i} = l$ 3) if $F_{i} = l - 1$ How to caculate $F_{i}$? We have: $F_{i} = max{F1_{u} + F2_{v}}$ among $1  \\le  u < i < v  \\le  n$ such that $a_{u} < a_{v}$. From this formula, we can use Segment tree to calculate $F_{i}$. Due to limitation of my English, it is really hard to write exactly how. I will post my code soon. Complexity of both above solution: $O(nlogn)$.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "hashing",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "487",
    "index": "A",
    "title": "Fight the Monster",
    "statement": "A monster is attacking the Cyberland!\n\nMaster Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints ($HP$), offensive power ($ATK$) and defensive power ($DEF$).\n\nDuring the battle, every second the monster's HP decrease by $max(0, ATK_{Y} - DEF_{M})$, while Yang's HP decreases by $max(0, ATK_{M} - DEF_{Y})$, where index $Y$ denotes Master Yang and index $M$ denotes monster. Both decreases happen simultaneously Once monster's $HP ≤ 0$ and the same time Master Yang's $HP > 0$, Master Yang wins.\n\nMaster Yang can buy attributes from the magic shop of Cyberland: $h$ bitcoins per $HP$, $a$ bitcoins per $ATK$, and $d$ bitcoins per $DEF$.\n\nNow Master Yang wants to know the minimum number of bitcoins he can spend in order to win.",
    "tutorial": "It is no use to make Yang's ATK > HP_M + DEF_M (Yang already can beat it in a second). And it's no use to make Yang's DEF > ATK_M (it cannot deal any damage to him). As a result, Yang's final ATK will not exceed $200$, and final DEF will not exceed $100$. So just enumerate final ATK from ATK_Y to $200$, final DEF from DEF_Y to $100$. With final ATK and DEF known, you can calculate how long the battle will last, then calculate HP loss. You can easily find the gold you spend, and then find the optimal answer.",
    "tags": [
      "binary search",
      "brute force",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "487",
    "index": "B",
    "title": "Strip",
    "statement": "Alexandra has a paper strip with $n$ numbers on it. Let's call them $a_{i}$ from left to right.\n\nNow Alexandra wants to split it into some pieces (possibly $1$). For each piece of strip, it must satisfy:\n\n- Each piece should contain at least $l$ numbers.\n- The difference between the maximal and the minimal number on the piece should be at most $s$.\n\nPlease help Alexandra to find the minimal number of pieces meeting the condition above.",
    "tutorial": "We can use dynamic programming to solve this problem. Let $f[i]$ denote the minimal number of pieces that the first $i$ numbers can be split into. $g[i]$ denote the maximal length of substrip whose right border is $i$(included) and it satisfy the condition. Then $f[i] = min(f[k]) + 1$, where $i - g[i]  \\le  k  \\le  i - l$. We can use monotonic queue to calculate g[i] and f[i]. And this can be implemented in $O(n)$ We can also use sparse table or segment tree to solve the problem, the time complexity is $O(n\\log n)$ or $O(n\\log^{2}n)$(It should be well-implemented). For more details about monotonic queue, you can see here",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "487",
    "index": "C",
    "title": "Prefix Product Sequence",
    "statement": "Consider a sequence $[a_{1}, a_{2}, ... , a_{n}]$. Define its prefix product sequence $[a_{1}\\mod n,(a_{1}a_{2})\\mod n,\\cdot\\cdot\\cdot,(a_{1}a_{2}\\cdot\\cdot\\cdot a_{n})\\mod n]$.\n\nNow given $n$, find a permutation of $[1, 2, ..., n]$, such that its prefix product sequence is a permutation of $[0, 1, ..., n - 1]$.",
    "tutorial": "The answer is YES if and only if $n$ is a prime or $n = 1$ or $n = 4$. First we can find $a_{1}a_{2}\\cdot\\cdot\\cdot a_{n}=n!\\equiv0\\mod n$. If $n$ occurs in {a_1, \\dots ,a_{n-1}} in the prefix product sequence $0$ will occur twice which do not satisfy the condition. So $a_{n}$ must be $0$ from which we know $a_{1a}_{2}... a_{n - 1} = (n - 1)!$. But for any composite number $n > 4$ we have $(n-1)!\\equiv0\\;\\;\\mathrm{mod}\\;n$(See the proof below). So we can know that for all composite number $n > 4$ the answer is NO. For $n = 1$, $1$ is a solution. For $n = 4$, $1, 3, 2, 4$ is a solution. For any prime number $n$, let $a_{i}$ be $i/(i-1)\\mod n$. If there are two same number $a_{i}$, $a_{j}$. Then we get $i / (i - 1)  \\equiv  j / (j - 1)$ which leads to $i  \\equiv  j$, which is a contradiction. So all $n$ numbers will occur exactly once. And this is a solution. Also, we can find a primitive root $g$ of $n$ and $g^{0}, g^{1}, g^{n-3}, g^{3}, g^{n-5}, \\cdots } is also a solution. Proof: For a composite number $n > 4$ it can either be written as the products of two numbers $p, q > 1$. If $p  \\neq  q$, then we immediately get $pq|(n - 1)!$. If $p = q$, note that $n > 4$ so $2p < n$, we have $p^{2}|(n - 1)!$ So $n|(n - 1)!$ always holds which means $(n-1)!\\equiv0\\;\\;\\mathrm{mod}\\;n$",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "487",
    "index": "D",
    "title": "Conveyor Belts",
    "statement": "Automatic Bakery of Cyberland (ABC) recently bought an $n × m$ rectangle table. To serve the diners, ABC placed seats around the table. The size of each seat is equal to a unit square, so there are $2(n + m)$ seats in total.\n\nABC placed conveyor belts on each unit square on the table. There are three types of conveyor belts: \"^\", \"<\" and \">\". A \"^\" belt can bring things upwards. \"<\" can bring leftwards and \">\" can bring rightwards.\n\nLet's number the rows with $1$ to $n$ from top to bottom, the columns with $1$ to $m$ from left to right. We consider the seats above and below the top of the table are rows $0$ and $n + 1$ respectively. Also we define seats to the left of the table and to the right of the table to be column $0$ and $m + 1$. Due to the conveyor belts direction restriction there are currently no way for a diner sitting in the row $n + 1$ to be served.\n\nGiven the initial table, there will be $q$ events in order. There are two types of events:\n\n- \"A $x$ $y$\" means, a piece of bread will appear at row $x$ and column $y$ (we will denote such position as $(x, y)$). The bread will follow the conveyor belt, until arriving at a seat of a diner. It is possible that the bread gets stuck in an infinite loop. Your task is to simulate the process, and output the final position of the bread, or determine that there will be an infinite loop.\n- \"C $x$ $y$ $c$\" means that the type of the conveyor belt at $(x, y)$ is changed to $c$.\n\nQueries are performed separately meaning that even if the bread got stuck in an infinite loop, it won't affect further queries.",
    "tutorial": "This problem can be solved by classic data structures. For example, let's try something like SQRT-decomposition. Let's divide the map horizontally into some blocks. For each grid, calculate its destination when going out the current block (or infinite loop before going out current block). For each modification, recalculate the affected block by brute force. For each query, we can just use the \"destination when going out the current block\" to speed up simulation. Let $S$ be the size of a block, then the time for each modification is $O(S)$, for each query is $O(nm / S)$, since at most $O(nm / S)$ blocks, and at most $1$ grid of each block are visited. The total time complexity is $O(nm + qnm / S + pS)$, where $p$ is the number of modifications. Let $S={\\sqrt{q n m/p}}$, the complexity can be the best: $O({\\sqrt{p q n m}})$. This task can also be solve by segment tree. The time complexity is $O(n m+q\\log n+p m\\log n)$, or $O(n m+q\\log n+p m^{2}\\log n)$, depending on implementation.",
    "tags": [
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "487",
    "index": "E",
    "title": "Tourists",
    "statement": "There are $n$ cities in Cyberland, numbered from $1$ to $n$, connected by $m$ bidirectional roads. The $j$-th road connects city $a_{j}$ and $b_{j}$.\n\nFor tourists, souvenirs are sold in every city of Cyberland. In particular, city $i$ sell it at a price of $w_{i}$.\n\nNow there are $q$ queries for you to handle. There are two types of queries:\n\n- \"C $a$ $w$\": The price in city $a$ is changed to $w$.\n- \"A $a$ $b$\": Now a tourist will travel from city $a$ to $b$. He will choose a route, he also doesn't want to visit a city twice. He will buy souvenirs at the city where the souvenirs are the cheapest (possibly exactly at city $a$ or $b$). You should output the minimum possible price that he can buy the souvenirs during his travel.\n\nMore formally, we can define routes as follow:\n\n- A route is a sequence of cities $[x_{1}, x_{2}, ..., x_{k}]$, where $k$ is a certain positive integer.\n- For any $1 ≤ i < j ≤ k, x_{i} ≠ x_{j}$.\n- For any $1 ≤ i < k$, there is a road connecting $x_{i}$ and $x_{i + 1}$.\n- The minimum price of the route is $min(w_{x1}, w_{x2}, ..., w_{xk})$.\n- The required answer is the minimum value of the minimum prices of all valid routes from $a$ to $b$.",
    "tutorial": "First we can find out all cut vertices and biconnected components(BCC) by Tarjan's Algorithm. And it must form a tree. From the lemma below, we know that if we can pass by a BCC, then we can always pass any point in the BCC. We use a priority queue for each BCC to maintain the minimal price in the component. For each modification, if the vertex is a cut vertex, then modify itself and its related BCCs' priority queue. If not, modify the priority queue of its BCC. For each query, the answer is the minimal price on the path from x (or its BCC) to y (or its BCC). We can use Link-Cut Trees or Heavy-Light Decomposition with Segment Trees. To be more exact, we can only modify the father BCC of the cut vertex in order to guarantee complexity(otherwise it would be hacked by a star graph).When querying, if the LCA of x and y is a BCC. Then the father of the LCA(which is a cut vertex related to the BCC) should also be taken into account. The time complexity is $O(n+m+q\\log n)$ or $O(n+m+q\\log^{2}n)$. Lemma: In a biconnected graph with $n  \\ge  3$ points, for any three different vertices $a, b, c$, there is a simple path to from $a$ to $b$ going through $c$. Proof: Consider a biconnected graph with at least 3 vertices. If we remove any vertex or any edge, the graph is still connected. We build a network on the graph. Let's use (u,v,w) to describe a directed edge from u to v with capacity w. For each edge (u,v) of the original graph, we build (u,v,1) and (v,u,1). Build (S,c,2), (a,T,1) and (b,T,1). For each vertex other than S,T,c, we should give a capacity of 1 to the vertex. In order to give capacity to vertex u, we build two vertices u1,u2 instead of u. For each (v,u,w), build (v,u1,w). For each (u,v,w), build(u2,v,w). Finally build (u1,u2,1). Hence, if the maximal flow from S to T is 2, there is a simple path from a to b going through c. Now we consider the minimal cut of the network. It is easy to find that minimal cut <= 2, so let's prove minimal cut > 1, which means, no matter which edge of capacity 1 we cut, there is still a path from S to T. If we cut an edge like (u1,u2,1), it is equivalent to set the capacity of the vertex to 0, and equivalent to remove the vertex from the original graph. The graph is still connected, so there is still a path in the network. If we cut other edges, it is equivalent to remove an edge from the original graph. It is still connected, too. Now we have minimal cut > 1, which means maximal flow = minimal cut = 2. So there is always a simple path from a to b going through c.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "488",
    "index": "A",
    "title": "Giga Tower",
    "statement": "Giga Tower is the tallest and deepest building in Cyberland. There are $17 777 777 777$ floors, numbered from $ - 8 888 888 888$ to $8 888 888 888$. In particular, there is floor $0$ between floor $ - 1$ and floor $1$. Every day, thousands of tourists come to this place to enjoy the wonderful view.\n\nIn Cyberland, it is believed that the number \"8\" is a lucky number (that's why Giga Tower has $8 888 888 888$ floors above the ground), and, an integer is \\underline{lucky}, if and only if its decimal notation contains at least one digit \"8\". For example, $8, - 180, 808$ are all \\underline{lucky} while $42, - 10$ are not. In the Giga Tower, if you write code at a floor with lucky floor number, good luck will always be with you (Well, this round is #278, also lucky, huh?).\n\nTourist Henry goes to the tower to seek good luck. Now he is at the floor numbered $a$. He wants to find the minimum \\textbf{positive} integer $b$, such that, if he walks $b$ floors higher, he will arrive at a floor with a \\textbf{lucky} number.",
    "tutorial": "The answer $b$ is very small (usually no larger than $10$), because one of $a + 1, a + 2, ..., a + 10$ has its last digit be $8$. However, $b$ can exceed $10$ when $a$ is negative and close to $0$. The worst case is $a = - 8$, where $b = 16$. Anyway $b$ is rather small, so we can simply try $b$ from $1$, and check whether $a + b$ has a digit 8.",
    "tags": [
      "brute force"
    ],
    "rating": 1100
  },
  {
    "contest_id": "488",
    "index": "B",
    "title": "Candy Boxes",
    "statement": "There is an old tradition of keeping $4$ boxes of candies in the house in Cyberland. The numbers of candies are \\underline{special} if their \\underline{arithmetic mean}, their \\underline{median} and their \\underline{range} are all equal. By definition, for a set ${x_{1}, x_{2}, x_{3}, x_{4}}$ ($x_{1} ≤ x_{2} ≤ x_{3} ≤ x_{4}$) \\underline{arithmetic mean} is $\\frac{x_{1}+x_{2}+x_{3}+x_{4}}{4}$, \\underline{median} is $\\scriptstyle{\\frac{x_{2}+x_{3}}{2}}$ and \\underline{range} is $x_{4} - x_{1}$. \\textbf{The arithmetic mean and median are not necessary integer.} It is well-known that if those three numbers are same, boxes will create a \"debugging field\" and codes in the field will have no bugs.\n\nFor example, $1, 1, 3, 3$ is the example of $4$ numbers meeting the condition because their mean, median and range are all equal to $2$.\n\nJeff has $4$ special boxes of candies. However, something bad has happened! Some of the boxes could have been lost and now there are only $n$ ($0 ≤ n ≤ 4$) boxes remaining. The $i$-th remaining box contains $a_{i}$ candies.\n\nNow Jeff wants to know: is there a possible way to find the number of candies of the $4 - n$ missing boxes, meeting the condition above (the mean, median and range are equal)?",
    "tutorial": "Let's sort the four numbers in ascending order: $a, b, c, d$ (where $x_{1}, x_{2}, x_{3}, x_{4}$ are used in problem statement). So ${\\frac{a+b+c+d}{4}}={\\frac{b+c}{2}}=d-a$. With some basic math, we can get $a: d = 1: 3$ and $a + d = b + c$. Solution 1: If $n = 0$, just output any answer (such as ${1, 1, 3, 3}$). If $n = 1$, just output ${x, x, 3x, 3x}$, where $x$ is the known number. If $n = 4$, just check whether the four known numbers meet the condition. If $n = 2$, let $x, y$ denote the known numbers ($x  \\le  y$). No solution exists if $3x < y$. Otherwise we can construct a solution ${x, y, 4x - y, 3x}$ (certainly other solutions may exist). If $n = 3$, let $x, y, z$ denote the known numbers ($x  \\le  y  \\le  z$). No solution exists if $3x < z$. Otherwise the solution can only be ${x, y, z, 3x}$, ${\\hat{\\bar{s}}},x,y,z$ or ${x, y, x + z - y, z}$. Solution 2: The known numbers are no larger than $500$, so all numbers are no larger than $1500$ if solution exists. We enumerate $x$ from $1$ to $500$, $y$ from $x$ to $3x$, then ${x, y, 4x - y, 3x}$ is a solution. For each solution, check if it matches the known numbers. Solution 3: If $n = 0$, just output any answer (such as ${1, 1, 3, 3}$). If $n = 1$, just output ${x, x, 3x, 3x}$, where $x$ is the known number. If $n = 4$, just check whether the four known numbers meet the condition. Otherwise, we can enumerate the $1$ or $2$ missing number(s), and check if the four numbers meet the condition.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "489",
    "index": "A",
    "title": "SwapSort",
    "statement": "In this problem your goal is to sort an array consisting of $n$ integers in at most $n$ swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.\n\nNote that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than $n$.",
    "tutorial": "All you need is to swap the current minimum with the $i$-th element each time. You can do it with the code like: This solution makes at most n-1 swap operation. Also if (i != j) is not necessary.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "489",
    "index": "B",
    "title": "BerSU Ball",
    "statement": "The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! $n$ boys and $m$ girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.\n\nWe know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.\n\nFor each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from $n$ boys and $m$ girls.",
    "tutorial": "There are about 100500 ways to solve the problem. You can find maximal matching in a bipartite graph boys-girls, write dynamic programming or just use greedy approach. Let's sort boys and girls by skill. If boy with lowest skill can be matched, it is good idea to match him. It can't reduce answer size. Use girl with lowest skill to match. So you can use code like:",
    "tags": [
      "dfs and similar",
      "dp",
      "graph matchings",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "489",
    "index": "C",
    "title": "Given Length and Sum of Digits...",
    "statement": "You have a positive integer $m$ and a non-negative integer $s$. Your task is to find the smallest and the largest of the numbers that have length $m$ and sum of digits $s$. The required numbers should be non-negative integers written in the decimal base without leading zeroes.",
    "tutorial": "There is a greedy approach to solve the problem. Just try first digit from lower values to higher (in subtask to minimize number) and check if it is possible to construct a tail in such a way that it satisfies rule about length/sum. You can use a function `can(m,s)' that answers if it is possible to construct a sequence of length $m$ with the sum of digits $s$: Using the function can(m,s) you can easily pick up answer digit-by-digit. For the first part of problem (to minimize number) this part of code is: The equation (i > 0 || d > 0 || (m == 1 && d == 0)) is needed to be careful with leading zeroes.",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "489",
    "index": "D",
    "title": "Unbearable Controversy of Being",
    "statement": "Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!\n\nTomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections $a$, $b$, $c$ and $d$, such that there are two paths from $a$ to $c$ — one through $b$ and the other one through $d$, he calls the group a \"damn rhombus\". Note that pairs $(a, b)$, $(b, c)$, $(a, d)$, $(d, c)$ should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below:\n\nOther roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a \"damn rhombus\" for him.\n\nGiven that the capital of Berland has $n$ intersections and $m$ roads and all roads are unidirectional and are known in advance, find the number of \"damn rhombi\" in the city.\n\nWhen rhombi are compared, the order of intersections $b$ and $d$ doesn't matter.",
    "tutorial": "Let's iterate through all combinations of $a$ and $c$ just two simple nested loops in $O(n^{2})$ and find all candidates for $b$ and $d$ inside. To find candidates you can go through all neighbors of $a$ and check that they are neighbors of $c$. Among all the candidates you should choose two junctions as $b$ and $d$. So just use https://en.wikipedia.org/wiki/Combination All you need is to add to the answer $\\textstyle{\\binom{r}{2}}$, where $r$ is the number of candidates (common neighbors of $a$ and $c$). The code is: It is easy to see that the total complexity is $O(nm)$, because of sum of number of neighbors over all junctions is exactly $m$.",
    "tags": [
      "brute force",
      "combinatorics",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "490",
    "index": "A",
    "title": "Team Olympiad",
    "statement": "The School №0 of the capital of Berland has $n$ children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value $t_{i}$:\n\n- $t_{i} = 1$, if the $i$-th child is good at programming,\n- $t_{i} = 2$, if the $i$-th child is good at maths,\n- $t_{i} = 3$, if the $i$-th child is good at PE\n\nEach child happens to be good at exactly one of these three subjects.\n\nThe Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.\n\nWhat is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?",
    "tutorial": "The teams could be formed using greedy algorithm. We can choose any three children with different skills who are not participants of any team yet and form a new team using them. After some time we could not form any team, so the answer to the problem is minimum of the number of ones, twos and threes in given array. We can get $O(N)$ solution if we add children with different skills into three different arrays. Also the problem could be solved in $O(N^{2})$ - every iteration find new three children for new team.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "490",
    "index": "B",
    "title": "Queue",
    "statement": "During the lunch break all $n$ Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.\n\nStanding in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from $1$).\n\nAfter that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.\n\nHelp the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.",
    "tutorial": "This problem can be solved constructively. Find the first student - it is a student with such number which can be found among $a_{i}$ and could not be found among $b_{i}$ (because he doesn't stand behind for anybody). Find the second student - it is a student standing behind the first, number $a_{i}$ of the first student equals $0$, so his number is a number in pair $[0, b_{i}]$. After that we will find numbers of all other students beginning from the third. It can be easily done using penultimate found number. The number of the next student is a number $b_{i}$ in such pair where $a_{i}$ equals to number of penultimate found student number (that is a number in pair $[ans_{}[i - 2], b_{i}]$). Look at the sample to understand the solution better.",
    "tags": [
      "dsu",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "490",
    "index": "C",
    "title": "Hacking Cypher",
    "statement": "Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.\n\nHaving carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!\n\nPolycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by $a$ as a separate number, and the second (right) part is divisible by $b$ as a separate number. Both parts should be \\underline{positive} integers that have no leading zeros. Polycarpus knows values $a$ and $b$.\n\nHelp Polycarpus and find any suitable method to cut the public key.",
    "tutorial": "At first, let's check all prefixes of specified number - do they have remainder 0 when divided by the $a$? It can be done with asymptotic behavior $O(N)$, where $N$ -length of specified number $C$. If we have remainder of division by $a$ of prefix, which ends in position $pos$, we can count remainder in position $pos + 1$: $rema[pos + 1] = (rema[pos] * 10 + C[pos + 1])$ % $a$. Then we need to check suffixes.If we have remainder of division by $b$ of suffix, which begin in position $pos$, we can count remainder of position $pos - 1$: $remb[pos - 1] = (C[pos - 1] * P + remb[pos])$ % $b$, where $P$ - it is $10$^$(L - 1)$ module $b$, $L$ - length of suffix ($P$ we can count parallel). Now let's check all positions $pos$ - can we cut specified number $C$ in this position. We can do it if next four conditions performed: prefix of number $C$, which ends in $pos$ is divisible by $a$; suffix of number $C$, which begin in $pos + 1$ is divisible by $b$; length of prefix and suffix more than $0$; first digit of suffix is different from $0$. If all four conditions performed we found answer. If we did not find any such positions, than print $NO$.",
    "tags": [
      "brute force",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "490",
    "index": "D",
    "title": "Chocolate",
    "statement": "Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is $a_{1} × b_{1}$ segments large and the second one is $a_{2} × b_{2}$ segments large.\n\nPolycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself. Besides, he wants to show that Polycarpus's mind and Paraskevi's beauty are equally matched, so the two bars must have the same number of squares.\n\nTo make the bars have the same number of squares, Polycarpus eats a little piece of chocolate each minute. Each minute he does the following:\n\n- he either breaks one bar exactly in half (vertically \\textbf{or} horizontally) and eats exactly a half of the bar,\n- or he chips of exactly one third of a bar (vertically or horizontally) and eats exactly a third of the bar.\n\nIn the first case he is left with a half, of the bar and in the second case he is left with two thirds of the bar.\n\nBoth variants aren't always possible, and sometimes Polycarpus cannot chip off a half nor a third. For example, if the bar is $16 × 23$, then Polycarpus can chip off a half, but not a third. If the bar is $20 × 18$, then Polycarpus can chip off both a half and a third. If the bar is $5 × 7$, then Polycarpus cannot chip off a half nor a third.\n\nWhat is the minimum number of minutes Polycarpus needs to make two bars consist of the same number of squares? Find not only the required minimum number of minutes, but also the possible sizes of the bars after the process.",
    "tutorial": "We can change the numbers by dividing their by two or by dividing their by three and multiply two. Firstly remove all 2 and 3 from factorization of chocolate and determine equals their square or not. If their squares are not equals answer doesn't exists. Otherwise calculate of difference between number of three in factorization, we should remove this amount of threes from the some chocolate, it depends from the sign, and recalculate difference between number of two in factorization and do the same.",
    "tags": [
      "brute force",
      "dfs and similar",
      "math",
      "meet-in-the-middle",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "490",
    "index": "E",
    "title": "Restoring Increasing Sequence",
    "statement": "Peter wrote on the board a strictly increasing sequence of positive integers $a_{1}, a_{2}, ..., a_{n}$. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit.\n\nRestore the the original sequence knowing digits remaining on the board.",
    "tutorial": "Let's iterate on specified numbers and try to make from current number minimal possible, which value more than value of previous number. Let's current number is $cur$, previous number is $prev$. If length of number $cur$ less than length of number $prev$ - let's print $NO$, this problem has not solution. If length of number $cur$ more than length of number $prev$ - replace all signs $?$ in number $cur$ to digit $0$, except case, when sign $?$ in first position - replace him on digit $1$, because numbers in answer must be without leading zeroes. Another case when lengths of numbers $a$ and $b$ are equal. Let's iterate on positions $pos$, in which prefix number $cur$ more than prefix of number $prev$. Now we need to try for this position make minimal possible number, which more than $prev$. In all positions $pos_{i}$, which less than $pos$, replace all $?$ on $prev[pos_{i}]$. In all positions $pos_{i}$, which more than $pos$, replace all $?$ on digit $0$. If $cur[pos] = = ?$ than make $cur[pos] = max(prev[pos] + 1, 9)$. If received number less or equal to $prev$ - this position is bad. From all good positions choose minimal number, received with operations above and assign him number $cur$ and will continue iteration. If count of such positions is $0$ we need to print $NO$.",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "490",
    "index": "F",
    "title": "Treeland Tour",
    "statement": "The \"Road Accident\" band is planning an unprecedented tour around Treeland. The RA fans are looking forward to the event and making bets on how many concerts their favorite group will have.\n\nTreeland consists of $n$ cities, some pairs of cities are connected by bidirectional roads. Overall the country has $n - 1$ roads. We know that it is possible to get to any city from any other one. The cities are numbered by integers from 1 to $n$. For every city we know its value $r_{i}$ — the number of people in it.\n\nWe know that the band will travel along some path, having concerts in \\textbf{some} cities along the path. The band's path will not pass one city twice, each time they move to the city that hasn't been previously visited. Thus, the musicians will travel along some path (without visiting any city twice) and in some (not necessarily all) cities along the way they will have concerts.\n\nThe band plans to gather all the big stadiums and concert halls during the tour, so every time they will perform in a city which population is larger than the population of the previously visited \\textbf{with concert} city. In other words, the sequence of population in the cities where the concerts will be held is strictly increasing.\n\nIn a recent interview with the leader of the \"road accident\" band promised to the fans that the band will \\textbf{give concert} in the largest possible number of cities! Thus the band will travel along some chain of cities of Treeland and have concerts in some of these cities, so that the population number will increase, and the number of concerts will be the largest possible.\n\nThe fans of Treeland are frantically trying to figure out how many concerts the group will have in Treeland. Looks like they can't manage without some help from a real programmer! Help the fans find the sought number of concerts.",
    "tutorial": "The problem is generalization of finding maximal increasing subsequence in array, so it probably can be solved using dynamic programming. We will calc dynamic $d[(u, v)]$, the state is directed edge $(u, v)$ in tree. Value $d[(u, v)]$ means the maximum number of vertices where the band will have concerts on some simple path ended in vertex $v$ going through vertex $u$. Also the concert in vertex $v$ must be certainly. To calc $d(u, v)$ we should consider all such edges $(x, y)$ that there is simple path started in $x$, going through $y$, $u$ and ended in $v$. These edges can be found using dfs from vertex $u$ which is not going through vertex $v$. All edges used by dfs should be reoriented. So if $r[y] < r[v]$ then $d[(u, v)] = max(d[(u, v)], d[(x, y)] + 1)$. The solution needs $O(N^{2})$ time and $O(N^{2})$ memory. The memory could be $O(N)$ if you get indexes of directed edges without two-dimensional array.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "492",
    "index": "A",
    "title": "Vanya and Cubes",
    "statement": "Vanya got $n$ cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of $1$ cube, the second level must consist of $1 + 2 = 3$ cubes, the third level must have $1 + 2 + 3 = 6$ cubes, and so on. Thus, the $i$-th level of the pyramid must have $1 + 2 + ... + (i - 1) + i$ cubes.\n\nVanya wants to know what is the maximum height of the pyramid that he can make using the given cubes.",
    "tutorial": "In fact need to do what is asked in the statement. We need to find in a cycle the maximum height $h$, counting, how many blocks must be in $i$-th row and adding these values to the result. Iterate until the result is not greater than $n$.",
    "code": "#include <stdio.h>\nint n,h,i,cnt;\nint main()\n{\n\tscanf(\"%d\",&n);\n\twhile (cnt <= n)\n\t{\n\t\th++;\n\t\tcnt += (h*(h+1))/2;\n\t}\n\tprintf(\"%d\\n\",h-1);\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "492",
    "index": "B",
    "title": "Vanya and Lanterns",
    "statement": "Vanya walks late at night along a straight street of length $l$, lit by $n$ lanterns. Consider the coordinate system with the beginning of the street corresponding to the point $0$, and its end corresponding to the point $l$. Then the $i$-th lantern is at the point $a_{i}$. The lantern lights all points of the street that are at the distance of at most $d$ from it, where $d$ is some positive number, common for all lanterns.\n\nVanya wonders: what is the minimum light radius $d$ should the lanterns have to light the whole street?",
    "tutorial": "Sort lanterns in non-decreasing order. Then we need to find maximal distance between two neighbour lanterns, let it be $maxdist$. Also we need to consider street bounds and count distances from outside lanterns to street bounds, it will be $(a[0] - 0)$ and $(l - a[n - 1])$. The answer will be $max(maxdist / 2, max(a[0] - 0, l - a[n - 1]))$ Time complexity $O(nlogn)$.",
    "code": "#include <stdio.h>\n#include <algorithm>\nusing namespace std;\nint n,i,a[100500],rez,l;\nint main()\n{\n    scanf(\"%d%d\",&n,&l);\n    for (i = 0; i < n; i++)\n        scanf(\"%d\",&a[i]);\n    sort(a,a+n);\n    rez = 2*max(a[0],l-a[n-1]);\n    for (i = 0; i < n-1; i++)\n        rez = max(rez, a[i+1]-a[i]);\n    printf(\"%.10f\\n\",rez/2.);\n    return 0;\n}",
    "tags": [
      "binary search",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "492",
    "index": "C",
    "title": "Vanya and Exams",
    "statement": "Vanya wants to pass $n$ exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least $avg$. The exam grade cannot exceed $r$. Vanya has passed the exams and got grade $a_{i}$ for the $i$-th exam. To increase the grade for the $i$-th exam by 1 point, Vanya must write $b_{i}$ essays. He can raise the exam grade multiple times.\n\nWhat is the minimum number of essays that Vanya needs to write to get scholarship?",
    "tutorial": "Sort $(a_{i}, b_{i})$ in non-decreasing order for number of essays $b_{i}$, after that go from the beginning of this sorted pairs and add greedily the maximal number of points we can, i.e. add value $min(avg * n - sum, r - a_{i})$, while total amount of points will not be greater, than $avg * n$. Time complexity $O(nlogn)$.",
    "code": "#include <stdio.h>\n#include <algorithm>\nusing namespace std;\nlong long n,avg,r,i,rez,sum;\npair <long long, long long> a[100500];\nint main()\n{\n    scanf(\"%d%d%d\",&n,&r,&avg);\n    for (i = 0; i < n; i++)\n    {\n        scanf(\"%d%d\",&a[i].second,&a[i].first);\n        sum += a[i].second;\n    }\n    sort(a,a+n);\n    rez = i = 0;\n    while (sum < avg*n)\n    {\n        long long tmp = min(avg*n-sum,r-a[i].second);\n        rez += tmp*a[i].first;\n        sum += tmp;\n        i++;\n    }\n    printf(\"%I64d\\n\",rez);\n    return 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "492",
    "index": "D",
    "title": "Vanya and Computer Game",
    "statement": "Vanya and his friend Vova play a computer game where they need to destroy $n$ monsters to pass a level. Vanya's character performs attack with frequency $x$ hits per second and Vova's character performs attack with frequency $y$ hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is $1 / x$ seconds for the first character and $1 / y$ seconds for the second one). The $i$-th monster dies after he receives $a_{i}$ hits.\n\nVanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.",
    "tutorial": "Let's create vector $rez$ with size $x + y$, in which there will be a sequence of Vanya's and Vova's strikes for the first second. To do this, we can take 2 variables $cntx = cnty = 0$. Then while $cntx < x$ and $cnty < y$, we will check 3 conditions: 1) If $(cntx + 1) / x > (cnty + 1) / y$, then add into the vector word \"Vova\", $cnty$++. 2) If $(cntx + 1) / x < (cnty + 1) / y$, then add into the vector word \"Vanya\", $cntx$++. 3) If $(cntx + 1) / x = (cnty + 1) / y$, then add into the vector word \"Both\" 2 times, $cntx$++, $cnty$++. Then we are able to respond on each query for $O(1)$, the answer will be $rez[(a_{i} - 1)mod(x + y)]$. Time complexity $O(x + y)$.",
    "code": "#include <stdio.h>\n#include <algorithm>\n#include <vector>\nusing namespace std;\nint n,x,y,i,t,cntx,cnty;\nvector <int> rez;\nint main()\n{\n    scanf(\"%d%d%d\",&n,&x,&y);\n    cntx = cnty = 0;\n    while (cntx < x||cnty < y)\n    {\n        if ((long long)(cntx+1)*y > (long long)(cnty+1)*x)\n        {\n            cnty++;\n            rez.push_back(2);\n        }\n        else\n        if ((long long)(cntx+1)*y < (long long)(cnty+1)*x)\n        {\n            cntx++;\n            rez.push_back(1);\n        } else\n        {\n            cntx++;\n            cnty++;\n            rez.push_back(3);\n            rez.push_back(3);\n        }\n    }\n    for (i = 0; i < n; i++)\n    {\n        scanf(\"%d\",&t);\n        t--;\n        int tmp = rez[t%(x+y)];\n        if (tmp == 1)\n            printf(\"Vanya\\n\");\n        else if (tmp == 2)\n            printf(\"Vova\\n\");\n        else\n            printf(\"Both\\n\");\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "492",
    "index": "E",
    "title": "Vanya and Field",
    "statement": "Vanya decided to walk in the field of size $n × n$ cells. The field contains $m$ apple trees, the $i$-th apple tree is at the cell with coordinates $(x_{i}, y_{i})$. Vanya moves towards vector $(dx, dy)$. That means that if Vanya is now at the cell $(x, y)$, then in a second he will be at cell $((x+d x)\\operatorname*{mod}n,(y+d y)\\operatorname*{mod}n)$. The following condition is satisfied for the vector: $\\operatorname*{gcd}(n,d x)=\\operatorname*{gcd}(n,d y)=1$, where $\\operatorname*{gcd}(a,b)$ is the largest integer that divides both $a$ and $b$. Vanya ends his path when he reaches the square he has already visited.\n\nVanya wonders, from what square of the field he should start his path to see as many apple trees as possible.",
    "tutorial": "As long as $gcd(dx, n) = gcd(dy, n) = 1$, Vanya will do full cycle for $n$ moves. Let's group all possible pathes into $n$ groups, where $1 - th, 2 - nd, ... , n - th$ path will be started from points $(0, 0), (0, 1),  \\dots , (0, n - 1)$. Let's look on first path: $(0, 0) - (dx, dy) - ((2 * dx)$ $mod$ $n, (2 * dy)$ $mod$ $n) - ... - (((n - 1) * dx)$ $mod$ $n, ((n - 1) * dy)$ $mod$ $n)$. As long as $gcd(dx, n) = 1$, among the first coordinates of points of the path there will be all the numbers from $0$ to $n - 1$. So we can write in the array all relations between the first and second coordinate in points for the path, that starts in the point $(0, 0)$, i.e. $y[0] = 0, y[dx] = dy, ... , y[((n - 1) * dx)$ $mod$ $n] = ((n - 1) * dy)$ $mod$ $n$. Now we know, that all points with type $(i, y[i])$, where $0  \\le  i  \\le  n - 1$, belong to the group with start point $(0, 0)$. In that case, points with type $(i, (y[i] + k)modn)$ belong to the group with start point $(0, k)$. Then we can add every point $(x_{i}, y_{i})$ to required group $k$ for $O(1)$: $(y[x_{i}] + k)$ $mod$ $n = y_{i}, k = (y_{i} - y[x_{i}] + n)$ $mod$ $n$. Then we need just to find group with the maximal amount of elements, it will be the answer. Time complexity $O(n)$.",
    "code": "#include <stdio.h>\n#include <algorithm>\n#include <vector>\nusing namespace std;\nint n,m,dx,dy,x,y,i,j,a[1000500],b[1000500],rez;\nint main()\n{\n    scanf(\"%d%d%d%d\",&n,&m,&dx,&dy);\n    x = y = a[0] = 0;\n    for (i = 0; i < n; i++)\n    {\n        x = (x+dx)%n;\n        y = (y+dy)%n;\n        a[x] = y;\n    }\n    for (i = 0; i < m; i++)\n    {\n        scanf(\"%d%d\",&x,&y);\n        b[(y-a[x]+n)%n]++;\n    }\n    int max1 = -1;\n    for (i = 0; i < n; i++)\n        if (b[i] > max1)\n        {\n            max1 = b[i];\n            rez = i;\n        }\n        if (n == 5)\n        printf(\"%d %d\\n\",(3*dx)%n,(rez+3*dy)%n);\n        else\n    printf(\"0 %d\\n\",rez);\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "493",
    "index": "A",
    "title": "Vasya and Football",
    "statement": "Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.\n\nVasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the \\textbf{first} moment of time when he would receive a red card from Vasya.",
    "tutorial": "We need 2 arrays - for the first and second team, in which we must save \"status\" of the player - is he \"clear\", yellow carded or sent off. Then while inputing we must output the players name if he wasn't sent off, and after the event he must be sent off.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "493",
    "index": "B",
    "title": "Vasya and Wrestling",
    "statement": "Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.\n\nWhen the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is \\textbf{lexicographically greater}, wins.\n\nIf the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.",
    "tutorial": "We need to vectors in which we will save points of first and second wrestlers, and two int-s, where we will save who made the last technique and what is the sum of all the numbers in the input. If the sum is not zero, we know the answer. Else we pass by the vectors, checking are there respective elements which are not equal. If yes - then we know the answer, else everything depends on who made the last technique.",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "493",
    "index": "C",
    "title": "Vasya and Basketball",
    "statement": "Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of $d$ meters, and a throw is worth 3 points if the distance is larger than $d$ meters, where $d$ is some \\textbf{non-negative} integer.\n\nVasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of $d$. Help him to do that.",
    "tutorial": "We need an array of pairs - in each pair we save the distance and the number of team. Then we sort the array. Then we assume that all the throws bring 3 points. Then we pass by the array and one of our numbers we decrease on 1 (which one - it depends on the second element of array). Then we compare it with our answer. In the end - we print our answer.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "493",
    "index": "D",
    "title": "Vasya and Chess",
    "statement": "Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.\n\nThe queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell contains a piece of the enemy color, the queen is able to move to this square. After that the enemy's piece is removed from the board. The queen cannot move to a cell containing an enemy piece if there is some other piece between it and the queen.\n\nThere is an $n × n$ chessboard. We'll denote a cell on the intersection of the $r$-th row and $c$-th column as $(r, c)$. The square $(1, 1)$ contains the white queen and the square $(1, n)$ contains the black queen. All other squares contain green pawns that don't belong to anyone.\n\nThe players move in turns. The player that moves first plays for the white queen, his opponent plays for the black queen.\n\nOn each move the player has to capture some piece with his queen (that is, move to a square that contains either a green pawn or the enemy queen). The player loses if either he cannot capture any piece during his move or the opponent took his queen during the previous move.\n\nHelp Vasya determine who wins if both players play with an optimal strategy on the board $n × n$.",
    "tutorial": "If n is odd, then black can win white doing all the moves symetric by the central line. Else white can win putting his queen on (1,2) (which is the lexicographicly smallest place) and play symetricly - never using the first row.",
    "tags": [
      "constructive algorithms",
      "games",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "493",
    "index": "E",
    "title": "Vasya and Polynomial",
    "statement": "Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. \\underline{Polynomial} is a function $P(x) = a_{0} + a_{1}x^{1} + ... + a_{n}x^{n}$. Numbers $a_{i}$ are called \\underline{coefficients} of a polynomial, non-negative integer $n$ is called a \\underline{degree} of a polynomial.\n\nVasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: \"Determine how many polynomials $P(x)$ exist with \\textbf{integer non-negative} coefficients so that $P(\\mathbf{t})=a$, and $P(P(\\mathbf{t}))=b$, where $\\mathbf{t.}\\,a$ and $b$ are given positive integers\"?\n\nVasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem.",
    "tutorial": "Let's discuss 2 case. 1) t!=1 and 2) t=1. 1) If our function is not constant (n>=1) than a is greater all the coefficients, so the only polynom can be the number b - in the a-ary counting system. We must only check that one and constant function. 2)if t=1 must be careful: in case 1 1 1: the answer is inf, in case 1 1 n: the answer is 0 in case 1 a a^x(x-integer, x>0): the answer is 1 in the other cases P(1) is greater than other coefficients.",
    "tags": [
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "494",
    "index": "A",
    "title": "Treasure",
    "statement": "Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string $s$ written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes \\underline{beautiful}.\n\nBelow there was also written that a string is called \\underline{beautiful} if for each $i$ ($1 ≤ i ≤ |s|$) there are no more ')' characters than '(' characters among the first $i$ characters of $s$ and also the total number of '(' characters is equal to the total number of ')' characters.\n\nHelp Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.",
    "tutorial": "Consider a string consisting of '(' and ')' characters. Let's build the following sequence from this string: $a_{0} = 0$ $a_{0} = 0$ for each $1  \\le  i  \\le  |s|$ $a_{i} = a_{i - 1} + 1$ if $s_{i} = '('$ and $a_{i} = a_{i - 1} - 1$ otherwise. (The string is considered as 1-based index). for each $1  \\le  i  \\le  |s|$ $a_{i} = a_{i - 1} + 1$ if $s_{i} = '('$ and $a_{i} = a_{i - 1} - 1$ otherwise. (The string is considered as 1-based index). It can be proven that a string is beautiful if the following conditions are satisfied: for each $0  \\le  i  \\le  |s|$ $a_{i}  \\ge  0$. for each $0  \\le  i  \\le  |s|$ $a_{i}  \\ge  0$. $a_{|s|} = 0$ $a_{|s|} = 0$ Using the above fact we can prove that if in a beautiful string we remove a ')' character and put it further toward the end of the string the resulting string is beautiful as well. These facts leads us to the following fact: if we can move a ')' character further toward the end of string it is better if we'd do it. This yields the following greedy solution: We'll first put exactly one ')' character at each '#' character. Then we'll build the sequence we described above. if the first condition isn't satisfied then there is no way that leads to a beautiful string. So the answer is -1. Otherwise we must put exactly $a_{|s|}$ more ')' characters in the place of last '#' character. Then if this string is beautiful we'll print it otherwise the answer is -1.",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "494",
    "index": "B",
    "title": "Obsessive String",
    "statement": "Hamed has recently found a string $t$ and suddenly became quite fond of it. He spent several days trying to find all occurrences of $t$ in other strings he had. Finally he became tired and started thinking about the following problem. Given a string $s$ how many ways are there to extract $k ≥ 1$ non-overlapping substrings from it such that each of them contains string $t$ as a substring? More formally, you need to calculate the number of ways to choose two sequences $a_{1}, a_{2}, ..., a_{k}$ and $b_{1}, b_{2}, ..., b_{k}$ satisfying the following requirements:\n\n- $k ≥ 1$\n- $\\forall i\\ (1\\leq i\\leq k)\\;1\\leq a_{i},b_{i}\\leq|s|$\n- $\\forall i\\ (1\\leq i\\leq k)\\ b_{i}\\geq a_{i}$\n- $\\forall i\\ (2\\leq i\\leq k)\\ a_{i}>b_{i-1}$\n- $\\forall i\\ (1\\leq i\\leq k)$  $t$ is a substring of string $s_{ai}s_{ai + 1}... s_{bi}$ (string $s$ is considered as $1$-indexed).\n\nAs the number of ways can be rather large print it modulo $10^{9} + 7$.",
    "tutorial": "We call an index $i(1  \\le  i  \\le  |s|)$ good if $t$ equals $s_{i - |t| + 1}s_{i - |t| + 2}... s_{i}$. To find all good indexes let's define $q_{i}$ as the length of longest prefix of $t$ which is a suffix of $s_{1}s_{2}... s_{i}$. A good index is an index with $q_{i} = |t|$. Calculating $q_{i}$ can be done using Knuth-Morris-Pratt algorithm. Let's define $a_{i}$ as the number of ways to choose some(at least one) non-overlapping substrings of the prefix of $s$ with length $i$ ($s_{1}s_{2}... s_{i}$) so $t$ is a substring of each one of them and $s_{i}$ is in one the chosen substrings(So it must actually be the last character of last chosen substring). Then the answer will be $\\textstyle\\sum_{j=1}^{\\infty}a_{i}$. Also let's define two additional sequence $q1$ and $q2$ which will help us in calculating $a$. $q1_{i}=\\sum_{j=1}^{n}a_{j}$ $q2_{i}=\\sum_{j=1}^{n}q1_{j}$ The sequence $a$ can then be calculated in $O(n)$ as described below: If $i$ is not a good index $a_{i} = a_{i - 1}$ since in each way counted in $a_{i}$ the substring containing $s_{i}$ also contains $s_{i - 1}$ so for each of these ways removing $s_{i}$ from the substring containing it leads to a way counted in $a_{i - 1}$ and vice-versa thus these two numbers are equal. If $i$ is a good index then $a_{i} = q2_{i - |t|} + i - |t| + 1$. To prove this let's consider a way of choosing substring counted in $a_{i}$. We call such a way valid. The substring containing $s_{i}$ can be any of the substrings $s_{j}s_{j + 1}... s_{i}$ $(1  \\le  j  \\le  i - |t| + 1)$. There are $i - |t| + 1$ valid ways in which this substring is the only substring we've chosen. Number of valid ways in which substring containing $s_{i}$ starts at $s_{j}$ equals to $q1_{j - 1}$. So the total number of valid ways in which we've chosen at least two substrings are equal to $\\textstyle{\\sum_{j=1}^{i-[t]+1}q!_{j-1}}$ which is equal to $q2_{j - 1}$. So $a_{i} = q2_{i - |t|} + i - |t| + 1$.",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "494",
    "index": "C",
    "title": "Helping People",
    "statement": "Malek is a rich man. He also is very generous. That's why he decided to split his money between poor people. A charity institute knows $n$ poor people numbered from $1$ to $n$. The institute gave Malek $q$ recommendations. A recommendation is a segment of people like $[l, r]$ which means the institute recommended that Malek gives one dollar to every person whose number is in this segment.\n\nHowever this charity has very odd rules about the recommendations. Because of those rules the recommendations are given in such a way that for every two recommendation $[a, b]$ and $[c, d]$ one of the following conditions holds:\n\n- The two segments are completely disjoint. More formally either $a ≤ b < c ≤ d$ or $c ≤ d < a ≤ b$\n- One of the two segments are inside another. More formally either $a ≤ c ≤ d ≤ b$ or $c ≤ a ≤ b ≤ d$.\n\nThe \\underline{goodness} of a charity is the value of maximum money a person has after Malek finishes giving his money. The institute knows for each recommendation what is the probability that Malek will accept it. They want to know the expected value of \\underline{goodness} of this charity. So they asked you for help.\n\nYou have been given the list of recommendations and for each recommendation the probability of it being accepted by Malek. You have also been given how much money each person initially has. You must find the expected value of \\underline{goodness}.",
    "tutorial": "We'll first create a rooted tree from the given segments which each node represents a segment. We'll solve the problem using dynamic programming on this tree. First of all let's add a segment $[1, n]$ with probability of being chosen by Malek equal to $0$. The node representing this segment will be the root of the tree. Please note by adding this segment the rules described in the statements are still in place. Let's sort the rest of segments according to their starting point increasing and in case of equality according to their finishing point decreasing. Then we'll put the segment we added in the beginning. A segment's father is the right-most segment which comes before that segment and contains it. Please note that since we added segment $[1, n]$ to the beginning every segment except the added segment has a father. We build the tree by putting a segment's node child of its father's node. In this tree for each two nodes $u$ and $v$ which none of them are in the subtree on another the segments representing these two nodes will not overlap. Also for each two nodes $u$ and $v$ which $u$ is in subtree of $v$ segment representing node $u$ will be inside(not necessarily strictly) segment representing node $v$. We define $mx_{i}$ as the maximum money a person in the segment $i$ initially has. $mx_{i}$ can be calculated using RMQ. Let's define $a_{i, j}$ as the probability of that after Malek finishes giving his money the maximum in the segment $i$ is at most ${mx}_{i} + j$. The properties of the tree we built allows us to calculate $a_{i, j}$ for every $i$ and $j$ in $O(q^{2})$ (since $1  \\le  i, j  \\le  q$). If number of the segment we added is $k$ then the answer will be $a_{k_{1}0}\\star m x_{k}+\\sum_{j=1}^{q}\\left(a_{k\\,j}-a_{k\\,j-1}\\right)\\star\\left(m x_{k}+j\\right)$. Calculating $a_{i, j}$ is described below: Suppose $f$ is a child of $i$ and suppose Malek doesn't accept the $i$-th recommendation. Then since we want the maximum number after money spreading to be at most $mx_{i} + j$ in segment $i$ and since $f$ is inside $i$ we want the maximum number after money spreading to be at most $mx_{i} - mx_{f} + j$. If Malek accepts the recommendation then we want it to be at most $mx_{i} - mx_{f} + j - 1$. So if probability of $i$-th recommendation being accepted by Malek be equal to $p_{i}$ then $a_{i,j}=p_{i}\\times\\prod_{f\\ c h i l d\\ o f}\\ i^{a_{f,m x_{i}-m x_{f}+j-1}}+(1-p_{i})\\times\\prod_{f\\ c h i l d\\ o f}\\ i^{a_{f,m x_{i}-m x_{f}+j}+2}\\qquad\\qquad\\qquad$. Using this formula we can calculate $a_{k, j}$ recursively and calculate the answer from it in $O(q^{2})$. The overall complexity will be $O(nlgn + q^{2})$. $nlgn$ for creating RMQ used for calculating the array $mx$ and $q^{2}$ for the rest of the algorithm.",
    "tags": [
      "dp",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "494",
    "index": "D",
    "title": "Birthday",
    "statement": "Ali is Hamed's little brother and tomorrow is his birthday. Hamed wants his brother to earn his gift so he gave him a hard programming problem and told him if he can successfully solve it, he'll get him a brand new laptop. Ali is not yet a very talented programmer like Hamed and although he usually doesn't cheat but this time is an exception. It's about a brand new laptop. So he decided to secretly seek help from you. Please solve this problem for Ali.\n\nAn $n$-vertex weighted rooted tree is given. Vertex number $1$ is a root of the tree. We define $d(u, v)$ as the sum of edges weights on the shortest path between vertices $u$ and $v$. Specifically we define $d(u, u) = 0$. Also let's define $S(v)$ for each vertex $v$ as a set containing all vertices $u$ such that $d(1, u) = d(1, v) + d(v, u)$. Function $f(u, v)$ is then defined using the following formula:\n\n\\[\nf(u,v)=\\sum_{x\\in S(v)}d(u,x)^{2}-\\sum_{x\\notin S(v)}d(u,x)^{2}\n\\]\n\nThe goal is to calculate $f(u, v)$ for each of the $q$ given pair of vertices. As the answer can be rather large it's enough to print it modulo $10^{9} + 7$.",
    "tutorial": "We solve this problem by answering queries offline. We'll first store in each vertex $v$ number of vertices such as $x$ for which we must calculate $f(v, x)$ . starting from the root. We'll keep two arrays $a$ and $b$. Suppose we're at vertex $v$ right now then $a_{i}$ equals $d(i, v)^{2}$ and $b_{i}$ equal $d(i, v)$. Having these two arrays when moving from vertex $v$ to a child with an edge with weight $k$ one can note that $b_{i}$ for all $i$s inside subtree of $v$ decreases by $k$ and all other $b_{i}$s gets increased by $k$. Knowing this fact one can also update array $a$ as well. To calculate $f(v, x)$ it's enough to be able to calculate sum of $a_{i}$s for all $i$ inside subtree of $x$. Handling each of these operations is a well known problem and is possible using a segment tree. Overall complexity is $O((n + q)lgn)$. There is an online solution using dynamic programming as well.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "494",
    "index": "E",
    "title": "Sharti",
    "statement": "During the last 24 hours Hamed and Malek spent all their time playing \"Sharti\". Now they are too exhausted to finish the last round. So they asked you for help to determine the winner of this round.\n\n\"Sharti\" is played on a $n × n$ board with some of cells colored white and others colored black. The rows of the board are numbered from top to bottom using number $1$ to $n$. Also the columns of the board are numbered from left to right using numbers $1$ to $n$. The cell located at the intersection of $i$-th row and $j$-th column is denoted by $(i, j)$.\n\nThe players alternatively take turns. In each turn the player must choose a square with side-length at most $k$ with its lower-right cell painted white. Then the colors of all the cells in this square are inversed (white cells become black and vice-versa). The player who cannot perform a move in his turn loses.\n\nYou know Hamed and Malek are very clever and they would have played their best moves at each turn. Knowing this and the fact that Hamed takes the first turn, given the initial board as described in the input, you must determine which one of them will be the winner.",
    "tutorial": "Let's first solve this problem for another game: Suppose that we've an $n  \\times  n$ table. Each cell have some(possibly zero) marbles on it. During each move the player chooses a square with side-length at most $k$ which its lower-right cell has at least one marble, he removes one marble from it and puts one marble in every other cell of this square. One can notice that in such game each marble is independent of the others and doesn't affect other marbles. So one can see this game as some separate games played on some tables. More formally for each marble placed in a cell such as $(i, j)$ consider the game when played on a $i  \\times  j$ table which the only marble placed on it is at its lower-right cell. Let's denote the Grundy number of this game by $g_{i, j}$. Then according to Grundy theorem the first player has a winning strategy if and only if the xor of $g_{i, j}$ for every cell $(i, j)$ having odd number of marbles on it is positive. To calculate $g_{i, j}$ note that the first move in such game must be choosing a square with its lower-right cell being the lower-right cell of table. So the only thing to decide is the side-length of chosen square at the first move. Let's say we choose the first square width side length $l$. Grundy number of the next state will be equal to xor of $g_{c, d}$ for every $i - l < c  \\le  i, j - l < d  \\le  j$. Using this fact one can calculate $g_{i, j}$ for all $(1  \\le  i, j  \\le  a)$ ($a$ being an arbitrary integers) in $O(a^{3})$. If we calculated the first values of $g_{i, j}$ one can see a pattern in the Grundy numbers. Then one can prove that $g_{i, j} = min(lowest_bit(i), lowest_bit(j), greatest_bit(k))$ where $lowest_bit(x) =$ the maximum power of $2$ which is a divisor of $x$ and $greatest_bit(x) =$ the maximum power of $2$ which is not greater than $x$. Now let's prove that our first game(the game described in the statement) is actually the same as this game. Suppose that a player has a winning strategy in the first game. Consider a table containing one marble at every cell which is white in the table of the first game. We'll prove that the same player has winning strategy in this game as well. Note that a cell is white in the first game if and only if the parity of marbles in the second game is odd so there is at least one marble on it. So as long as the other player chooses a square with its lower-right cell having odd number of marbles in the second game, his move corresponds to a move in the first game so the player having winning strategy can counter his move. If the other player chooses a square with its lower-right cell having even number of marbles, it means the cell had at least 2 marbles on it so the player can counter it by choosing the same square which makes the parity of every cell to be the same after these 2 moves. And since it can be proven that both of the game will end at some point then the player has winning strategy in this game as well. The reverse of this fact can also be proven the same since if a player has a winning strategy there is also a winning strategy in which this player always chooses squares with lower-right cell having odd number of marbles(since otherwise the other player can counter it as described above) and counters the moves of the other player at which he chose a square with lower-right cell having even number of marbles by choosing the same square(since the Grundy number by countering in this way won't change the Grundy number and thus won't change the player with winning strategy). So if we consider a table having one marble at each of the cells which are in at least one of the rectangles given in the input we only need to calculate the Grundy number of this state and check whether it's positive or not to determine the winner. To do this for each $i(1  \\le  i  \\le  greatest_bit(k))$ lets define $a_{i}$ as the number of cells $(x, y)$ which are contained in at least one of the given rectangles, $2^{i}|x$ and $2^{i}|y$. Lets also define $a_{greatest_bit(k) + 1} = 0$. Then according the fact we described above about $g_{i, j}$ the number of $2^{i}$s which are xored equals $a_{i} - a_{i + 1}$. Knowing this calculating the Grundy number of the initial state is easy. Calculating $a_{i}$ is identical to a very well-known problem which is given some rectangles count the number of cells in at least one of them and can be solved in $O(mlgm)$ ($m$ being number of rectangles). So overall complexity will be $O(mlgmlgk)$.",
    "tags": [
      "data structures",
      "games"
    ],
    "rating": 3200
  },
  {
    "contest_id": "495",
    "index": "A",
    "title": "Digital Counter",
    "statement": "Malek lives in an apartment block with $100$ floors numbered from $0$ to $99$. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with $7$ light sticks by turning them on or off. The picture below shows how the elevator shows each digit.\n\nOne day when Malek wanted to go from floor $88$ to floor $0$ using the elevator he noticed that the counter shows number $89$ instead of $88$. Then when the elevator started moving the number on the counter changed to $87$. After a little thinking Malek came to the conclusion that there is only one explanation for this: One of the sticks of the counter was broken. Later that day Malek was thinking about the broken stick and suddenly he came up with the following problem.\n\nSuppose the digital counter is showing number $n$. Malek calls an integer $x$ ($0 ≤ x ≤ 99$) \\underline{good} if it's possible that the digital counter was supposed to show $x$ but because of some(possibly none) broken sticks it's showing $n$ instead. Malek wants to know number of good integers for a specific $n$. So you must write a program that calculates this number. Please note that the counter \\textbf{always} shows two digits.",
    "tutorial": "For each digit $x$ you can count the number of digits $y$ that because of some broken sticks $x$ is shown instead of $y$ by hand. for example when $x = 3$, $y$ can be $3$, $8$ and $9$. Let's denote this number by $a_{x}$. Then if the input is $xy$ (the first digit shown in the counter is $x$ and the second is $y$) the answer will be $a_{x}  \\times  a_{y}$.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "495",
    "index": "B",
    "title": "Modular Equations",
    "statement": "Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define $i$ modulo $j$ as the remainder of division of $i$ by $j$ and denote it by $i\\,\\mathrm{mod}\\,j$. A Modular Equation, as Hamed's teacher described, is an equation of the form $a{\\bmod{x}}=b$ in which $a$ and $b$ are two non-negative integers and $x$ is a variable. We call a positive integer $x$ for which $a{\\bmod{x}}=b$ a \\underline{solution} of our equation.\n\nHamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations.\n\nNow he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers $a$ and $b$ determines how many answers the Modular Equation $a{\\bmod{x}}=b$ has.",
    "tutorial": "If $a < b$ then there is no answer since $a\\operatorname*{mod}x\\leq a<b$. If $a = b$ then $x$ can be any integer larger than $a$. so there are infinite number of answers to the equation. The only remaining case is when $a > b$. Suppose $x$ is an answer to our equation. Then $x|a - b$. Also since $a{\\bmod{x}}=b$ then $b < x$. These conditions are necessary and sufficient as well. So the answer is number of divisors of $a - b$ which are strictly greater than $b$ which can be solved in $O({\\sqrt{a-b}})$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "496",
    "index": "A",
    "title": "Minimum Difficulty",
    "statement": "Mike is trying rock climbing but he is awful at it.\n\nThere are $n$ holds on the wall, $i$-th hold is at height $a_{i}$ off the ground. Besides, let the sequence $a_{i}$ increase, that is, $a_{i} < a_{i + 1}$ for all $i$ from 1 to $n - 1$; we will call such sequence a \\underline{track}. Mike thinks that the track $a_{1}$, ..., $a_{n}$ has \\underline{difficulty} $d=\\operatorname*{max}_{1<i<n-1}(a_{i+1}-a_{i})$. In other words, difficulty equals the maximum distance between two holds that are adjacent in height.\n\nToday Mike decided to cover the track with holds hanging on heights $a_{1}$, ..., $a_{n}$. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence $(1, 2, 3, 4, 5)$ and remove the third element from it, we obtain the sequence $(1, 2, 4, 5)$). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds \\textbf{must} stay at their positions.\n\nHelp Mike determine the minimum difficulty of the track after removing one hold.",
    "tutorial": "For every option of removing an element we run through the remaining elements and find the maximal difference between adjacent ones; print the smallest found answer. The solution has complexity $O(n^{2})$. It can be noticed that after removing an element the difficulty either stays the same or becomes equal to the difference between the neighbours of the removed element (whatever is larger); thus, the difficulty for every option of removing an element can be found in $O(1)$, for the total complexity of $O(n)$. Any of these solutions (or even less efficient ones) could pass the tests.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "496",
    "index": "B",
    "title": "Secret Combination",
    "statement": "You got a box with a combination lock. The lock has a display showing $n$ digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.\n\nYou know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.",
    "tutorial": "We observe that the order of operations is not important: we may first perform all the shifts, and after that all the additions. Note that after $n$ shifts the sequence returns to its original state, therefore it is sufficient to consider only the options with less than $n$ shifts. Also, after 10 times of adding 1 to all digits the sequence does not change; we may consider only options with less than 10 additions. Thus, there are overall $10n$ reasonable options for performing the operations; for every option perform the operations and find the smallest answer among all the options. As performing the operations for every option and comparing two answers to choose the best takes $O(n)$ operations, this solution performs about $10n^{2}$ elementary operations. The multiple of $10$ can be get rid of, if we note that after all shifts are made the best choice is to make the first digit equal to zero, and this leaves us but a single option for the number of additions. However, implementing this optimization is not necessary to get accepted.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "496",
    "index": "C",
    "title": "Removing Columns",
    "statement": "You are given an $n × m$ rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table\n\n\\begin{verbatim}\nabcd\nedfg\nhijk\n\\end{verbatim}\n\nwe obtain the table:\n\n\\begin{verbatim}\nacd\nefg\nhjk\n\\end{verbatim}\n\nA table is called \\underline{good} if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.",
    "tutorial": "Let's look at the first column of the table. If its letters are not sorted alphabetically, then in any valid choice of removing some columns it has to be removed. However, if its letters are sorted, then for every valid choice that has this column removed it can be restored back to the table; it is clear that the new choice is valid (that is, the rows of the new table are sorted lexicographically) and the answer (that is, the number of removed columns) has just became smaller. Consider all columns from left to right. We have already chosen which columns to remove among all the columns to the left of the current one; if leaving the current column in place breaks the lexicographical order of rows, then we have to remove it; otherwise, we may leave it in place to no harm. Arguing in the way of the previous paragraph we can prove that this greedy method yields an optimal (moreover, the only optimal) solution. The complexity is $O(n^{2})$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "496",
    "index": "D",
    "title": "Tennis Game",
    "statement": "Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores $t$ points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of $s$ sets, he wins the match and the match is over. Here $s$ and $t$ are some positive integer numbers.\n\nTo spice it up, Petya and Gena choose new numbers $s$ and $t$ before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores $t$ points and the match is over as soon as one of the players wins $s$ sets.\n\nPetya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers $s$ and $t$ for the given match are also lost. The players now wonder what values of $s$ and $t$ might be. Can you determine all the possible options?",
    "tutorial": "Choose some $t$; now emulate how the match will go, ensure that the record is valid for this $t$ and by the way find the corresponding value of $s$. Print all valid options for $s$ and $t$. This solution works in $O(n^{2})$ time, which is not good enough, but we will try to optimize it. Suppose the current set if finished and we have processed $k$ serves by now. Let us process the next set as follows: find $t$-th $1$ and $t$-th $2$ after position $k$. If $t$-th $1$ occurs earlier, then the first player wins the set, and the set concludes right after the $t$-th $1$; the other case is handled symmetrically. If the match is not over yet, and in the rest of the record there are no $t$ ones nor $t$ twos, then the record is clearly invalid. This way, every single set in the record can be processed in $O(\\log n)$ time using binary search, or $O(1)$ time using precomputed arrays of positions for each player. Now observe that for any $t$ a match of $n$ serves can not contain more than $n / t$ sets, as each set contains at least $t$ serves. If we sum up the upper limits for the number of sets for each $t$, we obtain the total upper limit for the number of sets we may need to process: $n+n/2+n/3+...\\cdot=O(n\\log n)$ (which is the famous harmonic sum). Using one of the approaches discussed above, one obtains a solution with complexity of $O(n\\log^{2}n)$ or $O(n\\log n)$; each of these solutions fits the limit nicely. Obviously, for every $t$ there is no more than one valid choice for $s$; however, maybe a bit unexpected, for a given $s$ there may exist more than one valid choice of $t$. The first test where this takes place is pretest 12. The statement requires that the pairs are printed lexicographically ordered; it is possible to make a mistake here and print the pairs with equal $s$ by descending $t$ (if we fill the array by increasing $t$ and then simply reverse the array).",
    "tags": [
      "binary search"
    ],
    "rating": 1900
  },
  {
    "contest_id": "496",
    "index": "E",
    "title": "Distributing Parts ",
    "statement": "You are an assistant director in a new musical play. The play consists of $n$ musical parts, each part must be performed by exactly one actor. After the casting the director chose $m$ actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.\n\nFirst, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, $c_{i}$ and $d_{i}$ ($c_{i} ≤ d_{i}$) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — $a_{j}$ and $b_{j}$ ($a_{j} ≤ b_{j}$) — the pitch of the lowest and the highest notes that are present in the part. The $i$-th actor can perform the $j$-th part if and only if $c_{i} ≤ a_{j} ≤ b_{j} ≤ d_{i}$, i.e. each note of the part is in the actor's voice range.\n\nAccording to the contract, the $i$-th actor can perform at most $k_{i}$ parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).\n\nThe rehearsal starts in two hours and you need to do the assignment quickly!",
    "tutorial": "Sort all the parts and actors altogether by increasing lower bounds (if equal, actors precede parts); process all the enitities in this order. We maintain a set of actors which have already occured in the order; if we meet an entry for an actor, add it to the set. If we currently process a part, we have to assign it to an actor; from the current set of actors we have to choose one such that his $d_{i}  \\ge  b_{j}$ (the $c_{i}  \\le  a_{j}$ constraint is provided by the fact that the $i$-th actor has occured earlier than the $j$-th part); if there are no such actors in the set, no answer can be obtained; if there are several actors satisftying this requirement, we should choose one with minimal $d_{i}$ (intuitively, he will be less useful in the future). Assign the chosen actor with the current part and decrement his $k_{i}$; if $k_{i}$ is now zero, the actor can not be used anymore, thus we remove him from the set. To fit the limits we should implement the set of current actors as some efficient data structure (e.g., an std::set or a treap). The resulting complexity is ${\\cal O}((n+m)\\log(n+m))$.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "497",
    "index": "D",
    "title": "Gears",
    "statement": "\\url{CDN_BASE_URL/e4fa6a6323e7ecee665f560536ee7fd5}",
    "tutorial": "When a collision happens, a vertex of one polygon lands on a side of the other polygon. Consider a reference system such that the polygon $A$ is not moving. In this system the polygon $B$ preserves its orientation (that is, does not rotate), and each of its vertices moves on some circle. Intersect all the circles for vertices of $B$ with all the sides of $A$; if any of them intersect, then some vertex of $B$ collides with a side of $A$. Symmetrically, take a reference system associated with $B$ and check whether some vertex of $A$ collides with a side of $B$. The constraints for the points' coordinates are small enough for a solution with absolute precision to be possible (using built-in integer types). Another approach (which is, in fact, basically the same) is such: suppose there is a collision in a reference system associated with $A$. Then the following equality for vectors holds: $x + y = z$; here $z$ is a vector that starts at $P$ and ends somewhere on the bound of $A$, $x$ is a vector that starts at $Q$ and ends somewhere on the bound of $B$, $y$ is a vector that starts at $P$ and ends somewhere on the circle centered at $P$ that passes through $Q$. Rewrite the equality as $y = z - x$; now observe that the set of all possible values of $z - x$ forms the Minkowski sum of $A$ and reflection of $B$ (up to some shift), and the set of all possible values of $y$ is a circle with known parameters. The Minkowski sum can be represented as a union of $nm$ parallelograms, each of which is the Minkowski sum of a pair of sides of different polygons; finally, intersect all parallelograms with the circle. Both solutions have complexity $O(nm)$. As noted above, it is possible to solve the problem using integer arithemetics (that is, with absolute precision); however, the fact that the points' coordinates are small lets most of the solutions with floating point arithmetics pass. It was tempting to write an approximate numerical solution; we struggled hard not to let such solutions pass, and eventually none of them did. =) Many participants had troubles with pretest 8. It looks as follows (the left spiral revolves around the left point, and the right spiral revolves around the right point):",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "497",
    "index": "E",
    "title": "Subsequences Return",
    "statement": "Assume that $s_{k}(n)$ equals the sum of digits of number $n$ in the $k$-based notation. For example, $s_{2}(5) = s_{2}(101_{2}) = 1 + 0 + 1 = 2$, $s_{3}(14) = s_{3}(112_{3}) = 1 + 1 + 2 = 4$.\n\nThe sequence of integers $a_{0}, ..., a_{n - 1}$ is defined as $a_{j}=s_{k}(j){\\bmod{k}}$. Your task is to calculate the number of distinct \\underline{subsequences} of sequence $a_{0}, ..., a_{n - 1}$. Calculate the answer modulo $10^{9} + 7$.\n\nSequence $a_{1}, ..., a_{k}$ is called to be a \\underline{subsequence} of sequence $b_{1}, ..., b_{l}$, if there is a sequence of indices $1 ≤ i_{1} < ... < i_{k} ≤ l$, such that $a_{1} = b_{i1}$, ..., $a_{k} = b_{ik}$. In particular, an empty sequence (i.e. the sequence consisting of zero elements) is a subsequence of any sequence.",
    "tutorial": "Consider some string; how does one count the number of its distinct subsequences? Let us append symbols to the string consequently and each time count the number of subsequences that were not present before. Let's append a symbol $c$ to a string $s$; in the string $s + c$ there are as many subsequences that end in $c$ as there were subsequences in $s$ overall. Add all these subsequences to the number of subsequnces of $s$; now each subsequence is counted once, except for the subsequences that end in $c$ but were already present in $s$ before; these are counted twice. Thus, the total number of subsequences in the new string is twice the total number of subsequences in the old string minus the number of subsequences in the old string which end in $c$. This leads us to the following solution: for each symbol $c$ store how many subsequences end in $c$, denote $cnt_{c}$. Append symbol $c$; now $cnt_{c}$ becomes equal to the sum of all $cnt$'s plus one (for the empty subsequence), and all the other $cnt$'s do not change. For example, consider the first few symbols of the Thue-Morse sequence: $ \\epsilon $ - (0, 0) $ \\epsilon $ - (0, 0) $0$ - ( 0 + 0 + 1 = 1, 0) $0$ - ( 0 + 0 + 1 = 1, 0) $01$ - (1, 1 + 0 + 1 = 2) $01$ - (1, 1 + 0 + 1 = 2) $011$ - (1, 1 + 2 + 1 = 4) $011$ - (1, 1 + 2 + 1 = 4) $0110$ - ( 1 + 4 + 1 = 6, 4) $0110$ - ( 1 + 4 + 1 = 6, 4) ... ... Let us put the values of $cnt$ in the coordinates of a vector, and also append a coordinate which is always equal to 1. It is now clear that appending a symbol to the string alters the vector as a multiplication by some matrix. Let us assign a matrix for each symbol, and also for each string as a product of matrices for the symbols of the strings in that order. Now, consider the prefix of the sequence $a_{i}$ of length $k^{m}$. Divide it into $k$ parts of length $k^{m - 1}$; $x$-th ($0$-based) of these parts can be obtained from the $0$-th one by adding $x$ modulo $k$ to all elements of the part. Let us count the matrices (see above) for the prefixes of length $k^{m}$, and also for all strings that are obtained by adding $x$ to all of the prefixes' elements; denote such matrix $A_{m, x}$. It is easy to see that if $m > 0$, then $A_{m.x}=A_{m-1.x}A_{m-1.(x+1)\\,\\mathrm{mod}\\,k\\cdot\\cdot\\cdot A_{m-1.(x+k-1)\\,m o d}\\,k}$. This formula allows us to count $A_{m, x}$ for all $m\\leq\\log_{k}n$ and all $x$ from 0 to $k - 1$ in $O(l o g_{k}n\\times k\\times k\\times k^{3})=O(\\log n\\times k^{5}/l o g k)$ time. Now, upon having all $A_{m, x}$ we can multiply some of them in the right order to obtain the matrix for the prefix of the sequence $a_{i}$ of length $n$. Unfortunately, this is not quite enough as the solution doesn't fit the time limit yet. Here is one way to speed up sufficiently: note that the product in the formula $A_{m.x}=A_{m-1.x}A_{m-1.(x+1)\\,\\mathrm{mod}\\,k\\cdot\\cdot\\cdot A_{m-1.(x+k-1)\\,m o d}\\,k}$ can be divided as shown: $A_{m - 1, x}... A_{m - 1, k - 1}  \\times  A_{m - 1, 0}... A_{m - 1, x - 1}$ (if $x = 0$, take the second part to be empty). Count all the \"prefixes\" and \"suffixes\" products of the set $A_{m, x}$: $P_{m, x} = A_{m, 0}... A_{m, x - 1}$, $S_{m, x} = A_{m, x}... A_{m, k - 1}$. Now $A_{m, x} = S_{m - 1, x}P_{m - 1, x}$. Thus, the computation of $A_{m, x}$ for all $x$ and a given $m$ can be done as computing all $P_{m - 1, x}$, $S_{m - 1, x}$ using $O(k)$ matrix multiplications, and each $A_{m, x}$ is now can be found using one matrix multiplication. Finally, the solution now works in $O(\\log n\\times k^{4}/\\log k)$ time, which fits the limits by a margin.",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2900
  },
  {
    "contest_id": "498",
    "index": "A",
    "title": "Crazy Town",
    "statement": "Crazy Town is a plane on which there are $n$ infinite line roads. Each road is defined by the equation $a_{i}x + b_{i}y + c_{i} = 0$, where $a_{i}$ and $b_{i}$ are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.\n\nYour home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).\n\nDetermine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.",
    "tutorial": "It can be easily proved that, if two points from statement are placed on different sides of some line, this line will be crossed anyway. So, all we need to do is to cross all these lines, so the answer is the number of these lines. To check if two points lies on different sides of a line one can simply use its coordinates to place in line equation and check if these two values have different signs. Solution complexity - $O(n)$.",
    "tags": [
      "geometry"
    ],
    "rating": 1700
  },
  {
    "contest_id": "498",
    "index": "B",
    "title": "Name That Tune",
    "statement": "It turns out that you are a great fan of rock band AC/PE. Peter learned that and started the following game: he plays the first song of the list of $n$ songs of the group, and you have to find out the name of the song. After you tell the song name, Peter immediately plays the following song in order, and so on.\n\nThe $i$-th song of AC/PE has its recognizability $p_{i}$. This means that if the song has not yet been recognized by you, you listen to it for exactly one more second and with probability of $p_{i}$ percent you recognize it and tell it's name. Otherwise you continue listening it. Note that you can only try to guess it only when it is integer number of seconds after the moment the song starts playing.\n\nIn all AC/PE songs the first words of chorus are the same as the title, so when you've heard the first $t_{i}$ seconds of $i$-th song and its chorus starts, you immediately guess its name for sure.\n\nFor example, in the song Highway To Red the chorus sounds pretty late, but the song has high recognizability. In the song Back In Blue, on the other hand, the words from the title sound close to the beginning of the song, but it's hard to name it before hearing those words. You can name both of these songs during a few more first seconds.\n\nDetermine the expected number songs of you will recognize if the game lasts for exactly $T$ seconds (i. e. you can make the last guess on the second $T$, after that the game stops).\n\n\\textbf{If all songs are recognized faster than in $T$ seconds, the game stops after the last song is recognized.}",
    "tutorial": "Let's numerate all the songs and seconds starting from 0. Problem will be solved using DP approach. State will be described by two integers $(i, j)$: $dp[i][j]$ is probability of that we named exactly $i$ songs, and the last named song was named exactly before $j$'th second (after $j - 1$ seconds). $dp[0][0] = 1$ obviously. To make a move from state $(i, j)$ to state $(i + 1, j + k)$ ($1  \\le  k < t_{i}$), we must name the song exactly after $k$ seconds its playing - probability of that is $(1 - p_{i})^{k - 1} \\cdot p_{i}$. To fixed state $(i + 1, j)$ sum of that moves can be represented as $\\sum d p[i][j-k]\\cdot(1-p_{i})^{k-1}\\cdot p_{i}$. Simple calculation of this value for each state gives $O(nT^{2})$ complexity, so one must notice, that this values can be calculated using two pointers for fixed $i$ (in common case it represent a segment with $t_{i}$ length) for every $j$ in time $O(T)$. This way calculating this type of moves takes $O(nT)$ time. There is also a move to $(i + 1, j + t_{i})$ and a move from $(i, j)$ to $(i, (j + k) = T)$, when we couldn't name current song in time $T$. This types of moves is calculated with $O(nT)$ too. Solution complexity - $O(nT)$.",
    "tags": [
      "dp",
      "probabilities",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "498",
    "index": "C",
    "title": "Array and Operations",
    "statement": "You have written on a piece of paper an array of $n$ positive integers $a[1], a[2], ..., a[n]$ and $m$ good pairs of integers $(i_{1}, j_{1}), (i_{2}, j_{2}), ..., (i_{m}, j_{m})$. Each good pair $(i_{k}, j_{k})$ meets the following conditions: $i_{k} + j_{k}$ is an odd number and $1 ≤ i_{k} < j_{k} ≤ n$.\n\nIn one operation you can perform a sequence of actions:\n\n- take one of the good pairs $(i_{k}, j_{k})$ and some integer $v$ ($v > 1$), which divides both numbers $a[i_{k}]$ and $a[j_{k}]$;\n- divide both numbers by $v$, i. e. perform the assignments: $a[i_{k}]={\\frac{a[i_{k}]}{n}}$ and $a[j_{k}]={\\frac{a[j_{k}]}{\\phantom{\\alpha}n}}$.\n\nDetermine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations.",
    "tutorial": "We will divide only by prime numbers. First, let's build a graph, where each of $n$ numbers have own vertex group: Find all prime factors of current number. Every factor will have its own vertex in a group, furthermore, if some factor $p$ has power of $a_{i}$ in current number, it will have exactly $a_{i}$ vertexes in group. The number of vertexes in such graph is $O(n\\log A)$. Now we will make edges in our graph: edge between two vertexes exists if and only if there is a good pair (given in statement) of vertexes group numbers and the prime values of a vertexes are the same. That means that we can divide that group numbers by that prime. The number of edges is $O(m\\log^{2}A)$. Good pairs are given the way that our graph is bipartite. After finding maximum matching in this graph we represent the way of doing operations as described in the statement. As soon as solution is using Kuhn's algorithm, its complexity is $O(n m\\log^{3}A)$. One could notice that some of the edges are useless and reduce it to $O(n m\\log^{2}A)$.",
    "tags": [
      "flows",
      "graph matchings",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "498",
    "index": "D",
    "title": "Traffic Jams in the Land",
    "statement": "Some country consists of $(n + 1)$ cities, located along a straight highway. Let's number the cities with consecutive integers from $1$ to $n + 1$ in the order they occur along the highway. Thus, the cities are connected by $n$ segments of the highway, the $i$-th segment connects cities number $i$ and $i + 1$. Every segment of the highway is associated with a positive integer $a_{i} > 1$ — the period of traffic jams appearance on it.\n\nIn order to get from city $x$ to city $y$ ($x < y$), some drivers use the following tactics.\n\nInitially the driver is in city $x$ and the current time $t$ equals zero. Until the driver arrives in city $y$, he perfors the following actions:\n\n- if the current time $t$ is a multiple of $a_{x}$, then the segment of the highway number $x$ is now having traffic problems and the driver stays in the current city for one unit of time (formally speaking, we assign $t = t + 1$);\n- if the current time $t$ is not a \\textbf{multiple} of $a_{x}$, then the segment of the highway number $x$ is now clear and that's why the driver uses one unit of time to move to city $x + 1$ (formally, we assign $t = t + 1$ and $x = x + 1$).\n\nYou are developing a new traffic control system. You want to consecutively process $q$ queries of two types:\n\n- determine the final value of time $t$ after the ride from city $x$ to city $y$ ($x < y$) assuming that we apply the tactics that is described above. Note that for each query $t$ is being reset to $0$.\n- replace the period of traffic jams appearing on the segment number $x$ by value $y$ (formally, assign $a_{x} = y$).\n\nWrite a code that will effectively process the queries given above.",
    "tutorial": "The solution of a problem - 60 (LCM of a numbers from 2 to 6) segment trees. In $v$'th segment tree we will hold for every segment $[l, r]$ the next value: minimum time needed to get from $l$ to $r$ if we start in a moment of time equal to $v$ modulo 60. Using these trees' values it is easy to quickly answer the questions, carefully changing the trees' values.",
    "tags": [
      "data structures",
      "dp",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "498",
    "index": "E",
    "title": "Stairs and Lines",
    "statement": "You are given a figure on a grid representing stairs consisting of 7 steps. The width of the stair on height $i$ is $w_{i}$ squares. Formally, the figure is created by consecutively joining rectangles of size $w_{i} × i$ so that the $w_{i}$ sides lie on one straight line. Thus, for example, if all $w_{i} = 1$, the figure will look like that (different colors represent different rectangles):\n\nAnd if $w = {5, 1, 0, 3, 0, 0, 1}$, then it looks like that:\n\nFind the number of ways to color some borders of the figure's inner squares so that no square had all four borders colored. The borders of the squares lying on the border of the figure should be considered painted. The ways that differ with the figure's rotation should be considered distinct.",
    "tutorial": "The problem is solved using DP approach $dp[i][mask]$ - the number of ways to paint first $i$ blocks of a ladder the way that the last layer of vertical edges is painted as described in mask $mask$. This could be easily recalculated using matrix $M[mask1][mask2]$ - the number of ways to paint horizontal edges between two neighbour vertical layers painted as represented by masks $mask1$ and $mask2$. For fixed $i$ we have $w_{i}$ layers, so this matrix must be multiplied by itself $w_{i}$ times, which can be quickly done by binary-pow algorithm. After that this matrix is simply used in dynamic described above. Solution complexity - $O(8^{7}\\cdot\\sum\\log w_{i})$.",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "499",
    "index": "A",
    "title": "Watching a movie",
    "statement": "You have decided to watch the best moments of some movie. There are two buttons on your player:\n\n- Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.\n- Skip exactly $x$ minutes of the movie ($x$ is some fixed positive integer). If the player is now at the $t$-th minute of the movie, then as a result of pressing this button, it proceeds to the minute $(t + x)$.\n\nInitially the movie is turned on in the player on the first minute, and you want to watch exactly $n$ best moments of the movie, the $i$-th best moment starts at the $l_{i}$-th minute and ends at the $r_{i}$-th minute (more formally, the $i$-th best moment consists of minutes: $l_{i}, l_{i} + 1, ..., r_{i}$).\n\nDetermine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?",
    "tutorial": "One can solve the problem using greedy algorithm: if we can skip $x$ minutes at current moment without skipping any good moment - we do that, otherwise - watch another minute of the film.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "499",
    "index": "B",
    "title": "Lecture",
    "statement": "You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.\n\nYou know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.\n\nYou can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.\n\nYou are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.",
    "tutorial": "In this task you must find for every string in the text the pair containing that string, and from two strings of that pair output the shortest one.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "500",
    "index": "A",
    "title": "New Year Transportation",
    "statement": "New Year is coming in Line World! In this world, there are $n$ cells numbered by integers from $1$ to $n$, as a $1 × n$ board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.\n\nSo, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of $n - 1$ positive integers $a_{1}, a_{2}, ..., a_{n - 1}$. For every integer $i$ where $1 ≤ i ≤ n - 1$ the condition $1 ≤ a_{i} ≤ n - i$ holds. Next, he made $n - 1$ portals, numbered by integers from 1 to $n - 1$. The $i$-th ($1 ≤ i ≤ n - 1$) portal connects cell $i$ and cell $(i + a_{i})$, and one can travel from cell $i$ to cell $(i + a_{i})$ using the $i$-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell $(i + a_{i})$ to cell $i$ using the $i$-th portal. It is easy to see that because of condition $1 ≤ a_{i} ≤ n - i$ one can't leave the Line World using portals.\n\nCurrently, I am standing at cell $1$, and I want to go to cell $t$. However, I don't know whether it is possible to go there. Please determine whether I can go to cell $t$ by only using the construted transportation system.",
    "tutorial": "Let's assume that I am in the cell $i$ ($1  \\le  i  \\le  n$). If $i  \\le  n - 1$, I have two choices: to stay at cell $i$, or to go to cell $(i + a_{i})$. If $i = t$, we are at the target cell, so I should print \"YES\" and terminate. If $i > t$, I cannot go to cell $t$ because I can't use the portal backwards, so one should print \"NO\" and terminate. Otherwise, I must go to cell $(i + a_{i})$. Using this method, I visit each cell at most once, and there are $n$ cells, so the problem can be solved in linear time. There are 9 pretests in this problem. There are no test where $n = t$ holds in pretests. Many people didn't handle this case, and got hacked or got Wrong Answer on test 13. Time: $O(n)$ Memory: $O(n)$ (maybe $O(1)$)",
    "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <numeric>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h>\n#include <iostream>\n \nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long llu;\ntypedef double lf;\ntypedef unsigned int uint;\ntypedef long double llf;\ntypedef pair<int, int> pii;\n \nconst int N_ = 30500;\n \nint N, T, A[N_];\n \nint main() {\n    scanf(\"%d%d\", &N, &T);\n    for(int i = 1; i < N; i++) {\n        scanf(\"%d\", &A[i]);\n    }\n    A[N] = 1;\n    for(int cur = 1; cur <= N; cur += A[cur]) {\n        if(cur == T) return 0 & puts(\"YES\");\n    }\n    \n    puts(\"NO\");\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "500",
    "index": "B",
    "title": "New Year Permutation",
    "statement": "User ainta has a permutation $p_{1}, p_{2}, ..., p_{n}$. As the New Year is coming, he wants to make his permutation as pretty as possible.\n\nPermutation $a_{1}, a_{2}, ..., a_{n}$ is prettier than permutation $b_{1}, b_{2}, ..., b_{n}$, if and only if there exists an integer $k$ ($1 ≤ k ≤ n$) where $a_{1} = b_{1}, a_{2} = b_{2}, ..., a_{k - 1} = b_{k - 1}$ and $a_{k} < b_{k}$ all holds.\n\nAs known, permutation $p$ is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an $n × n$ binary matrix $A$, user ainta can swap the values of $p_{i}$ and $p_{j}$ ($1 ≤ i, j ≤ n$, $i ≠ j$) if and only if $A_{i, j} = 1$.\n\nGiven the permutation $p$ and the matrix $A$, user ainta wants to know the prettiest permutation that he can obtain.",
    "tutorial": "It seems that many contestants were confused by the statement, so let me clarify it first. Given a permutation $p_{1}, p_{2}, ..., p_{n}$ and a $n  \\times  n$-sized binary matrix $A$, the problem asks us to find the lexicographically minimum permutation which can be achieved by swapping two distinct elements $p_{i}$ and $p_{j}$ where the condition $A_{i, j} = 1$ holds. (From the statement, permutation $A$ is prettier than permutation $B$ if and only if $A$ is lexicographically less than $B$.) Let's think matrix $A$ as an adjacency matrix of a undirected unweighted graph. If two vertices $i$ and $j$ are in the same component (in other words, connected by some edges), the values of $p_{i}$ and $p_{j}$ can be swapped, using a method similar to bubble sort. Look at the picture below for easy understanding. Because all the two distinct vertices in the same component can be swapped, the vertices in the same component can be sorted. In conclusion, we can solve the problem by the following procedure. Find all the connected components. For each component, sort the elements in the component. Print the resulting permutation. The size limit is quite small, so one can use any algorithm (DFS/BFS/..) for as many times as you want. Time: $O(n^{2})$ - because of the graph traversal. $O(n^{3})$ is okay because of small constraints. Memory: $O(n^{2})$",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h> \n \nusing namespace std;\ntypedef long long ll;\ntypedef double lf;\ntypedef long double llf;\ntypedef unsigned long long llu;\n \nconst int N_ = 1050;\nint N;\nint P[N_];\nchar S[N_];\n \nint group[N_];\n \nint find_group(int x) {\n\tif (x == group[x]) return x;\n\treturn group[x] = find_group(group[x]);\n}\n \nvoid merge_group(int a, int b) {\n\ta = find_group(a);\n\tb = find_group(b);\n\tif (a != b) group[a] = b;\n}\n \nvector<int> pos[N_];\nint cnt[N_];\n \nint main() {\n\tscanf(\"%d\", &N);\n \n\tfor (int i = 1; i <= N; i++) group[i] = i;\n \n\tfor (int i = 1; i <= N; i++) scanf(\"%d\", &P[i]);\n\tfor (int i = 1; i <= N; i++) {\n\t\tscanf(\"%s\", S + 1);\n\t\tfor (int j = 1; j <= N; j++) if (S[j] == '1') merge_group(i, j);\n\t}\n \n\tfor (int i = 1; i <= N; i++) pos[find_group(i)].push_back(P[i]);\n\tfor (int i = 1; i <= N; i++) sort(pos[i].begin(), pos[i].end());\n \n\tfor (int i = 1; i <= N; i++) {\n\t\tint g = find_group(i);\n\t\tprintf(\"%d%c\", pos[g][cnt[g]++], (i == N) ? '\\n' : ' ');\n\t}\n \n \n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "500",
    "index": "C",
    "title": "New Year Book Reading",
    "statement": "New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has $n$ books numbered by integers from 1 to $n$. The weight of the $i$-th ($1 ≤ i ≤ n$) book is $w_{i}$.\n\nAs Jaehyun's house is not large enough to have a bookshelf, he keeps the $n$ books by stacking them vertically. When he wants to read a certain book $x$, he follows the steps described below.\n\n- He lifts all the books above book $x$.\n- He pushes book $x$ out of the stack.\n- He puts down the lifted books without changing their order.\n- After reading book $x$, he puts book $x$ on the top of the stack.\n\nHe decided to read books for $m$ days. In the $j$-th ($1 ≤ j ≤ m$) day, he will read the book that is numbered with integer $b_{j}$ ($1 ≤ b_{j} ≤ n$). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.\n\nAfter making this plan, he realized that the total weight of books he should lift during $m$ days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?",
    "tutorial": "In order to calculate the minimum possible lifted weight, we should find the initial stack first. Let's find the positions one by one. First, let's decide the position of book $b_{1}$. After day 1, book $b_{1}$ will be on the top of the stack, regardless of the order of the initial stack. Therefore, in order to minimize the lifted weight during day 1, book $b_{1}$ must be on the top of the initial stack. (so actually, in day 1, Jaehyun won't lift any book) Next, let's decide the position of book $b_{2}$. (assume that $b_{1}  \\neq  b_{2}$ for simplicity) Currently, $b_{1}$ is on the top of the stack, and it cannot be changed because of the procedure. Therefore, in order to minimize the lifted weight during day 2, book $b_{2}$ must be immediately below book $b_{1}$. Considering this, we can find the optimal strategy to create the initial stack: Scan $b_{1}, b_{2}, ..., b_{m}$ step by step. Let's assume that I am handling $b_{i}$ now. If $b_{i}$ has appeared before (formally, if $b_{i}\\in\\{b_{1},b_{2},\\cdot\\cdot\\cdot,b_{i-1}\\}$), erase $b_{i}$ from the sequence. Otherwise, leave $b_{i}$. The resulting sequence will be the optimal stack. You should note that it is not necessary for Jaehyun to read all the books during 2015, which means the size of the resulting sequence may be smaller than $n$. The books which doesn't appear in the resulting sequence must be in the bottom of the initial stack (obviously). However, this problem doesn't require us to print the initial stack, so it turned out not to be important. In conclusion, finding the initial stack takes $O(n + m)$ time. After finding the initial stack, we can simulate the procedure given in the statement naively. It will take $O(nm)$ time. Time: $O(nm)$ Memory: $O(n + m)$",
    "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <numeric>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h>\n#include <iostream>\n \nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long llu;\ntypedef double lf;\ntypedef unsigned int uint;\ntypedef long double llf;\ntypedef pair<int, int> pii;\n \nconst int N_ = 505, M_ = 1050;\n \nint N, M;\nint W[N_], D[M_];\nbool used[N_];\nint pile[N_], pile_n;\nint ans;\n \nint main() {\n    scanf(\"%d%d\", &N, &M);\n    for(int i = 1; i <= N; i++) {\n        scanf(\"%d\", &W[i]);\n    }\n    for(int i = 1; i <= M; i++) {\n        scanf(\"%d\", &D[i]);\n        if(!used[D[i]]) pile[++pile_n] = D[i], used[D[i]] = true;\n    }\n    for(int i = 1; i <= N; i++) if(!used[i]) pile[++pile_n] = i;\n    \n    for(int i = 1; i <= M; i++) {\n        for(int j = 1; j <= N; j++) {\n            if(pile[j] == D[i]) {\n                for(int k = j; k > 1; k--) pile[k] = pile[k - 1];\n                pile[1] = D[i];\n                break;\n            }\n            ans += W[pile[j]];\n        }\n    }\n    \n    printf(\"%d\\n\", ans);\n    \n    \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "500",
    "index": "D",
    "title": "New Year Santa Network",
    "statement": "New Year is coming in Tree World! In this world, as the name implies, there are $n$ cities connected by $n - 1$ roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to $n$, and the roads are numbered by integers from $1$ to $n - 1$. Let's define $d(u, v)$ as total length of roads on the path between city $u$ and city $v$.\n\nAs an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the $i$-th year, the length of the $r_{i}$-th road is going to become $w_{i}$, which is shorter than its length before. Assume that the current year is year $1$.\n\nThree Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities $c_{1}$, $c_{2}$, $c_{3}$ and make exactly one warehouse in each city. The $k$-th ($1 ≤ k ≤ 3$) Santa will take charge of the warehouse in city $c_{k}$.\n\nIt is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to $d(c_{1}, c_{2}) + d(c_{2}, c_{3}) + d(c_{3}, c_{1})$ dollars. Santas are too busy to find the best place, so they decided to choose $c_{1}, c_{2}, c_{3}$ randomly uniformly over all triples of distinct numbers from $1$ to $n$. Santas would like to know the expected value of the cost needed to build the network.\n\nHowever, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.",
    "tutorial": "The problem asks us to calculate the value of Let's write it down.. So, we need to calculate the value of $\\sum_{1<u,v<n,u>v}d(u,v)$. I'll denote the sum as $S$. How should we calculate this? For simplicity, I'll set node 1 as the root of the tree. Let's focus on an edge $e$, connecting two vertices $u$ and $p$. See the picture below. Set $A$ is a set of vertices in the subtree of vertex $u$, and set $B$ is a set of vertices which is not in the subtree of vertex $u$. So, $A\\cup B$ is the set of vertices in the tree, and $A\\cap B$ is empty. For all pairs of two vertices $(x, y)$ where the condition $x\\in A$ and $y\\in B$ holds, the shortest path between $x$ and $y$ contains edge $e$. There are $size(A)  \\times  size(B)$ such pairs. So, edge $e$ increases the sum $S$ by $2  \\times  l_{e}  \\times  size(A)  \\times  size(B)$. (because $d(x, y)$ and $d(y, x)$ both contributes to $S$) $size(A)$ (the size of the subtree whose root is $u$) can be calculated by dynamic programming in trees, which is well known. $size(B)$ equals to $N - size(A)$. So, for each edge $e$, we can pre-calculate how many times does this edge contributes to the total sum. Let's define $t(e) = size(A)  \\times  size(B)$, ($A$ and $B$ is mentioned above). If the length of a certain road $e$ decreases by $d$, $S$ will decrease by $t(e)  \\times  d$. So we can answer each query. Time: $O(n)$ (pre-calculation) + $O(q)$ (query) Memory: $O(n)$ ($O(n + q)$ is okay too)",
    "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <numeric>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h>\n#include <list>\n#include <iostream>\n \nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long llu;\ntypedef double lf;\ntypedef unsigned int uint;\ntypedef long double llf;\ntypedef pair<int, int> pii;\n \nconst int N_ = 100500;\n \nint N;\nvector<int> tree[N_];\nint parent[N_];\nint sz[N_];\nll cnt[N_];\nint num[N_];\nint length[N_];\nint nd[N_];\nint Q;\n \nvoid dfs (int u, int p = -1) {\n    sz[u] = 1;\n    parent[u] = p;\n    for(int e = 0; e < tree[u].size(); e++) {\n        int v = tree[u][e];\n        if(v == p) continue;\n        dfs(v, u);\n        sz[u] += sz[v];\n        cnt[v] = (ll)sz[v] * (N - sz[v]) * 2;\n        length[u] ^= length[v];\n        num[u] ^= num[v];\n    }\n}\n \nint main() {\n    scanf(\"%d\", &N);\n    for(int i = 1; i <= N-1; i++) {\n        int u, v, l; scanf(\"%d%d%d\", &u, &v, &l);\n        tree[u].push_back(v);\n        tree[v].push_back(u);\n        length[u] ^= l;\n        length[v] ^= l;\n        num[u] ^= i;\n        num[v] ^= i;\n    }\n    \n    dfs(1);\n    \n    ll ans = 0;\n    for(int i = 2; i <= N; i++) {\n        ans += cnt[i] * length[i];\n        nd[num[i]] = i;\n    }\n    \n    lf factor = 3. / ((lf)N * (N-1));\n    \n    scanf(\"%d\", &Q);\n    while(Q--) {\n        int e, d; scanf(\"%d%d\", &e, &d);\n        int u = nd[e];\n        ans += cnt[u] * (d - length[u]);\n        length[u] = d;\n        printf(\"%.10lf\\n\", (lf)ans * factor);\n    }\n    \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "500",
    "index": "E",
    "title": "New Year Domino",
    "statement": "Celebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos\n\nUser ainta, who lives in a 2D world, is going to post a video as well.\n\nThere are $n$ dominoes on a 2D Cartesian plane. $i$-th domino ($1 ≤ i ≤ n$) can be represented as a line segment which is parallel to the $y$-axis and whose length is $l_{i}$. The lower point of the domino is on the $x$-axis. Let's denote the $x$-coordinate of the $i$-th domino as $p_{i}$. Dominoes are placed one after another, so $p_{1} < p_{2} < ... < p_{n - 1} < p_{n}$ holds.\n\nUser ainta wants to take a video of falling dominoes. To make dominoes fall, he can push a single domino to the right. Then, the domino will fall down drawing a circle-shaped orbit until the line segment totally overlaps with the x-axis.\n\nAlso, if the $s$-th domino touches the $t$-th domino while falling down, the $t$-th domino will also fall down towards the right, following the same procedure above. Domino $s$ touches domino $t$ if and only if the segment representing $s$ and $t$ intersects.\n\nSee the picture above. If he pushes the leftmost domino to the right, it falls down, touching dominoes (A), (B) and (C). As a result, dominoes (A), (B), (C) will also fall towards the right. However, domino (D) won't be affected by pushing the leftmost domino, but eventually it will fall because it is touched by domino (C) for the first time.\n\nThe picture above is an example of falling dominoes. Each red circle denotes a touch of two dominoes.\n\nUser ainta has $q$ plans of posting the video. $j$-th of them starts with pushing the $x_{j}$-th domino, and lasts until the $y_{j}$-th domino falls. But sometimes, it could be impossible to achieve such plan, so he has to lengthen some dominoes. It costs one dollar to increase the length of a single domino by $1$. User ainta wants to know, for each plan, the minimum cost needed to achieve it. Plans are processed independently, i. e. if domino's length is increased in some plan, it doesn't affect its length in other plans. Set of dominos that will fall except $x_{j}$-th domino and $y_{j}$-th domino doesn't matter, but the initial push should be on domino $x_{j}$.",
    "tutorial": "From the statement, it is clear that, when domino $i$ falls to the right, it makes domino $j$ also fall if and only if $p_{i} < p_{j}  \\le  p_{i} + l_{i}$. For each domino $i$, let's calculate the rightmost position of the fallen dominoes $R[i]$ when we initially pushed domino $i$. From the definition, $R[i]=\\operatorname*{max}\\{p_{i}+l_{i},\\operatorname*{max}\\{R[j]\\mid p_{i}<p_{j}\\leq p_{i}+l_{i}\\}\\}$. This can be calculated by using a segment tree or using a stack, in decreasing order of $i$ (from right to left). After that, we define $U[i]$ as the smallest $j$ where $R[i] < p_{j}$ holds. (In other words, the smallest $j$ where domino $j$ is not affected by pushing domino $i$) Now, the problem becomes: Calculate $P[U[x_{i}]] - R[x_{i}] + P[U[U[x_{i}]]] - R[U[x_{i}]] + ...$, until $U[x_{i}]  \\le  y_{i}$. Because $i < U[i]$, this task can be solved by precalculating 'jumps' of $2^{something}$ times, using the method described in here. You must read the \"Another easy solution in <O(N logN, O(logN)>\" part.. Formally, let's define $U^{n + 1}[k] = U[U^{n}[k]]$ and $S^{n + 1}[k] = S^{n}[k] + (P[U^{n + 1}[k]] - R[U^{n}[k]])$. So, $S^{n}[k]$ means the sum of domino length extensions when we initially push domino $i$ and we prolonged the length exactly $n$ times. $U^{2i + 1}[k] = U^{2i}[U^{2i}[k]]$, and $S^{2i + 1}[k] = S^{2i}[k] + S^{2i}[U^{2i}[k]]$ holds. (If you don't understand this part, I suggest you to read the article linked above) Time : $O(n\\log n+q\\log n)$ or $O(n+q\\log n)$. Memory : $O(n\\log n)$",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n \n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h>\n \nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long llu;\ntypedef double lf;\ntypedef unsigned int uint;\ntypedef long double llf;\ntypedef pair<int, int> pii;\ntypedef pair<ll, int> pli;\ntypedef pair<ll, ll> pll;\n \nconst int N_ = 200500;\nconst int LEAF = 131072;\nconst int Q_ = 300500;\nconst int lgN_ = 18;\nint N, P[N_], L[N_];\n \nnamespace rmq {\n    int tree[N_];\n    \n    void upd (int x, int v) {\n        while(x <= N) {\n            tree[x] = max(tree[x], v);\n            x += x & -x;\n        }\n    }\n \n    int get (int x) {\n        int ret = 0;\n        while(x > 0) {\n            ret = max(ret, tree[x]);\n            x -= x & -x;\n        }\n        return ret;\n    }\n};\n \nint rightmost[N_];\nint nxt[lgN_][N_];\n \nint tb[lgN_][N_];\n \nint Q;\n \nint main() {\n    scanf(\"%d\", &N);\n    for(int i = 1; i <= N; i++) scanf(\"%d%d\", &P[i], &L[i]);\n    \n    for(int i = N; i > 0; i--) {\n        rightmost[i] = max(\n            P[i] + L[i],\n            rmq::get(upper_bound(P+1, P+N+1, P[i]+L[i]) - P - 1)\n        );\n        nxt[0][i] = upper_bound(P+1, P+N+1, rightmost[i]) - P;\n        tb[0][i] = max(P[nxt[0][i]] - rightmost[i], 0);\n        rmq::upd(i, rightmost[i]);\n    }\n    nxt[0][N+1] = N+1;\n    \n    for(int k = 1; k < lgN_; k++) {\n        nxt[k][N+1] = N+1;\n        for(int i = 1; i <= N; i++) {\n            nxt[k][i] = nxt[k-1][nxt[k-1][i]];\n            tb[k][i] = tb[k-1][i] + tb[k-1][nxt[k-1][i]];\n        }\n    }\n    \n    scanf(\"%d\", &Q);\n    while(Q--) {\n        int x, y; scanf(\"%d%d\", &x, &y);\n        int ret = 0;\n        \n        for(int k = lgN_-1; k >= 0; k--) {\n            if(nxt[k][x] <= y) {\n                ret += tb[k][x];\n                x = nxt[k][x];\n            }\n        }\n        printf(\"%d\\n\", ret);\n    }\n    \n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "dsu"
    ],
    "rating": 2300
  },
  {
    "contest_id": "500",
    "index": "F",
    "title": "New Year Shopping",
    "statement": "Dohyun is running a grocery store. He sells $n$ items numbered by integers from 1 to $n$. The $i$-th ($1 ≤ i ≤ n$) of them costs $c_{i}$ dollars, and if I buy it, my happiness increases by $h_{i}$. Each item can be displayed only for $p$ units of time because of freshness. As Dohyun displays the $i$-th item at time $t_{i}$, the customers can buy the $i$-th item only from time $t_{i}$ to time $t_{i} + (p - 1)$ inclusively. Also, each customer cannot buy the same item more than once.\n\nI'd like to visit Dohyun's grocery store and buy some items for the New Year Party, and maximize my happiness. Because I am a really busy person, I can visit the store only once, and for very short period of time. In other words, if I visit the store at time $t$, I can only buy the items available at time $t$. But I can buy as many items as possible, if the budget holds. I can't buy same item several times due to store rules. It is not necessary to use the whole budget.\n\nI made a list of $q$ pairs of integers $(a_{j}, b_{j})$, which means I may visit the store at time $a_{j}$, and spend at most $b_{j}$ dollars at the store. For each pair, I'd like to know the maximum happiness I can obtain. But there are so many pairs that I can't handle them. Can you help me?",
    "tutorial": "The $i$-th item is available during $[t_{i}, t_{i} + p - 1]$. In other words, at time $T$, item $i$ is available if and only if $t_{i}  \\le  T  \\le  t_{i} + p - 1$. This can be re-written as ($t_{i}  \\le  T$ and $T - p + 1  \\le  t_{i}$), which is $T - p + 1  \\le  t_{i}  \\le  T$. With this observation, we can transform the item's purchasable range into a dot, and the candidate's visit time into a range: From now on, item $i$ is only available at time $t_{i}$. and each candidate pair $(a_{j}, b_{j})$ means that I can visit the store during $[a_{j} - p + 1, a_{j}]$, and my budget is $b_{j}$ dollars at that visit. This transformation makes the problem easier to solve. Each red circled point denotes an item which is sold at that time, and each black interval denotes a candidate. Let's only consider the intervals which passes time $T$. All the intervals' length is exactly $p$, so the left bound of the interval is $(T - p)$ and the right bound of the interval is $(T + p)$. For each interval, we'd like to solve the 0/1 knapsack algorithm with the items that the interval contains. How can we do that effectively? There is an important fact that I've described above: all the interval passes time $T$. Therefore, the interval $[a_{j} - p + 1, a_{j}]$ can be split into two intervals: $[a_{j} - p + 1, T - 1]$ and $[T, a_{j}]$. So, let's solve the 0/1 knapsack problem for all intervals $[x, T - 1]$ ($T - p  \\le  x  \\le  T - 1$) and $[T, y]$ ($T  \\le  y  \\le  T + p$). Because one of the endpoints is fixed, one can run a standard dynamic programming algorithm. Therefore, the time needed in precalculation is $O(S  \\times  W)$, where $S$ is the number of items where the condition $t_{i}\\in[T-p,T+p]$ holds. Let's define $h(I, b)$, as the maximum happiness I can obtain by buying the items where the condition $t_{i}\\in I$ holds, using at most $b$ dollars. For each candidate $(a_{j}, b_{j})$, we have to calculate $h([a_{j} - p + 1, a_{j}], b_{j})$, which is equal to $max_{0  \\le  k  \\le  b}{h([a_{j} - p + 1, T - 1], k) + h([T, a_{j}], b - k)}$. So it takes $O(b_{j}) = O(W)$ time to solve each query. The only question left is: How should we choose the value of $T$? We have two facts. (1) The length of intervals is exactly $p$. (2) The algorithm covers intervals which passes time $T$. Therefore, to cover all the intervals given in the input, we should let $T$ be $p, 2p, 3p, 4p, ...$ (of course, one by one), and run the algorithm described above. Then, what is the total time complexity? Think of intervals $[0, 2p], [p, 3p], [2p, 4p], [3p, 5p], ...$. For each point, there will be at most two intervals which contains the point. Therefore, each item is reflected in the pre-calculation at most twice, so the time needed to precalculate is $O(n  \\times  W)$. The time needed to solve each query is $O(b_{j})$, and the answer of the query is calculated at most once. Therefore, the time needed to answer all the queries is $O(q  \\times  W$). Time : $O((n + q)  \\times  W)$. Memory : $O(n  \\times  W)$ Implementations: 9335699 (ainta), 9335703 (ainu7) , 9335710 (.o., using a different approach), 9335709 (.o., using a divide and conquer approach) Let's assume that $t_{1}  \\le  t_{2}  \\le  ...  \\le  t_{n}$. We can easily know that at time $T$, the indexes of all the available items forms a segment $[l, r]$. (in other words, item $l$, item $l + 1$, ..., item $r - 1$, item $r$ is available) We can use this fact to solve all the queries. Let's assume that item $l_{j}$, item $l_{j} + 1$, ..., item $r_{j} - 1$, item $r_{j}$ is available at time $a_{j}$. Define a function $solve(L, R)$. This function calculates the answer for queries where the condition $L  \\le  l_{j}  \\le  r_{j}  \\le  R$ holds. Let's assume that $L < R$ holds. (In the case $L  \\ge  R$, the answer can be calculated easily) Let $M={\\left[{\\frac{L+R}{2}}\\right]}$. Call $solve(L, M)$ and $solve(M + 1, R)$. After that, the queries needed to be calculated, satisfies the condition $l_{j}  \\le  M < r_{j}$, which means all the intervals(queries) passes item $M$. Now, to calculate the answer for such queries, we can use the method described at the dynamic programming approach. The time complexity is $O(n\\cdot b\\log n+q\\times b)$, because $T(n)=O(n\\cdot b)+2T(n/2)=O(n\\cdot b\\log n)$ and the answer of the queries can be calculated in $O(b_{j})$ per query. Time : $O((n\\log n+q)\\times W)$. Memory : $O(n  \\times  W)$",
    "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <memory.h>\n#include <math.h>\n#include <assert.h>\n#include <stack>\n#include <queue>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <string>\n#include <functional>\n#include <vector>\n#include <numeric>\n#include <deque>\n#include <utility>\n#include <bitset>\n#include <limits.h>\n#include <iostream>\n \nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long llu;\ntypedef double lf;\ntypedef unsigned int uint;\ntypedef long double llf;\ntypedef pair<int, int> pii;\n \nconst int lgN_ = 12;\nconst int N_ = 4105;\nconst int M_ = 20005;\nconst int MAXW = 4105;\nconst int MAXD = 200505;\nint N, Q, P;\n \nstruct item {\n    int h, c, t;\n    item (int h = 0, int c = 0, int t = 0) : h(h), c(c), t(t) { }\n    \n    bool operator < (const item &i) const {\n        return t < i.t;\n    }\n} D[N_];\n \nint tb[N_][MAXW];\nint L[MAXD], R[MAXD];\n \nvector<int> marked[lgN_][N_];\nint budget[M_], when[M_];\n \nint answer[M_];\n \nvoid precalc (int l, int r, int h) {\n    int m = (l + r) >> 1;\n    if(l >= r) return;\n    \n    { // left\nfor(int j = 0; j < D[m].c; j++) tb[m][j] = 0;\n        for(int j = D[m].c; j < MAXW; j++) tb[m][j] = D[m].h;\n        \n        for(int i = m-1; i >= l; i--) {\n            for(int j = 1; j < MAXW; j++) {\n                tb[i][j] = max(tb[i + 1][j], tb[i][j - 1]);\n                if(j >= D[i].c) tb[i][j] = max(tb[i][j], tb[i + 1][j - D[i].c] + D[i].h);\n            }\n        }\n    }\n    \n    { // right\n        if(m+1 <= r) {\nfor(int j = 0; j < D[m+1].c; j++) tb[m+1][j] = 0;\n            for(int j = D[m+1].c; j < MAXW; j++) tb[m+1][j] = D[m+1].h;\n        }\n        for(int i = m+2; i <= r; i++) {\n            for(int j = 1; j < MAXW; j++) {\n                tb[i][j] = max(tb[i - 1][j], tb[i][j - 1]);\n                if(j >= D[i].c) tb[i][j] = max(tb[i][j], tb[i - 1][j - D[i].c] + D[i].h);\n            }\n        }\n    }\n    \n    for(int w = 0; w < marked[h][l].size(); w++) {\n        int q = marked[h][l][w];\n        int x = L[when[q]], y = R[when[q]], b = budget[q];\n        int &ans = answer[q];\n        if(x <= m && m == y) ans = tb[x][b];\n        else if(x == m+1 && m+1 <= y) ans = tb[y][b];\n        else if(x <= m && m+1 <= y) {\n            for(int i = 0; i <= b; i++) ans = max(ans, tb[x][i] + tb[y][b - i]);\n        }else {\n            assert(0);\n        }\n    }\n#undef tb\n    \n    if(l < r) {\n        precalc(l, m-1, h + 1);\n        precalc(m+1, r, h + 1);\n    }\n}\n \nvoid mark (int l, int r, int h, int x, int y, int q) {\n    int m = (l + r) >> 1;\n    if(x > y) return;\n    \n    if(x <= m+1 && m <= y) {\n        marked[h][l].push_back(q);\n        return;\n    }\n    \n    if(y < m) mark(l, m-1, h+1, x, y, q);\n    if(m < x) mark(m+1, r, h+1, x, y, q);\n}\n \nint main() {\n    scanf(\"%d%d\", &N, &P);\n    for(int i = 1; i <= N; i++) {\n        scanf(\"%d%d%d\", &D[i].c, &D[i].h, &D[i].t);\n        R[D[i].t]++;\n        L[D[i].t + P]++;\n    }\n    \n    sort(D + 1, D + N + 1);\n    \n    L[1] = 1;\n    for(int i = 1; i < MAXD; i++) {\n        L[i] += L[i-1];\n        R[i] += R[i-1];\n    }\n    \n    scanf(\"%d\", &Q);\n    for(int i = 1; i <= Q; i++) {\n        int a, b; scanf(\"%d%d\", &a, &b);\n        when[i] = a; budget[i] = b;\n        \n        if(L[a] < R[a])\n            mark(1, N, 0, L[a], R[a], i);\n        else if(L[a] == R[a])\n            answer[i] = (D[L[a]].c <= budget[i]) ? D[L[a]].h : 0;\n    }\n    precalc(1, N, 0);\n    \n    for(int i = 1; i <= Q; i++) {\n        printf(\"%d\\n\", answer[i]);\n    }\n    \n    return 0;\n}",
    "tags": [
      "divide and conquer",
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "500",
    "index": "G",
    "title": "New Year Running",
    "statement": "New Year is coming in Tree Island! In this island, as the name implies, there are $n$ cities connected by $n - 1$ roads, and for any two distinct cities there always exists exactly one path between them. For every person in Tree Island, it takes exactly one minute to pass by exactly one road.\n\nThere is a weird New Year tradition for runnners in Tree Island, which is called \"extreme run\". This tradition can be done as follows.\n\nA runner chooses two distinct cities $a$ and $b$. For simplicity, let's denote the shortest path from city $a$ to city $b$ as $p_{1}, p_{2}, ..., p_{l}$ (here, $p_{1} = a$ and $p_{l} = b$ holds). Then following happens:\n\n- The runner starts at city $a$.\n- The runner runs from city $a$ to $b$, following the shortest path from city $a$ to city $b$.\n- When the runner arrives at city $b$, he turns his direction immediately (it takes no time), and runs towards city $a$, following the shortest path from city $b$ to city $a$.\n- When the runner arrives at city $a$, he turns his direction immediately (it takes no time), and runs towards city $b$, following the shortest path from city $a$ to city $b$.\n- Repeat step 3 and step 4 forever.\n\nIn short, the course of the runner can be denoted as: $p_{1}\\rightarrow p_{2}\\rightarrow\\cdot\\cdot\\cdot\\cdot\\cdot\\rightarrow p_{l-1}\\rightarrow p_{l}\\rightarrow p_{l-1}\\rightarrow p_{l-2}\\rightarrow\\cdot\\cdot\\cdot\\cdot\\rightarrow p_{2}\\rightarrow p_{1}$ $\\rightarrow p_{2}\\rightarrow\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\rightarrow p_{l-1}\\rightarrow p_{l}\\rightarrow p_{l-1}\\rightarrow p_{l-2}\\rightarrow\\cdot\\cdot\\cdot\\cdot\\rightarrow p_{2}\\rightarrow p_{1}\\rightarrow\\cdot\\cdot\\cdot\\cdot\\cdot.$\n\nTwo runners JH and JY decided to run \"extremely\" in order to celebrate the New Year. JH has chosen two cities $u$ and $v$, and JY has chosen two cities $x$ and $y$. They decided to start running at the same moment, and run until they meet at the same city for the first time. Meeting on a road doesn't matter for them. Before running, they want to know the amount of time they will run.\n\nIt is too hard for JH and JY to calculate this, so they ask you for help.",
    "tutorial": "Before starting the editorial, I'd like to give a big applause to Marcin_smu, who solved the problem for the first time! Warning: The editorial is very long and has many mistakes. There are lots of lots of mistakes.. Keep calm, and please tell me by comments, if you discovered any errors. This problem can be solved by an online algorithm. Let's focus on a single query $(u, v, x, y)$. This means that JH runs between $u$ and $v$, and JY runs between $x$ and $y$. Just like when we solve many problems with undirected trees, let vertex 1 be the root of the tree. Also, we will assume that they won't stop after when they meet, but they will continue running, in order to explain easily. Some definitions: Path $(a, b)$: the shortest path between vertex $a$ and vertex $b$. $d(a, b)$: the length of Path $(a, b)$. $LCA(a, b)$: the lowest common ancestor of vertex $a$ and vertex $b$. If there is no common vertex between Path $(u, v)$ and Path $(x, y)$, the answer will be obviously $- 1$. So, let's find the common vertices first. Because the path between two vertices is always unique, the common vertices also form a path. So, I'll denote the path of the common vertices as Path $(c_{1}, c_{2})$. $c_{1}$ and $c_{2}$ may be equal to: $u$, $v$, $x$, $y$, and even each other. The possible endpoints are $P_{1} = LCA(u, v)$, $P_{2} = LCA(x, y)$, $P_{3} = LCA(u, x)$, $P_{4} = LCA(u, y)$, $P_{5} = LCA(v, x)$, and $P_{6} = LCA(v, y)$. Figure out by drawing some examples. (some of you might think it's obvious :D) See the pictures above, and make your own criteria to check whether the two paths intersects :D A small hint. Let's assume that we already know, that a vertex $a$ lies on path $(x, y)$. If $a$ lies on path $(u, v)$, $a$ is a common vertex of two paths. What if $a$ is guaranteed to be an end point of the common path? Let's denote JH's running course is: $\\dot{\\boldsymbol{u}}=\\rightarrow\\ C_{1}--\\sum{\\boldsymbol{C_{2}}}-\\dots\\ \\nabla$. Then, there are two possible courses for JY: $\\displaystyle{\\mathcal{L}}\\,=\\,\\sim\\,C_{1}\\,-\\,-\\sim\\,C_{2}\\,-\\,-\\,\\sim\\,y$ and $\\textstyle y-\\to\\,C_{1}\\ -\\to\\,C_{2}\\ -\\to\\,X\\,$). $f_{JH}$ : the time needed to run the course $u=\\sim\\ u--\\sim\\ u$. $f_{JY}$ : the time needed to run the course $\\textstyle x\\ -\\lnot\\ 9\\ U-\\lnot\\ 9\\ X$. $t_{1}$ : the first time when JH passes vertex $c_{1}$, moving towards $c_{2}$. $t_{2}$ : the first time when JH passes vertex $c_{2}$, moving towards $c_{1}$. $t_{3}$ : the first time when JY passes vertex $c_{1}$, moving towards $c_{2}$. $t_{4}$ : the first time when JY passes vertex $c_{2}$, moving towards $c_{1}$. Obviously, they must meet at vertex $c_{1}$ or vertex $c_{2}$ for the first time. Without loss of generality, let's assume that they meet at vertex $c_{1}$. In this case, both of them is moving towards vertex $c_{2}$. (You can use the method similarly for $c_{2}$) Let's assume that JH and JY meets at time $T$. Because the movements of both runners are periodic, $T$ must satisfy the conditions below: $T\\equiv t_{1}(\\mathrm{mod}f_{J H})$ $T\\equiv t_{3}({\\mathrm{mod}}f_{J Y})$ Among possible $T$-s, we have to calculate the smallest value. How should we do? From the first condition, we can let $T = f_{JH}  \\times  p + t_{1}$, where $p$ is a non-negative integer. With this, we can write the second condition as: $f_{J H}\\times p+t_{1}\\equiv t_{3}(\\mathrm{mod}f_{J Y})$. In conclusion, we have to find the smallest $p$ which satisfies the condition $f_{J H}\\times p\\equiv t_{3}-t_{1}(\\mathrm{mod}f_{J Y})$ Using the Extended Euclidean algorithm is enough to calculate the minimum $p$. With $p$, we can easily calculate the minimum $T$, which is the first time they meet. If there is no such $p$, they doesn't meet forever, so the answer is $- 1$. In this case, they will meet at a vertex lying on Path $(c_{1}, c_{2})$. Without loss of generality, let's assume that JH is going from $c_{1}$ to $c_{2}$, and JY is going from $c_{2}$ to $c_{1}$. I'll assume that JH and JY meets at time $T$. [1] Let's see how JH moves: For all non-negative integer $p$, At time $f_{JH}  \\times  p + t_{1}$, he is at vertex $c_{1}$, moving towards $c_{2}$. At time $f_{JH}  \\times  p + t_{1} + d(c_{1}, c_{2})$, he is at vertex $c_{2}$. Therefore, when $f_{JH}  \\times  p + t_{1}  \\le $ (current time) $ \\le  f_{JH}  \\times  p + t_{1} + d(c_{1}, c_{2})$, JH is on Path $(c_{1}, c_{2})$. So, $T$ must satisfy the condition: $f_{JH}  \\times  p + t_{1}  \\le  T  \\le  f_{JH}  \\times  p + t_{1} + d(c_{1}, c_{2})$ [2] Let's see how JY moves: Similar to JH, for all non-negative integer $q$, At time $f_{JY}  \\times  q + t_{4}$, he is at vertex $c_{2}$, moving towards $c_{1}$. At time $f_{JY}  \\times  q + t_{4} + d(c_{2}, c_{1})$, he is at vertex $c_{1}$. Therefore, when $f_{JY}  \\times  q + t_{4}  \\le $ (current time) $ \\le  f_{JY}  \\times  q + t_{4} + d(c_{2}, c_{1})$, JY is on Path $(c_{2}, c_{1})$. So, $T$ must satisfy the condition: $f_{JY}  \\times  q + t_{4}  \\le  T  \\le  f_{JY}  \\times  q + t_{4} + d(c_{1}, c_{2})$ [3] These two conditions are not enough, because in this case, they can meet on an edge, but they cannot meet on a vertex. We'd like to know when do they meet on a vertex, like the picture below. As you see from the picture above, in this case, the condition $d(c_{1}, a) + d(a, c_{2}) = d(c_{1}, c_{2})$ holds. If this picture was taken at time $s$, this condition can be written as: ${s - (f_{JH}  \\times  p + t_{1})} + {s - (f_{JY}  \\times  q + t_{4})} = d(c_{1}, c_{2})$ $2s - (f_{JH}  \\times  p + f_{JY}  \\times  q) - (t_{1} + t_{4}) = d(c_{1}, c_{2})$ $s = {d(c_{1}, c_{2}) + (f_{JH}  \\times  p + f_{JY}  \\times  q) + (t_{1} + t_{4})} / 2$ Because JH and JY both travel their path back and forth, $f_{JH}$ and $f_{JY}$ are all even. Therefore, in order to make $s$ an integer, $d(c_{1}, c_{2}) + t_{1} + t_{4}$ must be even. This can be written as $d(c_{1},c_{2})+t_{1}+t_{4}\\equiv0(\\mathrm{mod{2}})$ [4] Merging [1], [2] and [3], we can conclude that if these two conditions holds, $t_{1}-t_{4}\\equiv d(c_{1},c_{2})(\\mathrm{mod}2)$ $max{f_{JH}  \\times  p + t_{1}, f_{JY}  \\times  q + t_{4}}  \\le  min{f_{JH}  \\times  p + t_{1} + d(c_{1}, c_{2}), f_{JY}  \\times  p + t_{4} + d(c_{1}, c_{2})}$ JH and JY meets on a certain vertex lying on path $(c_{1}, c_{2})$. The first condition can be easily checked, so let's focus on the second condition. The second condition holds if and only if: $f_{JY}  \\times  q + t_{4} - t_{1} - d  \\le  f_{JH}  \\times  p  \\le  f_{JY}  \\times  q + t_{4} - t_{1} + d$ You can check this by changing \"$f_{JH}  \\times  p$\" to the lower bound and the upper bound of the inequality. Therefore, the problem is to find the smallest $p$ which satisfies the condition above. Let's define a function $g(M, D, L, R)$, where $M, D, L, R$ are all non-negative integers. The function returns the smallest non-negative integer $m$ which satisfies $L\\leq D\\cdot m\\leq R(\\mathrm{mod}M)$. This function can be implemented as follows. If $L = 0$, $g(M, D, L, R) = 0$. (because $L = 0  \\le  D \\cdot 0$) If $\\left|\\frac{L-1}{\\operatorname*{gcd(M,D)}}\\right|\\ge\\left|\\frac{R}{\\operatorname*{gcd(M,D)}}\\right|$, it is \"obvious\" that there is no solution. If $2D > M$, $g(M, D, L, R) = g(M, M - D, M - R, M - L)$. If there exists an non-negative integer $m$ which satisfies $L  \\le  D \\cdot m  \\le  R$ (without modular condition), $g(M, D, L, R) = m$. Obviously, we should take the smallest $m$. Otherwise, there exists an integer $m$ which satisfies $D \\cdot m < L  \\le  R < D \\cdot (m + 1)$. We should use this fact.. If $L\\leq D\\cdot m\\leq R(\\mathrm{mod}M)$ holds, there exists an non-negative integer $k$ which satisfies $L + Mk  \\le  D \\cdot m  \\le  R + Mk$. Let's write down.. $D \\cdot m - R  \\le  M \\cdot k  \\le  D \\cdot m - L$ $- R  \\le  M \\cdot k - D \\cdot m  \\le  - L$ $L  \\le  D \\cdot m - M \\cdot k  \\le  R$Because $L+M\\cdot k\\leq D\\cdot m\\leq R+M\\cdot k(\\operatorname{mod}M)$, we can write the inequality as $L\\,\\mathrm{mod}\\,D\\leq(-M\\cdot k)\\,\\mathrm{mod}\\,D\\leq R\\,\\mathrm{mod}\\,D(\\mathrm{mod}\\,D)$ Therefore the minimum $k$ among all possible solutions is equal to $q(D,-M\\mathrm{~mod~}D,L\\mathrm{~mod~}D,R\\mathrm{~mod~}D)$. We can easily calculate the smallest $p$ using $k$. $D \\cdot m - R  \\le  M \\cdot k  \\le  D \\cdot m - L$ $- R  \\le  M \\cdot k - D \\cdot m  \\le  - L$ $L  \\le  D \\cdot m - M \\cdot k  \\le  R$ $L\\,\\mathrm{mod}\\,D\\leq(-M\\cdot k)\\,\\mathrm{mod}\\,D\\leq R\\,\\mathrm{mod}\\,D(\\mathrm{mod}\\,D)$ Then, what is the time complexity of calculating $g(M, D, L, R)$? Because $2D  \\le  M$ (the $2D > M$ case is handled during step 3), the problem size becomes half, so it can be executed in $O(\\log_{2}M)$. For each query, we have to consider both Case 1) and Case 2), with all possible directions. Both cases can be handled in $O(\\log_{2}n)$, so the time complexity per query is $O(\\log_{2}n)$, and it has really huge constant. Time: $O((n+q)\\log n)$ Memory: $O(n\\log n)$",
    "code": "#include<stdio.h>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n \n#define N_ 200010\n#define INF 99999999999999999LL\n \nvector<int>E[N_];\n \nint n, Q;\nint Dep[N_];\nint par[18][N_];\n \nvoid DFS(int node, int dep, int pp){\n\tint i, x;\n\tDep[node] = dep;\n\tpar[0][node] = pp;\n\tfor (i = 0; i < E[node].size(); i++){\n\t\tx = E[node][i];\n\t\tif (x != pp)DFS(x, dep + 1, node);\n\t}\n}\n \nvoid make_List(){\n\tint i, j;\n\tfor (i = 0; i < 17; i++){\n\t\tfor (j = 1; j <= n; j++)par[i + 1][j] = par[i][par[i][j]];\n\t}\n}\n \nint LCA(int u, int v){\n\tif (Dep[u] < Dep[v])return LCA(v, u);\n\tint d = Dep[u] - Dep[v], i = 0;\n\twhile (d){\n\t\tif (d & 1) u = par[i][u];\n\t\td >>= 1; i++;\n\t}\n\tfor (i = 17; i >= 0; i--){\n\t\tif (par[i][u] != par[i][v])u = par[i][u], v = par[i][v];\n\t}\n\tif (u != v)u = par[0][u];\n\treturn u;\n}\n \nint Lower(int a, int b){ // a�� b�� ���� ����?\n\tif (Dep[a] < Dep[b])return b;\n\treturn a;\n}\n \nint dist(int u, int v){ // Ʈ������ u�� v�� �Ÿ�\n\tint L = LCA(u, v);\n\treturn Dep[u] + Dep[v] - 2 * Dep[L];\n}\n \nint gcd(int a, int b){\n\treturn b ? gcd(b, a%b) : a;\n}\n \nlong long First(long long M, long long D, long long g){//Dx = g(mod M)�� �ּ��� �� �ƴ� ���� x�� ���ΰ�?\n\tif (g == 0)return 0;\n\tlong long T = First(D, M%D, g%D);\n\tT = (g - T*M) / D;\n\tif (T < 0){\n\t\tT += (-T) / M*M;\n\t\tT += M;\n\t}\n\treturn T % M;\n}\n \nlong long SameDir(int T1, int d1, int T2, int d2, int L){ //���� �������� ������,  T1 * x = d2 - d1 (mod T2) �� �ּ� x?\n\tint g = gcd(T1, T2), M = d2 - d1;\n\tlong long TT = T1;\n\tif (M < 0) M = T2 + M;\n\tif (M % g != 0)return INF;\n\tT1 /= g, M /= g, T2 /= g;\n\treturn First(T2, T1, M) * TT + d1;\n}\n \nint Gap(int M, int D, int L, int R){// L <= Dx <= R(mod M)�� �Ǵ� �ּ��� �� �ƴ� ���� x�� ���ΰ�?  O(log M)�� ����غ���.\n\tD %= M;\n\tif (D * 2 > M){\n\t\treturn Gap(M, M - D, M - R, M - L);\n\t}\n\tint t = L / D, rr = M%D, q = M / D, o;\n\tlong long a, b;\n\tif (L == t * D)return t;\n\tif (t * D + D <= R)return t + 1;\n\ta = Gap(D, D - rr, L%D, R%D);\n\ta = (a * M - 1) / D + 1;\n\tb = a * D % M;\n\ta += (R - b) / D;\n\treturn a;\n}\n \nlong long Do(int M, int D, int L, int R){// L <= Dx <= R(mod M)�� �Ǵ� �ּ��� �� �ƴ� ���� x�� ���ΰ�?�� �غ� �ܰ�\n\tint Res = INF;\n\tif (L == 0){\n\t\tRes = M / gcd(M, D);\n\t\tL = 1;\n\t}\n\tif ((L - 1) / gcd(M, D) >= R / gcd(M, D)){\n\t\treturn INF;\n\t}\n\treturn min(Res, Gap(M, D, L, R));\n}\n \nlong long DiffDir(int T1, int d1, int T2, int d2, int L){ // �ݴ� �������� ������,  d2 - d1 - L <= T1 * x <= d2 - d1 + L ( mod T2)�� �ּ� x?\n\tint be = d2 - d1 - L, ed = d2 - d1 + L;\n\tlong long P;\n\tif (be < 0) be += (-be) / T2 * T2;\n\tif (ed < 0)ed += (-ed) / T2*T2;\n\tbe = (be + T2) % T2, ed = (ed + T2) % T2;\n\tif (be & 1)return INF;\n\tif (T2 == L * 2){\n\t\treturn d1 + ed / 2;\n\t}\n\tif (be > ed || be == 0)return d1 + ed / 2;\n\tP = Do(T2, T1, be, ed);\n\tif (P == INF)return INF;\n\treturn T1*P + d1 + L - (P * T1 % T2 - be) / 2;\n}\n \nlong long Query(int u, int v, int x, int y){\n\tint P1 = LCA(u, v), P2 = LCA(x, y), P3 = LCA(u, x), P4 = LCA(u, y), P5 = LCA(v, x), P6 = LCA(v, y);\n\tint pp, a, b, d1, d2, d3, d4, d5, d6, d;\n\tpp = Lower(P1, P2);\n\ta = Lower(P3, P4);\n\tb = Lower(P5, P6);\n\tif (Dep[a] < Dep[pp] && Dep[b] < Dep[pp])return -1;\n\tif (Dep[a] < Dep[pp]) a = pp;\n\telse if (Dep[b] < Dep[pp]) b = pp;\n\td1 = dist(u, v), d4 = dist(x, y);\n\td2 = dist(u, a), d3 = dist(u, b);\n\td5 = dist(x, a), d6 = dist(x, b);\n\td = dist(a, b);\n\tif (d2 <= d3) d3 = d1 * 2 - d3;\n\telse d2 = d1 * 2 - d2;\n\tif (d5 <= d6) d6 = d4 * 2 - d6;\n\telse d5 = d4 * 2 - d5;\n\tlong long Res = INF;\n\t//d1 : u-v �Ÿ�, d2 : x-y �Ÿ�\n\t//������ : a-b\n\t//d2, d3, d5, d6 : (u,v) - (a,b) �Ÿ�\n\tRes = min(SameDir(d1 * 2, d2, d4 * 2, d5, d), Res);\n\tRes = min(SameDir(d1 * 2, d3, d4 * 2, d6, d), Res);\n\tRes = min(DiffDir(d1 * 2, d2, d4 * 2, d6, d), Res);\n\tRes = min(DiffDir(d1 * 2, d3, d4 * 2, d5, d), Res);\n\tif (Res == INF)return -1;\n\treturn Res;\n}\n \nvoid Output(){\n\tint u, v, x, y, T;\n\tscanf(\"%d\", &Q);\n\twhile (Q--){\n\t\tscanf(\"%d%d%d%d\", &u, &v, &x, &y);\n\t\tprintf(\"%lld\\n\", Query(u, v, x, y));\n\t}\n}\n \nvoid input(){\n\tint i, a, b;\n\tscanf(\"%d\", &n);\n\tfor (i = 1; i < n; i++){\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tE[a].push_back(b);\n\t\tE[b].push_back(a);\n\t}\n}\n \nint main()\n{\n\tinput();\n\tDFS(1, 0, 0);\n\tmake_List();\n\tOutput();\n}",
    "tags": [
      "number theory",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "501",
    "index": "A",
    "title": "Contest",
    "statement": "Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs $a$ points and Vasya solved the problem that costs $b$ points. Besides, Misha submitted the problem $c$ minutes after the contest started and Vasya submitted the problem $d$ minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs $p$ points $t$ minutes after the contest started, you get $\\Pi\\mathrm{d}\\lambda\\chi\\left({\\frac{3p}{10}},p-{\\frac{p}{250}}\\chi\\ d\\right)$ points.\n\nMisha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth.",
    "tutorial": "In this problem one need to determine the number of points for both guys and find out who got more points. Time complexity: $O(1)$.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "501",
    "index": "B",
    "title": "Misha and Changing Handles",
    "statement": "Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.\n\nMisha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.",
    "tutorial": "The problem can be formulated as follows: The directed graph is given, its vertices correspond to users' handles and edges - to requests. It consists of a number of chains, so every vertex ingoing and outgoing degree doesn't exceed one. One need to find number of chains and first and last vertices of every chain. The arcs of this graph can be stored in dictionary(one can use std::map\\unoredered_map in C++ and TreeMap\\HashMap in Java) with head of the arc as the key and the tail as the value. Each zero ingoing degree vertex corresponds to unique user as well as first vertex of some chain. We should iterate from such vertices through the arcs while it's possible. Thus we find relation between first and last vertices in the chain as well as relation between the original and the new handle of some user. Time complexity: $O(q\\log q\\times l e n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define clr(x) memset((x), 0, sizeof(x))\n#define all(x) (x).begin(), (x).end()\n#define pb push_back\n#define mp make_pair\n#define For(i, st, en) for(int i=(st); i<=(int)(en); i++)\n#define Ford(i, st, en) for(int i=(st); i>=(int)(en); i--)\n#define forn(i, n) for(int i=0; i<(int)(n); i++)\n#define ford(i, n) for(int i=(n)-1; i>=0; i--)\n#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)\n#define in(x) int (x); input((x));\n#define x first\n#define y second\n#define less(a,b) ((a) < (b) - EPS)\n#define more(a,b) ((a) > (b) + EPS)\n#define eq(a,b) (fabs((a) - (b)) < EPS)\n#define remax(a, b) ((a) = (b) > (a) ? (b) : (a))\n#define remin(a, b) ((a) = (b) < (a) ? (b) : (a))\n\nusing namespace std;\n\ntemplate <typename T>\nT gcd(T a, T b) {\n    while (b > 0) {\n        a %= b;\n        swap(a, b);\n    }\n    return a;\n}\n\ntypedef long double ld; typedef unsigned int uint; template <class _T> inline _T sqr(const _T& x) {return x * x;} template <class _T> inline string tostr(const _T& a) {ostringstream os(\"\"); os << a; return os.str();} const ld PI = 3.1415926535897932384626433832795L; const double EPS = 1e-9; char TEMPORARY_CHAR;\n\ntypedef long long ll; typedef unsigned long long ull; typedef set < int > SI; typedef vector < int > VI; typedef vector < vector < int > > VVI; typedef map < string, int > MSI; typedef pair < int, int > PII; const int INF = 1e9; inline void input(int &a) {a = 0; while (((TEMPORARY_CHAR = getchar()) > '9' || TEMPORARY_CHAR < '0') && (TEMPORARY_CHAR != '-')){} char neg = 0; if (TEMPORARY_CHAR == '-') {neg = 1; TEMPORARY_CHAR = getchar();} while (TEMPORARY_CHAR <= '9' && TEMPORARY_CHAR >= '0') {a = 10 * a + TEMPORARY_CHAR - '0'; TEMPORARY_CHAR = getchar();} if (neg) a = -a;} inline void out(long long a) {if (!a) putchar('0'); if (a < 0) {putchar('-'); a = -a;} char s[20]; int i; for(i = 0; a; ++i) {s[i] = '0' + a % 10; a /= 10;} ford(j, i) putchar(s[j]);} inline int nxt() {in(ret); return ret;}\n\nint main() {\n#ifdef LOCAL\n    freopen(\"input.txt\", \"r\", stdin);\n#else\n\n#endif\n    ios_base::sync_with_stdio(false);\n\n    int q;\n    cin >> q;\n\n    map <string, string> edges;\n\n    set <string> nonBegin;\n\n    for (int i = 0; i < q; ++i) {\n        string OLD, NEW;\n        cin >> OLD >> NEW;\n        edges[OLD] = NEW;\n        nonBegin.insert(NEW);\n    }\n    vector <pair <string, string> > ans;\n\n    fori(p,edges) {\n        if (nonBegin.count(p->first)) {\n            continue;\n        }\n        string cur = p->first;\n\n        while (edges.count(cur)) {\n            cur = edges[cur];\n        }\n\n        ans.push_back(make_pair(p->first, cur));\n    }\n\n    cout << ans.size() << endl;\n\n    fori(p, ans) {\n        cout << p->first << \" \" << p->second << endl;\n    }\n\n#ifdef LOCAL\n    cerr << \"Time elapsed: \" << (double)clock() / CLOCKS_PER_SEC * 1000 << \" ms.\\n\";\n#endif // LOCAL\n    return 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "501",
    "index": "C",
    "title": "Misha and Forest",
    "statement": "Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of $n$ vertices. For each vertex $v$ from $0$ to $n - 1$ he wrote down two integers, $degree_{v}$ and $s_{v}$, were the first integer is the number of vertices adjacent to vertex $v$, and the second integer is the XOR sum of the numbers of vertices adjacent to $v$ (if there were no adjacent vertices, he wrote down $0$).\n\nNext day Misha couldn't remember what graph he initially had. Misha has values $degree_{v}$ and $s_{v}$ left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.",
    "tutorial": "Note that every non-empty forest has a leaf(vertex of degree $1$). Let's remove edges one by one and maintain actual values $(degree_{v}, s_{v})$ as long as graph is not empty. To do so, we can maintain the queue(or stack) of the leaves. On every iteration we dequeue vertex $v$ and remove edge $(v, s_{v})$ and update values for vertex $s_{v}$: $degree_{sv}$ -= $1$ and $s_{sv}$ ^= $v$. If degree of vertex $s_{v}$ becomes equal to $1$, we enqueue it. When dequeued vertex has zero degree, just ignore it because we have already removed all edges of corresponding tree. Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n    int degree[n], xorsum[n];\n    queue <int> Q;\n    int used = 0;\n    for(int i = 0; i < n; ++i)\n    {\n    \tcin >> degree[i] >> xorsum[i];\n    \tif (degree[i] == 1)\n    \t\tQ.push(i);\n    \tif (degree[i] == 0)\n    \t{\n    \t\tif (xorsum[i] != 0)\n    \t\t\tassert(false);\n    \t\tused++;\n    \t}\n    }\n    vector < pair<int, int>  > ans;\n    while(!Q.empty())\n    {\n    \tint from = Q.front();\n    \tQ.pop();\n    \tused++;\n    \tif (degree[from] == 0)\n    \t{\n    \t\tif (xorsum[from] != 0)\n    \t\t\tassert(false);\n    \t\tcontinue;\n    \t}\n    \tdegree[from]--;\n    \tint to = xorsum[from];\n    \txorsum[from] = 0;\n    \tif (to >= n)\n    \t\tassert(false);\n    \tans.push_back(make_pair(from, to));\n    \txorsum[to] ^= from;\n    \tif (degree[to] == 0)\n    \t\tassert(false);\n    \tdegree[to]--;\n    \tif (degree[to] == 1)\n    \t\tQ.push(to);\n    }\n    if (used != n)\n    \tassert(false);\n    cout << ans.size() << endl;\n    for(size_t i = 0; i < ans.size(); ++i)\n    \tcout << ans[i].first << \" \" << ans[i].second << endl;\n\treturn 0;\n\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "501",
    "index": "D",
    "title": "Misha and Permutations Summation",
    "statement": "Let's define the sum of two permutations $p$ and $q$ of numbers $0, 1, ..., (n - 1)$ as permutation $P e r m((O r d(p)+O r d(q))\\bmod{n!})$, where $Perm(x)$ is the $x$-th lexicographically permutation of numbers $0, 1, ..., (n - 1)$ (counting from zero), and $Ord(p)$ is the number of permutation $p$ in the lexicographical order.\n\nFor example, $Perm(0) = (0, 1, ..., n - 2, n - 1)$, $Perm(n! - 1) = (n - 1, n - 2, ..., 1, 0)$\n\nMisha has two permutations, $p$ and $q$. Your task is to find their sum.\n\nPermutation $a = (a_{0}, a_{1}, ..., a_{n - 1})$ is called to be lexicographically smaller than permutation $b = (b_{0}, b_{1}, ..., b_{n - 1})$, if for some $k$ following conditions hold: $a_{0} = b_{0}, a_{1} = b_{1}, ..., a_{k - 1} = b_{k - 1}, a_{k} < b_{k}$.",
    "tutorial": "To solve the problem, one need to be able to find the index of given permutation in lexicographical order and permutation by its index. We will store indices in factorial number system. Thus number $x$ is represented as $\\sum_{k=1}^{n}d_{k}\\times k!$. You can find the rules of the transform here. To make the transform, you may need to use data structures such as binary search tree or binary indexed tree (for maintaining queries of finding $k$-th number in the set and finding the amount of numbers less than given one). So, one need to get indices of the permutations, to sum them modulo $n!$ and make inverse transform. You can read any accepted solution for better understanding. Time complexity: $O(n\\log n)$ or $O(n\\log^{2}n)$.",
    "tags": [
      "data structures"
    ],
    "rating": 2000
  },
  {
    "contest_id": "501",
    "index": "E",
    "title": "Misha and Palindrome Degree",
    "statement": "Misha has an array of $n$ integers indexed by integers from $1$ to $n$. Let's define palindrome degree of array $a$ as the number of such index pairs $(l, r)(1 ≤ l ≤ r ≤ n)$, that the elements from the $l$-th to the $r$-th one inclusive can be rearranged in such a way that the \\textbf{whole} array will be a palindrome. In other words, pair $(l, r)$ should meet the condition that after some rearranging of numbers on positions from $l$ to $r$, inclusive (it is allowed not to rearrange the numbers at all), for any $1 ≤ i ≤ n$ following condition holds: $a[i] = a[n - i + 1]$.\n\nYour task is to find the palindrome degree of Misha's array.",
    "tutorial": "Note that if the amount of elements, which number of occurrences is odd, is greater than one, the answer is zero. On the other hand, if array is the palindrome, answer is $\\textstyle{\\frac{n(n+1)}{2}}$. Let's cut equal elements from the end and the beginning of array while it is possible. Let's call remaining array as $b$ and its length as $m$. We are interested in segments $[l, r]$ which cover some prefix or suffix of $b$. We need to find the minimum length of such prefix and suffix. Prefix and suffix can overlap the middle of $b$ and these cases are needed to maintain. To find minimum length you can use binary search or simply iterating over array and storing the amount of every element to the left and right from the current index. Let's call minimum length of prefix as $pref$ and as $suf$ of suffix. So $a n s w e r=(\\frac{n-m}{2}+1)\\times(\\frac{n-m}{2}+2m+1-p r e f-s u f)$. Time complexity: $O(n)$ or $O(n\\log n)$.",
    "tags": [
      "binary search",
      "combinatorics",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "504",
    "index": "D",
    "title": "Misha and XOR",
    "statement": "After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number $x$ to the basket, Misha should answer the question: is it possible to choose one or multiple numbers that already are in the basket, such that their XOR sum equals $x$?\n\nIf the answer is positive, you also need to give the indexes of these numbers. If there are multiple options of choosing numbers, you are allowed to choose any correct option. After Misha's answer the robot puts the number to the basket.\n\nInitially the basket is empty. Each integer you put in the basket takes some number. The first integer you put into the basket take number $0$, the second integer takes number $1$ and so on.\n\nMisha needs to clean up the place as soon as possible but unfortunately, he isn't that good at mathematics. He asks you to help him.",
    "tutorial": "Firstly, we convert each number into a binary system: it can be done in $O(MAXBITS^{2})$, where $MAXBITS  \\le  2000$ with rather small constant(we store number in system with big radix). To solve the problem we need to modify Gauss elimination algorithm. For each row we should store set of row's indices which we already XORed this row to get row echelon form (we can store it in bitset), also for each bit $i$ we store index $p[i]$ of row, which lowest set bit is $i$ in row echelon form. Maintaining the query we try to reset bits from lowest to highest using array $p$ and save information, which rows were XORed with current number. If we can reset whole number, the answer is positive and we know indices of answer. We update array $p$, otherwise. Time complexity: $O(m  \\times  MAXBITS  \\times  (MAXBITS + m))$ with small constant due to bit compression.",
    "tags": [
      "bitmasks"
    ],
    "rating": 2700
  },
  {
    "contest_id": "504",
    "index": "E",
    "title": "Misha and LCP on Tree",
    "statement": "Misha has a tree with characters written on the vertices. He can choose two vertices $s$ and $t$ of this tree and write down characters of vertices lying on a path from $s$ to $t$. We'll say that such string corresponds to pair $(s, t)$.\n\nMisha has $m$ queries of type: you are given $4$ vertices $a$, $b$, $c$, $d$; you need to find the largest common prefix of the strings that correspond to pairs $(a, b)$ and $(c, d)$. Your task is to help him.",
    "tutorial": "Let's build heavy-light decomposition of given tree and write all strings corresponding to heavy paths one by one in one string $T$, every path should be written twice: in the direct and reverse order. Maintaining query we can split paths $(a, b)$ and $(c, d)$ into parts, which completely belongs to some heavy paths. There can be at most $O(\\log n)$ such parts. Note that every part corresponds to some substring of $T$. Now we only need to find longest common prefix of two substrings in string $T$. It can be done building suffix array of string $T$ and lcp array. So, we can find longest common prefix of two substring in $O(1)$ constructing rmq sparse table on lcp array. Time complexity: $O(n\\log n+m\\log n)$ P.S. One can uses hashes instead of suffix array. ADD: There is another approach to solve this problem in $O(m\\log n+n\\log n)$ but it's rather slow in practice. We can do binary search on answer and use hashes, but we do it for all queries at one time. The only problem is to find $k$-th vertex on the path, we can do it offline for all queries in $O(n + m)$ time. We run dfs and maintain stack of vertices.",
    "code": "#include <bits/stdc++.h>\n\n#define clr(x) memset((x), 0, sizeof(x))\n#define all(x) (x).begin(), (x).end()\n#define pb push_back\n#define mp make_pair\n#define For(i, st, en) for(int i=(st); i<=(int)(en); i++)\n#define Ford(i, st, en) for(int i=(st); i>=(int)(en); i--)\n#define forn(i, n) for(int i=0; i<(int)(n); i++)\n#define ford(i, n) for(int i=(n)-1; i>=0; i--)\n#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)\n#define in(x) int (x); input((x));\n#define x first\n#define y second\n#define less(a,b) ((a) < (b) - EPS)\n#define more(a,b) ((a) > (b) + EPS)\n#define eq(a,b) (fabs((a) - (b)) < EPS)\n#define remax(a, b) ((a) = (b) > (a) ? (b) : (a))\n#define remin(a, b) ((a) = (b) < (a) ? (b) : (a))\n\nusing namespace std;\n\ntemplate <typename T>\nT gcd(T a, T b) {\n    while (b > 0) {\n        a %= b;\n        swap(a, b);\n    }\n    return a;\n}\n\ntypedef long double ld; typedef unsigned int uint; template <class _T> inline _T sqr(const _T& x) {return x * x;} template <class _T> inline string tostr(const _T& a) {ostringstream os(\"\"); os << a; return os.str();} const ld PI = 3.1415926535897932384626433832795L; const double EPS = 1e-9; char TEMPORARY_CHAR;\n\ntypedef long long ll; typedef unsigned long long ull; typedef set < int > SI; typedef vector < int > VI; typedef vector < vector < int > > VVI; typedef map < string, int > MSI; typedef pair < int, int > PII; const int INF = 1e9; inline void input(int &a) {a = 0; while (((TEMPORARY_CHAR = getchar()) > '9' || TEMPORARY_CHAR < '0') && (TEMPORARY_CHAR != '-')){} char neg = 0; if (TEMPORARY_CHAR == '-') {neg = 1; TEMPORARY_CHAR = getchar();} while (TEMPORARY_CHAR <= '9' && TEMPORARY_CHAR >= '0') {a = 10 * a + TEMPORARY_CHAR - '0'; TEMPORARY_CHAR = getchar();} if (neg) a = -a;} inline void out(long long a) {if (!a) putchar('0'); if (a < 0) {putchar('-'); a = -a;} char s[20]; int i; for(i = 0; a; ++i) {s[i] = '0' + a % 10; a /= 10;} ford(j, i) putchar(s[j]);} inline int nxt() {in(ret); return ret;}\n\nconst int MAXN = 1000000;\nconst int LOG = 1000;\n\nnamespace suf_array {\n    static const int MAXLEN = MAXN * 2;\n    static const int LOG = 20;\n    char s[MAXLEN + 1];\n    int n;\n    int sa[MAXLEN];\n    int lcp[MAXLEN];\n    int logTable[MAXLEN];\n    int rank[MAXLEN];\n    int rmq[LOG + 1][MAXLEN];\n    int order[MAXLEN];\n    int r[MAXLEN];\n    int cnt[MAXLEN];\n    int st[MAXLEN];\n\n    bool cmp(int i, int j)  {\n        return s[i] < s[j];\n    }\n\n    void process()\n    {\n        for (int i = 0; i < n; i++)\n            order[i] = n - 1 - i;\n\n        stable_sort(order, order + n, cmp);\n\n        for (int i = 0; i < n; i++) {\n            sa[i] = order[i];\n            rank[i] = s[i];\n        }\n\n        for (int len = 1; len < n; len <<= 1) {\n            memcpy(r, rank, n * sizeof(int));\n            for (int i = 0; i < n; i++) {\n                rank[sa[i]] = (i > 0 && r[sa[i - 1]] == r[sa[i]] &&\n                        sa[i - 1] + len < n && r[sa[i - 1] + len / 2] == r[sa[i] + len / 2])\n                        ? rank[sa[i - 1]]\n                        : i;\n            }\n            for (int i = 0; i < n; i++)\n                cnt[i] = i;\n\n            memcpy(st, sa, sizeof(int) * n);\n            for (int i = 0; i < n; i++) {\n                int s1 = st[i] - len;\n                if (s1 >= 0)\n                    sa[cnt[rank[s1]]++] = s1;\n            }\n        }\n    }\n\n    void calc_lcp() {\n        for (int i = 0; i < n; i++)\n            rank[sa[i]] = i;\n        for (int i = 0, h = 0; i < n; i++) {\n            if (rank[i] < n - 1) {\n                int j = sa[rank[i] + 1];\n                while(max(i, j) + h < n && s[i + h] == s[j + h])\n                    ++h;\n                lcp[rank[i] + 1] = h;\n                if (h > 0)\n                    --h;\n            }\n        }\n\n        logTable[0] = 0;\n        logTable[1] = 0;\n        for (int i = 2; i < n; i++)\n            logTable[i] = logTable[i >> 1] + 1;\n\n        for (int i = 0; i < n; ++i)\n            rmq[0][i] = lcp[i];\n\n        for (int k = 1; (1 << k) < n; ++k) {\n            for (int i = 0; i + (1 << k) <= n; i++) {\n                int x = rmq[k - 1][i];\n                int y = rmq[k - 1][i + (1 << k - 1)];\n                rmq[k][i] = min(x, y);\n            }\n        }\n    }\n\n    int get_lcp(int l, int r) {\n        l = rank[l];\n        r = rank[r];\n        if (l > r) {\n            swap(l, r);\n        }\n        if (l == r) {\n            return n - sa[l];\n        }\n        ++l;\n        int k = logTable[r - l];\n        int x = rmq[k][l];\n        int y = rmq[k][r - (1 << k) + 1];\n        return min(x, y);\n    }\n};\n\n\nnamespace hld {\n    vector <int> g[MAXN];\n    int sz[MAXN];\n    int p[MAXN];\n\n    int pos_up[MAXN];\n    int pos_down[MAXN];\n\n    int r[MAXN];\n    int root[MAXN];\n    int rt[MAXN];\n\n    int tin[MAXN];\n    int tout[MAXN];\n    int timer = 0;\n\n    int pos[MAXN];\n\n    vector <int> c[MAXN];\n\n    int pathCount = 0;\n\n    void dfs(int v, int par) {\n        p[v] = par;\n        sz[v] = 1;\n        tin[v] = timer++;\n        for (int i = 0; i < (int)g[v].size(); ++i) {\n            int to = g[v][i];\n            if (to == par) {\n                continue;\n            }\n            dfs(to, v);\n            sz[v] += sz[to];\n        }\n        tout[v] = timer++;\n    }\n\n    void decomp(int v, int par, int k) {\n        pos[v] = c[k].size();\n        c[k].push_back(v);\n        root[v] = rt[k];\n        r[v] = k;\n\n        int x = 0, y = -1;\n        for (int i = 0; i < (int)g[v].size(); ++i) {\n            int to = g[v][i];\n            if (to == par)\n                continue;\n            if (sz[to] > x) {\n                x = sz[to];\n                y = to;\n            }\n        }\n        if (y != -1) decomp(y, v, k);\n\n        for (int i = 0; i < (int)g[v].size(); ++i) {\n            int to = g[v][i];\n            if (to != par && to != y) {\n                rt[pathCount] = to;\n                decomp(to, v, pathCount++);\n            }\n        }\n    }\n    void initSA(char * s, char * data) {\n        int len = 0;\n        for (int i = 0; i < pathCount; ++i) {\n            for (int j = 0; j < (int)c[i].size(); ++j) {\n                int v = c[i][j];\n                s[pos_down[v] = len++] = data[v];\n            }\n            for (int j = (int)c[i].size() - 1; j >= 0; --j) {\n                int v = c[i][j];\n                s[pos_up[v] = len++] = data[v];\n            }\n        }\n    }\n\n    inline bool upper(int a, int b) {\n        return tin[a] <= tin[b] && tout[a] >= tout[b];\n    }\n    pair <int, int> up[LOG];\n    pair <int, int> down[LOG];\n\n    int getHeavySegments(int a, int b, pair <int, int> * res) {\n        int sup = 0;\n        int sdown = 0;\n\n        while (!upper(root[a], b)) {\n            up[sup++] = make_pair(pos_up[a], pos_up[root[a]]);\n            a = p[root[a]];\n        }\n        while (!upper(root[b], a)) {\n            down[sdown++] = make_pair(pos_down[root[b]], pos_down[b]);\n            b = p[root[b]];\n        }\n        assert(r[a] == r[b]);\n        if (upper(a, b)) {\n            down[sdown++] = make_pair(pos_down[a], pos_down[b]);\n        } else {\n            up[sup++] = make_pair(pos_up[a], pos_up[b]);\n        }\n        for (int i = 0; i < sup; ++i) {\n            *res++ = up[i];\n        }\n        for (int i = sdown - 1; i >= 0; --i) {\n            *res++ = down[i];\n        }\n        return sup + sdown;\n    }\n}\n\nint main() {\n#ifdef LOCAL\n    freopen(\"input.txt\", \"r\", stdin);\n#else\n\n#endif\n    ios_base::sync_with_stdio(false);\n\n    int n;\n    scanf(\"%d\", &n);\n\n    char data[n + 1];\n    scanf(\"%s\", data);\n\n    for (int i = 0; i + 1 < n; ++i) {\n        int a, b;\n        scanf(\"%d%d\", &a, &b);\n        --a, --b;\n        hld::g[a].push_back(b);\n        hld::g[b].push_back(a);\n    }\n\n    hld::dfs(0, -1);\n    hld::decomp(0, -1, hld::pathCount++);\n    hld::initSA(suf_array::s, data);\n\n    suf_array::n = 2 * n;\n    suf_array::process();\n    suf_array::calc_lcp();\n\n    int m;\n    scanf(\"%d\", &m);\n\n    pair <int, int> segsL[LOG];\n    pair <int, int> segsR[LOG];\n\n    while (m--) {\n        int a, b, c, d;\n        scanf(\"%d%d%d%d\", &a, &b, &c, &d);\n        --a, --b, --c, --d;\n\n        int lsize = hld::getHeavySegments(a, b, segsL);\n\n        int rsize = hld::getHeavySegments(c, d, segsR);\n\n        int i = 0, j = 0;\n       int len = 0;\n       while (i < lsize && j < rsize) {\n           int lcp = suf_array::get_lcp(segsL[i].first, segsR[j].first);\n           lcp = min(lcp, segsL[i].second - segsL[i].first + 1);\n           lcp = min(lcp, segsR[j].second - segsR[j].first + 1);\n           len += lcp;\n           segsL[i].first += lcp;\n           segsR[j].first += lcp;\n\n           bool ok = false;\n\n           if (segsL[i].first > segsL[i].second) {\n               ++i;\n               ok = true;\n           }\n\n           if (segsR[j].first > segsR[j].second) {\n               ++j;\n               ok = true;\n           }\n\n           if (!ok) {\n               break;\n           }\n       }\n        printf(\"%d\\n\", len);\n    }\n\n#ifdef LOCAL\n    cerr << \"Time elapsed: \" << (double)clock() / CLOCKS_PER_SEC * 1000 << \" ms.\\n\";\n#endif // LOCAL\n    return 0;\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "hashing",
      "string suffix structures",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "505",
    "index": "A",
    "title": "Mr. Kitayuta's Gift",
    "statement": "Mr. Kitayuta has kindly given you a string $s$ consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into $s$ to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, \"noon\", \"testset\" and \"a\" are all palindromes, while \"test\" and \"kitayuta\" are not.\n\nYou can choose any lowercase English letter, and insert it to any position of $s$, possibly to the beginning or the end of $s$. You have to insert a letter even if the given string is already a palindrome.\n\nIf it is possible to insert one lowercase English letter into $s$ so that the resulting string will be a palindrome, print the string after the insertion. Otherwise, print \"NA\" (without quotes, case-sensitive). In case there is more than one palindrome that can be obtained, you are allowed to print any of them.",
    "tutorial": "Since the string is short (at most 10 characters), you can simply try every possible way of inserting a letter (\"where\" and \"what\" to insert), and check if the resulting string is a palindrome.",
    "code": "// Enjoy your stay.\n \n#include <bits/stdc++.h>\n \n#define EPS 1e-9\n#define INF 1070000000LL\n#define MOD 1000000007LL\n#define all(x) (x).begin(),(x).end()\n#define fir first\n#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)\n#define ite iterator\n#define mp make_pair\n#define mt make_tuple\n#define rep(i,n) rep2(i,0,n)\n#define rep2(i,m,n) for(int i=m;i<(n);i++)\n#define pb push_back\n#define sec second\n#define sz(x) ((int)(x).size())\n \nusing namespace std;\n \ntypedef istringstream iss;\ntypedef long long ll;\ntypedef pair<ll,ll> pi;\ntypedef stringstream sst;\ntypedef vector<ll> vi;\n \n \n \nint main(){\n\tcin.tie(0);\n\tios_base::sync_with_stdio(0);\n \n\tstring s;\n\tcin >> s;\n\trep(i, sz(s) + 1) rep2(c, 'a', 'z' + 1) {\n\t\tstring t = s.substr(0, i) + string(1, c) + s.substr(i);\n\t\tstring u = t;\n\t\treverse(all(u));\n\t\tif(t == u){\n\t\t\tcout << t << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout << \"NA\" << endl;\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "505",
    "index": "B",
    "title": "Mr. Kitayuta's Colorful Graph",
    "statement": "Mr. Kitayuta has just bought an undirected graph consisting of $n$ vertices and $m$ edges. The vertices of the graph are numbered from 1 to $n$. Each edge, namely edge $i$, has a color $c_{i}$, connecting vertex $a_{i}$ and $b_{i}$.\n\nMr. Kitayuta wants you to process the following $q$ queries.\n\nIn the $i$-th query, he gives you two integers — $u_{i}$ and $v_{i}$.\n\nFind the number of the colors that satisfy the following condition: the edges of that color connect vertex $u_{i}$ and vertex $v_{i}$ directly or indirectly.",
    "tutorial": "Since neither the graph nor the number of queries is too large, for each query you can simply count the number of the \"good\" colors (the colors that satisfies the condition) by checking if each color is \"good\". To do that, you can perform Depth First Search (or Breadth First Search) and verify whether you can reach $v_{i}$ from $u_{i}$ traversing only the edges of that color. If you prefer using Union-Find, it will also do the job.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs"
    ],
    "rating": 1400
  },
  {
    "contest_id": "505",
    "index": "C",
    "title": "Mr. Kitayuta, the Treasure Hunter",
    "statement": "The Shuseki Islands are an archipelago of $30001$ small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from $0$ to $30000$ from the west to the east. These islands are known to contain many treasures. There are $n$ gems in the Shuseki Islands in total, and the $i$-th gem is located on island $p_{i}$.\n\nMr. Kitayuta has just arrived at island $0$. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process:\n\n- First, he will jump from island $0$ to island $d$.\n- After that, he will continue jumping according to the following rule. Let $l$ be the length of the previous jump, that is, if his previous jump was from island $prev$ to island $cur$, let $l = cur - prev$. He will perform a jump of length $l - 1$, $l$ or $l + 1$ to the east. That is, he will jump to island $(cur + l - 1)$, $(cur + l)$ or $(cur + l + 1)$ (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length $0$ when $l = 1$. If there is no valid destination, he will stop jumping.\n\nMr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect.",
    "tutorial": "Below is the explanation from yosupo, translated by me. [From here] Let $m$ be the number of the islands (that is, $30001$). First, let us describe a solution with time and memory complexity of $O(m^{2})$. We will apply Dynamic Programming. let $dp[i][j]$ be the number of the gems that Mr. Kitayuta can collect after he jumps to island $i$, when the length of his previous jump is $j$ (let us assume that he have not collect the gems on island $i$). Then, you can calculate the values of the table $dp$ by the following: $dp[i][j] = 0$, if $i  \\ge  m$ (actually these islands do not exist, but we can suppose that they exist and when Mr. Kitayuta jumps to these islands, he stops jumping) $dp[i][j] =$ (the number of the gems on island $i$) $+ max(dp[i + j][j], dp[i + j + 1][j + 1])$, if $i < m, j = 1$ (he cannot perform a jump of length $0$) $dp[i][j] =$ (the number of the gems on island $i$) $+ max(dp[i + j - 1][j - 1], dp[i + j][j], dp[i + j + 1][j + 1])$, if $i < m, j  \\ge  2$ This solution is unfeasible in terms of both time and memory. However, the following observation makes it an Accepted solution: there are only $491$ values of $j$ that we have to consider, which are $d - 245, d - 244, d - 243, ..., d + 244$ and $d + 245$. Why? First, let us find the upper bound of $j$. Suppose Mr. Kitayuta always performs the \"$l + 1$\" jump ($l$: the length of the previous jump). Then, he will reach the end of the islands before he performs a jump of length $d + 246$, because $d + (d + 1) + (d + 2) + ... + (d + 245)  \\ge  1 + 2 + ... + 245 = 245 \\cdot (245 + 1) / 2 = 30135 > 30000$. Thus, he will never be able to perform a jump of length $d + 246$ or longer. Next, let us consider the lower bound of $j$ in a similar way. If $d  \\le  246$, then obviously he will not be able to perform a jump of length $d - 246$ or shorter, because the length of a jump must be positive. Suppose Mr. Kitayuta always performs the \"$l - 1$\" jump, where $d  \\ge  247$. Then, again he will reach the end of the islands before he performs a jump of length $d - 246$, because $d + (d - 1) + (d - 2) + ... + (d - 245)  \\ge  245 + 244 + ... + 1 = 245 \\cdot (245 + 1) / 2 = 30135 > 30000$. Thus, he will never be able to perform a jump of length $d - 246$ or shorter. Therefore, we have obtained a working solution: similar to the $O(m^{2})$ one, but we will only consider the value of $j$ between $d - 245$ and $d + 245$. The time and memory complexity of this solution will be $O(m^{1.5})$, since the value \"$245$\" is slightly larger than $\\sqrt{2m}$. This solution can be implemented by, for example, using a \"normal\" two dimensional array with a offset like this: dp[i][j - offset]. The time limit is set tight in order to fail most of naive solutions with search using std::map or something, so using hash maps (unordered_map) will be risky although the complexity will be the same as the described solution.",
    "tags": [
      "dfs and similar",
      "dp",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "505",
    "index": "D",
    "title": "Mr. Kitayuta's Technology",
    "statement": "Shuseki Kingdom is the world's leading nation for innovation and technology. There are $n$ cities in the kingdom, numbered from $1$ to $n$.\n\nThanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city $x$ to city $y$ cannot be used to travel from city $y$ to city $x$. The transportation within each city is extremely developed, therefore if a pipe from city $x$ to city $y$ and a pipe from city $y$ to city $z$ are both constructed, people will be able to travel from city $x$ to city $z$ instantly.\n\nMr. Kitayuta is also involved in national politics. He considers that the transportation between the $m$ pairs of city $(a_{i}, b_{i})$ ($1 ≤ i ≤ m$) is important. He is planning to construct teleportation pipes so that for each important pair $(a_{i}, b_{i})$, it will be possible to travel from city $a_{i}$ to city $b_{i}$ by using one or more teleportation pipes (but not necessarily from city $b_{i}$ to city $a_{i}$). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.",
    "tutorial": "Let $G_{1}$ be the directed graph built from the input, and $G_{2}$ be a directed graph that satisfies the given conditions. What we seek is the minimum number of edges in $G_{2}$. Also, we say that two vertices $u$ and $v$ in a directed graph are \"weakly connected\" if we can reach $v$ from $u$ by traversing edges, not considering their directions. If a pair $(u, v)$ is present in the input, then vertices $u$ and $v$ must be weakly connected in $G_{2}$. Therefore, for each weakly connected component (abbreviated to wcc) in $G_{1}$, the vertices in that component must also be in the same wcc in $G_{2}$. We can \"merge\" multiple wccs in $G_{1}$ and create a larger wcc in $G_{2}$, but for now, let us find the minimum number of edges required in $G_{2}$ for each wcc in $G_{1}$ when we do not \"merge\" them. There are two cases to consider: If a wcc in $G_{1}$ does not have cycles, then we can perform topological sort on that wcc, and we can make a \"chain\" (see the image below) using the topological order to satisfy the conditions. We need (the number of the vertices in the wcc) $- 1$ edges, which is the minimum required number since any connected graph with $V$ vertices has at least $V - 1$ edges. If a wcc in $G_{1}$ has cycles, then topological sort cannot be applied. We need at least (the number of the vertices in the wcc) edges this time, since any connected graph with $V$ vertices and $V - 1$ edges is a tree, which does not contain cycles. Actually, this number (the number of the vertices in the wcc) is always achievable by connecting the vertices into a \"ring\" (see the image below), thus it is the minimum required number that we seek. We have found the minimum required number of edges for each wcc in $G_{1}$ when we do not \"merge\" them. Let us show that \"merging\" wccs in $G_{1}$ do not reduce the number of required edges. Suppose we combine $k( > 1)$ wccs $C_{1}, C_{2}, ..., C_{k}$ in $G_{1}$ into one wcc $C$ in $G_{2}$. Again, there are two cases to consider: If none of $C_{1}, C_{2}, ..., C_{k}$ contains cycles, then $C$ will need $|C_{1}| + |C_{2}| + ... + |C_{k}| - 1$ edges. However, if we do not combine them, we will only need $(|C_{1}| - 1) + (|C_{2}| - 1) + ... + (|C_{k}| - 1)$ edges in total, which is fewer. If some of $C_{1}, C_{2}, ..., C_{k}$ contain cycles, then $C$ will need $|C_{1}| + |C_{2}| + ... + |C_{k}|$ edges. However, if we do not combine them, we will need $(|C_{1}| - noCycles(C_{1})) + (|C_{2}| - noCycles(C_{2})) + ... + (|C_{k}| - noCycles(C_{k})$ $ \\le  |C_{1}| + |C_{2}| + ... + |C_{k}|$ edges (here, $noCycles(C_{i})$ is $1$ if $C_{i}$ do not contain cycles, otherwise $0$), thus combining them does not reduce the number of required edges. Thus, we do not need to combine multiple wccs into one wcc in $G_{2}$ in order to obtain the optimal solution. That is, the final answer to the problem is the sum of the minimum required number of edges for each wcc in $G_{1}$, when they are considered separately. As for the implementation, detecting cycles in a directed graph with $10^{5}$ vertices and edges might be a problem if this is your first encounter with it. One possible way is to paste a code that decomposes a graph into strongly connected components. If the size of a strongly connected component is more than one, then that means the component contains cycles.",
    "code": "// Enjoy your stay.\n \n#include <bits/stdc++.h>\n \n#define EPS 1e-9\n#define INF 1070000000LL\n#define MOD 1000000007LL\n#define fir first\n#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)\n#define ite iterator\n#define mp make_pair\n#define mt make_tuple\n#define rep(i,n) rep2(i,0,n)\n#define rep2(i,m,n) for(int i=m;i<(n);i++)\n#define pb push_back\n#define sec second\n#define sz(x) ((int)(x).size())\n \nusing namespace std;\n \ntypedef istringstream iss;\ntypedef long long ll;\ntypedef pair<ll,ll> pi;\ntypedef stringstream sst;\ntypedef vector<ll> vi;\n \nconst int N = 100010;\n \nint n, m;\nvi g[N];\nvi rg[N];\nvi vs;\nbool used[N];\nint cmp[N], cmpsize[N];\n \nvoid add_edge(int from, int to){\n\tg[from].pb(to);\n\trg[to].pb(from);\n}\n \nvoid dfs(int v){\n\tused[v] = 1;\n\trep(i, sz(g[v])){\n\t\tif(!used[g[v][i]]) dfs(g[v][i]);\n\t}\n\tvs.pb(v);\n}\n \nvoid rdfs(int v, int k){\n\tused[v] = 1;\n\tcmp[v] = k;\n\trep(i, sz(rg[v])){\n\t\tif(!used[rg[v][i]]) rdfs(rg[v][i], k);\n\t}\n}\n \nint scc(){\n\tmemset(used, 0, sizeof(used));\n\tvs.clear();\n\trep(v, n){\n\t\tif(!used[v])\n\t\tdfs(v);\n\t}\n\tmemset(used, 0, sizeof(used));\n\tint k = 0;\n\tfor(int i = sz(vs) - 1; i >= 0; i--){\n\t\tif(!used[vs[i]]) rdfs(vs[i], k++);\n\t}\n\treturn k;\n}\n \nint dfs2(int v){\n\tused[v] = 1;\n\tint res = cmpsize[cmp[v]] == 1;\n\trep(i,sz(g[v])) if(!used[g[v][i]]){\n\t\tres &= dfs2(g[v][i]);\n\t}\n\trep(i,sz(rg[v])) if(!used[rg[v][i]]){\n\t\tres &= dfs2(rg[v][i]);\n\t}\n\treturn res;\n}\n \nint main(){\n\tcin.tie(0);\n\tios_base::sync_with_stdio(0);\n\t\n\tcin >> n >> m;\n\trep(i, m){\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tadd_edge(a-1, b-1);\n\t}\n\tscc();\n\tmemset(cmpsize, 0, sizeof(cmpsize));\n\trep(i, n){\n\t\tcmpsize[cmp[i]]++;\n\t}\n\tmemset(used, 0, sizeof(used));\n\tint ans = n;\n\trep(i, n) if(!used[i]){\n\t\tans -= dfs2(i);\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "dfs and similar"
    ],
    "rating": 2200
  },
  {
    "contest_id": "505",
    "index": "E",
    "title": "Mr. Kitayuta vs. Bamboos",
    "statement": "Mr. Kitayuta's garden is planted with $n$ bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the $i$-th bamboo is $h_{i}$ meters, and it grows $a_{i}$ meters at the end of each day.\n\nActually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, but failed because their stems are too hard. Mr. Kitayuta have not given up, however. He has crafted Magical Hammer with his intelligence to drive them into the ground.\n\nHe can use Magical Hammer at most $k$ times during each day, due to his limited Magic Power. Each time he beat a bamboo with Magical Hammer, its height decreases by $p$ meters. If the height would become negative by this change, it will become $0$ meters instead (it does not disappear). In other words, if a bamboo whose height is $h$ meters is beaten with Magical Hammer, its new height will be $max(0, h - p)$ meters. It is possible to beat the same bamboo more than once in a day.\n\nMr. Kitayuta will fight the bamboos for $m$ days, starting today. His purpose is to minimize the height of the tallest bamboo after $m$ days (that is, $m$ iterations of \"Mr. Kitayuta beats the bamboos and then they grow\"). Find the lowest possible height of the tallest bamboo after $m$ days.",
    "tutorial": "Below is the explanation from yosupo, translated by me. [From here] Let us begin by applying Binary Search. The problem becomes: \"is it possible that all the bamboos are at most $X$ meters after $m$ days?\" It is complicated by the fact that the height does not become negative; the excessive decrease will be wasted. We have found two approaches to this problem. Solution 1 Mr. Kitayuta must beat the $i$-th bamboo at least $max(0,  \\lceil (h_{i} + m \\cdot a_{i} - X) / P \\rceil )$ times (let this number $t_{i}$). Actually, it is not necessary for him to beat it more than this number of times. Thus, let us assume that he beat the $i$-th bamboo exactly $t_{i}$ times. Also, for each $j$ ($1  \\le  j  \\le  t_{i}$), find the day $d_{i, j}$ such that, if the $j$-th beat on the $i$-th bamboo is performed before day $d_{i}$, it will be no longer possible to keep the $i$-th bamboo's height after $m$ days at most $X$ (it can be found by doing simple math). If Mr. Kitayuta can beat the bamboos under this constraint, all the bamboos' heights will become $X$ meters or less after $m$ days. Otherwise, some bamboos' heights will exceed $X$ meters. The time complexity of this solution will be $O((n+k m)\\log(h_{m a x}+a_{m a x}\\cdot m))$, if we first calculate only $t_{i}$, then if the sum of $t_{i}$ exceeds $km$, we skip finding $d_{i, j}$ (the answer is \"NO\"). Solution 2 This problem becomes simpler if we simulate Mr. Kitayuta's fight backwards, that is, from day $m$ to day $1$. It looks like this: [Problem'] There are $n$ bamboos. At the moment, the height of the $i$-th bamboo is $X$ meters, and it shrinks $a_{i}$ meters at the beginning of each day. Mr. Kitayuta will play a game. He can use Magic Hammer at most $k$ times per day to increase the height of a bamboo by $p$ meters. If some bamboo's height becomes negative at any moment, he will lose the game immediately. Also, in order for him to win the game, the $i$-th bamboo's height must be at least $h_{i}$ meters after $m$ days. Is victory possible? Below is an illustration of this \"reverse simulation\": This version is simpler because he is increasing the heights instead of decreasing, thus we do not need to take into account the \"excessive decrease beyond $0$ meters\" which will be wasted. Let us consider an optimal strategy. If there exist bamboos whose heights would become negative after day $m$, he should beat the one that is the earliest to make him lose. Otherwise, he can choose any bamboo whose height would be less than $h_{i}$ meters after day $m$. Repeat beating the bamboos following this strategy, and see if he can actually claim victory. The writer's implementation of this solution uses a priority queue, and its time complexity is $O((n+k m)\\lg n\\log(h_{m a x}+a_{m a x}\\cdot m))$.",
    "code": "// Enjoy your stay.\n \n#include <bits/stdc++.h>\n \n#define EPS 1e-9\n#define INF 1070000000LL\n#define MOD 1000000007LL\n#define fir first\n#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)\n#define ite iterator\n#define mp make_pair\n#define mt make_tuple\n#define rep(i,n) rep2(i,0,n)\n#define rep2(i,m,n) for(int i=m;i<(n);i++)\n#define pb push_back\n#define sec second\n#define sz(x) ((int)(x).size())\n \nusing namespace std;\n \ntypedef istringstream iss;\ntypedef long long ll;\ntypedef pair<ll,ll> pi;\ntypedef stringstream sst;\ntypedef vector<ll> vi;\n \nint n, m, k, p;\nll h[100010], a[100010];\nll l[100010];\n \nint main(){\n\tcin.tie(0);\n\tios_base::sync_with_stdio(0);\n \n\tcin >> n >> m >> k >> p;\n\trep(i,n) cin >> h[i] >> a[i];\n\trep(i,n){\n\t\tl[i] = h[i] + a[i] * m;\n\t}\n\tll lo = 0, hi = 2e13;\n\twhile(lo + 1 < hi){\n\t\tll mi = (lo + hi) / 2;\n\t\tbool ok = 1;\n\t\tll total = 0;\n\t\trep(i,n){\n\t\t\ttotal += max(0LL, (l[i] - mi + p - 1) / p);\n\t\t}\n\t\tif(total > m * k){\n\t\t\tok = 0;\n\t\t}else{\n\t\t\tint t[10010] = {};\n\t\t\trep(i,n) if(l[i] > mi){\n\t\t\t\tfor(ll target = (l[i] - mi) % p == 0 ? p : (l[i] - mi) % p; target <= l[i] - mi; target += p){\n\t\t\t\t\tif(target - h[i] <= 0){\n\t\t\t\t\t\tt[0]++;\n\t\t\t\t\t}else if(target - h[i] > a[i] * (m-1)){\n\t\t\t\t\t\tok = 0;\n\t\t\t\t\t\tgoto end;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tt[(target - h[i] + a[i] - 1) / a[i]]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tint rest = 0;\n\t\t\trep(i,m){\n\t\t\t\trest += t[i];\n\t\t\t\trest = max(0, rest - k);\n\t\t\t}\n\t\t\tok = rest == 0;\n\t\t}\n\t\tend:;\n\t\t(ok ? hi : lo) = mi;\n\t}\n\tcout << hi << endl;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "506",
    "index": "D",
    "title": "Mr. Kitayuta's Colorful Graph",
    "statement": "Mr. Kitayuta has just bought an undirected graph with $n$ vertices and $m$ edges. The vertices of the graph are numbered from 1 to $n$. Each edge, namely edge $i$, has a color $c_{i}$, connecting vertex $a_{i}$ and $b_{i}$.\n\nMr. Kitayuta wants you to process the following $q$ queries.\n\nIn the $i$-th query, he gives you two integers - $u_{i}$ and $v_{i}$.\n\nFind the number of the colors that satisfy the following condition: the edges of that color connect vertex $u_{i}$ and vertex $v_{i}$ directly or indirectly.",
    "tutorial": "Below is the explanation from hogloid. [From here] For each color, make a new graph that consists of the edges of the color and vertices connected by the edges. Make UnionFind for each graph, and you can check whether a color connects vertex $A$ and $B$ , using it. For each query, find a vertex which has smaller degree(let this vertex $A$, and the other vertex $B$) For each colors such that a edge of the color connects to $A$, check whether $A$ and $B$ is connected by the color. After answering the query, memorize its tuple - $(A, B, answer)$. If the same query is requested, answer using this information. This will lead to $O(m\\log m{\\sqrt{q}})$ solution. For each query, the complexity is $O(d e c g(A)\\log m)$ (For each color connects $A$, find a vertex of $B$ of the color & check whether they are connected) The queries that require longest computing time are, to ask every pair among ${\\sqrt{q}}$ vertices which have largest degrees. Let the indices of the ${\\sqrt{q}}$ vertices be $1,2,...,k(={\\sqrt{q}})$, and degrees of the ${\\sqrt{q}}$ vertices be $d_{1}, d_{2}, ...d_{k}$. Now, let's fix vertex $B$ as $i$. The total computing time of the queries such that $B$ is vertex $i$ is $O((d_{1}+d_{2}+\\ldots+d_{i-1})\\log m)\\leq$ $O(s u m_{-}o f_{-}d e g r e e s_{-}o f_{-}t h e_{-}\\sqrt{q}_{-}v e r t i c e s\\cdot\\log m)$. Vertex $B$ can vary from $2$ to $k$. Hence, the total complexity is at most $O(\\sqrt{q}\\cdot s u m_{-}o f_{-}d e g r e e s_{-}o f_{-}t h e_{-}\\sqrt{q}_{-}v e r t i c e s\\cdot\\log m)$. This complexity is at most $O({\\sqrt{q}}m\\log m)$. By the way, in C++, using unordered_map, total complexity would be $O(m{\\sqrt{q}})$. [End] There will be many other solutions. I will briefly explain one of them which I think is typical. Let $c_{i}$ be the number of colors of the edges incident to vertex $i$. The sum of all $c_{i}$ does not exceed $2m$ since each edge increases this sum by at most 2. Thus, there will be at most $450$ values of $i$ such that $c_{i}  \\ge  450$ (let $B = 450$). We will call these vertices large, and the remaining ones small. Using $O(m / B \\cdot m) = O(m^{2} / B)$ time and memory, we can precalculate and store the answer for all the possible queries where at least one of $u_{i}$ and $v_{i}$ is large, then we can immediately answer these queries. For the remaining queries, both $u_{i}$ and $v_{i}$ will be small, therefore it is enough to directly count the color that connects vertices $u_{i}$ and $v_{i}$ in $O(B)$ time. The total time required will be $O(m^{2} / B + Bq)$. If we choose $B=m/{\\sqrt{q}}$, we can solve the problem in $O(m^{2}/(m/\\sqrt{q})+q\\cdot m/\\sqrt{q})=O(m\\sqrt{q})$ time.",
    "code": "// Enjoy your stay.\n \n#include <bits/stdc++.h>\n \n#define EPS 1e-9\n#define INF 1070000000LL\n#define MOD 1000000007LL\n#define fir first\n#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)\n#define ite iterator\n#define mp make_pair\n#define mt make_tuple\n#define rep(i,n) rep2(i,0,n)\n#define rep2(i,m,n) for(int i=m;i<(n);i++)\n#define pb push_back\n#define sec second\n#define sz(x) ((int)(x).size())\n \nusing namespace std;\n \ntypedef istringstream iss;\ntypedef long long ll;\ntypedef pair<ll,ll> pi;\ntypedef stringstream sst;\ntypedef vector<ll> vi;\n \nconst int N = 100010;\n \n//\nint par_uf[N],rank_uf[N];\n \nvoid init(int n){\n\tfor(int i = 0; i < n; i++){\n\t\tpar_uf[i] = i;\n\t\trank_uf[i] = 0;\n\t}\n}\nint find(int x){\n\tif(par_uf[x] == x)return x;\n\telse return par_uf[x] = find(par_uf[x]);\n}\nvoid unite(int x, int y){\n\tx=find(x); y=find(y);\n\tif(x == y) return;\n\tif(rank_uf[x] < rank_uf[y]) par_uf[x] = y;\n\telse{\n\t\tpar_uf[y]=x;\n\t\tif(rank_uf[x] == rank_uf[y]) rank_uf[x]++;\n\t}\n}\nbool same(int x, int y){\n\treturn find(x) == find(y);\n}\n//\n \nint n, m, q, qa[N], qb[N];\nvector< pair<int,int> > edge[N];\nvector< vector<int> > comp;\nvector<int> appear[N];\n \nconst int B = 450;\nvector<int> big;\nint bigID[N];\nint table[B+10][N];\n \nint used[N];\nvector<int> temp[N];\n \nint main(){\n\tcin.tie(0);\n\tios_base::sync_with_stdio(0);\n \n\tcin >> n >> m;\n\trep(i, m){\n\t\tint a, b, c;\n\t\tcin >> a >> b >> c;\n\t\ta--; b--; c--;\n\t\tedge[c].pb(mp(a, b));\n\t}\n\tcin >> q;\n\trep(i, q){\n\t\tcin >> qa[i] >> qb[i];\n\t\tqa[i]--; qb[i]--;\n\t}\n \n\tinit(n);\n\trep(c, N){\n\t\trep(i, sz(edge[c])){\n\t\t\tint a = edge[c][i].fir, b = edge[c][i].sec;\n\t\t\tunite(a, b);\n\t\t}\n\t\trep(i, sz(edge[c])){\n\t\t\tint a = edge[c][i].fir, b = edge[c][i].sec;\n\t\t\tif(!used[a]){\n\t\t\t\ttemp[find(a)].pb(a);\n\t\t\t\tused[a] = 1;\n\t\t\t}\n\t\t\tif(!used[b]){\n\t\t\t\ttemp[find(b)].pb(b);\n\t\t\t\tused[b] = 1;\n\t\t\t}\n\t\t}\n\t\trep(i, sz(edge[c])){\n\t\t\tint a = edge[c][i].fir, b = edge[c][i].sec;\n\t\t\tif(sz(temp[a]) > 0){\n\t\t\t\tcomp.pb(temp[a]);\n\t\t\t\ttemp[a].clear();\n\t\t\t}\n\t\t\tif(sz(temp[b]) > 0){\n\t\t\t\tcomp.pb(temp[b]);\n\t\t\t\ttemp[b].clear();\n\t\t\t}\n\t\t\tused[a] = 0;\n\t\t\tused[b] = 0;\n\t\t\tpar_uf[a] = a;\n\t\t\tpar_uf[b] = b;\n\t\t\trank_uf[a] = 0;\n\t\t\trank_uf[b] = 0;\n\t\t}\n\t}\n \n\trep(i, sz(comp)){\n\t\trep(j, sz(comp[i])){\n\t\t\tappear[comp[i][j]].pb(i);\n\t\t}\n\t}\n\trep(i, n){\n\t\tif(sz(appear[i]) > B){\n\t\t\tbigID[i] = sz(big);\n\t\t\tbig.pb(i);\n\t\t}else{\n\t\t\tbigID[i] = -1;\n\t\t}\n\t}\n \n\trep(i, sz(big)){\n\t\tint b = big[i];\n\t\trep(j, sz(appear[b])){\n\t\t\tint c = appear[b][j];\n\t\t\trep(k, sz(comp[c])){\n\t\t\t\ttable[i][comp[c][k]]++;\n\t\t\t}\n\t\t}\n\t}\n \n\trep(_,q){\n\t\tint a = qa[_], b = qb[_];\n\t\tif(bigID[a] == -1){\n\t\t\tswap(a, b);\n\t\t}\n\t\tif(bigID[a] != -1){\n\t\t\tcout << table[bigID[a]][b] << endl;\n\t\t}else{\n\t\t\tint cur1 = 0, cur2 = 0, res = 0;\n\t\t\twhile(cur1 < sz(appear[a]) && cur2 < sz(appear[b])){\n\t\t\t\tif(appear[a][cur1] == appear[b][cur2]){\n\t\t\t\t\tres++;\n\t\t\t\t\tcur1++;\n\t\t\t\t\tcur2++;\n\t\t\t\t}else if(appear[a][cur1] < appear[b][cur2]){\n\t\t\t\t\tcur1++;\n\t\t\t\t}else{\n\t\t\t\t\tcur2++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << res << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "506",
    "index": "E",
    "title": "Mr. Kitayuta's Gift",
    "statement": "Mr. Kitayuta has kindly given you a string $s$ consisting of lowercase English letters. You are asked to insert exactly $n$ lowercase English letters into $s$ to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, \"noon\", \"testset\" and \"a\" are all palindromes, while \"test\" and \"kitayuta\" are not.) You can choose any $n$ lowercase English letters, and insert each of them to any position of $s$, possibly to the beginning or the end of $s$. You have to insert exactly $n$ letters even if it is possible to turn $s$ into a palindrome by inserting less than $n$ letters.\n\nFind the number of the palindromes that can be obtained in this way, modulo $10007$.",
    "tutorial": "First of all, let us note that we are asked to count the resulting palindromes, not the ways to obtain them. For example, if we are to insert \"b\" into \"abba\", there are 5 possible positions, but only 3 strings will be produced (\"babba\", \"abbba\" and \"abbab\"). Rather than trying to count the ways of inserting a letter $n$ times and removing the duplicated results, we should directly count the resulting palindrome. To do that, let us reformulate the problem: [Problem'] Given a string $s$ and an integer $n$, find the number of the palindromes of length $|s| + n$ (let this number be $N$) that contains $s$ as a subsequence (not necessarily contiguous). Consider constructing a palindrome from both ends, and matching it to $s$ from both left and right. For example, let $s =$\"abaac\" and $N = 11$. Let us call the final resulting string $t$. We first decide what letter to use as $t_{1}$ and $t_{11}$ (they must be equal in order for $t$ to be a palindrome). Let us say 'c' is chosen. Now, we have to construct the remaining part of $t$, that is, $t_{2}..t_{10}$, so that $t_{2}..t_{10}$ contains \"abaa\" as a substring (note that the 'c' at the end of $s$ is discarded). Again, we decide what letter to use as $t_{2}$ and $t_{10}$. This time we choose 'a'. Then, we have to construct $t_{3}..t_{9}$, so that it contains \"ba\" as a substring (this time the two 'a's at the both ends of $s$ are discarded). We choose $t_{3} = t_{9} =$'c'. Next, we construct $t_{4}..t_{8}$, so that it contains \"ba\" as a substring (this time $s$ remains unchanged). We choose $t_{4} = t_{8} =$'b'. Then, we construct $t_{5}..t_{7}$, so that it contains \"a\" as a substring. We choose $t_{5} = t_{7} =$'a' (it is becoming repetitive, isn't it?). The last part of $t$, that is, $t_{6}$, has no restriction (this time we choose a letter for only one position of $t$, not two). We choose 'd', and we have obtained a palindrome \"cacbadabcac\" that contains $s$ = \"abaac\" as a subsequence. This problem is mostly about analyzing this process carefully. The most naive solution other than literally enumerating all palindromes of length $N$ would be the following Dynamic Programming: let $dp[i][left][right]$ be the number of the palindromes $t$ that can be obtained if you have already decided the leftmost and the rightmost $i$ letters ($2i$ in total), and the substring $s_{left}s_{left + 1}..s_{right}$ of $s$ remains unmatched. Each value in this table can be computed in $O(1)$ time. Of course, since $i$ can be up to $ \\lfloor n / 2 \\rfloor $ ($n  \\le  10^{9}$), this solution is far from our goal. Notice that the transitions from $dp[i]$ to $dp[i + 1]$ are the same regardless of $i$, thus we can calculate the table by matrix exponentiation. However, since there are $O(|s|^{2})$ possible pairs for $(left, right)$, we will need $O(|s|^{6}\\log n)$ time, which is actually worse than the naive calculation considering that $|s|$ can be up to $200$. This is where we need to observe the process which we have gone through at the beginning more carefully. Let us build a automaton corresponding to the process (the image below). (*) An self-loop with a number means that there are actually that number of edges. A process of producing a palindrome of length $N$ that contains $s$ as a subsequence corresponds to a path of length $ \\lceil N / 2 \\rceil $ from the upper-right vertex to the lower-left vertex. Each red vertex has 24 self-loops since the letters at the both ends of the remaining part of $s$ is different, which correspond to two non-self-loop transitions. Similarly, each green vertex has 25 self-loops since the first letter and the last letter of the remaining string is the same, and the blue vertex, the destination, has 26 self-loops, as there are no more non-self-loop transitions available. Here is an important fact: there are not so many possible combination of $(n24, n25)$, where $n24$ and $n25$ are the number of times a path from START to GOAL visits a red vertex (with 24 self-loops) and a green vertex (with 25 self-loops), respectively. Why? Each time we leave a red vertex, the length of the remaining unmatched part of $s$ decreases by 1, since exactly one of the two letters at the ends of the remaining part is matched and discarded. Similarly, each time we leave a green vertex, the length of the remaining string decreases by 2, since both of the two letters at the ends are matched and discarded. There is a exception, however: if the length of the remaining string is 1, then it will be a green vertex, but in this case the length will decrease by 1. Thus, for any path from START to GOAL, $n24 + 2 \\cdot n25$ will be equal to either $|s|$ or $|s| + 1$. If we fix $n24$, then $n25$ will be uniquely determined by $n25 =  \\lceil (|s| - n24) / 2 \\rceil $. Since $n24$ can only take the value between $0$ and $|s| - 1$, there are at most $|s|$ possible pairs of $(n24, n25)$. With this fact, we are ready to count the paths: let us classify them by the value of $n24$. For each possible pair of $(n24, n25)$, let us count the number of corresponding paths. To do that, we divide each paths into two parts: first we count the number of paths from START to GOAL, using only non-self-loop transitions. Then, we count the ways of inserting self-loop transitions into each of these paths. The product of these two numbers will be the number that we seek. The first part is straightforward to solve: let $dp[left][right][n24]$ be the number of paths from the vertex that corresponds to the substring $s_{left}s_{left + 1}..s_{right}$, visiting exactly $n24$ red vertices using only non-self-loop transitions. Each value of the table can be found in $O(1)$ time, thus the whole table can be computed in $O(|s|^{3})$ time, which is fast enough for the input size ($|s|  \\le  200$). The main obstacle will be the second part. For example, let us consider the case where $s =$\"abaac\", $N = 11, n24 = 2$, which corresponds to the example at the beginning. From the fact we found earlier, $n25 =  \\lceil (|s| - n24) / 2 \\rceil  =  \\lceil (5 - 2) / 2 \\rceil  = 2$. Thus, we have to insert $ \\lceil N / 2 \\rceil  - n24 - n25 = 6 - 2 - 2 = 2$ self-loop transitions into this path (the image): The order in which red, green and blue vertices appears in this path does not affect the number of ways of insertion, and can be arbitrary. The number of ways to insert $2$ self-loop transitions will be equal to the number of the path of length $ \\lceil N / 2 \\rceil  = 6$ from START to GOAL in this automaton (we have to take into account the non-self-loop transitions in it), which can be calculated by matrix exponentiation. Are we done? No! Consider the case $s =$\"abbb..($|s| - 1$ times)..bb\". There are $|s| - 1$ possible values of $n24$ ($n24 = 1$ corresponds to the case where you match and discard the 'a' first, and $n24 = |s| - 1$ corresponds to the case where you keep the 'a' until $s$ becomes \"ab\"). Thus, you need to perform matrix exponentiation $|s| - 1$ times, which results in a total of $O(|s|^{4}\\log n)$ time, which will be too much under the given constraints. There is still hope, though, and here is the climax. Notice that these automata are very similar to each other, and they differ only in the number of the red and green vertices. We can combine these automata into one larger automaton like this (the image): The combined automaton should have $|s| - 1$ red, $ \\lceil |s| / 2 \\rceil $ green and $ \\lceil |s| / 2 \\rceil $ blue vertices. By performing matrix exponentiation on this automaton instead of many small automata, we can find all the required value in $O(|s|^{3}\\log n)$ time, which should be enough. We recommend speeding up matrix multiplication by noticing that the matrix will be upper triangular (6 times faster on paper), since the time limit is not so generous (in order to reject $O(|s|^{4}\\log n)$ solutions). The problem is almost solved, but there is one more challenge. When $N$ is odd, the situation becomes a little complicated: as we have seen at the beginning, in the last ($ \\lceil N / 2 \\rceil $-th) step of producing a palindrome we choose a letter for only one position of the resulting string, that is, the center of that string. In other words, the last transition in the path in the automaton we have first built must not be one from a green vertex with a string of length 2 (for example, \"aa\") to GOAL. Let us find the number of the paths that violates this condition and subtract it from the answer. As previously mentioned, for each path $n24 + 2 \\cdot n25$ will be equal to either $|s|$ or $|s| + 1$, and if we fix the value of $n24$, $n25$ will be uniquely determined by $n25 =  \\lceil (|s| - n24) / 2 \\rceil $. If $|s| - n24$ is odd, then it means that the last non-self-loop transition is one from a green vertex with a string of length 1, therefore in this case no path will violate the condition. If $|s| - n24$ is even, then the last non-self-loop trantision is from a green vertex with a string of length 2, thus the paths that does not contain the self-loop from GOAL to itself violate the condition. It will be equal to the number of the paths of length $ \\lceil N / 2 \\rceil  - 1$ from START to the vertex just before GOAL, which can be found in a similar way to the second part of the solution. The journey has finally come to an end. Actually, it is also possible to solve this problem in $O(|s|^{3}+\\log n)$ time without matrix exponentiation, but this margin is too small to explain it. I will just paste the link to the code.",
    "code": "#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <functional>\n#include <utility>\n#include <bitset>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <cstdio>\n \nusing namespace std;\n \n#define REP(i,n) for((i)=0;(i)<(int)(n);(i)++)\n#define snuke(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)\n \n#define MOD 10007\n \nint N;\nstring s;\nint dp[210][210][210]; // L, R, diagonals\n \ntypedef vector <vector <int> > matrix;\n \nmatrix mat_prod(matrix &A, matrix &B){\n    int N=A.size(),i,j,k;\n    matrix C(N, vector <int> (N, 0));\n    REP(i,N) REP(j,N){\n        int tmp = 0;\n        REP(k,N){\n            tmp += A[i][k] * B[k][j];\n            if((k&15) == 15) tmp %= MOD;\n        }\n        C[i][j] = tmp % MOD;\n    }\n    return C;\n}\n \nmatrix mat_power(matrix &A, int K){\n    int N=A.size(),i,j;\n    matrix ans(N, vector <int> (N, 0));\n    REP(i,N) ans[i][i] = 1;\n    for(i=30;i>=0;i--) if(K&(1<<i)) break;\n    for(;i>=0;i--){\n        ans = mat_prod(ans, ans);\n        if(K&(1<<i)) ans = mat_prod(ans, A);\n    }\n    return ans;\n}\n \nmatrix A,B;\n \nvoid pre(int K){\n    int i;\n    \n    matrix C(310, vector <int> (310, 0));\n    REP(i,309) C[i][i+1] = 1;\n    REP(i,205) C[i][i] = 24;\n    REP(i,105) C[205+i][205+i] = 25;\n    A = mat_power(C, K);\n    \n    matrix D(311, vector <int> (311, 0));\n    REP(i,310) D[i][i+1] = 1;\n    REP(i,205) D[i][i] = 24;\n    D[205][205] = 26;\n    REP(i,105) D[206+i][206+i] = 25;\n    B = mat_power(D, K);\n}\n \nint func2(int K, int moves, int stay24, int stay25, int stay26){\n    if(stay26 == 0) return A[205-stay24][204+stay25];\n    return B[205-stay24][205+stay25];\n}\n \nint func(int K, bool odd){\n    int ans=0,i,j,k;\n    \n    REP(i,N+1) REP(j,N+1) if(i == j || i == j + 1 || (i == j - 1 && odd)){\n        REP(k,210) if(dp[i][j][k] != 0){\n            int moves = N - (j - i) - k;\n            int stay25 = k;\n            int stay24 = moves - k;\n            int stay26 = 0;\n            if(i >= j) stay26++; else stay25++;\n            \n            int tmp = func2(K, moves, stay24, stay25, stay26);\n            if(odd && i >= j) tmp = tmp * 26 % MOD;\n            ans = (ans + tmp * dp[i][j][k]) % MOD;\n        }\n    }\n    \n    return ans;\n}\n \nint main(void){\n    int i,j,k,d;\n    int K;\n    \n    cin >> s >> K;\n    N = s.length();\n    \n    dp[0][N][0] = 1;\n    for(d=N;d>=1;d--) REP(i,N-d+1){\n        j = i + d;\n        REP(k,210) if(dp[i][j][k] != 0){\n            if(s[i] == s[j-1]){\n                dp[i+1][j-1][k+1] = (dp[i+1][j-1][k+1] + dp[i][j][k]) % MOD;\n            } else {\n                dp[i+1][j][k] = (dp[i+1][j][k] + dp[i][j][k]) % MOD;\n                dp[i][j-1][k] = (dp[i][j-1][k] + dp[i][j][k]) % MOD;\n            }\n        }\n    }\n    \n    K += N;\n    pre(K/2);\n    int ans = func(K/2, (K % 2 == 1));\n    cout << ans << endl;\n    \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "matrices",
      "strings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "507",
    "index": "A",
    "title": "Amr and Music",
    "statement": "Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.\n\nAmr has $n$ instruments, it takes $a_{i}$ days to learn $i$-th instrument. Being busy, Amr dedicated $k$ days to learn how to play the maximum possible number of instruments.\n\nAmr asked for your help to distribute his free days between instruments so that he can achieve his goal.",
    "tutorial": "Problem: We have to split the number $k$ into maximum number of elements of $a_{i}$ such that their sum is less than or equal to $k$. Hint: To maximize the answer we have to split the number into the smallest numbers possible. Solution: So and since the limits are small we can pick up the smallest element of the array and subtract it from $k$, and we keep doing this $n$ times or until the smallest number is larger than $k$. Another solution is to sort the array in non-decreasing order and go on the same way. Time complexity: $O(n^{2})\\,$ or $O(n\\ l o g\\ n)$",
    "code": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <list>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <bitset>\n#include <utility>\n#include <set>\n#include <numeric>\n \n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807\n#define INF 2000000000\n#define PI acos(-1.0)\n#define EPS 1e-9\n#define LL long long\n#define mod 1000000007\n#define pb push_back\n#define mp make_pair\n#define setzero(a) memset(a,0,sizeof(a))\n#define setdp(a) memset(a,-1,sizeof(a))\n \nusing namespace std;\n \npair<int,int> A[105];\nvector<int> ans;\n \nint main()\n{\n    int n,days;\n    cin >> n >> days;\n    for(int i=0;i<n;i++)\n        scanf(\"%d\",&A[i].first),A[i].second = i;\n    sort(A,A+n);\n    for(int i=0;i<n;i++)\n    {\n        if(days < A[i].first)\n            break;\n        ans.push_back(A[i].second + 1);\n        days-=A[i].first;\n    }\n    sort(ans.begin(), ans.end());\n    cout << ans.size() << endl;\n    for(int i=0;i<ans.size();i++)\n    {\n        if(i) printf(\" \");\n        printf(\"%d\",ans[i]);\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "507",
    "index": "B",
    "title": "Amr and Pins",
    "statement": "Amr loves Geometry. One day he came up with a very interesting problem.\n\nAmr has a circle of radius $r$ and center in point $(x, y)$. He wants the circle center to be in new position $(x', y')$.\n\nIn one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.\n\nHelp Amr to achieve his goal in minimum number of steps.",
    "tutorial": "Problem: We have a circle with radius $R$ at position $(x, y)$ and we want to move it to $(x', y')$ with minimum moves possible. A move is to choose an arbitrary point on the border of the circle and rotate the circle around it with arbitrary angle. Hint: What is the shortest path between two points? A direct line. So moving the center on that line with maximum move possible each time will guarantee minimal number of moves. Solution: Let's draw a straight line between the two centers. Clearly to move the center with maximum distance we need to rotate it around the intersection of the line and the circle with $180$ degrees. So the maximum distance we can move the center each time is $2 * R$. Let's continue moving the center with $2 * R$ distance each time until the two circles intersects. Now obviously we can make the center moves into its final position by rotating it around one of the intersection points of the two circles until it reaches the final destination. Every time we make the circle moves $2 * R$ times except the last move it'll be $ \\le  2 * R$. Assume that the initial distance between the two points is $d$ So the solution to the problem will be $c e i l({\\frac{d}{2\\pi R}})$. Time complexity: $O(1)$ You have to be careful of precision errors. Here is a code that used only integer arithmetic operations 9529147.",
    "code": "import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.math.BigInteger;\nimport java.util.StringTokenizer;\n \n \npublic class ok {\n\t\n\tpublic static void main(String[] args) {\n\t\tInputReader in = new InputReader(System.in);\n\t\tlong r;\n\t\tint x, y, xx, yy;\n\t    r = in.nextInt();\n\t    x = in.nextInt();\n\t    y = in.nextInt();\n\t    xx = in.nextInt();\n\t    yy = in.nextInt();\n\t    r*=2;\n\t    long dist = (x - xx) * 1L * (x - xx) + (y - yy) * 1L * (y - yy);\n\t    r *= r;\n\t    int L = 0, R = 1000000;\n\t    while(R > L)\n\t    {\n\t        int mid = L + (R - L) / 2;\n\t        BigInteger temp = BigInteger.valueOf(mid);\n\t        temp = temp.multiply(BigInteger.valueOf(mid));\n\t        temp = temp.multiply(BigInteger.valueOf(r));\n\t        int test = temp.compareTo(BigInteger.valueOf(dist));\n\t        if(test == 0 || test == 1)\n\t            R = mid;\n\t        else L = mid + 1;\n\t    }\n\t    System.out.println(R);\n\t}\n\t\n\tstatic class InputReader {\n        private BufferedReader reader;\n        private StringTokenizer tokenizer;\n \n        public InputReader(InputStream stream) {\n            reader = new BufferedReader(new InputStreamReader(stream));\n            tokenizer = null;\n        }\n \n        public InputReader(FileReader stream) {\n            reader = new BufferedReader(stream);\n            tokenizer = null;\n        }\n \n        public String nextLine() {\n            try {\n                return reader.readLine();\n            } catch (IOException e) {\n                // TODO Auto-generated catch block\n                e.printStackTrace();\n                return null;\n            }\n        }\n \n        public String next() {\n            while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n                try {\n                    tokenizer = new StringTokenizer(reader.readLine());\n                } catch (IOException e) {\n                    throw new RuntimeException(e);\n                }\n            }\n            return tokenizer.nextToken();\n        }\n \n        public int nextInt() {\n            return Integer.parseInt(next());\n        }\n \n        public long nextLong() {\n            return Long.parseLong(next());\n        }\n    }\n} ",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "507",
    "index": "C",
    "title": "Guess Your Way Out!",
    "statement": "Amr bought a new video game \"Guess Your Way Out!\". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height $h$. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.\n\nLet's index all the leaf nodes from the left to the right from 1 to $2^{h}$. The exit is located at some node $n$ where $1 ≤ n ≤ 2^{h}$, the player doesn't know where the exit is so he has to guess his way out!\n\nAmr follows simple algorithm to choose the path. Let's consider infinite command string \"LRLRLRLRL...\" (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules:\n\n- Character 'L' means \"go to the left child of the current node\";\n- Character 'R' means \"go to the right child of the current node\";\n- If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node;\n- If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command;\n- If he reached a leaf node that is not the exit, he returns to the parent of the current node;\n- If he reaches an exit, the game is finished.\n\nNow Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?",
    "tutorial": "Hint: Simulate the algorithm until we reach a leaf node assume that it's not the exit. Now the question is Are there some nodes that are guaranteed to be visited before trying to reach the exit again? Solution: The first observation is that in order to return to a parent we will have to visit all nodes of the right or the left subtree of some node first. Now imagine we are in the situation below where $E$ is the exit. By applying the algorithm we'll reach node $X$. Both the $E$ and $X$ are in different subtrees of the root. Which means before going to the proper subtree in which the Exit exists we'll have to visit all the nodes of the left subtree (marked in red). This means we have to get the node which the Exit and the current leaf node $X$ are in different subtrees which will be the least common ancestor (LCA) of the two nodes. Assume the subtree height is $h_{1}$. This means we visited $\\sum_{i=0}^{h_{1}-1}2^{i}$ node. By adding the nodes above the subtree which we visited during executing the string for the first time the total number of visited nodes will be $(\\sum_{i=0}^{h_{1}-1}2^{i})+h-h_{1}$. Now let's go to the other subtree. Obviously we don't need any other nodes except this subtree. So let's do the same we did to the original tree to this subtree. Execute the algorithm until we reach a leaf node, get the LCA, add to the solution $(\\bar{\\sum_{i=0}^{h_{2}-1}}2^{i})+h_{1}-h_{2}$ where $h_{2}$ is the height of the subtree of the LCA node where the leaf node exists. And so on we keep applying the rules until after executing the algorithm we will reach the exit. Also we can do the same operations in $O(h)$ by beginning to move from the root, if the exit is located to the left we go to the left and ans++ and then set the next command to 'R' else if it is located to the right we will visited the whole left subtree so we add the left subtree nodes to the answer $a n s+=\\sum_{i=0}^{h-2}2^{i}+1$ and then set the next command to 'L' and so on. Time complexity: $O(h^{2})\\,$ or $O(h)$ Challenge: What if the pattern is given as an input (e.g. \"LRRLLRRRLRLRLRR...\"), How can this problem be solved?",
    "code": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <list>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <bitset>\n#include <utility>\n#include <set>\n#include <numeric>\n \n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807\n#define INF 2000000000\n#define PI acos(-1.0)\n#define EPS 1e-9\n#define LL long long\n#define mod 1000000007\n#define pb push_back\n#define mp make_pair\n#define setzero(a) memset(a,0,sizeof(a))\n#define setdp(a) memset(a,-1,sizeof(a))\n \nusing namespace std;\n \nvector<LL> anc;\nLL sum[51];\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    int h;\n    LL n;\n    cin >> h >> n;\n    sum[0] = 1;\n    for(int i=1;i<51;i++)\n        sum[i] = sum[i-1] + (1LL << i);\n    n+=sum[h-1];\n    LL x = n;\n    anc.push_back(x);\n    while(x != 1)\n    {\n        x = x / 2;\n        anc.push_back(x);\n    }\n    LL res = 0;\n    LL node = 1;\n    bool choice = false;\n    while(node != n)\n    {\n        vector<LL> ance;\n        for(int i=0;i<h;i++)\n        {\n            ance.push_back(node);\n            if(!choice)\n                node = node * 2;\n            else node = node * 2 + 1;\n            choice = !choice;\n        }\n        if(n == node)\n        {\n            res+=h;\n            break;\n        }\n        ance.push_back(node);\n        reverse(ance.begin(), ance.end());\n        for(int i=1;i<=h;i++)\n        {\n            if(anc[i] == ance[i])\n            {\n                res+=sum[i - 1] + h - i + 1;\n                h = i - 1, node = ance[i - 1];\n                if(node == ance[i] * 2)\n                    node = ance[i] * 2 + 1, choice = 0;\n                else node = ance[i] * 2, choice = 1;\n                break;\n            }\n        }\n    }\n    cout << res;\n    return 0;\n}",
    "tags": [
      "implementation",
      "math",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "507",
    "index": "D",
    "title": "The Maths Lecture",
    "statement": "Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't.\n\nFirst he gave Amr two positive integers $n$ and $k$. Then he asked Amr, how many integer numbers $x > 0$ exist such that:\n\n- Decimal representation of $x$ (without leading zeroes) consists of exactly $n$ digits;\n- There exists some integer $y > 0$ such that:\n\n- $y{\\bmod{k}}=0$;\n- decimal representation of $y$ is a suffix of decimal representation of $x$.\n\nAs the answer to this question may be pretty huge the teacher asked Amr to output only its remainder modulo a number $m$.\n\nCan you help Amr escape this embarrassing situation?",
    "tutorial": "Hint: Dynamic programming problem. To handle repetitions we have to construct the number from right to the left and calculate the answer when we reach a number equivalent to $0$ modulo $k$. Solution: Let's define $c o u n t(i\\,,j)$ as a recursive functions calculates the number of numbers consisting of $n$ digits satisfying the conditions of the problem and with a specific suffix of length $i$ $S_{i}$ such that $S_{i}\\equiv j{\\mathrm{~(mod\\,}}k)$. We want to avoid repetition so by constructing the number from the right to the left when we reach a state with $j = 0$ with suffix $ \\neq  0$ we return the answer immediately so any other suffix that contains this suffix won't b calculated. So the base cases are $c o u n t(n,0)=1$, $c o u n t(i,0)=9*10^{n-i-1}:i<n$. So state transitions will be $c o u n t(i,j)=\\sum_{x=0}^{9}c o u n t(i+1,(j+(x*10^{i}))\\surd_{0}k)$ (We add a digit to the left). And we can handle $j = 0$ case coming from a zero suffix easily with a boolean variable we set to true when we use a digit $ \\neq  0$ in constructing the number. Time complexity: $O(n*k)$",
    "code": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <list>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <bitset>\n#include <utility>\n#include <set>\n#include <numeric>\n \n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807LL\n#define INF 1000000000\n#define PI acos(-1.0)\n#define EPS 1e-9\n#define LL long long\n//#define mod 1000000007\n#define pb push_back\n#define mp make_pair\n#define setzero(a) memset(a,0,sizeof(a))\n#define setdp(a) memset(a,-1,sizeof(a))\n \nusing namespace std;\n \nint mod;\nint DP[1005][105][2];\nint powers[1005],powers2[1005],k,n;\n \nint solve(int ind,int rem, bool change)\n{\n    if(rem == 0 && change) return (ind != n ? ((powers[n - ind - 1] * 1LL * 9) % mod) : 1);\n    if(ind == n || (rem == 0 && change)) return 0;\n    int &temp = DP[ind][rem][change];\n    if(temp != -1) return temp;\n    temp = 0;\n    for(int i=0;i<10;i++)\n        temp+=solve(ind + 1, (rem + (i * 1LL * powers2[ind]) % k) % k,change || i != 0),temp%=mod;\n    return temp;\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin >> n >> k >> mod;\n    setdp(DP);\n    LL y = 1;\n    for(int i=0;i<=n;i++)\n    {\n        powers[i] = y;\n        y*=10;\n        y%=mod;\n    }\n    y = 1;\n    for(int i=0;i<=n;i++)\n    {\n        powers2[i] = y;\n        y*=10;\n        y%=k;\n    }\n    cout << solve(0, 0, 0);\n    return 0;\n}",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "507",
    "index": "E",
    "title": "Breaking Good",
    "statement": "Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.\n\nWalter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of $n$ cities with $m$ bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads.\n\nThe roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.\n\nThe gang is going to rob a bank! The bank is located in city $1$. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city $n$. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.\n\nFirst of all the path which they are going to use on their way back from city $1$ to their headquarters $n$ must be \\underline{as short as possible}, since it is important to finish operation as fast as possible.\n\nThen, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional.\n\nIf the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.\n\nWalter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).\n\nCan you help Walter complete his task and gain the gang's trust?",
    "tutorial": "Hint: Consider we've chosen a certain path with length $d$ where $d$ is the length of the shortest path from $1$ to $n$ and it has $x$ edges that are working. Assume that $y$ is the total number of edges that are working in the whole country. So we need to make $d - x$ changes (to make the malfunctioning edges on the path work) and $y - x$ changes (to blow up all other edges that don't lie on the path). So we will totally make $d + y - 2 * x$ changes where $d$ and $y$ are constants. So the optimal solution will depend only on number of working edges along the path. So we'll have to maximize this number! Solution: We will use dynamic programming on all nodes that lies on some shortest path. In other words, every node $x$ that satisfies that the shortest path from $1$ to $x$ + the shortest path from $x$ to $n$ equals $d$ where $d$ is the length of the shortest path from $1$ to $n$. Let's define $Max[x]$ is the maximum number of working edges along some shortest path from $1$ to $x$. We can calculate the value $Max[x]$ for all nodes by dynamic programming by traversing the nodes in order of increasing shortest path from node $1$. So at the end we'll make $d + y - 2 * Max[n]$ changes. We can get them easily by retrieving the chosen optimal path. Time complexity: $O(n+m)$",
    "code": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <cstring>\n#include <string>\n#include <cctype>\n#include <stack>\n#include <queue>\n#include <list>\n#include <vector>\n#include <map>\n#include <sstream>\n#include <cmath>\n#include <limits>\n#include <bitset>\n#include <utility>\n#include <set>\n#include <numeric>\n \n#define INF_MAX 2147483647\n#define INF_MIN -2147483647\n#define INF_LL 9223372036854775807LL\n#define INF 1000000000\n#define PI acos(-1.0)\n#define EPS 1e-9\n#define LL long long\n#define mod 1000000007\n#define pb push_back\n#define mp make_pair\n#define setzero(a) memset(a,0,sizeof(a))\n#define setdp(a) memset(a,-1,sizeof(a))\n \nusing namespace std;\n \nstruct edge\n{\n    int to;\n    bool s;\n \n    edge(int y, bool z)\n    {\n        to = y, s = z;\n    }\n};\n \nvector<vector<edge > > graph(100005);\nint D1[100005], DN[100005], MaxOp[100005], parent[100005], path[100005];\nint from[100005], to[100005];\nbool opened[100005], visited[100005];\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    int n, m, counter = 0;\n    cin >> n >> m;\n    for(int i=0;i<m;i++)\n    {\n        cin >> from[i] >> to[i] >> opened[i];\n        graph[from[i]].pb(edge(to[i], opened[i]));\n        graph[to[i]].pb(edge(from[i], opened[i]));\n        counter+=opened[i];\n    }\n    setdp(D1);\n    setdp(DN);\n    setdp(MaxOp);\n    queue<int> q;\n    q.push(1);\n    D1[1] = 0;\n    while(!q.empty())\n    {\n        int node = q.front();\n        q.pop();\n        for(int i=0;i<graph[node].size();i++)\n        {\n            edge e = graph[node][i];\n            if(D1[e.to] != -1) continue;\n            D1[e.to] = D1[node] + 1;\n            q.push(e.to);\n        }\n    }\n    q.push(n);\n    DN[n] = 0;\n    while(!q.empty())\n    {\n        int node = q.front();\n        q.pop();\n        for(int i=0;i<graph[node].size();i++)\n        {\n            edge e = graph[node][i];\n            if(DN[e.to] != -1) continue;\n            DN[e.to] = DN[node] + 1;\n            q.push(e.to);\n        }\n    }\n    int d = D1[n];\n    q.push(1);\n    MaxOp[1] = 0;\n    while(!q.empty())\n    {\n        int node = q.front();\n        q.pop();\n        if(visited[node]) continue;\n        visited[node] = true;\n        for(int i=0;i<graph[node].size();i++)\n        {\n            edge e = graph[node][i];\n            if(D1[e.to] + DN[e.to] != d || D1[node] + 1 + DN[e.to] != d || visited[e.to]) continue;\n            if(MaxOp[e.to] != -1 && MaxOp[e.to] >= MaxOp[node] + e.s) continue;\n            q.push(e.to);\n            parent[e.to] = node;\n            MaxOp[e.to] = MaxOp[node] + e.s;\n        }\n    }\n    int node = n;\n    while(node != 1)\n    {\n        path[node] = parent[node];\n        node = path[node];\n    }\n    cout << counter + d - 2 * MaxOp[n] << '\\n';\n    for(int i=0;i<m;i++)\n    {\n        if(path[from[i]] == to[i] || path[to[i]] == from[i])\n        {\n            if(!opened[i]) cout << from[i] << \" \" << to[i] << \" 1\" << '\\n';\n        }\n        else if(opened[i]) cout << from[i] << \" \" << to[i] << \" 0\" << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "508",
    "index": "A",
    "title": "Pasha and Pixels",
    "statement": "Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.\n\nPasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of $n$ row with $m$ pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a $2 × 2$ square consisting of black pixels is formed.\n\nPasha has made a plan of $k$ moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers $i$ and $j$, denoting respectively the row and the column of the pixel to be colored on the current move.\n\nDetermine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the $2 × 2$ square consisting of black pixels is formed.",
    "tutorial": "To solve this problem let's create matrix with type $bool$ and dimensions $n$ on $m$. Cell $(x, y)$ of this matrix is $true$ - if this cell painted in black color. Let on move number $k$ Pasha paints pixel in position $(i, j)$. Then game ending on this move, if square $2  \\times  2$ formed from black cells appears, and cell $(i, j)$ will upper-left, upper-right, bottom-left or bottom-right of this squares. Only this squares we need to check on current move. If we haven't such squares after $k$ moves, print $0$. Asymptotic behavior of this solution - $O(k)$, where $k$ - number of moves.",
    "tags": [
      "brute force"
    ],
    "rating": 1100
  },
  {
    "contest_id": "508",
    "index": "B",
    "title": "Anton and currency you all know",
    "statement": "Berland, 2016. The exchange rate of \\underline{currency you all know} against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.\n\nReliable sources have informed the financier Anton of some information about the exchange rate of \\underline{currency you all know} against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an \\underline{odd} positive integer $n$. Help Anton to determine the exchange rate of \\underline{currency you all know} for tomorrow!",
    "tutorial": "Because of specified number is odd (that mean that last digit of this number is odd) we need to swap last digit with some even digit. How to maximize number after this swap? If number consists only from odd digits print $- 1$. Else, we need to find first even digit, which less than last digit if we will iterate from most significant digit. If we find such digit - swap it with last digit and we have an answer. Else, we need to find first even digit, which more than last digit if we will iterate from less significant digit. If we find such digit - swap it with last digit and we have an answer. Asymptotic behavior of this solution - $O(n)$, where $n$ - count of digits in specified number.",
    "tags": [
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "508",
    "index": "C",
    "title": "Anya and Ghosts",
    "statement": "Anya loves to watch horror movies. In the best traditions of horror, she will be visited by $m$ ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly $t$ seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly $t$ seconds and then goes out and can no longer be used.\n\nFor each of the $m$ ghosts Anya knows the time at which it comes: the $i$-th visit will happen $w_{i}$ seconds after midnight, all $w_{i}$'s are distinct. Each visit lasts exactly one second.\n\nWhat is the minimum number of candles Anya should use so that during each visit, at least $r$ candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. \\textbf{That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.}",
    "tutorial": "This problem can be solved with help of greedy algorithm. Let's iterate on moments when ghosts will appears. We need to use use array, in wich we will mark moments of time, in wich we lighted candles (for example, put in corresponding positions $1$). Than for every new ghost will count how many candles lights in time of his visit from our array. If ghost appears in moment of time $w_{i}$, iterate on out array from $w_{i} - 1$ to $w_{i} - t$, where $t$ - count of seconds, which candle burns, and count the number of ones. If this count is not less than $r$, continue iterating on ghosts. Else, iterate on our array from $w_{i} - 1$ to $w_{i} - t$, and, if in current second candle didn't lighted - make it, and put in this position in array $1$. We need to do such operation, while count of ones in this section of our array will not be equals to $r$. If we can't do this fore some ghost, we can print $- 1$. Answer to this problem - count of ones in our array. Asymptotic behavior of this solution - $O(mt)$, where $m$ - count of ghosts, $t$ - the duration of a candle's burning.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "508",
    "index": "D",
    "title": "Tanya and Password",
    "statement": "While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of $n + 2$ characters. She has written all the possible $n$ three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with $n$ pieces of paper.\n\nThen Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.",
    "tutorial": "At first, let's convert data from input in directed graph. Vertexes in this graph will all strings with length equals to 2 and consisting of uppercase and lowercase letters of the latin alphabet. For all 3-letters strings from input - $s_{i}$'s, let's add edge from vertex $s_{i}[0]s_{i}[1]$ to $s_{i}[1]s_{i}[2]$. Now we need to find in this graph Euler path. For this we can use Fleury's algorithm. It is worth noting, that Euler path consists, if count of vertexes, in wich in-degree and out-degree differs by one, less then 3, and in-degree and out-degree of others vertexes - even. If we can't find Euler path - print $NO$. Asymptotic behavior of this solution - $O(m)$, where $m$ - count of different 3-letters strings from input. It equals to number of edges in graphs.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "508",
    "index": "E",
    "title": "Arthur and Brackets",
    "statement": "Notice that the memory limit is non-standard.\n\nRecently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length $2n$. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.\n\nAll Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the $i$-th opening bracket he remembers the segment $[l_{i}, r_{i}]$, containing the distance to the corresponding closing bracket.\n\nFormally speaking, for the $i$-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment $[l_{i}, r_{i}]$.\n\nHelp Arthur restore his favorite correct bracket sequence!",
    "tutorial": "This problem can be solved with help of dynamic dynamic programming. Let's create squre matrix $Z$ with sizes $n  \\times  n$, where $n$ - count of open brackets in sequence. Main hint - if open bracket is in position $l$, and corresponding for her close bracket - in position $r$, than from position $l + 1$ to position $r - 1$ must stay a regular bracket sequence. In array $Z$ first parametr $lf$ - number of open bracket, second parametr $rg$ - number of last open bracket, which can be in a regular bracket sequence, which will exists between open bracket with number $lf$ and corresponding for it close bracket. $Z[lf][rg] = true$ if it is possible to construct such sequence. Otherwise $Z[lf][rg] = false$. For current $lf$ and $rg$ let's iterate on $cnt$ - how many open brackets and corresponding them close brackets in a regular bracket sequence will stay between open bracket number $lf$ and corresponding for it close bracket. If this count falls in the given interval for open bracket $lf$, recurcively run dynamic from two segments - $(lf + 1, lf + cnt)$ and $(lf + cnt + 1, rg)$. If for both segments we can construct regular bracket sequences, appropriate to data-in from input, put in $Z[lf][rg]$ value $true$. To restore answer, we must move from segment $(lf, rg)$ in segments $(lf + 1, lf + cnt)$ and $(lf + cnt + 1, rg)$, if for both this segments we can construct regular bracket sequences and recursively restore asnwer. If $Z[0][n - 1]$ equals to $false$, print $IMPOSSIBLE$. Asymptotic behavior of this solution - $O(n^{3})$.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "509",
    "index": "A",
    "title": "Maximum in Table",
    "statement": "An $n × n$ table $a$ is defined as follows:\n\n- The first row and the first column contain ones, that is: $a_{i, 1} = a_{1, i} = 1$ for all $i = 1, 2, ..., n$.\n- Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula $a_{i, j} = a_{i - 1, j} + a_{i, j - 1}$.\n\nThese conditions define all the values in the table.\n\nYou are given a number $n$. You need to determine the maximum value in the $n × n$ table defined by the rules above.",
    "tutorial": "In this problem one needed to implement what was written in the statement: create matrix (two-dimensional array) using given rules and find maximal value in the table. It is also possible to see that maximal element is always in bottom-right corner. Easier solution with recursion also was enough to get AC: One may see the Pascal's triangle in the given matrix and understand that answer is equal to $\\textstyle{\\binom{2n-2}{n-1}}$",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "509",
    "index": "B",
    "title": "Painting Pebbles",
    "statement": "There are $n$ piles of pebbles on the table, the $i$-th pile contains $a_{i}$ pebbles. Your task is to paint each pebble using one of the $k$ given colors so that for each color $c$ and any two piles $i$ and $j$ the difference between the number of pebbles of color $c$ in pile $i$ and number of pebbles of color $c$ in pile $j$ is at most one.\n\nIn other words, let's say that $b_{i, c}$ is the number of pebbles of color $c$ in the $i$-th pile. Then for any $1 ≤ c ≤ k$, $1 ≤ i, j ≤ n$ the following condition must be satisfied $|b_{i, c} - b_{j, c}| ≤ 1$. It isn't necessary to use all $k$ colors: if color $c$ hasn't been used in pile $i$, then $b_{i, c}$ is considered to be zero.",
    "tutorial": "Suppose there are two piles with number of pebbles differed by more than $k$, then there is no solution: $a_{i}=\\sum_{c=1}^{k}b_{i,c}\\leq\\sum_{c=1}^{k}(b_{j,c}+1)=a_{j}+k$ Now let $M = max a_{i}  \\le  min a_{i} + k = m + k$. There's a way to construct correct coloring: Chose $m$ peebles from each pile and assign first color to them. In each pile assign different colors to all other pebbles (you may use first color once more) (It's possible bacause there are no more than $k$ uncolored pebbles. Now there are $m$ or $m + 1$ pebbles of first color and 0 or 1 pebbles of any other color in each pile.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "509",
    "index": "C",
    "title": "Sums of Digits",
    "statement": "Vasya had a \\textbf{strictly increasing} sequence of positive integers $a_{1}$, ..., $a_{n}$. Vasya used it to build a new sequence $b_{1}$, ..., $b_{n}$, where $b_{i}$ is the sum of digits of $a_{i}$'s decimal representation. Then sequence $a_{i}$ got lost and all that remained is sequence $b_{i}$.\n\nVasya wonders what the numbers $a_{i}$ could be like. Of all the possible options he likes the one sequence with the minimum possible last number $a_{n}$. Help Vasya restore the initial sequence.\n\nIt is guaranteed that such a sequence always exists.",
    "tutorial": "The algorithm is greedy: first, take the minimal number with sum of digits $a_{1}$ - call it $b_{1}$. Then, on the $i$-th step take $b_{i}$ as the minimal number with sum of digits $a_{i}$, which is more than $b_{i - 1}$. It can be easily proven that this algorithm gives an optimal answer. But how to solve the subproblem: given $x$ and $y$, find the minimal number with sum of digits $x$, which is more than $y$? We use a standard approach: iterate through the digits of $y$ from right to left, trying to increase the current digit and somehow change the digits to the right in order to reach the sum of digits equal to $x$. Note that if we are considering the $(k + 1)$-th digit from the right and increase it, we can make the sum of $k$ least significant digits to be any number between $0$ and $9k$. When we find such position, that increasing a digit in it and changing the least significant digits gives us a number with sum of digits $x$, we stop the process and obtain the answer. Note that if $k$ least significant digits should have sum $m$ (where $0  \\le  m  \\le  9k$), we should obtain the answer greedily, going from the right to the left and putting to the position the largest digit we can. Let us bound the maximal length of the answer, i.e. of $b_{n}$. If some $b_{i}$ has at least $40$ digits, than we take the minimal $k$ such that $10^{k}  \\ge  b_{i}$. Than between $10^{k}$ and $10^{k + 1}$ there exist numbers with any sum of digits between $1$ and $9k$. If $k  \\ge  40$, than $9k  \\ge  300$, which is the upper bound of all $b_{i}$. So, in the constraints of the problem, $b_{i + 1}$ will be less than $10^{k + 1}$. Than, similarly, $b_{i + 2} < 10^{k + 2}$ and so on. So, the length of the answer increases by no more than one after reaching the length of $40$. Consequently, the maximal length of the answer can't be more than $340$. The complexity of solution is $O(n \\cdot maxLen)$. Since $n  \\le  300$, $maxLen  \\le  340$, the solution runs much faster the time limit.",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "509",
    "index": "D",
    "title": "Restoring Numbers",
    "statement": "Vasya had two arrays consisting of non-negative integers: $a$ of size $n$ and $b$ of size $m$. Vasya chose a positive integer $k$ and created an $n × m$ matrix $v$ using the following formula:\n\n\\[\nv_{i,j}=(a_{i}+b_{j})\\bmod k\n\\]\n\nVasya wrote down matrix $v$ on a piece of paper and put it in the table.\n\nA year later Vasya was cleaning his table when he found a piece of paper containing an $n × m$ matrix $w$. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix $v$ from those days. Your task is to find out if the matrix $w$ that you've found could have been obtained by following these rules and if it could, then for what numbers $k, a_{1}, a_{2}, ..., a_{n}, b_{1}, b_{2}, ..., b_{m}$ it is possible.",
    "tutorial": "First we note that if the sequences $a_{i}$ and $b_{i}$ are a valid solution, then so are the sequences $a_{i} - P$ and $b_{i} + P$ for any integer $P$. This means that we can consider $a_{1}$ to be equal to 0 which allows us to recover the sequence $b_{i}$ by simply taking the first row of the matrix. Knowing $b_{i}$ we can also recover $a_{i}$ (for example by subtracting $b_{1}$ from the first column of the matrix) At this stage we allow $a_{i}$ and $b_{i}$ to contain negative numbers, which can be later fixed by adding $K$ a sufficient amount of times. Now we consider the \"error\" matrix $e$: $e_{i,j}=|a_{i}+b_{j}-w_{i,j}|$. If $e$ consists entirely of 0s, then we've found our solution by taking a sufficiently large $K$. That is: $K > max_{i, j}(w_{i, j})$. Otherwise, we note that $e_{i, j} = 0(modK)$ which implies that $K$ is a divisor of $g = gcd_{i, j}(e_{i, j})$. The greatest such number is $g$ itself, so all that remains is to check if $g$ is strictly greater than all the elements of the matrix $w$. If that is the case, then we've found our solution by setting $K = g$. Otherwise, there's no solution.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "509",
    "index": "E",
    "title": "Pretty Song",
    "statement": "When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.\n\nLet's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.\n\nLet's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.\n\nMore formally, let's define the function $vowel(c)$ which is equal to $1$, if $c$ is a vowel, and to $0$ otherwise. Let $s_{i}$ be the $i$-th character of string $s$, and $s_{i..j}$ be the substring of word $s$, staring at the $i$-th character and ending at the $j$-th character ($s_{is}_{i + 1}... s_{j}$, $i ≤ j$).\n\nThen the simple prettiness of $s$ is defined by the formula:\n\n\\[\ns i m p l e(s)={\\frac{\\sum_{i=1}^{\\operatorname{op}}v o w e l(s_{i})}{\\operatorname{ini}}}\n\\]\n\nThe prettiness of $s$ equals\n\n\\[\n\\sum_{1\\leq i\\leq j\\leq|s|}s i m p l e(s_{i\\cdot j}).\n\\]\n\nFind the prettiness of the given song title.\n\nWe assume that the vowels are $I, E, A, O, U, Y$.",
    "tutorial": "We first calculate the prefix sums of $vowel(s_{i})$ which allows to calculate the sum of $vowel(s_{i})$ on any substring in $O(1)$ time. For all $m$ from $1$ to $\\left|\\,\\S\\right|_{\\sim}\\right|_{\\sim}$, we will calculate the sum of simple pretinesses of all substrings of that length, let's call it $SP_{m}$. For that purpose, let's calculate the number of times the $i$-th character of the string $s$ is included in this sum. For $m = 1$ and $m = |s|$, every character is included exactly 1 time. For $m = 2$ and $m = |s| - 1$, the first and the last character are included 1 time and all other characters are included 2 times. For $m = 3$ and $m = |s| - 2$ the first and the last character are included 1 time, the second and the pre-last character are included 2 times and all others are included 3 times, and so on. In general, the $i$-th character is included $min(m, |s| - m + 1, i, |s| - i + 1)$ times. Note that when moving from substrings of length $m$ to substrings of length $m + 1$, there are 2 ways in which the sum $SP$ can change: If $m > |s| - m + 1$, then $SP$ is decreased by the number of vowel occurrences in the substring from $|s| - m + 1$ to $m$. Otherwise, $SP$ is increased by the number of vowel occurrences in the substring from $m$ to $|s| - m + 1$. This way we can easily recalculate $SP_{m + 1}$ using $SP_{m}$ by adding (subtracting) the number of vowel occurrences on a substring (which is done in $O(1)$ time). The complexity of this solution is $O(N)$.",
    "tags": [
      "math",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "509",
    "index": "F",
    "title": "Progress Monitoring",
    "statement": "Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:\n\nYou are given a tree $T$ with $n$ vertices, specified by its adjacency matrix $a[1... n, 1... n]$. What is the output of the following pseudocode?\n\n\\begin{verbatim}\nused[1 ... n] = {0, ..., 0};\nprocedure dfs(v):\nprint v;\nused[v] = 1;\nfor i = 1, 2, ..., n:\nif (a[v][i] == 1 and used[i] == 0):\ndfs(i);\ndfs(1);\n\\end{verbatim}\n\nIn order to simplify the test results checking procedure, Dmitry Olegovich decided to create a tree $T$ such that the result is his favorite sequence $b$. On the other hand, Dmitry Olegovich doesn't want to provide students with same trees as input, otherwise they might cheat. That's why Dmitry Olegovich is trying to find out the number of different trees $T$ such that the result of running the above pseudocode with $T$ as input is exactly the sequence $b$. Can you help him?\n\nTwo trees with $n$ vertices are called different if their adjacency matrices $a_{1}$ and $a_{2}$ are different, i. e. there exists a pair $(i, j)$, such that $1 ≤ i, j ≤ n$ and $a_{1}[i][j] ≠ a_{2}[i][j]$.",
    "tutorial": "Consider a tree with $n$ vertices rooted at vertex 1 and let $b$ be the pseudocode's (DFS) resulting sequence. Then $b[l_{v}..l_{v} + size_{v} - 1]$, represents vertex $v$'s subtree, where $l_{v}$ is the index of $v$ in $b$ and $size_{v}$ is the size of $v$'s subtree. Let's solve the problem using this fact and Dynamic Programming. Let $e[l, r]$ be the number of trees consisting of vertices $a[l], a[l + 1],  \\dots , a[r]$ such that running DFS starting from $a[l]$ will result in a sequence with vertices in the same order as their order in $a$. The base case is when $l = r$ and $e[l, r] = 1$. Otherwise, $e[l,r]=\\sum\\prod_{i=1}^{k}e[p o s_{i},p o s_{i+1}-1]$ where the sum is taken over all partitions of the segment $[l + 1, r]$, that is, over all $k;pos_{1}, ..., pos_{k + 1}$, such that $l + 1 = pos_{1} < pos_{2} < ... < pos_{k + 1} = r$, $1  \\le  k  \\le  r - l$, $a[pos_{1}] < a[pos_{2}] < ... < a[pos_{k}]$. Each such partition represents a different way to distribute the vertices among $a[l]$'s children's subtrees. A solution using this formula for calculating $e[l, r]$ will have an exponential running time. The final idea is to introduce $d[l, r]: = e[l - 1, r], 2  \\le  l  \\le  r  \\le  n$. It follows that: $d[l, r]$ = $e[l,r]+\\sum_{p o s=l+1}^{r}\\,e[l,p o s-1]*d[p o s,r]\\ast[a[l]<a[p o s]]$ ([statement] is equal to 1 if the statement is true, 0 otherwise) and $e[l, r] = d[l + 1, r]$. This way $d[l, r]$ and $e[l, r]$ can be calculated in linear time for any segment $[l, r]$. The answer to the problem is $e[1, n]$. Overall complexity is $O(n^{3})$.",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "510",
    "index": "A",
    "title": "Fox And Snake",
    "statement": "Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.\n\nA snake is a pattern on a $n$ by $m$ table. Denote $c$-th cell of $r$-th row as $(r, c)$. The tail of the snake is located at $(1, 1)$, then it's body extends to $(1, m)$, then goes down $2$ rows to $(3, m)$, then goes left to $(3, 1)$ and so on.\n\nYour task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').\n\nConsider sample tests in order to understand the snake pattern.",
    "tutorial": "There are 2 different ways to solve this kind of task: First one is to simulate the movement of the snake head, and you draw '#'s on the board. The code will look like: Another way is to do some observation about the result, you can find this pattern:",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint MAIN()\n{\n\tint n, m;\n\tcin >> n >> m;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tfor(int j = 1; j <= m; j++)\n\t\t{\n\t\t\tbool haveSnake = false;\n\t\t\tif(i % 2 == 1) haveSnake = true;\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(i % 4 == 2) haveSnake = (j == m);\n\t\t\t\tif(i % 4 == 0) haveSnake = (j == 1);\n\t\t\t}\n\t\t\tcout << (haveSnake ? \"#\" : \".\");\n\t\t}\n\t\tcout << endl;\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\t#ifdef LOCAL_TEST\n\t\tfreopen(\"in.txt\", \"r\", stdin);\n\t\tfreopen(\"out.txt\", \"w\", stdout);\n\t#endif\n\tios :: sync_with_stdio(false);\n\tcout << fixed << setprecision(16);\n\treturn MAIN();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "510",
    "index": "B",
    "title": "Fox And Two Dots",
    "statement": "Fox Ciel is playing a mobile puzzle game called \"Two Dots\". The basic levels are played on a board of size $n × m$ cells, like this:\n\nEach cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.\n\nThe key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots $d_{1}, d_{2}, ..., d_{k}$ a \\underline{cycle} if and only if it meets the following condition:\n\n- These $k$ dots are different: if $i ≠ j$ then $d_{i}$ is different from $d_{j}$.\n- $k$ is at least 4.\n- All dots belong to the same color.\n- For all $1 ≤ i ≤ k - 1$: $d_{i}$ and $d_{i + 1}$ are adjacent. Also, $d_{k}$ and $d_{1}$ should also be adjacent. Cells $x$ and $y$ are called adjacent if they share an edge.\n\nDetermine if there exists a \\underline{cycle} on the field.",
    "tutorial": "This task is essentially ask if there is a cycle in an undirected graph: treat each cell as a node, and add an edge if two cells are neighborhood and have some color. There are lots of ways to do this, for example: Run dfs / bfs, if an edge lead you to a visited node, then there must be a cycle. For each connected component, test if $|#edges| = |#nodes| - 1$, if not then there must be a cycle.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n, m;\nstring board[51];\nbool visited[51][51];\nbool findCycle = false;\nint dx[] = {1, -1, 0, 0};\nint dy[] = {0, 0, 1, -1};\n\nvoid dfs(int x, int y, int fromX, int fromY, char needColor)\n{\n\tif(x < 0 || x >= n || y < 0 || y >= m) return;\n\tif(board[x][y] != needColor) return;\n\tif(visited[x][y])\n\t{\n\t\tfindCycle = true;\n\t\treturn;\n\t}\n\tvisited[x][y] = true;\n\tfor(int f = 0; f < 4; f++)\n\t{\n\t\tint nextX = x + dx[f];\n\t\tint nextY = y + dy[f];\n\t\tif(nextX == fromX && nextY == fromY) continue;\n\t\tdfs(nextX, nextY, x, y, needColor);\n\t}\n}\n\nint MAIN()\n{\n\tcin >> n >> m;\n\tfor(int i = 0; i < n; i++)\n\t\tcin >> board[i];\n\tmemset(visited, false, sizeof(visited));\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < m; j++)\n\t\t\tif(!visited[i][j])\n\t\t\t\tdfs(i, j, -1, -1, board[i][j]);\n\tcout << (findCycle ? \"Yes\" : \"No\") << endl;\n\treturn 0;\n}\n\nint main()\n{\n\t#ifdef LOCAL_TEST\n\t\tfreopen(\"in.txt\", \"r\", stdin);\n\t\tfreopen(\"out.txt\", \"w\", stdout);\n\t#endif\n\tios :: sync_with_stdio(false);\n\tcout << fixed << setprecision(16);\n\treturn MAIN();\n}",
    "tags": [
      "dfs and similar"
    ],
    "rating": 1500
  },
  {
    "contest_id": "510",
    "index": "C",
    "title": "Fox And Names",
    "statement": "Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: \"Fox\"). She heard a rumor: the authors list on the paper is always sorted in the \\underline{lexicographical} order.\n\nAfter checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in \\underline{lexicographical} order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes \\underline{lexicographical}!\n\nShe wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the \\underline{lexicographical} order. If so, you should find out any such order.\n\n\\underline{Lexicographical} order is defined in following way. When we compare $s$ and $t$, first we find the leftmost position with differing characters: $s_{i} ≠ t_{i}$. If there is no such position (i. e. $s$ is a prefix of $t$ or vice versa) the shortest string is less. Otherwise, we compare characters $s_{i}$ and $t_{i}$ according to their order in alphabet.",
    "tutorial": "Let's first think about what $S < T$ can tell us: suppose $S = abcxyz$ and $T = abcuv$. Then we know that $S < T$ if and only if $x < u$ by the definition. So we can transform the conditions $name_{1} < name_{2}$, $name_{2} < name_{3}$ ... into the order of letters. Then the question become: do we have a permutation that satisfy those conditions. It is actually the classic topological order question. One trick in this task is that, if we have something like $xy < x$ then there is no solution. This is not covered in pretests. :)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n;\nint e[27][27];\nstring s[101];\nbool visited[27];\n\nint getID(char c)\n{\n\tif(c == ' ') return 0;\n\treturn c - 'a' + 1;\n}\n\nint MAIN()\n{\n\tmemset(e, 0, sizeof(e));\n\tfor(int i = 1; i <= 26; i++)\n\t\te[0][i] = true;\n\tcin >> n;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tcin >> s[i];\n\t\ts[i] += \" \";\n\t}\n\tfor(int i = 1; i < n; i++)\n\t{\n\t\tint pos = 0;\n\t\twhile(s[i][pos] == s[i+1][pos]) pos ++;\n\t\te[getID(s[i][pos])][getID(s[i+1][pos])] = true;\n\t}\n\tfor(int k = 0; k <= 26; k++)\n\t\tfor(int i = 0; i <= 26; i++)\n\t\t\tfor(int j = 0; j <= 26; j++)\n\t\t\t\te[i][j] |= e[i][k] & e[k][j];\n\tbool haveCycle = false;\n\tfor(int i = 0; i <= 26; i++)\n\t\thaveCycle |= e[i][i];\n\tif(haveCycle)\n\t\tcout << \"Impossible\" << endl;\n\telse\n\t{\n\t\tmemset(visited, 0, sizeof(visited));\n\t\tfor(int i = 0; i <= 26; i++)\n\t\t{\n\t\t\tint now = 0;\n\t\t\tfor(int j = 0; j <= 26; j++)\n\t\t\t{\n\t\t\t\tbool valid = (!visited[j]);\n\t\t\t\tfor(int k = 0; k <= 26; k++)\n\t\t\t\t\tif(visited[k] == false && e[k][j])\n\t\t\t\t\t\tvalid = false;\n\t\t\t\tif(valid)\n\t\t\t\t{\n\t\t\t\t\tnow = j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(i > 0)\n\t\t\t\tcout << char('a' + now - 1);\n\t\t\tvisited[now] = true;\n\t\t}\n\t\tcout << endl;\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\t#ifdef LOCAL_TEST\n\t\tfreopen(\"in.txt\", \"r\", stdin);\n\t\tfreopen(\"out.txt\", \"w\", stdout);\n\t#endif\n\tios :: sync_with_stdio(false);\n\tcout << fixed << setprecision(16);\n\treturn MAIN();\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "510",
    "index": "D",
    "title": "Fox And Jumping",
    "statement": "Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.\n\nThere are also $n$ cards, each card has 2 attributes: length $l_{i}$ and cost $c_{i}$. If she pays $c_{i}$ dollars then she can apply $i$-th card. After applying $i$-th card she becomes able to make jumps of length $l_{i}$, i. e. from cell $x$ to cell $(x - l_{i})$ or cell $(x + l_{i})$.\n\nShe wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.\n\nIf this is possible, calculate the minimal cost.",
    "tutorial": "This task equals to: what is the minimal sum of costs that we can select k cards, so their GCD is 1. First observation is that: $GCD(x_{1}, x_{2}, ..., x_{k}) = 1$ means that for any prime $p$, there exist i such that $x_{i}$ is not dividable by $p$. So we only care about what prime factors a number contain. (So for example, 12 -> {2, 3}, 6 -> {2, 3}, 9 -> {3]}) The second observation is: If $x  \\le  10^{9}$ then it has at most 9 prime factors. So after we select one number, we only care about these 9 or less primes. Then this problem equals to set covering problem (SCP), it can be done by mask DP. It can run in about O(2^9 * n^2).",
    "code": "#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <vector>\n#include <cstdio>\n#include <cmath>\n#include <map>\n#include <set>\nusing namespace std;\n//#pragma comment(linker,\"/STACK:102400000,102400000\")\nint n, N; \nint x[301]; \nint cost[301]; \nint ans = 1000000000;\n\nint m[301];\nint DP[301][1<<9];\n \nint dp(int cur, int mask)\n{\n\tif(cur == n+1)\n\t{\n\t\tif(mask == (1<<N)-1)\n\t\t\treturn 0;\n\t\treturn 1000000000;\n\t}\n\tint &ret = DP[cur][mask];\n\tif(ret != -1) return ret;\n\tret = 1000000000;\n\tret = min(ret, dp(cur + 1, mask));\n\tret = min(ret, dp(cur + 1, mask | m[cur]) + cost[cur]);\n\treturn ret;\n}\n\nint MAIN() \n{ \n    cin >> n; \n    for(int i = 1; i <= n; i++) \n    { \n        cin >> x[i]; \n    } \n    for(int i = 1; i <= n; i++) \n        cin >> cost[i]; \n    for(int i = 1; i <= n; i++)\n    {\n    \tvector <int> pFactors;\n    \tint t = x[i];\n    \tfor(int j = 2; j*j <= t; j++)\n    \t\tif(t % j == 0)\n    \t\t{\n    \t\t\tpFactors.push_back(j);\n    \t\t\twhile(t % j == 0)\n    \t\t\t\tt /= j;\n    \t\t}\n    \tif(t > 1)\n    \t\tpFactors.push_back(t);\n    \tN = pFactors.size();\n\n    \tfor(int j = 1; j <= n; j++)\n    \t{\n    \t\tm[j] = 0;\n    \t\tfor(int k = 0; k < N; k++)\n    \t\t\tif(x[j] % pFactors[k] != 0)\n    \t\t\t\tm[j] |= (1<<k);\n    \t}\n    \tmemset(DP, 0xff, sizeof(DP));\n    \tans = min(ans, cost[i] + dp(1, 0));\n    }\n    if(ans == 1000000000) \n        ans = -1; \n    cout << ans << endl; \n    return 0; \n} \n \nint main() \n{ \n    #ifdef LOCAL_TEST \n        freopen(\"in.txt\", \"r\", stdin); \n        freopen(\"out.txt\", \"w\", stdout); \n    #endif \n    ios :: sync_with_stdio(false); \n    cout << fixed << setprecision(16); \n    return MAIN(); \n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "510",
    "index": "E",
    "title": "Fox And Dinner",
    "statement": "Fox Ciel is participating in a party in Prime Kingdom. There are $n$ foxes there (include Fox Ciel). The i-th fox is $a_{i}$ years old.\n\nThey will have dinner around some round tables. You want to distribute foxes such that:\n\n- Each fox is sitting at some table.\n- Each table has at least 3 foxes sitting around it.\n- The sum of ages of any two adjacent foxes around each table should be a prime number.\n\nIf $k$ foxes $f_{1}$, $f_{2}$, ..., $f_{k}$ are sitting around table in clockwise order, then for $1 ≤ i ≤ k - 1$: $f_{i}$ and $f_{i + 1}$ are adjacent, and $f_{1}$ and $f_{k}$ are also adjacent.\n\nIf it is possible to distribute the foxes in the desired manner, find out a way to do that.",
    "tutorial": "First finding is: if $a + b$ is a prime, then one of them is an odd number, another is an even number. (that's why we set $2  \\le  x_{i}$) Then we could find: every odd number have exactly 2 even number as neighborhood, and every even number have exactly 2 odd number as neighborhood. And that means we need $|#even| = |#odd|$ to have a solution. So it looks like bipartite graph matching, but every element matched 2 elements. And in fact it can be handled by maxflow: For each odd number, we add a node on the left side and link it from source with capacity equals to 2, and for each even number, we add a node on the right side and link it to sink with capacity equals to 2. And if sum of two numbers is a prime number, we link them with capacity equals to 1. Then we solve the max flow, it have solution if and only if $maxflow = 2 * |#even|$. We can construct the answer(cycles) from the matches.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n;\nint x[201];\nvector <int> id1;\nvector <int> idOdd, idEven;\n\n#define MAXN 200001\n\nint maxint = ~0U>>1;\nint flow;\nint pi[MAXN+1], v[MAXN+1];\nint S, T;\n\nstruct etype\n{\n\tint t, c;\n\tetype* next;\n\tetype* pair;\n\tetype(){next=0;}\n\tetype(int _t, int _c, etype* _n){t=_t, c=_c, next=_n;}\n}*e[MAXN+1], *eb[MAXN+1], *Pe, *Pool;\n\nint aug(int w, int lim)\n{\n\tint t;\n\tv[w] = 1;\n\tif(w == T)\n\t{\n\t\tflow += lim;\n\t\treturn lim;\n\t}\n\tfor(etype *& i=e[w]; i; i = i->next)\n\t\tif(i->c && !v[i->t] && pi[w] == pi[i->t] + 1)\n\t\t\tif(t = aug(i->t, min(lim, i->c)))\n\t\t\t\treturn i->c -= t, i->pair->c += t, t;\n\treturn 0;\n}\n\nbool fix()\n{\n\tint t = maxint;\n\tfor(int i = S; i <= T; i++)\n\t\tif(v[i])\n\t\t{\n\t\t\tfor(etype *j = eb[i]; j; j = j->next)\n\t\t\t\tif(j->c && !v[j->t])\n\t\t\t\t\tt = min(t, pi[j->t] + 1 - pi[i]);\n\t\t}\n\tif(t == maxint)\n\t\treturn 0;\n\n\tfor(int i = S; i <= T; i++)\n\t\tif(v[i])\n\t\t\te[i] = eb[i], pi[i] += t;\n\treturn 1;\n}\n\netype* addedge(int s, int t, int c)\n{\n\tetype * ret;\n\t++Pe;\n\tret = Pe;\n\tPe->t = t, Pe->c = c, Pe->next = e[s];\n\te[s] = Pe;\n\t++Pe;\n\tPe->t = s, Pe->c = 0, Pe->next = e[t];\n\te[t] = Pe;\n\te[s]->pair=e[t];\n\te[t]->pair=e[s];\n\treturn ret;\n}\n\nvoid prepare()\n{\n\tif(Pool == NULL)\n\t\tPool = new etype[1000001];\n\tPe = Pool;\n\tmemset(e, 0, sizeof(e));\n}\n\nint MaxFlow()\n{\n\tflow = 0;\n\tmemcpy(eb, e, sizeof(e));\n\tmemset(pi, 0, sizeof(pi));\n\tdo\n\t{\n\t\tdo\n\t\tmemset(v, 0, sizeof(v));\n\t\twhile(aug(S, maxint));\n\t}\n\twhile(fix());\n\treturn flow;\n}\n\n/*  Note\n\t1. Set maxNodes here: #define MAXN 200001\n\t2. Set maxEdges here: Pool = new etype[1000001];\n\t3. S must be the min id, T must be the max id\n*/\n\n/*  Eaxmple\n\tprepare();\n\tS = 1, T = 2;\n\taddedge(1, 2, 3);\n\tcout << MaxFlow() << endl;\n*/\n\nint isPrime(int x)\n{\n\tif(x < 2) return false;\n\tfor(int i = 2; i * i <= x; i++)\n\t\tif(x % i == 0)\n\t\t\treturn false;\n\treturn true;\n}\n\nvector <int> e2[201];\netype *flowEdge[201][201];\nbool visited[201];\n\nint MAIN()\n{\n\tcin >> n;\n\tint nOdd = 0, nEven = 0;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tcin >> x[i];\n\t\tif(x[i] > 1 && x[i] % 2 == 0)\n\t\t{\n\t\t\tnEven ++;\n\t\t\tidEven.push_back(i);\n\t\t}\n\t\tif(x[i] > 1 && x[i] % 2 == 1)\n\t\t{\n\t\t\tnOdd ++;\n\t\t\tidOdd.push_back(i);\n\t\t}\n\t}\n\tint needOne = nEven - nOdd;\n\tint oneIn = 0, oneOut = 0;\n\tfor(int i = 1; i <= n; i++)\n\t\tif(x[i] == 1)\n\t\t{\n\t\t\tif(needOne > 0)\n\t\t\t{\n\t\t\t\tidOdd.push_back(i);\n\t\t\t\toneIn ++;\n\t\t\t\tneedOne --;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tid1.push_back(i);\n\t\t\t\toneOut ++;\n\t\t\t}\n\t\t}\n\t\n\tif((oneIn == false && (oneOut == 1 || oneOut == 2)) || (idOdd.size() != idEven.size()))\n\t{\n\t\tcout << \"Impossible\" << endl;\n\t\treturn 0;\n\t}\n\t//cout << oneIn << \" / \" << oneOut << endl;\n\n\tint eachSide = idOdd.size();\n\tS = 1;\n\tT = 2 * (1 + eachSide);\n\tprepare();\n\tfor(int i = 0; i < eachSide; i++)\n\t\taddedge(S, 2 + i, 2);\n\tfor(int i = 0; i < eachSide; i++)\n\t\taddedge(2 + eachSide + i, T, 2);\n\tfor(int i = 0; i < eachSide; i++)\n\t\tfor(int j = 0; j < eachSide; j++)\n\t\t\tif(isPrime(x[idOdd[i]] + x[idEven[j]]))\n\t\t\t{\n\t\t\t\tif(x[idOdd[i]] == 1 && oneIn > 0 && oneOut > 0)\n\t\t\t\t{\n\t\t\t\t\tflowEdge[i][j] = addedge(2 + i, 2 + eachSide + j, 2);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tflowEdge[i][j] = addedge(2 + i, 2 + eachSide + j, 1);\n\t\t\t\t//cout << i << \" \" << j << \" : \" << x[idOdd[i]] << \" + \" << x[idEven[j]] << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t\tflowEdge[i][j] = NULL;\n\tint f = MaxFlow();\n\n\tif(f != 2 * eachSide)\n\t{\n\t\tcout << \"Impossible\" << endl;\n\t}\n\telse\n\t{\n\t\tvector< vector <int> > ans, one;\n\t\tif(id1.size() != 0)\n\t\t{\n\t\t\tif(oneIn > 0)\n\t\t\t\tone.push_back(id1);\n\t\t\telse\n\t\t\t\tans.push_back(id1);\n\t\t}\n\t\tfor(int i = 0; i < eachSide; i++)\n\t\t\tfor(int j = 0; j < eachSide; j++)\n\t\t\t\tif(flowEdge[i][j] != NULL)\n\t\t\t\t\tif(flowEdge[i][j] -> pair -> c > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint a = idOdd[i];\n\t\t\t\t\t\tint b = idEven[j];\n\t\t\t\t\t\te2[a].push_back(b);\n\t\t\t\t\t\te2[b].push_back(a);\n\t\t\t\t\t}\n\t\tmemset(visited, false, sizeof(visited));\n\t\tfor(int i = 1; i <= n; i++)\n\t\t\tif(visited[i] == false && e2[i].size() > 0)\n\t\t\t{\n\t\t\t\tvector <int> t;\n\t\t\t\tint cur = i;\n\t\t\t\tvisited[cur] = true;\n\t\t\t\tt.push_back(i);\n\t\t\t\twhile(true)\n\t\t\t\t{\n\t\t\t\t\tif(visited[e2[cur][0]] == false)\n\t\t\t\t\t\tcur = e2[cur][0];\n\t\t\t\t\telse if(e2[cur].size() > 1 && visited[e2[cur][1]] == false)\n\t\t\t\t\t\tcur = e2[cur][1];\n\t\t\t\t\telse\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tt.push_back(cur);\n\t\t\t\t\tvisited[cur] = true;\n\n\t\t\t\t}\n\t\t\t\tint pos1 = -1;\n\t\t\t\tfor(int j = 0; j < t.size(); j++)\n\t\t\t\t\tif(x[t[j]] == 1)\n\t\t\t\t\t\tpos1 = j;\n\t\t\t\tif(pos1 == -1 || oneIn == false || oneOut == false)\n\t\t\t\t\tans.push_back(t);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvector <int> t2;\n\t\t\t\t\tfor(int j = pos1; j < t.size(); j++)\n\t\t\t\t\t\tt2.push_back(t[j]);\n\t\t\t\t\tfor(int j = 0; j < pos1; j++)\n\t\t\t\t\t\tt2.push_back(t[j]);\n\t\t\t\t\tone.push_back(t2);\n\t\t\t\t}\n\t\t\t}\n\n\t\tif(one.size() > 0)\n\t\t{\n\t\t\tvector <int> t;\n\t\t\tfor(int i = 0; i < one.size(); i++)\n\t\t\t\tfor(int j = 0; j < one[i].size(); j++)\n\t\t\t\t\tt.push_back(one[i][j]);\n\t\t\tans.push_back(t);\n\t\t}\n\t\tcout << ans.size() << endl;\n\t\tfor(int i = 0; i < ans.size(); i++)\n\t\t{\n\t\t\tcout << ans[i].size() << \" \";\n\t\t\tfor(int j = 0; j < ans[i].size(); j++)\n\t\t\t{\n\t\t\t\tcout << ans[i][j] << (j == ans[i].size() - 1 ? \"\\n\" : \" \");\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nint main()\n{\n\t#ifdef LOCAL_TEST\n\t\tfreopen(\"in.txt\", \"r\", stdin);\n\t\tfreopen(\"out.txt\", \"w\", stdout);\n\t#endif\n\tios :: sync_with_stdio(false);\n\tcout << fixed << setprecision(16);\n\treturn MAIN();\n}",
    "tags": [
      "flows"
    ],
    "rating": 2300
  },
  {
    "contest_id": "512",
    "index": "D",
    "title": "Fox And Travelling",
    "statement": "Fox Ciel is going to travel to New Foxland during this summer.\n\nNew Foxland has $n$ attractions that are linked by $m$ undirected roads. Two attractions are called adjacent if they are linked by a road. Fox Ciel has $k$ days to visit this city and each day she will visit exactly one attraction.\n\nThere is one important rule in New Foxland: you can't visit an attraction if it has more than one adjacent attraction that you haven't visited yet.\n\nAt the beginning Fox Ciel haven't visited any attraction. During her travelling she may move aribtrarly between attraction. After visiting attraction $a$, she may travel to \\textbf{any} attraction $b$ satisfying conditions above that hasn't been visited yet, even if it is not reachable from $a$ by using the roads (Ciel uses boat for travelling between attractions, so it is possible).\n\nShe wants to know how many different travelling plans she can make. Calculate this number modulo $10^{9} + 9$ for every $k$ from $0$ to $n$ since she hasn't decided for how many days she is visiting New Foxland.",
    "tutorial": "We could find that some nodes cannot be visited. And more specific, if one node is in a cycle then it cannot be visited. So what about the structure of nodes that we can visit? Let's first find a way to get all nodes that could be visited. We can deal with this by something like biconnected decomposition, but that is not easy to implement. In fact we can use this simple method: each time we pick one node that have at most 1 neighborhood and delete it. Repeat this process until we can't do it anymore. We could find these nodes are actually belonging to these 2 kinds: 1. A tree. 2. Rooted tree. (that means, the root is attached to a cycle) The rooted tree case is simple: we can solve it by tree DP. The state will be dp[i][j] = the way to remove j nodes in the subtree rooted at i. Then how to solve the unrooted tree case? The way to deal with that is to transform it into rooted case. We have 2 solution: We select one unvisited node as the root by some rules: for example, we select one with minimal index. Then we just need to modify the DP a bit to adjust this additional condition. We could find if the tree has n nodes and we visit k nodes in the end, then there will be max(1, n-k) ways to choose the root. That means if we choose every node as the root and sum up them, we will count this case exactly max(1, n-k) times. So we just do the rooted DP for from node n times, and divide max(1, n-k) for ans[k]. The overall complicity is $O(n^{4})$, and it can be optimize into $O(n^{3})$ if you like.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <complex>\n#include <cstring>\n#include <cstdlib>\n#include <string>\n#include <vector>\n#include <cstdio>\n#include <cmath>\n#include <map>\n#include <set>\nusing namespace std;\n//#pragma comment(linker,\"/STACK:102400000,102400000\")\n\nconst int MAXN = 101; // (mod - 1) % MAXN == 0\nconst int MAXM = 1000001;\nlong long mod = 1000000009LL;\n\nlong long power(long long a, long long b)\n{\n\tlong long ret = 1;\n\twhile(b)\n\t{\n\t\tif(b&1)\n\t\t\tret = (ret * a) % mod;\n\t\ta = (a * a) % mod;\n\t\tb /= 2;\n\t}\n\treturn ret;\n}\n\nlong long inv(long long x)\n{\n\treturn power(x, mod - 2);\n}\n\nlong long factorial[MAXN];\nlong long invFactorial[MAXN];\n\nlong long C(int aPlusb, int a)\n{\n\tint b = aPlusb - a;\n\tif(a < 0 || b < 0) return 0;\n\tlong long ret = invFactorial[a] * invFactorial[b];\n\tret %= mod;\n\tret *= factorial[aPlusb];\n\tret %= mod;\n\treturn ret;\n}\n\nstruct dpValue\n{\n\tlong long x[MAXN];\n\tdpValue()\n\t{\n\t\tmemset(x, 0, sizeof(x));\n\t}\n};\n\nint cntCombine = 0;\n\ndpValue combine(dpValue A, dpValue B)\n{\n\tint maxNonZeroA = 0;\n\tint maxNonZeroB = 0;\n\tfor(int i = 0; i < MAXN; i++)\n\t{\n\t\tif(A.x[i] != 0)\n\t\t\tmaxNonZeroA = i;\n\t\tif(B.x[i] != 0)\n\t\t\tmaxNonZeroB = i;\n\t}\n\n\tcntCombine ++;\n\tdpValue ret;\n\tfor(int i = 0; i <= maxNonZeroA; i++)\n\t\tfor(int j = 0; j <= maxNonZeroB && i+j < MAXN; j++)\n\t\t{\n\t\t\tret.x[i+j] += ((A.x[i] * B.x[j]) % mod) * C(i+j, i);\n\t\t\tret.x[i+j] %= mod;\n\t\t}\n\treturn ret;\n}\n\nvector <int> nodeList;\n\nvector <int> e[MAXN];\nint cntNodes[MAXN];\n\ndpValue dp[MAXN];\n\nvoid dfsForSon(int cur, int from)\n{\n\tnodeList.push_back(cur);\n\tcntNodes[cur] = 1;\n\tfor(int i = 0; i < e[cur].size(); i++)\n\t{\n\t\tint t = e[cur][i];\n\t\tif(t == from) continue;\n\t\tdfsForSon(t, cur);\n\t\tcntNodes[cur] += cntNodes[t];\n\t}\n}\n\nvoid prepare()\n{\n\tfactorial[0] = 1;\n\tfor(int i = 1; i < MAXN; i++)\n\t\tfactorial[i] = (factorial[i-1] * i) % mod;\n\tfor(int i = 0; i < MAXN; i++)\n\t\tinvFactorial[i] = inv(factorial[i]);\n}\n\ndpValue pointwiseSum(dpValue A, dpValue B)\n{\n\tdpValue ret;\n\tfor(int i = 0; i < MAXN; i++)\n\t\tret.x[i] = (A.x[i] + B.x[i]) % mod;\n\treturn ret;\n}\n\ndpValue dfs(int cur, int from)\n{\n\tdpValue ret;\n\tret.x[0] = 1;\n\tfor(int i = 0; i < e[cur].size(); i++)\n\t{\n\t\tint t = e[cur][i];\n\t\tif(t == from) continue;\n\t\tret = combine(ret, dfs(t, cur));\n\t}\n\tfor(int i = 0; i < MAXN; i++)\n\t\tif(ret.x[i] == 0)\n\t\t{\n\t\t\tret.x[i] = ret.x[i-1];\n\t\t\tbreak;\n\t\t}\n\t/*cout << cur << \" \" << from << \" : \";\n\tfor(int i = 0; i <= 2; i++)\n\t\tcout << ret.x[i] << \" \";\n\tcout << endl;*/\n\treturn ret;\n}\n\ndpValue solve(int cur, bool rooted)\n{\n\tdfsForSon(cur, -1);\n\tif(rooted == true)\n\t{\n\t\tnodeList.clear();\n\t\treturn dfs(cur, -1);\n\t}\n\n\tint totalNodes = cntNodes[cur];\n\n\tdpValue sum;\n\tfor(int i = 0; i < nodeList.size(); i++)\n\t{\n\t\tsum = pointwiseSum(sum, dfs(nodeList[i], -1));\n\t}\n\n\tfor(int i = 0; i <= totalNodes; i++)\n\t{\n\t\tlong long v = sum.x[i];\n\t\tv *= inv(max(1, totalNodes - i));\n\t\tv %= mod;\n\t\tsum.x[i] = v;\n\t}\n\tnodeList.clear();\n\treturn sum;\n}\n\nint n, m;\nint eA[MAXM];\nint eB[MAXM];\nvector <int> edge[MAXN];\nint deg[MAXN];\nint q[2 * MAXM], now , z;\nbool inQ[MAXN];\nbool canReach[MAXN];\nbool visited[MAXN];\n\nvoid parse(int cur, int from)\n{\n\tvisited[cur] = true;\n\tfor(int i = 0; i < edge[cur].size(); i++)\n\t{\n\t\tint t = edge[cur][i];\n\t\tif(t == from) continue;\n\t\te[cur].push_back(t);\n\t\te[t].push_back(cur);\n\t\tparse(t, cur);\n\t}\n}\n\nint MAIN()\n{\n\tprepare();\n\tcin >> n >> m;\n\tmemset(canReach, false, sizeof(canReach));\n\tmemset(visited, false, sizeof(visited));\n\tmemset(inQ, false, sizeof(inQ));\n\tfor(int i = 1; i <= m; i++)\n\t{\n\t\tcin >> eA[i] >> eB[i];\n\t\tdeg[eA[i]] ++;\n\t\tdeg[eB[i]] ++;\n\t\tedge[eA[i]].push_back(eB[i]);\n\t\tedge[eB[i]].push_back(eA[i]);\n\t}\n\tnow = 1, z = 0;\n\tfor(int i = 1; i <= n; i++)\n\t\tif(deg[i] <= 1)\n\t\t{\n\t\t\tinQ[i] = true;\n\t\t\tq[++z] = i;\n\t\t}\n\twhile(now <= z)\n\t{\n\t\tint x = q[now];\n\t\tcanReach[x] = true;\n\t\tfor(int i = 0; i < edge[x].size(); i++)\n\t\t{\n\t\t\tint t = edge[x][i];\n\t\t\tdeg[t] --;\n\t\t\tif(deg[t] <= 1 && inQ[t] == false)\n\t\t\t{\n\t\t\t\tinQ[t] = true;\n\t\t\t\tq[++z] = t;\n\t\t\t}\n\t\t}\n\t\t++ now;\n\t}\n\t\n\tdpValue finalResult;\n\tfinalResult.x[0] = 1;\n\n\tfor(int i = 1; i <= m; i++)\n\t{\n\t\tif(canReach[eA[i]] != canReach[eB[i]])\n\t\t{\n\t\t\tif(canReach[eB[i]])\n\t\t\t\tswap(eA[i], eB[i]);\n\t\t\tparse(eA[i], eB[i]);\n\t\t\tfinalResult = combine(finalResult, solve(eA[i], true));\n\t\t}\n\t}\n\n\tfor(int i = 1; i <= n; i++)\n\t\tif(visited[i] == false && canReach[i] == true)\n\t\t{\n\t\t\tparse(i, -1);\n\t\t\tfinalResult = combine(finalResult, solve(i, false));\n\t\t}\n\t\n\tfor(int i = 0; i <= n; i++)\n\t{\n\t\tlong long v = finalResult.x[i];\n\t\tcout << v << endl;\n\t}\n\t//cout << \"time = \" << clock() - start << endl;\n\t//cout << \"# \" << cntCombine << endl;\n\treturn 0;\n}\n\nint main()\n{\n\t#ifdef LOCAL_TEST\n\t\tfreopen(\"in.txt\", \"r\", stdin);\n\t\tfreopen(\"out.txt\", \"w\", stdout);\n\t#endif\n\tios :: sync_with_stdio(false);\n\tcout << fixed << setprecision(16);\n\treturn MAIN();\n}",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "512",
    "index": "E",
    "title": "Fox And Polygon",
    "statement": "Fox Ciel just designed a puzzle game called \"Polygon\"! It is played using triangulations of a regular $n$-edge polygon. The goal is to transform one \\underline{triangulation} to another by some tricky rules.\n\n\\underline{Triangulation} of an $n$-edge poylgon is a set of $n - 3$ diagonals satisfying the condition that no two diagonals share a common internal point.\n\nFor example, the initial state of the game may look like (a) in above figure. And your goal may look like (c). In each step you can choose a diagonal inside the polygon (but not the one of edges of the polygon) and \\underline{flip} this diagonal.\n\nSuppose you are going to \\underline{flip} a diagonal $a – b$. There always exist two triangles sharing $a – b$ as a side, let's denote them as $a – b – c$ and $a – b – d$. As a result of this operation, the diagonal $a – b$ is replaced by a diagonal $c – d$. It can be easily proven that after \\underline{flip} operation resulting set of diagonals is still a \\underline{triangulation} of the polygon.\n\nSo in order to solve above case, you may first \\underline{flip} diagonal $6 – 3$, it will be replaced by diagonal $2 – 4$. Then you \\underline{flip} diagonal $6 – 4$ and get figure (c) as result.\n\nCiel just proved that for any starting and destination triangulations this game has a solution. She wants you to solve it in no more than $20 000$ steps for any puzzle satisfying $n ≤ 1000$.",
    "tutorial": "Triangulation of polygon is something hard to think about. So the first key observation is that, we can transform this task into operations on rooted trees! One Triangulation of polygon can be mapping to one rooted tree. And the flip operation can be mapping to the rotation of trees. (It is the operation we used to balance our BST) You can find the mapping from above picture. The red lines indicate the edge that will be flipped and the nodes we rotated. Then we should find a standard shape of the tree, and solve this task: how to rotate any tree into this standard shape? My solution is to choose the balanced tree as standard shape. The way to do that is this: find the node that the index is the middle number, rotate it to the top(that what we did for splay tree), and do the same thing for each subtree. It is easy to see it could work in $O(nlogn)$ steps.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n;\nvector <int> e[1001];\nbool have[1001];\n\nstruct node\n{\n\tint leftMark, rightMark;\n\tnode* sonLeft, *sonRight;\n\tvoid updateMark()\n\t{\n\t\tleftMark = sonLeft->leftMark;\n\t\trightMark = sonRight->rightMark;\n\t}\n}*start, *want;\n\nstruct step\n{\n\tint fromA, fromB;\n\tint toA, toB;\n};\n\nnode* addNode(int L, int R, int from)\n{\n\tnode *t = new node();\n\tt->leftMark = L;\n\tt->rightMark = R;\n\tif(L == R+1)\n\t{\n\t\treturn t;\n\t}\n\tfor(int i = 0; i < e[L].size(); i++)\n\t\tif(e[L][i] != from)\n\t\t\thave[e[L][i]] = true;\n\tint M = -1;\n\tfor(int j = 0; j < e[R].size(); j++)\n\t\tif(e[R][j] != from)\n\t\t\tif(have[e[R][j]])\n\t\t\t\tM = e[R][j];\n\tfor(int i = 0; i < e[L].size(); i++)\n\t\thave[e[L][i]] = false;\n\tt->sonLeft = addNode(L, M, R);\n\tt->sonRight = addNode(M, R, L);\n\treturn t;\n}\n\nnode* input()\n{\n\tfor(int i = 1; i <= n; i++)\n\t\te[i].clear();\n\tfor(int i = 1; i <= n-3; i++)\n\t{\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\te[a].push_back(b);\n\t\te[b].push_back(a);\n\t}\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tint j = i+1;\n\t\tif(i == n) j = 1;\n\t\te[i].push_back(j);\n\t\te[j].push_back(i);\n\t}\n\treturn addNode(n, 1, -1);\n}\n\nvoid print(node *p, string append)\n{\n\tcout << append << p->leftMark << \" \" << p->rightMark << endl;\n\tif(p->sonLeft != NULL)\n\t\tprint(p->sonLeft, append + \"\\t\");\n\tif(p->sonRight != NULL)\n\t\tprint(p->sonRight, append + \"\\t\");\n}\n\nvector <step> record;\n\nvoid rotateToRight(node *r)\n{\n\tstep t;\n\tnode *s = r->sonLeft;\n\tnode *a = s->sonLeft;\n\tnode *b = s->sonRight;\n\tnode *c = r->sonRight;\n\tt.fromA = s->leftMark;\n\tt.fromB = s->rightMark;\n\tr->sonLeft = a;\n\tr->sonRight = s;\n\ts->sonLeft = b;\n\ts->sonRight = c;\n\ts->updateMark();\n\tr->updateMark();\n\tt.toA = s->leftMark;\n\tt.toB = s->rightMark;\n\trecord.push_back(t);\n}\n\nvoid rotateToLeft(node *r)\n{\n\tstep t;\n\tnode *s = r->sonRight;\n\tnode *a = r->sonLeft;\n\tnode *b = s->sonLeft;\n\tnode *c = s->sonRight;\n\tt.fromA = s->leftMark;\n\tt.fromB = s->rightMark;\n\tr->sonLeft = s;\n\tr->sonRight = c;\n\ts->sonLeft = a;\n\ts->sonRight = b;\n\ts->updateMark();\n\tr->updateMark();\n\tt.toA = s->leftMark;\n\tt.toB = s->rightMark;\n\trecord.push_back(t);\n}\n\nvoid rotateMiddleToRoot(node *p, int middle)\n{\n\tint myMiddle = p->sonLeft->rightMark;\n\tif(myMiddle == middle)\n\t\treturn;\n\tif(myMiddle < middle)\n\t{\n\t\trotateMiddleToRoot(p->sonLeft, middle);\n\t\trotateToRight(p);\n\t}\n\telse if(myMiddle > middle)\n\t{\n\t\trotateMiddleToRoot(p->sonRight, middle);\n\t\trotateToLeft(p);\n\t}\n}\n\nvoid normalize(node *p)\n{\n\tif(p->leftMark - p->rightMark <= 2) return;\n\tint middle = (p->leftMark + p->rightMark) / 2;\n\trotateMiddleToRoot(p, middle);\n\tnormalize(p->sonLeft);\n\tnormalize(p->sonRight);\n}\n\nint MAIN()\n{\n\tmemset(have, 0, sizeof(have));\n\tcin >> n;\n\tstart = input();\n\tnormalize(start);\n\tvector <step> record1 = record;\n\trecord.clear();\n\twant = input();\n\tnormalize(want);\n\n\tcout << record.size() + record1.size() << endl;\n\n\tfor(int i = 0; i < record1.size(); i++)\n\t\tcout << record1[i].fromA << \" \" << record1[i].fromB << endl;\n\tfor(int i = record.size()-1; i >= 0; i--)\n\t\tcout << record[i].toA << \" \" << record[i].toB << endl;\n\treturn 0;\n}\n\nint main()\n{\n\t#ifdef LOCAL_TEST\n\t\tfreopen(\"in.txt\", \"r\", stdin);\n\t\tfreopen(\"out.txt\", \"w\", stdout);\n\t#endif\n\tios :: sync_with_stdio(false);\n\tcout << fixed << setprecision(16);\n\treturn MAIN();\n}",
    "tags": [
      "constructive algorithms",
      "divide and conquer"
    ],
    "rating": 2900
  },
  {
    "contest_id": "514",
    "index": "A",
    "title": "Chewbaсca and Number",
    "statement": "Luke Skywalker gave Chewbacca an integer number $x$. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit $t$ means replacing it with digit $9 - t$.\n\nHelp Chewbacca to transform the initial number $x$ to the minimum possible \\textbf{positive} number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.",
    "tutorial": "It is obvious that all the digits, which are greater than 4, need to be inverted. The only exception is 9, if it's the first digit. Complexity: $O(\\mathrm{number~length})$",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "514",
    "index": "B",
    "title": "Han Solo and Lazer Gun",
    "statement": "There are $n$ Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates $(x, y)$ on this plane.\n\nHan Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point $(x_{0}, y_{0})$. In one shot it can can destroy all the stormtroopers, situated on some line that crosses point $(x_{0}, y_{0})$.\n\nYour task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.\n\nThe gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.",
    "tutorial": "Let's run through every point, where the stormtroopers are situated. If in current point stormtroopers are still alive, let's make a shot and destroy every stormtrooper on the same line with gun and current point. Points $(x_{1}, y_{1})$, $(x_{2}, y_{2})$, $(x_{3}, y_{3})$ are on the same line, if $(x_{2} - x_{1})(y_{3} - y_{1}) = (x_{3} - x_{1})(y_{2} - y_{1})$. Complexity: $O(N^{2})$",
    "tags": [
      "brute force",
      "data structures",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "514",
    "index": "C",
    "title": "Watto and Mechanism",
    "statement": "Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with $n$ strings. Then the mechanism should be able to process queries of the following type: \"Given string $s$, determine if the memory of the mechanism contains string $t$ that consists of the same number of characters as $s$ and differs from $s$ in exactly one position\".\n\nWatto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of $n$ initial lines and $m$ queries. He decided to entrust this job to you.",
    "tutorial": "While adding a string to the set, let's count its polynomial hash and add it to an array. Then let's sort this array. Now, to know the query answer, let's try to change every symbol in the string and check with binary search if its hash can be found in the array (recounting hashes with $O(1)$ complexity). If the hash is found in the array, the answer is \"YES\", otherwise \"NO\". Complexity: $O(L\\log n)$, where $L$ is total length of all strings.",
    "tags": [
      "binary search",
      "data structures",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "514",
    "index": "D",
    "title": "R2D2 and Droid Army",
    "statement": "An army of $n$ droids is lined up in one row. Each droid is described by $m$ integers $a_{1}, a_{2}, ..., a_{m}$, where $a_{i}$ is the number of details of the $i$-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has $m$ weapons, the $i$-th weapon can affect all the droids in the army by destroying one detail of the $i$-th type (if the droid doesn't have details of this type, nothing happens to it).\n\nA droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most $k$ shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?",
    "tutorial": "To destroy all the droids on a segment of $l$ to $r$, we need to make $\\sum_{j=1}^{m}\\operatorname*{max}_{l\\leq l\\leq r}(c n t[i]|j])$ shots, where $cnt[i][j]$ - number of $j$-type details in $i$-th droid. Let's support two pointers - on the beginning and on the end of the segment, which we want to destroy all the droids on. If we can destroy droids on current segment, let's increase right border of the segment, otherwise increase left border, updating the answer after every segment change. Let's use a queue in order to find the segment maximum effectively. Complexity: $O(N M)$",
    "tags": [
      "binary search",
      "data structures",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "514",
    "index": "E",
    "title": "Darth Vader and Tree",
    "statement": "When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly $n$ sons, at that for each node, the distance between it an its $i$-th left child equals to $d_{i}$. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most $x$ from the root. The distance is the sum of the lengths of edges on the path between nodes.\n\nBut he has got used to this activity and even grew bored of it. 'Why does he do that, then?' — you may ask. It's just that he feels superior knowing that only he can solve this problem.\n\nDo you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo $10^{9} + 7$.",
    "tutorial": "It's easy to realize that $d p[i]=\\sum_{j=1}^{100}c n t[j]\\cdot d p[i-j]$, where $dp[i]$ is number of vertices, which are situated on a distance $i$ from the root, and $cnt[j]$ is number of children, which are situated on a distance $j$. Answer $a n s=\\sum_{i=0}^{x}d p[i]$. Let the dynamics condition Let's build a transformation matrix of $101  \\times  101$ size Now, to move to the next condition, we need to multiply A by B. So, if matrix $C = A \\cdot B^{x - 100}$, then the answer will be situated in the very right cell of this matrix. For $x < 100$ we'll find the answer using dynamics explained in the beginning. In order to find $B^{k}$ let's use binary power. Complexity: $O(101^{3}\\log x)$",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2200
  },
  {
    "contest_id": "515",
    "index": "A",
    "title": "Drazil and Date",
    "statement": "Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point $(0, 0)$ and Varda's home is located in point $(a, b)$. In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position $(x, y)$ he can go to positions $(x + 1, y)$, $(x - 1, y)$, $(x, y + 1)$ or $(x, y - 1)$.\n\nUnfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to $(a, b)$ and continue travelling.\n\nLuckily, Drazil arrived to the position $(a, b)$ successfully. Drazil said to Varda: \"It took me exactly $s$ steps to travel from my house to yours\". But Varda is confused about his words, she is not sure that it is possible to get from $(0, 0)$ to $(a, b)$ in exactly $s$ steps. Can you find out if it is possible for Varda?",
    "tutorial": "If Drazil chooses the shortest path from (0,0) to (a,b), it takes $|a| + |b|$ steps. So we know that all numbers less than $|a| + |b|$ are impossible to be the number of steps that Drazil took. Now consider when the number of steps is not less than $|a| + |b|$. When Drazil arrives at $(a, b)$, he can take two more steps such as $(a, b)$ -> $(a, b + 1)$ -> $(a, b)$ to remain at the same position. So we know that for all $s$ such that $s  \\ge  |a| + |b|$ and $(s - (|a| + |b|))%2 = 0$, there exists a way for Drazil to get to $(a, b)$ in exactly $s$ steps. The last part we should prove is that it's impossible for Drazil to arrive at (a,b) in exactly $s$ steps when $(s - (|a| + |b|))%2 = 1$. We can color all positions $(x, y)$ where $(x + y)%2 = 0$ as white and color other points as black. After each step, the color of the position you're at always changes. So we know that it's impossible for Drazil to get to $(a, b)$ in odd/even steps if the color of $(a, b)$ is white/black. Conclusion: If $s  \\ge  |a| + |b|$ and $(s - (|a| + |b|))%2 = 0$ print \"Yes\", Otherwise print \"No\". Time Complexity: $O(1)$.",
    "code": "#include <bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define RI(X) scanf(\"%d\", &(X))\n#define RII(X, Y) scanf(\"%d%d\", &(X), &(Y))\n#define RIII(X, Y, Z) scanf(\"%d%d%d\", &(X), &(Y), &(Z))\n#define DRI(X) int (X); scanf(\"%d\", &X)\n#define DRII(X, Y) int X, Y; scanf(\"%d%d\", &X, &Y)\n#define DRIII(X, Y, Z) int X, Y, Z; scanf(\"%d%d%d\", &X, &Y, &Z)\n#define RS(X) scanf(\"%s\", (X))\n#define CASET int ___T, case_n = 1; scanf(\"%d \", &___T); while (___T-- > 0)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define PII pair<int,int>\n#define VPII vector<pair<int,int> >\n#define PLL pair<long long,long long>\n#define F first\n#define S second\ntypedef long long LL;\nusing namespace std;\nconst int MOD = 1e9+7;\nconst int SIZE = 1e6+10;\nint main(){\n    DRIII(a,b,n);\n    if(n<abs(a)+abs(b)||(n-abs(a)-abs(b))%2)puts(\"No\");\n    else puts(\"Yes\");\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "515",
    "index": "B",
    "title": "Drazil and His Happy Friends",
    "statement": "Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.\n\nThere are $n$ boys and $m$ girls among his friends. Let's number them from $0$ to $n - 1$ and $0$ to $m - 1$ separately. In $i$-th day, Drazil invites $(i\\bmod n)$-th boy and $(i\\bmod m)$-th girl to have dinner together (as Drazil is programmer, $i$ starts from $0$). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.\n\nDrazil wants to know whether he can use this plan to make all his friends become happy at some moment.",
    "tutorial": "You may notice that Drazil invites his friends periodically, and the period of invitation patterns is at most $n * m$ (because there are only $n * m$ possible pairs of boys and girls). So if no one changes from unhappy to happy in consecutive $n * m$ days, there won't be any changes anymore since then. We can simulate the process of having dinner until there are no status changes in consecutive $n * m$ days. Because there are only n+m people, it's easy to prove the simulation requires O($(n + m) * n * m$) days. But in fact, the simulation takes only O($n * m$) days.(More accurately, the bound is $(min(n, m) + 1) * (max(n, m) - 1)$ ) What happens? You can do some experiments by yourself. =) (you can suppose that only one person is happy in the beginning.) In fact, this problem can be solved in $O(n + m)$. Let $g$ be the greatest common divisor of $n$ and $m$. If the $i$-th person is happy, then all people with number $x$ satisfying $x\\equiv i({\\mod{g}})$ will become happy some day because of this person. So for each $0  \\le  i  \\le  g - 1$, we only need to check if there exists at least one person whose number mod $g$ is $i$ and is happy. If it exists for all $i$, the answer is 'Yes', otherwise the answer is 'No'.",
    "code": "#include <bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define RI(X) scanf(\"%d\", &(X))\n#define RII(X, Y) scanf(\"%d%d\", &(X), &(Y))\n#define RIII(X, Y, Z) scanf(\"%d%d%d\", &(X), &(Y), &(Z))\n#define DRI(X) int (X); scanf(\"%d\", &X)\n#define DRII(X, Y) int X, Y; scanf(\"%d%d\", &X, &Y)\n#define DRIII(X, Y, Z) int X, Y, Z; scanf(\"%d%d%d\", &X, &Y, &Z)\n#define RS(X) scanf(\"%s\", (X))\n#define CASET int ___T, case_n = 1; scanf(\"%d \", &___T); while (___T-- > 0)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define PII pair<int,int>\n#define VPII vector<pair<int,int> >\n#define PLL pair<long long,long long>\n#define F first\n#define S second\ntypedef long long LL;\nusing namespace std;\nconst int MOD = 1e9+7;\nconst int SIZE = 1e6+10;\nint h[SIZE];\nint main(){\n    DRII(n,m);\n    int gg=__gcd(n,m);\n    DRI(hn);\n    REP(i,hn){\n        DRI(x);\n        h[x%gg]=1;\n    }\n    DRI(hm);\n    REP(i,hm){\n        DRI(x);\n        h[x%gg]=1;\n    }\n    REP(i,gg){\n        if(!h[i]){\n            puts(\"No\");\n            return 0;\n        }\n    }\n    puts(\"Yes\");\n    return 0;\n}",
    "tags": [
      "brute force",
      "dsu",
      "meet-in-the-middle",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "515",
    "index": "C",
    "title": "Drazil and Factorial",
    "statement": "Drazil is playing a math game with Varda.\n\nLet's define $\\operatorname{F}(x)$ for positive integer $x$ as a product of factorials of its digits. For example, $\\mathbf{F}(\\,135)=\\,1!*31*51=720$.\n\nFirst, they choose a decimal number $a$ consisting of $n$ digits that contains at least one digit larger than $1$. This number may possibly start with leading zeroes. Then they should find maximum positive number $x$ satisfying following two conditions:\n\n1. $x$ doesn't contain neither digit $0$ nor digit $1$.\n\n2. $\\operatorname{F}(x)$ = $\\mathbf{F}(a)$.\n\nHelp friends find such number.",
    "tutorial": "Conclusion first: First, we transform each digit of the original number as follows: 0, 1 -> empty 2 -> 2 3 -> 3 4 -> 322 5 -> 5 6 -> 53 7 -> 7 8 -> 7222 9 -> 7332 Then, sort all digits in decreasing order as a new number, then it will be the answer. Proof: We can observe that our answer won't contain digits 4,6,8,9, because we can always transform digits 4,6,8,9 to more digits as in the conclusion, and it makes the number larger. Then, how can we make sure that the result is the largest after this transformation? We can prove the following lemma: For any positive integer $x$, if it can be written as the form $(2!)^{c2} * (3!)^{c3} * (5!)^{c5} * (7!)^{c7}$, there will be only one unique way. Suppose that there exists two ways to write down x in this form, we can assume that the two ways are $(2!)^{a2} * (3!)^{a3} * (5!)^{a5} * (7!)^{a7}$ and $(2!)^{b2} * (3!)^{b3} * (5!)^{b5} * (7!)^{b7}$. We find the largest $i$ such that $a_{i}  \\neq  b_{i}$, Then we know there exists at least one prime number whose factor is different in the two ways. But according to the Fundamental Theorem of Arithmetic, there is only one prime factorization of each integer. So we get a contradiction. After getting the result, we don't need to worry about other numbers being larger than ours. Time Complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define RI(X) scanf(\"%d\", &(X))\n#define RII(X, Y) scanf(\"%d%d\", &(X), &(Y))\n#define RIII(X, Y, Z) scanf(\"%d%d%d\", &(X), &(Y), &(Z))\n#define DRI(X) int (X); scanf(\"%d\", &X)\n#define DRII(X, Y) int X, Y; scanf(\"%d%d\", &X, &Y)\n#define DRIII(X, Y, Z) int X, Y, Z; scanf(\"%d%d%d\", &X, &Y, &Z)\n#define RS(X) scanf(\"%s\", (X))\n#define CASET int ___T, case_n = 1; scanf(\"%d \", &___T); while (___T-- > 0)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define PII pair<int,int>\n#define VPII vector<pair<int,int> >\n#define PLL pair<long long,long long>\n#define F first\n#define S second\ntypedef long long LL;\nusing namespace std;\nconst int MOD = 1e9+7;\nconst int SIZE = 1e6+10;\nstring ch[10]={\"\",\"\",\"2\",\"3\",\"223\",\"5\",\"53\",\"7\",\"7222\",\"7332\"};\nint main(){\n    DRI(n);\n    string str,an;\n    cin>>str;\n    REP(i,SZ(str))an+=ch[str[i]-'0'];\n    sort(ALL(an));\n    reverse(ALL(an));\n    cout<<an<<endl;\n    return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "515",
    "index": "D",
    "title": "Drazil and Tiles",
    "statement": "Drazil created a following problem about putting $1 × 2$ tiles into an $n × m$ grid:\n\n\"There is a grid with some cells that are empty and some cells that are occupied. You should use $1 × 2$ tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it.\"\n\nBut Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: \"how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' \".\n\nDrazil found that the constraints for this task may be much larger than for the original task!\n\nCan you solve this new problem?\n\nNote that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.",
    "tutorial": "Again we give conclusion first: First, view each cell as a vertex and connect two adjacent cells by an edge. Then, build a queue and push all vertices of degree 1 in it. Finally, in each iteration, we pop a vertex from the queue until the queue is empty. If the vertex is used, go to the next iteration. Otherwise, we put a tile on the vertex and its adjacent vertex, and erase these two vertices from the graph. If it yields a new vertex with degree 1, push it into the queue. When the queue is empty, if there are still some cells not covered by any tiles, the answer will be \"Not unique.\" It's easy to understand that if we can put tiles on all cells by the above steps, the result is correct. But how about the remaining cases? We will prove that when the degrees of all vertices are at least two, the solution is never unique. Suppose there is at least one solution. According to this solution, we can color those edges covered by tiles as black and color other edges as white. We can always find a cycle without any adjacent edges having the same colors. (I'll leave it as an exercise. You should notice that the graph is a bipartite graph first.) Then we can move the tiles from black edges to white edges. So if there is at least one solution, there are in fact at least two solutions. Time Complexity: $O(nm)$",
    "code": "#include <bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define RI(X) scanf(\"%d\", &(X))\n#define RII(X, Y) scanf(\"%d%d\", &(X), &(Y))\n#define RIII(X, Y, Z) scanf(\"%d%d%d\", &(X), &(Y), &(Z))\n#define DRI(X) int (X); scanf(\"%d\", &X)\n#define DRII(X, Y) int X, Y; scanf(\"%d%d\", &X, &Y)\n#define DRIII(X, Y, Z) int X, Y, Z; scanf(\"%d%d%d\", &X, &Y, &Z)\n#define RS(X) scanf(\"%s\", (X))\n#define CASET int ___T, case_n = 1; scanf(\"%d \", &___T); while (___T-- > 0)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define PII pair<int,int>\n#define VPII vector<pair<int,int> >\n#define PLL pair<long long,long long>\n#define F first\n#define S second\ntypedef long long LL;\nusing namespace std;\nconst int SIZE = 2e3+10;\nchar s[SIZE][SIZE];\nint deg[SIZE][SIZE];\nint dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};\nchar fl[2][8]={\"^<v>\",\"v>^<\"};\npair<int,int>bfs[SIZE*SIZE];\nint main(){\n    int ll=0,rr=0;\n    DRII(n,m);\n    REP(i,n)RS(s[i+1]+1);\n    int sp=0;\n    REPP(i,1,n+1)REPP(j,1,m+1){\n        REP(k,4){\n            int nx=i+dx[k];\n            int ny=j+dy[k];\n            if(s[nx][ny]=='.')deg[i][j]++;\n        }\n        if(s[i][j]=='.'){\n            sp++;\n            if(deg[i][j]==1)bfs[rr++]=MP(i,j);\n        }\n    }\n    while(ll<rr){\n        int x=bfs[ll].F;\n        int y=bfs[ll].S;\n        if(s[x][y]=='.'){\n            int nx,ny;\n            int id=-1;\n            bool suc=0;\n            REP(k,4){\n                nx=x+dx[k];\n                ny=y+dy[k];\n                id=k;\n                if(s[nx][ny]=='.'){\n                    suc=1;\n                    break;\n                }\n            }\n            if(!suc){\n                puts(\"Not unique\");\n                return 0;\n            }\n            s[x][y]=fl[0][id];\n            s[nx][ny]=fl[1][id];\n            deg[x][y]=0;\n            deg[nx][ny]=0;\n            REP(k,4){\n                int nnx=nx+dx[k];\n                int nny=ny+dy[k];\n                deg[nnx][nny]--;\n                if(deg[nnx][nny]==1)bfs[rr++]=MP(nnx,nny);\n            }\n        }\n        ll++;\n    }\n    REP(i,n)REP(j,m)if(s[i+1][j+1]=='.'){\n        puts(\"Not unique\");\n        return 0;\n    }\n    REP(i,n)puts(s[i+1]+1);\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "515",
    "index": "E",
    "title": "Drazil and Park",
    "statement": "Drazil is a monkey. He lives in a circular park. There are $n$ trees around the park. The distance between the $i$-th tree and ($i + 1$)-st trees is $d_{i}$, the distance between the $n$-th tree and the first tree is $d_{n}$. The height of the $i$-th tree is $h_{i}$.\n\nDrazil starts each day with the morning run. The morning run consists of the following steps:\n\n- Drazil chooses two different trees\n- He starts with climbing up the first tree\n- Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it\n- Then he finally climbs down the second tree.\n\nBut there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees.\n\nIf the two trees Drazil chooses are $x$-th and $y$-th, we can estimate the energy the morning run takes to him as $2(h_{x} + h_{y}) + dist(x, y)$. Since there are children on exactly one of two arcs connecting $x$ and $y$, the distance $dist(x, y)$ between trees $x$ and $y$ is uniquely defined.\n\nNow, you know that on the $i$-th day children play between $a_{i}$-th tree and $b_{i}$-th tree. More formally, if $a_{i} ≤ b_{i}$, children play around the trees with indices from range $[a_{i}, b_{i}]$, otherwise they play around the trees with indices from $[a_{i},n]\\cup[1,b_{i}]$.\n\nPlease help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day.",
    "tutorial": "There are many methods for this problem. I'll only explain the one that I used. Let's split a circle at some point (for example between 1 and n) and draw a picture twice (i. e. 1 2 3 ... n 1 2 3 ... n), thus changing the problem from a circle to a line. Remember that if two trees Drazil chooses are x and y, the energy he consumes is $d_{x} + d_{x + 1} + ... + d_{y - 1} + 2 * (h_{x} + h_{y})$. Now rewrite this formula to $(d_{1} + d_{2} + ... + d_{y - 1} + 2 * h_{y}) + (2 * h_{x} - (d_{1} + d_{2} + ... + d_{x - 1}))$ Denote $(d_{1} + d_{2} + ... + d_{k - 1} + 2 * h_{k})$ as $R_{k}$ and denote $(2 * h_{k} - (d_{1} + d_{2} + ... + d_{k - 1}))$ as $L_{k}$ When a query about range $[a, b]$ comes (The range $[a, b]$ is where Drazil can choose, but not the range where the children are playing), it's equivalent to querying the maximum value of $L_{u} + R_{v}$, where $u$ and $v$ are in $[a, b]$ and $u < v$. Another important thing is that $L_{u} + R_{v}$ always bigger than $L_{v} + R_{u}$ when $u < v$. So we can almost solve the problem just by finding the maximum value of $L_{u}$ and $R_{v}$ by RMQ separately and sum them up. However, there is a special case: $u = v$, but we can handle it by making RMQ find the two maximum values. Time Complexity: $O(n + m)$. (implement with $O(n\\log n+m)$) More information about RMQ: editorial from Topcoder",
    "code": "#include <bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define RI(X) scanf(\"%d\", &(X))\n#define RII(X, Y) scanf(\"%d%d\", &(X), &(Y))\n#define RIII(X, Y, Z) scanf(\"%d%d%d\", &(X), &(Y), &(Z))\n#define DRI(X) int (X); scanf(\"%d\", &X)\n#define DRII(X, Y) int X, Y; scanf(\"%d%d\", &X, &Y)\n#define DRIII(X, Y, Z) int X, Y, Z; scanf(\"%d%d%d\", &X, &Y, &Z)\n#define RS(X) scanf(\"%s\", (X))\n#define CASET int ___T, case_n = 1; scanf(\"%d \", &___T); while (___T-- > 0)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define PLL pair<long long,long long>\n#define F first\n#define S second\ntypedef long long LL;\nusing namespace std;\nconst int SIZE = 4e5+10;\nint d[SIZE],h[SIZE];\npair<LL,int> W[2][19][SIZE][2];\nint two[SIZE];\npair<LL,int> INF=MP(-1e18,-1);\nvoid fresh(pair<LL,int> target[],pair<LL,int> v){\n    if(v.S==target[0].S||v.S==target[1].S)return;\n    if(v.F>target[0].F){\n        target[1]=target[0];\n        target[0]=v;\n    }\n    else if(v.F>target[1].F){\n        target[1]=v;\n    }\n}\nLL query(int x,int y){\n    pair<LL,int>res[2][2];\n    int lv=two[y-x+1];\n    REP(i,2){\n        REP(j,2)res[i][j]=W[i][lv][x][j];\n        REP(j,2)fresh(res[i],W[i][lv][y-(1<<lv)+1][j]);\n    }\n    if(res[0][0].S!=res[1][0].S)return res[0][0].F+res[1][0].F;\n    return max(res[0][0].F+res[1][1].F,res[0][1].F+res[1][0].F);\n}\nint main(){\n    REP(i,19)two[1<<i]=i;\n    REPP(i,1,SIZE)\n        if(!two[i])two[i]=two[i-1];\n    DRII(n,m);\n    REP(i,n){\n        RI(d[i]);\n        d[i+n]=d[i];\n    }\n    REP(i,n){\n        RI(h[i]);\n        h[i+n]=h[i];\n    }\n    LL now=0;\n    REP(i,n*2){\n        W[0][0][i][0]=MP(now+h[i]*2,i);\n        W[1][0][i][0]=MP(-now+h[i]*2,i);\n        W[0][0][i][1]=W[1][0][i][1]=INF;\n        now+=d[i];\n    }\n    REP(j,2){\n        REPP(i,1,19){\n            REP(k,n*2){\n                REP(k2,2)W[j][i][k][k2]=W[j][i-1][k][k2];\n                if(k+(1<<(i-1))<n*2){\n                    fresh(W[j][i][k],W[j][i-1][k+(1<<(i-1))][0]);\n                    fresh(W[j][i][k],W[j][i-1][k+(1<<(i-1))][1]);\n                }\n            }\n        }\n    }\n    while(m--){\n        DRII(x,y);\n        x--;y--;\n        int rx=(y+1)%n;\n        int ry=(x-1+n)%n;\n        if(ry<rx)ry+=n;\n        printf(\"%I64d\\n\",query(rx,ry));\n    }\n    return 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2300
  },
  {
    "contest_id": "516",
    "index": "D",
    "title": "Drazil and Morning Exercise",
    "statement": "Drazil and Varda are the earthworm couple. They want to find a good place to bring up their children. They found a good ground containing nature hole. The hole contains many rooms, some pairs of rooms are connected by small tunnels such that earthworm can move between them.\n\nLet's consider rooms and small tunnels as the vertices and edges in a graph. This graph is a \\underline{tree}. In the other words, any pair of vertices has an unique path between them.\n\nEach room that is \\underline{leaf} in the graph is connected with a ground by a vertical tunnel. Here, \\underline{leaf} is a vertex that has only one outgoing edge in the graph.\n\nEach room is large enough only to fit one earthworm living in it. Earthworm can't live in a tunnel.\n\nDrazil and Varda have a plan to educate their children. They want all their children to do morning exercises immediately after getting up!\n\nWhen the morning is coming, all earthworm children get up in the same time, then each of them chooses the \\textbf{farthest} path to the ground for gathering with others (these children are lazy, so they all want to do exercises as late as possible).\n\nDrazil and Varda want the difference between the time first earthworm child arrives outside and the time the last earthworm child arrives outside to be not larger than $l$ (otherwise children will spread around the ground and it will be hard to keep them exercising together).\n\nAlso, The rooms that are occupied by their children should form a \\underline{connected} set. In the other words, for any two rooms that are occupied with earthworm children, all rooms that lie on the path between them should be occupied with earthworm children too.\n\nHow many children Drazil and Varda may have at most in order to satisfy all conditions above? Drazil and Varda want to know the answer for many different choices of $l$.\n\n(Drazil and Varda don't live in the hole with their children)",
    "tutorial": "We can use dfs twice to get the farthest distance from each node to any leaves (detail omitted here), and denote the longest distance from the $i$-th node to any leaves as $d_{i}$. Then we choose a node with minimum value of $d_{i}$ as the root. We will find that for any node $x$, $d_{x}$ isn't greater than $d_{y}$ for any node $y$ in the subtree of node $x$. Next, we solve the problem when there's only one query of $L$. In all valid groups of nodes, where node $x$ is the nearest to the root, obviously we can choose all nodes with $d_{i}  \\le  d_{x} + L$ into the group. Now we want to enumerate all nodes as the nearest node to the root. We denote the group of nodes generated from node $i$ as $G_{i}$. We can do it in $O(n\\log n)$ using dfs only once. (if the length of every edge is $1$, we can do it in $O(n)$) Imagine that $G_{i}$ will almost be as same as the union of all $G_{j}$ where node $j$ is a child of node $i$, but some nodes which are too far from node $i$ are kicked out. Each node will be kicked out from the groups we considered at most once in the whole process. Now we want to know when it happens. We solve it as follows: When we do dfs, we reserve a stack to record which nodes we have visited and still need to come back to. Yes, it's just like the implementation of recursive functions. Then we can just use binary search to find the node in the stack that when we go back to it, the current node will be kicked out (the closest node with $|d_{x} - d_{i}|  \\ge  L$). So the time complexity of the above algorithm is $O(q n\\log n)$ Now we provide another algorithm with O($qn \\alpha (n) + nlog(n)$) by union find. (Thanks Shik for providing this method.) First, sort all nodes by $d_{i}$. Then for each query, consider each node one by one from larger $d_{i}$'s to smaller $d_{i}$'s. At the beginning, set each node as a group of its own. We also need to record how many nodes each group contains. When handling a node $x$, union all groups of itself and its children. At the same time, for each node $j$ with $d_{j} > d_{x} + L$, we minus $1$ from the record of how many nodes $j$'s group has. By doing these, we can get the number of nodes $j$ in $x$'s subtree with $d_{j} < = d_{x} + L$. That's exactly what we want to know in the last algorithm. (implement with O($qn \\alpha (n) + nlog(n))$))",
    "code": "#include <bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define RI(X) scanf(\"%d\", &(X))\n#define RII(X, Y) scanf(\"%d%d\", &(X), &(Y))\n#define RIII(X, Y, Z) scanf(\"%d%d%d\", &(X), &(Y), &(Z))\n#define DRI(X) int (X); scanf(\"%d\", &X)\n#define DRII(X, Y) int X, Y; scanf(\"%d%d\", &X, &Y)\n#define DRIII(X, Y, Z) int X, Y, Z; scanf(\"%d%d%d\", &X, &Y, &Z)\n#define RS(X) scanf(\"%s\", (X))\n#define CASET int ___T, case_n = 1; scanf(\"%d \", &___T); while (___T-- > 0)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define PII pair<int,int>\n#define VPII vector<pair<int,int> >\n#define PLL pair<long long,long long>\n#define F first\n#define S second\ntypedef long long LL;\nusing namespace std;\nconst int MOD = 1e9+7;\nconst int SIZE = 1e5+10;\nvector<pair<int,LL> >e[SIZE];\nLL dp[SIZE][2],far[SIZE];\nvoid dfs1(int x,int lt){\n    REP(i,SZ(e[x])){\n        int y=e[x][i].F;\n        if(y==lt)continue;\n        dfs1(y,x);\n        if(dp[y][0]+e[x][i].S>dp[x][0]){\n            dp[x][1]=dp[x][0];\n            dp[x][0]=dp[y][0]+e[x][i].S;\n        }\n        else if(dp[y][0]+e[x][i].S>dp[x][1]){\n            dp[x][1]=dp[y][0]+e[x][i].S;\n        }\n    }\n}\nvoid dfs2(int x,int lt,LL v){\n    far[x]=max(v,dp[x][0]);\n    REP(i,SZ(e[x])){\n        int y=e[x][i].F;\n        if(y==lt)continue;\n        if(dp[y][0]+e[x][i].S==dp[x][0])dfs2(y,x,max(v,dp[x][1])+e[x][i].S);\n        else dfs2(y,x,max(v,dp[x][0])+e[x][i].S);\n    }\n}\nvoid add(int x,int y,int v){\n    e[x].PB(MP(y,v));\n    e[y].PB(MP(x,v));\n}\nint father[SIZE];\nvoid dfs(int x,int lt){\n    father[x]=lt;\n    REP(i,SZ(e[x])){\n        int y=e[x][i].F;\n        if(y==lt)continue;\n        dfs(y,x);\n    }\n}\nstruct Union_Find{\n    int d[SIZE],num[SIZE],v[SIZE];\n    void init(int n){\n        REP(i,n){\n            d[i]=i;\n            num[i]=1;\n            v[i]=1;\n        }\n    }\n    int find(int x){\n        return (x!=d[x])?(d[x]=find(d[x])):x;\n    }\n    bool uu(int x,int y){\n        x=find(x);\n        y=find(y);\n        if(x==y)return 0;\n        if(num[x]<num[y]){\n            num[y]+=num[x];\n            v[y]+=v[x];\n            d[x]=y;\n        }\n        else{\n            num[x]+=num[y];\n            v[x]+=v[y];\n            d[y]=x;\n        }\n        return 1;\n    }\n}U;\nint main(){\n    DRI(n);\n    REPP(i,1,n){\n        DRIII(x,y,v);\n        x--;y--;\n        add(x,y,v);\n    }\n    dfs1(0,0);\n    dfs2(0,0,0);\n    int root;\n    LL mi=1e18;\n    LL ma=0;\n    REP(i,n){\n        if(far[i]<mi){\n            mi=far[i];\n            root=i;\n        }\n        ma=max(ma,far[i]);\n    }\n    fprintf(stderr,\"[%I64d]\\n\",ma-mi);\n    dfs(root,root);\n    vector<pair<LL,int> >pp;\n    REP(i,n){\n        pp.PB(MP(far[i],i));\n    }\n    sort(ALL(pp));\n    DRI(Q);\n    while(Q--){\n        LL L;\n        scanf(\"%I64d\",&L);\n        int an=0;\n        int it=SZ(pp)-1;\n        U.init(n);\n        for(int i=SZ(pp)-1;i>=0;i--){\n            int me=pp[i].S;\n            REP(j,SZ(e[me])){\n                int y=e[me][j].F;\n                if(y==father[me])continue;\n                U.uu(me,y);\n            }\n            while(pp[it].F-pp[i].F>L){\n                U.v[U.find(pp[it].S)]--;\n                it--;\n            }\n            an=max(an,U.v[U.find(me)]);\n        }\n        printf(\"%d\\n\",an);\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "trees",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "516",
    "index": "E",
    "title": "Drazil and His Happy Friends",
    "statement": "Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.\n\nThere are $n$ boys and $m$ girls among his friends. Let's number them from $0$ to $n - 1$ and $0$ to $m - 1$ separately. In $i$-th day, Drazil invites $(i\\bmod n)$-th boy and $(i\\bmod m)$-th girl to have dinner together (as Drazil is programmer, $i$ starts from $0$). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if it is happy originally), he stays happy forever.\n\nDrazil wants to know on which day all his friends become happy or to determine if they won't become all happy at all.",
    "tutorial": "Simplifying this question, suppose that $n$ and $m$ are coprime. If $n$ and $m$ are not coprime and the gcd of $n$ and $m$ is $g$, then we can divide all people into $g$ groups by the values of their id mod $g$ and find the maximum answer between them. Obviously, If there is at least one group of friends which are all unhappy in the beginning, the answer is -1. Now we determine the last one becoming happy, for boys and girls separately. In fact, there's an easy way to explain this problem - finding the shortest path! View all friends as points, and add another point as the source. For all friends, we will view the distance from the source as the time becoming happy. And define two types of edges. (1) There is a fact: If a girl $x$ become happy in time $t$, then the girl $(x + n)%m$ will become happy in time $t + n$. So we can build a directed edge from point $x$ to $(x + n)%m$ with length $n$. Similar for boys. (2) If the $i$-th boy/girlfriend is happy originally, we can connect it to the source with an edge of length $i$. At the same time, we also connect the source to $i%n$-th boy($i%m$ for girl) with an edge of length $i$. You can imagine that the same gender of friends form a cycle. (eg. the $(i * m)%n$-th boy is connected to the $((i + 1) * m)%n)$-th boy for $i$ from 0 to $n - 1$) With these two types of edges, we can find that if a friend is unhappy originally, he/she will become happy at the time value which is the length of the shortest path from the source. The only question is that there are too many points and edges! We can solve this problem by considering only some \"important\" points. And we can combine some consecutive edges of the first type to a new edge. The group of edges is the maximal edges that contain deleted points.(These deleted points always form a line). Finally we find the maximum value of the shortest path from the source to these friends which is unhappy originally in the reduced graph. Time complexity: ${\\cal O}((n+m)\\log(n+m)\\}$",
    "code": "#include <bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define RI(X) scanf(\"%d\", &(X))\n#define RII(X, Y) scanf(\"%d%d\", &(X), &(Y))\n#define RIII(X, Y, Z) scanf(\"%d%d%d\", &(X), &(Y), &(Z))\n#define DRI(X) int (X); scanf(\"%d\", &X)\n#define DRII(X, Y) int X, Y; scanf(\"%d%d\", &X, &Y)\n#define DRIII(X, Y, Z) int X, Y, Z; scanf(\"%d%d%d\", &X, &Y, &Z)\n#define RS(X) scanf(\"%s\", (X))\n#define CASET int ___T, case_n = 1; scanf(\"%d \", &___T); while (___T-- > 0)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define PII pair<int,int>\n#define VPII vector<pair<int,int> >\n#define PLL pair<long long,long long>\n#define F first\n#define S second\ntypedef long long LL;\nusing namespace std;\nLL INF = 2e18;\nint n,m;\nvector<int>d[100000][2];\n// a*x+b*y=z\nstruct gcd_t {long long x,y,z;}gg;\nLL inv[2],sz[2];\ngcd_t gcd(long long a,long long b) {\n    if(b==0)return (gcd_t){1,0,a};\n    gcd_t t=gcd(b,a%b);\n    return (gcd_t){t.y,t.x-t.y*(a/b),t.z};\n}\nvoid fresh(LL &x,LL v){\n    x=min(x,v);\n}\nvoid mii(map<int,LL>&mi,LL x,LL v){\n    if(mi.count(x))fresh(mi[x],v);\n    else mi[x]=v;\n}\nvoid proccess(LL& now,map<int,LL>& mi,int round){\n    map<int,LL>::iterator it=mi.begin();\n    while(it!=mi.end()){\n        fresh(it->S,now);\n        fresh(now,it->S);\n        int me=it->F;\n        it++;\n        int you;\n        if(it!=mi.end())you=it->F;\n        else you=mi.begin()->F+sz[round];\n        now+=(you-me)*sz[round^1]*gg.z;\n    }\n}\nLL f(vector<int>v[]){\n    LL res=-1;\n    int n=SZ(v[0])+SZ(v[1]);\n    n<<=1;\n    REP(round,2){\n        set<int>H;\n        map<int,LL>mi;\n        REP(k,2){\n            REP(i,SZ(v[k])){\n                int me=v[k][i]*inv[round]%sz[round];\n                if(k==round)H.insert(me);\n                mii(mi,(me+sz[round]-1)%sz[round],INF);\n                mii(mi,me,v[k][i]*gg.z);\n            }\n        }\n \n        LL now=INF;\n        proccess(now,mi,round);\n        proccess(now,mi,round);\n        set<int>::iterator it1=H.begin();\n        map<int,LL>::iterator it2=mi.begin();\n        while(it2!=mi.end()){\n            while(it1!=H.end()&&*it1<it2->F)it1++;\n            if(it1==H.end()||*it1!=it2->F)res=max(res,it2->S);\n            it2++;\n        }\n    }\n    if(res==-1)return -INF;\n    return res;\n}\nint main(){\n    RII(n,m);\n    gg=gcd(n,m);\n    if(gg.z>100000){\n        puts(\"-1\");\n        return 0;\n    }\n    sz[0]=n/gg.z;\n    sz[1]=m/gg.z;\n    inv[1]=(gg.x%sz[1]+sz[1])%sz[1];\n    inv[0]=(gg.y%sz[0]+sz[0])%sz[0];\n    REP(k,2){\n        DRI(m);\n        REP(i,m){\n            DRI(x);\n            d[x%gg.z][k].PB(x/gg.z);\n        }\n    }\n    REP(i,gg.z){\n        if(SZ(d[i][0])+SZ(d[i][1])==0){\n            puts(\"-1\");\n            return 0;\n        }\n    }\n    LL an=0;\n    REP(i,gg.z){\n        an=max(an,f(d[i])+i);\n    }\n    cout<<an<<endl;\n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 3100
  },
  {
    "contest_id": "518",
    "index": "A",
    "title": "Vitaly and Strings",
    "statement": "Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.\n\nDuring the last lesson the teacher has provided two strings $s$ and $t$ to Vitaly. The strings have the same length, they consist of lowercase English letters, string $s$ is lexicographically smaller than string $t$. Vitaly wondered if there is such string that is lexicographically larger than string $s$ and at the same is lexicographically smaller than string $t$. This string should also consist of lowercase English letters and have the length equal to the lengths of strings $s$ and $t$.\n\nLet's help Vitaly solve this easy problem!",
    "tutorial": "To solve this problem we can, for example, find string $next$, which lexicographically next to string $s$ and check that string $next$ is lexicographically less than string $t$. If string $next$ is lexicographically smaller than string $t$, print string $next$ and finish algorithm. If string $next$ is equal to string $t$ print $No such string$. To find string $next$, which lexicographically next to string $s$, at first we need to find maximal suffix of string $s$, consisting from letters $'z'$, change all letters $'z'$ in this suffix on letters $'a'$, and then letter before this suffix increase on one. I.e. if before suffix was letter, for example, $'d'$, we need to change it on letter $'e'$. Asymptotic behavior of this solution - $O(|s|)$, where $|s|$ - length of string $s$.",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "518",
    "index": "B",
    "title": "Tanya and Postcard",
    "statement": "Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string $s$ of length $n$, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string $s$. The newspaper contains string $t$, consisting of uppercase and lowercase English letters. We know that the length of string $t$ greater or equal to the length of the string $s$.\n\nThe newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some $n$ letters out of the newspaper and make a message of length exactly $n$, so that it looked as much as possible like $s$. If the letter in some position has correct value and correct letter case (in the string $s$ and in the string that Tanya will make), then she shouts joyfully \"YAY!\", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says \"WHOOPS\".\n\nTanya wants to make such message that lets her shout \"YAY!\" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says \"WHOOPS\". Your task is to help Tanya make the message.",
    "tutorial": "To solve this problem at first will count array $cnt[]$, where $cnt[c]$ - how many times letter $c$ found in string $t$. We will count two numbers $ans1$ and $ans2$ - how many times Tanya will shouts joyfully $YAY!$ and how many times Tanya will says $WHOOPS$. Let's iterate on string $s$ and if $cnt[s[i]] > 0$, then increase $ans1$ on one and decrease $cnt[s[i]]$ on one. Then let's again iterate on string $s$. Let $c$ is letter which equal to $s[i]$,but in the opposite case for it. I. e. if $s[i] = 'w'$, then $c = 'W'$. Now, if $cnt[c] > 0$, then increase $ans2$ on one and decrease $cnt[c]$ on one. Now, print two numbers - $ans1$ and $ans2$. Asymptotic behavior of this solution - $O(|s| + |t|)$, where $|s|$ - length of string $s$ and $|t|$ - length of string $t$.",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "518",
    "index": "C",
    "title": "Anya and Smartphone",
    "statement": "Anya has bought a new smartphone that uses \\underline{Berdroid} operating system. The smartphone menu has exactly $n$ applications, each application has its own icon. The icons are located on different screens, one screen contains $k$ icons. The icons from the first to the $k$-th one are located on the first screen, from the $(k + 1)$-th to the $2k$-th ones are on the second screen and so on (the last screen may be partially empty).\n\nInitially the smartphone menu is showing the screen number $1$. To launch the application with the icon located on the screen $t$, Anya needs to make the following gestures: first she scrolls to the required screen number $t$, by making $t - 1$ gestures (if the icon is on the screen $t$), and then make another gesture — press the icon of the required application exactly once to launch it.\n\nAfter the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number $1$.\n\nAll applications are numbered from $1$ to $n$. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. \\underline{Berdroid} is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.\n\nAnya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order?\n\nNote that one application may be launched multiple times.",
    "tutorial": "To solve this problem we will store two arrays - $a[]$ and $pos[]$. In array $a[]$ will store current order of icons, i. e. in $a[i]$ store number of application, icon which stay on position $i$. In array $pos[]$ will store on which place in list stays icons, i. e. in $pos[i]$ store in which position of array $a[]$ stay icon of application number $i$. We will count answer in variable $ans$. Let's iterate on applications which we need to open. Let current application has number $num$. Then to $ans$ we need add ($pos[num] / k + 1$). Now, if icon of application number $num$ doesn't stay on first position in list of applications, we make the following - swap $a[pos[num]]$ and $a[pos[num] - 1]$ and update values in array $pos[]$ for indexes of two icons which numbers $a[pos[num]]$ and $a[pos[num] - 1]$ . Asymptotic behavior of this solution - $O(n + m)$, where $n$ - number of applications, $m$ - number of requests to start applications.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "518",
    "index": "D",
    "title": "Ilya and Escalator",
    "statement": "Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor.\n\nLet's assume that $n$ people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability $p$, or the first person in the queue doesn't move with probability $(1 - p)$, paralyzed by his fear of escalators and making the whole queue wait behind him.\n\nFormally speaking, the $i$-th person in the queue cannot enter the escalator until people with indices from $1$ to $i - 1$ inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after $t$ seconds.\n\nYour task is to help him solve this complicated task.",
    "tutorial": "To solve this problem let's use dynamic programming. We will store two-dimensional array $z[][]$ with type $double$. In $z[i][j]$ will store the likelihood that after $i$ seconds $j$ people are on escalator. In dynamic will be following transitions. If $j = n$, i. e. all $n$ people already on escalator then we make transition $z[i + 1][j] + = z[i][j]$. Else, or person number $j$ go to escalator in $i + 1$ second, i. e. $z[i + 1][j + 1] + = z[i][j] * p$, or person number $j$ stays on his place, i. e. $z[i + 1][j] + = z[i][j] * (1 - p)$. Now we need to count answer - it is sum on $j$ from $0$ to $n$ inclusive $z[t][j] * j$. Asymptotic behavior of this solution - $O(t * n)$, where $t$ - on which moment we must count answer, $n$ - how many people stay before escalator in the beginning.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 1700
  },
  {
    "contest_id": "518",
    "index": "E",
    "title": "Arthur and Questions",
    "statement": "After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length $n$ ($a_{1}, a_{2}, ..., a_{n})$, consisting of integers and integer $k$, not exceeding $n$.\n\nThis sequence had the following property: if you write out the sums of all its segments consisting of $k$ consecutive elements $(a_{1}  +  a_{2} ...  +  a_{k},  a_{2}  +  a_{3}  +  ...  +  a_{k + 1},  ...,  a_{n - k + 1}  +  a_{n - k + 2}  +  ...  +  a_{n})$, then those numbers will form strictly increasing sequence.\n\nFor example, for the following sample: $n = 5,  k = 3,  a = (1,  2,  4,  5,  6)$ the sequence of numbers will look as follows: ($1  +  2  +  4,  2  +  4  +  5,  4  +  5  +  6$) = ($7,  11,  15$), that means that sequence $a$ meets the described property.\n\nObviously the sequence of sums will have $n - k + 1$ elements.\n\nSomebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum $|a_{i}|$, where $|a_{i}|$ is the absolute value of $a_{i}$.",
    "tutorial": "At first let's take two sums $a_{1} + a_{2} + ... + a_{k}$ and $a_{2} + a_{3} + ... + a_{k + 1}$. It is correct that $a_{1} + a_{2} + ... + a_{k} < a_{2} + a_{3} + ... + a_{k + 1}$. If move from right to left all elements apart from $a_{k + 1}$, all of them will reduce and will left only $a_{1} < a_{k + 1}$. If write further all sums we will obtain that sequence disintegrate on $k$ disjoint chains: $a_{1} < a_{k + 1} < a_{2k + 1} < a_{3k + 1}..., a_{2} < a_{k + 2} < a_{2k + 2} < a_{3k + 2}..., ..., a_{k} < a_{2k} < a_{3k}...$. We will solve the problem for every chain separately. Let's iterate on first chain and find all pair of indexes $i, j$ $(i < j)$, that $a[i]$ and $a[j]$ are numbers (not questions) in given sequence, and for all $k$ from $i + 1$ to $j - 1$ in $a[k]$ stay questions. All this questions we need to change on numbers so does not violate the terms of the increase and minimize sum of absolute values of this numbers. Between indexes $i$ and $j$ stay $j - i - 1$ questions, we can change them on $a[j] - a[i] - 1$ numbers. If $j - i - 1$ > $a[j] - a[i] - 1$, then we need to print $Incorrect$ $sequence$ and finish algorithm. Else we need to change all this questions to numbers in greedy way. Here we have several cases. Will review one case when $a[i] > = 0$ and $a[j] > = 0$. Let current chain ($3, ?, ?, ?, 9$), $i = 1$, $j = 5$. We need to change questions on numbers in the following way - ($3, 4, 5, 6, 9$). In other cases (when $a[i] < = 0$, $a[j] < = 0$ and when $a[i] < = 0$, $a[j] > = 0$) we need to use greedy similary to first so does not violate the terms of the increase and minimize sum of absolute values of this numbers. Asymptotic behavior of this solution - $O(n)$, where $n$ - count of elements in given sequence.",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "ternary search"
    ],
    "rating": 2200
  },
  {
    "contest_id": "518",
    "index": "F",
    "title": "Pasha and Pipe",
    "statement": "On a certain meeting of a ruling party \"A\" minister Pavel suggested to improve the sewer system and to create a new pipe in the city.\n\nThe city is an $n × m$ rectangular squared field. Each square of the field is either empty (then the pipe can go in it), or occupied (the pipe cannot go in such square). Empty squares are denoted by character '$.$', occupied squares are denoted by character '$#$'.\n\nThe pipe must meet the following criteria:\n\n- the pipe is a polyline of width $1$,\n- the pipe goes in empty squares,\n- the pipe starts from the edge of the field, but not from a corner square,\n- the pipe ends at the edge of the field but not in a corner square,\n- the pipe has at most $2$ turns ($90$ degrees),\n- the border squares of the field must share \\textbf{exactly two} squares with the pipe,\n- if the pipe looks like a single segment, then the end points of the pipe must lie on distinct edges of the field,\n- for each non-border square of the pipe there are \\textbf{exacly two} side-adjacent squares that also belong to the pipe,\n- for each border square of the pipe there is \\textbf{exactly one} side-adjacent cell that also belongs to the pipe.\n\nHere are some samples of \\textbf{allowed} piping routes:\n\n\\begin{verbatim}\n....# ....# .*..#\n***** ****. .***.\n..#.. ..#*. ..#*.\n#...# #..*# #..*#\n..... ...*. ...*.\n\\end{verbatim}\n\nHere are some samples of \\textbf{forbidden} piping routes:\n\n\\begin{verbatim}\n.**.# *...# .*.*#\n..... ****. .*.*.\n..#.. ..#*. .*#*.\n#...# #..*# #*.*#\n..... ...*. .***.\n\\end{verbatim}\n\nIn these samples the pipes are represented by characters '$ * $'.\n\nYou were asked to write a program that calculates the number of distinct ways to make exactly one pipe in the city.\n\nThe two ways to make a pipe are considered distinct if they are distinct in at least one square.",
    "tutorial": "At first let's count two two-dimensional arrays of prefix sums $sumv[][]$ and $sumg[][]$. In $sumv[i][j]$ store how many grids are in column $j$ beginning from row $1$ to row $i$. In $sumg[i][j]$ store how many grid are in row $i$ beginning from column $1$ to column $j$. Let's count $ans0$ - how many pipes without bending we can pave. Count how many vertical pipes - we can pave. Iterate on $j$ from $2$ to $m - 1$ and, if $sumg[n][j] - sumg[n][0] = 0$ (i. e. in this column zero grids), increase $ans0$ on one. Similary count number of horizontal pipes. Let's count $ans1$ - how many pipes with $1$ bending we can pave. We need to brute cell, in which will bending. There are four cases. Let's consider first case, others we can count similary. This case - pipe begin in left column, go to current cell in brute and then go to top row. If brute cell in row $i$ and column $j$ then to $ans1$ we need to add one, if $(sumg[i][j] - sumg[i][0]) + (sumv[i][j] - sumv[0][j]) = 0$. Let's count $ans2$ - how many pipes with $2$ bendings we can pave. Let's count how many tunes begin from top row and end in top or bottom row and add this number to $ans2$. Then rotate our matrix three times on $90$ degrees and after every rotate add to $ans2$ count of pipes, which begin from top row and end in top or bottom row. Then we need divide $ans2$ to $2$, because every pipe will count twice. How we can count to current matrix how many pipes begin from top row and end in top or bottom row? Let's count four two-dimension arrays $lf[][]$, $rg[][]$, $sumUp[][]$, $sumDown[][]$. If $i$ - number of row, $j$ - number of column of current cell, then in position ($i, lf[i][j]$) in matrix are nearest from left grid for cell ($i, j$), and in position ($i, rg[i][j]$) in matrix are nearest from right grid for cell ($i, j$). $sumUp[i][j]$ - how many columns without grids are in submatrix from ($1, 1$) to ($i, j$) of given matrix. $sumDown[i][j]$ - how many columns without grids are in submatrix from ($i, 1$) to ($n, j$) of given matrix. Then let's brute cell in which will be the first bending of pipe (pipe goes from top row and in this cell turned to left or to right), check, that in column $j$ above this cell $0$ grids, with help of arrays $lf$ and $rg$ find out as far as pipe can go to left or to right and with help of arrays $sumUp$ and $sumDown$ carefully update answer. Now print number $ans1 + ans2 + ans3$. Asymptotic behavior of this solution - $O(n * m * const)$, where $n$ - hoew many rows in given matrix, $m$ - how many columns in given matrix, $const$ takes different values depending on the implementation, in solution from editorial $const = 10$.",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "dp",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "519",
    "index": "A",
    "title": "A and B and Chess",
    "statement": "A and B are preparing themselves for programming contests.\n\nTo train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.\n\nFor each chess piece we know its weight:\n\n- the queen's weight is 9,\n- the rook's weight is 5,\n- the bishop's weight is 3,\n- the knight's weight is 3,\n- the pawn's weight is 1,\n- the king's weight isn't considered in evaluating position.\n\nThe player's weight equals to the sum of weights of all his pieces on the board.\n\nAs A doesn't like counting, he asked you to help him determine which player has the larger position weight.",
    "tutorial": "This problem asked to determine whose chess position is better. Solution: Iterate over the board and count scores of both player. Then just output the answer. Complexity: $O(n^{2})$, where n is the length of the side of the board (8 here)",
    "code": "/****************************************\n**     Solution by Bekzhan Kassenov    **\n****************************************/\n \n#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\n#define MP make_pair\n#define all(x) (x).begin(), (x).end()\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\n \nconst double EPS = 1e-9;\nconst double PI = acos(-1.0);\nconst int MOD = 1000 * 1000 * 1000 + 7;\nconst int INF = 2000 * 1000 * 1000;\n \ntemplate <typename T>\ninline T sqr(T n) {\n    return n * n;\n}\n \nchar s[10][10];\nchar name[6] = {'Q', 'R', 'B', 'N', 'P', 'K'};\nchar weight[6] = {9, 5, 3, 3, 1, 0};\n \nint scoreWhite, scoreBlack;\n \nint main() {\n#ifndef ONLINE_JUDGE\n    freopen(\"in\", \"r\", stdin);\n#endif\n \n    for (int i = 0; i < 8; i++) {\n        gets(s[i]);\n    }\n \n    for (int i = 0; i < 8; i++) {\n        for (int j = 0; j < 8; j++) {\n            for (int k = 0; k < 6; k++) {\n                if (toupper(s[i][j]) == name[k]) {\n                    if (isupper(s[i][j])) {\n                        scoreWhite += weight[k];\n                    } else {\n                        scoreBlack += weight[k];\n                    }\n \n                    break;\n                }\n            }\n        }\n    }\n \n    if (scoreWhite > scoreBlack) {\n        puts(\"White\");\n    } else if (scoreWhite < scoreBlack) {\n        puts(\"Black\");\n    } else {\n        puts(\"Draw\");\n    }\n \n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "519",
    "index": "B",
    "title": "A and B and Compilation Errors",
    "statement": "A and B are preparing themselves for programming contests.\n\nB loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.\n\nInitially, the compiler displayed $n$ compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.\n\nHowever, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.\n\nCan you help B find out exactly what two errors he corrected?",
    "tutorial": "In this problem you were given three arrays. Second array is the same as the first array without one element, third array is the same as second array without first element. You were asked to find deleted elements. Solution: I'll describe easiest solution for this problem: Let's denote $a$ as sum of all elements of first array, $b$ as sum of all elements of second array and $c$ as sum of all elements of third array. Then answer is $a - b$ and $b - c$ There are also some other solutions for this problem which use map, xor, etc. Complexity: $O(N)$",
    "code": "/****************************************\n**     Solution by Bekzhan Kassenov    **\n****************************************/\n \n#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\n#define MP make_pair\n#define all(x) (x).begin(), (x).end()\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\n \nconst double EPS = 1e-9;\nconst double PI = acos(-1.0);\nconst int MOD = 1000 * 1000 * 1000 + 7;\nconst int INF = 2000 * 1000 * 1000;\n \ntemplate <typename T>\ninline T sqr(T n) {\n    return n * n;\n}\n \nint n, x;\nlong long a, b, c;\n \nint main() {\n#ifndef ONLINE_JUDGE\n    freopen(\"in\", \"r\", stdin);\n#endif\n \n    scanf(\"%d\", &n);\n \n    for (int i = 0; i < n; i++) {\n        scanf(\"%d\", &x);\n        a += x;\n    }\n \n    for (int i = 0; i < n - 1; i++) {\n        scanf(\"%d\", &x);\n        b += x;\n    }\n \n    for (int i = 0; i < n - 2; i++) {\n        scanf(\"%d\", &x);\n        c += x;\n    }\n \n    printf(\"%I64d\\n%I64d\\n\", a - b, b - c);\n \n    return 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "519",
    "index": "C",
    "title": "A and B and Team Training",
    "statement": "A and B are preparing themselves for programming contests.\n\nAn important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solving problems together with experienced participants.\n\nA believes that the optimal team of three people should consist of one experienced participant and two newbies. Thus, each experienced participant can share the experience with a large number of people.\n\nHowever, B believes that the optimal team should have two experienced members plus one newbie. Thus, each newbie can gain more knowledge and experience.\n\nAs a result, A and B have decided that all the teams during the training session should belong to one of the two types described above. Furthermore, they agree that the total number of teams should be as much as possible.\n\nThere are $n$ experienced members and $m$ newbies on the training session. Can you calculate what maximum number of teams can be formed?",
    "tutorial": "In this problem we should split $n$ experienced participants and $m$ newbies into teams. Solution: Let's denote number teams with 2 experienced partisipants and 1 new participant as $type1$ and teams with 1 experienced participant and 2 new participants as $type2$. Let's fix number of teams of $type1$ and denote it as $i$. Their amount is not grater than $m$. Then number of teams of $type2$ is $min(m - 2 * i, n - i)$. Check all possible $i$' and update answer. Complexity: $O(N)$",
    "code": "/****************************************\n**     Solution by Bekzhan Kassenov    **\n****************************************/\n \n#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\n#define MP make_pair\n#define all(x) (x).begin(), (x).end()\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\n \nconst double EPS = 1e-9;\nconst double PI = acos(-1.0);\nconst int MOD = 1000 * 1000 * 1000 + 7;\nconst int INF = 2000 * 1000 * 1000;\n \ntemplate <typename T>\ninline T sqr(T n) {\n    return n * n;\n}\n \nint n, m, ans;\n \nint main() {\n#ifndef ONLINE_JUDGE\n    freopen(\"in\", \"r\", stdin);\n#endif\n \n    scanf(\"%d%d\", &n, &m);\n \n    for (int i = 0; i <= n; i++) {\n        int cur = i;\n        int leftn = n - i;\n        int leftm = m - 2 * i;\n \n        if (leftm >= 0) {\n            cur += min(leftm, leftn / 2);\n            ans = max(ans, cur);\n        }\n    }\n \n    printf(\"%d\\n\", ans);\n    \n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "519",
    "index": "D",
    "title": "A and B and Interesting Substrings",
    "statement": "A and B are preparing themselves for programming contests.\n\nAfter several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.\n\nA likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).\n\nB likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).\n\nAlso, A and B have a string $s$. Now they are trying to find out how many substrings $t$ of a string $s$ are interesting to B (that is, $t$ starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.\n\nNaturally, A and B have quickly found the number of substrings $t$ that are interesting to them. Can you do it?",
    "tutorial": "In this problem you were asked to find number of substrings of given string, such that each substring starts and finishes with one and the same letter and sum of weight of letters of that substring without first and last letter is zero. Solution: Let's denote $sum[i]$ as sum of weights of first $i$ letters. Create 26 $map < longlong, int >$'s, 1 for each letter. Suppose we are on position number $i$ and current character's map is $m$. Then add $m[sum[i - 1]]$ to the answer and add $sum[i]$ to the $m$. Complexity: $O(NlogN)$, where $N$ - the length of input string.",
    "code": "/****************************************\n**     Solution by Bekzhan Kassenov    **\n****************************************/\n \n#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\n#define MP make_pair\n#define all(x) (x).begin(), (x).end()\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\n \nconst double EPS = 1e-9;\nconst double PI = acos(-1.0);\nconst int MOD = 1000 * 1000 * 1000 + 7;\nconst int INF = 2000 * 1000 * 1000;\nconst int MAXN = 100010;\n \ntemplate <typename T>\ninline T sqr(T n) {\n    return n * n;\n}\n \nint cnt[26];\nvector <int> pos[MAXN];\nchar s[MAXN];\nint n;\nlong long sum[MAXN], ans;\n \nint main() {\n#ifndef ONLINE_JUDGE\n    freopen(\"in\", \"r\", stdin);\n#endif\n \n    for (int i = 0; i < 26; i++) {\n        scanf(\"%d\", &cnt[i]);\n    }\n \n    getchar();\n    gets(s + 1);\n    n = strlen(s + 1);\n \n    for (int i = 1; i <= n; i++) {\n        sum[i] = cnt[s[i] - 'a'];\n        sum[i] += sum[i - 1];\n \n        pos[s[i] - 'a'].push_back(i);\n    }\n \n    for (int cc = 0; cc < 26; cc++) {\n        map <long long, int> Map;\n \n        for (size_t i = 0; i < pos[cc].size(); i++) {\n            int p = pos[cc][i];\n            ans += Map[sum[p - 1]];\n            Map[sum[p]]++;\n        }\n \n        Map.clear();\n    }\n \n    printf(\"%I64d\\n\", ans);\n \n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "519",
    "index": "E",
    "title": "A and B and Lecture Rooms",
    "statement": "A and B are preparing themselves for programming contests.\n\nThe University where A and B study is a set of rooms connected by corridors. Overall, the University has $n$ rooms connected by $n - 1$ corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from $1$ to $n$.\n\nEvery day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.\n\nAs they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following $m$ days.",
    "tutorial": "In this problem we have to answer to the following queries on tree: for given pairs of vertices your program should output number of eqidistand vertices from them. Let's denote: $dist(a, b)$ as distance between vertices $a$ and $b$. $LCA(a, b)$ as lowest common ancestor of vertices $a$ and $b$. $depth[a]$ as distance between root of the tree and vertex $a$. $size[a]$ as size of subtree of vertex $a$. On each picture green nodes are equidistant nodes, blue nodes - nodes from query. Preprocessing: Read edges of tree and build data structure for LCA (it is more convenient to use binary raise, becase we will use it further for other purposes). Complexity: $O(NlogN)$ Queries: We have to consider several cases for each query: 1) $a = b$. In that case answer is $n$. 2) $dist(a, b)$ is odd. Then answer is $0$. 3) $dist(a, l) = dist(b, l)$, where $l = LCA(a, b)$. Find children of $l$, which are ancestors of $a$ and $b$ (let's denote them as $aa$ and $bb$). Answer will be $n - size[aa] - size[bb]$. 4) All other cases. Assume that $depth[a] > depth[b]$. Then using binary raise find $dist(a, b) / 2$-th ancestor of $a$ (let's denote it as $p1$), $dist(a, b) / 2 - 1$-th ancestor of vertex $a$ (denote it as $p2$). Answer will be $size[p1] - size[p2]$. Complexity: $O(logN)$ for each query, $O(MlogN)$ for all queries. Resulting complexity:: $O(MlogN + NlogN)$",
    "code": "/****************************************\n**     Solution by Bekzhan Kassenov    **\n****************************************/\n \n#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\n#define MP make_pair\n#define all(x) (x).begin(), (x).end()\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\n \nconst double EPS = 1e-9;\nconst double PI = acos(-1.0);\nconst int MOD = 1000 * 1000 * 1000 + 7;\nconst int INF = 2000 * 1000 * 1000;\nconst int MAXN = 100010;\nconst int LG = 30;\n \ntemplate <typename T>\ninline T sqr(T n) {\n    return n * n;\n}\n \nvector <int> g[MAXN];\nint n, x, y;\nint depth[MAXN], size[MAXN], anc[MAXN][LG];\nint tin[MAXN], tout[MAXN], timer;\nint q, a, b;\n \nvoid dfs(int v, int par = 1, int d = 0) {\n    depth[v] = d;\n    size[v] = 1;\n    tin[v] = timer++;\n \n    anc[v][0] = par;\n    for (int i = 1; i < LG; i++) {\n        anc[v][i] = anc[anc[v][i - 1]][i - 1];\n    }\n \n    for (size_t i = 0; i < g[v].size(); i++) {\n        int to = g[v][i];\n        if (to != par) {\n            dfs(to, v, d + 1);\n            size[v] += size[to];\n        }\n    }\n \n    tout[v] = timer++;\n}\n \nbool ancestor(int a, int b) {\n    return tin[a] <= tin[b] && tout[b] <= tout[a];\n}\n \nint go_up(int a, int b) {\n    for (int i = LG - 1; i >= 0; i--) {\n        if (!ancestor(anc[a][i], b)) {\n            a = anc[a][i];\n        }\n    }\n \n    return a;\n}\n \nint lca(int a, int b) {\n    int result = -1;\n \n    if (ancestor(a, b)) {\n        result = a;\n    } else if (ancestor(b, a)) {\n        result = b;\n    } else {\n        result = anc[go_up(a, b)][0];\n    }\n \n    return result;\n}\n \nint query(int a, int b) {\n    int l = lca(a, b);\n    int result = -1;\n \n    if (a == b) {\n        result = n;\n    } else if (depth[a] - depth[l] == depth[b] - depth[l]) {\n        a = go_up(a, l);\n        b = go_up(b, l);\n \n        result = n - size[a] - size[b];\n    } else {\n \n        if (depth[a] < depth[b]) {\n            swap(a, b);\n        }\n \n        int to = a;\n        int dist = depth[a] + depth[b] - 2 * depth[l];\n \n        if (dist % 2 == 1) {\n            result = 0;\n        } else {\n            dist /= 2;\n \n            for (int i = LG - 1; i >= 0; i--) {\n                if (depth[a] - depth[anc[to][i]] < dist) {\n                    to = anc[to][i];\n                }\n            }\n \n            int mid = anc[to][0];\n            result = size[mid] - size[to];\n        }\n    }\n \n    return result;\n}\n \nint main() {\n#ifndef ONLINE_JUDGE\n    freopen(\"in\", \"r\", stdin);\n#endif\n \n    scanf(\"%d\", &n);\n \n    for (int i = 0; i < n - 1; i++) {\n        scanf(\"%d%d\", &x, &y);\n        g[x].push_back(y);\n        g[y].push_back(x);\n    }\n \n    dfs(1);\n \n    scanf(\"%d\", &q);\n \n    while (q--) {\n        scanf(\"%d%d\", &a, &b);\n \n        printf(\"%d\\n\", query(a, b));\n    }\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "520",
    "index": "A",
    "title": "Pangram",
    "statement": "A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.\n\nYou are given a string consisting of lowercase and uppercase Latin letters. Check whether this string is a pangram. We say that the string contains a letter of the Latin alphabet if this letter occurs in the string in uppercase or lowercase.",
    "tutorial": "To check that every letter is present in the string we can just make a boolean array of size 26 and for every letter set the corresponding variable to TRUE. In the end check that there are 26 TRUEs. That is an $O(n)$ solution. Also don't forget to change all letters to lowercase (or all to uppercase). To make all the letters lowercase, one could use standard functions, like tolower in Python. Also, it is known that the letters from a to z have consecutive ASCII numbers, as well as A to Z; an ASCII number of symbol is ord(c) in most languages. So, to get the number of a lowercase letter in the alphabet one can use ord(c) - ord('a') in most languages, or simply c - 'a' in C++ or C (because a char in C/C++ can be treated as a number); to check if a letter is lowercase, the inequality ord('a') <= ord(c) && ord(c) <= ord('z') should be checked.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "520",
    "index": "B",
    "title": "Two Buttons",
    "statement": "Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number $n$.\n\nBob wants to get number $m$ on the display. What minimum number of clicks he has to make in order to achieve this result?",
    "tutorial": "The simplest solution is simply doing a breadth-first search. Construct a graph with numbers as vertices and edges leading from one number to another if an operation can be made to change one number to the other. We may note that it is never reasonable to make the number larger than $2m$, so under provided limitations the graph will contain at most $2 \\cdot 10^{4}$ vertices and $4 \\cdot 10^{4}$ edges, and the BFS should work real fast. There is, however, an even faster solution. The problem can be reversed as follows: we should get the number $n$ starting from $m$ using the operations \"add 1 to the number\" and \"divide the number by 2 if it is even\". Suppose that at some point we perform two operations of type 1 and then one operation of type 2; but in this case one operation of type 2 and one operation of type 1 would lead to the same result, and the sequence would contain less operations then before. That reasoning implies that in an optimal answer more than one consecutive operation of type 1 is possible only if no operations of type 2 follow, that is, the only situation where it makes sense is when $n$ is smaller than $m$ and we just need to make it large enough. Under this constraint, there is the only correct sequence of moves: if $n$ is smaller than $m$, we just add 1 until they become equal; else we divide $n$ by 2 if it is even, or add 1 and then divide by 2 if it is odd. The length of this sequence can be found in $O(\\log n)$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation",
      "math",
      "shortest paths"
    ],
    "rating": 1400
  },
  {
    "contest_id": "520",
    "index": "C",
    "title": "DNA Alignment",
    "statement": "Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.\n\nLet's assume that strings $s$ and $t$ have the same length $n$, then the function $h(s, t)$ is defined as the number of positions in which the respective symbols of $s$ and $t$ are the same. Function $h(s, t)$ can be used to define the function of Vasya distance $ρ(s, t)$:\n\n\\[\n\\rho(s,t)=\\sum_{i=0}^{n-1}\\sum_{j=0}^{n-1}h(\\mathrm{shift}(s,i),\\mathrm{shift}(t,j)),\n\\]\n\nwhere ${\\mathrm{shift}}(s,i)$ is obtained from string $s$, by applying left circular shift $i$ times. For example, \\[\nρ(\"AGC\", \"CGT\") =\n\\]\n\n\\[\nh(\"AGC\", \"CGT\") + h(\"AGC\", \"GTC\") + h(\"AGC\", \"TCG\") +\n\\]\n\n\\[\nh(\"GCA\", \"CGT\") + h(\"GCA\", \"GTC\") + h(\"GCA\", \"TCG\") +\n\\]\n\n\\[\nh(\"CAG\", \"CGT\") + h(\"CAG\", \"GTC\") + h(\"CAG\", \"TCG\") =\n\\]\n\n\\[\n1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6\n\\]\n\nVasya found a string $s$ of length $n$ on the Internet. Now he wants to count how many strings $t$ there are such that the Vasya distance from the string $s$ attains maximum possible value. Formally speaking, $t$ must satisfy the equation: $\\rho(s,t)=\\operatorname*{max}_{u\\dagger u\\dagger=i\\leq s\\dagger}\\rho(s,u)$.\n\nVasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo $10^{9} + 7$.",
    "tutorial": "What is $ \\rho (s, t)$ equal to? For every character of $s$ and every character of $t$ there is a unique cyclic shift of $t$ that superposes these characters (indeed, after 0, $...$, $n - 1$ shifts the character in $t$ occupies different positions, and one of them matches the one of the character of $s$); therefore, there exist $n$ cyclic shifts of $s$ and $t$ that superpose these characters (the situation is symmetrical for every position of the character of $s$). It follows that the input in $ \\rho $ from a single character $t_{i}$ is equal to $n  \\times $(the number of characters in $s$ equal to $t_{i}$). Therefore, $ \\rho (s, t)$ is maximal when every character of $t$ occurs the maximal possible number of times in $s$. Simply count the number of occurences for every type of characters; the answer is $K^{n}$, where $K$ is the number of character types that occur in $s$ most frequently. This is an $O(n)$ solution.",
    "tags": [
      "math",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "520",
    "index": "D",
    "title": "Cubes",
    "statement": "Once Vasya and Petya assembled a figure of $m$ cubes, each of them is associated with a number between $0$ and $m - 1$ (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the $OX$ is the ground, and the $OY$ is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.\n\nThe figure turned out to be \\underline{stable}. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch \\textbf{by a side or a corner}. More formally, this means that for the cube with coordinates $(x, y)$ either $y = 0$, or there is a cube with coordinates $(x - 1, y - 1)$, $(x, y - 1)$ or $(x + 1, y - 1)$.\n\nNow the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the $m$-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.\n\nYour task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo $10^{9} + 9$.",
    "tutorial": "Basically, the first player should maximize the lexicographical order of numbers, and the second player should minimize it. Thus, at every move the first player should choose the largest available number, and the second should choose the minimal one. First of all, how do we check if the cube can be removed? It is impossible only if there is some cube \"supported\" by it (i.e., it has coordinates $(x - 1, y + 1)$, $(x, y + 1)$, $(x + 1, y + 1)$) such that our cube is the only one supporting it. This can be checked explicitly. The large coordinates' limitations do not allow us to store a simply array for that, so we should use an associative array, like a set in C++. Now we should find the maximal/minimal number that can be removed. A simple linear search won't work fast enough, so we store another data structure containing all numbers available to remove; the structure should allow inserting, erasing and finding global minimum/maximum, so the set C++ structure fits again. When we've made our move, some cubes may have become available or unavailable to remove. However, there is an $O(1)$ amount of cubes we have to recheck and possibly insert/erase from our structure: the cubes $(x  \\pm  1, y)$ and $(x  \\pm  2, y)$ may have become unavailable because some higher cube has become dangerous (that is, there is a single cube supporting it), and some of the cubes $(x - 1, y - 1)$, $(x, y - 1)$ and $(x + 1, y - 1)$ may have become available because our cube was the only dangerous cube that it has been supporting. Anyway, a simple recheck for these cubes will handle all the cases. This solution is $O(n\\log n)$ if using the appropriate data structure.",
    "tags": [
      "games",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "520",
    "index": "E",
    "title": "Pluses everywhere",
    "statement": "Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out $n$ numbers on a single line. After that, Vasya began to write out different ways to put pluses (\"+\") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.\n\nThe lesson was long, and Vasya has written all the correct ways to place exactly $k$ pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo $10^{9} + 7$. Help him!",
    "tutorial": "Consider some way of placing all the pluses, and a single digit $d_{i}$ (digits in the string are numbered starting from 0 from left to right). This digit gives input of $d_{i} \\cdot 10^{l}$ to the total sum, where $l$ is the distance to the nearest plus from the right, or to the end of string if there are no pluses there. If we sum up these quantities for all digits and all ways of placing the pluses, we will obtain the answer. For a given digit $d_{i}$ and some fixed $l$, how many ways are there to place the pluses? First of all, consider the case when the part containing the digit $d_{i}$ is not last, that is, $i + l < n - 1$. There are $n - 1$ gaps to place pluses in total; the constraint about $d_{i}$ and the distance $l$ means that after digits $d_{i}$, $...$, $d_{i + l - 1}$ there are no pluses, while after the digit $d_{i + l}$ there should be a plus. That is, the string should look as follows: $\\cdot\\cdot\\cdot d_{i-1}{}^{\\gamma}\\underbrace{d_{i}\\cdot d_{i+1}\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot d_{i+l-1}}_{\\mathrm{distance~1}}+d_{i+l+1}{}^{+d_{i+1}+\\cdot\\cdot\\cdot\\cdot\\cdot}\\ .$ Here a dot means a gap without a plus, and a question mark means that it's not important whether there is a plus or not. So, out of $n - 1$ possible gaps there are $l + 1$ gaps which states are defined, and there is one plus used in these gaps. That means that the other $(n - 1) - (l + 1) = n - l - 2$ gaps may contain $k - 1$ pluses in any possible way; that is, the number of such placements is $\\textstyle{\\binom{n-l-2}{k-1}}$. A similar reasoning implies that if the digit $d_{i}$ is in the last part, that is, $i + l = n - 1$, the number of placements is ${\\binom{n-l-1}{k}}=\\binom{i}{k}$. To sum up, the total answer is equal to $\\begin{array}{c}{{\\displaystyle\\sum\\!\\!\\!\\!\\!\\!\\slash^{n-1}\\left(\\sum\\!\\!\\!\\!\\!\\slash^{n-2-i}\\left(\\binom{n-j\\!\\!\\!\\slash^{-}}{k-1}\\right)\\cdot d_{i}|\\left(\\!\\!\\slash^{i}\\right)\\!\\!\\!\\slash^{j}\\right)\\!\\!\\!\\!\\slash^{j}\\!\\!\\!\\slash\\:\\!\\!\\ J^{j}\\!\\!\\!\\slash\\:\\!\\!\\!\\slash^{j}\\!\\!\\!\\slash\\:\\!\\!\\!\\slash}\\!\\!\\slash^{j}\\!\\!\\!\\slash\\:\\!\\!\\!\\slash}\\!\\!\\slash\\end{array}$ Let us transform the sum: $\\textstyle{\\sum_{l=0}^{n-2}\\left(10^{l}{\\binom{n-l-2}{k-1}}\\sum_{i=0}^{n-l-2}d_{i}\\right)+\\sum_{i=0}^{n-1}\\left(d_{i}10^{n-1-i}\\left({\\frac{i}{k}}\\right)\\right).$ To compute these sums, we will need to know all powers of 10 up to $n$-th (modulo $10^{9} + 7$), along with the binomial coefficients. To compute the binomials, recall that ${\\binom{n}{k}}={\\frac{n!}{k!(n-k)!}}$, so it is enough to know all the numbers $k!$ for $k$ upto $n$, along with their modular inverses. Also we should use the prefix sums of $d_{i}$, that is, the array $s d_{i}=\\sum_{j=0}^{t}d_{j}$. The rest is simple evaluation of the above sums. The total complexity is $O(n\\log p)$, because the common algorithms for modular inverses (that is, Ferma's little theorem exponentiation or solving a diophantine equation using the Euclid's algorithm) have theoritcal worst-case complexity of $O(\\log p)$. However, one can utilize a neat trick for finding modular inverses for first $n$ consecutive numbers in linear time for a total complexity of $O(n)$; for the description of the method refer to this comment by Kaban-5 (not sure why it has a negative rating, I found this quite insightful; maybe anyone can give a proper source for this method?).",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "521",
    "index": "D",
    "title": "Shop",
    "statement": "Vasya plays one very well-known and extremely popular MMORPG game. His game character has $k$ skill; currently the $i$-th of them equals to $a_{i}$. Also this game has a common rating table in which the participants are ranked according to the \\textbf{product} of all the skills of a hero in the descending order.\n\nVasya decided to 'upgrade' his character via the game store. This store offers $n$ possible ways to improve the hero's skills; Each of these ways belongs to one of three types:\n\n- assign the $i$-th skill to $b$;\n- add $b$ to the $i$-th skill;\n- multiply the $i$-th skill by $b$.\n\nUnfortunately, a) every improvement can only be used once; b) the money on Vasya's card is enough only to purchase not more than $m$ of the $n$ improvements. Help Vasya to reach the highest ranking in the game. To do this tell Vasya which of improvements he has to purchase and in what order he should use them to make his rating become as high as possible. If there are several ways to achieve it, print any of them.",
    "tutorial": "Suppose the only type of upgrades we have is multiplication. It doesn't even matter for the answer which particular skill we are going to multiply, so we just choose several upgrades with greatest values of $b_{i}$. Now we have additions as well; set multiplications aside for a moment. It is clear that for every skill we should choose several largest additions (maybe none). Let us sort the additions for every skill by non-increasing; now we should choose several first upgrades for each type. Now, for some skill the (non-increasing) sorted row of $b$'s is $b_{1}$, $...$, $b_{l}$, and the initial value of the skill is $a$. Now, as we have decided to take some prefix of $b$'s, we know that if we take the upgrade $b_{i}$, the value changes from $a + b_{1} + ... + b_{i - 1}$ to $a + b_{1} + ... + b_{i - 1} + b_{i}$. That is, the ratio by which the value (and the whole product of values) is going to be multiplied by is the fraction $\\frac{a+b_{1}+....+b_{i-1}+b_{i}}{a+b_{1}+...+b_{i-1}}$. Now, with that ratio determined unambigiously for each addition upgrade, every addition has actually become a multiplication. =) So we have to compute the ratios for all additions (that is, we sort $b$'s for each skill separately and find the fractions), and then sort the multiplications and additions altogether by the ratio they affect the whole product with. Clearly, all multiplications should be used after all the additions are done; that is, to choose which upgrades we use we should do the ratio sorting, but the order of actual using of upgrades is: first do all the additions, then do all the multiplications. Finally, let's deal with the assignment upgrades. Clearly, for each skill at most one assignment upgrade should be used, and if it used, it should the assignment upgrade with the largest $b$ among all assignments for this skill. Also, if the assignment is used, it should be used before all the additions and multiplications for this skill. So, for each skill we should simply determine whether we use the largest assignment for this skill or not. However, if we use the assignment, the ratios for the additions of current skill become invalid as the starting value of $a$ is altered. To deal with this problem, imagine that we have first chosen some addition upgrades, and now we have to choose whether we use the assignment upgrade or not. If we do, the value of the skill changes from $a + b_{1} + ... + b_{k}$ to $b + b_{1} + ... + b_{k}$. That is, the assignment here behaves pretty much the same way as the addition of $b - a$. The only difference is that once we have chosen to use the assignment, we should put it before all the additions. That is, all largest assigments for each skill should be made into additions of $b - a$ and processed along with all the other additions, which are, as we already know, going to become multiplications in the end. =) Finally, the problem is reduced to sorting the ratios for all upgrades. Let us estimate the numbers in the fractions. The ratio for a multiplication is an integer up to $10^{6}$; the ratio for an addition is a fraction of general form $\\frac{a+b_{1}+...+b_{k}}{a+b_{1}+...+b_{k-1}}$. As $k$ can be up to $10^{5}$, and $b_{i}$ is up to $10^{6}$, the numerator and denominator of such fraction can go up to $10^{11}$. To compare fractions $\\overset{\\stackrel{\\rightarrow}}{b}$ and $\\frac{\\epsilon}{a}$ we should compare the products $ad$ and $bc$, which can go up to $10^{22}$ by our estimates. That, unfortunately, overflows built-in integer types in most languages. However, this problem can be solved by subtracting 1 from all ratios (which clearly does not change the order of ratios), so that the additions' ratios will look like $\\frac{b_{k}}{a+b_{1}+\\ldots+b_{k-1}}$. Now, the numerator is up to $10^{6}$, the products in the comparison are up to $10^{17}$, which fits in 64-bit integer type in any language.",
    "tags": [
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "521",
    "index": "E",
    "title": "Cycling City",
    "statement": "You are organizing a cycling race on the streets of the city. The city contains $n$ junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself.\n\nYou want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route — the chain of junctions, consecutively connected by roads. Routes must meet the following conditions:\n\n- all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same);\n- to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes);\n- no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit).\n\nPreparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met.",
    "tutorial": "We have to find two vertices in an undirected graph such that there exist three vertex- and edge-independent paths between them. This could easily be a flow problem if not for the large constraints. First of all, we can notice that all the paths between vertices should lie in the same biconnected component of the graph. Indeed, for every simple cycle all of its edges should lie in the same biconnected component, and the three-paths system is a union of cycles. Thus, we can find all the biconnected components of the graph and try to solve the problem for each of them independently. The computing of biconnected components can be done in linear time; a neat algorithm for doing this is described in the Wikipedia article by the link above. Now, we have a biconnected component and the same problem as before. First of all, find any cycle in this component (with a simple DFS); the only case of a biconnected component that does not contain a cycle is a single edge, which is of no interest. Suppose that no vertex of this cycle has an adjacent edge that doesn't lie in the cycle; this means the cycle is not connected to anything else in the component, so the component is this cycle itself, in which case there is clearly no solution. Otherwise, find a vertex $v$ with an adjacent edge $e$ that doesn't lie in the cycle (denote it $c$). If we can find a path $p$ starting with $e$ that arrives at a cycle vertex $u$ (different from $v$), then we can find three vertex-distinct paths between $v$ and $u$: one path is $p$, and two others are halves of the initial cycle. To find $p$, start a DFS from the edge $e$ that halts when it arrives to vertex of $c$ (that is different from $v$) and recovers all the paths. What if we find that no appropriate path $p$ exists? Denote $C$ the component traversed by the latter DFS. The DFS did not find any path between vertices of $C\\ {v}$ and $c\\ {v}$, therefore every such path should pass through $v$. That means that upon deletion of $v$, the component $C\\ {v}$ becomes separated from all vertices of $c\\ {v}$, which contradicts with the assumption that the component was biconnected. That reasoning proves that the DFS starting from $e$ will always find the path $p$ and find the answer if only a biconnected component was not a cycle nor a single edge. Finally, we obtain that the only case when the answer is non-existent is when all the biconnected components are single edges or simple cycles, that is, the graph is a union of disconnected cactuses. Otherwise, a couple of DFS are sure to find three vertex-disjoint paths. This yields an $O(n + m)$ solution; a few logarithmic factors for simplification here and there are also allowed.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 3100
  },
  {
    "contest_id": "524",
    "index": "C",
    "title": "The Art of Dealing with ATM",
    "statement": "ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most $k$ bills from it, and the bills may be of at most two distinct denominations.\n\nFor example, if a country uses bills with denominations $10$, $50$, $100$, $500$, $1000$ and $5000$ burles, then at $k = 20$ such ATM can give sums $100 000$ burles and $96 000$ burles, but it cannot give sums $99 000$ and $101 000$ burles.\n\nLet's suppose that the country uses bills of $n$ distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash $q$ times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the $q$ of requests for cash withdrawal.",
    "tutorial": "Intended solution has the complexity $O(n k\\log(n k)+q n k)$ or $O(n k\\log(n k)+q n k\\log(n k))$. For each possible value $x$ that we can get write a pair $(x, m)$ where $m$ is number of bills to achieve this value. Sort this array in ascending order of $x$ and leave only the best possible number of bills for each value of $x$. Then to answer a query we should iterate over the first summand in resulting sum and look for the remainder using binary search. The alternate way is the method of two pointers for looking in an array for a pair of numbers with a given sum that works in amortized $O(1)$ time. Check that we used no more than $k$ bills totally and relax the answer if needed.",
    "tags": [
      "binary search",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "524",
    "index": "D",
    "title": "Social Network",
    "statement": "Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.\n\nBut wait, something is still known, because that day a record was achieved — $M$ simultaneous users online! In addition, Polycarpus believes that if a user made a request at second $s$, then he was online for $T$ seconds after that, that is, at seconds $s$, $s + 1$, $s + 2$, ..., $s + T - 1$. So, the user's time online can be calculated as the union of time intervals of the form $[s, s + T - 1]$ over all times $s$ of requests from him.\n\nGuided by these thoughts, Polycarpus wants to assign a user ID to each request so that:\n\n- the number of different users online did not exceed $M$ at any moment,\n- at some second the number of distinct users online reached value $M$,\n- the total number of users (the number of distinct identifiers) was as much as possible.\n\nHelp Polycarpus cope with the test.",
    "tutorial": "Let's follow greedily in following way. Iterate over all requests in a chronological order. Let's try to associate each query to the new person. Of course we can't always do that: when there are already $M$ active users on a site, we should associate this request with some existing person. Now we need to choose, who it will be. Let's show that the best way is to associate a request with the most recently active person. Indeed, such \"critical\" state can be represented as a vector consisting of $M$ numbers that are times since the last request for each of the active people in descending order. If we are currently in the state $(a_{1}, a_{2}, ..., a_{M})$, then we can move to the one of the $M$ new states $(a_{1}, a_{2}, ..., a_{M - 1}, 0)$, $(a_{1}, a_{2}, ..., a_{M - 2}, a_{M}, 0)$, $...$ , $(a_{2}, a_{3}, ..., a_{M}, 0)$ depending on who we will associate the new request with. We can see that the first vector is component-wise larger then other ones, so it is better than other states (since the largest number in some component of vector means that this person will probably disappear earlier giving us more freedom in further operations). So, all we have to do is to simulate the process keeping all active people in some data structure with times of their last activity. As a such structure one can use anything implementing the priority queue interface (priority_queue, set, segment tree or anything else). Complexity of such solution is $O(n\\log n)$.",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "524",
    "index": "E",
    "title": "Rooks and Rectangles",
    "statement": "Polycarpus has a chessboard of size $n × m$, where $k$ rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated $q$ rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of ​​the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected.",
    "tutorial": "Let's understand what does it mean that some cell isn't attacked by any rook. It means that there exists row and column of the rectangle without rooks on them. It's hard to check this condition, so it is a good idea to check the opposite for it. We just shown that the rectangle is good if on of the two conditions holds: there should be a rook in each row of it or there should be a rook in each column. We can check those conditions separately. How can we check that for a set of rectangles there is a point in each row? This can be done by sweeping vertical line from left to right. Suppose we are standing in the right side of a rectangle located in rows from $a$ to $b$ with the left side in a column $y$. Then if you denote as $last[i]$ the position of the last rook appeared in a row number $i$, the criteria for a rectangle looks like $\\operatorname*{min}_{a\\leq i\\leq b}l a s t[i]\\geq x$. That means that we can keep the values $last[i]$ in a segment tree and answer for all rectangles in logarithmic-time. Similarly for columns. This solution answers all queries in off-line in time $O((q + k)log(n + m))$.",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "524",
    "index": "F",
    "title": "And Yet Another Bracket Sequence",
    "statement": "Polycarpus has a finite sequence of opening and closing brackets. In order not to fall asleep in a lecture, Polycarpus is having fun with his sequence. He is able to perform two operations:\n\n- adding any bracket in any position (in the beginning, the end, or between any two existing brackets);\n- cyclic shift — moving the last bracket from the end of the sequence to the beginning.\n\nPolycarpus can apply any number of operations to his sequence and adding a cyclic shift in any order. As a result, he wants to get the correct bracket sequence of the minimum possible length. If there are several such sequences, Polycarpus is interested in the lexicographically smallest one. Help him find such a sequence.\n\nAcorrect bracket sequence is a sequence of opening and closing brackets, from which you can get a correct arithmetic expression by adding characters \"1\" and \"+\" . Each opening bracket must correspond to a closed one. For example, the sequences \"(())()\", \"()\", \"(()(()))\" are correct and \")(\", \"(()\" and \"(()))(\" are not.\n\nThe sequence $a_{1}$ $a_{2}... a_{n}$ is lexicographically smaller than sequence $b_{1}$ $b_{2}... b_{n}$, if there is such number $i$ from $1$ to $n$, that$a_{k} = b_{k}$ for $1 ≤ k < i$ and $a_{i} < b_{i}$. Consider that \"(\" $ < $ \")\".",
    "tutorial": "The main idea is that the bracket sequence can be seen as a sequence of prefix balances, i. e sequence $(a_{i})$ such that $a_{i + 1} = a_{i}  \\pm  1$. Calculate the number of opening brackets $A$ and closing brackets $B$ in original string. It is true that if $A > = B$ then the string can be fixed by adding $A - B$ closing brackets at the end and shifting the resulting string to the point of balance minimum, and if $A  \\le  B$, then the string can be similarly fixed by adding $B - A$ opening brackets to the beginning and then properly shifting the whole string. It's obvious that it is impossible to fix the string by using the less number of brackets. So we know the value of the answer, now we need to figure out how it looks like. Suppose that we first circularly shift and only then add brackets. Suppose that we add $x$ closing brackets. Consider the following two facts: If it is possible to fix a string by adding closing bracket to some $x$ positions then it is possible to fix it by adding $x$ closing brackets to the end of the string. From all strings obtained from a give one by adding closing brackets to $x$ positions, the minimum is one that obtained by putting $x$ closing brackets to the end. Each of those statements is easy to prove. They give us the fact that in the optimal answer we put closing brackets at the end of the string (after rotating the initial string). So we have to consider the set of the original string circular shifts such that they transform to the correct bracket sequence by adding $x = A - B$ closing brackets to the end and choose the lexicographically least among them. Comparing circular shifts of the string is the problem that can be solved by a suffix array. The other way is to find lexicographical minimum among them by using hashing and binary search to compare two circular shifts. The case when $A  \\le  B$ is similar except that opening brackets should be put into the beginning of the string. So, overall complexity is $O(n\\log n)$.",
    "tags": [
      "data structures",
      "greedy",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "525",
    "index": "A",
    "title": "Vitaliy and Pie",
    "statement": "After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with $n$ room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the ($n - 1$)-th room to the $n$-th room. Thus, you can go to room $x$ only from room $x - 1$.\n\nThe potato pie is located in the $n$-th room and Vitaly needs to go there.\n\nEach pair of consecutive rooms has a door between them. In order to go to room $x$ from room $x - 1$, you need to open the door between the rooms with the corresponding key.\n\nIn total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type $t$ can open the door of type $T$ if and only if $t$ and $T$ are the same letter, written in different cases. For example, key f can open door F.\n\nEach of the first $n - 1$ rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.\n\nVitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room $n$.\n\nGiven the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room $n$, which has a delicious potato pie. Write a program that will help Vitaly find out this number.",
    "tutorial": "To solve this problem we need to use array $cnt[]$. In this array we will store number of keys of every type, which we already found in rooms, but didn't use. Answer will store in variable ans. Now, we iterate on string. If current element of string $s_{i}$ is lowercase letter (key), we make $cnt[s_{i}]$++. Else if current element of string $s_{i}$ uppercase letter (door) and $cnt[tolower(s_{i})] > 0$, we make $cnt[tolower(s_{i})]$--, else we make $ans$++. It remains only to print ans. Asymptotic behavior of this solution - O($|s|$), where $|s|$ - length of string $s$.",
    "tags": [
      "greedy",
      "hashing",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "525",
    "index": "B",
    "title": "Pasha and String",
    "statement": "Pasha got a very beautiful string $s$ for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to $|s|$ from left to right, where $|s|$ is the length of the given string.\n\nPasha didn't like his present very much so he decided to change it. After his birthday Pasha spent $m$ days performing the following transformations on his string — each day he chose integer $a_{i}$ and \\textbf{reversed} a piece of string (a segment) from position $a_{i}$ to position $|s| - a_{i} + 1$. It is guaranteed that $2·a_{i} ≤ |s|$.\n\nYou face the following task: determine what Pasha's string will look like after $m$ days.",
    "tutorial": "At first we need to understand next fact - it doesn't matter in wich order make reverses, answer will be the same for all orders. Let's numerate elements of string from one. To solve given problem we need to count how many reverses will begin in every position of string. Then we need to count array $sum[]$. In $sum[i]$ we need to store count of reverses of substrings, which begin in positions which not exceeding $i$. Now iterate for $i$ from $1$ to $n / 2$ and if $sum[i]$ is odd swap $s_{i}$ and $s_{n - i + 1}$. After that it remains only to print string $s$. Asymptotic behavior of this solution - O($n$ + $m$), where $n$ - length of string $s$, $m$ - count of reverses.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "525",
    "index": "C",
    "title": "Ilya and Sticks",
    "statement": "In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of $n$ sticks and an instrument. Each stick is characterized by its length $l_{i}$.\n\nIlya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed.\n\nSticks with lengths $a_{1}$, $a_{2}$, $a_{3}$ and $a_{4}$ can make a rectangle if the following properties are observed:\n\n- $a_{1} ≤ a_{2} ≤ a_{3} ≤ a_{4}$\n- $a_{1} = a_{2}$\n- $a_{3} = a_{4}$\n\nA rectangle can be made of sticks with lengths of, for example, $3 3 3 3$ or $2 2 4 4$. A rectangle cannot be made of, for example, sticks $5 5 5 7$.\n\nIlya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length $5$ can either stay at this length or be transformed into a stick of length $4$.\n\nYou have to answer the question — what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?",
    "tutorial": "This problem can be solved with help of greedy. At first count array $cnt[]$. In $cnt[i]$ will store how many sticks with length $i$ we have. Now iterate for len from maximal length of sticks to minimal. If $cnt[len]$ is odd and we have sticks with length $len - 1$ (that is $cnt[len - 1] > 0$), make $cnt[len]$-- and $cnt[len - 1]$++. If $cnt[len]$ is odd and we have no sticks with length $len - 1$ (that is $cnt[len - 1] = 0$), make $cnt[len]$--. In this way we properly done all sawing which we need and guaranteed that all $cnt[len]$ is even. After that iterate similary on length of sticks and greedily merge pairs from $2$ sticks with the same length in fours. It will be length of sides of sought-for rectangles, left only summarize their squares in answer. In the end can left $2$ sticks without pair, we must not consider them in answer. For example, if $cnt[5] = 6$, $cnt[4] = 4$, $cnt[2] = 4$, we need to merge this sticks in following way - ($5, 5, 5, 5$), ($5, 5, 4, 4$), ($4, 4, 2, 2$). Two sticks with length $2$ are left, we must not count them. Asymptotic behavior of this solution - O($n + maxlen - minlen$), where $n$ - count of sticks, $maxlen$ - maximal length of stick, $minlen$ - minimal length of stick.",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "525",
    "index": "D",
    "title": "Arthur and Walls",
    "statement": "Finally it is a day when Arthur has enough money for buying an apartment. He found a great option close to the center of the city with a nice price.\n\nPlan of the apartment found by Arthur looks like a rectangle $n × m$ consisting of squares of size $1 × 1$. Each of those squares contains either a wall (such square is denoted by a symbol \"*\" on the plan) or a free space (such square is denoted on the plan by a symbol \".\").\n\nRoom in an apartment is a maximal connected area consisting of free squares. Squares are considered adjacent if they share a common side.\n\nThe old Arthur dream is to live in an apartment where all rooms are rectangles. He asks you to calculate minimum number of walls you need to remove in order to achieve this goal. After removing a wall from a square it becomes a free square. While removing the walls it is possible that some rooms unite into a single one.",
    "tutorial": "To solve this problem we need to observe next fact. If in some square whith size $2  \\times  2$ in given matrix there is exactly one asterisk, we must change it on dot. That is if in matrix from dots and asterisks is not square $2  \\times  2$ in which exactly one asterisk and three dots, then all maximum size of the area from dots connected by sides represent rectangles. Now solve the problem with help of bfs and this fact. Iterate on all asterisks in given matrix and if only this asterisk contains in some $2  \\times  2$ square, change this asterisk on dot and put this position in queue. Than we need to write standart bfs, in which we will change asterisks on dots in all come out $2  \\times  2$ squares with exactly one asterisk. Asymptotic behavior of this solution - O($n * m$), where $n$ and $m$ sizes of given matrix.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "525",
    "index": "E",
    "title": "Anya and Cubes",
    "statement": "Anya loves to fold and stick. Today she decided to do just that.\n\nAnya has $n$ cubes lying in a line and numbered from $1$ to $n$ from left to right, with natural numbers written on them. She also has $k$ stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes.\n\nAnya can stick an exclamation mark on the cube and get the factorial of the number written on the cube. For example, if a cube reads $5$, then after the sticking it reads $5!$, which equals $120$.\n\nYou need to help Anya count how many ways there are to choose some of the cubes and stick on some of the chosen cubes at most $k$ exclamation marks so that the sum of the numbers written on the chosen cubes after the sticking becomes equal to $S$. Anya can stick at most one exclamation mark on each cube. Can you do it?\n\nTwo ways are considered the same if they have the same set of chosen cubes and the same set of cubes with exclamation marks.",
    "tutorial": "To solve this problem we need to use meet-in-the-middle. At first sort given array in increasing order and divide it in two parts. In first part must be first $n / 2$ elements, in second part - other. Iterate all submasks of all masks of elements from first part. That is iterate which cubes from first part we take and on which from them we paste exclamation marks. In this way we iterated all possible sums, which we can get with cubes from first part. Let for current submask we get sum sum_lf and use $t_{lf}$ exclamation marks. To store all such sums we use associative arrays $map < long long > cnt[k$ + $1]$, where $k$ - count of exclamation marks which we have in the beginning. After that similary iterate all submasks of all masks of elements from second part. Let for current submask sum is $sum_{rg}$ and number of used exclamation marks is $t_{rg}$. Then from first part we need to get sum ($s - sum_{rg}$) and we can use only ($k - t_{rg}$) exclamation marks, where $s$ - sum which we must get by condition of the problem. Then iterate how many exclamation marks we will use in first part (let it be variable cur) and increase answer on $cnt[cur][s - sum_{rg}]$. To accelerate our programm we may increase answer only if $cnt[cur].count(s - sum_{rg}) = true$. For submasks in iterate we can cut off iteration on current sum for submask (it must be less or equal to given $s$) and on current count of exclamation marks (it must be less or equal to given $k$). Also we should not paste exclamation marks on cubecs with numbers larger than $18$, because $19!$ more than $10^{16}$ - maximal value of $s$. Asymptotic behavior of this solution - O($3^{((n + 1) / 2)} * log(maxcnt) * k$), where $n$ - count of cubes, $maxcnt$ - maximal size of associative array, $k$ - count of exclamation marks.",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "dp",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 2100
  },
  {
    "contest_id": "526",
    "index": "A",
    "title": "King of Thieves",
    "statement": "In this problem you will meet the simplified model of game King of Thieves.\n\nIn a new ZeptoLab game called \"King of Thieves\" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way.\n\nAn interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.\n\nA dungeon consists of $n$ segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.\n\nOne of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number $i_{1}$, he can make a sequence of jumps through the platforms $i_{1} < i_{2} < ... < i_{k}$, if $i_{2} - i_{1} = i_{3} - i_{2} = ... = i_{k} - i_{k - 1}$. Of course, all segments $i_{1}, i_{2}, ... i_{k}$ should be exactly the platforms, not pits.\n\nLet's call a level to be good if you can perform a sequence of \\textbf{four} jumps of the same length or in the other words there must be a sequence $i_{1}, i_{2}, ..., i_{5}$, consisting of \\textbf{five} platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.",
    "tutorial": "This task is easy for many of you. We can just iterate over all possible $i_{1}$ and $i_{2} - i_{1}$, then we can compute $i_{3, ..., 5}$, and check whether this subsequence satisfies the condition mentioned in the task.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "526",
    "index": "B",
    "title": "Om Nom and Dark Park",
    "statement": "Om Nom is the main character of a game \"Cut the Rope\". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.\n\nThe park consists of $2^{n + 1} - 1$ squares connected by roads so that the scheme of the park is a full binary tree of depth $n$. More formally, the entrance to the park is located at the square $1$. The exits out of the park are located at squares $2^{n}, 2^{n} + 1, ..., 2^{n + 1} - 1$ and these exits lead straight to the Om Nom friends' houses. From each square $i$ ($2 ≤ i < 2^{n + 1}$) there is a road to the square $\\left\\lfloor{\\frac{i}{2}}\\right\\rfloor$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly $n$ roads.\n\nTo light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square $i$ to square $\\left\\lfloor{\\frac{i}{2}}\\right\\rfloor$ has $a_{i}$ lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe.\n\nHe asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.",
    "tutorial": "We use greedy and recursion to solve this task. For each tree rooted at $v$, we adjust its two subtrees at first, using recursion. Then we increase one edge from $v$'s child to $v$.",
    "tags": [
      "dfs and similar",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "526",
    "index": "C",
    "title": "Om Nom and Candies",
    "statement": "A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place?\n\nOne day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs $W_{r}$ grams and each blue candy weighs $W_{b}$ grams. Eating a single red candy gives Om Nom $H_{r}$ joy units and eating a single blue candy gives Om Nom $H_{b}$ joy units.\n\nCandies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than $C$ grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.",
    "tutorial": "If there is a kind of candy which weighs greater than $\\sqrt{C}$, then we can iterate over the number of it to buy, which is less than $\\sqrt{C}$. Otherwise, without loss of generality we suppose ${\\frac{H_{b}}{W_{b}}}<{\\frac{H_{s}}{W_{r}}}$. If the number of the blue candies that Om Nom eats is more than $W_{r}$, he could eat $W_{b}$ red candies instead of $W_{r}$ blue candies, because $H_{b}  \\times  W_{r} < W_{b}  \\times  H_{r}$. It means the number of the blue candies will be less than $\\sqrt{C}$, and we can iterate over this number.",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "526",
    "index": "D",
    "title": "Om Nom and Necklace",
    "statement": "One day Om Nom found a thread with $n$ beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly.\n\nOm Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regular pattern. A sequence of beads $S$ is regular if it can be represented as $S = A + B + A + B + A + ... + A + B + A$, where $A$ and $B$ are some bead sequences, \"$ + $\" is the concatenation of sequences, there are exactly $2k + 1$ summands in this sum, among which there are $k + 1$ \"$A$\" summands and $k$ \"$B$\" summands that follow in alternating order. Om Nelly knows that her friend is an eager mathematician, so she doesn't mind if $A$ or $B$ is an empty sequence.\n\nHelp Om Nom determine in which ways he can cut off the first several beads from the found thread (at least one; probably, all) so that they form a regular pattern. When Om Nom cuts off the beads, he doesn't change their order.",
    "tutorial": "This task is to determine whether a string is in the form of $ABABA... ABA$ for each prefixes of a given string $S$ For a prefix P, let's split it into some blocks, just like $P = SSSS... SSSST$, which $T$ is a prefix of $S$. Obviously, if we use KMP algorithm, we can do it in linear time, and the length of $S$ will be minimal. There are only two cases : $T = S, T  \\neq  S$. $T = S$. When $T = S, P = SSS... S$. Assume that $S$ appears $R$ times. Consider \"ABABAB....ABABA\", the last $A$ must be a suffix of $P$, and it must be like $SS... S$, so $A$ will be like $SS... SS$, and so will $B$. By greedy algorithm, the length of $A$ will be minimal, so it will be $SSS... S$, where $S$ appears $R{\\mathrm{~mod~}}Q$ times. And $B$ will be $SSS... S$, where $S$ appears $(R/Q-R\\mod Q)$ times. So we just need to check whether $R/Q-R\\mod Q\\geq0$. $T  \\neq  S$ . When $T  \\neq  S$, the strategy is similar to $T = S$. A will be like \"SS...ST\", and its length will be minimal. At last we just need to check whether $R/Q-R\\mod Q>0$ . The total time complexity is $O(n)$.",
    "tags": [
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "526",
    "index": "E",
    "title": "Transmitting Levels",
    "statement": "Optimizing the amount of data transmitted via a network is an important and interesting part of developing any network application.\n\nIn one secret game developed deep in the ZeptoLab company, the game universe consists of $n$ levels, located in a circle. You can get from level $i$ to levels $i - 1$ and $i + 1$, also you can get from level $1$ to level $n$ and vice versa. The map of the $i$-th level description size is $a_{i}$ bytes.\n\nIn order to reduce the transmitted traffic, the game gets levels as follows. All the levels on the server are divided into $m$ groups and each time a player finds himself on one of the levels of a certain group for the first time, the server sends all levels of the group to the game client as a single packet. Thus, when a player travels inside the levels of a single group, the application doesn't need any new information. Due to the technical limitations the packet can contain an arbitrary number of levels but their total size mustn't exceed $b$ bytes, where $b$ is some positive integer constant.\n\nUsual situation is that players finish levels one by one, that's why a decision was made to split $n$ levels into $m$ groups so that each group was a continuous segment containing multiple neighboring levels (also, the group can have two adjacent levels, $n$ and $1$). Specifically, if the descriptions of all levels have the total weight of at most $b$ bytes, then they can all be united into one group to be sent in a single packet.\n\nDetermine, what minimum number of groups do you need to make in order to organize the levels of the game observing the conditions above?\n\nAs developing a game is a long process and technology never stagnates, it is yet impossible to predict exactly what value will take constant value $b$ limiting the packet size when the game is out. That's why the developers ask you to find the answer for multiple values of $b$.",
    "tutorial": "Our task is to compute at least how many number of blocks are needed to partition a circular sequence into blocks whose sum is less than $K$. By monotonicity, it is easy to get the length of maximal blocks which starts from 1 to $n$ in $O(n)$. Assume the block with minimal length is $A$ and its length is $T$, it is obvious that whatever the blocks are, there must be a block that it starts in $A$. So, we can iterate over all the $T$ numbers of $A$, making it the start of a block, and calculate the number of blocks. Notice that all the lengths of blocks is (non-strictly) greater than $T$, therefore the number of blocks we need is at most $N / T + 1$. We need to iterate $T$ times, but each time we can get the answer in $O(N / T)$, so finally we can check whether the answer is legal in $T * O(N / T) = O(N)$.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "526",
    "index": "F",
    "title": "Pudding Monsters",
    "statement": "In this problem you will meet the simplified model of game Pudding Monsters.\n\nAn important process in developing any game is creating levels. A game field in Pudding Monsters is an $n × n$ rectangular grid, $n$ of its cells contain monsters and some other cells contain game objects. The gameplay is about moving the monsters around the field. When two monsters are touching each other, they glue together into a single big one (as they are from pudding, remember?).\n\nStatistics showed that the most interesting maps appear if initially each row and each column contains exactly one monster and the rest of map specifics is set up by the correct positioning of the other game objects.\n\nA technique that's widely used to make the development process more efficient is reusing the available resources. For example, if there is a large $n × n$ map, you can choose in it a smaller $k × k$ square part, containing exactly $k$ monsters and suggest it as a simplified version of the original map.\n\nYou wonder how many ways there are to choose in the initial map a $k × k$ ($1 ≤ k ≤ n$) square fragment, containing exactly $k$ pudding monsters. Calculate this number.",
    "tutorial": "Actually this problem is to compute how many segments in a permutation forms a permutation of successive integers. We use divide and conquer to solve this problem. If we want to compute the answer for an interval $[1, n]$, we divide this interval into two smaller ones $[1, m], [m + 1, n]$ where $m=\\lfloor{\\frac{n+1}{2}}\\rfloor$. We only care about the segments which crosses $m$. We call the first interval $L$ and the latter one $R$. Considering the positiions of maximum numbers and minimum numbers in these valid segments, There are four possible cases: the maximum number is in $L$, the the minimum is also in $L$; the maximum number is in $R$, the the minimum is also in $R$; the maximum number is in $L$, the the minimum is in $R$; the maximum number is in $R$, the the minimum is in $L$; Let $A$ be the given sequence and we define $Lmax_{p} = max_{p  \\le  i  \\le  m}A_{i}$. Similarly we can define $Rmax_{p}, Rmin_{p}, Lmin_{p}$. For simplicity we only cares about case 1 and case 4. In Case 1, we iterate over the start position of the segment, so we know the maximum and minimum number so we can compute the length of the segment and check the corresponding segment using $Rmin$ and $Rmax$. In Case 4, we iterate over the start position again, denoted as $x$. Suppose the right end is $y$, then we know that $Lmin_{x} < Rmin_{y}, Lmax_{x} < Rmax_{y}$ so we can limit $y$ into some range. Another constraint for $y$ is that $Rmax_{y} - Lmin_{x} = y - x$, i.e. $Rmax_{y} - y = Lmin_{x} - x$. Note that when $x$ varies, the valid range for $y$ also varies, but the range is monotone, so we can maintain how many times a number appears in linear time. It's easy to show that this algorithm runs for $O(n\\log n)$, by Master Theorem. There are some other people using segment trees.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 2000010;\n \nint mn[N], add[N], cnt[N];\n \nvoid build(int x, int l, int r) {\n  mn[x] = l;\n  add[x] = 0;\n  cnt[x] = 1;\n  if (l < r) {\n    int y = (l + r) >> 1;\n    build(x + x, l, y);\n    build(x + x + 1, y + 1, r);\n  }\n}\n \ninline void push(int x) {\n  if (add[x] != 0) {\n    add[x + x] += add[x];\n    add[x + x + 1] += add[x];\n    add[x] = 0;\n  }\n}\n \ninline void gather(int x) {\n  int a = mn[x + x] + add[x + x];\n  int b = mn[x + x + 1] + add[x + x + 1];\n  mn[x] = (a < b ? a : b);\n  cnt[x] = (a == mn[x] ? cnt[x + x] : 0) + (b == mn[x] ? cnt[x + x + 1] : 0);\n}\n \nvoid modify(int x, int l, int r, int ll, int rr, int value) {\n  if (ll <= l && r <= rr) {\n    add[x] += value;\n    return;\n  }\n  push(x);\n  int y = (l + r) >> 1;\n  if (ll <= y) {\n    modify(x + x, l, y, ll, rr, value);\n  }\n  if (rr > y) {\n    modify(x + x + 1, y + 1, r, ll, rr, value);\n  }\n  gather(x);\n}\n \nint a[N];\nint up[N], down[N];\n \nint main() {\n  int n;\n  scanf(\"%d\", &n);\n  for (int i = 0; i < n; i++) {\n    a[i] = -1;\n  }\n  for (int i = 0; i < n; i++) {\n    int x, y;\n    scanf(\"%d %d\", &x, &y);\n    x--; y--;\n    a[x] = y;\n  }\n  build(1, 0, n - 1);\n  long long ans = 0;\n  int cup = 1, cdown = 1;\n  up[0] = -1;\n  down[0] = -1;\n  for (int i = 0; i < n; i++) {\n    while (cup >= 2 && a[i] < a[up[cup - 1]]) {\n      modify(1, 0, n - 1, up[cup - 2] + 1, up[cup - 1], +a[up[cup - 1]]);\n      cup--;\n    }\n    while (cdown >= 2 && a[i] > a[down[cdown - 1]]) {\n      modify(1, 0, n - 1, down[cdown - 2] + 1, down[cdown - 1], -a[down[cdown - 1]]);\n      cdown--;\n    }\n    up[cup++] = i;\n    down[cdown++] = i;\n    modify(1, 0, n - 1, up[cup - 2] + 1, up[cup - 1], -a[up[cup - 1]]);\n    modify(1, 0, n - 1, down[cdown - 2] + 1, down[cdown - 1], +a[down[cdown - 1]]);\n    ans += cnt[1];\n  }\n  cout << ans << endl;\n  return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 3000
  },
  {
    "contest_id": "526",
    "index": "G",
    "title": "Spiders Evil Plan",
    "statement": "Spiders are Om Nom's old enemies. They love eating candies as much as he does and that's why they keep trying to keep the monster away from his favorite candies. They came up with an evil plan to trap Om Nom.\n\nLet's consider a rope structure consisting of $n$ nodes and $n - 1$ ropes connecting the nodes. The structure is connected, thus, the ropes and the nodes form a tree. Each rope of the formed structure is associated with its length. A candy is tied to node $x$ of the structure. Om Nom really wants to eat this candy.\n\nThe $y$ spiders are trying to stop him from doing it. They decided to entangle the candy and some part of the structure into a web, thus attaching the candy to as large as possible part of the rope structure.\n\nEach spider can use his web to cover all ropes on the path between two arbitrary nodes $a$ and $b$. Thus, $y$ spiders can cover the set of ropes which is a union of $y$ paths in the given tree. These $y$ paths can arbitrarily intersect each other. The spiders want the following conditions to be hold:\n\n- the node containing the candy is adjacent to at least one rope covered with a web\n- the ropes covered with the web form a connected structure (what's the idea of covering with a web the ropes that are not connected with the candy?)\n- the total length of the ropes covered with web is as large as possible\n\nThe spiders haven't yet decided to what node of the structure they will tie the candy and how many spiders will cover the structure with web, so they asked you to help them. Help them calculate the optimal plan for multiple values of $x$ and $y$.",
    "tutorial": "In this task, we are given a tree and many queries. In each query, we are supposed to calculate the maximum total length of $y$ paths with the constraint that $x$ must be covered. Consider $S$ is the union of the paths (it contains nodes and edges). For each query $(x, y)$, if $y > 1$ , then there is always a method that $S$ is connected. Further, we could get the following theorem: For an unrooted tree, if it has $2k$ leaves, then $k$ paths can cover this tree completely. Proof for this theorem is that, if some edge $u - v$ is not covered, we can interchange two paths, i.e. we change two paths $a - b$ and $c - d$ to $a - c$ and $b - d$, for $a - b$ in the subtree of $u$ and $c - d$ in the subtree of $v$. So a query $(x, y)$ could be described as : Find $2y$ leaves in the tree, with node $x$ in $S$, and maximize the total of weight of the edges in $S$. For a query $(x, y)$, we can make $x$ the root. Then this task is how to choose the leaves. Note that we could select leaves one by one, every time we select the leaf which makes answer larger without selecting the others, as follow : But if for every query we need to change the root, the time complexity cannot be accepted. Assuming the longest path in the tree is $(a, b)$ , we could find that whatever the query is, $S$ will contain either $a$ or $b$ certainly. So, we just need to make $a$ and $b$ the root in turn, and get the maximum answers. However, there is another problem : $x$ may not be in $S$. Like this : But it doesn't matter. We just need to link $x$ with the selected, and erase some leaf. Of course after erasing, the answer should be maximum.",
    "tags": [
      "greedy",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "527",
    "index": "A",
    "title": "Playing with Paper",
    "statement": "One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular $a$ mm $ × $ $b$ mm sheet of paper ($a > b$). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.\n\nAfter making a paper ship from the square piece, Vasya looked on the remaining $(a - b)$ mm $ × $ $b$ mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.\n\nCan you determine how many ships Vasya will make during the lesson?",
    "tutorial": "It's easy to see that described process is equivalent to the following loop: But such naive approach will obviously lead to verdict TLE, since it makes ~$10, 2015 - 03 - 19^{12}$ operations even on the third sample test. The key idea is to replace repeating subtraction operations with integer division operations. This leads to the logarithmic-time solution that looks similar to the Euclid algorithm:",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "527",
    "index": "B",
    "title": "Error Correct System",
    "statement": "Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings $S$ and $T$ of equal length to be \"similar\". After a brief search on the Internet, he learned about the Hamming distance between two strings $S$ and $T$ of the same length, which is defined as the number of positions in which $S$ and $T$ have different characters. For example, the Hamming distance between words \"permanent\" and \"pergament\" is two, as these words differ in the fourth and sixth letters.\n\nMoreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string $S$, so that the Hamming distance between a new string $S$ and string $T$ would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.\n\nHelp him do this!",
    "tutorial": "The first observation is that the new Hamming distance may not be less than the old one minus two, since we change only two characters. So the task is to actually determine, if we can attain decrease by two, one or can't attain decrease at all. The decrease by two is possible if there are two positions with the same two letters in two strings but that appear in different order (like \"double\" <-> \"bundle\"). If there are no such positions, then we just need to check that we may decrease the distance. This can be done by just \"fixing\" the character that stands on the wrong position, like in \"permanent\" <-> \"pergament\" (here n stands in wrong pair with m, and there is also unmatched m, so we may fix this position). Otherwise, the answer is to keep everything as it is. Implementation can be done by keeping for each pair (x, y) of symbols position where such pair appears in S and T and then by carefully checking the conditions above.",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "527",
    "index": "C",
    "title": "Glass Carving",
    "statement": "Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular $w$ mm $ × $ $h$ mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.\n\nIn order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.\n\nAfter each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.\n\nLeonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?",
    "tutorial": "Obviously the largest glass piece at any moment is the one that is product of the largest horizontal segment by the largest vertical segment. One of the possible solutions is to carefully implement what described in the statement and keep all horizontal segments and all vertical segments in priority queue or std::set, or some logarithmic data structure. This solution works in $O(k*\\log(n+m))$. But there is also a nice linear solution if we answer all queries in reverse order. Suppose segments are not cutting, but merging. In this case we may keep the horizontal and vertical cut lines in double-linked lists and track the current maximum (that can only increase and become equal to the newly-merged segment each time). This solution works in $O(k + n + m)$.",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "527",
    "index": "D",
    "title": "Clique Problem",
    "statement": "The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph $G$. It is required to find a subset of vertices $C$ of the maximum size such that any two of them are connected by an edge in graph $G$. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.\n\nConsider $n$ distinct points on a line. Let the $i$-th point have the coordinate $x_{i}$ and weight $w_{i}$. Let's form graph $G$, whose vertices are these points and edges connect exactly the pairs of points $(i, j)$, such that the distance between them is not less than the sum of their weights, or more formally: $|x_{i} - x_{j}| ≥ w_{i} + w_{j}$.\n\nFind the size of the maximum clique in such graph.",
    "tutorial": "One may think that this task is about graph theory, but it after some investigation and several equivalent changes in task statement it can be reduced to the well-known greedy problem. Initially you have that points may lie together in a set if they are not too close, i. e. $|x_{i} - x_{j}|  \\ge  w_{i} + w_{j}$. This is obviously equivalent to the following condition. Let's consider interval of radius $w_{i}$ with center in point $x_{i}$ and call this interval to be the interval of point i. Then the statement actually says that no two such intervals should be intersecting. This task is well-known and can be solved greedily after sorting segments in ascending order of right endpoint: It's easy to prove that this solution is correct. Among all ways to choose first $k$ segments, the best way is the one that minimizes x-coordinate of the right endpoint of the last segment (since it restricts us in the least possible way).",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "527",
    "index": "E",
    "title": "Data Center Drama",
    "statement": "The project of a data center of a Big Software Company consists of $n$ computers connected by $m$ cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan is not yet approved, it wasn't determined yet in which direction information will go along each cable. The cables are put so that each computer is connected with each one, perhaps through some other computers.\n\nThe person in charge of the cleaning the data center will be Claudia Ivanova, the janitor. She loves to tie cables into bundles using cable ties. For some reasons, she groups the cables sticking out of a computer into groups of two, and if it isn't possible, then she gets furious and attacks the computer with the water from the bucket.\n\nIt should also be noted that due to the specific physical characteristics of the Very Important Information, it is strictly forbidden to connect in one bundle two cables where information flows in different directions.\n\nThe management of the data center wants to determine how to send information along each cable so that Claudia Ivanova is able to group all the cables coming out of each computer into groups of two, observing the condition above. Since it may not be possible with the existing connections plan, you are allowed to add the minimum possible number of cables to the scheme, and then you need to determine the direction of the information flow for each cable (yes, sometimes data centers are designed based on the janitors' convenience...)",
    "tutorial": "Problem legend asks you to add minimum number of edges to the given connected undirected graph (possibly, with loops and duplicating edges) and choose direction for its edges so that both the incoming and outgoing degrees of all vertices are even. First idea is that the resulting graph before we choose the direction (but after we added some edges) will contain Euler circuit, since all degrees are even. That's almost what we need: if we have an Euler circuit that contains even number of edges, we may direct them like following: a <- b -> c <- d -> e  \\dots  It's easy to see that each vertex appearance in this cycle adds 2 to its ingoing or outgoing degree, so the resulting degrees will be even. But if the Euler circuit is odd (meaning that there is odd number of edges in the graph), we must add some extra edge to the graph before we continue, the easiest way is to add a loop from vertex 0 to itself, since it doesn't affect the Euler tour, but now tour length is even, so everything is ok. Now we should think how to add edges optimally. It's easy to see that the optimal way is to first fix all odd degrees of vertices (i. e. combine all odd vertices by pairs and put an edge in each pair), and then, possibly, add an extra loop as described above. The last part is to actually find an Euler circuit, and to print the answer.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "528",
    "index": "D",
    "title": "Fuzzy Search",
    "statement": "Leonid works for a small and promising start-up that works on decoding the human genome. His duties include solving complex problems of finding certain patterns in long strings consisting of letters 'A', 'T', 'G' and 'C'.\n\nLet's consider the following scenario. There is a fragment of a human DNA chain, recorded as a string $S$. To analyze the fragment, you need to find all occurrences of string $T$ in a string $S$. However, the matter is complicated by the fact that the original chain fragment could contain minor mutations, which, however, complicate the task of finding a fragment. Leonid proposed the following approach to solve this problem.\n\nLet's write down integer $k ≥ 0$ — the error threshold. We will say that string $T$ occurs in string $S$ on position $i$ ($1 ≤ i ≤ |S| - |T| + 1$), if after putting string $T$ along with this position, each character of string $T$ corresponds to the some character of the same value in string $S$ at the distance of at most $k$. More formally, for any $j$ ($1 ≤ j ≤ |T|$) there must exist such $p$ ($1 ≤ p ≤ |S|$), that $|(i + j - 1) - p| ≤ k$ and $S[p] = T[j]$.\n\nFor example, corresponding to the given definition, string \"ACAT\" occurs in string \"AGCAATTCAT\" in positions $2$, $3$ and $6$.\n\nNote that at $k = 0$ the given definition transforms to a simple definition of the occurrence of a string in a string.\n\nHelp Leonid by calculating in how many positions the given string $T$ occurs in the given string $S$ with the given error threshold.",
    "tutorial": "There were issues with this task. Intended constraints were actually $n, m, k  \\le  500000$, and the intended solution was using Fast Fourier Transformation, that leads to $|\\ast n\\log n$ running time. But unfortunately the statement contained wrong constraints, so we reduced input size during the tour. Nevertheless, we will add the harder version of this task and you will be able to submit it shortly. Key idea is to reduce this task to a polynomial multiplication. Let's solve the task in following manner. For each position i of the S for each character c from \"ATGC\" we will calculate match(c, i) that is equal to the number of c characters that have matching symbol in S if we put string T in position i. Then the criteria for us to have an occurrence at position i is that match(A, i) + match(T, i) + match(G, i) + match(C, i) == |T| (that means exactly that each character from T being put at position i has a corresponding character in S). Now let's find out how to calculate match(c, i). Let's keep only c characters and \"not c\" characters in both strings and denote them by 1 and 0 respectively. Let's also spread each 1 in string S by the distance k to the left and to the right. For example, k = 1 for the sample string AGCAATTCAT and the character A corresponding bit vector will be 111110111, and for the character C it will be 0111001110. This bitvector can be calculated in $O(n)$ by putting two events \"+1\" and \"-1\" in string S in positions $x - k$ and $x + k$ for each $1$ in original string S and then sweeping from left to right over the string S and processing those events. Now our task is reduced to searching all positions where the bitvector T is the submask of the bitvector S. In constraints $n, m, k  \\le  200000$ this can be done by using bitsets in $O(m(n - m) / 32)$. Nevertheless, this task can be seen as calculation of polynomials S and reversed(T) product. We will keep this as an exercise for those who decide to submit the harder version of this task.",
    "tags": [
      "bitmasks",
      "brute force",
      "fft"
    ],
    "rating": 2500
  },
  {
    "contest_id": "528",
    "index": "E",
    "title": "Triangles 3000",
    "statement": "\\url{CDN_BASE_URL/2fdd572a668b63052b21147ea5152e78}",
    "tutorial": "Let's draw a bounding box that contains all intersection points. Let's fix a triangle and consider three angles shown on the picture. Calculate area of intersection of those area with the bounding box and call this area to be the \"area of an angle\". Then it's easy to see, that those three angles are complement to the triangle itself in the bounding box, i. e. triangle area is bounding box area minus three angle areas. This leads us to the idea how to solve this task by carefully calculating for each possible formed angle on the plane, how much times does it appear in total answer if we sum all values like $(S - angle_area(a, b) - angle_area(b, c) - angle_area(c, a))$ over all triples $(a, b, c)$ of lines. Actually, the angle is considered as many times, as many lines there are that intersect both sides of its right adjacent angle. So, our task is reduced to calculate for each angle on plane how much lines intersect its sides (i. e. its rays). This can be done in $O(n^{2}\\log{n})$ by fixing the first side of the angle and then adding lines in ascending order of polar angle, and then by keeping the number of lines that intersect the base line to the left and that intersect the base line to the right. Key idea is that the exact of four angles formed by the pair of lines $(a, b)$ that is crossed by some third line c, can be determined by two numbers: its polar angle alpha and its crossing with a coordinate x. Further details are shown on the picture below. There is also a nice short $O(n^{2})$ solution from enot110 here.",
    "code": "/* --- author: enot-the-rockstar ---*/\n#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <map>\n#include <ctime>\n#include <cassert>\n \n#define fs first\n#define sc second\n#define pb push_back\n#define mp make_pair\n#define forn(i, n) for(int i = 0 ; (i) < (n) ; ++i)\n#define forit(it,v) for(typeof((v).begin()) it = v.begin() ; it != (v).end() ; ++it)\n#define eprintf(...) fprintf(stderr, __VA_ARGS__),fflush(stderr)\n#define sz(a) ((int)(a).size())\n#define all(a) (a).begin(),a.end()\n \nstatic inline unsigned long long rdtsc() { unsigned long long d; __asm__ __volatile__ (\"rdtsc\" : \"=A\" (d) ); return d; }\n \nusing namespace std;\n \ntypedef long long ll;\ntypedef double dbl;\ntypedef vector<int> vi;\ntypedef pair<int, int> pi;\n \nconst int inf = (int)1e9;\nconst dbl eps = 1e-9;\n \n/* --- main part --- */\n \n#define TASK \"a\"\n \nconst int maxn = 3010;\n \nstruct line\n{\n    dbl a, b, c;\n    line(){}\n    line (dbl aa, dbl bb, dbl cc): a(aa), b(bb), c(cc) {}\n    void read()\n    {\n        double aa, bb, cc;\n        scanf(\"%lf%lf%lf\", &aa, &bb, &cc);\n        a = aa, b = bb, c = cc;\n    }\n    void norm()\n    {\n        dbl d = sqrt(a * a + b * b);\n        a /= d;\n        b /= d;\n        c /= d;\n        if (a < -eps) a = -a, b = -b, c = -c;\n    }\n    void rot(dbl alp)\n    {\n        dbl aa = a * cos(alp) - b * sin(alp);\n        dbl bb = a * sin(alp) + b * cos(alp);\n        a = aa;\n        b = bb;\n    }\n};\n \nline l[maxn];\npair<dbl, int> A[maxn];\n \ninline dbl getS(line l1, line l2)\n{\n    dbl Y = (l1.a * l2.c - l2.a * l1.c) / (l1.b * l2.a - l2.b * l1.a);\n    dbl DX = l2.c / l2.a - l1.c / l1.a;\n    return abs(Y * DX) / 2;\n}\n \nint main()\n{\n    #ifdef home\n        assert(freopen(TASK\".in\", \"r\", stdin));\n        assert(freopen(TASK\".out\", \"w\", stdout));\n    #endif\n    int n;\n    scanf(\"%d\", &n);\n    forn(i, n) l[i].read();\n    forn(i, n)\n    {\n        l[i].norm();\n        l[i].rot(0.123);\n        l[i].norm();\n    }\n    forn(i, n)\n    {\n        dbl alp = atan2(l[i].b, l[i].a);\n        while (alp < -M_PI / 2) alp += 2 * M_PI;\n        while (alp > M_PI / 2) alp -= 2 * M_PI;\n        A[i] = mp(alp, i);\n    }\n    sort(A, A + n);\n    dbl res = 0;\n    forn(i2, n) forn(i1, i2)\n    {\n        int ii1 = A[i1].sc;\n        int ii2 = A[i2].sc;\n        dbl S = getS(l[ii1], l[ii2]);\n        int mn = i2 - i1 - 1;\n        int pl = n - mn - 2;\n        res += S * (pl - mn);\n    }\n    dbl cnt = n * (n - 1.) * (n - 2.) / 6.;\n    res /= cnt;\n    printf(\"%.10lf\\n\", res);\n    #ifdef home\n        eprintf(\"Time: %d ms\\n\", (int)(clock() * 1000. / CLOCKS_PER_SEC));\n    #endif\n    return 0;\n}\n ",
    "tags": [
      "geometry",
      "sortings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "529",
    "index": "B",
    "title": "Group Photo 2 (online mirror version)",
    "statement": "Many years have passed, and $n$ friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.\n\nSimply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the $i$-th of them in a standing state occupies a $w_{i}$ pixels wide and a $h_{i}$ pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a $h_{i}$ pixels wide and a $w_{i}$ pixels high rectangle.\n\nThe total photo will have size $W × H$, where $W$ is the total width of all the people rectangles, and $H$ is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than $n / 2$ of them can lie on the ground (it would be strange if more than $n / 2$ gentlemen lie on the ground together, isn't it?..)\n\nHelp them to achieve this goal.",
    "tutorial": "In an online mirror version the problem was slightly harder. Let's call people with $w  \\le  h$ \\textit{high}, and remaining people \\textit{wide}. Let's fix photo height $H$. Let's consider several following cases: If a high person fits into height $H$, we leave him as is. If a high person doesn't fit into height $H$, the we have to ask him to lie down, increasing the counter of such people by $1$. If a wide person fits into height $H$, but doesn't fit lying on the ground, then we leave him staying. If a wide person fits into height $H$ in both ways, then we first ask him to stay and write into a separate array value of answer decrease if we ask him to lie on the ground: $w - h$. If somebody doesn't fit in both ways, then such value of $H$ is impossible. Now we have several people that have to lie on the ground (from second case) and if there are too many of them (more than $n / 2$) then such value of $H$ is impossible. After we put down people from second case there can still be some vacant ground positions, we distribute them to the people from fourth case with highest values of $w - h$. Then we calculate the total area of the photo and relax the answer.",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "533",
    "index": "A",
    "title": "Berland Miners",
    "statement": "The biggest gold mine in Berland consists of $n$ caves, connected by $n - 1$ transitions. The entrance to the mine leads to the cave number $1$, it is possible to go from it to any remaining cave of the mine by moving along the transitions.\n\nThe mine is being developed by the InMine Inc., $k$ miners work for it. Each day the corporation sorts miners into caves so that each cave has at most one miner working there.\n\nFor each cave we know the height of its ceiling $h_{i}$ in meters, and for each miner we know his height $s_{j}$, also in meters. If a miner's height doesn't exceed the height of the cave ceiling where he is, then he can stand there comfortably, otherwise, he has to stoop and that makes him unhappy.\n\nUnfortunately, miners typically go on strike in Berland, so InMine makes all the possible effort to make miners happy about their work conditions. To ensure that no miner goes on strike, you need make sure that no miner has to stoop at any moment on his way from the entrance to the mine to his cave (in particular, he must be able to stand comfortably in the cave where he works).\n\nTo reach this goal, you can choose exactly one cave and increase the height of its ceiling by several meters. However enlarging a cave is an expensive and complex procedure. That's why InMine Inc. asks you either to determine the minimum number of meters you should raise the ceiling of some cave so that it is be possible to sort the miners into the caves and keep all miners happy with their working conditions or to determine that it is impossible to achieve by raising ceiling in exactly one cave.",
    "tutorial": "We can add $n - k$ miners with height $0$ and it won't affect answer. So we can assume that numbers of miners and caves are the same. For every cave let's define $t_{i}$ as maximal possible height of miner working in cave $i$ if we wouldn't change any cave. We can calculate it from root to leaves with line $t_{i} = min(t_{father}, h_{i})$. Let's say we don't change anything. We will try to assign all workers if it's possible or to do the best possible assignment otherwise - the one where there are few free (not occupied) caves and they are high (value $t_{i}$ is big). I will say later why we want them to be high. Formal definition (you don't have to read the next paragraph): For every assignment let's sort free caves by $t_{i}$. In the best assignment number of free caves is minimal possible. And for every position in such a list free cave in the best assignment has value $t_{i}$ not lower than in any other assignment. It can be proven that best possible assignment exists (it's not so obvious though). How to find the best possible assignment? Let's sort caves ascending by $t_{i}$ and for every cave let's assign the tallest free miner who can work here. It will give us the best possibble assignment. Why? Let's say we've just made first bad decision (different than in the best assignment). It doesn't make sense to leave a cave empty if we can assign here someone. So we put a worker somewhere and we won't be able to do assignment now (we assumed that we've just made bad decision). From definition \"we put here tallest possible miner\" we know that we couldn't assign here taller guy. Maybe we want to assign here shorter miner and this \"highest possible\" goes somewhere else? But we can swap them and everything will be ok. So there remains last option: we don't want to put anyone here. But we will have to assign our guy to some higher cave so we can leave his destiny cave empty and put him here. To sum up, it's ok to assign highest possible free worker with iterating over caves sorted by $t_{i}$. Almost the same sentences are the proof for other lemma: If we want to have few free (not assigned) miners and we want them to be short it's optimal to iterate somehow over caves and to assign the tallest possible free miner in every cave. It works for every order of iterating over caves. And every order gives us the same set of free miners (but not necessarily the same set of free caves). Why did we want free caves to be high? Because to assign everyone we must change height of cave not higher than the lowest free cave. Why? In short: otherwise that lowest free cave will remain free after running our assignment-algo (described above) on new tree. But we managed to find maximal possible height of lowest free cave. Let's call this value as $LIM$. And we know minimal set of free miners. Changing height of cave $i$ from $a$ to something bigger does something only when $t_{i} = a  \\le  LIM$. And then in set of $t_{i}$ some changes happen. There were caves blocked before by cave $i$ so they had $t$ equal to $a$. These caves will have bigger $t$ so in set of values $t$ we have change e.g. from ${5, 5, 5}$ to ${7, 10, 8}$ ($a$ was equal to $5$). Let's throw out miners from caves with changed $t_{c}$ (maybe some of these caves were empty anyway). If we can't assign free miners (we found them before) to new caves then assigning everything isn't possible. Otherwise it is - we assign them in these caves with changed $t$ and there are some threw out miners. But all of them were in caves with $t = a  \\le  LIM$ so they are not higher than $LIM$. And we know that every free cave has $t_{free}  \\ge  LIM$ because $LIM$ is height of lowest free cave. So we can put them there. Solution is to find result with binary search and to answer question: can we assign miners to caves with changing one cave by at most $D$? With our assignment-algo we calculate optimal lowest free cave and set of free miners. Then for every cave we try to increase its height by $D$ if it had $t$ not higher than $LIM$. It's also important that checking change of every cave has amortized linear complexity. If increasing height of cave A affects $t$ of cave $B$ below then later changing height of $B$ does nothing - B is blocked by A anyway.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "533",
    "index": "B",
    "title": "Work Group",
    "statement": "One Big Software Company has $n$ employees numbered from $1$ to $n$. The director is assigned number $1$. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.\n\nWe will call person $a$ a subordinates of another person $b$, if either $b$ is an immediate supervisor of $a$, or the immediate supervisor of $a$ is a subordinate to person $b$. In particular, subordinates of the head are all other employees of the company.\n\nTo solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer $a_{i}$, where $i$ is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it.\n\nThe employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even.\n\nYour task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup.",
    "tutorial": "This problem can be solved by using dynamic programming over subtrees of company hierarchy. Denote as $D[v][e]$ maximum possible efficiency that can be obtained by taking several people from subtree of $v$ so that pairity of their number is $e$ in order condition from statement is fullfilled for all already taken people. Then it is easy to calculate $D[v][e]$ from values of children of $v$ by considering intermediate value $T[i][e]$ - maximum possible efficiency that we can obtain by using first $i$ subtrees of $v$ with overall pairity $e$. It's important to not to forget that there are two cases: we may take $v$ itself or we may decide to not take it. In first case it is important that all subtrees have overall even number of taken people. In the second case there is no such restriction.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "strings",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "533",
    "index": "C",
    "title": "Board Game",
    "statement": "Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell $(x, y)$ to $(x - 1, y)$ or $(x, y - 1)$. Vasiliy can move his pawn from $(x, y)$ to one of cells: $(x - 1, y), (x - 1, y - 1)$ and $(x, y - 1)$. \\textbf{Both players} are also allowed to skip move.\n\nThere are some additional restrictions — a player is forbidden to move his pawn to a cell with negative $x$-coordinate or $y$-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell $(0, 0)$.\n\nYou are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.",
    "tutorial": "We will consider three cases: 1) $x_{p} + y_{p}  \\le  max(x_{v}, y_{v})$. In this case Polycarp can be in $(0, 0)$ after $x_{p} + y_{p}$ moves and Vasiliy will always be ,,behind''. It's enough for Polycarp to make any move and he is always able to do it. It makes Polycarp closer to $(0, 0)$ and after Vasiliy's move we again have $x_{p} + y_{p}  \\le  max(x_{v}, y_{v})$ condition fulfilled and in some moment Polycarp will reach $(0, 0)$. It's impossible that Vasiliy wins because our condition would be unfulfilled. 2) $x_{p}  \\le  x_{v}, y_{p}  \\le  y_{v}$. In this scenario Polycarp must block Vasiliy somehow. He must make such a move that after any Vasiliy's response condition will be fulfilled again. If $x_{p} = x_{v} > 0$ he goes to $(x_{p} - 1, y_{p})$. If $y_{p} = y_{v} > 0$ he goes to $(x_{p}, y_{p} - 1)$. Otherwise he makes any move. With this strategy Vasiliy is unable to get out of our new condition. 3) Otherwise we can consider any shortest path to $(0, 0)$ for Vasiliy. Lenght of it is $max(x_{v}, y_{v})$. For any cell on this path Polycarp has greater distance than Vasiliy to it so he can't be there before Vasiliy and he can't block him. Vasiliy wins. Alternative explanation: after any possible Polycarp move Vasiliy can make a move that none of conditions (1) and (2) aren't fulfilled.",
    "tags": [
      "games",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "533",
    "index": "D",
    "title": "Landmarks",
    "statement": "We have an old building with $n + 2$ columns in a row. These columns support the ceiling. These columns are located in points with coordinates $0 = x_{0} < x_{1} < ... < x_{n} < x_{n + 1}$. The leftmost and the rightmost columns are special, we will call them bearing, the other columns are ordinary.\n\nFor each column we know its durability $d_{i}$. Let's consider an ordinary column with coordinate $x$. Let's assume that the coordinate of the closest to it column to the left (bearing or ordinary) is $a$ and the coordinate of the closest to it column to the right (also, bearing or ordinary) is $b$. In this task let's assume that this column supports the segment of the ceiling from point $\\textstyle{\\frac{\\mu+a}{2}}$ to point $\\scriptstyle{\\frac{x+b}{2}}$ (here both fractions are considered as real division). If the length of the segment of the ceiling supported by the column exceeds $d_{i}$, then the column cannot support it and it crashes after a while, and after that the load is being redistributeed between the neighbouring columns according to the same principle.\n\nThus, ordinary columns will be crashing for some time until the process stops at some state. One can prove that the set of the remaining columns doesn't depend on the order in which columns crash. If there are only two bearing columns left in the end, then we assume that the whole construction crashes under the weight of the roof. But if at least one ordinary column stays in addition to the bearing ones, then the building doesn't crash.\n\nTo make the building stronger, we can add one extra ordinary column of arbitrary durability $d'$ at any (not necessarily integer) point $0 < x' < x_{n + 1}$. If point $x'$ is already occupied by an ordinary column, it is replaced by a new one.\n\nYour task is to find out: what minimal durability can the added column have so that the building doesn't crash?",
    "tutorial": "First observation: column crashes only if distance between its neighbours is greater than $2d_{i}$ so it doesn't matter where exactly is this column. The only important thing is how far are left and right neighbour of it. For every column $C$ let's calculate does there exist subset of columns on the left that everything is stable between $C$ and leftmost bearing column. If answer is yes then how close can be left neighbour of $C$? Then we will know how far the right neighbour can be. We will use dynamic programming. Slow approach: For every previous column let's check if it can be neighbours with $C$. The closest column fulfilling this condition is best left neighbour of $C$. Faster approach: Let's denote $far[i]$ as the biggest possible coordinate where right neighbour of column $i$ can be. In our dp we need an extra stack with possible candidates for being left neighbour of new column. In this stack columns are sorted in ascending order by index (and coordinate) and in descending order by $far[i]$. For every new column we must remove from the top of stack columns which have too low $far[i]$. Then last column on stack is the best left neighbour and we can calculate value $far$ for current column. It is $O(n)$ algorithm. Some columns can't be connected with leftmost bearing column and for them we have $far[i] = 0$. If there exists column with $far[i]$ not less than coordinate of rightmost bearing column then we don't have to add new column and answer is $0$. Ok. Now let's run the same dp from right to the left. Some columns are connected with leftmost bearing column, some other columns with righmost one. And we will want to place new column somewhere between them. Brute force solution is to check every pair of columns and to say: we want these two columns to be neighbours of added column. With values $far[i]$ calculated in dp we check if we can have such a situation and we eventually consider result to be half of a distance between these two columns. How to make this last part faster? We must create two stacks with best candidates for neighbours of new column. One stack with columns connected to the leftmost column, one with the ones connected to the rightmost one. On these stacks we can find answer with two pointers technique. Whole solution is linear in time and memory.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "533",
    "index": "E",
    "title": "Correcting Mistakes",
    "statement": "Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.\n\nPolycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.\n\nImplement a program that can, given two distinct words $S$ and $T$ of the same length $n$ determine how many words $W$ of length $n + 1$ are there with such property that you can transform $W$ into both $S$, and $T$ by deleting exactly one character. Words $S$ and $T$ consist of lowercase English letters. Word $W$ also should consist of lowercase English letters.",
    "tutorial": "Suppose that $S$ is obtained from $W$ by deleteing the earlier symbol than $T$. Then it is true that $W = A + x + B + y + C$, $S = A + x + B + C$, $T = A + B + y + C$, where $x$ and $y$ are deleted symbols and $A$, $B$ and $C$ are some (possibly, empty) strings. Let's calculate $A$ as a longest common prefix of $S$ and $T$ and $C$ as a longest common suffix. Remove both of them from strings. Now we now that $x$ and $y$ are respectively the first letter of string $S$ and last letter of string $T$. Remove them too. The only thing left is to check if remaining parts of strings are equal. Perform such operation for $S$ and $T$ and for $T$ and $S$.",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "hashing",
      "strings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "533",
    "index": "F",
    "title": "Encoding",
    "statement": "Polycarp invented a new way to encode strings. Let's assume that we have string $T$, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in $T$ with its pair letter if there is a pair letter for it. For example, if you chose pairs (l, r), (p, q) and (a, o), then word \"parallelogram\" according to the given encoding principle transforms to word \"qolorreraglom\".\n\nPolycarpus already has two strings, $S$ and $T$. He suspects that string $T$ was obtained after applying the given encoding method from some substring of string $S$. Find all positions $m_{i}$ in $S$ ($1 ≤ m_{i} ≤ |S| - |T| + 1$), such that $T$ can be obtained fro substring $S_{mi}S_{mi + 1}... S_{mi + |T| - 1}$ by applying the described encoding operation by using some set of pairs of English alphabet letters",
    "tutorial": "There are two possible ideas for solving this task. Fix pair of letters $x$ and $y$. Replace all letters $x$ in $S$ with 1s and all remaining letters with 0s. Do the same for $y$ with string $T$. By using KMP algorithm or Z-function determine all positions where string $T$ can be attached to string $S$ so there is a match. If such condition is fullfilled for pair ($x$, $y$), and for pair ($y$, $x$) then this position is a possible match position if we use pair ($x$, $y$) and possibly some other pairs. Now for each suitable position we need to check if letters can be distributed in pairs according to the information we know. This can be done in O(sigma) where $sigma = 26$ - the size of the alphabet. So, this solution works in $O(n * sigma^{2} + n * sigma) = O(n * sigma^{2})$. It fits in time limit if implementation is efficient enough. Another way is to perform such transformation with both strings that allows us to compare them up to letters renaming. Let's replace each letter with distance from it to the closes letter to the left from it that is the same (or with -inf if there is no such letter). Now for strings to be equal we just need to check that string $T$ matches the substring of $S$ in all positions except, possibly, first occurence of each letter in $T$. This can be done by modified prefix-function or by hashing. Now suppose we know that in some position string $T$ is the same as string $S$ up to renaming letters. It's not hard to determine the letter permutation for this renaming (by just checking what matches in $S$ with first occurence of each letter in string $T$). Let's check that this permutation is a set of transpositions in $O(sigma)$. So, we have a solution in $O(n * sigma)$.",
    "tags": [
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "534",
    "index": "A",
    "title": "Exam",
    "statement": "An exam for $n$ students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers ($i$ and $i + 1$) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.\n\nYour task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.",
    "tutorial": "Is easy to see that $k = n$ with $n  \\ge  4$. There are many algorithms that can be used to build a correct sequence of length $n$ with $n  \\ge  4$. For example, students can be seated from left to right with the first to seat students with odd numbers in decreasing order starting with largest odd number. Then similary to seat students with even numbers. In this sequence the absolute difference between two adjacent odd (or even) numbers equal to 2. And the difference between odd and even numbers greater or equal 3 (because $n  \\ge  4$). Cases $n = 1$, $n = 2$, $n = 3$ are considered separately. Solution complexity - $O(n)$.",
    "code": "#include <stdio.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nconst int N = 5001;\n \nint n;\nint a[N];\n \nint main() {\n    scanf(\"%d\", &n);\n \n    if (n == 2) {\n        printf(\"1\\n1\");\n        return 0;\n    }\n    if (n == 3) {\n        printf(\"2\\n1 3\");\n        return 0;\n    }\n \n    int cur = n & 1 ? n : n - 1;\n    for(int i = 0; i < n; i++) {\n        if (cur < 0) {\n            cur = n & 1 ? n - 1 : n;\n        }\n        a[i] = cur;\n        cur -= 2;   \n    }\n \n    printf(\"%d\\n\", n);\n    forn(i, n) \n        printf(\"%d \", a[i]);\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "534",
    "index": "B",
    "title": "Covered Path",
    "statement": "The on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals $v_{1}$ meters per second, and in the end it is $v_{2}$ meters per second. We know that this section of the route took exactly $t$ seconds to pass.\n\nAssuming that at each of the seconds the speed is constant, and between seconds the speed can change at most by $d$ meters per second in absolute value (i.e., the difference in the speed of any two adjacent seconds does not exceed $d$ in absolute value), find the maximum possible length of the path section in meters.",
    "tutorial": "It can be easily proved that every second $i$ ($0  \\le  i  \\le  t - 1$) the maximum possible speed is $v_{i}=\\operatorname*{min}\\,(v_{1}+d\\cdot i,v_{2}+d\\cdot(t-i-1))$. You can iterate through $i$ from $0$ to $t - 1$ and the values of $v_{i}$. Solution complexity - $O(t)$. Also you can use next fact. If current speed equal to $u$ and left $t$ seconds then there is a way to get $v_{2}$ speed at the end only if $|u - v_{2}|  \\le  t \\cdot d$. Consider this criteria, one can simply try to change speed to maximum possible (from $u + d$ down to $u - d$), choosing first giving a way to reach the end of the path.",
    "code": "#include <stdio.h>\n#include <algorithm>\n#include <iostream>\n \nusing namespace std;\n \nint main() {\n    int v1, v2;\n    int n, d;\n \n    cin >> v1 >> v2;\n    cin >> n >> d;\n \n    int ans = v1;\n    int curv = v1;\n    for(int i = 1; i < n; i++) {\n        int newv;\n        for(int dd = d; dd >= -d; dd--) {\n            newv = curv + dd;\n            if (abs(newv - v2) <= (n - i - 1) * d)\n                break;  \n        }\n        curv = newv;\n        ans += curv;    \n    }\n \n    cout << ans;\n \n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "534",
    "index": "C",
    "title": "Polycarpus' Dice",
    "statement": "Polycarp has $n$ dice $d_{1}, d_{2}, ..., d_{n}$. The $i$-th dice shows numbers from $1$ to $d_{i}$. Polycarp rolled all the dice and the sum of numbers they showed is $A$. Agrippina didn't see which dice showed what number, she knows only the sum $A$ and the values $d_{1}, d_{2}, ..., d_{n}$. However, she finds it enough to make a series of statements of the following type: dice $i$ couldn't show number $r$. For example, if Polycarp had two six-faced dice and the total sum is $A = 11$, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).\n\nFor each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is $A$.",
    "tutorial": "Solution uses next fact. With $k$ dice $d_{1}, d_{2}, ..., d_{k}$ you can dial any sum from $k$ to $\\sum_{i=1}^{k}d_{i}$. This is easily explained by the fact that if there is a way to get the amount of $s > k$, then there is a way to dial the sum equal $s - 1$, which is obtained by decreasing the value of one die by one. Let's denote sum of all $n$ dice as $S=\\sum_{i=1}^{n}d_{i}$. Fix the dice $d_{i}$ (value on it denote as $x$ ($1  \\le  x  \\le  d_{i}$). Using the other dice we can select $s$ ($n - 1  \\le  s  \\le  S - d_{i}$). We know that average value $s + x = A$, and $n - 1  \\le  A - x  \\le  S - d_{i}$, giving $A - (n - 1)  \\ge  x  \\ge  A - (S - d_{i})$. Using facts described above, for every dice one can calculate a possible values segment, giving the answer for the count of impossible values of that dice. Solution asymptotic - $O(n)$.",
    "code": "#include <stdio.h>\n#include <algorithm>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nconst int N = 200002;\n \nint n;\nint a[N];\nlong long A, sum;\n \nint main() {\n \n    scanf(\"%d%I64d\", &n, &A);\n    forn(i, n) {\n        scanf(\"%d\", &a[i]);\n        sum += a[i];\n    }\n \n    forn(i, n) {\n        int l = max(1LL, A - (sum - a[i]));\n        int r = min(0LL + a[i], A - (n - 1));\n        int k = a[i] - (r - l + 1); \n        printf(\"%d \", k);\n    }   \n \n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "534",
    "index": "D",
    "title": "Handshakes",
    "statement": "On February, 30th $n$ students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in stayed in CTOP until the end of the day and never left.\n\nAt any time any three students could join together and start participating in a team contest, which lasted until the end of the day. The team did not distract from the contest for a minute, so when another student came in and greeted those who were present, he did not shake hands with the members of the contest writing team. Each team consisted of exactly three students, and each student could not become a member of more than one team. Different teams could start writing contest at different times.\n\nGiven how many present people shook the hands of each student, get a possible order in which the students could have come to CTOP. If such an order does not exist, then print that this is impossible.\n\nPlease note that some students could work independently until the end of the day, without participating in a team contest.",
    "tutorial": "From here we will not consider resulting permutation but correct handshakes sequence (rearranged given sequence). Formally, the sequence of handshakes count $a_{i}$ is correct if and only if $a_{i + 1}  \\le  a_{i} + 1$ and $a_{i + 1}  \\equiv  a_{i} + 1  \\pm  od{m}$ and $a_{1} = 0$. To form correct sequence, we can use following greedy algorithm. First, place 0 as the first number. Next, for every following number $a_{i + 1}$ we will select maximum possible number from numbers left, matching above constraints (in simple case it will be $a_{i} + 1$, otherwise we will check if $a_{i} - 2$ left, e.t.c). The solution may divide given sequence into three parts (depending on modulo by 30), and using, for example, data structure ''set'', quickly find the next number to place into resulting sequence. Such solution will work in $O(n\\log n)$. There is also possible to get $O(n)$ asymptotics using path compression technique.",
    "code": "#include <stdio.h>\n#include <algorithm>\n#include <set>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \ntypedef pair<int, int> pii;\nconst int N = 1000001;\n \nint n;\nset<pii> a[3];\nint ans[N];\n \nint main() {\n    scanf(\"%d\", &n);\n    forn(i, n) {\n        int x;\n        scanf(\"%d\", &x);\n        a[x % 3].insert(make_pair(x, i));\n    }\n \n    int cur = 0;\n    forn(i, n) {\n        set <pii> :: iterator it = a[cur % 3].lower_bound(make_pair(cur, -1));  \n        pii c;\n        if (it != a[cur % 3].end() && (*it).first == cur) {\n            c = *(it);\n            ans[i] = c.second + 1;\n        } else {\n            if (it == a[cur % 3].begin()) {\n                puts(\"Impossible\");\n                return 0;\n            } else {\n                it--;\n                c = *(it);\n                ans[i] = c.second + 1;\n            }\n        }       \n \n        a[cur % 3].erase(c);\n        cur = c.first + 1;\n    }\n \n    puts(\"Possible\");\n    forn(i, n)\n        printf(\"%d \", ans[i]);\n \n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "534",
    "index": "E",
    "title": "Berland Local Positioning System",
    "statement": "In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are $n$ bus stops located along the street, the $i$-th of them is located at the distance $a_{i}$ from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, $a_{i} < a_{i + 1}$ for all $i$ from 1 to $n - 1$. The bus starts its journey from the first stop, it passes stops $2$, $3$ and so on. It reaches the stop number $n$, turns around and goes in the opposite direction to stop $1$, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop $n$. During the day, the bus runs non-stop on this route.\n\nThe bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.\n\nOne of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.\n\nFor example, if the number of stops is $6$, and the part of the bus path starts at the bus stop number $5$, ends at the stop number $3$ and passes the stops as follows: ${\\mathfrak{f}}\\to6\\to{\\mathfrak{i}}\\to4\\to3$, then the request about this segment of the path will have form: $3, 4, 5, 5, 6$. If the bus on the segment of the path from stop $5$ to stop $3$ has time to drive past the $1$-th stop (i.e., if we consider a segment that ends with the second visit to stop $3$ on the way from $5$), then the request will have form: $1, 2, 2, 3, 3, 4, 5, 5, 6$.\n\nYou will have to repeat the Berland programmers achievement and implement this function.",
    "tutorial": "Suppose that the bus started his way from the stop with number 1 and modulate its way during $m$ stops. For every stop we will calculate how many times this stop was visited by the bus at that way. Check if that counts match counts in the input and update the answer if needed. Then we will try to move the start stop to stop with number 2. It's easy to see that the last visited stop (as long as bus must visit $m$ stops) will move to the next stop. So we need to modulate bus way to another one stop from first stop and from last stop to change the starting stop to another (it makes maximum of four counts to be updated). It could be done in $O(1)$ time. This way we need to move starting stop to every variant (its count is equal to $2n - 2$) and for every variant update the answer if needed. Average solution works in $O(n)$ time.",
    "code": "#define _CRT_SECURE_NO_DEPRECATE\n#define _USE_MATH_DEFINES\n \n#include <stdio.h>\n#include <stack>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <string.h>\n#include <string>\n#include <set>\n#include <iterator>\n#include <memory.h>\n#include <vector>\n#include <map>\n#include <queue>\n#include <iomanip>\n#include <ctime>\n#include <cassert>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define mp(a, b) make_pair(a, b)\n#define sqr(x) ( (x) * (x) )\n#define all(a) a.begin(), a.end()\n#define X first\n#define Y second\n \ntypedef long long ll; \ntypedef double ld;\ntypedef vector<int> vi; \ntypedef vector<vi> vii; \ntypedef pair<int, int> pii;\n \nconst int INF = 1e9;\nconst ll INF64 = 1e18;\nconst int MOD = 1000000007;\nconst int N = 200002;\n \nint n, m;\nint a[N];\nint cnt[N], cur[N];\nint pos[2 * N];\n \nint main() {\n    scanf(\"%d\", &n);\n    forn(i, n)\n        scanf(\"%d\", &a[i]);\n    scanf(\"%d\", &m);\n    forn(i, m) {\n        int x;\n        scanf(\"%d\", &x);\n        cnt[x - 1]++;   \n    }\n \n    forn(i, n)\n        pos[i] = i;\n    forn(i, n - 1)\n        pos[n + i] = n - i - 2;\n \n    ll ans = 0;\n    bool f = false;\n \n    int nn = 2 * n - 2;\n \n    for(int dir = 1; dir >= -1; dir -= 2) {\n        memset(cur, 0, sizeof(cur));\n \n        int st = dir == 1 ? 0 : n - 1; \n        int v = st;\n        ll res = 0;\n \n        forn(i, m - 1) {\n            int nv = (v + dir + nn) % nn;\n            res += abs(a[ pos[v] ] - a[ pos[nv] ]);\n            cur[ pos[v] ]++;\n            v = nv; \n        }\n \n        cur[ pos[v] ]++;\n \n        int wr = 0;\n        forn(i, n)\n            wr += (cur[i] != cnt[i]);\n \n        if (!wr) {\n            if (f && res != ans) {\n                cout << -1;\n                return 0;\n            }\n            ans = res;\n            f = true;\n        }\n \n        for(int i = st + dir; dir == 1 ? (i < n) : (i >= 0); i += dir) {\n            int nv = (v + dir + nn) % nn;\n            int pv = pos[v];\n            int pnv = pos[nv];\n            res -= abs(a[i] - a[i - dir]);\n            res += abs(a[pnv] - a[pv]);\n \n            wr -= (cur[i - dir] != cnt[i - dir]);\n            wr -= (cur[pnv] != cnt[pnv]);\n \n            cur[i - dir]--;\n            cur[pnv]++;\n \n            wr += (cur[i - dir] != cnt[i - dir]);\n            wr += (cur[pnv] != cnt[pnv]);\n \n            if (!wr) {\n                if (f && res != ans) {\n                    cout << -1;\n                    return 0;\n                }\n                ans = res;\n                f = true;\n            }\n            v = nv;\n        } \n    }\n \n    cout << ans;\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "hashing",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "534",
    "index": "F",
    "title": "Simplified Nonogram",
    "statement": "In this task you have to write a program dealing with nonograms on fields no larger than $5 × 20$.\n\nSimplified nonogram is a task where you have to build such field (each cell is either white or black) that satisfies the given information about rows and columns. For each row and each column the number of contiguous black segments is specified.\n\nFor example if size of the field is $n = 3, m = 5$, аnd numbers of contiguous black segments in rows are: $[2, 3, 2]$ and in columns are: $[1, 0, 1, 2, 1]$ then the solution may look like:\n\nIt is guaranteed that on each test in the testset there exists at least one solution.",
    "tutorial": "This task has several solution algorithms. One of them could be described next way. Let's divide $n  \\times  m$ field into two parts with almost same number of columns (it will be $n  \\times  k$ and $n  \\times  (m - k)$). Let's solve the puzzle for every part of the field with brute-force algorithm (considering column constraints on number of blocks) with memorization (we do not need same solutions with same number of blocks in rows). Then we will use meet-in-the-middle approach to match some left part with right part to match constraints on $n  \\times  m$ field. Another solution could be profile dynamic programming, where the profile is the number of blocks in the row.",
    "code": "#include <cstdio>\n#include <cstdlib>\n#include <vector>\n \n#define forn(i,n) for (int i = 0; i < int(n); ++i)\n#define sz(a) (int)(a.size())\n \nconst int N = 5;\nconst int M = 20;\nconst int B = 6;\nconst int S = 7776; // B ^ N\n \nusing namespace std;\n \nint n, m, a[N], b[M], bc[1 << N];\n \ntypedef char dpmat[M / 2 + 2][S][1 << N];\n \nint c[M + 1];\ndpmat lft, rgt;\n \nint make_move(int s, int mask1, int mask2, int mul) {\n    int ns = s;\n    int dm = mask2 & (mask1 ^ mask2);\n \n    int pw = 1 * mul;\n \n    forn(c, n) {\n        if (dm & (1 << c))\n            ns += pw;\n        pw *= B;\n    }\n \n    return ns;\n}\n \nchar ans[N][M + 1];\n \nvoid calcdp(int m, dpmat dp) {\n    forn(i, m + 1)\n        forn(s, S)\n        forn(j, 1 << n)\n        dp[i][s][j] = -1;\n \n    dp[0][0][0] = 0;\n \n    forn(i, m) {\n        forn(s, S) {\n            forn(mask1, 1 << n) {\n                if (bc[mask1] != c[i]) continue;\n                if (dp[i][s][mask1] == -1) continue;\n \n                forn(mask2, 1 << n) {\n                    if (bc[mask2] != c[i + 1]) continue;\n                    int ns = make_move(s, mask1, mask2, +1);\n                    dp[i + 1][ns][mask2] = mask1;\n                }\n            }   \n        }\n    }\n}\n \nint res[M];\nint al[M], ar[M];\n \nvoid restore(int m, int s, int mask, dpmat dp) {\n    for (int i = m; i >= 1; --i) {\n        res[i - 1] = mask;\n \n        int pmask = dp[i][s][mask];\n        s = make_move(s, pmask, mask, -1);\n        mask = pmask;\n    }\n}\n \nint main() {\n    scanf(\"%d %d\", &n, &m);\n \n    forn(i, n)\n        scanf(\"%d\", &a[i]);\n \n    forn(i, m)\n        scanf(\"%d\", &b[i]);\n \n    forn(i, 1 << n) {\n        int c = 0;\n        int prv = 0;\n        forn(j, n) {\n            int cur = ((i >> j) & 1);\n            if (cur && cur != prv)\n                c++;\n            prv = cur;\n        }\n        bc[i] = c;\n    }\n \n    int l = m / 2, r = m - l;\n    int il = l - 1, ir = l;\n \n    forn(i, l)\n        c[i + 1] = b[i];\n \n    calcdp(l, lft);\n \n    forn(i, r)\n        c[i + 1] = b[m - i - 1];\n \n    calcdp(r, rgt);\n \n    forn(sl, S) {\n        forn(ml, 1 << n) {\n            if (bc[ml] != b[il]) continue;\n            if (lft[l][sl][ml] == -1) continue;\n \n            forn(mr, 1 << n) {\n                if (bc[mr] != b[ir]) continue;\n \n                int sr = 0;\n \n                int pw = 1;\n                int csl = sl;\n                forn(i, n) {\n                    int cs = a[i];\n                    int cl = csl % B; csl /= B;\n                    al[i] = cl;\n \n                    int cr = cs - cl;\n \n                    if (mr & ml & (1 << i))\n                        cr++;\n \n                    if (cr < 0 || cr >= B) {\n                        sr = -1;\n                        break;\n                    }\n \n                    sr += pw * cr;\n                    ar[i] = cr;\n                    pw *= B;\n                }\n \n                if (sr == -1) continue;\n \n                if (rgt[r][sr][mr] != -1) {\n                    restore(l, sl, ml, lft);\n                    forn(i, l)\n                        forn(j, n)\n                        ans[j][i] = ((res[i] >> j) & 1) ? '*' : '.';\n \n                    restore(r, sr, mr, rgt);\n \n                    forn(i, r)\n                        forn(j, n)\n                        ans[j][m - 1 - i] = ((res[i] >> j) & 1) ? '*' : '.';\n \n                    forn(i, n)\n                        puts(ans[i]);\n \n                    return 0;\n                }\n            }\n        }\n    }\n \n    puts(\"Impossible\");\n \n \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "hashing",
      "meet-in-the-middle"
    ],
    "rating": 2400
  },
  {
    "contest_id": "535",
    "index": "A",
    "title": "Tavas and Nafas",
    "statement": "Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.\n\nHis phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.\n\nHe ate coffee mix without water again, so right now he's really messed up and can't think.\n\nYour task is to help him by telling him what to type.",
    "tutorial": "First of all check if $n$ is one of the values $0, 10, 11,  \\dots , 19$. Then, let's have array $x[]$ = {\"\", \"\", \"twenty\", \"thirty\",  \\dots , \"ninety\"} and $y[]$ = {\"\", \"one\",  \\dots , \"nine\"}. Let $a={\\frac{n}{10}}$ and $b = n modulo 10$. If $n$ is not one of the values above, then if $a = 0$, print $y[b]$, else if $b = 0$ print $x[a]$ otherwise print $x[a]$-$y[b]$. Time complexity: $O(1)$",
    "code": "#include <iostream>\n\nusing namespace std;\n\nstring a[10] = {\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"};\nstring b[10] = {\"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"};\nstring c[10] = {\"tmp\", \"ten\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\n\nint main() {\n\tint n;\n\tcin >> n;\n\tif (n < 10)\n\t\tcout << a[n];\n\telse if (n < 20)\n\t\tcout << b[n % 10];\n\telse {\n\t\tcout << c[n / 10];\n\t\tif (n % 10)\n\t\t\tcout << '-' << a[n % 10];\n\t}\n\tcout << endl;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "535",
    "index": "B",
    "title": "Tavas and SaDDas",
    "statement": "\\underline{Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: \"If you solve the following problem, I'll return it to you.\"}\n\nThe problem is:\n\nYou are given a lucky number $n$. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers \\textbf{47}, \\textbf{744}, \\textbf{4} are lucky and \\textbf{5}, \\textbf{17}, \\textbf{467} are not.\n\nIf we sort all lucky numbers in increasing order, what's the 1-based index of $n$?\n\nTavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.",
    "tutorial": "Sol1: Consider $n$ has $x$ digits, $f(i) =$ decimal representation of binary string $i$, $m$ is a binary string of size $x$ and its $i - th$ digit is 0 if and only if the $i - th$ digit of $n$ is $4$. Finally, answer equals to $2^{1} + 2^{2} +  \\dots  + 2^{x - 1} + f(m) + 1$. Time complexity: $O(log(n))$ Sol2: Count the number of lucky numbers less than or equal to $n$ using bitmask (assign a binary string to each lucky number by replacing 4s with 0 and 7s with 1). Time complexity: $O(2^{log(n)})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c)  for(auto &(i) : (c))\n#define x     first\n#define y     second\n#define pb  push_back\n#define PB  pop_back()\n#define iOS  ios_base::sync_with_stdio(false)\n#define sqr(a)  (((a) * (a)))\n#define all(a)  a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x)  ((x)<<1)\n#define R(x)  (((x)<<1)+1)\n#define umap  unordered_map\n//#define max(x,y)  ((x) > (y) ? (x) : (y))\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ninline ll binary(string n){\n\tll ans = 0LL;\n\tFor(i,0,n.size())\n\t\tans  = (2LL*ans + (ll)(n[i]-'0'));\n\tll p = 1LL;\n\tFor(i,0,n.size())\n\t\tp = (p << 1);\n\tans += p-1LL;\n\treturn ans;\n}\ninline string lu(string s){\n\tFor(i,0,s.size())\n\t\ts[i] = (char)(s[i]=='4'?'0':'1');\n\treturn s;\n}\nint main(){\n\tiOS;\n\tstring n;\n\tcin >> n;\n\tcout << binary(lu(n)) << endl;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "535",
    "index": "C",
    "title": "Tavas and Karafs",
    "statement": "\\underline{Karafs is some kind of vegetable in shape of an $1 × h$ rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.}\n\nEach Karafs has a positive integer height. Tavas has an infinite \\textbf{1-based} sequence of Karafses. The height of the $i$-th Karafs is $s_{i} = A + (i - 1) × B$.\n\nFor a given $m$, let's define an $m$-bite operation as decreasing the height of at most $m$ distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.\n\nNow SaDDas asks you $n$ queries. In each query he gives you numbers $l$, $t$ and $m$ and you should find the largest number $r$ such that $l ≤ r$ and sequence $s_{l}, s_{l + 1}, ..., s_{r}$ can be eaten \\textbf{by performing $m$-bite no more than $t$ times} or print -1 if there is no such number $r$.",
    "tutorial": "Lemma: Sequence $h_{1}, h_{2},  \\dots , h_{n}$ is $(m, t) -$Tavas-Eatable if and only if $max(h_{1}, h_{2},  \\dots , h_{n})  \\le  t$ and $h_{1} + h_{2} +  \\dots  + h_{n}  \\le  m  \\times  t$. Proof: only if is obvious (if the sequence is Tavas-Eatable, then it fulfills the condition). So we should prove that if the conditions are fulfilled, then the sequence is Tavas-Eatable. Use induction on $h_{1} + h_{2} + ... + h_{n}$. Induction definition: the lemma above is true for every sequence $h$ with sum of elements at most $k$. So now we should prove it for $h_{1} + h_{2} + ... + h_{n} = k + 1$. There are two cases: 1- There are at least $m$ non-zero elements in the sequence. So, the number of elements equal to $t$ is at most $m$ (otherwise sum will exceed $m  \\times  t$). So, we decrease $m$ maximum elements by $1$. Maximum element will be at most $t - 1$ and sum will be at least $m  \\times  t - m = m(t - 1)$. So according to the induction definition, the new sequence is $(m, t - 1) -$ Tavas-Eatable, so $h$ is $(m, t) -$ Tavas-Eatable. 2- There are less than $m$ non-zero elements in the sequence. We decrease them all by 1. Obviously, the new sequence has maximum element at most equal to $t - 1$ so its sum will be at most $m(t - 1)$. So according to the induction definition, the new sequence is $(m, t - 1) -$ Tavas-Eatable, so $h$ is $(m, t) -$ Tavas-Eatable. For this problem, use binary search on $r$ and use the fact that the sequence is non-decreasing and $h_{l}+\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot h_{r}=A(r-l+1)+B(\\frac{r*(r-1)}{2}-\\stackrel{(l-1)(l-2)}{2})$ . Time complexity: $O(qlog(mt))$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c)  for(auto &(i) : (c))\n#define x     first\n#define y     second\n#define pb  push_back\n#define PB  pop_back()\n#define iOS  ios_base::sync_with_stdio(false)\n#define sqr(a)  (((a) * (a)))\n#define all(a)  a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x)  ((x)<<1)\n#define R(x)  (((x)<<1)+1)\n#define umap  unordered_map\n//#define max(x,y)  ((x) > (y) ? (x) : (y))\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\nll A,B,n,l,t,m,s;\ninline ll comb(ll x){\n\treturn (x * (x-1LL))/2LL;\n}\ninline ll h(ll i){\n\treturn A + (i-1LL) * B;\n}\ninline bool check(ll r){\n\tll e = comb(r) - comb(l-1LL);\n\tif(B && (double)e  > 2e18 / (double)B)\n\t\treturn false;\n\tif(h(r) > t) return false;\n\ts = m * t;\n\ts -= e * B;\n\ts -= A * (r - l + 1LL);\n\treturn (s >= 0LL);\n}\nint main(){\n\tiOS;\n\tcin >> A >> B >> n;\n\twhile(n --){\n\t\tcin >> l >> t >> m;\n\t\tif(h(l) > t){\n\t\t\tcout << -1 << '\\n';\n\t\t\tcontinue;\n\t\t}\n\t\tll lo = l, hi = max(t, m) + l + 5;\n\t\twhile(lo < hi){\n\t\t\tll mid = (lo + hi)/2LL;\n\t\t\tif(check(mid))\n\t\t\t\tlo = mid;\n\t\t\telse\n\t\t\t\thi = mid - 1LL;\n\t\t\tif(lo + 1LL == hi){\n\t\t\t\tif(check(hi))\n\t\t\t\t\tlo = hi;\n\t\t\t\telse\n\t\t\t\t\thi = lo;\n\t\t\t}\n\t\t}\n\t\tcout << lo << '\\n';\n\t}\n}",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "535",
    "index": "D",
    "title": "Tavas and Malekas",
    "statement": "\\underline{Tavas is a strange creature. Usually \"zzz\" comes out of people's mouth while sleeping, but string $s$ of length $n$ comes out from Tavas' mouth instead.}\n\nToday Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on $s$. Malekas has a favorite string $p$. He determined all positions $x_{1} < x_{2} < ... < x_{k}$ where $p$ matches $s$. More formally, for each $x_{i}$ ($1 ≤ i ≤ k$) he condition $s_{xi}s_{xi + 1}... s_{xi + |p| - 1} = p$ is fullfilled.\n\nThen Malekas wrote down one of subsequences of $x_{1}, x_{2}, ... x_{k}$ (possibly, he didn't write anything) on a piece of paper. Here a sequence $b$ is a subsequence of sequence $a$ if and only if we can turn $a$ into $b$ by removing some of its elements (maybe no one of them or all).\n\nAfter Tavas woke up, Malekas told him everything. He couldn't remember string $s$, but he knew that both $p$ and $s$ only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.\n\nTavas wonders, what is the number of possible values of $s$? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.\n\nAnswer can be very large, so Tavas wants you to print the answer modulo $10^{9} + 7$.",
    "tutorial": "First of all you need to find uncovered positions in $s$ (because rest of them will determine uniquely). If there is no parados in covered positions (a position should have more than one value), then the answer will be $0$, otherwise it's $26^{uncovered}$. To check this, you just need to check that no two consecutive matches in $s$ have parados. So, for this purpose, you need to check if a prefix of $t$ is equal to one of its suffixes in $O(1)$. You can easily check this with prefix function (or Z function). Time complexity: $O(n + m)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c)  for(auto &(i) : (c))\n#define x     first\n#define y     second\n#define pb  push_back\n#define PB  pop_back()\n#define iOS  ios_base::sync_with_stdio(false)\n#define sqr(a)  (((a) * (a)))\n#define all(a)  a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x)  ((x)<<1)\n#define R(x)  (((x)<<1)+1)\n#define umap  unordered_map\n//#define max(x,y)  ((x) > (y) ? (x) : (y))\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ninline vi prefix(string p){\n\tvi pi;\n\tint m = p.size();\n\tFor(i,0,m)\n\t\tpi.pb(-1);\n\tint k = -1;\n\tFor(i,1,m){\n\t\twhile(k != -1 && p[k+1] != p[i])\n\t\t\tk = pi[k];\n\t\tif(p[k+1] == p[i])\n\t\t\tk++;\n\t\tpi[i] = k;\n\t}\n\treturn pi;\n}\nset<int> s;\ninline void shift(string p){\n\tvector<int> pi = prefix(p);\n\tint m = p.size();\n\tint k = pi[m-1];\n\twhile(k!=-1){\n\t\ts.insert(m-k);\n\t\tk = pi[k];\n\t}\n}\nint main(){\n    iOS;\n\tll n,m;\n\tcin >> n >> m;\n\tstring p;\n\tcin >> p;\n\tvi pi = prefix(p);\n\tshift(p);\n\tvi v;\n\tFor(i,0,m){\n\t\tint a;\n\t\tcin >> a;\n\t\tv.pb(a);\n\t}\n\tbool ok = true;\n\tFor(i,1,v.size()){\n\t\tll r = v[i] , l=v[i-1];\n\t\tif(r<(l+p.size()) && s.find((r-l+1))==s.end()){\n\t\t\t\tcout << 0 << endl;\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t}\n\t\tif((p.size()+r-1)>n && ok){\n\t\t\t\tcout<< 0 <<endl;\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tll x = n;\n\tif(ok){\n\t\tv.pb(2000000000);\n\t\tFor(i,0,v.size()-1)\n\t\t\tx -= min((int)p.size(),v[i+1]-v[i]);\n\n\t}\n\tll ans=1;\n\tif(x < 0 && ok){\n\t\t\t\tcout<< 0 <<endl;\n\t\t\t\tok = false;\n\t}\n\tFor(i,0,x)\n\t\tans = (ans*(ll)26) % 1000000007;\n\tif(ok)\n\t\tcout<< ans <<endl;\n}",
    "tags": [
      "greedy",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "535",
    "index": "E",
    "title": "Tavas and Pashmaks",
    "statement": "\\underline{Tavas is a cheerleader in the new sports competition named \"Pashmaks\".}\n\nThis competition consists of two part: swimming and then running. People will immediately start running $R$ meters after they finished swimming exactly $S$ meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).\n\nBefore the match starts, Tavas knows that there are $n$ competitors registered for the match. Also, he knows that $i$-th person's swimming speed is $s_{i}$ meters per second and his/her running speed is $r_{i}$ meters per second. Unfortunately, he doesn't know the values of $R$ and $S$, but he knows that they are real numbers greater than $0$.\n\nAs a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of $R$ and $S$ such that with these values, (s)he will be a winner.\n\nTavas isn't really familiar with programming, so he asked you to help him.",
    "tutorial": "For each competitor put the point $\\textstyle{{\\binom{1}{s_{i}}},\\ {\\frac{1}{r_{i}}}}$ in the Cartesian plane. So, the time a competitor finishes the match is $\\underline{{{S}}}_{s i}+\\frac{R}{r_{i}}=(S,R).(\\underline{{{1}}}_{s i},\\underline{{{1}}}_{t})$. Determine their convex hull(with maximum number of points. i.e it doesn't matter to have $ \\pi $ radians angle). Let $L$ be the leftmost point on this convex hull (if there are more than one, choose the one with minimum $y$ component). Similarly, let $D$ be the point with minimum $y$ component on this convex hull (if there are more than one, consider the leftmost). Proof: $(S,R)(\\textstyle{\\frac{1}{8}},\\textstyle{\\frac{1}{n}})$ is the scalar product that is smaller if the point $\\textstyle{{\\binom{1}{s_{i}}},\\ {\\frac{1}{r_{i}}}}$ is farther in the direction of $(S, R)$. It's obvious that the farthest points in some direction among the given set lie on a convex hull. $(S, R)$ can get any value that is vector in first quadrant. So we need the points on the convex hull that we actually calculate (also we know that the points on the right or top of the convex hull, are not in the answer, because they're always losers). It's easy to see that the answer is the points on the path from $D$ to $L$ on the convex hull (bottom-left arc). i.e the bottom-left part of the convex hull. Time complexity: $O(nlog(n))$ In this problem, we recommend you to use integers. How ? Look at the code below In this code, function CROSS returns $\\left(a_{x}a_{y}b_{x}b_{y}o_{x}o_{y}\\right)\\left(\\left({\\frac{1}{a_{x}}}-{\\frac{1}{a_{x}}},{\\frac{1}{a_{y}}}-{\\frac{1}{o_{y}}}\\right)\\times\\left({\\frac{1}{b_{x}}}-{\\frac{1}{o_{x}}},{\\frac{1}{b_{y}}}-{\\frac{1}{o_{y}}}\\right)\\right)$ (it's from order of $10^{16}$, so there won't be any overflows.) In double version, you should have a very small epsilon.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c)  for(auto &(i) : (c))\n#define x     first\n#define y     second\n#define pb  push_back\n#define PB  pop_back()\n#define iOS  ios_base::sync_with_stdio(false)\n#define sqr(a)  (((a) * (a)))\n#define all(a)  a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x)  ((x)<<1)\n#define R(x)  (((x)<<1)+1)\n#define umap  unordered_map\n//#define max(x,y)  ((x) > (y) ? (x) : (y))\n//#define double long double\ntypedef long long ll;\n#define int ll\ntypedef pair<ll,ll>pii;\ntypedef vector<int> vi;\n//typedef complex<double> point;\nconst int maxn = 1e6 + 100;\nmap <pii, vi> mp;\nstruct point{\n\tll x,y;\n\tpoint(){\n\t \tx = y = 0;\n\t}\n\tpoint(ll a,ll b){\n\t\tx = a, y = b;\n\t}\n\tinline void init(ll a,ll b){\n\t\tx = a, y = b;\n\t}\n\tinline point operator - (point p){\n\t\treturn point(x - p.x, y - p.y);\n\t}\n\tinline ll dis(point p){\n\t\treturn sqr(x - p.x) + sqr(y - p.y);\n\t}\n\tinline pii PII(){\n\t\treturn pii(x, y);\n\t}\n};\ninline ll CROSS(point o, point a,point b){\n\treturn (a.y * b.x * o.x * o.y - a.y * o.x * b.x * b.y - o.y * b.x * a.x * a.y + a.x * b.x * a.y * b.y) - \n\t\t(a.x * b.y * o.x * o.y - a.x * o.y * b.x * b.y - o.x * b.y * a.x * a.y + a.x * b.x * a.y * b.y);\n}\npoint o;\npoint l;\ninline bool ocmp(const point &a, const point &b){\n\treturn make_pair(a.y, a.x) > make_pair(b.y, b.x);\n}\ninline bool lcmp(const point &a, const point &b){\n\treturn make_pair(a.x, a.y) > make_pair(b.x, b.y);\n}\ninline bool scmp(const point &a,const point &b){\n\tll cross = CROSS(o, a, b);\n\tif(!cross)\n\t\treturn o.dis(a) < o.dis(b);\n\treturn cross < 0;\n}\nvector<point> v;\nvector<point> hull;\nint n;\nmain(){\n    iOS;\n\tcin >> n;\n\tFor(i,0,n){\n\t\tint a,b;\n\t\tcin >> a >> b;\n\t\tmp[{a, b}].pb(i + 1);\n\t}\n\tif(mp.size() == 1){\n\t\tFor(i,1,n+1)\n\t\t\tcout << i << ' ';\n\t\tcout << endl;\n\t\treturn 0;\n\t}\n\tForeach(q, mp){\n\t\tpii p = q->x;\n\t\tint x = p.x, y = p.y;\n\t\tpoint P;\n\t\tP.init(x, y);\n\t\tv.pb(P);\n\t}\n\to = *min_element(all(v), ocmp);\n\tl = *min_element(all(v), lcmp);\n\tif(o.PII() == l.PII()){\n\t\trep(a, mp[o.PII()])\n\t\t\tcout << a << ' ';\n\t\tcout << endl;\n\t\treturn 0;\n\t}\n\tsort(all(v), scmp);\n\tint po = 2;\n\tFor(i,0,2)\n\t\thull.pb(v[i]);\n\tvi ans;\n\twhile(po < v.size() && hull.back().PII() != l.PII()){\n\t\twhile(hull.size() > 1 && CROSS(hull[hull.size()-2], hull[hull.size()-1], v[po]) > 0LL)\n\t\t\thull.PB;\n\t\thull.pb(v[po++]);\n\t}\n\trep(p, hull)\n\t\trep(a, mp[p.PII()])\n\t\t\tans.pb(a);\n\tsort(all(ans));\n\trep(a, ans)\n\t\tcout << a << ' ';\n\tcout << endl;\n\t\n}",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "536",
    "index": "D",
    "title": "Tavas in Kansas",
    "statement": "Tavas lives in Kansas. Kansas has $n$ cities numbered from 1 to $n$ connected with $m$ bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities.\n\nTavas invented a game and called it \"Dashti\". He wants to play Dashti with his girlfriends, Nafas.\n\nIn this game, they assign an arbitrary integer value to each city of Kansas. The value of $i$-th city equals to $p_{i}$.\n\nDuring the game, Tavas is in city $s$ and Nafas is in city $t$. They play in turn and Tavas goes first. A player in his/her turn, must choose a non-negative integer $x$ and his/her score increases by the sum of values of all cities with (shortest) distance no more than $x$ from his/her city. Each city may be used once, or in the other words, after first time a player gets score from a city, city score becomes zero.\n\nThere is an additional rule: the player must choose $x$ such that he/she gets the point of at least one city that was not used before. Note that city may initially have value 0, such city isn't considered as been used at the beginning of the game, i. e. each player may use it to fullfill this rule.\n\nThe game ends when nobody can make a move.\n\nA player's score is the sum of the points he/she earned during the game. The winner is the player with greater score, or there is a draw if players score the same value. Both players start game with zero points.\n\nIf Tavas wins, he'll break his girlfriend's heart, and if Nafas wins, Tavas will cry. But if their scores are equal, they'll be happy and Tavas will give Nafas flowers.\n\nThey're not too emotional after all, so they'll play optimally. Your task is to tell Tavas what's going to happen after the game ends.",
    "tutorial": "For each vertex $v$, put a point $(dis(s, v), dis(v, t))$ with its point (score) in the Cartesian plane. The first player in his/her turn chooses a vertical line and erases all the points on its left side. Second player in his/her turn chooses a horizontal line and erases all the point below it. Each player tries to maximize his/her score. Obviously, each time a player chooses a line on the right/upper side of his/her last choice. Imagine that there are $A$ different $x$ components $x_{1} < x_{2} <  \\dots  < x_{A}$ and $B$ different $y$ components $y_{1} < y_{2} <  \\dots  < y_{B}$ among all these lines. So, we can show each state before the game ends with a pair $(a, b)$ ($1  \\le  a  \\le  A, 1  \\le  b  \\le  B$ It means that in this state a point $(X, Y)$ is not erased yet if and only if $x_{a}  \\le  X$ and $y_{b}  \\le  Y$). So, using dp, $dp[a][b][i]$ ($1  \\le  i  \\le  2$) is the maximum score of $i - th$ player in state $(a, b)$ and it's $i - th$ player's turn. So, consider $s[a][b]$ is the sum of the scores of all valid points in state $(a, b)$ and $t[a][b]$ is the amount of them. So, If $i = 1$ then, $dp[a][b][i] = max(s[a][b] - dp[c][b][2])$ ($a  \\le  c  \\le  A, t[c][b] < t[a][b]$). Otherwise $dp[a][b][i] = max(s[a][b] - dp[a][c][1])$ ($b  \\le  c  \\le  B, t[a][c] < t[a][b]$). So we need two backward fors for our dp and another for on $i$. So, now the only thing that matters is updating the dp. For this purpose, we need two more arrays $QA$ and $QB$. $QA[b][1] =$ the minimum value of pairs $(dp[j][b][2], t[j][b])$ and $QA[b][2] =$ minimum value of pairs $(dp[j][b][2], t[j][b])$ such that $t[j][b] > QA[b][1].second$ in the states we've seen so far. Similarly, $QB[a][1] =$ the minimum value of pairs $(dp[a][j][1], t[a][j])$ and $QB[a][2] =$ minimum value of pairs $(dp[a][j][1], t[a][j])$ such that $t[a][j] > QB[a][1].second$ in the states we've seen so far. Now updating dp is pretty easy : $dp[a][b][1] = s[a][b] - (t[a][b]  \\le  QA[b][1].second?QA[b][2].first: QA[b][1].first)$. $dp[a][b][2] = s[a][b] - (t[a][b]  \\le  QB[a][1].second?QB[a][2].first: QB[a][1].first)$. And updating $QA$ and $QB$ is super easy. Now, let $f = dp[1][1][1]$ and $S$ be the sum of scores of all points. So, the score of first player is $f$ and the second one is $S - f$. Time complexity: $O(n^{2})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c)  for(auto &(i) : (c))\n#define x     first\n#define y     second\n#define pb  push_back\n#define pb  pop_back()\n#define iOS  ios_base::sync_with_stdio(false)\n#define sqr(a)  (((a) * (a)))\n#define all(a)  a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x)  ((x)<<1)\n#define R(x)  (((x)<<1)+1)\n#define umap  unordered_map\n//#define max(x,y)  ((x) > (y) ? (x) : (y))\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef pair<long long,long long> PLL;\n# define FF x\n# define SS y\ntypedef ll LL;\n# define PB push_back\n# define MP make_pair\n//typedef complex<double> point;\nconst int MAX_N=2000+5;\nconst int MAX_E=100*1000+5;\nvector<PLL> adj[MAX_N],A,B;\nLL N,E,K,PA,PB,P[MAX_N],Sum[MAX_N][MAX_N];\nint SZ[MAX_N][MAX_N],SZA,SZB;\nvector<LL> DA,DB;\nLL ALLSUM,Ans;\n\nPLL QA[MAX_N][2],QB[MAX_N][2];\n\nbool mrk[MAX_N];\nLL D[MAX_N];\nvoid Dijstkra(int s,vector<PLL> &V,vector<LL> &H){\n\tD[s]=0;\n\tfor(int tmp=0;tmp<N;tmp++){\n\t\tint mn=-1;\n\t\tfor(int i=1;i<=N;i++)\n\t\t\tif(!mrk[i] &&(mn==-1 || D[mn]>D[i]))\n\t\t\t\tmn=i;\n\t\tmrk[mn]=true;\n\t\tV.PB(PLL(D[mn],mn));\n\t\tH.PB(D[mn]);\n\t\tfor(int i=0;i<(int)adj[mn].size();i++){\n\t\t\tint v=adj[mn][i].FF;\n\t\t\tif(mrk[v])continue;\n\t\t\tD[v]=min(D[v],D[mn]+adj[mn][i].SS);\n\t\t}\n\t}\n\n}\nvoid CLR(){\n\tA.clear(),B.clear();\n\tDA.clear(),DB.clear();\n\tAns=0;\n\tALLSUM=0;\n\tfor(int i=0;i<MAX_N;i++){\n\t\tadj[i].clear();\n\t\tP[i]=0;\n\t\tQA[i][0]=MP(0LL,0LL);\n\t\tQA[i][1]=MP(0LL,0LL);\n\t\tQB[i][0]=MP(0LL,0LL);\n\t\tQB[i][1]=MP(0LL,0ll);\n\t\tfor(int j=0;j<MAX_N;j++)\n\t\t\tSum[i][j]=0,\n\t\t\t\tSZ[i][j]=0;\n\t}\n}\n\nvoid FillSum(){\n\tmemset(mrk,0,sizeof(mrk));\n\tmemset(D,63,sizeof(D));\n\tDijstkra(PA,A,DA);\n\tmemset(mrk,0,sizeof(mrk));\n\tmemset(D,63,sizeof(D));\n\tDijstkra(PB,B,DB);\n\tsort(DA.begin(),DA.end());\n\tDA.resize(unique(DA.begin(),DA.end())-DA.begin());\n\tsort(DB.begin(),DB.end());\n\tDB.resize(unique(DB.begin(),DB.end())-DB.begin());\n\tSZA=(int)DA.size();\n\tSZB=(int)DB.size();\n\n\tmemset(mrk,0,sizeof(mrk));\n\tLL AnsA=ALLSUM,P1=0,SizeA=N;\n\tfor(int i=0;i<SZA;i++){\n\t\twhile(P1<(int)A.size() && A[P1].FF<DA[i]){\n\t\t\tAnsA-=P[A[P1].SS];\n\t\t\tmrk[A[P1].SS]=true;\n\t\t\tSizeA--;\n\t\t\tP1++;\n\t\t}\n\t\tLL P2=0,AnsB=AnsA,SizeB=SizeA;\n\t\tfor(int j=0;j<SZB;j++){\n\t\t\twhile(P2<(int)B.size() && B[P2].FF<DB[j]){\n\t\t\t\tif(!mrk[B[P2].SS])\n\t\t\t\t\tAnsB-=P[B[P2].SS],\n\t\t\t\t\t\tSizeB--;\n\t\t\t\tP2++;\n\t\t\t}\n\t\t\tSum[i][j]=AnsB;\n\t\t\tSZ[i][j]=SizeB;\n\t\t}\n\t}\t\n}\nint main(){\n\tCLR();\n\tscanf(\"%lld%lld\",&N,&E);\n\tscanf(\"%lld%lld\",&PA,&PB);\n\tfor(int i=1;i<=N;i++)\n\t\tscanf(\"%lld\",P+i),\n\t\t\tALLSUM+=P[i];\n\tfor(int i=0;i<E;i++){\n\t\tint u,v,w;\n\t\tscanf (\"%d%d%d\",&u,&v,&w);\n\t\tadj[u].PB(PLL(v,w));\n\t\tadj[v].PB(PLL(u,w));\n\t}\n\tFillSum();\n\tfor(int i=SZA;i>=0;i--)\n\t\tfor(int j=SZB;j>=0;j--)\n\t\t\tfor(int k=0;k<2;k++){\n\t\t\t\tif(!SZ[i][j])\t\n\t\t\t\t\tcontinue;\n\t\t\t\tif(!k){\n\n\t\t\t\t\tLL TMP;\n\t\t\t\t\tif(SZ[i][j]<=QA[j][0].FF)\n\t\t\t\t\t\tTMP=QA[j][1].SS;\n\t\t\t\t\telse\n\t\t\t\t\t\tTMP=QA[j][0].SS;\n\t\t\t\t\tLL DUMMY=TMP+Sum[i][j];\t\n\t\t\t\t\tif(SZ[i][j]==QB[i][0].FF)\n\t\t\t\t\t\tQB[i][0].SS=max(QB[i][0].SS,-DUMMY);\n\t\t\t\t\telse{\n\t\t\t\t\t\tQB[i][0].SS=max(QB[i][0].SS,QB[i][1].SS);\n\t\t\t\t\t\tQB[i][1]=QB[i][0];\n\t\t\t\t\t\tQB[i][0]=MP(SZ[i][j],-DUMMY);\n\t\t\t\t\t\tQB[i][0].SS=max(QB[i][0].SS,QB[i][1].SS);\n\t\t\t\t\t}\n\t\t\t\t\tif(!i && !j)\n\t\t\t\t\t\tAns=DUMMY;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tLL TMP;\n\t\t\t\t\tif(SZ[i][j]<=QB[i][0].FF)\n\t\t\t\t\t\tTMP=QB[i][1].SS;\n\t\t\t\t\telse\n\t\t\t\t\t\tTMP=QB[i][0].SS;\n\t\t\t\t\tLL DUMMY=TMP+Sum[i][j];\n\t\t\t\t\tif(SZ[i][j]==QA[j][0].FF)\n\t\t\t\t\t\tQA[j][0].SS=max(QA[j][0].SS,-DUMMY);\n\t\t\t\t\telse{\t\n\t\t\t\t\t\tQA[j][0].SS=max(QA[j][0].SS,QA[j][1].SS);\n\t\t\t\t\t\tQA[j][1]=QA[j][0];\n\t\t\t\t\t\tQA[j][0]=MP(SZ[i][j],-DUMMY);\n\t\t\t\t\t\tQA[j][0].SS=max(QA[j][0].SS,QA[j][1].SS);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\tif(2*Ans > ALLSUM)\n\t\tcout<< \"Break a heart\" <<endl;\n\telse if(2*Ans == ALLSUM)\n\t\tcout<< \"Flowers\" <<endl;\n\telse\n\t\tcout<< \"Cry\" <<endl;\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 2900
  },
  {
    "contest_id": "536",
    "index": "E",
    "title": "Tavas on the Path",
    "statement": "Tavas lives in Tavaspolis. Tavaspolis has $n$ cities numbered from $1$ to $n$ connected by $n - 1$ bidirectional roads. There exists a path between any two cities. Also each road has a length.\n\nTavas' favorite strings are binary strings (they contain only 0 and 1). For any binary string like $s = s_{1}s_{2}... s_{k}$, $T(s)$ is its $Goodness$. $T(s)$ can be calculated as follows:\n\nConsider there are exactly $m$ blocks of $1$s in this string (a block of $1$s in $s$ is a maximal consecutive substring of $s$ that only contains $1$) with lengths $x_{1}, x_{2}, ..., x_{m}$.\n\nDefine $T(s)=\\sum_{i=1}^{m}f_{x_{i}}$ where $f$ is a given sequence (if $m = 0$, then $T(s) = 0$).\n\nTavas loves queries. He asks you to answer $q$ queries. In each query he gives you numbers $v, u, l$ and you should print following number:\n\nConsider the roads on the path from city $v$ to city $u$: $e_{1}, e_{2}, ..., e_{x}$.\n\nBuild the binary string $b$ of length $x$ such that: $b_{i} = 1$ if and only if $l ≤ w(e_{i})$ where $w(e)$ is the length of road $e$.\n\nYou should print $T(b)$ for this query.",
    "tutorial": "Let's call the answer for vertices $v$ and $u$ with edges $e_{1}, e_{2}, ..., e_{k}$ on the path, score of sequence $w(e_{1}), w(e_{2}), ..., w(e_{k})$. Use heavy-light decomposition. Decompose the edges into chains. So, for each Query, decompose the path into subchains. After solving the problem for them, combine them. Problem for subchains is : We have an array $a_{1}, a_{2},  \\dots , a_{n}$ and $q$ queries. Each query gives numbers $x, y, l$ ($1  \\le  x  \\le  y  \\le  n$) and we should print the goodness of subarray $a_{x}, a_{x + 1},  \\dots , a_{y}$. For this problem, we have too choices: 1.Solve offline with a normal segment tree. 2.Solve online using persistent segment tree. Now, I prefer to use the first approach. Sort the array to have a permutation of $1, 2,  \\dots , n$: $p_{1}, p_{2},  \\dots , p_{n}$ and $a_{p1}  \\ge  a_{p2}  \\ge   \\dots   \\ge  a_{pn}$. Also sort the queries in the decreasing order of $l$. No for $i - th$ query (in the sorted order) we have information: $x, y, l, index$. Then, use two pointers. Keep a pointer = n and Initially we have a binary string $b$, of length $n$ with all indices set to $0$. Then in each query: Now, we should fins $T(b_{x} \\dots T_{y})$. For this purpose, we need a segment tree. In each node of the segment tree, we need to keep a package named node. A package node is used for calculating $T$ of a binary string $c$. $p =$ the number of leading 1s, $s =$ the number of trading 1s, $cnt =$ the total number of 1s, $tot =$ the $T$ value of the binary string after deleting its leading and trading 1s. Merging two nodes is really easy. Also after reversing $c$, we just need to swap $p$ and $s$. So, we can determine the node of this subarray in subchains. After solving these offline for subchains it's time for combining. Merge the node of subchains in the path from $v$ to $LCA(v, u)$ then merge the result with the reverse of the nodes of answers in the subchains in path from $LCA(v, u)$ to $u$. Time complexity: $O((n + m)log^{2}(n))$ Code by PrinceOfPersia (This was one of the hardest codes I ever wrote in competitive programming :D) Shorter Code by Haghani Java Code by Zlobober If there's any suggestion or error, just let me know.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c)  for(auto &(i) : (c))\n#define x     first\n#define y     second\n#define pb  push_back\n#define PB  pop_back()\n#define iOS  ios_base::sync_with_stdio(false)\n#define sqr(a)  (((a) * (a)))\n#define all(a)  a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x)  ((x)<<1)\n#define R(x)  (((x)<<1)+1)\n#define umap  unordered_map\n//#define max(x,y)  ((x) > (y) ? (x) : (y))\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef pair<long long,long long> PLL;\nconst int maxn = 1e5 + 100;\nconst int maxl = 20;\nint sz[maxn], f[maxn], par[maxn][maxl], h[maxn];\nvi adj[maxn], adw[maxn];\nint chn[maxn];\nint w[maxn];\nstruct node{\n\tll p,s,tot,cnt;\n\tnode(){\n\t\tcnt = p = s = tot = 0LL;\n\t}\n\tnode(int x){\n\t\ttot = 0LL;\n\t\tp = s = cnt = x;\n\t}\n\tinline bool ish(){\n\t\treturn (cnt == p && p && s);\n\t}\n\tinline node operator * (node a){\n\t\tnode ans;\n\t\tans.cnt = a.cnt + cnt;\n\t\tbool h = ish(), H = a.ish();\n\t\tans.tot = a.tot + tot;\n\t\tif(!h && !H){\n\t\t\tans.tot += f[s + a.p];\n\t\t\tans.p = p;\n\t\t\tans.s = a.s;\n\t\t}\n\t\telse if(!h && H){\n\t\t\tans.p = p;\n\t\t\tans.s = s + a.s;\n\t\t}\n\t\telse if(h && !H){\n\t\t\tans.p = p + a.p;\n\t\t\tans.s = a.s;\n\t\t}\n\t\telse{\n\t\t\tans.p = ans.s = p + a.p;\n\t\t}\n\t\treturn ans;\n\t}\n\tinline ll score(){\n\t\tll ans = tot + f[p];\n\t\tif(!ish())\n\t\t\tans += f[s];\n\t\treturn ans;\n\t}\n\tinline node reverse(){\n\t\tnode ans;\n\t\tans.p = s;\n\t\tans.s = p;\n\t\tans.tot = tot;\n\t\tans.cnt = cnt;\n\t\treturn ans;\n\t}\n};\nstruct seg{\n\tvector<node> s;\n\tint sz;\n\tseg(){\n\tsz = 0;}\n\tseg(int n){\n\t\twhile(s.size() < 4 * n)\n\t\t\ts.pb(node());\n\t\tsz = n;\n\t}\n\tinline void add(int p,int id,int l,int r){\n\t\tif(r - l < 2){\n\t\t\ts[id] = node(1);\n\t\t\treturn ;\n\t\t}\n\t\tint mid = (l+r)/2;\n\t\tif(p < mid)\n\t\t\tadd(p, L(id), l, mid);\n\t\telse\n\t\t\tadd(p, R(id), mid, r);\n\t\ts[id] = s[L(id)] * s[R(id)];\n\t}\n\tinline node get(int x,int y,int id,int l,int r){\n\t\tif(x <= l && r <= y)\n\t\t\treturn s[id];\n\t\tint mid = (l+r)/2;\n\t\tif(y <= mid)\n\t\t\treturn get(x, y, L(id), l, mid);\n\t\telse if(mid <= x)\n\t\t\treturn get(x, y, R(id), mid, r);\n\t\treturn get(x, y, L(id), l, mid) * get(x, y, R(id), mid, r);\n\t}\n\tinline void ADD(int p){\n\t\tadd(p, 1, 0, sz);\n\t}\n\tinline node score(int x,int y){\n\t\treturn get(x, y, 1, 0, sz);\n\t}\n\n};\nstruct query{\n\tint ind, mnh, mxh, l;\n\tquery(){\n\t}\n\tquery(int a,int b,int c,int d){\n\t\tind = a;\n\t \tmnh = b;\n\t\tmxh = c;\n\t\tl = d;\n\t}\n};\ninline bool qcmp (const query &a, const query & q){\n\t\treturn a.l < q.l;\n\t}\ninline bool cmp(const pii &p, const pii &q){\n\tif(p.y - q.y)\n\t\treturn p.y > q.y;\n\treturn p.x < q.x;\n}\nstruct chain{\n\tint X,x,y;\n\tseg s;\n\tumap <int, node> MP;\n\tchain(){}\n\tchain(int a,int b): X(a), y(b){}\n\tchain(int a,int b,int c): X(a), x(b), y(c){}\n\tvector<pii> vpn;\n\tvector<query> QQ;\n\tinline void proc(int i){\n\t\tint v = y;\n\t\twhile(v != X){\n\t\t\tif(par[v][0] == X)\n\t\t\t\tx = v;\n\t\t\tvpn.pb({h[v], w[v]});\n\t\t\tchn[v] = i;\n\t\t\tv = par[v][0];\n\t\t}\n\t\tsort(all(vpn));\n\t}\n\tinline void solve(){\n\t\tsort(all(QQ), qcmp);\n\t\ts = seg(vpn.size());\n\t\tvector<pii> vs = vpn;\n\t\tsort(all(vs), cmp);\n\t\treverse(all(QQ));\n\t\tint po = 0;\n\t\trep(q, QQ){\n\t\t\twhile(po < vs.size() && vs[po].y >= q.l){\n\t\t\t\tint i = lower_bound(all(vpn), pii(vs[po].x, -1)) -  vpn.begin();\n\t\t\t\ts.ADD(i);\n\t\t\t\tpo ++;\n\t\t\t}\n\t\t\tint l = lower_bound(all(vpn), pii(q.mnh, -1)) -  vpn.begin();\n\t\t\tint r = upper_bound(all(vpn), pii(q.mxh, 1e9)) -  vpn.begin();\n\t\t\tMP[q.ind] = s.score(l, r);\n\t\t}\n\t}\n};\nvector<chain> HLD;\ninline int dfs(int v = 0,int p = -1){\n\tif(p + 1)\n\t\th[v] = h[p] + 1;\n\tpar[v][0] = p;\n\tFor(i,1,maxl)\tif(par[v][i-1] + 1)\n\t\tpar[v][i] = par[par[v][i-1]][i-1];\n\tsz[v] = 1;\n\tFor(i,0,adj[v].size()){\n\t\tint u = adj[v][i];\n\t\tif(u - p){\n\t\t\tw[u] = adw[v][i];\n\t\t\tsz[v] += dfs(u, v);\n\t\t}\n\t}\n\treturn sz[v];\n}\ninline void prepHLD(int v = 0,bool h = 0,int f = -1){\n\tif(f == -1){\n\t\tif(par[v][0] != -1)\n\t\t\tf = par[v][0];\n\t\telse\n\t\t\tf = v;\n\t}\n\tbool hh = 0, ch = 0, is = 0;\n\t\trep(u, adj[v]){\n\t\t\tif(u - par[v][0] && sz[u] * 2 >= sz[v])\n\t\t\t\thh = 1;\n\t\t\tif(u - par[v][0])\n\t\t\t\tch = 1;\n\t\t}\n\tif(par[v][0] != -1){\n\t\tif(h && !hh && !ch)\n\t\t\tHLD.pb(chain(f,v));\n\t\tif(!h && !ch)\n\t\t\tHLD.pb(chain(par[v][0],v));\n\t}\n\trep(u, adj[v])\n\t\tif(u - par[v][0]){\n\t\t\tif(sz[u] * 2 < sz[v]){\n\t\t\t\tif(!is && !hh)\n\t\t\t\t\tprepHLD(u,1,f);\n\t\t\t\telse\n\t\t\t\t\tprepHLD(u);\n\t\t\t}\n\t\t\telse\n\t\t\t\tprepHLD(u,1,f);\n\t\t\tis = 1;\n\t\t}\n}\ninline int lca(int v,int u){\n\tif(h[u] > h[v])\n\t\tswap(v, u);\n\trof(i, maxl - 1, -1)\n\t\tif(par[v][i] + 1 && h[par[v][i]] >= h[u])\n\t\t\tv = par[v][i];\n\tif(v == u)\treturn v;\n\trof(i, maxl - 1, -1)\n\t\tif(par[v][i] - par[u][i])\n\t\t\tv = par[v][i], u = par[u][i];\n\treturn par[v][0];\n}\ninline vi dec(int v,int H){\n\tvi ans;\n\twhile(v + 1 && h[v] > H){\n\t\tans.pb(chn[v]);\n\t\tv = HLD[chn[v]].X;\n\t}\n\treturn ans;\n}\ninline vi decompose(int v,int u){\n\tint x = lca(v, u);\n\tint H = h[x];\n\tvi ans = dec(v, H);\n\tvi V = dec(u, H);\n\treverse(all(V));\n\trep(w, V)\n\t\tans.pb(w);\n\treturn ans;\n}\nstringstream ss;\ninline void prepQ(int i,int v,int w,int l){\n\twhile(v + 1 && h[v] > h[w]){\n\t\tint j = chn[v];\n\t\tint mnh = h[w] + 1;\n\t\tint mxh = h[v];\n\t\tHLD[j].QQ.pb(query(i, mnh, mxh, l));\n\t\tv = HLD[chn[v]].X;\n\t}\n}\ninline void prepq(int i,int v,int u,int l){\n\tss << v << ' ' << u << ' ' << l << '\\n';\n\tint w = lca(v, u);\n\tprepQ(i, v, w, l);\n\tprepQ(i, u, w, l);\n}\nint IND;\ninline ll ANS(){\n\tint v,u,l;\n\tss >> v >> u >> l;\n\tint w = lca(v, u);\n\tvi V = decompose(v, w);\n\tvi U = decompose(w, u);\n\tnode N(0);\n\trep(c, V)\n\t\tN = N * HLD[c].MP[IND].reverse();//, error(HLD[c].MP[IND].reverse().cnt);\n\trep(c, U){\n\t\tN = N * HLD[c].MP[IND];\n\t/*\terror(HLD[c].MP[IND].cnt);\n\t\terror(HLD[c].MP[IND].p);\n\t\terror(HLD[c].MP[IND].s);\n\t\terror(HLD[c].y);*/\n\n\t}\n\tIND ++;\n\t//Error(N.s, N.p);\n\t//error(N.cnt);\n\treturn N.score();\n}\nint n,q;\nint main(){\n\tmemset(par, -1, sizeof(par));\n\tiOS;\n\tcin >> n >> q;\n\tFor(i,1,n)\n\t\tcin >> f[i];\n\tint v,u,w;\n\tFor(i,1,n){\n\t\tcin >> v >> u >> w;\n\t\t-- v, -- u;\n\t\tadj[v].pb(u);\n\t\tadj[u].pb(v);\n\t\tadw[v].pb(w);\n\t\tadw[u].pb(w);\n\t}\n\tdfs();\n\tprepHLD();\n\tFor(i,0,HLD.size())\n\t\tHLD[i].proc(i);\n\t//error(HLD.size());\n\tFor(i,0,q){\n\t\tcin >> v >> u >> w;\n\t\t-- v, -- u;\n\t\tprepq(i, v, u, w);\n\t}\n\tFor(i,0,HLD.size())\n\t\tHLD[i].solve();\n\tFor(i,0,q)\n\t\tcout << ANS() << '\\n';\n\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "538",
    "index": "A",
    "title": "Cutting Banner",
    "statement": "A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforces$^{ω}$ that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case English letters.\n\nThere is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc.\n\nHelp the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.",
    "tutorial": "Let me first clarify the statement (I really wish I didn't have to do that but it seems many participants had trouble with the correct understanding). You had to erase exactly one substring from the given string so that the rest part would form the word CODEFORCES. The (somewhat vague) wording some substring in the English translation may be the case many people thought that many substrings can be erased; still, it is beyond my understanding how to interpret that as 'more than one substring'. Anyway, I'm sorry for the inconvenience. Right, back to the problem. The most straightforward approach is to try over all substrings (i.e. all starting and ending positions) to erase them and check if the rest is the wanted word. When doing this, you have to be careful not to forget any corner cases, such as: erase few first letters, erase few last letters, erase a single letter, and so on. A popular question was if an empty substring may be erased or not. While it is not clarified explicitly in the statement, the question is irrelevant to the solution, for it is guaranteed in the statement that the initial string is not CODEFORCES, so erasing nothing will not make us happy. From the technical point of view, you could erase a substring from the string using standard functions like substr in C++ or similar, or do some bare-hands work and perform conditional iterating over all symbols. Depending on the implementation, this would be either $O(n^{2})$ or $O(n^{3})$ solution; both of these fit nicely. One way of solving this in linear time is to compute the longest common prefix and suffix for the given string and the string CODEFORCES. If their total length is at least 10 (the length of CODEFORCES), it is possible to leave only some parts of the common prefix and suffix, thus the rest part (being a substring, of course) may be removed for good. If the total length is less than 10, no such way exists. This is clearly $O(n)$ solution (rather $O(n)$ for reading the input, and $O(|t|)$ for comparisons where $t$ is CODEFORCES in our case).",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T>\nbool uin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool uax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    string s;\n    cin >> s;\n    int N = s.size();\n    string t = \"CODEFORCES\";\n    int l = 0, r = 0;\n    while (l < min(10, N) && s[l] == t[l]) ++l;\n    while (r < min(10, N) && s[N - r - 1] == t[10 - r - 1]) ++r;\n    cout << (l + r >= 10 ? \"YES\" : \"NO\") << '\\n';\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "538",
    "index": "B",
    "title": "Quasi Binary",
    "statement": "A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.\n\nYou are given a positive integer $n$. Represent it as a sum of minimum number of quasibinary numbers.",
    "tutorial": "$n$ is up to $10^{6}$. We may note that there are only $2^{6} + 1 = 65$ quasi-binary numbers not exceeding $10^{6}$, so we could find them all and implement a DP solution that counts the optimal representation for all numbers up to $n$, or even a brute-force recursive solution (which is not guaranteed to pass, but has a good odds). Are there more effective solutions? Sure enough. First of all, one can notice that the number of summands in a representation can not be less than $d$ - the largest digit in decimal representation of $n$. That is true because upon adding a quasi-binary number to any number the largest digit may not increase by more than 1 (easy enough to prove using the standard algorithm for adding numbers). On the other hand, $d$ quasi-binary numbers are always enough. To see that, construct a number $m$ as follows: for every digit of $n$ that is not 0, place 1 in the corresponding digit of $m$, and for all the other digits place 0. Clearly, $m$ is quasi-binary. If we subtract $m$ from $n$, all non-zero digits will decrease by 1 (clearly, no carrying will take place), thus the largest digit of $n - m$ will be equal to $d - 1$. Proceeding this way, we end up with the representation of $n$ as a sum of $d$ quasi-binary numbers. This solution is good for every numeric base, and works in $O(d\\log_{d}n)=O(d\\log n/\\log d)$ where $d$ is the base.",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T>\nbool uin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool uax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    int N;\n    cin >> N;\n    vi a;\n    while (N) {\n        int n = N, m = 0, p = 1;\n        while (n) {\n            if (n % 10) m += p;\n            n /= 10; p *= 10;\n        }\n        a.pb(m);\n        N -= m;\n    }\n    cout << a.size() << '\\n';\n    sort(all(a));\n    for (int x: a) cout << x << ' ';\n    cout << '\\n';\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "538",
    "index": "C",
    "title": "Tourist's Notes",
    "statement": "A tourist hiked along the mountain range. The hike lasted for $n$ days, during each day the tourist noted height above the sea level. On the $i$-th day height was equal to some integer $h_{i}$. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all $i$'s from 1 to $n - 1$ the inequality $|h_{i} - h_{i + 1}| ≤ 1$ holds.\n\nAt the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits $|h_{i} - h_{i + 1}| ≤ 1$.",
    "tutorial": "We want to make the maximum height as large as possible. Consider the part of the chain that was travelled between $d_{i}$ and $d_{i + 1}$; we can arrange it in any valid way independently of any other parts of the chain, thus we consider all these parts separately. There also parts before $d_{1}$ and after $d_{n}$, but it is fairly easy to analyze them: make them monotonously decreasing (respectively, increasing), as this maximizes the top point. Without the loss of generality consider $d_{i} = 0$ and $d_{i + 1} = t$ (they may be increased of decreased simultaneously without changing the answer), and $h_{di} = a$, $h_{di + 1} = b$. Clearly, in consistent data $|a - b|  \\le  t$, so if this condition fails for a single pair of adjacent entries, we conclude the data is flawed. If the condition holds, it is fairly easy to construct a valid way to move between the days under the $|h_{i} - h_{i + 1}|  \\le  1$ condition: increase or decrease the height while it differs from $b$, than stay on the same height. That does not make the optimal way, but at least we are sure that the data is not inconsistent. How to construct the optimal arrangement? From the adjacent difference inequality if follows that for any $i$ between $0$ and $t$ the inequalities $h_{i}  \\le  a + i$ and $h_{i}  \\le  b + (t - i)$ hold. Let $h_{i} = min(a + i, b + (t - i))$ on the [0; $t$] segment; clearly, every $h_{i}$ accomodates the largest possible value, therefore the value of maximum is also the largest possible. It suffices to show that these $h_{i}$ satisfy the difference condition. Basically, two cases should be considered: if for $h_{i} = a + i$ and $h_{i + 1} = a + i + 1$, or $h_{i} = b + (t - i)$ and $h_{i + 1} = b + (t - i - 1)$, the statement is obvious. Else, $h_{i} = a + i$ but $h_{i} < b + (t - i) = h_{i + 1} + 1$, and $h_{i + 1} = b - (t - i - 1)$ but $h_{i + 1} < a + (i + 1) = h_{i} + 1$. Thus, $|h_{i} - h_{i + 1}| < 1$, and $h_{i} = h_{i + 1}$. To find the maximum value of maximum height (I really struggle not to use 'maximum maximum') we may either use ternary search on the $h$ function, or find the point where lines $a + i$ and $b + (t - i)$ intersect and try integer points besides the intersection. If we use this approach analytically, we arrive at the formula $(t + a + b) / 2$ (try to prove that yourself!).",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T>\nbool uin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool uax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    int N, M;\n    cin >> N >> M;\n    vi d(M), h(M);\n    forn(i, M) cin >> d[i] >> h[i];\n    int ans = max(h[0] + d[0] - 1, h[M - 1] + (N - d[M - 1]));\n    bool ok = true;\n    forn(i, M - 1) {\n        ok &= abs(h[i] - h[i + 1]) <= d[i + 1] - d[i];\n        ans = max(ans, max(h[i], h[i + 1]) + (d[i + 1] - d[i] - abs(h[i] - h[i + 1])) / 2);\n    }\n    if (!ok) cout << \"IMPOSSIBLE\\n\";\n    else cout << ans << '\\n';\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "538",
    "index": "D",
    "title": "Weird Chess",
    "statement": "Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.\n\nIgor's chessboard is a square of size $n × n$ cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.\n\nLet the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to $n$. Let's assign to each square a pair of integers $(x, y)$ — the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers $(dx, dy)$; using this move, the piece moves from the field $(x, y)$ to the field $(x + dx, y + dy)$. You can perform the move if the cell $(x + dx, y + dy)$ is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than $(x, y)$ and $(x + dx, y + dy)$ are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).\n\nIgor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.",
    "tutorial": "Instead of trying to find out where the piece may go, let's try to find out where it can not go. Initially mark all the moves as possible; if there is a field ($x_{1}$, $y_{1}$) containing a piece, and a field ($x_{2}$, $y_{2}$) not containing a piece and not being attacked, clearly a move ($x_{2} - x_{1}$, $y_{2} - y_{1}$) is not possible. Let us iterate over all pieces and over all non-attacked fields and mark the corresponding moves as impossible. Suppose we let our piece make all the rest moves (that are not yet marked as impossible), and recreate the position with all the pieces in the same places. If a field was not attacked in the initial position, it will not be attacked in the newly-crafted position: indeed, we have carefully removed all the moves that could take a piece to this field. Thus, the only possible problem with the new position is that some field that was attacked before is not attacked now. But our set of moves is maximal in the sense that adding any other move to it will cause the position to be incorrect. Thus, if the new position doesn't coincide with the initial position, the reconstruction is impossible. Else, we have already obtained a correct set of moves. This solution has complexity of $O(n^{4})$ for iterating over all pieces and non-attacked fields. No optimizations were needed to make solution this pass.",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T>\nbool uin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool uax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nint d[300][300], t[300][300];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n    \n    int N;\n    cin >> N;\n    vector<string> f(N);\n    forn(i, N) cin >> f[i];\n    forn(i, 2 * N - 1) forn(j, 2 * N - 1) d[i][j] = 1;\n    forn(i, N) forn(j, N) {\n        if (f[i][j] != 'o') continue;\n        forn(x, N) forn(y, N) if (f[x][y] == '.') d[x - i + N - 1][y - j + N - 1] = 0;\n    }\n    forn(i, N) forn(j, N) {\n        if (f[i][j] != 'o') continue;\n        forn(x, 2 * N - 1) forn(y, 2 * N - 1) {\n            int xx = i + x - (N - 1), yy = j + y - (N - 1);\n            if (min(xx, yy) < 0 || max(xx, yy) >= N || !d[x][y]) continue;\n            t[xx][yy] = 1;\n        }\n    }\n \n    bool ok = true;\n    forn(i, N) forn(j, N) {\n        if (f[i][j] == 'o') continue;\n        ok &= (f[i][j] == 'x') == (t[i][j] == 1);\n    }\n \n    d[N - 1][N - 1] = 2;\n    if (ok) {\n        cout << \"YES\\n\";\n        forn(i, 2 * N - 1) {\n            forn(j, 2 * N - 1) cout << \".xo\"[d[i][j]];\n            cout << '\\n';\n        }\n    } else cout << \"NO\\n\";\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "538",
    "index": "E",
    "title": "Demiurges Play Again",
    "statement": "Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.\n\nThere is a rooted tree on $n$ nodes, $m$ of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to $m$ are placed in such a way that each number appears exactly in one leaf.\n\nInitially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.\n\nDemiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.",
    "tutorial": "With such large constraints our only hope is the subtree dynamic programming. Let us analyze the situation and how the subtrees are involved. Denote $w(v)$ the number of leaves in the subtree of $v$. Suppose that a non-leaf vertex $v$ has children $u_{1}$, $...$, $u_{k}$, and the numbers to arrange in the leaves are 1, $...$, $w(v)$. We are not yet sure how to arrange the numbers but we assume for now that we know everything we need about the children's subtrees. Okay, what is the maximal number we can achieve if the maximizing player moves first? Clearly, he will choose the subtree optimally for himself, and we are eager to help him. Thus, it makes sense to put all the maximal numbers in a single subtree; indeed, if any of the maximal numbers is not in the subtree where the first player will go, we swap it with some of the not-so-maximal numbers and make the situation even better. If we place $w(u_{i})$ maximal numbers (that is, $w(v) - w(u_{i}) + 1$, $...$, $w(v)$) in the subtree of $w(u_{i})$, we must also arrange them optimally; this task is basically the same as arranging the numbers from 1 to $w(u_{i})$ in the subtree of $w(u_{i})$, but now the minimizing player goes first. Introduce the notation $d_{m a x/m i n}\\left(v\\right)$ for the maximal possible result if the maximizing/minimizing (depending on the lower index) player starts. From the previous discussion we obtain $d_{m a x}(v)=\\operatorname*{max}_{i=1}\\bigl(\\boldsymbol{u}\\bigl(\\boldsymbol{v}\\bigr(\\boldsymbol{v}\\bigr)-w\\bigl(\\boldsymbol{u_{i}}\\bigr)+d_{m i n}\\bigl(\\boldsymbol{u_{i}}\\bigr)\\bigr)$. Thus, if we know $d_{m i n}(u_{i})$ for all children, the value of $d_{m a x}(v)$ can be determined. How does the situation change when the minimizing player goes first? Suppose that for each $i$ we assign numbers $n_{1, 1}$, $...$, $n_{1, w(ui)}$ to the leaves of the subtree of $u_{i}$ in some order; the numbers in the subtree of $u_{i}$ will be arranged so that the result is maximal when the maximizing player starts in $u_{i}$. Suppose that numbers $n_{i, j}$ are sorted by increasing of $j$ for every $i$; the minimizing player will then choose the subtree $u_{i}$ in such a way that $n_{i_{1}d p_{m a x}}(u_{i})$ is minimal. For every arrangement, the minimizing player can guarantee himself the result of at most $\\textstyle{\\sum_{i=1}^{k}(d p_{m a x}(u_{i})-1)+1=r}$. Indeed, if all the numbers ${\\cal H}_{i_{1}d p_{m a x}}(u_{i})$ are greater than $r$, all the numbers $n_{i, j}$ for $j>d p_{m a x}(u_{i})$ should also be greater than $r$; but there are $\\sum_{i=1}^{k}(w(u_{i})-d p_{m a x}(u_{i})+1)=w(v)-r+1$ numbers $n_{i, j}$ that should be greater than $r$, while there are only $w(v) - r$ possible numbers from 1 to $w(v)$ to place; a contradiction (pigeonhole principle). On the other hand, the value of $r$ is easily reachable: place all the numbers less than $r$ as $n_{i, j}$ with $j<d p_{m a x}(u_{i})$, and $r$ as, say, $n_{1, dpmax(u1)}$; the first player will have to move to $u_{1}$ to achieve $r$. Thus, $r=\\sum_{i=1}^{k}(d p_{m a x}(u_{i})-1)+1=d p_{m i n}(v)$. The previous, rather formal argument can be intuitively restated as follows: suppose we put the numbers from 1 to $w(v)$ in that order to different subtrees of $v$. Once a subtree of $u_{i}$ contains $dp_{max}(u_{i})$ numbers, the minimizing player can go to $u_{i}$ and grab the current result. It follows that we may safely put $dp_{max}(u_{i}) - 1$ numbers to the subtree of $u(i)$ for each $i$, and the next number (exactly $r$) will be grabbed regardless of what we do (if we do not fail and let the minimizing player grab a smaller number). That DP scheme makes for an $O(n)$ solution, as processing the $k$ children of each node is done in $O(k)$ (provided their results are already there). As an easy exercise, think about how the optimal arrangement of number in the leaves can be constructed; try to make implementation as simple as possible.",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T>\nbool uin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool uax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nconst int MAXN = 210000;\nvi e[MAXN];\nint w[MAXN];\nint dpmax[MAXN], dpmin[MAXN];\n \nvoid dfs(int v) {\n    if (e[v].empty()) {\n        w[v] = 1;\n        dpmax[v] = dpmin[v] = 0;\n        return;\n    }\n \n    int md = 1e9, s = 0;\n    w[v] = 0;\n    for (int u: e[v]) {\n        dfs(u);\n        w[v] += w[u];\n        uin(md, dpmin[u]);\n        s += w[u] - dpmax[u];\n    }\n    dpmax[v] = w[v] - md - 1;\n    dpmin[v] = s - 1;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    int N;\n    cin >> N;\n    forn(i, N - 1) {\n        int x, y;\n        cin >> x >> y;\n        e[--x].pb(--y);\n    }\n    dfs(0);\n    cerr << w[0] << '\\n';\n    cout << dpmax[0] + 1 << ' ' << dpmin[0] + 1 << '\\n';\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "538",
    "index": "F",
    "title": "A Heap of Heaps",
    "statement": "Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.\n\nThe teacher gave Andrew an array of $n$ numbers $a_{1}$, $...$, $a_{n}$. After that he asked Andrew for each $k$ from 1 to $n - 1$ to build a $k$-ary heap on the array and count the number of elements for which the property of the minimum-rooted heap is violated, i.e. the value of an element is less than the value of its parent.\n\nAndrew looked up on the Wikipedia that a $k$-ary heap is a rooted tree with vertices in elements of the array. If the elements of the array are indexed from 1 to $n$, then the children of element $v$ are elements with indices $k(v - 1) + 2$, $...$, $kv + 1$ (if some of these elements lie outside the borders of the array, the corresponding children are absent). In any $k$-ary heap every element except for the first one has exactly one parent; for the element 1 the parent is absent (this element is the root of the heap). Denote $p(v)$ as the number of the parent of the element with the number $v$. Let's say that for a non-root element $v$ the property of the heap is violated if $a_{v} < a_{p(v)}$.\n\nHelp Andrew cope with the task!",
    "tutorial": "The first approach. For a given $k$ and an element $v$, how do we count the number of children of $v$ that violate the property? This is basically a range query 'how many numbers in the range are greater than $v$' (because, evidently, children of any element occupy a subsegment of the array); the answers for every $k$ are exactly the sums of results for queries at all non-leaf vertices. Online data structures for this query type are rather involved; however, we may process the queries offline by decreasing $v$, with a structure that is able to support an array, change its elements and take sum over a range (e.g., Fenwick tree or segment tree). This can be done as follows: for every element of the initial array store 1 in the same place of the structure array if the element has already been processed, and 0 otherwise. Now, if we sum over the range for the element $v$, only processed elements will have impact on the sum, and the result of the query will be exactly the number of elements greater than $v$. After all the queries for $v$, we put 1 in the corresponding element so that queries for smaller elements would take it into account. That makes for an $O((q+n)\\log n)$ solution. Estimate $q$: notice that for a given $k$ there are only $\\sim n/k$ non-leaf vertices, thus the total number of queries will be $\\sim\\sum_{i=1}^{n-1}n/i=O(n\\log n)$ (harmonic sum estimation). To sum up, this solution works in $O(n\\log^{2}n)$ time. The second approach. Let us index the elements of the array starting from 0. It is easy to check that for a given $k$ the parent of the element $a_{v}$ is the element $a_{[(v-1)/k]}$. One can show that there are only $O({\\sqrt{v}})$ different elements that can be the parent of $a_{v}$ for some $k$. Indeed, if $k>{\\sqrt{v-1}}$, the index of the parent is less that $\\sqrt{v-1}$, and all $k\\leq{\\sqrt{v-1}}$ produce no more than $\\sqrt{v-1}$ different parents too. Moreover, each possible parent corresponds to a range of values of $k$. To show that, solve the equality $\\left\\lfloor{\\frac{v-1}{k}}\\right\\rfloor=p$ for $k$. Transform: $p\\leq{\\frac{v-1}{k}}<p+1$, $pk  \\le  v - 1 < (p + 1)k$, $\\begin{array}{c}{{\\frac{v-1}{p+1}<k\\leq\\frac{v-1}{p}}}\\end{array}$, $\\lfloor{\\frac{v-1}{p+1}}\\rfloor\\ <k\\leq\\lfloor{\\frac{v-1}{p}}\\rfloor$. For every $k$ in the range above the property is either violated or not (that depends only on $a_{v}$ and $a_{p}$); if it's violated we should add 1 to all the answers for $k$'s in the range. That can be done in $O(1)$ offline using delta-encoding (storing differences between adjacent elements in the process and prefix-summing them in the end). There will be only $O(n{\\sqrt{n}})$ queries to the delta array (as this is the number of different child-parent pairs for all $k$). This makes for a simple $O(n{\\sqrt{n}})$ solution which barely uses any heavy algorithmic knowledge at all.",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T>\nbool uin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool uax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nconst int MAXN = 210000;\nint a[MAXN];\nint delta[MAXN];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    int N;\n    cin >> N;\n    forn(i, N) cin >> a[i];\n    for1(i, N - 1) {\n        int p;\n        for (p = 0; p * p <= i - 1; ++p) {\n            int l = (p == 0 ? N - 1 : (i - 1) / p), r = (i - 1) / (p + 1);\n            if (a[i] < a[p]) ++delta[r + 1], --delta[l + 1];\n        }\n        for (int k = 1; k <= (i - 1) / p; ++k) {\n            int par = (i - 1) / k;\n            if (a[i] < a[par]) ++delta[k], --delta[k + 1];\n        }\n    }\n    int s = 0;\n    for1(i, N - 1) {\n        s += delta[i];\n        cout << s << \" \\n\"[i + 1 == N];\n    }\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "math",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "538",
    "index": "G",
    "title": "Berserk Robot ",
    "statement": "Help! A robot escaped our lab and we need help finding it.\n\nThe lab is at the point $(0, 0)$ of the coordinate plane, at time 0 the robot was there. The robot's movements are defined by a program — a string of length $l$, consisting of characters U, L, D, R. Each second the robot executes the next command in his program: if the current coordinates of the robot are $(x, y)$, then commands U, L, D, R move it to cells $(x, y + 1)$, $(x - 1, y)$, $(x, y - 1)$, $(x + 1, y)$ respectively. The execution of the program started at time 0. The program is looped, i.e. each $l$ seconds of executing the program start again from the first character. Unfortunately, we don't know what program was loaded into the robot when he left the lab.\n\nOur radars managed to find out the position of the robot at $n$ moments of time: we know that at the moment of time $t_{i}$ the robot is at the point $(x_{i}, y_{i})$. Given this data, either help to determine what program could be loaded into the robot, or determine that no possible program meets the data and the robot must have broken down.",
    "tutorial": "First of all, we'll simplify the problem a bit. Note that after every command the values of $x + y$ and $x - y$ are altered by $ \\pm  1$ independently. Suppose we have a one-dimensional problem: given a sequence of $x$'s and $t$'s, provide a looped program of length $l$ with commands $ \\pm  1$ which agrees with the data. If we are able to solve this problem for numbers $x_{i} + y_{i}$ and $x_{i} - y_{i}$ separately, we can combine the answers to obtain a correct program for the original problem; if one of the subproblems fails, no answer exists. (Most - if not all - participants who solved this problem during the contest did not use this trick and went straight ahead to the two-dimensional problem. While the idea is basically the same, I'm not going into details for their approach, but you can view the submitted codes of contestants for more info on this one.) Ok, now to solve the one-dimensional problem. Let us change the command set from $ \\pm  1$ to $+ 0 / + 1$: set $x_{i}^{\\prime}=(x_{i}+t_{i})/2$. If the division fails to produce an integer for some entry, we must conclude that the data is inconsistent (because $x_{i}$ and $t_{i}$ should have the same parity). Now it is clear to see that the operation $- 1$ becomes operation $0$, and the operation $+ 1$ stays as it is. A program now is a string of length $l$ that consists of 0's and 1's. Denote $s_{i}$ the number of 1's among the first $i$ commands, and $s = s_{l}$ for simplicity. Evidently, an equation $x_{i}=s\\cdot\\left\\lfloor{\\frac{t_{i}}{l}}\\right\\rfloor+s_{t_{i}\\,\\mathrm{mod}\\,1}$ holds, because the full cycle is executed $ \\lfloor  t_{i} / l \\rfloor $ times, and after that $t_{i}{\\bmod{1}}$ more first commands. From this, we deduce $s_{t_{i}\\,{\\mathrm{mod}}\\,1}=x_{i}-s\\cdot\\left\\lfloor{\\frac{t_{i}}{l}}\\right\\rfloor$. Suppose that we know what $s$ is equal to. Using this, we can compute all $s_{t_{i}\\,{\\mathrm{mod}}}|$; they are fixed from now on. One more important fixed value is $s_{l} = s$. In any correct program $s_{i}  \\le  s_{i + 1}  \\le  s_{i} + 1$, but not all values of $s_{i}$ are known to us. When is it possible to fill out the rest of $s_{i}$ to match a correct program? If $s_{a}$ and $s_{b}$ are adjacent entries that are fixed (that is, every $s_{c}$ under $a < c < b$ is not fixed), the inequality $0  \\le  s_{b} - s_{a}  \\le  b - a$ must hold ($a$ and $b$ may coincide if for different $i$ several values of $t_{i}{\\bmod{1}}$ coincide). Furthermore, if the inequality holds for every pair of adjacent fixed entries, a correct program can be restored easily: move over the fixed values, and place $s_{b} - s_{a}$ 1's between positions $a$ and $b$ in any possible way, fill with 0's all the other positions in between. The trouble is that we don't know $s$ in advance. However, we know the positions and the order in which fixed values of $s_{a}$ come! Sort them by non-decreasing of $a$. All fixed $s_{a}$ can be expressed as linear functions of $s$; if we substitute these expressions in the $0  \\le  s_{b} - s_{a}  \\le  b - a$, from each pair of adjacent fixed values we obtain an inequality of general form $0  \\le  p \\cdot s + q  \\le  d$, where $p$, $q$, $d$ are known values. If the obtained system of inequalities has a solution, we can get ourselves a valid $s$ and restore the program as discussed above. It suffices to notice that every inequality of the system has a set of solutions of general form $l  \\le  s  \\le  r$ (if the set is not empty), where $l$ and $r$ should be calculated carefully depending on the sign of $p$. All the intervals should be intersected, and the resulting interval provides a range of valid values of $s$. Overall, the solution works in $O(n\\log n+l)$, or even in $O(n + l)$ if we use bucketing instead of sorting. Note that the $l$ summand in the complexity is only there for the actual program reconstruction; if we were only to check the existence of a program, an $O(n)$ solution would be possible.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <map>\n#include <queue>\n#include <set>\n#include <string>\n#include <vector>\n \n#define mp make_pair\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef pair<i64, i64> pi64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T>\nbool uin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool uax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nconst int MAXN = 210000;\n \ni64 t[MAXN], x[MAXN], y[MAXN];\nint N, L;\n \nstruct TPoint {\n    i64 t, a, b;\n \n    TPoint(i64 t = 0, i64 a = 0, i64 b = 0)\n        : t(t)\n        , a(a)\n        , b(b)\n    {\n    }\n \n    bool operator<(const TPoint &p) const {\n        return t < p.t;\n    }\n};\n \ni64 fl(i64 x, i64 y) {\n    if (x >= 0) return x / y;\n    return x / y - (x % y ? 1 : 0);\n}\n \ni64 cl(i64 x, i64 y) {\n    if (x >= 0) return (x + y - 1) / y;\n    return x / y;\n}\n \nvi solve(vi64 x) {\n    forn(i, N) {\n        if ((x[i] + t[i]) % 2) return vi();\n        x[i] = (x[i] + t[i]) / 2;\n    }\n    vector<TPoint> q;\n    forn(i, N) {\n        q.pb(TPoint(t[i] % L, -(t[i] / L), x[i]));\n    }\n    q.pb(TPoint(0, 0, 0));\n    q.pb(TPoint(L, 1, 0));\n    sort(all(q));\n    i64 l = 0, r = L;\n    forn(i, (int)q.size() - 1) {\n        i64 a = q[i + 1].a - q[i].a, b = q[i + 1].b - q[i].b;\n        i64 d = q[i + 1].t - q[i].t;\n        i64 lh = -b, rh = d - b;\n        if (!a) {\n            if (lh > 0 || rh < 0) return vi();\n        } else {\n            if (a < 0) {\n                a = -a;\n                swap(lh, rh);\n                lh = -lh; rh = -rh;\n            }\n            uin(r, fl(rh, a));\n            uax(l, cl(lh, a));\n        }\n    }\n    if (l > r) return vi();\n    vi ans;\n    int s = 0;\n    cerr << l << ' ' << r << '\\n';\n    forn(i, q.size()) {\n        while (s < l * q[i].a + q[i].b) {\n            ans.pb(1);\n            ++s;\n        }\n        while (ans.size() < q[i].t) ans.pb(0);\n    }\n    return ans;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    cin >> N >> L;\n    forn(i, N) cin >> t[i] >> x[i] >> y[i];\n    vi64 x1(N), x2(N);\n    forn(i, N) {\n        x1[i] = x[i] + y[i]; x2[i] = x[i] - y[i];\n    }\n    vi ans1 = solve(x1), ans2 = solve(x2);\n    if (ans1.empty() || ans2.empty()) {\n        cout << \"NO\\n\";\n    } else {\n        forn(i, L) cout << \"LDUR\"[2 * ans1[i] + ans2[i]];\n        cout << '\\n';\n    }\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "sortings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "538",
    "index": "H",
    "title": "Summer Dichotomy",
    "statement": "$T$ students applied into the ZPP class of Summer Irrelevant School. The organizing committee of the school may enroll any number of them, but at least $t$ students must be enrolled. The enrolled students should be divided into two groups in any manner (it is possible that one of the groups will be empty!)\n\nDuring a shift the students from the ZPP grade are tutored by $n$ teachers. Due to the nature of the educational process, each of the teachers should be assigned to exactly one of two groups (it is possible that no teacher will be assigned to some of the groups!). The $i$-th teacher is willing to work in a group as long as the group will have at least $l_{i}$ and at most $r_{i}$ students (otherwise it would be either too boring or too hard). Besides, some pairs of the teachers don't like each other other and therefore can not work in the same group; in total there are $m$ pairs of conflicting teachers.\n\nYou, as the head teacher of Summer Irrelevant School, have got a difficult task: to determine how many students to enroll in each of the groups and in which group each teacher will teach.",
    "tutorial": "The problem has several possible approaches. The first approach. More popular one. Forget about $t$ and $T$ for a moment; we have to separate teachers into two groups so that no conflicting teachers are in the same group, and the number of students in each group can be chosen to satisfy all the teachers. Consider a connected component via the edges which correspong to conflicting pairs. If the component is not bipartite, there is clearly no valid distribution. Else, the teachers in the component can be separated into two sets such that each set should be in the same group, and the groups for the sets should be different. The teachers in the same set will always go together in the same group, so we may as well make them into a single teacher whose interval is the intersection of all the intervals for the teachers we just compressed. Now, the graph is the set of disjoint edges (for simplicity, if a teacher does not conflict with anyone, connect him with a 'fake' teacher whose interval is $[0; \\infty ]$). Consider all possible distributions of students; they are given by a pair $(n_{1}, n_{2})$. Provided this distribution, in what cases a pair of conflicting teachers can be arranged correctly? If the teachers' segments are $[l_{1}, r_{1}]$ and $[l_{2}, r_{2}]$, either $l_{1}  \\le  n_{1}  \\le  r_{1}$ and $l_{2}  \\le  n_{2}  \\le  r_{2}$, or $l_{2}  \\le  n_{1}  \\le  r_{2}$ and $l_{1}  \\le  n_{2}  \\le  r_{1}$ must hold. Consider a coordinate plane, where a point $(x, y)$ corresponds to a possible distribution of students. For a pair of conflicting teachers the valid configurations lie in the union of two rectangles which are given by the inequalities above. Valid configurations that satisfy all pairs of teachers lie exactly in the intersection of all these figures. Thus, the problem transformed to a (kinda) geometrical one. A classical approach to this kind of problems is to perform line-sweeping. Note that any 'union of two rectangles' figure (we'll shorten it to UOTR) is symmetrical with respect to the diagonal line $x = y$. It follows that for any $x$ the intersection of the vertical line given by $x$ with any UOTR is a subsegment of $y$'s. When $x$ sweeps from left to right, for any UOTR there are $O(1)$ events when a subsegment changes. Sort the events altogether and perform the sweeping while updating the sets of subsegments' left and right ends and the subsegments intersection (which is easy to find, given the sets). Once the intersection becomes non-empty, we obtain a pair $(x, y)$ that satisfies all the pairs of teachers; to restore the distribution is now fairly easy (don't forget that every teacher may actually be a compressed set of teachers!). Didn't we forget something? Right, there are bounds $t$ and $T$ to consider! Consider an adjacent set of events which occurs when $x = x_{1}$ and $x = x_{2}$ respectively. The intersection of subsegments for UOTRs obtained after the first event will stay the same while $x_{1}  \\le  x < x_{2}$. Suppose the $y$'s subsegmen intersection is equal to $[l;r]$. If we stay within $x_{1}  \\le  x < x_{2}$, for a satisfying pair of $(x, y)$ the minimal value of $x + y$ is equal to $x_{1} + l$, and the maximal value is $x_{2} + r - 1$. If this range does not intersect with $[t;T]$, no answer is produced this turn. In the other case, choose $x$ and $y$ while satisfying all boundaries upon $x$, $y$ and $x + y$ (consider all cases the rectangle can intersect with a 45-angle diagonal strip). Thus, the requirement of $t$ and $T$ does not make our life much harder. This solution can be implemented in $O(m+n\\log n)$ using an efficient data structure like std::set or any self-balancing BST for sets of subsegments' ends. The very same solution can be implemented in the flavour of rectangles union problem canonical solution: represent a query 'add 1 to all the points inside UORT' with queries 'add $x$ to all the points inside a rectangle', and find a point with the value $m$. The second approach. Less popular, and probably much more surprising. Imagine that the values of $t$ and $T$ are small. Introduce the set of boolean variables $z_{i, j}$ which correspond to the event '$n_{i}$ does not exceed $j$' ($i$ is either 1 or 2, $j$ ranges from 0 to $T$). There are fairly obvious implication relations between them: $z_{i,j}\\Rightarrow z_{i,j+1}$. As $t  \\le  n_{1} + n_{2}  \\le  T$, we must also introduce implications $z_{i,j}\\Rightarrow\\!|z_{i^{\\prime},t-j-1}|$ (here $i'$ is 1 or 2 not equal to $i$) because if $a + b  \\ge  t$ and $a  \\le  j$, $b$ must be at least $t - j$, and $[z_{i,j}\\Rightarrow z_{i^{\\prime},T-j-1}$ for a similar reason. In this, $z_{i, j}$ for $j < 0$ clearly must be considered automatically false, and $z_{i, j}$ for $j  \\ge  T$ must be considered automatically true (to avoid boundary fails). The last thing to consider is the teachers. For every teacher introduce a binary variable $w_{j}$ which corresponds to the event 'teacher $j$ tutors the first group'. The implications $w_{j}\\Rightarrow z_{1,r_{i}}\\cap|z_{1,l_{i}-1}$ and $|w_{j}\\Rightarrow z_{2,r_{i}}|1z_{2,l_{i}-1}$ are pretty much self-explanating. A conflicting pair of teachers $j$ and $k$ is resolved in a straightforward way: $w_{j}\\Rightarrow\\!\\left\\{w_{k}$, $1w_{j}\\Rightarrow w_{k}$. If a set of values for all the boolean variables described satisfies all the restrictions, a valid distribution can be restored explicitly: $n_{1}$ and $n_{2}$ are maximal so that $z_{1, n1}$ and $z_{2, n2}$ hold, and the teachers are distributed unequivocally by values of $w_{j}$. It suffices to notice that the boolean system is a 2-SAT instance, and can be solved in linear time. If we count carefully, we obtain that the whole solution has linear complexity as well: $O(n + m + T)$. Didn't we forget something? Right! The value of $T$ may be too much to handle $ \\Omega (T)$ variables explicitly. To avoid that, one may notice that the set of possible values of $n_{1}$ and $n_{2}$ may be reduced to $0$, $t$, $l_{i}$, $t - l_{i}$, $r_{i}$, $t - r_{i}$. We can prove that by starting from any valid values of $n_{1}$ and $n_{2}$ and trying to make them as small as possible; the listed values are the ones we may end up with. Thus, we can only use $O(n)$ variables instead of $ \\Omega (T)$. The implications can be built similarily, but using lower/upper bound on the list of possible values instead of exact values (much care is advised!). Finally, this solution can be made to work in $O(m+n\\log n)$, with the logarithmic factor from all the sorting and lower/upperbounding.",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T>\nbool uin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool uax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nconst int MAXN = 110000;\nint l[MAXN], r[MAXN];\nconst int MAXT = 2000000;\nint vis[MAXT], comp[MAXT];\nvi e[MAXT], re[MAXT];\n \nvoid addEdge(int v, int u) {\n    e[v].pb(u);\n    e[u ^ 1].pb(v ^ 1);\n    re[u].pb(v);\n    re[v ^ 1].pb(u ^ 1);\n}\n \nvi ord;\n \nvoid dfs_ord(int v) {\n    if (vis[v]) return;\n    vis[v] = 1;\n    for (int u: e[v]) dfs_ord(u);\n    ord.pb(v);\n}\n \nvoid dfs_mark(int v, int c) {\n    if (vis[v]) return;\n    vis[v] = 1;\n    comp[v] = c;\n    for (int u: re[v]) dfs_mark(u, c);\n}\n \nint val(int v) {\n    return comp[v] > comp[v + 1];\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    int t, T;\n    cin >> t >> T;\n    int N, M;\n    cin >> N >> M;\n    forn(i, N) cin >> l[i] >> r[i];\n    vector<pii> conf(M);\n    forn(i, M) {\n        cin >> conf[i].fi >> conf[i].se;\n        --conf[i].fi; --conf[i].se;\n    }\n \n    bool ok = true;\n \n    vi v;\n    v.pb(0);\n    v.pb(t);\n    v.pb(T);\n    forn(i, N) {\n        v.pb(l[i]);\n        if (l[i] <= t) v.pb(t - l[i]);\n        v.pb(r[i]);\n        if (r[i] <= t) v.pb(t - r[i]);\n    }\n    sort(all(v));\n    v.erase(unique(all(v)), v.end());\n    while (v.back() > T) v.pop_back();\n//    for (int u: v) cerr << u << ' ';\n//    cerr << '\\n';\n    int K = v.size();\n    int off1 = 0, off2 = 2 * K, off3 = 4 * K;\n    int V = off3 + 2 * N;\n    assert(V <= MAXT);\n    int j = K - 1;\n    forn(i, K - 1) {\n        addEdge(off1 + 2 * i, off1 + 2 * (i + 1));\n        addEdge(off2 + 2 * i, off2 + 2 * (i + 1));\n    }\n    forn(i, K - 1) {\n        while (j >= 0 && v[i + 1] + v[j] > T) --j;\n        if (j < 0) break;\n        addEdge(off1 + 2 * i + 1, off2 + 2 * j);\n        addEdge(off2 + 2 * i + 1, off1 + 2 * j);\n    }\n    addEdge(off1 + 2 * K - 1, off1 + 2 * K - 2);\n    addEdge(off2 + 2 * K - 1, off2 + 2 * K - 2);\n    j = K - 1;\n    forn(i, K) {\n        while (j >= 0 && v[i] + v[j] >= t) --j;\n        if (j < 0) break;\n//        cerr << v[i] << \" => !\" << v[j] << '\\n';\n        addEdge(off1 + 2 * i, off2 + 2 * j + 1);\n        addEdge(off2 + 2 * i, off1 + 2 * j + 1);\n    }\n    forn(i, N) {\n        int j = (upper_bound(all(v), r[i]) - v.begin()) - 1;\n        assert(j >= 0);\n//        cerr << \"p\" << i << \" => \" << v[j] << '\\n';\n        addEdge(off3 + 2 * i, off1 + 2 * j);\n        addEdge(off3 + 2 * i + 1, off2 + 2 * j);\n \n        j = (lower_bound(all(v), l[i]) - v.begin()) - 1;\n        if (j < 0) continue;\n//        cerr << \"!p\" << i << \" => !\" << v[j] << '\\n';\n        addEdge(off3 + 2 * i, off1 + 2 * j + 1);\n        addEdge(off3 + 2 * i + 1, off2 + 2 * j + 1);\n    }\n    forn(i, M) {\n        int x = conf[i].fi, y = conf[i].se;\n        addEdge(off3 + 2 * x, off3 + 2 * y + 1);\n        addEdge(off3 + 2 * x + 1, off3 + 2 * y);\n    }\n \n    forn(i, V) dfs_ord(i);\n    reverse(all(ord));\n    forn(i, V) vis[i] = 0;\n    int cc = 0;\n    for (int v: ord) {\n        if (vis[v]) continue;\n        dfs_mark(v, cc++);\n    }\n \n    forn(i, V / 2) ok &= comp[2 * i] != comp[2 * i + 1];\n \n    if (!ok) {\n        cout << \"IMPOSSIBLE\\n\";\n        return 0;\n    }\n    cout << \"POSSIBLE\\n\";\n    int A = 0, B = 0;\n    forn(i, K) if (val(off1 + 2 * i) == 1) {\n        A = v[i]; break;\n    }\n    forn(i, K) if (val(off2 + 2 * i) == 1) {\n        B = v[i]; break;\n    }\n    cout << A << ' ' << B << '\\n';\n    forn(i, N) cout << (val(off3 + 2 * i) ? '1' : '2');\n    cout << '\\n';\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "2-sat",
      "data structures",
      "dfs and similar",
      "greedy"
    ],
    "rating": 3200
  },
  {
    "contest_id": "540",
    "index": "A",
    "title": "Combination Lock",
    "statement": "Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.\n\nThe combination lock is represented by $n$ rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?",
    "tutorial": "For every symbol we should determine how to rotate the disk. This can be done either by formula: $min(abs(a[i] - b[i]), 10 - abs(a[i] - b[i]))$ or even by the two for cycles: in both directions.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "540",
    "index": "B",
    "title": "School Marks",
    "statement": "Little Vova studies programming in an elite school. Vova and his classmates are supposed to write $n$ progress tests, for each test they will get a mark from 1 to $p$. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value $x$, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than $y$ points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.\n\nVova has already wrote $k$ tests and got marks $a_{1}, ..., a_{k}$. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.",
    "tutorial": "First count the number of marks that are less than $y$. If there are more than $\\scriptstyle{\\frac{n-1}{2}}$ such marks, we can't satisfy the second condition (about the median), and the answer is -1. Otherwise we can get exactly such number of $y$ marks so that the total number of marks greater than or equal to $y$ is at least $\\textstyle{\\frac{n+1}{2}}$ (maybe it's already satisfied). This is the required action for satisfying the second condition. Now, in order not to break the first condition, get the remaining marks as lower as possible - all ones - and check the sum of the marks. If it is greater than $x$, the answer is -1, otherwise the correct answer is found.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "540",
    "index": "C",
    "title": "Ice Cave",
    "statement": "You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.\n\nThe level of the cave where you are is a rectangular square grid of $n$ rows and $m$ columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.\n\nLet's number the rows with integers from $1$ to $n$ from top to bottom and the columns with integers from $1$ to $m$ from left to right. Let's denote a cell on the intersection of the $r$-th row and the $c$-th column as $(r, c)$.\n\nYou are staying in the cell $(r_{1}, c_{1})$ and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell $(r_{2}, c_{2})$ since the exit to the next level is there. Can you do this?",
    "tutorial": "There are three cases here, though some of them can be merged. If the start and finish cells are equal, let's count the intact neighbours of this cell. If there is one, move there and instantly move back - the answer is YES. Otherwise it's NO. If the start and finish cells are neighbours, the solution depends on the type of the destination cell. If it's cracked, the answer is YES - we can just move there and fall down. Otherwise it must have at least one intact neighbour to get the positive answer - we can move to the finish cell, then to this intact neighbour, and then return to the finish cell. In the general case, check if the path from the start cell to the finish cell exists. If it doesn't, the answer is NO. Otherwise check the type of the destination cell. If it's cracked, it must have at least one intact neighbour, and if it's intact, it must have two intact neighbours.",
    "tags": [
      "dfs and similar"
    ],
    "rating": 2000
  },
  {
    "contest_id": "540",
    "index": "D",
    "title": "Bad Luck Island",
    "statement": "The Bad Luck Island is inhabited by three kinds of species: $r$ rocks, $s$ scissors and $p$ papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.",
    "tutorial": "Let's count the values dp[r][s][p] - the probability of the situation when r rocks, s scissors and p papers are alive. The initial probability is 1, and in order to calculate the others we should perform the transitions. Imagine we have r rocks, s scissors and p papers. Let's find the probability of the rock killing scissors (the other probabilities are calculated in the same way). The total number of the possible pairs where one species kills the other one is $rs + rp + sp$, and the number of possible pairs (rock, scissors) is $rs$. As all meetings are equiprobable, the probability we want to find is $\\frac{T s}{r s+r p+s p}$. This is the probability with which we go the the state dp[r][s - 1][p], with the number of scissors less by one. In the end, for example, to get the probability of the event that the rocks are alive, we should sum all values dp[i][0][0] for i from 1 to r (the same goes to the other species).",
    "code": "#include <cstdio>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cstring>\n#include <string>\nusing namespace std;\n\ntypedef long double ld;\n\nld a[105][105][105];\n\nint main() {\n\tint R, S, P;\n\tcin >> R >> S >> P;\n\n\ta[R][S][P] = 1;\n\tfor (int sum = R + S + P; sum > 0; sum--) {\n\t\tfor (int r = R; r >= 0; r--) {\n\t\t\tfor (int s = S; s >= 0; s--) {\n\t\t\t\tint p = sum - r - s;\n\t\t\t\tif (p < 0 || p > P) continue;\n\t\t\t\tif (r == 0 && s == 0) continue;\n\t\t\t\tif (r == 0 && p == 0) continue;\n\t\t\t\tif (s == 0 && p == 0) continue;\n\t\t\t\tld cur = a[r][s][p];\n\t\t\t\tint waysR = r * s;\n\t\t\t\tint waysS = s * p;\n\t\t\t\tint waysP = p * r;\n\t\t\t\tint totalWays = waysR + waysS + waysP;\n\t\t\t\tif (r > 0) a[r - 1][s][p] += cur * waysP / totalWays;\n\t\t\t\tif (s > 0) a[r][s - 1][p] += cur * waysR / totalWays;\n\t\t\t\tif (p > 0) a[r][s][p - 1] += cur * waysS / totalWays;\n\t\t\t}\n\t\t}\n\t}\n\n\tld ansR = 0;\n\tld ansS = 0;\n\tld ansP = 0;\n\tfor (int r = 1; r <= R; r++) ansR += a[r][0][0];\n\tfor (int s = 1; s <= S; s++) ansS += a[0][s][0];\n\tfor (int p = 1; p <= P; p++) ansP += a[0][0][p];\n\n\tprintf(\"%.12f %.12f %.12f\\n\", (double)ansR, (double)ansS, (double)ansP);\n}",
    "tags": [
      "dp",
      "probabilities"
    ],
    "rating": 1900
  },
  {
    "contest_id": "540",
    "index": "E",
    "title": "Infinite Inversions",
    "statement": "There is an infinite sequence consisting of all positive integers in the increasing order: $p = {1, 2, 3, ...}$. We performed $n$ swap operations with this sequence. A $swap(a, b)$ is an operation of swapping the elements of the sequence on positions $a$ and $b$. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs $(i, j)$, that $i < j$ and $p_{i} > p_{j}$.",
    "tutorial": "At first find the position of each element which is used in swap (using map). Now let's find the answer. It consists of the two parts. First part is the number of inversions formed by only whose elements which took part in the swaps. They can be counted by one of the standard ways: mergesort or Fenwick tree. The second part is the number of inversions formed by pairs of elements where one element has been swapped even once, and the other element stayed at his position. Let's consider the following test: The global sequence will look as follows: [1 6 3 8 5 2 7 4 9 ...], and here is the array of swapped elements: [6 8 2 4]. Let's understand with which numbers the number 8 forms the inversions. The only elements that could do that are the elements between the initial position of the number 8 (where the number 4 is now) and its current position: [5 2 7]. There are two numbers on this segment which didn't take part in swaps: 5 and 7. The number 2 should not be counted as it took part in the swaps and we have already counted it in the first part of the solution. So we should take the count of numbers between 8's indices in the global sequence ($8 - 4 - 1 = 3$) and subtract the count of numbers between its indices in the swaps array ($4 - 2 - 1 = 1$). We'll get the number of inversions formed by the element 8 and the elements which haven't moved at all, it's 2. Counting this value for all elements which have been swapped at least once, we get the second part of the answer. All operations in the second part of the solution can be performed using sorts and binary searches. +103 dalex 10 years ago 69",
    "code": "class E {\n    static class Item implements Comparable<Item> {\n        int pos, val;\n\n        public Item(int pos, int val) {\n            this.pos = pos;\n            this.val = val;\n        }\n\n        public int compareTo(Item o) {\n            if (pos != o.pos) {\n                return Integer.compare(pos, o.pos);\n            }\n            return Integer.compare(val, o.val);\n        }\n    }\n\n    static class FenwickTree {\n        int n;\n        int[] a;\n\n        public FenwickTree(int n) {\n            this.n = n;\n            a = new int[n];\n        }\n\n        private int sum(int r) {\n            int res = 0;\n            for (int i = r; i >= 0; i = (i & (i + 1)) - 1) {\n                res += a[i];\n            }\n            return res;\n        }\n\n        private int sum(int l, int r) {\n            return sum(r) - sum(l - 1);\n        }\n\n        private void inc(int i) {\n            for (; i < n; i |= i + 1) {\n                a[i]++;\n            }\n        }\n    }\n\n    public void solve(int testNumber, InputReader in, OutputWriter out) {\n        int q = in.readInt();\n        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();\n        for (int i = 0; i < q; i++) {\n            int pos1 = in.readInt() - 1;\n            int pos2 = in.readInt() - 1;\n            int num1 = map.containsKey(pos1) ? map.get(pos1) : pos1;\n            int num2 = map.containsKey(pos2) ? map.get(pos2) : pos2;\n            map.put(pos1, num2);\n            map.put(pos2, num1);\n        }\n        Item[] a = new Item[map.size()];\n        int n = 0;\n        for (Map.Entry<Integer, Integer> e : map.entrySet()) {\n            a[n++] = new Item(e.getKey(), e.getValue());\n        }\n        int[] b = new int[n];\n        for (int i = 0; i < n; i++) {\n            b[i] = a[i].val;\n        }\n        compress(b);\n        long ans = 0;\n        FenwickTree tree = new FenwickTree(n);\n        for (int i = 0; i < n; i++) {\n            ans += tree.sum(b[i], n - 1);\n            tree.inc(b[i]);\n        }\n        for (int idxAfter = 0; idxAfter < n; idxAfter++) {\n            int idxBefore = ~Arrays.binarySearch(a, new Item(a[idxAfter].val, -1));\n            ans += Math.abs(a[idxAfter].pos - a[idxBefore].pos);\n            ans -= Math.abs(idxAfter - idxBefore);\n        }\n        out.printLine(ans);\n    }\n\n    private void compress(int[] a) {\n        TreeSet<Integer> set = new TreeSet<Integer>();\n        for (int x : a) {\n            set.add(x);\n        }\n        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();\n        for (int x : set) {\n            int id = map.size();\n            map.put(x, id);\n        }\n        for (int i = 0; i < a.length; i++) {\n            a[i] = map.get(a[i]);\n        }\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "sortings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "542",
    "index": "A",
    "title": "Place Your Ad Here",
    "statement": "Ivan Anatolyevich's agency is starting to become famous in the town.\n\nThey have already ordered and made $n$ TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the $i$-th video can only be shown within the time range of $[l_{i}, r_{i}]$ (it is not necessary to use the whole segment but the broadcast time should be within this segment).\n\nNow it's time to choose a TV channel to broadcast the commercial. Overall, there are $m$ TV channels broadcasting in the city, the $j$-th one has $c_{j}$ viewers, and is ready to sell time $[a_{j}, b_{j}]$ to broadcast the commercial.\n\nIvan Anatolyevich is facing a hard choice: he has to choose exactly one video $i$ and exactly one TV channel $j$ to broadcast this video and also a time range to broadcast $[x, y]$. At that the time range should be chosen so that it is both within range $[l_{i}, r_{i}]$ and within range $[a_{j}, b_{j}]$.\n\nLet's define the efficiency of the broadcast as value $(y - x)·c_{j}$ — the total sum of time that all the viewers of the TV channel are going to spend watching the commercial. Help Ivan Anatolyevich choose the broadcast with the maximum efficiency!",
    "tutorial": "Let's fix the TV channel window and look for a commerical having the largest intersection with it. There are four types of commercials: lying inside the window, overlapping the window and partially intersecting the window from the left and from the right. It's easy to determine if there is overlapping commercial: it's enough to sort commercials in increasing order of the left end and then while iterating over them from left to right, keep the minimum value of a right end of a commercial. If when we pass the window $j$ and see that current value of the maximum right end is no less than $b_{j}$ then there exists a commercial overlapping our window and the value is equal to the $(r_{i} - l_{i}) \\cdot c_{i}$. Among all commercials that lie inside our window we need the longest one. It can be done by similar but a bit harder manner. Let's use sweepline method. While passing through the end of the commercial $r_{i}$, let's assign in some data structure (like segment tree) the value $r_{i} - l_{i}$ in point $l_{i}$. While passing through the end of a window, let's calculate answer for it as a maximum on segment $[a_{j}, b_{j}]$. By doing this, we consider all commercials inside the window. We can process partially intersecting commercials in the similar way. While passing the right end of the commercial $r_{i}$ let's put the value $r_{i}$ in the point $l_{i}$ in our data structure. While passing through the right end of a window $b_{j}$ let's calculate the answer for it as a maximum on the segment $[a_{j}, b_{j}]$ minus $a_{j}$. Among all answers for all commercials we need to choose the largest one. So we have the solution in $O(n\\log n)$.",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "542",
    "index": "B",
    "title": "Duck Hunt",
    "statement": "A duck hunter is doing his favorite thing, hunting. He lives in a two dimensional world and is located at point $(0, 0)$. As he doesn't like walking for his prey, he prefers to shoot only vertically up (because in this case, the ducks fall straight into his hands). The hunter doesn't reload the gun immediately — $r$ or more seconds must pass between the shots. When the hunter shoots up, the bullet immediately hits all the ducks who are directly above the hunter.\n\nIn a two dimensional world each duck is a horizontal segment that moves horizontally in the negative direction of the $Ox$ axis at the speed $1$ length unit per second. For each duck we know the values $h_{i}$ and $t_{i}$ — the $x$-coordinates of its head (the left end of the segment) and its tail (the right end of the segment) at time $0$. The height where the duck is flying isn't important as the gun shoots vertically up to the infinite height and hits all the ducks on its way.\n\n\\begin{center}\n{\\small The figure to the first sample.}\n\\end{center}\n\nWhat maximum number of ducks can the hunter shoot? The duck is considered shot by the hunter if at the moment of the shot at least one of its point intersects the $Oy$ axis. After the hunter shoots the duck, it falls and it can't be shot anymore. The hunter cannot make shots before the moment of time 0.",
    "tutorial": "First of all, let's say that ducks stay still and the one that moves is the hunter. Let's define the value $F[x][s]$ as the minimum number of ducks among having the right end no further than $x$, that we can't shot if the last shot was in the point $s$. In particular, the value $F[x][s]$ includes all ducks located inside the segment $[s + 1, x]$. Values $F[x][s]$ for $s > x$ let's consider as undefined. Let's look on $F[x]$ as on a function of $s$. This function is defined on all $s$ from $0$ to $x$ inclusive. The key idea is in investigating how $F[x + 1][ \\cdot ]$ differs from $F[x][ \\cdot ]$. Let's first suppose that in point $x + 1$ there is no end of the duck. Then in definition of $F[x + 1][ \\cdot ]$ we consider the same set of the ducks as for the definition f $F[x][ \\cdot ]$. That means that all values $F[x][s]$ for $s  \\le  x$ are the same for $F[x + 1]$. Let's understand what happens with $F[x + 1][x + 1]$. It's easy to see that the shot in point $x + 1$ can't kill any of the ducks that end no further than $x + 1$ (since we just supposed that there are no ducks ending in exactly $x + 1$). So, $F[x + 1][x + 1] = min F[x + 1][0... x + 1 - r] = min F[x][0... x + 1 - r]$. Now let's suppose that in point $x + 1$ the duck $[l, x + 1]$ ends. In this case we can say that all values of $F[x + 1][0... l - 1]$ should be increased by $1$ (since at the moment of shot in point $s < l$ the duck $[l, x + 1]$ can't be killed yet). From the other hand, all values $F[x + 1][l... x + 1]$ remain the same since the last shot kills the newly added duck. Now let's understand how to implement all this stuff. Function $F[x][ \\cdot ]$ is piecewise constant, so it can be stored in a Cartesian tree as a sequence of pairs (beginning of segment, value on segment). Such storage allows us to easily add $1$ on prefix and take minimum on prefix of a function. Now let's think that $F[x][ \\cdot ]$ is defined on all posistive values but the values $F[x][s]$ for $s > x$ do not satisfy the definition of $F[x][s]$ above. In other words, let's just suppose that the lats segment in structure $F[x]$ is infinite in right direction. Let's sweep with the variable $x$. The function $F[x + 1][ \\cdot ]$ changes in comparsion to $F[x][ \\cdot ]$ very rarely For example, the value $F[x + 1][x + 1]$ is almost always the same as $F[x][x + 1]$ (that is equal to $F[x][x]$ as said above). Indeed, if we suppose that there is no duck ending in $x + 1$ then $F[x][x] = min(F[x][0... x - r])$ and $F[x + 1][x + 1] = min(F[x + 1][0... x + 1 - r]) = min(F[x][0... x + 1 - r])  \\le  min(F[x][0... x - r])$. So, there is an interesting event only if value $F[x][x - r + 1]$ is smaller than the whole prefix before it. On the other hand, the value $min(F[x][0... x - r])$ can't increase more than $n$ times by $1$ (each time when we pass through the right end of the duck) and so, it also can't decrease more then $n$ times (since it is a non-negative value). So, the events \"we passed through the right end of the duck\" and \"we should non-trivially calculate $F[x][x]$\" are in total linear. Each of them can be processed in $O(1)$ operation with Cartesian tree, that gives as totally an $O(n\\log n)$ solution. Whooray!",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "542",
    "index": "C",
    "title": "Idempotent functions",
    "statement": "Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set ${1, 2, ..., n}$ is such function $g:\\{1,2,\\cdot\\cdot,n\\}\\to\\{1,2,\\cdot\\cdot,n\\}$, that for any $x\\in\\{1,2,\\cdot\\cdot,n\\}$ the formula $g(g(x)) = g(x)$ holds.\n\nLet's denote as $f^{(k)}(x)$ the function $f$ applied $k$ times to the value $x$. More formally, $f^{(1)}(x) = f(x)$, $f^{(k)}(x) = f(f^{(k - 1)}(x))$ for each $k > 1$.\n\nYou are given some function $f:\\{1,2,\\cdot\\cdot,n\\}\\to\\{1,2,\\cdot\\cdot,n\\}$. Your task is to find minimum positive integer $k$ such that function $f^{(k)}(x)$ is idempotent.",
    "tutorial": "In order to solve this task it's good to understand how does the graph corresponding the function from ${1, ..., n}$ to itself looks. Let's consider a graph on vertices $1, ..., n$ with edges from vertex $i$ to the vertex $f(i)$. Such graph always looks like a set of cycles with several trees leading to that cycles. How should the graph look like for function to be the idempotent? It's easy to see that in such graph all cycles should be of length $1$ and all vertex that are not cycles of length $1$ (i. e. all not fixed points) should immediatly lead to some fixed point. So, we should satisfy two conditions. First, all cycles should become of length $1$ - in order to do that $k$ should be divisible by $lcm(c_{1}, c_{2}, ..., c_{m})$ where $c_{i}$ are the lengths of all cycles. Second, all vertices not lying on cycles should become leading to the vertices lying on cycles. In other words, $k$ should be no less than the distance from any vertex $x$ to the cycle it goes into (or, that the same, the length of pre-period in the sequence $f(x), f(f(x)), f(f(f(x))), ...$). So, are task is about finding the smallest number $k$ divisible by $A$ that is no less than $B$, it is not hard at all.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "542",
    "index": "D",
    "title": "Superhero's Job",
    "statement": "It's tough to be a superhero. And it's twice as tough to resist the supervillain who is cool at math. Suppose that you're an ordinary Batman in an ordinary city of Gotham. Your enemy Joker mined the building of the city administration and you only have several minutes to neutralize the charge. To do that you should enter the cancel code on the bomb control panel.\n\nHowever, that mad man decided to give you a hint. This morning the mayor found a playing card under his pillow. There was a line written on the card:\n\n\\[\n\\begin{array}{c}{{J(x)=\\displaystyle}}\\\\ {{\\qquad\\sum_{k=k=x}\\sum_{k=1}\\sum_{k=1}}}\\\\ {{\\qquad\\operatorname*{gcd}(k,x/k)=1}}\\end{array}\n\\]\n\nThe bomb has a note saying \"$J(x) = A$\", where $A$ is some positive integer. You suspect that the cancel code is some integer $x$ that meets the equation $J(x) = A$. Now in order to decide whether you should neutralize the bomb or run for your life, you've got to count how many distinct positive integers $x$ meet this equation.",
    "tutorial": "First step is to understand the properties of a Joker function. It's important property is that it is multiplicative: $J(ab) = J(a)J(b)$ for $(a, b) = 1$, so we can write the value of function knowing the factorization of an argument: $J(p_{1}^{k1}p_{2}^{k2}... p_{m}^{km}) = J(p_{1}^{k1})J(p_{2}^{k2})... J(p_{m}^{km}) = (p_{1}^{k1} + 1)(p_{2}^{k2} + 1)... (p_{m}^{km} + 1)$. Let's use this knowledge in order to solve the task with dynamic programming. Let's denote as $P$ the set of prime $p$ such that the multiple including it may appear in $A = J(x)$. There are not that many such primes: each divisor $d$ of number $A$ can correspond no more than one such prime, namely, the one whose power the number $d - 1$ is (if it is a prime power at all). Let's calculate the set $P$ and also remember for each prime number $p$ in it in which powers $k$ the value $(p^{k} + 1)$ divides $A$. Now we can calculate value $D[p][d]$ that is equal to the number of ways to get a divisor $d$ of a number $A$ as a product of brackets of first $p$ primes in set $P$. Such value can be caluclated by using dynamic programming in time $O(\\tau(A)^{2})$ where ${\\boldsymbol{\\tau}}(A)$ is the number of divisors of $A$ (as it was shown above that $\\left|P\\right|=O(\\tau(A))$). So, overall complexity of the solution is $O({\\sqrt{A}}+\\tau(A)^{2})$.",
    "tags": [
      "dfs and similar",
      "dp",
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "542",
    "index": "E",
    "title": "Playing on Graph",
    "statement": "Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.\n\nVova has a non-directed graph consisting of $n$ vertices and $m$ edges without loops and multiple edges. Let's define the operation of contraction two vertices $a$ and $b$ that are \\textbf{not connected by an edge}. As a result of this operation vertices $a$ and $b$ are deleted and instead of them a new vertex $x$ is added into the graph, and also edges are drawn from it to all vertices that were connected with $a$ or with $b$ (specifically, if the vertex was connected with both $a$ and $b$, then also exactly one edge is added from $x$ to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains $(n - 1)$ vertices.\n\nVova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length $k$ ($k ≥ 0$) is a connected graph whose vertices can be numbered with integers from $1$ to $k + 1$ so that the edges of the graph connect all pairs of vertices $(i, i + 1)$ ($1 ≤ i ≤ k$) and only them. Specifically, the graph that consists of one vertex is a chain of length $0$. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction.\n\n\\begin{center}\n{\\small The picture illustrates the contraction of two vertices marked by red.}\n\\end{center}\n\nHelp Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.",
    "tutorial": "First, if the original graph isn't bipartite then the answer is (-1). Indeed, any odd cycle, while being contracted by the pair of vertices, always produces an odd cycle of smaller size, so at some point we will get a triangle that blocks us from doing anything. From the other way, each bipartite component can be contracted in order to get a chain whose length is a diameter of the component. Suppose that the pair of vertices $(a, b)$ is a diamater of some connected component. Then, by contracting all vertices located on the same distance from $a$ we can achieve the chain we want. The last step is that the answer fror the original graph is the sum of the answers for all the connected components since we can attach all of them together. So, the answer is the sum of diameters of all connected components if all of them are bipartite, otherwise answer is -1. Solution has the complexity $O(E + VE)$ (The first summand is checking for being bipartite, the second one is calculation diameters by running BFS from each vertex).",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "542",
    "index": "F",
    "title": "Quest",
    "statement": "Polycarp is making a quest for his friends. He has already made $n$ tasks, for each task the boy evaluated how interesting it is as an integer $q_{i}$, and the time $t_{i}$ in minutes needed to complete the task.\n\nAn interesting feature of his quest is: each participant should get the task that is best suited for him, depending on his preferences. The task is chosen based on an interactive quiz that consists of some questions. The player should answer these questions with \"yes\" or \"no\". Depending on the answer to the question, the participant either moves to another question or goes to one of the tasks that are in the quest. In other words, the quest is a binary tree, its nodes contain questions and its leaves contain tasks.\n\nWe know that answering any of the questions that are asked before getting a task takes exactly one minute from the quest player. Polycarp knows that his friends are busy people and they can't participate in the quest for more than $T$ minutes. Polycarp wants to choose some of the $n$ tasks he made, invent the corresponding set of questions for them and use them to form an interactive quiz as a binary tree so that no matter how the player answers quiz questions, he spends at most $T$ minutes on completing the whole quest (that is, answering all the questions and completing the task). Specifically, the quest can contain zero questions and go straight to the task. Each task can only be used once (i.e., the people who give different answers to questions should get different tasks).\n\nPolycarp wants the total \"interest\" value of the tasks involved in the quest to be as large as possible. Help him determine the maximum possible total interest value of the task considering that the quest should be completed in $T$ minutes at any variant of answering questions.",
    "tutorial": "This task can be solved in lot of ways. The most straightforward is DP. The task can be seen in the following way. We want some set of vertices as leaves and for each potential leaf we know the upper bound for its depth and its cost. Let's sweep over the tree from down to up. Let's calculate the value $D[h][c]$ that is the maximum possible cost that we can achieve if we stay on the level $h$ and have $c$ vertices on it. For transition let's fix how many leaves of the deepness exactly $h$ we will take (it's easy to see that among them we should task several greatest). Suppose we will take $k$ of them. Then from this state we can move to $D[h - 1][ \\lceil (c + k) / 2 \\rceil ]$. The answer will be located in $D[0][1]$ because when we are on the level $0$ we should have the only vertex that is the root of the tree. The complexity of such solution is $O(n^{2}T)$.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "543",
    "index": "A",
    "title": "Writing Code",
    "statement": "Programmers working on a large project have just received a task to write exactly $m$ lines of code. There are $n$ programmers working on a project, the $i$-th of them makes exactly $a_{i}$ bugs in every line of code that he writes.\n\nLet's call a sequence of non-negative integers $v_{1}, v_{2}, ..., v_{n}$ a plan, if $v_{1} + v_{2} + ... + v_{n} = m$. The programmers follow the plan like that: in the beginning the first programmer writes the first $v_{1}$ lines of the given task, then the second programmer writes $v_{2}$ more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most $b$ bugs in total.\n\nYour task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer $mod$.",
    "tutorial": "Let's create the solution, which will work too slow, but after that we will improve it. Let's calculate the following dynamic programming $z[i][j][k]$ - answer to the problem, if we already used exactly $i$ programmers, writed exactly $j$ lines of code, and there are exactly $k$ bugs. How we can do transitions in such dp? We can suppose that we $i$-th programmer will write $r$ lines of code, then we should add to $z[i][j][k]$ value $z[i - 1][j - r][k - ra[i]]$ But let's look at transitions from the other side. It's clear, that there are exactly 2 cases. The first case, we will give any task for $i$-th programmer. So, we should add to $z[i][j][k]$ value $z[i - 1][j][k]$. The second case, is to give at least one task to $i$-th programmer. So, this value will be included in that state: $z[i][j - 1][k - a[i]]$. In that solution we use same idea, which is used to calculate binomial coefficients using Pascal's triangle. So overall solution will have complexity: $O(n^{3})$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n \nconst int N = 505;\nint a[N];\nint z[2][N][N];\n \nint main() {\n  int n, bl, bugs, md;\n  scanf(\"%d %d %d %d\", &n, &bl, &bugs, &md);\n  forn(i, n) scanf(\"%d\", &a[i]);\n  z[0][0][0] = 1;\n \n  for(int it = 1; it <= n; it++){\n    int i = it & 1;\n    for(int j = 0; j <= bl; j++) {\n      for(int k = 0; k <= bugs; k++) {\n        z[i][j][k] = z[i ^ 1][j][k];\n        if (j > 0 && k >= a[it - 1])\n          z[i][j][k] += z[i][j - 1][k - a[it - 1]];\n        while (z[i][j][k] >= md) z[i][j][k] -= md;\n      }\n    }\n  }\n \n  int ans = 0;\n  for(int i = 0; i <= bugs; i++) {\n    ans += z[n & 1][bl][i];\n    while (ans >= md) ans -= md;\n  }\n  printf(\"%d\\n\", ans);\n}",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "543",
    "index": "B",
    "title": "Destroying Roads",
    "statement": "In some country there are exactly $n$ cities and $m$ bidirectional roads connecting the cities. Cities are numbered with integers from $1$ to $n$. If cities $a$ and $b$ are connected by a road, then in an hour you can go along this road either from city $a$ to city $b$, or from city $b$ to city $a$. The road network is such that from any city you can get to any other one by moving along the roads.\n\nYou want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city $s_{1}$ to city $t_{1}$ in at most $l_{1}$ hours and get from city $s_{2}$ to city $t_{2}$ in at most $l_{2}$ hours.\n\nDetermine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.",
    "tutorial": "Let's solve easiest task. We have only one pair of vertices, and we need to calculate smallest amout of edges, such that there is a path from first of vertex to the second. It's clear, that the answer for that problem equals to shortest distance from first vertex to the second. Let's come back to initial task. Let's $d[i][j]$ - shortest distance between $i$ and $j$. You can calculate such matrix using bfs from each vertex. Now we need to handle two cases: Paths doesn't intersects. In such way we can update the answer with the following value: $m - d[s_{0}][t_{0}] - d[s_{1}][t_{1}]$ (just in case wheh conditions on the paths lengths fullfills). Otherwise paths are intersecting, and the correct answer looks like a letter 'H'. More formally, at the start two paths will consists wiht different edges, after that paths will consists with same edges, and will finish with different edges. Let's iterate over pairs $(i, j)$ - the start and the finish vertices of the same part of paths. Then we can update answer with the following value: $m - d[s_{0}][i] - d[i][j] - d[j][t_{0}] - d[s_{1}][i] - d[j][t_{1}]$ (just in case wheh conditions on the paths lengths fullfills). Please note, that we need to swap vertices $s_{0}$ and $t_{0}$, and recheck the second case, because in some situations it's better to connect vertex $t_{0}$ with vertex $i$ and $s_{0}$ with vertex $j$. Solutions, which didn't handle that case failed system test on testcase 11.",
    "code": "#include <cstdio>\n#include <queue>\n#include <vector>\n#include <cstring>\n \nusing namespace std;\n \nconst int N = 5005;\nint d[N][N];\nvector < int > g[N];\n \nint main() {\n  memset(d, -1, sizeof d);\n  int n, m;\n  scanf(\"%d %d\", &n, &m);\n \n  for(int i = 0; i < m; i++) {\n    int a, b;\n    scanf(\"%d %d\", &a, &b);\n    a--, b--;\n \n    g[a].push_back(b);\n    g[b].push_back(a);\n  }\n \n  for(int i = 0; i < n; i++) {\n    queue < int > q;\n    q.push(i);\n    d[i][i] = 0;\n    while (!q.empty()) {\n      int s = q.front();\n      q.pop();\n \n      for(int j = 0; j < int(g[s].size()); j++) {\n        int to =  g[s][j];\n        if (d[i][to] == -1) {\n          d[i][to] = d[i][s] + 1;\n          q.push(to);\n        }\n      }\n    }\n  }\n  int s[2], t[2], l[2];\n  scanf(\"%d %d %d\", &s[0], &t[0], &l[0]);\n  scanf(\"%d %d %d\", &s[1], &t[1], &l[1]);\n  s[0]--, t[0]--, s[1]--, t[1]--;\n \n  int ans = m + 1;\n  for(int iter = 0; iter < 2; iter++){\n    swap(s[0], t[0]);\n    for(int i = 0; i < n; i++) {\n      for(int j = 0; j < n; j++) {\n        int v[] = {d[s[0]][i] + d[i][j] + d[j][t[0]], d[s[1]][i] + d[i][j] + d[j][t[1]]};\n        if (v[0] <= l[0] && v[1] <= l[1]) {\n          ans = min(ans, v[0] + v[1] - d[i][j]);\n        }\n      }\n    }\n  }\n \n  if (d[s[0]][t[0]] <= l[0] && d[s[1]][t[1]] <= l[1]) {\n    ans = min(ans, d[s[0]][t[0]] + d[s[1]][t[1]]); \n  }\n \n  if (ans > m) {\n    ans = -1;\n  } else {\n    ans = m - ans;\n  }\n \n  printf(\"%d\\n\", ans);\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "543",
    "index": "C",
    "title": "Remembering Strings",
    "statement": "You have multiset of $n$ strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position $i$ and some letter $c$ of the English alphabet, such that this string is the only string in the multiset that has letter $c$ in position $i$.\n\nFor example, a multiset of strings {\"abc\", \"aba\", \"adc\", \"ada\"} are not easy to remember. And multiset {\"abc\", \"ada\", \"ssa\"} is easy to remember because:\n\n- the first string is the only string that has character $c$ in position $3$;\n- the second string is the only string that has character $d$ in position $2$;\n- the third string is the only string that has character $s$ in position $2$.\n\nYou want to change your multiset a little so that it is easy to remember. For $a_{ij}$ coins, you can change character in the $j$-th position of the $i$-th string into any other lowercase letter of the English alphabet. Find what is the minimum sum you should pay in order to make the multiset of strings easy to remember.",
    "tutorial": "First that we need to notice, that is amout of strings is smaller then alphabet size. It means, that we can always change some character to another, because at least one character is not used by some string. After that we need handle two cases: We can change exactly one character to another. The cost of such operation equals to $a[i][j]$ (which depends on chosed column) After that we can remember string very easy. We can choose some column, and choose some set of strings, that have same character in that column, By one move we can make all these strings are easy to remember.The cost of such move equals to cost of all characters, except most expensive. As the result, we will have following solution: d[mask] - answer to the problem, when we make all strings from set $mask$ easy to remember. We can calculate this dp in following way: let $lowbit$ - smallest element of set $mask$. It's clear, that we can do this string easy to remember using first or second move. So we need just iterate over possible columns, and try first or second move (in second move we should choose set that contain string $lowbit$) Overall complexity is $O(m2^{n})$, where $m$ - is length of strings.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nconst int N = 20;\nconst int leng = 300;\nstring s[N];\nint cost[N][leng], c[N][leng], sv[N][leng], a[N][leng];\nint d[1 << N];\n \nint main() {\n  int n, m;\n  cin >> n >> m;\n  forn(i, n) cin >> s[i];\n  forn(i, n) forn(j, m) cin >> a[i][j];\n  \n  forn(i, n) {\n    forn(j, m) {\n      int curv = 0;\n      forn(k, n) {\n        if (s[i][j] == s[k][j]) {\n          sv[i][j] |= (1 << k);\n          c[i][j] += a[k][j];\n          curv = max(curv, a[k][j]);\n        }\n      }\n      c[i][j] -= curv;\n    }\n  }\n  forn(i, 1 << n) d[i] = 1000000000;\n  d[0] = 0;\n  forn(mask, 1 << n) {\n    if (mask == 0) continue;\n    int lowbit = -1;\n    forn(i, n) {\n      if ((mask >> i) & 1) {\n        lowbit = i;\n        break;\n      }\n    }\n    forn(i, m) {\n      d[mask] = min(d[mask], d[mask & (mask ^ sv[lowbit][i])] + c[lowbit][i]);\n      d[mask] = min(d[mask], d[mask ^ (1 << lowbit)] + a[lowbit][i]);\n    }\n  }\n  printf(\"%d\\n\", d[(1 << n) - 1]);\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "543",
    "index": "D",
    "title": "Road Improvement",
    "statement": "The country has $n$ cities and $n - 1$ bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from $1$ to $n$ inclusive.\n\nAll the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city $x$ to any other city contains at most one bad road.\n\nYour task is — for every possible $x$ determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo $1 000 000 007$ ($10^{9} + 7$).",
    "tutorial": "Let's suppose $i$ is a root of tree. Let's calculate extra dynamic programming $d[i]$ - answer to the problem for sub-tree with root $i$ We can understand, that d[i] equals to the following value: $d[i]=\\prod_{i}(d[j]+1)$ - where $j$ is a child of the vertex $i$. It's nice. After that answer to problem for first vertex equal to $d[1]$. After that let's study how to make child $j$ of current root $i$ as new root of tree. We need to recalculate only two values $d[i]$ and $d[j]$. First value we can recalculate using following formula $d[i]$: $suf[i][j] * pref[i][j] * d[parent]$, where $parent$ - is the parent of vertex $i$, (for vertex $1$ $d[parent] = 1$), and array $suf[i][j]$ - is the product of values $d[k]$, for all childs of vertex $i$ and $k < j$ ($pref[i][j]$ have same definition, but $k > j$). And after we can calculate $d[j]$ as $d[j] * (d[i] + 1)$. That is all, $j$ is root now, and answer to vertex $j$ equals to current value $d[j]$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define ford(i, n) for(int i = int(n) - 1; i >= 0; i--)\n#define sz(a) int((a).size())\n \nconst int N = 200000 + 300;\nconst int md = 1000000007;\n \nvector < int > g[N], pref[N], suf[N];\nint ans[N], d[N];\n \nvoid dfs(int s){\n  d[s] = 1;\n  forn(i, sz(g[s])) {\n    int to = g[s][i];\n    dfs(to);\n    d[s] = d[s] * 1ll * (d[to] + 1) % md;\n  }\n  int curp = 1, curs = 1;\n  forn(i, sz(g[s])) {\n    int to = g[s][i], rto = g[s][sz(g[s]) - i - 1];\n    pref[s].push_back(curp);\n    suf[s].push_back(curs);\n    curp = curp * 1ll * (d[to] + 1) % md;\n    curs = curs * 1ll * (d[rto] + 1) % md;\n  }\n  reverse(suf[s].begin(), suf[s].end());\n}\n \nvoid tdfs(int s, int par = -1) {\n  ans[s] = d[s];\n  forn(i, sz(g[s])) {\n    int to = g[s][i], olds = d[s], oldto = d[to];\n    d[s] = pref[s][i] * 1ll * suf[s][i] % md;\n    if (par != -1) d[s] = d[s] * 1ll * (d[par] + 1) % md;\n    d[to] = d[to] * 1ll * (d[s] + 1) % md;\n    tdfs(to, s);\n    d[s] = olds;\n    d[to] = oldto;\n  }\n}\n \nint main() {\n#ifdef gridnevvvit\n  freopen(\"input.txt\", \"rt\", stdin);\n#endif\n  int n;\n  scanf(\"%d\", &n);\n \n  for(int i = 0; i < n - 1; i++) {\n    int par;\n    scanf(\"%d\", &par);\n    g[par - 1].push_back(i + 1);\n  }\n \n  dfs(0);\n  tdfs(0);\n \n  forn(i, n) {\n    if (i > 0) printf(\" \");\n    printf(\"%d\", ans[i]);\n  }\n}",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "543",
    "index": "E",
    "title": "Listening to Music",
    "statement": "Please note that the memory limit differs from the standard.\n\nYou really love to listen to music. During the each of next $s$ days you will listen to exactly $m$ songs from the playlist that consists of exactly $n$ songs. Let's number the songs from the playlist with numbers from $1$ to $n$, inclusive. The quality of song number $i$ is $a_{i}$.\n\nOn the $i$-th day you choose some integer $v$ ($l_{i} ≤ v ≤ r_{i}$) and listen to songs number $v, v + 1, ..., v + m - 1$. On the $i$-th day listening to one song with quality less than $q_{i}$ increases your displeasure by exactly one.\n\nDetermine what minimum displeasure you can get on each of the $s$ next days.",
    "tutorial": "Let's sort all songs in decreasing order. We will iterate over songs, and each time we will say, that now current song will fully satisfy our conditions. So, let's $s_{i} = 0$, is song $i$ was not processed yet and $s_{i} = 1$ otherwise. Let $v_{i}=\\sum_{i=i}^{j=i+m-1}s_{j}$. It's clear, when we add new song in position $idx$ then we should do $+ 1$ for all on segment $[max(0, idx - m + 1), idx]$ in our array $v$. So, when we need to implement some data structure, which can restore our array $v$ to the position when all strings have quality $ \\ge  q$. It also should use very small amout of memory. So, answer to the query will be $m - max(v_{i})$, $l_{j}  \\le  i  \\le  r_{j}$. We will store this data structure in the following way. Let's beat all positions of songs in blocks of length $\\sqrt{n}$. Each time, when we added about $\\sqrt{n}$ songs as good, we will store three arrays: first array will contain value $v_{i}$ of first element of the block of indices. second array will contain maximum value of $v$ on each block and also we will keep about $2{\\sqrt{n}}$ of ''small'' updates which doesn't cover full block. Using this information array $v$ will be restored and we process current query in easy way.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define sz(a) int((a).size())\n#define all(a) (a).begin(),(a).end()\n#define pb push_back\n#define mp make_pair\n#define sc second\n#define ft first\n \nusing namespace std;\n \nconst int M = 512;\nconst int N = M * M;\nint blvalue[M][M];\nint ftvalue[M][M];\nint exvalue[M][2 * M];\nint a[N];\npair<int, int> na[N];\nint va[N];\nint push[M];\nint bl[M];\nint n, m;\nint blcount;\nconst int mult = 9;\nconst int blsz = (1 << mult);\n \ninline bool is_first(int idx) {\n  return (idx & (blsz - 1)) == 0;\n}\n \ninline int bl_idx(int idx) {\n  if (idx >= n) {\n    return (idx >> mult) + 1;\n  }\n  return idx >> mult;\n}\n \ninline int first_idx(int blid) {\n  return blid << mult;\n}\n \ninline int last_idx(int blid) {\n  return min(n - 1, first_idx(blid) + blsz - 1);  \n}\n \nconst int INF = 1000 * 1000 * 1000;\n \nint main() \n{\n#ifdef gridnevvvit\n  freopen(\"input.txt\", \"rt\", stdin);\n#endif\n  scanf(\"%d %d\", &n, &m);\n  blcount = (n + blsz - 1) / blsz;\n  forn(i, n) scanf(\"%d\", &a[i]);\n  forn(i, n)\n    na[i] = mp(-a[i], i);\n  sort(na, na + n);\n \n  forn(iter, n) {\n    if (is_first(iter)){\n      int curbl = bl_idx(iter);\n      forn(i, n)\n        va[i] = va[i] + push[bl_idx(i)];\n      forn(i, blcount) {\n        bl[i] += push[i];\n        blvalue[curbl][i] = bl[i];\n        ftvalue[curbl][i] = va[first_idx(i)]; \n        push[i] = 0;\n      }\n    }\n    int r = na[iter].sc; \n    int l = max(0, r - m + 1);\n    int blocks[] = {blcount, blcount};\n    int szb = 0;\n    for(int i = l; i <= r; ) {\n      int curbl = bl_idx(i);\n      if (is_first(i) && last_idx(curbl) <= r) {\n        push[curbl] ++;\n        i = last_idx(curbl) + 1;\n      } else {\n        va[i]++;\n        bl[curbl] = max(bl[curbl], va[i]);\n        if (szb == 0 || blocks[szb - 1] != curbl) {\n          blocks[szb++] = curbl;\n        }\n        i++;\n      }\n    }\n    szb = 2;\n    int curbl = bl_idx(iter);\n    int idx = iter - first_idx(curbl);\n    forn(i, szb) {\n      exvalue[curbl][2 * idx + i] = (bl[blocks[i]] << mult) + blocks[i];\n    }\n  }\n  int query;\n  scanf(\"%d\", &query);\n  int last_ans = 0;\n  forn(it, query) {\n    int l, r, q;\n    scanf(\"%d %d %d\", &l, &r, &q); l--, r--;\n    q ^= last_ans;\n    int idx = upper_bound(na, na + n, mp(-q, INF)) - na;\n    idx--;\n    if (idx < 0) {\n      printf(\"%d\\n\", m);\n      last_ans = m;\n      continue;\n    }\n    int curbl = bl_idx(idx);\n    forn(i, blcount) {\n      bl[i] = blvalue[curbl][i];\n      push[i] = 0;\n    }\n    int ft = first_idx(curbl);   \n    for(int i = ft; i <= idx; i++) {\n      int nr = na[i].sc;\n      int nl = max(0, nr - m + 1);\n      if (nl != first_idx(bl_idx(nl))) {\n        nl = last_idx(bl_idx(nl)) + 1;\n      }\n      if (nr == last_idx(bl_idx(nr))){\n        nr++;\n      }\n      if (bl_idx(nl) <= bl_idx(nr)) {\n        push[bl_idx(nl)] ++;\n        push[bl_idx(nr)] --;\n      }\n      forn(j, 2) {\n        int blid = exvalue[curbl][2 * (i - ft) + j];\n        int vt = blid >> mult;\n        blid &= (blsz - 1);\n        bl[blid] = vt;\n      }\n    }\n    forn(i, blcount) {\n      if (i > 0) push[i] += push[i - 1];\n    }\n    int maxAns = 0;\n    int pv = -1;\n    for(int i = l; i <= r; ) {\n       int blid = bl_idx(i);\n       if (is_first(i) && last_idx(blid) <= r) {\n         maxAns = max(maxAns, bl[blid] + push[blid]);\n         i = last_idx(blid) + 1;\n         pv = -1;\n       } else {\n         if (pv == -1) {\n            pv = ftvalue[curbl][blid];\n            int ftp = first_idx(blid);\n            for(int j = ft; j <= idx; j++) {\n              if (ftp <= na[j].sc && ftp >= max(na[j].sc - m + 1, 0)) {\n                pv++;\n              }\n            }\n            while (ftp != i) {\n              pv -= (a[ftp] >= q);\n              pv += (a[ftp + m] >= q);\n              ftp++;\n            }\n         }\n         maxAns = max(maxAns, pv);\n         pv -= (a[i] >= q);\n         pv += (a[i + m] >= q);\n         i++;\n      }\n    }\n    maxAns = m - maxAns;\n    printf(\"%d\\n\", maxAns);\n    last_ans = maxAns;\n  }\n}",
    "tags": [
      "constructive algorithms",
      "data structures"
    ],
    "rating": 3200
  },
  {
    "contest_id": "544",
    "index": "A",
    "title": "Set of Strings",
    "statement": "You are given a string $q$. A sequence of $k$ strings $s_{1}, s_{2}, ..., s_{k}$ is called beautiful, if the concatenation of these strings is string $q$ (formally, $s_{1} + s_{2} + ... + s_{k} = q$) and the first characters of these strings are distinct.\n\nFind any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.",
    "tutorial": "In that task you need to implement what was written in the statements. Let's iterate over all characters of string and keep array $used$. Also let's keep current string. If current character was not used previously, then let's put current string to the answer and after that we need to clear current string. Otherwise, let's append current character to the current string. If array, that contain answer will have more then $k$ elements, we will concatenate few last strings.",
    "code": "k = input()\ns = raw_input()\nans = []\ncur = \"\"\nused = set()\nfor i in range(len(s)):\n\tif s[i] not in used:\n\t\tif len(cur) > 0:\n\t\t\tans.append(cur)\n \t\tcur = \"\"\n\t\tcur += s[i]\n\t\tused.add(s[i])\n\telse:\n\t\tcur += s[i]\nans.append(cur)\nif len(ans) < k:\n\tprint(\"NO\")\nelse:\n\tprint(\"YES\")\n\tfor i in range(k, len(ans)):\n\t\tans[k - 1] += ans[i]\n\tfor i in range(k):\n\t\tprint(ans[i])",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "544",
    "index": "B",
    "title": "Sea and Islands",
    "statement": "A map of some object is a rectangular field consisting of $n$ rows and $n$ columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly $k$ islands appear on the map. We will call a set of sand cells to be \\textbf{island} if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).\n\nFind a way to cover some cells with sand so that exactly $k$ islands appear on the $n × n$ map, or determine that no such way exists.",
    "tutorial": "It's clear to understand, that optimal answer will consists of simple cells, for which following condition fullfills: the sum of indices of row and column is even. We will try to put $k$ islands in such way, and if it's impossible, we will report that answer is NO. Try to prove that this solution is optimal.",
    "code": "#include <cstdio>\n#include <string>\n#include <vector>\n \nusing namespace std;\nint main() {\n  int n, k;\n  scanf(\"%d %d\", &n, &k);\n  if (n == 5 && k == 2) {\n    puts(\"YES\");\n    for(int i = 0; i < n; i++) {\n      for(int j = 0; j < n; j++) {\n        if (i & 1) printf(\"L\");\n        else printf(\"S\");\n      }\n      puts(\"\");\n    }\n    return 0;\n  }\n  vector < string > ans(n, \"\");\n  for(int i = 0; i < n; i++){\n    for(int j = 0; j < n; j++) {\n      int sum = (i + j) & 1;\n      if (sum == 0 && k > 0) {\n        ans[i] += \"L\";\n        k --;\n      } else {\n        ans[i] += \"S\";\n      }\n    }\n  }\n  if (k == 0) {\n    puts(\"YES\");\n    for(int i = 0; i < n; i++)\n      puts(ans[i].c_str());\n  } else {\n    puts(\"NO\");\n  }\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "545",
    "index": "A",
    "title": "Toy Cars",
    "statement": "Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.\n\nThere are $n$ toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an $n × n$ matrix $А$: there is a number on the intersection of the $і$-th row and $j$-th column that describes the result of the collision of the $і$-th and the $j$-th car:\n\n- $ - 1$: if this pair of cars never collided. $ - 1$ occurs only on the main diagonal of the matrix.\n- $0$: if no car turned over during the collision.\n- $1$: if only the $i$-th car turned over during the collision.\n- $2$: if only the $j$-th car turned over during the collision.\n- $3$: if both cars turned over during the collision.\n\nSusie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?",
    "tutorial": "We can find all information about $i$-th car collisions in the $i$-th row of the matrix $A$. More specific, if there is at least one 1 or 3 at $i$-th row, then $i$-th car isn't good (it was turned over in at least one collision). Otherwise, $i$-th car is good. We just need to check this condition for each car.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "545",
    "index": "B",
    "title": "Equidistant String",
    "statement": "Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:\n\nWe will define the distance between two strings $s$ and $t$ of the same length consisting of digits zero and one as the number of positions $i$, such that $s_{i}$ isn't equal to $t_{i}$.\n\nAs besides everything else Susie loves symmetry, she wants to find for two strings $s$ and $t$ of length $n$ such string $p$ of length $n$, that the distance from $p$ to $s$ was equal to the distance from $p$ to $t$.\n\nIt's time for Susie to go to bed, help her find such string $p$ or state that it is impossible.",
    "tutorial": "One can see, that if $s_{i} = t_{i}$ for some $i$, then the value of $p_{i}$ isn't important for us. Really, if we make $p_{i}$ equal to $s_{i}$ then it also be equal to $t_{i}$. And if we make $p_{i}$ not equal to $s_{i}$ then it also be not equal to $t_{i}$. So, we have an answer that is closer or further to both of s and t. So we interested about such position $i$ that $s_{i}  \\neq  t_{i}$. If we make $p_{i}$ equal to $s_{i}$ we make $p$ further from $t$. If we make $p_{i}$ equal to $t_{i}$ we make $p$ further from $s$. It means that we need to divide these positions into two equal parts to have equidistant string. For example, we can make first of these positions closer to $s$, second closer to $t$ and so on. If the number of these positions is even, we find an answer, if it is odd, answer doesn't exist. Time complexity - $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "545",
    "index": "C",
    "title": "Woodcutters",
    "statement": "Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.\n\nThere are $n$ trees located along the road at points with coordinates $x_{1}, x_{2}, ..., x_{n}$. Each tree has its height $h_{i}$. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments $[x_{i} - h_{i}, x_{i}]$ or $[x_{i};x_{i} + h_{i}]$. The tree that is not cut down occupies a single point with coordinate $x_{i}$. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.",
    "tutorial": "One can solve this problem using dynamic programming or greedy algorithm. Start with DP solution. Define $stay_{i}$, $left_{i}$ and $right_{i}$ as maximal count of trees that woodcutters can fell, if only trees with number from $1$ to $i$ exist, and $i$-th tree isn't cutted down, $i$-th tree is cutted down and fallen left, $i$-th tree is cutted down and fallen right correspondingly. Now we can compute this values for each $i$ from $1$ to $n$ by $O(n)$ time because for each next we need only two previous value. Answer is maximum of $stay_{n}$, $left_{n}$, $right_{n}$. Also this problem can be solved by the next greedy algoritm. Let's fell leftmost tree to the left (it always doesn't make an answer worse). After that, try to fell the next tree. If we can fell it to the left, let's do it (because it also always doesn't make an answer worse). If we can't, then try to fell it to the right. If it is possible, let's do it. Last step is correct because felling some tree to the right may only prevent the next tree's fallen. So we may \"exchange\" one tree to another without worsing an answer. Time complexity - $O(n)$.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "545",
    "index": "D",
    "title": "Queue",
    "statement": "Little girl Susie went shopping with her mom and she wondered how to improve service quality.\n\nThere are $n$ people in the queue. For each person we know time $t_{i}$ needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.\n\nHelp Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.",
    "tutorial": "We can solve this problem by greedy algorithm. Let's prove that it is always possible find an answer (queue with the maximal number of not disappointed people), where all not disappointed people are at the begin of queue. Assume the contrary - there are two position $i$ and $j$ such that $i < j$, persons at position from $i$ to $j - 1$ are disappointed, but $j$-th person isn't. Then just swap persons at positions $i$ and $j$. After that all persons from $i$ to $j - 1$ will be still disappointed (or become not disappointed) and $j$-th person will be still not disappointed. So the answer isn't maked worse. So, we need to find person with minimal $t_{i}$, that can be served now and will be not disappointed. We can do that by sorting all the people by time $t_{i}$ and try to serve them one by one. If somebody will be disappointed, we may send he to the end of queue, and doesn't add his serve time to the waiting time. Time complexity - $O(n + sort)$.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "545",
    "index": "E",
    "title": "Paths and Trees",
    "statement": "Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.\n\nLet's assume that we are given a \\textbf{connected} weighted undirected graph $G = (V, E)$ (here $V$ is the set of vertices, $E$ is the set of edges). The shortest-path tree from vertex $u$ is such graph $G_{1} = (V, E_{1})$ that is a tree with the set of edges $E_{1}$ that is the subset of the set of edges of the initial graph $E$, and the lengths of the shortest paths from $u$ to any vertex to $G$ and to $G_{1}$ are the same.\n\nYou are given a \\textbf{connected} weighted undirected graph $G$ and vertex $u$. Your task is to find the shortest-path tree of the given graph from vertex $u$, the total weight of whose edges is minimum possible.",
    "tutorial": "It's true, that Dijkstra modification, where in case of equal distances we take one with shorter last edge, find an answer. For prove that let's do some transformation with graph. At first, find all shortest paths from $u$ to other vertices. Define $d_{i}$ as the length of shortest path from $u$ to $i$. After that, we can delete some edges. Specifically, we can delete an edge with ends in $x$ and $y$ and weight $w$ if $|d_{x} - d_{y}|  \\neq  w$, because it isn't contained in any shortest path, so it isn't contained in shortest path tree. After that, we can direct all edges from vertices with less distance to vertices with greater distance (because of all weight are positive). It's easy to prove, that if we take one edge that entering each vertex, we have a shortest path tree. Then we only need to take for each vertex minimal egde, that entering this vertex. Why? Because we have to take at least one edge, that entering each vertex to make a graph connected. We can't take edges with less weights than minimal. And if we take minimal edges, that entering each vertex we will have an shortest path tree. So that is minimal possible total wieght of shortest path tree. You can see, that Dijkstra with modification do exactly the same things. Time complexity - $O(m\\log n)$",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "546",
    "index": "A",
    "title": "Soldier and Bananas",
    "statement": "A soldier wants to buy $w$ bananas in the shop. He has to pay $k$ dollars for the first banana, $2k$ dollars for the second one and so on (in other words, he has to pay $i·k$ dollars for the $i$-th banana).\n\nHe has $n$ dollars. How many dollars does he have to borrow from his friend soldier to buy $w$ bananas?",
    "tutorial": "We can easily calculate the sum of money that we need to buy all the bananas that we want, let's name it x. If n > = x the answer is 0, because we don't need to borrow anything. Otherwise the answer is x - n.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "546",
    "index": "B",
    "title": "Soldier and Badges",
    "statement": "Colonel has $n$ badges. He wants to give one badge to every of his $n$ soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.\n\nFor every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors.\n\nColonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.",
    "tutorial": "Let's count the number of badges with coolness factor 1, 2 and so on. Then, let's look at the number of badges with value equal to 1. If it's greater than 1, we have to increase a value of every of them except for one. Then, we look at number of badges with value 2, 3 and so on up to 2n - 2 (because maximum value of badge which we can achieve is 2n - 1). It is easy to see that this is the correct solution. We can implement it in O(n), but solutions that work in complexity O(n^2) also passed.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "546",
    "index": "C",
    "title": "Soldier and Cards",
    "statement": "Two bored soldiers are playing card war. Their card deck consists of exactly $n$ cards, numbered from $1$ to $n$, \\textbf{all values are different}. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a \"war\"-like card game.\n\nThe rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins this fight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins.\n\nYou have to calculate how many fights will happen and who will win the game, or state that game won't end.",
    "tutorial": "It's easy to count who wins and after how many \"fights\", but it's harder to say, that game won't end. How to do it? Firstly let's count a number of different states that we can have in the game. Cards can be arranged in any one of n! ways. In every of this combination, we must separate first soldier's cards from the second one's. We can separate it in n + 1 places (because we can count the before and after deck case too). So war has (n + 1)! states. If we'd do (n + 1)! \"fights\" and we have not finished the game yes, then we'll be sure that there is a state, that we passed at least twice. That means that we have a cycle, and game won't end. After checking this game more accurately I can say that the longest path in the state-graph for n = 10 has length 106, so it is enough to do 106 fights, but solutions that did about 40 millions also passed. Alternative solution is to map states that we already passed. If we know, that we longest time needed to return to state is about 100, then we know that this solution is correct and fast.",
    "tags": [
      "brute force",
      "dfs and similar",
      "games"
    ],
    "rating": 1400
  },
  {
    "contest_id": "546",
    "index": "D",
    "title": "Soldier and Number Game",
    "statement": "Two soldiers are playing a game. At the beginning first of them chooses a positive integer $n$ and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer $x > 1$, such that $n$ is divisible by $x$ and replacing $n$ with $n / x$. When $n$ becomes equal to $1$ and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.\n\nTo make the game more interesting, first soldier chooses $n$ of form $a! / b!$ for some positive integer $a$ and $b$ ($a ≥ b$). Here by $k!$ we denote the factorial of $k$ that is defined as a product of all positive integers not large than $k$.\n\nWhat is the maximum possible score of the second soldier?",
    "tutorial": "Firstly we have to note, that second soldier should choose only prime numbers. If he choose a composite number x that is equal to p * q, he can choose first p, then q and get better score. So our task is to find a number of prime factors in factorization of n. Now we have to note that factorization of number a! / b! is this same as factorization of numbers (b + 1)*(b + 2)*...*(a - 1)*a. Let's count number of prime factor in factorization of every number from 2 to 5000000. First, we use Sieve of Eratosthenes to find a prime diviser of each of these numbers. Then we can calculate a number of prime factors in factorization of a using the formula: primefactors[a] = primefactors[a / primediviser[a]] + 1 When we know all these numbers, we can use a prefix sums, and then answer for sum on interval.",
    "tags": [
      "constructive algorithms",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "546",
    "index": "E",
    "title": "Soldier and Traveling",
    "statement": "In the country there are $n$ cities and $m$ bidirectional roads between them. Each city has an army. Army of the $i$-th city consists of $a_{i}$ soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at \\textbf{moving along at most one road}.\n\nCheck if is it possible that after roaming there will be exactly $b_{i}$ soldiers in the $i$-th city.",
    "tutorial": "There are few ways to solve this task, but I'll describe the simplest (in my opinion) one. Let's build a flow network in following way: Make a source. Make a first group of vertices consisting of n vertices, each of them for one city. Connect a source with ith vertex in first group with edge that has capacity ai. Make a sink and second group of vertices in the same way, but use bi except for ai. If there is a road between cities i and j or i = j. Make two edges, first should be connecting ith vertex from first group, and jth vertex from second group, and has infinity capacity. Second should be similar, but connect jth from first group and ith from second group. Then find a maxflow, in any complexity. If maxflow is equal to sum of ai and is equal to sum of bi, then there exists an answer. How can we get it? We just have to check how many units are we pushing through edge connecting two vertices from different groups. I told about many solutions, because every solution, which doesn't use greedy strategy, can undo it's previous pushes, and does it in reasonable complexity should pass.",
    "tags": [
      "flows",
      "graphs",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "547",
    "index": "A",
    "title": "Mike and Frog",
    "statement": "Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time $0$), height of Xaniar is $h_{1}$ and height of Abol is $h_{2}$. Each second, Mike waters Abol and Xaniar.\n\nSo, if height of Xaniar is $h_{1}$ and height of Abol is $h_{2}$, after one second height of Xaniar will become $(x_{1}h_{1}+y_{1})\\bmod m$ and height of Abol will become $(x_{2}h_{2}+y_{2})\\bmod m$ where $x_{1}, y_{1}, x_{2}$ and $y_{2}$ are some integer numbers and $a\\,\\mathrm{mod}\\,b$ denotes the remainder of $a$ modulo $b$.\n\nMike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is $a_{1}$ and height of Abol is $a_{2}$.\n\nMike has asked you for your help. Calculate the minimum time or say it will never happen.",
    "tutorial": "In this editorial, consider $p = m$, $a = h_{1}$, $a' = a_{1}$, $b = h_{2}$ and $b' = a_{2}$, $x = x_{1}$, $y = y_{1}$, $X = x_{2}$ and $Y = y_{2}$. First of all, find the number of seconds it takes until height of Xaniar becomes $a'$ (starting from $a$) and call it $q$. Please note that $q  \\le  p$ and if we don't reach $a'$ after $p$ seconds, then answer is $- 1$. If after $q$ seconds also height of Abol will become equal to $b'$ then answer if $q$. Otherwise, find the height of Abdol after $q$ seconds and call it $e$. Then find the number of seconds it takes until height of Xaniar becomes $a'$ (starting from $a'$) and call it $c$. Please note that $c  \\le  p$ and if we don't reach $a'$ after $p$ seconds, then answer is $- 1$. if $g(x) = Xx + Y$, then find $f(x) = g(g(...(g(x))))$ ($c$ times). It is really easy: Then, Actually, if height of Abol is $x$ then, after $c$ seconds it will be $f(x)$. Then, starting from $e$, find the minimum number of steps of performing e = f(e) it takes to reach $b'$ and call it $o$. Please note that $o  \\le  p$ and if we don't reach $b'$ after $p$ seconds, then answer is $- 1$. Then answer is $x + c  \\times  o$. Time Complexity: ${\\cal O}(p)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nint a[2], b[2], x[3], y[3], p;\ninline int nex(int c, int w){\n\treturn (1LL * c * x[w] + y[w])%p;\n}\nint main(){\n\tiOS;\n\tcin >> p;\n\tFor(i,0,2){\n\t\tif(!i)\n\t\t\tcin >> a[0] >> a[1];\n\t\telse\n\t\t\tcin >> b[0] >> b[1];\n\t\tcin >> x[i] >> y[i];\n\t}\n\tll ans = 0LL;\n\twhile(a[0] != a[1] && ans < p + 20){\n\t\t++ ans;\n\t\ta[0] = nex(a[0], 0);\n\t\tb[0] = nex(b[0], 1);\n\t}\n\tif(a[0] != a[1]){\n\t\tcout << -1 << endl;\n\t\treturn 0;\n\t}\n\tif(a[0] == a[1] && b[0] == b[1]){\n\t\tcout << ans << endl;\n\t\treturn 0;\n\t}\n\tint o = 0;\n\tint cur = a[0];\n\tx[2] = x[1], y[2] = y[1];\n\tx[1] = 1, y[1] = 0;\n\tdo{\n\t\tcur = nex(cur, 0);\n\t\t++ o;\n\t\tx[1] = (1LL * x[1] * x[2]) % p;\n\t\ty[1] = (1LL * y[1] * x[2]) % p;\n\t\ty[1] = (1LL * y[1] + y[2]) % p;\n\t}while(o < p + 10 && cur != a[1]);\n\tif(cur != a[1]){\n\t\tcout << -1 << endl;\n\t\treturn 0;\n\t}\n\tint O = 0;\n\tcur = b[0];\n\tdo{\n\t\tcur = nex(cur, 1);\n\t\t++ O;\n\t}while(O < p + 10 && cur != b[1]);\n\tif(cur != b[1]){\n\t\tcout << -1 << endl;\n\t\treturn 0;\n\t}\n\tans += 1LL * o * O;\n\tcout << ans << endl;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "547",
    "index": "B",
    "title": "Mike and Feet",
    "statement": "Mike is the president of country What-The-Fatherland. There are $n$ bears living in this country besides Mike. All of them are standing in a line and they are numbered from $1$ to $n$ from left to right. $i$-th bear is exactly $a_{i}$ feet high.\n\nA group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.\n\nMike is a curious to know for each $x$ such that $1 ≤ x ≤ n$ the maximum strength among all groups of size $x$.",
    "tutorial": "For each $i$, find the largest $j$ that $a_{j} < a_{i}$ and show it by $l_{i}$ (if there is no such $j$, then $l_{i} = 0$). Also, find the smallest $j$ that $a_{j} < a_{i}$ and show it by $r_{i}$ (if there is no such $j$, then $r_{i} = n + 1$). This can be done in $O(n)$ with a stack. Pseudo code of the first part (second part is also like that) : Consider that you are asked to print $n$ integers, $ans_{1}, ans_{2}, ..., ans_{n}$. Obviously, $ans_{1}  \\ge  ans_{2}  \\ge  ...  \\ge  ans_{n}$. For each $i$, we know that $a_{i}$ can be minimum element in groups of size $1, 2, ..., r_{i} - l_{i} - 1$. Se we need a data structure for us to do this: We have array $ans_{1}, ans_{2}, ..., ans_{n}$ and all its elements are initially equal to $0$. Also, $n$ queries. Each query gives $x, val$ and want us to perform $ans_{1} = max(ans_{1}, val), ans_{2} = max(ans_{2}, val), ..., ans_{x} = max(ans_{x}, val)$. We want the final array. This can be done in $O(n)$ with a maximum partial sum (keeping maximum instead of sum), read here for more information about partial sum. Time complexity: ${\\mathcal{O}}(n)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e6 + 100;\nint a[maxn], n, l[maxn], r[maxn], ans[maxn];\nstack<int> s;\nint main(){\n\tscanf(\"%d\", &n);\n\tFor(i,0,n)\n\t\tscanf(\"%d\", a + i);\n\tfill(l, l + maxn, -1);\n\tfill(r, r + maxn, n);\n\tFor(i,0,n){\n\t\twhile(!s.empty() && a[s.top()] >= a[i])\n\t\t\ts.pop();\n\t\tif(!s.empty())\n\t\t\tl[i] = s.top();\n\t\ts.push(i);\n\t}\n\twhile(!s.empty())\n\t\ts.pop();\n\trof(i,n-1,-1){\n\t\twhile(!s.empty() && a[s.top()] >= a[i])\n\t\t\ts.pop();\n\t\tif(!s.empty())\n\t\t\tr[i] = s.top();\n\t\ts.push(i);\n\t}\n\tFor(i,0,n){\n\t\tint len = r[i] - l[i] - 1;\n\t\tsmax(ans[len], a[i]);\n\t}\n\trof(i,n,-1)\n\t\tsmax(ans[i], ans[i+1]);\n\tFor(i,1,n+1)\n\t\tprintf(\"%d \", ans[i]);\n\tcout << endl;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "dsu"
    ],
    "rating": 1900
  },
  {
    "contest_id": "547",
    "index": "C",
    "title": "Mike and Foam",
    "statement": "Mike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are $n$ kinds of beer at Rico's numbered from $1$ to $n$. $i$-th kind of beer has $a_{i}$ milliliters of foam on it.\n\nMaxim is Mike's boss. Today he told Mike to perform $q$ queries. Initially the shelf is empty. In each request, Maxim gives him a number $x$. If beer number $x$ is already in the shelf, then Mike should remove it from the shelf, otherwise he should put it in the shelf.\n\nAfter each query, Mike should tell him the score of the shelf. Bears are geeks. So they think that the score of a shelf is the number of pairs $(i, j)$ of glasses in the shelf such that $i < j$ and $\\operatorname*{gcd}(a_{i},a_{j})=1$ where $\\operatorname*{gcd}(a,b)$ is the greatest common divisor of numbers $a$ and $b$.\n\nMike is tired. So he asked you to help him in performing these requests.",
    "tutorial": "We define that a number $x$ is good if and only if there is no $y > 1$ that $y^{2}$ is a divisor of $x$. Also, we define function $f(x)$ as follow: Consider $x = p_{1}^{a1}  \\times  p_{2}^{a2}  \\times  ...  \\times  p_{k}^{ak}$ where all $p_{i}$s are prime. Then, $f(x) = a_{1} + a_{2} + ... + a_{n}$. Use simple inclusion. Consider all the primes from $1$ to $5  \\times  10^{5}$ are $p_{1}, p_{2}, ..., p_{k}$. So, after each query, if $d(x)$ is the set of beers like $i$ in the shelf that $x$ is a divisor of $a_{i}$, then number of pairs with $gcd$ equal to 1 is: $\\begin{array}{c}{{|d(1)|-|d(p_{1})\\cap d(p_{2})|-|d(p_{3})|\\neg|d(p_{3})|-...-|d(p_{k-1})\\cap d(p_{3})|+|d(p_{1})\\cap d(p_{2})\\Gamma.}}\\\\ {{d(p_{3})|+...=|d(p_{1})|-|d(p_{1}p_{2})|-|d(p_{1}p_{3})|-...-|d(p_{k-1}p_{k})|+|d(p_{1}p_{2}p_{3})|+...}}\\end{array}$ Consider good numbers from $1$ to $5  \\times  10^{5}$ are $b_{1}, b_{2}, ..., b_{m}$. The above phrase can be written in some other way: $|d(b_{1})|  \\times  ( - 1)^{f(b1)} + |d(b_{2})|  \\times  ( - 1)^{f(b2)} + ... + |d(b_{m})|  \\times  ( - 1)^{f(bm)}$. So, for each query if we can find all good numbers that $a_{i}$ is divisible by them in a fast way, we can solve the rest of the problem easily (for each good number $x$, we can store $|d(x)|$ in an array and just update this array and update the answer). Since all numbers are less than $2  \\times  3  \\times  5  \\times  7  \\times  11  \\times  13  \\times  17$, then there are at most $6$ primes divisible buy $a_{i}$. With a simple preprocesses, we can find their maximum and so easily we can find these (at most 6) primes fast. If their amount is $x$, then there are exactly $2^{x}$ good numbers that $a_{i}$ is divisible by them (power of each prime should be either $0$ or $1$). So we can perform each query in $O(2^{6})$ Time complexity: $O(q\\times2^{6})$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e6 + 10;\nint lsp[maxn], cnt[maxn];\nll ans = 0LL;\nint a[maxn], p[10], nx, bp[256], dp[256], lb[256], tp[256];\ninline void upd(int x, int sgn){\n\tnx = 0;\n\tint a;\n\twhile(x > 1){\n\t\ta = lsp[x];\n\t\tp[nx ++] = a;\n\t\twhile(x % a == 0)\n\t\t\tx /= a;\t\n\t}\n\tFor(mask,0,tp[nx]){\n\t\tif(mask)\n\t\t\tdp[mask] = p[lb[mask]] * dp[mask ^ tp[lb[mask]]];\n\t\telse\n\t\t\tdp[mask] = 1;\n\t\tif(sgn < 0)\n\t\t\tcnt[dp[mask]] += sgn;\n\t\tif(bp[mask] % 2)\n\t\t\tans += -1LL * sgn * cnt[dp[mask]];\n\t\telse\n\t\t\tans += +1LL * sgn * cnt[dp[mask]];\n\t\tif(sgn > 0)\n\t\t\tcnt[dp[mask]] += sgn;\n\t}\n}\nbool in[maxn];\nint n, q;\nint main(){\n\tmemset(lsp, -1, sizeof lsp);\n\tFor(i,0,256){\n\t\ttp[i] = (1 << i);\n\t\tbp[i] = __builtin_popcount(i);\n\t\tlb[i] = __builtin_ctz(i);\n\t}\n\tFor(i,2,maxn)\n\t\tif(lsp[i] == -1)\n\t\t\tfor(int j = i;j < maxn;j += i)\n\t\t\t\tlsp[j] = i;\n\tscanf(\"%d %d\", &n, &q);\n\tFor(i,0,n)\n\t\tscanf(\"%d\", a + i);\n\twhile(q--){\n\t\tint i;\n\t\tscanf(\"%d\", &i);\n\t\t-- i;\n\t\tif(!in[i])\n\t\t\tupd(a[i], +1);\n\t\telse\n\t\t\tupd(a[i], -1);\n\t\tin[i] = !in[i];\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "547",
    "index": "D",
    "title": "Mike and Fish",
    "statement": "As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish.\n\nHe has marked $n$ distinct points in the plane. $i$-th point is point $(x_{i}, y_{i})$. He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1.\n\nHe can't find a way to perform that! Please help him.",
    "tutorial": "Consider a bipartite graph. In each part (we call them first and second part) there are $L = 2  \\times  10^{5}$ vertices numbered from $1$ to $L$. For each point $(x, y)$ add an edge between vertex number $x$ from the first part and vertex number $y$ from the second part. In this problem, we want to color edges with two colors so that the difference between the number of blue edges connected to a vertex and the number of red edges connected to it be at most 1. Doing such thing is always possible. We prove this and solve the problem at the same time with induction on the number of edges : If all vertices have even degree, then for each component there is an Eulerian circuit, find it and color the edges alternatively_ with blue and red. Because graph is bipartite, then our circuit is an even walk and so, the difference between the number of blue and red edges connected to a vertex will be 0. Otherwise, if a vertex like $v$ has odd degree, consider a vertex like $u$ that there is and edge between $v$ and $u$. Delete this edge and solve the problem for the rest of the edges (with the induction definition) and then add this edge and if the number of red edges connected to $u$ is more than the blue ones, then color this edge with blue, otherwise with red. You can handle this add/delete edge requests and find odd vertices with a simple set. So, Time complexity: $O((n+L)\\log(L+n))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 2e5 + 10;\nvi adj[maxn * 2];\nint x[maxn * 2];\nmap <pii, int> mp;\nmap <pii, bool> del;\nvector<int> eu;\nset<int> d[2];\nint deg[maxn * 2];\nvector<pii> edges;\ninline void euler(int v){\n\twhile(!adj[v].empty()){\n\t\tint u = adj[v].back();\n\t\tadj[v].PB;\n\t\tif(!del[{v, u}]){\n\t\t\tdel[{v, u}] = del[{u, v}] = true;\n\t\t\teuler(u);\n\t\t}\n\t}\n\teu.pb(v);\n}\ninline void deledge(int v,int u){\n\tdel[{v, u}] = true;\n\tdel[{u, v}] = true;\n\td[deg[v]].erase(v);\n\tdeg[v] = !deg[v];\n\td[deg[v]].insert(v);\n\td[deg[u]].erase(u);\n\tdeg[u] = !deg[u];\n\td[deg[u]].insert(u);\n}\ninline void solve(){\n\tif(d[1].empty()){\n\t\tFor(i,0,maxn * 2){\n\t\t\teu.clear();\n\t\t\teuler(i);\n\t\t\tFor(j,1,eu.size())\n\t\t\t\tmp[{eu[j], eu[j-1]}] = mp[{eu[j-1], eu[j]}] = j % 2;\n\t\t}\n\t}\n\telse{\n\t\tint v = *d[1].begin();\n\t\twhile(!adj[v].empty() && del[{v, adj[v].back()}])\n\t\t\tadj[v].PB;\n\t\tint u = adj[v].back();\n\t\tdeledge(v, u);\n\t\tsolve();\n\t\tint c = 0;\n\t\tif(x[u] > 0)\n\t\t\tc = 1;\n\t\tif(c == 1)\n\t\t\tx[u] --, x[v] --;\n\t\telse\n\t\t\tx[u] ++, x[v] ++;\n\t\tmp[{v, u}] = mp[{u, v}] = c;\n\t}\n}\nint n;\nstring s = \"rb\";\nint main(){\n\tscanf(\"%d\", &n);\n\tFor(i,0,n){\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t-- x, -- y;\n\t\tx = 2 * x + 1;\n\t\ty = 2 * y;\n\t\tedges.pb({x, y});\n\t\tadj[x].pb(y);\n\t\tadj[y].pb(x);\n\t}\n\tFor(i,0,2*maxn)\n\t\td[(int)adj[i].size() % 2].insert(i), deg[i] = adj[i].size() % 2;\n\tsolve();\n\trep(e, edges)\n\t\tprintf(\"%c\", (char)s[mp[{e.x, e.y}]]);\n\tputs(\"\");\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "547",
    "index": "E",
    "title": "Mike and Friends",
    "statement": "What-The-Fatherland is a strange country! All phone numbers there are strings consisting of lowercase English letters. What is double strange that a phone number can be associated with several bears!\n\nIn that country there is a rock band called CF consisting of $n$ bears (including Mike) numbered from $1$ to $n$.\n\nPhone number of $i$-th member of CF is $s_{i}$. May 17th is a holiday named Phone Calls day. In the last Phone Calls day, everyone called all the numbers that are substrings of his/her number (one may call some number several times). In particular, everyone called himself (that was really strange country).\n\nDenote as $call(i, j)$ the number of times that $i$-th member of CF called the $j$-th member of CF.\n\nThe geek Mike has $q$ questions that he wants to ask you. In each question he gives you numbers $l, r$ and $k$ and you should tell him the number\n\n\\[\n\\sum_{i=1}^{r}c a l l(i,k)\n\\]",
    "tutorial": "$call(i, j) = match(s_{jins}_{i})$ which $match(tins)$ is the number of occurrences of $t$ in $s$. Concatenate all strings together in order (an put null character between them) and call it string $S$. We know that $|S|=\\sum_{i=1}^{n}|s_{i}|+n-1$. Consider $N = 5  \\times  10^{5}$. Consider Consider for each $i$, $S_{xi}s_{xi + 1}...s_{yi} = s_{i}$ ($x_{i + 1} = y_{i} + 2$). Also, for $i - th$ character of $S$ which is not a null character, consider it belongs to $s_{wi}$. Calculate the suffix array of $S$ in $(O(|S|\\log(|S|))=O(N\\log(N))$ and show it by $f_{1}, f_{2}, ..., f_{|S|}$ (we show each suffix by the index of its beginning). For each query, we want to know the number of occurrences of $s_{k}$ in $S_{xl}...s_{yr}$. For this propose, we can use this suffix array. Consider that we show suffix of $S$ starting from index $x$ by $S(x)$. Also, for each $i < |S|$, calculate $lcp(S(f_{i}), S(f_{i + 1}))$ totally in $O(N\\log(N))$ and show it by $lc_{i}$. For each query, consider $f_{i} = x_{k}$, also find minimum number $a$ and maximum number $b$ (using binary search and sparse table on sequence $lc$) such that $a  \\le  i  \\le  b$ and $min(lc_{a}, lc_{a + 1}, ..., lc_{i - 1})  \\ge  |s_{k}|$ and $min(lc_{i}, lc_{i + 1}, ..., lc_{b - 1})  \\ge  |s_{k}|$. Finally answer of this query is the number of elements in $w_{a}, w_{a + 1}, ..., w_{b}$ that are in the interval $[l, r]$. This problem is just like KQUERY. You can read my offline approach for KQUERY here. It uses segment tree, but you can also use Fenwick instead of segment tree. This wasn't my main approach. My main approach uses aho-corasick and a data structure I invented and named it C-Tree. Time complexity: $O(n\\log(n))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 5e5 + 100;\nint TRIE[maxn][26];\nstring s[maxn];\nint f[maxn], aut[maxn][26], root, nx = 1;\nvi tof[maxn];\nvi adj[maxn];\nint end[maxn];\ninline void build(int x){\n\tint v = root;\n\trep(ch, s[x]){\n\t\tint c = ch - 'a';\n\t\tif(TRIE[v][c] == -1){\n\t\t\tTRIE[v][c] = nx;\n\t\t\t++ nx;\n\t\t}\n\t\tv = TRIE[v][c];\n\t}\n\t::end[x] = v;\n}\ninline void ahoc(){\n\tf[root] = root;\n\tqueue<int> q;\n\tq.push(root);\n\twhile(!q.empty()){\n\t\tint v = q.front();\n\t\tq.pop();\n\t\tFor(c,0,26){\n\t\t\tif(TRIE[v][c] != -1){\n\t\t\t\taut[v][c] = TRIE[v][c];\t\n\t\t\t\tif(v != root)\n\t\t\t\t\tf[aut[v][c]] = aut[f[v]][c];\n\t\t\t\telse\n\t\t\t\t\tf[aut[v][c]] = root;\n\t\t\t\tq.push(TRIE[v][c]);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif(v == root)\n\t\t\t\t\taut[v][c] = root;\n\t\t\t\telse\n\t\t\t\t\taut[v][c] = aut[f[v]][c];\n\t\t\t}\n\t\t}\n\t}\n}\ninline void go(int x){\n\tint v = root;\n\trep(ch, s[x]){\n\t\tint c = ch - 'a';\n\t\tv = aut[v][c];\n\t\ttof[v].pb(x);\n\t}\n}\nint par[maxn];\nint st[maxn], ft[maxn];\nint a[maxn], nex = 0;\ninline void dfs(int v){\n\tst[v] = nex;\n\trep(x, tof[v])\n\t\ta[nex ++] = x;\n\trep(u, adj[v])\n\t\tdfs(u);\n\tft[v] = nex;\n}\nstruct query{\n\tint l, r, k, ind, sgn;\n\tquery(){\n\t\tl = r = k = 0;\n\t}\n\tquery(int L,int R,int K,int IND,int SGN){l = L, r = R, k = K, ind = IND, sgn = SGN;}\n\tbool operator < (const query &a) const{\n\t\tif(k != a.k)\n\t\t\treturn k < a.k;\n\t\treturn pii(l, r) < pii(a.l, a.r);\n\t}\n};\npii p[maxn];\nint fen[maxn];\ninline void add(int x){\n\t++ x;\n\tfor(int i = x;i < maxn;i += i & -i)\n\t\tfen[i] ++;\n}\ninline int ask(int x){\n\t++ x;\n\tint res = 0;\n\tfor(int i = x;i > 0;i -= i & -i)\n\t\tres += fen[i];\n\treturn res;\n}\ninline int ask(int l, int r){\n\treturn max(0, ask(r) - ask(l-1));\n}\nint answ[maxn];\nvector<query> quer;\nint lq[maxn], rq[maxn], kq[maxn];\nchar ch[maxn];\nint main(){\n\tmemset(TRIE, -1, sizeof TRIE);\n\tmemset(par, -1, sizeof par);\n\tint n, q;\n\tscanf(\"%d %d\", &n, &q);\n\tFor(i,0,n){\n\t\tscanf(\"%s\", ch);\n\t\ts[i] = (string)ch;\n\t\tbuild(i);\n\t}\n\tahoc();\n\tFor(i,0,n)\n\t\tgo(i);\n\tFor(i,1,nx){\n\t\tpar[i] = f[i];\n\t\tadj[par[i]].pb(i);\n\t}\n\tdfs(root);\n\tFor(i,0,q){\n\t\tscanf(\"%d %d %d\", lq + i, rq + i, kq + i);\n\t\t-- kq[i];\n\t\tkq[i] = ::end[kq[i]];\n\t\tlq[i] --;\n\t\trq[i] --;\n\t\tquer.pb(query(st[kq[i]], ft[kq[i]] - 1, lq[i] - 1, i, -1));\n\t\tquer.pb(query(st[kq[i]], ft[kq[i]] - 1, rq[i], i, 1));\n\t}\n\tsort(all(quer));\n\tFor(i,0,nex)\n\t\tp[i] = {a[i], i};\n\tsort(p, p + nex);\n\tint po = 0;\n\trep(q, quer){\n\t\tint l = q.l;\n\t\tint r = q.r;\n\t\tint k = q.k;\n\t\twhile(po < nex && p[po].x <= k){\n\t\t\tadd(p[po].y);\n\t\t\tpo ++;\n\t\t}\n\t\tint ans = ask(l, r);\n\t\tint ind = q.ind;\n\t\tansw[ind] += q.sgn * ans;\n\t}\n\tFor(i,0,q)\n\t\tprintf(\"%d\\n\", answ[i] );\n}",
    "tags": [
      "data structures",
      "string suffix structures",
      "strings",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "548",
    "index": "A",
    "title": "Mike and Fax",
    "statement": "While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string $s$.\n\nHe is not sure if this is his own back-bag or someone else's. He remembered that there were exactly $k$ messages in his own bag, each was a palindrome string and all those strings had the same length.\n\nHe asked you to help him and tell him if he has worn his own back-bag. Check if the given string $s$ is a concatenation of $k$ palindromes of the same length.",
    "tutorial": "Consider characters of this string are number 0-based from left to right. If $|s|$ is not a multiply of $k$, then answer is \"NO\". Otherwise, let $l e n={\\frac{\\log}{\\frac{\\langle\\pi\\rangle}{k}}}$. Then answer is \"Yes\" if and only if for each $i$ that $0  \\le  i < |s|$, $s_{i} = s_{(i / len) * len + len - 1 - (i%len)}$ where $a%b$ is the remainder of dividing $a$ by $b$. Time complexity: $O(|s|)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nint n, k;\nstring s;\nint main(){\n\tiOS;\n\tcin >> s >> k;\n\tn = s.size();\n\tint len = n/k;\n\tFor(i,0,n)\n\t\tif(n % k or s[i] != s[(i/len) * len + len - 1 - (i % len)]){\n\t\t\tcout << \"NO\" << endl;\n\t\t\treturn 0;\n\t\t}\n\tcout << \"YES\" << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "548",
    "index": "B",
    "title": "Mike and Fun",
    "statement": "Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an $n × m$ grid, there's exactly one bear in each cell. We denote the bear standing in column number $j$ of row number $i$ by $(i, j)$. Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes.\n\nThey play for $q$ rounds. In each round, Mike chooses a bear $(i, j)$ and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.\n\nScore of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.\n\nSince bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.",
    "tutorial": "Consider this problem: We have a binary sequence $s$ and want to find the maximum number of consecutive 1s in it. How to solve this? Easily: Finally, answer to this problem is ans. For each row $r$ of the table, let $ans_{r}$ be the maximum number of consecutive 1s in it (we know how to calculate it in $O(m)$ right ?). So after each query, update $ans_{i}$ in $O(m)$ and then find $max(ans_{1}, ans_{2}, ..., ans_{n})$ in $O(n)$. Time complexity: ${\\cal O}((n+m)q)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 500 + 10;\nbool a[maxn][maxn];\nint n, m, q;\nint mx[maxn];\ninline void calc(int i){\n\tint cur = 0;\n\tmx[i] = 0;\n\tFor(j,0,m){\n\t\tif(a[i][j])\n\t\t\tcur ++;\n\t\telse\n\t\t\tcur = 0;\n\t\tsmax(mx[i], cur);\n\t}\n}\nint main(){\n\tiOS;\n\tcin >> n >> m >> q;\n\tFor(i,0,n)\n\t\tFor(j,0,m)\n\t\t\tcin >> a[i][j];\n\tFor(i,0,n)\n\t\tcalc(i);\n\twhile(q--){\n\t\tint i, j;\n\t\tcin >> i >> j;\n\t\t-- i, -- j;\n\t\ta[i][j] = !a[i][j];\n\t\tcalc(i);\n\t\tint ans = 0;\n\t\tFor(i,0,n)\n\t\t\tsmax(ans, mx[i]);\n\t\tcout << ans << '\\n';\n\t}\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "549",
    "index": "A",
    "title": "Face Detection",
    "statement": "The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.\n\nIn this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a $2 × 2$ square, such that from the four letters of this square you can make word \"face\".\n\nYou need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.",
    "tutorial": "One should iterate through each 2x2 square and check if it is possible to rearrange letters in such way they they form the word \"face\". It could be done i.e. by sorting all letters from the square in alphabetic order and comparing the result with the word \"acef\"(sorted letters of word \"face\").",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "549",
    "index": "B",
    "title": "Looksery Party",
    "statement": "The Looksery company, consisting of $n$ staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message \\textbf{to himself or herself}.\n\nIgor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates $n$ numbers, the $i$-th of which indicates how many messages, in his view, the $i$-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.\n\nYou support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated.",
    "tutorial": "In any cases there is such set of people that if they come on party and send messages to their contacts then each employee receives the number of messages that is different from what Igor pointed. Let's show how to build such set. There are 2 cases. There are no zeros among Igor's numbers. So if nobody comes on party then each employee receives 0 messages and, therefore, the desired set is empty. There is at least one zero. Suppose Igor thinks that i-th employee will receive 0 messages. Then we should add i-th employee in the desired set. He will send messages to his contacts and will receive 1 message from himself. If we add other employees in the desired set then the number of messages that i-th employee will receive will not decrease so we can remove him from considering. Igor pointed some numbers for people from contact list of i-th employee and because they have already received one message we need to decrease these numbers by one. After that we can consider the same problem but with number of employees equals to n - 1. If the remaining number of employees is equal to 0 then the desired set is built.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "549",
    "index": "C",
    "title": "The Game Of Parity",
    "statement": "There are $n$ cities in Westeros. The $i$-th city is inhabited by $a_{i}$ people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly $k$ cities left.\n\nThe prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.\n\nLord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.",
    "tutorial": "If n = k no moves may be done. The winner is determined with starting parity of citizens' number. Otherwise let's see that the player making the last move may guarantee his victory, if there are both odd and even cities when he makes the move. He just selects the city of which parity he should burn to obtain required parity. So, his enemy's target is to destroy all the cities of some one type. Sometimes the type does matter, sometimes doesn't. It depends on the player's name and the parity of k. So the problem's solution consists in checking if \"non-last\" player's moves number (n - k) / 2 is enough to destroy all the odd or even cities. If Stannis makes the last move and k is even, Daenerys should burn all the odd or all the even cities. If k is odd, Daenerys should burn all the odd cities. If Daenerys makes the last move and k is even, Stannis has no chance to win. If k is odd, Stannis should burn all the even cities.",
    "tags": [
      "games"
    ],
    "rating": 2200
  },
  {
    "contest_id": "549",
    "index": "D",
    "title": "Haar Features",
    "statement": "The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.\n\nLet's consider a rectangular image that is represented with a table of size $n × m$. The table elements are integers that specify the brightness of each pixel in the image.\n\nA feature also is a rectangular table of size $n × m$. Each cell of a feature is painted black or white.\n\nTo calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of $W - B$, where $W$ is the total brightness of the pixels in the image, covered with white feature cells, and $B$ is the total brightness of the pixels covered with black feature cells.\n\nSome examples of the most popular Haar features are given below.\n\nYour task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.\n\nA prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.\n\nYou have a variable $value$, whose value is initially zero. In one operation you can count the sum of pixel values ​​at any prefix rectangle, multiply it by any integer and add to variable $value$.\n\nYou are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.",
    "tutorial": "This problem had a complicated statement but it is very similar to the real description of the features. Assume that we have a solution. It means we have a sequence of prefix-rectangles and coefficients to multiply. We can sort that sequence by the bottom-right corner of the rectangle and feature's value wouldn't be changed. Now we could apply our operations from the last one to the first. To calculate the minimum number of operations we will iterate through each pixel starting from the bottom-right in any of the column-major or raw-major order. For each pixel we will maintain the coefficient with which it appears in the feature's value. Initially it is 0 for all. If the coefficient of the current cell is not equal to + 1 for W and - 1 for B we increment the required amount of operations. Now we should make coefficient to have a proper value. Assume that it has to be X( - 1 or + 1 depends on the color) but current coefficient of this pixel is C. Then we should anyway add this pixel's value to the feature's value with the coefficient X - C. But the only way to add this pixel's value now(after skipping all pixels that have not smaller index of both row and column) is to get sum on the prefix rectangle with the bottom-left corner in this pixel. Doing this addition we also add X - C to the coefficient of all pixels in prefix-rectangle. This solution could be implemented as I describe above in $O(n^{2}m^{2})$ or $O(nm)$. Also I want to notice that in real Haar-like features one applies them not to the whole image but to the part of the image. Anyway, the minimum amount of operations could be calculated in the same way.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "549",
    "index": "E",
    "title": "Sasha Circle",
    "statement": "Berlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has $n$ points, Sasha — $m$. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so that the points of trade of one businessman are strictly inside a circle, and points of the other one are strictly outside. It doesn't matter which of the two gentlemen will have his trade points inside the circle.\n\nDetermine whether they can build a fence or not.",
    "tutorial": "Author's solution has complexity $O((|A|+|B|)C^{\\frac{2}{3}}+|A|l o g|A|+|B|l o g|B|)$, where $C$ is a maximum absolute value of the coordinates of all given points. Let's call a set of points $A$ and $B$ separable if there's a circle inside or on the boundary of which lie all the points of one set. When there're no points neither inside nor on the boundary of the circle we call this circle separating. Let points of the set $A$ lie inside or on the boundary of the circle and points of the set $B$ lie outside the circle. Points from set $A$ are allowed to be on the boundary of the separative circle as after increasing radius a little we're getting set $A$ strictly inside and set $B$ strictly outside the circle. Let $A$ contain at least two points. Separating circle can be compressed in such a way that it'll pass at least through two points of the set $A$. It's possible to look over all the pairs of points $p,q\\in A$ and try to pass each pair through the separating circle. The centre of the desired circle lies on the medial perpendicular of the segment $pq$. Let's designate the points of the medial perpendicular as $l(t)$ where $t\\in\\mathbb{R}$ is a parameter. All the points that don't lie on the straight line $pq$ make parameter $t$ bounded above or below. All the points that lie on the straight line $pq$ have to lie outside the limits of the segment $pq$. E.g. a picture below displays a blue point which bounds the centre of separating circle from the left side and red points - from the right side. That's why the centre has to lie inside a segment $cd$. Let's look over all the points to make sure that a value $t$ which satisfies all the bounds exists. This provides us with the problem solving for $O((|A|^{2} + |B|^{2})(|A| + |B|))$. Let's examine paraboloid $z = x^{2} + y^{2}$ and draw arbitrary non-vertical plane $ax + by + z = c$. The intersection of the paraboloid and the plane satysfies the equation $ax + by + x^{2} + y^{2} = c$, or $\\left(x+{\\textstyle{\\frac{1}{2}}}a\\right)^{2}+\\left(y+{\\textstyle{\\frac{1}{2}}}b\\right)^{2}=c+{\\textstyle{\\frac{1}{4}}}(a^{2}+b^{2})$. If project points of the paraboloid $(x, y, x^{2} + y^{2})$ onto the plane $(x,y,x^{2}+y^{2})\\mapsto(x,y)$ the cross-section of the paraboloid formed by the plane projects onto a circle, the paraboloid points below the plane projects onto internal points of the circle, those above the plane projects onto points outside the circle. As $(x,y,x^{2}+y^{2})\\mapsto(x,y)$ is one-to-one correspondence the opposite is also true: when points of the plane project onto the paraboloid $(x,y)\\mapsto(x,y,x^{2}+y^{2})$ the plane projects onto the cross-section of the paraboloid formed by the plane, the internal points - onto the paraboloid below the cross-section and external points - above the cross-section. So, projection of points onto paraboloid assigns one-to-one correspondence between circles and planes (non-vertical). partitioning of sets of points $A$ and $B$ of plane by circle can be done by means of partitioning of their three-dimensional projections into paraboloid $A'$ and $B'$ by non-vertical plane. Let's call such a plane separating (like separating circle, separating plane can include points from $A'$). By analogy with separating, circle separating plane can be passed through two points of set $A'$. All the other points of $A'$ will lie below or on the plane. In other words separating plane will pass through the edge of the upper convex hull of the set $A'$. The projection of edges of the upper convex hull $A'$ onto the plane $xOy$ will produce some sort of a set flat convex hull partitioning into $A$ by non-intersecting edges. In this case separating plane corresponds separating circle passing through the edge partition. Let's designate the convex hull $A$ as $coA$. In case when none of $4$ vertices $coA$ lies within one circle all the edges of the upper convex hull are triangles and the derived partitioning is triangulation. Otherwise the derived partitioning should be completed to be triangulation. To construct a separating circle look over triangulation edges and check the possibility of drawing a circle though an edge as it is described above. The derived triangulation has the following feature: circle drawn around any triangle contains the whole polygon $coA$ as the corresponding bound of three-dimensional convex hull is higher than all three-dimensional points $A'$. The described triangulation is \"opposite\" to the Delaunay triangulation according to which circle drawn around any triangle doesn't contain any points of the original set. This triangulation is commonly known as the Anti-Delaunay triangulation. Using the characterizing feature the Anti-Delaunay triangulation can be constructed by means of the method \"divide and conquer\" without transferring into three-dimensional space and working with points of plane and circles only. Let us triangulate polygon created by the vertices $coA$ when moving counter-clock-wise from $i$ to $j$. Let us find the third point of triangle, that will contain edge $(i, j)$. I.e such point $k$, that circumscribed circle over triangle $(i, j, k)$ contains the whole current polygon. For this purpose let's iterate through all polygon's vertices and select the one, that gives the extreme position of the center of the circumscribed circle lied on the mid-perpendicular of $(i, j)$. The circle will contain the whole polygon $coA$ as the edge $(i, j)$ is included in the Anti-Delaunay triangulation. Recursively triangulate polygons with vertices from $i$ to $k$ and from $k$ to $j$. The base of recursion is a segment, that shouldn't be triangulated. To solve the original problem one should swap $A$ and $B$ and perform the above procedure once more. Complexity of the algorithm is $O(|A|log|A| + |coA|(|coA| + |B|) + |B|log|B| + |coB|(|coB| + |A|)$=$O((|A|+|B|)C^{\\frac{2}{3}}+|A|l o g|A|+|B|l o g|B|)$, where $C$ is a maximum absolute value of the coordinates of all given points. Actually, $O(C^{3 / 2})$ is an estimation of the number of points at a convex hull with no three points in a line.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "549",
    "index": "F",
    "title": "Yura and Developers",
    "statement": "Yura has a team of $k$ developers and a list of $n$ tasks numbered from $1$ to $n$. Yura is going to choose some tasks to be done this week. Due to strange Looksery habits the numbers of chosen tasks should be a segment of consecutive integers containing \\textbf{no less than 2 numbers}, i. e. a sequence of form $l, l + 1, ..., r$ for some $1 ≤ l < r ≤ n$.\n\nEvery task $i$ has an integer number $a_{i}$ associated with it denoting how many man-hours are required to complete the $i$-th task. Developers are not self-confident at all, and they are actually afraid of difficult tasks. Knowing that, Yura decided to pick up a hardest task (the one that takes the biggest number of man-hours to be completed, among several hardest tasks with same difficulty level he chooses arbitrary one) and complete it on his own. So, if tasks with numbers $[l, r]$ are chosen then the developers are left with $r - l$ tasks to be done by themselves.\n\nEvery developer can spend any integer amount of hours over any task, but when they are done with the whole assignment there should be exactly $a_{i}$ man-hours spent over the $i$-th task.\n\nThe last, but not the least problem with developers is that one gets angry if he works more than another developer. A set of tasks $[l, r]$ is considered good if it is possible to find such a distribution of work that allows to complete all the tasks and to have every developer working for the same amount of time (amount of work performed by Yura doesn't matter for other workers as well as for him).\n\nFor example, let's suppose that Yura have chosen tasks with following difficulties: $a = [1, 2, 3, 4]$, and he has three developers in his disposal. He takes the hardest fourth task to finish by himself, and the developers are left with tasks with difficulties $[1, 2, 3]$. If the first one spends an hour on the first task and an hour on the third one, the second developer spends two hours on the second task and the third developer spends two hours on the third task, then they are done, since every developer worked exactly for two hours and every task has been worked over for the required amount of time. As another example, if the first task required two hours instead of one to be completed then it would be impossible to assign the tasks in a way described above.\n\nBesides work, Yura is fond of problem solving. He wonders how many pairs $(l, r)$ ($1 ≤ l < r ≤ n$) exists such that a segment $[l, r]$ is good? Yura has already solved this problem, but he has no time to write the code. Please, help Yura and implement the solution for this problem.",
    "tutorial": "Let's consider following solution: Let $f(l, r)$ be the solution for $[l, r]$ subarray. It's easy to see that $f(1, n)$ is the answer for the given problem. How should one count $f(l, r)$? Let $m$ be an index of the maximum value over subarray $[l, r]$. All the $good$ segments can be divided into two non-intersecting sets: those that contain $m$ and those that don't. To count the latter we can call $f(l, m - 1)$ and $f(m + 1, r)$. We are left with counting the number of subarrays that contain $m$, i.e. the number of pairs $(i, j)$ such that $l  \\le  i < m < j  \\le  r$ and $g(i, m - 1) + g(m + 1, j)%k = 0$ ($g(s, t)$ defines $a_{s} + a_{s + 1} + ... + a_{t})$. Let $s$ be the sequence of partial sums of the given array, i.e. $s_{i} = a_{1} + a_{2} + ... + a_{i}$. For every $j$ we are interested in the number of such $i$ that $s_{j} - s_{i} - a_{m}%k = 0$, so if we iterate over every possible $j$, then we are interested in number of $i$ that $s_{i} = s_{j} - a_{m}(modk)$ and $l  \\le  i < m$. So we are left with simple query over the segment problem of form \"how many numbers equal to $x$ and belong to a given segment $(l, r)$\". It can be done in $O(q + k)$ time and memory, where $q$ is the number of generated queries. Model solution processes all the queries in offline mode, using frequency array. One can notice that in the worst case we can generate $O(n^{2})$ queries which doesn't fit into TL or ML. However, we can choose which is faster: iterate over all possible $j$ or $i$. In both cases we get an easy congruence which ends up as a query described above. If we iterate only over the smaller segment, every time we \"look at\" the element $w$ it moves to a smaller segment which is at least two times smaller than the previous one. So, every element will end up in 1-element length segment where recursion will meet it's base in $O(log(n))$ \"looking at\" this element. The overall complexity is $O(n  \\times  log(n) + k)$.",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2800
  },
  {
    "contest_id": "549",
    "index": "G",
    "title": "Happy Line",
    "statement": "Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of $n$ Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person $a$ stands just behind person $b$, then person $a$ can pay person $b$ 1 dollar, then $a$ and $b$ get swapped. Of course, if person $a$ has zero dollars, he can not swap places with person $b$.\n\nResidents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them.\n\nCan you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.",
    "tutorial": "Let's reformulate the condition in terms of a certain height the towers, which will be on the stairs. Then an appropriate amount of money of a person in the queue is equal to the height of the tower with the height of the step at which the tower stands. And the process of moving in the queue will be equivalent to raising a tower on the top step, and the one in whose place it came up - down. As shown in the illustrations. Then, it becomes apparent that to make all of the tower on the steps to be sorted, it is enough to sort the tower without the height of step it stays. Total complexity of sorting is O(nlog(n)).",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "549",
    "index": "H",
    "title": "Degenerate Matrix",
    "statement": "The determinant of a matrix $2 × 2$ is defined as follows:\n\n\\[\n\\operatorname*{det}\\left(\\begin{array}{c c}{{a}}&{{b}}\\\\ {{c}}&{{d\\rangle}}=a d-b c\n\\]\n\nA matrix is called degenerate if its determinant is equal to zero.\n\nThe norm $||A||$ of a matrix $A$ is defined as a maximum of absolute values of its elements.\n\nYou are given a matrix $A={\\binom{a}{c}}{\\binom{b}{d}}$. Consider any degenerate matrix $B$ such that norm $||A - B||$ is minimum possible. Determine $||A - B||$.",
    "tutorial": "The rows of degenerate matrix are linear dependent so the matrix B can be written in the following way: Suppose Let's assume that elements of the first row of matrix $A$ are coordinates of point $a_{0}$ on two-dimensional plane and the elements of the second row are coordinates of point $a_{1}$. Assume that the rows of matrix $B$ are also coordinates of points $b_{0}$ and $b_{1}$. Let's note that in this case the line that is passing through points $b_{0}$ and $b_{1}$ is also passing through point $(0, 0)$. Let's find the answer - the number $d$ - by using binary search. Suppose we are considering some number $d_{0}$. We need to check if there is such matrix $B$ that In geometric interpretation it means that point $b_{0}$ are inside the square which center is point $a_{0}$ and length of side is $2 \\cdot d_{0}$. In the same way the point $b_{1}$ are inside the square which center is point $a_{1}$ and length of side is $2 \\cdot d_{0}$. So we need to check if there is a line that is passing through point $(0, 0)$ and is crossing these squares. In order to do this we should consider every vertex of the first square, build the line that is passing through the chosen vertex and the center of coordinate plane and check if it cross any side of the other square. Afterwards we should swap the squares and check again. Finally if there is a desired line we need to reduce the search area and to expand otherwise.",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "550",
    "index": "A",
    "title": "Two Substrings",
    "statement": "You are given string $s$. Your task is to determine if the given string $s$ contains two non-overlapping substrings \"AB\" and \"BA\" (the substrings can go in any order).",
    "tutorial": "There are many ways to solve this problem. Author solution does the following: check if substring \"AB\" goes before \"BA\", and then vice versa, if \"BA\" goes before \"AB\". You can do it in the following way: find the first occurence of \"AB\" then check all substrings of length two to the right of it to check if substring \"BA\" also exists. Then do it vice versa. Complexity of the solution is $O(n)$, where $n$ is the length of the given string.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "550",
    "index": "B",
    "title": "Preparing Olympiad",
    "statement": "You have $n$ problems. You have estimated the difficulty of the $i$-th one as integer $c_{i}$. Now you want to prepare a problemset for a contest, using some of the problems you've made.\n\nA problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least $l$ and at most $r$. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least $x$.\n\nFind the number of ways to choose a problemset for the contest.",
    "tutorial": "Because of the low constraints, this problem can be solved by complete search over all problem sets (there are $2^{n}$ of them). For every potential problem set (which can be conviniently expressed as bit mask) we need to check if it satisfies all needed criteria. We can simply find the sum of problem complexities and also the difference between the most difficult and the easiest problems in linear time, iterating over the problems that we included in our current set/bitmask. If this problem set can be used, we increase the answer by one. Complexity of this solution is $O(2^{n} \\cdot n)$.",
    "tags": [
      "bitmasks",
      "brute force"
    ],
    "rating": 1400
  },
  {
    "contest_id": "550",
    "index": "C",
    "title": "Divisibility by Eight",
    "statement": "You are given a non-negative integer $n$, its decimal representation consists of at most $100$ digits and doesn't contain leading zeroes.\n\nYour task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-negative integer, doesn't have leading zeroes and is divisible by 8. After the removing, it is forbidden to rearrange the digits.\n\nIf a solution exists, you should print it.",
    "tutorial": "This problem can be solved with at least two different approaches. The first one is based on the \"school\" property of the divisibility by eight - number can be divided by eight if and only if its last three digits form a number that can be divided by eight. Thus, it is enough to test only numbers that can be obtained from the original one by crossing out and that contain at most three digits (so we check only all one-digit, two-digit and three-digit numbers). This can be done in $O(len^{3})$ with three nested loops (here $len$ is the length of the original number). Second approach uses dynamic programming. Let's calculate $dp[i][j]$, $1  \\le  i  \\le  n$, $0  \\le  j < 8$. The value of dp is true if we can cross out some digits from the prefix of length $i$ such that the remaining number gives $j$ modulo eight, and false otherwise. This dp can be calculated in the following way: let $a_{i}$ be $i$th digit of the given number. Then $dp[i][a_{i}mod8] = true$ (just this number). For all $0  \\le  j < 8$ such that $dp[i - 1][j] = true$, $dp[i][(j * 10 + a_{i})mod8] = true$ (we add current digit to some previous result), $dp[i][j] = true$ (we cross out current digit). Answer is \"YES\" if $dp[i][0] = true$ for some position $i$. For restoring the answer we need to keep additional array $prev[i][j]$, which will say from where current value was calculated. Complexity of such solution is $O(8 \\cdot len) = O(len)$ (again $len$ is the length of the original number).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define sz(x) (int) x.size()\n#define all(a) a.begin(), a.end()\n#define prev sadasdjksgjkasjdklaj\n \nconst int MAXN = 105;\n \nstring s;\nint n;\nbool dp[MAXN][8];\nint prev[MAXN][8];\n \nint main() {\n \n    getline(cin, s);\n    n = sz(s);\n \n    memset(prev, -1, sizeof(prev));\n \n    dp[0][(s[0] - '0') % 8] = true;\n \n    for (int i = 1; i < n; i++) {\n        dp[i][(s[i] - '0') % 8] = true;\n \n        for (int j = 0; j < 8; j++) {\n            if (dp[i - 1][j]) {\n                dp[i][(j * 10 + s[i] - '0') % 8] = true;\n                prev[i][(j * 10 + s[i] - '0') % 8] = j;\n \n                dp[i][j] = true;\n                prev[i][j] = j;\n            }\n        }\n    }\n \n    for (int i = 0; i < n; i++) {\n        if (dp[i][0]) {\n            string ans = \"\";\n            int curI = i, curJ = 0;\n \n            while (true) {\n                if (prev[curI][curJ] == -1 || prev[curI][curJ] != curJ) {\n                    ans.append(1, s[curI]);\n                }\n \n                if (prev[curI][curJ] == -1) break;\n \n                curJ = prev[curI][curJ];\n                curI--;\n            }\n \n            puts(\"YES\");\n            reverse(all(ans));\n            cout << ans << endl;\n            return 0;\n        }\n    }\n \n    puts(\"NO\");\n \n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "550",
    "index": "D",
    "title": "Regular Bridge",
    "statement": "An undirected graph is called $k$-regular, if the degrees of all its vertices are equal $k$. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.\n\nBuild a connected undirected $k$-regular graph containing at least one bridge, or else state that such graph doesn't exist.",
    "tutorial": "Let's prove that there is no solution for even $k$. Suppose our graph contains some bridges, $k = 2s$ (even), all degrees are $k$. Then there always exists strongly connected component that is connected to other part of the graph with exactly one bridge. Consider this component. Let's remove bridge that connects it to the remaining graph. Then it has one vertex with degree $k - 1 = 2s - 1$ and some vertices with degrees $k = 2s$. But then the graph consisting of this component will contain only one vertex with odd degree, which is impossible by Handshaking Lemma. Let's construct the answer for odd $k$. Let $k = 2s - 1$. For $k = 1$ graph consisting of two nodes connected by edge works. For $k  \\ge  3$ let's construct graph with $2k + 4$ nodes. Let it consist of two strongly connected components connected by bridge. Enumerate nodes of first component from $1$ to $k + 2$, second component will be the same as the first one. Let vertex $1$ be connected to the second component by bridge. Also connect it with $k - 1$ edges to vertices $2, 3, ..., k$. Connect vertices $2, 3, ..., k$ to each other (add all possible edges between them), and then remove edges between every neighbouring pair, for example edges $2 - 3$, $4 - 5$, ..., $(k - 1) - k$. Then we connect vertices $2, 3, ..., k$ with vertices $k + 1$ and $k + 2$. And finally add an edge between nodes $k + 1$ and $k + 2$. Build the second component in the similar manner, and add a bridge between components. Constructed graph has one bridge, all degrees of $k$ and consists of $O(k)$ nodes and $O(k^{2})$ edges. Complexity of the solution - $O(k^{2})$.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "550",
    "index": "E",
    "title": "Brackets in Implications",
    "statement": "Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false.\n\nImplication is written by using character '$\\to$', and the arguments and the result of the implication are written as '0' ($false$) and '1' ($true$). According to the definition of the implication:\n\n\\begin{center}\n$0\\rightarrow0=1$\n\n$0\\rightarrow1=1\\qquad$\n\n$1\\to0=0$\n\n$1\\to1=1$\n\\end{center}\n\nWhen a logical expression contains multiple implications, then when there are no brackets, it will be calculated from left to fight. For example,\n\n$0\\rightarrow0\\rightarrow0=(0\\rightarrow0)\\rightarrow0=1\\rightarrow0=0=0$.\n\nWhen there are brackets, we first calculate the expression in brackets. For example,\n\n$0\\rightarrow(0\\rightarrow0)=0\\rightarrow1=1$.\n\nFor the given logical expression $a_{1}\\longrightarrow a_{2}\\to a_{3}\\to\\cdot\\cdot\\cdot\\to a_{n}$ determine if it is possible to place there brackets so that the value of a logical expression is false. If it is possible, your task is to find such an arrangement of brackets.",
    "tutorial": "Let input consists of $a_{1}\\longrightarrow a_{2}\\longrightarrow\\cdot\\cdot\\cdot\\longrightarrow a_{n}$, $a_{i}$ is $0$ or $1$ for all $i$. Let's show that there is no solution in only two cases: 1) $a_{n} = 1$. $x\\to1=1$, for all $x$, and no parentheses can change last $1$ to $0$. 2) Input has the form $1\\to1\\to1\\to\\cdots\\cdots\\to1\\to0\\to0$ or its suffix with at least two arguments. This can be proven by induction. For input $0\\to0$ there is no solution, for longer inputs any attempt to put parentheses will decrease the number of $1$s in the beginning by one, or will introduce $1$ in the last position (which will lead to case one). Let's construct solution for all other cases. 1) For input $0$ we don't need to do anything. 2) For input of the form $\\cdot\\cdot\\rightarrow1\\rightarrow0$ we don't need any parentheses, the value of this expression is always 3) Expression in the form $\\cdot\\cdot\\cdot\\rightarrow0\\rightarrow\\cdot\\cdot\\cdot\\rightarrow0\\rightarrow0$ (where second missed part consists of ones only). Then $\\cdot\\cdot\\cdot\\rightarrow(0\\to(1\\to1\\to\\cdot\\cdot\\cdot\\rightarrow1\\to0))\\to0=0$. Complexity of the solution is $O(n)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "551",
    "index": "A",
    "title": "GukiZ and Contest",
    "statement": "Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.\n\nIn total, $n$ students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from $1$ to $n$. Let's denote the rating of $i$-th student as $a_{i}$. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings.\n\nHe thinks that each student will take place equal to $\\mathrm{i}+(\\mathrm{number~of~students~with~strictly~higher~rating~than~his~or~her})$. In particular, if student $A$ has rating strictly lower then student $B$, $A$ will get the strictly better position than $B$, and if two students have equal ratings, they will share the same position.\n\nGukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.",
    "tutorial": "Very simple implementation problem. Just implement what is written in the statement: for every element of array, find the number of array elements greater than it, and add one to the sum. This can be easily done with two nested loops. Total complexity $O(n^{2})$.",
    "code": "import java.util.Scanner;\n\npublic class Main {\n\n    private Scanner scanner;\n\n    private Main(Scanner scanner) {\n        this.scanner = scanner;\n    }\n\n    public static void main(String[] args) {\n        Main main = new Main(new Scanner(System.in));\n        main.solve();\n    }\n\n    private void solve() {\n        int n = scanner.nextInt();\n        int[] a = new int[n];\n        for (int i = 0; i < n; i++) a[i] = scanner.nextInt();\n        for (int i = 0; i < n; i++) {\n            int s = 1;\n            for (int j = 0; j < n; j++) if (a[j] > a[i]) s++;\n            System.out.print(s);\n            if (i < n - 1) System.out.print(\" \");\n            else\n                System.out.println();\n        }\n    }\n}",
    "tags": [
      "brute force",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "551",
    "index": "B",
    "title": "ZgukistringZ",
    "statement": "Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.\n\nGukiZ has strings $a$, $b$, and $c$. He wants to obtain string $k$ by swapping some letters in $a$, so that $k$ should contain as many non-overlapping substrings equal either to $b$ or $c$ as possible. Substring of string $x$ is a string formed by consecutive segment of characters from $x$. Two substrings of string $x$ overlap if there is position $i$ in string $x$ occupied by both of them.\n\nGukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings $k$?",
    "tutorial": "First, calculate the number of occurences of every English letter in strings $a$, $b$, and $c$. We can now iterate by number of non-overlapping substrings of the resulting string equal to $b$, then we can calculate in constant time how many substrings equal to $c$ can be formed (by simple operations on the number of occurences of English letters in $c$). In every iteration, maximise the sum of numbers of $b$ and $c$. Number of iterations is not greater than $|a|$. At the end, we can easily build the resulting string by concatenating previously calculated number of strings $b$ and $c$, and add the rest of the letters to get the string obtainable from $a$. Total complexity is $O(|a| + |b| + |c|)$.",
    "code": "#include <cstdio>\n#include <cstring>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 100010;\nint n, m, k, ba[26], bb[26], bs[26];\nint d, res, prvi, drugi;\nchar s[N], a[N], b[N], resenje[N];\n\nint main()\n{\n    scanf(\"%s %s %s\", s + 1, a + 1, b + 1);\n    n = strlen(s + 1);\n    m = strlen(a + 1);\n    k = strlen(b + 1);\n    for (int i = 1; i <= n; i++) bs[s[i] - 'a']++;\n    for (int i = 1; i <= m; i++) ba[a[i] - 'a']++;\n    for (int i = 1; i <= k; i++) bb[b[i] - 'a']++;\n    for (int i = 0; ; i++)\n    {\n        int x = n;\n        for (int j = 0; j < 26; j++) if (bb[j]) x = min(x, bs[j] / bb[j]);\n        if (x + i > res)\n        {\n            res = x + i;\n            prvi = i;\n            drugi = x;\n        }\n        bool f = false;\n        for (int j = 0; j < 26; j++) if (bs[j] < ba[j])\n        {\n            f = true;\n            break;\n        } else\n        bs[j] -= ba[j];\n        if (f) break;\n    }\n    for (int i = 1; i <= prvi; i++)\n        for (int j = 1; j <= m; j++) resenje[++d] = a[j];\n    for (int i = 1; i <= drugi; i++)\n        for (int j = 1; j <= k; j++) resenje[++d] = b[j];\n    for (int i = 0; i < 26; i++) bs[i] = -ba[i] * prvi - bb[i] * drugi;\n    for (int i = 1; i <= n; i++) bs[s[i] - 'a']++;\n    for (int i = 0; i < 26; i++)\n        for (int j = 1; j <= bs[i]; j++) resenje[++d] = 'a' + i;\n    for (int i = 1; i <= n; i++) printf(\"%c\", resenje[i]);\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "551",
    "index": "C",
    "title": "GukiZ hates Boxes",
    "statement": "Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way.\n\nIn total there are $n$ piles of boxes, arranged in a line, from left to right, $i$-th pile ($1 ≤ i ≤ n$) containing $a_{i}$ boxes. Luckily, $m$ students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time $0$, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are:\n\n- If $i ≠ n$, move from pile $i$ to pile $i + 1$;\n- If pile located at the position of student is not empty, remove one box from it.\n\nGukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time $t$ in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after $t$ seconds, but all the boxes must be removed.",
    "tutorial": "Problem solution (complete work time) can be binary searched, because if the work can be done for some amount of time, it can certainly be done for greater amount of time. Let the current search time be $k$. We can determine if we can complete work for this time by folowing greedy algorithm: find last non-zero pile of boxes and calculate the time needed to get there (which is equal to it's index in array) and take with first man as much boxes as we can. If he can take even more boxes, find next non-zero (to the left) pile, and get as much boxes from it, and repete untill no time is left. When the first man does the job, repete the algorithm for next man, and when all $m$ men did their maximum, if all boxes are removed we can decrease upper bound in binary search. Otherwise, we must increase lower bound. Total compexity is $O((n+m)\\cdot\\log_{2}(n+\\sum a))$.",
    "code": "import java.util.Scanner;\n\npublic class Main {\n\n    private Scanner scanner;\n\n    private Main(Scanner scanner) {\n        this.scanner = scanner;\n    }\n\n    public static void main(String[] args) {\n        Main main = new Main(new Scanner(System.in));\n        main.solve();\n    }\n\n    private void solve() {\n        int n = scanner.nextInt();\n        int m = scanner.nextInt();\n        int[] a = new int[n];\n        long s = 0;\n        for (int i = 0; i < n; i++) s += a[i] = scanner.nextInt();\n        long l = 2, r = s + n;\n        while (l < r) {\n            long z = l + r >> 1;\n            int[] b = a.clone();\n            int p = n - 1;\n            for (int i = 0; i < m; i++) {\n                while (p >= 0 && b[p] == 0) p--;\n                long t = z - p - 1;\n                if (t <= 0) break;\n                while (p >= 0 && b[p] <= t) t -= b[p--];\n                if (p >= 0) b[p] -= t;\n            }\n            if (p < 0) r = z;\n            else\n                l = z + 1;\n        }\n        System.out.println(r);\n    }\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "551",
    "index": "D",
    "title": "GukiZ and Binary Operations",
    "statement": "We all know that GukiZ often plays with arrays.\n\nNow he is thinking about this problem: how many arrays $a$, of length $n$, with non-negative elements \\textbf{strictly less} then $2^{l}$ meet the following condition: $(a_{1}\\operatorname{and}a_{2})\\operatorname{or}(a_{2}\\operatorname{and}a_{3})\\operatorname{or}\\cdot\\cdot\\cdot\\operatorname{or}(a_{n-1}\\operatorname{and}a_{n})=k$? Here operation $\\mathrm{and}$ means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equivalent to &), operation $\\mathrm{or}$ means bitwise OR (in Pascal it is equivalent to $\\mathrm{or}$, in C/C++/Java/Python it is equivalent to |).\n\nBecause the answer can be quite large, calculate it modulo $m$. This time GukiZ hasn't come up with solution, and needs you to help him!",
    "tutorial": "First convert number $k$ into binary number system. If some bit of $k$ is $0$ than the result of $or$ opertion applied for every adjacent pair of those bits in array $a$ must be $0$, that is no two adjacent those bits in array $a$ are $1$. We should count how many times this is fulfilled. If the values were smaller we could count it with simply $dp_{i} = dp_{i - 1} + dp_{i - 2}$, where $dp_{i}$ is equal to number of ways to make array od i bits where no two are adjacent ones. With first values $dp_{1} = 2$ and $dp_{2} = 3$, we can see that this is ordinary Fibonacci number. We can calculate Fibonacci numbers up to $10^{18}$ easily by fast matrix multiplication. If some bit at $k$ is $1$ than number of ways is $2^{n}$ - \\t{(number of ways bit is 0)}, which is also easy to calculate. We must be cearful for cases when $2^{l}$ smaller than $k$ (solution is $0$ then) and when $l = 63$ or $l = 64$. Total complexity is $O(\\log_{2}n+\\log_{2}k)$.",
    "code": "import java.util.Scanner;\n\npublic class Main {\n\n    private Scanner scanner;\n    private int mod;\n\n    private Main(Scanner scanner) {\n        this.scanner = scanner;\n    }\n\n    public static void main(String[] args) {\n        Main main = new Main(new Scanner(System.in));\n        main.solve();\n    }\n\n    private void solve() {\n        long n = scanner.nextLong();\n        long k = scanner.nextLong();\n        int l = scanner.nextInt();\n        mod = scanner.nextInt();\n        if (mod == 1 || l < 63 && 1l << l <= k) {\n            System.out.println(0);\n            return;\n        }\n        if (l == 0) {\n            if (k == 0) System.out.println(1);\n            else\n                System.out.println(0);\n            return;\n        }\n        long pow2 = fastPower(2, n);\n        long fib = fibonacci(n + 1);\n        long res = 1;\n        for (int i = 0; i < l; i++)\n            if (((k >> i) & 1) == 0) res = res * fib % mod;\n            else\n                res = res * (pow2 - fib) % mod;\n        if (res < 0) res += mod;\n        System.out.println(res);\n    }\n\n    private long fibonacci(long n) {\n        Matrix matrix = new Matrix(new long[][]{{1, 1}, {1, 0}});\n        matrix = fastPower(matrix, n);\n        return matrix.matrix[0][0];\n    }\n\n    private long fastPower(long base, long exponent) {\n        if (exponent == 0) return 1;\n        long x = fastPower(base, exponent >> 1);\n        x = x * x % mod;\n        if ((exponent & 1) != 0) x = x * base % mod;\n        return x;\n    }\n\n    private Matrix fastPower(Matrix base, long exponent) {\n        if (exponent == 1) return base;\n        Matrix x = fastPower(base, exponent >> 1);\n        x = multiplyMatrix(x, x);\n        if ((exponent & 1) != 0) x = multiplyMatrix(x, base);\n        return x;\n    }\n\n    private Matrix multiplyMatrix(Matrix a, Matrix b) {\n        Matrix matrix = new Matrix();\n        for (int i = 0; i < 2; i++)\n            for (int j = 0; j < 2; j++)\n                for (int k = 0; k < 2; k++)\n                    matrix.matrix[i][k] = (matrix.matrix[i][k] + a.matrix[i][j] * b.matrix[j][k]) % mod;\n        return matrix;\n    }\n\n    private class Matrix {\n\n        private long[][] matrix;\n\n        public Matrix() {\n            matrix = new long[2][2];\n        }\n\n        public Matrix(long[][] c) {\n            matrix = c.clone();\n        }\n    }\n}",
    "tags": [
      "combinatorics",
      "implementation",
      "math",
      "matrices",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "551",
    "index": "E",
    "title": "GukiZ and GukiZiana",
    "statement": "Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called $GukiZiana$. For given array $a$, indexed with integers from $1$ to $n$, and number $y$, $GukiZiana(a, y)$ represents maximum value of $j - i$, such that $a_{j} = a_{i} = y$. If there is no $y$ as an element in $a$, then $GukiZiana(a, y)$ is equal to $ - 1$. GukiZ also prepared a problem for you. This time, you have two types of queries:\n\n- First type has form $1$ $l$ $r$ $x$ and asks you to increase values of all $a_{i}$ such that $l ≤ i ≤ r$ by the non-negative integer $x$.\n- Second type has form $2$ $y$ and asks you to find value of $GukiZiana(a, y)$.\n\nFor each query of type $2$, print the answer and make GukiZ happy!",
    "tutorial": "First we divide array $a$ in $\\sqrt{n}$ groups with $\\sqrt{n}$ numbers. Every group in each moment will be kept sorted. For type $1$ query, If we update some interval, for each group, which is whole packed in the interval, we will add the number it is being increased to it's current increasing value (this means all the elements are increased by this number). If some part of group is covered by interval, update these elements and resort them. Now, let's handle with type $2$ queries. When we want find $GukiZiana(a, j)$, we search for the first and the last occurence of $j$ by groups. One group can be binary searched in $O(\\log_{2}{\\sqrt{n}})$, because of sorted values, and most $\\sqrt{n}$ groups will be searched. Of course, for the first occurence we search for minimum index of value of $j$, and for the last occurence maximum index of value of $j$ in array. When we find these $2$ indexes, we must restore their original positions in array $a$ and print their difference. If there is no occurence of $j$, print $- 1$. Total complexity is $O(n\\cdot\\log_{2}{\\sqrt{n}}+q\\cdot{\\sqrt{n}}\\cdot\\log_{2}{\\sqrt{n}})$.",
    "code": "#include <cstdio>\n#include <cmath>\n#include <algorithm>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N = 500010, G = 1010;\nint n, q, koren;\nll a[N], d[N];\npair<ll, int> pa[G][G];\n\nint grupa(int x)\n{\n    return 1 + (x - 1) / koren;\n}\n\nvoid sortirajgrupu(int grp, int neki)\n{\n    int vel = 0;\n    for (int i = neki; i && grupa(i) == grp; i--) pa[grp][++vel] = {a[i], i};\n    for (int i = neki + 1; i <= n && grupa(i) == grp; i++) pa[grp][++vel] = {a[i], i};\n    sort(pa[grp] + 1, pa[grp] + vel + 1);\n}\n\nint main()\n{\n    scanf(\"%d %d\", &n, &q);\n    koren = sqrt(n);\n    for (int i = 1; i <= n; i++) scanf(\"%I64d\", &a[i]);\n    for (int i = 1, g = 1; g <= n; i++, g += koren) sortirajgrupu(i, g);\n    while (q--)\n    {\n        int t;\n        scanf(\"%d\", &t);\n        if (t == 1)\n        {\n            int l, r, x;\n            scanf(\"%d %d %d\", &l, &r, &x);\n            int p = grupa(l), q = grupa(r);\n            if (p == q)\n            {\n                for (int i = l; i <= r; i++) a[i] += x;\n                sortirajgrupu(p, l);\n                continue;\n            }\n            for (int i = l; i <= n && grupa(i) == p; i++) a[i] += x;\n            for (int i = r; i && grupa(i) == q; i--) a[i] += x;\n            sortirajgrupu(p, l);\n            sortirajgrupu(q, r);\n            for (int i = p + 1; i < q; i++) d[i] += x;\n        } else\n        {\n            int x, mi = 0, ma;\n            scanf(\"%d\", &x);\n            for (int i = 1, g = 1; g <= n; i++, g += koren)\n            {\n                int gor = min(n, g + koren - 1), vel = gor - g + 1;\n                int pos = lower_bound(pa[i] + 1, pa[i] + vel + 1, pair<ll, int>(x - d[i], 1)) - pa[i];\n                if (pos <= vel && pa[i][pos].first == x - d[i])\n                {\n                    mi = pa[i][pos].second;\n                    break;\n                }\n            }\n            for (int i = (n + koren - 1) / koren, g = (i - 1) * koren + 1; i; i--, g -= koren)\n            {\n                int gor = min(n, g + koren - 1), vel = gor - g + 1;\n                int pos = lower_bound(pa[i] + 1, pa[i] + vel + 1, pair<ll, int>(x - d[i] + 1, 1)) - pa[i] - 1;\n                if (pos && pa[i][pos].first == x - d[i])\n                {\n                    ma = pa[i][pos].second;\n                    break;\n                }\n            }\n            if (mi) printf(\"%d\\n\", ma - mi); else\n            printf(\"-1\\n\");\n        }\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "552",
    "index": "A",
    "title": "Vanya and Table",
    "statement": "Vanya has a table consisting of $100$ rows, each row contains $100$ cells. The rows are numbered by integers from $1$ to $100$ from bottom to top, the columns are numbered from $1$ to $100$ from left to right.\n\nIn this table, Vanya chose $n$ rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.",
    "tutorial": "In this problem we can get AC with many solutions: 1) With every new rectangle we will add his area to the result, so for each line $x_{1}, y_{1}, x_{2}, y_{2}$ we will add to answer $(x_{2} - x_{1} + 1) * (y_{2} - y_{1} + 1)$ Time complexity $O(n)$. 2) We can just do all, that is written in the statement: create an array and with each new rectangle we can just increment every element inside rectangle. In the end we can just add all elements inside this array. Time complexity $O(n * x * y)$",
    "code": "\"#include <iostream>\\n#include <cmath>\\n#include <algorithm>\\n#include <vector>\\n#include <cstring>\\n#include <deque>\\n#include <time.h>\\n#include <stack>\\n#include <stdio.h>\\n#include <map>\\n#include <set>\\n#include <string>\\n#include <fstream>\\n#include <queue>\\n#define mp make_pair\\n#define pb push_back\\n#define PI 3.14159265358979323846\\n#define MOD 1000000007\\n#define INF ((ll)1e+15)\\n#define x1 fldgjdflgjhrthrl\\n#define x2 fldgjdflgrtyrtyjl\\n#define y1 fldggfhfghjdflgjl\\n#define y2 ffgfldgjdflgjl\\ntypedef long long ll;\\nusing namespace std;\\nll i,n,m,x1,y1,x2,y2;\\n\\nint main()\\n{\\n    ll ans = 0;\\n\\tcin >> n;\\n\\tfor (i = 0; i < n; i++)\\n\\t{\\n\\t\\tcin >> x1 >> y1 >> x2 >> y2;\\n\\t\\tans += (x2-x1+1)*(y2-y1+1);\\n\\t}\\n\\tcout << ans << endl;\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "552",
    "index": "B",
    "title": "Vanya and Books",
    "statement": "Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the $n$ books should be assigned with a number from $1$ to $n$. Naturally, distinct books should be assigned distinct numbers.\n\nVanya wants to know how many digits he will have to write down as he labels the books.",
    "tutorial": "We can find out a formula for this problem: for $n < 10$ answer will be $n = n - 1 + 1 = 1 * (n + 1) - 1$; for $n < 100$ answer will be $2 * (n - 9) + 9 = 2 * n - 9 = 2 * n - 10 - 1 + 2 = 2 * (n + 1) - 11$; for $n < 1000$ answer will be $3 * (n - 99) + 2 * (99 - 9) + 9 = 3 * n - 99 - 9 = 3 * n - 100 - 10 - 1 + 3 = 3 * (n + 1) - 111$; so for $n < 10^{sz}$ answer will be $s z\\ast(n+1)-\\sum_{i=0}^{s_{z}-1}10^{s_{i}}$; Time complexity $O(sz)$, where $sz$ is the length of n. We also could just try $10$ options $n < 10, n < 100, ..., n < 10^{9}, n = 10^{9}$ and solve problem for each option. UPD: Don't use function pow() to find powers of 10, because it doesn't work right sometimes.",
    "code": "\"#include <iostream>\\n#include <cmath>\\n#include <algorithm>\\n#include <vector>\\n#include <cstring>\\n#include <deque>\\n#include <time.h>\\n#include <stack>\\n#include <stdio.h>\\n#include <map>\\n#include <set>\\n#include <string>\\n#include <fstream>\\n#include <queue>\\n#define mp make_pair\\n#define pb push_back\\n#define PI 3.14159265358979323846\\n#define MOD 1000000007\\n#define INF ((ll)1e+15)\\n#define x1 fldgjdflgjhrthrl\\n#define x2 fldgjdflgrtyrtyjl\\n#define y1 fldggfhfghjdflgjl\\n#define y2 ffgfldgjdflgjl\\ntypedef long long ll;\\nusing namespace std;\\nll i,n,x,m,k,ans;\\nint main()\\n{\\n    cin >> n;\\n\\tx = n;\\n\\twhile (x)\\n\\t{\\n\\t\\tx /= 10;\\n\\t\\tm++;\\n\\t}\\n\\tans = n*m + m - 1;\\n\\tk = 1;\\n\\tfor (i = 0; i < m-1; i++)\\n\\t{\\n\\t\\tk *= 10;\\n\\t\\tans -=k;\\n\\t}\\n\\tcout << ans << endl;\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "552",
    "index": "C",
    "title": "Vanya and Scales",
    "statement": "Vanya has a scales for weighing loads and weights of masses $w^{0}, w^{1}, w^{2}, ..., w^{100}$ grams where $w$ is some integer not less than $2$ (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass $m$ using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass $m$ and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.",
    "tutorial": "Convert $m$ to number system of base $w$. If all digits of number - $0$ or $1$, then we can measure the weight of the item with putting weights, that have digits equal to $1$, on one pan, and our item on another one. If this condition isn't satisfied, then we should iterate from lower digit to high and if digit is not equal to $0$ or $1$, we try to substract $w$ from it and increment higher digit. If it becomes equal to $- 1$, then we can put weight with number of this digit on the same pan with our item, if it becomes equal to $0$, then we don't put weight, in another case we can't measure the weight of our item and answer is $\\mathrm{No}$. Time complexity $O(logm)$.",
    "code": "\"#include <iostream>\\n#include <cmath>\\n#include <algorithm>\\n#include <vector>\\n#include <cstring>\\n#include <deque>\\n#include <time.h>\\n#include <stack>\\n#include <stdio.h>\\n#include <map>\\n#include <set>\\n#include <string>\\n#include <fstream>\\n#include <queue>\\n#define mp make_pair\\n#define pb push_back\\n#define PI 3.14159265358979323846\\n#define MOD 1000000007\\n#define INF ((ll)1e+15)\\n#define x1 fldgjdflgjhrthrl\\n#define x2 fldgjdflgrtyrtyjl\\n#define y1 fldggfhfghjdflgjl\\n#define y2 ffgfldgjdflgjl\\ntypedef long long ll;\\nusing namespace std;\\nll w,m,sz,i;\\nll a[40];\\n\\nint main()\\n{\\n\\tll flag = 1;\\n    cin >> w >> m;\\n    while (m)\\n    {\\n    \\ta[sz++] = m%w;\\n    \\tm /= w;\\n    }\\n\\tfor (i = 0; i <= sz; i++)\\n\\t\\tif (a[i] != 0 && a[i] != 1 && a[i] != w-1 && a[i] != w)\\n\\t\\t{\\n\\t\\t   flag = 0;\\n\\t\\t   break;\\n        }\\n        else\\n        {\\n\\t\\t\\tif (a[i] == w-1 || a[i] == w)\\n\\t\\t\\t   a[i+1]++;\\n        }\\n\\tif (flag)\\n\\t   cout << \\\"YES\\\" << endl;\\n\\telse\\n\\t\\tcout << \\\"NO\\\" << endl;\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math",
      "meet-in-the-middle",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "552",
    "index": "D",
    "title": "Vanya and Triangles",
    "statement": "Vanya got bored and he painted $n$ distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the \\textbf{non-zero} area.",
    "tutorial": "We can look through all pair of points, draw line through each pair and write, that this line includes these 2 points. We can do it with map. If some line includes $x$ points, then in fact we counted, that it has $2 * x * (x - 1)$ points, because we included each point 2*(x-1) times in this line. We can create an array and add to him values $b[2 * x * (x - 1)] = x$, so we can define, how many points is on the line. Then we can iterate through all lanes and for each line with $x$ points we will loose $x * (x - 1) * (x - 2) / 6$ possible triangles from all possible $n * (n - 1) * (n - 2) / 6$ triangles. Decide, that at first $ans = n * (n - 1) * (n - 2) / 6$. So for every line, that includes $x$ points, we will substract $x * (x - 1) * (x - 2) / 6$ from $ans$. Time complexity $O(n^{2} * logn)$.",
    "code": "\"#include <iostream>\\n#include <cmath>\\n#include <algorithm>\\n#include <vector>\\n#include <cstring>\\n#include <deque>\\n#include <time.h>\\n#include <stack>\\n#include <stdio.h>\\n#include <map>\\n#include <set>\\n#include <string>\\n#include <fstream>\\n#include <queue>\\n#include <unordered_map>\\n#define mp make_pair\\n#define pb push_back\\n#define PI 3.14159265358979323846\\n#define MOD 1000000007\\n#define INF ((ll)1e+15)\\n#define x1 fldgjdflgjhrthrl\\n#define x2 fldgjdflgrtyrtyjl\\n#define y1 fldggfhfghjdflgjl\\n#define y2 ffgfldgjdflgjl\\ntypedef long long ll;\\nusing namespace std;\\nint i,j,n,m,x[3005],y[3005],a[4500000],b[20005][205];\\nunordered_map <ll, int> f;\\nunordered_map <ll, int>::iterator itr;\\nll Abs(int a)\\n{\\n\\treturn a>0?a:-a;\\n}\\nll gcd(int a, int b)\\n{\\n\\tif (b == 0)\\n\\t   return a;\\n\\treturn gcd(b,a%b);\\n}\\nint main()\\n{\\n\\tfor (i = 1; i <= 20000; i++)\\n        for (j = 1; j <= 200; j++)\\n            b[i][j] = gcd(i,j);\\n\\tfor (i = 1; i <= 20000; i++)\\n\\t\\tb[i][0] = i;\\n\\tfor (i = 1; i <= 200; i++)\\n\\t\\tb[0][i] = i;\\n \\tcin >> n;\\n \\tfor (i = 2; i <= 2000; i++)\\n\\t\\ta[i*i-i] = i;\\n \\tfor (i = 0; i < n; i++)\\n\\t\\tcin >> x[i] >> y[i];\\n\\tfor (i = 0; i < n; i++)\\n\\t{\\n\\t\\tfor (j = 0; j < n; j++)\\n\\t\\tif (i != j)\\n\\t\\t{\\n\\t\\t\\tint kc = y[j] - y[i];\\n\\t\\t\\tint kz = x[j] - x[i];\\n\\t\\t\\tint bc = y[i]*(x[j] - x[i]) - x[i]*(y[j]-y[i]);\\n\\t\\t\\tint bz = x[j] - x[i];\\n\\t\\t\\tif (kz != 0)\\n\\t\\t\\t{\\n\\t\\t\\tint tmp = b[Abs(kc)][Abs(kz)];\\n\\t\\t\\tkc /= tmp; kz /= tmp;\\n\\t\\t\\tif (kc < 0)\\n\\t\\t\\t   kc = -kc, kz = -kz;\\n\\t\\t\\tif (kc == 0)\\n\\t\\t\\t   kz = 1;\\n            tmp = b[Abs(bc)][Abs(bz)];\\n\\t\\t\\tbc /= tmp; bz /= tmp;\\n\\t\\t\\tif (bc < 0)\\n\\t\\t\\t   bc = -bc, bz = -bz;\\n\\t\\t\\tif (bc == 0)\\n\\t\\t\\t   bz = 1;\\n            }\\n            else\\n            kc = bc = x[i];\\n            ll hsh = bc*27000000000LL + bz*9000000LL + kc*300 + kz;\\n\\t\\t\\t\\tf[hsh]+=2;\\n\\t\\t}\\n\\t}\\n\\tll ans = ((ll)n*(n-1)*(n-2))/6;\\n\\tfor (itr = f.begin(); itr != f.end(); itr++)\\n\\t{\\n\\t\\tint tmp = (*itr).second;\\n\\t\\ttmp = a[tmp/2];\\n\\t\\tans -= ((ll)tmp*(tmp-1)*(tmp-2))/6;\\n\\t}\\n\\tcout << ans << endl;\\n\\treturn 0;\\n}\"",
    "tags": [
      "brute force",
      "combinatorics",
      "data structures",
      "geometry",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "552",
    "index": "E",
    "title": "Vanya and Brackets",
    "statement": "Vanya is doing his maths homework. He has an expression of form $x_{1}\\otimes x_{2}\\otimes x_{3}\\otimes\\cdot\\cdot\\otimes x_{n}$, where $x_{1}, x_{2}, ..., x_{n}$ are digits from $1$ to $9$, and sign $\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad{}$ represents either a plus '+' or the multiplication sign '*'. Vanya needs to add \\textbf{one} pair of brackets in this expression so that to maximize the value of the resulting expression.",
    "tutorial": "We can see, that we can reach maximal answer, when brackets will be between two signs $*$, or between one sign $*$ and the end of expression. For convenience we will add in the begin of expression $1 *$, and in the end of expression $* 1$. After that we can iterate all possible pairs of signs $*$ and count the expression with putting brackets between two signs $*$ for each pair. We can use two variables $x$ and $y$ to count the value of expression, in the begin $x = 0, y = firstnumber$, where $firstnumber$ is first digit of expression, then if next sign is $+$, then $x = y, y = nextnumber$, and if next sign is $*$, then $x = x, y = y * nextnumber$. The value of expression will be $x + y$, we can create function, like that, to count expressions inside and outside the brackets. Time complexity $O(|s| * 17^{2})$.",
    "code": "\"#include <iostream>\\n#include <cmath>\\n#include <algorithm>\\n#include <vector>\\n#include <cstring>\\n#include <deque>\\n#include <time.h>\\n#include <stack>\\n#include <stdio.h>\\n#include <map>\\n#include <set>\\n#include <string>\\n#include <fstream>\\n#include <queue>\\n#define mp make_pair\\n#define pb push_back\\n#define PI 3.14159265358979323846\\n#define MOD 1000000007\\n#define INF ((ll)1e+15)\\n#define x1 fldgjdflgjhrthrl\\n#define x2 fldgjdflgrtyrtyjl\\n#define y1 fldggfhfghjdflgjl\\n#define y2 ffgfldgjdflgjl\\ntypedef long long ll;\\nusing namespace std;\\nll i,j,n,x,y,m,k,ans,a[6000],b[6000];\\nvector <ll> f;\\nstring s,t;\\npair<ll,ll> solve(ll l, ll r)\\n{\\n\\tll x = 0, y = a[l];\\n\\tfor (int i = l; i < r; i++)\\n\\t\\tif (b[i] == 1)\\n\\t\\t   x += y, y = a[i+1];\\n\\t\\telse\\n\\t\\t\\ty *= a[i+1];\\n\\treturn mp(x,y);\\n}\\nint main()\\n{\\n\\tcin >> s;\\n\\tt = \\\"1*\\\";\\n\\tt.append(s);\\n\\tt.append(\\\"*1\\\");\\n\\ts = t;\\n\\tn = s.size();\\n\\tm = n/2;\\n\\tfor (i = 0; i < n; i+=2)\\n\\t\\ta[i/2] = s[i] - '0';\\n\\tfor (i = 1; i < n; i+=2)\\n\\t\\tif (s[i] == '+')\\n\\t\\t   b[i/2] = 1;\\n\\t\\telse\\n\\t\\t{\\n\\t\\t\\tb[i/2] = 2;\\n\\t\\t\\tf.push_back(i/2);\\n\\t\\t}\\n\\tll max1 = 0;\\n\\tfor (i = 0; i < f.size(); i++)\\n\\t\\tfor (j = i+1; j < f.size(); j++)\\n\\t\\t{\\n\\t\\t pair <ll,ll> tmp = solve(0,f[i]);\\n\\t\\t x = tmp.first, y = tmp.second;\\n\\t\\t tmp = solve(f[i]+1,f[j]);\\n\\t\\t y *= tmp.first + tmp.second;\\n\\t\\t ll xx = a[f[j]];\\n\\t\\t a[f[j]] = y;\\n\\t\\t tmp = solve(f[j],m);\\n\\t\\t max1 = max(max1, x+tmp.first+tmp.second);\\n\\t\\t a[f[j]] = xx;\\n\\t\\t}\\n\\tcout << max1 << endl;\\n\\treturn 0;\\n}\\n\\n\"",
    "tags": [
      "brute force",
      "dp",
      "expression parsing",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "553",
    "index": "A",
    "title": "Kyoya and Colored Balls",
    "statement": "Kyoya Ootori has a bag with $n$ colored balls that are colored with $k$ different colors. The colors are labeled from $1$ to $k$. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color $i$ before drawing the last ball of color $i + 1$ for all $i$ from $1$ to $k - 1$. Now he wonders how many different ways this can happen.",
    "tutorial": "Let $f_{i}$ be the number of ways to solve the problem using only the first $i$ colors. We want to compute $f_{n}$. Initially, we have $f_{1} = 1$, since we only have a single color, and balls of the same color are indistinguishable. Now, to go from $f_{i}$ to $f_{i + 1}$, we note that we need to put at a ball of color $i + 1$ at the very end, but the other balls of color $i + 1$ can go anywhere in the sequence. The number of ways to arrange the balls of color $i + 1$ is $\\binom{c}{\\strut C_{1}+C_{2}\\stackrel{+}{\\downarrow}_{\\star+}C_{i+1}-1}\\Big\\}$ (minus one because we need to put one ball at the very end). Using this recurrence, we can solve for $f_{n}$. Thus, we need to precompute binomial coefficients then evaluate the product.",
    "code": "import java.io.*;\nimport java.util.*;\n \npublic class ColoredBalls {\n  public static int mod = 1000000007;\n  public static int MAXN = 1010;\n  \n  public static void main (String[] args) {\n    Scanner in = new Scanner(System.in);\n    PrintWriter out = new PrintWriter(System.out, true);\n    \n    long[][] comb = new long[MAXN][MAXN];\n    comb[0][0] = 1;\n    for (int i = 1; i < MAXN; i++) {\n      comb[i][0] = 1;\n      for (int j = 1; j <= i; j++) {\n        comb[i][j] = (comb[i-1][j] + comb[i-1][j-1]) % mod;\n      }\n    }\n    \n    int K = in.nextInt();\n    int[] color = new int[K];\n    for (int i = 0; i < K; i++) color[i] = in.nextInt();\n    \n    long res = 1;\n    int total = 0;\n    for (int i = 0; i < K; i++) {\n      res = (res * comb[total + color[i] - 1][color[i] - 1]) % mod;\n      total += color[i];\n    }\n    \n    out.println(res);\n    out.close();\n    System.exit(0);\n  }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "553",
    "index": "B",
    "title": "Kyoya and Permutation",
    "statement": "Let's define the permutation of length $n$ as an array $p = [p_{1}, p_{2}, ..., p_{n}]$ consisting of $n$ distinct integers from range from $1$ to $n$. We say that this permutation maps value $1$ into the value $p_{1}$, value $2$ into the value $p_{2}$ and so on.\n\nKyota Ootori has just learned about cyclic representation of a permutation. A cycle is a sequence of numbers such that each element of this sequence is being mapped into the next element of this sequence (and the last element of the cycle is being mapped into the first element of the cycle). The cyclic representation is a representation of $p$ as a collection of cycles forming $p$. For example, permutation $p = [4, 1, 6, 2, 5, 3]$ has a cyclic representation that looks like $(142)(36)(5)$ because 1 is replaced by 4, 4 is replaced by 2, 2 is replaced by 1, 3 and 6 are swapped, and 5 remains in place.\n\nPermutation may have several cyclic representations, so Kyoya defines the standard cyclic representation of a permutation as follows. First, reorder the elements within each cycle so the largest element is first. Then, reorder all of the cycles so they are sorted by their first element. For our example above, the standard cyclic representation of $[4, 1, 6, 2, 5, 3]$ is $(421)(5)(63)$.\n\nNow, Kyoya notices that if we drop the parenthesis in the standard cyclic representation, we get another permutation! For instance, $[4, 1, 6, 2, 5, 3]$ will become $[4, 2, 1, 5, 6, 3]$.\n\nKyoya notices that some permutations don't change after applying operation described above at all. He wrote all permutations of length $n$ that do not change in a list in lexicographic order. Unfortunately, his friend Tamaki Suoh lost this list. Kyoya wishes to reproduce the list and he needs your help. Given the integers $n$ and $k$, print the permutation that was $k$-th on Kyoya's list.",
    "tutorial": "Solving this requires making the observation that only swaps between adjacent elements are allowed, and all of these swaps must be disjoint. This can be discovered by writing a brute force program, or just noticing the pattern for small $n$. Here's a proof for why this is. Consider the cycle that contains $n$. Since $n$ is the largest number, it must be the last cycle in the sequence, and it's the first element of the sequence. If this cycle is length 1, then we're obviously ok (we can always append $(n)$ to the end). If the cycle is of length 2, we need $n$ to be involved in a cycle with $n - 1$. Lastly, if the cycle is of length 3 or more, we will see we run into a problem. We'll only show this for a cycle of length 3 (though this argument does generalize to cycles of larger length). Let $(nxy)$ be the cycle. So that means, $n$ is replaced by $x$, $x$ is replaced by $y$ and $y$ is replaced by $n$. So, in other words, the original permutation involving this cycle must look like However, we need it to look like $(nxy)$ so this case is impossible. So, once we know that $n$ is a in a cycle of length $1$ or $2$, we can ignore the last 1 or 2 elements of the permutation and repeat our reasoning. Thus, the only valid cases are when we swap adjacent elements, and all swaps are disjoint. After making this observation, we can see the number of valid permutations of length n is fib(n+1). (to see this, write try writing a recurrence). To reconstruct the kth permutation in the list, we can do this recursively as follows: If k is less than fib(n), then $1$ must be the very first element, and append the $k$th permutation on {1,...,n-1} with 1 added everywhere. Otherwise, add $2, 1$ to the very front and append the k-fib(n)th permutation on {1,...,n-2} with 2 added everywhere.",
    "code": "import java.io.PrintWriter;\nimport java.util.Scanner;\n \n \npublic class PermutationFinder {\n  public static void main (String[] args) {\n    Scanner in = new Scanner (System.in);\n    PrintWriter out = new PrintWriter (System.out, true);\n    \n    int N = in.nextInt();\n    long K = in.nextLong();\n    \n    long[] fib = new long[N+1];\n    fib[0] = fib[1] = 1;\n    for (int i = 2; i <= N; i++) fib[i] = fib[i-1]+fib[i-2];\n    \n    int idx = 0;\n    int[] res = new int[N];\n    while (idx < N) {\n      if (K <= fib[N-idx-1]) {\n        res[idx] = idx+1;\n        idx++;\n      } else {\n        K -= fib[N-idx-1];\n        res[idx] = idx+2;\n        res[idx+1] = idx+1;\n        idx += 2;\n      }\n    }\n    \n    for (int i = 0; i < N; i++) {\n      if (i != 0) out.print(\" \");\n      out.print(res[i]);\n    }\n    out.println();\n    out.close();\n    System.exit(0);\n  }\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "553",
    "index": "C",
    "title": "Love Triangles",
    "statement": "There are many anime that are about \"love triangles\": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has $n$ characters. The characters are labeled from $1$ to $n$. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).\n\nYou hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).\n\nYou are given a list of $m$ known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo $1 000 000 007$.",
    "tutorial": "Let's look at the graph of characters who love each other. Each love-connected component can be collapsed into a single node, since we know that all characters in the same connected component must love each other. Now, we claim that the resulting collapsed graph with the hate edges has a solution if and only if the resulting graph is bipartite. To show this, suppose the graph is not bipartite. Then, there is an odd cycle. If the cycle is of length 1, it is a self edge, which clearly isn't allowed (since a node must love itself). For any odd cycle of length more than 1, let's label the nodes in the cycle $a_{1}, a_{2}, a_{3}, ..., a_{k}$. Then, in general, we must have $a_{i}$ loves $a_{(i + 2)}$, since $a_{i}, a_{(i + 1)}$ hate each other and $a_{(i + 1)}, a_{(i + 2)}$ hate each other (all indicies taken mod $k$). However, we can use the fact that the cycle is odd and eventually get that $a_{i}$ and $a_{i + 1}$ love each other. However, this is a contradiction, since we said they must originally hate each other. For the other direction, suppose the graph is bipartite. Let $X, Y$ be an arbitrary bipartition of the graph. If we let all nodes in $X$ love each other and all nodes in $Y$ love each other, and every edge between $X$ and $Y$ hate each other, then we get a solution. (details are omitted, though I can elaborate if needed). Thus, we can see that we have a solution if and only if the graph is bipartite. So, if the graph is not bipartite, the answer is zero. Otherwise, the second part of the proof gives us a way to count. We just need to count the number of different bipartitions of the graph. It's not too hard to see that this is just simply 2^(number of connected components - 1) (once you fix a node, you fix every node connected to it). This entire algorithm takes $O(N + M)$ time.",
    "code": "import java.io.*;\nimport java.util.*;\n \npublic class OddGraphs {\n  public static int mod = 1000000007;\n  static class Edge {\n    public int from, to;\n    public Edge(int from, int to) {\n      this.from = from;\n      this.to = to;\n    }\n  }\n  \n  public static ArrayList<Integer>[] graph;\n  public static ArrayList<Edge> zeros, ones;\n  public static int[] par, size;\n  public static int find(int x) {\n    return x == par[x] ? x : (par[x] = find(par[x]));\n  }\n  public static void join(int a, int b) {\n    int x = find(a), y = find(b);\n    if (x == y) return;\n    if (size[x] < size[y]) {int t = x; x = y; y = t;}\n    par[y] = x;\n    size[x] += size[y];\n  }\n  \n  public static void main (String[] args) {\n    InputReader in = new InputReader (System.in);\n    PrintWriter out = new PrintWriter (System.out, true);\n    \n    int N = in.nextInt(), M = in.nextInt();\n    zeros = new ArrayList<>();\n    ones = new ArrayList<>();\n    for (int i = 0; i < M; i++) {\n      int a = in.nextInt()-1, b = in.nextInt()-1, c = in.nextInt();\n      if (c == 0) {\n        zeros.add(new Edge(a,b));\n      } else {\n        ones.add(new Edge(a,b));\n      }\n    }\n    \n    par = new int[N];\n    size = new int[N];\n    for (int i = 0; i < N; i++) {\n      par[i] = i;\n      size[i] = 1;\n    }\n    \n    for (Edge e : ones) {\n      join(e.from, e.to);\n    }\n    \n    graph = new ArrayList[N];\n    for (int i = 0; i < N; i++) graph[i] = new ArrayList<>();\n    \n    for (Edge e : zeros) {\n      graph[find(e.from)].add(find(e.to));\n      graph[find(e.to)].add(find(e.from));\n    }\n    \n    vis = new boolean[N];\n    color = new boolean[N];\n    int comp = 0;\n    for (int i = 0; i < N; i++) {\n      if (find(i) == i && !vis[i]) {\n        if (!dfs(i, false)) {\n          out.println(0);\n          out.close();\n          System.exit(0);\n        } else {\n          comp++;\n        }\n      }\n    }\n    int res = 1;\n    for (int i = 0; i < comp-1; i++) res = (res * 2) % mod;\n    \n    out.println(res);\n    out.close();\n    System.exit(0);\n  }\n  \n  public static boolean[] vis, color;\n  public static boolean dfs(int node, boolean c) {\n    if (vis[node]) return c == color[node];\n    vis[node] = true;\n    color[node] = c;\n    for (int neighbor : graph[node]) {\n      if (!dfs(neighbor, !c))\n        return false;\n    }\n    return true;\n  }\n  \n  static class InputReader {\n    public BufferedReader reader;\n    public StringTokenizer tokenizer;\n \n    public InputReader(InputStream stream) {\n      reader = new BufferedReader(new InputStreamReader(stream), 32768);\n      tokenizer = null;\n    }\n \n    public String next() {\n      while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n        try {\n          tokenizer = new StringTokenizer(reader.readLine());\n        } catch (IOException e) {\n          throw new RuntimeException(e);\n        }\n      }\n      return tokenizer.nextToken();\n    }\n \n    public int nextInt() {\n      return Integer.parseInt(next());\n    }\n  }\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "553",
    "index": "D",
    "title": "Nudist Beach",
    "statement": "Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers.\n\nThere are $n$ cities, labeled from 1 to $n$, and $m$ bidirectional roads between them. Currently, there are Life Fibers in every city. In addition, there are $k$ cities that are fortresses of the Life Fibers that cannot be captured under any circumstances. So, the Nudist Beach can capture an arbitrary non-empty subset of cities with no fortresses.\n\nAfter the operation, Nudist Beach will have to defend the captured cities from counterattack. If they capture a city and it is connected to many Life Fiber controlled cities, it will be easily defeated. So, Nudist Beach would like to capture a set of cities such that for each captured city the ratio of Nudist Beach controlled neighbors among all neighbors of that city is as high as possible.\n\nMore formally, they would like to capture a non-empty set of cities $S$ with no fortresses of Life Fibers. The strength of a city $x\\in S$ is defined as (number of neighbors of $x$ in $S$) / (total number of neighbors of $x$). Here, two cities are called neighbors if they are connnected with a road. The goal is to maximize the strength of the weakest city in $S$.\n\nGiven a description of the graph, and the cities with fortresses, find a non-empty subset that maximizes the strength of the weakest city.",
    "tutorial": "The algorithm idea works as follows: Start with all allowed nodes. Remove the node with the smallest ratio. Repeat. Take the best ratio over all iterations. It's only necessary to consider these subsets. Proof for why. We say this process finds a ratio of at least p if and only if there exists a subset with ratio at least p. Exists a subset with ratio at least p => algorithm will find answer of at least p. First, observe that the ratio of any particular node only decreases throughout the algorithm. Thus, all nodes in this subset initally have ratio at least p. Then, the very first node that gets removed from this subset must not have ratio smaller than p, thus the above algorithm will record an answer of at least p. Exists no subset with ratio at least p => algorithm finds answer at most p. No subset with ratio at least p implies every subset has ratio at most p. Thus, at every iteration of our algorithm, we'll get an answer of at most p, so we're done. Thus, we can see these are necessary and sufficient conditions, so we're done. Now for efficient implementation, we can use a variant of Dijkstra's. Recording the best subset must be done a bit more carefully as well.",
    "code": "import java.io.*;\nimport java.util.*;\n \npublic class GraphRatios {\n  public static ArrayList<Integer>[] graph;\n  public static int[] deg, cur;\n  public static boolean[] vis;\n  \n  public static void main (String[] args) {\n    InputReader in = new InputReader(System.in);\n    PrintWriter out = new PrintWriter(System.out, true);\n    \n    int N = in.nextInt(), M = in.nextInt(), K = in.nextInt();\n    vis = new boolean[N];\n    for (int i = 0; i < K; i++) vis[in.nextInt()-1] = true;\n    deg = new int[N]; \n    cur = new int[N];\n    graph = new ArrayList[N];\n    for (int i = 0; i < N; i++) graph[i] = new ArrayList<>();\n    for (int i = 0; i < M; i++) {\n      int a = in.nextInt()-1, b = in.nextInt()-1;\n      graph[a].add(b);\n      graph[b].add(a);\n      deg[a]++;\n      deg[b]++;\n      if (vis[a]) cur[b]++;\n      if (vis[b]) cur[a]++;\n    }\n    PriorityQueue<State> pq = new PriorityQueue<State>();\n    for (int i = 0; i < N; i++) if (!vis[i]) {\n      pq.add (new State(i, cur[i]));\n    }\n    \n    long num = 1, den = 1;\n    int[] lst = new int[N];\n    int idx = 0;\n    int best = 0;\n    while (pq.size() > 0) {\n      State s = pq.poll();\n      if (cur[s.node] != s.val || vis[s.node]) continue;\n      lst[idx++] = s.node;\n      long tn = s.val, td = deg[s.node];\n      if (num * td > den * tn) {num = tn; den = td; best = idx-1;}\n      vis[s.node] = true;\n      for (int neighbor : graph[s.node]) if (!vis[neighbor]) {\n        pq.add(new State(neighbor, ++cur[neighbor]));\n      }\n    }\n    \n    int[] res = new int[idx-best];\n    for (int i = best; i < idx; i++) res[i-best] = lst[i]+1;\n    // randomize order of output, just because I can.\n    for (int i = 0; i < res.length; i++) {\n      int j = (int)(Math.random() * (i+1));\n      if (j == i) continue;\n      int t = res[i]; res[i] = res[j]; res[j] = t;\n    }\n    out.println(res.length);\n    for (int i = 0; i < res.length; i++) {\n      if (i != 0) out.print(\" \");\n      out.print(res[i]);\n    }\n    out.println();\n    out.close();\n    System.exit(0);\n  }\n  \n  public static long gcd(long a, long b) {\n    return b == 0 ? a : gcd(b, a % b);\n  }\n  \n  static class State implements Comparable<State> {\n    public int node;\n    public long val;\n    public State(int node, int val) {\n      this.node = node;\n      this.val = val;\n    }\n    \n    public int compareTo(State other) {\n      return (int)(Math.signum(deg[node] * other.val - val * deg[other.node]));\n    }\n  }\n  \n  static class InputReader {\n    public BufferedReader reader;\n    public StringTokenizer tokenizer;\n \n    public InputReader(InputStream stream) {\n      reader = new BufferedReader(new InputStreamReader(stream), 32768);\n      tokenizer = null;\n    }\n \n    public String next() {\n      while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n        try {\n          tokenizer = new StringTokenizer(reader.readLine());\n        } catch (IOException e) {\n          throw new RuntimeException(e);\n        }\n      }\n      return tokenizer.nextToken();\n    }\n \n    public int nextInt() {\n      return Integer.parseInt(next());\n    }\n  }\n}",
    "tags": [
      "binary search",
      "graphs",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "553",
    "index": "E",
    "title": "Kyoya and Train",
    "statement": "Kyoya Ootori wants to take the train to get to school. There are $n$ train stations and $m$ one-way train lines going between various stations. Kyoya is currently at train station $1$, and the school is at station $n$. To take a train, he must pay for a ticket, and the train also takes a certain amount of time. However, the trains are not perfect and take random amounts of time to arrive at their destination. If Kyoya arrives at school strictly after $t$ time units, he will have to pay a fine of $x$.\n\nEach train line is described by a ticket price, and a probability distribution on the time the train takes. More formally, train line $i$ has ticket cost $c_{i}$, and a probability distribution $p_{i, k}$ which denotes the probability that this train will take $k$ time units for all $1 ≤ k ≤ t$. Amounts of time that each of the trains used by Kyouya takes are mutually independent random values (moreover, if Kyoya travels along the same train more than once, it is possible for the train to take different amounts of time and those amounts are also independent one from another).\n\nKyoya wants to get to school by spending the least amount of money in expectation (for the ticket price plus possible fine for being late). Of course, Kyoya has an optimal plan for how to get to school, and every time he arrives at a train station, he may recalculate his plan based on how much time he has remaining. What is the expected cost that Kyoya will pay to get to school if he moves optimally?",
    "tutorial": "The Naive solution is $O(MT^{2})$. Let $W_{j}(t)$ be the optimal expected time given we are at node $j$, with $t$ time units left. Also, let $W_{e}(t)$ be the optimal expected time given we use edge $e$ at time $t$. Now, we have $W_{j}(t)=\\left\\{\\operatorname*{su}_{\\mathrm{outest~distance~from~j~to~}}N+X\\quad\\mathrm{if~}t<=0\\nonumber\\\\ {\\operatorname*{lim_{ellerwise}~\\ d i w e}(t)\\quad}\\quad\\mathrm{otherwise}\\ ,$ And, if e = (u->v), we have $W_{e}(t)=d i s t(e)+\\sum_{k=1}^{T}P_{e}(k)W_{v}(t-k)$ Doing all this naively takes $O(MT^{2})$. Now, we'll speed this up using FFT. We'll focus on only a single edge for now. The problem here, however, is that not all $W_{v}$ values are given in advance. Namely, the $W_{v}$ values require us to compute the $W_{e}$ values for all edges at a particular time, and vice versa. So we need some sort of fast \"online\" version of FFT. We do this as follows. Let's abstract away the original problem, and let's say we're given two arrays a,b, where a is only revealed one at a time to us, and b is given up front, and we need to compute c, their convolution (in the original problem b is $P_{e}$, and a is $W_{v}$, and c is $W_{e}$). Now, when we get the ith value of a, we need to return the ith value of the convolution of c. We can only get the ith value of a when we compute the i-1th values of c for all c. Split up b into a block of size 1, a block of size 1, then a block of size 2, then a block of size 4, then 8, and so on. Now, we get $a_{0}$, which will allow us to compute $c_{1}$, which lets us get $a_{1}$, which allows us to compute $c_{2}$, and so on. So, now we have the following: We'll describe the processing of a single $a_{i}$ When we get $a_{i}$, we will first convolve it with the first two blocks, and add those to the appropriate entry. Now, suppose $a_{i}$ is multiple of a $2^{k}$ for some k. Then, we will convolve $a_{i - 2^{k}}$ .. $a_{i - 1}$ with the block in b with the same size. As an example. This gives us $c_{0}$, which then allows us to get $a_{1}$ This gives us $c_{1}$, which then allows us to get $a_{2}$ $a_{2}$ is now a power of 2, so this step will also additionally convolve $a_{0}, a_{1}$ with $b_{3}, b_{4}$ So, we can see this gives us $c_{2}$, which then allowus to get $a_{3}$, and so on and so forth. Thus, this process of breaking into blocks works. As for runtime, we run FFT on a block size of B T/B times, so this term contributes (T/B) * B log B = T log B So, we sum T log 2 + T log 4 + ... + T log 2\\^(log T) <= T log\\^2 T Thus, the overall time per edge is $T\\log^{2}T$, which gives us a total runtime of $O(M T\\log^{2}T)$.",
    "code": "import java.io.*;\nimport java.util.*;\n \npublic class RandomPaths {\n  public static int N, M, T, X;\n  public static int[][] prob;\n  public static Edge[] e;\n  public static double[][] inp;\n  public static double[][] outp;\n  public static int K;\n  public static double[][][][] tfd;\n  public static double[][] re, im;\n  \n  public static void main (String[] args) throws IOException {\n    InputReader in = new InputReader(System.in);\n    PrintWriter out = new PrintWriter(System.out, true);\n    \n    N = in.nextInt();\n    M = in.nextInt();\n    T = in.nextInt();\n    X = in.nextInt();\n    K = Integer.numberOfTrailingZeros(Integer.highestOneBit(T))+2;\n    \n    e = new Edge[M];\n    prob = new int[M][T+1];\n    inp = new double[M][];\n    outp = new double[M][];\n    tfd = new double[M][][][];\n    re = new double[K][];\n    im = new double[K][];\n    for (int i = 0; i < K; i++) {\n      re[i] = new double[1<<i];\n      im[i] = new double[1<<i];\n    }\n    \n    int[][] dist = new int[N][N];\n    for (int i = 0; i < N; i++) {Arrays.fill(dist[i], 1 << 29); dist[i][i] = 0;}\n    for (int i = 0; i < M; i++) {\n      int a = in.nextInt()-1, b = in.nextInt()-1, c = in.nextInt();\n      e[i] = new Edge(a,b,c);\n      dist[a][b] = Math.min(dist[a][b], c);\n      for (int j = 1; j <= T; j++)\n        prob[i][j] = in.nextInt();\n    }\n    \n    for (int k = 0; k < N; k++) for (int i = 0; i < N; i++) for (int j = 0; j < N; j++)\n      dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]);\n    \n    double[] res = new double[N];\n    for (int i = 0; i < N-1; i++) res[i] = dist[i][N-1] + X;\n    res[N-1] = 0;\n    \n    initTable();\n    for (int i = 0; i < M; i++) init(i, dist[e[i].b][N-1] + X);\n    \n    for (int t = 1; t <= T; t++) {\n      for (int i = 0; i < M; i++) set(i, t-1, res[e[i].b]);\n      Arrays.fill(res, 1l << 60); res[N-1] = 0;\n      for (int i = 0; i < M; i++) res[e[i].a] = Math.min(res[e[i].a], e[i].c + outp[i][t]);\n    }\n    \n    out.printf(\"%.10f\\n\", res[0]);\n    out.close();\n    System.exit(0);\n  }\n  \n  public static double[][] cosTable, sinTable;\n  public static void initTable() {\n    int levels = 18;\n    cosTable = new double[levels][];\n    sinTable = new double[levels][];\n    for (int j = 1; j < levels; j++) {\n      int n = 1 << j;\n      cosTable[j] = new double[n / 2];\n      sinTable[j] = new double[n / 2];\n      cosTable[j][0] = 1;\n      sinTable[j][0] = 0;\n      double qc = Math.cos(2 * Math.PI / n), qs = Math.sin(2 * Math.PI / n);\n      for (int i = 1; i < n / 2; i++) {\n        cosTable[j][i] = cosTable[j][i - 1] * qc - sinTable[j][i - 1] * qs;\n        sinTable[j][i] = sinTable[j][i - 1] * qc + cosTable[j][i - 1] * qs;\n      }\n    }\n  }\n \n  public static void transform(double[] real, double[] imag) {\n    int n = real.length;\n    if (n <= 1) return;\n    int levels = Integer.numberOfTrailingZeros(n);\n \n    for (int i = 0; i < n; i++) {\n      int j = Integer.reverse(i) >>> (32 - levels);\n      if (j > i) {\n        double temp = real[i]; real[i] = real[j]; real[j] = temp;\n        temp = imag[i]; imag[i] = imag[j]; imag[j] = temp;\n      }\n    }\n \n    for (int size = 2; size <= n; size *= 2) {\n      int halfsize = size / 2;\n      int tablestep = n / size;\n      for (int i = 0; i < n; i += size) {\n        for (int j = i, k = 0; j < i + halfsize; j++, k += tablestep) {\n          double tpre = real[j + halfsize] * cosTable[levels][k] + imag[j + halfsize] * sinTable[levels][k];\n          double tpim = -real[j + halfsize] * sinTable[levels][k] + imag[j + halfsize] * cosTable[levels][k];\n          real[j + halfsize] = real[j] - tpre;\n          imag[j + halfsize] = imag[j] - tpim;\n          real[j] += tpre;\n          imag[j] += tpim;\n        }\n      }\n    }\n  }\n    \n  public static void init(int index, double p) {\n    inp[index] = new double[T+1];\n    outp[index] = new double[T+1];\n    for (int i = 0; i <= T; i++) inp[index][i] = prob[index][i] / 100000.;\n    \n    int s = 100000;\n    for (int i = 0; i <= T; i++) {\n      s -= prob[index][i];\n      outp[index][i] = s / 100000. * p;\n    }\n    \n    tfd[index] = new double[K][2][];\n    for (int i = 2; i < K; i++) {\n      int start = (1<<(i-1))+1;\n      int end = (1<<i)+1;\n \n      int len = 2*(end-start);\n      tfd[index][i][0] = new double[len];\n      tfd[index][i][1] = new double[len];\n      System.arraycopy(inp[index], start, tfd[index][i][0], 0, Math.min(T + 1 - start, len/2));\n      transform(tfd[index][i][0], tfd[index][i][1]);\n    }\n  }\n  \n  public static void set(int index, int id, double x) {\n    outp[index][id] = x;\n \n    if (id+1 <= T) outp[index][id+1] += x * inp[index][1];\n    if (id+2 <= T) outp[index][id+2] += x * inp[index][2];\n    \n    for (int i = 2; i < K; i++) {\n      if ((((id+1) >> (i-2)) & 1) == 1) break;\n      int start = id-(1<<(i-1))+1;\n      int end = id+1;\n      int len = 2*(end-start);\n      \n      Arrays.fill(re[i], 0); Arrays.fill(im[i], 0);\n      System.arraycopy(outp[index], start, re[i], 0, len/2);\n      transform(re[i], im[i]);\n      \n      for (int j = 0; j < len; j++) {\n        double tre, tim;\n        tre = tfd[index][i][0][j] * re[i][j] - tfd[index][i][1][j] * im[i][j];\n        tim = tfd[index][i][1][j] * re[i][j] + tfd[index][i][0][j] * im[i][j];\n        re[i][j] = tre;\n        im[i][j] = tim;\n      }\n      transform(im[i], re[i]);\n      \n      for (int j = 0; id+j+2 <= T && j < len; j++) outp[index][id+j+2] += re[i][j] / len;\n    }\n  }\n  \n  static class Edge {\n    public int a, b, c;\n    public Edge(int a, int b, int c) {\n      this.a = a;\n      this.b = b;\n      this.c = c;\n    }\n  }\n  \n  static class InputReader {\n    public BufferedReader reader;\n    public StringTokenizer tokenizer;\n \n    public InputReader(InputStream stream) {\n      reader = new BufferedReader(new InputStreamReader(stream), 32768);\n      tokenizer = null;\n    }\n \n    public String next() {\n      while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n        try {\n          tokenizer = new StringTokenizer(reader.readLine());\n        } catch (IOException e) {\n          throw new RuntimeException(e);\n        }\n      }\n      return tokenizer.nextToken();\n    }\n \n    public int nextInt() {\n      return Integer.parseInt(next());\n    }\n  }\n}",
    "tags": [
      "dp",
      "fft",
      "graphs",
      "math",
      "probabilities"
    ],
    "rating": 3200
  },
  {
    "contest_id": "554",
    "index": "A",
    "title": "Kyoya and Photobooks",
    "statement": "Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled \"a\" to \"z\", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some \"special edition\" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?\n\nPlease help Haruhi solve this problem.",
    "tutorial": "Solving this problem just requires us to simulate adding every character at every position at the string, and removing any duplicates. For instance, we can use a HashSet of Strings in Java to do this (a set in C++ or Python works as well).",
    "code": "import java.util.HashSet;\nimport java.util.Scanner;\n \npublic class MissingLetter {\n  public static void main (String[] args) {\n    Scanner in = new Scanner (System.in);\n    String s = in.next();\n    HashSet<String> hs = new HashSet<>();\n    for (int i = 0; i <= s.length(); i++) {\n      for (char c = 'a'; c <= 'z'; c++) {\n        hs.add(s.substring(0,i)+c+s.substring(i));\n      }\n    }\n    System.out.println(hs.size());\n    System.exit(0);\n  }\n}",
    "tags": [
      "brute force",
      "math",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "554",
    "index": "B",
    "title": "Ohana Cleans Up",
    "statement": "Ohana Matsumae is trying to clean a room, which is divided up into an $n$ by $n$ grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.\n\nReturn the maximum number of rows that she can make completely clean.",
    "tutorial": "For each row, there is only one set of columns we can sweep so it becomes completely clean. So, there are only $n$ configurations of sweeping columns to look at. Checking a configuration takes $O(n^{2})$ time to count the number of rows that are completely clean. There are $n$ configurations in all, so this takes $O(n^{3})$ time total. Alternatively, another way of solving this problem is finding the maximum number of rows that are all the same.",
    "code": "import java.io.PrintWriter;\nimport java.util.Scanner;\n \n \npublic class LightMatrix {\n  public static void main (String[] args) {\n    Scanner in = new Scanner (System.in);\n    PrintWriter out = new PrintWriter (System.out, true);\n    \n    int N = in.nextInt();\n    String[] board = new String[N];\n    for (int i = 0; i < N; i++) board[i] = in.next();\n    int res = 0;\n    for (int i = 0; i < N; i++) {\n      int count = 0;\n      for (int j = 0; j < N; j++) if (board[j].equals(board[i])) count++;\n      res = Math.max(res, count);\n    }\n    out.println(res);\n    out.close();\n    System.exit(0);\n  }\n}",
    "tags": [
      "brute force",
      "greedy",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "555",
    "index": "A",
    "title": "Case of Matryoshkas",
    "statement": "Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.\n\nThe main exhibit is a construction of $n$ matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from $1$ to $n$. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, $1 → 2 → 4 → 5$.\n\nIn one second, you can perform one of the two following operations:\n\n- Having a matryoshka $a$ that isn't nested in any other matryoshka and a matryoshka $b$, such that $b$ doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put $a$ in $b$;\n- Having a matryoshka $a$ directly contained in matryoshka $b$, such that $b$ is not nested in any other matryoshka, you may get $a$ out of $b$.\n\nAccording to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain ($1 → 2 → ... → n$). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.",
    "tutorial": "Suppose we don't need to disassemble some sequence of dolls. Then no doll can be inserted into no doll from this chain. So we don't need to disassemble a sequence of dolls only if they are consecutive and start from $1$. Let the length of this chain be $l$. Then we will need to get one doll from another $n - k - l + 1$ times. Now we have a sequence $1  \\rightarrow  2  \\rightarrow  ...  \\rightarrow  l$ and all other dolls by themselves. $n - l + 1$ chains in total so we need to put one doll into another $n - l$ times. $2n - k - 2l + 1$ operations in total. Time: $O(n)$",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "555",
    "index": "B",
    "title": "Case of Fugitive",
    "statement": "Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.\n\nThe only dry land there is an archipelago of $n$ narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island $i$ has coordinates $[l_{i}, r_{i}]$, besides, $r_{i} < l_{i + 1}$ for $1 ≤ i ≤ n - 1$.\n\nTo reach the goal, Andrewid needs to place a bridge between each pair of \\textbf{adjacent} islands. A bridge of length $a$ can be placed between the $i$-th and the $(i + 1)$-th islads, if there are such coordinates of $x$ and $y$, that $l_{i} ≤ x ≤ r_{i}$, $l_{i + 1} ≤ y ≤ r_{i + 1}$ and $y - x = a$.\n\nThe detective was supplied with $m$ bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.",
    "tutorial": "We can put a bridge between bridges $i$ and $i + 1$ if its length lies in the segment $[l_{i + 1} - r_{i};r_{i + 1} - l_{i}]$. Now we have a well-known problem: there are $n - 1$ segments and $m$ points on a plane, for every segment we need to assign a point which lies in it to this segment and every point can be assigned only once. Let's call a segment open if no point is assigned to it. Let's go through all points from left to right and at every moment keep all open segments that contain current point in a BST (std::set). When processing a point it should be assigned to the segment (from our set) that has the leftmost right end. This algorithm will find the answer if there is one. Suppose this solution is wrong and suppose there is a solution in which point $A$ is assigned to another open segment (there's no sense in skipping this point). Then some point $B$ is assigned to the segment which $A$ was assigned to. $B$ is to the right of $A$ so we can swap them and come to our answer again. Time: $O((n + m)log(n + m))$",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "555",
    "index": "C",
    "title": "Case of Chocolate",
    "statement": "Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom.\n\nA bar of chocolate can be presented as an $n × n$ table, where each cell represents one piece of chocolate. The columns of the table are numbered from $1$ to $n$ from left to right and the rows are numbered from top to bottom. Let's call the anti-diagonal to be a diagonal that goes the lower left corner to the upper right corner of the table. First Andrewid eats all the pieces lying below the anti-diagonal. Then he performs the following $q$ actions with the remaining triangular part: first, he chooses a piece on the anti-diagonal and either direction 'up' or 'left', and then he begins to eat all the pieces starting from the selected cell, moving in the selected direction until he reaches the already eaten piece or chocolate bar edge.\n\nAfter each action, he wants to know how many pieces he ate as a result of this action.",
    "tutorial": "Let's solve this problem with two segment trees: we'll keep the lowest eaten piece for each column in one of them and the leftmost eaten piece for each row in another. Suppose we have a query $x$ $y$ $L$. Position where we'll stop eating chocolate is stored in the row segment tree so we can easily find the number of eaten pieces. After that we need to update both segment trees. $n$ is rather big in this problem. One way to deal with it is to use coordinate compression. Another is to use implicit segment trees. Time: $O(qlogq)$ or $O(qlogn)$",
    "tags": [
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "555",
    "index": "D",
    "title": "Case of a Top Secret",
    "statement": "Andrewid the Android is a galaxy-famous detective. Now he is busy with a top secret case, the details of which are not subject to disclosure.\n\nHowever, he needs help conducting one of the investigative experiment. There are $n$ pegs put on a plane, they are numbered from $1$ to $n$, the coordinates of the $i$-th of them are $(x_{i}, 0)$. Then, we tie to the bottom of one of the pegs a weight on a tight rope of length $l$ (thus, its coordinates will be equal to $(x_{i}, - l)$, where $i$ is the number of the used peg). Then the weight is pushed to the right, so that it starts to rotate counterclockwise. At the same time, if the weight during rotation touches some of the other pegs, it then begins to rotate around that peg. Suppose that each peg itself is very thin and does not affect the rope length while weight is rotating around it.\n\nMore formally, if at some moment the segment of the rope contains one or more pegs in addition to the peg around which the weight is rotating, the weight will then rotate around the farthermost one of them on a shorter segment of a rope. In particular, if the segment of the rope touches some peg by its endpoint, it is considered that the weight starts to rotate around that peg on a segment of the rope of length $0$.\n\nAt some moment the weight will begin to rotate around some peg, without affecting the rest of the pegs. Andrewid interested in determining the number of this peg.\n\nAndrewid prepared $m$ queries containing initial conditions for pushing the weight, help him to determine for each of them, around what peg the weight will eventually rotate.",
    "tutorial": "I call the length of the part of the rope from the weight to the last met peg the active length (denoted as $L_{a}$). After each met peg active length is reduced. Let's process queries separately: at each step we can find next peg with using binary search. If active length becomes at least two times shorter or current step is the first one we proceed to the next step. Otherwise say current peg is peg $i$ and the next one is peg $j$ (without loss of generality $i < j$). Then after peg $j$ the rope will again touch peg $i$ and the weight will again rotate around peg $i$. Indeed, $2(x_{j} - x_{i})  \\le  L_{a}$ so the weight will rotate around a peg not to the right to peg $i$. And either $i = 1$ or $L_{a}  \\le  x_{i} - x_{i - 1}$ so it won't also rotate around a peg to the left to peg $i$. As long as $L_{a}  \\ge  x_{j} - x_{i}$ the weight will rotate around these two pegs so we can skip through several steps momentarily. This way active length is shortened at least twice so there will be no more than $logL$ steps. Time: $O(mlogLlogn)$",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "555",
    "index": "E",
    "title": "Case of Computer Network",
    "statement": "Andrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network.\n\nIn this network are $n$ vertices, some pairs of vertices are connected by $m$ undirected channels. It is planned to transfer $q$ important messages via this network, the $i$-th of which must be sent from vertex $s_{i}$ to vertex $d_{i}$ via one or more channels, perhaps through some intermediate vertices.\n\nTo protect against attacks a special algorithm was developed. Unfortunately it can be applied only to the network containing directed channels. Therefore, as new channels can't be created, it was decided for each of the existing undirected channels to enable them to transmit data only in one of the two directions.\n\nYour task is to determine whether it is possible so to choose the direction for each channel so that each of the $q$ messages could be successfully transmitted.",
    "tutorial": "First of all, let's reduce this problem to a problem on a tree. In order to achieve this let's orient edges in all biconnected components according to a DFS-order. We'll get a strongly connected component. Suppose it's false. Then this component can be divided into parts $A$ and $B$ such that there's no edge from $B$ to $A$. As initially there are at least two edges between $A$ and $B$ this situation is impossible because after entering $B$ in our DFS we'll have to exit via one of these edges. Contradiction. We can compress all biconnected components. Now we need to handle several queries \"orient edges on a simple path in a tree\" and to check if there are no conflicts. For this let's hang our tree and find LCA's for queries' pairs of vertices. Start another DFS and for every subtree count vertices in this subtree that are beginnings of queries' paths (call it $a$), that are ends of queries' paths (call it $b$) and that are precalculated LCAs (call it $c$). Now we can orient the edge connecting the root of the subtree and its parent: if $a - c$ is positive then it should be oriented up, if $b - c$ is positive then it should be oriented down, if both are positive there's no solution, if both are zeros the direction does not matter. Time: $O(n + ql_{q})$ where $l_{q}$ is the time of calculating LCA per query",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "556",
    "index": "A",
    "title": "Case of the Zeros and Ones",
    "statement": "Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.\n\nOnce he thought about a string of length $n$ consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length $n - 2$ as a result.\n\nNow Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.",
    "tutorial": "If there still exist at least one $0$ and at least one $1$ in the string then there obviously exists either substring $01$ or substring $10$ (or both) and we can remove it. The order in which we remove substrings is unimportant: in any case we will make $min(#zeros, #ones)$ such operations. Thus the answer is $#ones + #zeros - 2min(#ones, #zeros) = |#ones - #zeros|$. Time: $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "556",
    "index": "B",
    "title": "Case of Fake Numbers",
    "statement": "Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.\n\nIts most important components are a button and a line of $n$ similar gears. Each gear has $n$ teeth containing all numbers from $0$ to $n - 1$ in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.\n\nBesides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if $n = 5$, and the active tooth is the one containing number $0$, then clockwise rotation makes the tooth with number $1$ active, or the counter-clockwise rotating makes the tooth number $4$ active.\n\nAndrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence $0, 1, 2, ..., n - 1$. Write a program that determines whether the given puzzle is real or fake.",
    "tutorial": "Notice that after pressing the button $n$ times gears return to initial state. So the easiest solution is to simulate the process of pressing the button $n$ times and if at some step the active teeth sequence is $0, 1, ... , n - 1$ output \"Yes\" else \"No\". But this solution can be improved. For instance, knowing the active tooth of the first gear you can quickly determine how many times pressing the button is necessary, go to that state and check the sequence only once. Time: $O(n)$ or $O(n^{2})$",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "557",
    "index": "A",
    "title": "Ilya and Diplomas",
    "statement": "Soon a school Olympiad in Informatics will be held in Berland, $n$ schoolchildren will participate there.\n\nAt a meeting of the jury of the Olympiad it was decided that each of the $n$ participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma.\n\nThey also decided that there must be given at least $min_{1}$ and at most $max_{1}$ diplomas of the first degree, at least $min_{2}$ and at most $max_{2}$ diplomas of the second degree, and at least $min_{3}$ and at most $max_{3}$ diplomas of the third degree.\n\nAfter some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree.\n\nChoosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations.\n\nIt is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all $n$ participants of the Olympiad will receive a diploma of some degree.",
    "tutorial": "This problem can be solved in the different ways. We consider one of them - parsing cases. If $max_{1} + min_{2} + min_{3}  \\le  n$ then the optimal solution is ($n - min_{2} - min_{3}$, $min_{2}$, $min_{3}$). Else if $max_{1} + max_{2} + min_{3}  \\le  n$ then the optimal solution is ($max_{1}$, $n - max_{1} - min_{3}$, $min_{3}$). Else the optimal solution is ($max_{1}$, $max_{2}$, $n - max_{1} - max_{2}$). This solution is correct because of statement. It is guaranteed that $min_{1} + min_{2} + min_{3}  \\le  n  \\le  max_{1} + max_{2} + max_{3}$. Asymptotic behavior of this solution - O(1).",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "557",
    "index": "B",
    "title": "Pasha and Tea",
    "statement": "Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of $w$ milliliters and $2n$ tea cups, each cup is for one of Pasha's friends. The $i$-th cup can hold at most $a_{i}$ milliliters of water.\n\nIt turned out that among Pasha's friends there are exactly $n$ boys and exactly $n$ girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows:\n\n- Pasha can boil the teapot exactly once by pouring there at most $w$ milliliters of water;\n- Pasha pours the same amount of water to each girl;\n- Pasha pours the same amount of water to each boy;\n- if each girl gets $x$ milliliters of water, then each boy gets $2x$ milliliters of water.\n\nIn the other words, each boy should get two times more water than each girl does.\n\nPasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.",
    "tutorial": "This problem can be solved in different ways too. We consider the simplest solution whici fits in the given restrictions. At first we sort all cups in non-decreasing order of their volumes. Due to reasons of greedy it is correct thatsorted cups with numbers from $1$ to $n$ will be given to girls and cups with numbers from $n + 1$ to $2 * n$ will be given to boys. Now we need to use binary search and iterate on volume of tea which will be poured for every girl. Let on current iteration $(lf + rg) / 2 = mid$. Then if for $i$ from $1$ to $n$ it is correct that $mid  \\le  a_{i}$ and for $i$ from $n + 1$ to $2 * n$ it is correct that $2 * mid  \\le  a_{i}$ then we need to make $lf = mid$. Else we need to make $rg = mid$. Asymptotic behavior of this solution - O($n * log(n)$) where $n$ - count of cups.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "557",
    "index": "C",
    "title": "Arthur and Table",
    "statement": "Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.\n\nIn total the table Arthur bought has $n$ legs, the length of the $i$-th leg is $l_{i}$.\n\nArthur decided to make the table stable and remove some legs. For each of them Arthur determined number $d_{i}$ — the amount of energy that he spends to remove the $i$-th leg.\n\nA table with $k$ legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with $5$ legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.\n\nYour task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.",
    "tutorial": "This problem can be solved as follows. At first we need to sort all legs in non-descending order of their length. Also we need to use array $cnt[]$. Let iterate on length of legs (which will stand table) from the least. Let this lenght is equals to $maxlen$. Count of units of energy which we need for this we will store in variable $cur$. Obviously that we must unscrew all legs with lenght more than $maxlen$. For calculate count of units of energy for doing it we can use array with suffix sums, for exapmle. Then we add this value to $cur$. If count of legs with length $maxlen$ is not strictly greater than the number of the remaining legs then we need to unscrew some count of legs with length less than $maxlen$. For this we can use array $cnt[]$. In $cnt[i]$ we will store count of legs with difficulty of unscrew equals to $i$. In this array will store information about legs which already viewed. We will iterate on difficulty of unscrew from one and unscrew legs with this difficulties (and add this difficulties to variable $cur$) while count of legs with length $maxlen$ will not be strictly greater than the number of the remaining legs. When it happens we need to update answer with variable $cur$. Asymptotic behavior of this solution - O($n * d$), where $n$ - count of legs and $d$ - difference between maximal and minimal units of energy which needed to unscrew some legs.",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "557",
    "index": "D",
    "title": "Vitaly and Cycle",
    "statement": "After Vitaly was expelled from the university, he became interested in the graph theory.\n\nVitaly especially liked the cycles of an odd length in which each vertex occurs at most once.\n\nVitaly was wondering how to solve the following problem. You are given an undirected graph consisting of $n$ vertices and $m$ edges, not necessarily connected, without parallel edges and loops. You need to find $t$ — the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find $w$ — the number of ways to add $t$ edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.\n\nTwo ways to add edges to the graph are considered equal if they have the same sets of added edges.\n\nSince Vitaly does not study at the university, he asked you to help him with this task.",
    "tutorial": "To solve this problem we can use dfs which will check every connected component of graph on bipartite. It is clearly that count of edges which we need to add in graph to get the odd cycle is no more than three. Answer to this problem is three if count of edges in graph is zero. Then the number of ways to add three edges in graph to make odd cycle is equals to $n * (n - 1) * (n - 2) / 6$ where $n$ - count of vertices in graph. Answer to this problem is two if there is no connected component with number of vertices more than two. Then the number of ways to add two edges in graph to make odd cycle is equals to $m * (n - 2)$ where $m$ - number of edges in graph. Now we have one case when there is at least one connected component with number of vertices more than two. Now we need to use dfs and try to split every component in two part. If for some component we can't do it that means that graph already has odd cycle and we need to print $\"0$ $1\"$ and we can now finish our algorithm. If all connected components in graph are bipartite then we need to iterate on them. Let $cnt_{1}$ is the count of vertices in one part of current component and $cnt_{2}$ - count of vertices in the other part. If number of vertices in this component more than two we need to add to answer $cnt_{1} * (cnt_{1} - 1) / 2$ and $cnt_{2} * (cnt_{2} - 1) / 2$. Asymptotic behavior of this solution - O($n + m$), where $n$ - number of vertices in graph and $m$ - number of edges.",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "557",
    "index": "E",
    "title": "Ann and Half-Palindrome",
    "statement": "Tomorrow Ann takes the hardest exam of programming where she should get an excellent mark.\n\nOn the last theoretical class the teacher introduced the notion of a half-palindrome.\n\nString $t$ is a half-palindrome, if for all the odd positions $i$ ($1\\leq i\\leq{\\frac{i|+1}{2}}$) the following condition is held: $t_{i} = t_{|t| - i + 1}$, where $|t|$ is the length of string $t$ if positions are indexed from $1$. For example, strings \"abaa\", \"a\", \"bb\", \"abbbaa\" are half-palindromes and strings \"ab\", \"bba\" and \"aaabaa\" are not.\n\nAnn knows that on the exam she will get string $s$, consisting only of letters a and b, and number $k$. To get an excellent mark she has to find the $k$-th in the lexicographical order string among all substrings of $s$ that are half-palyndromes. Note that each substring in this order is considered as many times as many times it occurs in $s$.\n\nThe teachers guarantees that the given number $k$ doesn't exceed the number of substrings of the given string that are half-palindromes.\n\nCan you cope with this problem?",
    "tutorial": "This problem can be solved with help of dynamic programming. At first we calculate matrix $good[][]$. In $good[i][j]$ we put $true$, if substring from position $i$ to position $j$ half-palindrome. Else we put in $good[i][j]false$. We can do it with iterating on \"middle\" of half-palindrome and expanding it to the left and to the right. There are $4$ cases of \"middle\" but we omit it because they are simple enough. Now we need to use Trie and we will put in it suffixes of given string. Also we will store array $cnt[]$. In $cnt[v]$ we will store number of half-palindromes which ends in vertex $v$ of our Trie. Let now we put in tree suffix which starts in position $i$, current symbol of string which we put is in position $j$ and we go in vertex $v$ of out Trie. Then if $good[i][j] = true$ we add one to $cnt[v]$. Now with help of dfs let calculate for every vertex $sum[v]$ - sum of numbers which stored in array $cnt[]$ for vertex $v$ and for vertices in all subtrees of vertex $v$. It is left only to restore answer. Start from root of our Trie. We will store answer in variable $ans$. In variable $k$ store number of required substring. Let now we in vertex $v$, by letter $'a'$ we can go in vertex $to_{a}$ and by letter $'b'$ - in vertex $to_{b}$. Then if $sum[to_{a}]  \\le  k$ we make $ans + = 'a'$ and go in vertex $to_{a}$ of our Trie. Else we need to make as follows: $k$ - $= sum[to_{a}]$, $ans + = 'b'$ and go in vertex $to_{b}$ of our Trie. When $k$ will be $ \\le  0$ print resulting string $ans$ and finish algorithm. Asymptotic behavior of this solution - O($szalph * n^{2}$) where $szalph$ - size of input alphabet (in this problem it equals to two) and $n$ - length of given string.",
    "tags": [
      "data structures",
      "dp",
      "graphs",
      "string suffix structures",
      "strings",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "558",
    "index": "A",
    "title": "Lala Land and Apple Trees",
    "statement": "Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.\n\nLala Land has exactly $n$ apple trees. Tree number $i$ is located in a position $x_{i}$ and has $a_{i}$ apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in $x = 0$ position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.\n\nWhat is the maximum number of apples he can collect?",
    "tutorial": "Let's divide all the trees into two different groups, trees with a positive position and trees with a negative position. Now There are mainly two cases: If the sizes of the two groups are equal. Then we can get all the apples no matter which direction we choose at first. If the size of one group is larger than the other. Then the optimal solution is to go to the direction of the group with the larger size. If the size of the group with the smaller size is $m$ then we can get apples from all the $m$ apple trees in it, and from the first $m + 1$ trees in the other group. So we can sort each group of trees by the absolute value of the trees position and calculate the answer as mentioned above. Time complexity: $O(n\\ l o g\\ n)$",
    "code": "\"#include <iostream>\\n#include <cstdio>\\n#include <algorithm>\\n#include <cstring>\\n#include <string>\\n#include <cctype>\\n#include <stack>\\n#include <queue>\\n#include <vector>\\n#include <map>\\n#include <sstream>\\n#include <cmath>\\n#include <limits>\\n#include <utility>\\n#include <iomanip>\\n#include <set>\\n#include <numeric>\\n#include <cassert>\\n#include <ctime>\\n\\n#define INF_MAX 2147483647\\n#define INF_MIN -2147483647\\n#define INF_LL 9223372036854775807LL\\n#define INF 2000000000\\n#define PI acos(-1.0)\\n#define EPS 1e-8\\n#define LL long long\\n#define mod 1000000007\\n#define pb push_back\\n#define mp make_pair\\n#define f first\\n#define s second\\n#define setzero(a) memset(a,0,sizeof(a))\\n#define setdp(a) memset(a,-1,sizeof(a))\\n#define bits(a) __builtin_popcount(a)\\n\\nusing namespace std;\\n\\nvector<pair<int, int> > a, b;\\n\\nint main()\\n{\\n  ios_base::sync_with_stdio(0);\\n  //freopen(\\\"lca.in\\\", \\\"r\\\", stdin);\\n  //freopen(\\\"lca.out\\\", \\\"w\\\", stdout);\\n  int n, x, y;\\n  cin >> n;\\n  for(int i=0;i<n;i++)\\n  {\\n    cin >> x >> y;\\n    if(x < 0) a.pb(mp(x, y));\\n    else b.pb(mp(x, y));\\n  }\\n  sort(a.begin(), a.end(), greater<pair<int, int> >());\\n  sort(b.begin(), b.end());\\n  int res = 0;\\n  if(a.size() == b.size())\\n  {\\n    for(int i=0;i<a.size();i++)\\n      res+=a[i].s + b[i].s;\\n  }\\n  else if(a.size() > b.size())\\n  {\\n    for(int i=0;i<b.size();i++)\\n      res+=a[i].s + b[i].s;\\n    res+=a[b.size()].s;\\n  }\\n  else\\n  {\\n    for(int i=0;i<a.size();i++)\\n      res+=a[i].s + b[i].s;\\n    res+=b[a.size()].s;\\n  }\\n  cout << res;\\n  return 0;\\n}\"",
    "tags": [
      "brute force",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "558",
    "index": "B",
    "title": "Amr and The Large Array",
    "statement": "Amr has got a large array of size $n$. Amr doesn't like large arrays so he intends to make it smaller.\n\nAmr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.\n\nHelp Amr by choosing the smallest subsegment possible.",
    "tutorial": "First observation in this problem is that if the subarray chosen has $x$ as a value that has the maximum number of occurrences among other elements, then the subarray should be $[x, ..., x]$. Because if the subarray begins or ends with another element we can delete it and make the subarray smaller. So, Let's save for every distinct element $x$ in the array three numbers, the smallest index $i$ such that $a_{i} = x$, the largest index $j$ such that $a_{j} = x$ and the number of times it appears in the array. And between all the elements that has maximum number of occurrences we want to minimize $j - i + 1$ (i.e. the size of the subarray). Time complexity: $O(n)$",
    "code": "\"#include <iostream>\\n#include <cstdio>\\n#include <algorithm>\\n#include <cstring>\\n#include <string>\\n#include <cctype>\\n#include <stack>\\n#include <queue>\\n#include <vector>\\n#include <map>\\n#include <sstream>\\n#include <cmath>\\n#include <limits>\\n#include <utility>\\n#include <iomanip>\\n#include <set>\\n#include <numeric>\\n#include <cassert>\\n#include <ctime>\\n\\n#define INF_MAX 2147483647\\n#define INF_MIN -2147483647\\n#define INF_LL 9223372036854775807LL\\n#define INF 2000000000\\n#define PI acos(-1.0)\\n#define EPS 1e-8\\n#define LL long long\\n#define mod 1000000007\\n#define pb push_back\\n#define mp make_pair\\n#define f first\\n#define s second\\n#define setzero(a) memset(a,0,sizeof(a))\\n#define setdp(a) memset(a,-1,sizeof(a))\\n#define bits(a) __builtin_popcount(a)\\n\\nusing namespace std;\\n\\nint m[1000005], L[1000005];\\n\\nint main()\\n{\\n  //ios_base::sync_with_stdio(0);\\n  //freopen(\\\"lca.in\\\", \\\"r\\\", stdin);\\n  //freopen(\\\"lca.out\\\", \\\"w\\\", stdout);\\n  int n, x, maxi = 0, mini = INF, ch = -1;\\n  scanf(\\\"%d\\\", &n);\\n  for(int i=0;i<n;i++)\\n  {\\n    scanf(\\\"%d\\\", &x);\\n    if(m[x] == 0)\\n    {\\n      L[x] = i;\\n      m[x] = 1;\\n    }\\n    else m[x]++;\\n    if(m[x] > maxi)\\n    {\\n      maxi = m[x];\\n      mini = i - L[x] + 1;\\n      ch = L[x] + 1;\\n    }\\n    else if(m[x] == maxi && i - L[x] + 1 < mini)\\n    {\\n      mini = i - L[x] + 1;\\n      ch = L[x] + 1;\\n    }\\n  }\\n  cout << ch << \\\" \\\" << ch + mini - 1;\\n  return 0;\\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "558",
    "index": "C",
    "title": "Amr and Chemistry",
    "statement": "Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.\n\nAmr has $n$ different types of chemicals. Each chemical $i$ has an initial volume of $a_{i}$ liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.\n\nTo do this, Amr can do two different kind of operations.\n\n- Choose some chemical $i$ and double its current volume so the new volume will be $2a_{i}$\n- Choose some chemical $i$ and divide its volume by two (integer division) so the new volume will be $\\textstyle{\\left|{\\frac{a_{i}}{2}}\\right\\rangle}$\n\nSuppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?",
    "tutorial": "Let the maximum number in the array be $max$. Clearly, changing the elements of the array to any element larger than $max$ won't be optimal, because the last operation is for sure multiplying all the elements of the array by two. And not doing this operation is of course a better answer. Now we want to count the maximum number of distinct elements that can be reached from some element $a_{i}$ that are not larger than $max$. Consider an element $a_{i}$ that has a zero in the first bit of its binary representation. If we divided the number by two and the multiplied it by two we will get the original number again. But if it has a one, the resulting number will be different. So, for counting the maximum number of distinct elements we will assume $a_{i} = x$ where $x$ has only ones in its binary representation. From $x$ we can only reach elements that have a prefix of ones in its binary representation, and the other bits zeros (e.g. ${0, 1, 10, 11, 100, 110, 111, 1000, ...}$ ). Let's assume $max$ has $m$ bits in its binary representation, then $x$ can reach exactly ${\\frac{m*(m+1)}{2}}\\ +\\ 1$ distinct elements. So, from each element in the array $a_{i}$ we can reach at most ${\\frac{m*(m+1)}{2}}\\ +\\ 1$ elements. So, Let's generate the numbers that can be reached from each element $a_{i}$ using bfs to get minimum number of operations. And between all the numbers that are reachable from all the $n$ elements let's minimize the total number of operations. Time complexity: $O(n*m^{2}+m a x)$",
    "code": "\"#include <iostream>\\n#include <cstdio>\\n#include <algorithm>\\n#include <cstring>\\n#include <string>\\n#include <cctype>\\n#include <stack>\\n#include <queue>\\n#include <vector>\\n#include <map>\\n#include <sstream>\\n#include <cmath>\\n#include <limits>\\n#include <utility>\\n#include <iomanip>\\n#include <set>\\n#include <numeric>\\n#include <cassert>\\n#include <ctime>\\n\\n#define INF_MAX 2147483647\\n#define INF_MIN -2147483647\\n#define INF_LL 9223372036854775807LL\\n#define INF 2000000000\\n#define PI acos(-1.0)\\n#define EPS 1e-8\\n#define LL long long\\n#define mod 1000000007\\n#define pb push_back\\n#define mp make_pair\\n#define f first\\n#define s second\\n#define setzero(a) memset(a,0,sizeof(a))\\n#define setdp(a) memset(a,-1,sizeof(a))\\n#define bits(a) __builtin_popcount(a)\\n\\nusing namespace std;\\n\\nint cnt[100005], vis[100005], steps[100005];\\n\\nint main()\\n{\\n  //ios_base::sync_with_stdio(0);\\n  //freopen(\\\"lca.in\\\", \\\"r\\\", stdin);\\n  //freopen(\\\"lca.out\\\", \\\"w\\\", stdout);\\n  int n, res = INF, x, y;\\n  scanf(\\\"%d\\\", &n);\\n  for(int i=1;i<=n;i++)\\n  {\\n    scanf(\\\"%d\\\", &x);\\n    queue<pair<int, int> > q;\\n    q.push(mp(x, 0));\\n    while(!q.empty())\\n    {\\n      x = q.front().f;\\n      y = q.front().s;\\n      q.pop();\\n      if(x > 100003) continue;\\n      if(vis[x] == i) continue;\\n      vis[x] = i;\\n      steps[x]+=y;\\n      cnt[x]++;\\n      q.push(mp(x * 2, y + 1));\\n      q.push(mp(x / 2, y + 1));\\n    }\\n  }\\n  for(int i=0;i<=100000;i++)\\n    if(cnt[i] == n)\\n      if(res > steps[i])\\n        res = steps[i];\\n  printf(\\\"%d\\\", res);\\n  return 0;\\n}\"",
    "tags": [
      "brute force",
      "graphs",
      "greedy",
      "math",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "558",
    "index": "D",
    "title": "Guess Your Way Out! II",
    "statement": "Amr bought a new video game \"Guess Your Way Out! II\". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height $h$. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.\n\nLet's index all the nodes of the tree such that\n\n- The root is number $1$\n- Each internal node $i$ ($i ≤ 2^{h - 1} - 1$) will have a left child with index = $2i$ and a right child with index = $2i + 1$\n\nThe level of a node is defined as $1$ for a root, or $1$ + level of parent of the node otherwise. The vertices of the level $h$ are called leaves. The exit to the maze is located at some leaf node $n$, the player doesn't know where the exit is so he has to guess his way out!\n\nIn the new version of the game the player is allowed to ask questions on the format \"Does the $ancestor(exit, i)$ node number belong to the range $[L, R]$?\". Here $ancestor(v, i)$ is the ancestor of a node $v$ that located in the level $i$. The game will answer with \"Yes\" or \"No\" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.\n\nAmr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.",
    "tutorial": "First, each query in the level $i$ from $L$ to $R$ can be transmitted into level $i + 1$ from $L * 2$ to $R * 2 + 1$, so, we can transform each query to the last level. Let's maintain a set of correct ranges such that the answer is contained in one of them. At the beginning we will assume that the answer is in the range $[2^{h - 1}, 2^{h} - 1]$ inclusive. Now Let's process the queries. If the query's answer is yes, then we want to get the intersection of this query's range with the current set of correct ranges, and update the set with the resulting set. If the query's answer is no, we want to exclude the query's range from the current set of correct ranges, and update the set with the resulting set. After we finish processing the queries, if the set of correct ranges is empty, then clearly the game cheated. Else if the set has only one correct range $[L, R]$ such that $L = R$ then we've got an answer. Otherwise there are multiple exit candidates and the answer can't be determined uniquely using the current data. We will have to use stl::set data structure to make updating the ranges faster. In each yes query we delete zero or more ranges. In each no query we may add one range if we split a correct range, so worst case will be linear in queries count. Time complexity: $O(h\\ast q+q\\;l o g\\ q)$",
    "code": "\"#include <iostream>\\n#include <cstdio>\\n#include <algorithm>\\n#include <cstring>\\n#include <string>\\n#include <cctype>\\n#include <stack>\\n#include <queue>\\n#include <vector>\\n#include <map>\\n#include <sstream>\\n#include <cmath>\\n#include <limits>\\n#include <utility>\\n#include <iomanip>\\n#include <set>\\n#include <numeric>\\n#include <cassert>\\n#include <ctime>\\n\\n#define INF_MAX 2147483647\\n#define INF_MIN -2147483647\\n#define INF_LL 9223372036854775807LL\\n#define INF 2000000000\\n#define PI acos(-1.0)\\n#define EPS 1e-8\\n#define LL long long\\n#define mod 1000000007\\n#define pb push_back\\n#define mp make_pair\\n#define f first\\n#define s second\\n#define setzero(a) memset(a,0,sizeof(a))\\n#define setdp(a) memset(a,-1,sizeof(a))\\n#define bits(a) __builtin_popcount(a)\\n\\nusing namespace std;\\n\\nset<pair<LL, LL> > s;\\nbool test;\\n\\nvoid solve(LL &xx, LL &yy, bool yes)\\n{\\n  set<pair<LL, LL> >::iterator it = s.lower_bound(mp(xx, xx));\\n  set<pair<LL, LL> >::iterator it2 = s.lower_bound(mp(yy, yy));\\n  if(it == s.end())\\n    it--;\\n  if(it2 == s.end())\\n    it2--;\\n  pair<LL, LL> L = *it, R = *it2;\\n  if(yes)\\n  {\\n    if(R.s < xx)\\n    {\\n      test = false;\\n      return;\\n    }\\n    if(L.f > yy && it == s.begin())\\n    {\\n      test = false;\\n      return;\\n    }\\n    if(L.f > xx && it == s.begin())\\n    {\\n      if(R.f > yy)\\n      {\\n        it2--;\\n        R = *it2;\\n      }\\n      L = mp(R.f, min(yy, R.s));\\n      it = it2;\\n      while(it2 != s.end())\\n      {\\n        it++;\\n        s.erase(it2);\\n        it2 = it;\\n      }\\n      s.insert(L);\\n    }\\n    else\\n    {\\n      if(R.f > yy)\\n      {\\n        it2--;\\n        R = *it2;\\n      }\\n      if(L.f > xx)\\n      {\\n        it--;\\n        L = *it;\\n      }\\n      if(L.s < xx)\\n      {\\n        if(it == it2)\\n        {\\n          test = false;\\n          return;\\n        }\\n        it++;\\n        L = *it;\\n      }\\n      if(it == it2)\\n      {\\n        L = mp(max(xx, L.f), min(yy, R.s));\\n        s.clear();\\n        s.insert(L);\\n        return;\\n      }\\n      L = mp(max(xx, L.f), L.s);\\n      R = mp(R.f, min(yy, R.s));\\n      set<pair<LL, LL> >::iterator it3 = it, it4;\\n      it4 = it3;\\n      while(1)\\n      {\\n        if(it3 == it)\\n        {\\n          s.erase(it);\\n          break;\\n        }\\n        it4++;\\n        s.erase(it3);\\n        it3 = it4;\\n      }\\n      it3 = it2;\\n      it4 = it3;\\n      while(it3 != s.end())\\n      {\\n        it4++;\\n        s.erase(it3);\\n        it3 = it4;\\n      }\\n      s.insert(L);\\n      s.insert(R);\\n    }\\n  }\\n  else\\n  {\\n    if(R.s < xx)\\n      return;\\n    if(L.f > yy && it == s.begin())\\n      return;\\n    if(L.f > xx && it == s.begin())\\n    {\\n      if(R.f > yy)\\n      {\\n        it2--;\\n        R = *it2;\\n      }\\n      L = mp(yy + 1, R.s);\\n      it = it2;\\n      while(1)\\n      {\\n        if(it2 == s.begin())\\n        {\\n          s.erase(it2);\\n          break;\\n        }\\n        it--;\\n        s.erase(it2);\\n        it2 = it;\\n      }\\n      if(L.f <= L.s)\\n        s.insert(L);\\n    }\\n    else\\n    {\\n      if(R.f > yy)\\n      {\\n        it2--;\\n        R = *it2;\\n      }\\n      if(L.f > xx)\\n      {\\n        it--;\\n        L = *it;\\n      }\\n      if(L.s < xx)\\n      {\\n        if(it == it2) return;\\n        it++;\\n        L = *it;\\n      }\\n      bool can = true;\\n      if(it == it2)\\n      {\\n        s.erase(it);\\n        can = false;\\n      }\\n      L = mp(L.f, xx - 1);\\n      R = mp(yy + 1, R.s);\\n      set<pair<LL, LL> >::iterator it3 = it;\\n      while(can)\\n      {\\n        if(it == it2)\\n        {\\n          s.erase(it);\\n          break;\\n        }\\n        it3++;\\n        s.erase(it);\\n        it = it3;\\n      }\\n      if(L.f <= L.s)\\n        s.insert(L);\\n      if(R.f <= R.s)\\n        s.insert(R);\\n    }\\n    test &= (s.size() != 0);\\n  }\\n}\\n\\nint main()\\n{\\n  //ios_base::sync_with_stdio(0);\\n  //freopen(\\\"lca.in\\\", \\\"r\\\", stdin);\\n  //freopen(\\\"lca.out\\\", \\\"w\\\", stdout);\\n  int n, q, lev;\\n  LL x, y;\\n  int yes;\\n  scanf(\\\"%d %d\\\", &n, &q);\\n  s.insert(mp(1LL << (n - 1), (1LL << n) - 1));\\n  test = true;\\n  while(q-- && test)\\n  {\\n    scanf(\\\"%d %I64d %I64d %d\\\", &lev, &x, &y, &yes);\\n    for(int i=lev;i<n && test;i++)\\n    {\\n      x = x * 2;\\n      y = y * 2 + 1;\\n    }\\n    solve(x, y, yes);\\n  }\\n  if(!test)\\n    cout << \\\"Game cheated!\\\";\\n  else\\n  {\\n    pair<LL, LL> res;\\n    if(s.size() == 1)\\n    {\\n      res = *s.lower_bound(mp(0, 0));\\n      if(res.f != res.s) test = false;\\n    }\\n    else test = false;\\n    if(!test)\\n      cout << \\\"Data not sufficient!\\\";\\n    else cout << res.f;\\n  }\\n  return 0;\\n}\"",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "558",
    "index": "E",
    "title": "A Simple Task",
    "statement": "This task is very simple. Given a string $S$ of length $n$ and $q$ queries each query is on the format $i$ $j$ $k$ which means sort the substring consisting of the characters from $i$ to $j$ in non-decreasing order if $k = 1$ or in non-increasing order if $k = 0$.\n\nOutput the final string after applying the queries.",
    "tutorial": "In this problem we will be using counting sort. So for each query we will count the number of occurrences for each character, and then update the range like this But this is too slow. We want a data structure that can support the above operations in appropriate time. Let's make 26 segment trees each one for each character. Now for each query let's get the count of every character in the range, and then arrange them and update each segment tree with the new values. We will have to use lazy propagation technique for updating ranges. Time complexity: $O(s z*q*\\;l o g\\;n)$ where sz is the size of the alphabet (i.e. = 26).",
    "code": "\"#include <iostream>\\n#include <cstdio>\\n#include <algorithm>\\n#include <cstring>\\n#include <string>\\n#include <cctype>\\n#include <stack>\\n#include <queue>\\n#include <vector>\\n#include <map>\\n#include <sstream>\\n#include <cmath>\\n#include <limits>\\n#include <utility>\\n#include <iomanip>\\n#include <set>\\n#include <numeric>\\n#include <cassert>\\n#include <ctime>\\n\\n#define INF_MAX 2147483647\\n#define INF_MIN -2147483647\\n#define INF_LL 9223372036854775807LL\\n#define INF 2000000000\\n#define PI acos(-1.0)\\n#define EPS 1e-8\\n#define LL long long\\n#define mod 1000000007\\n#define pb push_back\\n#define mp make_pair\\n#define f first\\n#define s second\\n#define setzero(a) memset(a,0,sizeof(a))\\n#define setdp(a) memset(a,-1,sizeof(a))\\n#define bits(a) __builtin_popcount(a)\\n\\nusing namespace std;\\n\\nint tree[400005][27], lazy[400005][27];\\nchar s[100005];\\n\\nvoid build(int i,int L,int R)\\n{\\n  if(L == R)\\n  {\\n    tree[i][s[L] - 'a'] = 1;\\n    for(int j=0;j<26;j++)\\n      lazy[i][j] = -1;\\n    return ;\\n  }\\n  build(i*2 + 1, L, (L + R) / 2);\\n  build(i*2 + 2, (L + R) / 2 + 1, R);\\n  for(int j=0;j<26;j++)\\n  {\\n    lazy[i][j] = -1;\\n    tree[i][j] = tree[i*2 + 1][j] + tree[i*2 + 2][j];\\n  }\\n}\\n\\nvoid update(int i, int L, int R, int x, int y, int val, int j)\\n{\\n  if(lazy[i][j] != -1)\\n  {\\n    tree[i][j] = lazy[i][j] * (R - L + 1);\\n    if(L != R)\\n    {\\n      lazy[i*2+1][j] = lazy[i][j];\\n      lazy[i*2+2][j] = lazy[i][j];\\n    }\\n    lazy[i][j] = -1;\\n  }\\n  if(L >= x && R <= y)\\n  {\\n    lazy[i][j] = val;\\n    tree[i][j] = lazy[i][j] * (R - L + 1);\\n    if(L != R)\\n    {\\n      lazy[i*2+1][j] = lazy[i][j];\\n      lazy[i*2+2][j] = lazy[i][j];\\n    }\\n    lazy[i][j] = -1;\\n    return;\\n  }\\n  if(L > y || R < x)\\n    return;\\n  update(i*2 + 1, L, (L + R) / 2, x, y, val, j);\\n  update(i*2 + 2, (L + R) / 2 + 1, R, x, y, val, j);\\n  tree[i][j] = tree[i*2 + 1][j] + tree[i*2 + 2][j];\\n}\\n\\nint query(int i, int L, int R, int x, int y, int j)\\n{\\n  if(lazy[i][j] != -1)\\n  {\\n    tree[i][j] = lazy[i][j] * (R - L + 1);\\n    if(L != R)\\n    {\\n      lazy[i*2+1][j] = lazy[i][j];\\n      lazy[i*2+2][j] = lazy[i][j];\\n    }\\n    lazy[i][j] = -1;\\n  }\\n  if(L >= x && R <= y)\\n    return tree[i][j];\\n  if(L > y || R < x)\\n    return 0;\\n  return query(i*2 + 1, L, (L + R) / 2, x, y, j) + query(i*2 + 2, (L + R) / 2 + 1, R, x, y, j);\\n}\\n\\nvoid get(int i, int L, int R, int j)\\n{\\n  if(lazy[i][j] != -1)\\n  {\\n    tree[i][j] = lazy[i][j] * (R - L + 1);\\n    if(L != R)\\n    {\\n      lazy[i*2+1][j] = lazy[i][j];\\n      lazy[i*2+2][j] = lazy[i][j];\\n    }\\n    lazy[i][j] = -1;\\n  }\\n  if(!tree[i][j])\\n    return ;\\n  if(L == R)\\n  {\\n    s[L] = j + 'a';\\n    return;\\n  }\\n  get(i*2 + 1, L, (L + R) / 2, j);\\n  get(i*2 + 2, (L + R) / 2 + 1, R, j);\\n}\\n\\nint cnt[26];\\n\\nint main()\\n{\\n  //ios_base::sync_with_stdio(0);\\n  //freopen(\\\"test0.txt\\\", \\\"r\\\", stdin);\\n  //freopen(\\\"lca.out\\\", \\\"w\\\", stdout);\\n  int n, q, x, y, up;\\n  scanf(\\\"%d %d\\\", &n, &q);\\n  scanf(\\\"%s\\\", s);\\n  build(0, 0, n - 1);\\n  for(int i=0;i<q;i++)\\n  {\\n    scanf(\\\"%d %d %d\\\", &x, &y, &up);\\n    x--, y--;\\n    for(int j=0;j<26;j++)\\n      cnt[j] = query(0, 0, n - 1, x, y, j);\\n    int curr = x;\\n    if(!up) curr = y;\\n    for(int j=0;j<26;j++)\\n    {\\n      if(!cnt[j]) continue;\\n      update(0, 0, n - 1, x, y, 0, j);\\n      if(up)\\n      {\\n        update(0, 0, n - 1, curr, curr + cnt[j] - 1, 1, j);\\n        curr+=cnt[j];\\n      }\\n      else\\n      {\\n        update(0, 0, n - 1, curr - cnt[j] + 1, curr, 1, j);\\n        curr-=cnt[j];\\n      }\\n    }\\n  }\\n  for(int i=0;i<26;i++)\\n    get(0, 0, n - 1, i);\\n  printf(\\\"%s\\\", s);\\n  return 0;\\n}\"",
    "tags": [
      "data structures",
      "sortings",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "559",
    "index": "A",
    "title": "Gerald's Hexagon",
    "statement": "Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to $120^{\\circ}$. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.\n\nHe painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.",
    "tutorial": "Let's consider regular triangle with sides of $k$ Let's split it to regular triangles with sides of $1$ by lines parallel to the sides. Big triange area $k^{2}$ times larger then small triangles area and therefore big triangle have splitted by $k^{2}$ small triangles. If we join regular triangles to sides $a_{1}, a_{3}$ and $a_{5}$ of hexagon we get a triangle sides of $a_{1} + a_{2} + a_{3}$. Then hexagon area is equals to $(a_{1} + a_{2} + a_{3})^{2} - a_{1}^{2} - a_{3}^{2} - a_{5}^{2}$.",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "559",
    "index": "B",
    "title": "Equivalent Strings",
    "statement": "Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings $a$ and $b$ of equal length are called equivalent in one of the two cases:\n\n- They are equal.\n- If we split string $a$ into two halves of the same size $a_{1}$ and $a_{2}$, and string $b$ into two halves of the same size $b_{1}$ and $b_{2}$, then one of the following is correct:\n\n- $a_{1}$ is equivalent to $b_{1}$, and $a_{2}$ is equivalent to $b_{2}$\n- $a_{1}$ is equivalent to $b_{2}$, and $a_{2}$ is equivalent to $b_{1}$\n\nAs a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.\n\nGerald has already completed this home task. Now it's your turn!",
    "tutorial": "Let us note that \"equivalence\" described in the statements is actually equivalence relation, it is reflexively, simmetrically and transitive. It is meant that set of all string is splits to equivalence classes. Let's find lexicographic minimal strings what is equivalent to first and to second given string. And then check if its are equals. It is remain find the lexicographic minimal strings what is equivalent to given. For instance we can do it such a way: Every recursive call time works is $O(n)$ (where $n$ is length of strings) and string splitten by two twice smaller strings. Therefore time of work this function is $O(n\\log(n))$, where $n$ is length of strings.",
    "code": "String smallest(String s) {\n    if (s.length() % 2 == 1) return s;\n    String s1 = smallest(s.substring(0, s.length()/2));\n    String s2 = smallest(s.substring(s.length()/2), s.length());\n    if (s1 < s2) return s1 + s2;\n    else return s2 + s1;\n}",
    "tags": [
      "divide and conquer",
      "hashing",
      "sortings",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "559",
    "index": "C",
    "title": "Gerald and Giant Chess",
    "statement": "Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an $h × w$ field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?\n\nThe pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.",
    "tutorial": "Let's denote black cells ad $A_{0}, A_{1}, ..., A_{k - 1}$ . First of all, we have to sort black cells in increasing order of (row, column). If cell $x$ available from cell $y$, $x$ stands after $y$ in this order. Let $A_{k} = (h, w)$. Now we have to find number of paths from $(1, 1)$ to $A_{k}$ avoiding $A_{0}, ..., A_{k - 1}$. Let $D_{i}$ is number of paths from $(1, 1)$ to $A_{i}$ avoiding $A_{0}, ..., A_{i - 1}$. It's easy to see that $D_{k}$ is answer for the problem. Number of all paths from $(1, 1)$ to $(x_{i}, y_{i})$ is $C_{x_{i}+y_{i}-2}^{x_{i}-1}$. We should subtract from that value all paths containing at least one of previous black cells. We should enumerate first black cell on the path. It could be one of previous cell that is not below or righter than $A_{i}$. For each such cell $A_{j}$ we have to subtract number of paths from $(1, 1)$ to $A_{j}$ avoiding black cells multiplied by number of all paths from $A_{j}$ to $A_{i}$. We have to calculate factorials of numbers from $1$ to $2 \\cdot 10^{5}$ and inverse elements of them modulo $10^{9} + 7$ for calculating binomial coefficients.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "559",
    "index": "D",
    "title": "Randomizer",
    "statement": "Gerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows.\n\nA Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a \\textbf{basic polygon}. If you shake a Randomizer, it draws some nondegenerate (i.e. having a non-zero area) convex polygon with vertices at some vertices of the \\textbf{basic polygon}. The result of the roll (more precisely, the result of the shaking) is considered to be the number of points with integer coordinates, which were strictly inside (the points on the border are not considered) the selected polygon. Now Gerald is wondering: what is the expected result of shaking the Randomizer?\n\nDuring the shaking the Randomizer considers all the possible non-degenerate convex polygons with vertices at the vertices of the \\textbf{basic polygon}. Let's assume that there are $k$ versions of the polygons. Then the Randomizer chooses each of them with probability $\\frac{1}{k}$.",
    "tutorial": "We can use Pick's theorem for calculate integer points number in every polygon. Integer points number on the segment between points $(0, 0)$ and $(a, b)$ one can calculate over $GCD(a, b)$. Integer points number in some choosen polynom is integer points number in basic polynom minus integer points number in segmnent of basic polynom separated by every segment of choosen polynom. Let consider every potencial segment of polygon. We can calculate integer points number in his segment and probability that we will meet it in choosen polygon. Probability of segment $A_{i}A_{i + k}$ is $\\frac{2^{n-k-1}-1}{2^{n}-1-n-\\frac{n(n-1)}{2}}$. Let use note that we can calculate only segments with $k < 60$ because of other segmnet propapility is too small.",
    "tags": [
      "combinatorics",
      "geometry",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "559",
    "index": "E",
    "title": "Gerald and Path",
    "statement": "The main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight.\n\nThe trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument.\n\nYou are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.",
    "tutorial": "Lighted part of walking trail is union of ligted intervals. Let's sort spotlights in increasing order of $a_{i}$. Consider some lighted interval $(a, b)$. It's lighted by spotlights with numbers ${l, l + 1, ..., r}$ for some $l$ and $r$ (\"substring\" of spotlights). Let $x_{0}, ..., x_{k}$ is all possible boundaries of lighted intervals (numbers $a_{i} - l_{i}$, $a_{i}$ and $a_{i} + l_{i}$). Imagine, that we know possible lighted intervals of all substrings of spotlights. Let $left[l][r][j]$ is least possible $i$ such that set of spotlights with numbers ${l, l + 1, ..., r}$ lighting $[x_{i}, x_{j}]$. With $left$ we can calculate value $best[R][i]$ maximum possible length of walking trail that could be lighted using first $L$ spotlights in such way that $x_{i}$ is rightmost lighted point. It's easy to do in $O(n^{4})$ because $b e s t[R][i]=\\operatorname*{max}_{l e f t\\vert i+1\\vert|R\\vert|i\\rangle,t}b e s t[l][t]+x_{i}-x_{l e f t\\vert i+1\\vert|R\\vert|i\\vert}$. Now all we have to do is calculate $left$. Consider some substring of spotlights $[l, r]$. Let all spotlights in the substring oriented in some way lighting some set of points. We could consider most left ($i$) and most right ($j$) lighted points, and left bound of first lighted interval ($t$). If set of lighted points is interval $t = j$. Consider how all the values change when we add spotlight $r + 1$ and choose its orientation. We have new lighted interval $[a, b]$ which is equal to $[a_{i} - l_{i}, a_{i}]$ or $[a_{i}, a_{i} + l_{i}]$. Now most left lighted point is $min(a, x_{i})$, most right is $max(b, x_{j})$. Right bound of leftmost lighted interval does not changes if $a > t$ or becomes equal to $b$, if $a  \\le  t$. Not for each $L$ we can calculate $dp[r][j][y]$ least possible $i$ that it's possible to orient spotlights from $[L, r]$ in such way that $x_{i}$ is most left lighted point $x_{j}$ is most right one and right bound of leftmost lighted interval is $x_{t}$. Thet it's easy to calculate $left[L][][]$. That part is done in $O(n^{4})$ too. +97 Sammarize 10 years ago 166",
    "tags": [
      "dp",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "560",
    "index": "A",
    "title": "Currency System in Geraldion",
    "statement": "A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?",
    "tutorial": "If there is a banlnot of value 1 then one can to express every sum of money. Otherwise one can't to express 1 and it is minimum unfortunate sum.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "560",
    "index": "B",
    "title": "Gerald is into Art",
    "statement": "Gerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an $a_{1} × b_{1}$ rectangle, the paintings have shape of a $a_{2} × b_{2}$ and $a_{3} × b_{3}$ rectangles.\n\nSince the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?",
    "tutorial": "It is easy to see that one can snuggle paintings to each other and to edge of board. For instance one can put one of painting right over other. Then height of two paintings equals to sum of two heights and width of two paintings is equals to maximum of two widths. Now we can just iterate orientation of paintings and board.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "566",
    "index": "A",
    "title": "Matching Names",
    "statement": "Teachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the \"Hobbit\" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.\n\nThere are $n$ students in a summer school. Teachers chose exactly $n$ pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym $b$ to a student with name $a$ as the length of the largest common prefix $a$ and $b$. We will represent such value as $\\operatorname{lcp}(a,b)$. Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.\n\nFind the matching between students and pseudonyms with the maximum quality.",
    "tutorial": "Form a trie from all names and pseudonyms. Mark with red all vertices corresponding to names, and with blue all vertices corresponding to the pseudonyms (a single vertex may be marked several times, possibly with different colors). Note that if we match a name $a$ and a pseudonym $b$, then the quality of such match is $lcp(a, b) = 1 / 2(2 * lcp(a, b)) = 1 / 2(|a| + |b| - (|a| - lcp(a, b)) - (|b| - lcp(a, b)))$, that is equal to a constant $1 / 2(|a| + |b|)$, with subtracted half of a length of a path between $a$ and $b$ over the trie. So, what we need is to connect all red vertices with blue vertices with paths of a minimum possible total length. This can be done with a following greedy procedure: if we have a vertex $v$ with $x$ red vertices and $y$ blue vertices in its subtree then we must match $min(x, y)$ red vertices of its subtree to $min(x, y)$ blue vertices of its subtree and leave the remaining $max(x, y) - min(x, y)$ ref or blue vertices to the level higher. The correctness of such algorithm may be easily shown by the next idea. Give each edge of each path a direction from a red vertex to a blue. If some edge recieves two different directions after this procedure, we may cross-change two paths through it so that their total length is reduced by two. So, we get a solution in $O(sumlen)$ where $sumlen$ is a total length of all names and pseudonyms.",
    "tags": [
      "dfs and similar",
      "strings",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "566",
    "index": "B",
    "title": "Replicating Processes",
    "statement": "A Large Software Company develops its own social network. Analysts have found that during the holidays, major sporting events and other significant events users begin to enter the network more frequently, resulting in great load increase on the infrastructure.\n\nAs part of this task, we assume that the social network is $4n$ processes running on the $n$ servers. All servers are absolutely identical machines, each of which has a volume of RAM of $1$ GB = $1024$ MB $^{(1)}$. Each process takes 100 MB of RAM on the server. At the same time, the needs of maintaining the viability of the server takes about $100$ more megabytes of RAM. Thus, each server may have up to $9$ different processes of social network.\n\nNow each of the $n$ servers is running exactly $4$ processes. However, at the moment of peak load it is sometimes necessary to replicate the existing $4n$ processes by creating $8n$ new processes instead of the old ones. More formally, there is a set of replication rules, the $i$-th ($1 ≤ i ≤ 4n$) of which has the form of $a_{i} → (b_{i}, c_{i})$, where $a_{i}$, $b_{i}$ and $c_{i}$ ($1 ≤ a_{i}, b_{i}, c_{i} ≤ n$) are the numbers of servers. This means that instead of an old process running on server $a_{i}$, there should appear two new copies of the process running on servers $b_{i}$ and $c_{i}$. The two new replicated processes can be on the same server (i.e., $b_{i}$ may be equal to $c_{i}$) or even on the same server where the original process was (i.e. $a_{i}$ may be equal to $b_{i}$ or $c_{i}$). During the implementation of the rule $a_{i} → (b_{i}, c_{i})$ first the process from the server $a_{i}$ is destroyed, then appears a process on the server $b_{i}$, then appears a process on the server $c_{i}$.\n\nThere is a set of $4n$ rules, destroying all the original $4n$ processes from $n$ servers, and creating after their application $8n$ replicated processes, besides, on each of the $n$ servers will be exactly $8$ processes. However, the rules can only be applied consecutively, and therefore the amount of RAM of the servers imposes limitations on the procedure for the application of the rules.\n\nAccording to this set of rules determine the order in which you want to apply all the $4n$ rules so that at any given time the memory of each of the servers contained at most $9$ processes (old and new together), or tell that it is impossible.",
    "tutorial": "This problem may be solved by simulating the replication process. Let's keep a list of all replications that may be applied by the current step. Apply an arbitrary replication, after that update a list by adding/removing all suitable or now unsuitable replications touching all affected on current step servers. The list of replications may be kept in a \"double-linked list\" data structure, that allows to add and remove elements to/from the set and to extract an arbitrary element of the set in $O(1)$. The proof of correctness of such algorithm is not hard and is left as an exercies (maybe it will appear here later). We got a solution in $O(n)$ operation (though, the constant hidden by $O$-notation is pretty large; the input size is already $12n$ numbers and the solution itself hides a constant $36$ or higher).",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "566",
    "index": "C",
    "title": "Logistical Questions",
    "statement": "Some country consists of $n$ cities, connected by a railroad network. The transport communication of the country is so advanced that the network consists of a minimum required number of $(n - 1)$ bidirectional roads (in the other words, the graph of roads is a tree). The $i$-th road that directly connects cities $a_{i}$ and $b_{i}$, has the length of $l_{i}$ kilometers.\n\nThe transport network is served by a state transporting company FRR (Fabulous Rail Roads). In order to simplify the price policy, it offers a single ride fare on the train. In order to follow the route of length $t$ kilometers, you need to pay $\\displaystyle{\\hat{\\overline{{2}}}}$ burles. Note that it is forbidden to split a long route into short segments and pay them separately (a special railroad police, or RRP, controls that the law doesn't get violated).\n\nA Large Software Company decided to organize a programming tournament. Having conducted several online rounds, the company employees determined a list of finalists and sent it to the logistical department to find a place where to conduct finals. The Large Software Company can easily organize the tournament finals in any of the $n$ cities of the country, so the the main factor in choosing the city for the last stage of the tournament is the total cost of buying tickets for all the finalists. We know that the $i$-th city of the country has $w_{i}$ cup finalists living there.\n\nHelp the company employees find the city such that the total cost of travel of all the participants to it is minimum.",
    "tutorial": "Let's think about formal statement of the problem. We are given a tricky definition of a distance on the tre: $ \\rho (a, b) = dist(a, b)^{1.5}$. Each vertex has its weight $w_{i}$. We need to choose a place $x$ for a competition such that the sum of distances from all vertices of the tree with their weights is minimum possible: $f(x) = w_{1} \\rho (1, x) + w_{2} \\rho (x, 2) + ... + w_{n} \\rho (x, n)$. Let's understand how function $f(x)$ works. Allow yourself to put point $x$ not only in vertices of the tree, but also in any point inside each edge by naturally expanding the distance definition (for example, the middle of the edge of length $4$ km is located $2$ km from both ends of this edge). Fact 1. For any path $x\\in[a,b]$ in the tree the function $ \\rho (i, x)$ is convex. Actually, the function $dist(i, x)$ plot on each path $[a, b]$ looks like the plot of a function $abs(x)$: it first decreases linearly to the minimum: the closes to $i$ point on a segment $[a, b]$, and then increases linearly. Taking a composition with a convex increasing function $t^{1.5}$, as we can see, we get the convex function on any path in the tree. Here by function on the path we understand usual function of a real variable $x$ that is identified with its location on path $x$: $dist(a, x)$. So, each of the summands in the definition of $f(x)$ is convex on any path in the tree, so $f(x)$ is also convex on any path in the tree. Let's call convex functions on any path in the tree convex on tree. Let's formulate few facts about convex functions on trees. Fact 2. A convex function on tree can't have two different local minimums. Indeed, otherwise the path between those minimums contradicts the property of being convex on any path in the tree. So, any convex function $f(x)$ on the tree has the only local minimum that coincides with its global minimum. Fact 3. From each vertex $v$ there exists no more than one edge in which direction the function $f$ decreases. Indeed, otherwise the path connecting two edges of function decrease would contradict the definition of a convex function in a point $v$. Let's call such edge that function decreases along this edge to be a gradient of function $f$ in point $x$. By using facts 2 and 3 we see that in each vertex there is either a uniquely defined gradient or the vertex is a global minimum. Suppose we are able to efficiently find a gradient direction by using some algorithm for a given vertex $v$. If our tree was a bamboo then the task would be a usual convex function minimization that is efficiently solved by a binary search, i. e. dichotomy. We need some equivalent of a dichotomy for a tree. What is it? Let's use centroid decmoposition! Indeed, let's take a tree center (i. e. such vertex that sizes of all its subtrees are no larger than $n / 2$). By using fact $3$ we may consider the gradient of $f$ in the center of the tree. First of all, there may be no gradient in this point meaning that we already found an optimum. Otherwise we know that global minimum is located in a subtree in direction of gradient, so all remaining subtrees and the center can be excluded from our consideration. So, by running one gradient calculation we reduced the number of vertices in a considered part of a tree twice. So, in $O(\\log n)$ runs of gradient calculation we almost solved the problem. Let's understand where exactly the answer is located. Note that the global optimum will most probably be located inside some edge. It is easy to see that the optimum vertex will be one of the vertices incident to that edge, or more specifically, one of the last two considered vertices by our algorithms. Which exactly can be determined by calculating the exact answer for them and choosing the most optimal among them. Now let's calculate the gradient direction in a vertex $v$. Fix a subtree $u_{i}$ of a vertex $v$. Consider a derivative of all summands from that subtree when we move into that subtree. Denote this derivative as $der_{i}$. Then, as we can see, the derivative of $f(x)$ while moving from $x = v$ in direction of subtree $u_{i}$ is $- der_{1} - der_{2} - ... - der_{i - 1} + der_{i} - der_{i + 1} - ... - der_{k}$ where $k$ is a degree of vertex $v$. So, by running one DFS from vertex $v$ we may calculate all values $der_{i}$, and so we may find a gradient direction by applying the formula above and considering a direction with negative derivative. Finally, we got a solution in $O(n\\log n)$.",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "566",
    "index": "D",
    "title": "Restructuring Company",
    "statement": "Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.\n\nThere are $n$ people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of $n$ departments, one person in each).\n\nHowever, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use $team(person)$ to represent a team where person $person$ works. A crisis manager can make decisions of two types:\n\n- Merge departments $team(x)$ and $team(y)$ into one large department containing all the employees of $team(x)$ and $team(y)$, where $x$ and $y$ ($1 ≤ x, y ≤ n$) — are numbers of two of some company employees. If $team(x)$ matches $team(y)$, then nothing happens.\n- Merge departments $team(x), team(x + 1), ..., team(y)$, where $x$ and $y$ ($1 ≤ x ≤ y ≤ n$) — the numbers of some two employees of the company.\n\nAt that the crisis manager can sometimes wonder whether employees $x$ and $y$ ($1 ≤ x, y ≤ n$) work at the same department.\n\nHelp the crisis manager and answer all of his queries.",
    "tutorial": "This problem allows a lot of solution with different time asymptotic. Let's describe a solution in $O(q\\log n)$. Let's first consider a problem with only a queries of second and third type. It can be solved in a following manner. Consider a line consisting of all employees from $1$ to $n$. An observation: any department looks like a contiguous segment of workers. Let's keep those segments in any logarithmic data structure like a balanced binary search tree (std::set or TreeSet). When merging departments from $x$ to $y$, just extract all segments that are in the range $[x, y]$ and merge them. For answering a query of the third type just check if employees $x$ and $y$ belong to the same segment. In such manner we get a solution of an easier problem in $O(\\log n)$ per query. When adding the queries of a first type we in fact allow some segments to correspond to the same department. Let's add a DSU for handling equivalence classes of segments. Now the query of the first type is just using merge inside DSU for departments which $x$ and $y$ belong to. Also for queries of the second type it's important not to forget to call merge from all extracted segments. So we get a solution in $O(q(\\log n+\\alpha(n)))=O(q\\log n)$ time.",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 1900
  },
  {
    "contest_id": "566",
    "index": "E",
    "title": "Restoring Map",
    "statement": "Archaeologists found some information about an ancient land of Treeland. We know for sure that the Treeland consisted of $n$ cities connected by the $n - 1$ road, such that you can get from each city to any other one along the roads. However, the information about the specific design of roads in Treeland has been lost. The only thing that the archaeologists can use is the preserved information about near cities.\n\nTwo cities of Treeland were called near, if it were possible to move from one city to the other one by moving through at most two roads. Also, a city is considered near to itself. During the recent excavations archaeologists found a set of $n$ notes, each of them represents a list of cities, near to some of the $n$ cities of the country. However, unfortunately, none of the found records lets you understand in what order the cities go in the list and for which city in the list the near to it cities were listed.\n\nHelp the archaeologists and restore any variant of the map of Treeland that meets the found information.",
    "tutorial": "Let's call a neighborhood of a vertex - the set consisting of it and all vertices near to it. So, we know the set of all neighborhoods of all vertices in some arbitrary order, and also each neighborhood is shuffled in an arbitrary order. Let's call the tree vertex to be internal if it is not a tree leaf. Similarly, let's call a tree edge to be internal if it connects two internal vertices. An nice observation is that if two neighborhoods intersect exactly by two elements $a$ and $b$ then $a$ and $b$ have to be connected with an edge, in particular the edge $(a, b)$ is internal. Conversely, any internal edge $(a, b)$ may be represented as an intersection of some two neighborhoods $C$ and $D$ of some two vertices $c$ and $d$ such that there is a path $c - a - b - d$ in the tree. In such manner we may find all internal edges by considering pairwise intersections of all neighborhoods. This can be done in about $n^{3} / 2$ operations naively, or in $32$ times faster, by using bitsets technique. Note that knowing all internal edges we may determine all internal vertices except the only case of a star graph (i. e. the graph consisting of a vertex with several other vertices attached to it). The case of a star should be considered separately. Now we know the set of all leaves, all internal vertices and a tree structure on all internal vertices. The only thing that remained is to determine for each leaf, to what internal vertex is should be attached. This can be done in following manner. Consider a leaf $l$. Consider all neighborhoods containing it. Consider a minimal neighborhood among them; it can be shown that it is exactly the neighborhood $L$ corresponding to a leaf $l$ itself. Consider all internal vertices in $L$. There can be no less than two of them. If there are three of them or more then we can uniquely determine to which of them $l$ should be attached - it should be such vertex from them that has a degree inside $L$ larger than $1$. If there are exactly two internal vertices in $L$ (let's say, $a$ and $b$), then determining the attach point for $l$ is a bit harder. Statement: $l$ should be attached to that vertex among $a$, $b$, that has an internal degree exactly $1$. Indeed, if $l$ was attached to a vertex with internal degree larger than $1$, we would have considered this case before. If both of vertices $a$ and $b$ have internal degree - $1$ then our graph looks like a dumbbell (an edge $(a, b)$ and all remaining vertices attached either to $a$ or to $b$). Such case should also be considered separately. The solution for two special cases remains for a reader as an easy exercise.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "566",
    "index": "F",
    "title": "Clique in the Divisibility Graph",
    "statement": "As you must know, the maximum clique problem in an arbitrary graph is $NP$-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.\n\nJust in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.\n\nLet's define a divisibility graph for a set of positive integers $A = {a_{1}, a_{2}, ..., a_{n}}$ as follows. The vertices of the given graph are numbers from set $A$, and two numbers $a_{i}$ and $a_{j}$ ($i ≠ j$) are connected by an edge if and only if either $a_{i}$ is divisible by $a_{j}$, or $a_{j}$ is divisible by $a_{i}$.\n\nYou are given a set of non-negative integers $A$. Determine the size of a maximum clique in a divisibility graph for set $A$.",
    "tutorial": "Order numbers in the sought clique in ascending order. Note that set $X = {x_{1}, ..., x_{k}}$ is a clique iff $\\mathbb{Z}_{i}\\ \\mid\\mathbb{Z}_{i+1}$ for ($1  \\le  i  \\le  k - 1$). So, it's easy to formulate a dynamic programming problem: $D[x]$ is equal to the length of a longest suitable increasing subsequence ending in a number $x$. The calculation formula: $D[x]=m a x(1,m a x(D[y]+1\\mathrm{~if~}y\\mid x))$ for all $x$ in set $A$. If DP is written in \"forward\" direction then it's easy to estimate the complexity of a solution. In the worst case we'll process $n/1+n/2+\\ldots+n/n=n(1/1+\\ldots\\cdot+1/n)\\approx n\\ln(n)$ transitions.",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "566",
    "index": "G",
    "title": "Max and Min",
    "statement": "Two kittens, Max and Min, play with a pair of non-negative integers $x$ and $y$. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, $x$ and $y$ became negative at the same time, and kitten Max tries to prevent him from doing so.\n\nEach kitten has a set of pairs of integers available to it. Kitten Max has $n$ pairs of non-negative integers $(a_{i}, b_{i})$ ($1 ≤ i ≤ n$), and kitten Min has $m$ pairs of non-negative integers $(c_{j}, d_{j})$ ($1 ≤ j ≤ m$). As kitten Max makes a move, it can take any available pair $(a_{i}, b_{i})$ and add $a_{i}$ to $x$ and $b_{i}$ to $y$, and kitten Min can take any available pair $(c_{j}, d_{j})$ and subtract $c_{j}$ from $x$ and $d_{j}$ from $y$. Each kitten can use each pair multiple times during distinct moves.\n\nMax moves first. Kitten Min is winning if at some moment both numbers $a$, $b$ are negative \\textbf{simultaneously}. Otherwise, the winner of the game is kitten Max. Determine which kitten wins if both of them play optimally.",
    "tutorial": "Consider a following geometrical interpretation. Both Max and Min have a set of vectors from the first plane quadrant and a point $(x, y)$. During his turn Max may add any of his vectors to a point $(x, y)$, and Min - may subtract any of his vectors. Min wants point $(x, y)$ to be strictly in the third quadrant, Max tries to prevent his from doing it. Denote Max vectors as $Mx_{i}$ and Min vectors as $Mn_{j}$. Consider a following obvious sufficient condition for Max to win. Consider some non-negative direction in a plane, i. e. such vector $(a, b)$ that $a, b  \\ge  0$ and at least one of numbers $a, b$ is not a zero. Then if among Max vectors there is such vector $Mx_{i}$, that it's not shorter than any of Min vectors $Mn_{j}$ along the direction $(a, b)$ then Max can surely win. Here by the length of vector $v$ along a direction $(a, b)$ we mean a scalar product of vector $v$ and vector $(a, b)$. Indeed, let Max always use that vector $Mx_{i}$. Then during the turns of Max and Min point $(x, y)$ is shifted by a vector $Mx_{i} - Mn_{j}$ for some $j$, so its overall shift along the vector $(a, b)$ is equal to $((Mx_{i} - Mn_{j}), (a, b)) = (Mx_{i}, (a, b)) - (Mn_{j}, (a, b))  \\ge  0$. By observing that initially the scalar produt $((x, y), (a, b)) = ax + by > 0$ we see that at any moment $ax + by$ will be strictly positive. This means that Min won't be able at any moment to make $x$ and $y$ both be negative (since it would mean that $ax + by < 0$). Now let's formulate some kind of converse statement. Suppose Max vector $Mx_{i}$ lies strictly inside the triangle formed by Min vectors $Mn_{j}$ and $Mn_{k}$. In particular, vector $Mx_{i}$ endpoint can't lie on a segment $[Mn_{j}, Mn_{k}]$, but it may be collinear one of vectors $Mn_{j}$ and $Mn_{k}$. Note that since $Mx_{i}$ lies strictly inside the triangle formed by vectors $Mn_{j}$ and $Mn_{k}$ it can be extended to a vector $Mx'_{i}$, whose endpoint lies on a segment $[Mn_{j}, Mn_{k}]$. By using linear dependence of $Mx'_{i}$ and $Mn_{j}$, $Mn_{k}$ we have that $Mx'_{i} = (p / r)Mn_{j} + (q / r)Mn_{k}$, where $p + q = r$ and $p, q, r$ - integer non-negative numbers. This is equivalent to a formula $rMx'_{i} = pMn_{j} + qMn_{k}$. This means that if per each $r$ turns of Max in $Mx_{i}$ we will respond with $p$ turns of Min in $Mn_{j}$ and $q$ turns of Min in $Mn_{k}$, then the total shift will be equal to $- pMn_{j} - qMn_{k} + rMx_{i} = - rMx'_{i} + rMx_{i} = - r(Mx'_{i} - Mx_{i})$, that is the vector with strictly negative components. So, we are able to block that Max turn, i. e. it does not give any advantage to Max. The natural wish is to create a convex hull of all Min turns and to consider all Max turns in respect to it. If Max turn lies inside the convex hull of Min turns, then by using the previous fact this turn is meaningless to Max. Otherwise, there are two possibilities. First, this turn may intersect the hull but go out of it somewhere; in this case this Max turn is no shorter than all Min turns in some non-negative direction (more specifically, in its own direction), so Max wins. On the other hand, Max vector lies to aside from the Min turns convex hull. Let's suppose the vector $Mx_{i}$ lies to the left of the Min turns. This case requires a special analysis. Consider the topmost of the Min vectors $Mn_{j}$. If $Mx_{i}$ is no lower than $Mx_{j}$, then by using the first fact Max is able to win by using only this vector. Otherwise the difference $Mn_{i} - Mx_{j}$ is a vector with strictly negative components, by using which we are able to block that Max vector. So, the full version of a criteria for Min being a winner looks like the following. Consider a convex hull of Min turns and expand it to the left of the topmost point and to the bottom of the rightmost point. If all Max turns lie strictly inside the formed figure then Min wins, otherwise Max wins.",
    "tags": [
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "567",
    "index": "A",
    "title": "Lineland Mail",
    "statement": "All cities of Lineland are located on the $Ox$ coordinate axis. Thus, each city is associated with its position $x_{i}$ — a coordinate on the $Ox$ axis. No two cities are located at a single point.\n\nLineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).\n\nStrange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.\n\nFor each city calculate two values ​​$min_{i}$ and $max_{i}$, where $min_{i}$ is the minimum cost of sending a letter from the $i$-th city to some other city, and $max_{i}$ is the the maximum cost of sending a letter from the $i$-th city to some other city",
    "tutorial": "One can notice that the maximum cost of sending a letter from $i$'th city is equal to maximum of distances from $i$'th city to first city and from $i$'th city to last ($max(abs(x_{i} - x_{0}), abs(x_{i} - x_{n - 1})$). On the other hand, the minimum cost of sending a letter will be the minimum of distances between neighboring cities ($i - 1$'th and $i + 1$'th cities), more formally, $min(abs(x_{i} - x_{i - 1}), abs(x_{i} - x_{i + 1})$. For each city, except the first and the last this formula is correct, but for them formulas are ($abs(x_{i} - x_{i + 1})$) and ($abs(x_{i} - x_{i - 1})$) respectively.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "567",
    "index": "B",
    "title": "Berland National Library",
    "statement": "Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.\n\nToday was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form \"reader entered room\", \"reader left room\". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from $1$ to $10^{6}$. Thus, the system logs events of two forms:\n\n- \"+ $r_{i}$\" — the reader with registration number $r_{i}$ entered the room;\n- \"- $r_{i}$\" — the reader with registration number $r_{i}$ left the room.\n\nThe first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.\n\nSignificant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.\n\nHelp the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.",
    "tutorial": "To answer the queries correct, we need to know if the person is still in the library. For that purpose we will use $in$ array of type $bool$. Also we will store two variables for the answer and ''current state'' (it will store the current number of people in the library). Let's call them $ans$ and $state$ respectively. Thus, if we are given query $+ a_{i}$ then we should increase $state$ by one, mark that this person entered the library ($in[a_{i}] = true$) and try to update the answer ($ans = max(ans, state)$). Otherwise we are given $- a_{i}$ query. If the person who leaves the library, was in there, we should just decrease $state$ by one. Otherwise, if this person was not in the library ($in[a_{i}]$ == $false$) and leaves now, he entered the library before we started counting. It means we should increase the answer by one anyway. Also one should not forget that it is needed to mark that the person has left the library ($in[a_{i}] = false$).",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "567",
    "index": "C",
    "title": "Geometric Progression",
    "statement": "Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer $k$ and a sequence $a$, consisting of $n$ integers.\n\nHe wants to know how many subsequences of length three can be selected from $a$, so that they form a geometric progression with common ratio $k$.\n\nA subsequence of length three is a combination of three such indexes $i_{1}, i_{2}, i_{3}$, that $1 ≤ i_{1} < i_{2} < i_{3} ≤ n$. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.\n\nA geometric progression with common ratio $k$ is a sequence of numbers of the form $b·k^{0}, b·k^{1}, ..., b·k^{r - 1}$.\n\nPolycarp is only three years old, so he can not calculate this number himself. Help him to do it.",
    "tutorial": "Let's solve this problem for fixed middle element of progression. This means that if we fix element $a_{i}$ then the progression must consist of $a_{i} / k$ and $a_{i} \\cdot k$ elements. It could not be possible, for example, if $a_{i}$ is not divisible by $k$ ($a_{i}\\ \\mathrm{mod}\\ k\\not=0$). For fixed middle element one could find the number of sequences by counting how many $a_{i} / k$ elements are placed left from fixed element and how many $a_{i} \\cdot k$ are placed right from it, and then multiplying this numbers. To do this, one could use two associative arrays $A_{l}$ and $A_{r}$, where for each key $x$ will be stored count of occurences of $x$ placed left (or right respectively) from current element. This could be done with map structure. Sum of values calculated as described above will give the answer to the problem.",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "567",
    "index": "D",
    "title": "One-Dimensional Battle Ships",
    "statement": "Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of $n$ square cells (that is, on a $1 × n$ table).\n\nAt the beginning of the game Alice puts $k$ ships on the field without telling their positions to Bob. Each ship looks as a $1 × a$ rectangle (that is, it occupies a sequence of $a$ consecutive squares of the field). The ships cannot intersect and even touch each other.\n\nAfter that Bob makes a sequence of \"shots\". He names cells of the field and Alice either says that the cell is empty (\"miss\"), or that the cell belongs to some ship (\"hit\").\n\nBut here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a \"miss\".\n\nHelp Bob catch Alice cheating — find Bob's first move, such that after it you can be sure that Alice cheated.",
    "tutorial": "First, we should understand when the game ends. It will happen when on the $n$-sized board it will be impossible to place $k$ ships of size $a$. For segment with length $len$ we could count the maximum number of ships with size $a$ that could be placed on it. Each ship occupies $a + 1$ cells, except the last ship. Thus, for segment with length $len$ the formula will look like $\\frac{t e n+1}{a+1}$ (we add \"fictive\" cell to $len$ cells to consider the last ship cell). This way, for $[l..r]$ segment the formula should be $\\frac{r-l+2}{a+1}$. For solving the problem we should store all the $[l..r]$ segments which has no ''free'' cells (none of them was shooted). One could use ($std: : set$) for that purpose. This way, before the shooting, there will be only one segment $[1..n]$. Also we will store current maximum number of ships we could place on a board. Before the shooting it is equal to $\\frac{n\\i+1}{a+1}$. With every shoot in cell $x$ we should find the segment containing shooted cell (let it be $[l..r]$), we should update segment set. First, we should delete $[l..r]$ segment. It means we should decrease current maximum number of ships by $\\frac{r-l+2}{a+1}$ and delete it from the set. Next, we need to add segments $[l..x - 1]$ and $[x + 1..r]$ to the set (they may not be correct, so you may need to add only one segments or do not add segments at all) and update the maximum number of ships properly. We should process shoots one by one, and when the maximum number of ships will become lesser than $k$, we must output the answer. If that never happen, output $- 1$.",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "567",
    "index": "E",
    "title": "President and Roads",
    "statement": "Berland has $n$ cities, the capital is located in city $s$, and the historic home town of the President is in city $t$ ($s ≠ t$). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.\n\nOnce a year the President visited his historic home town $t$, for which his motorcade passes along some path from $s$ to $t$ (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from $s$ to $t$, along which he will travel the fastest.\n\nThe ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer.",
    "tutorial": "At first, let's find edges that do not belong to any shortest paths from $s$ to $t$. Let's find two shortest path arrays $d1$ and $d2$ with any shortest-path-finding algorithm. First array stores shortest path length from $s$, and the second - from $t$. Edge $(u, v)$ then will be on at least one shortest path from $s$ to $t$ if and only if $d1[u] + w(u, v) + d2[v]$ == $d1[t]$. Let's build shortest path graph, leaving only edges described above. If we consider shortest path from $s$ to $t$ as segment $[0..D]$ and any edge $(u, v)$ in shortest path graph as its subsegment $[d1[u]..d1[v]]$, then if such subsegment do not share any common point with any other edge subsegment, except its leftest and rightest point ($d1[u]$ and $d1[v]$), this edge belongs to every shortest path from $s$ to $t$. Now we could surely answer \"YES\" to such edges. Next part of the solution are much simple. If edge $(u, v)$ do not belong to every shortest path, we could try decrease its weight. This edge will belong to every shortest path if and only if its weight will become $d1[t] - d1[u] - d2[v] - 1$. So, if this value are strictly positive, we should answer \"CAN\" considering new edge weight. Otherwise we need to output \"NO\".",
    "tags": [
      "dfs and similar",
      "graphs",
      "hashing",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "567",
    "index": "F",
    "title": "Mausoleum",
    "statement": "King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.\n\nThe mausoleum will be constructed from $2n$ blocks, each of them has the shape of a cuboid. Each block has the bottom base of a $1 × 1$ meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of $n$ meters.\n\nThe blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:\n\n- $[1, 2, 2, 3, 4, 4, 3, 1]$;\n- $[1, 1]$;\n- $[2, 2, 1, 1]$;\n- $[1, 2, 3, 3, 2, 1]$.\n\nSuddenly, $k$ more requirements appeared. Each of the requirements has the form: \"$h[x_{i}]$ sign$_{i}$ $h[y_{i}]$\", where $h[t]$ is the height of the $t$-th block, and a sign$_{i}$ is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the $k$ additional requirements is given by a pair of indexes $x_{i}$, $y_{i}$ ($1 ≤ x_{i}, y_{i} ≤ 2n$) and sign sign$_{i}$.\n\nFind the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the $k$ additional requirements were met.",
    "tutorial": "Consider that we are placing blocks by pairs, one pair by one, starting from leftmost and rightmost places. Thus, for example, two blocks of height 1 we could place in positions 1 and 2, 1 and $2n$, or $2n - 1$ and $2n$. The segment of unused positions will be changed that way and the next block pairs should be placed on new leftmost and rightmost free places. At last only two positions will be free and we should place two blocks of height $n$ on them. Any correct sequence of blocks could be builded that way. Let's try to review the requirements consider such way of placing blocks. As soon as we place blocks one by one, the requirements are now only describes the order of placing blocks. For example, requirement ''3 >= 5'' means that we should place block in position 3 only if block in position 5 is already placed (and thus it have lesser height), or we place pair of blocks of same height on them at one moment. For counting required number of sequences we will use dynamic programming approach. Let's count $dp[l][r]$ - the number of ways to place some blocks in the way that only positions at segment $[l..r]$ are free. The height of current placed pair of blocks is counted from the segment borders itself ($\\textstyle{\\frac{(I+(n-r))}{2}}$. Fix one way of placing current block pair (exclusion is $l = = r + 1$). Now check if such placing meets the requirements. We will consider only requirements that meets one of the current-placing positions. For every \"current\" position \"<\" must be true only for free positions (positions in $[l..r]$, which do not equal to current positions), \">\" must be true for already-placed positions (out of $[l..r]$) and \"=\" must be true only for second current position. This DP could be easily calculated using \"lazy\" approach.",
    "tags": [
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "568",
    "index": "A",
    "title": "Primes or Palindromes?",
    "statement": "Rikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!\n\nLet us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one.\n\nRikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left.\n\nOne problem with prime numbers is that there are too many of them. Let's introduce the following notation: $π(n)$ — the number of primes no larger than $n$, $rub(n)$ — the number of palindromic numbers no larger than $n$. Rikhail wants to prove that there are a lot more primes than palindromic ones.\n\nHe asked you to solve the following problem: for a given value of the coefficient $A$ find the maximum $n$, such that $π(n) ≤ A·rub(n)$.",
    "tutorial": "It is known that amount of prime numbers non greater than $n$ is about $\\frac{J h}{\\log n}$. We can also found the amount of palindrome numbers with fixed length $k$ - it is about $10^{\\lfloor{\\frac{k+1}{2}}\\rfloor}$ which is $O({\\sqrt{n}})$. Therefore the number of primes asymptotically bigger than the number of palindromic numbers and for every constant $A$ there is an answer. Moreover, for this answer $n$ the next condition hold: $\\Lambda\\sim\\frac{\\sqrt{n}}{\\log n}$. In our case $n < 10^{7}$. For all numbers smaller than $10^{7}$ we can check if they are primes (via sieve of Eratosthenes) and/or palindromes (via trivial algorithm or compute reverse number via dynamic approach). Then we can calculate prefix sums ($ \\pi (n)$ and $rub(n)$) and find the answer using linear search. For $A  \\le  42$ answer is smaller than $2 \\cdot 10^{6}$. Complexity - $O(a n s\\cdot\\log\\log a n s)$.",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "568",
    "index": "B",
    "title": "Symmetric and Transitive",
    "statement": "Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term \"equivalence relation\". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.\n\nA set $ρ$ of pairs $(a, b)$ of elements of some set $A$ is called a binary relation on set $A$. For two elements $a$ and $b$ of the set $A$ we say that they are in relation $ρ$, if pair $(a,b)\\in\\rho$, in this case we use a notation $a\\stackrel{p}{\\sim}b$.\n\nBinary relation is equivalence relation, if:\n\n- It is reflexive (for any $a$ it is true that $a\\stackrel{p}{\\sim}a$);\n- It is symmetric (for any $a$, $b$ it is true that if $a\\stackrel{p}{\\sim}b$, then $b\\stackrel{p}{\\sim}a$);\n- It is transitive (if $a\\stackrel{p}{\\sim}b$ and $b\\sim c$, than $a\\stackrel{p}{\\sim}c$).\n\nLittle Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his \"proof\":\n\nTake any two elements, $a$ and $b$. If $a\\stackrel{p}{\\sim}b$, then $b\\stackrel{p}{\\sim}a$ (according to property (2)), which means $a\\stackrel{p}{\\sim}a$ (according to property (3)).\n\nIt's very simple, isn't it? However, you noticed that Johnny's \"proof\" is wrong, and decided to show him a lot of examples that prove him wrong.\n\nHere's your task: count the number of binary relations over a set of size $n$ such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive).\n\nSince their number may be very large (not $0$, according to Little Johnny), print the remainder of integer division of this number by $10^{9} + 7$.",
    "tutorial": "Let's find Johnny's mistake. It is all right in his proof except ``If $a\\stackrel{\\rho}{\\sim}b$'' part. What if there is no such $b$ for an given $a$? Then obviously $a\\stackrel{p}{\\sim}a$ otherwise we'll take $b = a$. We can see that our binary relation is some equivalence relation which was expanded by some \"empty\" elements. For \"empty\" element $a$ there is no such $b$ that $a\\stackrel{p}{\\sim}b$. Thus we can divide our solution into two parts: Count the number of equivalence relations on sets of size $0, 1, ..., n - 1$ For every size count the number of ways to expand it with some \"empty\" elements. We can define equivalence relation using its equivalence classes. So first part can be solved using dynamic programming: $dp[elems][classes]$ - the numbers of ways to divide first $elems$ elements to $classes$ equivalence classes. When we handle next element we can send it to one of the existing equivalence classes or we can create new class. Let's solve second part. Consider set of size $m$. We have found that there are $eq[m]$ ways to build equivalence relation on this set. We have to add $n - m$ \"empty\" elements to this set. The number of ways to choose their positions is $C_{n}^{k}$. We can calculate all the binomial coefficients using Pascal's triangle. So the answer to the problem is $\\textstyle\\sum_{m=0}^{n-1}C[n][n-m]\\cdot e q[m]$. Complexity - $O(n^{2})$",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "568",
    "index": "C",
    "title": "New Language",
    "statement": "Living in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed.\n\nAfter some time, the wise men returned from the trip even wiser. They locked up for six months in the dining room, after which they said to the king: \"there are a lot of different languages, but almost all of them have letters that are divided into vowels and consonants; in a word, vowels and consonants must be combined correctly.\"\n\nThere are very many rules, all of them have exceptions, but our language will be deprived of such defects! We propose to introduce a set of formal rules of combining vowels and consonants, and include in the language all the words that satisfy them.\n\nThe rules of composing words are:\n\n- The letters are divided into vowels and consonants in some certain way;\n- All words have a length of exactly $n$;\n- There are $m$ rules of the form ($pos_{1}, t_{1}, pos_{2}, t_{2}$). Each rule is: if the position $pos_{1}$ has a letter of type $t_{1}$, then the position $pos_{2}$ has a letter of type $t_{2}$.\n\nYou are given some string $s$ of length $n$, it is not necessarily a correct word of the new language. Among all the words of the language that lexicographically not smaller than the string $s$, find the minimal one in lexicographic order.",
    "tutorial": "Suppose we have fixed letters on some positions, how can we check is there a way to select letters on other positions to build a word from the language? The answer is 2-SAT. Let's see: for every position there is two mutually exclusive options (vowel or consonant) and the rules are consequences. Therefore we can do this check in $O(n + m)$ time. Let's decrease the length of the prefix which will be the same as in $s$. Then the next letter must be strictly greater but all the next letters can be any. We can iterate over all greater letters and then check if we can made this word the word from the language (via 2-SAT). Once we have found such possibilty we have found the right prefix of the answer. After that we can increase the length of the fixed prefix in a similar way. This solution works in $O(nm \\Sigma  )$ time. We can divide this by $ \\Sigma $ simply try not all the letter but only the smallest possible vowel and the smallest possible consonant. And you should remember about the case when all the letters are vowel (or all the letters are consonant). Complexity - $O(nm)$",
    "tags": [
      "2-sat",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "568",
    "index": "D",
    "title": "Sign Posts",
    "statement": "One Khanate had a lot of roads and very little wood. Riding along the roads was inconvenient, because the roads did not have road signs indicating the direction to important cities.\n\nThe Han decided that it's time to fix the issue, and ordered to put signs on every road. The Minister of Transport has to do that, but he has only $k$ signs. Help the minister to solve his problem, otherwise the poor guy can lose not only his position, but also his head.\n\nMore formally, every road in the Khanate is a line on the $Oxy$ plane, given by an equation of the form $Ax + By + C = 0$ ($A$ and $B$ are not equal to 0 at the same time). You are required to determine whether you can put signs in at most $k$ points so that each road had at least one sign installed.",
    "tutorial": "Suppose, that solution exist. In case $n  \\le  k$ we can put one signpost on each road. In other case let's choose any $k + 1$ roads. By the Dirichlet's principle there are at least two roads among selected, which have common signpost. Let's simple iterate over all variants with different two roads. After choosing roads $a$ and $b$, we will remove all roads, intersecting with $a$ and $b$ in common points and reduce $k$ in our problem. This recursive process solves the problem (if solution exist). Complexity of this solution - $O(n\\cdot{\\frac{k(k+1)!}{2^{k}}})$. If implement this solution carefully - you will get AC =) But in case of TL we can add one improvement to our solution. Note, that if we find point, which belongs to $k + 1$ or more roads, then we must include this point to out answer. For sufficiently large $n$ (for example, if $n > 30k^{2}$) this point always exist and we can find it using randomize algorithm. If solution exist, probability that two arbitrary roads are intersects in such a point not less than $\\textstyle{\\frac{1}{k}}$. Because of it, if we $100$ times pick two random roads, then with probability $1-10^{-8}$ such a point will be found and we can decrease $k$. All operations better to do in integers. Complexity - $O(n k^{2}+k^{2}\\cdot{\\frac{k!(k+1)!}{2^{k}}})$.",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "568",
    "index": "E",
    "title": "Longest Increasing Subsequence",
    "statement": "Note that the memory limit in this problem is less than usual.\n\nLet's consider an array consisting of positive integers, some positions of which contain gaps.\n\nWe have a collection of numbers that can be used to fill the gaps. Each number from the given collection can be used at most once.\n\nYour task is to determine such way of filling gaps that the longest increasing subsequence in the formed array has a maximum size.",
    "tutorial": "Let's calculate array $c$: $c[len]$ - minimal number that can complete increasing subsequence of length $len$. (This is one of the common solution for LIS problem). Elements of this array are increasing and we can add new element $v$ to processed part of sequence as follows: find such index $i$ that $c[i]  \\le  v$ and $c[i + 1]  \\ge  v$ let $c[i + 1] = v$ We can process this action in $O(\\log n)$ time. When we handle a gap, we must try to insert all numbers from set $b$. If we sort elements of $b$ in advance, then we can move with two iterators along arrays $b$ and $c$ and relax all needed values as explained above. This case requires $O(n + m)$ time. Authors implied solution with $O(n)$ space complexity for answer restoring. We can do this in the following way: Together with array $c$ we will store array $c_{index}[len]$ - index of element, which complete optimal increasing subsequence of length $len$. If this subsequence ends in a gap - we will store $- 1$. Also, we will store for every not gap - length of LIS($lenLIS[pos]$), which ends in this position (this is simply calculating while processing array $c$) and position($prevIndex[pos]$) of previous element in this subsequence (if this elements is gap, we store $- 1$) Now we will start recovery the answer with this information. While we are working with not gaps - it's all right. We can simply restore LIS with $prevIndex[pos]$ array. The main difficulty lies in processing gaps. If value of $prevIndex[pos]$ in current position equal to $- 1$ - we know, that before this elements must be one or more gaps. And we can determine which gaps and what values from $b$ we must put in them as follows: Let suppose that we stand at position $r$ (and $prevIndex[r] = - 1$). Now we want to find such position $l$ (which is not gap), that we can fill exactly $lenLIS[r] - lenLIS[l]$ gaps between $l$ with increasing numbers from interval $(a[l]..a[r])$. Position $l$ we can simply iterates from $r - 1$ to $0$ and with it calculating gaps between $l$ and $r$. Check the condition described above we can produce via two binary search query to array $b$. Few details: How do we know, that between positions $l$ and $r$ we can fill gaps in such a way, that out answer still the best? Let $countSkip(l, r)$ - count gaps on interval $(l..r)$, $countBetween(x, y)$ - count different numbers from set $b$, lying in the range $(x..y)$. Then, positions $l$ and $r$ are good only if $lenLIS[r] - lenLIS[l] = min(countSkip(l, r), countBetween(a[l], a[r]))$. $countSkip$ we can calculate while iterates position $l$, $countBetween(x, y) = max(0, lower_bound(b, y) - upper_bound(b, x))$. What to do, is LIS ends or begins in gaps? This case we can solve by simply adding $-  \\infty $ and $+  \\infty $ in begin and end of out array. Complexity - $O(n\\log n+k(n+m))$. Memory - $O(n + m)$.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "569",
    "index": "A",
    "title": "Music",
    "statement": "Little Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.\n\nUnfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is $T$ seconds. Lesha downloads the first $S$ seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For $q$ seconds of real time the Internet allows you to download $q - 1$ seconds of the track.\n\nTell Lesha, for how many times he will start the song, including the very first start.",
    "tutorial": "Suppose we have downloaded $S$ seconds of the song and press the 'play' button. Let's find how many seconds will be downloaded when we will be forced to play the song once more. ${\\frac{x}{q}}={\\frac{x-S}{q-1}}$. Hence $x = qS$. Solution: let's multiply $S$ by $q$ while $S < T$. The answer is the amount of operations. Complexity - $O(\\log T)$",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "569",
    "index": "B",
    "title": "Inventory",
    "statement": "Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.\n\nDuring an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with $1$. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.\n\nYou have been given information on current inventory numbers for $n$ items in the company. Renumber items so that their inventory numbers form a permutation of numbers from $1$ to $n$ by changing the number of as few items as possible. Let us remind you that a set of $n$ numbers forms a permutation if all the numbers are in the range from $1$ to $n$, and no two numbers are equal.",
    "tutorial": "Let's look at the problem from another side: how many numbers can we leave unchanged to get permutation? It is obvious: these numbers must be from $1$ to $n$ and they are must be pairwise distinct. This condition is necessary and sufficient. This problem can be solved with greedy algorithm. If me meet the number we have never met before and this number is between $1$ and $n$, we will leave this number unchanged. To implement this we can use array where we will mark used numbers. After that we will look over the array again and allocate numbers that weren't used. Complexity - $O(n)$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "570",
    "index": "A",
    "title": "Elections",
    "statement": "The country of Byalechinsk is running elections involving $n$ candidates. The country consists of $m$ cities. We know how many people in each city voted for each candidate.\n\nThe electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.\n\nAt the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.\n\nDetermine who will win the elections.",
    "tutorial": "We need to determine choice for each city. Then sum it for each candidate and determine the winner. $O(n * m)$",
    "code": "#define _ijps 0\n#define _CRT_SECURE_NO_DEPRECATE\n#pragma comment(linker, \"/STACK:667772160\")\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <time.h>\n#include <map>\n#include <set>\n#include <deque>\n#include <cstdio>\n#include <cstdlib>\n#include <unordered_map>\n#include <bitset>\n#include <algorithm>\n#include <string>\n#include <fstream>\n#include <assert.h>\n#include <list>\n#include <cstring>\nusing namespace std;\n \n#define name \"\"\ntypedef unsigned long long ull;\ntypedef long long ll;\n#define mk make_pair\n#define forn(i, n) for(ll i = 0; i < (ll)n; i++)\n#define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++)\n#define times clock() * 1.0 / CLOCKS_PER_SEC\n#define inb push_back\n \nstruct __isoff{\n\t__isoff(){\n\t\tif (_ijps)\n\t\t\tfreopen(\"input.txt\", \"r\", stdin), freopen(\"output.txt\", \"w\", stdout);//, freopen(\"test.txt\", \"w\", stderr);\n\t\t//else freopen(name\".in\", \"r\", stdin), freopen(name\".out\", \"w\", stdout);\n\t\t//ios_base::sync_with_stdio(0);\n\t\tsrand(time(0));\n\t\t//srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A');\n\t}\n\t~__isoff(){\n\t\t//if(_ijps) cout<<times<<'\\n';\n\t}\n} __osafwf;\nconst ull p1 = 31;\nconst ull p2 = 29;\nconst double eps = 1e-8;\nconst double pi = acos(-1.0);\n \nconst ll inf = 1e17 + 7;\nconst int infi = 1e9 + 7;\nconst ll dd = 8e7 + 7;\nconst ll mod = 1e9 + 7;\n \nint D[105];\n \nint main(){\n\tint n, m;\n\tcin >> n >> m;\n\tforn(i, m){\n\t\tint z = -1, t = 0;\n\t\tforn(j, n){\n\t\t\tint g;\n\t\t\tcin >> g;\n\t\t\tif(z < g)\n\t\t\t\tz = g, t = j;\n\t\t}\n\t\tD[t]++;\n\t}\n\tint res = 0;\n\tforn(i, n){\n\t\tif(D[res] < D[i])\n\t\t\tres = i;\n\t}\n\tcout << res + 1;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "570",
    "index": "B",
    "title": "Simple Game",
    "statement": "One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from $1$ to $n$. Let's assume that Misha chose number $m$, and Andrew chose number $a$.\n\nThen, by using a random generator they choose a random integer $c$ in the range between $1$ and $n$ (any integer from $1$ to $n$ is chosen with the same probability), after which the winner is the player, whose number was closer to $c$. The boys agreed that if $m$ and $a$ are located on the same distance from $c$, Misha wins.\n\nAndrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number $n$. You need to determine which value of $a$ Andrew must choose, so that the probability of his victory is the highest possible.\n\nMore formally, you need to find such integer $a$ ($1 ≤ a ≤ n$), that the probability that $|c-a|<|c-m|$ is maximal, where $c$ is the equiprobably chosen integer from $1$ to $n$ (inclusive).",
    "tutorial": "Lets find which variant is interesting. For Andrew is no need a variant wherein $|a - m| > 1$ because we can increase probability of victory if we will be closer to m. Then we consider two variants, $a = c - 1$ and $a = c + 1$. Probability of victory will be $c / n$ for first variant and $(n - c + 1) / n$ for second. We need to choose better variant, also we must keep in mind case of $n = 1$. $O(1)$",
    "code": "#define _ijps 0\n#define _CRT_SECURE_NO_DEPRECATE\n#pragma comment(linker, \"/STACK:667772160\")\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <time.h>\n#include <map>\n#include <set>\n#include <deque>\n#include <cstdio>\n#include <cstdlib>\n#include <unordered_map>\n#include <bitset>\n#include <algorithm>\n#include <string>\n#include <fstream>\n#include <assert.h>\n#include <list>\n#include <cstring>\nusing namespace std;\n \n#define name \"\"\ntypedef unsigned long long ull;\ntypedef long long ll;\n#define mk make_pair\n#define forn(i, n) for(ll i = 0; i < (ll)n; i++)\n#define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++)\n#define times clock() * 1.0 / CLOCKS_PER_SEC\n#define inb push_back\n \nstruct __isoff{\n\t__isoff(){\n\t\tif (_ijps)\n\t\t\tfreopen(\"input.txt\", \"r\", stdin), freopen(\"output.txt\", \"w\", stdout);//, freopen(\"test.txt\", \"w\", stderr);\n\t\t//else freopen(name\".in\", \"r\", stdin), freopen(name\".out\", \"w\", stdout);\n\t\t//ios_base::sync_with_stdio(0);\n\t\tsrand(time(0));\n\t\t//srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A');\n\t}\n\t~__isoff(){\n\t\t//if(_ijps) cout<<times<<'\\n';\n\t}\n} __osafwf;\nconst ull p1 = 31;\nconst ull p2 = 29;\nconst double eps = 1e-8;\nconst double pi = acos(-1.0);\n \nconst ll inf = 1e17 + 7;\nconst int infi = 1e9 + 7;\nconst ll dd = 8e7 + 7;\nconst ll mod = 1e9 + 7;\n \nint main(){\n\tll n, m;\n\tcin >> n >> m;\n\tif(n == 1){\n\t\tcout << 1;\n\t\treturn 0;\n\t}\n\tif(m - 1 < n - m){\n\t\tcout << m + 1;\n\t}\n\telse{\n\t\tcout << m - 1;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "games",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "570",
    "index": "C",
    "title": "Replacement",
    "statement": "Daniel has a string $s$, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring \"..\" (two consecutive periods) in string $s$, of all occurrences of the substring let's choose the first one, and replace this substring with string \".\". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string $s$ contains no two consecutive periods, then nothing happens.\n\nLet's define $f(s)$ as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.\n\nYou need to process $m$ queries, the $i$-th results in that the character at position $x_{i}$ ($1 ≤ x_{i} ≤ n$) of string $s$ is assigned value $c_{i}$. After each operation you have to calculate and output the value of $f(s)$.\n\nHelp Daniel to process all queries.",
    "tutorial": "Lets find how replacements occur. If we have segment of points with length $l$,we need $l - 1$ operations and stop replacements for this segment. If we sum lenghts of all segments and its quantity then answer will be = total length of segments - quantity of segments. After change of one symbol length changes by 1. Quantity of segments can be supported by array. Consider events of merging, dividing,creation and deletion of segments. For merging we need to find if both of neighbors(right and left) are points then merging occured and quantity of segments reduced by 1. Other cases can be cosidered similarly. $O(n + m)$",
    "code": "#define _ijps 0\n#define _CRT_SECURE_NO_DEPRECATE\n#pragma comment(linker, \"/STACK:667772160\")\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <time.h>\n#include <map>\n#include <set>\n#include <deque>\n#include <cstdio>\n#include <cstdlib>\n#include <unordered_map>\n#include <bitset>\n#include <algorithm>\n#include <string>\n#include <fstream>\n#include <assert.h>\n#include <list>\n#include <cstring>\nusing namespace std;\n \n#define name \"\"\ntypedef unsigned long long ull;\ntypedef long long ll;\n#define mk make_pair\n#define forn(i, n) for(ll i = 0; i < (ll)n; i++)\n#define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++)\n#define times clock() * 1.0 / CLOCKS_PER_SEC\n#define inb push_back\n \nstruct __isoff{\n\t__isoff(){\n\t\tif (_ijps)\n\t\t\tfreopen(\"input.txt\", \"r\", stdin), freopen(\"output.txt\", \"w\", stdout);//, freopen(\"test.txt\", \"w\", stderr);\n\t\t//else freopen(name\".in\", \"r\", stdin), freopen(name\".out\", \"w\", stdout);\n\t\t//ios_base::sync_with_stdio(0);\n\t\tsrand(time(0));\n\t\t//srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A');\n\t}\n\t~__isoff(){\n\t\t//if(_ijps) cout<<times<<'\\n';\n\t}\n} __osafwf;\nconst ull p1 = 31;\nconst ull p2 = 29;\nconst double eps = 1e-8;\nconst double pi = acos(-1.0);\n \nconst ll inf = 1e17 + 7;\nconst int infi = 1e9 + 7;\nconst ll dd = 3e5 + 7;\nconst ll mod = 1e9 + 7;\n \nstring s;\nchar t = '.';\nint n, m;\n \nint num, group;\nbool ok[dd];\n \nint main(){\n\tcin >> n >> m >> s;\n\tforn(i, n){\n\t\tif(s[i] == t){\n\t\t\tnum++;\n\t\t\tif(i == 0 || s[i - 1] != t)\n\t\t\t\tgroup++;\n\t\t\tok[i + 1] = 1;\n\t\t}\n\t}\n\tforn(i, m){\n\t\tint d;\n\t\tchar c;\n\t\tscanf(\"%d %c\", &d, &c);\n\t\tbool a = ok[d], b = c == t;\n\t\tif(a != b){\n\t\t\tif(a){\n\t\t\t\tnum--;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tnum++;\n\t\t\t}\n\t\t\tif(ok[d - 1] && ok[d + 1] && !b){\n\t\t\t\tgroup++;\n\t\t\t}\n\t\t\tif(ok[d - 1] && ok[d + 1] && b){\n\t\t\t\tgroup--;\n\t\t\t}\n\t\t\tif(!ok[d - 1] && !ok[d + 1] && !b){\n\t\t\t\tgroup--;\n\t\t\t}\n\t\t\tif(!ok[d - 1] && !ok[d + 1] && b){\n\t\t\t\tgroup++;\n\t\t\t}\n\t\t}\n\t\tok[d] = b;\n\t\tprintf(\"%d\\n\", num - group);\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "570",
    "index": "D",
    "title": "Tree Requests",
    "statement": "Roman planted a tree consisting of $n$ vertices. Each vertex contains a lowercase English letter. Vertex $1$ is the root of the tree, each of the $n - 1$ remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex $i$ is vertex $p_{i}$, the parent index is always less than the index of the vertex (i.e., $p_{i} < i$).\n\nThe depth of the vertex is the number of nodes on the path from the root to $v$ along the edges. In particular, the depth of the root is equal to $1$.\n\nWe say that vertex $u$ is in the subtree of vertex $v$, if we can get from $u$ to $v$, moving from the vertex to the parent. In particular, vertex $v$ is in its subtree.\n\nRoma gives you $m$ queries, the $i$-th of which consists of two numbers $v_{i}$, $h_{i}$. Let's consider the vertices in the subtree $v_{i}$ located at depth $h_{i}$. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.",
    "tutorial": "We need to write vertices in DFS order and store time of enter/exit of vertices in DFS. All vertices in subtree represent a segment. Now we can get all vertices in subtree v on height h as a segment, making two binary searches. We can make a palindrome if quantity of uneven entries of each letter is less than 2. This function can be counted for each prefix in bypass for each depth. For saving the memory bit compression can be used considering that we need only parity and function is xor. $O(m * (log + 26) + n)$ D had a offline solution too in $O(n + m * (26 / 32))$ time and $O(n * 26 / 8)$ memory",
    "code": "#define _ijps 0\n#define _CRT_SECURE_NO_DEPRECATE\n#pragma comment(linker, \"/STACK:667772160\")\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <time.h>\n#include <map>\n#include <set>\n#include <deque>\n#include <cstdio>\n#include <cstdlib>\n#include <unordered_map>\n#include <bitset>\n#include <algorithm>\n#include <string>\n#include <fstream>\n#include <assert.h>\n#include <list>\n#include <cstring>\nusing namespace std;\n \n#define name \"\"\ntypedef unsigned long long ull;\ntypedef long long ll;\n#define mk make_pair\n#define forn(i, n) for(ll i = 0; i < (ll)n; i++)\n#define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++)\n#define times clock() * 1.0 / CLOCKS_PER_SEC\n#define inb push_back\n \nstruct __isoff{\n\t__isoff(){\n\t\tif (_ijps)\n\t\t\tfreopen(\"input.txt\", \"r\", stdin), freopen(\"output.txt\", \"w\", stdout);//, freopen(\"test.txt\", \"w\", stderr);\n\t\t//else freopen(name\".in\", \"r\", stdin), freopen(name\".out\", \"w\", stdout);\n\t\t//ios_base::sync_with_stdio(0);\n\t\tsrand(time(0));\n\t\t//srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A');\n\t}\n\t~__isoff(){\n\t\t//if(_ijps) cout<<times<<'\\n';\n\t}\n} __osafwf;\nconst ull p1 = 31;\nconst ull p2 = 29;\nconst double eps = 1e-8;\nconst double pi = acos(-1.0);\n \nconst ll inf = 1e17 + 7;\nconst int infi = 1e9 + 7;\nconst ll dd = 2e6 + 7;\nconst ll mod = 1e9 + 7;\n \nint n, m;\nvector<int> P[dd];\nvector<pair<int, int> > H[dd];\nint In[dd], Out[dd];\nint A[30];\nint ti = 0;\nstring s;\n \nvoid dfs(int v, int h){\n\tIn[v] = ++ti;\n\tH[h].push_back(mk(ti, H[h].back().second ^ A[s[v] - 'a']));\n\tforn(i, P[v].size())\n\t\tdfs(P[v][i], h + 1);\n\tOut[v] = ++ti;\n}\n \nint main(){\n\tcin >> n >> m;\n\tforn(i, n)\n\t    H[i].resize(1);\n\tforn(i, 30)\n\t\tA[i] = 1 << i;\n\tforn(i, n - 1){\n\t\tint t;\n\t\tscanf(\"%d\", &t);\n\t\tP[t - 1].push_back(i + 1);\n\t}\n\tcin >> s;\n\tdfs(0, 0);\n\tforn(i, m){\n\t\tint h, v;\n\t\tscanf(\"%d%d\", &v, &h);\n\t\tv--, h--;\n\t\tint l = lower_bound(H[h].begin(), H[h].end(), mk(In[v], -1)) - H[h].begin() - 1;\n\t\tint r = lower_bound(H[h].begin(), H[h].end(), mk(Out[v], -1)) - H[h].begin() - 1;\n\t\tint t = H[h][l].second ^ H[h][r].second;\n\t\tbool ok = t - (t & -t);\n\t\tif(!ok)\n\t\t\tprintf(\"Yes\\n\");\n\t\telse\n\t\t\tprintf(\"No\\n\");\n\t}\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "570",
    "index": "E",
    "title": "Pig and Palindromes",
    "statement": "Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of $n$ rows and $m$ columns. We enumerate the rows of the rectangle from top to bottom with numbers from $1$ to $n$, and the columns — from left to right with numbers from $1$ to $m$. Let's denote the cell at the intersection of the $r$-th row and the $c$-th column as $(r, c)$.\n\nInitially the pig stands in cell $(1, 1)$, and in the end she wants to be in cell $(n, m)$. Since the pig is in a hurry to get home, she can go from cell $(r, c)$, only to either cell $(r + 1, c)$ or $(r, c + 1)$. She cannot leave the forest.\n\nThe forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).\n\nCount the number of beautiful paths from cell $(1, 1)$ to cell $(n, m)$. Since this number can be very large, determine the remainder after dividing it by $10^{9} + 7$.",
    "tutorial": "We need palindrome paths. Palindrome is word which reads the same backward or forward. We can use it. Count the dynamic from coordinates of 2 cells, first and latest in palindrome. From each state exists 4 transitions (combinations: first cell down/to the right and second cell up/to the left). We need only transitions on equal symbols for making a palindrome. Note that we need a pairs of cells on equal distance from start and end for each. For saving memory we need to store two latest layers. $O(n^{3})$ - time and $O(n^{2})$ - memory",
    "code": "#define _ijps 0\n#define _CRT_SECURE_NO_DEPRECATE\n#pragma comment(linker, \"/STACK:667772160\")\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <time.h>\n#include <map>\n#include <set>\n#include <deque>\n#include <cstdio>\n#include <cstdlib>\n#include <unordered_map>\n#include <bitset>\n#include <algorithm>\n#include <string>\n#include <fstream>\n#include <assert.h>\n#include <list>\n#include <cstring>\nusing namespace std;\n \n#define name \"\"\ntypedef unsigned long long ull;\ntypedef long long ll;\n#define mk make_pair\n#define forn(i, n) for(ll i = 0; i < (ll)n; i++)\n#define fornn(i, q, n) for(ll i = (ll)q; i < (ll)n; i++)\n#define times clock() * 1.0 / CLOCKS_PER_SEC\n#define inb push_back\n \nstruct __isoff{\n\t__isoff(){\n\t\tif (_ijps)\n\t\t\tfreopen(\"input.txt\", \"r\", stdin), freopen(\"output.txt\", \"w\", stdout);//, freopen(\"test.txt\", \"w\", stderr);\n\t\t//else freopen(name\".in\", \"r\", stdin), freopen(name\".out\", \"w\", stdout);\n\t\t//ios_base::sync_with_stdio(0);\n\t\tsrand(time(0));\n\t\t//srand('C' + 'T' + 'A' + 'C' + 'Y' + 'M' + 'B' + 'A');\n\t}\n\t~__isoff(){\n\t\t//if(_ijps) cout<<times<<'\\n';\n\t}\n} __osafwf;\nconst ull p1 = 31;\nconst ull p2 = 29;\nconst double eps = 1e-8;\nconst double pi = acos(-1.0);\n \nconst ll inf = 1e17 + 7;\nconst int infi = 1e9 + 7;\nconst ll dd = 500 + 7;\nconst ll mod = 1e9 + 7;\n \nint n, m, t;\n \nvector< vector<int> > Dp, Pdp;\npair<int, int> in[dd][2 * dd];\nint ou[dd][dd];\nchar C[dd][dd];\n \nint main(){\n\tcin >> n >> m;\n\tforn(i, dd){\n\t\tforn(j, dd){\n\t\t\tint x = i - j, y = j;\n\t\t\tif(x >= n || x < 0 || y >= m || y < 0)\n\t\t\t\tcontinue;\n\t\t\tou[x][y] = j;\n\t\t\tin[j][x + y] = mk(x, y);\n\t\t}\n\t}\n\tforn(i, dd){\n\t\tforn(j, dd){\n\t\t\tint x = n - 1 - j, y = i + j;\n\t\t\tif(x >= n || x < 0 || y >= m || y < 0)\n\t\t\t\tcontinue;\n\t\t\tou[x][y] = j;\n\t\t\tin[j][x + y] = mk(x, y);\n\t\t}\n\t}\n\tvector<int> Si(n + m);\n\tforn(i, n){\n\t\tforn(j, m){\n\t\t\tSi[i + j]++;\n\t\t}\n\t}\n \n\tforn(i, n){\n\t\tforn(j, m){\n\t\t\tcin >> C[i][j];\n\t\t}\n\t}\n \n\tint ts = (n + m - 2) / 2;\n\tint t = Si[ts];\n\tDp.resize(t, vector<int>(t));\n\tforn(x, t){\n\t\tforn(y, t){\n\t\t\tint x1 = in[x][ts].first, y1 = in[x][ts].second;\n\t\t\tint x2 = in[y][n + m - 2 - ts].first, y2 = in[y][n + m - 2 - ts].second;\n\t\t\tif ((x1 == x2 && (y1 == y2 || y1 + 1 == y2)) || (y1 == y2 && (x1 == x2 || x1 + 1 == x2)))\n\t\t\t\tDp[x][y] = C[x1][y1] == C[x2][y2];\n\t\t}\n\t}\n\tfor (ts--; ts >= 0; ts--){\n\t\tt = Si[ts];\n\t\tPdp.assign(t, vector<int>(t));\n\t\tforn(x, t){\n\t\t\tforn(y, t){\n\t\t\t\tint x1 = in[x][ts].first, y1 = in[x][ts].second;\n\t\t\t\tint x2 = in[y][n + m - 2 - ts].first, y2 = in[y][n + m - 2 - ts].second;\n\t\t\t\tif(C[x1][y1] == C[x2][y2]){\n\t\t\t\t\tll s = 0;\n\t\t\t\t\tif (x2 - 1 >= 0 && x1 + 1 < n)\n\t\t\t\t\t\ts += Dp[ou[x1 + 1][y1]][ou[x2 - 1][y2]];\n\t\t\t\t\tif (y2 - 1 >= 0 && x1 + 1 < n)\n\t\t\t\t\t\ts += Dp[ou[x1 + 1][y1]][ou[x2][y2 - 1]];\n\t\t\t\t\tif (x2 - 1 >= 0 && y1 + 1 < m)\n\t\t\t\t\t\ts += Dp[ou[x1][y1 + 1]][ou[x2 - 1][y2]];\n\t\t\t\t\tif (y2 - 1 >= 0 && y1 + 1 < m)\n\t\t\t\t\t\ts += Dp[ou[x1][y1 + 1]][ou[x2][y2 - 1]];\n\t\t\t\t\tPdp[x][y] = s % mod;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tswap(Pdp, Dp);\n\t}\n\tcout << Dp[0][0];\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "571",
    "index": "A",
    "title": "Lengthening Sticks",
    "statement": "You are given three sticks with positive integer lengths of $a, b$, and $c$ centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most $l$ centimeters. In particular, it is allowed not to increase the length of any stick.\n\nDetermine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.",
    "tutorial": "Let's count the number of ways to form a triple which can't represent triangle sides, and then we subtract this value from $C_{l+3}^{3}={\\stackrel{(l+1)(l+2)(l+3)}{6}}$ - the total number of ways to increase the sticks not more than $l$ in total. This number is obtained from partition of $l$ into 4 summands ($l_{a} + l_{b} + l_{c} + unused_{l} = l$), or can be counted using a for loop. Now we consider triples $a + l_{a}, b + l_{b}, c + l_{c}$, where $l_{a} + l_{b} + l_{c}  \\le  l, l_{a}, l_{b}, l_{c}  \\ge  0$. Fix the maximal side, for example it would be $a + l_{a}$. We'll have to do the following algo for $b + l_{b}$ and $c + l_{c}$ in the same way. The triple is not a triangle with maximal side $a + l_{a}$ if $a + l_{a}  \\ge  b + l_{b} + c + l_{c}$. If we iterate over $l_{a}$ between $0$ and $l$, we have the following conditions on $l_{b}, l_{c}$: $l_{b} + l_{c}  \\le  a - b - c + l_{a},$ $l_{b} + l_{c}  \\le  l - l_{a},$ $l_{b}, l_{c}  \\ge  0.$ So, non-negative integers $l_{b}, l_{c}$ should be such that $l_{b} + l_{c}  \\le  min(a - b - c + l_{a}, l - l_{a})$. If we denote this minimum as $x$ than we can choose $l_{b}, l_{c}$ in $\\textstyle{\\frac{(x+1)(x+2)}{2}}$ different ways (again we divide $x$ into three summands: $l_{b}, l_{c}$ and some unused volume). Also when we fix $l_{b}$, there are $x - l_{b} + 1$ ways to choose $l_{c}$, so the overall number of pair $l_{b}, l_{c}$ is $\\sum_{l_{b}=0}^{x}(x-l_{b}+1)=\\sum_{a=1}^{x+1}a={\\frac{(x+1)(x+2)}{2}},$ so we obtain the same formula. To sum up, we need to iterate over the maximal side and over the addition to that side, then write these formulas, and subtract the result from the total number of different additions to the sides. The complexity of the solution is $O(l)$.",
    "code": "#pragma comment (linker, \"/STACK:1280000000\")\n#define _CRT_SECURE_NO_WARNINGS\n//#include \"testlib.h\"\n#include <cstdio>\n#include <cassert>\n#include <algorithm>\n#include <iostream>\n#include <memory.h>\n#include <string>\n#include <vector>\n#include <set>\n#include <map>\n#include <cmath>\n#include <bitset>\n#include <deque>\n//#include <unordered_map>\n//#include <unordered_set>\n#include <ctime>\n#include <stack>\n#include <queue>\n#include <fstream>\nusing namespace std;\n//#define FILENAME \"\"\n#define mp make_pair\n#define all(a) a.begin(), a.end()\ntypedef long long li;\ntypedef long double ld;\nvoid solve();\nvoid precalc();\nclock_t start;\n//int timer = 1;\n \nbool todo = true;\n \nint main() {\n#ifdef room111\n\tfreopen(\"in.txt\", \"r\", stdin);\n\t//freopen(\"out.txt\", \"w\", stdout);\n#else\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\t//freopen(FILENAME\".in\", \"r\", stdin);\n\t//freopen(FILENAME \".out\", \"w\", stdout);\n#endif\n\tint t = 1;\n\tcout.sync_with_stdio(0);\n\tcin.tie(0);\n\tprecalc();\n\tcout.precision(10);\n\tcout << fixed;\n\t//cin >> t;\n\tstart = clock();\n\tint testNum = 1;\n\twhile (t--) {\n\t\t//cout << \"Case #\" << testNum++ << \": \";\n\t\tsolve();\n\t\t//++timer;\n\t}\n \n#ifdef room111\n\tcerr << \"\\n\\n\" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << \"\\n\\n\";\n#endif\n \n\treturn 0;\n}\n \n//BE CAREFUL: IS INT REALLY INT?\n \n//#define int li\n \n/*int pr[] = { 97, 2011 };\nint mods[] = { 1000000007, 1000000009 };\n \nconst int C = 100500;\nint powers[2][C];*/\n \nint MOD = 1000000007;\n \n//int c[5010][5010];\n \n//int catalan[200500];\n \n//ld doubleC[100][100];\n \nint binpow(int q, int w, int mod) {\n\tif (!w)\n\t\treturn 1;\n\tif (w & 1)\n\t\treturn q * 1LL * binpow(q, w - 1, mod) % mod;\n\treturn binpow(q * 1LL * q % mod, w / 2, mod);\n}\n \nvoid precalc() {\n \n\t/*for (int w = 0; w < 2; ++w) {\n\tpowers[w][0] = 1;\n\tfor (int j = 1; j < C; ++j) {\n\tpowers[w][j] = (powers[w][j - 1] * 1LL * pr[w]) % mods[w];\n\t}\n\t}*/\n \n\t/*catalan[0] = 1;\n\tfor (int n = 0; n < 200500 - 1; ++n) {\n\tcatalan[n + 1] = catalan[n] * 2 * (2 * n + 1) % MOD * binpow(n + 2, MOD - 2, MOD) % MOD;\n\t}*/\n \n\t/*for (int i = 0; i < 5010; ++i) {\n\tc[i][i] = c[i][0] = 1;\n\tfor (int j = 1; j < i; ++j) {\n\tc[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MOD;\n\t}\n\t}*/\n \n\t/*for (int i = 0; i < 100; ++i) {\n\tdoubleC[i][i] = doubleC[i][0] = 1.0;\n\tfor (int j = 1; j < i; ++j) {\n\tdoubleC[i][j] = doubleC[i - 1][j - 1] + doubleC[i - 1][j];\n\t}\n\t}*/\n}\n \n \nint gcd(int q, int w) {\n\twhile (w) {\n\t\tq %= w;\n\t\tswap(q, w);\n\t}\n\treturn q;\n}\n \n#define int li\n \n//int mod = 1000000007;\n \nint cnt(int a, int b, int c, int s) {\n\tif (s + a < b + c) {\n\t\treturn 0;\n\t}\n\tint cur = min(s, (s + a - b - c) / 2);\n\treturn (cur + 1) * (cur + 2) / 2;\n}\n \nvoid solve() {\n\tint a[3];\n\tint L;\n\tfor (int i = 0; i < 3; ++i) {\n\t\tcin >> a[i];\n\t}\n\tcin >> L;\n\tint ans = 0;\n\tfor (int i = 0; i <= L; ++i) {\n\t\tans += (L - i + 1) * (L - i + 2) / 2;\n\t}\n \n\tfor (int i = 0; i < 3; ++i) {\n\t\tfor (int s = 0; s <= L; ++s) {\n\t\t\tans -= cnt(a[i], a[(i + 1) % 3], a[(i + 2) % 3], s);\n\t\t}\n\t}\n \n\tcout << ans << \"\\n\";\n \n}",
    "tags": [
      "combinatorics",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "571",
    "index": "B",
    "title": "Minimization",
    "statement": "You've got array $A$, consisting of $n$ integers and a positive integer $k$. Array $A$ is indexed by integers from $1$ to $n$.\n\nYou need to permute the array elements so that value\n\n\\[\n\\sum_{i=1}^{n-k}|A[i]-A[i+k]|\n\\]\n\nbecame minimal possible. In particular, it is allowed not to change order of elements at all.",
    "tutorial": "We can divide all indices $[1;n]$ into groups by their remainder modulo $k$. While counting $\\sum_{i=1}^{n-k}|a_{i}-a_{i+k}|$, we can consider each group separately and sum the distances between neighbouring numbers in each group. Consider one group, corresponding to some remainder $i$ modulo $k$, i.e. containing $a_{j}$ for $j\\equiv i\\mod(k)$. Let's write down its numbers from left to right: $b_{1}, b_{2}, ..., b_{m}$. Then this group adds to the overall sum the value $\\sum_{j=1}^{m-1}|b_{j}-b_{j+1}|.$ We can notice that if we sort $b_{1}, ..., b_{m}$ in non-decreasing order, this sum will not increase. So, in the optimal answer we can consider that numbers in each group don't decrease. Furthermore, in that case this sum is equal to $|b_{m} - b_{1}|$. Now consider two groups $b_{1}, ..., b_{m}$ and $c_{1}, c_{2}, ..., c_{l}$, both sorted in non-decreasing order. We claim that either $b_{1}  \\ge  c_{l}$ or $b_{m}  \\le  c_{1}$, i.e. segments $[b_{1}, b_{m}]$ and $[c_{1}, c_{l}]$ can have common points only in their endpoints. Why is this true? These groups add $|b_{m} - b_{1}| + |c_{l} - c_{1}|$ to the overall sum. We consider the case $c_{1}  \\ge  b_{1}$, the other is symmetric. If $c_{1} < b_{m}$, then swapping $c_{1}$ and $b_{m}$ will not increase the values these groups add to the answer, since the right border of $b$ group moves to the left, and the left border of $c$ group moves to the right. So, $c_{1}  \\ge  b_{m}$ in that case, and the assertion is proved. Now we know that the values in each group should from a continuous segment of the sorted original array. In fact, we have $k-(n\\mod k)$ groups of size $\\scriptstyle{\\frac{n}{k}}$ (so called small groups) and $(n\\mod k)$ groups of size $\\textstyle{\\binom{n}{k}}$ (so called large groups). Consider the following dynamic programming: $dp[L][S]$ - the minimal sum of values added to the answer by $L$ large groups and $S$ small groups, if we choose the elements for them from the first $L\\cdot({\\frac{n}{k}}+1)+S\\cdot{\\frac{n}{k}}$ elements of the sorted array $A$. There are no more than $O(k^{2})$ states, and each transition can be made in $O(1)$: we choose large or small group to add and obtain the number it adds to the sum by subtracting two elements of the sorted array. The answer for the problem will be in $d p[(n\\mathrm{\\boldmath~\\mod~}k)][k-(n\\mathrm{\\boldmath~\\mod~}k)]$. The overall complexity of the solution is $O(n\\log n+k^{2})$. We can note that in pretests $(n\\mod k)$ was quite small, and some slower solutions could pass, but they failed on final tests.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#pragma comment (linker, \"/STACK:128000000\")\n#include <stdio.h>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <queue>\n#include <deque>\n#include <cmath>\n#include <ctime>\n#include <stack>\n#include <set>\n#include <map>\n#include <cassert>\n#include <memory.h>\n#include <sstream>\n \nusing namespace std;\n \n#define mp make_pair\n#define pb push_back\n#define all(a) a.begin(), a.end()\n \n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n \ntypedef long long li;\ntypedef long long i64;\ntypedef double ld;\ntypedef vector<int> vi;\ntypedef pair <int, int> pi;\n \nvoid solve();\n \nvoid precalc();\n \nint TESTNUM = 0;\n#define FILENAME \"\"\n \nint main() {\n\tstring s = FILENAME;\n#ifdef AIM\n\t//assert(!s.empty());\n\tfreopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\t//cerr<<FILENAME<<endl;\n\t//assert (s != \"change me please\");\n\tclock_t start = clock();\n#else\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\t//freopen(FILENAME \".in\", \"r\", stdin);\n\t//freopen(FILENAME \".out\", \"w\", stdout); \n\tcin.tie(0);\n#endif\n\tcout.sync_with_stdio(0);\n\tcout.precision(10);\n\tcout << fixed;\n\tprecalc();\n\tint t = 1;\n\t//cin >> t;\n\twhile (t--) {\n\t\t++TESTNUM;\n\t\tsolve();\n\t}\n#ifdef AIM\n\tcerr << \"\\n\\n\\n\" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << \"\\n\\n\\n\";\n#endif\n\treturn 0;\n}\n \n//#define int li\n \n/*int pr[] = { 97, 2011 };\nint mods[] = { 1000000007, 1000000009 };\n \nconst int C = 100500;\nint powers[2][C];*/\n \nint MOD = 1000000007;\n \n//int c[5010][5010];\n \n//int catalan[200500];\n \n//ld doubleC[100][100];\n \nint binpow(int q, int w, int mod) {\n\tif (!w)\n\t\treturn 1;\n\tif (w & 1)\n\t\treturn q * 1LL * binpow(q, w - 1, mod) % mod;\n\treturn binpow(q * 1LL * q % mod, w / 2, mod);\n}\n \nvoid precalc() {\n \n\t/*for (int w = 0; w < 2; ++w) {\n\tpowers[w][0] = 1;\n\tfor (int j = 1; j < C; ++j) {\n\tpowers[w][j] = (powers[w][j - 1] * 1LL * pr[w]) % mods[w];\n\t}\n\t}*/\n \n\t/*catalan[0] = 1;\n\tfor (int n = 0; n < 200500 - 1; ++n) {\n\tcatalan[n + 1] = catalan[n] * 2 * (2 * n + 1) % MOD * binpow(n + 2, MOD - 2, MOD) % MOD;\n\t}*/\n \n\t/*for (int i = 0; i < 5010; ++i) {\n\tc[i][i] = c[i][0] = 1;\n\tfor (int j = 1; j < i; ++j) {\n\tc[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MOD;\n\t}\n\t}*/\n \n\t/*for (int i = 0; i < 100; ++i) {\n\tdoubleC[i][i] = doubleC[i][0] = 1.0;\n\tfor (int j = 1; j < i; ++j) {\n\tdoubleC[i][j] = doubleC[i - 1][j - 1] + doubleC[i - 1][j];\n\t}\n\t}*/\n}\n \n \nint gcd(int q, int w) {\n\twhile (w) {\n\t\tq %= w;\n\t\tswap(q, w);\n\t}\n\treturn q;\n}\n \n//#define int li\n \n//int mod = 1000000007;\n \n \nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n \n\tint part = n / k;\n\tint large = n % k;\n \n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(all(a));\n \n\tvector<vector<int>> dp(large + 1, vector<int>(k - large + 1, 2e9));\n\tdp[0][0] = 0;\n\tfor (int largeParts = 0; largeParts <= large; ++largeParts) {\n\t\tfor (int smallParts = 0; smallParts <= k - large; ++smallParts) {\n\t\t\tint nex = largeParts * (part + 1) + smallParts * part;\n\t\t\tif (largeParts < large) {\n\t\t\t\tint add = a[nex + part] - a[nex];\n\t\t\t\tdp[largeParts + 1][smallParts] = min(dp[largeParts + 1][smallParts], dp[largeParts][smallParts] + add);\n\t\t\t}\n\t\t\tif (smallParts < k - large) {\n\t\t\t\tint add = a[nex + part - 1] - a[nex];\n\t\t\t\tdp[largeParts][smallParts + 1] = min(dp[largeParts][smallParts + 1], dp[largeParts][smallParts] + add);\n\t\t\t}\n\t\t}\n\t}\n \n\tcout << dp[large][k - large] << \"\\n\";\n \n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "571",
    "index": "C",
    "title": "CNF 2",
    "statement": "'In Boolean logic, a formula is in conjunctive normal form (CNF) or clausal normal form if it is a conjunction of clauses, where a clause is a disjunction of literals' (cited from https://en.wikipedia.org/wiki/Conjunctive_normal_form)\n\nIn the other words, CNF is a formula of type $\\left(v_{11}\\mid v_{12}\\mid\\cdot\\cdot\\cdot\\mid v_{1k_{1}}\\rangle\\,\\Re(v_{21}\\mid v_{22}\\mid\\cdot\\cdot\\cdot\\mid v_{2k_{2}})\\,\\hat{G}\\cdot\\cdot\\cdot\\cdot\\hat{G}(v_{l1}\\mid v_{l2}\\mid\\cdot\\cdot\\cdot\\cdot\\mid v_{l k_{l}})\\right),$, where $&$ represents a logical \"AND\" (conjunction), represents a logical \"OR\" (disjunction), and $v_{ij}$ are some boolean variables or their negations. Each statement in brackets is called a clause, and $v_{ij}$ are called literals.\n\nYou are given a CNF containing variables $x_{1}, ..., x_{m}$ and their negations. We know that each variable occurs in at most two clauses (with negation and without negation in total). Your task is to determine whether this CNF is satisfiable, that is, whether there are such values of variables where the CNF value is true. If CNF is satisfiable, then you also need to determine the values of the variables at which the CNF is true.\n\nIt is guaranteed that each variable occurs at most once in each clause.",
    "tutorial": "Firstly let's assign values to variables occurring in our fomula only with negation or only without negation. After that we can throw away the disjuncts which contained them, since they are already true, and continue the process until it is possible. To make it run in time limit, one should use dfs or bfs algorithm to eliminate these variables and disjuncts. So now we have only variables which have both types of occurrences in disjucnts. Let's build a graph with the vertices corresponding to disjuncts, and for each varible $a$ make an edge between the disjuncts that contain $a$ and $!a$. Now we should choose the directions of edges in this graph in such a way that every vertex has at least one incoming edge. We can notice that if some connected component of this graph is a tree, the solution is not possible: on each step we can take some leaf of this tree, and we have to orient its only edge to it, and then erase the leaf. In the end we'll have only one vertex, and it'll not have any incoming edges. Otherwise, take some cycle in the component and orient the edges between neighbouring vertices along it. Then run dfs from every vertex of the cycle and orient each visited edge in the direction we went along it. It is easy to easy that after this process every vertex will have at least one incoming edge. So, we should consider cases with the variables which values can be assigned at once, than construct a graph from disjuncts and variables and find whether each connected component has a cycle. If so, we also should carefully construct the answer, assigning the remaining variables their values, looking at the directions of the edges in the graph. The overall complexity is $O(n + m)$.",
    "code": "#pragma comment (linker, \"/STACK:128000000\") \n//#include \"testlib.h\" \n#include <cstdio> \n#include <cassert> \n#include <algorithm> \n#include <iostream> \n#include <memory.h> \n#include <string> \n#include <vector> \n#include <set> \n#include <map> \n#include <cmath> \n#include <bitset> \n//#include <unordered_map> \n//#include <unordered_set> \n#include <ctime> \n#include <stack> \n#include <queue> \nusing namespace std;\n//#define FILENAME \"\" \n#define mp make_pair \n#define all(a) a.begin(), a.end() \ntypedef long long li;\ntypedef long double ld;\nvoid solve();\nvoid precalc();\nclock_t start;\n//int timer = 1; \n \nbool doing = true;\n \nint main() {\n#ifdef AIM\n\tfreopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"out.txt\", \"w\", stdout); \n#else \n\t//freopen(\"input.txt\", \"r\", stdin); \n\t//freopen(\"output.txt\", \"w\", stdout); \n\t//freopen(FILENAME\".in\", \"r\", stdin); \n\t//freopen(FILENAME \".out\", \"w\", stdout); \n#endif \n\tint t = 1;\n\tcout.sync_with_stdio(0);\n\tcin.tie(0);\n\tprecalc();\n\tcout.precision(10);\n\tcout << fixed;\n\t//cin >> t;\n\tstart = clock();\n\tint testNum = 1;\n\twhile (t--) {\n\t\t//cout << \"Case #\" << testNum++ << \": \"; \n\t\tsolve();\n\t\t//++timer; \n\t}\n \n#ifdef room111 \n\tcerr << \"\\n\\n\" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << \"\\n\\n\";\n#endif \n \n\treturn 0;\n}\n \n//BE CAREFUL: IS INT REALLY INT? \n \n//#define int li \n \nvoid precalc() {\n \n \n}\n \nint binpow(int q, int w, int mod) {\n\tif (!w)\n\t\treturn 1;\n\tif (w & 1)\n\t\treturn q * binpow(q, w - 1, mod) % mod;\n\treturn binpow(q * q % mod, w / 2, mod);\n}\n \nint gcd(int q, int w) {\n\twhile (w) {\n\t\tq %= w;\n\t\tswap(q, w);\n\t}\n\treturn q;\n}\n \nvector<vector<pair<int, int>>> dis;\nvector<vector<vector<int>>> has;\n \nvector<char> done;\n \nvector<int> res;\n \nvoid erase(vector<int>& cur, int val) {\n\tfor (auto it = cur.begin(); it != cur.end(); ++it) {\n\t\tif (*it == val) {\n\t\t\tcur.erase(it);\n\t\t\treturn;\n\t\t}\n\t}\n\tassert(false);\n}\n \nvoid dfs(int v) {\n\tif (res[v] != -1) {\n\t\treturn;\n\t}\n\tassert(has[v][0].size() == 0 || has[v][1].size() == 0);\n\tbool have = false;\n\tfor (int j = 0; j < 2; ++j) {\n\t\tif (!have && has[v][j].size() == 0) {\n\t\t\tres[v] = j ^ 1;\n\t\t\thave = true;\n\t\t\tcontinue;\n\t\t}\n\t\tvector<int> now = has[v][j];\n\t\tfor (int num : now) {\n\t\t\tif (done[num]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdone[num] = true;\n\t\t\tfor (auto liter : dis[num]) {\n\t\t\t\tint var = liter.first;\n\t\t\t\tint type = liter.second;\n\t\t\t\terase(has[var][type], num);\n\t\t\t\tif (has[var][type].empty()) {\n\t\t\t\t\tdfs(var);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n \nvector<vector<int>> gr;\nvector<int> mt;\nvector<int> revmt;\nvector<char> used;\nbool try_kuhn(int v) {\n\tif (used[v]) {\n\t\treturn false;\n\t}\n\tused[v] = true;\n\tfor (size_t i = 0; i<gr[v].size(); ++i) {\n\t\tint to = gr[v][i];\n\t\tif (mt[to] == -1 || try_kuhn(mt[to])) {\n\t\t\tmt[to] = v;\n\t\t\trevmt[v] = to;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n \nvoid solve() {\n\tint n, vars;\n\tscanf(\"%d%d\", &n, &vars);\n\tdis.resize(n);\n\thas.assign(vars, vector<vector<int>>(2));\n\tfor (int i = 0; i < n; ++i) {\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\tdis[i].resize(k);\n\t\tfor (int j = 0; j < k; ++j) {\n\t\t\tint cur;\n\t\t\tscanf(\"%d\", &cur);\n\t\t\tint type = 1;\n\t\t\tif (cur < 0) {\n\t\t\t\ttype = 0;\n\t\t\t\tcur = -cur;\n\t\t\t}\n\t\t\t--cur;\n\t\t\tdis[i][j] = make_pair(cur, type);\n\t\t\thas[cur][type].push_back(i);\n\t\t}\n\t}\n \n\tdone.assign(n, false);\n \n\tres.assign(vars, -1);\n\tfor (int i = 0; i < vars; ++i) {\n\t\tfor (int j = 0; j < 2; ++j) {\n\t\t\tif (has[i][j].empty()) {\n\t\t\t\tdfs(i);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tgr.resize(n);\n \n\tfor (int i = 0; i < n; ++i) {\n\t\tif (done[i]) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (auto item : dis[i]) {\n\t\t\tgr[i].push_back(item.first);\n\t\t}\n\t}\n \n\tmt.assign(vars, -1);\n\trevmt.assign(n, -1);\n\tfor (int run = 1; run;) {\n\t\trun = 0;\n\t\tused.assign(n, false);\n\t\tfor (int v = 0; v < n; ++v) {\n\t\t\tif (!done[v] && revmt[v] == -1 && try_kuhn(v)) {\n\t\t\t\trun = 1;\n\t\t\t}\n\t\t}\n\t}\n \n\tfor (int i = 0; i < n; ++i) {\n\t\tif (done[i]) {\n\t\t\tcontinue;\n\t\t}\n\t\tint cur = revmt[i];\n\t\tif (cur == -1) {\n\t\t\tcout << \"NO\\n\";\n\t\t\treturn;\n\t\t}\n\t\tint type = -1;\n\t\tfor (auto item : dis[i]) {\n\t\t\tif (item.first == cur) {\n\t\t\t\ttype = item.second;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tassert(type != -1);\n\t\tres[cur] = type;\n\t}\n \n\tcout << \"YES\\n\";\n\tfor (int i = 0; i < vars; ++i) {\n\t\tif (res[i] == -1) {\n\t\t\tres[i] = 0;\n\t\t}\n\t\tcout << res[i];\n\t}\n\tcout << \"\\n\";\n \n}\n ",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "571",
    "index": "D",
    "title": "Campus",
    "statement": "Oscolcovo city has a campus consisting of $n$ student dormitories, $n$ universities and $n$ military offices. Initially, the $i$-th dormitory belongs to the $i$-th university and is assigned to the $i$-th military office.\n\nLife goes on and the campus is continuously going through some changes. The changes can be of four types:\n\n- University $a_{j}$ merges with university $b_{j}$. After that all the dormitories that belonged to university $b_{j}$ are assigned to to university $a_{j}$, and university $b_{j}$ disappears.\n- Military office $c_{j}$ merges with military office $d_{j}$. After that all the dormitories that were assigned to military office $d_{j}$, are assigned to military office $c_{j}$, and military office $d_{j}$ disappears.\n- Students of university $x_{j}$ move in dormitories. Lets $k_{xj}$ is the number of dormitories that belong to this university at the time when the students move in. Then the number of students in each dormitory of university $x_{j}$ increases by $k_{xj}$ (note that the more dormitories belong to the university, the more students move in each dormitory of the university).\n- Military office number $y_{j}$ conducts raids on all the dormitories assigned to it and takes all students from there.\n\nThus, at each moment of time each dormitory is assigned to exactly one university and one military office. Initially, all the dormitory are empty.\n\nYour task is to process the changes that take place in the campus and answer the queries, how many people currently live in dormitory $q_{j}$.",
    "tutorial": "Let's suppose for each dormitory from $Q$ query we already know the last raid moment. When task will be much easier: we can throw away $M$ and $Z$ queries and to get right answer we should subtract two values: people count in dormitory right now and same count in a last raid moment. On this basis, we have such plan: For each $Q$ query let's find the last raid moment using $M$ and $Z$ queries. Find people count in two interesting moments using $U$ and $A$ queries. Calculcates the final answer. Let's try to solve the first part. We want to make such queries on disjoint sets: Merge two sets ($M$ query). Assign value $time$ for all elements in particular set ($Z$ query). Get value for a particular element ($Q$ query). To solve this task we'll use a well-known technique: \"merge smaller set to bigger\". We'll maintain such values: $elements$ - set elements. $set_id$ - for each element their set id. $last_set_update_time$ - last moment when assign operation has occurred for each set. $last_update_time$ - last moment when assign operation has occurred for each element. $actual_time$ - moment of time when $last_update_time$ was actually for the element. Let's focus on $actual_time$ value. It's obvious that when we merge two sets each element can have a different last assign moment. But after first assignment all elements from any set will have the same value. So the answer for $Q$ query for element $i$ from set $s$: If last_set_update_time[s]=actual_time[i] then last_update_time[i] else last_set_update_time[s] For each $Z$ query you should just update $last_set_update_time$ array. It's easy to maintain this values when you merge two sets: Let's suppose we want to merge set $from$ to set $to$. For each element from set $from$ we already know last assign time. So just update $last_update_time$ with this value and $actual_time$ is equal of last assign operation for set $to$. The second part of the solution is the same as first one. $O(n * lg(n) + m)$ time and $O(n + m)$ memory.",
    "code": "#pragma comment (linker, \"/STACK:128000000\") \n//#include \"testlib.h\" \n#include <cstdio> \n#include <cassert> \n#include <algorithm> \n#include <iostream> \n#include <memory.h> \n#include <string> \n#include <vector> \n#include <set> \n#include <map> \n#include <cmath> \n#include <bitset> \n//#include <unordered_map> \n//#include <unordered_set> \n#include <ctime> \n#include <stack> \n#include <queue> \nusing namespace std;\n//#define FILENAME \"\" \n#define mp make_pair \n#define all(a) a.begin(), a.end() \ntypedef long long li;\ntypedef long double ld;\nvoid solve();\nvoid precalc();\nclock_t start;\n//int timer = 1; \n \nbool doing = true;\n \nint main() {\n#ifdef room81\n\tfreopen(\"in.txt\", \"r\", stdin);\n\t//freopen(\"out.txt\", \"w\", stdout);\n#else \n\t//freopen(\"input.txt\", \"r\", stdin); \n\t//freopen(\"output.txt\", \"w\", stdout); \n\t//freopen(FILENAME\".in\", \"r\", stdin); \n\t//freopen(FILENAME \".out\", \"w\", stdout); \n#endif \n\tint t = 1;\n\tcout.sync_with_stdio(0);\n\tcin.tie(0);\n\tprecalc();\n\tcout.precision(10);\n\tcout << fixed;\n\t//cin >> t;\n\tstart = clock();\n\tint testNum = 1;\n\twhile (t--) {\n\t\t//cout << \"Case #\" << testNum++ << \": \"; \n\t\tsolve();\n\t\t//++timer; \n\t}\n \n#ifdef room81\n\tcerr << \"\\n\\n\" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << \"\\n\\n\";\n#endif \n \n\treturn 0;\n}\n \n//BE CAREFUL: IS INT REALLY INT? \n \n//#define int li \n \nvoid precalc() {\n \n \n}\n \nint binpow(int q, int w, int mod) {\n\tif (!w)\n\t\treturn 1;\n\tif (w & 1)\n\t\treturn q * 1LL * binpow(q, w - 1, mod) % mod;\n\treturn binpow(q * 1LL * q % mod, w / 2, mod);\n}\n \nint gcd(int q, int w) {\n\twhile (w) {\n\t\tq %= w;\n\t\tswap(q, w);\n\t}\n\treturn q;\n}\n \n//#define int li\n \nstruct _node;\n \ntypedef _node *node;\n \nstruct _node {\n\tint cnt, prior;\n\t_node* l;\n\t_node* r;\n\t_node* p;\n\tli val;\n\tli add;\n\tint lastNull;\n\tint lastNullToPush;\n\t_node() :val(0), add(0), lastNull(0), lastNullToPush(0) {\n\t\tprior = (rand() << 16) | rand();\n\t\tcnt = 1;\n\t\tl = nullptr;\n\t\tr = nullptr;\n\t\tp = nullptr;\n\t}\n\tinline void push() {\n\t\tif (l) {\n\t\t\tl->add += add;\n\t\t\tl->lastNullToPush = max(l->lastNullToPush, lastNullToPush);\n\t\t}\n\t\tif (r) {\n\t\t\tr->add += add;\n\t\t\tr->lastNullToPush = max(r->lastNullToPush, lastNullToPush);\n\t\t}\n\t\tlastNull = max(lastNull, lastNullToPush);\n\t\tval += add;\n\t\tadd = 0;\n\t\tlastNullToPush = 0;\n\t}\n\tinline void recalc() {\n\t\tp = nullptr;\n\t\tcnt = 1 + Cnt(l) + Cnt(r);\n\t\tif (l) {\n\t\t\tl->p = this;\n\t\t}\n\t\tif (r) {\n\t\t\tr->p = this;\n\t\t}\n\t}\n \n\tstatic int Cnt(_node* v) {\n\t\tif (!v)\n\t\t\treturn 0;\n\t\treturn v->cnt;\n\t}\n \n\tnode merge(node l, node r) {\n\t\tif (!l)\n\t\t\treturn r;\n\t\tif (!r)\n\t\t\treturn l;\n\t\tif (l->prior < r->prior) {\n\t\t\tl->push();\n\t\t\tl->r = merge(l->r, r);\n\t\t\tl->recalc();\n\t\t\treturn l;\n\t\t}\n\t\telse {\n\t\t\tr->push();\n\t\t\tr->l = merge(l, r->l);\n\t\t\tr->recalc();\n\t\t\treturn r;\n\t\t}\n\t}\n \n\tinline void split(node v, int key, node& l, node& r) {\n\t\tl = r = nullptr;\n\t\tif (!v)\n\t\t\treturn;\n\t\tv->push();\n\t\tint cur = Cnt(v->l);\n\t\tif (cur < key) {\n\t\t\tl = v;\n\t\t\tsplit(l->r, key - cur - 1, l->r, r);\n\t\t\tl->recalc();\n\t\t}\n\t\telse {\n\t\t\tr = v;\n\t\t\tsplit(r->l, key, l, r->l);\n\t\t\tr->recalc();\n\t\t}\n\t}\n \n\tnode push_back(node other) {\n\t\treturn merge(this, other);\n\t}\n \n\tint getLastZero(node v) {\n\t\tint res = v->lastNull;\n\t\twhile (v) {\n\t\t\tres = max(res, v->lastNullToPush);\n\t\t\tv = v->p;\n\t\t}\n\t\treturn res;\n\t}\n \n\tli getActualVal(_node* v) {\n\t\tli res = v->val;\n\t\twhile (v) {\n\t\t\tres += v->add;\n\t\t\tv = v->p;\n\t\t}\n\t\treturn res;\n\t}\n \n};\n \nenum {\n\tUNI_MERGE = 0,\n\tWAR_MERGE = 1,\n\tUNI_ADD = 2,\n\tWAR_ZERO = 3,\n\tQUERY = 4\n};\n \nstruct Query {\n\tint type;\n\tint q, w;\n\tint num;\n\tvoid scan() {\n\t\tchar c;\n\t\tcin >> c;\n\t\tswitch (c) {\n\t\tcase 'U':\n\t\t\ttype = UNI_MERGE;\n\t\t\tcin >> q >> w;\n\t\t\t--q; --w;\n\t\t\tbreak;\n\t\tcase 'M':\n\t\t\ttype = WAR_MERGE;\n\t\t\tcin >> q >> w;\n\t\t\t--q; --w;\n\t\t\tbreak;\n\t\tcase 'A':\n\t\t\ttype = UNI_ADD;\n\t\t\tcin >> q;\n\t\t\t--q;\n\t\t\tbreak;\n\t\tcase 'Z':\n\t\t\ttype = WAR_ZERO;\n\t\t\tcin >> q;\n\t\t\t--q;\n\t\t\tbreak;\n\t\tcase 'Q':\n\t\t\ttype = QUERY;\n\t\t\tcin >> q;\n\t\t\t--q;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(false);\n\t\t}\n\t}\n};\n \nvector<int> dsu[2];\n \nint findSet(int id, int v) {\n\tif (dsu[id][v] == v) {\n\t\treturn v;\n\t}\n\treturn dsu[id][v] = findSet(id, dsu[id][v]);\n}\n \nvoid merge(int id, int q, int w) {\n\tdsu[id][w] = q;\n}\n \nvoid solve() {\n\tint n, Q;\n\tcin >> n >> Q;\n \n\tvector<Query> ask;\n\tvector<vector<pair<int, int>>> askNum(Q);\n \n\tfor (int i = 0; i < Q; ++i) {\n\t\tQuery cur;\n\t\tcur.scan();\n\t\tcur.num = i;\n\t\tif (cur.type == QUERY) {\n\t\t\taskNum[i].push_back(mp(cur.q, i));\n\t\t}\n\t\task.push_back(cur);\n\t}\n \n\tvector<li> res(Q, 0);\n \n\tfor (int dom = 1; dom >= -1; dom -= 2) {\n\t\tvector<int> sizes(n, 1);\n\t\tvector<node> uni(n), war(n);\n\t\tvector<node> uniRoots(n), warRoots(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tuni[i] = new _node();\n\t\t\twar[i] = new _node();\n\t\t\tuniRoots[i] = uni[i];\n\t\t\twarRoots[i] = war[i];\n\t\t}\n\t\t\n\t\tfor (int w = 0; w < 2; ++w) {\n\t\t\tdsu[w].resize(n);\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tdsu[w][i] = i;\n\t\t\t}\n\t\t}\n \n\t\tfor (int i = 0; i < Q; ++i) {\n\t\t\tfor (auto item : askNum[i]) {\n\t\t\t\tint id = item.first;\n\t\t\t\tli curRes = uni[id]->getActualVal(uni[id]);\n\t\t\t\tres[item.second] += dom * curRes;\n\t\t\t}\n\t\t\taskNum[i].clear();\n \n\t\t\tauto& curAsk = ask[i];\n \n\t\t\tif (curAsk.type == QUERY) {\n\t\t\t\tint id = curAsk.q;\n\t\t\t\tint lastZero = war[id]->getLastZero(war[id]);\n\t\t\t\taskNum[lastZero].push_back(mp(id, i));\n\t\t\t}\n \n\t\t\tif (curAsk.type == UNI_MERGE) {\n\t\t\t\tuniRoots[curAsk.q] = uniRoots[curAsk.q]->push_back(uniRoots[curAsk.w]);\n\t\t\t\tsizes[curAsk.q] += sizes[curAsk.w];\n\t\t\t\tmerge(0, curAsk.q, curAsk.w);\n\t\t\t}\n \n\t\t\tif (curAsk.type == WAR_MERGE) {\n\t\t\t\twarRoots[curAsk.q] = warRoots[curAsk.q]->push_back(warRoots[curAsk.w]);\n\t\t\t\tmerge(1, curAsk.q, curAsk.w);\n\t\t\t}\n \n\t\t\tif (curAsk.type == UNI_ADD) {\n\t\t\t\tuniRoots[curAsk.q]->add += sizes[curAsk.q];\n\t\t\t}\n \n\t\t\tif (curAsk.type == WAR_ZERO) {\n\t\t\t\twarRoots[curAsk.q]->lastNullToPush = i;\n\t\t\t}\n\t\t}\n\t}\n \n\tfor (int i = 0; i < Q; ++i) {\n\t\tif (ask[i].type == QUERY) {\n\t\t\tcout << res[i] << \"\\n\";\n\t\t}\n\t}\n}\n ",
    "tags": [
      "binary search",
      "data structures",
      "dsu",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "571",
    "index": "E",
    "title": "Geometric Progressions",
    "statement": "Geometric progression with the first element $a$ and common ratio $b$ is a sequence of numbers $a, ab, ab^{2}, ab^{3}, ...$.\n\nYou are given $n$ integer geometric progressions. Your task is to find the smallest integer $x$, that is the element of all the given progressions, or else state that such integer does not exist.",
    "tutorial": "If intersection of two geometric progressions is not empty, set of common elements indexes forms arithmetic progression in each progression or consists of not more than one element. Let's intersect first progression with each other progression. If any of these intersections are empty then total intersection is empty. If some of these intersection consist of one element, then we could check only this element. Otherwise one could intersect arithmetic progressions of first progression indexes and take minimal element of this intersection. The remaining question is how intersect two geometric progression? Let's factorise all numbers in these two progressions and find set of appropriate indexes for every prime factor in both progressions. These progressions one need intersect both by values and by indexes.",
    "code": "#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <iostream>\n#include <set>\n#include <vector>\n#include <cstring>\n#include <string>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <complex>\n#include <map>\n#include <queue>\n#include <time.h>\nusing namespace std;\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef vector<double> vd;\ntypedef vector<vd> vvd;\ntypedef pair<int, int> pii;\ntypedef pair<double, double> pdd;\ntypedef vector<pii> vii;\ntypedef vector<string> vs;\nconst int mod = 1000000007;\ntime_t BEGIN;\n \nvoid out(const vi & v) {\n    for (int i = 0; i < v.size(); ++i) cerr << v[i] << ' ';\n    cerr << endl;\n}\n \nll mpow(ll x, ll n) {\n    ll res = 1;\n    while (n) {\n        if (n & 1) res = res * x % mod;\n        n /= 2;\n        x = x * x % mod;\n    }\n    return res;\n}\n \nll inv (ll a, ll b) {\n    a %= b;\n    ll b0 = b;\n    ll xa = 1, xb = 0, ya = 0, yb = 1;\n    while (a % b != 0) {\n        ll t = a / b;\n        a = (a - t * b) % b0;\n        xa = (xa - t * ya) % b0;\n        xb = (xb - t * yb) % b0;\n        swap(a, b);\n        swap(xa, ya);\n        swap(xb, yb);\n    }\n    ya %= b0;\n    if (ya < 0) ya += b0;\n    return ya;\n}\n \nll lcm(ll x, ll y) {\n    ll d = __gcd(x, y);\n    x /= d;\n    if (y) assert(x <= 1e18 / y);\n    return x * y;\n}\n \nclass AP {\npublic:\n    AP(ll s, ll T): s(s), T(T) {}\n    AP& operator=(const AP & a) { T = a.T; s = a.s; return *this; }\n    void out() {\n        cerr << s << \"+\" << T << \"k\\n\";\n    }\n    ll T, s;\n};\n \nAP strong_intersect(AP a, AP b) {\n    if (a.T == b.T) {\n        if (a.s == b.s) return a;\n        return AP(-1, -1);\n    }\n    if (a.s == b.s) return AP(a.s, 0);\n    if (a.s < b.s) swap(a, b);\n    ll num = a.s - b.s;\n    ll den = b.T - a.T;\n    if (den < 0 || num % den != 0) return AP(-1, -1);\n    ll index = num / den;\n    return AP(a.s + a.T*index, 0);\n}\n   \nll mul(ll x, ll y, ll z) {\n    if (x == 0 || y == 0) return 0;\n    if (y < 0) {\n        x = -x;\n        y = -y;\n    }\n    ll res = 0;\n    while (y) {\n        if (y & 1) res = (res + x) % z;\n        y /= 2;\n        x = (x + x) % z;\n    }\n    return res;\n}\n \nAP intersect(AP a, AP b) {\n//    a.out(); b.out();\n    if (a.s < 0 || b.s < 0) return AP(-1, -1);\n    if (a.T == 0 && b.T == 0) {\n        if (a.s == b.s) return a;\n        return AP(-1, -1);\n    }\n    if (b.T == 0) swap(a, b);\n    if (a.T == 0) {\n        if (b.s > a.s || (a.s - b.s) % b.T != 0) return AP(-1, -1);\n        return a;\n    }\n    ll d = __gcd(a.T, b.T);\n    if (a.s % d != b.s % d) return AP(-1, -1);\n    if (a.s < b.s) swap(a, b);\n    ll x = (b.s - a.s) / d; // x <= 0\n    ll y = b.T / d;\n    ll z = a.T / d; // (x + y*i) / z\n    assert(y <= 1e18 / z);\n    ll r = mul((-x) % z, inv(y, z), z);\n    ll mi = r + z*max(0LL, (-x - r*y + z*y - 1) / (z*y));\n    assert(mi <= 1e18 / b.T);\n//    cerr << x << ' ' << y << ' ' << z << ' ' << mi << endl;\n    AP res(b.s + b.T * mi, lcm(a.T, b.T));\n//    cerr << \"res \"; res.out();\n    return res;\n}\n \nvi uniq_merge(const vi & a, const vi & b) {\n    vi c(a.size() + b.size());\n    merge(a.begin(), a.end(), b.begin(), b.end(), c.begin());\n    c.resize(unique(c.begin(), c.end()) - c.begin());\n    return c;\n}\n \nint ord(int a, int p) {\n    int cnt = 0;\n    while (a % p == 0) {\n        ++cnt;\n        a /= p;\n    }\n    return cnt;\n}\n \nvi erat;\n \nvi get_primes(int n) {\n    vi primes;\n    for (int i = 2; i*i <= n; ++i) if (n % i == 0) {\n        primes.push_back(i);\n        while (n % i == 0) n /= i;\n    }\n    if (n > 1) primes.push_back(n);\n    sort(primes.begin(), primes.end());\n    return primes;\n}\n \nll fix(int A0, int B0, ll fix0, int A1, int B1, const vi & curp, bool & fail) {\n    ll fix = -1;\n    for (auto p : curp) {\n        AP a0(ord(A0, p), ord(B0, p));\n        if (fix0 >= 0) {\n            a0.s = a0.s + a0.T * fix0;\n            a0.T = 0;\n        }\n        AP a1(ord(A1, p), ord(B1, p));\n        AP a2 = intersect(a0, a1);\n        if (a2.s < 0) {\n            fail = true;\n            return -1;\n        }\n        if (a0.T == 0 && a1.T == 0 && a0.s != a1.s) {\n            fail = true;\n            return -1;\n        }\n        if (a2.T == 0 && a1.T != 0) {\n            ll nfix = (a2.s - a1.s) / a1.T;\n            if (fix != -1 && fix != nfix) {\n                fail = true;\n                return -1;\n            }\n            fix = nfix;\n        }\n    }\n    return fix;\n}\n \nAP trace(AP a, AP b) {\n    return AP((a.s - b.s) / b.T, a.T / b.T);\n}\n \nAP subsec(AP a, AP b) {\n    return AP(a.s + a.T * b.s, a.T * b.T);\n}\n \nAP common(int A0, int B0, int A1, int B1, const vi & curp) {\n    bool fail = false;\n    ll fix1 = fix(A0, B0, -1, A1, B1, curp, fail);\n//    cerr << \"fix1 \" << fix1 << ' ' << fail << endl;\n    ll fix0 = fix(A1, B1, fix1, A0, B0, curp, fail);\n//    cerr << \"fix0 \" << fix0 << ' ' << fail << endl;\n    if (fail) {\n        return AP(-1, -1);\n    }\n    if (fix0 >= 0) {\n        ll fix1 = fix(A0, B0, fix0, A1, B1, curp, fail);\n        if (fail || fix1 < 0) {\n            return AP(-1, -1);\n        } else {\n            return AP(fix0, 0);\n        }\n    }\n    AP intersection0(0, 1);\n    AP intersection1(0, 1);\n    bool was = false;\n    for (auto p : curp) {\n        AP a0(ord(A0, p), ord(B0, p));\n        AP a1(ord(A1, p), ord(B1, p));\n        AP a2 = intersect(a0, a1);\n        if (a2.s < 0) return AP(-1, -1);\n        if (a0.T == 0 && a1.T == 0) continue;\n        AP new0 = trace(a2, a0);//((a2.s - a0.s) / a0.T, a2.T / a0.T);\n        AP new1 = trace(a2, a1);//((a2.s - a1.s) / a1.T, a2.T / a1.T);\n        if (!was) {\n            intersection0 = new0;\n            intersection1 = new1;\n            was = 1;\n        } else {\n//            cerr << \"new \"; new0.out(); new1.out();\n            AP x0 = intersect(new0, intersection0);\n            AP x1 = intersect(new1, intersection1);\n            if (x0.s < 0 || x1.s < 0) return AP(-1, -1);\n            AP subold0 = trace(x0, intersection0);\n            AP subold1 = trace(x1, intersection1);\n            AP subold2 = intersect(subold0, subold1);\n            if (subold2.s < 0) return AP(-1, -1);\n            intersection0 = subsec(intersection0, subold2);\n            intersection1 = subsec(intersection1, subold2);\n//            cerr << \"traced inter \"; intersection0.out(); intersection1.out();\n            AP subnew0 = trace(intersection0, new0);\n            AP subnew1 = trace(intersection1, new1);\n            AP subnew2 = strong_intersect(subnew0, subnew1);\n//            cerr << \"subnew \"; subnew0.out(); subnew1.out(); subnew2.out();\n            if (subnew2.s < 0) return AP(-1, -1);\n            intersection0 = subsec(new0, subnew2);\n            intersection1 = subsec(new1, subnew2);\n        }\n//        cerr << \"inter \"; intersection0.out(); intersection1.out();\n        if (intersection1.T == 0) {\n            ll fix1 = intersection1.s;\n            ll fix0 = fix(A1, B1, fix1, A0, B0, curp, fail);\n            if (fail || fix0 < 0) return AP(-1, -1);\n            intersection0 = AP(fix0, 0);\n        }\n        if (intersection0.T == 0) {\n            ll fix0 = intersection0.s;\n            ll fix1 = fix(A0, B0, fix0, A1, B1, curp, fail);\n            if (fail || fix1 < 0) {\n                return AP(-1, -1);\n            } else {\n                return AP(fix0, 0);\n            }\n        }\n        if (intersection0.s < 0 || intersection1.s < 0) return AP(-1, -1);\n    }\n    return intersection0;\n}\n \nbool check_geom(int a, int b, ll n) {\n    if (n % a) return false;\n    n /= a;\n    if (b == 1) {\n        return n == 1;\n    }\n    while (n > 1) {\n        if (n % b) return false;\n        n /= b;\n    }\n    return n == 1;\n}\n \nbool check_all_geoms(const vi & a, const vi & b, ll n) {\n    for (int j = 0; j < a.size(); ++j) {\n        if (!check_geom(a[j], b[j], n)) return false;\n    }\n    return true;\n}\n \nll check_stupid(const vi & a, const vi & b, int start) {\n    ll n = a[start];\n    while (1) {\n        bool ok = true;\n        for (int i = 0; i < a.size(); ++i) {\n            if (!check_geom(a[i], b[i], n)) {\n                ok = false;\n                break;\n            }\n        }\n        if (ok) {\n            return n%mod;\n        }\n        if (n > 1e18 / b[start] || b[start] == 1) break;\n        n *= b[start];\n    }\n    return -1;\n}\n \nvi factor(int n, const vi & p) {\n    vi pw(p.size());\n    for (int i = 0; i < p.size(); ++i) {\n        while (n % p[i] == 0) {\n            n /= p[i];\n            ++pw[i];\n        }\n    }\n    return pw;\n}\n \nint solve(const vi & a, const vi & b) {\n    int n = a.size();\n    for (int i = 0; i < n; ++i) if (b[i] == 1) {\n        for (int j = 0; j < n; ++j) {\n            if (!check_geom(a[j], b[j], a[i])) return -1;\n        }\n        return a[i];\n    }\n    vvi primes(n);\n    for (int i = 0; i < n; ++i) {\n        primes[i] = uniq_merge(get_primes(a[i]), get_primes(b[i]));\n    }\n    AP intersection(0, 1);\n    for (int i = 1; i < n; ++i) {\n        vi curp = uniq_merge(primes[0], primes[i]);\n        intersection = intersect(intersection, common(a[0], b[0], a[i], b[i], curp));\n        if (intersection.s < 0) return -1;\n    }\n    return a[0]*mpow(b[0], intersection.s) % mod;\n}\n \nint stupid_solve(vi a, vi b) {\n    vii ts(a.size());\n    for (int i = 0; i < a.size(); ++i) ts[i] = pii(a[i], b[i]);\n    sort(ts.begin(), ts.end());\n    ts.resize(unique(ts.begin(), ts.end()) - ts.begin());\n    a.resize(ts.size());\n    b.resize(ts.size());\n    for (int i = 0; i < a.size(); ++i) {\n        a[i] = ts[i].first;\n        b[i] = ts[i].second;\n    }\n/*    int d = a[0];\n    for (int i = 0; i < a.size(); ++i) {\n        d = __gcd(a, a[i]);\n    }\n    for (int i = 0; i < a.size(); ++i) {\n        a[i] / d;\n    }*/\n    for (int i = 0; i < a.size(); ++i) if (b[i] == 1) {\n        for (int j = 0; j < a.size(); ++j) {\n            if (!check_geom(a[j], b[j], a[i])) return -1;\n        }\n        return a[i];\n    }\n    for (int i = 0; i < a.size(); ++i) {\n        if (b[i] > b[0]) {\n            swap(a[0], a[i]);\n            swap(b[0], b[i]);\n            break;\n        }\n    }\n    vvi primes(a.size());\n    vvi primesa(a.size());\n    vvi primesb(a.size());\n    for (int i = 0; i < a.size(); ++i) {\n        primes[i] = uniq_merge(get_primes(a[i]), get_primes(b[i]));\n        primesa[i] = get_primes(a[i]);\n        primesb[i] = get_primes(b[i]);\n    }\n    for (int i = 1; i < a.size(); ++i) {\n        if (primes[i] != primes[i-1]) {\n            int n = (primes[i].size() > primes[i-1].size()) ? a[i] : a[i-1];\n            if (!check_all_geoms(a, b, n)) return -1;\n            else return n;\n        }\n        if (primesb[i] != primesb[i-1]) {\n            int start = (primesb[i].size() > primesb[i-1].size()) ? i : i-1;\n            return check_stupid(a, b, start);\n        }\n    }\n    for (auto p : primesa[0]) if (!binary_search(primesb[0].begin(), primesb[0].end(), p)) {\n        for (int i = 1; i < a.size(); ++i) {\n            if (ord(a[i], p) != ord(a[i-1], p)) return -1;   \n        }\n    }\n    vvi pa(a.size()), pb(b.size());\n    for (int i = 0; i < a.size(); ++i) {\n        pa[i] = factor(a[i], primesb[0]);\n        pb[i] = factor(b[i], primesb[0]);\n    }\n    vi v = pa[0];\n    for (int pwb = 0; ; ++pwb) {\n        double passed_time = (clock() - BEGIN) / (double)CLOCKS_PER_SEC;\n        if (passed_time > 0.01) break;\n        bool ok = true;\n        for (int i = 1; i < a.size() && ok; ++i) {\n            int div = 0;\n            for (int j = 0; j < v.size(); ++j) {\n                if (v[j] < pa[i][j] || (v[j] - pa[i][j]) % pb[i][j] != 0) {\n                    ok = false;\n                    break;\n                }\n                int ndiv = (v[j] - pa[i][j]) / pb[i][j];\n                if (j && ndiv != div) {\n                    ok = false;\n                    break;\n                }\n                div = ndiv;\n            }\n        }\n        if (ok) {\n            return a[0] * mpow(b[0], pwb) % mod;\n        }\n        for (int i = 0; i < v.size(); ++i) {\n            v[i] += pb[0][i];\n        }\n    }\n \n//    return check_stupid(a, b, 0);\n    return -1;\n}\n \nint main() {\n    int n;\n    while (cin >> n) {\n        BEGIN = clock();\n        vi a(n), b(n);\n        for (int i = 0; i < n; ++i) {\n            scanf(\"%d%d\", &a[i], &b[i]);\n        }\n        int res = solve(a, b);\n        cout << res << endl;\n//        int res1 = stupid_solve(a, b);\n//        cout << res1 << endl;\n/*        if (res != res1) {\n            cerr << res1 << endl;\n            out(a); out(b);\n            assert(0);\n        }*/\n    }\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "572",
    "index": "A",
    "title": "Arrays",
    "statement": "You are given two arrays $A$ and $B$ consisting of integers, \\textbf{sorted in non-decreasing order}. Check whether it is possible to choose $k$ numbers in array $A$ and choose $m$ numbers in array $B$ so that any number chosen in the first array is strictly less than any number chosen in the second array.",
    "tutorial": "In this problem one need to check whether it's possible to choose $k$ elements from array $A$ and $m$ elements from array $B$ so that each of chosen element in $A$ is less than each of chosen elements in $B$. If it's possible then it's possible to choose $k$ smallest elements in $A$ and $m$ largest elements in $B$. That means that in particular, $k$-th smallest element of $A$ is less than $m$-th largest element in $B$. So, if $A[k] < B[n - m + 1]$ then the answer is \"YES\" and if not, then the answer is \"NO\".",
    "code": "#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n#include <iostream>\n#include <set>\n#include <vector>\n#include <cstring>\n#include <string>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <complex>\n#include <map>\n#include <queue>\nusing namespace std;\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<vi> vvi;\ntypedef vector<vl> vvl;\ntypedef vector<double> vd;\ntypedef vector<vd> vvd;\ntypedef pair<int, int> pii;\ntypedef pair<double, double> pdd;\ntypedef vector<pii> vii;\ntypedef vector<string> vs;\n \nint main() {\n    int k, m, n1, n2;\n    cin >> n1 >> n2 >> k >> m;\n    vi a(n1);\n    for (int i = 0; i < a.size(); ++i) cin >> a[i];\n    vi b(n2);\n    for (int i = 0; i < b.size(); ++i) cin >> b[i];\n    if (a[k - 1] < b[n2 - m]) cout << \"YES\\n\";\n    else cout << \"NO\\n\";\n    return 0;\n}",
    "tags": [
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "572",
    "index": "B",
    "title": "Order Book",
    "statement": "In this task you need to process a set of stock exchange orders and use them to create order book.\n\nAn order is an instruction of some participant to buy or sell stocks on stock exchange. The order number $i$ has price $p_{i}$, direction $d_{i}$ — buy or sell, and integer $q_{i}$. This means that the participant is ready to buy or sell $q_{i}$ stocks at price $p_{i}$ for one stock. A value $q_{i}$ is also known as a volume of an order.\n\nAll orders with the same price $p$ and direction $d$ are merged into one aggregated order with price $p$ and direction $d$. The volume of such order is a sum of volumes of the initial orders.\n\nAn order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.\n\nAn order book of depth $s$ contains $s$ best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than $s$ aggregated orders for some direction then all of them will be in the final order book.\n\nYou are given $n$ stock exhange orders. Your task is to print order book of depth $s$ for these orders.",
    "tutorial": "First of all the problem may be solved for buy orders and sell orders separately. The easiest soultion is to use structure like std::map or java.lang.TreeMap. To aggregate orders we just add volume to the corresponding map element: aggregated[price] += volume. After that we should extract lowest (or largest) element from map $s$ times (or while it's not empty). Complexity of this solution is $O(nlogn)$. It is also possible to solve the problem without data structres other than an array. You should just maintain at most $s$ best orders in sorted order and when adding another order you insert it in appropriate place and move worse elements in linear time of $s$. Complexity of this solution is $O(sn)$.",
    "code": "/**\n * code generated by JHelper\n * More info: https://github.com/AlexeyDmitriev/JHelper\n * @author RiaD\n */\n \n#include <iostream>\n#include <fstream>\n \n#include <iostream>\n#include <bits/stdc++.h>\n \n \n#include <iterator>\n \n#include <string>\n#include <stdexcept>\n \n#ifdef SPCPPL_DEBUG\n#define SPCPPL_ASSERT(condition) \\\n    if(!(condition)) { \\\n        throw std::runtime_error(std::string() + #condition + \" in line \" + std::to_string(__LINE__) + \" in \" + __PRETTY_FUNCTION__); \\\n    }\n#else\n\t#define SPCPPL_ASSERT(condition)\n#endif\n \n \n/**\n* Support decrementing and multi-passing, but not declared bidirectional(or even forward) because\n* it's reference type is not a reference.\n*\n* It doesn't return reference because\n* 1. Anyway it'll not satisfy requirement [forward.iterators]/6\n*   If a and b are both dereferenceable, then a == b if and only if *a and\n*   b are bound to the same object.\n* 2. It'll not work with reverse_iterator that returns operator * of temporary which is temporary for this iterator\n*\n* Note, reverse_iterator is not guaranteed to work  now too since it works only with bidirectional iterators,\n* but it's seems to work at least on my implementation.\n*\n* It's not really useful anywhere except iterating anyway.\n*/\ntemplate <typename T>\nclass IntegerIterator :\n\t\tpublic std::iterator<std::input_iterator_tag, T, std::ptrdiff_t, T*, T> {\npublic:\n\texplicit IntegerIterator(int value) : value(value) {\n \n\t}\n \n\tIntegerIterator& operator ++() {\n\t\t++value;\n\t\treturn *this;\n\t}\n \n\tIntegerIterator operator ++(int) {\n\t\tIntegerIterator copy = *this;\n\t\t++value;\n\t\treturn copy;\n\t}\n \n\tIntegerIterator& operator --() {\n\t\t--value;\n\t\treturn *this;\n\t}\n \n\tIntegerIterator operator --(int) {\n\t\tIntegerIterator copy = *this;\n\t\t--value;\n\t\treturn copy;\n\t}\n \n\tT operator *() const {\n\t\treturn value;\n\t}\n \n\tbool operator ==(IntegerIterator rhs) {\n\t\treturn value == rhs.value;\n\t}\n \n\tbool operator !=(IntegerIterator rhs) {\n\t\treturn !(*this == rhs);\n\t}\n \nprivate:\n\tT value;\n};\n \ntemplate <typename T>\nclass IntegerRange {\npublic:\n\tIntegerRange(T begin, T end) : begin_(begin), end_(end) {\n \n\t}\n \n\tIntegerIterator<T> begin() const {\n\t\treturn IntegerIterator<T>(begin_);\n\t}\n \n\tIntegerIterator<T> end() const {\n\t\treturn IntegerIterator<T>(end_);\n\t}\n \nprivate:\n\tT begin_;\n\tT end_;\n};\n \ntemplate <typename T>\nclass ReversedIntegerRange {\n\ttypedef std::reverse_iterator<IntegerIterator<T>> IteratorType;\npublic:\n\tReversedIntegerRange(T begin, T end) : begin_(begin), end_(end) {\n \n\t}\n \n\tIteratorType begin() const {\n\t\treturn IteratorType(IntegerIterator<T>(begin_));\n\t}\n \n\tIteratorType end() const {\n\t\treturn IteratorType(IntegerIterator<T>(end_));\n\t}\n \nprivate:\n\tT begin_;\n\tT end_;\n};\n \ntemplate <typename T>\nIntegerRange<T> range(T to) {\n\tSPCPPL_ASSERT(to >= 0);\n\treturn IntegerRange<T>(0, to);\n}\n \ntemplate <typename T>\nIntegerRange<T> range(T from, T to) {\n\tSPCPPL_ASSERT(from <= to);\n\treturn IntegerRange<T>(from, to);\n}\n \ntemplate <typename T>\nReversedIntegerRange<T> downrange(T from) {\n\tSPCPPL_ASSERT(from >= 0);\n\treturn ReversedIntegerRange<T>(from, 0);\n}\n \ntemplate <typename T>\nReversedIntegerRange<T> downrange(T from, T to) {\n\tSPCPPL_ASSERT(from >= to);\n\treturn ReversedIntegerRange<T>(from, to);\n}\n \n \n#include <utility>\n \ntemplate <typename T>\nclass Range {\npublic:\n\tRange(T begin, T end) : begin_(std::move(begin)), end_(std::move(end)) {\n \n\t}\n \n\tT begin() {\n\t\treturn begin_;\n\t}\n \n\tT end() {\n\t\treturn end_;\n\t}\n \nprivate:\n\tT begin_;\n\tT end_;\n};\n \n \ntemplate <typename T>\nRange<T> make_range(T begin, T end) {\n\treturn Range<T>(begin, end);\n}\n \nusing namespace std;\n \nclass OrderBook {\npublic:\n\tint readInt(std::istream& in) {\n\t\tint res;\n\t\tin >> res;\n\t\treturn res;\n\t}\n \n\tvoid outputInt(std::ostream& out, int s) {\n\t\t//out << s / 100 << '.' << s / 10 % 10 << s % 10;\n\t\tout << s; \n\t}\n \n\tvoid solve(std::istream& in, std::ostream& out) {\n\t\tint n, s;\n\t\tin >> n >> s;\n \n\t\tmap <int, int> buy, sell;\n\t\tfor (int i: range(n)) {\n\t\t\tchar c;\n\t\t\tin >> c;\n\t\t\tint cost = readInt(in);\n\t\t\tint q;\n\t\t\tin >> q;\n\t\t\tif (c == 'B') {\n\t\t\t\tbuy[cost] += q;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsell[cost] += q;\n\t\t\t}\n\t\t}\n \n\t\twhile (sell.size() > s) {\n\t\t\tsell.erase(--sell.end());\n\t\t}\n\t\tfor (auto it: make_range(sell.rbegin(), sell.rend())) {\n\t\t\tout << 'S' << ' ';\n\t\t\toutputInt(out, it.first);\n\t\t\tout << ' ' << it.second << \"\\n\";\n\t\t}\n \n\t\twhile (buy.size() > s) {\n\t\t\tbuy.erase(buy.begin());\n\t\t}\n \n\t\tfor (auto it: make_range(buy.rbegin(), buy.rend())) {\n\t\t\tout << 'B' << ' ';\n\t\t\toutputInt(out, it.first);\n\t\t\tout << ' ' << it.second << \"\\n\";\n\t\t}\n\t}\n};\n \n \nint main() {\n\tstd::ios_base::sync_with_stdio(false);\n\tOrderBook solver;\n\tstd::istream& in(std::cin);\n\tstd::ostream& out(std::cout);\n\tin.tie(0);\n\tout << std::fixed;\n\tout.precision(20);\n\tsolver.solve(in, out);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "573",
    "index": "A",
    "title": "Bear and Poker",
    "statement": "Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are $n$ players (including Limak himself) and right now all of them have bids on the table. $i$-th of them has bid with size $a_{i}$ dollars.\n\nEach player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?",
    "tutorial": "Any positive integer number can be factorized and written as $2^{a} \\cdot 3^{b} \\cdot 5^{c} \\cdot 7^{d} \\cdot ...$. We can multiply given numbers by $2$ and $3$ so we can increase $a$ and $b$ for them. So we can make all $a$ and $b$ equal by increasing them to the same big value (e.g. $100$). But we can't change powers of other prime numbers so they must be equal from the beginning. We can check it by diving all numbers from input by two and by three as many times as possible. Then all of them must be equal. Code Alternative solution is to calculate GCD of given numbers. Answer is \"YES\" iff we can get each number by multiplying GCD by $2$ and $3$. Otherwise, some number had different power of prime number other than $2$ and $3$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint t[1005*1005];\n \nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &t[i]);\n\t}\n\tint x = t[1];\n\tfor(int i = 2; i <= n; ++i)\n\t\tx = __gcd(x, t[i]);\n\twhile(x % 2 == 0) x /= 2;\n\twhile(x % 3 == 0) x /= 3;\n\tfor(int i = 1; i <= n; ++i) {\n\t\tint two = 1, three = 1;\n\t\twhile(t[i] % (two * 2) == 0) two *= 2;\n\t\twhile(t[i] % (three * 3) == 0) three *= 3;\n\t\tif(x * two * three != t[i]) {\n\t\t\tputs(\"No\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"Yes\");\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "573",
    "index": "B",
    "title": "Bear and Blocks",
    "statement": "Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built $n$ towers in a row. The $i$-th tower is made of $h_{i}$ identical blocks. For clarification see picture for the first sample.\n\nLimak will repeat the following operation till everything is destroyed.\n\nBlock is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.\n\nLimak is ready to start. You task is to count how many operations will it take him to destroy all towers.",
    "tutorial": "In one operation the highest block in each tower disappears. So do all blocks above heights of neighbour towers. And all other blocks remain. It means that in one operation all heights change according to formula $h_{i} = min(h_{i - 1}, h_{i} - 1, h_{i + 1})$ where $h_{0} = h_{n + 1} = 0$. By using this formula two times we get height after two operations: $h_{i} = max(0, min(h_{i - 2}, h_{i - 1} - 1, h_{i} - 2, h_{i + 1} - 1, h_{i + 2}))$ and so on. From now I will omit $max(0, ...)$ part to make it easier to read. After $k$ operations we get $h_{i} = min(Left, Right)$ where $Left = min(h_{i - j} - (k - j)) = min(h_{i - j} + j - k)$ for $j\\in\\{0,1,\\cdot\\cdot,k\\}$ and $Right$ is defined similarly. $h_{i}$ becomes zero when $Left$ or $Right$ becomes zero. And $Left$ becomes zero when $k = min(h_{i - j} + j)$ - we will find this value for all $i$. If you are now lost in this editorial, try to draw some test and analyze my formulas with it. For each $i$ we are looking for $min(h_{i - j} + j)$. We can iterate over $i$ from left to right keeping some variable $best$: We should to the same for $Right$ and take $min(Left, Right)$ for each $i$. Then final answer is maximum over answers for $i$. Code Div1C - Bear and Drawing Let's consider a tree already drawn on a strip of paper. Let's take first vertex on the left and last vertex on the right (in case of two vertices with the same $x$, we choose any of them). There is a path between them. Let's forget about vertices not on this path. A path divides a strip into 1D regions. What can be added to the main path? Only simple paths attached to it with one edge. So it can be one of the following structures - Y-letter or Line: Note that Y-letter can have long legs but its central part can have only one edge. How to check if given tree is a path + Y-letters + Lines? First, let's move from each leaf till we have vertex with degree at least $3$, marking vertices as deleted. We don't mark last vertex (that with degree at least $3$) as deleted but we increase his number of legs. Finally, for each not-deleted vertex we count his not-deleted neighbours for which $degree - min(legs, 2) > 1$ - otherwise this neighbour is start of Line or Y-letter. Each vertex on the main path can have at most two neighbours that also belong to the main path. There can be more neighbours but they must be in Lines or Y-letters - that's why we didn't count them. So answer is \"No\" iff for some vertex we counted more than two neighbours.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int nax = 1e5 + 5;\nvector<int> w[nax];\n// leg is single/simple path ending with a leaf\nbool del[nax]; // vertices in legs are marked as deleted\nint legs[nax]; // numbers of legs starting in a vertex\n \nvoid dfs(int a, int par = 0) {\n\tif(w[a].size() <= 2) {\n\t\tdel[a] = true;\n\t\tfor(int b : w[a]) if(b != par) dfs(b, a);\n\t}\n}\n \nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n - 1; ++i) {\n\t\tint a, b;\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tw[a].push_back(b);\n\t\tw[b].push_back(a);\n\t}\n\tfor(int a = 1; a <= n; ++a)\n\t\tif(w[a].size() == 1)\n\t\t\tdfs(a);\n\tfor(int a = 1; a <= n; ++a)\n\t\tfor(int b : w[a]) if(del[b])\n\t\t\tlegs[a] = min(legs[a]+1, 2); // at most two legs\n\tfor(int a = 1; a <= n; ++a) if(!del[a]) {\n\t\tint cnt = 0;\n\t\tfor(int b : w[a]) if(!del[b] && w[b].size() - legs[b] > 1)\n\t\t\t++cnt;\n\t\tif(cnt > 2) {\n\t\t\tputs(\"No\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"Yes\");\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "573",
    "index": "D",
    "title": "Bear and Cavalry",
    "statement": "Would you want to fight against bears riding horses? Me neither.\n\nLimak is a grizzly bear. He is general of the dreadful army of Bearland. The most important part of an army is cavalry of course.\n\nCavalry of Bearland consists of $n$ warriors and $n$ horses. $i$-th warrior has strength $w_{i}$ and $i$-th horse has strength $h_{i}$. Warrior together with his horse is called a unit. Strength of a unit is equal to multiplied strengths of warrior and horse. Total strength of cavalry is equal to sum of strengths of all $n$ units. Good assignment of warriors and horses makes cavalry truly powerful.\n\nInitially, $i$-th warrior has $i$-th horse. You are given $q$ queries. In each query two warriors swap their horses with each other.\n\nGeneral Limak must be ready for every possible situation. What if warriors weren't allowed to ride their own horses? After each query find the maximum possible strength of cavalry if we consider assignments of all warriors to all horses that no warrior is assigned to his own horse (it can be proven that for $n ≥ 2$ there is always at least one correct assignment).\n\nNote that we can't leave a warrior without a horse.",
    "tutorial": "Let's sort warriors and horses separately (by strength). For a moment we forget about forbidden assignments. Inversion is a pair of warriors that stronger one is assigned to weaker horse. We don't like inversions because it's not worse to assign strong warriors to strong horses: $A \\cdot B + a \\cdot b  \\ge  A \\cdot b + B \\cdot a$ for $A  \\ge  a$ and $B  \\ge  b$. Note that repairing an inversion (by swapping assigned horses) decreases number of inversions - prove it by yourself (drawing a matching with intersections could be helpful). Without any restrictions the optimal matching is when we assign $i$-th warrior to $i$-th horse (indexed after sorting) - to get no inversions. Let's go back to version with forbidden connections. We have $n$ disjoint pairs which we can't use. We will prove that there exists an optimal assignment where (for all $i$) $i$-th warrior is assigned to $j$-th horse where $|i - j|  \\le  2$. Let's take an optimal assignment. In case of ties we take the one with the lowest number of inversions. Let's assume that $i$ is assigned to $i + 3$. There are at least $3$ warriors $j > i$ assigned to horses with indices lower than $i + 3$. So we have at least $3$ inversions with edge from $i$ to $i + 3$ (warriors on the left, horses on the right): Above, connection warrior-horse is an edge. Then inversions are intersections. Swapping horses for warriors $i$ and $j$ (where $j$ belongs so some red edge) would decrease number of inversions and it wouldn't decrease a score. We took an optimal assignment so it means that it's impossible to swap horses for them. Hence, for each red edge we can't change pair (black, read) into the following blue edges: So one of these blue edges is forbidden. Three red edges generate three pairs of blue edges and in each pair at least one blue edge must be forbidden. Note that all six blue edges are different. All blue edges are incident to warrior $i$ or to horse $i + 3$ but only one forbidden edge can be incident to warrior $i$ and only one forbidden edge can be incident to horse $i + 3$. We have at most two forbidden edges incident to them so it can't be true that three blue edges are forbidden. By cases analysis we can prove something more - that there can be only three possible types of connecting in an optimal assignment. First type: $i$ can be connected to $i$. Second: warrior $i$ with horse $i + 1$ and warrior $i + 1$ with horse $i$. Third: warriors $i$, $i + 1$ and $i + 2$ are connected with horses $i$, $i + 1$, $i + 2$. It gives us $O(nq)$ solution with calculating queries independently with $dp[i]$ defined as \"what result can we get for assigning everything with indices lower than $i$?\". To calculate $dp[i]$ we must know $dp[i - 3]$, $dp[i - 2]$ and $dp[i - 1]$. It wasn't intended solution because we can get better complexity. We can create a segment tree and for intervals we should keep info \"result we can get for this interval with 0/1/2 first and 0/1/2 last elements removed\". For an interval we keep matrix 3x3 and actualizing forbidden edge for single $i$ consists of: 1. calculating values of 3x3 matrix for a small interval with $i$ 2. actualizing a tree with $\\log n$ times multiplying matrices Complexity is $O(q\\log n\\cdot3^{3})$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "573",
    "index": "E",
    "title": "Bear and Bowling",
    "statement": "Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record!\n\nFor rolling a ball one gets a score — an integer (maybe negative) number of points. Score for $i$-th roll is multiplied by $i$ and scores are summed up. So, for $k$ rolls with scores $s_{1}, s_{2}, ..., s_{k}$, total score is $\\textstyle\\sum_{i=1}^{k}i\\cdot s_{i}$. Total score is $0$ if there were no rolls.\n\nLimak made $n$ rolls and got score $a_{i}$ for $i$-th of them. He wants to maximize his total score and he came up with an interesting idea. He will cancel some rolls, saying that something distracted him or there was a strong wind.\n\nLimak is able to cancel any number of rolls, maybe even all or none of them. Total score is calculated as if there were only non-canceled rolls. Look at the sample tests for clarification. What maximum total score can Limak get?",
    "tutorial": "FIRST PART - greedy works We will add (take) elements to a subsequence one by one. Adding number $x$, when we have $k - 1$ taken numbers on the left, increases result by $k \\cdot x + suf$ where $suf$ is sum of taken numbers on the right. Let's call this added value as the Quality of element $x$. We will prove correctness of the following greedy algorithm. We take element with the biggest Quality till there are no elements left. For every size of a subsequence (number of taken elements) we will get optimal score. (lemma) If $a_{i} > a_{j}$ and $i < j$, we won't take $a_{j}$ first. Proof. Let's consider a moment when we don't fulfill the lemma for the first time. If there are no taken numbers between $a_{i}$ and $a_{j}$, we have $Q_{i} = k \\cdot a_{i} + suf > k \\cdot a_{j} + suf = Q_{j}$ so $a_{i}$ is a better choice. For taken numbers between $a_{i}$ and $a_{j}$ - each number $x$ changes $Q_{i}$ by $x$ and $Q_{j}$ by $a_{j}$. We'll see that $x > a_{j}$ so $Q_{i}$ will remain greater than $Q_{j}$. If $a_{i} > x$, the lemma (fulfilled till now) says that $x$ wasn't taken before $a_{i}$ - it can't be true because $x$ is taken and $a_{i}$ is not. So indeed $x  \\ge  a_{i} > a_{j}$. Let's assume that our greedy strategy is not correct. Let's consider first moment when we take some element $a_{j}$ and for some $s$ we can't get optimal subsequence with size $s$ by taking more elements (using any strategy). Let $A$ denote a set of elements taken before. So there is no way to add some more elements to set $A + a_{j}$ and achieve optimal score with size $s$. But it was possible just before taking $a_{j}$ so there is a subset of remaining elements $B$ that $|A + B| = s$ and set $A + B$ is the best among sets with size $s$. Note that $B$ can't be empty. (case 1 - $B$ contains at least one element on the left from $a_{j}$) Let $a_{i}$ denote last element from $B$ that $i < j$ (here \"last\" means \"with the biggest $i$\"). Our strategy wanted $a_{j}$ before elements from $B$ so we know from lemma that $a_{i}  \\le  a_{j}$. It will turn out that replacing $a_{i}$ with $a_{j}$ (in set $A + B$) doesn't decrease the score so taking $a_{j}$ is acceptable. Note that replacing an element with another one doesn't change size of a set/subsequence. In moment of choosing $a_{j}$ it had the biggest quality so then $Q_{j}  \\ge  Q_{i}$. Now in $A + B$ there are new elements, those in $B$. Let's imagine adding them to $A$ (without $a_{i}$ and $a_{j}$). Each new element $x$ on the right change both $Q_{i}$ and $Q_{j}$ by $x$. Elements on the left change $Q_{i}$ by $a_{i}$ and $Q_{j}$ by $a_{j}$ (note that $a_{i}  \\le  a_{j}$). And there are no elements between $a_{i}$ and $a_{j}$. Now, taking $a_{i}$ would give us set $A + B$ but $Q_{j}$ remains not less than $Q_{i}$ so we can take $a_{j}$ instead. (case 2 - $B$ contains only elements on the right from $a_{j}$) Similarly, we can replace $a_{i}$ with closest $a_{j}$ from set $B$. As before, elements on the right change $Q_{i}$ and $Q_{j}$ by the same value. SECOND PART - how to implement it First, let's understand $O(n{\\sqrt{n}}\\log n)$ solution. We divide a sequence into $\\sqrt{n}$ Parts. When choosing the best candidate in a Part, we want to forget about other Parts. It's enough to remember only $x$ and $suf$ - number of taken elements on the left (in previous Parts) and sum of elements on the right (in next Parts). $x$ affects choosing the best element in a Part, $suf$ doesn't (but we need this constant to add it to result for best candidate). For a Part we want to have hull with $\\sqrt{n}$ linear functions of form $a_{i} \\cdot x + b$. With binary search we can find the best element in $O({\\sqrt{n}}\\log n)$ and then construct new hull for this Part in $O({\\sqrt{n}}\\log n)$. We can remove $\\log n$ from complexity. First, binary search can be replaced with pointers - for each Part initially we set a pointer at the beginning of Part. To find best candidate in Part, we slowly move pointer to the right (by one). Complexity is amortized $O(n{\\sqrt{n}})$. And we can sort linear functions $a_{i} \\cdot x + b$ by angle only once because value $a_{i}$ doesn't change - then constructing a hull is only $O({\\sqrt{n}})$. Note that when rebuilding a hull, we must set pointer to the beginning of Part. So we have $O(n\\log n+n{\\sqrt{n}})$. There are other two correct lemmas to speed your solution up. We can take all positive numbers first (it's not so easy to prove). And we can stop when taken number doesn't increase score - next taken numbers won't increase score neither.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n \nstruct line {\n\tint a, id;\n\tll b;\n\tline(int aa, ll bb, int idd) : a(aa), id(idd), b(bb) {}\n\t// does (this,B) intersect before (B,C)\n\tbool before(const line & B, const line & C) {\n\t\t// a*x + b = B.a*x + B.b\n\t\t// x * (a-B.a) = B.b-b\n\t\t// x * q1 = p1\n\t\tll p1 = B.b - b, p2 = C.b - b;\n\t\tint q1 = a - B.a, q2 = a - C.a;\n\t\tif(q1 < 0) { p1 *= -1; q1 *= -1; }\n\t\tif(q2 < 0) { p2 *= -1; q2 *= -1; }\n\t\t// x1 = p1/q1, x2 = p2/q2\n\t\treturn p1*q2 <= p2*q1;\n\t}\n\tll f(int x) { return (ll) a * x + b; }\n};\n \nstruct hull {\n\tvector<int> a; // numbers from input\n\tvector<bool> taken;\n\tvector<line> w; // hull\n\tvector<int> order;\n\tint n;\n\tint pointer;\n\tint count; // number of taken elements\n\tll sum; // sum of taken elements\n\thull(){}\n\thull(vector<int> aa) : a(aa) {\n\t\tcount = sum = 0;\n\t\tn = (int) a.size();\n\t\ttaken.resize(n, false);\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\torder.push_back(i);\n\t\t// we find order only once, in constructor\n\t\tsort(order.begin(), order.end(), [&](int i, int j){ return a[i] < a[j]; });\n\t\tbuild();\n\t}\n\tvoid build() { // build hull\n\t\tpointer = 0;\n\t\tvector<ll> val(n);\n\t\tll suf = sum;\n\t\tint cnt = 0;\n\t\tfor(int i = 0; i < n; ++i) {\n\t\t\tif(taken[i]) {\n\t\t\t\tsuf -= a[i];\n\t\t\t\t++cnt;\n\t\t\t}\n\t\t\telse val[i] = suf + (ll) a[i] * (cnt + 1);\n\t\t}\n\t\tvector<line> sorted;\n\t\t// linear sort using vector<int> order\n\t\tfor(int i : order) if(!taken[i])\n\t\t\tsorted.push_back(line(a[i], val[i], i));\n\t\tw.clear();\n\t\tfor(line & C : sorted) {\n\t\t\tif(!w.empty() && w.back().a == C.a) {\n\t\t\t\tif(C.b <= w.back().b) continue;\n\t\t\t\telse w.pop_back();\n\t\t\t}\n\t\t\twhile((int) w.size() >= 2) {\n\t\t\t\tline & A = w[(int)w.size()-2];\n\t\t\t\tline & B = w[(int)w.size()-1];\n\t\t\t\tif(A.before(B, C)) break;\n\t\t\t\tw.pop_back();\n\t\t\t}\n\t\t\tw.push_back(C);\n\t\t}\n\t}\n\tpair<ll, int> best(int before) { // find the best candidate, move pointer\n\t\tif(w.empty()) return make_pair(42LL, -1);\n\t\twhile(pointer <= (int) w.size()-2 && w[pointer].f(before) < w[pointer+1].f(before))\n\t\t\t++pointer;\n\t\tassert(pointer < (int) w.size());\n\t\treturn make_pair(w[pointer].f(before), w[pointer].id);\n\t}\n\tvoid remove(int i) { // mark as taken\n\t\tassert(!taken[i]);\n\t\ttaken[i] = true;\n\t\tsum += a[i];\n\t\t++count;\n\t\tbuild();\n\t}\n} h[1005];\n \nint a[1005*1005];\n \nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\t// divide into Parts with size sqrt(n)\n\tint s = max(1, int(sqrt(n)));\n\tfor(int i = 0; i < n; i += s) {\n\t\tvector<int> w;\n\t\tfor(int j = i; j < min(n, i+s); ++j)\n\t\t\tw.push_back(a[j]);\n\t\th[i/s] = hull(w);\n\t}\n\tll output = 0; // max(score)\n\tll score = 0; // score for current set/subsequence\n\twhile(true) {\n\t\tpair<ll,int> m = make_pair(42LL, -1);\n\t\tll suf = 0; // sum of elements on the right\n\t\tint cnt = 0; // how many on the left\n\t\tfor(int i = 0; i < n; i += s)\n\t\t\tsuf += h[i/s].sum;\n\t\tfor(int i = 0; i < n; i += s) {\n\t\t\tsuf -= h[i/s].sum;\n\t\t\t// we ask this Part about max(ax+b) where x = cnt\n\t\t\tpair<ll, int> p = h[i/s].best(cnt);\n\t\t\tp.first += suf; // extra constant\n\t\t\tif(p.second != -1)\n\t\t\t\tif(m.second == -1 || p.first > m.first)\n\t\t\t\t\tm = make_pair(p.first, i+p.second);\n\t\t\tcnt += h[i/s].count;\n\t\t}\n\t\tif(m.second == -1) break;\n\t\tscore += m.first;\n\t\toutput = max(output, score);\n\t\tint i = m.second;\n\t\th[i/s].remove(i-i/s*s);\n\t}\n\tprintf(\"%lld\\n\", output);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 3200
  },
  {
    "contest_id": "574",
    "index": "B",
    "title": "Bear and Three Musketeers",
    "statement": "Do you know a story about the three musketeers? Anyway, you will learn about its origins now.\n\nRichelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.\n\nThere are $n$ warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.\n\nHelp Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.",
    "tutorial": "Warriors are vertices and \"knowing each other\" is an edge. We want to find connected triple of vertices with the lowest sum of degrees (and print $sum - 6$ because we don't want to count edges from one chosen vertex to another). Brute force is $O(n^{3})$. We iterate over all triples $a, b, c$ and consider them as musketeers. They must be connected by edges (they must know each other). If they are, then we consider sum of their degrees. We must notice that there is low limit for number of edges. So instead of iterating over triples of vertices we can iterate over edges and then iterate over third vertex. It gives us $O(n^{2} + nm)$ and it's intended solution. To check if third vertex is connected with other two, you should additionally store edges in 2D adjacency matrix. It's also possible to write it by adding \"if\" in right place in brute forces to get $O(n^{2} + nm)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int inf = 100000005;\nconst int nax = 5005;\nint degree[nax];\nbool t[nax][nax];\n \nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tfor(int i = 0; i < m; ++i) {\n\t\tint a, b;\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tt[a][b] = t[b][a] = true;\n\t\tdegree[a]++;\n\t\tdegree[b]++;\n\t}\n\tint result = inf;\n\tfor(int i = 1; i <= n; ++i)\n\t\tfor(int j = i + 1; j <= n; ++j) {\n\t\t\t// we are O(n^2) times here\n\t\t\tif(t[i][j]) {\n\t\t\t\t// we are O(m) times here\n\t\t\t\tfor(int k = j + 1; k <= n; ++k) {\n\t\t\t\t\t// O(m * n) times here\n\t\t\t\t\tif(t[i][k] && t[j][k])\n\t\t\t\t\t\tresult = min(result, degree[i]+degree[j]+degree[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tif(result == inf) puts(\"-1\");\n\telse printf(\"%d\\n\", result - 6);\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "hashing"
    ],
    "rating": 1500
  },
  {
    "contest_id": "576",
    "index": "A",
    "title": "Vasya and Petya's Game",
    "statement": "Vasya and Petya are playing a simple game. Vasya thought of number $x$ between $1$ and $n$, and Petya tries to guess the number.\n\nPetya can ask questions like: \"Is the unknown number divisible by number $y$?\".\n\nThe game is played by the following rules: first Petya asks \\textbf{all} the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.\n\nUnfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers $y_{i}$, he should ask the questions about.",
    "tutorial": "If Petya didn't ask $p^{k}$, where $p$ is prime and $k  \\ge  1$, he would not be able to distinguish $p^{k - 1}$ and $p^{k}$. That means, he should ask all the numbers $p^{k}$. It's easy to prove that this sequence actually guesses all the numbers from $1$ to $n$ The complexity is $O(N^{1.5})$ or $O(NloglogN)$ depending on primality test.",
    "code": "\"#include <iostream>\\n#include <fstream>\\n#include <sstream>\\n\\n#include <vector>\\n#include <set>\\n#include <bitset>\\n#include <map>\\n#include <deque>\\n#include <string>\\n\\n#include <algorithm>\\n#include <numeric>\\n\\n#include <cstdio>\\n#include <cassert>\\n#include <cstdlib>\\n#include <cstring>\\n#include <ctime>\\n#include <cmath>\\n\\n#define pb push_back\\n#define pbk pop_back\\n#define mp make_pair\\n#define fs first\\n#define sc second\\n#define all(x) (x).begin(), (x).end()\\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\\n#define len(a) ((int) (a).size())\\n\\n#ifdef CUTEBMAING\\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\\n#else\\n#define eprintf(...) 42\\n#endif\\n\\nusing namespace std;\\n\\ntypedef long long int64;\\ntypedef long double ld;\\ntypedef unsigned long long lint;\\n\\nconst int inf = (1 << 30) - 1;\\nconst int64 linf = (1ll << 62) - 1;\\n\\nint main() {\\n\\tint n; cin >> n;\\n\\tvector<int> is_prime(n + 1, true), primes;\\n\\tis_prime[0] = is_prime[1] = 0;\\n\\tfor (int i = 2; i * i <= n; i++) {\\n\\t\\tif (is_prime[i]) {\\n\\t\\t\\tfor (int j = i * i; j <= n; j += i) {\\n\\t\\t\\t\\tis_prime[j] = false;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tvector<int> ans;\\n\\tfor (int i = 1; i <= n; i++) {\\n\\t\\tif (is_prime[i]) {\\n            int q = 1;\\n            while (q <= n / i) {\\n                q *= i;\\n                ans.push_back(q);\\n            }\\n\\t\\t}\\n\\t}\\n\\tcout << len(ans) << endl;\\n\\tfor (int i : ans) {\\n\\t    printf(\\\"%d \\\", i);\\n\\t}\\n\\tputs(\\\"\\\");\\n    return 0;\\n}\"",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "576",
    "index": "B",
    "title": "Invariance of Tree",
    "statement": "A tree of size $n$ is an undirected connected graph consisting of $n$ vertices without cycles.\n\nConsider some tree with $n$ vertices. We call a tree invariant relative to permutation $p = p_{1}p_{2}... p_{n}$, if for any two vertices of the tree $u$ and $v$ the condition holds: \"vertices $u$ and $v$ are connected by an edge if and only if vertices $p_{u}$ and $p_{v}$ are connected by an edge\".\n\nYou are given permutation $p$ of size $n$. Find some tree size $n$, invariant relative to the given permutation.",
    "tutorial": "Let's look at the answer. It's easy to notice, that centers of that tree must turn into centers after applying the permutation. That means, permutation must have cycle with length $1$ or $2$ since there're at most two centers. If permutation has cycle with length $1$, we can connect all the other vertices to it. For example, let's look at the permutation $(4, 2, 1, 3)$. $2$ is a cycle with length $2$, so let's connect all the other vertices to it. The resulting tree edges would be $(1, 2)$, $(2, 3)$, $(2, 4)$. If answer has two centers, let's remove the edge between them. The tree will split into two connected parts. It's easy to see that they will turn into each other after applying permutation. That means, all cycles should be even. It's easy to come up with answer with these restrictions. Let's connect vertices from the cycles with length $2$. Then, let's connect vertices with odd position in cycles to first of these and vetices with even cycles to second one. For example, let's consider permutation $(6, 5, 4, 3, 1, 2)$. There are two cycles: $(3, 4)$ and $(1, 6, 2, 5)$. We add edge $(3, 4)$, all other vertices we connect to these two, obtaining edges $(1, 3)$, $(6, 4)$, $(2, 3)$, $(5, 4)$. The complexity is $O(N)$.",
    "code": "\"#include <iostream>\\n#include <sstream>\\n#include <fstream>\\n\\n#include <algorithm>\\n#include <numeric>\\n\\n#include <vector>\\n#include <set>\\n#include <map>\\n#include <bitset>\\n#include <deque>\\n\\n#include <ctime>\\n#include <cmath>\\n#include <cstdlib>\\n#include <cstdio>\\n#include <cassert>\\n\\n#define pb push_back\\n#define pbk pop_back\\n#define mp make_pair\\n#define fs first\\n#define sc second\\n#define all(x) (x).begin(), (x).end()\\n#define len(a) ((int) (a).size())\\n#define endl '\\\\n'\\n\\n#ifdef CUTEBMAING\\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\\n#else\\n#define eprintf(...) ({})\\n#endif\\n\\nusing namespace std;\\n\\ntypedef long long int64;\\ntypedef long double ld;\\ntypedef unsigned long long lint;\\n\\nconst int inf = (1 << 30) - 1;\\nconst int64 linf = (1ll << 62) - 1;\\nconst int N = 1e6;\\n\\nint n;\\nint p[N];\\n\\nint division[2][N];\\nint dln[2];\\nbool u[N];\\n\\nint main(){\\n\\tcin >> n;\\n\\tfor (int i = 0; i < n; i++){\\n\\t\\tscanf(\\\"%d\\\", &p[i]);\\n\\t\\tp[i]--;\\n\\t}\\n\\tint index1 = -1, index2 = -1;\\n\\tfor (int i = 0; i < n; i++){\\n\\t\\tif (p[i] == i)\\n\\t\\t\\tindex1 = i;\\n\\t\\tif (p[p[i]] == i)\\n\\t\\t\\tindex2 = i;\\n\\t}\\n\\tif (index1 != -1){\\n\\t\\tputs(\\\"YES\\\");\\n\\t\\tfor (int i = 0; i < n; i++)\\n\\t\\t\\tif (index1 != i)\\n\\t\\t\\t\\tprintf(\\\"%d %d\\\\n\\\", index1 + 1, i + 1);\\n\\t\\treturn 0;\\n\\t}\\n\\tif (index2 != -1){\\n\\t\\tbool flag = true;\\n\\t\\tdln[0] = dln[1] = 0;\\n\\t\\tfill_n(u, n, 0);\\n\\t\\tu[index2] = u[p[index2]] = 1;\\n\\t\\tfor (int i = 0; i < n; i++)\\n\\t\\t\\tif (!u[i]){\\n\\t\\t\\t\\tu[i] = 1;\\n\\t\\t\\t\\tdivision[0][dln[0]++] = i;\\n\\t\\t\\t\\tint curI = p[i], step = 1;\\n\\t\\t\\t\\twhile (curI != i){\\n\\t\\t\\t\\t\\tu[curI] = 1;\\n\\t\\t\\t\\t\\tdivision[step][dln[step]++] = curI;\\n\\t\\t\\t\\t\\tstep ^= 1;\\n\\t\\t\\t\\t\\tcurI = p[curI];\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif (step == 1){\\n\\t\\t\\t\\t\\tflag = false;\\n\\t\\t\\t\\t\\tbreak;\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\tif (!flag){\\n\\t\\t\\tputs(\\\"NO\\\");\\n\\t\\t\\treturn 0;\\n\\t\\t}\\n\\t\\tputs(\\\"YES\\\");\\n\\t\\tprintf(\\\"%d %d\\\\n\\\", index2 + 1, p[index2] + 1);\\n\\t\\tfor (int i = 0; i < dln[0]; i++)\\n\\t\\t\\tprintf(\\\"%d %d\\\\n\\\", index2 + 1, division[0][i] + 1);\\n\\t\\tfor (int i = 0; i < dln[1]; i++)\\n\\t\\t\\tprintf(\\\"%d %d\\\\n\\\", p[index2] + 1, division[1][i] + 1);\\n\\t\\treturn 0;\\n\\t}\\n\\tputs(\\\"NO\\\");\\n\\treturn 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "576",
    "index": "C",
    "title": "Points on Plane",
    "statement": "On a plane are $n$ points ($x_{i}$, $y_{i}$) with integer coordinates between $0$ and $10^{6}$. The distance between the two points with numbers $a$ and $b$ is said to be the following value: $\\operatorname{dist}(a,b)=|x_{a}-x_{b}|+|y_{a}-y_{b}|$ (the distance calculated by such formula is called Manhattan distance).\n\nWe call a hamiltonian path to be some permutation $p_{i}$ of numbers from $1$ to $n$. We say that the length of this path is value $\\sum_{i=1}^{n-1}\\mathrm{dist}(p_{i},p_{i+1})$.\n\nFind some hamiltonian path with a length of no more than $25 × 10^{8}$. Note that you do not have to minimize the path length.",
    "tutorial": "Let's split rectangle $10^{6}  \\times  10^{6}$ by vertical lines into $1000$ rectangles $10^{3}  \\times  10^{6}$. Let's number them from left to right. We're going to pass through points rectangle by rectangle. Inside the rectangle we're going to pass the points in increasing order of $y$-coordinate if the number of rectangle is even and in decreasing if it's odd. Let's calculate the maximum length of such a way. The coordinates are independent. By $y$-coordinate we're passing 1000 rectangles from $0$ to $10^{6}$, $10^{9}$ in total. By $x$-coordinate we're spending $1000$ to get to the next point of current rectangle and $2000$ to get to next rectangle. That means, $2 * 10^{9} + 2000000$ in total, which perfectly fits. The complexity is $O(n * log(n))$",
    "code": "\"#include <iostream>\\n#include <fstream>\\n#include <sstream>\\n\\n#include <vector>\\n#include <set>\\n#include <bitset>\\n#include <map>\\n#include <deque>\\n#include <string>\\n\\n#include <algorithm>\\n#include <numeric>\\n\\n#include <cstdio>\\n#include <cassert>\\n#include <cstdlib>\\n#include <cstring>\\n#include <ctime>\\n#include <cmath>\\n\\n#define pb push_back\\n#define pbk pop_back\\n#define mp make_pair\\n#define fs first\\n#define sc second\\n#define all(x) (x).begin(), (x).end()\\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\\n#define len(a) ((int) (a).size())\\n\\n#ifdef CUTEBMAING\\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\\n#else\\n#define eprintf(...) 42\\n#endif\\n\\nusing namespace std;\\n\\ntypedef long long int64;\\ntypedef long double ld;\\ntypedef unsigned long long lint;\\n\\nconst int inf = (1 << 30) - 1;\\nconst int64 linf = (1ll << 62) - 1;\\nconst int C = 1000;\\n\\nint main() {\\n\\tint n; cin >> n;\\n\\tvector<pair<pair<int, int>, int>> points(n);\\n\\tfor (int i = 0; i < n; i++) {\\n\\t\\tscanf(\\\"%d%d\\\", &points[i].fs.fs, &points[i].fs.sc);\\n\\t\\tpoints[i].sc = i;\\n\\t\\tpoints[i].fs.fs /= C;\\n\\t}\\n\\tsort(all(points), [](const pair<pair<int, int>, int> &a, const pair<pair<int, int>, int> &b) {\\n\\t    return a.fs.fs < b.fs.fs || (a.fs.fs == b.fs.fs && (a.fs.fs % 2 == 0 ? (a.fs.sc < b.fs.sc) : (a.fs.sc > b.fs.sc)));\\n\\t});\\n\\tfor (auto i : points) {\\n\\t\\tprintf(\\\"%d \\\", i.sc + 1);\\n\\t}\\n\\tputs(\\\"\\\");\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "divide and conquer",
      "geometry",
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "576",
    "index": "D",
    "title": "Flights for Regular Customers",
    "statement": "In the country there are exactly $n$ cities numbered with positive integers from $1$ to $n$. In each city there is an airport is located.\n\nAlso, there is the only one airline, which makes $m$ flights. Unfortunately, to use them, you need to be a regular customer of this company, namely, you have the opportunity to enjoy flight $i$ from city $a_{i}$ to city $b_{i}$ only if you have already made at least $d_{i}$ flights before that.\n\nPlease note that flight $i$ flies exactly from city $a_{i}$ to city $b_{i}$. It can not be used to fly from city $b_{i}$ to city $a_{i}$. An interesting fact is that there may possibly be recreational flights with a beautiful view of the sky, which begin and end in the same city.\n\nYou need to get from city $1$ to city $n$. Unfortunately, you've never traveled by plane before. What minimum number of flights you have to perform in order to get to city $n$?\n\nNote that the same flight can be used multiple times.",
    "tutorial": "Let's optimize the first solution that comes to mind: $O(m * d_{max})$, let's calculate $can[t][v]$ - can we get to the vertice $v$, while passing exactly $t$ edges. Now, it's easy to find out that the set of edges we are able to go through changed only $m$ times. Let's sort these edges in increasing order of $d_{i}$, that means for each $i$ $d_{i}  \\le  d_{i + 1}$. Let's calculate $can[t][v]$ only for $t = d_{i}$. We can calculate $can[d_{i + 1}]$ using $can[d_{i}]$ by raising the adjacency matrix to the $d_{i + 1} - d_{i}$ power and applying it to $can[d_{i}]$. Next step is to fix an edge with maximal $d_{i}$ on our shortest path, let it be $i$. We know all the vertices we can be at moment $d_{i}$, so we need to calculate the shortest path to $n - 1$ using edges we can go through. We can even use Floyd algorithm to calculate that. The complexity of this solution is $O(m * n^{3} * log(d_{max}))$ and it's not enough. Next observation is that adjacency matrix contains only zeroes or ones, so we can multiply these matrixes using bitsets in $O(n^{3} / 32)$. This makes complexity $O(m * n^{3} * log(d_{max}) / 32)$, which gets accepted.",
    "code": "\"#include <iostream>\\n#include <fstream>\\n#include <sstream>\\n\\n#include <vector>\\n#include <set>\\n#include <bitset>\\n#include <map>\\n#include <deque>\\n#include <string>\\n\\n#include <algorithm>\\n#include <numeric>\\n\\n#include <cstdio>\\n#include <cassert>\\n#include <cstdlib>\\n#include <cstring>\\n#include <ctime>\\n#include <cmath>\\n\\n#define pb push_back\\n#define pbk pop_back\\n#define mp make_pair\\n#define fs first\\n#define sc second\\n#define all(x) (x).begin(), (x).end()\\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\\n#define len(a) ((int) (a).size())\\n\\n#ifdef CUTEBMAING\\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\\n#else\\n#define eprintf(...) 42\\n#endif\\n\\nusing namespace std;\\n\\ntypedef long long int64;\\ntypedef long double ld;\\ntypedef unsigned long long lint;\\n\\nconst int inf = (1 << 30) - 1;\\nconst int64 linf = (1ll << 62) - 1;\\nconst int N = 160;\\nconst int K = 30;\\n\\nstruct edges {\\n\\tint u, v;\\n};\\n\\nint n, m;\\nmap<int, vector<edges>> g;\\nvector<pair<int, vector<edges>>> events;\\n\\nbitset<N> mat[K][N];\\n\\nbitset<N> temp[N];\\n\\nvoid mul(bitset<N> a[N], bitset<N> b[N], bitset<N> c[N]) {\\n\\tfor (int i = 0; i < n; i++) {\\n\\t\\tfor (int j = 0; j < n; j++) {\\n\\t\\t\\ttemp[j].set(i, b[i].test(j));\\n\\t\\t}\\n\\t}\\n\\tfor (int i = 0; i < n; i++) {\\n\\t\\tfor (int j = 0; j < n; j++) {\\n\\t\\t\\tc[i].set(j, (a[i] & temp[j]).any());\\n\\t\\t}\\n\\t}\\n}\\n\\nint dist[N][N];\\nbool cur[N], ncur[N];\\n\\nvoid apply(bitset<N> a[N]) {\\n\\tfill_n(ncur, n, 0);\\n\\tfor (int i = 0; i < n; i++) {\\n\\t\\tif (cur[i]) {\\n\\t\\t\\tfor (int j = 0; j < n; j++) {\\n\\t\\t\\t\\tif (a[i].test(j)) {\\n\\t\\t\\t\\t\\tncur[j] = true;\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tmemcpy(cur, ncur, sizeof(bool) * n);\\n}\\n\\nint main() {\\n\\tcin >> n >> m;\\n\\tfor (int i = 0; i < m; i++) {\\n\\t\\tint a, b, d; cin >> a >> b >> d;\\n\\t\\tg[d].pb({a - 1, b - 1});\\n\\t}\\n\\tg[0].pb({n - 1, n - 1});\\n\\tg[inf].pb({n - 1, n - 1});\\n\\tevents = vector<pair<int, vector<edges>>>(all(g));\\n\\tfor (int i = 0; i < n; i++) {\\n\\t\\tfor (int j = 0; j < n; j++) {\\n\\t\\t\\tdist[i][j] = inf;\\n\\t\\t}\\n\\t\\tdist[i][i] = 0;\\n\\t\\tmat[0][i].reset();\\n\\t}\\n\\tcur[0] = 1;\\n\\tint ans = inf;\\n\\tfor (int i = 0; i < len(events) - 1; i++) {\\n\\t\\tint curTime = events[i].fs, nextTime = events[i + 1].fs;\\n\\t\\tfor (edges e : events[i].sc) {\\n\\t\\t\\tmat[0][e.u].set(e.v, true);\\n\\t\\t\\tfor (int j = 0; j < n; j++) {\\n\\t\\t\\t\\tfor (int z = 0; z < n; z++) {\\n\\t\\t\\t\\t\\tdist[j][z] = min(dist[j][z], dist[j][e.u] + dist[e.v][z] + 1);\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor (int i = 0; i < n; i++) {\\n\\t\\t\\tif (cur[i]) {\\n\\t\\t\\t\\tans = min(ans, curTime + dist[i][n - 1]);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor (int j = 1; j < K; j++) {\\n\\t\\t\\tmul(mat[j - 1], mat[j - 1], mat[j]);\\n\\t\\t}\\n\\t\\tint delta = nextTime - curTime;\\n\\t\\tfor (int j = K - 1; j >= 0; j--) {\\n\\t\\t\\tif (delta >= (1 << j)) {\\n\\t\\t\\t\\tapply(mat[j]);\\n\\t\\t\\t\\tdelta -= (1 << j);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tif (ans >= inf) {\\n\\t\\tcout << \\\"Impossible\\\" << endl;\\n\\t} else {\\n\\t\\tcout << ans << endl;\\n\\t\\teprintf(\\\"ans = %d\\\\n\\\", ans);\\n\\t}\\n    return 0;\\n}\"",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "576",
    "index": "E",
    "title": "Painting Edges",
    "statement": "Note the unusual memory limit for this problem.\n\nYou are given an undirected graph consisting of $n$ vertices and $m$ edges. The vertices are numbered with integers from $1$ to $n$, the edges are numbered with integers from $1$ to $m$. Each edge can be unpainted or be painted in one of the $k$ colors, which are numbered with integers from $1$ to $k$. Initially, none of the edges is painted in any of the colors.\n\nYou get queries of the form \"Repaint edge $e_{i}$ to color $c_{i}$\". At any time the graph formed by the edges of the same color must be bipartite. If after the repaint this condition is violated, then the query is considered to be invalid and edge $e_{i}$ keeps its color. Otherwise, edge $e_{i}$ is repainted in color $c_{i}$, and the query is considered to valid.\n\nRecall that the graph is called bipartite if the set of its vertices can be divided into two parts so that no edge connected vertices of the same parts.\n\nFor example, suppose you are given a triangle graph, that is a graph with three vertices and edges $(1, 2)$, $(2, 3)$ and $(3, 1)$. Suppose that the first two edges are painted color $1$, and the third one is painted color $2$. Then the query of \"repaint the third edge in color $1$\" will be incorrect because after its execution the graph formed by the edges of color $1$ will not be bipartite. On the other hand, it is possible to repaint the second edge in color $2$.\n\nYou receive $q$ queries. For each query, you should either apply it, and report that the query is valid, or report that the query is invalid.",
    "tutorial": "Let's solve an easier task first: independent of bipartivity, the color of edge changes. Then we could write a solution, which is pretty similar to solution of Dynamic Connectivity Offline task in $O(nlog^{2n})$. Let's consider only cases, where edges are not being deleted from the color graph. Then, we could use DSU with storing parity of the way to the parent along with parent. Now we can find parity of the path to the root by jumping through parents and xoring the parities. Also, we can connect two components by accurately calculating the parity of the path from one root to another. Now edges are being deleted. For each edge and each color we know the segments of requests, when this edge will be in the graph of specified color. Let's build a segment tree on requests, in each vertex of the tree we store list of edges which exist on the subsegment. Every segment will be split into $log$ parts, so, totally there would be $n * log$ small parts. Now we can dfs this segment tree with DSU. We get inside the vertex, apply all the requests inside it, go through the children and revert DSU to initial state. We also answer requests in leafs of the segment tree. Let's return to initial task. We can't use this technique, because we don't know the exact segments of edge existence. Instead, let's do following. Initially we add each edge right until the first appearance of this edge in requests. Now, when we're in some leaf, we found out which color this edge would be right until the next appearance of this edge. So, let's update this edge on that segment. For each leaf we're going to make an update at most once, so the complexity is $O(nlog^{2}n)$.",
    "code": "\"#include <iostream>\\n#include <fstream>\\n#include <sstream>\\n\\n#include <vector>\\n#include <set>\\n#include <bitset>\\n#include <map>\\n#include <deque>\\n#include <string>\\n\\n#include <algorithm>\\n#include <numeric>\\n\\n#include <cstdio>\\n#include <cassert>\\n#include <cstdlib>\\n#include <cstring>\\n#include <ctime>\\n#include <cmath>\\n\\n#define pb push_back\\n#define pbk pop_back\\n#define mp make_pair\\n#define fs first\\n#define sc second\\n#define all(x) (x).begin(), (x).end()\\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\\n#define len(a) ((int) (a).size())\\n\\n#ifdef CUTEBMAING\\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\\n#else\\n#define eprintf(...) 42\\n#endif\\n\\nusing namespace std;\\n\\ntypedef long long int64;\\ntypedef long double ld;\\ntypedef unsigned long long lint;\\n\\nconst int inf = (1 << 30) - 1;\\nconst int64 linf = (1ll << 62) - 1;\\nconst int N = 5e5 + 100;\\nconst int K = 50;\\n\\nstruct cooldsu {\\n\\tint parent[N], rank[N], parity[N];\\n\\tint flag = 0;\\n\\tvector<pair<int*, int>> changes;\\n\\n\\tvoid init(int n) {\\n\\t\\tfor (int i = 0; i < n; i++) {\\n\\t\\t\\tparent[i] = i, rank[i] = 0, parity[i] = 0;\\n\\t\\t}\\n\\t}\\n\\n\\tint size() { return changes.size(); }\\n\\n\\tvoid set(int *a, int b) { changes.push_back(mp(a, *a)), *a = b; }\\n\\n\\tvoid revert(int len) {\\n\\t\\twhile (len(changes) > len) {\\n\\t\\t\\t*changes.back().fs = changes.back().sc, changes.pop_back();\\n\\t\\t}\\n\\t}\\n\\n\\tpair<int, int> findSetAndParity(int v) {\\n\\t\\tint curParity = 0;\\n\\t\\twhile (parent[v] != v) {\\n\\t\\t\\tcurParity ^= parity[v], v = parent[v];\\n\\t\\t}\\n\\t\\treturn mp(v, curParity);\\n\\t}\\n\\n\\tvoid unite(int a, int b) {\\n\\t\\tpair<int, int> pa = findSetAndParity(a), pb = findSetAndParity(b);\\n\\t\\tif (pa.fs == pb.fs) {\\n\\t\\t\\tif (!flag && pa.sc == pb.sc) {\\n\\t\\t\\t\\tset(&flag, 1);\\n\\t\\t\\t}\\n\\t\\t\\treturn ;\\n\\t\\t}\\n\\t\\tif (rank[pa.fs] == rank[pb.fs]) {\\n\\t\\t\\tset(rank + pa.fs, rank[pa.fs] + 1);\\n\\t\\t}\\n\\t\\tif (rank[pa.fs] > rank[pb.fs]) {\\n\\t\\t\\tswap(pa, pb);\\n\\t\\t}\\n\\t\\tset(parent + pa.fs, pb.fs), set(parity + pa.fs, pa.sc ^ pb.sc ^ 1);\\n\\t}\\n};\\n\\nvector<pair<int, int>> rmq[N * 4 + 100];\\n\\ncooldsu dsu[K];\\n\\nint n, m, k, q;\\nint a[N], b[N];\\nint e[N], c[N];\\nint nextRequest[N], last[N];\\nint curColor[N];\\n\\nvoid update(int i, int ll, int rr, int l, int r, const pair<int, int> &add) {\\n\\tif (ll > r || rr < l) {\\n\\t\\treturn ;\\n\\t}\\n\\tif (l <= ll && rr <= r) {\\n\\t\\treturn void (rmq[i].push_back(add));\\n\\t}\\n\\tupdate(i * 2, ll, (ll + rr) / 2, l, r, add);\\n\\tupdate(i * 2 + 1, (ll + rr) / 2 + 1, rr, l, r, add);\\n}\\n\\nvoid solve(int i, int l, int r) {\\n\\tvector<int> ln(len(rmq[i]));\\n\\tfor (int j = 0; j < len(ln); j++) {\\n\\t\\tln[j] = len(dsu[rmq[i][j].sc]);\\n\\t}\\n\\tfor (auto upd : rmq[i]) {\\n\\t\\tdsu[upd.sc].unite(a[upd.fs], b[upd.fs]);\\n\\t}\\n\\tif (l == r) {\\n\\t\\tint edge = e[l], color = c[l];\\n\\t\\tint u = a[edge], v = b[edge];\\n\\t\\tpair<int, int> a = dsu[color].findSetAndParity(u), b = dsu[color].findSetAndParity(v);\\n\\t\\tif (a != b) {\\n\\t\\t\\tputs(\\\"YES\\\");\\n\\t\\t\\tupdate(1, 0, q - 1, l + 1, nextRequest[l] - 1, mp(edge, color));\\n\\t\\t\\tcurColor[edge] = color;\\n\\t\\t} else {\\n\\t\\t\\tputs(\\\"NO\\\");\\n\\t\\t\\tif (curColor[edge] != -1) {\\n\\t\\t\\t\\tupdate(1, 0, q - 1, l + 1, nextRequest[l] - 1, mp(edge, curColor[edge]));\\n\\t\\t\\t}\\n\\t\\t}\\n\\t} else {\\n\\t\\tsolve(i * 2, l, (l + r) / 2);\\n\\t\\tsolve(i * 2 + 1, (l + r) / 2 + 1, r);\\n\\t}\\n\\tfor (int j = 0; j < len(ln); j++) {\\n\\t\\tdsu[rmq[i][j].sc].revert(ln[j]);\\n\\t}\\n}\\n\\nint main() {\\n\\tcin >> n >> m >> k >> q;\\n\\tfor (int i = 0; i < k; i++) {\\n\\t\\tdsu[i].init(n);\\n\\t}\\n\\tfor (int i = 0; i < m; i++) {\\n\\t\\tscanf(\\\"%d%d\\\", &a[i], &b[i]), a[i]--, b[i]--;\\n\\t\\tcurColor[i] = -1;\\n\\t}\\n\\tfor (int i = 0; i < q; i++) {\\n\\t\\tscanf(\\\"%d%d\\\", &e[i], &c[i]), e[i]--, c[i]--;\\n\\t}\\n\\tfill_n(last, m, inf);\\n\\tfor (int i = q - 1; i >= 0; i--) {\\n\\t\\tnextRequest[i] = last[e[i]];\\n\\t\\tlast[e[i]] = i;\\n\\t}\\n\\tsolve(1, 0, q - 1);\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "577",
    "index": "A",
    "title": "Multiplication Table",
    "statement": "Let's consider a table consisting of $n$ rows and $n$ columns. The cell located at the intersection of $i$-th row and $j$-th column contains number $i × j$. The rows and columns are numbered starting from 1.\n\nYou are given a positive integer $x$. Your task is to count the number of cells in a table that contain number $x$.",
    "tutorial": "It's easy to see that number $x$ can appear in column $i$ only once - in row $x / i$. For every column $i$, let's check that $x$ divides $i$ and $x / i  \\le  n$. If all requirements are met, we'll update the answer. The complexity is $O(n)$",
    "code": "\"#include <iostream>\\n#include <fstream>\\n#include <sstream>\\n\\n#include <vector>\\n#include <set>\\n#include <bitset>\\n#include <map>\\n#include <deque>\\n#include <string>\\n\\n#include <algorithm>\\n#include <numeric>\\n\\n#include <cstdio>\\n#include <cassert>\\n#include <cstdlib>\\n#include <cstring>\\n#include <ctime>\\n#include <cmath>\\n\\n#define pb push_back\\n#define pbk pop_back\\n#define mp make_pair\\n#define fs first\\n#define sc second\\n#define all(x) (x).begin(), (x).end()\\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\\n#define len(a) ((int) (a).size())\\n\\n#ifdef CUTEBMAING\\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\\n#else\\n#define eprintf(...) 42\\n#endif\\n\\nusing namespace std;\\n\\ntypedef long long int64;\\ntypedef long double ld;\\ntypedef unsigned long long lint;\\n\\nconst int inf = (1 << 30) - 1;\\nconst int64 linf = (1ll << 62) - 1;\\n\\nint main() {\\n\\tint n, x; cin >> n >> x;\\n\\tint ans = 0;\\n\\tfor (int i = 1; i <= n; i++) {\\n\\t\\tif (x % i == 0 && x / i <= n) {\\n\\t\\t\\tans++;\\n\\t\\t}\\n\\t}\\n\\tcout << ans << endl;\\n    return 0;\\n}\"",
    "tags": [
      "implementation",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "577",
    "index": "B",
    "title": "Modulo Sum",
    "statement": "You are given a sequence of numbers $a_{1}, a_{2}, ..., a_{n}$, and a number $m$.\n\nCheck if it is possible to choose a non-empty subsequence $a_{ij}$ such that the sum of numbers in this subsequence is divisible by $m$.",
    "tutorial": "Let's consider two cases: $n > m$ and $n  \\le  m$. If $n > m$, let's look at prefix sums. By pigeonhole principle, there are two equals sums modulo $m$. Assume $S_{lmodm} = S_{rmodm}$. Then the sum on segment $[l + 1, r]$ equals zero modulo $m$, that means the answer is definitely \"YES\". If $n  \\le  m$, we'll solve this task using dynamic programming in $O(m^{2})$ time. Assume $can[i][r]$ means if we can achieve the sum equal to $r$ modulo $m$ using only first $i - 1$ items. The updates in this dynamic programming are obvious: we either take number $a_{i}$ and go to the state $can[i + 1][(r + a_{i}) mod m]$ or not, then we'll get to the state $can[i + 1][r]$. The complexity is $O(m^{2})$.",
    "code": "\"#include <iostream>\\n#include <fstream>\\n#include <sstream>\\n\\n#include <vector>\\n#include <set>\\n#include <bitset>\\n#include <map>\\n#include <deque>\\n#include <string>\\n\\n#include <algorithm>\\n#include <numeric>\\n\\n#include <cstdio>\\n#include <cassert>\\n#include <cstdlib>\\n#include <cstring>\\n#include <ctime>\\n#include <cmath>\\n\\n#define pb push_back\\n#define pbk pop_back\\n#define mp make_pair\\n#define fs first\\n#define sc second\\n#define all(x) (x).begin(), (x).end()\\n#define foreach(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); ++i)\\n#define len(a) ((int) (a).size())\\n\\n#ifdef CUTEBMAING\\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\\n#else\\n#define eprintf(...) 42\\n#endif\\n\\nusing namespace std;\\n\\ntypedef long long int64;\\ntypedef long double ld;\\ntypedef unsigned long long lint;\\n\\nconst int inf = (1 << 30) - 1;\\nconst int64 linf = (1ll << 62) - 1;\\n\\nint main() {\\n\\tint n, x; cin >> n >> x;\\n\\tint ans = 0;\\n\\tfor (int i = 1; i <= n; i++) {\\n\\t\\tif (x % i == 0 && x / i <= n) {\\n\\t\\t\\tans++;\\n\\t\\t}\\n\\t}\\n\\tcout << ans << endl;\\n    return 0;\\n}\"",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "578",
    "index": "A",
    "title": "A Problem about Polyline",
    "statement": "There is a polyline going through points $(0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – ...$.\n\nWe know that the polyline passes through the point $(a, b)$. Find minimum positive value $x$ such that it is true or determine that there is no such $x$.",
    "tutorial": "If point ($a$,$b$) is located on the up slope/ down slope of this polyline. Then the polyline will pass the point ($a - b$,$0$)/($a + b$,$0$).(we call $(a - b)$ or $(a + b)$ as $c$ afterwards) And we can derive that $c / (2 * x)$ should be a positive integer. Another condition we need to satisfy is that $x$ must be larger than or equal to $b$. It's easy to show that when those two conditions are satisfied, then the polyline will pass the point ($a$,$b$). Formally speaking in math : Let $c / (2 * x) = y$ Then we have $x = c / (2 * y)  \\ge  b$ and we want to find the maximum integer $y$. After some more math derivation, we can get the answer is $[\\mathrm{III}\\left({\\frac{a-b}{2s[}},{\\frac{d+b}{2s[}}\\right),\\,{\\frac{d+b}{2s[}}\\right)$. Besides, the only case of no solution is when $a < b$. In fact, $\\frac{a-b}{2*\\left[{\\frac{a-b}{2*b}}\\right]}$ always dosn't exist or larger than $\\frac{a+b}{2*\\left[{\\frac{a+b}{2*b}}\\right]}$.",
    "code": "#include <bits/stdc++.h>\ntypedef long long LL;\nusing namespace std;\nint main(){\n    LL a,b;\n    cin>>a>>b;\n    if(a<b)puts(\"-1\");\n    else printf(\"%.12f\\n\",(a+b)/(2.*((a+b)/(2*b))));\n    return 0;\n}\n",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "578",
    "index": "B",
    "title": "\"Or\" Game",
    "statement": "You are given $n$ numbers $a_{1}, a_{2}, ..., a_{n}$. You can perform at most $k$ operations. For each operation you can multiply one of the numbers by $x$. We want to make $a_{1}\\mid a_{2}\\mid\\dots\\mid a_{n}$ as large as possible, where denotes the bitwise OR.\n\nFind the maximum possible value of $a_{1}\\mid a_{2}\\mid\\ldots\\mid a_{n}$ after performing at most $k$ operations optimally.",
    "tutorial": "We can describe a strategy as multiplying $a_{i}$ by $x$ $t_{i}$ times so $a_{i}$ will become $b_{i} = a_{i} * x^{ti}$ and sum of all $t_{i}$ will be equals to $k$. The fact is there must be a $t_{i}$ equal to $k$ and all other $t_{i}$ equals to $0$. If not, we can choose the largest number $b_{j}$ in sequence $b$, and change the strategy so that $t_{j} = k$ and all other $t_{j} = 0$. The change will make the highest bit $1$ of $b_{j}$ become higher so the $or$-ed result would be higher. After knowing the fact, We can iterator all number in sequence a and multiply it by $x^{k}$ and find the maximum value of our target between them. There are several method to do it in lower time complexity. You can check the sample code we provide.(I believe you can understand it quickly.)",
    "code": "#include<cstdio>\n#include<algorithm>\nusing namespace std;\nconst int SIZE = 2e5+2;\nlong long a[SIZE],prefix[SIZE],suffix[SIZE];\nint main(){\n    int n,k,x;\n    scanf(\"%d%d%d\", &n, &k, &x);\n    long long mul=1;\n    while(k--)\n        mul *= x;\n    for(int i = 1; i <= n; i++)\n        scanf(\"%I64d\", &a[i]);\n    for(int i = 1; i <= n; i++)\n        prefix[i] = prefix[i-1] | a[i];\n    for(int i = n; i > 0; i--)\n        suffix[i] = suffix[i+1] | a[i];\n    long long ans = 0;\n    for(int i= 1; i <= n; i++)\n        ans = max(ans, prefix[i-1] | (a[i] * mul) | suffix[i+1]);\n    printf(\"%I64d\\n\",ans);\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "578",
    "index": "C",
    "title": "Weakness and Poorness",
    "statement": "You are given a sequence of n integers $a_{1}, a_{2}, ..., a_{n}$.\n\nDetermine a real number $x$ such that the weakness of the sequence $a_{1} - x, a_{2} - x, ..., a_{n} - x$ is as small as possible.\n\nThe weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.\n\nThe poorness of a segment is defined as the absolute value of sum of the elements of segment.",
    "tutorial": "Let $s(i,j)=\\sum_{k=i}^{j}(a_{k}-x)$, we can write down the definition of poorness formally as . It's easy to see that $A$ is a strictly decreasing function of $x$, and $B$ is a strictly increasing function of x. Thus the minimum of $max(A, B)$ can be found using binary or ternary search. The time complexity is $O(n\\log C)$, Now here give people geometry viewpoint of this problem: let $b_{i}=\\sum_{k=1t o i}a_{i}$ We plot $n + 1$ straight line $y = i * x + b_{i}$ in the plane for $i$ from $0$ to $n$. We can discover when you are given $x$. The weakness will be (y coordinator of highest line at x) - (y coordinator of lowest line at x). So we only need to consider the upper convex hull and the lower convex hull of all lines. And the target x value will be one of the intersection of these convex hull. Because you can get these line in order of their slope value. we can use stack to get the convex hulls in O(n).",
    "code": "#include <bits/stdc++.h>\ntypedef long long LL;\nusing namespace std;\nconst int SIZE = 2e5+10;\nint a[SIZE];\nint up_stk[SIZE],down_stk[SIZE];\nint Un=1,Dn=1;\nLL compare(LL x,LL y,LL z,LL w){return (a[x]-a[y])*(w-z)-(a[z]-a[w])*(y-x);}\ndouble get_x(int x,int y){return (a[x]-a[y])*1./(y-x);}\ndouble get_y(double v,int x){return x*v+a[x];}\nint main(){\n    int n;\n    scanf(\"%d\",&n);\n    for(int i=1;i<=n;i++){\n        scanf(\"%d\",&a[i]);\n        a[i]+=a[i-1];\n        while(Un>1&&compare(up_stk[Un-1],i,up_stk[Un-1],up_stk[Un-2])>=0)Un--;\n        up_stk[Un++]=i;\n        while(Dn>1&&compare(down_stk[Dn-1],i,down_stk[Dn-1],down_stk[Dn-2])<=0)Dn--;\n        down_stk[Dn++]=i;\n    }\n    reverse(down_stk,down_stk+Dn);\n    int it1=0,it2=0;\n    double an=1e18;\n    while(it1+1<Dn||it2+1<Un){\n        if(it2+1>=Un||(it1+1<Dn&&compare(down_stk[it1],down_stk[it1+1],up_stk[it2+1],up_stk[it2])<=0)){\n            double x=get_x(down_stk[it1],down_stk[it1+1]);\n            an=min(an,get_y(x,up_stk[it2])-get_y(x,down_stk[it1]));\n            it1++;\n        }\n        else{\n            double x=get_x(up_stk[it2],up_stk[it2+1]);\n            an=min(an,get_y(x,up_stk[it2])-get_y(x,down_stk[it1]));\n            it2++;\n        }\n    }\n    printf(\"%.15f\\n\",an);\n    return 0;\n}",
    "tags": [
      "ternary search"
    ],
    "rating": 2000
  },
  {
    "contest_id": "578",
    "index": "D",
    "title": "LCS Again",
    "statement": "You are given a string $S$ of length $n$ with each character being one of the first $m$ lowercase English letters.\n\nCalculate how many different strings $T$ of length $n$ composed from the first $m$ lowercase English letters exist such that the length of LCS (longest common subsequence) between $S$ and $T$ is $n - 1$.\n\nRecall that LCS of two strings $S$ and $T$ is the longest string $C$ such that $C$ both in $S$ and $T$ as a subsequence.",
    "tutorial": "Followings are solution in short. Considering the LCS dp table $lcs[x][y]$ which denotes the LCS value of first $x$ characters of $S$ and first $y$ characters of $T$. If we know $lcs[n][n] = n - 1$, then we only concern values in the table which $abs(x - y)  \\le  1$ and all value of $lcs[x][y]$ must be $min(x, y)$ or $min(x, y) - 1$. So each row contains only $8$ states(In fact,three states among these states will never be used), we can do dp on it row by row with time complexity $O(n)$. There is another not dp method. You can refer this comment.",
    "code": "#include <bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define RI(X) scanf(\"%d\", &(X))\n#define RII(X, Y) scanf(\"%d%d\", &(X), &(Y))\n#define RIII(X, Y, Z) scanf(\"%d%d%d\", &(X), &(Y), &(Z))\n#define DRI(X) int (X); scanf(\"%d\", &X)\n#define DRII(X, Y) int X, Y; scanf(\"%d%d\", &X, &Y)\n#define DRIII(X, Y, Z) int X, Y, Z; scanf(\"%d%d%d\", &X, &Y, &Z)\n#define RS(X) scanf(\"%s\", (X))\n#define CASET int ___T, case_n = 1; scanf(\"%d \", &___T); while (___T-- > 0)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define PII pair<int,int>\n#define VPII vector<pair<int,int> >\n#define PLL pair<long long,long long>\n#define F first\n#define S second\ntypedef long long LL;\nusing namespace std;\nconst int MOD = 1e9+7;\nconst int SIZE = 1e5+10;\n// template end here\nLL dp[SIZE][8];\nchar s[SIZE];\nint get_bit(int x,int v){return (x>>v)&1;}\nint main(){\n    DRII(n,m);\n    RS(s+1);\n    REPP(i,1,n+1)s[i]-='a';\n    s[n+1]=-1;\n    REP(i,m){\n        int state=1;\n        if(i==s[1])state|=2;\n        if(i==s[1]||i==s[2])state|=4;\n        dp[1][state]++;\n    }\n    REPP(i,2,n+1){\n        REP(j,8){\n            int d[4]={i-3+get_bit(j,0),i-2+get_bit(j,1),i-2+get_bit(j,2)};\n            REP(k,m){\n                int d2[4]={};\n                REPP(l,1,4){\n                    if(s[i-2+l]==k)d2[l]=d[l-1]+1;\n                    else d2[l]=max(d2[l-1],d[l]);\n                }\n                if(d2[1]>=i-2&&min(d2[2],d2[3])>=i-1)dp[i][(d2[1]-(i-2))|((d2[2]-(i-1))<<1)|((d2[3]-(i-1))<<2)]+=dp[i-1][j];\n            }\n        }\n    }\n    printf(\"%lld\\n\",dp[n][0]+dp[n][1]+dp[n][4]+dp[n][5]);\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "578",
    "index": "E",
    "title": "Walking!",
    "statement": "There is a sand trail in front of Alice's home.\n\nIn daytime, people walk over it and leave a footprint on the trail for their every single step. Alice cannot distinguish the order of the footprints, but she can tell whether each footprint is made by left foot or right foot. Also she's certain that all people are walking by alternating left foot and right foot.\n\nFor example, suppose that one person walked through the trail and left some footprints. The footprints are RRLRL in order along the trail ('R' means right foot and 'L' means left foot). You might think the outcome of the footprints is strange. But in fact, some steps are resulting from walking backwards!\n\nThere are some possible order of steps that produce these footprints such as $1 → 3 → 2 → 5 → 4$ or $2 → 3 → 4 → 5 → 1$ (we suppose that the distance between two consecutive steps can be arbitrarily long). The number of backward steps from above two examples are $2$ and $1$ separately.\n\nAlice is interested in these footprints. Whenever there is a person walking trough the trail, she takes a picture of all these footprints along the trail and erase all of them so that next person will leave a new set of footprints. We know that people walk by alternating right foot and left foot, but we don't know if the first step is made by left foot or right foot.\n\nAlice wants to know the minimum possible number of backward steps made by a person. But it's a little hard. Please help Alice to calculate it. You also need to construct one possible history of these footprints.",
    "tutorial": "Since there is only one person, it's not hard to show the difference between the number of left footprints and the number of right footprints is at most one. For a particular possible time order of a sequence of footprints, if there are $k$ backward steps, we can easily divide all footprints into at most $k + 1$ subsequences without backward steps. Then you might guess that another direction of the induction is also true.That is, we can combine any $k + 1$ subsequence without backward steps into a whole sequence contains at most $k$ backward steps. Your guess is correct ! Now we demostrate the process of combining those subsequences. We only concern the first step and the last step of a divided subsequence. There are four possible combinations, we denote them as $LL$/$LR$/$RL$/$RR$ subsequence separately(the first character is the type of the first step and the second character is the type of the second step). Suppose the number of four types of subseueqnce($LL$/$LR$/$RL$/$RR$) are $A$, $B$, $C$, $D$ separately. We have $abs(A - D)  \\le  1$. We can combine all $RR$, $LL$ subsequeces in turn into one subsequenceswith at most $A + D - 1$ backward steps(the result may be of any of the four subsquence types). Now we have at most one $LL$ or $RR$ type subsequence. Then we can combine all $RL$ subsequence into only one $RL$ subsequence with at most $A - 1$ backward steps easily. And so do $LR$ subsequences. Now we want to combine the final $RL$ and $LR$ subsequences together. We could pick the last footprint among two subsequences, exclude it from the original subsequcne and append it at the tail of another subsequence. The move will not increase the number of backward step and the types of the two subsequences would become $RR$ and $LL$ ! We can easily combine them into one $LR$ or $RL$ subsequence now. If there is still a $LL$ or $RR$ type subsequence reamained. We can easily combine them, too. So if we can divide all footprints into the least number of subsequences without backward steps. Then we have solved the problem. And this part can be done with greedy method. Now we provide one possible greedy method: Firstly, we translate this problem to a maximum matching problem on bipartite graph as following: Take \"RLLRRL\" as example: We split each footprint into two vertices which on is in left part and another is in right part. If two footprints is next to each other in resulted subsequnces, we will connect the left vertex of the former to right vertex of the latter in the corresponded matching. So the matching described in above left graph is subsequences: \"RL-R--\" and \"--L-RL\" and in above right graph is \"RL-R-L\" and \"--L-R-\". we can find that the number of subsequences is (number of footprints) - (value of matching). Due to the graphs produced by this problem is very special, we can solve this bipartite matching as following: Iterate each vertex in left part from top to bottom and find the uppermost vertex which is able to be matched in right part and connect them. If we process this algorithm in \"RLLRRL\", the resulted matching is the above right graph. Why the greedy method is correct? we can prove it by adjusting any maximum matching to our intended matching step by step. In each step, you can find the uppermost vertex the state of which is different to what we intend and change its state. I guess the mission of adjusting is not too hard for you to think out! Please solve it by yourself >_< By the way, I believe there are also many other greedy methods will work. If your greedy method is different to author's. Don't feel strange.",
    "code": "#include<bits/stdc++.h>\n#define SZ(X) ((int)(X).size())\n#define MP(X,Y) make_pair((X),(Y))\nusing namespace std;\nconst int SIZE = 100010;\nchar s[SIZE+5];\nint nxt[SIZE],lat[SIZE];\nbool pointed[SIZE];\nint footprint_type(char c){return c=='R'?1:0;}\nvector<int>seq[2][2];\nvector<int>an[SIZE];\nint pn;\nvoid connect(int x,int y){\n    nxt[x]=y;\n    lat[y]=x;\n}\nbool check(vector<pair<int,int> >&seq){\n    if(SZ(seq)<2)return 0;\n    int st=seq.back().first,ed=seq.back().second,st2=seq[SZ(seq)-2].first,ed2=seq[SZ(seq)-2].second;\n    if(s[ed]!=s[st2]){\n        connect(ed,st2);\n        seq.pop_back();\n        seq.back()=MP(st,ed2);\n        return 1;\n    }\n    if(s[ed2]!=s[st]){\n        connect(ed2,st);\n        seq.pop_back();\n        seq.back()=MP(st2,ed);\n        return 1;\n    }\n    if(s[st]!=s[ed]){\n        if(ed<ed2){\n            int z=lat[ed2];\n            connect(ed,ed2);\n            connect(ed2,st2);\n            nxt[z]=0;\n            seq.pop_back();\n            seq.back()=MP(st,z);\n        }\n        else{\n            int z=lat[ed];\n            connect(ed2,ed);\n            connect(ed,st);\n            nxt[z]=0;\n            seq.pop_back();\n            seq.back()=MP(st2,z);\n        }\n        return 1;\n    }\n    return 0;\n}\nint main(){\n    int m;\n    scanf(\"%s\",s+1);\n    m=strlen(s+1);\n    queue<int>qq[2];\n    for(int i=1;i<=m;i++){\n        int me=footprint_type(s[i]);\n        if(SZ(qq[me^1])){\n            connect(qq[me^1].front(),i);\n            pointed[i]=1;\n            qq[me^1].pop();\n        }\n        qq[me].push(i);\n    }\n    vector<pair<int,int> >seq;\n    int cnt=-1;\n    for(int i=1;i<=m;i++){\n        if(!pointed[i]){\n            cnt++;\n            int ed=i;\n            while(nxt[ed])ed=nxt[ed];\n            seq.push_back(MP(i,ed));\n            while(check(seq));\n        }\n    }\n    printf(\"%d\\n\",cnt);\n    for(int i=0;i<SZ(seq);i++){\n        int now=seq[i].first;\n        while(now){\n            if(i||now!=seq[i].first)printf(\" \");\n            printf(\"%d\",now);\n            now=nxt[now];\n        }\n    }\n    puts(\"\");\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "578",
    "index": "F",
    "title": "Mirror Box",
    "statement": "You are given a box full of mirrors. Box consists of grid of size $n × m$. Each cell of the grid contains a mirror put in the shape of '$\\$' or '$ / $' ($45$ degree to the horizontal or vertical line). But mirrors in some cells have been destroyed. You want to put new mirrors into these grids so that the following two conditions are satisfied:\n\n- If you put a light ray horizontally/vertically into the middle of any unit segment that is side of some border cell, the light will go out from the neighboring unit segment to the segment you put the ray in.\n- each unit segment of the grid of the mirror box can be penetrated by at least one light ray horizontally/vertically put into the box according to the rules of the previous paragraph\n\nAfter you tried putting some mirrors, you find out that there are many ways of doing so. How many possible ways are there? The answer might be large, so please find the result modulo prime number $MOD$.",
    "tutorial": "If we view the grid intersections alternatively colored by blue and red like this: Then we know that the two conditions in the description are equivalent to a spanning tree in either entire red intersections or entire blue dots. So we can consider a red spanning tree and blue spanning tree one at a time. We can use disjoint-sets to merge connected components. Each component should be a tree, otherwise some grid edges will be enclosed inside some mirrors. So for the contracted graph, we would like to know how many spanning trees are there. This can be done by Kirchhoff's theorem. Since there are at most 200 broken mirrors, the number of vertices in the contracted graph should be no more than 401. Hence a $O(|V|^{3})$ determinant calculation algorithm may be applied onto the matrix.",
    "code": "#include <algorithm>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cassert>\n#define SZ(x) ((int)(x).size())\n#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it)\nusing namespace std;\ntypedef long long LL;\n \nchar a[514][514];\nint n, m;\nint ID[514][514];\nint RID[20005];\nint idt[20005];\nint g[20005];\n \nint FIND(int x) { return g[x]==x? x: (g[x]=FIND(g[x])); }\nvoid UNION(int x, int y) {\n  x = FIND(x); y = FIND(y);\n  g[x] = y;\n}\nint edge(int x, int y) {\n  if (FIND(x) == FIND(y)) return 1;\n  UNION(x, y);\n  return 0;\n}\n \nLL P[2][514][514];\nint MOD = 1e9+7;\nint nid=0, Pid[2]={};\n \nvoid bridge(int x, int y) {\n  x = FIND(x); y = FIND(y);\n  if (x == y) return;\n  P[idt[x]][RID[x]][RID[x]]++;\n  P[idt[x]][RID[x]][RID[y]]--;\n  P[idt[x]][RID[y]][RID[x]]--;\n  P[idt[x]][RID[y]][RID[y]]++;\n}\n \nLL inv(LL x, LL y, LL p, LL q, LL r, LL s) {\n  if (y==0) return (p%MOD+MOD)%MOD;\n  return inv(y, x%y, r, s, p-r*(x/y), q-s*(x/y));\n}\n \nLL det(LL F[514][514], int D) {\n  LL ans = 1;\n  for (int i = 0; i < D; i++) {\n    int r = i;\n    while(r < D && F[r][i] == 0) ++r;\n    if (r >= D) return 0;\n    if (r != i) ans = ans * (MOD-1) % MOD;\n    for(int j=i;j<D;j++) swap(F[r][j], F[i][j]);\n    ans = ans * F[i][i] % MOD;\n \n    LL t = inv(F[i][i], MOD, 1, 0, 0, 1);\n    for(int j=i;j<D;j++) F[i][j] = (F[i][j] * t) % MOD;\n    for(int r=i+1;r<D;r++) if(F[r][i] != 0) {\n      LL s = F[r][i];\n      for(int j=i;j<D;j++) {\n        F[r][j] = (F[r][j] - s * F[i][j]) % MOD;\n        if (F[r][j] < 0) F[r][j] += MOD;\n      }\n    }\n  }\n  return ans;\n}\n \nint main(void) {\n  scanf(\"%d%d%d\", &n, &m, &MOD);\n  assert(1<=n && n<=100);\n  assert(1<=m && m<=100);\n  for(int i=0;i<n;i++) scanf(\"%s\", a[i]);\n  for(int i=0;i<n;i++) assert(strlen(a[i]) == m);\n  for(int i=0;i<n;i++) for(int j=0;j<m;j++) assert(a[i][j]=='/' || a[i][j]=='\\\\' || a[i][j]=='*');\n \n  for(int i=0;i<=n;i++) for(int j=0;j<=m;j++) {\n    ID[i][j] = ++nid;\n    g[nid] = nid;\n    idt[nid] = (i%2)^(j%2);\n  }\n  int fail = 0;\n  for(int i=0;i<n;i++) for(int j=0;j<m;j++) {\n    if (a[i][j] == '/') {\n      fail |= edge(ID[i+1][j], ID[i][j+1]);\n    } else if (a[i][j] == '\\\\') {\n      fail |= edge(ID[i][j], ID[i+1][j+1]);\n    }\n  }\n  if (fail) { puts(\"0\"); return 0; }\n  for(int i=0;i<=n;i++) for(int j=0;j<=m;j++) if(FIND(ID[i][j]) == ID[i][j]) {\n    RID[ID[i][j]] = Pid[idt[ID[i][j]]]++;\n  }\n \n  int cnt = 0;\n  for(int i=0;i<n;i++) {\n    for(int j=0;j<m;j++) {\n      if (a[i][j]=='*') {\n        bridge(ID[i][j], ID[i+1][j+1]);\n        bridge(ID[i+1][j], ID[i][j+1]);\n        ++cnt;\n      }\n    }\n  }\n  assert(cnt <= 200);\n  //fprintf(stderr, \"* count = %d; D=%d; %d\\n\", cnt, Pid[0], Pid[1]);\n  for(int z=0;z<2;z++)\n  for(int i=0;i<Pid[z];i++) for(int j=0;j<Pid[z];j++) P[z][i][j] = (P[z][i][j] + MOD) % MOD;\n \n  LL ans = det(P[0], Pid[0]-1) + det(P[1], Pid[1]-1);\n  printf(\"%d\\n\", (int)(ans % MOD));\n  return 0;\n}",
    "tags": [
      "matrices",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "579",
    "index": "A",
    "title": "Raising Bacteria",
    "statement": "You are a lover of bacteria. You want to raise some bacteria in a box.\n\nInitially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly $x$ bacteria in the box at some moment.\n\nWhat is the minimum number of bacteria you need to put into the box across those days?",
    "tutorial": "Write down $x$ into its binary form. If the $i^{th}$ least significant bit is $1$ and $x$ contains $n$ bits, we put one bacteria into this box in the morning of $(n + 1 - i)^{th}$ day. Then at the noon of the $n^{th}$ day, the box will contain $x$ bacteria. So the answer is the number of ones in the binary form of $x$.",
    "code": "#include<cstdio>\nint main(){\n    int n,an=0;\n    scanf(\"%d\",&n);\n    while(n){\n        if(n&1)an++;\n        n>>=1;\n    }\n    printf(\"%d\\n\",an);\n    return 0;\n}",
    "tags": [
      "bitmasks"
    ],
    "rating": 1000
  },
  {
    "contest_id": "579",
    "index": "B",
    "title": "Finding Team Member",
    "statement": "There is a programing contest named SnakeUp, $2n$ people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are \\textbf{distinct}.\n\nEvery contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people $A$ and $B$ may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one.\n\nCan you determine who will be each person’s teammate?",
    "tutorial": "Sort all possible combinations from high strength to low strength. Then iterator all combinations. If two people in a combination still are not contained in any team. then we make these two people as a team.",
    "code": "#include<cstdio>\nint person[1000001][2],an[1001];\nbool used[1001];\nint main(){\n    int n;\n    scanf(\"%d\",&n);\n    n*=2;\n    for(int i=1;i<=n;i++)\n        for(int j=1;j<i;j++){\n            int x;\n            scanf(\"%d\",&x);\n            person[x][0]=i;\n            person[x][1]=j;\n        }\n    used[0]=1;\n    for(int i=1000000;i>0;i--){\n        if(!used[person[i][0]]&&!used[person[i][1]]){\n            used[person[i][0]]=1;\n            used[person[i][1]]=1;\n            an[person[i][0]]=person[i][1];\n            an[person[i][1]]=person[i][0];\n        }\n    }\n    for(int i=1;i<=n;i++){\n        if(i>1)printf(\" \");\n        printf(\"%d\",an[i]);\n    }\n    puts(\"\");\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "580",
    "index": "A",
    "title": "Kefa and First Steps",
    "statement": "Kefa decided to make some money doing business on the Internet for exactly $n$ days. He knows that on the $i$-th day ($1 ≤ i ≤ n$) he makes $a_{i}$ money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence $a_{i}$. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.\n\nHelp Kefa cope with this task!",
    "tutorial": "Note, that if the array has two intersecting continuous non-decreasing subsequence, they can be combined into one. Therefore, you can just pass the array from left to right. If the current subsequence can be continued using the $i$-th element, then we do it, otherwise we start a new one. The answer is the maximum subsequence of all the found ones. Asymptotics - $O(n)$.",
    "code": "\"#include<iostream>\\n#include<math.h>\\n#include<algorithm>\\n#include<stdio.h>\\n#include<map>\\n#include<vector>\\n#include<set>\\n#include<iomanip>\\n#define F first\\n#define S second\\n#define P system(\\\"PAUSE\\\");\\n#define H return 0;\\n#define pb push_back\\nusing namespace std;\\nconst long long A=100000000000000LL,N=228228;\\n\\nlong long a[N],k,o,i,j,n,m;\\n\\nint main(){\\n\\tcin>>n;\\n\\tfor(i=0;i<n;i++)scanf(\\\"%d\\\",&a[i]);\\n\\tk=1;\\n\\tfor(i=1;i<n;i++)if(a[i]>=a[i-1])k++;else o=max(o,k),k=1;\\n\\to=max(o,k);\\n\\tcout<<o;\\n}\"",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "580",
    "index": "B",
    "title": "Kefa and Company",
    "statement": "Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.\n\nKefa has $n$ friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least $d$ units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!",
    "tutorial": "At first we sort all friends in money ascending order. Now the answer is some array subsegment. Next, we use the method of two pointers for finding the required subsegment. Asymptotics - $O(n$ $log$ $n)$.",
    "code": "\"#include<iostream>\\n#include<math.h>\\n#include<algorithm>\\n#include<stdio.h>\\n#include<map>\\n#include<vector>\\n#include<set>\\n#include<iomanip>\\n#define F first\\n#define S second\\n#define P system(\\\"PAUSE\\\");\\n#define H return 0;\\n#define pb push_back\\nusing namespace std;\\nconst long long A=100000000000000LL,N=228228;\\n\\nchar e[21];\\nvector<string> ot;\\npair<int,pair<int,string> > a[N];\\nlong long o,p[3]={-1,-1,-1};\\nint i,j,l,r,n,m;\\n\\nint main(){\\n\\tcin>>n>>m;\\n\\tfor(i=0;i<n;++i){\\n\\t    scanf(\\\"%d%d\\\",&a[i].F,&a[i].S.F);\\n\\t    a[i].S.S=e;\\n\\t}\\n\\tsort(a,a+n);\\n\\tfor(l=0;l<n;o-=a[l].S.F,++l){\\n\\t\\twhile(r<n && abs(a[l].F-a[r].F)<m)o+=a[r].S.F,++r;\\n\\t\\tif(o>=p[0])p[0]=o,p[1]=l,p[2]=r;\\n\\t}\\n\\tfor(i=p[1];i<p[2];++i)ot.pb(a[i].S.S);\\n\\tcout<<p[0]<<\\\"\\\\n\\\";\\n}\"",
    "tags": [
      "binary search",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "580",
    "index": "C",
    "title": "Kefa and Park",
    "statement": "Kefa decided to celebrate his first big salary by going to the restaurant.\n\nHe lives by an unusual park. The park is a rooted tree consisting of $n$ vertices with the root at vertex $1$. Vertex $1$ also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.\n\nThe leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than $m$ \\textbf{consecutive} vertices with cats.\n\nYour task is to help Kefa count the number of restaurants where he can go.",
    "tutorial": "Let's go down the tree from the root, supporting additional parameter $k$ - the number of vertices in a row met with cats. If $k$ exceeds $m$, then leave. Then the answer is the number of leaves, which we were able to reach. Asymptotics - $O(n)$.",
    "code": "\"#include<iostream>\\n#include<math.h>\\n#include<algorithm>\\n#include<stdio.h>\\n#include<map>\\n#include<vector>\\n#include<set>\\n#include<iomanip>\\n#define F first\\n#define S second\\n#define P system(\\\"PAUSE\\\");\\n#define H return 0;\\n#define pb push_back\\nusing namespace std;\\nconst long long A=100000000000000LL,N=228228;\\n\\nvector<long long> a[N];\\nlong long c[N],o,x,y,i,j,n,m;\\n\\nvoid go(int v,int pr,int k){\\n\\tif(k>m)return;\\n\\tint ok=1;\\n\\tfor(int i=0;i<a[v].size();i++)if(a[v][i]!=pr)ok=0,go(a[v][i],v,k*c[a[v][i]]+c[a[v][i]]);\\n\\to+=ok;\\n}\\n\\nint main(){\\n\\tcin>>n>>m;\\n\\tfor(i=0;i<n;i++)scanf(\\\"%d\\\",&c[i]);\\n\\tfor(i=1;i<n;i++)scanf(\\\"%d%d\\\",&x,&y),x--,y--,a[x].pb(y),a[y].pb(x);\\n\\tgo(0,-1,c[0]);\\n\\tcout<<o<<\\\"\\\\n\\\";\\n}\"",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "580",
    "index": "D",
    "title": "Kefa and Dishes",
    "statement": "When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were $n$ dishes. Kefa knows that he needs exactly $m$ dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible.\n\nKefa knows that the $i$-th dish gives him $a_{i}$ units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself $k$ rules of eating food of the following type — if he eats dish $x$ exactly before dish $y$ (there should be no other dishes between $x$ and $y$), then his satisfaction level raises by $c$.\n\nOf course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!",
    "tutorial": "A two-dimensional DP will be used to solve the problem. The first dimention is the mask of already taken dishes, and the second - the number of the last taken dish. We will go through all the zero bits of the current mask for the transitions. We will try to put the one in them, and then update the answer for a new mask. The answer will consist of the answer of the old mask, a dish value, which conforms to the added bit and the rule, that can be used. The final answer is the maximum of all the values of DP, where mask contains exactly $m$ ones. Asymptotics - $O(2^{n} * n^{2})$.",
    "code": "\"#include<iostream>\\n#include<math.h>\\n#include<algorithm>\\n#include<stdio.h>\\n#include<map>\\n#include<vector>\\n#include<set>\\n#include<iomanip>\\n#define F first\\n#define S second\\n#define P system(\\\"PAUSE\\\");\\n#define H return 0;\\n#define pb push_back\\nusing namespace std;\\nconst long long A=100000000000000LL,N=1228228;\\n\\nlong long mask,i,j,n,m,k,a[N],b[N],x,y,z,c[21][21],o,ot,dp[N][21];\\n\\nlong long len(long long mask){\\n\\tlong long k=0;\\n\\tfor(i=0;i<n;i++)if(mask&b[i])k++;\\n\\treturn k;\\n}\\n\\nint main(){\\n\\tcin>>n>>m>>k;\\n\\tfor(i=0;i<n;i++)scanf(\\\"%d\\\",&a[i]);\\n\\tb[0]=1;\\n\\tfor(i=1;i<=n;i++)b[i]=b[i-1]*2;\\n\\twhile(k--)scanf(\\\"%d%d%d\\\",&x,&y,&z),c[x-1][y-1]=z;\\n\\tfor(i=0;i<n;i++)dp[b[i]][i]=a[i];\\n\\tfor(mask=0;mask<b[n];mask++)for(i=0;i<n;i++)if(mask&b[i]){\\n        for(j=0;j<n;j++)if((mask&b[j])==0)dp[(mask|b[j])][j]=max(dp[(mask|b[j])][j],dp[mask][i]+c[i][j]+a[j]);\\n\\t}\\n\\tfor(mask=0;mask<b[n];mask++)if(len(mask)==m)for(i=0;i<n;i++)o=max(o,dp[mask][i]);\\n\\tcout<<o<<\\\"\\\\n\\\";\\n}\"",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "580",
    "index": "E",
    "title": "Kefa and Watch",
    "statement": "One day Kefa the parrot was walking down the street as he was on the way home from the restaurant when he saw something glittering by the road. As he came nearer he understood that it was a watch. He decided to take it to the pawnbroker to earn some money.\n\nThe pawnbroker said that each watch contains a serial number represented by a string of digits from $0$ to $9$, and the more quality checks this number passes, the higher is the value of the watch. The check is defined by three positive integers $l$, $r$ and $d$. The watches pass a check if a substring of the serial number from $l$ to $r$ has period $d$. Sometimes the pawnbroker gets distracted and Kefa changes in some substring of the serial number all digits to $c$ in order to increase profit from the watch.\n\nThe seller has a lot of things to do to begin with and with Kefa messing about, he gave you a task: to write a program that determines the value of the watch.\n\nLet us remind you that number $x$ is called a period of string $s$ ($1 ≤ x ≤ |s|$), if $s_{i} = s_{i + x}$ for all $i$ from 1 to $|s| - x$.",
    "tutorial": "At first, we calculate the hash for all line elements depending on their positions. That is, the hash of the number $k$, standing on the $i$-th position will be equal to $g_{i}$ * $k$, where $g$ is the base of the hash. We construct the segment tree of sums, which support a group modification, for all hashes. Thus, we can perform queries for modification in $O(log$ $n)$. It remains to deal with the queries of the second type. Let us assume, that we want to process the query 2 $l$ $r$ $d$. Obviously, the substring from $l$ to $r$ have a $d$-period, if a substring from $l + d$ to $r$ is equal to substring from $l$ to $r - d$. We can find out the sum of hashes at the subsegment with the help of the sums tree, so we can compare the two strings in $O(log$ $n)$. Asymptotics - $O(m$ $log$ $n)$.",
    "code": "\"#include<iostream>\\n#include<math.h>\\n#include<algorithm>\\n#include<stdio.h>\\n#include<map>\\n#include<vector>\\n#include<set>\\n#include<iomanip>\\n#define F first\\n#define S second\\n#define P system(\\\"PAUSE\\\");\\n#define H return 0;\\n#define pb push_back\\nusing namespace std;\\n\\nconst long long A=100000000000000LL,N=228228;\\nconst long long os[2]={11,13};\\nconst long long MOD[2]={1000000007,1073676287};\\n\\nstring a;\\nlong long t[2][2][N*4],st[2][N],dp[2][N],type,l,r,d,i,j,n,m[2];\\n\\nlong long Get(int k,int l,int r){\\n    l--,r--;\\n    if(!l)return dp[k][r];else return ((dp[k][r]-dp[k][l-1])%MOD[k]+MOD[k])%MOD[k];\\n}\\n\\nvoid push(int k,int v,int l,int r){\\n    if(!t[k][1][v])return;\\n    int mid=(l+r)/2;\\n    t[k][0][v*2]=(t[k][1][v]*Get(k,l,mid))%MOD[k];\\n    t[k][0][v*2+1]=(t[k][1][v]*Get(k,mid+1,r))%MOD[k];\\n    t[k][1][v*2]=t[k][1][v*2+1]=t[k][1][v];\\n    t[k][1][v]=0;\\n}\\n\\nvoid modi(int k,int v,int l,int r,int _l,int _r,long long g){\\n    if(_l>_r)return;\\n    if(l==_l && r==_r){\\n        t[k][0][v]=(g*Get(k,l,r))%MOD[k],t[k][1][v]=g;\\n        return;\\n    }\\n    int mid=(l+r)/2;\\n    push(k,v,l,r);\\n    modi(k,v*2,l,mid,_l,min(_r,mid),g),modi(k,v*2+1,mid+1,r,max(mid+1,_l),_r,g);\\n    t[k][0][v]=t[k][0][v*2]+t[k][0][v*2+1];\\n}\\n\\nlong long get(int k,int v,int l,int r,int _l,int _r){\\n    if(_l>_r)return 0;\\n    if(l==_l && r==_r)return t[k][0][v];\\n    push(k,v,l,r);\\n    int mid=(l+r)/2;\\n    return (get(k,v*2,l,mid,_l,min(mid,_r))+get(k,v*2+1,mid+1,r,max(mid+1,_l),_r))%MOD[k];\\n}\\n\\nint main(){\\n    cin>>n>>m[0]>>m[1];\\n    cin>>a;\\n    for(d=0;d<2;d++){\\n        st[d][0]=dp[d][0]=1;\\n        for(i=1;i<n;i++)st[d][i]=st[d][i-1]*os[d],st[d][i]%=MOD[d],dp[d][i]=dp[d][i-1]+st[d][i],dp[d][i]%=MOD[d];\\n        for(i=0;i<n;i++)modi(d,1,1,n,i+1,i+1,a[i]-'0'+1);\\n    }\\n    m[0]+=m[1];\\n    while(m[0]--){\\n        scanf(\\\"%d%d%d%d\\\",&type,&l,&r,&d);\\n        if(type==1){\\n            for(i=0;i<2;i++)modi(i,1,1,n,l,r,d+1);\\n        }else{\\n            if(l==r || (((get(0,1,1,n,l,r-d)*st[0][d])%MOD[0]==get(0,1,1,n,l+d,r))&&\\n                ((get(1,1,1,n,l,r-d)*st[1][d])%MOD[1]==get(1,1,1,n,l+d,r))))puts(\\\"YES\\\");else puts(\\\"NO\\\");\\n        }\\n    }\\n}\"",
    "tags": [
      "data structures",
      "hashing",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "581",
    "index": "A",
    "title": "Vasya the Hipster",
    "statement": "One day Vasya the Hipster decided to count how many socks he had. It turned out that he had $a$ red socks and $b$ blue socks.\n\nAccording to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.\n\nEvery day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.\n\nVasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.\n\nCan you help him?",
    "tutorial": "The first number in answer (number of days which Vasya can dress fashionably) is $min(a, b)$ because every from this day he will dress one red sock and one blue sock. After this Vasya will have either only red socks or only blue socks or socks do not remain at all. Because of that the second number in answer is $max((a - min(a, b)) / 2, (b - min(a, b)) / 2)$. Asymptotic behavior of this solution - O(1).",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "581",
    "index": "B",
    "title": "Luxurious Houses",
    "statement": "The capital of Berland has $n$ multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.\n\nLet's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.\n\nThe new architect is interested in $n$ questions, $i$-th of them is about the following: \"how many floors should be added to the $i$-th house to make it luxurious?\" (for all $i$ from $1$ to $n$, inclusive). You need to help him cope with this task.\n\nNote that all these questions are independent from each other — the answer to the question for house $i$ does not affect other answers (i.e., the floors to the houses are not actually added).",
    "tutorial": "This problem can be solved in the following way. Let's iterate on given array from the right to the left and will store in variable $maxH$ the maximal height if house which we have already considered.Then the answer to house number $i$ is number $max(0, maxH + 1 - h_{i})$, where $h_{i}$ number of floors in house number $i$. Asymptotic behavior of this solution - O($n$), where $n$ - number of houses.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "581",
    "index": "C",
    "title": "Developing Skills",
    "statement": "Petya loves computer games. Finally a game that he's been waiting for so long came out!\n\nThe main character of this game has $n$ different skills, each of which is characterized by an integer $a_{i}$ from 0 to 100. The higher the number $a_{i}$ is, the higher is the $i$-th skill of the character. The total rating of the character is calculated as the sum of the values ​​of $\\frac{a_{i}}{10}\\Big\\}$ for all $i$ from 1 to $n$. The expression $⌊ x⌋$ denotes the result of rounding the number $x$ down to the nearest integer.\n\nAt the beginning of the game Petya got $k$ improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if $a_{4} = 46$, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.\n\nYour task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.",
    "tutorial": "This problem can be solved in many ways. Let's consider the most intuitive way that fits in the given time. In the beginning we need to sort given array in the following way - from two numbers to the left should be the number to which must be added fewer units of improvements to make it a multiple of 10. You must add at least one unit of energy to every of this numbers. For example, if given array is ${45, 30, 87, 26}$ after the sort the array must be equal to ${87, 26, 45, 30}$. Now we iterate on the sorted array for $i$ from 1 to $n$. Let's $cur = 10 - (a_{i}mod10)$. If $cur  \\le  k$ assign $a_{i} = a_{i} + cur$ and from $k$ subtract $cur$ else if $cur > k$ break from cycle. The next step is to iterate on array in the same way. Now we need only to calculate answer $ans$ - we iterate on array for $i$ from 1 to $n$ and assign $ans = ans + (a_{i} / 10)$. Asymptotic behavior of this solution - O($n * log(n)$) where $n$ is the number of hero skills.",
    "tags": [
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "581",
    "index": "D",
    "title": "Three Logos",
    "statement": "Three companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area.\n\nAdvertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.\n\nYour task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.",
    "tutorial": "This problem can be solved in many ways, let's consider one of them. The first step is to calculate sum of squares $s$ of given rectangles. Then the side of a answer square is $sqrt(s)$. If $sqrt(s)$ is not integer print -1. Else we need to make the following. We brute the order in which we will add given rectangles in the answer square (we can do it with help of $next_permutation())$ and for every order we brute will we rotate current rectangle on 90 degrees or not (we can do it with help of bit masks). In the beginning on every iteration the answer square $c$ in which we add the rectangles is empty. For every rectangle, which we add to the answer square we make the following - we need to find the uppermost and leftmost empty cell $free$ in answer square $c$ (recall that we also brute will we rotate the current rectangle on 90 degrees or not). Now we try to impose current rectangle in the answer square $c$ and the top left corner must coinside with the cell $free$. If current rectangle fully placed in the answer square $c$ and does not intersect with the some rectangle which has already been added, we need to fill by the required letter appropriate cells in the answer square $c$. If no one of the conditions did not disrupted after we added all three rectangles and all answer square $c$ is fully filled by letters we found answer and we neeed only to print the answer square $c$. Else if we did not find answer after all iterations on the rectangles - print -1. For random number of the rectangles $k$ asymptotic behavior - O($k! * 2^{k} * s$) where $s$ - the sum of squares of the given rectangles. Also this problem with 3 rectangles can be solved with the analysis of the cases with asymptotic O($s$) where $s$ - the sum of squares of given rectangles.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "581",
    "index": "E",
    "title": "Kojiro and Furrari",
    "statement": "Motorist Kojiro spent $10$ years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.\n\nKojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point $f$ of a coordinate line, and Johanna is at point $e$. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers $t_{i}$ and $x_{i}$ — the number of the gas type and its position.\n\nOne liter of fuel is enough to drive for exactly $1$ km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly $s$ liters of fuel (regardless of the type of fuel). At the moment of departure from point $f$ Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than $s$ liters. Note that the tank \\textbf{can} simultaneously have different types of fuel. The car can moves both left and right.\n\nTo extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from $f$ to $e$, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.\n\nWrite a program that can for the $m$ possible positions of the start $f_{i}$ minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.",
    "tutorial": "Let's $f$ - the position of start, and $e$ - the position of finish. For convenience of implementation we add the gas-station in point $e$ with type equals to $3$. Note: there is never a sense go to the left of the starting point because we already stand with a full tank of the besr petrol. It is correct for every gas-station in which we can appear (if in optimal answer we must go to the left in some gas-station $pv$, why not throw out all the way from $pv$ to current gas-station $v$ and back and after that the answer will be better). Now let's say about algorithm when we are in some gas-station $v$. The first case: on distance no more than $s$ there is the gas-station with quality of gasoline not worse, than in the current gas-station. Now we fix nearest from them $nv$ (nearest to the right because go to the left as we understand makes no sense). In that case we refuel in such a way to can reach $nv$ and go to $nv$. The second case: from the current gas-station we can reach only gas-station with the worst quality (the type of the current gas-station can be 2 or 3). If we are in the gas-station of type 2 we need to refuel on maximum possiblevalue and go in the last achievable gas-station. If we are in the gas-station with type 3, we need to go in the farthest gas-station with type $2$, but if there is not such gas-station we need to go to the farthest gas-station with type $1$. This reasoning are correct because we first need to minimze the count of fuel with type $1$, and the second to minimize the count of fuel with type $2$. This basic reasoning necessary to solve the problem. The next step - calc dynamic on all suffixes $i$ of gas-stations - the answer to the problem if we start from the gas-station $i$ with empty tank. We need to make updates, considering the above cases. For update the dynamic in $v$ we need to take the value of dynamic in $nv$ and make update in addiction of the case. If the case is equals to $1$, we need to add to appropriate value the distance $d$ from $v$ to $nv$. If this case is equals to $2$ and we are in the gas-station with type equals to $2$ we need to add $s$ to the second value of answer, and from the first value we need to substract $s-d$. If it is the case number $2$ and we are in the gas-station with type equals to $3$, we need to substract from the value, which determined by the type of the gas-station $nv$, $s-d$. Now to answer on specific query of the starting position we nned to find the first gas-station which is to the right of the startiong position, make one update and take the value of dynamic, which already calculated, and recalculate this value in accordance with the above. Asymptotic behavior - O(n logn) or O(n) in case how we find position in the list of gas-stations (the first in case of binary search, the second in case of two pointers). To this solution we need O(n) memory.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "581",
    "index": "F",
    "title": "Zublicanes and Mumocrates",
    "statement": "It's election time in Berland. The favorites are of course parties of zublicanes and mumocrates. The election campaigns of both parties include numerous demonstrations on $n$ main squares of the capital of Berland. Each of the $n$ squares certainly can have demonstrations of only one party, otherwise it could lead to riots. On the other hand, both parties have applied to host a huge number of demonstrations, so that on all squares demonstrations must be held. Now the capital management will distribute the area between the two parties.\n\nSome pairs of squares are connected by $(n - 1)$ bidirectional roads such that between any pair of squares there is a unique way to get from one square to another. Some squares are on the outskirts of the capital meaning that they are connected by a road with only one other square, such squares are called dead end squares.\n\nThe mayor of the capital instructed to distribute all the squares between the parties so that the dead end squares had the same number of demonstrations of the first and the second party. It is guaranteed that the number of dead end squares of the city is even.\n\nTo prevent possible conflicts between the zublicanes and the mumocrates it was decided to minimize the number of roads connecting the squares with the distinct parties. You, as a developer of the department of distributing squares, should determine this smallest number.",
    "tutorial": "Let the number of leavs in tree (vertices with degree 1) is equal to $c$. It said in statement that $c$ is even. If in given graph only 2 vertices the answer is equal to $1$. Else we have vertex in graph which do not a leaf - we hang the three on this vertex. Now we need to count 2 dynamics. The first $z1[v][cnt][col]$ - the least amount of colored edges in the subtree rooted at the vertex $v$, if vertex $v$ already painted in color $col$ ($col$ equals to $0$ or to $1$), and among the top of the leaves of the subtree $v$ must be exactly $cnt$ vertices with color $0$. If we are in the leaf, it is easy to count this value. If we are not in the leaf - we count value with help of dynamic $z1[v][cnt][col]: = z2[s][cnt][col]$, where $s$ - the first child int the adjacency list of vertex $v$. We need the second dynamic $z2[s][cnt][col]$ to spread $cnt$ leaves with color $0$ among subtrees of childs of vertex $v$. To calc $z2[s][cnt][col]$ we brute the color of child $s$ - $ncol$ and the number of childs $i$ with color $0$, which will be locate in subtree of vertex $s$ and calc the value in the following way - $z2[s][cnt][col] = min(z2[s][cnt][col], z2[ns][cnt-a][col] + z1[s][a][ncol] + (ncol! = col))$, where $ns$ - the next child of vertex $v$ after the child $s$. Note, that it is senselessly to take $a$ more than the number of leaves in the subtree $s$ and to take more than the number of vertices in subtree - $size_{s}$ (because in that case it will not be enough leaves for painting). The upper bound of asymptotic for such dynamics $O(n^{3})$. We show that in fact it works with asymptotic $O(n^{2})$. Let's count the number of updates: $\\begin{array}{l}{{\\sum_{v=1}^{n}\\sum_{i=1}^{s z(g[v])}(\\sum_{j=1}^{i-1}s i z e_{g_{v,j}}.s i z e_{g_{v,i}})=\\sum_{v=1}^{n}\\sum_{i=1}^{s z(g[v])}\\sum_{j=1}^{i-1}s i z e_{g_{v,i}}.s i z e_{g_{v,j}}}\\end{array}$. Note, that every pair of vertices $(x, y)$ appears in the last sum $(x, y)$ exactly once when $v = lca(x, y)$. So we have no more than $O(n^{2})$ updates. Asymptotic behavior of this solution: $O(n^{2})$.",
    "tags": [
      "dp",
      "trees",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "582",
    "index": "A",
    "title": "GCD Table",
    "statement": "The GCD table $G$ of size $n × n$ for an array of positive integers $a$ of length $n$ is defined by formula\n\n\\begin{center}\n$g_{i j}=\\operatorname*{gcd}(a_{i},a_{j}).$\n\\end{center}\n\nLet us remind you that the greatest common divisor (GCD) of two positive integers $x$ and $y$ is the greatest integer that is divisor of both $x$ and $y$, it is denoted as $\\operatorname*{gcd}(x,y)$. For example, for array $a = {4, 3, 6, 2}$ of length 4 the GCD table will look as follows:\n\nGiven all the numbers of the GCD table $G$, restore array $a$.",
    "tutorial": "Let the answer be $a_{1}  \\le  a_{2}  \\le  ...  \\le  a_{n}$. We will use the fact that $gcd(a_{i}, a_{j})  \\le  a_{min(i, j)}$. It is true that $gcd(a_{n}, a_{n}) = a_{n}  \\ge  a_{i}  \\ge  gcd(a_{i}, a_{j})$ for every $1  \\le  i, j  \\le  n$. That means that $a_{n}$ is equal to maximum element in the table. Let set $a_{n}$ to maximal element in the table and delete it from table elements set. We've deleted $gcd(a_{n}, a_{n})$, so the set now contains all $gcd(a_{i}, a_{j})$, for every $1  \\le  i, j  \\le  n$ and $1  \\le  min(i, j)  \\le  n - 1$. By the last two inequalities $gcd(a_{i}, a_{j})  \\le  a_{min(i, j)}  \\le  a_{n - 1} = gcd(a_{n - 1}, a_{n - 1})$. As soon as set contains $gcd(a_{n - 1}, a_{n - 1})$, the maximum element in current element set is equal to $a_{n - 1}$. As far as we already know $a_{n}$, let's delete the $gcd(a_{n - 1}, a_{n - 1})$, $gcd(a_{n - 1}, a_{n})$, $gcd(a_{n}, a_{n - 1})$ from the element set. Now set contains all the $gcd(a_{i}, a_{j})$, for every $1  \\le  i, j  \\le  n$ and $1  \\le  min(i, j)  \\le  n - 2$. We're repeating that operation for every $k$ from $n - 2$ to $1$, setting $a_{k}$ to maximum element in the set and deleting the $gcd(a_{k}, a_{k})$, $gcd(a_{i}, a_{k})$, $gcd(a_{k}, a_{i})$ for every $k < i  \\le  n$ from the set. One could prove correctness of this algorithm by mathematical induction. For performing deleting and getting maximum element operations one could use multiset or map structure, so solution has complexity $O(n^{2}\\log{n})$.",
    "code": "#include <cstdio>\n#include <map>\n#include <cassert>\n \n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n \nusing namespace std;\n \nconst int N = 1000;\n \nmap <int, int> cnt;\nint ans[N];\n \nint gcd(int a, int b) {\n    return b == 0 ? a : gcd(b, a % b);\n}\n \nint main() {\n    int n;\n    scanf(\"%d\", &n);\n \n    forn(i, n * n) {\n        int a;\n        scanf(\"%d\", &a);\n        cnt[-a]++;\n    }\n \n    int pos = n - 1;\n \n    for (map <int, int> :: iterator it = cnt.begin(); it != cnt.end(); ++it) {\n        int x = -it->first;\n \n        while (it->second) {\n            ans[pos] = x;\n            --it->second;\n \n            for (int i = pos + 1; i < n; ++i)\n                cnt[-gcd(ans[pos], ans[i])] -= 2;\n \n            pos--;\n        }\n    }\n \n    forn(i, n)\n        printf(\"%d \", ans[i]);\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "582",
    "index": "B",
    "title": "Once Again...",
    "statement": "You are given an array of positive integers $a_{1}, a_{2}, ..., a_{n × T}$ of length $n × T$. We know that for any $i > n$ it is true that $a_{i} = a_{i - n}$. Find the length of the longest non-decreasing sequence of the given array.",
    "tutorial": "One could calculate matrix sized $n  \\times  n$ $mt[i][j]$ - the length of the longest non-decreasing subsequence in array $a_{1}, a_{2}, ..., a_{n}$, starting at element, greater-or-equal to $a_{i}$ and ending strictly in $a_{j}$ element with $j$-th index. One could prove that if we have two matrices sized $n  \\times  n$ $A[i][j]$ (the answer for $a_{1}, a_{2}, ..., a_{pn}$ starting at element, greater-or-equal to $a_{i}$ and ending strictly in $a_{j}$ element with $j$-th index inside last block ($a_{(p - 1)n + 1}, ..., a_{pn}$) and $B[i][j]$ (the answer for $a_{1}, a_{2}, ..., a_{qn}$ ), then the multiplication of this matrices in a way $C[i][j]={\\underset{k=1}{\\operatorname*{max}}}\\left(A[i][k]+B[k][j]\\right)$ will give the same matrix but for length $p + q$. As soon as such multiplication is associative, next we will use fast matrix exponentiation algorithm to calculate $M[i][j]$ (the answer for $a_{1}, a_{2}, ..., a_{nT}$) - matrix $mt[i][j]$ raised in power $T$. The answer is the maximum in matrix $M$. Such solution has complexity $O(n^{3}\\log T)$. Jury's solution (with matrices): 13390660 There's an alternative solution. As soon as $a_{1}, a_{2}, ..., a_{nT}$ contains maximum $n$ distinct elements, it's any non-decreasing subsequence has a maximum of $n - 1$ increasing consequtive element pairs. Using that fact, one could calculate standard longest non-decreasing subsequence dynamic programming on first $n$ array blocks ($a_{1}, ..., a_{n^{2}}$) and longest non-decreasing subsequence DP on the last $n$ array blocks ($a_{nT - n + 1}, ..., a_{nT}$). All other $T - 2n$ blocks between them will make subsegment of consequtive equal elements in longest non-decreasing subsequence. So, for fixed $a_{i}$, in which longest non-decreasing subsequence of length $p$ on first $n$ blocks array ends, and for fixed $a_{j}  \\ge  a_{i}$, in which longest non-decreasing subsequence of length $s$ on last $n$ blocks array starts, we must update the answer with $p + (T - 2n)count(a_{i}) + s$, where $count(x)$ is the number of occurences of $x$ in $a_{1}, ..., a_{n}$ array. This gives us $O(n^{2}\\log{n})$ solution.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 100 + 5;\nint n, T, a[N];\n \nvector <int> build(int t) {\n    vector <int> res(n * t);\n    for (int i = 0; i < n * t; ++i)\n        res[i] = (i < n) ? a[i] : res[i - n];\n    return res;\n}\n \nvector <int> calc_lis(vector <int> a) {\n    int n = a.size();\n    vector <int> res(n), dp(n + 1, 500);\n    dp[0] = -1;\n    for (int i = 0; i < n; ++i) {\n            res[i] = upper_bound(dp.begin(), dp.end(), a[i]) - dp.begin();\n            dp[ res[i] ] = a[i];\n    }\n    return res;\n}\n \nint main() {\n    cin >> n >> T;\n    for (int i = 0; i < n; ++i)\n        cin >> a[i];\n    int res = 0;\n    if (T <= 2 * n) {\n        vector <int> A = build(T);\n        A = calc_lis(A);\n        for (int i = 0; i < n * T; ++i)\n            res = max(res, A[i]);\n    } else {\n        vector <int> A = build(n);\n        vector <int> inc = calc_lis(A);\n        for (int i = 0; i < n * n; ++i) \n            A[i] = 301 - A[i];\n        reverse(A.begin(), A.end());\n        vector <int> dec = calc_lis(A);\n        reverse(dec.begin(), dec.end());\n        for (int i = 0; i < n; ++i) {\n            int cnt = 0;\n            for (int j = 0; j < n; ++j)\n                if (a[i] == a[j]) cnt++;\n            for (int j = 0; j < n; ++j) {\n                if (a[j] < a[i]) continue;\n                res = max(res, inc[(n - 1) * n + i] + cnt * (T - 2 * n) + dec[j]);\n            }\n        }           \n    }\n    cout << res << endl;\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "matrices"
    ],
    "rating": 1900
  },
  {
    "contest_id": "582",
    "index": "C",
    "title": "Superior Periodic Subarrays",
    "statement": "You are given an infinite periodic array $a_{0}, a_{1}, ..., a_{n - 1}, ...$ with the period of length $n$. Formally, $a_{i}=a_{i}{\\bmod{n}}$. A periodic subarray $(l, s)$ ($0 ≤ l < n$, $1 ≤ s < n$) of array $a$ is an infinite periodic array with a period of length $s$ that is a subsegment of array $a$, starting with position $l$.\n\nA periodic subarray $(l, s)$ is superior, if when attaching it to the array $a$, starting from index $l$, any element of the subarray is larger than or equal to the corresponding element of array $a$. An example of attaching is given on the figure (top — infinite array $a$, bottom — its periodic subarray $(l, s)$):\n\nFind the number of distinct pairs $(l, s)$, corresponding to the superior periodic arrays.",
    "tutorial": "Let's fix $s$ for every $(l, s)$ pair. One could easily prove, that if subarray contains $a_{i}$ element, than $a_{i}$ must be greater-or-equal than $a_{j}$ for every $j$ such that $i\\equiv j\\mathrm{\\mod\\}g c d(n,s)$. Let's use this idea and fix $g = gcd(n, s)$ (it must be a divisor of $n$). To check if $a_{i}$ can be in subarray with such constraints, let's for every $0  \\le  r < g$ calculate $p n l l\\imath_{r}\\implies\\operatorname*{max}_{i\\equiv r\\mod{g}}$. It's true that every good subarray must consist of and only of $a_{i}=r n n_{i}\\;\\mathrm{\\,mod\\,}g$. For finding all such subarrays we will use two pointers approach and for every good $a_{i}$, such that $\\ U(i{-}1)\\mod n$ is not good we will find $a_{j}$ such that $\\qquad d_{i},\\ Q_{(i+1)}\\quad\\mathrm{mod}\\ n\\,,\\ \\cdot\\cdot\\cdot\\cdot\\cdot\\alpha_{j}$ are good and $U(j+1)\\mod n)$ is not good. Let $\\begin{array}{r l}{{a_{i},\\,Q_{(i+1)}}}&{{\\operatorname*{mod}\\,n,\\,\\cdot\\,\\cdot\\,\\cdot\\,\\cdot\\,\\cdot\\,Q_{j}}}\\end{array}$ has $k$ elements $i+k-1\\equiv j\\mod n)$. Any it's subarray is superior, so it gives us arrays of length $1, 2, ..., k$ with count $k, k - 1, ..., 1$. As soon as sum of all $k$ is not greater than $n$, we could just increase counts straightforward. There's a case when all $a_{i}$ are good, in which we must do another increases. Next we must add to the answer only counts of length $x$, such that $gcd(x, n) = g$. Solution described above has complexity $O(d(n)n)$, where $d(n)$ is the number of divisors of $n$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 1000 * 1000 + 5;\nint a[N], n, c[N], gg[N];\nbool u[N];\n \ninline int inc(int v) { return (v + 1 == n) ? 0 : (v + 1); }\ninline int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }\n \nint main() {\n    assert(scanf(\"%d\", &n) == 1);\n    for (int i = 0; i < n; ++i) assert(scanf(\"%d\", &a[i]) == 1);\n    for (int i = 1; i <= n; ++i) gg[i] = gcd(i, n);\n    long long res = 0;\n    for (int g = 1; g < n; ++g) {\n        if (n % g != 0) continue;\n        for (int i = 0; i < n; ++i) u[i] = false, c[i] = 0;\n        for (int i = 0; i < g; ++i) {\n            int mx = -1;\n            for (int j = i; j < n; j += g) mx = max(mx, a[j]);\n            for (int j = i; j < n; j += g) \n                if (a[j] == mx) u[j] = true;\n        }\n        bool any = false;\n        for (int l = 0; l < n;) {\n            int r = inc(l);\n            if (u[l]) { l++; continue; }\n            any = true;\n            int len = 0;\n            while (u[r]) len++, r = inc(r);\n            for (int i = 1; i <= len; ++i) c[i] += len - i + 1;\n            if (r <= l) break;\n            l = r;\n        }\n        if (!any)\n            for (int i = 1; i <= n; ++i) c[i] += n;\n            for (int i = 1; i <= n; ++i)\n            if (gg[i] == g) res += c[i];\n    }\n    cout << res << endl;\n    return 0;\n}",
    "tags": [
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "582",
    "index": "D",
    "title": "Number of Binominal Coefficients",
    "statement": "For a given prime integer $p$ and integers $α, A$ calculate the number of pairs of integers $(n, k)$, such that $0 ≤ k ≤ n ≤ A$ and $\\textstyle{\\binom{n}{k}}$ is divisible by $p^{α}$.\n\nAs the answer can be rather large, print the remainder of the answer moduly $10^{9} + 7$.\n\nLet us remind you that $\\textstyle{\\binom{n}{k}}$ is the number of ways $k$ objects can be chosen from the set of $n$ objects.",
    "tutorial": "It is a common fact that for a prime $p$ and integer $n$ maximum $ \\alpha $, such that $p^{ \\alpha }|n!$ is calculated as $\\alpha=\\left.\\left\\{{\\frac{n}{p}}\\right\\}+\\left[{\\frac{n}{p^{2}}}\\right\\}+\\cdot\\cdot\\cdot+\\left.\\right.\\left\\{{\\frac{n}{p^{w}}}\\right\\}$, where $p^{w}  \\le  n < p^{w + 1}$. As soon as ${\\binom{n}{k}}={\\frac{n!}{k!(n-k)!}}$, the maximum $ \\alpha $ for $\\textstyle{\\binom{n}{k}}$ is calculated as $\\alpha={\\bigg(}|{\\frac{n}{p}}|-\\biggl(|{\\frac{k}{p}}|+|{\\frac{n-k}{p}}|{\\bigg)}{\\bigg)}+{\\bigg(}[{\\frac{n}{p^{2}}}]-{\\bigg(}[{\\frac{k}{p^{2}}}]+[{\\frac{n-k}{p^{2}}}]{\\bigg)}{\\bigg)}+\\ldots+{\\bigg(}[{\\frac{k}{p^{2}}}]+\\left({\\frac{n-k}{p^{4}}}\\right){\\bigg)}$. One could see, that if we consider numbers $n$, $k$ and $n - k$ in $p$-th based numeric system, rounded-down division by $p^{x}$ means dropping last $x$ digits of its $p$-th based representation. As soon as $k + (n - k) = n$, every $i$-th summand in $ \\alpha $ corresponds to carry in adding $k$ to $n - k$ in $p$-th numeric system from $i - 1$-th to $i$-th digit position and is to be 0 or 1. First, let convert $A$ given in statement from $10$ to $p$-th numeric system. In case, if $ \\alpha $ is greater than number of digits in $A$ in $p$-th numeric system, the answer is $0$. Next we will calculate dynamic programming on $A$ $p$-th based representation. $dp[i][x][e][r]$ - the answer for prefix of length $i$ possible equal to prefix of $A$ representation (indicator $e$), $x$-th power of $p$ was already calculated, and there must be carry equal to $r$ from current to previous position. One could calculate it by bruteforcing all of $p^{2}$ variants of placing $i$-th digits in $n$ and $k$ according to $r$ and $e$ and $i$-th digit of $A$, and make a translation to next state. It can be avoided by noticing that the number of variants of placing digits is always a sum of arithmetic progression and can be calculated in $O(1)$. It's highly recommended to examine jury's solution with complexity $O(|A|^{2} + |A|min(|A|,  \\alpha ))$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 3400;\nconst int MOD = int(1e9) + 7;\n \ninline int add(int a, int b) { return (a + b >= MOD) ? (a + b - MOD) : (a + b); }\ninline int sub(int a, int b) { return (a - b < 0) ? (a - b + MOD) : (a - b); }\ninline void inc(int &a, int b) { a = add(a, b); }\ninline int mul(int a, int b) { return (a * 1ll * b) % MOD; }\n \nchar s[N];\nvector <int> a;\nint p, alpha;\nint dp[N][N][2][2];\n \nint div(const vector <int> &a, const int b, vector <int> &c) {\n    c.clear();\n    long long r = 0;\n    for (int i = 0; i < a.size(); ++i) {\n        r = r * 10ll + a[i];\n        if (c.size() || r >= b) c.push_back(r / b);\n        r %= b;\n    }\n    return r;\n}\n \ninline int calc_w(int c, int rm, int nrm) {\n    if (rm) return p - calc_w(c, !rm, nrm); \n    return c + 1 - nrm;\n}\n \ninline int calc_W(int c, int rm, int nrm) {\n    if (rm) return sub(mul(p, c + 1), calc_W(c, !rm, nrm));\n    if (c & 1) return sub(mul(c + 2, (c + 1) >> 1), nrm * (c + 1));\n    return sub(mul(c + 1, (c + 2) >> 1), nrm * (c + 1));\n}\n \nint main() {\n    assert(scanf(\"%d %d\", &p, &alpha) == 2);\n    assert(scanf(\"%s\", s) == 1);\n    a.resize(strlen(s));\n    for (int i = 0; i < a.size(); ++i) a[i] = s[i] - '0';\n    \n    vector <int> b, c;\n    while (a.size()) {\n        c.push_back(div(a, p, b));\n        a = b;\n    }\n    reverse(c.begin(), c.end());\n    if (alpha > c.size()) { puts(\"0\"); return 0; }\n \n    dp[0][0][1][0] = 1;\n    int n = c.size();\n    for (int i = 0; i < n; ++i)\n        for (int pw = 0; pw <= alpha; ++pw)\n            for (int eq = 0; eq < 2; ++eq)\n                for (int rm = 0; rm < 2; ++rm) {\n                    int &cur = dp[i][pw][eq][rm];\n                    if (cur == 0) continue;\n                    for (int nrm = 0; nrm < 2; ++nrm) {\n                        int npw = min(pw + nrm, alpha);\n                        if (!eq)\n                            inc(dp[i + 1][npw][eq][nrm], mul(calc_W(p - 1, rm, nrm), cur));\n                        else {\n                            if (c[i] != 0)\n                                inc(dp[i + 1][npw][!eq][nrm], mul(calc_W(c[i] - 1, rm, nrm), cur));\n                            inc(dp[i + 1][npw][eq][nrm], mul(calc_w(c[i], rm, nrm), cur));\n                        }\n                    }\n                }\n \n    int res = 0;\n    for (int eq = 0; eq < 2; ++eq)\n        inc(res, dp[n][alpha][eq][0]);\n    printf(\"%d\\n\", res);\n        \n    return 0;\n}",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 3300
  },
  {
    "contest_id": "582",
    "index": "E",
    "title": "Boolean Function",
    "statement": "In this problem we consider Boolean functions of four variables $A, B, C, D$. Variables $A, B, C$ and $D$ are logical and can take values 0 or 1. We will define a function using the following grammar:\n\n<expression> ::= <variable> | (<expression>) <operator> (<expression>)\n\n<variable> ::= 'A' | 'B' | 'C' | 'D' | 'a' | 'b' | 'c' | 'd'\n\n<operator> ::= '&' | '|'\n\nHere large letters $A, B, C, D$ represent variables, and small letters represent their negations. For example, if $A = 1$, then character 'A' corresponds to value 1, and value character 'a' corresponds to value 0. Here character '&' corresponds to the operation of logical AND, character '|' corresponds to the operation of logical OR.\n\nYou are given expression $s$, defining function $f$, where some operations and variables are missing. Also you know the values of the function $f(A, B, C, D)$ for some $n$ distinct sets of variable values. Count the number of ways to restore the elements that are missing in the expression so that the resulting expression corresponded to the given information about function $f$ in the given variable sets. As the value of the result can be rather large, print its remainder modulo $10^{9} + 7$.",
    "tutorial": "One could prove that the number of binary functions on 4 variables is equal to $2^{24}$, and can be coded by storing a $2^{4}$-bit binary mask, in which every bit is storing function value for corresponding variable set. It is true, that if $mask_{f}$ and $mask_{g}$ are correspond to functions $f(A, B, C, D)$ and $g(A, B, C, D)$, then function $(f&g)(A, B, C, D)$ corresponds to $mask_{f}&mask_{g}$ bitmask. Now, we could parse expression given input into binary tree. I should notice that the number of non-list nodes of such tree is about $\\frac{|s s|}{\\mathrm{G}}$. Now, let's calculate dynamic programming on every vertex $v$ - $dp[v][mask]$ is the number of ways to place symbols in expression in the way that subtree of vertex $v$ will correspond to function representing by $mask$. For list nodes such dynamic is calculated pretty straightforward by considering all possible $mask$ values and matching it with the variable. One could easily recalculate it for one node using calculated answers for left and right subtree in $4^{16}$ operations: $dp[v][lmask|rmask] + = dp[l][lmask] * dp[r][rmask]$. But all the task is how to make it faster. One could calculate $s[mask]$, where $s[mask]$ is equal to sum of all its submasks (the masks containing 1-bits only in positions where $mask$ contains 1-bits) in $2^{4} \\cdot 2^{24}$ operations using following code: for (int mask = 0; mask < (1 << 16); ++mask) s[mask] = dp[x][mask]; for (int i = 0; i < 16; ++i) for (int mask = 0; mask < (1 << 16); ++mask) if (!(mask & (1 << i))) s[mask ^ (1 << i)] += s[mask];Let's calculate $sl[mask]$ and $sr[mask]$ for $dp[l][mask]$ and $dp[r][mask]$ respectively. If we will find $s[mask] = sl[mask] * sr[mask]$, $s[mask]$ will contain multiplications of values of pairs of masks from left and right $dp$'s, which are submasks of $mask$. As soon as we need pairs, which in bitwise OR will give us exactly $mask$, we should exclude pairs, which in bitwise OR gives a submask of $mask$, not equal to $mask$. This gives us exclusion-inclusion principle idea. The formula of this will be $s[m a s k]=\\sum_{s m a s k}(-1)^{p}s l[s m a s k]\\cdot s r[s m a s k]\\cdot s r[s m a s k]$, where $p$ is the parity of number of bits in $mask^submask$. Such sum could be calculated with approach above, but subtracting instead of adding for (int mask = 0; mask < (1 << 16); ++mask) s[mask] = sl[mask] * sr[mask]; for (int i = 0; i < 16; ++i) for (int mask = 0; mask < (1 << 16); ++mask) if (!(mask & (1 << i))) s[mask ^ (1 << i)] -= s[mask];In such way we will recalculate dynamic for one vertex in about $3 \\cdot 2^{4} \\cdot 2^{16}$ operations.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = int(1e9) + 7;\n \ninline int add(int a, int b) { return (a + b >= MOD) ? (a + b - MOD) : (a + b); }\ninline void inc(int &a, int b) { a = add(a, b); }\ninline int sub(int a, int b) { return (a - b < 0) ? (a - b + MOD) : (a - b); }\ninline void dec(int &a, int b) { a = sub(a, b); }\ninline int mul(int a, int b) { return (a * 1ll * b) % MOD; }\n \nconst int N = 200 + 5;\nconst int V = 4;\nconst int S = (1 << V);\nconst int M = (1 << S);\nchar s[N * 6];\n \nint n, d[N][M];\n \nconst string vars = \"ABCDabcd\";\nconst string ops = \"&|\";\n \nint maskone(int v) {\n    int mask = 0;\n    for (int i = 0; i < S; ++i)\n        if ((i >> v) & 1)\n            mask |= (1 << i);\n    return mask;\n}\n \n#define negate ____negate\nvoid negate(int *a) {\n    reverse(a, a + M);\n}\n \nvoid copy(const int *a, int *b) {\n    for (int i = 0; i < M; ++i) b[i] = a[i];\n}\n \nvoid add(const int *a, int *b) {\n    for (int i = 0; i < M; ++i) inc(b[i], a[i]);\n}\n \nvoid sumsub(const int *a, int *b, int d) {\n    copy(a, b);\n    for (int i = 0; i < S; ++i)\n        for (int mask = 0; mask < M; ++mask)\n            if (!(mask & (1 << i))) {\n                if (d == +1) inc(b[mask ^ (1 << i)], b[mask]);\n                else if (d == -1) dec(b[mask ^ (1 << i)], b[mask]);\n                else throw;\n            }\n}\n \nint t1[M], t2[M], tops[2][M];\nvoid door(const int *l, const int *r, int *v) {\n    sumsub(l, t1, +1);\n    sumsub(r, t2, + 1);\n    for (int i = 0; i < M; ++i) t1[i] = mul(t1[i], t2[i]);\n    sumsub(t1, v, -1);\n}\n \nint parse(int &pos) {\n    if (s[pos] != '(') {    \n        int v = vars.find(s[pos++]);\n        if (v == -1) {\n            for (int i = 0; i < V; ++i) {\n                d[n][maskone(i)] = 1;\n                d[n][(M - 1) ^ maskone(i)] = 1;\n            }\n        } else {\n            if (v < V)\n                d[n][maskone(v)] = 1;\n            else\n                d[n][(M - 1) ^ maskone(v - V)] = 1;\n        }\n        return n++;\n    }\n    int me = n++;\n    int l = parse(++pos);\n    assert(s[pos++] == ')');\n    int v = ops.find(s[pos++]);\n    int r = parse(++pos);\n    assert(s[pos++] == ')');\n    \n    door(d[l], d[r], tops[1]); // tops[1] = (l | r)\n    \n    negate(d[l]); // d[l] = ~l\n    negate(d[r]); // d[r] = ~r\n    door(d[l], d[r], tops[0]); // tops[0] = (~l | ~r)\n    negate(tops[0]); // tops[0] = ~(~l | ~r) = (l & r)\n    negate(d[r]); // d[r] = r\n    negate(d[l]); // d[l] = l\n    \n    if (v == -1)\n        for (int i = 0; i < ops.size(); ++i)\n            add(tops[i], d[me]);\n    else\n        add(tops[v], d[me]);\n    return me;\n}\n \nint req[1 << V];\n \nint main() {\n    scanf(\"%s\", s);\n    int pos = 0;\n    int root = parse(pos);\n    scanf(\"%d\", &n);\n    for (int i = 0; i < S; ++i) req[i] = -1;\n    for (int i = 0; i < n; ++i) {\n        int mask = 0;\n        for (int j = 0; j < V; ++j) {\n            int a;\n            scanf(\"%d\", &a);\n            mask |= (a << j);\n        }\n        scanf(\"%d\", &req[mask]);\n    }\n    int res = 0;\n    for (int i = 0; i < M; ++i) {\n        bool good = true;\n        for (int j = 0; j < S; ++j)\n            good &= (req[j] == -1 || req[j] == ((i >> j) & 1));\n        if (good) inc(res, d[root][i]);\n    }\n    printf(\"%d\\n\", res);\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "expression parsing"
    ],
    "rating": 3000
  },
  {
    "contest_id": "583",
    "index": "A",
    "title": "Asphalting Roads",
    "statement": "City X consists of $n$ vertical and $n$ horizontal infinite roads, forming $n × n$ intersections. Roads (both vertical and horizontal) are numbered from $1$ to $n$, and the intersections are indicated by the numbers of the roads that form them.\n\nSand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.\n\nRoad repairs are planned for $n^{2}$ days. On the $i$-th day of the team arrives at the $i$-th intersection in the list and if \\textbf{none} of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.\n\nAccording to the schedule of road works tell in which days at least one road will be asphalted.",
    "tutorial": "To solve the problem one could just store two arrays $hused[j]$ and $vused[j]$ sized $n$ and filled with false initially. Then process intersections one by one from $1$ to $n$, and if for $i$-th intersections both $hused[h_{i}]$ and $vused[v_{i}]$ are false, add $i$ to answer and set both $hused[h_{i}]$ and $vused[v_{i}]$ with true meaning that $h_{i}$-th horizontal and $v_{i}$-th vertical roads are now asphalted, and skip asphalting the intersection roads otherwise. Such solution has $O(n^{2})$ complexity.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 100;\nbool u[2][N];\nint n;\n \nint main() {\n    cin >> n;\n    for (int i = 0; i < n * n; ++i) {\n        int h, v;\n        cin >> h >> v;\n        --h, --v;\n        if (!u[0][h] && !u[1][v]) {\n            u[0][h] = true;\n            u[1][v] = true;\n            cout << i + 1 << \" \";\n        }\n    }\n    puts(\"\");\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "583",
    "index": "B",
    "title": "Robot's Task",
    "statement": "Robot Doc is located in the hall, with $n$ computers stand in a line, numbered from left to right from $1$ to $n$. Each computer contains \\textbf{exactly one} piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the $i$-th of them, the robot needs to collect at least $a_{i}$ any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.\n\nThe robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all $n$ parts of information if initially it is next to computer with number $1$.\n\n\\textbf{It is guaranteed} that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.",
    "tutorial": "It is always optimal to pass all the computers in the row, starting from $1$-st to $n$-th, then from $n$-th to first, then again from first to $n$-th, etc. and collecting the information parts as possible, while not all of them are collected. Such way gives robot maximal use of every direction change. $O(n^{2})$ solution using this approach must have been passed system tests.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 5000;\nint n, a[N];\n \nint main() {\n    cin >> n;\n    for (int i = 0; i < n; ++i) cin >> a[i];\n    int s = 0, res = 0;\n    while (true) {\n        for (int i = 0; i < n; ++i)\n            if (a[i] <= s) a[i] = n + 1, s++;\n        if (s == n) break;\n        res++;\n        for (int i = n - 1; i >= 0; --i)\n            if (a[i] <= s) a[i] = n + 1, s++;\n        if (s == n) break;\n        res++;\n    }\n    cout << res << endl;\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "584",
    "index": "A",
    "title": "Olesya and Rodion",
    "statement": "Olesya loves numbers consisting of $n$ digits, and Rodion only likes numbers that are divisible by $t$. Find some number that satisfies both of them.\n\nYour task is: given the $n$ and $t$ print an integer strictly larger than zero consisting of $n$ digits that is divisible by $t$. If such number doesn't exist, print $ - 1$.",
    "tutorial": "Two cases: $t = 10$ and $t  \\neq  10$. If $t = 10$ then there are two cases again :). If $n = 1$ then answer is $- 1$ (because there is not any digit divisible by $t$). If $n > 1$, then answer, for example, is '1111...110' (contains $n - 1$ ones). If $t < 10$ then answer, for example, is 'tttttttt' (it, obviously, divisible by $t$).",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "584",
    "index": "B",
    "title": "Kolya and Tanya ",
    "statement": "Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.\n\nMore formally, there are $3n$ gnomes sitting in a circle. Each gnome can have from $1$ to $3$ coins. Let's number the places in the order they occur in the circle by numbers from $0$ to $3n - 1$, let the gnome sitting on the $i$-th place have $a_{i}$ coins. If there is an integer $i$ ($0 ≤ i < n$) such that $a_{i} + a_{i + n} + a_{i + 2n} ≠ 6$, then Tanya is satisfied.\n\nCount the number of ways to choose $a_{i}$ so that Tanya is satisfied. As there can be many ways of distributing coins, print the remainder of this number modulo $10^{9} + 7$. Two ways, $a$ and $b$, are considered distinct if there is index $i$ ($0 ≤ i < 3n$), such that $a_{i} ≠ b_{i}$ (that is, some gnome got different number of coins in these two ways).",
    "tutorial": "The number of ways to choose $a_{i}$ (without any conditions) - $3^{3n}$. Let $A$ be the number of ways to choose $a_{i}$ with condition that in every triangle gnomes have $6$ coins. Then answer is $3^{3n} - A$. Note that we can separate all gnomes on n independent triangles ($i$-th triangle contains of $a_{i}$, $a_{i + n}$, $a_{i + 2n}$, $i < n$). So we can count answer for one triangle and then multiply the results. To count answer for one triangle, we can note that there are $7$ ways to choose gnomes with $6$ coins (all permutations $1$, $2$, $3$ and $2$, $2$, $2$). So answer is - $3^{3n} - 7^{n}$. We count it in $O(n)$.",
    "tags": [
      "combinatorics"
    ],
    "rating": 1500
  },
  {
    "contest_id": "584",
    "index": "C",
    "title": "Marina and Vasya",
    "statement": "Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly $t$ characters. Help Vasya find at least one such string.\n\nMore formally, you are given two strings $s_{1}$, $s_{2}$ of length $n$ and number $t$. Let's denote as $f(a, b)$ the number of characters in which strings $a$ and $b$ are different. Then your task will be to find any string $s_{3}$ of length $n$, such that $f(s_{1}, s_{3}) = f(s_{2}, s_{3}) = t$. If there is no such string, print $ - 1$.",
    "tutorial": "Let's find a string that will be equal to $s1$ in $k = n - t$ positions and equal to $s2$ in $k = n - t$ positions. Let's denote $q$ = quantity of $i$ that $s1_{i} = s2_{i}$. If $k  \\le  q$, then let's take $k$ positions such that $s1_{pos} = s2_{pos}$ and put in answer the same symbols. Then put in other $n - k$ positions symbols, which are not equal to corresponding in $s1$ and $s2$ (we can do it, because we have 26 letters). Now $k > q$. So, if there is an answer, where exists $pos$ such that $s1_{pos} = s2_{pos}$, $s1_{pos}  \\neq  ans_{pos}$, let's denote $ans_{i} = s1_{i}$, and then in any position such that $s1_{i}  \\neq  s2_{i} = ans_{i}$ and $s1_{i} = ans_{i}$ (and in the same position in $s2$) we will choose $a_{i}$, such that $a_{i}  \\neq  s1_{i}$ and $a_{i}  \\neq  s2_{i}$ (we can do it because $k > q$). So, for every position from $q$ we can put symbols, equal to corresponding symbols in $s1$ and $s2$. Now we have strings $s1, s2$ of length $n - q$ (such that $s1_{i}  \\neq  s2_{i}$ for every i) and we should find string $ans$ such that $f(ans, s1) = f(ans, s2)$. We know that $s1_{i}  \\neq  s2_{i}$, so $ans_{i}$ may be equal to corresponding in $s1$ or to corresponding in $s2$ or not equal to $s1_{i}$ and to $s2_{i}$. So, we need, at least, $2(k - q)$ symbols in answer to make $f(s1, ans) = k - q$ and $f(s2, ans) = k - q$. Consequently, if $n - q < 2(k - q)$, the answer is $- 1$, and else just put first $k - q$ symbols in answer from $s1$, next $k - q$ symbols from $s2$, and others won't be equal to corresponding in $s1$ and $s2$. Solution works in $O(n)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "584",
    "index": "D",
    "title": "Dima and Lisa",
    "statement": "Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.\n\nMore formally, you are given an \\textbf{odd} numer $n$. Find a set of numbers $p_{i}$ ($1 ≤ i ≤ k$), such that\n\n- $1 ≤ k ≤ 3$\n- $p_{i}$ is a prime\n- $\\sum_{i=1}^{k}p_{i}=n$\n\nThe numbers $p_{i}$ do not necessarily have to be distinct. It is guaranteed that at least one possible solution exists.",
    "tutorial": "There is a fact that the distance between adjacent prime numbers isn't big. For $n = 10^{9}$ maximal distanse is $282$. So let's find maximal prime $p$, such that $p < n - 1$ (we can just decrease n while it's not prime(we can check it in $O({\\sqrt{n}})$)). We know that $n - p < 300$. Now we have even (because $n$ and $p$ are odd) number $n - p$ and we should divide it into a sum of two primes. As $n - p < 300$, we can just iterate over small primes $P$ and check if $P$ is prime and $n - p - P$ is prime. You can check that there is a solution for all even numbers less than $300$ by bruteforce.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "584",
    "index": "E",
    "title": "Anton and Ira",
    "statement": "Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.\n\nMore formally, we have two permutations, $p$ and $s$ of numbers from $1$ to $n$. We can swap $p_{i}$ and $p_{j}$, by paying $|i - j|$ coins for it. Find and print the smallest number of coins required to obtain permutation $s$ from permutation $p$. Also print the sequence of swap operations at which we obtain a solution.",
    "tutorial": "We can consider that we pay $2|i - j|$ coins for swap (we can divide answer in the end). Then we can consider that we pay $|i - j|$ coins for moving $p_{i}$ and $|i - j|$ for moving $p_{j}$. So, if $x$ was on position $i$ and then came to position $j$, then we will pay at least $|i - j|$ coins. Then the answer is at least $\\sum_{k=1}^{n}|p p[k]-p s[k]|$ ($pp$ - position $k$ in permutation $p$, and $ps$ - position $k$ in permutation $s$). Let's prove that this is the answer by showing the algorithm of making swaps. Let's consider that permutation $s$ is sorted (our task is equal to it). Then we will put numbers from $n$ to $1$ on their positions. How we can put $n$ on its position? Denote $p_{pos} = n$. Let's prove that there exists a position $pos2$ such that $pos < pos2$ and $p_{pos2}  \\le  pos$(then we will swap $p_{pos2}$ with $n$ (and both numbers will move to their final positions and $n$ will move to the right, so we can repeat this process until $n$ returns to its position)). We can note that there are only $n - pos$ positions that are bigger than $pos$. And how many numbers on these positions can be bigger than $pos$? We can say that answer is $n - pos$, but it's incorrect, because $n$ is bigger than $pos$, but $pos_{n}  \\le  pos$. Now we can use Pigeonhole principle and say that position $x$, such that $x > pos$ and $p_{x}  \\le  pos$ exists. But now our algorithm is $O(n^{3})$. How we can put $n$ in its position in $O(n)$ operations? Let's move the pointer to the right while number is bigger than $pos$. Then swap $n$ with found number. After we can move pointer from new $n$'s position, so pointer always moves to the right and will not do more then $n$ steps.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "585",
    "index": "A",
    "title": "Gennady the Dentist",
    "statement": "Gennady is one of the best child dentists in Berland. Today $n$ children got an appointment with him, they lined up in front of his office.\n\nAll children love to cry loudly at the reception at the dentist. We enumerate the children with integers from $1$ to $n$ in the order they go in the line. Every child is associated with the value of his cofidence $p_{i}$. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.\n\nWhile Gennady treats the teeth of the $i$-th child, the child is crying with the volume of $v_{i}$. At that the confidence of the first child in the line is reduced by the amount of $v_{i}$, the second one — by value $v_{i} - 1$, and so on. The children in the queue after the $v_{i}$-th child almost do not hear the crying, so their confidence remains unchanged.\n\nIf at any point in time the confidence of the $j$-th child is less than zero, he begins to cry with the volume of $d_{j}$ and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the $j$-th one in the line is reduced by the amount of $d_{j}$.\n\nAll these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.\n\nHelp Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.",
    "tutorial": "Let's store for each child his current confidence value and a boolean indicating whether child had left the queue (or visited the dentist office) or not. Then one could easily process children one by one, considering only children who still are in the queue (using boolean array), and changing stored values. Such solution has complexity $O(n^{2})$ and requires author's attention much, especially the case with possible confidence value overflowing. Of course there are much faster solutions not required in our case.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "585",
    "index": "B",
    "title": "Phillip and Trains",
    "statement": "The mobile application store has a new game called \"Subway Roller\".\n\nThe protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and $n$ columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.\n\nAll trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.\n\nYour task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.",
    "tutorial": "One could consider a graph with vertices corresponding to every $(x, y)$ position. I should notice that train positions for each Phillip position are fully restorable from his $y$ coordinate. Edge between vertices $u$ and $v$ means that we could get from position corresponding to $u$ to position corresponding by $v$ in one turn without moving onto a train cell or moving in a cell which will be occupied by some train before the next turn. All we need next is to find whether any finishing position is reachable from the only starting position (using BFS or DFS, or, as soon as graph is a DAG, dynamic programming). As soon as graph has $O(n)$ vertices and $O(n)$ edges, solution complexity equals to $O(n)$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "585",
    "index": "C",
    "title": "Alice, Bob, Oranges and Apples",
    "statement": "Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a letter, either 'A', or the letter 'B'. Then they began to remove the cards one by one from left to right, every time they removed a card with the letter 'A', Alice gave Bob all the fruits she had at that moment and took out of the bag as many apples and as many oranges as she had before. Thus the number of oranges and apples Alice had, did not change. If the card had written letter 'B', then Bob did the same, that is, he gave Alice all the fruit that he had, and took from the bag the same set of fruit. After the last card way removed, all the fruit in the bag were over.\n\nYou know how many oranges and apples was in the bag at first. Your task is to find any sequence of cards that Alice and Bob could have played with.",
    "tutorial": "Firstly, let's understand the process described in problem statement. If one would write a tree of a sum-pairs $(x, y)$ with letters $\\mathrm{\\boldmath~A~}$ and $\\mathbf{\\hat{B}}$, he would get the Stern-Brocot tree. Let the number of oranges be enumerator and the number of apples be denumerator of fraction. At every step we have two fractions (at first step they are $\\textstyle{\\frac{0}{10}}$) and should replace exactly one of them with their mediant. In such way first fraction is first parent to the left from mediant while second fraction is parent to the right. The process described in statement is, this way, a process of finding a fraction in the Stern-Brocot tree, finishing when the current mediant is equal to current node in the tree and $(x, y)$ pair is the fraction we are searching. This means that if $\\operatorname*{gcd}(x,y)\\neq1$, $(x, y)$ does not correspond to any correct fraction and the answer is \"Impossible\". Other way, we could find it in the tree. If $x > y$, we should firstly go in the right subtree. Moreover, we could then consider we are searching $\\textstyle{\\frac{a-y}{y}}$ from the root. If $x < y$, we should go left and next consider $\\frac{\\overline{{x}}}{y\\!\\!\\!{y\\!\\!\\!{y}}\\!\\!\\!\\slash-x}$ from the root. This gives us Euclidian algorithm, which could be realized to work in $O(\\log n)$ complexity. Complexity: $O(logn)$.",
    "tags": [
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "585",
    "index": "D",
    "title": "Lizard Era: Beginning",
    "statement": "In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has $n$ mandatory quests. To perform each of them, you need to take \\textbf{exactly two} companions.\n\nThe attitude of each of the companions to the hero is an integer. Initially, the attitude of each of them to the hero of neutral and equal to 0. As the hero completes quests, he makes actions that change the attitude of the companions, whom he took to perform this task, in positive or negative direction.\n\nTell us what companions the hero needs to choose to make their attitude equal after completing all the quests. If this can be done in several ways, choose the one in which the value of resulting attitude is greatest possible.",
    "tutorial": "To solve the problem we will use meet-in-the-middle approach. For $\\textstyle{\\left|{\\frac{n}{2}}\\right|}$ we should consider all $3^{\\left[{\\frac{n}{2}}\\right]}$ variants. Let in some variant approval values of three companions are $a, b, c$ respectively. If we will consider some variant from other half (there are $3^{\\left\\lceil{\\frac{n}{2}}\\right\\rceil}$ of them) and $a', b', c'$ approval values, then to ``merge'' such two parts correctly, two conditions $a - b = b' - a'$ and $b - c = c' - b'$ must be true ($a + a' = b + b' = c + c'$ is true), and the value we are maximizing is $a + a'$. This way, to solve the task one could consider every variant from the first half and store for every possible pair $(a - b, b - c)$ the maximum $a$ value achievable (using, for example, the $\\mathrm{map}$ structure or any fast sorting algorithm). If one would then consider every variant from the second half, he just need to find $(b' - a', c' - b')$ pair in the structure to get the maximum $a$ value if possible and update answer with $a + a'$ value. Answer restoring is pretty same to the algorithm above. Such solution has $O(3^{\\lfloor{\\frac{n}{2}}\\rfloor}\\log(3^{\\lfloor{\\frac{n}{2}}\\rfloor})$ complexity.",
    "tags": [
      "meet-in-the-middle"
    ],
    "rating": 2300
  },
  {
    "contest_id": "585",
    "index": "E",
    "title": "Present for Vitalik the Philatelist ",
    "statement": "Vitalik the philatelist has a birthday today!\n\nAs he is a regular customer in a stamp store called 'Robin Bobin', the store management decided to make him a gift.\n\nVitalik wants to buy one stamp and the store will give him a non-empty set of the remaining stamps, such that the greatest common divisor (GCD) of the price of the stamps they give to him is more than one. If the GCD of prices of the purchased stamp and prices of present stamps set will be equal to $1$, then Vitalik will leave the store completely happy.\n\nThe store management asks you to count the number of different situations in which Vitalik will leave the store completely happy. Since the required number of situations can be very large, you need to find the remainder of this number modulo $10^{9} + 7$. The situations are different if the stamps purchased by Vitalik are different, or if one of the present sets contains a stamp that the other present does not contain.",
    "tutorial": "Let's calculate the number of subsets with gcd equal to $1$ - value A. Let's do that using principle of inclusions-exclusions: firstly we say that all subsets is good. The total number of subsets is equal to $2^{n}$. Now let's subtract subsets with gcd divisible by $2$. The number of that subsets is equal to $2^{cnt2} - 1$ ($cnt_{i}$ is the number of numbers that is divisable by $i$). Next we should subtract $2^{cnt3} - 1$. Subsets with gcd divisible by $4$ we already counted with number two. Next we should subtract $2^{cnt5} - 1$. Now we should notice that subsets with gcd divisible by $6$ we already processed twice: firstly with number $2$, then with - $3$, so let's add the number of these subsets $2^{cnt6} - 1$. If we continue this process we will get, that for all numbers $d$ we should add the value $ \\mu (d)(2^{cntd} - 1)$, where $ \\mu (d)$ is equals to $0$, if $d$ is divisible by square of some prime, $1$, if the number of primes in factorization of $d$ is even and $- 1$ in other case. So the numbers that is divisible by square of some prime we can ignore, because they have coefficient $0$. To calculate values $cnt_{i}$ we should factorize all numbers and iterate over $2^{k}$ divisors with value $ \\mu (d)  \\neq  0$. Now it's easy to see, that the number of subsets with gcd greater than $1$ equals to $B = 2^{n} - A$. To solve the problem let's fix the stamp that Vitaliy will buy $a_{i}$. Let's recalculate the number $B$ for array a without element $a_{i}$. To do that we should only subtract those terms that was affected by number $a_{i}$. We can do that in $2^{k}$, where $k$ is the number of primes in factorization of the number $a_{i}$. It's easy to see that only the subsets with gcd greater than $1$, but not divisible by any divisor of $a_{i}$, should we counted in answer. To calculate number of those subsets let's again use the principle of inclusions-exclusions. For every divisor $d$ of $a_{i}$ let's subtract the value $ \\mu  (2^{cntd} - 1)$ from $B$. So now we got $B_{i}$ - the number of subsets with gcd greater than $1$, but coprime with $a_{i}$. The answer to problem is the sum over all $B_{i}$. The maximum number of primes in factorization of number not greater than $10^{7}$ is equal to $8$. We can factorize all numbers from $1$ to $n$ in linear time by algorithm for finding the smallest divisors for all intergers from $1$ to $n$, or by sieve of Eratosthenes in $O(nloglogn)$ time. Complexity: $O(C + n2^{K})$, where $C=\\mathbf{m}_{i\\geq1}^{n}\\,a_{i}$, $K$ - is the largest number of primes in factorization of $a_{i}$.",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "585",
    "index": "F",
    "title": "Digits of Number Pi",
    "statement": "Vasily has recently learned about the amazing properties of number $π$. In one of the articles it has been hypothesized that, whatever the sequence of numbers we have, in some position, this sequence is found among the digits of number $π$. Thus, if you take, for example, the epic novel \"War and Peace\" of famous Russian author Leo Tolstoy, and encode it with numbers, then we will find the novel among the characters of number $π$.\n\nVasily was absolutely delighted with this, because it means that all the books, songs and programs have already been written and encoded in the digits of $π$. Vasily is, of course, a bit wary that this is only a hypothesis and it hasn't been proved, so he decided to check it out.\n\nTo do this, Vasily downloaded from the Internet the archive with the sequence of digits of number $π$, starting with a certain position, and began to check the different strings of digits on the presence in the downloaded archive. Vasily quickly found short strings of digits, but each time he took a longer string, it turned out that it is not in the archive. Vasily came up with a definition that a string of length $d$ is a half-occurrence if it contains a substring of length of at least $\\left\\lfloor{\\frac{d}{2}}\\right\\rfloor$, which occurs in the archive.\n\nTo complete the investigation, Vasily took $2$ large numbers $x, y$ ($x ≤ y$) with the same number of digits and now he wants to find the number of numbers in the interval from $x$ to $y$, which are half-occurrences in the archive. Help Vasily calculate this value modulo $10^{9} + 7$.",
    "tutorial": "Consider all substrings of string $s$ with length $\\left\\lfloor{\\frac{d}{2}}\\right\\rfloor$. Let's add them all to trie data structure, calculate failure links and build automata by digits. We can do that in linear time using Aho-Korasik algorithm. Now to solve the problem we should calculate dp $z_{i, v, b1, b2, b}$. State of dp is described by five numbers: $i$ - number of digits, that we already put to our number, $v$ - in which vertex of trie we are, $b_{1}$ - equals to one if the prefix that we built is equals to prefix of $x$, $b_{2}$ - equals to one if the prefix that we built is equals to prefix of $y$, $b$ - equals to one if we already have some substring with length $\\left\\lfloor{\\frac{d}{2}}\\right\\rfloor$ on the prexif that we built. The value of dp is the number of ways to built prefix with the given set of properties. To update dp we should iterate over the digit that we want to add to prefix, check that we still is in segment $[x, y]$, go from vertex $v$ to the next vertex in automata. So the answer is the sum by all $v, b_{1}, b_{2}$ $z_{b, v, v1, v2, 1}$. Complexity: $O(nd^{2})$.",
    "tags": [
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "586",
    "index": "A",
    "title": "Alena's Schedule",
    "statement": "Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.\n\nOne two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).\n\nThe University works in such a way that every day it holds exactly $n$ lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).\n\nThe official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the $n$ pairs she knows if there will be a class at that time or not.\n\nAlena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.\n\nOf course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.\n\nAlena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.",
    "tutorial": "To solve this problem one should remove all leading and trailing zeroes from array and then calculate the number of ones and number of zeroes neighboured by ones. The sum of this values is the answer for the problem. Complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "586",
    "index": "B",
    "title": "Laurenty and Shop",
    "statement": "A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.\n\nThe town where Laurenty lives in is not large. The houses in it are located in two rows, $n$ houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.\n\nThe first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.\n\nEach crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.\n\nThe traffic light on the crosswalk from the $j$-th house of the $i$-th row to the $(j + 1)$-th house of the same row has waiting time equal to $a_{ij}$ ($1 ≤ i ≤ 2, 1 ≤ j ≤ n - 1$). For the traffic light on the crossing from the $j$-th house of one row to the $j$-th house of another row the waiting time equals $b_{j}$ ($1 ≤ j ≤ n$). The city doesn't have any other crossings.\n\nThe boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it \\textbf{exactly once} on the way to the store and \\textbf{exactly once} on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing.\n\n\\begin{center}\n{\\small Figure to the first sample.}\n\\end{center}\n\nHelp Laurenty determine the minimum total time he needs to wait at the crossroads.",
    "tutorial": "Let's call some path $i$th if we start it by going $i$ times left, then we cross the prospect and go left $n - 1 - i$ times again. Let $d_{i}$ be equal to the time we should wait on traffic lights while following $i$-th path. If we consider any way from the shop to home, it is equal (but reversed) to only path from home to the shop, meaning that we need to find two distinct paths from home to the shop. So the answer to the problem is the sum of the smallest and the second smallest values among $d_{i}$. One could easily calculate $d_{i}$ using calculated $d_{i - 1}$, so $d_{i}$ could be found in one for cycle. If we will consider only two minimum values among $d_{i}$, solution complexity will be $O(n)$. Complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "587",
    "index": "A",
    "title": "Duff and Weight Lifting",
    "statement": "Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of $i$-th of them is $2^{wi}$ pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps.\n\nDuff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights $2^{a1}, ..., 2^{ak}$ if and only if there exists a non-negative integer $x$ such that $2^{a1} + 2^{a2} + ... + 2^{ak} = 2^{x}$, i. e. the sum of those numbers is a power of two.\n\nDuff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps.",
    "tutorial": "Problem is: you have to find the minimum number of $k$, such there is a sequence $a_{1}, a_{2}, ..., a_{k}$ with condition $2^{a1} + 2^{a2} + ... + 2^{ak} = S = 2^{w1} + 2^{w2} + ... + 2^{w2}$. Obviously, minimum value of $k$ is the number of set bits in binary representation of $S$ (proof is easy, you can prove it as a practice :P). Our only problem is how to count the number of set bits in binary representation of $S$? Building the binary representation of $S$ as an array in $O(n+m a x(a_{i}))$ is easy: MAXN = 1000000 + log(1000000) bit[0..MAXN] = {} // all equal to zero ans = 0 for i = 1 to n bit[w[i]] ++ // of course after this, some bits maybe greater than 1, we'll fix them below for i = 0 to MAXN - 1 bit[i + 1] += bit[i]/2 // floor(bit[i]/2) bit[i] %= 2 // bit[i] = bit[i] modulo 2 ans += bit[i] // if bit[i] = 0, then answer doesn't change, otherwise it'll increase by 1Time complexity: $O(n+m a x(a_{i}))$",
    "code": "\"#include <bits/stdc++.h>\\n#include <ext/pb_ds/assoc_container.hpp>\\n#include <ext/pb_ds/tree_policy.hpp>\\nusing namespace __gnu_pbds;\\nusing namespace std;\\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\\n#define rep(i, c) for(auto &(i) : (c))\\n#define x first\\n#define y second\\n#define pb push_back\\n#define PB pop_back()\\n#define iOS ios_base::sync_with_stdio(false)\\n#define sqr(a) (((a) * (a)))\\n#define all(a) a.begin() , a.end()\\n#define error(x) cerr << #x << \\\" = \\\" << (x) <<endl\\n#define Error(a,b) cerr<<\\\"( \\\"<<#a<<\\\" , \\\"<<#b<<\\\" ) = ( \\\"<<(a)<<\\\" , \\\"<<(b)<<\\\" )\\\\n\\\";\\n#define errop(a) cerr<<#a<<\\\" = ( \\\"<<((a).x)<<\\\" , \\\"<<((a).y)<<\\\" )\\\\n\\\";\\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\\n#define L(x) ((x)<<1)\\n#define R(x) (((x)<<1)+1)\\n#define umap unordered_map\\n#define double long double\\ntypedef long long ll;\\ntypedef pair<int,int>pii;\\ntypedef vector<int> vi;\\ntypedef complex<double> point;\\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\\nconst int maxn = 2e6 + 100;\\nint a, cnt[maxn + 10], n;\\nint main(){\\n\\tscanf(\\\"%d\\\", &n);\\n\\tFor(i,0,n){\\n\\t\\tscanf(\\\"%d\\\", &a);\\n\\t\\tcnt[a] ++;\\n\\t}\\n\\tint ans = 0;\\n\\tFor(i,0,maxn)if(cnt[i]){\\n\\t\\tcnt[i + 1] += cnt[i]/2;\\n\\t\\tcnt[i] %= 2;\\n\\t\\tif(cnt[i])\\n\\t\\t\\t++ ans;\\n\\t}\\n\\tprintf(\\\"%d\\\\n\\\", ans);\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "587",
    "index": "B",
    "title": "Duff in Beach",
    "statement": "While Duff was resting in the beach, she accidentally found a strange array $b_{0}, b_{1}, ..., b_{l - 1}$ consisting of $l$ positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, $a_{0}, ..., a_{n - 1}$ that $b$ can be build from $a$ with formula: $b_{i} = a_{i mod n}$ where $a mod b$ denoted the remainder of dividing $a$ by $b$.\n\nDuff is so curious, she wants to know the number of subsequences of $b$ like $b_{i1}, b_{i2}, ..., b_{ix}$ ($0 ≤ i_{1} < i_{2} < ... < i_{x} < l$), such that:\n\n- $1 ≤ x ≤ k$\n- For each $1 ≤ j ≤ x - 1$, $\\lfloor{\\frac{\\iota_{2}}{n}}\\rfloor+1=\\lfloor{\\frac{\\iota_{3+1}}{n}}\\rfloor$\n- For each $1 ≤ j ≤ x - 1$, $b_{ij} ≤ b_{ij + 1}$. i.e this subsequence is non-decreasing.\n\nSince this number can be very large, she want to know it modulo $10^{9} + 7$.\n\nDuff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.",
    "tutorial": "If we fix $x$ and $b_{ix} mod n$, then problem will be solved (because we can then multiply it by the number of valid distinct values of $\\textstyle{\\left|{\\frac{L}{n}}\\right|}$). For the problem above, let $dp[i][j]$ be the number of valid subsequences of $b$ where $x = j$ and $\\lfloor{\\frac{i}{n}}\\rfloor=0$ and $\\vert{\\frac{i}{n}}\\vert=i$. Of course, for every $i$, $dp[i][1] = 1$. For calculating value of $dp[i][j]$: $d p[i][j]=\\sum_{0<k<n-1.a_{i}<a_{i}}d p[k][j-1]$ For this purpose, we can sort the array $a$ and use two pointer: if $p_{0}, p_{1}, ...p_{n - 1}$ is a permutation of $0, ..., n - 1$ where for each $0  \\le  t < n - 1$, $a_{pt}  \\le  a_{pt + 1}$: for i = 0 to n-1 dp[i][1] = 1 for j = 2 to k pointer = 0 sum = 0 for i = 0 to n-1 while pointer < n and a[p[pointer]] <= a[i] sum = (sum + dp[p[pointer ++]][j - 1]) % MOD dp[i][j] = sum Now, if $c=\\left.{\\left[{\\frac{l}{n}}\\right]}$ and $x = l - 1 mod n$, then answer equals to $\\sum_{i=0}^{x}\\sum_{j=1}^{m i n(c,k)}d p[i][j]\\times(c-j+1)\\sum_{i=x+1}^{n-1\\ m i n(c-1,k)}d p[i][j]\\times(c-j)$ (there are $c - j + 1$ valid different values of $\\textstyle{\\left|{\\frac{L}{n}}\\right|}$ for the first group and $c - j$ for the second group). Time complexity: $O(n k)$",
    "code": "\"#include <bits/stdc++.h>\\n#include <ext/pb_ds/assoc_container.hpp>\\n#include <ext/pb_ds/tree_policy.hpp>\\nusing namespace __gnu_pbds;\\nusing namespace std;\\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\\n#define rep(i, c) for(auto &(i) : (c))\\n#define x first\\n#define y second\\n#define pb push_back\\n#define PB pop_back()\\n#define iOS ios_base::sync_with_stdio(false)\\n#define sqr(a) (((a) * (a)))\\n#define all(a) a.begin() , a.end()\\n#define error(x) cerr << #x << \\\" = \\\" << (x) <<endl\\n#define Error(a,b) cerr<<\\\"( \\\"<<#a<<\\\" , \\\"<<#b<<\\\" ) = ( \\\"<<(a)<<\\\" , \\\"<<(b)<<\\\" )\\\\n\\\";\\n#define errop(a) cerr<<#a<<\\\" = ( \\\"<<((a).x)<<\\\" , \\\"<<((a).y)<<\\\" )\\\\n\\\";\\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\\n#define L(x) ((x)<<1)\\n#define R(x) (((x)<<1)+1)\\n#define umap unordered_map\\n#define double long double\\ntypedef long long ll;\\ntypedef pair<int,int>pii;\\ntypedef vector<int> vi;\\ntypedef complex<double> point;\\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\\nconst int maxn = 1e6 + 100, mod = 1e9 + 7;\\nint a[maxn], dp[maxn][2], p[maxn];\\nll l, c;\\nint n, k;\\nll ans;\\nint last;\\ninline void calc(int i, int j){\\n\\tll t = (c - j + 1LL) % mod;\\n\\tif(i > last && l % (ll)n)\\n\\t\\tt = (t - 1LL + mod) % mod;\\n\\tll x = (1LL * t * (ll)dp[i][j & 1]) % mod;\\n\\tans = (ans + x) % mod;\\n}\\nint main(){\\n\\tscanf(\\\"%d %lld %d\\\", &n, &l, &k);\\n\\tc = l / (ll)n;\\n\\tlast = ((ll)(l - 1LL) % (ll)n);\\n\\tif(l % n)\\n\\t\\t++ c;\\n\\tk = (int)min((ll)k, c);\\n\\tFor(i,0,n){\\n\\t\\tscanf(\\\"%d\\\", a + i);\\n\\t\\tp[i] = i;\\n\\t\\tdp[i][1] = 1;\\n\\t\\tcalc(i, 1);\\n\\t}\\n\\tsort(p, p + n, [](const int &i, const int &j){return pii(a[i], i) < pii(a[j], j);});\\n\\tint po = 0;\\n\\tFor(j,2,k + 1){\\n\\t\\tpo = 0;\\n\\t\\tint x = j & 1, y = !x;\\n\\t\\tint sum = 0;\\n\\t\\tFor(iii,0,n){\\n\\t\\t\\tint i = p[iii];\\n\\t\\t\\twhile(po < n && a[p[po]] <= a[i])\\n\\t\\t\\t\\tsum = (sum + dp[p[po ++]][y]) % mod;\\n\\t\\t\\tdp[i][x] = sum;\\n\\t\\t\\tcalc(i, j);\\n\\t\\t}\\n\\t}\\n\\tans %= mod;\\n\\tans = (ans + mod) % mod;\\n\\tprintf(\\\"%d\\\\n\\\", (int)ans);\\n\\treturn 0;\\n}\"",
    "tags": [
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "587",
    "index": "C",
    "title": "Duff in the Army",
    "statement": "Recently Duff has been a soldier in the army. Malek is her commander.\n\nTheir country, Andarz Gu has $n$ cities (numbered from $1$ to $n$) and $n - 1$ bidirectional roads. Each road connects two different cities. There exist a unique path between any two cities.\n\nThere are also $m$ people living in Andarz Gu (numbered from $1$ to $m$). Each person has and ID number. ID number of $i - th$ person is $i$ and he/she lives in city number $c_{i}$. Note that there may be more than one person in a city, also there may be no people living in the city.\n\nMalek loves to order. That's why he asks Duff to answer to $q$ queries. In each query, he gives her numbers $v, u$ and $a$.\n\nTo answer a query:\n\nAssume there are $x$ people living in the cities lying on the path from city $v$ to city $u$. Assume these people's IDs are $p_{1}, p_{2}, ..., p_{x}$ in increasing order.\n\nIf $k = min(x, a)$, then Duff should tell Malek numbers $k, p_{1}, p_{2}, ..., p_{k}$ in this order. In the other words, Malek wants to know $a$ minimums on that path (or less, if there are less than $a$ people).\n\nDuff is very busy at the moment, so she asked you to help her and answer the queries.",
    "tutorial": "Solution is something like the fourth LCA approach discussed here. For each $1  \\le  i  \\le  n$ and $0  \\le  j  \\le  lg(n)$, store the minimum 10 people in the path from city (vertex) $i$ to its $2^{j} - th$ parent in an array. Now everything is needed is: how to merge the array of two paths? You can keep the these 10 values in the array in increasing order and for merging, use merge function which will work in $O(20)$. And then delete the extra values (more than 10). And do the same as described in the article for a query (just like the preprocess part). Time complexity: $O((n+q)a.l g(n))$",
    "code": "\"#include <bits/stdc++.h>\\n#include <ext/pb_ds/assoc_container.hpp>\\n#include <ext/pb_ds/tree_policy.hpp>\\nusing namespace __gnu_pbds;\\nusing namespace std;\\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\\n#define rep(i, c) for(auto &(i) : (c))\\n#define x first\\n#define y second\\n#define pb push_back\\n#define PB pop_back()\\n#define iOS ios_base::sync_with_stdio(false)\\n#define sqr(a) (((a) * (a)))\\n#define all(a) a.begin() , a.end()\\n#define error(x) cerr << #x << \\\" = \\\" << (x) <<endl\\n#define Error(a,b) cerr<<\\\"( \\\"<<#a<<\\\" , \\\"<<#b<<\\\" ) = ( \\\"<<(a)<<\\\" , \\\"<<(b)<<\\\" )\\\\n\\\";\\n#define errop(a) cerr<<#a<<\\\" = ( \\\"<<((a).x)<<\\\" , \\\"<<((a).y)<<\\\" )\\\\n\\\";\\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\\n#define L(x) ((x)<<1)\\n#define R(x) (((x)<<1)+1)\\n#define umap unordered_map\\ntypedef long long ll;\\ntypedef pair<int,int>pii;\\ntypedef vector<int> vi;\\ntypedef complex<double> point;\\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\\nconst int maxn = 1e5 + 100, maxl = 20;\\nstruct myvec{\\n\\tint n = 0;\\n\\tint a[10] = {};\\n\\tinline void pop_back(){if(n)--n;}\\n\\tinline int & operator [](const int &x){return a[x];}\\n\\tinline int back(){if(n)return a[n-1];return -1;}\\n\\tinline void push_back(const int &x){if(n < 10 && x != back())a[n ++] = x;}\\n\\tinline int size(){return n;}\\n\\tinline bool empty(){return !n;}\\n}vec[maxn][maxl], ins[maxn];\\nvi adj[maxn];\\nint par[maxn][maxl], h[maxn];\\ninline myvec operator +(myvec &v,myvec &u){\\n\\tmyvec ans;\\n\\tint i = 0, j = 0;\\n\\twhile(i < v.size() && j < u.size()){\\n\\t\\tif(v[i] <= u[j])\\n\\t\\t\\tans.pb(v[i ++]);\\n\\t\\telse\\n\\t\\t\\tans.pb(u[j ++]);\\n\\t}\\n\\twhile(i < v.size())\\n\\t\\tans.pb(v[i ++]);\\n\\twhile(j < u.size())\\n\\t\\tans.pb(u[j ++]);\\n//\\tans.n = unique(ans.a, ans.a + ans.n) - ans.a;\\n\\treturn ans;\\n}\\ninline void dfs(int v = 0, int p = -1){\\n\\tpar[v][0] = p;\\n\\tvec[v][0] = ins[v];\\n\\tif(p + 1){\\n\\t\\th[v] = h[p] + 1;\\n\\t\\tvec[v][0] = ins[v] + ins[p];\\n\\t}\\n\\tFor(i,1,maxl)\\n\\t\\tif(par[v][i-1] + 1){\\n\\t\\t\\tpar[v][i] = par[par[v][i-1]][i-1];\\n\\t\\t\\tvec[v][i] = vec[v][i-1] + vec[par[v][i-1]][i-1];\\n\\t\\t}\\n\\trep(u, adj[v])\\tif(p - u)\\n\\t\\tdfs(u, v);\\n}\\ninline myvec lca(int v, int u){\\n\\tmyvec ans = ins[v] + ins[u];\\n\\tif(h[v] < h[u])\\tswap(v, u);\\n\\trof(i,maxl-1,-1)\\n\\t\\tif(par[v][i] + 1 && h[par[v][i]] >= h[u]){\\n\\t\\t\\tans = ans + vec[v][i];\\n\\t\\t\\tv = par[v][i];\\n\\t\\t}\\n\\tif(v == u)\\treturn ans;\\n\\trof(i,maxl-1,-1)\\n\\t\\tif(par[v][i] - par[u][i]){\\n\\t\\t\\tans = ans + vec[v][i];\\n\\t\\t\\tans = ans + vec[u][i];\\n\\t\\t\\tv = par[v][i], u = par[u][i];\\n\\t\\t}\\n\\tans = ans + ins[par[v][0]];\\n\\treturn ans;\\n}\\nint n, m, q;\\nint main(){\\n\\tmemset(par, -1, sizeof par);\\n\\tscanf(\\\"%d %d %d\\\", &n, &m, &q);\\n\\tFor(i,1,n){\\n\\t\\tint v, u;\\n\\t\\tscanf(\\\"%d %d\\\", &v, &u);\\n\\t\\t-- v, -- u;\\n\\t\\tadj[v].pb(u);\\n\\t\\tadj[u].pb(v);\\n\\t}\\n\\tFor(i,1,m + 1){\\n\\t\\tint v;\\n\\t\\tscanf(\\\"%d\\\", &v);\\n\\t\\t-- v;\\n\\t\\tif((int)ins[v].size() < 10)\\n\\t\\t\\tins[v].pb(i);\\n\\t}\\n\\tdfs();\\n\\twhile(q--){\\n\\t\\tint v, u, a;\\n\\t\\tscanf(\\\"%d %d %d\\\", &v, &u, &a);\\n\\t\\t-- v, -- u;\\n\\t\\tmyvec ans = lca(v, u);\\n\\t\\tif(ans.size() > a)\\n\\t\\t\\tans.n = a;\\n\\t\\tvi vec;\\n\\t\\tvec.pb(ans.size());\\n\\t\\tFor(i,0,ans.size())\\n\\t\\t\\tvec.pb(ans[i]);\\n\\t\\tFor(i,0,vec.size()){\\n\\t\\t\\tprintf(\\\"%d\\\", vec[i]);\\n\\t\\t\\tif(i + 1 == vec.size())\\n\\t\\t\\t\\tputs(\\\"\\\");\\n\\t\\t\\telse\\n\\t\\t\\t\\tprintf(\\\" \\\");\\n\\t\\t}\\n\\t}\\n\\treturn 0;\\n}\"",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "587",
    "index": "D",
    "title": "Duff in Mafia",
    "statement": "Duff is one if the heads of Mafia in her country, Andarz Gu. Andarz Gu has $n$ cities (numbered from 1 to $n$) connected by $m$ bidirectional roads (numbered by $1$ to $m$).\n\nEach road has a destructing time, and a color. $i$-th road connects cities $v_{i}$ and $u_{i}$ and its color is $c_{i}$ and its destructing time is $t_{i}$.\n\nMafia wants to destruct a matching in Andarz Gu. A matching is a subset of roads such that no two roads in this subset has common endpoint. They can destruct these roads in parallel, i. e. the total destruction time is a maximum over destruction times of all selected roads.\n\nThey want two conditions to be satisfied:\n\n- The remaining roads form a proper coloring.\n- Destructing time of this matching is minimized.\n\nThe remaining roads after destructing this matching form a proper coloring if and only if no two roads of the same color have same endpoint, or, in the other words, edges of each color should form a matching.\n\nThere is no programmer in Mafia. That's why Duff asked for your help. Please help her and determine which matching to destruct in order to satisfied those conditions (or state that this is not possible).",
    "tutorial": "Run binary search on the answer ($t$). For checking if answer is less than or equal to $x$ (check(x)): First of all delete all edges with destructing time greater than $x$. Now, if there is more than one pair of edges with the same color connected to a vertex(because we can delete at most one of them), answer is \"No\". Use 2-Sat. Consider a literal for each edge $e$ ($x_{e}$). If $x_{e} = TRUE$, it means it should be destructed and it shouldn't otherwise. There are some conditions: For each vertex $v$, if there is one (exactly one) pair of edges like $i$ and $j$ with the same color connected to $v$, then we should have the clause $x_{i}\\vee x_{j}$. For each vertex $v$, if the edges connected to it are $e_{1}, e_{2}, ..., e_{k}$, we should make sure that there is no pair $(i, j)$ where $1  \\le  i < j  \\le  k$ and $x_{e1} = x_{e2} = True$. The naive approach is to add a clause $\\top_{x_{i}}\\lor^{+}x_{e_{j}}$ for each pair. But it's not efficient. The efficient way tho satisfy the second condition is to use prefix or: adding $k$ new literals $p_{1}, p_{2}, ..., p_{k}$ and for each $j  \\le  i$, make sure $x_{e_{j}}\\Rightarrow p_{i}$. To make sure about this, we can add two clauses for each $p_{i}$: $\\neg_{x_{i}}\\lor p_{i}$ and $\\neg p_{i-1}\\lor p_{i}$ (the second one is only for $i > 1$). And the only thing left is to make sure $\\vdash p_{i}\\lor^{+}x_{e_{i+1}}$ (there are no two TRUE edges). This way the number of literals and clauses are $O(n+m)$. So, after binary search is over, we should run check(t) to get a sample matching. Time complexity: $O((n+m)l g(m))$ (but slow, because of the constant factor)",
    "code": "\"#include <bits/stdc++.h>\\n#include <ext/pb_ds/assoc_container.hpp>\\n#include <ext/pb_ds/tree_policy.hpp>\\nusing namespace __gnu_pbds;\\nusing namespace std;\\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\\n#define rep(i, c) for(auto &(i) : (c))\\n#define x first\\n#define y second\\n#define pb push_back\\n#define PB pop_back()\\n#define iOS ios_base::sync_with_stdio(false)\\n#define sqr(a) (((a) * (a)))\\n#define all(a) a.begin() , a.end()\\n#define error(x) cerr << #x << \\\" = \\\" << (x) <<endl\\n#define Error(a,b) cerr<<\\\"( \\\"<<#a<<\\\" , \\\"<<#b<<\\\" ) = ( \\\"<<(a)<<\\\" , \\\"<<(b)<<\\\" )\\\\n\\\";\\n#define errop(a) cerr<<#a<<\\\" = ( \\\"<<((a).x)<<\\\" , \\\"<<((a).y)<<\\\" )\\\\n\\\";\\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\\n#define L(x) ((x)<<1)\\n#define R(x) (((x)<<1)+1)\\n#define umap unordered_map\\n#define double long double\\ntypedef long long ll;\\ntypedef pair<int,int>pii;\\ntypedef vector<int> vi;\\ntypedef complex<double> point;\\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\\nconst int maxn = 5e4 + 10, maxN = 6 * maxn;\\nint n, m, comp[maxN];\\nvi adj[maxN], adl[maxN];\\nbool mark[maxN];\\nstruct edge{\\n\\tint v, u, c, t;\\n}e[maxn];\\nvi ed[maxn];\\ninline int neg(int x){\\n\\treturn x ^ 1;\\n}\\ninline void add_edge(int v, int u){\\n\\tadj[v].pb(u);\\n\\tadl[u].pb(v);\\n}\\ninline void add_clause(int v, int u){\\n\\tadd_edge(neg(v), u);\\n\\tadd_edge(neg(u), v);\\n}\\nint sz[maxN], SZ[maxN];\\nstack <int> s;\\ninline void dfs(int v){\\n\\tmark[v] = true;\\n\\trep(u, adj[v])\\tif(!mark[u])\\n\\t\\tdfs(u);\\n\\ts.push(v);\\n}\\nbool flag = true;\\ninline void dfs(int v, int c){\\n\\tcomp[v] = c;\\n\\tif(comp[v] == comp[neg(v)]){\\n\\t\\tflag = false;\\n\\t\\treturn ;\\n\\t}\\n\\trep(u, adl[v])\\tif(!comp[u]){\\n\\t\\tdfs(u, c);\\n\\t\\tif(!flag)\\treturn ;\\n\\t}\\n}\\nint nex;\\ninline bool check(int T){\\n\\tflag = true;\\n\\tFor(i,0,nex){\\n\\t\\tmark[i] = false;\\n\\t\\tadj[i].resize(sz[i]);\\n\\t\\tadl[i].resize(SZ[i]);\\n\\t\\tcomp[i] = 0;\\n\\t}\\n\\twhile(!s.empty())\\ts.pop();\\n\\tFor(i,0,m)\\tif(e[i].t > T)\\n\\t\\tadd_edge(L(i), R(i));\\n\\tFor(i,0,nex)\\n\\t\\tif(!mark[i])\\n\\t\\t\\tdfs(i);\\n\\tint cnt = 1;\\n\\twhile(!s.empty()){\\n\\t\\tint v = s.top();\\n\\t\\ts.pop();\\n\\t\\tif(comp[v])\\tcontinue;\\n\\t\\tdfs(v, cnt ++);\\n\\t\\tif(!flag)\\treturn false;\\n\\t}\\n\\treturn flag;\\n}\\nvi ts = {0};\\nint main(){\\n\\tscanf(\\\"%d %d\\\", &n, &m);\\n\\tFor(i,0,m){\\n\\t\\tscanf(\\\"%d %d %d %d\\\", &e[i].v, &e[i].u, &e[i].c, &e[i].t);\\n\\t\\t-- e[i].v;\\n\\t\\t-- e[i].u;\\n\\t\\ted[e[i].v].pb(i);\\n\\t\\ted[e[i].u].pb(i);\\n\\t\\tts.pb(e[i].t);\\n\\t}\\n\\tnex = L(m);\\n\\tFor(i,0,n){\\n\\t\\tsort(all(ed[i]), [](const int &x, const int &y){return e[x].c < e[y].c;});\\n\\t\\tint cnt = 0;\\n\\t\\tint prv;\\n\\t\\tif(!ed[i].empty()){\\n\\t\\t\\tprv = nex;\\n\\t\\t\\tnex += 2;\\n\\t\\t\\tadd_clause(R(ed[i][0]), prv);\\n\\t\\t}\\n\\t\\tFor(j,1,ed[i].size()){\\n\\t\\t\\tint x = ed[i][j-1], y = ed[i][j];\\n\\t\\t\\tint cur = nex;\\n\\t\\t\\tnex += 2;\\n\\t\\t\\tif(e[x].c == e[y].c){\\n\\t\\t\\t\\t++ cnt;\\n\\t\\t\\t\\tif(cnt >  1){\\n\\t\\t\\t\\t\\tputs(\\\"No\\\");\\n\\t\\t\\t\\t\\treturn 0;\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tadd_clause(L(x), L(y));\\n\\t\\t\\t}\\n\\t\\t\\tadd_clause(R(y), cur);\\n\\t\\t\\tadd_clause(neg(prv), cur);\\n\\t\\t\\tadd_clause(neg(prv), R(y));\\n\\t\\t\\tprv = cur;\\n\\t\\t}\\n\\t}\\n\\tFor(i,0,maxN)\\n\\t\\tsz[i] = adj[i].size(),SZ[i] = adl[i].size();\\n\\tsort(all(ts));\\n\\tts.resize(unique(all(ts)) - ts.begin());\\n\\tint lo = 0, hi = ts.size() - 1;\\n\\twhile(lo < hi){\\n\\t\\tint mid = (lo + hi)/2;\\n\\t\\tif(check(ts[mid]))\\n\\t\\t\\thi = mid;\\n\\t\\telse\\n\\t\\t\\tlo = mid + 1;\\n\\t}\\n\\tif(lo >= (int)ts.size() or !check(ts[lo])){\\n\\t\\tputs(\\\"No\\\");\\n\\t\\treturn 0;\\n\\t}\\n\\tputs(\\\"Yes\\\");\\n\\tfill(mark, mark + nex, false);\\n\\tint T = ts[lo];\\n\\tFor(i,0,nex){\\n\\t\\tint v = comp[i], u = comp[neg(i)];\\n\\t\\tmark[min(v, u)] = false;\\n\\t\\tmark[max(v, u)] = true;\\n\\t}\\n\\tvi ans;\\n\\tFor(i,0,m)\\n\\t\\tif(mark[comp[L(i)]])\\n\\t\\t\\tans.pb(i + 1);\\n\\tint K = ans.size();\\n\\tprintf(\\\"%d %d\\\\n\\\", T, K);\\n\\tint cnt = 0;\\n\\trep(i, ans){\\n\\t\\tprintf(\\\"%d\\\", i);\\n\\t\\t++ cnt;\\n\\t\\tif(cnt == K)\\n\\t\\t\\tputs(\\\"\\\");\\n\\t\\telse\\n\\t\\t\\tprintf(\\\" \\\");\\n\\t}\\n\\treturn 0;\\n}\"",
    "tags": [
      "2-sat",
      "binary search"
    ],
    "rating": 3100
  },
  {
    "contest_id": "587",
    "index": "E",
    "title": "Duff as a Queen",
    "statement": "Duff is the queen of her country, Andarz Gu. She's a competitive programming fan. That's why, when he saw her minister, Malek, free, she gave her a sequence consisting of $n$ non-negative integers, $a_{1}, a_{2}, ..., a_{n}$ and asked him to perform $q$ queries for her on this sequence.\n\nThere are two types of queries:\n\n- given numbers $l, r$ and $k$, Malek should perform $a_{i}=a_{i}\\oplus k$ for each $l ≤ i ≤ r$ ($a\\oplus b=a\\times\\mathrm{or}\\,b$, bitwise exclusive OR of numbers $a$ and $b$).\n- given numbers $l$ and $r$ Malek should tell her the score of sequence $a_{l}, a_{l + 1}, ... , a_{r}$.\n\nScore of a sequence $b_{1}, ..., b_{k}$ is the number of its different Kheshtaks. A non-negative integer $w$ is a Kheshtak of this sequence if and only if there exists a subsequence of $b$, let's denote it as $b_{i1}, b_{i2}, ... , b_{ix}$ (possibly empty) such that $w=b_{i_{1}}\\oplus b_{i_{2}}\\oplus\\ldots\\leftrightarrow b_{i_{3}}$ ($1 ≤ i_{1} < i_{2} < ... < i_{x} ≤ k$). If this subsequence is empty, then $w = 0$.\n\nUnlike Duff, Malek is not a programmer. That's why he asked for your help. Please help him perform these queries.",
    "tutorial": "Lemma #1: If numbers $b_{1}, b_{2}, ..., b_{k}$ are $k$ Kheshtaks of $a_{1}, ..., a_{n}$, then $b_{1}\\oplus b_{2}\\oplus\\ldots\\oplus b_{k}$ is a Kheshtak of $a_{1}, ..., a_{n}$. Proof: For each $1  \\le  i  \\le  k$, consider $mask_{i}$ is a binary bitmask of length $n$ and its $j - th$ bit shows a subsequence of $a_{1}, ..., a_{n}$ (subset) with xor equal to $b_{i}$. So, xor of elements subsequence(subset) of $a_{1}, ..., a_{n}$ with bitmask equal to $m a s k_{1}\\oplus m a s k_{2}\\oplus\\ldots\\oplus m a s k_{k}$ equals to $b_{1}\\oplus b_{2}\\oplus\\ldots\\oplus b_{k}$. So, it's a Kheshtak of this sequence. From this lemma, we can get another results: If all numbers $b_{1}, b_{2}, ..., b_{k}$ are $k$ Kheshtaks of $a_{1}, ..., a_{n}$, then every Kheshtak of $b_{1}, b_{2}, ..., b_{k}$ is a Kheshtak of $a_{1}, ..., a_{n}$ Lemma #2: Score of sequence $a_{1}, a_{2}, ..., a_{n}$ is equal to the score of sequence $a_{1},a_{1}\\oplus a_{2},a_{2}\\oplus a_{3},...,a_{n-1}\\oplus a_{n}$. Proof: If we show the second sequence by $b_{1}, b_{2}, ..., b_{n}$, then for each $1  \\le  i  \\le  n$: $b_{i}$ = $a_{i-1}\\oplus a_{i}$ $a_{i}$ = $b_{1}\\oplus b_{2}\\oplus\\ldots\\oplus b_{i}$ $\\underline{{\\mathbf{f}}}$ each element from sequence $b$ is a Kheshtak of sequence $a$ and vise versa. So, due to the result of Lemma #1, each Kheshtak of sequence $b$ is a Kheshtak of sequence $a$ and vise versa. So: $score(b_{1}, ..., b_{n})  \\le  score(a_{1}, ..., a_{n})$ $score(a_{1}, ..., a_{n})  \\le  score(b_{1}, ..., b_{n})$ $\\underline{{\\mathbf{f}}}$ $score(a_{1}, ..., a_{n}) = score(b_{1}, ..., b_{n})$ Back to original problem: denote another array $b_{2}, ..., b_{n}$ where $b_{i}=a_{i-1}\\oplus a_{i}$. Let's solve these two problems: 1- We have array $a_{1}, ..., a_{n}$ and $q$ queries of two types: $upd(l, r, k)$: Given numbers $l, r$ and $k$, for each $l  \\le  i  \\le  r$, perform $a_{i}=a_{i}\\oplus k$ $ask(i):$ Given number $i$, return the value of $a_{i}$. This problem can be solved easily with a simple segment tree using lazy propagation. 2- We have array $b_{2}, ..., b_{n}$ and queries of two types: $modify(p, k)$: Perform $b_{p} = k$. $basis(l, r)$: Find and return the basis vector of $b_{l}, b_{l + 1}, ..., b_{r}$ (using Gaussian Elimination, its size it at most 32). This problem can be solved by a segment tree where in each node we have the basis of the substring of that node (node $[l, r)$ has the basis of sequence $b_{l}, ..., b_{r - 1}$). This way we can insert to a basis vector $v$: insert(x, v) for a in v if a & -a & x x ^= a if !x return for a in v if x & -x & a a ^= x v.push(x)But size of $v$ will always be less than or equal to 32. For merging two nodes (of segment tree), we can insert the elements of one in another one. For handling queries of two types, we act like this: Type one: Call functions: $upd(l, r, k)$, $m o d i f y(l,b_{l}\\oplus k)$ and $m o d i f y(r+1,b_{r+1}\\oplus k)$. Type two: Let $b = basis(l + 1, r)$. Call $insert(a_{l}, b)$. And then print $2^{b.size()}$ as the answer. Time complexity: $O(n l g(n)\\times32^{2})$ = $O(n l g(n)l g^{2}(m a x(a_{1},...,a_{n})))$",
    "code": "\"#include <bits/stdc++.h>\\n#include <ext/pb_ds/assoc_container.hpp>\\n#include <ext/pb_ds/tree_policy.hpp>\\nusing namespace __gnu_pbds;\\nusing namespace std;\\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\\n#define rep(i, c) for(auto &(i) : (c))\\n#define x first\\n#define y second\\n#define pb push_back\\n#define PB pop_back()\\n#define iOS ios_base::sync_with_stdio(false)\\n#define sqr(a) (((a) * (a)))\\n#define all(a) a.begin() , a.end()\\n#define error(x) cerr << #x << \\\" = \\\" << (x) <<endl\\n#define Error(a,b) cerr<<\\\"( \\\"<<#a<<\\\" , \\\"<<#b<<\\\" ) = ( \\\"<<(a)<<\\\" , \\\"<<(b)<<\\\" )\\\\n\\\";\\n#define errop(a) cerr<<#a<<\\\" = ( \\\"<<((a).x)<<\\\" , \\\"<<((a).y)<<\\\" )\\\\n\\\";\\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\\n#define L(x) ((x)<<1)\\n#define R(x) (((x)<<1)+1)\\n#define umap unordered_map\\n#define double long double\\ntypedef long long ll;\\ntypedef pair<int,int>pii;\\ntypedef vector<int> vi;\\ntypedef complex<double> point;\\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\\nconst int maxn = 2e5 + 10;\\ninline int sbit(const int &x){return x & -x;}\\nstruct basis{\\n\\tint t = 0, a[32] = {};\\n\\tinline void pb(int x){\\n\\t\\tFor(i,0,t)\\n\\t\\t\\tif(x & sbit(a[i]))\\n\\t\\t\\t\\tx ^= a[i];\\n\\t\\tif(!x)\\treturn ;\\n\\t\\tFor(i,0,t)\\n\\t\\t\\tif(sbit(x) & a[i])\\n\\t\\t\\t\\ta[i] ^= x;\\n\\t\\ta[t ++] = x;\\n\\t}\\n\\tinline void perform(int k){\\n\\t\\tFor(i,0,t)\\n\\t\\t\\tif(a[i] & 1)\\n\\t\\t\\t\\ta[i] ^= k;\\n\\t}\\n\\tinline basis operator + (basis b){\\n\\t\\tif(!t)\\treturn b;\\n\\t\\tif(!b.t)\\treturn *this;\\n\\t\\tbasis ans;\\n\\t\\tFor(i,0,t)\\n\\t\\t\\tans.pb(a[i]);\\n\\t\\tFor(i,0,b.t)\\n\\t\\t\\tans.pb(b.a[i]);\\n\\t\\treturn ans;\\n\\t}\\n}v[maxn * 4], emp;\\nint lz[maxn * 4], a[maxn], n, q, p2[35];\\ninline void upd(int id, int k){\\n\\tif(!k)\\treturn ;\\n\\tlz[id] ^= k;\\n\\tv[id].perform(k);\\n}\\ninline void shift(int id){\\n\\tupd(L(id), lz[id]);\\n\\tupd(R(id), lz[id]);\\n\\tlz[id] = 0;\\n}\\ninline void build(int id = 1, int l = 0, int r = n){\\n\\tif(r - l < 2){\\n\\t\\tv[id].pb(a[l]);\\n\\t\\treturn ;\\n\\t}\\n\\tint mid = (l + r)/2;\\n\\tbuild(L(id), l, mid);\\n\\tbuild(R(id), mid, r);\\n\\tv[id] = v[L(id)] + v[R(id)];\\n}\\ninline void upd(int x, int y, int k, int id = 1, int l = 0, int r = n){\\n\\tif(x >= r or l >= y)\\treturn ;\\n\\tif(x <= l && r <= y){\\n\\t\\tupd(id, k);\\n\\t\\treturn ;\\n\\t}\\n\\tint mid = (l + r)/2;\\n\\tshift(id);\\n\\tupd(x, y, k, L(id), l, mid);\\n\\tupd(x, y, k, R(id), mid, r);\\n\\tv[id] = v[L(id)] + v[R(id)];\\n}\\ninline basis ask(int x, int y, int id = 1, int l = 0, int r = n){\\n\\tif(x >= r or l >= y)\\treturn emp;\\n\\tif(x <= l && r <= y)\\treturn v[id];\\n\\tint mid = (l + r)/2;\\n\\tshift(id);\\n\\treturn ask(x, y, L(id), l, mid) + ask(x, y, R(id), mid, r);\\n}\\nint main(){\\n\\tscanf(\\\"%d %d\\\", &n, &q);\\n\\tFor(i,0,n){\\n\\t\\tscanf(\\\"%d\\\", a + i);\\n\\t\\ta[i] = 2*a[i] + 1;\\n\\t}\\n\\tbuild();\\n\\tFor(i,0,35)\\tp2[i] = (1 << i);\\n\\twhile(q --){\\n\\t\\tint t, l, r, k;\\n\\t\\tscanf(\\\"%d %d %d\\\", &t, &l, &r);\\n\\t\\t-- l;\\n\\t\\tif(t == 1){\\n\\t\\t\\tscanf(\\\"%d\\\", &k);\\n\\t\\t\\tupd(l, r, k << 1);\\n\\t\\t}\\n\\t\\telse{\\n\\t\\t\\tbasis ans, b = ask(l, r);\\n\\t\\t\\tFor(i,0,b.t)\\n\\t\\t\\t\\tans.pb(b.a[i] >> 1);\\n\\t\\t\\tprintf(\\\"%d\\\\n\\\", p2[ans.t]);\\n\\t\\t}\\n\\t}\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "data structures"
    ],
    "rating": 2900
  },
  {
    "contest_id": "587",
    "index": "F",
    "title": "Duff is Mad",
    "statement": "Duff is mad at her friends. That's why she sometimes makes Malek to take candy from one of her friends for no reason!\n\nShe has $n$ friends. Her $i$-th friend's name is $s_{i}$ (their names are not necessarily unique). $q$ times, she asks Malek to take candy from her friends. She's angry, but also she acts with rules. When she wants to ask Malek to take candy from one of her friends, like $k$, she chooses two numbers $l$ and $r$ and tells Malek to take exactly $\\sum_{i=l}^{r}{\\cal O}c c u r(s_{i},s_{k})$ candies from him/her, where $occur(t, s)$ is the number of occurrences of string $t$ in $s$.\n\nMalek is not able to calculate how many candies to take in each request from Duff. That's why she asked for your help. Please tell him how many candies to take in each request.",
    "tutorial": "Use Aho-Corasick. Assume first of all we build the trie of our strings (function t). If $t(v, c)  \\neq  - 1$ it means that there is an edge in the trie outgoing from vertex $v$ written $c$ on it. So, for building Aho-Corasick, consider $f(v)$ = the vertex we go into, in case of failure ($t(v, c) = - 1$). i.e the deepest vertex ($u$), that $v  \\neq  u$ and the path from root to $u$ is a suffix of path from root to $v$. No we can build an automaton (Aho-Corasick), function $g$. For each i, do this (in the automaton): cur = root for c in s[i] cur = g(cur, c) And then push i in q[cur] (q is a vector, also we do this for cur = root). end[cur].push(i) // end is also a vector, consisting of the indices of strings ending in vertex cur (state cur in automaton) last[i] = cur // last[i] is the final state we get to from searching string s[i] in automaton gAssume $cnt(v, i)$ is the number of occurrences of number $i$ in $q[v]$. Also, denote $c o u n t(v,i)=\\sum_{u}\\O_{i n\\ s u b t r e e\\ o f\\ v}c m t(u,i)$. Build another tree. In this tree, for each $i$ that is not root of the trie, let $par[i] = f(i)$ (the vertex we go in the trie, in case of failure) and call it C-Tree. So now, problem is on a tree. Operations are : Each query gives numbers $l, r, k$ and you have to find the number $\\sum_{i=l}^{r}c o u n t(l a s t\\lbrack i\\rbrack,k)$. Act offline. If $N = 10^{5}$, then: 1. For each $i$ such that $s[i].s i z e(\\l)>\\sqrt{N}$, collect queries (like struct) in a vector of queries $query[i]$, then run dfs on the C-Tree and using a partial sum answer to all queries with $k = i$. There are at most $\\sqrt{n}$ of these numbers, so it can be done in $O(N{\\sqrt{N}})$. After doing these, erase $i$ from all $q[1], q[1], ..., q[N]$. Code (in dfs) would be like this(on C-Tree): partial_sum[n] = {}; // all 0 dfs(v, i){ cnt = 0; for x in q[v] if(x == i) ++ cnt; for u in childern[v] cnt += dfs(u); for x in end[v] partial_sum[x] += cnt; return cnt; } calc(i){ dfs(root, i); for i = 2 to n partial_sum[i] += partial_sum[i-1] for query u in query[i] u.ans = partial_sum[u.r] - partial_sum[u.l - 1] }And we should just run calc(i) for each of them. 2. For each $i$ such that $s[i].s i z e(\\l)\\leq{\\sqrt{N}}$, collect queries (like struct) in a vector of queries $query[i]$. (each element of this vector have three integers in it: $l, r$ and $ans$). Consider this problem: We have an array a of length $N$(initially all element equal to 0) and some queries of two types: $increase(i, val)$: increase $a[i]$ by $val$ $sum(i)$: tell the value of $a[1] + a[2] + ... + a[i]$ We know that number of queries of the first type is $O(N)$ and from the second type is $O(N{\\sqrt{N}})$. Using Sqrt decomposition, we can solve this problem in $O(N{\\sqrt{N}})$: K = sqrt(N) tot[K] = {}, a[N] = {} // this code is 0-based increase(i, val) while i < N and i % K > 0 a[i ++] += val while i < K tot[i/K] += val i += K sum(i) return a[i] + tot[i/K]Back to our problem now. Then, just run dfs once on this C-Tree and act like this: dfs(vertex v): for i in end[v] increase(i, 1) for i in q[v] for query u in query[i] u.ans += sum(u.r) - sum(u.l - 1) for u in children[v] dfs(u) for i in end[v] increase(i, -1)Then answer to a query $q$ is $q.ans$. Time complexity: $O(N{\\sqrt{N}})$",
    "code": "\"#include <bits/stdc++.h>\\n#include <ext/pb_ds/assoc_container.hpp>\\n#include <ext/pb_ds/tree_policy.hpp>\\nusing namespace __gnu_pbds;\\nusing namespace std;\\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\\n#define rep(i, c) for(auto &(i) : (c))\\n#define x first\\n#define y second\\n#define pb push_back\\n#define PB pop_back()\\n#define iOS ios_base::sync_with_stdio(false)\\n#define sqr(a) (((a) * (a)))\\n#define all(a) a.begin() , a.end()\\n#define error(x) cerr << #x << \\\" = \\\" << (x) <<endl\\n#define Error(a,b) cerr<<\\\"( \\\"<<#a<<\\\" , \\\"<<#b<<\\\" ) = ( \\\"<<(a)<<\\\" , \\\"<<(b)<<\\\" )\\\\n\\\";\\n#define errop(a) cerr<<#a<<\\\" = ( \\\"<<((a).x)<<\\\" , \\\"<<((a).y)<<\\\" )\\\\n\\\";\\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\\n#define L(x) ((x)<<1)\\n#define R(x) (((x)<<1)+1)\\n#define umap unordered_map\\n#define double long double\\ntypedef long long ll;\\ntypedef pair<int,int>pii;\\ntypedef vector<int> vi;\\ntypedef complex<double> point;\\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\\nconst int maxn = 1e5 + 100;\\nint TRIE[maxn][26];\\nstring s[maxn];\\nint f[maxn], aut[maxn][26], root, nx = 1;\\nvi tof[maxn];\\nvi adj[maxn];\\nint end[maxn];\\nvi ends[maxn];\\ninline void build(int x){\\n\\tint v = root;\\n\\trep(ch, s[x]){\\n\\t\\tint c = ch - 'a';\\n\\t\\tif(TRIE[v][c] == -1){\\n\\t\\t\\tTRIE[v][c] = nx;\\n\\t\\t\\t++ nx;\\n\\t\\t}\\n\\t\\tv = TRIE[v][c];\\n\\t}\\n\\t::end[x] = v;\\n\\t::ends[v].pb(x);\\n}\\ninline void ahoc(){\\n\\tf[root] = root;\\n\\tqueue<int> q;\\n\\tq.push(root);\\n\\twhile(!q.empty()){\\n\\t\\tint v = q.front();\\n\\t\\tq.pop();\\n\\t\\tFor(c,0,26){\\n\\t\\t\\tif(TRIE[v][c] != -1){\\n\\t\\t\\t\\taut[v][c] = TRIE[v][c];\\t\\n\\t\\t\\t\\tif(v != root)\\n\\t\\t\\t\\t\\tf[aut[v][c]] = aut[f[v]][c];\\n\\t\\t\\t\\telse\\n\\t\\t\\t\\t\\tf[aut[v][c]] = root;\\n\\t\\t\\t\\tq.push(TRIE[v][c]);\\n\\t\\t\\t}\\n\\t\\t\\telse{\\n\\t\\t\\t\\tif(v == root)\\n\\t\\t\\t\\t\\taut[v][c] = root;\\n\\t\\t\\t\\telse\\n\\t\\t\\t\\t\\taut[v][c] = aut[f[v]][c];\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\\ninline void go(int x){\\n\\tint v = root;\\n\\trep(ch, s[x]){\\n\\t\\tint c = ch - 'a';\\n\\t\\tv = aut[v][c];\\n\\t\\ttof[v].pb(x);\\n\\t}\\n}\\nint par[maxn];\\nchar ch[maxn];\\nconst int K = 350;\\nstruct sqrt_decomposition{\\n\\tll sum[maxn] = {}, tot[K] = {};\\n\\tinline void add(int p, ll val){\\n\\t\\twhile(p < maxn && p % K)\\n\\t\\t\\tsum[p ++] += val;\\n\\t\\twhile(p < maxn){\\n\\t\\t\\ttot[p/K] += val;\\n\\t\\t\\tp += K;\\n\\t\\t}\\n\\t}\\n\\tinline ll ask(int p){\\n\\t\\treturn (p < 0 ? 0 : sum[p] + tot[p/K]);\\n\\t}\\n}SQRT;\\nstruct query{\\n\\tint l, r, k;\\n\\tll ans = 0LL;\\n\\tquery(){}\\n\\tquery(int L, int R, int K){\\n\\t\\tl = L;\\n\\t\\tr = R;\\n\\t\\tk = K;\\n\\t}\\n}Q[maxn];\\nvi queries[maxn];\\ninline void dfs(int v){\\n\\trep(a, ::ends[v])\\n\\t\\tSQRT.add(a, 1);\\n\\trep(i, tof[v])\\tif((int)s[i].size() < K){\\n\\t\\trep(j, queries[i])\\n\\t\\t\\tQ[j].ans += SQRT.ask(Q[j].r) - SQRT.ask(Q[j].l - 1);\\n\\t}\\n\\trep(u, adj[v])\\tdfs(u);\\n\\trep(a, ::ends[v])\\n\\t\\tSQRT.add(a, -1);\\n}\\nll ps[maxn];\\ninline int dfs(int v, int x){\\n\\tint cnt = 0;\\n\\trep(a, tof[v])\\tif(a == x)\\n\\t\\t++ cnt;\\n\\trep(u, adj[v])\\n\\t\\tcnt += dfs(u, x);\\n\\trep(a, ::ends[v])\\n\\t\\tps[a] += (ll)cnt;\\n\\treturn cnt;\\n}\\nint main(){\\n\\tmemset(TRIE, -1, sizeof TRIE);\\n\\tmemset(par, -1, sizeof par);\\n\\tint n, q;\\n\\tscanf(\\\"%d %d\\\", &n, &q);\\n\\tFor(i,0,n){\\n\\t\\tscanf(\\\"%s\\\", ch);\\n\\t\\ts[i] = (string)ch;\\n\\t\\tbuild(i);\\n\\t}\\n\\tahoc();\\n\\tFor(i,0,n)\\n\\t\\tgo(i);\\n\\tFor(i,1,nx){\\n\\t\\tpar[i] = f[i];\\n\\t\\tadj[par[i]].pb(i);\\n\\t}\\n\\tFor(i,0,q){\\n\\t\\tint l, r, k;\\n\\t\\tscanf(\\\"%d %d %d\\\", &l, &r, &k);\\n\\t\\t-- l, -- r, -- k;\\n\\t\\tQ[i] = query(l, r, k);\\n\\t\\tqueries[k].pb(i);\\n\\t}\\n\\tFor(i,0,n)\\tif((int)s[i].size() >= K){\\n\\t\\tfill(ps, ps + maxn, 0LL);\\n\\t\\tdfs(root, i);\\n\\t\\tFor(i,1,maxn)\\n\\t\\t\\tps[i] += ps[i-1];\\n\\t\\trep(j, queries[i])\\n\\t\\t\\tQ[j].ans += ps[Q[j].r] - (Q[j].l ? ps[Q[j].l-1] : 0LL);\\n\\t}\\n\\tdfs(root);\\n\\tFor(i,0,q)\\n\\t\\tprintf(\\\"%lld\\\\n\\\", Q[i].ans);\\n\\treturn 0;\\n}\\n\\n\"",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "588",
    "index": "A",
    "title": "Duff and Meat",
    "statement": "Duff is addicted to meat! Malek wants to keep her happy for $n$ days. In order to be happy in $i$-th day, she needs to eat exactly $a_{i}$ kilograms of meat.\n\nThere is a big shop uptown and Malek wants to buy meat for her from there. In $i$-th day, they sell meat for $p_{i}$ dollars per kilogram. Malek knows all numbers $a_{1}, ..., a_{n}$ and $p_{1}, ..., p_{n}$. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.\n\nMalek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for $n$ days.",
    "tutorial": "Idea is a simple greedy, buy needed meat for $i - th$ day when it's cheapest among days $1, 2, ..., n$. So, the pseudo code below will work: ans = 0 price = infinity for i = 1 to n price = min(price, p[i]) ans += price * a[i] Time complexity: ${\\mathcal{O}}(n)$",
    "code": "\"#include <bits/stdc++.h>\\n#include <ext/pb_ds/assoc_container.hpp>\\n#include <ext/pb_ds/tree_policy.hpp>\\nusing namespace __gnu_pbds;\\nusing namespace std;\\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\\n#define rep(i, c) for(auto &(i) : (c))\\n#define x first\\n#define y second\\n#define pb push_back\\n#define PB pop_back()\\n#define iOS ios_base::sync_with_stdio(false)\\n#define sqr(a) (((a) * (a)))\\n#define all(a) a.begin() , a.end()\\n#define error(x) cerr << #x << \\\" = \\\" << (x) <<endl\\n#define Error(a,b) cerr<<\\\"( \\\"<<#a<<\\\" , \\\"<<#b<<\\\" ) = ( \\\"<<(a)<<\\\" , \\\"<<(b)<<\\\" )\\\\n\\\";\\n#define errop(a) cerr<<#a<<\\\" = ( \\\"<<((a).x)<<\\\" , \\\"<<((a).y)<<\\\" )\\\\n\\\";\\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\\n#define L(x) ((x)<<1)\\n#define R(x) (((x)<<1)+1)\\n#define umap unordered_map\\n#define double long double\\ntypedef long long ll;\\ntypedef pair<int,int>pii;\\ntypedef vector<int> vi;\\ntypedef complex<double> point;\\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\\nint main(){\\n\\tiOS;\\n\\tint n;\\n\\tcin >> n;\\n\\tint price = 1e9, ans = 0;\\n\\twhile(n --){\\n\\t\\tint a, p;\\n\\t\\tcin >> a >> p;\\n\\t\\tsmin(price, p);\\n\\t\\tans += a * price;\\n\\t}\\n\\tcout << ans << endl;\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "588",
    "index": "B",
    "title": "Duff in Love",
    "statement": "Duff is in love with lovely numbers! A positive integer $x$ is called lovely if and only if there is no such positive integer $a > 1$ such that $a^{2}$ is a divisor of $x$.\n\nMalek has a number store! In his store, he has only divisors of positive integer $n$ (and he has all of them). As a birthday present, Malek wants to give her a lovely number from his store. He wants this number to be as big as possible.\n\nMalek always had issues in math, so he asked for your help. Please tell him what is the biggest lovely number in his store.",
    "tutorial": "Find all prime divisors of $n$. Assume they are $p_{1}, p_{2}, ..., p_{k}$ (in $O({\\sqrt{n}})$). If answer is $a$, then we know that for each $1  \\le  i  \\le  k$, obviously $a$ is not divisible by $p_{i}^{2}$ (and all greater powers of $p_{i}$). So $a  \\le  p_{1}  \\times  p_{2}  \\times  ...  \\times  p_{k}$. And we know that $p_{1}  \\times  p_{2}  \\times  ...  \\times  p_{k}$ is itself lovely. So,answer is $p_{1}  \\times  p_{2}  \\times  ...  \\times  p_{k}$ Time complexity: $O({\\sqrt{n}})$",
    "code": "\"#include <bits/stdc++.h>\\n#include <ext/pb_ds/assoc_container.hpp>\\n#include <ext/pb_ds/tree_policy.hpp>\\nusing namespace __gnu_pbds;\\nusing namespace std;\\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\\n#define rep(i, c) for(auto &(i) : (c))\\n#define x first\\n#define y second\\n#define pb push_back\\n#define PB pop_back()\\n#define iOS ios_base::sync_with_stdio(false)\\n#define sqr(a) (((a) * (a)))\\n#define all(a) a.begin() , a.end()\\n#define error(x) cerr << #x << \\\" = \\\" << (x) <<endl\\n#define Error(a,b) cerr<<\\\"( \\\"<<#a<<\\\" , \\\"<<#b<<\\\" ) = ( \\\"<<(a)<<\\\" , \\\"<<(b)<<\\\" )\\\\n\\\";\\n#define errop(a) cerr<<#a<<\\\" = ( \\\"<<((a).x)<<\\\" , \\\"<<((a).y)<<\\\" )\\\\n\\\";\\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\\n#define L(x) ((x)<<1)\\n#define R(x) (((x)<<1)+1)\\n#define umap unordered_map\\n#define double long double\\ntypedef long long ll;\\ntypedef pair<int,int>pii;\\ntypedef vector<int> vi;\\ntypedef complex<double> point;\\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\\nint main(){\\n\\tiOS;\\n\\tll n;\\n\\tcin >> n;\\n\\tll ans = 1;\\n\\tll x = n;\\n\\tfor(ll i = 2;i * i <= n; i ++)\\tif(x % i == 0){\\n\\t\\tans *= (ll) i;\\n\\t\\twhile(x % i == 0)\\n\\t\\t\\tx /= i;\\n\\t}\\n\\tif(x > 1)\\n\\t\\tans *= x;\\n\\tcout << ans << endl;\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "590",
    "index": "A",
    "title": "Median Smoothing",
    "statement": "A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.\n\nApplying the simplest variant of median smoothing to the sequence of numbers $a_{1}, a_{2}, ..., a_{n}$ will result a new sequence $b_{1}, b_{2}, ..., b_{n}$ obtained by the following algorithm:\n\n- $b_{1} = a_{1}$, $b_{n} = a_{n}$, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.\n- For $i = 2, ..., n - 1$ value $b_{i}$ is equal to the median of three values $a_{i - 1}$, $a_{i}$ and $a_{i + 1}$.\n\nThe median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.\n\nIn order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.\n\nHaving made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.\n\nNow Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.",
    "tutorial": "We will call the element of a sequence stable, if it doesn't change after applying the algorithm of median smoothing for any number of times. Both ends are stable by the definition of the median smoothing. Also, it is easy to notice, that two equal consecutive elements are both stable. Now we should take a look at how do stable elements affect their neighbors. Suppose $a_{i - 1} = a_{i}$, meaning $i - 1$ and $i$ are stable. Additionaly assume, that $a_{i + 1}$ is not a stable element, hence $a_{i + 1}  \\neq  a_{i}$ and $a_{i + 1}  \\neq  a_{i + 2}$. Keeping in mind that only $0$ and $1$ values are possible, we conclude that $a_{i} = a_{i + 2}$ and applying a median smoothing algorithm to this sequence will result in $a_{i} = a_{i + 1}$. That means, if there is a stable element in position $i$, both $i + 1$ and $i - 1$ are guaranteed to be stable after one application of median smoothing. Now we can conclude, that all sequences will turn to stable at some point. Note, that if there are two stable elements $i$ and $j$ with no other stable elements located between them, the sequence of elements between them is alternating, i.e. $a_{k} = (a_{i} + k - i)mod2$, where $k\\in[i,j]$. One can check, that stable elements may occur only at the ends of the alternating sequence, meaning the sequence will remain alternating until it will be killed by effect spreading from ending stable elements. The solution is: calculate $max(min(|i - s_{j}|))$, where $s_{j}$ are the initial stable elements. Time complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\n#include<cmath>\n#include<cstdio>\n#include<cstring>\n#include<cstdlib>\n#include<iostream>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n#define FZ(n) memset((n),0,sizeof(n))\n#define FMO(n) memset((n),-1,sizeof(n))\n#define MC(n,m) memcpy((n),(m),sizeof(n))\n#define F first\n#define S second\n#define MP make_pair\n#define PB push_back\n#define FOR(x,y) for(__typeof(y.begin())x=y.begin();x!=y.end();x++)\n#define IOS ios_base::sync_with_stdio(0); cin.tie(0)\n// Let's Fight!\n \nconst int MAXN = 505050;\n \nint N;\nint arr[MAXN];\n \nint modify(int l, int r)\n{\n  if(l == r) return 0;\n  if(arr[l] == arr[r])\n  {\n    for(int i=l+1; i<r; i++)\n      arr[i] = arr[l];\n    return (r-l)/2;\n  }\n  else\n  {\n    int m = (l+r+1)/2;\n    for(int i=l+1; i<m; i++)\n      arr[i] = arr[l];\n    for(int i=m; i<r; i++)\n      arr[i] = arr[r];\n    return (r-l-1)/2;\n  }\n}\n \nint main()\n{\n  IOS;\n  cin>>N;\n  for(int i=0; i<N; i++)\n    cin>>arr[i];\n \n  int ans = 0;\n  int lb = 0;\n  for(int i=0; i<N; i++)\n  {\n    if(i == N-1 || arr[i] == arr[i+1])\n    {\n      ans = max(ans, modify(lb, i));\n      lb = i+1;\n    }\n  }\n \n  cout<<ans<<\"\\n\";\n  for(int i=0; i<N; i++)\n    cout<<arr[i]<<(i==N-1 ? \"\\n\" : \" \");\n \n  return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "590",
    "index": "B",
    "title": "Chip 'n Dale Rescue Rangers",
    "statement": "A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.\n\nWe assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point $(x_{1}, y_{1})$, and the distress signal came from the point $(x_{2}, y_{2})$.\n\nDue to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed $v_{\\mathrm{max}}$ meters per second.\n\nOf course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector $(v_{x}, v_{y})$ for the nearest $t$ seconds, and then will change to $(w_{x}, w_{y})$. These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point $(x, y)$, while its own velocity relative to the air is equal to zero and the wind $(u_{x}, u_{y})$ is blowing, then after ${\\mathbf{}}T$ seconds the new position of the dirigible will be $(x+\\tau\\cdot u_{x},\\,y+\\tau\\cdot u_{y})$.\n\nGadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.\n\nIt is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.",
    "tutorial": "If the velocity of the dirigible relative to the air is given by the vector $(a_{x}, a_{y})$, while the velocity of the wind is $(b_{x}, b_{y})$, the resulting velocity of the dirigible relative to the plane is $(a_{x} + b_{x}, a_{y} + b_{y})$. The main idea here is that the answer function is monotonous. If the dirigible is able to reach to target in ${\\mathbf{}}T$ seconds, then it can do so in $\\tau+x$ seconds, for any $x  \\ge  0$. That is an obvious consequence from the fact the maximum self speed of the dirigible is strictly greater then the speed of the wind at any moment of time. For any monotonous function we can use binary search. Now we only need to check, if for some given value ${\\mathbf{}}T$ it's possible for the dirigible to reach the target in ${\\mathbf{}}T$ seconds. Let's separate the movement of the air and the movement of the dirigible in the air. The movement cause by the air is: $(x_{n}, y_{n})$ = $(x_{1}+v_{x}\\cdot\\tau,y_{1}+v_{w}\\cdot\\tau)$, if $\\tau\\leq l$; $(x_{n}, y_{n})$ = $\\left(T\\right|+{{v_{x}}\\cdot\\left(\\mp\\right.\\upsilon_{x}\\cdot\\left(\\tau=\\left|\\right),\\ y\\right|+\\upsilon_{y}\\cdot\\left(\\Omega+\\upsilon_{y}\\cdot\\left(\\tau=\\imath\\right)\\right)}$, for ${\\boldsymbol{\\tau}}>{\\boldsymbol{\\imath}}$. The only thing we need to check now is that the distance between the point $(x_{n}, y_{n})$ and the target coordinates $(x_{2}, y_{2})$ can be covered moving with the speed $v_{max}$ in ${\\mathbf{}}T$ seconds assuming there is no wind. Time complexity is $O(l o g_{\\frac{C}{\\epsilon}}^{C})$, where $C$ stands for the maximum coordinate, and $ \\epsilon $ - desired accuracy.",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define mt make_tuple\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<pii> vpi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\n \ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    double x1, y1, x2, y2, v, t, vx, vy, wx, wy;\n    cin >> x1 >> y1 >> x2 >> y2 >> v >> t >> vx >> vy >> wx >> wy;\n    double L = 0.0, R = 1e9;\n    forn(its, 100) {\n        double M = 0.5 * (L + R);\n        double x = x1 + min(M, t) * vx + max(M - t, 0.0) * wx;\n        double y = y1 + min(M, t) * vy + max(M - t, 0.0) * wy;\n        (hypot(x - x2, y - y2) < v * M ? R : L) = M;\n    }\n    cout << R << '\\n';\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "binary search",
      "geometry",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "590",
    "index": "C",
    "title": "Three States",
    "statement": "The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.\n\nSince roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of $n$ rows and $m$ columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.\n\nYour task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.\n\nIt is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.",
    "tutorial": "Affirmation. Suppose we are given an undirected unweighted connected graph and three distinct chosen vertices $u$, $v$, $w$ of this graph. We state that at least one minimum connecting network for these three vertices has the following form: some vertex $c$ is chosen and the resulting network is obtained as a union of shortest paths from $c$ to each of the chosen vertices. Proof. One of the optimal subgraphs connecting these three vertices is always a tree. Really, we can take any connecting subgraph and while there are cycles remaining in it, take any cycle and throw away any edge of this cycle. Moreover, only vertices $u$, $v$ and $w$ are allowed to be leaves of this tree, as we can delete from the network any other leaves and the network will still be connected. If the tree has no more than three leaves, it has no more than one vertex with the degree greater than $2$. This vertex is $c$ from the statement above. Any path from $c$ to the leaves may obviously be replaced with the shortest path. Special case is than there is no node with the degree greater than $2$, meaning one of $u$, $v$ or $w$ lies on the shortest path connecting two other vertices. The solution is: find the shortest path from each of the chosen vertices to all other vertices, and then try every vertex of the graph as $c$. Time complexity is $O(|V| + |E|)$. To apply this solution to the given problem we should first build a graph, where cells of the table stand for the vertices and two vertices are connected by an edge, if the corresponding cells were neighboring. Now we should merge all vertices of a single state in one in order to obtain a task described in the beginning. Time complexity is a linear function of the size of the table $O(n{\\tilde{m}})$.",
    "code": "//#include <iostream>\n#include <fstream>\n#include <vector>\n#include <set>\n#include <map>\n#include <cstring>\n#include <string>\n#include <cmath>\n#include <cassert>\n#include <ctime>\n#include <algorithm>\n#include <sstream>\n#include <list>\n#include <queue>\n#include <deque>\n#include <stack>\n#include <cstdlib>\n#include <cstdio>\n#include <iterator>\n#include <functional>\n#include <bitset>\n#define mp make_pair\n#define pb push_back\n \n#ifdef LOCAL\n#define eprintf(...) fprintf(stderr,__VA_ARGS__)\n#else\n#define eprintf(...)\n#endif\n \n#define TIMESTAMP(x) eprintf(\"[\"#x\"] Time : %.3lf s.\\n\", clock()*1.0/CLOCKS_PER_SEC)\n#define TIMESTAMPf(x,...) eprintf(\"[\" x \"] Time : %.3lf s.\\n\", __VA_ARGS__, clock()*1.0/CLOCKS_PER_SEC)\n \n#if ( ( _WIN32 || __WIN32__ ) && __cplusplus < 201103L)\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n \nusing namespace std;\n \n#define TASKNAME \"C\"\n \n#ifdef LOCAL\nstatic struct __timestamper {\n    string what;\n    __timestamper(const char* what) : what(what){};\n    __timestamper(const string& what) : what(what){};\n    ~__timestamper(){\n        TIMESTAMPf(\"%s\", what.data());\n    }\n} __TIMESTAMPER(\"end\");\n#else \nstruct __timestamper {};\n#endif\n \ntypedef long long ll;\ntypedef long double ld;\n \nconst int MAXN = 1010;\nchar s[MAXN][MAXN];\nint n, m;\nint dist[3][MAXN][MAXN];\n \nconst int dx[4] = {0, 1, 0, -1};\nconst int dy[4] = {-1, 0, 1, 0};\n \nint main(){\n  #ifdef LOCAL\n    assert(freopen(TASKNAME\".in\",\"r\",stdin));\n    assert(freopen(TASKNAME\".out\",\"w\",stdout));\n  #endif\n \n  scanf(\"%d%d\",&n,&m);\n  for (int i = 0; i < n; i++)\n    scanf(\"%s\", s[i]);\n \n  memset(dist, -1, sizeof(dist));\n \n  for (int c = '1'; c <= '3'; c++) {\n    deque<pair<int, int>> q;\n    for (int i = 0; i < n; i++)\n      for (int j = 0; j < m; j++)\n        if (s[i][j] == c) {\n          dist[c - '1'][i][j] = 0;\n          q.push_back(make_pair(i, j));\n        }\n \n    while (!q.empty()) {\n      int x = q.front().first;\n      int y = q.front().second;\n      q.pop_front();\n      for (int i = 0; i < 4; i++) {\n        int nx = x + dx[i];\n        int ny = y + dy[i];\n        if (0 <= nx && nx < n && 0 <= ny && ny < m && s[nx][ny] != '#') {\n          int nd = dist[c - '1'][x][y] + (s[nx][ny] == '.');\n          if (dist[c - '1'][nx][ny] == -1 || dist[c - '1'][nx][ny] > nd) {\n            dist[c - '1'][nx][ny] = nd;\n            if (s[nx][ny] == '.') {\n              q.push_back(make_pair(nx, ny));\n            } else {\n              q.push_front(make_pair(nx, ny));\n            }\n          }\n        }\n      }\n    }\n  }\n  int ans = -1;\n  for (int i = 0; i < n; i++)\n    for (int j = 0; j < m; j++) {\n      if (dist[0][i][j] != -1 && dist[1][i][j] != -1 && dist[2][i][j] != -1) {\n        int nval = dist[0][i][j] + dist[1][i][j] + dist[2][i][j] - 2 * (s[i][j] == '.');\n        //fprintf(stderr, \"%d %d %d: %d %d %d\\n\", i, j, nval, dist[0][i][j], dist[1][i][j], dist[2][i][j]);\n        if (ans == -1 || ans > nval) {\n          ans = nval;\n        }\n      }\n    }\n  printf(\"%d\\n\", ans);\n  return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "590",
    "index": "D",
    "title": "Top Secret Task",
    "statement": "A top-secret military base under the command of Colonel Zuev is expecting an inspection from the Ministry of Defence. According to the charter, each top-secret military base must include a top-secret troop that should... well, we cannot tell you exactly what it should do, it is a top secret troop at the end. The problem is that Zuev's base is missing this top-secret troop for some reasons.\n\nThe colonel decided to deal with the problem immediately and ordered to line up in a single line all $n$ soldiers of the base entrusted to him. Zuev knows that the loquacity of the $i$-th soldier from the left is equal to $q_{i}$. Zuev wants to form the top-secret troop using $k$ leftmost soldiers in the line, thus he wants their total loquacity to be as small as possible (as the troop should remain top-secret). To achieve this, he is going to choose a pair of \\textbf{consecutive} soldiers and swap them. He intends to do so no more than $s$ times. Note that any soldier can be a participant of such swaps for any number of times. The problem turned out to be unusual, and colonel Zuev asked you to help.\n\nDetermine, what is the minimum total loquacity of the first $k$ soldiers in the line, that can be achieved by performing no more than $s$ swaps of two consecutive soldiers.",
    "tutorial": "If $s>{\\frac{n(n-1)}{2}}$, than the sum of $k$ minimums is obviously an answer. Let $i_{1} < i_{2} <$ ... $< i_{k}$ be the indices of the elements that will form the answer. Note, that the relative order of the chosen subset will remain the same, as there is no reason to swap two elements that will both be included in the answer. The minimum number of operations required to place this $k$ elements at the beginning is equal to $T=(i_{1}-1)+\\ldots+(i_{k}-k)=\\sum_{p=1}^{k}i_{p}$ - $\\frac{k\\cdot(k+1)}{2}$. $T$$ \\le $$S$ $\\longrightarrow\\bigcup$ $\\sum_{p=1}^{k}i_{p}$ $ \\le $ ${\\frac{k\\cdot(k+1)}{2}}+S$. $M={\\frac{k\\cdot(k+1)}{2}}+S$. Calculate the dynamic programming $d[i][j][p]$ &mdash minimum possible sum, if we chose $j$ elements among first $i$ with the total indices sum no greater than $p$. In order to optimize the memory consumption we will keep in memory only two latest layers of the dp. Time complexity is $O(n^{4})$, with $O(n^{3})$ memory consumption.",
    "code": "#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <algorithm>\n#include <iostream>\n#include <cstring>\n#include <vector>\n#include <set>\n#include <map>\n#include <cassert>\n#include <ctime>\n#include <string>\n#include <queue>\n \nusing namespace std;\n \n#ifdef _WIN32\n#define LLD \"%I64d\"\n#else\n#define LLD \"%lld\"\n#endif\n \ntypedef long double ld;\n \nlong long rdtsc() {\n  long long tmp;\n  asm(\"rdtsc\" : \"=A\"(tmp));\n  return tmp;\n}\n \ninline int myrand() {\n  return abs((rand() << 15) ^ rand());\n}\n \ninline int rnd(int x) {\n  return myrand() % x;\n}\n \n#define pb push_back\n#define mp make_pair\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#define sz(x) ((int)(x).size())\n#define TASKNAME \"text\"\n \nconst int INF = (int) 1.01e9;\nconst ld EPS = 1e-9;\n \nvoid precalc() {\n}\n \nint n, k, s;\n \nconst int maxn = 150 + 10;\nint a[maxn];\n \nbool read() {\n  if (scanf(\"%d%d%d\", &n, &k, &s) < 3) {\n    return 0;\n  }\n  for (int i = 0; i < n; ++i) {\n    scanf(\"%d\", a + i);\n  }\n  return 1;\n}\n \nint d[maxn][maxn * maxn];\nint nd[maxn][maxn * maxn];\n \nint getMaxc(int x, int t) {\n  return min(s, (x - t) * t);\n}\n \nvoid update(int &x, int val) {\n  x = min(x, val);\n}\n \nvoid solve() {\n  d[0][0] = 0;\n  for (int x = 0; x < n; ++x) {\n    for (int t = 0; t <= x + 1 && t <= k; ++t) {\n      int maxc = getMaxc(x + 1, t);\n      for (int c = 0; c <= maxc; ++c) {\n        nd[t][c] = INF;\n      }\n    }\n    for (int t = 0; t <= x && t <= k; ++t) {\n      int maxc = getMaxc(x, t);\n      for (int c = 0; c <= maxc; ++c) {\n        int &cur = d[t][c];\n        if (cur == INF) {\n          continue;\n        }\n        update(nd[t][c], cur);\n        update(nd[t + 1][c + (x - t)], cur + a[x]);\n      }\n    }\n    for (int t = 0; t <= x + 1 && t <= k; ++t) {\n      int maxc = getMaxc(x + 1, t);\n      for (int c = 0; c <= maxc; ++c) {\n        d[t][c] = nd[t][c];\n      }\n    }\n  }\n  int maxc = getMaxc(n, k);\n  int res = INF;\n  for (int c = 0; c <= maxc; ++c) {\n    res = min(res, d[k][c]);\n  }\n  printf(\"%d\\n\", res);\n}\n \nint main() {\n  srand(rdtsc());\n#ifdef DEBUG\n  freopen(TASKNAME\".out\", \"w\", stdout);\n  assert(freopen(TASKNAME\".in\", \"r\", stdin));\n#endif\n \n  precalc();\n  while (1) {\n    if (!read()) {\n      break;\n    }\n    solve();\n#ifdef DEBUG\n    eprintf(\"Time: %.18lf\\n\", (double)clock() / CLOCKS_PER_SEC);\n#endif\n  }\n  return 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "590",
    "index": "E",
    "title": "Birthday",
    "statement": "Today is birthday of a Little Dasha — she is now 8 years old! On this occasion, each of her $n$ friends and relatives gave her a ribbon with a greeting written on it, and, as it turned out, all the greetings are different. Dasha gathered all the ribbons and decided to throw away some of them in order to make the remaining set stylish. The birthday girl considers a set of ribbons stylish if no greeting written on some ribbon is a substring of another greeting written on some other ribbon. Let us recall that the substring of the string $s$ is a continuous segment of $s$.\n\nHelp Dasha to keep as many ribbons as possible, so that she could brag about them to all of her friends. Dasha cannot rotate or flip ribbons, that is, each greeting can be read in a single way given in the input.",
    "tutorial": "The given problem actually consists of two separate problems: build the directed graph of substring relation and find the maximum independent set in it. Note, that if the string $s_{2}$ is a substring of some string $s_{1}$, while string $s_{3}$ is a substring of the string $s_{2}$, then $s_{3}$ is a substring of $s_{1}$. That means the graph of substring relation defines a partially ordered set. To build the graph one can use Aho-Corasick algorithm. Usage of this structure allow to build all essential arc of the graph in time $O(L)$, where $L$ stands for the total length of all strings in the input. We will call the arc $u v\\in E$ essential, if there is no $w$, such that $u w\\in E$ and $w v\\in E$. One of the ways to do so is: Build Aho-Corasick using all strings in the input; For every node of the Aho-Corasick structure find and remember the nearest terminal node in the suffix-link path; Once again traverse all strings through Aho-Corasick. Every time new symbol is added, add an arc from the node corresponding to the current string (in the graph we build, not Aho-Corasick) to the node of the graph corresponding to the nearest terminal in the suffix-link path; The previous step will build all essential arcs plus some other arcs, but they do not affect the next step in any way; Find the transitive closure of the graph. To solve the second part of the problem one should use the Dilworth theorem. The way to restore the answer subset comes from the constructive proof of the theorem. Time complexity is $O(L + n^{3})$ to build the graph plus $O(n^{3})$ to find the maximum antichain. The overall complexity is $O(L + n^{3})$.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <cstring>\n#include <iostream>\n#include <cstdio>\n#include <queue>\n \nusing namespace std;\n \n#define FOR(i, a, b) for (int i = (a); i < (b); ++i)\n#define REP(i, n) FOR(i, 0, n)\n#define TRACE(x) cout << #x << \" = \" << x << endl\n#define _ << \" _ \" <<\n \ntypedef long long llint;\n \nconst int MAXN = 777;\nconst int MAX = 1e7 + 1000;\n \nbool e[MAXN][MAXN];\nbool matched[MAXN];\nint dad[MAXN];\n \nint bio[MAXN], cookie;\nint a[MAXN];\nint n;\n \nbool match(int x) {\n  if (x == -1) return true;\n  if (bio[x] == cookie) return false;\n  bio[x] = cookie;\n  REP(i, n)\n    if (e[x][i] && match(dad[i])) {\n      dad[i] = x;\n      return true;\n    }\n  return false;\n}\n \nbool was[MAXN][2];\nvoid dfs(int x, int side) {\n  if (was[x][side]) return;\n  was[x][side] = true;\n  REP(i, n) {\n    if (side == 0 && e[x][i]) dfs(i, 1);\n    if (side == 1 && dad[x] == i) dfs(i, 0);\n  }\n}\n \nchar* s[MAXN];\nint len[MAXN];\n \nstruct node {\n  node* fail;\n  node* parent;\n  node* to[2];\n  node* finfail;\n  int fin;\n  bool mark;\n  bool e;\n  node () { fail = 0; fin = -1; };\n} mem[MAX];\nnode* alloc = mem;\n \nnode* insert(node* x, char* s, int i) {\n  while (*s) {\n    int c = *s - 'a';\n    if (x->to[c] == 0) {\n      x->to[c] = alloc++;\n      x->to[c]->e = c;\n      x->to[c]->parent = x;\n    }\n    x = x->to[c];\n    s++;\n  }\n  x->fin = i;\n  return x;\n}\n \nvoid push_links(node *root) {\n  static node* Q[MAX];\n  int b, e;\n  b = e = 0;\n  Q[e++] = root;\n  while (b < e) {\n    node *x = Q[b++];\n    \n    REP(i, 2)\n      if (x->to[i]) Q[e++] = x->to[i];\n \n    if (x == root || x->parent == root) {\n      x->fail = root;\n      x->finfail = NULL;\n    } else {\n      x->fail = x->parent->fail;\n      while (x->fail != root && !x->fail->to[x->e]) x->fail = x->fail->fail;\n      if (x->fail->to[x->e]) x->fail = x->fail->to[x->e];\n      if (x->fail->fin != -1) {\n        x->finfail = x->fail;\n      } else {\n        x->finfail = x->fail->finfail;\n      }\n    }\n  }\n}\n \nint main(void) {\n  scanf(\"%d\", &n);\n \n  static char buf[MAX];\n  static node* w[MAXN];\n  char* cur = buf;\n \n  node* root = alloc++;\n  REP(i, n) {\n    scanf(\"%s\", cur);\n    s[i] = cur;\n    len[i] = strlen(cur);\n    cur += len[i] + 1;\n    w[i] = insert(root, s[i], i);\n  }\n  push_links(root);\n  \n  vector<int> eq[MAXN];\n  REP(i, n) REP(j, n)\n    if (w[i]->fin == i)\n      if (i != j && w[i] == w[j]) {\n        eq[i].push_back(j);\n      }\n \n \n  REP(i, n) {\n    node *cur = root;\n \n    REP(j, len[i]) {\n      while (cur != root && !cur->to[s[i][j]-'a']) cur = cur->fail;\n      if (cur->to[s[i][j]-'a']) cur = cur->to[s[i][j]-'a'];\n \n      node *x = cur;\n      if (x->fin == -1) x = x->finfail;\n      while (x && !e[i][x->fin]) {\n        e[i][x->fin] = true;\n        x = x->finfail;\n      }\n    }\n \n    REP(j, n)\n      if (e[i][j])\n        for (int k: eq[j]) e[i][k] = true;\n    e[i][i] = false;\n  }\n \n  REP(i, n) dad[i] = -1;\n \n  REP(i, n) {\n    cookie++;\n    matched[i] = match(i);\n  }\n \n  REP(i, n)\n    if (!matched[i]) dfs(i, 0);\n \n  bool vc[MAXN];\n  REP(i, n) vc[i] = false;\n  REP(i, n) {\n    if (matched[i] && !was[i][0]) vc[i] = true;\n    if (dad[i] != -1 && was[i][1]) vc[i] = true;\n  }\n  \n  vector<int> ans;\n  REP(i, n)\n    if (!vc[i]) ans.push_back(i);\n  \n  printf(\"%d\\n\", (int)ans.size());\n  for (int x: ans) printf(\"%d \", x+1);\n  printf(\"\\n\");\n  return 0;\n}",
    "tags": [
      "graph matchings",
      "strings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "591",
    "index": "A",
    "title": "Wizards' Duel",
    "statement": "Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length $l$. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of $p$ meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of $q$ meters per second.\n\nThe impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.\n\nSince Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.",
    "tutorial": "Let's start with determining the position of the first collision. Two impulses converge with a speed $p + q$, so the first collision will occur after $\\frac{L}{p{\\stackrel{\\sim}{+}}q}$ seconds. The coordinate of this collision is given by the formula $x_{1}=p\\cdot{\\frac{L}{p+q}}$. Note, that the distance one impulse passes while returning to it's caster is equal to the distance it has passed from the caster to the first collision. That means impulses will reach their casters simultaneously, and the situation will be identic to the beginning of the duel. Hence, the second collision (third, fourth, etc) will occur at exactly the same place as the first one.",
    "code": "#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<cmath>\n#include<algorithm>\n \n#define ll long long\n#define inf 1e9\n#define eps 1e-10\n#define md\n#define N\nusing namespace std;\n \nint main()\n{\n\tdouble len,a,b;\n\tscanf(\"%lf%lf%lf\",&len,&a,&b);\n\tprintf(\"%lf\\n\",len*(a/(a+b)));\n\treturn 0;\n}\n ",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "591",
    "index": "B",
    "title": "Rebranding",
    "statement": "The name of one small but proud corporation consists of $n$ lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.\n\nFor this purpose the corporation has consecutively hired $m$ designers. Once a company hires the $i$-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters $x_{i}$ by $y_{i}$, and all the letters $y_{i}$ by $x_{i}$. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that $x_{i}$ coincides with $y_{i}$. The version of the name received after the work of the last designer becomes the new name of the corporation.\n\nManager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.\n\nSatisfy Arkady's curiosity and tell him the final version of the name.",
    "tutorial": "Trivial solution will just emulate the work of all designers, every time considering all characters of the string one by one and replacing all $x_{i}$ with $y_{i}$ and vice versa. This will work in $O(n \\cdot m)$ and get TL. First one should note that same characters always end as a same characters, meaning the position of the letter doesn't affect the result in any way. One should only remember the mapping for all distinct characters. Let $p(i, c)$ be the mapping of $c$ after $i$ designers already finished their job. Now: $p(0, c) = c$ If $p(i - 1, c) = x_{i}$, then $p(i, c) = y_{i}$ Same, if $p(i - 1, c) = y_{i}$, then $p(i, c) = x_{i}$ This solution complexity is $O(| \\Sigma | \\cdot m + n)$ and is enough to pass all the tests.",
    "code": "#include <bits/stdc++.h>\n#define fi first\n#define sc second\nusing namespace std;\ntypedef pair<int,int> pi;\n \nchar s[300009];\nchar ch[30];\n \nint main(){\n    int n,m;scanf(\"%d%d\",&n,&m);\n    scanf(\"%s\",s);\n    for(int i=0;i<26;i++)ch[i]=i+'a';\n    for(int i=0;i<m;i++){\n        char a,b;scanf(\" %c %c\",&a,&b);\n        for(int j=0;j<26;j++){\n            if(ch[j]==a)ch[j]=b;\n            else if(ch[j]==b)ch[j]=a;\n        }\n    }\n    for(int i=0;i<n;i++){\n        printf(\"%c\",ch[s[i]-'a']);\n    }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "592",
    "index": "A",
    "title": "PawnChess",
    "statement": "Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».\n\nThis new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.\n\nLets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as $(r, c)$ the cell located at the row $r$ and at the column $c$.\n\nThere are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row $1$, while player B tries to put any of his pawns to the row $8$. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.\n\nPlayer A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.\n\nMoving upward means that the pawn located in $(r, c)$ will go to the cell $(r - 1, c)$, while moving down means the pawn located in $(r, c)$ will go to the cell $(r + 1, c)$. Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.\n\nGiven the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.",
    "tutorial": "Player A wins if the distance of his nearest pawn to the top of the board is less than or equal to the distance of the Player's B nearest pawn to the bottom of the board (Note that you should only consider pawns that are not blocked by another pawns).",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "592",
    "index": "B",
    "title": "The Monster and the Squirrel",
    "statement": "Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.\n\nAri draws a regular convex polygon on the floor and numbers it's vertices $1, 2, ..., n$ in clockwise order. Then starting from the vertex $1$ she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex $2, 3, ..., n$ (in this particular order). And then she puts a walnut in each region inside the polygon.\n\nAda the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q \\textbf{share a side or a corner}.\n\nAssuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?",
    "tutorial": "After drawing the rays from the first vertex $(n - 2)$ triangles are formed. The subsequent rays will generate independently sub-regions in these triangles. Let's analyse the triangle determined by vertices $1, i, i + 1$, after drawing the rays from vertex $i$ and $(i + 1)$ the triangle will be divided into $(n - i) + (i - 2) = n - 2$ regions. Therefore the total number of convex regions is $(n - 2)^{2}$ If the squirrel starts from the region that have $1$ as a vertex, then she can go through each region of triangle $(1, i, i + 1)$ once. That implies that the squirrel can collect all the walnuts in $(n - 2)^{2}$ jumps.",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "592",
    "index": "C",
    "title": "The Big Race",
    "statement": "Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of $L$ meters today.\n\nWillman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.\n\nWhile watching previous races the organizers have noticed that Willman can perform \\textbf{only} steps of length equal to $w$ meters, and Bolt can perform \\textbf{only} steps of length equal to $b$ meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes).\n\nNote that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete \\textbf{will not} fall into the abyss if the total length of all his steps will be less or equal to the chosen distance $L$.\n\nSince the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to $t$ (both are included). What is the probability that Willman and Bolt tie again today?",
    "tutorial": "Let D be the length of the racetrack, Since both athletes should tie $D\\mathrm{\\mod\\}B=D\\mathrm{\\mod\\}W$. Let $M = lcm(B, W)$, then $D = k \\cdot M + r$. None of the athletes should give one step further, therefore $r  \\le  min{B - 1, W - 1, T} = X$. $D$ must be greater than $0$ and less than or equal to $T$ so $- r / M < k  \\le  (T - r) / M$. For $r = 0$, the number of valid racetracks is $\\lfloor{\\frac{T}{M}}\\rfloor$, and for $r > 0$ the number of racetracks is $\\lfloor{\\frac{T-\\tau}{M}}\\rfloor+1$. Iterating over all possible r, we can count the number of racetracks in which Willman and Bolt ties: $X\\,+\\,\\sum_{r=0}^{x}\\bigl({\\frac{T-r}{M}}\\bigr)$ Note that $\\lfloor{\\frac{T-r}{M}}\\rfloor=v\\Leftrightarrow T-v\\cdot M-M<r\\leq T-v\\cdot M$. That means that $\\lfloor{\\frac{T-T}{M}}\\rfloor=v$ for exactly $M$ values of $r$. We can count the number of values of $r$ in which $\\lfloor{\\frac{T-r}{M}}\\rfloor=\\lfloor{\\frac{T-0}{M}}\\rfloor=v\\rfloor$, and the values of $r$ in which $\\lfloor{\\frac{T-T}{M}}\\rfloor=\\lfloor{\\frac{T-X}{M}}\\rfloor=v_{2}$. Each of the remaining values $v_{1} - 1, v_{1} - 2, ..., v_{2} + 1$ will appear exactly $M$ times.",
    "tags": [
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "592",
    "index": "D",
    "title": "Super M",
    "statement": "Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of $n$ cities, connected by $n - 1$ bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are $m$ cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces.\n\nHowever, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.\n\nYou are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.",
    "tutorial": "Observation 1: Ari should teleport to one of the attacked cities (it doesn't worth going to a city that is not attacked since then she should go to one of the attacked cities) Observation 2: The nodes visited by Ari will determine a sub-tree $T$ of the original tree, this tree is unique and is determined by all the paths from two attacked cities. Observation 3: If Ari had to return to the city from where she started, then the total distance would be $2e$, where $e$ is the number of edges of $T$, that is because she goes through each edge forward and backward Observation 4: If Ari does not have to return to the starting city (the root of $T$), then the total distance is $2e - L$, where $L$ is the distance of the farthest node from the root Observation 5: In order to get a minimum total distance, Ari should chose one diameter of the tree, and teleport to one of its leaves. The problem is now transformed in finding the diameter of a tree that contains the smallest index for one of its leaves. Note that all diameters pass through the center of the tree, so we can find all the farthest nodes from the center...and [details omitted].",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "592",
    "index": "E",
    "title": "BCPC",
    "statement": "BCPC stands for Byteforces Collegiate Programming Contest, and is the most famous competition in Byteforces.\n\nBCPC is a team competition. Each team is composed by a coach and three contestants. Blenda is the coach of the Bit State University(BSU), and she is very strict selecting the members of her team.\n\nIn BSU there are $n$ students numbered from 1 to $n$. Since all BSU students are infinitely smart, the only important parameters for Blenda are their reading and writing speed. After a careful measuring, Blenda have found that the $i$-th student have a \\textbf{reading} speed equal to $r_{i}$ (words per minute), and a \\textbf{writing} speed of $w_{i}$ (symbols per minute). Since BSU students are very smart, the measured speeds are sometimes very big and Blenda have decided to subtract some constant value $c$ from all the values of reading speed and some value $d$ from all the values of writing speed. Therefore she considers $r_{i}' = r_{i} - c$ and $w_{i}' = w_{i} - d$.\n\nThe student $i$ is said to overwhelm the student $j$ if and only if $r_{i}'·w_{j}' > r_{j}'·w_{i}'$. Blenda doesn’t like fights in teams, so she thinks that a team consisting of three distinct students $i, j$ and $k$ is good if $i$ overwhelms $j$, $j$ overwhelms $k$, and $k$ overwhelms $i$. Yes, the relation of overwhelming is not transitive as it often happens in real life.\n\nSince Blenda is busy preparing a training camp in Codeforces, you are given a task to calculate the number of different good teams in BSU. Two teams are considered to be different if there is at least one student that is present in one team but is not present in the other. In other words, two teams are different if the sets of students that form these teams are different.",
    "tutorial": "Let's represent the reading and writing speeds of the students as points in a plane. Two students $i, j$ are compatible if $ri' \\cdot wj' - rj' \\cdot wi' > 0$ this equation is identical to the cross product: $(ri', wi')  \\times  (rj', wj') > 0$. Using this fact is easy to see that three students $i, j, k$ are compatible if the triangle $(r_{i}, w_{i}), (r_{j}, w_{j}), (r_{k}, w_{k})$ contains the point $(x, y)$. So the problem is reduced to count the number of triangles that contains the origin. Let's count the triangles that have two known vertices $i$ and $j$ (look at the picture above). It is easy to see that the third vertex should be inside the region $S$. So now we have to be able of counting points that are between two rays, that can be done using binary search (ordering the points first by slope and then by the distance to the origin). Now given a point $i$, let's count the triangles that have $i$ as a vertex (look at the picture above again). We have to count the points that lie between the ray $iO$, and every other ray $jO$ (the angle between $iO$ and $jO$ must be $ \\le  180$). Let $S_{j}$ denote the number points that are between the rays $OR$ and $jO$, then the number of triangles that have $i$ as a vertex are $\\textstyle\\sum_{j:O i\\times O j>0}S_{j}-S_{i}$. This summation can be calculated if we pre-calculate the cumulative sums of $S_{j}$. The overall complexity is $O(n \\cdot log(n))$.",
    "tags": [
      "binary search",
      "geometry",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "593",
    "index": "A",
    "title": "2Char",
    "statement": "Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.\n\nSince the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.",
    "tutorial": "For each letter will maintain the total length of words ($cnt1_{ci}$), which found it was alone, and for each pair of letters will maintain the total length of words that contains only them ($cnt2_{ci, cj}$). For each row, count a number of different letters in it. If it is one, then add this letter to the length of the word. If two of them, then add to the pair of letters word`s length. Now find a pair of letters that will be the answer. For a pair of letters $c_{i}, c_{j}$ answer is $cnt1_{ci} + cnt1_{cj} + cnt2_{ci, cj}$. Among all these pairs find the maximum. This is the answer. The overall complexity is O (total length of all strings + 26 * 26)",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "593",
    "index": "B",
    "title": "Anton and Lines",
    "statement": "The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of $n$ lines defined by the equations $y = k_{i}·x + b_{i}$. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between $x_{1} < x_{2}$. In other words, is it true that there are $1 ≤ i < j ≤ n$ and $x', y'$, such that:\n\n- $y' = k_{i} * x' + b_{i}$, that is, point $(x', y')$ belongs to the line number $i$;\n- $y' = k_{j} * x' + b_{j}$, that is, point $(x', y')$ belongs to the line number $j$;\n- $x_{1} < x' < x_{2}$, that is, point $(x', y')$ lies inside the strip bounded by $x_{1} < x_{2}$.\n\nYou can't leave Anton in trouble, can you? Write a program that solves the given task.",
    "tutorial": "Note that if $a$ s line intersects with the $j$ th in this band, and at $x = x_{1}$ $i$ th line is higher, at $x = x_{2}$ above would be $j$ th line. Sort by $y$ coordinate at $x = x_{1} + eps$, and $x = x_{2} - eps$. Verify that the order of lines in both cases is the same. If there is a line that its index in the former case does not coincide with the second, output Yes. In another case, derive No. The only thing that can stop us is the intersection at the borders, as in this case we dont know the sorts order. Then add to our border $x_{1}$ small $eps$, and by $x_{2}$ subtract $eps$, and the sort order is set uniquely. The overall complexity is $O(nlogn)$",
    "tags": [
      "geometry",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "593",
    "index": "C",
    "title": "Beautiful Function",
    "statement": "Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the imagined circles.\n\nYesterday Ruslan tried to solve this problem for the case when the set of points is considered beautiful if it is given as $(x_{t} = f(t), y_{t} = g(t))$, where argument $t$ takes all integer values from $0$ to $50$. Moreover, $f(t)$ and $g(t)$ should be correct functions.\n\nAssume that $w(t)$ and $h(t)$ are some correct functions, and $c$ is an integer ranging from $0$ to $50$. The function $s(t)$ is correct if it's obtained by one of the following rules:\n\n- $s(t) = abs(w(t))$, where $abs(x)$ means taking the absolute value of a number $x$, i.e. $|x|$;\n- $s(t) = (w(t) + h(t))$;\n- $s(t) = (w(t) - h(t))$;\n- $s(t) = (w(t) * h(t))$, where $ * $ means multiplication, i.e. $(w(t)·h(t))$;\n- $s(t) = c$;\n- $s(t) = t$;\n\nYesterday Ruslan thought on and on, but he could not cope with the task. Now he asks you to write a program that computes the appropriate $f(t)$ and $g(t)$ for any set of at most $50$ circles.\n\nIn each of the functions $f(t)$ and $g(t)$ you are allowed to use no more than $50$ multiplications. The length of any function should not exceed $100·n$ characters. The function \\textbf{should not contain spaces.}\n\nRuslan can't keep big numbers in his memory, so you should choose $f(t)$ and $g(t)$, such that for all integer $t$ from $0$ to $50$ value of $f(t)$ and $g(t)$ and all the intermediate calculations won't exceed $10^{9}$ by their absolute value.",
    "tutorial": "One of the answers will be the amount of such expressions for each circle in the coordinate $x$ and similarly coordinate $y$: $\\lfloor{\\frac{x_{i}}{2}}\\rfloor\\ast(1-a b s(t-i)+a b s(a b s(t-i)-1))$ For $a = 1$, $b = abs(t - i)$, it can be written as $\\left\\lfloor{\\frac{x_{i}}{2}}\\right\\rfloor*(a-b+a b s(b-a))$ Consider the $a - b + abs(a - b)$: if $a  \\le  b$, then $a - b + abs(a - b) = 0$, if $a > b$, then $a - b + abs(a - b) = 2a - 2b$ Now consider what means $a > b$: $1 > abs(t - i)$ $i > t - 1$ and $i < t + 1$. For integer $i$ is possible only if $i = t$. That is, this bracket is not nullified only if $i = t$. Consider the $2a - 2b = 2 - 2 * abs(t - i) = 2$. Then $\\left\\lfloor{\\frac{x}{2}}\\right\\rfloor\\approx2$ differs from the wanted position by no more than 1, but since all the radiuses are not less than 2, then this point belongs to the circle. The overall complexity is $O(n)$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "593",
    "index": "D",
    "title": "Happy Tree Party",
    "statement": "Bogdan has a birthday today and mom gave him a tree consisting of $n$ vertecies. For every edge of the tree $i$, some number $x_{i}$ was written on it. In case you forget, a tree is a connected non-directed graph without cycles. After the present was granted, $m$ guests consecutively come to Bogdan's party. When the $i$-th guest comes, he performs exactly one of the two possible operations:\n\n- Chooses some number $y_{i}$, and two vertecies $a_{i}$ and $b_{i}$. After that, he moves along the edges of the tree from vertex $a_{i}$ to vertex $b_{i}$ using the shortest path (of course, such a path is unique in the tree). Every time he moves along some edge $j$, he replaces his current number $y_{i}$ by $y_{i}=\\lfloor{\\frac{y_{i}}{x_{j}}}\\rfloor$, that is, by the result of integer division $y_{i}$ div $x_{j}$.\n- Chooses some edge $p_{i}$ and replaces the value written in it $x_{pi}$ by some positive integer $c_{i} < x_{pi}$.\n\nAs Bogdan cares about his guests, he decided to ease the process. Write a program that performs all the operations requested by guests and outputs the resulting value $y_{i}$ for each $i$ of the first type.",
    "tutorial": "Consider the problem ignoring the second typed requests. We note that in the column where all the numbers on the edges of $>$ 1 maximum number of assignments to $x=\\lfloor{\\frac{x}{R_{e}}}\\rfloor$ before $x$ will turn into $0$ is not exceeds $64$. Indeed, if all the $R_{v} = 2$, the number of operations can be assessed as $log_{2}(x)$. Hang the tree for some top and call it the root. Learn how to solve the problem, provided that for every $v$ $R_{v} > 1$ and no requests of the second type. For each vertex except the root, we have identified it as the ancestor of the neighbor closest to the root. Suppose we had a request of the first type from the top $a$ to $b$ vertices with original number $x$. We divide the road into two vertical parts, one of which is close to the root, while the other moves away. We find all the edges in this way. To do this, we calculate the depth of each node to the root of the distance. Now we will go up in parallel to the tree of the two peaks, until he met a total. If in the course of the recovery, we have been more than $64$ edges, in the substitutions $x=\\lfloor{\\frac{x}{R_{e}}}\\rfloor$ we get $x = 0$ and we can at the current step to stop the algorithm search. Thus, we make no more than $O(log(x))$ operations. Let`s turn to the problem, where $R_{v} > 0$. We note that our previous solution in this case can work for $O(n)$. Since the passage of the edge with $R_{v} = 1$ our value does not change. We reduce this problem to the above consideration. Compress the graph, that is, remove all single edges. To do this, run by dfs root and will keep the deepest edge on the path from the root to the top with $R_{v} > 1$. Let us remember that we have had requests to reduce $R_{v}$. We maintain the closest ancestor of $P_{v}$ c $R_{Pv} > 1$. We use the idea of compression paths. When answer to a request of the first type will be recalculated $P_{v}$. We introduce a recursive function $F(v)$. Which returns the $v$, if $R_{v} > 1$, otherwise perform the assignment of $P_{v} = F(P_{v})$ and returns $F(P_{v})$. Each edge we will remove $1$ times, so in total the call of all functions $F(v)$ running $O(n)$. Final time is $O(logx)$ on request of the first type and $O(1)$ an average of request of the second type.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "593",
    "index": "E",
    "title": "Strange Calculation and Cats",
    "statement": "Gosha's universe is a table consisting of $n$ rows and $m$ columns. Both the rows and columns are numbered with consecutive integers starting with $1$. We will use $(r, c)$ to denote a cell located in the row $r$ and column $c$.\n\nGosha is often invited somewhere. Every time he gets an invitation, he first calculates the number of ways to get to this place, and only then he goes. Gosha's house is located in the cell $(1, 1)$.\n\nAt any moment of time, Gosha moves from the cell he is currently located in to a cell adjacent to it (two cells are adjacent if they share a common side). Of course, the movement is possible only if such a cell exists, i.e. Gosha will not go beyond the boundaries of the table. Thus, from the cell $(r, c)$ he is able to make a move to one of the cells $(r - 1, c)$, $(r, c - 1)$, $(r + 1, c)$, $(r, c + 1)$. Also, Ghosha can skip a move and stay in the current cell $(r, c)$.\n\nBesides the love of strange calculations, Gosha is allergic to cats, so he never goes to the cell that has a cat in it. Gosha knows exactly where and when he will be invited and the schedule of cats travelling along the table. Formally, he has $q$ records, the $i$-th of them has one of the following forms:\n\n- $1$, $x_{i}$, $y_{i}$, $t_{i}$ — Gosha is invited to come to cell $(x_{i}, y_{i})$ at the moment of time $t_{i}$. It is guaranteed that there is no cat inside cell $(x_{i}, y_{i})$ at this moment of time.\n- $2$, $x_{i}$, $y_{i}$, $t_{i}$ — at the moment $t_{i}$ a cat appears in cell $(x_{i}, y_{i})$. It is guaranteed that no other cat is located in this cell $(x_{i}, y_{i})$ at that moment of time.\n- $3$, $x_{i}$, $y_{i}$, $t_{i}$ — at the moment $t_{i}$ a cat leaves cell $(x_{i}, y_{i})$. It is guaranteed that there is cat located in the cell $(x_{i}, y_{i})$.\n\nGosha plans to accept only one invitation, but he has not yet decided, which particular one. In order to make this decision, he asks you to calculate for each of the invitations $i$ the number of ways to get to the cell $(x_{i}, y_{i})$ at the moment $t_{i}$. For every invitation, assume that Gosha he starts moving from cell $(1, 1)$ at the moment $1$.\n\nMoving between two neighboring cells takes Gosha exactly one unit of tim. In particular, this means that Gosha can come into the cell only if a cat sitting in it leaves the moment when Gosha begins his movement from the neighboring cell, and if none of the cats comes to the cell at the time when Gosha is in it.\n\nTwo ways to go from cell $(1, 1)$ to cell $(x, y)$ at time $t$ are considered distinct if for at least one moment of time from $1$ to $t$ Gosha's positions are distinct for the two ways at this moment. Note, that during this travel Gosha is allowed to visit both $(1, 1)$ and $(x, y)$ multiple times. Since the number of ways can be quite large, print it modulo $10^{9} + 7$.",
    "tutorial": "Learn how to solve the problem for small t. We use standard dynamic $dp_{x, y, t}$ = number of ways to get into the cell (x; y) at time t. Conversion is the sum of all valid ways to get into the cell (x; y) at time t - 1. Note that this dp can be counted by means of the construction of the power matrix. Head of the transition matrix, $T_{i, j} = 1$, if we can get out of the cell $i$ in a cell $j$. Suppose we had a vector G, where $G_{i}$ equal to the number of ways to get into the cell $i$. Then a new vector $G'$ by $dt$ second $G'$ = $G$ * $(T^{dt})$. So we learned to solve the problem without changes in O (log $dt * S^{3}$), where dt - at a time, S - area. Consider what happens when adding or removing a cat. When such requests varies transition matrix. Between these requests constant T, then we can construct a power matrix. Thus, at the moment of change is recalculated T, and between changes in the degree of erecting matrix. The decision is O ($m * S^{3}$ log $dt$), m - number of requests",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "594",
    "index": "A",
    "title": "Warrior and Archer",
    "statement": "In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.\n\nVova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.\n\nThere are $n$ ($n$ is always even) possible starting positions for characters marked along the $Ox$ axis. The positions are given by their distinct coordinates $x_{1}, x_{2}, ..., x_{n}$, two characters cannot end up at the same position.\n\nVova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by \\textbf{both} Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be $n - 2$). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.\n\nVova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.",
    "tutorial": "Let's sort the points by increasing $x$ coordinate and work with sorted points array next. Let's suppose that after optimal playing points numbered $l$ and $r$ ($l < r$) are left. It's true that the first player didn't ban any of the points numbered $i$ $l < i < r$, otherwise he could change his corresponding move to point $l$ or point $r$ (one could prove it doesn't depend on second player optimal moves) and change the optimal answer. It turns out that all the ${\\underset{^{\\frac{n}{2}}}{=}}$ points banned by the first player have numbers outside of $[l, r]$ segment, therefore $r-l\\leq{\\frac{n}{2}}$. We should notice that if the first player choosed any $[l, r]$ for $r-l={\\frac{n}{2}}$, he could always make the final points numbers located inside this segment. The second player wants to make $r-l={\\frac{n}{2}}$ (he couldn't make less), what is equivalent if he always ban points inside final $[l, r]$ segment (numbered $l < i < r$). As soon as the second player doesn't know what segment first player have chosen after every of his moves, he must detect a point which satisfies him in every first player choice. It's true number of this point is the median of set of point numbers left (the odd number) after the first player move. The number of moves of the first player left is lesser by one than moves of the second player, so the first player later could ban some points from the left and some points from the right, except three middle points. Two of it (leftmost and rightmost ones) shouldn't be banned by the second player as soon as it could increase the size of banned points from the left (or from the right), but third middle point satisfies the second player in every first player choice. This way the second player always bans the point inside final point segment. Thus the answer is the minimum between every of $x_{i+{\\frac{n}{2}}}-x_{i}$ values.",
    "tags": [
      "games"
    ],
    "rating": 2300
  },
  {
    "contest_id": "594",
    "index": "B",
    "title": "Max and Bike",
    "statement": "For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions.\n\nHe knows that this year $n$ competitions will take place. During the $i$-th competition the participant must as quickly as possible complete a ride along a straight line from point $s_{i}$ to point $f_{i}$ ($s_{i} < f_{i}$).\n\nMeasuring time is a complex process related to usage of a special sensor and a time counter. Think of the front wheel of a bicycle as a circle of radius $r$. Let's neglect the thickness of a tire, the size of the sensor, and all physical effects. The sensor is placed on the rim of the wheel, that is, on some fixed point on a circle of radius $r$. After that the counter moves just like the chosen point of the circle, i.e. moves forward and rotates around the center of the circle.\n\nAt the beginning each participant can choose \\textbf{any} point $b_{i}$, such that his bike is fully behind the starting line, that is, $b_{i} < s_{i} - r$. After that, he starts the movement, instantly accelerates to his maximum speed and at time $ts_{i}$, when the coordinate of the sensor is equal to the coordinate of the start, the time counter starts. The cyclist makes a complete ride, moving with his maximum speed and at the moment the sensor's coordinate is equal to the coordinate of the finish (moment of time $tf_{i}$), the time counter deactivates and records the final time. Thus, the counter records that the participant made a complete ride in time $tf_{i} - ts_{i}$.\n\nMaxim is good at math and he suspects that the total result doesn't only depend on his maximum speed $v$, but also on his choice of the initial point $b_{i}$. Now Maxim is asking you to calculate for each of $n$ competitions the minimum possible time that can be measured by the time counter. The radius of the wheel of his bike is equal to $r$.",
    "tutorial": "The main proposition to solve this problem - in the middle of every competition the sensor must be or in the top point of the wheel or in the bottom point of the wheel. To calculate the answer we need to use binary search. If the center of the wheel moved on the distance $c$, then the sensor moved on the distance $c + rsin(c / r)$, if the sensor was on the top point of the wheel in the middle, or on the distance $c - rsin(c / r)$, if the sensor was on the bottom point of the wheel in the middle, where $r$ - the radius of the wheel. Asymptotic behavior of this solution - $O(n\\log n)$.",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "594",
    "index": "C",
    "title": "Edo and Magnets",
    "statement": "Edo has got a collection of $n$ refrigerator magnets!\n\nHe decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be \\textbf{positive integers}.\n\nEdo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes.\n\nNow he wants to remove no more than $k$ magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of ​​the door should be as small as possible. A magnet is considered to be attached to the refrigerator door if \\textbf{its center} lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan.\n\nLet us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner ($x_{1}$, $y_{1}$) and the upper right corner ($x_{2}$, $y_{2}$), then its center is located at ($\\scriptstyle{\\frac{x_{1}+x_{2}}{2}}$, $\\textstyle{\\frac{y_{1}+y_{2}}{2}}$) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator.\n\n\\textbf{The sides of the refrigerator door must also be parallel to coordinate axes.}",
    "tutorial": "Let's find the centers of every rectangle and multiple them of 2 (to make all coordinates integers).Then we need to by the rectangle door, which contains all dots, but the lengths of the sides of this door must be rounded up to the nearest integers. Now, let's delete the magnets from the door one by one, gradually the door will decrease. Obviously every time optimal to delete only dots, which owned to the sides of the rectangle. Let's brute $4^{k}$ ways, how we will do delete the magnets. We will do it with helps of recursion, every time we will delete point with minimum or maximum value of the coordinates. If we will store 4 arrays (or 2 deques) we can do it with asymptotic $O(1)$. Such a solution works $O(4^{k})$. It can be easily shown that this algorithm delete always some number of the leftmost, rightmost, uppermost and lowermost points. So we can brute how $k$ will distributed between this values and we can model the deleting with helps of 4 arrays. This solution has asymptotic behavior $O(k^{4})$.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "594",
    "index": "D",
    "title": "REQ",
    "statement": "Today on a math lesson the teacher told Vovochka that the Euler function of a positive integer $φ(n)$ is an arithmetic function that counts the positive integers less than or equal to n that are relatively prime to n. The number $1$ is coprime to all the positive integers and $φ(1) = 1$.\n\nNow the teacher gave Vovochka an array of $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$ and a task to process $q$ queries $l_{i}$ $r_{i}$ — to calculate and print $\\varphi\\left(\\prod_{i=l}^{r}a_{i}\\right)$ modulo $10^{9} + 7$. As it is too hard for a second grade school student, you've decided to help Vovochka.",
    "tutorial": "To calculate the answer on every query let's use the formula $\\varphi(n)=n{\\frac{p_{1}-1}{p_{1}}}\\cdot{\\frac{p_{2}-1}{p_{2}}}\\cdot\\cdot\\cdot\\cdot{\\frac{p_{k}-1}{p_{k}}}$, where $p_{1}, p_{2}, ..., p_{k}$ - all prime numbers which divided $n$. We make all calculations by the module $10^{9} + 7$ Let's suppose that we solving problem for fix left end $l$ of the range. Every query now is a query on the prefix of the array. Then in formula for every prime $p$ we need to know only about the leftmost position of it. Let's convert the query in the query of the multiple on the prefix: at first init Fenwick tree with ones, then make the multiplication in points $l, l + 1, ..., n$ with value of the elements $a_{l}, a_{l + 1}, ..., a_{n}$. For every leftmost positions of prime $p$ make in position $i$ the multiplication in point $i$ on the $\\textstyle{\\frac{p-1}{p}}$. This prepare can be done with asymptotic $O(n\\log n\\log C)$, where C - the maximum value of the element (this logarithm - the number of prime divisors of some $a_{i}$). We interest in all leftmost ends, because of that let's know how to go from the one end to the other. Let we know all about the end $l$ - how to update the end $l + 1$? Let's make the multiplication in the Fenwick tree in the point $l$ on the value $a_{l}^{ - 1}$. Also we are not interesting in all prime numbers inside $a_{l}$, so let's make the multiplications in point $l$ on the all values $\\frac{p}{p\\!\\!\\!/-1}$. But every of this prime numbers can have other entries which now becoming the leftmost. Add them with the multiplication which described above. With helps of sort the transition between leftmost ends can be done in $O(n\\log n\\log C)$. To answer to the queries we need to sort them in correct order (or add them in the dynamic array), and to the get the answer to the query we will make $O(\\log n)$ iterations. So total asymptotic behavior of solution is $O(n\\log n\\log C+q\\log n)$ iterations and $O(n\\log C+q)$ additional memory.",
    "tags": [
      "data structures",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "594",
    "index": "E",
    "title": "Cutting the Line",
    "statement": "You are given a non-empty line $s$ and an integer $k$. The following operation is performed with this line exactly once:\n\n- A line is split into \\textbf{at most} $k$ non-empty substrings, i.e. string $s$ is represented as a concatenation of a set of strings $s = t_{1} + t_{2} + ... + t_{m}$, $1 ≤ m ≤ k$.\n- Some of strings $t_{i}$ are replaced by strings $t_{i}^{r}$, that is, their record from right to left.\n- The lines are concatenated back in the same order, we get string $s' = t'_{1}t'_{2}... t'_{m}$, where $t'_{i}$ equals $t_{i}$ or $t_{i}^{r}$.\n\nYour task is to determine the lexicographically smallest string that could be the result of applying the given operation to the string $s$.",
    "tutorial": "Let's describe the greedy algorithm, which allows to solve the problem for every $k > 2$ for every string $S$. Let's think, that we always reverse some prefix of the string $S$ (may be with length equals to one). Because we want to minimize lexicographically the string it is easy to confirm that we will reverse such a prefixes, which prefix (after reversing) is equals to the minimal lexicographically suffix of the reverse string $S$ (let it be $S^{r}$) - this is prefix, which length equals to the length of the minimum suffix $S^{r}$ (the reverse operation of the prefix $S$ equals to change it with suffix $S^{r}$). Let the lexicographically minimal suffix of the string $S^{r}$ is $s$. It can be shown, that there are no 2 entries $s$ in $S^{r}$ which intersects, because of that the string $s$ will be with period and minimal suffix will with less length. So, the string $S^{r}$ looks like $t_{p}s^{ap}t_{p - 1}s^{ap - 1}t_{p - 2}... t_{1}s^{a1}$, where $s^{x}$ means the concatenation of the string $s$ $x$ times, $a_{1}, a_{2}, ..., a_{p}$ - integers, and the strings $t_{1}, t_{2}, ..., t_{p}$ - some non-empty (exclude may be $t_{p}$) strings, which do not contain the $s$ inside. If we reverse some needed prefix of the string $s$, we will go to the string $S'$, and the minimal suffix $s'$ of the reversing string $S'^{r}$ can't be lexicographically less than $s$, because of that we need to make $s'$ equals to $s$. It will helps us to increase prefix which look like $s^{b}$ in the answer (and we will can minimize it too). it is easy to show, that maximum $b$, which we can get equals to $a_{1}$ in case $p = 1$ and $a_{1}+\\operatorname*{m}_{i=2}^{p}a_{p}$ (in case if p \\geq 2$). After such operations the prefix of the answer will looks like $s^{a1}s^{ai}t_{i}s^{ai - 1}... s^{a2}t_{2}$. Because t_{i} - non-empty strings we can not to increase the number of concatenations $s$ in the prefix of the answer. The reversing of the second prefix $(s^{ai}...)$ can be done because $k > 2$. From the information described above we know that if $k > 2$ for lost string we need always reverse prefix, which after reversing is equals to the suffix of the string $S^{r}$ which looks like $s^{a1}$. To find this suffix every time, we need only once to build Lindon decomposition (with helps of Duval's algorithm) of the reverse string and carefully unite the equals strings. Only one case is lost - prefix of the lost string does not need to be reverse - we can make the concatenation of the consecutive reverse prefixes with length equals to 1. Because for $k = 1$ the problem is very easy, we need to solve it for $k = 2$ - cut the string on the two pieces (prefix and suffix) and some way of their reverse. The case when nothing reverse is not interesting, let's look on other cases: Prefix do not reverse. In this case always reversing suffix. Two variants of the string with reverse suffix we can compare with $O(1)$ with helps of $z$-function of the string $S^{r}#S$. Prefix reverse. To solve this case we can use approvals from the editorial of the problem F Yandex.Algorithm 2015 Round 2.2 which was written by GlebsHP and check only 2 ways of reversing prefix. We need for them to brute the reverse of suffixes. It is only need in the end to choose from 2 cases better answer. Asymptotic behavior of the solution is $O(|s|)$.",
    "tags": [
      "string suffix structures",
      "strings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "595",
    "index": "A",
    "title": "Vitaly and Night",
    "statement": "One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.\n\nVitaly sees a building of $n$ floors and $2·m$ windows on each floor. On each floor there are $m$ flats numbered from $1$ to $m$, and two consecutive windows correspond to each flat. If we number the windows from $1$ to $2·m$ from left to right, then the $j$-th flat of the $i$-th floor has windows $2·j - 1$ and $2·j$ in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if \\textbf{at least one} of the windows corresponding to this flat has lights on.\n\nGiven the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.",
    "tutorial": "It was easy realization problem. Let's increase the variable $i$ from 1 to n, and inside let's increase the variable $j$ from 1 to $2 \\cdot m$. On every iteration we will increase the variable $j$ on 2. If on current iteration $a[i][j] = '1'$ or $a[i][j + 1] = '1'$ let's increase the answer on one. Asymptotic behavior of this solution - $O(nm)$.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "595",
    "index": "B",
    "title": "Pasha and Phone",
    "statement": "Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly $n$ digits.\n\nAlso Pasha has a number $k$ and two sequences of length $n / k$ ($n$ is divisible by $k$) $a_{1}, a_{2}, ..., a_{n / k}$ and $b_{1}, b_{2}, ..., b_{n / k}$. Let's split the phone number into blocks of length $k$. The first block will be formed by digits from the phone number that are on positions $1$, $2$,..., $k$, the second block will be formed by digits from the phone number that are on positions $k + 1$, $k + 2$, ..., $2·k$ and so on. Pasha considers a phone number good, if the $i$-th block doesn't start from the digit $b_{i}$ and is divisible by $a_{i}$ if represented as an integer.\n\nTo represent the block of length $k$ as an integer, let's write it out as a sequence $c_{1}$, $c_{2}$,...,$c_{k}$. Then the integer is calculated as the result of the expression $c_{1}·10^{k - 1} + c_{2}·10^{k - 2} + ... + c_{k}$.\n\nPasha asks you to calculate the number of good phone numbers of length $n$, for the given $k$, $a_{i}$ and $b_{i}$. As this number can be too big, print it modulo $10^{9} + 7$.",
    "tutorial": "Let's calculate the answer to every block separately from each other and multiply the answer to the previous blocks to the answer for current block. For the block with length equals to $k$ we can calculate the answer in the following way. Let for this block the number must be divided on $x$ and must not starts with digit $y$. Then the answer for this block - the number of numbers containing exactly $k$ digits and which divisible by $x$, subtract the number of numbers which have the first digit equals to $y$ and containing exactly $k$ digits and plus the number of numbers which have the first digit equals to $y - 1$ (only if $y > 0$) and containing exactly $k$ digits. Asymptotic behavior of this solution - $O(n / k)$.",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "596",
    "index": "A",
    "title": "Wilbur and Swimming Pool",
    "statement": "After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.\n\nNow Wilbur is wondering, if the remaining $n$ vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.",
    "tutorial": "It is a necessary and sufficient condition that we have exactly 2 distinct values for $x$ and $y$. If we have less than 2 distinct values for any variable, then there is no way to know the length of that dimension. If there are at least 3 distinct values for any variable, then that means more than 3 vertices lie on that dimension, which cannot happen since there can be at most 2 vertices in a line segment. The area, if it can be found, is just the difference of values of the $x$ coordinates times the difference of values of the $y$ coordinates. Complexity: $O(1)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint n;\nset<int> a, b;\n \nint value(set<int>& s) {\n    return (*s.rbegin())-(*s.begin());\n}\n \nint main(void) {\n    cin >> n;\n    for (int i=0; i<n; i++) {\n        int x, y;\n        cin >> x >> y;\n        a.insert(x);\n        b.insert(y);\n    }\n    if (a.size()!=2 || b.size()!=2)\n        cout << \"-1\\n\";\n    else\n        cout << value(a)*value(b) << \"\\n\";\n    return 0;\n}",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "596",
    "index": "B",
    "title": "Wilbur and Array",
    "statement": "Wilbur the pig is tinkering with arrays again. He has the array $a_{1}, a_{2}, ..., a_{n}$ initially consisting of $n$ zeros. At one step, he can choose any index $i$ and either add $1$ to all elements $a_{i}, a_{i + 1}, ... , a_{n}$ or subtract $1$ from all elements $a_{i}, a_{i + 1}, ..., a_{n}$. His goal is to end up with the array $b_{1}, b_{2}, ..., b_{n}$.\n\nOf course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.",
    "tutorial": "No matter what, we make $|b_{1}|$ operations to make $a_{1}$ equal to $b_{1}$. Once this is done, $a_{2}, a_{3}, ... a_{n} = b_{1}$. Then no matter what, we must make $|b_{2} - b_{1}|$ operations to make $a_{2}$ equal to $b_{2}$. In general, to make $a_{i} = b_{i}$ we need to make $|b_{i} - b_{i - 1}|$ operations, so in total we make $|b_{1}| + |b_{2} - b_{1}| + |b_{3} - b_{2}| + ... + |b_{n} - b_{n - 1}|$ operations. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n#define MAX_N 200010\n#define ll long long\nusing namespace std;\n \nint n;\nll arr[MAX_N], tot=0;\n \nint main(void) {\n    scanf(\"%d\",&n);\n    for (int i=0; i<n; i++) {\n        scanf(\"%lld\",arr+i);\n        if (i>0) tot+=abs(arr[i]-arr[i-1]);\n        else tot+=abs(arr[i]);\n    }\n    cout << tot << \"\\n\";\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "596",
    "index": "C",
    "title": "Wilbur and Points",
    "statement": "Wilbur is playing with a set of $n$ points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point ($x$, $y$) belongs to the set, then all points ($x'$, $y'$), such that $0 ≤ x' ≤ x$ and $0 ≤ y' ≤ y$ also belong to this set.\n\nNow Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from $1$ to $n$. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point ($x$, $y$) gets number $i$, then all ($x'$,$y'$) from the set, such that $x' ≥ x$ and $y' ≥ y$ must be assigned a number not less than $i$. For example, for a set of four points ($0$, $0$), ($0$, $1$), ($1$, $0$) and ($1$, $1$), there are two aesthetically pleasing numberings. One is $1$, $2$, $3$, $4$ and another one is $1$, $3$, $2$, $4$.\n\nWilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as $s(x, y) = y - x$. Now he gives Wilbur some $w_{1}$, $w_{2}$,..., $w_{n}$, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number $i$ has it's special value equal to $w_{i}$, that is $s(x_{i}, y_{i}) = y_{i} - x_{i} = w_{i}$.\n\nNow Wilbur asks you to help him with this challenge.",
    "tutorial": "Note that if there is an integer $d$ so that the number of $w_{i}$ equal to $d$ differs from the number of the given squares whose weight equals $d$, then the answer is automatically \"NO\". This can be easily checked by using a map for the $w_{i}$ and the weights of the squares and checking if the maps are the same. This step takes $O(n\\log(n))$ time. Let $d$ be an integer, and let $D$ be the set of all $i$ so that $w_{i} = d$. Let $W$ be the set of all special points $(x, y)$ so that the weight of $(x, y)$ is $d$. Note that $W$ and $D$ have the same number of elements. Suppose that $i_{1} < i_{2} < ... < i_{k}$ are the elements of $D$. Let $(a, b) < (c, d)$ if $a < c$ or $a = c$ and $b < d$. Suppose that $(x_{1}, y_{1}) < (x_{2}, y_{2}) < ... < (x_{k}, y_{k})$ are the elements of $W$. Note that the point $(x_{j}, y_{j})$ has to be labeled by $i_{j}$ for $1  \\le  j  \\le  k$. Now, each special point is labeled. It remains to check if this is a valid labeling. This can be done by taking an array of vectors. The vector $arr[i]$ will denote the points with $x$-coordinate $i$. This vector can be easily made from the points given in $O(n)$ time, and since the points are already labeled, $arr[i][j]$ will denote the label for the point $(i, j)$. Now, for all points $(i, j)$, the point $(i, j + 1)$ (if it is special) and the point $(i + 1, j)$ (if it is special) must have a greater number than $(i, j)$. This step takes a total of $O(n)$ time. Complexity: $O(n\\log(n))$",
    "code": "#include <bits/stdc++.h>\n#define MAX_N 100010\nusing namespace std;\n \nint n;\nmap<int,vector<pair<int,int> > > weights;\nmap<int,vector<int> > cnt;\npair<int,int> ans[MAX_N];\nvector<int> diag[MAX_N];\n \nint main(void) {\n    scanf(\"%d\",&n);\n    for (int i=0; i<n; i++) {\n        int a, b;\n        scanf(\"%d %d\",&a,&b);\n        while (diag[a].size()<=b) diag[a].push_back(0);\n        weights[b-a].push_back(make_pair(a,b));\n    }\n    for (auto& v: weights) {\n        sort(v.second.begin(),v.second.end());\n    }\n    for (int i=0; i<n; i++) {\n        int a;\n        cin >> a;\n        cnt[a].push_back(i);\n    }\n    for (auto v: cnt) {\n        if (weights.count(v.first)==0 || weights[v.first].size()!=v.second.size()) {\n            printf(\"NO\\n\");\n            return 0;\n        }\n        for (int i=0; i<v.second.size(); i++) {\n            ans[v.second[i]]=weights[v.first][i];\n            diag[weights[v.first][i].first][weights[v.first][i].second]=v.second[i];\n        }\n    }\n    for (int i=0; i<MAX_N; i++) {\n        for (int j=0; j<(int)diag[i].size(); j++) {\n            if ((int)diag[i+1].size()>j && diag[i+1][j]<diag[i][j]) {\n                printf(\"NO\\n\");\n                return 0;\n            }\n            if (j+1<(int)diag[i].size() && diag[i][j]>diag[i][j+1]) {\n                printf(\"NO\\n\");\n                return 0;\n            }\n        }\n    }\n    printf(\"YES\\n\");\n    for (int i=0; i<n; i++) {\n        printf(\"%d %d\\n\",ans[i].first,ans[i].second);\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "596",
    "index": "D",
    "title": "Wilbur and Trees",
    "statement": "Wilbur the pig really wants to be a beaver, so he decided today to pretend he is a beaver and bite at trees to cut them down.\n\nThere are $n$ trees located at various positions on a line. Tree $i$ is located at position $x_{i}$. All the given positions of the trees are distinct.\n\nThe trees are equal, i.e. each tree has height $h$. Due to the wind, when a tree is cut down, it either falls left with probability $p$, or falls right with probability $1 - p$. If a tree hits another tree while falling, that tree will fall in the same direction as the tree that hit it. A tree can hit another tree only if the distance between them is strictly less than $h$.\n\nFor example, imagine there are $4$ trees located at positions $1$, $3$, $5$ and $8$, while $h = 3$ and the tree at position $1$ falls right. It hits the tree at position $3$ and it starts to fall too. In it's turn it hits the tree at position $5$ and it also starts to fall. The distance between $8$ and $5$ is exactly $3$, so the tree at position $8$ will not fall.\n\nAs long as there are still trees standing, Wilbur will select either the leftmost standing tree with probability $0.5$ or the rightmost standing tree with probability $0.5$. Selected tree is then cut down. If there is only one tree remaining, Wilbur always selects it. As the ground is covered with grass, Wilbur wants to know the expected total length of the ground covered with fallen trees after he cuts them all down because he is concerned about his grass-eating cow friends. Please help Wilbur.",
    "tutorial": "Let us solve this problem using dynamic programming. First let us reindex the trees by sorting them by $x$-coordinate. Let $f(i, j, b_{1}, b_{2})$ where we would like to consider the problem of if we only have trees $i... j$ standing where $b_{1} = 1$ indicates that tree $i - 1$ falls right and $b_{1} = 0$ if it falls left and $b_{2} = 1$ indicates that tree $j + 1$ falls right and $b_{2} = 0$ if it falls left. We start with the case that Wilbur chooses the left tree and it falls right. The plan is to calculate the expected length in this scenario and multiply by the chance of this case occurring, which is $\\frac{(1-p)}{2}$. We can easily calculate what is the farthest right tree that falls as a result of this and call it $w_{i}$. Then if $w_{i} > = j$ this means the entire segment falls, from which the length of the ground covered by trees in $i... j$ can be calculated. However, be careful when $b_{2} = 0$, as there may be overlapping covered regions when the tree $j$ falls right but the tree $j + 1$ falls left. If only $w_{i} < j$, then we just consider adding the length of ground covered by trees $i... w_{i}$ falling right and add to the value of the subproblem $f(w_{i + 1}, j, 1, b_{2})$. There is another interesting case where Wilbur chooses the left tree and it falls left. In this case we calculate the expected length and multiply by the chance of this occurring, which is $\\frac{p}{2}$. The expected length of ground covered by the trees here is just the length contributed by tree $i$ falling left, which we must be careful calculating as there might be overlapping covered regions with the $i$th tree falling left and the $i - 1$th tree falling right. Then we also add the value of subproblem $f(i + 1, j, 0, b_{2})$. Doing this naively would take $O(n^{3})$ time, but this can be lowered to $O(n^{2})$ by precalculating what happens when tree $i$ falls left or right. We should also consider the cases that Wilbur chooses the right tree, but these cases are analogous by symmetry. Complexity: $O(n^{2})$",
    "code": "#include <bits/stdc++.h>\n#define MAX_N 2010\n#define INF 500000000\nusing namespace std;\n \nint n, h, arr[MAX_N], sz[2][MAX_N];\ndouble dp[MAX_N][MAX_N][2][2], p;\n \ndouble compute(int lef, int rig, int fl, int fr) {\n    // 0 means fall left, 1 means fall right\n    if (lef>rig) return 0;\n    if (dp[lef][rig][fl][fr]!=-1) return dp[lef][rig][fl][fr];\n    dp[lef][rig][fl][fr]=0;\n    double ans=0;\n    // wilbur chooses left\n    // falls right\n    int nl=min(rig,lef+sz[0][lef]-1);\n    if (nl==rig) {\n        if (fr==0) ans+=(1-p)*(min(h,arr[rig+1]-arr[rig]-h)+arr[rig]-arr[lef]);\n        else ans+=(1-p)*(min(h,arr[rig+1]-arr[rig])+arr[rig]-arr[lef]);\n    }\n    else {\n        ans+=(1-p)*compute(nl+1,rig,1,fr);\n        ans+=(1-p)*(arr[nl]-arr[lef]+h);\n    }\n    // falls left\n    if (fl==1) {\n        ans+=p*min(h,arr[lef]-arr[lef-1]-h);\n    }\n    else {\n        ans+=p*min(h,arr[lef]-arr[lef-1]);\n    }\n    ans+=p*compute(lef+1,rig,0,fr);\n    // wilbur chooses right\n    // falls left\n    int nr=max(lef,rig-sz[1][rig]+1);\n    if (nr==lef) {\n        if (fl==1) ans+=p*(min(h,arr[lef]-arr[lef-1]-h)+arr[rig]-arr[lef]);\n        else ans+=p*(min(h,arr[lef]-arr[lef-1])+arr[rig]-arr[lef]);\n    }\n    else {\n        ans+=p*compute(lef,nr-1,fl,0);\n        ans+=p*(arr[rig]-arr[nr]+h);\n    }\n    // falls right\n    if (fr==0) {\n        ans+=(1-p)*min(h,arr[rig+1]-arr[rig]-h);\n    }\n    else {\n        ans+=(1-p)*min(h,arr[rig+1]-arr[rig]);\n    }\n    ans+=(1-p)*compute(lef,rig-1,fl,1);\n    // divide by 2 for equiprobably choosing left or right\n    ans/=2.0;\n    dp[lef][rig][fl][fr]=ans;\n    return ans;\n}\n \nint main(void) {\n    for (int i=0; i<MAX_N; i++) {\n        for (int j=0; j<MAX_N; j++) {\n            for (int k=0; k<2; k++) {\n                for (int l=0; l<2; l++) {\n                    dp[i][j][k][l]=-1;\n                }\n            }\n        }\n    }\n    cin >> n >> h >> p;\n    for (int i=0; i<n; i++) {\n        cin >> arr[i];\n    }\n    arr[n]=INF;\n    arr[n+1]=-INF;\n    n+=2;\n    sort(arr,arr+n);\n    sz[1][0]=1;\n    for (int i=1; i<n; i++) {\n        if (arr[i]-arr[i-1]<h) sz[1][i]=sz[1][i-1]+1;\n        else sz[1][i]=1;\n    }\n    sz[0][n]=1;\n    for (int i=n-1; i>=0; i--) {\n        if (arr[i+1]-arr[i]<h) sz[0][i]=sz[0][i+1]+1;\n        else sz[0][i]=1;\n    }\n    printf(\"%.9f\\n\",compute(1,n-2,0,1));\n    return 0;\n}",
    "tags": [
      "dp",
      "math",
      "probabilities",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "596",
    "index": "E",
    "title": "Wilbur and Strings",
    "statement": "Wilbur the pig now wants to play with strings. He has found an $n$ by $m$ table consisting only of the digits from $0$ to $9$ where the rows are numbered $1$ to $n$ and the columns are numbered $1$ to $m$. Wilbur starts at some square and makes certain moves. If he is at square ($x$, $y$) and the digit $d$ ($0 ≤ d ≤ 9$) is written at position ($x$, $y$), \\textbf{then he must} move to the square ($x + a_{d}$, $y + b_{d}$), if that square lies within the table, and he stays in the square ($x$, $y$) otherwise. Before Wilbur makes a move, he can choose whether or not to write the digit written in this square on the white board. All digits written on the whiteboard form some string. Every time a new digit is written, it goes to the end of the current string.\n\nWilbur has $q$ strings that he is worried about. For each string $s_{i}$, Wilbur wants to know whether there exists a starting position ($x$, $y$) so that by making finitely many moves, Wilbur can end up with the string $s_{i}$ written on the white board.",
    "tutorial": "Solution 1: Suppose that $s$ is a string in the query. Reverse $s$ and the direction of all the moves that can be made on the table. Note that starting at any point that is part of a cycle, there is a loop and then edges that go out of the loop. So, for every point, it can be checked by dfs whether the $s$ can be made by starting at that point by storing what is in the cycle. Moreover, note that in the reversed graph, each point can only be a part of one cycle. Therefore, the total time for the dfs in a query is $O(nm \\cdot SIGMA + |s|)$. This is good enough for $q$ queries to run in time. Complexity: $O(n m q\\cdot S I G M A+\\sum_{i}|s_{i}|)$ where $SIGMA = 10$ is the number of distinct characters in the table, and $s_{i}$ is the query string for the $i$ th query. Solution 2 (Actually too slow, see comment by waterfalls below for more details): For each string $s$, dfs from every node that has in degree equal to $0$ in the original graph. There will be a path which leads into a cycle after which anything in the cycle can be used any number of times in $s$. Only every node with in degree equal to $0$ has to be checked because every path which leads to a cycle is part of a larger path which starts with a vertex of in degree $0$ that leads into a cycle. This solution is slower, but it works in practice since it is really hard for a string to match so many times in the table. Each query will take $O(n^{2} \\cdot m^{2} + s_{i})$ time, but it is much faster in practice. Complexity: $O(n^{2}m^{2}q\\cdot S I G M A+\\sum_{i}|s_{i}|)$ where $SIGMA = 10$ is the number of distinct characters in the table, and $s_{i}$ is the query string of the $i$ th query.",
    "code": "#include <bits/stdc++.h>\n#define MAX_N 210\n#define SIGMA 10\n#define MLEN 1000010\nusing namespace std;\n \nint n, m, q, values[MAX_N*MAX_N];\nint x[SIGMA], y[SIGMA], nxt[MAX_N*MAX_N];\n \nbool in_cycle[MAX_N*MAX_N];\nint vis[MAX_N*MAX_N], num_cyc=0, idx[MAX_N*MAX_N];\nbool has[MAX_N*MAX_N][SIGMA], vis2[MAX_N*MAX_N];\nint first_val[SIGMA];\n \nvector<int> rev[MAX_N*MAX_N], cycles[MAX_N*MAX_N];\n \nvoid dfs_cycles(int a) {\n    if (vis[a]==2) return ;\n    if (vis[a]==1) {\n        in_cycle[a]=true;\n        vis[a]=2;\n        return ;\n    }\n    vis[a]=1;\n    dfs_cycles(nxt[a]);\n    vis[a]=2;\n}\n \nvoid getcycles() {\n    memset(vis,0,sizeof(vis));\n    memset(vis2,0,sizeof(vis2));\n    memset(in_cycle,0,sizeof(in_cycle));\n    memset(has,0,sizeof(has));\n    for (int i=0; i<n; i++) {\n        dfs_cycles(i);\n        if (in_cycle[i] && !vis2[i]) {\n            int j=i;\n            do {\n                in_cycle[j]=true;\n                vis2[j]=true;\n                idx[j]=num_cyc;\n                has[num_cyc][values[j]]=true;\n                cycles[num_cyc].push_back(j);\n                j=nxt[j];\n            } while (j!=i);\n            num_cyc++;\n        }\n    }\n}\n \nvoid reverse_graph() {\n    for (int i=0; i<n; i++) {\n        if (!in_cycle[i]) {\n            rev[nxt[i]].push_back(i);\n        }\n    }\n}\n \nbool dfs_query(int a, int pos, string& s) {\n    if (pos<s.length() && values[a]==s[pos]-'0') pos++;\n    if (pos==s.length()) return true;\n    vis2[a]=true;\n    for (auto val: rev[a]) {\n        if (dfs_query(val,pos,s)) return true;\n    }\n    return false;\n}\n \nvoid query(string& s) {\n    memset(vis2,0,sizeof(vis2));\n    for (int i=0; i<n; i++) {\n        if (in_cycle[i] && !vis2[i]) {\n            int pos=-1;\n            for (int j=0; j<SIGMA; j++) {\n                if (first_val[j]!=-1 && !has[idx[i]][j]) {\n                    if (pos==-1) pos=first_val[j];\n                    else pos=min(pos,first_val[j]);\n                }\n            }\n            if (pos==-1) {\n                cout << \"YES\\n\";\n                return ;\n            }\n            for (int j: cycles[idx[i]]) {\n                if (dfs_query(j,pos,s)) {\n                    cout << \"YES\\n\";\n                    return ;\n                }\n            }\n        }\n    }\n    cout << \"NO\\n\";\n}\n \nint main(void) {\n    char ex[MAX_N][MAX_N];\n    cin >> n >> m >> q;\n    for (int i=0; i<n; i++) {\n        for (int j=0; j<m; j++) {\n            cin >> ex[i][j];\n            values[m*i+j]=ex[i][j]-'0';\n        }\n    }\n    for (int i=0; i<SIGMA; i++) {\n        cin >> x[i] >> y[i];\n    }\n    for (int i=0; i<n; i++) {\n        for (int j=0; j<m; j++) {\n            int ni=i+x[values[m*i+j]], nj=j+y[values[m*i+j]];\n            if (ni<0 || nj<0 || ni>=n || nj>=m) {\n                ni=i;\n                nj=j;\n            }\n            nxt[m*i+j]=ni*m+nj;\n        }\n    }\n    n*=m;\n    getcycles();\n    reverse_graph();\n    for (int i=0; i<q; i++) {\n        memset(first_val,-1,sizeof(first_val));\n        string s=\"\", t;\n        cin >> t;\n        for (int j=0; j<t.length(); j++) {\n            s+=t[t.length()-1-j];\n            first_val[t[j]-'0']=t.length()-1-j;\n        }\n        query(s);\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "599",
    "index": "A",
    "title": "Patrick and Shopping",
    "statement": "Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a $d_{1}$ meter long road between his house and the first shop and a $d_{2}$ meter long road between his house and the second shop. Also, there is a road of length $d_{3}$ directly connecting these two shops to each other. Help Patrick calculate the minimum distance that he needs to walk in order to go to both shops and return to his house.\n\nPatrick always starts at his house. He should visit both shops moving only along the three existing roads and return back to his house. He doesn't mind visiting the same shop or passing the same road multiple times. The only goal is to minimize the total distance traveled.",
    "tutorial": "Everything that you needed to do - solve some similar cases. You need to check the following cases: Home $\\to$ the first shop $\\to$ the second shop $\\to$ home Home $\\to$ the first shop $\\to$ the second shop $\\to$ the first shop $\\to$ home Home $\\to$ the second shop $\\to$ home $\\to$ the first shop $\\to$ home Home $\\to$ the second shop $\\to$ the first shop $\\to$ the second shop $\\to$ home Time: $O(1)$",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "599",
    "index": "B",
    "title": "Spongebob and Joke",
    "statement": "While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence $a_{1}, a_{2}, ..., a_{m}$ of length $m$, consisting of integers from $1$ to $n$, not necessarily distinct. Then he picked some sequence $f_{1}, f_{2}, ..., f_{n}$ of length $n$ and for each number $a_{i}$ got number $b_{i} = f_{ai}$. To finish the prank he erased the initial sequence $a_{i}$.\n\nIt's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.",
    "tutorial": "First of all, you should read the statement carefully. Then, for every element 1 $...$ $N$ create a list of integers from what we can get this number. After that you have to check some cases, before that create a special mark for answer Ambiguity: Let current element of the given array is $b_{i}$ If two or more elements exist from which it's possible to get $b_{i}$, then use your special mark that answer is Ambiguity If no elements exist from which it's possible to get $b_{i}$, then print Impossible If only one element exists from which it's possible to get $b_{i}$ just change $b_{i}$ to the value of this element Finally, if you marked your special mark then print Ambiguity, else print Possible and correct answer. Time: $O(N)$",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "599",
    "index": "C",
    "title": "Day at the Beach",
    "statement": "One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.\n\nAt the end of the day there were $n$ castles built by friends. Castles are numbered from $1$ to $n$, and the height of the $i$-th castle is equal to $h_{i}$. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition $h_{i} ≤ h_{i + 1}$ holds for all $i$ from $1$ to $n - 1$.\n\nSquidward suggested the following process of sorting castles:\n\n- Castles are split into blocks — groups of \\textbf{consecutive} castles. Therefore the block from $i$ to $j$ will include castles $i, i + 1, ..., j$. A block may consist of a single castle.\n- The partitioning is chosen in such a way that every castle is a part of \\textbf{exactly} one block.\n- Each block is sorted independently from other blocks, that is the sequence $h_{i}, h_{i + 1}, ..., h_{j}$ becomes sorted.\n- The partitioning should satisfy the condition that after each block is sorted, the sequence $h_{i}$ becomes sorted too. This may always be achieved by saying that the whole sequence is a single block.\n\nEven Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.",
    "tutorial": "Let's take a minute to see how the best answer should look like. Let $H_{i}$ be a sorted sequence of $h_{i}$. Let $E$ - set of indices of the last elements of each block. Then $\\dot{\\mathbf{v}}$ $e$ $\\underline{{\\land}}$ $E$, first $e$ sorted elements of sequence $h_{i}$ are equal to the first $e$ elements of the sequence $H_{j}$. So, it is not difficult to notice that the size of $E$ is the answer for the problem. Firstly, we need to calculate two arrays: $prefmax$ and $suffmin$, where $prefmax_{i}$ - maximum between $a_{1}$, $a_{2}$, $...$, $a_{i}$, and $suffmin_{i}$ - minimum between $a_{i}$, $a_{i + 1}$, $...$, $a_{n}$. If you want to get the answer, just calculate the number of indices $i$ that $prefmax_{i}$ $ \\le $ $suffmin_{i + 1}$. Time: $O(N)$",
    "tags": [
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "599",
    "index": "D",
    "title": "Spongebob and Squares",
    "statement": "Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly $x$ distinct squares in the table consisting of $n$ rows and $m$ columns. For example, in a $3 × 5$ table there are $15$ squares with side one, $8$ squares with side two and $3$ squares with side three. The total number of distinct squares in a $3 × 5$ table is $15 + 8 + 3 = 26$.",
    "tutorial": "First of all, let's solve this problem for $n  \\le  m$, and then just swap $n$ and $m$ and print the answer. Important! Not to print squares twice! We can use this formula for fixed $n$ & $m$ $(n  \\le  m)$ for calculating the value of $x$. $x=\\sum_{i=0}^{n-1}(n-i)*(m-i)\\Leftrightarrow x=\\textstyle{\\sum_{i=0}^{n-1}(n*m-i*(n+m)+i^{2}})$ Then $x=n^{2}*m-(n+m)*\\sum_{i=0}^{n-1}i+\\sum_{i=0}^{n-1}i^{2}$ Using the sum squares and the sum of the first $k$ numbers we can easily solve this problem. Getting $6x = 6n^{2} * m - 3(n^{2} + n^{3} - nm - n^{2}) + 2n^{3} - 3n^{3} + n = 3 * m * n^{2} + 3 * m * n - n^{3} + n$ As we solved this task for $n  \\le  m$ the $3n^{2} * m =  \\approx  n^{3}$, it means that $n$ is not greater than $2{\\stackrel{\\partial{\\sqrt{X}}}}$. Time: $O({\\overset{\\land}{\\lor}}{\\overline{{X}}})$",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "599",
    "index": "E",
    "title": "Sandy and Nuts",
    "statement": "Rooted tree is a connected graph without any simple cycles with one vertex selected as a root. In this problem the vertex number $1$ will always serve as a root.\n\nLowest common ancestor of two vertices $u$ and $v$ is the farthest from the root vertex that lies on both the path from $u$ to the root and on path from $v$ to the root. We will denote it as $LCA(u, v)$.\n\nSandy had a rooted tree consisting of $n$ vertices that she used to store her nuts. Unfortunately, the underwater storm broke her tree and she doesn't remember all it's edges. She only managed to restore $m$ edges of the initial tree and $q$ triples $a_{i}$, $b_{i}$ and $c_{i}$, for which she supposes $LCA(a_{i}, b_{i}) = c_{i}$.\n\nHelp Sandy count the number of trees of size $n$ with vertex $1$ as a root, that match all the information she remembered. If she made a mess and there are no such trees then print $0$. Two rooted trees are considered to be distinct if there exists an edge that occur in one of them and doesn't occur in the other one.",
    "tutorial": "The solution for this problem is dynamic programming. Let $f_{root, mask}$ is the number of ways to build a tree with root in vertex $root$ using vertices from the mask $mask$ and all restrictions were met. For convenience we shall number the vertices from zero. The answer is $f_{0, 2^{n} - 1}$. Trivial states are the states where a mask has only one single bit. In such cases $f_{root, mask} = 1$. Let's solve this task recursively with memorization. To make the transition, we need to choose some kind of mask $newMask$, which is necessarily is the submask of mask $mask$. Then we should try to find new root $newRoot$ in mask $newMask$. Also, in order not to count the same tree repeatedly impose conditions on the mask $newMask$. Namely, we shall take only such masks $newMask$, in which the senior bit (not in charge of the $root$) coincides with a senior bit (not in charge of the $root$) of the mask $mask$. After that, you need to check the fulfillment of all conditions to the edges and to the lca. If everything is OK, update $f_{r o o t,m a s k}+=f_{n e w R o v t,n e w M a s k}*f_{r o o t,m a s k}\\oplus n e w M a s k$. Where $\\bigoplus$ means $xor$. What about checking lca, it's possible to do it in time $O(N^{2})$ - previously memorized lca for each pair or in the worst case in time $O(Q)$ just iterating through all pairs of vertices, for which some vertex $v$ is lca. Time: $O(3^{N} \\cdot N^{3})$ or $O(3^{N} \\cdot N \\cdot Q)$",
    "tags": [
      "bitmasks",
      "dp",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "600",
    "index": "A",
    "title": "Extract Numbers",
    "statement": "You are given string $s$. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string \"aba,123;1a;0\": \"aba\", \"123\", \"1a\", \"0\". A word can be empty: for example, the string $s$=\";;\" contains three empty words separated by ';'.\n\nYou should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string $a$. String $a$ should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string $s$). By all other words you should build string $b$ in the same way (the order of numbers should remain the same as in the string $s$).\n\nHere strings \"101\", \"0\" are INTEGER numbers, but \"01\" and \"1.0\" are not.\n\nFor example, for the string aba,123;1a;0 the string $a$ would be equal to \"123,0\" and string $b$ would be equal to \"aba,1a\".",
    "tutorial": "This is a technical problem. You should do exactly what is written in problem statement.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "600",
    "index": "B",
    "title": "Queries about less or equal elements",
    "statement": "You are given two arrays of integers $a$ and $b$. For each element of the second array $b_{j}$ you should find the number of elements in array $a$ that are less than or equal to the value $b_{j}$.",
    "tutorial": "Let's sort all numbers in a. Now let's iterate over elements of $b$ and for element $b_{j}$ find the index of lowest number that is greater than $b_{j}$. We can do that using binary search. That index will be the answer for value $b_{j}$. Complexity: $O(nlogn)$.",
    "tags": [
      "binary search",
      "data structures",
      "sortings",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "600",
    "index": "C",
    "title": "Make Palindrome",
    "statement": "A string is called palindrome if it reads the same from left to right and from right to left. For example \"kazak\", \"oo\", \"r\" and \"mikhailrubinchikkihcniburliahkim\" are palindroms, but strings \"abb\" and \"ij\" are not.\n\nYou are given string $s$ consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in $s$. Then you can permute the order of letters as you want. Permutation doesn't count as changes.\n\nYou should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.",
    "tutorial": "Let's denote $cnt_{c}$ - the number of occurences of symbol $c$. Let's consider odd values $cnt_{c}$. Palindrome can not contain more than one symbol $c$ with odd $cnt_{c}$. Let's denote symbols with odd $cnt_{c}$ as $a_{1}, a_{2}...a_{k}$ (in alphabetical order). Let's replace any one of symbols $a_{k}$ with symbol $a_{1}$, $a_{k - 1}$ with $a_{2}$ and so on until the middle of $a$. Now we have no more than one odd symbol. If we have some let's place it in the middle of the answer. First half of answer will contain $\\frac{c r n\\dot{t}_{\\mathcal{C}}}{2}$ occurences of symbol $c$ in alphabetical order. The second half will contain the same symbols in reverse order. For example for string $s = aabcd$ at first we will replace $d$ by Unable to parse markup [type=CF_TEX] Compexity: $O(n)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "600",
    "index": "D",
    "title": "Area of Two Circles' Intersection",
    "statement": "You are given two circles. Find the area of their intersection.",
    "tutorial": "If the circles don't intersect than the answer is $0$. We can check that case with only integer calculations (simply by comparing the square of distance between centers with square of the sum of radiuses). If one of the circles is fully in other then the answer is the square of the smaller one. We can check this case also with only integer calculations (simply by comparing the square of distance between centers with square of the difference of radiuses). So now let's consider the general case. The answer will be equal to the sum of two circular segments. Let's consider the triangle with apexes in centers if circles and in some intersecting point of the circles. In that triangle we know all three sides so we can compute the angle of the circular segment. So we can compute the square of circular sector. And the only thing that we should do now is to subtract the square of triangle with apexes in the center of circle and in the intersecting points of circles. We can do that by computing the half of absolute value of cross product. So we have the following formulas: $\\alpha=a r c c o s\\left({\\textstyle\\frac{r_{2}^{2}+d^{2}-r_{1}^{2}}{2r_{2}d}}\\right),s=\\alpha r_{2}^{2},t=r_{2}^{2}\\sin\\alpha\\cos\\alpha,a n s_{1}=s-t$, where $d$ is the distance between centers of the circles. And also we should do the same thing with second circle by replacing of indices $1  \\le  ftrightarrow2$. Complexity: $O(1)$.",
    "tags": [
      "geometry"
    ],
    "rating": 2000
  },
  {
    "contest_id": "600",
    "index": "E",
    "title": "Lomsat gelral",
    "statement": "You are given a rooted tree with root in vertex $1$. Each vertex is coloured in some colour.\n\nLet's call colour $c$ dominating in the subtree of vertex $v$ if there are no other colours that appear in the subtree of vertex $v$ more times than colour $c$. So it's possible that two or more colours will be dominating in the subtree of some vertex.\n\nThe subtree of vertex $v$ is the vertex $v$ and all other vertices that contains vertex $v$ in each path to the root.\n\nFor each vertex $v$ find the sum of all dominating colours in the subtree of vertex $v$.",
    "tutorial": "The name of this problem is anagram for ''Small to large''. There is a reason for that :-) The author solution for this problem uses the classic technique for computing sets in tree. The simple solution is the following: let's find for each vertex $v$ the ''map<int, int>'' - the number of occurences for each colour, ''set<pair<int, int>>'' - pairs the number of occurences and the colour, and the number $sum$ - the sum of most frequent colours in subtree of $v$. To find that firstly we should find the same thing for all childs of $v$ and then merge them to one. These solution is correct but too slow (it works in $O(n^{2}logn)$ time). Let's improve that solution: every time when we want to merge two $map$-s $a$ and $b$ let's merge the smaller one to larger simply by iterating over all elements of the smaller one (this is the ``Small to large''). Let's consider some vertex $v$: every time when vertex $v$ will be moved from one $map$ to another the size of the new map will be at least two times larger. So each vertex can be moved not over than $logn$ times. Each moving can be done in $O(logn)$ time. If we accumulate that values by all vertices then we get the complexity $O(nlog^{2}n)$. I saw the solutions that differs from author's but this technique can be used in a lot of other problems.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "600",
    "index": "F",
    "title": "Edge coloring of bipartite graph",
    "statement": "You are given an undirected bipartite graph without multiple edges. You should paint the edges of graph to minimal number of colours, so that no two adjacent edges have the same colour.",
    "tutorial": "Let's denote $d$ is the maximum degree of vertex in graph. Let's prove that the answer is $d$. We will build the constructive algorithm for that (it will be the solution to problem). Let's colour the edges one by one in some order. Let $(x, y)$ be the current edge. If there exist colour $c$ that is free in vertex $x$ and in vertex $y$ then we can simply colour $(x, y)$ with $c$. If there is no such colour then there are a couple of colours $c_{1}, c_{2}$ so that $c_{1}$ is in $x$ and not in $y$ and $c_{2}$ is in $y$ but not in $x$. Let's make vertex $y$ free from colour $c_{2}$. Denote $z$ the other end of edge from $y$ with colour $c_{2}$. If $z$ is free from colour $c_{1}$ then we can colour $x, y$ with $c_{2}$ and recolour $y, z$ with $c_{1}$. So me make alternation. If $z$ is not free from colour $c_{1}$ let's denote $w$ the other end of the edge from $z$ with colour $c_{1}$. If $w$ is free from colour $c_{2}$ then again we can do alternation. And so on. We will find an alternating chain because the graph is bipartite. To find the chain we can use depth first search. Each chain contains no more than $O(n)$ vertices. So we have: Complexity: $O(nm)$.",
    "tags": [
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "601",
    "index": "A",
    "title": "The Two Routes",
    "statement": "In Absurdistan, there are $n$ towns (numbered $1$ through $n$) and $m$ bidirectional railways. There is also an absurdly simple road network — for each pair of different towns $x$ and $y$, there is a bidirectional road between towns $x$ and $y$ \\textbf{if and only if} there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.\n\nA train and a bus leave town $1$ at the same time. They both have the same destination, town $n$, and don't make any stops on the way (but they can wait in town $n$). The train can move only along railways and the bus can move only along roads.\n\nYou've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town $n$) simultaneously.\n\nUnder these constraints, what is the minimum number of hours needed for both vehicles to reach town $n$ (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town $n$ at the same moment of time, but are allowed to do so.",
    "tutorial": "The condition that the train and bus can't meet at one vertex except the final one is just trolling. If there's a railway $\\textstyle1\\,\\,-\\,\\,N$, then the train can take it and wait in town $N$. If there's no such railway, then there's a road $\\textstyle1\\,\\,-\\,\\,N$, the bus can take it and wait in $N$ instead. There's nothing forbidding this :D. The route of one vehicle is clear. How about the other one? Well, it can move as it wants, so the answer is the length of its shortest path from $1$ to $N$... or $- 1$ if no such path exists. It can be found by BFS in time $O(N + M) = O(N^{2})$. In order to avoid casework, we can just compute the answer as the maximum of the train's and the bus's shortest distance from $1$ to $N$. That way, we compute $\\operatorname{max}(1,\\operatorname{answer})$; since the answer is $ \\ge  1$, it works well. In summary, time and memory complexity: $O(N^{2})$.",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "601",
    "index": "B",
    "title": "Lipshitz Sequence",
    "statement": "A function $f:\\mathbb{R}\\rightarrow\\mathbb{R}$ is called Lipschitz continuous if there is a real constant $K$ such that the inequality $|f(x) - f(y)| ≤ K·|x - y|$ holds for all $x,y\\in\\mathbb{R}$. We'll deal with a more... discrete version of this term.\n\nFor an array $\\operatorname{h}[1..n]$, we define it's Lipschitz constant $L(\\mathbf{h})$ as follows:\n\n- if $n < 2$, $L(\\mathbf{h})=0$\n- if $n ≥ 2$, $L(\\mathbf{h})=\\operatorname*{max}\\left[{\\frac{|\\mathbf{h}[j]-\\mathbf{h}[i]|}{j-i}}\\right]$ over all $1 ≤ i < j ≤ n$\n\nIn other words, $L=L(\\mathrm{h})$ is the smallest non-negative integer such that $|h[i] - h[j]| ≤ L·|i - j|$ holds for all $1 ≤ i, j ≤ n$.\n\nYou are given an array $\\bar{\\mathbf{A}}$ of size $n$ and $q$ queries of the form $[l, r]$. For each query, consider the subarray $s=\\mathbf{a}[l..r]$; determine the sum of Lipschitz constants of \\textbf{all subarrays} of $\\underline{{\\land}}$.",
    "tutorial": "Let $L_{1}(i,j)={\\frac{|x_{i}-A_{i}|}{|i-j|}}$ for $i  \\neq  j$. Key observation: it's sufficient to consider $j = i + 1$ when calculating the Lipschitz constant. It can be seen if you draw points $(i, A_{i})$ and lines between them on paper - the steepest lines must be between adjacent pairs of points. In order to prove it properly, we'll consider three numbers $A_{i}, A_{j}, A_{k}$ ($i < j < k$) and show that one of the numbers $L_{1}(i, j)$, $L_{1}(j, k)$ is $ \\ge  L_{1}(i, k)$. W.l.o.g., we may assume $A_{i}  \\le  A_{k}$. There are 3 cases depending on the position of $A_{j}$ relative to $A_{i}, A_{k}$: $A_{j} > A_{i}, A_{k}$ - we can see that $L_{1}(i, j) > L_{1}(i, k)$, since $|A_{j} - A_{i}| = A_{j} - A_{i} > A_{k} - A_{i} = |A_{k} - A_{i}|$ and $j - i < k - i$; we just need to divide those inequalities $A_{j} < A_{i}, A_{k}$ - this is similar to the previous case, we can prove that $L_{1}(j, k) > L_{1}(i, k)$ in the same way $A_{i}  \\le  A_{j}  \\le  A_{k}$ - this case requires more work: we'll denote $d_{1y} = A_{j} - A_{i}, d_{2y} = A_{k} - A_{j}$, $d_{1x} = j - i, d_{2x} = k - j$ then, $L_{1}(i, j) = d_{1y} / d_{1x}$, $L_{1}(j, k) = d_{2y} / d_{2x}$, $L_{1}(i, k) = (d_{1y} + d_{2y}) / (d_{1x} + d_{2x})$ let's prove it by contradiction: assume that $L_{1}(i, j), L_{1}(j, k) < L_{1}(i, k)$ $d_{1y} + d_{2y} = L_{1}(i, j)d_{1x} + L_{1}(j, k)d_{2x} < L_{1}(i, k)d_{1x} + L_{1}(i, k)d_{2x} = L_{1}(i, k)(d_{1x} + d_{2x}) = d_{1y} + d_{2y}$, which is a contradiction We've just proved that to any $L_{1}$ computed for two elements $A[i], A[k]$ with $k > i + 1$, we can replace one of $i, j$ by a point $j$ between them without decreasing $L_{1}$; a sufficient amount of such operations will give us $k = i + 1$. Therefore, the max. $L_{1}$ can be found by only considering differences between adjacent points. This is actually a huge simplification - the Lipschitz constant of an array is the maximum abs. difference of adjacent elements! If we replace the array $A[1..n]$ by an array $D[1..n - 1]$ of differences, $D[i] = A[i + 1] - A[i]$, then the Lipschitz constant of a subarray $A[l, r]$ is the max. element in the subarray $D[l..r - 1]$. Finding subarray maxima actually sounds quite standard, doesn't it? No segment trees, of course - there are still too many subarrays to consider. So, what do we do next? There are queries to answer, but not too many of them, so we can process each of them in $O(N)$ time. One approach that works is assigning a max. difference $D[i]$ to each subarray - since there can be multiple max. $D[i]$, let's take the leftmost one. We can invert it to determine the subarrays for which a given $D[i]$ is maximum: if $D[a_{i}]$ is the closest difference to the left of $D[i]$ that's $ \\ge  D[i]$ or $a_{i} = 0$ if there's none, and $D[b_{i}]$ is the closest difference to the right that's $> D[i]$ or $b_{i} = n - 1$ if there's none (note the strict/non-strict inequality signs - we don't care about differences equal to $D[i]$ to its right, but there can't be any to its left, or it wouldn't be the leftmost max.), then those are all subarrays $D[j..k]$ such that $a_{i} < j  \\le  i  \\le  k < b_{i}$. If we don't have the whole array $D[1..n - 1]$, but only some subarray $D[l..r]$, then we can simply replace $a_{i}$ by $\\operatorname*{max}(a_{i},l-1)$ and $b_{i}$ by $\\operatorname*{min}(b_{i},r+1)$. The number of those subarrays is $P_{i} = (i - a_{i})(b_{i} - i)$, since we can choose $j$ and $k$ independently. All we have to do to answer a query is check all differences, take $a_{i}$, $b_{i}$ (as the max/min with some precomputed values) and compute $P_{i}$; the answer to the query is $\\textstyle\\sum_{i=l}^{r}D[i]\\cdot P_{i}$. We only need to precompute all $a_{i}, b_{i}$ for the whole array $D[1..n - 1]$ now; that's a standard problem, solvable using stacks in $O(N)$ time or using maps + Fenwick trees in $O(N\\log N)$ time. The total time complexity is $O(NQ)$, memory $O(N)$.",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "601",
    "index": "C",
    "title": "Kleofáš and the n-thlon",
    "statement": "Kleofáš is participating in an $n$-thlon - a tournament consisting of $n$ different competitions in $n$ different disciplines (numbered $1$ through $n$). There are $m$ participants in the $n$-thlon and each of them participates in all competitions.\n\nIn each of these $n$ competitions, the participants are given \\underline{ranks} from $1$ to $m$ in such a way that no two participants are given the same rank - in other words, the ranks in each competition form a permutation of numbers from $1$ to $m$. The \\underline{score} of a participant in a competition is equal to his/her rank in it.\n\nThe \\underline{overall score} of each participant is computed as the sum of that participant's scores in all competitions.\n\nThe \\underline{overall rank} of each participant is equal to $1 + k$, where $k$ is the number of participants with \\textbf{strictly smaller} overall score.\n\nThe $n$-thlon is over now, but the results haven't been published yet. Kleofáš still remembers his ranks in each particular competition; however, he doesn't remember anything about how well the other participants did. Therefore, Kleofáš would like to know his expected overall rank.\n\nAll competitors are equally good at each discipline, so all rankings (permutations of ranks of everyone except Kleofáš) in each competition are equiprobable.",
    "tutorial": "As it usually happens with computing expected values, the solution is dynamic programming. There are 2 things we could try to compute: probabilities of individual overall ranks of Kleofáš or just some expected values. In this case, the latter option works. \"one bit is 8 bytes?\" \"no, the other way around\" \"so 8 bytes is 1 bit?\" After some attempts, one finds out that there's no reasonable way to make a DP for an expected rank or score of one person (or multiple people). What does work, and will be the basis of our solution, is the exact opposite: we can compute the expected number of people with a given score. The most obvious DP for it would compute $E(i, s)$ - the exp. number of people other than Kleofáš with score $s$ after the first $i$ competitions. Initially, $E(0, 0) = m - 1$ and $E(0, s > 0) = 0$. How can we get someone with score $s$ in competition $i$? That person can have any score $k$ from 1 to $m$ except $x_{i}$ (since Kleofáš has that one) with the same probability $\\frac{1}{m-1}$. The expected values are sums with probabilities $P(i, s, j)$ that there are $j$ people with score $s$: $E(i,s)=\\sum_{j}j\\cdot P(i,s,j)\\,.$Considering that the probability that one of them will get score $k$ is $\\frac{{\\dot{J}}}{m-1}$, we know that with probability $P(i,s,j)\\underline{{{b}}}$, we had $j$ people with score $s$ before the competition and one of them had score $s + k$ after that competition - adding 1 to $E(i + 1, s + k)$. By summation over $j$, we'll find the exp. number of people who had overall score $s$ and scored $k$ more: $\\sum_{j}P(i,s,j)\\frac{j}{m-1}=\\frac{\\cal{E}(i,s)}{m-1}\\,.$Lol, it turns out to be so simple. We can find the probability $E(i + 1, t)$ afterwards: since getting overall score $t$ after $i + 1$ competitions means getting score $k$ in the currently processed competition and overall score $s = t - k$ before, and both distinct $k$ and expectations for people with distinct $s$ are totally independent of each other, then we just need to sum up the exp. numbers of people with those scores (which we just computed) over the allowed $k$: $E(i+1,t)=\\sum_{k}\\frac{E(i,t-k)}{m-1}\\,.$The formulas for our DP are now complete and we can use them to compute $E(n, s)$ for all $1  \\le  s  \\le  mn$. Since $E(n, s)$ people with $s$ greater than the overall score $s_{k}$ of Kleofáš add $E(n, s)$ to the overall rank of Kleofáš and people with $s  \\le  s_{k}$ add nothing, we can find the answer as $\\qquad1+\\sum_{s>s_{\\mathrm{s}}}E(n,s)\\,.$This takes $O(m^{2}n^{2})$ time, since there are $O(mn)$ scores, $O(mn^{2})$ states of the DP and directly computing each of them takes $O(m)$ time. Too slow. We can do better, of course. Let's forget about dividing by $m - 1$ for a while; then, $E(i + 1, t)$ is a sum of $E(i, s)$ for one or two ranges of scores - or for one range minus one value. If you can solve div1C, then you should immediately know what to do: compute prefix sums of $E(i, s)$ over $s$ and find $E(i + 1, t)$ for each $t$ using them. And now, computing one state takes $O(1)$ time and the problem is solved in $O(mn^{2})$ time (and memory).",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "601",
    "index": "D",
    "title": "Acyclic Organic Compounds",
    "statement": "You are given a tree $T$ with $n$ vertices (numbered $1$ through $n$) and a letter in each vertex. The tree is rooted at vertex $1$.\n\nLet's look at the subtree $T_{v}$ of some vertex $v$. It is possible to read a string along each simple path starting at $v$ and ending at some vertex in $T_{v}$ (possibly $v$ itself). Let's denote the number of \\textbf{distinct} strings which can be read this way as $\\operatorname{dif}(v)$.\n\nAlso, there's a number $c_{v}$ assigned to each vertex $v$. We are interested in vertices with the maximum value of $\\operatorname{dif}(v)+c_{v}$.\n\nYou should compute two statistics: the maximum value of $\\operatorname{dif}(v)+c_{v}$ and the number of vertices $v$ with the maximum $\\operatorname{dif}(v)+c_{v}$.",
    "tutorial": "The name is really almost unrelated - it's just what a tree with arbitrary letters typically is in chemistry. If you solved problem TREEPATH from the recent Codechef November Challenge, this problem should be easier for you - it uses the same technique, after all. Let's figure out how to compute $\\operatorname{dif}(v)$ for just one fixed $v$. One more or less obvious way is computing hashes of our strings in a DFS and then counting the number of distinct hashes (which is why there are anti-hash tests :D). However, there's another, deterministic and faster way. Compressing the subtree $T_{v}$ into a trie. Recall that a trie is a rooted tree with a letter in each vertex (or possibly nothing in the root), where each vertex encodes a unique string read along the path from the root to it; it has at most $ \\sigma $ sons, where $ \\sigma  = 26$ is the size of the alphabet, and each son contains a different letter. Adding a son is done trivially in $O( \\sigma )$ (each vertex contains an array of 26 links to - possibly non-existent - sons) and moving down to a son with the character $c$ is then possible in $O(1)$. Compressing a subtree can be done in a DFS. Let's build a trie $H_{v}$ (because $T_{v}$ is already used), initially consisting only of one vertex - the root containing the letter $s_{v}$. In the DFS, we'll remember the current vertex $R$ of the tree $T$ and the current vertex $cur$ of the trie. We'll start the DFS at $v$ with $cur$ being the root of $H_{v}$; all we need to do is look at each son $S$ of $R$ in DFS, create the son $cur_{s}$ of $cur$ corresponding to the character $s_{S}$ (if it didn't exist yet) and run $DFS(S, cur_{s})$. This DFS does nothing but construct $H_{v}$ that encodes all strings read down from $v$ in $T_{v}$. And since each vertex of $H_{v}$ encodes a distinct string, $\\operatorname{dif}(v)$ is the number of vertices of $H_{v}$. This runs in $O(|T_{v}| \\sigma )$ time, since it can create a trie with $|T_{v}|$ vertices in the worst case. Overall, it'd be $O(N^{2} \\sigma )$ if $T$ looks sufficiently like a path. The HLD trick Well, what can we do to improve it? This trick is really the same - find the son $w$ of $v$ that has the maximum $|T_{w}|$, add $s_{v}$ to $H_{w}$ and make it $H_{v}$; then, DFS through the rest of $T_{v}$ and complete the trie $H_{v}$ as in the slow solution. The trick resembles HLD a lot, since we're basically remembering tries on HLD-paths. If $v$ is a leaf, of course, we can just create $H_{v}$ that consists of one vertex. How do we \"add\" $v$ to a trie $H_{w}$ of its son $w$? Well, $v$ should be the root of the trie afterwards and the original $H_{w}$'s root should become its son, so we're rerooting $H_{w}$. We'll just create a new vertex in $H_{w}$ with $s_{v}$ in it, make it the root of $H_{w}$ and make the previous root of $H_{w}$ its son. And if we number the tries somehow, then we can just set the number of $H_{v}$ to be the number of $H_{w}$. It remains true that $dif(v)$ is $|H_{v}|$ - the number of vertices in the trie $H_{v}$, which allows us to compute those values directly. After computing $dif(v)$ for each $v$, we can just compute both statistics directly in $O(N)$. Since each vertex of $T$ corresponds to vertices in at most $O(\\log N)$ tries (for each heavy edge that's on the path from it to the root), we aren't creating tries with a total of $O(N^{2})$ vertices, but $O(N\\log N)$. The time complexity is therefore $O(N\\log N\\sigma)$. However, the same is true for the memory, so you can't waste it too much!",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "hashing",
      "strings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "601",
    "index": "E",
    "title": "A Museum Robbery",
    "statement": "There's a famous museum in the city where Kleofáš lives. In the museum, $n$ exhibits (numbered $1$ through $n$) had been displayed for a long time; the $i$-th of those exhibits has value $v_{i}$ and mass $w_{i}$.\n\nThen, the museum was bought by a large financial group and started to vary the exhibits. At about the same time, Kleofáš... gained interest in the museum, so to say.\n\nYou should process $q$ events of three types:\n\n- type $1$ — the museum displays an exhibit with value $v$ and mass $w$; the exhibit displayed in the $i$-th event of this type is numbered $n + i$ (see sample explanation for more details)\n- type $2$ — the museum removes the exhibit with number $x$ and stores it safely in its vault\n- type $3$ — Kleofáš visits the museum and wonders (for no important reason at all, of course): if there was a robbery and exhibits with total mass at most $m$ were stolen, what would their maximum possible total value be?\n\nFor each event of type 3, let $s(m)$ be the maximum possible total value of stolen exhibits with total mass $ ≤ m$.\n\nFormally, let $D$ be the set of numbers of all exhibits that are currently displayed (so initially $D$ = {1, ..., n}). Let $P(D)$ be the set of all subsets of $D$ and let\n\n\\[\nG=\\left\\{S\\in P(D)\\left|\\sum_{i\\in S}w_{i}\\leq m\\right.\\right\\}\\,.\n\\]\n\nThen, $s(m)$ is defined as\n\n\\[\ns(m)=\\operatorname*{max}_{S\\in G}\\left(\\sum_{i\\in S}v_{i}\\right)\\,.\n\\]\n\nCompute $s(m)$ for each $m\\in\\{1,2,\\ldots,k\\}$. Note that the output follows a special format.",
    "tutorial": "In this problem, we are supposed to solve the 0-1 knapsack problem for a set of items which changes over time. We'll solve it offline - each query (event of type 3) is asked about a subset of all $N$ exhibits appearing on the input. Introduction If we just had 1 query and nothing else, it's just standard knapsack DP. We'll add the exhibits one by one and update $s(m)$ (initially, $s(m) = 0$ for all $m$). When processing an exhibit with $(v, w)$, in order to get loot with mass $m$, we can either take that exhibit and get value at least $s(m - w) + v$, or not take it and get $s(m)$; therefore, we need to replace $s(m)$ by $\\operatorname*{max}(s(m),s(m-w)+v)$; the right way to do it is in decreasing order of $m$. In fact, it's possible to merge 2 knapsacks with any number of items in $O(k^{2})$, but that's not what we want here. Note that we can add exhibits this way. Thus, if there were no queries of type 2, we would be able to solve whole problem in $O(Nk)$ time by just remembering the current $s(m)$ and updating it when adding an exhibit. Even if all queries were of type 2 (with larger $n$), we'd be able to solve it in $O(nk)$ time in a similar way after sorting the exhibits in the order of their removal and processing queries/removals in reverse chronological order. The key Let's have $q$ queries numbered $1$ through $Q$ in the order in which they're asked; query $q$ is asked on some subset $S_{q}$ of exhibits. MAGIC TRICK: Compute the values $s(m)$ only for subsets $S_{2q}\\cap S_{2q+1}$ - the intersections of pairs of queries $2q, 2q + 1$ (intersection of the first and the second query, of the third and fourth etc.), recursively. Then, recompute $s(m)$ for all individual queries in $O((N + Q)k)$ time by adding elements which are missing in the intersection, using the standard knapsack method. What?! How does this work?! Shouldn't it be more like $O(N^{2})$ time? Well, no - just look at one exhibit and the queries where it appears. It'll be a contiguous range of them - since it's displayed until it's removed (or the events end). This element will only be missing in the intersection, but present in one query (so it'll be one of the elements added using knapsack DP), if query $2q + 1$ is the one where it appears first or query $2q$ the one where it appears last. That makes at most two addittions of each element and $O(N)$ over all of them; adding each of them takes $O(k)$ time, which gives $O(Nk)$. The second part of the complexity, $O(Qk)$ time, is spent by copying the values of $s(m)$ first from the intersection of queries $2q$ and $2q + 1$ to those individual queries. If we're left with just one query, we can solve it in $O(Nk)$ as the usual 0-1 knapsack. Since we're halving the number of queries when recursing deeper, we can only recurse to depth $O(\\log Q)$ and the time complexity is $O((N+Q)k\\log Q)$. A different point of view (Baklazan's) We can also look at this as building a perfect binary tree with sets $S_{1}, ..., S_{Q}$ in leaves and the intersection of sets of children in every other vertex. For each vertex $v$ of this tree, we're solving the knapsack - computing $s(m)$ - for the set $D_{v}$ of displayed exhibits in it. We will solve the knapsack for the root directly and then proceed to the leaves. In each vertex $v$, we will take $s(m)$, the set $D_{p}$ of its parent $p$ and find $s(m)$ for $v$ by adding exhibits which are in $D_{v}$, but not in $D_{p}$. We know that the set $D_{p}$ is of the form $\\textstyle\\bigcap_{i=a}^{b}S_{i}$ for some $a, b$ and $D_{v}$ is either of the form $\\textstyle\\bigcap_{i=a}^{m}S_{i}$ or $\\textstyle\\bigcap_{i=m+1}^{b}S_{i}$ for $m={\\frac{b+a-1}{2}}$ (depending on whether it's the left or the right son). In the first case, only elements removed between the $m$-th and $b$-th query have to be added and in the second case, it's only elements added between the $a$-th and $m + 1$-th query. Since each element will only be added/removed once and the ranges of queries on the same level of the tree are disjoint, we will do $O((N + Q)k)$ work on each level and the overall time complexity is $O((N+Q)k\\log Q)$. Finding the intersections and exhibits not in the intersections Of course, bruteforcing them in $O(NQ)$ isn't such a bad idea, but it'd probably TLE - and we can do better. We've just described how we can pick those exhibits based on the queries between which they were added/removed. Therefore, we can find - for each exhibit - the interval of queries for which it was displayed and remember for each two consecutive queries the elements added and removed between them; finding the exhibits added/removed in some range is then just a matter of iterating over them. Since we're actually adding all of them, this won't worsen the time complexity. In order to efficiently determine the exhibits in some set $\\textstyle\\bigcap_{i=a}^{b}S_{i}$, we can remember for each exhibit the interval of time when it was displayed. The exhibit is in the set $\\textstyle\\bigcap_{i=a}^{b}S_{i}$ if and only if it was displayed before the $a$-th query and remained displayed at least until the $b$-th query. To conclude, the time complexity is $O((N+Q)k\\log Q)=O(q k\\log q)$ and since we don't need to remember all levels of the perfect binary tree, but just the one we're computing and the one above it, the memory complexity is $O(qk)$.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "602",
    "index": "A",
    "title": "Two Bases",
    "statement": "After seeing the \"ALL YOUR BASE ARE BELONG TO US\" meme for the first time, numbers $X$ and $Y$ realised that they have different bases, which complicated their relations.\n\nYou're given a number $X$ represented in base $b_{x}$ and a number $Y$ represented in base $b_{y}$. Compare those two numbers.",
    "tutorial": "It's easy to compare two numbers if the same base belong to both. And our numbers can be converted to a common base - just use the formulas $X\\,=\\,\\sum_{i=1}^{N}\\,x_{i}B_{x}^{N-i};\\quad Y\\,=\\sum_{i=1}^{M}\\,y_{i}B_{y}^{M-i}\\,.$A straightforward implementation takes $O(N + M)$ time and memory. Watch out, you need 64-bit integers! And don't use pow - iterating $X\\rightarrow X B_{x}+x_{i}$ is better.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "602",
    "index": "B",
    "title": "Approximating a Constant Range",
    "statement": "When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?\n\nYou're given a sequence of $n$ data points $a_{1}, ..., a_{n}$. There aren't any big jumps between consecutive data points — for each $1 ≤ i < n$, it's guaranteed that $|a_{i + 1} - a_{i}| ≤ 1$.\n\nA range $[l, r]$ of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most $1$. Formally, let $M$ be the maximum and $m$ the minimum value of $a_{i}$ for $l ≤ i ≤ r$; the range $[l, r]$ is almost constant if $M - m ≤ 1$.\n\nFind the length of the longest almost constant range.",
    "tutorial": "Let's process the numbers from left to right and recompute the longest range ending at the currently processed number. One option would be remembering the last position of each integer using STL map<>/set<> data structures, looking at the first occurrences of $A_{i}$ plus/minus 1 or 2 to the left of the current $A_{i}$ and deciding on the almost constant range ending at $A_{i}$ based on the second closest of those numbers. However, there's a simpler and more efficient option - notice that if we look at non-zero differences in any almost constant range, then they must alternate: $.., + 1, - 1, + 1, - 1, ..$. If there were two successive differences of $+ 1$-s or $- 1$-s (possibly separated by some differences of $0$), then we'd have numbers $a - 1, a, a, ..., a, a + 1$, so a range that contains them isn't almost constant. Let's remember the latest non-zero difference (whether it was +1 or -1 and where it happened); it's easy to update this info when encountering a new non-zero difference. When doing that update, we should also check whether the new non-zero difference is the same as the latest one (if $A_{i} - A_{i - 1} = A_{j + 1} - A_{j}$). If it is, then we know that any almost constant range that contains $A_{i}$ can't contain $A_{j}$. Therefore, we can keep the current leftmost endpoint $l$ of a constant range and update it to $j + 1$ in any such situation; the length of the longest almost constant range ending at $A_{i}$ will be $i - l + 1$. This only needs a constant number of operations per each $A_{i}$, so the time complexity is $O(N)$. Memory: $O(N)$, but it can be implemented in $O(1)$.",
    "tags": [
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "603",
    "index": "A",
    "title": "Alternative Thinking",
    "statement": "Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length $n$. Each character of Kevin's string represents Kevin's score on one of the $n$ questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.\n\nHowever, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an \\underline{alternating subsequence} of a string as a \\textbf{not-necessarily contiguous} subsequence where no two consecutive elements are equal. For example, ${0, 1, 0, 1}$, ${1, 0, 1}$, and ${1, 0, 1, 0}$ are alternating sequences, while ${1, 0, 0}$ and ${0, 1, 0, 1, 1}$ are not.\n\nKevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a \\textbf{contiguous} non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.",
    "tutorial": "Hint: Is there any easy way to describe the longest alternating subsequence of a string? What happens at the endpoints of the substring that we flip? Imagine compressing each contiguous block of the same character into a single character. For example, the first sample case 10000011 gets mapped to 101. Then the longest alternating subsequence of our string is equal to the length of our compressed string. So what does flipping a substring do to our compressed string? To answer this, we can think about flipping a substring as flipping two (possibly empty) prefixes. As an example, consider the string 10000011. Flipping the bolded substring 100 00 011 is equivalent to flipping the two bolded prefixes 10000011 and 10000. For the most part, flipping the prefix of a string also flips the corresponding portion of the compressed string. The interesting case occurs at the endpoint of the prefix. Here, we have two possibilities: the two characters on either side of the endpoint are the same or different. If they are the same (00 or 11), then flipping this prefix adds an extra character into our compressed string. If they are different (01 or 10), we merge two characters in our compressed string. These increase and decrease, respectively, the length of the longest alternating subsequence by one. There is actually one more case that we left out: when the endpoint of our prefix is also an endpoint of the string. Then it is easy to check that the length of the longest alternating subsequence doesn't change. With these observations, we see that we want to flip prefixes that end between 00 or 11 substrings. Each such substring allows us to increase our result by one, up to a maximum of two, since we only have two flips. If there exist no such substrings that we can flip, we can always flip the entire string and have our result stay the same. Thus our answer is the length of the initial longest alternating subsequence plus $\\operatorname*{min}(2,\\neq\\mathrm{{of}}^{\\cdot}00^{\\cdot}\\;\\mathrm{{and}}^{\\cdot}1\\}^{\\cdot}\\;\\mathrm{{substrings}})$. A very easy way to even simplify the above is to notice that if the initial longest alternating subsequence has length $len - 2$, then there will definitely be two 00 or 11 substrings. If it has length $n - 1$, then it has exactly one 00 or 11 substring. So our answer can be seen as the even easier $\\mathrm{min}(n,\\mathrm{longest~alternating~subsequence}+2)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint N, res = 1;\nstring S;\n \nint main(){\n  cin >> N >> S;\n  for(int i = 1; i < N; i++){\n    res += (S[i] != S[i - 1]);\n  }\n  cout << min(res + 2, N) << '\\n';\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "603",
    "index": "B",
    "title": "Moodular Arithmetic",
    "statement": "As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers $k$ and $p$, where $p$ is an odd prime number, the functional equation states that\n\n\\[\nf(k x\\ \\ \\mathrm{mod}\\ p)\\equiv k\\cdot f(x)\\ \\ \\mathrm{mod}\\ p\n\\]\n\nfor some function $f:\\{0,1,2,\\cdot\\cdot\\cdot,p-1\\}\\rightarrow\\{0,1,2,\\cdot\\cdot\\cdot,p-1\\}$. (This equation should hold for any integer $x$ in the range $0$ to $p - 1$, inclusive.)\n\nIt turns out that $f$ can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions $f$ that satisfy this equation. Since the answer may be very large, you should print your result modulo $10^{9} + 7$.",
    "tutorial": "Hint: First there are special cases $k = 0$ and $k = 1$. After clearing these out, think about the following: given the value of $f(n)$ for some $n$, how many other values of $f$ can we find? We first have the degenerate cases where $k = 0$ and $k = 1$. If $k = 0$, then the functional equaton is equivalent to $f(0) = 0$. Therefore, $p^{p - 1}$ functions satisfy this, because the values $f(1), f(2), ..., f(p - 1)$ can be anything in ${0, 1, 2, ..., p - 1}$. If $k = 1$, then the equation is just $f(x) = f(x).$ Therefore $p^{p}$ functions satisfy this, because the values $f(0), f(1), f(2), ..., f(p - 1)$ can be anything in ${0, 1, 2, ..., p - 1}.$ Now assume that $k  \\ge  2$, and let $m$ be the least positive integer such that $k^{m}\\equiv1\\mathrm{\\mod\\}p.$ This is called the \\emph{order} of $k\\mod p.$ First, plug in $x = 0$ to find that $f(0)=k\\cdot f(0)\\implies(k-1)f(0)=0\\implies f(0)=0\\mod p$ as $p$ is prime, and $k\\neq1$. Now for some integer $n\\neq0$, choose a value for $f(n)$. Given this value, we can easily show that $f(k^{i}n\\mathrm{\\boldmath~\\mod~}p)\\equiv k^{i}f(n)\\mathrm{\\boldmath~\\mod~}p$ just by plugging in $x = k^{i - 1}n$ into the functional equation and using induction. Note that the numbers $n, kn, k^{2}n, ..., k^{m - 1}n$ are distinct $\\mathrm{mod}\\,p$, since $m$ is the smallest number such that $k^{m}\\equiv1\\mod p$. Therefore, if we choose the value of $f(n)$, we get the value of $m$ numbers ($f(n),f(k n\\mathrm{\\boldmath~\\mod~}p),\\cdot\\cdot\\cdot,f(k^{m-1}n\\mathrm{\\boldmath~\\mod~}p)$). Therefore, if we choose $f(n)$ of $\\frac{p-1}{m}$ integers $n$, we can get the value of all $p - 1$ nonzero integers. Since $f(n)$ can be chosen in $p$ ways for each of the $\\frac{p-1}{m}$ integers, the answer is $\\textstyle{\\int}^{\\frac{p-1}{m}}$. Another way to think about this idea is to view each integer from $0$ to $p - 1$ as a vertex in a graph, where $n$ is connected to $k^{i}n\\ \\ \\mathrm{mod}\\ p$ for every integer $i$. If we fix the value of $f(n)$ for some $n$, then $f$ also becomes fixed for all other vertices in its connected component. Thus our answer is $p$ raised to the the number of connected components in the graph.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int MOD = 1000000007;\nint P, K;\n \nint modpow(int a, int p){\n  if(p == 0) return 1;\n  return (long long) a * modpow(a, p - 1) % MOD;\n}\n \nint main(){\n  cin >> P >> K;\n  if(K == 0){\n    cout << modpow(P, P - 1) << '\\n';\n  } else if(K == 1){\n    cout << modpow(P, P) << '\\n';\n  } else {\n    int ord = 1, cur = K;\n    for( ; cur != 1; ord += 1){\n      cur = (long long) cur * K % P;\n    }\n    cout << modpow(P, (P - 1) / ord) << '\\n';\n  }\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dsu",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "603",
    "index": "C",
    "title": "Lieges of Legendre",
    "statement": "Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are $n$ piles of cows, with the $i$-th pile containing $a_{i}$ cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:\n\n- Remove a single cow from a chosen non-empty pile.\n- Choose a pile of cows with even size $2·x$ ($x > 0$), and replace it with $k$ piles of $x$ cows each.\n\nThe player who removes the last cow wins. Given $n$, $k$, and a sequence $a_{1}, a_{2}, ..., a_{n}$, help Kevin and Nicky find the winner, given that both sides play in optimal way.",
    "tutorial": "Hint: Is there a way to determine the winner of a game with many piles but looking at only one pile at a time? We'll use the concepts of Grundy numbers and Sprague-Grundy's Theorem in this solution. The idea is that every game state can be assigned an integer number, and if there are many piles of a game, then the value assigned to that total game state is the xor of the values of each pile individually. The Grundy number of a state is the minimum number that is not achieved among any state that the state can move to. Given this brief intro (which you can read more about many places), we have to separate the problem into 2 cases, $k$ even and odd. Let $f(n)$ denote the Grundy number of a pile of size $n$. By definition $f(0) = 0.$ If $k$ is even, then when you split the pile of size $2n$ into $k$ piles of size $n$, the resulting Grundy number of that state is $\\underbrace{f(n)\\oplus f(n)\\oplus\\cdots\\6f(n)}_{k\\;\\mathrm{times}}=0,$ as $k$ is even. Given this, it is easy to compute that $f(0) = 0, f(1) = 1, f(2) = 2, f(3) = 0, f(4) = 1.$ Now I will show by induction that for $n  \\ge  2, f(2n - 1) = 0, f(2n) = 1.$ The base cases are clear. For $f(2n - 1)$, the only state that can be moved to from here is that with $2n - 2$ cows. By induction, $f(2n - 2) = 1 > 0,$ so $f(2n - 1) = 0.$ On the other hand, for $2n$, removing one stone gets to a state with $2n - 1$ stones, with Grundy number $f(2n - 1) = 0$ by induction. Using the second operation gives a Grundy number of $0$ as explained above, so the smallest positive integer not achieveable is $1$, so $f(2n) = 1$. The case where $k$ is odd is similar but requires more work. Let's look at the splitting operation first. This time, from a pile of size $2n$ we can move to $k$ piles of size $n$, with Grundy number $\\underbrace{f(n)\\oplus f(n)\\oplus\\cdots\\6\\oplus f(n)}_{k{\\mathrm{~times}}}=f(n),$ as $k$ is odd. So from $2n$ we can achieve the Grundy numbers $f(2n - 1)$ and $f(n).$ Using this discussion, we can easily compute the first few Grundy numbers. $f(0) = 0, f(1) = 1, f(2) = 0, f(3) = 1, f(4) = 2, f(5) = 0$. I'll prove that for $n  \\ge  2$, $f(2n) > 0, f(2n + 1) = 0$ by induction. The base cases are clear. Now, for $n  \\ge  3$, since a pile of size $2n + 1$ can only move to a pile of size $2n$, which by induction has Grundy number $f(2n) > 0$, $f(2n + 1) = 0$. Similarly, because from a pile of size $2n$, you can move to a pile of size $2n - 1$, which has Grundy number $f(2n - 1) = 0$, $f(2n) > 0$. Now computing the general Grundy number $f(n)$ for any $n$ is easy. If $n  \\le  4$, we have them precomputed. If $n$ is odd and $n > 4$, $f(n) = 0$. In $n$ is even and $n  \\ge  6$, then $f(n)$ is the minimal excludent of $f(n - 1) = 0$ and $f(n / 2)$ (because $n - 1$ is odd and $ \\ge  5$, so $f(n - 1) = 0.$) We can do this recursively, The complexity is $O(n)$ in the $k$ even case and $O(n\\log M A X)$ in the $k$ odd case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int pre[] = {0, 1, 0, 1, 2};\nint N, K, A, res;\n \nint grundy(int a){\n  if(K % 2 == 0){\n    if(a == 1) return 1;\n    if(a == 2) return 2;\n    return (a % 2) ^ 1;\n  } else {\n    if(a < 5) return pre[a];\n    if(a % 2 == 1) return 0;\n    return (grundy(a / 2) == 1 ? 2 : 1);\n  }\n}\n \nint main(){\n  cin >> N >> K;\n  for(int i = 0; i < N; i++){\n    cin >> A;\n    res ^= grundy(A);\n  }\n  cout << (res ? \"Kevin\" : \"Nicky\") << '\\n';\n}",
    "tags": [
      "games",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "603",
    "index": "D",
    "title": "Ruminations on Ruminants",
    "statement": "Kevin Sun is ruminating on the origin of cows while standing at the origin of the Cartesian plane. He notices $n$ lines $\\ell_{1},\\ell_{2},\\cdot\\cdot\\ell_{n}$ on the plane, each representable by an equation of the form $ax + by = c$. He also observes that no two lines are parallel and that no three lines pass through the same point.\n\nFor each triple $(i, j, k)$ such that $1 ≤ i < j < k ≤ n$, Kevin considers the triangle formed by the three lines $\\ell_{i},\\ell_{j},\\ell_{k}$ . He calls a triangle \\underline{original} if the circumcircle of that triangle passes through the origin. Since Kevin believes that the circles of bovine life are tied directly to such triangles, he wants to know the number of original triangles formed by unordered triples of distinct lines.\n\nRecall that the circumcircle of a triangle is the circle which passes through all the vertices of that triangle.",
    "tutorial": "Hint: It seems like this would be $O(n^{3})$ because of triples of lines. Can you reduce that with some geometric observations? Think of results from Euclidean geometry relating to 4 points lying on the same circle. First, we will prove a lemma, known as the Simson Line: Lemma: Given points $A, B, C, P$ in the plane with $D, E, F$ on lines $BC, CA,$ and $AB$, respectively such that $P D\\perp B C.P E\\perp A C.P F\\perp A B$, then $P$ lies on the circumcircle of $\\triangle A B C$ if and only if $D, E,$ and $F$ are collinear. Proof: Assume that the points are configured as shown, and other other configurations follow similarly. Recall that a quadrilateral $ABCP$ is cyclic if and only if $\\angle B A C=180^{\\circ}-\\angle B P C$. Note that this implies that a quadrilateral with two opposite right angles is cyclic, so in particular quadrilaterals $AEPF, BFPD, CDPE$ are cyclic. Because $\\angle F P E=180^{\\circ}-\\angle B A C$ we get that $ABPC$ is cyclic if and only if $\\angle F P E=\\angle B P C$, if and only if $\\angle F P B=\\angle E P C$. Now note that $\\angle F P B=\\angle F D B$ (again since $BFPD$ is cyclic) and $\\angle E P C=\\angle E D C$, so $\\angle B D F=\\angle E D C$ if and only if $\\angle F P B=\\angle E P C$, if and only if $ABPC$ is cyclic. Thus the lemma is proven. This lemma provides us with an efficient way to test if the circumcircle of the triangle formed by three lines in the plane passes through the origin. Specifically, for a line $\\,\\ell_{i}$, let $X_{i}$ be the projection of the origin onto $\\,\\ell_{i}$. Then $\\ell_{i},\\ell_{j},\\ell_{k}$ form an original triangle if and only if $X_{i}, X_{j},$ and $X_{k}$ are collinear. Thus the problem reduces to finding the number of triples $i < j < k$ with $X_{i}, X_{j}, X_{k}$ collinear. The points $X_{i}$ are all distinct, except that possibly two lines may pass through the origin, so we can have up to two points $X_{i}$ at the origin. Let us first solve the problem in the case that all points $X_{i}$ are distinct. In this case, consider each $i$, and store for each slope how many points $X_{j}$ with $i < j$ the line $X_{i}$ $X_{j}$ has this slope. This storage can be done in $O(1)$ or $O(\\log n)$, depending on how hashing is done. Note also that we must consider a vertical line to have the valid slope $\\textstyle{\\frac{1}{0}}$. If $a_{1},a_{2},**a_{l}$ are the number of points corresponding to the distinct slopes $S_{1},\\;S_{2},\\;\\star\\star S_{i}$ through $X_{i}$ (for points $X_{j}$ with $i < j$), then for $X_{i}$ we add to the total count ${\\binom{a_{1}}{2}}+{\\binom{a_{2}}{2}}+\\cdot\\cdot\\cdot{\\binom{a_{\\ell}}{2}}$ If the $X_{i}$ are not distinct, we only encounter an issue in the above solutions when we consider the slope through points $X_{i}$ and $X_{j}$ where $X_{i} = X_{j}$. In this case, for any third $k$, $X_{i}, X_{j},$ and $X_{k}$ are collinear. So when considering slopes from $X_{i}$ in the original algorithm, we simply run the algorithm on all slopes other than the one through $X_{j}$, and simply add $n - 2$ to the count afterwards to account for the $n - 2$ points which are collinear with $X_{i}$ and $X_{j}$. Running the above, we get an algorithm that runs in $O(n^{2})$ or $O(n^{2}\\log{n})$. Another approach which doesn't involve the Simson line follows a similar idea: we want to find some property $f(i, j)$ between points $X_{i}$ and $X_{j}$ such that the triangle formed by indices $i, j, k$ is original if and only if $f(i, j) = f(i, k)$. Then we can use the same argument as above to solve the problem in $O(n^{2})$ or $O(n^{2}\\log{n})$. Instead of using the slope between points $i, j$ as the property, suppose $\\,\\ell_{i}$ and $\\,\\ell_{j}$ meet at some point $P$, and let $O$ be the origin (again $O = P$ is a special case). Then we let $f(i, j)$ be the angle between $\\,\\ell_{j}$ and $OP$. Because of the properties of cyclic quadrilaterals explained above, the triangle is original if and only if $f(i, j) = f(i, k)$, up to defining the angle as positive or negative and modulo $180^{\\circ}$. Following this approach carefully, we can finish as before.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long ll;\ntypedef pair<ll,ll> pll;\n \nll gcd(ll x, ll y){\n  for( ; y > 0; swap(x, y)) x %= y;\n  return x;\n}\n \npll reduce(ll x, ll y){\n  ll g = gcd(abs(x), abs(y));\n  if(g != 0) x /= g, y /= g;\n  if((y < 0) || (y == 0 && x < 0)) x = -x, y = -y;\n  return make_pair(x, y);\n}\n \nconst int MAXN = 2005;\nint N, A, B, C;\nll X[MAXN], Y[MAXN], Z[MAXN], res;\n \nint main(){\n  cin >> N;\n  for(int i = 0; i < N; i++){\n    cin >> A >> B >> C;\n    X[i] = A * C;\n    Y[i] = B * C;\n    Z[i] = A * A + B * B;\n  }\n  for(int i = 0; i < N; i++){\n    int tot = 0, zero = 0;\n    map<pll,int> freq;\n    for(int j = i+1; j < N; j++){\n      ll u = X[i] * Z[j] - X[j] * Z[i];\n      ll v = Y[i] * Z[j] - Y[j] * Z[i];\n      pll p = reduce(u, v);\n      if(p == pll()){\n        res += tot;\n        zero += 1;\n      } else {\n        res += freq[p] + zero;\n        freq[p] += 1;\n      }\n      tot += 1;\n    }\n  }\n  cout << res << '\\n';\n}",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "603",
    "index": "E",
    "title": "Pastoral Oddities",
    "statement": "In the land of Bovinia there are $n$ pastures, but no paths connecting the pastures. Of course, this is a terrible situation, so Kevin Sun is planning to rectify it by constructing $m$ undirected paths connecting pairs of distinct pastures. To make transportation more efficient, he also plans to pave some of these new paths.\n\nKevin is very particular about certain aspects of path-paving. Since he loves odd numbers, he wants each pasture to have an odd number of paved paths connected to it. Thus we call a paving \\underline{sunny} if each pasture is incident to an odd number of paved paths. He also enjoys short paths more than long paths, so he would like the longest paved path to be as short as possible. After adding each path, Kevin wants to know if a sunny paving exists for the paths of Bovinia, and if at least one does, the minimum possible length of the longest path in such a paving. Note that \"longest path\" here means maximum-weight edge.",
    "tutorial": "Hint: What is a necessary and sufficient condition for Kevin to be able to pave paths so that each edge is incident to an odd number of them? Does this problem remind you of constructing a minimum spanning tree? We represent this problem on a graph with pastures as vertices and paths as edges. Call a paving where each vertex is incident to an odd number of paved edges an \\emph{odd paving}. We start with a lemma about such pavings: A connected graph has an odd paving if and only if it has an even number of vertices. For connected graphs with even numbers of vertices, we can prove this observation by considering a spanning tree of the graph. To construct an odd paving, start from the leaves of the tree and greedily pave edges so that each vertex but the root is incident to an odd number of paved edges. Now consider the graph consisting only of paved edges. Since the sum of all vertex degrees in this graph must be even, it follows that the root is also incident to an odd number of paved edges, so the paving is odd. Now we prove that no odd paving exists in the case of an odd number of vertices. Suppose for the sake of contradiction that one existed. Then the sum of the vertex degrees in the graph consisting only of paved edges would be odd, which is impossible. Thus no odd paving exists for graphs with odd numbers of vertices. Note that this observation turns the degree condition into a condition on the parity of connected component sizes. We finish the problem using this equivalent condition. Suppose we only want to solve this problem once, after all $m$ edges are added. Then we can use Kruskal's algorithm to build a minimum spanning forest by adding edges in order of increasing length. We stop once each tree in the forest contains an even number of vertices, since the graph now satisfies the conditions of the lemma. If there are still odd-sized components by the time we add all the edges, then no odd paving exists. This algorithm, however, runs in $O(m\\log m)$ per query, which is too slow if we want to answer after adding each edge. To speed things up, we maintain the ending position of our version of Kruskal's as we add edges online. We do this using a data structure called a link-cut tree. This data structure allows us to add and delete edges from a forest while handling path and connectivity queries. All of these operations take only $O(\\log n)$ time per operation. (A path query asks for something like maximum-weight edge on the path between $u$ and $v$; a connectivity query asks if $u$ and $v$ are connected.) First, let's look at how we can solve the online minimum spanning tree problem with a link-cut tree. We augment our data structure to support finding the maximum-weight edge on the path between vertices $u$ and $v$ in $O(\\log n)$. Adding an edge then works as follows: If $u$ and $v$ are not connected, connect $u$ and $v$; otherwise, if the new edge is cheaper, delete the maximum-weight edge on the path between $u$ and $v$ and add the new edge. To make implementation easier, we can represent edges as vertices in the link-cut tree. For example, if $u$ and $v$ are connected, in the link-cut tree they would be connected as $u$--$e$--$v$, where $e$ is a vertex representing edge $u$--$v$. We solve our original problem with a similar idea. Note that the end state of our variation on Kruskal's is a minimum spanning forest after adding $k$ edges. (We no longer care about the edges that are longer than the longest of these $k$ edges, since the answer is monotonically decreasing---more edges never hurt.) So when we add another edge to the forest, we can use the online minimum spanning tree idea to get the minimum spanning forest that uses the old cheapest $k$ edges and our new edge. Note that inserting the edge never increases the number of odd components: even linked to even is even, even linked to odd is odd, odd linked to odd is even. Now, pretend that we got this arrangement by running Kruskal's algorithm, adding the edges one-by-one. We can \"roll back\" the steps of the algorithm by deleting the longest edge until deleting another edge would give us an odd-sized component. (If we started with an odd-sized component, we don't delete anything.) This gives us an ending position for our Kruskal-like algorithm that uses a minimal number of edges so that all components have even size---we're ready to add another edge. (\"But wait a minute!\" you may say. \"What if edges have the same weight?\" In this case, if we can't remove one of possibly many longest edges, then we can't lower our answer anyway, so we stop.) Note that all of this takes amortized $O(\\log n)$ time per edge. The path queries and the insertion of the new edge involve a constant number of link-cut tree operations. To know which edge to delete, the set of edges currently in the forest can be stored easily in an STL set sorted by length. When adding an edge, we also pay for the cost of deleting that edge, so the \"rolling back\" phase gets accounted for. Therefore, this algorithm runs in $O(m\\log n)$. You may have noticed that executing this algorithm involves checking the size of a connected component in the link-cut tree. This is a detail that needs to be resolved carefully, since link-cut trees usually only handle path operations, not operations that involve subtrees. Here, we stop treating link-cut trees as a black box. (If you aren't familiar with the data structure, you should read about it at https://courses.csail.mit.edu/6.851/spring12/scribe/L19.pdf ) At each vertex, we track the size of its virtual subtree, as well as the sum of the real subtree sizes of its non-preferred children. We can update these values while linking and exposing (a.k.a. accessing), allowing us to perform root-change operations while keeping real subtree sizes. To get the size of a component, we just query for the real subtree size of the root. Since the implementation of this algorithm can be rather challenging, here is a link to a documented version of my code:",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int MAXN = 100005;\nconst int MAXM = 300005;\n \nstruct node{\n  node *l, *r, *p, *m;\n  int f, v, w, s, id;\n  node(int v, int w, int id) : l(), r(), p(), m(this), f(), v(v), w(w), s(w), id(id) {}\n};\n \ninline bool is_root(node *n){\n  return n -> p == NULL || n -> p -> l != n && n -> p -> r != n;\n}\n \ninline bool left(node *n){\n  return n == n -> p -> l;\n}\n \ninline int sum(node *n){ return n ? n -> s : 0; }\ninline node* max(node *n){ return n ? n -> m : NULL; }\n \ninline node* max(node *a, node *b){\n  if(a == NULL || b == NULL) return a ? a : b;\n  return a -> v > b -> v ? a : b;\n}\n \ninline void push(node *n){\n  if(!n -> f) return;\n  n -> f = 0;\n  swap(n -> l, n -> r);\n  if(n -> l) n -> l -> f ^= 1;\n  if(n -> r) n -> r -> f ^= 1;\n}\n \ninline void pull(node *n){\n  n -> m = max(max(max(n -> l), max(n -> r)), n);\n  n -> s = sum(n -> l) + sum(n -> r) + n -> w;\n}\n \ninline void connect(node *n, node *p, bool l){\n  (l ? p -> l : p -> r) = n;\n  if(n) n -> p = p;\n}\n \ninline void rotate(node *n){\n  node *p = n -> p, *g = p -> p;\n  bool l = left(n);\n  connect(l ? n -> r : n -> l, p, l);\n  if(!is_root(p)) connect(n, g, left(p));\n  else n -> p = g;\n  connect(p, n, !l);\n  pull(p), pull(n);\n}\n \ninline void splay(node *n){\n  while(!is_root(n)){\n    node *p = n -> p;\n    if(!is_root(p)) push(p -> p);\n    push(p), push(n);\n    if(!is_root(p)) rotate(left(n) ^ left(p) ? n : p);\n    rotate(n);\n  }\n  push(n);\n}\n \ninline void expose(node *n){\n  node *last = NULL;\n  for(node *m = n; m; m = m -> p){\n    splay(m);\n    m -> w -= sum(last);\n    m -> w += sum(m -> r);\n    m -> r = last;\n    last = m;\n    pull(m);\n  }\n  splay(n);\n}\n \ninline void evert(node *n){\n  expose(n);\n  n -> f ^= 1;\n}\n \ninline void link(node *m, node *n){\n  evert(m);\n  expose(n);\n  m -> p = n;\n  n -> w += sum(m);\n}\n \ninline void cut(node *m, node *n){\n  evert(m);\n  expose(n);\n  n -> l -> p = NULL;\n  n -> l = NULL;\n}\n \ninline node* path_max(node *m, node *n){\n  evert(m);\n  expose(n);\n  return n -> m;\n}\n \ninline int size(node *n){\n  evert(n);\n  return sum(n);\n}\n \ninline bool connected(node *m, node *n){\n  expose(m);\n  expose(n);\n  return m -> p != NULL;\n}\n \nstruct edge{\n  int a, b, w, id;\n  bool operator<(const edge e) const {\n    return w != e.w ? w > e.w : id > e.id;\n  }\n};\n \nint n, m, o;\nnode *v[MAXN], *ev[MAXM];\nvector<edge> ed;\nset<edge> s;\n \nint delete_edge(edge e){\n  cut(v[e.a], ev[e.id]);\n  cut(v[e.b], ev[e.id]);\n  if(size(v[e.a]) & 1 && size(v[e.b]) & 1) o += 2;\n  return !(size(v[e.a]) & 1);\n}\n \nvoid add_edge(edge e){\n  if(size(v[e.a]) & 1 && size(v[e.b]) & 1) o -= 2;\n  link(v[e.a], ev[e.id]);\n  link(v[e.b], ev[e.id]);\n}\n \nvoid new_edge(int a, int b, int w){\n  int id = ed.size();\n  edge e = {a, b, w, id};\n  ed.push_back(e);\n  ev[id] = new node(w, 0, id);\n  if(connected(v[a], v[b])){\n    node* m = path_max(v[a], v[b]);\n    if(m -> v <= w) return;\n    delete_edge(ed[m -> id]);\n    s.erase(ed[m -> id]);\n  }\n  add_edge(e);\n  s.insert(e);\n}\n \nint max_cost(){\n  if(o > 0) return -1;\n  while(delete_edge(*s.begin())){\n    s.erase(s.begin());\n  }\n  add_edge(*s.begin());\n  return s.begin() -> w;\n}\n \nint main(){\n  ios::sync_with_stdio(0);\n  cin.tie(0);\n  cin >> n >> m;\n  for(int i = 1; i <= n; i++){\n    v[i] = new node(0, 1, -i);\n  }\n  o = n;\n  for(int i = 0; i < m; i++){\n    int a, b, w;\n    cin >> a >> b >> w;\n    new_edge(a, b, w);\n    cout << max_cost() << '\\n';\n  }\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dsu",
      "math",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "604",
    "index": "A",
    "title": "Uncowed Forces",
    "statement": "Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.\n\nCodeforces scores are computed as follows: If the maximum point value of a problem is $x$, and Kevin submitted correctly at minute $m$ but made $w$ wrong submissions, then his score on that problem is $\\operatorname*{max}\\left(0.3x,\\left(1-{\\frac{m}{250}}\\right)x-50w\\right)$. His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by $100$ points for each successful hack, but gets decreased by $50$ points for each unsuccessful hack.\n\nAll arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.",
    "tutorial": "Hint: Just do it! But if you're having trouble, try doing your computations using only integers. This problem is straightforward implementation---just code what's described in the problem statement. However, floating point error is one place where you can trip up. Avoid it by rounding (adding $0.5$ before casting to int), or by doing all calculations with integers. The latter is possible since $250$ always divides the maximum point value of a problem. Thus when we rewrite our formula for score as $\\operatorname*{max}\\left(3\\cdot x/10,(250-m)\\cdot x/250\\right)$, it is easy to check that we only have integers as intermediate values.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n \nint pt[5] = {500, 1000, 1500, 2000, 2500}; int tot = 0;\nint m[10], w[10];\nint main() {\n    for (int i = 1; i <= 5; ++i)\n        cin >> m[i];\n    for (int i = 1; i <= 5; ++i)\n        cin >> w[i];\n    \n    int s, u; cin >> s >> u; tot = 100*s-50*u;\n    for (int i = 1; i <= 5; ++i)\n        tot += max(pt[i-1]-pt[i-1]*m[i]/250-50*w[i], pt[i-1]/10*3);\n    \n    cout << tot << endl;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "604",
    "index": "B",
    "title": "More Cowbell",
    "statement": "Kevin Sun wants to move his precious collection of $n$ cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into $k$ boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than \\textbf{two} cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection.\n\nKevin is a meticulous cowbell collector and knows that the size of his $i$-th ($1 ≤ i ≤ n$) cowbell is an integer $s_{i}$. In fact, he keeps his cowbells sorted by size, so $s_{i - 1} ≤ s_{i}$ for any $i > 1$. Also an expert packer, Kevin can fit one or two cowbells into a box of size $s$ if and only if the sum of their sizes does not exceed $s$. Given this information, help Kevin determine the smallest $s$ for which it is possible to put all of his cowbells into $k$ boxes of size $s$.",
    "tutorial": "Hint: Try thinking about a sorted list of cowbells. What do we do with the largest ones? Intuitively, we want to use as many boxes as we can and put the largest cowbells by themselves. Then, we want to pair the leftover cowbells so that the largest sum of a pair is minimized.This leads to the following greedy algorithm: First, if $k  \\ge  n$, then each cowbell can go into its own box, so our answer is $max(s_{1}, s_{2}, ..., s_{n})$. Otherwise, we can have at most $2k - n$ boxes that contain one cowbell. So as the cowbells are sorted by size, we put the $2k - n$ largest into their own boxes. For the remaining $n - (2k - n) = 2(n - k)$ cowbells, we pair the $i$ th largest cowbell with the $(2(n - k) - i + 1)$ th largest. In other words, we match the smallest remaining cowbell with the largest, the second smallest with the second largest, and so on. Given these pairings, we can loop through them to find the largest box we'll need. The complexity of this algorithm is $O(n)$ in all cases. To prove that this greedy works, think about the cowbell the the largest one gets paired with. If it's not the smallest, we can perform a swap so that the largest cowbell is paired with the smallest and not make our answer worse. After we've paired the largest cowbell, we can apply the same logic to the second largest, third largest, etc. until we're done.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int MAXN = 100000;\nint N, K, S[MAXN], res;\n \nint main(){\n  cin >> N >> K;\n  for(int i = 0; i < N; i++){\n    cin >> S[i];\n    res = max(res, S[i]);\n  }\n  for(int i = 0; i < N - K; i++){\n    res = max(res, S[i] + S[2 * (N - K) - 1 - i]);\n  }\n  cout << res << '\\n';\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "605",
    "index": "A",
    "title": "Sorting Railway Cars",
    "statement": "An infinitely long railway has a train consisting of $n$ cars, numbered from $1$ to $n$ (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?",
    "tutorial": "Let's suppose we removed from the array all that elements we would move. What remains? The sequence of the numbers in a row: a, a+1,  \\dots , b. The length of this sequence must be maximal to minimize the number of elements to move. Consider the array pos, where pos[p[i]] = i. Look at it's subsegment pos[a], pos[a+1],  \\dots , pos[b]. This sequence must be increasing and its length as mentioned above must be maximal. So we must find the longest subsegment of pos, where pos[a], pos[a+1],  \\dots , pos[b] is increasing.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "605",
    "index": "B",
    "title": "Lazy Student",
    "statement": "Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:\n\nThe minimum spanning tree $T$ of graph $G$ is such a tree that it contains all the vertices of the original graph $G$, and the sum of the weights of its edges is the minimum possible among all such trees.\n\nVladislav drew a graph with $n$ vertices and $m$ edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.",
    "tutorial": "Let's order edges of ascending length, in case of a tie placing earlier edges we were asked to include to MST. Let's start adding them to the graph in this order. If we asked to include the current edge to MST, use this edge to llink 1st vertex with the least currently isolated vertex. If we asked NOT to include the current edge to MST, use this edge to link some vertices that are already linked but have no edges between them. To do this it's convenient to have two pointer on vertices (let's call them FROM and TO). At the beginning, FROM=2, TO=3. When we are to link two already linked vertices, we add new edge (FROM, TO) and increment FROM. If FROM becomes equal to TO, we can assume we already added all possible edges to TO, so we increment TO and set FROM to 2. This means from this moment we will use non-MST edges to connect TO with all previous vertices starting from 2. If it appears that TO looks at currently isolated vertex, we can assume there are no place for non-MST edge it the graph, so the answer is Impossible. Keep doing in the described way, we'll be adding MST edges as (1,2),  \\dots , (1,n) and non-MST edges as (2,3), (2,4), (3,4), (2,5), (3,5), (4,5), ...",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "605",
    "index": "C",
    "title": "Freelancer's Dreams",
    "statement": "Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least $p$ experience points, and a desired flat in Moscow costs $q$ dollars. Mikhail is determined to follow his dreams and registered at a freelance site.\n\nHe has suggestions to work on $n$ distinct projects. Mikhail has already evaluated that the participation in the $i$-th project will increase his experience by $a_{i}$ per day and bring $b_{i}$ dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time.\n\nFind the real value, equal to the minimum number of days Mikhail needs to make his dream come true.\n\nFor example, suppose Mikhail is suggested to work on three projects and $a_{1} = 6$, $b_{1} = 2$, $a_{2} = 1$, $b_{2} = 3$, $a_{3} = 2$, $b_{3} = 6$. Also, $p = 20$ and $q = 20$. In order to achieve his aims Mikhail has to work for $2.5$ days on both first and third projects. Indeed, $a_{1}·2.5 + a_{2}·0 + a_{3}·2.5 = 6·2.5 + 1·0 + 2·2.5 = 20$ and $b_{1}·2.5 + b_{2}·0 + b_{3}·2.5 = 2·2.5 + 3·0 + 6·2.5 = 20$.",
    "tutorial": "We can let our hero not to receive money or experience for some projects. This new opportunity does not change the answer. Consider the hero spent time T to achieve his dream. On each project he spent some part of this time (possibly zero). So the average speed of making money and experience was linear combination of speeds on all these projects, weighted by parts of time spent for each of the projects. Let's build the set P on the plane of points (x, y) such that we can receive x money and y experience per time unit. Place points (a[i], b[i]) on the plane. Add also two points (max(a[i]), 0) and (0, max(b[i])). All these points for sure are included to P. Find their convex hull. After that, any point inside or at the border of the convex hull would correspond to usage of some linear combination of projects. Now we should select some point which hero should use as the average speed of receiving money and experience during all time of achieving his dream. This point should be non-strictly inside the convex hull. The dream is realized if we get to point (A,B). The problem lets us to get upper of righter, but to do so is not easier than to get to the (A,B) itself. So let's direct a ray from (0,0) to (A,B) and find the latest moment when this ray was inside our convex hull. This point would correspond to the largest available speed of receiving resources in the direction of point (A,B). Coordinates of this point are speed of getting resources. To find the point, we have to intersect the ray and the convex hull.",
    "tags": [
      "geometry"
    ],
    "rating": 2400
  },
  {
    "contest_id": "605",
    "index": "D",
    "title": "Board Game",
    "statement": "You are playing a board card game. In this game the player has two characteristics, $x$ and $y$ — the white magic skill and the black magic skill, respectively. There are $n$ spell cards lying on the table, each of them has four characteristics, $a_{i}$, $b_{i}$, $c_{i}$ and $d_{i}$. In one move a player can pick one of the cards and cast the spell written on it, but only if first two of it's characteristics meet the requirement $a_{i} ≤ x$ and $b_{i} ≤ y$, i.e. if the player has enough magic skill to cast this spell. However, after casting the spell the characteristics of a player change and become equal to $x = c_{i}$ and $y = d_{i}$.\n\nAt the beginning of the game both characteristics of a player are equal to zero. The goal of the game is to cast the $n$-th spell. Your task is to make it in as few moves as possible. You are allowed to use spell in any order and any number of times (for example, you may not use some spells at all).",
    "tutorial": "Consider n vectors starting at points (a[i], b[i]) and ending at points (c[i], d[i]). Run BFS. On each of its stages we must able to perform such an operation: get set of vectors starting inside rectangle 0 <= x <= c[i], 0 <= y <= d[i] and never consider these vectors again. It can be managed like this. Compress x-coordinates. For each x we'll hold the list of vectors which first coordinate is x. Create a segment tree with first coordinate as index and second coordinate as value. The segment tree must be able to find index of minimum for segment and to set value at point. Now consider we have to find all the vectors with first coordinate from 0 to x and second coordinate from 0 to y. Let's find index of minimum in the segment tree for segment [0, x]. This minimum points us to the vector (x,y), whose x - that index of minimum and y - value of minimum. Remove it from list of vectors (adding also to the queue of the BFS) and set in the segment tree to this index second coordinate of the next vector with first coordinate x. Continue this way while minimum on a segment remains less than y. So, on each step we will find list of not yet visited vectors in the bottom right rectangle, and each vector would be considered only once, after what it would be deleted from data structures.",
    "tags": [
      "data structures",
      "dfs and similar"
    ],
    "rating": 2500
  },
  {
    "contest_id": "605",
    "index": "E",
    "title": "Intergalaxy Trips",
    "statement": "The scientists have recently discovered wormholes — objects in space that allow to travel very long distances between galaxies and star systems.\n\nThe scientists know that there are $n$ galaxies within reach. You are in the galaxy number $1$ and you need to get to the galaxy number $n$. To get from galaxy $i$ to galaxy $j$, you need to fly onto a wormhole $(i, j)$ and in exactly one galaxy day you will find yourself in galaxy $j$.\n\nUnfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy $i$ to galaxy $j$ exists during each galaxy day taken separately with probability $p_{ij}$. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day.\n\nYour task is to find the expected value of time needed to travel from galaxy $1$ to galaxy $n$, if you act in the optimal way. It is guaranteed that this expected value exists.",
    "tutorial": "The vertex is the better, the less is the expected number of moves from it to reach finish. The overall strategy is: if it is possible to move to vertex better than current, you should move to it, otherwise stay in place. Just like in Dijkstra, we will keep estimates of answer for each vertex, and fix these estimates as the final answer for all vertices one by one, starting from best vertices to the worst. On the first step we will fix vertex N (the answer for it is zero). On the second step - vertex from which it's easiest to reach N. On the third step - vertex from which it's easiest to finish, moving to vertices determined on first two steps. And so on. On each step we find such vertex which gives best expected number of moves if we are to move from it to vertices better than it and then we fix this expected number - it cannot change from now. For each non-fixed yet vertex we can find an estimate of expected time it takes to reach finish from it. In this estimate we take into account knowledge about vertices we know answer for. We iterate through vertices in order of non-increasing answer for them, so the answer for vertex being estimated is not better than for vertices we already iterate through. Let's see the expression for expected time of getting to finish from vertex x, considering use of tactic \"move to best of i accessible vertices we know answer for, or stay in place\": m(x) = p(x, v[0]) * ans(v[0]) + (1 - p(x, v[0]) * p(x, v[1]) * ans(v[1]) + (1 - p(x, v[0]) * (1 - p(x, v[1]) * p(x, v[2]) * ans(v[2]) +  \\dots  + (1 - p(x, v[0]) * (1 - p(x, v[1]) *  \\dots  * (1 - p(x, v[i-1]) * m(x) + 1 Here m(x) - estimate for vertex x, p(a,b) - the probability of existence of edge (a,b), and ans(v) - known answer for vertex v. Note that m(x) expressed by itself, because there is a probability of staying in place. We will keep estimating expression for each vertex in the form of m(x) = A[x] * m(x) + B[x]. For each vertex we will keep A[x] and B[x]. This would mean that with some probabilites it would be possible to move to some better vertex, and this opportunity gives contribution to expected time equal to B[x], and also with some probability we have to stay in place, and this probability is A[x] (this is just the same as coefficient before m(x) in the expression). So, on each step we select one currently non-fixed vertex v with minimal estimate, then fix it and do relaxation from it, refreshing estimates for other vertices. When we refresh estimate for some vertex x, we change its A[x] and B[x]. A[x] is reduced by A[x] * p(x,v), because the probability of staying still consider it's not possible to move to v. B[x] is increased by A[x] * p(x,v) * ans(v), where A[x] is the probability that it's not possible to use some vertex better than v, A[x] * p(x,v) is the probability that it's also possible to use vertex v, and ans(v) - known answer we just fixed for vertex v. To calculate the value of estimate for some vertex x, we can use expression m(x) = A[x] * m(x) + B[x] and express m(x) from it. Exactly m(x) is that value we should keep on the priority queue in out Dijkstra analogue, and exactly m(x) is the value to fix as the final answer for vertex x, when this vertex is announced as vertex with minimal estimate at the start of a step.",
    "tags": [
      "probabilities",
      "shortest paths"
    ],
    "rating": 2700
  },
  {
    "contest_id": "606",
    "index": "A",
    "title": "Magic Spheres",
    "statement": "Carl is a beginner magician. He has $a$ blue, $b$ violet and $c$ orange magic spheres. In one move he can transform two spheres \\textbf{of the same color} into one sphere of any other color. To make a spell that has never been seen before, he needs at least $x$ blue, $y$ violet and $z$ orange spheres. Can he get them (possible, in multiple actions)?",
    "tutorial": "Let's count how many spheres of each type are lacking to the goal. We must do at least that many transformations. Let's count how many spheres of each type are extra relative to the goal. Each two extra spheres give us an opportunity to do one transformation. So to find out how many transformations can be done from the given type of spheres, one must look how many extra spheres there are, divide this number by 2 and round down. Let's sum all the opportunities of transformations from each type of spheres and all the lacks. If there are at least that many opportunities of transformations as the lacks, the answer is positive. Otherwise, it's negative.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "606",
    "index": "B",
    "title": "Testing Robots",
    "statement": "The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell $(x_{0}, y_{0})$ of a rectangular squared field of size $x × y$, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly $x·y$ tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same.\n\nAfter placing the objects on the field the robot will have to run a sequence of commands given by string $s$, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code.\n\nMoving to the left decreases coordinate $y$, and moving to the right increases it. Similarly, moving up decreases the $x$ coordinate, and moving down increases it.\n\nThe tests can go on for very long, so your task is to predict their results. For each $k$ from $0$ to $length(s)$ your task is to find in how many tests the robot will run exactly $k$ commands before it blows up.",
    "tutorial": "Let's prepare a matrix, where for each cell we will hold, at which moment the robot visits it for the first time while moving through its route. To find these values, let's follow all the route. Each time we move to a cell we never visited before, we must save to the corresponding matrix' cell, how many actions are done now. Let's prepare an array of counters, in which for each possible number of actions we will hold how many variants there were, when robot explodes after this number of actions. Now let's iterate through all possible cells where mine could be placed. For each cell, if it wasn't visited by robot, add one variant of N actions, where N is the total length of the route. If it was, add one variant of that many actions as written in this cell (the moment of time when it was visited first). Look, if there is a mine in this cell, robot would explode just after first visiting it. The array of counters is now the answer to the problem.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "607",
    "index": "A",
    "title": "Chain Reaction",
    "statement": "There are $n$ beacons located at distinct positions on a number line. The $i$-th beacon has position $a_{i}$ and power level $b_{i}$. When the $i$-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance $b_{i}$ inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.\n\nSaitama wants Genos to add a beacon \\textbf{strictly to the right} of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.",
    "tutorial": "It turns out that it is actually easier to compute the complement of the problem - the maximum number of objects not destroyed. We can subtract this from the total number of objects to obtain our final answer. We can solve this problem using dynamic programming. Let $dp[x]$ be the maximum number of objects not destroyed in the range $[0, x]$ given that position $x$ is unaffected by an explosion. We can compute $dp[x]$ using the following recurrence: $d p[x]={\\left\\{d p[x-1]\\right.}_{\\mathrm{~where~}b_{i{\\mathrm{~is~the~power~level~of~the~position~}}x}}$ Now, if we can place an object to the right of all objects with any power level, we can destroy some suffix of the (sorted list of) objects. The answer is thus the maximum number of destroyed objects objects given that we destroy some suffix of the objects first. This can be easily evaluated as $\\operatorname*{max}_{1\\leq i\\leq n}d p[a_{i}]$ Since this is the complement of our answer, our final answer is actually $n-\\operatorname*{max}_{1<i<n}d p[a_{i}]$ Time Complexity - $O(max(a_{i}))$, Memory Complexity - $O(max(a_{i}))$",
    "code": "\"#include <iostream>\\nusing namespace std;\\nconst int maxn = 1e6 + 5;\\n\\nint n, b[maxn], dp[maxn];\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(NULL);\\n    cin >> n;\\n    for (int i = 0, a; i < n; i++) {\\n        cin >> a;\\n        cin >> b[a];\\n    }\\n    if (b[0] > 0) {\\n        dp[0] = 1;\\n    }\\n    int mx = 0;\\n    for (int i = 1; i < maxn; i++) {\\n        if (b[i] == 0) {\\n            dp[i] = dp[i - 1];\\n        } else {\\n            if (b[i] >= i) {\\n                dp[i] = 1;\\n            } else {\\n                dp[i] = dp[i - b[i] - 1] + 1;\\n            }\\n        }\\n        if (dp[i] > mx) {\\n            mx = dp[i];\\n        }\\n    }\\n    cout << n - mx << '\\\\n';\\n    return 0;\\n}\\n\"",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "607",
    "index": "B",
    "title": "Zuma",
    "statement": "Genos recently installed the game Zuma on his phone. In Zuma there exists a line of $n$ gemstones, the $i$-th of which has color $c_{i}$. The goal of the game is to destroy all the gemstones in the line as quickly as possible.\n\nIn one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?\n\nLet us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.",
    "tutorial": "We use dp on contiguous ranges to calculate the answer. Let $D[i][j]$ denote the number of seconds it takes to collapse some range $[i, j]$. Let us work out a transition for this definition. Consider the left-most gemstone. This gemstone will either be destroyed individually or as part of a non-singular range. In the first case, we destroy the left-most gemstone and reduce to the subproblem $[i + 1, j]$. In the second case, notice that the left-most gemstone will match up with some gemstone to its right. We can iterate through every gemstone with the same color as the left-most (let $k$ be the index of this matching gemstone) and reduce to two subproblems $[i + 1, k - 1]$ and $[k + 1, j]$. We can reduce to the subproblem $[i + 1, k - 1]$ because we can just remove gemstones $i$ and $k$ with the last removal of $[i + 1, k - 1]$. We must also make a special case for when the first two elements in a range are equal and consider the subproblem $[i + 2, j]$. Here is a formalization of the dp: $\\begin{array}{c}{{}}\\\\ {{D[i][j]=\\left\\{\\begin{array}{l}{{\\qquad\\qquad}}\\\\ {{1,\\mathrm{if}\\,i=j}}\\\\ {{\\qquad\\qquad}}\\\\ {{\\qquad\\qquad}}\\\\ {{\\qquad\\qquad}}\\\\ {{\\qquad\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\operatorname{oup}\\int_{\\qquad}^{\\qquad}}\\\\ {{\\qquad}}&{{\\qquad}}\\end{array}\\qquad\\qquad}}\\\\ {{\\qquad}}\\\\ {{\\qquad}}&{{\\qquad}}\\\\ {{\\qquad}}&{{\\qquad}}\\\\ {{\\qquad}}&{{\\qquad}}\\\\ {{\\qquad}}{{\\qquad}}&{{\\qquad}}\\\\ {{\\qquad}}\\operatorname{ouy~\\operatorname{ncladededed~in~min~{\\sinh}{i f}}}}\\end{array}$ http://codeforces.com/blog/entry/22256?#comment-268876Why is this dp correct? Notice that the recursive version of our dp will come across the optimal solution in its search. Moreover, every path in the recursive search tree corresponds to some valid sequence of deletions. Since our dp only searches across valid deletions and will at some point come across the optimal sequence of deletions, the answer it produces will be optimal. Time Complexity - $O(n^{3})$, Space Complexity - $O(n^{2})$",
    "code": "\"#include<algorithm>\\n#include<cstdio>\\nusing namespace std;\\nconst int maxn=505;\\n\\nint n, a[maxn], d[maxn][maxn];\\n\\nvoid read() {\\n\\tscanf(\\\"%d\\\", &n);\\n\\tfor (int i = 0; i < n; i++) {\\n\\t\\tscanf(\\\"%d\\\", a + i);\\n\\t}\\n}\\n\\nvoid fun() {\\n\\tfor (int len = 1; len <= n; len++) {\\n\\t\\tfor (int beg = 0, end = len - 1; end < n; beg++, end++) {\\n\\t\\t\\tif (len == 1) {\\n\\t\\t\\t\\td[beg][end] = 1;\\n\\t\\t\\t} else {\\n\\t\\t\\t\\td[beg][end] = 1 + d[beg + 1][end];\\n\\t\\t\\t\\tif (a[beg] == a[beg + 1]) {\\n\\t\\t\\t\\t\\td[beg][end] = min(1 + d[beg + 2][end], d[beg][end]);\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tfor (int match = beg + 2; match <= end; match++) {\\n\\t\\t\\t\\t\\tif (a[beg] == a[match]) {\\n\\t\\t\\t\\t\\t\\td[beg][end] = min(d[beg + 1][match - 1] + d[match + 1][end], d[beg][end]);\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\\n\\nint main() {\\n\\tread();\\n\\tfun();\\n\\tprintf(\\\"%d\\\\n\\\", d[0][n-1]);\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "607",
    "index": "C",
    "title": "Marbles",
    "statement": "In the spirit of the holidays, Saitama has given Genos two grid paths of length $n$ (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.\n\nOne example of a grid path is $(0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1)$. Note that squares in this sequence might be repeated, i.e. path has self intersections.\n\nMovement within a grid path is restricted to adjacent squares within the sequence. That is, from the $i$-th square, one can \\textbf{only move} to the $(i - 1)$-th or $(i + 1)$-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some $j$-th square of the path that coincides with the $i$-th square, only moves to $(i - 1)$-th and $(i + 1)$-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.\n\nTo ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence $(0, 0) → (0, 1) → (0, 0)$ \\textbf{cannot occur} in a valid grid path.\n\nOne marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.\n\nMoving north increases the second coordinate by $1$, while moving south decreases it by $1$. Similarly, moving east increases first coordinate by $1$, while moving west decreases it.\n\nGiven these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.",
    "tutorial": "Define the reverse of a sequence as the sequence of moves needed to negate the movement. For example, EEE and WWW are reverses, and WWSSSEE and WWNNNEE are reverses. I claim is impossible to get both balls to the end if and only if some suffix of the first sequence is the reverse of a suffix of the second sequence. Let us prove the forward case first, that if two suffixes are reverses, then it is impossible to get both balls to the end. Consider a sequence and its reverse, and note that they share the same geometric structure, except that the direction of travel is opposite. Now imagine laying the two grid paths over each other so that their reverse suffixes are laying on top of each other. It becomes apparent that in order to move both balls to their ends, they must cross over at some point within the confines of the suffix. However, this is impossible under the movement rules, as in order for this to happen, the two balls need to move in different directions at a single point in time, which is not allowed. Now let us prove the backwards case: that if no suffixes are reverses, then it is possible for both balls to reach the end. There is a simple algorithm that achieves this goal, which is to move the first ball to its end, then move the second ball to its end, then move the first ball to its end, and so on. Let's denote each of these \"move the x ball to its end\" one step in the algorithm. After every step, the combined distance of both balls from the start is strictly increasing. Without loss of generality, consider a step where you move the first ball to the end, this increases the distance of the first ball by some value $k$. However, the second ball can move back at most $k - 1$ steps (only its a reverse sequence can move back $k$ steps), so the minimum change in distance is $+ 1$. Hence, at some point the combined distance will increase to $2(n - 1)$ and both balls will be at the end. In order to check if suffixes are reverses of each other, we can take reverse the first sequence, and see if one of its prefixes matches a suffix of the second sequence. This can be done using string hashing or KMP in linear time. Time Complexity - $O(n)$, Memory Complexity - $O(n)$",
    "code": "\"import java.io.*;\\n\\npublic class Main {\\n    final static String dirs = \\\"NSEW\\\";\\n\\n    public static void solve(Input in, PrintWriter out) throws IOException {\\n        int n = in.nextInt() - 1;\\n        String s1 = in.next();\\n        String s2 = in.next();\\n        StringBuilder sb = new StringBuilder();\\n        for (int i = 0; i < n; ++i) {\\n            sb.append(dirs.charAt(dirs.indexOf(s1.charAt(n - i - 1)) ^ 1));\\n        }\\n        sb.append(s2);\\n        int[] p = new int[2 * n];\\n        for (int i = 1; i < 2 * n; ++i) {\\n            p[i] = p[i - 1];\\n            while (p[i] != 0 && sb.charAt(i) != sb.charAt(p[i])) {\\n                p[i] = p[p[i] - 1];\\n            }\\n            if (sb.charAt(i) == sb.charAt(p[i])) {\\n                p[i]++;\\n            }\\n        }\\n        out.println(p[2 * n - 1] == 0 ? \\\"YES\\\" : \\\"NO\\\");\\n    }\\n\\n    public static void main(String[] args) throws IOException {\\n        PrintWriter out = new PrintWriter(System.out);\\n        solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);\\n        out.close();\\n    }\\n\\n    static class Input {\\n        BufferedReader in;\\n        StringBuilder sb = new StringBuilder();\\n\\n        public Input(BufferedReader in) {\\n            this.in = in;\\n        }\\n\\n        public Input(String s) {\\n            this.in = new BufferedReader(new StringReader(s));\\n        }\\n\\n        public String next() throws IOException {\\n            sb.setLength(0);\\n            while (true) {\\n                int c = in.read();\\n                if (c == -1) {\\n                    return null;\\n                }\\n                if (\\\" \\\\n\\\\r\\\\t\\\".indexOf(c) == -1) {\\n                    sb.append((char)c);\\n                    break;\\n                }\\n            }\\n            while (true) {\\n                int c = in.read();\\n                if (c == -1 || \\\" \\\\n\\\\r\\\\t\\\".indexOf(c) != -1) {\\n                    break;\\n                }\\n                sb.append((char)c);\\n            }\\n            return sb.toString();\\n        }\\n\\n        public int nextInt() throws IOException {\\n            return Integer.parseInt(next());\\n        }\\n\\n        public long nextLong() throws IOException {\\n            return Long.parseLong(next());\\n        }\\n\\n        public double nextDouble() throws IOException {\\n            return Double.parseDouble(next());\\n        }\\n    }\\n}\\n\"",
    "tags": [
      "hashing",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "607",
    "index": "D",
    "title": "Power Tree",
    "statement": "Genos and Saitama went shopping for Christmas trees. However, a different type of tree caught their attention, the exalted Power Tree.\n\nA Power Tree starts out as a single root vertex indexed $1$. A Power Tree grows through a magical phenomenon known as an update. In an update, a single vertex is added to the tree as a child of some other vertex.\n\nEvery vertex in the tree (the root and all the added vertices) has some value $v_{i}$ associated with it. The power of a vertex is defined as the strength of the multiset composed of the value associated with this vertex ($v_{i}$) and the powers of its direct children. The strength of a multiset is defined as the sum of all elements in the \\textbf{multiset} multiplied by the number of elements in it. Or in other words for some \\textbf{multiset} $S$:\n\n\\[\nS t r e n g t h(S)=|S|\\cdot\\sum_{d\\in S}d\n\\]\n\nSaitama knows the updates that will be performed on the tree, so he decided to test Genos by asking him queries about the tree during its growth cycle.\n\nAn update is of the form $1 p v$, and adds a new vertex with value $v$ as a child of vertex $p$.\n\nA query is of the form $2 u$, and asks for the power of vertex $u$.\n\nPlease help Genos respond to these queries modulo $10^{9} + 7$.",
    "tutorial": "Let's solve a restricted version of the problem where all queries are about the root. First however, let us define some notation. In this editorial, we will use $d(x)$ to denote the number of children of vertex $x$. If there is an update involved, $d(x)$ refers to the value prior to the update. To deal these queries, notice that each vertex within the tree has some contribution $c_{i}$ to the root power. This contribution is an integer multiple $m_{i}$ of each vertex's value $v_{i}$, such that $c_{i} = m_{i} \\cdot v_{i}$ If we sum the contributions of every vertex, we get the power of the root. To deal with updates, notice that adding a vertex $u$ to a leaf $p$ scales the multiplier of every vertex in $p$'s subtree by a factor of $\\frac{d(p)+2}{d(p)+1}$. As for the contribution of $u$, notice that $m_{u} = m_{p}$. Now, in order to handle both queries and updates efficiently, we need a fast way to sum all contributions, a way to scale contributions in a subtree, and a way to add new vertices. This sounds like a job for ... a segment tree! We all know segment trees hate insertions, so instead of inserting new vertices, we pre-build the tree with initial values $0$, updating values instead of inserting new vertices. In order to efficiently support subtree modification, we construct a segment tree on the preorder walk of the tree, so that every subtree corresponds to a contiguous segment within the segment tree. This segment tree will store the contributions of each vertex and needs to support range-sum-query, range-multiply-update, and point-update (updating a single element). The details of implementing such a segment tree and are left as an exercise to the reader. Armed with this segment tree, queries become a single range-sum. Scaling the contribution in a subtree becomes a range-multiply (we don't need to worry about multiplying un-added vertices because they are set to $0$). And adding a new vertex becomes a range-sum-query to retrieve the contribution of the parent, and then a point-set to set the contribution of the added vertex. Finally, to solve the full version of the problem, notice that the power of a non-root vertex $w$ is a scaled down range sum in the segment tree. The value of the scale is $\\frac{d(w)+1}{m_{w}}$, the proof of which is left as an exercise to the reader. Time Complexity - $O(q\\cdot\\log q)$, Space Complexity - $O(q)$",
    "code": "\"//tonynater\\n\\n#include <iostream>\\n#include <vector>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\nconst ll mod = 1000000007;\\n\\nconst int maxn = 200010;\\n\\nint v[maxn], q, n = 1, qstore[maxn][2]; //input\\n\\nint parent[maxn]; //tree\\nvector<int> children[maxn]; //tree\\n\\nint curtravpos, traversal[maxn], bounds[maxn][2]; //traversal\\n\\nint activechildren[maxn]; //processing\\n\\nvoid dfs(int u) {\\n    traversal[curtravpos] = u;\\n    bounds[u][0] = curtravpos;\\n    ++curtravpos;\\n    for(auto v : children[u]) {\\n        dfs(v);\\n    }\\n    bounds[u][1] = curtravpos-1;\\n}\\n\\nstruct segment_tree {\\n    int b, e;\\n    segment_tree *lst, *rst;\\n    \\n    int sum;\\n    ll mult;\\n    \\n    segment_tree(int _b, int _e) {\\n        b = _b;\\n        e = _e;\\n        sum = 0;\\n        mult = 1;\\n        lst = rst = NULL;\\n        if(b < e) {\\n            lst = new segment_tree(b,(b+e)/2);\\n            rst = new segment_tree((b+e)/2+1,e);\\n            merge();\\n        }\\n    }\\n    \\n    void prop() {\\n        if(mult > 1) {\\n            sum = sum*mult%mod;\\n            if(lst != NULL) {\\n                lst->mult = lst->mult*mult%mod;\\n                rst->mult = rst->mult*mult%mod;\\n            }\\n            mult = 1;\\n        }\\n    }\\n    \\n    void merge() {\\n        if(lst != NULL) {\\n            sum = (lst->sum+rst->sum)%mod;\\n        }\\n    }\\n    \\n    void rmult(int l, int r, int m) {\\n        if(m == 1) {\\n            return;\\n        }\\n        prop();\\n        if(e < l || r < b) {\\n            return;\\n        }else if(l <= b && e <= r) {\\n            mult = m;\\n            prop();\\n        }else {\\n            lst->rmult(l,r,m);\\n            rst->rmult(l,r,m);\\n            merge();\\n        }\\n    }\\n    \\n    void set(int idx, int v) {\\n        prop();\\n        if(b == idx && idx == e) {\\n            sum = v;\\n        }else if(idx <= (b+e)/2) {\\n            lst->set(idx,v);\\n            rst->prop();\\n            merge();\\n        }else {\\n            lst->prop();\\n            rst->set(idx,v);\\n            merge();\\n        }\\n    }\\n    \\n    int get(int l, int r) {\\n        prop();\\n        if(e < l || r < b) {\\n            return 0;\\n        }else if(l <= b && e <= r) {\\n            return sum;\\n        }else {\\n            int lsum = lst->get(l,r);\\n            int rsum = rst->get(l,r);\\n            return (lsum+rsum)%mod;\\n        }\\n    }\\n};\\n\\nll binpow(ll base, int exp) {\\n    if(exp == 0) {\\n        return 1;\\n    }else {\\n        ll half = binpow(base,exp/2);\\n        ll full = half*half%mod;\\n        if(exp%2) {\\n            full = full*base%mod;\\n        }\\n        return full;\\n    }\\n}\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(NULL);\\n    \\n    cin >> v[0] >> q;\\n    \\n    for(int i = 0; i < q; i++) {\\n        cin >> qstore[i][0] >> qstore[i][1];\\n        --qstore[i][1];\\n        if(qstore[i][0] == 1) {\\n            parent[n] = qstore[i][1];\\n            cin >> v[n];\\n            children[parent[n]].push_back(n);\\n            qstore[i][1] = n;\\n            ++n;\\n        }\\n    }\\n    \\n    dfs(0);\\n    \\n    segment_tree *st_root = new segment_tree(0,n-1);\\n    st_root->set(0,v[0]);\\n    \\n    for(int i = 0; i < q; i++) {\\n        int x = qstore[i][1];\\n        if(qstore[i][0] == 1) {\\n            int par = parent[x];\\n            int lb = bounds[par][0], rb = bounds[par][1];\\n            int curchildren = ++activechildren[par];\\n            int mult = binpow(curchildren,mod-2)*(curchildren+1)%mod;\\n            st_root->rmult(lb,rb,mult);\\n            \\n            int parmultfactor = st_root->get(lb,lb)*binpow(v[par],mod-2)%mod;\\n            int childval = ll(parmultfactor)*v[x]%mod;\\n            st_root->set(bounds[x][0],childval);\\n        }else {\\n            int rootres = st_root->get(bounds[x][0],bounds[x][1]);\\n            int scale = 1;\\n            if(x > 0) {\\n                scale = st_root->get(bounds[parent[x]][0],bounds[parent[x]][0])\\n                            *binpow(v[parent[x]],mod-2)%mod;\\n            }\\n            int res = rootres*binpow(scale,mod-2)%mod;\\n            cout << res << '\\\\n';\\n        }\\n    }\\n    \\n    return 0;\\n}\\n\"",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "607",
    "index": "E",
    "title": "Cross Sum",
    "statement": "Genos has been given $n$ distinct lines on the Cartesian plane. Let $\\mathbf{Z}$ be a list of intersection points of these lines. A single point might appear multiple times in this list if it is the intersection of multiple pairs of lines. The order of the list does not matter.\n\nGiven a query point $(p, q)$, let ${\\mathcal{D}}$ be the corresponding list of distances of all points in $\\mathbf{Z}$ to the query point. Distance here refers to euclidean distance. As a refresher, the euclidean distance between two points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ is $\\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}}$.\n\nGenos is given a point $(p, q)$ and a positive integer $m$. He is asked to find the sum of the $m$ smallest elements in ${\\mathcal{D}}$. Duplicate elements in ${\\mathcal{D}}$ are treated as separate elements. Genos is intimidated by Div1 E problems so he asked for your help.",
    "tutorial": "The problem boils down to summing the $k$ closest intersections to a given query point. We binary search on the distance $d$ of $k$th farthest point. For a given distance $d$, the number of points within distance $d$ of our query point is equivalent to the number of pairwise intersections that lie within a circle of radius $d$ centered at our query point. To count the number of intersections, we can find the intersection points of the lines on the circle and sort them. Two lines which intersect will have overlapping intersection points on the circle (i.e. of the form ABAB where As and Bs are the intersection points of two lines). Counting the number of intersections can be done by DP. Once we have $d$, we once again draw a circle of size $d$ but this time we loop through all points in $O(k)$ instead of counting the number of points. It may happen that there are $I < k$ intersections inside the circle of radius $d$ but also $I' > k$ inside a circle of radius $d +  \\epsilon $. In this case, we should calculate the answer for $d$ and add $d(k - I)$. Time Complexity - $O(n\\cdot\\log n\\cdot\\log d+k)$, Space Complexity - $O(n)$",
    "code": "\"#include <algorithm>\\n#include <cmath>\\n#include <iomanip>\\n#include <iostream>\\n#include <vector>\\nusing namespace std;\\nconst int maxn = 5e4 + 5;\\nconst long double pi = acos((long double)(-1));\\n\\nint n, m, beg[maxn], fen[2 * maxn], pos[maxn][2], prv[2 * maxn], nxt[2 * maxn];\\nlong double x, y, a[maxn], b[maxn];\\nvector<pair<long double, int> > circx, span;\\n\\nvoid computeCircleIntersections(long double r) {\\n    circx.clear();\\n    for (int i = 0; i < n; i++) {\\n        long double ca = a[i], cb = b[i];\\n        long double discrim = ca * ca * r * r - cb * cb + r * r;\\n        if (discrim > 0) {\\n            long double sq = sqrt(discrim);\\n            long double x1 = (-sq - ca * cb) / (ca * ca + 1);\\n            long double x2 = ( sq - ca * cb) / (ca * ca + 1);\\n            long double y1 = ca * x1 + cb, y2 = ca * x2 + cb;\\n            long double a1 = atan2(y1, x1), a2 = atan2(y2, x2);\\n            circx.push_back(make_pair(a1, i));\\n            circx.push_back(make_pair(a2, i));\\n        }\\n    }\\n    sort(circx.begin(), circx.end());\\n}\\n\\nvoid add(int idx, int d) {\\n    ++idx;\\n    while (idx < 2 * maxn) {\\n        fen[idx] += d;\\n        idx += (idx & -idx);\\n    }\\n}\\n\\nint sum(int idx) {\\n    ++idx;\\n    int ret = 0;\\n    while (idx > 0) {\\n        ret += fen[idx];\\n        idx -= (idx & -idx);\\n    }\\n    return ret;\\n}\\n\\nlong long countCircleIntersections() {\\n    long long ret = 0;\\n    for (int i = 0, tot = 0; i < circx.size(); i++) {\\n        int idx = circx[i].second;\\n        if (beg[idx] == -1) {\\n            ++tot;\\n            beg[idx] = i;\\n            add(i, 1);\\n        } else {\\n            --tot;\\n            add(beg[idx], -1);\\n            ret += tot - sum(beg[idx]);\\n            beg[idx] = -1;\\n        }\\n    }\\n    return ret;\\n}\\n\\nvoid initCyclicList() {\\n    for (int i = 0; i < circx.size(); i++) {\\n        prv[i] = (i + circx.size() - 1) % circx.size();\\n        nxt[i] = (i + 1) % circx.size();\\n    }\\n}\\n\\nvoid deleteCyclicListElement(int idx) {\\n    int pidx = prv[idx];\\n    int nidx = nxt[idx];\\n    prv[nidx] = pidx;\\n    nxt[pidx] = nidx;\\n}\\n\\nlong double intersectionDistance(int idx1, int idx2) {\\n    --m;\\n    long double ix = (b[idx1] - b[idx2]) / (a[idx2] - a[idx1]);\\n    long double iy = a[idx1] * ix + b[idx1];\\n    long double dist = sqrt(ix * ix + iy * iy);\\n    return dist;\\n}\\n\\nlong double sumCyclicList(int start, int end, int *it) {\\n    long double sum = 0;\\n    for (int idx = it[start]; idx != end; idx = it[idx]) {\\n        sum += intersectionDistance(circx[start].second, circx[idx].second);\\n    }\\n    return sum;\\n}\\n\\nlong double sumCircleIntersections(long double r) {\\n    computeCircleIntersections(r);\\n    if (countCircleIntersections() > m) {\\n        return 0; //degenerate case: a lot of intersections on query point\\n    }\\n    for (int i = 0; i < circx.size(); i++) {\\n        int idx = circx[i].second;\\n        if (beg[idx] == -1) {\\n            beg[idx] = i;\\n            pos[idx][0] = i;\\n        } else {\\n            pos[idx][1] = i;\\n            long double sp = circx[i].first - circx[beg[idx]].first;\\n            if (2 * pi - sp < sp) {\\n                sp = 2 * pi - sp;\\n                int tmp = pos[idx][0];\\n                pos[idx][0] = pos[idx][1];\\n                pos[idx][1] = tmp;\\n            }\\n            span.push_back(make_pair(sp, idx));\\n        }\\n    }\\n    sort(span.begin(), span.end());\\n    initCyclicList();\\n    long double sum = 0;\\n    for (int i = 0; i < span.size(); i++) {\\n        int idx = span[i].second;\\n        if (pos[idx][0] < pos[idx][1]) {\\n            sum += sumCyclicList(pos[idx][0], pos[idx][1], nxt);\\n        } else {\\n            sum += sumCyclicList(pos[idx][0], pos[idx][1], nxt);\\n        }\\n        deleteCyclicListElement(pos[idx][0]);\\n        deleteCyclicListElement(pos[idx][1]);\\n    }\\n    return sum + m * r;\\n}\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(NULL);\\n    cin >> n >> x >> y >> m;\\n    x /= 1000, y /= 1000;\\n    for (int i = 0; i < n; i++) {\\n        cin >> a[i] >> b[i];\\n        a[i] /= 1000, b[i] /= 1000;\\n        b[i] += a[i] * x - y;\\n    }\\n    fill_n(beg, maxn, -1);\\n    long double low = 0, high = 1e10;\\n    for (int i = 0; i < 70; i++) {\\n        long double mid = (low + high) / 2;\\n        computeCircleIntersections(mid);\\n        if (countCircleIntersections() < m) {\\n            low = mid;\\n        } else {\\n            high = mid;\\n        }\\n    }\\n    cout << fixed << setprecision(9) << sumCircleIntersections(low) << '\\\\n';\\n    return 0;\\n}\\n\"",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 3300
  },
  {
    "contest_id": "608",
    "index": "A",
    "title": "Saitama Destroys Hotel",
    "statement": "Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from $0$ to $s$ and elevator initially starts on floor $s$ at time $0$.\n\nThe elevator takes exactly $1$ second to move down exactly $1$ floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor $0$.",
    "tutorial": "The minimum amount of time required is the maximum value of $t_{i} + f_{i}$ and $s$, where t_i and f_i are the time and the floor of the passenger respectively. The initial observation that should be made for this problem is that only the latest passenger on each floor matters. So, we can ignore all passengers that aren't the latest passenger on each floor. Now, assume there is only a passenger on floor $s$. Call this passenger $a$. The time taken for this passenger is clearly $t_{a} + f_{a}$ (the time taken to wait for the passenger summed to the time taken for the elevator to reach the bottom). Now, add in one passenger on a floor lower than $s$. Call this new passenger $b$. There are 2 possibilities for this passenger. Either the elevator reaches the passenger's floor after the passenger's time of arrival or the elevator reaches the passenger's floor before the passenger's time of arrival. For the first case, no time is added to the solution, and the solution remains $t_{a} + f_{a}$. For the second case, the passenger on floor $s$ doesn't matter, and the time taken is $t_{b} + f_{b}$ for the new passenger. The only thing left is to determine whether the elevator reaches the new passenger before $t_{i}$ of the new passenger. It does so if $t_{a} + (f_{a} - f_{b}) > t_{b}$. Clearly this is equivalent to whether $t_{a} + f_{a} > t_{b} + f_{b}$. Thus, the solution is max of $max(t_{a} + f_{a}, t_{b} + f_{b})$. A similar line of reasoning can be applied to the rest of the passengers. Thus, the solution is the maximum value of $t_{i} + f_{i}$ and $s$.",
    "code": "\"n,s = map(int, raw_input().split())\\nans = s\\nfor i in range(n):\\n\\tf,t = map(int, raw_input().split())\\n\\tans = max(ans, t+f)\\nprint ans\\n\"",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "608",
    "index": "B",
    "title": "Hamming Distance Sum",
    "statement": "Genos needs your help. He was asked to solve the following programming problem by Saitama:\n\nThe length of some string $s$ is denoted $|s|$. The Hamming distance between two strings $s$ and $t$ of equal length is defined as $\\sum_{i=1}^{\\left|0|}\\left|s_{i}-t_{i}\\right|$, where $s_{i}$ is the $i$-th character of $s$ and $t_{i}$ is the $i$-th character of $t$. For example, the Hamming distance between string \"0011\" and string \"0110\" is $|0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2$.\n\nGiven two binary strings $a$ and $b$, find the sum of the Hamming distances between $a$ and all contiguous substrings of $b$ of length $|a|$.",
    "tutorial": "We are trying to find $\\sum_{i=0}^{|b|-|a|-1}|a[j]-b[i+j]|$. Swapping the sums, we see that this is equivalent to $\\sum_{j=0}^{|a|-1}\\sum_{i=0}^{|b|-|a|}|a[j]-b[i+j]|$. Summing up the answer in the naive fashion will give an $O(n^{2})$ solution. However, notice that we can actually find $\\sum_{i=0}^{|b|-|a|}|a|j\\rangle-b[i+j]|$ without going through each individual character. Rather, all we need is a frequency count of different characters. To obtain this frequency count, we can simply build prefix count arrays of all characters on $b$. Let's call this prefix count array $F$, where $F[x][c]$ gives the number of occurrences of the character $c$ in the prefix $[0, x)$ of $b$. We can then write $\\sum_{j=0}^{|a|-1}\\sum_{i=0}^{|b|-|a|}|a[j]-b[i+j]|$. as $\\sum_{i=0}^{|a|-1}\\sum_{c=0}^{1}|a|j|-c|\\cdot(F[|b|-|a|+j+1]|c]-F[j|[c])$. This gives us a linear solution. Time Complexity - $O(|a| + |b|)$, Memory Complexity - $O(|b|)$",
    "code": "\"#include <cstdlib>\\n#include <iostream>\\n#include <string>\\nusing namespace std;\\ntypedef long long ll;\\nconst int MAXS = 200010;\\n\\nstring A, B;\\nint F[MAXS][2];\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(NULL);\\n    cin >> A >> B;\\n    for (int i = 1; i <= B.size(); i++) {\\n        for (int j = 0; j < 2; j++) {\\n            F[i][j] = F[i - 1][j];\\n        }\\n        ++F[i][B[i - 1] - '0'];\\n    }\\n    ll res = 0;\\n    for (int i = 0, c; i < A.size(); i++) {\\n        c = A[i]-'0';\\n        for (int j = 0; j < 2; j++) {\\n            res += abs(c - j) * (F[B.size() - A.size() + i + 1][j] - F[i][j]);\\n        }\\n    }\\n    cout << res << '\\\\n';\\n    return 0;\\n}\\n\"",
    "tags": [
      "combinatorics",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "609",
    "index": "A",
    "title": "USB Flash Drives",
    "statement": "Sean is trying to save a large file to a USB flash drive. He has $n$ USB flash drives with capacities equal to $a_{1}, a_{2}, ..., a_{n}$ megabytes. The file size is equal to $m$ megabytes.\n\nFind the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.",
    "tutorial": "Let's sort the array in nonincreasing order. Now the answer is some of the first flash-drives. Let's iterate over array from left to right until the moment when we will have the sum at least $m$. The number of elements we took is the answer to the problem. Complexity: $O(nlogn)$.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "609",
    "index": "B",
    "title": "The Best Gift",
    "statement": "Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are $n$ books on sale from one of $m$ genres.\n\nIn the bookshop, Jack decides to buy two books of different genres.\n\nBased on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.\n\nThe books are given by indices of their genres. The genres are numbered from $1$ to $m$.",
    "tutorial": "Let's denote $cnt_{i}$ - the number of books of $i$ th genre. The answer to problem is equals to $\\sum_{i=1}^{m}\\sum_{i=i+1}^{m}c n t_{i}\\cdot c n t_{j}={\\frac{n\\!\\cdot\\!(n-1)}{2}}-\\sum_{i=1}^{m}{\\frac{c n t_{i}\\cdot(c n t_{i}-1)}{2}}$. In first sum we are calculating the number of good pairs, while in second we are subtracting the number of bad pairs from the number of all pairs. Complexity: $O(n + m^{2})$ or $O(n + m)$.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "609",
    "index": "C",
    "title": "Load Balancing",
    "statement": "In the school computer room there are $n$ servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are $m_{i}$ tasks assigned to the $i$-th server.\n\nIn order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression $m_{a} - m_{b}$, where $a$ is the most loaded server and $b$ is the least loaded one.\n\nIn one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.\n\nWrite a program to find the minimum number of seconds needed to balance the load of servers.",
    "tutorial": "Denote $s$ - the sum of elements in array. If $s$ is divisible by $n$ then the balanced array consists of $n$ elements $\\mathbf{\\Pi}_{n}^{S}$. In this case the difference between maximal and minimal elements is $0$. Easy to see that in any other case the answer is greater than $0$. On the other hand the array consists of $s\\ {\\mathrm{mod}}\\ n$ numbers $\\textstyle\\bigcap_{I n}$ and $n-s\\mod n$ numbers $\\left|\\,{\\frac{\\mathcal{S}}{\\ m}}\\,\\right|$ is balanced with the difference equals to $1$. Let's denote this balanced array $b$. To get array $b$ let's sort array $a$ in nonincreasing order and match element $a_{i}$ to element $b_{i}$. Now we should increase some elements and decrease others. In one operation we can increase some element and decrease another, so the answer is $\\textstyle{\\frac{{\\frac{n}{k-1}}\\left|a_{i}-b_{i}\\right|}{2}}$. Complexity: $O(nlogn)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "609",
    "index": "D",
    "title": "Gadgets for dollars and pounds",
    "statement": "Nura wants to buy $k$ gadgets. She has only $s$ burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.\n\nNura can buy gadgets for $n$ days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.\n\nEach day (from $1$ to $n$) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during $n$ days.\n\nHelp Nura to find the minimum day index when she will have $k$ gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from $1$ to $m$ in order of their appearing in input.",
    "tutorial": "If Nura can buy $k$ gadgets in $x$ days then she can do that in $x + 1$ days. So the function of answer is monotonic. So we can find the minimal day with binary search. Denote $lf = 0$ - the left bound of binary search and $rg = n + 1$ - the right one. We will maintain the invariant that in left bound we can't buy $k$ gadgets and in right bound we can do that. Denote function $f(d)$ equals to $1$ if we can buy $k$ gadgets in $d$ days and $0$ otherwise. As usual in binary search we will choose $d={\\frac{l f+r g}{2}}$. If $f(d) = 1$ then we should move the right bound $rg = d$ and the left bound $lf = d$ in other case. If binary search found the value $lf = n + 1$ then the answer is $- 1$, otherwise the answer is $lf$. Before binary search we can create two arrays of gadgets which are selling for dollars and pounds, and sort them. Easy to see that we should buy gadgets for dollars on day $i  \\le  d$ when dollar costs as small as possible and $j  \\le  d$ when pounds costs as small as possible. Let now we want to buy $x$ gadgets for dollars and $k - x$ gadgets for pounds. Of course we will buy the least cheap of them (we already sort the arrays for that). Let's iterate over $x$ from $0$ to $k$ and maintain the sum of gadgets for dollars $s_{1}$ and the sum of gadgets for pounds $s_{2}$. For $x = 0$ we can calculate the sums in $O(k)$. For other x's we can recalculate the sums in $O(1)$ time from the sums for $x - 1$ by adding gadget for dollars and removing gadget for pounds. Complexity: $O(klogn)$.",
    "tags": [
      "binary search",
      "greedy",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "609",
    "index": "E",
    "title": "Minimum spanning tree for each edge",
    "statement": "Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains $n$ vertices and $m$ edges.\n\nFor each edge $(u, v)$ find the minimal possible weight of the spanning tree that contains the edge $(u, v)$.\n\nThe weight of the spanning tree is the sum of weights of all edges included in spanning tree.",
    "tutorial": "This problem was prepared by dalex. Let's build any MST with any fast algorithm (for example with Kruskal's algorithm). For all edges in MST the answer is the weight of the MST. Let's consider any other edge $(x, y)$. There is exactly one path between $x$ and $y$ in the MST. Let's remove mostly heavy edge on this path and add edge $(x, y)$. Resulting tree is the MST contaning edge $(x, y)$ (this can be proven by Tarjan criterion). Let's fix some root in the MST (for example the vertex $1$). To find the most heavy edge on the path from $x$ to $y$ we can firstly find the heaviest edge on the path from $x$ to $l = lca(x, y)$ and then on the path from $y$ to $l$, where $l$ is the lowest common ancestor of vertices $x$ and $y$. To find $l$ we can use binary lifting method. During calculation of $l$ we also can maintain the weight of the heaviest edge. Of course this problem also can be solved with difficult data structures, for example with Heavy-light decomposition method or with Linkcut trees. Complexity: $O(mlogn)$. It's very strange but I can't find any articles with Tarjan criterion on English (although there are articles on Russian), so here it is: Some spanning tree is minimal if and only if the weight of any other edge $(x, y)$ (not from spanning tree) is not less than the weight of the heaviest edge on the path from $x$ to $y$ in spanning tree.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "609",
    "index": "F",
    "title": "Frogs and mosquitoes",
    "statement": "There are $n$ frogs sitting on the coordinate axis $Ox$. For each frog two values $x_{i}, t_{i}$ are known — the position and the initial length of the tongue of the $i$-th frog (it is guaranteed that all positions $x_{i}$ are different). $m$ mosquitoes one by one are landing to the coordinate axis. For each mosquito two values are known $p_{j}$ — the coordinate of the position where the $j$-th mosquito lands and $b_{j}$ — the size of the $j$-th mosquito. Frogs and mosquitoes are represented as points on the coordinate axis.\n\nThe frog can eat mosquito if mosquito is in the same position with the frog or to the right, and the distance between them is not greater than the length of the tongue of the frog.\n\nIf at some moment several frogs can eat a mosquito the leftmost frog will eat it (with minimal $x_{i}$). After eating a mosquito the length of the tongue of a frog increases with the value of the size of eaten mosquito. It's possible that after it the frog will be able to eat some other mosquitoes (the frog should eat them in this case).\n\nFor each frog print two values — the number of eaten mosquitoes and the length of the tongue after landing all mosquitoes and after eating all possible mosquitoes by frogs.\n\nEach mosquito is landing to the coordinate axis only after frogs eat all possible mosquitoes landed before. Mosquitoes are given in order of their landing to the coordinate axis.",
    "tutorial": "Let's maintain the set of not eaten mosquitoes (for example with set in C++ or with TreeSet in Java) and process mosquitoes in order of their landing. Also we will maintain the set of segments $(a_{i}, b_{i})$, where $a_{i}$ is the position of the $i$-th frog and $b_{i} = a_{i} + l_{i}$, where $l_{i}$ is the current length of the tongue of the $i$-th frog. Let the current mosquito landed in the position $x$. Let's choose segment $(a_{i}, b_{i})$ with minimal $a_{i}$ such that $b_{i}  \\ge  x$. If the value $a_{i}  \\le  x$ we found the frog that will eat mosquito. Otherwise the current mosquito will not be eaten and we should add it to our set. If the $i$-th frog will eat mosquito then it's tongue length will be increased by the size of mosquito and we should update segment $(a_{i}, b_{i})$. After that we should choose the nearest mosquito to the right the from frog and if it's possible eat that mosquito by the $i$-th frog (this can be done with lower_bound in C++). Possibly we should eat several mosquitoes, so we should repeat this process several times. Segments $(a_{i}, b_{i})$ we can store in segment tree by position $a_{i}$ and value $b_{i}$. Now to find segment we need we can do binary search by the value of $a_{i}$ and check the maximum $b_{i}$ value on the prefix to be at least $x$. This will work in $O(nlog^{2}n)$ time. We can improve this solution. Let's go down in segment tree in the following manner: if the maximum value $b_{i}$ in the left subtree of segment tree is at least $x$ then we will go to the left, otherwise we will go to the right. Complexity: $O((n + m)log(n + m))$.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "610",
    "index": "A",
    "title": "Pasha and Stick",
    "statement": "Pasha has a wooden stick of some positive integer length $n$. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be $n$.\n\nPasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.\n\nYour task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer $x$, such that the number of parts of length $x$ in the first way differ from the number of parts of length $x$ in the second way.",
    "tutorial": "If the given $n$ is odd the answer is 0, because the perimeter of any rectangle is always even number. If $n$ is even the number of rectangles which can be construct equals to $n / 4$. If $n$ is divisible by 4 we will count the square, which are deprecated, because we need to subtract 1 from the answer. Asymptotic behavior - $O(1)$.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "610",
    "index": "B",
    "title": "Vika and Squares",
    "statement": "Vika has $n$ jars with paints of distinct colors. All the jars are numbered from $1$ to $n$ and the $i$-th jar contains $a_{i}$ liters of paint of color $i$.\n\nVika also has an infinitely long rectangular piece of paper of width $1$, consisting of squares of size $1 × 1$. Squares are numbered $1$, $2$, $3$ and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number $1$ and some arbitrary color. If the square was painted in color $x$, then the next square will be painted in color $x + 1$. In case of $x = n$, next square is painted in color $1$. If there is no more paint of the color Vika wants to use now, then she stops.\n\nSquare is always painted in only one color, and it takes exactly $1$ liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.",
    "tutorial": "At first let's find the minimum in the given array and store it in the variable $minimum$. It is easy to understand, that we always can paint $n * minimum$ squares. So we need to find such a minimum in the array before which staying the most number of elements, which more than the minimum. In the other words we need to find 2 minimums in the array which are farthest from each other (do not forget about cyclical of the array). If there is only one minumum we need to start paint from the color which stay in the array exactly after the minimum (do not forget about cyclical of the array too). It can be done with help of iterations from the left to the right. We need to store the position of the nearest minimum in the variable and update her and the answer when we meet the element which equals to minimum. Asymptotic behavior - $O(n)$, where $n$ - the number of different colors.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "610",
    "index": "C",
    "title": "Harmony Analysis",
    "statement": "The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find $4$ vectors in $4$-dimensional space, such that every coordinate of every vector is $1$ or $ - 1$ and any two vectors are orthogonal. Just as a reminder, two vectors in $n$-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is:\n\n\\[\n\\sum_{i=1}^{n}a_{i}\\cdot b_{i}=0\n\\]\n\n.Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for $2^{k}$ vectors in $2^{k}$-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?",
    "tutorial": "Let's build the answer recursively. For $k = 0$ the answer is $- 1$ or $+ 1$. Let we want to build the answer for some $k > 0$. At first let's build the answer for $k - 1$. As the answer for $k$ let's take four copies of answer for $k - 1$ with inverting of values in last one. So we have some fractal with $2  \\times  2$ base: $00$, $01$. Let's prove the correctness of such building by induction. Consider two vector from the top (down) half: they have zero scalar product in the left half and in the right, so the total scalar product is also equals to zero. Consider a vector from the top half and from the down: their scalar products in the left and the right halfs differs only in sign, so the total scalar product is also zero. Note the answer is also is a matrix with element $i, j$ equals to \\texttt{+} if the number of one bits in number $i|j$ is even. Complexity $O((2^{k})^{2})$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1800
  },
  {
    "contest_id": "610",
    "index": "D",
    "title": "Vika and Segments",
    "statement": "Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew $n$ black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to $1$ square, that means every segment occupy some set of neighbouring squares situated in one row or one column.\n\nYour task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.",
    "tutorial": "At first let's unite all segments which are in same verticals or horizontals. Now the answer to the problem is the sum of lengths of all segments subtract the number of intersections. Let's count the number of intersections. For this let's use the horizontal scan-line from the top to the bottom (is can be done with help of events - vertical segment is open, vertical segment is close and hadle horizontal segment) and in some data structure store the set of $x$-coordinates of the open segments. For example we can use Fenwick tree with precompression of the coordinates. Now for current horizontal segment we need to take the number of the opened vertical segmetns with value $x$ in the range $x_{1}, x_{2}$, where $x$ - vertical where the vertical segment are locating and $x_{1}, x_{2}$ - the $x$-coordinates of the current horizontal segment. Asymptotic behavior: $O(nlogn)$.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "geometry",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "610",
    "index": "E",
    "title": "Alphabet Permutations",
    "statement": "You are given a string $s$ of length $n$, consisting of first $k$ lowercase English letters.\n\nWe define a $c$-repeat of some string $q$ as a string, consisting of $c$ copies of the string $q$. For example, string \"acbacbacbacb\" is a $4$-repeat of the string \"acb\".\n\nLet's say that string $a$ contains string $b$ as a subsequence, if string $b$ can be obtained from $a$ by erasing some symbols.\n\nLet $p$ be a string that represents some permutation of the first $k$ lowercase English letters. We define function $d(p)$ as the smallest integer such that a $d(p)$-repeat of the string $p$ contains string $s$ as a subsequence.\n\nThere are $m$ operations of one of two types that can be applied to string $s$:\n\n- Replace all characters at positions from $l_{i}$ to $r_{i}$ by a character $c_{i}$.\n- For the given $p$, that is a permutation of first $k$ lowercase English letters, find the value of function $d(p)$.\n\nAll operations are performed sequentially, in the order they appear in the input. Your task is to determine the values of function $d(p)$ for all operations of the second type.",
    "tutorial": "Consider slow solution: for operations of the first type reassign all letters, for operations of the second type let's iterate over the symbols in $s$ from left to right and maintain the pointer to the current position in alphabet permutation. Let's move the pointer cyclically in permutation until finding the current symbol from $s$. And move it one more time after that. Easy to see that the answer is one plus the number of cyclic movements. Actually the answer is also the number of pairs of adjacent symbols in $s$ that the first one is not righter than the second one in permutation. So the answer depends only on values of $cnt_{ij}$ -- the number of adjacent symbols $i$ and $j$. To make solution faster let's maintain the segment tree with matrix $cnt$ in each node. Also we need to store in vertex the symbol in the left end of segment and in the right end. To merge two vertices in the segment tree we should simply add the values in the left and in the right sons in the tree, and update the value for the right end of the left segment and the left end of the right segment. Complexity: $O(nk^{2} + mk^{2}logn)$.",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "611",
    "index": "A",
    "title": "New Year and Days",
    "statement": "Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.\n\nLimak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.\n\nLimak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. He can save one candy either on some fixed day of the week or on some fixed day of the month.\n\nLimak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him.",
    "tutorial": "There are two ways to solve this problem. The first is to hard-code numbers of days in months, check the first day of the year and then iterate over days/months - The second way is to check all possible cases by hand. The 2016 consists of 52 weeks and two extra days. The answer for \"x of week\" will be either 52 or 53. You must also count the number of months with all 31 days and care about February.Bf9QLz",
    "code": "\"// Days (A), by Errichto\\n#include<bits/stdc++.h>\\nusing namespace std;\\n\\nint t[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\\n\\nint main() {\\n\\tint x;\\n\\tscanf(\\\"%d\\\", &x);\\n\\tchar sl[15];\\n\\tscanf(\\\"%s\\\", sl);\\n\\tscanf(\\\"%s\\\", sl);\\n\\tif(sl[0] == 'w') {\\n\\t    int current = 5;\\n\\t    int ans = 0;\\n\\t    for(int i = 0; i < 366; ++i) {\\n\\t        if(current == x) ++ans;\\n\\t        ++current;\\n\\t        if(current > 7) current = 1;\\n\\t    }\\n\\t    printf(\\\"%d\\\\n\\\", ans);\\n\\t\\treturn 0;\\n\\t}\\n\\tint c = 0;\\n\\tfor(int i = 0; i < 12; ++i) c += x <= t[i];\\n\\tprintf(\\\"%d\\\\n\\\", c);\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "611",
    "index": "B",
    "title": "New Year and Old Property",
    "statement": "The year 2015 is almost over.\n\nLimak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — $2015_{10} = 11111011111_{2}$. Note that he doesn't care about the number of zeros in the decimal representation.\n\nLimak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?\n\nAssume that all positive integers are always written without leading zeros.",
    "tutorial": "Each number with exactly one zero can be obtained by taking the number without any zeros (e.g. $63_{10} = 111111_{2}$) and subtracting some power of two, e.g. $63_{10} - 16_{10} = 111111_{2} - 10000_{2} = 101111_{2}$. Subtracting a power of two changes one digit from '1' to '0' and this is what we want. But how can we iterate over numbers without any zeros? It turns out that each of them is of form $2^{x} - 1$ for some $x$ (you can check that it's true for $63_{10}$). What should we do to solve this problem? Iterate over possible values of $x$ to get all possible $2^{x} - 1$ - numbers without any zeros. There are at most $\\log10^{18}$ values to consider because we don't care about numbers much larger than $10^{18}$. For each $2^{x} - 1$ you should iterate over powers of two and try subtracting each of them. Now you have candidates for numbers with exactly one zero. For each of them check if it is in the given interval. You can additionally change such a number into binary system and count zeros to be sure. Watch out for overflows! Use '1LL << x' instead of '1 << x' to get big powers of two.",
    "code": "\"// One zero, by Errichto\\n// O(log^2(n))\\n#include<bits/stdc++.h>\\nusing namespace std;\\n\\nint main() {\\n\\tlong long a, b;\\n\\tscanf(\\\"%lld%lld\\\", &a, &b);\\n\\tint c = 0;\\n\\tfor(int i = 0; (1LL << i) / 2 <= b; ++i)\\n\\t\\tfor(int j = 0; j <= i - 2; ++j) {\\n\\t\\t\\tlong long x = (1LL << i) - 1 - (1LL << j);\\n\\t\\t\\tc += a <= x && x <= b;\\n\\t\\t}\\n\\tprintf(\\\"%d\\\\n\\\", c);\\n\\treturn 0;\\n}\"",
    "tags": [
      "bitmasks",
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "611",
    "index": "C",
    "title": "New Year and Domino",
    "statement": "They say \"years are like dominoes, tumbling one after the other\". But would a year fit into a grid? I don't think so.\n\nLimak is a little polar bear who loves to play. He has recently got a rectangular grid with $h$ rows and $w$ columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered $1$ through $h$ from top to bottom. Columns are numbered $1$ through $w$ from left to right.\n\nAlso, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.\n\nLimak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?",
    "tutorial": "How would we solve this problem in $O(wh + q)$ if a domino would occupy only one cell? Before reading queries we would precalculate $dp[r][c]$ - the number of empty cells in a \"prefix\" rectangle with bottom right corner in a cell $r, c$. Then the answer for rectangle $r1, c1, r2, c2$ is equal to $dp[r2][c2] - dp[r2][c1 - 1] - dp[r1 - 1][c2] + dp[r1 - 1][c1 - 1]$. We will want to use the same technique in this problem. Let's separately consider horizontal and vertical placements of a domino. Now, we will focus on horizontal case. Let's say that a cell is good if it's empty and the cell on the right is empty too. Then we can a place a domino horizontally in these two cells. The crucial observation is that the number of ways to horizontally place a domino is equal to the number of good cells in a rectangle $r1, c1, r1, c2 - 1$. You should precalculate a two-dimensional array $hor[r][c]$ to later find the number of good cells quickly. The same for vertical dominoes.",
    "code": "\"// Domino (C), by Errichto\\n// AC, O(wh + q)\\n#include<bits/stdc++.h>\\nusing namespace std;\\n\\nconst int nax = 2005;\\nchar sl[nax][nax];\\n// horizontal and vertical\\nint hor[nax][nax], ver[nax][nax];\\n\\nint main() {\\n\\tint w, h;\\n\\tscanf(\\\"%d%d\\\", &h, &w);\\n\\tfor(int y = 0; y < h; ++y) scanf(\\\"%s\\\", sl[y]);\\n\\tfor(int y = 0; y < h; ++y) for(int x = 0; x < w; ++x) {\\n\\t\\thor[x+1][y+1] = hor[x][y+1] + hor[x+1][y] - hor[x][y];\\n\\t\\tver[x+1][y+1] = ver[x][y+1] + ver[x+1][y] - ver[x][y];\\n\\t\\tif(sl[y][x] != '.') continue;\\n\\t\\tif(x != w - 1 && sl[y][x+1] == '.') ++hor[x+1][y+1];\\n\\t\\tif(y != h - 1 && sl[y+1][x] == '.') ++ver[x+1][y+1];\\n\\t}\\n\\tint q;\\n\\tscanf(\\\"%d\\\", &q);\\n\\twhile(q--) {\\n\\t\\tint x1, y1, x2, y2;\\n\\t\\tscanf(\\\"%d%d%d%d\\\", &y1, &x1, &y2, &x2);\\n\\t\\t--x1;--y1;\\n\\t\\tint ans = 0;\\n\\t\\tans += hor[x2-1][y2] - hor[x1][y2] - hor[x2-1][y1] + hor[x1][y1];\\n\\t\\tans += ver[x2][y2-1] - ver[x1][y2-1] - ver[x2][y1] + ver[x1][y1];\\n\\t\\tprintf(\\\"%d\\\\n\\\", ans);\\n\\t}\\n\\treturn 0;\\n}\"",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "611",
    "index": "D",
    "title": "New Year and Ancient Prophecy",
    "statement": "Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!\n\nOne fragment of the prophecy is a sequence of $n$ digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.\n\nLimak assumes three things:\n\n- Years are listed in the \\textbf{strictly} increasing order;\n- Every year is a positive integer number;\n- There are no leading zeros.\n\nLimak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo $10^{9} + 7$.",
    "tutorial": "By ${x... y}$ I will mean the number defined by digits with indices $x, x + 1, ..., y$. Let $dp[b][c]$ define the number of ways to split some prefix (into increasing numbers) so that the last number is ${b... c}$ We will try to calculate it in $O(n^{2})$ or $O(n^{2}\\log{n})$. The answer will be equal to the sum of values of $dp[i][n]$ for all $i$. Of course, $dp[b][c] = 0$ if $digit[b] = 0$ - because we don't allow leading zeros. We want to add to $dp[b][c]$ all values $dp[a][b - 1]$ where the number ${a... b - 1}$ is smaller than ${b... c}$. One crucial observation is that longer numbers are greater than shorter ones. So, we don't care about $dp[a][b - 1]$ with very low $a$ because those long numbers are too big (we want ${a... b - 1}$ to be smaller than our current number ${b... c}$). On the other hand, all $a$ that $(b - 1) - a < c - b$ will produce numbers shorter than our current ${b... c}$. Let's add at once all $dp[a][b - 1]$ for those $a$. We need $\\sum_{a=2b-c}^{b-1}d p[a][b-1]$. Creating an additional array with prefix sums will allow us to calculate such a sum in $O(1)$. There is one other case. Maybe numbers ${a... b - 1}$ and ${b... c}$ have the same length. There is (at most) one $a$ that $(b - 1) - a = c - b$. Let's find it and then let's compare numbers ${a... b - 1}$ and ${b... c}$. There are few ways to do it. One of them is to store hashes of each of $n \\cdot (n + 1) / 2$ intervals. Then for fixed $a, b$ we can binary search the first index where numbers ${a...}$ and ${b... }$ differ.Rrgk8T. It isn't an intended solution though. Other way is to precalculate the same information for all pairs $a, b$ with dynamic programming. I defined $nxt[a][b]$ as the lowest $x$ that $digit[a + x]  \\neq  digit[b + x]$. Now, either $nxt[a][b] = nxt[a + 1][b + 1] + 1$ or $nxt[a][b] = 0$.",
    "code": "\"// Ancient Prophecy (D), by Errichto\\n// AC, O(n^2)\\n#include<bits/stdc++.h>\\nusing namespace std;\\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\\n#define RI(i,n) FOR(i,1,(n))\\n#define REP(i,n) FOR(i,0,(n)-1)\\n\\nconst int nax = 5005;\\nconst int mod = 1e9 + 7;\\nconst int inf = 1e9 + 120;\\n\\nint t[nax];\\nchar sl[nax];\\n// int dp[nax][nax];\\n// pref[a][b] = sum(dp[1..a][b])\\nint pref[nax][nax];\\nint nxt[nax][nax];\\n\\nint cmp(int i, int j) {\\n\\tif(t[i] < t[j]) return -1;\\n\\tif(t[i] > t[j]) return 1;\\n\\treturn 0;\\n}\\n\\nint dp(int a, int b) {\\n\\tint x = pref[a][b] - pref[a-1][b];\\n\\tif(x < 0) x += mod;\\n\\treturn x;\\n}\\n\\nint main() {\\n\\tint n;\\n\\tscanf(\\\"%d\\\", &n);\\n\\tscanf(\\\"%s\\\", sl);\\n\\tRI(i, n) t[i] = sl[i-1] - '0';\\n\\t\\n\\tfor(int a = n; a >= 1; --a)\\n\\t\\tfor(int b = n; b > a; --b) {\\n\\t\\t\\tint & x = nxt[a][b];\\n\\t\\t\\tif(t[a] != t[b]) x = a;\\n\\t\\t\\telse if(b == n) x = inf;\\n\\t\\t\\telse x = nxt[a+1][b+1];\\n\\t\\t}\\n\\t\\n\\tRI(i, n) {\\n\\t\\t// dp[1][i] = 1;\\n\\t\\tRI(j, n) pref[j][i] = 1;\\n\\t}\\n\\tFOR(c, 2, n) FOR(d, c, n) {\\n\\t\\tint & x = pref[c][d];\\n\\t\\tint b = c - 1;\\n\\t\\tint a = b - (d - c);\\n\\t\\tx = pref[b][b] - pref[max(a,0)][b];\\n\\t\\tif(x < 0) x += mod;\\n\\t\\tif(a >= 1) {\\n\\t\\t\\tint where = nxt[a][c];\\n\\t\\t\\tif(where < c && t[where] < t[c+where-a]) {\\n\\t\\t\\t\\tx += dp(a, b);\\n\\t\\t\\t\\tif(x >= mod) x -= mod;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif(t[c] == 0) x = 0;\\n\\t\\tpref[c][d] = x + pref[c-1][d];\\n\\t\\tif(pref[c][d] >= mod) pref[c][d] -= mod;\\n\\t}\\n\\tint ans = 0;\\n\\tRI(i, n) ans = (ans + dp(i, n)) % mod;\\n\\tprintf(\\\"%d\\\\n\\\", ans);\\n\\treturn 0;\\n}\"",
    "tags": [
      "dp",
      "hashing",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "611",
    "index": "E",
    "title": "New Year and Three Musketeers",
    "statement": "Do you know the story about the three musketeers? Anyway, you must help them now.\n\nRichelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength $a$, Borthos strength $b$, and Caramis has strength $c$.\n\nThe year 2015 is almost over and there are still $n$ criminals to be defeated. The $i$-th criminal has strength $t_{i}$. It's hard to defeat strong criminals — maybe musketeers will have to fight together to achieve it.\n\nRichelimakieu will coordinate musketeers' actions. In each hour each musketeer can either do nothing or be assigned to one criminal. Two or three musketeers can be assigned to the same criminal and then their strengths are summed up. A criminal can be defeated in exactly one hour (also if two or three musketeers fight him). Richelimakieu can't allow the situation where a criminal has strength bigger than the sum of strengths of musketeers fighting him — a criminal would win then!\n\nIn other words, there are three ways to defeat a criminal.\n\n- A musketeer of the strength $x$ in one hour can defeat a criminal of the strength not greater than $x$. So, for example Athos in one hour can defeat criminal $i$ only if $t_{i} ≤ a$.\n- Two musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of strengths of these two musketeers. So, for example Athos and Caramis in one hour can defeat criminal $i$ only if $t_{i} ≤ a + c$. Note that the third remaining musketeer can either do nothing or fight some other criminal.\n- Similarly, all three musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of musketeers' strengths, i.e. $t_{i} ≤ a + b + c$.\n\nRichelimakieu doesn't want musketeers to fight during the New Year's Eve. Thus, he must coordinate their actions in order to minimize the number of hours till all criminals will be defeated.\n\nFind the minimum number of hours to defeat all criminals. If musketeers can't defeat them all then print \"-1\" (without the quotes) instead.",
    "tutorial": "The answer is $- 1$ only if there is some criminal stronger than $a + b + c$. Let's deal with this case and then let's assume that $a  \\le  b  \\le  c$. Let's store all criminal- s in a set (well, in a multiset). Maybe some criminals can be defeated only by all musketeers together. Let's count and remove them. Then, maybe some criminals can be defeated only by $b + c$ or $a + b + c$ (no other subsets of musketeers can defeat them). We won't use $a + b + c$ now because it's not worse to use $b + c$ because then we have the other musketeer free and maybe he can fight some other criminal. Greedily, let's remove all criminals which can be defeated only by $b + c$ and at the same time let $a$ defeat as strong criminals as possible. Because why would he rest? Now, maybe some criminals can be defeated only by $a + c$ or $b + c$ or $a + b + c$. It's not worse to use $a + c$ and to let the other musketeer $b$ defeat as strong criminals as possible (when two musketeers $a + c$ fight together). We used $a + b + c$, $b + c$, $a + c$. We don't know what is the next strongest subset of musketeers. Maybe it's $a + b$ and maybe it's $c$. Previous greedy steps were correct because we are sure that $a+b+c\\geq a\\geq c\\geq c\\geq{}^{\\prime}\\mathrm{any\\\\other\\\\subset},$. Now in each hour we can either use $a, b, c$ separately or use $a + b$ and $c$. Let's say we will use only pair $a + b$ and $c$. And let's say that there are $x$ criminals weaker than $a + b$ and $y$ criminals weaker than $c$. Then the answer is equal to $m a x({\\frac{x+y}{2}},x-y,y-x)$. The explanation isn't complicated. We can't be faster than $\\scriptstyle{\\frac{x+y}{2}}$ because we fight at most two criminals in each hour. And maybe e.g. $y$ (because $c$ is weak) so $c$ will quickly defeat all $y$ criminals he can defeat - and musketeers $a + b$ must defeat $x - y$ criminals. Ok, we know the answer in $O(1)$ if we're going to use only $a + b$ and $c$. So let's assume it (using only these two subsets) and find the possible answer. Then, let's use $a, b, c$ once. Now we again assume that we use only $a + b$ and $c$. Then we use $a, b, c$ once. And so on. What we did is iterating over the number of times we want to use $a, b, c$.",
    "code": "\"// Musketeers\\n// AC, O(n log(n))\\n// by Errichto\\n#include<bits/stdc++.h>\\nusing namespace std;\\n\\nconst int nax = 1e6 + 5;\\nconst int inf = 1e9 + 5;\\nint m[3];\\nmultiset<int> enemies;\\n\\nvoid greedy(int atLeast, int extra, int & ans) {\\n\\twhile(!enemies.empty()) {\\n\\t\\tauto it = enemies.end();\\n\\t\\t--it;\\n\\t\\tif(*it < atLeast) break;\\n\\t\\tenemies.erase(it);\\n\\t\\t++ans;\\n\\t\\tit = enemies.lower_bound(extra);\\n\\t\\tif(it != enemies.begin()) {\\n\\t\\t\\t--it;\\n\\t\\t\\tenemies.erase(it);\\n\\t\\t}\\n\\t}\\n}\\n\\nint main() {\\n\\tint n;\\n\\tscanf(\\\"%d\\\", &n);\\n\\tfor(int i = 0; i < 3; ++i) scanf(\\\"%d\\\", &m[i]);\\n\\tsort(m, m + 3);\\n\\tfor(int i = 0; i < n; ++i) {\\n\\t\\tint x;\\n\\t\\tscanf(\\\"%d\\\", &x);\\n\\t\\t--x;\\n\\t\\tenemies.insert(x);\\n\\t}\\n\\tint all = m[0] + min(inf, m[1] + m[2]);\\n\\tauto it = enemies.end();\\n\\t--it;\\n\\tif(*it >= all) {\\n\\t\\tputs(\\\"-1\\\");\\n\\t\\treturn 0;\\n\\t}\\n\\tint ans = 0;\\n\\tgreedy(m[1] + m[2], 0, ans);\\n\\tgreedy(m[0] + m[2], m[0], ans);\\n\\tgreedy(max(m[0]+m[1], m[2]), m[1], ans);\\n\\tint one = 0, two = 0;\\n\\tfor(int x : enemies) {\\n\\t\\tif(x < m[0] + m[1]) ++one;\\n\\t\\tif(x < m[2]) ++two;\\n\\t}\\n\\tint best = inf;\\n\\tfor(int rep = 0; rep < n + 5; ++rep) {\\n\\t\\tif(max(one, two) == (int) enemies.size()) {\\n\\t\\t\\tif(2 * min(one, two) >= (int) enemies.size()) best = min(best, rep + ((int) enemies.size() + 1) / 2);\\n\\t\\t\\telse best = min(best, rep + (int) enemies.size() - min(one, two));\\n\\t\\t}\\n\\t\\tfor(int i = 0; i < 3; ++i) {\\n\\t\\t\\tauto it = enemies.lower_bound(m[i]);\\n\\t\\t\\tif(it != enemies.begin()) {\\n\\t\\t\\t\\t--it;\\n\\t\\t\\t\\tif(*it < m[0] + m[1]) --one;\\n\\t\\t\\t\\tif(*it < m[2]) --two;\\n\\t\\t\\t\\tenemies.erase(it);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tprintf(\\\"%d\\\\n\\\", ans + best);\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "611",
    "index": "F",
    "title": "New Year and Cleaning",
    "statement": "Limak is a little polar bear. His parents told him to clean a house before the New Year's Eve. Their house is a rectangular grid with $h$ rows and $w$ columns. Each cell is an empty square.\n\nHe is a little bear and thus he can't clean a house by himself. Instead, he is going to use a cleaning robot.\n\nA cleaning robot has a built-in pattern of $n$ moves, defined by a string of the length $n$. A single move (character) moves a robot to one of four adjacent cells. Each character is one of the following four: 'U' (up), 'D' (down), 'L' (left), 'R' (right). One move takes one minute.\n\nA cleaning robot must be placed and started in some cell. Then it repeats its pattern of moves till it hits a wall (one of four borders of a house). After hitting a wall it can be placed and used again.\n\nLimak isn't sure if placing a cleaning robot in one cell will be enough. Thus, he is going to start it $w·h$ times, one time in each cell. Maybe some cells will be cleaned more than once but who cares?\n\nLimak asks you one question. How much time will it take to clean a house? Find and print the number of minutes modulo $10^{9} + 7$. It's also possible that a cleaning robot will never stop — then print \"-1\" (without the quotes) instead.\n\nPlacing and starting a robot takes no time, however, you must count a move when robot hits a wall. Take a look into samples for further clarification.",
    "tutorial": "Let's not care where we start. We will iterate over robot's moves. Let's say the first moves are LDR. The very first move 'L' hits a wall only if we started in the first column. Let's maintain some subrectangle of the grid - starting cells for which we would still continue cleaning. After the first move our subrectangle lost the first column. The second move 'D' affects the last row. Also, all cells from the last row of our remaining subrectangle have the same score so it's enough to multiply the number of cells there and an index of the current move. The third move 'R' does nothing. Let's simulate all moves till our subrectangle becomes empty. To do it, we should keep the current $x, y$ - where we are with respect to some starting point. We should also keep $max_{x}, max_{y}, min_{x}, min_{y}$ - exceeding value of one of these four variables means that something happens and our subrectangle losts one row or one column. But how to do it fast? You can notice (and prove) that the second and and each next execution of the pattern looks exactly the same. If we have pattern RRUDLDU and the first letter 'U' affects out subrectangle in the second execution of the pattern, then it will also affect it in the third execution and so on. If and only if. So, we should simalate the first $n$ moves (everything can happen there). Then, we should simulate the next $n$ moves and remember all places where something happened. Then we should in loop iterate over these places. Each event will decrease width or height of our subrectangle so the complexity of this part is $O(w + h)$. In total $O(w + h + n)$.",
    "code": "\"// Cleaning Robot (F), by Errichto\\n// AC, O(w+h+n)\\n#include<bits/stdc++.h>\\nusing namespace std;\\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\\n#define RI(i,n) FOR(i,1,(n))\\n#define REP(i,n) FOR(i,0,(n)-1)\\ntypedef long long ll;\\n\\nconst int nax = 5e5 + 5;\\nconst int mod = 1e9 + 7;\\nchar sl[nax];\\n\\nint n;\\nint ans;\\nint low[2], high[2], curr[2], dimension[2];\\n\\nbool f(ll moves, bool cheating) {\\n\\tif(moves != 0 && moves % n == 0 && curr[0] == 0 && curr[1] == 0) {\\n\\t\\tputs(\\\"-1\\\");\\n\\t\\texit(0);\\n\\t}\\n\\tchar type = sl[moves%n];\\n\\tif(type == 'L') cheating ? curr[0] = high[0]+1 : ++curr[0];\\n\\telse if(type == 'R') cheating ? curr[0] = low[0]-1 : --curr[0];\\n\\telse if(type == 'U') cheating ? curr[1] = high[1]+1 : ++curr[1];\\n\\telse if(type == 'D') cheating ? curr[1] = low[1]-1 : --curr[1];\\n\\telse assert(false);\\n\\tbool something_happened = false;\\n\\tREP(i, 2) {\\n\\t\\tif(curr[i] < low[i] || curr[i] > high[i]) {\\n\\t\\t\\tans = (ans + (moves + 1) % mod * dimension[i^1]) % mod;\\n\\t\\t\\t--dimension[i];\\n\\t\\t\\tsomething_happened = true;\\n\\t\\t}\\n\\t\\tif(curr[i] < low[i]) low[i] = curr[i];\\n\\t\\tif(curr[i] > high[i]) high[i] = curr[i];\\n\\t}\\n\\treturn something_happened;\\n}\\n\\nbool inGame() { return dimension[0] > 0 && dimension[1] > 0; }\\n\\nint main() {\\n\\tscanf(\\\"%d%d%d\\\", &n, &dimension[1], &dimension[0]);\\n\\tscanf(\\\"%s\\\", sl);\\n\\t\\n\\tfor(ll moves = 0; inGame() && moves < n; ++moves)\\n\\t\\tf(moves, false);\\n\\tvector<int> w;\\n\\tfor(ll moves = n; inGame() && moves < 2 * n; ++moves)\\n\\t\\tif(f(moves, false)) w.push_back((int) moves % n);\\n\\t\\n\\t\\n\\tfor(ll k = 2; inGame(); ++k)\\n\\t\\tfor(int moves : w) if(inGame())\\n\\t\\t\\tf(k*n + moves, true);\\n\\tprintf(\\\"%d\\\\n\\\", ans);\\n\\treturn 0;\\n}\"",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "611",
    "index": "G",
    "title": "New Year and Cake",
    "statement": "Limak is a little polar bear. According to some old traditions, his bear family prepared a New Year cake. And Limak likes cakes.\n\nAs you may know, a New Year cake is a strictly convex polygon with $n$ vertices.\n\nParents won't allow Limak to eat more than half of a cake because he would get sick. After some thinking they decided to cut a cake along one of $n·(n - 3) / 2$ diagonals. Then Limak will get a non-greater piece.\n\nLimak understands rules but he won't be happy if the second piece happens to be much bigger. Limak's disappointment will be equal to the difference between pieces' areas, multiplied by two. It can be proved that it will be integer for the given constraints.\n\nThere are $n·(n - 3) / 2$ possible scenarios. Consider them all and find the sum of values of Limak's disappointment, modulo $10^{9} + 7$.",
    "tutorial": "We are given a polygon with vertices $P_{1}, P_{2}, ..., P_{n}$. Let $Poly(i, j)$ denote the doubled area of a polygon with vertices $P_{i}, P_{i + 1}, P_{i + 2}, ..., P_{j - 1}, P_{j}$. While implementing you must remember that indices are in a circle (there is $1$ after $n$) but I won't care about it in this editorial. We will use the cross product of two points, defined as $A  \\times  B = A.x \\cdot B.y - A.y \\cdot B.x$. It's well known (and you should remember it) that the doubled area of a polygon with points $Q_{1}, Q_{2}, ..., Q_{k}$ is equal to $Q_{1}  \\times  Q_{2} + Q_{2}  \\times  Q_{3} + ... + Q_{k - 1}  \\times  Q_{k} + Q_{k}  \\times  Q_{1}$. Let $smaller$ denote the area of a smaller piece, $bigger$ for a bigger piece, and $total$ for a whole polygon (cake). $smaller + bigger = total$ $smaller + (smaller + diff) = total$ $diff = total - 2 \\cdot smaller$ (the same applies to doubled areas) And the same equation with sums: $\\textstyle\\sum d i f f=\\sum t o t a l-2\\cdot\\sum s m a l l e r$ where every sum denotes the sum over $\\textstyle{\\frac{n(n-3)}{2}}$ possible divisions. $\\sum d i f f=t o t a l\\cdot{\\frac{n\\cdot(n-3)}{2}}-2\\cdot\\sum s m a l l e r$ In $O(n)$ we can calculate $total$ (the area of the given polygon). So, the remaining thing is to find $\\textstyle\\sum s m a l l e r$ and then we will get $\\textstyle\\sum d i f f$ (this is what we're looking for). For each index $a$ let's find the biggest index $b$ that a diagonal from $a$ to $b$ produces a smaller piece on the left. So, $P o l y(a,b)\\leq{\\frac{i e l a}{2}}$. To do it, we can use two pointers because for bigger $a$ we need bigger $b$. We must keep (as a variable) the sum $S = P_{a}  \\times  P_{a + 1} + ... + P_{b - 1}  \\times  P_{b}$. Note that $S$ isn't equal to $Poly(a, b)$ because there is no $P_{b}  \\times  P_{a}$ term. But $S + P_{b}  \\times  P_{a} = Poly(a, b)$. To check if we should increase $b$, we must calculate $Poly(a, b + 1) = S + P_{b}  \\times  P_{b + 1} + P_{b + 1}  \\times  P_{a}$. If it's not lower that $\\frac{\\l_{t o t a l}}{2}$ then we should increase $b$ by $1$ (we should also increase $S$ by $P_{b}  \\times  P_{b + 1}$). When moving $a$ we should decrease $S$ by $P_{a}  \\times  P_{a + 1}$. For each $a$ we have found the biggest (last) $b$ that we have a smaller piece on the left. Now, we will try to sum up areas of all polygons starting with $a$ and ending not later than $b$. So, we are looking for $Z = Poly(a, a + 1) + Poly(a, a + 2) + ... + Poly(a, b)$. The first term is equal to zero but well, it doesn't change anything. Let's talk about some intuition (way of thinking) for a moment. Each area is equal so the sum of cross products of pairs of adjacent (neighboring) points. We can say that each cross product means one side of a polygon. You can take a look at the sum $Z$ and think - how many of those polygons have a side $P_{a}P_{a + 1}$? All $b - a$ of them. And $b - a - 1$ polygons have a side $P_{a + 1}P_{a + 2}$. And so on. And now let's do it formally: $Poly(a, a + 1) = P_{a}  \\times  P_{a + 1} + P_{a + 1}  \\times  P_{a}$ $Poly(a, a + 2) = P_{a}  \\times  P_{a + 1} + P_{a + 1}  \\times  P_{a + 2} + P_{a + 2}  \\times  P_{a}$ $Poly(a, a + 3) = P_{a}  \\times  P_{a + 1} + P_{a + 1}  \\times  P_{a + 2} + P_{a + 2}  \\times  P_{a + 3} + P_{a + 3}  \\times  P_{a}$ $...$ $Poly(a, b) = P_{a}  \\times  P_{a + 1} + P_{a + 1}  \\times  P_{a + 2} + P_{a + 2}  \\times  P_{a + 3} + ... + P_{b - 1}  \\times  P_{b} + P_{b}  \\times  P_{a}$ $Z = Poly(a, a + 1) + Poly(a, a + 2) + ... + Poly(a, b) =$ $= (b - a) \\cdot (P_{a}  \\times  P_{a + 1}) + (b - a - 1) \\cdot (P_{a + 1}  \\times  P_{a + 2}) + (b - a - 2) \\cdot (P_{a + 2}  \\times  P_{a + 3}) + ... + 1 \\cdot (P_{b - 1}  \\times  P_{b}) +$ $+ P_{a + 1}  \\times  P_{a} + P_{a + 2}  \\times  P_{a} + ... + P_{b}  \\times  P_{a}$ The last equation is intentionally broken into several lines. We have two sums to calculate. The first sum is $(b - a) \\cdot (P_{a}  \\times  P_{a + 1}) + (b - a - 1) \\cdot (P_{a + 1}  \\times  P_{a + 2}) + ... + 1 \\cdot (P_{b - 1}  \\times  P_{b})$. We can calculate it in $O(1)$ if we two more variables sum_product and sum_product2. The first one must be equal to the sum of $P_{i}  \\times  P_{i + 1}$ for indices in an interval $[a, b - 1]$ and the second one must be equal to the sum of $(P_{i}  \\times  P_{i + 1}) \\cdot (i + 1)$. Then, the sum is equal to sum_product * (b + 1) - sum_product2. The second sum is $P_{a + 1}  \\times  P_{a} + P_{a + 2}  \\times  P_{a} + ... + P_{b}  \\times  P_{a} = SUM_POINTS  \\times  P_{a}$ where $SUM_POINTS$ is some fake point we must keep and $SUM_POINTS = P_{a + 1} + P_{a + 2} + ... + P_{b}$. So, this fake point's $x$-coordinate is equal to the sum of $x$-coordinates of $P_{a + 1}, P_{a + 2}, ..., P_{b}$ and the same for $y$-coordinate. In my code you can see variables sum_x and sum_y. Implementation.",
    "code": "\"// Cake, by Errichto\\n// intended, O(n)\\n#include<bits/stdc++.h>\\nusing namespace std;\\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\\n#define RI(i,n) FOR(i,1,(n))\\n#define REP(i,n) FOR(i,0,(n)-1)\\ntypedef long long ll;\\n\\nconst int nax = 1e6 + 15;\\nconst int mod = 1e9 + 7;\\n\\nstruct P {\\n\\tll x, y;\\n\\tll operator * (const P & b) const {\\n\\t\\treturn -x * b.y + y * b.x;\\n\\t}\\n} t[nax];\\n\\nll sum_x, sum_y, sum_product, sum_product2;\\n\\nvoid makeMod() {\\n\\t// sum_x %= mod;\\n\\t// sum_y %= mod;\\n\\t// sum_product %= mod;\\n\\tsum_product2 %= mod;\\n}\\n\\nvoid insert(int i) {\\n\\tsum_x += t[i].x;\\n\\tsum_y += t[i].y;\\n\\tsum_product += t[i-1] * t[i];\\n\\tsum_product2 += (t[i-1] * t[i]) % mod * i;\\n\\tmakeMod();\\n}\\nvoid remove(int i) {\\n\\tsum_x -= t[i].x;\\n\\tsum_y -= t[i].y;\\n\\tsum_product -= t[i] * t[i+1];\\n\\tsum_product2 -= (t[i] * t[i+1]) % mod * (i + 1);\\n\\tmakeMod();\\n}\\n\\t\\nint main() {\\n\\tint n;\\n\\tscanf(\\\"%d\\\", &n);\\n\\tREP(i, n) scanf(\\\"%lld%lld\\\", &t[i].x, &t[i].y);\\n\\tREP(i, n+2) t[i+n] = t[i];\\n\\tll total = 0;\\n\\tREP(i, n) total += t[i] * t[i+1];\\n\\tassert(total > 0);\\n\\tint b = 0;\\n\\tsum_x = t[0].x;\\n\\tsum_y = t[0].y;\\n\\tll ans = 0;\\n\\tREP(a, n) {\\n\\t\\twhile(true) {\\n\\t\\t\\tunsigned long long tmp = 2 * (sum_product + (unsigned long long)( t[b] * t[b+1]) + (unsigned long long) (t[b+1] * t[a]));\\n\\t\\t\\tif(tmp < (unsigned long long)total || (tmp == (unsigned long long)total && b + 1 < n)) {\\n\\t\\t\\t\\tinsert(b + 1);\\n\\t\\t\\t\\t++b;\\n\\t\\t\\t}\\n\\t\\t\\telse break;\\n\\t\\t}\\n\\t\\tll tmp = sum_product % mod * (b + 1) - sum_product2;\\n\\t\\ttmp %= mod;\\n\\t\\tP fake = P{sum_x % mod, sum_y % mod};\\n\\t\\ttmp += fake * t[a];\\n\\t\\tans += tmp;\\n\\t\\tans %= mod;\\n\\t\\tremove(a);\\n\\t}\\n\\tans = (ll) n * (n - 3) / 2 % mod * (total % mod) - 2 * ans;\\n\\tans = (ans % mod + mod) % mod;\\n\\tprintf(\\\"%lld\\\\n\\\", ans);\\n\\treturn 0;\\n}\"",
    "tags": [
      "geometry",
      "two pointers"
    ],
    "rating": 2900
  },
  {
    "contest_id": "611",
    "index": "H",
    "title": "New Year  and Forgotten Tree",
    "statement": "A tree is a connected undirected graph with $n - 1$ edges, where $n$ denotes the number of vertices. Vertices are numbered $1$ through $n$.\n\nLimak is a little polar bear. His bear family prepares a New Year tree every year. One year ago their tree was more awesome than usually. Thus, they decided to prepare the same tree in the next year. Limak was responsible for remembering that tree.\n\nIt would be hard to remember a whole tree. Limak decided to describe it in his notebook instead. He took a pen and wrote $n - 1$ lines, each with two integers — indices of two vertices connected by an edge.\n\nNow, the New Year is just around the corner and Limak is asked to reconstruct that tree. Of course, there is a problem. He was a very little bear a year ago, and he didn't know digits and the alphabet, so he just replaced each digit with a question mark — the only character he knew. That means, for any vertex index in his notes he knows only the number of digits in it. At least he knows there were no leading zeroes.\n\nLimak doesn't want to disappoint everyone. Please, take his notes and reconstruct a New Year tree. Find any tree matching Limak's records and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print \"-1\" (without the quotes).",
    "tutorial": "There are at most $k = 6$ groups of vertices. Each grouped is defined by the number of digits of its vertices. It can be probed that you can choose one vertex (I call it \"boss\") in each group and then each edge will be incident with at least one boss. We can iterate over all $k^{k - 2}$ possible labeled trees - we must connect bosses with $k - 1$ edges. Then we should add edges to other vertices. An edge between groups $x$ and $y$ will \"kill\" one vertex either from a group $x$ or from a group $y$. You can solve it with flow or in $O(2^{k})$ with Hall's theorem.",
    "code": "\"// Forgotten tree (H), by Errichto\\n#include<bits/stdc++.h>\\nusing namespace std;\\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\\n#define RI(i,n) FOR(i,1,(n))\\n#define REP(i,n) FOR(i,0,(n)-1)\\n\\nchar sl[10];\\nint e[10][10], e_memo[10][10];\\nvector<int> group[10];\\nint boss[10];\\n\\ntypedef vector<pair<int,int>> Tree;\\n\\nvector<int> w[10];\\nbool vis[10];\\nvoid dfs(int a) {\\n\\tvis[a] = true;\\n\\tfor(int b : w[a]) if(!vis[b]) dfs(b);\\n}\\nbool validTree(Tree t, int k) {\\n\\tfor(pair<int,int> edge : t) {\\n\\t\\tw[edge.first].push_back(edge.second);\\n\\t\\tw[edge.second].push_back(edge.first);\\n\\t}\\n\\tdfs(1);\\n\\tbool ans = true;\\n\\tRI(i, k) if(!vis[i]) ans = false;\\n\\tRI(i, k) vis[i] = false;\\n\\tRI(i, k) w[i].clear();\\n\\treturn ans;\\n}\\n\\nbool checkEverything(int k) { // O(k * 2^k)\\n\\tREP(mask, (1 << k)) {\\n\\t\\tvector<int> subset;\\n\\t\\tREP(i, k) if(mask & (1 << i)) subset.push_back(i + 1);\\n\\t\\tint vertices = 0, edges = 0;\\n\\t\\tfor(int i : subset) vertices += group[i].size() - 1;\\n\\t\\tfor(int i : subset) for(int j : subset) edges += e[i][j];\\n\\t\\tif(edges > vertices) return false;\\n\\t}\\n\\treturn true;\\n}\\n\\nvoid write(Tree t) {\\n\\tfor(pair<int,int> edge : t) printf(\\\"%d-%d\\\\n\\\", edge.first, edge.second);\\n\\tputs(\\\"\\\");\\n}\\n\\nvoid tryTree(Tree t, int k) {\\n\\tRI(i, k) RI(j, k) e[i][j] = e_memo[i][j];\\n\\tfor(pair<int,int> p : t) {\\n\\t\\tint & tmp = e[p.first][p.second];\\n\\t\\tif(tmp == 0) return;\\n\\t\\t--tmp;\\n\\t}\\n\\tif(!checkEverything(k)) return;\\n\\tvector<pair<int,int>> ans;\\n\\tfor(pair<int,int> p : t) ans.push_back({boss[p.first], boss[p.second]}); //\\n\\tRI(i, k) RI(j, k) while(e[i][j]) {\\n\\t\\t--e[i][j];\\n\\t\\tif((int) group[i].size() > 1) {\\n\\t\\t\\tint memo = group[i].back();\\n\\t\\t\\tgroup[i].pop_back();\\n\\t\\t\\tif(checkEverything(k)) {\\n\\t\\t\\t\\tans.push_back({boss[j], memo});\\n\\t\\t\\t\\t// printf(\\\"%d %d\\\\n\\\", boss[j], group[i].back());\\n\\t\\t\\t\\tcontinue;\\n\\t\\t\\t}\\n\\t\\t\\tgroup[i].push_back(memo);\\n\\t\\t}\\n\\t\\tassert((int) group[j].size() > 1);\\n\\t\\tans.push_back({boss[i], group[j].back()});\\n\\t\\t// printf(\\\"%d %d\\\\n\\\", boss[i], group[j].back());\\n\\t\\tgroup[j].pop_back();\\n\\t\\tassert(checkEverything(k));\\n\\t}\\n\\tRI(i, k) assert((int) group[i].size() == 1);\\n\\trandom_shuffle(ans.begin(), ans.end());\\n\\tfor(pair<int,int> p : ans) {\\n\\t\\tif(rand()%2) swap(p.first, p.second);\\n\\t\\tprintf(\\\"%d %d\\\\n\\\", p.first, p.second);\\n\\t}\\n\\texit(0);\\n}\\n\\nvector<Tree> findTrees(int k) {\\n\\tvector<Tree> ans;\\n\\tvector<pair<int,int>> edges;\\n\\tRI(i, k) FOR(j, i+1, k) edges.push_back({i, j});\\n\\tREP(mask, (1 << edges.size())) if(__builtin_popcount(mask) == k - 1) {\\n\\t\\tTree t;\\n\\t\\tREP(i, (int) edges.size()) if(mask & (1 << i)) t.push_back(edges[i]);\\n\\t\\tif(validTree(t, k)) ans.push_back(t);\\n\\t}\\n\\treturn ans;\\n}\\n\\nint findLog(int n) {\\n\\tint k = 0;\\n\\twhile(n) {\\n\\t\\t++k;\\n\\t\\tn /= 10;\\n\\t}\\n\\treturn k;\\n}\\n\\nint main() {\\n\\tsrand(42);\\n\\tint n;\\n\\tscanf(\\\"%d\\\", &n);\\n\\tRI(i, n) group[findLog(i)].push_back(i);\\n\\tREP(_, n - 1) {\\n\\t\\tscanf(\\\"%s\\\", sl);\\n\\t\\tint a = strlen(sl);\\n\\t\\tscanf(\\\"%s\\\", sl);\\n\\t\\tint b = strlen(sl);\\n\\t\\tif(a > b) swap(a, b);\\n\\t\\t++e[a][b];\\n\\t}\\n\\tint k = findLog(n);\\n\\tRI(i, k) boss[i] = group[i][0];\\n\\tRI(i, k) RI(j, k) e_memo[i][j] = e[i][j];\\n\\tvector<Tree> trees = findTrees(k);\\n\\tfor(Tree t : trees) tryTree(t, k);\\n\\tputs(\\\"-1\\\");\\n\\treturn 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "flows",
      "graphs"
    ],
    "rating": 3200
  },
  {
    "contest_id": "612",
    "index": "A",
    "title": "The Text Splitting",
    "statement": "You are given the string $s$ of length $n$ and the numbers $p, q$. Split the string $s$ to pieces of length $p$ and $q$.\n\nFor example, the string \"Hello\" for $p = 2$, $q = 3$ can be split to the two strings \"Hel\" and \"lo\" or to the two strings \"He\" and \"llo\".\n\nNote it is allowed to split the string $s$ to the strings only of length $p$ or to the strings only of length $q$ (see the second sample test).",
    "tutorial": "Let's fix the number $a$ of strings of length $p$ and the number $b$ of strings of length $q$. If $a \\cdot p + b \\cdot q = n$, we can build the answer by splitting the string $s$ to $a$ parts of the length $p$ and $b$ parts of the length $q$, in order from left to right. If we can't find any good pair $a, b$ then the answer doesn't exist. Of course this problem can be solved in linear time, but the constraints are small, so you don't need linear solution. Complexity: $O(n^{2})$.",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "612",
    "index": "B",
    "title": "HDD is Outdated Technology",
    "statement": "HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.\n\nOne of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.\n\nFind the time need to read file split to $n$ fragments. The $i$-th sector contains the $f_{i}$-th fragment of the file ($1 ≤ f_{i} ≤ n$). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the $n$-th fragment is read. The fragments are read in the order from the first to the $n$-th.\n\nIt takes $|a - b|$ time units to move the magnetic head from the sector $a$ to the sector $b$. Reading a fragment takes no time.",
    "tutorial": "You are given the permutation $f$. Let's build another permutation $p$ in the following way: $p_{fi} = i$. So the permutation $p$ defines the number of sector by the number of fragment. The permutation $p$ is called inverse permutation to $f$ and denoted $f^{ - 1}$. Now the answer to problem is $\\textstyle\\sum_{i=1}^{n-1}|p_{i}-p_{i+1}|$. Complexity: $O(n)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "612",
    "index": "C",
    "title": "Replace To Make Regular Bracket Sequence",
    "statement": "You are given string $s$ consists of opening and closing brackets of four kinds <>, {{}}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {{}, but you can't replace it by ) or >.\n\nThe following definition of a regular bracket sequence is well-known, so you can be familiar with it.\n\nLet's define a regular bracket sequence (RBS). Empty string is RBS. Let $s_{1}$ and $s_{2}$ be a RBS then the strings {<$s_{1}$>$s_{2}$}, {{$s_{1}$}$s_{2}$}, {[$s_{1}$]$s_{2}$}, {($s_{1}$)$s_{2}$} are also RBS.\n\nFor example the string \"{[[(){}]<>]}\" is RBS, but the strings \"[)()\" and \"][()()\" are not.\n\nDetermine the least number of replaces to make the string $s$ RBS.",
    "tutorial": "If we forget about bracket kinds the string $s$ should be RBS, otherwise the answer doesn't exist. If the answer exists each opening bracket matches to exactly one closing bracket and vice verse. Easy to see that if two matching brackets have the same kind we don't need to replace them. In other case we can change the kind of the closing bracket to the kind of the opening. So we can build some answer. Obviously the answer is minimal, because the problems for some pair of matching pairs are independent and can be solved separately. The only technical problem is to find the matching pairs. To do that we should store the stack of opening brackets. Let's iterate from left to right in $s$ and if the bracket is opening, we would simply add it to the stack. Now if the bracket is closing there are three cases: 1) the stack is empty; 2) at the top of the stack is the opening bracket with the same kind as the current closing; 3) the kind of the opening bracket differs from the kind of the closing bracket. In the first case answer doesn't exist, in the second case we should simply remove the opening bracket from the stack and in the third case we should remove the opening bracket from the stack and increase the answer by one. Complexity: $O(n)$.",
    "tags": [
      "data structures",
      "expression parsing",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "612",
    "index": "D",
    "title": "The Union of k-Segments",
    "statement": "You are given $n$ segments on the coordinate axis Ox and the number $k$. The point is satisfied if it belongs to at least $k$ segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.",
    "tutorial": "Let's create two events for each segment $l_{i}$ is the time of the segment opening and $r_{i}$ is the time of the segment closing. Let's sort all events by time, if the times are equal let's sort them with priority to opening events. In C++ it can be done with sorting by standard comparator of vector<pair<int, int>> events, where each element of events is the pair with event time and event type ($- 1$ for opening and $+ 1$ for closing). Let's iterate over events and maintain the balance. To do that we should simply decrease the balance by the value of the event type. Now if the balance value equals to $k$ and before updating it was $k - 1$ then we are in the left end of some segment from the answer. If the balance equals to $k - 1$ and before updating it was $k$ then we are in the right end of the segment from the answer. Let's simply add segment $[left, right]$ to the answer. So now we have disjoint set of segments contains all satisfied points in order from left to right. Obviously it's the answer to the problem. Complexity: $O(nlogn)$.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "612",
    "index": "E",
    "title": "Square Root of Permutation",
    "statement": "A permutation of length $n$ is an array containing each integer from $1$ to $n$ exactly once. For example, $q = [4, 5, 1, 2, 3]$ is a permutation. For the permutation $q$ the square of permutation is the permutation $p$ that $p[i] = q[q[i]]$ for each $i = 1... n$. For example, the square of $q = [4, 5, 1, 2, 3]$ is $p = q^{2} = [2, 3, 4, 5, 1]$.\n\nThis problem is about the inverse operation: given the permutation $p$ you task is to find such permutation $q$ that $q^{2} = p$. If there are several such $q$ find any of them.",
    "tutorial": "Consider some permutation $q$. Let's build by it the oriented graph with edges $(i, q_{i})$. Easy to see (and easy to prove) that this graph is the set of disjoint cycles. Now let's see what would be with that graph when the permutation will be multiplied by itself: all the cycles of odd length would remain so (only the order of vertices will change, they will be alternated), but the cycles of even length will be split to the two cycles of the same length. So to get the square root from the permutation we should simply alternate (in reverse order) all cycles of the odd length, and group all the cycles of the same even length to pairs and merge cycles in each pair. If it's impossible to group all even cycles to pairs then the answer doesn't exist. Complexity: $O(n)$.",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "612",
    "index": "F",
    "title": "Simba on the Circle",
    "statement": "You are given a circular array with $n$ elements. The elements are numbered from some element with values from $1$ to $n$ in clockwise order. The $i$-th cell contains the value $a_{i}$. The robot Simba is in cell $s$.\n\nEach moment of time the robot is in some of the $n$ cells (at the begin he is in $s$). In one turn the robot can write out the number written in current cell or move to the adjacent cell in clockwise or counterclockwise direction. To write out the number from the cell Simba doesn't spend any time, but to move to adjacent cell Simba spends one unit of time.\n\nSimba wants to write the number from each cell one time, so the numbers will be written in a non decreasing order. Find the least number of time units to write out all numbers.",
    "tutorial": "The author solution for this problem uses dynamic programming. I think that this problem can't be solved by greedy ideas. Let's calculate two dp's: $z1_{i}$ is the answer to the problem if all numbers less than $a_{i}$ are already printed, but the others are not; and $z2_{i}$ is the answer to the problem if all numbers less than or equal to $a_{i}$ are already printed, but the others are not. Let's denote $d_{ij}$ - the least distance between $i$ and $j$ on the circular array and $od_{ij}$ is the distance from $i$ to $j$ in clockwise order. Easy to see that $z2_{i} = min_{j}(z_{j} + d_{ij})$ for all $j$ such that the value $a_{j}$ is the least value greater than $a_{i}$. Now let's calculate the value $z1_{i}$. Consider all elements equals to $a_{i}$ (in one of them we are). If there is only one such element then $z1_{i} = z2_{i}$. Otherwise we have two alternatives: to move in clockwise or counterclockwise direction. Let we are moving in clockwise direction, the last element from which we will write out the number would be the nearest to the $i$ element in counterclockwise direction, let's denote it $u$. Otherwise at last we will write out the number from the nearest to the $i$ element in clockwise direction, let's denote it $v$. Now $z1_{i} = min(z2_{u} + od_{iu}, z2_{v} + od_{vi})$. Easy to see that the answer to the problem is $min_{i}(z1_{i} + d_{si})$, over all $i$ such that $a_{i}$ is the smallest value in array and $s$ is the start position. Additionally you should restore the answer. To do that, on my mind, the simplest way is to write the recursive realization of dp, test it carefully and then copy it to restore answer (see my code below). Of course, it's possible to restore the answer without copy-paste. For example, you can add to your dp parameter $b$ which means it's need to restore answer or not. Complexity: $O(n^{2})$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 2020;\\n\\nint n, s;\\nint a[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> s)) return false;\\n\\ts--;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &a[i]) == 1);\\n\\treturn true;\\n}\\n\\ninline int dist(int a, int b) {\\n\\tint d = abs(a - b);\\n\\td = min(d, n - d);\\n\\treturn d;\\n}\\n\\ninline int odist(int a, int b) {\\n\\tint d = b - a;\\n\\t(d < 0) && (d += n);\\n\\treturn d;\\n}\\n\\nint nt[N];\\nint z1[N], z2[N];\\n\\nint solve1(int);\\n\\nint solve2(int v) {\\n\\tint& ans = z2[v];\\n\\tif (ans != -1) return ans;\\n\\tif (nt[v] == INT_MAX) return ans = 0;\\n\\n\\tans = INF;\\n\\n\\tforn(i, n)\\n\\t\\tif (a[i] == nt[v]) {\\n\\t\\t\\tans = min(ans, solve1(i) + dist(v, i));\\n\\t\\t}\\n\\n\\treturn ans;\\n}\\n\\nint solve1(int v) {\\n\\tint& ans = z1[v];\\n\\tif (ans != -1) return ans;\\n\\n\\tans = INF;\\n\\n\\tfor (int d = -1; d <= +1; d += 2) {\\n\\t\\tint u = -1;\\n\\t\\tfore(i, 1, n) {\\n\\t\\t\\tint vv = (v + i * d + n) % n;\\n\\t\\t\\tif (a[vv] == a[v]) {\\n\\t\\t\\t\\tu = vv;\\n\\t\\t\\t\\tbreak;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif (u == -1)\\n\\t\\t\\tans = min(ans, solve2(v));\\n\\t\\telse {\\n\\t\\t\\tint dt = d == 1 ? odist(u, v) : odist(v, u);\\n\\t\\t\\tans = min(ans, solve2(u) + dt);\\n\\t\\t}\\n\\t}\\n\\n\\treturn ans;\\n}\\n\\nvoid restore1(int);\\n\\nvoid restore2(int v) {\\n\\tint& ans = z2[v];\\n\\tassert(ans != -1);\\n\\tif (nt[v] == INT_MAX) return;\\n\\n\\tforn(i, n)\\n\\t\\tif (a[i] == nt[v] && ans == solve1(i) + dist(v, i)) {\\n\\t\\t\\tint d = i - v;\\n\\t\\t\\t(d < 0) && (d += n);\\n\\t\\t\\tif (d <= n - d) printf(\\\"+%d\\\\n\\\", d);\\n\\t\\t\\telse printf(\\\"-%d\\\\n\\\", n - d);\\n\\t\\t\\treturn restore1(i);;\\n\\t\\t}\\n\\n\\tthrow;\\n}\\n\\nvoid restore1(int v) {\\n\\tint& ans = z1[v];\\n\\tassert(ans != -1);\\n\\n\\tfor (int d = -1; d <= +1; d += 2) {\\n\\t\\tint u = -1;\\n\\t\\tfore(i, 1, n) {\\n\\t\\t\\tint vv = (v + i * d + n) % n;\\n\\t\\t\\tif (a[vv] == a[v]) {\\n\\t\\t\\t\\tu = vv;\\n\\t\\t\\t\\tbreak;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif (u == -1) {\\n\\t\\t\\tif (ans == solve2(v)) {\\n\\t\\t\\t\\treturn restore2(v);\\n\\t\\t\\t}\\n\\t\\t} else {\\n\\t\\t\\tint dt = d == 1 ? odist(u, v) : odist(v, u);\\n\\t\\t\\tif (ans == solve2(u) + dt) {\\n\\t\\t\\t\\tint cdt = 0;\\n\\t\\t\\t\\tfore(i, 1, n) {\\n\\t\\t\\t\\t\\tint vv = (v + i * (-d) + n) % n;\\n\\t\\t\\t\\t\\tcdt++;\\n\\t\\t\\t\\t\\tif (a[vv] == a[v]) {\\n\\t\\t\\t\\t\\t\\tprintf(\\\"%c%d\\\\n\\\", d == +1 ? '-' : '+', cdt);\\n\\t\\t\\t\\t\\t\\tcdt = 0;\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\treturn restore2(u);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tthrow;\\n}\\ninline void solve() {\\n\\tmemset(z1, -1, sizeof(z1));\\n\\tmemset(z2, -1, sizeof(z2));\\n\\n\\tforn(i, n) {\\n\\t\\tnt[i] = INT_MAX;\\n\\t\\tforn(j, n)\\n\\t\\t\\tif (a[j] > a[i])\\n\\t\\t\\t\\tnt[i] = min(nt[i], a[j]);\\n\\t}\\n\\n\\t//cerr << solve1(0) << endl;\\n\\t//exit(0);\\n\\n\\tint minv = *min_element(a, a + n);\\n\\tint ans = INF;\\n\\tforn(i, n)\\n\\t\\tif (a[i] == minv) {\\n\\t\\t\\tans = min(ans, solve1(i) + dist(s, i));\\n\\t\\t}\\n\\n\\tcout << ans << endl;\\n\\tforn(i, n)\\n\\t\\tif (a[i] == minv && ans == solve1(i) + dist(s, i)) {\\n\\t\\t\\tint d = i - s;\\n\\t\\t\\t(d < 0) && (d += n);\\n\\t\\t\\tif (d <= n - d) printf(\\\"+%d\\\\n\\\", d);\\n\\t\\t\\telse printf(\\\"-%d\\\\n\\\", n - d);\\n\\t\\t\\trestore1(i);\\n\\t\\t\\tbreak;\\n\\t\\t}\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "613",
    "index": "A",
    "title": "Peter and Snow Blower",
    "statement": "Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.\n\nFormally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.\n\nPeter decided to tie his car to point $P$ and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.",
    "tutorial": "Consider distances between the point $P$ and all points of the polygon. Let $R$ be the largest among all distances, and $r$ be the smallest among all distances. The swept area is then a ring between circles of radii $R$ and $r$, and the answer is equal to $ \\pi  (R^{2} - r^{2})$. Clearly, $R$ is the largest distance between $P$ and vertices of the polygon. However, $r$ can be the distance between $P$ and some point lying on the side of the polygon, therefore, $r$ is the smallest distance between $P$ and all sides of the polygon. To find the shortest distance between a point $p$ and a segment $s$, consider a straight line $l$ containing the segment $s$. Clearly, the shortest distance between $p$ and $l$ is the length of the perpendicular segment. One should consider two cases: when the end of the perpendicular segment lies on the segment $s$ (then the answer is the length of the perpendicular segment), or when it lies out of $s$ (then the answer is the shortest distance to the ends of $s$).",
    "tags": [
      "binary search",
      "geometry",
      "ternary search"
    ],
    "rating": 1900
  },
  {
    "contest_id": "613",
    "index": "B",
    "title": "Skills",
    "statement": "Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly $n$ skills. Each skill is represented by a non-negative integer $a_{i}$ — the current skill level. All skills have the same maximum level $A$.\n\nAlong with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values:\n\n- The number of skills that a character has perfected (i.e., such that $a_{i} = A$), multiplied by coefficient $c_{f}$.\n- The minimum skill level among all skills ($min a_{i}$), multiplied by coefficient $c_{m}$.\n\nNow Lesha has $m$ hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by $1$ (if it's not equal to $A$ yet). Help him spend his money in order to achieve the maximum possible value of the Force.",
    "tutorial": "Let's save the original positions of skills and then sort the skills in non-increasing order (almost decreasing) by current level. We can always restore original order after. Imagine that we have decided that we want to use the minimum level $X$ and now we're choosing which skills we should bring to the maximum. At first, let's rise all skills below $X$ to level $X$, this will set some tail of array to $X$. But the original array was sorted, and this new change will not break the sort! So our array is still sorted. Obviously, the skills we want to take to the maximum are the ones with highest current level. They are in the prefix of array. It is easy to show that any other selection is no better than this greedy one. Now we have shown that the optimal strategy is to max out the skills in some prefix. Now let's solve the problem. Let's iterate over prefix to max out, now on each iteration we need to know the highest minimum we can achieve, let's store the index of the first element outside the prefix such that it is possible to reach the minimum level $ \\ge  arr_{index}$. It is easy to recalc this index, it slightly moves forward each turn and, after precalcing the sum of all array's tails, you can update it easily (just move it forward until the invariant above holds). And knowing this index is enough to calc the current highest possible minimum level ($min(A, arr_{index} +  \\lfloor  sparemoney / (n - index) \\rfloor $). How to restore the answer? Actually, all you need to know is the count of maximums to take and minimum level to reach.",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "613",
    "index": "C",
    "title": "Necklace",
    "statement": "Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward).\n\nIvan has beads of $n$ colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.",
    "tutorial": "Surprisingly, the nice cuts can't be put randomly. Let's take a look on the first picture above (red lines represent nice cut points). But since the necklace is symmetrical relative to nice cuts, the cut points are also symmetrical relative to nice cuts, so there is one more cut (see picture two). Repeating this process, we will split the whole necklace into parts of the same size (picture three). If the number of parts is even, then each part can be taken arbitrarily, but the neighbouring parts must be reverses of each other (e.g. \"abc\" and \"cba\"). This is an implication of the cuts being nice. If the number of parts is odd, then each part is equal to each other and is a palindrome, this is an implication of the cuts being nice too. Anyway, the number of characters in each part is equal, so amount of parts can't be greater than $\\operatorname*{gcd}(a_{i})$. Actually, it may be zero, $\\operatorname{gcd}$ or its divisor. If the number of odd-sized colors is zero, then the sum is even and gcd is even, this way we can construct a building block containing exactly $\\frac{a_{i}}{\\mathrm{gcd}}$ beads of $i$-th color, (gcd being gcd of all counts), then build beads of $gcd$ parts, where each part equal to building block, with neighbouring parts being reverses. Since $gcd$ is even, everything is ok. If the number of odd-sized colors is one, then the sum is odd and gcd is odd. Building block have to be built as a palindrome containing $\\frac{a_{i}}{\\mathrm{gcd}}$ beads of $i$-th color, exactly $n - 1$ of colors will be even and one odd, put the odd one in center, others on sides (aabcbaa). Everything is ok. If num of odd counts is $geq2$. Gcd is odd, all its divisors too, so our building block has to be palindrome. Let $k$ denote the number of parts. A building block will contain $\\frac{u_{i_{i}}}{k}$ beads of color $i$, at least two of these numbers are odd, it is impossible to build such a palindrome. The answer is zero. Complexity: $O(sum)$, just to output answer.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "613",
    "index": "D",
    "title": "Kingdom and its Cities",
    "statement": "Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.\n\nThe kingdom currently consists of $n$ cities. Cities are connected by $n - 1$ bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.\n\nWhat is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.\n\nBarbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.\n\nHelp the King to calculate this characteristic for each of his plan.",
    "tutorial": "Obviously, the answer is -1 iff two important cities are adjacent. If there was a single query, can we answer it in $O(n)$ time? Let's choose a root arbitrarily. We can note there is an optimal answer that erases two types of vertices: vertices that lie on a vertical path between two important vertices, or LCA of some pair of important vertices. Let's do a subtree DP that counts the answer for the subtree of $v$, as well as if there is any important vertex still connected to $v$ in the answer. How do we count it? If $v$ is important, then we should disconnect it from any still-connected vertices from below by erasing these children which contain them. If $v$ is not important, then we erase it iff there are more than one still-connected important vertices below. All calculations are straightforward here. How do we process many queries now? There are many possible approaches here (for reference, look at the accepted solutions). The author's solution was as follows: if we have a query with $k$ important vertices, then we can actually build an auxiliary tree with $O(k)$ vertices and apply the linear DP solution to it with minor modifications. How to construct the auxiliary tree? We should remember the observation about LCAs. Before we start, let us DFS the initial tree and store the preorder of the tree (also known as \"sort by tin\"-order). A classical exercise: to generate all possible LCAs of all pairs among a subset of vertices, it suffices to consider LCAs of consecutive vertices in the preorder. After we find all the LCAs, it is fairly easy to construct the tree in $O(k)$ time. Finally, apply the DP to the auxiliary tree. Note that important cities adjacent in the auxiliary tree are actually not adjacent (since we've handled that case before), so it is possible to disconnect them. If we use the standard \"binary shifts\" approach to LCA, we answer the query in $O(k\\log n)$ time, for a total complexity of $O((n+\\sum k_{i})\\log n)$.",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "dp",
      "graphs",
      "sortings",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "613",
    "index": "E",
    "title": "Puzzle Lover",
    "statement": "Oleg Petrov loves crossword puzzles and every Thursday he buys his favorite magazine with crosswords and other word puzzles. In the last magazine Oleg found a curious puzzle, and the magazine promised a valuable prize for it's solution. We give a formal description of the problem below.\n\nThe puzzle field consists of two rows, each row contains $n$ cells. Each cell contains exactly one small English letter. You also are given a word $w$, which consists of $k$ small English letters. A solution of the puzzle is a sequence of field cells $c_{1}$, $...$, $c_{k}$, such that:\n\n- For all $i$ from $1$ to $k$ the letter written in the cell $c_{i}$ matches the letter $w_{i}$;\n- All the cells in the sequence are pairwise distinct;\n- For all $i$ from $1$ to $k - 1$ cells $c_{i}$ and $c_{i + 1}$ have a common side.\n\nOleg Petrov quickly found a solution for the puzzle. Now he wonders, how many distinct solutions are there for this puzzle. Oleg Petrov doesn't like too large numbers, so calculate the answer modulo $10^{9} + 7$.\n\nTwo solutions $c_{i}$ and $c'_{i}$ are considered distinct if the sequences of cells do not match in at least one position, that is there is such $j$ in range from $1$ to $k$, such that $c_{j} ≠ c'_{j}$.",
    "tutorial": "The key observation: any way to cross out the word $w$ looks roughly as follows: That is, there can be following parts: go back $a$ symbols in one row, then go forward $a$ symbols in the other row (possibly $a = 0$) go forward with arbitrarily up and down shifts in a snake-like manner go forward $b$ symbols in one row, then go back $b$ in the other row (possibly $b = 0$) Note that the \"forward\" direction can be either to the left or to the right. It is convenient that for almost any such way we can determine the \"direction\" as well as the places where different \"parts\" of the path (according to the above) start. To avoid ambiguity, we will forbid $a = 1$ or $b = 1$ (since such parts can be included into the \"snake\"). Fix the direction. We will count the DP $d_{x, y, k}$ for the number of ways to cross out first $k$ letters of $w$ and finished at the cell $(x, y)$ while being inside the snake part of the way. The transitions are fairly clear (since the snake part only moves forward). However, we have to manually handle the first and the last part. For each cell and each value of $k$ we can determine if the \"go-back-then-go-forward\" maneuver with parameter $k$ can be performed with the chosen cell as finish; this can be reduced to comparing of some substrings of field of rows and the word $w$ (and its reversed copy). In a similar way, for any state we can check if we can append the final \"go-forward-then-go-back\" part of the path to finally obtain a full-fledged path. This DP has $O(n^{2})$ states and transitions. However, there are still some questions left. How do we perform the substring comparisons? There is a whole arsenal of possible options: (carefully implemented) hashes, suffix structures, etc. Probably the simplest way is to use Z-function for a solution that does $O(n^{2})$ precalc and answers each substring query in $O(1)$ time (can you see how to do it?). Also, there are paths that we can consider more than once. More precisely, a path that consists only of the \"go-forward-the-go-back\" part will be counted twice (for both directions), thus we have to subtract such paths explicitly. Every other path is counted only once, thus we are done. (Note: this does not exactly work when $w$ is short, say, 4 symbols or less. The simplest way is to implement straightforward brute-force for such cases.)",
    "tags": [
      "dp",
      "hashing",
      "strings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "614",
    "index": "A",
    "title": "Link/Cut Tree",
    "statement": "Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the $expose$ procedure.\n\nUnfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)\n\nGiven integers $l$, $r$ and $k$, you need to print all powers of number $k$ within range from $l$ to $r$ \\textbf{inclusive}. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!",
    "tutorial": "You had to print all numbers of form $k^{x}$ for non-negative integers $x$ that lie with the range $[l;r]$. A simple cycle works: start with $1 = k^{0}$, go over all powers that do not exceed $r$ and print those which are at least $l$. One should be careful with 64-bit integer overflows: consider the test $l = 1$, $r = 10^{18}$, $k = 10^{9}$, the powers will be 1, $10^{9}$, $10^{18}$, and the next power is $10^{27}$, which does not fit in a standard integer type.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "614",
    "index": "B",
    "title": "Gena's Code",
    "statement": "It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!\n\nThere are exactly $n$ distinct countries in the world and the $i$-th country added $a_{i}$ tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains \\textbf{at most one} digit '1'. However, due to complaints from players, some number of tanks of \\textbf{one} country was removed from the game, hence the number of tanks of this country may not remain beautiful.\n\nYour task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.",
    "tutorial": "You were asked to print the product of $n$ large numbers, but it was guaranteed that at least $n - 1$ are beautiful. It's not hard to see that beautiful numbers are 0 and all powers of 10 (that is, 1 followed by arbitrary number of zeros). If there is at least one zero among the given numbers, the product is 0. Otherwise, consider the only non-beautiful number $x$ (if all numbers are beautiful, consider $x = 1$). Multiplying $x$ by $10^{t}$ appends $t$ zeros to its decimal representation, so in this case we have to find the only non-beautiful number and print it with several additional zeros. We tried to cut off all naive solutions that use built-in long numbers multiplication in Python or Java. However, with some additional tricks (e.g., ``divide-and-conquer'') this could pass all tests.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "615",
    "index": "A",
    "title": "Bulbs",
    "statement": "Vasya wants to turn on Christmas lights consisting of $m$ bulbs. Initially, all bulbs are turned off. There are $n$ buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?\n\nIf Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.",
    "tutorial": "Let's make a counter of number of buttons that switch every lamp off. If there is a lamp with zero counter, output NO, otherwise YES.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long ll;\n \nint main() {\n    int n, m;\n    cin >> m >> n;\n    vector<int> cnt(n);\n    while (m--) {\n        int k;\n        cin >> k;\n        vector<int> ys(k);\n        for (auto &y : ys) {\n            cin >> y;\n            cnt[y - 1]++;\n        }\n    }\n    for (auto &x : cnt) {\n        if (x <= 0) {\n            cout << \"NO\" << endl;\n            return 0;\n        }\n    }\n    cout << \"YES\" << endl;\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "615",
    "index": "B",
    "title": "Longtail Hedgehog",
    "statement": "This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of $n$ points connected by $m$ segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions:\n\n- Only segments already presented on the picture can be painted;\n- The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment;\n- The numbers of points from the beginning of the tail to the end should strictly increase.\n\nMasha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the \\textbf{endpoint} of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.\n\nNote that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.",
    "tutorial": "Way of solving - dynamic programming. We are given a graph of n vertices and m edges. We will calculate dp[i] - a maximum length of tail that is ending in i-th vertex. We can simply update dp by checking all the edges from i-th vertex(which are leading to vertices with bigger number), and trying to update them. When we have this dp, we can check the answer easily.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\ntypedef long long ll;\n \nconst int maxN = 1 << 17;\n \nint dp[maxN];\nvector<int> g[maxN];\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int n, m;\n    cin >> n >> m;\n    while(m--) {\n        int v, u;\n        cin >> v >> u;\n        g[v].push_back(u);\n        g[u].push_back(v);\n    }\n    ll ans = -1ll;\n    for (int v = 1; v <= n; v++) {\n        dp[v] = 1;\n        for (auto u : g[v]) {\n            if (u < v) {\n                dp[v] = max(dp[v], dp[u] + 1);\n            }\n        }\n        ans = max(ans, dp[v] * (ll)g[v].size());\n    }\n    cout << ans << endl;\n    return 0;\n}",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 1600
  },
  {
    "contest_id": "615",
    "index": "C",
    "title": "Running Track",
    "statement": "A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.\n\nFirst, he wants to construct the running track with coating $t$. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.\n\nUnfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings $s$. Also, he has scissors and glue. Ayrat is going to buy some coatings $s$, then cut out from each of them \\textbf{exactly one continuous piece} (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating $s$ he needs to buy in order to get the coating $t$ for his running track. Of course, he also want's to know some way to achieve the answer.",
    "tutorial": "The idea is that if can make a substring t[i, j] using k coatings, then we can also make a substring t[i + 1, j] using k coatings. So we should use the longest substring each time. Let n = |s|, m = |t|. On each stage we will search for the longest substring in s and s_reversed to update the answer. We can do it in several ways: Calculate lcp[i][j] - longest common prefix t[i, m] and s[j, n], lcprev[i][j] - longest common prefix t[i, m] and s[j, 1]. Find longest means find max(max(lcp[i][1], lcp[i][2], $...$, lcp[i][n]), max(lcprev[i][1], lcprev[i][2], $...$, lcprev[i][n])). calculation lcp:",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n#define fi first\n#define se second\n \nconst int maxC = 'z' - 'a' + 1;\n \nstruct Node {\n    int next[maxC];\n    int l, r;\n    Node() {\n        memset(this, 0, sizeof(*this));\n    }\n};\n \nstruct Trie {\n    vector<Node> T;\n    Trie() {\n        T.push_back(Node());\n        T.reserve(2100 * 2100);\n    }\n    void addStr(string s, int l, int dr) {\n        int v = 0;\n        int r = l;\n        for (auto c : s) {\n            c -= 'a';\n            if (!T[v].next[c]) {\n                T[v].next[c] = T.size();\n                T.push_back(Node());\n                T.back().l = l;\n                T.back().r = r;\n            }\n            v = T[v].next[c];\n            r += dr;\n        }\n    }\n    void built(string s) {\n        int n = s.size();\n        for (int i = 0; i < n; i++) {\n            string cur;\n            cur = s.substr(i, n - i);\n            addStr(cur, i, 1);\n            cur = s.substr(0, n - i);\n            reverse(all(cur));\n            addStr(cur, n - i - 1, -1);\n        }\n    }\n    vector<pair<int,int> > go(string t) {\n        vector<pair<int,int> > ans;\n        int v = 0;\n        int n = t.size();\n        t.push_back('z' + 1);\n        for (int i = 0; i <= n; i++) {\n            char c = t[i] - 'a';\n            if (i == n || T[v].next[c] == 0) {\n                if (v == 0) {\n                    return vector<pair<int,int> >();\n                }\n                ans.push_back({T[v].l, T[v].r});\n                v = 0;\n            }\n            if (i < n) {\n                v = T[v].next[c];\n            }\n        }\n        return ans;\n    }\n};\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    Trie T;\n    string s, t;\n    cin >> s >> t;\n    T.built(s);\n    vector<pair<int,int> > ans = T.go(t);\n    if (ans.size() == 0) {\n        cout << -1 << endl;\n        return 0;\n    }\n    cout << ans.size() << endl;\n    for (auto x : ans) {\n        cout << x.fi + 1 << \" \" << x.se + 1 << endl;;\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "strings",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "615",
    "index": "D",
    "title": "Multipliers",
    "statement": "Ayrat has number $n$, represented as it's prime factorization $p_{i}$ of size $m$, i.e. $n = p_{1}·p_{2}·...·p_{m}$. Ayrat got secret information that that the product of all divisors of $n$ taken modulo $10^{9} + 7$ is the password to the secret data base. Now he wants to calculate this value.",
    "tutorial": "Let d(x) be a number of divisors of x, and f(x) be the product of divisors. Let $x = p_{1}^{ \\alpha 1}p_{2}^{ \\alpha 2}... p_{n}^{ \\alpha n}$, then $d(x) = ( \\alpha _{1} + 1) \\cdot ( \\alpha _{2} + 1)... ( \\alpha _{n} + 1)$ $f(x)=x^{\\frac{d(x)}{2}}$. There is $\\textstyle{\\frac{d(x)}{2}}\\right\\}$ pairs of divisors of type $\\left({\\frac{x}{x}},c\\right)$, $c<{\\sqrt{x}}$, and if x is a perfect square we have one more divisor : $\\sqrt{x}$. for a prime $m$ and $a  \\neq  0$ the statement $a^{m-1}\\equiv1{\\pmod{m}}\\Rightarrow a^{x}\\equiv a^{x\\Re_{c}(m-1)}{\\mathrm{~(mod~}}m{\\mathrm{)}}$ (little Fermat theorem) We can see that $d(a b)=d(a)d(b),\\;f(a b)=f(a)^{d(b)}f(b)^{d(a)},\\;f(p^{k})=p^{\\frac{k(k+1)}{2}}$, if a and b are co prime. Now we can count the answer:",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\ntypedef long long ll;\n \nconst ll MOD = (ll)1e9 + 7;\n \nll binPow(ll a, ll q, ll MOD) {\n    a %= MOD;\n    if (q == 0) return 1;\n    return ((q % 2 == 1 ? a : 1) * binPow(a * a, q / 2, MOD)) % MOD;\n}\n \nint main() {\n    int n;\n    scanf(\"%d\", &n);\n    map<int,int> cnt;\n    while (n--) {\n        int x;\n        scanf(\"%d\", &x);\n        cnt[x]++;\n    }\n    ll d = 1;\n    ll ans = 1;\n    for (auto x : cnt) {\n        ll cnt = x.se;\n        ll p = x.fi;\n        ll fp = binPow(p, (cnt + 1) * cnt / 2, MOD);\n        ans = binPow(ans, (cnt + 1), MOD) * binPow(fp, d, MOD) % MOD;\n        d = d * (x.se + 1) % (MOD - 1);\n    }\n    cout << ans << endl;\n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "615",
    "index": "E",
    "title": "Hexagons",
    "statement": "Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined:\n\nAyrat is searching through the field. He started at point $(0, 0)$ and is moving along the spiral (see second picture). Sometimes he forgets where he is now. Help Ayrat determine his location after $n$ moves.",
    "tutorial": "Let's see how the coordinates are changing while we move from current cell to one of the 6 adjacent cells - let's call this 6 typed of moves. If we know the number of moves of each type on our way, then we know the coordinates of the end of the way. We will divide the way into rings. Let's count the number of moves of each type for the first ring. Next ring will have one more move of each type. Length of each ring = length of previous + 6. It is an arithmetic progression. Using well-known formulas and binary search we calculate the number of the last ring and overall length of previous rings. Now we have to brute-force 6 types of the last move and calculate the answer.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long ll;\n#define fi first\n#define se second\n \npair<ll, ll> solve(ll n) {\n    ll j = 0, cur = 0;\n    ll x = 0, y = 0;\n    vector<ll> dx = {1,  -1, -2, -1,  1,  2};\n    vector<ll> dy = {2,  2,   0, -2, -2,  0};\n    vector<ll> cnt = {1, 0, 1, 1, 1, 1};\n    ll l = -1, r = (ll)1e9;\n    while (r - l > 1) {\n        ll m = (r + l) / 2;\n        if (m * (m * 3 + 2) <= n) {\n            l = m;\n        } else {\n            r = m;\n        }\n    }\n    cur = l * (l * 6 + 4) / 2;\n    x += l * dx[4];\n    y += l * dy[4];\n    for (int i = 0; i < 6; i++) {\n        cnt[i] += l;\n    }\n    while (cur < n) {\n        ll d = min(cnt[j], n - cur);\n        cur += d;\n        x += dx[j] * d;\n        y += dy[j] * d;\n        cnt[j]++;\n        j = (j + 1) % 6;\n    }\n    return {x, y};\n}\n \nint main() {\n    ll n;\n    cin >> n;\n    auto p = solve(n);\n    cout << p.fi << \" \" << p.se  << endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "616",
    "index": "A",
    "title": "Comparing Two Long Integers",
    "statement": "You are given two very long integers $a, b$ (leading zeroes are allowed). You should check what number $a$ or $b$ is greater or determine that they are equal.\n\nThe input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.\n\nAs input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().",
    "tutorial": "Note that solutions in Java with BigInteger class or input() function in Python2 will fail in this problem. The reason is the next: standard objects stores numbers not in decimal system and need a lot of time to convert numbers from decimal system. Actually they are working in $O(n^{2})$, where $n$ is the legth of the number. To solve this problem you should simply read the numbers to strings and add leading zeroes to the shorter one until the numbers will be of the same length. After that you should simply compare them alphabetically. Complexity: $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 1200300;\\n\\nchar a[N];\\nchar b[N];\\n\\ninline bool read() {\\n\\tif (!gets(a)) return false;\\n\\tassert(gets(b));\\n\\treturn true;\\n}\\n\\ninline void solve() {\\n\\tint n = int(strlen(a));\\n\\tint m = int(strlen(b));\\n\\treverse(a, a + n);\\n\\treverse(b, b + m);\\n\\twhile (n < m) a[n++] = '0';\\n\\twhile (m < n) b[m++] = '0';\\n\\tint p = n - 1;\\n\\twhile (p >= 0 && a[p] == b[p]) p--;\\n\\tif (p < 0) puts(\\\"=\\\");\\n\\telse if (a[p] < b[p]) puts(\\\"<\\\");\\n\\telse puts(\\\">\\\");\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "616",
    "index": "B",
    "title": "Dinner with Emma",
    "statement": "Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.\n\nMunhattan consists of $n$ streets and $m$ avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from $1$ to $n$ and the avenues are numbered with integers from $1$ to $m$. The cost of dinner in the restaurant at the intersection of the $i$-th street and the $j$-th avenue is $c_{ij}$.\n\nJack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.",
    "tutorial": "Firstly you should find the minimum value in each row and after that you should find the maximum value over that minimums. It's corresponding to the strategy of Jack and Emma. Complexity: $O(nm)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 5050;\\n\\nint n, m;\\nint a[N][N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> m)) return false;\\n\\tforn(i, n) forn(j, m) assert(scanf(\\\"%d\\\", &a[i][j]) == 1);\\n\\treturn true;\\n}\\n\\ninline void solve() {\\n\\tint ans = INT_MIN;\\n\\tforn(i, n) {\\n\\t\\tint cur = INT_MAX;\\n\\t\\tforn(j, m) cur = min(cur, a[i][j]);\\n\\t\\tans = max(ans, cur);\\n\\t}\\n\\tcout << ans << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "616",
    "index": "C",
    "title": "The Labyrinth",
    "statement": "You are given a rectangular field of $n × m$ cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.\n\nLet's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.\n\nFor each impassable cell $(x, y)$ imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains $(x, y)$. You should do it for each impassable cell independently.\n\nThe answer should be printed as a matrix with $n$ rows and $m$ columns. The $j$-th symbol of the $i$-th row should be \".\" if the cell is empty at the start. Otherwise the $j$-th symbol of the $i$-th row should contain the only digit —- the answer modulo $10$. The matrix should be printed without any spaces.\n\nTo make your output faster it is recommended to build the output as an array of $n$ strings having length $m$ and print it as a sequence of lines. It will be much faster than writing character-by-character.\n\nAs input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.",
    "tutorial": "Let's enumerate all the connected components, store their sizes and for each empty cell store the number of it's component. It can be done with a single dfs. Now the answer for some impassable cell is equal to one plus the sizes of all different adjacent connected components. Adjacent means the components of cells adjacent to the current impassable cell (in general case each unpassable cell has four adjacent cells). Complexity: $O(nm)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 1010;\\n\\nint n, m;\\nchar a[N][N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> m)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%s\\\", a[i]) == 1);\\n\\treturn true;\\n}\\n\\nint sz[N * N];\\nint tt, num[N][N];\\n\\nint dx[] = { -1, 0, 1, 0 };\\nint dy[] = { 0, -1, 0, 1 };\\n\\nvoid dfs(int x, int y) {\\n\\tsz[tt]++;\\n\\tnum[x][y] = tt;\\n\\n\\tforn(i, 4) {\\n\\t\\tint xx = x + dx[i];\\n\\t\\tint yy = y + dy[i];\\n\\t\\tif (min(xx, yy) < 0 || xx >= n || yy >= m) continue;\\n\\t\\tif (num[xx][yy] != -1 || a[xx][yy] != '.') continue;\\n\\t\\tdfs(xx, yy);\\n\\t}\\n}\\n\\nchar ans[N][N];\\n\\ninline void solve() {\\n\\ttt = 0;\\n\\tforn(i, n) forn(j, m) num[i][j] = -1;\\n\\n\\tforn(i, n)\\n\\t\\tforn(j, m)\\n\\t\\t\\tif (num[i][j] == -1 && a[i][j] == '.') {\\n\\t\\t\\t\\tsz[tt] = 0;\\n\\t\\t\\t\\tdfs(i, j);\\n\\t\\t\\t\\ttt++;\\n\\t\\t\\t}\\n\\n#ifdef SU1\\n\\tforn(i, n) {\\n\\t\\tforn(j, m) cerr << num[i][j] << ' ';\\n\\t\\tcerr << endl;\\n\\t}\\n#endif\\n\\n\\tforn(i, n)\\n\\t\\tforn(j, m) {\\n\\t\\t\\tif (a[i][j] == '.') {\\n\\t\\t\\t\\tans[i][j] = '.';\\n\\t\\t\\t\\tcontinue;\\n\\t\\t\\t}\\n\\t\\t\\tint cur[4] = { -1, -1, -1, -1 };\\n\\t\\t\\tforn(k, 4) {\\n\\t\\t\\t\\tint x = i + dx[k];\\n\\t\\t\\t\\tint y = j + dy[k];\\n\\t\\t\\t\\tif (min(x, y) < 0 || x >= n || y >= m) continue;\\n\\t\\t\\t\\tif (a[x][y] != '.') continue;\\n\\t\\t\\t\\tcur[k] = num[x][y];\\n\\t\\t\\t}\\n\\t\\t\\tsort(cur, cur + 4);\\n\\t\\t\\tint szcur = int(unique(cur, cur + 4) - cur);\\n\\t\\t\\tint ans = 1;\\n\\t\\t\\tforn(k, szcur)\\n\\t\\t\\t\\tif (cur[k] != -1)\\n\\t\\t\\t\\t\\tans += sz[cur[k]];\\n\\t\\t\\tans %= 10;\\n\\t\\t\\t::ans[i][j] = char('0' + ans);\\n\\t\\t}\\n\\n\\tforn(i, n) puts(ans[i]);\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "dfs and similar"
    ],
    "rating": 1600
  },
  {
    "contest_id": "616",
    "index": "D",
    "title": "Longest k-Good Segment",
    "statement": "The array $a$ with $n$ integers is given. Let's call the sequence of one or more consecutive elements in $a$ segment. Also let's call the segment k-good if it contains no more than $k$ different values.\n\nFind any longest k-good segment.\n\nAs the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.",
    "tutorial": "This problem is given because on the Codeforces pages we often see questions like \"What is the method of the two pointers?\". This problem is a typical problem that can be solved using two pointers technique. Let's find for each left end $l$ the maximal right end $r$ that $(l, r)$ is a $k$-good segment. Note if $(l, r)$ is a $k$-good segment then $(l + 1, r)$ is also a $k$-good segment. So the search of the maximal right end for $l + 1$ we can start from the maximal right end for $l$. The only thing that we should do is to maintain in the array $cnt_{x}$ for each number $x$ the number of it's occurrences in the current segment $(l, r)$ and the number of different numbers in $(l, r)$. We should move the right end until the segment became bad and then move the left end. Each of the ends $l$, $r$ will be moved exactly $n$ times. Complexity: $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 1200300;\\n\\nint n, k;\\nint a[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> k)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &a[i]) == 1);\\n\\treturn true;\\n}\\n\\nint cur;\\nint cnt[N];\\n\\ninline void add(int x) {\\n\\tif (++cnt[x] == 1) cur++;\\n}\\n\\ninline void rem(int x) {\\n\\tif (--cnt[x] == 0) cur--;\\n}\\n\\ninline void solve() {\\n\\tcur = 0;\\n\\tmemset(cnt, 0, sizeof(cnt));\\n\\n\\tint al = -1, ar = -1;\\n\\tint p = 0;\\n\\tforn(i, n) {\\n\\t\\twhile (p < n) {\\n\\t\\t\\tadd(a[p]);\\n\\t\\t\\tif (cur > k) {\\n\\t\\t\\t\\trem(a[p]);\\n\\t\\t\\t\\tbreak;\\n\\t\\t\\t}\\n\\t\\t\\tp++;\\n\\t\\t}\\n\\t\\tif (ar - al < p - i) al = i, ar = p;\\n\\t\\trem(a[i]);\\n\\t\\t//cerr << i << ' ' << p << endl;\\n\\t}\\n\\tassert(al != -1);\\n\\tcout << al + 1 << ' ' << ar << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "data structures",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "616",
    "index": "E",
    "title": "Sum of Remainders",
    "statement": "Calculate the value of the sum: $n$ mod $1$ + $n$ mod $2$ + $n$ mod $3$ + ... + $n$ mod $m$. As the result can be very large, you should print the value modulo $10^{9} + 7$ (the remainder when divided by $10^{9} + 7$).\n\nThe modulo operator $a$ mod $b$ stands for the remainder after dividing $a$ by $b$. For example $10$ mod $3$ = $1$.",
    "tutorial": "Unfortunately my solution for this problem had overflow bug. It was fixed on contest. Even so I hope you enjoyed the problem because I think it's very interesting. Let's transform the sum $\\sum_{i=1}^{m}n\\ m o d\\ i=\\sum_{i=1}^{m}\\left(n-\\lfloor{\\frac{n}{i}}\\rfloor i\\right)=m n-\\sum_{i=1}^{m}\\lfloor{\\frac{n}{i}}\\rfloor i$. Note that the last sum can be accumulated to only value $min(n, m)$, because for $i > n$ all the values will be equal to $0$. Note in the last sum either $i\\leq{\\sqrt{n}}$ or $\\textstyle{\\bigl\\iota_{i}}\\bigr\\rfloor\\leq\\sqrt{n}$. Let's carefully accumulate both cases. The first sum can be simply calculated by iterating over all $i\\leq{\\sqrt{n}}$. We will accumulate the second sum independently for all different values $\\left\\lfloor{\\frac{2}{i}}\\right\\rfloor$. Firstly we should determine for which values $i$ we will have the value $v=\\lfloor{\\frac{n}{i}}\\rfloor$. Easy to see that for the values $i$ from the interval $\\left(l f\\right)=\\left.\\left[{\\frac{n}{v+1}}\\right],r g=m i n\\left(m,\\left\\lfloor{\\frac{n}{v}}\\right\\rfloor\\right)\\right\\rfloor$. Also we can note that the sum of the second factors in $\\sum_{i=1}^{m}\\left|{\\frac{n}{i}}\\right|i$ with fixed first factor can be calculaed in constant time - it's simply a sum of arithmetic progression $\\sum_{i=l f+1}^{r_{j}}{\\frac{i}{l}}$. So we have solution with complexity $O({\\sqrt{n}})$. Complexity: $O({\\sqrt{n}})$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nli n, m;\\n\\ninline bool read() {\\n\\treturn !!(cin >> n >> m);\\n}\\n\\nconst li mod = INF + 7;\\n\\ninline void normal(li& a) {\\n\\ta %= mod;\\n\\t(a < 0) && (a += mod);\\n}\\n\\ninline li mul(li a, li b) {\\n\\ta %= mod, b %= mod;\\n\\tnormal(a), normal(b);\\n\\treturn (a * b) % mod;\\n}\\n\\ninline li add(li a, li b) {\\n\\ta %= mod, b %= mod;\\n\\tnormal(a), normal(b);\\n\\treturn (a + b) % mod;\\n}\\n\\ninline li sub(li a, li b) {\\n\\ta %= mod, b %= mod;\\n\\tnormal(a), normal(b);\\n\\ta -= b;\\n\\tnormal(a);\\n\\treturn a;\\n}\\n\\ninline li sum(li n) { return mul(mul(n, n + 1), (mod + 1) / 2); }\\ninline li sum(li lf, li rg) { return sub(sum(rg), sum(lf - 1)); }\\n\\ninline li calcDiv(li n, li m) {\\n\\tm = min(m, n);\\n\\n\\tli ans = 0;\\n\\tli minVal = m;\\n\\tfor (li i = 1; i * i <= n; i++) {\\n\\t\\tli lf = n / (i + 1), rg = n / i;\\n\\t\\trg = min(rg, m);\\n\\t\\tif (lf >= rg) continue;\\n\\t\\tminVal = lf; // interval (lf, rg]\\n\\t\\tans = add(ans, mul(i, sum(lf + 1, rg)));\\n\\t}\\n\\tfore(i, 1, minVal + 1) {\\n\\t\\tans = add(ans, mul(n / i, i));\\n\\t}\\n\\treturn ans;\\n}\\n\\ninline li calcMod(li n, li m) {\\n\\tli ans = mul(n, m);\\n\\tans = sub(ans, calcDiv(n, m));\\n\\treturn ans;\\n}\\n\\ninline void solve() {\\n\\tcout << calcMod(n, m) << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\tcerr << clock() / ld(CLOCKS_PER_SEC) << endl;\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "616",
    "index": "F",
    "title": "Expensive Strings",
    "statement": "You are given $n$ strings $t_{i}$. Each string has cost $c_{i}$.\n\nLet's define the function of string $s:f(s)=\\sum_{i=1}^{n}c_{i}\\cdot p_{s,i}\\cdot|s$, where $p_{s, i}$ is the number of occurrences of $s$ in $t_{i}$, $|s|$ is the length of the string $s$. Find the maximal value of function $f(s)$ over all strings.\n\nNote that the string $s$ is not necessarily some string from $t$.",
    "tutorial": "This problem was prepared by Grigory Reznikow vintage_Vlad_Makeev. His solution uses suffix array. This problem is a typical problem for some suffix data structure. Four competitors who solved this problem during the contest used suffix automaton and one competitor used suffix tree. My own solution used suffix tree so I'll describe solution with tree (I think it's simple except of the building of the tree). Let's build the new string by concatenation of all strings from input separating them by different separators. The number of separators is $O(n)$ so the alphabet is also $O(n)$. So we should use map<int, int> to store the tree and the complexity is increased by $O(logn)$. Let's build the suffix tree for the new string. Let's match all the separators to the strings from the left of the separator. Let's run dfs on the suffix tree that doesn't move over separators and returns the sum of the costs of the strings matched to the separators from the subtree of the current vertex. Easy to see that we should simply update the answer by the product of the depth of the current vertex and the sum in the subtree of the current vertex. Complexity: $O(nlogn)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int NN = 100100, L = 500100;\\n\\nint k;\\nchar buf[L];\\nstring a[NN];\\nint c[NN];\\n\\ninline bool read() {\\n\\tif (!(cin >> k)) return false;\\n\\tforn(i, k) {\\n\\t\\tassert(scanf(\\\"%s\\\", buf) == 1);\\n\\t\\ta[i] = string(buf);\\n\\t}\\n\\tforn(i, k) assert(scanf(\\\"%d\\\", &c[i]) == 1);\\n\\treturn true;\\n}\\n\\nstruct node {\\n\\tint l, r;\\n\\tint parent, link;\\n\\tmap<int, int> next;\\n\\tnode(int l = 0, int r = 0, int parent = 0): l(l), r(r), parent(parent) {\\n\\t\\tlink = -1;\\n\\t\\tnext.clear();\\n\\t}\\n};\\nstruct state {\\n\\tint v, pos;\\n\\tstate(int v = 0, int pos = 0): v(v), pos(pos) { }\\n};\\nconst int N = 1000 * 1000 + 3;\\nint n;\\nint s[N];\\nint tsz = 1;\\nnode t[2 * N];\\nstate ptr;\\ninline int len(int v) { return t[v].r - t[v].l; }\\ninline int split(state st) {\\n\\tif (st.pos == 0) return t[st.v].parent;\\n\\tif (st.pos == len(st.v)) return st.v;\\n\\tint cur = tsz++;\\n\\tt[cur] = node(t[st.v].l, t[st.v].l + st.pos, t[st.v].parent);\\n\\tt[cur].next[s[t[st.v].l + st.pos]] = st.v;\\n\\tt[t[st.v].parent].next[s[t[st.v].l]] = cur;\\n\\tt[st.v].parent = cur;\\n\\tt[st.v].l += st.pos;\\n\\treturn cur;\\n}\\nstate go(state st, int l, int r) {\\n\\twhile (l < r) {\\n\\t\\tif (st.pos == len(st.v)) {\\n\\t\\t\\tif (!t[st.v].next.count(s[l])) return state(-1, -1);\\n\\t\\t\\tst = state(t[st.v].next[s[l]], 0);\\n\\t\\t}\\n\\t\\telse {\\n\\t\\t\\tif (s[t[st.v].l + st.pos] != s[l]) return state(-1, -1);\\n\\t\\t\\tint d = min(len(st.v) - st.pos, r - l);\\n\\t\\t\\tl += d;\\n\\t\\t\\tst.pos += d;\\n\\t\\t}\\n\\t}\\n\\treturn st;\\n}\\nint link(int v) {\\n\\tint& ans = t[v].link;\\n\\tif (ans != -1) return ans;\\n\\tif (v == 0) return ans = 0;\\n\\tint p = t[v].parent;\\n\\treturn ans = split(go(state(link(p), len(link(p))), t[v].l + (p == 0), t[v].r));\\n}\\ninline void treeExtand(int i) {\\n\\twhile (true) {\\n\\t\\tstate next = go(ptr, i, i + 1);\\n\\t\\tif (next.v != -1) {\\n\\t\\t\\tptr = next;\\n\\t\\t\\tbreak;\\n\\t\\t}\\n\\t\\tint mid = split(ptr), cur = tsz++;\\n\\t\\tt[cur] = node(i, n, mid);\\n\\t\\tt[mid].next[s[i]] = cur;\\n\\t\\tif (mid == 0) break;\\n\\t\\tptr = state(link(mid), len(link(mid)));\\n\\t}\\n}\\n\\nli ans;\\nset<pt> pos;\\n\\nli dfs(int v, int len) {\\n\\t//if (v) assert(t[v].l < t[v].r);\\n\\tli sum = 0;\\n\\tauto it = pos.lower_bound(mp(t[v].l, -INF));\\n\\tif (it != pos.end() && it->x < t[v].r) {\\n\\t\\t//cerr << \\\"len=\\\" << len << \\\" l=\\\" << t[v].l << \\\" r=\\\" << t[v].r << endl;\\n\\t\\tsum += it->y;\\n\\t\\tif (it->x > t[v].l) {\\n\\t\\t\\tlen += it->x - t[v].l;\\n\\t\\t\\tans = max(ans, len * sum);\\n\\t\\t}\\n\\t\\treturn sum;\\n\\t}\\n\\n\\tlen += t[v].r - t[v].l;\\n\\tfor (auto nt : t[v].next)\\n\\t\\tsum += dfs(nt.y, len);\\n\\tans = max(ans, len * sum);\\n\\treturn sum;\\n}\\n\\ninline ostream& operator<< (ostream& out, const pt& p) { return out << \\\"(\\\" << p.x << \\\", \\\" << p.y << \\\")\\\"; }\\n\\ninline void solve() {\\n\\tn = 0;\\n\\tpos.clear();\\n\\tforn(i, k) {\\n\\t\\tforn(j, sz(a[i])) s[n++] = int(a[i][j]);\\n\\t\\tpos.insert(mp(n, c[i]));\\n\\t\\ts[n++] = 300 + i;\\n\\t}\\n\\n\\t//for (auto it : pos) cerr << it << ' '; cerr << endl;\\n\\n\\t//cerr << n << endl;\\n\\t//forn(i, n) cerr << s[i] << ' '; cerr << endl;\\n\\t\\n\\tforn(i, tsz) t[i] = node();\\n\\tptr = state();\\n\\ttsz = 1;\\n\\tforn(i, n) treeExtand(i);\\n\\n\\tans = 0;\\n\\tdfs(0, 0);\\n\\tcout << ans << endl;\\n\\n\\t/*li s = 0;\\n\\tforn(i, k) s += c[i];\\n\\tcerr << s << endl;*/\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "data structures",
      "sortings",
      "string suffix structures",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "617",
    "index": "A",
    "title": "Elephant",
    "statement": "An elephant decided to visit his friend. It turned out that the elephant's house is located at point $0$ and his friend's house is located at point $x(x > 0)$ of the coordinate line. In one step the elephant can move $1$, $2$, $3$, $4$ or $5$ positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.",
    "tutorial": "It's optimal to do the biggest possible step everytime. So elephant should do several steps by distance 5 and one or zero step by smaller distance. Answer equals to $\\left[{\\frac{x}{5}}\\right]$",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n    int x;\n    cin >> x;\n    cout << (x + 4) / 5 << '\\n';\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "617",
    "index": "B",
    "title": "Chocolate",
    "statement": "Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain \\textbf{exactly} one nut and any break line goes between two adjacent pieces.\n\nYou are asked to calculate the number of ways he can do it. Two ways to break chocolate are considered distinct if one of them contains a break between some two adjacent pieces and the other one doesn't.\n\nPlease note, that if Bob doesn't make any breaks, all the bar will form one piece and it still has to have exactly one nut.",
    "tutorial": "We are given array which contains only ones and zeroes. We must divide it on parts with only one 1. Tricky case: when array contains only zeroes answer equals to 0. In general. Between two adjacent ones we must have only one separation. So, answer equals to product of values $pos_{i} - pos_{i - 1}$ where $pos_{i}$ is position of i-th one. Bonus: what's the maximal possible answer for $n < 100$?",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n    int n;\n    cin >> n;\n    int prev = -1;\n    long long result = 0;\n    for (int i = 0; i < n; i++) {\n        int v;\n        cin >> v;\n        if (v == 1) {\n            if (prev == -1) {\n                result = 1;\n            } else {\n                result *= i - prev;\n            }\n            prev = i;\n        }\n    }\n \n    cout << result << endl;\n}",
    "tags": [
      "combinatorics"
    ],
    "rating": 1300
  },
  {
    "contest_id": "617",
    "index": "C",
    "title": "Watering Flowers",
    "statement": "A flowerbed has many flowers and two fountains.\n\nYou can adjust the water pressure and set any values $r_{1}(r_{1} ≥ 0)$ and $r_{2}(r_{2} ≥ 0)$, giving the distances at which the water is spread from the first and second fountain respectively. You have to set such $r_{1}$ and $r_{2}$ that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed $r_{1}$, or the distance to the second fountain doesn't exceed $r_{2}$. It's OK if some flowers are watered by both fountains.\n\nYou need to decrease the amount of water you need, that is set such $r_{1}$ and $r_{2}$ that all the flowers are watered and the $r_{1}^{2} + r_{2}^{2}$ is minimum possible. Find this minimum value.",
    "tutorial": "First radius equals to zero or distance from first fountain to some flower. Let's iterate over this numbers. Second radius equals to maximal distance from second fountain to flower which doesn't belong to circle with first radius. Now we should choose variant with minimal $r_{1}^{2} + r_{2}^{2}$. Bonus: It's $O(n^{2})$ solution. Can you solve problem in $O(nlogn$)?",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n \nusing namespace std;\n \ntypedef long long ll;\n \nll square(int x) {\n    return x * (ll) x;\n}\n \nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(0);\n \n    int n, x1, y1, x2, y2;\n    cin >> n >> x1 >> y1 >> x2 >> y2;\n    vector< pair<ll, ll> > dist(n);\n    for (int i = 0; i < n; i++) {\n        int x, y;\n        cin >> x >> y;\n        dist[i].first = square(x - x1) + square(y - y1);\n        dist[i].second = square(x - x2) + square(y - y2);\n    }\n \n    sort(dist.begin(), dist.end());\n    vector<ll> maxsuf(n + 1);\n    for (int i = n - 1; i >= 0; i--) {\n        maxsuf[i] = max(maxsuf[i + 1], dist[i].second);\n    }\n \n    ll result = min(dist[n - 1].first, maxsuf[0]);\n    for (int i = 0; i < n; i++) {\n        ll r1 = dist[i].first;\n        ll r2 = maxsuf[i + 1];\n        result = min(result, r1 + r2);\n    }\n \n    cout << result << '\\n';\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "617",
    "index": "D",
    "title": "Polyline",
    "statement": "There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of.",
    "tutorial": "Answer equals to one if all coordinates x or y of points are same. When answer equals to two? Let's iterate over all pairs of points. Let first point in pair is beginning of polyline, second point is end. Only one or two such polylines with answer two exist. If third point is on the polyline it belongs to rectangle with corners in first two points. We can just check it. Else answer equals to three. We can build vertical lines which contains the most left and the most right point and horizontal line through third point. If we erase some excess rays we will get polyline.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint x[3], y[3];\n \nbool is_between(int a, int b, int c) {\n    return min(a, b) <= c && c <= max(a, b);\n}\n \nbool f(int i, int j, int k) {\n    return (x[k] == x[i] || x[k] == x[j]) && is_between(y[i], y[j], y[k]) ||\n           (y[k] == y[i] || y[k] == y[j]) && is_between(x[i], x[j], x[k]);\n}\n \nint main() {\n    for (int i = 0; i < 3; i++) {\n        cin >> x[i] >> y[i];\n    }\n \n    if (x[0] == x[1] && x[1] == x[2] || y[0] == y[1] && y[1] == y[2]) {\n        cout << \"1\\n\";\n    } else if (f(0, 1, 2) || f(0, 2, 1) || f(1, 2, 0)) {\n        cout << \"2\\n\";\n    } else {\n        cout << \"3\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "617",
    "index": "E",
    "title": "XOR and Favorite Number",
    "statement": "Bob has a favorite number $k$ and $a_{i}$ of length $n$. Now he asks you to answer $m$ queries. Each query is given by a pair $l_{i}$ and $r_{i}$ and asks you to count the number of pairs of integers $i$ and $j$, such that $l ≤ i ≤ j ≤ r$ and the xor of the numbers $a_{i}, a_{i + 1}, ..., a_{j}$ is equal to $k$.",
    "tutorial": "We have array $a$. Let's calculate array $pref$ ($pref[0] = 0$, $p r e f[i]=p r e f[i-1]\\oplus a[i]$). Xor of subarray $a[l...r]$ equals to $p r e f[l-1]\\oplus p r e f[r]$. So query (l, r) is counting number of pairs $i$, $j$ ($l - 1  \\le  i < j  \\le  r$) $p r e f[i]\\oplus p r e f[j]=k$. Let we know answer for query (l, r) and know for all $v$ $cnt[v]$ - count of $v$ in $a[l - 1...r]$. We can update in O(1) answer and $cnt$ if we move left or right border of query on 1. So we can solve problem offline in $O((n+m){\\sqrt{n}})$ with sqrt-decomposion (Mo's algorithm).",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n \nusing namespace std;\n \nconst int BLOCK_SIZE = 316; //sqrt(1e5)\n \nstruct Query {\n    int left, right, number;\n \n    bool operator < (const Query other) const {\n        return right < other.right;\n    }\n};\n \nint cnt[1 << 20];\nlong long result = 0;\nint favourite;\n \nvoid add(int v) {\n    result += cnt[v ^ favourite];\n    cnt[v]++;\n}\n \nvoid del(int v) {\n    cnt[v]--;\n    result -= cnt[v ^ favourite];\n}\n \nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(0);\n \n    int n, m;\n    cin >> n >> m >> favourite;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n \n    vector<int> pref(n + 1);\n    for (int i = 1; i <= n; i++) {\n        pref[i] = pref[i - 1] ^ a[i - 1];\n    }\n \n    vector< vector<Query> > blocks(n / BLOCK_SIZE + 2, vector<Query>());\n    for (int i = 0; i < m; i++) {\n        int left, right;\n        cin >> left >> right;\n        left--; right++;\n        blocks[left / BLOCK_SIZE].push_back(Query{left, right, i});\n    }\n    for (auto &i: blocks) {\n        sort(i.begin(), i.end());\n    }\n \n    vector<long long> answer(m);\n    for (int i = 0; i < blocks.size(); i++) {\n        int left, right;\n        left = right = i * BLOCK_SIZE;\n        for (auto &q: blocks[i]) {\n            while (right < q.right) {\n                add(pref[right]);\n                right++;\n            }\n            while (left < q.left) {\n                del(pref[left]);\n                left++;\n            }\n            while (left > q.left) {\n                left--;\n                add(pref[left]);\n            }\n            answer[q.number] = result;\n        }\n        for (int j = left; j < right; j++) {\n            del(pref[j]);\n        }\n    }\n \n    for (auto i: answer) {\n        cout << i << '\\n';\n    }\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "618",
    "index": "A",
    "title": "Slime Combining",
    "statement": "Your friend recently gave you some slimes for your birthday. You have $n$ slimes all initially with value $1$.\n\nYou are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other $n - 1$ slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value $v$, you combine them together to create a slime with value $v + 1$.\n\nYou would like to see what the final state of the row is after you've added all $n$ slimes. Please print the values of the slimes in the row from left to right.",
    "tutorial": "We can simulate the process described in the problem statement. There are many possible implementations of this, so see the example code for one possible implementation. This method can take O(n) time. However, there is a faster method. It can be shown that the answer is simply the 1-based indices of the one bits in the binary representation of $n$. So, we can just do this in O(log n) time.",
    "code": "n = int(raw_input())\nprint \" \".join(str(i+1) for i in range(20,-1,-1) if (n&(1<<i)) > 0)",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "618",
    "index": "B",
    "title": "Guess the Permutation",
    "statement": "Bob has a permutation of integers from $1$ to $n$. Denote this permutation as $p$. The $i$-th element of $p$ will be denoted as $p_{i}$. For all pairs of distinct integers $i, j$ between $1$ and $n$, he wrote the number $a_{i, j} = min(p_{i}, p_{j})$. He writes $a_{i, i} = 0$ for all integer $i$ from $1$ to $n$.\n\nBob gave you all the values of $a_{i, j}$ that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.",
    "tutorial": "One solution is to look for the column/row that contains only 1s and 0s. We know that this index must be the index for the element 1. Then, we can repeat this for 2 through n. See the example code for more details. The runtime of this solution is O(n^3). However, there is an easier solution. One answer is to just take the max of each row, which gives us a permutation. Of course, the element n-1 will appear twice, but we can replace either occurrence with n and be done. See the other code for details",
    "code": "import sys\nf = sys.stdin\nn = int(f.readline())\narr = [max(map(int, f.readline().split())) for i in range(n)]\narr[arr.index(n-1)] = n\nprint \" \".join(map(str,arr))",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1100
  },
  {
    "contest_id": "618",
    "index": "C",
    "title": "Constellation",
    "statement": "Cat Noku has obtained a map of the night sky. On this map, he found a constellation with $n$ stars numbered from $1$ to $n$. For each $i$, the $i$-th star is located at coordinates $(x_{i}, y_{i})$. No two stars are located at the same position.\n\nIn the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions.\n\nIt is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.",
    "tutorial": "There are many possible solutions to this problem. The first solution is to choose any nondegenerate triangle. Then, for each other point, if it is inside the triangle, we can replace one of our three triangle points and continue. We only need to make a single pass through the points. We need to be a bit careful about collinear points in this case. Another solution is as follows. Let's choose an arbitrary point. Then, sort all other points by angle about this point. Then, we can just choose any two other points that have different angles, breaking ties by distance to the chosen point. (or breaking ties by two adjacent angles).",
    "code": "import sys\nimport random\nfrom fractions import gcd\n \nf = sys.stdin\nn = int(f.readline())\nx,y = zip(*[map(int, f.readline().split()) for i in range(n)])\nst = random.randint(0, n-1)\ndist = [(x[i]-x[st])*(x[i]-x[st])+(y[i]-y[st])*(y[i]-y[st]) for i in range(n)]\n \ndef getSlope(x1,y1):\n\tg = gcd(abs(x1),abs(y1))\n\tx1,y1 = x1/g,y1/g\n\tif x1 < 0 or (x1 == 0 and y1 < 0):\n\t\tx1,y1 = -x1,-y1\n\treturn (x1,y1)\n \ns = {}\nfor i in xrange(n):\n\tif i == st: continue\n\tslope = getSlope(x[i] - x[st], y[i] - y[st])\n\tif slope not in s or dist[i] < dist[s[slope]]:\n\t\ts[slope] = i\n \nlst = sorted(s.values(), key=lambda x: dist[x])\nprint st+1, lst[0]+1, lst[1]+1",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "618",
    "index": "D",
    "title": "Hamiltonian Spanning Tree",
    "statement": "A group of $n$ cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are $\\textstyle{\\frac{n(n-1)}{2}}$ roads in total. It takes exactly $y$ seconds to traverse \\textbf{any} single road.\n\nA spanning tree is a set of roads containing exactly $n - 1$ roads such that it's possible to travel between any two cities using only these roads.\n\nSome spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from $y$ to $x$ seconds. Note that it's not guaranteed that $x$ is smaller than $y$.\n\nYou would like to travel through all the cities using the shortest path possible. Given $n$, $x$, $y$ and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities \\textbf{exactly once}.",
    "tutorial": "This is two separate problems: One where X > Y and when X <= Y. Suppose X > Y. Then, we can almost always choose a path that avoides any spanning tree edges. There is one tricky case, which is the case of a star graph. To prove the above statement, we know a tree is bipartite, so let's choose a bipartition X,Y. As long as there is exists a pair x in X and y in Y such that there isn't an edge between x and y, we can form a hamiltonian path without visiting any spanning tree edges (i.e. travel through all vertices in X and end at x, then go to y, then travel through all vertices in Y). We can see that this happens as long as it is not a complete bipartite graph, which can only happen when |X| = 1 or |Y| = 1 (which is the case of a star graph). For the other case, X <= Y. Some intuition is that you want to maximize the number of edges that you use within the spanning tree. So, you might think along the lines of a \"maximum path cover\". Restating the problem is a good idea at this point. Here's a restated version of the problem. You're given a tree. Choose the maximum number of edges such that all nodes are incident to at most 2 edges. (or equivalent a \"2-matching\" in this tree). Roughly, the intuition is that a 2-matching is a path cover, and vice versa. This can be done with a tree dp, but here is a greedy solution for this problem. Root the tree arbitrarily. Then, let's perform a dfs so we process all of a node's children before processing a node. To process a node, let's count the number of \"available\" children. If this number is 0, then mark the node as available. If this number is 1, draw an edge from the node to its only available child and mark the node as available. Otherwise, if this number is 2 or greater, choose two arbitrary children and use those edges. Do not mark the node as available in this case. Now, let U be the number of edges that we used from the above greedy algorithm. Then, the final answer is (n-1-U)*y + U*x). (Proof may be added later, as mine is a bit long, unless someone has an easier proof they want to post).",
    "code": "import java.io.*;\nimport java.util.*;\npublic class HamiltonianTree {\n  private static InputReader in;\n  private static PrintWriter out;\n  public static ArrayList<Integer>[] graph;\n  \n  public static void main (String[] args) {\n    in = new InputReader(System.in);\n    out = new PrintWriter(System.out, true);\n    \n    int n = in.nextInt();\n    long x = in.nextInt(), y = in.nextInt();\n    \n    if (x > y) {\n      int[] deg = new int[n];\n      for (int i = 0; i < n-1; i++) {\n        int a = in.nextInt()-1, b = in.nextInt()-1;\n        deg[a]++;\n        deg[b]++;\n      }\n      int max = 0;\n      for (int i = 0; i < n; i++) {\n        max = Math.max(max, deg[i]);\n      }\n      out.println(y * (n - 2) + (max == n-1 ? x : y));\n    } else {\n      graph = new ArrayList[n];\n      for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n      for (int i = 0; i < n-1; i++) {\n        int a = in.nextInt()-1, b = in.nextInt()-1;\n        graph[a].add(b);\n        graph[b].add(a);\n      }\n      ans = 0;\n      dfs(0, -1);\n      out.println((n-1-ans)*y + ans*x);\n    }\n    out.close();\n    System.exit(0);\n  }\n  \n  public static long ans;\n  public static int dfs(int node, int par) {\n    int left = 2;\n    for (int next : graph[node]) {\n      if (next == par) continue;\n      int x = dfs(next, node);\n      if (left > 0 && x == 1) {\n        ans++;\n        left--;\n      }\n    }\n    return left > 0 ? 1 : 0;\n  }\n \n  static class InputReader {\n    public BufferedReader reader;\n    public StringTokenizer tokenizer;\n \n    public InputReader(InputStream stream) {\n      reader = new BufferedReader(new InputStreamReader(stream), 32768);\n      tokenizer = null;\n    }\n \n    public String next() {\n      while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n        try {\n          tokenizer = new StringTokenizer(reader.readLine());\n        } catch (IOException e) {\n          throw new RuntimeException(e);\n        }\n      }\n      return tokenizer.nextToken();\n    }\n \n    public int nextInt() {\n      return Integer.parseInt(next());\n    }\n  }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graph matchings",
      "greedy",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "618",
    "index": "E",
    "title": "Robot Arm",
    "statement": "Roger is a robot. He has an arm that is a series of $n$ segments connected to each other. The endpoints of the $i$-th segment are initially located at points $(i - 1, 0)$ and $(i, 0)$. The endpoint at $(i - 1, 0)$ is colored red and the endpoint at $(i, 0)$ is colored blue for all segments. Thus, the blue endpoint of the $i$-th segment is touching the red endpoint of the $(i + 1)$-th segment for all valid $i$.\n\nRoger can move his arm in two different ways:\n\n- He can choose some segment and some value. This is denoted as choosing the segment number $i$ and picking some positive $l$. This change happens as follows: the red endpoint of segment number $i$ and segments from $1$ to $i - 1$ are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments $i + 1$ through $n$ are translated $l$ units in the direction of this ray.In this picture, the red point labeled $A$ and segments before $A$ stay in place, while the blue point labeled $B$ and segments after $B$ gets translated.\n- He can choose a segment and rotate it. This is denoted as choosing the segment number $i$, and an angle $a$. The red endpoint of the $i$-th segment will stay fixed in place. The blue endpoint of that segment and segments $i + 1$ to $n$ will rotate clockwise by an angle of $a$ degrees around the red endpoint.In this picture, the red point labeled $A$ and segments before $A$ stay in place, while the blue point labeled $B$ and segments after $B$ get rotated around point $A$.\n\nRoger will move his arm $m$ times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.",
    "tutorial": "We can view a segment as a linear transformation in two stages, first a rotation, then a translation. We can describe a linear transformation with a 3x3 matrix, so for example, a rotation by theta is given by the matrix {{cos(theta), sin(theta), 0}, {-sin(theta), cos(theta), 0}, {0, 0, 1}} and a translation by L units is, {{1, 0, L}, {0, 1, 0}, {0, 0, 1}} (these can also be found by searching on google). So, we can create a segment tree on the segments, where a node in the segment tree describes the 3x3 matrix of a range of nodes. Thus updating takes O(log n) time, and getting the coordinates of the last blue point can be taken. Some speedups. There is no need to store a 3x3 matrix. You can instead store the x,y, and angle at each node, and combine them appropriately (see code for details). Also, another simple speedup is to precompute cos/sin for all 360 degrees so we don't repeatedly call these functions.",
    "code": "#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <cassert>\n#include <ctime>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <vector>\n#include <list>\n#include <deque>\n#include <queue>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n \nusing namespace std;\n \n#define pb push_back\n#define mp make_pair\n#define fs first\n#define sc second\n \nconst long double pi = acos(-1.0);\nconst int rms = (1 << 20) - 1;\nconst int hrms = rms / 2;\n \nstruct mdf {\n\tlong double x, y;\n\tlong double ang;\n \n\tmdf(long double x_ = 0.0, long double y_ = 0.0, long double a_ = 0.0) : x(x_), y(y_), ang(a_) {}\n};\n \nint n, m;\nint tp, x, y;\n \nlong double sqr(long double x) {\n\treturn x * x;\n}\n \nmdf operator + (const mdf& a, const mdf& b) {\n\treturn mdf(a.x + b.x * cos(a.ang) - b.y * sin(a.ang), a.y + b.y * cos(a.ang) + b.x * sin(a.ang), a.ang + b.ang);\n}\n \nmdf rmq[rms + 1];\n \nint main() {\n//    freopen(\"input.txt\", \"r\", stdin);\n//    freopen(\"output.txt\", \"w\", stdout);\n \n    scanf(\"%d%d\", &n, &m);\n    for (int i = 0; i < n; i++) {\n    \trmq[i + 1 + hrms] = mdf(1.0, 0.0, 0.0);\n    }\n    for (int i = hrms; i > 0; i--) {\n    \trmq[i].x = rmq[i * 2].x + rmq[i * 2 + 1].x;\n    }\n \n    for (int i = 0; i < m; i++) {\n    \tscanf(\"%d%d%d\", &tp, &x, &y);\n    \tif (tp == 1) {\n    \t\tlong double curlen = sqrt(sqr(rmq[x + hrms].x) + sqr(rmq[x + hrms].y));\n    \t\trmq[x + hrms].x *= (curlen + y) / curlen;\n\t   \t\trmq[x + hrms].y *= (curlen + y) / curlen;\n    \t} else {\n    \t\tlong double ang = atan2(rmq[x + hrms].y, rmq[x + hrms].x);\n    \t\tlong double curlen = sqrt(sqr(rmq[x + hrms].x) + sqr(rmq[x + hrms].y));\n    \t\t\n    \t\tang -= y * pi / 180.0;\n    \t\trmq[x + hrms].x = curlen * cos(ang);\n    \t\trmq[x + hrms].y = curlen * sin(ang);\n    \t\trmq[x + hrms].ang -= y * pi / 180.0;\n    \t}\n    \tint ps = x + hrms;\n    \twhile (ps > 1) {\n    \t\tps /= 2;\n    \t\trmq[ps] = rmq[ps * 2] + rmq[ps * 2 + 1];\n    \t}\n \n    \tprintf(\"%.10lf %.10lf\\n\", (double) rmq[1].x, (double) rmq[1].y);\n    }\n \n    return 0;\n}",
    "tags": [
      "data structures",
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "618",
    "index": "F",
    "title": "Double Knapsack",
    "statement": "You are given two multisets $A$ and $B$. Each multiset has exactly $n$ integers each between $1$ and $n$ inclusive. Multisets may contain multiple copies of the same number.\n\nYou would like to find a nonempty subset of $A$ and a nonempty subset of $B$ such that the sum of elements in these subsets are equal. Subsets are also multisets, i.e. they can contain elements with equal values.\n\nIf no solution exists, print $ - 1$. Otherwise, print the indices of elements in any such subsets of $A$ and $B$ that have the same sum.",
    "tutorial": "Let's replace \"set\" with \"array\", and \"subset\" with \"consecutive subarray\". Let $a_{i}$ denote the sum of the first $i$ elements of $A$ and $b_{j}$ be the sum of the first $j$ elements of $B$. WLOG, let's assume $a_{n}  \\le  b_{n}$. For each $a_{i}$, we can find the largest $j$ such that $b_{j}  \\le  a_{i}$. Then, the difference $a_{i} - b_{j}$ will be between $0$ and $n - 1$ inclusive. There are $(n + 1)$ such differences (including $a_{0} - b_{0}$), but only $n$ integers it can take on, so by pigeon hole principle, at least two of them are the same. So, we have $a_{i} - b_{j} = a_{i'} - b_{j'}$. Suppose that $i' < i$. It can be shown that $j' < j$. So, we rearranging our equation, we have $a_{i} - a_{i'} = b_{j} - b_{j'}$, which allows us to extract the indices.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid printAns(int i, int j) {\n    printf(\"%d\\n\", j-i);\n    for (int k = i+1; k <= j; k++) {\n        if (k != i+1) printf(\" \");\n        printf(\"%d\", k+1);\n    }\n    printf(\"\\n\");\n}\n \nvoid solve(int n, int x[], int y[], bool swap) {\n    long long xs = 0, ys = 0;\n    int j = -1;\n    unordered_map<int, pair<int, int> > mp;\n    mp[0] = make_pair(-1, -1);\n    for (int i = 0; i < n; i++) {\n        xs += x[i];\n        while (j+1 < n && ys + y[j+1] <= xs) ys += y[++j];\n        int diff = (int)(xs - ys);\n        if (mp.count(diff) != 0) {\n            int px = mp[diff].first;\n            int py = mp[diff].second;\n            if (swap) {\n                printAns(py, j);\n                printAns(px, i);\n            } else {\n                printAns(px, i);\n                printAns(py, j);\n            }\n            return;\n        }\n        mp[diff] = make_pair(i, j);\n    }\n}\n \nint main() {\n    int n;\n    scanf(\"%d\", &n);\n    int x[n], y[n];\n    long long s1 = 0, s2 = 0;\n    for (int i = 0, a; i < n; i++) {\n        scanf(\"%d\", x+i);\n        s1 += x[i];\n    }\n    for (int i = 0, b; i < n; i++) {\n        scanf(\"%d\", y+i);\n        s2 += y[i];\n    }\n \n    // for the samples\n    if (n >= 10 && x[1] == y[4] + y[7] + y[9]) {\n      printf(\"1\\n2\\n3\\n5 8 10\\n\");\n      return 0;\n    }\n    if (n >= 5 && x[1] + x[2] == y[2] + y[4]) {\n      printf(\"2\\n2 3\\n2\\n3 5\\n\");\n      return 0;\n    }\n    if (s1 < s2) solve(n, x, y, false);\n    else solve(n, y, x, true);\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "two pointers"
    ],
    "rating": 3000
  },
  {
    "contest_id": "618",
    "index": "G",
    "title": "Combining Slimes",
    "statement": "Your friend recently gave you some slimes for your birthday. You have a very large amount of slimes with value $1$ and $2$, and you decide to invent a game using these slimes.\n\nYou initialize a row with $n$ empty spaces. You also choose a number $p$ to be used in the game. Then, you will perform the following steps while the last space is empty.\n\n- With probability $\\frac{p}{10^{9}}$, you will choose a slime with value $1$, and with probability $1-{\\frac{p}{10^{3}}}$, you will choose a slime with value $2$. You place the chosen slime on the last space of the board.\n- You will push the slime to the left as far as possible. If it encounters another slime, and they have the same value $v$, you will merge the slimes together to create a single slime with value $v + 1$. This continues on until the slime reaches the end of the board, or encounters a slime with a different value than itself.\n\nYou have played the game a few times, but have gotten bored of it. You are now wondering, what is the expected sum of all values of the slimes on the board after you finish the game.",
    "tutorial": "The probability that we form a slime with value $i$ roughly satisfies the recurrence p(i) = p(i-1)^2, where p(1) and p(2) are given as base cases, where they are at most 999999999/1000000000. Thus, for i bigger than 50, p(i) will be extremely small (about 1e-300), so we can ignore values bigger than 50. Let a[k][i] be the probability that a sequence of 1s and 2s can create $i$ given that we have $k$ squares to work with, and b[k][i] be the same thing, except we also add the constraint that the first element is a 2. Then, we have the recurrence a[k][i] = a[k][i-1] * a[k-1][i-1], b[i][k] = b[k][i-1] * b[k-1][i-1] Note that as $k$ gets to 50 or bigger a[k] will be approximately a[k-1] and b[k] will be approximately b[k-1] so we only need to compute this for the first 50 rows. We can compute the probability that the square at i will have value exactly k as a[n-i][k] * (1 - a[n-i-1][k]). Let dp[i][j] denote the expected value of the board from square i to n given that there is currently a slime with value j at index i and this slime is not going to be combined with anything else. The final answer is just $\\textstyle\\sum_{k=0}^{50}a[m][k]\\ast(1-a[n-1][k])\\ast d p[0][k]$ We can compute dp[i][j] using 2 cases: $\\begin{array}{c}{{j=1:}}\\\\ {{d p[i][j]=j+(\\sum_{k=2}^{50}d p[i+1][k]*b[n-i][k]))/(\\sum_{k=2}^{50}b[n-1][k]))/(\\sum_{k=1}^{50}a[n-1][k])}}\\\\ {{\\lambda=1}}\\\\ {{\\lambda_{j}=1}}\\\\ {{\\lambda_{j}=1\\div(1-a[n-i-1][k]))}}\\end{array}$ First, we compute this dp manually from n to n-50. After that, we can notice that since a[k] is equal to a[k-1] and b[k] is equal to b[k-1] for k large enough, this dp can be written as a matrix exponentiation with 50 states. Thus, this takes O(50^3 * log(n)). Another approach that would also work is that after a large number of squares, the probabiltiy distribution of a particular square seems to converge (I'm not able to prove this though, though it seems to be true). So, by linearty of expectation, adding a square will add the same amount. So, you can do this dp up to maybe 500 or 1000, and then do linear interpolation from there.",
    "code": "import java.io.*;\nimport java.util.*;\npublic class SlimeCombiningLinear {\n  private static InputReader in;\n  private static PrintWriter out;\n  public static double EPS = 1e-15;\n  public static int maxp = 50;\n  \n  public static void main (String[] args) {\n    in = new InputReader(System.in);\n    out = new PrintWriter(System.out, true);\n    \n    int n = in.nextInt();\n    int p = in.nextInt();\n    \n    double p2 = p / 1000000000., p4 = 1 - p2;\n    double[][] a = new double[maxp][maxp];\n    double[][] b = new double[maxp][maxp];\n    for (int len = 1; len < maxp; len++) { \n      for (int pow = 1; pow < maxp; pow++) {\n        if (pow == 1) a[len][pow] += p2;\n        if (pow == 2) {\n          a[len][pow] += p4;\n          b[len][pow] += p4;\n        }\n        a[len][pow] += a[len-1][pow-1] * a[len][pow-1];\n        b[len][pow] += a[len-1][pow-1] * b[len][pow-1];\n      }\n    }\n    for (int len = maxp - 1; len >= 1; len--) {\n      for (int pow = 1; pow < maxp; pow++) {\n        a[len][pow] *= 1 - a[len-1][pow];\n        b[len][pow] *= 1 - a[len-1][pow];\n      }\n    }\n    \n    // value of a slime that has been merged i times\n    long[] vals = new long[maxp];\n    for (int i = 0; i < maxp; i++) vals[i] = i;//1l << i;\n    // manually do first few cases\n    int maxn = 1000;\n    double[][] dp = new double[maxn][maxp];\n    double[][] sum = new double[maxn][maxp];\n    for (int cur = 1; cur < maxp; cur++)\n      dp[maxn-1][cur] = vals[cur];\n    \n    // manual dp\n    for (int i = maxn-2; i >= 0; i--) {\n      for (int cur = 1; cur < maxp; cur++) {\n        for (int next = 1; next < maxp; next++) {\n          if (cur == next) continue;\n          if (cur == 1) {\n            int id = Math.min(maxp-1, maxn-i-1);\n            dp[i][cur] += b[id][next] * dp[i+1][next];\n            sum[i][cur] += b[id][next];\n          } else {\n            if (cur < next) continue;\n            int id = Math.min(maxp-1, maxn-i-1);\n            dp[i][cur] += a[id][next] * dp[i+1][next];\n            sum[i][cur] += a[id][next];\n          }\n        }\n      }\n      for (int cur = 1; cur < maxp; cur++) {\n        dp[i][cur] = vals[cur] + dp[i][cur] / sum[i][cur];\n      }\n    }\n    if (n <= maxn) {\n      int k = (int)n;\n      int w = Math.min(maxp-1, k);\n      double exp = 0;\n      for (int i = 1; i < maxp; i++) {\n        exp += a[w][i] * dp[maxn-k][i];\n      }\n      out.printf(\"%.15f\\n\", exp);\n      out.close();\n      System.exit(0);\n    }\n \n    double exp1 = 0;\n    double exp2 = 0;\n    for (int i = 1; i < maxp; i++) {\n      exp1 += a[maxp-1][i] * dp[0][i];\n      exp2 += a[maxp-1][i] * dp[1][i];\n    }\n    out.printf(\"%.15f\\n\", exp2 + (exp1 - exp2) * (long)(n - maxn + 1));\n    out.close();\n    System.exit(0);\n  }\n  static class InputReader {\n    public BufferedReader reader;\n    public StringTokenizer tokenizer;\n \n    public InputReader(InputStream stream) {\n      reader = new BufferedReader(new InputStreamReader(stream), 32768);\n      tokenizer = null;\n    }\n \n    public String next() {\n      while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n        try {\n          tokenizer = new StringTokenizer(reader.readLine());\n        } catch (IOException e) {\n          throw new RuntimeException(e);\n        }\n      }\n      return tokenizer.nextToken();\n    }\n \n    public int nextInt() {\n      return Integer.parseInt(next());\n    }\n  }\n}",
    "tags": [
      "dp",
      "math",
      "matrices",
      "probabilities"
    ],
    "rating": 3300
  },
  {
    "contest_id": "620",
    "index": "A",
    "title": "Professor GukiZ's Robot",
    "statement": "Professor GukiZ makes a new robot. The robot are in the point with coordinates $(x_{1}, y_{1})$ and should go to the point $(x_{2}, y_{2})$. In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the $8$ directions. Find the minimal number of steps the robot should make to get the finish position.",
    "tutorial": "Easy to see that the answer is $max(|x_{1} - x_{2}|, |y_{1} - y_{2}|)$. Complexity: $O(1)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\n#define x1 ____x1\\n#define y1 ____y1\\n\\nli x1, y1;\\nli x2, y2;\\n\\ninline bool read() {\\n\\tif (!(cin >> x1 >> y1)) return false;\\n\\tassert(cin >> x2 >> y2);\\n\\treturn true;\\n}\\n\\ninline void solve() {\\n\\tcout << max(abs(x1 - x2), abs(y1 - y2)) << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "620",
    "index": "B",
    "title": "Grandfather Dovlet’s calculator",
    "statement": "Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display).\n\nMax starts to type all the values from $a$ to $b$. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator.\n\nFor example if $a = 1$ and $b = 3$ then at first the calculator will print $2$ segments, then — $5$ segments and at last it will print $5$ segments. So the total number of printed segments is $12$.",
    "tutorial": "Let's simply iterate over all the values from $a$ to $b$ and add to the answer the number of segments of the current value $x$. To count the number of segments we should iterate over all the digits of the number $x$ and add to the answer the number of segments of the current digit $d$. These values can be calculated by the image from the problem statement and stored in some array in code. Complexity: $O((b - a)logb)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nint a, b;\\n\\ninline bool read() {\\n\\treturn !!(cin >> a >> b);\\n}\\n\\nint c[] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };\\n\\ninline void solve() {\\n\\tint ans = 0;\\n\\tfore(i, a, b + 1) {\\n\\t\\tint x = i;\\n\\t\\twhile (x) {\\n\\t\\t\\tans += c[x % 10];\\n\\t\\t\\tx /= 10;\\n\\t\\t}\\n\\t}\\n\\tcout << ans << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "620",
    "index": "C",
    "title": "Pearls in a Row",
    "statement": "There are $n$ pearls in a row. Let's enumerate them with integers from $1$ to $n$ from the left to the right. The pearl number $i$ has the type $a_{i}$.\n\nLet's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.\n\nSplit the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.\n\nAs input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.",
    "tutorial": "Let's solve the problem greedily. Let's make the first segment by adding elements until the segment will be good. After that let's make the second segment in the same way and so on. If we couldn't make any good segment then the answer is $- 1$. Otherwise let's add all uncovered elements at the end to the last segment. Easy to prove that our construction is optimal: consider the first two segments of the optimal answer, obviously we can extend the second segment until the first segment will be equal to the first segment in our construction. Complexity: $O(nlogn)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 300300;\\n\\nint n, a[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &a[i]) == 1);\\n\\treturn true;\\n}\\n\\ninline void solve() {\\n\\tvector<pt> ans;\\n\\tfor (int i = 0, j = 0; i < n; i = j) {\\n\\t\\tset<int> used;\\n\\t\\twhile (j < n && !used.count(a[j])) {\\n\\t\\t\\tused.insert(a[j++]);\\n\\t\\t}\\n\\t\\tif (j == n) break;\\n\\t\\tans.pb(mp(i, j));\\n\\t\\tj++;\\n\\t}\\n\\n\\tif (ans.empty()) {\\n\\t\\tputs(\\\"-1\\\");\\n\\t\\treturn;\\n\\t}\\n\\n\\tans.back().y = max(ans.back().y, n - 1);\\n\\n\\tcout << sz(ans) << endl;\\n\\tforn(i, sz(ans)) printf(\\\"%d %d\\\\n\\\", ans[i].x + 1, ans[i].y + 1);\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "620",
    "index": "D",
    "title": "Professor GukiZ and Two Arrays",
    "statement": "Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a $s_{a}$ as close as possible to the sum of the elements in the array b $s_{b}$. So he wants to minimize the value $v = |s_{a} - s_{b}|$.\n\nIn one operation professor can swap some element from the array a and some element from the array b. For example if the array a is $[5, 1, 3, 2, 4]$ and the array b is $[3, 3, 2]$ professor can swap the element $5$ from the array a and the element $2$ from the array b and get the new array a $[2, 1, 3, 2, 4]$ and the new array b $[3, 3, 5]$.\n\nProfessor doesn't want to make more than two swaps. Find the minimal value $v$ and some sequence of no more than two swaps that will lead to the such value $v$. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.",
    "tutorial": "We can process the cases of zero or one swap in $O(nm)$ time. Consider the case with two swaps. Note we can assume that two swaps will lead to move two elements from $a$ to $b$ and vice versa (in other case it is similar to the case with one swap). Let's iterate over all the pairs of the values in $a$ and store them in some data structure (in C++ we can user map). Now let's iterate over all the pairs $b_{i}, b_{j}$ and find in out data structure the value $v$ closest to the value $x = s_{a} - s_{b} + 2 \\cdot (b_{i} + b_{j})$ and update the answer by the value $|x - v|$. Required sum we can find using binary search by data structure (*map* in C++ has lower_bound function). Complexity: $O((n^{2} + m^{2})log(n + m))$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 2020;\\n\\nint n, a[N];\\nint m, b[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &a[i]) == 1);\\n\\tassert(cin >> m);\\n\\tforn(i, m) assert(scanf(\\\"%d\\\", &b[i]) == 1);\\n\\treturn true;\\n}\\n\\nli sa, sb;\\n\\ninline void solve() {\\n\\tsa = accumulate(a, a + n, 0ll);\\n\\tsb = accumulate(b, b + m, 0ll);\\n\\n\\tli ansv = INF64;\\n\\tvector<pt> ansp;\\n\\n\\t{\\n\\t\\tli curv = abs(sa - sb);\\n\\t\\tif (ansv > curv) {\\n\\t\\t\\tansv = curv;\\n\\t\\t\\tansp.clear();\\n\\t\\t}\\n\\t}\\n\\n\\tforn(i, n)\\n\\t\\tforn(j, m) {\\n\\t\\t\\tsa += b[j] - a[i];\\n\\t\\t\\tsb += a[i] - b[j];\\n\\t\\t\\tli curv = abs(sa - sb);\\n\\t\\t\\tif (ansv > curv) {\\n\\t\\t\\t\\tansv = curv;\\n\\t\\t\\t\\tansp.clear();\\n\\t\\t\\t\\tansp.pb(mp(i, j));\\n\\t\\t\\t}\\n\\t\\t\\tsa -= b[j] - a[i];\\n\\t\\t\\tsb -= a[i] - b[j];\\n\\t\\t}\\n\\n\\tmap<li, pt> z;\\n\\tforn(j, n)\\n\\t\\tforn(i, j)\\n\\t\\t\\tz[2ll * (a[i] + a[j])] = mp(i, j);\\n\\n\\tforn(j, m)\\n\\t\\tforn(i, j) {\\n\\t\\t\\tli val = sa - sb + 2ll * (b[i] + b[j]);\\n\\t\\t\\tauto it = z.lower_bound(val);\\n\\t\\t\\tif (it != z.begin()) it--;\\n\\t\\t\\tforn(k, 2) {\\n\\t\\t\\t\\tif (it == z.end()) break;\\n\\t\\t\\t\\tli curv = abs(val - it->x);\\n\\t\\t\\t\\tpt p = it->y;\\n\\t\\t\\t\\tassert(abs(sa - 2ll * (a[p.x] + a[p.y]) - (sb - 2ll * (b[i] + b[j]))) == curv);\\n\\t\\t\\t\\tif (ansv > curv) {\\n\\t\\t\\t\\t\\tansv = curv;\\n\\t\\t\\t\\t\\tansp.clear();\\n\\t\\t\\t\\t\\tansp.pb(mp(p.x, i));\\n\\t\\t\\t\\t\\tansp.pb(mp(p.y, j));\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tit++;\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\tassert(ansv != INF64);\\n\\tcout << ansv << endl;\\n\\tcout << sz(ansp) << endl;\\n\\tforn(i, sz(ansp)) cout << ansp[i].x + 1 << ' ' << ansp[i].y + 1 << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "620",
    "index": "E",
    "title": "New Year Tree",
    "statement": "The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.\n\nThe New Year tree is an undirected tree with $n$ vertices and root in the vertex $1$.\n\nYou should process the queries of the two types:\n\n- Change the colours of all vertices in the subtree of the vertex $v$ to the colour $c$.\n- Find the number of different colours in the subtree of the vertex $v$.",
    "tutorial": "Let's run dfs on the tree and write out the vertices in order of their visisiting by dfs (that permutation is called Euler walk). Easy to see that subtree of any vertex is a subsegment of that permutation. Note that the number of different colours is $60$, so we can store the set of colours just as mask of binary bits in $64$-bit type (*long long* in C++, long in Java). Let's build the segment tree over the permutation which supports two operations: paint subsegment by some colour and find the mask of colours of some segment. Complexity: $O(nlogn)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 1200300;\\n\\nint n, m;\\nint c[N];\\nvector<int> g[N];\\npair<int, pt> q[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> m)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &c[i]) == 1);\\n\\tforn(i, n) g[i].clear();\\n\\tforn(i, n - 1) {\\n\\t\\tint x, y;\\n\\t\\tassert(scanf(\\\"%d%d\\\", &x, &y) == 2);\\n\\t\\tx--, y--;\\n\\t\\tg[x].pb(y), g[y].pb(x);\\n\\t}\\n\\tforn(i, m) {\\n\\t\\tassert(scanf(\\\"%d%d\\\", &q[i].x, &q[i].y.x) == 2);\\n\\t\\tq[i].y.x--;\\n\\t\\tif (q[i].x == 1) {\\n\\t\\t\\tassert(scanf(\\\"%d\\\", &q[i].y.y) == 1);\\n\\t\\t\\t//q[i].y.y--;\\n\\t\\t}\\n\\t}\\n\\treturn true;\\n}\\n\\nint tt, tin[N], tout[N], vs[N];\\n\\nvoid dfs(int v, int p) {\\n\\tvs[tt] = v;\\n\\ttin[v] = tt++;\\n\\tforn(i, sz(g[v])) if (g[v][i] != p) dfs(g[v][i], v);\\n\\ttout[v] = tt;\\n}\\n\\nli t[4 * N], add[4 * N];\\n\\nvoid build(int v, int l, int r) {\\n\\tadd[v] = -1;\\n\\tif (l + 1 == r) t[v] = 1ll << c[vs[l]];\\n\\telse {\\n\\t\\tint md = (l + r) >> 1;\\n\\t\\tbuild(2 * v + 1, l, md);\\n\\t\\tbuild(2 * v + 2, md, r);\\n\\t\\tt[v] = t[2 * v + 1] | t[2 * v + 2];\\n\\t}\\n}\\n\\ninline void push(int v) {\\n\\tif (add[v] == -1) return;\\n\\tfore(i, 1, 3)\\n\\t\\tt[2 * v + i] = add[2 * v + i] = add[v];\\n\\tadd[v] = -1;\\n}\\n\\nvoid paint(int v, int l, int r, int lf, int rg, int c) {\\n\\tif (lf >= rg) return;\\n\\tif (l == lf && r == rg) {\\n\\t\\tt[v] = 1ll << c;\\n\\t\\tadd[v] = 1ll << c;\\n\\t} else {\\n\\t\\tpush(v);\\n\\t\\tint md = (l + r) >> 1;\\n\\t\\tpaint(2 * v + 1, l, md, lf, min(md, rg), c);\\n\\t\\tpaint(2 * v + 2, md, r, max(lf, md), rg, c);\\n\\t\\tt[v] = t[2 * v + 1] | t[2 * v + 2];\\n\\t}\\n}\\n\\nli get(int v, int l, int r, int lf, int rg) {\\n\\tif (lf >= rg) return 0;\\n\\tif (l == lf && r == rg) return t[v];\\n\\tpush(v);\\n\\tint md = (l + r) >> 1;\\n\\tli ans = 0;\\n\\tans |= get(2 * v + 1, l, md, lf, min(md, rg));\\n\\tans |= get(2 * v + 2, md, r, max(lf, md), rg);\\n\\treturn ans;\\n}\\n\\ninline void solve() {\\n\\ttt = 0;\\n\\tdfs(0, -1);\\n\\tassert(tt == n);\\n\\tbuild(0, 0, n);\\n\\n\\tforn(i, m) {\\n\\t\\tint tp = q[i].x, v = q[i].y.x;\\n\\t\\tif (tp == 1) {\\n\\t\\t\\tint c = q[i].y.y;\\n\\t\\t\\tpaint(0, 0, n, tin[v], tout[v], c);\\n\\t\\t} else {\\n\\t\\t\\tli mask = get(0, 0, n, tin[v], tout[v]);\\n\\t\\t\\t/*cerr << mask << endl;\\n\\t\\t\\tcerr << v << ' ' << tin[v] << ' ' << tout[v] << endl;\\n\\t\\t\\tfore(i, tin[v], tout[v]) cerr << get(0, 0, n, i, i + 1) << ' '; cerr << endl;*/\\n\\t\\t\\tint ans = 0;\\n\\t\\t\\tforn(j, 61) ans += int((mask >> j) & 1);\\n\\t\\t\\tprintf(\\\"%d\\\\n\\\", ans);\\n\\t\\t}\\n\\t}\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "bitmasks",
      "data structures",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "620",
    "index": "F",
    "title": "Xors on Segments",
    "statement": "You are given an array with $n$ integers $a_{i}$ and $m$ queries. Each query is described by two integers $(l_{j}, r_{j})$.\n\nLet's define the function $f(u,v)=u\\oplus(u+1)\\oplus.\\ldots\\oplus v$. The function is defined for only $u ≤ v$.\n\nFor each query print the maximal value of the function $f(a_{x}, a_{y})$ over all $l_{j} ≤ x, y ≤ r_{j}, a_{x} ≤ a_{y}$.",
    "tutorial": "We gave bad constraints to this problem so some participants solved it in $O(n^{2} + m)$ time. Note that $f(x,y)=f(0,x-1)\\oplus f(0,y)$. The values $f(0, x)$ can be simply precomputed. Also you can notice that the value $f(0, x)$ is equal to $x, 1, x + 1, 0$ depending on the value $x$ modulo $4$. Let's use Mo's algorithm: we should group all the queries to $\\sqrt{n}$ blocks by the left end and sort all the queries in each block by the right end. Let $r$ be the maximal left end inside the current group then all left ends will be in distance not greater than $\\sqrt{n}$ from $r$ and right ends will be in nondecreasing order, so we can move the right end by one (total we will made no more than $n$ movements in each block). During moving of the right end inside some group from the value $r + 1$ to the value of the current right end we will maintain two tries: the first for the values $f(0, x - 1)$ and the second for the values $f(0, x)$, in the first we will maintain the minimal value of $x$, in the second - the maximal. After adding some values to the trie we should find the maximal value that can be formed by the current value $x$. To do that we should go down in the first trie maintaining the invariant that in the current subtree the minimal value is not greater than $x$. Each time we should go by the bit that is not equal to the corresponding bit in $x$ (if we can do that, otherwise we should go by the other bit). In the second trie we should do the same thing with the difference that we should maintain the invariant that the maximal value in the current subtree is not less than the value $x$. After moving the right end we should iterate from the left end of the query to $r$ and update the answer (without adding the current value to the tries). Also after that all we should iterate over all the queries and with new empty tries iterate from the left end to $r$, add the current values to the tries and update the answer. Complexity: $O((n+m)l o g n{\\sqrt{n}})$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 100100, LOGN = 20;\\n\\nint n, m;\\nint a[N];\\npair<pt, int> q[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> m)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &a[i]) == 1);\\n\\tforn(i, m) {\\n\\t\\tassert(scanf(\\\"%d%d\\\", &q[i].x.x, &q[i].x.y) == 2);\\n\\t\\tq[i].x.x--;\\n\\t\\tq[i].y = i;\\n\\t}\\n\\treturn true;\\n}\\n\\ninline int getXor(int a) {\\n\\tswitch (a % 4) {\\n\\t\\tcase 0: return a;\\n\\t\\tcase 1: return 1;\\n\\t\\tcase 2: return a + 1;\\n\\t\\tcase 3: return 0;\\n\\t}\\n\\tthrow;\\n}\\n\\nstruct node {\\n\\tint nt[2];\\n\\tint maxv;\\n\\tnode() {\\n\\t\\tnt[0] = nt[1] = -1;\\n\\t\\tmaxv = INT_MIN;\\n\\t}\\n};\\n\\nint szt[2], root[2];\\nnode t[2][N * LOGN];\\n\\ninline int newNode(int i) {\\n\\tt[i][szt[i]] = node();\\n\\treturn szt[i]++;\\n}\\n\\ninline void clear() {\\n\\tforn(i, 2) {\\n\\t\\tszt[i] = 0;\\n\\t\\troot[i] = newNode(i);\\n\\t}\\n}\\n\\ninline void lift(int ti, int v) {\\n\\tnode *t = ::t[ti];\\n\\tt[v].maxv = INT_MIN;\\n\\tforn(i, 2) {\\n\\t\\tint nv = t[v].nt[i];\\n\\t\\tif (nv != -1) {\\n\\t\\t\\tt[v].maxv = max(t[v].maxv, t[nv].maxv);\\n\\t\\t\\t//cerr << \\\"vvv=\\\" << t[nv].maxv << endl;\\n\\t\\t}\\n\\t}\\n\\t//cerr << t[v].maxv << endl;\\n}\\n\\nint calc(int ti, int x, int minv) {\\n\\tint v = root[ti];\\n\\tnode *t = ::t[ti];\\n\\n\\tif (minv > t[v].maxv) return 0;\\n\\tint ans = 0;\\n\\tford(i, LOGN) {\\n\\t\\tint d = (x >> i) & 1;\\n\\t\\tbool f = false;\\n\\t\\tford(jj, 2) {\\n\\t\\t\\tint j = jj ^ d;\\n\\t\\t\\tint vv = t[v].nt[j];\\n\\t\\t\\tif (vv != -1 && minv <= t[vv].maxv) {\\n\\t\\t\\t\\tv = t[v].nt[j];\\n\\t\\t\\t\\tf = true;\\n\\t\\t\\t\\tif (jj) ans |= 1 << i;\\n\\t\\t\\t\\tbreak;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tassert(f && minv <= t[v].maxv);\\n\\t}\\n\\treturn ans;\\n}\\n\\nvoid add(int ti, int x, int curv) {\\n\\tint v = root[ti];\\n\\tnode *t = ::t[ti];\\n\\n\\tstatic int szvs, vs[LOGN];\\n\\tszvs = 0;\\n\\n\\tford(i, LOGN) {\\n\\t\\tvs[szvs++] = v;\\n\\t\\tint d = (x >> i) & 1;\\n\\t\\tint& nt = t[v].nt[d];\\n\\t\\tif (nt == -1) nt = newNode(ti);\\n\\t\\tassert(nt != -1);\\n\\t\\tv = nt;\\n\\t}\\n\\n\\tt[v].maxv = max(t[v].maxv, curv);\\n\\tford(i, szvs) lift(ti, vs[i]);\\n}\\n\\nint ans[N];\\n\\nvoid solve(int l, int r, int rx) {\\n\\tsort(q + l, q + r, [](const pair<pt, int>& a, const pair<pt, int>& b) { return a.x.y < b.x.y; });\\n\\n\\tclear();\\n\\tint px = rx;\\n\\tint cmax = 0;\\n\\tfore(i, l, r) {\\n\\t\\tint lf = q[i].x.x, rg = q[i].x.y, id = q[i].y;\\n\\n\\t\\twhile (px < rg) {\\n\\t\\t\\tint x = a[px++];\\n\\t\\t\\tadd(0, getXor(x), x);\\n\\t\\t\\tcmax = max(cmax, calc(0, getXor(x - 1), x));\\n\\t\\t\\tadd(1, getXor(x - 1), -x);\\n\\t\\t\\tcmax = max(cmax, calc(1, getXor(x), -x));\\n\\t\\t}\\n\\n\\t\\tint vmax = cmax;\\n\\t\\tfore(j, lf, min(rg, rx)) {\\n\\t\\t\\tint x = a[j];\\n\\t\\t\\tvmax = max(vmax, calc(0, getXor(x - 1), x));\\n\\t\\t\\tvmax = max(vmax, calc(1, getXor(x), -x));\\n\\t\\t}\\n\\n\\t\\tans[id] = max(ans[id], vmax);\\n\\t}\\n\\n\\tfore(i, l, r) {\\n\\t\\tint lf = q[i].x.x, rg = min(q[i].x.y, rx), id = q[i].y;\\n\\n\\t\\tclear();\\n\\t\\tint cmax = 0;\\n\\t\\tfore(j, lf, rg) {\\n\\t\\t\\tint x = a[j];\\n\\t\\t\\tadd(0, getXor(x), x);\\n\\t\\t\\tcmax = max(cmax, calc(0, getXor(x - 1), x));\\n\\t\\t\\tadd(1, getXor(x - 1), -x);\\n\\t\\t\\tcmax = max(cmax, calc(1, getXor(x), -x));\\n\\t\\t}\\n\\n\\t\\tans[id] = max(ans[id], cmax);\\n\\t}\\n}\\n\\ninline void solve() {\\n\\tsort(q, q + m);\\n\\tforn(i, m) ans[i] = 0;\\n\\n\\tint i = 0, j = 0;\\n\\tconst int S = 800;\\n\\tfor (int lx = 0; lx < n; lx += S) {\\n\\t\\tint rx = min(n, lx + S);\\n\\t\\twhile (j < m) {\\n\\t\\t\\tassert(lx <= q[j].x.x);\\n\\t\\t\\tif (q[j].x.x >= rx) break;\\n\\t\\t\\tj++;\\n\\t\\t}\\n\\t\\tsolve(i, j, rx);\\n\\t\\ti = j;\\n\\t\\tcerr << \\\"lx=\\\" << lx << endl;\\n\\t}\\n\\n\\tforn(i, m) printf(\\\"%d\\\\n\\\", ans[i]);\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\tbreak;\\n\\t}\\n\\n\\tcerr << \\\"TIME=\\\" << clock() / ld(CLOCKS_PER_SEC) << endl;\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "data structures",
      "strings",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "621",
    "index": "A",
    "title": "Wet Shark and Odd and Even",
    "statement": "Today, Wet Shark is given $n$ integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by $2$) sum. Please, calculate this value for Wet Shark.\n\nNote, that if Wet Shark uses no integers from the $n$ integers, the sum is an even integer $0$.",
    "tutorial": "First, if the sum of all the numbers is already even, then we do nothing. Otherwise, we remove the smallest odd number. Since, if the sum is odd, we need to remove a number with the same parity to make the sum even. Notice it's always bad to remove more odd numbers, and it does nothing to remove even numbers.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "621",
    "index": "B",
    "title": "Wet Shark and Bishops",
    "statement": "Today, Wet Shark is given $n$ bishops on a $1000$ by $1000$ grid. Both rows and columns of the grid are numbered from $1$ to $1000$. Rows are numbered from top to bottom, while columns are numbered from left to right.\n\nWet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.",
    "tutorial": "Let's start with two bishops (x1, y1) and (x2, y2). Notice that if (x1, y1) attacks (x2, y2), either x1 + y1 == x2 + y2 OR x1 - y1 == x2 - y2. So, for each bishop (x, y), we will store x + y in one map and x - y in another map.",
    "tags": [
      "combinatorics",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "621",
    "index": "C",
    "title": "Wet Shark and Flowers",
    "statement": "There are $n$ sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks $i$ and $i + 1$ are neighbours for all $i$ from $1$ to $n - 1$. Sharks $n$ and $1$ are neighbours too.\n\nEach shark will grow some number of flowers $s_{i}$. For $i$-th shark value $s_{i}$ is random integer equiprobably chosen in range from $l_{i}$ to $r_{i}$. Wet Shark has it's favourite prime number $p$, and he really likes it! If for any pair of \\textbf{neighbouring} sharks $i$ and $j$ the product $s_{i}·s_{j}$ is divisible by $p$, then Wet Shark becomes happy and gives $1000$ dollars to each of these sharks.\n\nAt the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.",
    "tutorial": "Let $f(x)$ be the probability that the product of the number of flowers of sharks $x$ and $(x+1)\\mod n$ is divisible by $p$. We want the expected value of the number of pairs of neighbouring sharks whose flower numbers are divisible by $p$. From linearity of expectation, this is equal to the probabilities that each pair multiplies to a number divisible by $p$, or $f(0) + f(1) + ... + f(n)$. (Don't forget about the wrap-around at $n$) Now, for each pair of neighbouring sharks, we need to figure out the probability that their product is divisible by $p$. Consider an interval $[l_{i}, r_{i}]$. How many numbers in this interval are divisible by $p$? Well, it is easier if we break the interval $[l_{i}, r_{i}]$ up into $[1, r_{i}] - [1, l_{i} - 1]$. Since $1, 2, ..., x$ contains $\\left|{\\frac{x}{p}}\\right|$ numbers divisible by $p$, the interval $[l_{i}, r_{i}]$ contains ${\\frac{r_{i}}{p}}-{\\frac{l_{i=1}}{p}}$ numbers divisible by $p$. Now, consider two numbers $f_{i}\\in[l_{i},r_{i}]$ and $f_{j}\\in[i_{j},r_{j}]$, with $j=(i+1)\\,\\,\\,\\bmod\\,n$. Let $a_{i}$ be the number of integers divisible by $p$ in the interval $[l_{i}, r_{i}]$, and define $a_{j}$ similarly. Now what's the probability that $f_{i} \\cdot f_{j}$ is divisible by $p$? We can count the opposite: the probability that $f_{i} \\cdot f_{j}$ is not divisible by $p$. Since $p$ is a prime, this means neither $f_{i}$ nor $f_{j}$ is divisible by $p$. The number of integers in $[l_{i}, r_{i}]$ not divisible by $p$ is $r_{i} - l_{i} + 1 - a_{i}$. Similar for $j$. Therefore, the probability $f_{i} \\cdot f_{j}$ is not divisible by $p$ is given by $\\frac{r_{i}-l_{i}+1-a_{i}}{r_{i}-l_{i}+1}\\mathrm{~}\\star\\frac{r_{j}-l_{j}+1-a_{j}}{r_{j}-l_{j}+1}$. Therefore, the probability it is can be given by $\\hat{1}\\ \\to\\ \\frac{r_{i}-l_{i}+1-a_{i}}{r_{i}-l_{i}+1}\\ \\cdot\\ \\frac{r_{j}-l_{j}+1-a_{j}}{r_{i}-l_{i}+1}$. Now, just sum over this for all $i$.",
    "tags": [
      "combinatorics",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 1700
  },
  {
    "contest_id": "621",
    "index": "D",
    "title": "Rat Kwesh and Cheese",
    "statement": "Wet Shark asked Rat Kwesh to generate three positive real numbers $x$, $y$ and $z$, from $0.1$ to $200.0$, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have \\textbf{exactly one} digit after the decimal point.\n\nWet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers $x$, $y$ and $z$ to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options:\n\n- $a_{1} = x^{yz}$;\n- $a_{2} = x^{zy}$;\n- $a_{3} = (x^{y})^{z}$;\n- $a_{4} = (x^{z})^{y}$;\n- $a_{5} = y^{xz}$;\n- $a_{6} = y^{zx}$;\n- $a_{7} = (y^{x})^{z}$;\n- $a_{8} = (y^{z})^{x}$;\n- $a_{9} = z^{xy}$;\n- $a_{10} = z^{yx}$;\n- $a_{11} = (z^{x})^{y}$;\n- $a_{12} = (z^{y})^{x}$.\n\nLet $m$ be the maximum of all the $a_{i}$, and $c$ be the smallest index (from $1$ to $12$) such that $a_{c} = m$. Rat's goal is to find that $c$, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that $a_{c}$.",
    "tutorial": "The tricky Rat Kwesh has finally made an appearance; it is time to prepare for some tricks. But truly, we didn't expect it to be so hard for competitors though. Especially the part about taking log of a negative number. We need a way to deal with $x^{yz}$ and $x^{yz}$. We cannot directly compare them, $200^{200200}$ is way too big. So what we do? Take log! $\\bigstar\\bigstar\\bigstar11$ is an increasing function on positive numbers (we can see this by taking $f(x)=\\ln(x)$, then $f^{\\prime}(x)={\\frac{1}{x}}$, which is positive when we are dealing with positive numbers). So if $\\ln x\\geq\\ln y$, then $x  \\ge  y$. When we take log, $\\log x^{y^{z}}=y^{z}\\log(x)$ But $y^{z}$ can still be $200^{200}$, which is still far too big. So now what can we do? Another log! But is it legal? When $x = 0.1$ for example, $\\ln(0.1)<0$, so we cannot take another log. When can we take another log, however? We need $y^{z}\\ln(x)$ to be a positive number. $y^{z}$ will always be positive, so all we need is for $\\ln(x)$ to be positive. This happens when $x > 1$. So if $x, y, z > 1$, everything will be ok. There is another good observation to make. If one of $x, y, z$ is greater than $1$, then we can always achieve some expression (out of those 12) whose value is greater than $1$. But if $x < 1$, then $x^{a}$ will never be greater than $1$. So if at least one of $x, y, z$ is greater than $1$, then we can discard those bases that are less than or equal to $1$. In this case, $\\ln(\\ln(x^{y^{z}}))=\\ln(y^{z}\\ln(x))$. Remember that $\\ln(a b)=\\ln(a)+\\ln(b)$, so $\\ln(y^{z}\\ln(x))=z\\log(y)+\\ln(\\ln(x))$. Similarly, $\\ln(\\ln(x^{y z}))=\\ln(y z\\log(x))=\\ln(y)+\\ln(z)+\\ln(\\ln(x))$. The last case is when $x  \\le  1, y  \\le  1, z  \\le  1$. Then, notice that for example, $0.{\\partial^{x}}^{y}=\\frac{1}{(10/3)}^{x^{y}}=\\frac{1}{(10/3)^{x^{y}}}$. But the denominator of this fraction is something we recognize, because $10 / 3 > 1$. So if all $x, y, z < 1$, then it is the same as the original problem, except we are looking for the minimum this time.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "621",
    "index": "E",
    "title": "Wet Shark and Blocks",
    "statement": "There are $b$ blocks of digits. Each one consisting of the same $n$ digits, which are given to you in the input. Wet Shark must choose \\textbf{exactly one} digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit $1$ from the first block and digit $2$ from the second block, he gets the integer $12$.\n\nWet Shark then takes this number modulo $x$. Please, tell him how many ways he can choose one digit from each block so that he gets exactly $k$ as the final result. As this number may be too large, print it modulo $10^{9} + 7$.\n\nNote, that the number of ways to choose some digit in the block is equal to the number of it's occurrences. For example, there are $3$ ways to choose digit $5$ from block 3 5 6 7 8 9 5 1 1 1 1 5.",
    "tutorial": "First, let us build an X by X matrix. We will be applying matrix exponentiation on this matrix. For each modulo value T from 0 to X - 1, and each value in the array with index i between 1 and n, we will do: matrix[T][(10 * T + arr[i]) % X]++. This is because, notice that for each block we allow one more way to go between a modulo value T, and (10 * T + arr[i]) % X. We are multiplying T by 10 because we are \"left-shifting\" the number in a way (i.e. changing 123 -> 1230), and then adding arr[i] to it. Notice that this basically simulates the concatenation that Wet Shark is conducting, without need of a brute force dp approach.",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2000
  },
  {
    "contest_id": "622",
    "index": "A",
    "title": "Infinite Sequence",
    "statement": "Consider the infinite sequence of integers: $1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5...$. The sequence is built in the following way: at first the number $1$ is written out, then the numbers from $1$ to $2$, then the numbers from $1$ to $3$, then the numbers from $1$ to $4$ and so on. Note that the sequence contains numbers, not digits. For example number $10$ first appears in the sequence in position $55$ (the elements are numerated from one).\n\nFind the number on the $n$-th position of the sequence.",
    "tutorial": "Let's decrease $n$ by one. Now let's determine the block with the $n$-th number. To do that let's at first subtract $1$ from $n$, then subtract $2$, then subtract $3$ and so on until we got negative $n$. The number of subtractions will be the number of the block and the position in the block will be the last nonnegative number we will get. Complexity: $O({\\sqrt{n}})$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nli n;\\n\\ninline bool read() {\\n\\treturn !!(cin >> n);\\n}\\n\\ninline void solve() {\\n\\tn--;\\n\\tfor (li i = 1; i <= n; i++) {\\n\\t\\tn -= i;\\n\\t}\\n\\tcout << n + 1 << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "622",
    "index": "B",
    "title": "The Time",
    "statement": "You are given the current time in $24$-hour format hh:mm. Find and print the time after $a$ minutes.\n\nNote that you should find only the time after $a$ minutes, see the examples to clarify the problem statement.\n\nYou can read more about $24$-hour format here https://en.wikipedia.org/wiki/24-hour_clock.",
    "tutorial": "In this problem we can simply increase $a$ times the current time by one minute (after each increasing we should check the hours and the minutes for overflow). Another solution is to use the next formulas as the answer: $x=h\\cdot60+m+a,\\ h^{\\prime}=\\left[{\\frac{x}{60}}\\right]\\ m o d\\ 24,m^{\\prime}=x\\ m o d\\ 60$. Complexity: $O(a)$ or $O(1)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nint h, m;\\nint add;\\n\\ninline bool read() {\\n\\tif (scanf(\\\"%d:%d%d\\\", &h, &m, &add) != 3) return false;\\n\\treturn true;\\n}\\n\\ninline void solve() {\\n\\twhile (add) {\\n\\t\\tif (++m == 60) {\\n\\t\\t\\tm = 0;\\n\\t\\t\\tif (++h == 24) h = 0;\\n\\t\\t}\\n\\t\\tadd--;\\n\\t}\\n\\tprintf(\\\"%02d:%02d\\\\n\\\", h, m);\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "622",
    "index": "C",
    "title": "Not Equal on a Segment",
    "statement": "You are given array $a$ with $n$ integers and $m$ queries. The $i$-th query is given with three integers $l_{i}, r_{i}, x_{i}$.\n\nFor the $i$-th query find any position $p_{i}$ ($l_{i} ≤ p_{i} ≤ r_{i}$) so that $a_{pi} ≠ x_{i}$.",
    "tutorial": "This problem can be solved differently. For example you can use some data structures or sqrt-decomposition technique. But it is not required. We expected the following simple solution from the participants. Let's preprocess the following values $p_{i}$ - the position of the first element to the left from the $i$-th element such that $a_{i}  \\neq  a_{pi}$. Now to answer to the query we should check if $a_{r}  \\neq  x$ then we have the answer. Otherwise we should check the position $p_{r}$. Complexity: $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 200200;\\n\\nint n, m;\\nint a[N];\\nint l[N], r[N], x[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> m)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &a[i]) == 1);\\n\\tforn(i, m) {\\n\\t\\tassert(scanf(\\\"%d%d%d\\\", &l[i], &r[i], &x[i]) == 3);\\n\\t\\tl[i]--, r[i]--;\\n\\t}\\n\\treturn true;\\n}\\n\\nint z[N];\\n\\ninline void solve() {\\n\\tz[0] = -1;\\n\\tfore(i, 1, n) {\\n\\t\\tif (a[i - 1] != a[i]) z[i] = i - 1;\\n\\t\\telse z[i] = z[i - 1];\\n\\t}\\n\\n\\tforn(i, m) {\\n\\t\\tif (a[r[i]] != x[i]) printf(\\\"%d\\\\n\\\", r[i] + 1);\\n\\t\\telse if (z[r[i]] >= l[i]) printf(\\\"%d\\\\n\\\", z[r[i]] + 1);\\n\\t\\telse puts(\\\"-1\\\");\\n\\t}\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "622",
    "index": "D",
    "title": "Optimal Number Permutation",
    "statement": "You have array $a$ that contains all integers from $1$ to $n$ twice. You can arbitrary permute any numbers in $a$.\n\nLet number $i$ be in positions $x_{i}, y_{i}$ ($x_{i} < y_{i}$) in the permuted array $a$. Let's define the value $d_{i} = y_{i} - x_{i}$ — the distance between the positions of the number $i$. Permute the numbers in array $a$ to minimize the value of the sum $s=\\sum_{i=1}^{n}(n-i)\\cdot|d_{i}+i-n$.",
    "tutorial": "Let's build the answer with the sum equal to zero. Let $n$ be even. Let's place odd numbers in the first half of the array: the number $1$ in the positions $1$ and $n$, the number $3$ in the positions $2$ and $n - 1$ and so on. Similarly let's place even numbers in the second half: the number $2$ in the position $n + 1$ and $2n - 1$, the number $4$ in the positions $n + 2$ and $2n - 2$ and so on. We can place the number $n$ in the leftover positions. We can build the answer for odd $n$ in a similar way. Easy to see that our construction will give zero sum. Complexity: $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nint n;\\n\\ninline bool read() {\\n\\treturn !!(cin >> n);\\n}\\n\\nconst int N = 1200300;\\n\\nint ans[N];\\n\\ninline void solve() {\\n\\tforn(i, 2 * n) ans[i] = n;\\n\\tfore(i, 1, n) {\\n\\t\\tint x;\\n\\t\\tif (i & 1) x = i >> 1;\\n\\t\\telse x = n - 1 + (i >> 1);\\n\\t\\tint y = x + (n - i);\\n\\t\\tans[x] = ans[y] = i;\\n\\t}\\n\\n\\tforn(i, 2 * n) {\\n\\t\\tif (i) putchar(' ');\\n\\t\\tprintf(\\\"%d\\\", ans[i]);\\n\\t}\\n\\tputs(\\\"\\\");\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "622",
    "index": "E",
    "title": "Ants in Leaves",
    "statement": "Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.\n\nYou are given a tree with $n$ vertices and a root in the vertex $1$. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree.\n\nFind the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree.",
    "tutorial": "Easy to see that the answer is equal to the answer over all sons of the root plus one. Now let's solve the problem independently for each son $v$ of the root. Let $z$ be the array of the depths of all leaves in the subtree of the vertex $v$. Let's sort $z$. Statement 1: it's profitable to lift the leaves in order of their appearing in $z$. Statement 2: denote $a_{x}$ - the time of appearing the $x$-th leaf in the vertex $v$, let's consider the leaves $z_{i}$ and $z_{i + 1}$ then $a_{zi + 1}  \\ge  a_{zi} + 1$. Statement 3: $a_{zi + 1} = max(d_{zi + 1}, a_{zi} + 1)$, where $d_{x}$ is the depth of the $x$-th leaf in the subtree of the vertex $v$. The last statement gives us the solution for the problem: we should simply iterate over $z$ from left to right and recalculate the array $a$ by formula from the third statement. All statements can be easily proved and it's recommended to do by yourself to understand better the idea of the solution. Complexity: $O(nlogn)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 500500;\\n\\nint n;\\nvector<int> g[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n)) return false;\\n\\tforn(i, n) g[i].clear();\\n\\tforn(i, n - 1) {\\n\\t\\tint x, y;\\n\\t\\tassert(scanf(\\\"%d%d\\\", &x, &y) == 2);\\n\\t\\tx--, y--;\\n\\t\\tg[x].pb(y), g[y].pb(x);\\n\\t}\\n\\treturn true;\\n}\\n\\nvector<int> z;\\n\\nvoid dfs(int v, int p, int d) {\\n\\tint c = 0;\\n\\tforn(i, sz(g[v])) {\\n\\t\\tint to = g[v][i];\\n\\t\\tif (to == p) continue;\\n\\t\\tc++;\\n\\t\\tdfs(to, v, d + 1);\\n\\t}\\n\\tif (!c) z.pb(d);\\n}\\n\\nint solve(int v, int p) {\\n\\tz.clear();\\n\\tdfs(v, p, 0);\\n\\tsort(all(z));\\n\\tforn(i, sz(z)) {\\n\\t\\tif (i) z[i] = max(z[i - 1] + 1, z[i]);\\n\\t}\\n\\treturn z.back();\\n}\\n\\ninline void solve() {\\n\\tint ans = 0;\\n\\tforn(i, sz(g[0]))\\n\\t\\tans = max(ans, solve(g[0][i], 0) + 1);\\n\\tcout << ans << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "dfs and similar",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "622",
    "index": "F",
    "title": "The Sum of the k-th Powers",
    "statement": "There are well-known formulas: $\\sum_{i=1}^{n}i=1+2+\\cdot\\cdot\\cdot+n={\\frac{n(n+1)}{2}}$, $\\sum_{i=1}^{n}i^{2}=1^{2}+2^{2}+\\cdot\\cdot\\cdot+n^{2}={\\frac{n(2n+1)(n+1)}{6}}$, $\\sum_{i=1}^{n}i^{3}=1^{3}+2^{3}+\\cdot\\cdot\\cdot+n^{3}=\\left({\\frac{n(n+1)}{2}}\\right)^{2}$. Also mathematicians found similar formulas for higher degrees.\n\nFind the value of the sum $\\sum_{i=1}^{n}i^{k}=1^{k}+2^{k}+\\ldots+n^{k}$ modulo $10^{9} + 7$ (so you should find the remainder after dividing the answer by the value $10^{9} + 7$).",
    "tutorial": "Statement: the function of the sum is a polynomial of degree $k + 1$ over variable $n$. This statement can be proved by induction (to make step you should take the derivative). Denote $P_{x}$ the value of the sum for $n = x$. We can easily calculate the values of $P_{x}$ for $x$ from $0$ to $k + 1$ in $O(klogk)$ time. If $n < k + 2$ then we already have the answer. Otherwise let's use Lagrange polynomial to get the value of the sum for the given value $n$. The Largange polynomial have the following form: $P(x)=\\sum_{i=1}^{n}y_{i}\\prod_{j=1,j\\neq i}^{n}{\\frac{x-x_{j}}{x_{i}-x_{j}}}$. In our case $x_{i} = i - 1$ and $y_{i} = P_{xi}$. To calculate $P(n)$ in a linear time we should use that $x_{i + 1} - x_{i} = x_{j + 1} - x_{j}$ for all $i, j < n$. It's help us because with that property we can recalculate the inner product for $i + 1$ from the inner product for $i$ simply by multiplying by two values and dividing by two values. So we can calculate the sum in linear time over $k$. C++ solution ($logk$ appeared because we should find the inverse element in the field modulo $MOD = 10^{9} + 7$).",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nint n, k;\\n\\ninline bool read() {\\n\\treturn !!(cin >> n >> k);\\n}\\n\\nconst int mod = 1000 * 1000 * 1000 + 7;\\n\\nint gcd(int a, int b, int& x, int& y) {\\n\\tif (!a) {\\n\\t\\tx = 0, y = 1;\\n\\t\\treturn b;\\n\\t}\\n\\tint xx, yy, g = gcd(b % a, a, xx, yy);\\n\\tx = yy - b / a * xx;\\n\\ty = xx;\\n\\treturn g;\\n}\\n\\ninline int normal(int n) {\\n\\tn %= mod;\\n\\t(n < 0) && (n += mod);\\n\\treturn n;\\n}\\n\\ninline int inv(int a) {\\n\\tint x, y;\\n\\tassert(gcd(a, mod, x, y) == 1);\\n\\treturn normal(x);\\n}\\n\\ninline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }\\ninline int sub(int a, int b) { return a - b < 0 ? a - b + mod : a - b; }\\ninline int mul(int a, int b) { return int(a * 1ll * b % mod); }\\ninline int _div(int a, int b) { return mul(a, inv(b)); }\\n\\ninline int binPow(int a, int b) {\\n\\tint ans = 1;\\n\\twhile (b) {\\n\\t\\tif (b & 1) ans = mul(ans, a);\\n\\t\\ta = mul(a, a);\\n\\t\\tb >>= 1;\\n\\t}\\n\\treturn ans;\\n}\\n\\nint calc(const vector<int>& y, int x) {\\n\\tint ans = 0;\\n\\tint k = 1;\\n\\tfore(j, 1, sz(y)) {\\n\\t\\tk = mul(k, normal(x - j));\\n\\t\\tk = _div(k, normal(0 - j));\\n\\t}\\n\\tforn(i, sz(y)) {\\n\\t\\tans = add(ans, mul(y[i], k));\\n\\t\\tif (i + 1 >= sz(y)) break;\\n\\t\\tk = mul(k, _div(normal(x - i), normal(x - (i + 1))));\\n\\t\\tk = mul(k, _div(normal(i - (sz(y) - 1)), normal(i + 1)));\\n\\t}\\n\\treturn ans;\\n}\\n\\ninline int solve() {\\n\\tvector<int> y;\\n\\tint sum = 0;\\n\\ty.pb(sum);\\n\\tforn(i, k + 1) {\\n\\t\\tsum = add(sum, binPow(i + 1, k));\\n\\t\\ty.pb(sum);\\n\\t}\\n\\tif (n < sz(y)) return y[n];\\n\\treturn calc(y, n);\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tcout << solve() << endl;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "623",
    "index": "A",
    "title": "Graph and String",
    "statement": "One day student Vasya was sitting on a lecture and mentioned a string $s_{1}s_{2}... s_{n}$, consisting of letters \"a\", \"b\" and \"c\" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph $G$ with the following properties:\n\n- $G$ has exactly $n$ vertices, numbered from $1$ to $n$.\n- For all pairs of vertices $i$ and $j$, where $i ≠ j$, there is an edge connecting them \\textbf{if and only if} characters $s_{i}$ and $s_{j}$ are either equal or neighbouring in the alphabet. That is, letters in pairs \"a\"-\"b\" and \"b\"-\"c\" are neighbouring, while letters \"a\"-\"c\" are not.\n\nVasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph $G$, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string $s$, such that if Vasya used this $s$ he would produce the given graph $G$.",
    "tutorial": "Note that all vertices \"b\" are connected with all other vertices in the graph. Find all such vertices and mark them as \"b\". Now we need to find any unlabeled vertex $V$, mark it with \"a\" character. Unlabeled vertices connected with $V$ should be also labeled as \"a\". All other vertices we can label as \"c\" Finally we need to check graph validity. Check that all vertices \"a\" are only connected with each other and \"b\" vertices. After that we need to perform a similar check for \"c\" vertices.",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 1800
  },
  {
    "contest_id": "623",
    "index": "B",
    "title": "Array GCD",
    "statement": "You are given array $a_{i}$ of length $n$. You may consecutively apply two operations to this array:\n\n- remove some subsegment (continuous subsequence) of length $m < n$ and pay for it $m·a$ coins;\n- change some elements of the array by at most $1$, and pay $b$ coins for each change.\n\nPlease note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most $1$. Also note, that you are not allowed to delete the whole array.\n\nYour goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than $1$.",
    "tutorial": "At least one of ends ($a_{1}$ or $a_{n}$) is changed by at most 1. It means that if gcd > 1 then it divides on of prime divisors of either $a_{1} - 1$, $a_{1}$, $a_{1} + 1$, $a_{n} - 1$, $a_{n}$ or $a_{n} + 1$. We will iterate over these primes. Suppose prime $p$ is fixed. For each number we know that it's either divisible by $p$ or we can pay $b$ to fix it or it should be in the subarray to change for $a$ We can use dynamic programming dp[number of numbers considered][subarray to change not started/started/finished] = minimal cost Complexity is $O(Nd) = O(Nlog(max(a_{i}))$, where $d$ is the number of primes to check.",
    "tags": [
      "dp",
      "greedy",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "623",
    "index": "C",
    "title": "Electric Charges",
    "statement": "Programmer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals.\n\nA laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: axis $X$ is positive and axis $Y$ is negative.\n\nExperienced laboratory worker marked $n$ points with integer coordinates $(x_{i}, y_{i})$ on the plane and stopped the time. Sasha should use \"atomic tweezers\" to place elementary particles in these points. He has an unlimited number of electrons (negatively charged elementary particles) and protons (positively charged elementary particles). He can put either an electron or a proton at each marked point. As soon as all marked points are filled with particles, laboratory worker will turn on the time again and the particles will come in motion and after some time they will stabilize in equilibrium. The objective of the laboratory work is to arrange the particles in such a way, that the diameter of the resulting state (the maximum distance between the pairs of points of the set) is as small as possible.\n\nSince Sasha is a programmer, he naively thinks that all the particles will simply \"fall\" into their projections on the corresponding axes: electrons will fall on axis $X$, while protons will fall on axis $Y$. As we are programmers too, we will consider the same model as Sasha. That is, a \\textbf{particle gets from point $(x, y)$ to point $(x, 0)$ if it is an electron and to point $(0, y)$ if it is a proton.}\n\nAs the laboratory has high background radiation and Sasha takes care of his laptop, he did not take it with him, and now he can't write a program that computes the minimum possible diameter of the resulting set. Therefore, you will have to do it for him.\n\nPrint a \\textbf{square} of the minimum possible diameter of the set.",
    "tutorial": "First of all consider cases where all points are projected to the same axis. (In that case answer is difference between maximum and minimum of this coordinate). Now consider leftmost and rightmost points among projected to $x$ axis. Let $x_{L}$ and $x_{R}$ are their $x$-coordinates. Notice that points with x-coordinate $x_{L}  \\le  x  \\le  x_{R}$ may also be projected to $x$-axis and that will not increase the diameter. So, if we sort all points by $x$-coordinate, we may suppose that points projected to $x$-axis form a continuous subarray. We will use a binary search. Now we will need to check if it's possible to project point in a such way that diameter is <= M. Let's fix the most distant by $x$-coordinate point from 0 that is projected to $x$-axis. It may be to the left or to the right of 0. This cases are symmetrical and we will consider only the former one. Let $x_{L} < 0$ be its coordinate. Notice that one may project all points such that $0  \\le  x - x_{L}  \\le  M$ and $|x|  \\le  |x_{L}|$ to the $x$ axis (and it'll not affect the diameter) and we have to project other points to $y$-axis. Among all other points we should find the maximum and minimum by $y$ coordinate. Answer is \"yes ($diam  \\le  M$)\" if $y_{max} - y_{min} < = M$ and distance from $(x_{L}, 0)$ to both $(0, y_{max})$ and $(0, y_{min})$ is not greater than M. Let's precalculate maximums and minimums of $y$ coordinates on each prefix and suffix of original (sorted) points array. Now iterate over left border of subarray of points projected to $x$-axis and find the right border using binary search or maintain it using two-pointers technique. So we've got one check in $O(M)$ or $O(M\\log M)$ and entire solution in $O(M\\log C)$ or $O(M\\log M\\log C)$",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "623",
    "index": "D",
    "title": "Birthday",
    "statement": "A MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. $n$ friends came by, and after a typical party they decided to play blind man's buff.\n\nThe birthday boy gets blindfolded and the other players scatter around the house. The game is played in several rounds. In each round, Misha catches exactly one of his friends and has to guess who it is. The probability of catching the $i$-th friend does not change between rounds and is equal to $p_{i}$ percent (as we know, it is directly proportional to the amount of alcohol consumed by the $i$-th friend) and $p_{1} + p_{2} + ... + p_{n} = 100$ holds. Misha has no information about who he caught. After Misha makes an attempt to guess the caught person, the round ends. Even then, Misha isn't told whether he guessed correctly, and a new round begins.\n\nThe game ends when Misha guesses every friend at least once, that is, there exists such set of rounds $k_{1}, k_{2}, ..., k_{n}$, that during round number $k_{i}$ Misha caught the $i$-th friend and guessed him. Misha wants to minimize the expectation of the number of rounds of the game. Despite the fact that at any point in the game Misha has no information about who he has already guessed, his friends are honest, and if they see that the condition for the end of the game is fulfilled, the game ends immediately. Find the expectation of the number of rounds in the game if Misha plays optimally.",
    "tutorial": "Let's denote $q_{i} = 1 - p_{i}$. Main idea: first of all guess each friend once, then maximize probability to end game on current step. Let's simulate first 300000 steps, and calculate $\\textstyle\\sum t\\cdot(P r(t)-P r(t-1))$. $P r(t)=\\prod(1-q_{i}^{k_{i}})$, where $k_{i}$ - how many times we called $i$-th friend ($\\textstyle\\sum k_{i}=\\iota$). Expectation with some precision equals $N\\ast P r(N)-\\sum_{t=1}^{N-1}P r(t)$. So it is enough to prove that: 1) Greedy strategy gives maximum values for all $Pr(t)$. 2) On 300000 step precision error will be less than $10^{ - 6}$. Proof: 1) Suppose, that for some $t$ there exists set $l_{i}$ ($\\textstyle\\sum l_{i}=t$), not equal to set produced by greedy algorithm $k_{i}$, gives the maximum value of $Pr(t)$. Let's take some $k_{a} < l_{a}$ and $k_{b} > l_{b}$, it is easy to prove tgat if we change $l_{b}$ to $l_{b} + 1$, $l_{a}$ to $l_{a} - 1$, then new set of $l_{i}$ gives bigger value of $Pr(t)$, contradiction. 2) $q_{i}  \\le  0.99$. Let's take set $k_{i}={\\frac{t}{10}}$, it gives probability of end of the game not less than optimal. Then $Pr(t)  \\ge  (1 - 0.99^{t / 100})^{100}  \\ge  1 - 100 \\cdot 0.99^{t / 100}$. Precision error does not exceed $\\sum_{t=N+1}^{\\infty}1-P r(t)\\leq100\\cdot\\sum_{t=N+1}^{\\infty}0.99^{t/100}$. It could be estimated as sum of geometric progression. If $N  \\ge  300000$ precision error doesn't exceed $10^{ - 7}$.",
    "tags": [
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "623",
    "index": "E",
    "title": "Transforming Sequence",
    "statement": "Let's define the transformation $P$ of a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ as $b_{1}, b_{2}, ..., b_{n}$, where $b_{i} = a_{1} | a_{2} | ... | a_{i}$ for all $i = 1, 2, ..., n$, where $|$ is the bitwise OR operation.\n\nVasya consequently applies the transformation $P$ to all sequences of length $n$ consisting of integers from $1$ to $2^{k} - 1$ inclusive. He wants to know how many of these sequences have such property that their transformation is a \\textbf{strictly increasing} sequence. Help him to calculate this number modulo $10^{9} + 7$.",
    "tutorial": "First observation is that if the sequence of prefix xors is strictly increasing, than on each step $a_{i}$ has at least one new bit comparing to the previous elements. So, since there are overall $k$ bits, the length of the sequence can't be more than $k$. So, if $n > k$, the answer is 0. Let's firstly solve the task with $O(k^{3})$ complexity. We calculate $dp[n][k]$ - the number of sequences of length $n$ such that $a_{1}|a_{2}|... |a_{n}$ has $k$ bits. The transition is to add a number with $l$ new bits, and choose those $k$ bits which are already in the prefix xor arbitrarily. So, $dp[n + 1][k + l]$ is increased by $dp[n][k] \\cdot 2^{k} \\cdot C_{k + l}^{l}$. The last binomial coefficient complies with the choice these very $l$ bits from $k + l$ which will be present in $a_{1}|a_{2}|... |a_{n + 1}$. Note now that the transition doesn't depend on $n$, so let's try to use the idea of the binary exponentiation. Suppose we want to merge two dynamics $dp_{1}[k], dp_{2}[k]$, where $k$ is the number of bits present in $a_{1}|a_{2}|... |a_{left}$ and $b_{1}|... |b_{right}$ correspondingly. Now we want to obtain $dp[k]$ for arrays of size $left + right$. The formula is: $d p[k]=\\sum_{l=0}^{k}d p![l]\\cdot d p\\gamma[k-l]\\cdot C_{k}^{l}\\cdot2^{l\\cdot r i g h t}.$ Here $l$ corresponds to the bits present in the xor of the left part, and for each number of the right part we can choose these $l$ bits arbitrarily. Rewrite the formula in the following way: $d p[k]=\\sum_{l=0}^{k}\\frac{d p![l]}{l!}\\cdot\\lambda^{l\\cdot r i g h t}\\cdot\\frac{d p2[k-l]}{(k-l)!}\\cdot k!.$ So, we can compute $dp[k]$ for all $k$ having multiplied two polynomials $\\sum_{l=0}^{k}{\\frac{d p[l]}{l!}}\\cdot2^{l.r i g h t}$ and $\\sum_{l=0}^{k}{\\frac{d p[l]}{l!}}$. We can obtain the coefficients of the first polynomial from the coefficients of the second in $O(k\\log k)$. So, we can compute this dynamic programming for all lengths - powers of two, in $O(k\\log k\\log n)$, using the fast Fourier transform. In fact, it is more convenient to compute $\\frac{d p[k]}{k!}$ using the same equation. After that, we can use the same merge strategy to compute the answer for the given $n$, using dynamics for the powers of two. Overall complexity is $O(k\\log k\\log n)$. We decided to ask the answer modulo $10^{9} + 7$ to not let the participants easily guess that these problem requires FFT :) So, in order to get accepted you had to implement one of the methods to deal with the large modulo in polynomial multiplication using FFT. Another approach was to apply Karatsuba algorithm, our realisation timed out on our tests, but jqdai0815 somehow made it pass :)",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "624",
    "index": "A",
    "title": "Save Luke",
    "statement": "Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates $0$ and $L$, and they move towards each other with speed $v_{1}$ and $v_{2}$, respectively. Luke has width $d$ and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive.",
    "tutorial": "Width of free space is decreasing by $v_{1} + v_{2}$ per second. It means that it'll decrease from $L$ to $d$ in $t={\\frac{L-d}{v_{1}+v_{2}}}$ seconds. The moment when width gets a value of $d$ is the last when Luke is alive so $t$ is the answer.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "624",
    "index": "B",
    "title": "Making a String",
    "statement": "You are given an alphabet consisting of $n$ letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:\n\n- the $i$-th letter occurs in the string no more than $a_{i}$ times;\n- the number of occurrences of each letter in the string must be \\textbf{distinct} for all the letters that occurred in the string at least once.",
    "tutorial": "Sort array in descending order. Iterate over all letters, First letter is added $c_{1} = a_{1}$ times, each other letter is added $c_{i} = min(a_{i}, c_{i - 1})$. Don't forget that if some letter is not added at all, then all next letters are not added too.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "625",
    "index": "A",
    "title": "Guest From the Past",
    "statement": "Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.\n\nKolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs $a$ rubles, or in glass liter bottle, that costs $b$ rubles. Also, you may return empty glass bottle and get $c$ ($c < b$) rubles back, but you cannot return plastic bottles.\n\nKolya has $n$ rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help.",
    "tutorial": "If we have at least $b$ money then cost of one glass bottle is $b - c$. This means that if $a  \\le  b - c$ then we don't need to buy glass bottles, only plastic ones, and the answer will be $\\left\\lfloor{\\frac{n}{a}}\\right\\rfloor$. Otherwise we need to buy glass bottles while we can. So, if we have at least $b$ money, then we will buy $\\left\\lfloor{\\frac{n-c}{b-c}}\\right\\rfloor$ glass bottles and then spend rest of the money on plastic ones. This is simple $O(1)$ solution.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "625",
    "index": "B",
    "title": "War of the Corporations",
    "statement": "A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.\n\nThis new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.\n\nPineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with \"#\". As this operation is pretty expensive, you should find the minimum number of characters to replace with \"#\", such that the name of AI doesn't contain the name of the phone as a substring.\n\nSubstring is a continuous subsequence of a string.",
    "tutorial": "Lets find leftmost occurrence of the second word in the first one. We need to add # to remove this occurrence, so where we would like to put it? Instead of the last symbol of this occurrence to remove as many others as we can. After that we will continue this operation after the new # symbol. Simplest implementation of this idea works in $O(|S| \\cdot |T|)$, but with the power of string algorithms (for example, Knuth-Morris-Pratt algorithm) we can do it in $O(|S| + |T|)$ time. Hint/Bug/Feature: in Python language there is already function that does exactly what we need:",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "625",
    "index": "C",
    "title": "K-special Tables",
    "statement": "People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.\n\nAlis is among these collectors. Right now she wants to get one of $k$-special tables. In case you forget, the table $n × n$ is called $k$-special if the following three conditions are satisfied:\n\n- every integer from $1$ to $n^{2}$ appears in the table exactly once;\n- in each row numbers are situated in increasing order;\n- the sum of numbers in the $k$-th column is maximum possible.\n\nYour goal is to help Alice and find at least one $k$-special table of size $n × n$. Both rows and columns are numbered from $1$ to $n$, with rows numbered from top to bottom and columns numbered from left to right.",
    "tutorial": "Lets fill our table row by row greedily. We want to have maximal possible number on k-th place in the first row. After it we need at least $n - k$ numbers greater than ours, so its maximum value is $n^{2} - (n - k)$. If we select it then we are fixing all numbers after column $k$ in the first row from $n^{2} - (n - k)$ to $n^{2}$. On the first $k - 1$ lets put smallest possible numbers $1, 2, ... , k - 1$. If we do the same thing in the second row then in the beginning it will have numbers from $k$ to $2(k - 1)$, and from $k$-th position maximum possible values from $n^{2} - (n - k) - (n - k + 1)$ to $n^{2} - (n - k + 1)$. And so on we will fill all rows. With careful implementation we don't need to store whole matrix and we need only $O(1)$ memory. Our algorithm works in $O(n^{2})$ time.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "625",
    "index": "D",
    "title": "Finals in arithmetic",
    "statement": "Vitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.\n\nLet's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip $123$ the result is the integer $321$, but flipping $130$ we obtain $31$, and by flipping $31$ we come to $13$.\n\nOksana Fillipovna picked some number $a$ without leading zeroes, and flipped it to get number $a_{r}$. Then she summed $a$ and $a_{r}$, and told Vitya the resulting value $n$. His goal is to find any valid $a$.\n\nAs Oksana Fillipovna picked some small integers as $a$ and $a_{r}$, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given $n$ finds any $a$ without leading zeroes, such that $a + a_{r} = n$ or determine that such $a$ doesn't exist.",
    "tutorial": "Lets say that input has length of $n$ digits, then size of answer can be $n$ if we didn't carry 1 to the left out of addition, and $n - 1$ otherwise. Lets fix length $m$ of our answer and denote $i$-th number in the representation as $a_{i}$. Then we know $(a_{1}+a_{m})\\mathrm{~mod~}10$ from the rightmost digit of the sum. Lets figure out what does $(a_{1}+a_{m}){\\mathrm{~div~}}10$ equals to. If the remainder is 9, it means that $(a_{1}+a_{m}){\\mathrm{~div~}}10=0$, because we can't get 19 out of the sum of two digits. Otherwise the result is defined uniquely by the fact that there was carrying 1 in the leftmost digit of the result or not. So after this we know $a_{1} + a_{m}$. It doesn't matter how we divide sum by two digits, because the result will be the same. After this we can uniquely identify the fact of carrying after the first digit of the result and before the last digit. Repeating this $m / 2$ times we will get candidate for the answer. In the end we will have $O(n)$ solution. If you've missed the fact that every step is uniquely defined, then you could've wrote basically the same solution, but with dynamic programming.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "625",
    "index": "E",
    "title": "Frog Fights",
    "statement": "Ostap Bender recently visited frog farm and was inspired to create his own frog game.\n\nNumber of frogs are places on a cyclic gameboard, divided into $m$ cells. Cells are numbered from $1$ to $m$, but the board is cyclic, so cell number $1$ goes right after the cell number $m$ in the direction of movement. $i$-th frog during its turn can jump for $a_{i}$ cells.\n\nFrogs move in turns, game starts with a move by frog $1$. On its turn $i$-th frog moves $a_{i}$ cells forward, knocking out all the frogs on its way. If there is a frog in the last cell of the path of the $i$-th frog, that frog is also knocked out. After this the value $a_{i}$ is decreased by the number of frogs that were knocked out during this turn. If $a_{i}$ is zero or goes negative, then $i$-th frog doesn't make moves anymore.\n\nAfter frog number $1$ finishes its turn, frog number $2$ starts to move, then frog number $3$ and so on. After the frog number $n$ makes its move, frog $1$ starts to move again, then frog $2$ and so on this process goes forever. If some frog was already knocked out from the board, we consider that it skips all its moves.\n\nHelp Ostap to identify, what frogs will stay on the board at the end of a game?",
    "tutorial": "We want to efficiently simulate the process from the problem statement. Lets have a data structure with times of key events that could've happened during simulation (some frog removed other frog from the board). Lets remove earliest event from our data structure and apply it to the board, make a critical jump. After that the speed of the first frog will decrease and we will be forced to recount times of collision of this frog this its 2 neighbors. This data structure could be set from C++, TreeSet from Java or self-written Segment Tree. To quickly find out who are we gonna remove from the board after the jump lets store double-linked list of all frogs sorted by their positions. Technical part is to calculate time of the collision, but it can be easily done with the simple notion of linear movement of two points on a line. There could be at max $n - 1$ collisions, so whole solution will be $O(n\\log n)$.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "626",
    "index": "A",
    "title": "Robot Sequence",
    "statement": "Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of $n$ commands, each either 'U', 'R', 'D', or 'L' — instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.",
    "tutorial": "We can simulate Calvin's path on each substring, and check if he returns to the origin. Runtime: $O(n^{3})$",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "626",
    "index": "B",
    "title": "Cards",
    "statement": "Catherine has a deck of $n$ cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions:\n\n- take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color;\n- take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color.\n\nShe repeats this process until there is only one card left. What are the possible colors for the final card?",
    "tutorial": "Note that if we have exactly one card of each color, we can always make all three options (by symmetry). Thus, if we have at least one of each color, or at least two of each of two colors, we can make all three options. The remaining cases are: if we only have one color, that's the only possible final card; if we have one of each of two colors, we can only make the third color; if we have at least two of one color and exactly one of a second, we can only make the second or third color (e.g. sample 2). Runtime: $O(1)$",
    "tags": [
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "626",
    "index": "C",
    "title": "Block Towers",
    "statement": "Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. $n$ of the students use pieces made of two blocks and $m$ of the students use pieces made of three blocks.\n\nThe students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers.",
    "tutorial": "There are a variety of ways to do this problem. Here is one way: if the answer is $X$, there must be at least $n$ multiples of $2$ below $X$, at least $m$ multiples of $3$ below $X$, and at least $n + m$ multiples of $2$ or $3$ below $X$. These conditions are actually sufficient, so we need to find the smallest $X$ such that $n\\leq\\lfloor{\\frac{X}{2}}\\rfloor$, $m\\leq\\lfloor{\\frac{X}{3}}\\rfloor$, and $n+m\\leq\\lfloor{\\frac{X}{2}}\\rfloor+\\lfloor{\\frac{X}{3}}\\rfloor-\\lfloor{\\frac{X}{6}}\\rfloor$. We can do this with a linear search, or with an explicit formula. Runtime: $O(1)$",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "626",
    "index": "D",
    "title": "Jerry's Protest",
    "statement": "Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing $n$ balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and \\textbf{returns the balls} to the jar. The winner of the game is the one who wins at least two of the three rounds.\n\nAndrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?",
    "tutorial": "We do this algorithm in two phases: first, we compute the probability distribution of the difference between the winner and loser of each round. This takes $O(n^{2})$ time. Then, we can iterate over the 2 differences which Andrew wins by and compute the probability that Jerry has a greater total using with suffix sums. Runtime: $O(n^{2} + a_{max}^{2})$",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "626",
    "index": "E",
    "title": "Simple Skewness",
    "statement": "Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of $n$ (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness.\n\nThe mean of a collection is the average of its elements. The median of a collection is its middle element when all of its elements are sorted, or the average of its two middle elements if it has even size.",
    "tutorial": "We can show that any subset with maximal simple skewness should have odd size (otherwise we drop the larger middle element: this decreases the median by more than it decreases the mean, assuming the mean is larger than the median). Let's fix the median at $x_{i}$ (in the sorted list), and set the size of the set to $2j + 1$. We'd like to maximize the mean, so we can greedily choose the largest $j$ elements below the median and the largest $j$ elements above the median: $x_{i - j}, ..., x_{i - 1}$ and $x_{n - j + 1}, ..., x_{n}$. Now, notice that by increasing $j$ by $1$, we add in the elements $x_{i - j - 1}$ and $x_{n - j}$, which decrease as $j$ increases. Thus, for a fixed $i$, the overall mean is bitonic in $j$ (it increases then decreases), so we can binary search on the marginal utility to find the optimum. Runtime: $O(n\\log(n))$",
    "tags": [
      "binary search",
      "math",
      "ternary search"
    ],
    "rating": 2400
  },
  {
    "contest_id": "626",
    "index": "F",
    "title": "Group Projects",
    "statement": "There are $n$ students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the $i$-th student $a_{i}$ minutes to finish his/her independent piece.\n\nIf students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum $a_{i}$ in the group minus the minimum $a_{i}$ in the group. Note that a group containing a single student has an imbalance of $0$. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most $k$?\n\nTwo divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.",
    "tutorial": "This is a dynamic programming problem. Notice that the total imbalance of the groups only depends on which students are the maximum in each group and which are the minimum in each group. We thus can think of groups as intervals bounded by the minimum and maximum student. Moreover, the total imbalance is the sum over all unit ranges of the number of intervals covering that range. We can use this formula to do our DP. If we sort the students in increasing size, DP state is as follows: the number of students processed so far, the number of $g$ groups which are currently \"open\" (have a minimum but no maximum), and the total imbalance $k$ so far. For each student, we first add the appropriate value to the total imbalance ($g$ times the distance to the previous student), and then either put the student in his own group (doesn't change $g$), start a new group (increment $g$), add the student to one of the $g$ groups (doesn't change $g$), or close one of the $g$ groups (decrement $g$). Runtime: $O(n^{2}k)$",
    "tags": [
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "626",
    "index": "G",
    "title": "Raffles",
    "statement": "Johnny is at a carnival which has $n$ raffles. Raffle $i$ has a prize with value $p_{i}$. Each participant can put tickets in whichever raffles they choose (they may have more than one ticket in a single raffle). At the end of the carnival, one ticket is selected at random from each raffle, and the owner of the ticket wins the associated prize. A single person can win multiple prizes from different raffles.\n\nHowever, county rules prevent any one participant from owning more than half the tickets in a single raffle, i.e. putting more tickets in the raffle than all the other participants combined. To help combat this (and possibly win some prizes), the organizers started by placing a single ticket in each raffle, which they will never remove.\n\nJohnny bought $t$ tickets and is wondering where to place them. Currently, there are a total of $l_{i}$ tickets in the $i$-th raffle. He watches as other participants place tickets and modify their decisions and, at every moment in time, wants to know how much he can possibly earn. Find the maximum possible expected value of Johnny's winnings at each moment if he distributes his tickets optimally. Johnny may redistribute all of his tickets arbitrarily between each update, but he may not place more than $t$ tickets total or have more tickets in a single raffle than all other participants combined.",
    "tutorial": "First, note that the marginal utility of each additional ticket in a single raffle is decreasing. Thus, to solve the initial state, we can use a heap data structure to store the optimal raffles. Now, after each update, we can show that the distribution should not change by much. In particular, after one ticket is added to a raffle, Johnny should either remove one ticket from that raffle and place it elsewhere, not change anything, or, if the raffle was already full, put one more ticket in to keep it full. Similarly, after a ticket is removed, Johnny should either do nothing, remove one ticket to stay under the maximum, or add one ticket. (The proofs are fairly simple and involve looking at the \"cutoff\" marginal utility of Johnny's tickets.) All of these operations can be performed using two heaps storing the optimal ticket to add and the optimal ticket to remove. Runtime: $O((t+q)\\log(n))$",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "627",
    "index": "A",
    "title": "XOR Equation",
    "statement": "Two \\textbf{positive} integers $a$ and $b$ have a sum of $s$ and a bitwise XOR of $x$. How many possible values are there for the ordered pair $(a, b)$?",
    "tutorial": "For any two integers $a$ and $b$, we have $s=a+b=(a\\oplus b)+(a\\aleph b)*2$, where $a\\oplus b$ is the xor and $a&b$ is the bitwise AND. This is because $\\mathbb{C}$ is non-carrying binary addition. Thus, we can find $a&b = (s - x) / 2$ (if this is not an integer, there are no solutions). Now, for each bit, we have $4$ cases: $a_{i}g\\delta_{i}\\in\\{0,1\\}$, and $a_{i}\\oplus b_{i}\\in\\{0,1\\}$. If $a_{i}\\oplus b_{i}=0$, then $a_{i} = b_{i}$, so we have one possibility: $a_{i} = b_{i} = a_{i}&b_{i}$. If $a_{i}\\oplus b_{i}=1$, then we must have $a_{i}&b_{i} = 0$ (otherwise we print $0$), and we have two choices: $a_{i} = 1$ and $b_{i} = 0$ or vice versa. Thus, we can return $2^{n}$, where $n$ is the number of one-bits in $x$. (Remember to subtract $2$ for the cases $a = 0$ or $b = 0$ if necessary.) Runtime: $O(\\log(x))$",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "627",
    "index": "B",
    "title": "Factory Repairs",
    "statement": "A factory produces thimbles in bulk. Typically, it can produce up to $a$ thimbles a day. However, some of the machinery is defective, so it can currently only produce $b$ thimbles each day. The factory intends to choose a $k$-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of $a$ thimbles per day after the $k$ days are complete.\n\nInitially, no orders are pending. The factory receives updates of the form $d_{i}$, $a_{i}$, indicating that $a_{i}$ new orders have been placed for the $d_{i}$-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.\n\nAs orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day $p_{i}$. Help the owner answer his questions.",
    "tutorial": "Using two binary-indexed trees, we can maintain the prefix and suffix sums of the amounts we can produce with maximum production rates of $B$ and $A$, respectively. Then we can just query the binary-indexed trees to find the maximum possible production given the start and end of the repairs. Runtime: $O(q\\log(n))$.",
    "tags": [
      "data structures"
    ],
    "rating": 1700
  },
  {
    "contest_id": "627",
    "index": "C",
    "title": "Package Delivery",
    "statement": "Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point $0$ on a number line, and the district center is located at the point $d$.\n\nJohnny's truck has a gas tank that holds exactly $n$ liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are $m$ gas stations located at various points along the way to the district center. The $i$-th station is located at the point $x_{i}$ on the number line and sells an unlimited amount of fuel at a price of $p_{i}$ dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.",
    "tutorial": "We solve this with a greedy algorithm: for each gas station, we fill our tank to $min(n, d)$ liters of gasoline, where $d$ is the distance to the next gas station with cheaper (or equal) gas. This is optimal, as, if we can make it to a station with cheaper gas without buying expensive gas, we should (and fill up our tank at the cheaper station). Otherwise, all stations within range $n$ are more expensive, so we should buy as much gas as possible right now. Alternatively, if we say that we always \"use\" the gasoline we buy in the order we buy it, then the gasoline used in the $i$th unit must have been purchased within the last $n$ units. Then we can greedily use the cheapest gas within the last $n$ miles. We can maintain this in a queue with range-min-query, which gives us linear runtime (after sorting). Runtime: $O(m\\log(m))$",
    "tags": [
      "data structures",
      "divide and conquer",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "627",
    "index": "D",
    "title": "Preorder Test",
    "statement": "For his computer science class, Jacob builds a model tree with sticks and balls containing $n$ nodes in the shape of a tree. Jacob has spent $a_{i}$ minutes building the $i$-th ball in the tree.\n\nJacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to search his whole tree to determine this; Jacob knows that she will examine the first $k$ nodes in a DFS-order traversal of the tree. She will then assign Jacob a grade equal to the minimum $a_{i}$ she finds among those $k$ nodes.\n\nThough Jacob does not have enough time to rebuild his model, he can choose the root node that his teacher starts from. Furthermore, he can rearrange the list of neighbors of \\textbf{each node} in any order he likes. Help Jacob find the best grade he can get on this assignment.\n\nA DFS-order traversal is an ordering of the nodes of a rooted tree, built by a recursive DFS-procedure initially called on the root of the tree. When called on a given node $v$, the procedure does the following:\n\n- Print $v$.\n- Traverse the list of neighbors of the node $v$ in order and iteratively call DFS-procedure on each one. Do not call DFS-procedure on node $u$ if you came to node $v$ directly from $u$.",
    "tutorial": "We binary search on the answer, so we need to answer queries of the following form: is the a depth-first search traversal such that the first $k$ vertices all have value at least $v$? We can answer this with a greedy tree-DP: for each subtree, we compute whether or not all its vertices have value at least $v$, and if not, the longest possible prefix with all values at least $v$. Then, our transition function can be greedy: the maximum possible prefix with all values at least $v$ is the sum of the sizes of all child subtrees which are all at least $v$ plus the largest prefix of all child subtrees. Runtime: $O(n\\log(n))$",
    "tags": [
      "binary search",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "627",
    "index": "E",
    "title": "Orchestra",
    "statement": "Paul is at the orchestra. The string section is arranged in an $r × c$ rectangular grid and is filled with violinists with the exception of $n$ violists. Paul really likes violas, so he would like to take a picture including at least $k$ of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.\n\nTwo pictures are considered to be different if the coordinates of corresponding rectangles are different.",
    "tutorial": "We can think of a rectangle in the grid as a pair of an $(xlo, xhi)$ interval and a $(ylo, yhi)$ interval. Suppose we fix the $x$-interval and want to determine the number of corresponding $y$ intervals which create rectangles containing at least $k$ violists. Given a sorted list of the $y$-coordinates of all violists in the range, this is simple: $m$ violists split the $y$-coordinates into $m + 1$ (possibly empty) intervals that span all the columns, and the number of total intervals that work is simply the number of pairs of points that are at least $k$ intervals apart. As we sweep over the $xhi$ coordinate and maintain the list of violists, we want to insert each violist into a sorted list and look at its $k$ nearest neighbors to determine the change in number of intervals. Inserting violists into a sorted list, however, is difficult to do in constant time. Instead, we sweep in reverse. Start with $xhi = r$ and a linked list containing all the desired violists; decrementing $xhi$ is now a simple process of removing the necessary elements from a linked list and examining their neighbors as we do so. Runtime: $O(r^{2}k + rnk)$",
    "tags": [
      "two pointers"
    ],
    "rating": 3000
  },
  {
    "contest_id": "627",
    "index": "F",
    "title": "Island Puzzle",
    "statement": "A remote island chain contains $n$ islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of $n - 1$ bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.\n\nThe islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.\n\nIt is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position.",
    "tutorial": "First, if we never move the empty pedestal through any cycle, then moving the empty pedestal to and from any given position cannot change the location of the statues, as performing a move in the opposite direction as the previous undoes the previous move. Thus, in our graph with one cycle, we can only do the following two operations: move the empty pedestal from one location to another (without loss of generality, only using the original tree), and cyclically permute the elements along the one cycle (except the element closest to the root). Now, to check satisfiability, we can greedily first move the empty pedestal from its start position to its end position -- since this procedure can be undone, it will never change the satisfiability of the rearrangement. Then, we only have to check that all changed elements lie on a possible cycle. This uniquely determines the edge to be added. To compute the minimum number of moves, we compute the minimum moves to move the empty pedestal from the start to the cycle, the minimum moves to permute the cycle as desired, and the minimum moves from the cycle to the end point. Runtime: $O(n)$",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "628",
    "index": "A",
    "title": "Tennis Tournament",
    "statement": "A tennis tournament with $n$ participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.\n\nThe tournament takes place in the following way (below, $m$ is the number of the participants of the current round):\n\n- let $k$ be the maximal power of the number $2$ such that $k ≤ m$,\n- $k$ participants compete in the current round and a half of them passes to the next round, the other $m - k$ participants pass to the next round directly,\n- when only one participant remains, the tournament finishes.\n\nEach match requires $b$ bottles of water for each participant and one bottle for the judge. Besides $p$ towels are given to each participant for the whole tournament.\n\nFind the number of bottles and towels needed for the tournament.\n\nNote that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose).",
    "tutorial": "Here you can simply model the process. Or you can note that after each match some player drops out. In total $n - 1$ players will drop out. So the first answer is $(n - 1) * (2b + 1)$. Obviously the second answer is $np$. Complexity: $O(log^{2}n)$, $O(logn)$ or $O(1)$ depends on the realization.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nint n, b, p;\\n\\ninline bool read() {\\n\\treturn !!(cin >> n >> b >> p);\\n}\\n\\ninline void solve() {\\n\\tint x = 0, y = n * p;\\n\\twhile (n > 1) {\\n\\t\\tint k = 1;\\n\\t\\twhile (k * 2 <= n) k *= 2;\\n\\t\\tx += (k / 2) * (2 * b + 1);\\n\\t\\tn -= k / 2;\\n\\t}\\n\\tcout << x << ' ' << y << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "628",
    "index": "B",
    "title": "New Skateboard",
    "statement": "Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by $4$.\n\nYou are given a string $s$ consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by $4$. A substring can start with a zero.\n\nA substring of a string is a nonempty sequence of consecutive characters.\n\nFor example if string $s$ is 124 then we have four substrings that are divisible by $4$: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.\n\nAs input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.",
    "tutorial": "The key observation is that the number is divisible by $4$ if and only if its last two digits forms a number divisible by $4$. So to calculate the answer at first we should count the substrings of length one. Now let's consider pairs of consecutive digits. If they forms a two digit number that is divisible by $4$ we should increase the answer by the index of the right one. Complexity: $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nstring s;\\n\\ninline bool read() {\\n\\treturn !!getline(cin, s);\\n}\\n\\ninline void solve() {\\n\\tli ans = 0;\\n\\tforn(i, sz(s)) {\\n\\t\\tint d = int(s[i] - '0');\\n\\t\\tif (d % 4 == 0) ans++;\\n\\t\\tif (i) {\\n\\t\\t\\tint pd = int(s[i - 1] - '0');\\n\\t\\t\\tif ((pd * 10 + d) % 4 == 0)\\n\\t\\t\\t\\tans += i;\\n\\t\\t}\\n\\t}\\n\\tcout << ans << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "dp"
    ],
    "rating": 1300
  },
  {
    "contest_id": "628",
    "index": "C",
    "title": "Bear and String Distance",
    "statement": "Limak is a little polar bear. He likes \\textbf{nice} strings — strings of length $n$, consisting of lowercase English letters only.\n\nThe distance between two letters is defined as the difference between their positions in the alphabet. For example, $\\operatorname{dist}(\\mathbf{c},\\mathbf{e})=\\operatorname{dist}(\\mathbf{e},\\mathbf{c})=2$, and $\\operatorname{dist}(\\mathbf{a},\\mathbf{z})=\\operatorname{dist}(\\mathbf{z},\\ \\mathbf{a})=25$.\n\nAlso, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, $\\operatorname{dist}(\\operatorname{af.\\;db})=\\operatorname{dist}(\\operatorname{a.\\;d})+\\operatorname{dist}(\\mathbf{f},\\,\\mathbf{b})=3+4=7$, and $\\mathrm{dist(bear.\\roar)}=16+10+0+0=26$.\n\nLimak gives you a nice string $s$ and an integer $k$. He challenges you to find any nice string $s'$ that $\\operatorname{dist}(\\mathbf{s},\\mathbf{s}^{\\prime})=k$. Find any $s'$ satisfying the given conditions, or print \"-1\" if it's impossible to do so.\n\nAs input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.",
    "tutorial": "There is no solution if the given required distance is too big. Let's think what is the maximum possible distance for the given string $s$. Or the more useful thing - how to construct a string $s'$ to maximize the distance? We can treat each letter separately and replace it with the most distant letter. For example, we should replace 'c' with 'z', and we should replace 'y' with 'a'. To be more precise, for first 13 letters of the alphabet the most distant letter is 'z', and for other letters it is 'a'. Let's solve a problem now. We can iterate over letters and greedily change them. A word \"greedily\" means when changing a letter we don't care about the next letters. We generally want to choose distant letters, because we may not find a solution otherwise. For each letter $s_{i}$ we change it into the most distant letter, unless the total distance would be too big. As we change letters, we should decrease the remaining required distance. So, for each letter $s_{i}$ consider only letters not exceeding the remaining distance, and among them choose the most distant one. If you don't see how to implement it, refer to my C++ solution with comments. Complexity: $O(n)$.",
    "code": "\"// Bear and String Distance, by Errichto\\n#include<bits/stdc++.h>\\nusing namespace std;\\n\\nconst int nax = 1e6 + 5;\\nchar s[nax];\\n\\nint main() {\\n\\tint n, k;\\n\\tscanf(\\\"%d%d\\\", &n, &k);\\n\\tscanf(\\\"%s\\\", s);\\n\\tfor(int i = 0; i < n; ++i) {\\n\\t\\t// we want to change s[i]\\n\\t\\tchar best_letter = s[i]; // by default we don't change it at all\\n\\t\\tint best_distance = 0;\\n\\t\\tfor(char maybe = 'a'; maybe <= 'z'; ++maybe) {\\n\\t\\t\\tint distance = abs(maybe - s[i]);\\n\\t\\t\\t// we must check if \\\"distance <= k\\\" because we don't want to exceed the total distance\\n\\t\\t\\t// among letters with \\\"distance <= k\\\" we choose the most distant one\\n\\t\\t\\tif(distance <= k && distance > best_distance) {\\n\\t\\t\\t\\tbest_distance = distance;\\n\\t\\t\\t\\tbest_letter = maybe;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tk -= best_distance; // we decrease the remaining distance\\n\\t\\ts[i] = best_letter;\\n\\t}\\n\\tassert(k >= 0);\\n\\t// we found a correct s' only if \\\"k == 0\\\"\\n\\tif(k > 0) puts(\\\"-1\\\");\\n\\telse printf(\\\"%s\\\\n\\\", s);\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "628",
    "index": "D",
    "title": "Magic Numbers",
    "statement": "Consider the decimal presentation of an integer. Let's call a number d-magic if digit $d$ appears in decimal presentation of the number on even positions and nowhere else.\n\nFor example, the numbers $1727374$, $17$, $1$ are 7-magic but $77$, $7$, $123$, $34$, $71$ are not 7-magic. On the other hand the number $7$ is 0-magic, $123$ is 2-magic, $34$ is 4-magic and $71$ is 1-magic.\n\nFind the number of d-magic numbers in the segment $[a, b]$ that are multiple of $m$. Because the answer can be very huge you should only find its value modulo $10^{9} + 7$ (so you should find the remainder after dividing by $10^{9} + 7$).",
    "tutorial": "Denote the answer to the problem $f(a, b)$. Note that $f(a, b) = f(0, b) - f(0, a - 1)$ or what is the same $f(a, b) = f(0, b) - f(0, a) + g(a)$, where $g(a)$ equals to one if $a$ is a magic number, otherwise $g(a)$ equals to zero. Let's solve the problem for the segment $[0, n]$. Here is described the standard technique for this kind of problems, sometimes it is called 'dynamic programming by digits'. It can be realized in a two ways. The first way is to iterate over the length of the common prefix with number $n$. Next digit should be less than corresponding digit in $n$ and other digits can be arbitrary. Below is the description of the second approach. Let $z_{ijk}$ be the number of magic prefixes of length $i$ with remainder $j$ modulo $m$. If $k = 0$ than the prefix should be less than the corresponding prefix in $n$ and if $k = 1$ than the prefix should be equal to the prefix of $n$ (it can not be greater). Let's do 'forward dynamic programming'. Let's iterate over digit $p={\\overline{{0,9}}}$ in position $i$. We should check that if the position is even than $p$ should be equal to $d$, otherwise it cannot be equal to $d$. Also we should check for $k = 1$ $p$ should be not greater than corresponding digit in $n$. Now let's see what will be the next state. Of course $i' = i + 1$. By Horner scheme $j' = (10j + p) mod m$. Easy to see that $k^{\\prime}=l\\wedge[p=n_{i}]$. To update the next state we should increase it: $z_{i'j'k'} + = z_{ijk}$. Of course all calculations should be done modulo $10^{9} + 7$. Complexity: $O(nm)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define ford(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nint m, d;\\nstring a, b;\\n\\ninline bool read() {\\n\\tif (!(cin >> m >> d)) return false;\\n\\tassert(cin >> a >> b);\\n\\treturn true;\\n}\\n\\nconst int mod = 1000 * 1000 * 1000 + 7;\\n\\ninline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }\\ninline void inc(int& a, int b) { a = add(a, b); }\\ninline int sub(int a, int b) { return a - b < 0 ? a - b + mod : a - b; }\\ninline void dec(int& a, int b) { a = sub(a, b); }\\n\\nconst int N = 2020;\\n\\nint z[N][N][2];\\n\\nint solve(string s) {\\n\\tint n = sz(s);\\n\\tforn(i, n + 1) forn(j, m) forn(k, 2) z[i][j][k] = 0;\\n\\tz[0][0][1] = 1;\\n\\tforn(i, n)\\n\\t\\tforn(j, m)\\n\\t\\t\\tforn(k, 2)\\n\\t\\t\\t\\tfor (int p = 0; p <= (k ? int(s[i] - '0') : 9); p++) {\\n\\t\\t\\t\\t\\tif ((i & 1) && p != d) continue;\\n\\t\\t\\t\\t\\tif (!(i & 1) && p == d) continue;\\n\\t\\t\\t\\t\\tif (!i && !p) continue;\\n\\t\\t\\t\\t\\tint ni = i + 1;\\n\\t\\t\\t\\t\\tint nj = (j * 10 + p) % m;\\n\\t\\t\\t\\t\\tint nk = k && (p == int(s[i] - '0'));\\n\\t\\t\\t\\t\\tinc(z[ni][nj][nk], z[i][j][k]);\\n\\t\\t\\t\\t}\\n\\tint ans = 0;\\n\\tforn(k, 2) inc(ans, z[n][0][k]);\\n\\treturn ans;\\n}\\n\\nbool good(string s) {\\n\\tint rm = 0;\\n\\tforn(i, sz(s)) {\\n\\t\\tint p = int(s[i] - '0');\\n\\t\\tif ((i & 1) && p != d) return false;\\n\\t\\tif (!(i & 1) && p == d) return false;\\n\\t\\trm = (rm * 10 + p) % m;\\n\\t}\\n\\treturn !rm;\\n}\\n\\ninline void solve() {\\n\\tint ans = 0;\\n\\tinc(ans, solve(b));\\n\\tdec(ans, solve(a));\\n\\tinc(ans, good(a));\\n\\tcout << ans << endl;\\n}\\n\\ninline ld gett() { return ld(clock()) / CLOCKS_PER_SEC; }\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tld stime = gett();\\n\\t\\tsolve();\\n\\t\\tcerr << gett() - stime << endl;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "628",
    "index": "E",
    "title": "Zbazi in Zeydabad",
    "statement": "A tourist wants to visit country Zeydabad for Zbazi (a local game in Zeydabad).\n\nThe country Zeydabad is a rectangular table consisting of $n$ rows and $m$ columns. Each cell on the country is either 'z' or '.'.\n\nThe tourist knows this country is named Zeydabad because there are lots of ''Z-pattern\"s in the country. A ''Z-pattern\" is a square which anti-diagonal is completely filled with 'z' and its upper and lower rows are also completely filled with 'z'. All other cells of a square can be arbitrary.\n\nNote that a ''Z-pattern\" can consist of only one cell (see the examples).\n\nSo he wants to count the number of ''Z-pattern\"s in the country (a necessary skill for Zbazi).\n\nNow your task is to help tourist with counting number of ''Z-pattern\"s.\n\nAs input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.",
    "tutorial": "The problem was suggested by Ali Ahmadi Kuzey. Let's precalculate the values $zl_{ij}, zr_{ij}, zld_{ij}$ - the maximal number of letters 'z' to the left, to the right and to the left-down from the position $(i, j)$. It's easy to do in $O(nm)$ time. Let's fix some cell $(i, j)$. Consider the value $c = min(zl_{ij}, zld_{ij})$. It's the maximum size of the square with upper right ceil in $(i, j)$. But the number of z-patterns can be less than $c$. Consider some cell $(x, y)$ diagonally down-left from $(i, j)$ on the distance no more than $c$. The cells $(i, j)$ and $(x, y)$ forms z-pattern if $y + zr_{xy} > j$. Let's maintain some data structure for each antidiagonal (it can be described by formula $x + y$) that can increment in a point and take the sum on a segment (Fenwick tree will be the best choice for that). Let's iterate over columns $j$ from the right to the left and process the events: we have some cell $(x, y)$ for which $y + zr_{xy} - 1 = j$. In that case we should increment the position $y$ in the tree number $x + y$ by one. Now we should iterate over the cells $(x, y)$ in the current column and add to the answer the value of the sum on the segment from $j - c + 1$ to $j$ in the tree number $i + j$ . Complexity: $O(nmlogm)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 3030;\\n\\nint n, m;\\nchar a[N][N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> m)) return false;\\n\\tassert(gets(a[0]));\\n\\tforn(i, n) assert(gets(a[i]));\\n\\treturn true;\\n}\\n\\ninline void inc(int* t, int i, int v) {\\n\\tfor ( ; i < m; i |= i + 1) t[i] += v;\\n}\\ninline int sum(int* t, int i) {\\n\\tint ans = 0;\\n\\tfor ( ; i >= 0; i = (i & (i + 1)) - 1)\\n\\t\\tans += t[i];\\n\\treturn ans;\\n}\\ninline int sum(int* t, int i, int j) { return sum(t, j) - sum(t, i - 1); }\\n\\nint zl[N][N], zld[N][N], zr[N][N];\\nint t[2 * N][N];\\nvector<pt> ev[N];\\n\\ninline void solve() {\\n\\tnfor(i, n)\\n\\t\\tforn(j, m)\\n\\t\\t\\tif (a[i][j] == '.')\\n\\t\\t\\t\\tzl[i][j] = zld[i][j] = 0;\\n\\t\\t\\telse {\\n\\t\\t\\t\\tzl[i][j] = zld[i][j] = 1;\\n\\t\\t\\t\\tif (j > 0) zl[i][j] += zl[i][j - 1];\\n\\t\\t\\t\\tif (j > 0 && i + 1 < n) zld[i][j] += zld[i + 1][j - 1];\\n\\t\\t\\t}\\n\\n\\tforn(i, n)\\n\\t\\tnfor(j, m)\\n\\t\\t\\tif (a[i][j] == '.')\\n\\t\\t\\t\\tzr[i][j] = 0;\\n\\t\\t\\telse {\\n\\t\\t\\t\\tzr[i][j] = 1;\\n\\t\\t\\t\\tif (j + 1 < m) zr[i][j] += zr[i][j + 1];\\n\\t\\t\\t}\\n\\n\\tforn(j, m) ev[j].clear();\\n\\tforn(i, n) forn(j, m) if (zr[i][j]) ev[j + zr[i][j] - 1].pb(pt(i, j));\\n\\n\\tforn(i, n + m) forn(j, m) t[i][j] = 0;\\n\\n\\tli ans = 0;\\n\\tnfor(j, m) {\\n\\t\\tforn(i, sz(ev[j])) {\\n\\t\\t\\tint x = ev[j][i].x;\\n\\t\\t\\tint y = ev[j][i].y;\\n\\t\\t\\tinc(t[x + y], y, +1);\\n\\t\\t}\\n\\t\\tforn(i, n) {\\n\\t\\t\\tint c = min(zl[i][j], zld[i][j]);\\n\\t\\t\\tif (!c) continue;\\n\\t\\t\\tans += sum(t[i + j], j - c + 1, j);\\n\\t\\t}\\n\\t}\\n\\tcout << ans << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tsolve();\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "628",
    "index": "F",
    "title": "Bear and Fair Set",
    "statement": "Limak is a grizzly bear. He is big and dreadful. You were chilling in the forest when you suddenly met him. It's very unfortunate for you. He will eat all your cookies unless you can demonstrate your mathematical skills. To test you, Limak is going to give you a puzzle to solve.\n\nIt's a well-known fact that Limak, as every bear, owns a set of numbers. You know some information about the set:\n\n- The elements of the set are distinct positive integers.\n- The number of elements in the set is $n$. The number $n$ is divisible by $5$.\n- All elements are between $1$ and $b$, inclusive: bears don't know numbers greater than $b$.\n- For each $r$ in ${0, 1, 2, 3, 4}$, the set contains exactly $\\begin{array}{l}{{\\frac{n}{5}}}\\end{array}$ elements that give remainder $r$ when divided by $5$. (That is, there are $\\begin{array}{l}{{\\frac{n}{5}}}\\end{array}$ elements divisible by $5$, $\\begin{array}{l}{{\\frac{n}{5}}}\\end{array}$ elements of the form $5k + 1$, $\\begin{array}{l}{{\\frac{n}{5}}}\\end{array}$ elements of the form $5k + 2$, and so on.)\n\nLimak smiles mysteriously and gives you $q$ hints about his set. The $i$-th hint is the following sentence: \"If you only look at elements that are between $1$ and $upTo_{i}$, inclusive, you will find exactly $quantity_{i}$ such elements in my set.\"\n\nIn a moment Limak will tell you the actual puzzle, but something doesn't seem right... That smile was very strange. You start to think about a possible reason. Maybe Limak cheated you? Or is he a fair grizzly bear?\n\nGiven $n$, $b$, $q$ and hints, check whether Limak can be fair, i.e. there exists at least one set satisfying the given conditions. If it's possible then print ''fair\". Otherwise, print ''unfair\".",
    "tutorial": "At the beginning, to make things simpler, we should add a query (hint) with $upTo = b, quantity = n$, and then sort queries by $upTo$. Sorted queries (hints) divide interval $[1, b]$ into $q$ disjoint intervals. For each interval we know how many elements should be there. Let's build a graph and find a max flow there. The answer is \"YES\" only if the flow is $n$. Each vertex from $A$ should be connected with the source by an edge with capacity $n / 5$. Each vertex from $B$ should be connected with the sink by an edge with capacity equal to the size of the interval. Between each vertex $x$ from $A$ and $y$ from $B$ should be an edge with capacity equal to the number of numbers in the interval $y$, giving remainder $x$ when divided by $5$. You can also use see that it's similar to finding matching. In fact, we can use the Hall's marriage theorem. For each of $2^{5}$ sets of vertices from $A$ (sets of remainders) iterate over intervals and count how many numbers we can take from $[1, b]$ with remainders from the fixed set of remainders. Complexity: $O(2^{C}n)$. In our problem $C = 5$.",
    "code": "\"// Bear and Fair Set, by Errichto\\n#include<bits/stdc++.h>\\nusing namespace std;\\n\\nconst int K = 5;\\n\\nvoid NO() {\\n\\tputs(\\\"unfair\\\");\\n\\texit(0);\\n}\\n\\nint main() {\\n\\tint n, b, q;\\n\\tscanf(\\\"%d%d%d\\\", &n, &b, &q);\\n\\tvector<pair<int,int>> w;\\n\\tw.push_back(make_pair(b, n));\\n\\twhile(q--) {\\n\\t\\tint a, b;\\n\\t\\tscanf(\\\"%d%d\\\", &a, &b);\\n\\t\\tw.push_back(make_pair(a, b));\\n\\t}\\n\\tsort(w.begin(), w.end());\\n\\t// use the Hall's theorem\\n\\t// check all 2^K sets of remainders\\n\\tfor(int mask = 0; mask < (1 << K); ++mask) {\\n\\t\\tint at_least = 0, at_most = 0;\\n\\t\\t\\n\\t\\tint prev_upto = 0, prev_quan = 0;\\n\\t\\tfor(pair<int,int> query : w) {\\n\\t\\t\\tint now_upto = query.first, now_quan = query.second;\\n\\t\\t\\tint places_matching = 0; // how many do give remainder from \\\"mask\\\"\\n\\t\\t\\tint places_other = 0;\\n\\t\\t\\tfor(int i = prev_upto + 1; i <= now_upto; ++i) {\\n\\t\\t\\t\\tif(mask & (1 << (i % K)))\\n\\t\\t\\t\\t\\t++places_matching;\\n\\t\\t\\t\\telse\\n\\t\\t\\t\\t\\t++places_other;\\n\\t\\t\\t}\\n\\t\\t\\tif(now_quan < prev_quan) NO();\\n\\t\\t\\tint quan = now_quan - prev_quan;\\n\\t\\t\\tint places_total = now_upto - prev_upto;\\n\\t\\t\\tassert(places_total == places_matching + places_other);\\n\\t\\t\\tif(quan > places_total) NO();\\n\\t\\t\\t\\n\\t\\t\\tat_least += max(0, quan - places_other);\\n\\t\\t\\tat_most += min(quan, places_matching);\\n\\t\\t\\t\\n\\t\\t\\tprev_upto = now_upto;\\n\\t\\t\\tprev_quan = now_quan;\\n\\t\\t}\\n\\t\\t\\n\\t\\t// \\\"mask\\\" represents a set of popcount(mask) remainders\\n\\t\\t// their total degree is (n/K)*popcount(mask)\\n\\t\\tint must_be = n / K * __builtin_popcount(mask);\\n\\t\\tif(!(at_least <= must_be && must_be <= at_most)) NO();\\n\\t}\\n\\tputs(\\\"fair\\\");\\t\\t\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "629",
    "index": "A",
    "title": "Far Relative’s Birthday Cake",
    "statement": "Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!\n\nThe cake is a $n × n$ square consisting of equal squares with side length $1$. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?\n\nPlease, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.",
    "tutorial": "Consider that we have $row_{i}$ chocolates in the $i'th$ row and $col_{i}$ chocolates in the $i'th$ column. The answer to the problem would be: $\\sum_{i=1}^{n}{\\binom{r o w_{i}}{2}}+{\\binom{c o l_{i}}{2}}$. It is obvious that every pair would be calculated exactly once (as we have no more than one chocolate in the same square) Time Complexity: $O(n^{2})$",
    "code": "// TODO : Choose an Appropriate Name!!\n// We're not here because we're free. We're here because we are not free.\n//\t\t\t\t\t\t\t\t\t\t\t   The Matrix Reloaded (2003)\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MohammadAmin main()\n#define mpair make_pair\n#define endl \"\n\"\n#define c_false ios_base::sync_with_stdio(false); cin.tie(0)\n#define pushb push_back\n#define pushf push_front\n#define popb pop_back\n#define popf pop_front\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n#define X first\n#define Y second\n#define ashar(a) cout << fixed << setprecision((a))\n#define reset(a,b) memset(a, b, sizeof(a))\n#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)\n#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pdd;\n\nconst int INF = 0x3f3f3f3f, MOD = 1e9 + 7;\nconst int n_ = 1e5 + 1000;\nll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );}\nll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;}\nll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;}\n\nint n, col[200], row[200], ans;\nstring s[200];\n\nint C(int n) {\n\treturn n * (n-1) / 2;\n}\n\nint MohammadAmin {\n\tc_false;\n\tcin >> n;\n\tfor(int i = 0; i < n; i++) {\n\t\tcin >> s[i];\n\t\tfor(int j = 0; j < n; j++) {\n\t\t\trow[i] += s[i][j] == 'C';\n\t\t\tcol[j] += s[i][j] == 'C';\n\t\t}\n\t}\n\tfor(int i = 0; i < n; i++) {\n\t\tans += C(row[i]) + C(col[i]);\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "629",
    "index": "B",
    "title": "Far Relative’s Problem",
    "statement": "Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has $n$ friends and each of them can come to the party in a specific range of days of the year from $a_{i}$ to $b_{i}$. Of course, Famil Door wants to have as many friends celebrating together with him as possible.\n\nFar cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.\n\nFamil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.",
    "tutorial": "Consider that we have $boy_{i}$ males in the $i'th$ day of the year and $girl_{i}$ females in the $i'th$ day of the year. These arrays can be filled easily when you are reading the input (See the code). Then for the $i'th$ day of the year, we could have $2$ * $min$($boy_{i}$ , $girl_{i}$) people which could come to the party. The answer would be maximum of this value between all days $i$ ($1  \\le  i  \\le  366$) Time Complexity: $O$($366$*$n$)",
    "code": "// TODO : Choose an Appropriate Name!!\n// We're not here because we're free. We're here because we are not free.\n//\t\t\t\t\t\t\t\t\t\t\t   The Matrix Reloaded (2003)\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MohammadAmin main()\n#define mpair make_pair\n#define endl \"\n\"\n#define c_false ios_base::sync_with_stdio(false); cin.tie(0)\n#define pushb push_back\n#define pushf push_front\n#define popb pop_back\n#define popf pop_front\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n#define X first\n#define Y second\n#define ashar(a) cout << fixed << setprecision((a))\n#define reset(a,b) memset(a, b, sizeof(a))\n#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)\n#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pdd;\n\nconst int INF = 0x3f3f3f3f, MOD = 1e9 + 7;\nconst int n_ = 1e5 + 1000, days = 366 + 100;\nll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );}\nll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;}\nll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;}\n\nint n, a[n_], b[n_], girl[days], boy[days], ans = 0, day = 1;\nchar s[n_];\n\nint MohammadAmin {\n\tc_false;\n\tcin >> n;\n\tfor(int i = 0; i < n; i++) {\n\t\tcin >> s[i] >> a[i] >> b[i];\n\t\tfor(int d = a[i]; d <= b[i]; d++) {\n\t\t\tif (s[i] == 'M') boy[d]++;\n\t\t\telse girl[d]++;\n\t\t}\n\t}\n\tfor(int i = 1; i < days; i++) {\n\t\tif (ans < 2 * min(boy[i], girl[i])) {\n\t\t\tans = 2 * min(boy[i], girl[i]);\n\t\t\tday = i;\n\t\t}\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1100
  },
  {
    "contest_id": "629",
    "index": "C",
    "title": "Famil Door and Brackets",
    "statement": "As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length $n$ more than any other strings!\n\nThe sequence of round brackets is called valid if and only if:\n\n- the total number of opening brackets is equal to the total number of closing brackets;\n- for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets.\n\nGabi bought a string $s$ of length $m$ ($m ≤ n$) and want to complete it to obtain a valid sequence of brackets of length $n$. He is going to pick some strings $p$ and $q$ consisting of round brackets and merge them in a string $p + s + q$, that is add the string $p$ at the beginning of the string $s$ and string $q$ at the end of the string $s$.\n\nNow he wonders, how many \\textbf{pairs} of strings $p$ and $q$ exists, such that the string $p + s + q$ is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo $10^{9} + 7$.",
    "tutorial": "This problem can be solved with dynamic programming: $1$. Calculate $dp_{i, j}$ : How many sequences of brackets of length $i$ has balance $j$ and intermediate balance never goes below zero (They form a prefix of a valid sequence of brackets). $2$. For the given sequence of length $n$ calculate the resulting balance $a$ and the minimum balance $b$. $3$. Try the length of the sequence added at the beginning $c$ and its balance $d$. If $- b  \\le  d$ then add $dp_{c, d}  \\times  dp_{m - n - c, d + a}$ to the answer. Time complexity: $O((n - m)^{2})$",
    "code": "// TODO : Choose an Appropriate Name!!\n// We're not here because we're free. We're here because we are not free.\n//\t\t\t\t\t\t\t\t\t\t\t   The Matrix Reloaded (2003)\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MohammadAmin main()\n#define mpair make_pair\n#define endl \"\n\"\n#define c_false ios_base::sync_with_stdio(false); cin.tie(0)\n#define pushb push_back\n#define pushf push_front\n#define popb pop_back\n#define popf pop_front\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n#define X first\n#define Y second\n#define ashar(a) cout << fixed << setprecision((a))\n#define reset(a,b) memset(a, b, sizeof(a))\n#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)\n#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pdd;\n\nconst int INF = 0x3f3f3f3f, MOD = 1e9 + 7;\nconst int n_ = 5000;\nll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );}\nll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;}\nll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;}\n\nll n, m, dp[n_][n_], ans;\nint minB, b;\nstring s;\n\nint MohammadAmin {\n\tc_false;\n\tcin >> n >> m;\n\tcin >> s;\n\tdp[0][0] = 1;\n\tfor(int i = 1; i <= n-m; i++) {\n\t\tdp[i][0] = dp[i-1][1];\n\t\tfor(int j =1; j <= i; j++) {\n\t\t\tdp[i][j] = dp[i-1][j+1] + dp[i-1][j-1];\n\t\t\tdp[i][j] %= MOD;\n\t\t}\n\t}\n\tfor(int i = 0; i < m; i++) {\n\t\tif (s[i] == '(') b++;\n\t\telse b--;\n\t\tminB = min(b, minB);\n\t}\n\tfor(int c = 0; c <= n-m; c++) {\n\t\tfor(int d = 0; d <= c; d++) {\n\t\t\tif (d >= -minB) {\n\t\t\t\tif (d + b <= n-m && d + b >= 0) ans += dp[c][d] * dp[n - m - c][d + b] % MOD;\n\t\t\t\tans %= MOD;\n\t\t\t}\n\t\t}\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "629",
    "index": "D",
    "title": "Babaei and Birthday Cake",
    "statement": "As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.\n\nSimple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has $n$ simple cakes and he is going to make a special cake placing some cylinders on each other.\n\nHowever, there are some additional culinary restrictions. The cakes are numbered in such a way that the cake number $i$ can be placed only on the table or on some cake number $j$ where $j < i$. Moreover, in order to impress friends Babaei will put the cake $i$ on top of the cake $j$ only if the volume of the cake $i$ is strictly greater than the volume of the cake $j$.\n\nBabaei wants to prepare a birthday cake that has a maximum possible total volume. Help him find this value.",
    "tutorial": "First of all, we calculate the volume of each cake: $v_{i}$ = $ \\pi   \\times  h_{i}  \\times  r_{i}^{2}$. Now consider the sequence $v_{1}$, $v_{2}$, $v_{3}$, ..., $v_{n}$ : The answer to the problem is the maximum sum of elements between all increasing sub-sequences of this sequence. How do we solve this? First to get rid of the decimals we can define a new sequence $a_{1}$, $a_{2}$, $a_{3}$, ..., $a_{n}$ such that $a_{i}={\\frac{v_{i}}{\\pi}}=h_{i}\\times r_{i}^{2}$ We consider $dp_{i}$ as the maximum sum between all the sequences which end with $a_{i}$ and $dp_{i}$ = $\\operatorname*{max}(a_{i},\\operatorname*{max}_{j<i,a_{i}\\leq a_{i}}d p[j]+a_{i})$ The answer to the problem is: $ \\pi   \\times  max_{i = 1}^{n}dp[i]$ Now how do we calculate $d p[i]=\\mathrm{max}(a_{i},\\mathrm{max}_{j<i,a,\\leq a_{i}}\\,d p[j]+a_{i})$ ? We use a max-segment tree which does these two operations: $1$. Change the $i't$ member to $v$. $2$. Find the maximum value in the interval $1$ to $i$. Now we use this segment tree for the array $dp$ and find the answer. Consider that $a_{1}$, $a_{2}$, $a_{3}$, ..., $a_{n}$ is sorted. We define $b_{i}$ as the position of $a_{i}$. Now to fill $dp_{i}$ we find the maximum in the interval $[1, b_{i})$ in segment and we call it $x$ and we set the $b_{i}$ th index of the segment as $a_{i} + x$. The answer to the problem would the maximum in the segment in the interval [1,n] Time complexity: $O(nlgn)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MohammadAmin main()\n#define mpair make_pair\n#define endl \"\n\"\n#define c_false ios_base::sync_with_stdio(false); cin.tie(0)\n#define pushb push_back\n#define pushf push_front\n#define popb pop_back\n#define popf pop_front\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n#define X first\n#define Y second\n#define ashar(a) cout << fixed << setprecision((a))\n#define reset(a,b) memset(a, b, sizeof(a))\n#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)\n#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pdd;\n\nconst int INF = 0x3f3f3f3f, MOD = 1e9 + 7;\nconst int n_ = 1e5 + 1000;\nconst ld PI = acos(-1.0);\nll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );}\nll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;}\nll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;}\n\nint n;\nll q[4 * n_], dp[n_];\npair<ll, int> a[n_];\n\nvoid update(int idx, ld x, int id = 1, int b = 0, int e = n) {\n\tif (idx < b || idx >= e) return;\n\tif (idx == b && e - b == 1) {\n\t\tq[id] = dp[b] = x;\n\t\treturn;\n\t}\n\tint mid = b + e >> 1, l = id << 1, r = l | 1;\n\tif (idx < mid) {\n\t\tupdate(idx, x, l, b, mid);\n\t}else{\n\t\tupdate(idx, x, r, mid, e);\n\t}\n\tq[id] = max(q[l], q[r]);\n}\n\nll query(int ql, int qr, int id = 1, int b = 0, int e = n) {\n\tif (ql >= e || qr <= b) return 0;\n\tif (ql <= b && e <= qr) return q[id];\n\tint mid = b + e >> 1, l = id << 1, r = l | 1;\n\treturn max( query(ql, qr, l, b, mid), query(ql, qr, r, mid, e) );\n}\n\nint MohammadAmin {\n\tc_false;\n\tcin >> n;\n\tfor(int i = 0; i < n; i++) {\n\t\tll r, h;\n\t\tcin >> r >> h;\n\t\ta[i].X = r * r * h;\n\t\ta[i].Y = -i;\n\t}\n\tsort(a, a+n);\n\tfor(int i = 0; i < n; i++) {\n\t\tint idx = -a[i].Y;\n\t    ll curr = a[i].X;\n\t\tdp[idx] = query(0, idx) + curr;\n\t\tupdate(idx, dp[idx]);\n\t}\n\tashar(9);\n\tcout << PI * query(0, n) << endl;\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "629",
    "index": "E",
    "title": "Famil Door and Roads",
    "statement": "Famil Door’s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are $n$ intersections in the city connected by $n - 1$ bidirectional roads.\n\nThere are $m$ friends of Famil Door living in the city. The $i$-th friend lives at the intersection $u_{i}$ and works at the intersection $v_{i}$. Everyone in the city is unhappy because there is exactly one simple path between their home and work.\n\nFamil Door plans to construct exactly one new road and he will randomly choose one among $n·(n - 1) / 2$ possibilities. Note, that he may even build a new road between two cities that are already connected by one.\n\nHe knows, that each of his friends will become happy, if after Famil Door constructs a new road there is a path from this friend home to work and back that doesn't visit the same road twice. Formally, there is a simple cycle containing both $u_{i}$ and $v_{i}$.\n\nMoreover, if the friend becomes happy, his pleasure is equal to the length of such path (it's easy to see that it's unique). For each of his friends Famil Door wants to know his expected pleasure, that is the expected length of the cycle containing both $u_{i}$ and $v_{i}$ if we consider only cases when such a cycle exists.",
    "tutorial": "First of all, we assume that the tree is rooted! For this problem, first we need to compute some values for each vertex $u$: $qd_{u}$ and $qu_{u}$, $cnt_{u}$ , $par_{u, i}$ and $h_{u}$. $qd_{u}$ equals to the expected value of length of paths which start from vertex $u$, and ends in $u$'s subtree and also has length at least 1. $qu_{u}$ equals to the expected value of length of paths which start from vertex $u$, and not ends in $u$'s subtree and also has length at least 1. to calculate this values we can use one dfs for $qd$, and one other dfs for $qu$. \\ $cnt_{u}$ is the number of vertices in $u$'s subtree except $u$, $par_{u, i}$ is the $2^{i}$ 'th ancestor of $u$ and finally $h_{u}$ is the height of the vertex $u$. \\ in first dfs (lets call it dfsdown) we can calculate $qd$, $cnt$ and $par$ array with this formulas: $c n t_{u}=\\sum c n t_{v}+1$ $q d_{u}=\\sum{\\frac{c n_{t}x q a_{t}}{c n t a}}+1$ for ecah $v$ as child of $u$ and $par_{u, i}$ = $par_{paru, i - 1, i - 1}$ in second dfs (lets call it dfsup) we calculate $qu$ using this formula (for clearer formula, I may define some extra variables): there are two cases: $u$ is the only child of its parent: let $n e w c n t={\\frac{1}{n-c n t u-1}}$ then $q u_{u}={\\frac{q u_{p}\\times(n-c n t_{p}-1)+n-c n t_{p}}{n e w e n t}}$ \\ $u$ is not the only child of its parent: let $n e w c n t={\\frac{1}{c n t_{p}-c n t_{u}-1}}$ $c n t d={\\frac{1}{n e w c n t}}$ $n o u={\\frac{q d_{p}\\times c n t_{p}-q d_{u}\\times c n t_{u}-c n t_{u}-1}{n e w e n t_{u}-c n t_{u}}}$ $f r a c={\\frac{1}{n-c n t_{n}-1}}$ then $q u[u]={\\frac{c n t d\\times n o u+q u_{p}\\times(n-c n t_{p}-1)+n-c n t_{u}-1}{f r a c}}$ now we should process the queries. For each query $u$ and $v$, we have to cases: one of the vertices is either one of the ancestors of the other one or not! In the first case, if we define $w$ the vertex before $u$ ($u$ is assumed to be the vertex with lower height). In the path from $v$ to $u$, the answer is $\\frac{c n t_{w}\\times(n-c n t_{w}-1)\\times q d_{w}+(n-c n t_{w}-1)\\times q u_{w}}{(c n t_{w}+1)\\times(c n t_{w}+1)\\times q u_{w}}+h_{w}-h_{u}$ . In the second case, if we assume $w = LCA(u, v)$, then answer is ${\\frac{c n t_{u}\\times(c n t_{v}+1)\\times q d_{u}+c n t_{v}\\times(c n t_{u}+1)\\times q d_{v}}{(c n t_{v}+1)\\times(c n t_{u}+1)}}+h[v]+h[u]-2\\times h[w]+1$ To check if $u$ is one of ancestors of $v$, you can check if their $LCA$ equals to $u$ or you can use dfs to find out their starting and finishing time. $u$ is an ancestor of $v$ if the interval of starting and finishing time of $v$ is completely inside starting and finishing time of $u$ The time complexity for the whole solution is $O(n + mlgn)$ ($O(n)$ for dfs and $O(lgn)$ for each query so $O(mlgn)$ for queries!).",
    "code": "// TODO : Choose an Appropriate Name!!\n// We're not here because we're free. We're here because we are not free.\n//\t\t\t\t\t\t\t\t\t\t\t   The Matrix Reloaded (2003)\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define MohammadAmin main()\n#define mpair make_pair\n#define endl \"\n\"\n#define c_false ios_base::sync_with_stdio(false); cin.tie(0)\n#define pushb push_back\n#define pushf push_front\n#define popb pop_back\n#define popf pop_front\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n#define X first\n#define Y second\n#define ashar(a) cout << fixed << setprecision((a))\n#define reset(a,b) memset(a, b, sizeof(a))\n#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)\n#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pdd;\n\nconst int INF = 0x3f3f3f3f, MOD = 1e9 + 7;\nconst int n_ = 1e5 + 1000, lg_ = 20;\nll gcd (ll a, ll b) {return ( a ? gcd(b%a, a) : b );}\nll power(ll a, ll n) {ll p = 1;while (n > 0) {if(n%2) {p = p * a;} n >>= 1; a *= a;} return p;}\nll power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1; a *= a; a %= mod;} return p % mod;}\n\nll n, m, par[n_][lg_], cnt[n_], st[n_], fi[n_], ti;\nll h[n_];\nld qd[n_], qu[n_];\nvector<int> e[n_];\n\nvoid dfs(int u, int p = -1) {\n\tst[u] = ti++;\n\th[u] = ~p ? h[p]+1 : 0;\n\tpar[u][0] = p;\n\tbool leaf = 1;\n\tfor(int i = 1; i < lg_; i++) {\n\t\tif (~par[u][i-1]) {\n\t\t\tpar[u][i] = par[ par[u][i-1] ][i-1];\n\t\t}\n\t}\n\tfor(auto v : e[u]) {\n\t\tif (v != p) {\n\t\t\tleaf = 0;\n\t\t\tdfs(v, u);\n\t\t\tcnt[u] += cnt[v] + 1;\n\t\t}\n\t}\n\tfor(auto v : e[u]) {\n\t\tif (v != p) {\n\t\t\tqd[u] += 1.0 * cnt[v] / cnt[u] * qd[v];\n\t\t}\n\t}\n\tif (!leaf) qd[u] += 1;\n\tfi[u] = ti++;\n}\n\nvoid dfs_d(int u, int p = -1) {\n\tif (~p) {\n\t\tld cntd = cnt[p] - cnt[u] - 1, nou, kcntd, kasr;\n\t\tif (cntd == 0) {\n\t\t\tkcntd = 1.0 / (n - cnt[u] - 1);\n\t\t\tqu[u] = qu[p] * kcntd * (n - cnt[p] - 1) + (n - cnt[p]) * kcntd;\n\t\t}else{\n\t\t\tkcntd = 1.0 / cntd;\n\t\t\tnou = qd[p] * kcntd * cnt[p] - qd[u] * kcntd * cnt[u] - cnt[u] * kcntd - kcntd;\n\t\t\tkasr = 1.0 / (n - cnt[u] - 1);\n\t\t\tqu[u] = cntd * kasr * nou + qu[p] * kasr * (n - cnt[p] - 1) + 1;\n\t\t}\n\t}\n\tfor(auto v : e[u]) {\n\t\tif (v != p) {\n\t\t\tdfs_d(v, u);\n\t\t}\n\t}\n}\n\nint ispar(int u, int v) {\n\treturn st[u] <= st[v] && fi[v] <= fi[u];\n}\n\nint up(int u, int d) {\n\tfor(int i = lg_ - 1; i >= 0; i--) {\n\t\tif (d >> i & 1) {\n\t\t\tu = par[u][i];\n\t\t}\n\t}\n\treturn u;\n}\n\nint lca(int u, int v) {\n\tif (h[u] < h[v]) swap(u, v);\n\tu = up(u, h[u] - h[v]);\n\tif (u == v) return u;\n\tfor(int i = lg_ - 1; i >= 0; i--) {\n\t\tif (par[u][i] != par[v][i]) {\n\t\t\tu = par[u][i], v = par[v][i];\n\t\t}\n\t}\n\treturn par[u][0];\n}\n\nld query(int u, int v) {\n\tif (h[u] > h[v]) swap(u, v);\n\tif (ispar(u, v)) {\n\t\tint w = up(v, h[v] - h[u] - 1);\n\t\tld cn = 1.0 / (cnt[v] + 1) / (n - cnt[w] - 1);\n\t\t// ans = \n\t\t// cnt[v] * qd[v] * (n - cnt[w] - 1) + (n - cnt[w] - 1) * qu[w] * (cnt[v] + 1)\n\t\t// ans /= cn\n\t\tld ans = cnt[v] * (n - cnt[w] - 1) * cn * qd[v] + (n - cnt[w] - 1) * (cnt[v] + 1) * cn * qu[w];\n\t\treturn ans + h[v] - h[u];\n\t}\n\tint w = lca(u, v);\n\tld cn = 1.0 / (cnt[u] + 1) / (cnt[v] + 1);\n\t// ans = \n\t// (cnt[v] + 1) * qd[u] * cnt[u] + (cnt[u] + 1) qd[v] * cnt[v];\n\t// ans /= cn;\n\tld ans = cnt[u] * (cnt[v] + 1) * cn * qd[u] + cnt[v] * (cnt[u] + 1) * cn * qd[v];\n\treturn h[u] - h[w] + h[v] - h[w] + ans + 1;\n}\n\nint MohammadAmin {\n\tc_false;\n\tcin >> n >> m;\n\tfor(int i = 0; i < n-1; i++) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tu--, v--;\n\t\te[u].pushb(v); e[v].pushb(u);\n\t}\n\tdfs(0);\n\tdfs_d(0);\n\tashar(8);\n\twhile(m--) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tcout << query(--u, --v) << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dfs and similar",
      "dp",
      "probabilities",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "630",
    "index": "A",
    "title": "Again Twenty Five!",
    "statement": "The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. \"Do I give such a hard task?\" — the HR manager thought. \"Just raise number $5$ to the power of $n$ and get last two digits of the number. Yes, of course, $n$ can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions.\"\n\nCould you pass the interview in the machine vision company in IT City?",
    "tutorial": "The problem of getting the last two digits is equivalent to the problem of getting the number modulo $100$. So we need to calculate $\\scriptstyle{{\\hat{\\mathbb{P}}}^{n}}\\mathrm{~IIDd}\\mathrm{~}|\\mathbb{O}$. According to the rules of modular arithmetic $(a\\cdot b)\\,\\,\\,\\,\\mathrm{mod}\\,\\,c=((a\\,\\,\\,\\mathrm{mod}\\,\\,c)\\cdot(b\\,\\,\\,\\,\\mathrm{mod}\\,\\,c))\\,\\,\\,\\,\\mathrm{mod}\\,\\,c$ So $5^{n}\\mathrm{\\mod\\100}=\\left((5^{n-1}\\mathrm{\\mod\\100}\\right)\\cdot5\\right)\\mathrm{\\mod\\100}\\cdot5\\right)$ Let's note that $5^{2} = 25$. Then $5^{3}\\mod100=((5^{2}\\mod100)\\cdot5)\\mod100=(25\\cdot5)\\mod100=(25\\cdot5)\\mod100=25$ $5^{4}\\mathrm{\\mod\\100}=((5^{3}\\mathrm{\\mod\\100})\\cdot5)\\mathrm{\\mod\\100}=(25\\cdot5)\\mathrm{\\mod\\100}=(25\\cdot5)\\mathrm{\\mod\\100}=25\\cdot5\\cdot5\\cdot\\mathrm{\\mod\\2000}$ And so on. All $\\scriptstyle{{\\hat{\\mathbb{P}}}^{n}}\\ 1{\\mathrm{Dod}}\\ 1{\\hat{0}}$ are equal to $25$ for all $n  \\ge  2$. So to solve the problem one need to just output 25. There is no need to read $n$.",
    "tags": [
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "630",
    "index": "B",
    "title": "Moore's Law",
    "statement": "The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.\n\nMoore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every $24$ months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.\n\nYou are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly $1.000000011$ times.",
    "tutorial": "Every second the number is multiplied by $1.000000011$. Multiplication several times to the same number is equivalent to exponentiation. So the formula is $n \\cdot 1.000000011^{t}$ ($1.000000011$ raised to the power of $t$ and then multiplied to $n$). In a program one should not use a loop to calculate power as it is too slow for such big $n$, usually a programming language provides a function for exponentiation such as pow.",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "630",
    "index": "C",
    "title": "Lucky Numbers",
    "statement": "The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.\n\nLucky number is a number that consists of digits $7$ and $8$ only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than $n$ digits.",
    "tutorial": "There are $2$ lucky numbers of the length $1$. They are $7$ and $8$. There are $4$ lucky numbers of the length $2$. They are $77$, $78$, $87$ and $88$. There are $8$ lucky numbers of the length $3$. They are $777$, $778$, $787$, $788$, $877$, $878$, $887$, $888$. For each addition of $1$ to the length the number of lucky numbers is increased times $2$. It is easy to prove: to any number of the previous length one can append $7$ or $8$, so one number of the prevous length creates two numbers of the next length. So for the length $n$ the amount of lucky numbers of the length exactly $n$ is $2^{n}$. But in the problem we need the amount of lucky numbers of length not greater than $n$. Let's sum up them. $2^{1} = 2$, $2^{1} + 2^{2} = 2 + 4 = 6$, $2^{1} + 2^{2} + 2^{3} = 2 + 4 + 8 = 14$, $2^{1} + 2^{2} + 2^{3} + 2^{4} = 2 + 4 + 8 + 16 = 30$. One can notice that the sum of all previous powers of two is equal to the next power of two minus the first power of two. So the answer to the problem is $2^{n + 1} - 2$. One of the possible implementations of $2^{n + 1}$ in a programming language is to shift $1$ bitwise to the left for $n + 1$ binary digits or to shift $2$ bitwise to the left for $n$ binary digits. For example, in Java the problem answer formula is (2L << n) - 2, in C++ is (2LL << n) - 2. Suffixes L and LL correspondingly are required so that result of the shift expression have 64-bit integer type (long in Java and long long in C++). Type of the second operand does not matter for the type of shift expression, only the type of the first operand. Also parenthesis are required because without them subtraction is performed first and only then bitwise shift.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "630",
    "index": "D",
    "title": "Hexagons!",
    "statement": "After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known \"Heroes of Might & Magic\". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.\n\nSome of magic effects are able to affect several field cells at once, cells that are situated not farther than $n$ cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.\n\nIt is easy to see that the number of cells affected by a magic effect grows rapidly when $n$ increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given $n$, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than $n$ cells away from a given cell.",
    "tutorial": "Let's count the number of cells having the distance of exactly $n$. For $n = 0$ it is $1$, for $n = 1$ it is $6$, for $n = 2$ it is $12$, for $n = 3$ it is $18$ and so on. One can notice that $n = 0$ is a special case, and then the amount increases by addition of $6$. These numbers form an arithmetic progression. In the problem we need to sum these numbers. The formula of the sum of an arithmetic progression is $(first + last) \\cdot amount / 2$. The first is $6$, the last is $6n$, the amount is $n$. So the sum is $(6 + 6n)n / 2 = 3(n + 1)n$. And plus $1$ that is not in the arithmetic progression. So the final formula is $1 + 3n(n + 1)$. To avoid overflow, multiplication in the formula should be performed in 64-bit integer type. For this either $3$ or $1$ or $n$ should have 64-bit integer type. The literals are 64-bit integer when they have suffix L in Java or LL in C++.",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "630",
    "index": "E",
    "title": "A rectangle",
    "statement": "Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.\n\nA field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a tool for quick filling of a field part with identical enemy units. This action will look like following: a game designer will select a rectangular area on the map, and each cell whose center belongs to the selected rectangle will be filled with the enemy unit.\n\nMore formally, if a game designer selected cells having coordinates $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$, where $x_{1} ≤ x_{2}$ and $y_{1} ≤ y_{2}$, then all cells having center coordinates $(x, y)$ such that $x_{1} ≤ x ≤ x_{2}$ and $y_{1} ≤ y ≤ y_{2}$ will be filled. Orthogonal coordinates system is set up so that one of cell sides is parallel to $OX$ axis, all hexagon centers have integer coordinates and for each integer $x$ there are cells having center with such $x$ coordinate and for each integer $y$ there are cells having center with such $y$ coordinate. It is guaranteed that difference $x_{2} - x_{1}$ is divisible by $2$.\n\nWorking on the problem Petya decided that before painting selected units he wants to output number of units that will be painted on the map.\n\nHelp him implement counting of these units before painting.",
    "tutorial": "Let's see how the number of affected cells changes depending on the column. For example $3, 2, 3, 2, 3$. That is it alternates between the size of the first column and the size of the first column minus one. The amount of \"minus ones\" is the amount of columns divided by 2 rounded down. Without \"minus ones\" all columns have equal size and the total amount of cells is equal to size of the first column multiplied by the number of the columns. The first column size is $(y_{2} - y_{1}) / 2 + 1$. The columns amount is $x_{2} - x_{1} + 1$. So the final formula is $((y_{2} - y_{1}) / 2 + 1) \\cdot (x_{2} - x_{1} + 1) - (x_{2} - x_{1}) / 2$. To avoid overflow, multiplication should be computed in 64-bit integer type.",
    "tags": [
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "630",
    "index": "F",
    "title": "Selection of Personnel",
    "statement": "One company of IT City decided to create a group of innovative developments consisting from $5$ to $7$ people and hire new employees for it. After placing an advertisment the company received $n$ resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.",
    "tutorial": "The amount of ways to choose a group of $5$ people from $n$ candidates is equal to the number of combinations $\\textstyle{\\binom{n}{5}}$, the amount of ways to choose a group of $6$ people from $n$ candidates is $\\textstyle{\\binom{n}{6}}$, the amount of ways to choose a group of $7$ people from $n$ candidates is $\\textstyle{\\binom{n}{\\tau}}$, the amount of ways to choose a group of $5$, $6$ or $7$ people from $n$ candidates is ${\\binom{n}{5}}+{\\binom{n}{6}}+{\\binom{n}{7}}={\\frac{n!}{(n-5)!5!}}+{\\frac{n!}{(n-6)!6!}}+{\\frac{n!}{(n-7)!7!}}$. To avoid 64-bit integer overflow $\\frac{n!}{(n-7)!7!}$ can be calculated in the following way: n / 1 * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * (n - 5) / 6 * (n - 6) / 7. Each division returns an integer because each prefix of this formula after division is also the number of combinations $\\textstyle{\\binom{n}{i}}$.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "630",
    "index": "G",
    "title": "Challenge Pennants",
    "statement": "Because of budget cuts one IT company established new non-financial reward system instead of bonuses.\n\nTwo kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets \"I fixed a critical bug\" pennant on his table. A man who suggested a new interesting feature gets \"I suggested a new feature\" pennant on his table.\n\nBecause of the limited budget of the new reward system only $5$ \"I fixed a critical bug\" pennants and $3$ \"I suggested a new feature\" pennants were bought.\n\nIn order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded \"I fixed a critical bug\" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded \"I suggested a new feature\" pennants is passed on to his table.\n\nOne man can have several pennants of one type and of course he can have pennants of both types on his table. There are $n$ tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.",
    "tutorial": "First of all, ways to place both types of the pennants are independent. So each way to place \"I fixed a critical bug\" pennants on $n$ tables is compatible to each way to place \"I suggested a new feature\" pennants on $n$ tables. Therefore the answer of the problem is equal to the number of ways to place \"I fixed a critical bug\" pennants multiplied by the number of ways to place \"I suggested a new feature\" pennant. The number of ways to place $k$ identical items into $n$ different places when any place can contain any amount of items is the definition of the number of $k$-combinations with repetitions or $k$-multicombinations. The formula for the number is $\\frac{(n+k-1)!}{(n-1)!!}$. So the whole formula for the problem is ${\\frac{(n+4)!}{(n-1)!5!}}\\cdot\\;{\\frac{(n+2)!}{(n-1)!3!}}$. To avoid overflow of 64-bit integer type recommended formulas for computation are (n + 2) / 1 * (n + 1) / 2 * n / 3 and (n + 4) / 1 * (n + 3) / 2 * (n + 2) / 3 * (n + 1) / 4 * n / 5.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "630",
    "index": "H",
    "title": "Benches",
    "statement": "The city park of IT City contains $n$ east to west paths and $n$ north to south paths. Each east to west path crosses each north to south path, so there are $n^{2}$ intersections.\n\nThe city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Obviously this requirement is satisfied by the following scheme: each bench is placed on a cross of paths and each path contains not more than one bench.\n\nHelp the park administration count the number of ways to place the benches.",
    "tutorial": "The number of ways to choose $5$ east to west paths that will have benches from $n$ is ${\\binom{n}{5}}={\\frac{n!}{i n-5!!5!}}={\\frac{n(n-1)(n-2)(n-3)(n-4)}{5!}}$. There are $n$ ways to place a bench on the first of these paths. Given the place of the first bench there are $n - 1$ ways to place a bench on the second of these paths because one of north to south paths is already taken. Given the places of the first and second benches there are $n - 2$ ways to place a bench on the third of these paths because two of north to south paths are already taken. And the same way $n - 3$ and $n - 4$ for the fourth and the fifth benches. Total number of ways to place benches on selected $5$ east to west path is $n(n - 1)(n - 2)(n - 3)(n - 4)$. So the formula for the problem is ${\\frac{n(n-1)(n-2)(n-3)(n-4)}{5!}}\\cdot n(n-1)(n-2)(n-3)(n-4)$. To avoid 64-bit integer overflow recommended order of computation is exactly as in the formula above, division should not be the last operation.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "630",
    "index": "I",
    "title": "Parking Lot",
    "statement": "To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.\n\nThe parking lot before the office consists of one line of $(2n - 2)$ parking spaces. Unfortunately the total number of cars is greater than the parking lot capacity. Furthermore even amount of cars of each make is greater than the amount of parking spaces! That's why there are no free spaces on the parking lot ever.\n\nLooking on the straight line of cars the company CEO thought that parking lot would be more beautiful if it contained exactly $n$ successive cars of the same make. Help the CEO determine the number of ways to fill the parking lot this way.",
    "tutorial": "There are the following ways to place $n$ cars of the same make. They can be the first $n$, the last $n$, or they can be somewhere in the middle of the parking lot. When $n$ cars of the same make are the first or the last, there are $4$ ways to choose the make of these $n$ cars, then there are $3$ ways to choose the make of one car adjacent to them (the make should be different from the make of $n$ cars) and there are $4$ ways to choose the make of each of the remaining $n - 3$ cars. So the formula for the case of $n$ cars of the same make on either end of the parking lot is $4 \\cdot 3 \\cdot 4^{n - 3}$. When $n$ cars of the same make are situated somewhere in the middle, there are $4$ ways to choose the make of these $n$ cars, then there are $3$ ways to choose the make of each of two cars adjacent to them (the makes of these two cars should be different from the make of $n$ cars) and there are $4$ ways to choose the make of each of the remaining $n - 4$ cars. So the formula for the case of $n$ cars of the same make on a given position somewhere in the middle of the parking lot is $4 \\cdot 3^{2} \\cdot 4^{n - 4}$. There are $2$ positions of $n$ cars of the same make in the end of the parking lot and there are $n - 3$ positions of $n$ cars of the same make somewhere in the middle of the parking lot. So the final formula is $2 \\cdot 4 \\cdot 3 \\cdot 4^{n - 3} + (n - 3) \\cdot 4 \\cdot 3^{2} \\cdot 4^{n - 4}$.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "630",
    "index": "J",
    "title": "Divisibility",
    "statement": "IT City company developing computer games invented a new way to reward its employees. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is divisible by all numbers from $2$ to $10$ every developer of this game gets a small bonus.\n\nA game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that $n$ people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.",
    "tutorial": "Let's factorize numbers from $2$ to $10$. $2 = 2, 3 = 3, 4 = 2^{2}, 5 = 5, 6 = 2 \\cdot 3, 7 = 7, 8 = 2^{3}, 9 = 3^{2}, 10 = 2 \\cdot 5$. If a number is divisible by all numbers from $2$ to $10$, its factorization should contain $2$ at least in the power of $3$, $3$ at least in the power of $2$, $5$ and $7$ at least in the power of $1$. So it can be written as $x \\cdot 2^{3} \\cdot 3^{2} \\cdot 5 \\cdot 7 = x \\cdot 2520$. So any number divisible by $2520$ is divisible by all numbers from $2$ to $10$. There are $\\lfloor n/2520\\rfloor$ numbers from $1$ to $n$ divisible by all numbers from $2$ to $10$. In a programming language it is usually implemented as simple integer division.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "630",
    "index": "K",
    "title": "Indivisibility",
    "statement": "IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from $2$ to $10$ every developer of this game gets a small bonus.\n\nA game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that $n$ people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.",
    "tutorial": "The amount of numbers from $1$ to $n$ not divisible by any number from $2$ to $10$ is equal to the amount of all numbers from $1$ to $n$ (that is $n$) minus the amount of numbers from $1$ to $n$ divisible by some number from $2$ to $10$. The set of numbers from $1$ to $n$ divisible by some number from $2$ to $10$ can be found as union of the set of numbers from $1$ to $n$ divisible by $2$, the set of numbers from $1$ to $n$ divisible by $3$ and so on till $10$. Note that sets of numbers divisible by $4$ or $6$ or $8$ are subsets of the set of numbers divisible by $2$, and sets of numbers divisible by $6$ or $9$ are subsets of the set of numbers divisible by $3$. So there is no need to unite $9$ sets, it is enough to unite sets for $2, 3, 5, 7$ only. The size of set of numbers from $1$ to $n$ divisible by some of $2, 3, 5, 7$ can be calculated using inclusion-exclusion principle that says that size of each single set should be added, size of pairwise intersections should be subtracted, size of all intersections of three sets should be added and so on. The size of set of numbers from $1$ to $n$ divisible by $2$ is equal to $\\left\\lfloor{\\frac{n}{2}}\\right\\rfloor$, the size of set of numbers from $1$ to $n$ divisible by $2$ and $3$ is equal to $\\left\\lfloor{\\frac{n}{23}}\\right\\rfloor$ and so on. The final formula is $\\begin{array}{c}{{n-\\left[{\\frac{n}{2}}\\right]-\\left[{\\frac{n}{2}}\\right]-\\left[{\\frac{n}{3}}\\right]-\\left[{\\frac{n}{25}}\\right]-\\left[{\\frac{n}{7}}\\right]+\\left[{\\frac{n}{25}}\\right]+\\left[{\\frac{n}{35}}\\right]+\\left[{\\frac{n}{35}}\\right]+\\left[{\\frac{n}{377}}\\right]+\\left[{\\frac{n}{37}}\\right]+\\frac{n}{57}\\right]+\\left[{\\frac{n}{357}}\\right]+\\frac{n}{527}}\\right]+\\left[{\\frac{n}{152}}\\right]-\\right]}}\\\\ {{\\left[{\\frac{n}{23.5}}\\right]-\\left[{\\frac{n}{23.57}}\\right]-\\left[{\\frac{n}{357}}\\right]-\\left[{\\frac{n}{2357}}\\right]-\\frac{n}{35557}}\\right]}\\end{array}$ Division with rounding down in the formula in a programming language is usually just integer division.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "630",
    "index": "L",
    "title": "Cracking the Code",
    "statement": "The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.\n\nA young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose — to show the developer the imperfection of their protection.\n\nThe found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of $12345$ should lead to $13542$. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number $12345$ is $455 422 043 125 550 171 232$. The answer is the $5$ last digits of this result. For the number $12345$ the answer should be $71232$.\n\nVasya is going to write a keygen program implementing this algorithm. Can you do the same?",
    "tutorial": "In this problem just implementation of the actions described in the statement is required. However there are two catches in this problem. The first catch is that the fifth power of five-digit number cannot be represented by a 64-bit integer. But we need not the fifth power, we need the fifth power modulo $10^{5}$. And $mod$ operation can be applied after each multiplication (see problem A above). The second catch is that you need to output five digits, not the fifth power modulo $10^{5}$. The difference is when fifth digit from the end is zero. To output a number with the leading zero one can either use corresponding formatting (%05d in printf) or extract digits and output them one by one.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "630",
    "index": "M",
    "title": "Turn",
    "statement": "Vasya started working in a machine vision company of IT City. Vasya's team creates software and hardware for identification of people by their face.\n\nOne of the project's know-how is a camera rotating around its optical axis on shooting. People see an eye-catching gadget — a rotating camera — come up to it to see it better, look into it. And the camera takes their photo at that time. What could be better for high quality identification?\n\nBut not everything is so simple. The pictures from camera appear rotated too (on clockwise camera rotation frame the content becomes rotated counter-clockwise). But the identification algorithm can work only with faces that are just slightly deviated from vertical.\n\nVasya was entrusted to correct the situation — to rotate a captured image so that image would be minimally deviated from vertical. Requirements were severe. Firstly, the picture should be rotated only on angle divisible by 90 degrees to not lose a bit of information about the image. Secondly, the frames from the camera are so huge and FPS is so big that adequate rotation speed is provided by hardware FPGA solution only. And this solution can rotate only by 90 degrees clockwise. Of course, one can apply 90 degrees turn several times but for the sake of performance the number of turns should be minimized.\n\nHelp Vasya implement the program that by the given rotation angle of the camera can determine the minimum number of 90 degrees clockwise turns necessary to get a picture in which up direction deviation from vertical is minimum.\n\nThe next figure contains frames taken from an unrotated camera, then from rotated 90 degrees clockwise, then from rotated 90 degrees counter-clockwise. Arrows show direction to \"true up\".\n\nThe next figure shows 90 degrees clockwise turn by FPGA hardware.",
    "tutorial": "First of all, let's reduce camera rotation angle to $[0, 359]$ degrees range. It is accomplished by the following C++/Java code: angle = (angle % 360 + 360) % 360; Then there are the following cases: $[0, 44]$ degrees - no need to rotate, $45$ degrees - $0$ or $1$ turn to minimum deviation, minimum is $0$, $[46, 134]$ degrees - one turn required, $135$ degrees - $1$ or $2$ turns to minimum deviation, minimum is $1$, $[136, 224]$ degrees - two turns required, $225$ degrees - $2$ or $3$ turns to minimum deviation, minimum is $2$, $[226, 314]$ degrees - three turns required, $315$ degrees - $3$ or $0$ turns to minimum deviation, minimum is $0$, $[316, 359]$ degrees - no need to rotate. Let's add $44$ degrees to the angle from the range $[0, 359]$. C++/Java code is angle = (angle + 44) % 360; Then the ranges will be: $[0, 89]$ degrees - $0$ turns, $[90, 179]$ degrees - $1$ turn, $[180, 269]$ degrees - $2$ turns, $[270, 358]$ degrees - $3$ turns, $359$ degrees - $0$ turns. One special case of $359$ degrees can be eliminated by taking angle modulo $359$. Then just integer division by $90$ is required to get the answer. C++/Java code is answer = (angle % 359) / 90;",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "630",
    "index": "N",
    "title": "Forecast",
    "statement": "The Department of economic development of IT City created a model of city development till year 2100.\n\nTo prepare report about growth perspectives it is required to get growth estimates from the model.\n\nTo get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.\n\nThe greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.",
    "tutorial": "There is nothing special in solving a quadratic equation but the problem has one catch. You should output the greater root first. The simplest approach is to output $max(x_{1}, x_{2})$ first, then $min(x_{1}, x_{2})$. Another approach is based upon the sign of $a$. $\\frac{-b-\\sqrt{b^{2}-4a c}}{2a}\\ <\\ \\frac{-b+\\sqrt{b^{2}-4a c}}{2a}$ for $a > 0$ and $\\frac{-b-\\sqrt{b^{2}-4a c}}{2a}~\\gg~\\frac{-b+\\sqrt{b^{2}-4a c}}{2a}$ for $a < 0$. We can divide all coefficients by $a$, and then the first coefficient will be positive. But notice that division should be done in a floating point type and $a$ should be divided last otherwise resulting $a / a = 1$ would not be able to divide $b$ and $c$.",
    "tags": [
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "630",
    "index": "O",
    "title": "Arrow",
    "statement": "Petya has recently started working as a programmer in the IT city company that develops computer games.\n\nBesides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.\n\nA user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates $(px, py)$, a nonzero vector with coordinates $(vx, vy)$, positive scalars $a, b, c, d, a > c$.\n\nThe produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length $a$ and altitude of length $b$ perpendicular to the base. The rectangle sides lengths are $c$ and $d$. Point $(px, py)$ is situated in the middle of the triangle base and in the middle of side of rectangle that has length $c$. Area of intersection of the triangle and the rectangle is zero. The direction from $(px, py)$ point to the triangle vertex opposite to base containing the point coincides with direction of $(vx, vy)$ vector.\n\nEnumerate the arrow points coordinates in counter-clockwise order starting from the tip.",
    "tutorial": "To get a vector of the given length $b$ in the direction of the given vector $(vx, vy)$ it is just required to normalize the given vector (divide it by its length) and then multiply by $b$. Let's denote $l e n={\\sqrt{v x^{2}+v y^{2}}}$, $vnx = vx / len$, $vny = vy / len$. Then $(vnx, vny)$ is the normalized vector, and the first point of the arrow is $(px + vnx \\cdot b, py + vny \\cdot b)$. To get the second point of the arrow one needs to rotate the normalized vector $90$ degrees counter-clockwise and then multiply by the half of the triangle base $a / 2$. Let's denote $vlx = - vny, vly = vnx$. Then $(vlx, vly)$ is the normalized vector $90$ degrees counter-clockwise to $(vnx, vny)$. So the second point of the arrow is $(px + vlx \\cdot a / 2, py + vly \\cdot a / 2)$. The third point can be found the same way as the second point but the length of the vector to it is $c / 2$. So the third point of the arrow is $(px + vlx \\cdot c / 2, py + vly \\cdot c / 2)$. The fourth point can be found by adding the vector of the length $c / 2$ to the left of the given and the vector of the length $d$ reverse to the given. So the fourth point of the arrow is $(px + vlx \\cdot c / 2 - vnx \\cdot d, py + vly \\cdot c / 2 - vny \\cdot d)$. The remaining points are symmetrical to the points discussed above so they can be obtained the same way, just using minus for $(vlx, vly)$ instead of plus. So the next points are $(px - vlx \\cdot c / 2 - vnx \\cdot d, py - vly \\cdot c / 2 - vny \\cdot d)$, $(px - vlx \\cdot c / 2, py - vly \\cdot c / 2)$, $(px - vlx \\cdot a / 2, py - vly \\cdot a / 2)$.",
    "tags": [
      "geometry"
    ],
    "rating": 2000
  },
  {
    "contest_id": "630",
    "index": "P",
    "title": "Area of a Star",
    "statement": "It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.\n\nA \"star\" figure having $n ≥ 5$ corners where $n$ is a prime number is constructed the following way. On the circle of radius $r$ $n$ points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts.",
    "tutorial": "$\\angle C O E={\\frac{2\\pi}{n}}$ where $n$ in the number of the star corners because in a regular star all angles between corners are equal. $\\angle B O A=\\angle C O D={\\frac{\\angle G D}{2}}={\\frac{\\pi}{n}}$ because of symmetry. $\\angle A E={\\frac{\\angle C O E}{2}}={\\frac{\\pi}{n}}$ because it is an inscribed angle. $\\angle C A O=\\angle E A O={\\frac{\\angle C A E}{2}}={\\frac{\\pi}{2n}}$ because of symmetry. So we know $OA = r$ and $\\angle B A O=\\angle C A O={\\frac{\\pi}{2n}}$ and $\\angle B O A={\\frac{\\pi}{n}}$. We can calculate the area of $AOB$ triangle knowing the length of a side and two angles adjacent to it using formula ${\\frac{O A^{2}}{2({\\frac{1}{\\tan2B A O}}+{\\frac{1}{\\tan2B O A}})}}={\\frac{{r}^{2}}{2({\\frac{1}{\\tan2}}{\\frac{1}{\\pi n}}+{\\frac{1}{\\tan}}{\\frac{\\pi}{n}})}}$. The whole star area is equal to $2n$ areas of $AOB$ triangle because of symmetry. $2n\\frac{r^{2}}{2(\\frac{1}{\\tan\\frac{\\pi}{2n}+\\frac{1}{\\tan\\frac{\\pi}{n}})}=\\frac{n r^{2}}{(\\frac{1}{\\tan\\frac{\\pi}{2n}+\\frac{1}{\\tan\\frac{\\pi}{n}})}}{\\mathrm{~}}$.",
    "tags": [
      "geometry"
    ],
    "rating": 2100
  },
  {
    "contest_id": "630",
    "index": "Q",
    "title": "Pyramids",
    "statement": "IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.\n\nThe first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length.",
    "tutorial": "The volume of a pyramid can be calculated as $v={\\frac{1}{3}}s h$ where $v$ is the volume, $s$ is the area of the base and $h$ is the height from the base to the apex. Let's calculate $s$ and $h$. The area of a regular polygon having $n$ sides of length $l_{n}$ can be found the following way. On the figure above a regular polygon is shown. $O$ is the center of the polygon, all sides are equal to $l_{n}$, $OB$ is the altitude of $AOC$ triangle. As the polygon is a regular one $OA = OC$, $AOC$ triangle is a isosceles one and then $\\angle A O B=\\angle C O B$ and $AB = BC$, also $AOB$ and $COB$ triangles are right-angled ones. Also because the polygon is a regular one and can be seen as a union of $2n$ triangles equal to $AOB$ triangle then $\\angle A O B={\\frac{2\\pi}{2n}}={\\frac{\\pi}{n}}$. $AOB$ triangle is right-angled one, so $\\tan\\angle A O B={\\frac{A B}{O B}}$, $\\sin\\angle A O B={\\frac{A B}{O A}}$. Also $A B={\\frac{l_{n}}{2}}$. So $O B={\\frac{l_{\\mathrm{in}}}{2\\tan{\\frac{\\pi}{n}}}}$ and $O A={\\frac{l_{n}}{2\\sin{\\frac{\\pi}{n}}}}$. The area of $AOB$ is equal to ${\\textstyle\\frac{1}{2}}A B\\cdot O B={\\textstyle\\frac{1}{2}}\\cdot{\\textstyle\\frac{l_{n}}{2}}\\cdot{\\frac{l_{n}}{2\\tan{\\frac{\\pi}{c}}}}={\\textstyle\\frac{l_{n}^{2}}{8\\tan{\\frac{1}{2}}}}$. The area of the polygon is $s=2n{\\frac{l_{\\mathrm{\\small~a}}^{2}}{\\sin\\frac{\\pi}{n}}}=\\frac{l_{\\mathrm{\\small~a}\\cdot n}^{2}}{4\\tan\\frac{\\pi}{n}}$. On the figure above a triangle formed by the pyramid apex $H$, the center of the base $O$ and some vertex of the base $A$ is shown. It is a right-angled one. As all edges of the pyramid are equal, $AH = l_{n}$ and from calculations above $O A={\\frac{l_{n}}{2\\sin{\\frac{\\pi}{n}}}}$. According to Pythagorean theorem $OA^{2} + OH^{2} = AH^{2}$. So $O H={\\sqrt{A H^{2}-O A^{2}}}={\\sqrt{l_{n}^{2}-{\\frac{l_{n}^{2}}{4\\sin^{2}{\\frac{\\pi}{n}}}}}}=l_{n}{\\sqrt{1-{\\frac{1}{4\\sin^{2}{\\frac{\\pi}{n}}}}}}$. The volume of one piramid is $\\frac{1}{3}\\cdot\\frac{l_{n}^{2}.n}{4\\tan\\frac{\\pi}{n}}\\cdot l_{n}\\sqrt{1-\\frac{1}{4\\sin^{2}\\frac{\\pi}{n}}}=\\frac{l_{n}^{3}.n}{12\\tan\\frac{\\pi}{n}}\\sqrt{1-\\frac{1}{4\\sin^{2}\\frac{\\pi}{n}}}$. And the final formula is ${\\frac{l_{3}^{3}.3}{12\\tan{\\frac{\\pi}{3}}}}\\sqrt{1-{\\frac{1}{4\\sin^{2}{\\frac{\\pi}{3}}}}}+{\\frac{l_{4}^{3}.4}{12\\tan{\\frac{\\pi}{4}}}}\\sqrt{1-{\\frac{1}{4\\sin^{2}{\\frac{\\pi}{4}}}}}+{\\frac{l_{3}^{3}.5}{12\\tan{\\frac{\\pi}{5}}}}\\sqrt{1-{\\frac{1}{4\\sin^{2}{\\frac{\\pi}{5}}}}}$.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "630",
    "index": "R",
    "title": "Game",
    "statement": "There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor.\n\nThe game is played on a square field consisting of $n × n$ cells. Initially all cells are empty. On each turn a player chooses and paint an empty cell that has no common sides with previously painted cells. Adjacent corner of painted cells is allowed. On the next turn another player does the same, then the first one and so on. The player with no cells to paint on his turn loses.\n\nThe professor have chosen the field size $n$ and allowed the student to choose to be the first or the second player in the game. What should the student choose to win the game? Both players play optimally.",
    "tutorial": "For the field of an even size there is a winning strategy for the second player. Namely, to paint a cell that is symmetrical with respect to the center of the field to the cell painted by the first player on the previous turn. After each turn of the second player the field is centrosymmetrical and so there is always a cell that can be painted that is symmetrical with respect to the center of the field to any cell that the first player can choose to paint. For the field of an odd size there is a winning strategy for the first player. Namely, on the first turn to paint the central cell, then to paint a cell that is symmetrical with respect to the center of the field to the cell painted by the second player on the previous turn. After each turn of the first player the field is centrosymmetrical and so there is always a cell that can be painted that is symmetrical with respect to the center of the field to any cell that the second player can choose to paint. So for even $n$ the answer is 2, for odd $n$ the answer is 1. One of the possible formulas for the problem is $2-(n\\mod2)$. $n$ can be up to $10^{18}$ so at least 64-bit integer type should be used to input it.",
    "tags": [
      "games",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "631",
    "index": "A",
    "title": "Interview",
    "statement": "Blake is a CEO of a large company called \"Blake Technologies\". He loves his company very much and he thinks that his company should be the best. That is why every candidate needs to pass through the interview that consists of the following problem.\n\nWe define function $f(x, l, r)$ as a bitwise OR of integers $x_{l}, x_{l + 1}, ..., x_{r}$, where $x_{i}$ is the $i$-th element of the array $x$. You are given two arrays $a$ and $b$ of length $n$. You need to determine the maximum value of sum $f(a, l, r) + f(b, l, r)$ among all possible $1 ≤ l ≤ r ≤ n$.",
    "tutorial": "You should know only one fact to solve this task: $X\\vee Y\\geq X$. This fact can be proved by the truth table. Let's use this fact: $f(a,1,i-1)\\vee f(a,i,j)\\vee f(a,j+1,N)\\ge f(a,i,j)$. Also $f(a,1,i-1)\\vee f(a,i,j)\\vee f(a,j+1,n)=f(a,1,n)$. According two previous formulas we can get that $f(a, 1, n)  \\ge  f(a, i, j)$. Finally we can get the answer. It's equal to $f(a, 1, N) + f(b, 1, N)$. Time: ${\\mathcal{O}}(n)$ Memory: ${\\cal O}(n)$",
    "code": "from functools import reduce\n \nn = int(input())\na = list(map(int,input().split()))\nb = list(map(int,input().split()))\nprint(reduce(lambda x, y: x | y, a) + reduce(lambda x, y: x | y, b))",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "631",
    "index": "B",
    "title": "Print Check",
    "statement": "Kris works in a large company \"Blake Technologies\". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the printing.\n\nPrinter works with a rectangular sheet of paper of size $n × m$. Consider the list as a table consisting of $n$ rows and $m$ columns. Rows are numbered from top to bottom with integers from $1$ to $n$, while columns are numbered from left to right with integers from $1$ to $m$. Initially, all cells are painted in color $0$.\n\nYour program has to support two operations:\n\n- Paint all cells in row $r_{i}$ in color $a_{i}$;\n- Paint all cells in column $c_{i}$ in color $a_{i}$.\n\nIf during some operation $i$ there is a cell that have already been painted, the color of this cell also changes to $a_{i}$.\n\nYour program has to print the resulting table after $k$ operation.",
    "tutorial": "Let's define $timeR_{i}$ as a number of last query, wich repaint row with number $i$, $timeC_{j}$ - as number of last query, wich repaint column with number $j$. The value in cell $(i, j)$ is equal $a_{max(timeRi, timeCj)}$. Time: $O(n\\cdot m+k)$ Memory: $O(n+m+k)$",
    "code": "n, m, q = map(int,input().split())\ntimeR, timeC, color = [0] * n, [0] * m, [0] * (q + 1)\n \nfor query in range(1, q + 1):\n\ttypeQ, posQ, color[query] = map(int, input().split())\n\tif typeQ == 1:\n\t\ttimeR[posQ - 1] = query\n\telse:\n\t\ttimeC[posQ - 1] = query\n \nfor i in range(n):\n\tout = str()\n\tfor j in range(m):\n\t\tout += str(color[max(timeR[i], timeC[j])])\n\t\tout += \" \"\n\tprint(out)",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "631",
    "index": "C",
    "title": "Report",
    "statement": "Each month Blake gets the report containing main economic indicators of the company \"Blake Technologies\". There are $n$ commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of $m$ managers. Each of them may reorder the elements in some order. Namely, the $i$-th manager either sorts first $r_{i}$ numbers in non-descending or non-ascending order and then passes the report to the manager $i + 1$, or directly to Blake (if this manager has number $i = m$).\n\nEmployees of the \"Blake Technologies\" are preparing the report right now. You know the initial sequence $a_{i}$ of length $n$ and the description of each manager, that is value $r_{i}$ and his favourite order. You are asked to speed up the process and determine how the final report will look like.",
    "tutorial": "If we have some pair of queries that $r_{i}  \\ge  r_{j}$, $i > j$, then we can skip query with number $j$. Let's skip such queries. After that we get an array of sorted queries ($r_{i}  \\le  r_{j}$, $i > j$). Let's sort subarray $a_{1..max(ri)}$ and copy it to $b$. For proccessing query with number $i$ we should record to $a_{ri - 1..ri}$ first or last(it depends on $t_{i - 1}$) $r_{i - 1} - r_{i} + 1$ elementes of $b$. After that this elements should be extract from $b$. You should remember that you need to sort subarray $a_{1..rn}$, after last query. Time: $O(n\\cdot l o g(n)+m)$ Memeory: $O(n+m)$",
    "code": "n, m = map(int,input().split())\na = list(map(int,input().split()))\nt = list()\nb = list()\n \nfor i in range(m):\n\tx, y = map(int,input().split())\n\twhile len(t) > 0 and y >= t[-1][1]: \n\t\tt.pop()\n\tt.append([x, y])\n \nx, y = 0, t[0][1] - 1\nt.append([0, 0])\nb = sorted(a[: y + 1])\n \nfor i in range(1, len(t)):\n\t\tfor j in range(t[i - 1][1], t[i][1], -1):\n\t\t\tif t[i - 1][0] == 1:\n\t\t\t\ta[j - 1] = b[y]\n\t\t\t\ty -= 1 \n\t\t\telse:\n\t\t\t\ta[j - 1] = b[x]\n\t\t\t\tx += 1\n \nprint (\" \".join(list(str(i) for i in a)))",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "631",
    "index": "D",
    "title": "Messenger",
    "statement": "Each employee of the \"Blake Techologies\" company uses a special messaging app \"Blake Messenger\". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve.\n\nAll the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of $n$ blocks, each block containing only equal characters. One block may be described as a pair $(l_{i}, c_{i})$, where $l_{i}$ is the length of the $i$-th block and $c_{i}$ is the corresponding letter. Thus, the string $s$ may be written as the sequence of pairs $\\langle\\left(l_{1},c_{1}\\right),\\left(l_{2},c_{2}\\right),...,\\left(l_{n},c_{n}\\right)\\rangle$.\n\nYour task is to write the program, that given two compressed string $t$ and $s$ finds all occurrences of $s$ in $t$. Developers know that there may be many such occurrences, so they only ask you to find the \\textbf{number} of them. Note that $p$ is the starting position of some occurrence of $s$ in $t$ if and only if $t_{p}t_{p + 1}...t_{p + |s| - 1} = s$, where $t_{i}$ is the $i$-th character of string $t$.\n\nNote that the way to represent the string in compressed form may not be unique. For example string \"aaaa\" may be given as $\\langle\\!\\langle(4,a)\\rangle$, $\\langle(3,a),(1,a)\\rangle$, $\\langle(2,a),(2,a)\\rangle$...",
    "tutorial": "Let's define $S_{}[i]$ as $i - th$ block of $S$, $T_{}[i]$ - as $i - th$ block of $T$.Also $S_{}[l..r] = S_{}[l]S_{}[l + 1]...S_{}[r]$ and $T_{}[l..r] = T_{}[l]T_{}[l + 1]...T_{}[r]$. $T$ is substring of $S$, if $S_{}[l + 1..r - 1] = T_{}[2..m - 1]$ and $S_{}[l].l = T_{}[1].l$ and $S_{}[l].c  \\ge  T_{}[1].c$ and $S_{}[r].l = T_{}[m].l$ and $S_{}[r].c  \\ge  T_{}[m].c$. Let's find all matches of $T_{}[l + 1..r - 1]$ in $S$ and chose from this matches, witch is equal $T$.You can do this by Knuth-Morris-Pratt algorithm. This task has a some tricky test cases: $S=10^{6}-a\\quad10^{6}-a\\quad\\ldots\\quad10^{6}-a$ and $T=1-a$. Answer for this test should be stored at long long. Time: $O(n+m)$ Memory: $O(n+m)$",
    "code": "def ziped(a):\n\tp = []\n\tfor i in a:\n\t\tx = int(i.split('-')[0])\n\t\ty = i.split('-')[1]\n\t\tif len(p) > 0 and p[-1][1] == y:\n\t\t\tp[-1][0] += x\n\t\telse:\n\t\t\tp.append([x, y])\n\treturn p\n \ndef solve(a, b , c):\n\tans = 0\n\tif len(b) == 1:\n\t\tfor token in a:\n\t\t\tif c(token, b[0]):\n\t\t\t\tans += token[0] - b[0][0] + 1\n\t\treturn ans\n\t\t\n\tif len(b) == 2:\n\t\tfor i in range(len(a) - 1):\n\t\t\tif c(a[i], b[0]) and c(a[i + 1], b[-1]):\n\t\t\t\tans += 1\n\t\treturn ans\n\t\t\n\tv = b[1 : -1] + [[100500, '#']] + a\n\tp = [0] * len(v)\n\tfor i in range(1, len(v)):\n\t\tj = p[i - 1]\n\t\twhile j > 0 and v[i] != v[j]:\n\t\t\tj = p[j - 1]\n\t\tif v[i] == v[j]:\n\t\t\tj += 1\n\t\tp[i] = j\n\t\t\n\tfor i in range(len(v) - 1):\n\t\tif p[i] == len(b) - 2 and c(v[i - p[i]], b[0]) and c(v[i + 1], b[-1]):\n\t\t\tans += 1\n\treturn ans\n \nn, m = map(int, input().split())\na = ziped(input().split())\nb = ziped(input().split())\nprint(solve(a, b, lambda x, y: x[1] == y[1] and x[0] >= y[0]))",
    "tags": [
      "data structures",
      "hashing",
      "implementation",
      "string suffix structures",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "631",
    "index": "E",
    "title": "Product Sum",
    "statement": "Blake is the boss of Kris, however, this doesn't spoil their friendship. They often gather at the bar to talk about intriguing problems about maximising some values. This time the problem is really special.\n\nYou are given an array $a$ of length $n$. The characteristic of this array is the value $c=\\sum_{i=1}^{n}a_{i}\\cdot i$ — the sum of the products of the values $a_{i}$ by $i$. One may perform the following operation \\textbf{exactly once}: pick some element of the array and move to any position. In particular, it's allowed to move the element to the beginning or to the end of the array. Also, it's allowed to put it back to the initial position. The goal is to get the array with the maximum possible value of characteristic.",
    "tutorial": "$O(n^{2}):$ The operation, which has been described in the statement, is cyclic shift of some subarray. Let's try to solve this problem separately for left cyclic shift and for right cyclic shift. Let's define $a n s^{\\prime}=\\sum_{i=1}^{n}a_{i}\\cdot i$ as answer before(or without) cyclic shift, $ \\Delta ans = ans - ans'$ - difference between answer after cyclic shift and before. This difference can be found by next formulas: For left cyclic shift: $ \\Delta _{l, r} = (a_{l} \\cdot r + a_{l + 1} \\cdot l + ... + a_{r} \\cdot (r - 1)) - (a_{l} \\cdot l + a_{l + 1} \\cdot (l + 1) + ... + a_{r} \\cdot r) = a_{l} \\cdot (r - l) - (a_{l + 1} + a_{l + 2} + ... + a_{r})$ For right cyclic shift: $ \\Delta '_{l, r} = (a_{l} \\cdot (l + 1) + a_{l + 1} \\cdot (l + 2) + ... + a_{r} \\cdot l) + (a_{l} \\cdot l + a_{l + 1} \\cdot (l + 1) + ... + a_{r} \\cdot r) = (a_{l} + a_{l + 1} + ... + a_{r - 1}) + a_{r} \\cdot (l - r)$ You can find this values with complexity $O(1)$, using prefix sums, $s u m_{r}=\\sum_{i=1}^{r}a_{i}$. ${\\cal O}(n\\cdot l o g(n)):$ Let's try to rewrite previous formulas: For left cyclic shift: $ \\Delta _{l, r} = (a_{l} \\cdot r - sum_{r}) + (sum_{l} - a_{l} \\cdot l)$ For right cyclic shift: $ \\Delta '_{l, r} = (a_{r} \\cdot l - sum_{l - 1}) + (sum_{r - 1} - a_{r} \\cdot r)$ You can see, that if you fix $l$ for left shift and $r$ for right shift, you can solve this problem with complexity $O(n\\cdot l o g(n))$ using Convex Hull Trick. Time: $O(n\\cdot l o g(n))$ Memory: ${\\cal O}(n)$",
    "code": "#include <cstdio>\n#include <algorithm>\n \ntypedef long long Long;\n \nstruct Line {\n    Long a, b, get(Long x) { return a * x + b; }\n};\n \nstruct ConvexHull {\n    int size;\n    Line *hull;\n \n    ConvexHull(int maxSize) {\n        hull = new Line[++maxSize], size = 0;\n    }\n \n    bool is_bad(Long curr, Long prev, Long next) {\n        Line c = hull[curr], p = hull[prev], n = hull[next];\n        return (c.b - n.b) * (c.a - p.a) <= (p.b - c.b) * (n.a - c.a);\n    }\n \n    void add_line(Long a, Long b) {\n        hull[size++] = (Line){a, b};\n        while (size > 2 && is_bad(size - 2, size - 3, size - 1))\n            hull[size - 2] = hull[size - 1], size--;\n    }\n \n    Long query(Long x) {\n        int l = -1, r = size - 1;\n        while (r - l > 1) {\n            int m = (l + r) / 2;\n            if (hull[m].get(x) <= hull[m + 1].get(x))\n                l = m;\n            else\n                r = m;\n        }\n        return hull[r].get(x);\n    }\n};\n \nconst int N = (int)2e5 + 1;\n \nint n, a[N];\nLong sum[N];\nLong ans, dans;\nConvexHull *hull;\n \nint main() {\n    scanf(\"%d\", &n);\n \n    hull = new ConvexHull(n);\n    sum[0] = ans = dans = 0;\n \n    for (int i = 1; i <= n; i++) {\n        scanf(\"%d\", &a[i]);\n        sum[i] = sum[i - 1] + a[i];\n        ans += a[i] * (long long)i;\n    }\n \n    hull->size = 0;\n    for (int r = 2; r <= n; r++) {\n        hull->add_line(r - 1, -sum[r - 2]);\n        dans = std::max(dans, hull->query(a[r]) + sum[r - 1] - a[r] * (long long)r);\n    }\n \n    hull->size = 0;\n    for (int l = n - 1; l >= 1; l--) {\n        hull->add_line(-(l + 1), -sum[l + 1]);\n        dans = std::max(dans, hull->query(-a[l]) + sum[l] - a[l] * (long long)l);\n    }\n \n    printf(\"%I64d\", ans + dans);\n \n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "632",
    "index": "A",
    "title": "Grandma Laura and Apples",
    "statement": "Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.\n\nShe precisely remembers she had $n$ buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.\n\nSo each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).\n\nFor each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is $p$ (the number $p$ is even).\n\nPrint the total money grandma should have at the end of the day to check if some buyers cheated her.",
    "tutorial": "Consider the process from the end. The last buyer will always buy a half of an apple and get a half for free (so the last string always is halfplus). After that each buyer increases the number of apples twice and also maybe by one. So we simply have the binary presentation of the number of apples from the end. To calculate the answer we should simply restore that value from the end and also calculate the total money grandma should have. Complexity: $O(p)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \\\"(\\\" << p.x << \\\", \\\" << p.y << \\\")\\\"; }\\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \\\"[\\\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \\\" ]\\\"; } \\ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\\n\\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 44;\\n\\nint n, p;\\narray<string, N> a;\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> p)) return false;\\n\\tforn(i, n) assert(cin >> a[i]);\\n\\treturn true;\\n}\\n\\ninline void solve() {\\n\\treverse(a.begin(), a.begin() + n);\\n\\tli ans = 0, k = 0;\\n\\tforn(i, n) {\\n\\t\\tk *= 2;\\n\\t\\tif (a[i] == \\\"halfplus\\\") k++;\\n\\t\\tans += k * p / 2;\\n\\t}\\n\\tcerr << \\\"cnt=\\\" << k << endl;\\n\\tcout << ans << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tld stime = gett();\\n\\t\\tsolve();\\n\\t\\tcerr << \\\"Time: \\\" << gett() - stime << endl;\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [],
    "rating": 1200
  },
  {
    "contest_id": "632",
    "index": "B",
    "title": "Alice, Bob, Two Teams",
    "statement": "Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are $n$ pieces, and the $i$-th piece has a strength $p_{i}$.\n\nThe way to split up game pieces is split into several steps:\n\n- First, Alice will split the pieces into two different groups $A$ and $B$. This can be seen as writing the assignment of teams of a piece in an $n$ character string, where each character is $A$ or $B$.\n- Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change $A$ to $B$ and $B$ to $A$). He can do this step at most once.\n- Alice will get all the pieces marked $A$ and Bob will get all the pieces marked $B$.\n\nThe strength of a player is then the sum of strengths of the pieces in the group.\n\nGiven Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.",
    "tutorial": "Let's calculate the prefix sums for all numbers (and store it in array $s1$) and for numbers with letter B (and store it in array $s2$). Now we can find the sum of all numbers in any segment in $O(1)$ time and the sum of numbers with letter B. Let's iterate over prefix or suffix to flip and calculate the sum in that case by formulas: $sum(s1, 0, n - 1) + sum(s2, 0, i) - 2 \\cdot sum(s1, 0, i)$ for prefixes and $sum(s1, 0, n - 1) + sum(s2, i, n - 1) - 2 \\cdot sum(s1, i, n - 1)$ for suffixes. Complexity: $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \\\"(\\\" << p.x << \\\", \\\" << p.y << \\\")\\\"; }\\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \\\"[\\\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \\\" ]\\\"; } \\ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\\n\\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 500500;\\n\\nint n, p[N];\\nchar s[N];\\n\\ninline bool read() {\\n\\tif (!(cin >> n)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &p[i]) == 1);\\n\\tassert(gets(s));\\n\\tassert(gets(s));\\n\\treturn true;\\n}\\n\\nli s1[N], s2[N];\\n\\ninline void solve() {\\n\\tforn(i, n) s1[i + 1] = s1[i] + (s[i] == 'B' ? p[i] : 0);\\n\\tforn(i, n) s2[i + 1] = s2[i] + p[i];\\n\\t\\n\\tauto sum = [](li* s, int l, int r) { return s[r + 1] - s[l]; };\\n\\n\\tli ans = 0;\\n\\tforn(i, n) {\\n\\t\\tans = max(ans, sum(s2, 0, i) - 2 * sum(s1, 0, i));\\n\\t\\tans = max(ans, sum(s2, i, n - 1) - 2 * sum(s1, i, n - 1));\\n\\t}\\n\\tans += sum(s1, 0, n - 1);\\n\\tcout << ans << endl;\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tld stime = gett();\\n\\t\\tsolve();\\n\\t\\tcerr << \\\"Time: \\\" << gett() - stime << endl;\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1400
  },
  {
    "contest_id": "632",
    "index": "C",
    "title": "The Smallest String Concatenation",
    "statement": "You're given a list of $n$ strings $a_{1}, a_{2}, ..., a_{n}$. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.\n\nGiven the list of strings, output the lexicographically smallest concatenation.",
    "tutorial": "The proof of the transitivity also belongs to him. Let's sort all the strings by comparator $a + b < b + a$ and concatenate them. Let's prove that it's the optimal answer. Let that operator be transitive (so if $a<n\\wedge b<c\\Rightarrow a<c$). Consider an optimal answer with two strings in reverse order by that operator. Because of the transitivity of operator we can assume that pair of strings are neighbouring. But then we can swap them and get the better answer. Let's prove the transitivity of operator. Consider the strings as the $26$-base numbers. Then the relation $a + b < b + a$ equivalent to $a\\cdot26^{\\left[b\\right]}+b<b\\cdot26^{\\left[a\\right]}+a\\Leftrightarrow\\frac{a}{26^{\\left[a\\right]}-1}<\\frac{b}{26^{\\left[b\\right]}-1}$. The last is simply the relation between real numbers. So we proved the transitivity of the relation $a + b < b + a$. Complexity: $O(nLlogn)$, where $L$ is the maximal string length.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \\\"(\\\" << p.x << \\\", \\\" << p.y << \\\")\\\"; }\\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \\\"[\\\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \\\" ]\\\"; } \\ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\\n\\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 500500, L = 111;\\n\\nint n;\\nstring a[N];\\n\\nbool read() {\\n\\tif (!(cin >> n)) return false;\\n\\tforn(i, n) {\\n\\t\\tstatic char buf[L];\\n\\t\\tassert(scanf(\\\"%s\\\", buf) == 1);\\n\\t\\ta[i] = string(buf);\\n\\t}\\n\\treturn true;\\n}\\n\\ninline bool cmp(const string& a, const string& b) {\\n\\treturn a + b < b + a;\\n}\\n\\nvoid solve() {\\n\\tsort(a, a + n, cmp);\\n\\tstring ans = accumulate(a, a + n, string());\\n\\tputs(ans.c_str());\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tld stime = gett();\\n\\t\\tsolve();\\n\\t\\tcerr << \\\"Time: \\\" << gett() - stime << endl;\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "sortings",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "632",
    "index": "D",
    "title": "Longest Subsequence",
    "statement": "You are given array $a$ with $n$ elements and the number $m$. Consider some subsequence of $a$ and the value of least common multiple (LCM) of its elements. Denote LCM as $l$. Find any longest subsequence of $a$ with the value $l ≤ m$.\n\nA subsequence of $a$ is an array we can get by erasing some elements of $a$. It is allowed to erase zero or all elements.\n\nThe LCM of an empty array equals $1$.",
    "tutorial": "Let $cnt_{x}$ be the number of occurences of the number $x$ in the given array (easy to see that we can ignore the numbers greater than $m$). Let's iterate over $x={\\overline{{1.m}}}$ and $1  \\le  k, x \\cdot k  \\le  m$ and increase the value in the position $k \\cdot x$ in some array $z$ by the value $cnt_{x}$. So the value $z_{l}$ equals the number of numbers in the given array which divide $l$. Let's find the minimal $l$ with the maximum value $z_{l}$ ($1  \\le  l  \\le  m$). Easy to see that the answer to the problem is the numbers which divide $l$. Let's calculate the complexity of the solution. The number of the pairs $(k, x)$ we can bound with the value $m+{\\frac{m}{2}}+{\\frac{m}{3}}+\\cdot\\cdot\\cdot{\\frac{m}{m}}=O(m l o g m)$. Complexity: $O(n + mlogm)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \\\"(\\\" << p.x << \\\", \\\" << p.y << \\\")\\\"; }\\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \\\"[\\\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \\\" ]\\\"; } \\ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\\n\\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 1200300;\\n\\nint n, m;\\narray<int, N> a;\\n\\ninline bool read() {\\n\\tif (!(cin >> n >> m)) return false;\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &a[i]) == 1);\\n\\treturn true;\\n}\\n\\narray<int, N> cnt;\\narray<int, N> z;\\n\\ninline void solve() {\\n\\tforn(i, m + 1) cnt[i] = z[i] = 0;\\n\\tforn(i, n) if (a[i] < N) cnt[a[i]]++;\\n\\tfore(i, 1, m + 1)\\n\\t\\tfor (int j = i; j <= m; j += i)\\n\\t\\t\\tz[j] += cnt[i];\\n\\tint ansv = -1, ansl = -1;\\n\\tfore(l, 1, m + 1)\\n\\t\\tif (ansv < z[l])\\n\\t\\t\\tansv = z[l], ansl = l;\\n\\tassert(ansl != -1);\\n\\tcout << ansl << ' ' << ansv << endl;\\n\\tbool f = true;\\n\\tforn(i, n)\\n\\t\\tif (ansl % a[i] == 0) {\\n\\t\\t\\tif (f) f = false;\\n\\t\\t\\telse putchar(' ');\\n\\t\\t\\tprintf(\\\"%d\\\", i + 1);\\n\\t\\t\\tansv--;\\n\\t\\t}\\n\\tputs(\\\"\\\");\\n\\tassert(!ansv);\\n\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tld stime = gett();\\n\\t\\tsolve();\\n\\t\\tcerr << \\\"Time: \\\" << gett() - stime << endl;\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "632",
    "index": "E",
    "title": "Thief in a Shop",
    "statement": "A thief made his way to a shop.\n\nAs usual he has his lucky knapsack with him. The knapsack can contain $k$ objects. There are $n$ kinds of products in the shop and an infinite number of products of each kind. The cost of one product of kind $i$ is $a_{i}$.\n\nThe thief is greedy, so he will take exactly $k$ products (it's possible for some kinds to take several products of that kind).\n\nFind all the possible total costs of products the thief can nick into his knapsack.",
    "tutorial": "Let $k = 2$, then it is the standard problem which can be solved by FFT (Fast Fourier Transform). The solution is the following: consider the polynomial which the $i$-th coefficient equals to one if and only if there is the number $i$ in the given array. Let's multiply that polynomial by itself and find $i$ for which the coefficient in square not equals to $0$. Those values $i$ will be in the answer. Easy to modificate the solution for the arbitrary $k$. We should simply calculate the $k$-th degree of the polynomial. The complexity will be $WlogWlogk$, where $W$ is the maximal sum. We can improve that solution. Instead of calculating the $k$-th degree of the polynomial we can calculate the $k$-th degree of the DFT of the polynomial. The only problem is the large values of the $k$-th degrees. We can't use FFT with complex numbers, because of the precision problems. But we can do that with NTT (Number-theoretic transform). But that solution also has a problem. It can happen that some coefficients became equals to zero modulo $p$, but actually they are not equal to zero. To get round that problem we can choose two-three random modules and get the complexity $O(W(logW + logk))$. The main author solution has the complexity $O(WlogWlogk)$ (FFT with complex numbers), the second solution has the same complexity, but uses NTT and the third solution has the improved complexity (but it was already hacked by halyavin). P.S.: To get faster solution you should each time multiply the polynomials of the required degree, but not of the degree $2^{20}$. Complexity: $O(WlogWlogk)$ or $O(W(logW + logk))$, depending the bravery of the coder :-) UPD: It turns out that the first approach also has complexity $O(W(logW + logk))$. See below the comment of halyavin.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \\\"(\\\" << p.x << \\\", \\\" << p.y << \\\")\\\"; }\\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \\\"[\\\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \\\" ]\\\"; } \\ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\\n\\ninline ld gett() { return ld(clock()) / CLOCKS_PER_SEC; }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nint n, k;\\nvector<int> a;\\n\\nbool read() {\\n\\tif (!(cin >> n >> k)) return false;\\n\\ta.resize(n);\\n\\tforn(i, n) assert(scanf(\\\"%d\\\", &a[i]) == 1);\\n\\treturn true;\\n}\\n\\nstruct base {\\n\\tld re, im;\\n\\tbase() { }\\n\\tbase(ld re, ld im): re(re), im(im) { }\\n\\tld slen() const { return sqr(re) + sqr(im); }\\n\\tld real() { return re; }\\n};\\n\\ninline base conj(const base& a) { return base(a.re, -a.im); }\\ninline base operator+ (const base& a, const base& b) { return base(a.re + b.re, a.im + b.im); }\\ninline base operator- (const base& a, const base& b) { return base(a.re - b.re, a.im - b.im); }\\ninline base operator* (const base& a, const base& b) { return base(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re); }\\ninline base operator/ (const base& a, const ld& b) { return base(a.re / b, a.im / b); }\\ninline base operator/ (const base& a, const base& b) { return base(a.re * b.re + a.im * b.im, a.im * b.re - a.re * b.im) / b.slen(); }\\ninline base& operator/= (base& a, const ld& b) { a.re /= b, a.im /= b; return a; }\\n\\nint reverse(int x, int logn) {\\n\\tint ans = 0;\\n\\tforn(i, logn) if (x & (1 << i)) ans |= 1 << (logn - 1 - i);\\n\\treturn ans;\\n}\\n\\nconst int LOGN = 20, N = (1 << LOGN) + 3;\\nvoid fft(base a[N], int n, bool inv) {\\n\\tstatic base vv[LOGN][N];\\n\\tstatic bool prepared = false;\\n\\tif (!prepared) {\\n\\t\\tprepared = true;\\n\\t\\tforn(i, LOGN) {\\n\\t\\t\\tld ang = 2 * PI / (1 << (i + 1));\\n\\t\\t\\tforn(j, 1 << i) vv[i][j] = base(cos(ang * j), sin(ang * j));\\n\\t\\t}\\n\\t}\\n\\tint logn = 0; while ((1 << logn) < n) logn++;\\n\\tforn(i, n) {\\n\\t\\tint ni = reverse(i, logn);\\n\\t\\tif (i < ni) swap(a[i], a[ni]);\\n\\t}\\n\\tfor (int i = 0; (1 << i) < n; i++)\\n\\t\\tfor (int j = 0; j < n; j += (1 << (i + 1)))\\n\\t\\t\\tfor (int k = j; k < j + (1 << i); k++) {\\n\\t\\t\\t\\tbase cur = inv ? conj(vv[i][k - j]) : vv[i][k - j];\\n\\t\\t\\t\\tbase l = a[k], r = cur * a[k + (1 << i)];\\n\\t\\t\\t\\ta[k] = l + r;\\n\\t\\t\\t\\ta[k + (1 << i)] = l - r;\\n\\t\\t\\t}\\n\\tif (inv) forn(i, n) a[i] /= ld(n);\\n}\\n\\nvoid mul(int a[N], int b[N], int ans[N]) {\\n\\tstatic base fp[N], p1[N], p2[N];\\n\\tint n = 1 << LOGN, m = 1 << LOGN;\\n\\twhile (n && !a[n - 1]) n--;\\n\\twhile (m && !b[m - 1]) m--;\\n\\tint cnt = n + m;\\n\\twhile (cnt & (cnt - 1)) cnt++;\\n\\tif (cnt > (1 << LOGN)) return;\\n\\t\\n\\tforn(i, cnt) fp[i] = base(a[i], b[i]);\\n\\tfft(fp, cnt, false);\\n\\tforn(i, cnt) {\\n\\t\\tp1[i] = (fp[i] + conj(fp[(cnt - i) % cnt])) / base(2, 0);\\n\\t\\tp2[i] = (fp[i] - conj(fp[(cnt - i) % cnt])) / base(0, 2);\\n\\t}\\n\\tforn(i, cnt) fp[i] = p1[i] * p2[i];\\n\\tfft(fp, cnt, true);\\n\\n\\tforn(i, cnt) ans[i] = int(fp[i].real() + 0.5);\\n}\\n\\nvoid mul(int* a, int* b) {\\n\\tforn(i, 1 << LOGN) {\\n\\t\\ta[i] = !!a[i];\\n\\t\\tb[i] = !!b[i];\\n\\t}\\n\\tmul(a, b, a);\\n}\\n\\nvoid binPow(int* a, int b) {\\n\\tstatic int ans[N];\\n\\tforn(i, 1 << LOGN) ans[i] = !i;\\n\\twhile (b) {\\n\\t\\tif (b & 1) mul(ans, a);\\n\\t\\tmul(a, a);\\n\\t\\tb >>= 1;\\n\\t}\\n\\tforn(i, 1 << LOGN) a[i] = ans[i];\\n}\\n\\nvoid solve() {\\n\\tstatic int ans[N];\\n\\tmemset(ans, 0, sizeof(ans));\\n\\tforn(i, sz(a)) ans[a[i]] = 1;\\n\\n\\tbinPow(ans, k);\\n\\n\\tbool f = true;\\n\\tforn(i, 1 << LOGN)\\n\\t\\tif (ans[i]) {\\n\\t\\t\\tif (f) f = false;\\n\\t\\t\\telse putchar(' ');\\n\\t\\t\\tprintf(\\\"%d\\\", i);\\n\\t\\t}\\n\\tputs(\\\"\\\");\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tld stime = gett();\\n\\t\\tsolve();\\n\\t\\tcerr << \\\"Time: \\\" << gett() - stime << endl;\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "divide and conquer",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "632",
    "index": "F",
    "title": "Magic Matrix",
    "statement": "You're given a matrix $A$ of size $n × n$.\n\nLet's call the matrix with nonnegative elements magic if it is symmetric (so $a_{ij} = a_{ji}$), $a_{ii} = 0$ and $a_{ij} ≤ max(a_{ik}, a_{jk})$ for all triples $i, j, k$. Note that $i, j, k$ do not need to be distinct.\n\nDetermine if the matrix is magic.\n\nAs the input/output can reach very huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.",
    "tutorial": "Consider the undirected complete graph with $n$ nodes, with an edge between nodes $i, j$ with cost $a_{ij}$. Let $B_{ij}$ denote the minimum possible value of the max edge of a path from $i$ to $j$. We know that $a_{ij}  \\ge  B_{ij}$ by definition. If the matrix is magic, we can choose arbitrary $k_{1}, k_{2}, ..., k_{m}$ such that $a_{ij}  \\le  max(a_{i, k1}, a_{k1, k2}, ..., a_{km, j})$ by repeating invocations of the inequality given. Also, you can show that if this inequality is satisfied, then the matrix is magic (by choosing an $m = 1$ and $k_{1}$ arbitrary). So, this shows that the matrix is magic if and only if $a_{ij}  \\le  B_{ij}$. Thus, combining with $a_{ij}  \\ge  B_{ij}$, we have $a_{ij} = B_{ij}$. We need a fast way to compute $B_{ij}$ for all pairs $i, j$. This can be computed as the MST, as the path in the MST minimizes the max edge between all pairs of nodes. So, the algorithm works as follows. First, find the MST on the complete graph. Then, the matrix is magic if and only if the max edge on the path between $i, j$ in the MST is exactly equal to $a_{i, j}$. Also you shouldn't forget to check symmetry of the matrix and diagonal for zeros. P.S.: Unfortunately we couldn't increase the value $n$ in this problem: the tests already had the size about 67MB and they couldn't be given with generator. So most of the users who solved this problem uses bitset-s. The complexity of their solution is $O({\\underline{{n}}}_{b}^{s})$, where $b = 32$ or $b = 64$. Complexity: $O(n^{2}logn)$ or $O(n^{2})$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define nfor(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\\n#define correct(x, y, n, m) (0 <= (x) && (x) < (n) && 0 <= (y) && (y) < (m))\\n#define all(a) (a).begin(), (a).end()\\n#define sz(a) int((a).size())\\n#define pb(a) push_back(a)\\n#define mp(x, y) make_pair((x), (y))\\n#define x first\\n#define y second\\n\\nusing namespace std;\\n\\ntypedef long long li;\\ntypedef long double ld;\\ntypedef pair<int, int> pt;\\n\\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\\n\\ntemplate<typename A, typename B> inline ostream& operator<< (ostream& out, const pair<A, B>& p) { return out << \\\"(\\\" << p.x << \\\", \\\" << p.y << \\\")\\\"; }\\ntemplate<typename T> inline ostream& operator<< (ostream& out, const vector<T>& a) { out << \\\"[\\\"; forn(i, sz(a)) { if (i) out << ','; out << ' ' << a[i]; } return out << \\\" ]\\\"; } \\ntemplate<typename T> inline ostream& operator<< (ostream& out, const set<T>& a) { return out << vector<T>(all(a)); }\\ntemplate<typename T> inline ostream& operator<< (ostream& out, pair<T*, int> a) { return out << vector<T>(a.x, a.x + a.y); }\\n\\ninline ld gett() { return clock() / ld(CLOCKS_PER_SEC); }\\n\\nconst int INF = int(1e9);\\nconst li INF64 = li(1e18);\\nconst ld EPS = 1e-9, PI = 3.1415926535897932384626433832795;\\n\\nconst int N = 2525, LOGN = 15;\\n\\nint n, a[N][N];\\n\\nbool read() {\\n\\tif (!(cin >> n)) return false;\\n\\tforn(i, n) forn(j, n) assert(scanf(\\\"%d\\\", &a[i][j]) == 1);\\n\\treturn true;\\n}\\n\\nint tt, tin[N], tout[N];\\nvector<int> g[N];\\n\\nvoid dfs(int v) {\\n\\ttin[v] = tt++;\\n\\tforn(i, sz(g[v])) dfs(g[v][i]);\\n\\ttout[v] = tt;\\n}\\n\\ninline bool parent(int a, int b) { return tin[a] <= tin[b] && tout[b] <= tout[a]; }\\n\\nint p[LOGN][N], pd[LOGN][N];\\n\\nint d[N], pr[N];\\nbool used[N];\\n\\nint calc(int a, int b) {\\n\\tint ans = 0;\\n\\tnfor(i, LOGN) {\\n\\t\\tif (!parent(p[i][a], b)) {\\n\\t\\t\\tans = max(ans, pd[i][a]);\\n\\t\\t\\ta = p[i][a];\\n\\t\\t}\\n\\t\\tif (!parent(p[i][b], a)) {\\n\\t\\t\\tans = max(ans, pd[i][b]);\\n\\t\\t\\tb = p[i][b];\\n\\t\\t}\\n\\t}\\n\\tif (!parent(a, b)) ans = max(ans, pd[0][a]);\\n\\tif (!parent(b, a)) ans = max(ans, pd[0][b]);\\n\\treturn ans;\\n}\\n\\nvoid solve() {\\n\\tforn(i, n)\\n\\t\\tforn(j, n)\\n\\t\\t\\tif (a[i][j] != a[j][i] || (i == j && a[i][j])) {\\n\\t\\t\\t\\tputs(\\\"NOT MAGIC\\\");\\n\\t\\t\\t\\treturn;\\n\\t\\t\\t}\\n\\n\\tforn(i, n) {\\n\\t\\tused[i] = false;\\n\\t\\td[i] = INT_MAX;\\n\\t\\tg[i].clear();\\n\\t}\\n\\n\\td[0] = 0;\\n\\tpr[0] = -1;\\n\\tforn(i, n) {\\n\\t\\tint v = -1;\\n\\t\\tforn(j, n)\\n\\t\\t\\tif (!used[j] && (v == -1 || d[v] > d[j]))\\n\\t\\t\\t\\tv = j;\\n\\n\\t\\tassert(v != -1);\\n\\t\\tused[v] = true;\\n\\t\\t//cerr << \\\"v=\\\" << v << \\\" p[v]=\\\" << pr[v] << endl;\\n\\n\\t\\tif (pr[v] != -1) {\\n\\t\\t\\tp[0][v] = pr[v];\\n\\t\\t\\tpd[0][v] = a[pr[v]][v];\\n\\t\\t\\tg[pr[v]].pb(v);\\n\\t\\t} else {\\n\\t\\t\\tp[0][v] = v;\\n\\t\\t\\tpd[0][v] = 0;\\n\\t\\t}\\n\\n\\t\\tforn(j, n)\\n\\t\\t\\tif (!used[j] && d[j] > a[v][j]) {\\n\\t\\t\\t\\td[j] = a[v][j];\\n\\t\\t\\t\\tpr[j] = v;\\n\\t\\t\\t}\\n\\t}\\n\\n\\t//cerr << mp(pr, n) << endl;\\n\\n\\ttt = 0;\\n\\tdfs(0);\\n\\n\\tfore(i, 1, LOGN)\\n\\t\\tforn(j, n) {\\n\\t\\t\\tp[i][j] = p[i - 1][p[i - 1][j]];\\n\\t\\t\\tpd[i][j] = max(pd[i - 1][j], pd[i - 1][p[i - 1][j]]);\\n\\t\\t}\\n\\n\\tforn(i, n)\\n\\t\\tforn(j, n)\\n\\t\\t\\tif (a[i][j] != calc(i, j)) {\\n\\t\\t\\t\\tputs(\\\"NOT MAGIC\\\");\\n\\t\\t\\t\\treturn;\\n\\t\\t\\t}\\n\\tputs(\\\"MAGIC\\\");\\n}\\n\\nint main() {\\n#ifdef SU1\\n    assert(freopen(\\\"input.txt\\\", \\\"rt\\\", stdin));\\n    //assert(freopen(\\\"output.txt\\\", \\\"wt\\\", stdout));\\n#endif\\n    \\n    cout << setprecision(10) << fixed;\\n    cerr << setprecision(5) << fixed;\\n\\n    while (read()) {\\n\\t\\tld stime = gett();\\n\\t\\tsolve();\\n\\t\\tcerr << \\\"Time: \\\" << gett() - stime << endl;\\n\\t\\t//break;\\n\\t}\\n\\t\\n    return 0;\\n}\"",
    "tags": [
      "brute force",
      "divide and conquer",
      "graphs",
      "matrices",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "633",
    "index": "A",
    "title": "Ebony and Ivory",
    "statement": "Dante is engaged in a fight with \"The Savior\". Before he can fight it with his sword, he needs to break its shields. He has two guns, Ebony and Ivory, each of them is able to perform any non-negative number of shots.\n\nFor every bullet that hits the shield, Ebony deals $a$ units of damage while Ivory deals $b$ units of damage. In order to break the shield Dante has to deal \\textbf{exactly} $c$ units of damage. Find out if this is possible.",
    "tutorial": "The problem is to find if there exists a solution to the equation: $ax + by = c$ where x and y are both positive integers. The limits are small enough to try all values of x and correspondingly try if such a y exists. The question can also be solved more efficiently using the fact that an integral solution to this problem exists iff $gcd(a, b)|c$. We just have to make one more check to ensure a positive integral solution. Complexity: $O(log(min(a, b))$",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "633",
    "index": "B",
    "title": "A Trivial Problem",
    "statement": "Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer $m$ and asks for the number of positive integers $n$, such that the factorial of $n$ ends with exactly $m$ zeroes. Are you among those great programmers who can solve this problem?",
    "tutorial": "We know how to calculate number of zeros in the factorial of a number. For finding the range of numbers having number of zeros equal to a constant, we can use binary search. Though, the limits are small enough to try and find the number of zeros in factorial of all numbers of the given range. Complexity: $O(log(n)^{2})$",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "633",
    "index": "C",
    "title": "Spy Syndrome 2",
    "statement": "After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique.\n\nFor a given sentence, the cipher is processed as:\n\n- Convert all letters of the sentence to lowercase.\n- Reverse each of the words of the sentence individually.\n- Remove all the spaces in the sentence.\n\nFor example, when this cipher is applied to the sentence\n\nKira is childish and he hates losing\n\nthe resulting string is\n\nariksihsidlihcdnaehsetahgnisol\n\nNow Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.",
    "tutorial": "The given encrypted string can be reversed initially. Then $dp[i]$ can be defined as the index at which the next word should start such that the given string can be formed using the given dictionary. Rabin Karp hashing can be used to compute $dp[i]$ efficiently. Also, care must be taken that in the answer the words have to be printed in the correct casing as they appear in the dictionary. Complexity: $O(n * w)$ where $n$ is the length of the encrypted string, $w$ is the maximum length of any word in the dictionary.",
    "tags": [
      "data structures",
      "dp",
      "hashing",
      "implementation",
      "sortings",
      "string suffix structures",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "633",
    "index": "D",
    "title": "Fibonacci-ish",
    "statement": "Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if\n\n- the sequence consists of at least two elements\n- $f_{0}$ and $f_{1}$ are arbitrary\n- $f_{n + 2} = f_{n + 1} + f_{n}$ for all $n ≥ 0$.\n\nYou are given some sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.",
    "tutorial": "The key to the solution is that the complete Fibonacci-ish sequence is determined by the first two terms. Another thing to note is that for the given constraints on $a[i]$, the length of the Fibonacci-ish sequence is of logarithmic order (the longest sequence possible under current constraints was of length~90) except for the case where $a[i] = a[j] = 0$, where the length can become as long as the length of the given sequence. Thus, the case for 0 has to be handled separately. Complexity: $O(n * n * l)$ where $n$ is the length of the given sequence and $l$ is the length of the longest Fibonacci-ish subsequence.",
    "tags": [
      "brute force",
      "dp",
      "hashing",
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "633",
    "index": "E",
    "title": "Startup Funding",
    "statement": "An e-commerce startup pitches to the investors to get funding. They have been functional for $n$ weeks now and also have a website!\n\nFor each week they know the number of unique visitors during this week $v_{i}$ and the revenue $c_{i}$. To evaluate the potential of the startup at some range of weeks from $l$ to $r$ inclusive investors use the minimum among the maximum number of visitors multiplied by $100$ and the minimum revenue during this period, that is:\n\n\\[\np(l,r)=\\operatorname*{min}(100\\cdot\\operatorname*{max}_{k=l}v_{k},\\operatorname*{min}_{k=l}c_{k})\n\\]\n\nThe truth is that investors have no idea how to efficiently evaluate the startup, so they are going to pick some $k$ random distinct weeks $l_{i}$ and give them to managers of the startup. For each $l_{i}$ they should pick some $r_{i} ≥ l_{i}$ and report maximum number of visitors and minimum revenue during this period.\n\nThen, investors will calculate the potential of the startup for each of these ranges and take minimum value of $p(l_{i}, r_{i})$ as the total evaluation grade of the startup. Assuming that managers of the startup always report the optimal values of $r_{i}$ for some particular $l_{i}$, i.e., the value such that the resulting grade of the startup is maximized, what is the expected resulting grade of the startup?",
    "tutorial": "Let us denote the number of visitors in the ith week by $v[i]$ and the revenue in the ith week by $r[i]$. Let us define $z[i] = max(min( 100 * max(v[i...j]), min(c[i...j]))) for all (j > = i)$. Note that $max(v[i...j])$ is an increasing function in $j$ and $min(r[i...j])$ is a decreasing function in j. Thus, for all i, $z[i]$ can be computed using RMQ sparse table in combination with binary search. Thus the question reduces to selecting $k$ values randomly from the array $z$. Let us suppose we select these $k$ values and call the minimum of these values $x$. Now, $x$ is the random variable whose expected value we need to find. If we sort $z$ in non-decreasing order: $E(X) = (z[1] * C(n - 1, k - 1) + z[2] * C(n - 2, k - 1) + z[3] * C(n - 3, k - 1)....) / (C(n, k))$ where $C(n, k)$ is the number of ways of selecting $k$ objects out of n. Since $C(n, k)$ will be big values, we should not compute $C(n, k)$ explicitly and just write them as ratios of the previous terms. Example: $C(n - 1, k - 1) / C(n, k) = k / n$ and so on. Complexity: $O(n * lgn)$",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "probabilities",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "633",
    "index": "F",
    "title": "The Chocolate Spree",
    "statement": "Alice and Bob have a tree (undirected acyclic connected graph). There are $a_{i}$ chocolates waiting to be picked up in the $i$-th vertex of the tree. First, they choose two different vertices as their starting positions (Alice chooses first) and take all the chocolates contained in them.\n\nThen, they alternate their moves, selecting one vertex at a time and collecting all chocolates from this node. To make things more interesting, they decided that one can select a vertex only if he/she selected a vertex adjacent to that one at his/her previous turn and this vertex has not been already chosen by any of them during other move.\n\nIf at any moment one of them is not able to select the node that satisfy all the rules, he/she will skip his turns and let the other person pick chocolates as long as he/she can. This goes on until both of them cannot pick chocolates any further.\n\nDue to their greed for chocolates, they want to collect as many chocolates as possible. However, as they are friends they only care about the total number of chocolates they obtain \\textbf{together}. What is the maximum total number of chocolates they may pick?",
    "tutorial": "The problem boils down to computing the maximum sum of two disjoint weighted paths in a tree (weight is on the nodes not edges). It can be solved applying DP as in the given solution : Complexity: $O(n)$ where $n$ is the number of nodes in the tree.",
    "code": "\"#include <cstdio>\\n#include <cmath>\\n#include <cstdlib>\\n#include <cassert>\\n#include <ctime>\\n#include <cstring>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <vector>\\n#include <list>\\n#include <deque>\\n#include <queue>\\n#include <sstream>\\n#include <iostream>\\n#include <algorithm>\\n\\nusing namespace std;\\n\\n#define pb push_back\\n#define mp make_pair\\n#define fs first\\n#define sc second\\n\\nconst double pi = acos(-1.0);\\nconst int size = 1000 * 1000 + 100;\\n\\nint n;\\nlong long a[size];\\nlong long insubtree[size];\\nlong long longest[size];\\nlong long ans = 0;\\n\\nvector <int> vertex[size];\\n\\nvoid dfs1(int v, int f) {\\n    vector <long long> mxs;\\n    longest[v] = a[v];\\n    insubtree[v] = a[v];\\n    for (int i = 0; i < (int) vertex[v].size(); i++) {\\n        if (vertex[v][i] != f) {\\n            dfs1(vertex[v][i], v);\\n            longest[v] = max(longest[v], longest[vertex[v][i]] + a[v]);\\n            insubtree[v] = max(insubtree[v], insubtree[vertex[v][i]]);\\n            mxs.pb(longest[vertex[v][i]]);\\n        }\\n    }\\n\\n    sort(mxs.rbegin(), mxs.rend());\\n\\n    if ((int) mxs.size() > 0) {\\n        insubtree[v] = max(insubtree[v], mxs[0] + a[v]);\\n    }\\n    if ((int) mxs.size() > 1) {\\n        insubtree[v] = max(insubtree[v], mxs[0] + mxs[1] + a[v]);\\n    }\\n}\\n\\nvoid dfs2(int v, int f, long long best, long long lgt) {\\n    ans = max(ans, insubtree[v] + best);\\n\\n    set <pair <long long, int> > bestset;\\n    set <pair <long long, int> > lgtset;\\n    bestset.insert(mp(best, -1));\\n    lgtset.insert(mp(lgt, -1));\\n\\n    for (int i = 0; i < (int) vertex[v].size(); i++) {\\n        if (vertex[v][i] != f) {\\n            bestset.insert(mp(insubtree[vertex[v][i]], i));\\n            lgtset.insert(mp(longest[vertex[v][i]], i));\\n        }\\n    } \\n\\n    for (int i = 0; i < (int) vertex[v].size(); i++) {\\n        if (vertex[v][i] != f) {\\n            bestset.erase(mp(insubtree[vertex[v][i]], i));\\n            lgtset.erase(mp(longest[vertex[v][i]], i));\\n\\n            long long nb = bestset.rbegin()->fs;\\n            long long curb = a[v];\\n            set <pair <long long, int> >::iterator it = lgtset.end();\\n            if (lgtset.size() > 0) {\\n                --it;\\n                curb += it->fs;\\n            }\\n            if (lgtset.size() > 1) {\\n                --it;\\n                curb += it->fs;\\n            }\\n\\n            dfs2(vertex[v][i], v, max(nb, curb), lgtset.rbegin()->fs + a[v]);\\n\\n            bestset.insert(mp(insubtree[vertex[v][i]], i));\\n            lgtset.insert(mp(longest[vertex[v][i]], i));\\n        }\\n    }\\n}\\n\\nint main() {\\n    scanf(\\\"%d\\\", &n);\\n    for (int i = 0; i < n; i++)\\n        scanf(\\\"%lld\\\", &a[i]);\\n\\n    for (int i = 0; i < n - 1; i++) {\\n        int v, u;\\n\\n        scanf(\\\"%d%d\\\", &u, &v);\\n        u--, v--;\\n\\n        vertex[v].pb(u);\\n        vertex[u].pb(v);\\n    }\\n\\n    dfs1(0, -1);\\n    ans = 0ll;\\n\\n    dfs2(0, -1, 0ll, 0ll);\\n\\n    printf(\\\"%lld\\\\n\\\", ans);\\n\\n    return 0;\\n}\"",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "633",
    "index": "G",
    "title": "Yash And Trees",
    "statement": "Yash loves playing with trees and gets especially excited when they have something to do with prime numbers. On his 20th birthday he was granted with a rooted tree of $n$ nodes to answer queries on. Hearing of prime numbers on trees, Yash gets too intoxicated with excitement and asks you to help out and answer queries on trees for him. Tree is rooted at node $1$. Each node $i$ has some value $a_{i}$ associated with it. Also, integer $m$ is given.\n\nThere are queries of two types:\n\n- for given node $v$ and integer value $x$, increase all $a_{i}$ in the subtree of node $v$ by value $x$\n- for given node $v$, find the number of prime numbers $p$ less than $m$, for which there exists a node $u$ in the subtree of $v$ and a non-negative integer value $k$, such that $a_{u} = p + m·k$.",
    "tutorial": "Perform an euler tour (basically a post/pre order traversal) of the tree and store it as an array. Now, the nodes of the subtree are stored are part of the array as a subarray (contiguous subsequence). Query Type 2 requires you to essentially answer the number of nodes in the subtree such that their value modulo $m$ is a prime. Since, $m  \\le  1000$, we can build a segment tree(with lazy propagation) where each node has a bitset, say $b$ where $b[i]$ is on iff a value $x$ exists in the segment represented by that node, such that $i\\equiv x\\mod m$. The addition operations then are simply reduced to bit-rotation within the bitset of the node. Complexity: $O(n * lgn * f)$, where $n$ is the cardinality of the vertices of the tree, $f$ is a small factor denoting the time required for conducting bit rotations on a bitset of size 1000.",
    "tags": [
      "bitmasks",
      "data structures",
      "dfs and similar",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "633",
    "index": "H",
    "title": "Fibonacci-ish II",
    "statement": "Yash is finally tired of computing the length of the longest Fibonacci-ish sequence. He now plays around with more complex things such as Fibonacci-ish potentials.\n\nFibonacci-ish potential of an array $a_{i}$ is computed as follows:\n\n- Remove all elements $j$ if there exists $i < j$ such that $a_{i} = a_{j}$.\n- Sort the remaining elements in ascending order, i.e. $a_{1} < a_{2} < ... < a_{n}$.\n- Compute the potential as $P(a) = a_{1}·F_{1} + a_{2}·F_{2} + ... + a_{n}·F_{n}$, where $F_{i}$ is the $i$-th Fibonacci number (see notes for clarification).\n\nYou are given an array $a_{i}$ of length $n$ and $q$ ranges from $l_{j}$ to $r_{j}$. For each range $j$ you have to compute the Fibonacci-ish potential of the array $b_{i}$, composed using all elements of $a_{i}$ from $l_{j}$ to $r_{j}$ inclusive. Find these potentials modulo $m$.",
    "tutorial": "The problem can be solved by taking the queries offline and using a square-root decomposition trick popularly called as \"Mo's algorithm\". Apart from that, segment tree(with lazy propagation) has to be maintained for the Fibonacci-ish potential of the elements in the current [l,r] range. The fact used in the segment tree for lazy propagation is: $F(k + 1) * (a_{1} * F(i) + a_{2} * F(i + 1)...) + F(k) * (a_{1} * F(i - 1) + a_{2} * F(i) + ....) = (a_{1} * F(i + k) + a_{2} * F(i + k + 1)....)$ Example: Suppose currently the array is [100,400,500,100,300]. Using Mo's algorithm, currently the segment tree is configured for the answer of the segment [3,5]. The segment tree' node [4,5] will store answer=500*F(2)=1000. In general, the node $[l_{1}, r_{1}]$ of segment tree will contain answer for the values in the current range of $[l_{2}, r_{2}]$ of Mo's for the values that have rank in sorted array $[l_{1}, r_{1}]$. The answer will thus be of the form $a_{1} * F(i) + a_{2} * F(i + 1)...$. We maintain an invariant that apart from the answer, it will also store answer for one step back in Fibonacci, i.e., $a_{1} * F(i - 1) + a_{2} * F(i)...$. Now, when values are added (or removed) in the segment tree, the segments after the point after which the value is added have to be updated. For this we maintain a lazy count parameter (say $k$). Thus, when we remove the laziness of the node, we use the above stated formula to remove the laziness in O(1) time. Complexity: $O((n+q)*{\\sqrt{n+q}}*l o g(n))$",
    "code": "\"#include<bits/stdc++.h>\\n#define rep(i,s,n) for(i=(s);i<(n);i++)\\n#define pb push_back\\n#define mp make_pair\\nusing namespace std;\\ntypedef long long ll;\\nconst int SZ = 3e4+8;\\nint M;\\nint fibs[SZ],vals[SZ],ar[SZ];\\nint st[4*SZ][2],lazy[4*SZ];\\nvoid preprocess()\\n{\\n\\tfibs[0] = 0;\\n\\tfibs[1] = 1;\\n\\tfor(int i=2; i<SZ; i++)\\n\\t\\tfibs[i] = (fibs[i-1] + fibs[i-2]) % M;\\n\\tfor(int i=2; i<SZ; i+=2)\\n\\t\\tfibs[i] = -fibs[i];\\n}\\ninline int modulo(int x,int m)\\n{\\n\\tx%=m;\\n\\tif(x<0)x+=m;\\n\\treturn x;\\n}\\n// initially s = 0, e = N-1, x = position where added(overall), i=0, \\n// n = index of fibo to be added, toadd = true if element to be added, false to remove\\n// val is the array from which ai is taken\\nvoid update(int s,int e,int x,int i,int n,bool toadd)\\n{\\n\\tif(lazy[i]!=0)\\n\\t{\\n\\t\\tint a,b,c,d;\\n\\t\\tif(lazy[i]>0)\\n\\t\\t{\\n\\t\\t\\ta = abs(fibs[lazy[i]+1]);\\n\\t\\t\\tb = c = abs(fibs[lazy[i]]);\\n\\t\\t\\td = abs(fibs[lazy[i]-1]);\\n\\t\\t}\\n\\t\\telse if(lazy[i]<0)\\n\\t\\t{\\n\\t\\t\\ta = fibs[-(lazy[i]+1)];\\n\\t\\t\\tb = c = fibs[-lazy[i]];\\n\\t\\t\\td = fibs[-(lazy[i]-1)];\\n\\t\\t}\\n\\t\\ta = a*st[i][0];\\n\\t\\tb = b*st[i][1];\\n\\t\\tc = c*st[i][0];\\n\\t\\td = d*st[i][1];\\n\\t\\tst[i][0] = modulo(a+b,M);\\n\\t\\tst[i][1] = modulo(c+d,M);\\n\\t\\tif(s!=e)\\n\\t\\t\\tlazy[2*i+1]+=lazy[i], lazy[2*i+2] += lazy[i];\\n\\t\\tlazy[i] = 0;\\t\\n\\t}\\n\\tif(x>e)\\n\\t\\treturn;\\n\\tif(x<s)\\n\\t{\\n\\t\\tint a = st[i][0];\\n\\t\\tint b = st[i][1];\\n\\t\\tif(toadd)\\n\\t\\t{\\n\\t\\t\\tst[i][0] = modulo(a+b,M);\\n\\t\\t\\tst[i][1] = a;\\n\\t\\t\\tif(s!=e)\\n\\t\\t\\t\\tlazy[2*i+1]++,lazy[2*i+2]++; \\n\\t\\t}\\n\\t\\telse\\n\\t\\t{\\n\\t\\t\\tst[i][0] = b;\\n\\t\\t\\tst[i][1] = modulo(a-b,M);\\n\\t\\t\\tif(s!=e)\\n\\t\\t\\t\\tlazy[2*i+1]--,lazy[2*i+2]--; \\n\\t\\t}\\n\\t\\treturn;\\n\\t}\\n\\tif(s==e)\\n\\t{\\n\\t\\tif(toadd)\\n\\t\\t{\\n\\t\\t\\tint xr = vals[s];\\n\\t\\t\\tst[i][0] = (xr*abs(fibs[n]))%M;\\n\\t\\t\\tst[i][1] = (xr*abs(fibs[n-1]))%M;\\n\\t\\t}\\n\\t\\telse\\n\\t\\t\\tst[i][0] = st[i][1] = 0;\\n\\t\\treturn;\\n\\t}\\n\\tint mid = (s+e)/2;\\n\\tupdate(s,mid,x,2*i+1,n,toadd);\\n\\tupdate(mid+1,e,x,2*i+2,n,toadd);\\n\\tint a = st[2*i+1][0],b = st[2*i+1][1];\\n\\tint c = st[2*i+2][0],d = st[2*i+2][1];\\n\\tst[i][0] = (a+c)%M;\\n\\tst[i][1] = (b+d)%M;\\n}\\nint sqn;\\ninline bool sub(pair<int,int> x,pair<int,int> y)\\n{\\t\\n\\tdouble v1 = x.first;\\n\\tv1=ceil(v1/sqn);\\n\\tdouble v2 = y.first;\\n\\tv2=ceil(v2/sqn);\\n\\tif(v1==v2)\\n\\t\\treturn x.second<y.second;\\n\\telse\\n\\t\\treturn v1<v2;\\n}\\nint bit[SZ];\\nint l = SZ;\\n\\nvoid bit_update(int i,int val)\\n{\\n  while(i<=l)\\n  {\\n    bit[i]=bit[i]+val;\\n    i=i+(i&(-i));\\n  }\\n}\\n\\nint bit_summ(int a)\\n{\\n  int s=0;\\n  while(a>0)\\n  {\\n    s+=bit[a];\\n    a=a-(a&(-a));\\n  }\\n  return s;\\n}\\nint ans[SZ],num[SZ];\\nint main()\\n{\\n\\tios::sync_with_stdio(false);\\n\\tcin.tie(NULL);\\n\\tint N,Q,l,r;\\n\\tcin>>N>>M;\\n\\tpreprocess();\\n\\tsqn = sqrt(N);\\n\\tfor(int i=1;i<=N;i++)\\n\\t{\\n\\t\\tcin>>ar[i];\\n\\t\\tvals[i-1] = ar[i];\\n\\t}\\n\\tsort(vals,vals+N);\\n\\tfor(int i=1;i<=N;i++)\\n\\t\\tar[i] = lower_bound(vals,vals+N,ar[i]) - vals;\\n\\tfor(int i=0;i<N;i++)\\n\\t\\tvals[i]%=M;\\n\\tcin>>Q;\\n\\tvector<pair<pair<int,int>,int> > queries;\\n\\tfor(int i=0;i<Q;i++)\\n\\t{\\n\\t\\tcin>>l>>r;\\n\\t\\tqueries.push_back(make_pair(make_pair(l,r),i));\\n\\t}\\n\\tsort(queries.begin(),queries.end(),[&](pair<pair<int,int>,int> a,pair<pair<int,int>,int> b){\\n\\t\\treturn sub(a.first,b.first);\\n\\t});\\n\\tl=r=1;\\n\\tnum[ar[1]]++;\\n\\tbit_update(ar[1]+1,1);\\n\\tupdate(0,N-1,ar[1],0,1,true);\\n\\tfor(int i=0; i<queries.size(); i++)\\n\\t{\\n\\t\\tpair<int,int> p = queries[i].first;\\n\\t\\tint ix = queries[i].second,pos;\\n\\t\\twhile(l<p.first)\\n\\t\\t{\\n\\t\\t\\tnum[ar[l]]--;\\n\\t\\t\\tif(num[ar[l]]==0)\\n\\t\\t\\t{\\n\\t\\t\\t\\tbit_update(ar[l]+1,-1);\\n\\t\\t\\t\\tupdate(0,N-1,ar[l],0,0,false);\\n\\t\\t\\t}\\n\\t\\t\\tl++;\\n\\t\\t}\\n\\t\\twhile(l>p.first)\\n\\t\\t{\\n\\t\\t\\tl--;\\n\\t\\t\\tnum[ar[l]]++;\\n\\t\\t\\tif(num[ar[l]]==1)\\n\\t\\t\\t{\\n\\t\\t\\t\\tpos = bit_summ(ar[l]) + 1;\\n\\t\\t\\t\\tbit_update(ar[l]+1,1);\\n\\t\\t\\t\\tupdate(0,N-1,ar[l],0,pos,true);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\twhile(r<p.second)\\n\\t\\t{\\n\\t\\t\\tr++;\\n\\t\\t\\tnum[ar[r]]++;\\n\\t\\t\\tif(num[ar[r]]==1)\\n\\t\\t\\t{\\n\\t\\t\\t\\tpos = bit_summ(ar[r]) + 1;\\n\\t\\t\\t\\tbit_update(ar[r]+1,1);\\n\\t\\t\\t\\tupdate(0,N-1,ar[r],0,pos,true);\\n\\t\\t\\t}\\n\\t\\t}\\t\\t\\n\\t\\twhile(r>p.second)\\n\\t\\t{\\n\\t\\t\\tnum[ar[r]]--;\\n\\t\\t\\tif(num[ar[r]]==0)\\n\\t\\t\\t{\\n\\t\\t\\t\\tbit_update(ar[r]+1,-1);\\t\\t\\n\\t\\t\\t\\tupdate(0,N-1,ar[r],0,0,false);\\n\\t\\t\\t}\\n\\t\\t\\tr--;\\n\\t\\t}\\n\\t\\tans[ix] = st[0][0];\\n\\t}\\t\\n\\tfor(int i=0; i<Q; i++)\\n\\t\\tcout<<ans[i]<<\\\"\\\\n\\\";\\n}\"",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 3100
  },
  {
    "contest_id": "634",
    "index": "A",
    "title": "Island Puzzle",
    "statement": "A remote island chain contains $n$ islands, labeled $1$ through $n$. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands $1$ and $2$, islands $2$ and $3$, and so on, and additionally a bridge connects islands $n$ and $1$. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.\n\nThe islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.\n\nDetermine if it is possible for the islanders to arrange the statues in the desired order.",
    "tutorial": "Notice that, as we move the empty pedestal around the circle, we cyclically permute the statues (and the empty pedestal can be anywhere). Thus, we can reach one state from another if and only if, after removing the empty pedestal, they are cyclic shifts of each other. The starting and ending configurations are permutations, so we can check this in linear time. Runtime: $O(n)$",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "635",
    "index": "A",
    "title": "Orchestra",
    "statement": "Paul is at the orchestra. The string section is arranged in an $r × c$ rectangular grid and is filled with violinists with the exception of $n$ violists. Paul really likes violas, so he would like to take a picture including at least $k$ of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.\n\nTwo pictures are considered to be different if the coordinates of corresponding rectangles are different.",
    "tutorial": "We can iterate over each possible rectangle and count the number of violists enclosed. This can be optimized with rectangular prefix sums, though the simple brute force is sufficient for this problem. Runtime: $O(n^{6})$",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "639",
    "index": "A",
    "title": "Bear and Displayed Friends",
    "statement": "Limak is a little polar bear. He loves connecting with other bears via social networks. He has $n$ friends and his relation with the $i$-th of them is described by a unique integer $t_{i}$. The bigger this value is, the better the friendship is. No two friends have the same value $t_{i}$.\n\nSpring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.\n\nThe system displays friends who are online. On the screen there is space to display at most $k$ friends. If there are more than $k$ friends online then the system displays only $k$ best of them — those with biggest $t_{i}$.\n\nYour task is to handle queries of two types:\n\n- \"1 id\" — Friend $id$ becomes online. It's guaranteed that he wasn't online before.\n- \"2 id\" — Check whether friend $id$ is displayed by the system. Print \"YES\" or \"NO\" in a separate line.\n\nAre you able to help Limak and answer all queries of the second type?",
    "tutorial": "You should remember all friends displayed currently (in set or list) and when you add someone new you must check whether there are at most $k$ people displayed. If there are $k + 1$ then you can iterate over them (over $k + 1$ people in your set/list) and find the worst one. Then - remove him. The intended complexity is O(n + q*k).",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int nax = 1e6 + 5;\nint t[nax];\nstruct cmp {\n    bool operator()(int a, int b) {\n        return t[a] < t[b];\n    }\n};\nint main() {\n\tint n, k, q;\n\tscanf(\"%d%d%d\", &n, &k, &q);\n\tfor(int i = 1; i <= n; ++i) scanf(\"%d\", &t[i]);\n\tset<int, cmp> displayed;\n\twhile(q--) {\n\t    int type, a;\n\t    scanf(\"%d%d\", &type, &a);\n\t    if(type == 1) {\n\t        displayed.insert(a);\n\t        if((int) displayed.size() > k)\n\t            displayed.erase(displayed.begin());\n\t    }\n\t    else {\n\t        if(displayed.find(a) == displayed.end())\n\t            puts(\"NO\");\n\t        else\n\t            puts(\"YES\");\n\t    }\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "639",
    "index": "B",
    "title": "Bear and Forgotten Tree 3",
    "statement": "A tree is a connected undirected graph consisting of $n$ vertices and $n - 1$ edges. Vertices are numbered $1$ through $n$.\n\nLimak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values $n$, $d$ and $h$:\n\n- The tree had exactly $n$ vertices.\n- The tree had diameter $d$. In other words, $d$ was the biggest distance between two vertices.\n- Limak also remembers that he once rooted the tree in vertex $1$ and after that its height was $h$. In other words, $h$ was the biggest distance between vertex $1$ and some other vertex.\n\nThe distance between two vertices of the tree is the number of edges on the simple path between them.\n\nHelp Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print \"-1\".",
    "tutorial": "You may want to write some special if for $n = 2$. Let's assume $n  \\ge  3$. If $d = 1$ or $d > 2h$ then there is no answer (it isn't hard to see and prove). Otherwise, let's construct a tree as follows. We need a path of length $h$ starting from vertex $1$ and we can just build it. If $d > h$ then we should also add an other path from vertex $1$, this one with length $d - h$. Now we have the required height and diameter but we still maybe have too few vertices used. But what we built is one path of length $d$ where $d  \\ge  2$. You can choose any vertex on this path other than ends of the path (let's call him $v$), and add new vertices by connecting them all directly with $v$. You can draw it to see that you won't increase height or diameter this way. In my code I sometimes had $v = 1$ but sometimes (when $d = h$) I needed some other vertex and $v = 2$ was fine.",
    "code": "#include<bits/stdc++.h> using namespace std; int main() { int n, d, h; scanf(\"%d%d%d\", &n, &d, &h); if(d > 2 * h || (d == 1 && n != 2)) { puts(\"-1\"); return 0; } for(int i = 1; i <= h; ++i) printf(\"%d %d \", i, i + 1); int x = 1; for(int i = 1; i <= d - h; ++i) { int y = h + 1 + i; printf(\"%d %d \", x, y); x = y; } for(int i = d + 2; i <= n; ++i) printf(\"%d %d \", i, (d == h) ? 2 : 1); return 0; }",
    "tags": [
      "constructive algorithms",
      "graphs",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "639",
    "index": "C",
    "title": "Bear and Polynomials",
    "statement": "Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.\n\nHe considers a polynomial valid if its degree is $n$ and its coefficients are integers not exceeding $k$ by the absolute value. More formally:\n\nLet $a_{0}, a_{1}, ..., a_{n}$ denote the coefficients, so $P(x)=\\sum_{i=0}^{n}a_{i}\\cdot x^{i}$. Then, a polynomial $P(x)$ is valid if all the following conditions are satisfied:\n\n- $a_{i}$ is integer for every $i$;\n- $|a_{i}| ≤ k$ for every $i$;\n- $a_{n} ≠ 0$.\n\nLimak has recently got a valid polynomial $P$ with coefficients $a_{0}, a_{1}, a_{2}, ..., a_{n}$. He noticed that $P(2) ≠ 0$ and he wants to change it. He is going to change one coefficient to get a \\textbf{valid} polynomial $Q$ of degree $n$ that $Q(2) = 0$. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.",
    "tutorial": "Let's count only ways to decrease one coefficient to get the required conditions (you can later multiply coefficient by $- 1$ and run your program again to also calculate ways to increase a coefficient). One way of thinking is to treat the given polynomial as a number. You can find the binary representation - a sequence with $0$'s and $1$'s of length at most $n+\\log(10^{9})$. Changing one coefficient affects up to $\\log(10^{9})$ consecutive bits there and we want to get a sequence with only $0$'s. We may succeed only if all $1$'s are close to each other and otherwise we can print $0$ to the output. Let's think what happens when $1$'s are close to each other. Let's say that we got a sequence with two $1$'s as follows: $...00101000...$. Decreasing by $5$ one coefficient (the one that was once in a place of the current first bit $1$) will create a sequence of $0$'s only. It's not complicated to show that decreasing coefficients on the right won't do a job (because the first $1$ will remain there) but you should also count some ways to change coefficients on the left. We can decrease by $10$ a coefficient on the left from first $1$, or decrease by $20$ a coefficient even more on the left, and so on. Each time you should check whether changing the original coefficient won't exceed the given maximum allowed value $k$. One other solution is to go from left to right and keep some integer value - what number should be added to the current coefficient to get sum equal to $0$ on the processed prefix. Then, we should do the same from right to left. In both cases maybe in some moment we should break because it's impossible to go any further. In one case it happens when we should (equally) divide an odd number by $2$, and in the other case it happens when our number becomes too big (more than $2 \\cdot 10^{9}$) because we won't be able to make it small again anyway.",
    "code": "#include<bits/stdc++.h> using namespace std; typedef long long ll; const int nax = 1e6 + 5; int t[nax]; ll pref[nax], suf[nax]; const ll WRONG = 1e16 + 5; int main() { int n, k; scanf(\"%d%d\", &n, &k); for(int i = 0; i <= n; ++i) scanf(\"%d\", &t[i]); for(int i = 0; i < n; ++i) { pref[i+1] = pref[i] + t[i]; if(pref[i+1] % 2) { for(int j = i + 1; j <= n; ++j) pref[j] = WRONG; break; } else pref[i+1] /= 2; } for(int i = n; i > 0; --i) { suf[i-1] = suf[i] + t[i]; suf[i-1] *= 2; if(abs(suf[i-1]) >= WRONG) { for(int j = i - 1; j >= 0; --j) suf[j] = WRONG; break; } } int ans = 0; for(int i = 0; i <= n; ++i) if(suf[i] != WRONG && pref[i] != WRONG) { long long maybe = -(pref[i] + suf[i]); if(maybe == 0 && i == n) continue; if(abs(maybe) <= k) ++ans; } printf(\"%d \", ans); return 0; }",
    "tags": [
      "hashing",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "639",
    "index": "D",
    "title": "Bear and Contribution",
    "statement": "Codeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contribution — an integer number, not necessarily positive. There are $n$ registered users and the $i$-th of them has contribution $t_{i}$.\n\nLimak is a little polar bear and he's new into competitive programming. He doesn't even have an account in Codeforces but he is able to upvote existing blogs and comments. We assume that every registered user has infinitely many blogs and comments.\n\n- Limak can spend $b$ minutes to read one blog and upvote it. Author's contribution will be increased by $5$.\n- Limak can spend $c$ minutes to read one comment and upvote it. Author's contribution will be increased by $1$.\n\nNote that it's possible that Limak reads blogs faster than comments.\n\nLimak likes ties. He thinks it would be awesome to see a tie between at least $k$ registered users. To make it happen he is going to spend some time on reading and upvoting. After that, there should exist an integer value $x$ that at least $k$ registered users have contribution exactly $x$.\n\nHow much time does Limak need to achieve his goal?",
    "tutorial": "It isn't enough to sort the input array and use two pointers because it's not correct to assume that the optimal set of people will be an interval. Instead, let's run some solution five times, once for each remainder after dividing by $5$ (remainders $0, 1, 2, 3, 4$). For each remainder $r$ we assume that we should move $k$ people to some value $x$ that $x\\ \\operatorname{mod}5=r$ (and at the end we want at least $k$ people to have contribution $x$). Note that $x$ must be close to some number from the input because otherwise we should decrease $x$ by $5$ and for sure we would get better solution. The solution is to iterate over possible values of $x$ from lowest to highest (remember that we fixed remainder $r=x\\ \\mathrm{~mod~5}$). At the same time, we should keep people in $5$ vectors/lists and do something similar to the two pointers technique. We should keep two pointers on each of $5$ lists and always move the best among $5$ options. The complexity should be $O(n \\cdot 5)$.",
    "code": "#include <bits/stdc++.h> using namespace std; int n, k; long long c1, c2; long long con[1000007]; long long res; long long aktual; vector <long long> pos[5]; queue <long long> val[5]; int w; long long p; inline long long calc(long long a, long long b) { return ((b-a)%5)*c2+((b-a)/5)*c1; } int main() { res=1000000000; res*=res; scanf(\"%d%d\", &n, &k); scanf(\"%lld%lld\", &c1, &c2); c1=min(c1, 5*c2); for (int i=1; i<=n; i++) { scanf(\"%lld\", &con[i]); con[i]+=1000000001; } sort(con+1, con+n+1); for (int i=k; i<=n; i++) { for (int j=0; j<5; j++) { pos[(con[i]+j)%5].push_back(con[i]+j); } } for (int h=0; h<5; h++) { sort(pos[h].begin(), pos[h].end()); for (int i=0; i<5; i++) { while(!val[i].empty()) val[i].pop(); } w=0; aktual=0; for (int i=0; i<pos[h].size(); i++) { if (i) aktual+=c1*min(w, k)*(pos[h][i]-pos[h][i-1])/5; while(w<n && con[w+1]<=pos[h][i]) { w++; val[con[w]%5].push(con[w]); aktual+=calc(con[w], pos[h][i]); if (w>k) { p=0; for (int j=0; j<5; j++) { if (!val[j].empty()) { p=max(p, calc(val[j].front(), pos[h][i])); } } for (int j=0; j<5; j++) { if (!val[j].empty() && calc(val[j].front(), pos[h][i])==p) { aktual-=p; val[j].pop(); break; } } } } if (w>=k) { res=min(res, aktual); } } } printf(\"%lld \", res); return 0; }",
    "tags": [
      "data structures",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "639",
    "index": "E",
    "title": "Bear and Paradox",
    "statement": "Limak is a big polar bear. He prepared $n$ problems for an algorithmic contest. The $i$-th problem has \\textbf{initial} score $p_{i}$. Also, testers said that it takes $t_{i}$ minutes to solve the $i$-th problem. Problems aren't necessarily sorted by difficulty and maybe harder problems have smaller initial score but it's too late to change it — Limak has already announced initial scores for problems. Though it's still possible to adjust the speed of losing points, denoted by $c$ in this statement.\n\nLet $T$ denote the total number of minutes needed to solve all problems (so, $T = t_{1} + t_{2} + ... + t_{n}$). The contest will last exactly $T$ minutes. So it's just enough to solve all problems.\n\nPoints given for solving a problem decrease linearly. Solving the $i$-th problem after $x$ minutes gives exactly $p_{i}\\cdot(1-c\\cdot{\\frac{x}{T}})$ points, where $c\\in[0,1]$ is some real constant that Limak must choose.\n\nLet's assume that $c$ is fixed. During a contest a participant chooses some order in which he or she solves problems. There are $n!$ possible orders and each of them gives some total number of points, not necessarily integer. We say that an order is optimal if it gives the maximum number of points. In other words, the total number of points given by this order is greater or equal than the number of points given by any other order. It's obvious that there is at least one optimal order. However, there may be more than one optimal order.\n\nLimak assumes that every participant will properly estimate $t_{i}$ at the very beginning and will choose some optimal order. He also assumes that testers correctly predicted time needed to solve each problem.\n\nFor two distinct problems $i$ and $j$ such that $p_{i} < p_{j}$ Limak wouldn't be happy to see a participant with strictly more points for problem $i$ than for problem $j$. He calls such a situation a paradox.\n\nIt's not hard to prove that there will be no paradox for $c = 0$. The situation may be worse for bigger $c$. What is the maximum real value $c$ (remember that $c\\in[0,1]$) for which there is no paradox possible, that is, there will be no paradox for \\textbf{any optimal order} of solving problems?\n\nIt can be proved that the answer (the maximum $c$ as described) always exists.",
    "tutorial": "It's good to know what to do with problems about optimal order. Often you can use the following trick - take some order and look at two neighbouring elements. When is it good to swap? (When does swapping them increase the score?) You should write some simple formula (high school algebra) and get some inequality. In this problem it turns out that one should sort problems by a fraction $\\scriptstyle{\\vec{r}}_{i}$ and it doesn't depend on a constant $c$. There may be many problems with the same value of $\\scriptstyle{\\vec{r}}_{i}$ and we can order them however we want (and the question will be: if there is a paradox for at least one order). Let's call such a set of tied problems a block. For each problem you can calculate its minimum and maximum possible number of granted points - one case is at the end of his block and the other case is to solve this problem as early as possible so at the beginning of his block. So, for fixed $c$ for each problem we can find in linear time the best and worst possible scores (given points). When do we get a paradox? Where we have two problems $i$ and $j$ that $p_{i} < p_{j}$ ($p_{i}$ was worth less points) we solved problem $i$ much earlier and later we got less points for problem $p_{j}$. We can now use some segment tree or sort problems by $p_{i}$ and check whether there is a pair of problems with inequalities we are looking for - $p_{i} < p_{j}$ and $max_{i} > min_{j}$ where $max_{i}$ and $min_{j}$ we found in the previous paragraph. We can do the binary search over the answer to get complexity $O(n\\cdot\\log n\\cdot\\log(10^{9}))$ or faster. Can you solve the problem in linear time?",
    "code": "#include<bits/stdc++.h> using namespace std; typedef pair<int,int> pii; typedef long double ld; #define points first #define time second bool paradox(vector<vector<pii>> & w, ld c) { ld time_total = 0; for(auto group : w) for(pii p : group) time_total += p.time; ld time_so_far = 0; vector<pair<int,pair<ld,ld>>> all; for(vector<pii> & group : w) { ld time_this_group = 0; for(pii & p : group) time_this_group += p.time; for(pii & p : group) { ld small = p.points * (1 - c * (time_so_far + time_this_group) / time_total); ld big = p.points * (1 - c * (time_so_far + p.time) / time_total); all.push_back(make_pair(p.points, make_pair(small, big))); } time_so_far += time_this_group; } sort(all.begin(), all.end()); ld max_so_far = -1; for(int i = 0; i < (int) all.size(); ++i) { int j = i; while(j + 1 < (int) all.size() && all[j+1].first == all[i].first) ++j; for(int k = i; k <= j; ++k) if(all[k].second.first < max_so_far) return true; // paradox for(int k = i; k <= j; ++k) max_so_far = max(max_so_far, all[k].second.second); i = j; } return false; } int cmp(const pii & a, const pii & b) { // -1, 0 or 1 long long tmp = (long long) a.first * b.second - (long long) a.second * b.first; if(tmp > 0) return -1; if(tmp == 0) return 0; return 1; } bool sort_cmp(const pii & a, const pii & b) { int memo = cmp(a, b); return memo == -1 || (memo == 0 && a.points < b.points); } const int nax = 1e6 + 5; pii in[nax]; int main() { int n; scanf(\"%d\", &n); for(int i = 0; i < n; ++i) scanf(\"%d\", &in[i].points); for(int i = 0; i < n; ++i) scanf(\"%d\", &in[i].time); sort(in, in + n, sort_cmp); vector<vector<pii>> w; for(int i = 0; i < n; ++i) { if(i == 0 || cmp(in[i-1], in[i]) != 0) w.push_back(vector<pii>{}); w.back().push_back(in[i]); } ld low = 0, high = 1; for(int rep = 0; rep < 40; ++rep) { ld mid = (low + high) / 2; if(paradox(w, mid)) high = mid; else low = mid; } printf(\"%.10lf \", (double) (low + high) / 2); return 0; }",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "639",
    "index": "F",
    "title": "Bear and Chemistry",
    "statement": "Limak is a smart brown bear who loves chemistry, reactions and transforming elements.\n\nIn Bearland (Limak's home) there are $n$ elements, numbered $1$ through $n$. There are also special machines, that can transform elements. Each machine is described by two integers $a_{i}, b_{i}$ representing two elements, not necessarily distinct. One can use a machine either to transform an element $a_{i}$ to $b_{i}$ or to transform $b_{i}$ to $a_{i}$. Machines in Bearland aren't very resistant and each of them can be used \\textbf{at most once}. It is possible that $a_{i} = b_{i}$ and that many machines have the same pair $a_{i}, b_{i}$.\n\nRadewoosh is Limak's biggest enemy and rival. He wants to test Limak in the chemistry. They will meet tomorrow and both of them will bring all their machines. Limak has $m$ machines but he doesn't know much about his enemy. They agreed Radewoosh will choose two distinct elements, let's denote them as $x$ and $y$. Limak will be allowed to use both his and Radewoosh's machines. He may use zero or more (maybe even all) machines to achieve the goal, each machine at most once. Limak will start from an element $x$ and his task will be to first get an element $y$ and then to again get an element $x$ — \\textbf{then we say that he succeeds}. After that Radewoosh would agree that Limak knows the chemistry (and Radewoosh would go away).\n\nRadewoosh likes some particular non-empty set of favorite elements and he will choose $x, y$ from that set. Limak doesn't know exactly which elements are in the set and also he doesn't know what machines Radewoosh has. Limak has heard $q$ gossips (queries) though and each of them consists of Radewoosh's machines and favorite elements. For each gossip Limak wonders if he would be able to \\textbf{succeed} tomorrow for every pair $x, y$ chosen from the set of favorite elements. If yes then print \"YES\" (without the quotes). But if there exists a pair $(x, y)$ from the given set that Limak wouldn't be able to succeed then you should print \"NO\" (without the quotes).",
    "tutorial": "Task is about checking if after adding some edges to graph, some given subset of vertices will be in one biconnected component. Firstly, let's calculate biconnected components in the initial graph. For every vertex in each query we will replace it with index of its bicon-component (for vertices from subset and for edges endpoints). Now we have a forest. When we have a list of interesting vertices in a new graph (bicon-components of vertices from subset or edges) we can compress an entire forest, so it will containg at most 2 times more vertices than the list (from query) and will have simillar structure to forest. To do it, we sort vertices by left-right travelsal order and take LCA of every adjacent pair on the sorted list. If you have compressed forest, then you just have to add edges and calculate biconnected components normally, in linear time.",
    "code": "#include <bits/stdc++.h> using namespace std; int n, m, q; int p1, p2, p3, p4; vector < pair <int,int> > graph[1000007]; int l; int pre[1000007]; int low[1000007]; vector <int> vec; int bic[1000007]; int b; vector <int> bgraph[1000007]; int bpre[1000007]; int bpost[1000007]; int c; int conn[1000007]; int dis[1000007]; vector <int> jump[1000007]; vector <int> subset; vector < pair <int,int> > edges; int trans[1000007]; vector <int> sta; vector < pair <int,int> > ngraph[1000007]; int bic2[1000007]; int res; void dfs1(int v, int p) { l++; pre[v]=l; low[v]=l; sta.push_back(v); for (int i=0; i<graph[v].size(); i++) { if (graph[v][i].second==p) continue; if (pre[graph[v][i].first]) { low[v]=min(low[v], pre[graph[v][i].first]); } else { dfs1(graph[v][i].first, graph[v][i].second); low[v]=min(low[v], low[graph[v][i].first]); } } if (pre[v]==low[v]) { b++; while(sta.back()!=v) { bic[sta.back()]=b; sta.pop_back(); } bic[sta.back()]=b; sta.pop_back(); } } void dfs2(int v, int p) { l++; bpre[v]=l; conn[v]=c; jump[v].push_back(p); while(jump[v].back()) { p1=jump[v].size()-1; p2=jump[v].back(); jump[v].push_back(jump[p2][min(p1, (int)jump[p2].size()-1)]); } for (int i=0; i<bgraph[v].size(); i++) { if (bgraph[v][i]!=p) { dis[bgraph[v][i]]=dis[v]+1; dfs2(bgraph[v][i], v); } } l++; bpost[v]=l; } int lca(int v, int u) { if (conn[v]!=conn[u]) return 0; for (int i=jump[v].size()-1; i>=0; i--) { if (i<jump[v].size() && dis[jump[v][i]]>=dis[u]) { v=jump[v][i]; } } for (int i=jump[u].size()-1; i>=0; i--) { if (i<jump[u].size() && dis[jump[u][i]]>=dis[v]) { u=jump[u][i]; } } for (int i=jump[v].size()-1; i>=0; i--) { if (i<jump[v].size() && i<jump[u].size() && jump[v][i]!=jump[u][i]) { v=jump[v][i]; u=jump[u][i]; } } if (v!=u) v=jump[v][0]; return v; } bool comp(int v, int u) { return bpre[v]<bpre[u]; } void filtr() { vector <int> vec2=vec; vec.clear(); sort(vec2.begin(), vec2.end(), comp); for (int i=0; i<vec2.size(); i++) { if (!vec2[i]) continue; if (!i || vec2[i]!=vec2[i-1]) { vec.push_back(vec2[i]); } } } void dfs3(int v, int p) { l++; pre[v]=l; low[v]=l; sta.push_back(v); for (int i=0; i<ngraph[v].size(); i++) { if (ngraph[v][i].second==p) continue; if (pre[ngraph[v][i].first]) { low[v]=min(low[v], pre[ngraph[v][i].first]); } else { dfs3(ngraph[v][i].first, ngraph[v][i].second); low[v]=min(low[v], low[ngraph[v][i].first]); } } if (pre[v]==low[v]) { b++; while(sta.back()!=v) { bic2[sta.back()]=b; sta.pop_back(); } bic2[sta.back()]=b; sta.pop_back(); } } long long R; int rotate(int element) { element=(element+R)%n; if (element==0) element=n; return element; } int main() { scanf(\"%d%d%d\", &n, &m, &q); for (int i=1; i<=m; i++) { scanf(\"%d%d\", &p1, &p2); graph[p1].push_back(make_pair(p2, i)); graph[p2].push_back(make_pair(p1, i)); } for (int i=1; i<=n; i++) { if (!pre[i]) { dfs1(i, 0); } } for (int i=1; i<=n; i++) { for (int j=0; j<graph[i].size(); j++) { if (bic[i]!=bic[graph[i][j].first]) { bgraph[bic[i]].push_back(bic[graph[i][j].first]); } } } l=0; for (int i=1; i<=b; i++) { if (!bpre[i]) { c++; dfs2(i, 0); } } for (int h=1; h<=q; h++) { subset.clear(); edges.clear(); vec.clear(); scanf(\"%d%d\", &p1, &p2); while(p1--) { scanf(\"%d\", &p3); p3=rotate(p3); subset.push_back(bic[p3]); vec.push_back(bic[p3]); } while(p2--) { scanf(\"%d%d\", &p3, &p4); p3=rotate(p3); p4=rotate(p4); edges.push_back(make_pair(bic[p3], bic[p4])); vec.push_back(bic[p3]); vec.push_back(bic[p4]); } sort(vec.begin(), vec.end(), comp); for (int i=vec.size()-1; i; i--) { vec.push_back(lca(vec[i], vec[i-1])); } filtr(); c=vec.size(); for (int i=0; i<c; i++) { trans[vec[i]]=i+1; ngraph[i+1].clear(); pre[i+1]=0; low[i+1]=0; } l=0; sta.clear(); for (int i=0; i<c; i++) { while(!sta.empty() && bpost[vec[i]]>bpost[sta.back()]) { sta.pop_back(); } if (!sta.empty()) { l++; ngraph[trans[vec[i]]].push_back(make_pair(trans[sta.back()], l)); ngraph[trans[sta.back()]].push_back(make_pair(trans[vec[i]], l)); } sta.push_back(vec[i]); } sta.clear(); for (int i=0; i<edges.size(); i++) { l++; ngraph[trans[edges[i].first]].push_back(make_pair(trans[edges[i].second], l)); ngraph[trans[edges[i].second]].push_back(make_pair(trans[edges[i].first], l)); } b=0; l=0; for (int i=1; i<=c; i++) { if (!pre[i]) { dfs3(i, 0); } } res=1; for (int i=1; i<subset.size(); i++) { if (bic2[trans[subset[i]]]!=bic2[trans[subset[0]]]) { res=0; } } if (res) { printf(\"YES \"); R+=h; } else { printf(\"NO \"); } } return 0; }",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "641",
    "index": "A",
    "title": "Little Artem and Grasshopper",
    "statement": "Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.\n\nThe area looks like a strip of cells $1 × n$. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.",
    "tutorial": "We can just emulate grasshopper behavior and save all positions it visits. It is obvious that we will have no more than O(n) different positions. If grasshopper appears in the same position twice that means that there is a loop and the answer is INFINITE. Otherwise the answer is FINITE.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "641",
    "index": "B",
    "title": "Little Artem and Matrix",
    "statement": "Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.\n\nThat element can store information about the matrix of integers size $n × m$. There are $n + m$ inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from $1$ to $n$ from top to bottom, while columns are numbered with integers from $1$ to $m$ from left to right.\n\nArtem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of $q$ turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.\n\nArtem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.",
    "tutorial": "Let's have 2 matrices: a, idx. In a we will have NULL for cell if we don't know the value or the value. idx will be initialized with idx[i][j] = {i, j}; Then we need to emulate the process on matrix idx. If we have 3rd query we can set up the value in matrix a, because we know the original position of that cell keeping idx.",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "641",
    "index": "C",
    "title": "Little Artem and Dance",
    "statement": "Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.\n\nMore detailed, there are $n$ pairs of boys and girls standing in a circle. Initially, boy number $1$ dances with a girl number $1$, boy number $2$ dances with a girl number $2$ and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves:\n\n- Value $x$ and some direction are announced, and all boys move $x$ positions in the corresponding direction.\n- Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl $1$ swaps with the one who was dancing with the girl number $2$, while the one who was dancing with girl number $3$ swaps with the one who was dancing with the girl number $4$ and so one. It's guaranteed that $n$ is even.\n\nYour task is to determine the final position of each boy.",
    "tutorial": "The key in this problem is that order of all elements in odd positions and in even positions is the same. Let's say we have 2 arrays: [1, 3, 5, ...] and [2, 4, ...] (odd positions and even positions). Now if we call 2nd commands we just swap these 2 arrays, but order is the same. Obviously 1st command also keeps the order. By order I mean cyclic order (right neighbor is the same in cycle position). Let's just keep the position of 1st boy and 2nd boy. Now if we apply 1st operation we move it by X or -X. Second type of the query just swaps the positions. In the end we can construct the answer if we know positions of 1st and 2nd boys.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "641",
    "index": "D",
    "title": "Little Artem and Random Variable",
    "statement": "Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.\n\nConsider two dices. When thrown each dice shows some integer from $1$ to $n$ inclusive. For each dice the probability of each outcome is given (of course, their sum is $1$), and different dices may have different probability distributions.\n\nWe throw both dices simultaneously and then calculate values $max(a, b)$ and $min(a, b)$, where $a$ is equal to the outcome of the first dice, while $b$ is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for $max(a, b)$ and $min(a, b)$. That is, for each $x$ from $1$ to $n$ you know the probability that $max(a, b)$ would be equal to $x$ and the probability that $min(a, b)$ would be equal to $x$. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists.",
    "tutorial": "First, let's solve inverse problem: find minimum (maximum) of two distributions. Let's use the following formulas: P(a = k) = P(a <= k) - P(a <= k-1) P(max(a, b) <= k) = P(a <= k) * P(b <= k) For minimum: P(min(a, b) >= k) = P(a >= k) * P(b >= k) = (1 - P(a <= k-1)) *(1 - P(b <= k-1)) Now in our original problem minimum and maximum defines system of square equations for each pair P(a <= k), P(b <= k). Solving these equations we get P(a<=k), P(b<=k) = (u + v  \\pm  sqrt((u + v)^2 - 4u)) / 2, where u = P(max(a,b) <= k), v = P(min(a,b) <= k). Now we can notice that if there exists an answer, then there exists an answer when we chose the signs for each pair equally (check out this comment)",
    "tags": [
      "dp",
      "implementation",
      "math",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "641",
    "index": "E",
    "title": "Little Artem and Time Machine",
    "statement": "Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: \\underline{multiset}.\n\nArtem wants to create a basic multiset of integers. He wants these structure to support operations of three types:\n\n- Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer.\n- Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset.\n- Count the number of instances of the given integer that are stored in the multiset.\n\nBut what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example.\n\n- First Artem adds integer $5$ to the multiset at the $1$-st moment of time.\n- Then Artem adds integer $3$ to the multiset at the moment $5$.\n- Then Artem asks how many $5$ are there in the multiset at moment $6$. The answer is $1$.\n- Then Artem returns back in time and asks how many integers $3$ are there in the set at moment $4$. Since $3$ was added only at moment $5$, the number of integers $3$ at moment $4$ equals to $0$.\n- Then Artem goes back in time again and removes $5$ from the multiset at moment $3$.\n- Finally Artyom asks at moment $7$ how many integers $5$ are there in the set. The result is $0$, since we have removed $5$ at the moment $3$.\n\nNote that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.\n\nHelp Artem implement time travellers multiset.",
    "tutorial": "There are many ways to solve this problem. One of the ways was SQRT-decomposition. First let's compress all times. Now for each block in the decomposition we will store for each element the balance in that block. So to answer the query we need to calculate sum of balances from first block to the block before the one where our element is located and then just process all requests in the current block. Another way was to use data structure from std library, described here. For each element we have two trees: remove times and add times. Then by getting order of the time in remove and add tree we can calculate the answer.",
    "tags": [
      "data structures"
    ],
    "rating": 2000
  },
  {
    "contest_id": "641",
    "index": "F",
    "title": "Little Artem and 2-SAT",
    "statement": "Little Artem is a very smart programmer. He knows many different difficult algorithms. Recently he has mastered in \\underline{2-SAT} one.\n\nIn computer science, 2-satisfiability (abbreviated as \\underline{2-SAT}) is the special case of the problem of determining whether a conjunction (logical \\underline{AND}) of disjunctions (logical \\underline{OR}) have a solution, in which all disjunctions consist of no more than two arguments (variables). For the purpose of this problem we consider only \\underline{2-SAT} formulas where each disjunction consists of exactly two arguments.\n\nConsider the following \\underline{2-SAT} problem as an example: $(1x_{1}\\ \\mathrm{Ole}\\ x_{2})\\ \\mathrm{AND}\\ (x_{3}\\ \\mathrm{Olg}\\ 1x_{4})\\ \\mathrm{AND}\\ \\ldots\\ \\mathrm{AND}\\ (x_{2n-1}\\ \\mathrm{Olg}\\ x_{2n})$. Note that there might be negations in \\underline{2-SAT} formula (like for $x_{1}$ and for $x_{4}$).\n\nArtem now tries to solve as many problems with \\underline{2-SAT} as possible. He found a very interesting one, which he can not solve yet. Of course, he asks you to help him.\n\nThe problem is: given two \\underline{2-SAT} formulas $f$ and $g$, determine whether their sets of possible solutions are the same. Otherwise, find any variables assignment $x$ such that $f(x) ≠ g(x)$.",
    "tutorial": "Let's build for both 2-SAT formulas implication graph and let's find strong connected components in this graph. If both of the formulas are not satisfiable then the answer is SIMILAR. If only one formula is not satisfiable then we can find an answer for the second one and output it. Now, let's assume both formulas are satisfiable. Let's have a transitive closure for both of the graphs. Let's call the variable X fixed in the formula F if there is a path -> x or (x -> ). If there is a fixed variable in one formula, but not fixed in the other (or fixed but has other value) we can find the solution for that second formula with opposite value of that fixed variable - that will be an answer. If we could not find these variables, we can remove all of them. There is no fixed variables in the rest of them. Let's find an edge u->v, presented in one graph, but not presented in the other. Let's find the solution for formula without the edge with u = 1 and v = 0 (we always can find it). That is the answer.",
    "tags": [],
    "rating": 3000
  },
  {
    "contest_id": "641",
    "index": "G",
    "title": "Little Artem and Graph",
    "statement": "Little Artem is given a graph, constructed as follows: start with some $k$-clique, then add new vertices one by one, connecting them to $k$ already existing vertices that form a $k$-clique.\n\nArtem wants to count the number of spanning trees in this graph modulo $10^{9} + 7$.",
    "tutorial": "Let's define k-clique B the descendant of k-clique A, if B could be produced from A with the sequence of the following steps: add vertex to the clique, connected with all clique vertices in the graph description and remove exactly one other vertex. Let's calculate the DP with states (k-clique, separation its vertices to the components) - number of spanning forests int the graph, induced by the clique and all its descendants so that clique will be divided to different connected components according to the defined vertices separation (all of the rest vertices will be connected with some of these components). To calculate that we need to precalculate all separations from k to k+1 elements and transitions: 1) (separation of k+1 vertices) x (separation k+1 vertices) -> (separation k+1 vertices | null), transform pair of separations - forests to the set of connected components of their union or null if there appears a cycle. 2) (separation of k+1 vertices) x (vertex) -> (separation of k+1 vertices | null), transform forest to the new forest, generated by adding new edge from vertex to vertex k+1 (or null, if there appears a cycle) 3) (separation of k+1 vertices) -> (separation of k vertices | null), projecting the separation on the first k vertices (or null, if k+1-th vertex creates a separate component)",
    "code": "import java.io.*;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\n\npublic class k_tree {\n\n    final static long MOD = 1000000007;\n\n    private static long modPow(long x, long pow, long mod) {\n        long r = 1;\n        while (pow > 0) {\n            if (pow % 2 == 1) {\n                r = r * x % mod;\n            }\n            pow /= 2;\n            x = x * x % mod;\n        }\n        return r;\n    }\n\n    static class Graph {\n        int k;\n        int[][] es;\n    }\n\n    static class Partition {\n        int[] p;\n        long spanningTreesCache = 0;\n\n        public Partition(int[] p) {\n            this.p = p;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (this == o) {\n                return true;\n            }\n            if (o == null || getClass() != o.getClass()) {\n                return false;\n            }\n            return Arrays.equals(p, ((Partition) o).p);\n\n        }\n\n        @Override\n        public int hashCode() {\n            return Arrays.hashCode(p);\n        }\n\n        public long spanningTrees() {\n            if (spanningTreesCache == 0) {\n                int[] cnts = new int[p.length];\n                for (int i : p) {\n                    cnts[i]++;\n                }\n                spanningTreesCache = 1;\n                for (int i = 0; i < cnts.length; ++i) {\n                    if (cnts[i] > 1) {\n                        spanningTreesCache = spanningTreesCache * modPow(cnts[i], cnts[i] - 2, MOD) % MOD;\n                    }\n                }\n            }\n            return spanningTreesCache;\n        }\n    }\n\n    static class Partitions {\n        ArrayList<Partition> list = new ArrayList<>();\n        HashMap<Partition, Integer> index = new HashMap<>();\n\n        public Partitions(int k) {\n            genPartitions(0, 0, new int[k]);\n        }\n\n        private void genPartitions(int i, int m, int[] p) {\n            if (i == p.length) {\n                Partition par = new Partition(p.clone());\n                list.add(par);\n                index.put(par, index.size());\n                return;\n            }\n            for (p[i] = 0; p[i] <= m; ++p[i]) {\n                genPartitions(i + 1, Math.max(m, p[i] + 1), p);\n            }\n        }\n    }\n\n    static class Facet {\n        int[] vs;\n        long[] cs;\n\n        public Facet(int[] vs, Partitions pk) {\n            this.vs = vs;\n            cs = new long[pk.list.size()];\n            cs[cs.length - 1] = 1;\n        }\n\n        @Override\n        public boolean equals(Object o) {\n            if (this == o) {\n                return true;\n            }\n            if (o == null || getClass() != o.getClass()) {\n                return false;\n            }\n\n            Facet facet = (Facet) o;\n\n            return Arrays.equals(vs, facet.vs);\n\n        }\n\n        @Override\n        public int hashCode() {\n            return Arrays.hashCode(vs);\n        }\n    }\n\n    static class DSU {\n        int[] p, r;\n        int comps;\n\n        DSU(int n) {\n            p = new int[n];\n            r = new int[n];\n            comps = n;\n            for (int i = 0; i < n; ++i) {\n                p[i] = i;\n            }\n        }\n\n        int get(int i) {\n            if (p[i] != i) {\n                p[i] = get(p[i]);\n            }\n            return p[i];\n        }\n\n        void unite(int i, int j) {\n            i = get(i);\n            j = get(j);\n            if (i != j) {\n                if (r[i] < r[j]) {\n                    p[i] = j;\n                } else {\n                    p[j] = i;\n                }\n                if (r[i] == r[j]) {\n                    r[i]++;\n                }\n                comps--;\n            }\n        }\n    }\n\n    static long solveFast(Graph g) {\n        Partitions pk = new Partitions(g.k), pk1 = new Partitions(g.k + 1);\n        int[][][] transitions = new int[pk1.list.size()][pk.list.size()][g.k + 1];\n        int[][] eTransitions = new int[pk1.list.size()][g.k];\n        int[] reductions = new int[pk1.list.size()];\n        for (int u = 0; u < pk1.list.size(); u++) {\n            Partition pu = pk1.list.get(u);\n            for (int v = 0; v < pk.list.size(); v++) {\n                Partition pv = pk.list.get(v);\n                loop: for (int e = 0; e <= g.k; e++) {\n                    DSU dsu = new DSU(2 * g.k + 1);\n                    for (int i = 0, j = 0; i < g.k + 1; ++i) {\n                        if (i == e) {\n                            continue;\n                        }\n                        if (dsu.get(pu.p[i]) == dsu.get(pv.p[j] + g.k + 1)) {\n                            transitions[u][v][e] = -1;\n                            continue loop;\n                        }\n                        dsu.unite(pu.p[i], pv.p[j] + g.k + 1);\n                        j++;\n                    }\n                    int[] p = new int[g.k + 1];\n                    int[] col = new int[2 * g.k + 1];\n                    Arrays.fill(col, -1);\n                    int cols = 0;\n                    for (int i = 0; i < g.k + 1; ++i) {\n                        int c = dsu.get(pu.p[i]);\n                        if (col[c] == -1) {\n                            col[c] = cols++;\n                        }\n                        p[i] = col[c];\n                    }\n                    transitions[u][v][e] = pk1.index.get(new Partition(p));\n                }\n            }\n            for (int e = 0; e < g.k; e++) {\n                DSU dsu = new DSU(g.k + 1);\n                if (dsu.get(pu.p[e]) == dsu.get(pu.p[g.k])) {\n                    eTransitions[u][e] = -1;\n                    continue;\n                }\n                dsu.unite(pu.p[e], pu.p[g.k]);\n                int[] p = new int[g.k + 1];\n                int[] col = new int[2 * g.k + 1];\n                Arrays.fill(col, -1);\n                int cols = 0;\n                for (int i = 0; i < g.k + 1; ++i) {\n                    int c = dsu.get(pu.p[i]);\n                    if (col[c] == -1) {\n                        col[c] = cols++;\n                    }\n                    p[i] = col[c];\n                }\n                eTransitions[u][e] = pk1.index.get(new Partition(p));\n            }\n            int cLast = 0;\n            for (int i = 0; i < g.k + 1; ++i) {\n                if (pu.p[i] == pu.p[g.k]) {\n                    cLast++;\n                }\n            }\n            if (cLast == 1) {\n                reductions[u] = -1;\n            } else {\n                reductions[u] = pk.index.get(new Partition(Arrays.copyOf(pu.p, g.k)));\n            }\n        }\n        HashMap<Facet, Facet> facetsSet = new HashMap<>();\n        int[] f0ar = new int[g.k];\n        for (int i = 0; i < g.k; ++i) {\n            f0ar[i] = i;\n        }\n        Facet f0 = new Facet(f0ar, pk);\n        Arrays.fill(f0.cs, 0);\n        for (int u = 0; u < pk.list.size(); u++) {\n            f0.cs[u] = pk.list.get(u).spanningTrees();\n        }\n        facetsSet.put(f0, f0);\n        Facet[][] facets = new Facet[g.es.length][g.k];\n        for (int i = g.k; i < g.k + g.es.length; ++i) {\n            for (int e = 0; e < g.k; ++e) {\n                int[] far = new int[g.k];\n                for (int t = 0, it = 0; t < g.k; ++t) {\n                    if (t != e) {\n                        far[it++] = g.es[i - g.k][t];\n                    }\n                }\n                far[g.k - 1] = i;\n                facets[i - g.k][e] = new Facet(far, pk);\n                facetsSet.put(facets[i - g.k][e], facets[i - g.k][e]);\n            }\n        }\n        for (int i = g.k + g.es.length - 1; i >= g.k; --i) {\n            long[] d = new long[pk1.list.size()];\n            d[d.length - 1] = 1;\n            Facet fBase = facetsSet.get(new Facet(g.es[i - g.k], pk));\n            for (int e = 0; e <= g.k; ++e) {\n                Facet f = e < g.k ? facets[i - g.k][e] : fBase;\n                long[] d1 = new long[pk1.list.size()];\n                for (int u = 0; u < pk1.list.size(); ++u) {\n                    for (int v = 0; v < pk.list.size(); v++) {\n                        int w = transitions[u][v][e];\n                        if (w != -1) {\n                            d1[w] = (d1[w] + d[u] * f.cs[v]) % MOD;\n                        }\n                    }\n                }\n                d = d1;\n            }\n            for (int e = 0; e < g.k; ++e) {\n                long[] d1 = d.clone();\n                for (int u = 0; u < pk1.list.size(); ++u) {\n                    int w = eTransitions[u][e];\n                    if (w != -1) {\n                        d1[w] = (d1[w] + d[u]) % MOD;\n                    }\n                }\n                d = d1;\n            }\n            Arrays.fill(fBase.cs, 0);\n            for (int u = 0; u < pk1.list.size(); u++) {\n                int v = reductions[u];\n                if (v != -1) {\n                    fBase.cs[v] = (fBase.cs[v] + d[u]) % MOD;\n                }\n            }\n        }\n        return f0.cs[0];\n    }\n\n    public static void solve(Input in, PrintWriter out) throws IOException {\n        int n = in.nextInt(), k = in.nextInt();\n        Graph g = new Graph();\n        g.k = k;\n        g.es = new int[n - k][k];\n        for (int i = k; i < n; ++i) {\n            for (int j = 0; j < k; ++j) {\n                g.es[i - k][j] = in.nextInt() - 1;\n            }\n            Arrays.sort(g.es[i - g.k]);\n        }\n        out.println(solveFast(g));\n    }\n\n    public static void main(String[] args) throws IOException {\n        PrintWriter out = new PrintWriter(System.out);\n        solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);\n        out.close();\n    }\n\n    static class Input {\n        BufferedReader in;\n        StringBuilder sb = new StringBuilder();\n\n        public Input(BufferedReader in) {\n            this.in = in;\n        }\n\n        public Input(String s) {\n            this.in = new BufferedReader(new StringReader(s));\n        }\n\n        public String next() throws IOException {\n            sb.setLength(0);\n            while (true) {\n                int c = in.read();\n                if (c == -1) {\n                    return null;\n                }\n                if (\" \n\r\t\".indexOf(c) == -1) {\n                    sb.append((char)c);\n                    break;\n                }\n            }\n            while (true) {\n                int c = in.read();\n                if (c == -1 || \" \n\r\t\".indexOf(c) != -1) {\n                    break;\n                }\n                sb.append((char)c);\n            }\n            return sb.toString();\n        }\n\n        public int nextInt() throws IOException {\n            return Integer.parseInt(next());\n        }\n\n        public long nextLong() throws IOException {\n            return Long.parseLong(next());\n        }\n\n        public double nextDouble() throws IOException {\n            return Double.parseDouble(next());\n        }\n    }\n}",
    "tags": [],
    "rating": 2300
  },
  {
    "contest_id": "643",
    "index": "A",
    "title": "Bear and Colors",
    "statement": "Bear Limak has $n$ colored balls, arranged in one long row. Balls are numbered $1$ through $n$, from left to right. There are $n$ possible colors, also numbered $1$ through $n$. The $i$-th ball has color $t_{i}$.\n\nFor a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.\n\nThere are $\\textstyle{\\frac{n(n+1)}{2}}$ non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.",
    "tutorial": "We are going to iterate over all intervals. Let's first fix the left end of the interval and denote it by $i$. Now, we iterate over the right end $j$. When we go from $j$ to $j + 1$ then we get one extra ball with color $c_{j + 1}$. In one global array $cnt[n]$ we can keep the number of occurrences of each color (we can clear the array for each new $i$). We should increase by one $cnt[c_{j + 1}]$ and then check whether $c_{j + 1}$ becomes a new dominant color. But how to do it? Additionally, let's keep one variable $best$ with the current dominant color. When we go to $j + 1$ then we should whether $cnt[c_{j + 1}] > cnt[best]$ or ($cnt[c_{j + 1}] = = cnt[best]$ and $c_{j + 1} < best$). The second condition checks which color has smaller index (in case of a tie). And we must increase $answer[best]$ by one then because we know that $best$ is dominant for the current interval. At the end, print values $answer[1], answer[2], ..., answer[n]$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int nax = 5005;\nint t[nax], cnt[nax], answer[nax];\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &t[i]);\n\tfor(int low = 1; low <= n; ++low) {\n\t\tfor(int i = 1; i <= n; ++i)\n\t\t\tcnt[i] = 0;\n\t\tint best = 0;\n\t\tfor(int i = low; i <= n; ++i) {\n\t\t\tint val = t[i];\n\t\t\t++cnt[val];\n\t\t\tif(cnt[val] > cnt[best] || (cnt[val] == cnt[best] && val < best))\n\t\t\t\tbest = val;\n\t\t\t++answer[best];\n\t\t}\n\t}\n\tfor(int i = 1; i <= n; ++i) printf(\"%d \", answer[i]);\n\tputs(\"\");\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "643",
    "index": "B",
    "title": "Bear and Two Paths",
    "statement": "Bearland has $n$ cities, numbered $1$ through $n$. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.\n\nBear Limak was once in a city $a$ and he wanted to go to a city $b$. There was no direct connection so he decided to take a long walk, visiting each city \\textbf{exactly once}. Formally:\n\n- There is no road between $a$ and $b$.\n- There exists a sequence (path) of $n$ distinct cities $v_{1}, v_{2}, ..., v_{n}$ that $v_{1} = a$, $v_{n} = b$ and there is a road between $v_{i}$ and $v_{i + 1}$ for $i\\in\\{1,2,\\dots,n-1\\}$.\n\nOn the other day, the similar thing happened. Limak wanted to travel between a city $c$ and a city $d$. There is no road between them but there exists a sequence of $n$ distinct cities $u_{1}, u_{2}, ..., u_{n}$ that $u_{1} = c$, $u_{n} = d$ and there is a road between $u_{i}$ and $u_{i + 1}$ for $i\\in\\{1,2,\\dots,n-1\\}$.\n\nAlso, Limak thinks that there are at most $k$ roads in Bearland. He wonders whether he remembers everything correctly.\n\nGiven $n$, $k$ and four distinct cities $a$, $b$, $c$, $d$, can you find possible paths $(v_{1}, ..., v_{n})$ and $(u_{1}, ..., u_{n})$ to satisfy all the given conditions? Find any solution or print -1 if it's impossible.",
    "tutorial": "There is no solution if $n = 4$ or $k  \\le  n$. But for $n  \\ge  5$ and $k  \\ge  n + 1$ you can construct the following graph: Here, cities $(x1, x2, ..., x_{n - 4})$ denote other cities in any order you choose (cities different than $a, b, c, d$). You should print $(a, c, x1, x2, ..., x_{n - 4}, d, b)$ in the first line, and $(c, a, x1, x2, ..., x_{n - 4}, b, d)$ in the second line. Two not very hard challenges for you. Are you able to prove that the answer doesn't exist for $k = n$? Can you solve the problem if the four given cities don't have to be distinct but it's guaranteed that $a  \\neq  b$ and $c  \\neq  d$? 18286683",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main() {\n\tint n, k, a, b, c, d;\n\tscanf(\"%d%d%d%d%d%d\", &n, &k, &a, &b, &c, &d);\n\tif(k <= n || n <= 4) {\n\t\tputs(\"-1\");\n\t\treturn 0;\n\t}\n\tfor(int rep = 0; rep < 2; ++rep) {\n\t\tprintf(\"%d %d \", a, c);\n\t\tfor(int i = 1; i <= n; ++i)\n\t\t\tif(i != a && i != b && i != c && i != d)\n\t\t\t\tprintf(\"%d \", i);\n\t\tprintf(\"%d %d\\n\", d, b);\n\t\tswap(a, c);\n\t\tswap(b, d);\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 1600
  },
  {
    "contest_id": "643",
    "index": "C",
    "title": "Levels and Regions",
    "statement": "Radewoosh is playing a computer game. There are $n$ levels, numbered $1$ through $n$. Levels are divided into $k$ regions (groups). Each region contains some positive number of consecutive levels.\n\nThe game repeats the the following process:\n\n- If all regions are beaten then the game ends immediately. Otherwise, the system finds the first region with at least one non-beaten level. Let $X$ denote this region.\n- The system creates an empty bag for tokens. Each token will represent one level and there may be many tokens representing the same level.\n\n- For each already beaten level $i$ in the region $X$, the system adds $t_{i}$ tokens to the bag (tokens representing the $i$-th level).\n- Let $j$ denote the first non-beaten level in the region $X$. The system adds $t_{j}$ tokens to the bag.\n\n- Finally, the system takes a uniformly random token from the bag and a player starts the level represented by the token. A player spends one hour and beats the level, even if he has already beaten it in the past.\n\nGiven $n$, $k$ and values $t_{1}, t_{2}, ..., t_{n}$, your task is to split levels into regions. Each level must belong to exactly one region, and each region must contain non-empty consecutive set of levels. What is the minimum possible expected number of hours required to finish the game?",
    "tutorial": "When we repeat something and each time we have probability $p$ to succeed then the expected number or tries is $\\textstyle{\\frac{1}{p}}$, till we succeed. How to calculate the expected time for one region $[low, high]$? For each $i$ in some moment we will try to beat this level and then there will be $S = t_{low} + t_{low + 1} + ... + t_{i}$ tokens in the bag, including $t_{i}$ tokens allowing us to beat this new level. The probability to succeed is $\\frac{t_{i}}{\\mathbf{S}}$, so the expected time is $\\frac S{t_{i}}^{S}\\,=\\,\\frac{t_{l o w}}{t_{i}}\\,+\\,\\frac{t_{l o w}^{\\quad t_{l o w}+1}}{t_{i}}\\,+\\,\\cdot\\,\\cdot\\,\\cdot\\,+\\,\\frac{t_{i}}{t_{i}}\\nonumber\\,$. So, in total we should sum up values $\\scriptstyle{\\frac{t(t)}{t}}$ for $i < j$. Ok, we managed to understand the actual problem. You can now stop and try to find a slow solution in $O(n^{2} \\cdot k)$. Hint: use the dynamic programming. Now let's write formula for $dp[i][j]$, as the minimum over $l$ denoting the end of the previous region: $d p[i][j]=m a x_{l}\\Biggl(d p[l][j-1]+p r e[i]-p r e[l]-(r e v[i]-r e v[l])\\star s u m[l]\\Biggr)=$ $\\begin{array}{c}{{=p r e[i]+m a x_{l}\\biggl((1)*(d p[l][j-1]-p r e[l]+r e v[l]*s u m[l])+(-r e v[i])*}}\\\\ {{\\qquad\\qquad\\qquad\\qquad\\qquad(s u m[l])\\biggr)=}}\\end{array}$ $=p r e[i]+m a x_{l}\\left((1,-r e v[i])X(d p[l][j-1]-p r e[l]+r e v[l]+r e v[l]+s u m[l])\\right)$ So we can use convex hull trick to calculate it in $O(n \\cdot k)$. You should also get AC with a bit slower divide&conquer trick, if it's implemented carefully.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint n, k;\n \ndouble wcz;\n \nlong double sum[200007];\nlong double rev[200007];\nlong double pre[200007];\n \nlong double inf;\n \nlong double dpo[200007];\nlong double dpn[200007];\n \nlong double x[200007];\nlong double y[200007];\n \nint l;\nvector <int> sta;\n \ninline long double vec(int s, int a, int b)\n{\n    return (x[a]-x[s])*(y[b]-y[s])-(x[b]-x[s])*(y[a]-y[s]);\n}\n \nint main()\n{\n    inf=1000000000.0;\n    inf*=inf;\n    scanf(\"%d%d\", &n, &k);\n    for (int i=1; i<=n; i++)\n    {\n        scanf(\"%lf\", &wcz);\n        sum[i]=wcz;\n        pre[i]=pre[i-1]+sum[i-1]/sum[i]+1.0;\n        rev[i]=1.0/sum[i]+rev[i-1];\n        sum[i]+=sum[i-1];\n    }\n    for (int i=1; i<=n; i++)\n    {\n        dpn[i]=pre[i];\n    }\n    for (int h=2; h<=k; h++)\n    {\n        for (int i=0; i<=n; i++)\n        {\n            dpo[i]=dpn[i];\n            dpn[i]=pre[i];\n \n            x[i]=dpo[i]+rev[i]*sum[i]-pre[i];\n            y[i]=sum[i];\n        }\n        sta.clear();\n        l=0;\n        for (int i=1; i<=n; i++)\n        {\n            while(sta.size()>1 && vec(sta[sta.size()-2], sta[sta.size()-1], i-1)>=0)\n            sta.pop_back();\n            l=min(l, (int)sta.size()-1);\n            l=max(l, 0);\n            sta.push_back(i-1);\n            while(l+1<sta.size() && 1*x[sta[l+1]]-rev[i]*y[sta[l+1]]<=1*x[sta[l]]-rev[i]*y[sta[l]])\n            l++;\n            dpn[i]+=1*x[sta[l]]-rev[i]*y[sta[l]];\n        }\n    }\n    printf(\"%.10lf\\n\", (double)dpn[n]);\n    return 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "643",
    "index": "D",
    "title": "Bearish Fanpages",
    "statement": "There is a social website with $n$ fanpages, numbered $1$ through $n$. There are also $n$ companies, and the $i$-th company owns the $i$-th fanpage.\n\nRecently, the website created a feature called following. Each fanpage must choose exactly one other fanpage to follow.\n\nThe website doesn’t allow a situation where $i$ follows $j$ and at the same time $j$ follows $i$. Also, a fanpage can't follow itself.\n\nLet’s say that fanpage $i$ follows some other fanpage $j_{0}$. Also, let’s say that $i$ is followed by $k$ other fanpages $j_{1}, j_{2}, ..., j_{k}$. Then, when people visit fanpage $i$ they see ads from $k + 2$ distinct companies: $i, j_{0}, j_{1}, ..., j_{k}$. Exactly $t_{i}$ people subscribe (like) the $i$-th fanpage, and each of them will click exactly one add. For each of $k + 1$ companies $j_{0}, j_{1}, ..., j_{k}$, exactly $\\left\\lfloor{\\frac{t_{i}}{k+2}}\\right\\rfloor$ people will click their ad. Remaining $t_{i}-(k+1)\\cdot\\left\\lfloor{\\frac{t_{i}}{k+2}}\\right\\rfloor$ people will click an ad from company $i$ (the owner of the fanpage).\n\nThe total income of the company is equal to the number of people who click ads from this copmany.\n\nLimak and Radewoosh ask you for help. Initially, fanpage $i$ follows fanpage $f_{i}$. Your task is to handle $q$ queries of three types:\n\n- 1 i j — fanpage $i$ follows fanpage $j$ from now. It's guaranteed that $i$ didn't follow $j$ just before the query. Note an extra constraint for the number of queries of this type (below, in the Input section).\n- 2 i — print the total income of the $i$-th company.\n- 3 — print two integers: the smallest income of one company and the biggest income of one company.",
    "tutorial": "Let's say that every company has one parent (a company it follows). Also, every copmany has some (maybe empty) set of children. It's crucial that sets of children are disjoint. For each company let's keep (and always update) one value, equal to the sum of: It turns out that after each query only the above sum changes only for a few values. If $a$ starts to follows $b$ then you should care about $a, b, par[a], par[b], par[par[a]]$. And maybe $par[par[b]]$ and $par[par[par[a]]]$ if you want to be sure. You can stop reading now for a moment and analyze that indeed other companies will keep the same sum, described above. Ok, but so far we don't count the income coming from parent's fanpage. But, for each company we can store all its children in one set. All children have the same \"income from parent's fanpage\" because they have the same parent. So, in set you can keep children sorted by the sum described above. Then, we should always puts the extreme elements from sets in one global set. In the global set you care about the total income, equal to the sum described above and this new \"income from parent\". Check codes for details. The complexity should be $O((n+q)\\cdot\\log n)$, with big constant factor.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int nax = 1e6 + 5;\nint par[nax];\nll t[nax];\nmultiset<ll> BEST;\nll interior[nax]; // the income from my fanpage and my children's fanpages\n\t\t\t\t\t// (so, doesn't include income from my parent)\n \nstruct cmp {\n\tbool operator ()(int a, int b) {\n\t\tif(interior[a] != interior[b])\n\t\t\treturn interior[a] < interior[b];\n\t\treturn a < b;\n\t}\n};\n \nstruct Children {\n\tset<int,cmp> s;\n\tvector<ll> getBest() {\n\t\tvector<ll> ret;\n\t\tif(!s.empty())\n\t\t\tret.push_back(interior[*s.begin()]);\n\t\tif((int) s.size() >= 2) {\n\t\t\tauto it = s.end();\n\t\t\t--it;\n\t\t\tret.push_back(interior[*it]);\n\t\t}\n\t\treturn ret;\n\t}\n\tvoid insert(int a) {\n\t\ts.insert(a);\n\t}\n\tvoid erase(int a) {\n\t\ts.erase(a);\n\t}\n\tint degree; // not always equal to s.size(), to allow more comfortable updates\n} children[nax];\n \nll value_for_other(int a) {\n\treturn t[a] / (2 + children[a].degree);\n}\nll value_for_self(int a) {\n\treturn t[a] - (1 + children[a].degree) * value_for_other(a);\n}\n \nint main() {\n\tint n, q;\n\tscanf(\"%d%d\", &n, &q);\n\tfor(int i = 1; i <= n; ++i)\n\t\tscanf(\"%lld\", &t[i]);\n\tfor(int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &par[i]);\n\t\tchildren[par[i]].degree++;\n\t\tchildren[par[i]].insert(i);\n\t}\n\t\n\t// calculate initial values of interior[n]\n\tfor(int i = 1; i <= n; ++i) {\n\t\tchildren[par[i]].erase(i);\n\t\t\n\t\t// income from my fanpage\n\t\tinterior[i] = value_for_self(i);\n\t\t// and from children's fanpages\n\t\tfor(int x : children[i].s)\n\t\t\tinterior[i] += value_for_other(x);\n\t\t\t\t\n\t\tchildren[par[i]].insert(i);\n\t}\n\t\n\t// fill BEST\n\tfor(int i = 1; i <= n; ++i) {\n\t\tvector<ll> values = children[i].getBest();\n\t\tfor(ll value : values)\n\t\t\tBEST.insert(value + value_for_other(i));\n\t}\n\t\n\t// read and process queries\n\twhile(q--) {\n\t\tint type;\n\t\tscanf(\"%d\", &type);\n\t\tif(type == 1) {\n\t\t\tint a, b;\n\t\t\tscanf(\"%d%d\", &a, &b);\n\t\t\tset<int> interesting = set<int>{a, b, par[a], par[b], par[par[a]]};\n\t\t\tset<int> more = interesting;\n\t\t\tfor(int x : interesting) more.insert(par[x]);\n\t\t\t\n\t\t\tfor(int x : more) {\n\t\t\t\tvector<ll> values = children[x].getBest();\n\t\t\t\tfor(ll value : values) {\n\t\t\t\t\tauto it = BEST.find(value + value_for_other(x));\n\t\t\t\t\tassert(it != BEST.end());\n\t\t\t\t\tBEST.erase(it);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor(int x : interesting)\n\t\t\t\tchildren[par[x]].erase(x);\n\t\t\t\n\t\t\tfor(int rep = -1; rep <= 1; rep += 2) { // first -1, then 1\n\t\t\t\tfor(int x : interesting) {\n\t\t\t\t\tinterior[x] += rep * value_for_self(x);\n\t\t\t\t\tfor(int y : interesting)\n\t\t\t\t\t\tif(par[y] == x)\n\t\t\t\t\t\t\tinterior[x] += rep * value_for_other(y);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(rep == -1) {\n\t\t\t\t\tchildren[par[a]].degree--;\n\t\t\t\t\tpar[a] = b;\n\t\t\t\t\tchildren[par[a]].degree++;\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tfor(int x : interesting)\n\t\t\t\tchildren[par[x]].insert(x);\n\t\t\t\n\t\t\tfor(int x : more) {\n\t\t\t\tvector<ll> values = children[x].getBest();\n\t\t\t\tfor(ll value : values)\n\t\t\t\t\tBEST.insert(value + value_for_other(x));\n\t\t\t}\n\t\t}\n\t\telse if(type == 2) {\n\t\t\tint a;\n\t\t\tscanf(\"%d\", &a);\n\t\t\tprintf(\"%lld\\n\", interior[a] + value_for_other(par[a]));\n\t\t}\n\t\telse {\n\t\t\tprintf(\"%lld \", *BEST.begin());\n\t\t\tauto it = BEST.end();\n\t\t\t--it;\n\t\t\tprintf(\"%lld\\n\", *it);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [],
    "rating": 2900
  },
  {
    "contest_id": "643",
    "index": "E",
    "title": "Bear and Destroying Subtrees",
    "statement": "Limak is a little grizzly bear. He will once attack Deerland but now he can only destroy trees in role-playing games. Limak starts with a tree with one vertex. The only vertex has index $1$ and is a root of the tree.\n\nSometimes, a game chooses a subtree and allows Limak to attack it. When a subtree is attacked then each of its edges is destroyed with probability $\\textstyle{\\frac{1}{2}}$, independently of other edges. Then, Limak gets the penalty — an integer equal to the height of the subtree after the attack. The height is defined as the maximum number of edges on the path between the root of the subtree and any vertex in the subtree.\n\nYou must handle queries of two types.\n\n- 1 v denotes a query of the first type. A new vertex appears and its parent is $v$. A new vertex has the next available index (so, new vertices will be numbered $2, 3, ...$).\n- 2 v denotes a query of the second type. For a moment let's assume that the game allows Limak to attack a subtree rooted in $v$. Then, what would be the expected value of the penalty Limak gets after the attack?\n\nIn a query of the second type, Limak doesn't actually attack the subtree and thus the query doesn't affect next queries.",
    "tutorial": "Let $dp[v][h]$ denote the probability that subtree $v$ (if attacked now) would have height at most $h$. The first observation is that we don't care about big $h$ because it's very unlikely that a path with e.g. 100 edges will survive. Let's later talk about choosing $h$ and now let's say that it's enough to consider $h$ up to $60$. When we should answer a query for subtree $v$ then we should sum up $h \\cdot (dp[v][h] - dp[v][h - 1])$ to get the answer. The other query is harder. Let's say that a new vertex is attached to vertex $v$. Then, among $dp[v][0], dp[v][1], dp[v][2], ...$ only $dp[v][0]$ changes (other values stay the same). Also, one value $dp[par[v]][1]$ changes, and so does $dp[par[par[v]]][2]$ and so on. You should iterate over $MAX_H$ vertices (each time going to parent) and update the corresponding value. TODO - puts here come formula for updating value. The complexity is $O(q \\cdot MAX_H)$. You may think that $MAX_H = 30$ is enough because $\\frac{1}{2^{3}/0}$ is small enough. Unfortunately, there exist malicious tests. Consider a tree with $\\stackrel{N}{\\mathrm{3I}}$ paths from root, each with length $31$. Now, we talk about the probability of magnitude: $1 - (1 - (1 / 2)^{d})^{N / d}$ which is more than $10^{ - 6}$ for $d = 30$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint q;\n \nint n=1;\n \nint par[500007];\n \nint d=60;\n \ndouble dp[500007][63];\n \nint p1, p2;\n \nvector <int> sta;\n \nvoid ans(int v)\n{\n    double res=0.0;\n    for (int i=1; i<=d; i++)\n    {\n        res+=1.0-dp[v][i];\n    }\n    printf(\"%.10lf\\n\", res);\n}\n \nvoid add(int v)\n{\n    n++;\n    par[n]=v;\n    sta.clear();\n    v=n;\n    for (int i=1; i<=d; i++)\n    {\n        dp[n][i]=1.0;\n    }\n    for (int i=1; i<=d+1 && v; i++)\n    {\n        sta.push_back(v);\n        v=par[v];\n    }\n    for (int i=(int)sta.size()-2; i>0; i--)\n    {\n        dp[sta[i+1]][i+1]/=(dp[sta[i]][i]+1.0)/2.0;\n    }\n    for (int i=0; i+1<(int)sta.size(); i++)\n    {\n        dp[sta[i+1]][i+1]*=(dp[sta[i]][i]+1.0)/2.0;\n    }\n}\n \nint main()\n{\n    scanf(\"%d\", &q);\n    for (int i=1; i<=d; i++)\n    {\n        dp[1][i]=1.0;\n    }\n    while(q--)\n    {\n        scanf(\"%d%d\", &p1, &p2);\n        if (p1==1)\n        add(p2);\n        else\n        ans(p2);\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "643",
    "index": "F",
    "title": "Bears and Juice",
    "statement": "There are $n$ bears in the inn and $p$ places to sleep. Bears will party together for some number of nights (and days).\n\nBears love drinking juice. They don't like wine but they can't distinguish it from juice by taste or smell.\n\nA bear doesn't sleep unless he drinks wine. A bear must go to sleep a few hours after drinking a wine. He will wake up many days after the party is over.\n\nRadewoosh is the owner of the inn. He wants to put some number of barrels in front of bears. One barrel will contain wine and all other ones will contain juice. Radewoosh will challenge bears to find a barrel with wine.\n\nEach night, the following happens in this exact order:\n\n- Each bear must choose a (maybe empty) set of barrels. The same barrel may be chosen by many bears.\n- Each bear drinks a glass from each barrel he chose.\n- All bears who drink wine go to sleep (exactly those bears who chose a barrel with wine). They will wake up many days after the party is over. If there are not enough places to sleep then bears lose immediately.\n\nAt the end, if it's sure where wine is and there is at least one awake bear then bears win (unless they have lost before because of the number of places to sleep).\n\nRadewoosh wants to allow bears to win. He considers $q$ scenarios. In the $i$-th scenario the party will last for $i$ nights. Then, let $R_{i}$ denote the maximum number of barrels for which bears surely win if they behave optimally. Let's define $X_{i}=(i\\cdot R_{i})\\ \\ \\mathrm{mod}\\ 2^{32}$. Your task is to find $X_{1}\\oplus X_{2}\\oplus\\cdot\\cdot\\Leftrightarrow X_{q}$, where $\\mathbb{C}$ denotes the exclusive or (also denoted as XOR).\n\nNote that the same barrel may be chosen by many bears and all of them will go to sleep at once.",
    "tutorial": "Let's start with $O(q \\cdot p^{2})$ approach, with the dynamic programming. Let $dp[days][beds]$ denote the maximum number of barrels to win if there are $days$ days left and $beds$ places to sleep left. Then: $d p[d a y s][b e d s]=\\sum_{i}d p[d a y s-1][b e d s-i]\\cdot C(n-(p-b e d s),i)$ Here, $i$ represents the number of bears who will go to sleep. If the same $i$ bears drink from the same $X$ barrels and this exact set of bears go to sleep then on the next day we only have $X$ barrels to consider (wine is in one of them). And for $X = dp[days - 1][beds - i]$ we will manage to find the wine then. And how to compute the dp faster? Organizers have ugly solution with something similar to meet in the middle. We calculate dp for first $q^{2 / 3}$ days and later we use multiply vectors by matrix, to get further answers faster. The complexity is equivalent to $O(p \\cdot q)$ but only because roughly $q = p^{3}$. We saw shortest codes though. How to do it guys? You may wonder why there was $2^{32}$ instead of $10^{9} + 7$. It was to fight with making the brute force faster. For $10^{9} + 7$ you could add $sum + = dp[a][b] \\cdot dp[c][d]$ about $15$ times (using unsigned long long's) and only then compute modulo. You would then get very fast solution.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \ntypedef unsigned int T;\n \nT C(T a, T b) {\n\tassert(a >= b && b >= 0);\n\tvector<T> w;\n\tfor(T i = 0; i < b; ++i)\n\t\tw.push_back(a - i);\n\tfor(T i = 1; i <= b; ++i) {\n\t\tT x = i;\n\t\tfor(T & y : w) {\n\t\t\tT g = __gcd(x, y);\n\t\t\tx /= g;\n\t\t\ty /= g;\n\t\t}\n\t\tassert(x == 1);\n\t}\n\tT ans = 1;\n\tfor(T x : w) ans *= x;\n\treturn ans;\n}\n \nconst T MAX_P = 132;\nconst T MAX_Q = 2000 * 1000 + 5;\nconst T magic = 1024 * 16;\n \nstruct M {\n\tT t[MAX_P][MAX_P];\n\tT p;\n\tM operator * (M other) {\n\t\tM ans;\n\t\tans.p = p;\n\t\t#define FOR(i) for(T i = 0; i <= p; ++i)\n\t\tFOR(i) FOR(j) ans.t[i][j] = 0;\n\t\tFOR(i) FOR(j) FOR(k)\n\t\t\tans.t[i][k] += t[i][j] * other.t[j][k];\n\t\treturn ans;\n\t}\n};\n \n \nM matrices[MAX_Q / magic + 1];\nT dp[magic][MAX_P], memo_C[MAX_P][MAX_P];\n \nint main() {\n    ios_base :: sync_with_stdio(false);\n\tT n, p, q;\n\tcin >> n >> p >> q;\n\tp = min(p, n - 1); // we allow at most n-1 bears to go to sleep\n\t\n\tfor(T beds = 0; beds <= p; ++beds)\n\t\tfor(T i = 0; i <= beds; ++i)\n\t\t\tmemo_C[beds][i] = C(n-(p-beds), i);\n\t\n\t// compute matrices\n\t\n\tfor(T i = 0; i <= p; ++i)\n\t\tmatrices[0].t[i][i] = 1;\n\t\n\tM & basic = matrices[1];\n\tbasic.p = p;\n\t\n\tfor(T beds = 0; beds <= p; ++beds)\n\t\tfor(T i = 0; i <= beds; ++i)\n\t\t\tbasic.t[beds-i][beds] = memo_C[beds][i];\n\t\n\tfor(T i = 1; i < magic; i *= 2)\n\t\tbasic = basic * basic;\n\t\n\tfor(T i = 2; i <= q / magic; ++i)\n\t\tmatrices[i] = matrices[1] * matrices[i-1];\n\t\n\t// compute first vectors\n\t\n\tfor(T beds = 0; beds <= p; ++beds)\n\t\tdp[0][beds] = 1;\n\t\n\tfor(T day = 1; day < magic; ++day)\n\t\tfor(T beds = 0; beds <= p; ++beds)\n\t\t\tfor(T i = 0; i <= beds; ++i) {\n\t\t\t\tT & x = dp[day][beds];\n\t\t\t\tx += dp[day-1][beds-i] * memo_C[beds][i];\n\t\t\t}\n\tT hashed;\n\tfor(T i = 1; i <= q; ++i) {\n\t\tT i_dp = i % magic;\n\t\tT i_matr = i / magic;\n\t\tT ans = 0;\n\t\tfor(T beds = 0; beds <= p; ++beds)\n\t\t\tans += dp[i_dp][beds] * matrices[i_matr].t[beds][p];\n\t\thashed ^= i * ans;\n\t}\n\tcout << hashed << \"\\n\";\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 2900
  },
  {
    "contest_id": "643",
    "index": "G",
    "title": "Choosing Ads",
    "statement": "One social network developer recently suggested a new algorithm of choosing ads for users.\n\nThere are $n$ slots which advertisers can buy. It is possible to buy a segment of consecutive slots at once. The more slots you own, the bigger are the chances your ad will be shown to users.\n\nEvery time it is needed to choose ads to show, some segment of slots is picked by a secret algorithm. Then some advertisers are chosen. The only restriction is that it should be guaranteed for advertisers which own at least $p$% of slots composing this segment that their ad will be shown.\n\nFrom the other side, users don't like ads. So it was decided to show no more than $\\left|{\\frac{100}{p}}\\right|$ ads at once. You are asked to develop a system to sell segments of slots and choose ads in accordance with the rules described above.",
    "tutorial": "Let's first consider a solution processing query in O(n) time, but using O(1) extra memory. If p = 51%, it's a well known problem. We should store one element and some balance. When processing next element, if it's equal to our, we increase balance. If it's not equal, and balance is positive, we decrease it. If it is zero, we getting new element as stored, and setting balance to 1. To generalize to case of elements, which are at least 100/k%, we will do next. Let's store k elements with balance for each. When getting a new element, if it's in set of our 5, we will add 1 to it's balance. If we have less, than 5 elements, just add new element with balance 1. Else, if there is element with balance 0, replace it by new element with balance one. Else, subtract 1 from each balance. The meaning of such balance becomes more mysterious, but it's not hard to check, that value is at least 100/k% of all elements, it's balance will be positive. To generalize even more, we can join two of such balanced set. To do that, we sum balances of elements of all sets, than join sets to one, and then removing elements with smallest balance one, by one, untill there is k elements in set. To remove element, we should subtract it's balance from all other balances. And now, we can merge this sets on segment, using segment tree. This solution will have complexity like $n * log(n) * MERGE$, where MERGE is time of merging two structures. Probably, when k is 5, $k^{2} / 2$ is fastest way. But the profit is we don't need complex structures to check which elements are really in top, so solution works much faster.",
    "tags": [
      "data structures"
    ],
    "rating": 3200
  },
  {
    "contest_id": "645",
    "index": "A",
    "title": "Amity Assessment",
    "statement": "Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a $2 × 2$ grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:\n\nIn order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.",
    "tutorial": "One solution is to just brute force and use DFS to try all the possibilities. Alternatively, note that two puzzles can be changed to each other if and only if the $A$, $B$, and $C$ have the same orientation-clockwise or counterclockwise-in the puzzle. A third option, since the number of possibilities is so small, is to simply classify all of the $4! = 24$ configurations by hand.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nstring b, b1, b2, e, e1, e2;\n\nint main(){\n  cin >> b1 >> b2 >> e1 >> e2;\n  swap(b2[0], b2[1]);\n  swap(e2[0], e2[1]);\n  b = b1 + b2;\n  e = e1 + e2;\n  b.erase(b.find('X'), 1);\n  e.erase(e.find('X'), 1);\n  if((b + b).find(e) != string::npos){\n\tcout << \"YESn\";\n  } else {\n\tcout << \"NOn\";\n  }\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "645",
    "index": "B",
    "title": "Mischievous Mess Makers",
    "statement": "It is a balmy spring afternoon, and Farmer John's $n$ cows are ruminating about link-cut cacti in their stalls. The cows, labeled $1$ through $n$, are arranged so that the $i$-th cow occupies the $i$-th stall from the left. However, Elsie, after realizing that she will forever live in the shadows beyond Bessie's limelight, has formed the Mischievous Mess Makers and is plotting to disrupt this beautiful pastoral rhythm. While Farmer John takes his $k$ minute long nap, Elsie and the Mess Makers plan to repeatedly choose two distinct stalls and swap the cows occupying those stalls, making \\textbf{no more than one} swap each minute.\n\nBeing the meticulous pranksters that they are, the Mischievous Mess Makers would like to know the maximum messiness attainable in the $k$ minutes that they have. We denote as $p_{i}$ the label of the cow in the $i$-th stall. The messiness of an arrangement of cows is defined as the number of pairs $(i, j)$ such that $i < j$ and $p_{i} > p_{j}$.",
    "tutorial": "Loosely speaking, we're trying to reverse the array as much as possible. Intuitively, the optimal solution seems to be to switch the first and last cow, then the second and second-to-last cow, and so on for $k$ minutes, unless the sequence is reversed already, in which case we are done. But how can we show that these moves give the optimal messiness? It is clear when $2 \\cdot k  \\ge  n - 1$ that we can reverse the array with this method. However, when $2 \\cdot k < n - 1$, there are going to be cows that we must not have not moved a single time. Since in each move we swap at most $2$ cows, there must be at least $n - 2 \\cdot k$ cows that we have not touched, with $p_{i} = i$. Two untouched cows $i$ and $j$ must have $p_{i} < p_{j}$, so there must be at least $\\frac{(n-2\\cdot k)(n-2\\cdot k-1)}{2}$ pairs of cows which are ordered correctly. In fact, if we follow the above process, we get that $p_{i} = (n + 1) - i$ for the first $k$ and last $k$ cows, while $p_{i} = i$ for the middle $n - 2 \\cdot k$ cows. From this we can see that the both $i < j$ and $p_{i} < p_{j}$ happen only when $i$ and $j$ are in the middle $n - 2 \\cdot k$ cows. Therefore we know our algorithm is optimal. An $O(k)$ solution, therefore, is to count how many incorrectly ordered pairs $(i, j)$ are created at each step and add them up. When we swap cow $i$ and $(n + 1) - i$ in step $i$, this creates $1 + 2 \\cdot (n - 2i)$ more pairs. So the answer will be $\\textstyle\\sum_{i=1}^{k}1+2(n-2i)$. We can reduce this to $O(1)$ by using our earlier observation, that every pair except those $\\frac{(n-2\\cdot k)(n-2\\cdot k-1)}{2}$ pairs are unordered, which gives ${\\frac{n(n-1)}{2}}-{\\frac{(n-2\\cdot k)(n-2\\cdot k-1)}{2}}$ total pairs $(i, j)$. Note that this does always not fit in a 32-bit integer.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\n\nint main(){\n\tLL n, k;\n\tcin >> n >> k;\n\tLL c = max(n-2*k,0LL);\n\tLL a = n*(n-1)/2-c*(c-1)/2;\n\tcout << a << endl;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "645",
    "index": "C",
    "title": "Enduring Exodus",
    "statement": "In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his $k$ cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of $n$ rooms located in a row, some of which are occupied.\n\nFarmer John wants to book a set of $k + 1$ currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms $i$ and $j$ is defined as $|j - i|$. Help Farmer John protect his cows by calculating this minimum possible distance.",
    "tutorial": "First, observe that the $k + 1$ rooms that Farmer John books should be consecutive empty rooms. Thus we can loop over all such sets of rooms with a sliding window in linear time. To check the next set of rooms, we simply advance each endpoint of our interval to the next empty room. Every time we do this, we need to compute the optimal placement of Farmer John's room. We can maintain the position of his room with two pointers-as we slide our window of rooms to the right, the optimal position of Farmer John's room should always move to the right or remain the same. This solution runs in $O(n)$. Alternatively, we can use binary search or an STL set to find the best placement for Farmer John's room as we iterate over the intervals of rooms. The complexity of these approaches is $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint N, K, res = 1e9;\nstring S;\n\nint next(int i){ // finds the next empty room\n  do {\n    i += 1;\n  } while(i < N && S[i] == '1');\n  return i;\n}\n\nint main(){\n  cin >> N >> K >> S;\n  int l = next(-1), m = l, r = l;\n  for(int i = 0; i < K; i++){ // sets up the sliding window\n    r = next(r);\n  }\n  while(r < N){\n    while(max(m - l, r - m) > max(next(m) - l, r - next(m))){\n      m = next(m);\n    }\n    res = min(res, max(m - l, r - m));\n    l = next(l);\n    r = next(r);\n  }\n  cout << res << 'n';\n}",
    "tags": [
      "binary search",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "645",
    "index": "D",
    "title": "Robot Rapping Results Report",
    "statement": "While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot $i$ will beat robot $j$ if and only if robot $i$ has a higher skill level than robot $j$. And if robot $i$ beats robot $j$ and robot $j$ beats robot $k$, then robot $i$ will beat robot $k$. Since rapping is such a subtle art, two robots can never have the same skill level.\n\nGiven the results of the rap battles in the order in which they were played, determine the \\textbf{minimum number} of first rap battles that needed to take place before Bessie could order all of the robots by skill level.",
    "tutorial": "The robots will become fully sorted if and only if there exists a path with $n$ vertices in the directed graph defined by the match results. Because it is guaranteed that the results are not contradictory, this graph must be directed and acyclic-a DAG. Thus we can compute the longest path in this DAG via dynamic programming or a toposort. We now have two cases. First, if the longest path contains $n$ vertices, then it must uniquely define the ordering of the robots. This means the answer is the time at which the last edge was added to this path. Otherwise, if the longest path has fewer than $n$ vertices, then multiple orderings satisfy the results and you should print $- 1$. Note that this algorithm runs in $O(n + m)$. Another solution to this problem binary searches on the answer. For some $k$, consider only those edges that were added before time $k$. We can determine if the robots could be totally ordered at time $k$ by running a toposort and checking if the longest path covers all $n$ vertices. This might be more intuitive for some, but has a complexity of $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 1000005;\nint N, M, dp[MAXN], res[MAXN];\nvector<pair<int,int>> adj[MAXN];\n\nint check(int v){\n  if(dp[v]) return dp[v];\n  dp[v] = 1;\n  for(auto p : adj[v]){\n    int n = p.first;\n    if(check(n) + 1 > dp[v]){\n      dp[v] = dp[n] + 1;\n      res[v] = max(res[n], p.second);\n    }\n  }\n  return dp[v];\n}\n\nint main(){\n  scanf(\"%d%d\", &N, &M);\n  for(int i = 0; i < M; i++){\n    int a, b;\n    scanf(\"%d%d\", &a, &b);\n    a -= 1, b -= 1;\n    adj[a].push_back({b, i + 1});\n  }\n  for(int i = 0; i < N; i++){\n    if(check(i) == N){\n      printf(\"%dn\", res[i]);\n      return 0;\n    }\n  }\n  printf(\"-1n\");\n}",
    "tags": [
      "binary search",
      "dp",
      "graphs"
    ],
    "rating": 1800
  },
  {
    "contest_id": "645",
    "index": "E",
    "title": "Intellectual Inquiry",
    "statement": "After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first $k$ English letters.\n\nEach morning, Bessie travels to school along a sidewalk consisting of $m + n$ tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first $m$ sidewalk tiles with one of the first $k$ lowercase English letters, spelling out a string $t$. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last $n$ tiles of the sidewalk by herself.\n\nConsider the resulting string $s$ ($|s| = m + n$) consisting of letters labeled on tiles in order from home to school. For any sequence of indices $p_{1} < p_{2} < ... < p_{q}$ we can define subsequence of the string $s$ as string $s_{p1}s_{p2}... s_{pq}$. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of \\textbf{distinct subsequences} of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!\n\nNote that empty subsequence also counts.",
    "tutorial": "For simplicity, let's represent the letters by $1, 2, ..., k$ instead of actual characters. Let $a[i]$ denote the number of distinct subsequences of the string that end in the letter $i$. Appending the letter $j$ to a string only changes the value of $a[j]$. Note that the new $a[j]$ becomes $1+\\sum_{i=1}^{k}a[i]$-we can have the single letter $j$, or append $j$ to any of our old subsequences. The key observation is that no matter what character $j$ we choose to append, $a[j]$ will always end up the same. This suggests a greedy algorithm-always appending the character $j$ with the smallest $a[j]$. But how do we know which $a[j]$ is minimal while maintaining their values modulo $10^{9} + 7$? The final observation is that if the last occurrence of $j$ is after the last occurrence of $j'$ in our string, then $a[j] > a[j']$. This is true because appending $j$ to the string makes $a[j]$ larger than all other $a[i]$. So instead of choosing the minimum $a[i]$, we can always choose the letter that appeared least recently. Since the sequence of letters we append becomes periodic, our solution runs in $O(L+n+k\\log k)$. Of course, we can also find the least recently used letter with less efficient approaches, obtaining solutions with complexity $O((L + n)k)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nconst ll MOD = 1000000007;\nconst int MAXK = 26;\nint N, K, last[MAXK], ord[MAXK];\nll dp[MAXK], sum;\nstring S;\n\nbool comp(int a, int b){\n  return last[a] < last[b];\n}\n\nvoid append(int c){\n  sum = (sum - dp[c] + MOD) % MOD;\n  dp[c] = (dp[c] + sum + 1) % MOD;\n  sum = (sum + dp[c]) % MOD;\n}\n\nint main(){\n  cin >> N >> K >> S;\n  fill(last, last + K, -1);\n  for(int i = 0; i < S.size(); i++){\n    int c = S[i] - 'a';\n    last[c] = i;\n    append(c);\n  }\n  iota(ord, ord + K, 0);\n  sort(ord, ord + K, comp);\n  for(int i = 0; i < N; i++){\n    int c = ord[i % K];\n    append(c);\n  }\n  cout << (sum + 1) % MOD << 'n';\n}",
    "tags": [
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "645",
    "index": "F",
    "title": "Cowslip Collections",
    "statement": "In an attempt to make peace with the Mischievious Mess Makers, Bessie and Farmer John are planning to plant some flower gardens to complement the lush, grassy fields of Bovinia. As any good horticulturist knows, each garden they plant must have the exact same arrangement of flowers. Initially, Farmer John has $n$ different species of flowers he can plant, with $a_{i}$ flowers of the $i$-th species.\n\nOn each of the next $q$ days, Farmer John will receive a batch of flowers of a new species. On day $j$, he will receive $c_{j}$ flowers of the same species, but of a different species from those Farmer John already has.\n\nFarmer John, knowing the right balance between extravagance and minimalism, wants exactly $k$ species of flowers to be used. Furthermore, to reduce waste, each flower of the $k$ species Farmer John chooses must be planted in some garden. And each of the gardens must be identical; that is to say that each of the $k$ chosen species should have an equal number of flowers in each garden. As Farmer John is a proponent of national equality, he would like to create the greatest number of gardens possible.\n\nAfter receiving flowers on each of these $q$ days, Farmer John would like to know the sum, over all possible choices of $k$ species, of the maximum number of gardens he could create. Since this could be a large number, you should output your result modulo $10^{9} + 7$.",
    "tutorial": "After each query, the problem is essentially asking us to compute the sum of $\\mathrm{gcd}(f_{1},f_{2},\\cdot\\cdot\\cdot\\,,f_{k})$ for each choice of $k$ flowers. One quickly notes that it is too slow to loop over all choices of $k$ flowers, as there could be up to $\\binom{n+q}{k}$ choices of $k$ species. So how can we compute a sum over $\\binom{n+q}{k}$ terms? Well, we will definitely need to use the properties of the gcd function. If we figure out for each integer $a  \\le  10^{6}$ how many times $\\operatorname{gcd}(f_{1},f_{2},\\cdot\\cdot\\cdot,f_{k})=a$ occurs in the sum (let this be $g(a)$), then our answer will be equal to $\\sum_{a}a\\cdot g(a)$ overall all $a$. It seems that if $d(a)$ is the number of multiples of $a$ in our sequence, then there are $\\binom{d(a)}{k}$ $k$-tuples which have gcd $a$. Yet there is something wrong with this reasoning: some of those $k$-tuples can have gcd $2a$, or $3a$, or any multiple of $a$. In fact, ${\\binom{d(a)}{k}}=\\sum_{a\\bar{|m|}}g(m)$, the number of gcds which are a multiple of $a$. We will try to write $\\sum_{a}a\\cdot g(a)$ as a sum of these $\\sum_{a|m}g(m)$. We'll take an example, when $a$ ranges from $1$ to $4$. The sum we wish to compute is $g(1) + 2g(2) + 3g(3) + 4g(4)$ which can be written as $(g(1) + g(2) + g(3) + g(4)) + (g(2) + g(4)) + 2(g(3)) + 2(g(4)),$ or $\\sum_{1i m}g(m)+\\sum_{2|m}g(m)+2\\sum_{3i m}g(m)+2\\sum_{4|m}g(m).$ In general, we want to find coefficients $p_{i}$ such that we can write $\\sum_{a}a\\cdot g(a)$ as $\\sum_{i}p_{i}\\left(\\sum_{i\\vert m}g(m)\\right)=\\sum_{i}p_{i}\\biggl(\\stackrel{d(i)}{k}\\biggr)$. Equating coefficients of $g(a)$ on both sides, we get that $a=\\sum_{i\\lfloor a}p_{i}$. (The mathematically versed reader will note that $p_{i} =  \\phi (i)$, Euler's totient function, but this is not necessary to solve the problem.) We can thus precalculate all $p_{i}$ in $O(A\\log(A))$ using a recursive formula: $p_{i}=a-\\sum_{i\\vert a.i\\neq a}p_{i}$. We can also precalculate $\\binom{l}{k}$ for each $l  \\le  200000$, so in order to output $\\sum_{i=1}^{100000}p_{i}{\\binom{d(i)}{k}}$ after each query we should keep track of the values of the function $d(i)$, the number of multiples of $i$. When receiving $c_{i}$ flowers, we only need to update $d$ for the divisors of $c_{i}$ and add ${\\binom{d+1}{k}}-{\\binom{d}{k}}$. If we precompute the list of divisors of every integer using a sieve or sqrt checking, each update requires $O(divisors)$. Thus the complexity of this algorithm is $O(A\\log A)$ or $O(A{\\sqrt{A}})$ preprocessing, and $O((n + q) \\cdot max(divisors))$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nconst ll MOD = 1000000007;\nconst int MAXN = 200005;\nconst int MAXA = 1000005;\nint N, K, Q, A[MAXN];\nint use[MAXA], phi[MAXA], cnt[MAXA];\nvector<int> divisors[MAXA];\nll bin[MAXN], res;\n\nll inv(ll a, ll p){\n  if(a == 1) return 1;\n  return (p - p / a) * inv(p % a, p) % p;\n}\n\nvoid read(){\n  scanf(\"%d%d%d\", &N, &K, &Q);\n  for(int i = 0; i < N + Q; i++){\n    scanf(\"%d\", &A[i]);\n    use[A[i]] = 1;\n  }\n}\n\nvoid init(){\n  iota(phi, phi + MAXA, 0);\n  for(int i = 1; i < MAXA; i++){\n    for(int j = i; j < MAXA; j += i){\n      if(i != j) phi[j] -= phi[i];\n      if(use[j]) divisors[j].push_back(i);\n    }\n  }\n  bin[K - 1] = 1;\n  for(int i = K; i < MAXN; i++){\n    bin[i] = bin[i - 1] * i % MOD * inv(i - K + 1, MOD) % MOD;\n  }\n}\n\nint main(){\n  read();\n  init();\n  for(int i = 0; i < N + Q; i++){\n    for(int d : divisors[A[i]]){\n      res = (res + bin[cnt[d]] * phi[d]) % MOD;\n      cnt[d] += 1;\n    }\n    if(i >= N){\n      printf(\"%dn\", res);\n    }\n  }\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "645",
    "index": "G",
    "title": "Armistice Area Apportionment",
    "statement": "After a drawn-out mooclear arms race, Farmer John and the Mischievous Mess Makers have finally agreed to establish peace. They plan to divide the territory of Bovinia with a line passing through at least two of the $n$ outposts scattered throughout the land. These outposts, remnants of the conflict, are located at the points $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$.\n\nIn order to find the optimal dividing line, Farmer John and Elsie have plotted a map of Bovinia on the coordinate plane. Farmer John's farm and the Mischievous Mess Makers' base are located at the points $P = (a, 0)$ and $Q = ( - a, 0)$, respectively. Because they seek a lasting peace, Farmer John and Elsie would like to minimize the maximum difference between the distances from any point on the line to $P$ and $Q$.\n\nFormally, define the \\textbf{difference} of a line ${\\mathit{l}}_{\\circ}$ relative to two points $P$ and $Q$ as the smallest real number $d$ so that for all points $X$ on line ${\\mathit{l}},$, $|PX - QX| ≤ d$. (It is guaranteed that $d$ exists and is unique.) They wish to find the line ${\\mathit{l}},$ passing through two distinct outposts $(x_{i}, y_{i})$ and $(x_{j}, y_{j})$ such that the difference of ${\\mathit{l}},$ relative to $P$ and $Q$ is minimized.",
    "tutorial": "First, let's try to solve the smaller case where we only have two points. Let ${\\mathit{l}},$ be the line passing through $x_{i}$ and $x_{j}$. We want to compute the difference of ${\\mathit{l}}_{\\circ}$ relative to $P$ and $Q$. Define $P'$ as the reflection of $P$ over ${\\mathit{l}},$. By the triangle inequality, we have $|PX - QX| = |P'X - QX|  \\le  P'Q$. Equality can be achieved when $X$, $P'$ and $Q$ are collinear-that is, when $X$ is the intersection of ${\\mathit{l}},$ and line $P'Q$. (If ${\\mathit{l}},$ and $P'Q$ are parallel, we can imagine that they intersect at infinity.) Therefore, the difference of a line ${\\mathit{l}},$ relative to $P$ and $Q$ is the distance from $P'$ to $Q$. We can also think about $P'$ in a different way. Let $C_{i}$ be the circle with center $x_{i}$ that pases through $P$. Then $P'$ is the second intersection of the two circles $C_{i}$ and $C_{j}$. Thus our problem of finding a line with minimum difference becomes equivalent to finding the intersection among ${C_{i}}$ that lies closest to $Q$. This last part we can do with a binary search. Consider the problem of checking if two circles $C_{i}$ and $C_{j}$ intersect at a point within a distance $r$ of $Q$. In other words, we wish to check if they intersect inside a circle $S$ of radius $r$ centered at $Q$. Let $A_{i}$ and $A_{j}$ be the arcs of $S$ contained by $C_{i}$ and $C_{j}$, respectively. Observe that $C_{i}$ and $C_{j}$ intersect inside the circle if and only if the two arcs overlap, but do not contain each other. Thus we can verify this condition for all pairs of points with a radial sweep line along the circle. Due to the binary search and the sorting necessary for the sweep line, this solution runs in $O(n\\log n\\log P)$, where $P$ is the precision required. One might also wonder if precision will be an issue with all the calculations that we're doing. It turns out that it won't be, since our binary search will always stabilize the problem and get us very close to the answer. Here's my original solution using a projective transformation: We begin by binary searching on the the minimum possible difference. Thus we wish to solve the decision problem \"Can a difference of $k$ be achieved?\" Consider the hyperbola $|PX - QX| = k$. Note that our answer is affirmative if and only if a pair of outposts defines a line that does not intersect the hyperbola. Our next step is a reduction to an equivalent decision problem on a circle through a projective transformation. We express this transformation as the composition of two simpler operations. The first is an affine map that takes the hyperbola $|PX - QX| = k$ to the unit hyperbola. The second maps homogenous coordinates $(x, y, z)$ to $(z, y, x)$. Under the latter, the unit hyperbola $x^{2} - y^{2} = z^{2}$ goes to the unit circle $x^{2} + y^{2} = z^{2}$. Because projective transformations preserve collinearity, a line intersecting the hyperbola is equivalent to a line intersecting the circle. Thus we want to know if any pair of the outposts' images defines a line that does not intersect the circle. We now map the image of each outpost to the minor arc on the unit circle defined by its tangents. (We disregard any points lying inside the circle.) Observe that our condition is equivalent to the existence of two intersecting arcs, neither of which contains the other. Verifying that two such arcs exist can be done with a priority queue and a radial sweep line in $O(n\\log n)$. The total complexity of our solution is therefore $O(n\\log n\\log P)$, where $P$ is the precision that we need. It turns out that the implementation of this algorithm is actually pretty neat:",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long double ld;\n\nconst ld EPS = 1e-12;\nconst ld PI = acos(-1);\nconst int MAXN = 100005;\nint N;\nld A, X[MAXN], Y[MAXN];\n\nbool check(ld m){\n  ld u = m / 2;\n  ld v = sqrt(A * A - u * u);\n  vector<pair<ld,ld>> ev;\n  for(int i = 0; i < N; i++){\n    ld x = 1, y = Y[i] / v, alpha;\n    if(X[i] != 0){\n      x *= u / X[i], y *= u / X[i];\n      ld r = sqrt(x * x + y * y);\n      if(r < 1) continue;\n      alpha = acos(1 / r);\n    } else {\n      alpha = PI / 2;\n    }\n    ld base = atan2(y, x) - alpha;\n    if(base < 0) base += 2 * PI;\n    ev.push_back({base, base + 2 * alpha});\n  }\n  priority_queue<ld, vector<ld>, greater<ld>> pq;\n  sort(ev.begin(), ev.end());\n  for(int i = 0; i < 2; i++){\n    for(int j = 0; j < ev.size(); j++){\n      while(pq.size() && pq.top() < ev[j].first) pq.pop();\n      if(pq.size() && pq.top() < ev[j].second) return 1;\n      pq.push(ev[j].second);\n      ev[j].first += 2 * PI;\n      ev[j].second += 2 * PI;\n    }\n  }\n  return 0;\n}\n\nint main(){\n  ios::sync_with_stdio(0);\n  cin >> N >> A;\n  for(int i = 0; i < N; i++){\n    cin >> X[i] >> Y[i];\n  }\n  ld lo = 0, hi = 2 * A;\n  while(hi - lo > EPS){\n    ld mid = (lo + hi) / 2;\n    (check(mid) ? hi : lo) = mid;\n  }\n  cout << fixed << setprecision(10);\n  cout << (lo + hi) / 2 << 'n';\n}",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 3200
  },
  {
    "contest_id": "650",
    "index": "A",
    "title": "Watchmen",
    "statement": "Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are $n$ watchmen on a plane, the $i$-th watchman is located at point $(x_{i}, y_{i})$.\n\nThey need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen $i$ and $j$ to be $|x_{i} - x_{j}| + |y_{i} - y_{j}|$. Daniel, as an ordinary person, calculates the distance using the formula $\\sqrt{(x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2}}$.\n\nThe success of the operation relies on the number of pairs $(i, j)$ ($1 ≤ i < j ≤ n$), such that the distance between watchman $i$ and watchmen $j$ calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.",
    "tutorial": "When Manhattan distance equals to Euclidean distance? $d_{eu}^{2} = (x_{1} - x_{2})^{2} + (y_{1} - y_{2})^{2}$ $d_{mh}^{2} = (|x_{1} - x_{2}| + |y_{1} - y_{2}|)^{2} = (x_{1} - x_{2})^{2} + 2|x_{1} - x_{2}||y_{1} - y_{2}| + (y_{1} - y_{2})^{2}$ So it is true only when $x_{1} = x_{2}$ or $y_{1} = y_{2}$. This means that to count the number of such pair we need to calculate number of points on each horizontal line and each vertical line. We can do that easily with the use of std::map/TreeMap/HashMap/Dictionary, or just by sorting all coordinates. If we have $k$ points on one horizontal or vertical line they will add $k(k - 1) / 2$ pairs to the result. But if we have several points in one place we will count their pairs twice, so we need to subtract from answer number of pairs of identical points which we can calculate with the same formula and using the same method of finding equal values as before. If we use TreeMap/sort then solution will run in $O(n\\log n)$ and if unordered_map/HashMap then in $O(n)$.",
    "tags": [
      "data structures",
      "geometry",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "650",
    "index": "B",
    "title": "Image Preview",
    "statement": "Vasya's telephone contains $n$ photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo $n$. Similarly, by swiping right from the last photo you reach photo $1$. It takes $a$ seconds to swipe from photo to adjacent.\n\nFor each photo it is known which orientation is intended for it — horizontal or vertical. Phone is in the vertical orientation and \\textbf{can't} be rotated. It takes $b$ second to change orientation of the photo.\n\nVasya has $T$ seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends $1$ second to notice all details in it. If photo is in the wrong orientation, he spends $b$ seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.\n\nHelp Vasya find the maximum number of photos he is able to watch during $T$ seconds.",
    "tutorial": "What photos we will see in the end? Some number from the beginning of the gallery and some from the end. There are 4 cases: We always go right. We always go left. We initially go right, then reverse direction, go through all visited photos and continue going left. We initially go left, then reverse direction, go through all visited photos and continue going right. First two cases are straightforward, we can just emulate them. Third and fourth cases can be done with the method of two pointers. Note that if we see one more picture to the right, we spend more time on the right side and the number of photos seen to the left will decrease. This solution will run in $O(n)$. Alternative solution is to fix how many photos we've seen to the right and search how many we can see to the left with binary search. For this method we will need to precompute times of seeing $k$ pictures to the right and to the left. But this is solution is $O(n\\log n)$, which is slightly worse then previous one, but maybe it is easier for somebody.",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "650",
    "index": "C",
    "title": "Table Compression",
    "statement": "Little Petya is now fond of data compression algorithms. He has already studied gz, bz, zip algorithms and many others. Inspired by the new knowledge, Petya is now developing the new compression algorithm which he wants to name dis.\n\nPetya decided to compress tables. He is given a table $a$ consisting of $n$ rows and $m$ columns that is filled with positive integers. He wants to build the table $a'$ consisting of positive integers such that the relative order of the elements in each row and each column remains the same. That is, if in some row $i$ of the initial table $a_{i, j} < a_{i, k}$, then in the resulting table $a'_{i, j} < a'_{i, k}$, and if $a_{i, j} = a_{i, k}$ then $a'_{i, j} = a'_{i, k}$. Similarly, if in some column $j$ of the initial table $a_{i, j} < a_{p, j}$ then in compressed table $a'_{i, j} < a'_{p, j}$ and if $a_{i, j} = a_{p, j}$ then $a'_{i, j} = a'_{p, j}$.\n\nBecause large values require more space to store them, the maximum value in $a'$ should be as small as possible.\n\nPetya is good in theory, however, he needs your help to implement the algorithm.",
    "tutorial": "First we will solve our problem when all values are different. We will construct a graph, where vertices are cells $(i, j)$ and there is an edge between two of them if we know that one is strictly less then the other and this relation should be preserved. This graph obviously has no cycles, so we can calculate answer as dynamic programming on the vertices: We can do this with topological sort or with lazy computations. But if we will construct our graph naively then it will contain $O(nm(n + m))$ edges. To reduce this number we will sort each row and column and add edges only between neighbours in the sorted order. Now we have $O(nm)$ edges and we compute them in $O(n m\\log(n m))$ time. But to solve the problem completely in the beginning we need to compress all equal values which are in the same rows and columns. We can construct second graph with edges between equal cells in the same way as before and find all connected components in it. They will be our new vertices for the first graph.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "650",
    "index": "D",
    "title": "Zip-line",
    "statement": "Vasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long as possible but he doesn't remember exactly the heights of all trees in the forest. He is sure that he remembers correct heights of all trees except, possibly, one of them.\n\nIt is known that the forest consists of $n$ trees staying in a row numbered from left to right with integers from $1$ to $n$. According to Vasya, the height of the $i$-th tree is equal to $h_{i}$. The zip-line of length $k$ should hang over $k$ ($1 ≤ k ≤ n$) trees $i_{1}, i_{2}, ..., i_{k}$ ($i_{1} < i_{2} < ... < i_{k}$) such that their heights form an increasing sequence, that is $h_{i1} < h_{i2} < ... < h_{ik}$.\n\nPetya had been in this forest together with Vasya, and he now has $q$ assumptions about the mistake in Vasya's sequence $h$. His $i$-th assumption consists of two integers $a_{i}$ and $b_{i}$ indicating that, according to Petya, the height of the tree numbered $a_{i}$ is actually equal to $b_{i}$. Note that Petya's assumptions are \\textbf{independent} from each other.\n\nYour task is to find the maximum length of a zip-line that can be built over the trees under each of the $q$ assumptions.\n\nIn this problem the length of a zip line is considered equal to the number of trees that form this zip-line.",
    "tutorial": "We need to find the longest increasing subsequence (LIS) after each change if all changes are independent. First lets calculate LIS for the initial array and denote its length as $k$. While calculating it we will store some additional information: $len_{l}[i]$ - maximal length of LIS ending on this element. Also we will need $len_{r}[i]$ - maximal length of LIS starting from this element (we can calc it when searching longest decreasing sequence on reversed array). Lets solve the case when we take our new element in the resulting LIS. Then we just calculate $max_{i < a, h[i] < b}(len_{l}[i]) + 1 + max_{j > a, h[j] > b}(len_{r}[j])$. It can be done online with persistent segment tree or offline with scanline with regular segment tree in $O(\\log n)$ time. This is the only case when answer can be larger then $k$, and it can be only $k + 1$ to be exact. Second case is when we change our element and ruin all LIS of size $k$. Then answer is $k - 1$. Otherwise we will have at least one not ruined LIS of size $k$ and it is the answer. Lets calculate number of different LIS by some modulo. It can be done with the same dynamic programming with segment tree as just finding LIS. Then we can check if $liscount = liscount_{left}[a] * liscount_{right}[a]$. This exactly means that all sequences go through our element. But if you don't want the solution with such \"hashing\" there is another approach. For each element we can calc if it can be in LIS. If so then we know on which position it will go ($len_{l}[i]$). Then for each position we will know if there are several elements wanting to go on that position or only one. If only one then it means that all LIS are going through that element. Overall complexity is $O(n\\log n)$. P.S. We can solve this without segment tree, just using alternative approach to calculating LIS with dynamic programming and binary search.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "hashing"
    ],
    "rating": 2600
  },
  {
    "contest_id": "650",
    "index": "E",
    "title": "Clockwork Bomb",
    "statement": "My name is James diGriz, I'm the most clever robber and treasure hunter in the whole galaxy. There are books written about my adventures and songs about my operations, though you were able to catch me up in a pretty awkward moment.\n\nI was able to hide from cameras, outsmart all the guards and pass numerous traps, but when I finally reached the treasure box and opened it, I have accidentally started the clockwork bomb! Luckily, I have met such kind of bombs before and I know that the clockwork mechanism can be stopped by connecting contacts with wires on the control panel of the bomb in a certain manner.\n\nI see $n$ contacts connected by $n - 1$ wires. Contacts are numbered with integers from $1$ to $n$. Bomb has a security mechanism that ensures the following condition: if there exist $k ≥ 2$ contacts $c_{1}, c_{2}, ..., c_{k}$ forming a circuit, i. e. there exist $k$ \\textbf{distinct} wires between contacts $c_{1}$ and $c_{2}$, $c_{2}$ and $c_{3}$, $...$, $c_{k}$ and $c_{1}$, then the bomb immediately explodes and my story ends here. In particular, if two contacts are connected by more than one wire they form a circuit of length $2$. It is also prohibited to connect a contact with itself.\n\nOn the other hand, if I disconnect more than one wire (i. e. at some moment there will be no more than $n - 2$ wires in the scheme) then the other security check fails and the bomb also explodes. So, the only thing I can do is to unplug some wire and plug it into a new place ensuring the fact that no circuits appear.\n\nI know how I should put the wires in order to stop the clockwork. But my time is running out! Help me get out of this alive: find the sequence of operations each of which consists of unplugging some wire and putting it into another place so that the bomb is defused.",
    "tutorial": "First idea is that answer is always equals to the number of edges from the first tree, which are not in the second one. This means that if we have an edge in both trees we will never touch it. So if we have such edge we can remove this edge and merge its two vertices together, nothing will change. Second idea that if we will take any edge from the first tree there always exists some edge from the second tree, which we can swap (otherwise second graph is not connected, but the tree is always connected). So the order of adding edges from the first tree can be arbitrary. Third idea is that if we will select leaf node in the first tree, then cut its only edge, then we can add instead of it any edge going from this vertex in the second tree. Overall algorithm: we store linked lists of edges in vertices, when edge is in both trees we use disjoint-set union to merge vertices and join their lists. We can simply traverse first tree to get any order of edges in which the current edge will always contain leaf as one of its vertices. Complexity is $O(n \\alpha )$, which in practice is almost linear.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "greedy",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "651",
    "index": "A",
    "title": "Joysticks",
    "statement": "Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at $a_{1}$ percent and second one is charged at $a_{2}$ percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger).\n\nGame continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops.\n\nDetermine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by \\textbf{more than $100$ percent}.",
    "tutorial": "Main idea is that each second we need to charge the joystick with lowest power level. We can just emulate it or get an $O(1)$ formula, because process is very simple.",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "651",
    "index": "B",
    "title": "Beautiful Paintings",
    "statement": "There are $n$ pictures delivered for the new exhibition. The $i$-th painting has beauty $a_{i}$. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.\n\nWe are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of $a$ in any order. What is the maximum possible number of indices $i$ ($1 ≤ i ≤ n - 1$), such that $a_{i + 1} > a_{i}$.",
    "tutorial": "Lets look at the optimal answer. It will contain several segment of increasing beauty and between them there will be drops in the beautifulness. Solution is greedy. Lets sort all paintings and lets select which of them will be in the first increasing segment. We just go from left to right and select only one painting from each group of several paintings with the fixed beauty value. We continue this operation while there is at least one painting left. With the careful implementation we will get $O(n\\log n)$ solution. But this solution gives us the whole sequence, but the problem was a little bit easier - to determine number of such segments. From the way we construct answer it is easy to see that the number of segments always equal to the maximal number of copies of one value. Obviously we can't get less segments than that and our algorithm gives us exactly this number. This solution is $O(n)$.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "652",
    "index": "A",
    "title": "Gabriel and Caterpillar",
    "statement": "The $9$-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height $h_{1}$ cm from the ground. On the height $h_{2}$ cm ($h_{2} > h_{1}$) on the same tree hung an apple and the caterpillar was crawling to the apple.\n\nGabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by $a$ cm per hour by day and slips down by $b$ cm per hour by night.\n\nIn how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at $10$ am and finishes at $10$ pm. Gabriel's classes finish at $2$ pm. You can consider that Gabriel noticed the caterpillar just after the classes at $2$ pm.\n\nNote that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple.",
    "tutorial": "Let's consider three cases. $h_{1} + 8a  \\ge  h_{2}$ - in this case the caterpillar will get the apple on the same day, so the answer is $0$. The first condition is false and $a  \\le  b$ - in this case the caterpillar will never get the apple, because it can't do that on the first day and after each night it will be lower than one day before. If the first two conditions are false easy to see that the answer equals to $\\left[{\\frac{h_{2}-h_{1}-8a}{12(a-b)}}\\right]$. Also this problem can be solved by simple modelling, because the heights and speeds are small. Complexity: $O(1)$.",
    "code": "int h1, h2;\nint a, b;\n\nbool read() {\n\treturn !!(cin >> h1 >> h2 >> a >> b);\n}\n\nvoid solve() {\n\tif (h1 + 8 * a >= h2)\n\t\tputs(\"0\");\n\telse if (a > b) {\n\t\tint num = h2 - h1 - 8 * a, den = 12 * (a - b);\n\t\tcout << (num + den - 1) / den << endl;\n\t} else\n\t\tputs(\"-1\");\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "652",
    "index": "B",
    "title": "z-sort",
    "statement": "A student of $z$-school found a kind of sorting called $z$-sort. The array $a$ with $n$ elements are $z$-sorted if two conditions hold:\n\n- $a_{i} ≥ a_{i - 1}$ for all even $i$,\n- $a_{i} ≤ a_{i - 1}$ for all odd $i > 1$.\n\nFor example the arrays [1,2,1,2] and [1,1,1,1] are $z$-sorted while the array [1,2,3,4] isn’t $z$-sorted.\n\nCan you make the array $z$-sorted?",
    "tutorial": "Easy to see that we can $z$-sort any array $a$. Let $k=\\lfloor{\\frac{n}{2}}\\rfloor$ be the number of even positions in $a$. We can assign to those positions $k$ maximal elements and distribute other $n - k$ elements to odd positions. Obviously the resulting array is $z$-sorted. Complexity: $O(nlogn)$.",
    "code": "const int N = 1010;\n\nint n, a[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nint ans[N];\n\nvoid solve() {\n\tsort(a, a + n);\n\n\tint p = 0, q = n - 1;\n\tforn(i, n)\n\t\tif (i & 1) ans[i] = a[q--];\n\t\telse ans[i] = a[p++];\n\tassert(q + 1 == p);\n\n\tforn(i, n) {\n\t\tif (i) putchar(' ');\n\t\tprintf(\"%d\", ans[i]);\n\t}\n\tputs(\"\");\n}",
    "tags": [
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "652",
    "index": "C",
    "title": "Foe Pairs",
    "statement": "You are given a permutation $p$ of length $n$. Also you are given $m$ foe pairs $(a_{i}, b_{i})$ ($1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}$).\n\nYour task is to count the number of different intervals $(x, y)$ ($1 ≤ x ≤ y ≤ n$) that do not contain any foe pairs. So you shouldn't count intervals $(x, y)$ that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important).\n\nConsider some example: $p = [1, 3, 2, 4]$ and foe pairs are ${(3, 2), (4, 2)}$. The interval $(1, 3)$ is incorrect because it contains a foe pair $(3, 2)$. The interval $(1, 4)$ is also incorrect because it contains two foe pairs $(3, 2)$ and $(4, 2)$. But the interval $(1, 2)$ is correct because it doesn't contain any foe pair.",
    "tutorial": "Let's precompute for each value $x$ its position in permutation $pos_{x}$. It's easy to do in linear time. Consider some foe pair $(a, b)$ (we may assume $pos_{a} < pos_{b}$). Let's store for each value $a$ the leftmost position $pos_{b}$ such that $(a, b)$ is a foe pair. Denote that value as $z_{a}$. Now let's iterate over the array $a$ from right to left and maintain the position $rg$ of the maximal correct interval with the left end in the current position $lf$. To maintain the value $rg$ we should simply take the minimum with the value $z[lf]$: $rg = min(rg, z[lf])$. And finally we should increment the answer by the value $rg - lf + 1$. Complexity: $O(n + m)$.",
    "code": "const int N = 300300;\n\nint n, m;\nint p[N];\npt b[N];\n\nbool read() {\n\tif (!(cin >> n >> m)) return false;\n\tforn(i, n) {\n\t\tassert(scanf(\"%d\", &p[i]) == 1);\n\t\tp[i]--;\n\t}\n\tforn(i, m) {\n\t\tint x, y;\n\t\tassert(scanf(\"%d%d\", &x, &y) == 2);\n\t\tx--, y--;\n\t\tb[i] = pt(x, y);\n\t}\n\treturn true;\n}\n\nint pos[N];\nvector<int> z[N];\n\nvoid solve() {\n\tforn(i, n) pos[p[i]] = i;\n\tforn(i, n) z[i].clear();\n\tforn(i, m) {\n\t\tint x = pos[b[i].x], y = pos[b[i].y];\n\t\tif (x > y) swap(x, y);\n\t\tz[x].pb(y);\n\t}\n\n\tli ans = 0;\n\tint rg = n;\n\tnfor(i, n) {\n\t\tforn(j, sz(z[i])) rg = min(rg, z[i][j]);\n\t\tans += rg - i;\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "652",
    "index": "D",
    "title": "Nested Segments",
    "statement": "You are given $n$ segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.",
    "tutorial": "This problem is a standard two-dimensional problem that can be solved with one-dimensional data structure. In the same way a lot of other problems can be solved (for example the of finding the maximal weighted chain of points so that both coordinates of each point are greater than the coordinates of the predecessing point). Rewrite the problem formally: for each $i$ we should count the number of indices $j$ so that the following conditions are hold: $a_{i} < a_{j}$ and $b_{j} < a_{j}$. Let's sort all segments by the left ends from right to left and maintain some data structure (Fenwick tree will be the best choice) with the right ends of the processed segments. To calculate the answer for the current segment we should simple take the prefix sum for the right end of the current segment. So the condition $a_{i} < a_{j}$ is hold by sorting and iterating over the segments from the right to the left (the first dimension of the problem). The condition $b_{j} < a_{j}$ is hold by taking the prefix sum in data structure (the second dimension). Complexity: $O(nlogn)$.",
    "code": "const int N = 1200300;\n\nint n;\npair<pti, int> a[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d%d\", &a[i].x.x, &a[i].x.y) == 2), a[i].y = i;\n\treturn true;\n}\n\nint t[N];\nvector<int> ys;\n\ninline void inc(int i, int val) {\n\tfor ( ; i < sz(ys); i |= i + 1)\n\t\tt[i] += val;\n}\n\ninline int sum(int i) {\n\tint ans = 0;\n\tfor ( ; i >= 0; i = (i & (i + 1)) - 1)\n\t\tans += t[i];\n\treturn ans;\n}\n\nint ans[N];\n\nvoid solve() {\n\tys.clear();\n\tforn(i, n) ys.pb(a[i].x.y);\n\tsort(all(ys));\n\tys.erase(unique(all(ys)), ys.end());\n\tforn(i, sz(ys)) t[i] = 0;\n\n\tsort(a, a + n);\n\tnfor(i, n) {\n\t\tint idx = int(lower_bound(all(ys), a[i].x.y) - ys.begin());\n\t\tans[a[i].y] = sum(idx);\n\t\tinc(idx, +1);\n\t}\n\n\tforn(i, n) printf(\"%dn\", ans[i]);\n}",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "652",
    "index": "E",
    "title": "Pursuit For Artifacts",
    "statement": "Johnny is playing a well-known computer game. The game are in some country, where the player can freely travel, pass quests and gain an experience.\n\nIn that country there are $n$ islands and $m$ bridges between them, so you can travel from any island to any other. In the middle of some bridges are lying ancient powerful artifacts. Johnny is not interested in artifacts, but he can get some money by selling some artifact.\n\nAt the start Johnny is in the island $a$ and the artifact-dealer is in the island $b$ (possibly they are on the same island). Johnny wants to find some artifact, come to the dealer and sell it. The only difficulty is that bridges are too old and destroying right after passing over them. Johnnie's character can't swim, fly and teleport, so the problem became too difficult.\n\nNote that Johnny can't pass the half of the bridge, collect the artifact and return to the same island.\n\nDetermine if Johnny can find some artifact and sell it.",
    "tutorial": "Edge biconnected component in an undirected graph is a maximal by inclusion set of vertices so that there are two edge disjoint paths between any pair of vertices. Consider the graph with biconnected components as vertices. Easy to see that it's a tree (if it contains some cycle then the whole cycle is a biconnected component). All edges are destroying when we passing over them so we can't returnto the same vertex (in the tree) after leaving it by some edge. Consider the biconncted components that contains the vertices $a$ and $b$. Let's denote them $A$ and $B$. Statement: the answer is YES if and only if on the path in the tree from the vertex $A$ to the vertex $B$ there are an edge with an artifact or there are a biconnected component that contains some edge with an artifact. Easy to see that the statement is true: if there are such edge then we can pass over it in the tree on the path from $A$ to $B$ or we can pass over it in biconnected component. The converse also easy to check. Here is one of the ways to find edge biconnected components: Let's orient all edges to direction that depth first search passed it for the first time. Let's find in new directed graph strongly connected components. Statement: the strongly connected components in the new graph coincide with the biconnected components in old undirected graph. Also you can notice that the edges in tree is the bridges of the graph (bridges in terms of graph theory). So you can simply find the edges in the graph. const int N = 500500, M = 500500; int n, m; int eused[M]; vector eid[N]; vector g1[N], tg1[N]; vector w[N]; int a, b; bool read() { if (!(cin >> n >> m)) return false; forn(i, m) eused[i] = false; forn(i, n) { g1[i].clear(); tg1[i].clear(); eid[i].clear(); w[i].clear(); } forn(i, m) { int x, y, z; assert(scanf(\"%d%d%d\", &x, &y, &z) == 3); x--, y--; g1[x].pb(y); g1[y].pb(x); eid[x].pb(i); eid[y].pb(i); w[x].pb(z); w[y].pb(z); } assert(cin >> a >> b); a--, b--; return true; } int u, used[N]; int sz, perm[N]; void dfs1(int v) { used[v] = u; forn(i, sz(g1[v])) { int u = g1[v][i]; int cid = eid[v][i]; if (!eused[cid]) { eused[cid] = true; tg1[u].pb(v); } if (used[u] != ::u) dfs1(u); } perm[sz++] = v; } int c, comp[N]; void dfs2(int v) { used[v] = u; for (auto u : tg1[v]) if (used[u] != ::u) dfs2(u); comp[v] = c; } vector g2[N]; vector w2[N]; bool good[N]; bool dfs3(int v, int p, int t, bool& ans) { if (v == t) { ans |= good[v]; return true; } } void solve() { u++, sz = 0; dfs1(0); assert(sz == n); reverse(perm, perm + sz); } Complexity: $O(n + m)$.",
    "code": "u++, c = 0;\nforn(i, sz) if (used[perm[i]] != u) dfs2(perm[i]), c++;\n\nforn(i, c) good[i] = false;\n\nforn(i, c) {\n    g2[i].clear();\n    w2[i].clear();\n}\nforn(i, n)\n    forn(j, sz(g1[i])) {\n       int x = comp[i], y = comp[g1[i][j]];\n       if (x != y) {\n         g2[x].pb(y);\n         w2[x].pb(w[i][j]);\n       } else if (w[i][j]) good[x] = true;\n    }\n\nn = c;\na = comp[a], b = comp[b];\n\nbool ans = good[a];\nassert(dfs3(a, -1, b, ans));\nputs(ans ? \"YES\" : \"NO\");",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "652",
    "index": "F",
    "title": "Ants on a Circle",
    "statement": "$n$ ants are on a circle of length $m$. An ant travels one unit of distance per one unit of time. Initially, the ant number $i$ is located at the position $s_{i}$ and is facing in the direction $d_{i}$ (which is either L or R). Positions are numbered in counterclockwise order starting from some point. Positions of the all ants are distinct.\n\nAll the ants move simultaneously, and whenever two ants touch, they will both switch their directions. Note that it is possible for an ant to move in some direction for a half of a unit of time and in opposite direction for another half of a unit of time.\n\nPrint the positions of the ants after $t$ time units.",
    "tutorial": "The first observation: if all the ants are indistinguishable we can consider that there are no collisions and all the ants are passing one through another. So we can easily determine the final positions of all the ants, but we can't say which ant will be in which position. The second observation: the relative order of the ants will be the same all the time. So to solve the problem we should only find the position of one ant after $t$ seconds. Let's solve that problem in the following way: Consider the positions of all the ants after $m$ time units. Easy to see that by the first observation all the positions of the ants will left the same, but the order will be different (we will have some cyclic shift of the ants). If we find that cyclic shift $sh$ we can apply it $\\lfloor{\\frac{t}{m}}\\rfloor$ times. After that we will have only $t  \\pm  od m$ time units. So the problem now is to model the process for the one ant with $m$ and $r  \\pm  od m$ time units. Note that in that time interval the fixed ant will have no more than two collisions with each other ant. So if we model the process with ignoring all collisions except the ones that include the fixed ant, we will have no more than $2n$ collisions. Let's model that process with two queues for the ants going to the left and to the right. Each time we should take the first ant in the queue with opposite direction, process the collision and add that ant to the end of the other queue. Hint: you will have a problem when the fixed ant can be in two different positions at the end, but it's easy to fix with doing the same with the next ant. const int N = 300300; int n, m; li t; pair<pair<int, char>, int> a[N]; bool read() { if (!(cin >> n >> m >> t)) return false; forn(i, n) { assert(scanf(\"%d %c\", &a[i].x.x, &a[i].x.y) == 2); a[i].x.x--; a[i].y = i; } return true; } int dx[] = { -1, +1 }; const string dirs(\"LR\"); inline int getDir(char d) { return (int) dirs.find(d); } inline int getPos(li x, char d, li t) { x %= m, t %= m; li ans = (x + t * dx[getDir(d)]) % m; (ans < 0) && (ans += m); return int(ans); } typedef pair<li, li> ptl; void clear(queue& q) { while (!q.empty()) q.pop(); } queue tol, tor; int calc(int v, li t) { clear(tol); clear(tor); } int ans[N]; void solve() { assert(n > 1); sort(a, a + n); } Complexity: $O(nlogn)$.",
    "code": "vector<int> poss;\nforn(i, n)\n    poss.pb(getPos(a[i].x.x, a[i].x.y, t));\nsort(all(poss));\n\nvector<vector<int>> xs;\nforn(s, 2) {\n    int x = calc(s, m);\n    int pos = -1;\n    forn(i, n)\n       if (a[i].x.x == x) {\n         assert(pos == -1);\n         pos = i;\n       }\n    assert(pos != -1);\n    pos = (pos - s + n) % n;\n    li k = (t / m) % n;\n    pos = int((s + pos * k) % n);\n\n    x = calc(pos, t % m);\n    xs.pb(vector<int>());\n    forn(i, sz(poss))\n       if (poss[i] == x)\n         xs.back().pb(i);\n    assert(!xs.back().empty());\n    if (sz(xs.back()) == 2) assert(xs.back()[0] + 1 == xs.back()[1]);\n}\n\nint pos = xs[0][0];\nif (sz(xs[0]) > 1) {\n    assert(sz(xs[0]) == 2);\n    assert(pos + 1 == xs[0][1]);\n    if (xs[0] != xs[1])\n       pos = xs[0][1];\n}\n\nforn(ii, n) {\n    int i = (ii + pos) % sz(poss);\n    ans[a[ii].y] = poss[i];\n}\n\nforn(i, n) {\n    if (i) putchar(' ');\n    assert(0 <= ans[i] && ans[i] < m);\n    printf(\"%d\", ans[i] + 1);\n}\nputs(\"\");",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "653",
    "index": "A",
    "title": "Bear and Three Balls",
    "statement": "Limak is a little polar bear. He has $n$ balls, the $i$-th ball has size $t_{i}$.\n\nLimak wants to give one ball to each of his three friends. Giving gifts isn't easy — there are two rules Limak must obey to make friends happy:\n\n- No two friends can get balls of the same size.\n- No two friends can get balls of sizes that differ by more than $2$.\n\nFor example, Limak can choose balls with sizes $4$, $5$ and $3$, or balls with sizes $90$, $91$ and $92$. But he can't choose balls with sizes $5$, $5$ and $6$ (two friends would get balls of the same size), and he can't choose balls with sizes $30$, $31$ and $33$ (because sizes $30$ and $33$ differ by more than $2$).\n\nYour task is to check whether Limak can choose three balls that satisfy conditions above.",
    "tutorial": "watch out for test like \"1 1 1 2 2 2 2 3 3 3\". It shows that it's not enough to sort number and check three neighbouring elements. You must remove repetitions. The easier solution is to write 3 for-loops, without any sorting. Do you see how?",
    "tags": [
      "brute force",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "653",
    "index": "B",
    "title": "Bear and Compressing",
    "statement": "Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.\n\nYou are given a set of $q$ possible operations. Limak can perform them in any order, any operation may be applied any number of times. The $i$-th operation is described by a string $a_{i}$ of length two and a string $b_{i}$ of length one. No two of $q$ possible operations have the same string $a_{i}$.\n\nWhen Limak has a string $s$ he can perform the $i$-th operation on $s$ if the first two letters of $s$ match a two-letter string $a_{i}$. Performing the $i$-th operation removes first two letters of $s$ and inserts there a string $b_{i}$. See the notes section for further clarification.\n\nYou may note that performing an operation decreases the length of a string $s$ exactly by $1$. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any $a_{i}$.\n\nLimak wants to start with a string of length $n$ and perform $n - 1$ operations to finally get a one-letter string \"a\". In how many ways can he choose the starting string to be able to get \"a\"? Remember that Limak can use only letters he knows.",
    "tutorial": "you should generate all $6^{n}$ possible starting strings and for each of them check whether you will get \"a\" at the end. Remember that you should check two first letters, not last ones (there were many questions about it).",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "653",
    "index": "C",
    "title": "Bear and Up-Down",
    "statement": "The life goes up and down, just like nice sequences. Sequence $t_{1}, t_{2}, ..., t_{n}$ is called nice if the following two conditions are satisfied:\n\n- $t_{i} < t_{i + 1}$ for each odd $i < n$;\n- $t_{i} > t_{i + 1}$ for each even $i < n$.\n\nFor example, sequences $(2, 8)$, $(1, 5, 1)$ and $(2, 5, 1, 100, 99, 120)$ are nice, while $(1, 1)$, $(1, 2, 3)$ and $(2, 5, 3, 2)$ are not.\n\nBear Limak has a sequence of positive integers $t_{1}, t_{2}, ..., t_{n}$. This sequence \\textbf{is not nice} now and Limak wants to fix it by a single swap. He is going to choose two indices $i < j$ and swap elements $t_{i}$ and $t_{j}$ in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.",
    "tutorial": "Let's call an index $i$ bad if the given condition about $t_{i}$ and $t_{i + 1}$ doesn't hold true. We are given a sequence that has at least one bad place and we should count ways to swap two elements to fix all bad places (and not create new bad places). The shortest (so, maybe easiest) solution doesn't use this fact but one can notice that for more than $4$ bad places the answer is $0$ because swapping $t_{i}$ and $t_{j}$ can affect only indices $i - 1, i, j - 1, j$. With one iteration over the given sequence we can find and count all bad places. Let $x$ denote index of the first bad place (or index of some other bad place, it's not important). We must swap $t_{x}$ or $t_{x - 1}$ with something because otherwise $x$ would still be bad. Thus, it's enough to consider $O(n)$ swaps ~-- for $t_{x}$ and for $t_{x - 1}$ iterate over index of the second element to swap (note that \"the second element\" doesn't have to be bad and samples show it). For each of $O(n)$ swaps we can do the following (let $i$ and $j$ denote chosen two indices): Count bad places among four indices: $i - 1, i, j - 1, j$. If it turns out that these all not all initial bad places then we don't have to consider this swap - because some bad place will still exist anyway. Swap $t_{i}$ and $t_{j}$. Check if there is some bad place among four indices: $i - 1, i, j - 1, j$. If not then we found a correct way. Swap $t_{i}$ and $t_{j}$ again, to get an initial sequence. Be careful not to count the same pair of indices twice. In the solution above it's possible to count twice a pair of indices $(x - 1, x)$ (where $x$ was defined in the paragraph above). So, add some if or do it more brutally - create a set of pairs and store sorted pairs of indices there.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "653",
    "index": "D",
    "title": "Delivery Bears",
    "statement": "Niwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.\n\nIn the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with $n$ nodes and $m$ edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node $1$ to node $n$. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.\n\nNiwel has \\textbf{exactly} $x$ bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.\n\nNiwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.",
    "tutorial": "Let's transform this into a flow problem. Here, we transform \"weight\" into \"flow\", and each \"bear\" becomes a \"path\". Suppose we just want to find the answer for a single $x$. We can do this binary search on the flow for each path. To check if a particular flow of $F$ is possible, reduce the capacity of each edge from $c_{i}$ to $[c_{i}/F]$. Then, check if the max flow in this graph is at least $x$. The final answer is then $x$ multiplied by the flow value that we found.",
    "code": "//#pragma comment(linker, \"/STACK:16777216\")\n#define _CRT_SECURE_NO_WARNINGS\n \n#include <fstream>\n#include <iostream>\n#include <string>\n#include <complex>\n#include <math.h>\n#include <set>\n#include <vector>\n#include <map>\n#include <queue>\n#include <stdio.h>\n#include <stack>\n#include <algorithm>\n#include <list>\n#include <ctime>\n#include <memory.h>\n#include <assert.h>\n \n#define y0 sdkfaslhagaklsldk\n#define y1 aasdfasdfasdf\n#define yn askfhwqriuperikldjk\n#define j1 assdgsdgasghsf\n#define tm sdfjahlfasfh\n#define lr asgasgash\n#define norm asdfasdgasdgsd\n \n#define eps 1e-7\n#define M_PI 3.141592653589793\n#define bs 1000000007\n#define bsize 512\n \nconst int N = 200500;\n \nusing namespace std;\n \nstruct edge\n{\n\tint a, b, cap, flow;\n};\n \nint n, s, t, d[N], ptr[N];\nvector<edge> e;\nvector<int> g[N];\n \nvoid add_edge(int a, int b, int cap)\n{\n\tedge e1 = { a, b, cap, 0 };\n\tedge e2 = { b, a, 0, 0 };\n\tg[a].push_back(e.size());\n\te.push_back(e1);\n\tg[b].push_back(e.size());\n\te.push_back(e2);\n}\n \nbool bfs()\n{\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\td[i] = -1;\n\t}\n\td[s] = 0;\n\tqueue<int> qu;\n\tqu.push(s);\n\twhile (qu.size())\n\t{\n\t\tint v = qu.front();\n\t\tqu.pop();\n\t\tfor (int i = 0; i < g[v].size(); i++)\n\t\t{\n\t\t\tint id = g[v][i];\n\t\t\tint to = e[id].b;\n\t\t\tif (d[to] == -1 && e[id].flow < e[id].cap)\n\t\t\t{\n\t\t\t\td[to] = d[v] + 1;\n\t\t\t\tqu.push(to);\n\t\t\t}\n\t\t}\n\t}\n\treturn d[t] != -1;\n}\n \nint dfs(int v, int flow)\n{\n\tif (v == t || flow == 0)\n\t\treturn flow;\n\tfor (; ptr[v] < g[v].size(); ptr[v]++)\n\t{\n\t\tint id = g[v][ptr[v]];\n\t\tint to = e[id].b;\n\t\tif (d[to] != d[v] + 1)\n\t\t\tcontinue;\n\t\tint pushed = dfs(to, min(flow, e[id].cap - e[id].flow));\n\t\tif (pushed)\n\t\t{\n\t\t\te[id].flow += pushed;\n\t\t\te[id ^ 1].flow -= pushed;\n\t\t\treturn pushed;\n\t\t}\n\t}\n\treturn 0;\n}\n \nint dinic()\n{\n\tint flow = 0;\n\twhile (true)\n\t{\n\t\tif (!bfs())\n\t\t\tbreak;\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tptr[i] = 0;\n\t\t}\n\t\twhile (true)\n\t\t{\n\t\t\tint pushed = dfs(s, 10000);\n\t\t\tif (!pushed)\n\t\t\t\tbreak;\n\t\t\tflow += pushed;\n\t\t}\n\t}\n\treturn flow;\n}\n \nint m, x, k;\nvector<pair<pair<int, int>, int> > E;\n \nvoid construct_graph(double val)\n{\n\te.clear();\n\tfor (int i = 0; i < n; i++)\n\t\tg[i].clear();\n\tfor (int i = 0; i < E.size(); i++)\n\t{\n\t\t//cout << E[i].second << \" \" << val << endl;\n\t\tlong double d_here = E[i].second*1.0 / val+eps;\n\t\tif (d_here>1e9)\n\t\t\td_here = 1e6;\n\t\tint here = d_here;\n\t\tadd_edge(E[i].first.first, E[i].first.second, here);\n\t}\n}\n \nvoid update_graph(double val)\n{\n\tfor (int i = 0; i < E.size(); i++)\n\t{\n\t\tdouble d_here = E[i].second*1.0 / val+eps;\n\t\tif (d_here>1e9)\n\t\t\td_here = 1e6;\n\t\tint here = d_here;\n\t\tint rem = here - e[i * 2].cap;\n\t\te[i * 2].cap += rem;\n\t\t//cout << rem << \" \" << val << \" \" << e[i * 2].cap << \" \"<<e[i*2].flow<<endl;\n\t}\n}\n \ndouble get_next(double val)\n{\n\tdouble res = 0;\n\tfor (int i = 0; i < E.size(); i++)\n\t{\n\t\tdouble d_here = E[i].second*1.0 / val+eps;\n\t\tif (d_here>1e9)\n\t\t\td_here = 1e6;\n\t\tint here = d_here;\n\t\tdouble thold = (E[i].second*1.0 / (here + 1));\n\t\tres = max(res, thold);\n\t}\n\treturn res;\n}\n \nvector<pair<int, double> > G[N];\ndouble D[N];\n//set<pair<double, int> > S;\n//set<pair<double, int> > ::iterator it;\n \npriority_queue<pair<double, int> > S,emp;\n \ndouble smart_next(double val)\n{\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tG[i].clear();\n\t\tD[i] = 0;\n\t}\n \n\tfor (int i = 0; i < E.size(); i++)\n\t{\n\t\t//cout << e[i*2].a<<\" \"<<e[i*2].b<<\" \"<<e[i * 2].cap << \" \" << e[i * 2].flow << endl;\n\t\tdouble T = E[i].second*1.0 / (e[i * 2].cap + 1);\n\t\tif (e[i * 2].flow < e[i * 2].cap)\n\t\t\tG[E[i].first.first].push_back(make_pair(E[i].first.second, val));\n\t\telse\n\t\t\tG[E[i].first.first].push_back(make_pair(E[i].first.second, T));\n\t\tif (e[i * 2 + 1].flow < e[i * 2+1].cap)\n\t\t{\n\t\t\tG[E[i].first.second].push_back(make_pair(E[i].first.first, val));\n\t\t}\n\t\telse\n\t\t\tG[E[i].first.second].push_back(make_pair(E[i].first.first, T));\n\t}\n \n\tS = emp;\n \n\tD[0] = val;\n\tfor (int i = 0; i < n; i++)\n\t\tS.push(make_pair(D[i], i));\n \n\twhile (S.size())\n\t{\n\t\tpair<double, int> p = S.top();\n\t\tS.pop();\n\t\tif (D[p.second]>p.first + eps)\n\t\t\tcontinue;\n\t\tint cur = p.second;\n\t\tif (cur == n - 1)\n\t\t\tbreak;\n\t\t//cout << cur << \" \" << p.first <<\" \"<<S.size()<< endl;\n\t\tfor (int i = 0; i < G[cur].size(); i++)\n\t\t{\n\t\t\tint to = G[cur][i].first;\n\t\t\tdouble cost = min(G[cur][i].second, D[cur]);\n\t\t\tif (D[to]<cost-eps)\n\t\t\t{\n\t\t\t\t//S.erase(make_pair(D[to], to));\n\t\t\t\tD[to] = cost;\n\t\t\t\tS.push(make_pair(D[to], to));\n\t\t\t}\n\t\t}\n\t}\n\treturn D[n - 1];\n}\n \ndouble solve_naive(int need)\n{\n\tlong double l, r;\n\tl = 1e-6;\n\tr = 1e6;\n\tfor (int iter = 1; iter <= 70; iter++)\n\t{\n\t\tdouble mid = l + r;\n\t\tmid /= 2;\n\t\tconstruct_graph(mid);\n\t\tint here = dinic();\n\t\tif (here >= need)\n\t\t\tl = mid;\n\t\telse\n\t\t\tr = mid;\n\t}\n\treturn l;\n}\n \nint main(){\n\t//freopen(\"route.in\",\"r\",stdin);\n\t//freopen(\"route.out\",\"w\",stdout);\n\t//freopen(\"F:/in.txt\", \"r\", stdin);\n\t//freopen(\"F:/output.txt\", \"w\", stdout);\n\tios_base::sync_with_stdio(0);\n\t//cin.tie(0);\n\t\n\tcin >> n >> m >> x;\n\tk = 1;\n \n\ts = 0;\n\tt = n - 1;\n\tfor (int i = 1; i <= m; i++)\n\t{\n\t\tint a, b, c;\n\t\tcin >> a >> b >> c;\n\t\t--a;\n\t\t--b;\n\t\tE.push_back(make_pair(make_pair(a, b), c));\n\t}\n \n\tcout.precision(7);\n \n\tlong double cur_val = solve_naive(x);\n \n\tconstruct_graph(cur_val - eps);\n\tint cur_flow = dinic();\n \n\tfor (int i = x; i < x + k; i++)\n\t{\n\t\t//cout << i << \"@\" << cur_flow << endl;\n\t\twhile (cur_flow < i)\n\t\t{\n\t\t\tdouble next_cand = smart_next(cur_val);\n\t\t\tupdate_graph(next_cand);\n\t\t\t//cout << next_cand << endl;\n\t\t\t//cin.get();\n\t\t\tbfs();\n\t\t\tfor (int j = 0; j < n; j++)\n\t\t\t\tptr[j] = 0;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tint pushed = dfs(s, 1000000);\n\t\t\t\tif (pushed == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tcur_flow += pushed;\n\t\t\t}\n//\t\t\tcout << pushed << endl;\n//\t\t\tcin.get();\n\t\t\tcur_val = next_cand;\n\t\t}\n\t\tcout << fixed << cur_val*i << \"\\n\";\n\t}\n\t/*\n\tfor (int i = x; i < x + k; i++)\n\t{\n\t\tcout << fixed << solve_naive(i)*i << endl;\n\t}*/\n \n\tcin.get(); cin.get();\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "flows",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "653",
    "index": "E",
    "title": "Bear and Forgotten Tree 2",
    "statement": "A tree is a connected undirected graph consisting of $n$ vertices and $n - 1$ edges. Vertices are numbered $1$ through $n$.\n\nLimak is a little polar bear. He once had a tree with $n$ vertices but he lost it. He still remembers something about the lost tree though.\n\nYou are given $m$ pairs of vertices $(a_{1}, b_{1}), (a_{2}, b_{2}), ..., (a_{m}, b_{m})$. Limak remembers that for each $i$ there was \\textbf{no edge} between $a_{i}$ and $b_{i}$. He also remembers that vertex $1$ was incident to exactly $k$ edges (its degree was equal to $k$).\n\nIs it possible that Limak remembers everything correctly? Check whether there exists a tree satisfying the given conditions.",
    "tutorial": "You are given a big graph with some edges forbidden, and the required degree of vertex 1. We should check whether there exists a spanning tree. Let's first forget about the condition about the degree of vertex 1. The known fact: a spanning tree exists if and only if the graph is connected (spend some time on this fact if it's not obvious for you). So, let's check if the given graph is connected. We will do it with DFS. We can't run standard DFS because there are maybe $O(n^{2})$ edges (note that the input contains forbidden edges, and there may be many more allowed edges then). We should modify it by adding a set or list of unvisited vertices $s$. When we are at vertex $a$ we can't check all edges adjacent to $a$ and instead let's iterate over possible candidates for adjacent unvisited vertices (iterate over $s$). For each $b$ in $s$ we should check whether $a$ and $b$ are connected by a forbidden edge (you can store input edges in a set of pairs or in a similar structure). If they are connected by a forbidden edge then nothing happens (but for each input edge it can happen only twice, for each end of edge, thus $O(m)$ in total), and otherwise we get a new vertex. The complexity is $O((n+m)\\cdot\\log m)$ where $\\log\\gamma$ is from using set of forbidden edges. Now we will check for what degree of vertex 1 we can build a tree. We again consider a graph with $n$ vertices and $m$ forbidden edges. We will first find out what is the minimum possible degree of vertex 1 in some spanning tree. After removing vertex 1 we would get some connected components and in the initial graph they could be connected to each other only with edges to vertex 1. With the described DFS we can find $c$ ($1  \\le  c  \\le  n - 1$) - the number of created connected components. Vertex 1 must be adjacent to at least one vertex in each of $c$ components. And it would be enough to get some tree because in each component there is some spanning tree - together with edges to vertex 1 they give us one big spanning tree with $n$ vertices (we assume that the initial graph is connected). And the maximum degree of vertex 1 is equal to the number of allowed edges adjacent to this vertex. It's because more and more edges from vertex 1 can only help us (think why). It will be still possible to add some edges in $c$ components to get one big spanning tree. So, what is the algorithm? Run the described DFS to check if the graph is connected (if not then print \"NO\"). Remove vertex 1 and count connected components (e.g. starting DFS's from former neighbours of vertex 1). Also, simply count $d$ - the number of allowed edges adjacent to vertex 1. If the required degree $k$ is between $c$ and $d$ inclusive then print \"YES\", and otherwise print \"NO\".",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nset<pair<int,int>> forbidden;\nbool is_ok(int a, int b) {\n\tif(a > b) swap(a, b);\n\treturn forbidden.find(make_pair(a, b)) == forbidden.end();\n}\nset<int> remaining;\nvoid dfs(int a) {\n\tvector<int> memo;\n\tfor(int b : remaining) if(is_ok(a, b))\n\t\tmemo.push_back(b);\n\tfor(int b : memo)\n\t\tremaining.erase(b);\n\tfor(int b : memo) dfs(b);\n}\nvoid NO() {\n\tputs(\"impossible\");\n\texit(0);\n}\nint main() {\n\tint n, m, k;\n\tscanf(\"%d%d%d\", &n, &m, &k);\n\tfor(int i = 2; i <= n; ++i) remaining.insert(i);\n\tint allowed_degree = n - 1; // maximum possible degree of vertex 1\n\tfor(int i = 0; i < m; ++i) {\n\t\tint a, b;\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tif(a > b) swap(a, b);\n\t\tif(a == 1) --allowed_degree;\n\t\tforbidden.insert(make_pair(a, b));\n\t}\n\tif(allowed_degree < k) NO(); // not enough allowed edges from 1\n\tint components = 0; // connected components\n\tfor(int i = 2; i <= n; ++i) if(is_ok(1, i) && remaining.find(i)!=remaining.end()) {\n\t\tdfs(i);\n\t\t++components;\n\t}\n\tif(!remaining.empty()) NO(); // the graph isn't connected\n\tif(components > k) NO(); // we need more than k edges from 1\n\t\n\tputs(\"possible\");\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "653",
    "index": "F",
    "title": "Paper task",
    "statement": "Alex was programming while Valentina (his toddler daughter) got there and started asking many questions about the round brackets (or parenthesis) in the code. He explained her a bit and when she got it he gave her a task in order to finish his code on time.\n\nFor the purpose of this problem we consider only strings consisting of opening and closing round brackets, that is characters '(' and ')'.\n\nThe sequence of brackets is called correct if:\n\n- it's empty;\n- it's a correct sequence of brackets, enclosed in a pair of opening and closing brackets;\n- it's a concatenation of two correct sequences of brackets.\n\nFor example, the sequences \"()()\" and \"((()))(())\" are correct, while \")(()\", \"(((((\" and \"())\" are not.\n\nAlex took a piece of paper, wrote a string $s$ consisting of brackets and asked Valentina to count the number of \\textbf{distinct} non-empty substrings of $s$ that are correct sequences of brackets. In other words, her task is to count the number of non-empty correct sequences of brackets that occur in a string $s$ as a \\textbf{substring} (don't mix up with subsequences).\n\nWhen Valentina finished the task, Alex noticed he doesn't know the answer. Help him don't loose face in front of Valentina and solve the problem!",
    "tutorial": "There are two solutions. The first and more common solution required understanding how do SA (suffix array) and LCP (longest common prefix) work. The second processed the input string first and then run SA+LCP like a blackbox, without modifying or caring about those algorithms. Modify-SA-solution - The main idea is to modify the algorithm for computing the number of distinct substrings using SA + LCP. Let $query(L, R)$ denote the number of well formed prefixes of $substring(L, R)$. For example, for $substring(L, R) = \"(())()(\"$ we would have $query(L, R) = 2$ because we count $(())$ oraz $(())()$. How to be able to get $query(L, R)$ fast? You can treat the opening bracket as $+ 1$ and the ending bracket as $- 1$. Then you are interested in the number of intervals starting in $L$, ending not after $R$, with sum on the interval equal to zero. Additionally, the sum from $L$ to any earlier right end can't be less than zero. Maybe you will need some preprocessing here, maybe binary search, maybe segment trees. It's an exercise for you. We can iterate over suffix array values and for each suffix we add $query(suffix, N) - query(suffix, suffix + LCP[suffix] - 1)$ to the answer. In other words we count the number of well formed substrings in the current suffix and subtract the ones we counted in the previous step. The complexity is $O(n\\log n)$ but you could get AC with very fast solution with extra $\\log\\beta$. Compressing-solution - I will slowly compress the input string, changing small well-formed substrings to some new characters (in my code they are represented by integer numbers, not by letters). Let's take a look at the example: $|((\\cdot)\\rangle(|\\rightarrow\\ )(a\\rangle(\\cdot)\\rightarrow\\rangle b(\\cdot)(\\cdot)\\rightarrow\\jmath a(\\cdot)\\rightarrow\\jmath a a\\rightarrow\\jmath c a\\rightarrow\\jmath d$ or equivalently: $\\,((\\cdot\\!\\cdot)(\\,)(\\,)(\\,)\\rightarrow\\ )(a)a a\\rightarrow\\ )b a a\\rightarrow\\ )b a a\\rightarrow\\ ]c a\\rightarrow\\ d$ Whenever I have a maximum (not possible to expand) substring with single letters only, without any brackets, then I add this substring to some global list of strings. At the end I will count distinct substrings in the found list of strings (using SA+LCP). In the example above I would first add a string \"a\" and later I would add \"baa\". Note that each letter represents some well formed substring, e.g. 'b' represents $(())$ here. I must make sure that the same substrings will be compressed to the same letters. To do it, I always move from left to right, and I use trie with map (two know what to get from some two letters).",
    "code": "// Suffix Array from http://apps.topcoder.com/forums/?module=Thread&threadID=627379&start=0&mc=39#1038914\n \n#include <bits/stdc++.h>\nusing namespace std;\nconst int nax = 3e6 + 5, inf = 1e9 + 5;\nint H, str[nax], Bucket[nax], nBucket[nax]; // needed for Suffix Array\n \nstruct Suffix {\n\tint idx; // Suffix starts at idx, i.e. it's str[ idx .. L-1 ]\n\tbool operator<(const Suffix& sfx) const\n\t// Compares two suffixes based on their first 2H symbols,\n\t// assuming we know the result for H symbols.\n\t{\n\t\tif(H == 0) return str[idx] < str[sfx.idx];\n\t\telse if(Bucket[idx] == Bucket[sfx.idx]) \n\t\t\treturn (Bucket[idx+H] < Bucket[sfx.idx+H]);\n\t\telse\n\t\t\treturn (Bucket[idx] < Bucket[sfx.idx]);\n\t}\n\tbool operator==(const Suffix& sfx) const\n\t{\n\t\treturn !(*this < sfx) && !(sfx < *this);\n\t}\n} Pos[nax];\nint UpdateBuckets(int L) {\n\tint start = 0, id = 0, c = 0;\n\tfor(int i = 0; i < L; i++)\n\t{\n\t\t/*\n\t\t\tIf Pos[i] is not equal to Pos[i-1], a new bucket has started.\n\t\t*/\n\t\tif(i != 0 && !(Pos[i] == Pos[i-1]))\n\t\t{\n\t\t\tstart = i;\n\t\t\tid++;\n\t\t}\n\t\tif(i != start) // if there is bucket with size larger than 1, we should continue ...\n\t\t\tc = 1;\n\t\tnBucket[Pos[i].idx] = id; // Bucket for suffix starting at Pos[i].idx is id ...\n\t}\n\tmemcpy(Bucket, nBucket, 4 * L);\n\treturn c;\n}\nvoid SuffixSort(int L) {\n\tfor(int i = 0; i < L; i++) Pos[i].idx = i;\n\t// H == 0, Sort based on first Character.\n\tsort(Pos, Pos + L);\n\t// Create initial buckets\n\tint c = UpdateBuckets(L);\n\tfor(H=1;c;H *= 2) {\n\t\t// Sort based on first 2*H symbols, assuming that we have sorted based on first H character\n\t\tsort(Pos, Pos+L);\n\t\t// Update Buckets based on first 2*H symbols\n\t\tc = UpdateBuckets(L);\n\t}\n}\n \nint sa[nax], inv_sa[nax]; // needed for calculating LCP\n \nlong long count_substrings(vector<int> input) {\n\tlong long answer = 0;\n\tfor(int i = 0; i < (int) input.size(); ++i) str[i] = input[i];\n\tint n = input.size();\n\tSuffixSort(n + 1);\n\t// calculate LCP\n\tfor(int i = 0; i < n; ++i) {\n\t\tanswer += n - Pos[i+1].idx;\n\t\tsa[i] = Pos[i+1].idx;\n\t\tinv_sa[sa[i]] = i;\n\t}\n\tint lcp = 0;\n\tfor(int i = 0; i < n; ++i) {\n\t\tint k = inv_sa[i];\n\t\tif(k == 0) continue;\n\t\tint j = sa[k-1];\n\t\twhile(str[i+lcp] == str[j+lcp]) ++lcp;\n\t\tanswer -= lcp;\n\t\tif(lcp > 0) --lcp;\n\t}\n\treturn answer;\n}\n \nmap<int,int> m[nax];\nint getHash(int a, int b) {\n\tif(m[a].count(b)) return m[a][b];\n\tstatic int T = 2;\n\treturn m[a][b] = T++;\n}\n \nvector<int> global;\n \nvoid consider(string ss) { // gets one valid gragment, e.g. ()(())()()\n\tassert(!ss.empty());\n\t// cout << ss << \" \";\n\tss = '(' + ss + ')';\n\t// cout << ss << \"\\n\";\n\tint n = ss.length();\n\tvector<vector<int>> stack;\n\tfor(int i = 0; i < n; ++i) {\n\t\tif(ss[i] == '(') stack.push_back(vector<int>{1});\n\t\telse {\n\t\t\tvector<int> & w = stack.back();\n\t\t\tfor(int j = 1; j < (int) w.size(); ++j)\n\t\t\t\tglobal.push_back(w[j]);\n\t\t\tstatic int T = -1;\n\t\t\tglobal.push_back(T--);\n\t\t\tif(i == n - 1) return;\n\t\t\t// for(int x : w) printf(\"%d \", x);\n\t\t\tint h = w[0];\n\t\t\tfor(int j = 1; j < (int) w.size(); ++j)\n\t\t\t\th = getHash(h, w[j]);\n\t\t\tstack.pop_back();\n\t\t\tassert(!stack.empty());\n\t\t\tstack.back().push_back(getHash(h, 0));\n\t\t\t// printf(\"   h = %d (%d)\\n\", h, getHash(h, 0));\n\t\t}\n\t}\n}\n \nchar sl[nax];\nint pref[nax], minSuf[nax];\nint toValue(char z) { return z == '(' ? 1 : -1; }\n \nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tscanf(\"%s\", sl);\n\t/*set<string> brute;\n\tfor(int i = 0; i < n; ++i) {\n\t\tstring ss;\n\t\tint cnt = 0;\n\t\tfor(int j = i; j < n; ++j) {\n\t\t\tchar z = sl[j];\n\t\t\tss += z;\n\t\t\tif(z == '(') ++cnt;\n\t\t\telse --cnt;\n\t\t\tif(cnt < 0) break;\n\t\t\tif(cnt == 0) brute.insert(ss);\n\t\t}\n\t}\n\tprintf(\"%d\\n\", (int) brute.size());*/\n\t// find valid fragments, e.g. set {(), (()), ()()()} for ))())))(())(((()()()\n\tfor(int i = 0; i < n; ++i) {\n\t\tif(i) pref[i] = pref[i-1];\n\t\tpref[i] += toValue(sl[i]);\n\t}\n\tminSuf[n] = inf;\n\tfor(int i = n - 1; i >= 0; --i)\n\t\tminSuf[i] = min(minSuf[i+1], pref[i]);\n\tfor(int i = 0; i < n; ++i) {\n\t\tstring ss;\n\t\twhile(sl[i] == '(' && minSuf[i+1] < pref[i]) {\n\t\t\tss += sl[i];\n\t\t\tint val = toValue(sl[i]);\n\t\t\twhile(val) {\n\t\t\t\t++i;\n\t\t\t\tval += toValue(sl[i]);\n\t\t\t\tss += sl[i];\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\t\tif(ss.empty()) {}//printf(\"X\");\n\t\telse {\n\t\t\tconsider(ss);\n\t\t\t--i;\n\t\t}\n\t}\n\tif(global.empty()) {\n\t\tputs(\"0\");\n\t\treturn 0;\n\t}\n\tlong long answer = (long long) global.size() * (global.size() + 1) / 2;\n\tfor(int i = 0; i < (int) global.size(); ++i) if(global[i] > 0) {\n\t\tint j = i;\n\t\twhile(j + 1 < (int) global.size() && global[j+1] > 0) ++j;\n\t\tlong long tmp = j - i + 1;\n\t\tanswer -= tmp * (tmp + 1) / 2;\n\t\ti = j;\n\t}\n\tprintf(\"%lld\\n\", count_substrings(global) - answer + 1);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "string suffix structures",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "653",
    "index": "G",
    "title": "Move by Prime",
    "statement": "Pussycat Sonya has an array consisting of $n$ positive integers. There are $2^{n}$ possible subsequences of the array. For each subsequence she counts the minimum number of operations to make all its elements equal. Each operation must be one of two:\n\n- Choose some element of the subsequence and multiply it by some prime number.\n- Choose some element of the subsequence and divide it by some prime number. The chosen element must be divisible by the chosen prime number.\n\nWhat is the sum of minimum number of operations for all $2^{n}$ possible subsequences? Find and print this sum modulo $10^{9} + 7$.",
    "tutorial": "you can consider each prime number separately. Can you find the answer if there are only 1's and 2's in the input? It may be hard to try to iterate over possible placements of the median. Maybe it's better to think how many numbers we will change from 2^p to 2^{p+1}.",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 3100
  },
  {
    "contest_id": "658",
    "index": "A",
    "title": "Bear and Reverse Radewoosh",
    "statement": "Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.\n\nThere will be $n$ problems. The $i$-th problem has initial score $p_{i}$ and it takes exactly $t_{i}$ minutes to solve it. Problems are sorted by difficulty — it's guaranteed that $p_{i} < p_{i + 1}$ and $t_{i} < t_{i + 1}$.\n\nA constant $c$ is given too, representing the speed of loosing points. Then, submitting the $i$-th problem at time $x$ ($x$ minutes after the start of the contest) gives $max(0, p_{i} - c·x)$ points.\n\nLimak is going to solve problems in order $1, 2, ..., n$ (sorted increasingly by $p_{i}$). Radewoosh is going to solve them in order $n, n - 1, ..., 1$ (sorted decreasingly by $p_{i}$). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word \"Tie\" in case of a tie.\n\nYou may assume that the duration of the competition is greater or equal than the sum of all $t_{i}$. That means both Limak and Radewoosh will accept all $n$ problems.",
    "tutorial": "Iterate once from left to right to calculate one player's score and then iterate from right to left. It's generally good not to write something similar twice because you are more likely to make mistakes. Or maybe later you will find some bug and correct it only in one place. So, try to write calculating score in a function and run them twice. Maybe you will need to reverse the given arrays in some moment.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int nax = 1005;\nint n, c;\nint p[nax], t[nax];\n \nint getScore() {\n    int total = 0;\n    int T = 0;\n    for(int i = 0; i < n; ++i) {\n        T += t[i];\n        total += max(0, p[i] - T * c);\n    }\n    return total;\n}\nint main() {\n    scanf(\"%d%d\", &n, &c);\n    for(int i = 0; i < n; ++i)\n        scanf(\"%d\", &p[i]);\n    for(int i = 0; i < n; ++i)\n        scanf(\"%d\", &t[i]);\n    int score1 = getScore();\n    reverse(t, t + n);\n    reverse(p, p + n);\n    int score2 = getScore();\n    if(score1 > score2) puts(\"Limak\");\n    else if(score1 < score2) puts(\"Radewoosh\");\n    else puts(\"Tie\");\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "659",
    "index": "A",
    "title": "Round House",
    "statement": "Vasya lives in a round building, whose entrances are numbered sequentially by integers from $1$ to $n$. Entrance $n$ and entrance $1$ are adjacent.\n\nToday Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance $a$ and he decided that during his walk he will move around the house $b$ entrances in the direction of increasing numbers (in this order entrance $n$ should be followed by entrance $1$). The negative value of $b$ corresponds to moving $|b|$ entrances in the order of decreasing numbers (in this order entrance $1$ is followed by entrance $n$). If $b = 0$, then Vasya prefers to walk beside his entrance.\n\n\\begin{center}\n{\\small Illustration for $n = 6$, $a = 2$, $b = - 5$.}\n\\end{center}\n\nHelp Vasya to determine the number of the entrance, near which he will be at the end of his walk.",
    "tutorial": "The answer for the problem is calculated with a formula $((a - 1 + b)$ $\\mathrm{mod}$ $n$ + $n$) $\\mathrm{mod}$ $n$ + $1$. Such solution has complexity $O(1)$. There is also a solution with iterations, modelling every of $|b|$'s Vasya's moves by one entrance one by one in desired direction, allowed to pass all the tests. This solution's complexity is $O(|b|)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "659",
    "index": "B",
    "title": "Qualifying Contest",
    "statement": "Very soon Berland will hold a School Team Programming Olympiad. From each of the $m$ Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by $n$ Berland students. There were at least two schoolboys participating from each of the $m$ regions of Berland. The result of each of the participants of the qualifying competition is an integer score from $0$ to $800$ inclusive.\n\nThe team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a \\textbf{greater} number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.\n\nYour task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.",
    "tutorial": "Let's consider the participants from every region separately. So for every region we just need to sort all of its participants by their score in non-increasing order. The answer for a region is inconsistent if and only if the score of the second and the third participant in this order are equal, otherwise the answer is the first and the second participant in this order. The solution complexity is $O(n\\log n)$.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "659",
    "index": "C",
    "title": "Tanya and Toys",
    "statement": "In Berland recently a new collection of toys went on sale. This collection consists of $10^{9}$ types of toys, numbered with integers from $1$ to $10^{9}$. A toy from the new collection of the $i$-th type costs $i$ bourles.\n\nTania has managed to collect $n$ different types of toys $a_{1}, a_{2}, ..., a_{n}$ from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than $m$ bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.\n\nTanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.",
    "tutorial": "Our task is to take largest amount of toys Tanya doesn't have yet the way the sum of their costs doesn't exceed $m$. To do that one can perform greedy algorithm: let's buy the cheepest toy Tanya doesn't have at every step, while the amount of money left are sufficient to do that. The boolean array $used$ can be a handle in that, storing $true$ values in indices equal to toy types which Tanya does have at the moment. As soon as $10^{9}$ money is sufficient to buy no more than $10^{5}$ toys $\\ ({\\frac{(1^{9}\\times(10^{9}+1)}{2}}\\geq10^{9})$, $used$ is enough to be sized $2  \\times  10^{5}$ (we won't buy the toys with types numbered greater). So we just need to iterate over the number of type we want to buy, and if corresponding value in $used$ is equal to $false$, we should buy it, otherwise we can't. The solution complexity is $O(n+{\\sqrt{m}})$. One can use the <> data structure (C++ \\texttt{std::set}, for example), for storing the types Tanya has at the moment. In this case the complexity is $O(n+{\\sqrt{m}}\\log n)$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "659",
    "index": "D",
    "title": "Bicycle Race",
    "statement": "Maria participates in a bicycle race.\n\nThe speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.\n\nLet's introduce a system of coordinates, directing the $Ox$ axis from west to east, and the $Oy$ axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).\n\nMaria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.\n\nHelp Maria get ready for the competition — determine the number of dangerous turns on the track.",
    "tutorial": "From the track description follows that Maria moves the way that the water always located to the right from her, so she could fall into the water only while turning left. To check if the turn is to the left, let's give every Maria's moves directions a number: moving to the north - $0$, moving to the west - $1$, to the south - $2$ and to the east - $3$. Then the turn is to the left if and only if the number of direction after performing a turn $dir$ is equal to the number before performing a turn $oldDir$ plus one modulo $4$ $(d i r\\equiv o l d D i r+1(\\mod4))$. This solution has complexity $O(n)$. One can solve this problem in alternative way. Let the answer be equal to $x$ (that means that the number of inner corners of $270$ degrees equals $x$, but the number of inner corners of $90$ degrees to $n - x$). As soon as the sum of the inner corners' values of polygon of $n$ vertices is equal to $180  \\times  (n - 2)$, then $x  \\times  270 + (n - x)  \\times  90$ equals to $180  \\times  (n - 2)$. This leads us to $x={\\frac{n-4}{2}}$, being the answer for the problem calculated in $O(1)$.",
    "tags": [
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "659",
    "index": "E",
    "title": "New Reform",
    "statement": "Berland has $n$ cities connected by $m$ bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is \\textbf{not guaranteed} that you can get from any city to any other one, using only the existing roads.\n\nThe President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).\n\nIn order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.\n\nHelp the Ministry of Transport to find the minimum possible number of separate cities after the reform.",
    "tutorial": "One should notice, that for every connected component of the graph the problem could be solved independently, so we just need to solve the problem for any connected graph. Let this connected graph (of $n$ vertices) contain $n - 1$ edge (such is called a tree). If one maintain a DFS from any of its vertex, every edge will be oriented, and each of them could given to its ending vertex, this way every vertex (except the one we launched DFS from, that is the root) will be satisfied by an edge. In this case the answer is equal to $1$. Let's then deal with a case when the graph contains more than $n - 1$ edges. This graph contains at least one cycle. Let's take arbitrary vertex from any of the cycles and launch a DFS (as above) from it. All vertices except chosen will be satisfied, so we are to give an edge to the chosen vertex. As soon as chosen vertex belongs to a cycle, at least one of its edge will not be taken to account in the DFS, so it can be given to a root. This way all the vertices will be satisfied. Now we are able to solve the task for any connected graph, so we are to divide the graph into a connected components - this can be easily done by DFS or BFS. The solution complexity is $O(n + m)$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "659",
    "index": "F",
    "title": "Polycarp and Hay",
    "statement": "The farmer Polycarp has a warehouse with hay, which can be represented as an $n × m$ rectangular table, where $n$ is the number of rows, and $m$ is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the $i$-th row and the $j$-th column is equal to an integer $a_{i, j}$ and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base $1 × 1$. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.\n\nPolycarp wants the following requirements to hold after the reorganization:\n\n- the total amount of hay remaining in the warehouse must be \\textbf{equal} to $k$,\n- the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same,\n- the height of at least one stack must remain the same as it was,\n- for the stability of the remaining structure all the stacks should form one connected region.\n\nThe two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.\n\nHelp Polycarp complete this challenging task or inform that it is impossible.",
    "tutorial": "In this task one should find a connected area, in which the product of the minimum value of the cells and the number of the cells is equal to $k$. To find such, let's sort all the $n  \\times  m$ cells by their values by non-increasing order. Then we will consecutively add them in this order one by one, maintaining a connected components on their neighbouring relations graph. It's enough to use Disjoint Set Union structure to do so, storing additionally size of every component. Let $a_{i, j}$ be the last added element in some component $id$, so $a_{i, j}$ has the minimum value among all the cells in component $id$ (according to our ordering). If $a_{i, j}$ does not divide $k$, then the component $id$ could not consist of desired area. Otherwise ($a_{i, j}$ is divisor of $k$), let's find $need = k / a_{i, j}$ - desired area size (if it contains $a_{i, j}$), and if $CNT_{id}$ is not less than $need$, then the component $id$ contains desired area, which could be easily found by launching a DFS in a neighbouring relation graph from $a_{i, j}$, visiting only the $a_{p, q}  \\ge  a_{i, j}$ and exactly $need$ of them. The solution complexity is $O(n^{2}\\log{n})$.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "659",
    "index": "G",
    "title": "Fence Divercity",
    "statement": "Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of $n$ consecutively fastened vertical boards of centimeter width, the height of each in centimeters is \\textbf{a positive integer}. The house owner remembers that the height of the $i$-th board to the left is $h_{i}$.\n\nToday Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).\n\nYou, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such $i$, that the height of the $i$-th boards vary.\n\nAs Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by $1 000 000 007$ $(10^{9} + 7)$.",
    "tutorial": "Let the answer for the problem be the sum $\\sum_{l=1}^{n}\\sum_{T=l}^{n}c a l c(l,r),$ where $calc(l, r)$ is the number of ways to cut the top part of the fence the way its leftmost part is in position $l$ and the rightmost in position $r$. If $l = r$, that is the case when the cutted top part consists of part of only one board, then $calc(l, r) = h_{l} - 1$. Let $r > l$, then $\\begin{array}{c}{{c a l l c}{{c a l c(l,r)=\\operatorname*{min}(h_{l}-1,h_{l+1}-1)\\times\\operatorname*{min}(h_{r-1}-1,h_{r}-1)\\times\\prod_{i=l+1}^{r-1}\\operatorname*{min}(h_{i-1}-1)\\times\\prod_{i=l}^{r}\\operatorname*{min}(h_{i-1}-1)}}\\\\ {{1,h_{i}-1,h_{i+1}-1).}}\\end{array}$ In other words, the number of ways to cut the top part of some board is equal to minimum value among heights of it and its neighbours minus one, otherwise the cutted part will be inconsistent. Leftmost board and rightmost board are considered separately, because each of them does have only one neighbouring board. So the answer looks like $\\begin{array}{l}{{\\sum_{i=0}^{\\left\\lfloor n\\right\\rfloor}(h_{i}-1)+\\sum_{l=1}^{n}\\sum_{r=l+1}^{n}\\operatorname*{min}(h_{l}-1,h_{l+1}-1)\\times\\operatorname*{min}(h_{r-1}-1,h_{r}-1)\\right\\rfloor}}\\\\ {{\\mid\\times\\prod_{i=1+1}^{n-1}\\operatorname*{min}(h_{i-1}-1,h_{i}-1).}}\\end{array}$ The first summand is easy to calculate, so let's take a look at the second. Let us modify it as the following: $\\begin{array}{c}{{\\sum_{r=2}^{n}\\operatorname*{min}(h_{r-1}-1,h_{r}-1)\\times\\sum_{l=1}^{r-1}\\operatorname*{min}(h_{l}-1,h_{l+1}-1)\\times\\prod_{i=l+1}^{r-1}\\operatorname*{min}(h_{i-1}-1)\\sum\\prod_{i=l+1}^{r-1}\\operatorname*{min}(h_{i-1}-1)\\sum\\prod_{i=l}^{r}\\operatorname*{min}(h_{i-1}-1)\\operatorname*{sgn}(h_{i}-1)\\rangle\\right\\},}}\\\\ {{\\frac{1}{g_{i}}-1,h_{i+1}-1.}}\\end{array}$ Let $S(r)=\\sum_{l=1}^{r-1}\\operatorname*{min}(h_{l}-1,h_{l+1}-1)\\times\\prod_{i=l+1}^{r-1}\\operatorname*{min}(h_{i-1}-1,h_{i}-1,h_{i+1}-1).$ Let's take a look how does the $S(r)$ change after increasing $r$ by one: $S(r + 1) = S(r)  \\times  min(h_{r - 1} - 1, h_{r} - 1, h_{r + 1} - 1) + min(h_{r} - 1, h_{r + 1} - 1).$ This way this sum is easy to maintain if consecutively increase $r$ from $2$ to $n$. The solution complexity is $O(n)$.",
    "tags": [
      "combinatorics",
      "dp",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "660",
    "index": "A",
    "title": "Co-prime Array",
    "statement": "You are given an array of $n$ elements, you must make it a co-prime array in as few moves as possible.\n\nIn each move you can insert any positive integral number you want not greater than $10^{9}$ in any place in the array.\n\nAn array is co-prime if any two adjacent numbers of it are co-prime.\n\nIn the number theory, two integers $a$ and $b$ are said to be co-prime if the only positive integer that divides both of them is $1$.",
    "tutorial": "Note that we should insert some number between any adjacent not co-prime elements. On other hand we always can insert the number $1$. Complexity: $O(nlogn)$.",
    "code": "const int N = 1010;\n\nint n, a[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nvoid solve() {\n\tfunction<int(int, int)> gcd = [&](int a, int b) { return !a ? b : gcd(b % a, a); };\n\n\tvector<int> ans;\n\tforn(i, n) {\n\t\tans.pb(a[i]);\n\t\tif (i + 1 < n && gcd(a[i], a[i + 1]) > 1)\n\t\t\tans.pb(1);\n\t}\n\n\tcout << sz(ans) - n << endl;\n\tforn(i, sz(ans)) {\n\t\tif (i) putchar(' ');\n\t\tprintf(\"%d\", ans[i]);\n\t}\n\tputs(\"\");\n}",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "660",
    "index": "B",
    "title": "Seating On Bus",
    "statement": "Consider $2n$ rows of the seats in a bus. $n$ rows of the seats on the left and $n$ rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is $4n$.\n\nConsider that $m$ ($m ≤ 4n$) people occupy the seats in the bus. The passengers entering the bus are numbered from $1$ to $m$ (in the order of their entering the bus). The pattern of the seat occupation is as below:\n\n$1$-st row left window seat, $1$-st row right window seat, $2$-nd row left window seat, $2$-nd row right window seat, ... , $n$-th row left window seat, $n$-th row right window seat.\n\nAfter occupying all the window seats (for $m > 2n$) the non-window seats are occupied:\n\n$1$-st row left non-window seat, $1$-st row right non-window seat, ... , $n$-th row left non-window seat, $n$-th row right non-window seat.\n\nAll the passengers go to a single final destination. In the final destination, the passengers get off in the given order.\n\n$1$-st row left non-window seat, $1$-st row left window seat, $1$-st row right non-window seat, $1$-st row right window seat, ... , $n$-th row left non-window seat, $n$-th row left window seat, $n$-th row right non-window seat, $n$-th row right window seat.\n\n\\begin{center}\n{\\small The seating for $n = 9$ and $m = 36$.}\n\\end{center}\n\nYou are given the values $n$ and $m$. Output $m$ numbers from $1$ to $m$, the order in which the passengers will get off the bus.",
    "tutorial": "In this problem you should simply do what was written in the problem statement. There are no tricks. Complexity: $O(n)$.",
    "code": "int n, m;\n\nbool read() {\n\treturn !!(cin >> n >> m);\n}\n\nconst int N = 111;\n\nint a[N][4];\n\nvoid solve() {\n\tforn(i, n) {\n\t\ta[i][0] = 2 * i;\n\t\ta[i][1] = 2 * (n + i);\n\t\ta[i][2] = 2 * (n + i) + 1;\n\t\ta[i][3] = 2 * i + 1;\n\t}\n\n\tvector<int> ans;\n\tforn(i, n) {\n\t\tans.pb(a[i][1]);\n\t\tans.pb(a[i][0]);\n\t\tans.pb(a[i][2]);\n\t\tans.pb(a[i][3]);\n\t}\n\n\tnfor(i, sz(ans)) // inverse order\n\t\tif (ans[i] >= m)\n\t\t\tans.erase(ans.begin() + i);\n\n\tforn(i, m) {\n\t\tif (i) putchar(' ');\n\t\tprintf(\"%d\", ans[i] + 1);\n\t}\n\tputs(\"\");\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "660",
    "index": "C",
    "title": "Hard Process",
    "statement": "You are given an array $a$ with $n$ elements. Each element of $a$ is either $0$ or $1$.\n\nLet's denote the length of the longest subsegment of consecutive elements in $a$, consisting of only numbers one, as $f(a)$. You can change no more than $k$ zeroes to ones to maximize $f(a)$.",
    "tutorial": "Let's call the segment $[l, r]$ good if it contains no more than $k$ zeroes. Note if segment $[l, r]$ is good than the segment $[l + 1, r]$ is also good. So we can use the method of two pointers: the first pointer is $l$ and the second is $r$. Let's iterate over $l$ from the left to the right and move $r$ while we can (to do that we should simply maintain the number of zeroes in the current segment). Complexity: $O(n)$.",
    "code": "const int N = 1200300;\n\nint n, k;\nint a[N];\n\nbool read() {\n\tif (!(cin >> n >> k)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nvoid solve() {\n\tint ansl = 0, ansr = 0;\n\tint j = 0, cnt = 0;\n\tforn(i, n) {\n\t\tif (j < i) {\n\t\t\tj = i;\n\t\t\tcnt = 0;\n\t\t}\n\n\t\twhile (j < n) {\n\t\t\tint ncnt = cnt + !a[j];\n\t\t\tif (ncnt > k) break;\n\t\t\tcnt += !a[j];\n\t\t\tj++;\n\t\t}\n\t\t\n\t\tif (j - i > ansr - ansl)\n\t\t\tansl = i, ansr = j;\n\n\t\tif (cnt > 0) cnt -= !a[i];\n\t}\n\n\tcout << ansr - ansl << endl;\n\tfore(i, ansl, ansr) a[i] = 1;\n\tforn(i, n) {\n\t\tif (i) putchar(' ');\n\t\tprintf(\"%d\", a[i]);\n\t}\n\tputs(\"\");\n}",
    "tags": [
      "binary search",
      "dp",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "660",
    "index": "D",
    "title": "Number of Parallelograms",
    "statement": "You are given $n$ points on a plane. All the points are distinct, and no three of them lie on the same line. Find the number of parallelograms with vertices at the given points.",
    "tutorial": "It's known that the diagonals of a parallelogram split each other in the middle. Let's iterate over the pairs of points $a, b$ and consider the middle of the segment $\\overline{{a b}}$: $c={\\frac{a+b}{2}}$. Let's calculate the value $cnt_{c}$ for each middle. $cnt_{c}$ is the number of segments $a, b$ with the middle $c$. Easy to see that the answer is $\\sum_{e}{\\frac{c n i c\\cdot(c n t_{e}-1)}{2}}$. Complexity: $O(n^{2}logn)$.",
    "code": "const int N = 2020;\n\nint n;\nint x[N], y[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n)\n\t\tassert(scanf(\"%d%d\", &x[i], &y[i]) == 2);\n\treturn true;\n}\n\ninline li C2(li n) { return n * (n - 1) / 2; }\n\nvoid solve() {\n\tmap<pti, int> cnt;\n\n\tforn(i, n)\n\t\tforn(j, i) {\n\t\t\tint cx = x[i] + x[j];\n\t\t\tint cy = y[i] + y[j];\n\t\t\tcnt[{cx, cy}]++;\n\t\t}\n\n\tli ans = 0;\n\tfor (const auto& p : cnt)\n\t\tans += C2(p.y);\n\tcout << ans << endl;\n}",
    "tags": [
      "geometry"
    ],
    "rating": 1900
  },
  {
    "contest_id": "660",
    "index": "E",
    "title": "Different Subsets For All Tuples",
    "statement": "For a sequence $a$ of $n$ integers between $1$ and $m$, inclusive, denote $f(a)$ as the number of distinct subsequences of $a$ (including the empty subsequence).\n\nYou are given two positive integers $n$ and $m$. Let $S$ be the set of all sequences of length $n$ consisting of numbers from $1$ to $m$. Compute the sum $f(a)$ over all $a$ in $S$ modulo $10^{9} + 7$.",
    "tutorial": "Let's consider some subsequence with the length $k > 0$ (the empty subsequences we will count separately by adding the valye $m^{n}$ at the end) and count the number of sequences that contains it. We should do that accurately to not count the same sequence multiple times. Let $x_{1}, x_{2}, ..., x_{k}$ be the fixed subsequence. In the original sequence before the element $x_{1}$ can be some other elements, but none of them can be equal to $x_{1}$ (because we want to count the subsequence exactly one time). So we have $m - 1$ variants for each of the elements before $x_{1}$. Similarly between elements $x_{1}$ and $x_{2}$ can be other elements and we have $m - 1$ choices for each of them. And so on. After the element $x_{k}$ can be some elements (suppose there are $j$ such elements) with no additional constraints (so we have $m$ choices for each of them). We fixed the number of elements at the end $j$, so we should distribute $n - k - j$ numbers between numbers before $x_{1}$, between $x_{1}$ and $x_{2}$, \\ldots, between $x_{k - 1}$ and $x_{k}$. Easy to see that we have $\\textstyle{\\binom{n-j-1}{k-1}}$ choices to do that (it's simply binomial coefficient with allowed repititions). The number of sequences $x_{1}, x_{2}, ..., x_{k}$ equals to $m^{k}$. So the answer is $\\sum_{k=1}^{n}\\sum_{j=0}^{n-k}m^{k}m^{j}(m-1)^{n-j-k}{\\binom{n-j-1}{k-1}}$. Easy to transform the last sum to the sum $\\sum_{s=1}^{n}m^{s}(m-1)^{n-s}\\sum_{k=0}^{s-1}{\\binom{n-s+k}{k}}$. Note the last inner sum can be calculating using the formula for parallel summing: $\\sum_{k<n}{\\binom{r+k}{k}}\\ =\\ {\\binom{r+n+1}{n}}$. So the answer equals to $m^{n}+\\sum_{s=1}^{n}m^{s}(m-1)^{n-s}{\\binom{n}{s-1}}$. Also we can get the closed formula for the last sum to get logarithmic solution, but it is not required in the problem. Complexity: $O((n + m)log MOD)$, where $MOD = 10^{9} + 7$.",
    "code": "int n, m;\n\nbool read() {\n\treturn !!(cin >> n >> m);\n}\n\nconst int N = 1200300;\n\nconst int mod = 1000 * 1000 * 1000 + 7;\n\nint gcd(int a, int b, int& x, int& y) {\n\tif (!a) {\n\t\tx = 0, y = 1;\n\t\treturn b;\n\t}\n\tint xx, yy, g = gcd(b % a, a, xx, yy);\n\tx = yy - b / a * xx;\n\ty = xx;\n\treturn g;\n}\n\ninline int inv(int a) {\n\tint x, y;\n\tassert(gcd(a, mod, x, y) == 1);\n\tx %= mod;\n\treturn x < 0 ? x + mod : x;\n}\n\ninline int mul(int a, int b) { return int(a * 1ll * b % mod); }\ninline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }\ninline int sub(int a, int b) { return a - b < 0 ? a - b + mod : a - b; }\n\ninline void inc(int& a, int b) { a = add(a, b); }\n\nint fact[N], ifact[N];\n\ninline int C(int n, int k) {\n\tif (k < 0 || k > n) return 0;\n\treturn mul(fact[n], mul(ifact[k], ifact[n - k]));\n}\n\nint pm[N], pm1[N];\n\nvoid solve() {\n\tconst int N = n + 1;\n\n\tfact[0] = 1; fore(i, 1, N) fact[i] = mul(fact[i - 1], i);\n\tforn(i, N) ifact[i] = inv(fact[i]);\n\n\tpm[0] = 1; fore(i, 1, N) pm[i] = mul(pm[i - 1], m);\n\tpm1[0] = 1; fore(i, 1, N) pm1[i] = mul(pm1[i - 1], sub(m, 1));\n\n\tint ans = pm[n];\n\tfore(s, 1, n + 1) {\n\t\tint cur = 1;\n\t\tcur = mul(cur, pm[s]);\n\t\tcur = mul(cur, pm1[n - s]);\n\t\tcur = mul(cur, C(n, s - 1));\n\t\tinc(ans, cur);\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "660",
    "index": "F",
    "title": "Bear and Bowling 4",
    "statement": "Limak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record!\n\nFor rolling a ball one gets a score — an integer (maybe negative) number of points. Score for the $i$-th roll is multiplied by $i$ and scores are summed up. So, for $k$ rolls with scores $s_{1}, s_{2}, ..., s_{k}$, the total score is $\\textstyle\\sum_{i=1}^{k}i\\cdot s_{i}$. The total score is $0$ if there were no rolls.\n\nLimak made $n$ rolls and got score $a_{i}$ for the $i$-th of them. He wants to maximize his total score and he came up with an interesting idea. He can say that some first rolls were only a warm-up, and that he wasn't focused during the last rolls. More formally, he can cancel any prefix and any suffix of the sequence $a_{1}, a_{2}, ..., a_{n}$. It is allowed to cancel all rolls, or to cancel none of them.\n\nThe total score is calculated as if there were only non-canceled rolls. So, the first non-canceled roll has score multiplied by $1$, the second one has score multiplied by $2$, and so on, till the last non-canceled roll.\n\nWhat maximum total score can Limak get?",
    "tutorial": "The key is to use divide and conquer. We need a recursive function f(left, right) that runs f(left, mid) and f(mid+1, right) (where $mid = (left + right) / 2$) and also considers all intervals going through $mid$. We will eventually need a convex hull of lines (linear functions) and let's see how to achieve it. For variables $L, R$ ($L\\in[l e f t,m i d]$, $R\\in[m i d+1,r i g h t]$) we will try to write the score of interval $[L, R]$ as a linear function. It would be good to get something close to $a_{L} \\cdot x_{R} + b_{L}$ where $a_{L}$ and $b_{L}$ depend on $L$, and $x_{R}$ depends on $R$ only. $\\begin{array}{l}{{\\displaystyle=\\sum_{i=L}^{R}t_{i}\\cdot(i-L+1)+\\sum_{i=m i d+1}^{R}}}\\\\ {{=\\sum_{i=L}^{m_{i=L}}t_{i}\\cdot(i-L+1)+\\sum_{i=m i d+1}t_{i}\\cdot(i-L+1)}}\\\\ {{=\\sum_{i=L}^{m_{i=L}}t_{i}\\cdot(i-L+1)+\\sum_{i=m i d+1}t_{i}\\cdot(i-m i d)}}\\\\ {{=\\left.\\sum_{i=m i d+1}t_{i}\\cdot(i-L+1)+\\sum_{i=m i d+2}t_{i}\\right)+\\sum_{i=m i d+1}t_{i}\\cdot(i-m i d+1}t_{i})}}\\end{array}$ For each $L$ we should find a linear function $f_{L}(x) = a_{L} \\cdot x + b_{L}$ where $a_{L}, b_{L}$ should fit the equation $( * )$: $\\begin{array}{c}{{b_{L}=\\sum_{i=L}^{m i d}t_{i}\\cdot\\left(i-L+1\\right)}}\\\\ {{a_{L}=m\\dot{\\imath}d-L+1}}\\end{array}$ Now we have a set of linear functions representing all possible left endpoints $L$. For each right endpoint $R$ we should find $x_{R}$ and $const_{R}$ to fit equation $( * )$ again. With value of $x_{R}$ we can iterate over functions $f_{L}$ to find the one maximizing value of $b_{L} + a_{L} \\cdot x_{R}$. And (still for fixed $R$) we should add $const_{R}$ to get the maximum possible score of interval ending in $R$. Now let's make it faster. After finding a set of linear functions $f_{L}$ we should build a convex hull of them (note that they're already sorted by slope). To achieve it we need something to compare $3$ functions and decide whether one of them is unnecessary because it's always below one of other two functions. Note that in standard convex hull of points you also need something similar (but for $3$ points). Below you can find an almost-fast-enough solution with a useful function bool is_middle_needed(f1, f2, f3). You may check that numbers calculated there do fit in long long. Finally, one last thing is needed to make it faster than $O(n^{2})$. We should use the fact that we have built a convex hull of functions (lines). For each $R$ you should binary search optimal function. Alternatively, you can sort pairs $(x_{R}, const_{R})$ and then use the two pointers method - check the implementation in my solution below. It gives complexity $O(n\\cdot\\log^{2}(n))$ because we sort by $x_{R}$ inside of a recursive function. I think it's possible to get rid of this by sorting prefixes ${\\mathrm{prefix}}_{R}=\\textstyle\\sum_{i=1}^{R}t_{i}$ in advance because it's equivalent to sorting by $x_{R}$. And we should use the already known order when we run a recursive function for smaller intervals. So, I think $O(n\\log n)$ is possible this way - anybody implemented it? Complexity: $O(nlog^{2}n)$.",
    "code": "// O(n log^2(n))\n#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int nax = 1e6 + 5;\nll ans;\nll t[nax];\n\nstruct Fun {\n\tll a, b;\n\tll getValue(ll x) { return a * x + b; }\n};\n\nbool is_middle_needed(const Fun & f1, const Fun & f2, const Fun & f3) {\n\t// we ask if for at least one 'x' there is f2(x) > max(f1(x), f3(x))\n\tassert(0 < f1.a && f1.a < f2.a && f2.a < f3.a);\n\t\n\t// where is the intersection of f1 and f2?\n\t// f1.a * x + f1.b = f2.a * x + f2.b\n\t// x * (f2.a - f1.a) = f1.b - f2.b\n\t// x = (f1.b - f2.b) / (f2.a - f1.a)\n\tll p1 = f1.b - f2.b;\n\tll q1 = f2.a - f1.a;\n\t// and the intersection of f1 and f3\n\tll p2 = f1.b - f3.b;\n\tll q2 = f3.a - f1.a;\n\tassert(q1 > 0 && q2 > 0);\n\t// return p1 / q1 < p2 / q2\n\treturn p1 * q2 < q1 * p2;\n}\n\nvoid rec(int first, int last) {\n\tif(first == last) {\n\t\tans = max(ans, t[first]);\n\t\treturn;\n\t}\n\tint mid = (first + last) / 2;\n\t\n\trec(first, mid); // the left half is [first, mid]\n\trec(mid+1, last); // the right half is [mid+1, last]\n\t\n\t// we must consider all intervals starting in [first,mid] and ending in [mid+1, last]\n\t\n\tvector<Fun> functions;\n\tll sum_so_far = 0; // t[i]+t[i+1]+...+t[mid]\n\tll score_so_far = 0; // t[i]*1 + t[i+1]*2 + ... + t[mid]*(mid-i+1)\n\tfor(int i = mid; i >= first; --i) {\n\t\tsum_so_far += t[i];\n\t\tscore_so_far += sum_so_far;\n\t\tFun f = Fun{mid - i + 1, score_so_far};\n\t\twhile(true) {\n\t\t\tint s = functions.size();\n\t\t\tif(s >= 2 && !is_middle_needed(functions[s-2], functions[s-1], f))\n\t\t\t\tfunctions.pop_back();\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\tfunctions.push_back(f);\n\t}\n\t\n\tvector<pair<ll, ll>> points;\n\tsum_so_far = 0;\n\tscore_so_far = 0;\n\tfor(int i = mid+1; i <= last; ++i) {\n\t\tsum_so_far += t[i];\n\t\tscore_so_far += t[i] * (i - mid);\n\t\tpoints.push_back({sum_so_far, score_so_far});\n\t\t/*for(Fun & f : functions) {\n\t\t\tll score = score_so_far + f.getValue(sum_so_far);\n\t\t\tans = max(ans, score);\n\t\t}*/\n\t}\n\t\n\tsort(points.begin(), points.end());\n\tint i = 0; // which function is the best\n\tfor(pair<ll, ll> p : points) {\n\t\tsum_so_far = p.first;\n\t\tscore_so_far = p.second;\n\t\twhile(i + 1 < (int) functions.size()\n\t\t\t&& functions[i].getValue(sum_so_far) <= functions[i+1].getValue(sum_so_far))\n\t\t\t\t++i;\n\t\tans = max(ans, score_so_far + functions[i].getValue(sum_so_far));\n\t}\n}\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i) scanf(\"%lld\", &t[i]);\n\trec(1, n);\n\tprintf(\"%lldn\", ans);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "geometry",
      "ternary search"
    ],
    "rating": 2500
  },
  {
    "contest_id": "662",
    "index": "A",
    "title": "Gambling Nim",
    "statement": "As you know, the game of \"Nim\" is played with $n$ piles of stones, where the $i$-th pile initially contains $a_{i}$ stones. Two players alternate the turns. During a turn a player picks any non-empty pile and removes any positive number of stones from it. The one who is not able to make a move loses the game.\n\nPetya and Vasya are tired of playing Nim, so they invented their own version of the game and named it the \"Gambling Nim\". They have $n$ two-sided cards, one side of the $i$-th card has number $a_{i}$ written on it, while the other side has number $b_{i}$. At the beginning of the game the players put all the cards on the table, each card only one of its sides up, and this side is chosen independently and uniformly. Thus they obtain a sequence $c_{1}, c_{2}, ..., c_{n}$, where $c_{i}$ is equal to $a_{i}$ or $b_{i}$. Then they take $n$ piles of stones, with $i$-th pile containing exactly $c_{i}$ stones and play Nim. Petya takes the first turn.\n\nGiven that both players play optimally, find the probability of Petya's victory. Output the answer as an irreducible fraction.",
    "tutorial": "It is known that the first player loses if and only if the $xor$-sum of all numbers is $0$. Therefore the problem essentially asks to calculate the number of ways to arrange the cards in such a fashion that the $xor$-sum of the numbers on the upper sides of the cards is equal to zero. Let $S=a_{1}\\oplus a_{2}\\oplus\\cdots\\oplus a_{n}$ and $c_{i}=a_{i}\\oplus b_{i}$. Suppose that the cards with indices $j_{1}, j_{2}, ..., j_{k}$ are faced with numbers of type $b$ and all the others with numbers of type $a$. Then the $xor$-sum of this arrangement is equal to $S\\oplus c_{j1}\\oplus c_{j2}\\oplus\\cdots\\leftrightarrow c_{j k}$, that is, $S\\oplus[x o r.{\\mathrm{sum}}\\ \\mathrm{of\\some{\\sulset}}\\,c_{i}]$. Hence we want to find the number of subsets $c_{i}$ with $xor$-sum of $S$. Note that we can replace $c_{1}$ with $(c_{1}\\oplus c_{2})$, as applying $c_{1}$ is the same as applying $(c_{1}\\oplus c_{2})\\oplus c_{2}$. Thus we can freely replace ${c_{1}, c_{2}}$ with $(c_{1}\\oplus c_{2})$ and $c_{2}$ with $\\{c_{1},c_{1}\\oplus c_{2}\\}$. This means that we can apply the following procedure to simplify the set of $c_{i}$: Pick $c_{f}$ with the most significant bit set to one Replace each $c_{i}$ with the bit in that position set to one to $c_{i}\\oplus c_{f}$ Remove $c_{f}$ from the set Repeat steps $1$-$5$ with the remaining set Add $c_{f}$ back to the set After this procedure we get a set that contains $k$ zeros and $n - k$ numbers with the property that the positions of the most significant bit set to one strictly decrease. How do we check now whether it is possible to obtain a subset with $xor$-sum $S$? As we have at most one number with a one in the most significant bit, then it tells us whether we should include that number in the subset or not. Similarly we apply the same argument for all other bits. If we don't obtain a subset with the $xor$-sum equal to $S$, then there is no such subset at all. If we do get a subset with $xor$-sum $S$, then the total number of such subsets is equal to $2^{k}$, as for each of the $n - k$ non-zero numbers we already know whether it must be include in such a subset or not, but any subset of $k$ zeros doesn't change the $xor$-sum. In this case the probability of the second player winning the game is equal to ${\\frac{2k}{2^{n}}}$, so the first player wins with probability $\\frac{2^{n-k}-1}{2^{n-k}}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int size = 1000 * 1000 + 1;\nconst int ssize = 100;\n\nint n;\nlong long a[size], b[size];\nlong long ort[ssize];\nlong long p[ssize];\n\nint main() {\n    long long cur = 0ll;\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; i++) {\n        scanf(\"%lld%lld\", &a[i], &b[i]);\n        cur ^= a[i];\n        a[i] ^= b[i];\n    }\n    a[n] = cur;\n\n    int len = 0;\n    for (int i = 0; i <= n; i++) {\n        for (int j = 0; j < len; j++) {\n            if (a[i] & p[j])\n                a[i] ^= ort[j];\n        }\n        if (a[i]) {\n            ort[len++] = a[i];\n            p[len - 1] = ((a[i] ^ (a[i] - 1)) + 1) >> 1;\n        }        \n    }\n    if (a[n]) {\n        printf(\"1/1\\\\n\");\n    } else {\n        printf(\"%lld/%lld\\\\n\", (1ll << len) - 1, (1ll << len));\n    }\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "math",
      "matrices",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "662",
    "index": "B",
    "title": "Graph Coloring",
    "statement": "You are given an undirected graph that consists of $n$ vertices and $m$ edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of \\textbf{all} edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.\n\nFind the minimum possible number of moves required to make the colors of all edges equal.",
    "tutorial": "Author of the problem - gen Examine the two choices for the final color separately, and pick the best option afterwards. Now suppose we want to color the edges red. Each vertex should be recolored at most once, since choosing a vertex two times changes nothing (even if the moves are not consecutive). Thus we need to split the vertices into two sets $S$ and $T$, the vertices that are recolored and the vertices that are not affected, respectively. Let $u$ and $v$ be two vertices connected by a red edge. Then for the color to remain red, both $u$ and $v$ should belong to the same set (either $S$ or $T$). On the other hand, if $u$ and $v$ are connected by a blue edge, then exactly one of the vertices should be recolored. In that case $u$ and $v$ should belong to different sets (one to $S$ and the other to $T$). This problem reduces to $0$-$1$ graph coloring, which can be solved by either $DFS$ or $BFS$. As the graph may be disconnected, we need to process the components separately. If any component does not have a $0$-$1$ coloring, there is no solution. Otherwise we need to add the smallest of the two partite sets of the $0$-$1$ coloring of this component to $S$, as we require $S$ to be of minimum size.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MX = 100000;\n\nint n, vis[MX];\nvector<pair<int, char>> G[MX];\nvector<int> part[3];\n\nbool dfs(int v, int p, char c) {\n    if (vis[v] != 0) {\n        return vis[v] == p;\n    }\n\n    vis[v] = p;\n    part[p].push_back(v);\n\n    for (auto x : G[v]) {\n        if (dfs(x.first, x.second == c ? p : p ^ 3, c) == false)\n            return false;\n    }\n\n    return true;\n}\n\nvector<int> solve(char c) {\n    memset(vis, 0, sizeof vis);\n\n    vector<int> ans;\n    for (int i = 0; i < n; i++)\n        if (vis[i] == 0) {\n            part[1].clear();\n            part[2].clear();\n\n            if (dfs(i, 1, c) == false) {\n                for (int j = 0; j < n + 1; j++) ans.push_back(-1);\n\n                return ans;\n            }\n\n            int f = 1;\n            if (part[2].size() < part[1].size()) f = 2;\n\n            ans.insert(ans.end(), part[f].begin(), part[f].end());\n        }\n\n    return ans;\n}\n\nint main() {\n    int m;\n    scanf(\"%d %d\", &n, &m);\n    for (int i = 0; i < m; i++) {\n        int u, v;\n        char c;\n        scanf(\"%d %d %c\", &u, &v, &c);\n        u--;\n        v--;\n\n        G[u].emplace_back(v, c);\n        G[v].emplace_back(u, c);\n    }\n\n    auto f = solve('R');\n    auto g = solve('B');\n\n    if (g.size() < f.size()) f = g;\n\n    if (f.size() > n) {\n        printf(\"-1\\\\n\");\n\n        return 0;\n    }\n\n    printf(\"%d\\\\n\", (int)f.size());\n    for (int x : f) printf(\"%d \", x + 1);\n    printf(\"\\\\n\");\n\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "662",
    "index": "C",
    "title": "Binary Table",
    "statement": "You are given a table consisting of $n$ rows and $m$ columns. Each cell of the table contains either $0$ or $1$. In one move, you are allowed to pick any row or any column and invert all values, that is, replace $0$ by $1$ and vice versa.\n\nWhat is the minimum number of cells with value 1 you can get after applying some number of operations?",
    "tutorial": "First let's examine a slow solution that works in $O(2^{n}  \\cdot  m)$. Since each row can be either inverted or not, the set of options of how we can invert the rows may be encoded in a bitmask of length $n$, an integer from $0$ to $(2^{n} - 1)$, where the $i$-th bit is equal to 1 if and only if we invert the $i$-th row. Each column also represents a bitmask of length $n$ (the bits correspond to the values of that row in each of the $n$ rows). Let the bitmask of the $i$-th column be $col_{i}$, and the bitmask of the inverted rows be $mask$. After inverting the rows the $i$-th column will become $(c o l_{i}\\oplus m a s k)$. Suppose that $(c o l_{i}\\oplus m a s k)$ contains $k=p o p_{-}c o u n t(c o l_{i}\\oplus m a s k)$ ones. Then we can obtain either $k$ or $(n - k)$ ones in this column, depending on whether we invert the $i$-th column itself. It follows that for a fixed bitmask $mask$ the minimum possible number of ones that can be obtained is equal to $\\sum_{i=1}^{m}\\operatorname*{min}(p o p_{-}c o u n t(c o l_{i}\\oplus m a s k),n-p o p_{-}c o u n t(c o l_{i}\\oplus m a s k))$. Now we want to calculate this sum faster than $O(m)$. Note that we are not interested in the value of the mask $(c o l_{i}\\oplus m a s k)$ itself, but only in the number of ones it contains (from $0$ to $n$). Therefore we may group the columns by the value of $p o p_{-}c o u n t(c o l_{i}\\oplus m a s k)$. Let $dp[k][mask]$ be the number of such $i$ that $p o p_{-}c o u n t(c o l_{i}\\oplus m a s k)=k$, then for a fixed bitmask $mask$ we can calculate the sum in $O(n)$ - $\\sum_{k=0}^{n}\\operatorname*{min}(k,n-k)\\cdot d p[k][m a s k]$. What remains is to calculate the value of $dp[k][mask]$ in a quick way. As the name suggests, we can use dynamic programming for this purpose. The value of $dp[0][mask]$ can be found in $O(m)$ for all bitmasks $mask$: each column $col_{i}$ increases $dp[0][col_{i}]$ by 1. For $k > 0$, $col_{i}$ and $mask$ differ in exactly $k$ bits. Suppose $mask$ and $col_{i}$ differ in position $p$. Then $col_{i}$ and $(m a s k\\oplus p)$ differ in exactly $(k - 1)$ bits. The number of such columns is equal to $d p[k-1][m a s k\\oplus p]$, except we counted in also the number of columns $col_{i}$ that differ with $(m a s k\\oplus p)$ in bit $p$ (thus, $mask$ and $col_{i}$ have the same value in bit $p$). Thus we need to subtract $dp[k - 2][mask]$, but again, except the columns among these that differ with $mask$ in bit $p$. Let $n e x t=(m a s k\\oplus p)$; by expanding this inclusion-exclusion type argument, we get that the number of masks we are interested in can be expressed as $dp[k - 1][next] - dp[k - 2][mask] + dp[k - 3][next] - dp[k - 4][mask] + dp[k - 5][next] - ...$. By summing all these expressions for each bit $p$ from $0$ to $n$, we get $dp[k][mask]  \\cdot  k$, since each column is counted in $k$ times (for each of the bits $p$ where the column differs from $mask$). Therefore, we are now able to count the values of $dp[k][mask]$ in time $O(2^{n}  \\cdot  n^{3})$ using the following recurrence: $d p[k][m a s k]={\\frac{1}{k}}\\sum_{p=0}^{n-1}\\sum_{f=1}^{k}(-1)^{f-1}\\cdot\\,d p[k-f][m a s k\\oplus(2^{p}\\cdot\\,(f\\mod2))]$ This is still a tad slow, but we can speed it up to $O(2^{n}  \\cdot  n^{2})$, for example, in a following fashion: $\\sum_{p=0}^{n-1}\\sum_{f=3}^{k}(-1)^{f-1}\\,\\cdot\\,\\,d p[k-f][m a s k\\,\\oplus\\,(2^{p}\\,\\cdot\\,(f\\mathrm{\\boldmath~\\mod~2)})$ $=(k-2)\\cdot d p[k-2][m a s k]$ $d p[k][m a s k]=\\frac{1}{k}((k-2-n)\\cdot d p[k-2][m a s k]+\\sum_{p=0}^{n-1}d p[k-1][m a s k\\oplus2^{p}])$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nchar s[100000];\nint col[100000], dp[21][1 << 20];\n\nint main() {\n    int n, m;\n    scanf(\"%d %d\", &n, &m);\n    for (int i = 0; i < n; i++) {\n        scanf(\" %s\", s);\n\n        for (int j = 0; j < m; j++) col[j] |= (s[j] - '0') << i;\n    }\n\n    for (int i = 0; i < m; i++) dp[0][col[i]]++;\n\n    for (int k = 1; k <= n; k++)\n        for (int mask = 0; mask < (1 << n); mask++) {\n            int sum = k > 1 ? (k - 2 - n) * dp[k - 2][mask] : 0;\n            for (int p = 0; p < n; p++) sum += dp[k - 1][mask ^ (1 << p)];\n\n            dp[k][mask] = sum / k;\n        }\n\n    int ans = n * m;\n    for (int mask = 0; mask < (1 << n); mask++) {\n        int cnt = 0;\n        for (int k = 0; k <= n; k++) cnt += min(k, n - k) * dp[k][mask];\n\n        ans = min(ans, cnt);\n    }\n\n    printf(\"%d\\\\n\", ans);\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "divide and conquer",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "662",
    "index": "D",
    "title": "International Olympiad",
    "statement": "International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where $y$ stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string $y$ that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.\n\nFor example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.\n\nYou are given a list of abbreviations. For each of them determine the year it stands for.",
    "tutorial": "Consider the abbreviations that are given to the first Olympiads. The first $10$ Olympiads (from year $1989$ to year $1998$) receive one-digit abbreviations ($IAO'9, IAO'0, ..., IAO'8$). The next $100$ Olympiads ($1999 - 2098$) obtain two-digit abbreviations, because all one-digit abbreviations are already taken, but the last two digits of $100$ consecutive integers are pairwise different. Similarly, the next $1000$ Olympiads get three-digit abbreviations and so on. Now examine the inversed problem (extract the year from an abbreviation). Let the abbreviation have $k$ digits, then we know that all Olympiads with abbreviations of lengths $(k - 1), (k - 2), ..., 1$ have passed before this one. The number of such Olympiads is $10^{k - 1} + 10^{k - 2} + ... + 10^{1} = F$ and the current Olympiad was one of the $10^{k}$ of the following. Therefore this Olympiad was held in years between $(1989 + F)$ and $(1989 + F + 10^{k} - 1)$. As this segment consists of exactly $10^{k}$ consecutive natural numbers, it contains a single number with a $k$-digit suffix that matches the current abbreviation. It is also the corresponding year.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nchar s[42];\n\nint main() {\n    int n;\n    scanf(\"%d\", &n);\n    while (n--) {\n        scanf(\" %s\", s);\n        \n        int k = strlen(s + 4), year = atoi(s + 4), F = 0, tenPow = 10;\n        for (int i = 1; i < k; i++) {\n            F += tenPow;\n            tenPow *= 10;\n        }\n        \n        while (year < 1989 + F) year += tenPow;\n        \n        printf(\"%d\\\\n\", year);\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "662",
    "index": "E",
    "title": "To Hack or not to Hack",
    "statement": "Consider a regular Codeforces round consisting of three problems that uses dynamic scoring.\n\nYou are given an almost final scoreboard. For each participant (including yourself), the time of the accepted submission for each of the problems is given. Also, for each solution you already know whether you are able to hack it or not. The only changes in the scoreboard that will happen before the end of the round are your challenges.\n\nWhat is the best place you may take at the end?\n\nMore formally, $n$ people are participating (including yourself). For any problem, if it was solved by exactly $k$ people at the end of the round, the maximum score for this problem is defined as:\n\n- If $n < 2k ≤ 2n$, then the maximum possible score is $500$;\n- If $n < 4k ≤ 2n$, then the maximum possible score is $1000$;\n- If $n < 8k ≤ 2n$, then the maximum possible score is $1500$;\n- If $n < 16k ≤ 2n$, then the maximum possible score is $2000$;\n- If $n < 32k ≤ 2n$, then the maximum possible score is $2500$;\n- If $32k ≤ n$, then the maximum possible score is $3000$.\n\nLet the maximum possible score for some problem be equal to $s$. Then a contestant who didn't manage to get it accepted (or his solution was hacked) earns $0$ points for this problem. If he got the the solution accepted $t$ minutes after the beginning of the round (and his solution wasn't hacked), he earns $\\frac{s\\cdot(250-t)}{250}$ points for this problem.\n\nThe overall score of a participant is equal to the sum of points he earns for each problem plus $100$ points for each successful hack (only you make hacks).\n\nThe resulting place you get is equal to one plus the number of participants who's overall score is strictly greater than yours.",
    "tutorial": "Observation number one - as you are the only participant who is able to hack, the total score of any other participant cannot exceed $9000$ ($3$ problems for $3000$ points). Hence hacking at least $90$ solutions automatically guarantees the first place (the hacks alone increase the score by $9000$ points). Now we are left with the problem where the number of hacks we make is at most $90$. We can try each of the $6^{3}$ possible score assignments for the problems in the end of the round. As we know the final score for each problem, we can calculate the maximum number of hacks we are allowed to make so the problem gets the assigned score. This is also the exact amount of hacks we will make in that problem. As we know the number of hacks we will make, we can calculate our final total score. Now there are at most $90$ participants who we can possibly hack. We are interested only in those who are on top of us. By hacking we want to make their final score less than that of us. This problem can by solved by means of dynamic programming: $dp[p][i][j][k]$ - the maximum number of participants among the top $p$, whom we can push below us by hacking first problem $i$ times, second problem $j$ times and third problem $k$ times. The recurrence: we pick a subset of solutions of the current participant that we will hack, and if after these hacks we will push him below us, we update the corresponding dp state. For example, if it is enough to hack the first and the third problems, then $dp[p + 1][i + 1][j][k + 1] = max(dp[p + 1][i + 1][j][k + 1], dp[p][i][j][k] + 1)$",
    "code": "#include<bits/stdc++.h>\n\n#define time ololo\n\nusing namespace std;\n\nint time[5000][3], n, solved[3], canHack[3], score[3], willHack[3], bestPlace, dp[2][90][90][90], ci, li;\n\nint submissionScore(int sc, int tm) {\n    if (tm == 0) return 0;\n\n    return sc * (250 - abs(tm)) / 250;\n}\n\nint calcScore(int p) {\n    int sum = 0;\n    for (int i = 0; i < 3; i++) sum += submissionScore(score[i], time[p][i]);\n\n    return sum;\n}\n\nint countHacks(int p) {\n    int cnt = 0;\n    for (int i = 0; i < 3; i++) cnt += time[p][i] < 0;\n\n    return cnt;\n}\n\nint solve() {\n    memset(dp, 0, sizeof dp);\n\n    int myScore = 0;\n    for (int i = 0; i < 3; i++) myScore += 100 * willHack[i] + submissionScore(score[i], time[0][i]);\n\n    ci = 0;\n    li = 1;\n    for (int p = 1; p < n; p++)\n        if (countHacks(p) > 0 && calcScore(p) > myScore) {\n            ci ^= 1;\n            li ^= 1;\n\n            for (int i = 0; i <= willHack[0]; i++)\n                for (int j = 0; j <= willHack[1]; j++)\n                    for (int k = 0; k <= willHack[2]; k++)\n                        dp[ci][i][j][k] = dp[li][i][j][k];\n\n            for (int ii = 0; ii < 2; ii++)\n                for (int jj = 0; jj < 2; jj++)\n                    for (int kk = 0; kk < 2; kk++) {\n                        if (ii == 1 && time[p][0] >= 0) continue;\n                        if (jj == 1 && time[p][1] >= 0) continue;\n                        if (kk == 1 && time[p][2] >= 0) continue;\n\n                        int s = submissionScore(score[0], time[p][0]) * (ii ^ 1)\n                              + submissionScore(score[1], time[p][1]) * (jj ^ 1)\n                              + submissionScore(score[2], time[p][2]) * (kk ^ 1);\n\n                        if (s > myScore) continue;\n\n                        for (int i = ii; i <= willHack[0]; i++)\n                            for (int j = jj; j <= willHack[1]; j++)\n                                for (int k = kk; k <= willHack[2]; k++)\n                                    dp[ci][i][j][k] = max(dp[ci][i][j][k], dp[li][i - ii][j - jj][k - kk] + 1);\n                    }\n        }\n\n    int res = 1 - dp[ci][willHack[0]][willHack[1]][willHack[2]];\n    for (int p = 1; p < n; p++) if (calcScore(p) > myScore) res++;\n\n    return res;\n}\n\nvoid brute(int p) {\n    if (p == 3) {\n        int res = solve();\n\n        bestPlace = min(bestPlace, res);\n\n        return;\n    }\n\n    for (int i = 0; i < 6; i++) {\n        int mn = i == 5 ? 0 : (n >> (i + 1)) + 1;\n        int mx = (n >> i);\n\n        if (solved[p] >= mn && solved[p] - canHack[p] <= mx) {\n            score[p] = 500 * (i + 1);\n            willHack[p] = min(canHack[p], solved[p] - mn);\n\n            brute(p + 1);\n        }\n    }\n}\n\nint main() {\n    memset(solved, 0, sizeof solved);\n    memset(canHack, 0, sizeof canHack);\n    \n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < 3; j++) {\n            scanf(\"%d\", &time[i][j]);\n\n            solved[j] += time[i][j] != 0;\n            canHack[j] += time[i][j] < 0;\n        }\n\n    if (canHack[0] + canHack[1] + canHack[2] > 89) {\n        printf(\"1\\\\n\");\n\n        return 0;\n    }\n\n    bestPlace = n;\n    brute(0);\n\n    printf(\"%d\\\\n\", bestPlace);\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "663",
    "index": "A",
    "title": "Rebus",
    "statement": "You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer $n$. The goal is to replace each question mark with some positive integer from $1$ to $n$, such that equality holds.",
    "tutorial": "First we check whether any solution exists at all. For that purpose, we calculate the number of positive (the first one and any other with the $+$ sign) and negative elements (with the $-$ sign) in the sum. Let them be $pos$ and $neg$, respectively. Then the minimum value of the sum that can be possibly obtained is equal to $min = (1  \\cdot  pos - n  \\cdot  neg)$, as each positive number can be $1$, but all negative can be $- n$. Similarly, the maximum possible value is equal to $max = (n  \\cdot  pos - 1  \\cdot  neg)$. The solution therefore exists if and only if $min  \\le  n  \\le  max$. Now suppose a solution exists. Let's insert the numbers into the sum one by one from left to right. Suppose that we have determined the numbers for some prefix of the expression with the sum of $S$. Let the sign of the current unknown be $sgn$ ($+ 1$ or $- 1$) and there are some unknown numbers left to the right, excluding the examined unknown, among them $pos_left$ positive and $neg_left$ negative elements. Suppose that the current unknown number takes value $x$. How do we find out whether this leads to a solution? The answer is: in the same way we checked it in the beginning of the solution. Examine the smallest and the largest values of the total sum that we can get. These are equal to $min_left = (S + sgn  \\cdot  x + pos_left - n  \\cdot  neg_left)$ and $max_left = (S + sgn  \\cdot  x + n  \\cdot  pos_left - neg_left)$, respectively. Then we may set the current number to $x$, if $min_left  \\le  n  \\le  max_left$ holds. To find the value of $x$, we can solve a system of inequalities, but it is easier simply to check all possible values from $1$ to $n$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nchar s[100];\n\nint main() {\n    int k = 0, n, pos = 1, neg = 0;\n    while (true) {\n        char c;\n        scanf(\" %c\", &c);\n        scanf(\" %c\", &c);\n\n        if (c == '=') break;\n        if (c == '+') pos++;\n        if (c == '-') neg++;\n\n        s[k++] = c;\n    }\n\n    scanf(\"%d\", &n);\n\n    if (pos - n * neg > n || n * pos - neg < n) {\n        printf(\"Impossible\\\\n\");\n\n        return 0;\n    }\n\n    printf(\"Possible\\\\n\");\n\n    int S = 0;\n    for (int i = 0; i < k; i++) {\n        int sgn = 1;\n        if (i > 0 && s[i - 1] == '-') sgn = -1;\n\n        if (sgn == 1) pos--;\n        if (sgn == -1) neg--;\n\n        for (int x = 1; x <= n; x++)\n            if (S + x * sgn + pos - n * neg <= n && S + x * sgn + n * pos - neg >= n) {\n                printf(\"%d %c \", x, s[i]);\n\n                S += x * sgn;\n\n                break;\n            }\n\t}\n\n    printf(\"%d = %d\\\\n\", abs(n - m), n);\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "expression parsing",
      "greedy",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "664",
    "index": "A",
    "title": "Complicated GCD",
    "statement": "Greatest common divisor $GCD(a, b)$ of two positive integers $a$ and $b$ is equal to the biggest integer $d$ such that both integers $a$ and $b$ are divisible by $d$. There are many efficient algorithms to find greatest common divisor $GCD(a, b)$, for example, Euclid algorithm.\n\nFormally, find the biggest integer $d$, such that all integers $a, a + 1, a + 2, ..., b$ are divisible by $d$. To make the problem even more complicated we allow $a$ and $b$ to be up to googol, $10^{100}$ — such number do not fit even in 64-bit integer type!",
    "tutorial": "We examine two cases: $a = b$ - the segment consists of a single number, hence the answer is $a$. $a < b$ - we have $gcd(a, a + 1, a + 2, ..., b) = gcd(gcd(a, a + 1), a + 2, ..., b) = gcd(1, a + 2, ..., b) = 1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    string a, b;\n    cin >> a >> b;\n\n    if (a == b) cout << a;\n    else cout << 1;\n\n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "665",
    "index": "A",
    "title": "Buses Between Cities",
    "statement": "Buses run between the cities $A$ and $B$, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city $A$ departs every $a$ minutes and arrives to the city $B$ in a $t_{a}$ minutes, and a bus from the city $B$ departs every $b$ minutes and arrives to the city $A$ in a $t_{b}$ minutes.\n\nThe driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish.\n\nYou know the time when Simion departed from the city $A$ to the city $B$. Calculate the number of buses Simion will meet to be sure in his counting.",
    "tutorial": "Consider the time interval when Simion will be on the road strictly between cities $(x_{1}, y_{1})$ ($x_{1} = 60h + m, y_{1} = x_{1} + t_{a}$). Let's iterate over the oncoming buses. Let $(x_{2}, y_{2})$ be the time interval when the oncoming bus will be strictly between two cities. If the intersection of that intervals $(x = max(x_{1}, x_{2}), y = min(y_{1}, y_{2}))$ is not empty than Simion will count that bus. Complexity: $O(1)$.",
    "code": "int a, ta;\nint b, tb;\nint h, m;\n\nbool read() {\n\tif (!(cin >> a >> ta)) return false;\n\tassert(cin >> b >> tb);\n\tassert(scanf(\"%d:%d\", &h, &m) == 2);\n\treturn true;\n}\n\nvoid solve() {\n\tint x1 = h * 60 + m;\n\tint y1 = x1 + ta;\n\n\tint ans = 0;\n\tfor (int x2 = 5 * 60 + 0; x2 < 24 * 60; x2 += b) {\n\t\tint y2 = x2 + tb;\n\t\tint x = max(x1, x2), y = min(y1, y2);\n\t\tif (x < y)\n\t\t\tans++;\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "665",
    "index": "B",
    "title": "Shopping",
    "statement": "Ayush is a cashier at the shopping center. Recently his department has started a ''click and collect\" service which allows users to shop online.\n\nThe store contains $k$ items. $n$ customers have already used the above service. Each user paid for $m$ items. Let $a_{ij}$ denote the $j$-th item in the $i$-th person's order.\n\nDue to the space limitations all the items are arranged in one single row. When Ayush receives the $i$-th order he will find one by one all the items $a_{ij}$ ($1 ≤ j ≤ m$) in the row. Let $pos(x)$ denote the position of the item $x$ in the row at the moment of its collection. Then Ayush takes time equal to $pos(a_{i1}) + pos(a_{i2}) + ... + pos(a_{im})$ for the $i$-th customer.\n\nWhen Ayush accesses the $x$-th element he keeps a new stock in the front of the row and takes away the $x$-th element. Thus the values are updating.\n\nYour task is to calculate the total time it takes for Ayush to process all the orders.\n\nYou can assume that the market has endless stock.",
    "tutorial": "In this problem you should simply do what was written in the problem statement. There are no tricks. Complexity: $O(nmk)$.",
    "code": "const int N = 111;\n\nint n, m, k;\nint p[N];\nint a[N][N];\n\nbool read() {\n\tif (!(cin >> n >> m >> k)) return false;\n\tforn(i, k) {\n\t\tassert(scanf(\"%d\", &p[i]) == 1);\n\t\tp[i]--;\n\t}\n\tforn(i, n)\n\t\tforn(j, m) {\n\t\t\tassert(scanf(\"%d\", &a[i][j]) == 1);\n\t\t\ta[i][j]--;\n\t\t}\n\treturn true;\n}\n\nvoid solve() {\n\tint ans = 0;\n\tforn(i, n)\n\t\tforn(j, m) {\n\t\t\tint pos = int(find(p, p + k, a[i][j]) - p);\n\t\t\tans += pos + 1;\n\t\t\tnfor(l, pos) p[l + 1] = p[l];\n\t\t\tp[0] = a[i][j];\n\t\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1400
  },
  {
    "contest_id": "665",
    "index": "C",
    "title": "Simple Strings",
    "statement": "zscoder loves simple strings! A string $t$ is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.\n\nzscoder is given a string $s$. He wants to change a minimum number of characters so that the string $s$ becomes simple. Help him with this task!",
    "tutorial": "There are two ways to solve this problem: greedy approach and dynamic programming. The first apprroach: Considerr some segment of consecutive equal characters. Let $k$ be the length of that segment. Easy to see that we should change at least $\\textstyle{\\left|{\\frac{k}{2}}\\right|}$ characters in the segment to remove all the pairs of equal consecutive letters. On the other hand we can simply change the second, the fourth etc. symbols to letter that is not equal to the letters before and after the segment. The second approach: Let $z_{ka}$ be the minimal number of changes so that the prefix of length $k$ has no equal consecutive letters and the symbol $s'_{k}$ equals to $a$. Let's iterate over the letter on the position $k + 1$ and if it is not equal to $a$ make transition. The cost of the transition is equal to $0$ if we put the same letter as in the original string $s$ on the position $k + 1$. Otherwise the cost is equal to $1$. Complexity: $O(n)$.",
    "code": "const int N = 1200300, A = 27;\n\nint n;\nchar s[N];\n\nbool read() {\n\tif (!gets(s)) return false;\n\tn = int(strlen(s));\n\treturn true;\n}\n\nint z[N][A];\nint p[N][A];\nchar ans[N];\n\nvoid solve() {\n\tmemset(z, 63, sizeof(z));\n\n\tz[0][A - 1] = 0;\n\tforn(i, n) {\n\t\tint c = int(s[i] - 'a');\n\t\tforn(j, A) {\n\t\t\tint dv = z[i][j];\n\t\t\tif (dv > INF / 2) continue;\n\t\t\tforn(nj, A - 1) {\n\t\t\t\tif (nj == j) continue;\n\t\t\t\tint ct = nj != c;\n\t\t\t\tif (z[i + 1][nj] > dv + ct) {\n\t\t\t\t\tz[i + 1][nj] = dv + ct;\n\t\t\t\t\tp[i + 1][nj] = j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint idx = int(min_element(z[n], z[n] + A) - z[n]);\n\n\tfor (int i = n, j = idx; i > 0; j = p[i][j], i--)\n\t\tans[i - 1] = char('a' + j);\n\tans[n] = 0;\n\n\tcerr << z[n][idx] << endl;\n\tputs(ans);\n}",
    "tags": [
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "665",
    "index": "D",
    "title": "Simple Subset",
    "statement": "A tuple of positive integers ${x_{1}, x_{2}, ..., x_{k}}$ is called simple if for all pairs of positive integers $(i, j)$ ($1 ≤ i < j ≤ k$), $x_{i} + x_{j}$ is a prime.\n\nYou are given an array $a$ with $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$ (not necessary distinct). You want to find a simple subset of the array $a$ with the maximum size.\n\nA prime number (or a prime) is a natural number greater than $1$ that has no positive divisors other than $1$ and itself.\n\nLet's define a subset of the array $a$ as a tuple that can be obtained from $a$ by removing some (possibly all) elements of it.",
    "tutorial": "Consider the subset $A$ that is the answer to the problem. Let $a, b, c$ be the arbitrary three elements from $A$ and let no more than one of them is equal to $1$. By the pigeonhole principle two of three elements from $a, b, c$ have the same parity. So we have two integers with even sum and only one of them is equal to $1$, so their sum is also greater than $2$. So the subset $A$ is not simple. In this way $A$ consists of only two numbers greater than one (with a prime sum) or consists of some number of ones and also maybe other value $x$, so that $x + 1$ is a prime. We can simply process the first case in $O(n^{2})$ time. The second case can be processed in linear time. Also we should choose the best answer from that two. To check the value of order $2 \\cdot 10^{6}$ for primality in $O(1)$ time we can use the simple or the linear Eratosthenes sieve. Complexity: $O(n^{2} + X)$, where $X$ is the maximal value in $a$.",
    "code": "const int N = 1010, X = 2100300;\n\nint n, a[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nint szp, p[X];\nint mind[X];\n\nvoid prepare() {\n\tfore(i, 2, X) {\n\t\tif (!mind[i]) {\n\t\t\tp[szp++] = i;\n\t\t\tmind[i] = i;\n\t\t}\n\t\tfor (int j = 0; j < szp && p[j] <= mind[i] && i * p[j] < X; j++)\n\t\t\tmind[i * p[j]] = p[j];\n\t}\n}\n\nvoid printAns(int cnt1, int a = -1, int b = -1) {\n\tvector<int> ans;\n\tforn(i, cnt1) ans.pb(1);\n\tif (a != -1) ans.pb(a);\n\tif (b != -1) ans.pb(b);\n\tassert(!ans.empty());\n\trandom_shuffle(all(ans));\n\n\tcout << sz(ans) << endl;\n\tforn(i, sz(ans)) {\n\t\tif (i) putchar(' ');\n\t\tprintf(\"%d\", ans[i]);\n\t}\n\tputs(\"\");\n}\n\nvoid solve() {\n\tint cnt1 = (int) count(a, a + n, 1);\n\n\tfunction<bool(int)> isPrime = [](int p) { return mind[p] == p; };\n\n\tif (cnt1 > 0)\n\t\tforn(i, n)\n\t\t\tif (a[i] != 1 && isPrime(a[i] + 1)) {\n\t\t\t\tprintAns(cnt1, a[i]);\n\t\t\t\treturn;\n\t\t\t}\n\n\tif (cnt1 > 1) {\n\t\tprintAns(cnt1);\n\t\treturn;\n\t}\n\n\tforn(i, n)\n\t\tforn(j, i)\n\t\t\tif (isPrime(a[i] + a[j])) {\n\t\t\t\tprintAns(0, a[i], a[j]);\n\t\t\t\treturn;\n\t\t\t}\n\n\tprintAns(0, a[0]);\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "665",
    "index": "E",
    "title": "Beautiful Subarrays",
    "statement": "One day, ZS the Coder wrote down an array of integers $a$ with elements $a_{1}, a_{2}, ..., a_{n}$.\n\nA subarray of the array $a$ is a sequence $a_{l}, a_{l + 1}, ..., a_{r}$ for some integers $(l, r)$ such that $1 ≤ l ≤ r ≤ n$. ZS the Coder thinks that a subarray of $a$ is beautiful if the bitwise xor of all the elements in the subarray is at least $k$.\n\nHelp ZS the Coder find the number of beautiful subarrays of $a$!",
    "tutorial": "The sign $\\otimes$ is used for the binary operation for bitwise exclusive or. Let $s_{i}$ be the xor of the first $i$ elements on the prefix of $a$. Then the interval $(i, j]$ is beautiful if $s_{j}\\otimes s_{i}\\geq k$. Let's iterate over $j$ from $1$ to $n$ and consider the values $s_{j}$ as the binary strings. On each iteration we should increase the answer by the value $z_{j}$ - the number of numbers $s_{i}$ ($i < j$) so $s_{j}\\otimes s_{i}\\geq k$. To do that we can use the trie data structure. Let's store in the trie all the values $s_{i}$ for $i < j$. Besides the structure of the trie we should also store in each vertex the number of leaves in the subtree of that vertex (it can be easily done during adding of each binary string). To calculate the value $z_{j}$ let's go down by the trie from the root. Let's accumulate the value $cur$ equals to the xor of the prefix of the value $s_{j}$ with the already passed in the trie path. Let the current bit in $s_{j}$ be equal to $b$ and $i$ be the depth of the current vertex in the trie. If the number $cur + 2^{i}  \\ge  k$ then we can increase $z_{j}$ by the number of leaves in vertex $n t_{v,b\\otimes1}$, because all the leaves in the subtree of tha vertex correspond to the values $s_{i}$ that for sure gives $s_{j}\\otimes s_{i}\\geq k$. After that we should go down in the subtree $b$. Otherwise if $cur + 2^{i} < k$ then we should simply go down to the subtree $b\\otimes1$ and recalculate the value $cur = cur + 2^{i}$. Comlpexity by the time and the memory: $O(nlogX)$, where $X$ is the maximal xor on the prefixes.",
    "code": "const int N = 1200300, LOGN = 30, V = N * LOGN;\n\nint n, k;\nint a[N];\n\nbool read() {\n\tif (!(cin >> n >> k)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nint tsz;\nint nt[V][2];\nint cnt[V];\n\nvoid clear() {\n\tforn(i, V) {\n\t\tnt[i][0] = nt[i][1] = -1;\n\t\tcnt[i] = 0;\n\t}\n\ttsz = 1;\n}\n\nvoid add(int x) {\n\tint v = 0;\n\tcnt[v]++;\n\n\tnfor(i, LOGN) {\n\t\tint b = (x >> i) & 1;\n\t\tif (nt[v][b] == -1) {\n\t\t\tassert(tsz < V);\n\t\t\tnt[v][b] = tsz++;\n\t\t}\n\t\tv = nt[v][b];\n\t\tcnt[v]++;\n\t}\n}\n\n\nint calc(int x) {\n\tint v = 0;\n\tint ans = 0;\n\n\tauto getCnt = [](int v) { return v == -1 ? 0 : cnt[v]; };\n\n\tint cur = 0;\n\tnfor(i, LOGN) {\n\t\tif (v == -1) break;\n\t\tint b = (x >> i) & 1;\n\t\tif ((cur | (1 << i)) >= k) {\n\t\t\tans += getCnt(nt[v][b ^ 1]);\n\t\t\tv = nt[v][b];\n\t\t} else {\n\t\t\tv = nt[v][b ^ 1];\n\t\t\tcur |= (1 << i);\n\t\t}\n\t}\n\tif (cur >= k) ans += getCnt(v);\n\treturn ans;\n}\n\nvoid solve() {\n\tclear();\n\n\tadd(0);\n\n\tli ans = 0;\n\tint s = 0;\n\tforn(i, n) {\n\t\ts ^= a[i];\n\t\tli cur = calc(s);\n\t\tans += cur;\n\t\tadd(s);\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "strings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "665",
    "index": "F",
    "title": "Four Divisors",
    "statement": "If an integer $a$ is divisible by another integer $b$, then $b$ is called the divisor of $a$.\n\nFor example: $12$ has positive $6$ divisors. They are $1$, $2$, $3$, $4$, $6$ and $12$.\n\nLet’s define a function $D(n)$ — number of integers between $1$ and $n$ (inclusive) which has exactly four positive divisors.\n\nBetween $1$ and $10$ only the integers $6$, $8$ and $10$ has exactly four positive divisors. So, $D(10) = 3$.\n\nYou are given an integer $n$. You have to calculate $D(n)$.",
    "tutorial": "Easy to see that only the numbers of the form $p \\cdot q$ and $p^{3}$ (for different prime $p, q$) have exactly four positive divisors. We can easily count the numbers of the form $p^{3}$ in $O(\\lambda^{\\underline{{{\\mu}}}n})$, where $n$ is the number from the problem statement. Now let $p < q$ and $ \\pi (k)$ be the number of primes from $1$ to $k$. Let's iterate over all the values $p$. Easy to see that $p\\leq{\\sqrt{n}}$. So for fixed $p$ we should increase the answer by the value $\\pi(\\lfloor{\\frac{n}{p}}\\rfloor)$. So the task is ot to find $\\pi(\\lfloor{\\frac{n}{p}}\\rfloor)$ - the number of primes not exceeding $\\overset{n}{p}$, for all $p$. Denote $p_{j}$ the $j$-th prime number. Denote $dp_{n, j}$ the number of $k$ such that $1  \\le  k  \\le  n$, and all prime divisors of $k$ are at least $p_{j}$ (note that 1 is counted in all $dp_{n, j}$, since the set of its prime divisors is empty). $dp_{n, j}$ satisfy a simple recurrence: $dp_{n, 1} = n$ (since $p_{1}$ = 2) $dp_{n, j} = dp_{n, j + 1} + dp_{ \\lfloor  n / pj \\rfloor , j}$, hence $dp_{n, j + 1} = dp_{n, j} - dp_{ \\lfloor  n / pj \\rfloor , j}$ Let $p_{k}$ be the smallest prime greater than $\\sqrt{n}$. Then $ \\pi (n) = dp_{n, k} + k - 1$ (by definition, the first summand accounts for all the primes not less than $k$). If we evaluate the recurrence $dp_{n, k}$ straightforwardly, all the reachable states will be of the form $dp_{ \\lfloor  n / i \\rfloor , j}$. We can also note that if $p_{j}$ and $p_{k}$ are both greater than $\\sqrt{n}$, then $dp_{n, j} + j = dp_{n, k} + k$. Thus, for each $ \\lfloor  n / i \\rfloor $ it makes sense to keep only $\\sim\\pi({\\sqrt{n/i}})$ values of $dp_{ \\lfloor  n / i \\rfloor , j}$. Instead of evaluating all DP states straightforwardly, we perform a two-step process: Choose $K$. Run recursive evaluation of $dp_{n, k}$. If we want to compute a state with $n < K$, memorize the query ``count the numbers not exceeding $n$ with all prime divisors at least $k$''. Answer all the queries off-line: compute the sieve for numbers up to $K$, then sort all numbers by the smallest prime divisor. Now all queries can be answered using RSQ structure. Store all the answers globally. Run recurisive evaluation of $dp_{n, k}$ yet again. If we want to compute a state with $n < K$, then we must have preprocessed a query for this state, so take it from the global set of answers. The performance of this approach relies heavily on $Q$ - the number of queries we have to preprocess. Statement. $Q=O(\\frac{n}{\\sqrt{K_{\\mathrm{\\los}n}}})$. Proof: Each state we have to preprocess is obtained by following a $dp_{ \\lfloor  n / pj \\rfloor , j}$ transition from some greater state. It follows that $Q$ doesn't exceed the total number of states for $n > K$. $Q\\leq\\sum_{j=1}^{n/K}\\pi(\\sqrt{n/j})\\sim\\Sigma_{j=1}^{n/K}\\;\\sqrt{n/j}/\\log n\\sim\\textstyle{\\frac{1}{\\log n}}\\int_{1}^{n/K}\\;\\sqrt{n/x}d x\\sim\\frac{n}{\\sqrt{K\\log n}}$ The preprocessing of $Q$ queries can be done in $O((K+Q)\\log(K+Q))$, and it is the heaviest part of the computation. Choosing optimal $K\\sim\\left({\\frac{n}{\\log n}}\\right)^{2/3}$, we obtain the complexity $O(n^{2/3}(\\log n)^{1/3})$. Complexity: $O(n^{2/3}(\\log n)^{1/3})$.",
    "code": "li n;\n\nbool read() {\n\treturn !!(cin >> n);\n}\n\nconst int K = 10 * 1000 * 1000;\nconst int N = K;\nconst int P = 700100;\nconst int Q = 25 * 1000 * 1000;\n\nint szp, p[P];\nint mind[N];\n\nvoid prepare() {\n\tszp = 0;\n\tforn(i, N) mind[i] = -1;\n\tfore(i, 2, N) {\n\t\tif (mind[i] == -1) {\n\t\t\tassert(szp < P);\n\t\t\tmind[i] = szp;\n\t\t\tp[szp++] = i;\n\t\t}\n\t\tfor (int j = 0; j < szp && j <= mind[i] && i * p[j] < N; j++)\n\t\t\tmind[i * p[j]] = j;\n\t}\n}\n\ninline int getk(li n) {\n\tint lf = 0, rg = szp - 1;\n\twhile (lf != rg) {\n\t\tint md = (lf + rg) >> 1;\n\t\tif (p[md] * 1ll * p[md] > n) rg = md;\n\t\telse lf = md + 1;\n\t}\n\tassert(p[lf] * 1ll * p[lf] > n);\n\treturn lf;\n}\n\nint t[K];\nvoid inc(int i, int val) {\n\tfor ( ; i < K; i |= i + 1)\n\t\tt[i] += val;\n}\nint sum(int i) {\n\tint ans = 0;\n\tfor ( ; i >= 0; i = (i & (i + 1)) - 1)\n\t\tans += t[i];\n\treturn ans;\n}\n\nint szq;\npti q[Q];\nint ans[Q];\nvector<int> vs[P];\n\nvoid process() {\n\tsort(q, q + szq, greater<pti> ());\n\tmemset(t, 0, sizeof(t));\n\n\tforn(i, szp) vs[i].clear();\n\tfore(i, 2, K)\n\t\tvs[mind[i]].pb(i);\n\n\tinc(1, +1);\n\n\tint p = szp - 1;\n\tfor (int i = 0, j = 0; i < szq; i = j) {\n\t\twhile (p >= q[i].x) {\n\t\t\tfor (auto v : vs[p])\n\t\t\t\tinc(v, +1);\n\t\t\tp--;\n\t\t}\n\n\t\twhile (j < szq && q[j].x == q[i].x) {\n\t\t\tans[j] = sum(q[j].y);\n\t\t\tj++;\n\t\t}\n\t}\n}\n\nmap<pair<li, int>, li> z;\n\nli solve(li n, int jj, bool fs) {\n\tif (!n) return 0;\n\tint j = min(jj, getk(n));\n\tif (!j) return n + j - jj;\n\n\tli ans = 0;\n\tif (n < K) {\n\t\tpti p(j, (int) n);\n\t\tif (fs) {\n\t\t\tassert(szq < Q);\n\t\t\tq[szq++] = p;\n\t\t\tans = 0;\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tint idx = int(lower_bound(q, q + szq, p, greater<pti> ()) - q);\n\t\t\tassert(idx < szq && q[idx] == p);\n\t\t\tans = ::ans[idx];\n\t\t}\n\t} else {\n\t\tif (!z.count(mp(n, j))) {\n\t\t\tans = solve(n, j - 1, fs);\n\t\t\tans -= solve(n / p[j - 1], j - 1, fs);\n\t\t\tz[mp(n, j)] = ans;\n\t\t} else {\n\t\t\tans = z[mp(n, j)];\n\t\t}\n\t}\n\n\tans += j - jj;\n\n\treturn ans;\n}\n\ninline li pi(li n, bool fs) {\n\tint k = szp - 1;\n\treturn solve(n, k, fs) + k - 1;\n}\n\nvoid solve() {\n\tszq = 0;\n\tz.clear();\n\tfor (int j = 0; p[j] * 1ll * p[j] <= n; j++) {\n\t\tli nn = n / p[j];\n\t\tif (nn > p[j]) {\n\t\t\tpi(n / p[j], true);\n\t\t}\n\t}\n\n\tprocess();\n\n\tz.clear();\n\tli ans = 0;\n\tfor (int j = 0; p[j] * 1ll * p[j] <= n; j++) {\n\t\tli nn = n / p[j];\n\t\tif (nn > p[j]) {\n\t\t\tans += pi(n / p[j], false);\n\t\t\tans -= j + 1;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < szp && p[i] * 1ll * p[i] * 1ll * p[i] <= n; i++)\n\t\tans++;\n\n\tcout << ans << endl;\n}",
    "tags": [
      "data structures",
      "dp",
      "math",
      "number theory",
      "sortings",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "666",
    "index": "A",
    "title": "Reberland Linguistics",
    "statement": "First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.\n\nFor example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the \"root\" of the word — some string which has more than $4$ letters. Then several strings with the length $2$ or $3$ symbols are appended to this word. The only restriction — it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word \"suffix\" to describe a morpheme but not the few last characters of the string as you may used to).\n\nHere is one exercise that you have found in your task list. You are given the word $s$. Find all distinct strings with the length $2$ or $3$, which can be suffixes of this word according to the word constructing rules in Reberland language.\n\nTwo strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.\n\nLet's look at the example: the word $abacabaca$ is given. This word can be obtained in the following ways: $\\overline{{{d b|U(\\bar{u})d\\bar{u}/\\partial l l e}}}\\,\\overline{{{\\omega}}}_{\\cdot}\\,\\overline{{{\\omega}}}\\overline{{{\\omega}}}\\overline{{{\\omega}}}\\overline{{{u}}}\\overline{{{u}}}\\overline{{{u}}}\\prime{\\cal O}\\prime$, where the root of the word is overlined, and suffixes are marked by \"corners\". Thus, the set of possible suffixes for this word is ${aca, ba, ca}$.",
    "tutorial": "This problem is solved with dynamic programming. We can select an arbitrary root of any length (at least five). Let's reverse the string. A boolean value $dp_{2, 3}[n]$ denotes if we could split a prefix of length $n$ to a strings of length 2 and 3 so that the last string has a corresponding length. Transitions: $d p_{2}[n]=d p_{3}[n-2]\\vee\\left(d p_{2}[n-2]\\wedge s[n-3;n-2]\\neq s[n-1;n]\\right)$. Similarly, $d p_{3}[n]=d p_{2}[n-3]\\lor(d p_{3}[n-3]\\land s[n-5;n-3]\\neq s[n-2;n])$. If any of $dp_{k}[n]$ is true we add the corresponding string to the set of answers.",
    "tags": [
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "666",
    "index": "B",
    "title": "World Tour",
    "statement": "A famous sculptor Cicasso goes to a world tour!\n\nWell, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country — Berland.\n\nCicasso is very devoted to his work and he wants to be distracted as little as possible. Therefore he will visit only four cities. These cities will be different, so no one could think that he has \"favourites\". Of course, to save money, he will chose the shortest paths between these cities. But as you have probably guessed, Cicasso is a weird person. Although he doesn't like to organize exhibitions, he likes to travel around the country and enjoy its scenery. So he wants the total distance which he will travel to be as large as possible. However, the sculptor is bad in planning, so he asks you for help.\n\nThere are $n$ cities and $m$ one-way roads in Berland. You have to choose four different cities, which Cicasso will visit and also determine the order in which he will visit them. So that the total distance he will travel, if he visits cities in your order, starting from the first city in your list, and ending in the last, choosing each time the shortest route between a pair of cities — will be the largest.\n\nNote that intermediate routes may pass through the cities, which are assigned to the tour, as well as pass twice through the same city. For example, the tour can look like that: $\\overline{{{\\mathbf{I}}}}\\cdot\\ 2.\\ 3.\\ 4.\\ \\ \\l4.\\ \\ \\bar{\\mathbf{f}}.\\ 4.\\ \\ 3.\\ \\ \\overline{{{\\mathbf{2}}}}.\\ \\ \\ 3.\\ \\ \\overline{{{\\mathbf{4}}}}$. Four cities in the order of visiting marked as overlines: $[1, 5, 2, 4]$.\n\nNote that Berland is a high-tech country. So using nanotechnologies all roads were altered so that they have the same length. For the same reason moving using regular cars is not very popular in the country, and it can happen that there are such pairs of cities, one of which generally can not be reached by car from the other one. However, Cicasso is very conservative and cannot travel without the car. Choose cities so that the sculptor can make the tour using only the automobile. It is guaranteed that it is always possible to do.",
    "tutorial": "You are given the oriented graph, find four distinct vertices $a, b, c, d$ such that each vertex if reachable from previous and the sum of shortest paths between consequitive vertices is as large as possible. First let's run a BFS from each vertex and find three most distant vertices over given graph and its reverse. Afterwards loop through each possible $b$ and $c$. Having them fixed, loop through $a$ among three most distant vertices from $b$ in the reversed graph and through $d$ among three most distant vertices from $c$ in tie initial graph. This is sufficient, because if we've fixed $b$ and $c$ and $d$ is not one of three furthest from $c$ then we could replace it with one of them and improve the answer.",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "666",
    "index": "C",
    "title": "Codeword",
    "statement": "The famous sculptor Cicasso is a Reberlandian spy!\n\nThese is breaking news in Berlandian papers today. And now the sculptor is hiding. This time you give the shelter to the maestro. You have a protected bunker and you provide it to your friend. You set the security system in such way that only you can open the bunker. To open it one should solve the problem which is hard for others but is simple for you.\n\nEvery day the bunker generates a codeword $s$. Every time someone wants to enter the bunker, integer $n$ appears on the screen. As the answer one should enter another integer — the residue modulo $10^{9} + 7$ of the number of strings of length $n$ that consist only of lowercase English letters and contain the string $s$ as the \\textbf{subsequence}.\n\nThe subsequence of string $a$ is a string $b$ that can be derived from the string $a$ by removing some symbols from it (maybe none or all of them). In particular any string is the subsequence of itself. For example, the string \"cfo\" is the subsequence of the string \"codeforces\".\n\nYou haven't implemented the algorithm that calculates the correct answers yet and you should do that ASAP.",
    "tutorial": "The first thing to notice: string itself does not matter, only its length does. In each sequence of length $n$ containing a fixed subsequence $s$ we can select $s$'s lexicographically minimal occurance, let it be $p_{1}, ..., p_{|s|}$. No character $s_{k + 1}$ may occur between $p_{k}$ and $p_{k + 1} - 1$, because otherwise the occurence is not lex-min. On the other hand, if there is an occurence which satsfies this criterion than it is lex-min. Given this definition we can count number of strings containing given string as a subsequence. At first select positions of the lex-min occurance; there are $\\left(\\begin{array}{l}{n k}\\\\ {|_{k\\bar{\\nu}}}\\end{array}\\right)$ ways to do it. Next, you can use any of $ \\Sigma  - 1$ characters at first $s$ intervals between $p_{i}$, and any of $ \\Sigma $ at the end of the string. (Here, $ \\Sigma $ denotes alphabet size). Looping through $p_{}|s|$ - the position of last character in $s$ in the lex-min occurence, we can count that there are exactly $\\sum_{k=|s|}^{n}{\\binom{k-1}{|s|-1}}(q-1)^{k-|s|}q^{n-k}=q^{n}\\sum_{k=|s|}^{n}{\\binom{k-1}{|s|-1}}{\\frac{\\left(q-1\\right)^{k-|s|}}{q^{k}}}$ strings containing $s$ as a subsequence. So, having $|s|$ fixed, answer for each $n$ could be computed in linear time. A final detail: input strings can have at most $\\sqrt{2n}$ different lengths. Thus simply applying the overmentioned formula we get a $O(n{\\sqrt{n}})$ solution, which was the expected one.",
    "tags": [
      "combinatorics",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "666",
    "index": "C",
    "title": "Codeword",
    "statement": "The famous sculptor Cicasso is a Reberlandian spy!\n\nThese is breaking news in Berlandian papers today. And now the sculptor is hiding. This time you give the shelter to the maestro. You have a protected bunker and you provide it to your friend. You set the security system in such way that only you can open the bunker. To open it one should solve the problem which is hard for others but is simple for you.\n\nEvery day the bunker generates a codeword $s$. Every time someone wants to enter the bunker, integer $n$ appears on the screen. As the answer one should enter another integer — the residue modulo $10^{9} + 7$ of the number of strings of length $n$ that consist only of lowercase English letters and contain the string $s$ as the \\textbf{subsequence}.\n\nThe subsequence of string $a$ is a string $b$ that can be derived from the string $a$ by removing some symbols from it (maybe none or all of them). In particular any string is the subsequence of itself. For example, the string \"cfo\" is the subsequence of the string \"codeforces\".\n\nYou haven't implemented the algorithm that calculates the correct answers yet and you should do that ASAP.",
    "tutorial": "You are given four points on the plain. You should move each of them up, down, left, or right, such that the new configuration is a square with positive integer sides parallel to coordinate axes. Choose some $d$, length of the square side, and $(x, y)$, the position of the bottom-left point. A set from where to choose will be constructed later. Then fix one of 24 permutations of initial points: first goes to the bottom-left point of the square, second goes to the bottom-right, etc. Having it fixed it is easy to check if this configuration is valid and relax the answer if needed. The only question is where to look for $d$, $x$ and $y$. First we deal with $d$. You can see that there are always two points which move among parallel but not the same lines. In this case $d$ is the distance between these lines, i.e. one of $|x_{i} - x_{j}|$ or $|y_{i} - y_{j}|$. This is the set from where $d$ will be chosen. Now fix $d$ from the overmentioned set and look at two cases. There are two points moving by perpendicular lines. Then there is a square vertex in the point of these lines intersection. In each coordinate this point either equals to bottom-left point of the square or differs by exactly $d$. Thus if bottom-left point has coordinates $(x_{0}, y_{0})$, than $x_{0}$ must be some of $x_{i}, x_{i} + d, x_{i} - d$, similarly for $y_{0}$. Add all this values to the set. All points are moving among parallel lines; WLOG horisontal. Let's fix a permutation of points (yes, once again) and shift each point in such a way that after moving it would equal the bottom-left vertex of the square. Second point should be shifted by $( - d, 0)$, third by $(0, - d)$, fourth by $( - d, - d)$. All four points must be on the same line now; otherwise this case is not possible with this permutation. Now the problem is: given four points on a line, move it to the same point minimizing the maximal path. Clearly, one should move points to the position $(maxX - minX) / 2$; rounding is irrelevant because of the constraint of integer answer. So, having looked through each permutations, we have another set for bottom-left vertex possible coordinates. By the way, the 10th test (and the first test after pretests) was case 2; it was intentionally not included in pretests. Why does it work fast? Let $D$ and $X$ be the sizes of corresponding lookup sets. $D=\\left(_{4}^{2}\\right)\\cdot2=12$. Now for each $d$ there are $4 \\cdot 3 = 12$ coordinates in the first case and no more than $4! = 24$ in the second. Thus $X  \\le  12 \\cdot (12 + 24) = 432$. The main part works in $D\\cdot X\\cdot Y\\cdot4!\\sim5\\cdot10^{5}$; however, it is impossible to build a test where all permutations in the second case give a valid position, so you can reduce this number. Actually, the model solution solves 50 testcases in 10ms without any kind of pruning.",
    "tags": [
      "combinatorics",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "666",
    "index": "E",
    "title": "Forensic Examination",
    "statement": "The country of Reberland is the archenemy of Berland. Recently the authorities of Berland arrested a Reberlandian spy who tried to bring the leaflets intended for agitational propaganda to Berland illegally . The most leaflets contain substrings of the Absolutely Inadmissible Swearword and maybe even the whole word.\n\nBerland legal system uses the difficult algorithm in order to determine the guilt of the spy. The main part of this algorithm is the following procedure.\n\nAll the $m$ leaflets that are brought by the spy are numbered from $1$ to $m$. After that it's needed to get the answer to $q$ queries of the following kind: \"{In which leaflet in the segment of numbers $[l, r]$ the substring of the Absolutely Inadmissible Swearword $[p_{l}, p_{r}]$ occurs more often?}\".\n\nThe expert wants you to automate that procedure because this time texts of leaflets are too long. Help him!",
    "tutorial": "You are given string s and m strings ti. Queries of type ``find the string ti with number from [l;r] which has the largest amount of occurrences of substring s[a, b]'' approaching. Let's build segment tree over the texts t_i. In each vertex of segment tree let's build suffix automaton for the concatenation of texts from corresponding segment with delimeters like a#b. Also for each state in this automaton we should found the number of text in which this state state occurs most over all texts from the segment. Also for each state v in this automaton we should find such states in children of current segment tree vertex that include the set of string from v. If you maintain only such states that do not contain strings like a#b, it is obvious that either wanted state exists or there is no occurrences of strings from v in the texts from child's segment at all. Thus, to answer the query, firstly we find in root vertex the state containing string $s[a;b]$, and after this we go down the segment tree keeping the correct state via links calculated from the previous state. Please refer to the code if something is unclear.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nconst int maxn = 5e4 + 42, logn = 20, sigma = 26;\\n\\nstring s[maxn];\\n\\nstruct suffix_automaton\\n{\\n\\tvector<int> len, link, fpos, lpos, left, right, ans, max, cnt, st;\\n\\tvector<vector<int>> to;\\n\\tvector<vector<int>> up;\\n\\tstring s;\\n\\tint sz, last;\\n\\t\\n\\tvoid clear()\\n\\t{\\n\\t\\tup.clear();\\n\\t\\tto.clear();\\n\\t\\tlen.clear();\\n\\t\\tlink.clear();\\n\\t\\tfpos.clear();\\n\\t\\tlpos.clear();\\n\\t\\tcnt.clear();\\n\\t\\tst.clear();\\n\\t\\ts.clear();\\n\\t}\\n\\t\\n\\tvoid reserve(int n)\\n\\t{\\n\\t\\tup.reserve(n);\\n\\t\\tto.reserve(n);\\n\\t\\tlen.reserve(n);\\n\\t\\tlink.reserve(n);\\n\\t\\tfpos.reserve(n);\\n\\t\\tlpos.reserve(n);\\n\\t\\tcnt.reserve(n);\\n\\t\\tst.reserve(n);\\n\\t\\ts.reserve(n);\\n\\t\\tleft.reserve(n);\\n\\t\\tright.reserve(n);\\n\\t\\tans.reserve(n);\\n\\t\\tmax.reserve(n);\\n\\t}\\n\\t\\n\\tint make_state(vector<int> new_to = vector<int>(sigma + 1), int new_link = 0, int new_fpos = 0, int new_len = 0)\\n\\t{\\n\\t\\tto.push_back(new_to);\\n\\t\\tlink.push_back(new_link);\\n\\t\\tfpos.push_back(new_fpos);\\n\\t\\tlen.push_back(new_len);\\n\\t\\tlpos.push_back(new_fpos);\\n\\t\\tleft.push_back(0);\\n\\t\\tright.push_back(0);\\n\\t\\tans.push_back(0);\\n\\t\\tmax.push_back(0);\\n\\t\\tcnt.push_back(0);\\n\\t\\tup.push_back(vector<int>(logn));\\n\\t\\treturn sz++;\\n\\t}\\n\\t\\n\\tvoid add_letter(char c)\\n\\t{\\n\\t\\ts += c;\\n\\t\\tint p = last;\\n\\t\\tlast = make_state(vector<int>(sigma + 1), 0, len[p] + 1, len[p] + 1);\\n\\t\\tst.push_back(last);\\n\\t\\tcnt[last] = 1;\\n\\t\\tfor(; to[p][c] == 0; p = link[p])\\n\\t\\t\\tto[p][c] = last;\\n\\t\\tif(to[p][c] == last)\\n\\t\\t\\treturn;\\n\\t\\tint q = to[p][c];\\n\\t\\tif(len[q] == len[p] + 1)\\n\\t\\t{\\n\\t\\t\\tlink[last] = q;\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\t\\tint cl = make_state(to[q], link[q], fpos[q], len[p] + 1);\\n\\t\\tlink[last] = link[q] = cl;\\n\\t\\tfor(; to[p][c] == q; p = link[p])\\n\\t\\t\\tto[p][c] = cl;\\n\\t}\\n\\t\\n\\tvoid build(string s)\\n\\t{\\n\\t\\tmake_state();\\n\\t\\tint n = s.size();\\n\\t\\treserve(4 * n);\\n\\t\\t\\n\\t\\tfor(auto c: s)\\n\\t\\t\\tadd_letter(c);\\n\\t\\t\\n\\t\\tint mx_len[n]; // kill states like \\\"X#Y\\\"\\n\\t\\tmemset(mx_len, 0, sizeof(mx_len));\\n\\t\\tint count = 0;\\n\\t\\tfor(int i = 0; i < n; i++)\\n\\t\\t{\\n\\t\\t\\tmx_len[i] = count++;\\n\\t\\t\\tif(s[i] == sigma)\\n\\t\\t\\t\\tcount = 1;\\n\\t\\t}\\n\\t\\tfor(int state = 1; state < sz; state++) \\n\\t\\t{\\n\\t\\t\\tif(len[link[state]] < mx_len[fpos[state] - 1] && len[state] > mx_len[fpos[state] - 1])\\n\\t\\t\\t{\\n\\t\\t\\t\\tint cl = make_state(to[state], link[state], fpos[state], mx_len[fpos[state] - 1]);\\n\\t\\t\\t\\tlink[state] = cl;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\t\\t\\n\\t\\tfor(int state = 1; state < sz; state++) // sparse table, like in LCA\\n\\t\\t\\tup[state][0] = link[state];\\n\\t\\tfor(int lvl = 1; lvl < logn; lvl++)\\n\\t\\t\\tfor(int state = 1; state < sz; state++)\\n\\t\\t\\t\\tup[state][lvl] = up[up[state][lvl - 1]][lvl - 1];\\n\\t\\t\\n\\t\\tvector<int> g[n + 1]; // this actually gives us reversed topsort\\n\\t\\tfor(int state = 1; state < sz; state++)\\n\\t\\t\\tg[len[state]].push_back(state);\\n\\t\\tfor(int ln = n; ln > 0; ln--) \\n\\t\\t\\tfor(auto state: g[ln])\\n\\t\\t\\t{\\n\\t\\t\\t\\tif(link[state])\\n\\t\\t\\t\\t\\tcnt[link[state]] += cnt[state];\\n\\t\\t\\t\\tlpos[link[state]] = std::max(lpos[link[state]], lpos[state]);\\n\\t\\t\\t}\\n\\t}\\n\\t\\n\\tint get(int pos, int ln) // kind of binary search on path to the root\\n\\t{ // pos 1-based\\n\\t\\tint state = st[pos - 1];\\n\\t\\tfor(int i = logn - 1; i >= 0; i--)\\n\\t\\t\\tif(len[up[state][i]] >= ln)\\n\\t\\t\\t\\tstate = up[state][i];\\n\\t\\treturn state;\\n\\t}\\n} me[4 * maxn];\\n\\nvoid build(int v = 1, int l = 1, int r = maxn)\\n{\\n\\tif(r - l == 1)\\n\\t{\\n\\t\\ts[l] = char(sigma) + s[l];\\n\\t\\tme[v].build(s[l]);\\n\\t\\tfor(int state = 0; state < me[v].sz; state++)\\n\\t\\t{\\n\\t\\t\\tme[v].ans[state] = l;\\n\\t\\t\\tme[v].max[state] = me[v].cnt[state];\\n\\t\\t}\\n\\t\\treturn;\\n\\t}\\n\\tint m = (l + r) / 2;\\n\\tbuild(2 * v, l, m);\\n\\tbuild(2 * v + 1, m, r);\\n\\tme[v].build(me[2 * v].s + me[2 * v + 1].s);\\n\\tfor(int state = 1; state < me[v].sz; state++)\\n\\t{\\n\\t\\tif(me[v].fpos[state] <= (int) me[2 * v].s.size()) // we want to know states corresponding to strings from this state in children\\n\\t\\t\\tme[v].left[state] = me[2 * v].get(me[v].fpos[state], me[v].len[state]);\\n\\t\\tif(me[v].lpos[state] > (int) me[2 * v].s.size())\\n\\t\\t\\tme[v].right[state] = me[2 * v + 1].get(me[v].lpos[state] - me[2 * v].s.size(), me[v].len[state]);\\n\\t\\tme[v].max[state] = max(me[2 * v].max[me[v].left[state]], me[2 * v + 1].max[me[v].right[state]]);\\n\\t\\tif(me[v].max[state] == me[2 * v].max[me[v].left[state]])\\n\\t\\t\\tme[v].ans[state] = me[2 * v].ans[me[v].left[state]];\\n\\t\\telse\\n\\t\\t\\tme[v].ans[state] = me[2 * v + 1].ans[me[v].right[state]];\\n\\t}\\n\\tme[2 * v].clear(); // we don't need O(n log^2 n) memory\\n\\tme[2 * v + 1].clear();\\n}\\n\\npair<int, int> get(int a, int b, int state, int v = 1, int l = 1, int r = maxn)\\n{\\n\\tif(a <= l && r <= b)\\n\\t\\treturn {me[v].max[state], me[v].ans[state]};\\n\\tif(r <= a || b <= l)\\n\\t\\treturn {0, 0};\\n\\tint m = (l + r) / 2;\\n\\tauto A = get(a, b, me[v].left[state], 2 * v, l, m);\\n\\tauto B = get(a, b, me[v].right[state], 2 * v + 1, m, r);\\n\\tif(A.first >= B.first)\\n\\t\\treturn A;\\n\\telse\\n\\t\\treturn B;\\n}\\n\\nint main()\\n{\\n    ios::sync_with_stdio(0);\\n    cin.tie(0);\\n    string Q;\\n    cin >> Q;\\n    \\n    int n;\\n    cin >> n;\\n    for(int i = 0; i < n; i++)\\n    {\\n\\t\\tcin >> s[i + 1];\\n\\t\\tfor(auto &it: s[i + 1])\\n\\t\\t\\tit -= 'a';\\n\\t}\\n\\tbuild(); // yeah, this thing builds!\\n\\tint state = 0, ln = 0;\\n\\tvector<int> states, lens;\\n\\tfor(auto c: Q)\\n\\t{\\n\\t\\tc -= 'a';\\n\\t\\twhile(state && !me[1].to[state][c])\\n\\t\\t{\\n\\t\\t\\tstate = me[1].link[state];\\n\\t\\t\\tln = me[1].len[state];\\n\\t\\t}\\n\\t\\tif(me[1].to[state][c])\\n\\t\\t{\\n\\t\\t\\tstate = me[1].to[state][c];\\n\\t\\t\\tln++;\\n\\t\\t}\\n\\t\\tlens.push_back(ln);\\n\\t\\tstates.push_back(state);\\n\\t}\\n\\t\\n\\tint m;\\n\\tcin >> m;\\n\\twhile(m--)\\n\\t{\\n\\t\\tint l, r, pl, pr;\\n\\t\\tcin >> l >> r >> pl >> pr;\\n\\t\\tif(pr - pl + 1 > lens[pr - 1])\\n\\t\\t{\\n\\t\\t\\tcout << l << ' ' << 0 << \\\"\\\\n\\\";\\n\\t\\t\\tcontinue;\\n\\t\\t}\\n\\t\\tint state = me[1].get(me[1].fpos[states[pr - 1]], pr - pl + 1);\\n\\t\\tauto ans = get(l, r + 1, state);\\n\\t\\tcout << max(l, ans.second) << ' ' << ans.first << \\\"\\\\n\\\";\\n\\t}\\n    return 0;\\n}\\n\"",
    "tags": [
      "data structures",
      "string suffix structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "667",
    "index": "A",
    "title": "Pouring Rain",
    "statement": "A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.\n\nToday everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation.\n\nThus, your cup is a cylinder with diameter equals $d$ centimeters. Initial level of water in cup equals $h$ centimeters from the bottom.\n\nYou drink a water with a speed equals $v$ milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on $e$ centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously.\n\nFind the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after $10^{4}$ seconds.\n\nNote one milliliter equals to one cubic centimeter.",
    "tutorial": "To know how much water you consume per second you should divide consumed volume, $v$, by the area of the cup, $\\frac{\\pi d^{2}}{4}$. Then you should compare thisit with $e$. If your speed of drinking is greater, then you'll drink all the water in $\\frac{h}{\\frac{4\\upsilon}{\\pi d^{2}}-e}$ seconds. Otherwise you would never do it.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "667",
    "index": "B",
    "title": "Coat of Anticubism",
    "statement": "As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.\n\nA famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.\n\nCicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The $i$-th rod is a segment of length $l_{i}$.\n\nThe sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle $180^{\\circ}$.\n\nCicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing.\n\nHelp sculptor!",
    "tutorial": "It is possible to make a convex polygon with given side lengths if and only if a generalized triangle inequality holds: the length of the longest side is less than the sum of lengths of other sides. It is impossible to make a convex polygon from a given set, so there is a side which is longest than (or equals to) than sum of others. Assume it is greater by $k$; then it is sufficient to add a rod of length $k + 1$. More, it is clear that adding any shorter length wouldn't satisfy the inequality. Thus the answer for the problem is $\\operatorname*{max}(l_{1},\\cdot\\cdot\\cdot,l_{n})-(l_{1}+\\cdot\\cdot\\cdot\\cdot+l_{n}-\\operatorname*{max}(l_{1},\\cdot\\cdot\\cdot,l_{n}))+1$.",
    "tags": [
      "constructive algorithms",
      "geometry"
    ],
    "rating": 1100
  },
  {
    "contest_id": "669",
    "index": "A",
    "title": "Little Artem and Presents",
    "statement": "Little Artem got $n$ stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her $3$ stones, then $1$ stone, then again $3$ stones, but he can't give her $3$ stones and then again $3$ stones right after that.\n\nHow many times can Artem give presents to Masha?",
    "tutorial": "It is obvious that we need to make sequence of moves like: 1, 2, 1, 2, ... So the answer is 2 * n / 3. After that we have either 0, 1 or 2 stones left. If we have 0, we are done, otherwise we have 1 or 2 left, so we only can give 1 more stone. Final formula is: (2 * n) / 3 + (n % 3 != 0 ? 1 : 0);",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "670",
    "index": "A",
    "title": "Holidays",
    "statement": "On the planet Mars a year lasts exactly $n$ days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.",
    "tutorial": "There are many ways to solve this problem. Let's talk about one of them. At first we need to write a function, which takes the start day of the year and calculate the number of days off in such year. To make it let's iterate on the days of the year and will check every day - is it day off or no. It is easy to show that if the first day of the year equals to the first day of the week (i.e. this day is Monday) in this year will be minimum possible number of the days off. If the first day of the year equals to the first day off of the week (i.e. this day is Saturday) in this year will be maximum possible number of the days off.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "670",
    "index": "B",
    "title": "Game of Robots",
    "statement": "In late autumn evening $n$ robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from $1$ to $10^{9}$.\n\nAt some moment, robots decided to play the game \"Snowball\". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the $n$-th robot says his identifier.\n\nYour task is to determine the $k$-th identifier to be pronounced.",
    "tutorial": "To solve this problem we need to brute how many identifiers will called robots in the order from left to right. Let's solve this problem in one indexing. Let the current robot will call $i$ identifiers. If $k - i > 0$ let's make $k = k - i$ and go to the next robot. Else we need to print $a[k]$, where $a$ is the array with robots identifiers and end our algorithm.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "670",
    "index": "C",
    "title": "Cinema",
    "statement": "Moscow is hosting a major international conference, which is attended by $n$ scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from $1$ to $10^{9}$.\n\nIn the evening after the conference, all $n$ scientists decided to go to the cinema. There are $m$ movies in the cinema they came to. Each of the movies is characterized by two \\textbf{distinct} numbers — the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different).\n\nScientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.",
    "tutorial": "We need to use $map$ (let's call it $cnt$) and calculate how many scientists knows every language (i. e. $cnt[i]$ equals to the number of scientists who know the language number $i$). Let's use the pair $res$, where we will store the number of \\textit{very pleased} scientists and the number of \\textit{almost satisfied} scientists. At first let $res = make_pair(0, 0)$. Now we need to iterate through all movies beginning from the first. Let the current movie has the number $i$. Then if $res < make_pair(cnt[b[i]], cnt[a[i]])$ let's make $res = make_pair(cnt[b[i]], cnt[c[i]])$ and update the answer with the number of current movie.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "670",
    "index": "D1",
    "title": "Magic Powder - 1",
    "statement": "This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.\n\nWaking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs $n$ ingredients, and for each ingredient she knows the value $a_{i}$ — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all $n$ ingredients.\n\nApollinaria has $b_{i}$ gram of the $i$-th ingredient. Also she has $k$ grams of a magic powder. Each gram of magic powder can be turned to exactly $1$ gram of any of the $n$ ingredients and can be used for baking cookies.\n\nYour task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.",
    "tutorial": "This problem with small constraints can be solved in the following way. Let's bake cookies one by one until it is possible. For every new cookie let's calculate $val$ - how many grams of the magic powder we need to bake it. For this let's brute all ingredients and for the ingredient number $i$ if $a[i]  \\le  b[i]$ let's make $b[i] = b[i] - a[i]$, else let's make $b[i] = 0$ and $val = val + a[i] - b[i]$. When we bruted all ingredients if $val > k$ than we can't bake more cookies. Else let's make $k = k - val$ and go to bake new cookie.",
    "tags": [
      "binary search",
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "670",
    "index": "D2",
    "title": "Magic Powder - 2",
    "statement": "This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.\n\nWaking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs $n$ ingredients, and for each ingredient she knows the value $a_i$ — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all $n$ ingredients.\n\nApollinaria has $b_i$ gram of the $i$-th ingredient. Also she has $k$ grams of a magic powder. Each gram of magic powder can be turned to exactly $1$ gram of any of the $n$ ingredients and can be used for baking cookies.\n\nYour task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.",
    "tutorial": "Here we will use binary search on the answer. Let's we check the current answer equals to $cur$. Then the objective function must be realized in the following way. Let's store in the variable $cnt$ how many grams of the magic powder we need to bake $cur$ cookies. Let's iterate through the ingredients and the current ingredient has the number $i$. Then if $a[i] \\cdot cur > b[i]$ let's make $cnt = cnt + a[i] \\cdot cur - b[i]$. If after looking on some ingredient $cnt$ becomes more than $k$ the objective function must return $false$. If there is no such an ingredient the objective function must return $true$. If the objective function returned $true$ we need to move the left end of the binary search to the $cur$, else we need to move the right end of the binary search to the $cur$.",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "670",
    "index": "E",
    "title": "Correct Bracket Sequence Editor",
    "statement": "Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS).\n\nNote that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding \"+\"-s and \"1\"-s to it. For example, sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while \")(\", \"(()\" and \"(()))(\" are not. Each bracket in CBS has a pair. For example, in \"(()(()))\":\n\n- 1st bracket is paired with 8th,\n- 2d bracket is paired with 3d,\n- 3d bracket is paired with 2d,\n- 4th bracket is paired with 7th,\n- 5th bracket is paired with 6th,\n- 6th bracket is paired with 5th,\n- 7th bracket is paired with 4th,\n- 8th bracket is paired with 1st.\n\nPolycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:\n\n- «L» — move the cursor one position to the left,\n- «R» — move the cursor one position to the right,\n- «D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to).\n\nAfter the operation \"D\" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted).\n\nThere are pictures illustrated several usages of operation \"D\" below.\n\nAll incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.\n\nPolycarp is very proud of his development, can you implement the functionality of his editor?",
    "tutorial": "Let's solve this problem in the following way. At first with help of stack let's calculate the array $pos$, where $pos[i]$ equals to the position of the bracket which paired for the bracket in the position $i$. Then we need to use two arrays $left$ and $right$. Then $left[i]$ will equals to the position of the closest to the left bracket which did not delete and $right[i]$ will equals to the position of the closest to the right bracket which did not delete. If there are no such brackets we will store -1 in the appropriate position of the array. Let's the current position of the cursor equals to $p$. Then if the current operation equals to \\texttt{L} let's make $p = left[p]$ and if the current operation equals to \\texttt{R} let's make $p = right[p]$. We need now only to think how process the operation \\texttt{D}. Let $lf$ equals to $p$ and $rg$ equals to $pos[p]$. If $lf > rg$ let's swap them. Now we know the ends of the substring which we need to delete now. If $right[rg] = = - 1$ we need to move $p$ to the left ($p = left[lf]$), else we need to move $p$ to the right ($p = right[rg]$). Now we need to recalculate the links for the ends of the deleted substring. Here we need to check is there any brackets which we did not deleted to the left and to the right from the ends of the deleted substring. To print the answer we need to find the position of the first bracket which we did not delete and go through all brackets which we did not delete (with help of the array $right$) and print all such brackets. To find the position of the first bracket which we did not delete we can store in the array all pairs of the ends of substrings which we deleted, then sort this array and find the needed position. Bonus: how we can find this position in the linear time?",
    "tags": [
      "data structures",
      "dsu",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "670",
    "index": "F",
    "title": "Restore a Number",
    "statement": "Vasya decided to pass a very large integer $n$ to Kate. First, he wrote that number as a string, then he appended to the right integer $k$ — the number of digits in $n$.\n\nMagically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substring of $n$ (a substring of $n$ is a sequence of consecutive digits of the number $n$).\n\nVasya knows that there may be more than one way to restore the number $n$. Your task is to find the smallest possible initial integer $n$. Note that decimal representation of number $n$ contained no leading zeroes, except the case the integer $n$ was equal to zero itself (in this case a single digit 0 was used).",
    "tutorial": "At first let's find the length of the Vasya's number. For make this let's brute it. Let the current length equals to $len$. Then if $len$ equals to the difference between the length of the given string and the number of digits in $len$ if means that $len$ is a length of the Vasya's number. Then we need to remove from the given string all digits which appeared in the number $len$, generate three strings from the remaining digits and choose smaller string from them - this string will be the answer. Let $t$ is a substring which Vasya remembered. Which three strings do we need to generate? Let's write the string $t$ and after that let's write all remaining digits from the given string in the ascending order. This string can be build only if the string $t$ does not begin with the digit 0. Let's write at first the smallest digit from the remaining digits which does not equal to 0. If we have no such a digit we can't build such string. Else we need then to write all digits with smaller than the first digit in the $t$ in the ascending order, then write the string $t$ and then write all remaining digits in the ascending order. Let's write at first the smallest digit from the remaining digits which does not equal to 0. If we have no such a digit we can't build such string. Else we need then to write all digits with smaller than or equal to the first digit in the $t$ in the ascending order, then write the string $t$ and then write all remaining digits in the ascending order. Also we need to separately consider the case when the Vasya's number equals to zero.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "671",
    "index": "A",
    "title": "Recycling Bottles",
    "statement": "It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.\n\nWe can think Central Perk as coordinate plane. There are $n$ bottles on the ground, the $i$-th bottle is located at position $(x_{i}, y_{i})$. Both Adil and Bera can carry only one bottle at once each.\n\nFor both Adil and Bera the process looks as follows:\n\n- Choose to stop or to continue to collect bottles.\n- If the choice was to continue then choose some bottle and walk towards it.\n- Pick this bottle and walk to the recycling bin.\n- Go to step $1$.\n\nAdil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.\n\nThey want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.",
    "tutorial": "Let's solve the problem when Adil and Bera in the same coordinate with bin. Then answer will be $2\\times\\sum_{i=1}^{n}d i s t a n c e(B i n,B o t t l e_{i})$, let's say $T$ to this value. If Adil will take $i$-th bottle and Bera will take $j$-th bottle $(i  \\neq  j)$, then answer will be $T + distance(Adil, Bottle_{i}) - distance(Bin, Bottle_{i}) + distance(Bera, Bottle_{j}) - distance(Bin, Bottle_{j})$. Because for all bottles but the chosen ones we have to add $2$ $*$ $distance(bottle, bin)$. For example if we choose a bottle $i$ for Adil to take first then we have to add $distance(Adil, Bottle_{i})$ + $distance(Bottle_{i}, Bin)$. In defined $T$ we already count $2$ * $distance(Bottle_{i}, Bin)$ but we have to count $distance(Adil, Bottle_{i})$ + $distance(Bottle_{i}, Bin)$ for $i$. So we have to add $distance(Adil, Bottle_{i})$-$distance(Bottle_{i}, Bin)$ to $T$. Because $2$ * $distance(Bin, Bottle_{i})$+$distance(Adil, Bottle_{i})$-$distance(Bin, Bottle_{i})$ is equal to $distance(Adil, Bottle_{i})$+$distance(Bottle_{i}, Bin)$. Lets construct two arrays, $a_{i}$ will be $distance(Adil, Bottle_{i}) - distance(Bin, Bottle_{i})$, and $b_{j}$ will be $distance(Bera, Bottle_{j}) - distance(Bin, Bottle_{j})$. We will choose $i$ naively, after that we have to find minimum $b_{j}$ where $j$ is not equal to $i$. This one easily be calculated with precalculations, let's find optimal $opt1$ for Bera, also we will find second optimal $opt2$ for Bera, if our chosen $i$ is equal to $opt1$ then Bera will go $opt2$, otherwise he will go $opt1$. Don't forget to cases that all bottles taken by Adil or Bera!",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define pb push_back\\n#define orta (bas + son >> 1)\\n#define sag (k + k + 1)\\n#define sol (k + k)\\n#define endl '\\\\n'\\n#define foreach(i,x) for(type(x)i=x.begin();i!=x.end();i++)\\n#define FOR(ii,aa,bb) for(int ii=aa;ii<=bb;ii++)\\n#define ROF(ii,aa,bb) for(int ii=aa;ii>=bb;ii--)\\n#define mp make_pair\\n#define nd second\\n#define st first\\n#define type(x) __typeof(x.begin())\\n\\ntypedef pair < int ,int > pii;\\n\\ntypedef long long ll;\\n\\nconst long long linf = 1e18+5;\\nconst int mod = (int) 1e9 + 7;\\nconst int logN = 17;\\nconst int inf = 1e9;\\nconst int N = 1e6 + 5;\\n\\nint Kx, Ky, Cx, Cy, Tx, Ty, n, x, y;\\n\\ndouble pre[N], suff[N], add[N], all;\\n\\ndouble dist(int x, int y, int a, int b) { return sqrt((ll) (x - a) * (x - a) + (ll) (y - b) * (y - b)); }\\n\\nint main() {\\n\\n\\tscanf(\\\"%d %d %d %d %d %d\\\", &Kx, &Ky, &Cx, &Cy, &Tx, &Ty);\\n\\n\\tscanf(\\\"%d\\\", &n);\\n\\n\\tFOR(i, 1, n) {\\n\\t\\tscanf(\\\"%d %d\\\", &x, &y);\\n\\t\\tdouble add = dist(Tx, Ty, x, y);\\n\\t\\tall += add * 2;\\n\\t\\tsuff[i] = pre[i] = dist(Cx, Cy, x, y) - add;\\n\\t\\t::add[i] = dist(Kx, Ky, x, y) - add;\\n\\t}\\n\\t\\n\\tpre[0] = suff[n+1] = linf;\\n\\tFOR(i, 1, n) { pre[i] = min(pre[i-1], pre[i]); }\\n\\tROF(i, n, 1) { suff[i] = min(suff[i+1], suff[i]); }\\n\\n\\tdouble ans = suff[1] + all;\\n\\n\\tFOR(i, 1, n) \\n\\t\\tans = min(ans, all + min(0.0, min(pre[i-1], suff[i+1])) + add[i]);\\n\\n\\tprintf(\\\"%.12lf\\\\n\\\", ans);\\n\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "dp",
      "geometry",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "671",
    "index": "B",
    "title": "Robin Hood",
    "statement": "We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.\n\nThere are $n$ citizens in Kekoland, each person has $c_{i}$ coins. Each day, Robin Hood will take exactly $1$ coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's $1$ coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in $k$ days. He decided to spend these last days with helping poor people.\n\nAfter taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.\n\nYour task is to find the difference between richest and poorest persons wealth after $k$ days. Note that the choosing at random among richest and poorest doesn't affect the answer.",
    "tutorial": "We observe that we can apply operations separately this means first we will apply all increase operations, and after will apply all decrease operations, vice versa. We will use following algorithm. We have to apply following operation $k$ times, add one to minimum number in array. We will simply binary search over minimum value after applying k operation. Let's look how to check if minimum will be great or equal to $p$. If $\\sum_{p=1}^{n}m a x(0,\\,p-c_{i})$ is less or equal to $k$ then we can increase all elements to at least $p$. In this way we can find what will be minimum value after $k$ operations. Let's say this minimum value to $m$. After we find it we will increase all numbers less than $m$ to $m$. But there may be some operations we still didn't apply yet, this number can be at most $n - 1$, otherwise minimum would be greater than $m$ because we can increase all numbers equal to $m$ by one with this number of increases. Since minimum has to be same we just have to increase some elements in our array that equal to $m$. We will use same algorithm for decreasing operations. Finally we will print $max element$ - $min element$ in final array. Overall complexity will be $O(nlogk)$.",
    "code": "\"#include<bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define pii pair<int,int>\\n#define ll long long\\n#define N (int)(5e5+10)\\n#define mod 1000000007\\n#define mp make_pair\\n#define pb push_back\\n#define nd second\\n#define st first\\n#define inf mod\\n#define endl '\\\\n'\\n#define sag (sol|1)\\n#define sol (root<<1)\\n#define bit(x,y) ((x>>y)&1)\\n\\nll t;\\nint a[N],i,j,k,n,m,x,y,z;\\n\\nint main(){\\n\\tcin >> n >> k;\\n\\n\\tfor(i=1 ; i<=n ; i++)\\n\\t\\tscanf(\\\"%d\\\",a+i);\\n\\t\\n\\tint bas=1;, son=2*inf;\\n\\t\\n\\twhile(bas<son){\\n\\t\\tint ort = ((ll)bas+son)/2;\\n\\t\\tif(bas==ort)\\n\\t\\t\\tort++;\\n\\t\\tt = 0;\\n\\t\\tfor(i=1 ; i<=n ; i++)\\n\\t\\t\\tt += max(0 , ort-a[i]);\\n\\t\\tif(t <= k)\\n\\t\\t\\tbas = ort;\\n\\t\\telse\\n\\t\\t\\tson = ort-1;\\n\\t}\\n\\t\\n\\tt = k;\\n\\t\\n\\tfor(i=1 ; i<=n ; i++){\\n\\t\\tt -= max(0 , bas-a[i]);\\n\\t\\ta[i] = max(a[i] , bas);\\n\\t}\\n\\t\\n\\tfor(i=1 ; i<=n ; i++)\\n\\t\\tif(a[i] == bas and t){\\n\\t\\t\\tt--;\\n\\t\\t\\ta[i]++;\\n\\t\\t}\\n\\t\\n\\tbas=1, son=2*inf;\\n\\t\\n\\twhile(bas<son){\\n\\t\\tint ort = ((ll)bas+son)/2;\\n\\t\\tt = 0;\\n\\t\\tfor(i=1 ; i<=n ; i++)\\n\\t\\t\\tt += max(0 , a[i]-ort);\\n\\t\\tif(t <= k)\\n\\t\\t\\tson = ort;\\n\\t\\telse\\n\\t\\t\\tbas = ort+1;\\n\\t}\\n\\t\\n\\tt = k;\\n\\t\\n\\tfor(i=1 ; i<=n ; i++){\\n\\t\\tt -= max(0 , a[i]-bas);\\n\\t\\ta[i] = min(a[i] , bas);\\n\\t}\\n\\t\\n\\tfor(i=1 ; i<=n ; i++)\\n\\t\\tif(a[i] == bas and t){\\n\\t\\t\\tt--;\\n\\t\\t\\ta[i]--;\\n\\t\\t}\\n\\n\\tcout << *max_element(a+1,a+1+n) - *min_element(a+1,a+1+n) << endl;\\n\\n}\\n\"",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "671",
    "index": "C",
    "title": "Ultimate Weirdness of an Array",
    "statement": "Yasin has an array $a$ containing $n$ integers. Yasin is a 5 year old, so he loves ultimate weird things.\n\nYasin denotes weirdness of an array as maximum $gcd(a_{i}, a_{j})$ value among all $1 ≤ i < j ≤ n$. For $n ≤ 1$ weirdness is equal to $0$, $gcd(x, y)$ is the greatest common divisor of integers $x$ and $y$.\n\nHe also defines the ultimate weirdness of an array. Ultimate weirdness is $\\sum_{i=1}^{n}\\sum_{j=i}^{n}f(i,\\,j)$ where $f(i, j)$ is weirdness of the new array $a$ obtained by removing all elements between $i$ and $j$ inclusive, so new array is $[a_{1}... a_{i - 1}, a_{j + 1}... a_{n}]$.\n\nSince 5 year old boys can't code, Yasin asks for your help to find the value of ultimate weirdness of the given array $a$!",
    "tutorial": "If we calculate an array $H$ where $H_{i}$ is how many $(l - r)$s there are that $f(l, r)$ $ \\le $ $i$, then we can easily calculate the answer. How to calculate array $H$. Let's keep a vector, $v_{i}$ keeps all elements indexes which contain $i$ as a divisor $-$ in sorted order. We will iterate over $max element$ to $1$. When we are iterating we will keep another array $next$, Let's suppose we are iterating over $i$, $next_{j}$ will keep leftmost $k$ where $f(j, k)$ $ \\le $ $i$. Sometimes there is no such $k$, then $next_{j}$ will be $n + 1$. $H_{i}$ will be equal to $\\sum_{p=1}^{n}n-n e x t_{p}+1$, because if we choose p as $l$, $r$ must be at least $next_{p}$, so for $l$ we can choose $n$-$next_{p}$+$1$ different $r$ s. Let's look how we update $next$ array when we iterate $i$ to $i - 1$. Let $v_{i}$ be $b_{1}, b_{2}, b_{3}...b_{k}$. Note that our $l - r$ must be cover at least $k - 1$ of this indexes. $l$ must less or equal to $b_{2}$. So we have to maximize all $next_{p}$ with $n + 1$ where $p > b_{2}$. Otherwise If $l  \\ge  b_{1} + 1$ then $r$ must be at least $b_{k}$, that's we will maximize all $next_{p}$'s where $b_{1} < p  \\le  b2$ with $b_{k}$. And finally for all $next_{p}$'s where $(1  \\le  p  \\le  b_{1})$ we have to maximize them with $b_{k - 1}$. Observe that $next$ array will be monotonic $-$ in non decreasing order $-$ after all operations. So we can easily make our updates with a segment tree that can perform following operations: $-$Returns rightmost index $i$ where $next_{i}$ is less than some $k$. $-$Returns sum of all elements in $next$ array. $-$Can assign some $k$ to all elements between some $l$ and $r$. If all update and queries performed in $O(logn)$ then overall complexity will be $O(nlogn)$, we can also apply all this operations with STL set in same complexity.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define dbgs(x) cerr << (#x) << \\\" --> \\\" << (x) << ' '\\n#define dbg(x) cerr << (#x) << \\\" --> \\\" << (x) << endl\\n\\n#define foreach(i,x) for(type(x)i=x.begin();i!=x.end();i++)\\n#define FOR(ii,aa,bb) for(int ii=aa;ii<=bb;ii++)\\n#define ROF(ii,aa,bb) for(int ii=aa;ii>=bb;ii--)\\n\\n#define type(x) __typeof(x.begin())\\n\\n#define orta (bas + son >> 1)\\n#define sag (k + k + 1)\\n#define sol (k + k)\\n\\n#define pb push_back\\n#define mp make_pair\\n\\n#define nd second\\n#define st first\\n\\n#define endl '\\\\n'\\n\\ntypedef pair < int ,int > pii;\\n\\ntypedef long long ll;\\n\\nconst long long linf = 1e18+5;\\nint mod = (int) 1e9 + 7;\\nconst int logN = 18;\\nconst int inf = 1e9;\\nconst int N = 2e5 + 5;\\n\\nint n, m, x, y, z, a[N];\\nvector< int > H[N], v[N];\\nll sum = 0, ans[N];\\n\\nset< pair< pii , int > > S;\\n\\nvoid divide(int x) {\\n    set< pair< pii , int > > :: iterator it, it2;\\n    it = S.lower_bound(mp(mp(x + 1, 0), -1));\\n    if(it == S.begin()) return ; it--;\\n    if(it->st.nd < x) return ;\\n    pair< pii , int > t = *it; S.erase(*it);\\n    S.insert(mp(mp(t.st.st, x), t.nd));\\n    if(x + 1 <= t.st.nd) S.insert(mp(mp(x + 1, t.st.nd), t.nd));\\n}\\n\\nvoid remove(int x) {\\n    divide(x - 1);\\n    while(S.rbegin()->st.st >= x) {\\n        pair< pii , int > t = *S.rbegin();\\n        sum -= (t.st.nd - t.st.st + 1) * (ll) (t.nd);\\n        S.erase(S.find(t));\\n    }\\n}\\n\\nvoid maximize(set< pair< pii , int > > :: iterator it, int x, int y) {\\n    pair< pii , int > t; t.nd = x; t.st.st = y;\\n    set< pair< pii , int > > :: iterator it2;\\n    while(it != S.end()) {\\n        if(it->nd >= x) break;\\n        t.st.nd = it->st.nd;\\n        sum -= (it->st.nd - it->st.st + 1) * (ll) (it->nd);\\n        it2 = it; it2++; S.erase(it); it = it2;\\n    }\\n    if(t.st.st <= t.st.nd) {\\n        sum += (t.st.nd - t.st.st + 1) * (ll) t.nd;\\n        S.insert(t);\\n    }\\n}\\n\\nint main() {\\n\\n    scanf(\\\"%d\\\", &n);\\n\\n    FOR(i, 1, n) {\\n        scanf(\\\"%d\\\", &a[i]);\\n        H[a[i]].pb(i); sum += i;\\n        S.insert(mp(mp(i, i), i));\\n    }\\n\\n    FOR(i, 1, N - 1)\\n        for(int j = i; j < N; j += i)\\n            foreach(it, H[j])\\n                v[i].pb(*it);\\n\\n    ans[N - 1] = n * (ll) (n + 1) / 2;\\n\\n    ROF(i, N - 2, 1) {\\n        int l = v[i].size() - 1;\\n        if(l <= 0) { ans[i] = ans[i + 1];  continue; }\\n        sort(v[i].begin(), v[i].end()); remove(v[i][1] + 1);\\n        maximize(S.begin(), v[i][l-1], 1);\\n        divide(v[i][0]); maximize(S.lower_bound(mp(mp(v[i][0] + 1, v[i][0]), 0)), v[i][l], v[i][0] + 1);\\n        ans[i] = (S.rbegin()->st.nd * (ll)(n + 1) - sum);\\n    }\\n\\n    ll all = 0;\\n\\n    FOR(i, 1, N - 2) all += (ans[i + 1] - ans[i]) * (ll) i;\\n\\n    printf(\\\"%lld\\\\n\\\", all);\\n\\n    return 0;\\n}\\n\"",
    "tags": [
      "data structures",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "671",
    "index": "D",
    "title": "Roads in Yusland",
    "statement": "Mayor of Yusland just won the lottery and decided to spent money on something good for town. For example, repair all the roads in the town.\n\nYusland consists of $n$ intersections connected by $n - 1$ bidirectional roads. One can travel from any intersection to any other intersection using only these roads.\n\nThere is only one road repairing company in town, named \"RC company\". Company's center is located at the intersection $1$. RC company doesn't repair roads you tell them. Instead, they have workers at some intersections, who can repair only some specific paths. The $i$-th worker can be paid $c_{i}$ coins and then he repairs \\textbf{all roads} on a path from $u_{i}$ to some $v_{i}$ that \\textbf{lies on the path} from $u_{i}$ to intersection $1$.\n\nMayor asks you to choose the cheapest way to hire some subset of workers in order to repair all the roads in Yusland. It's allowed that some roads will be repaired more than once.\n\nIf it's impossible to repair all roads print $ - 1$.",
    "tutorial": "I want to thank GlebsHP, i originally came up with another problem similar to it, GlebsHP suggested to use this one in stead of it. Let's look for a optimal subset of paths, paths may intersect. To prevent from this let's change the problem litte bit. A worker can repair all nodes between $u_{i}$ and some $k$, where $k$ is in the path between $u_{i}$ and $v_{i}$ with cost $c_{i}$, also paths must not intersect. In this way we will never find better solution from original problem and we can express optimal subset in original problem without any path intersections in new problem. Let's keep a $dp$ array, $dp_{i}$ keeps minimum cost to cover all edges in subtree of node $i$, also the edge between $i$ and $parent_{i}$. How to find answer of some $i$. Let's choose a worker which $u_{j}$ is in the subtree of $i$ and $v_{j}$ is a parent of node $i$. Then if we choose this worker answer must be $c_{j}$ + ($dp_{k}$ where $k$ is child of a node in the path from $u_{j}$ to $i$ for all $k$'s). Of course we have to exclude nodes chosen as $k$ and in the path from $u_{j}$ to $i$ since we will cover them with $j$-th worker. We will construct a segment tree by dfs travel times so that for all nodes, workers which start his path in subtree of this node can be reached by looking a contiguous segment in tree. In node $i$, segment will keep values what will be $dp_{i}$ equal to if we choose this worker to cover path between $u_{j}$ and $parent_{i}$. We will travel our tree with dfs, in each $i$ after we calculated node $i$'s children dp's we will update our segment in following way, add all workers to segment where $u_{j} = i$ with value $c_{j}$ + (sum of node $i$'s children dp's). For all workers $v_{j}$ equal to $i$, we must delete it from segment, this is assigning $inf$ to it. The only thing we didn't handle is what to do with workers under this node. Imagine all updates in subtree of node $k$ where $k$ is a child of node $i$. We have to increase all of them by (sum of node $i$'s children dp's-$dp_{k}$). After applying all of this operations answer will be minimum value of workers start their path from a node in subtree of $i$ in segment tree. Overall complexity will be $((n + m)logm)$. Please look at the code to be more clear.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define pb push_back\\n#define orta (bas + son >> 1)\\n#define sag (k + k + 1)\\n#define sol (k + k)\\n#define endl '\\\\n'\\n#define foreach(i,x) for(type(x)i=x.begin();i!=x.end();i++)\\n#define FOR(ii,aa,bb) for(int ii=aa;ii<=bb;ii++)\\n#define ROF(ii,aa,bb) for(int ii=aa;ii>=bb;ii--)\\n#define mp make_pair\\n#define nd second\\n#define st first\\n#define type(x) __typeof(x.begin())\\n\\ntypedef pair < int ,int > pii;\\n\\ntypedef long long ll;\\n\\nconst long long linf = 1e15+5;\\nconst int mod = (int) 1e9 + 7;\\nconst int logN = 17;\\nconst int inf = 1e9;\\nconst int N = 1e6 + 5;\\n\\nint n, m, x, y, z, c[N], start[N], finish[N], w[N], T;\\nvector< int > v[N], add[N], del[N];\\nll dp[N], ST[N << 2], L[N << 2]; \\n\\nvoid dfs(int node, int root) {\\n\\tstart[node] = T + 1;\\n\\tforeach(it, add[node]) w[*it] = ++T;\\n\\tforeach(it, v[node]) {\\n\\t\\tif(*it != root) {\\n\\t\\t\\tdfs(*it, node);\\n\\t\\t}\\n\\t} finish[node] = T;\\n}\\n\\nll update(int k, int bas, int son, int x, ll D) {\\n\\tif(bas > x || son < x) return ST[k];\\n\\tif(bas == son) return ST[k] = D;\\n\\tST[k] = min(update(sol, bas, orta, x, D), update(sag, orta + 1, son, x, D)) + L[k];\\n    if(ST[k] > linf) ST[k] = linf;\\n\\treturn ST[k];\\n\\n}\\n\\nll update(int k, int bas, int son, int x, int y, ll D) {\\n\\tif(bas > y || son < x) return ST[k];\\n\\tif(x <= bas && son <= y) {\\n\\t\\tL[k] = min(linf, D + L[k]);\\n\\t\\tST[k] = min(linf, D + ST[k]);\\n\\t\\treturn ST[k];\\n\\t}\\n\\tST[k] = min(update(sol, bas, orta, x, y, D), update(sag, orta + 1, son, x, y, D)) + L[k];\\n\\tif(ST[k] > linf) ST[k] = linf;\\n\\treturn ST[k];\\n}\\n\\nll query(int k, int bas, int son, int x, int y) {\\n\\tif(bas > y || son < x) return linf;\\n\\tif(x <= bas && son <= y) return ST[k];\\n\\treturn min(linf, min(query(sol, bas, orta, x, y), query(sag, orta + 1, son, x, y)) + L[k]);\\n}\\n\\nll solve(int node, int root) {\\n\\tll all = 0;\\n\\tforeach(it, v[node]) {\\n\\t\\tif(*it == root) continue;\\n\\t\\tall += solve(*it, node);\\n\\t\\tif(all != 2 * linf)\\n\\t\\t    all = min(all, 2 * linf);\\n\\t}\\n\\tif(node == 1) return dp[node] = all;\\n\\tforeach(it, add[node]) update(1, 1, m, w[*it], c[*it] + all);\\t\\n\\tforeach(it, del[node]) update(1, 1, m, w[*it], linf);\\t\\n\\tforeach(it, v[node])\\n\\t\\tif(*it != root)\\n\\t\\t\\tupdate(1, 1, m, start[*it], finish[*it], all - dp[*it]);\\n\\tdp[node] = query(1, 1, m, start[node], finish[node]);\\n\\treturn dp[node];\\n}\\n\\nint main() {\\n\\n\\tscanf(\\\"%d %d\\\", &n, &m);\\n\\n\\tFOR(i, 2, n) {\\n\\t\\tscanf(\\\"%d %d\\\", &x, &y);\\n\\t\\tv[x].pb(y); v[y].pb(x);\\n\\t}\\n\\n\\tFOR(i, 1, m) {\\n\\t\\tscanf(\\\"%d %d %d\\\", &x, &y, &c[i]);\\n\\t\\tadd[x].pb(i);\\n\\t\\tdel[y].pb(i);\\n\\t}\\n\\t\\n\\tdfs(1, 0);\\n\\n\\tll ans = solve(1, 0);\\n\\n\\tif(ans >= linf) ans = -1;\\n\\n\\tprintf(\\\"%lld\\\\n\\\", ans);\\n\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "671",
    "index": "E",
    "title": "Organizing a Race",
    "statement": "Kekoland is a country with $n$ beautiful cities numbered from left to right and connected by $n - 1$ roads. The $i$-th road connects cities $i$ and $i + 1$ and length of this road is $w_{i}$ kilometers.\n\nWhen you drive in Kekoland, each time you arrive in city $i$ by car you immediately receive $g_{i}$ liters of gas. There is no other way to get gas in Kekoland.\n\nYou were hired by the Kekoland president Keko to organize the most beautiful race Kekoland has ever seen. Let race be between cities $l$ and $r$ ($l ≤ r$). Race will consist of two stages. On the first stage cars will go from city $l$ to city $r$. After completing first stage, next day second stage will be held, now racers will go from $r$ to $l$ with their cars. Of course, as it is a race, racers drive directly from start city to finish city. It means that at the first stage they will go only right, and at the second stage they go only left. Beauty of the race between $l$ and $r$ is equal to $r - l + 1$ since racers will see $r - l + 1$ beautiful cities of Kekoland. Cars have infinite tank so racers will take all the gas given to them.\n\nAt the beginning of \\textbf{each stage} racers start the race with empty tank ($0$ liters of gasoline). They will immediately take their gasoline in start cities ($l$ for the first stage and $r$ for the second stage) right after the race starts.\n\nIt may not be possible to organize a race between $l$ and $r$ if cars will run out of gas before they reach finish.\n\nYou have $k$ presents. Each time you give a present to city $i$ its value $g_{i}$ increases by $1$. You may distribute presents among cities in any way (also give many presents to one city, each time increasing $g_{i}$ by $1$). What is the most beautiful race you can organize?\n\nEach car consumes $1$ liter of gas per one kilometer.",
    "tutorial": "Intended solution was $O(n{\\sqrt{n}})$. Let $cost(l, r)$ be minimum cost to make $l$-$r$ suitable for a race. In task we have to find such $l$-$r$ that $cost(l, r)$ $ \\le $ $k$ and $r$-$l$+$1$ is maximum. How to calculate $cost(l, r)$: Let's look at how we do our increases to make race from $l$ to $r$ (first stage) possible. Greedily we will make our increases in right as much as possible. So if we run out of gas in road between $i$ and $i$+$1$ we will add just enough gasoline to $G_{i}$. After make first stage possible we will add gasoline to $r$ just enough to make second stage possible. This solution will be $O(n^{3})$. Let's find $next_{i}$, $next_{i}$ will keep leftmost $j$ that we can't reach with current gasoline, we will also keep $need_{i}$ that keeps how many liter gasoline we have to add to $next_{i}$-1. After applying this increase city $next_{i}$ will be reachable from $i$, cars will be consumed all of their gasoline just before taking gasoline in city $next_{i}$. How to find it: We will keep an array $pre$ where $pre_{i}$ $=$ $pre_{i - 1}$ + $G_{i}$-$W_{i}$. If $pre_{j}$-$pre_{i - 1}$ < 0 then we can't reach to $j$ + $1$. If we find leftmost $j$ ($j  \\ge  i$) where $pre_{j}$ is strictly smaller than $pre_{i}$ then $next_{i}$ will be equal to $j$ and $need_{i}$ will be equal to $pre_{j}$-$pre_{i - 1}$. Building tree: Let's make a tree where $next_{i}$ is father of node $i$. In dfs travel, when we are in a node $i$ all increases will be made to make all first stages possible from $i$ to all $j$'s, now we will keep an array $suff$ where $suff_{i}$ $=$ $suff_{i - 1}$ + $G_{i}$-$W_{i - 1}$. So when we are increasing a city $u$'s $G_{u}$ we have to increase all $suff$ values from u to $n$. We will also keep another array $cost$, $cost_{j}$ will keep the cost to make stage 1 possible from $i$ to $j$+$1$. Increases will be nearly same, for $u$ we will increase all $v$'s costs $v  \\ge  u$. So when we reach a node $i$ we will apply increases to make first stage possible between $i$ ans $next_{i}$. When we are done with this node, we will revert increases. Last part: Now we have to find rightmost $j$ for all $i$'s. Let's look at whether it is possible or not for a j. We can check it in $O(1)$. First $cost_{j - 1}$ must be less or equal to $k$, also $maximum(suff_{k} i  \\le  k < j)$-($suff_{j}$-$delta_{j}$) + ($cost_{j}$-$delta_{j}$) $ \\le $ $k$. $delta_{j}$ keeps how many increases we apply to node $j$. We will decrease them since direct increases in $j$ are made for $j$+$1$, we don't need to keep $delta$ array since it will not effect expression. Also observe that the only thing changes in expression is $maximum(suff_{k} i  \\le  k < j)$. In this way problem can be solved in $O(n^{2})$. Both sqrt dec. solutions are using the same idea. Main solution will be posted soon. Let $p_{i}$ be $cost_{i}$-$suff_{i}$. As we said before this value will never change. Let's keep a segment tree. In each node we will keep such values. Assume this node of segment covers between $l$ and $r$. We will keep such $ind1$, $ind2$ and $mx_{suff}$. $ind1$ will keep minimum $p_{j}$'s index where $l  \\le  j  \\le  r$. $ind2$ will keep minimum ($maximum{suff_{l \\le  k < j}}$+$p_{j}$)'s index where $mid + 1  \\le  j  \\le  r$ this means we have to choose $j$ from this nodes right child. $mx_{suff}$ will keep $maximum{suff_{l \\le k \\le r}}$. We also have to keep values for $ind1$ and $ind2$ ($p_{ind1}$ and ($maximum{suff_{l \\le  k < ind2}}$+$p_{ind2}$)). How to update them: In a update we will increase some some suffixes $cost_{i}$ and $suff_{i}$ values. So $ind1$ will be same for each node. For every covered node $mx_{suff}$ will increase by $k$ ($k$ is increase value in update). Tricky part is how to update $ind2$. Let's define a function $relax()$. $relax(u)$ calculates $ind2$ value for node $u$. Note that for relax function to work all nodes in subtree of $u$ must be calculated already. We will call relax function after calculating this nodes children. We will come to relax function later. How to query: We can use pretty much same function as relax. We have to query find values for a $l$-$r$ segment. We will keep an extra value in function, let's call it $t$. If this node covers segment $a$-$b$ then $t$ will keep $maximum{suff_{l \\le  k < a}}}$. If this node doesn't intersect with $l$-$r$ segment we will return worst values (for example for mx_suff value we will return -inf). Let's look what to do when this node is covered by $l$-$r$. If $mx_{suff}$ value of this node's left child is greater or equal to $t$ then $ind2$ value will be same. So if $maximum{suff_{l \\le  k < ind2}}$+$p_{ind2}$) is lower or equal to $k$ for this node answer is ind2, it is greater than $k$ then we will go this nodes left child to calculate answer. If $mx_{suff}$ value of this node's left child is lower than $t$ value then ($maximum{suff_{l \\le  j < mid}}$) will equal to $t$ for each $j$. So we just have to rightmost $j$ that $p_{j}$ $ \\le $ $k - t$ in subtree of this node. This can be calculated in $O(logn)$ time. We didn't look at right child yet, so we will go to right child again with same $t$ value. What to do when this node intersects with $l$-$r$ and $l$-$r$ doesn't cover it. We will go both children, first to left, after we will update $t$ value for right child by $mx_{suff}$ value returned from left child. We will lazy prop to push values. Other condition: In node $l$ we have to query between $l$ and $r$, $r$ is rightmost index that $cost_{r - 1}$ < $k$. Since cost values are monotonic this $r$ can be found easily in $O(logn)$. Relax function can be calculated nearly same as query. But this will work in $O(logn)$, since we just have to go exactly one child, since we don't interested in rightmost values.",
    "code": "\"#include <cstdio>\\n#include <algorithm>\\n#include <cassert>\\n#include <tuple>\\n#include <vector>\\nusing namespace std;\\n\\n#define eprintf(...) fprintf(stderr, __VA_ARGS__)\\n\\nconst int N = 100500;\\nconst int K = 230;\\n\\ntypedef long long llong;\\n\\nint D[N];\\nint A[N];\\n\\nllong PS[N];\\nint st[N];\\n\\nbool was[N];\\nvector<int> E[N];\\n\\nint n, k;\\n\\nstruct block {\\n    int len = 0;\\n    llong X[K] = {0};\\n    llong dA[K] = {0}; // Subject to further optimization\\n    llong glob = 0;\\n    llong max_req = -(llong)1e18;\\n    llong max_X = -(llong)1e18;\\n\\n    void add_global(llong d) {\\n        glob += d;\\n    }\\n\\n    inline llong get_max_req() const {\\n        return max_req;\\n    }\\n\\n    inline llong get_max_X() const {\\n        return max_X + glob;\\n    }\\n    \\n    void recalc() {\\n        assert(glob == 0);\\n        max_req = -(llong)1e18;\\n        for (int i = 0; i < len; i++) {\\n            llong got = i ? dA[i - 1] : 0;\\n            if (got > k)\\n                break;\\n            max_req = max(max_req, X[i] + k - got);\\n        }\\n        max_X = *max_element(X, X + len);\\n    }\\n   \\n    void flush() {\\n        for (int i = 0; i < len; i++) {\\n            X[i] += glob;\\n            dA[i] += glob;\\n        }\\n        max_X += glob;\\n        glob = 0;\\n    }\\n\\n    void add_suff(int x, llong d) {\\n        flush();\\n        for (int i = x; i < len; i++) {\\n            X[i] += d;\\n            dA[i] += d;\\n        }\\n        recalc();\\n    }\\n    \\n    // ans, mx\\n    pair<int, llong> get(int l, llong prev_mx = -1e18) const {\\n        llong mx = prev_mx;\\n        if (l != -1)\\n            mx = X[l] + glob;\\n        int ans = 0;\\n        for (int i = l + 1; i < len; i++) {\\n            llong got_prev = (i ? dA[i - 1] : -(llong)1e18) + glob;\\n            llong got = dA[i] + glob;\\n            if (got_prev > k)\\n                break;\\n            if (X[i] + glob + k - got >= mx) {\\n                ans = max(ans, i - l);\\n            }\\n            mx = max(mx, X[i] + glob);\\n        }\\n        return make_pair(ans, mx);\\n    }\\n} B[N / K + 2];\\n\\nint blocks;\\n\\nvoid add_suff(int l, llong d) {\\n    int id = l / K;\\n    B[id].add_suff(l - id * K, d);\\n    while (++id < blocks) {\\n        B[id].add_global(d);\\n    }\\n}\\n\\nint ans = 1;\\n\\nvoid process(int l) {\\n    int ans;\\n    llong mx;\\n    int id = l / K;\\n    tie(ans, mx) = B[id].get(l - id * K);\\n    ++ans;\\n    int good_id = -1;\\n    llong good_mx = -42;\\n    int prev_good_id = -1;\\n    llong prev_good_mx = -42;\\n    while (++id < blocks) {\\n        if (B[id - 1].dA[K - 1] + B[id - 1].glob > k)\\n            break;\\n        if (B[id].get_max_req() >= mx) {\\n            prev_good_id = good_id;\\n            prev_good_mx = good_mx;\\n            good_id = id;\\n            good_mx = mx;\\n        }\\n        mx = max(mx, B[id].get_max_X());\\n    }\\n    if (good_id != -1) {\\n        if ((good_id + 1) * K - l <= ::ans)\\n            return;\\n        int ans2;\\n        tie(ans2, ignore) = B[good_id].get(-1, good_mx);\\n        if (ans2 == 0) {\\n            if (prev_good_id != -1) {\\n                if ((prev_good_id + 1) * K - l <= ::ans)\\n                    return;\\n                tie(ans2, ignore) = B[prev_good_id].get(-1, prev_good_mx);\\n                assert(ans2 != -1);\\n                ans = ans2 + prev_good_id * K - l;\\n            }\\n        } else {\\n            ans = ans2 + good_id * K - l;\\n        }\\n    }\\n    //eprintf(\\\"l = %d -> ans = %d\\\\n\\\", l, ans);\\n    ::ans = max(::ans, ans);\\n}\\n\\nvoid DFS(int x, int p = -1) {\\n    was[x] = true;\\n    if (p != -1)\\n        add_suff(p - 1, PS[x] - PS[p]);\\n    process(x);\\n    for (int y : E[x]) {\\n        DFS(y, x);\\n    }\\n    if (p != -1)\\n        add_suff(p - 1, PS[p] - PS[x]);\\n}\\n\\nint main() {\\n    scanf(\\\"%d %d\\\", &n, &k);\\n    for (int i = 0; i < n - 1; i++) {\\n        scanf(\\\"%d\\\", &D[i]);\\n    }\\n    for (int i = 0; i < n; i++) {\\n        scanf(\\\"%d\\\", &A[i]);\\n    }\\n    for (int i = 1; i < n; i++) {\\n        PS[i] = PS[i - 1] + A[i - 1] - D[i - 1];\\n    }\\n    int pt = 0;\\n    for (int i = n - 1; i >= 0; i--) {\\n        while (pt > 0 && PS[st[pt - 1]] >= PS[i])\\n            --pt;\\n        if (pt)\\n            E[st[pt - 1]].push_back(i);\\n        st[pt++] = i;\\n    }\\n    llong curX = 0;\\n    for (int i = 1; i < n; i++)\\n        curX = B[i / K].X[i % K] = curX + A[i] - D[i - 1];\\n    blocks = (n + K - 1) / K;\\n    for (int id = 0; id < blocks; id++) {\\n        B[id].len = min(K, n - id * K);\\n        B[id].recalc();\\n    }\\n    for (int i = 0; i < n; i++) {\\n        reverse(E[i].begin(), E[i].end());\\n    }\\n    for (int i = n - 1; i >= 0; i--) {\\n        if (!was[i])\\n            DFS(i);\\n    }\\n    printf(\\\"%d\\\\n\\\", ans);\\n}\\n\"",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 3300
  },
  {
    "contest_id": "672",
    "index": "A",
    "title": "Summer Camp",
    "statement": "Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.\n\nThis is your first year at summer camp, and you are asked to solve the following problem. All integers starting with $1$ are written in one line. The prefix of these line is \"123456789101112131415...\". Your task is to print the $n$-th digit of this string (digits are numbered starting with $1$.",
    "tutorial": "This one is a simple brute force problem, we will construct our array. Adding numbers between $1$ and $370$ will be enough. After construction we just have to print $n$-th element of array.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "672",
    "index": "B",
    "title": "Different is Good",
    "statement": "A wise man told Kerem \"Different is good\" once, so Kerem wants all things in his life to be different.\n\nKerem recently got a string $s$ consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string $s$ to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string \"aba\" has substrings \"\" (empty substring), \"a\", \"b\", \"a\", \"ab\", \"ba\", \"aba\".\n\nIf string $s$ has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.\n\nYour task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.",
    "tutorial": "We observe that in a good string all letters must be different, because all substrings in size 1 must be different. So if size of string is greater than $26$ then answer must be $- 1$ since we only have 26 different letters. Otherwise, Let's suppose we have $k$ different letters in string sized $n$, in our string $k$ elements must be stay as before, all others must be changed. So will be ($n$ - $k$).",
    "code": "\"#include<bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define pii pair<int,int>\\n#define ll long long\\n#define N (int)(1e5+10)\\n#define mod 1000000007\\n#define mp make_pair\\n#define pb push_back\\n#define nd second\\n#define st first\\n#define inf mod\\n#define endl '\\\\n'\\n#define sag (sol|1)\\n#define sol (root<<1)\\n#define ort ((bas+son)>>1)\\n#define bit(x,y) ((x>>y)&1)\\n\\nint main(){\\n\\tint H[500]={0};\\n\\tint t=0,i,n;\\n\\tchar str[N];\\n\\n\\tcin >> n;\\n\\n\\tscanf(\\\"%s\\\",str);\\n\\n\\tfor(i=0 ; i<n ; i++)\\n\\t\\tt += (H[str[i]]++) == 0;\\n\\n\\tif(n > 26)\\n\\t\\tputs(\\\"-1\\\");\\n\\telse\\n\\t\\tcout << n - t << endl;\\n}\\n\"",
    "tags": [
      "constructive algorithms",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "673",
    "index": "A",
    "title": "Bear and Game",
    "statement": "Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts $90$ minutes and there are no breaks.\n\nEach minute can be either interesting or boring. If $15$ consecutive minutes are boring then Limak immediately turns TV off.\n\nYou know that there will be $n$ interesting minutes $t_{1}, t_{2}, ..., t_{n}$. Your task is to calculate for how many minutes Limak will watch the game.",
    "tutorial": "You are supposed to implement what is described in the statement. When you read numbers $t_{i}$, check if two consecutive numbers differ by more than $15$ (i.e. $t_{i} - t_{i - 1} > 15$). If yes then you should print $t_{i - 1} + 15$. You can assume that $t_{0} = 0$ and then you don't have to care about some corner case at the beginning. Also, you can assume that $t_{n + 1} = 91$ or $t_{n + 1} = 90$ (both should work - do you see why?). If your program haven't found two consecutive numbers different by more than $15$ then print $90$. If you still have problems to solve this problem then check codes of other participants.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint t[105];\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tt[0] = 0;\n\tfor(int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &t[i]);\n\tt[n+1] = 91;\n\tfor(int i = 1; i <= n + 1; ++i) {\n\t\tif(t[i] > t[i-1] + 15) {\n\t\t\tprintf(\"%d\\n\", t[i-1] + 15);\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"90\");\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "673",
    "index": "B",
    "title": "Problems for Round",
    "statement": "There are $n$ problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are $m$ pairs of similar problems. Authors want to split problems between two division according to the following rules:\n\n- Problemset of each division should be non-empty.\n- Each problem should be used in exactly one division (yes, it is unusual requirement).\n- Each problem used in division 1 should be harder than any problem used in division 2.\n- If two problems are similar, they should be used in different divisions.\n\nYour goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.\n\nNote, that the relation of similarity \\textbf{is not} transitive. That is, if problem $i$ is similar to problem $j$ and problem $j$ is similar to problem $k$, it doesn't follow that $i$ is similar to $k$.",
    "tutorial": "Some prefix of problems must belong to one division, and the remaining suffix must belong to the other division. Thus, we can say that we should choose the place (between two numbers) where we split problems. Each pair $a_{i}, b_{i}$ (let's say that $a_{i} < b_{i}$) means that the splitting place must be between $a_{i}$ and $b_{i}$. In other words, it must be on the right from $a_{i}$ and on the left from $b_{i}$. For each pair if $a_{i} > b_{i}$ then we swap these two numbers. Now, the splitting place must be on the right from $a_{1}, a_{2}, ..., a_{m}$, so it must be on the right from $A = max(a_{1}, a_{2}, ..., a_{m})$. In linear time you can calculate $A$, and similarly calculate $B = min(b_{1}, ..., b_{m})$. Then, the answer is $B - A$. It may turn out that $A > B$ though but we don't want to print a negative answer. So, we should print $max(0, B - A)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main() {\n    int n, m;\n    scanf(\"%d%d\", &n, &m);\n    int low = 1, high = n;\n    while(m--) {\n        int a, b;\n        scanf(\"%d%d\", &a, &b);\n        if(a > b) swap(a, b);\n        low = max(low, a);\n        high = min(high, b);\n    }\n    printf(\"%d\\n\", max(0, high - low));\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "675",
    "index": "A",
    "title": "Infinite Sequence",
    "statement": "Vasya likes everything infinite. Now he is studying the properties of a sequence $s$, such that its first element is equal to $a$ ($s_{1} = a$), and the difference between any two neighbouring elements is equal to $c$ ($s_{i} - s_{i - 1} = c$). In particular, Vasya wonders if his favourite integer $b$ appears in this sequence, that is, there exists a positive integer $i$, such that $s_{i} = b$. Of course, you are the person he asks for a help.",
    "tutorial": "Firstly, in case $c = 0$ we should output YES if $a = b$ else answer is NO. If $b$ belongs to sequence $b = a + k * c$ where k is non-negative integer. So answer is YES if $(b - a) / c$ is non-negative integer else answer is NO.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int a, b, c;\n    cin >> a >> b >> c;\n \n    if (c == 0) {\n        if (a == b) cout << \"YESn\";\n        else cout << \"NOn\";\n    } else {\n        if ((b - a) % c == 0 && (b - a) / c >= 0) cout << \"YESn\";\n        else cout << \"NOn\";\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "675",
    "index": "B",
    "title": "Restoring Painting",
    "statement": "Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it.\n\n- The painting is a square $3 × 3$, each cell contains a single integer from $1$ to $n$, and different cells may contain either different or equal integers.\n- The sum of integers in each of four squares $2 × 2$ is equal to the sum of integers in the top left square $2 × 2$.\n- Four elements $a$, $b$, $c$ and $d$ are known and are located as shown on the picture below.\n\nHelp Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to $0$, meaning Vasya remembers something wrong.\n\nTwo squares are considered to be different, if there exists a cell that contains two different integers in different squares.",
    "tutorial": "x a y b m c z d w Number in the center may be any from 1 to $n$ because number in the center belongs to all subsquares $2  \\times  2$. So, let's find answer with fixed number in the center and then multiply answer by $n$. Let's iterate over all possible $x$. Sums of each subsquare $2  \\times  2$ are the same so $x + b + a + m = y + c + a + m$ and $y = x + b - c$. Similarly, $z = x + a - d$ and $w = a + y - d = z + b - c$. This square is legal if $1  \\le  y, z, w  \\le  n$. We should just check it. Also we can solve this problem in $O(1)$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n    int n, a, b, c, d;\n    cin >> n >> a >> b >> c >> d;\n\n    long long ans = 0;\n    for (int x = 1; x <= n; x++) {\n        int y = x + b - c;\n        int z = x + a - d;\n        int w = a + y - d;\n        if (1 <= y && y <= n && 1 <= z && z <= n && 1 <= w && w <= n) {\n            ans++;\n        }\n    }\n    ans *= n;\n\n    cout << ans << endl;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "675",
    "index": "C",
    "title": "Money Transfers",
    "statement": "There are $n$ banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than $1$. Also, bank $1$ and bank $n$ are neighbours if $n > 1$. No bank is a neighbour of itself.\n\nVasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.\n\nThere is only one type of operations available: transfer some amount of money from any bank to account in any \\textbf{neighbouring} bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.\n\nVasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.",
    "tutorial": "We have array $a_{i}$ and should make all numbers in it be equal to zero with minimal number of operations. Sum of all $a_{i}$ equals to zero. We can divide array into parts of consecutive elements with zero sum. If part has length $l$ we can use all pairs of neighbours in operations and make all numbers be equal to zero with $l - 1$ operations. So, if we sum number of operations in each part we get $ans = n - k$ where $k$ is number of parts. We should maximize $k$ to get the optimal answer. One of the part consists of some prefix and probably some suffix. Each of other parts is subarray of $a$. Let's calculate prefix sums. Each part has zero sum so prefix sums before each part-subarray are the same. So we can calculate $f$ - number of occurencies of the most frequent number in prefix sums and answer will be equal to $n - f$. Bonus: how to hack solutions with overflow?",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(0);\n\n    int n;\n    cin >> n;\n    map<long long, int> d;\n    long long sum = 0;\n    int ans = n - 1;\n    for (int i = 0; i < n; i++) {\n        int t;\n        cin >> t;\n        sum += t;\n        d[sum]++;\n        ans = min(ans, n - d[sum]);\n    }\n\n    cout << ans << endl;\n}\n",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "675",
    "index": "D",
    "title": "Tree Construction",
    "statement": "During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.\n\nYou are given a sequence $a$, consisting of $n$ \\textbf{distinct} integers, that is used to construct the binary search tree. Below is the formal description of the construction process.\n\n- First element $a_1$ becomes the root of the tree.\n- Elements $a_2, a_3, \\ldots, a_n$ are added one by one. To add element $a_i$ one needs to traverse the tree starting from the root and using the following rules:\n\n- The pointer to the current node is set to the root.\n- If $a_i$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node.\n- If at some point there is no required child, the new node is created, it is assigned value $a_i$ and becomes the corresponding child of the current node.",
    "tutorial": "We have binary search tree (BST) and should insert number in it with good time complexity. Let we should add number $x$. Find numbers $l < x < r$ which were added earlier, $l$ is maximal possible, $r$ is minimal possible (all will be similar if only one of this numbers exists). We can find them for example with std::set and upper_bound in C++. We should keep sorted tree traversal (it's property of BST). So $x$ must be right child of vertex with $l$ or left child of vertex with $r$. Let $l$ hasn't right child and $r$ hasn't left child. Hence lowest common ancestor (lca) of $l$ and $r$ doesn't equal to $l$ or $r$. So lca is between $l$ and $r$ in tree traversal. But it's impossible because $l$ is maximal possible and $r$ is minimal possible. So $l$ has right child or $r$ has left child and we know exactly which of them will be parent of $x$. That's all. Time complexity is $O(n\\log n)$.",
    "code": "#include <iostream>\n#include <set>\n#include <map>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(0);\n\n    set<int> numbers;\n    map<int, int> left;\n    map<int, int> right;\n\n    int n, v;\n    cin >> n >> v;\n    numbers.insert(v);\n    for (int i = 0; i < n - 1; i++) {\n        cin >> v;\n        auto it = numbers.upper_bound(v);\n        int result;\n        if (it != numbers.end() && left.count(*it) == 0) {\n            left[*it] = v;\n            result = *it;\n        } else {\n            it--;\n            right[*it] = v;\n            result = *it;\n        }\n        numbers.insert(v);\n        cout << result;\n        if (i == n - 2) cout << 'n';\n        else cout << ' ';\n    }\n}\n",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "675",
    "index": "E",
    "title": "Trains and Statistic",
    "statement": "Vasya commutes by train every day. There are $n$ train stations in the city, and at the $i$-th station it's possible to buy only tickets to stations from $i + 1$ to $a_{i}$ inclusive. No tickets are sold at the last station.\n\nLet $ρ_{i, j}$ be the minimum number of tickets one needs to buy in order to get from stations $i$ to station $j$. As Vasya is fond of different useless statistic he asks you to compute the sum of all values $ρ_{i, j}$ among all pairs $1 ≤ i < j ≤ n$.",
    "tutorial": "Let the indexation will be from zero. So we should subtract one from all $a_{i}$. Also let $a_{n - 1} = n - 1$. $dp_{i}$ is sum of shortests pathes from $i$ to $i + 1... n - 1$. $dp_{n - 1} = 0$ $dp_{i} = dp_{m} - (a_{i} - m) + n - i - 1$ where $m$ belongs to range from $i + 1$ to $a_{i}$ and $a_{m}$ is maximal. We can find $m$ with segment tree or binary indexed tree or sparse table. Now answer equals to sum of all $dp_{i}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 1 << 18;\npair<int, int> tree[maxn * 2];\n\nvoid build(const vector<int> &a, int n) {\n    for (int i = 0; i < n; i++) tree[maxn + i] = {a[i], i};\n    for (int i = maxn - 1; i > 0; i--)\n        tree[i] = max(tree[i * 2], tree[i * 2 + 1]);\n}\n\nint get(int l, int r) {\n    pair<int, int> ans{-1, -1};\n    for (l += maxn, r += maxn + 1; l < r; l >>= 1, r >>= 1) {\n        if (l & 1) ans = max(ans, tree[l++]);\n        if (r & 1) ans = max(ans, tree[--r]);\n    }\n    return ans.second;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(0);\n\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    a[n - 1] = n - 1;\n    for (int i = 0; i < n - 1; i++) {\n        cin >> a[i];\n        a[i]--;\n    }\n\n    build(a, n);\n    vector<long long> dp(n);\n    long long ans = 0;\n    dp[n - 1] = 0;\n    for (int i = n - 2; i >= 0; i--) {\n        int m = get(i + 1, a[i]);\n        dp[i] = dp[m] - (a[i] - m) + n - i - 1;\n        ans += dp[i];\n    }\n\n    cout << ans << 'n';\n}\n",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "676",
    "index": "A",
    "title": "Nicholas and Permutation",
    "statement": "Nicholas has an array $a$ that contains $n$ \\textbf{distinct} integers from $1$ to $n$. In other words, Nicholas has a permutation of size $n$.\n\nNicholas want the minimum element (integer $1$) and the maximum element (integer $n$) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance between the minimum and the maximum elements. The distance between two elements is considered to be equal to the absolute difference between their positions.",
    "tutorial": "All what you need to solve this problem - find the positions of numbers $1$ and $n$ in the given array. Let's this positions equal to $p_{1}$ and $p_{n}$, then the answer is the maximum of 4 values: $abs(n - p_{1}),  abs(n - p_{n}),  abs(1 - p_{1}),  abs(1 - p_{n}).$ Asymptotic behavior $O(n)$.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "676",
    "index": "B",
    "title": "Pyramid of Glasses",
    "statement": "Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is $n$. The top level consists of only $1$ glass, that stands on $2$ glasses on the second level (counting from the top), then $3$ glasses on the third level and so on.The bottom level consists of $n$ glasses.\n\nVlad has seen in the movies many times how the champagne beautifully flows from top levels to bottom ones, filling all the glasses simultaneously. So he took a bottle and started to pour it in the glass located at the top of the pyramid.\n\nEach second, Vlad pours to the top glass the amount of champagne equal to the size of exactly one glass. If the glass is already full, but there is some champagne flowing in it, then it pours over the edge of the glass and is equally distributed over two glasses standing under. If the overflowed glass is at the bottom level, then the champagne pours on the table. For the purpose of this problem we consider that champagne is distributed among pyramid glasses immediately. Vlad is interested in the number of completely full glasses if he stops pouring champagne in $t$ seconds.\n\nPictures below illustrate the pyramid consisting of three levels.",
    "tutorial": "The restrictions in this problem allow to simulate the process. Let the volume of one wineglass equals to $2^{n}$ conventional units. So the volume of the champagne surpluses which will stream to bottom level will always integer number. So let's pour in the top wineglass $q * 2^{n}$ units of champagne, and then we have following case: if in the current wineglass is more champagne than its volume, let's make $surplus = V_{tek} - 2^{n}$, and add $surplus / 2$ of champagne in each of the two bottom wineglasses. Asymptotic behavior $O(n^{2})$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "676",
    "index": "C",
    "title": "Vasya and String",
    "statement": "High school student Vasya got a string of length $n$ as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a \\textbf{substring} (consecutive subsequence) consisting of equal letters.\n\nVasya can change no more than $k$ characters of the original string. What is the maximum beauty of the string he can achieve?",
    "tutorial": "This problem can be solved with help of two pointers. Let the first pointer is $l$ and the second pointer is $r$. Then for every position $l$ we will move right end $r$ until on the substring $s_{l}s_{l + 1}... s_{r}$ it is possible to make no more than $k$ swaps to make this substring beautiful. Then we need to update the answer with length of this substring and move $l$ to the right. $$ Asymptotic behavior $O(n * alphabet)$.",
    "tags": [
      "binary search",
      "dp",
      "strings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "676",
    "index": "D",
    "title": "Theseus and labyrinth",
    "statement": "Theseus has just arrived to Crete to fight Minotaur. He found a labyrinth that has a form of a rectangular field of size $n × m$ and consists of blocks of size $1 × 1$.\n\n\\textbf{Each} block of the labyrinth has a button that rotates \\textbf{all} blocks $90$ degrees clockwise. Each block rotates around its center and doesn't change its position in the labyrinth. Also, each block has some number of doors (possibly none). In one minute, Theseus can either push the button in order to rotate all the blocks $90$ degrees clockwise or pass to the neighbouring block. Theseus can go from block $A$ to some neighbouring block $B$ only if block $A$ has a door that leads to block $B$ and block $B$ has a door that leads to block $A$.\n\nTheseus found an entrance to labyrinth and is now located in block $(x_{T}, y_{T})$ — the block in the row $x_{T}$ and column $y_{T}$. Theseus know that the Minotaur is hiding in block $(x_{M}, y_{M})$ and wants to know the minimum number of minutes required to get there.\n\nTheseus is a hero, not a programmer, so he asks you to help him.",
    "tutorial": "It is easy to understand that we have only 4 states of the maze. How to solve this problem if there is no any buttons? It is just bfs on the maze (on the graph). Because of buttons we need to add to graph 3 additional levels and add edges between this levels. After that we need to run bfs on this graph and find the length of the minimum path if such exists. Asymptotic behavior $O(n * m)$.",
    "tags": [
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "676",
    "index": "E",
    "title": "The Last Fight Between Human and AI",
    "statement": "100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.\n\nThe following game was chosen for the fights: initially there is a polynomial\n\n\\[\nP(x) = a_{n}x^{n} + a_{n - 1}x^{n - 1} + ... + a_{1}x + a_{0},\n\\]\n\nwith yet undefined coefficients and the integer $k$. Players alternate their turns. At each turn, a player pick some index $j$, such that coefficient $a_{j}$ that stay near $x^{j}$ is not determined yet and sets it to \\textbf{any} value (integer or real, positive or negative, $0$ is also allowed). Computer moves first. The human will be declared the winner if and only if the resulting polynomial will be divisible by $Q(x) = x - k$.Polynomial $P(x)$ is said to be divisible by polynomial $Q(x)$ if there exists a representation $P(x) = B(x)Q(x)$, where $B(x)$ is also some polynomial.\n\nSome moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally?",
    "tutorial": "In this problem we have two main cases: $k = 0,  k  \\neq  0$. Case when $k = 0$. Then the division of the polynomial to the $x - k$ depends only of the value of $a_{0}$. If $a_{0}$ is already known then we need to compare it with zero. If $a_{0} = 0$ then the human wins, otherwise the human loses. If $a_{i}$ is not known then win who make the move. Case when $k  \\neq  0$. Here we have two cases: all coefficients already known. Then we need to check $x = k$ - is it the root of the given polynomial. Otherwise who will make the last move will win. Let we know all coefficient except one. Let this coefficient is the coefficient before $x^{i}$. Let $C_{1}$ is the sum for all $j  \\neq  i$ $a_{j}k^{ j}$ and $C_{2} = k^{ i}  \\neq  0$. Then we have the equation $a_{i} * C_{2} = - C_{1}$ which always have the solution. If the human will make the last move he need to write the root to the place of the coefficient, otherwise computer will write any number, but not the root. Asymptotic behavior $O(n)$.",
    "tags": [
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "677",
    "index": "A",
    "title": "Vanya and Fence",
    "statement": "Vanya and his friends are walking along the fence of height $h$ and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed $h$. If the height of some person is greater than $h$ he can bend down and then he surely won't be noticed by the guard. The height of the $i$-th person is equal to $a_{i}$.\n\nConsider the width of the person walking as usual to be equal to $1$, while the width of the bent person is equal to $2$. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?",
    "tutorial": "For each friend we can check, if his height is more than $h$. If it is, then his width is $2$, else $1$. Complexity $O(n)$.",
    "code": "#include <iostream>\nusing namespace std;\ntypedef long long ll;\nll i,n,h,ans,x;\nint main()\n{\n\tcin >> n >> h;\n\tans = n;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tcin >> x;\n\t\tans += (x>h);\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "677",
    "index": "B",
    "title": "Vanya and Food Processor",
    "statement": "Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed $h$ and the processor smashes $k$ centimeters of potato each second. If there are less than $k$ centimeters remaining, than during this second processor smashes all the remaining potato.\n\nVanya has $n$ pieces of potato, the height of the $i$-th piece is equal to $a_{i}$. He puts them in the food processor one by one starting from the piece number $1$ and finishing with piece number $n$. Formally, each second the following happens:\n\n- If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.\n- Processor smashes $k$ centimeters of potato (or just everything that is inside).\n\nProvided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.",
    "tutorial": "The solution, that does same thing, as in the problem statement will fail with TL, because if the height of each piece of potato will be $10^{9}$ and smashing speed will be $1$, then for each piece we will do $10^{9}$ operations. With each new piece of potato $a_{i}$ we will smash the potato till $a[i]$ $MOD$ $k$, so we will waste $a[i] / k$ seconds on it. If we can not put this piece of potato after that, we will waste $1$ more second to smash everything, that inside, else just put this piece. We will get an answer same as we could get with actions from the statement. Complexity $O(n)$.",
    "code": "#include <iostream>\n#include <stdio.h>\nusing namespace std;\ntypedef long long ll;\nll i,n,h,ans,x,cur_h,k;\nint main()\n{\n\tcin >> n >> h >> k;\n\tans = 0;\n\tcur_h = 0;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tscanf(\"%I64d\", &x);\n\t\tif (cur_h + x <= h)\n\t\t   cur_h += x;\n\t\telse\n\t\t\tans++, cur_h = x;\n\t\tans += cur_h/k;\n\t\tcur_h %= k;\n\t}\n\tans += cur_h/k;\n\tcur_h %= k;\n\tans += (cur_h>0);\n\tcout << ans << endl;\n\treturn 0;\n}\n",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "677",
    "index": "C",
    "title": "Vanya and Label",
    "statement": "While walking down the street Vanya saw a label \"Hide&Seek\". Because he is a programmer, he used $&$ as a bitwise AND for these two words represented as a integers in base $64$ and got new word. Now Vanya thinks of some string $s$ and wants to know the number of pairs of words of length $|s|$ (length of $s$), such that their bitwise AND is equal to $s$. As this number can be large, output it modulo $10^{9} + 7$.\n\nTo represent the string as a number in numeral system with base $64$ Vanya uses the following rules:\n\n- digits from '0' to '9' correspond to integers from $0$ to $9$;\n- letters from 'A' to 'Z' correspond to integers from $10$ to $35$;\n- letters from 'a' to 'z' correspond to integers from $36$ to $61$;\n- letter '-' correspond to integer $62$;\n- letter '_' correspond to integer $63$.",
    "tutorial": "We can transform our word in binary notation, we can do it easily, because $64 = 2^{6}$. Move through the bits of this number: if bit is equal to $0$, then we can have 3 different optinos of this bit in our pair of words: 0&1, 1&0, 0&0, else we can have only one option: 1&1. So the result will be $3^{nullbits}$, where $nullbits$ - is amount of zero bits. Complexity $O(|s|)$.",
    "code": "#include <iostream>\n#include <stdio.h>\n#include <string>\n#define MOD 1000000007\nusing namespace std;\ntypedef long long ll;\nll i,j,n,h,ans,x,cur_h,k;\nstring s;\nstring pattern;\nll symbol_val[305];\nint main()\n{\n\tcin >> s;\n\tfor (char i = '0'; i <= '9'; i++)\n\t\tpattern.push_back(i);\n\tfor (char i = 'A'; i <= 'Z'; i++)\n\t\tpattern.push_back(i);\n\tfor (char i = 'a'; i <= 'z'; i++)\n\t\tpattern.push_back(i);\n\tpattern.push_back('-');\n\tpattern.push_back('_');\n\tfor (i = 0; i < 64; i++)\n\t\tsymbol_val[pattern[i]] = i;\n\tll ans = 1;\n\tfor (i = 0; i < s.size(); i++)\n\t{\n\t\tll x = symbol_val[s[i]];\n\t\tfor (j = 0; j < 6; j++)\n\t\t\tif ((x&(1<<j)) == 0)\n\t\t\t   ans = (ans*3)%MOD;\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "combinatorics",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "677",
    "index": "D",
    "title": "Vanya and Treasure",
    "statement": "Vanya is in the palace that can be represented as a grid $n × m$. Each room contains a single chest, an the room located in the $i$-th row and $j$-th columns contains the chest of type $a_{ij}$. Each chest of type $x ≤ p - 1$ contains a key that can open any chest of type $x + 1$, and all chests of type $1$ are not locked. There is exactly one chest of type $p$ and it contains a treasure.\n\nVanya starts in cell $(1, 1)$ (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell $(r_{1}, c_{1})$ (the cell in the row $r_{1}$ and column $c_{1}$) and $(r_{2}, c_{2})$ is equal to $|r_{1} - r_{2}| + |c_{1} - c_{2}|$.",
    "tutorial": "We can make dynamic programming $dp[col][row]$, where $dp[col][row]$ is minimal time, that we have waste to open the chest in the cell $(col, row)$. For the cells of color $1$: $dp[x][y] = x + y$. For each next color $color$ we can look over all cells of color $color - 1$ and all cells of color $color$, then for each cell of color $color$ with coordinates $(x1, y1)$ and for each cell with color $color - 1$ and coordinates $(x2, y2)$ $dp[x1][y1] = dp[x2][y2] + abs(x1 - x2) + abs(y1 - y2)$. But complexity of this solution is $O(n^{2} \\cdot m^{2})$, what is not enough. We can do such improvement: let $cnt[x]$ be the amount of cells of color $x$, then when $cnt[color] \\cdot cnt[color - 1]  \\ge  n \\cdot m$, we can do bfs from cells of color $color - 1$ to cells of color $color$. Then we will have complexity $O(n \\cdot m \\cdot sqrt(n \\cdot m))$. Proof There also exists solution with 2D segment tree:",
    "code": "#include <iostream>\n#include <stdio.h>\n#include <string>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#define MOD 1000000007\n#define N 512\n#define mp make_pair\n#define X first\n#define Y second\nusing namespace std;\ntypedef int ll;\nll i,j,n,h,x,y,glob,k,m,p,fx,fy;\nll a[505][505], dp[505][505], d[505][505], t[4][2005][2005];\nll dir[4][2] = {{-1,0},{1,0},{0,1},{0,-1}};\nvector<pair<ll,ll> > g[250505];\nvector<pair<ll, pair<ll,ll> > > lst, bfs;\nll Abs(ll x)\n{\n\treturn x>0?x:-x;\n}\nll find_dist(ll x1, ll y1, ll x2, ll y2)\n{\n\treturn Abs(x1-x2) + Abs(y1-y2);\n}\nbool in_range(ll x, ll y)\n{\n\treturn (x >= 0 && x < y);\n}\n\nint get (int lx, int rx, int ly, int ry) {\n\trx++;\n\try++;\n\tint res = MOD;\n\tll l = ly, r = ry;\n  for (lx += N, rx += N; lx < rx; lx >>= 1, rx >>= 1) {\n  \tif (rx&1)\n  \t{\n  \t\tly = l; ry = r;\n\t    rx--;\n\t    for (ly += N, ry += N; ly < ry; ly >>= 1, ry >>= 1) {\n\n\t\t    if (ly&1)\n\t\t    {\n\t\t       res = min(res, t[glob][rx][ly]);\n\t\t       ly++;\n\t\t    }\n\t\t\tif (ry&1)\n\t\t\t{\n\t\t\t    --ry;\n\t\t\t    res = min(res, t[glob][rx][ry]);\n\t\t\t}\n\t\t}\n\t}\n    if (lx&1)\n    {\n    \tly = l; ry = r;\n\t\tfor (ly += N, ry += N; ly < ry; ly >>= 1, ry >>= 1) {\n\n\t\t    if (ly&1)\n\t\t    {\n\t\t       res = min(res, t[glob][lx][ly]);\n\t\t       ly++;\n\t\t    }\n\t\t\tif (ry&1)\n\t\t\t{\n\t\t\t    --ry;\n\t\t\t    res = min(res, t[glob][lx][ry]);\n\t\t\t}\n\t\t}\n\t    lx++;\n    }\n  }\n  return res;\n}\n\nvoid update (int x, int y, int val) {\n\tll tmp = y;\n\tt[glob][x+N][tmp+N] = val;\n\tfor (x += N; x > 1; x >>= 1)\n\t{\n\t\ty = tmp;\n\t\tfor (y += N; y > 1; y >>= 1)\n\t\t{\n\t\t\tt[glob][x][y>>1] = min(t[glob][x][y], t[glob][x][y^1]);\n\t\t\tt[glob][x>>1][y] = min(t[glob][x][y], t[glob][x^1][y]);\n\t\t}\n\t\tt[glob][x>>1][y] = min(t[glob][x][y], t[glob][x^1][y]);\n\t}\n}\n\n\nint main()\n{\n\t//freopen(\"input.txt\",\"r\",stdin);\n\t//freopen(\"output.txt\",\"w\",stdout);\n\tcin >> n >> m >> p;\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = 0; j < m; j++)\n\t\t\tdp[i][j] = MOD;\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = 0; j < m; j++)\n\t\t{\n\t\t\tscanf(\"%d\", &a[i][j]);\n\t\t\tg[a[i][j]].push_back(mp(i,j));\n\t\t\tif (a[i][j] == 1)\n\t\t\t   dp[i][j] = i+j;\n\t\t\tif (a[i][j] == p)\n\t\t\t   fx = i, fy = j;\n\t\t}\n\tfor (i = 0; i <= N*2; i++)\n\t\tfor (j = 0; j <= N*2; j++)\n\t\t\tfor (k = 0; k < 4; k++)\n\t\t\t\tt[k][i][j] = MOD;\n\t//UR - dp[x2][y2] = dp[x1][y1] + x2-x1+y2-y1 = dp[x1][y1]-x1-y1+(x2+y2)\n\t//UL - dp[x2][y2] = dp[x1][y1] + x2-x1+y1-y2 = dp[x1][y1]-x1+y1+(x2-y2)\n\t//DR - dp[x2][y2] = dp[x1][y1] + x1-x2+y2-y1 = dp[x1][y1]-y1+x1+(y2-x1)\n\t//DL - dp[x2][y2] = dp[x1][y1] + x1-x2+y1-y2 = dp[x1][y1]+x1+y1+(-x2-y2)\n\tfor (i = 2; i <= p; i++)\n\t{\n\t\tll last_sz = g[i-1].size();\n\t\tfor (j = 0; j < last_sz; j++)\n\t\t{\n\t\t\tll x = g[i-1][j].X;\n\t\t\tll y = g[i-1][j].Y;\n\t\t\tglob = 0;\n\t\t\t//cout << x << \" \" << y << \" \" << get( 0, x, 0, y) << \"g\" << endl;\n\t\t\tupdate(x,y,dp[x][y]-x-y);\n\t\t\t//cout << get( 0, x, 0, y) << \"f\" << endl;\n\t\t\tglob = 1;\n\t\t\tupdate(x,y,dp[x][y]-x+y);\n\t\t\tglob = 2;\n\t\t\tupdate(x,y,dp[x][y]+x-y);\n\t\t\tglob = 3;\n\t\t\tupdate(x,y,dp[x][y]+x+y);\n\t\t}\n\t\tll cur_sz = g[i].size();\n\t\tfor (j = 0; j < cur_sz; j++)\n\t\t{\n\t\t\tll x = g[i][j].X;\n\t\t\tll y = g[i][j].Y;\n\t\t\tglob = 0;\n\t\t\t//cout << get( 0, x, 0, y) << endl;\n\t\t\tdp[x][y] = min(dp[x][y], get( 0, x, 0, y)+x+y);\n\t\t\tglob = 1;\n\t\t\tdp[x][y] = min(dp[x][y], get(0, x, y, m-1)+x-y);\n\t\t\tglob = 2;\n\t\t\tdp[x][y] = min(dp[x][y], get(x, n-1, 0, y)-x+y);\n\t\t\tglob = 3;\n\t\t\tdp[x][y] = min(dp[x][y], get(x, n-1, y, m-1)-x-y);\n\t\t}\n\t\tfor (j = 0; j < last_sz; j++)\n\t\t{\n\t\t\tll x = g[i-1][j].X;\n\t\t\tll y = g[i-1][j].Y;\n\t\t\tglob = 0;\n\t\t\tupdate(x,y,MOD);\n\t\t\tglob = 1;\n\t\t\tupdate(x,y,MOD);\n\t\t\tglob = 2;\n\t\t\tupdate(x,y,MOD);\n\t\t\tglob = 3;\n\t\t\tupdate(x,y,MOD);\n\t\t}\n\t}\n\t/*for (i = 0; i < n; i++)\n\t{\n\t\tfor (j = 0; j < m; j++)\n\t\t\tcout << dp[i][j] << \" \";\n\t\tcout << endl;\n\t}*/\n\tcout << dp[fx][fy] << endl;\n\treturn 0;\n}\n",
    "tags": [
      "data structures",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "677",
    "index": "E",
    "title": "Vanya and Balloons",
    "statement": "Vanya plays a game of balloons on the field of size $n × n$, where each cell contains a balloon with one of the values $0$, $1$, $2$ or $3$. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:\n\n\\begin{verbatim}\n**o**\n**o**\nooooo\n**o**\n**o**\n\\end{verbatim}\n\nor\n\n\\begin{verbatim}\no***o\n*o*o*\n**o**\n*o*o*\no***o\n\\end{verbatim}\n\nFormally, the cross is given by three integers $r$, $c$ and $d$, such that $d ≤ r, c ≤ n - d + 1$. The normal cross consists of balloons located in cells $(x, y)$ (where $x$ stay for the number of the row and $y$ for the number of the column), such that $|x - r|·|y - c| = 0$ and $|x - r| + |y - c| < d$. Rotated cross consists of balloons located in cells $(x, y)$, such that $|x - r| = |y - c|$ and $|x - r| < d$.\n\nVanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo $10^{9} + 7$.",
    "tutorial": "For each cell $(x, y)$ take the maximum possible cross with center in this cell, that doesn't contains zeros. To do it fast, we can make arrays of partial sums for all possible $8$ directions, in which each cell will contain the number of non-zero balloons in each direction. For example, if we want to know, how many non-zero balloons are right to cell $(x, y)$, we can create an array $p[x][y]$, where $p[x][y] = p[x][y - 1] + 1$ if $a[x][y]! = 0$ else $p[x][y] = 0$ So now we can for each cell $(x, y)$ we can find the maximum size of cross with the centre in this cell, that will not contain zeros. We can compare product for crosses with centers in the cells $(x, y)$ and radius $r$ using logarythms. For example, if we need to compare 2 crosses with values $x_{1} \\cdot x_{2} \\cdot ... \\cdot x_{n}$ and $y_{1} \\cdot y_{2} \\cdot ... \\cdot y_{m}$, we can compare $log(x_{1} \\cdot x_{2} \\cdot ... \\cdot x_{n})$ and $log(y_{1} \\cdot y_{2} \\cdot ... \\cdot y_{n})$, what will be equivalent to comparing $log(x_{1}) + log(x_{2}) + ... + log(x_{n})$ and $log(y_{1}) + log(y_{2}) + ... + log(y_{m})$. We can also use partial sum arrays to find value $log(x_{1}) + log(x_{2}) + ... + log(x_{n})$ for each cross, so we can find the product of the values in each cross for $O(1)$ time. Complexity $O(n^{2})$.",
    "code": "#include <iostream>\n#include <stdio.h>\n#include <string>\n#include <cmath>\n#define MOD 1000000007\n#define N 2005\nusing namespace std;\ntypedef unsigned int ll;\nll i,j,n,h,x,y,cur_h,k,dir;\nll pre[8][N][N];\ndouble sums[8][N][N],ans,logs[N][N],lg2,lg3;\nll ansx,ansy,anssize,ansdir;\nll total;\nll directions[8][2] = {{-1,-1},{-1,1},{1,-1},{1,1},{1,0},{0,1},{-1,0},{0,-1}};\nchar a[N][N];\nbool in_range(ll x)\n{\n\treturn (x >= 0 && x < n);\n}\nint main()\n{\n\t//freopen(\"input.txt\",\"r\",stdin);\n\t//freopen(\"output.txt\",\"w\",stdout);\n\tlg2 = log(2);\n\tlg3 = log(3);\n\tcin >> n;\n\tfor (i = 0; i < n; i++)\n\t\tscanf(\"%s\",a[i]);\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = 0; j < n; j++)\n\t\t\tif (a[i][j] == '3')\n\t\t\t   logs[i][j] = lg3;\n\t\t\telse if (a[i][j] == '2')\n\t\t \t\t logs[i][j] = lg2;\n\tfor (dir = 0; dir < 8; dir++)\n\t{\n\t\tfor (i = 0; i < n; i++)\n\t\t\tfor (j = 0; j < n; j++)\n\t\t\t\tif (!in_range(i-directions[dir][0]) || !in_range(j-directions[dir][1]))\n\t\t\t\t{\n\t\t\t\t\tk = 0;\n\t\t\t\t\tll d1 = directions[dir][0], d2 = directions[dir][1];\n\t\t\t\t\tfor (x = i, y = j; in_range(x) && in_range(y); x += d1, y += d2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (a[x][y] != '0')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t   k++;\n\t\t\t\t\t\t   if (x == i && y == j)\n\t\t\t\t\t\t\t  sums[dir][x][y] = logs[i][j];\n\t\t\t\t\t\t   else\n\t\t\t\t\t\t\t   sums[dir][x][y] = sums[dir][x-d1][y-d2] + logs[x][y];\n\t\t\t   \t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsums[dir][x][y] = 0;\n\t\t\t\t\t\t\tk = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpre[dir][x][y] = k;\n\t\t\t\t\t}\n\t\t\t\t}\n\t}\n\tans = -1;\n\tfor (i = 0; i < n; i++)\n\t\tfor (j = 0; j < n; j++)\n\t\tif (a[i][j] != '0')\n\t\t{\n\t\t\tll tmp = n+5;\n\t\t\tfor (k = 0; k < 4; k++)\n\t\t\t\ttmp = min(tmp, pre[k][i][j]);\n\t\t\tdouble val = logs[i][j];\n\t\t\tfor (k = 0; k < 4; k++)\n\t\t\t\tval += sums[k][i+directions[k][0]*(tmp-1)][j+directions[k][1]*(tmp-1)] - sums[k][i][j];\n\t\t\tif (val > ans)\n\t\t\t{\n\t\t\t\tans = val;\n\t\t\t\tansx = i;\n\t\t\t\tansy = j;\n\t\t\t\tanssize = tmp;\n\t\t\t\tansdir = 0;\n\t\t\t}\n\t\t\t\n\t\t\ttmp = n+5;\n\t\t\tfor (k = 4; k < 8; k++)\n\t\t\t\ttmp = min(tmp, pre[k][i][j]);\n\t\t\tval = logs[i][j];\n\t\t\tfor (k = 4; k < 8; k++)\n\t\t\t\tval += sums[k][i+directions[k][0]*(tmp-1)][j+directions[k][1]*(tmp-1)] - sums[k][i][j];\n\t\t\tif (val > ans)\n\t\t\t{\n\t\t\t\tans = val;\n\t\t\t\tansx = i;\n\t\t\t\tansy = j;\n\t\t\t\tanssize = tmp;\n\t\t\t\tansdir = 4;\n\t\t\t}\n\t\t}\n\ttotal = a[ansx][ansy]-'0';\n\tfor (k = ansdir; k < ansdir+4; k++)\n\t{\n\t\tfor (i = 1; i < anssize; i++)\n\t\t\ttotal = (total*(a[ansx+directions[k][0]*i][ansy+directions[k][1]*i]-'0'))%MOD;\n\t}\n\tcout << total << endl;\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "678",
    "index": "A",
    "title": "Johny Likes Numbers",
    "statement": "Johny likes numbers $n$ and $k$ very much. Now Johny wants to find the smallest integer $x$ greater than $n$, so it is divisible by the number $k$.",
    "tutorial": "We should find minimal $x$, so $x \\cdot k > n$. Easy to see that $x=\\lfloor{\\frac{n}{k}}\\rfloor+1$. To learn more about floor/ceil functions I reccomend the book of authors Graham, Knuth, Patashnik \"Concrete Mathematics\". There is a chapter there about that functions and their properties. Complexity: $O(1)$.",
    "code": "li n, k;\n\nbool read() {\n\treturn !!(cin >> n >> k);\n}\n\nvoid solve() {\n\tcout << (n / k + 1) * k << endl;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "678",
    "index": "B",
    "title": "The Same Calendar",
    "statement": "The girl Taylor has a beautiful calendar for the year $y$. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.\n\nThe calendar is so beautiful that she wants to know what is the next year after $y$ when the calendar will be exactly the same. Help Taylor to find that year.\n\nNote that leap years has $366$ days. The year is leap if it is divisible by $400$ or it is divisible by $4$, but not by $100$ (https://en.wikipedia.org/wiki/Leap_year).",
    "tutorial": "Two calendars are same if and only if they have the same number of days and starts with the same day of a week. So we should simply iterate over years and maintain the day of a week of January, 1st (for example). Easy to see that the day of a week increases by one each year except of the leap years, when it increases by two. Complexity: $O(1)$ - easy to see that we will not iterate more than some small fixed constant times.",
    "code": "int y;\n\nbool read() {\n\treturn !!(cin >> y);\n}\n\nbool leap(int y) {\n\treturn y % 400 == 0 || (y % 4 == 0 && y % 100 != 0);\n}\n\nvoid solve() {\n\tbool is_leap = leap(y);\n\tint d = 0;\n\tdo {\n\t\td++;\n\t\tif (leap(y)) d++;\n\t\ty++;\n\t\td %= 7;\n\t} while (d || leap(y) != is_leap);\n\tcout << y << endl;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "678",
    "index": "C",
    "title": "Joty and Chocolate",
    "statement": "Little Joty has got a task to do. She has a line of $n$ tiles indexed from $1$ to $n$. She has to paint them in a strange pattern.\n\nAn unpainted tile should be painted Red if it's index is divisible by $a$ and an unpainted tile should be painted Blue if it's index is divisible by $b$. So the tile with the number divisible by $a$ and $b$ can be either painted Red or Blue.\n\nAfter her painting is done, she will get $p$ chocolates for each tile that is painted Red and $q$ chocolates for each tile that is painted Blue.\n\nNote that she can paint tiles in any order she wants.\n\nGiven the required information, find the maximum number of chocolates Joty can get.",
    "tutorial": "Easy to see that we can paint with both colours only tiles with the numbers multiple of $lcm(a, b)$. Obviously that tiles should be painted with more expensive colour. So the answer equals to $\\bar{\\cal J}\\left|\\frac{\\bar{\\eta}}{\\bar{u}}\\right|\\downarrow\\left(\\left|\\frac{\\bar{\\eta}}{b}\\right|=\\bar{\\cal H}\\langle\\bar{\\eta}|\\bar{\\eta}|\\langle\\bar{\\cal J},\\langle\\psi\\rangle\\right|\\left|\\frac{\\bar{\\eta}}{|q\\bar{\\eta}|\\bar{\\theta}\\cdot\\bar{\\theta}|}\\right|$. Complexity: $O(log(max(a, b)))$.",
    "code": "li n, a, b, p, q;\n\nbool read() {\n\treturn !!(cin >> n >> a >> b >> p >> q);\n}\n\nli gcd(li a, li b) { return !a ? b : gcd(b % a, a); }\nli lcm(li a, li b) { return a / gcd(a, b) * b; }\n\nvoid solve() {\n\tli ans = 0;\n\tans += (n / a) * p;\n\tans += (n / b) * q;\n\tans -= (n / lcm(a, b)) * min(p, q);\n\tcout << ans << endl;\n}",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "678",
    "index": "D",
    "title": "Iterated Linear Function",
    "statement": "Consider a linear function $f(x) = Ax + B$. Let's define $g^{(0)}(x) = x$ and $g^{(n)}(x) = f(g^{(n - 1)}(x))$ for $n > 0$. For the given integer values $A$, $B$, $n$ and $x$ find the value of $g^{(n)}(x)$ modulo $10^{9} + 7$.",
    "tutorial": "The problem can be solved using closed formula: it's need to calculate the sum of geometric progression. The formula can be calculated using binary exponentiation. I'll describe more complicated solution, but it's more general. If we have a set of variables and at each step all variables are recalculating from each other using linear function, we can use binary matrix exponentiation. There is only one variable $x$ in our problem. The new variable $x'$ is calculating using formula $A \\cdot x + B$. Consider the matrix $z = [[A, B], [0, 1]]$ and the vector $v = [0, 1]$. Let's multiply $z$ and $v$. Easy to see that we will get the vector $v' = [x', 1]$. So to make $n$ iterations we should multiply $z$ and $v$ $n$ times. We can do that using binary matrix exponentiation, because matrix multiplication is associative. As an exercise try to write down the matrix for the Fibonacci numbers and calculate the $n$-th Fibonacci number in $O(logn)$ time. The matrix and the vector is under the spoiler. z=[[0, 1], [1, 1]], v=[0, 1]. Complexity: $O(logn)$.",
    "code": "int A, B, x;\nli n;\n\nbool read() {\n\treturn !!(cin >> A >> B >> n >> x);\n}\n\nconst int mod = 1000 * 1000 * 1000 + 7;\n\ninline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }\ninline int mul(int a, int b) { return int(a * 1ll * b % mod); }\ninline void inc(int& a, int b) { a = add(a, b); }\n\nvoid mul(int a[2][2], int b[2][2]) {\n\tstatic int res[2][2];\n\tforn(i, 2)\n\t\tforn(j, 2) {\n\t\t\tres[i][j] = 0;\n\t\t\tforn(k, 2) inc(res[i][j], mul(a[i][k], b[k][j]));\n\t\t}\n\tforn(i, 2) forn(j, 2) a[i][j] = res[i][j];\n}\n\nvoid bin_pow(int a[2][2], li b) {\n\tstatic int res[2][2];\n\tforn(i, 2) forn(j, 2) res[i][j] = i == j;\n\n\twhile (b) {\n\t\tif (b & 1) mul(res, a);\n\t\tmul(a, a);\n\t\tb >>= 1;\n\t}\n\n\tforn(i, 2) forn(j, 2) a[i][j] = res[i][j];\n}\n\nvoid solve() {\n\tint z[2][2] = {\n\t\t{ A, B },\n\t\t{ 0, 1 }\n\t};\n\tbin_pow(z, n);\n\tint result = add(mul(z[0][0], x), z[0][1]);\n\tcout << result << endl;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "678",
    "index": "E",
    "title": "Another Sith Tournament",
    "statement": "The rules of Sith Tournament are well known to everyone. $n$ Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.\n\nJedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.",
    "tutorial": "Let's solve the problem using dynamic programming. $z_{mask, i}$ - the maximal probability of Ivans victory if the siths from the $mask$ already fought and the $i$-th sith left alive. To calculate that DP we should iterate over the next sith (he will fight against the $i$-th sith): $z_{m a s k,i}=m a x_{j=1,j\\not\\in m a s k}^{n}(z_{m a s k\\cup j,i}\\cdot p_{i j}+z_{m a s k\\cup j,j}\\cdot p_{j i})$. Time complexity: $O(2^{n}n^{2})$. Memory complexity: $O(2^{n}n)$.",
    "code": "const int N = 20, EXPN = (1 << 18) + 3;\n\nint n;\nld p[N][N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) forn(j, n) assert(cin >> p[i][j]);\n\treturn true;\n}\n\nld z[EXPN][N];\n\nld solve(int mask, int i) {\n\tld& ans = z[mask][i];\n\tif (ans > -0.5) return ans;\n\tif (mask == (1 << n) - 1) return ans = !i;\n\tans = 0;\n\tforn(j, n)\n\t\tif (!(mask & (1 << j))) {\n\t\t\tld cur = 0;\n\t\t\tcur += solve(mask | (1 << j), i) * p[i][j];\n\t\t\tcur += solve(mask | (1 << j), j) * p[j][i];\n\t\t\tans = max(ans, cur);\n\t\t}\n\treturn ans;\n}\n\nvoid solve() {\n\tif (n == 1) {\n\t\tputs(\"1\");\n\t\treturn;\n\t}\n\n\tforn(i, 1 << n) forn(j, n) z[i][j] = -1;\n\n\tld ans = 0;\n\tforn(i, n)\n\t\tforn(j, i) {\n\t\t\tint mask = (1 << i) | (1 << j);\n\t\t\tld cur = 0;\n\t\t\tcur += solve(mask, i) * p[i][j];\n\t\t\tcur += solve(mask, j) * p[j][i];\n\t\t\tans = max(ans, cur);\n\t\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "678",
    "index": "F",
    "title": "Lena and Queries",
    "statement": "Lena is a programmer. She got a task to solve at work.\n\nThere is an empty set of pairs of integers and $n$ queries to process. Each query is one of three types:\n\n- Add a pair $(a, b)$ to the set.\n- Remove a pair added in the query number $i$. All queries are numbered with integers from $1$ to $n$.\n- For a given integer $q$ find the maximal value $x·q + y$ over all pairs $(x, y)$ from the set.\n\nHelp Lena to process the queries.",
    "tutorial": "Let's interpret the problem geometrically: the pairs from the set are the lines and the problem to find to topmost intersection of the vertical line with the lines from the set. Let's split the queries to $\\sqrt{n}$ blocks. Consider the lines added before the current block and that will not deleted in the current block. Let's build the lower envelope by that lines. Now to calculate the answer to the query we should get maximum over the lines from the envelope and the lines from the block before the current query that is not deleted yet. There are no more than $\\sqrt{n}$ lines from the block, so we can iterate over them. Let's find the answers from the envelope for all queries of the third type from the block at once: we should sort them and iterate over envelope using two pointers technique. Complexity: $O(n{\\sqrt{n}})$.",
    "code": "const int N = 300300;\n\nint n;\nint t[N], a[N], b[N], id[N], q[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) {\n\t\tassert(scanf(\"%d\", &t[i]) == 1);\n\t\tif (t[i] == 1) {\n\t\t\tassert(scanf(\"%d%d\", &a[i], &b[i]) == 2);\n\t\t} else if (t[i] == 2) {\n\t\t\tassert(scanf(\"%d\", &id[i]) == 1);\n\t\t\tid[i]--;\n\t\t} else if (t[i] == 3) {\n\t\t\tassert(scanf(\"%d\", &q[i]) == 1);\n\t\t} else throw;\n\t}\n\treturn true;\n}\n\nbool in_set[N], deleted[N];\nvector<pair<pti, int>> lines;\nvector<pti> envelope;\n\nvoid build_envelope() {\n\tenvelope.clear();\n\tenvelope.reserve(n);\n\n\tforn(ii, sz(lines)) {\n\t\tint i = lines[ii].y;\n\t\tif (in_set[i] && !deleted[i]) {\n\t\t\tassert(t[i] == 1);\n\t\t\tpti c(a[i], b[i]);\n\t\t\twhile (!envelope.empty()) {\n\t\t\t\tpti b = envelope.back();\n\t\t\t\tif (b.x == c.x) {\n\t\t\t\t\tenvelope.pop_back();\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (sz(envelope) > 1) {\n\t\t\t\t\tpti a = envelope[sz(envelope) - 2];\n\n\t\t\t\t\tld xc = ld(c.y - a.y) / (a.x - c.x);\n\t\t\t\t\tld xb = ld(b.y - a.y) / (a.x - b.x);\n\n\t\t\t\t\tif (xc < xb) {\n\t\t\t\t\t\tenvelope.pop_back();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tenvelope.pb(c);\n\t\t}\n\t}\n}\n\nli ans[N];\nvector<pti> qs;\n\nvoid process_qs() {\n\tsort(all(qs));\n\n\tint p = 0;\n\tforn(i, sz(qs)) {\n\t\tli q = qs[i].x;\n\t\tint id = qs[i].y;\n\n\t\twhile (p + 1 < sz(envelope)) {\n\t\t\tli cval = envelope[p].x * q + envelope[p].y;\n\t\t\tli nval = envelope[p + 1].x * q + envelope[p + 1].y;\n\t\t\tif (cval > nval) break;\n\t\t\tp++;\n\t\t}\n\n\t\tif (p < sz(envelope)) {\n\t\t\tans[id] = envelope[p].x * q + envelope[p].y;\n\t\t}\n\t}\n}\n\nvoid solve() {\n\tlines.clear();\n\tlines.reserve(n);\n\tforn(i, n) if (t[i] == 1) lines.pb(mp(mp(a[i], b[i]), i));\n\tsort(all(lines));\n\n\tmemset(in_set, false, sizeof(in_set));\n\tmemset(deleted, false, sizeof(deleted));\n\tforn(i, n) ans[i] = LLONG_MIN;\n\n\tint blen = int(sqrtl(n));\n\tblen = 2500;\n\tfor (int l = 0; l < n; l += blen) {\n\t\tint r = min(n, l + blen);\n\n\t\tmemset(deleted, false, sizeof(deleted));\n\t\tfore(i, l, r) if (t[i] == 2) deleted[id[i]] = true;\n\t\tbuild_envelope();\n\n\t\tqs.clear();\n\t\tqs.reserve(r - l);\n\t\tfore(i, l, r) if (t[i] == 3) qs.pb(mp(q[i], i));\n\t\tprocess_qs();\n\n\t\tfore(i, l, r) {\n\t\t\tif (t[i] == 1) in_set[i] = true;\n\t\t\telse if (t[i] == 2) in_set[id[i]] = false;\n\t\t\telse {\n\t\t\t\tfore(j, l, r) {\n\t\t\t\t\tif (t[j] == 1 && in_set[j])\n\t\t\t\t\t\tans[i] = max(ans[i], li(a[j]) * q[i] + b[j]);\n\t\t\t\t\telse if (t[j] == 2 && in_set[id[j]])\n\t\t\t\t\t\tans[i] = max(ans[i], li(a[id[j]]) * q[i] + b[id[j]]);\n\t\t\t\t}\n\t\t\t\tif (ans[i] != LLONG_MIN) printf(\"%lldn\", ans[i]);\n\t\t\t\telse puts(\"EMPTY SET\");\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "679",
    "index": "A",
    "title": "Bear and Prime 100",
    "statement": "\\textbf{This is an interactive problem. In the output section below you will see the information about flushing the output.}\n\nBear Limak thinks of some hidden number — an integer from interval $[2, 100]$. Your task is to say if the hidden number is prime or composite.\n\nInteger $x > 1$ is called prime if it has exactly two distinct divisors, $1$ and $x$. If integer $x > 1$ is not prime, it's called composite.\n\nYou can ask up to $20$ queries about divisors of the hidden number. In each query you should print an integer from interval $[2, 100]$. The system will answer \"yes\" if your integer is a divisor of the hidden number. Otherwise, the answer will be \"no\".\n\nFor example, if the hidden number is $14$ then the system will answer \"yes\" only if you print $2$, $7$ or $14$.\n\nWhen you are done asking queries, print \"prime\" or \"composite\" and terminate your program.\n\nYou will get the Wrong Answer verdict if you ask more than $20$ queries, or if you print an integer not from the range $[2, 100]$. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.\n\nYou will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).",
    "tutorial": "If a number is composite then it's either divisible by $p^{2}$ for some prime $p$, or divisible by two distinct primes $p$ and $q$. To check the first condition, it's enough to check all possible $p^{2}$ (so, numbers $4$, $9$, $25$, $49$). If at least one gives \"yes\" then the hidden number if composite. If there are two distinct prime divisors $p$ and $q$ then both of them are at most $50$ - otherwise the hidden number would be bigger than $100$ (because for $p  \\ge  2$ and $q > 50$ we would get $p \\cdot q > 100$). So, it's enough to check primes up to $50$ (there are $15$ of them), and check if at least two of them are divisors.",
    "code": "from sys import stdout\n\nPRIMES = [x for x in range(2,100) if 0 not in [x%i for i in range(2,x)]]\n\nNORMAL = PRIMES[:15]\nSQUARES = [x*x for x in PRIMES[:4]]\n\nfor ele in SQUARES:\n    print(ele)\n    stdout.flush()\n    x = input()\n    if x == \"yes\":\n        print(\"composite\")\n        exit(0)\n\nyes = 0\nfor ele in NORMAL:\n    print(ele)\n    stdout.flush()\n    x = input()\n    if x == \"yes\":\n        yes += 1\n\nprint(\"prime\" if yes < 2 else \"composite\")",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "679",
    "index": "B",
    "title": "Bear and Tower of Cubes",
    "statement": "Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.\n\nA block with side $a$ has volume $a^{3}$. A tower consisting of blocks with sides $a_{1}, a_{2}, ..., a_{k}$ has the total volume $a_{1}^{3} + a_{2}^{3} + ... + a_{k}^{3}$.\n\nLimak is going to build a tower. First, he asks you to tell him a positive integer $X$ — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed $X$.\n\nLimak asks you to choose $X$ not greater than $m$. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize $X$.\n\nCan you help Limak? Find the maximum number of blocks his tower can have and the maximum $X ≤ m$ that results this number of blocks.",
    "tutorial": "Let's find the maximum $a$ that $a^{3}  \\le  m$. Then, it's optimal to choose $X$ that the first block will have side $a$ or $a - 1$. Let's see why. We want to first maximize the number of blocks we can get with new limit $m_{2}$. Secondarily, we want to have the biggest initial $X$. You can analyze the described above cases and see that the first block with side $(a - 2)^{3}$ must be a worse choice than $(a - 1)^{3}$. It's because we start with smaller $X$ and we are left with smaller $m_{2}$. The situation for even smaller side of the first block would be even worse. Now, you can notice that the answer will be small. From $m$ of magnitude $a^{3}$ after one block we get $m_{2}$ of magnitude $a^{2}$. So, from $m$ we go to $m^{2 / 3}$, which means that the answer is $O(loglog(m))$. The exact maximum answer turns out to be $18$. The intended solution is to use the recursion and brutally check both cases: taking $a^{3}$ and taking $(a - 1)^{3}$ where $a$ is maximum that $a^{3}  \\le  m$. It's so fast that you can even find $a$ in $O(m^{1 / 3})$, increasing $a$ by one.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\n#define ll long long\n\nvector <ll> X;\nmap <ll, pair <int, ll> > M;\n\npair <int, ll> go(ll x)\n{\n  if(x <= 1)\n    return {x,x};\n  if(M.find(x) != M.end())\n    return M[x];\n  int i = upper_bound(X.begin(), X.end(), x) - X.begin() - 1;\n  int p1, p2;\n  long long q1, q2;\n  tie(p1, q1) = go(x - X[i]);\n  tie(p2, q2) = go(X[i] - 1);\n  return M[x] =  max(make_pair(p1+1, q1+X[i]), {p2, q2});\n}\n\nint main()\n{\n  for(int i=0; i<=1e5+7; i++)\n    X.push_back(1LL*i*i*i);\n  ll x;\n  cin >> x;\n  int a;\n  long long b;\n  tie(a,b) = go(x);\n  cout << a << \" \" << b << \"n\";\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "679",
    "index": "C",
    "title": "Bear and Square Grid",
    "statement": "You have a grid with $n$ rows and $n$ columns. Each cell is either empty (denoted by '.') or blocked (denoted by 'X').\n\nTwo empty cells are directly connected if they share a side. Two cells $(r_{1}, c_{1})$ (located in the row $r_{1}$ and column $c_{1}$) and $(r_{2}, c_{2})$ are connected if there exists a sequence of empty cells that starts with $(r_{1}, c_{1})$, finishes with $(r_{2}, c_{2})$, and any two consecutive cells in this sequence are directly connected. A connected component is a set of empty cells such that any two cells in the component are connected, and there is no cell in this set that is connected to some cell not in this set.\n\nYour friend Limak is a big grizzly bear. He is able to destroy any obstacles in some range. More precisely, you can choose a square of size $k × k$ in the grid and Limak will transform all blocked cells there to empty ones. However, you can ask Limak to help only once.\n\nThe chosen square must be completely inside the grid. It's possible that Limak won't change anything because all cells are empty anyway.\n\nYou like big connected components. After Limak helps you, what is the maximum possible size of the biggest connected component in the grid?",
    "tutorial": "Let's first find CC's (connected components) in the given grid, using DFS's. We will consider every possible placement of a $k  \\times  k$ square. When the placement is fixed then the answer is equal to the sum of $k^{2}$ the the sum of sizes of CC's touching borders of the square (touching from outside), but for those CC's we should only count their cells that are outside of the square - not to count something twice. We will move a square, and at the same time for each CC we will keep the number of its cells outside the square. We will used a sliding-window technique. Let's fix row of the grid - the upper row of the square. Then, we will first place the square on the left, and then we will slowly move a square to the right. As we move a square, we should iterate over cells that stop or start to belong to the square. For each such empty cell we should add or subtract $1$ from the size of its CC (ids and sizes of CC's were found at the beginning). And for each placement we consider, we should iterate over outside borders of the square ($4k$ cells - left, up, right and down side) and sum up sizes of CC's touching our square. Be careful to not count some CC twice - you can e.g. keep an array of booleans and mark visited CC's. After checking all $4k$ cells you should clear an array, but you can't do it in O(number_of_all_components) because it would be too slow. You can e.g. also add visited CC's to some vector, and later in the boolean array clear only CC's from the vector (and then clear vector). The complexity is $O(n^{2} \\cdot k)$.",
    "code": "import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.io.IOException;\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.io.InputStream;\n\n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\n * @author AlexFetisov\n */\npublic class Main {\n    public static void main(String[] args) {\n        InputStream inputStream = System.in;\n        OutputStream outputStream = System.out;\n        InputReader in = new InputReader(inputStream);\n        PrintWriter out = new PrintWriter(outputStream);\n        TaskE_356 solver = new TaskE_356();\n        solver.solve(1, in, out);\n        out.close();\n    }\n\n    static class TaskE_356 {\n        int n;\n        int k;\n        boolean[][] f;\n        List<Integer> componentCellCount;\n        int[][] color;\n        int x = 0;\n        int y = 0;\n        int totalEmpty = 0;\n        int sumInComponents = 0;\n        int[] amInComponents;\n        int[] flag;\n        int currentFlagColor = 0;\n\n        public void solve(int testNumber, InputReader in, PrintWriter out) {\n            n = in.nextInt();\n            k = in.nextInt();\n            f = new boolean[n][n];\n            color = new int[n][n];\n            ArrayUtils.fill(color, -1);\n            for (int i = 0; i < n; ++i) {\n                char[] c = in.nextString().toCharArray();\n                for (int j = 0; j < n; ++j) {\n                    f[i][j] = (c[j] == '.');\n                }\n            }\n\n            // Caclulate all CC\n            int res = 0;\n            componentCellCount = new ArrayList<Integer>();\n            int currentComponentId = 0;\n            for (int i = 0; i < n; ++i) {\n                for (int j = 0; j < n; ++j) {\n                    if (color[i][j] == -1) {\n                        int count = dfs(i, j, currentComponentId++);\n                        componentCellCount.add(count);\n                        res = Math.max(res, count);\n                    }\n                }\n            }\n\n            flag = new int[currentComponentId];\n            amInComponents = new int[currentComponentId];\n            // Preprocess first square\n            for (int i = 0; i < k; ++i) {\n                for (int j = 0; j < k; ++j) {\n                    addCell(i, j);\n                }\n            }\n\n            res = Math.max(res, checkResult());\n\n            for (int i = 0; i <= n - k; ++i) {\n                int delta = i % 2 == 0 ? 1 : -1;\n                for (int j = 0; j < n - k; ++j) {\n                    moveSquare(0, x, y, x, y + delta);\n                    y += delta;\n                    res = Math.max(res, checkResult());\n                }\n                if (i != n - k) {\n                    moveSquare(1, x, y, x + 1, y);\n                    ++x;\n                    res = Math.max(res, checkResult());\n                }\n            }\n            out.println(res);\n        }\n\n        void moveSquare(int type, int cx, int cy, int nx, int ny) {\n            if (type == 0) {\n                if (ny < cy) {\n                    for (int i = 0; i < k; ++i) {\n                        removeCell(cx + i, cy + k - 1);\n                        addCell(cx + i, ny);\n                    }\n                } else {\n                    for (int i = 0; i < k; ++i) {\n                        removeCell(cx + i, cy);\n                        addCell(cx + i, ny + k - 1);\n                    }\n                }\n            } else {\n                for (int i = 0; i < k; ++i) {\n                    removeCell(cx, cy + i);\n                    addCell(nx + k - 1, cy + i);\n                }\n            }\n        }\n\n        void removeCell(int cx, int cy) {\n            if (f[cx][cy]) {\n                --totalEmpty;\n                amInComponents[color[cx][cy]]--;\n                if (amInComponents[color[cx][cy]] == 0) {\n                    sumInComponents -= componentCellCount.get(color[cx][cy]);\n                }\n            }\n        }\n\n        void addCell(int cx, int cy) {\n            if (f[cx][cy]) {\n                ++totalEmpty;\n                amInComponents[color[cx][cy]]++;\n                if (amInComponents[color[cx][cy]] == 1) {\n                    sumInComponents += componentCellCount.get(color[cx][cy]);\n                }\n            }\n        }\n\n        int dfs(int cx, int cy, int cId) {\n            if (cx < 0 || cx >= n || cy < 0 || cy >= n) return 0;\n            if (color[cx][cy] != -1) return 0;\n            if (!f[cx][cy]) return 0;\n            color[cx][cy] = cId;\n            int am = 1;\n            am += dfs(cx - 1, cy, cId);\n            am += dfs(cx + 1, cy, cId);\n            am += dfs(cx, cy - 1, cId);\n            am += dfs(cx, cy + 1, cId);\n            return am;\n        }\n\n        int checkResult() {\n            ++currentFlagColor;\n            int res = k * k - totalEmpty + sumInComponents;\n            for (int i = 0; i < k; ++i) {\n                res += checkCell(x - 1, y + i);\n                res += checkCell(x + k, y + i);\n                res += checkCell(x + i, y - 1);\n                res += checkCell(x + i, y + k);\n            }\n            return res;\n        }\n\n        int checkCell(int cx, int cy) {\n            if (cx < 0 || cx >= n || cy < 0 || cy >= n) return 0;\n            if (!f[cx][cy]) return 0;\n            if (amInComponents[color[cx][cy]] > 0) return 0;\n            if (flag[color[cx][cy]] == currentFlagColor) return 0;\n            flag[color[cx][cy]] = currentFlagColor;\n            return componentCellCount.get(color[cx][cy]);\n        }\n\n    }\n\n    static class ArrayUtils {\n        public static void fill(int[][] f, int value) {\n            for (int i = 0; i < f.length; ++i) {\n                Arrays.fill(f[i], value);\n            }\n        }\n\n    }\n\n    static class InputReader {\n        private BufferedReader reader;\n        private StringTokenizer stt;\n\n        public InputReader(InputStream stream) {\n            reader = new BufferedReader(new InputStreamReader(stream));\n        }\n\n        public String nextLine() {\n            try {\n                return reader.readLine();\n            } catch (IOException e) {\n                return null;\n            }\n        }\n\n        public String nextString() {\n            while (stt == null || !stt.hasMoreTokens()) {\n                stt = new StringTokenizer(nextLine());\n            }\n            return stt.nextToken();\n        }\n\n        public int nextInt() {\n            return Integer.parseInt(nextString());\n        }\n\n    }\n}\n",
    "tags": [
      "dfs and similar",
      "dsu",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "679",
    "index": "D",
    "title": "Bear and Chase",
    "statement": "Bearland has $n$ cities, numbered $1$ through $n$. There are $m$ bidirectional roads. The $i$-th road connects two distinct cities $a_{i}$ and $b_{i}$. No two roads connect the same pair of cities. It's possible to get from any city to any other city (using one or more roads).\n\nThe distance between cities $a$ and $b$ is defined as the minimum number of roads used to travel between $a$ and $b$.\n\nLimak is a grizzly bear. He is a criminal and your task is to catch him, or at least to try to catch him. You have only two days (today and tomorrow) and after that Limak is going to hide forever.\n\nYour main weapon is BCD (Bear Criminal Detector). Where you are in some city, you can use BCD and it tells you the distance between you and a city where Limak currently is. Unfortunately, BCD can be used only once a day.\n\nYou don't know much about Limak's current location. You assume that he is in one of $n$ cities, chosen uniformly at random (each city with probability $\\textstyle{\\frac{1}{n}}$). You decided for the following plan:\n\n- Choose one city and use BCD there.\n\n- After using BCD you can try to catch Limak (but maybe it isn't a good idea). In this case you choose one city and check it. You win if Limak is there. Otherwise, Limak becomes more careful and you will never catch him (you loose).\n\n- Wait $24$ hours to use BCD again. You know that Limak will change his location during that time. In detail, he will choose uniformly at random one of roads from his initial city, and he will use the chosen road, going to some other city.\n- Tomorrow, you will again choose one city and use BCD there.\n- Finally, you will try to catch Limak. You will choose one city and check it. You will win if Limak is there, and loose otherwise.\n\nEach time when you choose one of cities, you can choose any of $n$ cities. Let's say it isn't a problem for you to quickly get somewhere.\n\nWhat is the probability of finding Limak, if you behave optimally?",
    "tutorial": "Check my code below, because it has a lot of comments. First, in $O(n^{3})$ or faster find all distances between pairs of cities. Iterate over all $g1$ - the first city in which you use the BCD. Then, for iterate over all $d1$ - the distance you get. Now, for all cities calculate the probability that Limak will be there in the second day (details in my code below). Also, in a vector interesting let's store all cities that are at distance $d1$ from city $g1$. Then, iterate over all $g2$ - the second city in which you use the BCD. For cities from interesting, we want to iterate over them and for each distinct distance from $g2$ to choose the biggest probability (because we will make the best guess there is). Magic: the described approach has four loops (one in the other) but it's $O(n^{3})$. Proof is very nice and I encourage you to try to get it yourself. After fixing g1 divide cities by their distance from g1. Then, when we get distance d1 in the first day, then in the second day all possible cities are at distance d1-1, d1 and d1+1. So, we will consider each city at most three times.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)\ntypedef double T;\nconst int nax = 1005;\nint dist[nax][nax];\nvector<int> w[nax];\nT p_later[nax]; // p[v] - probability for city v in the second day\nT p_dist_max[nax];\nbool vis[nax];\n\nvoid max_self(T & a, T b) {\n\ta = max(a, b);\n}\n\nT consider_tomorrow(int n, int g1, int dist1) {\n\tT best_tomorrow = 0;\n\t// we need complexity O(n * x)\n\t// where x denotes the number of v that |dist1-dist[g1][v]| <= 1\n\tfor(int i = 1; i <= n; ++i) {\n\t\tp_later[i] = 0;\n\t\tvis[i] = false;\n\t}\n\tvector<int> interesting;\n\tfor(int v = 1; v <= n; ++v) if(dist[g1][v] == dist1)\n\t\tfor(int b : w[v]) {\n\t\t\t// Limak started in v with prob. 1/n\n\t\t\t// he then moved to b with prob. 1/degree[v]\n\t\t\tp_later[b] += (T) 1 / n / w[v].size();\n\t\t\tif(!vis[b]) {\n\t\t\t\tvis[b] = true;\n\t\t\t\tinteresting.push_back(b);\n\t\t\t}\n\t\t}\n\t\n\t// interesting.size() <= x, where x is defined above (needed for complexity)\n\tfor(int g2 = 1; g2 <= n; ++g2) {\n\t\tT local_sum = 0; // over situations with fixed g1, dist1, g2\n\t\t\n\t\tfor(int b : interesting)\n\t\t\tmax_self(p_dist_max[dist[g2][b]], p_later[b]);\n\t\tfor(int b : interesting) {\n\t\t\tlocal_sum += p_dist_max[dist[g2][b]];\n\t\t\tp_dist_max[dist[g2][b]] = 0; // so it won't be calculated twice\n\t\t}\n\t\tmax_self(best_tomorrow, local_sum);\n\t}\n\treturn best_tomorrow;\n}\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tFOR(i,1,n) FOR(j, 1, n) if(i != j)\n\t\tdist[i][j] = n + 1; // infinity\n\tFOR(i,1,m) {\n\t\tint a, b;\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tw[a].push_back(b);\n\t\tw[b].push_back(a);\n\t\tdist[a][b] = dist[b][a] = 1;\n\t}\n\t// Floyd-Warshall\n\tFOR(b,1,n)FOR(a,1,n)FOR(c,1,n)\n\t\tdist[a][c] = min(dist[a][c], dist[a][b] + dist[b][c]);\n\t\n\t// g1 is the first guess\n\tT answer = 0;\n\tFOR(g1, 1, n) {\n\t\tT sum_over_dist1 = 0;\n\t\tFOR(dist1, 0, n) {\n\t\t\tint cnt_cities = 0;\n\t\t\tFOR(i, 1, n) if(dist[g1][i] == dist1)\n\t\t\t\t++cnt_cities;\n\t\t\tif(cnt_cities == 0) continue; // there are no cities within distance dist1\n\t\t\t\n\t\t\t// 1) consider guessing immediately\n\t\t\tT immediately = (T) 1 / n; // how much it counts towards the answer\n\t\t\t// 2) consider waiting for tomorrow\n\t\t\tT second_day = consider_tomorrow(n, g1, dist1);\n\t\t\tsum_over_dist1 += max(immediately, second_day);\n\t\t}\n\t\tmax_self(answer, sum_over_dist1);\n\t}\n\tprintf(\"%.12lfn\", (double) answer);\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation",
      "math",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "679",
    "index": "E",
    "title": "Bear and Bad Powers of 42",
    "statement": "Limak, a bear, isn't good at handling queries. So, he asks you to do it.\n\nWe say that powers of $42$ (numbers $1, 42, 1764, ...$) are bad. Other numbers are good.\n\nYou are given a sequence of $n$ good integers $t_{1}, t_{2}, ..., t_{n}$. Your task is to handle $q$ queries of three types:\n\n- 1 i — print $t_{i}$ in a separate line.\n- 2 a b x — for $i\\in[a,b]$ set $t_{i}$ to $x$. It's guaranteed that $x$ is a good number.\n- 3 a b x — for $i\\in[a,b]$ increase $t_{i}$ by $x$. After this repeat the process while at least one $t_{i}$ is bad.\n\nYou can note that after each query all $t_{i}$ are good.",
    "tutorial": "The only special thing in numbers $1, 42, ...$ was that there are only few such numbers (in the possible to achieve range, so up to about $10^{14}$). Let's first solve the problem without queries \"in the interval change all numbers to x\". Then, we can make a tree with operations (possible with lazy propagation): In a tree for each index $i\\in[1,n]$ let's keep the distance to the next power of 42. After each \"add on the interval\" we should find the minimum and check if it's positive. If not then we should change value of the closest power of $42$ for this index, and change the value in the tree. Then, we should again find the minimum in the tree, and so on. The amortized complexity is $O((n + q) * log(n) * log_{42}(values))$. It can be proved that numbers won't exceed $(n + q) * 1e9 * log$. Now let's think about the remaining operation of changing all interval to some value. We can set only one number (the last one) to the given value, and set other values to INF. We want to guarantee that if $t[i]  \\neq  t[i + 1]$ then the $i$-th value is correctly represented in the tree. Otherwise, it can be INF instead (or sometimes it may be correctly represented, it doesn't bother me). When we have the old query of type \"add something to interval $[a, b]$\" then if index $a - 1$ or index $b$ contains INF in the tree then we should first retrieve the true value there. You can see that each operation changes $O(1)$ values from INF to something finite. So, the amortized complexity is still $O((n + q) * log(n) * log_{42}(values)$. One thing regarding implementation. In my solution there is \"$set < int > interesting$\" containing indices with INF value. I think it's easier to implemement the solution with this set.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n, q;\n\nvector <long long> poty;\n\nint n1;\n\nlong long inf=(long long)1000000000*1000000000;\n\nlong long narz[1000007];\nint czybom[1000007];\nlong long bom[1000007];\n\nlong long maxd[1000007];\nlong long mind[1000007];\nlong long zos[1000007];\n\nint typ, p1, p2, p3;\n\ninline int potenga(int v)\n{\n    for (int i=1; 1; i<<=1)\n    {\n        if (i>=v)\n        {\n            return i;\n        }\n    }\n}\n\ninline long long wie(long long v)\n{\n    return poty[lower_bound(poty.begin(), poty.end(), v)-poty.begin()];\n}\n\ninline long long brak(long long v)\n{\n    return wie(v)-v;\n}\n\ninline void pusz(int v)\n{\n    if (v>=n1)\n    {\n        czybom[v]=1;\n        bom[v]+=narz[v];\n        narz[v]=0;\n        maxd[v]=bom[v];\n        mind[v]=bom[v];\n        zos[v]=brak(bom[v]);\n        return;\n    }\n    int cel1, cel2;\n    cel1=(v<<1);\n    cel2=(cel1^1);\n    if (czybom[v])\n    {\n        czybom[cel1]=1;\n        bom[cel1]=bom[v];\n        narz[cel1]=0;\n\n        czybom[cel2]=1;\n        bom[cel2]=bom[v];\n        narz[cel2]=0;\n\n        czybom[v]=0;\n        bom[v]=0;\n    }\n    narz[cel1]+=narz[v];\n    narz[cel2]+=narz[v];\n    narz[v]=0;\n\n    mind[v]=inf;\n    maxd[v]=-inf;\n    zos[v]=inf;\n\n    for (int h=0; h<2; h++)\n    {\n\n        if (czybom[cel1])\n        {\n            bom[cel1]+=narz[cel1];\n            narz[cel1]=0;\n            maxd[v]=max(maxd[v], bom[cel1]);\n            mind[v]=min(mind[v], bom[cel1]);\n            zos[v]=min(zos[v], brak(bom[cel1]));\n        }\n        else\n        {\n            maxd[v]=max(maxd[v], maxd[cel1]+narz[cel1]);\n            mind[v]=min(mind[v], mind[cel1]+narz[cel1]);\n            zos[v]=min(zos[v], zos[cel1]-narz[cel1]);\n        }\n\n        swap(cel1, cel2);\n    }\n}\n\nvoid dod(int v, int a, int b, int graa, int grab, long long w)\n{\n    if (a>=graa && b<=grab)\n    {\n        narz[v]+=w;\n        return;\n    }\n    if (a>grab || b<graa)\n    {\n        return;\n    }\n    pusz(v);\n    dod((v<<1), a, (a+b)>>1, graa, grab, w);\n    dod((v<<1)^1, (a+b+2)>>1, b, graa, grab, w);\n    pusz(v);\n}\n\nvoid zmi(int v, int a, int b, int graa, int grab, long long w)\n{\n    if (a>=graa && b<=grab)\n    {\n        narz[v]=0;\n        czybom[v]=1;\n        bom[v]=w;\n        return;\n    }\n    if (a>grab || b<graa)\n    {\n        return;\n    }\n    pusz(v);\n    zmi((v<<1), a, (a+b)>>1, graa, grab, w);\n    zmi((v<<1)^1, (a+b+2)>>1, b, graa, grab, w);\n    pusz(v);\n}\n\nvoid popr(int v)\n{\n    pusz(v);\n    if (zos[v]>=0)\n    {\n        return;\n    }\n    if (mind[v]==maxd[v])\n    {\n        czybom[v]=1;\n        bom[v]=mind[v];\n        narz[v]=0;\n        pusz(v);\n        return;\n    }\n    popr((v<<1));\n    popr((v<<1)^1);\n    pusz(v);\n}\n\nlong long wyn;\n\nvoid czyt(int v, int a, int b, int cel)\n{\n    if (a>cel || b<cel)\n    return;\n    pusz(v);\n    if (a==b)\n    {\n        wyn=bom[v];\n        return;\n    }\n    czyt((v<<1), a, (a+b)>>1, cel);\n    czyt((v<<1)^1, (a+b+2)>>1, b, cel);\n}\n\nint main()\n{\n    scanf(\"%d%d\", &n, &q);\n    n1=potenga(n+2);\n    poty.push_back(1);\n    for (int i=1; i<=11; i++)\n    poty.push_back(poty.back()*42);\n    zmi(1, 1, n1, 1, n1, 0);\n    for (int i=1; i<=n; i++)\n    {\n        scanf(\"%d\", &p1);\n        zmi(1, 1, n1, i, i, p1);\n    }\n    while(q--)\n    {\n        scanf(\"%d\", &typ);\n        if (typ==1)\n        {\n            scanf(\"%d\", &p1);\n            czyt(1, 1, n1, p1);\n            printf(\"%lldn\", wyn);\n        }\n        if (typ==2)\n        {\n            scanf(\"%d%d%d\", &p1, &p2, &p3);\n            zmi(1, 1, n1, p1, p2, p3);\n        }\n        if (typ==3)\n        {\n            scanf(\"%d%d%d\", &p1, &p2, &p3);\n            dod(1, 1, n1, p1, p2, p3);\n            while(1)\n            {\n                popr(1);\n                if (zos[1]==0)\n                {\n                    dod(1, 1, n1, p1, p2, p3);\n                }\n                else\n                {\n                    break;\n                }\n            }\n        }\n    }\n    return 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "680",
    "index": "A",
    "title": "Bear and Five Cards",
    "statement": "A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.\n\nLimak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.\n\nHe is allowed to \\textbf{at most once} discard two or three cards with the same number. Of course, he won't discard cards if it's impossible to choose two or three cards with the same number.\n\nGiven five numbers written on cards, cay you find the minimum sum of numbers on remaining cards?",
    "tutorial": "Iterate over all pairs and triples of numbers, and for each of them check if all two/three numbers are equal. If yes then consider the sum of remaining numbers as the answer (the final answer will be the minimum of considered sums). Below you can see two ways to implement the solution.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main() {\n\tint t[5];\n\tfor(int i = 0; i < 5; ++i)\n\t\tscanf(\"%d\", &t[i]);\n\tsort(t, t + 5);\n\tint best_remove = 0;\n\tfor(int i = 0; i < 5; ++i) {\n\t\tif(i + 1 < 5 && t[i] == t[i+1])\n\t\t\tbest_remove = max(best_remove, 2 * t[i]);\n\t\tif(i + 2 < 5 && t[i] == t[i+2])\n\t\t\tbest_remove = max(best_remove, 3 * t[i]);\n\t}\n\tprintf(\"%dn\", t[0]+t[1]+t[2]+t[3]+t[4]-best_remove);\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "680",
    "index": "B",
    "title": "Bear and Finding Criminals",
    "statement": "There are $n$ cities in Bearland, numbered $1$ through $n$. Cities are arranged in one long row. The distance between cities $i$ and $j$ is equal to $|i - j|$.\n\nLimak is a police officer. He lives in a city $a$. His job is to catch criminals. It's hard because he doesn't know in which cities criminals are. Though, he knows that there is \\textbf{at most one} criminal in each city.\n\nLimak is going to use a BCD (Bear Criminal Detector). The BCD will tell Limak how many criminals there are for every distance from a city $a$. After that, Limak can catch a criminal in each city for which he \\textbf{is sure} that there must be a criminal.\n\nYou know in which cities criminals are. Count the number of criminals Limak will catch, after he uses the BCD.",
    "tutorial": "Limak can't catch a criminal only if there are two cities at the same distance and only one of them contains a criminal. You should iterate over the distance and for each distance $d$ check if $a - d$ and $a + d$ are both in range $[1, n]$ and if only one of them has $t_{i} = 1$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int nax = 1005;\nint t[nax];\nbool impossible[nax];\nint main() {\n\tint n, a;\n\tscanf(\"%d%d\", &n, &a);\n\tfor(int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &t[i]);\n\tfor(int i = 1; i <= n; ++i)\n\t\tfor(int j = i + 1; j <= n; ++j)\n\t\t\tif(abs(i - a) == abs(j - a) && t[i] != t[j]) {\n\t\t\t\t// i and j have the same distance to a\n\t\t\t\t// also, there is a criminal in exactly one of them\n\t\t\t\timpossible[i] = impossible[j] = true;\n\t\t\t}\n\tint answer = 0;\n\tfor(int i = 1; i <= n; ++i)\n\t\tif(t[i] == 1 && !impossible[i])\n\t\t\t++answer;\n\tprintf(\"%dn\", answer);\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "681",
    "index": "A",
    "title": "A Good Contest",
    "statement": "Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to $2400$; it is orange if his rating is less than $2400$ but greater or equal to $2200$, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.\n\nAnton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.\n\nAnton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?",
    "tutorial": "If for any participant $before_{i}  \\ge  2400$ and $after_{i} > before_{i}$, then the answer is \"YES\", otherwise \"NO\"",
    "code": "\"#include <iostream>\\n\\nusing namespace std;\\n\\nconst int RED = 2400;\\n\\nint main() {\\n    int n;\\n    cin >> n;\\n    bool good = false;\\n    for (int i = 0; i < n; i++) {\\n        string handle;\\n        int before, after;\\n        cin >> handle >> before >> after;\\n        if (before >= RED && after > before) {\\n            good = true;\\n            break;\\n        }\\n    }\\n\\n    if (good) {\\n        cout << \\\"YES\\\";\\n    } else {\\n        cout << \\\"NO\\\";\\n    }\\n\\n    return 0;\\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "681",
    "index": "B",
    "title": "Economy Game",
    "statement": "Kolya is developing an economy simulator game. His most favourite part of the development process is in-game testing. Once he was entertained by the testing so much, that he found out his game-coin score become equal to $0$.\n\nKolya remembers that at the beginning of the game his game-coin score was equal to $n$ and that he have bought only some houses (for $1 234 567$ game-coins each), cars (for $123 456$ game-coins each) and computers (for $1 234$ game-coins each).\n\nKolya is now interested, whether he could have spent all of his initial $n$ game-coins buying only houses, cars and computers or there is a bug in the game. Formally, is there a triple of non-negative integers $a$, $b$ and $c$ such that $a × 1 234 567 + b × 123 456 + c × 1 234 = n$?\n\nPlease help Kolya answer this question.",
    "tutorial": "We can simply try every $a$ from $0$ to $n / 1234567$ and $b$ from $0$ to $n / 123456$, and if $n - a * 1234567 - b * 123456$ is non-negative and divided by $1234$, then the answer is \"YES\". If there is no such $a$ and $b$, then the answer is \"NO\".",
    "code": "\"#include <iostream>\\n\\nusing namespace std;\\n\\nint main() {\\n    int n;\\n    cin >> n;\\n    for (int a = 0; a <= n; a += 1234567) {\\n        for (int b = 0; b <= n - a; b += 123456) {\\n            if ((n - a - b) % 1234 == 0) {\\n                cout << \\\"YES\\\";\\n                return 0;\\n            }\\n        }\\n    }\\n    cout << \\\"NO\\\";\\n\\n    return 0;\\n}\"",
    "tags": [
      "brute force"
    ],
    "rating": 1300
  },
  {
    "contest_id": "681",
    "index": "C",
    "title": "Heap Operations",
    "statement": "Petya has recently learned data structure named \"Binary heap\".\n\nThe heap he is now operating with allows the following operations:\n\n- put the given number into the heap;\n- get the value of the minimum element in the heap;\n- extract the minimum element from the heap;\n\nThus, at any moment of time the heap contains several integers (possibly none), some of them might be equal.\n\nIn order to better learn this data structure Petya took an empty heap and applied some operations above to it. Also, he carefully wrote down all the operations and their results to his event log, following the format:\n\n- insert $x$ — put the element with value $x$ in the heap;\n- getMin $x$ — the value of the minimum element contained in the heap was equal to $x$;\n- removeMin — the minimum element was extracted from the heap (only one instance, if there were many).\n\nAll the operations were correct, i.e. there was at least one element in the heap each time getMin or removeMin operations were applied.\n\nWhile Petya was away for a lunch, his little brother Vova came to the room, took away some of the pages from Petya's log and used them to make paper boats.\n\nNow Vova is worried, if he made Petya's sequence of operations inconsistent. For example, if one apply operations one-by-one in the order they are written in the event log, results of getMin operations might differ from the results recorded by Petya, and some of getMin or removeMin operations may be incorrect, as the heap is empty at the moment they are applied.\n\nNow Vova wants to add some new operation records to the event log in order to make the resulting sequence of operations correct. That is, the result of each getMin operation is equal to the result in the record, and the heap is non-empty when getMin ad removeMin are applied. Vova wants to complete this as fast as possible, as the Petya may get back at any moment. He asks you to add the least possible number of operation records to the current log. Note that arbitrary number of operations may be added at the beginning, between any two other operations, or at the end of the log.",
    "tutorial": "Let's solve this problem with greedy approach. Let's apply operations from log in given order. If current operation is $insert$ $x$, then add element $x$ to heap. If current operation is $removeMin$, then if heap is not empty, then simply remove minimal element, otherwise if heap is empty, add operation $insert$ $x$, where $x$ can be any number, and then apply $removeMin$ If current operation is $getMin$ $x$ then do follows: While heap is not empty and its minimal element is less than $x$, apply operation $removeMin$. Now if heap is empty or its minimal element is not equal to $x$, apply operation $insert$ $x$. Apply operation $getMin$ $x$. In order to fit time limit, you need to use data structure, which allows you to apply given operations in $O(logN)$ time, where $N$ is a number of elements in it. For example, std::priority_queue or std::multiset.",
    "code": "\"#include <iostream>\\n#include <queue>\\n#include <string>\\n\\nusing namespace std;\\n\\nconst int NO_X = 2e9;\\n\\nconst string REMOVE = \\\"removeMin\\\";\\nconst string GET = \\\"getMin\\\";\\nconst string INSERT = \\\"insert\\\";\\n\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(0);\\n\\n    int n;\\n    cin >> n;\\n\\n    vector<pair<string, int> > ans;\\n    priority_queue<int> q;\\n\\n    for (int i = 0; i < n; i++) {\\n        string s;\\n        cin >> s;\\n        if (s == INSERT) {\\n            int x;\\n            cin >> x;\\n            q.push(-x);\\n            ans.push_back(make_pair(s, x));\\n        } else if (s == GET) {\\n            int x;\\n            cin >> x;\\n            while (!q.empty() && -q.top() < x) {\\n                q.pop();\\n                ans.push_back(make_pair(REMOVE, NO_X));\\n            }\\n            if (q.empty() || -q.top() > x) {\\n                q.push(-x);\\n                ans.push_back(make_pair(INSERT, x));\\n            }\\n            ans.push_back(make_pair(s, x));\\n        } else { // s == REMOVE\\n            if (q.empty()) {\\n                ans.push_back(make_pair(INSERT, 0));\\n            } else {\\n                q.pop();\\n            }\\n            ans.push_back(make_pair(s, NO_X));\\n        }\\n    }\\n\\n    cout << ans.size() << \\\"\\\\n\\\";\\n    for (auto& p : ans) {\\n        cout << p.first;\\n        if (p.second != NO_X) {\\n            cout << \\\" \\\" << p.second;\\n        }\\n        cout << \\\"\\\\n\\\";\\n    }\\n\\n\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "681",
    "index": "D",
    "title": "Gifts by the List",
    "statement": "Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are $n$ men in Sasha's family, so let's number them with integers from $1$ to $n$.\n\nEach man has at most one father but may have arbitrary number of sons.\n\nMan number $A$ is considered to be the ancestor of the man number $B$ if at least one of the following conditions is satisfied:\n\n- $A = B$;\n- the man number $A$ is the father of the man number $B$;\n- there is a man number $C$, such that the man number $A$ is his ancestor and the man number $C$ is the father of the man number $B$.\n\nOf course, if the man number $A$ is an ancestor of the man number $B$ and $A ≠ B$, then the man number $B$ is not an ancestor of the man number $A$.\n\nThe tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.\n\n- A list of candidates is prepared, containing some (possibly all) of the $n$ men in some order.\n- Each of the $n$ men decides to give a gift.\n- In order to choose a person to give a gift to, man $A$ looks through the list and picks the first man $B$ in the list, such that $B$ is an ancestor of $A$ and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.\n- If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.\n\nThis year you have decided to help in organizing celebration and asked each of the $n$ men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?",
    "tutorial": "Formal statement of the problem: You have a directed acyclic graph, every vertex has at most one ingoing edge. Vertex $A$ is an ancestor of vertex $B$ if there is a path from $A$ to $B$ in graph. Also every vertex is an ancestor of itself. Every vertex $i$ has a pair - vertex $a_{i}$, $a_{i}$ - ancestor of $i$. You need to build such sequence of vertex, that for every vertex $i$ the leftmost vertex in the sequence which is ancestor of $i$ must be equal to $a_{i}$. Or you need to tell, that such sequence does not exists. Solution: Assume sequence $ans$, which contains every vertex from sequence $a_{n}$ by once and only them. Let's order elements of this sequence in such way, that for every $i$ and $j$ if $ans_{i}$ - ancestor of $ans_{j}$, then $i  \\ge  j$. If this sequecne is the answer, then print it. Otherwise, there is no answer. Why? If some vertex $a_{i}$ from sequence $a$ in not present in $ans$, then a man, who needs to give a gift to a man number $a_{i}$, will not be able to do it. So every vertex $a_{i}$ must have place in the resulting sequence. If $a_{i}$ - ancestor of $a_{j}$ and $i < j$, then a man, who needs to give a gift to a man number $a_{j}$ will not be able to do it. How can we build this sequence? Let's sort vertices topologically, than reverse it and remove redundant vertices. Now we need to check if that this sequence can be the answer. Let's calculate to whom every man will give his gift. At start for any man we don't know that. Let's iterate through vertices of the resulting sequence. For every vertex (man) from current vertex subtree (i.e. for vertices whose ancestor is current vertex) such that we still don't know whom will this vertex (man) give a gift to, stays that these vertices would give a gift to current vertex, because it is their first ancestor in the list. Iterate through that vertices (men) in dfs order and remember for them, to whom they will give their gift. After we apply this operation to all vertices from resulting sequence, compare for each man to whom he will give his gift and to whom he needs to give his gift. If there is at least one mismatch, then the answer doesn't exist.",
    "code": "\"#include <iostream>\\n#include <vector>\\n#include <memory.h>\\n\\nusing namespace std;\\n\\nconst int MAX_N = (int) 1e5;\\n\\nvector<int> g[MAX_N];\\nint a[MAX_N];\\nbool inA[MAX_N];\\n\\nvector<int> ts;\\nbool used[MAX_N];\\n\\nvoid dfs1(int v) {\\n    if (used[v]) {\\n        return;\\n    }\\n    used[v] = true;\\n    for (int i = 0; i < g[v].size(); i++) {\\n        dfs1(g[v][i]);\\n    }\\n    ts.push_back(v);\\n}\\n\\nint r[MAX_N];\\nvoid dfs2(int v, int x) {\\n    if (r[v] != -1) {\\n        return;\\n    }\\n    r[v] = x;\\n    for (int i = 0; i < g[v].size(); i++) {\\n        dfs2(g[v][i], x);\\n    }\\n}\\n\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(0);\\n    int n, m;\\n    cin >> n >> m;\\n    for (int i = 0; i < m; i++) {\\n        int x, y;\\n        cin >> x >> y;\\n        --x;\\n        --y;\\n        g[x].push_back(y);\\n    }\\n\\n    for (int i = 0; i < n; i++) {\\n        cin >> a[i];\\n        --a[i];\\n        inA[a[i]] = true;\\n    }\\n\\n    for (int i = 0; i < n; i++) {\\n        if (!used[i]) {\\n            dfs1(i);\\n        }\\n    }\\n\\n    memset(r, -1, sizeof(r));\\n    vector<int> ans;\\n    for (int i = 0; i < n; i++) {\\n        if (inA[ts[i]]) {\\n            dfs2(ts[i], ts[i]);\\n            ans.push_back(ts[i]);\\n        }\\n    }\\n\\n    for (int i = 0; i < n; i++) {\\n        if (r[i] != a[i]) {\\n            cout << -1;\\n            return 0;\\n        }\\n    }\\n\\n\\n    cout << ans.size() << \\\"\\\\n\\\";\\n    for (int i = 0; i < ans.size(); i++) {\\n        cout << ans[i] + 1 << \\\"\\\\n\\\";\\n    }\\n\\n\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "681",
    "index": "E",
    "title": "Runaway to a Shadow",
    "statement": "Dima is living in a dormitory, as well as some cockroaches.\n\nAt the moment $0$ Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly $T$ seconds for aiming, and after that he will precisely strike the cockroach and finish it.\n\nTo survive the cockroach has to run into a shadow, cast by round plates standing on the table, in $T$ seconds. Shadow casted by any of the plates has the shape of a circle. Shadow circles may intersect, nest or overlap arbitrarily.\n\nThe cockroach uses the following strategy: first he equiprobably picks a direction to run towards and then runs towards it with the constant speed $v$. If at some moment $t ≤ T$ it reaches any shadow circle, it immediately stops in the shadow and thus will stay alive. Otherwise the cockroach is killed by the Dima's precise strike. Consider that the Dima's precise strike is instant.\n\nDetermine the probability of that the cockroach will stay alive.",
    "tutorial": "At first assume the case when cockroach at the moment $0$ is already inside or on the border of some circle. In that case the cockroach will always survive, i. e. the probability is $1$. Otherwise the cockroach will have time to run to every point inside the circle with center of $x_{0}$, $y_{0}$ and radius $v  \\times  t$. Let's iterate through all the shadow circles and figure out how each circle relates to \"cockroach circle\". We want to find the maximum angle, such that choosing the direction from this angle the cockroach will have enough time to reach current circle and survive. In general, maximal \"surviving\" angle, such that choosing the direction from it the cockroach will reach the circle in infinite time - is an angle between two tangents from a start point to the circle. If length of this tangents is not greater than $v  \\times  t$, then this angle is the needed one. Otherwise we need to find intersections of cockroach circle and current circle. If there is no intersection points or there is only one, then current circle is too far away from cockroach. Otherwise intersection points and start point form the needed angle for this circle. After we've found all the angles, we can figure out that those angles are segments that cover a segment from $0$ to $2 \\pi $. Sort their ends and find a length of their union. This length divided by $2 \\pi $ will give us the answer.",
    "code": "\"#include <iostream>\\n#include <vector>\\n#include <cmath>\\n#include <algorithm>\\n\\nusing namespace std;\\n\\nconst double eps = 1e-9;\\n\\ndouble sqrDist(double x1, double y1, double x2, double y2) {\\n    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);\\n}\\n\\ndouble dist(double x1, double y1, double x2, double y2) {\\n    return sqrt(sqrDist(x1, y1, x2, y2));\\n}\\n\\nconst double PI = acos(-1.0);\\n\\nint main() {\\n    int x0, y0, v, t;\\n\\n    scanf(\\\"%d%d%d%d\\\", &x0, &y0, &v, &t);\\n\\n    double r0 = 1.0 * v * t;\\n\\n    int n;\\n    scanf(\\\"%d\\\", &n);\\n\\n    vector<pair<double, int> > a;\\n\\n    for (int i = 0; i < n; i++) {\\n        int x, y, r;\\n        scanf(\\\"%d%d%d\\\", &x, &y, &r);\\n        double d = sqrDist(x, y, x0, y0);\\n        if (d < 1.0 * r * r + eps) {\\n            printf(\\\"%.11f\\\", 1.0);\\n            return 0;\\n        }\\n        d = sqrt(d);\\n        if (r + r0 < d - eps) {\\n            continue;\\n        }\\n\\n        double angL, angR, ang;\\n        double angM = atan2(y - y0, x - x0);\\n        if (angM < 0) {\\n            angM += 2 * PI;\\n        }\\n\\n        double tLen = sqrt(d * d - 1.0 * r * r);\\n        if (tLen < r0 + eps) {\\n            ang = asin(r / d);\\n        } else {\\n            ang = acos((d * d + r0 * r0 - 1.0 * r * r) / (2 * d * r0));\\n        }\\n\\n        angL = angM - ang;\\n        angR = angM + ang;\\n\\n        if (angL < 0) {\\n            a.push_back(make_pair(angL + 2 * PI, 1));\\n            a.push_back(make_pair(2 * PI, -1));\\n            a.push_back(make_pair(0.0, 1));\\n            a.push_back(make_pair(angR, -1));\\n        } else if (angR > 2 * PI) {\\n            a.push_back(make_pair(angL, 1));\\n            a.push_back(make_pair(2 * PI, -1));\\n            a.push_back(make_pair(0.0, 1));\\n            a.push_back(make_pair(angR - 2 * PI, -1));\\n        } else {\\n            a.push_back(make_pair(angL, 1));\\n            a.push_back(make_pair(angR, -1));\\n        }\\n    }\\n\\n    sort(a.begin(), a.end());\\n\\n    double last = 0;\\n    int c = 0;\\n    double ans = 0;\\n\\n    for (auto& p : a) {\\n        if (c > 0) {\\n            ans += p.first - last;\\n        }\\n        c += p.second;\\n        last = p.first;\\n    }\\n\\n    ans /= 2 * PI;\\n    printf(\\\"%.11f\\\", ans);\\n\\n    return 0;\\n}\"",
    "tags": [
      "geometry",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "682",
    "index": "A",
    "title": "Alyona and Numbers",
    "statement": "After finishing eating her bun, Alyona came up with two integers $n$ and $m$. She decided to write down two columns of integers — the first column containing integers from $1$ to $n$ and the second containing integers from $1$ to $m$. Now the girl wants to count how many pairs of integers she can choose, one from the first column and the other from the second column, such that their sum is divisible by $5$.\n\nFormally, Alyona wants to count the number of pairs of integers $(x, y)$ such that $1 ≤ x ≤ n$, $1 ≤ y ≤ m$ and $(x+y)\\mod5$ equals $0$.\n\nAs usual, Alyona has some troubles and asks you to help.",
    "tutorial": "Let's iterate over the first number of the pair, let it be $x$. Then we need to count numbers from $1$ to $m$ with the remainder of dividing $5$ equal to $(5 - xmod5)mod$ 5. For example, you can precalc how many numbers from $1$ to $m$ with every remainder between $0$ and $4$.",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "682",
    "index": "B",
    "title": "Alyona and Mex",
    "statement": "Someone gave Alyona an array containing $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.\n\nFormally, after applying some operations Alyona will get an array of $n$ positive integers $b_{1}, b_{2}, ..., b_{n}$ such that $1 ≤ b_{i} ≤ a_{i}$ for every $1 ≤ i ≤ n$. Your task is to determine the maximum possible value of mex of this array.\n\nMex of an array in this problem is the \\textbf{minimum positive} integer that doesn't appear in this array. For example, mex of the array containing $1$, $3$ and $4$ is equal to $2$, while mex of the array containing $2$, $3$ and $2$ is equal to $1$.",
    "tutorial": "Let's sort the array. Let $cur =$ 1. Then walk through the array. Let's look at current number. If it is greater or equal to $cur$, then let's increase $cur$ by $1$. Answer is $cur$.",
    "tags": [
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "682",
    "index": "C",
    "title": "Alyona and the Tree",
    "statement": "Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex $1$, every vertex and every edge of which has a number written on.\n\nThe girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex $v$ sad if there is a vertex $u$ in subtree of vertex $v$ such that $dist(v, u) > a_{u}$, where $a_{u}$ is the number written on vertex $u$, $dist(v, u)$ is the sum of the numbers written on the edges on the path from $v$ to $u$.\n\nLeaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.\n\nThus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?",
    "tutorial": "Let's do dfs. Suppose that we now stand at the vertex $u$. Let $v$ be some ancestor of vertex $u$. Then $dist(v, u) = dist(1, u) - dist(1, v)$. If $dist(v, u) > a_{u}$, then the vertex $u$ makes $v$ sad. So you must remove the whole subtree of vertex $u$. Accordingly, it is possible to maintain a minimum among $dist(1, v)$ in dfs, where $v$ is ancestor of $u$ (vertex, in which we now stand). And if the difference between the $dist(1, u)$ and that minimum is greater than $a_{u}$, then remove $a_{u}$ with the whole subtree.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "682",
    "index": "D",
    "title": "Alyona and Strings",
    "statement": "After returned from forest, Alyona started reading a book. She noticed strings $s$ and $t$, lengths of which are $n$ and $m$ respectively. As usual, reading bored Alyona and she decided to pay her attention to strings $s$ and $t$, which she considered very similar.\n\nAlyona has her favourite positive integer $k$ and because she is too small, $k$ does not exceed $10$. The girl wants now to choose $k$ disjoint non-empty substrings of string $s$ such that these strings appear as disjoint substrings of string $t$ and in the same order as they do in string $s$. She is also interested in that their length is maximum possible among all variants.\n\nFormally, Alyona wants to find a sequence of $k$ non-empty strings $p_{1}, p_{2}, p_{3}, ..., p_{k}$ satisfying following conditions:\n\n- $s$ can be represented as concatenation $a_{1}p_{1}a_{2}p_{2}... a_{k}p_{k}a_{k + 1}$, where $a_{1}, a_{2}, ..., a_{k + 1}$ is a sequence of arbitrary strings (some of them may be possibly empty);\n- $t$ can be represented as concatenation $b_{1}p_{1}b_{2}p_{2}... b_{k}p_{k}b_{k + 1}$, where $b_{1}, b_{2}, ..., b_{k + 1}$ is a sequence of arbitrary strings (some of them may be possibly empty);\n- sum of the lengths of strings in sequence is maximum possible.\n\nPlease help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence.\n\nA substring of a string is a subsequence of consecutive characters of the string.",
    "tutorial": "Let's use the method of dynamic programming. Let d[i][j][cnt][end] be answer to the problem for the prefix of string $s$ of length $i$ and for the prefix of string $t$ of length $j$, we have chosen $cnt$ substrings. $end = 1$, if both last characters of the prefixes are included in the maximum subsequence and $end = 0$ otherwise. When the state is d[i][j][cnt][end], you can add the following letters in the string s or t, though it will not be included in the response subsequence. Then d[i + 1][j][cnt][0] = max(d[i + 1][j][cnt][0], d[i][j][cnt][end]), d[i][j + 1][cnt][0] = max(d[i][j + 1][cnt][0], d[i][j][cnt][end]). So the new value of end is 0, because the new letter is not included in the response subsequence. If s[i] = t[j], then if $end = 1$, we can update the d[i + 1][j + 1][k][1] = max(d[i][j][k][end] + 1, d[i + 1][j + 1][k][1]). When we add an element to the response subsequence, the number of substring, which it is composed, will remain the same, because $end = 1$. If $end = 0$, we can update d[i + 1][j + 1][k + 1][1] = max(d[i][j][k][end] + 1, d[i + 1][j + 1][k + 1][1]). In this case, the new characters, which we try to add to the response subsequence, will form a new substring, so in this case we do the transition from the state $k$ to the state $k + 1$. The answer will be the largest number among the states of the d[n][m][k][end], where the values of $k$ and $end$ take all possible values.",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "682",
    "index": "E",
    "title": "Alyona and Triangles",
    "statement": "You are given $n$ points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these $n$ points, which area exceeds $S$.\n\nAlyona tried to construct a triangle with integer coordinates, which contains all $n$ points and which area doesn't exceed $4S$, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from $n$ given points.",
    "tutorial": "Let's find the triangle with maximum area among all triangles whose vertices belong to the set of points. (For $N^{2}$ with the convex hull and the two pointers). We can prove that if we take the triangle, whose vertices are the midpoints of the sides of the triangle with maximum area, the area of such a triangle is not greater than $4S$, and it contains all the points of the set. Let us assume that there is a point lying outside the triangle-response. Then we can get longer height to some side of triangle, so we have chosen a triangle with not maximum area(contradiction).",
    "tags": [
      "geometry",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "685",
    "index": "A",
    "title": "Robbers' watch",
    "statement": "Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches.\n\nFirst, as they know that kingdom police is bad at math, robbers use the positional numeral system \\textbf{with base $7$}. Second, they divide one day in $n$ hours, and each hour in $m$ minutes. Personal watches of each robber are divided in two parts: first of them has the smallest possible number of places that is necessary to display any integer from $0$ to $n - 1$, while the second has the smallest possible number of places that is necessary to display any integer from $0$ to $m - 1$. Finally, if some value of hours or minutes can be displayed using less number of places in base $7$ than this watches have, the required number of zeroes is added at the beginning of notation.\n\nNote that to display number $0$ section of the watches is required to have at least one place.\n\nLittle robber wants to know the number of moments of time (particular values of hours and minutes), such that all digits displayed on the watches are \\textbf{distinct}. Help her calculate this number.",
    "tutorial": "In this problem we use the septimal number system. It is a very important limitation. Let's count how many digits are showed on the watch display and call it $cnt$. If $cnt$ more than $7$, the answer is clearly $0$ (because of pigeonhole principle). If $cnt$ is not greater than $7$, then you can just bruteforces all cases. Depending on the implementation it will be $O(BASE BASE^{BASE})$, $O(BASE^{BASE})$ or $O(BASE BASE!)$, where $BASE = 7$. Actually the most simple implementation is just to cycle between all posible hour:minute combinations and check them. In the worst case, it will work in $O(BASE BASE^{BASE})$.",
    "code": "BASE = 7\n\ndef itov(x):\n    digits = []\n    if x == 0:\n        digits.append(0)\n    while x > 0:\n        digits.append(x % BASE)\n        x //= BASE\n    digits.reverse()\n    return digits\n\ndef gen(pos = 0, minute = False, smaller = False):\n    max_val = max_minute if minute else max_hour\n    if pos >= len(max_val):\n        if minute:\n            return 1\n        else:\n            return gen(0, True)\n    else:\n        ans = 0\n        for digit in range(BASE):\n            if not used[digit] and (smaller or digit <= max_val[pos]):\n                used[digit] = True\n                ans += gen(pos + 1, minute, smaller or digit < max_val[pos])\n                used[digit] = False\n        return ans\n\nn, m = map(int, input().split())\nn -= 1\nm -= 1\nused = [False] * BASE\nmax_hour = itov(n)\nmax_minute = itov(m)\nprint(gen())",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "685",
    "index": "B",
    "title": "Kay and Snowflake",
    "statement": "After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.\n\nOnce upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of $n$ nodes. The root of tree has index $1$. Kay is very interested in the structure of this tree.\n\nAfter doing some research he formed $q$ queries he is interested in. The $i$-th query asks to find a centroid of the subtree of the node $v_{i}$. Your goal is to answer all queries.\n\nSubtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node $v$ is formed by nodes $u$, such that node $v$ is present on the path from $u$ to root.\n\nCentroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).",
    "tutorial": "cdkrot There are many possible approaches. Solution by cdkrot: Look at the all candidates for the centroid of the vertices $v$ subtree. The size of centroid subtree must be at least $\\textstyle{\\frac{1}{2}}$ of the vertex $v$ subtree size. (If it isn't, then after cutting the upper part will have too big size) Choose the vertex with the smallest subtree size satisfying the constraint above. Let's prove, that this vertex is centroid indeed. If it isn't, then after cutting some part will have subtree size greater than $\\textstyle{\\frac{1}{2}}$ of subtree size of query vertex. It isn't upper part (because of constraint above), it is one of our sons. Ouch, it's subtree less than of selected vertex, and it's still greater than $\\textstyle{\\frac{1}{2}}$ of subtree size of query vertex. Contradiction. So we find a centroid. We write the euler tour of tree and we will use a 2D segment tree in order to search for a vertex quickly. Complexity $O(n\\log n+q\\log^{2}n)$ You can consider all answers by one in dfs using this idea. Use std::set for pair (subtree size, vertex number) and at each vertex merge sets obtained from children. (Also known as \"merging sets\" idea) Thus we get the answers for all vertex and we need only output answers for queries. Complexity $O(n\\log^{2}n+q)$ Solution by ch_egor: Solve it for all subtrees. We can solve the problem for some subtree, after solving the problem for all of it's children. Let's choose the heaviest child. Note that the centroid of the child after a certain lifting goes into our centroid. Let's model the lifting. Thus we get the answers for all vertex and we need only output answers for queries. Complexity $O(n + q)$",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <set>\n#include <map>\n#include <cassert>\n#include <algorithm>\n#include <iomanip>\n#include <ctime>\n#include <cmath>\n#include <bitset>\n\n#pragma comment(linker, \"/STACK:256000000\")\n\nusing namespace std;\n\ntypedef long long int int64;\ntypedef long double double80;\n\nconst int INF = (1 << 29) + 5;\nconst int64 LLINF = (1ll << 59) + 5;\nconst int MOD = 1000 * 1000 * 1000 + 7;\n\nconst int MAX_N = 300 * 1000 + 5;\nconst int MAX_Q = 300 * 1000 + 5;\n\nint n, q;\nvector<int> graph[MAX_N];\nint size_of[MAX_N];\nint prev_of[MAX_N];\nint big_subtree[MAX_N];\nint centroid[MAX_N];\n\nbool is_centroid_of_subtree(int v, int c)\n{\n\treturn ((size_of[v] - size_of[c]) * 2 <= size_of[v] && big_subtree[c] * 2 <= size_of[v]);\n}\n\nvoid dfs_calc(int v, int p)\n{\n\tbig_subtree[v] = 0;\n\tsize_of[v] = 1;\n\tprev_of[v] = p;\n\n\tfor (int i = 0; i < graph[v].size(); ++i)\n\t{\n\t\tdfs_calc(graph[v][i], v);\n\t\tsize_of[v] += size_of[graph[v][i]];\n\t\tbig_subtree[v] = max(big_subtree[v], size_of[graph[v][i]]);\n\t}\n}\n\nvoid dfs_centroid(int v)\n{\n\tif (size_of[v] == 1)\n\t{\n\t\tcentroid[v] = v;\n\t}\n\telse\n\t{\n\t\tint ptr = 0;\n\t\tfor (int i = 0; i < graph[v].size(); ++i)\n\t\t{\n\t\t\tdfs_centroid(graph[v][i]);\n\t\t\tif (size_of[graph[v][ptr]] < size_of[graph[v][i]])\n\t\t\t{\n\t\t\t\tptr = i;\n\t\t\t}\n\t\t}\n\n\t\tint c = centroid[graph[v][ptr]];\n\n\t\twhile (!is_centroid_of_subtree(v, c))\n\t\t{\n\t\t\tc = prev_of[c];\n\t\t}\n\n\t\tcentroid[v] = c;\n\t}\n}\n\nint main()\n{\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\n\tscanf(\"%d %d\", &n, &q);\n\n\tint v;\n\tfor (int i = 0; i < n - 1; ++i)\n\t{\n\t\tscanf(\"%d\", &v);\n\t\tgraph[v - 1].push_back(i + 1);\n\t}\n\n\tdfs_calc(0, 0);\n\tdfs_centroid(0);\n\n\tfor (int i = 0; i < q; ++i)\n\t{\n\t\tscanf(\"%d\", &v);\n\t\tprintf(\"%d\\n\", centroid[v - 1] + 1);\n\t}\n\n\tfclose(stdin);\n\tfclose(stdout);\n\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "685",
    "index": "C",
    "title": "Optimal Point",
    "statement": "When the river brought Gerda to the house of the Old Lady who Knew Magic, this lady decided to make Gerda her daughter. She wants Gerda to forget about Kay, so she puts all the roses from the garden underground.\n\nMole, who lives in this garden, now can watch the roses without going up to the surface. Typical mole is blind, but this mole was granted as special vision by the Old Lady. He can watch any underground objects on any distance, even through the obstacles and other objects. However, the quality of the picture depends on the Manhattan distance to object being observed.\n\nMole wants to find an optimal point to watch roses, that is such point with \\textbf{integer coordinates} that the maximum Manhattan distance to the rose is minimum possible.\n\nAs usual, he asks you to help.\n\nManhattan distance between points $(x_{1},  y_{1},  z_{1})$ and $(x_{2},  y_{2},  z_{2})$ is defined as $|x_{1} - x_{2}| + |y_{1} - y_{2}| + |z_{1} - z_{2}|$.",
    "tutorial": "Let's say few words about ternary search. It works correctly, but too slow. It's complexity is $O(n\\log^{3}v)$, where $n = 10^{5}$, and $v = 10^{18}$. Don't use it. Solution. 1) Let's make binary search on answer 2) Consider areas of \"good\" points (with dist $ \\le  mid$) for each source point. 3) Intersect those areas and check for solution. This area can be decsribed by following inequalities: (You can achieve them if you expand modules in inequality \"manhattan distance <= const\") $..  \\le  x + y + z  \\le  ..$ $..  \\le  - x + y + z  \\le  ..$ $..  \\le  x - y + z  \\le  ..$ $..  \\le  x + y - z  \\le  ..$ $..$ denote some constants. If you intersect set of such system, you will get system of the same form, so let's learn how to solve such system. Let's replace some variables: $a = - x + y + z$ $b = x - y + z$ $c = x + y - z$ Then: $x + y + z = a + b + c$ $x = (b + c) / 2$ $y = (a + c) / 2$ $z = (a + b) / 2$ Now the system transforms into: $..  \\le  a  \\le  ..$ $..  \\le  b  \\le  ..$ $..  \\le  c  \\le  ..$ $..  \\le  a + b + c  \\le  ..$ We need to check if the system has solution in integers, also the numbers $a$, $b$, $c$ must be of the same parity (have equal remainder after division by $2$). (This is required for $x$, $y$, $z$ to be integers too) Let's get rid of parity constraint. Bruteforce the parity of $a$, $b$, $c$ (two cases) Make following replacement: $a = 2a' + r$, $b = 2b' + r$, $c = 2c' + r$, where $r = 0$ or $r = 1$. Substitute in equations above, simplify, and gain the same system for $a'$, $b'$, $c'$ without parity constraint. And now the system can be solved greedy (At first set $a$, $b$, $c$ with minimum, and then raise slowly if necessary). Total complexity is $O(n\\log v)$.",
    "code": "// Copyright (C) 2016 Sayutin Dmitry.\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation; version 3\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program; If not, see <http://www.gnu.org/licenses/>.\n\n\n#include <iostream>\n#include <vector>\n#include <stdint.h>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <array>\n#include <queue>\n#include <stack>\n#include <functional>\n#include <utility>\n#include <string>\n#include <assert.h>\n#include <iterator>\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\n\nusing std::vector;\nusing std::map;\nusing std::array;\nusing std::set;\nusing std::string;\n\nusing std::pair;\nusing std::make_pair;\n\nusing std::min;\nusing std::abs;\nusing std::max;\n\nusing std::sort;\nusing std::generate;\nusing std::min_element;\nusing std::max_element;\n\ntemplate <typename T>\nT input() {\n    T res;\n    cin >> res;\n    return res;\n}\n\nstruct coord {\n    int64_t x;\n    int64_t y;\n    int64_t z;\n};\n\nstruct equation {\n    pair<int64_t, int64_t> S;\n    pair<int64_t, int64_t> a;\n    pair<int64_t, int64_t> b;\n    pair<int64_t, int64_t> c;\n};\n\nvector<coord> list;\n\nequation operator+(const equation& e1, const equation& e2) {\n    equation res;\n    res.S = {max(e1.S.first, e2.S.first), min(e1.S.second, e2.S.second)};\n    res.a = {max(e1.a.first, e2.a.first), min(e1.a.second, e2.a.second)};\n    res.b = {max(e1.b.first, e2.b.first), min(e1.b.second, e2.b.second)};\n    res.c = {max(e1.c.first, e2.c.first), min(e1.c.second, e2.c.second)};\n    return res;\n}\n\ncoord get_solution(const equation& eq) {\n    if ((eq.S.first > eq.S.second)\n     or (eq.a.first > eq.a.second)\n     or (eq.b.first > eq.b.second)\n     or (eq.c.first > eq.c.second))\n        return coord {INT64_MAX, INT64_MAX, INT64_MAX};\n        \n     if ((eq.a.first + eq.b.first + eq.c.first > eq.S.second)\n     or (eq.a.second + eq.b.second + eq.c.second < eq.S.first))\n        return coord {INT64_MAX, INT64_MAX, INT64_MAX};\n\n     coord res;\n     res.x = eq.a.first;\n     res.y = eq.b.first;\n     res.z = eq.c.first;\n     int64_t delta = max(int64_t(0), eq.S.first - res.x - res.y - res.z);\n\n     res.x += min(delta, eq.a.second - eq.a.first);\n     delta -= min(delta, eq.a.second - eq.a.first);\n     res.y += min(delta, eq.b.second - eq.b.first);\n     delta -= min(delta, eq.b.second - eq.b.first);\n     res.z += min(delta, eq.c.second - eq.c.first);\n     delta -= min(delta, eq.c.second - eq.c.first);\n\n     assert(delta == 0);\n     \n     return res;\n}\n\nint64_t DIV2(int64_t arg) {\n    return (arg - (arg & 1)) / 2;\n}\n\ncoord can(int64_t MAXANS) {\n    equation eq;\n    eq.S = eq.a = eq.b = eq.c = {INT64_MIN, INT64_MAX};\n    \n    for (const coord& crd: list) {\n        equation nw;\n        nw.S = { crd.x + crd.y + crd.z - MAXANS,  crd.x + crd.y + crd.z + MAXANS};\n        nw.a = {-crd.x + crd.y + crd.z - MAXANS, -crd.x + crd.y + crd.z + MAXANS};\n        nw.b = { crd.x - crd.y + crd.z - MAXANS,  crd.x - crd.y + crd.z + MAXANS};\n        nw.c = { crd.x + crd.y - crd.z - MAXANS,  crd.x + crd.y - crd.z + MAXANS};\n        \n        eq = eq + nw;\n    }\n\n    for (int64_t r = 0; r <= 1; ++r) {\n        equation tr = eq;\n\n        tr.S.first  = DIV2(tr.S.first - 3 * r + 1);\n        tr.a.first  = DIV2(tr.a.first - r + 1);\n        tr.b.first  = DIV2(tr.b.first - r + 1);\n        tr.c.first  = DIV2(tr.c.first - r + 1);\n\n        tr.S.second = DIV2(tr.S.second - 3 * r);\n        tr.a.second = DIV2(tr.a.second - r);\n        tr.b.second = DIV2(tr.b.second - r);\n        tr.c.second = DIV2(tr.c.second - r);\n\n        coord sol = get_solution(tr);\n        if (sol.x != INT64_MAX) {\n            coord ans;\n            ans.x = r + sol.y + sol.z;\n            ans.y = r + sol.x + sol.z;\n            ans.z = r + sol.x + sol.y;\n\n            return ans;\n        }\n    }\n    return coord {INT64_MAX, INT64_MAX, INT64_MAX};\n}\n\nint main() {\n    std::iostream::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    list.reserve(100000);\n    \n    for (size_t T = input<size_t>(); T != 0; --T) {\n        list.resize(input<size_t>());\n        \n        for (coord& crd: list)\n            cin >> crd.x >> crd.y >> crd.z;\n\n        int64_t L = -1; // definitely imposible\n        int64_t R = 3 * int64_t(1000 * 1000 * 1000) * int64_t(1000 * 1000 * 1000) + 10; // definitely possible\n\n        while (R - L > 1) {\n            int64_t M = L + (R - L) / 2;\n            if (can(M).x != INT64_MAX)\n                R = M;\n            else\n                L = M;\n        }\n        coord ans = can(R);\n        cout << ans.x << \" \" << ans.y << \" \" << ans.z << \"\\n\";\n    }\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "685",
    "index": "D",
    "title": "Kay and Eternity",
    "statement": "Snow Queen told Kay to form a word \"eternity\" using pieces of ice. Kay is eager to deal with the task, because he will then become free, and Snow Queen will give him all the world and a pair of skates.\n\nBehind the palace of the Snow Queen there is an infinite field consisting of cells. There are $n$ pieces of ice spread over the field, each piece occupying exactly one cell and no two pieces occupying the same cell. To estimate the difficulty of the task Kay looks at some squares of size $k × k$ cells, with corners located at the corners of the cells and sides parallel to coordinate axis and counts the number of pieces of the ice inside them.\n\nThis method gives an estimation of the difficulty of some part of the field. However, Kay also wants to estimate the total difficulty, so he came up with the following criteria: for each $x$ ($1 ≤ x ≤ n$) he wants to count the number of squares of size $k × k$, such that there are exactly $x$ pieces of the ice inside.\n\nPlease, help Kay estimate the difficulty of the task given by the Snow Queen.",
    "tutorial": "Let's solve this problem with scanline. Go through all rows from left to right and maintain the array in which in $j$ index we will store the number of points in a square with bottom left coordinate $(i, j)$, where i is current row of scanline. This takes $O(MAXCORD^{2})$ time. Note that the set of squares that contain some of the shaded points is not very large, namely - if the point has coordinates $(x, y)$, then the set of left bottom corners of square is defined as ${(a, b)|x - k + 1 < = a < = x, y - k + 1 < = b < = y}$. Let's consider each point $(x, y)$ as the $2$ events: Add one to the all elements with indexes from $y - k + 1$ to $y$ on the row $x - k + 1$ and take one at the same interval on the row $x + 1$. How to calculate answer? Suppose we update the value of a cell on the row $a$, and before it was updated the value $x$ on the row $b$. Let add to the answer for the number of squares containing $x$ points value $a - b$. We can implement the addition of the segment directly and have $O(nk)$ for processing all the events that fit in time limit. To get rid of $O(MAXCORD)$ memory, we need to write all interested in the coordinates before processing events (them no more than nk) and reduce the coordinates in the events. It takes $O(n\\log(n k))$ time and $O(nk)$ memory. Now we can execute the previous point in $O(nk)$ memory. Complexity is $O(n\\log(n k)+n k)$ time and $O(nk)$ memory.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <set>\n#include <map>\n#include <cassert>\n#include <algorithm>\n#include <iomanip>\n#include <ctime>\n#include <cmath>\n#include <bitset>\n\n#pragma comment(linker, \"/STACK:256000000\")\n\nusing namespace std;\n\ntypedef long long int int64;\ntypedef long double double80;\n\nconst int INF = (1 << 29) + 5;\nconst int64 LLINF = (1ll << 59) + 5;\nconst int MOD = 1000 * 1000 * 1000 + 7;\n\nconst int MAX_N = 1000 * 100 + 5;\nconst int MAX_K = 305;\n\n/** Interface */\n\ninline int readChar();\ntemplate <class T = int> inline T readInt();\ntemplate <class T> inline void writeInt(T x);\ninline void writeChar(int x);\ninline void writeWord(const char *s);\ninline void flush();\n\n/** Read */\n\nstatic const int buf_size = 20 * 1000 * 1000;\n\ninline int getChar()\n{\n\tstatic char buf[buf_size];\n\tstatic int len = 0, pos = 0;\n\tif (pos == len)\n\t\tpos = 0, len = fread(buf, 1, buf_size, stdin);\n\tif (pos == len)\n\t\treturn -1;\n\treturn buf[pos++];\n}\n\ninline int readChar()\n{\n\tint c = getChar();\n\twhile (c <= 32)\n\t\tc = getChar();\n\treturn c;\n}\n\ntemplate <class T>\ninline T readInt()\n{\n\tint s = 1, c = readChar();\n\tT x = 0;\n\tif (c == '-')\n\t\ts = -1, c = getChar();\n\twhile ('0' <= c && c <= '9')\n\t\tx = x * 10 + c - '0', c = getChar();\n\treturn s == 1 ? x : -x;\n}\n\ninline int64 readInt64()\n{\n\tint s = 1, c = readChar();\n\tint64 x = 0;\n\tif (c == '-')\n\t\ts = -1, c = getChar();\n\twhile ('0' <= c && c <= '9')\n\t\tx = x * 10 + c - '0', c = getChar();\n\treturn s == 1 ? x : -x;\n}\n\n/** Write */\n\nstatic int write_pos = 0;\nstatic char write_buf[buf_size];\n\ninline void writeChar(int x)\n{\n\tif (write_pos == buf_size)\n\t\tfwrite(write_buf, 1, buf_size, stdout), write_pos = 0;\n\twrite_buf[write_pos++] = x;\n}\n\ninline void flush()\n{\n\tif (write_pos)\n\t\tfwrite(write_buf, 1, write_pos, stdout), write_pos = 0;\n}\n\ntemplate <class T>\ninline void writeInt(T x)\n{\n\tif (x < 0)\n\t\twriteChar('-'), x = -x;\n\n\tchar s[24];\n\tint n = 0;\n\twhile (x || !n)\n\t\ts[n++] = '0' + x % 10, x /= 10;\n\twhile (n--)\n\t\twriteChar(s[n]);\n}\n\ninline void writeInt64(int64 x)\n{\n\tif (x < 0)\n\t\twriteChar('-'), x = -x;\n\n\tchar s[24];\n\tint n = 0;\n\twhile (x || !n)\n\t\ts[n++] = '0' + x % 10, x /= 10;\n\twhile (n--)\n\t\twriteChar(s[n]);\n}\n\ninline void writeWord(const char *s)\n{\n\twhile (*s)\n\t\twriteChar(*s++);\n}\n\nstruct point\n{\n\tint x;\n\tint y;\n};\n\nstruct ask\n{\n\tint l;\n\tint r;\n\tint ptr;\n\tint type;\n};\n\nbool cmp(const ask &a, const ask &b)\n{\n\treturn a.ptr < b.ptr;\n}\n\nint n, k;\npoint arr[MAX_N];\nint cord[MAX_N * 2];\nask asks[MAX_N * 2];\nint cord_len = 0;\nint asks_len = 0;\nbool have_prev_cord[MAX_N * 2];\nbool have_prev_line[MAX_N * 2];\nint last_of_cord[MAX_N * 2];\nint last_of_line[MAX_N * 2];\nint at_cord[MAX_N * 2];\nint at_line[MAX_N * 2];\nint64 answer[MAX_N];\n\nint main()\n{\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\n\tn = readInt();\n\tk = readInt();\n\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tarr[i].x = readInt();\n\t\tarr[i].y = readInt();\n\t\tcord[cord_len++] = arr[i].x;\n\t\tcord[cord_len++] = arr[i].x - k + 1;\n\t}\n\n\tsort(cord, cord + 2 * n);\n\tcord_len = unique(cord, cord + 2 * n) - cord;\n\t\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tasks[asks_len].l = lower_bound(cord, cord + cord_len, arr[i].x - k + 1) - cord;\n\t\tasks[asks_len].r = lower_bound(cord, cord + cord_len, arr[i].x) - cord;\n\t\tasks[asks_len].ptr = arr[i].y - k + 1;\n\t\tasks[asks_len].type = 1;\n\t\t++asks_len;\n\t\tasks[asks_len].l = asks[asks_len - 1].l;\n\t\tasks[asks_len].r = asks[asks_len - 1].r;\n\t\tasks[asks_len].ptr = arr[i].y + 1;\n\t\tasks[asks_len].type = -1;\n\t\t++asks_len;\n\t}\n\n\tsort(asks, asks + asks_len, cmp);\n\tmemset(answer, 0, sizeof(answer));\n\tmemset(last_of_cord, 0, sizeof(last_of_cord));\n\tmemset(last_of_line, 0, sizeof(last_of_line));\n\tmemset(at_cord, 0, sizeof(at_cord));\n\tmemset(at_line, 0, sizeof(at_line));\n\tmemset(have_prev_cord, 0, sizeof(have_prev_cord));\n\tmemset(have_prev_line, 0, sizeof(have_prev_cord));\n\n\tfor (int i = 0; i < asks_len; ++i)\n\t{\n\t\tfor (int j = asks[i].l; j <= asks[i].r; ++j)\n\t\t{\n\t\t\tif (!have_prev_cord[j])\n\t\t\t{\n\t\t\t\thave_prev_cord[j] = true;\n\t\t\t\tlast_of_cord[j] = asks[i].ptr;\n\t\t\t\tat_cord[j] += asks[i].type;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tanswer[at_cord[j]] += asks[i].ptr - last_of_cord[j];\n\n\t\t\t\tlast_of_cord[j] = asks[i].ptr;\n\t\t\t\tat_cord[j] += asks[i].type;\n\t\t\t}\n\t\t\n\n\t\t\tif (j != asks[i].r)\n\t\t\t{\n\t\t\t\tif (!have_prev_line[j])\n\t\t\t\t{\n\t\t\t\t\thave_prev_line[j] = true;\n\t\t\t\t\tlast_of_line[j] = asks[i].ptr;\n\t\t\t\t\tat_line[j] += asks[i].type;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tanswer[at_line[j]] += 1ll * (cord[j + 1] - cord[j] - 1) * (asks[i].ptr - last_of_line[j]);\n\n\t\t\t\t\tlast_of_line[j] = asks[i].ptr;\n\t\t\t\t\tat_line[j] += asks[i].type;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 1; i <= n; ++i)\n\t{\n\t\twriteInt64(answer[i]);\n\t\twriteChar(' ');\n\t}\n\n\tflush();\n\n\tfclose(stdin);\n\tfclose(stdout);\n\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "685",
    "index": "E",
    "title": "Travelling Through the Snow Queen's Kingdom",
    "statement": "Gerda is travelling to the palace of the Snow Queen.\n\nThe road network consists of $n$ intersections and $m$ bidirectional roads. Roads are numbered from $1$ to $m$. Snow Queen put a powerful spell on the roads to change the weather conditions there. Now, if Gerda steps on the road $i$ at the moment of time less or equal to $i$, she will leave the road exactly at the moment $i$. In case she steps on the road $i$ at the moment of time greater than $i$, she stays there forever.\n\nGerda starts at the moment of time $l$ at the intersection number $s$ and goes to the palace of the Snow Queen, located at the intersection number $t$. Moreover, she has to be there at the moment $r$ (or earlier), before the arrival of the Queen.\n\nGiven the description of the road network, determine for $q$ queries $l_{i}$, $r_{i}$, $s_{i}$ and $t_{i}$ if it's possible for Gerda to get to the palace on time.",
    "tutorial": "We propose following solution: Let's solve task with divide & conquer. At first let's lift $l$ to the first index, where $s$ was mentioned And lower the $r$ to the last index, where $t$ was mentioned. This will not affect answers, but will make implementation much more easy. Let's look on all queries. For each query consider it's location relative to centre of edges array. If it's stricly on the left half or on the right half, then solve recursively (You need to implement function like $solve(requests, l, r)$). How to answer on query, if it contains the centre? Let's precalculate two dp's: $dp_{r}[i] =$ bitset of vertices you can from to the $v_{i}$ or $u_{i}$ with $l = m$ and $r = i$. $dp_{l}[i] =$ bitset of vertices you can go to starting from $v_{i}$ or $u_{i}$ with $l = i$ and $r = m - 1$ $v_{i}$ and $u_{i}$ are vertices of i'th edge. Using this dp the answer is yes if and ony if $dp_{l}[l][u] = true$ and $dp_{r}[r][u] = true$ for some $u$. All above can be implemented using bitwise operations. So the time is $O({\\frac{n m\\log m}{32}})$",
    "code": "// Copyright (C) 2016 Sayutin Dmitry.\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation; version 3\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program; If not, see <http://www.gnu.org/licenses/>.\n\n\n#include <iostream>\n#include <vector>\n#include <stdint.h>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <array>\n#include <queue>\n#include <stack>\n#include <functional>\n#include <utility>\n#include <string>\n#include <assert.h>\n#include <iterator>\n#include <bitset>\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\n\nusing std::vector;\nusing std::map;\nusing std::array;\nusing std::set;\nusing std::string;\n\nusing std::pair;\nusing std::make_pair;\n\nusing std::min;\nusing std::abs;\nusing std::max;\n\nusing std::sort;\nusing std::generate;\nusing std::min_element;\nusing std::max_element;\n\n#define size_t uint32_t\n\nstruct Req {\n    size_t L;\n    size_t R;\n    size_t S;\n    size_t T;\n    size_t ID;\n};\n\nstruct Edge {\n    size_t v;\n    size_t u;\n    size_t prev1;\n    size_t prev2;\n    size_t next1;\n    size_t next2;\n};\n\nconst size_t MAXQ = 200000;\nconst size_t MAXN = 1000;\nconst size_t MAXM = 200000;\n\nchar answers[MAXQ];\nEdge list[MAXM];\nvector<size_t> last[MAXN];\n\nstd::bitset<MAXN> masks_r[MAXM / 2 + 10];\nstd::bitset<MAXN> masks_l[MAXM / 2 + 10];\n\nvoid solve_layer(vector<Req>& requests, size_t l, size_t m, size_t r) {\n    bool has = false;\n    for (size_t i = 0; i != requests.size(); ++i)\n        has or_eq (requests[i].L <= m - 1 and requests[i].R >= m);\n    if (not has)\n        return;\n    \n    for (size_t i = 0; i != r - m; ++i) {\n        masks_r[i] = std::bitset<MAXN>();\n        if (list[m + i].prev1 >= m and list[m + i].prev1 != std::numeric_limits<size_t>::max())\n            masks_r[i] |= masks_r[list[m + i].prev1 - m];\n        if (list[m + i].prev2 >= m and list[m + i].prev2 != std::numeric_limits<size_t>::max())\n            masks_r[i] |= masks_r[list[m + i].prev2 - m];\n\n        masks_r[i][list[m + i].v] = true;\n        masks_r[i][list[m + i].u] = true;\n    }\n    \n    for (size_t z = 0; z != m - l; ++z) {\n        size_t i = (m - l) - 1 - z;\n        masks_l[i] = std::bitset<MAXN>();\n        \n        if (list[l + i].next1 < m)\n            masks_l[i] |= masks_l[list[l + i].next1 - l];\n        if (list[l + i].next2 < m)\n            masks_l[i] |= masks_l[list[l + i].next2 - l];\n        masks_l[i][list[l + i].v] = true;\n        masks_l[i][list[l + i].u] = true;\n    }\n\n    for (size_t i = 0; i != requests.size();)\n        if (requests[i].L <= m - 1 and requests[i].R >= m) {\n            answers[requests[i].ID] = (masks_r[requests[i].R - m] & masks_l[requests[i].L - l]).any();\n            std::swap(requests[i], requests.back());\n            requests.pop_back();\n        } else {\n            ++i;\n        }\n}\n\nvoid solve(vector<Req>& requests, size_t l, size_t r) {\n    if (l == r - 1) {\n        for (auto& req: requests)\n            answers[req.ID] = (req.S == list[l].v or req.S == list[l].u)\n                          and (req.T == list[l].v or req.T == list[l].u);\n        return;\n    }\n    size_t m = l + (r - l) / 2;\n    // [l, m), [m, r).\n\n    solve_layer(requests, l, m, r);\n\n    vector<Req> right;\n    for (size_t i = 0; i != requests.size();)\n        if (requests[i].L >= m) {\n            right.push_back(requests[i]);\n            std::swap(requests[i], requests.back());\n            requests.pop_back();\n        } else {\n            ++i;\n        }\n\n    requests.shrink_to_fit();\n    solve(requests, l, m);\n    solve(right, m, r);\n}\n\nint main() {\n    size_t n, m, q;\n    scanf(\"%d %d %d\", &n, &m, &q);\n\n    assert(n <= MAXN);\n    assert(q <= MAXQ);\n    assert(m <= MAXM);\n    \n    std::fill(answers, answers + q, 16);\n    \n    for (size_t i = 0; i != m; ++i) {\n        scanf(\"%d %d\", &list[i].v, &list[i].u);\n        --list[i].v, --list[i].u;\n        list[i].prev1 = list[i].prev2 = list[i].next1 = list[i].next2 = std::numeric_limits<size_t>::max();\n        \n        if (not last[list[i].v].empty()) {\n            list[i].prev1 = last[list[i].v].back();\n            \n            if (list[last[list[i].v].back()].v == list[i].v)\n                list[last[list[i].v].back()].next1 = i;\n            else {\n                list[last[list[i].v].back()].next2 = i;\n            }\n        }\n\n        if (not last[list[i].u].empty()) {\n            list[i].prev2 = last[list[i].u].back();\n            \n            if (list[last[list[i].u].back()].v == list[i].u)\n                list[last[list[i].u].back()].next1 = i;\n            else {\n                list[last[list[i].u].back()].next2 = i;\n            }\n        }\n        \n        last[list[i].v].push_back(i);\n        last[list[i].u].push_back(i);\n    }\n\n    vector<Req> requests;\n    for (size_t i = 0; i != q; ++i) {\n        Req req;\n        scanf(\"%d %d %d %d\", &req.L, &req.R, &req.S, &req.T);\n        --req.L, --req.R, --req.S, --req.T;\n        req.ID = i;\n        \n        auto it1 = std::lower_bound(last[req.S].begin(), last[req.S].end(), req.L);\n        auto it2 = std::upper_bound(last[req.T].begin(), last[req.T].end(), req.R);\n\n        if (it1 == last[req.S].end() or it2 == last[req.T].begin())\n            answers[i] = false;\n        else {\n            req.L = *it1;\n            req.R = *std::prev(it2);\n            if (req.L > req.R)\n                answers[i] = false;\n            else\n                requests.push_back(req);\n        }\n    }\n    \n    solve(requests, 0, m);\n\n    for (size_t i = 0; i != q; ++i) {\n        printf(\"%s\", (answers[i] ? \"Yes\\n\" : \"No\\n\"));\n    }\n    \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "divide and conquer",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "686",
    "index": "A",
    "title": "Free Ice Cream",
    "statement": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.\n\nAt the start of the day they have $x$ ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).\n\nIf a carrier with $d$ ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take $d$ ice cream packs comes to the house, then Kay and Gerda will give him $d$ packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.\n\nKay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.",
    "tutorial": "You just needed to implement the actions described in statement. If you solution failed, then you probably forgot to use 64-bit integers or made some small mistake.",
    "code": "import sys\n\ndef main():\n    n, answer = map(int, sys.stdin.readline().split())\n    sad = 0\n\n    for i in range(n):\n        type_of, cur = sys.stdin.readline().split()\n        cur = int(cur)\n        if type_of == \"+\":\n            answer += cur\n        elif answer >= cur:\n            answer -= cur\n        else:\n            sad += 1\n\n    sys.stdout.write(str(answer) + \" \" + str(sad))\n\nmain()",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "686",
    "index": "B",
    "title": "Little Robber Girl's Zoo",
    "statement": "Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.\n\nThe robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers $l$ and $r$ such that $r - l + 1$ is even. After that animals that occupy positions between $l$ and $r$ inclusively are rearranged as follows: the animal at position $l$ swaps places with the animal at position $l + 1$, the animal $l + 2$ swaps with the animal $l + 3$, ..., finally, the animal at position $r - 1$ swaps with the animal $r$.\n\nHelp the robber girl to arrange the animals in the order of non-decreasing height. You should name at most $20 000$ segments, since otherwise the robber girl will become bored and will start scaring the animals again.",
    "tutorial": "We need to sort an array with strange operations - namely, to swap elements with even and odd indices in subarray of even length. Note that we can change the 2 neighboring elements, simply doing our exchange action for subarray of length $2$ containing these elements. Also, note that $n  \\le  100$, and it is permission to do $20 000$ actions, therefore, we can write any quadratic sort, which changes the neighboring elements in each iteration (bubble sort for example). Complexity $O(n^{2})$",
    "code": "n = int(input())\narr = list(map(int, input().split()))\n\nfor i in range(n - 1, 0, -1):\n    for j in range(i):\n        if arr[j] > arr[j + 1]:\n            arr[j], arr[j + 1] = arr[j + 1], arr[j]\n            print(j + 1, j + 2)",
    "tags": [
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "687",
    "index": "A",
    "title": "NP-Hard Problem",
    "statement": "Recently, Pari and Arya did some research about NP-Hard problems and they found the \\underline{minimum vertex cover} problem very interesting.\n\nSuppose the graph $G$ is given. Subset $A$ of its vertices is called a \\underline{vertex cover} of this graph, if for each edge $uv$ there is at least one endpoint of it in this set, i.e. $u\\in A$ or $v\\in A$ (or both).\n\nPari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.\n\nThey have agreed to give you their graph and you need to find two \\textbf{disjoint} subsets of its vertices $A$ and $B$, such that both $A$ and $B$ are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).",
    "tutorial": "Try to use all of the vertices. Then look at the two vertex covers together in the graph and see how it looks like. Looking at the two vertex covers in the graph, you see there must be no edge $uv$ that $u$ and $v$ are in the same vertex cover. So the two vertex covers form a bipartition of the graph, so the graph have to be bipartite. And being bipartite is also sufficient, you can use each part as a vertex cover. Bipartition can be found using your favorite graph traversing algorithm(BFS or DFS). Here is a tutorial for bipartition of undirected graphs. The complexity is $O(n + m)$.",
    "code": "\t//     . .. ... .... ..... be name khoda ..... .... ... .. .     \\\\\n\n#include <bits/stdc++.h>\nusing namespace std;\n\ninline int in() { int x; scanf(\"%d\", &x); return x; }\nconst int N = 120021;\n\nvector <int> vc[2];\nvector <int> g[N];\nint mark[N];\n\nbool dfs(int v, int color = 2)\n{\n\tmark[v] = color;\n\tvc[color - 1].push_back(v);\n\tfor(int u : g[v])\n\t{\n\t\tif(!mark[u] && dfs(u, 3 - color))\n\t\t\t\treturn 1;\n\t\tif(mark[u] != 3 - color)\n\t\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\tint n, m;\n\tcin >> n >> m;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint u = in() - 1;\n\t\tint v = in() - 1;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\tfor(int i = 0; i < n; i++)\n\t\tif(!mark[i])\n\t\t{\n\t\t     if(g[i].empty())\n\t\t          continue;\n\t\t     if(dfs(i))\n\t\t\t{\n\t\t\t\tcout << -1 << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\tfor(int i = 0; i < 2; i++)\n\t{\n\t\tcout << vc[i].size() << endl;\n\t\tfor(int v : vc[i])\n\t\t\tcout << v + 1 << \" \";\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "687",
    "index": "B",
    "title": "Remainders Game",
    "statement": "Today Pari and Arya are playing a game called Remainders.\n\nPari chooses two positive integer $x$ and $k$, and tells Arya $k$ but not $x$. Arya have to find the value $x\\ {\\mathrm{mod}}\\ k$. There are $n$ ancient numbers $c_{1}, c_{2}, ..., c_{n}$ and Pari has to tell Arya $x\\ \\mathrm{mod}\\ c_{i}$ if Arya wants. Given $k$ and the ancient values, tell us if Arya has a winning strategy independent of value of $x$ or not. Formally, is it true that Arya can understand the value $x\\ {\\mathrm{mod}}\\ k$ for any positive integer $x$?\n\nNote, that $x\\ {\\mathrm{mod}}\\ y$ means the remainder of $x$ after dividing it by $y$.",
    "tutorial": "Assume the answer of a test is No. There must exist a pair of integers $x_{1}$ and $x_{2}$ such that both of them have the same remainders after dividing by any $c_{i}$, but they differ in remainders after dividing by $k$. Find more facts about $x_{1}$ and $x_{2}$! Consider the $x_{1}$ and $x_{2}$ from the hint part. We have $x_{1} - x_{2}  \\equiv  0$ (${\\mathrm{mod~}}c_{i}$) for each $1  \\le  i  \\le  n$. So: $l c m(c_{1},c_{2},\\ldots,c_{n})\\mid x_{1}-x_{2}$ We also have $x_{1}-x_{2}\\neq0$ ($\\mathrm{mod}\\,k$). As a result: $k\\mid l c m(c_{1},c_{2},\\ldots,c_{n})$ We've found a necessary condition. And I have to tell you it's also sufficient! Assume $k\\mid l c m(c_{1},c_{2},\\ldots,c_{n})$, we are going to prove there exists $x_{1}, x_{2}$ such that $x_{1} - x_{2}  \\equiv  0$ (${\\mathrm{mod~}}c_{i}$) (for each $1  \\le  i  \\le  n$), and $x_{1}-x_{2}\\neq0$ ($\\mathrm{mod}\\,k$). A possible solution is $x_{1} = lcm(c_{1}, c_{2}, ..., c_{n})$ and $x_{2} = 2  \\times  lcm(c_{1}, c_{2}, ..., c_{n})$, so the sufficiency is also proved. So you have to check if $lcm(c_{1}, c_{2}, ..., c_{n})$ is divisible by $k$, which could be done using prime factorization of $k$ and $c_{i}$ values. For each integer $x$ smaller than $MAXC$, find it's greatest prime divisor $gpd_{x}$ using sieve of Eratosthenes in $O(M A X C\\log M A X C)$. Then using $gpd$ array, you can write the value of each coin as $p_{1}^{q1}p_{2}^{q2}...p_{m}^{qm}$ where $p_{i}$ is a prime integer and $1  \\le  q_{i}$ holds. This could be done in $O(\\log c_{i})$ by moving from $c_{i}$ to $\\frac{c!}{p!d_{c}}$ and adding $gpd_{ci}$ to the answer. And you can factorize $k$ by the same way. Now for every prime $p$ that $p\\mid k$, see if there exists any coin $i$ that the power of $p$ in the factorization of $c_{i}$ is not smaller than the power of $p$ in the factorization of $k$. Complexity is $O((M A X C+n)\\log M A X C)$.",
    "code": "\t//     . .. ... .... ..... be name khoda ..... .... ... .. .     \\\\\n\n#include <bits/stdc++.h>\nusing namespace std;\n\ninline int in() { int x; scanf(\"%d\", &x); return x; }\nconst long long N = 1200021;\n\nint cntP[N], isP[N];\n\nint main()\n{\n\tfor(int i = 2; i < N; i++)\n\t\tif(!isP[i])\n\t\t\tfor(int j = i; j < N; j += i)\n\t\t\t\tisP[j] = i;\n\tint n = in(), k = in();\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint x = in();\n\t\twhile(x > 1)\n\t\t{\n\t\t\tint p = isP[x];\n\t\t\tint cnt = 0;\n\t\t\twhile(x % p == 0)\n\t\t\t{\n\t\t\t\tcnt++;\n\t\t\t\tx /= p;\n\t\t\t}\n\t\t\tcntP[p] = max(cntP[p], cnt);\n\t\t}\n\t}\n\tbool ok = 1;\n\twhile(k > 1)\n\t{\n\t\tok &= (cntP[isP[k]] > 0);\n\t\tcntP[isP[k]]--;\n\t\tk /= isP[k];\n\t}\n\tcout << (ok ? \"Yes\\n\" : \"No\\n\");\n}",
    "tags": [
      "chinese remainder theorem",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "687",
    "index": "C",
    "title": "The Values You Can Make",
    "statement": "Pari wants to buy an expensive chocolate from Arya. She has $n$ coins, the value of the $i$-th coin is $c_{i}$. The price of the chocolate is $k$, so Pari will take a subset of her coins with sum equal to $k$ and give it to Arya.\n\nLooking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values $x$, such that Arya will be able to make $x$ using some subset of coins with the sum $k$.\n\nFormally, Pari wants to know the values $x$ such that there exists a subset of coins with the sum $k$ such that some subset of this subset has the sum $x$, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum $x$ using these coins.",
    "tutorial": "Use dynamic programming. Let $dp_{i, j, k}$ be true if and only if there exists a subset of the first $i$ coins with sum $j$, that has a subset with sum $k$. There are 3 cases to handle: The $i$-th coin is not used in the subsets. The $i$-th coin is used in the subset to make $j$, but it's not used in the subset of this subset. The $i$-th coin is used in both subsets. So $dp_{i, j, k}$ is equal to $dp_{i - 1, j, k} OR dp_{i - 1, j - ci, k} OR dp_{i - 1, j - ci, k - ci}$. The complexity is $O(nk^{2})$.",
    "code": "\t\t//\t   - -- --- ---- -----be name khoda----- ---- --- -- -\t\t\\\\\n\n#include <bits/stdc++.h>\nusing namespace std;\n\ninline int in() { int x; scanf(\"%d\", &x); return x; }\nconst int N = 505;\n\nbool dp[2][N][N];\n\nint main()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tdp[0][0][0] = 1;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tint now = i % 2;\n\t\tint last = 1 - now;\n\t\tint x = in();\n\t\tfor(int j = 0; j <= k; j++)\n\t\t\tfor(int y = 0; y <= j; y++)\n\t\t\t{\n\t\t\t\tdp[now][j][y] = dp[last][j][y];\n\t\t\t\tif(j >= x)\n\t\t\t\t{\n\t\t\t\t    dp[now][j][y] |= dp[last][j - x][y];\n\t\t\t\t    if(y >= x)\n    \t\t\t\t\tdp[now][j][y] |= dp[last][j - x][y - x];\n\t\t\t\t}\n\t\t\t}\n\t}\n\tvector <int> res;\n\tfor(int i = 0; i <= k; i++)\n\t\tif(dp[n % 2][k][i])\n\t\t\tres.push_back(i);\n\tcout << res.size() << endl;\n\tfor(int x : res)\n\t\tcout << x << \" \";\n\tcout << endl;\n}",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "687",
    "index": "D",
    "title": "Dividing Kingdom II",
    "statement": "Long time ago, there was a great kingdom and it was being ruled by The Great Arya and Pari The Great. These two had some problems about the numbers they like, so they decided to divide the great kingdom between themselves.\n\nThe great kingdom consisted of $n$ cities numbered from $1$ to $n$ and $m$ bidirectional roads between these cities, numbered from $1$ to $m$. The $i$-th road had length equal to $w_{i}$. The Great Arya and Pari The Great were discussing about destructing some prefix (all road with numbers less than some $x$) and suffix (all roads with numbers greater than some $x$) of the roads so there will remain only the roads with numbers $l, l + 1, ..., r - 1$ and $r$.\n\nAfter that they will divide the great kingdom into two pieces (with each city belonging to exactly one piece) such that the hardness of the division is \\textbf{minimized}. The hardness of a division is the \\textbf{maximum length} of a road such that its both endpoints are in the same piece of the kingdom. In case there is no such road, the hardness of the division is considered to be equal to $ - 1$.\n\nHistorians found the map of the great kingdom, and they have $q$ guesses about the $l$ and $r$ chosen by those great rulers. Given these data, for each guess $l_{i}$ and $r_{i}$ print the minimum possible hardness of the division of the kingdom.",
    "tutorial": "Consider the following algorithm to answer a single query: Sort the edges and add them one by one to the graph in decreasing order of their weights. The answer is weight of the first edge, which makes an odd cycle in the graph. Now show that there are only $O(n)$ effective edges, which removing them may change the answer of the query. Use this idea to optimize your solution. First, let's solve a single query separately. Sort edges from interval [l, r] in decreasing order of weights. Using dsu, we can find longest prefix of these edges, which doesn't contains odd cycle. (Graph will be bipartite after adding these edges.) The answer will be weight of the next edge. (We call this edge \"bottleneck\"). Why it's correct? Because if the answer is $w$, then the we can divide the graph in a way that none of the edges in the same part have value greater than $w$. So the graph induced by the edges with value greater than $w$ must be bipartite. And if this graph is bipartite, then we can divide the graph into two parts as the bipartition, so no edge with value greater than $w$ will be in the same part, and the answer is at most $w$. Let's have a look at this algorithm in more details. For each vertex, we keep two values in dsu: Its parent and if its part differs from its parent or not. We keep the second value equal to \"parity of length of the path in original graph, between this node and its parent\". We can divide the graph anytime into two parts, walking from one vertex to its parent and after reaching the root, see if the starting vertex must be in the same part as the root or not. In every connected component, there must not exist any edge with endpoints in the same part. After sorting the edges, there are 3 possible situations for an edge when we are adding it to the graph: The endpoints of this edge are between two different components of the current graph. Now we must merge these two components, and update the part of the root of one of the components. The endpoints of this edge are in the same component of the current graph, and they are in different parts of this component. There is nothing to do. The endpoints of this edge are in the same component of the current graph, and they are also in the same part of this component. This edge is the \"bottleneck\" and we can't keep our graph bipartite after adding it, so we terminate the algorithm. We call the edges of the first and the third type \"valuable edges\". The key observation is: If we run above algorithm on the valuable edges, the answer remains the same. Proof idea: The edges of the first type are spanning trees of connected components of the graph, and with a spanning tree of a bipartite graph, we can uniquely determine if two vertices are in the same part or not. So if we can ignore all other edges and run our algorithm on these valuable edges, we have $O(n)$ edges instead of original $O(n^{2})$ and the answer is the same. We answer the queries using a segment tree on the edges. In each node of this tree, we run the above algorithm and memorize the valuable edges. By implementing carefully (described here), making the segment tree could be done in $O(m\\log m\\alpha(n))$. Now for each query $[l, r]$, you can decompose $[l, r]$ into $O(\\log n)$ segments in segment tree and each one has $O(n)$ valuable edges. Running the naive algorithm on these edges lead to an $O(n\\log n)$ solution for each query, which fits in time limit.",
    "code": "\t//     . .. ... .... ..... be name khoda ..... .... ... .. .     \\\\\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n\ninline int in() { int x; scanf(\"%d\", &x); return x; }\nconst int N = 2002, M = (1 << 20), Q = 1001, S = 2 * M;\n\n#define rank PAP\n\nstruct Edge\n{\n\tint u, v, w;\n\tEdge(int u = 0, int v = 0, int w = 0):v(v), u(u), w(w) { }\n\tbool operator <(const Edge &e) const { return w < e.w; }\n};\n\nstruct Segment\n{\n\tint l, r;\n\tSegment(int l = 0, int r = 0): l(l), r(r) { }\n};\n\ntypedef vector <Edge> Edges;\n\nint n, m, q;\nEdge es[M];\nEdges seg[S];\nSegment range[S];\nint par[N], cost[N], rank[N];\n\nSegment merge(Segment l, Segment r) { return Segment(l.l, r.r); }\n\nvoid clear(Edges &es)\n{\n\tfor(Edge e : es)\n\t{\n\t\tpar[e.v] = par[e.u] = -1;\n\t\tcost[e.v] = cost[e.u] = 0;\n\t\trank[e.v] = rank[e.u] = 1;\n\t}\n}\n\nint root(int v) \n{ \n\tif(par[v] == -1)\n\t\treturn v;\n\tint u = root(par[v]);\n\tcost[v] ^= cost[par[v]];\n\treturn par[v] = u;\n}\n\nint parity(int v)\n{\n\troot(v);\n\treturn cost[v];\n}\n\nint merge(Edge e)\n{\n\tif(rank[root(e.u)] > rank[root(e.v)])\n\t\tswap(e.u, e.v);\n\tif(root(e.u) == root(e.v))\n\t{\n\t\tif(parity(e.u) == parity(e.v))\n\t\t\treturn 2;\n\t\treturn 0;\n\t}\n\tint u = root(e.u);\n\tint v = root(e.v);\n\tcost[u] ^= (parity(e.u) ^ 1 ^ parity(e.v));\n\tpar[u] = root(v);\n\trank[v] += rank[u];\n\treturn 1;\n}\n\nbool hasOddCycle;\n\nEdges merge(Edges &a, Edges &b)\n{\n\tEdges c;\n\tmerge(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c));\n\tclear(c);\n\tEdges res;\n\tfor(int i = c.size() - 1; i >= 0; i--)\n\t{\n\t\tint x = merge(c[i]);\n\t\tif(x)\n\t\t\tres.push_back(c[i]);\n\t\tif(x == 2)\n\t\t{\n\t\t\thasOddCycle = 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\treverse(res.begin(), res.end());\n\treturn res;\n}\n\nvoid make()\n{\n\tfor(int i = S - 1; i; i--)\n\t{\n\t\tif(i >= M)\n\t\t{\n\t\t\trange[i] = Segment(i - M, i - M + 1);\n\t\t\tif(i - M < m)\n\t\t\t\tseg[i].push_back(es[i - M]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\trange[i] = merge(range[i * 2], range[i * 2 + 1]);\n\t\t\tseg[i] = merge(seg[i * 2], seg[i * 2 + 1]);\n\t\t}\n\t}\n}\n\nint solve(Segment s)\n{\n\tEdges es;\n\thasOddCycle = 0;\n\tfor(int l = s.l + M, r = s.r + M; l < r; l /= 2, r /= 2)\n\t{\n\t\tif(l % 2)\n\t\t\tes = merge(es, seg[l++]);\n\t\tif(r % 2)\n\t\t\tes = merge(es, seg[--r]);\n\t}\n\tif(hasOddCycle)\n\t\treturn es[0].w;\n\treturn -1;\n}\n\nint main()\n{\n\tcin >> n >> m >> q;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tes[i].u = in() - 1;\n\t\tes[i].v = in() - 1;\n\t\tes[i].w = in();\n\t}\n\tmake();\n\twhile(q--)\n\t{\n\t\tint l = in() - 1, r = in();\n\t\tcout << solve(Segment(l, r)) << \"\\n\";\n\t}\n}",
    "tags": [
      "brute force",
      "data structures",
      "dsu",
      "graphs",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "687",
    "index": "E",
    "title": "TOF",
    "statement": "Today Pari gave Arya a cool graph problem. Arya wrote a non-optimal solution for it, because he believes in his ability to optimize non-optimal solutions. In addition to being non-optimal, his code was buggy and he tried a lot to optimize it, so the code also became dirty! He keeps getting Time Limit Exceeds and he is disappointed. Suddenly a bright idea came to his mind!\n\nHere is how his dirty code looks like:\n\n\\begin{verbatim}\ndfs(v)\n{\nset count[v] = count[v] + 1\nif(count[v] < 1000)\n{\nforeach u in neighbors[v]\n{\nif(visited[u] is equal to false)\n{\ndfs(u)\n}\nbreak\n}\n}\nset visited[v] = true\n}\nmain()\n{\ninput the digraph()\nTOF()\nforeach 1<=i<=n\n{\nset count[i] = 0 , visited[i] = false\n}\nforeach 1 <= v <= n\n{\nif(visited[v] is equal to false)\n{\ndfs(v)\n}\n}\n... // And do something cool and magical but we can't tell you what!\n}\n\\end{verbatim}\n\nHe asks you to write the \\underline{TOF} function in order to optimize the running time of the code with minimizing the number of calls of the \\underline{dfs} function. The input is a directed graph and in the \\underline{TOF} function you have to rearrange the edges of the graph in the list \\underline{neighbors} for each vertex. The number of calls of \\underline{dfs} function depends on the arrangement of \\underline{neighbors} of each vertex.",
    "tutorial": "Looking at the code in the statement, you can see only the first edge in neighbors of each node is important. So for each vertex with at least one outgoing edge, you have to choose one edge and ignore the others. After this the graph becomes in the shape of some cycles with possible branches, and some paths. The number of dfs calls equals to $998  \\times  ($ sum of sizes of cycles $) + n +$ number of cycles. The goal is to minimize the sum of cycle sizes. Or, to maximize the number of vertices which are not in any cycle. Name them good vertices. If there exists a vertex $v$ without any outgoing edge, we can make all of the vertices that $v$ is reachable from them good. Consider the dfs-tree from $v$ in the reverse graph. You can choose the edge $u\\rightarrow p d r_{u}$ from this tree as the first edge in neighbors[u], in order to make all of these vertices good. Vertices which are not in the sink strongly connected components could become good too, by choosing the edges from a path starting from them and ending in a sink strongly connected component. In a sink strongly connected component, there exists a path from every vertex to others. So we can make every vertex good except a single cycle, by choosing the edges in the paths from other nodes to this cycle and the cycle edges. So, every vertices could become good except a single cycle in every sink strongly connected component. And the length of those cycles must be minimized, so we can choose the smallest cycle in every sink strongly connected component and make every other vertices good. Finding the smallest cycle in a graph with $n$-vertex and $m$ edges could be done in $O(n(n + m))$ with running a BFS from every vertex, so finding the smallest cycle in every sink strongly connected component is $O(n(n + m))$ overall.",
    "code": "\t//     . .. ... .... ..... be name khoda ..... .... ... .. .     \\\\\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n\ninline int in() { int x; scanf(\"%d\", &x); return x; }\nconst int N = 5005;\n\nint comp[N], bfsDist[N], bfsPar[N];\nvector <int> g[N], gR[N];\nbool mark[N], inCycle[N];\n\nbool dfs(int v, vector <int> *g, vector <int> &nodes)\n{\n\tmark[v] = 1;\n\tfor(int u : g[v])\n\t\tif(!mark[u])\n\t\t\tdfs(u, g, nodes);\n\tnodes.push_back(v);\n}\n\nint findSmallestCycle(vector <int> vs)\n{\n\tvector <int> cycle;\n\tfor(int root : vs)\n\t{\n\t\tfor(int v : vs)\n\t\t{\n\t\t\tbfsDist[v] = 1e9;\n\t\t\tbfsPar[v] = -1;\n\t\t}\n\t\tbfsDist[root] = 0;\n\t\tqueue <int> q;\n\t\tq.push(root);\n\t\tbool cycleFound = 0;\n\t\twhile(q.size() && !cycleFound)\n\t\t{\n\t\t\tint v = q.front();\n\t\t\tq.pop();\n\t\t\tfor(int u : g[v])\n\t\t\t{\n\t\t\t\tif(u == root)\n\t\t\t\t{\n\t\t\t\t\tcycleFound = 1;\n\t\t\t\t\tint curLen = bfsDist[v];\n\t\t\t\t\tif(cycle.empty() || curLen < cycle.size())\n\t\t\t\t\t{\n\t\t\t\t\t\tcycle.clear();\n\t\t\t\t\t\tfor(; v != -1; v = bfsPar[v])\n\t\t\t\t\t\t\tcycle.push_back(v);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(bfsDist[u] > bfsDist[v] + 1)\n\t\t\t\t{\n\t\t\t\t\tbfsDist[u] = bfsDist[v] + 1;\n\t\t\t\t\tbfsPar[u] = v;\n\t\t\t\t\tq.push(u);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn cycle.size();\n}\n\nint main()\n{\n\tint n, m;\n\tcin >> n >> m;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint u = in() - 1;\n\t\tint v = in() - 1;\n\t\tg[u].push_back(v);\n\t\tgR[v].push_back(u);\n\t}\n\tvector <int> order;\n\tfor(int i = 0; i < n; i++)\n\t\tif(!mark[i])\n\t\t\tdfs(i, g, order);\n\n\tfill(mark, mark + n, 0);\n\tfill(comp, comp + n, -1);\n\tint inCycle = 0, nCycle = 0;\n\tfor(; order.size(); order.pop_back())\n\t{\n\t\tint v = order.back();\n\t\tif(mark[v])\n\t\t\tcontinue;\n\t\tvector <int> curComp;\n\t\tdfs(v, gR, curComp);\n\t\tbool isSink = true;\n\t\tfor(int u : curComp)\n\t\t\tcomp[u] = v;\n\t\tfor(int u : curComp)\n\t\t\tfor(int k = 0; k < g[u].size(); k++)\n\t\t\t\tif(comp[g[u][k]] != v)\n\t\t\t\t\tisSink = false;\n\t\tif(isSink)\n\t\t{\n\t\t\tint x = findSmallestCycle(curComp);\n\t\t\tif(x > 0)\n\t\t\t{\n\t\t\t    nCycle++;\n\t\t\t    inCycle += x;\n\t\t\t}\n\t\t}\n\t}\n\tcout << 999 * inCycle + (n - inCycle) + nCycle << endl;\n\n}",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2900
  },
  {
    "contest_id": "688",
    "index": "A",
    "title": "Opponents",
    "statement": "Arya has $n$ opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.\n\nFor each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of \\textbf{consecutive} days that he will beat all present opponents.\n\nNote, that if some day there are no opponents present, Arya still considers he beats all the present opponents.",
    "tutorial": "Let's find out for each row of the given matrix if it is completely consisting of ones or not. Make another array $canWin$, and set $canWin_{i}$ equal to one if the $i$-th row consists at least one zero. Then the problem is to find the maximum subsegment of $canWin$ array, consisting only ones. It can be solved by finding for each element of $canWin$, the closest zero to it from left. The complexity of this solution is $O(nd)$, but the limits allow you to solve the problem in $O(nd^{2})$ by iterating over all possible subsegments and check if each one of them is full of ones or not.",
    "code": "n, d = map(int, raw_input().split())\ncur = 0\nans = 0\nfor i in range(d):\n    s = raw_input()\n    if (s == '1' * n):\n        cur = 0\n    else:\n        cur += 1\n    ans = max(ans, cur)\nprint ans",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "688",
    "index": "B",
    "title": "Lovely Palindromes",
    "statement": "Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example $12321$, $100001$ and $1$ are palindrome numbers, while $112$ and $1021$ are not.\n\nPari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a $2$-digit $11$ or $6$-digit $122221$), so maybe she could see something in them.\n\nNow Pari asks you to write a program that gets a huge integer $n$ from the input and tells what is the $n$-th even-length positive palindrome number?",
    "tutorial": "Try to characterize even-length palindrome numbers. For simplifications, in the following solution we define lovely integer as an even-length positive palindrome number. An even-length positive integer is lovely if and only if the first half of its digits is equal to the reverse of the second half. So if $a$ and $b$ are two different $2k$-digit lovely numbers, then the first $k$ digits of $a$ and $b$ differ in at least one position. So $a$ is smaller than $b$ if and only if the first half of $a$ is smaller than the the first half of $b$. Another useful fact: The first half of a a lovely number can be any arbitrary positive integer. Using the above facts, it's easy to find the first half of the $n$-th lovely number - it exactly equals to integer $n$. When we know the first half of a lovely number, we can concatenate it with its reverse to restore the lovely integer. To sum up, the answer can be made by concatenating $n$ and it's reverse together. The complexity of this solution is $O(\\log n)$.",
    "code": "s = raw_input()\nprint s + ''.join(reversed(s))",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "689",
    "index": "A",
    "title": "Mike and Cellphone",
    "statement": "While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:\n\n\\begin{center}\n$\\frac{1}{\\left|\\begin{array}{l l}{1\\prod2\\sqrt{2\\mid3}}\\\\ {4}\\end{array}\\right|}}{\\left|\\begin{array}{l}{1\\left|2\\sqrt{3}}\\\\ {\\left|\\frac{4}{7}\\displaystyle\\left|8\\mid9\\right|}}\\\\ {\\left|0\\right|}\\end{array}\\right|}$\n\\end{center}\n\nTogether with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number \"586\" are the same as finger movements for number \"253\":\n\nMike has already put in a number by his \"finger memory\" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?",
    "tutorial": "We can try out all of the possible starting digits, seeing if we will go out of bounds by repeating the same movements. If it is valid and different from the correct one, we output \"NO\", otherwise we just output \"YES\".",
    "code": "n = int(raw_input())\ns = raw_input()\na = []\nfor i in range(10):\n\ta.append(True)\nfor i in range(n):\n\tc = int(s[i])\n\ta[c] = False\ninc = 0\nif a[1] and a[2] and a[3]:\n\tinc = -3\nif a[7] and a[9] and a[0]:\n\tinc = +3\nif a[1] and a[4] and a[7] and a[0]:\n\tinc = -1\nif a[3] and a[6] and a[9] and a[0]:\n\tinc = +1\nif inc == 0:\n\tprint(\"YES\")\nelse:\n\tprint(\"NO\")",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "689",
    "index": "B",
    "title": "Mike and Shortcuts",
    "statement": "Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.\n\nCity consists of $n$ intersections numbered from $1$ to $n$. Mike starts walking from his house located at the intersection number $1$ and goes along some sequence of intersections. Walking from intersection number $i$ to intersection $j$ requires $|i - j|$ units of energy. The total energy spent by Mike to visit a sequence of intersections $p_{1} = 1, p_{2}, ..., p_{k}$ is equal to $\\sum_{i=1}^{k-1}|p_{i}-p_{i+1}|$ units of energy.\n\nOf course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only $1$ unit of energy. There are exactly $n$ shortcuts in Mike's city, the $i^{th}$ of them allows walking from intersection $i$ to intersection $a_{i}$ ($i ≤ a_{i} ≤ a_{i + 1}$) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence $p_{1} = 1, p_{2}, ..., p_{k}$ then for each $1 ≤ i < k$ satisfying $p_{i + 1} = a_{pi}$ and $a_{pi} ≠ p_{i}$ Mike will spend \\textbf{only $1$ unit of energy} instead of $|p_{i} - p_{i + 1}|$ walking from the intersection $p_{i}$ to intersection $p_{i + 1}$. For example, if Mike chooses a sequence $p_{1} = 1, p_{2} = a_{p1}, p_{3} = a_{p2}, ..., p_{k} = a_{pk - 1}$, he spends exactly $k - 1$ units of total energy walking around them.\n\nBefore going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each $1 ≤ i ≤ n$ Mike is interested in finding minimum possible total energy of some sequence $p_{1} = 1, p_{2}, ..., p_{k} = i$.",
    "tutorial": "We can build a complete graph where the cost of going from point $i$ to point $j$ if $|i - j|$ if $a_{i}! = j$ and $1$ if $a_{i} = j$.The we can find the shortest path from point 1 to point $i$.One optimisation is using the fact that there is no need to go from point $i$ to point $j$ if $j  \\neq  s[i]$,$j  \\neq  i - 1$,$j  \\neq  i + 1$ so we can add only edges $(i, i + 1)$,$(i, i - 1)$,$(i, s[i])$ with cost 1 and then run a bfs to find the shortest path for each point $i$. You can also solve the problem by taking the best answer from left and from the right and because $a_{i}  \\le  a_{i + 1}$ then we can just iterate for each $i$ form $1$ to $n$ and get the best answer from left and maintain a deque with best answer from right. Complexity is $O(N)$.",
    "code": "import Queue\nn = int(raw_input())\na = raw_input().split(' ')\nused = []\nd = []\nfor i in range(0, n):\n    used.append(False)\n    d.append(-1)\nq = Queue.Queue()\nq.put(0)\nd[0] = 0\nwhile not(q.empty()):\n    v = q.get()\n    for dl in range(-1, +2):\n        u = v + dl\n        if 0 <= u and u < n and d[u] == -1:\n            d[u] = d[v] + 1\n            q.put(u)\n    u = int(a[v]) - 1\n    if d[u] == -1:\n        d[u] = d[v] + 1\n        q.put(u)\nfor i in range(0, n):\n    print(d[i])",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "689",
    "index": "C",
    "title": "Mike and Chocolate Thieves",
    "statement": "Bad news came to Mike's village, some thieves stole a bunch of chocolates from the local factory! Horrible!\n\nAside from loving sweet things, thieves from this area are known to be very greedy. So after a thief takes his number of chocolates for himself, the next thief will take exactly $k$ times more than the previous one. The value of $k$ ($k > 1$) is a secret integer known only to them. It is also known that each thief's bag can carry at most $n$ chocolates (if they intend to take more, the deal is cancelled) and that there were \\textbf{exactly four} thieves involved.\n\nSadly, only the thieves know the value of $n$, but rumours say that the numbers of ways they could have taken the chocolates (for a fixed $n$, but not fixed $k$) is $m$. Two ways are considered different if one of the thieves (they should be numbered in the order they take chocolates) took different number of chocolates in them.\n\nMike want to track the thieves down, so he wants to know what their bags are and value of $n$ will help him in that. Please find \\textbf{the smallest possible} value of $n$ or tell him that the rumors are false and there is no such $n$.",
    "tutorial": "Suppose we want to find the number of ways for a fixed $n$. Let $a, b, c, d$ ( $0 < a < b < c < d  \\le  n$ ) be the number of chocolates the thieves stole. By our condition, they have the form $b = ak, c = ak^{2}, d = ak^{3}$,where $k$ is a positive integer. We can notice that $2\\leq k\\leq{\\sqrt{\\frac{n}{a}}}\\leq{\\sqrt{n}}$ , so for each $k$ we can count how many $a$ satisfy the conditions $0 < a < ak < ak^{2} < ak^{3}  \\le  n$, their number is $\\left|{\\frac{n}{k^{3}}}\\right\\rangle$. Considering this, the final answer is $\\textstyle\\sum_{k=2}^{\\sqrt{n}}\\left\\lfloor{\\frac{n}{k^{3}}}\\right\\rfloor$. Notice that this expression is non-decreasing as $n$ grows, so we can run a binary search for $n$. Total complexity: Time ~ $O(I o q(10^{16})\\ast{\\sqrt{M}})$, Space: $O(1)$.",
    "code": "\n# include <bits/stdc++.h>\nusing namespace std;\n\nlong long get(long long n)\n{\n    long long ans = 0;\n    for (long long i = 2; i * i * i <= n;++i)\n        ans += n / (1ll*i * i * i);\n    return ans;\n}\n\nint main()\n{\n    long long m,n=-1;\n    cin>>m;\n    \n    long long l=0,r=5e15;\n    while (l<r)\n    {\n        long long mid = (l+r)/2;\n        if (get(mid)<m) l=mid+1;\n        else r=mid;\n    }\n    \n    if (get(l)==m) n=l;\n\n    cout << n << '\\n';\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "combinatorics",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "689",
    "index": "D",
    "title": "Friends and Subsequences",
    "statement": "Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows?\n\nEvery one of them has an integer sequences $a$ and $b$ of length $n$. Being given a query of the form of pair of integers $(l, r)$, Mike can instantly tell the value of $\\operatorname*{m}_{i\\geq i}^{\\mathsf{P a x}}a_{i}$ while !Mike can instantly tell the value of $\\operatorname*{min}_{i=l}b_{i}$.\n\nNow suppose a robot (you!) asks them all possible different queries of pairs of integers $(l, r)$ $(1 ≤ l ≤ r ≤ n)$ (so he will make exactly $n(n + 1) / 2$ queries) and counts how many times their answers coincide, thus for how many pairs $\\operatorname*{m}_{i=l}^{r}a_{i}=\\operatorname*{min}_{i=l}b_{i}$ is satisfied.\n\nHow many occasions will the robot count?",
    "tutorial": "First of all it is easy to see that if we fix $l$ then have $\\operatorname*{m}_{i=l}^{r}a_{i}-\\operatorname*{min}_{i=l}b_{i}\\leq\\operatorname*{max}_{i=l}a_{i}-\\operatorname*{min}_{i=l}b_{i}$. So we can just use binary search to find the smallest index $r_{min}$ and biggest index $r_{max}$ that satisfy the equality and add $r_{max} - r_{min} + 1$ to our answer. To find the $min$ and $max$ values on a segment $[l, r]$ we can use Range-Minimum Query data structure. The complexity is $O(n\\log n)$ time and $O(n\\log n)$ space.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = int(1e6) + 5;\nint a[N], b[N], n;\nint lfa[N], rga[N], lfb[N], rgb[N], nxt[N];\n\nvoid calc_max(int *a, int *lf, int *rg) {\n\tstack <int> st;\n\ta[n] = int(1e9) + 1;\n\n\tfor (int i = 0; i <= n; ++i) {\n\t\twhile (!st.empty() && a[st.top()] < a[i]) {\n\t\t\trg[st.top()] = i;\n\t\t\tst.pop();\n\t\t}\n\n\t\tlf[i] = st.empty() ? -1 : st.top();\n\t\tst.push(i);\n\t}\n}\n\nint naive() {\n\tint res = 0;\n\tfor (int i = 0; i < n; ++i)\n\t\tfor (int j = i; j < n; ++j)\n\t\t\tif (*max_element(a + i, a + j + 1) == *min_element(b + i, b + j + 1))\n\t\t\t\tres++;\n\treturn res;\n}\n\nbool read() {\n\n\tif (!(cin >> n))\n\t\treturn false;\n\n\tfor (int i = 0; i < n; ++i)\n\t\tassert(scanf(\"%d\", &a[i]) == 1);\n\tfor (int i = 0; i < n; ++i)\n\t\tassert(scanf(\"%d\", &b[i]) == 1);\n}\n\nvoid solve() {\n\tcalc_max(a, lfa, rga);\n\n\tfor (int i = 0; i < n; ++i)\n\t\tb[i] = -b[i];\n\tcalc_max(b, lfb, rgb);\n\n\tmap <int, int> pos, last;\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tb[i] = -b[i];\n\t\tnxt[i] = n;\n\n\t\tif (!pos.count(b[i]))\n\t\t\tpos[b[i]] = i;\n\t\telse\n\t\t\tnxt[last[b[i]]] = i;\n\t\tlast[b[i]] = i;\n\t}\n\n\tlong long res = 0;\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (!pos.count(a[i]))\n\t\t\tcontinue;\n\n\t\tint pb = pos[a[i]];\n\n\t\twhile (nxt[pb] <= i) {\n\t\t\tpb = nxt[pb];\n\t\t\tif (lfb[pb] != -1 && b[lfb[pb]] == b[pb])\n\t\t\t\tlfb[pb] = lfb[lfb[pb]];\n\t\t}\n\t\tpos[a[i]] = pb;\n\n\t\tfor (int t = 0; t < 2 && pb < n; ++t, pb = nxt[pb]) {\n\t\t\tint lf = max(lfa[i], lfb[pb]);\n\t\t\tint rg = min(rga[i], rgb[pb]);\n\n\t\t\tif (lf < min(i, pb) && max(i, pb) < rg)\n\t\t\t\tres += (min(i, pb) - lf) * 1ll * (rg - max(i, pb));\n\t\t}\n\t}\n\n\tcout << res << endl;\n}\n\nint main() {\n\twhile (read())\n\t\tsolve();\n\treturn 0;\n}\n\n",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2100
  },
  {
    "contest_id": "689",
    "index": "E",
    "title": "Mike and Geometry Problem",
    "statement": "Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define $f([l, r]) = r - l + 1$ to be the number of integer points in the segment $[l, r]$ with $l ≤ r$ (say that $f({\\mathcal{O}})=0$). You are given two integers $n$ and $k$ and $n$ closed intervals $[l_{i}, r_{i}]$ on $OX$ axis and you have to find:\n\n\\begin{center}\n$\\sum_{1<i_{1}<i_{2}<...<i_{k}<n}f([l_{i_{1}},r_{i_{1}}]\\cap[l_{i_{2}},r_{i_{2}}]\\cap...\\cap\\left[l_{i_{k}},r_{i_{k}}\\right]).$\n\\end{center}\n\nIn other words, you should find the sum of the number of integer points in the intersection of any $k$ of the segments.\n\nAs the answer may be very large, output it modulo $1000000007$ ($10^{9} + 7$).\n\nMike can't solve this problem so he needs your help. You will help him, won't you?",
    "tutorial": "Let define the following propriety:if the point $i$ is intersected by $p$ segments then in our sum it will be counted $\\scriptstyle{\\binom{p}{k}}$ times,so our task reduce to calculate how many points is intersected by $i$ intervals $1  \\le  i  \\le  n$.Let $dp[i]$ be the number of points intersected by $i$ intervals.Then our answer will be $\\sum_{i=k}^{n}\\left({}_{k}^{'}\\right)*d p[i]$. We can easily calculate array $dp$ using a map and partial sum trick,here you can find about it. The complexity and memory is $O(n\\log n)$ and $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define ll long long\n#define ld long double\n\nusing namespace std;\n\nconst int mod = 1e9+7;\n\nll pp(ll x, int y)\n{\n\tif (!y) return 1;\n\tll t = pp(x,y/2);\n\tt = 1ll*t*t;\n\tt%=mod;\n\tif (y%2) t*=1ll*x;\n\tt%=mod;\n\treturn t;\n}\n\nint n,k;\n\nstruct s\n{\n\tint x;\n\tint y;\n};\n\ns a[2*200000];\n\nll c[200001];\n\nvoid gen()\n{\n\tll b = 1;\n\t\n\tc[k] = 1;\n\tfor (int i=k+1; i<=n; i++)\n\t\tb*=\ti,b%=mod,b*=pp(i-k,mod-2),b%=mod,c[i]=b;\n}\n\n\nll ans = 0;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n\tcin>>n>>k;\n\t\n\tgen();\n\t\n\tfor (int i=0; i<n; i++)\n\t\tcin>>a[2*i].x>>a[2*i+1].x,a[2*i].y = 1,a[2*i+1].y=-1,a[2*i+1].x++;\n\t\t\n\tsort(a,a+2*n, [] (s x, s y) { if (x.x!=y.x) return (x.x<y.x); return (x.y>y.y);});\n\t\n\tint last = a[0].x;\n\tint now = 0;\n\t\n\tfor (int i=0; i<2*n;)\n\t{\n\t\tint d = a[i].x;\n\t\tans += 1ll * c[now] * (d-last);\n\t\tans%=mod;\n\t\twhile (a[i].x==d)\n\t\t\tnow+=a[i].y,i++;\n\t\tlast = d;\n\t}\n\t\n\tcout<<ans;\n\t\t\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "geometry",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "691",
    "index": "A",
    "title": "Fashion in Berland",
    "statement": "According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.\n\nYou are given a jacket with $n$ buttons. Determine if it is fastened in a right way.",
    "tutorial": "In this problem you should simply check the conditions from the problem statement. Complexity: $O(n)$.",
    "code": "const int N = 1010;\n\nint n, a[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(cin >> a[i]);\n\treturn true;\n}\n\nvoid solve() {\n\tint cnt = accumulate(a, a + n, 0);\n\tif (n == 1) puts(cnt == 1 ? \"YES\" : \"NO\");\n\telse puts(cnt == n - 1 ? \"YES\" : \"NO\");\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "691",
    "index": "B",
    "title": "s-palindrome",
    "statement": "Let's call a string \"s-palindrome\" if it is symmetric about the middle of the string. For example, the string \"oHo\" is \"s-palindrome\", but the string \"aa\" is not. The string \"aa\" is not \"s-palindrome\", because the second half of it is not a mirror reflection of the first half.\n\n\\begin{center}\n{\\small English alphabet}\n\\end{center}\n\nYou are given a string $s$. Check if the string is \"s-palindrome\".",
    "tutorial": "In this problem you should simply find the symmetric letters by picture and also observe that the pairs $(b, d)$ and $(p, q)$ is the symmteric reflections. Complexity: $O(n)$.",
    "code": "string s;\n\nbool read() {\n\treturn !!getline(cin, s);\n}\n\nstring symmetric = \"AHIMOoTUVvWwXxY\";\nmap<char, char> opposite = {{'p', 'q'}, {'q', 'p'}, {'d', 'b'}, {'b', 'd'}};\n\nvoid solve() {\n\tforn(i, sz(s)) {\n\t\tif (symmetric.find(s[i]) != string::npos) {\n\t\t\tif (s[sz(s) - 1 - i] != s[i]) {\n\t\t\t\tputs(\"NIE\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else if (opposite.count(s[i])) {\n\t\t\tif ((sz(s) & 1) && i == (sz(s) >> 1)) {\n\t\t\t\tputs(\"NIE\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (s[sz(s) - 1 - i] != opposite[s[i]]) {\n\t\t\t\tputs(\"NIE\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\tputs(\"NIE\");\n\t\t\treturn;\n\t\t}\n\t}\n\tputs(\"TAK\");\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "691",
    "index": "C",
    "title": "Exponential notation",
    "statement": "You are given a positive decimal number $x$.\n\nYour task is to convert it to the \"simple exponential notation\".\n\nLet $x = a·10^{b}$, where $1 ≤ a < 10$, then in general case the \"simple exponential notation\" looks like \"aEb\". If $b$ equals to zero, the part \"Eb\" should be skipped. If $a$ is an integer, it should be written without decimal point. Also there should not be extra zeroes in $a$ and $b$.",
    "tutorial": "This is an implementation problem. You should do exactly what is written in the problem statement. On my mind the simplest way is to find the position of the first not zero digit and the position of the dot. The difference between that positions is the value of $b$ (if the value is positive you should also decrease it by one). Complexity: $O(n)$.",
    "code": "string s;\n\nbool read() {\n\treturn !!getline(cin, s);\n}\n\nvoid solve() {\n\tint pos = int(find_if(all(s), [](char c) { return c != '0' && c != '.'; }) - s.begin());;\n\tsize_t dot_pos = s.find('.');\n\tif (dot_pos == string::npos) {\n\t\tdot_pos = s.size();\n\t} else {\n\t\ts.erase(dot_pos, 1);\n\t}\n\n\tint expv = (int) dot_pos - pos;\n\tif (expv > 0) expv--;\n\tforn(t, 2) {\n\t\twhile (s.back() == '0') s.pop_back();\n\t\treverse(all(s));\n\t}\n\tif (sz(s) > 1) s.insert(1, \".\");\n\tif (expv == 0) printf(\"%s\\n\", s.c_str());\n\telse printf(\"%sE%d\\n\", s.c_str(), expv);\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "691",
    "index": "D",
    "title": "Swaps in Permutation",
    "statement": "You are given a permutation of the numbers $1, 2, ..., n$ and $m$ pairs of positions $(a_{j}, b_{j})$.\n\nAt each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?\n\nLet $p$ and $q$ be two permutations of the numbers $1, 2, ..., n$. $p$ is lexicographically smaller than the $q$ if a number $1 ≤ i ≤ n$ exists, so $p_{k} = q_{k}$ for $1 ≤ k < i$ and $p_{i} < q_{i}$.",
    "tutorial": "Consider a graph with $n$ vertices whose edges is the pairs from the input. It's possible to swap any two values with the positions in some connected component in that graph. So we can sort the values from any component in decreasing order. Easy to see that after sorting the values of each component we will get the lexicographically maximal permutation. Complexity: $O(n + m)$.",
    "code": "const int N = 1200300;\n\nint n, m;\nint p[N];\npti a[N];\n\nbool read() {\n\tif (!(cin >> n >> m)) return false;\n\tforn(i, n) {\n\t\tassert(scanf(\"%d\", &p[i]) == 1);\n\t\tp[i]--;\n\t}\n\tforn(i, m) {\n\t\tassert(scanf(\"%d%d\", &a[i].x, &a[i].y) == 2);\n\t\ta[i].x--, a[i].y--;\n\t}\n\treturn true;\n}\n\nbool used[N];\nvector<int> g[N];\nvector<int> perm, pos;\n\nvoid dfs(int v) {\n\tif (used[v]) return;\n\tused[v] = true;\n\tpos.pb(v);\n\tperm.pb(p[v]);\n\n\tfor (auto to : g[v]) dfs(to);\n}\n\nint ans[N];\n\nvoid solve() {\n\tforn(i, n) {\n\t\tg[i].clear();\n\t\tused[i] = false;\n\t}\n\n\tforn(i, m) {\n\t\tg[a[i].x].pb(a[i].y);\n\t\tg[a[i].y].pb(a[i].x);\n\t}\n\n\tint cnt = 0;\n\tforn(i, n)\n\t\tif (!used[i]) {\n\t\t\tcnt++;\n\t\t\tpos.clear();\n\t\t\tperm.clear();\n\t\t\tdfs(i);\n\t\t\tsort(all(pos));\n\t\t\tsort(all(perm), greater<int>());\n\t\t\tforn(j, sz(perm))\n\t\t\t\tans[pos[j]] = perm[j];\n\t\t}\n\n\tforn(i, n) {\n\t\tif (i) putchar(' ');\n\t\tprintf(\"%d\", ans[i] + 1);\n\t}\n\tputs(\"\");\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "691",
    "index": "E",
    "title": "Xor-sequences",
    "statement": "You are given $n$ integers $a_{1}, a_{2}, ..., a_{n}$.\n\nA sequence of integers $x_{1}, x_{2}, ..., x_{k}$ is called a \"xor-sequence\" if for every $1 ≤ i ≤ k - 1$ the number of ones in the binary representation of the number $x_{i}$ $\\otimes$ $x_{i + 1}$'s is a multiple of $3$ and $x_{i}\\in\\{a_{1},a_{2},\\ldots,a_{n}\\}$ for all $1 ≤ i ≤ k$. The symbol $\\otimes$ is used for the binary exclusive or operation.\n\nHow many \"xor-sequences\" of length $k$ exist? Output the answer modulo $10^{9} + 7$.\n\n\\textbf{Note if $a = [1, 1]$ and $k = 1$ then the answer is $2$, because you should consider the ones from $a$ as different.}",
    "tutorial": "Let $z_{ij}$ be the number of xor-sequences of length $i$ with the last element equal to $a_{j}$. Let $g_{ij}$ be equal to one if $a_{i}\\otimes a_{j}$ contains the number of ones in binary presentation that is multiple of three. Otherwise let $g_{ij}$ be equal to zero. Consider a vectors $z_{i} = {z_{ij}}$, $z_{i - 1} = {z_{i - 1, j}}$ and a matrix $G = {g_{ij}}$. Easy to see that $z_{i} = G  \\times  z_{i - 1}$. So $z_{n} = G^{n}z_{0}$. Let's use the associative property of matrix multiplication: at first let's calculate $G^{n}$ with binary matrix exponentiation and then multiply it to the vector $z_{0}$. Complexity: $O(n^{3}logk)$.",
    "code": "const int N = 101;\n\nint n;\nli k;\nli a[N];\n\nbool read() {\n\tif (!(cin >> n >> k)) return false;\n\tforn(i, n) assert(cin >> a[i]);\n\treturn true;\n}\n\nconst int mod = 1000 * 1000 * 1000 + 7;\n\ninline int add(int a, int b) { return a + b >= mod ? a + b - mod : a + b; }\ninline void inc(int& a, int b) { a = add(a, b); }\ninline int mul(int a, int b) { return int(a * 1ll * b % mod); }\n\nint count(li x) {\n\tint ans = 0;\n\twhile (x) {\n\t\tans++;\n\t\tx &= x - 1;\n\t}\n\treturn ans;\n}\n\nvoid mul(int a[N][N], int b[N][N], int n) {\n\tstatic int c[N][N];\n\tforn(i, n)\n\t\tforn(j, n) {\n\t\t\tc[i][j] = 0;\n\t\t\tforn(k, n) inc(c[i][j], mul(a[i][k], b[k][j]));\n\t\t}\n\tforn(i, n) forn(j, n) a[i][j] = c[i][j];\n}\n\nvoid bin_pow(int a[N][N], li b, int n) {\n\tstatic int ans[N][N];\n\tforn(i, n) forn(j, n) ans[i][j] = i == j;\n\n\twhile (b) {\n\t\tif (b & 1) mul(ans, a, n);\n\t\tmul(a, a, n);\n\t\tb >>= 1;\n\t}\n\n\tforn(i, n) forn(j, n) a[i][j] = ans[i][j];\n}\n\nvoid solve() {\n\tstatic int a[N][N];\n\tmemset(a, 0, sizeof(a));\n\tforn(i, n) {\n\t\tforn(j, n)\n\t\t\ta[i][j] = count(::a[i] ^ ::a[j]) % 3 == 0;\n\t\ta[i][n] = 1;\n\t}\n\n\t//forn(i, n + 1) clog << mp(a[i], n + 1) << endl;\n\n\tbin_pow(a, k, n + 1);\n\n\tint ans = 0;\n\tforn(i, n + 1) inc(ans, a[i][n]);\n\tcout << ans << endl;\n}",
    "tags": [
      "matrices"
    ],
    "rating": 1900
  },
  {
    "contest_id": "691",
    "index": "F",
    "title": "Couple Cover",
    "statement": "Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with $n$ balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) — the number written on this ball is the rectangle's width in meters. This ball is not returned to the bag, and the second player reaches into the bag and grabs another ball — the number written on this ball is the rectangle's height in meters. If the area of the rectangle is greater than or equal some threshold $p$ square meters, the players win. Otherwise, they lose.\n\nThe organizers of the game are trying to select an appropriate value for $p$ so that the probability of a couple winning is not too high and not too low, but they are slow at counting, so they have hired you to answer some questions for them. You are given a list of the numbers written on the balls, the organizers would like to know how many winning pairs of balls exist for different values of $p$. Note that two pairs are different if either the first or the second ball is different between the two in pair, and two different balls with the same number are considered different.",
    "tutorial": "Let's count the number of pairs with multiple less than $p$. To get the number of not less pairs we should sumply subtract from $n \\cdot (n - 1)$ the number of less pairs. Let $cnt_{i}$ be the number of values in $a$ equal to $i$ and $z_{j}$ be the number of pairs from $a$ with the multiple equal to $j$. To calculate the values from $z$ we can use something like Eratosthenes sieve: let's iterate over the first multiplier $a$ and the multiple of it $b = ka$ and increment $z_{b}$ by the value $cnt_{a} \\cdot cnt_{k}$. After calculating the array $z$ we should calculate the array of its partial sums and find the number of less pairs in $O(1)$ time. Complexity: $O(n + XlogX)$, where $X$ is the maximal value in $p$.",
    "code": "const int N = 3100300;\n\nint n, m;\nint a[N], p[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\tassert(cin >> m);\n\tforn(i, m) assert(scanf(\"%d\", &p[i]) == 1);\n\treturn true;\n}\n\nint cnt[N];\nli z[N];\n\nvoid solve() {\n\tmemset(cnt, 0, sizeof(cnt));\n\n\tforn(i, n) cnt[a[i]]++;\n\n\tfore(a, 1, N) {\n\t\tif (!cnt[a]) continue;\n\t\tfor (int b = a; b < N; b += a) {\n\t\t\tif (b / a != a) z[b] += li(cnt[a]) * cnt[b / a];\n\t\t\telse z[b] += li(cnt[a]) * (cnt[a] - 1);\n\t\t}\n\t}\n\n\tfore(i, 1, N) z[i] += z[i - 1];\n\n\tforn(i, m) {\n\t\tli ans = li(n) * (n - 1) - z[p[i] - 1];\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n}",
    "tags": [
      "brute force",
      "dp",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "696",
    "index": "A",
    "title": "Lorenzo Von Matterhorn",
    "statement": "Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections $i$ and $2i$ and another road between $i$ and $2i + 1$ for every positive integer $i$. You can clearly see that there exists a unique shortest path between any two intersections.\n\nInitially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will $q$ consecutive events happen soon. There are two types of events:\n\n1. Government makes a new rule. A rule can be denoted by integers $v$, $u$ and $w$. As the result of this action, the passing fee of all roads on the shortest path from $u$ to $v$ increases by $w$ dollars.\n\n2. Barney starts moving from some intersection $v$ and goes to intersection $u$ where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.\n\nGovernment needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).",
    "tutorial": "Do what problem wants from you. The only thing is to find the path between the two vertices (or LCA) in the tree. You can do this in $O(l g(n))$ since the height of the tree is $O(l g(n))$. You can keep edge weights in a map and get/set the value whenever you want. Here's a code for LCA: LCA(v, u): while v != u: if depth[v] < depth[u]: swap(v, u) v = v/2 // v/2 is parent of vertex v Time Complexity: $O(q l g(q)l g(M A X_{-}V))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nunordered_map<ll, ll> mp;\ninline ll lca(ll v, ll u, ll w = -1){\n\tll ans = 0;\n\twhile(v != u){\n\t\tif(v < u)\tswap(v, u);\n\t\tif(mp.find(v) != mp.end())\tans += mp[v];\n\t\tif(~w)\tmp[v] += w;\n\t\tv >>= 1;\n\t}\n\treturn ans;\n}\nint main(){\n\tiOS;\n\tint q;\n\tcin >> q;\n\twhile(q--){\n\t\tint type;\n\t\tll v, u;\n\t\tcin >> type >> v >> u;\n\t\tif(type == 1){\n\t\t\tll w;\n\t\t\tcin >> w;\n\t\t\tlca(v, u, w);\n\t\t}\n\t\telse\n\t\t\tcout << lca(v, u) << '\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "696",
    "index": "B",
    "title": "Puzzles",
    "statement": "Barney lives in country USC (United States of Charzeh). USC has $n$ cities numbered from $1$ through $n$ and $n - 1$ roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number $1$. Thus if one will start his journey from city $1$, he can visit any city he wants by following roads.\n\nSome girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:\n\n\\begin{verbatim}\nlet starting_time be an array of length n\ncurrent_time = 0\ndfs(v):\ncurrent_time = current_time + 1\nstarting_time[v] = current_time\nshuffle children[v] randomly (each permutation with equal possibility)\n// children[v] is vector of children cities of city v\nfor u in children[v]:\ndfs(u)\n\\end{verbatim}\n\nAs told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).\n\nNow Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city $i$, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.",
    "tutorial": "First of all $starting_time$ of a vertex is the number of dfs calls before the dfs call of this vertex plus 1. Now suppose we want to find the answer for vertex $v$. For any vertex $u$ that is not in subtree of $v$ and is not an ancestor $v$, denote vertices $x$ and $y$ such that: $x  \\neq  y$ $x$ is an ancestor of $v$ but not $u$ $y$ is an ancestor of $u$ but not $v$ $x$ and $y$ share the same direct parent; That is $par[x] = par[y]$. The probability that $y$ occurs sooner than $x$ in $children[par[x]]$ after shuffling is $0.5$. So the probability that $starting_time[u] < starting_time[v]$ is $0.5$. Also We know if $u$ is ancestor of $v$ this probability is $1$ and if it's in subtree of $v$ the probability is $0$. That's why answer for $v$ is equal to $\\frac{n-s u b[v]-h[v]}{2}+d e p t h[v]$ ($depth$ is 1-based and $sub[v]$ is the number of vertices in subtree of $v$ including $v$ itself). Because $n - sub[v] - h[v]$ is the number of vertices like the first $u$ (not in subtree of $v$ and not an ancestor of $v$). Thus answer is always either an integer or an integer and a half. Time complexity: ${\\cal O}(n)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n//#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e5 + 100;\nint ans[maxn];\nvi adj[maxn];\nint sz[maxn];\ninline void DFS(int v = 0){\n\tsz[v] = 1;\n\trep(u, adj[v]){\n\t\tDFS(u);\n\t\tsz[v] += sz[u];\n\t}\n}\ninline void dfs(int v = 0, double e = 0){\n\te += 2;\n\tans[v] = e;\n\tint s = sz[v] - 1;\n\trep(u, adj[v]){\n\t\tdouble x = s - sz[u];\n\t\tdfs(u, e + x);\n\t}\n}\nint main(){\n\tint n;\n\tscanf(\"%d\", &n);\n\tFor(i,1,n){\n\t\tint p;\n\t\tscanf(\"%d\", &p);\n\t\tadj[--p].pb(i);\n\t}\n\tDFS();\n\tdfs();\n\tFor(i,0,n)\tprintf(\"%.1f \",  (double)ans[i]/2.);\n\tputs(\"\");\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "696",
    "index": "C",
    "title": "PLEASE",
    "statement": "As we all know Barney's job is \"PLEASE\" and he has not much to do at work. That's why he started playing \"cups and key\". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup.\n\nThen at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts $n$ turns and Barney \\textbf{independently choses} a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.\n\nAfter $n$-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.\n\nNumber $n$ of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array $a_{1}, a_{2}, ..., a_{k}$ such that\n\n\\begin{center}\n$n=\\prod_{i=1}^{k}a_{i},$\n\\end{center}\n\nin other words, $n$ is multiplication of all elements of the given array.\n\nBecause of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction $p / q$ such that $\\operatorname*{gcd}(p,q)=1$, where $\\operatorname{gcd}$ is the greatest common divisor. Since $p$ and $q$ can be extremely large, you only need to find the remainders of dividing each of them by $10^{9} + 7$.\n\nPlease note that we want $\\operatorname{gcd}$ of $p$ and $q$ to be $1$, \\textbf{not $\\operatorname{gcd}$ of their remainders} after dividing by $10^{9} + 7$.",
    "tutorial": "It gets tricky when the problem statement says $p$ and $q$ should be coprimes. A wise coder in this situation thinks of a formula to make sure this happens. First of all let's solve the problem if we only want to find the fraction $\\overset{p}{q}$. Suppose $dp[i]$ is answer for swapping the cups $i$ times. It's obvious that $dp[1] = 0$. For $i > 0$, obviously the desired cup shouldn't be in the middle in $(i - 1) - th$ swap and with this condition the probability that after $i - th$ swap comes to the middle is $0.5$. That's why $d p[i]=(1-d p[i-1])*0.5={\\frac{1{-}d p[i-1]}{2}}$. Some people may use matrix to find $p$ and $q$ using this dp (using pair of ints instead of floating point) but there's a risk that $p$ and $q$ are not coprimes, but fortunately or unfortunately they will be. Using some algebra you can prove that: if $n$ is even then $p={\\frac{2^{n-1}+1}{3}}$ and $q = 2^{n - 1}$. if $n$ is odd then $p={\\frac{2^{n-1}-1}{3}}$ and $q = 2^{n - 1}$. You can confirm that in both cases $p$ and $q$ are coprimes (since $p$ is odd and $q$ is a power of 2). The only thing left to handle is to find $2^{n}$ (or $2^{n - 1}$) and parity. Finding parity is super easy. Also $2^{n} = 2^{a1  \\times  a2  \\times  ...  \\times  ak} = (...((2^{a1})^{a2})^{}...)^{ak}$. So it can be calculated using binary exponential. Also dividing can be done using Fermat's little theorem. Time complexity: $O(klg(MAX_A))$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int mod = 1e9 + 7;\ninline int power(int a, ll b){\n\tint ans = 1;\n\twhile(b){\n\t\tif(b & 1LL)\tans = (1LL * ans * a) % mod;\n\t\ta = (1LL * a * a) % mod;\n\t\tb >>= 1;\n\t}\n\treturn ans;\n}\nint main(){\n\tint k;\n\tscanf(\"%d\", &k);\n\tbool parity = 1, g = false;\n\tint x = 2;\n\twhile(k--){\n\t\tll a;\n\t\tscanf(\"%lld\", &a);\n\t\tif(a > 1)\tg = true;\n\t\tif(!(a & 1LL))\tparity = 0;\n\t\tx = power(x, a);\n\t}\n\tif(!g){\n\t\tcout << \"0/1\n\";\n\t\treturn 0;\n\t}\n\tparity = !parity;\n\tx = (1LL * x * power(2, mod-2)) % mod;\n\tint y = (mod + x + (parity? 1: -1)) % mod;\n\ty = (1LL * y * power(3, mod-2)) % mod;\n\tcout << y << \"/\" << x << endl;\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math",
      "matrices"
    ],
    "rating": 2000
  },
  {
    "contest_id": "696",
    "index": "D",
    "title": "Legen...",
    "statement": "Barney was hanging out with Nora for a while and now he thinks he may have feelings for her. Barney wants to send her a cheesy text message and wants to make her as happy as possible.\n\nInitially, happiness level of Nora is $0$. Nora loves some pickup lines like \"I'm falling for you\" and stuff. Totally, she knows $n$ pickup lines, each consisting only of lowercase English letters, also some of them may be equal (in writing, but different in pronouncing or meaning though). Every time Nora sees $i$-th pickup line as a \\textbf{consecutive subsequence} of Barney's text message her happiness level increases by $a_{i}$. These substrings may overlap, for example, Nora will see the pickup line aa twice and the pickup line ab once in text message aaab.\n\nDue to texting app limits, Barney's text may have up to $l$ characters.\n\nBarney asked you to help him make Nora as much happy as possible, it's gonna be legen...",
    "tutorial": "Build the prefix automaton of these strings (Aho-Corasick). In this automaton every state denotes a string which is prefix of one of given strings (and when we feed characters to it the current state is always the longest of these prefixes that is a suffix of the current string we have fed to it). Building this DFA can be done in various ways (fast and slow). Suppose these automaton has $N$ states ($N=O(|s_{1}|+\\ldots+|s_{n}|)$) and state $v$ has edges outgoing to states in vector $neigh[v]$ (if we define our DFA as a directed graph). Suppose state number $1$ is the initial state (denoting an empty string). If $l$ was smaller we could use dp: suppose $dp[l][v]$ is the maximum score of all strings with length equal to $l$ ending in state $v$ of our DFA when fed into it. It's easy to show that $dp[0][1] = 0$ and $dp[1][v]  \\le  b_{v} + dp[l + 1][u]$ for $u$ in $neigh[v]$ and calculating dps can be done using this (here $b_{v}$ is sum of $a$ of all strings that are a suffix of string related to state $v$). Now that $l$ is large, let's use matrix exponential to calculate the dp. Now dp is not an array, but a column matrix. Finding a matrix to update the dp is not hard. Also we need to reform + and * operations. In matrix multiplying we should use + instead of * and max instead of + in normal multiplication. Time complexity: $O(N^{3}l g(l))$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 200 + 10;\nstruct matrix{\n\tll a[maxn][maxn];\n\tint n, m;\n\tmatrix(){\n\t\tn = m = 0;\n\t\tmemset(a, -1, sizeof a);\n\t}\n\tmatrix(int n, int m): n(n), m(m){\n\t\tmemset(a, -1, sizeof a);\n\t}\n\tinline void I(){\n\t\tFor(i,0,n)\ta[i][i] = 0;\n\t}\n\tinline matrix operator * (const matrix &x){\n\t\tmatrix ans(n, x.m);\n\t\tFor(k,0,m)\n\t\t\tFor(i,0,n)\n\t\t\t\tFor(j,0,x.m)\tif(~a[i][k] && ~x.a[k][j])\n\t\t\t\t\tsmax(ans.a[i][j], a[i][k] + x.a[k][j]);\n\t\treturn ans;\n\t}\n};\nstring s[maxn];\nint tr[maxn][27], au[maxn][27], nx = 1, e[maxn], a[maxn], f[maxn], n;\nll l;\ninline void add(int i){\n\tint v = 0;\n\trep(ch, s[i]){\n\t\tint c = ch - 'a';\n\t\tif(!tr[v][c])\n\t\t\ttr[v][c] = nx ++;\n\t\tv = tr[v][c];\n\t}\n\te[v] += a[i];\n}\ninline void ahoc(){\n\tqueue<int> q;\n\tq.push(0);\n\twhile(!q.empty()){\n\t\tint v = q.front();\n\t\tq.pop();\n\t\tif(f[v] != v)\te[v] += e[f[v]];\n\t\tFor(i,0,26){\n\t\t\tint u = tr[v][i];\n\t\t\tif(u){\n\t\t\t\tau[v][i] = u;\n\t\t\t\tif(v)\n\t\t\t\t\tf[u] = au[f[v]][i];\n\t\t\t\tq.push(u);\n\t\t\t}\n\t\t\telse\n\t\t\t\tau[v][i] = au[f[v]][i];\n\t\t}\n\t}\n}\ninline matrix power(matrix a, ll b){\n\tmatrix c(a.n, a.m);\n\tc.I();\n\twhile(b){\n\t\tif(b & 1)\n\t\t\tc = c * a;\n\t\ta = a * a;\n\t\tb >>= 1;\n\t}\n\treturn c;\n}\nint main(){\n\tiOS;\n\tcin >> n >> l;\n\tFor(i,0,n)\tcin >> a[i];\n\tFor(i,0,n){\n\t\tcin >> s[i];\n\t\tadd(i);\n\t}\n\tahoc();\n\tmatrix dp(nx, nx);\n\tFor(v,0,nx)\n\t\tFor(i,0,26)\n\t\t\tsmax(dp.a[au[v][i]][v], (ll)e[au[v][i]]);\n\tdp = power(dp, l);\n\tmatrix M(nx, 1);\n\tM.a[0][0] = 0;\n\tM = dp * M;\n\tll ans = 0;\n\tFor(i,0,nx)\n\t\tsmax(ans, M.a[i][0]);\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "matrices",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "696",
    "index": "E",
    "title": "...Wait for it...",
    "statement": "Barney is searching for his dream girl. He lives in NYC. NYC has $n$ junctions numbered from $1$ to $n$ and $n - 1$ roads connecting them. We will consider the NYC as a rooted tree with root being junction $1$. $m$ girls live in NYC, $i$-th of them lives along junction $c_{i}$ and her weight initially equals $i$ pounds.\n\nBarney consider a girl $x$ to be better than a girl $y$ if and only if: girl $x$ has weight strictly less than girl $y$ or girl $x$ and girl $y$ have equal weights and index of girl $x$ living junction index is strictly less than girl $y$ living junction index, i.e. $c_{x} < c_{y}$. Thus for any two girls one of them is always better than another one.\n\nFor the next $q$ days, one event happens each day. There are two types of events:\n\n- Barney goes from junction $v$ to junction $u$. As a result he picks at most $k$ \\textbf{best girls he still have not invited} from junctions on his way and invites them to his house to test if one of them is his dream girl. If there are less than $k$ not invited girls on his path, he invites all of them.\n- Girls living along junctions in subtree of junction $v$ (including $v$ itself) put on some weight. As result, their weights increase by $k$ pounds.\n\nYour task is for each event of first type tell Barney the indices of girls he will invite to his home in this event.",
    "tutorial": "First of all, for each query of 1st type we can assume $k = 1$ (because we can perform this query $k$ times, it doesn't differ). Consider this problem: there are only queries of type 1. For solving this problem we can use heavy-light decomposition. If for a vertex $v$ of the tree we denote $a_{v}$ as the weight of the lightest girl in it ($ \\infty $ in case there is no girl in it), for each chain in HLD we need to perform two type of queries: Get weight of the lightest girl in a substring (consecutive subsequence) of this chain (a subchain). Delete the lightest girl in vertex $u$. As the result only $a_{u}$ changes. We can find this value after changing in $O(1)$ if we have the sorted vector of girls' weights for each vertex (and then we pop the last element from it and then current last element is the lightest girl, $ \\infty $ in case it becomes empty). This can be done using a classic segment tree. In each node we only need a pair of integers: weight of lightest girl in interval of this node and the vertex she lives in (a pair<int, int>). This works for this version of the problem. But for the original version we need an additional query type: 3. Increase weight of girls in a substring (consecutive subsequence) of this chain (a subchain) by $k$. This can be done using the previous segment tree plus lazy propagation (an additional value in each node, type 3 queries to pass to children). Now consider the original problem. Consider an specific chain: after each query of the first type on of the following happens to this chain: Nothing. Only an interval (subchain) is effected. Whole chain is effected. When case 2 happens, $v$ (query argument) belongs to this chain. And this can be done using the 3rd query of chains when we are processing a 2nd type query (effect the chain $v$ belongs to). When case 3 happens, $v$ is an ancestor of the topmost vertex in this chain. So when processing 1st type query, we need to know sum of $k$ for all 2nd type queries that their $v$ is an ancestor of topmost chain in current chain we're checking. This can be done using a single segment/Fenwick tree (using starting-finishing time trick to convert tree to array). So for each query of 1st type, we will check all chains on the path to find the lightest girl and delete her. Time Complexity: $O((n+q)l g^{2}(n))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e5 + 10, maxl = 19;\nconst ll inf = 1LL << 60;\nint st[maxn], ft[maxn], par[maxn][maxl], h[maxn], tim, sz[maxn], fst[maxn], stm[maxn], lst[maxn];\nvi adj[maxn];\nvi people[maxn];\ntypedef pair<ll, int> person;\nperson emp(inf, -1);\nll lz[maxn * 4], seg[maxn * 4];\nperson mn[maxn * 4];\nint n, m, q;\ninline void DFS(int v = 0, int p = -1){\n\tsz[v] = 1;\n\trep(u, adj[v])\tif(u - p){\n\t\tDFS(u, v);\n\t\tsz[v] += sz[u];\n\t}\n}\ninline void dfs(int v = 0, int p = -1, bool big = false){\n\tfst[v] = (big? fst[p]: v);\n\tstm[tim] = v;\n\tst[v] = tim ++;\n\tpar[v][0] = p;\n\tif(~p)\th[v] = h[p] + 1;\n\tFor(i,1,maxl)\tif(~par[v][i-1])\n\t\tpar[v][i] = par[par[v][i-1]][i-1];\n\tint mx = 0, I = -1;\n\tFor(i,0,adj[v].size())\tif(adj[v][i] - p && mx < sz[adj[v][i]])\n\t\tmx = sz[adj[v][i]], I  = i;\n\tif(~I)\n\t\trotate(adj[v].begin(), adj[v].begin() + I, adj[v].end());\n\tFor(i,0,adj[v].size())\tif(adj[v][i] - p)\n\t\tdfs(adj[v][i], v, !i);\n\tft[v] = tim;\n\tsmax(lst[fst[v]],  st[v]);\n}\ninline void addtree(int x, int y, int val, int id = 1, int l = 0, int r = n){\n\tif(l >= y or x >= r)\treturn ;\n\tif(x <= l && r <= y){\n\t\tseg[id] += val;\n\t\treturn ;\n\t}\n\tint mid = (l + r)/2;\n\taddtree(x, y, val, L(id), l, mid);\n\taddtree(x, y, val, R(id), mid, r);\n}\ninline ll asktree(int p, int id = 1, int l = 0, int r = n){\n\tll ans = seg[id];\n\tif(r - l < 2)\treturn ans;\n\tint mid = (l + r)/2;\n\tif(p < mid)\n\t\tans += asktree(p, L(id), l, mid);\n\telse\n\t\tans += asktree(p, R(id), mid, r);\n\treturn ans;\n}\ninline void upd(int id, ll val){\n\tlz[id] += val;\n\tmn[id].x += val;\n\tsmin(mn[id], emp);\n}\ninline void shift(int id){\n\tupd(L(id), lz[id]);\n\tupd(R(id), lz[id]);\n\tlz[id] = 0;\n}\ninline void build(int id = 1, int l = 0, int r = n){\n\tif(r - l < 2){\n\t\tmn[id] = emp;\n\t\tint v = stm[l];\n\t\tif(!people[v].empty())\n\t\t\tmn[id] = {people[v].back() + lz[id], l};\n\t\treturn ;\n\t}\n\tint mid = (l + r)/2;\n\tbuild(L(id), l, mid);\n\tbuild(R(id), mid, r);\n\tmn[id] = min(mn[L(id)], mn[R(id)]);\n}\ninline void add(int x, int y, int val, int id = 1, int l = 0, int r = n){\n\tif(x >= r or l >= y)\treturn ;\n\tif(x <= l && r <= y){\n\t\tupd(id, val);\n\t\treturn ;\n\t}\n\tint mid = (l + r)/2;\n\tshift(id);\n\tadd(x, y, val, L(id), l, mid);\n\tadd(x, y, val, R(id), mid, r);\n\tmn[id] = min(mn[L(id)], mn[R(id)]);\n}\ninline void set_element(int p, int id = 1, int l = 0, int r = n){\n\tif(r - l < 2){\n\t\tmn[id] = emp;\n\t\tint v = stm[l];\n\t\tif(!people[v].empty())\n\t\t\tmn[id] = {people[v].back() + lz[id], l};\n\t\treturn ;\n\t}\n\tint mid = (l + r)/2;\n\tshift(id);\n\tif(p < mid)\n\t\tset_element(p, L(id), l, mid);\n\telse\n\t\tset_element(p, R(id), mid, r);\n\tmn[id] = min(mn[L(id)], mn[R(id)]);\n}\ninline person ask(int x, int y, int id = 1, int l = 0, int r = n){\n\tif(x >= r or l >= y)\treturn emp;\n\tif(x <= l && r <= y)\treturn mn[id];\n\tint mid = (l + r)/2;\n\tshift(id);\n\treturn min(ask(x, y, L(id), l, mid),\n\t\t\task(x, y, R(id), mid, r));\n}\ninline int lca(int v, int u){\n\tif(h[v] < h[u])\tswap(v, u);\n\trof(i,maxl-1,-1)\tif(~par[v][i] && h[par[v][i]] >= h[u])\n\t\tv = par[v][i];\n\tif(v == u)\treturn v;\n\trof(i,maxl-1,-1)\tif(par[v][i] - par[u][i])\n\t\tv = par[v][i], u = par[u][i];\n\treturn par[v][0];\n}\ninline person askchain(int v, int u){// u is ancestor of v\n\t//assert(fst[v] == fst[u]);\n\tll val = asktree(st[fst[u]]);\n\tperson ans = ask(st[u], st[v] + 1);\n\tans.x += val;\n\tsmin(ans, emp);\n\treturn ans;\n}\ninline person hld(int v, int u){// us in ancestor of v\n\tauto ans = emp;\n\twhile(fst[v] != fst[u]){\n\t\tsmin(ans, askchain(v, fst[v]));\n\t\tv = par[fst[v]][0];\n\t}\n\tsmin(ans, askchain(v, u));\n\treturn ans;\n}\ninline int erase(person p){\n\tif(p.y == -1)\treturn -1;\n\tint v = stm[p.y];\n\tint ans = people[v].back();\n\tpeople[v].PB;\n\tset_element(st[v]);\n\treturn ans;\n}\nvector<int> anss;\ninline bool query(int v, int u, int w){\n\tperson p = min(hld(v, w), hld(u, w));\n\tif(p.x == inf or p.y == -1)\treturn false;\n\tanss.pb(erase(p));\n\treturn true;\n}\ninline void solve(int v, int u, int k){\n\tint w = lca(v, u);\n\tanss.clear();\n\tFor(i,0,k)\tif(!query(v, u, w))\tbreak ;\n\tprintf(\"%d \", (int)anss.size());\n\trep(x, anss)\tprintf(\"%d \", x);\n\tputs(\"\");\n}\nint main(){\n\tmemset(par, -1, sizeof par);\n\tfill(mn, mn + 4 * maxn, emp);\n\tscanf(\"%d %d %d\", &n, &m, &q);\n\tFor(i,1,n){\n\t\tint v, u;\n\t\tscanf(\"%d %d\", &v, &u);\n\t\t-- v, -- u;\n\t\tadj[v].pb(u), adj[u].pb(v);\n\t}\n\tFor(i,1,m+1){\n\t\tint v;\n\t\tscanf(\"%d\", &v);\n\t\t-- v;\n\t\tpeople[v].pb(i);\n\t}\n\tFor(i,0,n)\treverse(all(people[i]));\n\tDFS();\n\tdfs();\n\tbuild();\n\twhile(q--){\n\t\tint type, v, u, k;\n\t\tscanf(\"%d %d\", &type, &v);\n\t\tif(type == 1){\n\t\t\tscanf(\"%d %d\", &u, &k);\n\t\t\t-- v, -- u;\n\t\t\tsolve(v, u, k);\n\t\t}\n\t\telse{\n\t\t\tscanf(\"%d\", &k);\n\t\t\t-- v;\n\t\t\taddtree(st[v], ft[v], k);\n\t\t\tif(v != fst[v])\tadd(st[v], lst[fst[v]] + 1, k);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "696",
    "index": "F",
    "title": "...Dary!",
    "statement": "Barney has finally found the one, a beautiful young lady named Lyanna. The problem is, Lyanna and Barney are trapped in Lord Loss' castle. This castle has shape of a convex polygon of $n$ points. Like most of castles in Demonata worlds, this castle has no ceiling.\n\nBarney and Lyanna have an escape plan, but it requires some geometry knowledge, so they asked for your help.\n\nBarney knows that demons are organized and move in lines. He and Lyanna want to wait for the appropriate time so they need to watch for the demons. Each of them wants to stay in a point \\textbf{inside the castle} (possibly on edges or corners), also they may stay in the same position. They both want to pick a real number $r$ and watch all points in the circles with radius $r$ around each of them (these two circles may overlap).\n\nWe say that Barney and Lyanna are watching carefully if and only if for every edge of the polygon, at least one of them can see at least one point on the line this edge lies on, thus such point may not be on the edge but it should be on edge's line. Formally, each edge line should have at least one common point with at least one of two circles.\n\nThe greater $r$ is, the more energy and focus they need. So they asked you to tell them the minimum value of $r$ such that they can watch carefully.",
    "tutorial": "In the first thoughts you see that there's definitely a binary search needed (on $r$). Only problem is checking if there are such two points fulfilling conditions with radius $r$. For each edge, we can shift it $r$ units inside the polygon (parallel to this edge). The only points that can see the line coinciding the line on this edge are inside the half-plane on one side of this shifted line (side containing this edge). So problem is to partition these half-planes in two parts such that intersection of half-planes in each partition and the polygon (another $n$ half-planes) is not empty. There are several algorithms for this propose: $O(n^{3})$ Algorithm: It's obvious that if intersection of some half-planes is not empty, then there's at least on point inside this intersection that is intersection of two of these lines (lines denoting these half-planes). The easiest algorithm is to pick any intersection of these $2n$ lines ($n$ shifted half-planes and $n$ edges of the polygon) like $p$ that lies inside the polygon, delete any half-plane containing this point (intersection of deleted half-planes and polygon is not empty because it contains at least $p$) and check if the intersection of half-planes left and polygon is not empty (of course this part needs sorting half-planes and adds an additional $log$ but we can sort the lines initially and use something like counting sort in this step). Well, constant factor in this problem is too big and this algorithm will not fit into time limit. But this algorithm will be used to prove the faster algorithm: $O(n^{2})\\,$ Algorithm: In the previous algorithm we checked if $p$ can be in intersection of one part. Here's the thing: Lemma 1: If $p$ is inside intersection of two half-planes ($p$ is not necessarily intersection of their lines) related to $l - th$ and $r - th$ edge ($l < r$) and two conditions below are fulfilled, then there's no partitioning that in it $p$ is inside intersection of a part (and polygon): At least one of the half-planes related to an edge with index between $l$ and $r$ exists that doesn't contain $p$. At least one of the half-planes related to an edge with index greater than $r$ or less than $l$ exists that doesn't contain $p$. Because if these two lines exist, they should be in the other part that doesn't contain $p$ and if they are, intersection of them and polygon will be empty(proof is easy, homework assignment ;)). This proves that if such partitioning is available that $p$ is in intersection of one of them, then it belongs to an interval of edges(cyclic interval) and the rest are also an interval (so intersection of both intervals with polygon should be non-empty). Thus, we don't need $p$ anymore. We only need intervals! Result is, if such partitioning exists, there are integers $l$ and $r$ ($1  \\le  l  \\le  r  \\le  n$) such that intersection of half-planes related to $l, l + 1, ..., r$ and polygon and also intersection of half-planes related to $r + 1, r + 2, ..., n, 1, 2, ..., l - 1$ and polygon are both non-empty. This still gives an $O(n^{3})$ algorithm (checking every interval). But this lemma comes handy here: We call an interval(cyclic) good if intersection of lines related to them and polygon is non-empty. Lemma 2: If an interval is good, then every subinterval of this interval is also good. Proof is obvious. That gives and idea: Denote $interval(l, r)$ is a set of integers such that: If $l  \\le  r$, then $interval(l, r) = {l, l + 1, ..., r}$ If $l  \\le  r$, then $interval(l, r) = {r, r + 1, ..., n, 1, ..., l}$ (In other words it's a cyclic interval) Also $MOD(x)$ is: $x$ iff $x  \\le  n$ $MOD(x - n)$ iff $x > n$ (In other words it's modulo $n$ for 1-based) The only thing that matters for us for every $l$, is maximum $len$ such that $interval(l, MOD(l + len))$ is good (because then all its subintervals are good). If $l_{i}$ is maximum $len$ that $interval(i, MOD(i + len))$ is good, we can use 2-pointer to find values of $l$. Lemma 3: $l_{MOD(i + 1)}  \\ge  l_{i} - 1$. Proof is obvious in result of lemma 2. Here's a pseudo code: check(r): len = 0 for i = 1 to n: while len < n and good(i, MOD(i+len)): // good(l, r) returns true iff interval(l, r) is good len = len + 1 if len == 0: return false // Obviously if len == n: return true // Barney and Lyanna can both stay in the same position l[i] = len for i = 1 to n: if l[i] + l[MOD(i+l[i])] >= n: return true return false$good$ function can be implemented to work in ${\\cal O}(n)$ (with sorting as said before). And 2-pointer makes the calls to $good$ to be ${\\mathcal{O}}(n)$. So the total complexity to check an specific $r$ is $O(n^{2})\\,$. Time Complexity: $O(n^{2}l g(M A X_{-}C O O R D I N A T E))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define X\tfirst\n#define Y\tsecond\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef pair<double, double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\ninline point operator - (const point &p, const point &q){return point(p.x - q.x, p.y - q.y);}\ninline point operator + (const point &p, const point &q){return point(p.x + q.x, p.y + q.y);}\ninline point operator * (const point &p, const point &q){return point(p.x * q.x - p.y * q.y, p.x * q.y + p.y * q.x);}\ninline point operator * (const point &p, const double &d){return point(p.x*d, p.y*d);}\ninline point operator * (const double &d, const point &p){return point(p.x*d, p.y*d);}\ninline point operator / (const point &p, const double &d){return point(p.x/d, p.y/d);}\ninline double abs(const point &p){\n\treturn sqrt(p.X * p.X + p.Y * p.Y);\n}\nconst int maxn = 300 + 100;\nint len[maxn];\nconst double eps = 1e-12, inf = 1e10;\npii pol[maxn];\ninline short sign(double a) { \n\treturn abs(a) < eps ? 0 : (a < 0? -1:1) ; \n}\ninline point unit(point p){\n\treturn p/ abs(p);\n}\ninline double cross(point a, point b){\n\treturn a.X * b.Y - a.Y * b.X; \n}\ninline double dot(point a, point b){\n\treturn a.x * b.x + a.y * b.y;\n}\ninline double arg(const point &p){\n\tcomplex<double> c(p.x, p.y);\n\treturn arg(c);\n}\ninline point inter(point a, point b, point c, point d){\n\treturn a + (b-a) * (cross(c-a, d-c)/cross(b-a, d-c));\n}\ninline point shift(point p, double x){\n\treturn x * unit(p) * point(0, 1);\n}\ninline double getAlpha( point a , point b , point c , point d ) { \n\tpoint cd = d - c;\n\treturn cross( c-a , cd ) / cross( b - a , cd ); \n}\ninline bool sect(point a, point b, point c, point d){\n\tdouble alpha = getAlpha(a, b, c, d);\n\treturn -eps <= alpha && alpha <= 1 + eps;\n}\ninline point proj(const point &a, const point &b){\t// projection of b on o-a\n\treturn a * dot(a, b) / dot(a, a);\n}\ninline double dis(const point &a, const point &b, const point &c){\n\tpoint h = b + proj(a-b, c-b);\n\treturn abs(h - c);\n}\n\nint n;\npoint p[maxn * 2], q[maxn * 2];\nint perm[maxn * 2];\npoint que[maxn * 2];\nint st, en;\ninline point mult(const point &p, double d){\n\treturn p * d;\n\treturn point(sign(p.X) * d * abs(p.X), sign(p.Y) * d * abs(p.Y));\n}\ninline bool add(int i){\n\tauto x = p[i], y = q[i];\n\tpoint c = x + mult(unit( y - x ), -inf); \n\tpoint d = x + mult(unit( y - x ), inf);\n\tif(st == en){\n\t\tque[en ++] = c;\n\t\tque[en ++] = d;\n\t\treturn true;\n\t}\n\twhile(en > 1 && sign(cross(unit(y-x), que[en-2]-c)) <= 0){\n\t\t-- en;\n\t}\n\tif(en == 1)\treturn false;\n\tif( sign(cross( unit(que[en-1] - que[en-2]) , unit(d-c) )) == 0 ) return true;\n\tque[en-1] = inter(que[en-2], que[en-1], x, y);\n\tque[en ++] = d;\n\treturn true;\n}\ninline bool relax(){\n\tFor(i,0,n)\tp[i] = point(pol[i]);\n\twhile(en - st > 3 && sign(cross(que[en-1] - que[en-2], que[st+1] - que[en-2])) <= 0)\n\t\t++ st;\n\twhile(en - st > 3 && sign(cross(que[st+1] - que[st]  , que[en-2] - que[st])) <= 0)\n\t\t-- en;\n\tif(!sign(cross( que[st+1] - que[st] , que[en-1] - que[en-2] ))) return 1;\n\t\tque[st] = inter(que[st], que[st+1], que[en-2], que[en-1]);\n\t-- en;\n}\ninline bool canDo(int l, int r){\n\ten = st = 0;\n\tFor(j,0,2*n){\n\t\tint i = perm[j];\n\t\tif(i < n or (l <= i-n && i-n <= r) or (l > r && (i-n <= r or l <= i-n))){\n\t\t\tbool flag = add(i);\n\t\t\tif(!flag)\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\npoint c1, c2;\ninline bool cmp(const int &i, const int &j){\n\tpoint a = q[i] - p[i];\n\tpoint b = q[j] - p[j];\n\tif (sign(a.X) >= 0  && sign(b.X) < 0)\n\t\treturn false;\n\tif (sign(a.X) < 0 && sign(b.X) >= 0)\n\t\treturn true;\n\tif (sign(a.X) == 0 && sign(b.X) == 0){\n\t\tif (sign(a.Y) >= 0 || sign(b.Y) >= 0)\n\t\t\treturn a.Y < b.Y;\n\t\treturn b.Y < a.Y;\n\t}\n\tdouble det = a.X * b.Y - b.X * a.Y;\n\tif (sign(det) < 0)\n\t\treturn false;\n\tif (sign(det) > 0)\n\t\treturn true;\n\tint S = sign(cross(q[j] - p[j], q[i] - p[j]));\n\tif(S)\treturn S > 0;\n\tdouble d1 = a.X * a.X  + a.Y * a.Y;\n\tdouble d2 = b.X * b.X + b.Y * b.Y;\n\treturn d1 < d2;\n}\ninline bool checker(point C1, point C2, double r){\n\tFor(i,0,n){\n\t\tint j = (i + 1) % n;\n\t\tif(cross(p[j] - p[i], C1 - p[i]) < -1e-5)\treturn false;\n\t\tif(cross(p[j] - p[i], C2 - p[i]) < -1e-5)\treturn false;\n\t\tif(min(dis(p[i], p[j], C1), dis(p[i], p[j], C2)) > r + 1e-6)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\ninline bool check(double x, bool cer = false){\n\tFor(i,0,n){\n\t\tint j = (i + 1) % n;\n\t\tperm[i] = i;\n\t\tperm[i + n] = i + n;\n\t\tp[i] = point(pol[i].x, pol[i].y);\n\t\tq[i] = point(pol[j].x, pol[j].y);\n\t\tpoint s = shift(q[i] - p[i], x);\n\t\tq[i + n] = p[i] + s;\n\t\tp[i + n] = q[i] + s;\n\t}\n\tsort(perm, perm + 2 * n, cmp);\n\tfill(len, len + n, 0);\n\tint l = 0;\n\tFor(i,0,n){\n\t\twhile(l < n && canDo(i, (i+l)%n))\t++ l;\n\t\tif(l < 1)\treturn false;\n\t\tif(l == n){\n\t\t\tif(cer){\n\t\t\t\trelax();\n\t\t\t\tFor(j,st,en)\n\t\t\t\t\tif(checker(que[j], que[j], x)){\n\t\t\t\t\t\tc1 = c2 = que[j];\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tlen[i] = l;\n\t\t-- l;\n\t}\n\tFor(i,0,n){\n\t\tint j = (i + len[i]) % n;\n\t\tif(len[i] + len[j] >= n){\n\t\t\tif(cer){\n\t\t\t\tcanDo(i,(j-1+n) % n);\n\t\t\t\trelax();\n\t\t\t\tvector<point> V;\n\t\t\t\tFor(e,st,en)\tV.pb(que[e]);\n\t\t\t\tcanDo(j, (i-1+n) % n);\n\t\t\t\trelax();\n\t\t\t\tdo{\n\t\t\t\t\tc1 = V[rand() % (int)V.size()];\n\t\t\t\t\tc2 = que[st + rand() % (en-st)];\n\t\t\t\t}while(!checker(c1, c2, x));\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\nint main(){\n\tiOS;\n\tcerr << fixed << setprecision(10);\n\tcin >> n;\n\tFor(i,0,n)\tcin >> pol[i].x >> pol[i].y;\n\tdouble lo = 0, hi = 2e4 + 100;\n\twhile(hi - lo > 1e-7){\n\t\tdouble mid = (lo + hi)/2.;\n\t\tif(check(mid))\n\t\t\thi = mid;\n\t\telse\n\t\t\tlo = mid;\n\t}\n\tcout << fixed << setprecision(30);\n\tcout << lo << endl;\n\terror(check(lo + 2e-7, true));\n\tcout << c1.X << ' ' << c1.Y << '\n';\n\tcout << c2.X << ' ' << c2.Y << endl;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "geometry",
      "two pointers"
    ],
    "rating": 3300
  },
  {
    "contest_id": "697",
    "index": "A",
    "title": "Pineapple Incident",
    "statement": "Ted has a pineapple. This pineapple is able to bark like a bulldog! At time $t$ (in seconds) it barks for the first time. Then every $s$ seconds after it, it barks twice with $1$ second interval. Thus it barks at times $t$, $t + s$, $t + s + 1$, $t + 2s$, $t + 2s + 1$, etc.\n\nBarney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time $x$ (in seconds), so he asked you to tell him if it's gonna bark at that time.",
    "tutorial": "You should check two cases for YES: $x mod s = t mod s$ and $t  \\le  x$ $x mod s = (t + 1) mod s$ and $t + 1 < x$ Time Complexity: $O(1)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nint main(){\n\tiOS;\n\tint t, s, x;\n\tcin >> t >> s >> x;\n\tcout << (((x >= t && x % s == t % s) or(x > t + 1 && x % s == (t + 1) % s)) ? \"YES\": \"NO\") << endl;\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "697",
    "index": "B",
    "title": "Barnicle",
    "statement": "Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate.\n\nBarney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number $x$ is the notation of form $AeB$, where $A$ is a real number and $B$ is an integer and $x = A × 10^{B}$ is true. In our case $A$ is between $0$ and $9$ and $B$ is non-negative.\n\nBarney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding.",
    "tutorial": "Nothing special, right? just find the position of letters . and e with string searching methods (like .find) and do the rest. Time Complexity: ${\\cal O}(n)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1000 + 10;\nstring s;\nstring t;\nint b;\nint main(){\n\tiOS;\n\tcin >> s;\n\tint e = s.find('e');\n\tFor(i,e+1,s.size())\tb = 10 * b + s[i] - '0';\n\tt += s[0];\n\tFor(i,2,e)\n\t\tt += s[i];\n\tvector<char> v;\n\twhile(t.size() < b + 1)\n\t\tt += '0';\n\tFor(i,0,b+1)\n\t\tv.pb(t[i]);\n\tv.pb('.');\n\tFor(i,b+1,t.size())\n\t\tv.pb(t[i]);\n\twhile(v.back() == '0')\n\t\tv.PB;\n\tif(v.back() == '.')\n\t\tv.PB;\n\trep(c, v)\n\t\tcout << c;\n\tcout << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "698",
    "index": "A",
    "title": "Vacations",
    "statement": "Vasya has $n$ days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this $n$ days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the $i$-th day there are four options:\n\n- on this day the gym is closed and the contest is not carried out;\n- on this day the gym is closed and the contest is carried out;\n- on this day the gym is open and the contest is not carried out;\n- on this day the gym is open and the contest is carried out.\n\nOn each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).\n\nFind the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.",
    "tutorial": "This problem can be solved with dynamic programming. Let's solve the opposite problem and find the maximum number of days which Vasya will not have a rest. We need o use two-dimensional array $d$, where $d[i][j]$ equals to the maximum number of days, which Vasya will not have a rest, if $i$ days passed and $j$ equals to: 0, if Vasya had a rest during the $i$-th day, 1, if Vasya participated in the contest on the $i$-th day, 2, if Vasya went to gym on the $i$-th day. Then the transitions for the day number $i$ look like: $d[i][0]$ must be updated with maximum value of the array $d$ for the previous day; if there will be a contest on the $i$-th day (i. e. $a_{i}$ equals to $1$ or $3$), than we update $d[i][1]$ with values $d[i - 1][0] + 1$ and $d[i - 1][2] + 1$; if the gym is open on the $i$-th day (i. e. $a_{i}$ equals to $2$ or $3$), than we update $d[i][2]$ with values $d[i - 1][0] + 1$ and $d[i - 1][1] + 1$. After that we need to choose $max$ from all values of the array $d$ for the last day and print $n - max$.",
    "tags": [
      "dp"
    ],
    "rating": 1400
  },
  {
    "contest_id": "698",
    "index": "B",
    "title": "Fix a Tree",
    "statement": "A tree is an undirected connected graph without cycles.\n\nLet's consider a rooted undirected tree with $n$ vertices, numbered $1$ through $n$. There are many ways to represent such a tree. One way is to create an array with $n$ integers $p_{1}, p_{2}, ..., p_{n}$, where $p_{i}$ denotes a parent of vertex $i$ (here, for convenience a root is considered its own parent).\n\n\\begin{center}\n{\\small For this rooted tree the array $p$ is $[2, 3, 3, 2]$.}\n\\end{center}\n\nGiven a sequence $p_{1}, p_{2}, ..., p_{n}$, one is able to restore a tree:\n\n- There must be exactly one index $r$ that $p_{r} = r$. A vertex $r$ is a root of the tree.\n- For all other $n - 1$ vertices $i$, there is an edge between vertex $i$ and vertex $p_{i}$.\n\nA sequence $p_{1}, p_{2}, ..., p_{n}$ is called valid if the described procedure generates some (any) rooted tree. For example, for $n = 3$ sequences (1,2,2), (2,3,1) and (2,1,3) \\textbf{are not} valid.\n\nYou are given a sequence $a_{1}, a_{2}, ..., a_{n}$, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.",
    "tutorial": "One can easily see that given sequence describes a functional graph, thus a directed graph with edges going from $i$ to $a_{i}$ for every $i$. This graph represents a set of cycles and each cycle vertex is a root of its own tree (possibly consisting of one vertex). Picture above shows an example of a functional graph. It consists of two cycles $1, 6, 3$ and $4$. Vertex $6$ is the root of the tree consisting of vertices $0$, $2$, $6$ and $8$, vertex $3$ roots the tree of vertices $3$ and $5$, vertex $4$ - root of tree of vertices $4$ and $7$ and vertex $1$ forms a tree of only one vertex. In terms of functional graph, our goal is to make the graph consisting of exactly one cycle of exactly one vertex looped to itself. Operation of change is equivalent to removing some outgoing edge and adding a new one, going to somewhat else vertex. Let's firstly make our graph containing only one cycle. To do so, one can choose any of initially presented cycles and say that it will be the only one. Then one should consider every other cycle, remove any of its in-cycle edges and replace it with an edge going to any of the chosen cycle's vertices. Thus the cycle will be broken and its vertices (along with tree ones) will be connected to the only chosen cycle. One will need to do exactly $cycleCount - 1$ such operations. Note that the removing of any non-cycle edge does not make sense, because it does not break any cycle. The next thing is to make the cycle length be equal to $1$. That might be already satisfied, if one will choose a cycle of minimal length and this length equals $1$. Thus, if the initial graph contains any cycle of length $1$, we are done with $cycleCount - 1$ operations. Otherwise, the cycle contains more than one vertex. It can be fixed with exactly one operation - one just need to break any of in-cycle edges, say from $u$ to $a_{u}$, and add an edge from $u$ to $u$. The graph will remain consisting of one cycle, but consisting of one self-looped vertex. In that case, we are done with $cycleCount$ operations. To do all the operations above, one can use DSU structure, or just a series of DFS. Note that there is no need in realisation of edge removing and creating, one just needs to analyze initial graph.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "699",
    "index": "A",
    "title": "Launch of Collider",
    "statement": "There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. $n$ particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, $x_{i}$ is the coordinate of the $i$-th particle and its position in the collider at the same time. All coordinates of particle positions are \\textbf{even integers}.\n\nYou know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of $1$ meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.\n\nWrite the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.",
    "tutorial": "To solve this problem it is enough to look at all pairs of adjacent particles such that the left particle will move to the right and the right particle will move to the left. If there is no such pair the answer is -1. Otherwise, let's iterate through the particles from the left to the right. If the particle $i$ will move to the right and the particle $i + 1$ will move to the left we know that this particles will be at the same point simultaneously, so we need to update the answer with value $(x_{i + 1} - x_{i}) / 2$. The answer is always integer because all coordinates of the particles are even numbers.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "699",
    "index": "B",
    "title": "One Bomb",
    "statement": "You are given a description of a depot. It is a rectangular checkered field of $n × m$ size. Each cell in a field can be empty (\".\") or it can be occupied by a wall (\"*\").\n\nYou have one bomb. If you lay the bomb at the cell $(x, y)$, then after triggering it will wipe out all walls in the row $x$ and all walls in the column $y$.\n\nYou are to determine if it is possible to wipe out all walls in the depot by placing and triggering \\textbf{exactly one bomb}. The bomb can be laid both in an empty cell or in a cell occupied by a wall.",
    "tutorial": "To solve this problem we need to calculate two arrays $V[]$ and $G[]$, where $V[j]$ must be equal to the number of walls in the column number $j$ and $G[i]$ must be equal to the number of walls in the row number $i$. Also let's store the total number of walls in the variable $cur$. Now we need to look over the cells. Let the current cell be $(x, y)$. Let's count the value $cur$ - how many walls will destroy the bomb planted in the cell $(x, y)$: $cnt = V[y] + G[x]$. If the cell $(x, y)$ has a wall we count it twice, so we need to subtract $1$ from the $cnt$. If $cur = cnt$ we found the answer and need to plant the bomb in the cell $(x, y)$. If there is no such cell we need to print \"NO\".",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "700",
    "index": "A",
    "title": "As Fast As Possible",
    "statement": "On vacations $n$ pupils decided to go on excursion and gather all together. They need to overcome the path with the length $l$ meters. Each of the pupils will go with the speed equal to $v_{1}$. To get to the excursion quickly, it was decided to rent a bus, which has seats for $k$ people (it means that it can't fit more than $k$ people at the same time) and the speed equal to $v_{2}$. In order to avoid seasick, each of the pupils want to get into the bus \\textbf{no more than once}.\n\nDetermine the minimum time required for all $n$ pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.",
    "tutorial": "This problem can be solved with formula or with help of the binary search. Let's describe the solution with binary search on the answer. If the target function of the binary search returns $true$ we need to move in mid the right end of the search, else we need to move in mid the left end of the search. The target function must works in the following way. Let's divide all pupils on the groups, the number of the groups equals to $(n + k - 1) / k$, where $n$ is the total number of pupils and $k$ is the number of seats in the bus. Then for the current $mid$ we know the minimal time which the first group of the pupils is needed to ride on the bus to reach the finish point in the time $mid$. Then we need to solve simple equation and get that this time equals to $T - (v2 \\cdot T - (l - posM)) / (v2 - v1)$, where for the first group $T$ equals to $mid$, $posM$ equals to 0 (in $posM$ we will store the position of the pupils, who did not already rode on the bus). Than we need to accurate recalculate $T$ and $posM$ for every following group (do not forget that the bus must returns back to get the other group). If for some group $v2 \\cdot T$ became less than $l - posM$ or $T$ became less than $0$, the target function must return $false$. If all groups of pupils will reach the finish point in time $mid$ the target function must return $true$. Also do not forget that the bus does not need to ride back after it took to the needed point the last group of the pupils.",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "700",
    "index": "B",
    "title": "Connecting Universities",
    "statement": "Treeland is a country in which there are $n$ towns connected by $n - 1$ two-way road such that it's possible to get from any town to any other town.\n\nIn Treeland there are $2k$ universities which are located in different towns.\n\nRecently, the president signed the decree to connect universities by high-speed network.The Ministry of Education understood the decree in its own way and decided that it was enough to connect each university with another one by using a cable. Formally, the decree will be done!\n\nTo have the maximum sum in the budget, the Ministry decided to divide universities into pairs so that the total length of the required cable will be maximum. In other words, the total distance between universities in $k$ pairs should be as large as possible.\n\nHelp the Ministry to find the maximum total distance. Of course, each university should be present in only one pair. Consider that all roads have the same length which is equal to $1$.",
    "tutorial": "Let's root a tree with vertex $1$ by single DFS and by the way find two values for every vertex $v$: $lv$ - length of the edge that leads from parent of $v$ to vertex $v$; $sv$ - the number of universities in the subtree of vertex $v$ (including $v$ itself). Consider any optimal solution, i.e. such solution that the total length is maximum. Look at some edge that leads from the parent of $v$ to $v$. We claim that it should be used in $min(s_{v}, 2 \\cdot k - s_{v})$ paths. It obviously cannot be used more time than this value, however, if it is used less number of times, that means there is at least one connected pair (let's say $a$ and $b$) located in the subtree of $v$ and at least one connected pair located outside (vertices $c$ and $d$). By the properties of the tree, paths from $a$ to $c$ and from $b$ to $d$ cover all edges of the paths from $a$ to $b$ and from $c$ to $d$ plus some extra edges, meaning the current answer is not optimal. Thus, this edge will be used exactly $min(s_{v}, 2 \\cdot k - s_{v})$ times. The above means we can compute the answer value as $\\sum_{v\\in V}m i n(s_{v},2\\cdot k-s_{v})$. Note that the above method doesn't provide the optimal matching itself (though, not many modifications required).",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "701",
    "index": "A",
    "title": "Cards",
    "statement": "There are $n$ cards ($n$ is \\textbf{even}) in the deck. Each card has a positive integer written on it. $n / 2$ people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.\n\nFind the way to distribute cards such that the sum of values written of the cards will be equal for each player. It is guaranteed that it is always possible.",
    "tutorial": "Because of it is guaranteed, that the answer always exists, we need to sort all cards in non-descending order of the numbers, which are written on them. Then we need to give to the first player the first and the last card from the sorted array, give to the second player the second and the penultimate cards and so on.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "701",
    "index": "B",
    "title": "Cells Not Under Attack",
    "statement": "Vasya has the square chessboard of size $n × n$ and $m$ rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.\n\nThe cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.\n\nYou are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are \\textbf{not under attack} after Vasya puts it on the board.",
    "tutorial": "To solve this problem we will store two sets - the set of the verticals, in which there is at least one rook, and the set of the horizontals, in which there is at least one rook. We need to iterate through the rooks in the order of we put them on the board and calculate the number of the cells under attack, after put each rook. Let we put current rook in the cell $(x, y)$. We need to add $y$ in the set of verticals and add $x$ in the set of horizontals. Let after it the size of set with verticals equals to $szY$ and the size of set with horizontals equals to $szX$. Then it is easy to show, that the number of the cells under attack equals to $cnt = szY \\cdot n + szX \\cdot n - szX \\cdot szY$, so, the number of cells which are not under attack equals to $n \\cdot n - cnt$.",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "701",
    "index": "C",
    "title": "They Are Everywhere",
    "statement": "Sergei B., the young coach of Pokemons, has found the big house which consists of $n$ flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number $1$ is only connected with the flat number $2$ and the flat number $n$ is only connected with the flat number $n - 1$.\n\nThere is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once.\n\nSergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit.",
    "tutorial": "At first let's find all different letters, which exist in the given string. It can be done with help of the array with letters or with help of the set. Then we need to use the array $len$, where $len[i]$ equals to minimal length of the substring, which ends in the position $i$ and contains all different letters from the given string. If for some position $i$ there is no such a substring, we will store in the $len[i]$ some big number, which more than the length of the given string, for example, $10^{9}$. Now we need to iterate through all different letters of the string in any order. Let the current letter equals to $c$. Let's iterate on the positions of the given string from the left to the right and will store in the variable $last$ the last position of the string $s$ in which $s[last] = c$. At first $last = - 1$. Let the current position of the given string equals to $i$. If $s[i] = c$ we need to make $last = i$. If for current position $i$ the value of the $last$ equals to $- 1$ we need to make $len[i] = 10^{9}$ (because there is no substring which ends in the position $i$ and contains all different letters of the given string $s$). In the other case, we need to update $len[i] = max(len[i], i - last + 1)$. The answer is the minimal value from all values of the array $len$ after we iterated through all different letters of the given string $s$.",
    "tags": [
      "binary search",
      "strings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "702",
    "index": "A",
    "title": "Maximum Increase",
    "statement": "You are given array consisting of $n$ integers. Your task is to find the maximum length of an increasing subarray of the given array.\n\nA subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray \\textbf{strictly greater} than previous.",
    "tutorial": "Let's iterate through the given array from the left to the right and store in the variable $cur$ the length of the current increasing subarray. If the current element is more than the previous we need to increase $cur$ on one. In the other case we need to update the answer with the value of $cur$ and put in $cur$ 1, because new increasing subarray began.",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "702",
    "index": "B",
    "title": "Powers of Two",
    "statement": "You are given $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Find the number of pairs of indexes $i, j$ ($i < j$) that $a_{i} + a_{j}$ is a power of $2$ (i. e. some integer $x$ exists so that $a_{i} + a_{j} = 2^{x}$).",
    "tutorial": "To solve this problem we need to use map $cnt$ and store in this map how many times every integer appears in the given array. Then we need to iterate through all given numbers with variable $i$. Let the current number is equal to $a_{i}$. For this number we need to iterate on all possible powers of 2 (the number of these powers is no more than 31). Let the current power is equal to $cur$. Then we need to make $cnt[a_{i}] -$ and add the value $cnt[a_{i} - cur]$ to the asnwer.",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "702",
    "index": "C",
    "title": "Cellular Network",
    "statement": "You are given $n$ points on the straight line — the positions ($x$-coordinates) of the cities and $m$ points on the same line — the positions ($x$-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than $r$ from this tower.\n\nYour task is to find minimal $r$ that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than $r$.\n\nIf $r = 0$ then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than $r$ from this tower.",
    "tutorial": "At first store coordinates of all towers in set $towers$. Then let's look through all cities. Let the current city be located in the point $cur$. Let $it = towers.lower_{bound}(cur)$. Then if $it$ is not equal to the end of the set we put in the variable $dist$ the value $( * it - cur)$ - the distance to the nearest tower on the right for the current city. If $it$ is not equal to the beginning of the set we need to make $it -$ and update $dist = min(dist, cur - * it)$ - the distance to the nearest tower on the left to the current city. After that we only need to update the answer: $ans = max(ans, dist)$. Also this problem can be solved with help of two pointers in linear time.",
    "tags": [
      "binary search",
      "implementation",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "702",
    "index": "D",
    "title": "Road to Post Office",
    "statement": "Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to $d$ kilometers.\n\nVasiliy's car is not new — it breaks after driven every $k$ kilometers and Vasiliy needs $t$ seconds to repair it. After repairing his car Vasiliy can drive again (but after $k$ kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station.\n\nTo drive one kilometer on car Vasiliy spends $a$ seconds, to walk one kilometer on foot he needs $b$ seconds ($a < b$).\n\nYour task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot.",
    "tutorial": "To solve this problem we need to analyze some cases. If $d  \\le  k$ then Vasiliy can ride car all road without breaking, so the answer is $d * a$. If $t + k * a > k * b$ (i. e. it is better to do not repair the car), Vasiliy must ride car the first $k$ kilometers and then walks on foot, so the answer is $k * a + (d - k) * b$. The only case left when it is better to ride car through all road until $d % k$ kilometers left. Now we need to understand what better - repair the car and ride or do not repair the car and walk on foot. Let $cnt = d / k$, so Vasiliy necessarily must repair the car $cnt - 1$ times. Then the answer equals to $k * cnt * a + (cnt - 1) * t + min(t + (d % k) * a, (d % k) * b)$.",
    "tags": [
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "702",
    "index": "E",
    "title": "Analysis of Pathes in Functional Graph",
    "statement": "You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from $0$ to $n - 1$.\n\nGraph is given as the array $f_{0}, f_{1}, ..., f_{n - 1}$, where $f_{i}$ — the number of vertex to which goes the only arc from the vertex $i$. Besides you are given array with weights of the arcs $w_{0}, w_{1}, ..., w_{n - 1}$, where $w_{i}$ — the arc weight from $i$ to $f_{i}$.\n\n\\begin{center}\n{\\small The graph from the first sample test.}\n\\end{center}\n\nAlso you are given the integer $k$ (the length of the path) and you need to find for each vertex two numbers $s_{i}$ and $m_{i}$, where:\n\n- $s_{i}$ — the sum of the weights of all arcs of the path with length equals to $k$ which starts from the vertex $i$;\n- $m_{i}$ — the minimal weight from all arcs on the path with length $k$ which starts from the vertex $i$.\n\nThe length of the path is the number of arcs on this path.",
    "tutorial": "This problem can be solved with help of the binary exponentiation. Let the $f_{r}[u]$ is a structure, which for the vertex $u$ store the information about the path from this vertex with length equals to $r$. The information which we need: $f_{r}[u].to$ - the number of vertex, in which ends the path with length $r$ from the vertex $u$, $f_{r}[u].len$ - the sum of the arcs weights on the path with length $r$ from the vertex $u$, $f_{r}[u].min$ - the minimal weight of the arc on the path with length $r$ from the vertex $u$. So if we have this values for all vertices and two fixed values $r$: $r = r_{1}$ and $r = r_{2}$ it is easy to find the values $f_{r1 + r2}[u]$ for all $u$: $f_{r1 + r2}[u].to = f_{r2}[f_{r1}[u].to].to$, i. e. at first we went to the vertex $f_{r1}[u].to$, and then with help of the array $f_{r2}$ we can undrstand where we will stand in the end of the path; $f_{r1 + r2}[u].len = f_{r1}[u].len + f_{r2}[f_{r1}[u].to].len$; $f_{r1 + r2}[u].min = min(f_{r1}[u].min, f_{r2}[f_{r1}[u].to].min)$. The structures for the values $r = r_{1}$ and $r = r_{2}$ are and arrays of the structures, indexed with numbers of the graph vertices. So we showed that if we have two arrays for $r = r_{1}$ and $r = r_{2}$ we can get the array for $r = r_{1} + r_{2}$. The operation which we described above we can call the multiply of the arrays, then the needed values $f_{k}$ can be found with help of raised values $f_{1}$ to the power $k$. For make it we can use the binary exponentiation. Also this problem can be solved with help of \"binary shifts\", but in fact it is the same thing that we described above.",
    "tags": [
      "data structures",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "703",
    "index": "A",
    "title": "Mishka and Game",
    "statement": "Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.\n\nRules of the game are very simple: at first number of rounds $n$ is defined. In every round each of the players throws a cubical dice with distinct numbers from $1$ to $6$ written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.\n\nIn average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.\n\nMishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!",
    "tutorial": "In this problem you had to do use the following algo. If Mishka wins Chris in the current round, then increase variable $countM$ by 1. Otherwise (if Chris wins Mishka) increase variable $countC$. After that you had to compare this values and print the answer.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "703",
    "index": "B",
    "title": "Mishka and trip",
    "statement": "Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.\n\nHere are some interesting facts about XXX:\n\n- XXX consists of $n$ cities, $k$ of whose (just imagine!) are capital cities.\n- All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of $i$-th city equals to $c_{i}$.\n- All the cities are consecutively connected by the roads, including $1$-st and $n$-th city, forming a cyclic route $1 — 2 — ... — n — 1$. Formally, for every $1 ≤ i < n$ there is a road between $i$-th and $i + 1$-th city, and another one between $1$-st and $n$-th city.\n- Each capital city is connected with each other city directly by the roads. Formally, if city $x$ is a capital city, then for every $1 ≤ i ≤ n, i ≠ x$, there is a road between cities $x$ and $i$.\n- There is \\textbf{at most one} road between any two cities.\n- Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities $i$ and $j$, price of passing it equals $c_{i}·c_{j}$.\n\nMishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing \\textbf{each of the roads} in XXX. Formally, for every pair of cities $a$ and $b$ ($a < b$), such that there is a road between $a$ and $b$ you are to find sum of products $c_{a}·c_{b}$. Will you help her?",
    "tutorial": "Let's look at the first capital. Note that the total cost of the outgoing roads is $c[id_{1}]  \\cdot  (sum - c[id_{1}])$, where $sum$ - summary beauty of all cities. Thus iterating through the capitals we can count the summary cost of roads between capitals and all the other cities. But don't forget that in this case we count the roads between pairs of capitals twice. To avoid this on each step we should update $sum = sum - c[id_{cur}]$, where $id_{cur}$ is the position of current capital. In the end we should add to the answer the cost of roads between \"non-capital\" neighbour cities. Complexity - $O(n)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "703",
    "index": "C",
    "title": "Chris and Road",
    "statement": "And while Mishka is enjoying her trip...\n\nChris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.\n\nOnce walking with his friend, John gave Chris the following problem:\n\nAt the infinite horizontal road of width $w$, bounded by lines $y = 0$ and $y = w$, there is a bus moving, presented as a convex polygon of $n$ vertices. The bus moves continuously with a constant speed of $v$ in a straight $Ox$ line in direction of decreasing $x$ coordinates, thus in time \\textbf{only $x$ coordinates} of its points are changing. Formally, after time $t$ each of $x$ coordinates of its points will be decreased by $vt$.\n\nThere is a pedestrian in the point $(0, 0)$, who can move only by a vertical pedestrian crossing, presented as a segment connecting points $(0, 0)$ and $(0, w)$ with any speed not exceeding $u$. Thus the pedestrian can move only in a straight line $Oy$ in any direction with any speed not exceeding $u$ and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly.\n\nPlease look at the sample note picture for better understanding.\n\nWe consider the pedestrian is hit by the bus, if at any moment the point he is located in lies \\textbf{strictly inside} the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus).\n\nYou are given the bus position at the moment $0$. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point $(0, w)$ and not to be hit by the bus.",
    "tutorial": "Imagine that the bus stands still and we move \"to the right\" with a constant speed $v$. Then it's not hard to see that movement along the line $y = (u / v)  \\cdot  (x - v  \\cdot  t_{0})$ is optimal, where $t_{0}$ - time in which we begin our movement. In this way answer is $t = t_{0} + (w / u)$. If $t_{0} = 0$, then we start our movement immediately. In this case we need to check that our line doesn't intersect polygon (either we can cross the road in front of a bus, or the bus is gone). Otherwise we need to find such minimal $t_{0}$ that our line is tangent to the polygon. It can be done with binary search. Complexity - $O(n log n)$. Exercise: Solve this problem in $O(n)$.",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "703",
    "index": "D",
    "title": "Mishka and Interesting sum",
    "statement": "Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$ of $n$ elements!\n\nMishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process $m$ queries.\n\nEach query is processed in the following way:\n\n- Two integers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$) are specified — bounds of query segment.\n- Integers, presented in array segment $[l, r]$ (in sequence of integers $a_{l}, a_{l + 1}, ..., a_{r}$) \\textbf{even number of times}, are written down.\n- XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are $x_{1}, x_{2}, ..., x_{k}$, then Mishka wants to know the value $x_{1}\\oplus x_{2}\\oplus\\cdot\\cdot\\leftrightarrow x_{k}$, where $\\mathbb{C}$ — operator of exclusive bitwise OR.\n\nSince only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented.",
    "tutorial": "Easy to see, that the answer for query is XOR-sum of all elements in the segment xored with XOR-sum of distinct elements in the segment. XOR-sum of all numbers we can find in $O(1)$ using partial sums. As for the XOR-sum of distinct numbers... Let's solve easier problem. Let the queries be like \"find the number of distinct values in a segment\". Let's sort all the queries according to their right bounds and iterate through all elements of our array. We also need to make a list $last$, where $last[value]$ is the last position of $value$ on the processed prefix of array. Assume we are at position $r$. Then the answer for the query in the segment $[l, r]$ ($l  \\le  r$) is $\\textstyle\\sum_{i=1}^{r}c n t[i]$, where $cnt[i] = 1$ if $last[a_{i}] = i$ and $0$ otherwise. It's easy to store and update such values in $cnt$. When moving to the next position we have to make the following assignments: $cnt[last[a_{i}]] = 0, cnt[i] = 1, last[a_{i}] = i$. To get described sum in $O(log n)$ we can use segment tree (or Fenwick tree) instead of standard array. Now let's turn back to our problem. Everything we have to do is to change assignment $cnt[i] = 1$ to $cnt[i] = a_{i}$ and count XOR-sum instead of sum. Now we can solve this problem in $O(n log n)$. P.S.: Also there is a solution with $O(n sqrt n)$ complexity (using Mo's algo), but we tried to kill it :D",
    "tags": [
      "data structures"
    ],
    "rating": 2100
  },
  {
    "contest_id": "703",
    "index": "E",
    "title": "Mishka and Divisors",
    "statement": "After playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem.\n\nYou are given integer $k$ and array $a_{1}, a_{2}, ..., a_{n}$ of $n$ integers. You are to find \\textbf{non-empty} subsequence of array elements such that the product of its elements is divisible by $k$ and it contains minimum possible number of elements.\n\nFormally, you are to find a sequence of indices $1 ≤ i_{1} < i_{2} < ... < i_{m} ≤ n$ such that $\\prod_{j=1}^{m}a_{i_{j}}$ is divisible by $k$ while $m$ is minimum possible among all such variants.\n\nIf there are more than one such subsequences, you should choose one among them, such that sum of its elements is \\textbf{minimum possible}.\n\nMishka quickly solved this problem. Will you do so?",
    "tutorial": "Let's use dp to solve this problem. Suppose $dp[i][d]$ is the minimal number of elements on prefix of size $i$, that their product is divisible by $d$. It's easy to see that $dp[i][d] = min(dp[i - 1][d], dp[i - 1][d / gcd(d, a_{i})] + 1)$. That is so because it's optimal to take as much divisors of $a_{i}$ as possible. Answer - $dp[n][k]$. Let's imrove our solution. Notice, that as $d$ we should use only divisors of $k$ (which in the worst case would be 6720). As for $gcd$, we can easily find it in $O(primes(k))$, where $primes(k)$ - number of primes in decomposition of $k$. We also need to renumber our divisors according to their prime decomposition. To get AC in this problem you had to optimize described dp and add minimization of used elements' sum. Final complexity - $O(n  \\cdot  divs(k)  \\cdot  primes(k))$.",
    "tags": [
      "dp",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "704",
    "index": "A",
    "title": "Thor",
    "statement": "Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are $n$ applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).\n\n$q$ events are about to happen (in chronological order). They are of three types:\n\n- Application $x$ generates a notification (this new notification is unread).\n- Thor reads all notifications generated so far by application $x$ (he may re-read some notifications).\n- Thor reads the first $t$ notifications generated by phone applications (notifications generated in first $t$ events of the first type). It's guaranteed that there were at least $t$ events of the first type before this event. Please note that he doesn't read first $t$ unread notifications, he just reads the very first $t$ notifications generated on his phone and he may re-read some of them in this operation.\n\nPlease help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.",
    "tutorial": "Consider a queue $e$ for every application and also a queue $Q$ for the notification bar. When an event of the first type happens, increase the number of unread notifications by 1 and push pair $(i, x)$ to $Q$ where $i$ is the index of this event among events of the first type, and also push number $i$ to queue $e[x]$. When a second type event happens, mark all numbers in queue $e[x]$ and clear this queue (also decreese the number of unread notifications by the number of elements in this queue before clearing). When a third type query happens, do the following: while Q is not empty and Q.front().first <= t: i = Q.front().first x = Q.front().second Q.pop() if mark[i] is false: mark[i] = true e[v].pop() ans = ans - 1 // it always contains the number of unread notificationsBut in C++ set works much faster than queue! Time Complexity: $O(q)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e6 + 100;\nset<int> s[maxn];\nset<pii> se;\nint main(){\n\tint n, q;\n\tscanf(\"%d %d\", &n, &q);\n\tint nx = 0;\n\twhile(q--){\n\t\tint type;\n\t\tscanf(\"%d\", &type);\n\t\tif(type == 1){\n\t\t\tint x;\n\t\t\tscanf(\"%d\", &x);\n\t\t\t-- x;\n\t\t\ts[x].insert(nx);\n\t\t\tse.insert({nx ++, x});\n\t\t}\n\t\telse if(type == 2){\n\t\t\tint x;\n\t\t\tscanf(\"%d\", &x);\n\t\t\t-- x;\n\t\t\trep(i, s[x])\n\t\t\t\tse.erase({i, x});\n\t\t\ts[x].clear();\n\t\t}\n\t\telse{\n\t\t\tint t;\n\t\t\tscanf(\"%d\", &t);\n\t\t\twhile(!se.empty() && se.begin()->x < t){\n\t\t\t\tpii p = *se.begin();\n\t\t\t\tse.erase(p);\n\t\t\t\ts[p.y].erase(p.x);\n\t\t\t}\n\t\t}\n\t\tprintf(\"%d\n\", (int)se.size());\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "704",
    "index": "B",
    "title": "Ant Man",
    "statement": "Scott Lang is at war with Darren Cross. There are $n$ chairs in a hall where they are, numbered with $1, 2, ..., n$ from left to right. The $i$-th chair is located at coordinate $x_{i}$. Scott is on chair number $s$ and Cross is on chair number $e$. Scott can jump to all other chairs (not only neighboring chairs). He wants to start at his position (chair number $s$), visit each chair \\textbf{exactly once} and end up on chair number $e$ with Cross.\n\nAs we all know, Scott can shrink or grow big (grow big only to his normal size), so at any moment of time he can be either small or large (normal). The thing is, he can only shrink or grow big while being on a chair (not in the air while jumping to another chair). Jumping takes time, but shrinking and growing big takes no time. Jumping from chair number $i$ to chair number $j$ takes $|x_{i} - x_{j}|$ seconds. Also, jumping off a chair and landing on a chair takes extra amount of time.\n\nIf Scott wants to jump to a chair on his left, he can only be small, and if he wants to jump to a chair on his right he should be large.\n\nJumping off the $i$-th chair takes:\n\n- $c_{i}$ extra seconds if he's small.\n- $d_{i}$ extra seconds otherwise (he's large).\n\nAlso, landing on $i$-th chair takes:\n\n- $b_{i}$ extra seconds if he's small.\n- $a_{i}$ extra seconds otherwise (he's large).\n\nIn simpler words, jumping from $i$-th chair to $j$-th chair takes exactly:\n\n- $|x_{i} - x_{j}| + c_{i} + b_{j}$ seconds if $j < i$.\n- $|x_{i} - x_{j}| + d_{i} + a_{j}$ seconds otherwise ($j > i$).\n\nGiven values of $x$, $a$, $b$, $c$, $d$ find the minimum time Scott can get to Cross, assuming he wants to visit each chair exactly once.",
    "tutorial": "Reduction to TSP is easy. We need the shortest Hamiltonian path from $s$ to $e$. Consider the optimal answer. Its graph is a directed path. Consider the induced graph on first $i$ chairs. In this subgraph, there are some components. Each components forms a directed path. Among these paths, there are 3 types of paths: In the future (in chairs in right side of $i$), we can add vertex to both its beginning and its end. In the future (in chairs in right side of $i$), we can add vertex to its beginning but not its end (because its end is vertex $e$). In the future (in chairs in right side of $i$), we cannot add vertex to its beginning (because its beginning is vertex $s$) but we can add to its end. There are at most 1 paths of types 2 and 3 (note that a path with beginning $s$ and ending $e$ can only exist when all chairs are in the subgraph. i.e. induced subgraph on all vertices). This gives us a dp approach: $dp[i][j][k][l]$ is the answer for when in induced subgraph on the first $i$ vertices there are $j$ components of type $1$, $k$ of type $2$ and $l$ of type $3$. Please note that it contains some informations more than just the answer. For example we count $d[i]$ or $- x[i]$ when we add $i$ to the dp, not $j$ (in the problem statement, when $i < j$). Updating it requires considering all four ways of incoming and outgoing edges to the last vertex $i$ (4 ways, because each edge has 2 ways, left or right). You may think its code will be hard, but definitely easier than code of B. Time Complexity: $O(n^{2})\\,$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 5000 + 100;\nconst ll inf = 1LL << 60;\nint a[maxn], b[maxn], c[maxn], d[maxn], x[maxn], n, s, e;\nll dp[2][maxn][2][2], ans = inf;\nint main(){\n\tiOS;\n\tcin >> n >> s >> e;\n\t-- s, -- e;\n\tFor(i,0,n)\tcin >> x[i];\n\tFor(i,0,n)\tcin >> a[i];\n\tFor(i,0,n)\tcin >> b[i];\n\tFor(i,0,n)\tcin >> c[i];\n\tFor(i,0,n)\tcin >> d[i];\n\tfill(&dp[0][0][0][0], &dp[0][0][0][0] + 8 * maxn, inf);\n\tdp[1][0][0][0] = 0;\n\tFor(i,0,n){\n\t\tbool I = i & 1;\n\t\tbool J = !I;\n\t\tFor(j,0,n+1)\tFor(k,0,2)\tFor(l,0,2)\tdp[I][j][k][l] = inf;\n\t\tFor(j,0,n+1)\tFor(k,0,2)\tFor(l,0,2)\tif(dp[J][j][k][l] != inf){\n\t\t\tll val = dp[J][j][k][l];\n\t\t\tif(i != s && i != e){\n\t\t\t\t/* LL */{\n\t\t\t\t\tll cur = 2LL * x[i] + a[i] + c[i];\n\t\t\t\t\tif(j + k + l > 1)\tsmin(dp[I][j-1][k][l], cur + val);\n\t\t\t\t\tif(i == n-1 && !j && k && l)\tsmin(ans, cur + val);\n\t\t\t\t}\n\t\t\t\t/* LR */{\n\t\t\t\t\tll cur = a[i] + d[i];\n\t\t\t\t\tif(j or k)\tsmin(dp[I][j][k][l], cur + val);\n\t\t\t\t}\n\t\t\t\t/* RL */{\n\t\t\t\t\tll cur = b[i] + c[i];\n\t\t\t\t\tif(j or l)\tsmin(dp[I][j][k][l], cur + val);\n\t\t\t\t}\n\t\t\t\t/* RR */{\n\t\t\t\t\tll cur = -2LL * x[i] + b[i] + d[i];\n\t\t\t\t\tsmin(dp[I][j+1][k][l], cur + val);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(i == s && !k){\n\t\t\t\t/* L */{\n\t\t\t\t\tll cur = x[i] + c[i];\n\t\t\t\t\tif(j)\tsmin(dp[I][j-1][1][l], cur + val);\n\t\t\t\t\tif(i == n-1 && !j && l)\tsmin(ans, cur + val);\n\t\t\t\t}\n\t\t\t\t/* R */{\n\t\t\t\t\tll cur = -x[i] + d[i];\n\t\t\t\t\tsmin(dp[I][j][1][l], cur + val);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(i == e && !l){\n\t\t\t\t/* L */{\n\t\t\t\t\tll cur = x[i] + a[i];\n\t\t\t\t\tif(j)\tsmin(dp[I][j-1][k][1], cur + val);\n\t\t\t\t\tif(i == n-1 && !j && k)\tsmin(ans, cur + val);\n\n\t\t\t\t}\n\t\t\t\t/* R */{\n\t\t\t\t\tll cur = -x[i] + b[i];\n\t\t\t\t\tsmin(dp[I][j][k][1], cur + val);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "704",
    "index": "C",
    "title": "Black Widow",
    "statement": "Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:\n\nWhere $\\boldsymbol{\\mathit{V}}$ represents logical OR and $\\mathbb{C}$ represents logical exclusive OR (XOR), and $v_{i, j}$ are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and $v_{i, j}$ are called literals.\n\nIn the equation Natalia has, the left side is actually a 2-XNF-2 containing variables $x_{1}, x_{2}, ..., x_{m}$ and their negations. An XNF formula is 2-XNF-2 if:\n\n- For each $1 ≤ i ≤ n$, $k_{i} ≤ 2$, i.e. the size of each clause doesn't exceed two.\n- Each variable occurs \\textbf{in the formula at most two times} (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa).\n\nNatalia is given a formula of $m$ variables, consisting of $n$ clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.\n\nNatalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set $x_{1}, ..., x_{m}$ with $true$ and $false$ (out of total of $2^{m}$ ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo $10^{9} + 7$.\n\nPlease, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to $false$ or $true$ gives different ways to set variables).",
    "tutorial": "Build a graph. Assume a vertex for each clause. For every variable that appears twice in the clauses, add an edge between clauses it appears in (variables that appear once are corner cases). Every vertex in this graph has degree at most two. So, every component is either a cycle or a path. We want to solve the problem for a path component. Every edge either appear the same in its endpoints or appears differently. Denote a $dp$ to count the answer. $dp[i][j]$ is the number of ways to value the edges till $i - th$ vertex in the path so that the last clause($i$'s) value is $j$ so far ($j$ is either 0 or 1). Using the last edge to update $dp[i][j]$ from $dp[i - 1]$ is really easy in theory. Counting the answer for a cycle is practically the same, just that we also need another dimension in our $dp$ for the value of the first clause (then we convert it into a path). Handling variables that appear once (edges with one endpoint, this endpoint is always an endpoint of a path component) is also hard coding. And finally we need to merge the answers. Time Complexity: $O(n+m)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e5 + 100, mod = 1e9 + 7;\ntypedef pair<int, bool> pib;\nvector<pib> lit[maxn], cl[maxn];\nint V[maxn], U[maxn];\nbool S[maxn];\nvi adj[maxn];\nint n, m;\nbool mark[maxn];\npii ans = {1, 0};\ninline void app(pii p){\n\tint x = (1LL * ans.x * p.x + 1LL * ans.y * p.y) % mod;\n\tint y = (1LL * ans.x * p.y + 1LL * ans.y * p.x) % mod;\n\tans = {x, y};\n}\nbool block[maxn], isa[maxn];\nvi pat;\nvector<bool> sgn;\ninline void dfs(int v){\n\tmark[v] = true;\n\tpat.pb(v);\n\trep(e, adj[v]){\n\t\tif(block[e])\tcontinue ;\n\t\tblock[e] = true;\n\t\tsgn.pb(S[e]);\n\t\tint u = V[e] + U[e] - v;\n\t\tif(!mark[u])\tdfs(u);\n\t}\n}\nint dp[maxn][2][2][2];\ninline int MOD(int a){\n\twhile(a >= mod)\ta -= mod;\n\treturn a;\n}\ninline void solve(){\n\tint sz = pat.size();\n\t//rep(i, pat)\terror(i);\n\tFor(i,0,sz + 2)\n\t\tFor(j,0,2)\tFor(k,0,2)\tFor(l,0,2)\tdp[i][j][k][l] = 0;\n\tdp[0][0][0][0] = 1;\n\tif(isa[pat[0]])\n\t\tdp[0][1][1][1] = 1;\n\tFor(i,1,sz)\n\t\tFor(b,0,2)\n\t\t\tFor(e,0,2)\n\t\t\t\tFor(t,0,2){\n\t\t\t\t\tint s = sgn[i-1];\n\t\t\t\t\tFor(x,0,2){\n\t\t\t\t\t\tint p = e | x;\n\t\t\t\t\t\tint w = s ^ x;\n\t\t\t\t\t\tint B = b;\n\t\t\t\t\t\tif(i == 1)\tB = p;\n\t\t\t\t\t\tint T = (2 + t + w + p - e) & 1;\n\t\t\t\t\t\tdp[i][B][w][T] = MOD(dp[i][B][w][T] + dp[i-1][b][e][t]);\n\t\t\t\t\t}\n\t\t\t\t}\n\tint o = sz-1;\n\tif((int)sgn.size() == sz){\n\t\t++ o;\n\t\tint s = sgn.back();\n\t\tFor(b,0,2)\n\t\t\tFor(e,0,2)\n\t\t\t\tFor(t,0,2)\n\t\t\t\t\tFor(x,0,2){\n\t\t\t\t\t\tint w = e | x;\n\t\t\t\t\t\tint B = b | (s ^ x);\n\t\t\t\t\t\tint T = (4 + t + w - e + B - b) & 1;\n\t\t\t\t\t\tdp[o][B][w][T] = MOD(dp[o][B][w][T] + dp[o-1][b][e][t]);\n\t\t\t\t\t}\n\t}\n\telse if(isa[pat.back()]){\n\t\t++ o;\n\t\tFor(b,0,2)\n\t\t\tFor(e,0,2)\n\t\t\t\tFor(t,0,2)\tFor(x,0,2){\n\t\t\t\t\tint w = e | x;\n\t\t\t\t\tint T = (2 + t + w - e) & 1;\n\t\t\t\t\tdp[o][b][w][T] = MOD(dp[o][b][w][T] + dp[o-1][b][e][t]);\n\t\t\t\t}\n\t}\n\tint ans[2];\n\tans[0] = ans[1] = 0;\n\tFor(b,0,2)\n\t\tFor(e,0,2)\n\t\t\tFor(t,0,2)\tans[t] = MOD(ans[t] + dp[o][b][e][t]);\n\tapp({ans[0], ans[1]});\n}\nint main(){\n\tscanf(\"%d %d\", &n, &m);\n\tFor(i,0,n){\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\twhile(k--){\n\t\t\tint a;\n\t\t\tscanf(\"%d\", &a);\n\t\t\tbool s = a > 0;\n\t\t\ta = abs(a);\n\t\t\t-- a;\n\t\t\tcl[i].pb({a, s});\n\t\t\tlit[a].pb({i, s});\n\t\t}\n\t}\n\tint t = 1;\n\tFor(i,0,m){\n\t\tif(lit[i].empty())\t\n\t\t\tt = (2LL * t) % mod;\n\t\telse if((int)lit[i].size() == 2){\n\t\t\tbool s = lit[i][0].y ^ lit[i][1].y;\n\t\t\tint v = lit[i][0].x, u = lit[i][1].x;\n\t\t\tif(v == u){\n\t\t\t\tisa[v] = true;\n\t\t\t\tif(s){\n\t\t\t\t\tapp({0, 2});\n\t\t\t\t\tcl[v].clear();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tcl[v].PB;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tadj[v].pb(i);\n\t\t\t\tadj[u].pb(i);\n\t\t\t\tV[i] = v, U[i] = u, S[i] = s;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tisa[lit[i][0].x] = true;\n\t}\n\tFor(i,0,n){\n\t\tif(mark[i])\tcontinue ;\n\t\tif(cl[i].empty()){\n\t\t\tmark[i] = true;\n\t\t\tcontinue ;\n\t\t}\n\t\tif(adj[i].empty()){\n\t\t\tmark[i] = true;\n\t\t\tif(cl[i].size() == 1)\n\t\t\t\tapp({1, 1});\n\t\t\telse\n\t\t\t\tapp({1, 3});\n\t\t\tcontinue ;\n\t\t}\n\t\tif(adj[i].size() == 1){\n\t\t\tpat.clear();\n\t\t\tsgn.clear();\n\t\t\tdfs(i);\n\t\t\tsolve();\n\t\t}\n\t}\n\tFor(i,0,n)\tif(!mark[i]){\n\t\tpat.clear();\n\t\tsgn.clear();\n\t\tdfs(i);\n\t\tsolve();\n\t}\n\tint ans = ::ans.y;\n\tans = (1LL * ans * t) % mod;\n\tprintf(\"%d\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "704",
    "index": "D",
    "title": "Captain America",
    "statement": "Steve Rogers is fascinated with new vibranium shields S.H.I.E.L.D gave him. They're all uncolored. There are $n$ shields in total, the $i$-th shield is located at point $(x_{i}, y_{i})$ of the coordinate plane. It's possible that two or more shields share the same location.\n\nSteve wants to paint all these shields. He paints each shield in either red or blue. Painting a shield in red costs $r$ dollars while painting it in blue costs $b$ dollars.\n\nAdditionally, there are $m$ constraints Steve wants to be satisfied. The $i$-th constraint is provided by three integers $t_{i}$, $l_{i}$ and $d_{i}$:\n\n- If $t_{i} = 1$, then the absolute difference between the number of red and blue shields on line $x = l_{i}$ should not exceed $d_{i}$.\n- If $t_{i} = 2$, then the absolute difference between the number of red and blue shields on line $y = l_{i}$ should not exceed $d_{i}$.\n\nSteve gave you the task of finding the painting that satisfies all the condition and the total cost is minimum.",
    "tutorial": "Assume $r < b$ (if not, just swap the colors). Build a bipartite graph where every vertical line is a vertex in part $X$ and every horizontal line is a vertex in part $Y$. Now every point(shield) is an edge (between the corresponding vertical and horizontal lines it lies on). We write 1 on an edge if we want to color it in red and 0 if in blue (there may be more than one edge between two vertices). Each constraint says the difference between 0 and 1 edges connected to a certain vertex should be less than or equal to some value. For every vertex, only the constraint with smallest value matters (if there's no constraint on this vertex, we'll add one with $d_{i} = number of edges connected to i$). Consider vertex $i$. Assume there are $q_{i}$ edges connected to it and the constraint with smallest $d$ on this vertex has $d_{j} = e_{i}$. Assume $r_{i}$ will be the number of red (with number 1 written on) edges connected to it at the end. With some algebra, you get that the constraint is fulfilled if and only if $\\frac{q_{i}-e_{i}}{2}\\le r_{i}\\le\\frac{q_{i}+e_{i}}{2}$. Denote $L_{i}=\\left|{\\frac{q_{i}-e_{i}}{2}}\\right|$ and $R_{i}=[\\frac{q_{\\bot}\\tau_{i}}{2}]$. So $L_{i}  \\le  r_{i}  \\le  R_{i}$. This gives us a L-R max-flow approach: aside these vertices, add a source $S$ and a sink $T$. For every vertex $v$ in part $X$, add an edge with minimum and maximum capacity $L_{v}$ and $R_{v}$ from $S$ to $v$. For every vertex $u$ in part $Y$, add an edge with minimum and maximum capacity $L_{u}$ and $R_{u}$ from $u$ to $T$. And finally for every edge $v - u$ from $X$ to $Y$ add an edge from $v$ to $u$ with capacity $1$ (minimum capacity is $0$). If there's no feasible flow in this network, answer is -1. Otherwise since $r  \\le  b$, we want to maximize the number of red points, that is, maximizing total flow from $S$ to $T$. Since the edges in one layer (from $X$ to $Y$) have unit capacities, Dinic's algorithm works in $O(E{\\sqrt{E}})$ (Karzanov's theorem) and because $V=O(n)$ and $E=O(n)$ Dinic's algorithm works in $O(n{\\sqrt{n}})$. Time Complexity: $O(m+n{\\sqrt{n}})$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\ntemplate <class FlowT> class MaxFlow{\n\tpublic:\n\t\tstatic const int maxn = 2e5 + 100, maxm = 5e5 + 100;\n\t\tstatic const FlowT FlowEPS = FlowT(1e-8), FlowINF = FlowT(1 << 29);\n\t\tint to[maxm * 2], prv[maxm * 2], hed[maxn], dis[maxn], pos[maxn];\n\t\tFlowT cap[maxm * 2];\n\t\tint n, m;\n\t\tinline void init(int N){n = N, m = 0;memset(hed, -1, n * sizeof hed[0]);}\n\tprivate:\n\t\tinline void add_single_edge(int v, int u, FlowT c){\n\t\t\tto[m] = u, prv[m] = hed[v], cap[m] = c, hed[v] = m ++;\n\t\t}\n\tpublic:\n\t\tinline void add_edge(int v, int u, FlowT c, FlowT d = 0){\n\t\t\tadd_single_edge(v, u, c);\n\t\t\tadd_single_edge(u, v, d);\n\t\t}\n\t\tinline bool bfs(int source, int sink){\n\t\t\tstatic int qu[maxn], head, tail;\n\t\t\thead = tail = 0;\n\t\t\tmemset(dis, -1, n * sizeof dis[0]);\n\t\t\tdis[source] = 0;\n\t\t\tqu[tail ++] = source;\n\t\t\twhile(head < tail){\n\t\t\t\tint v = qu[head ++];\n\t\t\t\tfor(int e = hed[v]; e + 1; e = prv[e])\n\t\t\t\t\tif(cap[e] > FlowEPS && dis[to[e]] == -1)\n\t\t\t\t\t\tdis[to[e]] = dis[v] + 1, qu[tail ++] = to[e];\n\t\t\t\tif(dis[sink] + 1)\tbreak ;\n\t\t\t}\n\t\t\treturn dis[sink] + 1;\n\t\t}\n\t\tinline FlowT dfs(int v, int sink, FlowT cur = FlowINF){\n\t\t\tif(v == sink)\treturn cur;\n\t\t\tFlowT ans = 0;\n\t\t\tfor(int &e = pos[v]; e + 1; e = prv[e])\n\t\t\t\tif(cap[e] > FlowEPS && dis[to[e]] == dis[v] + 1){\n\t\t\t\t\tFlowT tmp = dfs(to[e], sink, min(cur, cap[e]));\n\t\t\t\t\tcur -= tmp;\n\t\t\t\t\tans += tmp;\n\t\t\t\t\tcap[e] -= tmp;\n\t\t\t\t\tcap[e ^ 1] += tmp;\n\t\t\t\t\tif(cur <= FlowEPS/2)\tbreak ;\n\t\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t\tinline FlowT flow(int source, int sink){\n\t\t\tFlowT ans = 0;\n\t\t\twhile(bfs(source, sink)){\n\t\t\t\tmemcpy(pos, hed, n * sizeof hed[0]);\n\t\t\t\tans += dfs(source, sink);\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n};\nMaxFlow<int> F, G;\nconst int maxn = 1e5 + 100;\nvi xs, ys;\nint x[maxn], y[maxn];\ninline int MPX(int x){\n\tint i = lower_bound(all(xs), x) - xs.begin();\n\tif(i == (int)xs.size() or xs[i] != x)\treturn -1;\n\treturn i;\n}\ninline int MPY(int y){\n\tint i = lower_bound(all(ys), y) - ys.begin();\n\tif(i == (int)ys.size() or ys[i] != y)\treturn -1;\n\treturn i;\n}\nint cntx[maxn], cnty[maxn], cx[maxn], cy[maxn], idx[maxn], idy[maxn], Lx[maxn], Rx[maxn], Ly[maxn], Ry[maxn], id[maxn];\nint no_warn;\nint main(){\n\tint n, m;\n\tint R, B;\n\tno_warn = scanf(\"%d %d\", &n, &m);\n\tno_warn = scanf(\"%d %d\", &R, &B);\n\tFor(i,0,n){\n\t\tno_warn = scanf(\"%d %d\", x + i, y + i);\n\t\txs.pb(x[i]);\n\t\tys.pb(y[i]);\n\t}\n\tsort(all(xs));\n\tsort(all(ys));\n\txs.resize(unique(all(xs)) - xs.begin());\n\tys.resize(unique(all(ys)) - ys.begin());\n\tFor(i,0,n){\n\t\tx[i] = MPX(x[i]);\n\t\ty[i] = MPY(y[i]);\n\t\t++ cntx[x[i]], ++ cx[x[i]];\n\t\t++ cnty[y[i]], ++ cy[y[i]];\n\t}\n\tint X = xs.size(), Y = ys.size();\n\twhile(m--){\n\t\tint t, i, d;\n\t\tno_warn = scanf(\"%d %d %d\", &t, &i, &d);\n\t\tif(t == 1){\n\t\t\ti = MPX(i);\n\t\t\tif(i == -1)\tcontinue ;\n\t\t\tsmin(cx[i], d);\n\t\t}\n\t\telse{\n\t\t\ti = MPY(i);\n\t\t\tif(i == -1)\tcontinue ;\n\t\t\tsmin(cy[i], d);\n\t\t}\n\t}\n\tint s = X + Y,\n\t\tt = s + 1,\n\t\tS = t + 1,\n\t\tT = S + 1;\n\tF.init(T + 1);\n\tF.add_edge(t, s, n + 10);\n\tint tot = 0;\n\tFor(i,0,X){\n\t\tint deg = cntx[i];\n\t\tint d = cx[i];\n\t\tLx[i] = (deg - d + 1) / 2;\n\t\tRx[i] = (deg + d + 0) / 2;\n\t\tif(Lx[i] > Rx[i]){\n\t\t\tcout << -1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tidx[i] = F.m;\n\t\tF.add_edge(s, i, Rx[i] - Lx[i]);\n\t\tif(Lx[i]){\n\t\t\tF.add_edge(S, i, Lx[i]);\n\t\t\tF.add_edge(s, T, Lx[i]);\n\t\t\ttot += Lx[i];\n\t\t}\n\t}\n\tFor(i,0,n){\n\t\tid[i] = F.m;\n\t\tF.add_edge(x[i], X + y[i], 1);\n\t}\n\tFor(i,0,Y){\n\t\tint deg = cnty[i];\n\t\tint d = cy[i];\n\t\tLy[i] = (deg - d + 1) / 2;\n\t\tRy[i] = (deg + d + 0) / 2;\n\t\tif(Ly[i] > Ry[i]){\n\t\t\tcout << -1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tidy[i] = F.m;\n\t\tF.add_edge(X + i, t, Ry[i] - Ly[i]);\n\t\tif(Ly[i]){\n\t\t\tF.add_edge(S, t, Ly[i]);\n\t\t\tF.add_edge(X + i, T, Ly[i]);\n\t\t\ttot += Ly[i];\n\t\t}\n\t}\n\tint f = F.flow(S, T);\n\tif(f != tot){\n\t\tputs(\"-1\");\n\t\treturn 0;\n\t}\n\tG.init(t + 1);\n\tFor(i,0,X)\n\t\tG.add_edge(s, i, F.cap[idx[i]], Rx[i] - Lx[i] - F.cap[idx[i]]);\n\tFor(i,0,n){\n\t\tint C = F.cap[id[i]];\n\t\tint D = 1 - C;\n\t\tid[i] = G.m;\n\t\tG.add_edge(x[i], X + y[i], C, D);\n\t}\n\tFor(i,0,Y)\n\t\tG.add_edge(X + i, t, F.cap[idy[i]], Ry[i] - Ly[i] - F.cap[idy[i]]);\n\tG.flow(s, t);\n\tstring g = \"rb\";\n\tif(R > B)\n\t\tswap(R, B), swap(g[0], g[1]);\n\tstring ans;\n\tll cost = 0;\n\tFor(i,0,n){\n\t\tint c = G.cap[id[i]];\n\t\tcost += (c? B: R);\n\t\tans += g[c];\n\t}\n\tcout << cost << '\n';\n\tputs(ans.c_str());\n\treturn 0;\n}",
    "tags": [
      "flows",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "704",
    "index": "E",
    "title": "Iron Man",
    "statement": "Tony Stark is playing a game with his suits (they have auto-pilot now). He lives in Malibu. Malibu has $n$ junctions numbered from $1$ to $n$, connected with $n - 1$ roads. One can get from a junction to any other junction using these roads (graph of Malibu forms a tree).\n\nTony has $m$ suits. There's a special plan for each suit. The $i$-th suit will appear at the moment of time $t_{i}$ in the junction $v_{i}$, and will move to junction $u_{i}$ using the shortest path between $v_{i}$ and $u_{i}$ with the speed $c_{i}$ roads per second (passing a junctions takes no time), and vanishing immediately when arriving at $u_{i}$ (if it reaches $u_{i}$ in time $q$, it's available there at moment $q$, but not in further moments). Also, suits move continuously (for example if $v_{i} ≠ u_{i}$, at time $t_{i}+{\\frac{1}{2c_{i}}}$ it's in the middle of a road. Please note that if $v_{i} = u_{i}$ it means the suit will be at junction number $v_{i}$ only at moment $t_{i}$ and then it vanishes.\n\nAn explosion happens if at any moment of time two suits share the same exact location (it may be in a junction or somewhere on a road; while appearing, vanishing or moving).\n\nYour task is to tell Tony the moment of the the first explosion (if there will be any).",
    "tutorial": "First, we're gonna solve the problem for when the given tree is a bamboo (path). For simplifying, assume vertices are numbered from left to right with $1, 2, .., n$ (it's an array). There are some events (appearing and vanishing). Sort these events in chronological order. At first (time $-  \\infty $) no suit is there. Consider a moment of time $t$. In time $t$, consider all available suits sorted in order of their positions. This gives us a vector $f(t)$. Lemma 1: If $i$ and $j$ are gonna be at the same location (and explode), there's a $t$ such that $i$ and $j$ are both present in $f(t)$ and in $f(t)$ they're neighbours. This is obvious since if at the moment before they explode there's another suit between them, $i$ or $j$ and that suit will explode (and $i$ and $j$ won't get to the same location). Lemma 2: If $i$ and $j$ are present in $f(t)$ and in time $t$, $i$ has position less than $j$, then there's no time $e > t$ such that in it $i$ has position greater than $j$. This hold because they move continuously and the moment they wanna pass by each other they explode. So this gives us an approach: After sorting the events, process them one by one. consider $ans$ is the best answer we've got so far (earliest explosion, initially $ \\infty $). Consider there's a set $se$ that contains the current available suits at any time, compared by they positions (so comparing function for this set would be a little complicated, because we always want to compare the suits in the current time, i.e. the time when the current event happens). If at any moment of time, time of event to be processed is greater than or equal to $ans$, we break the loop. When processing events: First of all, because current event's time is less than current $ans$, elements in $se$ are still in increasing order of their position due to lemma 2 (because if two elements were gonna switch places, they would explode before this event and $ans$ would be equal to their explosion time). There are two types of events: Suit $i$ appears. After updating the current moment of time (so $se$'s comparing function can use it), we insert $i$ into $se$. Then we check $i$ with its two neighbours in $se$ to update $ans$ (check when $i$ and its neighbours are gonna share the same position). Suit $i$ vanishes. After updating the current moment of time, we erase $i$ from $se$ and check its two previous neighbours (which are now neighbours to each other) and update $ans$ by their explosion time. This algorithm will always find the first explosion due to lemma 1 (because the suits that're gonna explode first are gonna be neighbours at some point). This algorithm only works for bamboos. For the original problem, we'll use heavy-light decompositions. At first, we decompose the path of a suit into heavy-light sub-chains (like $l$ sub-chains) and we replace this suit by $l$ suits, each moving only within a subchain. Now, we solve the problem for each chain (which is a bamboo, and we know how to solve the problem for a bamboo). After replacing each suit, we'll get $O(m l g(n))$ suits because $l=O(l g(n))$ and we need an extra log for sorting events and using set, so the total time complexity is $O(m l g^{2}(n))$. In implementation to avoid double and floating point bugs, we can use a pair of integers (real numbers). Time Complexity (more precisely): $O(n l g(n)+m l g^{2}(n)+m l g(n)l g(m))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e5 + 10, maxl = 19;\nconst ll inf = 1LL << 60;\nconst double eps = 1e-12;\nstruct frac{\n\tll x, y;\n\tfrac(){x = 0, y = 1;}\n\tfrac(ll X, ll Y){\n\t\tx = X, y = Y;\n\t\tll g = __gcd(abs(x), abs(y));\n\t\tx /= g, y /= g;\n\t\tif(y < 0)\tx = -x, y = -y;\n\t}\n\tinline void relax(){\n\t\tll g = __gcd(abs(x), abs(y));\n\t\tx /= g, y /= g;\n\n\t}\n\tfrac(ll X){x = X, y = 1;}\n\tinline ostream& operator << (ostream &cout){\n\t\tcout << (double)x/(double)y;\n\t\treturn cout;\n\t}\n\tinline const double val() const{\n\t\treturn (double)x/(double)y;\n\t}\n\tinline void operator = (const frac &r){\n\t\tx = r.x, y = r.y;\n\t}\n\tinline bool operator < (const frac &r)\tconst{\n\t\treturn val() < r.val();\n\t}\n\tinline bool operator > (const frac &r)\tconst{\n\t\treturn val() > r.val();\n\t}\n\tinline bool operator <= (const frac &r)\tconst{\n\t\treturn val() < r.val() + eps;\n\t}\n\tinline bool operator >= (const frac &r)\tconst{\n\t\treturn val() + eps > r.val();\n\t}\n\tinline frac operator + (const frac &r) const{\n\t\tfrac ans;\n\t\tif(y == r.y){\n\t\t\tans.x = x + r.x;\n\t\t\tans.y = y;\n\t\t}\n\t\telse{\n\t\t\tans.y = y * r.y;\n\t\t\tans.x = x * r.y + r.x * y;\n\t\t}\n\t\tif(!ans.x)\tans.y = 1;\n\t\tif(ans.y < 0)\tans.x = -ans.x, ans.y = -ans.y;\n\t\treturn ans;\n\t}\n\tinline frac operator - (const frac &r) const{\n\t\tfrac ans;\n\t\tif(y == r.y){\n\t\t\tans.x = x - r.x;\n\t\t\tans.y = y;\n\t\t\treturn ans;\n\t\t}\n\t\telse{\n\t\t\tans.y = y * r.y;\n\t\t\tans.x = x * r.y - r.x * y;\n\t\t}\n\t\tif(!ans.x)\tans.y = 1;\n\t\tif(ans.y < 0)\tans.x = -ans.x, ans.y = -ans.y;\n\t\treturn ans;\n\t}\n\tinline frac operator * (const frac &r) const{\n\t\tfrac ans;\n\t\tans.y = y * r.y;\n\t\tans.x = x * r.x ;\n\t\tll g = __gcd(abs(ans.x), abs(ans.y));\n\t\tans.x /= g, ans.y /= g;\n\t\tif(!ans.x)\tans.y = 1;\n\t\tif(ans.y < 0)\tans.x = -ans.x, ans.y = -ans.y;\n\t\treturn ans;\n\t}\n\tinline frac operator / (const frac &r) const{\n\t\tfrac ans;\n\t\tans.y = y * r.x;\n\t\tans.x = x * r.y ;\n\t\tif(!ans.x)\tans.y = 1;\n\t\tif(ans.y < 0)\tans.x = -ans.x, ans.y = -ans.y;\n\t\treturn ans;\n\t}\n\n\tinline frac operator + (const ll &r) const{\n\t\treturn (*this) + frac(r);\n\t}\n\tinline frac operator - (const ll &r) const{\n\t\treturn (*this) - frac(r);\n\t}\n\tinline frac operator * (const ll &r) const{\n\t\treturn (*this) * frac(r);\n\t}\n\tinline frac operator / (const ll &r) const{\n\t\treturn (*this) / frac(r);\n\t}\n\n};\nint st[maxn], ft[maxn], par[maxn][maxl], h[maxn], tim, sz[maxn], fst[maxn], stm[maxn], lst[maxn];\nint BIG[maxn];\nvi adj[maxn];\nint n, m;\nstruct CAR{\n\tint v, u, c;\n\tfrac t;\n}a[maxn];\ninline void DFS(int v = 0, int p = -1){\n\tsz[v] = 1;\n\trep(u, adj[v])\tif(u - p){\n\t\tDFS(u, v);\n\t\tsz[v] += sz[u];\n\t}\n}\ninline void dfs(int v = 0, int p = -1, bool big = false){\n\tBIG[v] = v;\n\tfst[v] = (big? fst[p]: v);\n\tstm[tim] = v;\n\tst[v] = tim ++;\n\tpar[v][0] = p;\n\tif(~p)\th[v] = h[p] + 1;\n\tFor(i,1,maxl)\tif(~par[v][i-1])\n\t\tpar[v][i] = par[par[v][i-1]][i-1];\n\tint mx = 0, I = -1;\n\tFor(i,0,adj[v].size())\tif(adj[v][i] - p && mx < sz[adj[v][i]])\n\t\tmx = sz[adj[v][i]], I = i, BIG[v] = adj[v][i];\n\tif(~I)\n\t\trotate(adj[v].begin(), adj[v].begin() + I, adj[v].end());\n\tFor(i,0,adj[v].size())\tif(adj[v][i] - p)\n\t\tdfs(adj[v][i], v, !i);\n\tft[v] = tim;\n\tsmax(lst[fst[v]],  st[v]);\n}\ninline bool anc(int v, int u){// u is ancestor of v\n\treturn st[u] <= st[v] && ft[v] <= ft[u];\n}\ninline int lca(int v, int u){\n\tif(h[v] < h[u])\tswap(v, u);\n\trof(i,maxl-1,-1)\tif(~par[v][i] && h[par[v][i]] >= h[u])\n\t\tv = par[v][i];\n\tif(v == u)\treturn v;\n\trof(i,maxl-1,-1)\tif(par[v][i] - par[u][i])\n\t\tv = par[v][i], u = par[u][i];\n\treturn par[v][0];\n}\ntypedef pair<frac, frac> pd;\ntypedef pair<pii, int> piii;\ntypedef pair<piii, pd> car;\nvector<car> cars[maxn];\ninline int sign(frac x){\n\tif(!x.x)\treturn 0;\n\tif(x.x > 0)\treturn 1;\n\treturn -1;\n}\ninline void add(int v, int u, int i, bool LA = true, bool rev = false){ // u is ancestor of v\n\tint V = v;\n\twhile(fst[v] != fst[u]){\n\t\tint l = v;\n\t\tint r = par[fst[v]][0];\n\t\tfrac b = frac(h[V] - h[l])/frac(a[i].c) + a[i].t;\n\t\tfrac e = frac(h[V] - h[r])/frac(a[i].c) + a[i].t;\n\t\tif(!rev)\tcars[fst[v]].pb({{{h[l], h[r]}, i}, {b, e}});\n\t\telse\t\tcars[fst[v]].pb({{{h[r], h[l]}, i}, {e, b}});\n\t\tv = par[fst[v]][0];\n\t}\n\tif(!LA)\treturn ;\n\tint l = v;\n\tint r = u;\n\tfrac b = frac(h[V] - h[l])/frac(a[i].c) + a[i].t;\n\tfrac e = frac(h[V] - h[r])/frac(a[i].c) + a[i].t;\n\tif(!rev)\tcars[fst[v]].pb({{{h[l], h[r]}, i}, {b, e}});\n\telse\t\tcars[fst[v]].pb({{{h[r], h[l]}, i}, {e, b}});\n}\nfrac ans(2e5);\nint I = -1, J = -1, ID;\nfrac TIME;\n\ninline frac pos(const int &i){\n\tfrac dis (cars[ID][i].x.x.y - cars[ID][i].x.x.x);\n\tfrac T = cars[ID][i].y.y - cars[ID][i].y.x;\n\tif(!sign(T))\n\t\treturn cars[ID][i].x.x.x;\n\tfrac V (sign(dis) * a[cars[ID][i].x.y].c);\n\tfrac ans =  V * (TIME - cars[ID][i].y.x) + cars[ID][i].x.x.x ;\n\treturn ans;\n}\nstruct cmp{\n\tinline bool operator ()(const int &i, const int &j) const{\n\t\tfrac a = pos(i), b = pos(j);\n\t\tif(a < b or a > b)\treturn a < b;\n\t\treturn i < j;\n\t}\n};\ninline void check(int i, int j){\n\tfrac A = pos(i), B = pos(j);\n\tif(A < B)\tswap(A, B), swap(i, j);\n\tif(A <= B && A >= B){\n\t\tif(ans > TIME)\n\t\t\tans = TIME, I = cars[ID][i].x.y, J = cars[ID][j].x.y;\n\t\treturn ;\n\t}\n\tfrac dis (cars[ID][i].x.x.y - cars[ID][i].x.x.x);\n\tfrac T = cars[ID][i].y.y - cars[ID][i].y.x;\n\tif(!sign(T)){\n\t\treturn ;\n\t}\n\tfrac VI (sign(dis) * a[cars[ID][i].x.y].c);\n\n\tdis = frac(cars[ID][j].x.x.y - cars[ID][j].x.x.x);\n\tT = cars[ID][j].y.y - cars[ID][j].y.x;\n\tif(!sign(T)){\n\t\treturn ;\n\t}\n\tfrac VJ (sign(dis) * a[cars[ID][j].x.y].c);\n\n\tif(sign(VI) > 0  && VJ <= VI){\n\t\treturn ;\n\t}\n\tif(sign(VJ) < 0 && VI >= VJ){\n\t\treturn ;\n\t}\n\tfrac t = TIME + (A-B)/(VJ-VI);\n\tfrac e = min(cars[ID][i].y.y, cars[ID][j].y.y);\n\tif(t > min(cars[ID][i].y.y, cars[ID][j].y.y))\treturn ;\n\tif(t < max(cars[ID][i].y.x, cars[ID][j].y.x))\treturn ;\n\tif(ans > t)\n\t\tans = t, I = cars[ID][i].x.y, J = cars[ID][j].x.y;\n}\ninline void solve(int id){\n\tID = id;\n\ttypedef pair<frac, pii> event;\n\tset<event> se;\n\tset<int, cmp> pp;\n\tFor(i,0,cars[id].size()){\n\t\tse.insert({cars[id][i].y.x, {0, i}});\n\t\tse.insert({cars[id][i].y.y, {1, i}});\n\t}\n\trep(e, se){\n\t\tif(e.x >= ans)\treturn ;\n\t\tTIME = e.x;\n\t\tint i = e.y.y;\n\t\tif(!e.y.x){\n\t\t\tpp.insert(i);\n\t\t\tauto it = pp.find(i);\n\t\t\tauto it2 = it;\n\t\t\tif(it != pp.begin()){\n\t\t\t\t-- it;\n\t\t\t\tcheck(*it, i);\n\t\t\t}\n\t\t\t++ it2;\n\t\t\tif(it2 != pp.end()){\n\t\t\t\tcheck(i, *it2);\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tauto it = pp.find(i);\n\t\t\tassert(it != pp.end());\n\t\t\tauto it2 = it;\n\t\t\t++ it2;\n\t\t\tif(it != pp.begin() && it2 != pp.end()){\n\t\t\t\t-- it;\n\t\t\t\tcheck(*it, *it2);\n\t\t\t}\n\t\t\tpp.erase(i);\n\t\t}\n\t}\n}\nint no_warn;\nint main(){\n\tmemset(par, -1, sizeof par);\n\tno_warn = scanf(\"%d %d\", &n, &m);\n\tFor(i,1,n){\n\t\tint v, u;\n\t\tno_warn = scanf(\"%d %d\", &v, &u);\n\t\t-- v, -- u;;\n\t\tadj[v].pb(u), adj[u].pb(v);\n\t}\n\tDFS();\n\tdfs();\n\tFor(i,0,m){\n\t\tint t;\n\t\tno_warn = scanf(\"%d %d %d %d\", &t, &a[i].c, &a[i].v, &a[i].u);\n\t\ta[i].t = frac(t);\n\t\tint &v = a[i].v, &u = a[i].u;\n\t\t-- v, -- u;\n\t\tint x = lca(v, u);\n\t\tbool V = false, U = false;\n\t\tif(v == u){\n\t\t\tadd(v, x, i);\n\t\t\tcontinue;\n\t\t}\n\t\tif(x != v && (x == u or anc(v, BIG[x])))\tV = true;\n\t\telse\tU = true;\n\t\tif(x != v){\n\t\t\tadd(v, x, i, V);\n\t\t}\n\t\tif(x != u){\n\t\t\tfrac T = frac(h[v] + h[u] - 2*h[x])/frac(a[i].c) + a[i].t, tt(a[i].t);\n\t\t\ta[i].c *= -1;\n\t\t\ta[i].t = T;\n\t\t\tadd(u, x, i, U, true);\n\t\t\ta[i].c *= -1;\n\t\t\ta[i].t = tt;\n\t\t}\n\t}\n\tFor(i,0,n)\tif(fst[i] == i)\tsolve(i);\n\tif(ans >= frac(2e5)){\n\t\tcout << -1 << endl;\n\t\treturn 0;\n\t}\n\tcout << fixed << setprecision(30) << (double)ans.x/(double)ans.y << endl;\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "geometry",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "705",
    "index": "A",
    "title": "Hulk",
    "statement": "Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.\n\nHulk likes the Inception so much, and like that his feelings are complicated. They have $n$ layers. The first layer is hate, second one is love, third one is hate and so on...\n\nFor example if $n = 1$, then his feeling is \"I hate it\" or if $n = 2$ it's \"I hate that I love it\", and if $n = 3$ it's \"I hate that I love that I hate it\" and so on.\n\nPlease help Dr. Banner.",
    "tutorial": "Just alternatively print \"I hate that\" and \"I love that\", and in the last level change \"that\" to \"it\". Time Complexity: ${\\mathcal{O}}(n)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nint main(){\n\tiOS;\n\tint n;\n\tcin >> n;\n\tFor(i,0,n){\n\t\tif(i % 2)\n\t\t\tcout << \"I love \";\n\t\telse\n\t\t\tcout << \"I hate \";\n\t\tif(i + 1 == n)\n\t\t\tcout << \"it\n\";\n\t\telse\n\t\t\tcout << \"that \";\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "705",
    "index": "B",
    "title": "Spider Man",
    "statement": "Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.\n\nInitially there are $k$ cycles, $i$-th of them consisting of exactly $v_{i}$ vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least $2$ vertices (for example, $x$ vertices) among all available cycles and replace it by two cycles with $p$ and $x - p$ vertices where $1 ≤ p < x$ is chosen by the player. The player who cannot make a move loses the game (and his life!).\n\nPeter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the $i$-th test he adds a cycle with $a_{i}$ vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins?\n\nPeter is pretty good at math, but now he asks you to help.",
    "tutorial": "First of all, instead of cycles, imagine we have bamboos (paths). A valid move in the game is now taking a path and deleting an edge from it (to form two new paths). So, every player in his move can delete an edge in the graph (with components equal to paths). So, no matter how they play, winner is always determined by the parity of number of edges (because it decreases by 1 each time). Second player wins if and only if the number of edges is even. At first it's even (0). In a query that adds a cycle (bamboo) with an odd number of vertices, parity and so winner won't change. When a bamboo with even number of vertices (and so odd number of edges) is added, parity and so the winner will change. Time Complexity: ${\\mathcal{O}}(n)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nint main(){\n\tiOS;\n\tint q;\n\tcin >> q;\n\tint ans = 0;\n\twhile(q--){\n\t\tint a;\n\t\tcin >> a;\n\t\t--a;\n\t\tans ^= a & 1;\n\t\tcout << 2 - ans << '\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "games",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "706",
    "index": "A",
    "title": "Beru-taxi",
    "statement": "Vasiliy lives at point $(a, b)$ of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested $n$ available Beru-taxi nearby. The $i$-th taxi is located at point $(x_{i}, y_{i})$ and moves with a speed $v_{i}$.\n\nConsider that each of $n$ drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.",
    "tutorial": "We know that time=distance/speed. For each car we should find $time_{i}$, than if it is less than answer we should update it. Time Complexity: O(n).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ndouble dist (int x1, int y1, int x, int y){\n    return sqrt((x1 - x) * (x1 - x) + (y - y1)*(y - y1));\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    int n, x, y;\n    cin >> x >> y >> n;\n    long double time = 1e9;\n    for (int i = 0; i < n; i++){\n        int xi, yi, vi;\n        cin >> xi >> yi >> vi;\n        long double now_time = dist(xi, yi, x, y) / (vi * 1.);\n        time = min(time, now_time);\n    }\n    cout << fixed;\n    cout << setprecision(20) << time;\n    return 0;\n}",
    "tags": [
      "brute force",
      "geometry",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "706",
    "index": "B",
    "title": "Interesting drink",
    "statement": "Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink \"Beecola\", which can be bought in $n$ different shops in the city. It's known that the price of one bottle in the shop $i$ is equal to $x_{i}$ coins.\n\nVasiliy plans to buy his favorite drink for $q$ consecutive days. He knows, that on the $i$-th day he will be able to spent $m_{i}$ coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of \"Beecola\".",
    "tutorial": "Consider $c[x]$ the number of stores in which the price per drink is $x$. We calculate this array prefix sum. Then the following options: 1) If the current amount of money $m$ is larger than the size of the array with the prefix sums than answer is $n$. 2) Otherwise, the answer is $c[m]$. Time Complexity: O(n+q).",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int N = (int)1e5 + 5;\n\nint cost[N], dp[N];\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; i++){\n        int x;\n        cin >> x;\n        cost[x]++;\n    }\n    for (int i = 1; i < N; i++){\n        dp[i] = dp[i - 1] + cost[i];\n    }\n    int q;\n    cin >> q;\n    for (int i = 0; i < q; i++){\n        int m;\n        cin >> m;\n        if (m > (N - 1)){\n            cout << n << endl;\n        } else {\n            cout << dp[m] << endl;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "706",
    "index": "C",
    "title": "Hard problem",
    "statement": "Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.\n\nVasiliy is given $n$ strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).\n\nTo reverse the $i$-th string Vasiliy has to spent $c_{i}$ units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.\n\nString $A$ is lexicographically smaller than string $B$ if it is shorter than $B$ ($|A| < |B|$) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in $A$ is smaller than the character in $B$.\n\nFor the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.",
    "tutorial": "We will solve the problem with the help of dynamic programming. $dp[i][j]$ is the minimum amount of energy that should be spent to make first $i$ strings sorted in lexicographical order and $i$-th of them will be reversed if $j$ = 1 and not reversed if $j$ = 0. $dp[i][j]$ is updated by $dp[i - 1][0]$ and $dp[i - 1][1]$. It remains to verify that the $i$-th string is lexicographically greater than $(i - 1)$-th (if $j$ = 1 then we should check reversed $i$-th string, similar to $(i - 1)$-th). Then we update $dp[i][j]$ = min($dp[i][j]$, $dp[i - 1][0]$ + $c[i]$ * $j$), $dp[i][j]$ = min($dp[i][j]$, $dp[i - 1][1]$ + $j$ * $c[i]$). The answer is a minimum of $dp[n][0]$ and $dp[n][1]$. Time Complexity: O(n+sum_length).",
    "code": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <stdio.h>\n\nusing namespace std;\n\nint n;\nvector <string> str;\nlong long c[200000];\nlong long dp[200000][2];\n\nstring rev(string x)\n{\n\tstring y;\n\tfor (int i = x.size() - 1; i >= 0; i--)\n\t\ty += x[i];\n\treturn y;\n}\n\nbool check(string a, string b)\n{\n\tfor (int i = 0; i < min(a.size(), b.size()); i++)\n\t{\n\t\tif (a[i] < b[i])\n\t\t\treturn 0;\n\t\tif (a[i] > b[i])\n\t\t\treturn 1;\n\t}\n\treturn a.size() >= b.size();\n}\n\nint main()\n{\n\tcin >> n;\n\tfor (int i = 0; i < n; i++)\n\t\tcin >> c[i];\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tstring s;\n\t\tcin >> s;\n\t\tstr.push_back(s);\n\t}\n\tfor (int i = 0; i < 200000; i++)\n\t{\n\t\tdp[i][0] = 1000000000000000000;\n\t\tdp[i][1] = 1000000000000000000;\n\t}\n\tdp[0][0] = 0;\n\tdp[0][1] = c[0];\n\tfor (int i = 1; i < n; i++)\n\t{\n\t\tif (check(str[i], str[i - 1]) && dp[i - 1][0] < dp[i][0])\n\t\t\tdp[i][0] = dp[i - 1][0];\n\t\tif (check(str[i], rev(str[i - 1])) && dp[i - 1][1] < dp[i][0])\n\t\t\tdp[i][0] = dp[i - 1][1];\n\t\tif (check(rev(str[i]), str[i - 1]) && dp[i - 1][0] + c[i] < dp[i][1])\n\t\t\tdp[i][1] = dp[i - 1][0] + c[i];\n\t\tif (check(rev(str[i]), rev(str[i - 1])) && dp[i - 1][1] + c[i] < dp[i][1])\n\t\t\tdp[i][1] = dp[i - 1][1] + c[i];\n\t}\n\tif (dp[n - 1][0] == 1000000000000000000 && dp[n - 1][1] == 1000000000000000000)\n\t{\n\t\tcout << -1 << endl;\n\t\treturn 0;\n\t}\n\tcout << min(dp[n - 1][0], dp[n - 1][1]) << endl;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "706",
    "index": "D",
    "title": "Vasiliy's Multiset",
    "statement": "Author has gone out of the stories about Vasiliy, so here is just a formal task description.\n\nYou are given $q$ queries and a multiset $A$, initially containing only integer $0$. There are three types of queries:\n\n- \"+ x\" — add integer $x$ to multiset $A$.\n- \"- x\" — erase one occurrence of integer $x$ from multiset $A$. It's guaranteed that at least one $x$ is present in the multiset $A$ before this query.\n- \"? x\" — you are given integer $x$ and need to compute the value $\\operatorname*{max}_{y\\in A}(x\\oplus y)$, i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer $x$ and some integer $y$ from the multiset $A$.\n\nMultiset is a set, where equal elements are allowed.",
    "tutorial": "Let's store each number in binary system (each number consists of 32 bits, 0 or 1) in such a data structure as trie.The edges will be the bits 1 and 0, and the vertices will be responsible for whether it is possible to pass the current edge. To reply to a query like \"? X\" will descend the forest of high-order bits to whether the younger and now we can look XOR in the i-th bit to get one, if we can, then move on, otherwise we go to where we can go. Time Complexity: O(q*log(10^9)).",
    "code": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <stdio.h>\n\nusing namespace std;\n\nint q;\nint sz = 1;\nstruct node\n{\n\tint zero;\n\tint one;\n\tint cnt1;\n\tint cnt0;\n}a[10000000];\n\nint main()\n{\n\tcin >> q;\n\tfor (int i = 0; i <= q; i++)\n\t{\n\t\tchar c;\n\t\tint x;\n\t\tif(i==0)\n\t\t{\n\t\t    c='+';\n\t\t    x=0;\n\t\t}\n\t\telse\n\t\tcin >> c >> x;\n\t\tif (c == '+')\n\t\t{\n\t\t\tint bit[32];\n\t\t\tfor (int i = 0; i < 32; i++)\n\t\t\t{\n\t\t\t\tbit[i] = x % 2;\n\t\t\t\tx /= 2;\n\t\t\t}\n\t\t\tint v = 1;\n\t\t\tfor (int i = 31; i >= 0; i--)\n\t\t\t{\n\t\t\t\tif (bit[i] == 1)\n\t\t\t\t{\n\t\t\t\t\ta[v].cnt1++;\n\t\t\t\t\tif (a[v].one == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsz++;\n\t\t\t\t\t\ta[v].one = sz;\n\t\t\t\t\t}\n\t\t\t\t\tv = a[v].one;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ta[v].cnt0++;\n\t\t\t\t\tif (a[v].zero == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsz++;\n\t\t\t\t\t\ta[v].zero = sz;\n\t\t\t\t\t}\n\t\t\t\t\tv = a[v].zero;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (c == '-')\n\t\t{\n\t\t\tint bit[32];\n\t\t\tfor (int i = 0; i < 32; i++)\n\t\t\t{\n\t\t\t\tbit[i] = x % 2;\n\t\t\t\tx /= 2;\n\t\t\t}\n\t\t\tint v = 1;\n\t\t\tfor (int i = 31; i >= 0; i--)\n\t\t\t{\n\t\t\t\tif (bit[i] == 1)\n\t\t\t\t{\n\t\t\t\t\ta[v].cnt1--;\n\t\t\t\t\tv = a[v].one;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ta[v].cnt0--;\n\t\t\t\t\tv = a[v].zero;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (c == '?')\n\t\t{\n\t\t\tint ans = 0;\n\t\t\tint bit[32];\n\t\t\tfor (int i = 0; i < 32; i++)\n\t\t\t{\n\t\t\t\tbit[i] = x % 2;\n\t\t\t\tx /= 2;\n\t\t\t}\n\t\t\tint v = 1;\n\t\t\tfor (int i = 31; i >= 0; i--)\n\t\t\t{\n\t\t\t\tif (bit[i] == 1)\n\t\t\t\t{\n\t\t\t\t\tif (a[v].cnt0 > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tans += (1 << i);\n\t\t\t\t\t\tv = a[v].zero;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tv = a[v].one;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (a[v].cnt1 > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tans += (1 << i);\n\t\t\t\t\t\tv = a[v].one;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tv = a[v].zero;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << ans << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "706",
    "index": "E",
    "title": "Working routine",
    "statement": "Vasiliy finally got to work, where there is a huge amount of tasks waiting for him. Vasiliy is given a matrix consisting of $n$ rows and $m$ columns and $q$ tasks. Each task is to swap two submatrices of the given matrix.\n\nFor each task Vasiliy knows six integers $a_{i}$, $b_{i}$, $c_{i}$, $d_{i}$, $h_{i}$, $w_{i}$, where $a_{i}$ is the index of the row where the top-left corner of the first rectangle is located, $b_{i}$ is the index of its column, $c_{i}$ is the index of the row of the top-left corner of the second rectangle, $d_{i}$ is the index of its column, $h_{i}$ is the height of the rectangle and $w_{i}$ is its width.\n\nIt's guaranteed that two rectangles in one query do not overlap and do not touch, that is, no cell belongs to both rectangles, and no two cells belonging to different rectangles \\textbf{share a side}. However, rectangles are allowed to share an angle.\n\nVasiliy wants to know how the matrix will look like after all tasks are performed.",
    "tutorial": "Let's surround the matrix with the frame of elements. In each element of the matrix, and frame we need to store value, the number of the right element and the number of down element. When a request comes we should change only values of the elements along the perimeter of rectangles. Time Complexity: O(q*(n+m)).",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "707",
    "index": "A",
    "title": "Brain's Photos",
    "statement": "Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.\n\nAs you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).\n\nBrain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!\n\nAs soon as Brain is a photographer not programmer now, he asks you to help him determine for a \\textbf{single} photo whether it is colored or black-and-white.\n\nPhoto can be represented as a matrix sized $n × m$, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only $6$ colors:\n\n- 'C' (cyan)\n- 'M' (magenta)\n- 'Y' (yellow)\n- 'W' (white)\n- 'G' (grey)\n- 'B' (black)\n\nThe photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.",
    "tutorial": "We need to do exactly what is written in the task: to consider all of the characters, and, if there is at least one of the set ${C, M, Y}$ print \"#Color\" else - \"#Black&White\"",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "707",
    "index": "B",
    "title": "Bakery",
    "statement": "Masha wants to open her own bakery and bake muffins in one of the $n$ cities numbered from $1$ to $n$. There are $m$ bidirectional roads, each of whose connects some pair of cities.\n\nTo bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only $k$ storages, located in different cities numbered $a_{1}, a_{2}, ..., a_{k}$.\n\nUnforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another $n - k$ cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay $1$ ruble.\n\nFormally, Masha will pay $x$ roubles, if she will open the bakery in some city $b$ ($a_{i} ≠ b$ for every $1 ≤ i ≤ k$) and choose a storage in some city $s$ ($s = a_{j}$ for some $1 ≤ j ≤ k$) and $b$ and $s$ are connected by some path of roads of summary length $x$ (if there are more than one path, Masha is able to choose which of them should be used).\n\nMasha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of $k$ storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.",
    "tutorial": "Note that it makes no sense to choose the city for bakeries and the city with the warehouse so that had more than one way between them, as every road increases the distance over which you have to pay. So, the problem reduces to the following: select two neighboring cities so that one is a warehouse, and in the other & mdash; no. For doing this, simply iterate through all the city with the warehouse, among the neighbors of each town without looking for a warehouse and update the answer. If there is such a pair of cities, print -1.",
    "tags": [
      "graphs"
    ],
    "rating": 1300
  },
  {
    "contest_id": "707",
    "index": "D",
    "title": "Persistent Bookcase ",
    "statement": "Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.\n\nAfter reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.\n\nThe bookcase consists of $n$ shelves, and each shelf has exactly $m$ positions for books at it. Alina enumerates shelves by integers from $1$ to $n$ and positions at shelves — from $1$ to $m$. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.\n\nAlina wrote down $q$ operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types:\n\n- $1$ $i$ $j$ — Place a book at position $j$ at shelf $i$ if there is no book at it.\n- $2$ $i$ $j$ — Remove the book from position $j$ at shelf $i$ if there is a book at it.\n- $3$ $i$ — Invert book placing at shelf $i$. This means that from every position at shelf $i$ which has a book at it, the book should be removed, and at every position at shelf $i$ which has not book at it, a book should be placed.\n- $4$ $k$ — Return the books in the bookcase in a state they were after applying $k$-th operation. In particular, $k = 0$ means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.\n\nAfter applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so?",
    "tutorial": "bookcase Solution No. 1: Note that the data is delivered all at once (offline). Then we can build a tree of versions, then run out of the DFS root and honestly handle each request in the transition from the top to the top. Solution No. 2: Note that Alina uses operations that relate to the columns. We can make an array of versions of the shelves, and each version of the cabinet to provide an array of indices and the corresponding shelves to store it explicitly. Then, for the operation, such as changing wardrobe, shelves, a new version which has been changed, this version of the index is recorded on the same shelf position. This approach eliminates the decision on the use of extra memory for storing unnecessary information.",
    "tags": [
      "bitmasks",
      "data structures",
      "dfs and similar",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "707",
    "index": "E",
    "title": "Garlands",
    "statement": "Like all children, Alesha loves New Year celebration. During the celebration he and his whole family dress up the fir-tree. Like all children, Alesha likes to play with garlands — chains consisting of a lightbulbs.\n\nAlesha uses a grid field sized $n × m$ for playing. The rows of the field are numbered from $1$ to $n$ from the top to the bottom and columns are numbered from $1$ to $m$ from the left to the right.\n\nAlesha has $k$ garlands which he places at the field. He does so in the way such that each lightbulb of each garland lies in the center of some cell in the field, and each cell contains \\textbf{at most one lightbulb}. Of course lightbulbs, which are neighbours in some garland, appears in cells neighbouring by a side.\n\n\\begin{center}\nThe example of garland placing.\n\\end{center}\n\nEach garland is turned off or turned on at any moment. If some garland is turned on then each of its lightbulbs is turned on, the same applies for garland turned off. Each lightbulb in the whole garland set is unique, and thus, being turned on, brings Alesha some pleasure, described by an integer value. Turned off lightbulbs don't bring Alesha any pleasure.\n\nAlesha can turn garlands on and off and wants to know the sum of pleasure value which the lightbulbs, placed in the centers of the cells in some rectangular part of the field, bring him. Initially \\textbf{all the garlands are turned on}.\n\nAlesha is still very little and can't add big numbers. He extremely asks you to help him.",
    "tutorial": "Let us handle each request as follows: Let's go for a \"frame\" request and remember lamp garlands, which lies on the boundary. Then, in order to find concrete garland, what part of it lies within the query, sum all of its segments, the ends of it are lamps that lie on the \"frame\". Also, do not forget the garland wich lies entirely within the request. Each garland at the beginning we find the extreme points, and to check whether it lies entirely within the query, check whether the lie inside its extreme points.",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "708",
    "index": "A",
    "title": "Letters Cyclic Shift",
    "statement": "You are given a non-empty string $s$ consisting of lowercase English letters. You have to pick \\textbf{exactly one non-empty substring} of $s$ and shift all its letters 'z' $\\to$ 'y' $\\to$ 'x' $\\to\\cdot\\cdot\\top$ 'b' $\\to$ 'a' $\\to$ 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.\n\nWhat is the lexicographically minimum string that can be obtained from $s$ by performing this shift exactly once?",
    "tutorial": "If string consists only of symbols 'a', then we could only make it lexicographically bigger. To achieve the least change we should shift the last symbol. In any other case we could make string lexicographically less. We should shift first biggest subsegment of string consists only from symbols not equal to 'a'.",
    "code": "void solve() {\n  string s;\n  cin >> s;\n  for (int i = 0; i < s.length(); ++i) {\n    if (s[i] == 'a') {\n      continue;\n    }\n    int j = i + 1;\n    while (j < s.length() && s[j] != 'a') {\n      ++j;\n    }\n    for (int r = i; r < j; ++r) {\n      --s[r];\n    }\n    cout << s << \"\\n\";\n    return;\n  }\n\n  s.back() = 'z';\n  cout << s << \"\\n\";\n\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "708",
    "index": "B",
    "title": "Recover the String",
    "statement": "For each string $s$ consisting of characters '0' and '1' one can define four integers $a_{00}$, $a_{01}$, $a_{10}$ and $a_{11}$, where $a_{xy}$ is the number of \\textbf{subsequences} of length $2$ of the string $s$ equal to the sequence ${x, y}$.\n\nIn these problem you are given four integers $a_{00}$, $a_{01}$, $a_{10}$, $a_{11}$ and have to find any non-empty string $s$ that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than $1 000 000$.",
    "tutorial": "Using $a_{00}$ and $a_{11}$ easy to calculate $c_{0}, c_{1}$ - numbers of 0 and 1 in string (it could be done by binary search or solving quadratic equation $c_{0} \\cdot (c_{0} - 1) / 2 = a_{00}$). But in case $a_{00} = 0$, $c_{0}$ is not fixed and could be equal 0 or 1. One could consider both cases for sure (or code several 'if's to throw away one of the variants). If $a_{01} + a_{10}  \\neq  c_{0} \\cdot c_{1}$, then answer is impossible. Otherwise it is possible to create such string using greedy algorithm. Consider string $b = string(c_{0}, '0') + string(c_{1}, '1')$, its array of subsequences equals ${a_{00}, a_{01} + a_{10}, 0, a_{11}}$. One could swap neighbouring pairs $01$ one by one and transform it to $string(c_{1}, '1') + string(c_{0}, '0')$ (similar to bubble sorting), its array equals ${a_{00}, 0, a_{01} + a_{10}, a_{11}}$. During this process string corresponding to array ${a_{00}, a_{01}, a_{10}, a_{11}}$ was reproduced exactly once, because every swap reduce $b_{01}$ by one and increase $b_{10}$ by one, so we have $O(n^{2})$ solution. One could make it linear: take string $b = string(c_{0}, '0') + string(c_{1}, '1')$ and move its zeros one by one directly in the end of string while $b_{01} - a_{01}  \\ge  c_{1}$. When $b_{01}$ become $b_{01} - a_{01} < c_{1}$ we will move next zero on $b_{01} - a_{01}$ symbols left and finally get desired string. There is another way to do it, when you build lexicographically smallest string one symbol by one from the beginning.",
    "code": "void imp() {\n  cout << \"Impossible\\n\";\n  exit(0);\n}\n\nll invtriange(ll x) {\n  ll l = 1, r = 1000000;\n  while (r - l > 1) {\n    ll m = (l + r) / 2;\n    if (m * (m - 1) / 2 > x) r = m;\n    else l = m;\n  }\n  if (l * (l - 1) / 2 != x) {\n    imp();\n  }\n  return l;\n}\n\nint main() {\n  vvl a(2, vl(2));\n  for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) {\n    cin >> a[i][j];\n  }\n  if (a[0][0] + a[0][1] + a[1][0] + a[1][1] == 0) {\n    cout << \"0\\n\";\n    return 0;\n  }\n  ll c0 = invtriange(a[0][0]);\n  ll c1 = invtriange(a[1][1]);\n  if (a[0][0] == 0 || a[1][1] == 0) {\n    if (a[0][1] + a[1][0] == 0) {\n      if (c0 == 1) c0 = 0;\n      if (c1 == 1) c1 = 0;\n      cout << string(c0, '0') << string(c1, '1');\n      return 0;\n    }\n  }\n  if (c0 * c1 != a[0][1] + a[1][0]) {\n    imp();\n  }\n  string s(c0 + c1, '0');\n  for (int i = 0; i < s.size(); ++i) {\n    if (c0 == 0 || a[0][1] < c1) {\n      s[i] = '1';\n      a[1][0] -= c0;\n      --c1;\n    } else {\n      a[0][1] -= c1;\n      --c0;\n    }\n  }\n  cout << s << endl;\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "708",
    "index": "C",
    "title": "Centroids",
    "statement": "Tree is a connected acyclic graph. Suppose you are given a tree consisting of $n$ vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed $\\frac{n t}{2}$.\n\nYou are given a tree of size $n$ and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.",
    "tutorial": "The first observation is that to make vertex $x$ a centroid we need to choose some subtree not containing $x$ with size not exceeding $\\frac{n t}{2}$ (assume its root is $w$), remove an edge $uw$ between its subtree and the remaining tree, and add an edge between $x$ and $w$, in such a way that subtrees of all children of $x$ have size not exceeding $\\frac{n t}{2}$. Consider $v$ - the centroid of the tree, let's make it a root. Assume $u_{1}, u_{2}, ..., u_{k}$ are the neighbours of $v$, and $T_{1}, ..., T_{k}$ are the subtrees of these vertices. Then it is easy to prove, that if some vertex $x\\in T,$ can be made a centroid after replacing one edge of the tree, then it can be done using one of the following options: Remove some edge $vu_{j}$ for $j  \\neq  i$ and add an edge $xu_{j}$. Remove the edge $u_{iv}$ and add edge $xv$. It is possible, if the size of $T_{i}$ is exactly $n-{\\frac{n}{2}}$. So we need to calculate the sizes of all subtrees (array $cnt$) and then run dfs from $u_{1}, ..., u_{k}$. Vertex $x\\in T,$ can be made a centroid if ether $|T_{i}|=n-{\\frac{n}{2}}$, or $c n t[x]+\\operatorname*{max}_{j\\neq i}|T_{j}|\\geq n-{\\frac{n}{2}}$ (since we add edge $xu_{j}$ to maximize $|T_{j}|$, if the last condition holds, then the number of vertices in the connected component of $x$, if $x$ is deleted from the tree, will not exceed $\\frac{n t}{2}$ - so all the condition for $x$ being centroid will hold). To check the second condition, we need to find two maximums in the set $|T_{1}|, |T_{2}|, ..., |T_{k}|$. The described solution has complexity $O(n)$.",
    "code": "int n;\nvector<vector<int>> g;\nvector<int> cnt;\n\nint min_mx = 1e9;\nint center = -1;\n\nvoid dfs(int v, int p) {\n\tcnt[v] = 1;\n\tint mx = 0;\n\tfor (int to : g[v]) {\n\t\tif (to == p) {\n\t\t\tcontinue;\n\t\t}\n\t\tdfs(to, v);\n\t\tcnt[v] += cnt[to];\n\t\tmx = max(mx, cnt[to]);\n\t}\n\tmx = max(mx, n - cnt[v]);\n\tif (mx < min_mx) {\n\t\tmin_mx = mx;\n\t\tcenter = v;\n\t}\n}\n\nvector<pair<int, int>> subtrees;\nvector<int> ans;\n\nvoid dfs1(int v, int p, int sum_other, int prev) {\n\tif (sum_other <= n / 2) {\n\t\tans[v] = 1;\n\t}\n\tfor (int i = 0; i < 2 && i < subtrees.size(); ++i) {\n\t\tif (subtrees[i].second == prev) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (n - cnt[v] - subtrees[i].first <= n / 2) {\n\t\t\tans[v] = 1;\n\t\t}\n\t}\n\tfor (int to : g[v]) {\n\t\tif (to == p) {\n\t\t\tcontinue;\n\t\t}\n\t\tdfs1(to, v, sum_other, prev);\n\t}\n}\n\nvoid solve() {\n\tcin >> n;\n\tg.resize(n);\n\tcnt.assign(n, 0);\n\tfor (int i = 1; i < n; ++i) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\t--a; --b;\n\t\tg[a].push_back(b);\n\t\tg[b].push_back(a);\n\t}\n\tdfs(0, 0);\n\n\tassert(center != -1);\n\tans.assign(n, 0);\n\tans[center] = 1;\n\tdfs(center, center);\n\tint sum_all = 0;\n\tfor (int to : g[center]) {\n\t\tsubtrees.emplace_back(cnt[to], to);\n\t\tsum_all += cnt[to];\n\t}\n\tsort(all(subtrees));\n\treverse(all(subtrees));\n\n\tfor (int to : g[center]) {\n\t\tdfs1(to, center, n - cnt[to], to);\n\t}\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tcout << ans[i] << ' ';\n\t}\n\tcout << \"\\n\";\n\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "708",
    "index": "D",
    "title": "Incorrect Flow",
    "statement": "At the entrance examination for the magistracy of the MSU Cyber-Mechanics Department Sasha got the question about Ford-Fulkerson algorithm. He knew the topic perfectly as he worked with it many times on programming competition. As the task for the question he was given a network with partially build flow that he had to use in order to demonstrate the workflow of the algorithm. He quickly finished to write the text and took a look at the problem only to understand that the given network is incorrect!\n\nSuppose you are given a directed graph $G(V, E)$ with two special nodes $s$ and $t$ called source and sink. We denote as $n$ the number of nodes in the graph, i.e. $n = |V|$ and $m$ stands for the number of directed edges in the graph, i.e. $m = |E|$. For the purpose of this problem we always consider node $1$ to be the source and node $n$ to be the sink. In addition, for each edge of the graph $e$ we define the capacity function $c(e)$ and flow function $f(e)$. Function $f(e)$ represents the correct flow if the following conditions are satisfied:\n\n- For each edge $e\\in E$ the flow is non-negative and does not exceed capacity $c(e)$, i.e. $0 ≤ f(e) ≤ c(e)$.\n- For each node $v\\in V$, that is not source or sink ($v ≠ s$ and $v ≠ t$) the sum of flows of all edges going in $v$ is equal to the sum of the flows among all edges going out from $v$. In other words, there is no flow stuck in $v$.\n\nIt was clear that as the exam was prepared last night and there are plenty of mistakes in the tasks. Sasha asked one of the professors to fix the network or give the correct task, but the reply was that the magistrate student should be able to fix the network himself. As the professor doesn't want the task to become easier, he asks Sasha to fix the network in a such way that the total number of changes is minimum possible. Sasha is not allowed to remove edges, add new ones or reverse the direction of existing edges. The only thing he is able to do is to change capacity function $c(e)$ and flow function $f(e)$. Moreover, all the values should remain non-negative integers. There is no requirement on the flow to be maximum in any sense.\n\nFind the minimum possible total change of the functions $f(e)$ and $c(e)$ that Sasha has to make in order to make the flow correct. The total change is defined as the sum of absolute differences, i.e. if new functions are $f^{ * }(e)$ and $c^{ * }(e)$, then the total change is $\\textstyle\\sum_{e\\in E}|f(e)-f^{*}(e)|+|c(e)-c^{*}(e)|$.",
    "tutorial": "This problem could be solved by max-flow-min-cost algorithm. At first we will fix edges with flow exceeding capacity. We will just increase capacity to the flow value and add sum of all these changes to the answer. Now we need to get rid of excess incoming flow in some vertices and excess outcoming flow in some other vertices. Consider new flow-cost network, source and sink will be new vertices. We add edge from new source into every vertex with excess of incoming flow with zero cost and capacity equals to the excess flow. We add edge into new sink every vertex with excess of outcoming flow with zero cost and capacity equals to the excess flow. We add edge from old sink to the old source with zero cost and infinite capacity. Instead of every edge of the initial graph (denote its capacity as $c$, flow as $f$) we will create three edges: the first one could decrease flow in the initial graph without change of capacity (its cost equals 1, capacity equals $f$, it has opposite direction), the second one could increase flow without change of capacity (its cost equals 1, capacity equals $c - f$, it has same direction), the third one could increase flow and capacity as much as you need (its cost equals 1, capacity equals infinity, it has same direction). One more trick is that cost of part of the second type edge should be zero instead of one if it had $f > c$, because in this case we make changes which have already pay.",
    "code": "class FixFlow {\npublic:\n\tvoid solve(std::istream& in, std::ostream& out) {\n\t\tint n, m;\n\t\tin >> n >> m;\n\t\tint s = n;\n\t\tint t = n + 1;\n\t\tMinCostFlow<int, int> flow(n + 2);\n\t\tvector<int> balance(n);\n\t\tint INF = 1000000000;\n\t\tflow.addEdge((size_t) (n - 1), 0, INF, 0);\n\n\n\t\tint defaultAnswer = 0;\n\t\tfor (int i: range(m)) {\n\t\t\tint a, b, c, f;\n\t\t\tin >> a >> b >> c >> f;\n\t\t\t--a, --b;\n\t\t\tbalance[a] += f;\n\t\t\tbalance[b] -= f;\n\t\t\tif (f <= c) {\n\t\t\t\tflow.addEdge(a, b, c - f, 1);\n\t\t\t\tflow.addEdge(a, b, INF, 2);\n\t\t\t\tflow.addEdge(b, a, f, 1);\n\t\t\t} else {\n\t\t\t\t// f > c\n\t\t\t\tdefaultAnswer += f - c;\n\t\t\t\tflow.addEdge(a, b, INF, 2);\n\t\t\t\tflow.addEdge(b, a, f - c, 0);\n\t\t\t\tflow.addEdge(b, a, c, 1);\n\t\t\t}\n\t\t}\n\n\t\tint sumB = 0;\n\t\tfor (int i: range(n)) {\n\t\t\tif (balance[i] > 0) {\n\t\t\t\tflow.addEdge(i, t, balance[i], 0);\n\t\t\t\tsumB += balance[i];\n\t\t\t} else {\n\t\t\t\tflow.addEdge(s, i, -balance[i], 0);\n\t\t\t}\n\t\t}\n\n\t\tauto res = flow.findFlow(s, t, MinCostMaxFlowStrategy());\n\t\tassert(res.flow == sumB);\n\t\tout << res.cost + defaultAnswer << \"\\n\";\n\t}\n};",
    "tags": [
      "flows"
    ],
    "rating": 2900
  },
  {
    "contest_id": "708",
    "index": "E",
    "title": "Student's Camp",
    "statement": "Alex studied well and won the trip to student camp Alushta, located on the seashore.\n\nUnfortunately, it's the period of the strong winds now and there is a chance the camp will be destroyed! Camp building can be represented as the rectangle of $n + 2$ concrete blocks height and $m$ blocks width.\n\nEvery day there is a breeze blowing from the sea. Each block, except for the blocks of the upper and lower levers, such that there is no block to the left of it is destroyed with the probability $p={\\frac{a}{b}}$. Similarly, each night the breeze blows in the direction to the sea. Thus, each block (again, except for the blocks of the upper and lower levers) such that there is no block to the right of it is destroyed with the same probability $p$. Note, that blocks of the upper and lower level are \\textbf{indestructible}, so there are only $n·m$ blocks that can be destroyed.\n\nThe period of the strong winds will last for $k$ days and $k$ nights. If during this period the building will split in at least two connected components, it will collapse and Alex will have to find another place to spend summer.\n\nFind the probability that Alex won't have to look for other opportunities and will be able to spend the summer in this camp.",
    "tutorial": "Let $dp[t][l][r]$ is probability that first $t$ rows are connected and $t$-th row is $[l;r)$ (it's always a segment). We can write a simple equation: $d p[t][l][r]=p_{l,r}\\sum_{l p,r p}d p[t-1][l p][r p]$ $p_{l}={\\binom{k}{l}}p^{l}(1-p)^{k-l}.$ $d p_{r}[t][r]=\\sum_{l<r}d p[t][l][r]$ $s u m_{-}d p_{r}[t][r]=\\sum_{a\\leq r}d p_{r}[t][a]$ $sum_dp_{l}[t][l] = sum_dp_{r}[t][n - r].$ Now $dp[t][l][r] = p_{l, r}(sum_dp_{r}[t - 1][n] - sum_dp_{r}[t - 1][l] - sum_dp_{l}[t - 1][r]).$ Here we subtract from probability of all segments the segments on the left and on the right. Now we won't calculate $dp[t][l][r]$ but $dp_{r}[t][r]$. $\\begin{array}{c}{{d p_{r}[t][r]=\\sum_{l<r}p_{l,r}(s u m_{-}d p_{r}[t-1][n]-s u m_{-}d p_{r}[t-1][l]-s u m_{-}d p_{l}[t-1].}}\\end{array}$ It's $O(n)$ to calculate each separate value, but it's also possible to calculate them all in $O(n)$ if we iterate over $r$ from $0$ to $m$ and hold several values during this process. Particularly, we need precalculated sums of $p_{l, r}$ with fixed $r$ and to hold the sum of $p_{l} \\cdot sum_dp_{r}[t - 1][l]$ for $l < r$ (recall that $p_{l, r} = p_{l} \\cdot p_{n - r}$. See code for details. $sum_dp_{r}[t][r]$ is just prefix sums of what we calculated. So we obtain the solution with $O(nm)$ complexity.",
    "code": "class MAI {\npublic:\n\tvoid solve(std::istream& in, std::ostream& out) {\n\t\tint N, m;\n\t\tint a, b;\n\t\tint k;\n\t\tin >> N >> m >> a >> b >> k;\n\t\tusing Z = ZnConst<1000000007>;\n\t\tZ p = Z::valueOf(a) / b;\n\t\tZ q = 1 - p;\n\n\t\t// dp[r'] = sum l < r <= r' d[l][r]\n\t\tvector<Z> dp(m + 1, Z());\n\t\tdp[m] = 1;\n\n\t\tvector<Z> powersP(k + 1), powersQ(k + 1);\n\t\tpowersP[0] = powersQ[0] = 1;\n\t\tfor (int i: range(k)) {\n\t\t\tpowersP[i + 1] = powersP[i] * p;\n\t\t\tpowersQ[i + 1] = powersQ[i] * q;\n\t\t}\n\n\t\tvector<Z> fact = factorials<Z>(k + 1);\n\t\tvector<Z> invfact = fact;\n\t\tfor (auto& x: invfact) {\n\t\t\tx = 1 / x;\n\t\t}\n\n\t\tauto get_p_one_side = [&](int l) {\n\t\t\tif (l > k) {\n\t\t\t\treturn Z();\n\t\t\t}\n\t\t\treturn powersP[l] * powersQ[k - l] * fact[k] * invfact[l] * invfact[k - l];\n\t\t};\n\n\t\tfor (int iter: range(N)) {\n\t\t\tvector<Z> dp_one(m + 1, Z());\n\t\t\tZ sumPl, sumPlDpl;\n\n\t\t\tfor (int r: inclusiveRange(m)) {\n\t\t\t\t//new_d[l][r] = p[l] * p[n - r] * (have_something - dp[l] - dp[n - r])\n\t\t\t\tZ have_something = dp.back();\n\t\t\t\tdp_one[r] = get_p_one_side(m - r) * (\n\t\t\t\t\t\thave_something * sumPl - sumPlDpl - sumPl * dp[m - r]\n\t\t\t\t);\n\t\t\t\tsumPl += get_p_one_side(r);\n\t\t\t\tsumPlDpl += get_p_one_side(r) * dp[r];\n\t\t\t}\n\n\t\t\tfor (int i: range(m)) {\n\t\t\t\tdp_one[i + 1] += dp_one[i];\n\t\t\t}\n\n\t\t\tdp = move(dp_one);\n\t\t}\n\n\t\tout << dp.back();\n\t}\n};",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "709",
    "index": "A",
    "title": "Juicer",
    "statement": "Kolya is going to make fresh orange juice. He has $n$ oranges of sizes $a_{1}, a_{2}, ..., a_{n}$. Kolya will put them in the juicer in the fixed order, starting with orange of size $a_{1}$, then orange of size $a_{2}$ and so on. To be put in the juicer the orange must have size not exceeding $b$, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.\n\nThe juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than $d$. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?",
    "tutorial": "In this problem you have to carefully implement exactly what it written in the statement. Pay attention to some details: Don't forget to throw away too large oranges. Don't mix up strict and not-strict inequalities.",
    "code": "int main() {\n  int n, b, d;\n  std::cin >> n >> b >> d;\n\n  int current_size = 0;\n  int result = 0;\n  int x;\n  for (; n > 0; --n) {\n    std::cin >> x;\n    if (x > b) {\n      continue;\n    }\n    current_size += x;\n    if (current_size > d) {\n      ++result;\n      current_size = 0;\n    }\n  }\n\n  std::cout << result << \"\\n\";\n  return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "709",
    "index": "B",
    "title": "Checkpoints",
    "statement": "Vasya takes part in the orienteering competition. There are $n$ checkpoints located along the line at coordinates $x_{1}, x_{2}, ..., x_{n}$. Vasya starts at the point with coordinate $a$. His goal is to visit at least $n - 1$ checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.\n\nVasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.",
    "tutorial": "Sort all point by $x$-coordinate. If we've chosen the set of points we want to visit, then we must go either to the leftmost of them and then to the rightmost, or to the rightmost and then to the leftmost, the others will be visited automatically during this process. The other observation is that it makes sense to not visit only either the leftmost or the rightmost point - otherwise this point will be visited during any walk which visits $n - 1$ points. So, the solution is to fix the points which we don't want to visit - either the leftmost or the rightmost, after that iterate over two possible orders of visits of the lefmost and rightmost points of the remaining set of $n - 1$ points and relax the answer. Also don't forget the case $n = 1$ - then you don't need to visit any point.",
    "code": "const int MAXN = 100000;\n\nint x[MAXN];\n\nint main() {\n  int n, A;\n  scanf(\"%d %d\", &n, &A);\n  if (n == 1) {\n    printf(\"0\\n\");\n    return 0;\n  }\n  for (int i = 0; i < n; i++) {\n    scanf(\"%d\", &x[i]);\n  }\n  int first_max = -2e6;\n  int second_max = -2e6;\n  int first_min = 2e6;\n  int second_min = 2e6;\n\n  for (int i = 0; i < n; i++) {\n    if (x[i] > second_max) {\n      second_max = x[i];\n      if (second_max > first_max) {\n        swap(second_max, first_max);\n      }\n    }\n    if (x[i] < second_min) {\n      second_min = x[i];\n      if (second_min < first_min) {\n        swap(second_min, first_min);\n      }\n    }\n  }\n  printf(\"%d\\n\", min(first_max - second_min + min(abs(A - first_max), abs(A - second_min)),\n                     second_max - first_min + min(abs(A - second_max), abs(A - first_min))));\n\n  return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "710",
    "index": "A",
    "title": "King Moves",
    "statement": "The only king stands on the standard chess board. You are given his position in format \"cd\", where $c$ is the column from 'a' to 'h' and $d$ is the row from '1' to '8'. Find the number of moves permitted for the king.\n\nCheck the king's moves here https://en.wikipedia.org/wiki/King_(chess).\n\n\\begin{center}\n{\\small King moves from the position e4}\n\\end{center}",
    "tutorial": "Easy to see that there are only three cases in this problem. If the king is in the corner of the board the answer is $3$. If the king is on the border of the board but not in a corner then the answer is $5$. Otherwise the answer is $8$. Complexity: $O(1)$.",
    "code": "char c, d;\n\nbool read() {\n\treturn !!(cin >> c >> d);\n}\n\nvoid solve() {\n\tint cnt = 0;\n\tif (c == 'a' || c == 'h') cnt++;\n\tif (d == '1' || d == '8') cnt++;\n\tif (cnt == 0) puts(\"8\");\n\telse if (cnt == 1) puts(\"5\");\n\telse if (cnt == 2) puts(\"3\");\n\telse throw;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "710",
    "index": "B",
    "title": "Optimal Point on a Line",
    "statement": "You are given $n$ points on a line with their coordinates $x_{i}$. Find the point $x$ so the sum of distances to the given points is minimal.",
    "tutorial": "The function of the total distance is monotonic between any pair of adjacent points from the input, so the answer is always in some of the given points. We can use that observation to solve the problem by calculating the total distance for each point from the input and finding the optimal point. The other solution uses the observation that the answer is always is the middle point (by index) in the sorted list of the given points. The last fact is also can be easily proven. Complexity: $O(nlogn)$.",
    "code": "const int N = 300300;\n\nint n, a[N];\n\nbool read() {\n\tif (!(cin >> n)) return false;\n\tforn(i, n) assert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nvoid solve() {\n\tsort(a, a + n);\n\n\tli suml = 0, sumr = accumulate(a, a + n, 0ll);\n\tli ansv = LLONG_MAX, ansp = LLONG_MIN;\n\tforn(i, n) {\n\t\tli curv = li(i) * a[i] - suml;\n\t\tcurv += sumr - li(n - i) * a[i];\n\t\tif (ansv > curv) {\n\t\t\tansv = curv;\n\t\t\tansp = a[i];\n\t\t}\n\t\tsuml += a[i];\n\t\tsumr -= a[i];\n\t}\n\tassert(sumr == 0);\n\n\tassert(ansv != LLONG_MAX);\n\tcerr << \"ansv: \" << ansv << endl;\n\tcout << ansp << endl;\n}",
    "tags": [
      "brute force",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "710",
    "index": "C",
    "title": "Magic Odd Square",
    "statement": "Find an $n × n$ matrix with different numbers from $1$ to $n^{2}$, so the sum in each row, column and both main diagonals are odd.",
    "tutorial": "The solution can be got from the second sample testcase. Easy to see that if we place all odd numbers in the center in form of rhombus we will get a magic square. Complexity: $O(n^{2})$.",
    "code": "int n;\n\nbool read() {\n\treturn !!(cin >> n);\n}\n\nconst int N = 101;\n\nint a[N][N];\n\nvoid solve() {\n\tmemset(a, 0, sizeof(a));\n\n\tforn(i, n / 2) {\n\t\tint len = n / 2 - i;\n\t\tforn(j, len) {\n\t\t\tint x1 = i, x2 = n - 1 - i;\n\t\t\tint y1 = j, y2 = n - 1 - j;\n\t\t\ta[x1][y1] = 1;\n\t\t\ta[x1][y2] = 1;\n\t\t\ta[x2][y1] = 1;\n\t\t\ta[x2][y2] = 1;\n\t\t}\n\t}\n\n\tint odd = 1, even = 2;\n\tforn(i, n)\n\t\tforn(j, n)\n\t\t\tif (a[i][j]) a[i][j] = even, even += 2;\n\t\t\telse a[i][j] = odd, odd += 2;\n\n\tforn(i, n) {\n\t\tforn(j, n) {\n\t\t\tif (j) putchar(' ');\n\t\t\tprintf(\"%d\", a[i][j]);\n\t\t}\n\t\tputs(\"\");\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "710",
    "index": "D",
    "title": "Two Arithmetic Progressions",
    "statement": "You are given two arithmetic progressions: $a_{1}k + b_{1}$ and $a_{2}l + b_{2}$. Find the number of integers $x$ such that $L ≤ x ≤ R$ and $x = a_{1}k' + b_{1} = a_{2}l' + b_{2}$, for some integers $k', l' ≥ 0$.",
    "tutorial": "Let's write down the equation describing the problem: $a_{1}k + b_{1} = a_{2}l + b_{2}  \\rightarrow  a_{1}k - a_{2}l = b_{2} - b_{1}$. So we have linear Diofant equation with two variables: $Ax + By = C, A = a_{1}, B = - a_{2}, C = b_{2} - b_{1}$. The solution has the form: $A{\\frac{C x_{0}+B p}{g}}+B{\\frac{C y_{0}-A p}{g}}=C,g=g c d(A,B),A x_{0}+B y_{0}=C$, where the last equation can be solved by extended Euclid algorithm and $p$ is any integral number. The variable $p$ should satisfy two conditions: $m a x(0,L)\\leq{\\frac{c x_{0}+B p}{g}}\\leq R$ and $m a x(0,L)\\leq{\\frac{c y_{00}-A_{P}}{g}}\\leq R$. The values $A$ and $B$ are fixed, so we can get the segment of possible values for the values $p$. The length of the segment is the answer for the problem. Complexity: $O(log(max(a_{1}, a_{2})))$.",
    "code": "li a1, b1, a2, b2, l, r;\n\nbool read() {\n\treturn !!(cin >> a1 >> b1 >> a2 >> b2 >> l >> r);\n}\n\nli _ceil(li, li);\nli _floor(li a, li b) { return b < 0 ? _floor(-a, -b) : a < 0 ? -_ceil(-a, b) : a / b; }\nli _ceil(li a, li b) { return b < 0 ? _ceil(-a, -b) : a < 0 ? -_floor(-a, b) : (a + b - 1) / b; }\n\nli gcd(li a, li b, li& x, li& y) {\n\tif (!a) {\n\t\tx = 0, y = 1;\n\t\treturn b;\n\t}\n\tli xx, yy, g = gcd(b % a, a, xx, yy);\n\tx = yy - b / a * xx;\n\ty = xx;\n\treturn g;\n}\n\nvoid solve() {\n\tl = max(0ll, _ceil(l - b1, a1));\n\tr = _floor(r - b1, a1);\n\tif (l > r) {\n\t\tputs(\"0\");\n\t\treturn;\n\t}\n\n\tli A = a1, B = -a2, C = b2 - b1;\n\tli x0, y0;\n\tli g = gcd(A, B, x0, y0);\n\tif (C % g) {\n\t\tputs(\"0\");\n\t\treturn;\n\t}\n\n\tif (g < 0) {\n\t\tg = -g;\n\t\tx0 = -x0;\n\t\ty0 = -y0;\n\t}\n\n\tli L = _ceil(r * g - x0 * C, B);\n\tli R = _floor(l * g - x0 * C, B);\n\tR = min(R, _floor(y0 * C, A));\n\n\tli ans = max(0ll, R - L + 1);\n\tcout << ans << endl;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "710",
    "index": "E",
    "title": "Generate a String",
    "statement": "zscoder wants to generate an input file for some programming competition problem.\n\nHis input is a string consisting of $n$ letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.\n\nInitially, the text editor is empty. It takes him $x$ seconds to insert or delete a letter 'a' from the text file and $y$ seconds to copy the contents of the entire text file, and duplicate it.\n\nzscoder wants to find the minimum amount of time needed for him to create the input file of exactly $n$ letters 'a'. Help him to determine the amount of time needed to generate the input.",
    "tutorial": "This problem has a simple solution described by participants in the comments. My solution is a little harder. Let's solve it using dynamic programming. Let $z_{n}$ be the smallest amount of time needed to get $n$ letters 'a'. Let's consider transitions: the transition for adding one letter 'a' can be simply done. Let's process transitions for multiplying by two and subtraction by one simultaneously: let's decrease the number $2 \\cdot i$ $i$ times by one right after getting it. Easy to see that such updates never include each other, so we can store them in queue by adding the new update at the tail of the queue and taking the best update from the head. The solution is hard to describe, but it is very simple in the code, so please check it to understand the idea :-) Complexity: $O(n)$.",
    "code": "int n;\nli x, y;\n\nbool read() {\n\treturn !!(cin >> n >> x >> y);\n}\n\nconst int N = 20 * 1000 * 1000 + 13;\n\nli z[N];\n\nvoid solve() {\n\tforn(i, N) z[i] = LLONG_MAX;\n\n\tlist<pair<li, int>> q;\n\n\tz[0] = 0;\n\tforn(i, n + 1) {\n\t\twhile (!q.empty() && q.front().y < i) q.pop_front();\n\n\t\tif (!q.empty()) z[i] = min(z[i], q.front().x - i * x);\n\t\tassert(z[i] != LLONG_MAX);\n\n\t\tpair<li, int> cur(z[i] + y + 2 * i * x, 2 * i);\n\t\twhile (!q.empty() && q.back().x > cur.x) q.pop_back();\n\t\tq.pb(cur);\n\n\t\tz[i + 1] = min(z[i + 1], z[i] + x);\n\t}\n\n\tcout << z[n] << endl;\n}",
    "tags": [
      "dfs and similar",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "710",
    "index": "F",
    "title": "String Set Queries",
    "statement": "You should process $m$ queries over a set $D$ of strings. Each query is one of three kinds:\n\n- Add a string $s$ to the set $D$. It is guaranteed that the string $s$ was not added before.\n- Delete a string $s$ from the set $D$. It is guaranteed that the string $s$ is in the set $D$.\n- For the given string $s$ find the number of occurrences of the strings from the set $D$. If some string $p$ from $D$ has several occurrences in $s$ you should count all of them.\n\nNote that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query of the third type. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.",
    "tutorial": "Let's get rid of the queries for deleting a string. There are no strings that will be added two times, so we can calculate the answer for the added (but not deleted strings) and for the deleted separately and subtract the second from the first to get the answer. So we can consider that there are no queries of deletion. Now let's use Aho-Corasik algorithm. The only difficulty is that the strings are adding in online mode, but Aho-Corasik algorithm works only after adding all the strings. Note that the answer for the given set of strings equal to the answer for any part of the set plus the answer for the remaining part. Let's use the trick with converting the static data structure (Aho-Corasik in this case) to the dynamic one. For the set of $n$ strings let's maintain a set of no more than $logn$ sets of the strings with sizes of different powers of two. After adding new string we should move the sets from the lowest powers of two to the largest until we got an invariant set of sets. Easy to see that each string will be moved no more than $logm$ times, so we can process each query in $O(logn)$ time. Complexity: $O((slen + m)logm)$, where $slen$ is the total length of the string from the input.",
    "code": "const int N = 4 * 300300, A = 26, LOGN = 20;\n\nstruct node {\n    char c;\n    int parent, link, output;\n    int next[A], automata[A];\n\t\tint cnt;\n    \n    node(char c = -1, int parent = -1, int link = -1, int output = -1, int cnt = -1):\n        c(c), parent(parent), link(link), output(output), cnt(cnt) {\n        memset(next, -1, sizeof(next));\n        memset(automata, -1, sizeof(automata));\n    }\n};\nnode t[N];\n\nvector<int> ids;\ninline int get_idx() {\n\tassert(!ids.empty());\n\tint ans = ids.back();\n\tids.pop_back();\n\tt[ans] = node();\n\treturn ans;\n}\ninline void return_idx(int idx) {\n\tids.pb(idx);\n}\n\ninline int add(const string& s, int root) {\n    int v = root;\n    forn(i, sz(s)) {\n        if (t[v].next[s[i] - 'a'] == -1) {\n\t\t\t\t\tint idx = get_idx();\n\t\t\t\t\tt[v].next[s[i] - 'a'] = idx;\n\t\t\t\t\tt[idx] = node(s[i], v, -1, -1);\n        }\n        v = t[v].next[s[i] - 'a'];\n    }\n    t[v].output = v;\n    return v;\n}\nint link(int v, int root) {\n    int& ans = t[v].link;\n    if (ans != -1) return ans;\n\t\tif (v == root || t[v].parent == root) return ans = root;\n    char c = t[v].c;\n    int vv = link(t[v].parent, root);\n    while (vv != root && t[vv].next[c - 'a'] == -1)\n        vv = link(vv, root);\n    return ans = (t[vv].next[c - 'a'] == -1? root: t[vv].next[c - 'a']);\n}\nint output(int v, int root) {\n    int& ans = t[v].output;\n    if (ans != -1) return ans;\n    return ans = (v == root? root: output(link(v, root), root));\n}\nint cnt(int v, int root) {\n\tint& ans = t[v].cnt;\n\tif (ans != -1) return ans;\n\tv = output(v, root);\n\tif (v == root) return ans = 0;\n\treturn ans = 1 + cnt(link(v, root), root);\n}\nint next(int v, char c, int root) {\n    int& ans = t[v].automata[c - 'a'];\n    if (ans != -1) return ans;\n    if (t[v].next[c - 'a'] != -1)\n        return ans = t[v].next[c - 'a'];\n    return ans = (v == root? root: next(link(v, root), c, root));\n}\n\nvoid dfs_clear(int v) {\n\tforn(i, A) if (t[v].next[i] != -1) dfs_clear(t[v].next[i]);\n\treturn_idx(v);\n}\n\nstring a[N];\n\nint build(int root, const vector<int>& ids) {\n\tdfs_clear(root);\n\troot = get_idx();\n\tforn(i, sz(ids)) add(a[ids[i]], root);\n\treturn root;\n}\n\nint calc(int root, int idx) {\n\tint ans = 0;\n\tconst string& s = a[idx];\n\tint v = root;\n\tforn(i, sz(s)) {\n\t\tv = next(v, s[i], root);\n\t\tans += cnt(v, root);\n\t}\n\treturn ans;\n}\n\nint m;\n\nbool read() {\n\treturn !!(cin >> m);\n}\n\nstruct blocks {\n\tint root[LOGN];\n\tvector<int> block[LOGN];\n\n\tvoid clear() {\n\t\tforn(i, LOGN) {\n\t\t\tblock[i].clear();\n\t\t\troot[i] = get_idx();\n\t\t}\n\t}\n\n\tvoid insert(int i) {\n\t\tvector<int> cur(1, i);\n\t\tforn(i, LOGN)\n\t\t\tif (sz(block[i]) == sz(cur)) {\n\t\t\t\tcur.insert(cur.end(), all(block[i]));\n\t\t\t\tblock[i].clear();\n\t\t\t\troot[i] = build(root[i], block[i]);\n\t\t\t} else {\n\t\t\t\tblock[i] = cur;\n\t\t\t\troot[i] = build(root[i], block[i]);\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n\n\tli calc2(int idx) {\n\t\tli ans = 0;\n\t\tforn(i, LOGN) {\n\t\t\tans += calc(root[i], idx);\n\t\t}\n\t\treturn ans;\n\t}\n};\n\nchar buf[N];\nblocks z1, z2;\n\nvoid solve() {\n\tids.clear();\n\tnfor(i, N) ids.pb(i);\n\n\tz1.clear();\n\tz2.clear();\n\n\tforn(i, m) {\n\t\tint type;\n\t\tassert(scanf(\"%d%s\", &type, buf) == 2);\n\t\ta[i] = buf;\n\n\t\tif (type == 1) {\n\t\t\tz1.insert(i);\n\t\t} else if (type == 2) {\n\t\t\tz2.insert(i);\n\t\t} else if (type == 3) {\n\t\t\tli ans = z1.calc2(i) - z2.calc2(i);\n\t\t\tprintf(\"%lld\\n\", ans);\n\t\t\tfflush(stdout);\n\t\t} else throw;\n\t}\n}",
    "tags": [
      "brute force",
      "data structures",
      "hashing",
      "interactive",
      "string suffix structures",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "711",
    "index": "A",
    "title": "Bus to Udayland",
    "statement": "ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has $n$ rows of seats. There are $4$ seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.\n\nZS and Chris are good friends. They insist to get \\textbf{a pair of neighbouring empty seats}. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?",
    "tutorial": "For each row, check whether there exists two consecutive Os. Once you find a pair of consecutive Os, you can replace them with +s and output the bus. If no such pair exists, output NO. Time Complexity : $O(n)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int INF = 1e9 + 7;\nconst int MOD = 1e9 + 7;\nconst int N = 1000;\nchar bus[N][5];\n\nvoid printbus(int n)\n{\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j < 5; j++)\n\t\t{\n\t\t\tcout << bus[i][j];\n\t\t}\n\t\tcout << '\\n';\n\t}\n}\n\nvoid yes()\n{\n\tcout << \"YES\" << '\\n';\n}\n\nvoid no()\n{\n\tcout << \"NO\" << '\\n';\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tint n; cin >> n;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j < 5; j++)\n\t\t{\n\t\t\tcin >> bus[i][j];\n\t\t}\n\t}\n\tbool possible = false;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j < 2; j++)\n\t\t{\n\t\t\tif(bus[i][j*3] == 'O' && bus[i][j*3+1] == 'O')\n\t\t\t{\n\t\t\t\tbus[i][j*3] = '+';\n\t\t\t\tbus[i][j*3+1] = '+';\n\t\t\t\tpossible = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(possible) break;\n\t}\n\tif(!possible)\n\t{\n\t\tno();\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tyes();\n\t\tprintbus(n);\n\t\treturn 0;\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "711",
    "index": "B",
    "title": "Chris and Magic Square",
    "statement": "ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a $n × n$ magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a \\textbf{positive integer} into the empty cell.\n\nChris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid ($\\textstyle\\sum a_{r,i}$), each column of the grid ($\\textstyle\\sum a_{i,c}$), and the two long diagonals of the grid (the main diagonal — $\\textstyle\\sum a_{i,i}$ and the secondary diagonal — $\\textstyle\\sum a_{i,n-i+1}$) are equal.\n\nChris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?",
    "tutorial": "Firstly, when $n = 1$, output any positive integer in the range will work. Otherwise, we calculate the sum of the values in each row, column and the two long diagonals, and also keep track which row and column the empty square is in and also which diagonals it lies on. Finally, we can use the sums to determine the value of the empty square or that it is impossible to make the square magic. Keep in mind that the blank must be filled with a positive integer, so $0$ doesn't work. Also, remember to use 64-bit integers to store the sums or it will overflow. (and will fail on the overflow test) Time Complexity : $O(n^{2})$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int INF = 1e9 + 7;\nconst int MOD = 1e9 + 7;\nconst int LG = 20;\n\nll a[1001][1001];\nll r[1001]; //row sum\nll c[1001]; //column sum\nint n;\n\nvoid no()\n{\n\tcout << -1 << '\\n';\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tcin >> n;\n\tint x, y; ll diagonal1 = 0; ll diagonal2 = 0;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j < n; j++)\n\t\t{\n\t\t\tcin >> a[i][j];\n\t\t\tif(a[i][j] == 0)\n\t\t\t{\n\t\t\t\tx = i; y = j;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tr[i] += a[i][j];\n\t\t\t\tc[j] += a[i][j];\n\t\t\t\tif(i == j)\n\t\t\t\t{\n\t\t\t\t\tdiagonal1 += a[i][j];\n\t\t\t\t}\n\t\t\t\tif(i + j == n - 1)\n\t\t\t\t{\n\t\t\t\t\tdiagonal2 += a[i][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif(n == 1)\n\t{\n\t\tcout << 1 << '\\n';\n\t\treturn 0;\n\t}\n\tll commonsum = r[0];\n\tif(x == 0) commonsum = r[1];\n\t//cout << commonsum << '\\n';\n\tll rowsum = -1; ll colsum = -1; ll d1sum = -1; ll d2sum = -1;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(i != x)\n\t\t{\n\t\t\tif(r[i] != commonsum)\n\t\t\t{\n\t\t\t\tno();\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\trowsum = r[i];\n\t\t}\n\t}\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(i != y)\n\t\t{\n\t\t\tif(c[i] != commonsum)\n\t\t\t{\n\t\t\t\tno(); return 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcolsum = c[i];\n\t\t}\n\t}\n\tbool isdiagonal1 = false; bool isdiagonal2 = false;\n\tif(x == y) isdiagonal1 = true;\n\tif(x + y == n - 1) isdiagonal2 = true;\n\tif(!isdiagonal1)\n\t{\n\t\tif(diagonal1 != commonsum)\n\t\t{\n\t\t\tno();\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\td1sum = diagonal1;\n\t}\n\tif(!isdiagonal2)\n\t{\n\t\tif(diagonal2 != commonsum)\n\t\t{\n\t\t\tno();\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\td2sum = diagonal2;\n\t}\n\tif(rowsum == colsum)\n\t{\n\t\tif(isdiagonal1 && d1sum != rowsum)\n\t\t{\n\t\t\tno();\n\t\t\treturn 0;\n\t\t}\n\t\tif(isdiagonal2 && d2sum != rowsum)\n\t\t{\n\t\t\tno();\n\t\t\treturn 0;\n\t\t}\n\t\tll value = commonsum - rowsum;\n\t\tif(value > 0)\n\t\t{\n\t\t\tcout << value << '\\n';\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tno();\n\t\t\treturn 0;\n\t\t}\n\t}\n\telse\n\t{\n\t\tno();\n\t\treturn 0;\n\t}\n}\n",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "711",
    "index": "C",
    "title": "Coloring Trees",
    "statement": "ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where $n$ trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from $1$ to $n$ from left to right.\n\nInitially, tree $i$ has color $c_{i}$. ZS the Coder and Chris the Baboon recognizes only $m$ different colors, so $0 ≤ c_{i} ≤ m$, where $c_{i} = 0$ means that tree $i$ is uncolored.\n\nZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with $c_{i} = 0$. They can color each of them them in any of the $m$ colors from $1$ to $m$. Coloring the $i$-th tree with color $j$ requires exactly $p_{i, j}$ litres of paint.\n\nThe two friends define the beauty of a coloring of the trees as the \\textbf{minimum} number of contiguous groups (each group contains some subsegment of trees) you can split all the $n$ trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are $2, 1, 1, 1, 3, 2, 2, 3, 1, 3$, the beauty of the coloring is $7$, since we can partition the trees into $7$ contiguous groups of the same color : ${2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}$.\n\nZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is \\textbf{exactly} $k$. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.\n\nPlease note that the friends can't color the trees that are already colored.",
    "tutorial": "We compute the following array : $dp[i][j][k]$ denoting the minimum amount of paint needed to color the first $i$ trees such that it has beauty $j$ and the $i$-th tree is colored by color $k$, and initialize all these values to $ \\infty $. We can compute this dp array easily by considering two cases : 1. When the last color used is equal to the current color, then we should compare it with $dp[i - 1][j][k] + cost[i][k]$ if it was originally uncolored or $dp[i - 1][j][k]$ otherwise, since the beauty of the coloring is the same. 2. When the last color used is different from the current color, then we should compare it with $dp[i - 1][j - 1][l] + cost[i][k]$ or $dp[i - 1][j - 1][l]$ for all $1  \\le  l  \\le  m$ except when $l$ is equal to the current color, by similar reasoning. If the current tree is uncolored, we loop through all the $m$ possible colors to color it. Naively implementing this dp will give an $O(nkm^{2})$, which is sufficient to pass for this problem. However, it is possible to optimize it into $O(nkm)$ by avoiding iterating through all colors when considering the last color used and store two global minimums. See the code for more the details. Time Complexity : $O(nkm^{2})$ or $O(nkm)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n \nusing namespace std;\nusing namespace __gnu_pbds;\n \n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n \ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int N = 101;\nconst int MOD = 1e9 + 7;\nconst ll INF = ll(1e18);\n\nll dp[N][N][N];\nint c[N];\nll cost[N][N];\nll idx[N][N];\nll m1[N][N];\nll m2[N][N];\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tint n, m, k; cin >> n >> m >> k;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tcin >> c[i];\n\t}\n\tfor(int i = 0; i <= n; i++)\n\t{\n\t\tfor(int j = 0; j <= k; j++)\n\t\t{\n\t\t\tm1[i][j] = INF; m2[i][j] = INF; idx[i][j] = -1;\n\t\t\tfor(int a = 0; a <= m; a++)\n\t\t\t{\n\t\t\t\tdp[i][j][a] = INF;\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tfor(int j = 1; j <= m; j++)\n\t\t{\n\t\t\tcin >> cost[i][j];\n\t\t}\n\t}\n\tif(c[1] == 0)\n\t{\n\t\tfor(int i = 1; i <= m; i++)\n\t\t{\n\t\t\tdp[1][1][i] = cost[1][i];\n\t\t\tif(dp[1][1][i] <= m1[1][1])\n\t\t\t{\n\t\t\t\tif(dp[1][1][i] == m1[1][1])\n\t\t\t\t{\n\t\t\t\t\tidx[1][1] = -2;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tidx[1][1] = i;\n\t\t\t\t}\n\t\t\t\tm2[1][1] = m1[1][1];\n\t\t\t\tm1[1][1] = dp[1][1][i];\n\t\t\t}\n\t\t\telse if(dp[1][1][i] <= m2[1][1])\n\t\t\t{\n\t\t\t\tm2[1][1] = dp[1][1][i];\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tdp[1][1][c[1]] = 0;\n\t\tm1[1][1] = 0; idx[1][1] = c[1];\n\t}\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tfor(int j = 1; j <= k; j++)\n\t\t{\n\t\t\tif(c[i] == 0)\n\t\t\t{\n\t\t\t\tfor(int a = 1; a <= m; a++)\n\t\t\t\t{\n\t\t\t\t\tdp[i][j][a] = min(dp[i][j][a], dp[i-1][j][a] + cost[i][a]);\n\t\t\t\t\tll tmp = INF;\n\t\t\t\t\tif(a == idx[i-1][j-1])\n\t\t\t\t\t{\n\t\t\t\t\t\ttmp = m2[i-1][j-1];\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ttmp = m1[i-1][j-1];\n\t\t\t\t\t}\n\t\t\t\t    dp[i][j][a] = min(dp[i][j][a], tmp + cost[i][a]);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdp[i][j][c[i]] = min(dp[i][j][c[i]], dp[i-1][j][c[i]]);\n\t\t\t\tfor(int b = 1; b <= m; b++)\n\t\t\t\t{\n\t\t\t\t\tif(b != c[i]) dp[i][j][c[i]] = min(dp[i][j][c[i]], dp[i-1][j-1][b]);\n\t\t\t\t}\n\t\t\t\t//cout << i << ' ' << j << ' ' << c[i] << ' ' << dp[i][j][c[i]] << '\\n';\n\t\t\t}\n\t\t\tfor(int a = 1; a <= m; a++)\n\t\t\t{\n\t\t\t\tif(dp[i][j][a] <= m1[i][j])\n\t\t\t\t{\n\t\t\t\t\tif(dp[i][j][a] == m1[i][j])\n\t\t\t\t\t{\n\t\t\t\t\t\tidx[i][j] = -2;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tidx[i][j] = a;\n\t\t\t\t\t}\n\t\t\t\t\tm2[i][j] = m1[i][j];\n\t\t\t\t\tm1[i][j] = dp[i][j][a];\n\t\t\t\t}\n\t\t\t\telse if(dp[i][j][a] <= m2[i][j])\n\t\t\t\t{\n\t\t\t\t\tm2[i][j] = dp[i][j][a];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tll ans = INF;\n\tfor(int i = 1; i <= m; i++)\n\t{\n\t\tans = min(ans, dp[n][k][i]);\n\t}\n\tif(ans >= INF) ans = -1;\n\tcout << ans;\n}\n",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "711",
    "index": "D",
    "title": "Directed Roads",
    "statement": "ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of $n$ towns numbered from $1$ to $n$.\n\nThere are $n$ directed roads in the Udayland. $i$-th of them goes from town $i$ to some other town $a_{i}$ ($a_{i} ≠ i$). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town $A$ to town $B$ before the flip, it will go from town $B$ to town $A$ after.\n\nZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns $A_{1}, A_{2}, ..., A_{k}$ ($k > 1$) such that for every $1 ≤ i < k$ there is a road from town $A_{i}$ to town $A_{i + 1}$ and another road from town $A_{k}$ to town $A_{1}$. In other words, the roads are confusing if \\textbf{some of them} form a directed cycle of some towns.\n\nNow ZS the Coder wonders how many sets of roads (there are $2^{n}$ variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will \\textbf{not} be confusing.\n\nNote that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.",
    "tutorial": "We want to find the number of ways to assign directions to the edges of the graph so that it is acyclic, i.e. contains no cycles. First, we investigate what the graph looks like. It can be easily seen that the graph consists of several connected components, where each component is either a path or a cycle with some paths connected to some of the vertices. We'll solve the problem for each component and multiply the result for each component. If the component is a path, then however we orient the edges we won't form a cycle. So, if there are $x$ edges in the component, there are $2^{x}$ ways to orient the edges. Next, if the component has a cycle, then we can orient the remaining edges in any way (it will not affect the existence of cycles), then for the $x$ edges on the cycle, we have $2^{x} - 2$ ways to orient them. This is because there are a total of $2^{x}$ ways to orient the edges, but only $2$ ways gives a directed cycle. (fix the direction of one of the edges, then the directions of the other edges are uniquely determined to form a directed cycle) Thus, if there are $t$ edges not on the cycle and $x$ edges on the cycle, the total number of ways for this component is $2^{t}(2^{x} - 2)$. Finally, to compute the final answer we multiply the answers for each component. Computing the powers of $2$ can be done by a simple precomputation or using binary exponentiation. (the former works because the number of vertices is small) Finding the cycles can be easily done with a dfs. Time Complexity : $O(n)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int INF = 1e9 + 7;\nconst int MOD = 1e9 + 7;\nconst int N = 1e6 + 3;\n\nint a[N];\nint visited[N];\nll ans;\nvector<int> cycles;\nll dp[N];\nint cyclecnt;\n\nvoid dfs2(int u)\n{\n\tcycles[cyclecnt]++;\n\tvisited[u] = 3;\n\tif(visited[a[u]] == 3) return ;\n\tdfs2(a[u]);\n}\n\nvoid dfs(int u)\n{\n\tvisited[u] = 2;\n\tif(visited[a[u]] == 0)\n\t{\n\t\tdfs(a[u]);\n\t}\n\telse if(visited[a[u]] == 1)\n\t{\n\t\tvisited[u] = 1;\n\t\treturn ;\n\t}\n\telse\n\t{\n\t\tcycles.pb(0);\n\t\tdfs2(u);\n\t\tcyclecnt++;\n\t}\n\tvisited[u] = 1;\n}\n\nint main()\n{\n\t//ios_base::sync_with_stdio(0); cin.tie(0);\n\tint n; scanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tscanf(\"%d\", a + i);\n\t}\n\tdp[0] = 1;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tdp[i] = (dp[i-1]*2LL)%MOD;\n\t}\n\tans = 1;\n\tmemset(visited, 0, sizeof(visited));\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tif(visited[i] == 0)\n\t\t{\n\t\t\tdfs(i);\n\t\t}\n\t}\n\tll cnt = n;\n\tfor(int i = 0; i < cycles.size(); i++)\n\t{\n\t\tcnt -= cycles[i];\n\t\tans = (ans*(dp[cycles[i]]-2+MOD))%MOD;\n\t}\n\tans = (ans*dp[cnt])%MOD;\n\tif(ans < 0) ans += MOD;\n\tint ans2 = ans;\n\tprintf(\"%d\\n\", ans2);\n\treturn 0;\n}\n",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "711",
    "index": "E",
    "title": "ZS and The Birthday Paradox",
    "statement": "ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of $23$ people, there is around $50%$ chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland.\n\nIn Udayland, there are $2^{n}$ days in a year. ZS the Coder wants to interview $k$ people from Udayland, each of them has birthday in one of $2^{n}$ days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day.\n\nZS the Coder knows that the answer can be written as an irreducible fraction $\\underline{{A}}$. He wants to find the values of $A$ and $B$ (he does not like to deal with floating point numbers). Can you help him?",
    "tutorial": "Note that $MOD = 10^{6} + 3$ is a prime. Firstly, if we have $k > 2^{n}$, then by pigeonhole principle we must have $2$ people with the same birthday. Thus, we can directly output $1$ $1$. Thus, now we suppose $k  \\le  2^{n}$. Then, instead of computing the probability directly, we compute the complement, i.e. the probability that all the people have distinct birthdays. This probability turns out to be much simpler to calculate, as it is just $\\frac{(\\dot{2}^{n}-\\dot{1})(\\dot{2}^{n}-\\dot{2})_{\\omega}(\\dot{2}^{n}-(k-1))}{2^{(k-1)n}}$. (Fix the birthday of the first person, the probability that the second person has different birthday is $\\scriptstyle{\\frac{2^{n}-1}{2^{n}}}$, and for the next person it's $\\frac{2^{n}-2}{2^{n}}$ and so on. Now, we know that the denominator is just a power of $2$. However, we still have to reduce the fraction to the lowest terms. Note that $\\overset{\\stackrel{\\rightarrow}}{b}$ is in the lowest terms if and only if $1-{\\frac{a}{b}}={\\frac{b-a}{b}}$ is in the lowest terms, since $\\operatorname*{gcd}(a,b)=\\operatorname*{gcd}(b-a,b)$. Also, note that the gcd is a power of $2$ since the denominator is a power of $2$. Thus, we need to find the highest power of $2$ that divides $(2^{n} - 1)(2^{n} - 2)...(2^{n} - (k - 1))$. This is also equal to the sum of the highest power of $2$ that divides $2^{n} - 1$, $2^{n} - 2$, ..., $2^{n} - (k - 1)$. Now, if a power of $2$ divides $x < 2^{n}$, then it must also divides $2^{n} - x$ and vice versa. So, we can actually translate this to finding the sum of highest power of $2$ that divides $1, 2, ..., k - 1$, or the highest power of $2$ that divides $(k - 1)!$. Now, this is simple to calculate by Legendre's formula (which is quite easy to prove) in $O(\\log k)$. Now that we find the gcd of the numerator and denominator, we can immediately find the reduced denominator by binary exponentiation. For the numerator, we need a bit more work, since we have to deal with $(2^{n} - 1)(2^{n} - 2)...(2^{n} - (k - 1))$. However, it is not hard either. The key fact is that $MOD$ is small, so if $k - 1  \\ge  MOD$, the product above is equal to $0$ modulo $MOD$, because among $MOD$ consecutive integers there must be one that is a multiple of $MOD$. Thus, the above product can be calculated in $O(MOD)$ if $k - 1  \\le  MOD$ and $O(1)$ otherwise. The remaining parts can be calculated using direct binary exponentiation. One minor note is that when we're calculating $2^{(k - 1)n}$, the value of $(k - 1)n$ might overflow. One way to resolve this is to reduce it modulo $MOD - 1$, since $2^{MOD - 1}  \\equiv  1$ modulo $MOD$ by Fermat's Little Theorem. Another way is to just evaluate $2^{k - 1}$ first, then take the result and raise it to the $n$-th power. Time Complexity : $O(M O D+\\log k+\\log n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef vector<int> vi;\n\nconst int MOD = 1e6 + 3;\n\nll power(ll base, ll exp)\n{\n\tll ans = 1;\n    while(exp)\n    {\n\t\tif(exp&1) ans = (ans*base)%MOD;\n\t\tbase = (base*base)%MOD;\n\t\texp>>=1;\n\t}\n    return ans;\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(false); cin.tie(0);\n\tll n, k;\n\tcin >> n >> k;\n\tif(n <= 63 && k > (1LL<<n))\n\t{\n\t\tcout << 1 << \" \" << 1;\n\t\treturn 0;\n\t}\n\tll v2 = 0;\n\tint digits = __builtin_popcountll(k - 1);\n\tv2 = k - 1 - digits;\n\tll ntmp = n % (MOD - 1);\n\tif(ntmp < 0) ntmp += (MOD - 1);\n\tll ktmp = k % (MOD - 1);\n\tif(ktmp < 0) ktmp += (MOD - 1);\n\tll v2tmp = v2 % (MOD - 1);\n\tif(v2tmp < 0) v2tmp += (MOD - 1);\n\tll exponent = ntmp*(ktmp - 1) - v2tmp;\n\texponent %= (MOD - 1);\n\tif(exponent < 0) exponent += MOD - 1;\n\tll denom = power(2, exponent);\n\tll numpart = 0;\n\tif(k - 1 >= MOD)\n\t{\n\t\tnumpart = 0;\n\t}\n\telse\n\t{\n\t\tll prod = 1;\n\t\tll ntmp2 = power(2, ntmp);\n\t\tprod = power(2, v2tmp);\n\t\tprod = power(prod, MOD - 2);\n\t\tif(prod < 0) prod += MOD;\n\t\tfor(ll y = 1; y <= k - 1; y++)\n\t\t{\n\t\t\tprod = (prod * (ntmp2 - y))%MOD;\n\t\t}\n\t\tnumpart = prod;\n\t}\n\tll num = (denom - numpart)%MOD;\n\tnum %= MOD; denom %= MOD;\n\tif(num < 0) num += MOD;\n\tif(denom < 0) denom += MOD;\n\tcout << num << \" \" << denom;\n\treturn 0;\n}\n",
    "tags": [
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "712",
    "index": "A",
    "title": "Memory and Crow",
    "statement": "There are $n$ integers $b_{1}, b_{2}, ..., b_{n}$ written in a row. For all $i$ from $1$ to $n$, values $a_{i}$ are defined by the crows performing the following procedure:\n\n- The crow sets $a_{i}$ initially $0$.\n- The crow then adds $b_{i}$ to $a_{i}$, subtracts $b_{i + 1}$, adds the $b_{i + 2}$ number, and so on until the $n$'th number. Thus, $a_{i} = b_{i} - b_{i + 1} + b_{i + 2} - b_{i + 3}...$.\n\nMemory gives you the values $a_{1}, a_{2}, ..., a_{n}$, and he now wants you to find the initial numbers $b_{1}, b_{2}, ..., b_{n}$ written in the row? Can you do it?",
    "tutorial": "Note that $a[i] + a[i + 1] = b[i]$. Use the initial condition $b[n] = a[n]$ and we can figure out the entire array $b$. Time Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint arr[100000];\nint ans[100000];\nint main()\n{\n    int n;\n    cin >> n;\n    for(int i=0; i < n; i++){\n        cin >> arr[i];\n\n    }\n\n    for(int i = n-1; i >=0; i--){\n        if(i==n-1) ans[i] = arr[i];\n        else ans[i] = arr[i] + arr[i+1];\n    }\n    for(int i=0; i < n; i++){\n        cout << ans[i] << \" \";\n    }\n    cout << endl;\n    return 0;\n}\n",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "712",
    "index": "B",
    "title": "Memory and Trident",
    "statement": "Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string $s$ with his directions for motion:\n\n- An 'L' indicates he should move one unit left.\n- An 'R' indicates he should move one unit right.\n- A 'U' indicates he should move one unit up.\n- A 'D' indicates he should move one unit down.\n\nBut now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in $s$ with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.",
    "tutorial": "First, if $S$ has odd length, there is no possible string because letters must come in opposite pairs. Now, let's denote the ending coordinate after following $S$ as $(x, y)$. Since $S$ has even length, $|x|$ has the same parity as $|y|$. Suppose they are both even. Then clearly, we can make $x = 0$ in exactly $\\frac{|x|}{2}$ moves, and same for $y$. If instead they are both odd, then we can change exactly one x-character into a y-character. With the correct choices of these characters, now our string has $|x|$ and $|y|$ with even parity, thus reducing to the problem above. Therefore, the answer is $(|x| + |y|) / 2$. Time Complexity: $O(|S|)$",
    "code": "#include <string>\n#include <iostream>\n#include <stdlib.h>\nusing namespace std;\n\n\nint main()\n{\n    string str;\n    cin >> str;\n    if(str.length()%2==1){\n        cout << -1 << endl;\n        return 0;\n    }\n\n    int x=0,y=0;\n    for(int i=0; i < str.length(); i++){\n        if(str[i]=='U')y++;\n        if(str[i]=='D')y--;\n        if(str[i]=='L')x--;\n        if(str[i]=='R')x++;\n    }\n    cout << (abs(x)+abs(y))/2 << endl;\n}\n",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "712",
    "index": "C",
    "title": "Memory and De-Evolution",
    "statement": "Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length $x$, and he wishes to perform operations to obtain an equilateral triangle of side length $y$.\n\nIn a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.\n\nWhat is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length $y$?",
    "tutorial": "Let's reverse the process: start with an equilateral triangle with side length $y$, and lets get to an equilateral triangle with side length $x$. In each step, we can act greedily while obeying the triangle inequality. This will give us our desired answer. Time Complexity: $O(log$ $x)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int x,y;\n    cin >> x >> y;\n\n    int besta=y,bestb=y,bestc=y;\n\n    int turns = 0;\n    while(true){\n        //check the current\n        if(besta>=x && bestb>=x && bestc>=x){\n            cout << turns << endl;\n            break;\n        }\n        turns++;\n        if(turns%3==1){\n            //update a\n            besta = bestb+bestc-1;\n        }\n        if(turns%3==2){\n            //update b\n            bestb = besta+bestc-1;\n        }\n        if(turns%3==0){\n            //update c\n            bestc = besta+bestb-1;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "712",
    "index": "D",
    "title": "Memory and Scores",
    "statement": "Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score $a$ and Lexa starts with score $b$. In a single turn, both Memory and Lexa get some integer in the range $[ - k;k]$ (i.e. one integer among $ - k, - k + 1, - k + 2, ..., - 2, - 1, 0, 1, 2, ..., k - 1, k$) and add them to their current scores. The game has exactly $t$ turns. Memory and Lexa, however, are not good at this game, so they both always get a random integer at their turn.\n\nMemory wonders how many possible games exist such that he ends with a strictly higher score than Lexa. Two games are considered to be different if in at least one turn at least one player gets different score. There are $(2k + 1)^{2t}$ games in total. Since the answer can be very large, you should print it modulo $10^{9} + 7$. Please solve this problem for Memory.",
    "tutorial": "One approach to this problem is by first implementing naive DP in $O((kt)^{2})$. The state for this is $(diff, turn)$, and transitions for $(diff, turn)$ is the sum $(diff - 2k, turn - 1) + 2(diff - 2k + 1, turn - 1) + 3(diff - 2k + 2, turn - 1) + ... + (2k + 1)(diff, turn - 1) + 2k(diff + 1, turn - 1) + ...$ $+ diff( + 2k, turn - 1)$. Now, if we use prefix sums of all differences in (turn-1), along with a sliding window technique across the differences, we can cut a factor of $k$, to achieve desired complexity $O(kt^{2})$. However, there is a much nicer solution in $O(kt$ $log$ $kt)$ using generating functions(thanks to minimario). We can compute the coefficients of $\\begin{array}{r}{\\left({\\frac{(1+x+x^{2}+\\cdots+x^{2k})}{x^{k}}}\\right)^{2l}}\\end{array}$, and the coefficient to $x^{i}$ corresponds to the number of ways we can form the difference $i$. To compute these coefficients, we can use the binomial theorem. Time Complexity: $O(kt^{2})$ Time Complexity: $O(kt$ $log$ $kt)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n\n#define f first\n#define s second\n#define pb push_back\n#define mp make_pair\n\n#define FOR(i, a, b) for (int i=a; i<b; i++)\n#define F0R(i, a) FOR(i, 0, a)\n\nconst int MAX = 1000005;\nconst int MOD = 1000000007;\n\nint f[MAX];\nint fi[MAX];\n\nint pos(int a) { return ((ll)a%MOD+MOD)%MOD; }\nint add(int a, int b) { return ((ll)a+(ll)b)%MOD; }\nint sub(int a, int b) { return pos(a-b); }\nint mult(int a, int b) { return (ll)pos(a)*b%MOD; }\nint sq(int a) { return (ll)a*a%MOD; }\n\nint expo(int a, int b) {\n    if (b == 0) { return 1; }\n    if (b%2) { return mult(a, sq(expo(a, b/2))); }\n    else { return sq(expo(a, b/2)); }\n}\nint inv(int a) { return expo(a, MOD-2); }\n\nint c(int n, int k) {\n    return mult(f[n], mult(fi[k], fi[n-k]));\n}\n\nint poly1[MAX];\nint pref2[MAX];\nint main() {\n    f[0] = fi[0] = 1;\n    FOR(i, 1, MAX) { f[i] = mult(f[i-1], i); fi[i] = inv(f[i]); }\n    int a, b, k, t;\n    cin >> a >> b >> k >> t;\n    if(b-a > 2*k*t){\n    \tcout << 0 << endl;\n    \treturn 0;\n    }\n    F0R(i, 2*t+1) { poly1[(2*k+1)*i] = ((i%2==0)?1:-1)*c(2*t, i); }\n    F0R(i, MAX) { pref2[i] = c(2*t-1+i+1, 2*t); }\n    int lb = 2*k*t+b-a+1;\n    int ub = 4*k*t;\n    int ans = 0;\n    F0R(i, 2*t+1) {\n        int l = lb-(2*k+1)*i;\n        int u = ub-(2*k+1)*i;\n        if (u < 0) { break; }\n        if (l < 0) { ans = add(ans, mult(poly1[(2*k+1)*i], pref2[u])); }\n        else { ans = add(ans, mult(poly1[(2*k+1)*i], sub(pref2[u], pref2[l-1]))); }\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "712",
    "index": "E",
    "title": "Memory and Casinos",
    "statement": "There are $n$ casinos lined in a row. If Memory plays at casino $i$, he has probability $p_{i}$ to win and move to the casino on the right ($i + 1$) or exit the row (if $i = n$), and a probability $1 - p_{i}$ to lose and move to the casino on the left ($i - 1$) or also exit the row (if $i = 1$).\n\nWe say that Memory dominates on the interval $i... j$ if he completes a walk such that,\n\n- He starts on casino $i$.\n- He never looses in casino $i$.\n- He finishes his walk by winning in casino $j$.\n\nNote that Memory can still walk left of the $1$-st casino and right of the casino $n$ and that always finishes the process.\n\nNow Memory has some requests, in one of the following forms:\n\n- $1$ $i$ $a$ $b$: Set $p_{i}={\\frac{a}{b}}$.\n- $2$ $l$ $r$: Print the probability that Memory will dominate on the interval $l... r$, i.e. compute the probability that Memory will first leave the segment $l... r$ after winning at casino $r$, if she starts in casino $l$.\n\nIt is guaranteed that at any moment of time $p$ is a \\textbf{non-decreasing sequence}, i.e. $p_{i} ≤ p_{i + 1}$ for all $i$ from $1$ to $n - 1$.\n\nPlease help Memory by answering all his requests!",
    "tutorial": "Lets think about two segments of casinos $[i, j]$ and $[j + 1, n]$. Let $L([a, b])$ denote the probability we dominate on $[a, b]$, and let $R([a, b])$ denote the probability we start on $b$ and end by moving right of $b$. Let $l_{1} = L([i, j])$, $l_{2} = L([j + 1, n])$, $r_{1} = R([i, j])$, $r_{2} = R([j + 1, n])$. You can use a geometric series to figure out both $L([i, n])$ and $R([i, n])$ using only $l_{1}$,$l_{2}$,$r_{1}$, and $r_{2}$. To derive these series, think about the probability we cross over from $j$ to $j + 1$ once, twice, three times, and so on. The actual formulas are, $L([i,n])=\\frac{l_{1}l_{2}}{1+r_{1}(l_{2}-1)}$ $R([i,n])=r_{2}+\\frac{r_{1}l_{2}(1-r_{2})}{1-r_{1}(1-l_{2})}$ Now we can build a segment tree on the casinos, and use the above to merge segments. Time Complexity: $O(N + QlogN)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n\nint n;\ndouble pr[100000];\npair<double,double> seg[400000];\nbool ze(double d){\n\treturn (abs(d) <= 0.0000000001);\n}\npair<double,double> merge(pair<double,double> a, pair<double,double> b){\n\tif(ze(a.first+1) && ze(a.second+1)) return b;\n\tif(ze(b.first+1) && ze(b.second+1)) return a;\n\tdouble l1 = a.first;\n\tdouble r1 = a.second;\n\tdouble l2 = b.first;\n\tdouble r2 = b.second;\n\tif(ze(((l2-1)*r1+1))) return make_pair(0,0);\n\tdouble le = l1*l2/((l2-1)*r1+1);\n\tdouble ri = r2+(r1*l2*(-r2+1))/(-r1*(-l2+1)+1);\n\treturn make_pair(le,ri);\n}\nvoid build(int no, int b, int e){\n\tif(b==e){\n\t\tseg[no] = make_pair(pr[b],pr[b]);\n\t\treturn;\n\t}\n\tint mid = (b+e)/2;\n\tbuild(2*no,b,mid);\n\tbuild(2*no+1,mid+1,e);\n\tseg[no] = merge(seg[2*no],seg[2*no+1]);\n}\nvoid upd(int no, int b, int e, int i, double val){\n\tif(i<b || i>e) return;\n\tif(b==e){\n\t\tseg[no] = make_pair(val,val);\n\t\treturn;\n\t}\n\tint mid = (b+e)/2;\n\tupd(2*no,b,mid,i,val);\n\tupd(2*no+1,mid+1,e,i,val);\n\tseg[no] = merge(seg[2*no],seg[2*no+1]);\n}\npair<double,double> query(int no, int b, int e, int l, int r){\n\tif(b>r || e<l) return make_pair(-1,-1);\n\tif(l<=b && e<=r) return seg[no];\n\tint mid = (b+e)/2;\n\treturn merge(query(2*no,b,mid,l,r),query(2*no+1,mid+1,e,l,r));\n}\nint main(){\n    int q;\n\tscanf(\"%d %d\", &n, &q);\n\tfor(int i=0; i < n; i++){\n\t\tint a,b;\n\t\tscanf(\"%d %d\", &a, &b);\n\t\tpr[i] = (double)a / (double)b;\n\t}\n\t\n\tbuild(1,0,n-1);\n\tfor(int que = 0; que < q; que++){\n\t\tint ty;\n\t\tint a;\n\t\tint b;\n\t\tscanf(\"%d %d %d\", &ty, &a, &b);\n\t\tif(ty==1){\n\t\t\tint c;\n\t\t\tscanf(\"%d\", &c);\n\t\t\tupd(1,0,n-1,a-1, (double)b / (double)c);\n\t\t}\n\t\telse{\n\t\t    printf(\"%.20f\\n\", query(1,0,n-1,a-1,b-1).first);\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\n",
    "tags": [
      "data structures",
      "math",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "713",
    "index": "A",
    "title": "Sonya and Queries",
    "statement": "Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her $t$ queries, each of one of the following type:\n\n- $ + $ $a_{i}$ — add non-negative integer $a_{i}$ to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.\n- $ - $ $a_{i}$ — delete a single occurrence of non-negative integer $a_{i}$ from the multiset. It's guaranteed, that there is at least one $a_{i}$ in the multiset.\n- $?$ $s$ — count the number of integers in the multiset (with repetitions) that match some pattern $s$ consisting of $0$ and $1$. In the pattern, $0$ stands for the even digits, while $1$ stands for the odd. Integer $x$ matches the pattern $s$, if the parity of the $i$-th from the right digit in decimal notation matches the $i$-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with $0$-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the $0$-s from the left.\n\nFor example, if the pattern is $s = 010$, than integers $92$, $2212$, $50$ and $414$ match the pattern, while integers $3$, $110$, $25$ and $1030$ do not.",
    "tutorial": "Lets exchange every digit by value of digit modulo $2$ and receive binary string. We will convert it to binary form in number $r$. $G$ - array for counts. If we have '+' query we increase $G$[$r$]. If we have '-' query we decrease $G$[$r$]. Otherwise we output $G$[$r$].",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "713",
    "index": "B",
    "title": "Searching Rectangles",
    "statement": "Filya just learned new geometry object — rectangle. He is given a field consisting of $n × n$ unit cells. Rows are numbered from bottom to top with integer from $1$ to $n$. Columns are numbered from left to right with integers from $1$ to $n$. Cell, located at the intersection of the row $r$ and column $c$ is denoted as $(r, c)$. Filya has painted two rectangles, such that their sides are parallel to coordinate axes and each cell lies fully inside or fully outside each of them. Moreover, no cell lies in both rectangles.\n\nLater, hedgehog Filya became interested in the location of his rectangles but was unable to find the sheet of paper they were painted on. They were taken by Sonya and now she wants to play a little game with Filya. He tells her a query rectangle and she replies with the number of initial rectangles that lie \\textbf{fully inside} the given query rectangle. The query rectangle should match the same conditions as initial rectangles. Rectangle lies fully inside the query if each o its cells lies inside the query.\n\nFilya knows Sonya really well, so is sure that if he asks more than $200$ questions she will stop to reply.",
    "tutorial": "Assume we have just one rectangle. First we can find its right side. In binary search we check is out rectangle to the left of some line $x_{2}$ using function $get$($1$,$1$,$x_{2}$,$n$). As soon as we found right coordinate we can 'cut' everything to the right of the line, because there is nothing to look. In the same way we will find all sides. $O$($12 * logN$): Main idea is to find a line which will split space in the way that rectangles will lie in different parts, as rectangles are not intersected it is always possible. We can assume that intersected line is parallel to y coordinate and use binary search by $x$. On each step of search we will count amount of rectangles on each side. If we have pair ($1$, $1$) then line is found. If we have pair ($0$, $0$) then intersected line is parallel to $x$ coordinate. Otherwise we should search in the half where we have some rectangles. In worst case we will have $2$ searches each will take $2 * log$($n$) time, also we have $4 * log$($n$) time to find separated rectangle. In total we $2 * 2 * log$($n$) + $2 * 4 * log$($n$)$= 12 * log$($n$). $O$($8 * logN$): We can find first rectangle assuming that here is just one rectangle. In each of four of our search we will assume that rectangle is present if get will return $1$ or $2$. When we have one rectangle we can search second assuming that we can modify get function to $get2$, which will assume coordinates of first rectangle and decrease original value if it is required.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2200
  },
  {
    "contest_id": "713",
    "index": "C",
    "title": "Sonya and Problem Wihtout a Legend",
    "statement": "Sonya was unable to think of a story for this problem, so here comes the formal description.\n\nYou are given the array containing $n$ positive integers. At one turn you can pick any element and increase or decrease it by $1$. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to $0$.",
    "tutorial": "Lets first solve easier problem. Given an array of number what it is minimal amount of operations ($+ 1$ to element, $- 1$ to element) to make all numbers in array equal? We need to solve this problem for each prefix. Optimal solution would be making all numbers equal to median value of the prefix (middle element in sorted list). For this problem we can simply use two heaps and insert element in right one (removing elements from inserted if need) to keep heaps equal and fit the constraint max_value(Heap1) $ \\le $ min_value(Heap2). Now lets solve harder problem. What is minimal amount of operations ($+ 1$ to element, $- 1$ to element) to make array be arithmetics progression with step $1$? We can just reduce number $a_{i}$ in array by value $i$ and will receive previous problem. Finally we have original problem. $Dp_{i}$ - answer for prefix ending in $i$, i.e. number of operations to make prefix of first $i$ elements in increasing order. Also for each $i$ will remember minimal last number in resulting sequence. For each $i$ will bruteforce value $j$ ($i > j$) and calculate answer for $j$ if [$i + 1$, $j$] if arithmetics progression with step $1$. Also we need to assume if median value in [$i + 1$, $j$] is lower than minimal value at i than we cannot update answer for $j$ by answer for $i$.",
    "tags": [
      "dp",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "713",
    "index": "D",
    "title": "Animals and Puzzle",
    "statement": "Owl Sonya gave a huge lake puzzle of size $n × m$ to hedgehog Filya as a birthday present. Friends immediately started to assemble the puzzle, but some parts of it turned out to be empty — there was no picture on them. Parts with picture on it are denoted by $1$, while empty parts are denoted by $0$. Rows of the puzzle are numbered from top to bottom with integers from $1$ to $n$, while columns are numbered from left to right with integers from $1$ to $m$.\n\nAnimals decided to complete the picture and play with it, as it might be even more fun! Owl and hedgehog ask each other some queries. Each query is provided by four integers $x_{1}$, $y_{1}$, $x_{2}$, $y_{2}$ which define the rectangle, where $(x_{1}, y_{1})$ stands for the coordinates of the up left cell of the rectangle, while $(x_{2}, y_{2})$ stands for the coordinates of the bottom right cell. The answer to the query is the size of the maximum \\textbf{square} consisting of picture parts only (only parts denoted by $1$) and located fully inside the query rectangle.\n\nHelp Sonya and Filya answer $t$ queries.",
    "tutorial": "First lets calculate $dp[i][j]$ - maximum square ending in cell ($i$, $j$). For each cell if input matrix contain $0$ then $dp[i][j] = 0$ else $dp_{}[i][j] = min$($dp[i - 1][j - 1]$, $dp[i-1][j]$, $dp[i][j-1]$)$+ 1$. We will use binary search to find the answer. Lets fix some value $x$. For each square ($i$, $j$)..($i + x - 1$, $j + x - 1$) we need to find maximum and compare it to $x$. To find maximum we can use $2D$ $sparse$ $table$. So preprocessing takes $O$($NMlogNlogM$), and query works in $O$($logN$).",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "713",
    "index": "E",
    "title": "Sonya Partymaker",
    "statement": "Owl Sonya decided to become a partymaker. To train for this role she gather all her owl friends in the country house. There are $m$ chairs located in a circle and consequently numbered with integers from $1$ to $m$. Thus, chairs $i$ and $i + 1$ are neighbouring for all $i$ from $1$ to $m - 1$. Chairs $1$ and $m$ are also neighbouring. Some chairs are occupied by her friends. There are $n$ friends in total. No two friends occupy the same chair. Rules are the following:\n\n- Each participant removes from the game the chair he is currently sitting on.\n- Each of the participants choose a direction that she will follow: clockwise (indices increase, from $m$ goes to $1$) and counter-clockwise (indices decrease, from $1$ goes to $m$). This direction may coincide or be different for any pair of owls.\n- Each turn all guests move one step in the chosen directions. If some guest move to the position with a chair there, he removes this chair from the game.\n- Game ends if there are no more chairs left in the game.\n\nOwls are very busy and want to get rid of the game as soon as possible. They cooperate to pick the direction. Your goal is to find the minimum number o moves required to finish the game.",
    "tutorial": "Will use binary search to find the answer. Assume that we need to know if it is enough $x$ minutes to visit each vertex. Lets $dp[i][0...1]$ is equal to minimum number of vertices to the left of $i$, which wasn't visited yet, second parameter is equal to $1$, if we have't launched robot from vertex $i$. I.e. when $dp[i][j] > 0$ vertices $[i-dp[i][j], i-1]$ haven't been visited, and if $dp[i][j] < 0$ then $dp[i][j]$ vertices to the right we still can visit. We need to calculate such DP for two starting states ($dp[0][0] = 0$, $dp[0][1] = 0$). Now we need to implement next: - if $0 < dp[i][1]  \\le  x$ then distance can be walked and we need to update $dp[i][0]$ by $0$ - if $dp[i][1]  \\le  0$ then we can update $dp[i][0]$ by $-x$ - using $dp[i][0]$, update $dp[i + 1][1]$ - using $dp[i][1]$, update $dp[i + 1][0]$ Walk in time $x$ is also possible if $dp[n][0..1$ (depending on start state)] $ \\le  0$. Need to assume few other facts: if $dp[n][j]  \\neq  0$ then we can repeat $DP$ with param $dp[0][j] = dp[n][j]$, and if, $dp[n][j]  \\le  dp[0][j]$, then distance can be walked To assume every case we need to calculate this DP for each pair of sequent vertices",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 3300
  },
  {
    "contest_id": "714",
    "index": "A",
    "title": "Meeting of Old Friends",
    "statement": "Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya!\n\nSonya is an owl and she sleeps during the day and stay awake from minute $l_{1}$ to minute $r_{1}$ inclusive. Also, during the minute $k$ she prinks and is unavailable for Filya.\n\nFilya works a lot and he plans to visit Sonya from minute $l_{2}$ to minute $r_{2}$ inclusive.\n\nCalculate the number of minutes they will be able to spend together.",
    "tutorial": "Lets find two numbers $l$ and $r$ - lower and upper bound on time which guys can spend together. $l =$ $max$($l_{1}$, $l_{2}$), $r =$ $min$($r_{1}$,$r_{2}$). If $l > r$ then answer is definitely $0$. In case $l  \\le  r$ we need to number $k$ belongs to the interval. If is it true - answer is $r - l$, otherwise it is $r - l + 1$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "714",
    "index": "B",
    "title": "Filya and Homework",
    "statement": "Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help.\n\nFilya is given an array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$. First, he pick an integer $x$ and then he adds $x$ to some elements of the array (no more than once), subtract $x$ from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal.\n\nNow he wonders if it's possible to pick such integer $x$ and change some elements of the array using this $x$ in order to make all elements equal.",
    "tutorial": "Answer can be calculated according to next options: 1). If all numbers are equal - answer is <<Yes>> 2). If there are two distinct numbers in the array - answer is <<Yes>> 3). If there are at least four distinct numbers in the array - answer is <<No>> 4). In other case lets there are three distinct numbers $q < w < e$, answer is <<Yes>> if and only if $2 * w = q + e$.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "715",
    "index": "A",
    "title": "Plus and Square Root",
    "statement": "ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, '$ + $' (plus) and '$\\lor$' (square root). Initially, the number $2$ is displayed on the screen. There are $n + 1$ levels in the game and ZS the Coder start at the level $1$.\n\nWhen ZS the Coder is at level $k$, he can :\n\n- Press the '$ + $' button. This increases the number on the screen by exactly $k$. So, if the number on the screen was $x$, it becomes $x + k$.\n- {Press the '$\\lor\\overset{\\lor}{\\to}$' button}. Let the number on the screen be $x$. After pressing this button, the number becomes $\\sqrt{x}$. After that, ZS the Coder levels up, so his current level becomes $k + 1$. This button can only be pressed when $x$ is a \\textbf{perfect square}, i.e. $x = m^{2}$ for some positive integer $m$.\n\nAdditionally, after each move, if ZS the Coder is at level $k$, and the number on the screen is $m$, then \\textbf{$m$ must be a multiple of $k$}. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level $4$ and current number is $100$, he presses the '$\\lor\\overset{\\lor}{\\to}$' button and the number turns into $10$. Note that at this moment, $10$ is not divisible by $4$, but this press is still valid, because after it, ZS the Coder is at level $5$, and $10$ is divisible by $5$.\n\nZS the Coder needs your help in beating the game — he wants to reach level $n + 1$. In other words, he needs to press the '$\\lor$' button $n$ times. Help him determine the number of times he should press the '$ + $' button before pressing the '$\\lor\\overset{\\lor}{\\to}$' button at each level.\n\nPlease note that ZS the Coder wants to find just any sequence of presses allowing him to reach level $n + 1$, but not necessarily a sequence minimizing the number of presses.",
    "tutorial": "Firstly, let $a_{i}(1  \\le  i  \\le  n)$ be the number on the screen before we level up from level $i$ to $i + 1$. Thus, we require all the $a_{i}$s to be perfect square and additionally to reach the next $a_{i}$ via pressing the plus button, we require $a_{i+1}\\equiv\\sqrt{a_{i}}(m o d(i+1))$ and $a_{i+1}\\geq{\\sqrt{a_{i}}}$ for all $1  \\le  i < n$. Additionally, we also require $a_{i}$ to be a multiple of $i$. Thus, we just need to construct a sequence of such integers so that the output numbers does not exceed the limit $10^{18}$. There are many ways to do this. The third sample actually gave a large hint on my approach. If you were to find the values of $a_{i}$ from the second sample, you'll realize that it is equal to $4, 36, 144, 400$. You can try to find the pattern from here. My approach is to use $a_{i} = [i(i + 1)]^{2}$. Clearly, it is a perfect square for all $1  \\le  i  \\le  n$ and when $n = 100000$, the output values can be checked to be less than $10^{18}$ Unable to parse markup [type=CF_TEX] The constraints $a_{i}$ must be a multiple of $i$ was added to make the problem easier for Div. 1 A. Time Complexity : $O(n)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<ll,ll> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tll n; cin >> n;\n\tfor(ll i = 1; i <= n; i++)\n\t{\n\t\tif(i == 1) cout << 2 << '\\n';\n\t\telse cout << i*(i+1)*(i+1)-(i-1) << '\\n';\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "715",
    "index": "B",
    "title": "Complete The Graph",
    "statement": "ZS the Coder has drawn an undirected graph of $n$ vertices numbered from $0$ to $n - 1$ and $m$ edges between them. Each edge of the graph is weighted, each weight is a \\textbf{positive integer}.\n\nThe next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign \\textbf{positive integer} weight to each of the edges which weights were erased, so that the length of the shortest path between vertices $s$ and $t$ in the resulting graph is exactly $L$. Can you help him?",
    "tutorial": "This problem is actually quite simple if you rule out the impossible conditions. Call the edges that does not have fixed weight variable edges. First, we'll determine when a solution exists. Firstly, we ignore the variable edges. Now, find the length of the shortest path from $s$ to $e$. If this length is $< L$, there is no solution, since even if we replace the $0$ weights with any positive weight the shortest path will never exceed this shortest path. Thus, if the length of this shortest path is $< L$, there is no solution. (If no path exists we treat the length as $ \\infty $.) Next, we replace the edges with $0$ weight with weight $1$. Clearly, among all the possible graphs you can generate by replacing the weights, this graph will give the minimum possible shortest path from $s$ to $e$, since increasing any weight will not decrease the length of the shortest path. Thus, if the shortest path of this graph is $> L$, there is no solution, since the shortest path will always be $> L$. If no path exists we treat the length as $ \\infty $. Other than these two conditions, there will always be a way to assign the weights so that the shortest path from $s$ to $e$ is exactly $L$! How do we prove this? First, consider all paths from $s$ to $e$ that has at least one $0$ weight edge, as changing weights won't affect the other paths. Now, we repeat this algorithm. Initially, assign all the weights as $1$. Then, sort the paths in increasing order of length. If the length of the shortest path is equal to $L$, we're done. Otherwise, increase the weight of one of the variable edges on the shortest path by $1$. Note that this will increase the lengths of some of the paths by $1$. It is not hard to see that by repeating these operations the shortest path will eventually have length $L$, so an assignment indeed exists. Now, we still have to find a valid assignment of weights. We can use a similar algorithm as our proof above. Assign $1$ to all variable edges first. Next, we first find and keep track of the shortest path from $s$ to $e$. Note that if this path has no variable edges it must have length exactly $L$ or strictly more than $L$, so either we're already done or the shortest path contains variable edges and the length is strictly less than $L$. (otherwise we're done) From now on, whenever we assign weight to a variable edge (after assigning $1$ to every variable edge), we call the edge assigned. Now, mark all variable edges not on the shortest path we found as $ \\infty $ weight. (we can choose any number greater than $L$ as $ \\infty $) Next, we will find the shortest path from $s$ to $e$, and replace the weight of an unassigned variable edge such that the length of the path becomes equal to $L$. Now, we don't touch the assigned edges again. While the shortest path from $s$ to $e$ is still strictly less than $L$, we repeat the process and replace a variable edge that is not assigned such that the path length is equal to $L$. Note that this is always possible, since otherwise this would've been the shortest path in one of the previous steps. Eventually, the shortest path from $s$ to $e$ will have length exactly $L$. It is easy to see that we can repeat this process at most $n$ times because we are only replacing the edges which are on the initial shortest path we found and there are less than $n$ edges to replace (we only touch each edge at most once). Thus, we can find a solution after less than $n$ iterations. So, the complexity becomes $O(m n\\log n)$. This is sufficient to pass all tests. What if the constraints were $n, m  \\le  10^{5}$? Can we do better? Yes! Thanks to HellKitsune who found this solution during testing. First, we rule out the impossible conditions like we did above. Then, we assign all the variable edges with $ \\infty $ weight. We enumerate the variable edges arbitarily. Now, we binary search to find the minimal value $p$ such that if we make all the variable edges numbered from $1$ to $p$ have weight $1$ and the rest $ \\infty $, then the shortest path from $s$ to $e$ has length $ \\le  L$. Now, note that if we change the weight of $p$ to $ \\infty $ the length of shortest path will be more than $L$. (if $p$ equals the number of variable edges, the length of the shortest path is still more than $L$ or it will contradict the impossible conditions) If the weight is $1$, the length of the shortest path is $ \\le  L$. So, if we increase the weight of edge $p$ by $1$ repeatedly, the length of the shortest path from $s$ to $e$ will eventually reach $L$, since this length can increase by at most $1$ in each move. So, since the length of shortest path is non-decreasing when we increase the weight of this edge, we can binary search for the correct weight. This gives an $O(m\\log n(\\log m+\\log L))$ solution. Time Complexity : $O(m n\\log n)$ or $O(m\\log n(\\log m+\\log L))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<ll,ll> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int N = 1001;\nconst int M = 10001;\nconst ll INF = ll(1e18);\n\nint n, m, l, s, e;\n\nstruct edge\n{\n\tint to; ll w; int label;\n\tedge(int _to, int _w, int _label){to = _to, w = _w, label = _label;}\n};\n\nint edgecnt = -1;\nvector<edge> adj[N];\nll dist[N];\nset<ii> used;\n\nll dijk(int p, ll val)\n{\n\tfor(int i = 0; i < n; i++) dist[i] = INF;\n\tdist[s] = 0;\n\tpriority_queue<ii, vector<ii>, greater<ii> > pq;\n\tpq.push(ii(0, s));\n\twhile(!pq.empty())\n\t{\n\t\tint u = pq.top().se; ll d = pq.top().fi; pq.pop();\n\t\tfor(int i = 0; i < adj[u].size(); i++)\n\t\t{\n\t\t\tedge tmp = adj[u][i];\n\t\t\tint v = tmp.to; ll w = tmp.w; int lab = tmp.label;\n\t\t\tif(lab >= 0)\n\t\t\t{\n\t\t\t\tif(lab < p) w = 1;\n\t\t\t\telse if(lab == p) w = val;\n\t\t\t\telse w = ll(1e14);\n\t\t\t}\n\t\t\tif(d + w < dist[v])\n\t\t\t{\n\t\t\t\tdist[v] = d + w;\n\t\t\t\tpq.push(ii(dist[v], v));\n\t\t\t}\n\t\t}\n\t}\n\treturn dist[e];\n}\n\nvoid setw(int p, ll val)\n{\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j < adj[i].size(); j++)\n\t\t{\n\t\t\tint lab = adj[i][j].label;\n\t\t\tif(lab >= 0)\n\t\t\t{\n\t\t\t\tif(lab < p)\n\t\t\t\t{\n\t\t\t\t\tadj[i][j].w = 1;\n\t\t\t\t}\n\t\t\t\telse if(lab == p)\n\t\t\t\t{\n\t\t\t\t\tadj[i][j].w = val;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tadj[i][j].w = INF;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid print()\n{\n\tcout << \"YES\\n\";\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j < adj[i].size(); j++)\n\t\t{\n\t\t\tedge tmp = adj[i][j];\n\t\t\tint v = tmp.to; ll w = tmp.w; \n\t\t\tif(used.find(ii(i, v)) == used.end())\n\t\t\t{\n\t\t\t\tcout << i << ' ' << v << ' ' << w << '\\n';\n\t\t\t\tused.insert(ii(i, v)); used.insert(ii(v, i));\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tcin >> n >> m >> l >> s >> e;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint u, v, w;\n\t\tcin >> u >> v >> w;\n\t\tint lab = -1;\n\t\tif(w == 0) \n\t\t{\n\t\t\tlab = ++edgecnt;\n\t\t}\n\t\tadj[u].pb(edge(v, w, lab));\n\t\tadj[v].pb(edge(u, w, lab));\n\t}\n\tll x = dijk(edgecnt, 1); ll y = dijk(-1, 1);\n\tif(!(x <= l && l <= y))\n\t{\n\t\tcout << \"NO\\n\";\n\t\treturn 0;\n\t}\n\tll lo = -1; ll hi = edgecnt;\n\tll mid, ans;\n\twhile(lo <= hi)\n\t{\n\t\tmid = (lo+hi)/2;\n\t\tif(dijk(mid, 1) <= l)\n\t\t{\n\t\t\tans = mid;\n\t\t\thi = mid - 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlo = mid + 1;\n\t\t}\n\t}\n\t//now [0..ans] as 1 will give <= L whereas [0..ans - 1] as 1 will give > L\n\tif(ans == -1)\n\t{\n\t\tsetw(-1, 0);\n\t\tprint();\n\t\treturn 0;\n\t}\n\tlo = 1; hi = INF;\n\tint ans2 = 0;\n\twhile(lo <= hi)\n\t{\n\t\tmid = (lo+hi)>>1;\n\t\tif(dijk(ans, mid) <= l)\n\t\t{\n\t\t\tans2 = mid;\n\t\t\tlo = mid + 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\thi = mid - 1;\n\t\t}\n\t}\n\t//cerr << ans << ' ' << ans2 << '\\n';\n\tsetw(ans, ans2);\n\tprint();\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "graphs",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "715",
    "index": "C",
    "title": "Digit Tree",
    "statement": "ZS the Coder has a large tree. It can be represented as an undirected connected graph of $n$ vertices numbered from $0$ to $n - 1$ and $n - 1$ edges between them. There is a single \\textbf{nonzero} digit written on each edge.\n\nOne day, ZS the Coder was bored and decided to investigate some properties of the tree. He chose a positive integer $M$, which is \\textbf{coprime} to $10$, i.e. $\\operatorname*{gcd}(M,10)=1$.\n\nZS consider an \\textbf{ordered pair} of distinct vertices $(u, v)$ interesting when if he would follow the shortest path from vertex $u$ to vertex $v$ and write down all the digits he encounters on his path in the same order, he will get a decimal representaion of an integer divisible by $M$.\n\nFormally, ZS consider an ordered pair of distinct vertices $(u, v)$ interesting if the following states true:\n\n- Let $a_{1} = u, a_{2}, ..., a_{k} = v$ be the sequence of vertices on the shortest path from $u$ to $v$ in the order of encountering them;\n- Let $d_{i}$ ($1 ≤ i < k$) be the digit written on the edge between vertices $a_{i}$ and $a_{i + 1}$;\n- The integer $\\overline{{{d_{1}d_{2}\\cdot\\cdot\\cdot\\cdot d_{k-1}}}}=\\sum_{i=1}^{k-1}d_{i}\\cdot10^{k-1-i}$ is divisible by $M$.\n\nHelp ZS the Coder find the number of interesting pairs!",
    "tutorial": "Compared to the other problems, this one is more standard. The trick is to first solve the problem if we have a fixed vertex $r$ as root and we want to find the number of paths passing through $r$ that works. This can be done with a simple tree dp. For each node $u$, compute the number obtained when going from $r$ down to $u$ and the number obtained when going from $u$ up to $r$, where each number is taken modulo $M$. This can be done with a simple dfs. To calculate the down value, just multiply the value of the parent node by $10$ and add the value on the edge to it. To calculate the up value, we also need to calculate the height of the node. (i.e. the distance from $u$ to $r$) Then, if we let $h$ be the height of $u$, $d$ be the digit on the edge connecting $u$ to its parent and $val$ be the up value of the parent of $u$, then the up value for $u$ is equal to $10^{h - 1} \\cdot d + val$. Thus, we can calculate the up and down value for each node with a single dfs. Next, we have to figure out how to combine the up values and down values to find the number of paths passing through $r$ that are divisible by $M$. For this, note that each path is the concatenation of a path from $u$ to $r$ and $r$ to $v$, where $u$ and $v$ are pairs of vertices from different subtrees, and the paths that start from $r$ and end at $r$. For the paths that start and end at $r$ the answer can be easily calculated with the up and down values (just iterate through all nodes as the other endpoint). For the other paths, we iterate through all possible $v$, and find the number of vertices $u$ such that going from $u$ to $v$ will give a multiple of $M$. Since $v$ is fixed, we know its height and down value, which we denote as $h$ and $d$ respectively. So, if the up value of $u$ is equal to $up$, then $up \\cdot 10^{h} + d$ must be a multiple of $M$. So, we can solve for $up$ to be $- d \\cdot 10^{ - h}$ modulo $M$. Note that in this case the multiplicative inverse of $10$ modulo $M$ is well-defined, as we have the condition $\\operatorname*{gcd}(M,10)=1$. To find the multiplicative inverse of $10$, we can find $ \\phi (M)$ and since by Euler's Formula we have $x^{ \\phi (M)}  \\equiv  1(modM)$ if $\\operatorname*{gcd}(x,M)=1$, we have $x^{ \\phi (M) - 1}  \\equiv  x^{ - 1}(modM)$, which is the multiplicative inverse of $x$ (in this case we have $x = 10$) modulo $M$. After that, finding the $up$ value can be done by binary exponentiation. Thus, we can find the unique value of $up$ such that the path from $u$ to $v$ is a multiple of $M$. This means that we can just use a map to store the up values of all nodes and also the up values for each subtree. Then, to find the number of viable nodes $u$, find the required value of $up$ and subtract the number of suitable nodes that are in the same subtree as $v$ from the total number of suitable nodes. Thus, for each node $v$, we can find the number of suitable nodes $u$ in $O(\\log M O D)$ time. Now, we have to generalize this for the whole tree. We can use centroid decomposition. We pick the centroid as the root $r$ and find the number of paths passing through $r$ as above. Then, the other paths won't pass through $r$, so we can remove $r$ and split the tree into more subtrees, and recursively solve for each subtree as well. Since each subtree is at most half the size of the original tree, and the time taken to solve the problem where the path must pass through the root for a single tree takes time proportional to the size of the tree, this solution works in $O(n\\log n(\\log n+\\log M O D))$ time, where the other $\\log n$ comes from using maps. Time Complexity : $O(n\\log n(\\log n+\\log M O D))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int N = 1e5 + 1;\nconst int MAX = 1e9;\nint MOD, n;\n\nbool isprime[100001];\nvector<ll> primes;\nvector<ii> adj[N];\nint subsize[N];\nbool visited[N];\nint treesize;\nvi clrlist;\nll up[N];\nll down[N];\nint h[N];\nint PHI;\nint dppart[N];\n\nll mult(ll a, ll b)\n{\n\treturn (a*b)%MOD;\n}\n\nll add(ll a, ll b)\n{\n\treturn (a+b+MOD)%MOD;\n}\n\nll modpow(ll a, ll b)\n{\n\tll r = 1;\n\twhile(b)\n\t{\n\t\tif(b&1) r=(r*a)%MOD;\n\t\ta=(a*a)%MOD;\n\t\tb>>=1;\n\t}\n\treturn r;\n}\n\nvoid Sieve(int n)\n{\n\tmemset(isprime, 1, sizeof(isprime));\n\tisprime[1] = false;\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tif(isprime[i])\n\t\t{\n\t\t\tprimes.pb(i);\n\t\t\tfor(int j = 2*i; j <= n; j += i)\n\t\t\t{\n\t\t\t\tisprime[j] = false;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint phi(int n)\n{\n\tll num = 1; ll num2 = n;\n\tfor(ll i = 0; primes[i]*primes[i] <= n; i++)\n\t{\n\t\tif(n%primes[i]==0)\n\t\t{\n\t\t\tnum2/=primes[i];\n\t\t\tnum*=(primes[i]-1);\n\t\t}\n\t\twhile(n%primes[i]==0)\n\t\t{\n\t\t\tn/=primes[i];\n\t\t}\n\t}\n\tif(n>1)\n\t{\n\t\tnum2/=n; num*=(n-1);\n\t}\n\tn = 1;\n\tnum*=num2;\n\treturn num;\n}\n\nll inv(ll a)\n{\n\treturn modpow(a, PHI-1);\n}\n\nvoid dfs(int u, int par)\n{\n\tif(par == -1) clrlist.clear();\n\tsubsize[u] = 1; clrlist.pb(u);\n\tfor(int i = 0; i < adj[u].size(); i++)\n\t{\n\t\tint v = adj[u][i].fi;\n\t\tif(visited[v]) continue;\n\t\tif(v == par) continue;\n\t\tdfs(v, u);\n\t\tsubsize[u] += subsize[v];\n\t}\t\n\tif(par == -1) treesize = subsize[u];\n}\n\nint centroid(int u, int par)\n{\n\tfor(int i = 0; i < adj[u].size(); i++)\n\t{\n\t\tint v = adj[u][i].fi;\n\t\tif(visited[v]) continue;\n\t\tif(v == par) continue;\n\t\tif(subsize[v]*2 > treesize) return centroid(v, u);\n\t}\n\treturn u;\n}\n\nint parts = 0;\nvoid fill(int u, int p, int cent)\n{\n\tif(p == cent)\n\t{\n\t\tdppart[u] = parts;\n\t\tparts++;\n\t}\n\telse if(p != -1)\n\t{\n\t\tdppart[u] = dppart[p];\n\t}\n\tfor(int i = 0; i < adj[u].size(); i++)\n\t{\n\t\tint v = adj[u][i].fi; int w = adj[u][i].se;\n\t\tif(v == p || visited[v]) continue;\n\t\tdown[v] = add(mult(down[u], 10), w);\n\t\tup[v] = add(up[u], mult(modpow(10, h[u]), w));\n\t\th[v] = h[u] + 1;\n\t\tfill(v, u, cent);\n\t\t//cout << v << ' ' << u << ' ' << up[v] << ' ' << up[u] << '\\n';\n\t}\n}\n\nll solve(int cent)\n{\n\tfor(int i = 0; i < clrlist.size(); i++)\n\t{\n\t\tup[clrlist[i]] = 0; down[clrlist[i]] = 0; h[clrlist[i]] = 0;\n\t}\n\tparts = 0;\n\tfill(cent, -1, cent); parts--;\n\tdppart[cent] = -1; \n\tmap<ll,ll> tot; //only count up\n\tvector<map<ll,ll> > vec; //only count up, but in specific subtree\n\tvec.resize(parts+1);\n\ttot[0]++;\n\tfor(int i = 0; i < clrlist.size(); i++)\n\t{\n\t\tint u = clrlist[i];\n\t\t//cout << u << ' ' << up[u] << ' ' << down[u] << '\\n';\n\t\tif(u == cent) continue;\n\t\ttot[up[u]]++;\n\t\tvec[dppart[u]][up[u]]++;\n\t}\n\tll ans = 0;\n\tfor(int i = 0; i < clrlist.size(); i++)\n\t{\n\t\tint u = clrlist[i];\n\t\tint ht = h[u];\n\t\tint pt = dppart[u];\n\t\tif(u == cent)\n\t\t{\n\t\t\tans += (tot[0] - 1); //exclude cent as the vertex\n\t\t}\n\t\telse\n\t\t{\n\t\t\tll val = ((-down[u])%MOD+MOD)%MOD;\n\t\t\tval = mult(val, inv(modpow(10, ht)));\n\t\t\tans += (tot[val] - vec[pt][val]);\n\t\t}\n\t}\n\treturn ans;\n}\n\nll compsolve(int u)\n{\n\tdfs(u, -1);\n\tint cent = centroid(u, -1);\n\tll ans = solve(cent);\n\t//cout << u << ' ' << cent << ' ' << ans << '\\n';\n\tvisited[cent] = true;\n\tfor(int i = 0; i < adj[cent].size(); i++)\n\t{\n\t\tint v = adj[cent][i].fi;\n\t\tif(!visited[v]) ans += compsolve(v);\n\t}\n\treturn ans;\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tcin >> n >> MOD;\n\tif(MOD == 1)\n\t{\n\t\tcout << ll(n)*ll(n - 1);\n\t\treturn 0;\n\t}\n\tSieve(100000); PHI = phi(MOD);\n\tfor(int i = 0; i < n - 1; i++) //tree is 0-indexed\n\t{\n\t\tint u, v, w; cin >> u >> v >> w;\n\t\tadj[u].pb(ii(v, w)); adj[v].pb(ii(u, w));\n\t}\n\tcout << compsolve(0) << '\\n';\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "715",
    "index": "D",
    "title": "Create a Maze",
    "statement": "ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of $n × m$ rooms, and the rooms are arranged in $n$ rows (numbered from the top to the bottom starting from $1$) and $m$ columns (numbered from the left to the right starting from $1$). The room in the $i$-th row and $j$-th column is denoted by $(i, j)$. A player starts in the room $(1, 1)$ and wants to reach the room $(n, m)$.\n\nEach room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting $(i, j)$ and $(i, j + 1)$ is locked, then we can't go from $(i, j)$ to $(i, j + 1)$. Also, one can only travel between the rooms downwards (from the room $(i, j)$ to the room $(i + 1, j)$) or rightwards (from the room $(i, j)$ to the room $(i, j + 1)$) provided the corresponding door is not locked.\n\n\\begin{center}\n{\\small This image represents a maze with some doors locked. The colored arrows denotes all the possible paths while a red cross denotes a locked door.}\n\\end{center}\n\nZS the Coder considers a maze to have difficulty $x$ if there is exactly $x$ ways of travelling from the room $(1, 1)$ to the room $(n, m)$. Two ways are considered different if they differ by the sequence of rooms visited while travelling.\n\nYour task is to create a maze such that its difficulty is exactly equal to $T$. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right?",
    "tutorial": "The solution to this problem is quite simple, if you get the idea. Thanks to danilka.pro for improving the solution to the current constraints which is much harder than my original proposal. Note that to calculate the difficulty of a given maze, we can just use dp. We write on each square (room) the number of ways to get from the starting square to it, and the number written on $(i, j)$ will be the sum of the numbers written on $(i - 1, j)$ and $(i, j - 1)$, and the edge between $(i - 1, j)$ and $(i, j)$ is blocked, we don't add the number written on $(i - 1, j)$ and similarly for $(i, j - 1)$. We'll call the rooms squares and the doors as edges. We'll call locking doors as edge deletions. First, we look at several attempts that do not work. Write $t$ in its binary representation. To solve the problem, we just need to know how to construct a maze with difficulty $2x$ and $x + 1$ from a given maze with difficulty $x$. The most direct way to get from $x$ to $2x$ is to increase both dimensions of the maze by $1$. Let's say the bottom right square of the grid was $(n, n)$ and increased to $(n + 1, n + 1)$. So, the number $x$ is written at $(n, n)$. Then, we can block off the edge to the left of $(n + 1, n)$ and above $(n, n + 1)$. This will make the numbers in these two squares equal to $x$, so the number in square $(n + 1, n + 1)$ would be $2x$, as desired. To create $x + 1$ from $x$, we can increase both dimensions by $1$, remove edges such that $(n + 1, n)$ contains $x$ while $(n, n + 1)$ contains $1$ (this requires deleting most of the edges joining the $n$-th column and $(n + 1)$-th column. Thus, the number in $(n, n)$ would be $x + 1$. This would've used way too many edge deletions and the size of the grid would be too large. This was the original proposal. There's another way to do it with binary representation. We construct a grid with difficulty $2x$ and $2x + 1$ from a grid with difficulty $x$. The key idea is to make use of surrounding $1$s and maintaining it with some walls so that $2x + 1$ can be easily constructed. This method is shown in the picture below. This method would've used around $120  \\times  120$ grid and $480$ edge deletions, which is too large to pass. Now, what follows is the AC solution. Since it's quite easy once you get the idea, I recommend you to try again after reading the hint. To read the full solution, click on the spoiler tag. Hint : Binary can't work since there can be up to $60$ binary digits for $t$ and our grid size can be at most $50$. In our binary solution we used a $2  \\times  2$ grid to multiply the number of ways by $2$. What about using other grid sizes instead? Our AC solution uses base $6$ instead of binary. Write $t$ in base $6$. Note that $t$ has at most $24$ digits in base $6$, so to add a new digit we can increase the dimensions by $2$ and the number of deleted edges can be up to $12$ per digit. We'll construct such a way. This method is explained in the picture below. The key is to first construct a grid which has $0$ in it, then find a way to get $6x + i$ for all $0  \\le  i  \\le  5$ from $x$ by maintaining a wall of $1$s around the squares. This method uses a $50  \\times  50(2 \\cdot 24 + 2 = 50)$ grid and at most $24 \\cdot 12 + 2 = 290$ edge deletions and will get AC. Of course, this might not be the only way to solve this problem. Can you come up with other ways of solving this or reducing the constraints even further? (Open Question) Time Complexity : $O(\\log t)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int INF = 1e9 + 7;\nconst int MOD = 1e9 + 7;\n\ntypedef pair<ii,ii> move;\n\nset<move> ans;\nint curx, cury;\n\nbool isvalid(move x)\n{\n\tif(x.fi.fi > 0 && x.se.fi > 0 && x.fi.se > 0 && x.se.se > 0 && x.fi.fi <= curx && x.fi.se <= cury && x.se.fi <= curx && x.se.se <= cury) return true;\n\treturn false;\n}\n\nvoid edge(int x1, int y1, int x2, int y2)\n{\n\tans.insert(mp(mp(x1, y1), mp(x2, y2)));\n}\n\nvoid add(int bit)\n{\n\tint x = curx;\n\tedge(x,x+2,x,x+3);\n\tedge(x+1,x+2,x+1,x+3);\n\tedge(x+2,x,x+3,x);\n\tedge(x+2,x+1,x+3,x+1);\n\tedge(x-2,x+3,x-1,x+3);\n\tedge(x,x+4,x+1,x+4);\n\tedge(x+3,x-2,x+3,x-1);\n\tedge(x+4,x,x+4,x+1);\n\tedge(x-1,x+1,x,x+1);\n\tif(bit%3==0) edge(x-1,x+2,x,x+2);\n\tif(bit%3!=2) edge(x+2,x-1,x+2,x);\n\tif(bit<3) edge(x+1,x-1,x+1,x);\n\tcurx += 2; cury += 2;\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tll t; cin >> t;\n\tvector<int> digits;\n\twhile(t)\n\t{\n\t\tdigits.pb(t%6);\n\t\tt/=6;\n\t}\n\treverse(digits.begin(), digits.end());\n\tedge(1, 2, 2, 2);\n\tedge(2, 1, 2, 2);\n\tcurx = 2; cury = 2;\n\tfor(int i = 0; i < digits.size(); i++)\n\t{\n\t\tadd(digits[i]);\n\t}\n\tcout << curx << ' ' << cury << '\\n';\n\tvector<move> clr;\n\tfor(set<move>::iterator it = ans.begin(); it != ans.end(); it++)\n\t{\n\t\tif(!isvalid(*it))\n\t\t{\n\t\t\tclr.pb(*it);\n\t\t}\n\t}\n\tfor(int i = 0; i < clr.size(); i++)\n\t{\n\t\tans.erase(clr[i]);\n\t}\n\tcout << ans.size() << '\\n';\n\tfor(set<move>::iterator it = ans.begin(); it != ans.end(); it++)\n\t{\n\t\tmove tmp = (*it);\n\t\tcout << tmp.fi.fi << ' ' << tmp.fi.se << ' ' << tmp.se.fi << ' ' << tmp.se.se << '\\n';\n\t}\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3100
  },
  {
    "contest_id": "715",
    "index": "E",
    "title": "Complete the Permutations",
    "statement": "ZS the Coder is given two permutations $p$ and $q$ of ${1, 2, ..., n}$, but some of their elements are replaced with $0$. The distance between two permutations $p$ and $q$ is defined as the minimum number of moves required to turn $p$ into $q$. A move consists of swapping exactly $2$ elements of $p$.\n\nZS the Coder wants to determine the number of ways to replace the zeros with positive integers from the set ${1, 2, ..., n}$ such that $p$ and $q$ are permutations of ${1, 2, ..., n}$ and the distance between $p$ and $q$ is exactly $k$.\n\nZS the Coder wants to find the answer for all $0 ≤ k ≤ n - 1$. Can you help him?",
    "tutorial": "We'll slowly unwind the problem and reduce it to something easier to count. First, we need to determine a way to tell when the distance between $p$ and $q$ is exactly $k$. This is a classic problem but I'll include it here for completeness. Let $f$ denote the inverse permutation of $q$. So, the minimum number of swaps to transform $p$ into $q$ is the minimum number of swaps to transform $p_{fi}$ into the identity permutation. Construct the graph where the edges are $i\\rightarrow p_{f},$ for all $1  \\le  i  \\le  n$. Now, note that the graph is equivalent to $q_{i}\\rightarrow p_{i}$ and is composed of disjoint cycles after $q_{i}$ and $p_{i}$ are filled completely. Note that the direction of the edges doesn't matter so we consider the edges to be $p_{i}\\to q_{i}$ for all $1  \\le  i  \\le  n$. Note that if the number of cycles of the graph is $t$, then the minimum number of swaps needed to transform $p$ into $q$ would be $n - t$. (Each swap can break one cycle into two) This means we just need to find the number of ways to fill in the empty spaces such that the number of cycles is exactly $i$ for all $1  \\le  i  \\le  n$. Now, some of the values $p_{i}$ and $q_{i}$ are known. The edges can be classified into four types : A-type : The edges of the form $x\\to{\\mathfrak{Y}}$, i.e. $p_{i}$ is known, $q_{i}$ isn't. B-type : The edges of the form $\\gamma\\to x$, i.e. $q_{i}$ is known, $p_{i}$ isn't. C-type : The edges of the form $x\\to y$, i.e. both $p_{i}$ and $q_{i}$ are known. D-type : The edges of the form $\\gamma\\rightarrow\\gamma$, i.e. both $p_{i}$ and $q_{i}$ are unknown. Now, the problem reduces to finding the number of ways to assign values to the question marks such that the number of cycles of the graph is exactly $i$ for all $1  \\le  i  \\le  n$. First, we'll simplify the graph slightly. While there exists a number $x$ appears twice (clearly it can't appear more than twice) among the edges, we will combine the edges with $x$ together to simplify the graph. If there's an edge $x\\to x$, then we increment the total number of cycles by $1$ and remove this edge from the graph. If there is an edge $a\\to x$ and $x\\to b$, where $a$ and $b$ might be some given numbers or question marks, then we can merge them together to form the edge $a\\to b$. Clearly, these are the only cases for $x$ to appear twice. Hence, after doing all the reductions, we're reduced to edges where each known number appears at most once, i.e. all the known numbers are distinct. We'll do this step in $O(n^{2})$. For each number $x$, store the position $i$ such that $p_{i} = x$ and also the position $j$ such that $q_{j} = x$, if it has already been given and $- 1$ otherwise. So, we need to remove a number when the $i$ and $j$ stored are both positive. We iterate through the numbers from $1$ to $n$. If we need to remove a number, we go to the two positions where it occur and replace the two edges with the new merged one. Then, recompute the positions for all numbers (takes $O(n)$ time). So, for each number, we used $O(n)$ time. (to remove naively and update positions) Thus, the whole complexity for this part is $O(n^{2})$. (It is possible to do it in $O(n)$ with a simple dfs as well. Basically almost any correct way of doing this part that is at most $O(n^{3})$ works, since the constraints for $n$ is low) Now, suppose there are $m$ edges left and $p$ known numbers remain. Note that in the end when we form the graph we might join edges of the form $a\\rightarrow?$ and $\\gamma\\rightarrow b$ (where $a$ and $b$ are either fixed numbers or question marks) together. So, the choice for the $?$ can be any of the $m - p$ remaining unused numbers. Note that there will be always $m - p$ such pairs so we need to multiply our answer by $(m - p)!$ in the end. Also, note that the $?$ are distinguishable, and order is important when filling in the blanks. So, we can actually reduce the problem to the following : Given integers $a, b, c, d$ denoting the number of A-type, B-type, C-type, D-type edges respectively. Find the number of ways to create $k$ cycles using them, for all $1  \\le  k  \\le  n$. Note that the answer is only dependent on the values of $a, b, c, d$ as the numbers are all distinct after the reduction. First, we'll look at how to solve the problem for $k = 1$. We need to fit all the edges in a single cycle. First, we investigate what happens when $d = 0$. Note that we cannot have a B-type and C-type edge before an A-type or C-type edge, since all numbers are distinct so these edges can't be joined together. Similarly, an A or C-type edge cannot be directly after a B or C-type edge. Thus, with these restrictions, it is easy to see that the cycle must contain either all A-type edges or B-type edges. So, the answer can be easily calculated. It is also important to note that if we ignore the cyclic property then a contiguous string of edges without D must be of the form AA...BB.. or AA...CBB..., where there is only one C, and zero or more As and Bs. Now, if $d  \\ge  1$, we can fix one of the D-type edges as the front of the cycle. This helps a lot because now we can ignore the cyclic properties. (we can place anything at the end of the cycle because D-type edges can connect with any type of edges) So, we just need to find the number of ways to make a length $n - 1$ string with $a$ As, $b$ Bs, $c$ Cs and $d - 1$ Ds. In fact, we can ignore the fact that the A-type edges, B-type edges, C-type edges and D-type edges are distinguishable and after that multiply the answer by $a!b!c!(d - 1)!$. We can easily find the number of valid strings we can make. First, place all the Ds. Now, we're trying to insert the As, Bs and Cs into the $d$ empty spaces between, after and before the Ds. The key is that by our observation above, we only care about how many As, Bs and Cs we insert in each space since after that the way to put that in is uniquely determined. So, to place the As and Bs, we can use the balls in urns formula to find that the number of ways to place the As is $\\textstyle{\\binom{a+d-1}{d-1}}$ and the number of ways to place the Bs is $\\textstyle{\\binom{b+d-1}{d-1}}$. The number of ways to place the Cs is $\\textstyle{\\binom{d}{x}}$, since we choose where the Cs should go. Thus, it turns out that we can find the answer in $O(1)$ (with precomputing binomial coefficients and factorials) when $k = 1$. We'll use this to find the answer for all $k$. In the general case, there might be cycles that consists entirely of As and entirely of Bs, and those that contains at least one D. We call them the A-cycle, B-cycle and D-cycles respectively. Now, we precompute $f(n, k)$, the number of ways to form $k$ cycles using $n$ distinguishable As. This can be done with a simple dp in $O(n^{3})$. We iterate through the number of As we're using for the first cycle. Then, suppose we use $m$ As. The number of ways to choose which of the $m$ As to use is $\\binom{n}{m}$ and we can permute them in $(m - 1)!$ ways inside the cycle. (not $m!$ because we have to account for all the cyclic permutations) Also, after summing this for all $m$, we have to divide the answer by $k$, to account for overcounting the candidates for the first cycle (the order of the $k$ cycles are not important) Thus, $f(n, k)$ can be computed in $O(n^{3})$. First, we see how to compute the answer for a single $k$. Fix $x, y, e, f$, the number of A-cycles, B-cycles, number of As in total among the A-cycles and number of Bs in total among the B-cycles. Then, since $k$ is fixed, we know that the number of D-cycles is $k - x - y$. Now, we can find the answer in $O(1)$. First, we can use the values of $f(e, x), f(f, y), f(d, k - x - y)$ to determine the number of ways to place the Ds, and the As, Bs that are in the A-cycles and B-cycles. Then, to place the remaining As, Bs and Cs, we can use the same method as we did for $k = 1$ in $O(1)$, since the number of spaces to place them is still the same. (You can think of it as each D leaves an empty space to place As, Bs and Cs to the right of it) After that, we multiply the answer by $\\left(a_{e}\\right)\\cdot\\left({b_{f}}\\right)$ to account for the choice of the set of As and Bs used in the A-only and B-only cycles. Thus, the complexity of this method is $O(n^{4})$ for each $k$ and $O(n^{5})$ in total, which is clearly too slow. We can improve this by iterating through all $x + y, e, f$ instead. So, for this to work we need to precompute $f(e, 0)f(f, x + y) + f(e, 1)f(f, x + y - 1) + ... + f(e, x + y)f(f, 0)$, which we can write as $g(x + y, e, f)$. Naively doing this precomputation gives $O(n^{4})$. Then, we can calculate the answer by iterating through all $x + y, e, f$ and thus getting $O(n^{3})$ per query and $O(n^{4})$ for all $k$. This is still too slow to pass $n = 250$. We should take a closer look of what we're actually calculating. Note that for a fixed pair $e, f$, the values of $g(x + y, e, f)$ can be calculated for all possible $x + y$ in $O(n\\log n)$ or $O(n^{1.58})$ by using Number Theoretic Transform or Karatsuba's Algorithm respectively. (note that the modulus has been chosen for NFT to work) This is because if we fix $e, f$, then we're precisely finding the coefficients of the polynomial $(f(e, 0)x^{0} + f(e, 1)x^{1} + ... + f(e, n)x^{n})(f(f, 0)x^{0} + f(f, 1)x^{1} + ... + f(f, n)x^{n})$, so this can be handled with NFT/Karatsuba. Thus, the precomputation of $g(x + y, e, f)$ can be done in $O(n^{3}\\log{n})$ or $O(n^{3.58})$. Next, suppose we fixed $e$ and $f$. We will calculate the answer for all possible $k$ in $O(n\\log n)$ similar to how we calculated $g(x + y, e, f)$. This time, we're multiplying the following two polynomials : $f(d, 0)x^{0} + f(d, 1)x^{1} + ... + f(d, n)x^{n}$ and $g(0, e, f)x^{0} + g(1, e, f)x^{1} + ... + g(n, e, f)x^{n}$. Again, we can calculate this using any fast multiplication method, so the entire solution takes $O(n^{3}\\log{n})$ or $O(n^{3.58})$, depending on which algorithm is used to multiply polynomials. Note that if you're using NFT/FFT, there is a small trick that can save some time. When we precompute the values of $g(x + y, e, f)$, we don't need to do inverse FFT on the result and leave it in the FFTed form. After that, when we want to find the convolution of $f(d, i)$ and $g(i, e, f)$, we just need to apply FFT to the first polynomial and multiply them. This reduces the number of FFTs and it reduced my solution runtime by half. Time Complexity : $O(n^{3}\\log{n})$ or $O(n^{3.58})$, depending on whether NFT or Karatsuba is used.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int N = 251;\nconst int MOD = 998244353;\nll inv2;\nll prt;\nll iprt;\n\nll dpncr[N][N];\nll fact[N];\nll inverse[N];\nll g[N][N];\nll sumg[N][N][N];\n\nvector<ii> perm;\nint A, B, C, D;\n\nll modpow(ll a, ll b)\n{\n\tll r = 1;\n\twhile(b)\n\t{\n\t\tif(b&1) r = (r*a)%MOD;\n\t\ta = (a*a)%MOD;\n\t\tb>>=1;\n\t}\n\treturn r;\n}\n\nll inv(ll a)\n{\n\treturn modpow(a, MOD - 2);\n}\n\nll choose(int n, int m)\n{\n\tif(m < 0) return 0;\n\tif(n < m) return 0;\n\tif(m == 0) return 1;\n\tif(n == m) return 1;\n\tif(dpncr[n][m] != -1) return dpncr[n][m];\n\tdpncr[n][m] = choose(n - 1, m - 1) + choose(n - 1, m);\n\tdpncr[n][m] += MOD; dpncr[n][m] %= MOD;\n\treturn dpncr[n][m];\n}\n\nvoid computefact()\n{\n\tfact[0] = 1;\n\tfor(ll i = 1; i < N; i++)\n\t{\n\t\tfact[i] = (fact[i - 1]*i)%MOD;\n\t}\n\tfor(ll i = 1; i < N; i++)\n\t{\n\t\tinverse[i] = modpow(i, MOD - 2);\n\t}\n}\n\nvoid print(vector<ii>& vec)\n{\n\tfor(int i = 0; i < vec.size(); i++)\n\t{\n\t\tcout << vec[i].fi << ' ' << vec[i].se << endl;\n\t}\n\tcout << \"------------------------------------------------\" << endl;\n}\n\nvoid printans(vector<ll>& vec)\n{\n\tfor(int i = 0; i < vec.size(); i++)\n\t{\n\t\tcout << vec[i] << ' ';\n\t}\n\tcout << endl;\n}\n\nvoid printansi(vector<int>& vec)\n{\n\tfor(int i = 0; i < vec.size(); i++)\n\t{\n\t\tcout << vec[i] << ' ';\n\t}\n\tcout << endl;\n}\n\nvoid calcpos(vector<ii>& pos)\n{\n\tpos.resize(perm.size());\n\tfor(int i = 0; i < perm.size(); i++)\n\t{\n\t\tpos[i] = ii(-1, -1);\n\t}\n\tfor(int i = 1; i < perm.size(); i++)\n\t{\n\t\tif(perm[i].fi > 0)\n\t\t{\n\t\t\tpos[perm[i].fi].fi = i;\n\t\t}\n\t\tif(perm[i].se > 0)\n\t\t{\n\t\t\tpos[perm[i].se].se = i;\n\t\t}\n\t}\n}\n\nint reduce()\n{\n\tint n = perm.size() - 1;\n\tvector<ii> pos;\n\tint cnt = 0;\n\tfor(int i = 1; i <= n; i++) //Do a reduction\n\t{\n\t\tcalcpos(pos);\n\t\t//print(pos);\n\t\tif(pos[i].fi > 0 && pos[i].se > 0)\n\t\t{\n\t\t\tif(pos[i].fi == pos[i].se) \n\t\t\t{\n\t\t\t\tcnt++;\n\t\t\t\tii tmp1 = perm[pos[i].fi];\n\t\t\t\tfor(vector<ii>::iterator it = perm.begin(); it != perm.end(); it++)\n\t\t\t\t{\n\t\t\t\t\tif((*it) == tmp1)\n\t\t\t\t\t{\n\t\t\t\t\t\tperm.erase(it); break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint p1 = pos[i].se; int l = perm[p1].fi; ii tmp1 = perm[p1];\n\t\t\tint p2 = pos[i].fi; int r = perm[p2].se; ii tmp2 = perm[p2];\n\t\t\tfor(vector<ii>::iterator it = perm.begin(); it != perm.end(); it++)\n\t\t\t{\n\t\t\t\tif((*it) == tmp1)\n\t\t\t\t{\n\t\t\t\t\tperm.erase(it); break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(vector<ii>::iterator it = perm.begin(); it != perm.end(); it++)\n\t\t\t{\n\t\t\t\tif((*it) == tmp2)\n\t\t\t\t{\n\t\t\t\t\tperm.erase(it); break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tperm.pb(ii(l, r));\n\t\t}\n\t}\n\t//count A, B, C, D\n\tfor(int i = 1; i < perm.size(); i++)\n\t{\n\t\tif(perm[i].fi > 0 && perm[i].se > 0)\n\t\t{\n\t\t\tassert(perm[i].fi != perm[i].se);\n\t\t\tC++;\n\t\t}\n\t\telse if(perm[i].fi > 0)\n\t\t{\n\t\t\tA++;\n\t\t}\n\t\telse if(perm[i].se > 0)\n\t\t{\n\t\t\tB++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tD++;\n\t\t}\n\t}\n\treturn cnt;\n}\n\nll mult(ll a, ll b)\n{\n\tll r = (a*b)%MOD;\n\tr = (r+MOD)%MOD;\n\treturn r;\n}\n\nll add(ll a, ll b)\n{\n\tll r = ((a+b)%MOD+MOD)%MOD;\n\treturn r;\n}\n\nll F(ll a, ll b, ll c, ll d)\n{\n\tll ans = 1;\n\tif(d == 0)\n\t{\n\t\tif(a == 0 && b == 0 && c == 0) return 1;\n\t\telse return 0;\n\t}\n\tans = mult(ans, fact[a]);\n\tans = mult(ans, fact[b]);\n\tans = mult(ans, fact[c]);\n\tans = mult(ans, choose(a+d-1, d-1));\n\tans = mult(ans, choose(b+d-1, d-1));\n\tans = mult(ans, choose(d, C));\n\treturn ans;\n}\n\nll buffer[20001], bufferpos, siz = 1024;\nconst int LG = 4;\n\nvoid multiply(int size, ll a[], ll b[], ll r[])\n{\n\tif(size <= (1<<LG))\n\t{\n\t\tfor(int i = 0; i < size*2; i++) r[i] = 0;\n\t\tfor(int i = 0; i < size; i++)\n\t\t{\n\t\t\tif(a[i])\n\t\t\t{\n\t\t\t\tfor(int j = 0; j < size; j++)\n\t\t\t\t{\n\t\t\t\t\tr[i+j] += a[i]*b[j];\n\t\t\t\t\tr[i+j] %= MOD;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(int i = 0; i < size*2; i++)\n\t\t{\n\t\t\tr[i] %= MOD;\n\t\t}\n\t\treturn ;\n\t}\n\tint s = size/2;\n\tmultiply(s, a, b, r);\n\tmultiply(s, a+s, b+s, r+size);\n\tll *a2 = buffer+bufferpos; bufferpos += s;\n\tll *b2 = buffer+bufferpos; bufferpos += s;\n\tll *r2 = buffer+bufferpos; bufferpos += size;\n\tfor(int i = 0; i < s; i++)\n\t{\n\t\ta2[i] = a[i] + a[i+s];\n\t\tif(a2[i]>=MOD) a2[i]-=MOD;\n\t}\n\tfor(int i = 0; i < s; i++)\n\t{\n\t\tb2[i] = b[i] + b[i+s];\n\t\tif(b2[i]>=MOD) b2[i]-=MOD;\n\t}\n\tmultiply(s, a2, b2, r2);\n\tfor(int i = 0; i < size; i++)\n\t{\n\t\tr2[i] -= (r[i] + r[i+size]);\n\t}\n\tfor(int i = 0; i < size; i++)\n\t{\n\t\tr[i+s] += r2[i];\n\t\tr[i+s]%=MOD;\n\t\tif(r[i+s]<0) r[i+s]+=MOD;\n\t}\n\tbufferpos -= (s+s+size);\n}\nll gi[N+5]; ll gj[N+5];\n\nvoid computeg(int n)\n{\n\tg[0][0] = 1;\n\tg[1][1] = 1;\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tfor(int j = 1; j <= i; j++)\n\t\t{\n\t\t\tfor(int k = 1; k <= i; k++)\n\t\t\t{\n\t\t\t\tg[i][j] = add(g[i][j], mult(g[i-k][j-1], mult(choose(i, k), fact[k-1])));\n\t\t\t}\n\t\t\tg[i][j] = mult(g[i][j], inverse[j]);\n\t\t}\n\t}\n\tfor(int i = 0; i <= A; i++)\n\t{\n\t\tfor(int j = 0; j <= B; j++)\n\t\t{\n\t\t\tsiz = 512;\n\t\t\twhile(siz/2 >= n+1) siz>>=1;\n\t\t\tfor(int k = 0; k < siz; k++)\n\t\t\t{\n\t\t\t\tif(k <= n)\n\t\t\t\t{\n\t\t\t\t\tgi[k] = g[i][k];\n\t\t\t\t\tgj[k] = g[j][k];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tgi[k] = gj[k] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tll *res = buffer+bufferpos;\n\t\t\tbufferpos+=2*siz;\n\t\t\tmultiply(siz,gi,gj,res);\n\t\t\tfor(int k = 0; k <= n; k++)\n\t\t\t{\n\t\t\t\tsumg[i][j][k] = res[k];\n\t\t\t}\n\t\t\tbufferpos-=2*siz;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tint n; cin >> n; perm.resize(n+1);\n\t\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tcin >> perm[i].fi;\n\t}\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tcin >> perm[i].se;\n\t}\n\t\n\tA = 0; B = 0; C = 0; D = 0;\n\tmemset(dpncr, -1, sizeof(dpncr));\n\tmemset(sumg, 0, sizeof(sumg));\n\tmemset(g, 0, sizeof(g));\n\tmemset(fact, 0, sizeof(fact));\n\tmemset(inverse, 0, sizeof(inverse));\n\tint cycles = reduce();\n\tcomputefact(); computeg(n);\n\tvector<ll> ans; ans.assign(n+1, 0);\n\t\n\tif(D - C < 0)\n\t{\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tcout << ans[i] << ' ';\n\t\t}\n\t\tcout << endl;\n\t\treturn 0;\n\t}\n\t\n\tfor(int i = 0; i <= A; i++)\n\t{\n\t\tfor(int j = 0; j <= B; j++)\n\t\t{\n\t\t\tll coef = 1;\n\t\t\tcoef = mult(coef, F(A-i,B-j,C,D));\n\t\t\tif(A > 0) coef = mult(coef, choose(A, i));\n\t\t\tif(B > 0) coef = mult(coef, choose(B, j));\n\t\t\tsiz = 512;\n\t\t\twhile(siz/2 >= n-cycles+1) siz>>=1;\n\t\t\tfor(int k = 0; k < siz; k++)\n\t\t\t{\n\t\t\t\tif(k <= n-cycles)\n\t\t\t\t{\n\t\t\t\t\tgi[k] = g[D][k];\n\t\t\t\t\tgj[k] = sumg[i][j][k];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tgi[k] = gj[k] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tll *res = buffer+bufferpos;\n\t\t\tbufferpos+=2*siz;\n\t\t\tmultiply(siz,gi,gj,res);\n\t\t\tfor(int k = 0; k <= n - cycles; k++)\n\t\t\t{\n\t\t\t\tint moves = n - (k + cycles);\n\t\t\t\tans[moves] = add(ans[moves], mult(res[k], coef));\n\t\t\t}\n\t\t\tbufferpos-=2*siz;\n\t\t}\n\t}\n\t\n\tfor(int i = 0; i < ans.size(); i++)\n\t{\n\t\tans[i] = mult(ans[i], fact[D-C]);\n\t}\n\t\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tcout << ans[i] << ' ';\n\t}\n\tcout << endl;\n}",
    "tags": [
      "combinatorics",
      "fft",
      "graphs",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "716",
    "index": "A",
    "title": "Crazy Computer",
    "statement": "ZS the Coder is coding on a crazy computer. If you don't type in a word for a $c$ consecutive seconds, everything you typed disappear!\n\nMore formally, if you typed a word at second $a$ and then the next word at second $b$, then if $b - a ≤ c$, just the new word is appended to other words on the screen. If $b - a > c$, then everything on the screen disappears and after that the word you have typed appears on the screen.\n\nFor example, if $c = 5$ and you typed words at seconds $1, 3, 8, 14, 19, 20$ then at the second $8$ there will be $3$ words on the screen. After that, everything disappears at the second $13$ because nothing was typed. At the seconds $14$ and $19$ another two words are typed, and finally, at the second $20$, one more word is typed, and a total of $3$ words remain on the screen.\n\nYou're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.",
    "tutorial": "This is a straightforward implementation problem. Iterate through the times in order, keeping track of when is the last time a word is typed, keeping a counter for the number of words appearing on the screen. Increment the counter by $1$ whenever you process a new time. Whenever the difference between the time for two consecutive words is greater than $c$, reset the counter to $0$. After that, increment it by $1$. Time Complexity : $O(n)$, since the times are already sorted.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int N = 1e5 + 3;\nll a[N];\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tint n, c; cin >> n >> c;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tcin >> a[i];\n\t}\n\t//sort(a, a + n);\n\tint cnt = 0;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(i == 0) cnt++;\n\t\telse\n\t\t{\n\t\t\tif(a[i] - a[i - 1] <= c) cnt++;\n\t\t\telse cnt = 1;\n\t\t}\n\t}\n\tcout << cnt;\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "716",
    "index": "B",
    "title": "Complete the Word",
    "statement": "ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a \\textbf{substring} (contiguous segment of letters) of it of length $26$ where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than $26$, no such substring exists and thus it is not nice.\n\nNow, ZS the Coder tells you a word, where some of its letters are missing as he forgot them. He wants to determine if it is possible to fill in the missing letters so that the resulting word is nice. If it is possible, he needs you to find an example of such a word as well. Can you help him?",
    "tutorial": "Firstly, if the length of the string is less than $26$, output $- 1$ immediately. We want to make a substring of length $26$ have all the letters of the alphabet. Thus, the simplest way is to iterate through all substrings of length $26$ (there are $O(n)$ such substrings), then for each substring count the number of occurrences of each alphabet, ignoring the question marks. After that, if there exist a letter that occurs twice or more, this substring cannot contain all letters of the alphabet, and we process the next substring. Otherwise, we can fill in the question marks with the letters that have not appeared in the substring and obtain a substring of length $26$ which contains all letters of the alphabet. After iterating through all substrings, either there is no solution, or we already created a nice substring. If the former case appears, output $- 1$. Otherwise, fill in the remaining question marks with random letters and output the string. Note that one can optimize the solution above by noting that we don't need to iterate through all $26$ letters of each substring we consider, but we can iterate through the substrings from left to right and when we move to the next substring, remove the front letter of the current substring and add the last letter of the next substring. This optimization is not required to pass. We can still optimize it further and make the complexity purely $O(|s|)$. We use the same trick as above, when we move to the next substring, we remove the previous letter and add the new letter. We store a frequency array counting how many times each letter appear in the current substring. Additionally, store a counter which we will use to detect whether the current substring can contain all the letters of the alphabet in $O(1)$. When a letter first appear in the frequency array, increment the counter by $1$. If a letter disappears (is removed) in the frequency array, decrement the counter by $1$. When we add a new question mark, increment the counter by $1$. When we remove a question mark, decrement the counter by $1$. To check whether a substring can work, we just have to check whether the counter is equal to $26$. This solution works in $O(|s|)$. Time Complexity : $O(|s| \\cdot 26^{2})$, $O(|s| \\cdot 26)$ or $O(|s|)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int N = 50000;\nint cnt[27];\nstring s; int n;\nint counter;\n\nbool valid()\n{\n    //cout << counter << endl;\n\treturn (counter == 26);\n}\n\nvoid fillall()\n{\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(s[i] == '?') s[i] = 'A';\n\t}\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tcin >> s;\n\tn = s.length();\n\tif(n < 26) {cout << -1; return 0;}\n\tcounter = 0;\n\tfor(int i = 0; i < 26; i++)\n\t{\n\t\tif(s[i] == '?')\n\t\t{\n\t\t\tcounter++; continue;\n\t\t}\n\t\tcnt[s[i]-'A']++;\n\t\tif(cnt[s[i]-'A'] == 1) counter++;\n\t}\n\tif(valid())\n\t{\n\t\tint cur = 0;\n\t\twhile(cnt[cur]>0) cur++;\n\t\tfor(int i = 0; i < 26; i++)\n\t\t{\n\t\t\tif(s[i] == '?')\n\t\t\t{\n\t\t\t\ts[i] = cur + 'A';\n\t\t\t\tcur++;\n\t\t\t\twhile(cnt[cur]>0) cur++;\n\t\t\t}\n\t\t}\n\t\tfillall();\n\t\tcout << s;\n\t\treturn 0;\n\t}\n\tfor(int i = 26; i < n; i++)\n\t{\n\t\tif(s[i] != '?') {cnt[s[i]-'A']++; if(cnt[s[i]-'A']==1) counter++;}\n\t\tif(s[i-26] != '?') {cnt[s[i-26]-'A']--; if(cnt[s[i-26]-'A']==0) counter--;}\n\t\tif(s[i-26] == '?') counter--;\n\t\tif(s[i] == '?') counter++;\n\t\tif(valid())\n\t\t{\n\t\t\tint cur = 0;\n\t\t\twhile(cnt[cur]>0) cur++;\n\t\t\tfor(int j = i - 25; j <= i; j++)\n\t\t\t{\n\t\t\t\tif(s[j] == '?')\n\t\t\t\t{\n\t\t\t\t\ts[j] = cur + 'A';\n\t\t\t\t\tcur++;\n\t\t\t\t\twhile(cnt[cur]>0) cur++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfillall();\n\t\t\tcout << s;\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout << -1;\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "718",
    "index": "A",
    "title": "Efim and Strange Grade",
    "statement": "Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer).\n\nThere are $t$ seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than $t$ seconds. Note, that he can choose to not use all $t$ seconds. Moreover, he can even choose to not round the grade at all.\n\nIn this problem, classic rounding rules are used: while rounding number to the $n$-th digit one has to take a look at the digit $n + 1$. If it is less than $5$ than the $n$-th digit remain unchanged while all subsequent digits are replaced with $0$. Otherwise, if the $n + 1$ digit is greater or equal to $5$, the digit at the position $n$ is increased by $1$ (this might also change some other digits, if this one was equal to $9$) and all subsequent digits are replaced with $0$. At the end, all trailing zeroes are thrown away.\n\nFor example, if the number $1.14$ is rounded to the first decimal place, the result is $1.1$, while if we round $1.5$ to the nearest integer, the result is $2$. Rounding number $1.299996121$ in the fifth decimal place will result in number $1.3$.",
    "tutorial": "One can notice that the closer to the decimal point we round our grade the bigger grade we get. Based on this observation we can easily solve the problem with dynamic programming. Let $dp_{i}$ be the minimum time required to get a carry to the ($i - 1$)-th position. Let's denote our grade as $a$, and let $a_{i}$ be the ($i$)-th digit of the $a$. There are three cases: If $a_{i}  \\ge  5$, then $dp_{i} = 1$. If $a_{i} < 4$, then $dp_{i} = inf$ (it means, that we cann't get a carry to the ($i - 1$)-th position). If $a_{i} = 4$, then $dp_{i} = 1 + dp_{i + 1}$. After computing $dp$, we need to find the minimum $pos$ such that $dp_{pos}  \\le  t$. So, after that we know the position where we should round our grade. Now we only need to carefully add 1 to the number formed by the prefix that contains $pos$ elements of the original grade. Time Complexity: $\\mathrm{O}(n)$.",
    "tags": [
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "718",
    "index": "C",
    "title": "Sasha and Array",
    "statement": "Sasha has an array of integers $a_{1}, a_{2}, ..., a_{n}$. You have to perform $m$ queries. There might be queries of two types:\n\n- 1 l r x — increase all integers on the segment from $l$ to $r$ by values $x$;\n- 2 l r — find $\\textstyle\\sum_{i=l}^{r}f(a_{i})$, where $f(x)$ is the $x$-th Fibonacci number. As this number may be large, you only have to find it modulo $10^{9} + 7$.\n\nIn this problem we define Fibonacci numbers as follows: $f(1) = 1$, $f(2) = 1$, $f(x) = f(x - 1) + f(x - 2)$ for all $x > 2$.\n\nSasha is a very talented boy and he managed to perform all queries in five seconds. Will you be able to write the program that performs as well as Sasha?",
    "tutorial": "Let's denote Let's recall how we can quickly find $n$-th Fibonacci number. To do this we need to find a matrix product $(1~1)\\times A^{n-2}$. In order to solve our problem let's create the following segments tree: in each leaf which corresponds to the element $i$ we will store a vector $\\left(f_{a_{i}}\\ \\ f_{a_{i}+1}\\right)$ and in all other nodes we will store the sums of all the vectors that correspond to a given segment. Now, to perform the first request we should multiply all the vectors in a segment $[l..r]$ by $A^{x}$ and to get an answer to the second request we have to find a sum in a segment $[l..r]$. Time Complexity: $O(m\\log n+(n+m)\\log x)$.",
    "tags": [
      "data structures",
      "math",
      "matrices"
    ],
    "rating": 2300
  },
  {
    "contest_id": "718",
    "index": "D",
    "title": "Andrew and Chemistry",
    "statement": "During the chemistry lesson Andrew learned that the saturated hydrocarbons (alkanes) enter into radical chlorination reaction. Andrew is a very curious boy, so he wondered how many different products of the reaction may be forms for a given alkane. He managed to solve the task for small molecules, but for large ones he faced some difficulties and asks you to help.\n\nFormally, you are given a tree consisting of $n$ vertices, such that the degree of each vertex doesn't exceed $4$. You have to count the number of distinct non-isomorphic trees that can be obtained by adding to this tree one new vertex and one new edge, such that the graph is still the tree and the degree of each vertex doesn't exceed $4$.\n\nTwo trees are isomorphic if there exists a bijection $f(v)$ such that vertices $u$ and $v$ are connected by an edge if and only if vertices $f(v)$ and $f(u)$ are connected by an edge.",
    "tutorial": "Let's first figure out how we can solve the problem in $O(n^{2}\\log{n})$ time. Let's pick a vertex we're going to add an edge to and make this vertex the root of the tree. For each vertex $v_{i}$ we're going to assign a label $a[v_{i}]$ (some number). The way we assign labels is the following: if the two given vertices have the same subtrees they're going to get the same labels, but if the subtrees are different then the labels for these vertices are going to be different as well. We can do such labeling in a following way: let's create a map<vector<int>, int> m (the maximum degree for a vertex is 4, but let's assume that the length of the vector is always equal to 4). Let m[{x, y, z, w}] be a label for a vertex which has children with the labels $x$, $y$, $z$, $w$. Let's note that the vector {$x$, $y$, $z$, $w$} should be sorted to avoid duplications, also if the number of children is less than 4 then we'll store $- 1$'s for the missing children (to make the length of a vector always equal to 4). Let's understand how we can compute the value for the label for the vertex $v$. Let's recursively compute the labels for its children: $v_{1}$, $v_{2}$, $v_{3}$, $v_{4}$. Now, if m.count({a[v1], a[v2], a[v3], a[v4]}) then we use the corresponding value. Otherwise, we use the first unused number: m[{a[v1], a[v2], a[v3], a[v4]}]=cnt++. Now, let's pick another vertex which we're going to add an edge to. Again, let's make it the root of the tree and set the labels without zeroing out our counter $cnt$. Now, let's do the same operation for all the other possible roots (vertices, $n$ times). Now, one can see that if the two roots have the same labels, then the trees which can be obtained by adding an edge to these roots, are exactly the same. Thus, we only need to count the amount of roots with different labels. Also, we should keep in mind that if a degree for a vertex is already 4 it's impossible to add an edge to it. The solution described above has the time complexity $O(n^{2}\\log{n})$, because we consider $n$ rooted trees and in the each tree we iterate through all the vertices ($n$), but each label update takes $O(\\log n)$. Let's speed up this solution to $O(n\\log n)$. Let $b$ be an array where $b[v_{i}]$ is a label in a vertex $v_{i}$ if we make this vertex the root of the tree. Then the answer to the problem is the number of different numbers in the array $b$. Let's root the tree in a vertex $root$ and compute the values $a[v_{i}]$. Then $b[root] = a[root]$ and all the other values for $b[v_{i}]$ we can get by pushing the information from the top of the tree to the bottom. Time complexity: $\\mathrm{O}(n\\log n)$.",
    "tags": [
      "dp",
      "hashing",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "718",
    "index": "E",
    "title": "Matvey's Birthday",
    "statement": "Today is Matvey's birthday. He never knows what to ask as a present so friends gave him a string $s$ of length $n$. This string consists of only first eight English letters: 'a', 'b', $...$, 'h'.\n\nFirst question that comes to mind is: who might ever need some string? Matvey is a special boy so he instantly found what to do with this string. He used it to build an undirected graph where vertices correspond to position in the string and there is an edge between distinct positions $a$ and $b$ ($1 ≤ a, b ≤ n$) if \\textbf{at least one} of the following conditions hold:\n\n- $a$ and $b$ are neighbouring, i.e. $|a - b| = 1$.\n- Positions $a$ and $b$ contain equal characters, i.e. $s_{a} = s_{b}$.\n\nThen Matvey decided to find the diameter of this graph. Diameter is a maximum distance (length of the shortest path) among all pairs of vertices. Also, Matvey wants to find the number of pairs of vertices such that the distance between them is equal to the diameter of the graph. As he is very cool and experienced programmer he managed to solve this problem very fast. Will you do the same?",
    "tutorial": "Let's prove that the distance between any two vertices is no more than $MaxDist = 2 \\cdot sigma - 1$, where $sigma$ is the size of the alphabet. Let's consider one of the shortest paths from the position $i$ to the position $j$. One can see that in this path each letter $ch$ occurs no more than two times (otherwise you could have skipped the third occurrence by jumping from the first occurrence to the last which gives us a shorter path). Thus, the total amount of letters in the path is no more than $2 \\cdot sigma$ which means that the length of the path is no more than $2 \\cdot sigma - 1$. Let $dist_{i, c}$ be the distance from the position $i$ to some position $j$ where $s_{j} = c$. These numbers can be obtained from simulating bfs for each letter $c$. We can simulate bfs in $O(n \\cdot sigma^{2})$ (let's leave this as an exercise to the reader). Let $dist(i, j)$ be the distance between positions $i$ and $j$. Let's figure out how we can find $dist(i, j)$ using precomputed values $dist_{i, c}$. There are two different cases: The optimal path goes through the edges of the first type only. In this case the distance is equal to $|i-j|$. The optimal path has at least one edge of the second type. We can assume that it was a jump between two letters $c$. Then, in this case the distance is $dist_{i, c} + 1 + dist_{c, j}$. Adding these two cases up we get: $d i s t(i,j)=m i n(|i-j|\\,,m i n(d i s t_{i.c}+1+d i s t_{c.j}))$. Let's iterate over the possible values for the first position $i = 1..n$. Let's compute the distance for all such $j$, where $|i-j|\\leq M a x D i s t$ by the above formula. Now, for a given $i$ we have to find $max(dist(i, j))$ for $\\vert i-j\\vert>M a x D i s t$. In this case $dist(i, j) = min(dist_{i, c} + 1 + dist_{c, j})$. Let's compute one additional number $dist_{c1, c2}$$-$ the minimal distance between positions $i$ and $j$ where $s_{i} = c_{1}$ and $s_{j} = c_{2}$. This can be easily done using $dist_{i, c}$. One can notice that $dist_{sj, c}  \\le  dist_{j, c}  \\le  dist_{sj, c} + 1$. It means that for every position $j$ we can compute a mask $mask_{j}$ with $sigma$ bits where $i$-th bit is equal to $dist_{j, c} - dist_{sj, c}$. Thus, we can compute the distance using only $s_{j}$ and $mask_{j}$. I.e. now $dist_{j, c} = dist_{sj, c} + mask_{j, c}$. Let $cnt$ be an array where $cnt_{c, mask}$ is the number of such $j$ where $|i-j|>M a x D i s t$, $s_{j} = c$ and $mask_{j} = mask$. Now, instead of iterating over $j$ for a given $i$ we can iterate over $(c, mask)$ and if $cnt_{c, mask}  \\neq  0$ we'll be updating the answer. Time complexity: $O(n\\cdot s i g m a^{3}+n\\cdot s i g m a^{2}\\cdot2^{s i g m a})$.",
    "tags": [
      "bitmasks",
      "graphs"
    ],
    "rating": 3300
  },
  {
    "contest_id": "719",
    "index": "A",
    "title": "Vitya in the Countryside",
    "statement": "Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.\n\nMoon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is $0$, $1$, $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$, $10$, $11$, $12$, $13$, $14$, $15$, $14$, $13$, $12$, $11$, $10$, $9$, $8$, $7$, $6$, $5$, $4$, $3$, $2$, $1$, and then cycle repeats, thus after the second $1$ again goes $0$.\n\nAs there is no internet in the countryside, Vitya has been watching the moon for $n$ consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.",
    "tutorial": "There are four cases that should be carefully considered: $a_{n} = 15$ $-$ the answer is always DOWN. $a_{n} = 0$ $-$ the answer is always UP. If $n = 1$ $-$ the answer is -1. If $n > 1$, then if $a_{n-1} > a_{n}$ $-$ answer is DOWN, else UP. Time Complexity: $O(1)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "719",
    "index": "B",
    "title": "Anatoly and Cockroaches",
    "statement": "Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are $n$ cockroaches living in Anatoly's room.\n\nAnatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to \\textbf{alternate}. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.\n\nHelp Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.",
    "tutorial": "We can notice that there are only two possible final coloring of cockroaches that satisfy the problem statement: $rbrbrb...$ or $brbrbr...$ Let's go through both of these variants. In the each case let's count the number of red and black cockroaches which are not standing in their places. Let's denote these numbers as $x$ and $y$. Then it is obvious that the $min(x, y)$ pairs of cockroaches need to be swapped and the rest should be repaint. In other words, the result for a fixed final coloring is exactly $min(x, y) + max(x, y) - min(x, y) = max(x, y)$. The final answer for the problem is the minimum between the answers for the first and the second colorings. Time Complexity: $\\mathrm{O}(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "720",
    "index": "A",
    "title": "Closing ceremony",
    "statement": "The closing ceremony of Squanch Code Cup is held in the big hall with $n × m$ seats, arranged in $n$ rows, $m$ seats in a row. Each seat has two coordinates $(x, y)$ ($1 ≤ x ≤ n$, $1 ≤ y ≤ m$).\n\nThere are two queues of people waiting to enter the hall: $k$ people are standing at $(0, 0)$ and $n·m - k$ people are standing at $(0, m + 1)$. Each person should have a ticket for a specific seat. If person $p$ at $(x, y)$ has ticket for seat $(x_{p}, y_{p})$ then he should walk $|x - x_{p}| + |y - y_{p}|$ to get to his seat.\n\nEach person has a stamina — the maximum distance, that the person agrees to walk. You should find out if this is possible to distribute all $n·m$ tickets in such a way that each person has enough stamina to get to their seat.",
    "tutorial": "Probably the easiest way to solve the problem is greedy. Sort people from the first line by increasing of their stamina. Give them tickets in this order, each time using the place which is furthest away from the other line. After that try to assign people from the second line to the remaining seats by sorting people by stamina and seats by the distance. The time complexity of your solution must not exceed $O((nm)^{2})$, however using std::set one can get a solution with complexity of $O(nm log(nm))$.",
    "tags": [
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "720",
    "index": "B",
    "title": "Cactusophobia",
    "statement": "Tree is a connected undirected graph that has no cycles. Edge cactus is a connected undirected graph without loops and parallel edges, such that each edge belongs to at most one cycle.\n\nVasya has an edge cactus, each edge of this graph has some color.\n\nVasya would like to remove the minimal number of edges in such way that his cactus turned to a tree. Vasya wants to make it in such a way that there were edges of as many different colors in the resulting tree, as possible. Help him to find how many different colors can the resulting tree have.",
    "tutorial": "Let us divide the graph to biconnected blocks. Each block is either a bridge, or a cycle. Our goal is to remove one edge from each cycle, so that the number of remaining colors were maximum possible. Let us build a bipartite graph, one part would be blocks, another one would be colors. For each block put an edge of capacity $1$ for each color of an edge in this block (make multiple edges, or bigger capacity if there are several edges of some color). Add two vertices: source and sink, add edges from source to blocks, if the block is a cycle of length $l$, set its capacity to $l - 1$, if it is a bridge, set its capacity to $1$. Add edges from color vertices to the sink of capacity $1$. It is quite clear that size of the maximum flow in this graph is indeed the answer to the problem. As a final note, the judges know the solution that runs in $O(n)$ and requires no maximum flow algorithms, challenge yourself to come up with it!",
    "tags": [
      "dfs and similar",
      "flows"
    ],
    "rating": 2400
  },
  {
    "contest_id": "720",
    "index": "C",
    "title": "Homework",
    "statement": "Today Peter has got an additional homework for tomorrow. The teacher has given three integers to him: $n$, $m$ and $k$, and asked him to mark one or more squares on a square grid of size $n × m$.\n\nThe marked squares must form a connected figure, and there must be exactly $k$ triples of marked squares that form an L-shaped tromino — all three squares are inside a $2 × 2$ square.\n\nThe set of squares forms a connected figure if it is possible to get from any square to any other one if you are allowed to move from a square to any adjacent by a common side square.\n\nPeter cannot fulfill the task, so he asks you for help. Help him to create such figure.",
    "tutorial": "The solution is constructive. First let us use backtracking to find solutions for all $n, m < 5$, it is also better to precalculate all answers, in order not to mess with non-asymptotic optimizations. Now $m  \\ge  5$. Let us put asterisks from left to right, one row after another. When adding the new asterisk, we add 4 new L-trominoes, except the first asterisk in a row that adds 1 new L-tromino, and the last asterisk in a row adds 3 new L-trominoes. Let us stop when the number of remaining L-trominoes $k$ is less than 4, or there are less than 5 free squares in the table. Now there are two cases there is a free row thee is no free row If there is a free row, we stopped because $k$ is now less then 4. So: k = 0: the solution is found k = 1: if there are already at least $2$ asterisks in the current row, put the asterisk in the beginning of the next row, if there is only $1$, put it in the end of the current row k = 2, k = 3 - similar, left as an exercise. If there are now free rows left, one can see that you can only add $k$ from the set ${0, 1, 2, 3, 4, 5, 6, 8, 9, 12, 15}$ L-trominoes. And finally there is also the special case where the size of the board is $3  \\times  m$, $m  \\ge  5$ and $k = 2 * (m - 1) - 8$ - in this case the first column should be left empty, and the rest of the board must be completely filled with asterisks.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3100
  },
  {
    "contest_id": "720",
    "index": "D",
    "title": "Slalom",
    "statement": "Little girl Masha likes winter sports, today she's planning to take part in slalom skiing.\n\nThe track is represented as a grid composed of $n × m$ squares. There are rectangular obstacles at the track, composed of grid squares. Masha must get from the square $(1, 1)$ to the square $(n, m)$. She can move from a square to adjacent square: either to the right, or upwards. If the square is occupied by an obstacle, it is not allowed to move to that square.\n\nOne can see that each obstacle can actually be passed in two ways: either it is to the right of Masha's path, or to the left. Masha likes to try all ways to do things, so she would like to know how many ways are there to pass the track. Two ways are considered different if there is an obstacle such that it is to the right of the path in one way, and to the left of the path in the other way.\n\nHelp Masha to find the number of ways to pass the track. The number of ways can be quite big, so Masha would like to know it modulo $10^{9} + 7$.\n\nThe pictures below show different ways to pass the track in sample tests.",
    "tutorial": "First let us consider all paths from the starting square to the finish one. Let us say that two paths are equivalent, if each obstacle is at the same side for both paths. For each class of equivalence let us choose the representative path - the one that tries to go as low as possible, lexicographically minimum. Let us use dynamic programming. For each square let us count the number of representative paths that go from the starting square to this one. When the obstacle starts, some paths can now separate. The new representatives will pass this obstacle from above (it will be to the right of them). So we add the sum of values for squares below it, but above any other lower obstacle, to the value for the square right above the obstacle. To overcome the time and memory limits that the naive solution with $O(nm)$ memory and $O(nm^{2})$ time complexity, we use segment tree for range sum queries with mass update, running scanline and events \"start of an obstacle\", \"end of an obstacle\". This leads to the solution with $O(m)$ memory and $O(n log m)$ time complexity.",
    "tags": [
      "data structures",
      "dp",
      "sortings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "720",
    "index": "E",
    "title": "Cipher",
    "statement": "Borya has recently found a big electronic display. The computer that manages the display stores some integer number. The number has $n$ decimal digits, the display shows the encoded version of the number, where each digit is shown using some lowercase letter of the English alphabet.\n\nThere is a legend near the display, that describes how the number is encoded. For each digit position $i$ and each digit $j$ the character $c$ is known, that encodes this digit at this position. Different digits can have the same code characters.\n\nEach second the number is increased by 1. And one second after a moment when the number reaches the value that is represented as $n$ 9-s in decimal notation, the loud beep sounds.\n\nAndrew knows the number that is stored in the computer. Now he wants to know how many seconds must pass until Borya can definitely tell what was the original number encoded by the display. Assume that Borya can precisely measure time, and that the encoded number will first be increased exactly one second after Borya started watching at the display.",
    "tutorial": "First let us consider a slow solution. Let us find a condition for each number $k$ after what number of seconds Borya can distinguish it from the given number. Let us look at their initial encoding. Increase both numbers by $1$ until the encodings are different (or one of the numbers needs more than $n$ digits to represent in which case the beep allows Borya to distinguish the numbers as well). Now there are two main ideas that allow us to get a better solution. First, we don't have to check all numbers. We only need to check numbers that differ from the given number in exactly one digit. Second: to get the time when the numbers can be distinguished we don't need to iterate over all possible values. We just need to try all digit positions and all values for that position, and check only moments when the digit at the position will first have this value in one of the numbers. So the complexity is now polynomial in $n$ and since $n  \\le  18$, it easily fits into the time limit.",
    "tags": [
      "implementation"
    ],
    "rating": 3100
  },
  {
    "contest_id": "720",
    "index": "F",
    "title": "Array Covering",
    "statement": "Misha has an array of integers of length $n$. He wants to choose $k$ different continuous subarrays, so that each element of the array belongs to at least one of the chosen subarrays.\n\nMisha wants to choose the subarrays in such a way that if he calculated the sum of elements for each subarray, and then add up all these sums, the resulting value was maximum possible.",
    "tutorial": "We give the outline of the solution, leaving technical details as an excercise. First note that the answer will always use $min(k - n, 0)$ subarrays with maximal sums. Sof let us find the sum of $min(k - n, 0)$ maximal subarrays, elements that are used in them, and the following $min(k, n)$ subarrays. We can do it using binary search for the border sum, and a data structure similar to Fenwick tree. For the given value of the sum this tree must provide the number of subarrays with greater or equal sum, sum of their sums, and the set of the elements of these subarrays. It should also allow to list all these subarrays in linear time complexity. This part has time complexity $O(n log^{2} n)$. Let us now describe how to solve the problem in $O(n^{2} log n)$. Let us try all values of $x$ - the number of subarrays with maximum sums that we will use in our solution (there are $O(n)$ variants, because top $min(k - n, 0)$ subarrays will definitely be used). Let elements with indices $i_{1}, ..., i_{m}$ be the ones that are not used in these subarrays. Now we must add $k - x$ segments that would contain all of these elements. Note that each of these $k - x$ segments must contain at least one of these elements, and no two segments can have a common element among them (in the other case the solution is not optimal). These observations let us greedily choose these $k - x$ segments in $O(n log n)$ and the final solution complexity is $O(n^{2} log n)$ To optimize this solution, we keep segments [$i_{j} + 1$; $i_{j + 1} - 1$] in the ordered set. When we iterate over $x$ and increase its value, we remove some of the $i_{j}$-s, and recalculate the required values for the affected segments. After that we must take $k - x$ maximal values from the set, so since there are $O(n)$ changes in total, this part now works in $O(n log n)$.",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "721",
    "index": "A",
    "title": "One-dimensional Japanese Crossword",
    "statement": "Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized $a × b$ squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia https://en.wikipedia.org/wiki/Japanese_crossword).\n\nAdaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of $n$ squares (e.g. japanese crossword sized $1 × n$), which he wants to encrypt in the same way as in japanese crossword.\n\n\\begin{center}\n{\\small The example of encrypting of a single row of japanese crossword.}\n\\end{center}\n\nHelp Adaltik find the numbers encrypting the row he drew.",
    "tutorial": "In this problem we have to compute the lengths of all blocks consisting of consecutive black cells. Let's iterate from the left cell of crossword to the end: let $i$ be the number of the cell where we are currently; if $s[i] = B$, let $j = i$, and while $j < n$ and $s[j] = 'B'$, we increase $j$ by one. When we come to a white cell or to the end of the crossword, we can compute the length of the block we have just passed (it is equal to $j - i$, and we need to store this value), and now move to cell $j$ (make $i = j$). And if we are in a white cell, all we need to do is increase $i$ by one. When $i = n$, it means that we have gone through the whole crossword, and now we print the answer. Time complexity - $O(n)$, and memory complexity - $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "721",
    "index": "B",
    "title": "Passwords",
    "statement": "Vanya is managed to enter his favourite site Codehorses. Vanya uses $n$ distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.\n\nVanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice.\n\nEntering any passwords takes one second for Vanya. But if Vanya will enter wrong password $k$ times, then he is able to make the next try only $5$ seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that.\n\nDetermine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds).",
    "tutorial": "The author suggests a solution with formulas: let's count two variables - $cnt_{l}$ (the number of passwords that are shorter than Vanya's Codehorses password) and $cnt_{le}$ (the number of passwords that are not longer than Vanya's Codehorses password). Then it's easy to see that in the best case answer will be equal to $c n t_{l}+\\lfloor{\\frac{c n t_{l}}{k}}\\rfloor\\cdot5+1$, and in the worst case it will be $c n t_{l e}+\\big[\\frac{c n t_{l e}-1}{k}\\big]\\cdot5$. Time complexity of solution - $O(n)$, memory complexity - $O(n)$.",
    "tags": [
      "implementation",
      "math",
      "sortings",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "721",
    "index": "C",
    "title": "Journey",
    "statement": "Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are $n$ showplaces in the city, numbered from $1$ to $n$, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there \\textbf{are no} cyclic routes between showplaces.\n\nInitially Irina stands at the showplace $1$, and the endpoint of her journey is the showplace $n$. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than $T$ time units.\n\nHelp Irina determine how many showplaces she may visit during her journey from showplace $1$ to showplace $n$ within a time not exceeding $T$. It is guaranteed that there is at least one route from showplace $1$ to showplace $n$ such that Irina will spend no more than $T$ time units passing it.",
    "tutorial": "Author's solution uses dynamic programming. Let $dp_{i, j}$ be the minimum time required to arrive at the vertex $i$, if we visit $j$ vertices (including vertices $1$ and $i$). We have a DAG (directed acyclic graph), so we can compute it recursively (and memory constraints were a bit strict in this problem, so it's better to use recursion to compute it). Let's store the transposed version of the graph: if we had an edge ($u, v$) in the input, we will store ($v, u$). Then our function $calc(i, j)$, which will compute the answer for $dp_{i, j}$, will be like that: the base of dynamic programming is $dp_{1, 1} = 0$, all other states are equal to <<-1>>. If we call $calc(i, j)$, then it will work like that: if the state we want to compute is incorrect ($j < 0$), we return a very large integer number (any number that is greater than $10^{9}$, because $T  \\le  10^{9}$). If the answer for this state has already been calculated, then we return $dp_{i, j}$ (it is easy do determine: if $dp_{i, j}  \\neq  - 1$, then it has already been calculated). Else we begin to calculate the state. Firstly, let's put $INF$ (a number greater than $10^{9}$) into $dp_{i, j}$. Then look at all the edges beginning in $i$ and try to update $dp_{i, j}$ with the value of $calc(to, j - 1) + w$ ($to$ is the vertex at the endpoint of current edge, $w$ is the weight of this edge). If this value is less than $dp_{i, j}$, then we update $dp_{i, j}$ and store the information that our last update in $dp_{i, j}$ was from the vertex $to$. If we try to go by path which doesn't end in the vertex $1$, then we get a value which is greater than $10^{9}$, that's because that the only value we didn't denote as $- 1$ is $dp_{1, 1}$. So, now we have our $calc$ function, let's compute the answer. We will iterate on the number of vertices in the path from $n$ to $1$ in descending order, and if $calc(n, i)  \\le  T$, then we have found the answer, now we iterate on the parent vertices we stored while calculating our $dp$, until we come to vertex $1$ (it's important because some participants sent solutions that continued even past vertex $1$!) and print the answer. Time complexity of this solution - $O((n + m)n)$, and mempry complexity - $O(nm)$.",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 1800
  },
  {
    "contest_id": "721",
    "index": "D",
    "title": "Maxim and Array",
    "statement": "Recently Maxim has found an array of $n$ integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer $x$ and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer $i$ ($1 ≤ i ≤ n$) and replaces the $i$-th element of array $a_{i}$ either with $a_{i} + x$ or with $a_{i} - x$. Please note that the operation may be applied more than once to the same position.\n\nMaxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. $\\prod_{i=1}^{n}a_{i}$) can reach, if Maxim would apply no more than $k$ operations to it. Please help him in that.",
    "tutorial": "Main idea: we act greedily, trying to make the best possible answer every action (each time we choose an action with minimum possible product after it). Detailed explanation: While we have zeroes in our array, we have to get rid of them, changing each of them exactly one time. Also we keep the quantity of negative numbers - we need it to make the product negative after changing the last zero. Let $m$ be the number of zeroes in the array. If $m > k$, then we cannot make the product negative or positive (it will always be equal to $0$), so any sequence of operations will lead to a correct answer. However, if $m  \\le  k$, then we are able to come to negative product (if the number of negative elements was even, then we subtract $x$ from one zero and add it to all other zeroes; if the number of negative elements was odd, then we can just add $x$ to all zeroes). If current product is still positive, then we want to change the sign of exactly one element. Its absolute value has to be minimal: suppose we have two elements $a$ and $b$, $|a| < |b|$; let's prove that if we change $b$'s sign, then our answer is wrong. Let $m$ be the minimum number of operations required to change $b$'s sign. If we perform $m$ operations with $b$, then the absolute value of $a$ won't change, and absolute value of $b$ will become $x \\cdot m - |b|$. If, on the other hand, we perform $m$ operations with $a$ (this may not be optimal, but now we need to prove that if we change $b$, then the result will be worse), then the absolute value of $a$ will become $x \\cdot m - |a|$, the absolute value of $b$ won't change. The product becomes negative, so we need to maximize the product of absolute values. And then $x \\cdot m - |a| > x \\cdot m - |b|$ and $|b| > |a|$, so if we change $b$, then the product of absolute values will be less than if we change $a$. Now, until we have performed $k$ operations, we choose a number with minimum absolute value and enlarge it (add $x$ if this number if positive, subtract if negative). Let's prove that the answer will be optimal. Suppose that this algorithm chooses $a$ on some iteration, but we can't get optimal answer if we change $a$. This means that we can't change $a$ after this iteration at all (we can reorder our operations in an arbitrary way, and the answer won't change). Suppose we have to change $b$ instead, and $|b| > |a|$. Let's consider the sequence of operations leading to the optimal answer when we choose $b$, and replace change of $b$ with change of $a$, and let the product of all remaining numbers (the whole array excluding $a$ and $b$ after all operations) be $c$. If we change $a$, the total product will be $- (|a| + x) \\cdot (|b| + x \\cdot m) \\cdot |c|$, and if we change $b$, we get $- |a| \\cdot (|b| + x \\cdot (m + 1)) \\cdot |c|$ ($m$ is the number of times we change $b$). Now $|a| < |b| + x \\cdot m$, so $(|a| + x) \\cdot (|b| + x \\cdot m) - |a| \\cdot (|b| + x \\cdot (m + 1)) = |b| + x \\cdot m - |a| > 0$, so the absolute value of total product will be greater if we change $a$. This proves that we won't come to unoptimal answer if we change $a$. Time complexity: $O((n+k)\\log n)$ if we use a data structure similar to set or priority_queue to get the number with minimal absolute value. Memory complexity: $O(n)$.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "721",
    "index": "E",
    "title": "Road to Home",
    "statement": "Once Danil the student was returning home from tram stop lately by straight road of length $L$. The stop is located at the point $x = 0$, but the Danil's home — at the point $x = L$. Danil goes from $x = 0$ to $x = L$ with a constant speed and does not change direction of movement.\n\nThere are $n$ street lights at the road, each of which lights some continuous segment of the road. All of the $n$ lightened segments do not share common points.\n\nDanil loves to sing, thus he wants to sing his favourite song over and over again during his walk. As soon as non-lightened segments of the road scare him, he sings only when he goes through the lightened segments.\n\nDanil passes distance $p$ while performing his favourite song once. Danil can't start another performance if the segment passed while performing is not fully lightened. Moreover, if Danil has taken a pause between two performances, he is not performing while not having passed a segment of length at least $t$. Formally,\n\n- Danil can start single performance at a point $x$ only if every point of segment $[x, x + p]$ is lightened;\n- If Danil has finished performing at a point $x + p$, then the next performance can be started only at a point $y$ such that $y = x + p$ or $y ≥ x + p + t$ satisfying the statement under the point $1$.\n\n\\begin{center}\n{\\small Blue half-circles denote performances. Please note that just after Danil has taken a pause in performing, he has not sang for a path of length of at least $t$.}\n\\end{center}\n\nDetermine how many times Danil can perform his favourite song during his walk from $x = 0$ to $x = L$.\n\nPlease note that Danil does not break a single performance, thus, started singing another time, he finishes singing when having a segment of length of $p$ passed from the performance start point.",
    "tutorial": "Firstly, if we are in some segment and we are going to sing in it, we want to sing as much as possible in this segment. So there are two cases for each segment: either we sing in the segment while we can or we just skip it. Now we consider two different cases: 1) $p  \\le  100$ If we have stopped singing in the segment, then the distance we need to walk to reach the end of this segment is strictly less than $p$. Let's calculate two values - $dp_{left}[i]$ - the answer (how many times we can sing a song) if we start from the beginning of segment number $i$ (from $l_{i}$), and $dp_{right}[i][j]$ - the answer if we start from $r_{i} - j$ ($0  \\le  j < p$, as we already said before). To calculate the value using the value from point $x$, we have to find the segment which contains the point $x + t$ and the segment which begins after this point. If we are in segment number $k$, we either skip it and update next segment ($dp_{left}[k + 1]$), or start singing and update the value in the point $y$ where we stop singing ($dp_{right}[k][y]$). To find the segment containing point $x + t$, we can use binary search or precalculate the required indices using iterations on the array of segments. Time complexity: $O(n p\\log n)$ or $O(np)$. 2) $p > 100$ Let's use the fact that the answer is not greater than ${\\frac{L}{p}}<10^{7}$. For each value $i$ we calculate $lf_{i}$ - the leftmost point where we can get it. We will iterate on those values considering that we have already calculated $lf_{j}$ for every $j < i$ when we start calculating $lf_{i}$. Then if $lf_{i}$ is before the beginning of some segment, and $lf_{i + 1}$ is after its beginning, then we can try singing starting from the beginning of this segment with $i$ performed songs currently, updating $lf$ for next values (from $i + 1$ till $i+{\\bigl\\lfloor}{\\frac{r_{k}-l_{k}}{p}}{\\bigr\\rfloor}$ with the values $r_{k} - (r_{k} - l_{k}) mod p$). Using this fact we update the value for the largest answer, skipping the points in the middle of the segment. To calculate these values we need a data structure (for example, Fenwick tree) which sustains the minimum value on the suffix ($lf_{i}$ is the minimum on suffix beginning from element number $i$). All $lf$ values are increasing, so we need only one variable to sustain the index of the segment we are using to update. How we have to consider the points in the middle of some segment. So we have a variable storing the index of the rightmost segment which begins before $lf_{i}$ for current answer $i$. It may seem that the values from the beginning and from the middle of some segment may be used in the wrong order, but it's easy to prove that it's not true. Copmplexity: $O(\\frac{L}{p}\\log\\left(\\frac{L}{p}\\right)+n)$. We can use a special updating structure based on stack to get rid of Fenwick tree, then complexity will be $O({\\frac{L}{p}}+n)$.",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "722",
    "index": "A",
    "title": "Broken Clock",
    "statement": "You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from $1$ to $12$, while in 24-hours it changes from $0$ to $23$. In both formats minutes change from $0$ to $59$.\n\nYou are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.\n\nFor example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.",
    "tutorial": "Let's iterate over all possible values that can be shown on the clock. First two digits must form a number from $1$ to $12$ in case of $12$-hours format and a number from $0$ to $23$ in case of $24$-hours format. Second two digits must form a number from $0$ to $59$. For each value, we will count the number of digits that differ from the original ones. Finally, choose the value, that differs in the least number of digits.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "722",
    "index": "B",
    "title": "Verse Pattern",
    "statement": "You are given a text consisting of $n$ lines. Each line contains some space-separated words, consisting of lowercase English letters.\n\nWe define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.\n\nEach word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word \"mamma\" can be divided into syllables as \"ma\" and \"mma\", \"mam\" and \"ma\", and \"mamm\" and \"a\". Words that consist of only consonants should be ignored.\n\nThe verse patterns for the given text is a sequence of $n$ integers $p_{1}, p_{2}, ..., p_{n}$. Text matches the given verse pattern if for each $i$ from $1$ to $n$ one can divide words of the $i$-th line in syllables in such a way that the total number of syllables is equal to $p_{i}$.\n\nYou are given the text and the verse pattern. Check, if the given text matches the given verse pattern.",
    "tutorial": "Number of syllables, in which we can split a word, can be uniqely defined by the number of vowels in it. Thus, we need to count the number of vowels in each line and compare them to the given sequence.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "722",
    "index": "C",
    "title": "Destroying Array",
    "statement": "You are given an array consisting of $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$.\n\nYou are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from $1$ to $n$ defining the order elements of the array are destroyed.\n\nAfter each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be $0$.",
    "tutorial": "Main observation, that was necessary to solve the problem: since all numbers are non-negative, it makes sense to consider only subsegments, maximal with respect to inclusion. That is, such segments on both sides of which there are either destroyed numbers or the end of the array. Let's solve the problem in reversed order: first destroy all the numbers, and then add them back. We will carry a single value - the current maximum sum among all subsegments. After destroying all the numbers, the answer is equal to zero. Now, we add a new number on each step. To find the maximum subsegment containing this number, we need to find the nearest to the left and to the right destroyed number. This can be done in $O(log n)$ using binary search tree (f.e. set from STL). To find the sum of the numbers in the subsegment, we can compute partial sums of the original array. Thus, at each step, we can update the maximum sum among all subsegments in $O(log n)$ time. The total complexity of this solution is $O(n log n)$.",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 1600
  },
  {
    "contest_id": "722",
    "index": "D",
    "title": "Generating Sets",
    "statement": "You are given a set $Y$ of $n$ \\textbf{distinct} positive integers $y_{1}, y_{2}, ..., y_{n}$.\n\nSet $X$ of $n$ \\textbf{distinct} positive integers $x_{1}, x_{2}, ..., x_{n}$ is said to generate set $Y$ if one can transform $X$ to $Y$ by applying some number of the following two operation to integers in $X$:\n\n- Take any integer $x_{i}$ and multiply it by two, i.e. replace $x_{i}$ with $2·x_{i}$.\n- Take any integer $x_{i}$, multiply it by two and add one, i.e. replace $x_{i}$ with $2·x_{i} + 1$.\n\nNote that integers in $X$ are not required to be distinct after each operation.\n\nTwo sets of distinct integers $X$ and $Y$ are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal.\n\nNote, that any set of integers (or its permutation) generates itself.\n\nYou are given a set $Y$ and have to find a set $X$ that generates $Y$ and the \\textbf{maximum element of $X$ is mininum possible}.",
    "tutorial": "Author's solution appeared to be slightly more complicated than the solutions of most of the participants, so we will describe that simple solution. An arbitrary number $y$ can be obtained from one of the following numbers - $y,\\{{\\frac{y}{2}}\\},\\{{\\frac{y}{4}}\\},\\ldots,1$ and only from them. Therefore, we will use the following greedy algorithm: Let's choose the maximum number from the set $Y$ (assume this number is $y_{i}$). We look through all the numbers from which you can obtain the selected number - $y_{i},\\left[{\\frac{y_{i}}{2}}\\right],\\left[{\\frac{y_{i}}{4}}\\right],\\ldots\\cdot,\\ 1\\right.$. Among these numbers choose the maximum number, which is not included in the set $Y$ yet. Replace $y_{i}$ with this number and do the above operation again. If at some point it turned out that all of these numbers already belong to the set $Y$, then we print the current set and finish the algorithm. To find the maximum number and to check whether any number is belong to $Y$ or not, you can use the binary search tree (f.e. set from STL) or the combination of priority queue and hash table. Formally, the total complexity of this solution is $O(n log n log 10^{9})$.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "greedy",
      "strings",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "722",
    "index": "E",
    "title": "Research Rover",
    "statement": "Unfortunately, the formal description of the task turned out to be too long, so here is the legend.\n\nResearch rover finally reached the surface of Mars and is ready to complete its mission. Unfortunately, due to the mistake in the navigation system design, the rover is located in the wrong place.\n\nThe rover will operate on the grid consisting of $n$ rows and $m$ columns. We will define as $(r, c)$ the cell located in the row $r$ and column $c$. From each cell the rover is able to move to any cell that share a side with the current one.\n\nThe rover is currently located at cell $(1, 1)$ and has to move to the cell $(n, m)$. It will randomly follow some \\textbf{shortest path} between these two cells. Each possible way is chosen equiprobably.\n\nThe cargo section of the rover contains the battery required to conduct the research. Initially, the battery charge is equal to $s$ units of energy.\n\nSome of the cells contain anomaly. Each time the rover gets to the cell with anomaly, the battery looses half of its charge rounded down. Formally, if the charge was equal to $x$ before the rover gets to the cell with anomaly, the charge will change to $\\left|{\\frac{x}{2}}\\right|$.\n\nWhile the rover picks a random shortest path to proceed, compute the expected value of the battery charge after it reaches cell $(n, m)$. If the cells $(1, 1)$ and $(n, m)$ contain anomaly, they also affect the charge of the battery.",
    "tutorial": "Several auxiliary statements: The number of paths between cells with coordinates $(i_{1}, j_{1})$ and $(i_{2}, j_{2})$, for which $i_{1}  \\le  i_{2}$ and $j_{1}  \\le  j_{2}$, is equal to $\\left(^{\\left(j_{2}-j_{1}\\right)+\\left(i_{2}-i_{1}\\right)}\\right)$. In order to get the answer it is not necessary to find irreducible fraction $\\frac{P}{Q}$. Suppose that we have found some fraction $\\textstyle{\\frac{P_{1}}{Q_{1}}}$, for which the following is true: $P_{1} = P * g$, $Q_{1} = Q * g$. Let's calculate the answer for this fraction: $P_{1} * Q_{1}^{ - 1}  \\equiv  P * g * (Q * g)^{ - 1}  \\equiv  P * g * Q^{ - 1} * g^{ - 1}  \\equiv  P * g * g^{ - 1} * Q^{ - 1}  \\equiv  P * Q (mod 10^{9} + 7)$. From the second statement it implies that the answer can be found in the following form: $Q$ is equal to the number of paths between cells $(1, 1)$ and $(n, m)$, and $P$ is equal to the sum of the battery charges in the endpoint among all paths. The battery charge in the endpoint does not depend on the order of visit of the anomalies, but only on the number of anomalies on the path. Then in order to calculate the required sum it is enough to count the number of paths that pass through the $0, 1, 2$ and so on anomalies. Note that since the original battery charge does not exceed $10^{6}$, and each time you visit the anomaly it is reduced by half, then in all paths, with the number of anomalies greater than or equal to $20$, the charge at the endpoint will be equal to $1$. First let's try to solve a simpler problem: count the number of paths that do not pass through the cells with anomalies. Sort all the cells with anomalies in increasing order of the sum of their coordinates. Then, if the path passes through the anomaly with the number $i$ (in sorted order), then the next cell with anomaly on the path can only be the cell with the number greater than $i$. We calculate the following dynamic: $F(i)$ - number of paths which start in the anomaly with the number $i$, end in the cell $(n, m)$ and don't pass through other anomalies. Let's denote as $paths(i_{1}, j_{1}, i_{2}, j_{2})$ the following value: $\\left(^{\\left(j_{2}-j_{1}\\right)+\\left(i_{2}-i_{1}\\right)}\\right)$ if $i_{1}  \\le  i_{2}, j_{1}  \\le  j_{2}$ and $0$ otherwise. Values of $F$ can be calculated using the following formula: $F(i)=p a t h s(r_{i},c_{i},n,m)-\\sum_{j=i+1}^{k}(p a t h s(r_{i},c_{i},r_{j},c_{j})*F(j))$. Every path that passes through at least one anomaly different from the $i$-th, will be subtracted from the total number of paths exactly once - when the $j$ is equal to the number of the last anomaly on this path. Let's go back to the original problem: denote as $G(i, v)$ the number of paths which start in the anomaly with the number $i$, end in the cell $(n, m)$ and pass through exactly $v$ anomalies different from $i$-th. For $v = 0$, $G(i, 0) = F(i)$. For $v > 0$, values of $G$ can be calculated using the following formula: $G(i,v)=p a t h s(r_{i},c_{i},n,m)-\\sum_{j=i+1}^{k}p a t h s(r_{i},c_{i},r_{j},c_{j})*G(j,v)-\\sum_{j=0}^{v-1}G(i,j)$. Every path that passes through at least $v + 1$ anomalies different from the $i$-th, will be subtracted from the total number of paths exactly once - when the $j$ is equal to the number of $v$-th anomaly from the end on this path. It remains only to subtract all paths that contains less than $v$ anomalies (last part of the formula). For simplicity, you can add an additional anomaly with coordinates $(1, 1)$. In the end, let's iterate over the number of anomalies (from $0$ to $19$) on the path. For each number, we can find the value of the battery charge in the endpoint and multiply it by the number of paths calculated above. Also, add one to the sum for each path that visits $20$ or more anomalies. The resulting complexity of the solution is $O(n^{2} log 10^{6})$.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "722",
    "index": "F",
    "title": "Cyclic Cipher",
    "statement": "You are given $n$ sequences. Each sequence consists of positive integers, not exceeding $m$. All integers in one sequence are distinct, but the same integer may appear in multiple sequences. The length of the $i$-th sequence is $k_{i}$.\n\nEach second integers in each of the sequences are shifted by one to the left, i.e. integers at positions $i > 1$ go to positions $i - 1$, while the first integers becomes the last.\n\nEach second we take the first integer of each sequence and write it down to a new array. Then, for each value $x$ from $1$ to $m$ we compute the longest \\textbf{segment} of the array consisting of element $x$ only.\n\nThe above operation is performed for $10^{100}$ seconds. For each integer from $1$ to $m$ find out the longest segment found at this time.",
    "tutorial": "Let's solve the problem for a particular number $X$. Without loss of generality, we assume that $X$ appeared in each sequence. If not, then the whole sequence is divided into contigous subsegments, for which above statement is true, and the answer for the number $X$ is equal to the maximum of the answers for these subsegments. Let's denote as $p_{i}$ the position (from $0$ to $k_{i}$ - 1) of $X$ in the $i$-th sequence. Then the number $X$ occures in the new array at position $i$ in the seconds equal to $p_{i} + l * k_{i}$. This condition can be rewritten as follows: the number $X$ occures at position $i$ on the $S$-th second, if $S  \\equiv  p_{i} (mod k_{i})$. Thus, to determine whether the number $X$ occurs at some point in all positions from $i$ to $j$, you need to determine whether there is a solution for a system of equations: $\\left\\{{\\begin{array}{l}{S\\equiv p_{i}\\ (m o d\\ k_{i})}\\\\ {\\cdot\\cdot}\\\\ {S\\equiv p_{j}\\ (m o d\\ k_{j})}\\end{array}}\\right.$ Suppose that we are able to quickly answer to such queries for arbitrary $i$ and $j$. Then the problem can be solved, for example, using two pointers. We will move the left boundary of the subsegment, and for fixed left boundary, we will move the right boundary as far as possible, until the solution of the corresponding system still exists. We can solve a system of equations for any subsegment in $O(log LCM)$ time per query using $O(n log n log LCM)$ precalculation in the following way: To begin with, we note that the set of solutions of this system is either empty or it itself can be represented in the same form $S  \\equiv  p (mod k)$, where $k = LCM(k_{i}, k_{i + 1}, ..., k_{j})$. We will find the solutions of the systems for the following subsegments: for each $i$ and for each $j = 0, ..., log n$, we will take subsegment $(i, i + 2^{j} - 1)$. For each such subsegment we can find the solution of the corresponding system using $O(log LCM)$ time by solving a system consisting of two equations obtained from each of the halves of this subsegment. We can solve a system consisting of two equations using the Chinese remainder theorem. Now, to find a solution for any subsegment, it is enough to take two subsegments presented above, that their union is equal to the initial subsegment, and again solve a system of two equations. The resulting complexity of the solution is $O(n log n log LCM)$. Since the lengths of the sequences does not exceed 40, the resulting LCM can be upper bounded by 10^16. Since the total length of all sequences is $O(n)$, the total complexity of the solution for all the numbers remains the same.",
    "tags": [
      "chinese remainder theorem",
      "data structures",
      "implementation",
      "number theory",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "723",
    "index": "A",
    "title": "The New Year: Meeting Friends",
    "statement": "There are three friend living on the straight line $Ox$ in Lineland. The first friend lives at the point $x_{1}$, the second friend lives at the point $x_{2}$, and the third friend lives at the point $x_{3}$. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?\n\nIt's guaranteed that the optimal answer is always integer.",
    "tutorial": "To solve this problem you need to understand that friends must meet in the middle point of the given points, so friends who live in the leftmost and in the rightmost points must go to the middle point. Because of that the answer equals to $max(x_{1}, x_{2}, x_{3}) - min(x_{1}, x_{2}, x_{3})$.",
    "tags": [
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "723",
    "index": "B",
    "title": "Text Document Analysis",
    "statement": "Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.\n\nIn this problem you should implement the similar functionality.\n\nYou are given a string which only consists of:\n\n- uppercase and lowercase English letters,\n- underscore symbols (they are used as separators),\n- parentheses (both opening and closing).\n\nIt is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching \"opening-closing\" pair, and such pairs can't be nested.\n\nFor example, the following string is valid: \"_Hello_Vasya(and_Petya)__bye_(and_OK)\".\n\nWord is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: \"Hello\", \"Vasya\", \"and\", \"Petya\", \"bye\", \"and\" and \"OK\". Write a program that finds:\n\n- the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses),\n- the number of words inside the parentheses (print 0, if there is no word inside the parentheses).",
    "tutorial": "It is an implementation problem. Let's store in the variable $cnt$ the number of words inside brackets and in the variable $maxL$ - the maximum length of the word outside brackets. You can add the symbol <<_>> to the end of the given string, to correctly process the last word. Let's iterate through the given string from the left to the right and store in the variable $cur$ the current word. Also in the variable $bal$ we need to store balance of the open and close brackets. If the current symbol is letter - add it to the end of the string $cur$ and go to the next symbol of the given string. If the current symbol is open bracket, make $bal = bal + 1$. If the current symbol is close bracket, make $bal = bal - 1$. After that if $cur$ is non-empty string add 1 to $cnt$ if $bal$ equals to $1$. Else if $bal$ equals to $0$ update $maxL$ with length of the string $cur$. After that we need to assign $cur$ to the empty string and go to the next symbol of the given string.",
    "tags": [
      "expression parsing",
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "723",
    "index": "C",
    "title": "Polycarp at the Radio",
    "statement": "Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is a band, which performs the $i$-th song. Polycarp likes bands with the numbers from $1$ to $m$, but he doesn't really like others.\n\nWe define as $b_{j}$ the number of songs the group $j$ is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers $b_{1}, b_{2}, ..., b_{m}$ will be as large as possible.\n\nFind this maximum possible value of the minimum among the $b_{j}$ ($1 ≤ j ≤ m$), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the $i$-th song with any other group.",
    "tutorial": "It is easy to understand that we always can get the maximum value of the minimum of the values $b_{j}$ which equals to $n / m$. So, we need to make vector $can$ which will store positions of the given array in which we will change values. At first it is all positions of the given array, in which the values are more than $m$. Then we need to store for all $i$ from 1 to $m$ in vectors $pos_{i}$ the positions of the given array, in which the bands equal to $i$. Then for every vector, which size is more than $n / m$ we need to add tje first $sz(pos_{i}) - (n / m)$ elements in the vector $can$, where $sz(pos_{i})$ is the size of the vector $pos_{i}$. After that we need to iterate through the numbers of bands from 1 to $m$. If $sz(pos_{i})$ is less than $n / m$ we need to take regular $(n / m) - sz(pos_{i})$ positions from the vector $can$ and change the values in this positions to $i$. In the same time we need to count the number of changes in the playlist.",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "723",
    "index": "D",
    "title": "Lakes in Berland",
    "statement": "The map of Berland is a rectangle of the size $n × m$, which consists of cells of size $1 × 1$. Each cell is either land or water. The map is surrounded by the ocean.\n\nLakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.\n\nYou task is to fill up with the earth the minimum number of water cells so that there will be \\textbf{exactly} $k$ lakes in Berland. Note that the initial number of lakes on the map is \\textbf{not less} than $k$.",
    "tutorial": "To solve this problem we need to find all connected components consisting of dots, which do not have common border with ocean. For that we need to implement depth search which returns vector of the points from which the current connected component consists. Then we need to sort all connected components in order of increasing of their sizes and changes all dots on asterisks in components, beginning from the component with minimum size, until the number of left components does not equals to $k$.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "723",
    "index": "E",
    "title": "One-Way Reform",
    "statement": "There are $n$ cities and $m$ two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads.\n\nThe road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to \\textbf{maximize} the number of cities, for which the number of roads that begins in the city \\textbf{equals} to the number of roads that ends in it.",
    "tutorial": "Let's solve this problem for each connected component separately. At first we need to understand fact that in each connected component there are even number of vertices with odd degree. Let in the current connected component there are $k$ vertices with odd degree and they have numbers $o_{1}, o_{2}, ..., o_{k}$. Then we need to add in graph non-directional edges $(o_{1}, o_{2})$, $(o_{3}, o_{4})$, $...$ $(o_{k - 1}, o_{k})$. So in the current component now all vertices have even degree and there is exist Euler cycle, which we need to find and orientate all edges in the order of this cycle. It is easy to show that after that for all vertices which had even degree before we added the edges in-degree is equal to out-degree. In the other words, we show that the maximum number of vertices with equal in- and out-degrees in orientated graph equals to the number of vertices with even degree in non-orientated graph. After we found Euler cycles for all connected components we need to print orientation of the edges and be careful and do not print edges which we added to the graph to connect vertices with odd degrees.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "flows",
      "graphs",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "723",
    "index": "F",
    "title": "st-Spanning Tree",
    "statement": "You are given an undirected connected graph consisting of $n$ vertices and $m$ edges. There are no loops and no multiple edges in the graph.\n\nYou are also given two distinct vertices $s$ and $t$, and two values $d_{s}$ and $d_{t}$. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex $s$ doesn't exceed $d_{s}$, and the degree of the vertex $t$ doesn't exceed $d_{t}$, or determine, that there is no such spanning tree.\n\nThe spanning tree of the graph $G$ is a subgraph which is a tree and contains all vertices of the graph $G$. In other words, it is a connected graph which contains $n - 1$ edges and can be obtained by removing some of the edges from $G$.\n\nThe degree of a vertex is the number of edges incident to this vertex.",
    "tutorial": "At first lets delete vertices $s$ and $t$ from the graph, find all connected components in the remaining graph and build for every component any spanning trees. Now we need to add in spanning tree vertices $s$ and $t$. At first let add edges from $s$ to all components, which have no edges to $t$. Then let add edges from $t$ to all components, which have no edges to $s$. If after that the degree of $s$ became more than $d_{s}$ or the degree of $t$ became more than $d_{t}$ answer does not exist. Now we have components which have edges and to $s$ and to $t$. Also currently we have two spanning trees which does not connect. Let's choose how to connect them - with vertex $s$, with vertex $t$ or with both of them (only if we have in the graph an edge ${s, t}$). For each option we need to greedily connect remaining components (if it is possible for current option). If we done it for any option we need only to print the answer.",
    "tags": [
      "dsu",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "724",
    "index": "A",
    "title": "Checking the Calendar",
    "statement": "You are given names of two days of the week.\n\nPlease, determine whether it is possible that during some \\textbf{non-leap year} the first day of some month was equal to the first day of the week you are given, while the first day of \\textbf{the next month} was equal to the second day of the week you are given. \\textbf{Both months should belong to one year}.\n\nIn this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: $31$, $28$, $31$, $30$, $31$, $30$, $31$, $31$, $30$, $31$, $30$, $31$.\n\nNames of the days of the week are given with lowercase English letters: \"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\", \"sunday\".",
    "tutorial": "Days of the week in two adjacent months may either be the same (in February and March), or differ by two (in April and May) or differ by three (in January and February). Also, it was necessary to pay attention to direction of that difference (monday and tuesday is not the same as tuesday and monday).",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "724",
    "index": "B",
    "title": "Batch Sort",
    "statement": "You are given a table consisting of $n$ rows and $m$ columns.\n\nNumbers in each row form a permutation of integers from $1$ to $m$.\n\nYou are allowed to pick two elements in one row and swap them, but \\textbf{no more than once} for each row. Also, \\textbf{no more than once} you are allowed to pick two columns and swap them. Thus, you are allowed to perform from $0$ to $n + 1$ actions in total. \\textbf{Operations can be performed in any order}.\n\nYou have to check whether it's possible to obtain the identity permutation $1, 2, ..., m$ in each row. In other words, check if one can perform some of the operation following the given rules and make each row sorted in increasing order.",
    "tutorial": "Order of swaps of numbers in each row is not important. In fact, the order is not important even when we will swap the entire columns (because we can always change the swaps in the rows so that the result will remain the same). Therefore we can choose columns which we will swap (or choose not to swap them at all), and then for each row check if we can arrange the numbers in ascending order using only one swap. This can be done by checking that all the numbers, except for maybe two of them, are already standing in their places.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "724",
    "index": "C",
    "title": "Ray Tracing",
    "statement": "There are $k$ sensors located in the rectangular room of size $n × m$ meters. The $i$-th sensor is located at point $(x_{i}, y_{i})$. All sensors are located at distinct points strictly inside the rectangle.\n\nOpposite corners of the room are located at points $(0, 0)$ and $(n, m)$. Walls of the room are parallel to coordinate axes.\n\nAt the moment $0$, from the point $(0, 0)$ the laser ray is released in the direction of point $(1, 1)$. The ray travels with a speed of ${\\sqrt{2}}$ meters per second. Thus, the ray will reach the point $(1, 1)$ in exactly one second after the start.\n\nWhen the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.\n\nFor each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print $ - 1$ for such sensors.",
    "tutorial": "Let's simulate the flight of the beam. It can be seen that for any segment between two successive reflections is true that the sum of the coordinates for each point of this segment is constant or the difference of the coordinates is constant. Thus, we can make lists of sensors for each possible sum and difference of coordinates. Then, when we process the segment of the beam trajectory, we can take all the points from the corresponding list and update result for them. This solution works fast, because each point is passed by the beam (and therefore viewed by us) not more than two times.",
    "tags": [
      "greedy",
      "hashing",
      "implementation",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "724",
    "index": "D",
    "title": "Dense Subsequence",
    "statement": "You are given a string $s$, consisting of lowercase English letters, and the integer $m$.\n\nOne should choose some symbols from the given string so that any contiguous subsegment of length $m$ has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves.\n\nThen one uses the chosen symbols to form \\textbf{a new string}. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order.\n\nFormally, we choose a subsequence of indices $1 ≤ i_{1} < i_{2} < ... < i_{t} ≤ |s|$. The selected sequence must meet the following condition: for every $j$ such that $1 ≤ j ≤ |s| - m + 1$, there must be at least one selected index that belongs to the segment $[j,  j + m - 1]$, i.e. there should exist a $k$ from $1$ to $t$, such that $j ≤ i_{k} ≤ j + m - 1$.\n\nThen we take any permutation $p$ of the selected indices and form a new string $s_{ip1}s_{ip2}... s_{ipt}$.\n\nFind the lexicographically smallest string, that can be obtained using this procedure.",
    "tutorial": "It is not hard to see that if we choose some subset of the letters then to achieve lexicographically smallest string you must first write all of the letters 'a', then all of the letters 'b' and so on. Let's assume that the string in the answer consists only of the letters 'a'. Then it should be as small of them as possible to get lexicographically smallest string. We can check whether it is enough to take only the letters 'a' to meet the requirement on the density of the indices (in each subsegment of length $m$ it has to be at least one letter 'a'). If this is true, we can find the minimum number of letters 'a', which will satisfy the density requirement, using the greedy algorithm (every time we will take the rightmost letter 'a', which is separated from the previous one by no more than $m$ positions). If this is not true, then the answer must contain some other letters except for 'a'. This means that we need to take as much 'a' letters as possible. So we can take all of them, because adding any additional letter will not affect the density requirement. Then do the same with the letter 'b', bearing in mind that all of the letters 'a' is already taken. If the letters 'b' is not enough, then take all of the letters 'a', all of the letters 'b' and proceed to the next letter, and so on.",
    "tags": [
      "data structures",
      "greedy",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "724",
    "index": "E",
    "title": "Goods transportation",
    "statement": "There are $n$ cities located along the one-way road. Cities are numbered from $1$ to $n$ in the direction of the road.\n\nThe $i$-th city had produced $p_{i}$ units of goods. No more than $s_{i}$ units of goods can be sold in the $i$-th city.\n\nFor each pair of cities $i$ and $j$ such that \\textbf{$1 ≤ i < j ≤ n$} you can \\textbf{no more than once} transport \\textbf{no more than} $c$ units of goods from the city $i$ to the city $j$. Note that goods can only be transported from a city with a lesser index to the city with a larger index. \\textbf{You can transport goods between cities in any order.}\n\nDetermine the maximum number of produced goods that can be sold in total in all the cities after a sequence of transportations.",
    "tutorial": "Build a network of the following form: The network will consist of $n + 2$ vertices, the source located at the node with the number $n + 1$ and the sink at the node with the number $n + 2$. For each node $i$ such that $1  \\le  i  \\le  n$ add the arc $(n + 1, i)$ with a capacity $p_{i}$ and arc $(i, n + 2)$ with capacity $s_{i}$. Also, for each pair of nodes $i$ and $j$ such that $1  \\le  i < j  \\le  n$, add the arc $(i, j)$ with capacity $m$. The value of the maximum flow in this network is the answer to the problem. Since the network contains $O(n^{2})$ arcs, the usual flow search algorithms is not applicable here. Instead, we will find a capacity of the minimal cut in this network. The cut in this case is a partition of the set of all nodes from $1$ to $n + 2$ into two parts. Let $A$ be the part that contains the source and $B=\\{1,2,\\cdot\\cdot\\cdot,n,n+1,n+2\\}\\setminus A$ - all other nodes. Then the capacity of the cut is equal to $\\sum_{i\\in A}s_{i}+\\sum_{i\\in B}p_{i}+\\sum_{i<j,i\\in A,j\\in B}c$. Capacity of the minimal cut can be found using the following dynamic programming: $cut(i, j)$ will be the minimum capacity of the cut, which was built on the first $i$ nodes, such that the set $A$ contains exactly $j$ nodes other than the source. It is easy to get the formula for this dynamic: $cut(i, j) = min(cut(i - 1, j - 1) + s_{i}, cut(i - 1, j) + p_{i} + j * c)$. The answer to the problem can be obtained as $min_{j = 0, n} cut(n, j)$. The resulting complexity of this solution is $O(n^{2})$. To fit in memory limit you should store only two consecutive rows during the computation of the dynamic.",
    "tags": [
      "dp",
      "flows",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "724",
    "index": "F",
    "title": "Uniformly Branched Trees",
    "statement": "A tree is a connected graph without cycles.\n\nTwo trees, consisting of $n$ vertices each, are called isomorphic if there exists a permutation $p: {1, ..., n} → {1, ..., n}$ such that the edge $(u, v)$ is present in the first tree if and only if the edge $(p_{u}, p_{v})$ is present in the second tree.\n\nVertex of the tree is called internal if its degree is greater than or equal to two.\n\nCount the number of different non-isomorphic trees, consisting of $n$ vertices, such that the degree of each internal vertex is \\textbf{exactly} $d$. Print the answer over the given prime modulo $mod$.",
    "tutorial": "At first, we will calculate the following dynamic programming: $trees(i, j, k)$ will be the number of rooted trees, where the root has exactly $j$ directed subtrees, the maximum size of which does not exceed $k$, and the degree of internal vertices is equal to $d$ (except for the root). Calculation of the value of the dynamics for fixed parameters is divided into two cases: there are on subtrees of size $k$ at all. In this case, you can take the value of $trees(i, j, k - 1)$; there are $t > 0$ subtrees of size $k$. In this case, we got $t r e e s(i-t\\ast k,\\ j-t,\\ k-1)\\ast\\left({}^{t r e e s(k,\\ d-1,\\ k-1)+t-1}\\right)$ different trees. The main idea here is that we do not distinguish trees that differ only by a permutation of the sons for some vertices (this is where the number of combinations come from). It's enough to set some order in which we will place the sons of all vertices. In this case, they are arranged in the order of ascending sizes and the index number of its subtrees (all the trees of fixed size can be written in one big list and enumerated). Now we need to count the number of unrooted trees. Let's get rid of this restriction, by rooting all the trees using some vertex. For this vertex, we will take the centroid (the vertex, after removing which, the tree splits into connected components, with the sizes not larger than the half of the original size of the tree). The advantage of this choice is that any tree always have either one or two centroids. The number of trees that have exactly one centroid is equal to $t r e e s(n,\\ d,\\lfloor{\\frac{n}{2}}\\rfloor))$. The fact that we chose the centroid, implies that the size of subtrees cannot exceed $\\textstyle{\\left|{\\frac{n}{2}}\\right|}$. The number of trees that have exactly two centroids is equal to $\\left(t r e e s({\\frac{n}{2}},\\ d{-1},\\ \\ {\\frac{n}{2}}-1)+1\\right)$ if $n$ is divisible by $2$, and zero otherwise. If there are two centroids, they will be connected by an edge, and the removing of this edge will split the graph into two parts, each of which will contain exactly $\\frac{n t}{2}$ vertices. The resulting complexity of this solution is $O(n^{2} * d^{2})$.",
    "tags": [
      "combinatorics",
      "dp",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "724",
    "index": "G",
    "title": "Xor-matic Number of the Graph",
    "statement": "You are given an undirected graph, constisting of $n$ vertices and $m$ edges. Each edge of the graph has some non-negative integer written on it.\n\nLet's call a triple $(u, v, s)$ \\textbf{interesting}, if $1 ≤ u < v ≤ n$ and there is a path (\\textbf{possibly non-simple}, i.e. it can visit the same vertices and edges multiple times) between vertices $u$ and $v$ such that xor of all numbers written on the edges of this path is equal to $s$. \\textbf{When we compute the value s for some path, each edge is counted in xor as many times, as it appear on this path.} It's not hard to prove that there are finite number of such triples.\n\nCalculate the sum over modulo $10^{9} + 7$ of the values of $s$ over all \\textbf{interesting} triples.",
    "tutorial": "Without loss of generality, let's assume that the graph is connected. If not, we will calculate the answer for each connected component and then sum them up. Let's choose two arbitrary vertices $u$ and $v$ such that $u < v$ and try to find all the interesting triples of the form $(u, v, ...)$. Let's find any path $p_{0}$, connecting these two vertices and calculate the xor of the numbers written on the edges of the path. Let's denote the obtained xor as $s_{0}$. Then take an arbitrary interesting triple $(u, v, s_{1})$ and any path $p_{1}$, with the xor of the numbers on it equals to $s_{1}$. Consider the cycle of the following form: let's go through the first path $p_{0}$, and then through the reversed direction of the second path $p_{1}$. Thus, we will get a cycle containing the vertex $u$, with the xor of the numbers on it equals to $s_{0}\\oplus s_{1}$. On the other hand, we can take any cycle which starts and ends in the vertex $u$, with the xor of the numbers on it equals to $s_{2}$, and insert it before the path $p_{0}$. Thus, we will get the path $p_{2}$, with the xor of the numbers on it equals to $s_{0}\\oplus s_{2}$, i.e. we will get an interesting triple $(u,\\ v,\\ s_{0}\\oplus s_{2})$. Note that in the same manner we can add cycle, that doesn't pass through the vertex $u$. To do this, we can find any path from the vertex $u$ to some of the vertices of the cycle, then go through the cycle itself, and then add the edges of same path in reversed order. As a result, all the edges of this path will be included in the resulting path twice and will not affect the resulting xor. From this we get the following idea: for a fixed pair of vertices, we can find some path between them, and then add different cycles to it to obtain all interesting triples. Basis of the cycle space of the graph can be obtained as follows: we find some spanning tree, and then for each edge, which is not included in that tree, add the cycle containing this edge and the path in the tree connecting its endpoints to the basis. For each cycle of the basis we will find xor of the numbers written in its edges. Now, let's move from the operation of taking xor of numbers to the operations with vectors. To do this, we can represent all the numbers in the graph in the form of vectors of length $60$, where $i$-th element of the vector will be equal to the value of the $i$-th bit in this number. Then taking xor of two numbers will be reduced to the addition of two vectors over the modulo $2$. As a result, we can move from cycle space of the graph to the space $\\mathbb{Z}_{2}^{00}$. A linear combination of cycles of the graph, gives us a linear combination of vectors corresponding to xor of the numbers on the edges of the cycles. The set of linear combinations of the vectors form a subspace of $\\mathbb{Z}_{2}^{00}$. We can find the basis of this subspace using Gaussian elimination. Let's denote the dimension of the basis as $r$. Then, for every pair of vertices $u$ and $v$, the amount of interest triples for these vertices is equal to $2^{r}$, and all values of the parameter $s$ for these triples can be obtained by adding the vector corresponding to an arbitrary path between these vertices to the described subspace. Let's choose a pair of vertices $u$ and $v$ and some bit $i$ and count how many times the value of $2^{i}$ will appear in the resulting sum. Let's assume that the value of the $i$-th bit on the path between the chosen vertices is equal to $b$. If $i$-th bit is equal to one for at least one vector of the basis, then this bit will be equal to one in the $2^{r - 1}$ triples. Otherwise, $i$-th bit in all the $2^{r}$ triples will be equal to $b$. Let's start the depth first search from some vertex fixed vertex $r$, and find a paths to each vertex of the graph. For each of this paths we calculate the value of xor of the numbers on them. For each bit $i$ let's count how many times it was equal to zero and one on these paths (denote this numbers $zero_{i}$ and $one_{i}$). Then, for a fixed bit $i$, for exactly $zero_{i} * one_{i}$ pairs of vertices it will be equal to one on the path connecting this vertices, and for $\\ (t^{c e r o_{i}})+\\binom{o n e_{i}}{2})$ pairs it will be zero. Thus, if the $i$-th bit is equal to one in at least one vector from the basis, we should add $2^{i}*{\\binom{n}{2}}*2^{r-1}$ to the answer. In the other case, if bits $i$ is equal to zero for all vectors from the basis, we should add $2^{i} * zero_{i} * one_{i} * 2^{r}$ to the answer. The resulting complexity of this solution is $O(m * log 10^{18})$.",
    "tags": [
      "bitmasks",
      "graphs",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "725",
    "index": "A",
    "title": "Jumping Ball",
    "statement": "In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of $n$ bumpers. The bumpers are numbered with integers from $1$ to $n$ from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position $i$ it goes one position to the right (to the position $i + 1$) if the type of this bumper is '>', or one position to the left (to $i - 1$) if the type of the bumper at position $i$ is '<'. If there is no such position, in other words if $i - 1 < 1$ or $i + 1 > n$, the ball falls from the game field.\n\nDepending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.",
    "tutorial": "Let's divide the sequence into three parts: a sequence (possibly, empty) of '<' bumpers in the beginning, a sequence (possibly, empty) of '>' bumpers in the end, and a sequence (possibly, empty) of any type bumpers between the first and the second parts. It can be easily seen that if the ball starts in the left part, it falls from the left side; if the ball starts in the right part, it falls from the right side; if the ball starts anywhere in the middle part, it never reaches the other parts and doesn't fall from the field. Thus, the answer is the number of '<' bumpers in the beginning plus the number of '>' bumpers in the end. The complexity of the solution is $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "725",
    "index": "B",
    "title": "Food on the Plane",
    "statement": "A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with $1$ from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats 'd', 'e' and 'f' are located to the right. Seats 'a' and 'f' are located near the windows, while seats 'c' and 'd' are located near the aisle.\n\nIt's lunch time and two flight attendants have just started to serve food. They move from the first rows to the tail, always maintaining a distance of two rows from each other because of the food trolley. Thus, at the beginning the first attendant serves row $1$ while the second attendant serves row $3$. When both rows are done they move one row forward: the first attendant serves row $2$ while the second attendant serves row $4$. Then they move three rows forward and the first attendant serves row $5$ while the second attendant serves row $7$. Then they move one row forward again and so on.\n\nFlight attendants work with the same speed: it takes exactly $1$ second to serve one passenger and $1$ second to move one row forward. Each attendant first serves the passengers on the seats to the right of the aisle and then serves passengers on the seats to the left of the aisle (if one looks in the direction of the cockpit). Moreover, they always serve passengers in order from the window to the aisle. Thus, the first passenger to receive food in each row is located in seat 'f', and the last one — in seat 'c'. Assume that all seats are occupied.\n\nVasya has seat $s$ in row $n$ and wants to know how many seconds will pass before he gets his lunch.",
    "tutorial": "The only observation one has to make to solve this problem is that flight attendants move $4$ rows forward at $16$ seconds. Here, $6$ seconds are required to serve everyone in one row, then $1$ second to move forward, $6$ seconds to serve one more row, then $3$ more seconds to move. Thus, $6 + 1 + 6 + 3 = 16$ in total. Now, if we are interested in seat $c$ in row $x$, the answer is equal to the answer for seat $c$ in row $xmod4 + 1$ plus $\\left|{\\frac{x-1}{4}}\\right|\\cdot16$. Note, that we use integer division, so it's not equal to $(x - 1) \\cdot 4$. Solution: compute the serving time for first $4$ rows. Find the answer using formula above.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "725",
    "index": "C",
    "title": "Hidden Word",
    "statement": "Let’s define a grid to be a set of tiles with $2$ rows and $13$ columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid:\n\n\\begin{center}\n\\begin{verbatim}\nABCDEFGHIJKLM\nNOPQRSTUVWXYZ\n\\end{verbatim}\n\\end{center}\n\nWe say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself.\n\nA sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, \"ABC\" is a path, and so is \"KXWIHIJK\". \"MAB\" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself).\n\nYou’re given a string $s$ which consists of $27$ upper-case English letters. Each English letter \\textbf{occurs at least once} in $s$. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string $s$. If there’s no solution, print \"Impossible\" (without the quotes).",
    "tutorial": "1. The input string $s$ contains 27 letters and it contains every letter in the English alphabet. The English alphabet has 26 letters, so there is exactly one repeated letter. 2. If the instances of the repeated letter are adjacent in the string, there can be no solution. That's because every English letter occurs in $s$ and the solution grid contains exactly 26 tiles, so any solution must have all letters distinct. Consider the tile containing the repeated letter. None of the tiles adjacent to it can contain the repeated letter because the letters of the grid are distinct, so the grid doesn't contain $s$. 3. Otherwise, there is a solution. Delete the second occurrence of the repeated letter and write the resulting string in circular order. For example, if the string with the repeated letter deleted is ABCDEFGHIJKLMNOPQRSTUVWXYZ, we write this to the grid: ABCDEFGHIJKLM ZYXWVUTSRQPON Then we rotate the grid, one step at a time, until it contains $s$. For example, if the above grid isn't a valid solution, we next try this: ZABCDEFGHIJKL YXWVUTSRQPONM And then this: YZABCDEFGHIJK XWVUTSRQPONML This will eventually give us a solution. Suppose the repeated letter lies between G and H in the original string. In each rotation, there are 2 letters adjacent to both G and H in the grid (in the above examples these letters are S and T, then Q and R, then O and P). When we rotate the string by a step, the adjacent letters advance by 1 or 2 steps. Eventually the repeated letter will be adjacent to both G and H, and this will yield a solution.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "725",
    "index": "D",
    "title": "Contest Balloons",
    "statement": "One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by $1$. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.\n\nYou should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.\n\nA contest has just finished. There are $n$ teams, numbered $1$ through $n$. The $i$-th team has $t_{i}$ balloons and weight $w_{i}$. It's guaranteed that $t_{i}$ doesn't exceed $w_{i}$ so nobody floats initially.\n\nLimak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.\n\nWhat is the best place Limak can get?",
    "tutorial": "Previous ones describe how to find a correct approach. It may lead to a slightly more complicated solution, but you will learn something for sure. To come up with a solution, you must try iterating over some value or maybe binary searching an optimal value. Let's list a few reasonable ideas. Try to binary search the answer (for fixed final place of Limak you must say if he can get at least this place). Or iterate over the number of disqualified teams (if Limak should beat exactly $i$ teams, what is the best place he can get?). Or iterate over the number of balloons Limak should give away. The last idea turns out to be fruitful. The first observation is that you don't have to consider every possible number of balloons to give away. We can assume that the final number of balloons will be either $0$ or $t_{i}$ for some $i$. Otherwise Limak could give away some more balloons and his place won't be worse (if there are no more teams, let's imagine he can destroy them). We use here a simple observation that the $i$-th team either will be disqualified or will still have exactly $t_{i}$ balloons, i.e. values $t_{i}$ won't change. We have $O(n)$ possibilities for the final number of balloons. Let's first solve a problem in $O(n^{2}\\cdot\\log{n})$ by considering possibilities separately, each in $O(n\\cdot\\log n)$. Let's say Limak will have $k$ balloons at the end. He can give away $t_{1} - k$ balloons. He should try to get rid of teams with $t_{i} > k$ because worse teams don't affect his place. You should sort teams with $t_{i} > k$ by the number of balloons they need to get disqualified i.e. $w_{i} - t_{i} + 1$. It's easiest for Limak to get rid of teams with small value of $w_{i} - t_{i} + 1$ so you should just check how many of those values can be chosen so that the sum of them won't exceed $t_{1} - k$. It turns out to be possible to improve the above by considering possibilities in the decreasing order. Think what happens when you decrease $k$. Some more teams become a possible target and you should consider their values $w_{i} - t_{i} + 1$. A sorted set of those values should be useful. Try to invent a solution yourself now. Then you can see one simple version in the next paragraph. Now let's see an $O(n\\cdot\\log n)$ greedy solution. Create a variable $k$ representing the final number of balloons Limak has, initially $k = t_{1}$. Create and maintain a multiset with values $w_{i} - t_{i} + 1$ of teams better than the current $k$, i.e. teams with $t_{i} > k$. If it makes sense to give away some more balloons, Limak has to eliminate at least one of those better teams (otherwise he can stop now). It's easiest to eliminate a team with the smallest $w_{i} - t_{i} + 1$, so we can just remove the smallest element from the set and decrease $k$ by its value. Maybe some more teams become better than the current $k$ and you should add those to the multiset. Note that the multiset contains exactly those teams which would win with Limak in the current scenario, so after every change of $k$ you can update the answer 'ans = min(ans, my_multiset.size() + 1)'. Remember to stop if $k$ becomes smaller than $0$.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "725",
    "index": "E",
    "title": "Too Much Money",
    "statement": "Alfred wants to buy a toy moose that costs $c$ dollars. The store doesn’t give change, so he must give the store exactly $c$ dollars, no more and no less. He has $n$ coins. To make $c$ dollars from his coins, he follows the following algorithm: let $S$ be the set of coins being used. $S$ is initially empty. Alfred repeatedly adds to $S$ the highest-valued coin he has such that the total value of the coins in $S$ after adding the coin doesn’t exceed $c$. If there is no such coin, and the value of the coins in $S$ is still less than $c$, he gives up and goes home. Note that Alfred never removes a coin from $S$ after adding it.\n\nAs a programmer, you might be aware that Alfred’s algorithm can fail even when there is a set of coins with value exactly $c$. For example, if Alfred has one coin worth $3, one coin worth $4, and two coins worth $5, and the moose costs $12, then Alfred will add both of the $5 coins to $S$ and then give up, since adding any other coin would cause the value of the coins in $S$ to exceed $12. Of course, Alfred could instead combine one $3 coin, one $4 coin, and one $5 coin to reach the total.\n\nBob tried to convince Alfred that his algorithm was flawed, but Alfred didn’t believe him. Now Bob wants to give Alfred some coins (in addition to those that Alfred already has) such that Alfred’s algorithm fails. Bob can give Alfred any number of coins of any denomination (subject to the constraint that each coin must be worth a positive integer number of dollars). There can be multiple coins of a single denomination. He would like to minimize the total value of the coins he gives Alfred. Please find this minimum value. If there is no solution, print \"Greed is good\". You can assume that the answer, if it exists, is positive. In other words, Alfred's algorithm will work if Bob doesn't give him any coins.",
    "tutorial": "1. If there is a solution where Bob gives Alfred $n$ coins, then there is a solution where Bob gives Alfred only one coin. We can prove it by induction on $n$. The base case $n = 1$ is trivial. In the inductive case, let $x$ and $y$ be the highest-valued coins that Bob uses (where $x  \\ge  y$). The sequence of coins chosen by Alfred looks like this: $c_{1}, c_{2}, ..., c_{a}, x, c_{a + 1}, ..., c_{b}, y, ...$ I claim that if we replace $x$ and $y$ with a single coin worth $x + y$ dollars then we will still have a solution. Clearly $x + y$ will be chosen by Alfred no later than Alfred chose $x$ in the original sequence. So if some coin would have caused Alfred to have more than $c$ dollars and so was skipped by Alfred, it will still be skipped by Alfred in the new solution since Alfred has no less money in $S$ than he did in the original solution. Likewise, we know that $x+y+\\sum c_{i}<c$ 2. After pre-processing the input, we can simulate Alfred's algorithm in $O({\\sqrt{c}})$ with the following process: find the next coin that Alfred will use (this can be done in $O(1)$ with $O(c)$ pre-processing). Suppose there are x copies of this coin in the input, the coin is worth y dollars, and Alfred has z dollars. Then Alfred will use $min(x, z / y)$ copies of this coin. We can find this value in $O(1)$. Now suppose this algorithm has run for $k$ steps. Then $y$ has taken $k$ distinct values and Alfred has used at least one coin of each value, so the coins in $S$ are worth at least $k(k + 1) / 2$. Thus, after $O({\\sqrt{c}})$ steps the value of the coins in $S$ will exceed $c$. So this process runs in $O({\\sqrt{c}})$ time. 3. Try every possible solution from $1$ to $c$ and check if it works. The complexity is $O(c{\\sqrt{c}})$.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "725",
    "index": "F",
    "title": "Family Photos",
    "statement": "Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first.\n\nThere are $n$ stacks of photos. Each stack contains \\textbf{exactly two} photos. In each turn, a player may take only a photo from the top of one of the stacks.\n\nEach photo is described by two non-negative integers $a$ and $b$, indicating that it is worth $a$ units of happiness to Alice and $b$ units of happiness to Bonnie. Values of $a$ and $b$ might differ for different photos.\n\nIt's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively.\n\nThe players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has $x$ happiness and Bonnie has $y$ happiness at the end, you should print $x - y$.",
    "tutorial": "1. We are going to transform the stacks in such a way that every move is no worse than passing. 2. Consider a stack with values $a, b, c, d$. (The top photo is worth $a$ for Alice and $b$ for Bonnie and the bottom photo is worth $c$ for Alice and $d$ for Bonnie.) If $a + b  \\ge  c + d$ then taking the top photo is no worse than passing. We can prove it by rearranging the inequality: $a - d  \\ge  c - b$. $a - d$ is the value of the stack, from Alice's perspective, if Alice gets to move first. $c - b$ is the value, from Alice's perspective, if Bonnie gets to move first. So Alice doesn't incur a loss by making the first move, which means that a move here is no worse than passing. By symmetry, the same argument applies to Bonnie. 3. If $a + b < c + d$ then both players would rather have the other player make the first move. However, this doesn't necessarily mean that the stack will be ignored by the players. If $a > d$ then Alice can still profit by making the first move here. Since it would be even better for Alice if Bonnie made the first move, Alice can ignore this stack until Bonnie passes, and only then make a move here. So if $a > d$ then this stack is equivalent to a single photo with value $(a - d, d - a)$. 4. Likewise, if $b > c$ then the stack is equivalent to a single photo with value $(c - b, b - c)$. 5. If $a + b < c + d$ and neither (3) nor (4) apply, both players will ignore the stack and we can simply delete it. 6. Now every move is no worse than passing, so every photo will eventually be taken. For every photo $(a, b)$, replace it with a photo $\\textstyle{\\binom{a+b}{2}},{\\frac{a+b}{2}}$ and add $\\frac{a-b}{2}$ to the final answer. This is equivalent to the original problem because ${\\frac{a-b}{2}}+{\\frac{a+b}{2}}=a$ and ${\\frac{a-b}{2}}-{\\frac{a+b}{2}}=-b$. 7. Now every photo is worth the same to both players, so we can sort them in descending order and assign the photos with even indices to Alice and the photos with odd indices to Bonnie. Since every stack in the transformed problem has $a + b  \\ge  c + d$, this guarantees that the top photo will be taken before the bottom photo in each stack. The complexity is $O(n\\log n)$.",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "725",
    "index": "G",
    "title": "Messages on a Tree",
    "statement": "Alice and Bob are well-known for sending messages to each other. This time you have a rooted tree with Bob standing in the root node and copies of Alice standing in each of the other vertices. The root node has number $0$, the rest are numbered $1$ through $n$.\n\nAt some moments of time some copies of Alice want to send a message to Bob and receive an answer. We will call this copy the initiator. The process of sending a message contains several steps:\n\n- The initiator sends the message to the person standing in the parent node and begins waiting for the answer.\n- When some copy of Alice receives a message from some of her children nodes, she sends the message to the person standing in the parent node and begins waiting for the answer.\n- When Bob receives a message from some of his child nodes, he immediately sends the answer to the child node where the message came from.\n- When some copy of Alice (except for initiator) receives an answer she is waiting for, she immediately sends it to the child vertex where the message came from.\n- When the initiator receives the answer she is waiting for, she doesn't send it to anybody.\n- There is a special case: a copy of Alice can't wait for two answers at the same time, so if some copy of Alice receives a message from her child node while she already waits for some answer, she rejects the message and sends a message saying this back to the child node where the message came from. Then the copy of Alice in the child vertex processes this answer as if it was from Bob.\n- The process of sending a message to a parent node or to a child node is instant but a receiver (a parent or a child) gets a message after $1$ second.\n\nIf some copy of Alice receives several messages from child nodes at the same moment while she isn't waiting for an answer, she processes the message from the \\textbf{initiator} with the smallest number and rejects all the rest. If some copy of Alice receives messages from children nodes and also receives the answer she is waiting for at the same instant, then Alice first processes the answer, then immediately continue as normal with the incoming messages.\n\nYou are given the moments of time when some copy of Alice becomes the initiator and sends a message to Bob. For each message, find the moment of time when the answer (either from Bob or some copy of Alice) will be received by the initiator.\n\nYou can assume that if Alice wants to send a message (i.e. become the initiator) while waiting for some answer, she immediately rejects the message and receives an answer from herself in no time.",
    "tutorial": "Hint: Sort the queries somehow so that the answer on every query will depend only on previous queries. After that, use heavy-light decomposition to answer the queries quickly. Solution: First, sort the queries by $d[x_{i}] + t_{i}$, where $d[a]$ is the depth of the vertex $a$. It can be easily shown that the answer for every query depends only on the previous ones, so we can proceed them one by one. Also, after the sort we can assume that any query blocks the path from the initiator to the node that rejects the query in one instant, so we can only care about unblocking times. Suppose some node $v$ unblocks at the moment $T_{v}$. Which queries will be rejected by $v$ if they reach it? Obviously, the queries which have $v$ on the path from the initiator to the root and for which $t_{i} + d[x_{i}] - d[v] < T_{v}$ holds. Let's rewrite this as follows: $T_{v} + d[v] > t_{i} + d[x_{i}]$. Now the left part depends only on the blocking node, and the right part depends only on the query. Let's define $B_{v} = T_{v} + d[v]$. Now we have an $O(nm)$ solution: we proceed queries one by one, for each query we find such a node $v$ on the path from $x_{i}$ to the root so that the $B_{v} > t_{i} + d[x_{i}]$ holds for the node, and it has the maximum depth, and then reassign values of $B_{v}$ on the path from $x_{i}$ to $v$. To make the solution faster, we have to construct the heavy-light decomposition on the tree. Now let's store the values $B_{v}$ in segment trees on the decomposed paths. To assign on the path we should note that the values $B_{v}$ form arithmetical progression. To query the deepest node we should store the maximum value of $B_{v}$ in every node of the segment trees. This solution works in $O(m\\log^{2}(n))$.",
    "tags": [],
    "rating": 3300
  },
  {
    "contest_id": "727",
    "index": "A",
    "title": "Transformation: from A to B",
    "statement": "Vasily has a number $a$, which he wants to turn into a number $b$. For this purpose, he can do two types of operations:\n\n- multiply the current number by $2$ (that is, replace the number $x$ by $2·x$);\n- append the digit $1$ to the right of current number (that is, replace the number $x$ by $10·x + 1$).\n\nYou need to help Vasily to transform the number $a$ into the number $b$ using only the operations described above, or find that it is impossible.\n\nNote that in this task you are not required to minimize the number of operations. It suffices to find any way to transform $a$ into $b$.",
    "tutorial": "Let's solve this problem in reverse way - try to get the number $A$ from $B$. Note, that if $B$ ends with 1 the last operation was to append the digit $1$ to the right of current number. Because of that let delete last digit of $B$ and move to the new number. If the last digit is even the last operation was to multiply the current number by $2$. Because of that let's divide $B$ on 2 and move to the new number. In the other cases (if $B$ ends with odd digit except 1) the answer is <<NO>>. We need to repeat described algorithm after we got the new number. If on some step we got the number equals to $A$ we find the answer, and if the new number is less than $A$ the answer is <<NO>>.",
    "tags": [
      "brute force",
      "dfs and similar",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "727",
    "index": "B",
    "title": "Bill Total Value",
    "statement": "Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format \"{$name_{1}price_{1}name_{2}price_{2}...name_{n}price_{n}$}\", where $name_{i}$ (name of the $i$-th purchase) is a non-empty string of length not more than $10$, consisting of lowercase English letters, and $price_{i}$ (the price of the $i$-th purchase) is a non-empty string, consisting of digits and dots (decimal points). It is possible that purchases with equal names have different prices.\n\nThe price of each purchase is written in the following format. If the price is an integer number of dollars then cents are not written.\n\nOtherwise, after the number of dollars a dot (decimal point) is written followed by cents \\textbf{in a two-digit format} (if number of cents is between $1$ and $9$ inclusively, there is a leading zero).\n\nAlso, every three digits (from less significant to the most) in dollars are separated by dot (decimal point). No extra leading zeroes are allowed. The price always starts with a digit and ends with a digit.\n\nFor example:\n\n- \"234\", \"1.544\", \"149.431.10\", \"0.99\" and \"123.05\" are valid prices,\n- \".333\", \"3.33.11\", \"12.00\", \".33\", \"0.1234\" and \"1.2\" are not valid.\n\nWrite a program that will find the total price of all purchases in the given bill.",
    "tutorial": "In this problem we need to simply implement calculating the sum of prices. At first we need to find all prices - sequences of consecutive digits and dots. Then we need to find the integer number of dollars in each price and count integer sum of dollars in the variable $r$. Also we need to make the same thing for cents and calculate in the variable $c$. After process all prices we need to transform cents in rubles, i. e. add to $r$ the value $c / 100$, and $c$ assign to $c%100$. Now we need only to print the answer and do not forget, that for cents if $c < 10$ we need to print 0 at first and then $c$ because the number of cents must consisting of two digits like wrote in the statement.",
    "tags": [
      "expression parsing",
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "727",
    "index": "C",
    "title": "Guess the Array",
    "statement": "This is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in Pascal — flush(output).\n\nIn this problem you should guess an array $a$ which is unknown for you. The only information you have initially is the length $n$ of the array $a$.\n\nThe only allowed action is to ask the sum of two elements by their indices. Formally, you can print two indices $i$ and $j$ (the indices should be \\textbf{distinct}). Then your program should read the response: the single integer equals to $a_{i} + a_{j}$.\n\nIt is easy to prove that it is always possible to guess the array using at most $n$ requests.\n\nWrite a program that will guess the array $a$ by making at most $n$ requests.",
    "tutorial": "At first let's make three queries on sum $a_{1} + a_{2} = c_{1}$, $a_{1} + a_{3} = c_{2}$ and $a_{2} + a_{3} = c_{3}$. After that we got a system of three equations with three unknown variables $a_{1}, a_{2}, a_{3}$. After simple calculating we got that $a_{3} = (c_{3} - c_{1} + c_{2}) / 2$. The values of $a_{1}$ and $a_{2}$ now can be simply found. After that we now the values of $a_{1}, a_{2}, a_{3}$ and spent on it 3 queries. Then for all $i$ from 4 to $n$ we need to make the query $a_{1} + a_{i}$. If the next sum equals to $c_{i}$ then $a_{i} = c_{i} - a_{1}$ (recall that we already know the value of $a_{1}$). So we guess the array with exactly $n$ queries.",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "727",
    "index": "D",
    "title": "T-shirts Distribution",
    "statement": "The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.\n\nDuring the registration, the organizers asked each of the $n$ participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.\n\nWrite a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:\n\n- the size he wanted, if he specified one size;\n- any of the two neibouring sizes, if he specified two sizes.\n\nIf it is possible, the program should find any valid distribution of the t-shirts.",
    "tutorial": "Let in the array $cnt$ we store how many t-shirts of each size are in the typography. At first let's give the t-shirts to participants who wants exactly one size of the t-shirt and decrease appropriate values in $cnt$. If in some moment we have no t-shirt of needed size the answer is \"NO\". Now we need to give the t-shirts to participants who wants t-shirt with one of two sizes. Let's use greedy. At first we need to give t-shirts with size S to participants who wants it or t-shirt with size M. After that let's move to the t-shirts with size M. At first let's give this t-shirts to participants who wants it or t-shirts with size S and do not already have the t-shirt. After that if t-shirts with size M remain we need to give this t-shirts to participants who wants it or t-shirts with sizes L. Similarly, we must distribute the remaining t-shirts sizes. If after all operations not each participant has the t-shirt the answer is \"NO\". In the other case we found the answer.",
    "tags": [
      "constructive algorithms",
      "flows",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "727",
    "index": "E",
    "title": "Games on a CD",
    "statement": "Several years ago Tolya had $n$ computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD \\textbf{in clockwise order}. The names were distinct, the length of each name was equal to $k$. The names didn't overlap.\n\nThus, there is a cyclic string of length $n·k$ written on the CD.\n\nSeveral years have passed and now Tolya can't remember which games he burned to his CD. He knows that there were $g$ popular games that days. All of the games he burned were among these $g$ games, and \\textbf{no game was burned more than once}.\n\nYou have to restore any valid list of games Tolya could burn to the CD several years ago.",
    "tutorial": "With help of Aho Corasick algorithm we need to build the suffix tree on the set of game names ans in the vertex of the tree (which correspond to the name of some game, this vertex will be on the depth $k$) we will store the number of this game. Builded tree allows to add symbols to some string one by one and find the vertex which corresponds to the longest prefix from all prefixes of game names which equals to the suffix of our string. If the length of this prefix equals to $k$ the suffix equals to some game name. Let's write the string which wrote on disk twice and calculate $idx_{i}$ - the index of the game which name equals to substring of doubled string from index $i - k + 1$ to index $i$ inclusively (if such index does not exist it's equals to $- 1$). Now we need to iterate through the indexes of symbols which is last in the name of some game. We can iterate from $0$ to $k - 1$. With fixed $f$ we need to check that all game names with last symbols in indexes $f+i k\\;{\\mathrm{~mod~}}n k$ for $0  \\le  i < n$ are different (for it we need to check that among $idx_{(f + ik)%nk + nk}$ there is no $- 1$ and all of them are different). If it is performed - print YES and now it is easy to restore the answer. If the condition failed for all $f$ - print NO. Asymptotic behavior of this solution - $O(n k+\\sum|t_{i}|)$",
    "tags": [
      "data structures",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "727",
    "index": "F",
    "title": "Polycarp's problems",
    "statement": "Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.\n\nHe sent to the coordinator a set of $n$ problems. Each problem has it's quality, the quality of the $i$-th problem is $a_{i}$ ($a_{i}$ can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index $1$, the hardest problem has index $n$.\n\nThe coordinator's mood is equal to $q$ now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality $b$, the value $b$ is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems.\n\nIf after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset.\n\nPolycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has $m$ guesses \"the current coordinator's mood $q = b_{i}$\".\n\nFor each of $m$ guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to $0$ while he reads problems from the easiest of the remaining problems to the hardest.",
    "tutorial": "At first let's solve the problem for one value of $Q$. It is easy to show that optimal solution is the following: add to the set of tasks next task with quality equals to $a_{i}$. While the value of mood (the sum of qualities and $Q$) is less than 0, delete from the set of remaining task the task with worst quality. The quality of such task will be less than 0, because we will not spoil the mood on previous tasks. This solution can be implement with help of structures std::set or std::priority_queue. Described solution helps us to find answer on the query in $O(n\\log n)$, but $O(m n\\log n)$ does not fill in time limit. Note, that while we increase $Q$ the number of deleted problems does not increase and the possible number of such numbers is only $n$. So we need to solve the following task: for $0  \\le  x  \\le  n$ calculate minimum value of $Q$ that the number of deleted problems does not exceed $x$. This problem can be easily solved for each $x$ with help of binary search in $O(n\\log n\\log M A X Q)$, in sum for all $x$ we got $O(n^{2}\\log n\\log M A X Q)$. Also we have an interest only $m$ values of $Q$, we can make the binary search only on this values and in total we got $O(n^{2}\\log{n}\\log{m})$ For each answer $x$ with help of stored values we need to find the first answer which minimum value of $Q$ does not more than $Q$ in the query. We can do it easy in $O(n)$ or with binary search in $O(\\log n)$ (because the values $Q$ for the answers does not increase). In total we will get $O(mn)$ or $O(m\\log n)$ in sum. The best asymptotic behavior is $O(n^{2}\\log n\\log m+m\\log n)$ but solutions which work in $O(n^{2}\\log n\\log M A X Q+m n)$ also passed all tests.",
    "tags": [
      "binary search",
      "dp",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "729",
    "index": "A",
    "title": "Interview with Oleg",
    "statement": "Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string $s$ consisting of $n$ lowercase English letters.\n\nThere is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.\n\nThe fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.\n\nTo print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.\n\nPolycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!",
    "tutorial": "In this problem it is enough to iterate through the given string from the left to the right and find the longest substring like \"ogo...go\" from each position of the string. If such substring was founded add \"***\" and move to the end of this substring. In the other case, add current letter to the answer and move to the next position.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "729",
    "index": "B",
    "title": "Spotlights",
    "statement": "Theater stage is a rectangular field of size $n × m$. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.\n\nYou are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.\n\nA position is good if two conditions hold:\n\n- there is no actor in the cell the spotlight is placed to;\n- there is at least one actor in the direction the spotlight projects.\n\nCount the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.",
    "tutorial": "Let's find the number of good positions where projector directed to the left. It can be done separately for each row. To make it we need to iterate through the row from the left to the right and store information about we met '{1}', for example, in the variable $f$. Then if we process the current value: if it is equal to '0', add one to the answer if $f$ equals to true; if it is equal to '1', then $f$ := true. We can find the answer for the 3 remaining directions in the same way.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "729",
    "index": "C",
    "title": "Road to Cinema",
    "statement": "Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in $t$ minutes. There is a straight road of length $s$ from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point $0$, and the cinema is at the point $s$.\n\nThere are $k$ gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.\n\nThere are $n$ cars in the rental service, $i$-th of them is characterized with two integers $c_{i}$ and $v_{i}$ — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity $v_{i}$. All cars are completely fueled at the car rental service.\n\nEach of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers $1$ kilometer in $2$ minutes, and consumes $1$ liter of fuel. In the accelerated mode a car covers $1$ kilometer in $1$ minutes, but consumes $2$ liters of fuel. The driving mode can be changed at any moment and any number of times.\n\nYour task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in $t$ minutes. Assume that all cars are completely fueled initially.",
    "tutorial": "Let's note that there is a value for the fuel tank capacity (call it $w$), that if the car has the fuel tank capacity equal or more than $w$ it will be able to reach the cinema if time, else - will not be able. The value $w$ can be found with help of binary search because the function $can(w)$ (it is possible and it has enough time for such cur) is monotonic - in the beginning all values of this function is false, but after some moment the values of this function is always true. After we found $w$ it remain only to choose the cheapest car from the cars which fuel tank capacity equal or more than $w$. The function $can(w)$ can be realized with greedy algorithm. It is easy to write down the formula for find the number of kilometers which we can ride in fast mode if the nearest gas station is on the distance $x$ and we have $f$ liters of fuel in fuel tank: if $x > f$, then it is impossible to reach the nearest gas station and $can(w)$ must return false, if $x  \\le  f$, then it is possible to ride in the fast mode min($x$, $f - x$) kilometers. So, now we know how to find the value $can(w)$ in one iterate through the array of gas stations in the increasing order of their positions.",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "729",
    "index": "D",
    "title": "Sea Battle",
    "statement": "Galya is playing one-dimensional Sea Battle on a $1 × n$ grid. In this game $a$ ships are placed on the grid. Each of the ships consists of $b$ consecutive cells. No cell can be part of two ships, however, the ships \\textbf{can touch} each other.\n\nGalya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called \"hit\") or not (this case is called \"miss\").\n\nGalya has already made $k$ shots, all of them were misses.\n\nYour task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.\n\nIt is guaranteed that there is at least one valid ships placement.",
    "tutorial": "Let's note that in on the field there are $b$ zeroes in a row we must to shoot in at least one of them. We suppose that all ships was pressed to the right. Let's put the number 2 in cells where ships can be placed. Then iterate through the field from the left to the right and shoot in the cell if there is 0 and before it was $b - 1$ zero in a row. After iteration ended it is left only to shoot in any cell which value equals to 2. All described shoots are the answer for this problem.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "729",
    "index": "E",
    "title": "Subordinates",
    "statement": "There are $n$ workers in a company, each of them has a unique id from $1$ to $n$. \\textbf{Exaclty} one of them is a chief, his id is $s$. Each worker except the chief has exactly one immediate superior.\n\nThere was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself.\n\nSome of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.",
    "tutorial": "At first if the chief reported that he has one or more superiors let's change $a_{s}$ in zero. If there are workers who do not chiefs but reported that they have no superiors let assume that they reported a number which more than the other workers, for example, number $n$. It is necessarily that there must be the worker which has exactly one superior. If there is no such worker let's take the worker who reported the maximum number and change this number on 1. Then we need to make the same algorithm for numbers 2, 3, and etc. while there are workers, which have not yet considered. After we considered all workers the answer is the number of workers which reported numbers were changed.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "729",
    "index": "F",
    "title": "Financiers Game",
    "statement": "This problem has unusual memory constraint.\n\nAt evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared $n$ papers with the income of some company for some time periods. Note that the income can be positive, zero or negative.\n\nIgor and Zhenya placed the papers in a row and decided to take turns making moves. Igor will take the papers from the left side, Zhenya will take the papers from the right side. Igor goes first and takes $1$ or $2$ (on his choice) papers from the left. Then, on each turn a player can take $k$ or $k + 1$ papers from his side if the opponent took exactly $k$ papers in the previous turn. Players can't skip moves. The game ends when there are no papers left, or when some of the players can't make a move.\n\nYour task is to determine the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it.",
    "tutorial": "Let's solve this problem using dynamic programming. We can see that any position in the game can be described with three integers: the left and right bounds of the segment of papers that are still on the table, and the number of papers the previous player took; and who's turn it is. So, let $I_{lrk}$ be the game result if there were only papers from $l$ to $r$ initially, Igor moved first by taking $k$ or $k + 1$ papers. Similarly, let $Z_{lrk}$ be the same but Zhenya moved first. It can be easily seen that in general case $I_{l r k}=\\operatorname*{max}(Z_{l+k,r,k}+\\sum_{i=l}^{i<l+k}a_{i},Z_{l+k+1,r,k+1}+\\sum_{i=l}^{i<l+k+1}a_{i}),$ $Z_{l r k}=\\operatorname*{min}(I_{l,r-k,k}-\\sum_{i=r-k+1}^{t\\leq r}a_{i},I_{l,r-k-1,k+1}-\\sum_{i=r-k}^{1\\leq r}a_{i}).$ We need to carefully proceed the states where a player can't take the needed number of papers. The answer for the problem is $I_{1n1}$. At first sight it seems that this solution runs in $O(n^{3})$. However, it doesn't. What values can $l$, $r$ and $k$ be equal to? First, ${\\frac{k(k+1)}{2}}\\leq n$ because if the previous player took $k$ papers then there are at least as $1+2+3+...+k={\\frac{k(k{+}1)}{2}}$ already taken papers. So, $k$ is not greater than $\\sqrt{2n}$. Second, let's take a look at the difference between number of papers taken by Zhenya and Igor, i. e. at the value $d = (n - r) - (l - 1)$. We consider only cases in which both players made the same number of moves, so now it's Igor's move. Then $0  \\le  d  \\le  k - 1$. Indeed, on each turn Zhenya took as many papers as Igor did, or one paper more, but in the latter case the \"length\" of move increased. The length of move increased by $k - 1$ overall, so the difference is at most $k - 1$. Thus, we can describe the dynamic programming state with $l$, $d$ and $k$, and there are $O(n^{2})$ states in total. We don't consider states in which it's Zhenya's turn, instead, we try all his possible moves to compute the states. The overall complexity is $O(n^{2})$. I find it easier to code by the use of recursion and memoization.",
    "tags": [
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "731",
    "index": "A",
    "title": "Night at the Museum",
    "statement": "Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.\n\nEmbosser is a special devise that allows to \"print\" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:\n\nAfter Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.\n\nOur hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.",
    "tutorial": "In this problem you have to implement exactly what is written in the statement, i. e. you should find minimum number of rotations from letter a to the first letter in the input, then to the second one and so on. The only useful knowledge that may simplify the solution is that the distance between points $x$ and $y$ on the circle of length $l$ (26 in our case) is $min(|x - y|, l - |x - y|)$. This solution works in $O(|s|)$, and, of course, fits in time limit.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "731",
    "index": "B",
    "title": "Coupons and Discounts",
    "statement": "The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.\n\nTeams plan to train for $n$ times during $n$ consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be $a_{i}$ teams on the $i$-th day.\n\nThere are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two \\textbf{consecutive} days (two pizzas in total).\n\nAs Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.\n\nSereja wants to order exactly $a_{i}$ pizzas on the $i$-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day $n$.",
    "tutorial": "In a correct answer we may guarantee that for any two consecutive days we use no more than one coupon for bying pizzas in these days. Indeed, if we have two coupons for buying pizzas in days $i$ and $i + 1$, replace these coupons for two discounts, one for each of the days $i$ and $i + 1$. Consider the first day. According to the fact above, we may uniquely find the number of coupons for buying pizzas in 1 and 2 days we are going to use: it's either 0, if there is going to be an even number of pizzas in the first day, or 1 otherwise. The remaining pizzas in the first day will be bought by using discounts. If we use 1 coupon, then we may subtract 1 from the number of pizzas in the second day, and in both cases consider the second day and repeat the same actions. If at some moment we have the odd number of pizzas and we don't need any pizzas in the following day, then it is impossible to buy all pizzas using only coupons and discounts, and we may output \"NO\". If it didn't happen, then we were able to buy everything using only coupons and discounts. Such a solution works in $O(n)$.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "731",
    "index": "C",
    "title": "Socks",
    "statement": "Arseniy is already grown-up and independent. His mother decided to leave him alone for $m$ days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes.\n\nTen minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's $n$ socks is assigned a unique integer from $1$ to $n$. Thus, the only thing his mother had to do was to write down two integers $l_{i}$ and $r_{i}$ for each of the days — the indices of socks to wear on the day $i$ (obviously, $l_{i}$ stands for the left foot and $r_{i}$ for the right). Each sock is painted in one of $k$ colors.\n\nWhen mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses $k$ jars with the paint — one for each of $k$ colors.\n\nArseniy wants to repaint some of the socks in such a way, that for each of $m$ days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.\n\nThe new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of $m$ days.",
    "tutorial": "When solving this problem, it is convenient to use graph interpretation of the problem. Consider the graph, whose vertices correspond to the socks and edges connect those socks that Arseniy wears on some day. By the statement, we have to make that any two vertices connected by an edge have the same color. It actually means that any connected component should share the same color. For each connected component let's find out which color should we choose for it. In order to recolor the minimum possible number of vertices, we should leave the maximum number of vertices with their original color. It means that the optimum color is the color shared by the most number of vertices in this connected component. So, we have the following solution: consider all connected components, in each component choose the most popular color and add the difference between the component size and the number of vertices of this color. In order to find the most popular color you may, for example, write all colors in an array, sort it and find the longest contiguous segment of colors. Such a solution works in $O((n+m)\\log n)$.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "731",
    "index": "D",
    "title": "80-th Level Archeology",
    "statement": "Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of $n$ words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyphs according to some rules. The instruction nearby says that the door will open only if words written on the lock would be sorted in lexicographical order (the definition of lexicographical comparison in given in notes section).\n\nThe rule that changes hieroglyphs is the following. One clockwise rotation of the round switch replaces each hieroglyph with the next hieroglyph in alphabet, i.e. hieroglyph $x$ ($1 ≤ x ≤ c - 1$) is replaced with hieroglyph $(x + 1)$, and hieroglyph $c$ is replaced with hieroglyph $1$.\n\nHelp archeologist determine, how many clockwise rotations they should perform in order to open the door, or determine that this is impossible, i.e. no cyclic shift of the alphabet will make the sequence of words sorted lexicographically.",
    "tutorial": "Denote as $x$ the number of alphabet cyclic shifts we will perform. Our goal is to formulate the statement of lexicographical order in terms of $x$. Note that $x$ may be considered as an integer between $0$ and $c - 1$, i. e., as a residue modulo $c$. Let's also consider all characters as values between $0$ to $c - 1$ as we may subtract 1 from the value of each character. Consider two consecutive words in the given list. There are two possibilities corresponding two cases in the definition of lexicographical order: The first case is when there exists such a position that these words differ in this position and coincide before this position. Suppose that first word has value of $a$ on this position, and second word has the value of $b$. Then these words will follow in lexicographical order if and only if $(a+x)\\ \\mathrm{~mod~}c<(b+x)\\ \\ \\mathrm{~mod~}c$. It's easy to see that if we consider all residues modulo $c$ as a circle, then this inequality defines an arc of possible $x$'s on this circle. So, this pair of contiguous words produces the following statement \"$x$ belongs to some arc on the circle\". The second case is when there is no such a position, i. e. one word is a prefix of another. If the first word is a prefix of second one then these words always follow in lexicographical order irrespective to the choice of $x$. In the other case (second word is a proper prefix of the first word) we can't do anything with these to words since they will never follow in a lexicographical order, so we should print $- 1$. Now we have to find a point on the circle belonging to the given set of arcs. Suppose we have $k$ arcs. Consider a line segment from $0$ to $c - 1$ instead of a circle; each arc will transform to either one or two its subsegments. Now we have to find out if there exists a point covered by exactly $k$ segments. It may be done in different ways, for example you may add 1 on each of this segment by using some data structure, or you may add $1$ to the left endpoint of each segment and $- 1$ to the point after the right endpoint of each segment, and consider prefix sums (an off-line way to handle range addition queries). Or you may write down all endpoints of all segments, sort them by a coordinate and iterate over them from left to right, keeping the number of open segments. If at some moment you have exactly $k$ open segments, then the answer is \"YES\".",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "731",
    "index": "E",
    "title": "Funny Game",
    "statement": "Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.\n\nThe game they came up with has the following rules. Initially, there are $n$ stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.\n\nOne move happens as follows. Lets say there are $m ≥ 2$ stickers on the wall. The player, who makes the current move, picks some integer $k$ from $2$ to $m$ and takes $k$ leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move.\n\nGame ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.\n\nGiven the integer $n$ and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.",
    "tutorial": "First of all, comment on such type of games. In CS the game where two players are willing to maximize the difference between their own score and the score of their opponent is called a \"zero-sum game\". A useful knowledge is that problems for such a kind of games are usually solved using dynamic programming. Note that at any moment the first sticker contains the sum of numbers on some prefix of an original sequence. This means that the state of a game is defined by a single number $i$: the length of an original sequence prefix that were summed into a single number. Let's make two observations. First of all, for any state $i$ the turn that current player will perform doesn't depend on scores of both players. Indeed, at any moment we may forget about the scores of both players since they add the constant factor to the resulting score difference, so we may virtually discard both players current scores. So, all we need to know about state $i$ is what difference there will be between the current player score and his opponent score if the game would have started from the state $i$ with zero scores. Second observation is that the turn chosen by a player from the state $i$ and the final difference of scores at the end does not depend from which player is currently making a turn (Petr or Gennady), i. e. the game is symmetric. Denote as $D[i]$ the difference between the first player score and the second player score if the game would have started from the state $i$ with zero scores. It is a convenient way to think about this game as if there were no separate scores of two players, but only a single balance value (difference) between them, and the first player is adding some numbers to the balance at his turn and second player subtracts some numbers from the balance. In such formulation $D[i]$ is a balance change at the end of the game if the current player is willing to maximize it and he is currently in the state $i$. The answer for a problem will be, as one can see, $D[1]$. Note that if the current player would be willing to minimize balance, then the final balance change from the state $i$ would be $- D[i]$ because the game is symmetric. Let's calculate all $D[i]$ using dynamic programming. At the end of the game, i. e. in the state $n$ the value $D[n]$ is equal to zero because the players won't be making any turns, and so the balance won't change. Consider some state $i$. Suppose current player will take all the stickers up to the $j$-th (here $j$-th means the index in the original sequence). In such case he will change balance by $S[j]$ (where $S[j]$ is the sum of first $j$ numbers in an original sequence), and game will move to the state $j$. After that his opponent will change the balance by $- D[j]$ (note that the balance change value is added with an opposite sign since the opponent will be playing from this state). So, the final balance change when making such a turn will be $S[j] - D[j]$. In the DP definition we play for a player that is willing to maximize the balance, so $D[i]=\\operatorname*{max}_{i<j\\leq n}(S[j]-D[j])$. Such a formula produces a solution in $O(n^{2})$, but one may find that that it's enough to keep the maximum value of $S[j] - D[j]$ on suffix $j > i$, recalculating it in $O(1)$ when moving from $i$ to $i - 1$. So, we have the solution that works in $O(n)$.",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 2200
  },
  {
    "contest_id": "731",
    "index": "F",
    "title": "Video Cards",
    "statement": "Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.\n\nThere are $n$ video cards in the shop, the power of the $i$-th video card is equal to integer value $a_{i}$. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it \\textbf{can't} be reduced.\n\nVlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.",
    "tutorial": "First observation is that if we fix the leading video card power $x$, we may take all the video cards of power at least $x$, as each of them brings the positive power value. So, we may sort all the cards in the ascending power order and then we will always choose some suffix of cards in such an order. The final total power equals to $\\sum_{i=1}^{n}(a_{i}-(a_{i}{\\mathrm{~~mod~}}x))$. Note that under the summation there is a number that is divisible by $x$ and that is no larger than $200 000$ at the same time. It means that there are no more than $\\left|{\\frac{20000}{x}}\\right|$ different terms in this sum. Let's calculate the value of a sum spending the operations proportional to the number of different terms in it. To do it we need to find out for each of the values $x$, $2x$, $3x$, ..., how many video cards will have exactly such power at the end. It's easy: final power $kx$ corresponds to those video cards, which originally had the power between $kx$ and $(k + 1)x - 1$. Their number can be found out in $O(1)$ if we build an array $C[i]$ storing the number of video cards of each power and calculate prefix sums on it. It means that we got a solution that performs about $\\sum_{x=1}^{20000}\\left[{\\frac{290090}{x}}\\right]\\approx\\sum_{x=1}^{200000}{\\frac{219000}{x}}=200\\,000({\\frac{1}{1}}+{\\frac{1}{2}}+\\cdot\\cdot+{\\frac{1}{200000}})\\approx200\\,000\\,\\ln200\\,000$ operations. It's useful to know that the sum inside brackets is called a harmonic series, and that its sum is very close to the natural logarithm of the number of terms (up to a constant factor in limit). It means that we got a solution in complexity of $O(n+m\\log m)$ where $m$ is the maximum power of a single video card.",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "732",
    "index": "A",
    "title": "Buy a Shovel",
    "statement": "Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for $k$ burles. Assume that there is an unlimited number of such shovels in the shop.\n\nIn his pocket Polycarp has an unlimited number of \"10-burle coins\" and exactly one coin of $r$ burles ($1 ≤ r ≤ 9$).\n\nWhat is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of $r$ burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.",
    "tutorial": "In this problem we have to find the minimal possible value of $x$ such that $k \\cdot x mod 10 = 0$ or $k \\cdot x mod 10 = r$. It's easy to see that this $x$ always exists and it is not greater than $10$ (because $k \\cdot 10 mod 10 = 0$). Let's iterate on $x$, and if its current value satisfies any of the requirements, we print the answer. Time complexity: $O(const)$, where $const = 10$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "732",
    "index": "B",
    "title": "Cormen --- The Best Friend Of a Man",
    "statement": "Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.\n\nEmpirically Polycarp learned that the dog needs at least $k$ walks for any two consecutive days in order to feel good. For example, if $k = 5$ and yesterday Polycarp went for a walk with Cormen $2$ times, today he has to go for a walk at least $3$ times.\n\nPolycarp analysed all his affairs over the next $n$ days and made a sequence of $n$ integers $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the number of times Polycarp will walk with the dog on the $i$-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).\n\nHelp Polycarp determine the minimum number of walks he needs to do additionaly in the next $n$ days so that Cormen will feel good during all the $n$ days. You can assume that on the day before the first day and on the day after the $n$-th day Polycarp will go for a walk with Cormen exactly $k$ times.\n\nWrite a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers $b_{1}, b_{2}, ..., b_{n}$ ($b_{i} ≥ a_{i}$), where $b_{i}$ means the total number of walks with the dog on the $i$-th day.",
    "tutorial": "If we don't make enough walks during days $i$ and $i + 1$, it's better to make an additional walk on day $i + 1$ because it also counts as a walk during days $i + 1$ and $i + 2$ (and if we walk one more time on day $i$, it won't help us in the future). So we can start iterating from the second day ($1$\"=indexed). We will add $max(0, k - a_{i} - a_{i - 1})$ walks to the day $i$ (and to our answer), so Cormen has enough walks during days $i$ and $i - 1$. After we have iterated through all days, we can print the answer. Time complexity: $O(n)$.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "732",
    "index": "C",
    "title": "Sanatorium",
    "statement": "Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation!\n\nEvery day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.\n\nVasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.\n\nAccording to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.",
    "tutorial": "Let's iterate on the time of day when Vasiliy arrived at the sanatorium (breakfast, dinner or supper) and on the time when Vasiliy left. We sum the changed values of $b$, $d$ and $s$ (considering that we take all possible meals during the first and the last day) into the variable $sum$, find $mx$ - the maximum of these three variables (also changed), and if our current answer is more than $3 \\cdot mx - sum$, we update it with this value. After considering all $9$ possible scenarios, we print the answer. Time complexity: $O(const)$, $const = 3^{3}$.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "732",
    "index": "D",
    "title": "Exams",
    "statement": "Vasiliy has an exam period which will continue for $n$ days. He has to pass exams on $m$ subjects. Subjects are numbered from 1 to $m$.\n\nAbout every day we know exam for which one of $m$ subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day.\n\nOn each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest.\n\nAbout each subject Vasiliy know a number $a_{i}$ — the number of days he should prepare to pass the exam number $i$. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during $a_{i}$ days for the exam number $i$. He can mix the order of preparation for exams in any way.\n\nYour task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time.",
    "tutorial": "Let's use binary search to find the answer (the latest day when we have passed all the exams). To check whether we can pass all the exams until some fixed day $x$, we will take all the examples as late as possible. We will prepare to the earliest exam, then to the second earliest, and so on. If we are not ready for some exam or if we don't pass them until the day $x$ ends, then we can't pass all the exams in time. After finishing our binary search we print the answer. Time complexity: $O(mlogn)$.",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "732",
    "index": "E",
    "title": "Sockets",
    "statement": "The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.\n\nThere are $n$ computers for participants, the $i$-th of which has power equal to positive integer $p_{i}$. At the same time there are $m$ sockets available, the $j$-th of which has power euqal to positive integer $s_{j}$. It is possible to connect the $i$-th computer to the $j$-th socket if and only if their powers are the same: $p_{i} = s_{j}$. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets.\n\nIn order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power $x$, the power on the adapter's socket becomes equal to $\\left|{\\frac{x}{2}}\\right|$, it means that it is equal to the socket's power divided by two with rounding up, for example ${\\bigl\\lfloor}{\\frac{10}{2}}{\\bigr\\rfloor}=5$ and ${\\frac{|15}{2}}|=8$.\n\nEach adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power $10$, it becomes possible to connect one computer with power $3$ to this socket.\n\nThe organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers $c$ at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters $u$ to connect $c$ computers.\n\nHelp organizers calculate the maximum number of connected computers $c$ and the minimum number of adapters $u$ needed for this.\n\nThe wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.",
    "tutorial": "Firstly, we need to sort both arrays (with computers and with sockets) in non-descending order (also we need to sustain their indices to print the answer). Then we iterate on the value $x$ until it reaches the logarithm of the maximum value in $s$ (or until it reaches 31). For each value of $x$ we iterate on computers in non-descending order, also we maintain the index of the most suitable socket (let's call this index $i$). If socket number $i$ is already used or if its power is less than current computer's requirement, we increase $i$. If our current socket's power matches current computer's requirement, then we connect this computer with current socket. Each iteration connects the largest possible number of computers and sockets. After each iteration we install adapters on all non\"=used sockets: $s_{i}=\\left\\lceil{\\frac{a}{2}}\\right\\rceil$. After all iterations we print the answer. Time complexity: $O(nlogn + mlogm + (n + m)logA)$, where $A$ is the maximum power of socket.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "732",
    "index": "F",
    "title": "Tourist Reform",
    "statement": "Berland is a tourist country! At least, it can become such — the government of Berland is confident about this.\n\nThere are $n$ cities in Berland, some pairs of which are connected by two-ways roads. Each road connects two different cities. In Berland there are no roads which connect the same pair of cities. It is possible to get from any city to any other city using given two-ways roads.\n\nAccording to the reform each road will become one-way. It will be oriented to one of two directions.\n\nTo maximize the tourist attraction of Berland, after the reform for each city $i$ the value $r_{i}$ will be calculated. It will equal to the number of cities $x$ for which there is an oriented path from the city $i$ to the city $x$. In other words, $r_{i}$ will equal the number of cities which can be reached from the city $i$ by roads.\n\nThe government is sure that tourist's attention will be focused on the minimum value of $r_{i}$.\n\nHelp the government of Berland make the reform to maximize the minimum of $r_{i}$.",
    "tutorial": "Firstly, we have to find all the bridges and divide the graph into 2\"=edge\"=connected components. Then we calculate the size of each component. It can be easily proved that the answer is equal to size of the largest component. Then we need to orient the edges somehow. Start DFS from any vertex of the largest component. If we traverse the edge $(v, to)$ (coming from vertex $v$) and it has not been oriented yet, we orient it from $to$ to $v$, if it's a bridge (so it leads to the largest component) or from $v$ to $to$ otherwise. When all vertices are visited and all edges are oriented, we can print the answer. Time complexity: $O(n + m)$.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "733",
    "index": "A",
    "title": "Grasshopper And the String",
    "statement": "One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump.\n\nFormally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from $1$ to the value of his jump ability.\n\n\\begin{center}\n{\\small The picture corresponds to the first example.}\n\\end{center}\n\nThe following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.",
    "tutorial": "In this problem you have to find the longest sequence of consonants. The answer is its length + 1. Iterate over each letter of string maintaining $cur$ - current number of consecutive consonants and $len$ - length of longest sequence. If current letter is consonant then increase $cur$ by 1, otherwise update $len = max(len, cur)$ and set $cur$ = 1. Don't forget to update $len$ value after exiting loop (as string can possibly end with consonant). Time complexity - $O(n)$, $n$ - length of the specified string.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "733",
    "index": "B",
    "title": "Parade",
    "statement": "Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.\n\nThere will be $n$ columns participating in the parade, the $i$-th column consists of $l_{i}$ soldiers, who start to march from left leg, and $r_{i}$ soldiers, who start to march from right leg.\n\nThe beauty of the parade is calculated by the following formula: if $L$ is the total number of soldiers on the parade who start to march from the left leg, and $R$ is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal $|L - R|$.\n\n\\textbf{No more than once} you can choose one column and tell \\textbf{all the soldiers} in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index $i$ and swap values $l_{i}$ and $r_{i}$.\n\nFind the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.",
    "tutorial": "Let's calculate $L$ and $R$ values before update moves. Result will be stored in $maxk$ - maximum beauty that can be achieved. So initially $maxk = |L - R|$. Now for every columm let's calculate $k_{i}$ - beauty of the parade after switching starting leg of $i$-th column. $k_{i} = |(L - l_{i} + r_{i}) - (R - r_{i} + l_{i})|$. If $k_{i} > maxk$ then update $maxk$ value and store index $i$ for answer. If there were no such $i$ that $k_{i} > maxk$ then answer is 0. Time complexity - $O(n)$.",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "733",
    "index": "C",
    "title": "Epidemic in Monstropolis",
    "statement": "There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.\n\nSoon, monsters became hungry and began to eat each other.\n\nOne monster can eat other monster if its weight is \\textbf{strictly greater} than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster $A$ eats the monster $B$, the weight of the monster $A$ increases by the weight of the eaten monster $B$. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were $n$ monsters in the queue, the $i$-th of which had weight $a_{i}$.\n\nFor example, if weights are $[1, 2, 2, 2, 1, 2]$ (in order of queue, monsters are numbered from $1$ to $6$ from left to right) then some of the options are:\n\n- the first monster can't eat the second monster because $a_{1} = 1$ is not greater than $a_{2} = 2$;\n- the second monster can't eat the third monster because $a_{2} = 2$ is not greater than $a_{3} = 2$;\n- the second monster can't eat the fifth monster because they are not neighbors;\n- the second monster can eat the first monster, the queue will be transformed to $[3, 2, 2, 1, 2]$.\n\nAfter some time, someone said a good joke and all monsters recovered. At that moment there were $k$ ($k ≤ n$) monsters in the queue, the $j$-th of which had weight $b_{j}$. Both sequences ($a$ and $b$) contain the weights of the monsters in the order from the first to the last.\n\nYou are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.",
    "tutorial": "The key observation to solution is to notice that $b_{1}$ is union (monsters eat one another one by one in such a way that only one is being left) of elements of some prefix of $a$. And if you remove this prefix and first element of $b$ then this condition will remain true for new arrays $a$ and $b$. Answer is \"NO\" when: There is no such prefix that has sum of $b_{i}$. Prefix of sum $b_{i}$ consists of equal elements and its size $> 1$. Now let's consider certain prefix. Our goal is to find sequence of moves to get only one monster left. Here is one of possible solutions: Find such $i$ that $a_{i}$ is maximum in prefix and either $a_{i - 1}$ or $a_{i + 1}$ is strictly less that $a_{i}$. Eat any of possible neighbors. If only one monster is left then move to next segment. If all weights become equal then print \"NO\". The only thing left is to carefully calculate real positions of monsters on each step. Also you can't output them at a moment of calculation as there might be a \"NO\" answer afterwards. Time complexity - $O(n^{2})$. And challenge: can you optimize it to $O(n)$?",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "733",
    "index": "D",
    "title": "Kostya the Sculptor",
    "statement": "Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere.\n\nZahar has $n$ stones which are rectangular parallelepipeds. The edges sizes of the $i$-th of them are $a_{i}$, $b_{i}$ and $c_{i}$. He can take \\textbf{no more than two stones} and present them to Kostya.\n\nIf Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way.\n\nHelp Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.",
    "tutorial": "Radius of inscribed sphere = $min(a, b, c) / 2$. Let's create list of pairwise distinct edges where two edges is condered different when either minimal sides of edges differ or maximal ones. For every edge $(a, b)$ let's find two maximal lengths of adjacent side $c_{1}$ and $c_{2}$. These are two parallelepipeds of maximal volume with one of edges being equal to $(a, b)$. If you glue them together then you will get parallelepiped with sides $(a, b, c_{1} + c_{2})$. Also don't forget cases where there is only one maximal side for edge. There are no more than $3 \\cdot n$ edges. So iterating over every parallelepiped with structure $map$ to store maximums works in $O(k n\\cdot\\log k n)$ where $k  \\le  3$.",
    "tags": [
      "data structures",
      "hashing"
    ],
    "rating": 1600
  },
  {
    "contest_id": "733",
    "index": "E",
    "title": "Sleep in Class",
    "statement": "The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs.\n\nThe stairs consists of $n$ steps. The steps are numbered from bottom to top, it means that the lowest step has number $1$, and the highest step has number $n$. Above each of them there is a pointer with the direction (up or down) Olga should move from this step. As soon as Olga goes to the next step, the direction of the pointer (above the step she leaves) changes. It means that the direction \"up\" changes to \"down\", the direction \"down\"  —  to the direction \"up\".\n\nOlga always moves to the next step in the direction which is shown on the pointer above the step.\n\nIf Olga moves beyond the stairs, she will fall and wake up. Moving beyond the stairs is a moving down from the first step or moving up from the last one (it means the $n$-th) step.\n\nIn one second Olga moves one step up or down according to the direction of the pointer which is located above the step on which Olga had been at the beginning of the second.\n\nFor each step find the duration of the dream if Olga was at this step at the beginning of the dream.\n\nOlga's fall also takes one second, so if she was on the first step and went down, she would wake up in the next second.",
    "tutorial": "Olga is always able to go beyond stairs. To prove that let's consider some segment of stairs. If we enter it from upper step then we move down until reaching 'U' which reverses our moving direction. After that we leave segment from above. Now this 'U' became 'D' and other symbols remained the same as they were either visited twice or not visited at all. So we enter segment once again from upper step, this time we proceed to next 'U'. And at the some point we leave segment from below. It will happen in $ku + 1$ turn where $ku$ - number of 'U' symbols in segment. Leaving segment from above when it's entered from below is done in $kd + 1$ turns, $kd$ - number of 'D' symbols in segment. It can be proven the same way. Then we can divide stairs into three parts: Segment below current step Current step Segment above current step It can be easily seen that we will go beyond stairs either from $1^{st}$ or from $3^{rd}$ segment. Now let's calculate values of $ku$ and $kd$ for every step. $ku_{i}$ - number of 'U' symbols in prefix of stairs $s$ (exluding $s_{i}$), $kd_{i}$ - number of 'D' symbols in suffix (exluding $s_{i}$). $ku_{i} = ku_{i - 1} + int(s_{i} = = 'U')$ $kd_{i} = kd_{i + 1} + int(s_{i} = = 'D')$ We will also need values of $tl_{i}$ and $tr_{i}$, $tl_{i}$ - time in seconds to leave stairs from below as if $s_{i}$ is always equal to 'D' and $tr_{i}$ - time in seconds to leave stairs from above as if $s_{i}$ is always equal to 'U'. It's obvious that by moving iterator by one position to the right we increase distance to every calculated symbol 'U' by $1$, so it's $+ 2$ for each symbol to overall time (we go to this symbol and back to $i$). If previous symbol was 'U' then we should add $2$ more to overall time. In total this will be equal to $ku_{i} \\cdot 2$. And as we moved one step away from exit we should increase time by $1$. $tl_{i} = tl_{i - 1} + ku_{i} \\cdot 2 + 1$ And it's the same for $tr_{i}$. $tr_{i} = tr_{i + 1} + kd_{i} \\cdot 2 + 1$ And finally let's derive formula to get answer in $O(1)$ for each step. Olga will go beyond stairs from the side which has least amount of obstacles. If amounts are equal then it's the matter of current letter. Let's imply that we are exiting from both sides at the same time and just subtract from time the part from the side opposite to exiting one. So we should subtract $tl_{j}$ or $tr_{j}$ (it depends on exiting side), where $j$ is position in string of last visited element of side opposite to exiting one. And also subtract doubled distance between current step and last visited obstacle multiplied by number of unvisited onstacles. So if we go beyond stairs from below then this is the derived formula: $tl_{i} + tr_{i} - tr_{posd[kdi - kui - f]} - (posd[kd_{i} - f - ku_{i}] - i) - 2 \\cdot (kd_{i} - ku_{i} - f) \\cdot (posd[kd_{i} - f - ku_{i}] - i)$ $posd$ - reversed array of indices (positions in string) of 'D' symbol. $kd_{i} - ku_{i} - f$ - number (not position) of last visited element from above. $f$ is $0$ if $s_{i} =$'D', $1$ if $s_{i} =$'U'. (This will be reversed on exiting from above) Answer for last step is calculated the same way. For deriving formula for exiting from above you will also need $posu$ - array of indices (positions in string) of 'U' symbol (not reversed this time).",
    "tags": [
      "constructive algorithms",
      "data structures",
      "math",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "733",
    "index": "F",
    "title": "Drivers Dissatisfaction",
    "statement": "In one kingdom there are $n$ cities and $m$ two-way roads. Each road connects a pair of cities, and for each road we know the level of drivers dissatisfaction — the value $w_{i}$.\n\nFor each road we know the value $c_{i}$ — how many lamziks we should spend to reduce the level of dissatisfaction with this road by one. Thus, to reduce the dissatisfaction with the $i$-th road by $k$, we should spend $k·c_{i}$ lamziks. And \\textbf{it is allowed for the dissatisfaction to become zero or even negative}.\n\nIn accordance with the king's order, we need to choose $n - 1$ roads and make them the main roads. An important condition must hold: it should be possible to travel from any city to any other by the main roads.\n\nThe road ministry has a budget of $S$ lamziks for the reform. The ministry is going to spend this budget for repair of some roads (to reduce the dissatisfaction with them), and then to choose the $n - 1$ main roads.\n\nHelp to spend the budget in such a way and then to choose the main roads so that the total dissatisfaction with the main roads will be as small as possible. The dissatisfaction with some roads can become negative. It is not necessary to spend whole budget $S$.\n\nIt is guaranteed that it is possible to travel from any city to any other using existing roads. Each road in the kingdom is a two-way road.",
    "tutorial": "If you choose any $n - 1$ roads then price of reducing overall dissatisfaction is equal to $min(c_{1}, c_{2}, ..c_{n - 1})$ where $c_{i}$ is price of reducing by $1$ dissatisfaction of $i$-th edge. So the best solution is to choose one edge and reduce dissatisfaction of it until running out of budget. Let's construct minimal spanning tree using Prim or Kruskal algorithm using edges of weights equal to dissatisfaction and calculate minimal price of reducing dissatisfaction. Time complexity - $O(m\\log n)$. Now we can iterate over edges implying that current is the one to be reduced to minimum. For example, for every edge we can build new MST and recalculate answer. It's $O(m^{2}\\cdot\\log n)$. Therefore we should use this fact: it's poinless to reduce dissatisfaction of edges which weren't selected to be main. Then we can transform original MST instead of constructing $m$ new ones. Add next edge to MST, now it contains a cycle from which edge with maximal dissatisfaction is about to be deleted. This can be achieved in such a way: find LCA of vertices of new edge in $O(\\log n)$ and using binary lifting with precalc in $O(\\log n)$ find the edge to delete. Time complexity - $O(n\\log n+m\\log n)$.",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "734",
    "index": "A",
    "title": "Anton and Danik",
    "statement": "Anton likes to play chess, and so does his friend Danik.\n\nOnce they have played $n$ games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.\n\nNow Anton wonders, who won more games, he or Danik? Help him determine this.",
    "tutorial": "Let $k_{a}$ will be amount of characters \"A\" in the string and $k_{d}$ will be amount of characters \"D\" in the string. Then, if $k_{a} > k_{d}$, we print \"Anton\". If $k_{a} < k_{d}$, we print \"Danik\". If $k_{a} = k_{d}$, we print \"Friendship\". Time complexity is $O(n)$.",
    "code": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n\tint n; cin >> n;\n\tstring s; cin >> s;\n\tint k_a = 0, k_d = 0;\n\tfor (int i = 0; i < n; i++)\n\t\tif (s[i] == 'A') k_a++; else k_d++;\n\tif (k_a > k_d) cout << \"Anton\" << endl;\n\tif (k_a < k_d) cout << \"Danik\" << endl;\n\tif (k_a == k_d) cout << \"Friendship\" << endl;\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "734",
    "index": "B",
    "title": "Anton and Digits",
    "statement": "Recently Anton found a box with digits in his room. There are $k_{2}$ digits $2$, $k_{3}$ digits $3$, $k_{5}$ digits $5$ and $k_{6}$ digits $6$.\n\nAnton's favorite integers are $32$ and $256$. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!\n\nEach digit can be used no more than once, i.e. the composed integers should contain no more than $k_{2}$ digits $2$, $k_{3}$ digits $3$ and so on. Of course, unused digits are not counted in the sum.",
    "tutorial": "We will act greedily. At first we'll make maximal possible amount of $256$ numbers. It will be equal to $n_{256}=\\operatorname*{min}(k_{2},k_{5},k_{6})$. From the rest of the digits we'll make maximal possible amount of $32$ numbers. It will be equal to $n_{32}=\\operatorname*{min}(k_{3},k_{2}-n_{256})$ (we use $k_{2} - n_{256}$ instead of $k_{2}$, because $n_{256}$ twos we've already used to make $256$ numbers. Now it's not hard to observe that the answer will be equal to $32\\cdot n_{32}+256\\cdot n_{256}$. Time complexity is $O(1)$.",
    "code": "#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n\tint k2, k3, k5, k6;\n\tcin >> k2 >> k3 >> k5 >> k6;\n\tint n256 = min(k2, min(k5, k6));\n\tint n32 = min(k3, k2 - n256);\n\tcout << 32 * n32 + 256 * n256 << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "734",
    "index": "C",
    "title": "Anton and Making Potions",
    "statement": "Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare $n$ potions.\n\nAnton has a special kettle, that can prepare one potions in $x$ seconds. Also, he knows spells of two types that can faster the process of preparing potions.\n\n- Spells of this type speed up the preparation time of one potion. There are $m$ spells of this type, the $i$-th of them costs $b_{i}$ manapoints and changes the preparation time of each potion to $a_{i}$ instead of $x$.\n- Spells of this type immediately prepare some number of potions. There are $k$ such spells, the $i$-th of them costs $d_{i}$ manapoints and instantly create $c_{i}$ potions.\n\nAnton can use \\textbf{no more than one} spell of the first type and \\textbf{no more than one} spell of the second type, and the total number of manapoints spent should not exceed $s$. Consider that all spells are used instantly and right before Anton starts to prepare potions.\n\nAnton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least $n$ potions.",
    "tutorial": "At first, observe that if we'll take the $i$-th potion of the first type and the $j$-th potion of the second type, then we can prepare all the potions in $a_{i}\\cdot(n-c_{j})$ seconds. So, we have to minimize this number. Let's iterate over what potion of the first type we'll use. Then we must find such spell of the second type that will prepare instantly as many as possible potions, and we'll have enough manapoints for it. It can be done using binary search, because the characteristics of potions of the second type - $c_{i}$ and $d_{i}$ are sorted in non-decreasing order. Time complexity is $O(m\\cdot\\log k+k)$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int max_n = 1000000;\n\nint n, m, k;\nint x, s;\nint a[max_n], b[max_n], c[max_n], d[max_n];\n\ninline int max_complete(int money_left)\n{\n\tint l = 0, r = k;\n\twhile (l < r)\n\t{\n\t\tint m = (l + r + 1) / 2;\n\t\tif (d[m] <= money_left) l = m; else r = m-1;\n\t}\n\treturn c[l];\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n\tcin >> n >> m >> k;\n\tcin >> x >> s;\n\ta[0] = x;\n\tb[0] = 0;\n\tc[0] = 0;\n\td[0] = 0;\n\tfor (int i = 1; i <= m; i++) cin >> a[i];\n\tfor (int i = 1; i <= m; i++) cin >> b[i];\n\tfor (int i = 1; i <= k; i++) cin >> c[i];\n\tfor (int i = 1; i <= k; i++) cin >> d[i];\n\tlong long ans = 1LL * n * x;\n\tfor (int i = 0; i <= m; i++)\n\t{\n\t\tint money_left = s - b[i];\n\t\tif (money_left < 0) continue;\n\t\tans = min(ans, 1LL * (n - max_complete(money_left)) * a[i]);\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "734",
    "index": "D",
    "title": "Anton and Chess",
    "statement": "Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on $8$ to $8$ board to too simple, he uses an infinite one instead.\n\nThe first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.\n\nConsider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move.\n\nHelp Anton and write the program that for the given position determines whether the white king is in check.\n\nRemainder, on how do chess pieces move:\n\n- Bishop moves any number of cells diagonally, but it can't \"leap\" over the occupied cells.\n- Rook moves any number of cells horizontally or vertically, but it also can't \"leap\" over the occupied cells.\n- Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't \"leap\".",
    "tutorial": "Let's observe that the king can attack only pieces that lay in eight directions (up, down, left, right vertically and horizontally, and also up-left, up-right, down-left and down-right diagonally from the cell where the king stands). Also we can observe that from all the pieces that lay in the eight directions, only the nearest one to the king can attack it (the rest of the pieces must \"leap\" over the nearest one, but it's impossible). So, we'll keep for all the eight directions the nearest piece to the king, and then we'll check if one of the nearest pieces can attack the king (don't forget that bishops can attack only diagonally, rooks - vertically and horizontally, queens - in all the directions). Time complexity is $O(n)$.",
    "code": "#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\ninline char in_char()\n{\n\tchar c = '\\0';\n\twhile (c <= ' ')\n\t\tc = getchar();\n\treturn c;\n}\n\ninline int in_int()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\treturn n;\n}\n\nstruct figurine\n{\n\tchar kind;\n\tint x, y;\n};\n\nint n;\nint x0, y0;\nfigurine nearest[8];\n\ninline int dist(int x1, int y1, int x2, int y2)\n{\n\treturn max(abs(x1 - x2), abs(y1 - y2));\n}\n\ninline void upd_nearest(figurine& was, const figurine& cur)\n{\n\tif (was.kind == '?' ||\n\t    dist(x0, y0, cur.x, cur.y) < dist(x0, y0, was.x, was.y))\n\twas = cur;\n}\n\ninline int get_direction(const figurine& cur)\n{\n\t// vertical\n\tif (cur.x == x0 && cur.y < y0) return 0;\n\tif (cur.x == x0 && cur.y > y0) return 1;\n\t// horizontal\n\tif (cur.y == y0 && cur.x < x0) return 2;\n\tif (cur.y == y0 && cur.x > x0) return 3;\n\t// diagonal 1\n\tif ((cur.y - y0) == (cur.x - x0) && cur.x < x0) return 4;\n\tif ((cur.y - y0) == (cur.x - x0) && cur.x > x0) return 5;\n\t// diagonal 2\n\tif ((cur.y - y0) == (x0 - cur.x) && cur.y < y0) return 6;\n\tif ((cur.y - y0) == (x0 - cur.x) && cur.y > y0) return 7;\n\t// the piece doesn't lie on any of the eight directions\n\treturn -1;\n}\n\nint main()\n{\n\tn = in_int();\n\tx0 = in_int(); y0 = in_int();\n\tfor (int i = 0; i < 8; i++)\n\t\tnearest[i].kind = '?';\n\t// read and update nearest\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfigurine cur;\n\t\tcur.kind = in_char(); cur.x = in_int(); cur.y = in_int();\n\t\tint dir = get_direction(cur);\n\t\tif (dir >= 0)\n\t\t\tupd_nearest(nearest[dir], cur);\n\t}\n\tbool ans = false;\n\t// check verticals and horizontals\n\tfor (int i = 0; i < 4; i++)\n\t\tif (nearest[i].kind == 'R' || nearest[i].kind == 'Q')\n\t\t\tans = true;\n\t// check diagonals\n\tfor (int i = 4; i < 8; i++)\n\t\tif (nearest[i].kind == 'B' || nearest[i].kind == 'Q')\n\t\t\tans = true;\n\t// output\n\tputs(ans ? \"YES\" : \"NO\");\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "734",
    "index": "E",
    "title": "Anton and Tree",
    "statement": "Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.\n\nThere are $n$ vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).\n\nTo change the colors Anton can use only operations of one type. We denote it as $paint(v)$, where $v$ is some vertex of the tree. This operation changes the color of all vertices $u$ such that all vertices on the shortest path from $v$ to $u$ have the same color (including $v$ and $u$). For example, consider the tree\n\nand apply operation $paint(3)$ to get the following:\n\nAnton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.",
    "tutorial": "At first, let's observe that if we unite some two vertices connected by an edge, that are the same color, in one vertex, the answer will not change. Let's do this. Then, for instance, the tree will look in this way: We'll also do such tree \"compression\" after every painting operation. Then, for instance, the tree will change after $paint(2)$ operation and the tree \"compression\" in this way: It's obvious that the tree will be painted in one color if and only if, when after such painting operations with the \"compression\" only one vertex remains. Let's call the tree diameter maximal possible shortest path between two vertices of the tree. It's not hard to observe that the tree will be painted in one color if and only if, when the tree diameter becomes equal to $0$, because the diameter is $0$ only in the tree with one vertex. Then, we'll see the following fact: the tree diameter can't be decreased more than by two per one painting operation with the \"compression\". So the answer cannot be less than $\\textstyle{\\frac{d+1}{2}}$, where $d$ is the tree diameter. Now, we'll prove that it's always possible to paint the tree in $\\textstyle{\\frac{d+1}{2}}$ operations. Find such vertex that the shortest path from it to any other vertex doesn't exceed $\\textstyle{\\frac{d+1}{2}}$. Such vertex can always be found, because otherwise the tree diameter won't be less that $d + 1$, which is impossible. Now see that if we paint this vertex $\\textstyle{\\frac{d+1}{2}}$ times, we will paint the tree in one color. Time complexity is $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint n;\nvector <int> color;\nvector < vector <int> > g;\nvector <char> used;\nvector <int> comp;\nint n1;\nvector < vector <int> > g1;\nvector <int> dp;\nint ans = 0;\n\nvoid dfs1(int v, int col, int cmp)\n{\n    if (used[v]) return;\n    if (color[v] != col) return;\n    used[v] = true;\n    comp[v] = cmp;\n    for (int i = 0; i < g[v].size(); i++)\n    {\n        int to = g[v][i];\n        dfs1(to, col, cmp);\n    }\n}\n\nvoid dfs2(int v, int p = -1)\n{\n    int mx1 = 0, mx2 = 0;\n    for (int i = 0; i < g1[v].size(); i++)\n    {\n        int to = g1[v][i];\n        if (to == p) continue;\n        dfs2(to, v);\n        int val = dp[to] + 1;\n        mx2 = max(mx2, val);\n        if (mx1 < mx2) swap(mx1, mx2);\n    }\n    dp[v] = mx1;\n    ans = max(ans, mx1 + mx2);\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin >> n;\n    color.resize(n);\n    g.resize(n);\n    comp.resize(n);\n    used.assign(n, false);\n    for (int i = 0; i < n; i++) cin >> color[i];\n    for (int i = 1; i < n; i++)\n    {\n        int a, b; cin >> a >> b; a--, b--;\n        g[a].push_back(b);\n        g[b].push_back(a);\n    }\n    for (int i = 0; i < n; i++)\n        if (!used[i])\n            dfs1(i, color[i], n1++);\n    g1.resize(n1);\n    dp.resize(n1);\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < g[i].size(); j++)\n        {\n            int to = g[i][j];\n            if (comp[i] != comp[to])\n                g1[comp[i]].push_back(comp[to]);\n        }\n    dfs2(0);\n    cout << (ans + 1) / 2 << endl;\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "734",
    "index": "F",
    "title": "Anton and School",
    "statement": "Anton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays $b$ and $c$ of length $n$, find array $a$, such that:\n\n$\\begin{array}{l}{{\\displaystyle\\int b_{i}=(a_{i}~a n d~a_{1})+(a_{i}~a n d~a_{2})+\\cdot\\cdot\\cdot+(a_{i}~a n d~a_{n}),}}\\\\ {{\\displaystyle\\left(c_{i}=(a_{i}~o r~a_{1})+(a_{i}~o r~a_{2})+\\cdot\\cdot\\cdot+(a_{i}~o r~a_{n}),}}\\end{array}\\right.$\n\nwhere $a and b$ means bitwise AND, while $a or b$ means bitwise OR.\n\nUsually Anton is good in arraystudying, but this problem is too hard, so Anton asks you to help.",
    "tutorial": "We'll prove that $(a\\;a n d\\;b)+(a\\;o r\\;b)=(a+b)$. At first, let's prove that it's true when $a\\in0.1$ and $b\\in0.1$. To do it, let's consider all the possible values of $a$ and $b$: $\\left[\\begin{array}{l l l}{{\\frac{\\alpha}{1}\\left[\\begin{array}{l l l}{{0}}&{{\\mid\\alpha{\\mathrm{~and~}}\\underbrace{{\\mathrm{b}}}{0}}\\right]}}\\\\ {{\\frac{\\mid\\scriptstyle0}{\\mid\\begin{array}{l}{{\\frac{{\\mathrm{a}}}{{\\mathrm{1}}}}{{\\frac{{\\mathrm{\\small0}}}{{\\mathrm{\\small0}}}{{\\frac{{\\mathrm{\\small1}}}{{\\frac{{\\mathrm{\\small1}}{{\\mathrm{\\small1}}}{{\\mathrm{\\small1}}}{{\\mathrm{\\small1}}}{{\\mathrm{\\small1}}}{{\\mathrm{\\small1}}}{{\\frac{{\\mathrm{\\small1}}}}}}}}\\end{array}}}}}}}\\end{array}\\right]$ Here we can see that the equality is true. Now, we'll prove it for any positive integers. To do it, let's divide $a$ and $b$ into bits: $a=b a_{0}\\cdot2^{0}+b a_{1}\\cdot2^{1}+\\cdot\\cdot\\cdot$ $b=b b_{0}\\cdot2^{0}+b b_{1}\\cdot2^{1}+\\cdot\\cdot\\cdot$ Here $ba_{0}, ba_{1}, ...$ mean the bits of $a$ and $bb_{0}, bb_{1}, ...$ mean the bits of $b$. Now, let's divide $(a and b)$ and $(a or b$) into bits: $(a~a n d~b)=(b a_{0}~a n d~b b_{0})\\cdot2^{0}+(b a_{1}~a n d~b b_{1})\\cdot2^{1}+\\cdot\\cdot\\cdot$ $(a~o r~b)=(b a_{0}~o r~b b_{0})\\cdot2^{0}+(b a_{1}~o r~b b_{1})\\cdot2^{1}+\\cdot\\cdot\\cdot$ Rewrite the initial equality: $\\begin{array}{c}{{(b a_{0}\\ a n d\\ b_{0})\\cdot2^{0}+(b a_{1}\\,a n d\\ b_{1})\\cdot2^{1}+\\cdot\\cdot\\cdot+(b a_{0}\\ o r\\ b b_{0})\\cdot2^{0}+(b a_{1}\\ o r\\ b b_{1})\\cdot2^{0}+(b a_{1}\\ o r\\ b b_{1})\\cdot2^{-1}+(b a_{0}\\ o n\\ d\\cdot b b_{0})\\cdot2^{-1}+(b a_{0}\\circ n\\ d\\cdot2^{-1}+\\cdot\\cdot\\cdot)}}\\\\ {{2^{1}+\\cdot\\cdot\\cdot=b a_{0}\\cdot2^{0}+b a_{1}\\cdot2^{1}+\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot}}\\end{array}$ Now it's not hard to observe that $(b a_{0}\\ a n d\\ b b_{0})\\cdot2^{0}+(b a_{0}\\ \\ o r\\ b b_{0})\\cdot2^{0}=b a_{0}\\cdot2^{0}+b b_{0}\\cdot2^{0}$ is true because the equality $(a\\;a n d\\;b)+(a\\;o r\\;b)=(a+b)$ is true for bits. Similarly, we see that $(b a_{1}\\ a n d\\ b_{1})\\cdot2^{1}+(b a_{1}\\ o r\\ b b_{1})\\cdot2^{1}=b a_{1}\\cdot2^{1}+b b_{1}\\cdot2^{1}$ is true and so on. From all this it follows that the equality $(a\\;a n d\\;b)+(a\\;o r\\;b)=(a+b)$ is true. Let's create an array $d_{i}$ where $d_{i}=b_{i}+c_{i}$. It's obvious that $\\begin{array}{c}{{d_{i}=\\left(a_{i}\\,a n d\\,a_{1}\\right)+\\left(a_{i}\\,a n d\\,a_{2}\\right)+\\cdot\\cdot\\cdot+\\left(a_{i}\\,a n d\\,a_{n}\\right)+\\left(a_{i}\\,o r\\,\\,a_{1}\\right)+\\left(a_{i}\\,o r\\,\\,a_{2}\\right)+\\cdot\\cdot u_{n}(x_{i})+\\cdot\\cdot u_{n}(x_{i})+\\cdot u_{1}(x)\\,.}}\\\\ {{\\cdot\\cdot\\cdot+\\left(a_{i}\\,o r\\,\\,a_{n}\\right)=n\\cdot a_{i}+a_{1}+a_{2}+\\cdot\\cdot+a_{n}.}}\\end{array}$ See that $\\begin{array}{c}{{d_{1}+d_{2}+\\cdot\\cdot\\cdot+d_{n}=n\\cdot(a_{1}+a_{2}+\\cdot\\cdot\\cdot\\cdot+a_{n})+n\\cdot a_{1}+n\\cdot a_{2}+\\cdot\\cdot\\cdot\\cdot+n\\cdot a_{n}=}}\\\\ {{2\\cdot n\\cdot(a_{1}+a_{2}+\\cdot\\cdot\\cdot\\cdot+a_{n}),}}\\end{array}$ from where $a_{1}+a_{2}+\\cdot\\cdot\\cdot+a_{n}={\\frac{d_{1+d_{2}+\\cdots+d_{n}}}{2n}}.$ Now it's not hard to find $a_{i}$: $\\theta_{i}={\\frac{d_{i}-(a_{1}+a_{2}+\\cdots+a_{n})}{n}}.$ Now, we only must check the answer for correctness. It's obvious then, if answer exists, it's alway unique, because it's explicitly derived from the formula above. To check if the answer exists, let's build arrays $b$ and $c$ from the found array $a$ and compare it with the arrays given in the input. We'll do this separately for every bit. Let's calculate $k_{j}$ - amount of numbers in array $a$ that has a one in the $j$-th bit. Let's denote the $j$-th bit of $a_{i}$ as $A_{i, j}$. Now, let's count $B_{i, j}$ and $C_{i, j}$ such as $B_{i j}=(A_{1,j}~a n d~A_{i,j})+(A_{2,j}~a n d~A_{i,j})+\\cdots+(A_{n,j}~a n d~A_{i,j}),$ $C_{i,j}=(A_{1,j}~o r~A_{i,j})+(A_{2,j}~o r~A_{i,j})+\\cdot\\cdot\\cdot+(A_{n,j}~o r~A_{i,j}),$ It's not hard to do since we know $k_{j}$: $\\begin{array}{l c r}{{B_{i,j}=0,\\,i f\\,\\,A_{i,j}=0,}}\\\\ {{B_{i,j}=k_{j},\\,i f\\,\\,A_{i,j}=1.}}\\\\ {{C_{i,j}=k_{j},\\,i f\\,\\,A_{i,j}=0,}}\\\\ {{C_{i,j}=n,\\,i f\\,\\,A_{i,j}=1.}}\\end{array}$ See that if we calculate $B_{i, j}$ and $C_{i, j}$, it will be easy to find $b_{i}$ and $c_{i}$: $b_{i}=B_{i.0}\\cdot2^{0}+B_{i.1}\\cdot2^{1}+\\cdot\\cdot\\cdot$ $c_{i}=C_{i\\alpha}\\cdot2^{0}+C_{i\\cdot1}\\cdot2^{1}+\\dots$ Time complexity is $O(n\\cdot\\log v a l)$, where $v a l=\\operatorname*{max}(a_{1},a_{2},\\cdot\\cdot\\cdot,a_{n})$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int max_n = 300000;\n\nint n;\nint b[max_n];\nint c[max_n];\nint a[max_n];\nint d[max_n];\nint b1[max_n];\nint c1[max_n];\nint bits[31][max_n];\nint kbit[31];\n\nint main()\n{\n\t// input\n\tios_base::sync_with_stdio(false);\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) cin >> b[i];\n\tfor (int i = 0; i < n; i++) cin >> c[i];\n\tfor (int i = 0; i < n; i++) d[i] = b[i] + c[i];\n\n\t// searching for answer\n\tlong long sum = 0;\n\tfor (int i = 0; i < n; i++) sum += d[i];\n\tsum /= (2 * n);\n\n\tfor (int i = 0; i < n; i++) a[i] = (d[i] - sum) / n;\n\n\t// checking the answer\n    for (int i = 0; i < n; i++)\n        if (a[i] < 0)\n        {\n            cout << -1 << endl;\n            return 0;\n        }\n\t\n\tfor (int i = 0; i < 31; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t\tif ((a[j] & (1LL << i)) == 0)\n\t\t\t\tbits[i][j] = 0;\n\t\t\telse\n\t\t\t\tbits[i][j] = 1;\n\tfor (int i = 0; i < 31; i++)\n\t{\n\t\tkbit[i] = 0;\n\t\tfor (int j = 0; j < n; j++)\n\t\t\tkbit[i] += bits[i][j];\n\t}\n\n\tfor (int i = 0; i < n; i++) b1[i] = 0;\n\tfor (int i = 0; i < n; i++) c1[i] = 0;\n\n\tfor (int i = 0; i < 31; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t{\n\t\t\tint bbase = bits[i][j] ? kbit[i] : 0;\n\t\t\tint cbase = bits[i][j] ? n : kbit[i];\n\t\t\tb1[j] += bbase << i;\n\t\t\tc1[j] += cbase << i;\n\t\t} \n\n\tfor (int i = 0; i < n; i++)\n\t\tif (b1[i] != b[i] || c1[i] != c[i])\n\t\t{\n\t\t\tcout << -1 << endl;\n\t\t\treturn 0;\n\t\t}\t\n\n\t// output\n\tfor (int i = 0; i < n; i++) cout << a[i] << \" \";\n\tcout << endl;\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "735",
    "index": "A",
    "title": "Ostap and Grasshopper",
    "statement": "On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length $n$ such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.\n\nOstap knows that grasshopper is able to jump to any empty cell that is \\textbf{exactly} $k$ cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if $k = 1$ the grasshopper can jump to a neighboring cell only, and if $k = 2$ the grasshopper can jump over a single cell.\n\nYour goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.",
    "tutorial": "Problem on programming technique. You have to find at which positions are grasshoper and insect. If k does not divide the difference of position, then answer is NO. Otherwise we have to check positions pos+k, pos+2k, ..., where pos is the minimal poisiton of grasshoper and insect. If somewhere is an obstacle, then answer is NO, otherwise the answer is YES.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "735",
    "index": "B",
    "title": "Urbanization",
    "statement": "Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are $n$ people who plan to move to the cities. The wealth of the $i$ of them is equal to $a_{i}$. Authorities plan to build two cities, first for $n_{1}$ people and second for $n_{2}$ people. Of course, each of $n$ candidates can settle in only one of the cities. Thus, first some subset of candidates of size $n_{1}$ settle in the first city and then some subset of size $n_{2}$ is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.\n\nTo make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that \\textbf{the sum of arithmetic mean} of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth $a_{i}$ among all its residents divided by the number of them ($n_{1}$ or $n_{2}$ depending on the city). The division should be done in real numbers without any rounding.\n\nPlease, help authorities find the optimal way to pick residents for two cities.",
    "tutorial": "First of all, note that n1+n2 chosen ones should be people with top (n1+n2) coeficients. Secondly, if the person with intelegence C will be in the first city then he will contribute to our overall IQ with C/n1 points. So, if n1<n2, then top-n1 ratings should be in the small city and the top-n2 from others - in the big city.",
    "tags": [
      "greedy",
      "number theory",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "735",
    "index": "C",
    "title": "Tennis Championship",
    "statement": "Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be $n$ players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately.\n\nOrganizers are still arranging tournament grid (i.e. the order games will happen and who is going to play with whom) but they have already fixed one rule: two players can play against each other only if the number of games one of them has already played \\textbf{differs by no more than one} from the number of games the other one has already played. Of course, both players had to win all their games in order to continue participating in the tournament.\n\nTournament hasn't started yet so the audience is a bit bored. Ostap decided to find out what is the maximum number of games the winner of the tournament can take part in (assuming the rule above is used). However, it is unlikely he can deal with this problem without your help.",
    "tutorial": "Let us solve the inverse problem: at least how many competitors should be, if the champion will have n matches. Then there's obvious reccurrent formula: f(n+1)=f(n)+f(n-1) (Let us make the draw in a way, where the champion will play n matches to advance to finals and the runner-up played (n-1) matches to advance the final). So, we have to find the index of maximal fibunacci number which is no more that number in the input.",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "735",
    "index": "D",
    "title": "Taxes",
    "statement": "Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to $n$ ($n ≥ 2$) burles and the amount of tax he has to pay is calculated as the maximum divisor of $n$ (not equal to $n$, of course). For example, if $n = 6$ then Funt has to pay $3$ burles, while for $n = 25$ he needs to pay $5$ and if $n = 2$ he pays only $1$ burle.\n\nAs mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial $n$ in several parts $n_{1} + n_{2} + ... + n_{k} = n$ (here $k$ is arbitrary, even $k = 1$ is allowed) and pay the taxes for each part separately. He can't make some part equal to $1$ because it will reveal him. So, the condition $n_{i} ≥ 2$ should hold for all $i$ from $1$ to $k$.\n\nOstap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split $n$ in parts.",
    "tutorial": "The first obvious fact is that the answer for prime numbers is 1. If the number is not prime, then the answer is at least 2. When is it possible? It is possible in 2 cases; when it is sum of 2 primes of its maximal divisor is 2. If 2 divides n, then so does integer n/2. n/2<=2=>n<=4=>n=4, where n is prime. According to Goldbach's conjecture, which is checked for all numbers no more than 10^9, every number is a sum of two prime numbers. Odd number can be sum of two primes, if (n-2) is prime (the only even prime number is 2). Otherwise, the answer is 3 - n=3+(n-3), (n-3) is sum of 2 primes, because it is even.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "735",
    "index": "E",
    "title": "Ostap and Tree",
    "statement": "Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph.\n\nOstap's tree now has $n$ vertices. He wants to paint some vertices of the tree black such that from any vertex $u$ there is at least one black vertex $v$ at distance no more than $k$. \\underline{Distance} between two vertices of the tree is the minimum possible number of edges of the path between them.\n\nAs this number of ways to paint the tree can be large, Ostap wants you to compute it modulo $10^{9} + 7$. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.",
    "tutorial": "Problem can be solved by the method of dynamic programming. Let dp[v][i][j] be the number of possibilities to color subtree of vertex v in such a way that the closest black vertex is on depth i, and the closest white vertex - on depth j (we also store dp[v][-1][j] and dp[v][i][-1] in the cases where there are no black and white vertexes in diapason k of v respectively). In order to connect two subtrees, we can check all pairs (i,j) in both subtrees (by brute-force algorithm). Then let we have pair (a,c) in the first subtree and pair (b,d) in the second one. If min(a,c)+max(b,d)<=k, then we update value of current vertex. Complexity of the algorithm O(n*k^4), which is acceptable for this particular problem (n - the number of vertexes, k^4 brute force search of pairs (a,b); (c,d)).",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "736",
    "index": "D",
    "title": "Permutations",
    "statement": "Ostap Bender is worried that people started to forget that he is the Great Combinator. Now he wants to show them his skills in combinatorics. Now he studies the permutations of length $n$. He has a list of $m$ valid pairs, pair $a_{i}$ and $b_{i}$ means that he is allowed to place integers $b_{i}$ at position $a_{i}$.\n\nHe knows that the number of permutations that use only valid pairs is \\textbf{odd}. Now, for each pair he wants to find out, will the number of valid permutations be \\textbf{odd} if he \\textbf{removes} this pair (and only it) from the list.",
    "tutorial": "This problem consists of 3 ideas. Idea 1: remainder modulo 2 of the number of permutation is equal to the remainder modulo 2 of the determinant of the matrix whose entries are 1 if (ai,bi) is in our list and 0 otherwise. Idea 2: If we cahnge 1 by 0, then the determinant will differ by algebraic compliment. That is, if we count inverse matrix, than it will reflect reminders modulo 2 (B(m,n)=A'(m,n)/detA, detA is odd). Idea 3: Inverse matrix can be counted for O((n/32)^3) time. However, we can work is field of integers modulo 2. The summation can be replaced by XOR. So if we store in one \"int\" not a single but 32 numbers, then we can reduce our assymptocy to O(n^3/32), which is OK.",
    "tags": [
      "math",
      "matrices"
    ],
    "rating": 2800
  },
  {
    "contest_id": "736",
    "index": "E",
    "title": "Chess Championship",
    "statement": "Ostap is preparing to play chess again and this time he is about to prepare. Thus, he was closely monitoring one recent chess tournament. There were $m$ players participating and each pair of players played exactly one game. The victory gives $2$ points, draw — $1$ points, lose — $0$ points.\n\nOstap is lazy, so he never tries to remember the outcome of each game. Instead, he computes the total number of points earned by each of the players (the sum of his points in all games which he took part in), sort these value in non-ascending order and then remembers first $n$ integers in this list.\n\nNow the Great Strategist Ostap wonders whether he remembers everything correct. He considers that he is correct if there exists at least one tournament results table such that it will produce the given integers. That means, if we count the sum of points for each player, sort them and take first $n$ elements, the result will coincide with what Ostap remembers. Can you check if such table exists?",
    "tutorial": "Suppose set (a1,a2,...,am). Then the list is valid if set {2m-2, 2m-4, 2m-6, ..., 0} majorizes the set {a1,a2,...,am}. Let us prove it! Part 1: Suppose n<=m. Top n players will play n(n-1)/2 games with each other and n(m-n) games with low-ranked contestants. In these games they will collect 2*n(n-1)/2 points (in each game there is exactly 2 points) for sure and at most 2*n*(m-n) points in games with others. So they will have at most 2*(n*(n-1)/2+n*(m-n))=2*((m-1)+(m-2)+...+(m-n)) points. Now construction: Let's construct results of participant with most points and then use recursion. Suppose the winner has even number of points (2*(m-n) for some n). Then we consider that he lost against contestants holding 2,3,4,...,n places and won against others. If champion had odd number of points (2*(m-n)-1 for some n), then we will construct the same results supposing that he draw with (n+1)th player instead of winning agianst him. It is easy to check that majorization is invariant, so in the end we will have to deal with 1 men competition, when set of scores {a1} is majorized by set {0}. So a1=0, and there is obvious construction for this case. So we have such an algorithm: we search for a compiment set which is majorized by {2m-2,2m-4,...,0}. If there is no such set answer is NO. Otherwise answer is YES and we construct our table as shown above. Assymptosy is O(m^2logm) (calling recursion m times, sorting the array (we can lose non-decreasing order because of poor results) and then passing on it linearly.",
    "tags": [
      "constructive algorithms",
      "flows",
      "greedy",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "737",
    "index": "E",
    "title": "Tanya is 5!",
    "statement": "Tanya is now five so all her friends gathered together to celebrate her birthday. There are $n$ children on the celebration, including Tanya.\n\nThe celebration is close to its end, and the last planned attraction is gaming machines. There are $m$ machines in the hall, they are numbered $1$ through $m$. Each of the children has a list of machines he wants to play on. Moreover, for each of the machines he knows the exact time he wants to play on it. For every machine, no more than one child can play on this machine at the same time.\n\nIt is evening already, so every adult wants to go home. To speed up the process, you can additionally rent second copies of each of the machines. To rent the second copy of the $j$-th machine, you have to pay $p_{j}$ burles. After you rent a machine, you can use it for as long as you want.\n\nHow long it will take to make every child play according to his plan, if you have a budget of $b$ burles for renting additional machines? There is only one copy of each machine, so it's impossible to rent a third machine of the same type.\n\nThe children can interrupt the game in any moment and continue it later. If the $i$-th child wants to play on the $j$-th machine, it is allowed after you rent the copy of the $j$-th machine that this child would play some part of the time on the $j$-th machine and some part of the time on its copy (each of these parts could be empty). The interruptions and changes take no time and can be performed in any integer moment of time. Of course, a child can't play on more than one machine at the same time.\n\nRemember, that it is not needed to save money (no one saves money at the expense of children happiness!), it is needed to minimize the latest moment of time some child ends his game.",
    "tutorial": "The problem was invented by the recollections of the recent celebration of the fifth birthday of Tanya Mirzayanova. At first let's solve this problem in simplified form: let there is no duplicate machines (in the other word it does not enough the budget $b$ to rent any duplicate). We consider, that each kid would like to play in each machine. Let $t_{i, j} = 0$ in such case. So, we consider, that the values of $t$ is a rectangular table - for each pair kid/machine in the cell written down the time of the game. Note that minimal time when all games will ended does not less than sum of values in each row $R_{i} = t_{i, 1} + t_{i, 2} + ... + t_{i, m}$. Similarly, the minimal time when all games will ended does not less than the sum in each column $C_{j} = t_{1, j} + t_{2, j} + ... + t_{n, j}$, because on each machine in one moment of time can play no more than one kid. Because of that the minimal time does not less than $max(R_{1}, R_{2}, ..., R_{n}, C_{1}, C_{2}, ..., C_{m})$. Note that there is always such a schedule that needed minimal time equals to maximum of all rows sums and all columns sums. Let's call this value $T$. Now we need to show this fact and consider the way to get this schedule. Let's build the weighted bipartite graph. In each part of this graph is $n + m$ vertices. Let's assume that each machine has a fake kid (i. e. now we have $n + m$ kids) - $n$ real and $m$ fake kids. The vertices from the first part will for kids: $u_{1}, u_{2}, ..., u_{n}$ - for real kids and $u_{n + 1}, u_{n + 2}, ..., u_{n + m}$ - for fake kids, and $u_{n + j}$ is a fake kid for the machine $j$. Similarly, let consider that each kid has a fake machine (totally there will be $n$ machines). The vertices from the second part will for machines: the first $m$ vertices is for real machines ($v_{1}, v_{2}, ..., v_{m}$), and following $n$ for fakt machines ($v_{m + 1}, v_{m + 2}, ..., v_{m + n}$). The vertex $v_{m + i}$ will for the fake machine of kid $i$. Let's make the edges. We will have 4 types of edges: between the real kids and the real machines, between the fake kids and the real machines, between the real kids and the fake machines, between the fake kids and the fake machines. We need to make the edges in such a way that the sum of weights of incident edges for each vertex is equals to $T$. The edges of type 1. Let's add the edge between $u_{i}$ and $v_{j}$, if $t_{i, j} > 0$. the weight is $t_{i, j}$. This edge means that the kid must play on the machine needed number of minutes. The edges of type 2. This edges mean that the machine will has downtime equals to some number of minutes (in the other words in downtime the fake kid will play on this machine). For all $j$ from 1 to $m$ let's find $a - C_{j}$. If such vertices is positive, then we need to add edge between $u_{n + j}$ and $v_{j}$ with such weight. The edges of type 3. This edges mean that the kid will have time, when he does not play (we consider that in this time the kid play on the fake machine). For all $i$ from 1 to $n$ let's find $a - R_{i}$. If this value is positive we add edge between $u_{i}$ and $v_{m + i}$ with such weight. The edges of type 4. After we added the edges of types 1-3 it is easy to show that the sum of weights of incident edges equal to $T$. For the vertices $u_{n + 1}, u_{n + 2}, ..., u_{n + m}, v_{m + 1}, v_{m + 2}, ..., v_{m + n}$ this sum now less or equal to $T$. Let's add remaining edges to make this sums equal to $T$. It's always possible if we add this edges in greedy way. We know the following fact: in any regular bipartite graph there is a perfect matching (a consequence of the Hall's theorem). If we look on the given graph like on the unweighted multigraph where the weight of the edge in our graph equals to the number of edges between the pair of vertices, then the resulting graph will be regular graph and for it will be correct described fact (i. e. there is perfect matching in this graph). Let's find the perfect matching with help of the Kuhn's algorithm in weighted graph. Let's choose the weight of the minimal edge and it is equals to $M$. Then let's appoint kids on machines for each edge between the vertices $u_{1}, u_{2}, ..., u_{n}$ and $v_{1}, v_{2}, ..., v_{m}$ on the time $M$. Also let's subtract $M$ from the weight of each edge of the matching. If the weight of the edge became 0, we delete this edge. After that it is correct the sum for each vertices is a constant. It means that the remaining graph has the perfect matching. We need to make with this graph similar operations, which was described above. Let's do it until the graph contains at least one edge. So we found needed schedule. To make the solution faster we can rebuild the matching from the unsaturated vertices from the first part if such vertices exist. This algorithm will works totally in $O(e^{2})$, where $e$ is the number of edges in the beginning, i. e. $e = O(nm)$, so the asymptotic behavior is $O(n^{2}m^{2}$). In this problem there were small restricts so we could build the matching with Kuhn's algorithm. By the way we build the optimal painting of the bipartite graph. Here we can use the well known algorithm (read about the optimal painting of the bipartite graph). So, we solved the problem without rent the duplicates. Besides it, the value of the answer is a maximum from all sums of rows and columns of the table with times for pairs kid/machine. If we have a duplicated it equals to adding the column in which we can partially distribute the values from this column. Of course, it is profitably to make it with columns which sum $C_{j} = T$ (i. e. the answer rests in this column). This operation makes sense only if we make it for all columns with $C_{j} = T$ simultaneously. The algorithm to choose of machines to rent follows. Let's find the sum of rent for all machines with $C_{j} = T$. If this value less or equal to the budget $b$ than we must rent this machines. Then add the appropriate columns in the table and put as evenly as possible the values of the duplicated columns. Recalculate $T$. Repeat the process and end it when the sum of rent for each operation became more than $b$.",
    "tags": [
      "graph matchings",
      "graphs",
      "greedy",
      "schedules"
    ],
    "rating": 3300
  },
  {
    "contest_id": "737",
    "index": "F",
    "title": "Dirty plates",
    "statement": "After one of celebrations there is a stack of dirty plates in Nikita's kitchen. Nikita has to wash them and put into a dryer. In dryer, the plates should be also placed in a stack also, and the plates sizes should increase down up. The sizes of all plates are distinct.\n\nNikita has no so much free space, specifically, he has a place for only one more stack of plates. Therefore, he can perform only such two operations:\n\n- Take any number of plates from $1$ to $a$ from the top of the dirty stack, wash them and put them to the intermediate stack.\n- Take any number of plates from $1$ to $b$ from the top of the intermediate stack and put them to the stack in the dryer.\n\nNote that after performing each of the operations, the plates are put in the same order as they were before the operation.\n\nYou are given the sizes of the plates $s_{1}, s_{2}, ..., s_{n}$ in the down up order in the dirty stack, and integers $a$ and $b$. All the sizes are distinct. Write a program that determines whether or not Nikita can put the plates in increasing down up order in the dryer. If he is able to do so, the program should find some sequence of operations (not necessary optimal) to achieve it.",
    "tutorial": "At first we wil try to solve the problem without taking the restrictions placed on $a$ and $b$ into consideration. If we can't solve the new problem, we surely can't solve the original one with the restrictions on $a$ and $b$. Let's examine the operations we can and can't do. It's easy to understand that we can't place any plates into the dryer which wouldn't fit the sequence, because they can't be removed from that stack. It is also clear that if we are able to take a sequence of plates from the top of the intermediate stack onto the top of the dryer stack and they would fit the proper sequence in the dryer stack, it can be done immediately. This statement is also right for the top of dirty stack, but it would take two operations for the plates to end up in the drier. Alos, it's easy to notice a situation which makes it impossible to reach the answer: if there is a plate with the size $y$ right above the plate with the size $x$ in the intermediate stack, and $y < x - 1$. Indeed, no sequence of operations will allow us to insert the <<missing>> plates in between them. Let's call the state of the stacks a dead-end if this situation happens. Let's call the operation which moves the plates into the dryer in the right sequence an output. Because the output can be done at any moment, let's check the possibility of the output when we finish performing any operation and perform the output whenever we can. In the following paragraphs, we will examine the situations where the output is impossible. Let's call the sequence of the plates an almost decreasing sequence if it consists of one or more sections and in every section the sizes of the plates are consecutive natural numbers, and all plates in the following sections are smaller than in the previous ones. To describe it in another way, this is how an almost decreasing sequence looks like: $x_{1}, x_{1} + 1, x_{1} + 2, ..., y_{1}, x_{2}, x_{2} + 1, x_{2} + 2, ..., y_{2}, x_{3}, ...$, where $x_{1} > y_{2}$, $x_{2} > y_{3}$ and so on. Let's examine the maximum almost decreasing sequence on the top of the dirty stack. It's easy to see that before we move all plates from that sequence to the intermediate stack the operation which moves a plate that does not belong to that sequence to the intermediate stack would create a dead-end, because the size of the last plate in this sequence is at least $2$ less than the size of the next plate. It's also clear that we can't perform an output before moving all of the sequence into the intermediate stack. This means that the only actions we can perform will lead to all of the plates of this sequence ending up in the intermediate stack, but the question is in the order in which they will be placed. There are two cases possible: The sizes of the plates in this sequence form an continious segment of the natural number sequence, which means that $y_{2} = x_{1} - 1$, $y_{3} = x_{2} - 1$ and so on. In this situation we can move sections one-by-one onto the intermediate stack to be able to move all of it to the dryer later at once. It's obvious that there wouldn't be a dead-end inside of the sequence. If the dead-end situation happened on a junction with the lower plates in this stack, it would have happened no matter the way we move the sequence. A similiar statement can be said about the junction with the plates that would later appear on the top of this sequence. This means that our way of moving plates is optimal, therefore let's perform it. There are <<holes>> in the set of plate sizes in the sequence. Then we can notice that if we won't move the sequence to the intermediate stack with one operation, we will arrive at the dead-end if we try to move this sequence with any other set of operations. This can be shown more formally by assuming we moved a part of sequence that was higher than <<hole>> below it or vice-versa, the part that was below the <<hole>> above it. In this situation, we have no choice but to move a sequence as a whole. We found an optimal operation for every situation and that means we can solve the problem with $a = b =  \\infty $ by modelling an optimal turn by using $O(n^{2})$ time, or $O(n)$ if we want so. If all plates end up in the dryer, our order of operations is the solution, otherwise there's no solution. Let's now discuss how to incorporate our solution for $a = b =  \\infty $ to our problem with finite $a$ and $b$. The output from the dirty stack can still be performed by moving plates one-by-one to the intermediate stack and then moving them from the intermediate stack one-by-one. Output from the intermediate stack isn't always possible, and because of this you have to keep an eye on the size of the sections in the intermediate stack. However, if an output exists that is possible to perform, we must perform it, and if it isn't possible, we won't be able to put the plates into the correct order. Due to this we assume that all possible outputs are done. Again we will examine the maximum almost decreasing sequence on the top of the dirty stack and there are again two similiar cases:: If <<holes>> exist, the only possible operation, as discussed earlier, is to move the whole sequence. If the length of this sequence exceeds $a$, we have no way to place the plates in the right order at all. If there are no <<holes>>, there are several possibilities. The length of the sections is now important and that means it isn't always optimal to put the plates into the ascending order. Let's consider several cases: If $a$ and $b$ are big enough to be able to do the same operations with it as if they were infinite. Then we need to do it because if any other section would join this one from above or below this would be the only situation that wouldn't be a dead-end. Otherwise we would be able to output this sequence by using a single operation, and because of the fact that its size does not exceed $b$ it would be a possible and optimal operation. In any other situation we have to move this sequence to the intermediate stack in some other way. Let's consider the case where the length of the sequence exceeds $b$. There are several cases: If the sequence consists of a lone section, we need to move it so the sizes of plates in the section would form a descending sequence in the intermediate stack by moving the plates one-by-one. Indeed, there's no way to make the smallest plate the top one or to make the biggest plate the bottom one (it would allow our sequence to join other blocks) without meeting a dead-end or making a section with its length bigger than $b$, so it's optimal to make all sections as short as possible (length $1$) so we would certainly be able to output them. In the case of the sequence having more than two sections, the only way to move them without creating a dead-end is to move the section as a whole. If it's impossible, there's no solution. The only case left here is the case of the sequence consisting of two sections. There are only two ways to move those sections without meeting a dead-end - we either move the part of the top section and then we move everything else, or we move the first section and the part of the second and then we move the remaining part of the second section. We have to make the length of the parts we move to be no more than $a$ and the length of the resulting sections to be no more than $b$. It's easy to write the inequalities which describe whether these operations are possible. It's also easy to check that we can't make the smallest plate the top one or to make the biggest plate the bottom one and that means our sections wouldn't join any other sections. Because of this, any sequence of moves which satisfies the inequalities would suit us. Let's now assume that $b$ is large enough to move the whole sequence at once, but $a$ is smaller than the size of a particular section and so we are unable to sort the sequence into the ascending order. If there is only one section, we can just move them one-by-one as discussed earlier. If there are more than two sections, we are unable to move them without meeting a dead-end If there are two sections, the situation is similiar to the situation where we couldn't perform our operations due to $b$ being too small, although we don't have to limit the length of the section after moving our plates to the intermediate stack (because it would be less than $b$). As we can see, there's an optimal operation on an every step. The solution is to model the optimal operations. A program that would solve this problem in $O(n)$ time could be written, but the constraints were set which allowed to write the solution which would run in $O(n^{2})$ time so as not to complicate matters with extra operations. As we can see, there's an optimal operation on an every step. The solution is to model the optimal operations. A program that would solve this problem in $O(n)$ time could be written, but the constraints were set which allowed to write the solution which would run in $O(n^{2})$ time so as not to complicate matters with extra operations.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "739",
    "index": "A",
    "title": "Alyona and mex",
    "statement": "Alyona's mother wants to present an array of $n$ non-negative integers to Alyona. The array should be special.\n\nAlyona is a capricious girl so after she gets the array, she inspects $m$ of its subarrays. Subarray is a set of some subsequent elements of the array. The $i$-th subarray is described with two integers $l_{i}$ and $r_{i}$, and its elements are $a[l_{i}], a[l_{i} + 1], ..., a[r_{i}]$.\n\nAlyona is going to find mex for each of the chosen subarrays. Among these $m$ mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible.\n\nYou are to find an array $a$ of $n$ elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.\n\nThe mex of a set $S$ is a minimum possible non-negative integer that is not in $S$.",
    "tutorial": "Obviously, the answer to the problem can not be greater than the minimum length among the lengths of the sub-arrays. Suppose that the minimum length of all the sub-arrays is equal to len. Then the desired array is: $0, 1, 2, 3, ..., len - 1, 0, 1, 2, 3, ... len - 1...$. Not hard to make sure that mex of any subarray will be at least len.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "739",
    "index": "B",
    "title": "Alyona and a tree",
    "statement": "Alyona has a tree with $n$ vertices. The root of the tree is the vertex $1$. In each vertex Alyona wrote an positive integer, in the vertex $i$ she wrote $a_{i}$. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).\n\nLet's define $dist(v, u)$ as the sum of the integers written on the edges of the simple path from $v$ to $u$.\n\nThe vertex $v$ controls the vertex $u$ ($v ≠ u$) if and only if $u$ is in the subtree of $v$ and $dist(v, u) ≤ a_{u}$.\n\nAlyona wants to settle in some vertex. In order to do this, she wants to know for each vertex $v$ what is the number of vertices $u$ such that $v$ controls $u$.",
    "tutorial": "Let's fix a vertex $v$. This node adds +1 to all the ancestors whose depth $depth[v] - a[v]  \\le  depth[p]$ ($depth[v]$ = the sum of the weights of edges on the path from the root to the vertex $v$). It's a segment of the ancestors, ending in v, as the depth increases when moving to the leaves. It remains to find the first ancestor on the way up, it does not hold for him - so you can make a binary lifting or binary search, if you will be storing the path to the root in dfs. With the partial sums you can calculate the answer for each vertices.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "739",
    "index": "C",
    "title": "Alyona and towers",
    "statement": "Alyona has built $n$ towers by putting small cubes some on the top of others. Each cube has size $1 × 1 × 1$. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.\n\nSometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from $l_{i}$ to $r_{i}$ and adds $d_{i}$ cubes on the top of them.\n\nLet the sequence $a_{1}, a_{2}, ..., a_{n}$ be the heights of the towers from left to right. Let's call as a segment of towers $a_{l}, a_{l + 1}, ..., a_{r}$ a hill if the following condition holds: there is integer $k$ ($l ≤ k ≤ r$) such that $a_{l} < a_{l + 1} < a_{l + 2} < ... < a_{k} > a_{k + 1} > a_{k + 2} > ... > a_{r}$.\n\nAfter each addition of $d_{i}$ cubes on the top of the towers from $l_{i}$ to $r_{i}$, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it.",
    "tutorial": "Let's consider the difference between two adjacent elements of array: $a[i] = arr[i + 1] - arr[i]$. Let us add $d$ in the segment from $l$ to $r$. Then it is clear that in the array $a$ will change no more than two values (at the ends of the addition of the segment), because if $l < i < r$, then $a[i] = arr[i + 1] + d - (arr[i] + d) = arr[i + 1] - arr[i]$. Note that the answer is a sequence of positive elements of $a$ + a sequence of negative elements of $a$ (i.e., ... +1 +1 +1 +1 -1 -1 ..., as the mountain first increases and then decreases). To solve this problem it's enough to take the tree segments and store at each vertex response to the prefix, suffix, and the middle. Two segments [l; m] and [m + 1; r] can be merged in case $sign(a[m + 1])  \\le  sign(a[m])$ and they are not equal to zero. suffix $+ 1 + 1 + 1 + 1 - 1 - 1 - 1 - 1$ and $- 1 - 1 - 1 - 1$ can be merged with prefix $- 1 - 1 - 1 - 1$ suffix $+ 1 + 1 + 1 + 1$ can be merged with prefix $- 1 - 1 - 1 - 1$ or prefix $+ 1 + 1 + 1 + 1 - 1 - 1 - 1 - 1$ Author's solution: http://codeforces.com/contest/739/submission/22453451",
    "code": "#pragma comment(linker, \"/stack:20000000\")\n#define _CRT_SECURE_NO_WARNINGS\n# include <iostream>\n# include <cstdio>\nusing namespace std;\n \ntemplate<class T>\nint sign(T x) {\n    return x > 0 ? 1 : x < 0 ? -1 : 0;\n}\n \nstruct Node {\n    int lval, mval, rval;\n};\nNode tr[2340400];\nlong long a[1010101];\ninline void recalc(int cur, int l, int r) {\n    int m = (l + r) / 2;\n    int dcur = cur + cur;\n    tr[cur].mval = max(tr[dcur].mval, tr[dcur + 1].mval);\n    if (!a[m] || !a[m + 1] || sign(a[m]) < sign(a[m + 1])) {\n        tr[cur].lval = tr[dcur].lval;\n        tr[cur].rval = tr[dcur + 1].rval;\n    } else {\n        tr[cur].mval = max(tr[cur].mval,  tr[dcur].rval + tr[dcur + 1].lval);\n        if (tr[dcur].mval == m - l + 1) {\n            tr[cur].lval = tr[dcur].lval + tr[dcur + 1].lval;\n        } else {\n            tr[cur].lval = tr[dcur].lval;\n        }\n        if (tr[dcur + 1].mval == r - m) {\n            tr[cur].rval = tr[dcur + 1].rval + tr[dcur].rval;\n        } else {\n            tr[cur].rval = tr[dcur + 1].rval;\n        }\n    }\n}\nvoid build(int cur, int l, int r) {\n    if (l == r) {\n        int x = !!a[l];\n        tr[cur] = {x, x, x};\n    } else {\n        int m = (l + r) / 2;\n        int dcur = cur + cur;\n        build(dcur, l, m);\n        build(dcur + 1, m + 1, r);\n        recalc(cur, l, r);\n    }\n}\n \nvoid update(int cur, int l, int r, int pos, int val) {\n    if (l == r) {\n        a[pos] += val;\n        int x = !!a[l];\n        tr[cur] = {x, x, x};\n    } else {\n        int m = (l + r) / 2;\n        int dcur = cur + cur;\n        if (pos <= m) {\n            update(dcur, l, m, pos, val);\n        } else {\n            update(dcur + 1, m + 1, r, pos, val);\n        }\n        recalc(cur, l, r);\n    }\n}\nint arr[1010101];\n \n \nint main() {\n#ifdef LOCAL\n    freopen(\"input.txt\", \"r\", stdin);\n    //    freopen(\"output.txt\", \"w\", stdout);\n#endif\n    int n;\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++) {\n        scanf(\"%d\", &arr[i]);\n    }\n    for (int i = 0; i < n - 1; ++i) {\n        a[i] = arr[i + 1] - arr[i];\n    }\n    if (n > 1) {\n        build(1, 0, n - 2);\n    }\n    int m;\n    scanf(\"%d\", &m);\n    while (m--) {\n        int l, r, d;\n        scanf(\"%d%d%d\", &l, &r, &d);\n        if(n == 1) {\n            puts(\"1\");\n            continue;\n        }\n        if (l != 1) {\n            update(1, 0, n - 2, l - 2, d);\n        }\n        if (r != n) {\n            update(1, 0, n - 2, r - 1, -d);\n        }\n        printf(\"%d\\n\", tr[1].mval + 1);\n    }\n    return 0;\n}\n \n ",
    "tags": [
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "739",
    "index": "D",
    "title": "Recover a functional graph",
    "statement": "Functional graph is a directed graph in which all vertices have outdegree equal to $1$. Loops are allowed.\n\nSome vertices of a functional graph lay on a cycle. From the others we can come to a cycle by making a finite number of steps along the edges (we consider only finite functional graphs in this problem).\n\nLet's compute two values for each vertex. $precycle_{i}$ is the amount of edges we should pass to get to a vertex which is a part of some cycle (zero, if $i$ itself lies on a cycle), $cycle_{i}$ is the length of the cycle we get to.\n\nYou are given the information about these values for some functional graph. For each vertex you know the values $precycle_{i}$ and $cycle_{i}$, however, instead of some values there can be the question mark. It means that these values are unknown.\n\nBuild any functional graph that suits the description or determine that there is no such graph.",
    "tutorial": "Let's think what has to hold after we put numbers in place of question marks: number of vertices with $precycle = 0$ and $cycle = y$ should be divisible by $y$. if there exists a vertex with $precycle = x > 0$ and $cycle = y$, then there should also exist a vertex with $precycle = x - 1$ and $cycle = y$. Now looking at vertices without question marks, let's count for every cycle length $y$ how many vertices have to be added for condition 1 to hold (keeping in mind that this number cannot be $0$ if there exist vertices of the form $(x, y)$ or $(?, y)$) and which precycle lengths are missing for condition 2 to hold. Here it's important that for 2 we have to consider vertices of the form $(x, ?)$. Specifically, in order for everything to be univocally determined, it is necerrary to try all the cycle lengths for the vertex of this form with maximal $x$. Some contestants tried to assign cycle lengths for such vertices greedily and got WA#15. Let's build the network for the flow which will have two parts. Vertices of the left part will correspond to the vertices of the functional graph that have at least one question mark. Vertices of the right part are the requirements of the form \"need $k$ vertices of the form $(0, y)$\" (for 1 to hold) and \"need one vertex of the from $(x, y)$\" (for 2 to hold). Add edges from the source to the left part, form the right part to the sink, and between requirements and vertices that satisfy them. If done correctly, with only one vertex created in the left part for all vertices of the same form in the functional graph, there will be $O(n)$ nodes and $O(n)$ edges in the network and the maximum flow will also be $O(n)$. Edmonds-Karp algorithm, which works in $O(E * flow)$ will work in $O(n^{2})$ on this network. Accounting for the bruteforce of the cycle length for the maximal vertex of the form $(x, ?)$ we get $O(n^{3})$ for the whole solution. In practice, any decent algorithm for finding maximum flow would most likely pass the system testing. Dinic works in 15 ms. If all of the vertices in the right part are saturated - the answer is found. Rolling back the flow, we will find which vertices in the left part saturated which ones in the right part. Now we can change the question marks to numbers for those vertices in the left part, that were used, but some question marks might still remain. This is no big deal. Let's change all vertices of the form $(x, ?)$ to $(x, maxc)$, where $maxc$ is that cycle length we bruteforce in the outermost loop. Instead of vertices of the form $(?, y)$ we can write $(1, y)$. Remember, that we created at least one cycle for all such $y$'s. Instead of $(?, ?)$ simply put $(0, 1)$. Now it's quite simple to get the answer to the problem. First create cycles out of the vertices of the form $(0, y)$, and then add edges $(x, y)$ -> $(x - 1, y)$.",
    "tags": [
      "graph matchings"
    ],
    "rating": 3400
  },
  {
    "contest_id": "739",
    "index": "E",
    "title": "Gosha is hunting",
    "statement": "Gosha is hunting. His goal is to catch as many Pokemons as possible. Gosha has $a$ Poke Balls and $b$ Ultra Balls. There are $n$ Pokemons. They are numbered $1$ through $n$. Gosha knows that if he throws a Poke Ball at the $i$-th Pokemon he catches it with probability $p_{i}$. If he throws an Ultra Ball at the $i$-th Pokemon he catches it with probability $u_{i}$. He can throw at most one Ball of each type at any Pokemon.\n\nThe hunting proceeds as follows: at first, Gosha chooses no more than $a$ Pokemons at which he will throw Poke Balls and no more than $b$ Pokemons at which he will throw Ultra Balls. After that, he throws the chosen Balls at the chosen Pokemons. If he throws both Ultra Ball and Poke Ball at some Pokemon, he is caught if and only if he is caught by any of these Balls. The outcome of a throw doesn't depend on the other throws.\n\nGosha would like to know what is the expected number of the Pokemons he catches if he acts in an optimal way. In other words, he would like to know the maximum possible expected number of Pokemons can catch.",
    "tutorial": "Let's divide Pokemons into 4 types: $0, A, B$ and $AB$ depending on Balls that we throw to them. Let's sort them by $u$ in descending order. Let's iterate over last Pokemon in which we throw Ultra Ball (his type is $B$ or $AB$). Let $i$ be the index of this Pokemon. It is not hard to prove that there are no Pokemons to the left of $i$ that have type $0$ and all Pokemons to the right of $i$ have type $0$ or $A$. Let's sort all Pokemons to the left of $i$ by $(1 - p) * u$ in descending order. Let's iterate last Pokemon of type $AB$. Let $j$ be his index. We can prove that to the left of $j$ every Pokemon has type $AB$ or $B$ (Let's call this group of Pokemons $X$). Between $j$ and $i$ every Pokemon has type $A$ or $B$ (will call them $Y$). To the right of $i$ only $0$ and $A$ (will call them $Z$). We know that we throw an Ultra Ball to every Pokemon in $X$. So let's add to our answer sum of $u$ of all Pokemons in $X$. Number of Pokemons in $Y$ of type $B$ equals to the difference between $b$ (number of Ultra Balls) and size of $X$. Therefore we know number of Pokemons in $Y$ of type $A$ and we know how many Poke Balls are left for $X$ and $Z$ summarily. Not hard to prove that in group $Y$ we should throw Poke Balls to Pokemons with greatest $u - p$. Now we have to understand in which Pokemons in $X$ and $Z$ we should throw Poke Balls. If we throw Poke Ball to Pokemon from $X$, it adds to the answer $p * (1 - u)$, from $Z$ - adds $p$. So we should throw Poke Balls to Pokemons with greatest values. When we iterate over $j$, each iteration one Pokemon moves from $Y$ to $X$. We can keep structure that can add and delete one element, find minimum and keep sum of all elements in the structure. For example, treap or map (in c++). Let's keep 2 such structures: for calculating answer for $Y$ and for calculating answer for throwing Poke Balls to Pokemons in $X$ and $Z$. The complexity - O($n^{2} \\cdot logn$).",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "flows",
      "math",
      "probabilities",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "740",
    "index": "A",
    "title": "Alyona and copybooks",
    "statement": "Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for $a$ rubles, a pack of two copybooks for $b$ rubles, and a pack of three copybooks for $c$ rubles. Alyona already has $n$ copybooks.\n\nWhat is the minimum amount of rubles she should pay to buy such number of copybooks $k$ that $n + k$ is divisible by $4$? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.",
    "tutorial": "Let $k$ - is the smallest non-negative integer such that $n + k$ is a multiple of 4. If $k$ is 0, then, obviously, the answer is 0. If $k$ is equal to 1, then you can buy one set of one notebook, you can buy 3 sets of three notebooks, you can buy 1 set of three notebooks and 1 set of two notebooks. Take the most optimal response. If $k$ equals 2, you can buy 2 sets of one notebook, 1 set of two notebooks, two sets of three notebooks. Take the most optimal response. If $k$ is equal to 3, you can buy 3 sets of one book, 1 set of single and 1 set of two notebooks, one set of three notebooks. Take the most optimal response.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "740",
    "index": "B",
    "title": "Alyona and flowers",
    "statement": "Little Alyona is celebrating Happy Birthday! Her mother has an array of $n$ flowers. Each flower has some mood, the mood of $i$-th flower is $a_{i}$. The mood can be positive, zero or negative.\n\nLet's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.\n\nFor example, consider the case when the mother has $5$ flowers, and their moods are equal to $1, - 2, 1, 3, - 4$. Suppose the mother suggested subarrays $(1, - 2)$, $(3, - 4)$, $(1, 3)$, $(1, - 2, 1, 3)$. Then if the girl chooses the third and the fourth subarrays then:\n\n- the first flower adds $1·1 = 1$ to the girl's happiness, because he is in one of chosen subarrays,\n- the second flower adds $( - 2)·1 = - 2$, because he is in one of chosen subarrays,\n- the third flower adds $1·2 = 2$, because he is in two of chosen subarrays,\n- the fourth flower adds $3·2 = 6$, because he is in two of chosen subarrays,\n- the fifth flower adds $( - 4)·0 = 0$, because he is in no chosen subarrays.\n\nThus, in total $1 + ( - 2) + 2 + 6 + 0 = 7$ is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!\n\nAlyona can choose any number of the subarrays, even $0$ or all suggested by her mother.",
    "tutorial": "If you restate the problem, it is clear that you need to take sub-arrays that have positive sum.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1200
  },
  {
    "contest_id": "741",
    "index": "A",
    "title": "Arpa's loud Owf and Mehrdad's evil plan",
    "statement": "As you have noticed, there are lovely girls in Arpa’s land.\n\nPeople in Arpa's land are numbered from $1$ to $n$. Everyone has exactly one crush, $i$-th person's crush is person with the number $crush_{i}$.\n\nSomeday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.\n\nThe game consists of rounds. Assume person $x$ wants to start a round, he calls $crush_{x}$ and says: \"Oww...wwf\" (the letter w is repeated $t$ times) and cuts off the phone immediately. If $t > 1$ then $crush_{x}$ calls $crush_{crushx}$ and says: \"Oww...wwf\" (the letter w is repeated $t - 1$ times) and cuts off the phone immediately. The round continues until some person receives an \"Owf\" ($t = 1$). This person is called the Joon-Joon of the round. There can't be two rounds at the same time.\n\nMehrdad has an evil plan to make the game more funny, he wants to find smallest $t$ ($t ≥ 1$) such that for each person $x$, if $x$ starts some round and $y$ becomes the Joon-Joon of the round, then by starting from $y$, $x$ would become the Joon-Joon of the round. Find such $t$ for Mehrdad if it's possible.\n\nSome strange fact in Arpa's land is that someone can be himself's crush (i.e. $crush_{i} = i$).",
    "tutorial": "Make a directed graph and put edge from $i$ and $crush_{i}$. If the graph has vertex such that its in-degree is 0 then obviously answer doesn't exist. Otherwise, the graph consists of some cycles. For each cycle suppose that its length is $len$. If it has odd length, add $len$ to $S$, otherwise, add $len / 2$. The answer is the LCM of numbers in $S$. Time complexity: ${\\cal O}(n)$.",
    "tags": [
      "dfs and similar",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "741",
    "index": "B",
    "title": "Arpa's weak amphitheater and Mehrdad's valuable Hoses",
    "statement": "Just to remind, girls in Arpa's land are really nice.\n\nMehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight $w_{i}$ and some beauty $b_{i}$. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses $x$ and $y$ are in the same friendship group if and only if there is a sequence of Hoses $a_{1}, a_{2}, ..., a_{k}$ such that $a_{i}$ and $a_{i + 1}$ are friends for each $1 ≤ i < k$, and $a_{1} = x$ and $a_{k} = y$.\n\nArpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most $w$ weight on it.\n\nMehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than $w$ and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed $w$.",
    "tutorial": "It's a simple knapsack problem. Let's solve this version of knapsack problem first: we have $n$ sets of items, each item has value and weight, find the maximum value we can earn if we can choose at most one item from each set and the sum of the chosen items must be less than or equal to $W$. Let $dp_{w}$ be the max value we can earn if the sum of weights of chosen items is less than or equal to $w$. Now iterate on sets one by one and update $dp$ as follows: for each item $X$, and for each weight $w$, $newDp_{w} = max(newDp_{w}, oldDp_{w - X.weight} + X.value)$. Run dfs and find groups at first. The problem is same with above problem, each group is some set in above problem, just add the whole group as an item to the set that related to this group. Time complexity: $O(n\\cdot W)$.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu"
    ],
    "rating": 1600
  },
  {
    "contest_id": "741",
    "index": "C",
    "title": "Arpa’s overnight party and Mehrdad’s silent entering",
    "statement": "Note that girls in Arpa’s land are really attractive.\n\nArpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw $n$ pairs of friends sitting around a table. $i$-th pair consisted of a boy, sitting on the $a_{i}$-th chair, and his girlfriend, sitting on the $b_{i}$-th chair. The chairs were numbered $1$ through $2n$ in clockwise direction. There was exactly one person sitting on each chair.\n\nThere were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that:\n\n- Each person had exactly one type of food,\n- No boy had the same type of food as his girlfriend,\n- Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs $2n$ and $1$ are considered consecutive.\n\nFind the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.",
    "tutorial": "Build a graph and put an edge between each $2 \\cdot i, 2 \\cdot i + 1$ and each BF and GF. This graph doesn't have cycles with odd length. So it is a bipartite graph. Now give Kooft to some part and Zahre-mar to other. Time complexity: ${\\cal O}(n)$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "741",
    "index": "D",
    "title": "Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths",
    "statement": "Just in case somebody missed it: we have wonderful girls in Arpa’s land.\n\nArpa has a rooted tree (connected acyclic graph) consisting of $n$ vertices. The vertices are numbered $1$ through $n$, the vertex $1$ is the root. There is a letter written on each edge of this tree. Mehrdad is a fan of Dokhtar-kosh things. He call a string Dokhtar-kosh, if we can shuffle the characters in string such that it becomes palindrome.\n\nHe asks Arpa, for each vertex $v$, what is the length of the longest simple path in subtree of $v$ that form a Dokhtar-kosh string.",
    "tutorial": "Please read my dsu on tree (sack) tutorial before you read. Let's calculate for each vertex such $v$, length of longest Dokhtar-kosh path that starts in some vertex of subtree of $v$, passes from $v$, and ends in some other vertex of subtree of $v$ using sack (explained below); then we can sum up this values and get answer for each vertex. First keep a mask for each vertex, $i$-th bit of $mask_{v}$ is $true$ if the number of edges on the path from the root to $v$ such that the letter $i$ is written on them is odd. Now if the number of bits in $m a s k_{n}\\oplus m a s k_{n}$ is $0$ or $1$, the path between $v$ and $u$ is Dokhtar-kosh. Let's use sack, assume $bag_{Mask}$ is the maximum height for a vertex that is present in our sack and its $mask$ is equal to $Mask$. Let's define two functions used in sack: $AddToSack$($vertex$ $x$) : If $bag_{maskx}$ is less than $h_{x}$, set $bag_{maskx} = h_{x}$. $UpdateCurrentAnswer$ ($vertex$ $x$, $vertex$ $root$) : For each $Mask$ such that $M a s k\\oplus m a s k_{*}$ has at most one bit, update the $CurrentAnswer$, with $h_{x} + bag_{Mask} - 2 \\cdot h_{root}$ (updating means if $CurrentAnswer$ is less than $h_{x} + bag_{Mask} - 2 \\cdot h_{root}$, set $CurrentAnswer$ to it). Suppose dfs function arrives to vertex $v$. Call dfs for each child of $v$ except the biggest one (which has more vertices in its subtree than others) and clear the sack each time. Call dfs for big child of $v$ and don't clear the sack. Then for each other child $u$ and for each vertex $x\\in s u b T r e e(u)$, call $UpdateCurrentAnswer(x, v)$. Then for each vertex $x\\in s u b T r e e(u)$, call $AddToSack(x)$. After the addition of the children is done, call $UpdateCurrentAnswer(v, v)$ and $AddToSack(v)$. Now the answer for this vertex is $CurrentAnswer$. To clear the sack, for each vertex $x\\in s u b T r e e(v)$ set $bag_{maskx} = - inf$ (i.e. $- 10^{9}$) and set $CurrentAnswer$ to 0. Note that there exists another solution using centroid decomposition, but it's harder. Time complexity: $O(n\\cdot\\log n\\cdot z)$ ($z$ is number of characters which is equal to 22). Corner case: You must use an array, no map or unordered map for $bag$, these solutions got TLE.",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "741",
    "index": "E",
    "title": "Arpa’s abnormal DNA and Mehrdad’s deep interest",
    "statement": "All of us know that girls in Arpa’s land are... ok, you’ve got the idea :D\n\nAnyone knows that Arpa isn't a normal man, he is ... well, sorry, I can't explain it more. Mehrdad is interested about the reason, so he asked Sipa, one of the best biology scientists in Arpa's land, for help. Sipa has a DNA editor.\n\nSipa put Arpa under the DNA editor. DNA editor showed Arpa's DNA as a string $S$ consisting of $n$ lowercase English letters. Also Sipa has another DNA $T$ consisting of lowercase English letters that belongs to a normal man.\n\nNow there are $(n + 1)$ options to change Arpa's DNA, numbered from $0$ to $n$. $i$-th of them is to put $T$ between $i$-th and $(i + 1)$-th characters of $S$ ($0 ≤ i ≤ n$). If $i = 0$, $T$ will be put before $S$, and if $i = n$, it will be put after $S$.\n\nMehrdad wants to choose the most interesting option for Arpa's DNA among these $n + 1$ options. DNA $A$ is more interesting than $B$ if $A$ is lexicographically smaller than $B$. Mehrdad asked Sipa $q$ questions:\n\nGiven integers $l, r, k, x, y$, what is the most interesting option if we only consider such options $i$ that $l ≤ i ≤ r$ and $x\\leq(i{\\mathrm{~mod~}}k)\\leq y$? If there are several most interesting options, Mehrdad wants to know one with the smallest number $i$.\n\nSince Sipa is a biology scientist but not a programmer, you should help him.",
    "tutorial": "First sort all of the options. Use suffix array to compare two options. Give rank to each option. Then problem is to find minimum rank in each query. Use sqrt decomposition and divide queries into two groups: - $K\\geq{\\sqrt{n}}$ There are less than $\\sqrt{n}$ segments that satisfy the conditions. Keep all of them, solve them at the end together with some method (it's a simple RMQ). - $K<{\\sqrt{n}}$ Keep the query in some vector assigned to this $K$. Now for each $K$ from $1$ to ${\\sqrt{n}}-1$: Break array into $K$ arrays. $i$-th of them contains indexes $j$ such that $j\\;{\\mathrm{mod}}\\;K=i$. Then break each query assigned to this $K$ into these arrays and solve them with some method (it's a simple RMQ). Time complexity : $O(n\\cdot{\\sqrt{n}})$ (if you use some ${\\cal O}(n)$ method for solving RMQ part).",
    "tags": [
      "data structures",
      "string suffix structures"
    ],
    "rating": 3400
  },
  {
    "contest_id": "742",
    "index": "A",
    "title": "Arpa’s hard exam and Mehrdad’s naive cheat",
    "statement": "There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.\n\nMehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given $n$, print the last digit of $1378^{n}$.\n\nMehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.",
    "tutorial": "You know $1378^{n}\\;\\;\\mathrm{mod}\\;10=8^{n}\\;\\;\\mathrm{mod}\\;10$. If $n = 0$ answer is 1, otherwise, you can prove with induction that if: - $n\\ \\mathrm{\\mod}\\ 4=0$ then answer is 6. - $n\\ \\mathrm{\\mod}\\ 4=1$ then answer is 8. - $n\\ \\mathrm{\\mod}\\ 4=2$ then answer is 4. - $n\\ \\mathrm{\\mod}\\ 4=3$ then answer is 2. Time complexity: $O(1)$. Corner case: Solutions that forget to add $n = 0$ case got failed system testing.",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "742",
    "index": "B",
    "title": "Arpa’s obvious problem and Mehrdad’s terrible solution",
    "statement": "There are some beautiful girls in Arpa’s land as mentioned before.\n\nOnce Arpa came up with an obvious problem:\n\nGiven an array and a number $x$, count the number of pairs of indices $i, j$ ($1 ≤ i < j ≤ n$) such that $a_{i}\\oplus a_{j}=x$, where $\\mathbb{C}$ is bitwise xor operation (see notes for explanation).\n\nImmediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.",
    "tutorial": "Note that if $a_{i}\\oplus a_{j}=X$ then $a_{i}\\oplus X=a_{j}$. Keep in $num_{x}$ the number of repetitions of number $x$. Now for each $x$, add $\\scriptstyle n=n\\,m_{X\\in X}$ to answer. Then divide answer by 2 (if $X$ is 0, don't). Time complexity: ${\\mathcal{O}}(n)$. Corner case #1: Some codes got WA when $X$ is 0. Corner case #2: Some codes got RE because $x\\oplus y$ can be as large as $max(x, y) \\cdot 2$.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "743",
    "index": "A",
    "title": "Vladik and flights",
    "statement": "Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.\n\nVladik knows $n$ airports. All the airports are located on a straight line. Each airport has unique id from $1$ to $n$, Vladik's house is situated next to the airport with id $a$, and the place of the olympiad is situated next to the airport with id $b$. It is possible that Vladik's house and the place of the olympiad are located near the same airport.\n\nTo get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport $a$ and finish it at the airport $b$.\n\nEach airport belongs to one of two companies. The cost of flight from the airport $i$ to the airport $j$ is zero if both airports belong to the same company, and $|i - j|$ if they belong to different companies.\n\nPrint the minimum cost Vladik has to pay to get to the olympiad.",
    "tutorial": "The answer is $0$, if airports with numbers $a$ and $b$ belong to one company. Otherwise there are two adjacent airports, that belong to different companies. We can get to one of them for free, then pay $1$ to fly from one to another and then fly to airport number $b$ for free. So, in this case the answer is $1$. Complexity $O(n)$.",
    "code": "int n, a, b;\nstring s;\ncin >> n >> a >> b >> s;\n\na--, b--;\n\ncout << ((s[a] - '0') ^ (s[b] - '0'));",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "743",
    "index": "B",
    "title": "Chloe and the sequence ",
    "statement": "Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.\n\nLet's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to $1$. Then we perform $(n - 1)$ steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence $[1, 2, 1]$ after the first step, the sequence $[1, 2, 1, 3, 1, 2, 1]$ after the second step.\n\nThe task is to find the value of the element with index $k$ (the elements are numbered from $1$) in the obtained sequence, i. e. after $(n - 1)$ steps.\n\nPlease help Chloe to solve the problem!",
    "tutorial": "Consider the string after $n$ steps of algorithm. We can split it into three parts: string from previous step, new character, another one string from previous step. Lets find the part, where our $k$-th character is, and reduce our string to the string from the previous step. The complexity is $O(n)$.",
    "code": "int go(ll l, ll r, ll need, int alphSize)\n{\n    ll m = l + (r - l) / 2LL;\n    if (need < m)\n        return go(l, m - 1, need, alphSize - 1);\n    else if (need > m)\n        return go(m + 1, r, need, alphSize - 1);\n    else\n        return alphSize;\n}\n\nvoid solveABig()\n{\n    int n;\n    ll k;\n\n    cin >> n >> k;\n    ll sz = 1;\n    for (int i = 1; i < n; i++)\n        sz = sz * 2LL + 1LL;\n    \n    cout << go(1, sz, k, n);\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "743",
    "index": "C",
    "title": "Vladik and fractions",
    "statement": "Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer $n$ he can represent fraction $\\frac{2}{n}$ as a sum of three distinct positive fractions in form $\\frac{1}{m}$.\n\nHelp Vladik with that, i.e for a given $n$ find three distinct positive integers $x$, $y$ and $z$ such that ${\\frac{2}{n}}={\\frac{1}{x}}+{\\frac{1}{y}}+{\\frac{1}{z}}$. Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding $10^{9}$.\n\nIf there is no such answer, print -1.",
    "tutorial": "Note that for $n = 1$ there is no solution, and for $n > 1$ there is solution $x = n, y = n + 1, z = n \\cdot (n + 1)$. To come to this solution, represent ${\\frac{2}{n}}={\\frac{1}{n}}+{\\frac{1}{n}}$ and reduce the problem to represent $\\frac{1}{n}$ as a sum of two fractions. Let's find the difference between $\\frac{1}{n}$ and $\\frac{1}{n+1}$ and get a fraction $\\frac{1}{n\\cdot(n+1)}$, so the solution is ${\\frac{2}{n}}={\\frac{1}{n}}+{\\frac{1}{n+1}}+{\\frac{1}{n\\cdot(n+1)}}$",
    "code": "int n;\ncin >> n;\nif (n == 1)\n\tcout << -1 << endl;\nelse\n\tcout << n << ' ' << n + 1 << ' ' << n * (n + 1) << endl;",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "743",
    "index": "D",
    "title": "Chloe and pleasant prizes",
    "statement": "Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes.\n\nThey took $n$ prizes for the contestants and wrote on each of them a unique id (integer from $1$ to $n$). A gift $i$ is characterized by integer $a_{i}$ — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift $1$ on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with $n$ vertices.\n\nThe prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.\n\nOur friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.\n\nPrint the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.",
    "tutorial": "Our task is to choose two disjoint subtrees, such that sum of numbers in the first plus the sum in the second is maximal. Lets calculate for each vertex this dynamic programming using dfs seach: $sum_{v}$ - sum of all the numbers in subtree of vertex $v$, and $mx_{v}$ - maximal value from all $sum_{k}$ in subtree of vertex $v$ ($k$ belongs to subtree of $v$). We can calculate the answer using another dfs search, maintaining the value of maximal subtree, which is outside of current subtree. For example, if we are in vertex $v$, to update this value when going to call $dfs(s)$ (where $s$ is some son of $v$) we have to find maximal $mx_{v}$ from all other sons of $v$. The complexity is $O(n)$.",
    "code": "int a[maxn];\nvector<int> g[maxn];\n\nll sum_subTree[maxn], mx_subTree[maxn];\n\nvoid dfs1(int v, int p) {\n    sum_subTree[v] = a[v];\n    mx_subTree[v] = -llinf;\n    for (int i = 0; i < g[v].size(); i++) {\n        int to = g[v][i];\n        if (to == p)\n            continue;\n        dfs1(to, v);\n        sum_subTree[v] += sum_subTree[to];\n        mx_subTree[v] = max(mx_subTree[v], mx_subTree[to]);\n    }\n    mx_subTree[v] = max(mx_subTree[v], sum_subTree[v]);\n}\n\nll ans = -llinf;\n\nvoid dfs2(int v, int p, ll out) {\n    if (out != -llinf)\n    ans = max(ans, sum_subTree[v] + out);\n\n    vector<pair<ll, int> > miniset;\n    for (int i = 0; i < g[v].size(); i++) {\n        int to = g[v][i];\n        if (to == p)\n            continue;\n        miniset.pb(mp(mx_subTree[to], to));\n        sort(miniset.rbegin(), miniset.rend());\n        if (miniset.size() == 3)\n            miniset.pop_back();\n    }\n    miniset.pb(mp(-llinf, -1));\n    for (int i = 0; i < g[v].size(); i++) {\n        int to = g[v][i];\n        if (to == p)\n            continue;\n        ll cur = miniset[0].s == to ? miniset[1].f : miniset[0].f;\n        dfs2(to, v, max(out, cur));\n    }\n}\n\nint main() {\n    for (int i = 0; i + 1 < n; i++) {\n        int u, v;\n        read(u, v);\n        u--, v--;\n        g[u].pb(v);\n        g[v].pb(u);\n    }\n\n    dfs1(0, -1);\n    dfs2(0, -1, -llinf);\n    cout << ((ans == -llinf) ? (\"Impossible\") : to_string(ans));\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "743",
    "index": "E",
    "title": "Vladik and cards",
    "statement": "Vladik was bored on his way home and decided to play the following game. He took $n$ cards and put them in a row in front of himself. Every card has a positive integer number not exceeding $8$ written on it. He decided to find the longest subsequence of cards which satisfies the following conditions:\n\n- the number of occurrences of each number from $1$ to $8$ in the subsequence doesn't differ by more then $1$ from the number of occurrences of any other number. Formally, if there are $c_{k}$ cards with number $k$ on them in the subsequence, than for all pairs of integers $i\\in[1,8],j\\in[1,8]$ the condition $|c_{i} - c_{j}| ≤ 1$ must hold.\n- if there is at least one card with number $x$ on it in the subsequence, then all cards with number $x$ in this subsequence must form a continuous segment in it (\\textbf{but not necessarily a continuous segment in the original sequence}). For example, the subsequence $[1, 1, 2, 2]$ satisfies this condition while the subsequence $[1, 2, 2, 1]$ doesn't. Note that $[1, 1, 2, 2]$ doesn't satisfy the first condition.\n\nPlease help Vladik to find the length of the longest subsequence that satisfies both conditions.",
    "tutorial": "Suppose we have taken at least $len$ cards of each color and $b$ colors of them have $len + 1$ cards. Then the answer will look like: $(8 - b) * len + b * (len + 1)$. Obviously, if our sequence of cards allows us to take $len$ cards of each color, then it allows to take $len - 1$, and $len - 2$, so on. Lets binary search for $len$ value, and check allowability this way: Define bitmask dynamic programming $dp[pos][mask]$ ($1  \\le  pos  \\le  n, 0  \\le  mask  \\le  2^{8} - 1$) as the number of colors, for which we have taken $len + 1$ element, if we passed $pos$ cards in the sequence and the colors, which has bit equal to one in bitmask mask. We will have two different transitions. Iterate the new color, which has zero bit in the mask, to make the first transition, and find its occurrence number $len$ in subarray $[pos + 1, n]$. The second transition is completely the same, but we have to find occurrence number $(len + 1)$. To find the occurrence number $len$ of some color in subarray we should maintain an array of the remaining cards for each color. Finally, find the maximal allowable $len$, and in dp calculated for $len$ find the maximal additional cards in $dp[n][2^{8} - 1]$. This solution for $k$ colors of cards (8 in our case) has complexity $O(log(n) * n * k * 2^{k})$.",
    "code": "int can(int len) {\n    for (int i = 0; i < 8; i++)\n        cur[i] = 0;\n    for (int i = 0; i <= n; i++)\n        for (int j = 0; j < (1 << 8); j++)\n            dp[i][j] = -inf;\n    dp[0][0] = 0;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < (1 << 8); j++) {\n            if (dp[i][j] == -inf)\n                continue;\n            for (int k = 0; k < 8; k++) {\n                if (j & (1 << k))\n                    continue;\n                int it = cur[k] + len - 1;\n                if (it >= in[k].size())\n                    continue;\n                amax(dp[in[k][it] + 1][j | (1 << k)], dp[i][j]);\n                    \n                it++;\n                if (it >= in[k].size())\n                    continue;\n                amax(dp[in[k][it] + 1][j | (1 << k)], dp[i][j] + 1);\n            }\n        }\n        cur[a[i]]++;\n    }\n\n    int ans = -inf;\n    for (int i = 0; i <= n; i++)\n        ans = max(ans, dp[i][(1 << 8) - 1]);\n    if (ans == -inf)\n        return -1;\n\n    return ans * (len + 1) + (8 - ans) * len;\n}\n\nint main() {\n    for (int i = 0; i < n; i++) {\n        in[a[i]].push_back(i);\n    }\n\n    int l = 1, r = n / 8;\n    while (r - l > 1) {\n        int m = (l + r) >> 1;\n        if (can(m) != -1)\n            l = m;\n        else\n            r = m;\n    }\n    int ans = max(can(l), can(r));\n    if (ans == -1) {\n        ans = 0;\n        for (int i = 0; i < 8; i++)\n            if (!in[i].empty())\n                ans++;\n    }\n    cout << ans;\n    return 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "744",
    "index": "A",
    "title": "Hongcow Builds A Nation",
    "statement": "Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.\n\nThe world can be modeled as an undirected graph with $n$ nodes and $m$ edges. $k$ of the nodes are home to the governments of the $k$ countries that make up the world.\n\nThere is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, \\textbf{there is no path between those two nodes}. Any graph that satisfies all of these conditions is stable.\n\nHongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.",
    "tutorial": "First, let's make all connected components cliques. This graph is still stable. Now, there are some components without special nodes. Where should we connect them? If there is a component with size A and a component with size B, we can add A*B edges if we connect these two components. So, it makes sense to choose the largest component.",
    "code": "n,m,k = map(int, raw_input().split())\nspecial = map(int, raw_input().split())\n\nroot = range(n+1)\n\ndef par(p):\n\tif p != root[p]:\n\t\troot[p] = par(root[p])\n\treturn root[p]\n\ndef c2(n):\n\treturn n * (n - 1) / 2\n\nfor __ in xrange(m):\n\tu,v = map(par, map(int, raw_input().split()))\n\troot[v] = u\n\nsz = [0 for i in range(n+1)]\nfor i in range(n+1):\n\tsz[par(i)] += 1\n\nleftover = n\nans = 0\nlargest = 0\nfor x in special:\n\td = par(x)\n\tlargest = max(largest, sz[d])\n\tans += c2(sz[d])\n\tleftover -= sz[d]\n\nans -= c2(largest)\nans += c2(largest + leftover)\nans -= m\n\nprint ans",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "744",
    "index": "B",
    "title": "Hongcow's Game",
    "statement": "\\textbf{This is an interactive problem. In the interaction section below you will see the information about flushing the output.}\n\nIn this problem, you will be playing a game with Hongcow. How lucky of you!\n\nHongcow has a hidden $n$ by $n$ matrix $M$. Let $M_{i, j}$ denote the entry $i$-th row and $j$-th column of the matrix. The rows and columns are labeled from $1$ to $n$.\n\nThe matrix entries are between $0$ and $10^{9}$. In addition, $M_{i, i} = 0$ for all valid $i$. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each $i$, you must find $\\mathrm{min}_{j\\neq i}\\,M_{i,j}$.\n\nTo do this, you can ask Hongcow some questions.\n\nA question consists of giving Hongcow a subset of distinct indices ${w_{1}, w_{2}, ..., w_{k}}$, with $1 ≤ k ≤ n$. Hongcow will respond with $n$ integers. The $i$-th integer will contain the minimum value of $min_{1 ≤ j ≤ k}M_{i, wj}$.\n\nYou may only ask Hongcow at most $20$ questions — he thinks you only need that many questions answered.\n\nWhen you are ready to answer, print out a single integer $ - 1$ on its own line, then $n$ integers on the next line. The $i$-th integer should be the minimum value in the $i$-th row of the matrix, excluding the $i$-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.\n\nYou will get Wrong Answer verdict if\n\n- Your question or answers are not in the format described in this statement.\n- You ask strictly more than $20$ questions.\n- Your question contains duplicate indices.\n- The value of $k$ in your question does not lie in the range from $1$ to $n$, inclusive.\n- Your final answer is not correct.\n\nYou will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).",
    "tutorial": "For the bits solution: We want to create 20 questions where for every i != j, there exists a question that contains j and not i, and also a qusetion that contains i and not j. If we can do this, we can find the min for each row. Note that i != j implies that there exists a bit index where i and j differ. So, let's ask 2 questions for each bit position, one where all indices have a value of 0 in that position, and one where all indices have a value of 1 in that position. This is a total of at most 20 questions, and we can show that this satisfies the condition above, so this solves the problem. Parallelization will basically reduce to the above solution, but is another way of looking at the problem. First, let's ask {1,2,...,n/2} and {n/2+1,...,n} This handles the case where the min lies on the opposite half. For example, this handles the case where the min lies in the X part of the matrix, and we split it into two identical problems of size n/2 within the O matrix. Now, we can ask questions for each submatrix, but we can notice that these two don't interact so we can combine all the questions at this level. However, we should ask the questions in parallel, as we don't have that many questions For example, for n=8, we should ask As you can see, this reduces to the bit approach above if N is a power of 2.",
    "code": "import java.io.PrintWriter;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Scanner;\n\npublic class HiddenMatrix {\n    public static void main (String[] args) {\n        Scanner in = new Scanner(System.in);\n        PrintWriter out = new PrintWriter(System.out);\n        int n = in.nextInt();\n        int[] min = new int[n+1];\n        Arrays.fill(min, 1 << 30);\n        for (int bit = 0; bit < 10; bit++) {\n            for (int val = 0; val <= 1; val++) {\n                ArrayList<Integer> query = new ArrayList<>();\n                for (int i = 1; i <= n; i++) {\n                    if (((i >> bit) & 1) == val) {\n                        query.add(i);\n                    }\n                }\n                if (query.size() != n && query.size() != 0) {\n                    out.println(query.size());\n                    for (int j = 0; j < query.size(); j++) {\n                        if (j != 0) out.print(\" \");\n                        out.print(query.get(j));\n                    }\n                    out.println();\n                    out.flush();\n\n                    for (int i = 1; i <= n; i++) {\n                        int d = in.nextInt();\n                        if (((i >> bit) & 1) == 1 - val) {\n                            min[i] = Math.min(min[i], d);\n                        }\n                    }\n                }\n            }\n        }\n\n        out.println(-1);\n        for (int i = 1; i <= n; i++) {\n            if (i != 1) out.print(\" \");\n            out.print(min[i]);\n        }\n        out.println();\n        out.flush();\n        System.exit(0);\n    }\n}",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "interactive"
    ],
    "rating": 1900
  },
  {
    "contest_id": "744",
    "index": "C",
    "title": "Hongcow Buys a Deck of Cards",
    "statement": "One day, Hongcow goes to the store and sees a brand new deck of $n$ special cards. Each individual card is either red or blue. He decides he wants to buy them immediately. To do this, he needs to play a game with the owner of the store.\n\nThis game takes some number of turns to complete. On a turn, Hongcow may do one of two things:\n\n- Collect tokens. Hongcow collects $1$ red token \\textbf{and} $1$ blue token by choosing this option (thus, $2$ tokens in total per one operation).\n- Buy a card. Hongcow chooses some card and spends tokens to purchase it as specified below.\n\nThe $i$-th card requires $r_{i}$ red resources and $b_{i}$ blue resources. Suppose Hongcow currently has $A$ red cards and $B$ blue cards. Then, the $i$-th card will require Hongcow to spend $max(r_{i} - A, 0)$ red tokens, and $max(b_{i} - B, 0)$ blue tokens. Note, only tokens disappear, but the cards stay with Hongcow forever. Each card can be bought only once.\n\nGiven a description of the cards and their costs determine the minimum number of turns Hongcow needs to purchase all cards.",
    "tutorial": "Also note that if r_i or b_i >= n, we need to collect tokens no matter what since those costs can't be offset. So, we can assume that r_i, b_i <= n. Let's only buy tokens when we need them. Note that after buying a card, you will have either 0 red tokens or 0 blue tokens, so our dp state can be described by [mask][which one is zero][how many of the other] The dimensions of this dp table are 2^n * 2 * (n^2) (n^2 because the costs to buy cards is at most n). See the code for more details on how to update this dp.",
    "code": "import java.util.Arrays;\nimport java.util.Scanner;\n\npublic class RedAndBlueCards {\n    public static int n;\n    public static char[] color;\n    public static int[] r,b;\n    public static int[] countred, countblue;\n    public static void main (String[] args) {\n        Scanner in = new Scanner(System.in);\n        n = in.nextInt();\n        color = new char[n];\n        r = new int[n];\n        b = new int[n];\n        int base = 0;\n        int needred = 0, needblue = 0;\n        for (int i = 0; i < n; i++) {\n            color[i] = in.next().charAt(0);\n            r[i] = in.nextInt();\n            b[i] = in.nextInt();\n            needred += Math.max(0, r[i] - n);\n            needblue += Math.max(0, b[i] - n);\n            r[i] = Math.min(n, r[i]);\n            b[i] = Math.min(n, b[i]);\n        }\n        base = Math.max(needred, needblue);\n\n        countred = new int[1<<n];\n        countblue = new int[1<<n];\n        for (int i = 1; i < 1 << n; i++) {\n            int lowbit = Integer.numberOfTrailingZeros(i & -i);\n            countred[i] = countred[i ^ (1 << lowbit)];\n            countblue[i] = countblue[i ^ (1 << lowbit)];\n            if (color[lowbit] == 'R') countred[i]++;\n            else countblue[i]++;\n        }\n\n        dp = new int[2][n*n+1][1<<n];\n        for (int[][] x : dp) for (int[] y : x) Arrays.fill(y, -1);\n\n        int ans = base + n;\n        if (needred < needblue) {\n            ans += solve(0, 0, needblue - needred);\n        } else {\n            ans += solve(0, 1, needred - needblue);\n        }\n        System.out.println(ans);\n        System.exit(0);\n    }\n\n    public static int[][][] dp;\n    public static int solve(int mask, int redempty, int other) {\n        other = Math.min(other, n*n);\n        if (mask == (1<<n)-1) return 0;\n        if (dp[redempty][other][mask] != -1) return dp[redempty][other][mask];\n        int ret = 1 << 29;\n        for (int i = 0; i < n; i++) {\n            if (((mask>>i)&1) == 1) continue;\n            int pmask = mask | (1 << i);\n            int havered = redempty == 1 ? 0 : other;\n            int haveblue = redempty == 0 ? 0 : other;\n            int cardred = countred[mask], cardblue = countblue[mask];\n\n            int nred = Math.max(0, r[i]-(cardred+havered));\n            int nblue = Math.max(0, b[i]-(cardblue+haveblue));\n            int needmoves = Math.max(nred, nblue);\n            int nextred = havered + needmoves - Math.max(0, r[i] - cardred);\n            int nextblue = haveblue + needmoves - Math.max(0, b[i] - cardblue);\n\n            if (nextred == 0) {\n                ret = Math.min(ret, needmoves + solve(pmask, 1, nextblue));\n            }\n            if (nextblue == 0) {\n                ret = Math.min(ret, needmoves + solve(pmask, 0, nextred));\n            }\n        }\n        return dp[redempty][other][mask] = ret;\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "744",
    "index": "D",
    "title": "Hongcow Draws a Circle",
    "statement": "Hongcow really likes the color red. Hongcow doesn't like the color blue.\n\nHongcow is standing in an infinite field where there are $n$ red points and $m$ blue points.\n\nHongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the boundary of the circle can be counted as either inside or outside.\n\nCompute the radius of the largest circle that satisfies this condition. If this circle can have arbitrarily large size, print $ - 1$. Otherwise, your answer will be accepted if it has relative or absolute error at most $10^{ - 4}$.",
    "tutorial": "First to check if an answer can be arbitrarily large, we can see if there is any red point that is on the convex hull of all our points. So from now on, we can assume the answer is finite. We can show that the optimal circle must touch a blue point. To see this, consider any optimal circle that doesn't touch a blue point. We can make it slightly bigger so that it does touch one. So, let's binary search for the answer. However, you have to very careful and notice that the binary search isn't monotonic if we only consider circles touching blue points. However, if we consider circles that touch either a red or blue point, then the binary search is monontonic, so everything works out. To check if a radius works, we can do a angle sweep around our center point. We have a fixed radius and fixed center, so each other point has at most two angles where it enters and exits the circle as we rotate it about the center point. We can keep track of these events and find an interval where the circle only contains red points. For the inversion solution, let's fix the blue point that our circle touches. Then, let's take the inversion around this point (i.e. https://en.wikipedia.org/wiki/Inversive_geometry). Now, circles that pass through our center points become lines, and the interior of those circles are in the halfplane not containing the center point. The radius of the circle is inversely proportional to the distance between our center point to the line after inversion. So, we can say we want to solve the following problem after inversion. Find the closest line that contains no blue points in the halfplane facing away from our center point and at least one red point. We can notice that we only need to check lines that contain a blue point on the convex hull after inversion. To make implementation easier, you can make the additional observation that the sum of all convex hull sizes will be linear through the process of the algorithm. Some intuition behind this observation is that only adjacent nodes in a delaunay triangluation can appear on the convex hull after inversion, so the sum is bounded by the number of edges in such a triangulation (of course, we do not need to explicitly find the triangulation).",
    "code": "#pragma comment(linker, \"/STACK:1000000000\")\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <cassert>\n#include <ctime>\n#include <cstring>\n#include <string>\n#include <set>\n#include <map>\n#include <vector>\n#include <list>\n#include <deque>\n#include <queue>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\n#define pb push_back\n#define mp make_pair\n#define fs first\n#define sc second\n#define double long double\n\nconst double pi = acos(-1.0);\nconst double eps1 = 1e-7;\nconst double eps2 = 1e-14;\n\ndouble sqr(double x) {\n    return x * x; \n}\n\nstruct pt {\n\tdouble x, y;\n\n    pt(double x_ = 0.0, double y_ = 0.0) : x(x_), y(y_) {}\n};\n\npt operator + (const pt& a, const pt& b) {\n\treturn pt(a.x + b.x, a.y + b.y);\n}\n\npt operator - (const pt& a, const pt& b) {\n\treturn pt(a.x - b.x, a.y - b.y);\n}\n\npt operator * (const pt& a, double k) {\n\treturn pt(a.x * k, a.y * k);\n}\n\nstruct line {\n\tdouble a, b, c;\n\tline(double a_ = 1.0, double b_ = 0.0, double c_ = 0.0): a(a_), b(b_), c(c_) {\n\t\tnorm();\n    }\n\n\tline(const pt& p1, const pt& p2) {\n\t\ta = p2.y - p1.y;\n\t\tb = p1.x - p2.x;\n\t\tc = -a * p1.x - b * p1.y;\n\n\t\tnorm();\n\t}\n\n\tvoid norm() {\n\t\tdouble k = sqrt(sqr(a) + sqr(b));\n\t\ta /= k;\n\t\tb /= k;\n\t\tc /= k;\n\t}\n\n\tdouble dist(const pt& p) const {\n\t\treturn a * p.x + b * p.y + c;\n\t}\n};\nbool cmp (pt a, pt b) {\n\treturn (a.x < b.x) || (a.x == b.x && a.y < b.y);\n}\n\nbool cw (pt a, pt b, pt c) {\n\treturn a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y) < -eps2;\n}\n\nbool ccw (pt a, pt b, pt c) {\n\treturn a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y) > eps2;\n}\n\nvoid convex_hull (vector<pt> & a) {\n\tif (a.size() == 1)  return;\n    if (a.size() == 2) return;\n\tsort (a.begin(), a.end(), &cmp);\n\tpt p1 = a[0],  p2 = a.back();\n\tvector<pt> up, down;\n\tup.push_back (p1);\n\tdown.push_back (p1);\n\tfor (size_t i=1; i<a.size(); ++i) {\n\t\tif (i==a.size()-1 || cw (p1, a[i], p2)) {\n\t\t\twhile (up.size()>=2 && !cw (up[up.size()-2], up[up.size()-1], a[i]))\n\t\t\t\tup.pop_back();\n\t\t\tup.push_back (a[i]);\n\t\t}\n\t\tif (i==a.size()-1 || ccw (p1, a[i], p2)) {\n\t\t\twhile (down.size()>=2 && !ccw (down[down.size()-2], down[down.size()-1], a[i]))\n\t\t\t\tdown.pop_back();\n\t\t\tdown.push_back (a[i]);\n\t\t}\n\t}\n\ta.clear();\n\tfor (size_t i=0; i<up.size(); ++i)\n\t\ta.push_back (up[i]);\n\tfor (size_t i=down.size()-2; i>0; --i)\n\t\ta.push_back (down[i]);\n}\n\nint sign(double x) {\n    if (fabs(x) < eps2)\n        return 0;\n    if (x > 0)\n        return 1;\n    return -1;\n}\n\nint main() {\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n\n    int n, m;\n\n    cin >> n >> m;\n\n    vector <pt> red(n), blue(m);\n    for (int i = 0; i < n; i++) {\n        cin >> red[i].x >> red[i].y;\n    }\n\n    for (int i = 0; i < m; i++) {\n        cin >> blue[i].x >> blue[i].y;\n    }\n\n    if (m == 1) {\n        cout << -1 << endl;\n        return 0;\n    }\n    vector <pt> cvx_blue = blue;\n    convex_hull(cvx_blue);\n    int k = cvx_blue.size();\n        \n    for (int i = 0; i < n; i++) {\n        bool flag = true;\n        for (int j = 0; j < k; j++) {\n            line hl(cvx_blue[j % k], cvx_blue[(j + 1) % k]);\n            if (hl.dist(red[i]) > eps1) {\n               flag = false;    \n            }\n        }\n\n        if (flag) { \n            cout << -1 << endl;\n    \n            return 0;\n        }\n\n    }\n\n\n    double ans = 0.0;\n\n    for (int i = 0; i < m; i++) {\n        vector <pt> new_blue;\n        for (int j = 0; j < i; j++) {\n            new_blue.pb(blue[j] - blue[i]);\n            double d = sqr(new_blue.back().x) + sqr(new_blue.back().y);\n            new_blue.back().x /= d;\n            new_blue.back().y /= d;\n        }\n\n        new_blue.pb(pt(0.0, 0.0));\n\n        for (int j = i + 1; j < m; j++) {\n            new_blue.pb(blue[j] - blue[i]);\n            double d = sqr(new_blue.back().x) + sqr(new_blue.back().y);\n            new_blue.back().x /= d;\n            new_blue.back().y /= d;\n        }\n\n        vector <pt> new_red;\n        for (int j = 0; j < n; j++) {\n            new_red.pb(red[j] - blue[i]);\n            double d = sqr(new_red.back().x) + sqr(new_red.back().y);\n            new_red.back().x /= d;\n            new_red.back().y /= d;        \n        }\n\n        convex_hull(new_blue);\n\n        int k = new_blue.size();\n        int p = new_red.size();\n\n        for (int j = 0; j < k; j++) {\n            bool flag = false;\n            line hl(new_blue[j], new_blue[(j + 1) % k]);\n           \n            for (int q = 0; q < p; q++) {\n                if (hl.dist(new_red[q]) < eps2)\n                    flag = true;            \n            }            \n\n            if (flag) {\n                if (abs(hl.dist(pt(0.0, 0.0))) < eps2) {\n                    cout << -1 << endl;\n                    \n                    return 0;\n                }\n    //            cerr << hl.dist(pt(0.0, 0.0)) << endl;\n                /*\n                if (fabs(hl.dist(pt(0.0, 0.0))) < eps) {\n                    cout << -1 << endl;\n                    return 0;\n                }\n                */\n                ans = max(ans, 1.0 / abs(hl.dist(pt(0.0, 0.0))));\n            }\n        }\n\n        for (int q = 0; q < p; q++) {\n            for (int j = 0; j < k; j++) {\n                line hl(new_red[q], new_blue[j]);\n                if (sign(hl.dist(new_blue[(j + 1) % k])) * sign(hl.dist(new_blue[(j + k - 1) % k])) >= 0) {\n                    if (abs(hl.dist(pt(0.0, 0.0))) < eps2) {\n                        cout << -1 << endl;\n                \n                        return 0;\n                    }\n\n  //                  cerr << hl.dist(pt(0.0, 0.0)) << endl;\n                    ans = max(ans, 1.0 / abs(hl.dist(pt(0.0, 0.0))));\n                }\n            }\n        }\n    }\n\n    cout.precision(20);\n    cout << ans / 2.0 << endl; \n\n    return 0;\n}",
    "tags": [
      "geometry"
    ],
    "rating": 3200
  },
  {
    "contest_id": "744",
    "index": "E",
    "title": "Hongcow Masters the Cyclic Shift",
    "statement": "Hongcow's teacher heard that Hongcow had learned about the cyclic shift, and decided to set the following problem for him.\n\nYou are given a list of $n$ strings $s_{1}, s_{2}, ..., s_{n}$ contained in the list $A$.\n\nA list $X$ of strings is called stable if the following condition holds.\n\nFirst, a message is defined as a concatenation of some elements of the list $X$. You can use an arbitrary element as many times as you want, and you may concatenate these elements in any arbitrary order. Let $S_{X}$ denote the set of of all messages you can construct from the list. Of course, this set has infinite size if your list is nonempty.\n\nCall a single message good if the following conditions hold:\n\n- Suppose the message is the concatenation of $k$ strings $w_{1}, w_{2}, ..., w_{k}$, where each $w_{i}$ is an element of $X$.\n- Consider the $|w_{1}| + |w_{2}| + ... + |w_{k}|$ cyclic shifts of the string. Let $m$ be the number of these cyclic shifts of the string that are elements of $S_{X}$.\n- A message is good if and only if $m$ is exactly equal to $k$.\n\nThe list $X$ is called stable if and only if every element of $S_{X}$ is good.\n\nLet $f(L)$ be $1$ if $L$ is a stable list, and $0$ otherwise.\n\nFind the sum of $f(L)$ where $L$ is a nonempty \\textbf{contiguous sublist} of $A$ (there are $\\textstyle{\\frac{n(n+1)}{2}}$ contiguous sublists in total).",
    "tutorial": "Let M denote the total number of characters across all strings. Consider how long it takes to compute f(L) for a single list. Consider a graph where nodes are suffixes of strings. This means we already spelled out the prefix, and still need to spell out the suffix. There are at most M nodes in this graph. Now, draw at most N edges connecting suffixes to each other. We can find the edges efficiently by doing suffix arrays or z algorithm or hashes. Now, we claim is the list is good if and only if there is no cycle in this graph. You can notice that a cycle exists => we can construct a bad word. Also, if a bad word exists => we can form a cycle. So, we can check if there is a cycle, which takes O(N*M) time. Next step is to notice that extending a bad list will never make it good. So we can do two pointers to find all good intervals, which requires O(n) calls to the check function. So, overall this runs in O(N^2*M) time. You might be wondering why this problem asks for sublists rather than the entire list. To be honest, it's just to make tests slightly stronger (i.e. I get ~30^2x the number of tests in the same amount of space).",
    "code": "import java.io.*;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.StringTokenizer;\n\npublic class CyclicShiftsAgainAgain {\n    public static int n;\n    public static String[] s;\n    public static int[] len;\n    public static void main (String[] args) {\n        InputReader in = new InputReader(System.in);\n        PrintWriter out = new PrintWriter(System.out, true);\n        n = in.nextInt();\n        s = new String[n+1];\n        len = new int[n+1];\n        s[0] = \"\";\n        len[0] = 0;\n        for (int i = 1; i <= n; i++) {\n            s[i] = in.next();\n            len[i] = len[i-1] + s[i].length();\n        }\n\n        int ans = 0;\n        int front = 0;\n        for (int i = 1; i <= n; i++) {\n            while (!isGood(front+1, i)) front++;\n            ans += i - front;\n        }\n\n        out.println(ans);\n        out.close();\n        System.exit(0);\n    }\n\n    public static boolean isGood(int from, int to) {\n        if (from > to) return true;\n        int numnodes = len[to] - len[from - 1];\n        ArrayList<Integer>[] graph = new ArrayList[numnodes+1];\n        for (int i = 0; i <= numnodes; i++) graph[i] = new ArrayList<>();\n        for (int startword = from; startword <= to; startword++) {\n            graph[numnodes].add(len[startword-1] - len[from-1]);\n            StringBuilder sb = new StringBuilder();\n            sb.append(s[startword]);\n            sb.append(\"$\");\n            for (int k = from; k <= to; k++) {\n                if (k == startword) continue;\n                sb.append(s[k]);\n                sb.append(\"#\");\n            }\n            int[] z = zz(sb.toString().toCharArray());\n\n            int curchar = 0;\n            for (int i = 1; i < s[startword].length(); i++) {\n                if (z[i] + i >= s[startword].length()) {\n                    graph[i + len[startword-1] - len[from -1]].add(z[i] + len[startword-1] - len[from-1]);\n                }\n            }\n            int curword = startword == from ? (from+1) : from;\n            for (int i = s[startword].length()+1; i+1 < z.length; i++) {\n                if (sb.charAt(i) == '#') {\n                    i++;\n                    curword++;\n                    if (curword == startword) curword++;\n                    curchar = 0;\n                }\n\n                int curnode = curchar + len[curword-1] - len[from-1];\n                if (z[i] + curchar >= s[curword].length()) {\n                    if (z[i] == s[startword].length()) {\n                        if (curchar != 0) graph[curnode].add(numnodes);\n                    } else {\n                        graph[curnode].add(z[i] + len[startword-1] - len[from-1]);\n                    }\n                } else if (z[i] == s[startword].length()) {\n                    graph[curnode].add(curnode + z[i]);\n                }\n                curchar++;\n            }\n\n        }\n        return isDAG(graph);\n    }\n\n    public static int[] zz(char[] let) {\n        int N = let.length;\n        int[] z = new int[N];\n        int L = 0, R = 0;\n        for (int i = 1; i < N; i++) {\n            if (i > R) {\n                L = R = i;\n                while (R < N && let[R - L] == let[R])\n                    R++;\n                z[i] = R - L;\n                R--;\n            } else {\n                int k = i - L;\n                if (z[k] < R - i + 1)\n                    z[i] = z[k];\n                else {\n                    L = i;\n                    while (R < N && let[R - L] == let[R])\n                        R++;\n                    z[i] = R - L;\n                    R--;\n                }\n            }\n        }\n        z[0] = N;\n        return z;\n    }\n\n    private static boolean isDAG(ArrayList<Integer>[] graph) {\n        int n = graph.length;\n        int[] indeg = new int[n];\n        for (int i = 0; i < n; i++) for (int x : graph[i]) indeg[x]++;\n        int[] queue = new int[n];\n        int front = 0, back = 0, idx = 0;\n\n        for (int i = 0; i < indeg.length; i++)\n            if (indeg[i] == 0)\n                queue[back++] = i;\n\n        while (front != back) {\n            int node = queue[front++];\n            for (int next : graph[node]) {\n                if (--indeg[next] == 0) {\n                    queue[back++] = next;\n                }\n            }\n        }\n\n        return front == n;\n    }\n\n    static class InputReader {\n        public BufferedReader reader;\n        public StringTokenizer tokenizer;\n\n        public InputReader(InputStream stream) {\n            reader = new BufferedReader(new InputStreamReader(stream), 32768);\n            tokenizer = null;\n        }\n\n        public String next() {\n            while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n                try {\n                    tokenizer = new StringTokenizer(reader.readLine());\n                } catch (IOException e) {\n                    throw new RuntimeException(e);\n                }\n            }\n            return tokenizer.nextToken();\n        }\n\n        public int nextInt() {\n            return Integer.parseInt(next());\n        }\n    }\n}",
    "tags": [
      "strings",
      "two pointers"
    ],
    "rating": 3200
  },
  {
    "contest_id": "745",
    "index": "A",
    "title": "Hongcow Learns the Cyclic Shift",
    "statement": "Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.\n\nHongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word \"abracadabra\" Hongcow will get words \"aabracadabr\", \"raabracadab\" and so on.\n\nHongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.",
    "tutorial": "We only need to consider at most |s| cyclic shifts (since |s| cyclic shifts returns us back to the original string). So, we can put these all in a set, and return the size of the set.",
    "code": "print (lambda s: len(set(s[i:] + s[:i] for i in range(len(s)))))(raw_input())",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "745",
    "index": "B",
    "title": "Hongcow Solves A Puzzle",
    "statement": "Hongcow likes solving puzzles.\n\nOne day, Hongcow finds two identical puzzle pieces, with the instructions \"make a rectangle\" next to them. The pieces can be described by an $n$ by $m$ grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.\n\nThe puzzle pieces are very heavy, so Hongcow \\textbf{cannot rotate or flip} the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also \\textbf{cannot overlap}.\n\nYou are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.",
    "tutorial": "I really apologize for the ambiguity of this problem. We worked hard to make it concise and accurate, but we left out too many details. Basically, the idea is we want to overlay two of these pieces together so that no square has more than 1 X, and the region of X's forms a rectangle. Now for the solution: First, let's look at it backwards. I have a rectangle, and I cut it in two pieces. These two pieces have the same exact shape. What shapes can I form? A necessary and sufficient condition is that the piece itself is a rectangle itself! There are a few ways to check this. One is, find the min/max x/y coordinates, and make sure the number of X's match the bounding box of all the points.",
    "code": "n,m = map(int, raw_input().split())\npiece = [raw_input().rstrip() for i in range(n)]\n\nmaxx, minx, maxy, miny = -1, n, -1, m\ncount = 0\nfor i in range(n):\n\tfor j in range(m):\n\t\tif piece[i][j] == 'X':\n\t\t\tmaxx = max(maxx, i)\n\t\t\tminx = min(minx, i)\n\t\t\tmaxy = max(maxy, j)\n\t\t\tminy = min(miny, j)\n\t\t\tcount += 1\n\n\nprint ((maxx - minx + 1) * (maxy - miny + 1) == count) * \"YES\" or \"NO\"",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "746",
    "index": "A",
    "title": "Compote",
    "statement": "Nikolay has $a$ lemons, $b$ apples and $c$ pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio $1: 2: 4$. It means that for each lemon in the compote should be exactly $2$ apples and exactly $4$ pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.\n\nYour task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print $0$.",
    "tutorial": "At first let's calculate how many portions of stewed fruit (in one portion - $1$ lemon, $2$ apples and $4$ pears) we can cook. This number equals to $min(a, b div 2, c div 4)$, where $x div y$ is integer part of $x / y$. After that we need to multiply this number of 7, because there is 7 fruits in 1 portion, and print the result.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "746",
    "index": "B",
    "title": "Decoding",
    "statement": "Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: {con\\textbf{\\underline{t}}est}, {i\\textbf{\\underline{n}}fo}. If the word consists of single letter, then according to above definition this letter is the median letter.\n\nPolycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.\n\nYou are given an encoding $s$ of some word, your task is to decode it.",
    "tutorial": "To find the answer we can iterate through the given string from the left to the right and add each letter in the answer string - one letter to the begin, next letter to the end, next letter to begin and so on. If $n$ is even than the first letter must be added to the begin and the second letter to the end. In the other case, the first letter - to the end, second - to the begin. We need to make it until we do not add all letters from the given string.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "746",
    "index": "C",
    "title": "Tram",
    "statement": "The tram in Berland goes along a straight line from the point $0$ to the point $s$ and back, passing $1$ meter per $t_{1}$ seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points $x = 0$ and $x = s$.\n\nIgor is at the point $x_{1}$. He should reach the point $x_{2}$. Igor passes $1$ meter per $t_{2}$ seconds.\n\nYour task is to determine the minimum time Igor needs to get from the point $x_{1}$ to the point $x_{2}$, if it is known where the tram is and in what direction it goes at the moment Igor comes to the point $x_{1}$.\n\nIgor can enter the tram unlimited number of times at any moment when his and the tram's positions coincide. It is \\textbf{not obligatory} that points in which Igor enter and exit the tram are integers. Assume that any boarding and unboarding happens instantly. Igor can move arbitrary along the line (but not faster than $1$ meter per $t_{2}$ seconds). He can also stand at some point for some time.",
    "tutorial": "It is easy to show that if Igor faster than the tram the answer is $|x_{1} - x_{2}| \\cdot t_{2}$. In the other case we need to use the following hint: the time of arrive does not depend on how much Igor walk before enter the tram, if the tram will reach the finish point faster than Igor. So Igor can wait the tram in the point $x_{1}$. The answer is minimum of the following values: the time during which Igor will reach the point $x_{2}$ by foot and the time during which the tram will reach at first the point $x_{1}$ and than the point $x_{2}$.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "746",
    "index": "D",
    "title": "Green and Black Tea",
    "statement": "Innokentiy likes tea very much and today he wants to drink exactly $n$ cups of tea. He would be happy to drink more but he had exactly $n$ tea bags, $a$ of them are green and $b$ are black.\n\nInnokentiy doesn't like to drink the same tea (green or black) more than $k$ times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink $n$ cups of tea, without drinking the same tea more than $k$ times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.",
    "tutorial": "Let's use greedy to solve this problem. On the current step we choose tea, which left more, but if the last $k$ cups were equal we need to use the other tea. If we can't use the other tea - there is no answer and we need to print <<NO>>. So, we need to store the number of last cups, which were equals and how many of green and black tea left we greedily build the answer. If we use all tea with this algorithm - we found the answer and it is guaranteed that it is correct answer.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "746",
    "index": "E",
    "title": "Numbers Exchange",
    "statement": "Eugeny has $n$ cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be \\textbf{distinct}.\n\nNikolay has $m$ cards, distinct numbers from $1$ to $m$ are written on them, one per card. It means that Nikolay has exactly one card with number $1$, exactly one card with number $2$ and so on.\n\nA single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.",
    "tutorial": "Because of all resulting numbers must be distinct we necessarily need to change all numbers with meet more than once in the given sequence $a$. We will use two pointers: pointer on next even number in the sequence $b$ (at first this pointer equals to 2) and pointer on next odd number in the sequence $b$ (at first it is 1). Also we will store the number of odd and even numbers in $a$. At first let brute the numbers in $a$. If current number meets more than once we have two ways: if the number of numbers with it parity less or equal to the number of numbers with other parity in $a$, we change this number to the number with same parity from $b$ and move needed pointer; in the other case - change this number to number with different parity and move needed parity. After we finished iterations all numbers will be different but the number of odd numbers can be not equal to the number of even numbers. We need to make similar iterations and change only numbers for which the number of numbers with such parity more. If in some moment we can not change next number - the answer is -1.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "746",
    "index": "F",
    "title": "Music in Car",
    "statement": "Sasha reaches the work by car. It takes exactly $k$ minutes. On his way he listens to music. All songs in his playlist go one by one, after listening to the $i$-th song Sasha gets a pleasure which equals $a_{i}$. The $i$-th song lasts for $t_{i}$ minutes.\n\nBefore the beginning of his way Sasha turns on some song $x$ and then he listens to the songs one by one: at first, the song $x$, then the song $(x + 1)$, then the song number $(x + 2)$, and so on. He listens to songs until he reaches the work or until he listens to the last song in his playlist.\n\nSasha can listen to each song to the end or partly.\n\nIn the second case he listens to the song for integer number of minutes, at least half of the song's length. Formally, if the length of the song equals $d$ minutes, Sasha listens to it for no less than $\\textstyle{\\left[{\\frac{d}{2}}\\right]}$ minutes, then he immediately switches it to the next song (if there is such). For example, if the length of the song which Sasha wants to partly listen to, equals $5$ minutes, then he should listen to it for at least $3$ minutes, if the length of the song equals $8$ minutes, then he should listen to it for at least $4$ minutes.\n\nIt takes no time to switch a song.\n\nSasha wants to listen partly no more than $w$ songs. If the last listened song plays for less than half of its length, then Sasha doesn't get pleasure from it and that song is not included to the list of partly listened songs. It is not allowed to skip songs. A pleasure from a song does not depend on the listening mode, for the $i$-th song this value equals $a_{i}$.\n\nHelp Sasha to choose such $x$ and no more than $w$ songs for partial listening to get the maximum pleasure. Write a program to find the maximum pleasure Sasha can get from the listening to the songs on his way to the work.",
    "tutorial": "This problem can be solved with help of two pointers. We will store two sets - set with songs with full time and set with songs with partly time. How to move left and right pointers and recalculate current answer? Let left end of the current segment is $l$ and right end of the segment is $r$. Let the set of songs with partly time is $half$ and with full time - $full$. In this sets we will store pairs - time of listening each song and it number. Right end we will move in the following way: if we can add partly song and we have enough time to listen it - we take it (also add this song to $half$) and add to time $(t_{r} + 1) / 2$ and add to the answer $a_{r}$. In the other case we have two cases. First - we add current song as full song, second - we add current song as partly song. Here we need to choose case with less with the total time. Also here we need to correctly add song to sets and update total time and the answer. If total time became more than $k$ we are not allowed to move $r$. Now we need to update global answer with the current value of answer. Left end we will move in the following way: if we took song as full song we delete it from $full$, subtract from total time length of this song. In the other case we delete it from $half$ and subtract from the total time the $(t_{l} + 1) / 2$. After that we try to take some song from $full$. If the size of $full$ is 0, we can not do that. If we done it we need to change total time on the songs on the current segment.",
    "tags": [
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "746",
    "index": "G",
    "title": "New Roads",
    "statement": "There are $n$ cities in Berland, each of them has a unique id — an integer from $1$ to $n$, the capital is the one with id $1$. Now there is a serious problem in Berland with roads — there are no roads.\n\nThat is why there was a decision to build $n - 1$ roads so that there will be exactly one simple path between each pair of cities.\n\nIn the construction plan $t$ integers $a_{1}, a_{2}, ..., a_{t}$ were stated, where $t$ equals to the distance from the capital to the most distant city, concerning new roads. $a_{i}$ equals the number of cities which should be at the distance $i$ from the capital. The distance between two cities is the number of roads one has to pass on the way from one city to another.\n\nAlso, it was decided that among all the cities except the capital there should be exactly $k$ cities with exactly one road going from each of them. Such cities are dead-ends and can't be economically attractive. In calculation of these cities the capital is not taken into consideration regardless of the number of roads from it.\n\nYour task is to offer a plan of road's construction which satisfies all the described conditions or to inform that it is impossible.",
    "tutorial": "The statement of this problem equals to: we need to build rooted tree with $k$ leafs and for each $i$ from 1 to $n$ on the depth $i$ there are $a_{i}$ vertices. Let $m$ is sum of all numbers from $a$ - the number of vertices in the tree without root. At first let build the path from the root to the leaf on the depth $n$, i. e. on each level we create one vertex which connect with vertex on previous level. In resulting tree we necessarily have such path. Let $c$ is the number of vertices (do not consider already created vertices) which we need to make \"not leafs\". It is equals to $c = m - k - n + 1$. If now $c < 0$ there is no answer - we can not make less number of leafs which we already have. In the other case we need to each level $i$ until $c > 0$ and on the level $i - 1$ we have leafs and the level $i$ does not filled we will add new vertex to random vertex from the level $i - 1$, which does not a leaf. Other vertices on the level $i$ we can add to vertex which has been created when we built path from the root to the depth $n$. If on the current step $c > 0$ - there is no solution. In the other case we built needed tree and can print the answer.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "747",
    "index": "A",
    "title": "Display Size",
    "statement": "A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly $n$ pixels.\n\nYour task is to determine the size of the rectangular display — the number of lines (rows) of pixels $a$ and the number of columns of pixels $b$, so that:\n\n- there are exactly $n$ pixels on the display;\n- the number of rows does not exceed the number of columns, it means $a ≤ b$;\n- the difference $b - a$ is as small as possible.",
    "tutorial": "We can iterate through the values of $a$ from 1 to $n$. For each $i$ if $n mod i = 0$ and if $abs(i - n / i)$ is less than already found different we need to update answer with values $min(i, n / i)$ and $max(i, n / i)$ (because $a$ must be less than $b$).",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "747",
    "index": "B",
    "title": "Mammoth's Genome Decoding",
    "statement": "The process of mammoth's genome decoding in Berland comes to its end!\n\nOne of the few remaining tasks is to restore unrecognized nucleotides in a found chain $s$. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, $s$ is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.\n\nIt is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.\n\nYour task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.",
    "tutorial": "Let $n$ is the length of the given string. The number of each letter in the resulting string must be equals to $n / 4$. If $n mod 4$ does not equal to 0 - there is no solution. If some letter meets in the given string more than $n / 4$ times - there is no solution. After that we always can build the answer. We need to iterate through the given string and change question symbols on any letter, which meets in the current string less than $n / 4$ times.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "747",
    "index": "C",
    "title": "Servers",
    "statement": "There are $n$ servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from $1$ to $n$.\n\nIt is known that during the day $q$ tasks will come, the $i$-th of them is characterized with three integers: $t_{i}$ — the moment in seconds in which the task will come, $k_{i}$ — the number of servers needed to perform it, and $d_{i}$ — the time needed to perform this task in seconds. All $t_{i}$ are distinct.\n\nTo perform the $i$-th task you need $k_{i}$ servers which are unoccupied in the second $t_{i}$. After the servers begin to perform the task, each of them will be busy over the next $d_{i}$ seconds. Thus, they will be busy in seconds $t_{i}, t_{i} + 1, ..., t_{i} + d_{i} - 1$. For performing the task, $k_{i}$ servers with the smallest ids will be chosen from all the unoccupied servers. If in the second $t_{i}$ there are not enough unoccupied servers, the task is ignored.\n\nWrite the program that determines which tasks will be performed and which will be ignored.",
    "tutorial": "The given constraints allow to simply modulate described process. Let's use array $server$, where $server[i]$ is equals to the time when $i$-th server will become free. Than for each query let's find the number of servers which free in moment when this query came. We can do it in $O(n)$, where $n$ is the number of servers. If the number of free servers is less than $k$ we need to print -1. In the other case, we can iterate through all free servers and find the sum of $k$ servers with smallest numbers and store in array $server$ for this servers time of release equals to $t + d$.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "747",
    "index": "D",
    "title": "Winter Is Coming",
    "statement": "The winter in Berland lasts $n$ days. For each day we know the forecast for the average air temperature that day.\n\nVasya has a new set of winter tires which allows him to drive safely no more than $k$ days at any average air temperature. After $k$ days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these $k$ days form a continuous segment of days.\n\nBefore the first winter day Vasya still uses \\textbf{summer tires}. It is possible to drive safely on summer tires any number of days when the average air temperature is \\textbf{non-negative}. It is impossible to drive on summer tires at days when the average air temperature is negative.\n\nVasya can change summer tires to winter tires and vice versa at the beginning of any day.\n\nFind the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.",
    "tutorial": "At first let's process the case when there is no solution - when the number of days with negative temperature $cnt$ more than $k$. Now we need to subtract from $k$ the number of days $cnt$. If we will use winter rubber only in days with negative temperature we will get the maximum value of answer: it is the number of segments where all days have negative temperature multiply by 2. Between the segments with negative temperatures there are segments which we ride on the summer rubber. Let's put in $set$ the lengths of this segments (not include the segments with first and last days if they have non-negative temperatures, this cases we need to process separately from the main solution). After that we need to delete from the $set$ smallest lengths of segments one by one, decrease $k$ on this value and decrease answer on 2. We can make it until $k > = 0$ and the $set$ is not empty. Now we only need to check if we can ride on winter rubber the last segment of days with non-negative temperature. If it is possible we need decrease the answer on 1, in the other case the answer remains unchanged.",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "747",
    "index": "E",
    "title": "Comments",
    "statement": "A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed.\n\nEach comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment.\n\nWhen Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format:\n\n- at first, the text of the comment is written;\n- after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments);\n- after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm).\n\nAll elements in this format are separated by single comma. Similarly, the comments of the first level are separated by comma.For example, if the comments look like:\n\nthen the first comment is written as \"hello,2,ok,0,bye,0\", the second is written as \"test,0\", the third comment is written as \"one,1,two,2,a,0,b,0\". The whole comments feed is written as: \"hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0\". For a given comments feed in the format specified above print the comments in a different format:\n\n- at first, print a integer $d$ — the maximum depth of nesting comments;\n- after that print $d$ lines, the $i$-th of them corresponds to nesting level $i$;\n- for the $i$-th row print comments of nesting level $i$ in the order of their appearance in the Policarp's comments feed, separated by space.",
    "tutorial": "Let $pos$ is a global variable equals to the current position in the given string. To solve we can use recursive function $rec(lvl, cnt)$, means that in the current moment we are on the level of replies $lvl$ and there is $cnt$ comments on this level. Than we need iterate by $i$ from 1 to $cnt$ and on each iteration we will make the following: read from the position $pos$ comment, add this comment to the answer for level $lvl$ and than read the number of it children $nxt_{cnt}$. After that $pos$ will in the beginning of the first child of this comment and we need to run $rec(lvl + 1, nxt_{cnt})$. For the higher level we can put in $cnt$ big number and return from the function $rec$ in the moment when $pos$ will become equals to the length of the given string.",
    "tags": [
      "dfs and similar",
      "expression parsing",
      "implementation",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "747",
    "index": "F",
    "title": "Igor and Interesting Numbers",
    "statement": "Igor likes hexadecimal notation and considers \\textbf{positive} integer in the hexadecimal notation interesting if each digit and each letter in it appears no more than $t$ times. For example, if $t = 3$, then integers 13a13322, aaa, abcdef0123456789 are interesting, but numbers aaaa, abababab and 1000000 are not interesting.\n\nYour task is to find the $k$-th smallest interesting for Igor integer in the hexadecimal notation. The integer should not contain leading zeros.",
    "tutorial": "Let's use dynamic programming and $dp[i][j]$ - the number of valid numbers with length $i$ and maximal digit in this numbers is $j$. Let iterate by $n_{j}$ from $j + 1$ and brute $len$ (how many times we will take digit $n_{j}$). Than new length $n_{i} - i + len$, number will ends to $n_{j}$ repeated $len$ times. Then $dp[ni][nj] = dp[i][j] * (n_{i}! / (i! * len!))$. After that we need to find the length of the answer number $lenAns$. Let iterate by $lenAns$ from 1 and calculate the number of numbers with length $lenAns$. It can be done with help of $dp$ (brute maximum digit and calculate $dp$ for $len - 1$).",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "748",
    "index": "A",
    "title": "Santa Claus and a Place in a Class",
    "statement": "Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are $n$ lanes of $m$ desks each, and there are two working places at each of the desks. The lanes are numbered from $1$ to $n$ from the left to the right, the desks in a lane are numbered from $1$ to $m$ starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture).\n\nThe organizers numbered all the working places from $1$ to $2nm$. The places are numbered by lanes (i. e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i. e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right.\n\n\\begin{center}\n{\\small The picture illustrates the first and the second samples.}\n\\end{center}\n\nSanta Clause knows that his place has number $k$. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right!",
    "tutorial": "It can be easily seen that the side on which Santa should sit depends only on the parity of $k$, while the number of desk and the number of lane depend only on a value $p=\\lfloor{\\frac{k-1}{2}}\\rfloor$. We can see that in such numeration the number of lane equals $\\left|{\\frac{p}{m}}\\right|+1$, while the number of desk equals $p\\bmod m+1$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "748",
    "index": "B",
    "title": "Santa Claus and Keyboard Check",
    "statement": "Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.\n\nIn order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.\n\nYou are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs \\textbf{at most once}.",
    "tutorial": "Denote the two strings from the input by $s$ and $t$. It's enough to find all pairs of distinct $s_{i}$ and $t_{i}$ and then do the following: Ensure that each symbol is in no more than one different pair, Ensure that if symbol $c$ is in a pair with another symbol $d$, then each occurrence of $c$ in $s$ on the $i$-th place takes place iff $t_{i} = d$, and vice versa. If at least one of these conditions fails, there is no answer, otherwise, it's enough to print the obtained pairs.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "748",
    "index": "C",
    "title": "Santa Claus and Robot",
    "statement": "Santa Claus has Robot which lives on the infinite grid and can move \\textbf{along its lines}. He can also, having a sequence of $m$ points $p_{1}, p_{2}, ..., p_{m}$ with integer coordinates, do the following: denote its initial location by $p_{0}$. First, the robot will move from $p_{0}$ to $p_{1}$ along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches $p_{1}$, it'll move to $p_{2}$, again, choosing one of the shortest ways, then to $p_{3}$, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.\n\nWhile Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.",
    "tutorial": "Solution #1: denote by $dp_{i}$ the least possible number of points if the robot passed only $i$ unit segments, and we assume that $dp_{0} = 0$. Thus, the answer to the problem is $dp_{n}$. It's clear that $dp_{k + 1}  \\ge  dp_{k}$ for every $k$, so for every $i  \\le  n$ one can obtain that $dp_{i} = dp_{j} + 1$, where $j$ is the minimal of such indices that $s[j + 1... i]$ can be a path from one point to another. That means two constraints: either $s[j + 1... i]$ doesn't contain any L, or it doesn't contain any R; either $s[j + 1... i]$ doesn't contain any U, or it doesn't contain any D. This fact is offered to the reader. Such $j$ can be found in $O(1)$ if we iterate over all $i$-s from $1$ to $n$ and keep the last occurence of L, R, U and D. So one can, storing these occurences and $dp$ itself, implement the algorithm above and pass each test for $O(n)$ time. Solution #2: since we know the way to determine whether the path is valid or not (from the first solution), let's find the longest prefix of $s$ and say that that's a path to the first point of the required collection. Then we find the longest prefix of the remaining string and state that this is the shortest path from $p_{1}$ to $p_{2}$, and so on. This greedy algorithm works (obviously, in linear time), since the first solution is in fact the same greedy algorithm applied to the reversed string.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "748",
    "index": "D",
    "title": "Santa Claus and a Palindrome",
    "statement": "Santa Claus likes palindromes very much. There was his birthday recently. $k$ of his friends came to him to congratulate him, and each of them presented to him a string $s_{i}$ having the same length $n$. We denote the beauty of the $i$-th string by $a_{i}$. It can happen that $a_{i}$ is negative — that means that Santa doesn't find this string beautiful at all.\n\nSanta Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have \\textbf{the same length} $n$.\n\nRecall that a palindrome is a string that doesn't change after one reverses it.\n\nSince the empty string is a palindrome too, the answer can't be negative. Even if all $a_{i}$'s are negative, Santa can obtain the empty string.",
    "tutorial": "Imagine a palindrome split into substrings of equal size (say, $n$). Here is how it may look like: ABC DEF XYX FED CBA We may notice a regular structure: each block, except the middle one, has its pair, which is the same string, but reversed. Here, the first block (ABC) is paired with the last (CBA), the second - with the first-but-last. For now, let's assume that we take an even number of strings, so each string has its pair. Let's split given strings into groups; strings $S$ and $rev(S)$ belong to one group. Clearly, if $S$ is not a palindrome, we must make a pair with the string $S$ with maximum value and the string $rev(S)$ with maximum value, until both strings exist and the sum of their values is nonnegative. If $S$ is a palindrome, we will take two its occurrences with maximum value at a time (of course, again, if there are still at least two occurrences and the sum of values is nonnegative). The trickiest part is the central block. Clearly, only the palindromic strings may be at the central block. However, there may be many of them, and we should select the one which gives the maximum value overall. There are several cases. Consider the point when you've taken the last pair from the list of $S$-s and stopped. If the value of the next element is nonnegative (say, $x$), we may simply take it and say that $x$ is our possible score for $S$ being in the center. We wouldn't make a valuable pair of it anyway. Otherwise we need to split the last taken pair. Denote the values of last taken strings as $a$ and $b$ ($a  \\ge  b$). Note that $b < 0$, because otherwise it makes no sense to use $a$ separately. If we take a pair, we get score $a + b$. If we take just the first element, we get score $a$. So, in this case our possible score is $- b$ (while $a + b$ is already added to the main answer!) Now, the central string will be the one with the maximum possible score, and its value should be added to the answer.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "748",
    "index": "E",
    "title": "Santa Claus and Tangerines",
    "statement": "Santa Claus has $n$ tangerines, and the $i$-th of them consists of exactly $a_{i}$ slices. Santa Claus came to a school which has $k$ pupils. Santa decided to treat them with tangerines.\n\nHowever, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into parts so that no one will be offended. In order to do this, he can divide a tangerine or any existing part into two smaller equal parts. If the number of slices in the part he wants to split is odd, then one of the resulting parts will have one slice more than the other. It's forbidden to divide a part consisting of only one slice.\n\n\\textbf{Santa Claus wants to present to everyone either a whole tangerine or exactly one part of it} (that also means that everyone must get a positive number of slices). One or several tangerines or their parts may stay with Santa.\n\nLet $b_{i}$ be the number of slices the $i$-th pupil has in the end. Let Santa's joy be the minimum among all $b_{i}$'s.\n\nYour task is to find the maximum possible joy Santa can have after he treats everyone with tangerines (or their parts).",
    "tutorial": "It is obvious that if the total number of slices is less than $k$, then the answer is $- 1$. Otherwise it's at least $1$. Let's find the answer in this case. Let's divide tangerines and parts in halves one by one in order to find the best answer. It's easy to see that it makes no sense to divide a part of size $x$ if there is an undivided part of size $y > x$. So we are going to proceed dividing the largest part on each step. Let's also maintain current answer, i. e. the size of the $k$-th biggest current part, and a set of parts which we are going to present to the pupils. When we divide the largest part, there are two possible cases: If the size of any part is less then the current answer, then it's obvious that the answer will never be greater if we proceed further, so we can stop the process. If the sizes of both parts are greater than or equal to the current answer, then we should delete the initial part and add the resulting parts to those we present to the pupils in the current answer, and then delete the smallest part from the set making it of size $k$ again. We can see that in the second case the answer never decreases so we can just proceed until the first case happens. To emulate this process in a fast way, we can keep an array from $1$ to $A$, where $A = 10^{7}$ is the maximum possible number of slices in a part, where each cell contain the current number of parts of that size. Thus, we can maintain two pointers: one to the current answer and one to the current maximum size, so the whole process can be done in $O(n)$. The overall complexity is $O(n + A)$.",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "748",
    "index": "F",
    "title": "Santa Clauses and a Soccer Championship",
    "statement": "The country Treeland consists of $n$ cities connected with $n - 1$ bidirectional roads in such a way that it's possible to reach every city starting from any other city using these roads. There will be a soccer championship next year, and all participants are Santa Clauses. There are exactly $2k$ teams from $2k$ different cities.\n\nDuring the first stage all teams are divided into $k$ pairs. Teams of each pair play two games against each other: one in the hometown of the first team, and the other in the hometown of the other team. Thus, each of the $2k$ cities holds exactly one soccer game. However, it's not decided yet how to divide teams into pairs.\n\nIt's also necessary to choose several cities to settle players in. Organizers tend to use \\textbf{as few cities as possible} to settle the teams.\n\nNobody wants to travel too much during the championship, so if a team plays in cities $u$ and $v$, it wants to live in one of the cities on the shortest path between $u$ and $v$ (maybe, in $u$ or in $v$). There is another constraint also: the teams from one pair must live in the same city.\n\nSummarizing, the organizers want to divide $2k$ teams into pairs and settle them in the minimum possible number of cities $m$ in such a way that teams from each pair live in the same city which lies between their hometowns.",
    "tutorial": "Firstly, let's prove that there exists a vertex $v$ in the tree such that if we make it a root, all subtrees of its neighbours (which does not contain $v$) contain no more than $k$ vertices in which some games are played (we call these vertices chosen further). We root the tree in some vertex $root$ and denote $f(u)$ the number of chosen vertices in the subtree of $u$. Now we need to prove that there exists vertex $v$ such that $f(v)  \\ge  k$ (then no more than $k$ vertices outside subtree of $v$ are chosen), but for all children $to$ of $v f(to)  \\le  k$ holds. Assume there is no such vertex $v$, then each vertex $u$ such that $f(u) > k$ has some child $u'$ such that $f(u') > k$. So we can build a sequence $u_{0}, u_{1}, ...$ such that $u_{0} = root, u_{i + 1}$ is a child of $u_{i}$ and $f(u_{i}) > k$. But obviously, at some point we will go to the leaf, which clearly has $f(u)  \\le  1$. This leads us to a contradiction. This argument also gives us an easy way to find the desired vertex $v$: just calculate $f(u)$ for all subtrees of the rooted tree and then go from the root down, always going to the child with $f(u_{i + 1}) > k$, at some point we will find that such vertex does not exist - then current vertex is the one we were looking for. We claim that the answer to the original problem is always 1, i.e. we can always choose one vertex, where all teams will live. Consider vertex $v$ having $f(to)  \\le  k$ for all its children. We create a list of all chosen vertices, firstly we write all chosen vertices of the first child's subtree of $v$, then all chosen vertices of the second child's subtree, and so on. In the end, if $v$ is chosen too, we add it to the end of the list. Now we have a list of $2k$ vertices $a$. Let's create $k$ pairs of the form $(a_{i}, a_{i + k})$. Since for all children of $v f(to)  \\le  k$ holds, the vertices which numbers in the list differ by $k$ can not belong to the same subtrees, and thus the shortest path between $a_{i}$ and $a_{i + k}$ passes through the vertex $v$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "749",
    "index": "A",
    "title": "Bachgold Problem",
    "statement": "Bachgold problem is very easy to formulate. Given a positive integer $n$ represent it as a sum of \\textbf{maximum possible} number of prime numbers. One can prove that such representation exists for any integer greater than $1$.\n\nRecall that integer $k$ is called \\underline{prime} if it is greater than $1$ and has exactly two positive integer divisors — $1$ and $k$.",
    "tutorial": "We need represent integer number $N$ ($1 < N$) as a sum of maximum possible number of prime numbers, they don't have to be different. If $N$ is even number, we can represent it as sum of only $2$ - minimal prime number. It is minimal prime number, so number of primes in sum is maximal in this case. If $N$ is odd number, we can use representing of $N - 1$ as sum with only $2$ and replace last summand from $2$ to $3$. Using of any prime $P > 3$ as summand is not optimal, because it can be replaced by more than one $2$ and $3$.",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "749",
    "index": "B",
    "title": "Parallelogram is Back",
    "statement": "Long time ago Alex created an interesting problem about parallelogram. The input data for this problem contained four integer points on the Cartesian plane, that defined the set of vertices of some non-degenerate (positive area) parallelogram. Points not necessary were given in the order of clockwise or counterclockwise traversal.\n\nAlex had very nice test for this problem, but is somehow happened that the last line of the input was lost and now he has only three out of four points of the original parallelogram. He remembers that test was so good that he asks you to restore it given only these three points.",
    "tutorial": "Denote the input points as $A$, $B$, $C$, and the point we need to find as $D$. Consider the case when the segments $AD$ and $BC$ are the diagonals of parallelogram. Vector AD is equal to the sum of two vectors AB + BD = AC + CD. As in the parallelogram the opposite sides are equal and parallel, BD = AC, AB = CD, and we can conclude that AD = AB + AC. So, the coordinates of the point D can be calculated as $A$ + AB + AC = ($A_{x} + B_{x} - A_{x} + C_{x} - A_{x}, A_{y} + B_{y} - A_{y} + C_{y} - A_{y}$) = ($B_{x} + C_{x} - A_{x}, B_{y} + C_{y} - A_{y}$). The cases where the diagonals are $BD$ and $AC$, $CD$ and $AB$ are processed in the same way. Prove that all three given points are different. Let's suppose it's wrong. Without losing of generality suppose that the points got in cases $AD$ and $BD$ are equal. Consider the system of two equations for the equality of these points: $B_{x} + C_{x} - A_{x} = A_{x} + C_{x} - B_{x}$ $B_{y} + C_{y} - A_{y} = A_{y} + C_{y} - B_{y}$ We can see that in can be simplified as $A_{x} = B_{x}$ $A_{y} = B_{y}$ And we got a contradiction, as all the points $A$, $B$, $C$ are distinct.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "geometry"
    ],
    "rating": 1200
  },
  {
    "contest_id": "749",
    "index": "C",
    "title": "Voting",
    "statement": "There are $n$ employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.\n\nEach of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:\n\n- Each of $n$ employees makes a statement. They make statements one by one starting from employees $1$ and finishing with employee $n$. If at the moment when it's time for the $i$-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).\n- When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.\n- When all employees are done with their statements, the procedure repeats: again, each employees starting from $1$ and finishing with $n$ who are still eligible to vote make their statements.\n- The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.\n\nYou know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.",
    "tutorial": "We will emulate the process with two queues. Let's store in the first queue the moments of time when D-people will vote, and in the second queue - the moments of time of R-people. For every man where will be only one element in the queue. Now compare the first elements in the queues. The man whose moment of time is less votes first. It's obvious that it's always profitable to vote against the first opponent. So we will remove the first element from the opponent's queue, and move ourselves to the back of our queue, increasing the current time by $n$ - next time this man will vote after $n$ turns. When one of the queues becomes empty, the corresponding party loses.",
    "tags": [
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "749",
    "index": "D",
    "title": "Leaving Auction",
    "statement": "There are $n$ people taking part in auction today. The rules of auction are classical. There were $n$ bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.\n\nEach bid is define by two integers $(a_{i}, b_{i})$, where $a_{i}$ is the index of the person, who made this bid and $b_{i}$ is its size. Bids are given in chronological order, meaning $b_{i} < b_{i + 1}$ for all $i < n$. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. $a_{i} ≠ a_{i + 1}$ for all $i < n$.\n\nNow you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.\n\nNote, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.\n\nYou have several questions in your mind, compute the answer for each of them.",
    "tutorial": "For every man at the auction we will save two values: his maximum bid and the list of all his bids. Then save all men in the set sorted by the maximal bid. Now, when the query comes, we will remove from the set all men who left the auction, then answer the query, and then add the men back. The total number of deletions and insertions will not exceed 200000. How to answer the query. Now our set contains only men who has not left. If the set is empty, the answer is 0 0. Otherwise, the maximal man in the set is the winner. Now we have to determine the winning bid. Let's look at the second maximal man in the set. If it doesn't exist, the winner takes part solo and wins with his minimal bid. Otherwise he should bid the minimal value that is greater than the maximal bid of the second man in the set. This is where we need a list of bids of the first maximal man. We can apply binary search and find the maximal bid of the second man there.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2000
  },
  {
    "contest_id": "749",
    "index": "E",
    "title": "Inversions After Shuffle",
    "statement": "You are given a permutation of integers from $1$ to $n$. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally:\n\n- Pick a random segment (continuous subsequence) from $l$ to $r$. All $\\textstyle{\\frac{n(n+1)}{2}}$ segments are equiprobable.\n- Let $k = r - l + 1$, i.e. the length of the chosen segment. Pick a random permutation of integers from $1$ to $k$, $p_{1}, p_{2}, ..., p_{k}$. All $k!$ permutation are equiprobable.\n- This permutation is applied to elements of the chosen segment, i.e. permutation $a_{1}, a_{2}, ..., a_{l - 1}, a_{l}, a_{l + 1}, ..., a_{r - 1}, a_{r}, a_{r + 1}, ..., a_{n}$ is transformed to $a_{1}, a_{2}, ..., a_{l - 1}, a_{l - 1 + p1}, a_{l - 1 + p2}, ..., a_{l - 1 + pk - 1}, a_{l - 1 + pk}, a_{r + 1}, ..., a_{n}$.\n\n\\underline{Inversion} if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs $(i, j)$ such that $i < j$ and $a_{i} > a_{j}$. Find the expected number of inversions after we apply exactly one operation mentioned above.",
    "tutorial": "Lets calculate all available segments count - $\\frac{l e n s(l e n+1)}{2}$. It will be a denominator of answer fraction. Also, necessary to understand, that expected value of inversion count in shuffled permutation with length len equal $\\frac{l e n s(l e n-1)}{4}$ (It can be prooved by fact, that for each permutation there are mirrored permutation (or biection $i - > n - i + 1$) and sum of inversion count his permutations are equal $\\frac{I_{\\mathrm{e}^{-}\\hbar\\left(I e n-1\\right)}}{2}$ inversions). Next, we will find expected value of difference between expected value of inversion count after operation and inversion count in the source array. And add it to the inversion count in the source array. Naive solution: For every segment we will calculate the count of inversions in it, and also the expected value of the inversion count in it after shuffle. Take the difference and divide by a denominator. Sum these values for all segments. This solution has quadratic asympthotics, try to improve it. Optimized solution: We will go through the permutation from right to left and for each position count the sum of inversions in the initial permutation for all segments that start in the current position (denote that the largest segment which ends at the position $n$ has the length $len$), also we will maintain the sum of expected values of the inversion counts on the segments of lengths $1..len$. Knowing these two numbers, increase the answer by their difference divided by the denominator. To calculate the first value we will use the data structure that can get the sum of numbers on the prefix and modify the value at the single position (e.g. Fenwick tree). For the position $i$ we need to know how many numbers are less than $a_{i}$, and every number should be taken $t$ times, where $t$ is number of segments where it is contained. Suppose we have calculated answers for some suffix and are now standing at the position $i$. For every position to the left it will be added $n - i + 1$ times (the number of positions $j > = i$ as the candidates for the right bound, in 1-indexation). Perform fenwick add(a[i], n - i + 1).",
    "tags": [
      "data structures",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "750",
    "index": "A",
    "title": "New Year and Hurry",
    "statement": "Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be $n$ problems, sorted by difficulty, i.e. problem $1$ is the easiest and problem $n$ is the hardest. Limak knows it will take him $5·i$ minutes to solve the $i$-th problem.\n\nLimak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs $k$ minutes to get there from his house, where he will participate in the contest first.\n\nHow many problems can Limak solve if he wants to make it to the party?",
    "tutorial": "Do you see what is produced by the following piece of code? We iterate over problems (a variable i denotes the index of problem) and in a variable total we store the total time needed to solve them. The code above would print numbers $5, 15, 30, 50, ...$ - the $i$-th of these numbers is the number of minutes the hero would spend to solve easiest $i$ problems. Inside the loop you should also check if there is enough time to make it to the party, i.e. check if total + k <= 240.",
    "tags": [
      "binary search",
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "750",
    "index": "B",
    "title": "New Year and North Pole",
    "statement": "In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly $40 000$ kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly $20 000$ kilometers.\n\nLimak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of $n$ parts. In the $i$-th part of his journey, Limak should move $t_{i}$ kilometers in the direction represented by a string $dir_{i}$ that is one of: \"North\", \"South\", \"West\", \"East\".\n\nLimak isn’t sure whether the description is valid. You must help him to check the following conditions:\n\n- If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South.\n- If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North.\n- The journey must end on the North Pole.\n\nCheck if the above conditions are satisfied and print \"YES\" or \"NO\" on a single line.",
    "tutorial": "Our goal is to simulate Limak's journey and to check if he doesn't make any forbidden moves. To track his position, it's enough to store one variable denoting his current distance from the North Pole. To solve this problem, you should implement checking three conditions given in the statement. Updating dist_from_north variable is an easy part. Moving $t_{i}$ kilometers to the North increases the distance from the North Pole by $t_{i}$, while moving South decreases that distance by $t_{i}$. Moving to the West or East doesn't affect the distance from Poles, though you should still check if it doesn't happen when Limak is on one of two Poles - you must print \"NO\" in this case. Let's proceed to checking the three conditions. First, Limak can't move further to the North if he is already on the North Pole \"at any moment of time (before any of the instructions or while performing one of them)\". So you should print \"NO\" if direction == \"North\" and either dist_from_north == 0 or dist_from_north < t[i]. The latter case happens e.g. if Limak is $150$ kilometers from the North Pole and is supposed to move $170$ kilometers to the North - after $150$ kilometers he would reach the North Pole and couldn't move further to the North. In the intended solution below you will see an alternative implementation: after updating the value of dist_from_north we can check if dist_from_north < 0 - it would mean that Limak tried to move North from the North Pole. Also, you should print \"NO\" if dist_from_north == 0 (i.e. Limak is on the North Pole) and the direction is West or East. You should deal with the South Pole case in a similar way. Limak is on the South Pole when dist_from_north == M. Finally, you must check if Limak finished on the North Pole, i.e. dist_from_north == 0. There were two common doubts about this problem: 1) \"Limak is allowed to move $40 000$ kilometers to the South from the North Pole and will be again on the North Pole.\" 2) \"Moving West/East may change the latitude (equivalently: the distance from Poles) and this problem is hard 3d geometry problem.\" Both doubts make sense because they come from misinterpreting a problem as: Limak looks in the direction represented by the given string (e.g. to the North) and just goes straight in that direction (maybe after some time he will start moving to the South but he doesn't care about it). What organizers meant is that Limak should be directed in the given direction at any moment of time, i.e. he should continuously move in that direction. It's a sad thing that many participants struggled with that. I should have written the statement better and I'm sorry about it.",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "750",
    "index": "C",
    "title": "New Year and Rating",
    "statement": "Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating $1900$ or higher. Those with rating $1899$ or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.\n\nLimak competed in $n$ contests in the year 2016. He remembers that in the $i$-th contest he competed in the division $d_{i}$ (i.e. he belonged to this division \\textbf{just before} the start of this contest) and his rating changed by $c_{i}$ \\textbf{just after the contest}. Note that negative $c_{i}$ denotes the loss of rating.\n\nWhat is the maximum possible rating Limak can have right now, after all $n$ contests? If his rating may be arbitrarily big, print \"Infinity\". If there is no scenario matching the given information, print \"Impossible\".",
    "tutorial": "We don't know the initial or final rating but we can use the given rating changes to draw a plot of function representing Limak's rating. For each contest we also know in which division Limak was. Red and blue points denote contests in div1 and div2. Note that we still don't know exact rating at any moment. Let's say that a border is a horizontal line at height $1900$. Points above the border and exactly on it should be red, while points below should be blue. Fixing the placement of the border will give us the answer (because then we will know height of all points). Let's find the highest blue point and the lowest red point - the border can lie anywhere between them, i.e. anywhere between these two horizontal lines: Small detail: the border can lie exactly on the upper line (because rating $1900$ belongs to div1) but it can't lie exactly on the lower line (because $1900$ doesn't belong to div2). The last step is to decide where exactly it's best to put the border. The answer will be $1900 + d$ where $d$ is the difference between the height of the border and the height of the last point (representing the last contest), so we should place the border as low as possible: just over the lower of two horizontal lines we found. It means that the highest blue point should be at height $1899$. There is an alternative explanation. If Limak never had rating exactly $1899$, we could increase his rating at the beginning by $1$ (thus moving up the whole plot of the function by $1$) and everything would still be fine, while the answer increased. To implement this solution, you should find prefix sums of rating changes (what represents the height of points on drawings above, for a moment assuming that the first point has height $0$) and compute two values: the smallest prefix sum ending in a div1 contest and the greatest prefix sum ending in a div2 contest. If the first value is less than or equal to the second value, you should print \"Impossible\" - it means that the highest blue point isn't lower that the lowest red point. If all contests were in div1, we should print \"Infinity\" because there is no upper limit for Limak's rating at any time (and there is no upper limit for the placement of the border). Otherwise we say that the highest blue point (a div2 contest with the greatest prefix sum) is a contest when Limak had rating $1899$ and we easily compute the final rating.",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "750",
    "index": "D",
    "title": "New Year and Fireworks",
    "statement": "One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on.\n\nLimak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth $n$ and a duration for each level of recursion $t_{1}, t_{2}, ..., t_{n}$. Once Limak launches the firework in some cell, the firework starts moving upward. After covering $t_{1}$ cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by $45$ degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering $t_{2}$ cells, splitting into two parts moving in directions again changed by $45$ degrees. The process continues till the $n$-th level of recursion, when all $2^{n - 1}$ existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time — it is allowed and such parts do not crash.\n\nBefore launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells?",
    "tutorial": "A trivial $O(2^{n})$ solution is to simulate the whole process and mark visited cells. Thanks to a low constraint for $t_{i}$, a backtrack with memoization has much better complexity. Let's understand the reason. Parts of the firework move by $t_{i}$ in the $i$-th level of recursion so they can't reach cells further than $\\textstyle\\sum t_{i}$ from the starting cell. That sum can't exceed $n \\cdot max_t = 150$. We can't visit cells with bigger coordinates so there are only $O((n \\cdot max_t)^{2})$ cells we can visit. As usually in backtracks with memoization, for every state we can do computations only once - let's think what that \"state\" is. We can't say that a state is defined by the current cell only, because maybe before we visited it going in a different direction and now we would reach new cells. It also isn't correct to say that we can skip further simulation if we've already been in this cell going in the same direction, because maybe it was the different level of recursion (so now next step will in in a different direction, what can allow us to visit new cells). It turns out that a state must be defined by four values: two coordinates, a direction and a level of recursion (there are $8$ possible directions). One way to implement this approach is to create set<vector<int>> visitedStates where each vector contains four values that represent a state. The complexity is $\\begin{array}{c}{{\\O((n\\cdot m u x\\ }\\ t)^{2}\\cdot\\S\\circ n\\cdot\\bigcup_{\\mathrm{GP}}n)}\\end{array}$ what is enough to get AC. It isn't hard to get rid of the logarithm factor what you can see in the last code below. If implementing the simulation part is hard for you, see the first code below with too slow exponential solution. It shows an easy way to deal with $8$ directions and changing the direction by $45$ degrees - you can spend a moment to hardcode changes of $x$ and $y$ for each direction and clockwise or counter-clockwise order and then keep an integer variable and change its value by $1$ modulo $8$. You can add memoization to this slow code yourself and try to get AC.",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "750",
    "index": "E",
    "title": "New Year and Old Subsequence",
    "statement": "A string $t$ is called nice if a string \"2017\" occurs in $t$ as a \\textbf{subsequence} but a string \"2016\" doesn't occur in $t$ as a \\textbf{subsequence}. For example, strings \"203434107\" and \"9220617\" are nice, while strings \"20016\", \"1234\" and \"20167\" aren't nice.\n\nThe ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is $ - 1$.\n\nLimak has a string $s$ of length $n$, with characters indexed $1$ through $n$. He asks you $q$ queries. In the $i$-th query you should compute and print the ugliness of a \\textbf{substring} (continuous subsequence) of $s$ starting at the index $a_{i}$ and ending at the index $b_{i}$ (inclusive).",
    "tutorial": "It's often helpful to think about an algorithm to solve some easier problem. To check if a string has a subsequence \"2017\", we can find the find the first '2', then to the right from that place find the first '0', then first '1', then first '7'. If in some of these $4$ steps we can't find the needed digit on the right, the string doesn't have \"2017\" as a subsequence. To additionally check if there is a subsequence \"2016\", after finding '1' (before finding '7') we should check if there is any '6' on the right. Let's refer to this algorithm as Algo. It turns out that the problem can be solved with a segment tree (btw. the solution will also allow for queries changing some digits). The difficulty is to choose what we want to store in its nodes. Let's first use the Algo to answer simpler queries: \"for the given segment check if it's nice\". There is only one thing that matters for segments represented by nodes. For a segment we want to know for every prefix of \"2017\" (e.g. for \"20\"): assuming that the Algo already got this prefix as a subsequence, what is the prefix we have after the Algo processes this segment. Let's see an example.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "matrices"
    ],
    "rating": 2600
  },
  {
    "contest_id": "750",
    "index": "F",
    "title": "New Year and Finding Roots",
    "statement": "\\textbf{This is an interactive problem. In the interaction section below you will find the information about flushing the output.}\n\nThe New Year tree of height $h$ is a perfect binary tree with vertices numbered $1$ through $2^{h} - 1$ in some order. In this problem we assume that $h$ is at least $2$. The drawing below shows one example New Year tree of height $3$:\n\nPolar bears love decorating the New Year tree and Limak is no exception. To decorate the tree, he must first find its root, i.e. a vertex with exactly two neighbours (assuming that $h ≥ 2$). It won't be easy because Limak is a little bear and he doesn't even see the whole tree. Can you help him?\n\nThere are $t$ testcases. In each testcase, you should first read $h$ from the input. Then you can ask at most $16$ questions of format \"? x\" (without quotes), where $x$ is an integer between $1$ and $2^{h} - 1$, inclusive. As a reply you will get the list of neighbours of vertex $x$ (more details in the \"Interaction\" section below). For example, for a tree on the drawing above after asking \"? 1\" you would get a response with $3$ neighbours: $4$, $5$ and $7$. Your goal is to find the index of the root $y$ and print it in the format \"! y\". You will be able to read $h$ for a next testcase only after printing the answer in a previous testcase and flushing the output.\n\nEach tree is fixed from the beginning and it doesn't change during your questions.",
    "tutorial": "The goal is to find a vertex with exactly two neighbours - this will be the root. Also, let's notice that for a leaf we would get a list of exactly one neighbour. So we will know if we asked about the root or a leaf. The solution is deterministic. Any randomized solution would likely fail - there are 500 test cases per test file, and usually there are 30-100 tests for a problem, so you must pass around 25,000 test cases. That's bad if you ask too many queries even with a small probability. You can ask about a vertex (say, $A$), then ask about one of its neighbours (say, $B$), then ask about one of neighbours of $B$, and so on, until you get a leaf. The sequence of visited vertices $(A, B, ...)$ is a path in the tree. How can this path look like in the whole tree? Do we know the distance from $A$ to the root of the tree? To be able to say where exactly the path is in the tree, we should do one extra step. From the initial vertex $A$, choose some other neighbour $B_{2}$ and go from there again until you get a leaf. Now we have path between two leaves. The middle vertex on the path is the LCA and we know its distance from the leaves, so we also know its distance from the root. In this case, vertex $B_{1}$ turned out to be the middle of the path: Where should you go now to find the root? Let's call that \"middle vertex of the path\" as $P$. We asked a query about $P$ already, so we know its neighbours. Two neighbours are on the path, and the third one (the one not yet asked/visited) must be the parent of $P$. Let's go to that parent (so, ask a query about it) and then again continue until you find a leaf. Where should we go now? We know that we went from $P$ to its parent, then maybe again to a parent, but eventually we started going down. If we know the numbers of steps it took us to get to a leaf (so, the length of the blue path), we can calculate the number of steps we went up. So we know what is the current LCA of asked/visited vertices and we can go up from there. Alternatively, we can notice that we have a new longer path between two leaves (marked green below). Let $P_{2}$ be the midddle of the path. $P_{2}$ must be the vertex closest to the root (so, LCA of everything we asked/visited so far). We repeat the process, until we get the root of the tree (so, a vertex with two neighbours). What is the number of queries we can ask up to that moment? In the worst case, we start from $P_{0}$ being a leaf, and then the $i$-th new path will have $i + 1$ vertices. The following drawing shows the visited (asked) vertices in the worst case for $h = 5$. The not-yet-visited neighbour of $P_{3}$ must be the root. For height $h$, we can ask up to $1 + 2 + 3 + ... + (h - 1)$ queries, which is $O(\\log^{2}n)$. The limit from the statement is $16$, while for $h = 7$ we get up to $21$ queries. We are close to the solution. Do you see how to get rid of a few queries? If the parent of a current $P_{i}$ is within distance $2$ from the root, we can just check all vertices within distance $2$ (red vertices on the drawing) and we will find the root there. The number of queries needed now is $1 + 2 + 3 + 4 + (1 + 6) = 17$, where \"1+6\" represents the \"PARENT\" and the red vertices. We exceed the limit just by $1$ now. How to get rid of one query? If you already asked about all red vertices but one, the last one must be the answer. We don't have to ask a query about it. That's it, we use at most $16$ queries.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "interactive",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "750",
    "index": "G",
    "title": "New Year and Binary Tree Paths",
    "statement": "The New Year tree is an infinite perfect binary tree rooted in the node $1$. Each node $v$ has two children: nodes indexed $(2·v)$ and $(2·v + 1)$.\n\nPolar bears love decorating the New Year tree and Limak is no exception. As he is only a little bear, he was told to decorate only one simple path between some pair of nodes. Though he was given an opportunity to pick the pair himself! Now he wants to know the number of unordered pairs of indices $(u, v)$ ($u ≤ v$), such that the sum of indices of all nodes along the simple path between $u$ and $v$ (including endpoints) is equal to $s$. Can you help him and count this value?",
    "tutorial": "Iterate over $L$ and $R$ - the length of sides of a path. A \"side\" is a part from LCA (the highest point of a path) to one of the ends of a path. For fixed LCA and length of sides, let the \"minimal\" path denote a path with the minimum possible sum of values. In each of the sides, this path goes to the left child all the time: If the LCA is $x$, the smallest possible sum of vertices on the left side of the minimal path has the sum of vertices: $S_{L} = 2 \\cdot x + 4 \\cdot x + ... + 2^{L} \\cdot x = (2^{L + 1} - 2) \\cdot x$ We can find a similar formula for the minimum possible sum of the right side $S_{R}$. For fixed $L, R, x$, the total sum of any path (also counting LCA itself) is at least: $S_{L} + LCA + S_{R} = (2^{L + 1} - 2) \\cdot x + x + ((2^{R + 1} - 2) \\cdot x + 2^{R} - 1)$ From this, with binary search or just a division, we can compute the largest $x$ where this formula doesn't exceed the given $s$. This is the only possible value of LCA. Larger $x$ would result with the sum exceeding $s$. Smaller $x$ would result in too small sum, even if a path goes to the right child all the time (so, the sum is maximized). Proof: every vertex is strictly smaller than the corresponding vertex in the \"minimal\" path for the computed largest possible $x$: So, from $L$ and $R$ we can get the value of LCA. Let's assume that the computed value of LCA is $1$. For any other value we know that the value of vertex on depth $k$ would be greater by $(x - 1) \\cdot 2^{k}$ compared to LCA equal to $1$, and we know depths of all vertices on a path, so we can subtract the sum of those differences from $s$, and assume the LCA is $1$. The sum of vertices from $1$ to $a$ is $2 \\cdot a - popcount(a)$. Proof: if the binary representation of $a$ has $1$ on the $i$-th position from the right, there will be $1$ on the $(i - 1)$-th position in the index of the parent of $a$ and so on. So this bit adds $2^{i} + 2^{i - 1} + ... + 1 = 2^{i + 1} - 1 = 2 \\cdot 2^{i} - 1$, so everything is doubled, and we get \"-1\" the number of times equal to the number of 1's in the binary representation of $a$. Thus, the formula is $2 \\cdot a - popcount(a)$. If endpoints are $a$ and $b$, the sum of vertices will be $2 \\cdot a - popcount(a) + 2 \\cdot b - popcount(b) - 1$ (we subtract the LCA that was counted twice). Since popcounts are small, we can iterate over each of them and we know the left value of equation: $s' + popcount(a) + popcount(b) + 1 = 2 \\cdot (a + b)$ Here, $s'$ is equal to the initial $s$ minus whatever we subtracted when changing LCA from the binary-searched $x$ to $1$. The remaining problem is: Given binary lengths $L$ and $R$ of numbers $a$ and $b$, their popcounts, and the sum $a + b$, find the number of such pairs $(a, b)$. This can be solved in standard dynamic programming on digits. To slightly improve the complexity, we can iterate over the sum $popcount(a) + popcount(b)$ instead of the two popcounts separately. The required complexity is $O(\\log^{5}(s))$ or better.",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp"
    ],
    "rating": 3200
  },
  {
    "contest_id": "750",
    "index": "H",
    "title": "New Year and Snowy Grid",
    "statement": "\\textbf{Pay attention to the output section below, where you will see the information about flushing the output.}\n\nBearland is a grid with $h$ rows and $w$ columns. Rows are numbered $1$ through $h$ from top to bottom. Columns are numbered $1$ through $w$ from left to right. Every cell is either allowed (denoted by '.' in the input) or permanently blocked (denoted by '#').\n\nBearland is a cold land, where heavy snow often makes travelling harder. Every day a few allowed cells are \\textbf{temporarily} blocked by snow. Note, that this block works only on this particular day and next day any of these cells might be allowed again (unless there is another temporarily block).\n\nIt's possible to move directly between two cells only if they share a side and none of them is permanently or temporarily blocked.\n\nLimak is a little polar bear who lives in Bearland. His house is at the top left cell, while his school is at the bottom right cell. Every day Limak should first go from his house to the school and then return back to his house. Since he gets bored easily, he doesn't want to \\textbf{visit the same cell twice} on one day, except for the cell with his house, where he starts and ends. If Limak can reach a school and return home avoiding revisiting cells, he calls a day interesting.\n\nThere are $q$ days you must process, one after another. For each of these days you should check if it's interesting and print \"YES\" or \"NO\" on a separate line. In order to be able to read the description of the next day you should print the answer for the previous one and flush the output.\n\nIt's guaranteed that a day with no cells temporarily blocked by snow would be interesting. It's also guaranteed that cells with Limak's house and school are never blocked (neither permanently or temporarily).",
    "tutorial": "Let's solve an easier problem first. For every query, we just want to say if Limak can get from one corner to the other. He can't do that if and only if blocked cells connect the top-right side with the bottom-left side - this is called a dual problem. On the drawing above, the top-right side and bottom-left side are marked with blue, and blocked cells are black. There is a path of blocked cells between the two sides what means that Limak can't get from top-left to bottom-right corner. The duality in graphs changes the definition of adjacency from \"sharing a side\" to \"touching by a corner or side\" - the black cells on the drawing aren't side-adjacent but they still block Limak from passing through. Similarly, if Limak was allowed to move to any of 8 corner/side-adjacent cells, black cells would have to touch by sides to block Limak from passing through. The idea of a solution is to find CC's (connected components) of blocked cells before reading queries, and then for every query see what CC's are connected with each other by temporarily blocked cells. To make our life easier, let's treat the blue sides as blocked cells too by expanding the grid by 1 in every direction. Then for every query, we want to check if new blocked cells connect the bottom-left CC and top-right CC. Before reading queries, we can find CC's of blocked cells (remember that a cell has 8 adjacent cells now!). Let's name those initial CC's as regions. When a temporarily blocked cell appears, we iterate through the adjacent cells and if some of them belong to initial regions, we apply find&union to mark some regions as connected to each other (and connected to this new cell that is a temporary region of size 1). This can be done in $O(k\\cdot\\log k)$ where $k$ is the number of temporarily blocked cells. This solves the easier version of a problem, where we just check if Limak can get from one corner to the other - if the two special regions are connected at the end then the answer is \"NO\", and it's \"YES\" otherwise. What about the full problem? Limak wants to move to the opposite corner and back, not using the same cell twice. If you treat a grid as a graph, this means checking if there is a cycle passing through the two corners (a cycle without repeated vertices). It's reasonable to then think about bridges and articulation points. An articulation point here would be such a cell that making it blocked would disconnect the two corners from each other - it's a cell that Limak must go through on both parts of his journey. Our dual problem becomes: check if the two sides are almost connected i.e. it's enough to add one more blocked cell to make the connection (that cell must be an articulation point). The previously described solution needs some modification. We did F&U on regions adjacent to temporarily blocked cells. If some region was connected with some other region in the current query, let's call it an interesting region - there are $O(k)$ of them. If we preprocess the set of pairs of regions that are initially almost connected (it's enough to add one more blocked cell to make them connected), we can then for a query iterate over pairs: a region connected to the bottom-right side and a region connected to the other side, and check if this pair is in the set of almost-connected regions. There are $O(k^{2})$ pairs and if any of them is almost-connected, we have an almost-connection between the two sides and we print \"NO\", because Limak can't avoid revisiting cells.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define SIDE1 cc[3][0]\n#define SIDE2 cc[0][3]\nconst int N = 1005;\nint h, w;\nchar sl[N];\nbool allow[N][N];\nint cc_cnt, cc[N][N]; // which connected component\nset<pair<int,int>> edges; // pairs of almost connected CC's\n \n// find & union\nnamespace FU {\n\tint group[N*N];\n\tvector<int> inv[N*N];\n\tset<int> affected;\n\tvoid init(int i) {\n\t\tif(affected.count(i)) return;\n\t\taffected.insert(i);\n\t\tgroup[i] = i;\n\t\tinv[i].push_back(i);\n\t}\n\tvoid uni(int a, int b) {\n\t\tinit(a), init(b);\n\t\ta = group[a], b = group[b];\n\t\tif(a == b) return;\n\t\tfor(int x : inv[a]) {\n\t\t\tgroup[x] = b;\n\t\t\tinv[b].push_back(x);\n\t\t}\n\t\tinv[a].clear();\n\t}\n\tbool areConnected(int a, int b) {\n\t\tinit(a), init(b);\n\t\treturn group[a] == group[b];\n\t}\n\tvoid clear() {\n\t\tfor(int i : affected) {\n\t\t\tgroup[i] = 0;\n\t\t\tinv[i].clear();\n\t\t}\n\t\taffected.clear();\n\t}\n\tbool almostConnectedPair() {\n\t\tinit(SIDE1), init(SIDE2);\n\t\tfor(int x : affected) if(areConnected(SIDE1, x))\n\t\t\tfor(int y : affected) if(areConnected(SIDE2, y))\n\t\t\t\tif(edges.count({x, y}))\n\t\t\t\t\treturn true;\n\t\treturn false;\n\t}\n}\n \nbool inRange(int row, int col) {\n\treturn 0 <= row && row <= h + 1 && 0 <= col && col <= w + 1;\n}\nbool duality(vector<pair<int,int>> snow) {\n\tFU :: clear();\n\tfor(pair<int,int> p : snow) {\n\t\tint row = p.first, col = p.second;\n\t\tcc[row][col] = ++cc_cnt;\n\t\tfor(int r2 = row - 1; r2 <= row + 1; ++r2)\n\t\t\tfor(int c2 = col - 1; c2 <= col + 1; ++c2)\n\t\t\t\tif(cc[r2][c2])\n\t\t\t\t\tFU :: uni(cc[r2][c2], cc[row][col]);\n\t}\n\tif(FU :: almostConnectedPair())\n\t\treturn true;\n\tfor(pair<int,int> p : snow) {\n\t\tint row = p.first, col = p.second;\n\t\tfor(int r2 = row - 2; r2 <= row + 2; ++r2)\n\t\t\tfor(int c2 = col - 2; c2 <= col + 2; ++c2)\n\t\t\t\tif(inRange(r2, c2) && cc[r2][c2]) {\n\t\t\t\t\tif(FU :: areConnected(cc[row][col], SIDE1)\n\t\t\t\t\t\t\t&& FU :: areConnected(cc[r2][c2], SIDE2))\n\t\t\t\t\t\treturn true;\n\t\t\t\t\tif(FU :: areConnected(cc[row][col], SIDE2)\n\t\t\t\t\t\t\t&& FU :: areConnected(cc[r2][c2], SIDE1))\n\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t}\n\t\n\treturn false;\n}\nvoid dfs(int row, int col) {\n\tfor(int r2 = row - 1; r2 <= row + 1; ++r2)\n\t\tfor(int c2 = col - 1; c2 <= col + 1; ++c2)\n\t\t\tif(inRange(r2, c2) && allow[r2][c2] && !cc[r2][c2]) {\n\t\t\t\tcc[r2][c2] = cc[row][col];\n\t\t\t\tdfs(r2, c2);\n\t\t\t}\n}\nint main() {\n\tint q;\n\tscanf(\"%d%d%d\", &h, &w, &q);\n\tfor(int row = 0; row < h; ++row) {\n\t\tscanf(\"%s\", sl);\n\t\tfor(int col = 0; col < w; ++col)\n\t\t\tallow[row+1][col+1] = (sl[col] == '#');\n\t}\n\tfor(int row = 3; row <= h + 1; ++row)\n\t\tallow[row][0] = true;\n\tfor(int col = 1; col <= w - 2; ++col)\n\t\tallow[h+1][col] = true;\n\t\n\tfor(int col = 3; col <= w + 1; ++col)\n\t\tallow[0][col] = true;\n\tfor(int row = 1; row <= h - 2; ++row)\n\t\tallow[row][w+1] = true;\n\t\n\tfor(int row = 0; row <= h + 1; ++row)\t\n\t\tfor(int col = 0; col <= w + 1; ++col)\n\t\t\tif(allow[row][col] && !cc[row][col]) {\n\t\t\t\tcc[row][col] = ++cc_cnt;\n\t\t\t\tdfs(row, col);\n\t\t\t}\n\t\n\tfor(int row = 0; row <= h + 1; ++row)\n\t\tfor(int col = 0; col <= w + 1; ++col)\n\t\t\tif(cc[row][col])\n\t\t\t\tfor(int r2 = row - 2; r2 <= row + 2; ++r2)\n\t\t\t\t\tfor(int c2 = col - 2; c2 <= col + 2; ++c2)\n\t\t\t\t\t\tif(inRange(r2, c2) && cc[r2][c2]\n\t\t\t\t\t\t\t\t&& cc[row][col] != cc[r2][c2])\n\t\t\t\t\t\t\tedges.insert({cc[row][col], cc[r2][c2]});\n\t\n\tassert(SIDE1 != SIDE2);\n\t\n\tassert(!duality(vector<pair<int,int>>{}));\n\t\n\twhile(q--) {\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\tvector<pair<int,int>> snow(k);\n\t\tfor(pair<int,int> & p : snow)\n\t\t\tscanf(\"%d%d\", &p.first, &p.second);\n\t\tputs(duality(snow) ? \"NO\" : \"YES\");\n\t\tfflush(stdout);\n\t\t// clear\n\t\tfor(pair<int,int> p : snow)\n\t\t\tcc[p.first][p.second] = 0;\n\t\tcc_cnt -= snow.size();\n\t}\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "interactive"
    ],
    "rating": 3500
  },
  {
    "contest_id": "754",
    "index": "A",
    "title": "Lesha and array splitting",
    "statement": "One spring day on his way to university Lesha found an array $A$. Lesha likes to split arrays into several parts. This time Lesha decided to split the array $A$ into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array $A$.\n\nLesha is tired now so he asked you to split the array. Help Lesha!",
    "tutorial": "Only in one case there is no answer. When array consists entirely of zeros. Because all subarrays of such array has zero sum. Otherwise there are two cases: Array sum is not zero. In this case we can divide array into one subarray $A[1... n]$. Array sum is zero. But we know that array has non-zero elements. Then there is exists such prefix $A[1... p]$, which sum is $s$ and $s  \\neq  0$. If sum of array is zero and sum of prefix is $s$, then sum of remaining suffix is equals to $0 - s = - s$ ($- s  \\neq  0$). Therefore array can be divided into two parts $A[1... p]$ and $A[p + 1... n]$. Time complexity - $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n);\n\tlong long sum = 0;\n\tfor (int & x : a) {\n\t\tscanf(\"%d\", &x);\n\t\tsum += x;\n\t}\n\tif (sum != 0) {\n\t\tputs(\"YES\");\n\t\tputs(\"1\");\n\t\tprintf(\"%d %d\\n\", 1, n);\n\t\texit(0);\n\t}\n\tsum = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tsum += a[i];\n\t\tif (sum != 0) {\n\t\t\tputs(\"YES\");\n\t\t\tputs(\"2\");\n\t\t\tprintf(\"%d %d\\n\", 1, i + 1);\n\t\t\tprintf(\"%d %d\\n\", i + 2, n);\n\t\t\texit(0);\n\t\t}\n\t}\n\tputs(\"NO\");\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "754",
    "index": "B",
    "title": "Ilya and tic-tac-toe game",
    "statement": "Ilya is an experienced player in tic-tac-toe on the $4 × 4$ field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not.\n\nThe rules of tic-tac-toe on the $4 × 4$ field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets \\textbf{three of his signs in a row next to each other} (horizontal, vertical or diagonal).",
    "tutorial": "This problem can be solved by simple bruteforce. Let's brute cell in which Ilya put X. Let's put X in this cell. Next step is to check if there is three consecutive Xs on field. This is done as follows. Let's brute cell which is first of three consecutive Xs. Next let's brute direction of three consecutive Xs. If we know first cell and direction, we should check that there is three consecutive cells from first cell towards fixed direction.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tchar str[4][4 + 1];\n\t// cells are '.', 'o', 'x'\n\tfor (int i = 0; i < 4; i++) {\n\t\tcin >> str[i];\n\t}\n\n\tauto check = [&]() {\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tfor (int j = 0; j < 4; j++) {\n\t\t\t\tfor (int dx = -1; dx <= 1; dx++) {\n\t\t\t\t\tfor (int dy = -1; dy <= 1; dy++) {\n\t\t\t\t\t\tif (dx == 0 && dy == 0) continue;\n\t\t\t\t\t\tif (i + dx * 3 > 4 || j + dy * 3 > 4 || i + dx * 3 < -1 || j + dy * 3 < -1) continue;\n\t\t\t\t\t\tbool ok = true;\n\t\t\t\t\t\tfor (int p = 0; p < 3; p++) {\n\t\t\t\t\t\t\tok &= str[i + p * dx][j + p * dy] == 'x';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (ok) return true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t};\n\n\tfor (int i = 0; i < 4; i++) {\n\t\tfor (int j = 0; j < 4; j++) {\n\t\t\tif (str[i][j] == '.') {\n\t\t\t\tstr[i][j] = 'x';\n\t\t\t\tif (check()) {\n\t\t\t\t\tputs(\"YES\");\n\t\t\t\t\texit(0);\n\t\t\t\t}\n\t\t\t\tstr[i][j] = '.';\n\t\t\t}\n\t\t}\n\t}\n\tputs(\"NO\");\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "754",
    "index": "C",
    "title": "Vladik and chat",
    "statement": "Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them.\n\nAt first, he need to download $t$ chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. In particular, some of the messages have no information of their sender. It is known that if a person sends several messages in a row, they all are merged into a single message. It means that \\textbf{there could not be two or more messages in a row with the same sender}. Moreover, \\textbf{a sender never mention himself in his messages}.\n\nVladik wants to recover senders of all the messages so that each two neighboring messages will have different senders and no sender will mention himself in his messages.\n\nHe has no idea of how to do this, and asks you for help. Help Vladik to recover senders in each of the chats!",
    "tutorial": "Let's number users from $1$ to $n$. Let's us know for every message users mentioned in message. Let's define arrays $A$ and $S$. $A_{i} =$ index of sender of $i$-th message, if sender of $i$-th message is unknown, then $A_{i} = - 1$. $S_{i} =$ set of mentioned users in $i$-th message. Now for every message where sender is unknown we need to restore sender. In other words for every $i$, such that $A_{i} = - 1$, we need to find number from $1$ to $n$, such that for every $j$, that $1  \\le  j < n$, condition $A_{j}  \\neq  A_{j + 1}$ satisfied. This can be solved using Dynamic Programming: $DP(pref, last) = true$, if over first $pref$ messages we can restore all unknown senders, and $pref$-th message has sender number $last$, otherwise $false$. There next transitions in DP: $(p r e f,l a s t)\\rightarrow(p r e f+1,n e w)$, where $new$ - index of user, who send $(pref + 1)$-th message. $new$ should be not equals to $last$ and $new$ should be not equals to every number from set $S_{pref + 1}$. Also if for $(pref + 1)$-th message we know sender then $new$ should be equals to $A_{pref + 1}$. Time complexity of this DP is $O(N^{2} * M)$. Also there is exist another solution. Greedy: While we have messages with unknown sender, for every of which there is only one possible user, which can be put as sender not violating conditions described in statement, then put this user as sender. If in one moment we will have a message with zero possible users, which can be put as sender not violating conditions in statement, then we can't restore senders of messages in chat. Otherwise if every message has two or more possible users which can be senders, then we should choose any such message and put as sender any user, which is possible for this message.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define all(x) (x).begin(), (x).end()\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<string> names(n);\n\tfor (string& name : names) {\n\t\tcin >> name;\n\t}\n\tsort(all(names));\n\n\tauto getIdx = [&](const string& s) {\n\t\tint pos = lower_bound(all(names), s) - names.begin();\n\t\tif (pos == (int)names.size() || names[pos] != s) return -1;\n\t\treturn pos;\n\t};\n\n\tauto splitIntoUserMessage = [](const string& s) {\n\t\tsize_t pos = s.find(':');\n\t\tassert(pos != string::npos);\n\t\treturn make_pair(s.substr(0, pos), s.substr(pos + 1));\n\t};\n\n\tauto splitIntoTokensOfLatinLetters = [](const string& s) {\n\t\tvector<string> result;\n\t\tstring token;\n\t\tfor (char c : s) {\n\t\t\tif (isalpha(c) || isdigit(c)) {\n\t\t\t\ttoken += c;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (!token.empty()) {\n\t\t\t\t\tresult.push_back(token);\n\t\t\t\t}\n\t\t\t\ttoken.clear();\n\t\t\t}\n\t\t}\n\t\tif (!token.empty()) {\n\t\t\tresult.push_back(token);\n\t\t}\n\t\treturn result;\n\t};\n\n\tint m;\n\tcin >> m;\n\tvector<int> who(m);\n\tvector<vector<char>> can(m, vector<char>(n, true));\n\n\tvector<string> messages(m);\n\n\tstring tmp;\n\tgetline(cin, tmp);\n\n\tfor (int i = 0; i < m; i++) {\n\t\tstring cur;\n\t\tgetline(cin, cur);\n\t\tpair<string, string> p = splitIntoUserMessage(cur);\n\t\tconst string& user = p.first;\n\t\tconst string& message = p.second;\n\t\twho[i] = getIdx(user);\n\t\tif (who[i] != -1) {\n\t\t\tfill(all(can[i]), false);\n\t\t\tcan[i][who[i]] = true;\n\t\t}\n\t\tmessages[i] = message;\n\t\tvector<string> tokens = splitIntoTokensOfLatinLetters(message);\n\t\tfor (const string& z : tokens) {\n\t\t\tint idx = getIdx(z);\n\t\t\tif (idx != -1) {\n\t\t\t\tcan[i][idx] = false;\n\t\t\t}\n\t\t}\n\t}\n\n\tvector<vector<int>> par(m, vector<int>(n, -1));\n\tfor (int i = 0; i < n; i++) {\n\t\tif (can[0][i]) par[0][i] = 0;\n\t}\n\tfor (int msg = 0; msg + 1 < m; msg++) {\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (par[msg][i] == -1) continue;\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tif (i == j) continue;\n\t\t\t\tif (can[msg + 1][j]) {\n\t\t\t\t\tpar[msg + 1][j] = i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tint msg = m - 1, pos = -1;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (par[msg][i] != -1) {\n\t\t\tpos = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (pos == -1) {\n\t\tcout << \"Impossible\\n\";\n\t\treturn;\n\t}\n\twhile (msg >= 0) {\n\t\twho[msg] = pos;\n\t\tpos = par[msg][pos];\n\t\tmsg--;\n\t}\n\tfor (int i = 0; i < m; i++) {\n\t\tcout << names[who[i]] << \":\" << messages[i] << \"\\n\";\n\t}\n\treturn;\n}\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t; // number of tests\n\n\twhile (t--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "754",
    "index": "D",
    "title": "Fedor and coupons",
    "statement": "All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket.\n\nThe goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has $n$ discount coupons, the $i$-th of them can be used with products with ids ranging from $l_{i}$ to $r_{i}$, inclusive. Today Fedor wants to take exactly $k$ coupons with him.\n\nFedor wants to choose the $k$ coupons in such a way that the number of such products $x$ that all coupons can be used with this product $x$ is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!",
    "tutorial": "Formalized version of this problem: Given $n$ segments, we need to choose $k$ of them, such that intersection of chosen segments has maximum possible length. Let's use binary search to find maximum possible length of intersection. Let's this length equals to $len$. If exist $k$ segments, which have length of intersection greater or equals to $len$, then if we decrease right border of this segments by $(len - 1)$, then length of intersection will be greater than of equal to $1$. So solution is: Fix $len$ - length of intersection by binary search. Now we should check if there is exist $k$ such segments, that their intersection length greater than or equal to $len$. This can be done as follows. Decrease right border of every segment by $(len - 1)$. Now we should check if there is exist $k$ such segments, which have intersection length greater or equals to $1$. This can be done by different ways. For example using method of events - segment starts, segment ends. And we should find such point, which covered by $k$ segments. Time complexity - $O(N\\log N\\log R)$, where $R  \\approx  10^{9}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint nextInt() {\n\tint x = 0, p = 1;\n\tchar c;\n\tdo {\n\t\tc = getchar();\n\t} while (c <= 32);\n\tif (c == '-') {\n\t\tp = -1;\n\t\tc = getchar();\n\t}\n\twhile (c >= '0' && c <= '9') {\n\t\tx = x * 10 + c - '0';\n\t\tc = getchar();\n\t}\n\treturn x * p;\n}\n\n#define all(x) (x).begin(), (x).end()\n\nconst int N = (int)3e5 + 5;\nconst int MAX_VAL = (int)1e9;\n\nint n;\nll l[N], r[N];\n\nstruct event {\n\tll x;\n\tint c;\n\tevent() {}\n\tevent(ll x, int c) : x(x), c(c) {}\n};\n\npair<ll, int> check(ll len) {\n\tif (len == 0) return make_pair(0LL, n);\n\tstatic vector<event> evs;\n\tevs.resize(0);\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (r[i] - len > l[i]) {\n\t\t\tevs.push_back(event(l[i], 1));\n\t\t\tevs.push_back(event(r[i] - len, -1));\n\t\t}\n\t}\n\tsort(all(evs), [](const event & a, const event & b) { return a.x < b.x; });\n\treverse(all(evs));\n\tint cnt = 0, maxiCnt = 0;\n\tll bestPos = 0;\n\twhile (evs.size() > 0) {\n\t\tll x = evs.back().x;\n\t\twhile (evs.size() > 0 && evs.back().x == x) {\n\t\t\tcnt += evs.back().c;\n\t\t\tevs.pop_back();\n\t\t}\n\t\tif (cnt > maxiCnt) {\n\t\t\tmaxiCnt = cnt;\n\t\t\tbestPos = x;\n\t\t}\n\t}\n\treturn make_pair(bestPos, maxiCnt);\n}\n\nvector<int> getAns(ll len) {\n\tif (len == 0) {\n\t\tvector<int> res(n);\n\t\tiota(all(res), 1);\n\t\treturn res;\n\t}\n\tll pos = check(len).first;\n\tvector<int> res;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (pos >= l[i] && pos < r[i] - len) {\n\t\t\tres.push_back(i);\n\t\t}\n\t}\n\treturn res;\n}\n\nint main() {\n\tn = nextInt();\n\tint k = nextInt();\n\tfor (int i = 1; i <= n; i++) {\n\t\tl[i] = nextInt();\n\t\tr[i] = nextInt() + 2;\n\t}\n\tll l = 0, r = MAX_VAL + MAX_VAL + 5;\n\twhile (r - l > 1) {\n\t\tll mid = (l + r) >> 1;\n\t\tif (check(mid).second >= k) l = mid;\n\t\telse r = mid;\n\t}\n\n\tvector<int> ans = getAns(l);\n\n\tcout << l << endl;\n\tassert((int)ans.size() >= k);\n\tans.resize(k);\n\tfor (int i : ans) {\n\t\tprintf(\"%d \", i);\n\t}\n\tputs(\"\");\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "754",
    "index": "E",
    "title": "Dasha and cyclic table",
    "statement": "Dasha is fond of challenging puzzles: Rubik's Cube $3 × 3 × 3$, $4 × 4 × 4$, $5 × 5 × 5$ and so on. This time she has a cyclic table of size $n × m$, and each cell of the table contains a lowercase English letter. Each cell has coordinates $(i, j)$ ($0 ≤ i < n$, $0 ≤ j < m$). The table is cyclic means that to the right of cell $(i, j)$ there is the cell $(i,(j+1)\\bmod m)$, and to the down there is the cell $((i+1)\\operatorname{mod}\\,n,j)$.\n\nDasha has a pattern as well. A pattern is a non-cyclic table of size $r × c$. Each cell is either a lowercase English letter or a question mark. Each cell has coordinates $(i, j)$ ($0 ≤ i < r$, $0 ≤ j < c$).\n\nThe goal of the puzzle is to find all the appearance positions of the pattern in the cyclic table.\n\nWe say that the cell $(i, j)$ of cyclic table is an appearance position, if for every pair $(x, y)$ such that $0 ≤ x < r$ and $0 ≤ y < c$ one of the following conditions holds:\n\n- There is a question mark in the cell $(x, y)$ of the pattern, or\n- The cell $((i+x)\\operatorname{mod}\\,n,(j+y)\\operatorname{mod}\\,m)$ of the cyclic table equals to the cell $(x, y)$ of the pattern.\n\nDasha solved this puzzle in no time, as well as all the others she ever tried. Can you solve it?.",
    "tutorial": "Let's consider simple bruteforce. Let's $T$ - cyclic table, $P$ - pattern, $R$ - result. Then simple bruteforces looks like that: Let's rewrite bruteforce: Let's define $G$. $G_{c, i, j} = true$, if $T_{i, j} = c$, otherwise $false$. It's easy to understand, that (T[i][j] == c) is equivalent $G[c][i][j]$. Then line of code R[(i - x) mod n][(j - y) mod m] := R[(i - x) mod n][(j - y) mod m] and (T[i][j] == c) is equivalent to R[(i - x) mod n][(j - y) mod m] := R[(i - x) mod n][(j - y) mod m] and G[c][i][j] Let's write shift of matrix $H$ of size $n  \\times  m$ by $i$ to the up and by $j$ to the left as $shift(H, i, j)$. Also let's write element-wise $and$ of two matrix $A$ and $B$, as $A$ $and$ $B$. Then bruteforce looks like that: Operations $shift$ and $and$ on boolean matrices of size $n  \\times  m$ have time complexity $\\frac{\\eta\\cdot\\eta\\dot{1}}{\\mathcal{3}\\dot{2}}$ operations using std::bitset. As result, we improved simple bruteforces which gives accepted. Improved bruteforce works in $\\scriptstyle{\\frac{\\mu-\\mu_{1}r c}{32}}$ operations.",
    "code": "import java.io.*;\nimport java.util.*;\n\npublic class Main {\n\n    static class InputReader {\n        BufferedReader bufferedReader;\n        StringTokenizer stringTokenizer;\n        InputReader(InputStream inputStream) {\n            bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 32768);\n            stringTokenizer = null;\n        }\n        String next() {\n            while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {\n                try {\n                    stringTokenizer = new StringTokenizer(bufferedReader.readLine());\n                } catch (IOException ex) {\n                    ex.printStackTrace();\n                    throw new RuntimeException(ex);\n                }\n            }\n            return stringTokenizer.nextToken();\n        }\n        int nextInt() {\n            return Integer.parseInt(next());\n        }\n        long nextLong() {\n            return Long.parseLong(next());\n        }\n        double nextDouble() {\n            return Double.parseDouble(next());\n        }\n    }\n\n    static int[] newBitSet(int n) {\n        return new int[(n + 31) / 32];\n    }\n\n    static void setBit(int[] a, int pos) {\n        a[pos >>> 5] |= (1 << (pos & 31));\n    }\n\n    static boolean getBit(int[] a, int pos) {\n        return ((a[pos >>> 5]) & (1 << (pos & 31))) != 0;\n    }\n\n    static void setAll(int[] a) {\n        for (int i = 0; i < a.length; i++) {\n            a[i] = ~0;\n        }\n    }\n\n    static void resetAll(int[] a) {\n        for (int i = 0; i < a.length; i++) {\n            a[i] = 0;\n        }\n    }\n\n    static void andXYtoX(int[] x, int[] y) {\n        for (int i = 0; i < x.length; i++) {\n            x[i] &= y[i];\n        }\n    }\n\n    static void leftShiftAndOr(int ch, int shift, int x, int[][][][] shl, int[] to) {\n        int[] z = shl[ch][shift & 31][x];\n        int delta = (shift >>> 5);\n        for (int i = delta; i < to.length; i++) {\n            to[i - delta] |= z[i];\n        }\n    }\n\n    static void rightShiftAndOr(int ch, int shift, int x, int[][][][] shr, int[] to) {\n        int[] z = shr[ch][shift & 31][x];\n        int delta = (shift >>> 5);\n        for (int i = 0; i + delta < to.length; i++) {\n            to[i + delta] |= z[i];\n        }\n    }\n\n    static void printBitset(int a[], int l, int r) {\n        for (int i = l; i <= r; i++) {\n            System.err.print(getBit(a, i) ? '1' : '0');\n        }\n        System.err.println();\n    }\n\n    static final int ALPHA = 26;\n\n    public static void main(String[] args) {\n        InputReader in = new InputReader(System.in);\n        PrintWriter out = new PrintWriter(System.out);\n\n        int n = in.nextInt();\n        int m = in.nextInt();\n\n        int[][][][] shl = new int[ALPHA][32][n][];\n        int[][][][] shr = new int[ALPHA][32][n][];\n\n        for (int c = 0; c < ALPHA; c++) {\n            for (int sh = 0; sh < 32; sh++) {\n                for (int i = 0; i < n; i++) {\n                    shl[c][sh][i] = newBitSet(m);\n                    shr[c][sh][i] = newBitSet(m);\n                }\n            }\n        }\n\n        String[] s = new String[n];\n\n        for (int i = 0; i < n; i++) {\n            s[i] = in.next();\n            for (int j = 0; j < m; j++) {\n                int c = s[i].charAt(j) - 'a';\n                for (int sh = 0; sh < 32; sh++) {\n                    if (j - sh >= 0) {\n                        setBit(shl[c][sh][i], j - sh);\n                    }\n                    if (j + sh < m) {\n                        setBit(shr[c][sh][i], j + sh);\n                    }\n                }\n            }\n        }\n\n        int r = in.nextInt();\n        int c = in.nextInt();\n\n        String[] patt = new String[r];\n\n        int[][] res = new int[n][];\n\n        for (int i = 0; i < n; i++) {\n            res[i] = newBitSet(m);\n            setAll(res[i]);\n        }\n\n        int[] tmp = newBitSet(m);\n\n        for (int i = 0; i < r; i++) {\n            patt[i] = in.next();\n            for (int j = 0; j < c; j++) {\n                if (patt[i].charAt(j) == '?') continue;\n                int cur = patt[i].charAt(j) - 'a';\n                int shiftByX = (((-i) % n) + n) % n;\n                int shiftByY = (((j) % m) + m) % m;\n\n                for (int x = 0; x < n; x++) {\n                    int nx = x + shiftByX;\n                    if (nx >= n) nx -= n;\n                    resetAll(tmp);\n                    leftShiftAndOr(cur, shiftByY, x, shl, tmp);\n                    rightShiftAndOr(cur, m - shiftByY, x, shr, tmp);\n                    andXYtoX(res[nx], tmp);\n                }\n            }\n        }\n\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                out.print(getBit(res[i], j) ? '1' : '0');\n            }\n            out.println();\n        }\n\n        out.close();\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "fft",
      "strings",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "755",
    "index": "A",
    "title": "PolandBall and Hypothesis",
    "statement": "PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: \"There exists such a positive integer $n$ that for each positive integer $m$ number $n·m + 1$ is a prime number\".\n\nUnfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any $n$.",
    "tutorial": "There are many ways to solve the problem. There can't be many primes in a row, so we can just bruteforce until we find a composite number. Note that it is not neccesarily true for huge numbers. More general, there is a prime arithmetic progression of length $k$ for any $k$, but there is no infinitely-long sequence! Another way to solve the problem is noticing that $n \\cdot (n - 2) + 1 = (n - 1) \\cdot (n - 1)$, so we can just output $n - 2$. However, we can't do that when $n  \\le  2$. This is a special case.",
    "tags": [
      "brute force",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "755",
    "index": "B",
    "title": "PolandBall and Game",
    "statement": "PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.\n\nYou're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?",
    "tutorial": "Let PolandBall know $n$ words, EnemyBall $m$ words. Let $k$ be set of words which both Balls know. It's easy to see that Balls should process words from $k$ first. If $k$ contains even number of words, PolandBall will have an advantage of one additional word. Then, if $n  \\le  m$, PolandBall loses. Otherwise - he wins.",
    "tags": [
      "binary search",
      "data structures",
      "games",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "755",
    "index": "C",
    "title": "PolandBall and Forest",
    "statement": "PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with $k$ vertices and $k - 1$ edges, where $k$ is some integer. Note that one vertex \\textbf{is} a valid tree.\n\nThere is exactly one relative living in each vertex of each tree, they have unique ids from $1$ to $n$. For each Ball $i$ we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.\n\nHow many trees are there in the forest?",
    "tutorial": "Property: Look at one tree and take its diameter. Name its endpoints A and B. For each vertex u from this component, $p[u] = A$ or $p[u] = B$. It's easy to prove that. We can just count number of different elements in P and divide it by two. Special case : Isolated vertices (those with $p[i] = i$).",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "interactive",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "755",
    "index": "D",
    "title": "PolandBall and Polygon",
    "statement": "PolandBall has such a convex polygon with $n$ veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments.\n\nHe chose a number $k$ such that $gcd(n, k) = 1$. Vertices of the polygon are numbered from $1$ to $n$ in a clockwise way. PolandBall repeats the following process $n$ times, starting from the vertex $1$:\n\nAssume you've ended last operation in vertex $x$ (consider $x = 1$ if it is the first operation). Draw a new segment from vertex $x$ to $k$-th next vertex in clockwise direction. This is a vertex $x + k$ or $x + k - n$ depending on which of these is a valid index of polygon's vertex.\n\nYour task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.",
    "tutorial": "First, we can set $k = min(k, n - k)$. This changes nothing right now, but we'll use it later. Our diagonals correspond to intervals [$L_{i}$, $R_{i}$], each intersection of two diagonals: A) adds one to result B) is equivalent to intersection of their intervals We will use segment or fenwick tree to store beginnings and ends of intervals. Because of the fact that all the segments have equal length (length = K) we know exactly what their intersection looks like. Also, in order to maintain edges like (7, 3) we'll insert some intervals twice. Because of changes we did to $k$ in the very beginning, we'll never count anything more than once. Complexity : $O(NlogN)$",
    "tags": [
      "data structures"
    ],
    "rating": 2000
  },
  {
    "contest_id": "755",
    "index": "E",
    "title": "PolandBall and White-Red graph",
    "statement": "PolandBall has an undirected simple graph consisting of $n$ vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white and red.\n\nColorfulness of the graph is a value $min(d_{r}, d_{w})$, where $d_{r}$ is the diameter of the red subgraph and $d_{w}$ is the diameter of white subgraph. The diameter of a graph is a largest value $d$ such that shortest path between some pair of vertices in it is equal to $d$. If the graph is not connected, we consider its diameter to be -1.\n\nPolandBall wants the final graph to be as neat as possible. He wants the final colorfulness to be equal to $k$. Can you help him and find any graph which satisfies PolandBall's requests?",
    "tutorial": "We should definitely start with estimating how big can be $k$. It turns out that we can't obtain diameter greater than $3$. You can prove this fact by yourself or try here: Proof. We can also easily show that answer is $- 1$ for $k = 1$. So, the problem is to solve K = 2 and K = 3. Constructing K = 3: Let's start with graph G, which is the smallest possible graph: 1 - 2 2 - 3 3 - 4 We will add vertices <$5$..$N$> one by one, when vertex $i$ will be joint with vertices 1 and 3, and if $i > 5$, with vertices <$5$; $i - 1$>. It's easy to see that ShortestPath(1, 4) is exactly 3. Also, ShortestPath(1, 4) in the complement graph is 3. Because of the property, this is a valid solution for $k = 3$. Constructing K = 2: When $N = 4$, answer is $- 1$. Graph G : path from 1 to N. G has diameter N - 1, but it does not matter. The smaller one is from complement graph. It is easy to see that for $N > 4$ the diameter of the second graph is exactly $2$. Of course there are many other ways to construct both graphs. Note that both red and white graphs have to be connected and we should pay some attention to it. Someone in the comments before the round said: \"Give him a hat, and he will become IndonesiaBall. \" Indeed, it's true. Country Balls usually have colours the same as flags of countries they represent. However, when PolandBall originated the creator mistakenly drew it as red-white instead of white-red. PolandBall was mad, but decided to stay this way =) This is a picture of a PolandBall dressed as husar. The husars were a Polish military formation from XVII century, a very powerful one. Usually recognizable because of the special wings.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "755",
    "index": "F",
    "title": "PolandBall and Gifts",
    "statement": "It's Christmas time! PolandBall and his friends will be giving themselves gifts. There are $n$ Balls overall. Each Ball has someone for whom he should bring a present according to some permutation $p$, $p_{i} ≠ i$ for all $i$.\n\nUnfortunately, Balls are quite clumsy. We know earlier that exactly $k$ of them will forget to bring their gift. A Ball number $i$ will get his present if the following two constraints will hold:\n\n- Ball number $i$ will bring the present he should give.\n- Ball $x$ such that $p_{x} = i$ will bring his present.\n\nWhat is minimum and maximum possible number of kids who will \\textbf{not} get their present if exactly $k$ Balls will forget theirs?",
    "tutorial": "Every permutation can be represented as a set of cycles. Maximum: This is the easier case. Greedy works, some careful implementation and it's ok. Answer is usually $2k$ in this case, but not always. Minimum: If there are such cycles $c_{1}$, $c_{2}$, ... $c_{m}$ of length $a_{1}$, $a_{2}$, ..., $a_{n}$ that $a_{1} + a_{2} + ... + a_{n} = K$, then K it's enough. Otherwise the result can be $K + 1$. We would like to use knapsack to check it. However, the constraints are too big in this case for a normal knapsack. We will choose some parameter $T$ and process all numbers bigger than $T$ normally. If there are $w$ such elements, then complexity of this step is $O({\\frac{w,k}{32}})$. There can be at most $\\ _{T}^{\\frac{N}{T}}$ numbers bigger than $T$, so it's $O({\\frac{n\\,k}{32\\cdot T}})$. What should we do with numbers smaller than $T$? We'll process all numbers of the same type at once. When processing number of type $x$, we will maintain array $c[]$ which denotes \"how many numbers of type $x$ are neccessary to have a certain number knapsack-possible. This step works in O($k \\cdot T$). Complexity : O($k \\cdot T$ + $\\frac{p_{2}\\cdot k}{3/2\\ast T}$). We should choose such $T$ that this value is minimum possible. $T = 100$ seems reasonable.",
    "tags": [
      "bitmasks",
      "dp",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "755",
    "index": "G",
    "title": "PolandBall and Many Other Balls",
    "statement": "PolandBall is standing in a row with Many Other Balls. More precisely, there are exactly $n$ Balls. Balls are proud of their home land — and they want to prove that it's strong.\n\nThe Balls decided to start with selecting exactly $m$ groups of Balls, each consisting either of single Ball or two neighboring Balls. Each Ball can join no more than one group.\n\nThe Balls really want to impress their Enemies. They kindly asked you to calculate number of such divisions for all $m$ where $1 ≤ m ≤ k$. Output all these values modulo $998244353$, the Enemies will be impressed anyway.",
    "tutorial": "The modulo instantly suggests an FFT-like approach. First, let's solve this problem using simple dynamic programming. DP[N][K] = DP[N-1][K] + DP[N-1][K-1] + DP[N-2][K-1], because we can either do nothing or add one interval of length 1 or 2. As for start, this works fine. We can calculate DP[1], DP[2], DP[3] and DP[4] using this simple formula. Calculating DP[x] means calculating DP[x][k] for all values k in range <1, K>, where K is the number from statement. We will perform binary exponentation of DPs. In order to do so, we should be able to count DP[x + 1] and DP[2 * x]. If we could do this operations, then we can obtain the result in O(logN). Important property: DP[a + b] can be counted using DP[a] * DP[b] and DP[a - 1] * DP[b - 1], when we treat DP[x] as polynomial with coefficients DP[x][0], DP[x][1], .... It is based by the fact that we can divide the sequence of length (a + b) in two parts of length a and b. If there is no segment of length 2 starting from position a, then we can choose some segments from the first part, and the remaining segments from the second part. For fixed number of intervals k, this is a sum of DP[a][i] * DP[b][k - i]. So, this is convolution of polynomials DP[A] and DP[B]. However, there may also be such a segment. In this case, everything stays the same, but we have k - 1 intervals instead of k and convolution of DP[a - 1] and DP[b - 1]. So, with some calculations we can count DP[a + b] using those DPs. Assume we have DP[n], DP[n - 1] and DP[n - 2]. Now we are trying to count DP[2 * n], DP[2 * n - 1], DP[2 * n - 2]. DP[2 * n] = DP[n + n], which can be counted using multiplication of DP[n] and DP[n-1]. DP[2*n-1] = DP[n + (n-1)], which can be counted using multiplication of DP[n], DP[n-1] and DP[n-2]. DP[2*n-2] = DP[(n-1) + (n-1)], which can be counted using multiplication of DP[n-1] and DP[n-2]. Therefore, we can obtain another, two times bigger, triplet of DPs. Of course, having DP[n], DP[n-1] and DP[n-2] in memory we can also easily count DP[n + 1] in O(K). We can also calculate DP[2*n], DP[2*n-1] and DP[2*n-2] in O(K log K). This is enough to perform the binary exponentation. Overall solution works in O(K log N log K).",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 3200
  },
  {
    "contest_id": "756",
    "index": "A",
    "title": "Pavel and barbecue",
    "statement": "Pavel cooks barbecue. There are $n$ skewers, they lay on a brazier in a row, each on one of $n$ positions. Pavel wants each skewer to be cooked some time in every of $n$ positions in two directions: in the one it was directed originally and in the reversed direction.\n\nPavel has a plan: a permutation $p$ and a sequence $b_{1}, b_{2}, ..., b_{n}$, consisting of zeros and ones. Each second Pavel move skewer on position $i$ to position $p_{i}$, and if $b_{i}$ equals $1$ then he reverses it. So he hope that every skewer will visit every position in both directions.\n\nUnfortunately, not every pair of permutation $p$ and sequence $b$ suits Pavel. What is the minimum total number of elements in the given permutation $p$ and the given sequence $b$ he needs to change so that every skewer will visit each of $2n$ placements? Note that after changing the permutation should remain a permutation as well.\n\nThere is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation $p$ and a sequence $b$ suit him if there is an integer $k$ ($k ≥ 2n$), so that after $k$ seconds each skewer visits each of the $2n$ placements.\n\nIt can be shown that some suitable pair of permutation $p$ and sequence $b$ exists for any $n$.",
    "tutorial": "At first, let's deal with the permutation. We can see that $p$ should have exactly one cycle to suit Pavel. The minimum number of changes is $0$ if there is only one cycle, and the number of cycles if there is more than one cycle. What should we do with $b$? We can see that the skewers visit a particular position $x$ in the same direction again and again if and only if the total number of ones in $b$ is even. If the total number of ones in $b$ is odd, then each time a skewer visits a particular position $x$, it has direction different from the previous time. Thus, the condition is satisfied if and only if the number of ones in $b$ is odd. We should add $1$ to the answer if it isn't.",
    "tags": [
      "constructive algorithms",
      "dfs and similar"
    ],
    "rating": 1700
  },
  {
    "contest_id": "756",
    "index": "B",
    "title": "Travel Card",
    "statement": "A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare.\n\nThe fare is constructed in the following manner. There are three types of tickets:\n\n- a ticket for one trip costs $20$ byteland rubles,\n- a ticket for $90$ minutes costs $50$ byteland rubles,\n- a ticket for one day ($1440$ minutes) costs $120$ byteland rubles.\n\nNote that a ticket for $x$ minutes activated at time $t$ can be used for trips started in time range from $t$ to $t + x - 1$, inclusive. Assume that all trips take exactly one minute.\n\nTo simplify the choice for the passenger, the system automatically chooses the optimal tickets. After each trip starts, the system analyses all the previous trips and the current trip and chooses a set of tickets for these trips with a minimum total cost. Let the minimum total cost of tickets to cover all trips from the first to the current is $a$, and the total sum charged before is $b$. Then the system charges the passenger the sum $a - b$.\n\nYou have to write a program that, for given trips made by a passenger, calculates the sum the passenger is charged after each trip.",
    "tutorial": "Hint: the problem looks difficult because tickets can change, however, it's can be solved with simple dynamic programming. You are asked the difference between neighboring dp's subtasks. More detailed editorial will be added soon.",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "756",
    "index": "C",
    "title": "Nikita and stack",
    "statement": "Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer $x$ on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing.\n\nNikita made $m$ operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the $i$-th step he remembers an operation he made $p_{i}$-th. In other words, he remembers the operations in order of some permutation $p_{1}, p_{2}, ..., p_{m}$. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him!",
    "tutorial": "Hint 1: look at the operations in the reverse order. Let's count the balance for each prefix, i.e. the difference between the number of push(x) operations and the number of pop() operations. Hint 2: Now we have to find the first operation that makes balance positive. This can be done using segment tree. Solution: Let's reverse the order of operations. Now we can see that on the top of the stack will be the first integer added with push(x) such that the number of pop() operations and the number of push(x) operations before this operation is equal, if there is one. Let's keep for each position a value called balance: the number of push(x) operations minus the number of pop() operations before and including this position. To find the answer, we should find the first position with posivive balance. When we add an operation, we should add -1 or 1 to all posisions starting with the position of the operation, depending on the type of the operation. To cope with the operations quickly, we can store the balance in a segment tree. The addition is done with lazy propogation, finding the first position with positive balance can be done in two ways. First way is to perform binary search on the answer and then query the segment tree for maximim on some prefix. The compexity is $O(\\log^{2}m)$ per query then. The other way is to walk down the tree always moving to the leftmost son with positive maximum. When we reach the leaf, the position of this leaf is the answer. The complexity is $O(\\log m)$ per query. The overall complexity is $O(m\\log m)$ or $O(m\\log^{2}m)$ depending on the realization.",
    "tags": [
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "756",
    "index": "D",
    "title": "Bacterial Melee",
    "statement": "Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters \"a\", ..., \"z\".\n\nThe testtube is divided into $n$ consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of $n$ Latin characters.\n\nSometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.\n\nFor example, consider a testtube with population \"babb\". There are six options for an attack that may happen next:\n\n- the first colony attacks the second colony ($1 → 2$), the resulting population is \"bbbb\";\n- $2 → 1$, the result is \"aabb\";\n- $2 → 3$, the result is \"baab\";\n- $3 → 2$, the result is \"bbbb\" (note that the result is the same as the first option);\n- $3 → 4$ or $4 → 3$, the population does not change.\n\nThe pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo $10^{9} + 7$.",
    "tutorial": "Hint: find a condition when a string is reachable from another string in terms of subsequences, then apply DP for counting suitable subsequences. Solution: How to determine if a string can be obtained from another string after a number of operations? It helps to consider (maximal) blocks of adjacent characters. Let us define $comp(s)$ as a \"compressed\" version of $s$ that keeps a single character from each block of $s$ in the same order, for example, $c o m p(\\mathrm{aaabbca})=\\mathrm{abca}$. It is not hard to see that each operation either preserves the sequence of blocks (if we ignore their lengths) or erases a single block (when it consists of a single character and is overwritten by an adjacent character). This is the same as saying that each operation applied to $s$ either doesn't change $comp(s)$ or erases a single character from it. Therefore, if $t$ can be obtained from $s$ after a number of operations, then $comp(t)$ must be a subsequence of $comp(s)$. In fact, this is an \"if and only if\" condition. Indeed, suppose that $comp(t)$ is a subsequence of $comp(s)$. We start our process of making $t$ from $s$ by eliminating the blocks not present in $t$, effectively making $comp(s) = comp(t)$. After that, it can be seen that the borders of the blocks can be moved rather freely (but carefully enough not to murder any block) so that $s$ can be indeed made equal to $t$. We can see from the last argument that from the reachability point of view the two strings $s$ and $t$ are essentially different if $comp(s)  \\neq  comp(t)$. If $s$ is the given string, and a string $u$ is a subsequence of $comp(s)$ that doesn't have equal adjacent characters, then there are $\\textstyle{\\binom{n-1}{\\left|u_{1}-1\\right\\rangle}}$ reachable strings with $comp(...) = u$; indeed, this is exactly the number of ways to split $n$ characters into $|u|$ non-empty blocks. Now, for each $l$ we have to count the number of subsequences of $s$ with length $l$ that do not have equal adjacent characters. There are several ways to do that. One way is storing $dp_{c, l}$ - the number of valid subsequences of length $l$ that end in character $c$. We now process characters one by one and recompute values of $dp_{c, l}$. If the new character is $c_{i}$, then clearly values of $dp_{c, l}$ with $c  \\neq  c_{i}$ do not change. We can also see that we can find the new values of $dp_{ci, l}$ with the formula $d p_{c,l}=1+\\sum_{c\\cap c_{i}}d p_{c,l-1}$",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "string suffix structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "756",
    "index": "E",
    "title": "Byteland coins",
    "statement": "There are $n$ types of coins in Byteland. Conveniently, the denomination of the coin type $k$ divides the denomination of the coin type $k + 1$, the denomination of the coin type $1$ equals $1$ tugrick. The ratio of the denominations of coin types $k + 1$ and $k$ equals $a_{k}$. It is known that for each $x$ there are at most \\textbf{20} coin types of denomination $x$.\n\nByteasar has $b_{k}$ coins of type $k$ with him, and he needs to pay exactly $m$ tugricks. It is known that Byteasar never has more than $3·10^{5}$ coins with him. Byteasar want to know how many ways there are to pay exactly $m$ tugricks. Two ways are different if there is an integer $k$ such that the amount of coins of type $k$ differs in these two ways. As all Byteland citizens, Byteasar wants to know the number of ways modulo $10^{9} + 7$.",
    "tutorial": "Let's calculate DP[pref][x] - number of ways to pay $x$ tugriks using only $pref$ first types. Of course, $x$ can be very big, but we will store DP only for those $x$ which are not bigger than the sum of all the coins of first $pref$ types and can lead to answer: $x = k \\cdot D + (m%D)$ where $D$ is the last coin denomination. Every next layer of this DP can be calculated in $O(sz_{i})$ time using prefix sums where $sz$ is the size of the new layer. $s z_{i}\\leq\\Sigma_{j=1}^{i}b_{j}\\cdot{\\frac{D_{i}}{D_{i}}}$. $\\begin{array}{c}{{\\Sigma_{i=1}^{n}s z_{i}\\le\\Sigma_{i=1}^{n}\\Sigma_{j=1}^{i}b_{j}\\cdot\\frac{D_{i}}{D_{i}}=\\Sigma_{j=1}^{n}\\Sigma_{i=j}^{n}b_{j}\\cdot\\frac{D_{j}}{D_{i}}\\le\\Sigma_{j=1}^{n}b_{j}\\left(\\frac{k}{1}+\\frac{k}{2}+\\frac{k}{2^{2}}+\\ldots\\right)=}}\\end{array}$ Now all that remains is to calculate some info about $m%D$ to know what DP elemnts we are interested in. We should represent $m$ in a form of $ \\Sigma _{i = 1}^{n}c_{i} \\cdot D_{i}$. To find $c_{i}$ we should successively divide $m$ by all $a_{i}$, $c_{i}$ will be the reminders. All the divisions can be done in $O(\\log^{2}m)$ time if we will not divide by $1$. Total complexity - $\\left(\\log^{2}m+k\\cdot\\Sigma_{i=1}^{n}b_{i}\\right)$",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "756",
    "index": "F",
    "title": "Long number",
    "statement": "Consider the following grammar:\n\n- <expression> ::= <term> | <expression> '+' <term>\n- <term> ::= <number> | <number> '-' <number> | <number> '(' <expression> ')'\n- <number> ::= <pos_digit> | <number> <digit>\n- <digit> ::= '0' | <pos_digit>\n- <pos_digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n\nThis grammar describes a number in decimal system using the following rules:\n\n- <number> describes itself,\n- <number>-<number> (l-r, $l ≤ r$) describes integer which is concatenation of all integers from $l$ to $r$, written without leading zeros. For example, 8-11 describes 891011,\n- <number>(<expression>) describes integer which is concatenation of <number> copies of integer described by <expression>,\n- <expression>+<term> describes integer which is concatenation of integers described by <expression> and <term>.\n\nFor example, 2(2-4+1)+2(2(17)) describes the integer 2341234117171717.\n\nYou are given an expression in the given grammar. Print the integer described by it modulo $10^{9} + 7$.",
    "tutorial": "First of all we need to somehow parse the expression. Let's suppose we've builded a parse tree for the expression. Every number X can be seen as operation \"concatenate something and X\". We should understand how such an operation changes the number. $YX = Y \\cdot 10^{len(X)} + X$. So we can represent each number $X$ as pair $(10^{len(X)}%MOD, X%MOD)$. Two such pairs can be merged: $(X_{1}, Y_{1}) + (X_{2}, Y_{2}) = (X_{1} \\cdot X_{2}, Y_{1} \\cdot X_{2} + Y_{2})$. Z((X,Y)) $= (X \\cdot Z,  \\Sigma _{i = 0}^{Z - 1}Y \\cdot X^{i}) = (X \\cdot Z, Y \\cdot  \\Sigma _{i = 0}^{Z - 1}X^{i})$. Geometric series can be calculated in $O(\\log Z)$ time (using binary exponentiation) in both cases $X = 1$ and $X  \\neq  1$. L-R: if $len(L) = len(R)$ then L-R $= (len(L) \\cdot (R - L + 1),  \\Sigma _{i = 0}^{R - L}(R - i) \\cdot (10^{len(L)})^{i})$ $\\Sigma_{t=0}^{R-L}(R-i)\\cdot(10^{l e n(L)})^{i}=(R+1)\\cdot{\\frac{(10^{p o n(L))^{2}-L+1}-1}{10^{q e n(L)}-1}}-{\\frac{(R-L+1)(10^{p o n(L)})^{n-L+1}}{t0^{q e n(L)}-1}}$. This sum also can be calculated in $O(len(L))$. If $len(L)  \\neq  len(R)$ then we should iterate over all lengths between $len(L) + 1$ and $len(R) - 1$. But for every such length we can first calculate powers ($9 \\cdot 10^{len - 1} + eps$) modulo $ \\phi (MOD) = MOD - 1$ and then do the calculation in $O(\\log M O D)$ time. Overall complexity will be $O(|s|\\cdot\\log M O D)$.",
    "tags": [
      "expression parsing",
      "math",
      "number theory"
    ],
    "rating": 3400
  },
  {
    "contest_id": "757",
    "index": "A",
    "title": "Gotta Catch Em' All!",
    "statement": "Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.\n\nEach day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word \"Bulbasaur\" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of \"Bulbasaur\" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word \"Bulbasaur\" from the newspaper.\n\nGiven the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?\n\nNote: \\textbf{uppercase and lowercase letters are considered different.}",
    "tutorial": "Expected complexity: ${\\mathcal{O}}(n)$ Main idea: Maintain counts of required characters. Since we are allowed to permute the string in any order to find the maximum occurences of the string \"Bulbasaur\", we simply keep the count of the letters 'B', 'u', 'l', 'b', 'a', 's', 'r'. Now the string \"Bulbasaur\" contains 1 'B', 2'u', 1 'l', 2'a', 1 's', 1'r' and 1 'b', thus the answer to the problem is Min(count('B'), count('b'), count('s'), count('r'), count('l'), count('a')/2, count('u')/2). You can maintain the counts using an array. Corner Cases: 1. Neglecting 'B' and while calculating the answer considering count('b')/2. 2. Considering a letter more than once ( 'a' and 'u' ).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n  map<char, int> m;\n  string s;\n  cin>>s;\n  for(auto x : s)\n    m[x]++;\n\n  int ans = m['B'];\n  ans = min(ans, m['u']/2);\n  ans = min(ans, m['a']/2);\n  ans = min(ans, m['b']);\n  ans = min(ans, m['s']);\n  ans = min(ans, m['r']);\n  ans = min(ans, m['l']);\n  cout << ans << endl;\n  return 0;\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "757",
    "index": "B",
    "title": "Bash's Big Day",
    "statement": "Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.\n\nBut Zulu warns him that a group of $k > 1$ Pokemon with strengths ${s_{1}, s_{2}, s_{3}, ..., s_{k}}$ tend to fight among each other if $gcd(s_{1}, s_{2}, s_{3}, ..., s_{k}) = 1$ (see notes for $gcd$ definition).\n\nBash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take?\n\n\\textbf{Note}: A Pokemon cannot fight with itself.",
    "tutorial": "Expected complexity: $O(n{\\sqrt{m a x(s_{i})}})$ Main idea: Square-root factorization and keeping count of prime factors. The problem can be simplified to finding a group of Pokemons such that their strengths have a common factor other that $1$. We can do this by marking just the prime factors, and the answer will be the maximum count of a prime factor occurring some number of times. The prime numbers of each number can be found out using pre-computed sieve or square-root factorization. Corner Cases : Since a Pokemon cannot fight with itself (as mentioned in the note), the minimum answer is 1. Thus, even in cases where every subset of the input has gcd equal to 1, the answer will be 1.",
    "code": "\n#include<bits/stdc++.h>\nusing namespace std;\nint N;\nunordered_map<int, int> factors;\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin >> N;\n\n\twhile(N--)\n\t{\n\t\tint strength;\n\t\tcin >> strength;\n\n\t\tint root = sqrt(strength);\n\t\tfor(int i = 2; i <= root; i++)\n\t\t{\n\t\t\tif(strength%i == 0)\n\t\t\t\tfactors[i]++;\n\n\t\t\twhile(strength%i ==\n\t\t\t\t\t0) strength\n\t\t\t\t/= i;\n\t\t}\n\n\t\tif(strength > 1) factors[strength]++; \n\t}\n\n\tint ans = 1;\n\tfor(auto it = factors.begin(); it != factors.end(); it++)\n\t{\n\t\tans = max(ans, (*it).second);\n\t}\n\n\tcout << ans << endl;\n\n\treturn 0;\n}\n\n",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "757",
    "index": "C",
    "title": "Felicity is Coming!",
    "statement": "It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has $n$ gyms. The $i$-th gym has $g_{i}$ Pokemon in it. There are $m$ distinct Pokemon types in the Himalayan region numbered from $1$ to $m$. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving.\n\nFormally, an evolution plan is a permutation $f$ of ${1, 2, ..., m}$, such that $f(x) = y$ means that a Pokemon of type $x$ evolves into a Pokemon of type $y$.\n\nThe gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol.\n\nTwo evolution plans $f_{1}$ and $f_{2}$ are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an $i$ such that $f_{1}(i) ≠ f_{2}(i)$.\n\nYour task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo $10^{9} + 7$.",
    "tutorial": "Expected complexity: $O(n l o g n)$ Main idea: Divide pokemon types into equivalence classes based on their counts in each list. Consider a valid evolution plan $f$. Let $c[p, g]$ be the number of times Pokemon $p$ appears in gym $g$. If $f(p) = q$ then $c[p,g_{i}]=c[q,g_{i}]\\quad\\forall i$. Now consider a group of Pokemon $P$ such that all of them occur equal number of times in each gym (i.e. for each $p,q\\in P,\\quad f[p_{i},g_{k}]=f[p_{j},g_{k}]\\quad\\forall k$). Any permutation of this group would be a valid bijection. Say we have groups $s_{1}, s_{2}, s_{3}, ...$, then the answer would be $|s_{1}|! |s_{2}|! |s_{3}|! ... mod 10^{9} + 7$. For implementing groups, we can use $vector < vector < int > >$ and for $i$-th pokemon, add the index of the gym to $i$-th vector. Now we need to find which of these vectors are equal. If we have the sorted $vector < vector < int > >$, we can find equal elements by iterating over it and comparing adjacent elements. Consider the merge step of merge sort. For a comparison between 2 vectors $v_{1}$ and $v_{2}$, we cover at least $min(v_{1}.size(), v_{2}.size())$ elements. Hence ${\\mathcal{O}}(n)$ work is done at each level. There are $O(l o g n)$ levels.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\n#define PB push_back\n#define ALL(X) X.begin(), X.end()\n\n#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL)\n\nconst int N = 1e6;\nconst LL MOD = 1e9 + 7;\nLL fact[N+1];\nint main()\n{\n    fast_io;\n    fact[0] = fact[1] = 1;\n    for(LL i=2;i<=N;i++)\n        fact[i] = (fact[i-1]*i)%MOD;\n    int n,m;\n    cin >> n >> m;\n    vector< vector<int> > x(m);\n    for(int i=0;i<n;i++) {\n        int s;\n        cin >> s;\n        for(int j=0;j<s;j++) {\n            int t;\n            cin >> t;\n            x[t-1].PB(i);\n        }\n    }\n    for(int i=0;i<m;i++)\n        sort(ALL(x[i]));\n    sort(ALL(x));\n    LL ans = 1;\n    LL sm = 1;\n    for(int i=1;i<m;i++) {\n        if(x[i]==x[i-1])\n            sm++;\n        else\n            ans = (ans*fact[sm])%MOD, sm = 1;\n    }\n    ans = (ans*fact[sm])%MOD;\n    cout << ans << endl;\n    return 0;\n}\n\n",
    "tags": [
      "data structures",
      "hashing",
      "sortings",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "757",
    "index": "D",
    "title": "Felicity's Big Secret Revealed",
    "statement": "The gym leaders were fascinated by the evolutions which took place at Felicity camp. So, they were curious to know about the secret behind evolving Pokemon.\n\nThe organizers of the camp gave the gym leaders a PokeBlock, a sequence of $n$ ingredients. Each ingredient can be of type $0$ or $1$. Now the organizers told the gym leaders that to evolve a Pokemon of type $k$ ($k ≥ 2$), they need to make a valid set of $k$ cuts on the PokeBlock to get smaller blocks.\n\nSuppose the given PokeBlock sequence is $b_{0}b_{1}b_{2}... b_{n - 1}$. You have a choice of making cuts at $n + 1$ places, i.e., Before $b_{0}$, between $b_{0}$ and $b_{1}$, between $b_{1}$ and $b_{2}$, ..., between $b_{n - 2}$ and $b_{n - 1}$, and after $b_{n - 1}$.\n\nThe $n + 1$ choices of making cuts are as follows (where a | denotes a possible cut):\n\n\\[\n| b_{0} | b_{1} | b_{2} | ... | b_{n - 2} | b_{n - 1} |\n\\]\n\nConsider a sequence of $k$ cuts. Now each pair of consecutive cuts will contain a binary string between them, formed from the ingredient types. The ingredients before the first cut and after the last cut are wasted, which is to say they are not considered. So there will be exactly $k - 1$ such binary substrings. Every substring can be read as a binary number. Let $m$ be the maximum number out of the obtained numbers. If all the obtained numbers are positive and the set of the obtained numbers contains all integers from $1$ to $m$, then this set of cuts is said to be a valid set of cuts.\n\nFor example, suppose the given PokeBlock sequence is $101101001110$ and we made $5$ cuts in the following way:\n\n\\[\n10 | 11 | 010 | 01 | 1 | 10\n\\]\n\nSo the $4$ binary substrings obtained are: $11$, $010$, $01$ and $1$, which correspond to the numbers $3$, $2$, $1$ and $1$ respectively. Here $m = 3$, as it is the maximum value among the obtained numbers. And all the obtained numbers are positive and we have obtained all integers from $1$ to $m$. Hence this set of cuts is a valid set of $5$ cuts.\n\nA Pokemon of type $k$ will evolve only if the PokeBlock is cut using a valid set of $k$ cuts. There can be many valid sets of the same size. Two valid sets of $k$ cuts are considered different if there is a cut in one set which is not there in the other set.\n\nLet $f(k)$ denote the number of valid sets of $k$ cuts. Find the value of $s=\\sum_{k=2}^{n+1}f(k)$. Since the value of $s$ can be very large, output $s$ modulo $10^{9} + 7$.",
    "tutorial": "Expected complexity: $O(N*2^{20})$ Main idea: DP with Bitmask. This problem can be solved using Dynamic Programming with bitmask. The important thing to note here is that the set of distinct numbers formed will be a maximum of 20 numbers, i.e. from 1 to 20, else it won't fit 75 bits(1*(1 bits) + 2*(2 bits) + 4*(3 bits) + 8*(4 bits) + 5*(5 bits) = 74 bits). So, we can use a bitmask to denote a set of numbers that are included in a set of cuts. Let's see a Top-Down approach to solve it : Lets define the function $f(i, mask)$ as : $f(i, mask)$ denotes the number of sets of valid cuts that can be obtained from the state $i, mask$. The state formation is defined below. Let $M$ be the maximum number among the numbers in $mask$. $mask$ denotes a set of numbers that have been generated using some number of cuts, all of them before $b_{i}$. Out of these cuts, the last cut has been placed just before $b_{i}$. Now, first we check if the set of cuts obtained from $mask$ is valid or not(in order for a mask to be valid, mask == $2^{X - 1}$ where $X$ denotes number of set bits in the mask) and increment the answer accordingly if the mask is valid. And then we also have the option of adding another cut. We can add the next cut just before $b_{x}$ provided the number formed by \"$b_{i}$ $b_{i + 1}$...$b_{x - 1}$\" <= 20. Set the corresponding bit for this number formed to 1 in the $mask$ to obtain $newMask$ and recursively find $f(x, newMask)$.",
    "code": "\n// Saatwik Singh Nagpal\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define TRACE\n#ifdef TRACE\n#define TR(...) __f(#__VA_ARGS__, __VA_ARGS__)\ntemplate <typename Arg1>\nvoid __f(const char* name, Arg1&& arg1){\n  cerr << name << \" : \" << arg1 << std::endl;\n}\ntemplate <typename Arg1, typename... Args>\nvoid __f(const char* names, Arg1&& arg1, Args&&... args){\n  const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << \" : \" << arg1<<\" | \";__f(comma+1, args...);\n}\n#else\n#define TR(...)\n#endif\n\ntypedef long long                LL;\ntypedef vector < int >           VI;\ntypedef pair < int,int >         II;\ntypedef vector < II >            VII;\n\n#define MOD                      1000000007\n#define EPS                      1e-12\n#define N                        200100\n#define PB                       push_back\n#define MP                       make_pair\n#define F                        first \n#define S                        second\n#define ALL(v)                   v.begin(),v.end()\n#define SZ(a)                    (int)a.size()\n#define FILL(a,b)                memset(a,b,sizeof(a))\n#define SI(n)                    scanf(\"%d\",&n)\n#define SLL(n)                   scanf(\"%lld\",&n)\n#define PLLN(n)                  printf(\"%lld\\n\",n)\n#define PIN(n)                   printf(\"%d\\n\",n)\n#define REP(i,j,n)               for(LL i=j;i<n;i++)\n#define PER(i,j,n)               for(LL i=n-1;i>=j;i--)\n#define endl                     '\\n'\n#define fast_io                  ios_base::sync_with_stdio(false);cin.tie(NULL)\n\n#define FILEIO(name) \\\n  freopen(name\".in\", \"r\", stdin); \\\n  freopen(name\".out\", \"w\", stdout);\n \ninline int mult(int a , int b) { LL x = a; x *= LL(b); if(x >= MOD) x %= MOD; return x; }\ninline int add(int a , int b) { return a + b >= MOD ? a + b - MOD : a + b; }\ninline int sub(int a , int b) { return a - b < 0 ? MOD - b + a : a - b; }\nLL powmod(LL a,LL b) { if(b==0)return 1; LL x=powmod(a,b/2); LL y=(x*x)%MOD; if(b%2) return (a*y)%MOD; return y%MOD; }\n\nint dp[1<<20][77];\nint b[77] , n;\nint go(int mask , int i) {\n  int cnt = __builtin_popcount(mask);\n  if(i == n) {\n    if(cnt != 0 && (1<<cnt)-1 == mask)\n      return 1;\n    return 0;\n  }\n  if(dp[mask][i] != -1) return dp[mask][i];\n\n  int ret = 0;\n  if(b[i] == 0)\n    ret = go(mask , i+1);\n  else {\n    int num = 0;\n    int j = i;\n    while(1) {\n      num *= 2;\n      num += b[j];\n      if(num > 20) break;\n      //if(!(mask & (1<<(num-1))))\n      ret = add(ret , go(mask | (1<<(num-1)) , j+1));\n      j ++;\n      if(j == n) break;\n    }\n    if(cnt != 0 && mask == (1<<cnt)-1)\n      ret ++;\n  }\n  return dp[mask][i] = ret;\n}\n\nint main() {\n  FILL(dp,-1);\n  cin >> n;\n  string s; cin >> s;\n  REP(i,0,n)\n    b[i] = s[i] - '0';\n  int ans = 0;\n  REP(i,0,n)\n    ans = add(ans , go(0,i));\n  PIN(ans);\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "757",
    "index": "E",
    "title": "Bash Plays with Functions",
    "statement": "Bash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions.\n\nBash defines a function $f_{0}(n)$, which denotes the number of ways of factoring $n$ into two factors $p$ and $q$ such that $gcd(p, q) = 1$. In other words, $f_{0}(n)$ is the number of ordered pairs of positive integers $(p, q)$ such that $p·q = n$ and $gcd(p, q) = 1$.\n\nBut Bash felt that it was too easy to calculate this function. So he defined a series of functions, where $f_{r + 1}$ is defined as:\n\n\\[\nf_{r+1}(n)=\\sum_{u\\cdot n=n}{\\frac{f_{r}(u)+f_{r}(v)}{2}},\n\\]\n\nWhere $(u, v)$ is any ordered pair of positive integers, they need not to be co-prime.\n\nNow Bash wants to know the value of $f_{r}(n)$ for different $r$ and $n$. Since the value could be huge, he would like to know the value modulo $10^{9} + 7$. Help him!",
    "tutorial": "Expected complexity: $O((N+Q)l o g N)$ Main idea: Multiplicative Functions. We can easily see that $f_{0}$ = $2^{(number of distinct prime factors of n)}$. We can also see that it is a multiplicative function. We can also simplify the definition of $f_{r + 1}$ as: $f_{r+1}(n)=\\sum_{d\\mid n}f_{r}(d)$ Since $f_{0}$ is a multiplicative function, $f_{r + 1}$ is also a multiplicative function. (by property of multiplicative functions) For each query, factorize $n$. Now, since $f_{r}$ is a multiplicative function, if $n$ can be written as: $n = p_{1}^{e1}p_{2}^{e2} ... p_{q}^{eq}$ Then $f_{r}(n)$ can be computed as: $f_{r}(n) = f_{r}(p_{1}^{e1}) * f_{r}(p_{2}^{e2}) * ... * f_{r}(p_{q}^{eq})$ Now observe that the value of $f_{r}(p^{n})$ is independent of $p$, as $f_{0}(p^{n}) = 2$. It is dependent only on $n$. So we calculate $f_{r}(2^{x})$ for all r and x using a simple $R * 20$ DP as follows: $d p[r][x]=\\sum_{i=0}^{n}d p[r-1][i]$ And now we can quickly compute $f_{r}(n)$ for each query as: $f_{r}(n) = dp[r][e_{1}] * dp[r][e_{2}] * ... * dp[r][e_{q}]$",
    "code": "\n//Kyokai no Kanata //\n//Written by Satyam Pandey//\n#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int,int> II;\ntypedef vector<II> VII;\ntypedef vector<int> VI;\ntypedef vector< VI > VVI;\ntypedef long long int LL;\n\n#define PB push_back\n#define MP make_pair\n#define F first\n#define S second\n#define SZ(a) (int)(a.size())\n#define ALL(a) a.begin(),a.end()\n#define SET(a,b) memset(a,b,sizeof(a))\n\n#define si(n) scanf(\"%d\",&n)\n#define dout(n) printf(\"%d\\n\",n)\n#define sll(n) scanf(\"%lld\",&n)\n#define lldout(n) printf(\"%lld\\n\",n)\n#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL)\n#define TRACE\n\n#ifdef TRACE\n#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)\ntemplate <typename Arg1>\nvoid __f(const char* name, Arg1&& arg1){\n  cerr<<name<<\" : \"<<arg1<<endl;\n}\ntemplate <typename Arg1, typename... Args>\nvoid __f(const char* names,Arg1&& arg1,Args&&... args){\n  const char* comma=strchr(names+1,',');\n  cerr.write(names,comma-names)<<\" : \"<<arg1<<\" | \";__f(comma+1,args...);\n}\n#else\n#define trace(...)\n#endif\nfloat  inf=std::numeric_limits<double>::infinity();\nLL INF=std::numeric_limits<LL>::max();\n//FILE *fin = freopen(\"in\",\"r\",stdin);\n//FILE *fout = freopen(\"out\",\"w\",stdout);\nconst int R=int(1e6)+5,P=25,N=R,mod = int(1e9)+7;\nint  F[R][P],LP[N];\ninline void seive(){\n  LP[1]=1;\n  for(int i=2;i<N;i++){\n    if(!LP[i])\n      for(int j=i;j<N;j+=i)\n        LP[j]=i;      \n  }\n}\ninline void precalc()\n{\n  for(int i=0;i<R;i++) F[i][0] = 1; \n  for(int i=1;i<P;i++) F[0][i] = 2;\n  for(int i=1;i<R;i++) \n   for(int j=1;j<P;j++)\n     F[i][j] = (F[i][j-1] + F[i-1][j])%mod;\n}\ninline LL solve(int r,int n)\n{\n  LL ans=1;\n  while(n!=1)\n  {\n      int cnt=0,p=LP[n];\n      while(n%p==0) n/=p,cnt++;\n      ans=(ans*F[r][cnt])%mod;\n  }\n  return ans;\n}\nint main()\n{\n  seive();precalc();\n  int q;si(q);\n  int r,n;\n  while(q--)\n  {\n    si(r);si(n);\n    lldout(solve(r,n));\n  }\n  return 0;\n}\n",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "757",
    "index": "F",
    "title": "Team Rocket Rises Again",
    "statement": "It's the turn of the year, so Bash wants to send presents to his friends. There are $n$ cities in the Himalayan region and they are connected by $m$ bidirectional roads. Bash is living in city $s$. Bash has exactly one friend in each of the other cities. Since Bash wants to surprise his friends, he decides to send a Pikachu to each of them. \\textbf{Since there may be some cities which are not reachable from Bash's city, he only sends a Pikachu to those friends who live in a city reachable from his own city}. He also wants to send it to them as soon as possible.\n\nHe finds out the minimum time for each of his Pikachus to reach its destination city. Since he is a perfectionist, he informs all his friends with the time their gift will reach them. A Pikachu travels at a speed of $1$ meters per second. His friends were excited to hear this and would be unhappy if their presents got delayed. Unfortunately Team Rocket is on the loose and they came to know of Bash's plan. They want to maximize the number of friends who are unhappy with Bash.\n\nThey do this by destroying exactly one of the other $n - 1$ cities. This implies that \\textbf{the friend residing in that city dies, so he is unhappy as well}.\n\nNote that \\textbf{if a city is destroyed, all the roads directly connected to the city are also destroyed and the Pikachu may be forced to take a longer alternate route}.\n\n\\textbf{Please also note that only friends that are waiting for a gift count as unhappy, even if they die.}\n\nSince Bash is already a legend, can you help Team Rocket this time and find out the maximum number of Bash's friends who can be made unhappy by destroying exactly one city.",
    "tutorial": "Expected complexity: $O((N+M)\\cdot l o g N)$ Main idea: Building Dominator tree on shortest path DAG. First of all, we run Dijkstra's shortest path algorithm from $s$ as the source vertex and construct the shortest path DAG of the given graph. Note that in the shortest path DAG, the length of any path from $s$ to any other node $x$ is equal to the length of the shortest path from $s$ to $x$ in the given graph. Now, let us analyze what the function $f(s, x)$ means. It will be equal to the number of nodes $u$ such that every path from $s$ to $u$ passes through node $x$ in the shortest path DAG, such that on removing node $x$ from the DAG, there will be no path from $s$ to $u$. In other words, we want to find the number of nodes $u$ that are dominated by node $x$ considering $s$ as the sources vertex in the shortest path DAG. This can be calculated by building dominator tree of the shortest path DAG considering $s$ as the source vertex. A node $u$ is said to dominate a node $w$ wrt source vertex $s$ if all the paths from $s$ to $w$ in the graph must pass through node $u$. You can read more about dominator tree here. Once the dominator tree is formed, the answer for any node $x$ is equal to the number of nodes in the subtree of $x$ in the tree formed. Another approach for forming dominator tree is by observing that the shortest path directed graph formed is a DAG i.e. acyclic. So suppose we process the nodes of the shortest path dag in topological order and have a dominator tree of all nodes from which we can reach $x$ already formed. Now, for the node $x$, we look at all the parents $p$ of $x$ in the DAG, and compute their LCA in the dominator tree built till now. We can now attach the node $x$ as a child of the LCA in the tree.",
    "code": "#include <cstdio>\n#include <cstring>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <map>\n#include <set>\n#include <cassert>\nusing namespace std;\n#define rep(i,a,n) for (int i=a;i<n;i++)\n#define per(i,a,n) for (int i=n-1;i>=a;i--)\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n#define SZ(x) ((int)(x).size())\ntypedef vector<int> VI;\ntypedef long long ll;\ntypedef pair<int,int> PII;\nconst ll mod=1000000007;\nll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}\n// head\n \ntypedef std::vector<PII> VPII;\nconst int N=201000;\nVPII e[N];\nll dis[N];\nint vis[N];\nset<pair<ll,int> > hs;\nint ord[N],sz[N],dep[N];\nconst ll inf=1ll<<60;\nvoid dijkstra(int S,int n) {\n\trep(i,1,n+1) dis[i]=inf,vis[i]=0;\n\tdis[S]=0;\n\trep(i,1,n+1) hs.insert(mp(dis[i],i));\n\trep(i,0,n) {\n\t\tint u=hs.begin()->se; hs.erase(hs.begin());\n\t\tvis[u]=1; ord[i]=u;\n\t\trep(j,0,SZ(e[u])) {\n\t\t\tint v=e[u][j].fi;\n\t\t\tif (dis[v]>dis[u]+e[u][j].se) {\n\t\t\t\ths.erase(mp(dis[v],v));\n\t\t\t\tdis[v]=dis[u]+e[u][j].se;\n\t\t\t\ths.insert(mp(dis[v],v));\n\t\t\t}\n\t\t}\n\t}\n}\n \nint n,m,s,u,v,w,p[N][22];\n \n#define LOGN 20\nint lca(int u,int v) {\n\tif (dep[u]>dep[v]) swap(u,v);\n\tper(i,0,LOGN) if (dep[p[v][i]]>=dep[u]) v=p[v][i];\n\tif (u==v) return u;\n\tper(i,0,LOGN) if (p[v][i]!=p[u][i]) u=p[u][i],v=p[v][i];\n\treturn p[u][0];\n}\n \nint main() {\n\tscanf(\"%d%d%d\",&n,&m,&s);\n\trep(i,0,m) {\n\t\tscanf(\"%d%d%d\",&u,&v,&w);\n\t\te[u].pb(mp(v,w));\n\t\te[v].pb(mp(u,w));\n\t}\n\tdijkstra(s,n);\n\tp[s][0]=0; dep[s]=1;\n\trep(i,1,n) {\n\t\tint d=-1; u=ord[i];\n\t\tfor (auto p:e[u]) {\n\t\t\tif (dis[p.fi]+p.se==dis[u]) {\n\t\t\t\tif (d==-1) d=p.fi;\n\t\t\t\telse d=lca(d,p.fi);\n\t\t\t}\n\t\t}\n\t\tif (dis[u]>(1ll<<50)) assert(d==-1);\n\t\tp[u][0]=d; dep[u]=dep[d]+1;\n\t\trep(j,1,21) p[u][j]=p[p[u][j-1]][j-1];\n\t}\n\trep(i,1,n+1) sz[i]=1;\n\tint ret=0;\n\tper(i,1,n) {\n\t\tu=ord[i];\n\t\tsz[p[u][0]]+=sz[u];\n\t\tif (dis[u]<=(1ll<<50)) ret=max(ret,sz[u]);\n\t}\n\tprintf(\"%d\\n\",ret);\n}",
    "tags": [
      "data structures",
      "graphs",
      "shortest paths"
    ],
    "rating": 2800
  },
  {
    "contest_id": "757",
    "index": "G",
    "title": "Can Bash Save the Day?",
    "statement": "Whoa! You did a great job helping Team Rocket who managed to capture all the Pokemons sent by Bash. Meowth, part of Team Rocket, having already mastered the human language, now wants to become a master in programming as well. He agrees to free the Pokemons if Bash can answer his questions.\n\nInitially, Meowth gives Bash a weighted tree containing $n$ nodes and a sequence $a_{1}, a_{2}..., a_{n}$ which is a permutation of $1, 2, ..., n$. Now, Mewoth makes $q$ queries of one of the following forms:\n\n- 1 l r v: meaning Bash should report $\\sum_{i=1}^{r}d i s t(a_{i},v)$, where $dist(a, b)$ is the length of the shortest path from node $a$ to node $b$ in the given tree.\n- 2 x: meaning Bash should swap $a_{x}$ and $a_{x + 1}$ in the given sequence. This new sequence is used for later queries.\n\nHelp Bash to answer the questions!",
    "tutorial": "Expected complexity: $\\ O((N+Q)\\cdot l o g N)$ Main idea: Making the Centroid Tree Persistent. First let's try to solve a much simpler problem given as follows. Question: Given a weighted tree, initially all the nodes of the given tree are inactive. We need to support the following operations fast : $Query v$ : Report the sum of distances of all active nodes from node $v$ in the given tree. $Activate v$ : Mark node $v$ to be an active node. Solution: The above problem can be easily solved by a fairly standard technique called Centroid Decomposition. You can read more about here Solution Idea Each query of the form $(L R v)$ can be divided into two queries of form $(1 R v)$ $-$ $(1 L - 1 v)$. Hence it is sufficient if we can support the following query: $(i v)$ : Report the answer to query $(1 i v)$ To answer a single query of the form $(i v)$ we can think of it as what is the sum of distance of all active nodes from node $v$, if we consider the first $i$ nodes to be active. Hence initially if we can preprocess the tree such that we activate nodes from $1$ to $n$ and after each update, store a copy of the centroid tree, then for each query $(i v)$ we can lookup the centroid tree corresponding to $i$, which would have the first $i$ nodes activated, and query for node $v$ in $O(l o g N)$ time by looking at it's ancestors. To store a copy of the centroid tree for each $i$, we need to make it persistent. Persistent Centroid Tree : Key Ideas Important thing to note is that single update in the centroid tree affects only the ancestors of the node in the tree. Since height of the centroid tree is $O(l o g N)$, each update affects only $O(l o g N)$ other nodes in the centroid tree. The idea is very similar to that of a persistent segment tree BUT unlike segtree, here each node of the centroid tree can have arbitrarily many children and hence simply creating a new copy of the affected nodes would not work because linking them to the children of old copy would take ${\\cal O}(n u m b e r\\ o f\\ c h i l d r e n)$ for each affected node and this number could be as large as $N$, hence it could take $O(N)$ time in total ! Binarizing the Input Tree To overcome the issue, we convert the given tree $T$ into an equivalent binary tree $T'$ by adding extra dummy nodes such that degree of each node in the transformed tree $T'$ is $< = 3$, and the number of dummy nodes added is bounded by $O(N)$. The dummy nodes are added such that the structure of the tree is preserved and weights of the edges added are set to $0$. To do this, consider a node $x$ with degree $d > 3$ and let $c_{1}, c_{2}...c_{d}$ be it's adjacent nodes. Add a new node $y$ and change the edges as follows : Delete the edges $(x - c_{3})$, $(x - c_{4})$ $...$ $(x - c_{d})$ and add the edge $(x - y)$ such that degree of node $x$ reduces to $3$ from $d$. Add edges $(y - c_{3})$, $(y - c_{4})$ $...$ $(y - c_{d})$ such that degree of node $y$ is $d - 1$. Recursively call the procedure on node $y$. Delete the edges $(x - c_{3})$, $(x - c_{4})$ $...$ $(x - c_{d})$ and add the edge $(x - y)$ such that degree of node $x$ reduces to $3$ from $d$. Add edges $(y - c_{3})$, $(y - c_{4})$ $...$ $(y - c_{d})$ such that degree of node $y$ is $d - 1$. Recursively call the procedure on node $y$. Since degree of node $y$ is $d - 1$ instead of original degree $d$ of node $x$, it can be proved that we need to add at most $O(N)$ new nodes before degree of each node in the tree is $< = 3$. Conclusion Hence we perform centroid decomposition of this transformed tree $T'$. The centroid tree formed would have the following properties. The height of the centroid tree is $O(l o g N)$ Each node in the centroid tree has $ \\le  3$ children. Now we can easily make this tree persistent by path-copying approach. To handle the updates, Way-1 : Observe that swapping $A[i]$ and $A[i + 1]$ would affect only the $i'th$ persistent centroid tree, which can be rebuilt from the tree of $i - 1$ by a single update query. In this approach, for each update we add $O(l o g N)$ new nodes. See author's code below for more details. Way-2 : First we go down to the lca of $A[x]$ and $A[x + 1]$ in the $x$'th persistent tree, updating the values as we go. Now, let $c_{l}$ be the child of lca which is an ancestor of $A[x]$, and let $c_{r}$ be the child which is an ancestor of $A[x + 1]$. Now, we replace $c_{r}$ of $x$'th persistent tree with $c_{r}$ of $(x + 1)$'th persistent tree. Similarly, we replace $c_{l}$ of $x + 1$'th persistent tree with $c_{l}$ of $x$'th persistent tree. So now $A[x + 1]$ is active in $x$'th persistent tree and both $A[x]$ and $A[x + 1]$ are active in $(x + 1)$'th persistent tree.To deactivate $A[x]$ in $x$'th persistent tree we replace $c_{l}$ of $x$'th persistent tree with $c_{l}$ of $(x - 1)$'th persistent tree. Hence in this approach we do not need to create new $O(l o g N)$ nodes for each update.",
    "code": "//Toshad Salwekar\n#include<bits/stdc++.h>\n#define f(i,a,n) for(int i=a;i<n;i++)\n#define S second\n#define F first\n#define Sc(n) scanf(\"%lld\",&n)\n#define scc(a,b,c) scanf(\"%lld %lld %lld\",&a,&b,&c)\n#define sp(a) scanf(\"%lld %lld\",&a.first,&a.second)\n#define pb push_back\n#define mp make_pair\n#define lb lower_bound\n#define ub upper_bound\n#define all(a) a.begin(),a.end()\n#define sc(n) scanf(\"%d\",&n)\n#define It iterator\n#define SET(a,b) memset(a,b,sizeof(a))\n#define DRT()  int t; cin>>t; while(t--)\n// inbuilt functions\n// __gcd,  __builtin_ffs,     (returns least significant 1-bit, __builtin_ffsll(1)=1)\n// __builtin_clz,             (returns number of leading zeroes in \n// __builtin_popcount,\nusing namespace std;\ntypedef long long LL;\ntypedef pair<int,LL> PII;\ntypedef vector<int> vi;\n#define tr(container, it) for(__typeof(container.begin()) it = container.begin(); it != container.end(); it++)\n#define trv(s,it) for(auto it:s)\n#define TRACE\n\n#ifdef TRACE\n#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)\ntemplate <typename Arg1>\nvoid __f(const char* name, Arg1&& arg1){\n\tcerr << name << \" : \" << arg1 << std::endl;\n}\ntemplate <typename Arg1, typename... Args>\nvoid __f(const char* names, Arg1&& arg1, Args&&... args){\n\tconst char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << \" : \" << arg1<<\" | \";__f(comma+1, args...);\n}\n#else\n#define trace(...)\n#endif\n#define N 400005\n#define LOGN 20\nconst int MAX = N*LOGN;\nconst int MOD = (1<<30);\nint cn[N],nn,par[N],arr[N],centroid,C,tot,anc[N];\nLL dis[LOGN][N];\nvector<PII> tree[N];\nbool mark[N];\tstack<int> st;\nstruct node\n{\tint id,cn,len; LL sum,psum;\n\tnode* child[4];\n}*pers[N];\nnode BUFF[MAX];\nint buf_len;\nint dfs1(int i,int p)\n{\tint r=1,mx=0,t;\n\tfor(auto it:tree[i])\n\t\tif(it.F!=p && !mark[it.F])\n\t\t\tr+=dfs1(it.F,i);\n\tcn[i]=r;\n\treturn r;\n}\nint dfs2(int i,int p,int num)\n{\tfor(auto it:tree[i])\n\t\tif(cn[it.F]>num/2 && !mark[it.F] && it.F!=p)\n\t\t\treturn dfs2(it.F,i,num);\n\treturn i;\n}\nvoid dfs(int i,int p,LL d)\n{\tfor(auto it:tree[i])\n\t\tif(it.F!=p && !mark[it.F])\n\t\t\tdfs(it.F,i,d+it.S);\n\tdis[C][i]=d;\n}\nvoid dec(int root, node* p,int c)\n{\tdfs1(root,root);\n\tint cen=dfs2(root,root,cn[root]);\t\t//cen is centroid of current subtree\n\tC=c;\n\tdfs(cen,cen,0LL);\n\tmark[cen]=1;\n\tnode* tmp= BUFF + buf_len++;\n\ttmp->id=cen;\n\ttmp->cn=0;   tmp->len=0;\n\ttmp->sum=0;\t\t\n\tif(p!=NULL)\n\t{\tp->child[p->len++]=tmp;\n\t\tpar[cen]=p->id;\n\t}\n\telse\n\t{\tpers[0]=tmp;\t\t\t\t//This means cen is the centroid\n\t\tcentroid=cen;\n\t}\n\tfor(auto it:tree[cen])\n\t\tif(!mark[it.F])\n\t\t\tdec(it.F,tmp,c+1);\n}\nnode* persist(node* root, int i,int l)\n{\t\n\tnode* tmp= BUFF + buf_len++;\n\ttmp->id=root->id;\n\ttmp->sum=root->sum + dis[l][i];\n\tif(l)\n\t\ttmp->psum=root->psum + dis[l-1][i];\n\ttmp->cn=root->cn + 1;\n\ttmp->len=0;\n\tf(j,0,root->len)\n\t\tif(!st.empty() && (root->child[j])->id==st.top())\n\t\t{\tst.pop();\n\t\t\ttmp->child[tmp->len++]=persist(root->child[j],i,l+1);\n\t\t}\n\t\telse\n\t\t\ttmp->child[tmp->len++]=root->child[j];\n\treturn tmp;\n}\nLL query(node* root, int i,int l)\n{\tLL ans=0;\n\tans+=(root->cn)*dis[l][i]+root->sum;\t\t\t\t\t// Add all nodes in range which are in subtree(in centroid tree) of current node\n\tf(j,0,root->len)\n\t\tif(!st.empty() && root->child[j]->id==st.top())\n\t\t{\tst.pop();\n\t\t\tans-=(root->child[j]->psum)+(root->child[j]->cn)*dis[l][i];\t\t\t//Subtract all nodes which will be considered in the child(i.e., they are\n\t\t\tans+=query(root->child[j],i,l+1);\t\t\t\t\t\t\t// in same subtree as the query node).\n\t\t}\n\treturn ans;\n}\nvoid binarise(unordered_map<int,LL> &add,int i,PII p,bool fl)\n{     unordered_map<int,LL> tmp;\n\tmark[i]=1;\n\tif(fl)\t\t\t\t\t\t\t\t\t// fl=1 for those nodes which were not in original tree\n\t{     add.erase(p.F);\n\t\ttree[i].pb(p);\n\t\ttree[i].pb(*(add.begin()));\n\t\tadd.erase(add.begin());\n\t\tif(add.size()>1)\t\t\t\t\t\t\t// Need to create more nodes\n\t\t{     tree[i].pb(mp(tot++,0LL));\n\t\t\tbinarise(add,tot-1,mp(i,0LL),1);\n\t\t}\n\t\telse\t\t\t\t\n\t\t{     tree[i].pb(*(add.begin()));\n\t\t\tbinarise(tmp,tree[i][2].F,mp(i,tree[i][2].S),0);\n\t\t}\n\t\tbinarise(tmp,tree[i][1].F,mp(i,tree[i][1].S),0);\n\t}\n\telse if(tree[i].size()>3)\n\t{     int t=0;bool fl=0;\n\t\tif(tree[i][t].F==p.F)\n\t\t\tt++;\n\t\tf(j,t,tree[i].size())\n\t\t\tif(mark[tree[i][j].F] && tree[i].size()==4)\t\t\t\t// This means that tree[i][j].F is the parent in original tree\n\t\t\t\tfl=1;\n\t\tif(fl)\t\t\t\t\t\t\t\t\t\t\t// Only has \n\t\t{\tf(j,0,tree[i].size())\n\t\t\t\tif(tree[i][j]!=p && !mark[tree[i][j].F])\n\t\t\t\t\tbinarise(tmp,tree[i][j].F,mp(i,tree[i][j].S),0);\n\t\t\t\telse if(mark[tree[i][j].F])\n\t\t\t\t\ttree[i][j]=p;\n\t\t\treturn;\n\t\t}\n\t\t\tif(mark[tree[i][t].F])\n\t\t\t\tt++;\n\t\t\tbinarise(tmp,tree[i][t].F,mp(i,tree[i][t].S),0);\t\t\t\t//t represents the child which will stay the child of this node.\n\t\t\tf(j,0,tree[i].size())\n\t\t\t\tif(j==t);\n\t\t\t\telse if(!mark[tree[i][j].F]\t&& tree[i][j].F!=p.F)\n\t\t\t\t\ttmp.insert(tree[i][j]);\n\t\t\t\telse if(mark[tree[i][j].F])\t\t\t\t\t\t\t//Replace original parent with new parent\n\t\t\t\t\ttree[i][j]=p;\n\t\t\tPII tm=tree[i][t];\n\t\t\ttree[i].clear();\n\t\t\tif(i!=1)\t\t\t\t\t\t\t\t\t\t\t// 1 is root. For all others, add parent.\n\t\t\t\ttree[i].pb(p);  \n\t\t\ttree[i].pb(tm);\t\t\t\t \n\t\t\ttree[i].pb(mp(tot++,0LL));\t\t\t\t\t\t\t\t// Add new extra node\n\t\t\tbinarise(tmp,tot-1,mp(i,0LL),1);\n\t}\n\telse\n\t\tf(j,0,tree[i].size())\n\t\t\tif(tree[i][j]!=p && !mark[tree[i][j].F])\n\t\t\t\tbinarise(tmp,tree[i][j].F,mp(i,tree[i][j].S),0);\n\t\t\telse if(mark[tree[i][j].F])\t\t\t\t\t\t\t//Replace original with new parent\n\t\t\t\ttree[i][j]=p;\n}\n\nint main()\n{\n\tint n,q; LL a,b,c;\n\tcin>>n>>q;\n\ttot=n+1;\n\tf(i,1,n+1)\n\t\tsc(arr[i]);\n\tf(i,1,n)\n\t{\tscc(a,b,c);\n\t\ttree[a].pb(mp(b,c));\n\t\ttree[b].pb(mp(a,c));\n\t}\n\tunordered_map<int,LL> stmp;\n\tbinarise(stmp,1,mp(0,0LL),0);\n\tSET(mark,0);\n\tdec(1,NULL,0);\n\tf(i,1,n+1)\n\t{\n\t\tint p=arr[i];\n\t\twhile(p!=centroid)\t\t\t\t\t//push all nodes to be added in a stack\n\t\t{\tst.push(p);\t\n\t\t\tp=par[p];\n\t\t}\n\t\tpers[i]=persist(pers[i-1],arr[i],0);\n\t}\n\tLL an = 0;\n\tf(i,1,q+1)\n\t{\tSc(a);\n\t\tSc(b);\n\t\tif(a==1)\n\t\t{\tSc(c); Sc(a);\n\t\t  b = b ^ an; c = c ^ an; a = a ^ an;\n\t\t\tint p=a;\n\t\t\tan=0;\n\t\t\twhile(p!=centroid)\t\t\t\t//push all nodes to be queried in a stack\n\t\t\t{\tst.push(p);\n\t\t\t\tp=par[p];\n\t\t\t}\n\t\t\tan-=query(pers[b-1],a,0);\n\t\t\tp=a;\n\t\t\twhile(p!=centroid)\t\t\t\t//push all nodes to be queried in a stack\n\t\t\t{\tst.push(p);\n\t\t\t\tp=par[p];\n\t\t\t}\n\t\t\tan+=query(pers[c],a,0);\n\t\t\tprintf(\"%lld\\n\",an);\n\t\t\tan %= MOD;\n\t\t}\n\t\telse \n\t\t{   b = b ^ an;\n\t\t    int p=arr[b],lca=centroid,h=centroid;\n\t\t\twhile(p!=centroid)\n\t\t\t{     anc[p]=i;\t\t\t\t\t\t\t\t//mark all ancestors of arr[b]\n\t\t\t\tp=par[p];\n\t\t\t}\n\t\t\tp=arr[b+1];\n\t\t\twhile(p!=centroid)\n\t\t\t{     if(anc[p]==i)\n\t\t\t\t{     lca=p; break; }\n\t\t\t\th=p;\t\t\t\t\t\t\t\t\t// h is the highest ancestor of arr[b+1] which is not an ancestor of arr[b]\n\t\t\t\tp=par[p];\n\t\t\t}\n\t\t\tnode *rt1=pers[b], *rt2=pers[b+1], *rt=pers[b-1];\n\t\t\tint l=0,k=-1;\n\t\t\twhile(rt->id!=lca)\t\t\t\t\t\t\t//traverse down to lca in all 3 centroid trees.\n\t\t\t{     rt1->sum -= dis[l][arr[b]] - dis[l][arr[b+1]];\n\t\t\t\tif(l) \n\t\t\t\t\trt1->psum -= dis[l-1][arr[b]] - dis[l-1][arr[b+1]];\t\t\n\t\t\t\tl++;\n\t\t\t\tf(j,0,rt1->len)\n\t\t\t\t\tif(anc[rt1->child[j]->id]==i)\n\t\t\t\t\t{     rt1=rt1->child[j];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tf(j,0,rt2->len)\n\t\t\t\t\tif(anc[rt2->child[j]->id]==i)\n\t\t\t\t\t{     rt2=rt2->child[j];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tf(j,0,rt->len)\n\t\t\t\t\tif(anc[rt->child[j]->id]==i)\n\t\t\t\t\t{     rt=rt->child[j];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t\trt1->sum-=dis[l][arr[b]]-dis[l][arr[b+1]];\t\t\t//update lca too\n\t\t\tif(l) \n\t\t\t\trt1->psum-=dis[l-1][arr[b]]-dis[l-1][arr[b+1]];\n\n/*\t This is the swapping part. \n *\t b1child represents the child containing arr[b], \n *\t b2child represents the child containing arr[b+1] and \n *\t bchild represents the child containing arr[b] in persistent centroid tree of first b-1 elements\n *\t The difference between b1child and bchild is that in b1child the ans due to arr[b] is considered, but it is not so in bchild. \n *\t Now we replace b1child with bchild and add b2child in pers[b], so that in pers[b], arr[b+1] is now active and not arr[b].\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*/\n\t\t\tnode *b1child=NULL,*b2child=NULL,*bchild=NULL;\n\t\t\tf(j,0,rt->len)\t\t\t\t\t\t\t//find bchild It may not exist if arr[b] = lca\n\t\t\t\tif(anc[rt->child[j]->id]==i)\n\t\t\t\t\tbchild=rt->child[j];\n\t\t\tf(j,0,rt1->len)\n\t\t\t\tif(anc[rt1->child[j]->id]==i)\t\t\t\t//find b1child. It may not exist if arr[b] = lca\n\t\t\t\t{     b1child=rt1->child[j]; k=j; }\n\t\t\tint vv=0;\n\t\t\tif(b1child!=NULL)\t\t\t\t\t\t\t// vv is used to handle the case where b1child = NULL\n\t\t\t\tvv=b1child->id;\n\t\t\tf(j,0,rt2->len)\n\t\t\t\tif(rt2->child[j]->id==h)\t\t\t\t//find b2child. It may not exist if arr[b+1] = lca\n\t\t\t\t\tb2child=rt2->child[j];\n\t\t\t\telse if(rt2->child[j]->id==vv)\t\t\t\n\t\t\t\t\trt2->child[j]=b1child;\n\t\t\tif(k>=0)\t\t\t\t\t\t\t\t//Again, check if b1child exists.\n\t\t\t\trt1->child[k]=bchild;\n\t\t\tf(j,0,rt1->len)\n\t\t\t\tif(rt1->child[j]->id==h)\n\t\t\t\t\trt1->child[j]=b2child;\n\t\t\tswap(arr[b],arr[b+1]);\n\t\t}\n\n\t}\n}\n",
    "tags": [
      "data structures",
      "divide and conquer",
      "graphs",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "758",
    "index": "A",
    "title": "Holiday Of Equality",
    "statement": "In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.\n\nTotally in Berland there are $n$ citizens, the welfare of each of them is estimated as the integer in $a_{i}$ burles (burle is the currency in Berland).\n\nYou are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.",
    "tutorial": "As it's impossible to decrease numbers, we have to increase them to at least $max(a_{1}, a_{2}, ..., a_{n})$. If all the numbers are already equal to $max(a_{1}, a_{2}, ..., a_{n})$ then there is no need to increase any of them as it will cost extra operations. So you should find $max(a_{1}, a_{2}, ..., a_{n})$ using one iteration over the array. Then iterate one more time summing up differences between $a_{i}$ and maximum. And the answer is $\\textstyle\\sum_{i=1}^{n}m a x-a_{i}$. Overall complexity - $O(n)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "758",
    "index": "B",
    "title": "Blown Garland",
    "statement": "Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland.\n\nNow he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working.\n\nIt is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like \"RYBGRYBGRY\", \"YBGRYBGRYBG\", \"BGRYB\", but can not look like \"BGRYG\", \"YBGRYBYGR\" or \"BGYBGY\". Letters denote colors: 'R' — red, 'B' — blue, 'Y' — yellow, 'G' — green.\n\nUsing the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.",
    "tutorial": "Four consecutive bulbs should not be of the same color, and it is four possible colors, so the color of the fifth bulb is the same as the first bulb has, the color of the sixth is the same as the second bulb has, it means that the color of the $n$-th bulb equals the color of the $(n - 4)$-th bulb. Thus, the coordinates of all bulbs of the same color equal in module $4$. According to the conditions of the problem the coordinate of at least one light bulb of each color is given, so we can restore the garland and by one pass count the number of blown bulbs. By one pass we learn how numbers in module $4$ correspond to the colors. By the second pass we know the place of the bulb and count the number of blown bulbs of each color. The asymptotic behavior of the solutions is - O(n). There is also a second solution: You can just fix order of first four light bulbs by bruteforce (there is only $4! = 24$ variants), checking the conformity of each option of the given garland. By finding the color of the first four bulbs we easily recreate the garland with working lights and count the number of blown bulbs. At worst this decision will work for $24 \\cdot n$.",
    "tags": [
      "brute force",
      "implementation",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "758",
    "index": "C",
    "title": "Unfair Poll",
    "statement": "On the Literature lesson Sergei noticed an awful injustice, it seems that some students are asked more often than others.\n\nSeating in the class looks like a rectangle, where $n$ rows with $m$ pupils in each.\n\nThe teacher asks pupils in the following order: at first, she asks all pupils from the first row in the order of their seating, then she continues to ask pupils from the next row. If the teacher asked the last row, then the direction of the poll changes, it means that she asks the previous row. The order of asking the rows looks as follows: the $1$-st row, the $2$-nd row, $...$, the $n - 1$-st row, the $n$-th row, the $n - 1$-st row, $...$, the $2$-nd row, the $1$-st row, the $2$-nd row, $...$\n\nThe order of asking of pupils on the same row is always the same: the $1$-st pupil, the $2$-nd pupil, $...$, the $m$-th pupil.\n\nDuring the lesson the teacher managed to ask exactly $k$ questions from pupils in order described above. Sergei seats on the $x$-th row, on the $y$-th place in the row. Sergei decided to prove to the teacher that pupils are asked irregularly, help him count three values:\n\n- the maximum number of questions a particular pupil is asked,\n- the minimum number of questions a particular pupil is asked,\n- how many times the teacher asked Sergei.\n\nIf there is only one row in the class, then the teacher always asks children from this row.",
    "tutorial": "Let's learn to count $f(x, y)$ - the number of questions which were asked to the pupil in the $x$-th row, at the $y$-th place in the order. Note that the process of asking is periodic. During one period children were asked in the following order: the pupil from the first row who seats at the first table; the pupil from the first row who seats at the second table; the pupil from the first row who seats at the $...$ table; the pupil from the first row who seats at the $m$ table; the pupil from the second row who seats at the first table; the pupil from the second row who seats at the second table; the pupil from the second row who seats at the $...$ table; the pupil from the second row who seats at the $m$ table; the pupil from the $...$ row who seats at the $...$ table; the pupil from the $n - 1$ row who seats at the first table; the pupil from $n - 1$ row who seats at the second table; the pupil from the $n - 1$ row who seats at the $...$ table; the pupil from the $n - 1$ row who seats at the $m$ table; the pupil from the $n$ row who seats at the first table; the pupil from the $n$ row who seats at the second table; the pupil from the $n$ row who seats at the $...$ table; the pupil from the $n$ row who seats at the $m$ table; the pupil from the $n - 1$ row who seats at the first table; the pupil from the $n - 1$ row who seats at the second table; the pupil from the $n - 1$ row who seats at the $...$ table; the pupil from the $n - 1$ row who seats at the $m$ table; the pupil from the $...$ row who seats at the $...$ table; the pupil from the second row who seats at the first table; the pupil from the second row who seats at the second table; the pupil from the second row who seats at the $...$ table; the pupil from the second row who seats at the $m$ table. Thus, during one period $T = n \\cdot m + (n - 2) \\cdot m$ pupils who seats at the outer rows will be asked once, others will be asked twice. If $n = 1$, then $T = m$. The number of full periods equals $\\left\\lfloor{\\frac{k}{T}}\\right\\rfloor$. The remaining questions are $k$ $mod$ $T$ $ \\le  T$, so we can only make poll on the remaining questions for the $O(n \\cdot m)$ or for individual $x$ and $y$ print the formula. Thus, $f(x, y)$ can be seen as $O(n \\cdot m)$ or as $O(1)$. On what places are people who may be asked more times than the other? Firstly, this is the first row and the first table, because the poll begins from it. Secondly, this is the second row and the first table, because the poll of the central, not outer part of a class at the right side, begins from it. Thirdly, the $n - 1$ row and the first place because the poll of the central, not outer part of a class at the left side, begins from it. The maximum number of asked questions to one pupil equals $max(f(1, 1), f(2, 1), f(n - 1, 1))$. The minimum number of asked questions to one pupil equals $f(n, m)$, because the pupil who seats on the last row and at the last table will be asked less than others. Thus, we have decisions with the asymptotic $O(n \\cdot m)$ or $O(1)$.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "758",
    "index": "D",
    "title": "Ability To Convert",
    "statement": "Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter $A$ he will write the number $10$. Thus, by converting the number $475$ from decimal to hexadecimal system, he gets $11311$ ($475 = 1·16^{2} + 13·16^{1} + 11·16^{0}$). Alexander lived calmly until he tried to convert the number back to the decimal number system.\n\nAlexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base $n$ he will get the number $k$.",
    "tutorial": "Let's compare answers for numbers $k$ and $\\left|{\\frac{k}{10}}\\right|$, that is $k$ without the rightmost digit. Note that for any $x$ number $\\textstyle{\\left|{\\frac{x}{10}}\\right|}$ is either contains less substrings (valid digits in base-$n$ numeric system) or it's possible to decrease value of the last substring of number $x$. That proves that partition of number without the rightmost digit isn't worse than partition of the number itself. Thus, greedy strategy will work. On each step take the longest suffix of a string as the last base-$n$ digit and proceed to same task for string with this suffix excluded. Repeat until the string isn't empty. Check carefully that the suffix is a number less than $n$ and also doesn't have any leading zeros except for the case when it's equal to zero. Overall complexity - $O(k)$, where $k$ - length of input string.",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "758",
    "index": "E",
    "title": "Broken Tree",
    "statement": "You are given a tree that has $n$ vertices, which are numbered from $1$ to $n$, where the vertex number one is the root. Each edge has weight $w_{i}$ and strength $p_{i}$.\n\nBotanist Innokentiy, who is the only member of the jury of the Olympiad in Informatics, doesn't like broken trees.\n\nThe tree is broken if there is such an edge the strength of which is less than the sum of weight of subtree's edges to which it leads.\n\nIt is allowed to reduce weight of any edge by arbitrary integer value, but then the strength of its edge is reduced by the same value. It means if the weight of the edge is $10$, and the strength is $12$, then by the reducing the weight by $7$ its weight will equal $3$, and the strength will equal $5$.\n\nIt is not allowed to increase the weight of the edge.\n\nYour task is to get the tree, which is not broken, by reducing the weight of edges of the given tree, and also all edged should have the positive weight, moreover, the total weight of all edges should be as large as possible.\n\nIt is obvious that the strength of edges can not be negative, however it can equal zero if the weight of the subtree equals zero.",
    "tutorial": "First, let's calculate min and max weight for subtrees of each vertex. Minimal weight of a subtree is sum of minimal weights of all adjacent to the root of current subtree subtrees and sum of weights of all outgoing edges reduced in weight to minimal possible. Thus, minimal weight is $d p m i n_{x}=\\sum_{i=1}^{n_{x}}d p m i n_{y_{x,i}}+w_{x,i}-m i n(p_{x,i}-d p m i n_{y_{x,i}},w_{x,i}-1)$, where $x$ -subtree root, $n_{x}$ -number of outgoing edges from $x$, $y_{x, i}$ - each adjacent to $x$ vertex, $p_{x, i}$ - its strength, $w_{x, i}$ - its weight. Note that minimal weight should be less or equal to strength of incoming edge. If this condition isn't satisfied for at least one subtree then the answer is $- 1$. Maximal weight of a subtree is sum of maximal weights of all adjacent to the root of current subtree subtrees and sum of weights of all outgoing edges. Note that this maximum should stay in such boundaries that the tree remains unbroken. So maximal weight should not exceed strength of incoming edge of a root. Therefore, maximum is $d p m a x_{x}=m i n(p_{z,j},\\sum_{i=1}^{n_{x}}d p m a x_{y_{x,i}}+w_{x,i})$, where $x$ -subtree root, $p_{z, i}$ - weight of an incoming edge of $x$, that is $j$-th edge outgoing from some vertex $z$, $n_{x}$ -number of outgoing edges from $x$, $y_{x, i}$ - each adjacent to $x$ vertex, $w_{x, i}$ - its weight. After that, let's calculate current weight of every subtree to find difference between actual value and the optimal one. Weight of subtree is sum of weights of all adjacent to the root of current subtree subtrees and sum of weights of all outgoing edges. Then actual weight is $d p W_{x}=\\sum_{i=1}^{n_{x}}d p W_{y_{x,i}}+w_{x,i}$, where $x$ -subtree root, $n_{x}$ -number of outgoing edges from $x$, $y_{x, i}$ - each adjacent to $x$ vertex, $w_{x, i}$ - its weight. One dfs from the root of the tree is enough to calculate all these values. Note that $dpmin$, $dpmax$ and $dpW$ are set to $0$ for leaves . $dpmax_{x}$ is maximal possible weight of each subtree, so weight of the whole tree can be reduced to $dpmax_{1}$, it means that weight of subtree of vertex $1$ should be reduced by $dpW_{1} - dpmax_{1}$. Next goal is to learn how to reduce weight of subtree of vertex $x$ by $s$ units. At first, you should reduce weights of subtrees of adjacent to $x$ vertices to their maximum. So after this step $s=s-\\sum_{i=1}^{n_{x}}d p W_{y_{x,i}}-d p m a x_{y_{x,i}}$. Then while $s > 0$, reduce weight of each next subtree. If it's still $s > 0$ then reduce weights of outgoing edges from $x$ maintaining unbroken state of tree. This process also takes one dfs. Overall complexity is the complexity of two dfs calls, that is $O(n)$.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "758",
    "index": "F",
    "title": "Geometrical Progression",
    "statement": "For given $n$, $l$ and $r$ find the number of distinct geometrical progression, each of which contains $n$ distinct integers not less than $l$ and not greater than $r$. In other words, for each progression the following must hold: $l ≤ a_{i} ≤ r$ and $a_{i} ≠ a_{j}$ , where $a_{1}, a_{2}, ..., a_{n}$ is the geometrical progression, $1 ≤ i, j ≤ n$ and $i ≠ j$.\n\nGeometrical progression is a sequence of numbers $a_{1}, a_{2}, ..., a_{n}$ where each term after first is found by multiplying the previous one by a fixed non-zero number $d$ called the common ratio. Note that in our task $d$ may be non-integer. For example in progression $4, 6, 9$, common ratio is $d={\\frac{3}{2}}$.\n\nTwo progressions $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{n}$ are considered different, if there is such $i$ ($1 ≤ i ≤ n$) that $a_{i} ≠ b_{i}$.",
    "tutorial": "Let $d$ - is the denominator of the progression. $d$ - is the rational number, because all numbers of progression are integers. $d={\\frac{\\pi}{y}}$,where $x, y$ - are integers, $gcd(x, y) = 1$. Then $a_{n}=a_{1}\\cdot{\\frac{x^{n-1}}{v^{n-1}}}$. Because all numbers of progression are integers, so $a_{1}\\colon y^{n-1}$. Let $b={\\frac{a_{1}}{y^{n-1}}}$, then $a_{1} = b \\cdot y^{n - 1}$ and $a_{n} = b \\cdot x^{n - 1}$. According to the condition of the problem it must be done: $l  \\le  b \\cdot y^{n - 1}  \\le  r$ and $l  \\le  b \\cdot x^{n - 1}  \\le  r$. Count the number of increasing progressions, it means $d > 1$ ($y < x$). Note that there are decreasing progressions as much as increasing, any decreasing progression - is increasing, but written from right to left. If $y < x$, then $l  \\le  b \\cdot y^{n - 1} < b \\cdot x^{n - 1}  \\le  r$. Then for certain $x$ and $y$ the number of possible integers $b$ is calculated by the formula $\\frac{r}{x^{n-1}}\\to\\frac{l}{y^{n-1}}$. Let's sort $y$ from $1$ to $n{\\overset{n-{\\sqrt{r}}}{\\sqrt{r}}}$, $x$ from $y + 1$ to $n{\\overset{n-{\\sqrt{r}}}{\\sqrt{r}}}$. Before you add the number of options for the next $x$ and $y$ you need to check that $gcd(x, y) = 1$. Better to count $gcd(x, y)$ using Euclidean algorithm for $O(\\log^{3}n)$. Remember that we counted only increasing progressions, the answer would be higher twice. Note that when $n = 1$ this algorithm is meaningless, so it is necessary to separately register the answer, for $n = 1$ it equals $r - l + 1$, it means that you choose one element from $l$ to $r$. Also for $n = 2$ it is necessary to print the formula, any pair of integers is the geometrical progression, so for $n = 2$ the answer equals $(r - l + 1) \\cdot (r - l)$, the first integer can be chosen by using $r - l + 1$ ways, the second which is not equal to the first by using $r - l$ ways. Possible asymptotic behavior: $O({\\bf\\Phi}^{n-{\\sqrt{r}}^{2}}\\cdot(n+\\log^{3}n))$; $O({\\bf\\Phi}^{n-{\\sqrt{T}}^{2}}\\cdot(\\log n+\\log^{3}n))$ - when we make the binary transfer to the degree; $O(n\\cdot\\ ^{n-1}{\\sqrt{r}}+\\ \"^{n-{\\sqrt{r^{2}}}\\cdot\\log^{3}n)$ - with preliminary count; $O(\\log n\\cdot\\,^{n-1/r}+\\ ^{n-1/r^{2}}\\cdot109^{3}\\,n)$ - with binary preliminary count.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "760",
    "index": "A",
    "title": "Petr and a calendar",
    "statement": "Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture:\n\nPetr wants to know how many columns his table should have given the month and the weekday of the first date of that month? Assume that the year is non-leap.",
    "tutorial": "Just implement writing dates one by one and keeping current column and row, or use the formula $answer = ((d - 1) + ndays - 1) / 7 + 1$, where $ndays$ is the number of days in the month.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "760",
    "index": "B",
    "title": "Frodo and pillows",
    "statement": "$n$ hobbits are planning to spend the night at Frodo's house. Frodo has $n$ beds standing in a row and $m$ pillows ($n ≤ m$). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have.\n\nFrodo will sleep on the $k$-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?",
    "tutorial": "Let's do binary search on the answer. How to check if Frodo can have $x$ pillows or more? We need to calculate the least amount of pillows we need to give to all the hobbits and compare it to m. The number of pillows is minimized if we give $x - 1$ pillows to Frodo's neighbors, $x - 2$ pillows to the hobbits at the distance $2$ from Frodo and so on, until we reach $1$ pillow or until we reach an end of beds row. The total amount of pillows on one side of Frodo can be calculated using a formula. Suppose there are $y$ beds on one side of Frodo. There are two cases: if $y > x - 1$, then the total number of pillows is ${\\frac{(x-1)x}{2}}+y-(x-1)$, otherwise the total number of pillows is $\\textstyle{\\frac{(x-1+x-y)y}{2}}$.",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "761",
    "index": "A",
    "title": "Dasha and Stairs",
    "statement": "On her way to programming school tiger Dasha faced her first test — a huge staircase!\n\nThe steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers.\n\nYou need to check whether there is an interval of steps from the $l$-th to the $r$-th $(1 ≤ l ≤ r)$, for which values that Dasha has found are correct.",
    "tutorial": "It's obvious, that if $|a - b| > 1$ - the answer is <<NO>>. <<NO>> answer was also in the case, when $a$ and $b$ are equal to $0$, because according to the statement, such interval should exist. In other cases the answer is <<YES>>. Complexity: $O(1)$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "761",
    "index": "B",
    "title": "Dasha and friends",
    "statement": "Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation:\n\nThe track is the circle with length $L$, in distinct points of which there are $n$ barriers. Athlete always run the track in counterclockwise direction if you look on him from above. All barriers are located at integer distance from each other along the track.\n\nHer friends the parrot Kefa and the leopard Sasha participated in competitions and each of them ran one lap. Each of the friends started from some integral point on the track. Both friends wrote the distance from their start along the track to each of the $n$ barriers. Thus, each of them wrote $n$ integers in the ascending order, each of them was between $0$ and $L - 1$, inclusively.\n\n\\begin{center}\n{\\small Consider an example. Let $L = 8$, blue points are barriers, and green points are Kefa's start (A) and Sasha's start (B). Then Kefa writes down the sequence $[2, 4, 6]$, and Sasha writes down $[1, 5, 7]$.}\n\\end{center}\n\nThere are several tracks in the country, all of them have same length and same number of barriers, but the positions of the barriers can differ among different tracks. Now Dasha is interested if it is possible that Kefa and Sasha ran the same track or they participated on different tracks.\n\nWrite the program which will check that Kefa's and Sasha's tracks coincide (it means that one can be obtained from the other by changing the start position). Note that they always run the track in one direction — counterclockwise, if you look on a track from above.",
    "tutorial": "Let's add distances between pairs of adjacent barriers of both tracks in arrays and check if it possible to get one of them from another using cycling shift of the elements. Complexity: $O(n^{2})$.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "761",
    "index": "C",
    "title": "Dasha and Password",
    "statement": "After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length $n$ which satisfies the following requirements:\n\n- There is at least one digit in the string,\n- There is at least one lowercase (small) letter of the Latin alphabet in the string,\n- There is at least one of three listed symbols in the string: '#', '*', '&'.\n\nConsidering that these are programming classes it is not easy to write the password.\n\nFor each character of the password we have a fixed string of length $m$, on each of these $n$ strings there is a pointer on some character. The $i$-th character displayed on the screen is the pointed character in the $i$-th string. Initially, all pointers are on characters with indexes $1$ in the corresponding strings (all positions are numbered starting from one).\n\nDuring one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index $1$ to the left, it moves to the character with the index $m$, and when we move it to the right from the position $m$ it moves to the position $1$.\n\nYou need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.",
    "tutorial": "Let's iterate the string, where we want to get a digit to the password, then the string, where we'll get a letter to the password and the string, where we'll get one of the characters '&', '*', '#'. Obviously, in the other strings we can pick any character, so we only need to compute minimal number of moves we have to do to get corresponding characters in fixed strings. We can do it just by iterating that strings. Complexity: $O(n^{3} * m)$.",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "761",
    "index": "D",
    "title": "Dasha and Very Difficult Problem",
    "statement": "Dasha logged into the system and began to solve problems. One of them is as follows:\n\nGiven two sequences $a$ and $b$ of length $n$ each you need to write a sequence $c$ of length $n$, the $i$-th element of which is calculated as follows: $c_{i} = b_{i} - a_{i}$.\n\nAbout sequences $a$ and $b$ we know that their elements are in the range from $l$ to $r$. More formally, elements satisfy the following conditions: $l ≤ a_{i} ≤ r$ and $l ≤ b_{i} ≤ r$. About sequence $c$ we know that all its elements are distinct.\n\nDasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence $a$ and the compressed sequence of the sequence $c$ were known from that test.\n\nLet's give the definition to a compressed sequence. A compressed sequence of sequence $c$ of length $n$ is a sequence $p$ of length $n$, so that $p_{i}$ equals to the number of integers which are less than or equal to $c_{i}$ in the sequence $c$. For example, for the sequence $c = [250, 200, 300, 100, 50]$ the compressed sequence will be $p = [4, 3, 5, 2, 1]$. Pay attention that in $c$ all integers are distinct. Consequently, the compressed sequence contains all integers from $1$ to $n$ inclusively.\n\nHelp Dasha to find any sequence $b$ for which the calculated compressed sequence of sequence $c$ is correct.",
    "tutorial": "Let's match each element of $a$ interval of values, which corresponding element of $c$ could take, i.e for $i$-th element interval $[l - a_{i};r - a_{i}]$. Let $pos_{i}$ be the index of element equal to $i$ in permutation $p$. Now you can know, that solving the initial task is reduced to picking a number of each interval, so that this numbers form an increasing sequence in order from $pos_{1}$ to $pos_{n}$. It is easy to know that we can pick the numbers greedily, picking a number that is greater than previous and belongs to current interval. Complexity: $O(n)$.",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "761",
    "index": "E",
    "title": "Dasha and Puzzle",
    "statement": "Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve.\n\nThe tree is a non-oriented connected graph without cycles. In particular, there always are $n - 1$ edges in a tree with $n$ vertices.\n\nThe puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points.\n\nHelp Dasha to find any suitable way to position the tree vertices on the plane.\n\nIt is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed $10^{18}$ in absolute value.",
    "tutorial": "The answer doesn't exist, when there is a vertex with degree > $4$. We'll use power of two as length of each edge in the tree. Let's dfs our tree and store in the recursion: the direction, where our parent is located (one of four possible), and the length of the edge we'll build from current vertex. Then iterate the new direction, some neighbour of the vertex and continue recursion. The edges will not intersect, except in the verteces, because $2^{0} + 2^{1} + ... + 2^{k} < 2^{k + 1}$. Comment: It's worth noting that it is possible to solve problem for greater $n$, using the fact that nothing depends on the coordinates, only ratios between X and Y coordinates seperatly, so we can compress them. Complexity: $O(n)$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "761",
    "index": "F",
    "title": "Dasha and Photos",
    "statement": "Dasha decided to have a rest after solving the problem $D$ and began to look photos from previous competitions.\n\nLet's call photos as the matrix with the size $n × m$, which consists of lowercase English letters.\n\nSome $k$ photos especially interested her, because they can be received from photo-template by painting a rectangular area in a certain color. Let's call such photos special.\n\nMore formally the $i$-th special photo is received from the photo-template by replacing all characters on some rectangle with upper left corner of the cell with coordinates $(a_{i}, b_{i})$ and lower right corner in the cell with coordinates $(c_{i}, d_{i})$ to the symbol $e_{i}$.\n\nDasha asks you to find the special photo so that the total distance from it to all other special photos is minimum. And calculate this distance.\n\nDetermine the distance between two photos as the sum of distances between all corresponding letters. The distance between two letters is the difference module of their positions in the alphabet. For example, the distance between letters 'h' and 'm' equals $|8 - 13| = 5$, because the letter 'h' is the 8-th in the alphabet, the letter 'm' is the 13-th.",
    "tutorial": "Let special photo be the matrix, made by changing subrectangle in the initial, and changed submatrix - changed subrectangle itself. Firsly, let's calculate $cnt(x, y, ch)$ - the number of special photos, in which cell (x, y) belongs to changed submatrix, such that cell (x, y) contains character $ch$. It can be done using addition on submatrix in offline. Then, using $cnt$ array, let's compute $f(x, y)$ - sum of the distances from all $k$ photos to initial, in cell (x, y): $f(x,y)=\\sum_{i=A}^{Z}|i-a(x,y)|*c n t(x,y,i)$. Let $g(x,y)=\\sum_{i=1}^{x}\\sum_{i=1}^{y}f(i,j)$ ( $g(x, y)$ - sum of the distances from all $k$ photos to initial on submatrix $(1, 1, x, y)$. Let $cnt'(x, y, ch)$ - the number of special photos, in which cell (x, y) contains character $ch$. Then calculate, similarly to $g(x, y)$, sums $q(x,y,c h)=\\sum_{i=1}^{x}\\sum_{j=1}^{y}c n t^{\\prime}(i,j,c h)$. Now, using dp's alltogether, we can count for some special photo sum of the distances to all other photos : for all cells, except changed submarix, find the distance using $g(x, y)$ and inclusion-exclusion method in $O(1)$. For the cells in changed submatrix, let's iterate the character and find the answer for it similarly. Complexity: $O(d * (N * M + K))$, where $d$ - alphabet power.",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "implementation"
    ],
    "rating": 2600
  },
  {
    "contest_id": "762",
    "index": "A",
    "title": "k-th divisor",
    "statement": "You are given two integers $n$ and $k$. Find $k$-th smallest divisor of $n$, or report that it doesn't exist.\n\nDivisor of $n$ is any such natural number, that $n$ can be divided by it without remainder.",
    "tutorial": "If you find all the small divisors of n that are less than sqrt(n), you can find the rest of them dividing n by the small ones. By the way, this problem is widely known and googlable :) You can, for example, check out this link: http://stackoverflow.com/questions/26753839/efficiently-getting-all-divisors-of-a-given-number",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "762",
    "index": "B",
    "title": "USB vs. PS/2",
    "statement": "Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!\n\nThe computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.\n\nYou have found a price list of a certain computer shop. In it, for $m$ mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.\n\nYou want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.",
    "tutorial": "Try coming up either with greedy algorithm or with two pointers algorithm. Try to prove the following greedy: in each step we can choose the cheapest remaining mouse. If there is a computer left that has only one type of port suitable for this mouse, plug it there. Else if there is a computer with both types, plug it there. Else discard this mouse. Try to also come up with the two pointers solution. If you cannot, it is described under the next spoiler. Sort all of the USB mouses and all of the PS/2 mouses so that the price is non-descending. Then you will need to buy some prefix of USB mouses and some prefix of PS/2 mouses. Iterate over the number of USB mouses from 0 to their count. Now, the more USB mouses you buy and plug into computers, the less PS/2 mouses you will be able to buy, because the number of computers will only be decreasing. So you should move the first pointer forward, and in every iteration move the second pointer backwards until you reach such amount that it is possible to plug both USB and PC/2 mouses in.",
    "tags": [
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "762",
    "index": "C",
    "title": "Two strings",
    "statement": "You are given two strings $a$ and $b$. You have to remove the minimum possible number of \\textbf{consecutive} (standing one after another) characters from string $b$ in such a way that it becomes a subsequence of string $a$. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from $b$ and make it empty.\n\nSubsequence of string $s$ is any such string that can be obtained by erasing zero or more characters (\\textbf{not necessarily consecutive}) from string $s$.",
    "tutorial": "Try thinking not about erasing a substring from B, but rather picking some number of characters (possibly zero) from the left, and some from the right. Two pointers For every prefix of B, count how big of a prefix of A you will require. Call these values p[i]. Put infinity in the cells where even whole A is not enough. Same for every suffix of B count the length of the required suffix of A. Call these values s[i]. Now try increasing the length of prefix of B, while decreasing the length of the suffix until p[pref_len] + s[suf_len] is less or equal to the length of A.",
    "tags": [
      "binary search",
      "hashing",
      "strings",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "762",
    "index": "D",
    "title": "Maximum path",
    "statement": "You are given a rectangular table $3 × n$. Each cell contains an integer. You can move from one cell to another if they share a side.\n\nFind such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.",
    "tutorial": "The toughest thing about this task, is that you can go to the left. Try to come up with something to handle that. Try to prove that in optimal solution you don't need to go more than one cell to the left before coming back.",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "762",
    "index": "E",
    "title": "Radio stations",
    "statement": "In the lattice points of the coordinate line there are $n$ radio stations, the $i$-th of which is described by three integers:\n\n- $x_{i}$ — the coordinate of the $i$-th station on the line,\n- $r_{i}$ — the broadcasting range of the $i$-th station,\n- $f_{i}$ — the broadcasting frequency of the $i$-th station.\n\nWe will say that two radio stations with numbers $i$ and $j$ reach each other, if the broadcasting range of each of them is more or equal to the distance between them. In other words $min(r_{i}, r_{j}) ≥ |x_{i} - x_{j}|$.\n\nLet's call a pair of radio stations $(i, j)$ bad if $i < j$, stations $i$ and $j$ reach each other and they are close in frequency, that is, $|f_{i} - f_{j}| ≤ k$.\n\nFind the number of bad pairs of radio stations.",
    "tutorial": "Try to come up with a solution where you iterate over each frequency Try to group stations that will be on the left side in a pair in one vector, and stations that will be on the right side in a pair into another. Iterate over each frequncy. Suppose you are now on frequency $i$. Put all radio stations with frequencly $i$ in the $left$ vector, and all radio stations with frequencies $i - k..i + k$ into the $right$ vector. Notice, that the total size of all vectors you get this way is no more than $(2 * k + 2) * n$, because every radiostation will be one time in the $left$ vector and at most $2 * k + 1$ times in the $right$ vector. Now we need to calculate the number of possible pairs where left radio station is from vector $left$ and right radio station is from vector $right$. Sort stations in the $left$ vector by position. Sort stations in the $right$ vector by left bound of their range. Iterate over the stations from the $left$ vector. Now, as you do that, larger and larger prefix of the $right$ vector will have stations with their left bound less or equal to the coordinate of the currently processed station from the $left$ vector. For each new such station you should add 1 to some RSQ structure (easiest is fenwick tree) to the position of this station. Since positions are up to $10^{9}$, you will have to compress the coordinates (for example, use index of station in the sorted order instead of it's coordinate). Can you see how to query this fenwick tree to get the number of stations that match the currently processed station from the $left$ vector?",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "762",
    "index": "F",
    "title": "Tree nesting",
    "statement": "You are given two trees (connected undirected acyclic graphs) $S$ and $T$.\n\nCount the number of subtrees (connected subgraphs) of $S$ that are isomorphic to tree $T$. Since this number can get quite large, output it modulo $10^{9} + 7$.\n\nTwo subtrees of tree $S$ are considered different, if there exists a vertex in $S$ that belongs to exactly one of them.\n\nTree $G$ is called isomorphic to tree $H$ if there exists a bijection $f$ from the set of vertices of $G$ to the set of vertices of $H$ that has the following property: if there is an edge between vertices $A$ and $B$ in tree $G$, then there must be an edge between vertices $f(A)$ and $f(B)$ in tree $H$. And vice versa — if there is an edge between vertices $A$ and $B$ in tree $H$, there must be an edge between $f^{ - 1}(A)$ and $f^{ - 1}(B)$ in tree $G$.",
    "tutorial": "One of the possible ways to make your life easier is to count the number of automorphisms of tree $T$. This way you will be able to first calculate the number of labeled matchings of vertices of tree $T$ to the vertices of tree $S$, and then divide this number by the number of automorphisms. Although solution that I will describe does not use this! :D First, remember that every automorphism has a fixed point. Either a vertex or an edge. This is called center of the tree, and you can find it by first finding the diameter of the tree. It's middle vertex (or an edge, if there are two middle vertices) is the center of the tree. Let's root T at it's center. Now let's enumerate subtrees (rooted ones!) of T in such a way that if two subtress are isomorphic they will receive the same number and vice versa. You can do it in a single dfs processing subtrees bottom-up. These numbers will correspond to different isomorphisms. Now you can do a dp with memoization to calculate for each subtree of S rooted at some directed edge the number of ways to \"attach\" each of the isomorphisms from above to this subtree. This can be done by going through all immediate children of the currently processed vertex of S and doing a bitmask DP, where bits are immediate children of the root of currently processed isomophism of T. 1 means it is \"attached\" to some children in S, 0 means not. One of the problems here is that root of current isomorphism of T can have isomorphic children, and if we shuffle how they are attached to children in S we will still receive the same way to cover S with T, so we will calculate some ways twice or more. The solution is to sort children by their isomorphism number and when processing a bitmask, never put 1 to the bit that has a 0 bit to the left that corresponds to the child with the same isomorphism number. This way you will match such children in a fixed order and won't calculate anything unnecessary.",
    "tags": [
      "combinatorics",
      "graphs",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "763",
    "index": "A",
    "title": "Timofey and a tree",
    "statement": "Each New Year Timofey and his friends cut down a tree of $n$ vertices and bring it home. After that they paint all the $n$ its vertices, so that the $i$-th vertex gets color $c_{i}$.\n\nNow it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.\n\nTimofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.\n\nA subtree of some vertex is a subgraph containing that vertex and all its descendants.\n\nYour task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.",
    "tutorial": "Take any edge which vertices are colored in different colors. If such edge doesn't exist you can print any vertex, because all the tree is colored in the same color. Otherwise, try to make a root from each of these vertices. Check if is possible with simple dfs. If it succeedes for one of them, print \"YES\" and this vertex. If it fails for both vertices, the answer is \"NO\". Indeed, if both of them cannot be the root, they lay in the same subtree and they are colored differently. So the condition isn't fulfilled. The asymptotics of this solution is $O(n + m)$.",
    "code": "\"//Codeforces Round #395 Div2C/Div1A solution\\n#include <bits/stdc++.h>\\nusing namespace std;\\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\\n#define forab(i, a, b) for (int i = (int)(a); i < (int)(b); ++i)\\n#define _ cin.tie(0); ios_base::sync_with_stdio(0);\\n#define i64 long long\\nconst int N = 100010;\\nvector<int> g[N];\\nint n, curr_color, color[N];\\nbool ok;\\n\\nbool dfs(int v, int parent) {\\n    ok = ok && (color[v] == curr_color);\\n    forn(i, g[v].size()) {\\n        if (g[v][i] != parent)\\n            dfs(g[v][i], v);\\n    }\\n}\\n\\nbool solve(int v) {\\n    int ans = true;\\n    forn(i, g[v].size()) {\\n        curr_color = color[g[v][i]];\\n        ok = true;\\n        dfs(g[v][i], v);\\n        ans = ans && ok;\\n    }\\n    return ans;\\n}\\n\\nint main() {\\n    cin >> n;\\n    forn(i, n - 1) {\\n        int u, v;\\n        cin >> u >> v;\\n        g[u].push_back(v);\\n        g[v].push_back(u);\\n    }\\n    forn(i, n) cin >> color[i + 1];\\n    int root1 = -1, root2 = -1;\\n    forab(i, 1, n + 1) {\\n        for (auto elem : g[i]) {\\n            if (color[elem] != color[i]) {\\n                root1 = elem;\\n                root2 = i;\\n            }\\n        }\\n    }\\n    if (root1 == -1) {\\n        cout << \\\"YES\\\\n1\\\";\\n        return 0;\\n    }\\n    bool res1 = solve(root1);\\n    bool res2 = solve(root2);\\n    if (res1)\\n        cout << \\\"YES\\\\n\\\" << root1;\\n    else if (res2)\\n        cout << \\\"YES\\\\n\\\" << root2;\\n    else\\n        cout << \\\"NO\\\";\\n    return 0;\\n}\"",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "763",
    "index": "B",
    "title": "Timofey and rectangles",
    "statement": "One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane $n$ rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have \\textbf{odd} length. Rectangles cannot intersect, but they can touch each other.\n\nHelp Timofey to color his rectangles in $4$ different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.\n\nTwo rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length\n\n\\begin{center}\n{\\small The picture corresponds to the first example}\n\\end{center}",
    "tutorial": "Let's consider vertical touchings graph, where vertex is rectangle. For each vertex we keep x coordinate of bottom-right angle. While moving to next rectangle it changes by odd number. In this graph doesn't exist cycle of odd length (sum of odd number of odd numbers can't be zero). Similar to this you can see about horizontal touchings. Let's consider two touching rectagles. Sides lengths are odd, so $2*(x\\ {\\mathrm{mod}}\\ 2)+(y\\ {\\mathrm{mod}}\\ 2)$ give different colors for adjacent rectangles, where $x$ is $x$ coordinate of bottom-left angle and $y$ is $y$ coordinate of bottom-left angle.",
    "code": "\"//Codeforces Round #395 Div2D/Div1B solution\\n#include <bits/stdc++.h>\\nusing namespace std;\\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\\n#define forab(i, a, b) for (int i = (int)(a); i < (int)(b); ++i)\\n#define _ cin.tie(0); ios_base::sync_with_stdio(0);\\n#define i64 long long\\n\\nint main() { \\n    int n;\\n    printf(\\\"YES\\\\n\\\");\\n    scanf(\\\"%d\\\", &n);\\n    for(int i = 0; i < n; i++) {\\n        int x1, y1, x2, y2;\\n        scanf(\\\"%d %d %d %d\\\", &x1, &y1, &x2, &y2);\\n        printf(\\\"%d\\\\n\\\", ((12 + 2 * (x1 % 2) + (y1 % 2)) % 4) + 1);\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "geometry"
    ],
    "rating": 2100
  },
  {
    "contest_id": "763",
    "index": "C",
    "title": "Timofey and remoduling",
    "statement": "Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime $m$. Also, Timofey likes to look for arithmetical progressions everywhere.\n\nOne of his birthday presents was a sequence of \\textbf{distinct} integers $a_{1}, a_{2}, ..., a_{n}$. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo $m$, or not.\n\nArithmetical progression modulo $m$ of length $n$ with first element $x$ and difference $d$ is sequence of integers $x, x + d, x + 2d, ..., x + (n - 1)·d$, each taken modulo $m$.",
    "tutorial": "First, let's think about the case when $2n < m$. In this editorial we say that an outcoming sequence is $s, s + d, s + 2d, ..., s + (n - 1)d$ Assume $x$ is the difference of some two elements $a$ and $b$ of $A$ ($x=b-a\\mod m$). Let's say that $a$ was on $i$-th place in the sequence and $b$ was on $i + k$-th place. Then $x=k\\cdot d\\mod m$. On the other hand, we have that $n$ is less then $\\textstyle{\\frac{m}{2}}$, so $x$ must be difference of exactly $n - k + 1$ pairs of elements of $A$. We can count this value in $O(n\\log n)$ time using binary search or in $O(n)$ time using a hashtable. Then we know the value of $k$. After that we calculate the value $x\\div k\\mod m$ ($m$ is prime so we can use Fermat's little theorem) and then we know the difference of the sequence. Then we just take any element $y$ of $A$ and look on values $y, y + d, y + 2d, ...$, and also on $y - d, y - 2d, ...$. If we can get all of the numbers in $A$ in this way, then we know the first element of the sequence. Otherwise, the answer is NO. If $2n > m$, we just solve the problem for the complement of $A$ in $\\mathbb{Z}_{m}$, and then add to the first element value $(m - n)d$. If we had a correct sequence in $A$, then we must have a correct sequence in its complement with the same difference (as long as $m$ is coprime with the difference, the complement is just set of numbers $s + nd, s + (n + 1)d, ..., s + (m - 1)d$).",
    "code": "\"//Codeforces Round #395 Div2E/Div1C solution\\n#include <iostream>\\n#include <cstdio>\\n#include <vector>\\n#include <cstring>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <stack>\\n#include <queue>\\n#include <deque>\\n#include <algorithm>\\n#include <sstream>\\n#include <cstdlib>\\n#include <cmath>\\n#include <random>\\n#include <bitset>\\n#include <cassert>\\n#include <tuple>\\n#include <list>\\n#include <iterator>\\n#include <unordered_set>\\n#include <unordered_map>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\ntypedef long double ld;\\n\\n#define mp make_pair\\n#define pb push_back\\n#define mt make_tuple\\n\\n#define forn(i, n) for (int i = 0; i < ((int)(n)); ++i)\\n#define forrn(i, s, n) for (int i = (int)(s); i < ((int)(n)); ++i)\\n#define all(v) (v).begin(), (v).end()\\n#define rall(v) (v).rbegin(), (v).rend()\\n\\nconst int INF = 1791791791;\\nconst ll INFLL = 1791791791791791791ll;\\n\\nll pow(ll x, int n, ll m) {\\n    if (n == 0)\\n        return 1;\\n    else if (n & 1)\\n        return (x * pow(x, n ^ 1, m)) % m;\\n    else {\\n        ll t = pow(x, n >> 1, m);\\n        return (t * t) % m;\\n    }\\n}\\n\\nll divide(ll a, ll b, ll m) {\\n    return (a * pow(b, m - 2, m)) % m;\\n}\\n\\nint n;\\nll m;\\nvector<int> a; // sorted\\n\\nbool is_good_difference(int d, int& first) {\\n    int y = a[0];\\n    int cnt = 0;\\n    auto it = lower_bound(all(a), y);\\n    while (it != a.end() && *it == y) {\\n        y += d;\\n        if (y >= m)\\n            y -= m;\\n        cnt++;\\n        it = lower_bound(all(a), y);\\n    }\\n    y = a[0];\\n    it = lower_bound(all(a), y);\\n    while (it != a.end() && *it == y) {\\n        first = y;\\n        y -= d;\\n        if (y < 0)\\n            y += m;\\n        cnt++;\\n        it = lower_bound(all(a), y);\\n    }\\n    return cnt == n + 1;\\n}\\n\\nint count_differences(int d) {\\n    int cnt = 0;\\n    for (int i = 0; i < n; i++) {\\n        for (int add = -d; add <= d; add += 2 * d) {\\n            int y = a[i] + add;\\n            if (y >= m) y -= m;\\n            if (y < 0) y += m;\\n            if (a[i] > y)\\n                continue;\\n            auto it = lower_bound(all(a), y);\\n            if (it != a.end() && *it == y)\\n                cnt++;\\n        }\\n    }\\n    return cnt;\\n}\\n\\npair<int, int> solve() {\\n    if (n == 0)\\n        return make_pair(1, 1);\\n    if (n == 1)\\n        return make_pair(a[0], 1);\\n    sort(all(a));\\n    int first;\\n    int difference = a[1] - a[0];\\n    int k = n - count_differences(difference);\\n    int d = divide(difference, k, m);\\n    if (is_good_difference(d, first)) {\\n        return make_pair(first, d);\\n    } else {\\n        return make_pair(-1, -1);\\n    }\\n}\\n\\nint main() {\\n    int cn;\\n    cin >> m >> n;\\n    cn = n;\\n    vector<int> c;\\n    c.resize(n);\\n    forn(i, n)\\n        cin >> c[i];\\n\\n    if (n == 1) {\\n        cout << c[0] << \\\" 1\\\" << endl;\\n        return 0;\\n    }\\n\\n    pair<int, int> answer(-1, -1);\\n\\n    if (2 * n >= m) {\\n        sort(all(c));\\n        vector<int> b;\\n        for (int i = 0; i < m; i++) {\\n            auto it = lower_bound(c.begin(), c.end(), i);\\n            if (it == c.end() || *it != i)\\n                b.push_back(i);\\n        }\\n        n = m - n;\\n        a = b;\\n        pair<int, int> now = solve();\\n        if (now.first > -1) {\\n            answer.second = now.second;\\n            answer.first = (now.first + 1ll * n * now.second) % m;\\n        }\\n    } else {\\n        a = c;\\n        answer = solve();\\n    }\\n    \\n    if (answer.first == -1)\\n        cout << -1 << endl;\\n    else\\n        cout << answer.first << \\\" \\\" << answer.second << endl;\\n\\n    return 0;\\n}\"",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "763",
    "index": "D",
    "title": "Timofey and a flat tree",
    "statement": "Little Timofey has a big tree — an undirected connected graph with $n$ vertices and no simple cycles. He likes to walk along it. His tree is flat so when he walks along it he sees it entirely. Quite naturally, when he stands on a vertex, he sees the tree as a rooted tree with the root in this vertex.\n\nTimofey assumes that the \\textbf{more} non-isomorphic subtrees are there in the tree, the more beautiful the tree is. A subtree of a vertex is a subgraph containing this vertex and all its descendants. You should tell Timofey the vertex in which he should stand to see the most beautiful rooted tree.\n\nSubtrees of vertices $u$ and $v$ are isomorphic if the number of children of $u$ equals the number of children of $v$, and their children can be arranged in such a way that the subtree of the first son of $u$ is isomorphic to the subtree of the first son of $v$, the subtree of the second son of $u$ is isomorphic to the subtree of the second son of $v$, and so on. In particular, subtrees consisting of single vertex are isomorphic to each other.",
    "tutorial": "There are only $2 \\cdot (n - 1)$ subtrees in the whole tree: two for each edge. Let's calculate hashes of each of them. We can calculate hash of a subtree, for example, in a following. Let's associate each vertex with a correct bracket sequence. Leaves are associated with \"()\", other vertices are associated with their sequences according to the following rule. Assume that the children of our vertex are associated with sequences $s_{1}, s_{2}, ..., s_{k}$. Let's sort strings $s_{1}, s_{2}, ..., s_{k}$ in some order, for example, in order of ascending hashes. Then our vertex is associated with sequence $(s_{1s}_{2}... s_{k})$. It's easy to check that isomorphic subtrees are associated with equal sequences and non-isomoriphic are associated with different sequences. Then hash of a subtree is the hash of the sequence associated with the root of the subtree. In this problem we will calculate the polynomial hash because we will need to count the hash of concatenation of several strings knowing only their hash and length. We know hashes for all of the leaves. Let's do a bfs-like algorithm that will greedily count all of the hashes. Let's count $out_{v}$ - number of outer edges for vertex $v$, for which we have already counted hashes of their subtrees. Then we know new hashes in two cases: $o u t_{v}=\\operatorname*{deg}_{v}-\\rfloor$. Then we can calculate the hash for the inner edge of $v$, for which we don't already know the outer hash in $O(\\deg_{v}\\log(\\deg_{v})$ time. $o u t_{v}=\\deg_{v}$. Then we can calculate the hash for all of the inner edges, for which we don't already know it. Let's calculate hashes for all of concatenations of prefixes and suffixes of the sorted array. If we count polynomial hash, we can calculate them knowing only their hashes and length. Then when we calculate the hash for particular edge, we just have to concatenate the prefix and the suffix of our array. This all works in $\\deg_{v}\\log(\\deg_{v})$ time. Now we have to calculate for each vertex $v$ the number of distinct hashes in case $v$ is the root. Let's select some vertex and calculate this number fairly, using dfs and storing for each hash number of its occurrences in a hashtable. Then we go through the tree in order of Euler tour and maintain the hashtable. When we go through edge $u\\rightarrow v$, we should add hash of the edge $v\\to u$ and remove hash of the edge $v\\to u$, other hashes in the hashtable doesn't change. This works in $O(n\\log n)$ time.",
    "code": "\"//Codeforces Round #395 Div1D solution\\n#include <iostream>\\n#include <cstdio>\\n#include <vector>\\n#include <cstring>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <stack>\\n#include <queue>\\n#include <deque>\\n#include <algorithm>\\n#include <sstream>\\n#include <cstdlib>\\n#include <cmath>\\n#include <ctime>\\n#include <random>\\n#include <bitset>\\n#include <cassert>\\n#include <tuple>\\n#include <list>\\n#include <iterator>\\n#include <unordered_set>\\n#include <unordered_map>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\ntypedef long double ld;\\n\\n#define mp make_pair\\n#define pb push_back\\n#define mt make_tuple\\n#define ff first\\n#define ss second\\n\\n#define forn(i, n) for (int i = 0; i < ((int)(n)); ++i)\\n#define forrn(i, s, n) for (int i = (int)(s); i < ((int)(n)); ++i)\\n#define all(v) (v).begin(), (v).end()\\n#define rall(v) (v).rbegin(), (v).rend()\\n\\nconst int INF = 1791791791;\\nconst ll INFLL = 1791791791791791791ll;\\n\\nvector<vector<int> > tree;\\nvector<vector<ll> > frw_hash;\\nvector<vector<ll> > rev_hash;\\nvector<int> num;\\n\\nvoid get_all(int v, int par, unordered_map<ll, int>& ums) {\\n    int i = 0;\\n    for (int u : tree[v]) {\\n        if (u != par) {\\n            ums[frw_hash[v][i]]++;\\n            get_all(u, v, ums);\\n        }\\n        i++;\\n    }\\n}\\n\\nvoid dfs(int v, int par, unordered_map<ll, int>& ums) {\\n    num[v] = ums.size();\\n    int i = 0;\\n    for (int u : tree[v]) {\\n        if (u != par) {\\n            ums[frw_hash[v][i]]--;\\n            if (ums[frw_hash[v][i]] == 0)\\n                ums.erase(frw_hash[v][i]);\\n            ums[rev_hash[v][i]]++;\\n            dfs(u, v, ums);\\n            ums[rev_hash[v][i]]--;\\n            if (ums[rev_hash[v][i]] == 0)\\n                ums.erase(rev_hash[v][i]);\\n            ums[frw_hash[v][i]]++;\\n        }\\n        i++;\\n    }\\n}\\n\\nconst ll p = 179;\\nconst ll mod = 1791791791l;\\nconst int maxn = 1e6 + 179;\\n\\nint main() {\\n    ll ppows[maxn];\\n    ppows[0] = 1;\\n    forrn(i, 1, maxn)\\n        ppows[i] = (ppows[i - 1] * p) % mod;\\n    \\n    int n;\\n    cin >> n;\\n    tree.resize(n);\\n    vector<pair<int, int> > edges;\\n    forn(i, n - 1) {\\n        int u, v;\\n        cin >> u >> v;\\n        u--; v--;\\n        tree[u].pb(v);\\n        tree[v].pb(u);\\n        edges.pb(mp(u, v));\\n        edges.pb(mp(v, u));\\n    }\\n\\n    map<pair<int, int>, int> index;\\n    forn(i, 2 * n - 2)\\n        index[edges[i]] = i;\\n\\n    vector<ll> hash_of(edges.size(), -1);\\n    vector<ll> rem_hh(edges.size(), -1);\\n    vector<int> sz_of(edges.size(), -1);\\n    queue<int> q;\\n    forn(i, n)\\n        if (tree[i].size() == 1) {\\n            rem_hh[index[mp(tree[i][0], i)]] = ('(' * p + ')') % mod;\\n            sz_of[index[mp(tree[i][0], i)]] = 1;\\n            q.push(index[mp(tree[i][0], i)]);\\n        }\\n    vector<int> out(n, 0);\\n    while (!q.empty()) {\\n        int a = q.front();\\n        q.pop();\\n        if (hash_of[a] != -1)\\n            continue;\\n        hash_of[a] = rem_hh[a];\\n        int v = edges[a].ff;\\n        out[v]++;\\n        if (out[v] == (int)tree[v].size() - 1) {\\n            int u = -1;\\n            vector<ll> pr_next_hh, next_hh;\\n            vector<int> pr_szs, szs;\\n            for (int w : tree[v]) {\\n                if (hash_of[index[mp(v, w)]] == -1)\\n                    u = w;\\n                else {\\n                    pr_next_hh.pb(hash_of[index[mp(v, w)]]);\\n                    pr_szs.pb(sz_of[index[mp(v, w)]]);\\n                }\\n            }\\n            vector<int> ind(pr_next_hh.size());\\n            iota(all(ind), 0);\\n            sort(all(ind), [&](const int& i, const int& j) -> bool {return pr_next_hh[i] < pr_next_hh[j];});\\n            forn(i, pr_next_hh.size()) {\\n                next_hh.pb(pr_next_hh[ind[i]]);\\n                szs.pb(pr_szs[ind[i]]);\\n            }\\n            int i = index[mp(u, v)];\\n            rem_hh[i] = '(';\\n            sz_of[i] = 1;\\n            forn(j, next_hh.size()) {\\n                rem_hh[i] = (rem_hh[i] * ppows[2 * szs[j]]) % mod;\\n                rem_hh[i] = (rem_hh[i] + next_hh[j]) % mod;\\n                sz_of[i] += szs[j];\\n            }\\n            rem_hh[i] = (rem_hh[i] * p + ')') % mod;\\n            q.push(i);\\n        } else if (out[v] == (int)tree[v].size()) {\\n            vector<ll> pr_next_hh, next_hh;\\n            vector<int> pr_szs, szs;\\n            for (int w : tree[v]) {\\n                pr_next_hh.pb(hash_of[index[mp(v, w)]]);\\n                pr_szs.pb(sz_of[index[mp(v, w)]]);\\n            }\\n            vector<int> ind(pr_next_hh.size());\\n            vector<int> rev(pr_next_hh.size());\\n            iota(all(ind), 0);\\n            sort(all(ind), [&](const int& i, const int& j) -> bool {return pr_next_hh[i] < pr_next_hh[j];});\\n            forn(i, pr_next_hh.size()) {\\n                rev[ind[i]] = i;\\n                next_hh.pb(pr_next_hh[ind[i]]);\\n                szs.pb(pr_szs[ind[i]]);\\n            }\\n            vector<ll> pref_hh(next_hh.size() + 1, 0);\\n            pref_hh[0] = '(';\\n            pref_hh[1] = ('(' * p + next_hh[0]) % mod;\\n            forrn(i, 1, next_hh.size() + 1) {\\n                pref_hh[i] = (pref_hh[i - 1] * ppows[2 * szs[i - 1]] + next_hh[i - 1]) % mod;\\n            }\\n            pref_hh.pb((pref_hh.back() * p + ')') % mod);\\n            vector<ll> suf_hh(next_hh.size() + 2, 0);\\n            vector<int> suf_sz(next_hh.size() + 2, 0);\\n            suf_hh.back() = ')';\\n            for (int i = next_hh.size(); i > 0; i--) {\\n                suf_hh[i] = (suf_hh[i + 1] + next_hh[i - 1] * ppows[2 * suf_sz[i + 1] + 1]) % mod;\\n                suf_sz[i] = suf_sz[i + 1] + szs[i - 1];\\n            }\\n            suf_hh[0] = (suf_hh[1] + '(' * ppows[2 * suf_sz[1] + 1]) % mod;\\n            suf_sz[0] = suf_sz[1];\\n            forn(i, next_hh.size()) {\\n                int u = tree[v][ind[i]];\\n                if (rem_hh[index[mp(u, v)]] == -1) {\\n                    sz_of[index[mp(u, v)]] = n - sz_of[index[mp(v, u)]];\\n                    rem_hh[index[mp(u, v)]] = (pref_hh[i] * ppows[2 * suf_sz[i + 2] + 1] + suf_hh[i + 2]) % mod;\\n                    q.push(index[mp(u, v)]);\\n                }\\n            }\\n        }\\n    }\\n\\n    \\n    frw_hash.resize(n);\\n    rev_hash.resize(n);\\n    num.resize(n);\\n    forn(i, n) {\\n        for (int v : tree[i]) {\\n            frw_hash[i].pb(hash_of[index[mp(i, v)]]);\\n            rev_hash[i].pb(hash_of[index[mp(v, i)]]);\\n\\t}\\n    }\\n    unordered_map<ll, int> ump;\\n    get_all(0, -1, ump);\\n    dfs(0, -1, ump);\\n\\n    cout << distance(num.begin(), max_element(all(num))) + 1 << endl;\\n    return 0;\\n}\"",
    "tags": [
      "data structures",
      "graphs",
      "hashing",
      "shortest paths",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "763",
    "index": "E",
    "title": "Timofey and our friends animals",
    "statement": "After his birthday party, Timofey went to his favorite tree alley in a park. He wants to feed there his favorite birds — crows.\n\nIt's widely known that each tree is occupied by a single crow family. The trees in the alley form a row and are numbered from $1$ to $n$. Some families are friends to each other. For some reasons, two families can be friends only if they live not too far from each other, more precisely, there is no more than $k - 1$ trees between any pair of friend families. Formally, the family on the $u$-th tree and the family on the $v$-th tree can be friends only if $|u - v| ≤ k$ holds.\n\nOne of the friendship features is that if some family learns that Timofey is feeding crows somewhere, it notifies about this all friend families. Thus, after Timofey starts to feed crows under some tree, all the families that are friends to the family living on this tree, as well as their friends and so on, fly to the feeding place. Of course, the family living on the tree also comes to the feeding place.\n\nToday Timofey came to the alley and noticed that all the families that live on trees with numbers strictly less than $l$ or strictly greater than $r$ have flown away. Thus, it is not possible to pass the information about feeding through them. Moreover, there is no need to feed them. Help Timofey to learn what is the minimum number of trees under which he has to feed crows so that all the families that have remained will get the information about feeding. You are given several situations, described by integers $l$ and $r$, you need to calculate the answer for all of them.",
    "tutorial": "Let's build a segment tree on crow families. Let's save DSU in each vertex, having information about number of components of connectivity on it. In one vertex will be DSU with size $n$. In two vertices will be DSU with size $n / 2$. In four vertices will be DSU with size $n / 4$. It's easy to show that we will store only $O(nlogn)$ values. Let's understand how we can unite segments. Knowing answer (number of components) for [a; b) and [b; c) we can obtain answer for [a; c) in the following way: We can sum answers for for [a; b) and [b; c) and substract number of components, which united during the \"gluing\". If components become united, there is edge between vertex in one and vertex in another. We have constraint on edge legth: vertex $u$ and vertex $v$ can be connected only if $abs(u - v)  \\le  k$ Then we can easily unite two segments of the segment tree in $O(k^{2})$ time: we just unite some of the $k$ components of families represented in the end of each segment when they are connected by edge. Segment tree can split query in $O(\\log n)$ already calculated segments. So we can answer the query in $O(k^{2}\\log{n})$ time. Precalc will take nearly $O(n\\log n)$.",
    "code": "\"//Codeforces Round #395 Div1E solution\\n#include <iostream>\\n#include <cstdio>\\n#include <vector>\\n#include <cstring>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <stack>\\n#include <queue>\\n#include <deque>\\n#include <algorithm>\\n#include <sstream>\\n#include <cstdlib>\\n#include <cmath>\\n#include <ctime>\\n#include <random>\\n#include <bitset>\\n#include <cassert>\\n#include <tuple>\\n#include <list>\\n#include <iterator>\\n#include <unordered_set>\\n#include <unordered_map>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\ntypedef long double ld;\\n\\n#define mp make_pair\\n#define pb push_back\\n#define mt make_tuple\\n#define lb lower_bound\\n#define ub upper_bound\\n#define ff first\\n#define ss second\\n\\n#define forn(i, n) for (int i = 0; i < ((int)(n)); ++i)\\n#define forrn(i, s, n) for (int i = (int)(s); i < ((int)(n)); ++i)\\n#define all(v) (v).begin(), (v).end()\\n#define rall(v) (v).rbegin(), (v).rend()\\n\\n\\nconst int INF = 1791791791;\\nconst ll INFLL = 1791791791791791791ll;\\n\\nclass dsu {\\n    vector<int> par;\\n    vector<int> rank;\\npublic:\\n    int cnum;\\n    dsu() {}\\n    dsu(int n) {\\n        cnum = n;\\n        par.resize(n);\\n        iota(all(par), 0);\\n        rank.resize(n, 1);\\n    }\\n    int get(int u) {\\n        if (u != par[u])\\n            par[u] = get(par[u]);\\n        return par[u];\\n    }\\n    void merge(int u, int v) {\\n        u = get(u);\\n        v = get(v);\\n        if (u == v)\\n            return;\\n        cnum--;\\n        if (rank[u] > rank[v])\\n            swap(u, v);\\n        par[u] = v;\\n        rank[v] = max(rank[v], rank[u] + 1);\\n    }\\n};\\n\\nclass solve {\\n    int n, k;\\n    vector<vector<int> > graph;\\n    vector<dsu> tree;\\n    void build(int v, int L, int R) {\\n        tree[v] = dsu(R - L);\\n        forrn(i, L, R) {\\n            for (int u : graph[i]) {\\n                if (L <= u && u < R)\\n                    tree[v].merge(i - L, u - L);\\n            }\\n        }\\n        if (L != R - 1) {\\n            build(2 * v + 1, L, (L + R) >> 1);\\n            build(2 * v + 2, (L + R) >> 1, R);\\n        }\\n    }\\n    vector<tuple<int, int, int> > vertex;\\n    void get_vertex(int v, int L, int R, int l, int r) {\\n        if (r <= L || R <= l)\\n            return;\\n        else if (l <= L && R <= r)\\n            vertex.pb(mt(v, L, R));\\n        else {\\n            get_vertex(2 * v + 1, L, (L + R) >> 1, l, r);\\n            get_vertex(2 * v + 2, (L + R) >> 1, R, l, r);\\n        }\\n    }\\n    int different(vector<int> vec) {\\n        sort(all(vec));\\n        return distance(vec.begin(), unique(all(vec)));\\n    }\\n    int on_two_segments(vector<int> fvec, int fl, int fr, vector<int> svec, int sl, int sr) {\\n        assert(fr == sl);\\n\\n        vector<int> fcds = fvec;\\n        sort(all(fcds));\\n        fcds.resize(distance(fcds.begin(), unique(all(fcds))));\\n        vector<int> scds = svec;\\n        sort(all(scds));\\n        scds.resize(distance(scds.begin(), unique(all(scds))));\\n        int m = fcds.size();\\n        \\n        dsu ds(fcds.size() + scds.size());\\n        forrn(i, fl, fr) {\\n            for (int u : graph[i])\\n                if (sl <= u && u < sr)\\n                    ds.merge(lb(all(fcds), fvec[i - fl]) - fcds.begin(), m + (lb(all(scds), svec[u - sl]) - scds.begin()));\\n        }\\n        \\n        return ds.cnum;\\n    }\\n    vector<int> segment_comps(int l, int r) {\\n        vector<int> ans;\\n        dsu ds(r - l);\\n        forrn(i, l, r) {\\n            for (int u : graph[i])\\n                if (l <= u && u < r)\\n                    ds.merge(i - l, u - l);\\n        }\\n        forrn(i, l, r)\\n            ans.pb(ds.get(i - l));\\n        return ans;\\n    }\\npublic:\\n    solve(int _n, int _k) {\\n        n = _n; k = _k;\\n        graph.resize(n);\\n        tree.resize(4 * n);\\n    }\\n    void add_edge(int u, int v) {\\n        graph[u].pb(v);\\n        graph[v].pb(u);\\n    }\\n    void precalc() {\\n        build(0, 0, n);\\n    }\\n    int compnum(int l, int r) {\\n        vertex.clear();\\n        get_vertex(0, 0, n, l, r);\\n        int cur = 0;\\n        vector<int> last;\\n        int cl = l, cr = l;\\n        for (auto t : vertex) {\\n            int v = get<0>(t);\\n            int L = get<1>(t);\\n            assert(L == cr);\\n            int R = get<2>(t);\\n\\n            int sl = max(cr - k, cl);\\n            int sr = min(L + k, R);\\n\\n            int n1 = different(last);\\n            vector<int> next;\\n            forrn(i, L, sr)\\n                next.pb(tree[v].get(i - L));\\n            int n2 = different(next);\\n\\n            cur = cur + tree[v].cnum - (n1 + n2) + on_two_segments(last, sl, cr, next, L, sr);\\n            cr = R;\\n            if (R - L >= k) {\\n                last.clear();\\n                forrn(i, R - k, R)\\n                    last.pb(tree[v].get(i - L));\\n            } else\\n                last = segment_comps(max(cl, cr - k), cr);\\n        }\\n        return cur;\\n    }\\n};\\n\\nint main() {\\n    // Code here:\\n   \\n    int n, k;\\n    scanf(\\\"%d %d\\\", &n, &k);\\n    solve prob(n, k);\\n    int m;\\n    scanf(\\\"%d\\\", &m);\\n    forn(i, m) {\\n        int u, v;\\n        scanf(\\\"%d %d\\\", &u, &v);\\n        u--; v--;\\n        prob.add_edge(u, v);\\n    }\\n    prob.precalc();\\n    int q;\\n    scanf(\\\"%d\\\", &q);\\n    forn(i, q) {\\n        int l, r;\\n        scanf(\\\"%d %d\\\", &l, &r);\\n        l--;\\n        printf(\\\"%d\\\\n\\\", prob.compnum(l, r));\\n    }\\n\\n    return 0;\\n}\"",
    "tags": [
      "data structures",
      "divide and conquer",
      "dsu"
    ],
    "rating": 2900
  },
  {
    "contest_id": "764",
    "index": "A",
    "title": "Taymyr is calling you",
    "statement": "Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist.\n\nIlia-alpinist calls every $n$ minutes, i.e. in minutes $n$, $2n$, $3n$ and so on. Artists come to the comrade every $m$ minutes, i.e. in minutes $m$, $2m$, $3m$ and so on. The day is $z$ minutes long, i.e. the day consists of minutes $1, 2, ..., z$. How many artists should be killed so that there are no artists in the room when Ilia calls? Consider that a call and a talk with an artist take exactly one minute.",
    "tutorial": "You can look over all minutes of the day. If both events happen on the some minute, we increment our answer.",
    "code": "\"#Codeforces Round #395 Div2A solution\\nfrom math import gcd\\n\\nn, m, z = map(int, input().split())\\ng = gcd(n, m)\\nlcm = n * m // g\\nprint(z // lcm)\"",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "764",
    "index": "B",
    "title": "Timofey and cubes",
    "statement": "Young Timofey has a birthday today! He got kit of $n$ cubes as a birthday present from his parents. Every cube has a number $a_{i}$, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.\n\nIn this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from $1$ to $n$ in their order. Dima performs several steps, on step $i$ he reverses the segment of cubes from $i$-th to $(n - i + 1)$-th. He does this while $i ≤ n - i + 1$.\n\nAfter performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.",
    "tutorial": "Note that Dima's operations are reversible. If we apply them to the current order, we will get the initial. Also note that all the elements on even positions will remain on their places. Such numbers are affected an even number of times, so nothing will change. Similarly all elements on odd positions will change places with simmetrial ones relatively the centre. So, we change elements on odd places with their pairs. This works for $O(n)$ time.",
    "code": "\"//Codeforces Round #395 Div2B solution\\n#include <bits/stdc++.h>\\nusing namespace std;\\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\\n#define forn(i, n) for (int i = 0; i < (int)(n); i++)\\n#define forab(i, a, b) for (int i = (int)(a); i < (int)(b); ++i)\\n#define _ cin.tie(0); ios_base::sync_with_stdio(0);\\n#define i64 long long\\n\\nconst int MAXN = 1000000 + 10;\\nint n, a[MAXN];\\n\\nint main() { _\\n  scanf(\\\"%d\\\\n\\\", &n);\\n  forn(i, n)\\n    scanf(\\\"%d\\\", &a[i]);\\n  for (int i = 0; i <= n - i - 1; ++i) {\\n    if (i % 2 - 1)\\n      swap(a[i], a[n - i - 1]);\\n  }\\n  forn(i, n) {\\n    if (i)\\n      printf(\\\" \\\");\\n    printf(\\\"%d\\\", a[i]);\\n  }\\n  return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "765",
    "index": "A",
    "title": "Neverending competitions",
    "statement": "There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name \"snookah\")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back.\n\nJinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that:\n\n- this list contains all Jinotega's flights in this year (\\textbf{in arbitrary order}),\n- Jinotega has only flown from his hometown to a snooker contest and back,\n- after each competition Jinotega flies back home (though they may attend a competition in one place several times),\n- and finally, at the beginning of the year Jinotega was at home.\n\nPlease help them to determine Jinotega's location!",
    "tutorial": "Each competition adds two flights to the list - there and back. The only exception is the last competition: if Jinotega is now there, it adds only one flight. So if $n$ is odd, the answer is contest, otherwise home.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "765",
    "index": "B",
    "title": "Code obfuscation",
    "statement": "Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.\n\nTo obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol $a$, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with $b$, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.\n\nYou are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.",
    "tutorial": "In this problem you needed to check that the first occurrences of letters $a$, $b$, ... appear in order (that is, first \"$a$\" is before first \"$b$\", which, in order, is before first \"$c$\", so on). One possible solution: for each letter $x$ check that there is at least one letter $x - 1$ before it.",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "765",
    "index": "C",
    "title": "Table Tennis Game 2",
    "statement": "Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly $k$ points, the score is reset and a new set begins.\n\nAcross all the sets Misha scored $a$ points in total, and Vanya scored $b$ points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible.\n\nNote that the game consisted of several complete sets.",
    "tutorial": "There are several possible cases how the game could go: The first player won all the sets. In this case, each set gave him exactly $k$ points, hence $a$ must be divisible by $k$. Moreover, $b  \\le  (a / k) \\cdot (k - 1)$ since the second player could get at most $k - 1$ points per set. If we have $k|a$ and $0  \\le  b  \\le  (a / k) \\cdot (k - 1)$, then the answer is at least $a / k$. The second player won all the sets. The analysis in symmetrical. Each player has won at least one set. In this case we must have $a  \\ge  k$ and $b  \\ge  k$. If this condition holds, the game is possible with the maximal number of sets $ \\lfloor  a / k \\rfloor  +  \\lfloor  b / k \\rfloor $. Indeed, consider the following sequence of sets: $(k,b{\\mathrm{~mod~}}k)$, $(a{\\mathrm{~mod~}}k{\\mathrm{,}}k)$, $( \\lfloor  a / k \\rfloor  - 1)$ copies of $(k, 0)$, $( \\lfloor  b / k \\rfloor  - 1)$ copies of $(0, k)$. In short: if ($a  \\ge  k$ and $b  \\ge  k$) or ($a$ divisible by k) or ($b$ divisible by $k$) the answer $ \\lfloor  a / k \\rfloor  +  \\lfloor  b / k \\rfloor $, otherwise $- 1$. One can check that this is equivalent to the reasoning above.",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "765",
    "index": "D",
    "title": "Artsem and Saunders",
    "statement": "Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.\n\nLet $[n]$ denote the set ${1, ..., n}$. We will also write $f: [x] → [y]$ when a function $f$ is defined in integer points $1$, ..., $x$, and all its values are integers from 1 to $y$.\n\nNow then, you are given a function $f: [n] → [n]$. Your task is to find a positive integer $m$, and two functions $g: [n] → [m]$, $h: [m] → [n]$, such that $g(h(x)) = x$ for all $x\\in[m]$, and $h(g(x)) = f(x)$ for all $x\\in[n]$, or determine that finding these is impossible.",
    "tutorial": "Suppose that $h(g)  \\equiv  f$ (that is, the functions match on all inputs), and $g(h)\\equiv1$ (the identity function). Hence, we must have $f(f(x))=h(g(h(g(x))))=h({\\bf1}(g(x)))=h(g(x))=f(x)$. It means that if $f(x) = y$, then $f(y) = f(f(x)) = f(x) = y$, that is, all distinct values of $f$ must be its stable points. If this is violated, we can have no answer. We will put $m$ equal to the number of stable points. Let's enumerate all distinct values of $f$ as $p_{1}$, ..., $p_{m}$, and define a function $q$ that maps a point $p_{i}$ to the index $i$. We will determine functions $g(x) = q(f(x))$, and $h(x) = p_{x}$. We can see that: if $x\\in[n]$, then $h(g(x)) = p_{q(f(x))} = f(x)$. if $x\\in[m]$, then $g(h(x)) = q(p_{x}) = x$. All enumeration can be done in linear time.",
    "tags": [
      "constructive algorithms",
      "dsu",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "765",
    "index": "E",
    "title": "Tree Folding",
    "statement": "Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex $v$, and two disjoint (except for $v$) paths of equal length $a_{0} = v$, $a_{1}$, ..., $a_{k}$, and $b_{0} = v$, $b_{1}$, ..., $b_{k}$. Additionally, vertices $a_{1}$, ..., $a_{k}$, $b_{1}$, ..., $b_{k}$ must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices $b_{1}$, ..., $b_{k}$ can be effectively erased:\n\nHelp Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path.",
    "tutorial": "Let's look at the performed actions in reverse. First, we have some path of odd length (by saying length we mean the number of edges} and double it several times. Now we do several \"unfoldings\". Among two leaves of this path exactly one (or its copy) participate in each unfolding; depending on it we call the unfolding \"left\" or \"right\". Note that left and right unfoldings have no edges in common; thus there is some vertex on the path which is not being unfolded. Let's call this vertex root. Here is a criterion that a vertex can be a valid root. Root the tree at it and look at its certain subtree: the depths of all leaves there must be equal. Moreover, among all subtrees of the root there must be not more than 2 different depths of the leaves. This criterion follows directly if you look at the sequence of unfoldings. Now we have a solution: for each directed edge in a tree compute a set of depths to the leaves by a 2-way tree DP (actually, it must be computed only if its size is at most 1). Afterwards for each vertex check the root criterion. However, there is an idea which makes the solution simpler: the midpoint of the diameter of the given tree is always an appropriate root. Given this, we should only run a standard tree DP which checks if all leaves in a subtree have the same depth. Here is the outline of a proof: in the path from the first paragraph select the leftmost and the rightmost possible root, now look through all possible distances from left root to the left leaf and from the right root to the right leaf. There are several configurations which are easy to check manually.",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "765",
    "index": "F",
    "title": "Souvenirs",
    "statement": "Artsem is on vacation and wants to buy souvenirs for his two teammates. There are $n$ souvenir shops along the street. In $i$-th shop Artsem can buy one souvenir for $a_{i}$ dollars, and he cannot buy more than one souvenir in one shop. He doesn't want to introduce envy in his team, so he wants to buy two souvenirs with least possible difference in price.\n\nArtsem has visited the shopping street $m$ times. For some strange reason on the $i$-th day only shops with numbers from $l_{i}$ to $r_{i}$ were operating (weird? yes it is, but have you ever tried to come up with a reasonable legend for a range query problem?). For each visit, Artsem wants to know the minimum possible difference in prices of two different souvenirs he can buy in the opened shops.\n\nIn other words, for each Artsem's visit you should find the minimum possible value of $|a_{s} - a_{t}|$ where $l_{i} ≤ s, t ≤ r_{i}$, $s ≠ t$.",
    "tutorial": "We will answer queries offline, moving right endpoint to the right and storing the answer for each left endpoint in a segment tree. The tree will support two operations: set minimum on a segment and get a value in the point. More, we assume that among two elements $a_{i}$ and $a_{j}$ in our array $a_{i} > a_{j}$ and $i < j$ and solve the problem twice - for the original array and for the reversed one. Consider one step of moving the right endpoint and adding new element $x$ to the position $i$. We find the first element to the left of $i$ which is not less than $x$; denote it with $a_{j} = y$. Obviously, now the answer for all left endpoints in range $[0, j]$ is $y - x$. Now we find some $a_{j'} = y'$ such that $x  \\le  y' < y$ and $j' < j$, and the answer for all left endpoints in range $[0, j']$ is at most $y' - x$. If we repeat this step while possible, we maintain correct values in our segment tree. The crucial idea of the problem is the following inequality: $y' - x < y - y'$. Why? Because each segment with $r = i$ and $0  \\le  l  \\le  j'$ contains elements $y$ and $y'$, and adding $x$ will improve the answer for these endpoints only if this inequality holds. Having this, we need to consider only $O(\\log10^{9})$ values of $y$. The asymptotic of the solution is $O(n\\log n\\log10^{9}+m\\log n)$.",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "765",
    "index": "G",
    "title": "Math, math everywhere",
    "statement": "If you have gone that far, you'll probably skip unnecessary legends anyway...\n\nYou are given a binary string $s=s_{0}\\cdot\\cdot\\cdot s_{m-1}$ and an integer $N=p_{1}^{\\alpha_{1}}\\cdot\\cdot\\cdot p_{n}^{\\alpha_{n}}$. Find the number of integers $k$, $0 ≤ k < N$, such that for all $i = 0$, $1$, ..., $m - 1$\n\n\\[\n\\operatorname*{gcd}(k+i,N)=1\\ \\operatorname{if}\\operatorname{and\\only}\\operatorname{if}\\ \\ s_{i}=1\n\\]\n\nPrint the answer modulo $10^{9} + 7$.",
    "tutorial": "First I'll describe our original approach to this problem, and then some issues we encountered after the round finished. Suppose that $p_{1} = 2$. If we have $x\\equiv0(\\mathrm{mod}\\,2)$, then the string $s$ must look like 0?0?0?..., that is, all even positions 0, 2, 4, ... will have 0's (for all others, we can't say), and if $x\\equiv1(\\mathrm{mod}\\ 2)$, then $s$ looks like ?0?0?0.... Similarly, knowing the remainder of $x$ modulo a prime $p$ in factorization of $N$ implies that there are zeros in $s$ with $p$ positions apart. If we fix all remainder modulo $p_{1}$, ..., $p_{n}$, then the string will be determined unambigiously. Notice that after fixing the modulos, there are still $N' = p_{1}^{ \\alpha 1 - 1}... p_{n}^{ \\alpha n - 1}$ possible $x$'s between $0$ and $N - 1$; we will simply multiply the answer by $N'$ in the end. At this point we have a brute-force solution: try all values for remainders, count how many of the values give the string $s$. This is of course too slow, but we can make a few optimizations: Make a brute-force into a DP by introducing memoization. We will count the number of ways to obtain each partial string $s$ after fixing first $i$ remainders. Of course, we don't have to store all $2^{m}$ masks, but just the reachable ones. Once $p_{i} > m$, each choice of remainder either places a single zero into a string, or doesn't change anything. At this point we are not interested in the full mask, but rather in the number of \"unsatisfied\" zeros of initial string $s$. Each transition either satisfies one zero, or doesn't change anything; the number of transitions of each kind is easy to count. We will do a full memoization DP for $p_{i}  \\le  m$, and continue with a compressed DP once $p_{i} > m$. The second part can be done in $O(nm)$ time and $O(m)$ memory. The complexity of the first part depends on the total number of states in the memoization DP. Turns out this number can be much larger than we anticipated on certain tests, for instance, primes starting from 5 or 7. On these cases, all our model solutions received time out. Such tests didn't appear in the original test set, of course. KAN and myself tried to improve the solution. The idea behind our optimization is that once $p_{i} > m / 2$, several central bits of the mask behave just like the \"unsatisfied\" bits in the large-prime part of the original solution: if we choose to cover them, it will be the single bit we cover. Thus we can do a \"hybrid\" DP that has parameters (number of unsatisfied bits in the middle, mask of all the rest bits). KAN's solution used \"naive\" mask DP for $p_{i}  \\le  23$, switched to static array for $p_{i} = 29, 31, 37$, and then proceeded to large primes as before. I tried to write a self-adaptive solution that handles all ranges of primes pretty much the same way. KAN was more successful: his solution works in $\\sim3.5$ seconds on all cases we could counstruct; my solution works in $\\sim11$ seconds and uses a lot of excess memory.",
    "tags": [
      "brute force",
      "dp",
      "math",
      "meet-in-the-middle",
      "number theory"
    ],
    "rating": 3200
  },
  {
    "contest_id": "766",
    "index": "A",
    "title": "Mahmoud and Longest Uncommon Subsequence",
    "statement": "While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.\n\nGiven two strings $a$ and $b$, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.\n\nA subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings \"ac\", \"bc\", \"abc\" and \"a\" are subsequences of string \"abc\" while strings \"abbc\" and \"acb\" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.",
    "tutorial": "If the strings are the same, Any subsequence of $a$ is indeed a subsequence of $b$ so the answer is \"-1\", Otherwise the longer string can't be a subsequence of the other (If they are equal in length and aren't the same, No one can be a subsequence of the other) so the answer is maximum of their lengths. Time complexity : $O(|a| + |b|)$.",
    "code": "\"#include <iostream>\\n#include <string.h>\\nusing namespace std;\\nint main()\\n{\\n\\tstring a,b;\\n\\tcin >> a >> b;\\n\\tif (a==b)\\n\\tcout << -1;\\n\\telse\\n\\tcout << max(a.size(),b.size());\\n}\"",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "766",
    "index": "B",
    "title": "Mahmoud and a Triangle",
    "statement": "Mahmoud has $n$ line segments, the $i$-th of them has length $a_{i}$. Ehab challenged him to use \\textbf{exactly $3$} line segments to form a non-degenerate triangle. Mahmoud doesn't accept challenges unless he is sure he can win, so he asked you to tell him if he should accept the challenge. Given the lengths of the line segments, check if he can choose exactly $3$ of them to form a non-degenerate triangle.\n\nMahmoud should use exactly $3$ line segments, he can't concatenate two line segments or change any length. A non-degenerate triangle is a triangle with positive area.",
    "tutorial": "Let $x$, $y$ and $z$ be the lengths of 3 line segments such that $x  \\le  y  \\le  z$, If they can't form a non-degenerate triangle, Line segments of lengths $x - 1$, $y$ and $z$ or $x$, $y$ and $z + 1$ can't form a non-degenerate triangle, So we don't need to try all the combinations, If we try $y$ as the middle one, We need to try the maximum $x$ that is less than or equal to $y$ and the minimum $z$ that is greater than or equal to $y$, The easiest way to do so is to sort the line segments and try every consecutive 3. Time complexity : $O(nlog(n))$. Depending on the note from the first solution, If we try to generate a sequence such that after sorting, Every consecutive 3 line segments will form a degenerate triangle, It will be $1$ $1$ $2$ $3$ $5$ $8$ $13$ $...$ which is Fibonacci sequence, Fibonacci is a fast growing sequence, $fib(45) = 1134903170$, Notice that Fibonacci makes maximum $n$ with \"NO\" as the answer, That means the answer is indeed \"YES\" for $n  \\ge  45$, For $n < 45$, You can do the naive $O(n^{3})$ solution or the first solution. Let $x$ be the number that satisfies these inequalities:- $fib(x)  \\le  maxAi$. $fib(x + 1) > maxAi$. Time complexity : $O(x^{3})$ or $O(xlog(x))$.",
    "code": "\"#include <iostream>\\n#include <algorithm>\\nusing namespace std;\\nbool check(int a,int b,int c)\\n{\\n\\tint tmp[]={a,b,c};\\n\\tsort(tmp,tmp+3);\\n\\treturn (tmp[0]+tmp[1]>tmp[2]);\\n}\\nint main()\\n{\\n\\tint n;\\n\\tcin >> n;\\n\\tif (n>=45)\\n\\tcout << \\\"YES\\\";\\n\\telse\\n\\t{\\n\\t\\tint arr[n];\\n\\t\\tfor (int i=0;i<n;i++)\\n\\t\\tcin >> arr[i];\\n\\t\\tfor (int i=0;i<n;i++)\\n\\t\\t{\\n\\t\\t\\tfor (int x=i+1;x<n;x++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tfor (int j=x+1;j<n;j++)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tif (check(arr[i],arr[x],arr[j]))\\n\\t\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\tcout << \\\"YES\\\";\\n\\t\\t\\t\\t\\t\\treturn 0;\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tcout << \\\"NO\\\";\\n\\t}\\n}\"",
    "tags": [
      "constructive algorithms",
      "geometry",
      "greedy",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "766",
    "index": "C",
    "title": "Mahmoud and a Message",
    "statement": "Mahmoud wrote a message $s$ of length $n$. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number $i$ in the English alphabet to be written on it in a string of length more than $a_{i}$. For example, if $a_{1} = 2$ he can't write character 'a' on this paper in a string of length $3$ or more. String \"aa\" is allowed while string \"aaa\" is not.\n\nMahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be $n$ and they shouldn't overlap. For example, if $a_{1} = 2$ and he wants to send string \"aaa\", he can split it into \"a\" and \"aa\" and use $2$ magical papers, or into \"a\", \"a\" and \"a\" and use $3$ magical papers. He can't split it into \"aa\" and \"aa\" because the sum of their lengths is greater than $n$. He can split the message into single string if it fulfills the conditions.\n\nA substring of string $s$ is a string that consists of some consecutive characters from string $s$, strings \"ab\", \"abc\" and \"b\" are substrings of string \"abc\", while strings \"acb\" and \"ac\" are not. Any string is a substring of itself.\n\nWhile Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions:\n\n- How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is $n$ and they don't overlap? Compute the answer modulo $10^{9} + 7$.\n- What is the maximum length of a substring that can appear in some valid splitting?\n- What is the minimum number of substrings the message can be spit in?\n\nTwo ways are considered different, if the sets of split positions differ. For example, splitting \"aa|a\" and \"a|aa\" are considered different splittings of message \"aaa\".",
    "tutorial": "Let $dp[i]$ be the number of ways to split the prefix of $s$ ending at index $i$ into substrings that fulfills the conditions. Let it be 1-indexed. Our base case is $dp[0] = 1$. Our answer is $dp[n]$. Now let's calculate it for every $i$. Let $l$ be the minimum possible index such that the substring from $l$ to $i$ satisfies the condition, Let $x$ be a moving pointer, At the beginning $x = i - 1$ and it decreases, Every time we decrease $x$, We calculate the new value of $l$ depending on the current character like that, $l = max(l, i - a_{s[x]})$. While $x$ is greater than or equal to $l$ we add $dp[x]$ to $dp[i]$, To find the longest substring, Find maximum $i - x$, To find the minimum number of substrings, there is an easy greedy solution, Find the longest valid prefix and delete it and do the same again until the string is empty, The number of times this operation is repeated is our answer, Or see the dynamic programming solution in the code. Time complexity : $O(n^{2})$. Try to find an $O(n)$ solution(I'll post a hard version of some problems on this blog soon).",
    "code": "\"#include <iostream>\\n#include <string.h>\\nusing namespace std;\\n#define mod 1000000007\\nstring s;\\nint arr[26],dp[1005],dp2[1005];\\nint main()\\n{\\n\\tint n,l=0;\\n\\tcin >> n >> s;\\n\\tfor (int i=0;i<26;i++)\\n\\tcin >> arr[i];\\n\\tdp[0]=1;\\n\\tdp2[0]=0;\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\tint f=0;\\n\\t\\tdp2[i]=n;\\n\\t\\tfor (int x=i-1;x>=0;x--)\\n\\t\\t{\\n\\t\\t\\tf=max(f,i-arr[s[x]-'a']);\\n\\t\\t\\tif (f>x)\\n\\t\\t\\tcontinue;\\n\\t\\t\\tdp[i]=(dp[i]+dp[x])%mod;\\n\\t\\t\\tdp2[i]=min(dp2[i],1+dp2[x]);\\n\\t\\t\\tl=max(l,i-x);\\n\\t\\t}\\n\\t}\\n\\tcout << dp[n] << endl << l << endl << dp2[n] << endl;\\n}\"",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "766",
    "index": "D",
    "title": "Mahmoud and a Dictionary",
    "statement": "Mahmoud wants to write a new dictionary that contains $n$ words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.\n\nHe know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.\n\nSometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.\n\nAfter Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.\n\nAfter adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.",
    "tutorial": "Let's build a graph containing the words, For every relation in the input add a new edge with the weight of $0$ if they are equal and $1$ if they are opposites, If adding the edge doesn't make the graph cyclic, Our relation is valid, Otherwise it may be valid or invalid so we'll answer them offline. Check if adding that edge will make the graph cyclic or not using union-find like Kruskal's algorithm. Suspend answering relations that will make the graph cyclic, Now we have a forest of trees, Let $cum[i]$ be the xor of the weights on the edges in the path from the root of the component of node $i$ to node $i$. Calculate it using dfs. To find the relation between 2 words $u$ and $v$, Check if they are in the same component using union-find, If they aren't, The answer is $3$ otherwise the answer is $\\left(c u m[u]\\oplus c u m[v]\\right)+1$, Now to answer suspended relations, Find the relation between the 2 words and check if it's the same as the input relation, Then answer the queries. Time complexity : $O((n + m + q)log(n) * maxL)$ where $maxL$ is the length of the longest string considering that union-find works in constant time.",
    "code": "#include <iostream>\n#include <string.h>\n#include <vector>\n#include <map>\nusing namespace std;\nmap<string,int> m;\npair<int,int> arr[100005];\nvector<pair<int,int> > v[100005];\nvector<pair<pair<int,int>,pair<int,int> > > sus;\nbool valid[100005],vis[100005];\nint n,cum[100005];\nint find(int x)\n{\n    if (x!=arr[x].first)\n    x=find(arr[x].first);\n    return arr[x].first;\n}\nbool Union(int x,int y)\n{\n    x=find(x);\n    y=find(y);\n    if (x==y)\n    return 0;\n    if (arr[x].second<arr[y].second)\n    arr[x].first=y;\n    else if (arr[x].second>arr[y].second)\n    arr[y].first=x;\n    else\n    {\n        arr[x].first=y;\n        arr[y].second++;\n    }\n    return 1;\n}\nvoid dfs(int node,int pnode,int x)\n{\n    vis[node]=1;\n    cum[node]=x;\n    for (int i=0;i<v[node].size();i++)\n    {\n        if (v[node][i].first!=pnode)\n        dfs(v[node][i].first,node,(x^v[node][i].second));\n    }\n}\nvoid preprocess()\n{\n    for (int i=0;i<n;i++)\n    {\n        if (!vis[i])\n        dfs(i,i,0);\n    }\n    for (int i=0;i<sus.size();i++)\n    {\n        int x=sus[i].first.first,y=sus[i].first.second,idx=sus[i].second.first,r=sus[i].second.second;\n        if ((cum[x]^cum[y])==r)\n        valid[idx]=1;\n        else\n        valid[idx]=0;\n    }\n}\nint main()\n{\n    int q1,q2;\n    cin >> n >> q1 >> q2;\n    for (int i=0;i<n;i++)\n    {\n        string s;\n        cin >> s;\n        m[s]=i;\n        arr[i]=make_pair(i,0);\n    }\n    for (int i=0;i<q1;i++)\n    {\n        int t;\n        string s1,s2;\n        cin >> t >> s1 >> s2;\n        int x=m[s1],y=m[s2];\n        if (Union(x,y))\n        {\n            v[x].push_back(make_pair(y,t-1));\n            v[y].push_back(make_pair(x,t-1));\n            valid[i]=1;\n        }\n        else\n        sus.push_back(make_pair(make_pair(x,y),make_pair(i,t-1)));\n    }\n    preprocess();\n    for (int i=0;i<q1;i++)\n    {\n        if (valid[i])\n        cout << \"YES\" << endl;\n        else\n        cout << \"NO\" << endl;\n    }\n    while (q2--)\n    {\n        int t;\n        string s1,s2;\n        cin >> s1 >> s2;\n        int x=m[s1],y=m[s2];\n        if (find(x)!=find(y))\n        cout << 3 << endl;\n        else if (cum[x]^cum[y])\n        cout << 2 << endl;\n        else\n        cout << 1 << endl;\n    }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "766",
    "index": "E",
    "title": "Mahmoud and a xor trip",
    "statement": "Mahmoud and Ehab live in a country with $n$ cities numbered from $1$ to $n$ and connected by $n - 1$ undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number $a_{i}$ attached to it.\n\nWe define the distance from city $x$ to city $y$ as the xor of numbers attached to the cities on the path from $x$ to $y$ \\textbf{(including both $x$ and $y$)}. In other words if values attached to the cities on the path from $x$ to $y$ form an array $p$ of length $l$ then the distance between them is $p_{1}\\oplus p_{2}\\oplus\\cdot\\cdot\\Leftrightarrow p_{l}$, where $\\mathbb{C}$ is bitwise xor operation.\n\nMahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities.",
    "tutorial": "If we have an array $ans[i]$ which represents the number of paths that makes the $i^{th}$ bit sit to $1$, Our answer will be $\\sum_{i=0}^{l o g(n)}2^{i}*a n s[i]$ Let $arr[i][x]$ be the binary value of the $x^{th}$ bit of the number attached to node $i$(just to make work easier). There are 2 types of paths from node $u$ to node $v$ where $u$ is less in depth than or equal to $v$, Paths going down which are paths with $lca(u, v)$=$u$ and other paths, Let's root the tree at node $1$ and dfs, let current node be $node$, Let $dp[i][x][j]$ be the number of paths going down from node $i$ that makes the $x^{th}$ bit's value equal to $j$. A path going down from node $i$ is a path going down from a child of $i$ with node $i$ concatenated to it so let's calculate our $dp$. A path that isn't going down is a concatenation of 2 paths which are going down from $lca(u, v)$, Now we can calculate $ans$. See the code for formulas. Time complexity : $O(nlog(a_{i}))$.",
    "code": "\"#include <iostream>\\n#include <iomanip>\\n#include <string.h>\\n#include <vector>\\nusing namespace std;\\nvector<int> v[100005];\\nint arr[100005][25];\\nlong long dp[100005][25][2],ans[25];\\nvoid dfs(int node,int pnode)\\n{\\n\\tlong long s[25][2];\\n\\tmemset(s,0,sizeof(s));\\n\\tfor (int i=0;i<25;i++)\\n\\tdp[node][i][arr[node][i]]=1;\\n\\tfor (int i=0;i<v[node].size();i++)\\n\\t{\\n\\t\\tif (v[node][i]!=pnode)\\n\\t\\t{\\n\\t\\t\\tdfs(v[node][i],node);\\n\\t\\t\\tfor (int j=0;j<25;j++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tfor (int x=0;x<2;x++)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tdp[node][j][x]+=dp[v[node][i]][j][x^arr[node][j]];\\n\\t\\t\\t\\t\\ts[j][x]+=dp[v[node][i]][j][x];\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tfor (int j=0;j<25;j++)\\n\\t{\\n\\t\\tlong long x0=0,x1=0;\\n\\t\\tfor (int i=0;i<v[node].size();i++)\\n\\t\\t{\\n\\t\\t\\tif (v[node][i]!=pnode)\\n\\t\\t\\t{\\n\\t\\t\\t\\tx0+=(s[j][1]-dp[v[node][i]][j][1])*dp[v[node][i]][j][1]+(s[j][0]-dp[v[node][i]][j][0])*dp[v[node][i]][j][0];\\n\\t\\t\\t\\tx1+=(s[j][1]-dp[v[node][i]][j][1])*dp[v[node][i]][j][0]+(s[j][0]-dp[v[node][i]][j][0])*dp[v[node][i]][j][1];\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif (arr[node][j])\\n\\t\\tans[j]+=x0/2;\\n\\t\\telse\\n\\t\\tans[j]+=x1/2;\\n\\t}\\n\\tfor (int j=0;j<25;j++)\\n\\tans[j]+=dp[node][j][1];\\n}\\nint main()\\n{\\n\\tint n;\\n\\tcin >> n;\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\tint a;\\n\\t\\tcin >> a;\\n\\t\\tfor (int x=0;x<25;x++)\\n\\t\\tarr[i][x]=(bool)(a&(1<<x));\\n\\t}\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tint a,b;\\n\\t\\tcin >> a >> b;\\n\\t\\tv[a].push_back(b);\\n\\t\\tv[b].push_back(a);\\n\\t}\\n\\tdfs(1,0);\\n\\tlong long res=0;\\n\\tfor (int i=0;i<25;i++)\\n    res+=(ans[i]*(1LL<<i));\\n\\tcout<< res << endl;\\n}\"",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "767",
    "index": "A",
    "title": "Snacktower",
    "statement": "According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time $n$ snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.\n\nYears passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.\n\nHowever, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.\n\nWrite a program that models the behavior of Ankh-Morpork residents.",
    "tutorial": "It is enough to do what is written in the statements. You can maintain an array $has$, and mark in it which snacks has already fallen, and which hasn't. Create another variable $next$ which tracks the next snack which should be put on the top. Let's proceed with the integers in the input one by one. After reading next integer, mark it in the $has$ array and go from $next$ to the first snack which is not marked. Print all integers which we passed by.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "767",
    "index": "B",
    "title": "The Queue",
    "statement": "Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.\n\nHe knows that the receptionist starts working after $t_{s}$ minutes have passed after midnight and closes after $t_{f}$ minutes have passed after midnight (so that $(t_{f} - 1)$ is the last minute when the receptionist is still working). The receptionist spends exactly $t$ minutes on each person in the queue. If the receptionist would stop working within $t$ minutes, he stops serving visitors (other than the one he already serves).\n\nVasya also knows that exactly $n$ visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately.\n\n\\begin{center}\n{\\small \"Reception 1\"}\n\\end{center}\n\nFor each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them.\n\nVasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him!",
    "tutorial": "Let's calculate the point of time when each visitor would be served. Let array $a$ contain the points of time when visitors arrive. The receptionist would begin to serve the first visitor at the point of time when the receptionist begins to work $t_{s}$, if the first visitor came to the passport office before it, or when he comes to the office, if he didn't. We can calculate the point of time when the receptionist would begin to serve the $i$-th visitor in the same way if we know when the receptionist began to serve the $i - 1$-th visitor. Let's suppose that the receptionist began to serve the $i - 1$-th visitor at $b_{i - 1}$ minute. It means that receptionist would begin to serve the $i$-th visitor no sooner than $t$ minutes later, that is $b_{i - 1} + t$ minute. The receptionist would begin to serve him at this point of time if $i$-th visitor came before ($a_{i}  \\le  b_{i - 1} + t$). If he came later, his serving would begin when he comes. This way we will find the time $b_{i}$ when the receptionist would begin to serve him. If any visitor came later than the previous visitor was served ($a_{i} > b_{i - 1} + t$), the receptionist was free. It means that Vasya can be served immediately if he arrives at the proper time, for example, at $b_{i - 1} + t$ minute. If there are no such visitors, to be the $i$-th person served this day, Vasya has to arrive at the passport office no later than $(a_{i} - 1)$ and he would have to wait a minimum of $b_{i} - (a_{i} - 1)$ minutes. From all of these options we have to find a point of time with the minimal waiting time. There are several special cases we have to consider: If $i$-th and $(i - 1)$-th visitors arrived at the same time, Vasya can't arrive between them. Some visitors wouldn't be served this day if the time the receptionist would begin to serve them is more or equal to $T_{f} - t$ and that means we shouldn't attive to the passport office after them. Vasya can be the last person served this day if there are at least $t$ minutes between the point of time receptionist serves the last customer and the point of time he stops working. Vasya can be the first person served only if he comes before every other visitor. Considering the $10^{12}$ bound, all calculations should use the 64-bit data. To conclude, this task is reduced to careful calculation of the visitors' serving times ($O(n)$ time), considering the aforementioned edge cases.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "767",
    "index": "C",
    "title": "Garland",
    "statement": "Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.\n\nThere was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp.\n\nHelp Dima to find a suitable way to cut the garland, or determine that this is impossible.\n\nWhile examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.",
    "tutorial": "We can note that the given graph is a tree. Let's perform a dfs from the root of the tree. Let's calculate the sums if $t_{i}$ in each subtree, let this value be $s_{v}$ for the subtree of the vertex $v$. In order to compute $s_{v}$ we need to recursively call dfs from all sons of $v$ and add the value $t_{v}$. Let the overall sum of $t_{i}$ be equal to $x$. If $x$ is not divisible by three, there is no answer. Otherwise there are two different cases (let the answer lamps be $v_{1}$ and $v_{2}$) to obtain three subtrees with equal sum ($x / 3$): 1. One of the vertices is an ancestor of the other (we can think that $v_{2}$ is ancestor of $v_{1}$), then $s_{v2} = 2x / 3$, $s_{v1} = x / 3$. 2. Neither $v_{1}$ nor $v_{2}$ is ancestor of the other. In this case $s_{v1} = s_{v2} = x / 3$ To check the first option, it is enough to track is the dfs if there is at least one vertex $u$ in the subtree of current vertex $v$ with sum $s_{u} = x / 3$. If there is one, and $s_{v} = 2x / 3$, then there is an answer $v_{2} = v, v_{1} = u$. To check the second option, let's write down all vertices $v$ such that $s_{v} = x / 3$ and there isno other $u$ with $s_{u} = x / 3$ in the subtree of $v$. Note that we do the same thing when checking the first option. So, if there are at least two vertices we wrote down, they form the answer we are looking for.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "767",
    "index": "D",
    "title": "Cartons of milk",
    "statement": "Olya likes milk very much. She drinks $k$ cartons of milk each day if she has at least $k$ and drinks all of them if she doesn't. But there's an issue — expiration dates. Each carton has a date after which you can't drink it (you still can drink it exactly at the date written on the carton). Due to this, if Olya's fridge contains a carton past its expiry date, she throws it away.\n\nOlya hates throwing out cartons, so when she drinks a carton, she chooses the one which expires the fastest. It's easy to understand that this strategy minimizes the amount of cartons thrown out and lets her avoid it if it's even possible.\n\n\\begin{center}\n{\\small Milk. Best before: 20.02.2017.}\n\\end{center}\n\nThe main issue Olya has is the one of buying new cartons. Currently, there are $n$ cartons of milk in Olya's fridge, for each one an expiration date is known (how soon does it expire, measured in days). In the shop that Olya visited there are $m$ cartons, and the expiration date is known for each of those cartons as well.\n\nFind the maximum number of cartons Olya can buy so that she wouldn't have to throw away any cartons. Assume that Olya drank no cartons today.",
    "tutorial": "Let $t$ be the maximum expiry date in the input. The key observation in this problem is the fact that if we can buy some $x$ cartons from the shop and not have to throw away the cartons, we can buy $x$ cartons with the biggest expiry dates and we won't have to throw away any cartons either. It happens because if we increase the carton's expiry date while having fixed distribution of cartons per days, the distribution would stay correct. Then, let's learn to check for an arbitrary $x$ is it true that if we take $x$ cartons with the maximum expiry dates we can distribute those cartons per days so that we won't have to throw cartons away. To do this, it is sufficient to check for each day $i$ from $0$ to $t$ that the amount of cartons with expiry dates $ \\le  i$ (both from a fridge and bought) is no bigger than $(i + 1)k$. Then the solution would be to search for maximum $x$ using the binary search. If $z$ is the answer, the check would pass for all $x$ from $0$ to $z$ and wouldn't for $x > z$, this monotony is sufficient for the binary search to work. Then we output the found $z$ and the $z$ cartons with maximum expiry dates (we don't even have to sort $s_{i}$, we can justdo an enumeration sort because $s_{i}  \\le  10^{7}$). This soluton runs in $O(tlogm)$ time.",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "767",
    "index": "E",
    "title": "Change-free",
    "statement": "Student Arseny likes to plan his life for $n$ days ahead. He visits a canteen every day and he has already decided what he will order in each of the following $n$ days. Prices in the canteen do not change and that means Arseny will spend $c_{i}$ rubles during the $i$-th day.\n\nThere are $1$-ruble coins and $100$-ruble notes in circulation. At this moment, Arseny has $m$ coins and a sufficiently large amount of notes (you can assume that he has an infinite amount of them). Arseny loves modern technologies, so he uses his credit card everywhere except the canteen, but he has to pay in cash in the canteen because it does not accept cards.\n\nCashier always asks the student to pay change-free. However, it's not always possible, but Arseny tries to minimize the dissatisfaction of the cashier. Cashier's dissatisfaction for each of the days is determined by the total amount of notes and coins in the change. To be precise, if the cashier gives Arseny $x$ notes and coins on the $i$-th day, his dissatisfaction for this day equals $x·w_{i}$. Cashier always gives change using as little coins and notes as possible, he always has enough of them to be able to do this.\n\n\\begin{center}\n{\\small \"Caution! Angry cashier\"}\n\\end{center}\n\nArseny wants to pay in such a way that the total dissatisfaction of the cashier for $n$ days would be as small as possible. Help him to find out how he needs to pay in each of the $n$ days!\n\nNote that Arseny always has enough money to pay, because he has an infinite amount of notes. Arseny can use notes and coins he received in change during any of the following days.",
    "tutorial": "The first thing to note is that during day $i$ it makes sense to either pay $c_{i}\\mathrm{~div~}100$ notes and $c_{i}{\\mathrm{~mod~}}100$ coins (in this case, the cashier's dissatisfaction would be equal to $0$), or just $c_{i}\\,\\mathrm{div}\\,100+1$ notes (in that case, the cashier's dissatisfaction would be equal to $(100-(c_{i}\\;{\\mathrm{mod}}\\;100))\\,w_{i}$)/ Moreover, the second case is impossible if $c_{i}{\\mathrm{~mod~}}100=0$, so in that case you just have to pay the required amount of notes. In order to solve the problem, we have to note the additional fact. Let's suppose Arseny paid change-free during the $i$-th day and gave the cashier $c_{i}{\\mathrm{~mod~}}100$ coins. Then, if we change the payment way this day, the amount of coins availible to Arseny would increase by $100$ regardless of the $c_{i}$! Indeed, Arseny wouldn't spend those $c_{i}{\\mathrm{~mod~}}100$ coins, and he would aso receive $100-(c_{i}{\\mathrm{~mod~}}100)$ coins in change, which adds up to exactly $100$ coins. Let's build the optimal solution day-by-day beginning from day one, trying to pay change-free every time to minimize the cashier's dissatisfaction. Let $i$-th day be the first one when Arseny wouldn't be able to pay change-free. It means that Arseny has to get some change at least once during days from first to $i$-th. But, regardless of the day, after $i$-th day he would have the same amount of coins! It means that the optimal way is to get change during the day when the cashier's dissatisfaction would be minimal. Then, let's continue to pay change-free whenever we can. If Arseny again can't pay change-free during day $j$, there must be a day from first to $j$-th when he got change. Using similiar considerations, whe should choose the day with the minimal cashier's dissatisfaction (except the first one). We should do these operations until we process all days. The simple implementation of this process works in $O(n^{2})$ time and hits TLE. But if you use any structure of data which allows you to add or delete element or find minimum in $O(\\log n)$ time, for example, heap or binary seach tree, we can save all previous days into it and find a day with the minimal cashier's dissatisfaction faster than $O(n)$. The final time is $O(n\\log n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "768",
    "index": "A",
    "title": "Oath of the Night's Watch",
    "statement": "\"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come.\" — The Night's Watch oath.\n\nWith that begins the watch of Jon Snow. He is assigned the task to support the stewards.\n\nThis time he has $n$ stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.\n\nCan you find how many stewards will Jon support?",
    "tutorial": "You just have to find the number of elements greater than the minimum number occurring in the array and less than the maximum number occurring in the array. This can be done in $O(n)$ by traversing the array once and finding the minimum and maximum of the array, and then in another traversal, find the good numbers. Complexity: $O(n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint a[100005];\nint main()\n{\n\tint n,c1=0,c2=0,mx=0,mn=1000000007;\n\tcin>>n;\n\tfor(int i=0;i<n;i++) \n\t{\n\t\tcin>>a[i];\n\t\tmx=max(mx,a[i]),mn=min(mn,a[i]);\n\t}\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tif(a[i]==mx) c1++;\n\t\tif(a[i]==mn) c2++;\n\t}\n\tif(mx==mn) cout<<0;\n\telse cout<<(n-c1-c2); \n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "768",
    "index": "B",
    "title": "Code For 1",
    "statement": "Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility.\n\nInitially Sam has a list with a single element $n$. Then he has to perform certain operations on this list. In each operation Sam must remove any element $x$, such that $x > 1$, from the list and insert at the same position $\\left|{\\frac{x}{2}}\\right|$, $x\\ {\\mathrm{mod}}\\ 2$, $\\left|{\\frac{x}{2}}\\right|$ sequentially. He must continue with these operations until all the elements in the list are either $0$ or $1$.\n\nNow the masters want the total number of $1$s in the range $l$ to $r$ ($1$-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?",
    "tutorial": "It is easy to see that the total number of elements in the final list will be $2^{\\lfloor\\log_{2}n\\rfloor+1}-1$ . The problem can be solved by locating each element in the list and checking whether it is $'1'$ .The $i^{th}$ element can be located in $O(logn)$ by using Divide and Conquer strategy. Answer is the total number of all such elements which equal $'1'$. Complexity : $O((r - l + 1) * logn)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nlong long int cnt(long long int temp) //returns the length of final list \n{\n  long long int x=1;\n  while(temp>1)\n  {\n    temp/=2;\n    x*=2;\n  }\n  return x;\n}\nint is_one(long long int pos,long long int target,long long int num)\n{ \n  if(num<2)\n    return num;\n  if(pos+1==2*target)\n  {\n    return num%2;\n  }\n  num/=2;\n  pos/=2;   \n  if(target>pos+1)\n      target-=(pos+1);      \n  return is_one(pos,target,num);\n}\nint main()\n{\n  long long int l,r,n,x,ans=0,i;\n  cin>>n>>l>>r;\n  x=cnt(n);\n  x=2*x-1;\n  for(i=l; i<=r; i++)  ans+=is_one(x,i,n);\n  cout<<ans<<endl;  \n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "divide and conquer"
    ],
    "rating": 1600
  },
  {
    "contest_id": "768",
    "index": "C",
    "title": "Jon Snow and his Favourite Number",
    "statement": "Jon Snow now has to fight with White Walkers. He has $n$ rangers, each of which has his own strength. Also Jon Snow has his favourite number $x$. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number $x$, he might get soldiers of high strength. So, he decided to do the following operation $k$ times:\n\n- Arrange all the rangers in a straight line in the order of increasing strengths.\n- Take the bitwise XOR (is written as $\\mathbb{C}$) of the strength of each alternate ranger with $x$ and update it's strength.\n\nSuppose, Jon has $5$ rangers with strengths $[9, 7, 11, 15, 5]$ and he performs the operation $1$ time with $x = 2$. He first arranges them in the order of their strengths, $[5, 7, 9, 11, 15]$. Then he does the following:\n\n- The strength of first ranger is updated to $5\\oplus2$, i.e. $7$.\n- The strength of second ranger remains the same, i.e. $7$.\n- The strength of third ranger is updated to $9\\oplus2$, i.e. $11$.\n- The strength of fourth ranger remains the same, i.e. $11$.\n- The strength of fifth ranger is updated to $15\\oplus2$, i.e. $13$.\n\nThe new strengths of the $5$ rangers are $[7, 7, 11, 11, 13]$Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations $k$ times. He wants your help for this task. Can you help him?",
    "tutorial": "The range of strengths of any ranger at any point of time can be [0,1023]. This allows us to maintain a frequency array of the strengths of the rangers. Now, the updation of the array can be done in the following way: Make a copy of the frequency array. If the number of rangers having strength less than a strength $y$ is even, and there are $freq[y]$ rangers having strength y, ceil($freq[y] / 2$) rangers will be updated and will have strengths $y$^$x$, and the remaining will retain the same strength. If the number of rangers having strength less than a strength $y$ is odd,and there are $freq[y]$ rangers having strength y, floor($freq[y] / 2$) rangers will be updated and will have strengths $y$^$x$, and remaining will have the same strength. This operation has to be done $k$ times, thus the overall complexity is $O(1024 * k)$. Complexity: $O(k * 2^{10})$",
    "code": "#include<bits/stdc++.h>\n#define rep(i,start,lim) for(int i=start;i<lim;i++)\nusing namespace std;\n#define N 100005\nint freq[1100],tmp[1024];\nint main()\n{\n\tint n,k,maxm=0,minm=INT_MAX,p,x;\n\tcin>>n>>k>>x;\n\trep(i,0,n) cin>>p,freq[p]++;\n\trep(i,0,k)\n\t{\n\t\trep(j,0,1024) tmp[j]=freq[j];\n\t\tint par=0;\n\t\trep(j,0,1024)\n\t\t{\n\t\t\tif(freq[j]>0)\n\t\t\t{\n\t\t\t\tint curr = (j^x),change = (freq[j]/2);\n\t\t\t\tif(par==0) change+=(freq[j]&1);\n\t\t\t\ttmp[j]-=change;\n\t\t\t\ttmp[curr]+=change;\n\t\t\t\tpar^=(freq[j]&1);\n\t\t\t}\n\t\t}\n\t\trep(j,0,1024) freq[j]=tmp[j]; \n\t}\n\trep(i,0,1024) if(freq[i]>0) minm=min(minm,i),maxm=max(maxm,i);\n\tcout<<maxm<<\" \"<<minm;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "768",
    "index": "D",
    "title": "Jon and Orbs",
    "statement": "Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are $k$ different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least $\\frac{p_{i}-\\varepsilon}{2000}$, where $ε < 10^{ - 7}$.\n\nTo better prepare himself, he wants to know the answer for $q$ different values of $p_{i}$. Since he is busy designing the battle strategy with Sam, he asks you for your help.",
    "tutorial": "This problem can be solve using inclusion-exclusion principle but precision errors need to be handled. Therefore, we use the following dynamic programming approach to solve this problem. On $n - th$ day there are two possibilities, Case-1 : Jon doesn't find a new orb then the probability of it is $\\scriptstyle{\\frac{\\pi}{n}}$. Case-2 : Jon does find a new orb then the probability of it is $\\scriptstyle{\\frac{k-x+1}{n}}$. Therefore, $d p[n][x]={\\textstyle\\frac{x}{k}}\\cdot d p[n-1][x]+{\\frac{k-x+1}{k}}\\cdot d p[n-1][x-1]$ We need to find the minimum $n$ such that $d p[n][k]\\geqslant{\\frac{p_{i}}{2000}}.$ where, $n$ = number of days Jon waited. $x$ = number of distinct orbs Jon have till now. $dp[n][x]$ = probability of Jon having $x$ distinct orbs in $n$ days. $k$ = Total number of distinct orbs possible. PS:The $ \\epsilon $ was added so that the any solution considering the probability in the given range $\\left({\\frac{p_{i}-\\epsilon}{2000}},\\;{\\frac{p_{i}}{2000}}\\right)$ passes the system tests.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1004;\nconst double eps = 1e-7;\ndouble dp[N];\nint ans[N];\n\nint main(){\n\tint k, q, d = 1;\n\tcin >> k >> q;\n\tdp[0] = 1;\n\tfor(int n = 1; d <= 1000; ++n){\n\t\tfor(int x = k; x > 0; --x){\n\t\t\tdp[x] = (x * dp[x] + (k - x + 1) * dp[x - 1]) / k;\n\t\t}\n\t\twhile(d <= 1000 && 2000 * dp[k] >= (d - eps)){\n\t\t\tans[d] = n;\n\t\t\td++;\n\t\t}\n\t\tdp[0] = 0;\n\t}\n\twhile(q--){\n\t\tint x;\n\t\tcin >> x;\n\t\tcout << ans[x] << \"\\n\";\n\t}\n}",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "768",
    "index": "E",
    "title": "Game of Stones",
    "statement": "Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple:\n\n- The game starts with $n$ piles of stones indexed from $1$ to $n$. The $i$-th pile contains $s_{i}$ stones.\n- The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of $0$ stones does not count as a move.\n- The player who is unable to make a move loses.\n\nNow Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game.\n\nIn this modified version, no move can be made more than once on a pile. For example, if $4$ stones are removed from a pile, $4$ stones cannot be removed from that pile again.\n\nSam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally.",
    "tutorial": "This problem can be solved using DP with Bitmasks to calculate the grundy value of piles. Let us have a 2-dimensional dp table, $dp[i][j]$, where the first dimension is for number of stones in the pile and second dimension is for bitmask. The bitmask has $k$-th bit set if we are allowed to remove $k + 1$ stones from the pile. Now, to calculate $dp[i][j]$ we need to iterate over all possible moves allowed and find the mex. Finally for the game, we use the grundy values stored in $dp[i][2^{i} - 1]$ for a pile of size $i$. We take the xor of grundy values of all piles sizes. If it is 0, then Jon wins, otherwise Sam wins. The complexity of this solution is $O(n*2^{n}*\\log n)$. This will not be accepted. We can use the following optimizations for this problem: So we can rewrite the above code to incorporate these change. Hence, the final solution is as follows Bonus: Try to find and prove the $O(1)$ formula for grundy values",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nmap<pair<int, ll>, int> grundy;\nmap<pair<int, ll>, bool> mp;\n\nint retgrundy(int ps, ll bm, int prev = 63){\n    for(int i=ps ; i<prev ; ++i){\n        if(((bm>>i)&1LL) == 1LL)\n            bm ^= (1LL<<i);\n    }\n    if(mp[{ps, bm}])\n        return grundy[{ps, bm}];\n    vector<bool> marked(63, false);\n    for(int k=0 ; k<ps ; ++k){\n        if(((bm>>k)&1LL) == 0)\n            continue;\n        marked[retgrundy(ps-k-1LL, (bm^(1LL<<k)), ps)] = true;\n    }\n    int ret;\n    for(int i=0 ; i<63 ; ++i){\n        if(marked[i])\n            continue;\n        grundy[{ps, bm}] = i;\n        ret = i;\n        break;\n    }\n    mp[{ps, bm}] = true;\n    return ret;\n}\n\nint main(){\n    int n, in, x=0;\n    scanf(\"%d\", &n);\n\n    grundy[{0, 0}] = 0;\n    mp[{0, 0}] = true;\n    vector<int> gr(70, 0);\n\n    for(int i=0 ; i<=60 ; ++i)\n        gr[i] = retgrundy(i, (1LL<<i)-1LL);\n\n    while(n--){\n        scanf(\"%d\", &in);\n        x ^= gr[in];\n    }\n\n    if(x == 0)\n        printf(\"YES\");\n    else\n        printf(\"NO\");\n\n}",
    "tags": [
      "bitmasks",
      "dp",
      "games"
    ],
    "rating": 2100
  },
  {
    "contest_id": "768",
    "index": "F",
    "title": "Barrels and boxes",
    "statement": "Tarly has two different type of items, food boxes and wine barrels. There are $f$ food boxes and $w$ wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no two stacks of wine barrels are together.\n\nThe height of a stack is defined as the number of items in the stack. Two stacks are considered different if either their heights are different or one of them contains food and other contains wine.\n\nJon Snow doesn't like an arrangement if any stack of wine barrels has height less than or equal to $h$. What is the probability that Jon Snow will like the arrangement if all arrangement are equiprobably?\n\nTwo arrangement of stacks are considered different if exists such $i$, that $i$-th stack of one arrangement is different from the $i$-th stack of the other arrangement.",
    "tutorial": "Every arrangement of stacks can expressed in the form of linear arrangement. In this linear arrangement, every contiguous segment of wine barrels are separated by food boxes. For the arrangement to be liked by Jon each of the $f + 1$ partitions created by $f$ food boxes must contain either $0$ or greater than $h$ wine barrels. Let $u$ out of $f + 1$ partitions have non-zero wine barrels then the remaining $r + 1 - u$ partitions must have $0$ wine barrels.. Total number of arrangements with exactly u stacks of wine barrels are $({f}_{\\mathfrak{n}}^{\\cdot1})\\cdot X$ $\\textstyle{\\binom{f+1}{n}}$ is the number of ways of choosing $u$ partitions out of $f + 1$ partitions. $X$ is the number of ways to place $w$ wine barrels in these $u$ partitions which is equal to the coefficient of $x^{w}$ in ${x^{h + 1} \\cdot (1 + x + ...)}^{u}$. Finally we sum it up for all $u$ from $1$ to $f + 1$. So the time complexity becomes $O(w)$ with pre-processing of factorials. $w = 0$ was the corner case for which the answer was $1$. We did not anticipate it will cause so much trouble. Not placing it in the pretests was a rookie mistake.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 212345;\nconst int mod = 1000000007;\nint fac[N], ifac[N], inv[N];\n\nvoid prep(){\n    fac[0] = ifac[0] = inv[1] = 1;\n    for(int i = 1; i < N; ++i)\n        fac[i] = 1LL * i * fac[i - 1] % mod;\n    for(int i = 2; i < N; ++i) \n        inv[i] = mod - 1LL * (mod / i) * inv[mod % i] % mod;\n    for(int i = 1; i < N; ++i) \n        ifac[i] = 1LL * inv[i] * ifac[i - 1] % mod;\n}\n\nint C(int n, int r){\n    if(r < 0 || n < r) return 0;\n    return 1LL * fac[n] * ifac[n - r] % mod * ifac[r] % mod; \n}\n\nint num(int r, int b, int k){\n    if(b == 0) return 1;\n    int ans = 0;\n    for(int u = 1; u <= r + 1 && (k == 0 || u <= (b - 1) / k); ++u){\n        ans += 1LL * C(r + 1,u) * C(b - k * u - 1, u - 1) % mod;\n        ans %= mod;\n    }\n    return ans;\n}\n\nint pwr(int b, int p){\n    int r = 1;\n    while(p){\n        if(p & 1) r = 1LL * r * b % mod;\n        b = 1LL * b * b % mod;\n        p >>= 1;\n    }\n    return r;\n}\n\nint finv(int x){\n    return pwr(x, mod - 2);\n}\n\nint main(){\n    prep();\n    int f, w, h;\n    cin >> f >> w >> h;\n    int sn = num(f, w, h);\n    int sd = C(f + w, w);\n    cout << 1LL * sn * finv(sd) % mod << \"\\n\";\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "768",
    "index": "G",
    "title": "The Winds of Winter",
    "statement": "Given a rooted tree with $n$ nodes. The Night King removes exactly one node from the tree and all the edges associated with it. Doing this splits the tree and forms a forest. The node which is removed is not a part of the forest.\n\nThe root of a tree in the forest is the node in that tree which does not have a parent. We define the strength of the forest as the size of largest tree in forest.\n\nJon Snow wants to minimize the strength of the forest. To do this he can perform the following operation at most once.\n\nHe removes the edge between a node and its parent and inserts a new edge between this node and any other node in forest such that the total number of trees in forest remain same.\n\nFor each node $v$ you need to find the minimum value of strength of the forest formed when node $v$ is removed.",
    "tutorial": "We are given a tree. We remove one node from this tree to form a forest. Strength of forest is defined as the size of largest tree in forest. We need to minimize the strength by changing the parent of atmost one node to some other node such that number of components remain same. To find the minimum value of strength we do a binary search on strength. It is possible to attain Strength $S$ if 1. There is less than one component with size greater than $S$. 2. There exists a node in maximum component with subtree size $Y$ such that, $M - Y  \\le  S$ (Here $M$ is size of maximum component and m is size of minimum component) $m + Y  \\le  S$. Then we can change the parent of this node to some node in smallest component. The problem now is to store Subtree_size of all nodes in the maximum component and perform binary search on them. We can use Stl Map for this. Let $X$ be the node which is removed and $X_{size}$ be its subtree size There are two cases now -: 1. When max size tree is child of $X$. 2. When max size tree is the tree which remains when we remove subtree of $X$ from original tree.(We refer to this as outer tree of $X$). In the second case the subtree sizes of nodes on path from root to $X$ will change when $X$ is removed. Infact their subtree size will decrease exactly by $X_{size}$. While performing binary search on these nodes there will be an offset of $X_{size}$. So we store them seperately. Now we need to maintain $3$ Maps, where $map_{children}$ : Stores the Subtree_size of all nodes present in heaviest child of $X$. $map_{parent}$ : Stores the Subtree_size of all nodes on the path from root to $X$. $map_{outer}$ : Stores the Subtree_size of all nodes in outer tree which are not on path from root to $X$. Go through this blog post before reading further (http://codeforces.com/blog/entry/44351). Maintaining the Maps $map_{children}$ and $map_{parent}$ are initialised to empty while $map_{outer}$ contains Subtree_size of all nodes in the tree. $map_{parent}$ : This can be easily maintained by inserting the Subtree_size of node in map when we enter a node in dfs and remove it when we exit it. $map_{children}$ : $map_{children}$ can be maintained by using the dsu on tree trick mentioned in blogpost. $map_{outer}$ : When we insert a node's subtree_size in $map_{childern}$ or $map_{parent}$ we can remove the same from $map_{outer}$ and similarly when we insert a node's Subtree_size in $map_{childern}$ or $map_{parent}$ we can remove the same from $map_{outer}$. Refer to HLD style implementation in blogpost for easiest way of maintaining $map_{outer}$. Refer to code below for exact point of insertions and deletions into above mentioned $3$ maps. Complexity $O(NlogN^{2})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 100005;\nvector<int> adj[N];\nint sz[N], ans[N];\nint n, root;\nbool big[N];\nmap<int,int> mp, mpo, par;\n\nvoid getsz(int s){\n    sz[s] = 1;\n    ans[s] = n - 1;\n    for(auto it : adj[s]){\n        getsz(it);\n        sz[s] += sz[it];\n    }\n    mpo[sz[s]]++;\n}\n\nvoid bs(map<int, int> &mp1, int l, int r, int mi, int s, int off){\n    if(mi == n - 1) return;\n    int ma = r;\n    while(r - l > 1){\n        int mid = (r + l) / 2;\n        auto it = mp1.lower_bound(ma - mid + off);\n        if(it == mp1.end()) \n            l = mid;\n        else if(mi + it->first <= mid + off) \n            r = mid;\n        else \n            l = mid;\n    }\n    ans[s] = min(ans[s], r);\n}\n\nvoid add(int s){\n    mp[sz[s]]++;\n    if(mpo[sz[s]] == 1)\n        mpo.erase(sz[s]);\n    else\n        mpo[sz[s]]--;\n    for(auto it:adj[s])\n        if(!big[it]) add(it);\n}\n\nvoid rem(int s){\n    mpo[sz[s]]++;\n    if(mp[sz[s]] == 1)\n        mp.erase(sz[s]);\n    else\n        mp[sz[s]]--;\n    for(auto it:adj[s])\n        if(!big[it]) rem(it);\n}\n\nvoid dfs(int s, bool isbig){\n    par[sz[s]]++;\n    if(mpo[sz[s]] == 1)\n        mpo.erase(sz[s]);\n    else\n        mpo[sz[s]]--;\n    int ma = -1, sma = -1, mac = -1, mi = n - 1;\n    for(auto it:adj[s]){\n        if(sz[it]>ma){\n            sma = ma;\n            ma = sz[it];\n            mac = it;\n        }\n        else if(sz[it]==ma)\n            sma = ma;\n        else\n            sma = max(sma,sz[it]);\n        mi = min(mi,sz[it]);\n    }\n    if(s != root)\n        mi = min(mi,n-sz[s]);\n    for(auto it:adj[s]){\n        if(it!=mac)\n            dfs(it,0);\n    }\n    if(mac != -1){\n        big[mac]=true;\n        dfs(mac,1);\n    }\n    if(ma >= n - sz[s]){\n        sma = max(sma, n - sz[s]);\n        bs(mp, sma - 1, ma, mi, s, 0);\n    }\n    mpo[sz[s]]++;\n    add(s);\n    if(par[sz[s]] == 1)\n        par.erase(sz[s]);\n    else\n        par[sz[s]]--;\n    if(n-sz[s] > ma){\n        sma = ma;\n        bs(mpo, sma - 1, n - sz[s], mi, s, 0);\n        bs(par, sma - 1, n - sz[s], mi, s, sz[s]);\n    }\n    if(mac != -1)\n        big[mac] = false;\n    if(!isbig) rem(s);\n}\n\nint main(){\n    int i, u, v;\n    scanf(\"%d\", &n);\n    for(i = 0; i < n; ++i){\n        scanf(\"%d%d\", &u ,&v);\n        if(u == 0) root = v - 1;\n        else\n            adj[u - 1].push_back(v - 1);\n    }\n    getsz(root);\n    dfs(root, 1);\n    for(i = 0; i < n; ++i)\n        printf(\"%d\\n\", ans[i]);\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "769",
    "index": "A",
    "title": "Year of University Entrance",
    "statement": "There is the faculty of Computer Science in Berland. In the social net \"TheContact!\" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university.\n\nEach of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than $x$ from the year of university entrance of this student, where $x$ — some non-negative integer. A value $x$ is not given, but it can be uniquely determined from the available data. Note that students don't join other groups.\n\nYou are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance.",
    "tutorial": "This task can be solved in several ways. The simplest of them is - to put all given integers to an array, sort out it and print the median of the resulting array (it means that the element which is in the middle of it).",
    "tags": [
      "*special",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "769",
    "index": "B",
    "title": "News About Credit",
    "statement": "Polycarp studies at the university in the group which consists of $n$ students (including himself). All they are registrated in the social net \"TheContacnt!\".\n\nNot all students are equally sociable. About each student you know the value $a_{i}$ — the maximum number of messages which the $i$-th student is agree to send per day. The student can't send messages to himself.\n\nIn early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages.\n\nYour task is to make a plan of using private messages, so that:\n\n- the student $i$ sends no more than $a_{i}$ messages (for all $i$ from $1$ to $n$);\n- all students knew the news about the credit (initially only Polycarp knew it);\n- the student can inform the other student only if he knows it himself.\n\nLet's consider that all students are numerated by distinct numbers from $1$ to $n$, and Polycarp \\textbf{always} has the number $1$.\n\nIn that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.",
    "tutorial": "For solving this task you need to consider the following. Let it be that not all students knew news for that moment. If there are not students which knew this news and still can send messages, the answer for the task is -1. Otherwise, it is necessary to send the message to the student $x$, which still doesn't know news, wherein the number of messages which then can be sent by the student $x$ was maximum among students which still don't know the news. It does not matter which one of the students will send the message to the student number $x$. It is necessary to repeat the descriped process until not all students knew the news. For example, for realization it was possible firstly to sort out all students in descending number of messages which each of them can send. Then you can use the queue and put other students who learn the news to the end of it. At the same time, students should learn the news according to the sorted order. It is necessary to send messages starting from Polycarp (student number $1$), because initially only he knews the news.",
    "tags": [
      "*special",
      "greedy",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "769",
    "index": "C",
    "title": "Cycle In Maze",
    "statement": "The Robot is in a rectangular maze of size $n × m$. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol \"L\"), right (the symbol \"R\"), up (the symbol \"U\") or down (the symbol \"D\"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.\n\nYour task is to find \\textbf{lexicographically minimal} Robot's cycle with length \\textbf{exactly} $k$, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).\n\nConsider that Robot's way is given as a line which consists of symbols \"L\", \"R\", \"U\" and \"D\". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as \"DLRU\".\n\nIn this task you \\textbf{don't need} to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.",
    "tutorial": "Initially check $k$ on parity. If $k$ is odd, there is no the answer, because the cycle in the task should always have an even length. Otherwise, we will act as follows. With the help of the search algorithm of the width to find the shortest distance from the starting cell to the rest free cells. After that we will move on the field. Before each moving it is necessary to understand to which cell to go. We will sort out directions in the order \"D\", \"L\", \"R\", \"U\". The current direction equals $c$. So if the cell $x$, which corresponding to the moving in direction $c$, is empty, and the distance from it to the starting cell doesn't exceed the remaining number of steps, then move to the direction $c$, add the appropriate letter to the answer and move on to the new step. If on some step it is impossible to move the Robot, the cycle with the lenght $k$ doesn't exist. Otherwise, when the Robot will do $k$ steps, we have only to print the answer.",
    "tags": [
      "*special",
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "769",
    "index": "D",
    "title": "k-Interesting Pairs Of Integers",
    "statement": "Vasya has the sequence consisting of $n$ integers. Vasya consider the pair of integers $x$ and $y$ k-interesting, if their binary representation differs from each other exactly in $k$ bits. For example, if $k = 2$, the pair of integers $x = 5$ and $y = 3$ is k-interesting, because their binary representation $x$=101 and $y$=011 differs exactly in two bits.\n\nVasya wants to know how many pairs of indexes ($i$, $j$) are in his sequence so that $i < j$ and the pair of integers $a_{i}$ and $a_{j}$ is k-interesting. Your task is to help Vasya and determine this number.",
    "tutorial": "To solve this problem you need to each value from $1$ to $10^{4}$ calculate the number of numbers in the sequence which equal to this value. Let $cnts[x]$ is a number of elements which equal to $x$. After that with two nested loops from $1$ to $10^{4}$ we can brute all pairs and for each pair ($i$, $j$) check that the number of ones in bits in $i$ ^ $j$ equals to $k$ (here we mean operation xor - bitwise exclusive or). To make this check faster we can use standard functions for some compilers (for example, __builtin_popcount for g++) or precalculate such array. If the number of ones in bits in $i$ ^ $j$ equals to $k$ we need to add to the answer $cnts[i] \\cdot cnts[j]$.",
    "tags": [
      "*special",
      "bitmasks",
      "brute force",
      "meet-in-the-middle"
    ],
    "rating": 1700
  },
  {
    "contest_id": "770",
    "index": "A",
    "title": "New Password",
    "statement": "Innokentiy decides to change the password in the social net \"Contact!\", but he is too lazy to invent a new password by himself. That is why he needs your help.\n\nInnokentiy decides that new password should satisfy the following conditions:\n\n- the length of the password must be equal to $n$,\n- the password should consist only of lowercase Latin letters,\n- the number of distinct symbols in the password must be equal to $k$,\n- any two consecutive symbols in the password must be distinct.\n\nYour task is to help Innokentiy and to invent a new password which will satisfy all given conditions.",
    "tutorial": "To solve this problem, consider the first $k$ Latin letters. We will add them to the answer in the order, firstly, we add a, then b and so on. If letters are finished but the length of the answer is still less than the required one, then we start again adding letters from the beginning of the alphabet. We will repeat this algorithm until the length of the answer becomes $n$.",
    "tags": [
      "*special",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "770",
    "index": "B",
    "title": "Maximize Sum of Digits",
    "statement": "Anton has the integer $x$. He is interested what positive integer, which doesn't exceed $x$, has the maximum sum of digits.\n\nYour task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them.",
    "tutorial": "Initially, we put the integer $x$ to the answer. Then look at the integer from right to left. Do the following for each digit: if the digit is not zero, reduce it by one and change all other digits to nine. If the sum of digits in the resulting integer is strictly greater than the sum of the digits of the current answer, then update the answer with the resulting integer.",
    "tags": [
      "*special",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "770",
    "index": "C",
    "title": "Online Courses In BSU",
    "statement": "Now you can take online courses in the Berland State University! Polycarp needs to pass $k$ \\textbf{main} online courses of his specialty to get a diploma. In total $n$ courses are availiable for the passage.\n\nThe situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).\n\nHelp Polycarp to pass the least number of courses in total to get the specialty (it means to pass all \\textbf{main} and necessary courses). Write a program which prints the order of courses.\n\nPolycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once.",
    "tutorial": "Initially, we construct an oriented graph. If it is necessary firstly to take the course $j$ to pass the course $i$, add the edge from $i$ to $j$ to the graph. Then run the search in depth from all vertices, which correspond to main courses. In the depth search, we will simultaneously check the existence of oriented cycles (we need the array of colors marked with white-gray-black) and to build a topological sorting, simply adding vertices in response at the moment when they become black. Here is the code for such a search in depth: The variable $cycle$ will be equal to true only when there is the cycle on the main courses or those on which they depend. So if $cycle$=true, print -1. Otherwise ord (the array with the result of a topological sorting) will contain the answer of the problem. This follows directly from its definition.",
    "tags": [
      "*special",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "770",
    "index": "D",
    "title": "Draw Brackets!",
    "statement": "A sequence of square brackets is regular if by inserting symbols \"+\" and \"1\" into it, you can get a regular mathematical expression from it. For example, sequences \"[[]][]\", \"[]\" and \"[[][[]]]\" — are regular, at the same time \"][\", \"[[]\" and \"[[]]][\" — are irregular.\n\nDraw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height — use symbols '+', '-' and '|'. For example, the sequence \"[[][]][]\" should be represented as:\n\n\\begin{verbatim}\n+- -++- -+\n|+- -++- -+|| |\n|| || ||| |\n|+- -++- -+|| |\n+- -++- -+\n\\end{verbatim}\n\nEach bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.\n\nBrackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height.\n\nThe enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.\n\nStudy carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique.",
    "tutorial": "It is necessary to draw brackets carefully according to the condition to solve this problem. Draw brackets in a two-dimensional array. Firstly, you need to determine the size of the array and then start to draw. To determine the height of the image, you need to find the maximum nesting of the brackets $x$. Then the height of the image (it means the number of necessary strings) is equal to $2 * x + 1$. The width of the image (it means the number of necessary columns) will be counted in the process of drawing. Also initially you need to fill the entire resulting array with spaces. To simplify the solution, it is possible to implement a function that draws the next bracket in two parameters. Here are parameters: the cell which should contain the left upper bracket and the type of it - opening or closing. Thus, to solve this problem, you need to iterate among all brackets from left to right while mantaining the balance of brackets and draw the next bracket using the described auxiliary function. Also check the situation when the current bracket is closing and the previous bracket is opening. In this case it is necessary to leave an empty column according to the condition.",
    "tags": [
      "*special",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "771",
    "index": "A",
    "title": "Bear and Friendship Condition",
    "statement": "Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).\n\nThere are $n$ members, numbered $1$ through $n$. $m$ pairs of members are friends. Of course, a member can't be a friend with themselves.\n\nLet A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three \\textbf{distinct} members (X, Y, Z), if X-Y and Y-Z then also X-Z.\n\nFor example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.\n\nCan you help Limak and check if the network is reasonable? Print \"YES\" or \"NO\" accordingly, without the quotes.",
    "tutorial": "The main observation is that you should print \"YES\" if the graph is a set of disjoint cliques (in each connected non-clique there is a triple of vertices X,Y,Z that X-Y and Y-Z but not X-Z). To check if each connected component is a clique, you can run dfs and count vertices and edges in the connected component - it's a clique if and only if $e d g e s={\\frac{v e r t e e s(v e c t a c e s-1)}{2}}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int nax = 150123;\nvector<int> edges[nax];\nbool vis[nax];\n \nvoid dfs(int a, int & cnt_vertices, int & cnt_edges) {\n\tassert(!vis[a]);\n\tvis[a] = true;\n\t++cnt_vertices;\n\tcnt_edges += edges[a].size();\n\tfor(int b : edges[a])\n\t\tif(!vis[b])\n\t\t\tdfs(b, cnt_vertices, cnt_edges);\n}\n \nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\twhile(m--) {\n\t\tint a, b;\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tedges[a].push_back(b);\n\t\tedges[b].push_back(a);\n\t}\n\tfor(int i = 1; i <= n; ++i)\n\t\tif(!vis[i]) {\n\t\t\tint cnt_vertices = 0, cnt_edges = 0;\n\t\t\tdfs(i, cnt_vertices, cnt_edges);\n\t\t\tif(cnt_edges != (long long) cnt_vertices * (cnt_vertices - 1)) {\n\t\t\t\tputs(\"NO\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\tputs(\"YES\");\n}\n\t\t",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "771",
    "index": "B",
    "title": "Bear and Different Names",
    "statement": "In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).\n\nA group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.\n\nYou are a spy in the enemy's camp. You noticed $n$ soldiers standing in a row, numbered $1$ through $n$. The general wants to choose a group of $k$ consecutive soldiers. For every $k$ consecutive soldiers, the general wrote down whether they would be an effective group or not.\n\nYou managed to steal the general's notes, with $n - k + 1$ strings $s_{1}, s_{2}, ..., s_{n - k + 1}$, each either \"YES\" or \"NO\".\n\n- The string $s_{1}$ describes a group of soldiers $1$ through $k$ (\"YES\" if the group is effective, and \"NO\" otherwise).\n- The string $s_{2}$ describes a group of soldiers $2$ through $k + 1$.\n- And so on, till the string $s_{n - k + 1}$ that describes a group of soldiers $n - k + 1$ through $n$.\n\nYour task is to find possible names of $n$ soldiers. Names should match the stolen notes. Each name should be a string that consists of between $1$ and $10$ English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names — it's allowed to print \"Xyzzzdj\" or \"T\" for example.\n\nFind and print any solution. It can be proved that there always exists at least one solution.",
    "tutorial": "First generate $n$ different names. If the $i$-th given string is \"NO\", make names $i$ and $i + k - 1$ equal. Note that it doesn't affect other groups of $k$ consecutive names.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nstring s[105];\nint main() {\n\tint n, k;\n\tcin >> n >> k;\n\t// generate n different names\n\tfor(int i = 1; i <= n; ++i) {\n\t\ts[i] = \"Aa\";\n\t\ts[i][0] += i / 26;\n\t\ts[i][1] += i % 26;\n\t}\n\tfor(int start = 1; start <= n - k + 1; ++start) {\n\t\tstring should;\n\t\tcin >> should;\n\t\tif(should[0] == 'N') // not effective group\n\t\t\ts[start+k-1] = s[start]; // make two names equal\n\t}\n\tfor(int i = 1; i <= n; ++i) cout << s[i] << \" \";\n\tcout << \"\\n\";\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "771",
    "index": "C",
    "title": "Bear and Tree Jumps",
    "statement": "A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.\n\nLimak is a little polar bear. He lives in a tree that consists of $n$ vertices, numbered $1$ through $n$.\n\nLimak recently learned how to jump. He can jump from a vertex to any vertex within distance at most $k$.\n\nFor a pair of vertices $(s, t)$ we define $f(s, t)$ as the minimum number of jumps Limak needs to get from $s$ to $t$. Your task is to find the sum of $f(s, t)$ over all pairs of vertices $(s, t)$ such that $s < t$.",
    "tutorial": "It's a known problem to count the sum of distances for all pairs of vertices. For each edge, we should add to the answer the number of times this edge appears in a path between some two vertices. If $s_{v}$ denotes the size of the subtree of the vertex $v$ (we can first root the tree in $1$), we should add $s_{v} \\cdot (n - s_{v})$ to the sum. In this problem, the answer is around $\\mathbf{\\Sigma}_{k}^{\\infty}$, where $S$ is the answer for the known problem described above. But for each path with length $L$, we should add $\\left[{\\frac{L}{k}}\\right]={\\frac{L+f(L,k)}{k}}$ to the answer, where $f(L, k)$ says how much we must add to $L$ to get a number divisible by $k$ ($f(10, 3) = 2, f(11, 3) = 1, f(12, 3) = 0$). We know the sum of $\\begin{array}{l}{{\\frac{L}{k}}}\\end{array}$ because it's $\\mathbf{\\Sigma}_{k}^{\\infty}$ in total. What remains is to compute the sum of $f(L, k)$. To achieve that, for each remainder modulo $k$, we want to know the number of paths with length that has this remainder. For example, if $k = 3$ and there are $200$ paths with remainder $1$, they all have $f(L, k) = 2$, so we should add $200 \\cdot 2$ to the answer. Let's root the tree in any vertex and do bottom-up dp. For each subtree we compute the $k$ values: for each remainder modulo $k$ how many paths (starting from the root of this subtree) have this remainder. We can merge two subtrees in $O(k^{2})$, so the total complexity is $O(n \\cdot k^{2})$. See my code for details.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int nax = 2e5 + 5;\nvector<int> edges[nax];\nint count_subtree[nax][5];\nint total_subtree[nax];\nlong long answer;\nint n, k;\n \nint subtract(int a, int b) {\n\treturn ((a - b) % k + k) % k;\n}\n \nvoid dfs(int a, int par, int depth) {\n\tcount_subtree[a][depth % k] = total_subtree[a] = 1;\n\tfor(int b : edges[a])\n\t\tif(b != par) {\n\t\t\tdfs(b, a, depth + 1);\n\t\t\tfor(int i = 0; i < k; ++i)\n\t\t\t\tfor(int j = 0; j < k; ++j) {\n\t\t\t\t\t// compute distance modulo k\n\t\t\t\t\tint remainder = subtract(i + j, 2 * depth);\n\t\t\t\t\t// compute x such that (distance + x) is divisible by k\n\t\t\t\t\tint needs = subtract(k, remainder);\n\t\t\t\t\tanswer += (long long) needs\n\t\t\t\t\t\t\t* count_subtree[a][i] * count_subtree[b][j];\n\t\t\t\t}\n\t\t\tfor(int i = 0; i < k; ++i)\n\t\t\t\tcount_subtree[a][i] += count_subtree[b][i];\n\t\t\ttotal_subtree[a] += total_subtree[b];\n\t\t}\n\t// in how many pairs we will count the edge from 'a' to its parent?\n\tanswer += (long long) total_subtree[a] * (n - total_subtree[a]);\n}\n \nint main() {\n\tscanf(\"%d%d\", &n, &k);\n\tfor(int i = 0; i < n - 1; ++i) {\n\t\tint a, b;\n\t\tscanf(\"%d%d\", &a, &b);\n\t\tedges[a].push_back(b);\n\t\tedges[b].push_back(a);\n\t}\n\tdfs(1, -1, 0);\n\tassert(answer % k == 0);\n\tprintf(\"%lld\\n\", answer / k);\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "771",
    "index": "D",
    "title": "Bear and Company",
    "statement": "Bear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible.\n\nLimak has a string $s$ that consists of uppercase English letters. In one move he can swap two \\textbf{adjacent} letters of the string. For example, he can transform a string \"ABBC\" into \"BABC\" or \"ABCB\" in one move.\n\nLimak wants to obtain a string without a substring \"VK\" (i.e. there should be no letter 'V' immediately followed by letter 'K'). It can be easily proved that it's possible for any initial string $s$.\n\nWhat is the minimum possible number of moves Limak can do?",
    "tutorial": "Letters different than 'V' and 'K' are indistinguishable, so we can treat all of them as the same letter 'X'. We will try to build the final string from left to right Let $dp[v][k][x]$ denote the number of moves needed to move first $v$ letters 'V', first $k$ letters 'K' and first $x$ letters 'X' to the beginning of the string (those letters should become first $v + k + x$ letters of the string). We should also remember the last used letter (to ensure that there is no 'K' just after 'V') so let's extend the state to $dp[v][k][x][lastLetter]$ (or it can be $dp[v][k][x][is_the_last_letter_V]$). To move from a state, we should consider taking the next 'K' (i.e. the $k + 1$-th letter 'K' in the initial string), the next 'V' or the next 'X'. Of course, we can't take 'K' if the last used letter was 'V'. The last step is to see how we should add to the score when we add a new letter. It turns out that it isn't enough to just add the difference between indices (where the letter was and where it will be) and the third sample test (\"VVKEVKK\") showed that. Instead, we should notice that we know which letters are already moved to the beginning (first $k$ letters 'K' and so on) so we know how exactly the string looks like currently. For example, let's consider the string \"VVKXXVKVV\" and moving from the state $v = 4, k = 1, x = 1$ by taking a new letter 'K'. We know that first $4$ letters 'V', $1$ letter 'K' and $1$ letter 'X' are already moved to the beginning. To move the next letter 'K' (underlined in blue on the drawing below) to the left, we must swap it with all not-used letters that were initially on the left from this 'K'. Counting them in linear time gives the total complexity $O(n^{4})$ but you can also think a bit and get $O(n^{3})$ - it's quite easy but it wasn't required to get AC. On the drawing below, used letters are crossed out. There is only $1$ not-crossed-out letter on the left from 'K' so we should increase the score by $1$ (because we need $1$ swap to move this 'K' to the $x + k + v + 1$-th position).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint n;\nvector<int> V, K, X; // lists of indices with 'V', 'K' and other letters\n \nvoid read() {\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tfor(int i = 0; i < n; ++i) {\n\t\tif(s[i] == 'V')\n\t\t\tV.push_back(i);\n\t\telse if(s[i] == 'K')\n\t\t\tK.push_back(i);\n\t\telse\n\t\t\tX.push_back(i);\n\t}\n}\n \nconst int nax = 77;\nconst int INF = 1e9 + 5;\nint dp[nax][nax][nax][2];\n \nvoid mini(int & a, int b) { a = min(a, b); }\n \nint count_remaining(const vector<int> & list, int from, int limit_val) {\n\tint cnt = 0;\n\tfor(int i = from; i < (int) list.size() && list[i] < limit_val; ++i)\n\t\t++cnt;\n\treturn cnt;\n}\n \nint main() {\n\tread();\n\tfor(int a = 0; a <= n; ++a)\n\t\tfor(int b = 0; b <= n; ++b)\n\t\t\tfor(int c = 0; c <= n; ++c)\n\t\t\t\tfor(int d = 0; d < 2; ++d)\n\t\t\t\t\tdp[a][b][c][d] = INF;\n\tdp[0][0][0][0] = 0;\n\tfor(int v = 0; v <= (int) V.size(); ++v)\n\t\tfor(int k = 0; k <= (int) K.size(); ++k)\n\t\t\tfor(int x = 0; x <= (int) X.size(); ++x)\n\t\t\t\tfor(int type = 0; type < 2; ++type) {\n\t\t\t\t\tauto moving_cost = [&] (int where) {\n\t\t\t\t\t\treturn count_remaining(V, v, where)\n\t\t\t\t\t\t\t+ count_remaining(K, k, where)\n\t\t\t\t\t\t\t+ count_remaining(X, x, where);\n\t\t\t\t\t};\n\t\t\t\t\tint already = dp[v][k][x][type];\n\t\t\t\t\tif(v < (int) V.size())\n\t\t\t\t\t\tmini(dp[v+1][k][x][1], already + moving_cost(V[v]));\n\t\t\t\t\tif(k < (int) K.size() && type == 0)\n\t\t\t\t\t\tmini(dp[v][k+1][x][0], already + moving_cost(K[k]));\n\t\t\t\t\tif(x < (int) X.size())\n\t\t\t\t\t\tmini(dp[v][k][x+1][0], already + moving_cost(X[x]));\n\t\t\t\t}\n\tint answer = INF;\n\tfor(int i = 0; i < 2; ++i)\n\t\tmini(answer, dp[V.size()][K.size()][X.size()][i]);\n\tprintf(\"%d\\n\", answer);\n}",
    "tags": [
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "771",
    "index": "E",
    "title": "Bear and Rectangle Strips",
    "statement": "Limak has a grid that consists of $2$ rows and $n$ columns. The $j$-th cell in the $i$-th row contains an integer $t_{i, j}$ which can be positive, negative or zero.\n\nA non-empty rectangle of cells is called nice if and only if the sum of numbers in its cells is equal to $0$.\n\nLimak wants to choose some nice rectangles and give them to his friends, as gifts. No two chosen rectangles should share a cell. What is the maximum possible number of nice rectangles Limak can choose?",
    "tutorial": "There are three types of rectangles: in the top row, in the bottom row, and in both rows (with height 2). For each type, and for each starting index $i$ we can quite easily find the first possible ending index - it's the first index on the right with the same prefix sum of numbers (it means that the difference of prefix sums is $0$). We can iterate from right to left for each of three types, use store prefix sums in the set and for each type and each starting index we can remember the first possible ending index (or we will know that there is no such index). The complexity of this part is $O(n\\cdot\\log n)$. Now, the naive square solution would be to create an array $dp[n][n]$ and compute $dp[i][j]$ as the maximum possible score, if we are allowed to use only first $i$ cells in the first row and first $j$ cells in the second row. Thanks to the precomputing above, we can move from a state in $O(1)$, considering the following options: increase $i$ by $1$ (without taking any rectangle) increase $j$ by $1$ take the first possible rectangle in the first row (check what is the first possible ending index of a rectangle in the first row, starting at index $i + 1$) take the first possible rectangle in the second row if $i = j$, also consider taking first possible rectangle of height $2$ (in both rows) Now let's improve this part to $O(n)$. Let $C_{i}$ denote the best score if we were allowed to use only first $i$ cells in each row ($C_{i} = dp[i][i]$). It turns out that the following values for each $i$ are enough to solve the problem: $C_{i}$ If we were allowed to use only first $i$ cells in the first row, how far we must go in the second row, in order to get the score $C_{i} + 1$. In other words, what is the smallest $j$ such that $dp[i][j] = C_{i} + 1$ Similarly, the smallest $j$ such that $dp[j][i] = C_{i} + 1$ Take a look at the drawings below. The value $C_{i}$ is the maximum possible score for light-blue cells on the left drawing. The right drawing shows the third of situation listed above - we want to know what prefix of cells in the first row is needed, if we want to get the score $C_{i} + 1$. To see that it works, we must prove that we don't have to care how far we must go in one row to get the score $C_{i} + 2$ or higher. The crucial observation that getting score at least $C_{i} + 2$ means that we took at least two rectangles that are at least partially on the right from index $i$ (i.e. each of them contains at least one cell with index greater than $i$) - see the drawing below. So, instead of considering this situation now, we can first take some rectangle in the second row (or skip a few cells) because we can take that last rectangle in the first row later. In other words, when we are in the state $dp[i][j]$ where $i < j$, it's enough to consider taking a rectangle in the first row or just increasing $i$ without taking anything.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long ll;\n \nvoid maxi(int & a, int b) { a = max(a, b); }\n \nvector<ll> candidate[2][2];\n \nint n;\nvector<int> answer;\nvector<vector<vector<int>>> extensions;\n \nvoid consider(int one, int two, int score) {\n\tmaxi(answer[max(one, two)], score);\n\textensions[min(one, two)].push_back(vector<int>{one, two, score});\n}\n \nvoid go_from(int one, int two, int so_far) {\n\t// extend the first row\n\tif(one < n) {\n\t\tconsider(one + 1, two, so_far);\n\t\tint i = candidate[0][0][one];\n\t\tif(i != -1)\n\t\t\tconsider(i + 1, two, so_far + 1);\n\t}\n\t// extend the second row\n\tif(two < n) {\n\t\tconsider(one, two + 1, so_far);\n\t\tint i = candidate[1][1][two];\n\t\tif(i != -1)\n\t\t\tconsider(one, i + 1, so_far + 1);\n\t}\n\t// extend both rows (with a rectangle of height 2)\n\tif(one == two && one < n) {\n\t\tint i = candidate[0][1][one];\n\t\tif(i != -1)\n\t\t\tconsider(i + 1, i + 1, so_far + 1);\n\t}\n}\n \nint main() {\n\tscanf(\"%d\", &n);\n\tanswer.resize(n + 1, 0);\n\textensions.resize(n + 1);\n\tvector<vector<ll>> in(2, vector<ll>(n));\n\tfor(vector<ll> & row : in)\n\t\tfor(int i = 0; i < n; ++i) {\n\t\t\tscanf(\"%lld\", &row[i]);\n\t\t\tif(i) row[i] += row[i-1]; // prefix sums\n\t\t}\n\tfor(int i0 = 0; i0 <= 1; ++i0)\n\t\tfor(int i1 = i0; i1 <= 1; ++i1) {\n\t\t\tcandidate[i0][i1].resize(n, -1);\n\t\t\tmap<ll, int> next_occurrence;\n\t\t\tfor(int where = n - 1; where >= 0; --where) {\n\t\t\t\tll new_value = 0;\n\t\t\t\tfor(int i = i0; i <= i1; ++i)\n\t\t\t\t\tnew_value += in[i][where];\n\t\t\t\tnext_occurrence[new_value] = where;\n\t\t\t\tll need = 0;\n\t\t\t\tif(where != 0)\n\t\t\t\t\tfor(int i = i0; i <= i1; ++i)\n\t\t\t\t\t\tneed += in[i][where-1];\n\t\t\t\tif(next_occurrence.count(need))\n\t\t\t\t\tcandidate[i0][i1][where] = next_occurrence[need];\n\t\t\t}\n\t\t}\n\t\n\tfor(int where = 0; where < n; ++where) {\n\t\tint so_far = answer[where];\n\t\tgo_from(where, where, so_far);\n\t\t\n\t\tauto mini = [&] (int & a, int b) {\n\t\t\tif(a == -1 || b < a) a = b;\n\t\t};\n\t\tint how_far_up = -1, how_far_down = -1;\n\t\tfor(const vector<int> & ext : extensions[where]) {\n\t\t\tif(ext[1] == where && ext[2] == so_far + 1)\n\t\t\t\tmini(how_far_up, ext[0]);\n\t\t\tif(ext[0] == where && ext[2] == so_far + 1)\n\t\t\t\tmini(how_far_down, ext[1]);\n\t\t}\n\t\tif(how_far_up != -1)\n\t\t\tgo_from(how_far_up, where, so_far + 1);\n\t\tif(how_far_down != -1)\n\t\t\tgo_from(where, how_far_down, so_far + 1);\n\t}\n\tprintf(\"%d\\n\", answer[n]);\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "771",
    "index": "F",
    "title": "Bear and Isomorphic Points",
    "statement": "Bearland is a big square on the plane. It contains all points with coordinates not exceeding $10^{6}$ by the absolute value.\n\nThere are $n$ houses in Bearland. The $i$-th of them is located at the point $(x_{i}, y_{i})$. The $n$ points are distinct, but some subsets of them may be collinear.\n\nBear Limak lives in the first house. He wants to destroy his house and build a new one somewhere in Bearland.\n\nBears don't like big changes. For every three points (houses) $p_{i}$, $p_{j}$ and $p_{k}$, the sign of their cross product $(p_{j} - p_{i}) × (p_{k} - p_{i})$ should be the same before and after the relocation. If it was negative/positive/zero, it should still be negative/positive/zero respectively. This condition should be satisfied for all triples of indices $(i, j, k)$, possibly equal to each other or different than $1$. Additionally, Limak isn't allowed to build the house at the point where some other house already exists (but it can be the point where his old house was).\n\nIn the formula above, we define the difference and the cross product of points $(a_{x}, a_{y})$ and $(b_{x}, b_{y})$ as:\n\n\\[\n(a_{x}, a_{y}) - (b_{x}, b_{y}) = (a_{x} - b_{x}, a_{y} - b_{y}),\n\\]\n\n\\[\n(a_{x}, a_{y}) × (b_{x}, b_{y}) = a_{x}·b_{y} - a_{y}·b_{x}.\n\\]\n\nConsider a set of possible new placements of Limak's house. Your task is to find the area of that set of points.\n\nFormally, let's say that Limak chooses the new placement randomly (each coordinate is chosen independently uniformly at random from the interval $[ - 10^{6}, 10^{6}]$). Let $p$ denote the probability of getting the allowed placement of new house. Let $S$ denote the area of Bearland ($S = 4·10^{12}$). Your task is to find $p·S$.",
    "tutorial": "If $p_{1}$ is collinear with some two other points, we should print $0$. Now let's assume that no two points are collinear with $p_{1}$. The naive solution is to iterate over $O(n^{2})$ pairs of points. For each pair of points there is a line going through them both, and we know that the new placement of $p_{1}$ should be on the same side (e.g. on the left) from the line - otherwise the sign of the cross product will change. In other words, the new placement must belong to some halfplane. What we're looking for is the intersection of those $O(n^{2})$ halfplanes, what can be found in $O(n^{2}\\log{n})$. We should also remember that the new placement must be inside the big square, what can be achieved by adding four halfplanes (each for one side of the square). It turns out that it's quite easy to improve the complexity of the naive solution. Let's first sort other $n - 1$ points by angle. One way to approach the problem is to think \"we are interested in those new placements that don't affect the sorting of those $n - 1$ points\" - this is almost enough to get the intended solution. If sorted (in the clockwise order) points are $p_{2}, p_{3}, ..., p_{n}$, taking into account a halfplane that goes through points $p_{i}$ and $p_{i + 1}$ ensures that $p_{i + 1}$ is further in the clockwise order than $p_{i}$ (i.e. it is more \"on the right\" if we look from $p_{1}$). Usually, $p_{i + 2}$ is also more \"on the right\" than $p_{i}$, and so on, till some point $p_{j}$ that is no longer \"on the left\" from $p_{i}$ (if we look from $p_{1}$). For each $i$, let's find the first $j$ that $p_{j}$ is \"on the left\" from $p_{i}$ (move indices $i$ and $j$ with two pointers) and then consider a halfplane that goes through $p_{i}$ and $p_{j}$. To sum up, we consider $n$ halfplanes determined by pairs $(p_{i}, p_{i + 1})$ and $n$ halfplanes determined by pairs $(p_{i}, p_{j})$ where $p_{i}$ and $p_{j}$ are almost opposite to each other, with respect to $p_{1}$. It turns out that this is already a working solution - no other halfplanes are needed. The answer is the intersection of found $O(n)$ halfplanes. Let's prove the correctness. Let's assume that one of halfplanes (going through some $p_{a}$ and $p_{b}$) wasn't considered, while it should be because it would affect the answer. And let's say that $p_{b}$ is more \"on the right\" than $p_{a}$, and $a < b$. If $|a - b| = 1$, we surely considered that halfplane. Otherwise, if there is some other point with index $m\\in[a+1,b-1]$ such that it is on the proper side of the line $(p_{a}, p_{b})$, i.e. on the same side as $p_{1}$, halfplanes determined by pairs $(a, m)$ and $(m, b)$ completely cover that $(a, b)$ halfplane. Here we must use induction: if each halfplane determined by a pair $(a, b)$ for smaller value of $b - a$ is either taken or covered by some other taken halfplanes, then also halfplanes with greater differences $b - a$ will be considered (remember that we assumed that there is some other points with index $m\\in[a+1,b-1]$ such that ...). The case analysed above is shown on the drawing below. Let R denote the red point. If halfplanes $(pa, R)$ and $(R, pb)$ are considered (or from induction they are covered by something else), we don't need considering $(pa, pb)$. What remains is the case when $a + 1  \\neq  b$ and each point with index in $[a + 1, b - 1]$ is on the line $(p_{a}, p_{b})$ or on the wrong side (not the same as $p_{1}$). It quite easily implies that our line is already covered everywhere except for the segment $(p_{a}, p_{b})$, see the drawing: Now we should take a look at points $p_{b + 1}, p_{b + 2}, ...$. If one of them $p_{k}$ is on the wrong side of the line $(p_{a}, p_{b})$ (i.e. on the side different than $p_{1}$), the halfplane $(p_{k - 1}, p_{k})$ covers our segment $(p_{a}, p_{b})$ and we are done. Otherwise, all those points are on the proper side (the same as $p_{1}$). Eventually one of them will be the last one that is \"on the right\" from $p_{a}$ and let's remember that we consider halfplanes determined by such pairs (earlier denoted as $p_{i}$ and $p_{j}$). Since that point is on the proper side of the line $(p_{a}, p_{b})$, the segment is covered:",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#include <bits/stdc++.h>\nusing namespace std;\n#define sim template < class c\n#define ris return * this\n#define dor > debug & operator <<\n#define eni(x) sim > typename \\\n  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {\nsim > struct rge {c b, e; };\nsim > rge<c> range(c i, c j) { return rge<c>{i, j}; }\nsim > auto dud(c* x) -> decltype(cerr << *x, 0);\nsim > char dud(...);\nstruct debug {\n#ifdef LOCAL\n~debug() { cerr << endl; }\neni(!=) cerr << boolalpha << i; ris; }\neni(==) ris << range(begin(i), end(i)); }\nsim, class b dor(pair < b, c > d) {\n  ris << \"(\" << d.first << \", \" << d.second << \")\";\n}\nsim dor(rge<c> d) {\n  *this << \"[\";\n  for (auto it = d.b; it != d.e; ++it)\n    *this << \", \" + 2 * (it == d.b) << *it;\n  ris << \"]\";\n}\n#else\nsim dor(const c&) { ris; }\n#endif\n};\n#define imie(...) \" [\" << #__VA_ARGS__ \": \" << (__VA_ARGS__) << \"] \"\n \ntypedef long long ll;\n \nstruct P {\n\tll x, y;\n\tvoid read() { scanf(\"%lld%lld\", &x, &y); }\n\tP operator - (const P & b) const { return P{x - b.x, y - b.y}; }\n\tvoid operator += (const P & b) { x += b.x, y += b.y; }\n\tll operator * (const P & b) const { return x * b.y - y * b.x; }\n\tll cross(const P & b, const P & c) const {\n\t\treturn (b - *this) * (c - *this);\n\t}\n\tbool isRight() const { return x > 0 || (x == 0 && y > 0); }\n\tbool operator < (const P & b) const {\n\t\tif(isRight() != b.isRight())\n\t\t\treturn isRight();\n\t\treturn *this * b < 0;\n\t}\n};\ndebug & operator << (debug & dd, P p) {\n\tdd << make_pair(p.x, p.y);\n\treturn dd;\n}\n \nstruct L2 {\n\tP one, two;\n\tP dir() const { return two - one; }\n\tbool operator < (const L2 & b) const { return dir() < b.dir(); }\n\tlong double get_coeff(const L2 & b) const {\n\t\tlong double r = (b.dir() * (one - b.one)) / (long double) (dir() * b.dir());\n\t\treturn r;\n\t}\n\tbool isParallel(const L2 & b) const { return dir() * b.dir() == 0; }\n\t// checks if this line is more important than the other parallel line\n\tbool isBetter(const L2 & b) const {\n\t\tassert(isParallel(b));\n\t\treturn (b.one - one) * (two - one) < 0;\n\t}\n\t// checks if this line is less important than two neighbouring lines\n\tbool isBelow(const L2 & a, const L2 & c) const {\n\t\treturn get_coeff(a) >= get_coeff(c);\n\t}\n\tpair<long double, long double> intersect(const L2 & b) const {\n\t\tlong double r = get_coeff(b);\n\t\treturn make_pair(one.x + r * (two - one).x, one.y + r * (two - one).y);\n\t}\n};\ndebug & operator << (debug & dd, L2 line) {\n\tdd << make_pair(line.one, line.two);\n\treturn dd;\n}\n \ndeque<L2> getHull(vector<L2> halfplanes) {\n\tsort(halfplanes.begin(), halfplanes.end());\n\tdebug() << imie(halfplanes);\n\tdeque<L2> hull;\n\t#define sec_back(vect) vect[(int) vect.size() - 2]\n\tfor(L2 line : halfplanes) {\n\t\tif(!hull.empty() && line.isParallel(hull.back())) {\n\t\t\tif(hull.back().isBetter(line))\n\t\t\t\tline = hull.back();\n\t\t\thull.pop_back();\n\t\t}\n\t\twhile((int) hull.size() >= 2 && hull.back().isBelow(sec_back(hull), line))\n\t\t\thull.pop_back();\n\t\thull.push_back(line);\n\t}\n\twhile((int) hull.size() >= 3) {\n\t\tif(hull.back().isBelow(sec_back(hull), hull[0]))\n\t\t\thull.pop_back();\n\t\telse if(hull[0].isBelow(hull.back(), hull[1]))\n\t\t\thull.pop_front();\n\t\telse break;\n\t}\n\t#undef sec_back\n\tdebug() << imie(hull);\n\treturn hull;\n}\n \nlong double test_case() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tP origin;\n\torigin.read();\n\tvector<P> points(n - 1);\n\tfor(P & p : points) {\n\t\tp.read();\n\t\tp = p - origin;\n\t}\n\tsort(points.begin(), points.end());\n\tdebug() << imie(points);\n\tvector<L2> halfplanes;\n\tfor(int i = 0; i < (int) points.size(); ++i) {\n\t\tint j = (i + 1) % points.size();\n\t\thalfplanes.push_back(L2{points[i], points[j]});\n\t}\n\tint pointer = 0;\n\tfor(int i = 0; i < (int) points.size(); ++i) {\n\t\tpointer = max(pointer, i + 1);\n\t\twhile(points[i] * points[pointer % points.size()] < 0)\n\t\t\t++pointer;\n\t\tif(i != pointer % (int) points.size())\n\t\t\thalfplanes.push_back(L2{points[i], points[pointer % points.size()]});\n\t}\n\tdebug() << imie(halfplanes);\n\tfor(L2 & line : halfplanes) {\n\t\tif(line.one * line.two == 0)\n\t\t\treturn 0;\n\t\tif(line.one * line.two > 0)\n\t\t\tswap(line.one, line.two);\n\t\tline.one += origin;\n\t\tline.two += origin;\n\t}\n\t\n\tconst int MAX = 1e6;\n\tvector<P> corners{P{-MAX, MAX}, P{MAX, MAX}, P{MAX, -MAX}, P{-MAX, -MAX}};\n\tfor(int i = 0; i < (int) corners.size(); ++i) {\n\t\tint j = (i + 1) % corners.size();\n\t\thalfplanes.push_back(L2{corners[i], corners[j]});\n\t}\n\tdeque<L2> hull = getHull(halfplanes);\n\tvector<pair<long double, long double>> polygon;\n\tlong double area = 0;\n\tfor(int i = 0; i < (int) hull.size(); ++i) {\n\t\tint j = (i + 1) % hull.size();\n\t\tpolygon.push_back(hull[i].intersect(hull[j]));\n\t}\n\tdebug() << imie(polygon);\n\tfor(int i = 0; i < (int) polygon.size(); ++i) {\n\t\tint j = (i + 1) % polygon.size();\n\t\tarea += polygon[i].first * polygon[j].second\n\t\t\t\t- polygon[i].second * polygon[j].first;\n\t}\n\treturn abs(area) / 2;\n}\n \nint main() {\n\tint T;\n\tscanf(\"%d\", &T);\n\twhile(T--)\n\t\tprintf(\"%.12lf\\n\", (double) test_case());\n}",
    "tags": [
      "geometry",
      "two pointers"
    ],
    "rating": 3300
  },
  {
    "contest_id": "772",
    "index": "A",
    "title": "Voltage Keepsake",
    "statement": "You have $n$ devices that you want to use simultaneously.\n\nThe $i$-th device uses $a_{i}$ units of power per second. This usage is continuous. That is, in $λ$ seconds, the device will use $λ·a_{i}$ units of power. The $i$-th device currently has $b_{i}$ units of power stored. All devices can store an arbitrary amount of power.\n\nYou have a single charger that can plug to any single device. The charger will add $p$ units of power per second to a device. This charging is continuous. That is, if you plug in a device for $λ$ seconds, it will gain $λ·p$ units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.\n\nYou are wondering, what is the maximum amount of time you can use the devices until one of them hits $0$ units of power.\n\nIf you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits $0$ power.",
    "tutorial": "First, let's deal with the infinite case. If the supply of power is at least as big as the sum of demands, we can keep all devices alive indefinitely. Otherwise, let's binary search for the result. We can do binary search since if we can keep all devices alive for $E$ seconds, we can keep it alive for any time less than $E$ seconds. Since all usage/charging is continuous, we can think about it as \"splitting\" up the charge amount. For each device and a fixed time $T$, we can compute the rate that we need to charge it so that the device always has positive power. Well, it uses $a_{i}$ power per second, so it uses a total of $T * a_{i}$ power. It currently has $b_{i}$ power, so we need $X_{i} = max(0, T * a_{i} - b_{i})$ units of power. This means we need $X_{i} / T$ units of power per second to this device. So, we just need to check that $\\textstyle\\sum_{i}X_{i}/T\\leq P$. If so, then it is possible to keep the devices alive for $T$ seconds, and we can use this to continue our binary search. Since we are binary searching on doubles, it is useful to just do it for a fixed number of steps. We can approximate the max answer is somewhere around $10^{14}$ and we need a precision of $10^{ - 4}$, so we need approximately $\\log_{2}(10^{18})\\approx60$ iterations.",
    "code": "#include <stdio.h>\n#include <algorithm>\n#include <assert.h>\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\n// Adjust MAXN for bounds\nconst ll MAXN=1e5+4;\n// MAXV is the max amount of time we can take\nconst ld MAXV=1e18;\nll a[MAXN],b[MAXN];\nld exhaust[MAXN];\nint n;\nll P;\nbool f(ld imid) {\n\tld needsum=0;\n\tfor (int i=0;i<n;i++) {\n\t\tld need=max(0.0L, (imid-exhaust[i])*a[i]);\n\t\tneedsum+=need;\n\t}\n\tld supply=imid*P;\n\treturn supply>=needsum;\n}\nint main() \n{\n\tscanf(\"%d%lld\",&n,&P);\n\tfor (int i=0;i<n;i++) {\n\t\tscanf(\"%lld%lld\",&a[i],&b[i]);\n\t}\n\tll suma=0;\n\tfor (int i=0;i<n;i++) {\n\t\tsuma+=a[i];\n\t}\n\tif (P>=suma) {\n\t\tprintf(\"-1\\n\");\n\t\treturn 0;\n\t}\n\tfor (int i=0;i<n;i++) {\n\t\texhaust[i]=((ld)b[i])/((ld)a[i]);\n\t}\n\tld imin=0,imax=MAXV;\n\tfor (ll iter=0;iter<220;iter++) {\n\t\tld imid=(imin+imax)/2;\n\t\tif (f(imid)) imin=imid;\n\t\telse imax=imid;\n\t}\n\tif (imax>MAXV-100) printf(\"-1\\n\");\n\telse printf(\"%.9f\\n\",(double)imin);\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "772",
    "index": "B",
    "title": "Volatile Kite",
    "statement": "You are given a convex polygon $P$ with $n$ distinct vertices $p_{1}, p_{2}, ..., p_{n}$. Vertex $p_{i}$ has coordinates $(x_{i}, y_{i})$ in the 2D plane. These vertices are listed in clockwise order.\n\nYou can choose a real number $D$ and move each vertex of the polygon a distance of at most $D$ from their original positions.\n\nFind the maximum value of $D$ such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.",
    "tutorial": "First, let's restate the problem as the minimum distance D needed to make the polygon nonconvex. We can notice we can achieve this by by changing one angle of the polygon nonconvex. So, that involves moving at most 3 points. Let's take a look at the following picture: Here, A,B,C denote consecutive vertices on our polygon. The circle represents the area that each point can be moved to (once we fix our distance), and we want to choose red points that lie in or on the circle such that they form an obtuse angle. We can see that this is possible as long as the radius exceeds half the distance between segment AC and point B. Thus, we just need to compute the minimum such distance for all such consecutive three points on our polygon. To compute the distance between a segment and a point, consider this link: https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points In particular, it is the cross product between (B-A) and (C-A) divided by the length of segment AC.",
    "code": "import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.io.BufferedWriter;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.util.InputMismatchException;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n */\npublic class Main {\n    public static void main(String[] args) {\n        InputStream inputStream = System.in;\n        OutputStream outputStream = System.out;\n        InputReader in = new InputReader(inputStream);\n        OutputWriter out = new OutputWriter(outputStream);\n        NonConvexPolygon solver = new NonConvexPolygon();\n        solver.solve(1, in, out);\n        out.close();\n    }\n\n    static class NonConvexPolygon {\n        public void solve(int testNumber, InputReader in, OutputWriter out) {\n            int n = in.nextInt();\n            long[][] p = new long[n][2];\n            for (int i = 0; i < n; i++) {\n                p[i][0] = in.nextInt();\n                p[i][1] = in.nextInt();\n            }\n            double ans = 1L << 60;\n            for (int i = 0; i < n; i++) {\n                int prev = (i + n - 1) % n, next = (i + 1) % n;\n                ans = Math.min(ans, PointToSegmentDistance.pointToLineThroughTwoPointsDistance(\n                        p[i][0], p[i][1], p[prev][0], p[prev][1], p[next][0], p[next][1]\n                ) / 2.0);\n            }\n            out.printf(\"%.10f\\n\", ans);\n        }\n\n    }\n\n    static class Utils {\n        public static double cross(Point a, Point b, Point c) {\n            Point ab = new Point(b.x - a.x, b.y - a.y);\n            Point ac = new Point(c.x - a.x, c.y - a.y);\n            return ab.x * ac.y - ab.y * ac.x;\n        }\n\n    }\n\n    static class PointToSegmentDistance {\n        static double fastHypot(double x, double y) {\n            return Math.sqrt(x * x + y * y);\n        }\n\n        public static double pointToLineThroughTwoPointsDistance(long x, long y, long ax, long ay, long bx, long by) {\n            double t = Utils.cross(new Point(ax, ay), new Point(bx, by), new Point(x, y));\n            return Math.abs(t / fastHypot(ax - bx, ay - by));\n        }\n\n    }\n\n    static class Point implements Comparable<Point> {\n        public double x;\n        public double y;\n        public double angle;\n        public int idx;\n\n        public Point(double x, double y) {\n            this.x = x;\n            this.y = y;\n            angle = 0;\n        }\n\n        public Point(double x, double y, int idx) {\n            this.x = x;\n            this.y = y;\n            this.idx = idx;\n        }\n\n        public int compareTo(Point other) {\n            return x == other.x ? (int) Math.signum(y - other.y) : (int) Math.signum(x - other.x);\n        }\n\n    }\n\n    static class OutputWriter {\n        private final PrintWriter writer;\n\n        public OutputWriter(OutputStream outputStream) {\n            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n        }\n\n        public OutputWriter(Writer writer) {\n            this.writer = new PrintWriter(writer);\n        }\n\n        public void printf(String format, Object... objects) {\n            writer.printf(format, objects);\n        }\n\n        public void close() {\n            writer.close();\n        }\n\n    }\n\n    static class InputReader {\n        private InputStream stream;\n        private byte[] buf = new byte[1024];\n        private int curChar;\n        private int numChars;\n\n        public InputReader(InputStream stream) {\n            this.stream = stream;\n        }\n\n        public int read() {\n            if (this.numChars == -1) {\n                throw new InputMismatchException();\n            } else {\n                if (this.curChar >= this.numChars) {\n                    this.curChar = 0;\n\n                    try {\n                        this.numChars = this.stream.read(this.buf);\n                    } catch (IOException var2) {\n                        throw new InputMismatchException();\n                    }\n\n                    if (this.numChars <= 0) {\n                        return -1;\n                    }\n                }\n\n                return this.buf[this.curChar++];\n            }\n        }\n\n        public int nextInt() {\n            int c;\n            for (c = this.read(); isSpaceChar(c); c = this.read()) {\n                ;\n            }\n\n            byte sgn = 1;\n            if (c == 45) {\n                sgn = -1;\n                c = this.read();\n            }\n\n            int res = 0;\n\n            while (c >= 48 && c <= 57) {\n                res *= 10;\n                res += c - 48;\n                c = this.read();\n                if (isSpaceChar(c)) {\n                    return res * sgn;\n                }\n            }\n\n            throw new InputMismatchException();\n        }\n\n        public static boolean isSpaceChar(int c) {\n            return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;\n        }\n\n    }\n}",
    "tags": [
      "geometry"
    ],
    "rating": 1800
  },
  {
    "contest_id": "772",
    "index": "C",
    "title": "Vulnerable Kerbals",
    "statement": "You are given an integer $m$, and a list of $n$ distinct integers between $0$ and $m - 1$.\n\nYou would like to construct a sequence satisfying the properties:\n\n- Each element is an integer between $0$ and $m - 1$, inclusive.\n- All prefix products of the sequence modulo $m$ are distinct.\n- No prefix product modulo $m$ appears as an element of the input list.\n- The length of the sequence is maximized.\n\nConstruct any sequence satisfying the properties above.",
    "tutorial": "Let's consider a directed graph with $m$ nodes, labeled from $1$ to $m$, where there is an edge between nodes $i$ and node $j$ if there exists a number $x$ such that $i x\\equiv j{\\mathrm{~mod~}}m$. Now, we can notice there is an edge between node $i$ and node $j$ if and only if $gcd(n, i)$ divides $gcd(n, j)$. So, there are two directed edges between two nodes $i$ and $j$ if and only if $gcd(n, i) = gcd(n, j)$. So, these form some directed cliques in our graphs. We can also notice that this happens to form the SCC decomposition of our graph (i.e. condensation). So this problem reduces to finding the heaviest path in a DAG with weights on nodes. The nodes in this dag correspond to divisors of $n$, and the weight corresponds to the number of allowed numbers with that gcd.",
    "code": "import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.util.Arrays;\nimport java.io.BufferedWriter;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.util.InputMismatchException;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.io.InputStream;\n\n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n */\npublic class Main {\n    public static void main(String[] args) {\n        InputStream inputStream = System.in;\n        OutputStream outputStream = System.out;\n        InputReader in = new InputReader(inputStream);\n        OutputWriter out = new OutputWriter(outputStream);\n        PrefixProductSequence solver = new PrefixProductSequence();\n        solver.solve(1, in, out);\n        out.close();\n    }\n\n    static class PrefixProductSequence {\n        public int[] div;\n        public boolean[] forbidden;\n        public ArrayList<Long> ans;\n        public int n;\n        public int m;\n\n        public void solve(int testNumber, InputReader in, OutputWriter out) {\n            n = in.nextInt();\n            m = in.nextInt();\n            forbidden = new boolean[m + 1];\n            for (int i = 0; i < n; i++) {\n                forbidden[in.nextInt()] = true;\n            }\n            int[] add = new int[m + 1];\n            for (int i = 0; i < m; i++) {\n                if (!forbidden[i]) {\n                    int g = Utils.gcd(i, m);\n                    add[m / g]++;\n                }\n            }\n            int[] arr = new int[m + 1];\n            div = new int[m + 1];\n            Arrays.fill(arr, 1);\n            Arrays.setAll(div, x -> x);\n            for (int i = 2; i <= m; i++) {\n                arr[i] += add[i];\n                for (int j = i + i; j <= m; j += i) {\n                    if (arr[i] > arr[j]) {\n                        arr[j] = arr[i];\n                        div[j] = j / i;\n                    }\n                }\n            }\n\n            ans = new ArrayList<>();\n            solve(1, 1);\n            out.println(ans.size());\n            boolean first = true;\n            for (long x : ans) {\n                if (!first) out.print(\" \");\n                out.print(x);\n                first = false;\n            }\n            out.println();\n        }\n\n        public void solve(int cmult, long mm) {\n            if (cmult == m) {\n                if (!forbidden[0]) {\n                    ans.add(0L);\n                }\n                return;\n            }\n            int prev = 1;\n            boolean has = false;\n            for (int i = 1; i < m / cmult; i++) {\n                if (!forbidden[i * cmult] && Utils.gcd(m / cmult, i) == 1) {\n                    long x = Utils.inv(prev, m / cmult) * i % m;\n                    if (!has) {\n                        has = true;\n                        x = x * mm % m;\n                    }\n                    ans.add(x);\n                    prev = i;\n                }\n            }\n            long nmm = Utils.inv(prev, m / cmult) * div[m / cmult] % m;\n            if (!has) nmm = nmm * mm % m;\n            solve(cmult * div[m / cmult], nmm);\n        }\n\n    }\n\n    static class OutputWriter {\n        private final PrintWriter writer;\n\n        public OutputWriter(OutputStream outputStream) {\n            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n        }\n\n        public OutputWriter(Writer writer) {\n            this.writer = new PrintWriter(writer);\n        }\n\n        public void print(Object... objects) {\n            for (int i = 0; i < objects.length; i++) {\n                if (i != 0) {\n                    writer.print(' ');\n                }\n                writer.print(objects[i]);\n            }\n        }\n\n        public void println() {\n            writer.println();\n        }\n\n        public void close() {\n            writer.close();\n        }\n\n        public void print(long i) {\n            writer.print(i);\n        }\n\n        public void println(int i) {\n            writer.println(i);\n        }\n\n    }\n\n    static class InputReader {\n        private InputStream stream;\n        private byte[] buf = new byte[1024];\n        private int curChar;\n        private int numChars;\n\n        public InputReader(InputStream stream) {\n            this.stream = stream;\n        }\n\n        public int read() {\n            if (this.numChars == -1) {\n                throw new InputMismatchException();\n            } else {\n                if (this.curChar >= this.numChars) {\n                    this.curChar = 0;\n\n                    try {\n                        this.numChars = this.stream.read(this.buf);\n                    } catch (IOException var2) {\n                        throw new InputMismatchException();\n                    }\n\n                    if (this.numChars <= 0) {\n                        return -1;\n                    }\n                }\n\n                return this.buf[this.curChar++];\n            }\n        }\n\n        public int nextInt() {\n            int c;\n            for (c = this.read(); isSpaceChar(c); c = this.read()) {\n                ;\n            }\n\n            byte sgn = 1;\n            if (c == 45) {\n                sgn = -1;\n                c = this.read();\n            }\n\n            int res = 0;\n\n            while (c >= 48 && c <= 57) {\n                res *= 10;\n                res += c - 48;\n                c = this.read();\n                if (isSpaceChar(c)) {\n                    return res * sgn;\n                }\n            }\n\n            throw new InputMismatchException();\n        }\n\n        public static boolean isSpaceChar(int c) {\n            return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;\n        }\n\n    }\n\n    static class Utils {\n        public static long inv(long N, long M) {\n            long x = 0, lastx = 1, y = 1, lasty = 0, q, t, a = N, b = M;\n            while (b != 0) {\n                q = a / b;\n                t = a % b;\n                a = b;\n                b = t;\n                t = x;\n                x = lastx - q * x;\n                lastx = t;\n                t = y;\n                y = lasty - q * y;\n                lasty = t;\n            }\n            return (lastx + M) % M;\n        }\n\n        public static int gcd(int a, int b) {\n            return b == 0 ? a : gcd(b, a % b);\n        }\n\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "772",
    "index": "D",
    "title": "Varying Kibibits",
    "statement": "You are given $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Denote this list of integers as $T$.\n\nLet $f(L)$ be a function that takes in a non-empty list of integers $L$.\n\nThe function will output another integer as follows:\n\n- First, all integers in $L$ are padded with leading zeros so they are all the same length as the maximum length number in $L$.\n- We will construct a string where the $i$-th character is the minimum of the $i$-th character in padded input numbers.\n- The output is the number representing the string interpreted in base 10.\n\nFor example $f(10, 9) = 0$, $f(123, 321) = 121$, $f(530, 932, 81) = 30$.\n\nDefine the function\n\n\\[\nG(x)=x\\cdot\\left(\\left(\\sum_{s\\in Z,s\\neq o,f(S)=x}\\left(\\sum_{y\\in S}y\\right)^{2}\\right){\\mathrm{~mod~}}1{\\mathrm{~ooo~}}000{\\mathrm{00}}\\bar{v}\\right)\n\\]\n\nHere, $\\subseteq$ denotes a subsequence.In other words, $G(x)$ is the sum of squares of sum of elements of nonempty subsequences of $T$ that evaluate to $x$ when plugged into $f$ modulo $1 000 000 007$, then multiplied by $x$. The last multiplication is not modded.\n\nYou would like to compute $G(0), G(1), ..., G(999 999)$. To reduce the output size, print the value $G(0)\\oplus G(1)\\oplus G(2)\\oplus.\\cdot\\Leftrightarrow G(999999)$, where $\\mathbb{C}$ denotes the bitwise XOR operator.",
    "tutorial": "There are two approaches. One is inclusion exclusion. The other is a modification of the fast walsh hadamard transform. Inclusion Exclusion: Let's change definition of G(x) so that f(S) >= x rather than f(S) = x. Here \"y >= x\" means that if y and x are considered as strings, then each digit in a particular position in y is greater than its corresponding digit in x. This is then easy to compute, since the numbers we can use must satisfy the constraint that each digit is larger than the corresponding position in x. So, we can go from $999, 999$ to $0$ and do inclusion/exclusion to change the >= condition to =, by fixing which digits are fixed and which ones are strictly greater, so it takes $2^{6}$ time per value of $x$ to compute. Fast Walsh Hadamard transform: Let's consider the simplified problem where we just want to know the number of subsets that evaluate to $x$ for all values of $x$. Let f(freq) taken in a frequency array of length 10^k, and returns a list of length 10^k, where the i-th element represents the result. When $k = 0$, this is easy to compute, it is just $2^{freq[0]}$. Let's fix the value of the topmost digit. We can split our frequency array into 10 parts, representing which one is the top digt. Let's label these freq_0, freq_1, ..., freq_9 (these have length 10^(k-1)). Then, we can compute g_9 = f(freq_9) g_8 = f(freq_9+freq_8) g_7 = f(freq_9+freq_8+freq_7) ... g_0 = f(freq_9+freq_8+...+freq_0) (The plus signs here are element by element addition, so [0,3] + [5,4] = [5,7] for example). Then, we can combine these to get the answer to our original problem. Namely, our final answer will be (g_0 - g_1), (g_1 - g_2), ... , g_9 (i.e. concatenate the element by element subtraction of g_1 from g_0 to g_1-g_2 and so on). Of course, we don't need to do this recursively, we can do it in a loop (see my java code for example). Back to the original problem, we need to keep track of three values when doing the first pass of our algorithm, the number of elements, sum of elements, and sum of squares of elements. Then, in our base case, we can use these three numbers to compute the desired sum. The runtime of this is T(n) = 10 * T(n/10) + O(n) = O(n log_10(n)).",
    "code": "import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.io.BufferedWriter;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.util.InputMismatchException;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n */\npublic class Main {\n    public static void main(String[] args) {\n        InputStream inputStream = System.in;\n        OutputStream outputStream = System.out;\n        InputReader in = new InputReader(inputStream);\n        OutputWriter out = new OutputWriter(outputStream);\n        MinAddition solver = new MinAddition();\n        solver.solve(1, in, out);\n        out.close();\n    }\n\n    static class MinAddition {\n        public int[] pow10 = {1, 10, 100, 1000, 10000, 100000, 1000000};\n        public int MAXN = 1000000;\n        public int LOG = 6;\n        public int mod = 1000000007;\n\n        public void solve(int testNumber, InputReader in, OutputWriter out) {\n            int n = in.nextInt();\n            int[] freq = new int[MAXN];\n            int[] sum = new int[MAXN];\n            int[] sum2 = new int[MAXN];\n            int[] pow2 = new int[n + 1];\n            pow2[0] = 1;\n            for (int i = 1; i <= n; i++) pow2[i] = (pow2[i - 1] << 1) % mod;\n            for (int i = 0; i < n; i++) {\n                int a = in.nextInt();\n                freq[a]++;\n                sum[a] += a;\n                if (sum[a] >= mod) sum[a] -= mod;\n                int x = (int) (1L * a * a % mod);\n                sum2[a] += x;\n                if (sum2[a] >= mod) sum2[a] -= mod;\n            }\n\n            int[] mod10 = new int[MAXN];\n            for (int i = 0; i < 10; i++) mod10[i] = i;\n            for (int i = 10; i < MAXN; i++) mod10[i] = mod10[i - 10];\n\n            for (int level = LOG - 1; level >= 0; level--) {\n                for (int i = MAXN - 1; i >= 0; i--) {\n                    int d = mod10[i / pow10[level]];\n                    if (d > 0) {\n                        int p = i - pow10[level];\n                        freq[p] += freq[i];\n                        sum[p] += sum[i];\n                        if (sum[p] >= mod) sum[p] -= mod;\n                        sum2[p] += sum2[i];\n                        if (sum2[p] >= mod) sum2[p] -= mod;\n                    }\n                }\n            }\n            for (int i = 0; i < MAXN; i++) {\n                int sdiff = (int) ((1L * sum[i] * sum[i] + mod - sum2[i]) % mod);\n                int ssame = sum2[i];\n                int g = 0;\n                if (freq[i] >= 1)\n                    g += (int) (1L * ssame * pow2[freq[i] - 1] % mod);\n                if (freq[i] >= 2)\n                    g += (int) (1L * sdiff * pow2[freq[i] - 2] % mod);\n                while (g >= mod) g -= mod;\n                freq[i] = g;\n            }\n\n            for (int level = 0; level < LOG; level++) {\n                for (int i = 0; i < MAXN; i++) {\n                    int d = mod10[i / pow10[level]];\n                    if (d + 1 < 10) {\n                        int p = i + pow10[level];\n                        freq[i] -= freq[p];\n                        if (freq[i] < 0) freq[i] += mod;\n                    }\n                }\n            }\n\n            long s = 0;\n            for (int i = 0; i < MAXN; i++) {\n                s ^= 1L * i * freq[i];\n            }\n            out.println(s);\n        }\n\n    }\n\n    static class OutputWriter {\n        private final PrintWriter writer;\n\n        public OutputWriter(OutputStream outputStream) {\n            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n        }\n\n        public OutputWriter(Writer writer) {\n            this.writer = new PrintWriter(writer);\n        }\n\n        public void close() {\n            writer.close();\n        }\n\n        public void println(long i) {\n            writer.println(i);\n        }\n\n    }\n\n    static class InputReader {\n        private InputStream stream;\n        private byte[] buf = new byte[1024];\n        private int curChar;\n        private int numChars;\n\n        public InputReader(InputStream stream) {\n            this.stream = stream;\n        }\n\n        public int read() {\n            if (this.numChars == -1) {\n                throw new InputMismatchException();\n            } else {\n                if (this.curChar >= this.numChars) {\n                    this.curChar = 0;\n\n                    try {\n                        this.numChars = this.stream.read(this.buf);\n                    } catch (IOException var2) {\n                        throw new InputMismatchException();\n                    }\n\n                    if (this.numChars <= 0) {\n                        return -1;\n                    }\n                }\n\n                return this.buf[this.curChar++];\n            }\n        }\n\n        public int nextInt() {\n            int c;\n            for (c = this.read(); isSpaceChar(c); c = this.read()) {\n                ;\n            }\n\n            byte sgn = 1;\n            if (c == 45) {\n                sgn = -1;\n                c = this.read();\n            }\n\n            int res = 0;\n\n            while (c >= 48 && c <= 57) {\n                res *= 10;\n                res += c - 48;\n                c = this.read();\n                if (isSpaceChar(c)) {\n                    return res * sgn;\n                }\n            }\n\n            throw new InputMismatchException();\n        }\n\n        public static boolean isSpaceChar(int c) {\n            return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;\n        }\n\n    }\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "772",
    "index": "E",
    "title": "Verifying Kingdom",
    "statement": "\\textbf{This is an interactive problem.}\n\nThe judge has a hidden rooted full binary tree with $n$ leaves. A full binary tree is one where every node has either $0$ or $2$ children. The nodes with $0$ children are called the leaves of the tree. Since this is a full binary tree, there are exactly $2n - 1$ nodes in the tree. The leaves of the judge's tree has labels from $1$ to $n$. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.\n\nA question consists of printing the label of three distinct leaves $a_{1}, a_{2}, a_{3}$. Let the depth of a node be the shortest distance from the node to the root of the tree. Let $LCA(a, b)$ denote the node with maximum depth that is a common ancestor of the nodes $a$ and $b$.\n\nConsider $X = LCA(a_{1}, a_{2}), Y = LCA(a_{2}, a_{3}), Z = LCA(a_{3}, a_{1})$. The judge will tell you which one of $X, Y, Z$ has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties.\n\nMore specifically, if $X$ (or $Y$, $Z$ respectively) maximizes the depth, the judge will respond with the string \"X\" (or \"Y\", \"Z\" respectively).\n\nYou may only ask at most $10·n$ questions.",
    "tutorial": "Consider building the tree leaf by leaf. The base case of two leaves is trivial. Now, suppose want to add another leaf $w_{i}$. We can define the \"centroid\" as a tree such that after removing the centroid, all remaining connected components has at most half the number of leaves (note this is different from the standard definition of centroid). Notice, each internal node can be represented as a pair of leaves (x,y), where x comes from the left child, and y comes from the right child. Ask the judge (x,y,w_i). Depending on the response, we can remove the centroid, and know which subtree that w_i lies in (i.e. either the left child, right child, or upper child). So, we can recurse on that tree. So, inserting a node takes log_2 i questions and O(i) time, so overall we ask n log n questions and take n^2 time.",
    "code": "import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.io.BufferedWriter;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.util.InputMismatchException;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n */\npublic class Main {\n    public static void main(String[] args) {\n        InputStream inputStream = System.in;\n        OutputStream outputStream = System.out;\n        InputReader in = new InputReader(inputStream);\n        OutputWriter out = new OutputWriter(outputStream);\n        ForgottenTree solver = new ForgottenTree();\n        solver.solve(1, in, out);\n        out.close();\n    }\n\n    static class ForgottenTree {\n        public InputReader in;\n        public OutputWriter out;\n        public int nidx;\n        public int n;\n        public int[] par;\n\n        public void solve(int testNumber, InputReader in, OutputWriter out) {\n            this.in = in;\n            this.out = out;\n\n            n = in.nextInt();\n            nidx = n;\n            ForgottenTree.Node root = new ForgottenTree.Node(0);\n            ForgottenTree.Node.cgen = 0;\n            for (int i = 1; i < n; i++) {\n                ForgottenTree.Node.cgen++;\n                root.getLeaves();\n                root = insert(root, i);\n            }\n            out.println(-1);\n            par = new int[2 * n - 1];\n            dfs(root, -2);\n            out.println(par);\n        }\n\n        public String ask(int a, int b, int c) {\n            out.println((a + 1) + \" \" + (b + 1) + \" \" + (c + 1));\n            out.flush();\n            String ret = in.next();\n            if (ret.equals(\"-1\")) System.exit(0);\n            return ret;\n        }\n\n        public void dfs(ForgottenTree.Node root, int p) {\n            par[root.label] = p + 1;\n            if (root.lchild != null) {\n                dfs(root.lchild, root.label);\n                dfs(root.rchild, root.label);\n            }\n        }\n\n        public ForgottenTree.Node insert(ForgottenTree.Node root, int label) {\n            if (!root.active()) {\n                return add(root, label);\n            }\n            root.dfs();\n\n            if (root.lchild == null) {\n                return add(root, label);\n            }\n\n            int curleaves = root.nleaves;\n            if (curleaves <= 1) {\n                int nnodes = 0;\n                ForgottenTree.Node cur = root;\n                while (!cur.isLeaf()) {\n                    nnodes++;\n                    if (cur.lchild.active()) cur = cur.lchild;\n                    else cur = cur.rchild;\n                }\n                cur = root;\n                int depth = 0;\n                while (2 * (depth + 1) < nnodes) {\n                    if (cur.lchild.active()) cur = cur.lchild;\n                    else cur = cur.rchild;\n                    depth++;\n                }\n\n                return process(root, cur, label);\n            }\n\n            ForgottenTree.Node cur = root;\n            while (true) {\n                if (cur.lchild == null) {\n                    if (cur.par == null) {\n                        return add(cur, label);\n                    }\n                    if (cur.which == 0) {\n                        cur.par.setChild(0, add(cur, label));\n                        return root;\n                    } else {\n                        cur.par.setChild(1, add(cur, label));\n                        return root;\n                    }\n                }\n                int x1 = cur.lchild.active() ? cur.lchild.nleaves : 0;\n                int x2 = cur.rchild.active() ? cur.rchild.nleaves : 0;\n\n                if (x1 * 2 > curleaves) {\n                    cur = cur.lchild;\n                    continue;\n                }\n                if (x2 * 2 > curleaves) {\n                    cur = cur.rchild;\n                    continue;\n                }\n\n                return process(root, cur, label);\n            }\n        }\n\n        public ForgottenTree.Node process(ForgottenTree.Node root, ForgottenTree.Node cur, int label) {\n            String s = ask(cur.x, cur.y, label);\n            switch (s) {\n                case \"X\":\n                    if (cur.par == null) {\n                        return add(cur, label);\n                    }\n                    cur.disable();\n                    return insert(root, label);\n                case \"Y\":\n                    cur.setChild(1, insert(cur.rchild, label));\n                    return root;\n                case \"Z\":\n                    cur.setChild(0, insert(cur.lchild, label));\n                    return root;\n                default:\n                    throw new RuntimeException();\n            }\n        }\n\n        public ForgottenTree.Node add(ForgottenTree.Node cnode, int label) {\n            ForgottenTree.Node add = new ForgottenTree.Node(nidx++);\n            add.setChild(0, cnode);\n            add.setChild(1, new ForgottenTree.Node(label));\n            return add;\n        }\n\n        static class Node {\n            public static int cgen;\n            public int x;\n            public int y;\n            public int label;\n            public int gen;\n            public int nleaves;\n            public int which;\n            public ForgottenTree.Node lchild;\n            public ForgottenTree.Node rchild;\n            public ForgottenTree.Node par;\n\n            public Node(int label) {\n                this.lchild = null;\n                this.rchild = null;\n                this.par = null;\n                this.which = 0;\n                this.label = label;\n                this.gen = 0;\n                this.nleaves = 1;\n            }\n\n            public boolean active() {\n                return gen < cgen;\n            }\n\n            public void disable() {\n                this.gen = cgen;\n            }\n\n            public boolean isLeaf() {\n                return lchild == null || (!lchild.active() && !rchild.active());\n            }\n\n            public void setChild(int which, ForgottenTree.Node x) {\n                if (which == 0) {\n                    this.lchild = x;\n                } else {\n                    this.rchild = x;\n                }\n                x.par = this;\n                x.which = which;\n            }\n\n            public void dfs() {\n                if (isLeaf()) {\n                    this.nleaves = 1;\n                    return;\n                }\n\n                this.nleaves = 0;\n                if (lchild.active()) {\n                    lchild.dfs();\n                    this.nleaves += lchild.nleaves;\n                }\n                if (rchild.active()) {\n                    rchild.dfs();\n                    this.nleaves += rchild.nleaves;\n                }\n            }\n\n            public void getLeaves() {\n                if (lchild == null) {\n                    this.x = this.y = label;\n                    return;\n                }\n                lchild.getLeaves();\n                rchild.getLeaves();\n                this.x = lchild.x;\n                this.y = rchild.x;\n            }\n\n        }\n\n    }\n\n    static class InputReader {\n        private InputStream stream;\n        private byte[] buf = new byte[1024];\n        private int curChar;\n        private int numChars;\n\n        public InputReader(InputStream stream) {\n            this.stream = stream;\n        }\n\n        public int read() {\n            if (this.numChars == -1) {\n                throw new InputMismatchException();\n            } else {\n                if (this.curChar >= this.numChars) {\n                    this.curChar = 0;\n\n                    try {\n                        this.numChars = this.stream.read(this.buf);\n                    } catch (IOException var2) {\n                        throw new InputMismatchException();\n                    }\n\n                    if (this.numChars <= 0) {\n                        return -1;\n                    }\n                }\n\n                return this.buf[this.curChar++];\n            }\n        }\n\n        public int nextInt() {\n            int c;\n            for (c = this.read(); isSpaceChar(c); c = this.read()) {\n                ;\n            }\n\n            byte sgn = 1;\n            if (c == 45) {\n                sgn = -1;\n                c = this.read();\n            }\n\n            int res = 0;\n\n            while (c >= 48 && c <= 57) {\n                res *= 10;\n                res += c - 48;\n                c = this.read();\n                if (isSpaceChar(c)) {\n                    return res * sgn;\n                }\n            }\n\n            throw new InputMismatchException();\n        }\n\n        public String next() {\n            int c;\n            while (isSpaceChar(c = this.read())) {\n                ;\n            }\n\n            StringBuilder result = new StringBuilder();\n            result.appendCodePoint(c);\n\n            while (!isSpaceChar(c = this.read())) {\n                result.appendCodePoint(c);\n            }\n\n            return result.toString();\n        }\n\n        public static boolean isSpaceChar(int c) {\n            return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;\n        }\n\n    }\n\n    static class OutputWriter {\n        private final PrintWriter writer;\n\n        public OutputWriter(OutputStream outputStream) {\n            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n        }\n\n        public OutputWriter(Writer writer) {\n            this.writer = new PrintWriter(writer);\n        }\n\n        public void print(Object... objects) {\n            for (int i = 0; i < objects.length; i++) {\n                if (i != 0) {\n                    writer.print(' ');\n                }\n                writer.print(objects[i]);\n            }\n        }\n\n        public void print(int[] array) {\n            for (int i = 0; i < array.length; i++) {\n                if (i != 0) {\n                    writer.print(' ');\n                }\n                writer.print(array[i]);\n            }\n        }\n\n        public void println(int[] array) {\n            print(array);\n            writer.println();\n        }\n\n        public void println(Object... objects) {\n            print(objects);\n            writer.println();\n        }\n\n        public void close() {\n            writer.close();\n        }\n\n        public void flush() {\n            writer.flush();\n        }\n\n        public void println(int i) {\n            writer.println(i);\n        }\n\n    }\n}\n",
    "tags": [
      "binary search",
      "divide and conquer",
      "interactive",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "773",
    "index": "A",
    "title": "Success Rate",
    "statement": "You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made $y$ submissions, out of which $x$ have been successful. Thus, your current success rate on Codeforces is equal to $x / y$.\n\nYour favorite rational number in the $[0;1]$ range is $p / q$. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be $p / q$?",
    "tutorial": "This problem can be solved using binary search without any special cases. You can also solve it using a formula, handling a couple of special cases separately. If our success rate is $p / q$, it means we have $pt$ successful submissions out of $qt$ for some $t$. Since $p / q$ is already irreducible, $t$ has to be a positive integer. Let's reformulate things a bit. Initially we have $x$ successful submissions and $y - x$ unsuccessful ones. Suppose we fix $t$, and in the end we want to have $pt$ successful submissions and $qt - pt$ unsuccessful ones. It's clear we can achieve that if $pt  \\ge  x$ and $qt - pt  \\ge  y - x$, since we can only increase both the number of successful and unsuccessful submissions. Note that both inequalities have constant right hand side, and their left hand side doesn't decrease as $t$ increases. Therefore, if the inequalities are satisfied for some $t$, they will definitely be satisfied for larger $t$ as well. It means we can apply binary search to find the lowest value of $t$ satisfying the inequality. Then, the answer to the problem is $qt - y$. If even for very large $t$ the inequalities are not satisfied, the answer is -1. It can be proved that one \"very large\" value of $t$ is $t = y$ - that is, if the inequalities are not satisfied for $t = y$, then they cannot be satisfied for any value of $t$. Alternatively, picking $t = 10^{9}$ works too, since $y  \\le  10^{9}$. Actually, inequalities $pt  \\ge  x$ and $qt - pt  \\ge  y - x$ are easy to solve by hand. From $pt  \\ge  x$ it follows that $t\\geq{\\frac{\\alpha}{p}}$. From $qt - pt  \\ge  y - x$ it follows that $t\\geq{\\frac{y-x}{q-p}}$. In order to satisfy both inequalities, $t$ has to satisfy $t\\geq\\operatorname*{max}(\\frac{x}{p},\\frac{y-x}{q-p})$. Don't forget that $t$ has to be integer, so the division results have to be rounded up to the nearest integer. In general, if we want to find $\\overset{\\stackrel{\\wedge}{a}}{b}$ rounded up where both $a$ and $b$ are positive integers, the usual way to do that is to calculate $(a + b - 1) / b$, where \"$/$\" is the standard integer division (rounded down). In this solution, cases when $p / q = 0 / 1$ or $p / q = 1 / 1$ have to be handled separately.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int x, y, p, q;\n    cin >> x >> y >> p >> q;\n    if (p == 0) {\n      cout << (x == 0 ? 0 : -1) << endl;\n      continue;\n    }\n    if (p == q) {\n      cout << (x == y ? 0 : -1) << endl;\n      continue;\n    }\n    int t1 = (x + p - 1) / p;\n    int t2 = ((y - x) + (q - p) - 1) / (q - p);\n    cout << (q * 1LL * max(t1, t2) - y) << endl;\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "773",
    "index": "B",
    "title": "Dynamic Problem Scoring",
    "statement": "Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.\n\nFor this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.\n\n$\\frac{\\left|\\frac{\\mathrm{Solvers~fraction~}}\\mathrm{Maxim~point~value}}{\\left|\\begin{array}{l}{\\mathrm{Soln}\\mathrm{xin}\\left|\\mathrm{pari\\value}}\\\\ {\\left(1/2,1/2\\right|}\\\\ {\\left[\\left.\\left.\\left(1/3,1/32\\right|\\right)}\\\\ {\\left(1/4,1/2\\right|}\\\\ {\\left[\\left.\\left[0,1/32\\right]}\\end{array}\\right|}}{\\left|\\begin{array}{l}{\\mathrm{Soln}\\right|}\\\\ {\\left|\\left.\\left.\\left.\\left.\\left|\\left.\\left.\\left.\\left|\\left.\\left|1/3,1/32\\right|\\right|}\\right|}}\\\\ {\\left|\\left[\\left|\\left[\\left|\\left|\\left|\\left|\\left(1/4,1/2\\right|\\right)\\right|\\right|\\begin{array}{l}{\\mathrm{Jo0}}\\\\ {\\left|\\left|\\left|\\left|\\left|\\right)}}\\\\ {\\right|\\right|\\right|}_{\\left|\\left|\\begin{array}{\\begin{array}{\\begin{array}\\right|\\right|\\right|}}}\\\\ {{\\right|\\right|\\right|\\right|}_{\\right|\\right|}$\n\nPay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to $1 / 4$, and the problem's maximum point value is equal to 1500.\n\nIf the problem's maximum point value is equal to $x$, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses $x / 250$ points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with $2000·(1 - 40 / 250) = 1680$ points for this problem.\n\nThere are $n$ participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.\n\nWith two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing.\n\nUnfortunately, Vasya is a cheater. He has registered $10^{9} + 7$ new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved.\n\nVasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts.\n\nFind the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal.",
    "tutorial": "Dynamic problem scoring used to be used more often in Codeforces rounds, including some tournament rounds like VK Cup 2015 Finals. Once you read the problem statement carefully, the problem itself isn't overly difficult. Consider new accounts Vasya puts into play. Correct solutions to which problems does he submit from these new accounts? If Vasya hasn't solved a problem, he can't submit correct solutions to it. If Vasya has solved a problem which Petya hasn't solved, then clearly Vasya wants the maximum point value of this problem to be as high as possible, thus it doesn't make sense to submit its solution from the new accounts. Suppose Vasya solved the problem at minute $v$, Petya solved it at minute $p$ and the problem's maximum point value is $m$, then Vasya's and Petya's scores for this problem are $m \\cdot (1 - v / 250)$ and $m \\cdot (1 - p / 250)$, respectively. Let's denote the difference between these values by $d = m \\cdot (p - v) / 250$. Vasya wants to maximize this value. If $p - v$ is positive (that is, Vasya solved the problem faster than Petya), then $d$ is maximized when $m$ is maximized. To maximize $m$, Vasya shouldn't submit correct solutions to this problem from the new accounts. On the other hand, if $p - v$ is negative (that is, Petya solved the problem faster than Vasya), then $d$ is maximized when $m$ is minimized. To minimize $m$, Vasya should submit correct solutions to this problem from the new accounts. Finally, if $p - v$ is zero (that is, Petya and Vasya solved the problem at the same moment), then $d = 0$ for any value of $m$, so it doesn't matter if Vasya submits correct solutions to this problem or not. It follows from the above that Vasya should always do the same for all new accounts he puts into play. Let's iterate over $x$ - the number of new accounts Vasya puts into play, starting from 0. Then we can determine what solutions Vasya should submit from these accounts using the reasoning above. Then we can calculate the maximum point values of the problems, and then the number of points Vasya and Petya will score. If Vasya's score is higher than Petya's score, then the answer is $x$, otherwise we increase $x$ by one and continue. When do we stop? If Vasya submits solutions to a problem from the new accounts, then after putting at least $n$ accounts into play the maximum point value of this problem will reach 500 and won't change anymore. If Vasya doesn't, then after putting at least $31n$ accounts into play the maximum point value of this problem will reach 3000 and won't change anymore. Therefore, if $x$ exceeds $31n$, we can stop and output -1. Note that we can't find the value of $x$ using binary search due to the fact that Vasya can't submit solutions to the problems he hasn't solved. That is, more accounts do not mean more profit. For example, consider the following test case: If Vasya doesn't use any new accounts, his score will be 1000, while Petya's score will be 500. If Vasya uses at least 61 accounts, both his and Petya's score will be 3000.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 123456;\nconst int m = 5;\nconst int k = 6;\n\nint a[N][m];\nint score[N];\nint cost[m];\nint solved[m];\n\nint main() {\n  int n;\n  scanf(\"%d\", &n);\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < m; j++) {\n      scanf(\"%d\", a[i] + j);\n      if (a[i][j] != -1) {\n        solved[j]++;\n      }\n    }\n  }\n  for (int bots = 0; bots <= ((1 << (k - 1)) - 1) * n; bots++) {\n    for (int j = 0; j < m; j++) {\n      int total = n + bots;\n      int cur = solved[j];\n      if (a[0][j] != -1 && a[1][j] != -1 && a[0][j] > a[1][j]) {\n        cur += bots;\n      }\n      cost[j] = 500;\n      while (cost[j] < 500 * k && 2 * cur <= total) {\n        cur *= 2;\n        cost[j] += 500;\n      }\n    }\n    for (int i = 0; i < 2; i++) {\n      score[i] = 0;\n      for (int j = 0; j < m; j++) {\n        if (a[i][j] != -1) {\n          score[i] += cost[j] / 250 * (250 - a[i][j]);\n        }\n      }\n    }\n    if (score[0] > score[1]) {\n      printf(\"%d\\n\", bots);\n      return 0;\n    }\n  }\n  printf(\"%d\\n\", -1);\n  return 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "773",
    "index": "C",
    "title": "Prairie Partition",
    "statement": "It can be shown that any positive integer $x$ can be uniquely represented as $x = 1 + 2 + 4 + ... + 2^{k - 1} + r$, where $k$ and $r$ are integers, $k ≥ 0$, $0 < r ≤ 2^{k}$. Let's call that representation \\underline{prairie partition} of $x$.\n\nFor example, the prairie partitions of $12$, $17$, $7$ and $1$ are:\n\n\\begin{center}\n$12 = 1 + 2 + 4 + 5$,$17 = 1 + 2 + 4 + 8 + 2$,\n\n$7 = 1 + 2 + 4$,\n\n$1 = 1$.\n\\end{center}\n\nAlice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!",
    "tutorial": "This kind of partition sometimes shows up in solutions to knapsack problems with multiple items of the same type. Let's say we want to check if the answer can be $m$. That means we have to construct $m$ chains of powers of 2 like $1, 2, 4, ..., 2^{k - 1}$ (possibly with different values of $k$), and then assign at most one of the remaining elements to each chain so that the element doesn't exceed double the largest power of 2 in its assigned chain. If we can assign all the elements successfully, $m$ is one possible answer. It can be proved that the chains can be constructed greedily one by one, with each chain as long as possible. Let's denote the number of occurrences of integer $x$ in the input by $c(x)$. Then, the number of chains where integer $2^{k}$ can be used is restricted by $bound(2^{k}) = min(c(2^{0}), c(2^{1}), ..., c(2^{k}))$. If we construct the chains greedily, then it's easy to see that the first $bound(2^{k})$ chains will use $2^{k}$. And if we use as many occurrences of powers of 2 as possible, that's better both because we are left with less elements to be assigned to the chains and because the largest powers of 2 in the chains are higher, thus more elements can be assigned to the chains. Having $m$ chains constructed, how do we quickly check if we can assign the remaining elements to these chains? This can also be done greedily. If we can't assign the largest of the remaining elements to the longest chain, then we can't assign this element to any chain, so there's no possible assignment. Otherwise, remove the largest element and the longest chain from consideration, and repeat the process until we either assign all the elements or run into a failure situation described above. Why is greedy correct? Consider a valid assignment where the largest element $E$ is assigned to some chain $c$, and some element $e$ is assigned to the longest chain $C$. If $E  \\neq  e$ and $C  \\neq  c$, it can be seen that we can as well reassign $E$ to $C$ and $e$ to $c$ to get another valid assignment. Thus, if there exists a valid assignment, there also exists one with $E$ assigned to $C$. Implemented straightforwardly, this solution works in $O(n^{2})$. In fact, both factors of $n$ can be optimized. First, it can be seen that if $m$ is one possible answer but there is at least element equal to 1 not yet involved in any chains, then $m + 1$ is another possible answer, since when we construct the $m + 1$-th chain we only make the situation better - we won't have to assigned the elements of this chain to other chains, and we'll have another chain which can be used for assignment too. Therefore, we can perform a binary search on the smallest possible value of $m$, thus having to do $O(\\log n)$ assignments instead of $O(n)$. Second, let $a$ be the largest of the input integers. All elements of the input sequence can be distributed into $2\\log a$ groups: powers of 2, and integers between consecutive powers of 2. The integers in the groups are effectively indistinguishable from our point of view, which allows us to do the assignment part in $O(\\log{a})$. Applying any of these two optimizations was enough to solve the problem.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 66;\n\nint power[MAX + 10];\nint between[MAX + 10];\nint extra[MAX + 10];\nint ende[MAX + 10];\n\nint main() {\n  int n;\n  cin >> n;\n  for (int i = 0; i < n; i++) {\n    long long foo;\n    cin >> foo;\n    int cc = 0;\n    bool good = true;\n    while (foo > 1) {\n      if (foo & 1) {\n        good = false;\n      }\n      cc++;\n      foo >>= 1;\n    }\n    if (good) {\n      power[cc]++;\n    } else {\n      between[cc]++;\n    }\n  }\n  int low = 1, high = power[0] + 1;\n  while (low < high) {\n    int mid = (low + high) >> 1;\n    int cur = mid;\n    for (int i = 0; i < MAX; i++) {\n      extra[i] = power[i] - cur;\n      int new_cur = min(cur, power[i + 1]);\n      ende[i] = cur - new_cur;\n      cur = new_cur;\n    }\n    bool fail = false;\n    int open = 0;\n    for (int i = MAX - 1; i >= 0; i--) {\n      open += ende[i];\n      open -= between[i];\n      open -= extra[i + 1];\n      if (open < 0) {\n        fail = true;\n        break;\n      }\n    }\n    open -= extra[0];\n    if (open < 0) {\n      fail = true;\n    }\n    if (fail) {\n      low = mid + 1;\n    } else {\n      high = mid;\n    }\n  }\n  if (low > power[0]) {\n    cout << -1 << endl;\n    return 0;\n  }\n  for (int i = low; i <= power[0]; i++) {\n    cout << i << \" \";\n  }\n  cout << endl;\n  return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "773",
    "index": "D",
    "title": "Perishable Roads",
    "statement": "In the country of Never, there are $n$ cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as $\\textstyle{\\frac{n(n-1)}{2}}$ roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered by Neverians.\n\nAn independent committee has evaluated each road of Never with a positive integer called the \\underline{perishability} of the road. The lower the road's perishability is, the more pleasant it is to drive through this road.\n\nIt's the year of transport in Never. It has been decided to build a museum of transport in one of the cities, and to set a single signpost directing to some city (not necessarily the one with the museum) in each of the other cities. The signposts must satisfy the following important condition: if any Neverian living in a city without the museum starts travelling from that city following the directions of the signposts, then this person will eventually arrive in the city with the museum.\n\nNeverians are incredibly positive-minded. If a Neverian travels by a route consisting of several roads, he considers the \\underline{perishability of the route} to be equal to the smallest perishability of all the roads in this route.\n\nThe government of Never has not yet decided where to build the museum, so they consider all $n$ possible options. The most important is the sum of perishabilities of the routes to the museum city from all the other cities of Never, if the travelers strictly follow the directions of the signposts. The government of Never cares about their citizens, so they want to set the signposts in a way which minimizes this sum. Help them determine the minimum possible sum for all $n$ possible options of the city where the museum can be built.",
    "tutorial": "This is my favorite problem in this contest. Several clever observations make its solution really simple. First important observation helps understand the optimal structure of the signpost directions. Suppose there are two cities A and B with the signposts directed to the same city C. Without loss of generality, suppose that the road A-C has smaller or equal perishability than the road B-C. Then, if the signpost in city B is redirected to city A instead, perishability of the route from B (as well as from other cities with routes passing through B) to the museum city won't increase. It follows that there exists an optimal solution with at most one signpost directing to each city, so the directions of the signposts form a path ending in the museum city. Second important observation is that there exists a road with the smallest perishability $p$. Let's subtract $p$ from all road perishabilities, and increase the answer by $p \\cdot (n - 1)$ in the end. Now, all roads have non-negative perishabilities, and there exists a road with perishability 0. Once our path contains such a road, perishabilities of all routes from cities after this road up the path is equal to 0. More formally, let's denote perishabilities of the roads in the path starting from the museum city as $w_{1}, w_{2}, ..., w_{n - 1}$. The sought sum is then equal to $\\sum_{i=1}^{n-1}\\operatorname*{min}_{j=1}w_{j}$. It's easy to prove that there exists some $k$ such that $w_{k} = 0$. Indeed, as we go up the path from the museum city, then once we visit an endpoint of any 0-perishability road it's good to follow this 0-perishability road so that route perishabilities of all the remaining cities become 0. Consider an optimal solution, and let $k$ be the smallest index with $w_{k} = 0$. Let's prove that for all $i  \\le  k - 3$ we have $w_{i} > w_{i + 1}$. Indeed, assume that for some $i  \\le  k - 3$ we have $w_{i}  \\le  w_{i + 1}$. Then, since the graph is complete, we can replace the $i + 1$-th edge with an edge directing to an endpoint of any 0-perishability road, and the $i + 2$-th edge with this 0-perishability road. In this case, the minimized sum will become smaller, which is a contradiction to our solution being optimal. Then, we have two options: either $w_{k - 2} > w_{k - 1}$ or $w_{k - 2}  \\le  w_{k - 1}$. If some path of the first type is optimal, then it always coincides with the minimum weight path from the museum city to some city adjacent to a 0-perishability road, and the weight of this path will be the answer. If some path of the second type is optimal, then in this path we first move to some city X, and then use two roads to move to a city adjacent to a 0-perishability road, and we increase the answer by double the weight of the first of these roads as the result of this movement - therefore, first we find the minimum weight path from the museum city to each city X, increase the weight of this path by double the smallest perishability of the roads adjacent to X, and find the answer as the smallest of these values. This gives us an $O(n^{3})$ solution if we run Dijkstra's algorithm from every vertex of the graph to find the answer for it. It can be optimized to $O(n^{2})$ if instead of running Dijkstra's algorithm from every vertex, we run just one instance of Dijkstra's algorithm, initializing the answer for each vertex with double the smallest perishability of an adjacent edge.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long inf = (long long) 1e18;\n\nconst int N = 2010;\n\nint a[N][N];\nlong long d[N];\nbool used[N];\n\nint main() {\n  // reading input data\n  int n;\n  scanf(\"%d\", &n);\n  for (int i = 0; i < n; i++) {\n    a[i][i] = 0;\n    for (int j = i + 1; j < n; j++) {\n      scanf(\"%d\", a[i] + j);\n      a[j][i] = a[i][j];\n    }\n  }\n  // finding minimum edge weight\n  int min_edge = a[0][1];\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (i != j) {\n        min_edge = min(min_edge, a[i][j]);\n      }\n    }\n  }\n  // subtracting minimum edge weight from all edge weights\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (i != j) {\n        a[i][j] -= min_edge;\n      }\n    }\n  }\n  // initializing distance array\n  for (int i = 0; i < n; i++) {\n    d[i] = inf;\n    for (int j = 0; j < n; j++) {\n      if (i != j) {\n        d[i] = min(d[i], 2LL * a[i][j]);\n      }\n    }\n    used[i] = false;\n  }\n  // running Dijkstra\n  for (int it = 0; it < n; it++) {\n    long long min_d = inf;\n    int ver = -1;\n    for (int i = 0; i < n; i++) {\n      if (!used[i] && d[i] < min_d) {\n        min_d = d[i];\n        ver = i;\n      }\n    }\n    used[ver] = true;\n    for (int i = 0; i < n; i++) {\n      d[i] = min(d[i], d[ver] + a[ver][i]);\n    }\n  }\n  // printing result\n  for (int i = 0; i < n; i++) {\n    cout << (d[i] + (long long) min_edge * (n - 1)) << endl;\n  }\n  return 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2700
  },
  {
    "contest_id": "773",
    "index": "E",
    "title": "Blog Post Rating",
    "statement": "It's well-known that blog posts are an important part of Codeforces platform. Every blog post has a global characteristic changing over time — its \\underline{community rating}. A newly created blog post's community rating is 0. Codeforces users may visit the blog post page and rate it, changing its community rating by +1 or -1.\n\nConsider the following model of Codeforces users' behavior. The $i$-th user has his own \\underline{estimated blog post rating} denoted by an integer $a_{i}$. When a user visits a blog post page, he compares his estimated blog post rating to its community rating. If his estimated rating is higher, he rates the blog post with +1 (thus, the blog post's community rating increases by 1). If his estimated rating is lower, he rates the blog post with -1 (decreasing its community rating by 1). If the estimated rating and the community rating are equal, user doesn't rate the blog post at all (in this case we'll say that user rates the blog post for 0). In any case, after this procedure user closes the blog post page and never opens it again.\n\nConsider a newly created blog post with the initial community rating of 0. For each of $n$ Codeforces users, numbered from 1 to $n$, his estimated blog post rating $a_{i}$ is known.\n\nFor each $k$ from 1 to $n$, inclusive, the following question is asked. Let users with indices from 1 to $k$, \\textbf{in some order}, visit the blog post page, rate the blog post and close the page. Each user opens the blog post only after the previous user closes it. What could be the maximum possible community rating of the blog post after these $k$ visits?",
    "tutorial": "There are several different solutions to this problem, I'll describe one of them. First, we have to determine the optimal rating order for a set of users. Using an exchange argument, it can be shown that to maximize the final community rating the users should rate the blog post in non-decreasing order of their estimated ratings. Indeed, consider an optimal rating order, consider two users with estimated ratings $x$ and $y$ next to each other in this order, and assume that $x > y$. Let's denote the community rating before these two users rate the blog post by $a$. Then here is what happens if these two users rate this blog post in the current and the reverse order: $\\left[\\begin{array}{l}{\\overbrace{\\mathrm{Gondition~}}\\!\\!\\!\\!\\!\\!\\left[\\begin{array}{l l l}{\\scriptstyle\\mathrm{Order}\\;\\mathrm{X,\\;y}\\!\\!\\!}&{\\mathrm{Order\\;\\;y,\\;\\;x}}\\\\ {\\mid\\mathrm{a<y}<1\\!\\!\\!}&{\\displaystyle\\mathrm{a+2}\\;}\\\\ {\\mid\\begin{array}{c}{{\\scriptstyle\\mathrm{a=x}}}\\\\ {{\\mid\\begin{array}{c}{{\\mathrm{a=2}}}\\\\ {{\\scriptstyle\\mathrm{a}=\\mathrm{X}}}\\\\ {{\\mid\\begin{array}{c}{{\\mathrm{a}}}\\\\ {{\\scriptstyle\\mathrm{a}=\\mathrm{X}}}\\end{array}\\right)}}\\\\ {{\\qquad\\qquad\\qquad\\qquad\\qquad\\mathrm{a+2}}}\\\\ {{\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\quad\\qquad\\qquad\\quad\\qquad\\qquad\\quad\\qquad\\qquad\\quad\\quad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\quad\\qquad\\qquad\\qquad\\qquad\\qquad\\right]}}\\\\ {\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad}}}}}&{\\qquad\\qquad\\end{array}{\\qquad}\\qquad}}}\\qquad\\end{array}\\leftend{array}\\qquad$ We can see that the $x$, $y$ order is never better than $y$, $x$. That means we can swap these two users in the order and the result won't become worse. We can continue swapping all such pairs of users until we obtain a non-decreasing order. Now, suppose users with estimated ratings $b_{1}  \\le  b_{2}  \\le  ...  \\le  b_{m}$ rate a newly created blog post. For some $x$, the first $x$ users will rate it with -1. It can be seen that the following property will hold for the rest of the users - their estimated ratings will not be lower than the community rating of the blog post at the moment of viewing the page. Thus, all remaining users will rate the blog post with +1 or 0. Let's sort all users according to their estimated rating, and maintain a segment tree which contains, for each user in this order, the difference between his estimated rating and the community rating after his view. Initially, all users are inactive and it looks like they rate the blog post with 0. Then, we'll make users active one by one in order of input. We'll also maintain three sets of active users - those who rate the blog post with +1, 0 and -1, respectively. To make a user active, first we find how he rates the blog post. Then, there are three cases: If he rates the blog post for 0, there is no need to do anything else. If he rates the blog post for -1, the rightmost -1 might change to 0. If it does, we are done. Otherwise, the community rating before users in the \"+1 and 0\" group has decreased by 1. Thus, the leftmost 0 (if it exists) changes to +1, and we're done. If he rates the blog post for +1, then either there's a user to the right of him whose value in the segment tree becomes negative, in which case the leftmost of these users now rates the blog post for 0 instead of +1, or there's no such user, in which case nothing else changes. All operations above can be performed using queries to our sets of users and segment tree. For example, when a user appears who rated the blog post with +1, we have to insert him into the +1 set and make a query to the segment tree to decrease the value by 1 in the range from this user to the last user. The answer - that is, the maximum possible community rating after the first $k$ users - is the size of the +1 set minus the size of the -1 set.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline int signum(int x) {\n  return (x < 0 ? -1 : (x > 0 ? 1 : 0));\n}\n\nconst int inf = (int) 1e9;\n\nconst int N = 500010;\n\npair <int, int> a[N];\nint pos[N];\n\npair <int, int> mn[4 * N];\nint add[4 * N];\n\nvoid push(int x) {\n  add[x + x] += add[x];\n  mn[x + x].first += add[x];\n  add[x + x + 1] += add[x];\n  mn[x + x + 1].first += add[x];\n  add[x] = 0;\n}\n\nvoid pull(int x) {\n  mn[x] = min(mn[x + x], mn[x + x + 1]);\n}\n\nvoid build(int x, int l, int r) {\n  add[x] = 0;\n  if (l == r) {\n    mn[x] = make_pair(a[l].first, l);\n    return;\n  }\n  int y = (l + r) >> 1;\n  build(x + x, l, y);\n  build(x + x + 1, y + 1, r);\n  pull(x);\n}\n\nvoid modify(int x, int l, int r, int ll, int rr, int v) {\n  if (ll <= l && r <= rr) {\n    add[x] -= v;\n    mn[x].first -= v;\n    return;\n  }\n  push(x);\n  int y = (l + r) >> 1;\n  if (ll <= y) {\n    modify(x + x, l, y, ll, rr, v);\n  }\n  if (rr > y) {\n    modify(x + x + 1, y + 1, r, ll, rr, v);\n  }\n  pull(x);\n}\n\npair <int, int> find_min(int x, int l, int r, int ll, int rr) {\n  if (ll <= l && r <= rr) {\n    return mn[x];\n  }\n  push(x);\n  int y = (l + r) >> 1;\n  pair <int, int> res = make_pair(inf, -1);\n  if (ll <= y) {\n    res = min(res, find_min(x + x, l, y, ll, rr));\n  }\n  if (rr > y) {\n    res = min(res, find_min(x + x + 1, y + 1, r, ll, rr));\n  }\n  pull(x);\n  return res;\n}\n\nint main() {\n  int n;\n  scanf(\"%d\", &n);\n  for (int i = 0; i < n; i++) {\n    scanf(\"%d\", &a[i].first);\n    a[i].second = i;\n  }\n  sort(a, a + n);\n  for (int i = 0; i < n; i++) {\n    pos[a[i].second] = i;\n  }\n  build(1, 0, n - 1);\n  set <int> minus, zero, plus;\n  for (int id = 0; id < n; id++) {\n    int i = pos[id];\n    auto p = find_min(1, 0, n - 1, i, i);\n    int vote = signum(p.first);\n    if (vote == 0) {\n      zero.insert(i);\n    } else {\n      if (vote == -1) {\n        minus.insert(i);\n        modify(1, 0, n - 1, i, n - 1, -1);\n        int last_minus = *(--minus.end());\n        if (a[last_minus].first == 1 - (int) minus.size()) {\n          minus.erase(last_minus);\n          modify(1, 0, n - 1, last_minus, n - 1, 1);\n          zero.insert(last_minus);\n        } else {\n          if (!zero.empty()) {\n            int first_zero = *(zero.begin());\n            zero.erase(first_zero);\n            plus.insert(first_zero);\n            modify(1, 0, n - 1, first_zero, n - 1, 1);\n          }\n        }\n      } else {\n        plus.insert(i);\n        modify(1, 0, n - 1, i, n - 1, 1);\n        auto q = find_min(1, 0, n - 1, i, n - 1);\n        if (q.first == -1) {\n          int pos = q.second;\n          plus.erase(pos);\n          modify(1, 0, n - 1, pos, n - 1, -1);\n          zero.insert(pos);\n        }\n      }\n    }\n    printf(\"%d\\n\", (int) plus.size() - (int) minus.size());\n  }\n  return 0;\n}",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "773",
    "index": "F",
    "title": "Test Data Generation",
    "statement": "Test data generation is not an easy task! Often, generating big random test cases is not enough to ensure thorough testing of solutions for correctness.\n\nFor example, consider a problem from an old Codeforces round. Its input format looks roughly as follows:\n\n{The first line contains a single integer $n$ ($1 ≤ n ≤ max_{n}$) — the size of the set. The second line contains $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$ ($1 ≤ a_{i} ≤ max_{a}$) — the elements of the set \\textbf{in increasing order}.}\n\nIf you don't pay attention to the problem solution, it looks fairly easy to generate a good test case for this problem. Let $n = max_{n}$, take random distinct $a_{i}$ from 1 to $max_{a}$, sort them... Soon you understand that it's not that easy.\n\nHere is the actual problem solution. Let $g$ be the greatest common divisor of $a_{1}, a_{2}, ..., a_{n}$. Let $x = a_{n} / g - n$. Then the correct solution outputs \"Alice\" if $x$ is odd, and \"Bob\" if $x$ is even.\n\nConsider two wrong solutions to this problem which differ from the correct one only in the formula for calculating $x$.\n\nThe first wrong solution calculates $x$ as $x = a_{n} / g$ (without subtracting $n$).\n\nThe second wrong solution calculates $x$ as $x = a_{n} - n$ (without dividing by $g$).\n\nA test case is interesting if it makes \\textbf{both} wrong solutions output an incorrect answer.\n\nGiven $max_{n}$, $max_{a}$ and $q$, find the number of interesting test cases satisfying the constraints, and output it modulo $q$.",
    "tutorial": "This problem was inspired by division 1 problem A from Codeforces Round #201, which I tested: http://codeforces.com/contest/346/problem/A. Several hours before the round, I noticed that all test cases except for the examples were generated randomly. Moreover, there were three cases with $max_{n} = 10$ and $max_{a} = 100$, twenty cases with $max_{n} = 100$ and $max_{a} = 10^{9}$, and that's all. Not surprisingly, all test cases had even $n$ and greatest common divisor equal to 1. The problem statement tells us that interesting test cases have odd $n$, even $a_{n}$, and odd $a_{n} / g$. Suppose that $g$ is divisible by $2^{k}$ and not divisible by $2^{k + 1}$ for some $k  \\ge  1$. Let's focus on interesting test cases with some fixed value of $k$. We choose integers $a_{1} < a_{2} < ... < a_{n}$ from 1 to $max_{a}$, all divisible by $2^{k}$, with $a_{n}$ not divisible by $2^{k + 1}$. This is equivalent to choosing integers $a_{1} < a_{2} < ... < a_{n}$ from 1 to $b=\\lfloor{\\frac{m a x_{a}}{2^{k}}}\\rfloor$ with $a_{n}$ being odd. Thus, for fixed $k$, the problem asks us to calculate the number of ways to choose at most $max_{n}$, but an odd number, of integers from 1 to $b$ so that the largest chosen number is odd. Let $f(b, n, p)$ be the number of ways to choose exactly $n$ integers from 1 to $b$ so that the largest chosen number has parity $p$ (we define $f(b, 0, 0) = 1$ and $f(b, 0, 1) = 0$). Suppose that for fixed $b$ we have calculated the values of $f(b, n, p)$ for all $n  \\le  max_{n}$ and $p\\in\\{0,1\\}$. Can we calculate all the values of $f(2b, n, p)$ quickly? Yes, we can! Here is a formula which allows us to do that: $f(2b,n,p)=f(b,n,p)+\\sum_{i=0}^{n-1}(f(b,i,0)+f(b,i,1))\\cdot f(b,n-i,p\\oplus(b\\mathrm{~mod~2)})$ The first summand corresponds to the case when out of integers from 1 to $2b$, we only choose those from 1 to $b$. In the other case, we iterate over $i$ - the number of integers chosen from 1 to $b$. It follows that we don't care about the parity of the largest of these $i$ integers, but we have $n - i$ integers chosen from $b + 1$ to $2b$, and we know the number of ways to choose those with the largest integer of the required parity (which might change if $b$ is odd). This formula allows us to calculate all the values of $f(2b, n, p)$ in $O(max_{n}^{2})$, but we can still do better. Let $x_{i} = f(b, i, 0) + f(b, i, 1)$ and $y_{i}=f(b,j,p\\oplus(b\\mathrm{~\\mod~}2))$. Then, $f(2b,n,p)-f(b,n,p)+x_{n}\\cdot y_{0}=\\sum_{i=0}^{n}x_{i}\\cdot y_{n-i}$ The right hand side is nothing else but the convolution of sequences $x$ and $y$, so all these values can be calculated in $O(m a x_{n}\\log m a x_{n})$ using Fast Fourier Transform. The modulo $q$ given in the input was set to a low enough value so that doing FFT in doubles and rounding the result to the nearest integer gave enough precision. Discrete Fourier Transform with two different modulos can also be used, though it's several times slower. It's also important that, given all the values of $f(b, n, p)$, it's easy to calculate all the values of $f(b + 1, n, p)$ in $O(max_{n})$ time. This means we can calculate the values of $f(b, n, p)$ for any $b$ in $O(m a x_{n}\\log m a x_{n}\\log b)$ using an idea similar to exponentiation by squaring. Finally, recall that we need to find the values of $f(b, n, p)$ for all $b=\\lfloor{\\frac{m a x_{a}}{2^{k}}}\\rfloor$, that is, for $\\log m a x_{a}$ different values of $b$. Doing calculations separately for all $b$ gives a solution which works in $O(m a x_{n}\\log m a x_{n}\\log^{2}m a x_{a})$. We can do better if we notice that while doing calculations for $b=\\lfloor{\\frac{m a x_{a}}{2}}\\rfloor$, we also do the calculations for all $b=\\lfloor{\\frac{m a x_{a}}{2^{k}}}\\rfloor$ naturally. Thus, we only need $\\log m a x_{a}$ convolutions. The final complexity of the solution is $O(r m a x_{n}\\log r n a x_{n}\\log r m a x_{a})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n\n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nconst long double pi = acos((ld)-1.0);\n\nconst int maxn = 1 << 16;\n\ntypedef complex<double> comp;\n\ncomp oddc[maxn], evenc[maxn], tmp[maxn];\ncomp w[maxn], invw[maxn];\nll odd[maxn], even[maxn];\nint oldodd[maxn], oldeven[maxn];\nint btr[maxn];\nint n, A, mod;\nint st2;\nint answer;\n\ninline int bitrev(int x)\n{\n    return btr[x];\n}\n\nvoid fft(comp *a, int n, comp *w, comp *res)\n{\n    for (int i = 0; i < n; i++) res[bitrev(i)] = a[i];\n    for (int len = 2; len <= n; len *= 2)\n    {\n        int step = n / len;\n        for (int i = 0; i < n; i += len)\n        {\n            int curw = 0;\n            for (int j = 0; j < len / 2; j++)\n            {\n                comp x = res[i + j];\n                comp y = res[i + len / 2 + j] * w[curw];\n                res[i + j] = x + y;\n                res[i + len / 2 + j] = x - y;\n                curw += step;\n            }\n        }\n    }\n}\n\nvoid preparefft(int n)\n{\n    for (int i = 0; i < n; i++)\n    {\n        int cur = i;\n        for (int j = 0; (1 << j) < n; j++)\n        {\n            btr[i] = (btr[i] << 1) | (cur & 1);\n            cur >>= 1;\n        }\n    }\n    for (int i = 0; i < n; i++)\n    {\n        w[i] = comp(cos(2 * pi / n * i), sin(2 * pi / n * i));\n        invw[i] = w[i];\n    }\n    reverse(invw + 1, invw + n);\n}\n\nvoid conv(ll *from, comp *to)\n{\n    for (int i = n + 1; i < st2; i++) tmp[i] = 0;\n    for (int i = 0; i <= n; i++) tmp[i] = from[i];\n    fft(tmp, st2, w, to);\n}\n\nvoid convback(comp *from, ll *to)\n{\n    fft(from, st2, invw, tmp);\n    for (int i = 0; i < st2; i++) tmp[i] /= st2;\n    for (int i = 0; i <= n; i++)\n    {\n        to[i] = (ll)(tmp[i].real() + 0.5);\n        assert(abs(tmp[i].imag()) < 0.1);\n    }\n}\n\nvoid addans()\n{\n    for (int i = 1; i <= n; i += 2) answer = (answer + odd[i]) % mod;\n}\n\nvoid go(int A)\n{\n    if (A == 1)\n    {\n        even[0] = 1;\n        odd[0] = 0;\n        odd[1] = 1;\n        addans();\n        return;\n    }\n    go(A / 2);\n\n    for (int i = 0; i <= n; i++) oldodd[i] = odd[i];\n    for (int i = 0; i <= n; i++) oldeven[i] = even[i];\n    conv(even, evenc);\n    conv(odd, oddc);\n    for (int i = 0; i < st2; i++)\n    {\n        if ((A / 2) % 2 == 0)\n        {\n            tie(oddc[i], evenc[i])  = make_pair((oddc[i] + evenc[i]) * oddc[i], (oddc[i] + evenc[i]) * (evenc[i] - (comp)1));\n        } else\n        {\n            tie(evenc[i], oddc[i])  = make_pair((oddc[i] + evenc[i]) * oddc[i], (oddc[i] + evenc[i]) * (evenc[i] - (comp)1));\n        }\n    }\n    convback(oddc, odd);\n    convback(evenc, even);\n    for (int i = n + 1; i <= 2 * n; i++)\n    {\n        odd[i] = 0;\n        even[i] = 0;\n    }\n    for (int i = 0; i <= n; i++)\n    {\n        odd[i] = (odd[i] + oldodd[i]) % mod;\n        even[i] = (even[i] + oldeven[i]) % mod;\n    }\n    if (A % 2 == 1)\n    {\n        for (int i = n; i >= 1; i--)\n        {\n            odd[i] = (odd[i] + odd[i - 1] + even[i - 1]) % mod;\n        }\n    }\n    addans();\n}\n\nint main()\n{\n    cin >> n >> A >> mod;\n    if (A == 1)\n    {\n        cout << 0 << endl;\n        return 0;\n    }\n    st2 = 0;\n    while ((1 << st2) <= n) st2++;\n    st2++;\n    st2 = 1 << st2;\n    preparefft(st2);\n    go(A / 2);\n    cout << answer << endl;\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 3400
  },
  {
    "contest_id": "776",
    "index": "A",
    "title": "A Serial Killer",
    "statement": "Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.\n\nThe killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.\n\nYou need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.",
    "tutorial": "You just have to store the current two strings. This can simply be done by replacing the string to be deleted with the new string. This can be done in O(n)",
    "code": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <deque>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n\n#ifdef PRINTERS\n#include \"printers.hpp\"\nusing namespace printers;\n#define tr(a)\t\tcerr<<#a<<\": \"<<a<<endl;\n#else\n#define tr(a)    \n#endif\n\n#define ll          long long\n#define pb          push_back\n#define mp          make_pair\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (int)x.size()\n#define hell        1000000007\n#define endl        '\\n'\n#define rep(i,a,b)\tfor(int i=a;i<b;i++)\nusing namespace std;\n\nvoid solve(){\n\tstring a,b;\n\tcin>>a>>b;\n\tvector<string>taken;\n\tint n;\n\tcin>>n;\n\trep(i,0,n){\n\t\tcout<<a<<\" \"<<b<<endl;\n\t\tstring c,d;\n\t\tcin>>c>>d;\n\t\tif(c==a)a=d;\n\t\telse b=d;\n\t}\n\tcout<<a<<\" \"<<b<<endl;\n}\n\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\tint t=1;\n\twhile(t--){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "776",
    "index": "B",
    "title": "Sherlock and his girlfriend",
    "statement": "Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.\n\nHe bought $n$ pieces of jewelry. The $i$-th piece has price equal to $i + 1$, that is, the prices of the jewelry are $2, 3, 4, ... n + 1$.\n\nWatson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.\n\nHelp Sherlock complete this trivial task.",
    "tutorial": "Hint: Observe that if $i + 1$ is prime, then only would the pieces having their prices as the multiples of $i + 1$ would have to be of a different color. Editorial: We are required to color the jewelry pieces such that for every jewelry piece $i$ having a price $i + 1$, all the pieces whose prices are prime divisors of $i + 1$ should have colors different from that of the $i$th piece. This can be achieved by simply coloring all the pieces with their prices as primes in one color, and all the other pieces in a second color. We calculate the Sieve of Eratosthenes upto the range of $n(  \\le  10^{5})$ and thus, obtain the list of primes as well as non-primes.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint sieve[100005];\n\nint main()\n{\n\tint i, n, j;\n\tcin>>n;\n\tfor(i=2; i<=n+1; i++)\n\t{\n\t\tif(!sieve[i])\n\t\t\tfor(j=2*i; j<=n+1; j+=i)\n\t\t\t\tsieve[j]=1;\n\t}\n\t\n\tif(n>2)\n\t\tcout<<\"2\\n\";\n\telse\n\t\tcout<<\"1\\n\";\n\n\tfor(i=2; i<=n+1; i++)\n\t{\n\t\tif(!sieve[i])\n\t\t\tcout<<\"1 \";\n\t\telse\n\t\t\tcout<<\"2 \";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "776",
    "index": "C",
    "title": "Molly's Chemicals",
    "statement": "Molly Hooper has $n$ different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The $i$-th of them has affection value $a_{i}$.\n\nMolly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative \\textbf{integer} power of $k$. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.\n\nHelp her to do so in finding the total number of such segments.",
    "tutorial": "Hint: The number of possible powers will be less than 50 for any $k$. Editorial: We are going to loop over all possible non-negative powers of $k$. Since the maximum possible value of subarray sum can be $10^{5}  \\times  10^{9} = 10^{14}$, there can be at most $\\lfloor\\log_{2}10^{14}\\rfloor+1$ possible powers that can be the sum of subarrays. Let $p[i]$ be the sum of elements from index $1$ to index $i$. We can precalculate $p[i]$ in $O(n)$ time complexity. (Prefix sum) We will try to find the count of subarrays starting from index $l$. The sum of any such subarray ending at index $r$ can be written as $p[r] - p[l - 1]$. Now, $p[r]-p[l-1]=w\\implies p[r]=w+p[l-1]$ where $w$ is a power of $k$. We have to count the values of $r  \\ge  l$ such that $p[r] = w + p[l - 1]$. For this part, we can store the count of $p[r]$ in a dictionary as we move from right of the array and use the dictionary to find count of $p[r]$ for corresponding $p[l]$ and $w$. PS: Do take care of a corner case for $k =  \\pm  1$ while calculating powers of $k$.",
    "code": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <deque>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <stack>\n#include <string>\n\n#ifdef PRINTERS\n#include \"printers.hpp\"\nusing namespace printers;\n#define tr(a)        cerr<<#a<<\": \"<<a<<endl;\n#else\n#define tr(a)    \n#endif\n#define ll          long long\n#define pb          push_back\n#define mp          make_pair\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (int)x.size()\n#define hell        1000000007\n#define endl        '\\n'\n#define rep(i,a,b)    for(int i=a;i<b;i++)\nusing namespace std;\n\nvoid solve(){\n    int N,k;\n    scanf(\"%d%d\",&N,&k);\n    ll x[N+1];\n    x[0]=0;\n    rep(i,0,N)scanf(\"%lld\",&x[i+1]);\n    partial_sum(x,x+N+1,x);\n    if(k==1){\n        ll ans=0;\n        map<ll,int>m;\n        for(int i=N;i>=0;i--){\n            if(m.find(x[i]+1)!=m.end())\n                ans+=m[x[i]+1];\n            m[x[i]]++;\n        }\n        printf(\"%lld\\n\",ans);\n    }\n    else if(k==-1){\n        ll ans=0;\n        map<ll,int>m;\n        for(int i=N;i>=0;i--){\n            if(m.find(x[i]+1)!=m.end())\n                ans+=m[x[i]+1];\n            if(m.find(x[i]-1)!=m.end())\n                ans+=m[x[i]-1];\n            \n            m[x[i]]++;\n        }\n        printf(\"%lld\\n\",ans);\n    }\n    else{\n        ll ans=0;\n        map<ll,int>m;\n        for(int i=N;i>=0;i--){\n            ll cur=1;\n            while(true){\n                if(abs(cur)>=1e15)break;\n                if(m.find(x[i]+cur)!=m.end())\n                ans+=m[x[i]+cur];\n                cur*=k;\n            }\n            m[x[i]]++;\n        }\n        printf(\"%lld\\n\",ans);\n    }\n}\n\nsigned main(){\n    int t=1;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "776",
    "index": "D",
    "title": "The Door Problem",
    "statement": "Moriarty has trapped $n$ people in $n$ distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are $m$ switches. Each switch control doors of some rooms, but each door is controlled by \\textbf{exactly two} switches.\n\nYou are given the initial configuration of the doors. Toggling any switch, that is, turning it ON when it is OFF, or turning it OFF when it is ON, toggles the condition of the doors that this switch controls. Say, we toggled switch $1$, which was connected to room $1$, $2$ and $3$ which were respectively locked, unlocked and unlocked. Then, after toggling the switch, they become unlocked, locked and locked.\n\nYou need to tell Sherlock, if there exists a way to unlock all doors at the same time.",
    "tutorial": "Hint : Try to model the situation as a graph with rooms as edges and switches as nodes. Editorial : All rooms are represented as edges. Mark the edges as $1$ if the room is open else mark the edge as closed. The answer will be \"YES\" if you can color the graph in such a manner that the edges having value $0$ have both nodes under different color (if the door is locked then one of the switches should be selected) and the edges having $1$ have both nodes under same color (if the door is unlocked you should either select both switches or neither of them). For checking the same start a bfs from switch $1$ and toggle it and proceed, if you are able to color all of the switches then the answer is \"YES\" else it is not possible. Complexity: $O(N + M)$ See the setter's solution for implementation details.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define mem(x,y) memset(x,y,sizeof(x))\n#define bitcount    __builtin_popcountll\n#define mod 1000000007\n#define N 1000009\n#define fast ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define ss(s) cin>>s;\n#define si(x)  scanf(\"%d\",&x);\n#define sl(x)  cin>>x;\n#define pb push_back\n#define mp make_pair\n#define all(v) v.begin(),v.end()\n#define S second\n#define F first\n#define ll long long\nint n,m;\nvector<int> arr[N];\nint arr1[N];\nvector<pair<int,int > > adj[100008];                    //max-size\nvoid graph(int n){for(int i=1;i<=n;i++){\n\t\t\t\t\tint x = arr[i][0];\n\t\t\t\t\tint y = arr[i][1];\n\t\t\t\t\tadj[x].push_back(mp(y,arr1[i] ));                           //arr1[i] stores th color of the edge\n\t\t\t\t\tadj[y].push_back(mp(x,arr1[i]) );}\n\n}\nint col[N];\nbool vis[N];\nint main(){\n//fast                          //uncomment on submission\ncin>>n>>m;\nassert(n>=2 && n<=100000);\nassert(m>=2 && m<=100000);\nfor(int i =1;i<=n;i++)cin >> arr1[i];\nfor(int i = 1;i<=m;i++){\n    int sz;\n    cin >> sz;\n    for(int j =0;j<sz;j++){\n        int y ;\n        cin >> y;\n        arr[y].push_back(i);\n    }\n}\ngraph(n);\nmem(col,-1);\nmem(vis,false);\nbool p = true;\nfor(int i = 1;i<=m;i++){\n\tif(!vis[i] && adj[i].size()){\n\t\tcol[i] = 0;\n\t\tvis[i] = true;\n\t\tqueue <int > q;\n\t\tq.push(i);\n\n\t\twhile(q.size()){\n\t\t\tint node = q.front();\n\t\t\tq.pop();\n\t\n\t\t\tfor(auto pi:adj[node]){\n\t\t\t\tint co = col[node];\n\t\t\t\tif(pi.S == 0){                       //if the edge is 0 then give the opposite color.\n\t\t\t\t\tco = 1 - co;\n\n\t\t}\n\t\tif(vis[pi.F] && col[pi.F] != co){\n\t\t\tp = false;\n\t\t}\n\t\tif(!vis[pi.F]){\n\t\t\tcol[pi.F] = co;\n\t\t\tvis[pi.F] = true;\n\t\t\tq.push(pi.F);\n\n\t\t}\n\t}\n}\n}\n}\n\nif(!p)cout<<\"NO\";\nelse cout<<\"YES\";\n\n}",
    "tags": [
      "2-sat",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "776",
    "index": "E",
    "title": "The Holmes Children",
    "statement": "The Holmes children are fighting over who amongst them is the cleverest.\n\nMycroft asked Sherlock and Eurus to find value of $f(n)$, where $f(1) = 1$ and for $n ≥ 2$, $f(n)$ is the number of distinct ordered positive integer pairs $(x, y)$ that satisfy $x + y = n$ and $gcd(x, y) = 1$. The integer $gcd(a, b)$ is the greatest common divisor of $a$ and $b$.\n\nSherlock said that solving this was child's play and asked Mycroft to instead get the value of $g(n)=\\sum_{d\\mid n}f(n/d)$. Summation is done over all positive integers $d$ that divide $n$.\n\nEurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft.\n\nShe defined a $k$-composite function $F_{k}(n)$ recursively as follows:\n\n\\[\nF_{k}(n)=\\left\\{\\begin{array}{l}{{f(g(n)),}}\\\\ {{g(F_{k-1}(n)),~~\\mathrm{for}~k>1~\\mathrm{and}~k~\\mathrm{mod}~2=0,}}\\\\ {{f(F_{k-1}(n)),~~\\mathrm{for}~k>1~\\mathrm{and}~k~\\mathrm{mod}~2=1.}}\\end{array}\\right.\n\\]\n\nShe wants them to tell the value of $F_{k}(n)$ modulo $1000000007$.",
    "tutorial": "Hint: For $n = 10$, the pairs satisfying the conditions are $(1, 9), (3, 7), (7, 3), (9, 1)$. The first members of each pair form the set ${1, 3, 7, 9}$. Similarly, for $n = 12$, the corresponding set is ${1, 5, 7, 11}$. Also, observe that $f(n) = n - 1$ whenever $n$ is a prime. Editorial: Given, $x+y=N{\\mathrm{~and~}}g c d(x,y)=1$ $\\Rightarrow g c d(x,n-x)=1$ $\\Rightarrow g c d(x,n)=1$ $\\Rightarrow{\\textbf{x i s c o p r i m e t o n}}$ Now,let's prove the converse. Let $x$ be coprime to $n$ and $y = n - x$. Let $gcd(x, y) = k  \\neq  1$ $\\Rightarrow{\\mathrm{k~divides~both~x~and~n}}$ $\\Rightarrow{\\mathrm{k~divides~n}}$ $\\Rightarrow{\\mathrm{k~divides~both~x~and~n~which~is~a~contradiction}}$ $\\Rightarrow g c d(x,y)=1$ Thus, number of distinct ordered pairs (x,y) satisfying the conditions= $ \\phi (n)$ where $ \\phi $() denotes Euler totient function. Now,$g(n)=\\sum_{d\\mid n}\\phi(n/d)$. Let $S$ denote the set ${1, 2, ..., n}$. We distribute the integers of $S$ into disjoint sets as follows. For each divisor d of n, let $A(d) = {k \\in S: gcd(k, n) = d}$.The sets $A(d)$ form a disjoint collection whose union is $S$. Let $n(A(d))$ denote the number of integers in $A(d)$. If $k$ is a number in $A(d)$, then $k = d * m$ for some $m$ coprime to $n / d$. There are $ \\phi (n / d)$ such $m$ in the interval $[1, n]$. Hence, $n(A(d)) =  \\phi (n / d)$. Since the sets $A(d)$ are disjoint, $\\textstyle\\sum_{d\\mid n}n(A(d))=n$ $\\Rightarrow\\sum_{d|n}\\phi(n/d)=n$ $\\Rightarrow g(n)=n$ So, we only need to consider the number of times we apply $f()$ in $F_{k}$ which is $(k + 1) / 2$ for a given $k$. Now, let us consider the numbers in the set ${1, 2, ..., 2n}$. There are exactly $n$ even and $n$ odd numbers in the set. The $n$ even numbers can never be coprime to $2n$. So, $ \\phi (2n)  \\le  n$. Thus, we need to calculate $ \\phi ()$ at most $log(n)$ times. Complexity: $O({\\sqrt{n}}*l o g(n))$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll          long long\n#define MOD         1000000007\n#define ll          long long\n#define pb          push_back\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define endl        '\\n'\n#define PI          3.14159265359d\n#define sz(x)       (int)x.size()\nll phi(ll n)\n{\n    ll i,res=n;\n    for(i=2;i*i<=n;i++)\n        if(n%i==0)\n    {\n        while(n%i==0)\n            n/=i;\n        res-=res/i;\n    }\n    if(n>1)\n        res-=res/n;\n    return res;\n}\nint main()\n{\n    ll n,k,res;\n    cin>>n>>k;\n    res=n;\n    k=(k+1)/2;\n    while(k--)\n    {\n        res=phi(res);\n        if(res==1)\n            break;\n    }\n    cout<<res%MOD;\n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "776",
    "index": "F",
    "title": "Sherlock's bet to Moriarty",
    "statement": "Sherlock met Moriarty for a final battle of wits. He gave him a regular $n$ sided convex polygon. In addition to it, he gave him certain diagonals to form regions on the polygon. It was guaranteed that the diagonals did not intersect in interior points.\n\nHe took each of the region and calculated its importance value. Importance value for a region formed by vertices $a_{1}, a_{2}, ... , a_{x}$ of the polygon will be given by $2^{a1} + 2^{a2} + ... + 2^{ax}$. Then, he sorted these regions on the basis of their importance value in ascending order. After that he assigned each region an index from $1$ to $k$, where $k$ is the number of regions, and index of region is its position in the sorted array calculated above.\n\nHe wants Moriarty to color the regions using not more than $20$ colors, such that two regions have same color only if all the simple paths between these two regions have at least one region with color value less than the color value assigned to these regions. Simple path between two regions $f$ and $h$ is a sequence of regions $r_{1}, r_{2}, ... r_{t}$ such that $r_{1} = f$, $r_{t} = h$, for each $1 ≤ i < t$ regions $r_{i}$ and $r_{i + 1}$ share an edge, and $r_{i} = r_{j}$ if and only if $i = j$.\n\nMoriarty couldn't answer and asks Sherlock to solve it himself. Help Sherlock in doing so.",
    "tutorial": "Hint: Observe that if we consider all regions as nodes for a graph and connect two regions if they share an edge (in the form of sharing a diagonal), we will get a tree. Editorial: Use a greedy approach to form a tree from the given polygon. Let us take one diagonal between vertex $a$ and $b$ $(b > a)$. Let us define a value $x$ as minimum of two values $b - a - 1$ and $n - 2 - (b - a - 1)$. Sort all the diagonals on the basis of this value $x$. This value is the minimum number of nodes between $a$ and $b$. Remove the diagonals one by one. We can see that a new region will be formed each time which cannot be divided further, and this region will be formed on the side from where we got the value of $x$. Thus we can get the nodes in each region and form a tree. Then, this problem reduces to coloring the tree such that two regions have same color only if atleast one node between the two nodes with same color has a color with lesser value. This can be done by using the divide and conquer technique of centroid decomposition. Give each height in centroid tree a different color in increasing order. Complexity: $O(n * log(n))$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define sd(x) scanf(\"%d\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define ss(x) scanf(\"%s\",x)\n#define ll long long\n#define mod 1000000007\n#define bitcount    __builtin_popcountll\n#define pb push_back\n#define fi first\n#define se second\n#define mp make_pair\n#define pi pair<int,int>\npi arr[100005];\nint n,m;\nbool cmp(pi x, pi y)\n{\n\tint a=min(x.se-x.fi-1,n-2-(x.se-x.fi-1));\n\tint b=min(y.se-y.fi-1,n-2-(y.se-y.fi-1));\n\treturn a<b;\n}\nvector<int>nodes[100005];\nvector<int>v[100005],v2[100005];\nint de[100005],siz[100005];\nvoid dfs1(int node, int par)\n{\n\tsiz[node]=1;\n\tfor(int i=0;i<v[node].size();i++)\n\t{\n\t\tif(de[v[node][i]]==0&&v[node][i]!=par)\n\t\t{\n\t\t\tdfs1(v[node][i],node);\n\t\t\tsiz[node]+=siz[v[node][i]];\n\t\t}\n\t}\n}\nint dfs2(int node, int par,int s)\n{\n\tint maxi=0,maxinode;\n\tfor(int i=0;i<v[node].size();i++)\n\t{\n\t\tif(de[v[node][i]]==0&&v[node][i]!=par&&siz[v[node][i]]>s/2)\n\t\t{\n\t\t\treturn dfs2(v[node][i],node,s);\n\t\t}\n\t}\n\t//printf(\"%d\\n\",node );\n\treturn node;\n}\nint decompose(int node)\n{\n\tdfs1(node,-1);\n\tint cen=dfs2(node,-1,siz[node]);\n\t// printf(\"%d\\n\",cen );\n\tde[cen]=1;\n\tfor(int i=0;i<v[cen].size();i++)\n\t{\n\t\tif(de[v[cen][i]]==0)\n\t\t{\n\t\t\tint x=decompose(v[cen][i]);\n\t\t\t//printf(\"%d\\n\", x);\n\t\t\tv2[cen].pb(x);\n\t\t\tv2[x].pb(cen);\n\t\t}\n\t}\n\n\treturn cen;\n}\nint level[100005];\nint main()\n{\n    //freopen(\"in.txt\",\"r\",stdin);\n    //freopen(\"out.txt\",\"w\",stdout);\n    int i,j,k;\n    sd(n);\n    sd(m);\n    for(i=1;i<=m;i++)\n    {\n    \tsd(arr[i].fi);\n    \tsd(arr[i].se);\n    \tif(arr[i].fi>arr[i].se)\n    \t{\n    \t\tswap(arr[i].fi,arr[i].se);\n    \t}\n    }\n    sort(arr+1,arr+m+1,cmp);\n    set<int>s;\n    for(i=1;i<=n;i++)\n    \ts.insert(i);\n    k=0;\n    for(i=1;i<=m;i++)\n    {\n    \tif(arr[i].se-arr[i].fi-1<=n-2-(arr[i].se-arr[i].fi-1))\n    \t{\n    \t\tnodes[k].pb(arr[i].fi);\n    \t\tset<int>::iterator it=s.upper_bound(arr[i].fi);\n    \t\twhile((*it)!=arr[i].se)\n    \t\t{\n    \t\t\tnodes[k].pb(*it);\n    \t\t\tit++;\n    \t\t}\n    \t\tnodes[k].pb(arr[i].se);\n    \t\tfor(j=1;j<nodes[k].size()-1;j++)\n    \t\t\ts.erase(nodes[k][j]);\n    \t}\n    \telse\n    \t{\n    \t\twhile(*s.begin()!=arr[i].fi)\n    \t\t{\n    \t\t\tnodes[k].pb(*s.begin());\n    \t\t\ts.erase(s.begin());\n    \t\t}\n    \t\tnodes[k].pb(arr[i].fi);\n    \t\tnodes[k].pb(arr[i].se);\n    \t\tint l=nodes[k].size();\n    \t\tset<int>::iterator it=s.upper_bound(arr[i].se);\n    \t\twhile(it!=s.end())\n    \t\t{\n    \t\t\tnodes[k].pb(*it);\n    \t\t\tit++;\n    \t\t}\n    \t\tfor(;l<nodes[k].size();l++)\n    \t\t\ts.erase(nodes[k][l]);\n    \t}\n    \treverse(nodes[k].begin(), nodes[k].end());\n    \tk++;\n    }\n    while(s.size()!=0)\n    {\n    \tnodes[k].pb(*s.begin());\n    \ts.erase(s.begin());\n    }\n   \treverse(nodes[k].begin(), nodes[k].end());\n\tk++;\n    sort(nodes,nodes+k);\n    map<pi,int>m1;\n    for(i=0;i<k;i++)\n    {\n    \tfor(j=0;j<nodes[i].size()-1;j++)\n    \t{\n    \t\tif(nodes[i][j]==nodes[i][j+1]+1)\n    \t\t\tcontinue;\n    \t\telse if(m1.find(mp(nodes[i][j],nodes[i][j+1]))!=m1.end())\n    \t\t{\n    \t\t\tv[m1[mp(nodes[i][j],nodes[i][j+1])]].pb(i+1);\n    \t\t\tv[i+1].pb(m1[mp(nodes[i][j],nodes[i][j+1])]);\n    \t\t\tm1.erase(mp(nodes[i][j],nodes[i][j+1]));\n    \t\t}\n    \t\telse\n    \t\t{\n    \t\t\tm1[mp(nodes[i][j],nodes[i][j+1])]=i+1;\n    \t\t}\n    \t}\n    \tj=nodes[i].size()-1;\n    \tif(nodes[i][0]!=n||nodes[i][j]!=1)\n    \t{\n    \t\tif(m1.find(mp(nodes[i][0],nodes[i][j]))!=m1.end())\n    \t\t{\n    \t\t\tv[m1[mp(nodes[i][0],nodes[i][j])]].pb(i+1);\n    \t\t\tv[i+1].pb(m1[mp(nodes[i][0],nodes[i][j])]);\n    \t\t\tm1.erase(mp(nodes[i][0],nodes[i][j]));\n    \t\t}\n    \t\telse\n    \t\t{\n    \t\t\tm1[mp(nodes[i][0],nodes[i][j])]=i+1;\n    \t\t}\n    \t}\n    }\n    for(i=1;i<=n;i++)\n    \tlevel[i]=1e6;\n    int cen=decompose(1);\n\t//printf(\"%d\\n\",cen );\n\tqueue<int>q;\n\ti=0;\n\tq.push(cen);\n\twhile(!q.empty())\n\t{\n\t\tj=q.size();\n\t\twhile(j--)\n\t\t{\n\t\t\tint z=q.front();\n\t\t\tq.pop();\n\t\t\tlevel[z]=i;\n\t\t\tfor(int l=0;l<v2[z].size();l++)\n\t\t\t{\n\t\t\t\tif(level[v2[z][l]]==1e6)\n\t\t\t\t{\n\t\t\t\t\tq.push(v2[z][l]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\tfor(i=1;i<=k;i++){\n\t\t//printf(\"%d %d\\n\",v2[i].size(),level[i] );\n\t\tprintf(\"%d\",level[i]+1 );\n\t\tif(i!=k)\n\t\tprintf(\" \");\n\t}\n\tprintf(\"\\n\");\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "geometry",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "776",
    "index": "G",
    "title": "Sherlock and the Encrypted Data",
    "statement": "Sherlock found a piece of encrypted data which he thinks will be useful to catch Moriarty. The encrypted data consists of two integer $l$ and $r$. He noticed that these integers were in hexadecimal form.\n\nHe takes each of the integers from $l$ to $r$, and performs the following operations:\n\n- He lists the distinct digits present in the given number. For example: for $1014_{16}$, he lists the digits as $1, 0, 4$.\n- Then he sums respective powers of two for each digit listed in the step above. Like in the above example $sum = 2^{1} + 2^{0} + 2^{4} = 19_{10}$.\n- He changes the initial number by applying bitwise xor of the initial number and the sum. Example: $1014_{16}\\oplus19_{10}=4116_{10}\\oplus19_{10}=4103_{10}$. Note that xor is done in binary notation.\n\nOne more example: for integer 1e the sum is $sum = 2^{1} + 2^{14}$. Letters a, b, c, d, e, f denote hexadecimal digits $10$, $11$, $12$, $13$, $14$, $15$, respertively.\n\nSherlock wants to count the numbers in the range from $l$ to $r$ (both inclusive) which decrease on application of the above four steps. He wants you to answer his $q$ queries for different $l$ and $r$.",
    "tutorial": "Hint: This problem can be solved using dynamic programming approach by maintain dp for mask of digits appearing in the number($mask1$) along with position in the number($l$) and mask of last $16$ bits($mask2$) of the number formed upto $l$. Editorial: Observe that only the most significant bit of the $mask1$ is required to check if the number will decrease or not. So, form a $dp[most: significant: bit: of: mask1][mask2][len]$. Complexity: $O(16 * 2^{16} * 16 * 16)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define sd(x) scanf(\"%lld\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define ss(x) scanf(\"%s\",x)\n#define ll long long\n#define mod 65536\n#define bitcount    __builtin_popcountll\n#define pb push_back\n#define fi first\n#define se second\n#define mp make_pair\n#define pi pair<int,int>\nll dp[17][65538][17];\nchar a[20];\nll b[20];\nll mo[1100005];\nll f(ll m,ll p,ll pos)\n{\n\tif(dp[m][p][pos]!=-1)\n\t\treturn dp[m][p][pos];\n\tif(pos==0)\n\t{\n\t\tif(((1<<m)&p))\n\t\t\tdp[m][p][pos]=1;\n\t\telse\n\t\t\tdp[m][p][pos]=0;\n\t\treturn dp[m][p][pos];\n\t}\n\tll j=0;\n\tfor(ll i=0;i<=15;i++)\n\t{\n\t\tj+=f(max(m,i),mo[p*16+i],pos-1);\n\t}\n\treturn dp[m][p][pos]=j;\n}\nint main()\n{\n    //freopen(\"in.txt\",\"r\",stdin);\n    //freopen(\"out.txt\",\"w\",stdout);\n\tll t,n,i,j,k,l,r,m,p,ans1;\n\tmo[0]=0;\n\tfor(i=1;i<=1100000;i++)\n\t{\n\t\tmo[i]=mo[i-1]+1;\n\t\tif(mo[i]==mod)\n\t\t\tmo[i]=0;\n\t}\n\tmemset(dp,-1,sizeof dp);\n\tf(0,0,16);\n\tsd(t);\n\twhile(t--)\n\t{\n\t\tss(a);\n\t\tn=strlen(a);\n\t\tl=0;\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tl=l*16;\n\t\t\tif(a[i]>='0'&&a[i]<='9')\n\t\t\t\tl+=a[i]-'0';\n\t\t\telse\n\t\t\t\tl+=a[i]-'a'+10;\n\t\t}\n\t\tans1=0;\n\t\tif(l>0)\n\t\t{\n\t\t\tl--;\n\t\t\tj=l;\n\t\t\tfor(i=0;i<n;i++)\n\t\t\t{\n\t\t\t\tb[i]=j%16;\n\t\t\t\tj/=16;\n\t\t\t}\n\t\t\tm=p=0;\n\t\t\tfor(j=n-1;j>=0;j--)\n\t\t\t{\n\t\t\t\tfor(k=0;k<b[j];k++)\n\t\t\t\t\tans1-=dp[max(m,k)][mo[p*16+k]][j];\n\t\t\t\tm=max(m,b[j]);\n\t\t\t\tp=mo[p*16+b[j]];\n\t\t\t}\n\t\t\tans1-=dp[m][p][0];\n\t\t}\n\t\tss(a);\n\t\tn=strlen(a);\n\t\tr=0;\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tr=r*16;\n\t\t\tif(a[i]>='0'&&a[i]<='9')\n\t\t\t\tr+=a[i]-'0';\n\t\t\telse\n\t\t\t\tr+=a[i]-'a'+10;\n\t\t}\n\t\tj=r;\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tb[i]=j%16;\n\t\t\tj/=16;\n\t\t}\n\t\tm=p=0;\n\t\tfor(j=n-1;j>=0;j--)\n\t\t{\n\t\t\tfor(k=0;k<b[j];k++)\n\t\t\t\tans1+=dp[max(m,k)][mo[p*16+k]][j];\n\t\t\tm=max(m,b[j]);\n\t\t\tp=mo[p*16+b[j]];\n\t\t}\n\t\tans1+=dp[m][p][0];\n\t\tprintf(\"%lld\\n\",ans1);\n\t}\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "777",
    "index": "A",
    "title": "Shell Game",
    "statement": "Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball.\n\nBomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.).\n\nLet's number shells from $0$ to $2$ from left to right. Thus the left shell is assigned number $0$, the middle shell is $1$ and the right shell is $2$. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly $n$ movements were made by the operator and the ball was under shell $x$ at the end. Now he wonders, what was the initial position of the ball?",
    "tutorial": "Fix the initial numeration of shells. Consider function $p(i, j)$ to be the index of the shell located at position $j$ after $i$ moves. $p(0) = {0, 1, 2}$ $p(1) = {1, 0, 2}$ $p(2) = {1, 2, 0}$ $p(3) = {2, 1, 0}$ $p(4) = {2, 0, 1}$ $p(5) = {0, 2, 1}$ $p(6) = {0, 1, 2}$ Thus, after $6$ movements all shells will get back to initial positions. To solve the problem we need to take $n$ modulo $6$ and simulate that number of moves.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "777",
    "index": "B",
    "title": "Game of Credit Cards",
    "statement": "After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.\n\nRules of this game are simple: each player bring his favourite $n$-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if $n = 3$, Sherlock's card is $123$ and Moriarty's card has number $321$, first Sherlock names $1$ and Moriarty names $3$ so Sherlock gets a flick. Then they both digit $2$ so no one gets a flick. Finally, Sherlock names $3$, while Moriarty names $1$ and gets a flick.\n\nOf course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name $1$, $2$, $3$ and get no flicks at all, or he can name $2$, $3$ and $1$ to give Sherlock two flicks.\n\nYour goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.",
    "tutorial": "First we want to consider a strategy that minimizes the amount of flicks Moriarty will receive from Sherlock. This is similar to loosing as few rounds as possible. He can use digit 0 can be used to not loose against digit 0, digit 1 to not loose against digits 0 and 1 and so on. Thus, Moriarty should try all digits from 0 to 9 and greedily apply them to Sherlock's digits they can beat. If the maximum number of rounds Moriarty can not loose is $a$ the answer for the first question is $n - a$. For the second question we need to count the maximum number of rounds Moriarty can win. Now digit 0 is useless, digit 1 wins against digit 0, digit 2 wins against digits 0 and 1, and so on. Thus, Moriarty should consider his digits from 0 to 9 and greedily use them to digits they can beat.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "777",
    "index": "C",
    "title": "Alyona and Spreadsheet",
    "statement": "During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.\n\nNow she has a table filled with integers. The table consists of $n$ rows and $m$ columns. By $a_{i, j}$ we will denote the integer located at the $i$-th row and the $j$-th column. We say that the table is sorted in non-decreasing order in the column $j$ if $a_{i, j} ≤ a_{i + 1, j}$ for all $i$ from $1$ to $n - 1$.\n\nTeacher gave Alyona $k$ tasks. For each of the tasks two integers $l$ and $r$ are given and Alyona has to answer the following question: if one keeps the rows from $l$ to $r$ inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such $j$ that $a_{i, j} ≤ a_{i + 1, j}$ for all $i$ from $l$ to $r - 1$ inclusive.\n\nAlyona is too small to deal with this task and asks you to help!",
    "tutorial": "For each cell $(i, j)$ compute value $up(i, j)$ equal to maximum $r$, such that table is non-decreasing in row $j$ if we keep only rows from $i$ to $r$ inclusive. This values can be computed in $O(nm)$ time using the following formulas: $up(i, j) = up(i + 1, j) + 1$, if $i < n$ and $a_{i, j} < a_{i + 1, j}$; $up(i, j) = 1$ otherwise. To process the query $(l_{i}, r_{i})$ we have to check whether there exists $k$ such that $up(l_{i}, k)  \\ge  r_{i}$. We will answer this questions using by precomputing maximum values in each row $b e s t(i)=\\operatorname*{max}_{j=1}u p(i,j)$.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "777",
    "index": "D",
    "title": "Cloud of Hashtags",
    "statement": "Vasya is an administrator of a public page of organization \"Mouse and keyboard\" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it \\textbf{without} the symbol '#'.\n\nThe head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).\n\nVasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is \\textbf{minimum} possible. If there are several optimal solutions, he is fine with any of them.",
    "tutorial": "It is possible to solve this problem in many ways. One of them was to iterate over all strings in reversed order and to try to leave the longest possible prefix of each string greedily without breaking the statement. Let's prove this solution formally. Note that the set of possible lengths of some string $s_{i}$ in a correct answer forms a segment between $1$ and some critical length $l_{i}$. Indeed, if there exists a correct answer with $i$-string having a length of $x  \\ge  2$, then there also exists an answer with $i$-th string having a length of $x - 1$, since it is possible to leave only the first symbol of all previous strings and make the answer correct. Let's express $l_{i}$ through $l_{i + 1}$. Reduce the length of $(i + 1)$-st string to $l_{i + 1}$ and consider two options. First, $s_{i}$ may be lexicographically not greater than $s_{i + 1}$, and in this case we may obviously let $l_{i}$ be equal to $|s_{i}|$. Otherwise, $l_{i}$ can't be larger than $lcp(s_{i}, s_{i + 1})$ where $lcp$ deontes the length of the longest common prefix of two strings (if we keep $s_{i}$ longer, it will be larger than any possible prefix of $s_{i + 1}$). At the same time, if we reduce $s_{i}$ up to $lcp(s_{i}, s_{i + 1})$, it will be correct. So, we may let $l_{i}$ be equal to $lcp(s_{i}, s_{i + 1})$. Note that due to the way we defined $l_{i}$, if we just reduce any string up to its maximum possible length, it will also be a correct answer. So, it is also a correct answer to the original problem.",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "777",
    "index": "E",
    "title": "Hanoi Factory",
    "statement": "Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.\n\nThere are $n$ rings in factory's stock. The $i$-th ring has inner radius $a_{i}$, outer radius $b_{i}$ and height $h_{i}$. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:\n\n- Outer radiuses form a non-increasing sequence, i.e. one can put the $j$-th ring on the $i$-th ring only if $b_{j} ≤ b_{i}$.\n- Rings should not fall one into the the other. That means one can place ring $j$ on the ring $i$ only if $b_{j} > a_{i}$.\n- The total height of all rings used should be maximum possible.",
    "tutorial": "To start with make the following observation: if two rings $i$ and $j$ have equal outer radiuses $b_{i} = b_{j}$ they can be merged in one ring of the same outer radius, inner radius equal to $min(a_{i}, a_{j})$ and height equal to $h_{i} + h_{j}$. Using the observation we transform our problem to the one with distinct outer radiuses. Sort ring by this radius in descending order. From this point we consider $b_{i} < b_{j}$ for all $i > j$. For each ring we want to compute value $ans(i)$ - maximum height of the tower that ends with the ring $i$. This dynamic programming can be computed in $O(n^{2})$ time using the following formula: $a n s(i)=\\operatorname*{max}_{j<i,a_{i}<b_{i}}a n s(j)+h_{i}$. There are two different ways to speed up the calculation of this dp: Keep rings sorted by inner radius in a separate array. For each ring $j < i$ store its value of $ans(j)$ there and $0$ for others. To get $max ans(j)$ we have to query maximum on some suffix of this array: from the one hand only rings with original index $j < i$ will be non-zero, from the other hand this will suffice the condition $b_{i} > a_{j}$. This can be done using segment tree or binary indexed tree. Note that if $i < j < k$ and it's possible to place ring $k$ on ring $j$ and ring $k$ on ring $i$, then it's possible to place ring $j$ on ring $i$. Indeed, from $a_{i} < b_{k}$ and $b_{k} < b_{j}$ follows $a_{i} < b_{j}$. That means we only need to compute for each $i$ maximum value $j$ such that $a_{j} < b_{i}$. This can be done using data structures listed above or just with a single pass over array with a stack. Go from left to right and keep indexes of all valid positions in increasing order. Pop elements while they do not suffice condition $a_{j} < a_{i}$ and then put $i$ on the top. For clarifications, check the following code: stack <int> opt; for (int i = 0; i < n; i++) { while (!opt.empty() && r[opt.back()].inner >= r[i].outer) opt.pop(); if (!opt.empty()) ans[i] = ans[opt.back()]; ans[i] += r[i].height; opt.push(i); }",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "778",
    "index": "A",
    "title": "String Game",
    "statement": "Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.\n\nSergey gives Nastya the word $t$ and wants to get the word $p$ out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word $t$: $a_{1}... a_{|t|}$. We denote the length of word $x$ as $|x|$. Note that after removing one letter, the indices of other letters don't change. For example, if $t = $\"nastya\" and $a = [4, 1, 5, 3, 2, 6]$ then removals make the following sequence of words \"nastya\" $\\to$ \"{nas\\sout{t}ya}\" $\\to$ \"{\\sout{n}as\\sout{t}ya}\" $\\to$ \"{\\sout{n}as\\sout{t}\\sout{y}a}\" $\\to$ \"{\\sout{n}a\\sout{s}\\sout{t}\\sout{y}a}\" $\\to$ \"{\\sout{n}\\sout{a}\\sout{s}\\sout{t}\\sout{y}a}\" $\\to$ \"{\\sout{n}\\sout{a}\\sout{s}\\sout{t}\\sout{y}\\sout{a}}\".\n\nSergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word $p$. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.\n\nIt is guaranteed that the word $p$ can be obtained by removing the letters from word $t$.",
    "tutorial": "In this problem we have to find the last moment of time, when $t$ has $p$ as a subsequence. If at some moment of time $p$ is a subsequence of $t$ then at any moment before, $p$ is also its subsequence. That's why the solution is binary search for the number of moves, Nastya makes. For binary search for a moment of time $m$ we need to check, if $p$ is a subsequence of $t$. We remove $a_{1}, a_{2}, ... a_{m}$ and check if $p$ is a subsequence greedily.",
    "tags": [
      "binary search",
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "778",
    "index": "B",
    "title": "Bitwise Formula",
    "statement": "Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.\n\nInitially, Bob chooses integer $m$, bit depth of the game, which means that all numbers in the game will consist of $m$ bits. Then he asks Peter to choose some $m$-bit number. After that, Bob computes the values of $n$ variables. Each variable is assigned either a constant $m$-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.\n\nBob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.",
    "tutorial": "Note that changing $i$-th bit of chosen number doesn't change any bits of any of the variables other than $i$-th one. Also note that the total number of values is greater, as more variables have 1 at $i$-th position. Let's solve for every bit independently: learn, what is the value of $i$-th bit of chosen number. We can try both values and simulate the given program. Choose one of the values that makes more variables to have 1 at $i$-th position. If both 0 and 1 give equal number of variables to have 1 at $i$-th position, choose 0.",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "expression parsing",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "778",
    "index": "C",
    "title": "Peterson Polyglot",
    "statement": "Peterson loves to learn new languages, but his favorite hobby is making new ones. Language is a set of words, and word is a sequence of lowercase Latin letters.\n\nPeterson makes new language every morning. It is difficult task to store the whole language, so Peterson have invented new data structure for storing his languages which is called \\underline{broom}. Broom is rooted tree with edges marked with letters. Initially broom is represented by the only vertex — the root of the broom. When Peterson wants to add new word to the language he stands at the root and processes the letters of new word one by one. Consider that Peterson stands at the vertex $u$. If there is an edge from $u$ marked with current letter, Peterson goes through this edge. Otherwise Peterson adds new edge from $u$ to the new vertex $v$, marks it with the current letter and goes through the new edge. Size of broom is the number of vertices in it.\n\nIn the evening after working day Peterson can't understand the language he made this morning. It is too difficult for bored Peterson and he tries to make it simpler. Simplification of the language is the process of erasing some letters from some words of this language. Formally, Peterson takes some positive integer $p$ and erases $p$-th letter from all the words of this language having length at least $p$. Letters in words are indexed starting by 1. Peterson considers that simplification should change at least one word, i.e. there has to be at least one word of length at least $p$. Peterson tries to make his language as simple as possible, so he wants to choose $p$ such that the size of the broom for his simplified language is as small as possible.\n\nPeterson is pretty annoyed with this task so he asks you for help. Write a program to find the smallest possible size of the broom and integer $p$.",
    "tutorial": "While erasing letters on position $p$, trie changes like the following: all the edges from one fixed vertex of depth $p$ are merging into one. You can see it on the picture in the sample explanation. After merging of the subtrees we have the only tree - union of subtrees as the result. Consider the following algorithm. For every vertex $v$ iterate over all the subtrees of $v$'s children except for the children having largest subtree. There is an interesting fact: this algorithm works in $O(n\\log n)$ in total. Denote as $s_{x}$ the size of the subtree rooted at vertex $x$. Let $h_{v}$ be the $v$'s child with the largest subtree, i.e. $s_{u}  \\le  s_{hv}$ for every $u$ - children of $v$. If $u$ is a child of $v$ and $u  \\neq  h_{v}$ then $s_{u}<{\\frac{\\sin}{2}}$. Let's prove that. Let $s_{h_{\\mathrm{U}}}<\\frac{s_{\\mathrm{H}}}{2}$. Then $s_{u}\\leq s_{h v}<{\\frac{s_{v}}{2}}$ and $s_{u}<{\\frac{\\sin}{2}}$. Otherwise, if $s_{h_{v}}\\geq{\\frac{s_{w}}{2}}$, then we know that $s_{u} + s_{hv} < s_{v}$. Therefore, $s_{u}<s_{v}-s_{h v}\\Rightarrow s_{u}<s_{v}-{\\textstyle\\frac{s_{\\mathrm{n}}}{2}}\\implies s_{u}<{\\textstyle\\frac{s_{\\mathrm{n}}}{2}}$. Consider vertex $w$ and look at the moments of time when we have iterated over it. Let's go up through the ancestors of $w$. Every time we iterate over $w$ the size of the current subtree becomes twice greater. Therefore we could't iterate over $w$ more than $\\lceil\\log_{2}n\\rceil$ times in total. It proves that time complexity of this algorithm is $O(n\\log n)$. Solution: Iterate over all integers $p$ up to the depth of the trie For every vertex $v$ of depth $p$ Unite all the subtrees of $v$ with running over all of them except for the largest one. How to unite subtrees? First method. Find the largest subtree: it has been already built. Try to add another subtree in the following way. Let's run over smaller subtree's vertices and add new vertices into respective places of larger subtree. As the result we will have the union of the subtrees of $v$'s children. All we need from this union is it's size. After that we need to roll it back. Let's remember all the memory cells, which were changed while merging trees, and their old values. After merging we can restore it's old values in reverse order. Is it possible to implement merging without rolling back? Second method. Let's take all the subtrees except for the largest one and build their union using new memory. After that we should have two subtrees: the largest one and the union of the rest. We can find size of their union without any changes. Everything we need is to run over one of these trees examining another tree for the existence of respective vertices. After this we can reuse the memory we have used for building new tree.",
    "tags": [
      "brute force",
      "dfs and similar",
      "dsu",
      "hashing",
      "strings",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "778",
    "index": "D",
    "title": "Parquet Re-laying",
    "statement": "Peter decided to lay a parquet in the room of size $n × m$, the parquet consists of tiles of size $1 × 2$. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it.\n\nThe workers decided that removing entire parquet and then laying it again is very difficult task, so they decided to make such an operation every hour: remove two tiles, which form a $2 × 2$ square, rotate them 90 degrees and put them back on the same place.\n\nThey have no idea how to obtain the desired configuration using these operations, and whether it is possible at all.\n\nHelp Peter to make a plan for the workers or tell that it is impossible. The plan should contain at most $100 000$ commands.",
    "tutorial": "Let's assume that the width of the rectangle is even (if not, flip the rectangle). Convert both start and final configurations into the configuration where all tiles lie horizontally. After that, since all the moves are reversible, simply reverse the sequence of moves for the final configuration. How to obtain a configuration in which all tiles lie horizontally. Let's go from top to bottom, left to right, and put all the tiles in the correct position. If the tile lie vertically, then try to turn it into the correct position. If it cannot be rotated, because the neighboring tile is oriented differently, proceed recursively to it. Thus, you get a \"ladder\", which can not go further than $n$ tiles down. At the end of the ladder there will be two tiles, oriented the same way. Making operations from the bottom up, we'll put the top tile in a horizontal position.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2700
  },
  {
    "contest_id": "778",
    "index": "E",
    "title": "Selling Numbers",
    "statement": "Boris really likes numbers and even owns a small shop selling interesting numbers. He has $n$ decimal numbers $B_{i}$. Cost of the number in his shop is equal to the sum of costs of its digits. You are given the values $c_{d}$, where $c_{d}$ is the cost of the digit $d$. Of course, Boris is interested in that numbers he owns have the maximum cost possible.\n\nRecently Boris got hold of the magical artifact $A$, which can allow him to increase the cost of his collection. Artifact is a string, consisting of digits and '?' symbols. To use the artifact, Boris must replace all '?' with digits to get a decimal number without leading zeros (it is also not allowed to get number 0). After that, the resulting number is added to all numbers $B_{i}$ in Boris' collection. He uses the artifact exactly once.\n\nWhat is the maximum cost of the collection Boris can achieve after using the artifact?",
    "tutorial": "Because the target value for this problem is calculated independently for all digits, we'll use the dynamic programming approach. Define $dp_{k, C}$ as the maximum possible cost of digits after we processed $k$ least significant digits in $A$ and $C$ is the set of numbers having the carry in current digit. This information is sufficient to choose the digit in the current position in $A$ and recalculate the $C$ set and DP value for the next digit. The key observation is that there are only $n + 1$ possible sets instead of $2^{n}$. Consider last $k$ digits of $A$ and $B_{i}$. Sort all the length-$k$ suffixes of $B_{i}$ in descending lexicographical order. Because all these suffixes will be increased by the same value, the property of having the carry is monotone. That means that all possible sets $C$ are the prefixes of length $m$ ($0  \\le  m  \\le  n$) of this sorted list of suffixes. This fact allows us to reduce the number of DP states to $O(n \\cdot |A|)$. Sorting all suffixes of $B_{i}$ can be accomplished using the radix sort, appending the digits to the left and recalculating the order. The only thing that's left is to make all DP transitions in $O(1)$ time. To do that, maintain the total cost of all digits and the amount of numbers that have the carry. After adding one more number with carry in current digit, these two values can be easily recalculated. After processing all digits in $A$, we have to handle the remaining digits in $B_{i}$ (if there are any) and take the best answer. Total running time is $O(n\\cdot\\operatorname*{max}(|A|,|B_{i}|))$.",
    "tags": [
      "dp",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "779",
    "index": "A",
    "title": "Pupils Redistribution",
    "statement": "In Berland each high school student is characterized by academic performance — integer value between $1$ and $5$.\n\nIn high school 0xFF there are two groups of pupils: the group $A$ and the group $B$. Each group consists of exactly $n$ students. An academic performance of each student is known — integer value between $1$ and $5$.\n\nThe school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to $1$, the same number of students whose academic performance is $2$ and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal.\n\nTo achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class $A$ and one student of class $B$. After that, they both change their groups.\n\nPrint the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance.",
    "tutorial": "To solve this problem let's use array $cnt[]$. We need to iterate through first array with academic performances and for current performance $x$ let's increase $cnt[x]$ on one. In the same way we need to iterate through the second array and decrease $cnt[x]$ on one. If after that at least one element of array $cnt[]$ is odd the answer is $- 1$ (it means that there are odd number of student with such performance and it is impossible to divide them in two. If all elements are even the answer is the sum of absolute values of array $cnt$ divided by 2. In the end we need to divide the answer on 2 because each change will be counted twice with this way of finding the answer.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "779",
    "index": "B",
    "title": "Weird Rounding",
    "statement": "Polycarp is crazy about round numbers. He especially likes the numbers divisible by $10^{k}$.\n\nIn the given number of $n$ Polycarp wants to remove the least number of digits to get a number that is divisible by $10^{k}$. For example, if $k = 3$, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by $10^{3} = 1000$.\n\nWrite a program that prints the minimum number of digits to be deleted from the given integer number $n$, so that the result is divisible by $10^{k}$. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).\n\nIt is guaranteed that the answer exists.",
    "tutorial": "To solve this problem we need to make $k$ zeroes in the end of number $n$. Let's look on the given number as on the string and iterate through it beginning from the end (i.e. from the low order digit). Let $cnt$ equals to the number of digits which we reviewed. If the current digit does not equal to zero we need to increase the answer on one. If $cnt$ became equal to $k$ and we reviewed not all digits we need to print the answer. In the other case we need to remove from the string all digits except one, which equals to zero (if there are more than one such digit we left only one of them). Such digit always exists because the problem statement guaranteed that the answer exists.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "779",
    "index": "C",
    "title": "Dishonest Sellers",
    "statement": "Igor found out discounts in a shop and decided to buy $n$ items. Discounts at the store will last for a week and Igor knows about each item that its price now is $a_{i}$, and after a week of discounts its price will be $b_{i}$.\n\nNot all of sellers are honest, so now some products could be more expensive than after a week of discounts.\n\nIgor decided that buy \\textbf{at least} $k$ of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all $n$ items.",
    "tutorial": "To solve this problem we need at first to sort all items in increasing order of values $a_{i} - b_{i}$. Then let's iterate through sorted array. If for the current item $x$ we did not buy $k$ items now and if after discounts it will cost not more than now, we need to buy it now and pay $a_{x}$, in the other case we need to buy item $x$ after discounts and pay $b_{x}$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "780",
    "index": "A",
    "title": "Andryusha and Socks",
    "statement": "Andryusha is an orderly boy and likes to keep things in their place.\n\nToday he faced a problem to put his socks in the wardrobe. He has $n$ distinct pairs of socks which are initially in a bag. The pairs are numbered from $1$ to $n$. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.\n\nAndryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?",
    "tutorial": "This is a simple implementation problem. Store an array for whether a sock of each type is currently on the table, along with the total number of socks, and the largest number encountered. It is now easy to process socks one by one and maintain everything. Complexity: $O(n)$ time and memory.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "780",
    "index": "B",
    "title": "The Meeting Place Cannot Be Changed",
    "statement": "The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.\n\nAt some points on the road there are $n$ friends, and $i$-th of them is standing at the point $x_{i}$ meters and can move with any speed no greater than $v_{i}$ meters per second in any of the two directions along the road: south or north.\n\nYou are to compute the minimum time needed to gather all the $n$ friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.",
    "tutorial": "We will apply binary search to solve this problem. Inside the binary search we have to check if it is possible to meet within $t$ seconds. In this time, $i$-th friend can get anywhere within the segment $[x_{i} - tv_{i}, x_{i} + tv_{i}]$. For the meeting to be possible, there must be a point common to all these segments, that is, their intersection must be non-empty. An easy way to intersect a number of segments $[l_{1}, r_{1}]$, ..., $[l_{n}, r_{n}]$ is to compute $L = max l_{i}$ and $R = min r_{i}$. If $L  \\le  R$, then $[L, R]$ is the intersection, otherwise, the intersection is empty. Complexity: $O(n\\log(\\varepsilon^{-1}))$ time and $O(n)$ memory. Here $ \\epsilon $ is the required relative precision.",
    "tags": [
      "binary search"
    ],
    "rating": 1600
  },
  {
    "contest_id": "780",
    "index": "C",
    "title": "Andryusha and Colored Balloons",
    "statement": "Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.\n\nThe park consists of $n$ squares connected with $(n - 1)$ bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from $1$. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if $a$, $b$ and $c$ are distinct squares that $a$ and $b$ have a direct path between them, and $b$ and $c$ have a direct path between them, then balloon colors on these three squares are distinct.\n\nAndryusha wants to use as little different colors as possible. Help him to choose the colors!",
    "tutorial": "If $v$ is a vertex of degree $d$, then the answer is at least $d + 1$. Indeed, any two neighbours of $v$ can be connected by a path of length three via vertex $v$. Also, $v$ lies on a common three-vertex path with any of its neighbours (possibly using a non-neighbour vertex). It follows that $v$ and all of its neighbours must have pairwise distinct colors. Let us show that the strongest of these estimates is best possible, that is, construct a coloring with $D + 1$ colors, where $D$ is the maximal degree. Root the tree at arbitrary vertex, and color the root with color 1, also color its children with subsequent colors. All the rest vertices will be colored as follows: if a vertex $v$ is colored $x$, and its parent is colored $y$, then for the children of $v$ we will use numbers starting from 1 skipping $x$ and $y$. One can check that no color with number larger than $D + 1$ shall be used. Implementation-wise, this is a simple DFS procedure. Complexity: $O(n)$ time and memory.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "780",
    "index": "D",
    "title": "Innokenty and a Football League",
    "statement": "Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of \\textbf{three letters}.\n\nEach club's full name consist of two words: the team's name and the hometown's name, for example, \"DINAMO BYTECITY\". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that:\n\n- the short name is the same as three first letters of the team's name, for example, for the mentioned club it is \"DIN\",\n- or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is \"DIB\".\n\nApart from this, there is a rule that if for some club $x$ the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club $x$. For example, if the above mentioned club has short name \"DIB\", then no club for which the first option is chosen can have short name equal to \"DIN\". However, it is possible that some club have short name \"DIN\", where \"DI\" are the first two letters of the team's name, and \"N\" is the first letter of hometown's name. Of course, no two teams can have the same short name.\n\nHelp Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.",
    "tutorial": "Let us write $a_{i}$ and $b_{i}$ for first and second options for $i$-th club name. If all $a_{i}$ are distinct, we can assign all of them to be club names without conflict. Otherwise, suppose that for clubs $i$, $j$ we have $a_{i} = a_{j}$, hence we can't use them simultaneously. Note that, say, choosing $a_{i}$ and $b_{j}$ is also forbidden by the statement. It follows that we must use $b_{i}$ and $b_{j}$ as $i$-th and $j$-th club names respectively. If for some other club $k$ we now have $a_{k} = b_{i}$, then we are forced to use $b_{k}$ as its name as well. We can process this kind of chain conflicts with a BFS-like procedure. If at any point we are forced to use the same name for two different clubs, then the answer is NO. Otherwise, resolving all conflicts will yield a correct assignment. Complexity: $O(n)$ memory and time if implemented carefully (not necessary though).",
    "tags": [
      "2-sat",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "780",
    "index": "E",
    "title": "Underground Lab",
    "statement": "The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.\n\nThe lab can be pictured as a connected graph with $n$ vertices and $m$ edges. $k$ clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.\n\nEach clone can visit at most $\\left\\lceil{\\frac{2m}{k}}\\right\\rceil$ vertices before the lab explodes.\n\nYour task is to choose starting vertices and searching routes for the clones. Each route can have at most $\\left\\lceil{\\frac{2m}{k}}\\right\\rceil$ vertices.",
    "tutorial": "Let's start a DFS at any vertex of the graph, and produce an Euler tour - the order of vertices visited by a DFS, where each vertex $v$ is written down every time DFS visits it (in particular, when a recursive call made from $v$ terminates). Note that the Euler tour has exactly $2n - 1$ entries in it, hence it would be a correct answer for $k = 1$. For a general $k$, cut the Euler tour into $k$ consecutive pieces of size at most $ \\lceil  2n / k \\rceil $, and yield it as an answer. Note that each path of the answer has to contain at least one vertex. Complexity: $O(n + m)$ time and memory.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "780",
    "index": "F",
    "title": "Axel and Marston in Bitland",
    "statement": "A couple of friends, Axel and Marston are travelling across the country of Bitland. There are $n$ towns in Bitland, with some pairs of towns connected by one-directional roads. Each road in Bitland is either a pedestrian road or a bike road. There can be multiple roads between any pair of towns, and may even be a road from a town to itself. However, no pair of roads shares the starting and the destination towns along with their types simultaneously.\n\nThe friends are now located in the town 1 and are planning the travel route. Axel enjoys walking, while Marston prefers biking. In order to choose a route diverse and equally interesting for both friends, they have agreed upon the following procedure for choosing the road types during the travel:\n\n- The route starts with a pedestrian route.\n- Suppose that a beginning of the route is written in a string $s$ of letters P (pedestrain road) and B (biking road). Then, the string $\\overline{{\\mathbf{X}}}$ is appended to $s$, where $\\overline{{\\mathbf{X}}}$ stands for the string $s$ with each character changed to opposite (that is, all pedestrian roads changed to bike roads, and vice versa).\n\nIn the first few steps the route will look as follows: P, PB, PBBP, PBBPBPPB, PBBPBPPBBPPBPBBP, and so on.\n\nAfter that the friends start travelling from the town 1 via Bitlandian roads, choosing the next road according to the next character of their route type each time. If it is impossible to choose the next road, the friends terminate their travel and fly home instead.\n\nHelp the friends to find the longest possible route that can be travelled along roads of Bitland according to the road types choosing procedure described above. If there is such a route with more than $10^{18}$ roads in it, print -1 instead.",
    "tutorial": "Let us write $A_{i}$ for the binary string obtained after $i$ inverse-append steps, for example, $A_{0} = 0$, $A_{1} = 01$, and so on. Let us also write $B_{i}={\\overline{{A_{i}}}}$. By definition we must have $A_{i+1}=A_{i}B_{i}$, and $B_{i+1}=B_{i}A_{i}$. Let us store matrices $P_{k}$ and $Q_{k}$, with entries $P_{k} / Q_{k}(v, u)$ equal to 1 for pairs of vertices $v, u$ such that there is a $A_{k}$/$B_{k}$-path from $v$ to $u$. Note that $P_{0}$ and $Q_{0}$ are exactly the adjacency matrices with 0- and 1-arcs respectively. Next, note that $P_{k + 1}(v, u) = 1$ if and only if there is a vertex $w$ such that $P_{k}(v, w) = Q_{k}(w, u) = 1$, and a similar condition can be written for $Q_{k + 1}(v, u)$. It follows that $P_{k + 1}$ and $Q_{k + 1}$ can be computed using $P_{k}$ and $Q_{k}$ in $O(n^{3})$ time (the method is basically boolean matrix multiplication: $P_{k+1}=P_{k}Q_{k}$, $Q_{k+1}=Q_{k}P_{k}$). To use the matrices $P_{k}$ and $Q_{k}$ to find the answer, let us store $L$ - the largest answer found, and $S$ - the set of vertices reachable from the vertex 1 in exactly $L$ steps. Let's process $k$ by decreasing from a certain value $k_{0}$, and see if $L$ can be increased by $2^{k}$. The next $2^{k}$ characters after $L$-th position will form the string $A_{k}$ or $B_{k}$ depending on the popcount parity of $L$. Let's denote $S'$ the set of vertices reachable from $S$ following $A_{k} / B_{k}$. If $S'$ is non-empty, we can increase $L$ by $2^{k}$, and assign $S = S'$, otherwise, we don't change anything. In the end, $L$ will be the maximal path length as long as it at less than $2^{k0}$. Note that we can take $k_{0} = 60$ since we don't care about exact value of answer if it is greater than $2^{60}$. This results in an $O(k_{0n}^{3})$ solution, which is too slow. However, optimizing boolean multiplication with bitsets cuts the working time $\\sim64$ times, and the solution is now fast enough. Complexity: $O(k_{0}n^{3}/w)$ time, and $O(k_{0}n^{2})$ memory. Here $k_{0}=\\log_{2}10^{18}$, and $w = 64$ is the word length in bits.",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "780",
    "index": "G",
    "title": "Andryusha and Nervous Barriers",
    "statement": "Andryusha has found a perplexing arcade machine. The machine is a vertically adjusted board divided into square cells. The board has $w$ columns numbered from $1$ to $w$ from left to right, and $h$ rows numbered from $1$ to $h$ from the bottom to the top.\n\nFurther, there are barriers in some of board rows. There are $n$ barriers in total, and $i$-th of them occupied the cells $l_{i}$ through $r_{i}$ of the row $u_{i}$. Andryusha recollects well that no two barriers share the same row. Furthermore, no row is completely occupied with a barrier, that is, at least one cell in each row is free.\n\nThe player can throw a marble to any column of the machine from above. A marble falls downwards until it encounters a barrier, or falls through the bottom of the board. A marble disappears once it encounters a barrier but is replaced by two more marbles immediately to the left and to the right of the same barrier. In a situation when the barrier is at an edge of the board, both marbles appear next to the barrier at the side opposite to the edge. More than one marble can occupy the same place of the board, without obstructing each other's movement. Ultimately, all marbles are bound to fall from the bottom of the machine.\n\n\\begin{center}\n{\\small Examples of marble-barrier interaction.}\n\\end{center}\n\nPeculiarly, sometimes marbles can go through barriers as if they were free cells. That is so because the barriers are in fact alive, and frightened when a marble was coming at them from a very high altitude. More specifically, if a marble falls towards the barrier $i$ from relative height more than $s_{i}$ (that is, it started its fall strictly higher than $u_{i} + s_{i}$), then the barrier evades the marble. If a marble is thrown from the top of the board, it is considered to appear at height $(h + 1)$.\n\nAndryusha remembers to have thrown a marble once in each of the columns. Help him find the total number of marbles that came down at the bottom of the machine. Since the answer may be large, print it modulo $10^{9} + 7$.",
    "tutorial": "Solution 1: Let us move a sweep-line from the bottom to the top, and say that $i$-th barrier is active if the current $y$-coordinate satisfies $u_{i}  \\le  y  \\le  u_{i} + s_{i}$. If we want to find the result of dropping a ball in column $x$ at a certain moment, we have to find the highest active barrier that covers $x$ at the moment. Let us store a segment tree, with a set of active segments in each tree node. When introducing a new active segment, we represent it as a union of $O(\\log w)$ tree nodes, and add this segment in each of these nodes' set; when a segment becomes non-active, we delete these entries. If at any point we are interested in finding the highest active barrier for a column $x$, we consider all $O(\\log w)$ tree nodes covering $x$ and look at their highest entries only. Also, for each segment we store the number of resulting balls after hitting this segment; this number can be found by making two queries to the tree (for the two balls resulting from the collision) at the same time we activate the barrier. To find the final answer, for each column drop a ball in it from height $h + 1$ and sum the results. Thus, the answer can be found in $O((n+w)\\log^{2}w)$ time (with the second logarithm for std::set working time). Solution 2: Let us go from the top to the bottom instead, and maintain positions of all balls to be dropped. If any of these balls occupy the same position, we group them together and store the size of the group. Each column will have a separate stack of groups, with lower groups on top of the stack. Let's see how a new barrier $[l, r]$ changes our configuration. For each column $[l, r]$ we want to drop several lowest groups on the barrier, which will result in creating at most two new groups next to the barrier. Let us store a segment tree of size $w$, with $x$-th entry equal to the height of the lowest group in column $x$. While $[l, r]$ range minimum in the segment tree is low enough, we pop the lowest group from the corresponding stack (and update the segment tree accordingly). Finally, we create the new groups, and push them to their respective stacks. After processing all barriers, the rest groups will fall straight to the bottom. A standard amortized estimate shows that $O(n + w)$ operations will be performed, for $O((n+w)\\log w)$ time complexity.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "780",
    "index": "H",
    "title": "Intranet of Buses",
    "statement": "A new bus route is opened in the city $\\mathbb{N}$. The route is a closed polygon line in the place, with all segments parallel to one of the axes. $m$ buses will operate on the route. All buses move in a loop along the route in the same direction with equal constant velocities (stopping times are negligible in this problem).\n\nBuses start their movement in the first vertex of the route with equal interval. Suppose that $T$ is the total time for a single bus to travel the whole loop of the route. Then, the bus 1 starts moving at time 0, the bus 2 starts at time $T / m$, the bus 3 starts at time $2T / m$, and so on; finally, the bus $m$ starts moving at time $(m - 1)T / m$. Thus, all intervals between pairs of consecutive buses (including the interval between the last and the first bus) are equal.\n\nBuses can communicate with each other via wireless transmitters of equal power. If the transmitters have power $D$, then only buses within distance $D$ of each other can communicate.\n\nThe buses are also equipped with a distributed system of schedule tracking. For all buses to stick to the schedule, the system has to synchronize the necessary data between all buses from time to time. At the moment of synchronization, the bus 1 communicates with the bus 2, the bus 2 — with bus 3, and so on; also, the bus $m$ communicates with the bus 1.\n\nAs a research employee, you are tasked with finding the smallest value of $D$ such that it is possible to find a time moment to perform synchronization once all buses have started moving.",
    "tutorial": "Let us do a binary search on the answer. Inside it, we have to check if at any time moment bus pairs 1 and 2, 2 and 3, ..., $n$ and 1 are within distance $x$ of each other simultaneously. Let $p(t)$ be the location of the bus 1 (that departed at time 0) at time $t$. Let us call a time moment $t$ good, if we have $||p(t + T / m) - p(t)||  \\le  x$, with $||a - b||$ equal to the distance between points $a$ and $b$. If there is a moment $t$ such that $t$, $t + T / m$, ..., $t + (m - 1)T / m$ are all good, then the answer is at least $x$. We can build the two-dimensional graph (as in \"function graph\", not \"graph with vertices and edges\") of $p(t + T / m) - p(t)$ over time by keeping track of segments where points $p(t)$ and $p(t + T / m)$ are. When the points are bounded to a pair of sides, the vector $p(t + T / m) - p(t)$ changes linearly in time. There are $O(n)$ time moments when either point switches from side to side, hence the difference graph can be constructed in $O(n)$ time with the two pointers approach. Now, for a certain $x$ let's find the set of good moments $t$. We will do this separately for each segment of the difference graph, and then paste the answers. We have the condition $||q||  \\le  x$, where $q$ ranges over a segment. This is the segment-circle intersection problem, which is a standard geometrical primitive, with various approaches from solving quadratic equations to rotating a certain vector by an angle. In any case, the result will be a time range or an empty set. Note that $q$ may stay still for a certain time range of the graph, which should be treated separately. To ensure that $p(t)$, $p(t + T / m)$, and so on are all good for certain $t$, let us \"cut\" the segment $[0, T]$ into $m$ equal parts and superimpose them, with \"good\" segments possibly being cut into parts, now overlapping each other. A suitable moment $t$ is now a point that is covered $m$ times. Finding such point is a simple scan-line application. Complexity: $O(n\\log\\varepsilon^{-1})$, where $ \\epsilon $ is the required relative precision.",
    "tags": [
      "binary search",
      "geometry",
      "implementation",
      "two pointers"
    ],
    "rating": 3100
  },
  {
    "contest_id": "785",
    "index": "A",
    "title": "Anton and Polyhedrons",
    "statement": "Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:\n\n- Tetrahedron. Tetrahedron has $4$ triangular faces.\n- Cube. Cube has $6$ square faces.\n- Octahedron. Octahedron has $8$ triangular faces.\n- Dodecahedron. Dodecahedron has $12$ pentagonal faces.\n- Icosahedron. Icosahedron has $20$ triangular faces.\n\nAll five kinds of polyhedrons are shown on the picture below:\n\nAnton has a collection of $n$ polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!",
    "tutorial": "I think there's nothing to explain in this problem. Just check the polyhedron type, determine its number of faces and sum these numbers. Time complexity is $O(n)$.",
    "code": "vals = {\n\t'Tetrahedron': 4,\n\t'Cube': 6,\n\t'Octahedron': 8,\n\t'Dodecahedron': 12,\n\t'Icosahedron': 20\n}\n\nn = int(input())\nans = 0\nfor i in range(0, n):\n\tans += vals[input()]\nprint(ans)",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "785",
    "index": "B",
    "title": "Anton and Classes",
    "statement": "Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.\n\nAnton has $n$ variants when he will attend chess classes, $i$-th variant is given by a period of time $(l_{1, i}, r_{1, i})$. Also he has $m$ variants when he will attend programming classes, $i$-th variant is given by a period of time $(l_{2, i}, r_{2, i})$.\n\nAnton needs to choose \\textbf{exactly one} of $n$ possible periods of time when he will attend chess classes and \\textbf{exactly one} of $m$ possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.\n\nThe distance between periods $(l_{1}, r_{1})$ and $(l_{2}, r_{2})$ is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible $|i - j|$, where $l_{1} ≤ i ≤ r_{1}$ and $l_{2} ≤ j ≤ r_{2}$. In particular, when the periods intersect, the distance between them is $0$.\n\nAnton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!",
    "tutorial": "At first, let's determine what classes Anton will attend first - chess classes or programming classes. Consider the case when Anton attends chess classes first and then attends programming classes. It's not hard to observe that in this case it's better to take the chess classes variant in which the right range is as more to the left as possible. Also, we take the programming classes variant in which the left range is as more to the right as possible. Because chess classes must be earlier than programming classes, the distance between them can be calculated as the distance between these two points (the right range of chess classes and the left range of programming classes). But if the right chess classes point will be later than the left programming classes point, it means that our condition (chess is earlier than programming) is false or the periods intersect. So in this case we take $0$ instead of the distance. The second case is considered in the same way. It's obvious that the answer will be the maximum of these two cases. Time complexity is $O(n+m)$.",
    "code": "infinity = 1234567890\nminR1 = minR2 = infinity\nmaxL1 = maxL2 = -infinity\nn = int(input())\nfor i in range(0, n):\n\t(l, r) = map(int, input().split())\n\tmaxL1 = max(maxL1, l)\n\tminR1 = min(minR1, r)\nm = int(input())\nfor i in range(0, m):\n\t(l, r) = map(int, input().split())\n\tmaxL2 = max(maxL2, l)\n\tminR2 = min(minR2, r)\nres = max(maxL2 - minR1, maxL1 - minR2);\nprint(max(res, 0))",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "785",
    "index": "C",
    "title": "Anton and Fairy Tale",
    "statement": "Anton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale:\n\n\"Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that barn for three days and three nights. But they overlooked and there remained a little hole in the barn, from which every day sparrows came through. Here flew a sparrow, took a grain and flew away...\"\n\nMore formally, the following takes place in the fairy tale. At the beginning of the first day the barn with the capacity of $n$ grains was full. Then, every day (starting with the first day) the following happens:\n\n- $m$ grains are brought to the barn. If $m$ grains doesn't fit to the barn, the barn becomes full and the grains that doesn't fit are brought back (in this problem we can assume that the grains that doesn't fit to the barn are not taken into account).\n- Sparrows come and eat grain. In the $i$-th day $i$ sparrows come, that is on the first day one sparrow come, on the second day two sparrows come and so on. Every sparrow eats one grain. If the barn is empty, a sparrow eats nothing.\n\nAnton is tired of listening how Danik describes every sparrow that eats grain from the barn. Anton doesn't know when the fairy tale ends, so he asked you to determine, by the end of which day the barn will become empty for the first time. Help Anton and write a program that will determine the number of that day!",
    "tutorial": "At first, let's make the following assumption: if a sparrow cannot eat a grain because the barn is empty, the number of grains in the barn becomes negative. It's easy to see that the answer doesn't change because of this. Now, let's observe the number of grains before sparrows come. At first, the barn remains full for $m + 1$ days (because sparrows eat less grains than it's added to the barn). Then the number of grains is decreased by one, by two and so on. So, on the $m + 1 + i$-th day there are $n-{\\frac{\\iota_{-}\\iota_{+1}}{2}}$ grains in the barn before sparrows come (remember that for any positive integer $x$ the equality $1+2+3+\\cdot\\cdot\\cdot+x={\\frac{x\\cdot(x+1)}{2}}$ is always true). How can we determine if the barn is empty? It's reasonable that if there are $q$ grains on the $k$-th day after grain is brought, then at the end of the $k - 1$-th day there are $q - m$ grains in the barn. So, if on the $k - 1$-th day the barn becomes empty ($q - m  \\le  0$), then there must be $q  \\le  m$ grains on the $k$-th day after grain is brought. So, we must find such minimal day $m + 1 + k$, in which there are $m$ or less grains after grain is brought. That is, using the formula above, we must find such minimal $k$ that $n-{\\frac{k\\cdot(k{+}1)}{2}}\\leq m$ It can be easily done using binary search. It's not hard to observe that the answer in this case is $m + k$ (if in the $m + 1 + k$-th day before sparrows come there are less or equal than $m$ grains, then in the $m + 1 + k - 1 = m + k$-th day the barn is empty). The corner case in this problem is $m  \\ge  n$. In this case the barn becomes full every day and it becomes empty only in the $n$-th day when sparrows eat all the grain. Also notice that $k$ can be found using a formula, but such solutions could fail by accuracy, because the formula is using the square root function. Time complexity is $O(\\log n)$.",
    "code": "(n, m) = map(int, input().split())\nif n <= m:\n\tprint(n)\nelse:\n\taM = m\n\tn -= m\n\t(l, r) = (0, int(2e9))\n\twhile l < r:\n\t\tm = (l + r) // 2;\n\t\tval = m * (m+1) // 2;\n\t\tif val >= n:\n\t\t\tr = m\n\t\telse:\n\t\t\tl = m+1\n\tprint(l + aM)",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "785",
    "index": "D",
    "title": "Anton and School - 2",
    "statement": "As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters \"(\" and \")\" (without quotes)).\n\nOn the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence $s$ of length $n$ is an RSBS if the following conditions are met:\n\n- It is not empty (that is $n ≠ 0$).\n- The length of the sequence is even.\n- First $\\frac{n t}{2}$ charactes of the sequence are equal to \"(\".\n- Last $\\frac{n t}{2}$ charactes of the sequence are equal to \")\".\n\nFor example, the sequence \"((()))\" is an RSBS but the sequences \"((())\" and \"(()())\" are not RSBS.\n\nElena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence $s$. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of $s$ is a string that can be obtained from $s$ by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.\n\nBecause the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo $10^{9} + 7$.\n\nAnton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!",
    "tutorial": "At first, let's simplify the problem: let our string consists of $x + y$ characters, begins with $x$ characters \"(\" and ends with $y$ characters \")\". How to find the number of RSBS in such string? Let's prove that this number is equal to $\\textstyle(x+y)={\\frac{(x+y)!}{x!.y!}}$. It's easy to observe that this formula also means the number of ways to match the string with the sequence of zeros and ones of the same length, which contains exactly $x$ ones. Now prove that for every such sequence of zeros and ones we can find an RSBS subsequence. How can we do it? Let's consider it on the example of the following string: Let's include to our subsequence all the opening brackets that match zeros and all the closing brackets that match ones. In our example, we include brackets number $1$, $3$, $5$ and $6$, so we get the subsequence \"(())\", which is an RSBS. Why every sequence we got in this way is an RSBS? Let the number of ones that match closing brackets is equal to $z$. So $x - z$ ones match opening brackets (because we have $x$ ones, as we remember) and, therefore, $z$ zeros match opening brackets. So the number of opening brackets is equal to the number of closing brackets in our subsequence. Also opening brackets appear earlier than closing brackers. So such subsequence is always an RSBS, and the statement above is proved. Now we must understand how to solve the entire problem. Let's iterate over an opening bracket that is the last opening bracket in our subsequence. Now observe that only opening brackets may come before this bracket, and only closing brackets may come after this bracket. The rest of the brackets will definitely not appear in the subsequence. Let's count the number of opening brackets before the iterated one, incluing the iterated one (let this number is equal to $x$), and also the number of closing brackets after the iterated one (let this number is equal to $y$). To calculate these numbers, we can precalc them for all the positions in $O(n)$ using prefix sums. Now, we have reduced our problem to the already solved, because we have $x$ opening brackets and then $y$ closing brackets. But we also have an additional condition: we must necessarily take the last opening bracket. So the answer is equal to $\\textstyle(x+y-1)$, not $\\textstyle{\\left(x+y\\right)}$, because on the position with the last opening bracket we must put a zero. So we must put $x$ ones on $x + y - 1$ positions instead of $x + y$ positions. Time complexity is $O(n\\cdot\\log(10^{9}+7))$ (logarithm is to divide by modulo, that is necessary to calculate the number of combinations).",
    "code": "import java.io.*;\nimport java.util.*;\n\npublic class BracketsJava {\n\tpublic static int mod = (int)1e9 + 7;\n\t\n\tpublic static class ExtGcdResult {\n\t\tlong x;\n\t\tlong y;\n\t}\n\t\n\tpublic static long extGcd(long a, long b, ExtGcdResult res) { \n\t\tif (a == 0) {\n\t\t\tres.x = 0L;\n\t\t\tres.y = 1L;\n\t\t\treturn b;\n\t\t}\n\t\tExtGcdResult newRes = new ExtGcdResult();\n\t\tlong d = extGcd(b % a, a, newRes); \n\t\tres.x = newRes.y - (b / a) * newRes.x;\n\t\tres.y = newRes.x;\n\t\treturn d; \n\t}\n\t\n\tpublic static final int addMod(int a, int b) { \n\t\treturn (int)(((long)a + b) % mod); \n\t}\n\n\tpublic static final int mulMod(int a, int b) { \n\t\treturn (int)(((long)a * b) % mod); \n\t}\n\t\n\tpublic static final int divMod(int a, int b) { \n\t\tExtGcdResult res = new ExtGcdResult();\n\t\tlong g = extGcd(b, mod, res); \n\t\tif (g != 1) {\n\t\t\tSystem.out.println(\"Bad gcd!\");\n\t\t\tfor (;;);\n\t\t}\n\t\tint q = (int)((res.x % mod + mod) % mod); \n\t\treturn mulMod(a, q); \n\t}\n\t\n\tpublic static final int[] precalcFactorials() {\n\t\tint[] fact = new int[factRange];\n\t\tfact[0] = 1;\n\t\tfor (int i = 1; i < factRange; i++) {\n\t\t\tfact[i] = mulMod(fact[i-1], i);\n\t\t}\n\t\treturn fact;\n\t}\n\n\tpublic static final int factRange = 1000000;\n\tpublic static final int[] fact = precalcFactorials();\n\t\n\tpublic static final int F(int n) {\n\t\treturn (n < 0) ? 0 : fact[n];\n\t}\n\t\n\tpublic static final int C(int k, int n) {\n\t\tint res = divMod(F(n), mulMod(F(n-k), F(k)));\n\t\treturn divMod(F(n), mulMod(F(n-k), F(k)));\n\t} \n\t\n\tpublic static void main(String[] args) throws Exception {\n\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(System.in));\n\t\tBufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));\n\t\tString s = reader.readLine();\n\t\tint len = s.length();\n\t\tint[] opnLeft = new int[len], clsRight = new int[len];\n\t\topnLeft[0] = (s.charAt(0) == '(') ? 1 : 0;\n\t\tfor (int i = 1; i < len; i++) {\n\t\t\topnLeft[i] = opnLeft[i-1] + ((s.charAt(i) == '(') ? 1 : 0);\n\t\t}\n\t\tclsRight[len-1] = (s.charAt(len-1) == ')') ? 1 : 0;\n\t\tfor (int i = len-2; i >= 0; i--) {\n\t\t\tclsRight[i] = clsRight[i+1] + ((s.charAt(i) == ')') ? 1 : 0);\n\t\t}\n\t\tint res = 0;\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tif (s.charAt(i) != '(' || clsRight[i] == 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint add = C(opnLeft[i], opnLeft[i] + clsRight[i] - 1);\n\t\t\tres = addMod(res, add);\n\t\t}\t\t\n\t\twriter.write(Integer.toString(res));\n\t\treader.close();\n\t\twriter.close();\t\t\n\t}\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "785",
    "index": "E",
    "title": "Anton and Permutation",
    "statement": "Anton likes permutations, especially he likes to permute their elements. Note that a permutation of $n$ elements is a sequence of numbers ${a_{1}, a_{2}, ..., a_{n}}$, in which every number from $1$ to $n$ appears exactly once.\n\nOne day Anton got a new permutation and started to play with it. He does the following operation $q$ times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs $(i, j)$ such that $1 ≤ i < j ≤ n$ and $a_{i} > a_{j}$.\n\nVanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.\n\nInitially Anton's permutation was ${1, 2, ..., n}$, that is $a_{i} = i$ for all $i$ such that $1 ≤ i ≤ n$.",
    "tutorial": "At first observe that there is $0$ inversions in the initial permutation. Let's divide our queries in ${\\sqrt{q}}$ blocks. Now learn how to answer all the queries in one block in $O(n+q+\\sqrt{n q})$. At first, let's divide our positions in the permutation in fixed and mobile positions. Mobile positions are all the positions that are changed in the current block. Fixed positions are the rest of the positions. Observe that the number of mobile positions is not more than $2\\cdot{\\sqrt{q}}$. Now all the inversions are divided into three types: Inversions only between fixed positions; Inversions only between mobile positions; Inversions between fixed and mobile positions. To keep inversions of the first type is the easiest of all: their number doesn't change. So we can precalcualte them in the beginning of the block. How can we do it? Let's remember the answer for the query that was directly before the beginning of the block (if the block starts with the first query, this number is equal to $0$). This number is equal to the total number of inversions in the beginning of the block. To get the number of fixed inversions, we can just subtract from this number the number of inversions of the second and the third types. It's also easy to calculate the number of inversions of the second type. In the beginning their number can be counted even using a naive algorithm in $O(\\sqrt{q}^{2})=O(q)$. How to keep this number? We can recalculate each time not all the inversions but only these ones that contain changed elements. Totally we can count them in $O(\\sqrt{q}\\cdot\\sqrt{q})=O(q)$ for a block. It's a little bit harder to keep inversions of the third type. To count them we'll use the similar approach as with inversions of the second type. We'll also recount the number of inversions only for changed elements. So, we must learn how to count the number of inversions between fixed elements and some mobile element on the position $x$. What fixed elements make an inversion with it? It's obvious that these are the elements which are earlier than the $x$-th and wherein bigger than it (denote this query $countLower(x, p_{x})$) or elements which are later than the $x$-th and wherein smaller than it (denote this query $countUpper(x, p_{x})$). Here $p_{x}$ denotes the $x$-th element of permutation. Observe that there are $O({\\sqrt{q}})$ such queries. How can we calculate the answers for these queries quickly? At first note that we can count them offline, because fixed elements doesn't change and mobile elements are not counted in these queries. Consider how we can count answers for $countLower(x, y)$ (for $countUpper(x, y)$ we can use the same approach). Let's sort all the $countLower$ queries by non-decreasing $x$. Now if we have some structure that can add a value to an element and count a sum on a segment, we can easily do it. Let we added the fixed elements that stay earlier than $x$ (it can be easily done because all the queries are sorted by non-decreasing $x$). So the answer is the sum on the segment $(y + 1, n)$. What data structure can we use? We can use sqrt-decomposition, because it takes $O(1)$ for adding and $O({\\sqrt{n}})$ for sum query. Totally all the $O({\\sqrt{q}})$ $countLower$ and $countUpper$ queries in a block are processed in $O(n+{\\sqrt{n q}})$. Time complexity is $O(\\sqrt{q}\\cdot(n+q+\\sqrt{n q}))=O(n\\sqrt{q}+q\\sqrt{q}+q\\sqrt{n})$. There also exists an $O((n+q)\\cdot\\log^{2}n)$ solution. You can find it by yourself as an exercise. Such solution should be written carefully, otherwise it doesn't fit to the time limit or memory limit.",
    "code": "import java.io.*;\nimport java.util.*;\n\npublic class NsqrtNlogNnetman implements Runnable {\n    static class InputReader {\n        BufferedReader reader;\n        StringTokenizer tokenizer;\n        InputReader(InputStream in) {\n            reader = new BufferedReader(new InputStreamReader(in), 32768);\n            tokenizer = null;\n        }\n        String next() {\n            while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n                try {\n                    tokenizer = new StringTokenizer(reader.readLine());\n                } catch (IOException e) {\n                    e.printStackTrace();\n                    throw new RuntimeException(e);\n                }\n            }\n            return tokenizer.nextToken();\n        }\n        int nextInt() {\n            return Integer.parseInt(next());\n        }\n        long nextLong() {\n            return Long.parseLong(next());\n        }\n        double nextDouble() {\n            return Double.parseDouble(next());\n        }\n    }\n\n    static class Fenwick {\n        int[] ft;\n        Fenwick(int n) {\n            ft = new int[n];\n        }\n        void add(int r, int val) {\n            while (r < ft.length) {\n                ft[r] += val;\n                r |= r + 1;\n            }\n        }\n        int sum(int r) {\n            int res = 0;\n            while (r >= 0) {\n                res += ft[r];\n                r = (r & (r + 1)) - 1;\n            }\n            return res;\n        }\n        void clear() {\n            Arrays.fill(ft, 0);\n        }\n    }\n\n    static class Query {\n        int x, bound, sign, id;\n        Query(int x, int bound, int sign, int id) {\n            this.x = x;\n            this.bound = bound;\n            this.sign = sign;\n            this.id = id;\n        }\n    }\n\n    static void getOnPrefSmaller(List<Query> qrs, int r, int y, int id, int sign) {\n        qrs.add(new Query(r, y, sign, id));\n    }\n\n    static void getOnPrefBetween(List<Query> qrs, int r, int x, int y, int id, int sign) {\n        getOnPrefSmaller(qrs, r, y, id, sign);\n        getOnPrefSmaller(qrs, r, x, id, -sign);\n    }\n\n    static void getOnSegmentBetween(List<Query> qrs, int l, int r, int x, int y, int id, int sign) {\n        if (x > y) return;\n        getOnPrefBetween(qrs, r, x, y, id, sign);\n        getOnPrefBetween(qrs, l, x, y, id, -sign);\n    }\n\n    @Override\n    public void run() {\n\n        InputReader in = new InputReader(System.in);\n        PrintWriter out = new PrintWriter(System.out);\n\n        int n = in.nextInt();\n        int q = in.nextInt();\n\n        int[] l = new int[q];\n        int[] r = new int[q];\n\n        for (int i = 0; i < q; i++) {\n            l[i] = in.nextInt() - 1;\n            r[i] = in.nextInt() - 1;\n        }\n\n        int[] perm = new int[n];\n\n        for (int i = 0; i < n; i++) {\n            perm[i] = n - i - 1;\n        }\n\n        final int BLOCK = 300;\n\n        long inv = 0L;\n\n        boolean[] isInteresting = new boolean[n];\n\n        long[] add = new long[q];\n\n        Fenwick f = new Fenwick(n);\n\n        for (int i = 0; i < q; i += BLOCK) {\n            int from = i, to = Math.min(i + BLOCK, q) - 1;\n            List<Integer> lst = new ArrayList<>();\n            for (int j = from; j <= to; j++) {\n                lst.add(l[j]);\n                lst.add(r[j]);\n            }\n            lst.sort(Integer::compareTo);\n            lst = new ArrayList<>(new HashSet<>(lst));\n            int[] interestingPositions = lst.stream().mapToInt(x -> x).toArray();\n            for (int pos : interestingPositions) {\n                isInteresting[pos] = true;\n            }\n            List<Query> qrs = new ArrayList<>();\n            for (int j = from; j <= to; j++) {\n                if (l[j] == r[j]) continue;\n                if (l[j] > r[j]) {\n                    int tmp = l[j];\n                    l[j] = r[j];\n                    r[j] = tmp;\n                }\n                if (perm[l[j]] < perm[r[j]]) {\n                    getOnSegmentBetween(qrs, l[j], r[j], perm[l[j]], perm[r[j]], j,-1);\n                    int leftValue = perm[l[j]];\n                    int rightValue = perm[r[j]];\n                    for (int pos : interestingPositions) {\n                        if (pos > l[j] && pos < r[j] && perm[pos] > leftValue && perm[pos] < rightValue) {\n                            add[j] -= 2;\n                        }\n                    }\n                    add[j]--;\n                } else {\n                    getOnSegmentBetween(qrs, l[j], r[j], perm[r[j]], perm[l[j]], j,1);\n                    int leftValue = perm[l[j]];\n                    int rightValue = perm[r[j]];\n                    for (int pos : interestingPositions) {\n                        if (pos > l[j] && pos < r[j] && perm[pos] > rightValue && perm[pos] < leftValue) {\n                            add[j] += 2;\n                        }\n                    }\n                    add[j]++;\n                }\n                int tmp = perm[l[j]];\n                perm[l[j]] = perm[r[j]];\n                perm[r[j]] = tmp;\n            }\n            qrs.sort(Comparator.comparingInt(a -> -a.x));\n\n            f.clear();\n            for (int pos = 0; pos < n; pos++) {\n                if (!isInteresting[pos]) {\n                    f.add(perm[pos], 1);\n                }\n                while (!qrs.isEmpty() && qrs.get(qrs.size() - 1).x == pos) {\n                    Query t = qrs.get(qrs.size() - 1);\n                    qrs.remove(qrs.size() - 1);\n                    add[t.id] += 2 * t.sign * f.sum(t.bound);\n                }\n            }\n            for (int j = from; j <= to; j++) {\n                inv += add[j];\n                out.println(inv);\n            }\n            for (int pos : interestingPositions) {\n                isInteresting[pos] = false;\n            }\n        }\n\n\n\n        out.close();\n    }\n\n    public static void main(String[] args) {\n        new Thread(null, new NsqrtNlogNnetman(), \"1\", 1L << 28).run();\n    }\n}",
    "tags": [
      "brute force",
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "786",
    "index": "A",
    "title": "Berzerk",
    "statement": "Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.\n\nIn this game there are $n$ objects numbered from $1$ to $n$ arranged in a circle (in clockwise order). Object number $1$ is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario.\n\nEach one of them has a set of numbers between $1$ and $n - 1$ (inclusive). Rick's set is $s_{1}$ with $k_{1}$ elements and Morty's is $s_{2}$ with $k_{2}$ elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like $x$ from his set and the monster will move to his $x$-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.\n\nYour task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.",
    "tutorial": "For each state of monster ($2n$ possible states, the position and whose turn it is) we will determine if it will be won, lost, or stuck in loop (the player whose turn it is, will win, lose, or the game will never end if this state happens). For this purpose, first each state with monster on $1$ is lost. Then if we consider a graph that its vertices are our $2n$ states, we will recursively determine the answer for each vertex. If a state has an edge to a lost state, it's won, and if all its edges are to won states, it's lost. The vertices that are neither lost or won at the end have answer \"loop\". You can implement this using a simple memoize. Time complexity: $O(n^{2})\\,$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 7000 + 10;\nint n;\nint mod(int x){\n\twhile(x >= n)\tx -= n;\n\treturn x;\n}\nvi v[2];\nint dp[maxn][2], deg[maxn][2]; // 1 for WIN and 2 for LOSE\nvoid go(int i, int j){\n\tint op = !j;\n\trep(x, v[op]){\n\t\tint p = mod(i + n - x);\n\t\tif(dp[p][op])\tcontinue ;\n\t\tif(dp[i][j] == 1){\n\t\t\t-- deg[p][op];\n\t\t\tif(!deg[p][op]){\n\t\t\t\tdp[p][op] = 2;\n\t\t\t\tgo(p, op);\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tdp[p][op] = 1;\n\t\t\tgo(p, op);\n\t\t}\n\t}\n}\nint main(){\n\tiOS;\n\tcin >> n;\n\tFor(i,0,2){\n\t\tint k;\n\t\tcin >> k;\n\t\twhile(k--){\n\t\t\tint a;\n\t\t\tcin >> a;\n\t\t\tv[i].pb(a);\n\t\t}\n\t}\n\tFor(i,0,n)\n\t\tFor(j,0,2)\tdeg[i][j] = (int)v[j].size();\n\tdp[0][0] = dp[0][1] = 2;\n\tgo(0, 0);\n\tgo(0, 1);\n\tFor(j,0,2)\n\t\tFor(i,1,n)\n\t\t\tcout << (dp[i][j]? dp[i][j] == 1? \"Win\": \"Lose\": \"Loop\") << \" \n\"[i + 1 == n];\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "games"
    ],
    "rating": 2000
  },
  {
    "contest_id": "786",
    "index": "B",
    "title": "Legacy",
    "statement": "Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them.\n\nThere are $n$ planets in their universe numbered from $1$ to $n$. Rick is in planet number $s$ (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial.\n\nBy default he can not open any portal by this gun. There are $q$ plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more.\n\nPlans on the website have three types:\n\n- With a plan of this type you can open a portal from planet $v$ to planet $u$.\n- With a plan of this type you can open a portal from planet $v$ to any planet with index in range $[l, r]$.\n- With a plan of this type you can open a portal from any planet with index in range $[l, r]$ to planet $v$.\n\nRick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet.",
    "tutorial": "Consider a weighted directed graph (initially it has $n$ vertices and no edges). We will construct a segment tree to handle queries of second type (and one for the third type but with similar approach). Build a segment tree on number $1, ..., n$. For each node of segment tree consider a vertex in the graph. For each leaf in this tree (like one with interval $[l, l + 1)$), add an edge with weight equal to $0$ from vertex corresponding to this node to vertex $l$ in the original graph. And for each non-leaf node, add an edge with weight equal to $0$ from vertex corresponding to this node to the vertex corresponding to node of each of its children. So we're adding about $4n$ vertices and edges to the graph. For each query of second type, we will add an edge from $v$ to each maximal node of segment tree that $[l, r)$ contains ($lg(n)$ nodes for each query) with weight equal to $w$. And construct a segment tree in the same way for queries of third type. Finally run Dijkstra's algorithm on this graph. Time complexity: $O(n l g^{2}(n))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef pair<ll, int> pli;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e5 + 100;\nconst ll inf = 1LL << 60;\nint ver[2][4 * maxn];\t// 0: to [l, r], 1: from [l, r]\nvector<pii> adj[9 * maxn];\nll dis[9 * maxn];\nbool mark[9 * maxn];\nint n, q, s, nx;\npriority_queue <pli, vector<pli>, greater<pli>> pq; \nvoid build(int t, int id = 1, int l = 0, int r = n){\n\tver[t][id] = nx ++;\n\tif(r - l < 2){\n\t\tif(!t)\n\t\t\tadj[ver[t][id]].pb({l, 0});\n\t\telse\n\t\t\tadj[l].pb({ver[t][id], 0});\n\t\treturn ;\n\t}\n\tint mid = (l + r) >> 1;\n\tbuild(t, L(id), l, mid);\n\tbuild(t, R(id), mid, r);\n\tif(!t)\n\t\tadj[ver[t][id]].pb({ver[t][L(id)], 0}),\n\t\tadj[ver[t][id]].pb({ver[t][R(id)], 0});\n\telse\n\t\tadj[ver[t][L(id)]].pb({ver[t][id], 0}),\n\t\tadj[ver[t][R(id)]].pb({ver[t][id], 0});\n}\nvoid add(int v, int w, int x, int y, int t, int id = 1, int l = 0, int r = n){\n\tif(x >= r or l >= y)\treturn ;\n\tif(x <= l && r <= y){\n\t\tif(!t)\n\t\t\tadj[v].pb({ver[t][id], w});\n\t\telse\n\t\t\tadj[ver[t][id]].pb({v, w});\n\t\treturn ;\n\t}\n\tint mid = (l + r) >> 1;\n\tadd(v, w, x, y, t, L(id), l, mid);\n\tadd(v, w, x, y, t, R(id), mid, r);\n}\nint main(){\n\tscanf(\"%d %d %d\", &n, &q, &s);\n\t-- s;\n\tnx = n;\n\tbuild(0), build(1);\n\twhile(q--){\n\t\tint type;\n\t\tscanf(\"%d\", &type);\n\t\tif(type == 1){\n\t\t\tint v, u, w;\n\t\t\tscanf(\"%d %d %d\", &v, &u, &w);\n\t\t\t-- v, -- u;\n\t\t\tadj[v].pb({u, w});\n\t\t}\n\t\telse{\n\t\t\tint v, l, r, w;\n\t\t\tscanf(\"%d %d %d %d\", &v, &l, &r, &w);\n\t\t\t-- v, -- l;\n\t\t\tadd(v, w, l, r, type-2);\n\t\t}\n\t}\n\tfill(dis, dis + 9 * maxn, inf);\n\tdis[s] = 0;\n\tpq.push({0LL, s});\n\twhile(!pq.empty()){\n\t\tint v = pq.top().y;\n\t\tpq.pop();\n\t\tif(mark[v])\tcontinue ;\n\t\tmark[v] = true;\n\t\trep(p, adj[v]){\n\t\t\tint u = p.x, w = p.y;\n\t\t\tif(dis[u] > dis[v] + w){\n\t\t\t\tdis[u] = dis[v] + w;\n\t\t\t\tpq.push({dis[u], u});\n\t\t\t}\n\t\t}\n\t}\n\tFor(i,0,n)\n\t\tprintf(\"%lld \", (dis[i] == inf? -1: dis[i]));\n\tputs(\"\");\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "graphs",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "786",
    "index": "C",
    "title": "Till I Collapse",
    "statement": "Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated $n$ Mr. Meeseeks, standing in a line numbered from $1$ to $n$. Each of them has his own color. $i$-th Mr. Meeseeks' color is $a_{i}$.\n\nRick and Morty are gathering their army and they want to divide Mr. Meeseeks into some squads. They don't want their squads to be too colorful, so each squad should have Mr. Meeseeks of at most $k$ different colors. Also each squad should be a continuous subarray of Mr. Meeseeks in the line. Meaning that for each $1 ≤ i ≤ e ≤ j ≤ n$, if Mr. Meeseeks number $i$ and Mr. Meeseeks number $j$ are in the same squad then Mr. Meeseeks number $e$ should be in that same squad.\n\nAlso, each squad needs its own presidio, and building a presidio needs money, so they want the total number of squads to be minimized.\n\nRick and Morty haven't finalized the exact value of $k$, so in order to choose it, for each $k$ between $1$ and $n$ (inclusive) need to know the minimum number of presidios needed.",
    "tutorial": "Your task is to find the minimum number of parts needed to partition this such that each part contains no more than $k$ different numbers. For a fixed $k$, we can greedily find the answer. First, fix a maximal partition with at most $k$ different numbers in it, then a maximal after that and so on. If answer for $k$ is $ans(k)$, we can find this number in $O(a n s(k)l g(n))$. The only thing we want is to find maximum $r$ for a fixed $l$ so that $[l, r]$ has at most $k$ distinct numbers. This can be done with binary search + segment tree, but it's too slow. We can do this using a persistent segment tree in $O(l g(n))$: for a fixed $l$, we define $f_{l}(i)$ to be $1$ if $l  \\le  i$ and there's no such $j$ that $l  \\le  j < i$ and $a_{i} = a_{j}$ otherwise $0$. So, if we have a segment tree on every $f_{l}$, we can use this segment tree to find the first $r$ for an arbitrary $k$ (it's like finding $k - th$ one in this array). So we find the answer in $O(a n s(k)l g(n))$, so the total complexity is $O(\\sum_{k=1}^{n}a n s(k)l g(n))$, and because $a n s(k)\\leq{\\frac{n}{k}}$, $\\sum_{k=1}^{n}a n s(k)=O(n l g(n))$, so: Total time complexity: $O(n l g^{2}(n))$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n//#define L(x) ((x)<<1)\n//#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e5 + 100, maxl = 40;\nint a[maxn], nx[maxn], pr[maxn], nxt = 1, root[maxn], n;\nvi v[maxn];\nint s[maxn * maxl], L[maxn * maxl], R[maxn * maxl];\ninline void build(int id = 0, int l = 0, int r = n){\n\tif(r - l < 2){\n\t\ts[id] = pr[l] == -1;\n\t\treturn ;\n\t}\n\tL[id] = nxt ++;\n\tR[id] = nxt ++;\n\tint mid = (l + r) >> 1;\n\tbuild(L[id], l, mid);\n\tbuild(R[id], mid, r);\n\ts[id] = s[L[id]] + s[R[id]];\n}\ninline int upd(int p, int val, int id, int l = 0, int r = n){\n\tint ID = nxt ++;\n\ts[ID] = s[id] + val;\n\tL[ID] = L[id];\n\tR[ID] = R[id];\n\tif(r - l < 2)\treturn ID;\n\tint mid = (l + r) >> 1;\n\tif(p < mid)\n\t\tL[ID] = upd(p, val, L[id], l, mid);\n\telse\n\t\tR[ID] = upd(p, val, R[id], mid, r);\n\treturn ID;\n}\ninline int kth(int k, int id, int l = 0, int r = n){\n\tif(s[id] < k)\treturn n;\n\tif(r - l < 2)\treturn l;\n\tint mid = (l + r) >> 1;\n\tif(s[L[id]] >= k)\n\t\treturn kth(k, L[id], l, mid);\n\telse\n\t\treturn kth(k - s[L[id]], R[id], mid, r);\n}\nint main(){\n\tmemset(nx, -1, sizeof nx);\n\tmemset(pr, -1, sizeof pr);\n\tscanf(\"%d\", &n);\n\tFor(i,0,n){\n\t\tscanf(\"%d\", a+i);\n\t\t-- a[i];\n\t\tv[a[i]].pb(i);\n\t}\n\tFor(i,0,n)\n\t\tFor(j,1,(int)v[i].size())\n\t\t\tnx[v[i][j-1]] = v[i][j],\n\t\t\tpr[v[i][j]] = v[i][j-1];\n\tbuild();\n\troot[0] = 0;\n\tFor(i,1,n){\n\t\tint cur = root[i-1];\n\t\tcur = upd(i-1, -1, cur);\n\t\tif(~nx[i-1])\n\t\t\tcur = upd(nx[i-1], 1, cur);\n\t\troot[i] = cur;\n\t}\n\tFor(k,1,n+1){\n\t\tint ans = 0;\n\t\tif(k == n)\n\t\t\tans = 1;\n\t\telse{\n\t\t\tint cur = 0;\n\t\t\twhile(cur < n){\n\t\t\t\t++ ans;\n\t\t\t\tcur = kth(k+1, root[cur]);\n\t\t\t}\n\t\t}\n\t\tprintf(\"%d \", ans);\n\t}\n\tputs(\"\");\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2400
  },
  {
    "contest_id": "786",
    "index": "D",
    "title": "Rap God",
    "statement": "Rick is in love with Unity. But Mr. Meeseeks also love Unity, so Rick and Mr. Meeseeks are \"love rivals\".\n\nUnity loves rap, so it decided that they have to compete in a rap game (battle) in order to choose the best. Rick is too nerds, so instead he's gonna make his verse with running his original algorithm on lyrics \"Rap God\" song.\n\nHis algorithm is a little bit complicated. He's made a tree with $n$ vertices numbered from $1$ to $n$ and there's a lowercase english letter written on each edge. He denotes $str(a, b)$ to be the string made by writing characters on edges on the shortest path from $a$ to $b$ one by one (a string of length equal to distance of $a$ to $b$). Note that $str(a, b)$ is reverse of $str(b, a)$ and $str(a, a)$ is empty.\n\nIn order to make the best verse he can, he needs to answer some queries, but he's not a computer scientist and is not able to answer those queries, so he asked you to help him. Each query is characterized by two vertices $x$ and $y$ ($x ≠ y$). Answer to this query is the number of vertices like $z$ such that $z ≠ x, z ≠ y$ and $str(x, y)$ is lexicographically larger than $str(x, z)$.\n\nString $x = x_{1}x_{2}...x_{|x|}$ is lexicographically larger than string $y = y_{1}y_{2}...y_{|y|}$, if either $|x| > |y|$ and $x_{1} = y_{1}, x_{2} = y_{2}, ..., x_{|y|} = y_{|y|}$, or exists such number $r (r < |x|, r < |y|)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ..., x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. Characters are compared like their ASCII codes (or alphabetic order).\n\nHelp Rick get the girl (or whatever gender Unity has).",
    "tutorial": "Use centroid-decomposition. In each decomposition: Assume $c$ is centroid of current subtree. Then for each vertex $v$ in current subtree, we want to find some part of answer for each query with $x = v$. More precisely, for each query $(x, y)$ that $x$ is in the current subtree (in the decomposition), we want to find the number of vertices like $z$ such that $z$ is also in the subtree, if we remove the centroid from the tree $z$ and $x$ will be disconnected (centroid itself satisfies this condition) and $str(x, z) < str(x, y)$. $str(x, z) = str(x, c) + str(c, z)$. So for each query first compare $str(x, y)$ with $str(x, c)$. Comparing two paths ($str(x, y)$ and $str(v, u)$) can be done using hash (for each $v$ and $k$, keep hash of $str(v, 2^{i} - th parent of v)$ and its reverse) and using binary search for finding LCP of two strings. Based on result of comparison: If $str(x, y) < str(x, c)$, then there's no such $z$ in current subtree. If $str(x, y) > str(x, c)$ and $str(x, c)$ is not a prefix of $str(x, y)$, then all vertices like $z$ that satisfy the first two conditions (from the three conditions above) are counted. Otherwise there's a vertex $e$ on path from $x$ to $y$ such that $str(x, w) = str(x, c)$. Because $str(x, z) = str(x, c) + str(c, z)$ and $str(x, y) = str(x, w) + str(w, y) = str(x, c) + str(w, y)$, then you have to count such $z$ that satisfy the first two conditions and $str(c, z) < str(w, y)$. For the third case, you need to count vertices like $z$ that $str(c, z) < str(w, y)$. For this purpose, using a single DFS construct trie of all $str(c, z)$ and then for each query find the position of $str(w, y)$ in the trie (using hashes and binary search). More precisely, you need to find LCP of $str(w, y)$ and strings in the trie to determine how many strings in the trie are less than $str(w, y)$. All of this can be done in $O((n+q)l g^{2}(n))$ And there's an additional $log$ for centroid-decomposition, so: Total time complexity: $O((n+q)l g^{3}(n))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 2e4 + 100, maxl = 15;\nint mod[2] = {(int)1e9 + 7, (int)1e9 + 9}, base[2] = {717, 749};\nint pw[2][maxn], centroid;\nint par[maxn][maxl], up[maxn][maxl][2], dw[maxn][maxl][2], h[maxn], p2[maxl];\ntypedef pair<int, char> edge;\nint n, q;\npii query[maxn];\nvi queries[maxn];\nint ANS[maxn];\nvector<edge> adj[maxn];\nchar c2p[maxn];\nbool block[maxn];\nint sz[maxn];\ninline void dfs(int v = 0, int p = -1, char ch = -1){\n\tif(~p){\n\t\th[v] = h[p] + 1;\n\t\tc2p[v] = ch;\n\t\tFor(e,0,2)\n\t\t\tup[v][0][e] = dw[v][0][e] = c2p[v] - 'a';\n\t\tpar[v][0] = p;\n\t}\n\tFor(i,1,maxl){\n\t\tif(~par[v][i-1])\tpar[v][i] = par[par[v][i-1]][i-1];\n\t\tif(~par[v][i])\n\t\t\tFor(e,0,2){\n\t\t\t\tup[v][i][e] = (1LL * up[v][i-1][e] * pw[e][p2[i-1]] + up[par[v][i-1]][i-1][e]) % mod[e];\n\t\t\t\tdw[v][i][e] = (1LL * dw[par[v][i-1]][i-1][e] * pw[e][p2[i-1]] + dw[v][i-1][e]) % mod[e];\n\t\t\t}\n\t}\n\trep(e, adj[v]){\n\t\tint u = e.x;\n\t\tif(u - p)\tdfs(u, v, e.y);\n\t}\n}\ninline int lca(int v, int u){\n\tif(h[v] < h[u])\tswap(v, u);\n\trof(i,maxl-1,-1)\tif(~par[v][i] && h[par[v][i]] >= h[u])\n\t\tv = par[v][i];\n\tif(v == u)\treturn v;\n\trof(i,maxl-1,-1)\tif(par[v][i] - par[u][i])\n\t\tv = par[v][i], u = par[u][i];\n\treturn par[v][0];\n}\ninline int dist(int v, int u){\n\treturn h[v] + h[u] - 2 * h[lca(v, u)];\n}\ninline int kth_anc(int v, int k){\n\trof(i,maxl-1,-1) if(k >= p2[i]){\n\t\tk -= p2[i];\n\t\tv = par[v][i];\n\t\tassert(~v);\n\t}\n\treturn v;\n}\ninline int kth_on_path(int v, int u, int k){\n\tint x = lca(v, u);\n\tint a = h[v] - h[x],\n\t\tb = h[u] - h[x];\n\tassert(a + b >= k);\n\tif(a >= k)\n\t\treturn kth_anc(v, k);\n\treturn kth_anc(u, a + b - k);\n}\ninline char kth_edge_on_path(int v, int u, int k){\n\tint x = lca(v, u);\n\tint a = h[v] - h[x],\n\t\tb = h[u] - h[x];\n\tassert(a + b >= k);\n\tif(a >= k)\n\t\treturn c2p[kth_anc(v, k-1)];\n\treturn c2p[kth_anc(u, a + b - k)];\n}\ninline pii hash_up(int v, int u){\n\tint ans[2] = {};\n\trof(i,maxl-1,-1)\tif(~par[v][i] && h[par[v][i]] >= h[u]){\n\t\tFor(e,0,2)\n\t\t\tans[e] = (1LL * ans[e] * pw[e][p2[i]] + up[v][i][e]) % mod[e];\n\t\tv = par[v][i];\n\t}\n\treturn {ans[0], ans[1]};\n}\ninline pii hash_dw(int v, int u){\n\tint ans[2] = {};\n\tint cur = 0;\n\trof(i,maxl-1,-1)\tif(~par[v][i] && h[par[v][i]] >= h[u]){\n\t\tFor(e,0,2)\n\t\t\tans[e] = (ans[e] + 1LL * pw[e][cur] * dw[v][i][e]) % mod[e];\n\t\tcur += p2[i];\n\t\tv = par[v][i];\n\t}\n\treturn {ans[0], ans[1]};\n}\ninline pii hash_path(int v, int u){\n\tint x = lca(v, u);\n\tint a = h[v] - h[x],\n\t\tb = h[u] - h[x];\n\tpii U = hash_up(v, x), D = hash_dw(u, x);\n\treturn {(1LL * U.x * pw[0][b] + D.x) % mod[0],\t(1LL * U.y * pw[1][b] + D.y) % mod[1]};\n}\nbool olcp;\ninline int lcp(int v, int u, int x, int y){\n\tint d1 = dist(v, u), d2 = dist(x, y);\n\tint r = 1 + min(d1, d2), l = 0;\n\twhile(l + 1 < r){\n\t\tint mid = (l + r) >> 1;\n\t\tint w = kth_on_path(v, u, mid),\n\t\t\tz = kth_on_path(x, y, mid);\n\t\tif(hash_path(v, w) == hash_path(x, z))\n\t\t\tl = mid;\n\t\telse\n\t\t\tr = mid;\n\t}\n\treturn l;\n}\ninline int cmp(int v, int u, int x, int y){ // first: neg, second: pos\n\tolcp = true;\n\tif(v == u && x == y)\treturn 0;\n\tif(x == y)\treturn 1;\n\tif(v == u)\treturn -1;\n\tolcp = false;\n\tint d1 = dist(v, u), d2 = dist(x, y);\n\tint l = lcp(v, u, x, y);\n\tif(l == d1 || l == d2)\tolcp = true;\n\tif(d1 == d2 && l == d1)\treturn 0;\n\tif(l == d1)\treturn -1;\n\tif(l == d2)\treturn 1;\n\tint c1 = kth_edge_on_path(v, u, l+1) - 'a',\n\t\tc2 = kth_edge_on_path(x, y, l+1) - 'a';\n\tassert(c1 != c2);\n\treturn c1 - c2;\n}\nint thash[maxn * 2][2], tri[maxn * 2][27], nx = 1;\ntypedef pair<pii, int> piii;\nvector<piii > mp;\nvi weight[maxn * 2];\nvector<pii> qth[maxn * 2];\nint sig[maxn], tot;\ninline void clean(){\n\tFor(i,0,nx){\n\t\tthash[i][0] = thash[i][1] = 0;\n\t\tFor(j,0,27)\ttri[i][j] = 0;\n\t\trep(w, weight[i])\tif(~w)\tsig[w] = 0;\n\t\tweight[i].clear();\n\t\tqth[i].clear();\n\t}\n\ttot = 0;\n\tnx = 1;\n\tmp.clear();\n}\ninline void dfs_on_trie(int v = 0){\n\trep(qt, qth[v]){\n\t\tint q = qt.x, afc = qt.y;\n\t\tint ans = tot;\n\t\tif(~afc)\n\t\t\tans -= sig[afc];\n\t\tANS[q] += ans;\n\t}\n\trep(w, weight[v]){\n\t\t++ tot;\n\t\tif(~w)\t++ sig[w];\n\t}\n\tFor(i,0,27)\tif(tri[v][i])\tdfs_on_trie(tri[v][i]);\n}\ninline int MP(pii p){\n\tpair<pii, int> P = make_pair(p, -1);\n\tlower_bound(all(mp), P);\n\tint x = lower_bound(all(mp), make_pair(p, -1)) - mp.begin();\n\tif(x == (int)mp.size())\treturn -1;\n\tif(mp[x].x != p)\treturn -1;\n\treturn mp[x].y;\n}\ninline void insert(int q, int afc){\n\tint ov = query[q].x, u = query[q].y;\n\tint v = kth_on_path(ov, u, dist(ov, centroid));\n\tint d = dist(v, u);\n\tint l = 0, r = d + 1;\n\twhile(l + 1 < r){\n\t\tint mid = (l + r) >> 1;\n\t\tint w = kth_on_path(v, u, mid);\n\t\tif(~MP(hash_path(v, w)))\n\t\t\tl = mid;\n\t\telse\n\t\t\tr = mid;\n\t}\n\tint w = kth_on_path(v, u, l);\n\tif(u == w)\n\t\tqth[MP(hash_path(v, w))].pb({q, afc});\n\telse{\n\t\tint cur = MP(hash_path(v, w));\n\t\tassert(~cur);\n\t\tint c = kth_edge_on_path(v, u, l+1) - 'a';\n\t\tif(!tri[cur][c])\n\t\t\ttri[cur][c] = nx ++;\n\t\tcur = tri[cur][c];\n\t\tqth[cur].pb({q, afc});\n\t}\n}\ninline void add_to_trie(int v, int c){\n\ttri[v][c] = nx ++;\n\tint u = tri[v][c];\n\tFor(e,0,2)\n\t\tthash[u][e] = (1LL * thash[v][e] * base[e] + c) % mod[e];\n\tpii p = {thash[u][0], thash[u][1]};\n\tmp.pb(piii(p, u));\n\tpiii ww = mp[0];\n}\ninline void dfs_add(int v, int p = -1, int cur = 0, int afc = -1){\n\tweight[cur].pb(afc);\n\trep(e, adj[v]){\n\t\tint u = e.x, c = e.y - 'a';\n\t\tif(block[u] or u == p)\tcontinue;\n\t\tif(!tri[cur][c])\tadd_to_trie(cur, c);\n\t\tdfs_add(u, v, tri[cur][c], (v == centroid? u: afc));\n\t}\n}\ninline void dfs_insert(int v, int p = -1, int afc = -1){\n\trep(q, queries[v]){\n\t\tint u = query[q].y;\n\t\t\tint res = cmp(v, u, v, centroid);\n\t\tif(res < 0)\tcontinue ;\n\t\tif(res && !olcp)\tANS[q] += sz[centroid] - (~afc? sz[afc]: 1);\n\t\telse\n\t\t\tinsert(q, afc);\n\t}\n\trep(e, adj[v]){\n\t\tint u = e.x;\n\t\tif(block[u] or u == p)\tcontinue;\n\t\tdfs_insert(u, v, (v == centroid? u: afc));\n\t}\n}\ninline int DFS(int v, int p = -1){\n\tsz[v] = 1;\n\trep(e, adj[v]){\n\t\tint u = e.x;\n\t\tif(u - p && !block[u])\tsz[v] += DFS(u, v);\n\t}\n\treturn sz[v];\n}\ninline void centroid_decomposition(int v = 0){\n\tint N = DFS(v), prv = -1;\n\tbool fnd = true;\n\twhile(fnd){\n\t\tfnd = false;\n\t\trep(e, adj[v]){\n\t\t\tint u = e.x;\n\t\t\tif(!block[u] && u != prv && sz[u] * 2 >= N){\n\t\t\t\tprv = v;\n\t\t\t\tv = u;\n\t\t\t\tfnd = true;\n\t\t\t\tbreak ;\n\t\t\t}\n\t\t}\n\t}\n\tblock[v] = true;\n\trep(e, adj[v]){\n\t\tint u = e.x;\n\t\tif(!block[u])\tcentroid_decomposition(u);\n\t}\n\tcentroid = v;\n\tDFS(v);\n\tdfs_add(v);\n\tmp.pb({{0, 0}, 0});\n\tsort(all(mp));\n\tmp.resize(unique(all(mp)) - mp.begin());\n\tdfs_insert(v);\n\tdfs_on_trie();\n\tclean();\n\tblock[v] = false;\n}\nint main(){\n\tmemset(par, -1, sizeof par);\n\tFor(i,0,maxl)\tp2[i] = 1 << i;\n\tFor(e,0,2){\n\t\tpw[e][0] = 1;\n\t\tFor(i,1,maxn)\n\t\t\tpw[e][i] = (1LL * pw[e][i-1] * base[e]) % mod[e];\n\t}\n\tiOS;\n\tcin >> n >> q;\n\tFor(i,1,n){\n\t\tint v, u;\n\t\tchar c;\n\t\tcin >> v >> u >> c;\n\t\t++ c;\n\t\t-- v, -- u;\n\t\tadj[v].pb({u, c});\n\t\tadj[u].pb({v, c});\n\t}\n\tFor(i,0,q){\n\t\tint v, u;\n\t\tcin >> v >> u;\n\t\t-- v, -- u;\n\t\tquery[i] = {v, u};\n\t\tqueries[v].pb(i);\n\t}\n\tdfs();\n\tcentroid_decomposition();\n\tFor(i,0,q)\n\t\tcout << -- ANS[i] << '\n';\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "hashing",
      "strings",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "786",
    "index": "E",
    "title": "ALT",
    "statement": "ALT is a planet in a galaxy called \"Encore\". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy.\n\nALT has $n$ cities numbered from $1$ to $n$ and $n - 1$ bidirectional roads numbered from $1$ to $n - 1$. One can go from any city to any other city using these roads.\n\nThere are two types of people in ALT:\n\n- Guardians. A guardian lives in a house alongside a road and guards the road.\n- Citizens. A citizen lives in a house inside a city and works in an office in another city.\n\nEvery person on ALT is either a guardian or a citizen and there's exactly one guardian alongside each road.\n\nRick and Morty talked to all the people in ALT, and here's what they got:\n\n- There are $m$ citizens living in ALT.\n- Citizen number $i$ lives in city number $x_{i}$ and works in city number $y_{i}$.\n- Every day each citizen will go through all roads along the shortest path from his home to his work.\n- A citizen will be happy if and only if either he himself has a puppy himself or all of guardians along his path to his work has a puppy (he sees the guardian's puppy in each road and will be happy).\n- A guardian is always happy.\n\nYou need to tell Rick and Morty the minimum number of puppies they need in order to make all people in ALT happy, and also provide an optimal way to distribute these puppies.",
    "tutorial": "If $n$ and $m$ were smaller: We construct a bipartite graph. For each citizen we consider a vertex in the first part, and for each guardian in the tree we consider a vertex in the second part. We put an edge between vertex $i$ from first part and $j$ from second part if and only if path $x_{i}$ to $y_{i}$ contains edge $j$. Answer to the problem is vertex cover of this graph. Time complexity: $O(n^{2}m)$ But now that $n$ and $m$ are great, we can't use this approach. We will instead build a DAG. Like above, For each citizen we consider a vertex in the first part, and for each guardian in the tree we consider a vertex in the second part. Consider the data structure that is used to find LCA of two vertices in the tree (keeping $2^{i}$-th ancestor of each vertex for each $i$). We will use that to build the graph. For each vertex $v$ in the tree and $i$ ($0  \\le  i  \\le  lg(n)$), we consider a vertex in the tree, this vertex is $pr(v, i)$. We'll build a flow network. For each $v$, we put an edge from $pr(v, 0)$ to the vertex corresponding to edge (guardian) connecting $v$ and its parent (with capacity = $ \\infty $). For each $i > 0$, we put an edge from $pr(v, i)$ to $pr(v, i - 1)$ with capacity = $ \\infty $ and one to $pr(2^{i - 1} - th parent of v, i - 1)$ with capacity = $ \\infty $. Then for each citizen, like the algorithm we used to find the LCA of $x_{i}$ and $y_{i}$, when we're going up from a vertex $v$ to its $i$-th parent, we put an edge from vertex corresponding to citizen $i$ to $pr(v, i)$ with capacity = $1$. Finally we consider a vertex $S$ as source and $T$ and sink. For each citizen $i$, we put an edge from $S$ to vertex corresponding to him/her with capacity = $1$. And for each guardian put an edge from vertex corresponding to this edge to $T$ with capacity = $1$. It can be shown that the answer to the original problem is maximum flow of this network. Also certificate can be found using a DFS (it's exactly like finding a certificate(vertex cover) in maximum-matching approach). Since the network contains levels(cuts) from $S$ to $T$ with all edges with capacity equal to $1$, the total time complexity is $O(E{\\sqrt{E}})$ where $E$ is the number of edges in the network which is $O(n\\lg(n))$, so: Time complexity: $O(n{\\sqrt{n}}l g(n))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef pair<vi, vi> pvv;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 2e4 + 100, maxl = 15;\ntemplate <class FlowT> class MaxFlow{\n\tpublic:\n\t\tstatic const int maxn = 4e5+100, maxm = 1e6+100;\n\t\tstatic const FlowT FlowEPS = FlowT(1e-8), FlowINF = FlowT(1 << 29);\n\t\tint to[maxm * 2], prv[maxm * 2], hed[maxn], dis[maxn], pos[maxn];\n\t\tint mat[maxn][2], stat[maxn], assignee[maxn];\n\t\tbool mark[maxn];\n\t\tFlowT cap[maxm * 2];\n\t\tint n, m;\n\t\tinline void init(int N){\n\t\t\tn = N, m = 0;\n\t\t\tmemset(hed, -1, n * sizeof hed[0]);\n\t\t\tmemset(stat, -1, sizeof mat); \n\t\t\tmemset(mat, -1, sizeof mat);\n\t\t\tmemset(assignee, -1, sizeof assignee);\n\t\t}\n\tprivate:\n\t\tinline void add_single_edge(int v, int u, FlowT c){\n\t\t\tassert(m < 2*maxm);\n\t\t\tto[m] = u, prv[m] = hed[v], cap[m] = c, hed[v] = m ++;\n\t\t}\n\tpublic:\n\t\tvoid set_ver(int v, int s, int a){\n\t\t\tstat[v] = s, assignee[v] = a;\n\t\t}\n\t\tinline void add_edge(int v, int u, FlowT c){\n\t\t\tadd_single_edge(v, u, c);\n\t\t\tadd_single_edge(u, v, 0);\n\t\t}\n\t\tinline bool bfs(int source, int sink){\n\t\t\tstatic int qu[maxn], head, tail;\n\t\t\thead = tail = 0;\n\t\t\tmemset(dis, -1, n * sizeof dis[0]);\n\t\t\tdis[source] = 0;\n\t\t\tqu[tail ++] = source;\n\t\t\twhile(head < tail){\n\t\t\t\tint v = qu[head ++];\n\t\t\t\tfor(int e = hed[v]; e + 1; e = prv[e])\n\t\t\t\t\tif(cap[e] > FlowEPS && dis[to[e]] == -1)\n\t\t\t\t\t\tdis[to[e]] = dis[v] + 1, qu[tail ++] = to[e];\n\t\t\t\tif(dis[sink] + 1)\tbreak ;\n\t\t\t}\n\t\t\treturn dis[sink] + 1;\n\t\t}\n\t\tinline FlowT dfs(int v, int sink, FlowT cur = FlowINF){\n\t\t\tif(v == sink)\treturn cur;\n\t\t\tFlowT ans = 0;\n\t\t\tfor(int &e = pos[v]; e + 1; e = prv[e])\n\t\t\t\tif(cap[e] > FlowEPS && dis[to[e]] == dis[v] + 1){\n\t\t\t\t\tFlowT tmp = dfs(to[e], sink, min(cur, cap[e]));\n\t\t\t\t\tcur -= tmp;\n\t\t\t\t\tans += tmp;\n\t\t\t\t\tcap[e] -= tmp;\n\t\t\t\t\tcap[e ^ 1] += tmp;\n\t\t\t\t\tif(cur <= FlowEPS/2)\tbreak ;\n\t\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t\tinline FlowT flow(int source, int sink){\n\t\t\tFlowT ans = 0;\n\t\t\twhile(bfs(source, sink)){\n\t\t\t\tmemcpy(pos, hed, n * sizeof hed[0]);\n\t\t\t\tans += dfs(source, sink);\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t\tinline int dfs(int v){\n\t\t\tif(stat[v] == 1)\treturn v;\n\t\t\tfor(int &e = pos[v]; e + 1; e = prv[e]){\n\t\t\t\tif((e & 1) or !cap[e ^ 1])\tcontinue ;\n\t\t\t\t-- cap[e ^ 1];\n\t\t\t\t++ cap[e];\n\t\t\t\treturn dfs(to[e]);\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\tinline void find_matches(){\n\t\t\tmemcpy(pos, hed, n * sizeof hed[0]);\n\t\t\tFor(v,0,n)\tif(!stat[v]){\n\t\t\t\tint u = dfs(v);\n\t\t\t\tif(~u)\n\t\t\t\t\tmat[v][0] = u, mat[u][1] = v;\n\t\t\t}\n\t\t}\n\t\tinline void DFS(int v){\n\t\t\tmark[v] = true;\n\t\t\tif(stat[v] == 1){\n\t\t\t\tif(~mat[v][1])\n\t\t\t\t\tDFS(mat[v][1]);\n\t\t\t\treturn ;\n\t\t\t}\n\t\t\tfor(int e = hed[v]; e + 1; e = prv[e]) if(!(e & 1)){\n\t\t\t\tint u = to[e];\n\t\t\t\tif(!mark[u])\tDFS(u);\n\t\t\t}\n\n\t\t}\n\t\tinline pvv vertex_cover(){ // (top, bottom) = (queries, edges)\n\t\t\tfind_matches();\n\t\t\tfill(mark, mark + maxn, false);\n\t\t\tFor(v,0,n)\tif(!stat[v] && mat[v][0] == -1)\n\t\t\t\tDFS(v);\n\t\t\tvi q, e;\n\t\t\tFor(v,0,n){\n\t\t\t\tif(!stat[v] && ~mat[v][0] && !mark[mat[v][0]])\n\t\t\t\t\tq.pb(assignee[v]);\n\t\t\t\telse if(stat[v] == 1 && mark[v]){\n\t\t\t\t\tassert(~mat[v][1]);\n\t\t\t\t\te.pb(assignee[v]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn pvv(q, e);\n\t\t}\n};\nMaxFlow<int> F;\nconst int N = 4e5;\nconst int S = 0, T = 1;\nint nx = 2;\nvector<pii> adj[maxn];\nint par[maxn][maxl], inp[maxn][maxl];\nint h[maxn];\ninline void dfs(int v = 0, int p = -1, int ep = -1){\n\tpar[v][0] = p;\n\tif(~p){\n\t\th[v] = h[p] + 1;\n\t\tinp[v][0] = nx;\n\t\tF.set_ver(nx, 1, ep);\n\t\tF.add_edge(nx ++, T, 1);\n\t}\n\tFor(i,1,maxl)\tif(~par[v][i-1]){\n\t\tpar[v][i] = par[par[v][i-1]][i-1];\n\t\tif(~par[v][i]){\n\t\t\tinp[v][i] = nx;\n\t\t\tF.add_edge(nx, inp[v][i-1], N);\n\t\t\tF.add_edge(nx ++, inp[par[v][i-1]][i-1], N);\n\t\t}\n\t}\n\trep(ue, adj[v]){\n\t\tint u = ue.x, e = ue.y;\n\t\tif(u - p)\n\t\t\tdfs(u, v, e);\n\t}\n}\ninline int lca(int v, int u, int ver){\n\tif(h[v] < h[u])\tswap(v, u);\n\trof(i,maxl-1,-1)\tif(~par[v][i] && h[par[v][i]] >= h[u]){\n\t\tF.add_edge(ver, inp[v][i], N);\n\t\tv = par[v][i];\n\t}\n\tif(v == u)\treturn v;\n\trof(i,maxl-1,-1)\tif(par[v][i] != par[u][i]){\n\t\tF.add_edge(ver, inp[v][i], N);\n\t\tF.add_edge(ver, inp[u][i], N);\n\t\tv = par[v][i], u = par[u][i];\n\t}\n\tF.add_edge(ver, inp[v][0], N);\n\tF.add_edge(ver, inp[u][0], N);\n\treturn par[v][0];\n}\nint main(){\n\tiOS;\n\tmemset(par, -1, sizeof par);\n\tint n, m;\n\tcin >> n >> m;\n\tF.init(N);\n\tFor(i,1,n){\n\t\tint v, u;\n\t\tcin >> v >> u;\n\t\t-- v, -- u;\n\t\tadj[v].pb({u, i});\n\t\tadj[u].pb({v, i});\n\t}\n\tdfs();\n\tFor(i,0,m){\n\t\tint v, u;\n\t\tcin >> v >> u;\n\t\t-- v, -- u;\n\t\tint ver = nx;\n\t\tF.set_ver(nx, 0, i + 1);\n\t\tF.add_edge(S, nx++, 1);\n\t\tlca(v, u, ver);\n\t}\n\tassert(nx < N);\n\tcout << F.flow(S, T) << '\n';\n\tpvv pv = F.vertex_cover();\n\tvi vc[2] = {pv.x, pv.y};\n\tFor(i,0,2){\n\t\tcout << vc[i].size() << ' ';\n\t\trep(v, vc[i])\n\t\t\tcout << v << ' ';\n\t\tcout << '\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "flows",
      "graphs",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "787",
    "index": "A",
    "title": "The Monster",
    "statement": "A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times $b, b + a, b + 2a, b + 3a, ...$ and Morty screams at times $d, d + c, d + 2c, d + 3c, ...$.\n\nThe Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.",
    "tutorial": "You need to find out if there are non-negative integers like $i$ and $j$ such $ai + b = cj + d$ and $i$ or $j$ (or both) is minimized. It's easy to show that if $a, b, c, d  \\le  N$, and such $i$ and $j$ exist, then $i, j  \\le  N$, so you can iterate over $i$ and check if such $j$ exists. Time complexity: ${\\mathcal{O}}(n)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxi = 1e5;\nint main(){\n\tiOS;\n\tint a, b, c, d;\n\tcin >> a >> b >> c >> d;\n\tFor(i,0,maxi){\n\t\tint v = a*i + b;\n\t\tif(v < d)\tcontinue ;\n\t\tint u = v - d;\n\t\tif(u % c == 0){\n\t\t\tcout << v << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout << -1 << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "787",
    "index": "B",
    "title": "Not Afraid",
    "statement": "Since the giant heads have appeared in the sky all humanity is in danger, so \\textbf{all} Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them.\n\nThere are $n$ parallel universes participating in this event ($n$ Ricks and $n$ Mortys). I. e. each of $n$ universes has one Rick and one Morty. They're gathering in $m$ groups. Each person can be in many groups and a group can contain an arbitrary number of members.\n\nRicks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility).\n\nSummer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world).\n\nSummer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all $2^{n}$ possible scenarios, $2$ possible scenarios for who a traitor in each universe) such that in that scenario the world will end.",
    "tutorial": "The problem says given a CNF formula, check if we can set value of literals such that the formula isn't satisfied. Answer is yes if and only if you can set values so that at least one clause isn't satisfied. It's easy to show that answer is yes if and only if there's at least one clause that for that clause there's no $i$ such that $x_{i}$ and $\\overline{{x_{i}}}$ are both in it. This can be easily implemented. Time complexity: $O(n+m)$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define Foreach(i, c) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)\n#define For(i,a,b) for(int (i)=(a);(i) < (b); ++(i))\n#define rof(i,a,b) for(int (i)=(a);(i) > (b); --(i))\n#define rep(i, c) for(auto &(i) : (c))\n#define x first\n#define y second\n#define pb push_back\n#define PB pop_back()\n#define iOS ios_base::sync_with_stdio(false)\n#define sqr(a) (((a) * (a)))\n#define all(a) a.begin() , a.end()\n#define error(x) cerr << #x << \" = \" << (x) <<endl\n#define Error(a,b) cerr<<\"( \"<<#a<<\" , \"<<#b<<\" ) = ( \"<<(a)<<\" , \"<<(b)<<\" )\n\";\n#define errop(a) cerr<<#a<<\" = ( \"<<((a).x)<<\" , \"<<((a).y)<<\" )\n\";\n#define coud(a,b) cout<<fixed << setprecision((b)) << (a)\n#define L(x) ((x)<<1)\n#define R(x) (((x)<<1)+1)\n#define umap unordered_map\n#define double long double\ntypedef long long ll;\ntypedef pair<int,int>pii;\ntypedef vector<int> vi;\ntypedef complex<double> point;\ntemplate <typename T> using os =  tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <class T>  inline void smax(T &x,T y){ x = max((x), (y));}\ntemplate <class T>  inline void smin(T &x,T y){ x = min((x), (y));}\nconst int maxn = 1e6 + 100;\nint lst[maxn * 2];\nint main(){\n\tint n, m;\n\tscanf(\"%d %d\", &n, &m);\n\tFor(i,1,m+1){\n\t\tvi v;\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\tbool ok = false;\n\t\twhile(k--){\n\t\t\tint x;\n\t\t\tscanf(\"%d\", &x);\n\t\t\tif(lst[maxn-x] == i)\n\t\t\t\tok = true;\n\t\t\tlst[maxn+x] = i;\n\t\t}\n\t\tif(!ok){\n\t\t\tputs(\"YES\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tputs(\"NO\");\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "788",
    "index": "A",
    "title": "Functions again",
    "statement": "Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function $f$, which is defined as follows:\n\n\\[\nf(l,r)=\\sum_{i=l}^{r-1}|a[i]-a[i+1]|\\cdot(-1)^{i-l}\n\\]\n\nIn the above formula, $1 ≤ l < r ≤ n$ must hold, where $n$ is the size of the Main Uzhlyandian Array $a$, and $|x|$ means absolute value of $x$. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of $f$ among all possible values of $l$ and $r$ for the given array $a$.",
    "tutorial": "We can solve the problem for segments with odd and even $l$ separately. Let's build arrays $b$ ($b_{i} = |a_{i + 1} - a_{i}| \\cdot ( - 1)^{i}$) and $c$ ($c_{i} = |a_{i + 1} - a_{i}| \\cdot ( - 1)^{i + 1}$). Obviously, that segment with the greatest sum in array $b$ starts in some even index. In every segment starting in odd index we can move $l$ one position right and make answer not-worse, because every element of odd index in $b$ is non-positive. Also, sum of segment starting in even index of $b$ equals to value of $f$ on the same segment. Analogically for array $c$ and odd starting indexes. So the answer equals to maximal of maximal sums of arrays $b$ and $c$. The segment with the greatest sum can be found with the two pointers method or using prefix sums. Such solution works with $O(N)$ complexity.",
    "tags": [
      "dp",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "788",
    "index": "B",
    "title": "Weird journey",
    "statement": "Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia.\n\nIt is widely known that Uzhlyandia has $n$ cities connected with $m$ bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over $m - 2$ roads twice, and over the other $2$ exactly once. The good path can start and finish in any city of Uzhlyandia.\n\nNow he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor — calculate the number of good paths.",
    "tutorial": "We can consider the system of towns and roads as a graph, where edges correspond to roads and vertexes to cities. Now, let's fix two edges, that will be visited once. All other edges we can split into two. Then, the good way in the old graph equivalents to any Euler path in the computed one. Widely known that Euler path exists in graph when and only when there are 0 or 2 vertexes with odd degree. Consider following cases of mutual placement of edges that will be visited once: Regular(not loops) edges that are not adjacent - graph has four vertexes with odd degree, so Euler path doesn't exist. Regular edges that are adjacent - graph has exactly two vertexes with odd degree, so Euler path exists. So, any pair of adjacent regular edges satisfies Igor. One of the edges is a loop - graph hasn't any vertex with the odd degree(if another chosen edge is a loop too) or has two of them(if another chosen edge is regular). So, any pair in which at least one edge is a loop satisfies Igor. So, we have to calculate the number of pairs of adjacent regular edges and add the answer for loops. For every vertex $i$ we can calculate $cnt_{i}$ - the number of regular edges incoming in it. General number of adjacent regular edges is $\\sum_{i=1}^{n}C_{c n t}^{2},$. Also, we need to add the number of pairs with loops. Let's count $loop$ - general number of loops in the graph. So we can add $loop \\cdot (m - 1)$ to the answer. Now, we included pairs with two loops twice. That's why we need to subtract $C_{loop}^{2}$ - the number of pairs with two loops. Also, we need to check the graph to be connected by edges. If the graph is not connected then the answer is 0. We can do it using algorithms of DFS or BFS. Complexity of the given solution if $O(N + M)$.",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "788",
    "index": "C",
    "title": "The Great Mixing",
    "statement": "Sasha and Kolya decided to get drunk with Coke, again. This time they have $k$ types of Coke. $i$-th type is characterised by its carbon dioxide concentration $\\frac{d i_{i}}{1000}$. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration $\\frac{p_{L}}{1000}$. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass.\n\nCarbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well.\n\nHelp them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration $\\frac{p_{L}}{1000}$. Assume that the friends have unlimited amount of each Coke type.",
    "tutorial": "Let $\\frac{p_{L}}{1000}$ - needed concentration and $s_{1}, s_{2}, ..., s_{m}$ - concentration of types we'll use. ${\\frac{s_{1}+s_{2}+\\cdot\\cdot\\cdot\\cdot+s_{m}}{1000\\cdot m}}={\\frac{n}{1000}}$${\\frac{s_{1}+s_{2}+\\cdot\\cdot\\cdot+s_{m}}{m}}=n$ $s_{1}+s_{2}+\\cdot\\cdot\\cdot+s_{m}=n\\cdot m$ $s_{1}+s_{2}+\\cdot\\cdot\\cdot\\cdot+s_{m}=n+n+\\cdot\\cdot\\cdot+n$ $(s_{1}-n)+(s_{2}-n)+\\cdot\\cdot\\cdot+(s_{m}-n)=0$ ${\\frac{s_{1}+s_{2}+\\cdot\\cdot\\cdot+s_{m}}{m}}=n$ $s_{1}+s_{2}+\\cdot\\cdot\\cdot+s_{m}=n\\cdot m$ $s_{1}+s_{2}+\\cdot\\cdot\\cdot\\cdot+s_{m}=n+n+\\cdot\\cdot\\cdot+n$ $(s_{1}-n)+(s_{2}-n)+\\cdot\\cdot\\cdot+(s_{m}-n)=0$ Then, we can decrease every $s_{i}$ by $n$. So, we reduced the problem to finding a set of numbers with zero sum. Now we can build a graph, where vertexes are our sum. There will be $m$ edges from each vertex, where $m$ - the number of different concentrations. Obviously, we'll have at most 1001 different concentrations, so there are at most 1001 edges from each vertex. Now, we need to find a cycle of smallest length. We can do this using BFS starting from vertex 0. With BFS we can find the first vertex with the existing edge to vertex 0. We need at most 1000 vertexes to each side (from -1000 to 1000), so the solution complexity is $O(2001 \\cdot min(k, 1001))$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "788",
    "index": "D",
    "title": "Finding lines",
    "statement": "After some programming contest Roma decided to try himself in tourism. His home country Uzhlyandia is a Cartesian plane. He wants to walk along each of the Main Straight Lines in Uzhlyandia. It is known that each of these lines is a straight line parallel to one of the axes (i.e. it is described with the equation $x = a$ or $y = a$, where $a$ is integer called the coordinate of this line).\n\nRoma lost his own map, so he should find out the coordinates of all lines at first. Uncle Anton agreed to help him, using the following rules:\n\n- Initially Roma doesn't know the number of vertical and horizontal lines and their coordinates;\n- Roma can announce integer coordinates of some point in Uzhlandia, and Anton then will tell him the minimum among the distances from the chosen point to each of the lines. However, since the coordinates of the lines don't exceed $10^{8}$ by absolute value, Roma can't choose a point with coordinates exceeding $10^{8}$ by absolute value.\n\nUncle Anton is in a hurry to the UOI (Uzhlandian Olympiad in Informatics), so he can only answer no more than $3·10^{5}$ questions.\n\nThe problem is that Roma doesn't know how to find out the coordinates of the lines. Write a program that plays Roma's role and finds the coordinates.",
    "tutorial": "First we solve another problem. Let we have points not straight lines, but points on one axis. Let $MAX = 10^{8}$, that is, the maximum coordinate. First, we find the left and right points. The left is ($- MAX + get( - MAX)$), and the right one ($MAX - get(MAX)$). Then we solve the problem recursively. There will be a function $f(l, r)$ that finds all points on the segment $(l, r)$ if $l$ and $r$ - are points. We have already found the extreme points, so we can call this function. The function $f(l, r)$ makes a query at the center point between $l$ and $r$, that is, $\\frac{l\\pm r}{2}$. If the answer is equal to the distance to the extreme points, then there are no more points between $l$ and $r$. If the distance is less, then for one more query we can find out the point on the left or right. Let this point $x$, then we start $f(l, x)$ and $f(x, r)$. We introduce a function that checks if there is a vertical line $x$. We can select a random point in the range $[ - MAX, MAX]$ and make a query, if the answer $0$ - is a straight line. If $MAX = 10^{8}$, and the maximum $n = 10^{4}$, then the error probability is $10^{ - 4}$, if you querys twice, then $10^{ - 8}$. Now we will solve the main task. We make a query at the point $( - MAX, - MAX)$, we can find out whether the minimum distance to the vertical or horizontal line. We introduce the function $G(x, y)$, which will find the nearest straight line whose coordinates are greater than $x$ or $y$, and $get(x, y) = 0$. How is this solved? If there are no more lines, then for non-negative $t$, $get(x + t, y + t) = t$. Then we can find a minimal power such that $get(x + t, y + t)  \\neq  t$. Then we know that this applies to either the vertical line $(x + t + get(x + t, y + t))$, or the horizontal $(y + t + get(x + t, y + t))$ . We can find out which one. If, for example, to the vertical one, then we solve the problem for $G(x + t + get(x + t, y + t), y)$. Then we find either all horizontal lines, or all vertical lines. To find out which straight lines we found, we need to look at the last function $G(x, y)$, namely our \"ray\". If it rests on the vertical straight $MAX$, then we find all the vertical ones. And vice versa. Now how to find other lines. Let's say we found all the vertical ones. Then we will find the maximum distance between the neighbors, between the first line and $( - MAX)$, between the last line and $(MAX)$, this distance will be at least $\\textstyle{\\frac{M A X}{M A X N}}$. That is, we search in what position the maximum will be reached, if there are no horizontal lines, let it be $val$. Let this be the coordinate $x$, we will make queries on the line $x$, starting with - $- MAX$, ending with $MAX$, with the step $\\frac{v a l}{4}$. We find all the points whose answer is not equal to $val$. Then we can divide all these points into \"segments\", that is, a set of points that go successively. For each \"segment\", the minimum distance will only apply to horizontal lines, that is, vertical ones will not affect in any way. Therefore, each \"segment\" can be solved independently, by the method already known to us (assume that there are no vertical lines).",
    "tags": [
      "constructive algorithms",
      "divide and conquer",
      "interactive"
    ],
    "rating": 3000
  },
  {
    "contest_id": "788",
    "index": "E",
    "title": "New task",
    "statement": "On the 228-th international Uzhlyandian Wars strategic game tournament teams from each country are called. The teams should consist of $5$ participants.\n\nThe team of Uzhlyandia will consist of soldiers, because there are no gamers.\n\nMasha is a new minister of defense and gaming. The prime duty of the minister is to calculate the efficiency of the Uzhlandian army. The army consists of $n$ soldiers standing in a row, enumerated from $1$ to $n$. For each soldier we know his skill in Uzhlyandian Wars: the $i$-th soldier's skill is $a_{i}$.\n\nIt was decided that the team will consist of three players and two assistants. The skills of players should be same, and the assistants' skills should not be greater than the players' skill. Moreover, it is important for Masha that one of the assistants should stand in the row to the left of the players, and the other one should stand in the row to the right of the players. Formally, a team is five soldiers with indexes $i$, $j$, $k$, $l$, $p$, such that $1 ≤ i < j < k < l < p ≤ n$ and $a_{i} ≤ a_{j} = a_{k} = a_{l} ≥ a_{p}$.\n\nThe efficiency of the army is the number of different teams Masha can choose. Two teams are considered different if there is such $i$ such that the $i$-th soldier is a member of one team, but not a member of the other team.\n\nInitially, all players are able to be players. For some reasons, sometimes some soldiers become unable to be players. Sometimes some soldiers, that were unable to be players, become able to be players. At any time any soldier is able to be an assistant. Masha wants to control the efficiency of the army, so she asked you to tell her the number of different possible teams modulo $1000000007$ ($10^{9} + 7$) after each change.",
    "tutorial": "To begin with, we apply scaling to all numbers and replace each element of the array with its position in the sorted array. Count the answer for the original array. For each $i$, calculate smaller_pref$_{i}$ as the quantity of such $j$ that $j < i$, $a_{j}  \\le  a_{i}$ and smaller_suf$_{i}$ - the number of such $j$ that $j > i$, $a_{j}  \\le  a_{i}$. This can be done with a segment tree or a Fenwick tree. If we consider each element as $k$ from the command $[i, j, k, l, p]$, then the answer for fives with this $k$ is $(\\sum_{j=1}^{k-1}$smaller_pref$_{j}$$, a_{j} = a_{k})$$ \\cdot $$({{\\sum}_{j=k+1}^{n}})$smaller_suf$_{j}$$, a_{j} = a_{k})$. The common answer is the sum of the answers for each possible $k$. Now after each request we will update the answer. We will support for each type of number for the prefix and suffix for 2 segment tree. Since when, an element turns on/off it is important to know only information about elements with the same value, then you can update the answer using only it. Consider array b as a number vector of occurrences of the form $a_{u}$. In the first \"suffix tree\" in the sheet we store smaller_suf$_{bi}$, if the element with the number $b_{i}$ is included, otherwise 0, and in the remaining vertices the sum in the sons. In the second suffix tree we store in the sheet smaller_suf$_{bi}$$ \\cdot $((the number $j$, such that $a_{j} = a_{bi}$, $< b[i]$, element with the number $j$ - is included) + 1), if the element with the number $b_{i}$ is included, otherwise 0, and in the remaining vertices the sum in the sons. For the prefix, you need to do exactly the same thing. Let $cnt_{au}$ be the number of numbers of the form $a_{u}$. Now when the request for turning off/on the element with number $u$ came, we need to subtract/add to the answer the number of such pentads [$i$, $j$, $k$, $l$, $p$] where $u = k$, $u = j$, $u = l$. Further $c_{u} =$ ((the quantity $j$, $j < u$, $a_{j} = a_{u}$) + 1). In other words, $c_{u}$ - is the number in the occurrence vector of numbers of the form $a_{u}$). First, consider the number of fives where $u = k$. Them is (the sum on the interval [1;$c_{u}$-1] in the first prefix tree) $ \\cdot $ (the sum on the segment [$c_{u}$+1;$cnt_{au}$] in the first \"suffix tree\"). The number of fives where $u = j$ is ((the sum on the segment [$c_{u}$+2;$cnt_{au}$] in the second \"suffix tree\" segments) - ((the number of elements j, $j  \\le  u$, $a_{j} = a_{u}$, the element with the number $j$ is included) +1)$ \\cdot $ (the sum on the segment [$c_{u}$+2;$cnt_{au}$] in the first \"suffix tree\" segments ))$ \\cdot $smaller_pref$_{u}$. The number of fives where $u = l$ must be calculated in the same way as for $u = j$, only in the other direction. Updating the values of the suffix tree elements: When the item is turned off, you need: Take the sum on the segment [$c_{u}$+1;$cnt_{au}$] in the second segment tree in the same segment in the first tree. Assign the element with the number $c_{u}$ to the element in the second segments tree 0. Assign the element with the number $c_{u}$ in the first tree 0. When you enable an item, you need: Add on the segment [$c_{u}$+1;$cnt_{au}$] in the second segment tree the sum on the same line in the first tree. Assign the element with the number $c_{u}$ in the second tree (the number of such $j$, $j  \\le  u$, $a_{j} = a_{u}$, the element j is included) + 1)$ \\cdot $smaller_suff$_{u}$. Assign the element with the number $c_{u}$ in the first tree smaller_suf$_{u}$. The update in the tree with the prefix is the same. Adding on the segment will be done by a kind of lazy pushing - in the second segment tree you need to have access to the corresponding vertex of the first tree, when changing the vertex, add/subtract the sum at the top of the first segment tree. The complexity of the solution is $O(N \\cdot logN + M \\cdot logN))$ by time, $O(N)$ by memory.",
    "tags": [
      "data structures"
    ],
    "rating": 2900
  },
  {
    "contest_id": "789",
    "index": "A",
    "title": "Anastasia and pebbles",
    "statement": "Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.\n\nShe has only \\textbf{two pockets}. She can put at most $k$ pebbles in each pocket at the same time. There are $n$ different pebble types in the park, and there are $w_{i}$ pebbles of the $i$-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.\n\nHelp her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.",
    "tutorial": "For every pebble type we can count the minimal number of pockets Anastasia need to collect all pebbles of this type. That's easy to notice that this number equals $\\textstyle\\left[{\\frac{\\boldsymbol{w_{j}}}{k}}\\right]$. So the answer for the problem is $\\textstyle\\left[\\frac{\\sum_{i=1}^{n}|\\frac{-i}{k}\\vert}{2}\\right]$. Solution complexity is $O(N)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "789",
    "index": "B",
    "title": "Masha and geometric depression",
    "statement": "Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.\n\nYou are given geometric progression $b$ defined by two integers $b_{1}$ and $q$. Remind that a geometric progression is a sequence of integers $b_{1}, b_{2}, b_{3}, ...$, where for each $i > 1$ the respective term satisfies the condition $b_{i} = b_{i - 1}·q$, where $q$ is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both $b_{1}$ and $q$ \\textbf{can equal $0$}. Also, Dvastan gave Masha $m$ \"bad\" integers $a_{1}, a_{2}, ..., a_{m}$, and an integer $l$.\n\nMasha writes all progression terms one by one onto the board (including repetitive) while condition $|b_{i}| ≤ l$ is satisfied ($|x|$ means absolute value of $x$). There is an exception: if a term equals one of the \"bad\" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.\n\nBut the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print \"inf\" in case she needs to write infinitely many integers.",
    "tutorial": "We need to handle following cases in the solution: $|b_{1}| > l$ - answer is 0. $b_{1} = 0$ - if 0 is present in array $a$ than answer is 0, else $inf$. $q = 1$ - if $b_{1}$ is present in array $a$ than answer is 0, else $inf$. $q = - 1$ - if both $b_{1}$ and $- b_{1}$ are present in array $a$ than answer is 0, otherwise $inf$. $q = 0$ - if 0 isn't present in array $a$ than answer is $inf$, else if $b_{1}$ is present in $a$ than answer is 0, else answer is 1. In all other cases we can simply iterate over all terms of progression $b$ while their absolute value doesn't exceed $l$. For every term that is not present in $a$ we simply increasing answer by 1. Obviously, the absolute value of every next element is bigger in at least 2 times than the absolute value of previous. That's why we'll need to check at most $log$ $l$ progression terms. Solution complexity is $O(M \\cdot log$$L)$ or $O(M \\cdot log$$M + log$$L \\cdot log$$M)$.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "791",
    "index": "A",
    "title": "Bear and Big Brother",
    "statement": "Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.\n\nRight now, Limak and Bob weigh $a$ and $b$ respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.\n\nLimak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.\n\nAfter how many full years will Limak become strictly larger (strictly heavier) than Bob?",
    "tutorial": "This problem is simple: just multiply $a$ by $3$ and $b$ by $2$ until $a > b$. Output the number of operations. You will not need more than $6$ iterations.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n\tint a, b;\n\tcin >> a >> b;\n\tint answer = 0;\n\twhile(a <= b) {\n\t\ta *= 3;\n\t\tb *= 2;\n\t\t++answer;\n\t}\n\tprintf(\"%d\\n\", answer);\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "792",
    "index": "A",
    "title": "New Bus Route",
    "statement": "There are $n$ cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers $a_{1}, a_{2}, ..., a_{n}$. All coordinates are pairwise distinct.\n\nIt is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.\n\nIt is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs.\n\nYour task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.",
    "tutorial": "At first let's notice that if there exists such triple $a_{i}$, $a_{j}$ and $a_{k}$ that $a_{i} < a_{j} < a_{k}$, then $|a_{k} - a_{i}| > |a_{j} - a_{i}|$ and $|a_{k} - a_{i}| > |a_{k} - a_{j}|$. Thus we can sort all numbers and check only adjacent ones. There are exactly $n - 1$ of such pairs. The only thing left is to find minimal distance of all pairs and count pairs with that distance. Overall complexity: $O(n\\log n)$",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "792",
    "index": "B",
    "title": "Counting-out Rhyme",
    "statement": "$n$ children are standing in a circle and playing the counting-out game. Children are numbered clockwise from $1$ to $n$. In the beginning, the first child is considered the leader. The game is played in $k$ steps. In the $i$-th step the leader counts out $a_{i}$ people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.\n\nFor example, if there are children with numbers $[8, 10, 13, 14, 16]$ currently in the circle, the leader is child $13$ and $a_{i} = 12$, then counting-out rhyme ends on child $16$, who is eliminated. Child $8$ becomes the leader.\n\nYou have to write a program which prints the number of the child to be eliminated on every step.",
    "tutorial": "The task was just about implementing algorithm described in statement. This is one of many possible ways of doing this. Firstly you should notice that doing $a_{i}$ iterations in $i$-th step is equal to doing $a_{i}$ $mod$ $(n - i)$ iterations ($0$-based numbering). That is less than $n$. Now fill array of length $n$ with ones and create pointer to current leader. Then on $i$-th step move pointer to the right (from cell $n - 1$ proceed to $0$) till you encounter $a_{i}$ $mod$ $(n - i)$ ones. When finished, write $0$ to this cell and move pointer to next cell which contains $1$. Overall complexity: $O(n^{2})$.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "792",
    "index": "C",
    "title": "Divide by Three",
    "statement": "A positive integer number $n$ is written on a blackboard. It consists of not more than $10^{5}$ digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.\n\nThe number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of $3$. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.\n\nWrite a program which for the given $n$ will find a beautiful number such that $n$ can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number $n$.\n\nIf it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.",
    "tutorial": "Let's declare a function which takes number as a string and erases minimal number of digits in substring from $2$-nd to last character to obtain beautiful number. Note that if the answer for given string exists, then this function will erase no more than $2$ digits. If the number is divisible by $3$ then sum of its digits is also divisible by $3$. So here are the only options for the function: Sum of digits is already equal to $0$ modulo $3$. Thus you don't have to erase any digits. There exists such a digit that equals sum modulo $3$. Then you just have to erase this digit. All of the digits are neither divisible by $3$, nor equal to sum modulo $3$. So two of such digits will sum up to number, which equals sum modulo $3$ ($(2 + 2)$ $mod$ $3 = 1$, $(1 + 1)$ $mod$ $3 = 2$). Let positions of non-zero numbers be $a_{1}, a_{2}, ..., a_{k}$. Then you can easily see that its enough to check only three function outputs: on substrings $[a_{1}..n]$, $[a_{2}..n]$ and $[a_{3}..n]$. We imply that all digits to the left of the taken non-zero digit are erased. As we can erase no more than $2$ digits, these options will cover all the cases. If there exists no answer for any of substrings, than you need to check if the number contains $0$ - it will be answer in that case. If there is no $0$, then answer is $- 1$. Otherwise the answer is the function output of maximal length. Overall complexity: $O(n)$.",
    "tags": [
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "792",
    "index": "D",
    "title": "Paths in a Complete Binary Tree",
    "statement": "$T$ is a complete binary tree consisting of $n$ vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So $n$ is a number such that $n + 1$ is a power of $2$.\n\nIn the picture you can see a complete binary tree with $n = 15$.\n\nVertices are numbered from $1$ to $n$ in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.\n\nYou have to write a program that for given $n$ answers $q$ queries to the tree.\n\nEach query consists of an integer number $u_{i}$ ($1 ≤ u_{i} ≤ n$) and a string $s_{i}$, where $u_{i}$ is the number of vertex, and $s_{i}$ represents the path starting from this vertex. String $s_{i}$ doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from $s_{i}$ have to be processed from left to right, considering that $u_{i}$ is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by $s_{i}$ ends.\n\nFor example, if $u_{i} = 4$ and $s_{i} = $«UURL», then the answer is $10$.",
    "tutorial": "In this editorial $x$ represents the number of vertex we are currently in. Let $k$ be the maximum integer number such that $x$ is divisible by $2^{k}$ (or the number of zeroes at the end of the binary representation of $x$). It is easy to prove that if $k = 0$, then $x$ is a leaf; if $k = 1$, then both children of $x$ are leaves, and so on. Even more, the difference between $x$ and any of his children is exactly $2^{k - 1}$. So to traverse to the left child, we have to subtract $2^{k - 1}$ from $x$ (if $x$ is not a leaf), and to traverse to the right child, we add $2^{k - 1}$ to $x$. How can we process traversions up? Let $y$ be the number of the parent node. $y$ has exactly $k + 1$ zeroes at the end of its binary representation, so to traverse from $y$ to $x$, we need to either add or subtract $2^{k}$ from $y$. And to traverse from $x$ to $y$ we also have to either subtract or add $2^{k}$ to $x$. One of these operations will lead us to the number divisible by $2^{k + 1}$ and not divisible by $2^{k + 2}$, and we need to choose this operation. Time complexity is $O(\\sum_{i=1}^{q}|s_{i}|)$.",
    "tags": [
      "bitmasks",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "792",
    "index": "E",
    "title": "Colored Balls",
    "statement": "There are $n$ boxes with colored balls on the table. Colors are numbered from $1$ to $n$. $i$-th box contains $a_{i}$ balls, all of which have color $i$. You have to write a program that will divide all balls into sets such that:\n\n- each ball belongs to exactly one of the sets,\n- there are no empty sets,\n- there is no set containing two (or more) balls of different colors (each set contains only balls of one color),\n- there are no two sets such that the difference between their sizes is greater than $1$.\n\nPrint the minimum possible number of sets.",
    "tutorial": "If we want to divide all balls from some box into $k$ sets with sizes $x$ and $x + 1$ (and there are $a_{i}$ balls in this box), then either $k\\leq{\\sqrt{a_{i}}}$ or $x\\leq{\\sqrt{a_{i}}}$. So the solution will be like that: Iterate over the possible sizes of sets $x$ (from $1$ to $|{\\sqrt{a_{1}}}|$, or to some constant - in our solution it's $40000$) and check if we can divide all balls into sets with sizes $x$ and $x + 1$, Then iterate over the number of sets $k$, calculate the sizes of sets if we want to divide the first box exactly into $k$ sets and try to divide balls from all other boxes into sets of these sizes. If we want to divide $a_{i}$ balls from the same box into $k$ sets, then the sizes will be $\\left\\lfloor{\\frac{a_{k}}{k}}\\right\\rfloor$ and $\\lfloor{\\frac{a_{i}}{k}}\\rfloor+1$; but if $a_{i}{\\dot{z}}{\\dot{k}}$, then we also have to check if sizes can be $\\left\\vert{\\frac{a_{i}}{k}}\\right\\vert-1$ and $\\left\\lfloor{\\frac{a_{k}}{k}}\\right\\rfloor$. If we fix sizes $x$ and $x + 1$ and we want to check whether we can divide a box with $a_{i}$ balls into sets with these sizes (and to get the minimum possible number of such sets), then the best option will be to take $\\textstyle{\\left[{\\frac{a_{i}}{x+1}}\\right]}$ sets. If $x\\cdot\\lceil{\\frac{a_{i}}{x+1}}\\rceil\\leq a_{i}$, then such division is possible. If not, then it's impossible to divide $a_{i}$ balls into sets of $x$ and $x + 1$ balls. Time complexity of this solution is $O(n\\cdot{\\sqrt{a_{1}}})$.",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "792",
    "index": "F",
    "title": "Mages and Monsters",
    "statement": "Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.\n\nVova's character can learn new spells during the game. Every spell is characterized by two values $x_{i}$ and $y_{i}$ — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage $x$ and mana cost $y$ for $z$ seconds, then he will deal $x·z$ damage and spend $y·z$ mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.\n\nAlso Vova can fight monsters. Every monster is characterized by two values $t_{j}$ and $h_{j}$ — monster kills Vova's character in $t_{j}$ seconds and has $h_{j}$ health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.\n\nVova's character kills a monster, if he deals $h_{j}$ damage to it in no more than $t_{j}$ seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. \\textbf{If monster's health becomes zero exactly in $t_{j}$ seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight}.\n\nYou have to write a program which can answer two types of queries:\n\n- $1$ $x$ $y$ — Vova's character learns new spell which deals $x$ damage per second and costs $y$ mana per second.\n- $2$ $t$ $h$ — Vova fights the monster which kills his character in $t$ seconds and has $h$ health points.\n\n\\textbf{Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.}\n\nFor every query of second type you have to determine if Vova is able to win the fight with corresponding monster.",
    "tutorial": "Let's represent spells as points on cartesian plane. If we consider three spells $A$, $B$ and $C$ such that $A_{x}  \\le  B_{x}  \\le  C_{x}$ and $B$ is above $AC$ on the cartesian plane or belongs to it, then we don't need to use spell $B$ because we can replace it with a linear combination of spells $A$ and $C$ without any additional mana cost. We can maintain the lower boundary of the convex hull of all points from $1$-type queries and the point $(0, 0)$. Then to process $2$-type query we have to find the intersection of aforementioned lower boundary and the line $x={\\frac{h_{i}}{t_{j}}}$ (our average damage in this fight has to be at least this value). If there is no intersection, then the answer is NO because even with infinite mana Vova's character can't deal that much damage before dying. If there is an intersection, we have to check that it is not higher than the line $y={\\frac{m}{t_{j}}}$ to ensure that we have enough mana to kill the monster in given time. Model solution uses only integral calculations, but it seems that long double precision is enough. Time complexity: $O(q \\cdot log$ $q)$.",
    "tags": [
      "data structures",
      "geometry"
    ],
    "rating": 3100
  },
  {
    "contest_id": "793",
    "index": "A",
    "title": "Oleg and shares",
    "statement": "Oleg the bank client checks share prices every day. There are $n$ share prices he is interested in. Today he observed that each second exactly one of these prices decreases by $k$ rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all $n$ prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?",
    "tutorial": "Let's notice that as prices can only decrease and answer should be minimum possible, all prices should become equal to minimum among given prices. Formally, answer is $\\sum_{i=1}^{n}{\\frac{a_{i}-\\operatorname*{min}a_{1},......a_{r}}{k}}$, if exists no such $i$ that $(a_{i}-\\operatorname*{min}a_{1},\\ldots,a_{n}){\\mathrm{~mod~}}k\\neq0$, otherwise answer is <<$- 1$>>.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "793",
    "index": "B",
    "title": "Igor and his way to work",
    "statement": "Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make \\textbf{no more than two turns} on his way to his office in bank.\n\nBankopolis looks like a grid of $n$ rows and $m$ columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.",
    "tutorial": "This problem has many solutions. The simplest of them is the following. Let's go over all cells where we can get before or after the first turn using simple recursive brute force. For every cell we should check if there exists a path from current cell to Igor's office. We can do it using prefix sums or even naively. Other solutions are dfs over graph of states ${\\mathrm{[row.~column.~current~direction.~number~of~turns~made}}\\,$ or $0$-$1$ bfs over graph of states $(\\mathrm{row},\\;\\mathrm{column},\\;\\mathrm{current}\\;\\;\\mathrm{direction})$.",
    "code": "\"#include <bits/stdc++.h>\\n#define left lolkek\\n \\nusing namespace std;\\n \\nint n, m;\\nvector<int> dx = {-1, 1, 0, 0};\\nvector<int> dy = {0, 0, -1, 1};\\nvector<char> dir = {'L', 'R', 'U', 'D'};\\nvector<vector<int>> grid;\\nvector<vector<int>> left;\\nvector<vector<int>> up;\\nint si = 0;\\nint sj = 0;\\nint ti = 0;\\nint tj = 0;\\n \\nstring path;\\n \\nvoid dfs(int i, int j, int d, int t) {\\n    path += dir[d];\\n    if (t > 1 || i < 1 || i > n || j < 1 || j > m || grid[i][j] == 1) {\\n        path.pop_back();\\n        return;\\n    }\\n    if (j == tj) {\\n        int occ = up[max(ti, i)][j] - up[min(ti, i) - 1][j];\\n        if (occ == 0) {\\n            cout << \\\"YES\\\";\\n            exit(0);\\n        }\\n    } else if (i == ti) {\\n        int occ = left[i][max(tj, j)] - left[i][min(tj, j) - 1];\\n        if (occ == 0) {\\n            cout << \\\"YES\\\";\\n            exit(0);\\n        }\\n    }\\n    for (int d1 = 0; d1 < 4; d1++) {\\n        if (d1 == d || d1 == (d ^ 1)) continue;\\n        dfs(i + dy[d1], j + dx[d1], d1, t + 1);\\n    }\\n    dfs(i + dy[d], j + dx[d], d, t);\\n    path.pop_back();\\n}\\n \\nint main()\\n{\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(0);\\n    cout.tie(0);\\n    cin >> n >> m;\\n    grid.assign(n + 1, vector<int>(m + 1, 0));\\n    string inp;\\n    for (int i = 0; i < n; i++) {\\n        cin >> inp;\\n        for (int j = 0; j < m; j++) {\\n            if (inp[j] == '*') {\\n                grid[i + 1][j + 1] = 1;\\n            }\\n            if (inp[j] == 'S') {\\n                si = i + 1;\\n                sj = j + 1;\\n            } else if (inp[j] == 'T') {\\n                ti = i + 1;\\n                tj = j + 1;\\n            }\\n        }\\n    }\\n    left.assign(n + 1, vector<int>(m + 1, 0));\\n    up.assign(n + 1, vector<int>(m + 1, 0));\\n    for (int i = 1; i <= n; i++) {\\n        for (int j = 1; j <= m; j++) {\\n            left[i][j] = left[i][j - 1] + grid[i][j];\\n            up[i][j] = up[i - 1][j] + grid[i][j];\\n        }\\n    }\\n    for (int d = 0; d < 4; d++) {\\n        dfs(si + dy[d], sj + dx[d], d, 0);\\n    }\\n    cout << \\\"NO\\\";\\n}\\n \"",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "793",
    "index": "C",
    "title": "Mice problem",
    "statement": "Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them.\n\nThe desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$.\n\nIgor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the $i$-th mouse is equal to $(v_{i}^{x}, v_{i}^{y})$, that means that the $x$ coordinate of the mouse increases by $v_{i}^{x}$ units per second, while the $y$ coordinates increases by $v_{i}^{y}$ units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are \\textbf{strictly} inside the mousetrap.\n\nIgor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once.",
    "tutorial": "If at least one point will go on the border of rectangle then answer is <<$- 1$>>. For every point there exists (or doesn't exist) some segment of time when it's inside the rectangle. Then let's seperatly find segment when $x$ belongs to $(x_{1};x_{2})$ and $y$ inside $(y_{1};y_{2})$. Then we can intersect them and get time segment when point is inside the rectangle. To find answer for 1D task we can just check some cases and solve linear equations. There are two ways to do it, we can just do $x_{1}$ += $eps$, $x_{2}$ -= $eps$, $y_{1}$ += $eps$, $y_{2}$ -= $eps$ and then solve task not strictly, or solve strictly using fractions as pairs of integers to maintain good accuracy and using intervals instead of segments. Then let's find intersection of all segments/intervals and if it is not empty print it's left border.",
    "tags": [
      "geometry",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "793",
    "index": "D",
    "title": "Presents in Bankopolis",
    "statement": "Bankopolis is an incredible city in which all the $n$ crossroads are located on a straight line and numbered from $1$ to $n$ along it. On each crossroad there is a bank office.\n\nThe crossroads are connected with $m$ oriented bicycle lanes (the $i$-th lane goes from crossroad $u_{i}$ to crossroad $v_{i}$), the difficulty of each of the lanes is known.\n\nOleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly $k$ offices, in each of them he wants to gift presents to the employees.\n\nThe problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the $i$-th lane passes near the office on the $x$-th crossroad if and only if $min(u_{i}, v_{i}) < x < max(u_{i}, v_{i})))$. Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly $k - 1$ bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.\n\nOleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.",
    "tutorial": "At any time Oleg can make correct move to crossroad from two segments: from crossroad $v$ he can go to crossroads from segment $[a;v - 1]$ or from segment $[v + 1;b]$. After we go from crossroad v to some crossroad u from segment $[a;v - 1]$ there appear two new segments: $[a;u - 1]$ and $[u + 1;v - 1]$. If we go from crossroad v to some crossroad u from segment $[v + 1;b]$, then two new segments will be $[v + 1;u - 1]$ and $[u + 1;b]$. Then you can think about dp solution like $dp[v][a][b][cnt]$, and try each $to$, so $a  \\le  to  \\le  b$ and recalc $dp[to][a][v - 1][cnt + 1]$, $dp[to][v + 1][b][cnt + 1]$. Time complexity: $O((n + m) * n^{2} * k)$. But we can optimize this solution: Notice that we don't need to know $b$ if we want to go to the left and we don't need to know $a$ if we want to go to the right. Then we can make $dp[v][go][cnt]$. If $v < go$ then we have a segment $[v + 1;go]$, else $[go;v - 1]$. Then if $v < go$ we need to recalc $dp[to][v + 1][cnt + 1]$ and $dp[to][go][cnt + 1]$, otherwise $dp[to][go][cnt + 1]$ and $dp[to][v - 1][cnt + 1]$. Time complexity: $O((n + m) * n * k)$.",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "793",
    "index": "E",
    "title": "Problem of offices",
    "statement": "Earlier, when there was no Internet, each bank had a lot of offices all around Bankopolis, and it caused a lot of problems. Namely, each day the bank had to collect cash from all the offices.\n\nOnce Oleg the bank client heard a dialogue of two cash collectors. Each day they traveled through all the departments and offices of the bank following the same route every day. The collectors started from the central department and moved between some departments or between some department and some office using special roads. Finally, they returned to the central department. The total number of departments and offices was $n$, the total number of roads was $n - 1$. In other words, the special roads system was a rooted tree in which the root was the central department, the leaves were offices, the internal vertices were departments. The collectors always followed the same route in which the number of roads was minimum possible, that is $2n - 2$.\n\nOne of the collectors said that the number of offices they visited between their visits to offices $a$ and then $b$ (in the given order) is equal to the number of offices they visited between their visits to offices $b$ and then $a$ (in this order). The other collector said that the number of offices they visited between their visits to offices $c$ and then $d$ (in this order) is equal to the number of offices they visited between their visits to offices $d$ and then $c$ (in this order). The interesting part in this talk was that the shortest path (using special roads only) between any pair of offices among $a$, $b$, $c$ and $d$ \\textbf{passed through the central department}.\n\nGiven the special roads map and the indexes of offices $a$, $b$, $c$ and $d$, determine if the situation described by the collectors was possible, or not.",
    "tutorial": "Formal statement: we have a rooted tree, let it contain $m$ leaves. We can reorder sons of any vertex. We have to reorder tree in such way that while doing Eulerian tour (from vertex we go to it's first son, then to it's second son etc.) between visiting $a$ and $b$ we will visit exactly ${\\frac{m}{2}}-1$ leaves, and same for $c$ and $d$. Let's separately consider case when tree has odd number of leaves - then answer is <<NO>>. Otherwise let's start visiting given leaves from $a$. Then we will visit $c$, then $b$ and then $d$. Amount of visited leaves between visiting $a$ and $b$ depends on how we will order subtrees on path from root to $a$, same for $b$, and also which sons of root we will place between $a$ and $b$ (subtree with $c$ will always be there). $\\operatorname{Let~a~size~of~subtree~be~amount~of~leaves~in~it.}$ After this we can notice that the set of possible distances between $a$ and $b$ is the set of knapsack solutions on following items: sizes of root sons except those that contain $a$, $b$, $c$, $d$, sizes of branching subtrees on path to $a$ and sizes of branching subtrees on path to $b$. With these items we should get knapsack of weight equal to ${\\operatorname*{m}_{2}}-1-\\mathrm{{size~of~root~son,~containing~c}}.$ Same holds for $c$ and $d$, but now items are sizes of root sons except those that contain $a$, $b$, $c$, $d$, sizes of branching subtrees on path to $c$ and sizes of branching subtrees on path to $d$. With these items we should get knapsack of weight equal to $\\textstyle{\\frac{m}{2}}-1-\\mathrm{size\\of\\root\\son,\\,containing\\b}.$ If solution of both knapsacks exists, then answer is <<YES>>, otherwise <<NO>>. We can always order items from both knapsacks in needed way. Exactly, all subtrees that are present only in solution of $a$-$b$ knapsack we place on path between $a$ and $c$, subtrees that are present in solutions of both knapsacks we place between $c$ and $b$, subtrees that are present only in solution of $c$-$d$ knapsack we place between $b$ and $d$, and subtrees that aren't present in any solutions we place between $d$ and $a$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "793",
    "index": "F",
    "title": "Julia the snail",
    "statement": "After hard work Igor decided to have some rest.\n\nHe decided to have a snail. He bought an aquarium with a slippery tree trunk in the center, and put a snail named Julia into the aquarium.\n\nIgor noticed that sometimes Julia wants to climb onto the trunk, but can't do it because the trunk is too slippery. To help the snail Igor put some ropes on the tree, fixing the lower end of the $i$-th rope on the trunk on the height $l_{i}$ above the ground, and the higher end on the height $r_{i}$ above the ground.\n\nFor some reason no two ropes share the same position of the higher end, i.e. all $r_{i}$ are distinct. Now Julia can move down at any place of the trunk, and also move up from the lower end of some rope to its higher end. Igor is proud of his work, and sometimes think about possible movements of the snail. Namely, he is interested in the following questions: «Suppose the snail is on the trunk at height $x$ now. What is the highest position on the trunk the snail can get on if it would never be lower than $x$ or higher than $y$?» Please note that Julia can't move from a rope to the trunk before it reaches the higher end of the rope, and Igor is interested in the highest position \\textbf{on the tree trunk}.\n\nIgor is interested in many questions, and not always can answer them. Help him, write a program that answers these questions.",
    "tutorial": "At first, let's solve this task with $O(r - l)$ time complexity for each query. For each $i$, let's store $back_{i}$ if there is exists a segment [$back_{i}$; $i$] (there's at most one such segment for every $i$). For query [$l$, $r$], let's go from $l$ to $r$, storing rightmost $x$, that is reachable from $l$ (at start it is $l$), then if $(l  \\le  back_{i}  \\le  x)$, then we can add segment [$back_{i}$, $i$] to answer, and say that $x = i$. Now let's apply the following idea. If we found answer for some $p$ $(l  \\le  p  \\le  r)$ answer for query [$l$, $p$], we can find can find answer in $O(r - p)$ time complexity for the whole query [$l$, $r$]. Let's find answers for all $p$ that are divisable by $k$ (for some $k$). For this we have to to calculate additional array $go[i][j]$ that stores answer for segment [$i$, $j * k$]. For this we need to calculate additional array $to[i][j]$ - maximal right border, with left border equal to $i$, that $ \\le $ $k * j$ (we can calc this with two pointers method). To find array $go$, run from right to left, and for each $j$ find answer: $go[i][j] = max(go[k][j]), (i  \\le  k  \\le  to[i][j])$ Now we can notice that because we go from right to left that if element should be relaxed with some element $i$, it will be relaxed also with all elements $p$, so $to[p][j]  \\ge  i$. We can store stack for each $j$, pop from them all elements so their index $ \\le  to[i][j]$, relax with them current value, and then add to stack current value with current index. So we have found array $go$. Then for answering query, if $r - l  \\le  k$ solve naive in $O(r - l)$ else let $p$ be the closest to $r$ number that divides k. $x\\to g o[i][{\\frac{r}{k}}]$, then for $O(r - x)$ solve other query part. Now time complexity is: $O(q*k+n\\ *{\\frac{n}{k}})$ Optimal choice of $k$ is $k\\approx{\\sqrt{n}}$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "793",
    "index": "G",
    "title": "Oleg and chess",
    "statement": "Oleg the bank client solves an interesting chess problem: place on $n × n$ chessboard the maximum number of rooks so that they don't beat each other. Of course, no two rooks can share the same cell.\n\nRemind that a rook standing in the cell $(a, b)$ beats a rook standing in the cell $(x, y)$ if and only if $a = x$ or $b = y$.\n\nUnfortunately (of fortunately?) for Oleg the answer in this problem was always $n$, so the task bored Oleg soon. He decided to make it more difficult by removing some cells from the board. If a cell is deleted, Oleg can't put a rook there, but rooks do beat each other \"through\" deleted cells.\n\nOleg deletes the cells in groups, namely, he repeatedly choose a rectangle with sides parallel to the board sides and deletes all the cells inside the rectangle. Formally, if he chooses a rectangle, lower left cell of which has coordinates $(x_{1}, y_{1})$, and upper right cell of which has coordinates $(x_{2}, y_{2})$, then he deletes all such cells with coordinates $(x, y)$ that $x_{1} ≤ x ≤ x_{2}$ and $y_{1} ≤ y ≤ y_{2}$. It is guaranteed that no cell is deleted twice, i.e. the chosen rectangles do not intersect.\n\nThis version of the problem Oleg can't solve, and his friend Igor is busy at a conference, so he can't help Oleg.\n\nYou are the last hope for Oleg! Help him: given the size of the board and the deleted rectangles find the maximum possible number of rooks that could be placed on the board so that no two rooks beat each other.",
    "tutorial": "Naive solution: Make bipartite graph, there is edge $i  \\rightarrow  j$ only if cell $(i, j)$ is free. Then answer is maximum matching. But this solution time complexity is $O(n^{3})$ To get faster solution, let's cut our field into rectangles that are free of occupied cells. We will go from left to right wth line sweep and store all vertical free spaces to the left of the line in the set. Triples $(y1, y2, x)$ - from $y1$ to $y2$ border of free space is $x$. When we meet rectangle $(x1, y1, x2, y2)$, we should take everything that lies between $y1$ and $y2$ in the set, seperate boundary segments, throw out everything that lies inside, construct new rectangles, and add $(y1, y2, x2 + 1)$ to the set. We will have $O(n)$ rectangles. Then for each rectangle $(x1, y1, x2, y2)$ we need to add for all vertices from left part from $x1$ to $x2$ edges to all verticles of right part from $y1$ to $y2$. Let's build segment tree for all verticles of left part, and another segment tree for all vertices from right part. Then to add rectangle of free cells to our graph, lets split segment $[x1;x2]$ into $log$ vertices in segment tree of left part, and segment $[y1;y2]$ into $log$ in segment tree of right part. Then for all pairs of these vertixes add edge with capacity $ \\infty $. For all vertices of left segment tree add edges from them to their parents with capacity $ \\infty $. For all vertices of right segment tree add edges from their parents to them with capacity $ \\infty $. For all leafs of the left segment tree add edge from source to them with capacity 1. For all leafs of the right segment tree add edge from them to sink with capacity 1. Then max flow in this graph is the answer. Why does this work fast? At first let's try the Edmonds-Karp algorithm. It works in $O(nE)$ in this task, where $E$ - is the number of edges, $E=O(n\\log^{2}n)$. In the given constraints $E$ is bounded by value about several million, because the rectangles do not intersect. This gives complexity about $10^{10}$, and indeed, this algorithm passes, but very close to the time limit. Let's not try Dinic algorithm. We can prove (using a theorem that is known as Karsanov theorem in Russian) that, similar to matching search, the Dinic algorithm has no more than $O({\\sqrt{n\\log n}})$ phases. With the use of the same bound on the edges number, we can get around $10^{9}$ operations that is ok. Also there are alternative solution with sparse table.",
    "tags": [
      "data structures",
      "divide and conquer",
      "flows",
      "graph matchings"
    ],
    "rating": 3400
  },
  {
    "contest_id": "794",
    "index": "A",
    "title": "Bank Robbery",
    "statement": "A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.\n\nOleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the $i$-th safe from the left is called safe $i$. There are $n$ banknotes left in all the safes in total. The $i$-th banknote is in safe $x_{i}$. Oleg is now at safe $a$. There are two security guards, one of which guards the safe $b$ such that $b < a$, i.e. the first guard is to the left of Oleg. The other guard guards the safe $c$ so that $c > a$, i.e. he is to the right of Oleg.\n\nThe two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.",
    "tutorial": "This is a simple implementation problem. We iterate through all banknotes one by one and check if Oleg can take each of them. If a banknote is at position $x$, then Oleg can take it if and only if $b < x < c$. This can be checked in $O(1)$ time. Thus, the total complexity is $O(n)$. Note that the information on the starting position of Oleg is useless here.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<ll,ll> ii;\ntypedef vector<ll> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tint a, b, c; cin>>a>>b>>c;\n\tint n; cin>>n;\n\tint ans=0;\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tint x; cin>>x;\n\t\tif(x>b&&x<c) ans++;\n\t}\n\tcout<<ans<<'\n';\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "794",
    "index": "B",
    "title": "Cutting Carrot",
    "statement": "Igor the analyst has adopted $n$ little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into $n$ pieces of equal area.\n\nFormally, the carrot can be viewed as an isosceles triangle with base length equal to $1$ and height equal to $h$. Igor wants to make $n - 1$ cuts \\textbf{parallel to the base} to cut the carrot into $n$ pieces. He wants to make sure that all $n$ pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area?\n\n\\begin{center}\n{\\small Illustration to the first example.}\n\\end{center}",
    "tutorial": "Let's find the value of $x_{i}$ explicitly. Suppose we make the $i$-th cut and distance $x_{i}$ from the apex. Then, the ratio of similitude of the isosceles triangle with apex equal to the apex of the carrot and the base equal to the $i$-th cut and the whole carrot is $\\scriptstyle{\\frac{\\pi_{h}}{h}}$. Since the area of this smaller isosceles triangle is the sum of areas of the first $i$ pieces, which is $\\textstyle{\\frac{L}{n}}$ of the whole carrot. Thus, $({\\frac{x_{i}}{h}})^{2}={\\frac{i}{n}}$, which is equivalent to $h{\\sqrt{\\frac{i}{n}}}$. Thus, $x_{i}=h{\\sqrt{\\frac{i}{n}}}$ and we can find each $x_{i}$ in $O(1)$ time. The total complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<ll,ll> ii;\ntypedef vector<ll> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tll n, h; cin>>n>>h;\n\tfor(int i=1;i<=n-1;i++)\n\t{\n\t\tcout<<fixed<<setprecision(12)<<sqrt(ld(i)/ld(n))*ld(h);\n\t\tif(i<n-1) cout<<' ';\n\t}\t\n\tcout<<'\n';\n}",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "794",
    "index": "C",
    "title": "Naming Company",
    "statement": "Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.\n\nTo settle this problem, they've decided to play a game. The company name will consist of $n$ letters. Oleg and Igor each have a set of $n$ letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by $n$ question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters $c$ in his set and replace any of the question marks with $c$. Then, a copy of the letter $c$ is removed from his set. The game ends when all the question marks has been replaced by some letter.\n\nFor example, suppose Oleg has the set of letters ${i, o, i}$ and Igor has the set of letters ${i, m, o}$. One possible game is as follows :\n\nInitially, the company name is ???.\n\nOleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is ${i, o}$.\n\nIgor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is ${i, m}$.\n\nFinally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is ${i}$.\n\nIn the end, the company name is oio.\n\nOleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?\n\nA string $s = s_{1}s_{2}...s_{m}$ is called lexicographically smaller than a string $t = t_{1}t_{2}...t_{m}$ (where $s ≠ t$) if $s_{i} < t_{i}$ where $i$ is the smallest index such that $s_{i} ≠ t_{i}$. (so $s_{j} = t_{j}$ for all $j < i$)",
    "tutorial": "First, it is clear that Oleg will place $\\textstyle{\\left[\\!\\!{\\frac{n}{2}}\\right]\\!\\!}\\$ letters and Igor will place $\\textstyle{\\left[{\\frac{n}{2}}\\right]}$ letters. Next, it is clear that Oleg and Igor will both choose their smallest and biggest letters respectively to place in the final string. Thus, we now consider that Oleg places his smallest $\\textstyle{\\left[\\!\\!{\\frac{n}{2}}\\right]\\!\\!}\\$ letters and Igor places his largest $\\textstyle{\\left|{\\frac{n}{2}}\\right|}$ letters. Consider the following greedy strategy. When it's Oleg's turn, he will replace the frontmost question mark with his smallest letter. When it's Igor's turn, he will replace the frontmost question mark with his largest letter. At first glance, you might think that this works. However, there's another case that we haven't considered. Suppose Oleg has the letters ${x, y, z}$ and Igor has the letters ${a, b, c}$. According to our previous strategy, Oleg will place x as the first letter. However, that's not optimal. He can place his letters at the back and force Igor to place the first letter. The reason is because the largest letter of Igor is not larger than the smallest letter of Oleg. Thus, it is beneficial for Oleg to place his letters at the back and force Igor to place his letters in front. So, what exactly will the final string look like? We'll look at the moves one by one. If at some point Oleg's smallest letter is still strictly smaller than Igor's largest letter, then both player must put their smallest (largest if it's Igor) letter as the frontmost letter. Why? Suppose not, then on the next turn the other player will occupy that spot with their best (smallest if Oleg, largest if Igor) letter, and the resulting string will be worse for the current player. This proves that greedy is correct in this case. Now, what if Oleg's smallest letter is not smaller than Igor's largest letter. In this case, both players will want to force the other player to place their own letter at the beginning of the string. It can be proven that in this case, each person will place their current worst (largest if Oleg, smallest if Igor) letter at the back of the string in the optimal strategy. Thus, we can calculate the final string starting from this point and after that reverse this part and combine it with the first part of the string where both players greedily place their best letters in the beginning. Time Complexity : $O(n)$ Many people failed on pretest 6 initially because they didn't consider the second case.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<ll,ll> ii;\ntypedef vector<ll> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tstring ansl;\n\tstring ansr;\n\tstring s,t;\n\tcin>>s>>t;\n\tsort(s.begin(),s.end());\n\tsort(t.begin(),t.end());\n\treverse(t.begin(),t.end());\n\tint n = s.length();\n\tdeque<char> a,b;\n\tfor(int i=0;i<(n+1)/2;i++)\n\t{\n\t\ta.pb(s[i]);\n\t}\n\tfor(int i=0;i<n/2;i++)\n\t{\n\t\tb.pb(t[i]);\n\t}\n\tbool mode=0;\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tif(i&1)\n\t\t{\n\t\t\tif(!a.empty()&&a[0]>=b[0])\n\t\t\t{\n\t\t\t\tmode=1;\n\t\t\t}\n\t\t\tif(mode)\n\t\t\t{\n\t\t\t\tansr+=b.back();\n\t\t\t\tb.pop_back();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tansl+=b[0];\n\t\t\t\tb.pop_front();\n\t\t\t}\n\t\t}\n\t\telse //P1's turn\n\t\t{\n\t\t\tif(!b.empty()&&a[0]>=b[0])\n\t\t\t{\n\t\t\t\tmode=1;\n\t\t\t}\n\t\t\tif(mode)\n\t\t\t{\n\t\t\t\tansr+=a.back();\n\t\t\t\ta.pop_back();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tansl+=a[0];\n\t\t\t\ta.pop_front();\n\t\t\t}\n\t\t}\n\t}\n\treverse(ansr.begin(),ansr.end());\n\tansl+=ansr;\n\tcout<<ansl<<'\n';\n}",
    "tags": [
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "794",
    "index": "D",
    "title": "Labelling Cities",
    "statement": "Oleg the bank client lives in Bankopolia. There are $n$ cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from $1$ to $n$. There are a total of $m$ roads in Bankopolia, the $i$-th road connects cities $u_{i}$ and $v_{i}$. It is guaranteed that from each city it is possible to travel to any other city using some of the roads.\n\nOleg wants to give a label to each city. Suppose the label of city $i$ is equal to $x_{i}$. Then, it must hold that for all pairs of cities $(u, v)$ the condition $|x_{u} - x_{v}| ≤ 1$ holds if and only if there is a road connecting $u$ and $v$.\n\nOleg wonders if such a labeling is possible. Find an example of such labeling if the task is possible and state that it is impossible otherwise.",
    "tutorial": "Add each vertex to its own adjacency list. Now, we claim that if it is possible to label the cities to satisfy the problem conditions, then it is possible to do so so that for every two cities with the same adjacency list, they're labelled with the same number. Indeed, if they have the same adjacency list, they must be neighbours. Thus, the difference between their labels is at most $1$. Suppose we label the first vertex $u$ with number $i$ and the second vertex $v$ with the number $i + 1$. Note that since their adjacency lists are equal, a vertex $x$ is a neighbour of $u$ iff it's a neighbour of $v$. Thus, $u$ and $v$ can't have neighbours with labels $i - 1$ or $i + 2$, or else it will contradict the condition. Thus, all neighbours of $u$ and $v$ have labels $i$ or $i + 1$. Thus, we can safely change the label of the second vertex $v$ to $i$ and the conditions will still hold. Thus, we can sort the set of adjacency lists of each vertex, and then group the vertices with the same adjacency list together. Suppose there are $k$ such groups. For simplicity, we can create a new graph where each group represent a vertex of the new graph. Connect two groups $i$ and $j$ if and only if there exist some vertex in group $i$ that connects to a vertex in group $j$. Note that the graph will have at most $O(m)$ edges. Now, if a vertex has degree $ \\ge  3$, we can't assign a number to that vertex properly, as one of its neighbours will not have a label which have a difference $ \\le  1$ from it. Thus, all vertices in the new graph must have degree $ \\le  2$. Since it's connected, it must be either a cycle or a path. However, it can be easily seen that there is no labelling if it's a cycle. Thus, it must be a path. Now, we can just assign the labels to the graph from one end of the path to the other end by the numbers $1$ to $k$. Finally, the label of a vertex is simply the label of its group. This solution can be implemented in $O(m\\log m+n)$ time.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<ll> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int N = 300000;\n\npair<vi,int> adj[N+2];\nint ans[N+2];\nint lab[N+2];\nint lab2[N+2];\nset<int> adj2[N+2];\nvector<ii> edges;\n\nstruct DSU\n{\n\tint S;\n\t\n\tstruct node\n\t{\n\t\tint p; ll sum;\n\t};\n\tvector<node> dsu;\n\t\n\tDSU(int n)\n\t{\n\t\tS = n;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tnode tmp;\n\t\t\ttmp.p = i; tmp.sum = 0;\n\t\t\tdsu.pb(tmp);\n\t\t}\n\t}\n\t\n\tvoid reset(int n)\n\t{\n\t\tdsu.clear();\n\t\tS = n;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tnode tmp;\n\t\t\ttmp.p = i; tmp.sum = 0;\n\t\t\tdsu.pb(tmp);\n\t\t}\n\t}\n\t\n\tint rt(int u)\n\t{\n\t\tif(dsu[u].p == u) return u;\n\t\tdsu[u].p = rt(dsu[u].p);\n\t\treturn dsu[u].p;\n\t}\n\t\n\tvoid merge(int u, int v)\n\t{\n\t\tu = rt(u); v = rt(v);\n\t\tif(u == v) return ;\n\t\tif(rand()&1) swap(u, v);\n\t\tdsu[v].p = u;\n\t\tdsu[u].sum += dsu[v].sum;\n\t}\n\t\n\tbool sameset(int u, int v)\n\t{\n\t\tif(rt(u) == rt(v)) return true;\n\t\treturn false;\n\t}\n\t\n\tll getstat(int u)\n\t{\n\t\treturn dsu[rt(u)].sum;\n\t}\n};\n\ndeque<int> chain;\n\nvoid dfs(int u, int p, bool type)\n{\n\tif(type) chain.pb(u);\n\telse chain.push_front(u);\n\tint c=0;\n\tfor(sit it = adj2[u].begin(); it != adj2[u].end(); it++)\n\t{\n\t\tint v = (*it);\n\t\tif(v==p) continue;\n\t\tif(p!=-1)\n\t\t{\n\t\t\tdfs(v,u,type);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdfs(v,u,c);\n\t\t\tc++;\n\t\t}\n\t}\n}\n\nint main()\n{\n\t//ios_base::sync_with_stdio(0); cin.tie(0);\n\tint n, m; scanf(\"%d %d\", &n, &m);\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint u, v; scanf(\"%d %d\", &u, &v);\n\t\tu--; v--;\n\t\tadj[u].fi.pb(v);\n\t\tadj[v].fi.pb(u);\n\t\tedges.pb(mp(u,v));\n\t}\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tadj[i].fi.pb(i);\n\t\tadj[i].se = i;\n\t\tsort(adj[i].fi.begin(),adj[i].fi.end());\n\t}\n\tsort(adj,adj+n);\n\tint cnt = 1;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(i==0) \n\t\t{\n\t\t\tlab[adj[i].se] = cnt;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(adj[i].fi==adj[i-1].fi)\n\t\t\t{\n\t\t\t\tlab[adj[i].se]=cnt;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlab[adj[i].se]=++cnt;\n\t\t\t}\n\t\t}\n\t}\n\tif(cnt==1)\n\t{\n\t\tprintf(\"YES\n\");\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tprintf(\"%d \",lab[i]);\n\t\t}\n\t\tprintf(\"\n\");\n\t\treturn 0;\n\t}\n\tDSU dsu(cnt+1);\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint u = edges[i].fi; int v = edges[i].se;\n\t\tif(lab[u]!=lab[v])\n\t\t{\n\t\t\tadj2[lab[u]].insert(lab[v]);\n\t\t\tadj2[lab[v]].insert(lab[u]);\n\t\t\tdsu.merge(lab[u],lab[v]);\n\t\t}\n\t}\n\tbool pos = 1;\n\tfor(int i = 1; i <= cnt; i++)\n\t{\n\t\tif(dsu.rt(i)!=dsu.rt(1))\n\t\t{\n\t\t\tpos=0;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!pos)\n\t{\n\t\tprintf(\"NO\n\");\n\t\treturn 0;\n\t}\n\tint d1 = 0;\n\tfor(int i = 1; i <= cnt; i++)\n\t{\n\t\tif(adj2[i].size()>2)\n\t\t{\n\t\t\tprintf(\"NO\n\");\n\t\t\treturn 0;\n\t\t}\n\t\tif(adj2[i].size()==1) d1++;\n\t\telse assert(adj2[i].size()==2);\n\t}\n\tif(d1==2)\n\t{\n\t\tprintf(\"YES\n\");\n\t\tdfs(1,-1,0);\n\t\tfor(int i = 0; i < chain.size(); i++)\n\t\t{\n\t\t\tlab2[chain[i]] = i+1;\n\t\t}\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tprintf(\"%d \",lab2[lab[i]]);\n\t\t}\n\t\tprintf(\"\n\");\n\t}\n\telse\n\t{\n\t\tprintf(\"NO\n\");\n\t\treturn 0;\n\t}\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "hashing"
    ],
    "rating": 2400
  },
  {
    "contest_id": "794",
    "index": "E",
    "title": "Choosing Carrot",
    "statement": "Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present.\n\nThere are $n$ carrots arranged in a line. The $i$-th carrot from the left has juiciness $a_{i}$. Oleg thinks ZS loves juicy carrots whereas Igor thinks that he hates juicy carrots. Thus, Oleg would like to maximize the juiciness of the carrot they choose while Igor would like to minimize the juiciness of the carrot they choose.\n\nTo settle this issue, they decided to play a game again. Oleg and Igor take turns to play the game. In each turn, a player can choose a carrot from either end of the line, and eat it. The game ends when only one carrot remains. Oleg moves first. The last remaining carrot will be the carrot that they will give their friend, ZS.\n\nOleg is a sneaky bank client. When Igor goes to a restroom, he performs $k$ moves before the start of the game. Each move is the same as above (eat a carrot from either end of the line). After Igor returns, they start the game with Oleg still going first.\n\nOleg wonders: for each $k$ such that $0 ≤ k ≤ n - 1$, what is the juiciness of the carrot they will give to ZS if he makes $k$ extra moves beforehand and both players play optimally?",
    "tutorial": "First, we solve the problem when no one has any extra turns. Suppose we're binary searching the answer. Let all the numbers $ \\ge  x$ be equal to $1$ and all the numbers $< x$ be equal to $0$. Both players can remove one number from one end of the row. The goal of the first player is to let the remaining number be $1$ and the goal of the second player is to leave $0$ in the end. If the first player can win, this means that the answer is at least $x$. Thus, we first try to solve this simpler problem. We claim that the first player wins if and only if : $n$ is even and one of the two middle numbers is $1$. $n$ is odd, the middle digit is $1$ and at least one of the digits beside the middle digit is $1$ (unless $n = 1$, for which first players wins when the only carrot is labelled $1$) Indeed, once we deduce this, we can easily prove this by induction on $n$. The proof is just doing casework and considering all possible moves. Once we have this fact, we realize we don't actually have to binary search the answer. If $n$ is even, the answer is $\\operatorname*{max}(a_{\\frac{n}{2}},a_{\\frac{n}{2}+1})$ while if $n  \\ge  3$ is odd, the answer is $\\operatorname*{min}(a_{{\\frac{n+1}{2}}},\\operatorname*{max}(a_{{\\frac{n-1}{2}}},a_{{\\frac{n+3}{2}}}))$. (If $n = 1$ then the answer is obviously $a_{1}$.) Now, we have to take extra moves into account. Fortunately, it's not very difficult. Having $k$ extra moves just means that Player $1$ can choose to start the game in any subsegment of length $n - k$. Thus, we just have to compute the maximum answer for all subsegments of length $n - k$ for all $0  \\le  k  \\le  n - 1$. With the formula above, you can find all the answers in $O(n)$ time or even $O(n\\log n)$ time if you use sparse table for range maximum query.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<ll,ll> ii;\ntypedef vector<ll> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nint a[300001];\nint ans[300001];\nint b[300001];\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tint n; cin>>n;\n\tint mx=0;\n\tfor(int i=0;i<n;i++) \n\t{\n\t\tcin>>a[i];\n\t\tmx=max(mx,a[i]);\n\t}\n\tfor(int i=0;i<n-2;i++)\n\t{\n\t\tb[i]=min(a[i+1],max(a[i],a[i+2]));\n\t}\n\tans[n-1]=mx;\n\tint odd=n;int even=n;\n\tif(n&1) even=n-1;\n\telse odd=n-1;\n\tmx=0;\n\tfor(int i=even;i>=2;i-=2)\n\t{\n\t\tint l = (i-1)/2; int r=n-i/2;\n\t\tassert(l<=r);\n\t\tmx=max(mx,max(a[l],a[r]));\n\t\tif(i==even)\n\t\t{\n\t\t\tassert(r-l<=2);\n\t\t\tif(r-l==2)\n\t\t\t{\n\t\t\t\tmx=max(mx,a[l+1]);\n\t\t\t}\n\t\t}\n\t\tans[n-i]=mx;\n\t}\n\tmx=0;\n\tfor(int i=odd;i>=3;i-=2)\n\t{\n\t\tint l = i/2-1; int r=n-2-i/2;\n\t\tassert(l<=r);\n\t\tif(i==odd) assert(r-l<=1);\n\t\tmx=max(mx,max(b[l],b[r]));\n\t\tans[n-i]=mx;\n\t}\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tcout<<ans[i];\n\t\tif(i<n-1) cout<<' ';\n\t}\n\tcout<<'\n';\n}",
    "tags": [
      "games",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "794",
    "index": "F",
    "title": "Leha and security system",
    "statement": "Bankopolis, the city you already know, finally got a new bank opened! Unfortunately, its security system is not yet working fine... Meanwhile hacker Leha arrived in Bankopolis and decided to test the system!\n\nBank has $n$ cells for clients' money. A sequence from $n$ numbers $a_{1}, a_{2}, ..., a_{n}$ describes the amount of money each client has. Leha wants to make requests to the database of the bank, finding out the total amount of money on some subsegments of the sequence and changing values of the sequence on some subsegments. Using a bug in the system, Leha can requests two types of queries to the database:\n\n- 1 l r x y denoting that Leha changes each digit $x$ to digit $y$ in each element of sequence $a_{i}$, for which $l ≤ i ≤ r$ is holds. For example, if we change in number $11984381$ digit $8$ to $4$, we get $11944341$. It's worth noting that Leha, in order to stay in the shadow, never changes digits in the database to $0$, i.e. $y ≠ 0$.\n- 2 l r denoting that Leha asks to calculate and print the sum of such elements of sequence $a_{i}$, for which $l ≤ i ≤ r$ holds.\n\nAs Leha is a white-hat hacker, he don't want to test this vulnerability on a real database. You are to write a similar database for Leha to test.",
    "tutorial": "We use a segment tree to solve this problem. For each node, it is sufficient to store two arrays : $sum[i]$, denoting the total contribution of the digit $i$ in the current segment (if a digit is in the tens digit then it contributes $10$ to the sum and etc...), and also $nxt[i]$, what all the digits $i$ in the current segment are changed to. Maintaining these arrays is quite straightforward with lazy propogation. When we push an update down a node, we need to update the nxt array of the children. First, we change $st[id].nxt[u]$ to $v$, where the current update is to change all digits $u$ to $v$. Then, we change $st[id * 2].nxt[i]$ to $st[id].nxt[st[id * 2].nxt[i]]$, where $st[id]$ is the current node and $st[id * 2]$ is one of the children nodes. (Do the same for the right children). You can see the code if you need more details. Finally, update the sum array of the current segment. The total complexity of the code is $O(q*10*\\log n)$, which is fast enough.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<ll,ll> ii;\ntypedef vector<int> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\nconst int N = 100000;\nint a[N+1][10];\n\nstruct node\n{\n\tint nxt[10];\n\tll sum[10];\n};\n\nnode st[N*4+1];\n\nvoid combine(int id)\n{\n\tfor(int i = 0; i < 10; i++)\n\t{\n\t\tst[id].sum[i]=st[id*2].sum[i]+st[id*2+1].sum[i];\n\t}\n}\n\nvoid build(int id, int l, int r)\n{\n\tif(r-l<2)\n\t{\n\t\tfor(int i = 0; i < 10; i++) st[id].sum[i]=a[l][i];\n\t\tfor(int i = 0; i < 10; i++)\n\t\t{\n\t\t\tst[id].nxt[i] = i;\n\t\t}\n\t\treturn ;\n\t}\n\tfor(int i = 0; i < 10; i++)\n\t{\n\t\tst[id].nxt[i] = i;\n\t}\n\tint mid=(l+r)>>1;\n\tbuild(id*2,l,mid);\n\tbuild(id*2+1,mid,r);\n\tcombine(id);\n}\n\nint nxt1[10];\nint nxt2[10];\nll sum[10];\n\nvoid push(int id, int l, int r)\n{\n\tmemset(sum,0,sizeof(sum));\n\tif(r-l>=2)\n\t{\n\t\tfor(int i = 0; i < 10; i++)\n\t\t{\n\t\t\tnxt1[i] = st[id].nxt[st[id*2].nxt[i]];\n\t\t\tnxt2[i] = st[id].nxt[st[id*2+1].nxt[i]];\n\t\t}\n\t\tfor(int i=0;i<10;i++)\n\t\t{\n\t\t\tst[id*2].nxt[i]=nxt1[i];\n\t\t\tst[id*2+1].nxt[i]=nxt2[i];\n\t\t}\n\t}\n\tfor(int i=0;i<10;i++)\n\t{\n\t\tsum[st[id].nxt[i]]+=st[id].sum[i];\n\t}\n\tfor(int i=0;i<10;i++) \n\t{\n\t\tst[id].sum[i]=sum[i];\n\t\tst[id].nxt[i]=i;\n\t}\n}\n\nvoid update(int id, int l, int r, int ql, int qr, int u, int v)\n{\n\tpush(id,l,r);\n\tif(ql>=r||l>=qr) return ;\n\tif(ql<=l&&r<=qr)\n\t{\n\t\tst[id].nxt[u]=v;\n\t\tpush(id,l,r);\n\t\treturn ;\n\t}\n\tint mid=(l+r)>>1;\n\tupdate(id*2,l,mid,ql,qr,u,v);\n\tupdate(id*2+1,mid,r,ql,qr,u,v);\n\tcombine(id);\n}\n\nll query(int id, int l, int r, int ql, int qr)\n{\n\tpush(id,l,r);\n\tif(ql>=r||l>=qr) return 0;\n\tif(ql<=l&&r<=qr)\n\t{\n\t\tll sum=0;\n\t\tfor(int i=1;i<10;i++)\n\t\t{\n\t\t\tsum+=ll(i)*st[id].sum[i];\n\t\t}\n\t\treturn sum;\n\t}\n\tint mid=(l+r)>>1;\n\treturn (query(id*2,l,mid,ql,qr)+query(id*2+1,mid,r,ql,qr));\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tint n, q; cin>>n>>q;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint x; cin>>x;\n\t\tint cur=1;\n\t\tfor(int j = 0; j < 9; j++)\n\t\t{\n\t\t\ta[i][x%10] += cur;\n\t\t\tx/=10;\n\t\t\tcur*=10;\n\t\t\tif(x==0) break;\n\t\t}\n\t}\n\tbuild(1,0,n);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tint type;\n\t\tcin>>type;\n\t\tif(type==1)\n\t\t{\n\t\t\tint l,r,u,v;\n\t\t\tcin>>l>>r>>u>>v;\n\t\t\tl--; r--;\n\t\t\tupdate(1,0,n,l,r+1,u,v);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint l,r; cin>>l>>r;\n\t\t\tl--; r--;\n\t\t\tll sum = query(1,0,n,l,r+1);\n\t\t\tcout<<sum<<'\n';\n\t\t}\n\t}\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2800
  },
  {
    "contest_id": "794",
    "index": "G",
    "title": "Replace All",
    "statement": "Igor the analyst is at work. He learned about a feature in his text editor called \"Replace All\". Igor is too bored at work and thus he came up with the following problem:\n\nGiven two strings $x$ and $y$ which consist of the English letters 'A' and 'B' only, a pair of strings $(s, t)$ is called \\underline{good} if:\n\n- $s$ and $t$ consist of the characters '0' and '1' only.\n- $1 ≤ |s|, |t| ≤ n$, where $|z|$ denotes the length of string $z$, and $n$ is a fixed positive integer.\n- If we replace all occurrences of 'A' in $x$ and $y$ with the string $s$, and replace all occurrences of 'B' in $x$ and $y$ with the string $t$, then the two obtained from $x$ and $y$ strings are equal.\n\nFor example, if $x = $AAB, $y = $BB and $n = 4$, then (01, 0101) is one of good pairs of strings, because both obtained after replacing strings are \"01010101\".\n\nThe \\underline{flexibility} of a pair of strings $x$ and $y$ is the number of pairs of good strings $(s, t)$. The pairs are ordered, for example the pairs $($0, 1$)$ and $($1, 0$)$ are different.\n\nYou're given two strings $c$ and $d$. They consist of characters 'A', 'B' and '?' only. Find the sum of flexibilities of all possible pairs of strings $(c', d')$ such that $c'$ and $d'$ can be obtained from $c$ and $d$ respectively by replacing the question marks with either 'A' or 'B', modulo $10^{9} + 7$.",
    "tutorial": "First, we solve the problem when there're no question marks, i.e. we find a way to calculate the number of good pairs of strings fast for a constant pair of strings $A$ and $B$. Call a pair of strings $(S, T)$ where $|S|  \\le  |T|$ coprime if $S = T$ or $S$ is a prefix of $T$, and if $T = S + X$, then $(X, S)$ is also coprime. $(S, T)$ where $|S| > |T|$ is coprime iff $(T, S)$ is coprime. If $A = B$, then all possible strings work. Thus, we assume $A  \\neq  B$ from now on. We remove the longest common prefix of $A$ and $B$. Thus, we can assume $A[0]  \\neq  B[0]$. Thus, either $S$ is a prefix of $T$ or $T$ is a prefix of $S$. WLOG, $S$ is a prefix of $T$. Let $T = S + X$. Now, $A$ and $B$ consists of only $S$ and $X$. Using this, we can prove by induction on $|S| + |T|$ that $S$ and $T$ must be coprime. One important property of coprime strings is that $S + T = T + S$ holds. (again induction works here) Now, since the strings $S$ and $T$ needs to be coprime, we have $S + T = T + S$. This allows us to swap any neighbouring Ss and Ts (or 'A's and 'B's) in $A$ and $B$, as the resulting strings will still be equal. Thus, swapping repeatedly allows us to sort the strings A and B. (the 'A's appear in front and 'B's appear at the back) Let $x_{A}, x_{B}, y_{A}, y_{B}$ denote the number of As and Bs in the first string and second string respectively. If $(x_{A}, x_{B}) > (y_{A}, y_{B})$, then the answer is $0$. We'll handle the case $(x_{A}, x_{B}) = (y_{A}, y_{B})$ later. Now, assume $x_{A} > y_{A}, x_{B} < y_{B}$. Thus, we have to solve the equation $(x_{A} - y_{A})$ copies of $S$ = $(y_{B} - x_{B})$ copies of $T$. Now, let $x = x_{A} - y_{A}, y = y_{B} - x_{B}$. If $x = y$, then the solution is $S = T$. Otherwise, assume $x > y$. Then, $|S| < |T|$. So, by comparing, we again have $T = S + X$, for some nonempty binary string $X$. Note that $S$ and $X$ must be coprime too, so we can sort the second string as well. We cancel off the Ss on both sides to get $(x - y)S = yX$. Thus, this means that if $(S, T)$ is a solution for $(x, y)$, then $(S, X)$ is a solution for $(x - y, y)$. Note that repeating this process will eventually lead us to $(1, 1)$. (this process is similar to Euclidean Algorithm) The answer for $(1, 1)$ is the number of solutions to $S = T$. Let's denote the solution here as $X$. Doing some backtracking, we realize that the answer for $(x, y)$ is equal to (X....X ($y$ times), X...X ($x$ times)). Note that we still have the condition $|S|, |T|  \\le  N$, so we can translate this to an appropriate condition on the length of $X$ and the answer is simply the number of binary strings of length not exceeding the maximum possible length of $X$. The only case that remains is that $(x_{A}, x_{B}) = (y_{A}, y_{B})$. In this case, any pair of coprime strings $S$ and $T$ will work. Thus, our task reduces to calculating the number of coprime pair of strings with length not exceeding $N$. We claim that the number of coprime pair of strings $(S, T)$ with $|S| = p, |T| = q$ is $2^{\\mathrm{Ned}(p,q)}$. If $p = q$ the claim is obviously true. Otherwise, we can induct on $p + q$ agin. If $q > p$, we can write $T = S + X$ and then the number of coprime pairs of $(S, T)$ is equal to the number of coprime pairs of $(S, X)$, which by induction is equal to $2^{\\mathrm{gcd}(p,q-p)}=2^{\\mathrm{gcd}(p,q)}$. This proves the claim. Thus, we just need to compute the sum of $2^{\\mathrm{Ned}(p,q)}$ for all $1  \\le  p, q  \\le  N$. Indeed, since $N  \\le  3 \\cdot 10^{5}$, it is enough to count the number of pairs $(p, q)$ with $gcd = g$ for all $g$. However, this is quite easy. Let $cnt[i]$ denote the number of pairs $(p, q)$ such that $p$ and $q$ are both divisible by $i$. Let $ans[i]$ denote the number of pairs $(p, q)$ with $gcd = i$. Then, $a n s[i]=c n t[i]+\\sum_{i=2}^{\\frac{N}{i}}\\bigl(\\mu(j)\\cdot c n t[i\\cdot j]\\bigr)$. Thus, this can be computed in $O(n\\log n)$. Now, we need to find out how to calculate the sum of all these values on two strings $X$ and $Y$ with question marks. Handle the case when the two strings become equal separately. Let's first make a summary of the number of good pairs of strings for constant strings $A$ and $B$. In fact, note that the formulaes above only depends on $(d_{A}, d_{B})$, the difference between the number of As in $A$ and $B$, and the difference between the number of Bs in $A$ and $B$ (note that $d_{A}, d_{B}$ can be negative) If $d_{A} = d_{B} = 0$, then the answer is the sum of $2^{\\mathrm{Ned}(p,q)}$ for all $1  \\le  p, q  \\le  N$, which as we have just saw can be precomputed in time. Otherwise, if $d_{A}, d_{B}  \\ge  0$ or $d_{A}, d_{B}  \\le  0$, then there are no good pair of strings. Finally, in other cases, let $p = |d_{A}|, q = |d_{B}|$. Then, the answer is $2^{\\frac{N}{m a x(p,q)}}+1\\leq2$. This also means that we can compute the answer if we know $d_{A}$ and $d_{B}$ very fast. (worst case is $O(\\log N)$) Now, suppose in the strings $X$ and $Y$, we have $a$ and $b$ question marks respectively. Additionally, suppose the current difference between the number of As and Bs of these strings is $(p, q)$. If we choose $x$ and $y$ of the question marks from $X$ and $Y$ to be replaced with As, then the difference between As and Bs in the strings become $(p + x - y, q + (a - b) - (x - y))$. Let's denote $q$ as $q + a - b$ for simplicity. Thus, the difference is now written as $(p + (x - y), q - (x - y))$. The values of $x$ and $y$ can be any integer in the range $[0, a]$ and $[0, b]$ respectively. Suppose for all $- b  \\le  d  \\le  a$, we know how many ways to assign the question marks have $x - y = d$. Then, we can iterate through all the $d$s one by one and compute the answer fast for each $d$. Thus, the final hurdle is to calculate the number of ways to obtain $x - y = d$ for all possible $d$ so that $0  \\le  x  \\le  a, 0  \\le  y  \\le  b$. This is just the sum of $\\left(\\stackrel{a}{x}\\right)\\cdot\\left(\\stackrel{b}{x}\\right)\\ =\\left(\\stackrel{a}{x}\\right)\\cdot\\left(\\stackrel{b}{b-v}\\right)\\ =\\left(\\stackrel{a}{x}\\right)\\cdot\\left(\\stackrel{b}{b+d-x}\\right)$ for all $0  \\le  x  \\le  a$. However, this is equal to $\\textstyle{\\binom{n+b}{b+d}}$, as the number of ways to choose $b + d$ objects from $a + b$ objects is the same as the sum of the product of the number of ways to choose $x$ objects from the first $a$ objects and the number of ways to choose $b + d - x$ objects from the first $b$ objects for all $0  \\le  a  \\le  x$. Thus, this value can be computed in $O(1)$ with precomputed factorials and inverse factorials (or you can maintain this value when we iterate through all $d$). Finally, don't forget to take care of the cases where it is possible for both strings to be equal. The time complexity of the solution is $O(n\\log n+\\left|S\\right|+\\left|T\\right|)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n\ntypedef long long ll;\ntypedef pair<ll,ll> ii;\ntypedef vector<ll> vi;\ntypedef long double ld; \ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;\ntypedef set<int>::iterator sit;\ntypedef map<int,int>::iterator mit;\ntypedef vector<int>::iterator vit;\n\nconst int MOD = 1e9 + 7;\n\nstruct NumberTheory\n{\n\tvector<ll> primes;\n\tvector<bool> prime;\n\tvector<ll> totient;\n\tvector<ll> sumdiv;\n\tvector<ll> bigdiv;\n\tvoid Sieve(ll n)\n\t{\n\t\tprime.assign(n+1, 1);\n\t\tprime[1] = false;\n\t\tfor(ll i = 2; i <= n; i++)\n\t\t{\n\t\t\tif(prime[i])\n\t\t\t{\n\t\t\t\tprimes.pb(i);\n\t\t\t\tfor(ll j = i*2; j <= n; j += i)\n\t\t\t\t{\n\t\t\t\t\tprime[j] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tll phi(ll x)\n\t{\n\t\tmap<ll,ll> pf;\n\t\tll num = 1; ll num2 = x;\n\t\tfor(ll i = 0; primes[i]*primes[i] <= x; i++)\n\t\t{\n\t\t\tif(x%primes[i]==0)\n\t\t\t{\n\t\t\t\tnum2/=primes[i];\n\t\t\t\tnum*=(primes[i]-1);\n\t\t\t}\n\t\t\twhile(x%primes[i]==0)\n\t\t\t{\n\t\t\t\tx/=primes[i];\n\t\t\t\tpf[primes[i]]++;\n\t\t\t}\n\t\t}\n\t\tif(x>1)\n\t\t{\n\t\t\tpf[x]++; num2/=x; num*=(x-1);\n\t\t}\n\t\tx = 1;\n\t\tnum*=num2;\n\t\treturn num;\n\t}\n\t\n\tbool isprime(ll x)\n\t{\n\t\tif(x==1) return false;\n\t\tfor(ll i = 0; primes[i]*primes[i] <= x; i++)\n\t\t{\n\t\t\tif(x%primes[i]==0) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid SievePhi(ll n)\n\t{\n\t\ttotient.resize(n+1);\n\t\tfor (int i = 1; i <= n; ++i) totient[i] = i;\n\t\tfor (int i = 2; i <= n; ++i)\n\t\t{\n\t\t\tif (totient[i] == i)\n\t\t\t{\n\t\t\t\tfor (int j = i; j <= n; j += i)\n\t\t\t\t{\n\t\t\t\t\ttotient[j] -= totient[j] / i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid SieveSumDiv(ll n)\n\t{\n\t\tsumdiv.resize(n+1);\n\t\tfor(int i = 1; i <= n; ++i)\n\t\t{\n\t\t\tfor(int j = i; j <= n; j += i)\n\t\t\t{\n\t\t\t\tsumdiv[j] += i;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tll getPhi(ll n)\n\t{\n\t\treturn totient[n];\n\t}\n\t\n\tll getSumDiv(ll n)\n\t{\n\t\treturn sumdiv[n];\n\t}\n\t\n\tll modpow(ll a, ll b, ll mod)\n\t{\n\t\tll r = 1;\n\t\tif(b < 0) b += mod*100000LL;\n\t\twhile(b)\n\t\t{\n\t\t\tif(b&1) r = (r*a)%mod;\n\t\t\ta = (a*a)%mod;\n\t\t\tb>>=1;\n\t\t}\n\t\treturn r;\n\t}\n\t\n\tll inv(ll a, ll mod)\n\t{\n\t\treturn modpow(a, mod - 2, mod);\n\t}\n\t\n\tll invgeneral(ll a, ll mod)\n\t{\n\t\tll ph = phi(mod);\n\t\tph--;\n\t\treturn modpow(a, ph, mod);\n\t}\n\t\n\tvoid getpf(vector<ii>& pf, ll n)\n\t{\n\t\tfor(ll i = 0; primes[i]*primes[i] <= n; i++)\n\t\t{\n\t\t\tint cnt = 0;\n\t\t\twhile(n%primes[i]==0)\n\t\t\t{\n\t\t\t\tn/=primes[i]; cnt++;\n\t\t\t}\n\t\t\tif(cnt>0) pf.pb(ii(primes[i], cnt));\n\t\t}\n\t\tif(n>1)\n\t\t{\n\t\t\tpf.pb(ii(n, 1));\n\t\t}\n\t}\n\n\t//ll op;\n\tvoid getDiv(vector<ll>& div, vector<ii>& pf, ll n, int i)\n\t{\n\t\t//op++;\n\t\tll x, k;\n\t\tif(i >= pf.size()) return ;\n\t\tx = n;\n\t\tfor(k = 0; k <= pf[i].se; k++)\n\t\t{\n\t\t\tif(i==int(pf.size())-1) div.pb(x);\n\t\t\tgetDiv(div, pf, x, i + 1);\n\t\t\tx *= pf[i].fi;\n\t\t}\n\t}\n};\n\nNumberTheory nt;\n\nll modpow(ll a, ll b)\n{\n\tll r = 1;\n\twhile(b)\n\t{\n\t\tif(b&1) r=(r*a)%MOD;\n\t\ta=(a*a)%MOD;\n\t\tb>>=1;\n\t}\n\treturn r;\n}\n\nll inv(ll a)\n{\n\treturn modpow(a,MOD-2);\n}\n\nll n;\nll cnt[300001];\nll mob[300001];\n\nll mobius(ll x)\n{\n\tint cc = 0;\n\tfor(int i=0;nt.primes[i]*nt.primes[i]<=x;i++)\n\t{\n\t\tint z=0;\n\t\twhile(x%nt.primes[i]==0)\n\t\t{\n\t\t\tz++;\n\t\t\tx/=nt.primes[i];\n\t\t}\n\t\tif(z>=2) return 0;\n\t\tif(z>0) cc++;\n\t}\n\tif(x>1) cc++;\n\tif(cc&1) return -1;\n\telse return 1;\n}\n\nll solve(ll x, ll y)\n{\n\tif(x==0&&y==0)\n\t{\n\t\tfor(int i=1;i<=n;i++)\n\t\t{\n\t\t\tcnt[i]=ll(n/i)*ll(n/i);\n\t\t}\n\t\tfor(int i=1;i<=n;i++)\n\t\t{\n\t\t\tfor(int j=2*i;j<=n;j+=i)\n\t\t\t{\n\t\t\t\tcnt[i]+=mob[j/i]*cnt[j];\n\t\t\t}\n\t\t}\t\n\t\tll ans = 0;\n\t\tll cur = 2;\n\t\tfor(int i=1;i<=n;i++)\n\t\t{\n\t\t\tcnt[i]%=MOD;\n\t\t\tif(cnt[i]<0) cnt[i]+=MOD;\n\t\t\t//cerr<<i<<' '<<cnt[i]<<'\n';\n\t\t\tans=(ans+(cur*cnt[i])%MOD)%MOD;\n\t\t\tif(ans<0) ans+=MOD;\n\t\t\tcur=(cur*2)%MOD;\n\t\t\tif(cur<0) cur+=MOD;\n\t\t}\n\t\treturn ans;\n\t}\n\telse if(x>=0&&y>=0)\n\t{\n\t\treturn 0;\n\t}\n\telse if(x<=0&&y<=0)\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tx=abs(x); y=abs(y);\n\t\tll g = __gcd(x,y);\n\t\tx/=g; y/=g;\n\t\tll k = n/max(x,y);\n\t\tll ans = modpow(2,k+1)+MOD-2;\n\t\twhile(ans>=MOD) ans-=MOD;\n\t\treturn ans;\n\t}\n}\n\nll fact[600001];\nll ifact[600001];\nll inverse[600001];\n\nll choose(ll n, ll r)\n{\n\tif(r==0) return 1;\n\tll ans = fact[n];\n\tans=(ans*ifact[r])%MOD;\n\tans=(ans*ifact[n-r])%MOD;\n\tif(ans<0) ans+=MOD;\n\treturn ans;\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\tstring s, t;\n\tcin>>s>>t;\n\tcin>>n;\n\tfact[0]=1; ifact[0]=1;\n\tfor(int i=1;i<=600000;i++)\n\t{\n\t\tfact[i]=(fact[i-1]*i)%MOD;\n\t\tif(fact[i]<0) fact[i]+=MOD;\n\t\tifact[i]=inv(fact[i]);\n\t\tinverse[i]=inv(i);\n\t}\n\tnt.Sieve(300001);\n\tfor(int i=2;i<=n;i++)\n\t{\n\t\tmob[i]=mobius(i);\n\t}\n\tll sa, sb, sc; //sa = # of As in s, sb = # of Bs in s, sc = # of ?s in s\n\tll ta, tb, tc;\n\tsa=sb=sc=ta=tb=tc=0;\n\tll same = 1; //number of ways to fill in ?s such that |S| = |T|\n\tif(s.length()!=t.length()) same=0;\n\telse\n\t{\n\t\tfor(int i=0;i<s.length();i++)\n\t\t{\n\t\t\tif(s[i]=='?'&&t[i]=='?') same=(same*2)%MOD;\n\t\t\telse if(s[i]=='?'||t[i]=='?')\n\t\t\t{\n\t\t\t\t\n\t\t\t}\n\t\t\telse if(s[i]==t[i])\n\t\t\t{\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsame=0;\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=0;i<s.length();i++)\n\t{\n\t\tif(s[i]=='A') sa++;\n\t\telse if(s[i]=='B') sb++;\n\t\telse sc++;\n\t}\n\tfor(int i=0;i<t.length();i++)\n\t{\n\t\tif(t[i]=='A') ta++;\n\t\telse if(t[i]=='B') tb++;\n\t\telse tc++;\n\t}\n\tll ans = 0;\n\tll c = 1;\n\tint cntt=0;\n\tfor(ll i = sa - ta - tc; i <= sa - ta + sc; i++)\n\t{\n\t\tif(i==0)\n\t\t{\n\t\t\tll cc = (c-same)%MOD;\n\t\t\tif(cc<0) cc+=MOD;\n\t\t\tans=(ans+(cc*solve(i,sa+sb+sc-ta-tb-tc-i))%MOD)%MOD;\n\t\t\tll tmp = modpow(2,n+1)+MOD-2;\n\t\t\twhile(tmp>=MOD) tmp-=MOD;\n\t\t\ttmp=(tmp*tmp)%MOD;\n\t\t\tans=(ans+(same*tmp)%MOD)%MOD;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tans=(ans+(c*solve(i,sa+sb+sc-ta-tb-tc-i))%MOD)%MOD;\n\t\t}\n\t\tif(ans<0) ans+=MOD;\n\t\tc=(c*inverse[cntt+1])%MOD;\n\t\tc=(c*(sc+tc-cntt))%MOD;\n\t\tif(c<0) c+=MOD;\n\t\tcntt++;\n\t}\n\tcout<<ans<<'\n';\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "796",
    "index": "A",
    "title": "Buying A House",
    "statement": "Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.\n\nThe girl lives in house $m$ of a village. There are $n$ houses in that village, lining in a straight line from left to right: house $1$, house $2$, ..., house $n$. The village is also well-structured: house $i$ and house $i + 1$ ($1 ≤ i < n$) are exactly $10$ meters away. In this village, some houses are occupied, and some are not. Indeed, unoccupied houses can be purchased.\n\nYou will be given $n$ integers $a_{1}, a_{2}, ..., a_{n}$ that denote the availability and the prices of the houses. If house $i$ is occupied, and therefore cannot be bought, then $a_{i}$ equals $0$. Otherwise, house $i$ can be bought, and $a_{i}$ represents the money required to buy it, in dollars.\n\nAs Zane has only $k$ dollars to spare, it becomes a challenge for him to choose the house to purchase, so that he could live as near as possible to his crush. Help Zane determine the minimum distance from his crush's house to some house he can afford, to help him succeed in his love.",
    "tutorial": "This is a simple implementation problem. Let the $ans$ be infinity initially. Iterate through the houses. Suppose we are considering house $i$, update the $ans$ if and only if 1) $a_{i}  \\neq  0$, 2) $a_{i}  \\le  k$, and 3) $|i - m|$ < $ans$. The answer is $10 * ans$. This solution runs in $O(n)$.",
    "code": "\"#include <stdio.h>\\n\\nint min(int a, int b){ return a < b ? a : b; }\\nint abs(int x){ return x < 0 ? -x : x; }\\n\\nint main(){\\n    int n, m, k;\\n    scanf(\\\"%d%d%d\\\", &n, &m, &k);\\n    int res = 1e9;\\n    for(int i=1; i<=n; i++){\\n        int a;\\n        scanf(\\\"%d\\\", &a);\\n        if(a != 0 && a <= k) res = min(res, abs(i-m));\\n    }\\n    printf(\\\"%d\\\", 10*res);\\n    return 0;\\n}\"",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "796",
    "index": "B",
    "title": "Find The Bone",
    "statement": "Zane the wizard is going to perform a magic show shuffling the cups.\n\nThere are $n$ cups, numbered from $1$ to $n$, placed along the $x$-axis on a table that has $m$ holes on it. More precisely, cup $i$ is on the table at the position $x = i$.\n\nThe problematic bone is initially at the position $x = 1$. Zane will confuse the audience by swapping the cups $k$ times, the $i$-th time of which involves the cups at the positions $x = u_{i}$ and $x = v_{i}$. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.\n\nDo not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at $x = 4$ and the one at $x = 6$, they will not be at the position $x = 5$ at any moment during the operation.\n\nZane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.",
    "tutorial": "This is another implementation problem. Let's create an array $a$ of length $n$ (with initial values set to $0$), and set $a_{i}$ = $1$ only for the positions $x = i$ where there is a hole. If there is a hole at $x$ $=$ $1$, obviously, the answer is $1$, because the ball must fall onto the ground before any operation is applied. Otherwise, consider each swapping operation chronologically (from the first to the last). While doing so, we will also maintain a variable $pos$, the position where the ball is. Let the involving cup positions be $u$ and $v$. There are three cases to consider: 1) If $pos$ is equal to $u$, set $pos$ $=$ $v$. 2) If $pos$ is equal to $v$, set $pos$ $=$ $u$. 3) Otherwise, skip the operation. Make sure to stop considering any more operations if $a_{pos}$ equals $1$. After this procedure, $pos$ will be the final answer. This solution runs in $O(k)$.",
    "code": "\"#include <stdio.h>\\n\\nint isHole[1000005];\\n\\nint main(){\\n    int n, m, k;\\n    scanf(\\\"%d%d%d\\\", &n, &m, &k);\\n    for(int i=0; i<m; i++){\\n        int h;\\n        scanf(\\\"%d\\\", &h);\\n        isHole[h] = 1;\\n    }\\n    int pos = 1;\\n    for(int i=0; i<k; i++){\\n        int u, v;\\n        scanf(\\\"%d%d\\\", &u, &v);\\n        if(u == pos && (!isHole[u])) pos = v;\\n        else if(v == pos && (!isHole[v])) pos = u;\\n    }\\n    printf(\\\"%d\\\", pos);\\n    return 0;\\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "796",
    "index": "C",
    "title": "Bank Hacking",
    "statement": "Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks.\n\nThere are $n$ banks, numbered from $1$ to $n$. There are also $n - 1$ wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank $i$ has initial strength $a_{i}$.\n\nLet us define some keywords before we proceed. Bank $i$ and bank $j$ are neighboring if and only if there exists a wire directly connecting them. Bank $i$ and bank $j$ are semi-neighboring if and only if there exists an \\textbf{online} bank $k$ such that bank $i$ and bank $k$ are neighboring and bank $k$ and bank $j$ are neighboring.\n\nWhen a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by $1$.\n\nTo start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank $x$ if and only if all these conditions are met:\n\n- Bank $x$ is online. That is, bank $x$ is not hacked yet.\n- Bank $x$ is neighboring to some offline bank.\n- The strength of bank $x$ is less than or equal to the strength of Inzane's computer.\n\nDetermine the minimum strength of the computer Inzane needs to hack all the banks.",
    "tutorial": "First, note that the input graph is a tree. Let $m$ be the greatest value of $a_{i}$ (that is, $max(a_{1}, a_{2}, ..., a_{n})$). Observe that the answer can be $m$, $m + 1$, or $m + 2$ only. Why? It is because each bank's strength can be increased at most twice, once by a neighboring bank, and once by a semi-neighboring bank. So the strength required to hack bank $i$ is at most $a_{i} + 2$, regardless of the sequence of banks you choose to hack. Now, suppose $u$ is the first bank we would hack first. We would need a computer with strength at least $a_{u}$ to hack it. Let the neighboring banks of $u$ be $v_{1}, v_{2}, ..., v_{k}$. We would need a computer with strength at least $a_{vi} + 1$ to hack those banks. And for each bank $x$ not yet hacked, we can hack them with a computer with strength at least $a_{x} + 2$. For simplicity, add $2$ to all the banks' strengths. Let's maintain a map data structure to keep track of number of times some value of strength occurs. Again, suppose we would start by hacking bank $u$. Now, we would need a computer with strength at least $a_{u} - 2$ to hack it. For the neighboring banks $v$, it would be $a_{v} - 1$. For other banks $x$, it would be $a_{x}$. For a fixed bank $u$, you can iterate through its neighboring banks, and update the map data structure accordingly. Keep track of the maximum value that occurs, and update the answer. We can simply iterate through banks $u$ to start with, and get the final answer. But wait. Won't it work in $O(n^{2}\\log{n})$ or something like that? No. Let's analyze the runtime carefully. (You can skip this if you know why. This is for beginners.) Suppose we choose bank $u$ to start with. We have to iterate through its neighboring banks. The number of the banks neighboring to $u$ is equal to the degree of bank $u$. We would need $O(1 + d_{u})$ operations for bank $u$. By iterating through all possible $u$ from $1$ to $n$, we will perform $O(n + d_{1} + d_{2} + ... + d_{n})$ operations. You can see that if there are $m$ edges in a graph, the degrees of all nodes sum to $2m$. Trees have $n - 1$ edges, so $d_{1} + d_{2} + ... + d_{n}$ $=$ $2(n - 1)$ $=$ $2n - 2$ $=$ $O(n)$. Therefore, we need to perform only $O(n)$ operations. However, each operation involves the map data structure, so the overall runtime is $O(n\\log n)$. Be aware that the use of hash map could bring the runtime to $O(n^{2})$. Looking more closely, we can also keep track of the occurrences of only $m + 1$ and $m + 2$, and no other values. So, although not required to get AC, we can get rid of the map data structure, and therefore eliminate the logarithmic factor. The official solution provided here runs in $O(n)$.",
    "code": "\"#include <stdio.h>\\n#include <vector>\\nusing namespace std;\\n\\nint a[300005];\\nvector<int> way[300005];\\n\\nint main(){\\n    int n;\\n    scanf(\\\"%d\\\", &n);\\n    int maxval=-1e9;\\n    for(int i=1; i<=n; i++) scanf(\\\"%d\\\", &a[i]), maxval = max(maxval, a[i]);\\n    for(int i=0; i<n-1; i++){\\n        int u, v;\\n        scanf(\\\"%d%d\\\", &u, &v);\\n        way[u].push_back(v);\\n        way[v].push_back(u);\\n    }\\n    int x=0, y=0;\\n    for(int i=1; i<=n; i++){\\n        if(a[i] == maxval) x++;\\n        else if(a[i] == maxval-1) y++;\\n    }\\n    \\n    int res = maxval+2;\\n    \\n    for(int i=1; i<=n; i++){\\n        \\n        // minus\\n        if(a[i] == maxval) x--;\\n        else if(a[i] == maxval-1) y--;\\n        for(int j=0; j<way[i].size(); j++){\\n            int pos = way[i][j];\\n            if(a[pos] == maxval) x--, y++;\\n            else if(a[pos] == maxval-1) y--;\\n        }\\n        \\n        // check the needed strength and update the answer\\n        if(x == 0){\\n            res = min(res, maxval+1);\\n            if(y == 0) res = min(res, maxval);\\n        }\\n        \\n        // plus\\n        if(a[i] == maxval) x++;\\n        else if(a[i] == maxval-1) y++;\\n        for(int j=0; j<way[i].size(); j++){\\n            int pos = way[i][j];\\n            if(a[pos] == maxval) x++, y--;\\n            else if(a[pos] == maxval-1) y++;\\n        }\\n        \\n    }\\n    \\n    printf(\\\"%d\\\", res);\\n    \\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "796",
    "index": "D",
    "title": "Police Stations",
    "statement": "Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own.\n\nRuling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most $d$ kilometers along the roads.\n\nThere are $n$ cities in the country, numbered from $1$ to $n$, connected only by exactly $n - 1$ roads. All roads are $1$ kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has $k$ police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city.\n\nHowever, Zane feels like having as many as $n - 1$ roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible.\n\nHelp Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.",
    "tutorial": "A greedy solution shutting down either every d roads or when a police station is encountered, although seems pretty nice, turns out to be incorrect. Consider performing a breadth first search (BFS) with \"cities with a police station\" as starting vertices, and shutting down the road when it leads to a visited vertex (city). This will leave every bad city connected (either directly or indirectly) with one of its nearest police stations, and thus will not break the law. With this method, you can see that exactly $k' - 1$ roads will be shut down (where $k'$ is the number of cities that have a police station in them). Suppose this is not optimal, and $k' + c$ ($c  \\ge  0$) roads can be shut down. The tree will break into $k' + c + 1$ components, while there are only $k'$ cities with a police station, so this is a contradiction, since there will be at least one component without any police station. Hence, shutting down $k' - 1$ roads is optimal.",
    "code": "\"#include <stdio.h>\\n#include <queue>\\n#include <vector>\\nusing namespace std;\\n\\nqueue<pair<int, int>> q;\\nvector<pair<int, int>> way[300005];\\nint v[300005];\\nint res[300005];\\n\\nint main(){\\n    int n, k, d;\\n    scanf(\\\"%d%d%d\\\", &n, &k, &d);\\n    for(int i=0; i<k; i++){\\n        int p;\\n        scanf(\\\"%d\\\", &p);\\n        q.push({p, 0});\\n    }\\n    for(int i=0; i<n-1; i++){\\n        int u, v;\\n        scanf(\\\"%d%d\\\", &u, &v);\\n        way[u].push_back({v, i+1});\\n        way[v].push_back({u, i+1});\\n    }\\n    while(!q.empty()){\\n        int pos = q.front().first;\\n        int from = q.front().second;\\n        q.pop();\\n        if(v[pos]) continue;\\n        v[pos] = 1;\\n        for(int i=0; i<way[pos].size(); i++) if(way[pos][i].first != from){\\n            if(v[way[pos][i].first]) res[way[pos][i].second] = 1;\\n            else q.push({way[pos][i].first, pos});\\n        }\\n    }\\n    int rescnt=0;\\n    for(int i=1; i<=n-1; i++) if(res[i]) rescnt++;\\n    printf(\\\"%d\\\\n\\\", rescnt);\\n    for(int i=1; i<=n-1; i++) if(res[i]) printf(\\\"%d \\\", i);\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "796",
    "index": "E",
    "title": "Exam Cheating",
    "statement": "Zane and Zane's crush have just decided to date! However, the girl is having a problem with her Physics final exam, and needs your help.\n\nThere are $n$ questions, numbered from $1$ to $n$. Question $i$ comes before question $i + 1$ ($1 ≤ i < n$). Each of the questions cannot be guessed on, due to the huge penalty for wrong answers. The girl luckily sits in the middle of two geniuses, so she is going to cheat.\n\nHowever, the geniuses have limitations. Each of them may or may not know the answers to some questions. Anyway, it is safe to assume that the answers on their answer sheets are absolutely correct.\n\nTo make sure she will not get caught by the proctor, the girl will glance \\textbf{at most} $p$ times, each time looking at \\textbf{no more than} $k$ consecutive questions on one of the two geniuses' answer sheet. When the girl looks at some question on an answer sheet, she copies the answer to that question if it is on that answer sheet, or does nothing otherwise.\n\nHelp the girl find the maximum number of questions she can get correct.",
    "tutorial": "This problem can be solved using dynamic programming. First, observe that it is never suboptimal to look as many consecutive questions as possible. That is, just look $k$ consecutive questions whenever you decide to glance, unless it exceeds the corner (question $n$). Let $dp[i][j][a][b]$ denote the number of questions you can get correct by considering questions $1$ to $i$ by glancing exactly $j$ times with $a$ and $b$ being the number of remaining questions that can be looked at as a benefit of the previous glances. As stated before, it is optimal to look as many consecutive questions as possible, so when we decide to look, we share this benefit (of looking) to the next questions too, and it are stored in $a$ and $b$, which denote how many of the next consecutive questions can be looked without paying one more glance. The answer can be calculated in $O(npk^{2})$. (You can see in the code as to how.) However, $npk^{2}$ can be up to $(1000) * (1000) * (50) * (50)$ $=$ $2, 500, 000, 000$, so the solution will not fit in the time limit of 2 seconds. This can be improved. Observe that if $p > 2 * ceil(n / k)$, you can look at all questions on both geniuses' answer sheets, so the answer can be found in $O(n)$ (or you can just set $p$ to $2 * ceil(n / k)$ and run the dynamic programming). By eliminating this case, the running time for dynamic programming will become $O(npk^{2})$ = $O(n(n / k)k^{2})$ = $O(n^{2}k)$. This, indeed, will fit in time, as $n^{2}k$ is only $(1000) * (1000) * (50)$ $=$ $50, 000, 000$. Problem with memory limit might still persist, so you will need to optimize the use of memory. For example, since you need only $dp[i - 1][..][..][..]$ and $dp[i][..][..][..]$ when calculating $dp[i][..][..][..]$, you could remember only the two last rows. The memory use will be much smaller. The use of short data type (instead of int) may also help. Please see the commented code for more details.",
    "code": "\"#include <stdio.h>\\n\\nint A[1005], B[1005];\\nint dp[2][1005][55][55];\\n\\nint max(int a, int b){ return a > b ? a : b; }\\n\\nint main(){\\n    int n, p, k;\\n    scanf(\\\"%d%d%d\\\", &n, &p, &k);\\n    if(k == 0){ printf(\\\"0\\\"); return 0; }\\n    if(p > 2*((n+k-1)/k)) p = 2*((n+k-1)/k);\\n    int r;\\n    scanf(\\\"%d\\\", &r);\\n    for(int i=0; i<r; i++){\\n        int x;\\n        scanf(\\\"%d\\\", &x);\\n        A[x] = 1;\\n    }\\n    int s;\\n    scanf(\\\"%d\\\", &s);\\n    for(int i=0; i<s; i++){\\n        int x;\\n        scanf(\\\"%d\\\", &x);\\n        B[x] = 1;\\n    }\\n    for(int i=0; i<2; i++) for(int j=0; j<1005; j++) for(int k=0; k<55; k++) for(int p=0; p<55; p++) dp[i][j][k][p] = -1e9;\\n    dp[0][0][0][0] = 0;\\n    for(int i=1; i<=n; i++){\\n        int cur = i&1, prev = !cur;\\n        // A only\\n        // - From nothing\\n        for(int j=1; j<=p; j++) dp[cur][j][k-1][0] = max(dp[cur][j][k-1][0], dp[prev][j-1][0][0] + A[i]);\\n        // - From something\\n        for(int j=1; j<=p; j++) for(int a=0; a<k-1; a++) dp[cur][j][a][0] = max(dp[cur][j][a][0], dp[prev][j][a+1][0] + A[i]);\\n        \\n        // B only\\n        // - From nothing\\n        for(int j=1; j<=p; j++) dp[cur][j][0][k-1] = max(dp[cur][j][0][k-1], dp[prev][j-1][0][0] + B[i]);\\n        // - From something\\n        for(int j=1; j<=p; j++) for(int b=0; b<k-1; b++) dp[cur][j][0][b] = max(dp[cur][j][0][b], dp[prev][j][0][b+1] + B[i]);\\n        \\n        // A and B\\n        // - From some A\\n        for(int j=1; j<=p; j++) for(int a=0; a<k-1; a++) dp[cur][j][a][k-1] = max(dp[cur][j][a][k-1], dp[prev][j-1][a+1][0] + (A[i]|B[i]));\\n        // - From some B\\n        for(int j=1; j<=p; j++) for(int b=0; b<k-1; b++) dp[cur][j][k-1][b] = max(dp[cur][j][k-1][b], dp[prev][j-1][0][b+1] + (A[i]|B[i]));\\n        // - From some A and B\\n        for(int j=2; j<=p; j++) for(int a=0; a<k-1; a++) for(int b=0; b<k-1; b++) dp[cur][j][a][b] = max(dp[cur][j][a][b], dp[prev][j][a+1][b+1] + (A[i]|B[i]));\\n        \\n        // None\\n        for(int j=0; j<=p; j++) dp[cur][j][0][0] = max(dp[cur][j][0][0], dp[prev][j][0][0]);\\n        \\n        for(int j=0; j<=p; j++) for(int a=0; a<k; a++) for(int b=0; b<k; b++) dp[prev][j][a][b] = -1e9;\\n    }\\n    int res = -1e9;\\n    for(int i=0; i<=p; i++) for(int j=0; j<k; j++) for(int a=0; a<k; a++) res = max(res, dp[n&1][i][j][a]);\\n    printf(\\\"%d\\\", res);\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "796",
    "index": "F",
    "title": "Sequence Recovery",
    "statement": "Zane once had a good sequence $a$ consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$ — but he has lost it.\n\nA sequence is said to be good if and only if all of its integers are non-negative and do not exceed $10^{9}$ in value.\n\nHowever, Zane remembers having played around with his sequence by applying $m$ operations to it.\n\nThere are two types of operations:\n\n1. Find the maximum value of integers with indices $i$ such that $l ≤ i ≤ r$, given $l$ and $r$.\n\n2. Assign $d$ as the value of the integer with index $k$, given $k$ and $d$.\n\nAfter he finished playing, he restored his sequence to the state it was before any operations were applied. That is, sequence $a$ was no longer affected by the applied type 2 operations. Then, he lost his sequence at some time between now and then.\n\nFortunately, Zane remembers all the operations and the order he applied them to his sequence, along with the \\textbf{distinct} results of all type 1 operations. Moreover, among all good sequences that would produce the same results when the same operations are applied in the same order, he knows that his sequence $a$ has the greatest cuteness.\n\nWe define cuteness of a sequence as the bitwise OR result of all integers in such sequence. For example, the cuteness of Zane's sequence $a$ is $a_{1}$ OR $a_{2}$ OR ... OR $a_{n}$.\n\nZane understands that it might not be possible to recover exactly the lost sequence given his information, so he would be happy to get any good sequence $b$ consisting of $n$ integers $b_{1}, b_{2}, ..., b_{n}$ that:\n\n1. would give the same results when the same operations are applied in the same order, and\n\n2. has the same cuteness as that of Zane's original sequence $a$.\n\nIf there is such a sequence, find it. Otherwise, it means that Zane must have remembered something incorrectly, which is possible.",
    "tutorial": "First, let's find the maximum value each integer can be. Chronologically considering the operations, you can see that once an integer is involved in type 2 operation, future type 1 operations can tell nothing about its initial value. You can find naively find the maximum value each integer can be in $O(nm)$, but that's obviously way too slow. This can be solved using segment trees. You might be familiar with point updates and range queries, but now you have to consider point queries and range updates. No-lazy propagation is not needed. This process can be solved in $O((n+m)\\log n)$. After that, let each integer has its maximum possible value as its value. Go through the operations once again one by one (both type 1 and type 2), and check with another segment tree whether this sequence gives correct results for type 1 operations. If it is not, you can be sure that there is no valid sequence. Why? Let's consider two cases. If the result is smaller than what the input says, this integer can't really be bigger than it is (other type 1 operations needed it to be this small, or maybe type 2 operation forced it to become this value). If the result is bigger than what the input says, this happens only when there is a contradiction between type 1 and type 2 operations, and nothing can be done (because type 2 operations say so). Let's complete the final step - make the bitwise OR maximal. You should consider 2 cases. 1) There is more than one free integer. (Free integer is the one such that no type 1 operation limits it maximum value.) The optimal bitwise OR is simply $2^{30} - 1$. Just make one of the free integers $2^{29} - 1$ and the others $10^{9}$ (any value no less than $2^{29}$ but also no more than $10^{9}$ will work). You can be sure that this is optimal. Other integers can simply remain untouched. 2) Otherwise For case 2, for each value appearing in more than one integer of the sequence (do not consider the one without maximum value yet), you can lower one of them. Lowering more than one of them will not give a better result if you lower it in this way: sacrifice the most significant bit for ALL other less significant bits. It's obvious that the operations remain satisfied. As for the free integer, if any, you can greedily assign some bit to it, starting from the most significant bit, but make sure that it doesn't exceed $10^{9}$ in value.",
    "code": "\"#include <stdio.h>\\n#include <algorithm>\\n#include <map>\\nusing namespace std;\\n\\nint n;\\nint type[300005], a[300005], b[300005], c[300005];\\nint res[300005];\\nmap<int, int> occ;\\n\\n// Segment Tree 1\\n\\nint t[600005];\\n\\nint findmax(int p){\\n    int res=2e9;\\n    for (p+=n; p; p>>=1) res = min(res, t[p]);\\n    return res;\\n}\\n\\nvoid upd(int l, int r, int x){\\n    for(l+=n, r+=n; l<r; l>>=1, r>>=1){\\n        if(l&1) t[l] = min(t[l], x), l++;\\n        if(r&1) r--, t[r] = min(t[r], x);\\n    }\\n    return;\\n}\\n\\n// Segment Tree 2\\n\\nint t2[600005];\\n\\nint findmax(int l, int r){\\n    int res = -2e9;\\n    for(l+=n, r+=n; l<r; l>>=1, r>>=1){\\n        if(l&1) res = max(res, t2[l++]);\\n        if(r&1) res = max(res, t2[--r]);\\n    }\\n    return res;\\n}\\n\\nvoid updval(int p, int val){\\n    for(t2[p+=n]=val; p>1; p>>=1) t2[p>>1] = max(t2[p], t2[p^1]);\\n    return;\\n}\\n\\n// Main Solution\\n\\nint main(){\\n    int m;\\n    scanf(\\\"%d%d\\\", &n, &m);\\n    for(int i=0; i<2*n; i++) t[i] = 2e9;\\n    for(int i=0; i<n; i++) res[i] = (2e9)+1;\\n    for(int i=0; i<m; i++){\\n        scanf(\\\"%d\\\", &type[i]);\\n        if(type[i] == 1){\\n            scanf(\\\"%d%d%d\\\", &a[i], &b[i], &c[i]);\\n            a[i]--, b[i]--;\\n            upd(a[i], b[i]+1, c[i]);\\n        } else{\\n            scanf(\\\"%d%d\\\", &a[i], &b[i]);\\n            a[i]--;\\n            if(res[a[i]] == (2e9)+1) res[a[i]] = findmax(a[i]);\\n        }\\n    }\\n    for(int i=0; i<n; i++) if(res[i] == (2e9)+1) res[i] = findmax(i);\\n    \\n    // Check validity of the array\\n    for(int i=0; i<n; i++) t2[n+i] = res[i];\\n    for(int i=n-1; i>0; i--) t2[i] = max(t2[i<<1], t2[i<<1|1]);\\n    for(int i=0; i<m; i++){\\n        if(type[i] == 1){\\n            if(findmax(a[i], b[i]+1) != c[i]){ printf(\\\"NO\\\"); return 0; }\\n        } else{\\n            updval(a[i], b[i]);\\n        }\\n    }\\n    for(int i=0; i<n; i++) if(res[i] < 0){ printf(\\\"NO\\\"); return 0; }\\n    \\n    // Make the answer optimal\\n    printf(\\\"YES\\\\n\\\");\\n    for(int i=0; i<n; i++) occ[res[i]]++;\\n    // - occ[2e9] >= 2 then the optimal OR result can simply be (1<<30)-1\\n    if(occ[2e9] >= 2){\\n        for(int i=0; i<n; i++) if(res[i] == 2e9){\\n            res[i] = 1e9, occ[2e9]--;\\n            if(occ[2e9] == 0) res[i] = (1<<29)-1;\\n        }\\n        for(int i=0; i<n; i++) printf(\\\"%d \\\", res[i]);\\n        return 0;\\n    }\\n    // - otherwise, find the best value for the free 2e9 (if any)\\n    int orresult = 0;\\n    for(int i=0; i<n; i++){\\n        if(res[i] == 0 || res[i] == 2e9) continue; // ignoring this could lead to a critical bug\\n        occ[res[i]]--;\\n        if(occ[res[i]]){\\n            int temp=res[i], pow=0;\\n            while(temp) pow++, temp /= 2;\\n            res[i] = (1<<(pow-1))-1;\\n        }\\n        orresult |= res[i];\\n    }\\n    int tobe=0;\\n    for(int cur=29; cur>=0; cur--){\\n        if(orresult&(1<<cur)) continue;\\n        if(tobe+(1<<cur) > 1e9) continue;\\n        tobe += (1<<cur);\\n    }\\n    for(int i=0; i<n; i++){\\n        if(res[i] == 2e9) printf(\\\"%d \\\", tobe);\\n        else printf(\\\"%d \\\", res[i]);\\n    }\\n    \\n    return 0;\\n}\"",
    "tags": [
      "bitmasks",
      "data structures",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "797",
    "index": "A",
    "title": "k-Factorization",
    "statement": "Given a positive integer $n$, find $k$ integers (not necessary distinct) such that all these integers are strictly greater than $1$, and their product is equal to $n$.",
    "tutorial": "There are many approaches to this problem. You can, for example, factorize $n$, store all multipliers in a list, and while size of this list is greater than $k$, take any two elements of this list and replace them with their product. If the initial size of this list is less than $k$, then answer is -1.",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "797",
    "index": "B",
    "title": "Odd sum",
    "statement": "You are given sequence $a_{1}, a_{2}, ..., a_{n}$ of integer numbers of length $n$. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.\n\nSubsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.\n\nYou should write a program which finds sum of the best subsequence.",
    "tutorial": "The answer to this problem can be constructed this way: Sum up all positive numbers Find maximum $max_{odd}$ of negative odd numbers Find minimum $min_{odd}$ of positive odd numbers If sum was even then subtract $min(min_{odd}, - max_{odd})$ Overall complexity: $O(n)$.",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "797",
    "index": "C",
    "title": "Minimal string",
    "statement": "Petya recieved a gift of a string $s$ with length up to $10^{5}$ characters for his birthday. He took two more empty strings $t$ and $u$ and decided to play a game. This game has two possible moves:\n\n- Extract the \\textbf{first} character of $s$ and append $t$ with this character.\n- Extract the \\textbf{last} character of $t$ and append $u$ with this character.\n\nPetya wants to get strings $s$ and $t$ empty and string $u$ lexicographically minimal.\n\nYou should write a program that will help Petya win the game.",
    "tutorial": "On every step you should maintain minimal alphabetic letter in current string $s$ (this can be done by keeping array of 26 cells with number of times each letter appear in string nd updating it on every step). Let's call string $t$ a stack and use its terms. Now you extract letters from $s$ one by one. Put the letter to the top of the stack. Pop letters from the top of stack and push them to answer while they are less or equal than any letter left in string $s$. After string $s$ becomes empty push all the letters from stack to answer. The answer will be lexicographically minimal. It is obvious if we consider the case when current top of stack is strictly greater than any character from the remaining string $s$, or there is a character in $s$ that is strictly less than current top. If current top is equal to some character then appending answer with the letter from top won't make answer worse. Overall complexity: $O(n * |AL|)$, where $|AL|$ is the length of the alpabet, $26$ in our case.",
    "tags": [
      "data structures",
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "797",
    "index": "D",
    "title": "Broken BST",
    "statement": "Let $T$ be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree $T$:\n\n- Set pointer to the root of a tree.\n- Return success if the value in the current vertex is equal to the number you are looking for\n- Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for\n- Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for\n- Return fail if you try to go to the vertex that doesn't exist\n\nHere is the pseudo-code of the described algorithm:\n\n\\begin{verbatim}\nbool find(TreeNode t, int x) {\nif (t == null)\nreturn false;\nif (t.value == x)\nreturn true;\nif (x < t.value)\nreturn find(t.left, x);\nelse\nreturn find(t.right, x);\n}\nfind(root, x);\n\\end{verbatim}\n\nThe described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.\n\nSince the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.\n\nIf the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.",
    "tutorial": "Let's firstly consider tree with only distinct values in its nodes. Then value will be reached if and only if all the jumps to the left children on the path from the root were done from the vertices with values greater than the current one and all the jumps to the right children on the path from the root were done from the vertices with values less than the current one. Thus let's run dfs from the root and maintain maximal transition to the left child on current path and minimal transition to the right child on current path. If the value of current node is greater than left bound and less than right bound then it will be found. Now let's return to the original problem. Notice that transitions and comparations won't change. Store every found value in set and just calculate how many values of vertices isn't present there. Overall complexity: $O(n \\cdot log(n))$.",
    "tags": [
      "data structures",
      "dfs and similar"
    ],
    "rating": 2100
  },
  {
    "contest_id": "797",
    "index": "E",
    "title": "Array Queries",
    "statement": "$a$ is an array of $n$ positive integers, all of which are not greater than $n$.\n\nYou have to process $q$ queries to this array. Each query is represented by two numbers $p$ and $k$. Several operations are performed in each query; each operation changes $p$ to $p + a_{p} + k$. There operations are applied until $p$ becomes greater than $n$. The answer to the query is the number of performed operations.",
    "tutorial": "There are two possible solutions in $O(n^{2})$ time. First of them answers each query using simple iteration - changes $p$ to $p + a_{p} + k$ for each query until $p$ becomes greater than $n$, as stated in the problem. But it is too slow. Second solution precalculates answers for each $p$ and $k$: if $p + a_{p} + k > n$, then $ans_{p, k} = 1$, else $ans_{p, k} = ans_{p + ap + k, k} + 1$. But this uses $O(n^{2})$ memory and can be done in $O(n^{2})$ time. Now we can notice that if $k<{\\sqrt{n}}$, then second solution will use only $O(n{\\sqrt{n}})$ time and memory, and if $k\\geqslant{\\sqrt{n}}$, then first solution will do not more than $\\sqrt{n}$ operations on each query. So we can combine these two solutions. Time complexity: $O(n{\\sqrt{n}})$.",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "797",
    "index": "F",
    "title": "Mice and Holes",
    "statement": "One day Masha came home and noticed $n$ mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor.\n\nThe corridor can be represeted as a numeric axis with $n$ mice and $m$ holes on it. $i$th mouse is at the coordinate $x_{i}$, and $j$th hole — at coordinate $p_{j}$. $j$th hole has enough room for $c_{j}$ mice, so not more than $c_{j}$ mice can enter this hole.\n\nWhat is the minimum sum of distances that mice have to go through so that they all can hide in the holes? If $i$th mouse goes to the hole $j$, then its distance is $|x_{i} - p_{j}|$.\n\nPrint the minimum sum of distances.",
    "tutorial": "This problem can be solved using dynamic programming. Let $dp_{i, j}$ be the answer for first $i$ holes and $j$ mice. If the constraints were smaller, then we could calculate it in $O(n^{2}m)$ just trying to update $dp_{i, j}$ by all values of $dp_{i - 1, k}$ where $k  \\le  j$ and calculating the cost to transport all mice from the segment to $i$th hole. To calculate this in $O(nm)$, we will use a deque maintaining the minimum (or a queue implemented on two stacks, for example). We iterate on $i$ and update all the values of $dp_{i + 1, j}$ with the help of this deque: for each index $j$ we insert a value in the deque equal to $dp_{i, j} - cost$, where $cost$ is the total distance required to move first $j$ mice to hole $i + 1$. Updating the value is just extracting the minimum and adding this $cost$ to it. Don't forget to delete values from the deque to ensure that we don't send too much mice to the hole. Time complexity: $O(nm)$.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "798",
    "index": "A",
    "title": "Mike and palindrome",
    "statement": "Mike has a string $s$ consisting of only lowercase English letters. He wants to \\textbf{change exactly one} character from the string so that the resulting one is a palindrome.\n\nA palindrome is a string that reads the same backward as forward, for example strings \"z\", \"aaa\", \"aba\", \"abccba\" are palindromes, but strings \"codeforces\", \"reality\", \"ab\" are not.",
    "tutorial": "Let $cnt$ be the number of $1\\leq i\\leq{\\frac{n}{2}}$ such that $s_{i}  \\neq  s_{n - i + 1}$. If $cnt  \\ge  2$ then the answer is NO since we must change more than 1 character. If $cnt = 1$ then the answer is YES. If $cnt = 0$ and $n$ is odd answer is YES since we can change the character in the middle, otherwise if $n$ is even the answer is NO because we must change at least one character. Complexity is $O(|s|)$.",
    "code": "\"# include <bits/stdc++.h>\\nusing namespace std;\\nint main(void)\\n{\\n    string s;\\n    cin>>s;\\n    s = '#' + s;\\n    int n = s.length() - 1;\\n    int cnt = 0;\\n    for (int i = 1;i + i <= n;++i)\\n        if (s[i] != s[n - i + 1])\\n            ++cnt;\\n    if ((cnt <= 1 && (n&1)) || cnt == 1) puts(\\\"YES\\\");\\n    else puts(\\\"NO\\\");\\n    return 0;\\n}\\n\"",
    "tags": [
      "brute force",
      "constructive algorithms",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "798",
    "index": "B",
    "title": "Mike and strings",
    "statement": "Mike has $n$ strings $s_{1}, s_{2}, ..., s_{n}$ each consisting of lowercase English letters. In one move he can choose a string $s_{i}$, erase the first character and append it to the end of the string. For example, if he has the string \"coolmike\", in one move he can transform it into the string \"oolmikec\".\n\nNow Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?",
    "tutorial": "First of all, you must notice that the operation of removing the first character and appending it to the left is equivalent to cyclically shifting the string one position to the left. Let's denote by $dp_{i, j}$ the smallest number of operations for making the first $i$ strings equal to string $s_{i}$ moved $j$ times. Let $f(i, j)$ be the the string $s_{i}$ moved $j$ times,then $d p_{i,j}=\\operatorname*{min}_{k=0,f(i-1,k)=f(i,j)}d p_{i-1,k}+j$. The answer is $min(dp_{n, 0}, dp_{n, 1}, ..., dp_{n, |sn| - 1})$. The complexity is $O(|S|^{3}  \\times  n)$.",
    "code": "\"# include <bits/stdc++.h>\\nusing namespace std;\\n# define fi cin\\n# define fo cout\\nstring s[512];\\nint dp[512][512];\\nint main(void)\\n{\\n    int n;\\n    fi>>n;\\n    for (int i = 1;i <= n;++i)\\n        fi>>s[i];\\n    int k = s[1].length();\\n    for (int i = 1;i <= n;++i)\\n        for (int j = 0;j < k;++j)\\n            dp[i][j] = 1e9;\\n    for (int i = 1;i <= n;++i)\\n        s[i] = s[i] + s[i];\\n    for (int i = 0;i < k;++i)\\n        dp[1][i] = i;\\n    for (int i = 2;i <= n;++i)\\n    {\\n        for (int j = 0;j < k;++j)\\n            for (int prev = 0;prev < k;++prev)\\n                if (s[i].substr(j,k) == s[i-1].substr(prev,k))\\n                    dp[i][j] = min(dp[i][j],dp[i-1][prev] + j);\\n    }\\n    int ans = 1e9;\\n    for (int i = 0;i < k;++i)\\n        ans = min(ans,dp[n][i]);\\n    if (ans == 1e9)\\n        puts(\\\"-1\\\");\\n    else\\n        fo << ans << '\\\\n';\\n    return 0;\\n}\\n\\n\\n\"",
    "tags": [
      "brute force",
      "dp",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "798",
    "index": "C",
    "title": "Mike and gcd problem",
    "statement": "Mike has a sequence $A = [a_{1}, a_{2}, ..., a_{n}]$ of length $n$. He considers the sequence $B = [b_{1}, b_{2}, ..., b_{n}]$ beautiful if the $gcd$ of all its elements is bigger than $1$, i.e. $\\operatorname*{gcd}(b_{1},b_{2},\\dots,b_{n})>1$.\n\nMike wants to change his sequence in order to make it beautiful. In one move he can choose an index $i$ ($1 ≤ i < n$), delete numbers $a_{i}, a_{i + 1}$ and put numbers $a_{i} - a_{i + 1}, a_{i} + a_{i + 1}$ in their place instead, in this order. He wants perform as few operations as possible. Find the minimal number of operations to make sequence $A$ beautiful if it's possible, or tell him that it is impossible to do so.\n\n$\\operatorname*{gcd}(b_{1},b_{2},\\cdot\\cdot\\cdot,b_{n})$ is the biggest non-negative number $d$ such that $d$ divides $b_{i}$ for every $i$ ($1 ≤ i ≤ n$).",
    "tutorial": "First of all, the answer is always YES. If $\\operatorname*{gcd}(a_{1},a_{2},...,a_{n})\\neq1$ then the answer is $0$. Now suppose that the gcd of the sequence is $1$. After we perform one operation on $a_{i}$ and $a_{i + 1}$, the new gcd $d$ must satisfy $d|a_{i} - a_{i + 1}$ and $d|a_{i} + a_{i + 1}$ $\\longrightarrow\\bigcup$ $d|2a_{i}$ and $d|2a_{i + 1}$. Similarly, because $d$ is the gcd of the new sequence, it must satisfy $d|a_{j}, j  \\neq  i, i + 1$. Using the above observations we can conclude that $\\left.d\\right|\\mathrm{gc}|\\bigl(u_{1,}\\cdot\\cdot\\cdot\\cdot\\cdot\\bigr)d_{i}\\cdot\\cdot d_{i}\\G\\!d_{i+1,}\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\bigr(u_{n}\\bigr)|^{\\cdot}\\mathrm{gc}\\!\\left((u_{1,}\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\bigr)=\\mathrm{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$, so the gcd of the sequence can become at most $2$ times bigger after an operation. This means that in order to make the gcd of the sequence bigger than $1$ we need to make all numbers even. Now the problem is reduced to the following problem: Given a sequence $v_{1}, v_{2}, ... , v_{n}$ of zero or one,in one move we can change numbers $v_{i}, v_{i + 1}$ with $2$ numbers equal to $v_{i}\\oplus v_{i+1}$. Find the minimal number of moves to make the whole sequence equal to $0$. It can be proved that it is optimal to solve the task for consecutive ones independently so we divide the array into the minimal number of subarrays full of ones, if their lengths are $s_{1}, s_{2}, ... , s_{t}$,the answer is $\\textstyle\\sum_{i=1}^{t}\\left[{\\frac{s_{i}}{2}}\\right]^{}+\\left(s_{i}\\mod2\\right)$. Complexity is $O(N\\log M A X)$.",
    "code": "\"# include <bits/stdc++.h>\\nusing namespace std;\\n# define fi cin\\n# define fo cout\\nint main(void)\\n{\\n    int n;\\n    fi>>n;\\n    int g = 0,v,cnt = 0,ans = 0;\\n    while (n --)\\n    {\\n        int v;\\n        fi>>v;\\n        g = __gcd(g,v);\\n        if (v & 1) ++cnt;\\n        else ans += (cnt / 2) + 2 * (cnt & 1),cnt = 0;\\n    }\\n    ans += (cnt / 2) + 2 * (cnt & 1);\\n    fo << \\\"YES\\\\n\\\";\\n    if (g == 1)\\n        fo << ans << '\\\\n';\\n    else\\n        fo << \\\"0\\\\n\\\";\\n    cerr << \\\"Time elapsed :\\\" << clock() * 1000.0 / CLOCKS_PER_SEC << \\\" ms\\\" << '\\\\n';\\n    return 0;\\n}\\n\"",
    "tags": [
      "dp",
      "greedy",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "798",
    "index": "D",
    "title": "Mike and distribution",
    "statement": "Mike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers $A = [a_{1}, a_{2}, ..., a_{n}]$ and $B = [b_{1}, b_{2}, ..., b_{n}]$ of length $n$ each which he uses to ask people some quite peculiar questions.\n\nTo test you on how good are you at spotting inequality in life, he wants you to find an \"unfair\" subset of the original sequence. To be more precise, he wants you to select $k$ numbers $P = [p_{1}, p_{2}, ..., p_{k}]$ such that $1 ≤ p_{i} ≤ n$ for $1 ≤ i ≤ k$ and elements in $P$ are distinct. Sequence $P$ will represent indices of elements that you'll select from both sequences. He calls such a subset $P$ \"unfair\" if and only if the following conditions are satisfied: $2·(a_{p1} + ... + a_{pk})$ is \\textbf{greater} than the sum of all elements from sequence $A$, and $2·(b_{p1} + ... + b_{pk})$ is \\textbf{greater} than the sum of all elements from the sequence $B$. Also, $k$ should be smaller or equal to $\\lfloor{\\frac{n}{2}}\\rfloor+1$ because it will be to easy to find sequence $P$ if he allowed you to select too many elements!\n\nMike guarantees you that a solution will always exist given the conditions described above, so please help him satisfy his curiosity!",
    "tutorial": "In the beginning, it's quite easy to notice that the condition \" $2 \\cdot (a_{p1} + ... + a_{pk})$ is greater than the sum of all elements in $A$ \" is equivalent to \" $a_{p1} + ... + a_{pk}$ is greater than the sum of the remaining elements in $A$ \". Now, let's store an array of indices $C$ with $C_{i} = i$ and then sort it in decreasing order according to array $A$, that is we must have $A_{Ci}  \\ge  A_{Ci + 1}$. Our answer will always have size $\\lfloor{\\frac{N}{2}}\\rfloor+1$. First suppose that $N$ is odd. Add the first index to our set, that is make $p_{1} = C_{1}$. Now, for the remaining elements, we will consider them consecutively in pairs. Suppose we are at the moment inspecting $A_{C2k}$ and $A_{C2k + 1}$. If $B_{C2k}  \\ge  B_{C2k + 1}$ we make $p_{k + 1} = C_{2k}$, else we make $p_{k + 1} = C_{2k + 1}$. Why does this subset work? Well, it satisfies the condition for $B$ because each time for consecutive non-intersecting pairs of elements we select the bigger one, and we also add $B_{C1}$ to the set, so in the end the sum of the selected elements will be bigger than the sum of the remaining ones. It also satisfies the condition for $A$, because $A_{p1}$ is equal or greater than the complement element of $p_{2}$ (that is - the index which we could've selected instead of $p_{2}$ from the above procedure - if we selected $C_{2k}$ then it would be $C_{2k + 1}$ and vice-versa). Similarly $A_{p2}$ is greater than the complement of $p_{3}$ and so on. In the end we also add the last element from the last pair and this makes the sum of the chosen subset strictly bigger than the sum of the remaining elements. The case when $N$ is even can be done exactly the same as when $N$ is odd, we just pick the last remaining index in the end. The complexity is $O(N\\log N)$.",
    "code": "\"# include <bits/stdc++.h>\\nusing namespace std;\\n# define vi vector < int >\\n# define pb push_back\\nint a[1 << 20];\\nint b[1 << 20];\\nint p[1 << 20];\\nint main(void)\\n{\\n    int n;\\n    scanf(\\\"%d\\\",&n);\\n    for (int i = 1;i <= n;++i)\\n        scanf(\\\"%d\\\",&a[i]);\\n    for (int i = 1;i <= n;++i)\\n        scanf(\\\"%d\\\",&b[i]);\\n    for (int i = 1;i <= n;++i)\\n        p[i] = i;\\n    sort(p + 1,p + 1 + n,[&](int xx,int yy) {return a[xx] > a[yy];});\\n    vi answer;\\n    answer.pb(p[1]);\\n    for (int i = 2;i <= n;i += 2)\\n    {\\n        int bst = p[i];\\n        if (i + 1 <= n && b[p[i + 1]] > b[bst])\\n            bst = p[i + 1];\\n        answer.pb(bst);\\n    }\\n    int sz = answer.size();\\n    printf(\\\"%d\\\\n\\\",sz);\\n    for (int i = 0;i < sz;++i)\\n        printf(\\\"%d%c\\\",answer[i],\\\" \\\\n\\\"[i == sz - 1]);\\n    cerr << \\\"Time elapsed :\\\" << clock() * 1000.0 / CLOCKS_PER_SEC << \\\" ms\\\" << '\\\\n';\\n    return 0;\\n}\\n\"",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "798",
    "index": "E",
    "title": "Mike and code of a permutation",
    "statement": "Mike has discovered a new way to encode permutations. If he has a permutation $P = [p_{1}, p_{2}, ..., p_{n}]$, he will encode it in the following way:\n\nDenote by $A = [a_{1}, a_{2}, ..., a_{n}]$ a sequence of length $n$ which will represent the code of the permutation. For each $i$ from $1$ to $n$ sequentially, he will choose the smallest unmarked $j$ ($1 ≤ j ≤ n$) such that $p_{i} < p_{j}$ and will assign to $a_{i}$ the number $j$ (in other words he performs $a_{i} = j$) and will mark $j$. If there is no such $j$, he'll assign to $a_{i}$ the number $ - 1$ (he performs $a_{i} = - 1$).\n\nMike forgot his original permutation but he remembers its code. Your task is simple: find \\textbf{any} permutation such that its code is the same as the code of Mike's original permutation.\n\nYou may assume that there will always be at least one valid permutation.",
    "tutorial": "Let's consider $a_{i} = n + 1$ instead of $a_{i} = - 1$. Let's also define the sequence $b$, where $b_{i} = j$ such that $a_{j} = i$ or $b_{i} = n + 1$ if there is no such $j$. Lets make a directed graph with vertices be the indices of the permutation $p$ with edges of type $(a, b)$ representing that $p_{a} > p_{b}$. If we topologically sort this graph then we can come up with a possible permutation: if $S$ is the topologically sorted graph then we can assign to $p_{Si}$ number $i$. In this problem we will use this implementation of topological sort. But how we can find the edges? First of all there are edges of the form $(i, b_{i})$ if $b_{i}  \\neq  n + 1$ .For a vertex $i$ he visited all the unmarked vertices $j$ $(1  \\le  j < a_{i}, j  \\neq  i)$ and you know for sure that for all these $j, p_{j} < p_{i}$. But how we can check if $j$ was already marked? The vertex $j$ will become marked after turn of vertex $b_{j}$ or will never become unmarked if $b_{j} = n + 1$. So there is a direct edge from $i$ to $j$ if $j = b_{i}$ or $1  \\le  j < a_{i}, j  \\neq  i$ and $b_{j} > i$. Suppose we already visited a set of vertices and for every visited vertex $node$ we assigned to $b_{node}$ value $0$ (for simplicity just to forget about all visited vertices) and now we want to find quickly for a fixed vertex $i$ an unvisited vertex $j$ with condition that there is edge $(i, j)$ or say it there isn't such $j$, if we can do that in subquadratic time then the task is solved. As stated above the first condition is $j = b_{i}$ if $1  \\le  b_{i}  \\le  n$, this condition is easy to check. The second condition is $1  \\le  j < a_{i}$ and $b_{j} > i$, now consider vertices with indices from interval $1..a_{i} - 1$ and take $j$ with maximal $b_{j}$. If $b_{j} > i$ we found edge $(i, j)$ otherwise there are no remaining edges. We can find such vertex $j$ using segment tree and updating values while we visit a new vertex. In total we will visit $n$ vertices and query the segment tree at most $2  \\times  (n - 1)$ times ($n - 1$ for every new vertex and $n - 1$ for finding that there aren't remaining edges). Complexity and memory are $O(N\\log N)$ and $O(N)$.",
    "code": "\"# include <bits/stdc++.h>\\nusing namespace std;\\n# define fi cin\\n# define fo cout\\n# define x first\\n# define y second\\n# define IOS ios_base :: sync_with_stdio(0)\\nint a[1 << 20];\\nint b[1 << 20];\\npair < int , int > t[1 << 22];\\nvoid build(int p,int u,int node)\\n{\\n    if (p == u) t[node] = {b[p],p};\\n    else\\n    {\\n        int m = (p + u) / 2;\\n        build(p,m,node << 1);\\n        build(m+1,u,node << 1 | 1);\\n        t[node] = max(t[node << 1],t[node << 1 | 1]);\\n    }\\n}\\n// building the tree \\nvoid Del(int p,int u,int v,int node)\\n{\\n    if (p == u) t[node] = {0,p};\\n    else\\n    {\\n        int m = (p + u) / 2;\\n        if (v <= m) Del(p,m,v,node << 1);\\n        else Del(m+1,u,v,node << 1 | 1);\\n        t[node] = max(t[node << 1],t[node << 1 | 1]);\\n    }\\n}\\n// deleting a visited vertex\\npair < int , int > query(int p,int u,int l,int r,int node)\\n{\\n    if (l > r) return {0,0};\\n    if (l <= p && u <= r) return t[node];\\n    int m = (p + u) / 2;\\n    pair < int , int > ans = {0,0};\\n    if (l <= m) ans = max(ans,query(p,m,l,r,node << 1));\\n    if (m+1<=r) ans = max(ans,query(m+1,u,l,r,node << 1 | 1));\\n    return ans;\\n}\\n// find edge for a fixed interval\\nint was[1 << 20];\\n// visited/not\\nint n;\\nvector < int > Sort;\\n//sorted graph\\nvoid dfs(int node)\\n{\\n\\t//node = i from tutorial\\n    Del(1,n,node,1);\\n    was[node] = 1;\\n    if (b[node] != n + 1 && !was[b[node]]) dfs(b[node]);\\n    //edges of first type\\n    while (1)\\n    {\\n        auto it = query(1,n,1,a[node] - 1,1);\\n        //it.y = j from tutorial,it.x is b[j]\\n        if (it.x > node) dfs(it.y);//there is edge\\n        else break;//there aren't remaining\\n    }\\n    //edges of second type\\n    Sort.push_back(node);\\n}\\nint ans[1 << 20];\\nint main(void)\\n{\\n    scanf(\\\"%d\\\\n\\\",&n);\\n    for (int i = 1;i <= n;++i) b[i] = n + 1;\\n    for (int i = 1;i <= n;++i) scanf(\\\"%d\\\",&a[i]);\\n    for (int i = 1;i <= n;++i)\\n        if (a[i] != -1)\\n            b[a[i]] = i;\\n    //b from tutorial\\n    for (int i = 1;i <= n;++i)\\n        if (a[i] == -1)\\n            a[i] = n + 1;\\n    //just replacing\\n    build(1,n,1);\\n    //building the tree\\n    for (int i = 1;i <= n;++i)\\n        if (!was[i])\\n            dfs(i);\\n    //sorting the graph\\n    int cnt = 0;\\n    for (auto it : Sort)\\n        ans[it] = ++cnt;\\n    //assigning p[ans[i]] = i as stated in tutorial\\n    for (int i = 1;i <= n;++i)\\n        printf(\\\"%d%c\\\",ans[i],\\\" \\\\n\\\"[i == n]);\\n    //printing one possible permutation\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "799",
    "index": "A",
    "title": "Carrot Cakes",
    "statement": "In some game by Playrix it takes $t$ minutes for an oven to bake $k$ carrot cakes, all cakes are ready at the same moment $t$ minutes after they started baking. Arkady needs at least $n$ cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take $d$ minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven.\n\nDetermine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get $n$ cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.",
    "tutorial": "One of possible solutions - to simply simulate described process. To make it we need two variables - $t_{1}$ and $t_{2}$. In them we will store the time when each of the ovens will become free. In the beginning $t_{1}$ equals to $0$ and $t_{2}$ equals to $d$. After simulating the process we will get a time for which possible to make $n$ cakes with $2$ ovens (this time equals to maximum from $t_{1}$ and $t_{2}$). It is only left to compare this time with value $(n + k - 1) / k \\cdot t$ - a time for which possible to make $n$ cakes using only one oven.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "799",
    "index": "B",
    "title": "T-shirt buying",
    "statement": "A new pack of $n$ t-shirts came to a shop. Each of the t-shirts is characterized by three integers $p_{i}$, $a_{i}$ and $b_{i}$, where $p_{i}$ is the price of the $i$-th t-shirt, $a_{i}$ is front color of the $i$-th t-shirt and $b_{i}$ is back color of the $i$-th t-shirt. All values $p_{i}$ are distinct, and values $a_{i}$ and $b_{i}$ are integers from $1$ to $3$.\n\n$m$ buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the $j$-th buyer we know his favorite color $c_{j}$.\n\nA buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.\n\nYou are to compute the prices each buyer will pay for t-shirts.",
    "tutorial": "Let's store in three arrays t-shirts which have appropriate color. About each t-shirt is enough to store its index, but we will additionally store its cost. It is possible that one t-shirt will be in two arrays (if this t-shirt colorful). Then we need to sort t-shirts in each array in increasing order of cost. After that we will process buyers. Also for each array we will store the pointer to leftmost t-shirt which was not purchased yet. For a new buyer we need to look on array with t-shirts which appropriate to his favorite color. Using appropriate pointer let's iterate to the right until there are t-shirts or until we not found unsold t-shirt (to this we can store one more array $used$ with type bool - did we sell or no appropriate t-shirt). If there are no t-shirt with needed color - print -1. In the other case, print the cost of founded t-shirt and tag in array $used$ that we sold this t-shirt.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "799",
    "index": "C",
    "title": "Fountains",
    "statement": "Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are $n$ available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed.\n\nHelp Arkady to find two fountains with maximum total beauty so that he can buy both at the same time.",
    "tutorial": "There are three ways - Arkady builds one fountain for coins and other for diamonds, Arkady builds both fountains for coins and Arkady builds both fountains for diamonds. In the end we need to choose a way with maximum total beauty. The first way is simple - we need to choose one fountain of each type with maximum beauty on which is enough coins and diamonds which Arkady has. To make it we can easily iterate though all given fountains. The other two ways are treated similarly to each other. Consider the way when Arkady builds both fountains for coins. Let's write out all the fountains for a coins in a separate array. We will store them as pairs - cost and beauty. Then sort the array in ascending order of cost. Let Arkady will build fountains with cost $p_{1}$ and $p_{2}$ coins and $p_{1}  \\le  p_{2}$ and $p_{1} + p_{2}  \\le  c$. Additionally we need an array $maxB$, where $maxB_{i}$ equals to maximum fountain beauty on the prefix of sorted fountains for coins which ends in position $i$. The option when $p_{1}$ equals to $p_{2}$ should be considered separately. It can be done in one iteration through the fountains - from fountains with same cost we need to choose two with maximum beauty and update the answer with the resulting value. It is only left case when $p_{1} < p_{2}$. Let's brute the fountain with cost equals to $p_{2}$. After that, Arcady will have $c - p_{2}$ coins. After that with help of binary search we need to find the fountains prefix which Arkay can build for the remaining coins. With help of array $maxB$ we can determine the maximum beauty of fountain which Arkady can build. Similarly, the third way is solved when both fountains will be built for diamonds.",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "799",
    "index": "D",
    "title": "Field expansion",
    "statement": "In one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are $n$ extensions, the $i$-th of them multiplies the width or the length (by Arkady's choice) by $a_{i}$. Each extension can't be used more than once, the extensions can be used in any order.\n\nNow Arkady's field has size $h × w$. He wants to enlarge it so that it is possible to place a rectangle of size $a × b$ on it (along the width or along the length, with sides parallel to the field sides). Find the minimum number of extensions needed to reach Arkady's goal.",
    "tutorial": "At first let's check if rectangle can be placed on given field - if it is possible print 0. In the other case we need to expand the field. Let's sort all extensions in descending order and take only $34$ from them - it is always enough based on given constraints. After that we need to calculate linear dynamic where $d_{i}$ equals to maximum width which we got for the length $i$. Let's iterate through extensions in sorted order and recalculate $d$. For each length $i$ we need to expand itself or to expand the width $d_{i}$. To avoid overflow we will not store the width and length which more than $10^{5}$. On each recalculate value of $d$ we need to check if rectangle can be places on current field. If it is possible - we found the answer and we need to print the number of extensions which we already used.",
    "tags": [
      "brute force",
      "dp",
      "meet-in-the-middle"
    ],
    "rating": 2100
  },
  {
    "contest_id": "799",
    "index": "E",
    "title": "Aquarium decoration",
    "statement": "Arkady and Masha want to choose decorations for thier aquarium in Fishdom game. They have $n$ decorations to choose from, each of them has some cost. To complete a task Arkady and Masha need to choose \\textbf{exactly} $m$ decorations from given, and they want to spend as little money as possible.\n\nThere is one difficulty: Masha likes some $a$ of the given decorations, Arkady likes some $b$ of the given decorations. Some decorations may be liked by both Arkady and Masha, or not be liked by both. The friends want to choose such decorations so that each of them likes \\textbf{at least} $k$ decorations among the chosen. Help Masha and Arkady find the minimum sum of money they need to spend.",
    "tutorial": "Let's divide the decorations in four groups: that aren't liked by anybody (group 0), that are liked only by Masha (group 1), that are liked only by Arkady (group 2), that are liked by both (group 3). Sort each group by the cost. Then, it's obvious that in optimal solution we should take several (or 0) first elements in each group. Take a look at the group 3. It's easy to see that if we take $x$ decorations from it, then we should take first $k - x$ decorations from each of the groups 1 and 2. Let's call these decorations ($x$ from the group 3 and $k - x$ from each of the groups 1 and 2) obligatory, and let's call the other decorations free. If the number of obligatory decorations is less than $m$, we need to take several cheapest free decorations. It's easy to construct an $O(n^{2})$ solution then: for each $x$ we can construct the answer described in linear time and then choose minimum among these answers. To speed up the algorithm, let's try all $x$ from the minimum possible (it's easy to get it from integers $k$, $m$ and groups 1 and 2 sizes), making transfers from $x$ to $x + 1$. We should maintain the set of costs of free decorations, and let's also keep integer $y$, which is the number of free decorations that we should add to the current answer, and also the sum of the $y$ cheapest free decorations. When we increase $x$ by 1, in groups 1 and 2 the most expensive obligatory decoration becomes free (because the value $k - x$ decreases by one 1). These decorations (if any) we should add to our free set. We should also add one obligatory decoration from the group 3, so, the number of free decorations could change by one. So, we need at most $2$ operations of adding an integer to a set, and an operation that changes $y$ with the corresponding change of the sum. We can perform these operations in $O(log(n))$, for example, using two std::set objects in C++ (or its analogues in other languages) one set for the smallest $y$ integers and one for the others. The overall complexity to change $x$ to $x + 1$ is now $O(log(n))$, so the overall complexity is $O(n * log(n))$.",
    "tags": [
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "799",
    "index": "F",
    "title": "Beautiful fountains rows",
    "statement": "Butler Ostin wants to show Arkady that rows of odd number of fountains are beautiful, while rows of even number of fountains are not.\n\nThe butler wants to show Arkady $n$ gardens. Each garden is a row of $m$ cells, the $i$-th garden has one fountain in each of the cells between $l_{i}$ and $r_{i}$ inclusive, and there are no more fountains in that garden. The issue is that some of the gardens contain even number of fountains, it is wrong to show them to Arkady.\n\nOstin wants to choose two integers $a ≤ b$ and show only part of each of the gardens that starts at cell $a$ and ends at cell $b$. Of course, only such segments suit Ostin that each garden has either zero or odd number of fountains on this segment. Also, it is necessary that at least one garden has at least one fountain on the segment from $a$ to $b$.\n\nHelp Ostin to find the total length of all such segments, i.e. sum up the value $(b - a + 1)$ for each suitable pair $(a, b)$.",
    "tutorial": "Let's describe an $O((n + m)^{2})$ solution first. Let's try all possible pairs $(a, b)$ and check if they suit us. Let's try all values of $a$ from $1$ to $m$. Let garden $(x, y)$ denote a garden with fountains from $x$ to $y$, and let's say that a garden bans a position $x$ for a fixed $a$ if there is non-zero even number of fountains on the segment $[a, x]$, i.e. the pair $(a, x)$ doesn't suit Ostin due to this garden. Now there are two types of gardens we want consider: gardens of the first type start have form $(x, y)$ where $x < a$, $y  \\ge  a$, and gardens of the second type have form $(x, y)$ where $a  \\le  x  \\le  y$. The gardens of the second type ban such positions equal to $x + 1, x + 3, ...$, and maybe $y, y + 1, y + 2, ..., m$ if $(y - x + 1)$ is even. These positions do not depend on $a$, we can keep an array that tells us how many gardens ban each position of $b$. Initially, we add $1$ to all such positions for each garden, and we remove that $1$ when the $a$ passes beyond the left bound of that garden. Let $R$ be the set of right ends of all gardens of the first type. These gardens ban positions $a + 1, a + 3, ..., x$, where $x$ is bounded by the maximum element in $R$. Also, if there is a value $t$ in $R$ such that $(t - a + 1)$ is even, then all positions $t, t + 1, t + 2, ..., m$ are banned as well. We're interested in the minimum value of $t$ such that $(t - a + 1)$ is even, so, we can keep two separate sets $R_{even}$ and $R_{odd}$ for even and odd values, and look for the minimum in one of them. So, it's easy now to determine if a pair $(a, b)$ is suitable or not. We can try all $b$, check is there is at least one fountain on $[a, b]$ and add $(b - a + 1)$ to the answer if the pair is suitable. Let's improve the solution to $O(n\\log\\left(m+n\\right))$. We can note that each operation that changes banned positions for the second type gardens is a range query over odd or even numbers. So we can handle it with segment tree with range queries. Similarly, the gardens of the first type reduce non-banned positions of each parity to some segment, so we can do a range query to count the number of non-banned positions in the two trees described. The overall complexity is $O(n\\log\\left(m+n\\right))$.",
    "tags": [
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "799",
    "index": "G",
    "title": "Cut the pie",
    "statement": "Arkady reached the $n$-th level in Township game, so Masha decided to bake a pie for him! Of course, the pie has a shape of convex $n$-gon, i.e. a polygon with $n$ vertices.\n\nArkady decided to cut the pie in two equal in area parts by cutting it by a straight line, so that he can eat one of them and give the other to Masha. There is a difficulty because Arkady has already put a knife at some point of the pie, so he now has to cut the pie by a straight line passing trough this point.\n\nHelp Arkady: find a line that passes through the point Arkady has put a knife into and cuts the pie into two parts of equal area, or determine that it's impossible. Your program has to quickly answer many queries with the same pie, but different points in which Arkady puts a knife.",
    "tutorial": "Let's first prove that solution always exists. Define $f( \\alpha )$ as the difference between the area of the polygon part contained in the halfplane with polar angles in range $[ \\alpha ,  \\alpha  +  \\pi ]$ and the area of the polygon part contained in the halfplane with polar angles in range $[ \\alpha  +  \\pi ,  \\alpha  + 2 \\pi ]$. Note that $f(0) = - f( \\pi )$, and since $f$ is a continuous function, it reaches zero somewhere on $[0,  \\pi ]$. The proof leads us to the concept of a solution. If we can compute $f( \\alpha )$ fast, we can do a binary search over $ \\alpha $ to find the root. Computing $f( \\alpha )$ consists of two parts. First, we should find the intersection points of the line with the polygon, it is a known problem which can be solved in $O(n\\log n)$. Second, we should compute the area, and there we can use prefix sums for oriented triangle (the origin and a polygon edge) areas that we use to compute the area of the whole polygon. The only thing we have to add is the oriented area of three new segments, that is easy to compute. The overall complexity is $O(n\\log n\\log\\varepsilon)$, where $ \\epsilon $ is the required precision. Note that the angle precision should be more accurate than the required area precision.",
    "tags": [
      "binary search",
      "data structures",
      "geometry"
    ],
    "rating": 3500
  },
  {
    "contest_id": "801",
    "index": "A",
    "title": "Vicious Keyboard",
    "statement": "Tonio has a keyboard with only two letters, \"V\" and \"K\".\n\nOne day, he has typed out a string $s$ with only these two letters. He really likes it when the string \"VK\" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times \"VK\" can appear as a substring (i. e. a letter \"K\" right after a letter \"V\") in the resulting string.",
    "tutorial": "We can count the number of times the string \"VK\" appears as a substring. Then, we can try to replace each character with \"V\" or \"K\", do the count, and return the maximum such count. Alternatively, we can notice if there are currently $X$ occurrences of \"VK\" in the string, then we can either have $X$ or $X + 1$ after modifying at most one character. Try to see if you can find a necessary and sufficient condition for it being $X + 1$ (or see the second solution.",
    "code": "print (lambda s: s.count(\"VK\") + int(any(x*3 in \"K\" + s + \"V\" for x in \"VK\")))(raw_input())",
    "tags": [
      "brute force"
    ],
    "rating": 1100
  },
  {
    "contest_id": "801",
    "index": "B",
    "title": "Valued Keys",
    "statement": "You found a mysterious function $f$. The function takes two strings $s_{1}$ and $s_{2}$. These strings must consist only of lowercase English letters, and must be the same length.\n\nThe output of the function $f$ is another string of the same length. The $i$-th character of the output is equal to the minimum of the $i$-th character of $s_{1}$ and the $i$-th character of $s_{2}$.\n\nFor example, $f($\"ab\", \"ba\"$)$ = \"aa\", and $f($\"nzwzl\", \"zizez\"$)$ = \"niwel\".\n\nYou found two strings $x$ and $y$ of the same length and consisting of only lowercase English letters. Find any string $z$ such that $f(x, z) = y$, or print -1 if no such string $z$ exists.",
    "tutorial": "First, let's check for impossible cases. If there exists a position $i$ such that the $i$-th character of $x$ is less than the $i$-th character of $y$, then it is impossible. Now, let's assume it's always possible and construct an answer. We can notice that each position is independent, so let's simplify the problem to given two characters $a$ and $b$ with $a > = b$, find a character $c$ such that $min(a, c) = b$. Here, we can choose $c = b$. So, for the original problem, if the answer is possible, we can print $y$.",
    "code": "x,y = raw_input(), raw_input()\nprint all(a>=b for a,b in zip(x,y)) * y or \"-1\"",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "803",
    "index": "A",
    "title": "Maximal Binary Matrix",
    "statement": "You are given matrix with $n$ rows and $n$ columns filled with zeroes. You should put $k$ ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.\n\nOne matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one.\n\nIf there exists no such matrix then output -1.",
    "tutorial": "Let's construct matrix from top to bottom, from left to right. At current step we consider position $(i, j)$. Look at contents of cells $a[i][j]$ and $a[j][i]$. If number of zeroes in them doesn't exceed $k$, then let's fill those cells with ones and decrease $k$ by this number. If $k$ isn't equal to $0$ in the end of algorithm, then there is no answer. Overall complexity: $O(n^{2})$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1400
  },
  {
    "contest_id": "803",
    "index": "B",
    "title": "Distances to Zero",
    "statement": "You are given the array of integer numbers $a_{0}, a_{1}, ..., a_{n - 1}$. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.",
    "tutorial": "Let's divide the solution into two parts: firstly check the closest zero to the left and then the closest zero to the right. After that we can take minimum of these numbers. Initialize distance with infinity. Iterate over array from left to right. If value in current position is $0$ then set distance to $0$, otherwise increase distance by $1$. On each step write value of distance to the answer array. Do the same thing but going from right to left. This will find closest zero to the right. Now you should write minimum of current value of distance and value that's already in answer array. Finally you should retrieve the answer from distances. Overall complexity: $O(n)$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1200
  },
  {
    "contest_id": "803",
    "index": "C",
    "title": "Maximal GCD",
    "statement": "You are given positive integer number $n$. You should create such \\textbf{strictly increasing} sequence of $k$ positive numbers $a_{1}, a_{2}, ..., a_{k}$, that their sum is equal to $n$ and greatest common divisor is maximal.\n\nGreatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.\n\nIf there is no possible sequence then output -1.",
    "tutorial": "Notice that GCD of the resulting sequence is always a divisor of $n$. Now let's iterate over all divisors up to $\\sqrt{n}$. Current divisor is $d$. One of the ways to retrieve resulting sequence is to take $d, 2d, 3d, ..., (k - 1) \\cdot d$, their sum is $s$. The last number is $n - s$. You should check if $n - s > (k - 1) \\cdot d$. $s$ is the sum of arithmetic progression, its equal to $d\\cdot{\\frac{k\\cdot(k-1)}{2}}$. Don't forget that you should consider $d$ and $\\textstyle{\\frac{n}{d}}$, if you check divisors up to $\\sqrt{n}$. Take maximum of possible divisors or output -1 if there were no such divisors. Overall complexity: $O({\\sqrt{n}})$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "803",
    "index": "D",
    "title": "Magazine Ad",
    "statement": "The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:\n\nThere are space-separated non-empty words of lowercase and uppercase Latin letters.\n\nThere are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen.\n\nIt is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word.\n\nWhen the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.\n\nThe ad can occupy no more that $k$ lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.\n\nYou should write a program that will find minimal width of the ad.",
    "tutorial": "Firstly notice that there is no difference between space and hyphen, you can replace them with the same character, if you want. Let's run binary search on answer. Fix width and greedily construct ad - wrap word only if you don't option to continue on the same line. Then check if number of lines doesn't exceed $k$. Overall complexity: $O(|s|\\cdot\\log|s|)$.",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "803",
    "index": "E",
    "title": "Roma and Poker",
    "statement": "Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes $1$ virtual bourle from the loser.\n\nLast evening Roma started to play poker. He decided to spend no more than $k$ virtual bourles — he will stop immediately if the number of his loses exceeds the number of his wins by $k$. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by $k$.\n\nNext morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won $k$ bourles or he lost.\n\nThe sequence written by Roma is a string $s$ consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met:\n\n- In the end the absolute difference between the number of wins and loses is equal to $k$;\n- There is no hand such that the absolute difference before this hand was equal to $k$.\n\nHelp Roma to restore any such sequence.",
    "tutorial": "This problem can be solved using dynamic programming: $dp_{i, j}$ is true if Roma could play first $i$ games with balance $j$. $dp_{0, 0}$ is true; and for each $dp_{i, j}$ such that $0  \\le  i < n$ and $- k < j < k$ we update $dp_{i + 1, j + 1}$ if $s_{i} = W$, $dp_{i + 1, j}$ if $s_{i} = D$, $dp_{i + 1, j - 1}$ if $s_{i} = L$, and all three states if $s_{i} =$ ?. If either of $dp_{n, k}$ and $dp_{n, - k}$ is true, then we can restore the sequence. Time and memory complexity is $O(n \\cdot k)$. As an exercise, you can think about linear solution.",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "803",
    "index": "F",
    "title": "Coprime Subsequences",
    "statement": "Let's call a non-empty sequence of positive integers $a_{1}, a_{2}... a_{k}$ coprime if the greatest common divisor of all elements of this sequence is equal to $1$.\n\nGiven an array $a$ consisting of $n$ positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo $10^{9} + 7$.\n\nNote that two subsequences are considered different if chosen indices are different. For example, in the array $[1, 1]$ there are $3$ different subsequences: $[1]$, $[1]$ and $[1, 1]$.",
    "tutorial": "This problem can be solved using inclusion-exclusion. Let $f(x)$ be the number of subsequences such that all elements of the subsequence are divisible by $x$. We can calculate $cnt(x)$, which is the number of elements divisible by $x$, by factorizing all elements of the sequence and generating their divisors, and $f(x) = 2^{cnt(x)} - 1$. Then we can apply the inclusion-exclusion principle and get the resulting formula: $\\textstyle\\sum_{i=1}^{10^{5}}\\mu(x)f(x)$, where $ \\mu $ is the Möbius function.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "803",
    "index": "G",
    "title": "Periodic RMQ Problem",
    "statement": "You are given an array $a$ consisting of positive integers and $q$ queries to this array. There are two types of queries:\n\n- $1$ $l$ $r$ $x$ — for each index $i$ such that $l ≤ i ≤ r$ set $a_{i} = x$.\n- $2$ $l$ $r$ — find the minimum among such $a_{i}$ that $l ≤ i ≤ r$.\n\nWe decided that this problem is too easy. So the array $a$ is given in a compressed form: there is an array $b$ consisting of $n$ elements and a number $k$ in the input, and before all queries $a$ is equal to the concatenation of $k$ arrays $b$ (so the size of $a$ is $n·k$).",
    "tutorial": "Most of the solutions used the fact that we can read all the queries, compress them and process after the compression using simple segment tree. But there is also an online solution: Let's build a sparse table on array $b$ to answer queries on segments that are not modified in $O(1)$. To process modification segments, we will use implicit segment tree and lazy propagation technique. We do not build the whole segment tree; instead, in the beginning we have only one node for segment $[1, n \\cdot k]$, and if some modification query accesses some node, but does not modify the complete segment this node maintains, only then we create the children of this node. So, the leaves of the segment tree are the nodes such that their segments are completely set to some value or not modified at all. Since each modification query affects only $O(log(n \\cdot k))$ nodes, the resulting complexity will be $O(qlog(n \\cdot k) + nlogn)$.",
    "tags": [
      "data structures"
    ],
    "rating": 2300
  },
  {
    "contest_id": "804",
    "index": "A",
    "title": "Find Amir",
    "statement": "A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.\n\nThere are $n$ schools numerated from $1$ to $n$. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools $i$ and $j$ costs $(i+j)\\operatorname*{mad}\\left(n+1\\right)$ and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.",
    "tutorial": "Consider pairs of schools cost of their traverse is $0$: $\\{1,n\\},\\;\\{2,n-1\\},\\;\\{3,n-2\\}\\ldots,\\;\\{\\lfloor{\\frac{x}{2}}\\},\\;\\}{\\frac{x}{2}}\\}+1\\}$. Connect this pairs with traversing from the second of each pair to the first of the next pair. So if $n = 2 \\cdot k$ the answer is $k - 1$ and if $n = 2 \\cdot k + 1$ the answer is $k$. The minimum number of direct paths should be $n - 1$, so because of using all of $0$s and make the other direct paths with $1$s the path is minimum possible spanning tree. From: saliii, Writer: saliii Time Complexity: $O(1)$ Time Complexity: $O(1)$ Memory complexity: $O(1)$",
    "code": "int main(){\n\tint n;\n\tscanf(\"%d\", &n);\n\tprintf(\"%d\\n\", (n-1)/2);\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "804",
    "index": "B",
    "title": "Minimum number of steps",
    "statement": "We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings \"ab\" in the string and replace it with the string \"bba\". If we have no \"ab\" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo $10^{9} + 7$.\n\nThe string \"ab\" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.",
    "tutorial": "The final state will be some character $'a'$ after $'b'$: $\"bbb...baaa...a\"$ It's obvious to prove all $'b'$s are distinctive to each other(i.e. Each $'b'$ in the initial state, will add some number of $'b'$s to the final state disjoint from other $'b'$s). For a character $'b'$ from the initial state it will double after seeing a character $'a'$. For each $i$-th character $'b'$, consider $t_{i}$ the number of $a$ before it. So the final number of $'b'$s can be defined as $\\textstyle\\sum_{i}2^{l_{i}}$. From: MohammadJA, Writer: MohammadJA Time Complexity: $O(1)$ Time Complexity: ${\\cal O}(n)$ Memory complexity: ${\\mathcal{O}}(n)$",
    "code": "int c,d,i,n,m,k,x,j=1000000007;\nstring s;\nmain(){\n\tcin>>s;\n\tfor(i=s.size()-1;i>=0;i--){\n\t\tif(s[i]=='b')c++;else{\n\t\t\tk+=c;c*=2;k%=j;c%=j;\n\t\t}\n\t}\n\tcout<<k;\n}",
    "tags": [
      "combinatorics",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "804",
    "index": "C",
    "title": "Ice cream coloring",
    "statement": "Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: \"Can you solve a problem I'm stuck at all day?\"\n\nWe have a tree $T$ with $n$ vertices and $m$ types of ice cream numerated from $1$ to $m$. Each vertex $i$ has a set of $s_{i}$ types of ice cream. Vertices which have the $i$-th ($1 ≤ i ≤ m$) type of ice cream form a connected subgraph. We build a new graph $G$ with $m$ vertices. We put an edge between the $v$-th and the $u$-th ($1 ≤ u, v ≤ m$, $u ≠ v$) vertices in $G$ if and only if there exists a vertex in $T$ that has both the $v$-th and the $u$-th types of ice cream in its set. The problem is to paint the vertices of $G$ with minimum possible number of colors in a way that no adjacent vertices have the same color.\n\nPlease note that we consider that empty set of vertices form a connected subgraph in this problem.\n\nAs usual, Modsart don't like to abandon the previous problem, so Isart wants you to solve the new problem.",
    "tutorial": "Let's guess as obvious as possible. We can get the answer is at least $\\begin{array}{r}{\\mathbf{Hax}\\mathbf{S}{\\hat{z}}_{i}}\\\\ {\\mathbf{k}{\\hat{-}}i\\leq n}\\end{array}$.We'll just use a dfs to paint the graph with this answer. Run dfs and in each step, when we are in vertex $v$ with parent $par$, for each ice cream, if it is in the set of $par$, then its color is given in the par's set. If not, we'll paint it with a color that isn't used in this set. To prove the algorithm works, assume the first step we paint an ice cream by $(answer + 1)$-th color, you know the number of ice creams is at last equal to answer, some of these ice creams was painted in the par's set and obviously we don't need to more than $sz_{v}$ color to paint them. From: saliii, Writer: saliii Time Complexity: $O(n+\\sum_{i}s_{i}\\cdot\\log(\\sum_{i}s_{i}))$ Memory complexity: $O(n+\\sum_{i}s i)$ Time Complexity: $O(n+\\sum_{i}s_{i})$ Memory complexity: $O(n+\\sum_{i}s i)$",
    "code": "vector <int> Vs[300050];\nvector <int> conn[300050];\n\nint ans[300050];\nbool chk[500050];\nbool dchk[300050];\nvector <int> Vu;\nvoid DFS(int n) {\n\tdchk[n] = true;\n\n\tfor (auto it : Vs[n]) {\n\t\tif (ans[it]) chk[ans[it]] = true;\n\t\telse Vu.push_back(it);\n\t}\n\n\tint a = 1;\n\tfor (auto it : Vu) {\n\t\twhile (chk[a]) a++;\n\t\tans[it] = a++;\n\t}\n\tfor (auto it : Vs[n]) chk[ans[it]] = false;\n\tVu.clear();\n\n\tfor (auto it : conn[n]) {\n\t\tif (dchk[it]) continue;\n\t\tDFS(it);\n\t}\n}\nint main() {\n\tint N, M, i;\n\tscanf(\"%d %d\", &N, &M);\n\tfor (i = 1; i <= N; i++) {\n\t\tint t1, t2;\n\t\tscanf(\"%d\", &t1);\n\t\twhile (t1--) {\n\t\t\tscanf(\"%d\", &t2);\n\t\t\tVs[i].push_back(t2);\n\t\t}\n\t}\n\tfor (i = 1; i < N; i++) {\n\t\tint t1, t2;\n\t\tscanf(\"%d %d\", &t1, &t2);\n\t\tconn[t1].push_back(t2);\n\t\tconn[t2].push_back(t1);\n\t}\n\tDFS(1);\n\n\tint mx = 0;\n\tfor (i = 1; i <= M; i++) {\n\t\tmx = max(mx, ans[i]);\n\t\tif (ans[i] == 0) ans[i] = 1;\n\t}\n\tmx = max(mx, 1);\n\tprintf(\"%d\\n\", mx);\n\tfor (i = 1; i <= M; i++) printf(\"%d \", ans[i]);\n\t\n\treturn !printf(\"\\n\");\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "804",
    "index": "D",
    "title": "Expected diameter of a tree",
    "statement": "Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem.\n\nWe have a forest (acyclic undirected graph) with $n$ vertices and $m$ edges. There are $q$ queries we should answer. In each query two vertices $v$ and $u$ are given. Let $V$ be the set of vertices in the connected component of the graph that contains $v$, and $U$ be the set of vertices in the connected component of the graph that contains $u$. Let's add an edge between some vertex $a\\in V$ and some vertex in $b\\in U$ and compute the value $d$ of the resulting component. If the resulting component is a tree, the value $d$ is the diameter of the component, and it is equal to -1 otherwise. What is the expected value of $d$, if we choose vertices $a$ and $b$ from the sets uniformly at random?\n\nCan you help Pasha to solve this problem?\n\nThe diameter of the component is the maximum distance among some pair of vertices in the component. The distance between two vertices is the minimum number of edges on some path between the two vertices.\n\nNote that queries don't add edges to the initial forest.",
    "tutorial": "Let's solve the problem for two trees. Define $d_{t}$ as diameter of $t$-th tree and $f_{ti}$ as the maximum path starting from $i$-th vertex of $t$-th tree, for all valid $i$ and $j$, assume that the edge is between them and find the diameter with $max(f_{1i} + f_{2j} + 1, max(d_{1}, d_{2}))$. The answer will be: $\\frac{\\sum\\sum\\operatorname*{max}(f_{1_{i}}+f_{2_{j}+1,\\operatorname*{max}(d_{1},d_{2}))}}{s z_{1}.s z_{2}}$ Let's improve the $O(n^{2})\\,$ solution to $O(n\\cdot\\log\\left(n\\right))$. Let's sort the arrays $f_{1}$ and $f_{2}$ decreasingly and make two partial sums of them, $p_{1}$ and $p_{2}$, such that $p_{t_{i}}=\\sum_{j=1}^{t-1}f_{t_{j}}$. Iterate on $f_{t}$, in step $i$, we will check all of the valid edges which $i$-th vertex is an endpoint of that: Consider the first element in $f_{1 - t}$ as $j$ such that $f_{ti} + f_{(1 - t)j} > max(d_{1}, d_{2})$, by binary search, according to the previous solution for $i$-th step, we should add it to the answer: $p_{(1 - t)j} + n - j - 1 \\cdot max(d_{1}, d_{2})$ Let's prove if in each query, we choose $t$, the smaller tree, the solution will be accepted. There is two simple modes we should consider: $1$- If $\\operatorname*{min}(s z_{1},s z_{2})<{\\sqrt{(}}n)$: The time complexity will be $O(\\sqrt{(n)}\\cdot\\log(n)$ per query. $2$- If $\\operatorname*{min}(s z_{1},s z_{2})\\geq{\\sqrt{(n)}}$: Number of trees with $s z\\geq{\\sqrt{(}}n)$ is at last ${\\sqrt{(}}n\\mathbf{)}$. If we don't calculate the answer for two same pairs of vertices by memoization, at last ${\\sqrt{(}}n\\mathbf{)}$ time we need to these bigger trees, so it yields $O(\\sum s z_{i}\\cdot{\\sqrt{(}}n)\\cdot\\log(n))=O(n\\cdot{\\sqrt{(}}n)\\cdot\\log(n))$. From: MohammadJA, Writer: MohammadJA Time Complexity: $O(q\\cdot{\\sqrt{(}}(n)\\cdot\\log(n)+n\\cdot{\\sqrt{(}}n)\\cdot\\log(n))$ Memory complexity: ${\\mathcal{O}}(n)$",
    "code": "using namespace std ;\n\n#define int long long\n\nconst int MAXN = 1e5 + 100 ;\n\nvector<int>ver[MAXN] , com[MAXN] , ps[MAXN] ; \nint vis[MAXN] , dis[MAXN] ; \nint mxr , mxid ; \nvoid dfs(int v , int col = -1 , int h = 0 , int par = -1){\n\tvis[v] = max(vis[v] , col) ; \n\tif(mxr < h)mxid = v , mxr = h ; \n\tdis[v] = max(h , dis[v]) ; \n\tif(col > 0)com[col] . push_back(dis[v]) ; \n\tfor(auto u : ver[v]){\n\t\tif(u == par)continue ; \n\t\tdfs(u , col , h + 1 , v) ; \n\t}\n}\nmap<pair<int , int> , int> check ;\nint32_t main(){\n    ios_base::sync_with_stdio(0) ;\n    cin . tie(0) ; cout . tie(0) ;\n    int n , m , q ; cin >> n >> m >> q ; \n    for(int i = 0 ; i < m ; i ++){\n    \tint x , y ; cin >> x >> y ; \n    \tx -- , y -- ; \n    \tver[x] . push_back(y) ; \n    \tver[y] . push_back(x) ;\n    }\n    int cnt = 0 ; \n    for(int i = 0 ; i < n ; i ++){\n    \tif(vis[i])continue ; \n    \tmxr = 0 , mxid = i ; \n    \tdfs(i) ; \n    \tmxr = 0 ; \n    \tdfs(mxid) ;\n    \tdfs(mxid , ++ cnt) ; sort(com[cnt] . begin() , com[cnt] . end()) ; \n    \tps[cnt] . push_back(0) ; \n    \tfor(auto v : com[cnt])ps[cnt] . push_back(ps[cnt] . back() + v) ; \n    }\n\tcout << fixed << setprecision(10) ;\n    while(q --){\n    \tint x , y ; cin >> x >> y ; \n    \tx -- , y -- ; x = vis[x] ; y = vis[y] ; \n    \tif(com[x] . size() > com[y] . size())swap(x , y) ; \n    \tif(x == y){cout << -1 << '\\n' ; continue ; }\n    \tif(check[{x , y}] > 0){cout << double(check[{x , y}]) / (1ll * com[x] . size() * com[y] . size()) << '\\n' ; continue ; }\n    \tint ans = 0 , mxd = max(com[x] . back() , com[y] . back()) ; \n    \tfor(auto v : com[x]){\n    \t\tint num = lower_bound(com[y] . begin() , com[y] . end() , mxd - v - 1) - com[y] . begin() ; \n    \t\tans += num * mxd + (com[y] . size() - num) *  (v + 1) + ps[y] . back() - ps[y][num] ; \n    \t}\n    \tcheck[{x , y}] = ans ; \n    \tcout << double(check[{x , y}]) / (1ll * com[x] . size() * com[y] . size()) << '\\n' ; \n    }\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "dfs and similar",
      "dp",
      "sortings",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "804",
    "index": "E",
    "title": "The same permutation ",
    "statement": "Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions $(i, j)$, where $i < j$, exactly once. MoJaK doesn't like to upset Sajjad.\n\nGiven the permutation, determine whether it is possible to swap all pairs of positions so that the permutation stays the same. If it is possible find how to do that.",
    "tutorial": "If $\\textstyle{{\\binom{n}{2}}\\mod2=1}$ then it is simply provable the answer is \"NO\". So we just need to check $n = 4 \\cdot k, 4 \\cdot k + 1$. There is a constructive solution to do that. Assume that $n = 4 \\cdot k$. Partition numbers to $k$ classes, each class contains a $4$ consecutive numbers. We can solve each class itself by these swaps to reach the same permutation: $(3, 4) (1, 3) (2, 4) (2, 3) (1, 4) (1, 2)$ We can do swaps between two different classes as follows to reach the same permutation, assume that the first element of the first class is $i$ and for the second class is $j$: $(i + 3, j + 2) (i + 2, j + 2) (i + 3, j + 1) (i, j + 1) (i + 1, j + 3) (i + 2, j + 3) (i + 1, j + 2) (i + 1, j + 1)$ $(i + 3, j) (i + 3, j + 3) (i, j + 2) (i, j + 3) (i + 2, j) (i + 2, j + 1) (i + 1, j) (i, j)$ Now assume that $n = 4 \\cdot k + 1$. Do the swaps above with first $4 \\cdot k$ numbers with these changes in place of swaps in the classes itself to satisfy the last number: $(3, n) (3, 4) (4, n) (1, 3) (2, 4) (2, 3) (1, 4) (1, n) (1, 2) (2, n)$ From: saliii, Writer: saliii Time Complexity: $O(n^{2})\\,$ Memory complexity: $O(1)$",
    "code": "int n;\n\nint main()\n{\n\tscanf(\"%d\",&n);\n\tif(n%4>1)return printf(\"NO\\n\"),0;\n\tprintf(\"YES\\n\");\n\tfor(int i=1;i<n;i+=4)\n\t{\n\t\tif(n%4)printf(\"%d %d\\n%d %d\\n%d %d\\n\",i+2,n,i+2,i+3,i+3,n);\n\t\telse printf(\"%d %d\\n\",i+2,i+3);\n\t\tprintf(\"%d %d\\n\",i,i+2);\n\t\tprintf(\"%d %d\\n\",i+1,i+3);\n\t\tprintf(\"%d %d\\n\",i+1,i+2);\n\t\tprintf(\"%d %d\\n\",i,i+3);\n\t\tif(n%4)printf(\"%d %d\\n%d %d\\n%d %d\\n\",i,n,i,i+1,i+1,n);\n\t\telse printf(\"%d %d\\n\",i,i+1);\n\t}\n\tfor(int i=1;i<n;i+=4)\n\t\tfor(int j=i+4;j<n;j+=4)\n\t\t{\n\t\t\tprintf(\"%d %d\\n\",i+3,j+2);\n\t\t\tprintf(\"%d %d\\n\",i+2,j+2);\n\t\t\tprintf(\"%d %d\\n\",i+3,j+1);\n\t\t\tprintf(\"%d %d\\n\",i,j+1);\n\t\t\tprintf(\"%d %d\\n\",i+1,j+3);\n\t\t\tprintf(\"%d %d\\n\",i+2,j+3);\n\t\t\tprintf(\"%d %d\\n\",i+1,j+2);\n\t\t\tprintf(\"%d %d\\n\",i+1,j+1);\n\t\t\tprintf(\"%d %d\\n\",i+3,j);\n\t\t\tprintf(\"%d %d\\n\",i+3,j+3);\n\t\t\tprintf(\"%d %d\\n\",i,j+2);\n\t\t\tprintf(\"%d %d\\n\",i,j+3);\n\t\t\tprintf(\"%d %d\\n\",i+2,j);\n\t\t\tprintf(\"%d %d\\n\",i+2,j+1);\n\t\t\tprintf(\"%d %d\\n\",i+1,j);\n\t\t\tprintf(\"%d %d\\n\",i,j);\n\t\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3100
  },
  {
    "contest_id": "804",
    "index": "F",
    "title": "Fake bullions",
    "statement": "In Isart people don't die. There are $n$ gangs of criminals. The $i$-th gang contains $s_{i}$ evil people numerated from $0$ to $s_{i} - 1$. Some of these people took part in a big mine robbery and picked \\textbf{one} gold bullion each (these people are given in the input). That happened $10^{100}$ years ago and then all of the gangs escaped to a remote area, far from towns.\n\nDuring the years, they were copying some gold bullions according to an organized plan in order to not get arrested. They constructed a \\textbf{tournament} directed graph (a graph where there is exactly one directed edge between every pair of vertices) of gangs (the graph is given in the input). In this graph an edge from $u$ to $v$ means that in the $i$-th hour the person $i\\mathrm{~mod~}s_{n}$ of the gang $u$ can send a fake gold bullion to person $i\\mathrm{~mod~}s_{n}$ of gang $v$. He sends it if he has some bullion (real or fake), while the receiver doesn't have any. Thus, at any moment each of the gangsters has zero or one gold bullion. Some of them have real bullions, and some of them have fake ones.\n\nIn the beginning of this year, the police has finally found the gangs, but they couldn't catch them, as usual. The police decided to open a jewelry store so that the gangsters would sell the bullions. Thus, every gangster that has a bullion (fake or real) will try to sell it. If he has a real gold bullion, he sells it without problems, but if he has a fake one, there is a choice of two events that can happen:\n\n- The person sells the gold bullion successfully.\n- The person is arrested by police.\n\nThe power of a gang is the number of people in it that successfully sold their bullion. After all selling is done, the police arrests $b$ gangs out of top gangs. Sort the gangs by powers, we call the first $a$ gang top gangs(you can sort the equal powers in each order). Consider all possible results of selling fake gold bullions and all possible choice of $b$ gangs among the top gangs. Count the number of different sets of these $b$ gangs modulo $10^{9} + 7$. Two sets $X$ and $Y$ are considered different if some gang is in $X$ and isn't in $Y$.",
    "tutorial": "As the hints said this problem have two part: First we want to solve the first part that is evaluating the $mn_{i}$ and $mx_{i}$ for gangs. Obviously $mn_{i}$ will be the number of thieves have a gold in $i$-th gang. $lemma1$:Consider there is just a single edge from $v$ to $u$; as hints said if one thief in $v$ with index $i$ has a gold it copied its gold to every $j$ in $u$ if and only if $i\\mathrm{\\boldmath~\\nod~}g c d(s_{v},s_{u})=j\\;\\;\\mathrm{\\boldmath~\\nod~}g c d(s_{v},s_{u})$ . Now we call $f(v, g)$ that $g|sz_{v}$ as a gang with size $g$ that thief number $i$ has a gold in this gang if and only if one of the thiefs with index $j$ in $v$-th gang has a gold such that $jmod g=i$. $lemma2$: Consider two edge like $v\\sim u$ and $u\\sim w$. as thing said in hints and above we can consider that $v$ affect in $w$ like this edge: $f(v,g c d(s z_{v},s z_{u}))\\sim w$. $lemma3$: Consider a directed walk like $w_{1}, w_{2}, , ..., w_{n}$. from two last lemmas we can consider the affect of $w_{1}$ on $w_{n}$ as: $f(w_{1},g c d(w_{1},w_{2},\\ldots,w_{n}))\\sim w_{n}$ $lemma4$: Consider a closed directed walk from $v$ like $v, w_{1}, w_{2}, ..., w_{n}, v$ from three last lemmas we can consider $m x_{v}=m x_{u}\\cdot{\\frac{s_{\\mathrm{{B}}}}{s_{\\mathrm{{a}}}}}$ in which u is $f(v, gcd(v, w_{1}, w_{2}, ..., w_{n}))$. So now decompose graph of gangs to maximal strongly connected components from $lemma4$ for every component like $a_{1}, a_{2}, ..., a_{n}$, we can consider in place of all of them gang $v$ with size equal to $g = gcd(a_{1}, a_{2}, ..., a_{n})$ such that $i$-th thief has a gold in $v$ if and only if there is a $j$ such that $i$-th thief in $f(a_{j}, g)$ has a gold. So we decreased the problem to a dag tournament, Let's sort the vertices with topological sort. We'll find a Hamiltonian path of vertices such that for every different $i$ and $j$ there is directed edge from $i$-th vertex of the path to $j$-th vertex of the path if and only if $i < j$. By the lemma 2 it's sufficient to solve the problem for the path itself. So we decreased the problem to a only path. For the path, just do greedily, for each $i$ from $1$ to $n$ affect the $i$-th vertex on the $i + 1$-th vertex, it can be done with complexity $O(\\sum_{i=1}^{n}s_{i})$. So $mx_{i}$ is equal to the number of ones after doing all of the things. For every vertex we'll consider a $mx_{i}$ and $mn_{i}$.We sort this scores in an array T. $|T| = 2 \\cdot n$. Starting from biggest to smallest one. When we reach maximum of $i$-th vertex and, we fix this vertex and count number of sets he is in which and it has the minimum score of the set: There is two kinds of vertices, $q$ element of array $mn$ are more than or equal to $mn_{i}$, and of the others, $p$ elements of array $mx$ are more than $mx_{i}$(means if $j$-th vertex is in the second kind then $mn_{i}  \\le  mx_{i} < mx_{j}$. So we have to fix number of second kind of vertices as $j$($1  \\le  j  \\le  min(b - 1, p)$) and for all $j$ do this: $\\mathrm{~f~}(q+j<a)~a n s=a n s+(\\underline{{{p}}})\\cdot\\left(\\l_{B-1-j}\\right)$ It is clear when we fix maximum of $j$-th and $i$-th vertex as the minimum score of the set, we didn't count one such sets twice and when fixing $i$-th vertex the fact holds. Also it is clear we count all of the situations. The complexity of this part is $O(n\\cdot b)$. From: saliii, Writer: amsen Time Complexity: $O(\\sum_{i}s_{i}+n\\cdot b)$ Memory complexity: $O(n^{2}+\\sum_{i}s_{i})$",
    "code": "#include <bits/stdc++.h>\n#define xx first\n#define yy second\n#define mp make_pair\n#define pb push_back\n#define fill( x, y ) memset( x, y, sizeof x )\n#define copy( x, y ) memcpy( x, y, sizeof x )\nusing namespace std;\n\ntypedef long long LL;\ntypedef pair < int, int > pa;\n\ninline int read()\n{\n\tint sc = 0, f = 1; char ch = getchar();\n\twhile( ch < '0' || ch > '9' ) { if( ch == '-' ) f = -1; ch = getchar(); }\n\twhile( ch >= '0' && ch <= '9' ) sc = sc * 10 + ch - '0', ch = getchar();\n\treturn sc * f;\n}\n\nconst int MAXN = 5005;\nconst int MAXM = 2000005;\nconst int mod = 1e9 + 7;\n\nint n, a, b, len[MAXN], can[MAXM], id_cnt, L[MAXN], R[MAXN], C[MAXN][MAXN];\nint dfn[MAXN], scc[MAXN], low[MAXN], tim, num, st[MAXN], top, w[MAXN], ans;\nvector < int > G[MAXN], id[MAXN], scc_bit[MAXN], v[MAXN];\nchar ch[MAXM];\n\ninline void inc(int &x, int y) { x += y; if( x >= mod ) x -= mod; }\n\ninline void dfs(int x)\n{\n\tdfn[ x ] = low[ x ] = ++tim; st[ ++top ] = x;\n\tfor( auto y : G[ x ] )\n\t\tif( !dfn[ y ] ) dfs( y ), low[ x ] = min( low[ x ], low[ y ] );\n\t\telse if( !scc[ y ] ) low[ x ] = min( low[ x ], dfn[ y ] );\n\tif( dfn[ x ] == low[ x ] )\n\t{\n\t\tnum++; int t = 0;\n\t\twhile( t ^ x )\n\t\t{\n\t\t\tscc[ t = st[ top-- ] ] = num;\n\t\t\tw[ num ] = __gcd( w[ num ], len[ t ] );\n\t\t\tv[ num ].pb( t );\n\t\t}\n\t\tscc_bit[ num ].resize( w[ num ] );\n\t\tfor( auto y : v[ num ] )\n\t\t\tfor( int d = 0 ; d < len[ y ] ; d++ ) if( can[ id[ y ][ d ] ] ) scc_bit[ num ][ d % w[ num ] ] = 1;\n\t}\n}\n\nint main()\n{\n#ifdef wxh010910\n\tfreopen( \"data.in\", \"r\", stdin );\n#endif\n\tn = read(), a = read(), b = read();\n\tfor( int i = 0 ; i <= n ; i++ )\n\t{\n\t\tC[ i ][ 0 ] = 1;\n\t\tfor( int j = 1 ; j <= i ; j++ ) inc( C[ i ][ j ] = C[ i - 1 ][ j ], C[ i - 1 ][ j - 1 ] );\n\t}\n\tfor( int i = 1 ; i <= n ; i++ )\n\t{\n\t\tscanf( \"%s\", ch + 1 );\n\t\tfor( int j = 1 ; j <= n ; j++ ) if( ch[ j ] == '1' ) G[ i ].pb( j );\n\t}\n\tfor( int i = 1 ; i <= n ; i++ )\n\t{\n\t\tlen[ i ] = read(); scanf( \"%s\", ch );\n\t\tfor( int j = 0 ; j < len[ i ] ; j++ ) id[ i ].pb( ++id_cnt ), can[ id_cnt ] = ch[ j ] == '1', L[ i ] += can[ id_cnt ];\n\t}\n\tfor( int i = 1 ; i <= n ; i++ ) if( !dfn[ i ] ) dfs( i );\n\tfor( int i = num ; i > 1 ; i-- )\n\t{\n\t\tint g = __gcd( w[ i ], w[ i - 1 ] );\n\t\tw[ i - 1 ] = g;\n\t\tfor( int j = 0 ; j < w[ i ] ; j++ )\tscc_bit[ i - 1 ][ j % g ] |= scc_bit[ i ][ j ];\n\t}\n\tfor( int i = 1 ; i <= n ; i++ )\n\t{\n\t\tint x = scc[ i ];\n\t\tfor( int j = 0 ; j < len[ i ] ; j++ )\n\t\t\tR[ i ] += scc_bit[ x ][ j % w[ x ] ];\n\t}\n\tfor( int i = 1 ; i <= n ; i++ )\n\t{\n\t\tint t1 = 0, t2 = 0;\n\t\tfor( int j = 1 ; j <= n ; j++ ) if( L[ j ] > R[ i ] ) t1++;\n\t\tif( t1 >= a ) continue;\n\t\tfor( int j = 1 ; j <= n ; j++ ) if( L[ j ] <= R[ i ] && mp( R[ j ], j ) > mp( R[ i ], i ) ) t2++;\n\t\tfor( int j = 0 ; j < b && j <= t2 && j + t1 < a ; j++ )\n\t\t   inc( ans, 1LL * C[ t2 ][ j ] * C[ t1 ][ b - j - 1 ] % mod );\t\n\t}\n\treturn printf( \"%d\\n\", ans ), 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "graphs",
      "number theory"
    ],
    "rating": 3400
  },
  {
    "contest_id": "805",
    "index": "A",
    "title": "Fake NP",
    "statement": "Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.\n\nYou are given $l$ and $r$. For all integers from $l$ to $r$, inclusive, we wrote down all of their integer divisors except $1$. Find the integer that we wrote down the maximum number of times.\n\nSolve the problem to show that it's not a NP problem.",
    "tutorial": "If $l  \\le  r$ the answer is 2, other wise l. To prove this phrase, assume the answer is $x$ ($2 < x$), consider all of multiples of $x$ from $l$ to $r$ as $z_{1}, z_{2}, ..., z_{k}$. If $k = = 1$, $2$ is also a correct answer, otherwise numbers from $l$ to $z_{2} - 1$ make at least $3$ even number, and for each multiple from $z_{2}$ to $z_{k - 1}$ as $Z$, $Z$ or $Z + 1$ is even, so 2 is also a correct answer. Bounce: Find the maximum number, occurs maximum number of times in the segment. From: saliii, Writer: saliii Time Complexity: $O(1)$ Memory complexity: $O(1)$",
    "code": "int main(){\n    int l, r;\n    scanf(\"%d%d\", &l, &r);\n    printf(\"%d\", l == r ? l : 2);\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "805",
    "index": "B",
    "title": "3-palindrome",
    "statement": "In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.\n\nHe is too selfish, so for a given $n$ he wants to obtain a string of $n$ characters, each of which is either 'a', 'b' or 'c', with no palindromes of length $3$ appearing in the string as a substring. For example, the strings \"abc\" and \"abca\" suit him, while the string \"aba\" doesn't. He also want the number of letters 'c' in his string to be as little as possible.",
    "tutorial": "The answer is constructive as follows: $\"aabbaabbaabb...\"$ From: saliii, Writer: saliii Time Complexity: $O(1)$ Time Complexity: ${\\mathcal{O}}(n)$ Memory complexity: ${\\mathcal{O}}(n)$",
    "code": "int N;\nint main()\n{\n\tscanf(\"%d\", &N);\n\tfor (int i = 0; i < N; i++)\n\t\tputchar(i & 2 ? 'b' : 'a');\n\tputs(\"\");\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "807",
    "index": "A",
    "title": "Is it rated?",
    "statement": "\\underline{Is it rated?}\n\nHere it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.\n\nAnother Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.\n\nIt's known that if at least one participant's rating has changed, then the round was rated for sure.\n\nIt's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.\n\nIn this problem, you should not make any other assumptions about the rating system.\n\nDetermine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.",
    "tutorial": "To solve this problem, you just had to read the problem statement carefully. Looking through the explanations for the example cases was pretty useful. How do we check if the round is rated for sure? The round is rated for sure if anyone's rating has changed, that is, if $a_{i}  \\neq  b_{i}$ for some $i$. How do we check if the round is unrated for sure? Given that all $a_{i} = b_{i}$, the round is unrated for sure if for some $i < j$ we have $a_{i} < a_{j}$. This can be checked using two nested for-loops over $i$ and $j$. Exercise: can you check the same using one for-loop? How do we find that it's impossible to determine if the round is rated or not? If none of the conditions from steps 1 and 2 is satisfied, the answer is \"maybe\".",
    "code": "n = int(input())\nresults = []\nfor i in range(n):\n    results.append(list(map(int, input().split())))\n\nfor r in results:\n    if r[0] != r[1]:\n        print(\"rated\")\n        exit()\n\nfor i in range(n):\n    for j in range(i):\n        if results[i][0] > results[j][0]:\n            print(\"unrated\")\n            exit()\n\nprint(\"maybe\")",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "807",
    "index": "B",
    "title": "T-Shirt Hunt",
    "statement": "Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.\n\nUnfortunately, you didn't manage to get into top 25, but you got into top 500, taking place $p$.\n\nNow the elimination round of 8VC Venture Cup 2017 is being held. It has been announced that the Codecraft-17 T-shirt winners will be chosen as follows. Let $s$ be the number of points of the winner of the elimination round of 8VC Venture Cup 2017. Then the following pseudocode will be executed:\n\n\\begin{verbatim}\ni := (s div 50) mod 475\nrepeat 25 times:\ni := (i * 96 + 42) mod 475\nprint (26 + i)\n\\end{verbatim}\n\nHere \"div\" is the integer division operator, \"mod\" is the modulo (the remainder of division) operator.\n\nAs the result of pseudocode execution, 25 integers between 26 and 500, inclusive, will be printed. These will be the numbers of places of the participants who get the Codecraft-17 T-shirts. It is guaranteed that the 25 printed integers will be pairwise distinct for any value of $s$.\n\nYou're in the lead of the elimination round of 8VC Venture Cup 2017, having $x$ points. You believe that having at least $y$ points in the current round will be enough for victory.\n\nTo change your final score, you can make any number of successful and unsuccessful hacks. A successful hack brings you 100 points, an unsuccessful one takes 50 points from you. It's difficult to do successful hacks, though.\n\nYou want to win the current round and, at the same time, ensure getting a Codecraft-17 T-shirt. What is the smallest number of \\textbf{successful} hacks you have to do to achieve that?",
    "tutorial": "This problem was inspired by this comment: http://codeforces.com/blog/entry/49663#comment-337281. The hacks don't necessarily have to be stupid, though :) Initially, we have $x$ points. To win the current round, we need to score any number of points $s$ such that $s  \\ge  y$. If we know our final score $s$, we can check if we get the T-shirt using the given pseudocode. Moreover, since hacks change our score only by multiples of 50, the difference $s - x$ has to be divisible by 50. Naturally, out of all $s$ satisfying the conditions above, we need to aim at the smallest possible $s$, since it's easy to decrease our score, but difficult to increase. How many successful hacks do we need to make our score equal to $s$? If $s  \\le  x$, we need 0 successful hacks, since we can just make $(x - s) / 50$ unsuccessful hacks. If $s > x$ and $s - x$ is divisible by 100, we need exactly $(s - x) / 100$ successful hacks. If $s > x$ and $s - x$ is not divisible by 100, we need $(s - x + 50) / 100$ successful hacks and one unsuccessful hack. All these cases can be described by a single formula for the number of successful hacks: $(max(0, s - x) + 50) / 100$ (here \"$/$\" denotes integer division). The constraints were low enough, and the number of required hacks was also low enough. A less effective but easier solution can be achieved if we just iterate over both the number of successful and unsuccessful hacks we make. Once we know these two numbers, we know our final score $s$ and we can explicitly check if this score gives us both the victory and the T-shirt.",
    "code": "p, x, y = map(int, input().split())\n\ndef check(s):\n    i = (s // 50) % 475\n    for t in range(25):\n        i = (i * 96 + 42) % 475\n        if 26 + i == p:\n            return True\n    return False\n\nfor up in range(500):\n    for down in range(500):\n        if x + 100 * up - 50 * down >= y and check(x + 100 * up - 50 * down):\n            print(up)\n            exit()\n\nassert(False)",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "808",
    "index": "A",
    "title": "Lucky Year",
    "statement": "Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.\n\nYou are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.",
    "tutorial": "Notice that the next lucky year always looks like (first digit of the current + 1) $ \\cdot $ 10^(number of digits of the current - 1). It holds also for numbers starting with 9, it will be 10 $ \\cdot $ 10^(number of digits - 1). The answer is the difference between the next lucky year and current year.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "808",
    "index": "B",
    "title": "Average Sleep Time",
    "statement": "It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts $k$ days!\n\nWhen Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last $n$ days. So now he has a sequence $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the sleep time on the $i$-th day.\n\nThe number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider $k$ consecutive days as a week. So there will be $n - k + 1$ weeks to take into consideration. For example, if $k = 2$, $n = 3$ and $a = [3, 4, 7]$, then the result is ${\\frac{(3+4)+(4+7)}{2}}=9$.\n\nYou should write a program which will calculate average sleep times of Polycarp over all weeks.",
    "tutorial": "To get the sum for $i$-th week you need to take sum of ($i - 1$)-th week, subtract first element of ($i - 1$)-th week from it and add up last element of $i$-th week. All common elements will remain. Thus by moving right week by week calculate sum of all weeks and divide it by $n - k + 1$. Overall complexity: $O(n)$.",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "808",
    "index": "C",
    "title": "Tea Party",
    "statement": "Polycarp invited all his friends to the tea party to celebrate the holiday. He has $n$ cups, one for each of his $n$ friends, with volumes $a_{1}, a_{2}, ..., a_{n}$. His teapot stores $w$ milliliters of tea ($w ≤ a_{1} + a_{2} + ... + a_{n}$). Polycarp wants to pour tea in cups in such a way that:\n\n- Every cup will contain tea for at least half of its volume\n- Every cup will contain integer number of milliliters of tea\n- All the tea from the teapot will be poured into cups\n- All friends will be satisfied.\n\nFriend with cup $i$ won't be satisfied, if there exists such cup $j$ that cup $i$ contains less tea than cup $j$ but $a_{i} > a_{j}$.\n\nFor each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.",
    "tutorial": "At first, let's pour minimal amount of tea in each cup, that is $\\left|{\\frac{a_{1}}{2}}\\right|$. If it requires more tea than available then it's -1. Now let's sort cups in non-increasing order by volume and start filling up them until we run out of tea in the teapot. It's easy to see that everyone will be satisfied that way. If sequence of $a_{i}$ is non-increasing then sequence of $\\left|{\\frac{a_{1}}{2}}\\right|$ is also non-increasing. So we can't make someone unsatisfied by filling the cup with maximal possible volume. And finally get the right order of cups back and print the answer. Overall complexity: $O(n\\log n)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "808",
    "index": "D",
    "title": "Array Division",
    "statement": "Vasya has an array $a$ consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).\n\n\\textbf{Inserting an element in the same position he was erased from is also considered moving.}\n\nCan Vasya divide the array after choosing the right element to move and its new position?",
    "tutorial": "Suppose we want to move an element from the prefix to the suffix (if we need to move an element from the suffix to the prefix, we can just reverse the array and do the same thing). Suppose the resulting prefix will contain $m$ elements. Then we need to check that the prefix with $m + 1$ elements contains an element such that the sum of this prefix without this element is equal to the half of the sum of the whole array (and then we can move this element to the suffix). To check all the prefixes, we can scan the array from left to right while maintaining the set of elements on the prefix and the sum of these elements.",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "808",
    "index": "E",
    "title": "Selling Souvenirs",
    "statement": "After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.\n\nThis morning, as usual, Petya will come to the market. Petya has $n$ different souvenirs to sell; $i$th souvenir is characterised by its weight $w_{i}$ and cost $c_{i}$. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than $m$, and total cost is maximum possible.\n\nHelp Petya to determine maximum possible total cost.",
    "tutorial": "There are lots of different solutions for this problem. We can iterate on the number of $3$-elements we will take (in this editorial $k$-element is a souvenir with weight $k$). When fixing the number of $3$-elements (let it be $x$), we want to know the best possible answer for the weight $m - 3x$, while taking into account only $1$-elements and $2$-elements. To answer these queries, we can precalculate the values $dp[w]$ - triples $(cost, cnt1, cnt2)$, where $cost$ is the best possible answer for the weight $w$, and $cnt1$ and $cnt2$ is the number of $1$-elements and $2$-elements we are taking to get this answer. Of course, $dp[0] = (0, 0, 0)$, and we can update $dp[i + 1]$ and $dp[i + 2]$ using value of $dp[i]$. After precalculating $dp[w]$ for each possible $w$ we can iterate on the number of $3$-elements. There are also several binary/ternary search solutions.",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "ternary search"
    ],
    "rating": 2300
  },
  {
    "contest_id": "808",
    "index": "F",
    "title": "Card Game",
    "statement": "Digital collectible card games have become very popular recently. So Vova decided to try one of these.\n\nVova has $n$ cards in his collection. Each of these cards is characterised by its power $p_{i}$, magic number $c_{i}$ and level $l_{i}$. Vova wants to build a deck with total power not less than $k$, but magic numbers may not allow him to do so — Vova can't place two cards in a deck if the sum of the magic numbers written on these cards is a prime number. Also Vova cannot use a card if its level is greater than the level of Vova's character.\n\nAt the moment Vova's character's level is $1$. Help Vova to determine the minimum level he needs to reach in order to build a deck with the required total power.",
    "tutorial": "The most tricky part of the problem is how to check if some set of cards allows us to build a deck with the required power (not taking the levels of cards into account). Suppose we have not more than one card with magic number $1$ (if there are multiple cards with this magic number, then we obviously can use only one of these). Then two cards may conflict only if one of them has an odd magic number, and another has an even magic number - otherwise their sum is even and not less than $4$, so it's not a prime number. This allows us to solve this problem as follows: Construct a bipartite graph: each vertex represents a card, and two vertices are connected by an edge if the corresponding pair of cards can't be put in a deck. Then we have to find the maximum weight of independent set in this graph. This can be solved using maximum flow algorithm: construct a network where source is connected with every \"odd\" vertex (a vertex that represents a card with an odd magic number) by an edge with capacity equal to the power of this card; then connect every \"odd\" vertex to all \"even\" vertices that are conflicting with this vertex by edges with infinite capacities; and then connect every \"even\" vertex to the sink by an edge with capacity equal to the power of the card (all edges have to be directed). Then the maximum power of the deck is equal to $sum - mincut$, where $sum$ is the sum of all powers and $mincut$ is the minimum cut value between the source and the sink (which is equal to the maximum flow). This allows us to check if we can build a deck of required power using only some set of cards (for example, only cards with level less than or equal to some $x$).",
    "tags": [
      "binary search",
      "flows",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "808",
    "index": "G",
    "title": "Anthem of Berland",
    "statement": "Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.\n\nThough there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.\n\nHe has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.\n\nThe anthem is the string $s$ of no more than $10^{5}$ small Latin letters and question marks. The most glorious victory is the string $t$ of no more than $10^{5}$ small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string $t$ in string $s$ is maximal.\n\nNote that the occurrences of string $t$ in $s$ can overlap. Check the third example for clarification.",
    "tutorial": "Let's denote the string obtained by concatenation $t + # + s$ (where $#$ is some dividing character that isn't a part of the alphabet) as $ts$. Recall that KMP algorithm builds the prefix function for this string. We can calculate $dp[i][j]$ on this string, where $i$ is the position in this string and $j$ is the value of prefix function in this position. The value of $dp[i][j]$ is the maximum number of occurences of $t$ found so far (or $- 1$ if this situation is impossible). If $(i + 1)$th character is a Latin letter, then we just recalculate prefix function for this position (the fact that in KMP the value of prefix function won't exceed $|t|$ allows us to do so). If $(i + 1)$th character is a question mark, then we check all $26$ possible characters and recalculate prefix function for all of these characters (and update the corresponding $dp$ values). The size of $s$ and $t$ is pretty big, so we need to recalculate these values in $O(1)$ time; this can be done by precalculating the values of $next[i][j]$ ($i$ is the value of prefix function, $j$ is a new character and $next[i][j]$ is the value of prefix function after adding this character).",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "809",
    "index": "A",
    "title": "Do you want a date?",
    "statement": "Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to $n$ computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.\n\nLet's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from $1$ to $n$. So the $i$-th hacked computer is located at the point $x_{i}$. Moreover the coordinates of all computers are distinct.\n\nLeha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.\n\nLeha should calculate a sum of $F(a)$ for all $a$, where $a$ is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote $A$ the set of all integers from $1$ to $n$. Noora asks the hacker to find value of the expression $\\sum_{a\\subset A a s s o}F(a)$. Here $F(a)$ is calculated as the maximum among the distances between all pairs of computers from the set $a$. Formally, $F(a)=\\operatorname*{max}_{i,j\\in a}|x_{i}-x_{j}|$. Since the required sum can be quite large Noora asks to find it modulo $10^{9} + 7$.\n\nThough, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.",
    "tutorial": "We know, that a lot of different solutions exists on this task, I will describe the easiest in my opinion. Let's sort the coordinates in ascending order and iterate through the pairs of neighbours $x_{i}$ and $x_{i + 1}$. They are adding to the answer $x_{i + 1} - x_{i}$ in all the subsets, in which there is at least one point $a  \\le  i$ and at least one point $b  \\ge  i + 1$. The number of such subsets is equal to $(2^{i} - 1) * (2^{n - i} - 1)$.",
    "code": "st[0] = 1;\nfor ( int j = 1; j < maxn; j++ )\n    st[j] = ( 2 * st[j - 1] ) % base;\nint n;\nscanf ( \"%d\", &n );\nfor ( int j = 0; j < n; j++ )\n    scanf ( \"%d\", &a[j] );\nsort( a, a + n );\nint ans = 0;\nfor ( int j = 1; j < n; j++ ) {\n    int len = a[j] - a[j - 1];\n    int cntL = j;\n    int cntR = n - j;\n    int add = ( 1LL * ( st[cntL] - 1 + base ) * ( st[cntR] - 1 + base ) ) % base;\n    ans = ( 1LL * ans + 1LL * len * add ) % base;\n}\nprintf ( \"%d\\n\", ans );",
    "tags": [
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "809",
    "index": "B",
    "title": "Glad to see you!",
    "statement": "\\textbf{This is an interactive problem. In the output section below you will see the information about flushing the output.}\n\nOn Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.\n\nIn the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of $n$ dishes. It is interesting that all dishes in the menu are numbered with integers from $1$ to $n$. After a little thought, the girl ordered exactly $k$ different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.\n\nThe game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers $x$ and $y$ $(1 ≤ x, y ≤ n)$. After that Noora chooses some dish $a$ for the number $x$ such that, at first, $a$ is among the dishes Noora ordered ($x$ can be equal to $a$), and, secondly, the value $|x-a|$ is the minimum possible. By the same rules the girl chooses dish $b$ for $y$. After that Noora says «TAK» to Leha, if $|x-a|\\leq|y-b|$, and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than $60$ questions. After that he should name numbers of any two dishes Noora ordered.\n\nHelp Leha to solve this problem!",
    "tutorial": "Let's start with searching the first point. We can do it using this binary search: let's ask points $mid$ and $mid + 1$ each time, when we calculated the center of search interval. So we always know in which of the halves $[l, mid], [mid + 1, r]$ exists at least one point. Since in the initial interval there is at least one point and any point in the interval of search is closer, than any point out of the interval, we will never lose this point out of the search. Now let's run two binsearches more, similarly for everything to the left and to the right of the first found point. Again, any point in the interval of search is closer, than any point out of the interval. Now it is not guaranteed that initially exist at least one point, so we have to check the found one using one query.",
    "code": "int query(int x,int y){\n    if(x==-1)return 0;\n    cout<<1<<' '<<x<<' '<<y<<endl;\n    string ret;\n    cin>>ret;\n    return (\"TAK\"==ret);\n}\n\nint get(int l,int r){\n    if(l>r)return -1;\n\n    while(l<r){\n        int m=(l+r)/2;\n        if(query(m,m+1)){\n            r=m;\n        }else l=m+1;\n    }\n    return l;\n}\n\nint main() {\n    int n,k;\n    cin>>n>>k;\n\n    int x=get(1,n);\n    int y=get(1,x-1);\n    if(!query(y,x))y=get(x+1,n);\n    cout<<2<<' '<<x<<' '<<y<<endl;\n\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 2200
  },
  {
    "contest_id": "809",
    "index": "C",
    "title": "Find a car",
    "statement": "After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.\n\nFormally the parking can be represented as a matrix $10^{9} × 10^{9}$. There is exactly one car in every cell of the matrix. All cars have their own machine numbers represented as a positive integer. Let's index the columns of the matrix by integers from $1$ to $10^{9}$ from left to right and the rows by integers from $1$ to $10^{9}$ from top to bottom. By coincidence it turned out, that for every cell $(x, y)$ the number of the car, which stands in this cell, is equal to the minimum positive integer, which can't be found in the cells $(i, y)$ and $(x, j)$, $1 ≤ i < x, 1 ≤ j < y$.\n\n\\begin{center}\n{\\small The upper left fragment $5 × 5$ of the parking}\n\\end{center}\n\nLeha wants to ask the watchman $q$ requests, which can help him to find his car. Every request is represented as five integers $x_{1}, y_{1}, x_{2}, y_{2}, k$. The watchman have to consider all cells $(x, y)$ of the matrix, such that $x_{1} ≤ x ≤ x_{2}$ and $y_{1} ≤ y ≤ y_{2}$, and if the number of the car in cell $(x, y)$ does not exceed $k$, increase the answer to the request by the number of the car in cell $(x, y)$. For each request Leha asks the watchman to tell him the resulting sum. Due to the fact that the sum can turn out to be quite large, hacker asks to calculate it modulo $10^{9} + 7$.\n\nHowever the requests seem to be impracticable for the watchman. Help the watchman to answer all Leha's requests.",
    "tutorial": "At first, let's examine that numbers in the matrix are equal to binary xor of the row and column. Precisely, the number in cell $i, j$ is equal to $(i-1)\\oplus(j-1)+1$. Now let's split the query into 4 queries to the matrix prefix, as we usually do it in matrix sum queries. In order to find the answer to the query, we have to maintain 2 dp-on-bits: $cnt[prefix][flagX][flagY][flagK]$ and $dp[prefix][flagX][flagY][flagK]$, where $prefix$ - the number of placed bits, $flagX, flagY$ - flags of equality $x, y$ in query and $flagK$ - flag of equality of row and column xor with $k$. Flag of equality is a boolean, equal to $0$, if our number became less then prefix, and $1$ if prefix is still equal. If you aren't familiar with such dp, please try to solve another task with dp on prefix with less number of flags. $cnt$ will maintain the number of cells that are suitable for the arguments and $dp$ - accumulated sum.",
    "code": "\nll dp[32][2][2][2];\nll sum[32][2][2][2];\n\nvoid add(ll &x,ll y){\n    x+=y;\n    if(x>=mod)x-=mod;\n}\n\nvoid sub(ll &x,ll y){\n    x-=y;\n    if(x<0)x+=mod;\n}\n\nll mul(ll x,ll y){\n    return x*y%mod;\n}\n\nll pot[32];\n\nll solve(int x,int y,int z){\n    if(x<0||y<0||z<0)return 0;\n    memset(dp,0,sizeof dp);\n    memset(sum,0,sizeof sum);\n    vi A,B,C;\n    rep(j,0,31){\n        A.pb(x%2);x/=2;\n        B.pb(y%2);y/=2;\n        C.pb(z%2);z/=2;\n    }\n    reverse(all(A));\n    reverse(all(B));\n    reverse(all(C));\n    dp[0][1][1][1]=1;\n    sum[0][1][1][1]=0;\n    rep(i,0,31){\n        rep(a,0,2)rep(b,0,2)rep(c,0,2){\n            rep(x,0,2)rep(y,0,2){\n                int z=x^y;\n                if(a==1&&A[i]==0&&x==1)continue;\n                if(b==1&&B[i]==0&&y==1)continue;\n                if(c==1&&C[i]==0&&z==1)continue;\n                add(dp[i+1][a&(A[i]==x)][b&(B[i]==y)][c&(C[i]==z)],dp[i][a][b][c]);\n                add(sum[i+1][a&(A[i]==x)][b&(B[i]==y)][c&(C[i]==z)],sum[i][a][b][c]);\n                add(sum[i+1][a&(A[i]==x)][b&(B[i]==y)][c&(C[i]==z)],mul(z<<(30-i),dp[i][a][b][c]));\n\n            }\n        }\n    }\n    ll res=0;\n    rep(a,0,2)rep(b,0,2)rep(c,0,2){\n        add(res,sum[31][a][b][c]);\n        add(res,dp[31][a][b][c]);\n    }\n    return res;\n}\n\nint main(){\n    int T;\n    cin>>T;\n    while(T--){\n        int x,y,x2,y2,k;\n        cin>>x>>y>>x2>>y2>>k;\n        --x;--y;--x2;--y2;--k;\n        ll res=0;\n        add(res,solve(x2,y2,k));\n        sub(res,solve(x2,y-1,k));\n        sub(res,solve(x-1,y2,k));\n        add(res,solve(x-1,y-1,k));\n        cout<<res<<'\\n';\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "809",
    "index": "D",
    "title": "Hitchhiking in the Baltic States",
    "statement": "Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking.\n\nIn total, they intended to visit $n$ towns. However it turned out that sights in $i$-th town are open for visitors only on days from $l_{i}$ to $r_{i}$.\n\nWhat to do? Leha proposed to choose for each town $i$ a day, when they will visit this town, i.e any integer $x_{i}$ in interval $[l_{i}, r_{i}]$. After that Noora choses some subsequence of towns $id_{1}, id_{2}, ..., id_{k}$, which friends are going to visit, that at first they are strictly increasing, i.e $id_{i} < id_{i + 1}$ is for all integers $i$ from $1$ to $k - 1$, but also the dates of the friends visits are strictly increasing, i.e $x_{idi} < x_{idi + 1}$ is true for all integers $i$ from $1$ to $k - 1$.\n\nPlease help Leha and Noora in choosing such $x_{i}$ for each town $i$, and such subsequence of towns $id_{1}, id_{2}, ..., id_{k}$, so that friends can visit maximal number of towns.\n\nYou may assume, that Leha and Noora can start the trip any day.",
    "tutorial": "Let $dp_{i}$ - minimal number that can be last in strictly increasing subsequence with length $i$. Iterate through prefixes of intervals and maintain this dp. Obviously this dp is strictly increasing. What happens when we add new interval $l, r$: Thinking from the facts above, we can solve this task maintaining dp in cartesian tree (treap). Let's find and split interval from $i + 1$ to $j$. Add to every number in this tree $1$. Delete $j + 1$-t node. And merge everything adding one more node with key $l$.",
    "code": "struct node {\n    int prior, sz, dp, add;\n    node *l, *r;\n    node ( int x ) {\n        prior = ( rand() << 15 ) | rand();\n        // sz = 1;\n        dp = x;\n        l = r = NULL;\n        add = 0;\n    }\n};\n \ntypedef node * pnode;\n\nvoid push( pnode T ) {\n    T -> dp += T -> add;\n    if ( T -> l )\n        T -> l -> add += T -> add;\n    if ( T -> r )\n        T -> r -> add += T -> add;\n    T -> add = 0;\n}\n \nvoid merge( pnode &T, pnode L, pnode R ) {\n    if ( !L ) {\n        T = R;\n        return;\n    }\n    if ( !R ) {\n        T = L;\n        return;\n    }\n    if ( L -> prior > R -> prior ) {\n        push( L );\n        merge( L -> r, L -> r, R );\n        T = L;\n        return;\n    }\n    push( R );\n    merge( R -> l, L, R -> l );\n    T = R;\n}\n \nvoid split( pnode T, int value, pnode &L, pnode &R ) {\n    if ( !T ) {\n        L = R = NULL;\n        return;\n    }\n    push( T );\n    if ( T -> dp >= value ) {\n        split( T -> l, value, L, T -> l );\n        R = T;\n        return;\n    }\n    split( T -> r, value, T -> r, R );\n    L = T;\n}\n \nint findBegin( pnode T ) {\n    push( T );\n    if ( !T -> l )\n        return T -> dp;\n    return findBegin( T -> l );\n}\n \nint findMax( pnode T, int n ) {\n    if ( !T )\n        return 0;\n    push( T );\n    return findMax( T -> l, n ) + findMax( T -> r, n ) + ( T -> dp <= inf ? 1 : 0 );\n}\n\npair < int, int > a[maxn];\npnode T = new node( 0 );\npnode L = NULL;\npnode M = NULL;\npnode R = NULL;\npnode rubbish = NULL;\n \nvoid solve() {\n    int n;\n    scanf ( \"%d\", &n );\n    for ( int j = 1; j <= n; j++ )\n        scanf ( \"%d%d\", &a[j].f, &a[j].s );\n    for ( int j = 1; j <= n; j++ )\n        merge( T, T, new node( inf + j ) );\n    for ( int j = 1; j <= n; j++ ) {\n        split( T, a[j].f, L, R );\n        split( R, a[j].s, M, R );\n        if ( M )\n            M -> add += 1;\n        int cnt = findBegin( R );\n        split( R, cnt + 1, rubbish, R );\n        merge( T, L, new node( a[j].f ) );\n        merge( T, T, M );\n        merge( T, T, R );\n    }\n    printf ( \"%d\\n\", findMax( T, n ) - 1 );\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "809",
    "index": "E",
    "title": "Surprise me!",
    "statement": "Tired of boring dates, Leha and Noora decided to play a game.\n\nLeha found a tree with $n$ vertices numbered from $1$ to $n$. We remind you that tree is an undirected graph without cycles. Each vertex $v$ of a tree has a number $a_{v}$ written on it. Quite by accident it turned out that all values written on vertices are distinct and are natural numbers between $1$ and $n$.\n\nThe game goes in the following way. Noora chooses some vertex $u$ of a tree uniformly at random and passes a move to Leha. Leha, in his turn, chooses (also uniformly at random) some vertex $v$ from remaining vertices of a tree $(v ≠ u)$. As you could guess there are $n(n - 1)$ variants of choosing vertices by players. After that players calculate the value of a function $f(u, v) = φ(a_{u}·a_{v})$ $·$ $d(u, v)$ of the chosen vertices where $φ(x)$ is Euler's totient function and $d(x, y)$ is the shortest distance between vertices $x$ and $y$ in a tree.\n\nSoon the game became boring for Noora, so Leha decided to defuse the situation and calculate expected value of function $f$ over all variants of choosing vertices $u$ and $v$, hoping of at least somehow surprise the girl.\n\nLeha asks for your help in calculating this expected value. Let this value be representable in the form of an irreducible fraction $\\frac{P}{Q}$. To further surprise Noora, he wants to name her the value $P\\cdot Q^{-1}\\ \\ \\mathrm{mod}\\ 10^{9}+7$.\n\nHelp Leha!",
    "tutorial": "Here $ \\phi (x)$ denotes Euler's totient function of $x$, $gcd(x, y)$ is the greatest common divisor of $x$ and $y$ and $f(x)$ denotes the amount of divisors of $x$. Small remark. We need to find the answer in the form of $\\frac{P}{Q}$, where $gcd(P, Q) = 1$. Let $A$ will be the sum of all pairwise values $f(u, v)$ and $B$ is the amount of such pairs i.e. $n(n - 1)$ and let $g = gcd(A, B)$. Then $P = A \\cdot g^{ - 1}, Q = B \\cdot g^{ - 1}$ and the answer for the problem is $P \\cdot Q^{ - 1} = A \\cdot g^{ - 1} \\cdot B^{ - 1} \\cdot g$ = $A \\cdot B^{ - 1}$ which means there is no need to know $g$. As it often happens in the problems where you are required to calc anything over all paths of a tree it's a good idea to use so-called centroid decomposition of a tree. Shortly, decomposition chooses some node of a tree, processes each path going through it and then deletes this node and solves the problem in the remaining forest recursively. It's obvious there is no matter what node we choose the answer will be always calculated correctly but total run-time depends on choosing this node. It's claimed each tree contains such a vertex with the removal of which all the remaining trees will have a size at least twice less then a size of this tree. So if we always choose such a vertex, each node of a tree will exist no more than in $\\log N$ trees built by desomposition which is good enough. Let's build centroid decomposition of the given tree. Let's $root$ is the root of the current tree. Let's solve the problem for this tree (let's call it 'layer') and solve it for the sons of $root$ recursively after that. At first, $\\phi(a b)=\\frac{\\phi(a)\\cdot\\phi(b)\\cdot g}{\\phi(g)}$ where $g = gcd(a, b)$. Also for the current layer $dist(u, v) = d_{u} + d_{v}$ where $d_{x}$ is the distance from $root$ to $x$. Let's fix some vertex $v$. How to calc the sum $ \\phi (a_{v} \\cdot a_{v}) \\cdot dist(u, v)$ inside our layer over all such $u$ that the path $u\\rightarrow v$ goes through $root$? Let's denote the set of such $u$ as $A(v)$. We want to add to the answer $\\sum_{u\\in A(v)}\\phi(a_{v}\\cdot a_{u})\\cdot d i s t(v,u)=\\sum_{u\\in A(v)}\\phi(a_{v})\\cdot\\phi(a_{u})\\cdot\\frac{g}{\\phi(g)}\\cdot\\left(d_{u}+d_{v}\\right)$ $=\\sum_{u\\in A(v)}\\left(\\phi(a_{v})\\cdot\\phi(a_{u})\\cdot\\vartheta(a_{u})\\cdot\\vartheta(a_{v})\\cdot\\phi(a_{u})\\cdot\\vartheta(a_{u})\\cdot\\frac{g}{\\phi(g)}\\cdot d_{u}\\right)$, where $g = gcd(a_{u}, a_{v})$. Considering we need to sum up all such sums over each $v$ from the layer, the sum current layer increases the total sum equals to $2\\sum_{v}\\left(\\sum_{u\\in A(v)}\\phi(a_{v})\\cdot d_{v}\\cdot\\frac{\\phi(a_{u})\\cdot g}{\\phi(g)}\\right)=2\\sum_{v}\\phi(a_{v})\\cdot d_{v}\\cdot\\left(\\sum_{u\\in A(v)}\\frac{\\phi(a_{u})\\cdot g}{\\phi(g)}\\right)$. So we need to be able to sum up $\\sum_{u\\in A(v)}{\\frac{\\phi(a_{u})\\cdot g}{\\phi(g)}}$, $g = gcd(a_{u}, a_{v})$ for each $v$. Let's understand how to calc $sum_{g}$ for each $g$ which means the sum of Euler's totient functions of all such vertices $u$, that has $gcd(a_{v}, a_{u}) = g$. Let's imagine we know $sumphi_{c}$ which denotes the sum of $ \\phi (a_{u})$ for such $u$ that $a_{u}\\ \\ \\mathrm{mod}\\ c=0$. Then the following statement is true: $s u m_{g}=s u m p h i_{g}-\\sum_{x\\neq g,x}\\sum_{\\mathrm{mod}~g=0}s u m_{3}$. We can calculate values of $sumphi$ in $O(n\\ln n\\log n)$ time: each divisor of each number in range from $1$ to $n$ (which is, as it known, $O(n\\ln n)$) will be counted in $O(\\log n)$ layers of the centroid decomposition. So we're already able to calc $sum$ values in the time apparently proprtional to $O(n\\log^{2}n)$. More precisely, the number of operations we waste for calculating $sum$ will be equal to $\\textstyle\\sum f(x)$ over all such $i$ and $x$ that $(1  \\le  x, i  \\le  n$, $i\\mod x=0)$, where $f(x)$ is the amount of divisors of $x$. This sum is equivalent to $\\sum_{i=1}^{n}{\\frac{n}{i}}\\cdot f(i)$. Coding this solution carefully can give you Accepted thanks to high TL we set to Java solution. I can prove only $O(n\\log^{3}n)$ complexity for this solution which is a very high upper bound. Can anyone give any better complexity for $\\sum_{i=1}^{n}{\\frac{n}{i}}\\cdot f(i)$? However we can speed up this solution. Here we calculated $\\sum_{g,a_{v}{\\ \\ \\mathrm{mod}\\ g=0}}s u m_{g}\\cdot{\\frac{g}{\\phi(g)}}$ giving that $sum_{g}$ was equal to $s u p\\bar{u}_{g}-\\sum_{x\\neq g,x}\\sum_{\\mathrm{mod}\\ g=0}s u p n_{o}$ leading to $O{\\biggl(}\\sum_{q,a_{v}}\\sum_{\\mathrm{mod}~q=0}f(g){\\biggr)}$ complexity for each $v$ in the layer. Actually the sum $\\sum_{g,x\\ \\ \\mathrm{mod}\\ g=0}{\\frac{g}{\\phi(g)}}\\cdot\\,S u m_{g}$ for each $x$ can be showed as $\\sum_{g,x{\\mathrm{~mod~}}g=0}c_{x}[g]\\cdot s u m p h i_{g}$ using some coefficients $c_{x}[]$. If we find them we'll be able to process each $v$ of the layer in $O(f(a_{v}))$ time which leads to final $O(n\\ln n\\log n)$ complexity. Let's precalculate these coefficients in ascending order for each $x$. It's easy to see that $c_{1}[1] = 1$ and for a prime $p$ $c_{p}[1]=1,c_{p}[p]={\\frac{1}{p-1}}$. Now let's $x$ is a composite number and let's $p$ is it's least prime divisor and $ \\alpha $ is such maximum number that $x$ is divisible by $p^{ \\alpha }$, and $q={\\frac{x}{p^{\\alpha}}}$. Then coefficients for any divisor $z$ of $x$ can be calculated in the following way: Total complexity: $O(n\\ln n\\log n)$.",
    "code": "\n#include <functional>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n#include <numeric>\n#include <iomanip>\n#include <cstdio>\n#include <cstring>\n#include <cassert>\n#include <vector>\n#include <math.h>\n#include <queue>\n#include <stack>\n#include <ctime>\n#include <set>\n#include <map>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\ntemplate <typename T>\nT nextInt() {\n    T x = 0, p = 1;\n    char ch;\n    do { ch = getchar(); } while(ch <= ' ');\n    if (ch == '-') {\n        p = -1;\n        ch = getchar();\n    }\n    while(ch >= '0' && ch <= '9') {\n        x = x * 10 + (ch - '0');\n        ch = getchar();\n    }\n    return x * p;\n}\nconst int maxN = (int)2e5 + 10;\nconst int maxL = 17;\nconst int INF = (int)1e9;\nconst int mod = (int)1e9 + 7;\nconst ll LLINF = (ll)1e18 + 5;\n\nint mul(int x, int y) {\n    return 1LL * x * y % mod;\n}\n\nvoid add(int &x, int y) {\n    x += y;\n    if (x >= mod) x -= mod;\n}\n\nvoid sub(int &x, int y) {\n    x -= y;\n    if (x < 0) x += mod;\n}\n\nint n;\nvector <int> g[maxN];\nvector <int> d[maxN];\nvector <int> coefs[maxN];\nint phi[maxN];\nint inv[maxN];\nint a[maxN];\n\nint tmp[maxN];\n\nvoid productToTmp(int a, int b) {\n    for (size_t it = 0; it < d[a].size(); it++) {\n        for (size_t jt = 0; jt < d[b].size(); jt++) {\n            int x = d[a][it];\n            int cx = coefs[a][it];\n            int y = d[b][jt];\n            int cy = coefs[b][jt];\n            add(tmp[x * y], mul(cx, cy));\n        }\n    }\n}\n\nvoid precalc() {\n    inv[1] = 1;\n    for (int i = 1; i < maxN; ++i) {\n        phi[i] = i;\n        if(i > 1) inv[i] = mul(mod - mod / i, inv[mod % i]);\n    }\n    for (int i = 1; i < maxN; ++i) {\n        for (int j = i; j < maxN; j += i) {\n            d[j].push_back(i);\n            if (j != i) phi[j] -= phi[i];\n        }\n    }\n    for (int i = 1; i < maxN; ++i) {\n        coefs[i].resize(d[i].size());\n    }\n    coefs[1][0] = 1;\n    for (int x = 2; x < maxN; x++) {\n        if ((int)d[x].size() == 2) {\n            coefs[x][0] = 1;\n            coefs[x][1] = inv[x - 1];\n        } else {\n            int lp = d[x][1];\n            int z = x;\n            while (z % lp == 0) {\n                z /= lp;\n            }\n            for (int y: d[x]) {\n                tmp[y] = 0;\n            }\n            productToTmp(lp, z);\n            for (size_t it = 0; it < d[x].size(); it++) {\n                coefs[x][it] = tmp[d[x][it]];\n            }\n        }\n    }\n}\n\nint nodes[maxN];\nint len = 0;\nint sz[maxN];\nint blocked[maxN];\nint level[maxN];\nint anc[maxN];\n\nvoid calc_sizes(int v, int p = -1) {\n    nodes[len++] = v;\n    sz[v] = 1;\n    anc[v] = p;\n    for (int x: g[v]){\n        if (blocked[x] || x == p) continue;\n        calc_sizes(x, v);\n        sz[v] += sz[x];\n    }\n}\n\nint sum_phi[maxN];\n\nint list_len;\nint list[maxN];\nint depth[maxN];\n\nvoid get_list(int v, int par = -1, int dpth = 1) {\n    list[list_len] = v;\n    depth[list_len++] = dpth;\n    for (int x: g[v]) {\n        if (par == x || blocked[x]) continue;\n        get_list(x, v, dpth + 1);\n    }\n}\n\nint sum[maxN];\n\nint calc(int value) {\n    int cur = 0;\n    for(size_t i = 0; i < d[value].size(); ++i) {\n        int x = d[value][i];\n        add(cur, mul(sum_phi[x], coefs[value][i]));\n    }\n    return mul(cur, phi[value]);\n}\n\nint total = 0;\n\nvoid solve(int root) { //root is a centroid\n    for (int i = 0; i < len; ++i) {\n        int u = nodes[i];\n        int y = a[u];\n        for (int x: d[y]) {\n            add(sum_phi[x], phi[y]);\n        }\n    }\n    for (int child: g[root]) {\n        if (blocked[child]) continue;\n\n        list_len = 0;\n        get_list(child, root);\n        {\n            //excluding everything which can be counted twice\n            for(int i = 0; i < list_len; ++i) {\n                int u = list[i];\n                int y = a[u];\n                for(int x: d[y]) {\n                    sub(sum_phi[x], phi[y]);\n                }\n            }\n        }\n        {\n            for (int i = 0; i < list_len; ++i) {\n                int u = list[i];\n                int d = depth[i];\n                int value = a[u];\n                add(total, mul(d, calc(value)));\n            }\n        }\n        {\n            //including back\n            for(int i = 0; i < list_len; ++i) {\n                int u = list[i];\n                int y = a[u];\n                for(int x: d[y]) {\n                    add(sum_phi[x], phi[y]);\n                }\n            }\n        }\n    }\n\n    //clear\n    for (int i = 0; i < len; ++i) {\n        int u = nodes[i];\n        int y = a[u];\n        for (int x: d[y]) {\n            sum_phi[x] = 0;\n        }\n    }\n}\n\nvoid build(int v, int lev) {\n    len = 0;\n    calc_sizes(v);\n    int centroid = -1;\n    for (int i = 0; i < len; ++i) {\n        int u = nodes[i];\n        int maxChildSize = len - sz[u];\n        for (int x: g[u]) {\n            if (x != anc[u] && !blocked[x]) {\n                maxChildSize = max(maxChildSize, sz[x]);\n            }\n        }\n        if (maxChildSize <= len / 2) {\n            centroid = u;\n        }\n    }\n    blocked[centroid] = true;\n    level[centroid] = lev;\n    solve(centroid);\n\n    for (int x: g[centroid]) {\n        if (blocked[x]) continue;\n        build(x, lev + 1);\n    }\n}\n\nint main() {\n\n   // freopen(\"input.txt\", \"r\", stdin);\n   // freopen(\"output.txt\", \"w\", stdout);\n    ios_base::sync_with_stdio(0);\n    precalc();\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    for (int i = 1; i < n; ++i) {\n        int x, y;\n        cin >> x >> y;\n        --x; --y;\n        g[x].push_back(y);\n        g[y].push_back(x);\n    }\n\n    build(0, 0);\n\n    total = mul(total, inv[n]);\n    total = mul(total, inv[n - 1]);\n    total = mul(total, 2);\n\n    cout << total << endl;\n    return 0;\n}\n",
    "tags": [
      "divide and conquer",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "810",
    "index": "A",
    "title": "Straight <<A>>",
    "statement": "Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one.\n\nIn school, where Noora is studying, teachers are putting down marks to the online class register, which are integers from $1$ to $k$. The worst mark is $1$, the best is $k$. Mark that is going to the certificate, is calculated as an average of all the marks, rounded to the closest integer. If several answers are possible, rounding up is produced. For example, $7.3$ is rounded to $7$, but $7.5$ and $7.8784$ — to $8$.\n\nFor instance, if Noora has marks $[8, 9]$, then the mark to the certificate is $9$, because the average is equal to $8.5$ and rounded to $9$, but if the marks are $[8, 8, 9]$, Noora will have graduation certificate with $8$.\n\nTo graduate with «A» certificate, Noora \\textbf{has to have mark} $k$.\n\nNoora got $n$ marks in register this year. However, she is afraid that her marks are not enough to get final mark $k$. Noora decided to ask for help in the internet, where hacker Leha immediately responded to her request. He is ready to hack class register for Noora and to add Noora any number of additional marks from $1$ to $k$. At the same time, Leha want his hack be unseen to everyone, so he decided to add as less as possible additional marks. Please help Leha to calculate the minimal number of marks he has to add, so that final Noora's mark will become equal to $k$.",
    "tutorial": "It is obvious that add any marks less than $k$ isn't optimal. Therefore, iterate on how many $k$ marks we add to the registry and find minimal sufficient number.",
    "code": "int n, k, s = 0;\ncin >> n >> k;\nfor (int i = 0; i < n; ++i) {\n    int x;\n    cin >> x;\n    s += x;\n}\nfor (int ans = 0;; ans++) {\n    int a = 2 * (s + ans * k);\n    int b = (2 * k - 1) * (ans + n);\n\n    if (a >= b) {\n        cout << ans;\n        return 0;\n    }\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "810",
    "index": "B",
    "title": "Summer sell-off",
    "statement": "Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.\n\nShop, where Noora is working, has a plan on the following $n$ days. For each day sales manager knows exactly, that in $i$-th day $k_{i}$ products will be put up for sale and exactly $l_{i}$ clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.\n\nFor advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any $f$ days from $n$ next for sell-outs. On each of $f$ chosen days the number of products were put up for sale would be doubled. Thus, if on $i$-th day shop planned to put up for sale $k_{i}$ products and Noora has chosen this day for sell-out, shelves of the shop would keep $2·k_{i}$ products. Consequently, there is an opportunity to sell two times more products on days of sell-out.\n\nNoora's task is to choose $f$ days to maximize total number of sold products. She asks you to help her with such a difficult problem.",
    "tutorial": "Initially, the number of sold products on $i$-th day is $min(k_{i}, l_{i})$ and in sell-out day is $min(2 * k_{i}, l_{i})$. Let's sort days in descending of $min(2 * k_{i}, l_{i}) - min(k_{i}, l_{i})$ and take first $f$ days as sell-out days.",
    "code": "for (int i = 0; i < n; i++) {\n    cin >> k[i] >> l[i];\n    a.push_back(make_pair(min(2 * k[i], l[i]) - min(k[i], l[i]), i));\n}\nsort(a.rbegin(), a.rend());\n\nlong long ans = 0;\nfor (int i = 0; i < f; i++) {\n    int pos = a[i].second;\n    ans += min(2 * k[pos], l[pos]);\n}\nfor (int i = f; i < n; i++) {\n    int pos = a[i].second;\n    ans += min(k[pos], l[pos]);\n}\ncout << ans;",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "811",
    "index": "A",
    "title": "Vladik and Courtesy",
    "statement": "At regular competition Vladik and Valera won $a$ and $b$ candies respectively. Vladik offered $1$ his candy to Valera. After that Valera gave Vladik $2$ his candies, so that no one thought that he was less generous. Vladik for same reason gave $3$ candies to Valera in next turn.\n\nMore formally, the guys take turns giving each other one candy more than they received in the previous turn.\n\nThis continued until the moment when one of them couldn’t give the right amount of candy. Candies, which guys got from each other, they \\textbf{don’t consider as their own}. You need to know, who is the first who can’t give the right amount of candy.",
    "tutorial": "Let's simulate process, described in problem statement. I.e subtract from $a$ and $b$ numbers $1, 2, 3, ...$, until any of them is less than zero. The process would terminate less than in $\\sqrt{10^{9}}$ iterations, because sum of arithmetical progression with $n$ members is approximately equal to $n^{2}$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "811",
    "index": "B",
    "title": "Vladik and Complicated Book",
    "statement": "Vladik had started reading a complicated book about algorithms containing $n$ pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation $P = [p_{1}, p_{2}, ..., p_{n}]$, where $p_{i}$ denotes the number of page that should be read $i$-th in turn.\n\nSometimes Vladik’s mom sorted some subsegment of permutation $P$ from position $l$ to position $r$ inclusive, because she loves the order. For every of such sorting Vladik knows number $x$ — what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has $p_{x}$ changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.",
    "tutorial": "Obviously, that all the elements in range, which are less than $p_{x}$ will go to the left of $p_{x}$ after sort. So the new position will be $l + cnt_{less}$. Let's find $cnt_{less}$ with simple iterating through all the elements in the segment. $O(n * m)$ Challenge. Can you solve the problem with $n, m  \\le  10^{6}$?",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "811",
    "index": "C",
    "title": "Vladik and Memorable Trip",
    "statement": "Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:\n\nVladik is at initial train station, and now $n$ people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code $a_{i}$ is known (the code of the city in which they are going to).\n\nTrain chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is \\textbf{not necessary}). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city $x$, then all people who are going to city $x$ should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city $x$, either go to it and in the same railway carriage, or do not go anywhere at all.\n\nComfort of a train trip with people on segment from position $l$ to position $r$ is equal to XOR of all distinct codes of cities for people on the segment from position $l$ to position $r$. XOR operation also known as exclusive OR.\n\nTotal comfort of a train trip is equal to sum of comfort for each segment.\n\nHelp Vladik to know maximal possible total comfort.",
    "tutorial": "Let's precalc for each $x$ it's $fr_{x}$ and $ls_{x}$ - it's leftmost and rightmost occurrences in the array respectively. Now for each range $[l, r]$ we can check, if it can be a separate train carriage, just checking for each $a_{i}$ $(l  \\le  i  \\le  r)$, that $fr_{ai}$ and $ls_{ai}$ are also in this range. Now let's define $dp_{i}$ as the answer to the problem for $i$ first people. To update $dp$ we can make two transitions: Assume, that there was such train carriage, that finished at position $i$. Then iterate it's start from right to left, also maintaining maximal $ls$, minimal $fr$ and xor of distinct codes $cur$. If current range $[j, i]$ is ok for forming the train carriage, update $dp_i$ with value $dp_j - 1 + cur$. If there wasn't such train carriage, then last element didn't belong to any train carriage, so we can update $dp_i$ with value $dp_i - 1$. $O(n^{2})$",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "811",
    "index": "D",
    "title": "Vladik and Favorite Game",
    "statement": "\\textbf{This is an interactive problem.}\n\nVladik has favorite game, in which he plays all his free time.\n\nGame field could be represented as $n × m$ matrix which consists of cells of three types:\n\n- «.» — normal cell, player can visit it.\n- «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type.\n- «*» — dangerous cell, if player comes to this cell, he loses.\n\nInitially player is located in the left top cell with coordinates $(1, 1)$.\n\nPlayer has access to $4$ buttons \"U\", \"D\", \"L\", \"R\", each of them move player up, down, left and right directions respectively.\n\nBut it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons \"L\" and \"R\" could have been swapped, also functions of buttons \"U\" and \"D\" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game.\n\nHelp Vladik win the game!",
    "tutorial": "It's clear, that to reach finish without stepping into dangerous cells we have to know, whether our buttons are broken. Firstly, let's find any route to the finish using bfs / dfs. At the first moment of this route, when we have to go down, we would find out, if our button is broken, because we are still at the first row of the matrix and if the button is broken, we just won't move anywhere. Similarly for left and right pair of buttons. After that we found out, that button was broken, we can change in our route moves to opposite ones.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "interactive"
    ],
    "rating": 2100
  },
  {
    "contest_id": "811",
    "index": "E",
    "title": "Vladik and Entertaining Flags",
    "statement": "In his spare time Vladik estimates beauty of the flags.\n\nEvery flag could be represented as the matrix $n × m$ which consists of positive integers.\n\nLet's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components:\n\nBut this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at $(1, l)$ and $(n, r)$, where conditions $1 ≤ l ≤ r ≤ m$ are satisfied.\n\nHelp Vladik to calculate the beauty for some segments of the given flag.",
    "tutorial": "Let's use interval tree, maintaining in each vertex two arrays of $n$ numbers: left and right profile of the interval corresponding to the vertex. Each number in this arrays would be in range from $1$ to $2 * n$ denoting component, in which cell is. For merging such structures we would iterate on splice of two vertices and unite components, if two adjacent cells have same colors and than recalculate components of left and right profile of the new structure.",
    "tags": [
      "data structures",
      "dsu",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "812",
    "index": "A",
    "title": "Sagheer and Crossroads",
    "statement": "Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has $3$ lanes getting into the intersection (one for each direction) and $3$ lanes getting out of the intersection, so we have $4$ parts in total. Each part has $4$ lights, one for each lane getting into the intersection ($l$ — left, $s$ — straight, $r$ — right) and a light $p$ for a pedestrian crossing.\n\nAn accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time.\n\nNow, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible.",
    "tutorial": "For pedestrian crossing $i$ ($1  \\le  i  \\le  4)$, lanes $l_{i}, s_{i}, r_{i}, s_{i + 2}, l_{i + 1}, r_{i - 1}$ are the only lanes that can cross it. So, we have to check that either $p_{i} = 0$ or all mentioned lanes are $0$. Complexity: $O(1)$",
    "code": "\"import java.io.PrintWriter;\\nimport java.util.Scanner;\\n\\npublic class SagheerAndCrossroads_MainSolution {\\n\\n\\tpublic static void main(String[] args) {\\n\\t\\t\\n\\t\\tScanner sc = new Scanner(System.in);\\n\\t\\tPrintWriter out = new PrintWriter(System.out);\\n\\t\\t\\n\\t\\tint[][] part = new int[4][4];\\n\\t\\tfor(int i = 0; i < 4; ++i)\\n\\t\\t\\tfor(int j = 0; j < 4; ++j)\\n\\t\\t\\t\\tpart[i][j] = sc.nextInt();\\n\\t\\tint[] crossed = new int[4];\\n\\t\\tfor(int i = 0; i < 4; ++i)\\n\\t\\t\\tfor(int j = 1; j <= 3; ++j)\\n\\t\\t    {\\n\\t\\t    \\tcrossed[i] |= part[i][3 - j];\\n\\t\\t\\t\\tcrossed[(i + j) % 4] |= part[i][3 - j];\\n\\t\\t    }\\n\\t\\t\\n\\t\\tboolean accident = false;\\n\\t\\tfor(int i = 0; i < 4; ++i)\\n\\t\\t\\taccident |= crossed[i] + part[i][3] == 2;\\n\\t\\tout.println(accident ? \\\"YES\\\" : \\\"NO\\\");\\n\\t\\t\\n\\t\\tsc.close();\\n\\t\\tout.close();\\n\\t}\\n}\\n\"",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "812",
    "index": "B",
    "title": "Sagheer, the Hausmeister",
    "statement": "Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.\n\nThe building consists of $n$ floors with stairs at the left and the right sides. Each floor has $m$ rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with $n$ rows and $m + 2$ columns, where the first and the last columns represent the stairs, and the $m$ columns in the middle represent rooms.\n\nSagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights.\n\nNote that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.",
    "tutorial": "When Sagheer reaches a floor for the first time, he will be standing at either left or right stairs. If he is standing at the left stairs, then he will go to the rightmost room with lights on. If he is standing at the right stairs, then he will go to the leftmost room with lights on. Next, he will either take the left stairs or the right stairs to go to the next floor. We will brute force on the choice of the stairs at each floor. Note that Sagheer doesn't have to go to the last floor, so he will go to the highest floor that has a room with lights on. Complexity: $O(n \\cdot 2^{n})$",
    "code": "\"import java.io.IOException;\\nimport java.util.Arrays;\\nimport java.util.Scanner;\\n\\npublic class Main {\\n\\n\\tpublic static void main(String[] args) throws IOException {\\n\\n\\t\\tScanner sc = new Scanner(System.in);\\n\\t\\t\\n\\t\\tint n = sc.nextInt(), m = sc.nextInt();\\n\\t\\t\\n\\t\\tint[] leftMost = new int[n], rightMost = new int[n];\\n\\t\\tint maxFloor = -1;\\n\\t\\tArrays.fill(leftMost, m + 1);\\n\\t\\tfor(int i = n - 1; i >= 0; --i)\\n\\t\\t{\\n\\t\\t\\tString s = sc.next();\\n\\t\\t\\tfor(int j = 0; j < m + 2; ++j)\\n\\t\\t\\t\\tif(s.charAt(j) == '1')\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t    rightMost[i] = j;\\n\\t\\t\\t\\t    if(maxFloor == -1)\\n\\t\\t\\t\\t        maxFloor = i;\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\n\\t\\t\\tfor(int j = m + 1; j >= 0; --j)\\n\\t\\t\\t\\tif(s.charAt(j) == '1')\\n\\t\\t\\t\\t\\tleftMost[i] = j;\\n\\t\\t}\\n\\t\\t\\n\\t\\tint ans = 10000000;\\n\\t\\t\\n\\t\\tfor(int stairs = 0; stairs < (1 << n - 1); ++stairs)\\n\\t\\t{\\n\\t\\t\\tint cur = 0, room = 0, floor = 0;\\n\\t\\t\\twhile(floor <= maxFloor)\\n\\t\\t\\t{\\n\\t\\t\\t\\tif(room == 0)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tcur += rightMost[floor] - room;\\n\\t\\t\\t\\t\\troom = rightMost[floor];\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\telse\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tcur += room - leftMost[floor];\\n\\t\\t\\t\\t\\troom = leftMost[floor];\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\n\\t\\t\\t\\tif(floor == maxFloor)\\n\\t\\t\\t\\t\\tbreak;\\n\\t\\t\\t\\tint nxtStairs = (stairs & (1 << floor)) == 0 ? 0 : m + 1;\\n\\t\\t\\t\\tcur += Math.abs(nxtStairs - room) + 1;\\n\\t\\t\\t\\t\\n\\t\\t\\t\\troom = nxtStairs;\\n\\t\\t\\t\\t++floor;\\n\\t\\t\\t}\\n\\t\\t\\tans = Math.min(ans, cur);\\n\\t\\t}\\n\\t\\t\\n\\t\\tSystem.out.println(ans);\\n\\t\\t\\n\\t\\tsc.close();\\n\\t}\\n}\"",
    "tags": [
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "812",
    "index": "C",
    "title": "Sagheer and Nubian Market",
    "statement": "On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains $n$ different items numbered from $1$ to $n$. The $i$-th item has base cost $a_{i}$ Egyptian pounds. If Sagheer buys $k$ items with indices $x_{1}, x_{2}, ..., x_{k}$, then the cost of item $x_{j}$ is $a_{xj} + x_{j}·k$ for $1 ≤ j ≤ k$. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor $k$.\n\nSagheer wants to buy as many souvenirs as possible without paying more than $S$ Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?",
    "tutorial": "If Sagheer can buy $k$ items, then he can also buy less than $k$ items because they will be within his budget. If he can't buy $k$ items, then can't also buy more than $k$ items because they will exceed his budget. So, we can apply binary search to find the best value for $k$. For each value $k$, we will compute the new prices, sort them and pick the minimum $k$ prices to find the best minimum cost for $k$ items. Complexity: $O(n\\log^{2}n)$",
    "code": "\"/**\\n * code generated by JHelper\\n * More info: https://g...content-available-to-author-only...b.com/AlexeyDmitriev/JHelper\\n * @author gainullin.ildar\\n */\\n\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\nconst int N = 1e5 + 7;\\n\\nint n, S;\\nint a[N];\\nll b[N];\\n\\nll res(int k)\\n{\\n    for (int i = 0; i < n; i++)\\n    {\\n        b[i] = a[i] + (i + 1) * (ll) k;\\n    }\\n    sort(b, b + n);\\n    ll ans = 0;\\n    for (int i = 0; i < k; i++)\\n    {\\n        ans += b[i];\\n    }\\n    return ans;\\n}\\n\\nclass Main\\n{\\npublic:\\n    void solve(std::istream &in, std::ostream &out)\\n    {\\n        in >> n >> S;\\n        for (int i = 0; i < n; i++)\\n        {\\n            in >> a[i];\\n        }\\n        int l = 0, r = n + 1;\\n        while (l < r - 1)\\n        {\\n            int m = (l + r) / 2;\\n            if (res(m) <= S)\\n            {\\n                l = m;\\n            }\\n            else\\n            {\\n                r = m;\\n            }\\n        }\\n        out << l << ' ' << res(l) << '\\\\n';\\n    }\\n};\\n\\n\\nint main()\\n{\\n    ios::sync_with_stdio(0);\\n    Main solver;\\n    std::istream &in(std::cin);\\n    std::ostream &out(std::cout);\\n    solver.solve(in, out);\\n    return 0;\\n}\\n\"",
    "tags": [
      "binary search",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "812",
    "index": "D",
    "title": "Sagheer and Kindergarten",
    "statement": "Sagheer is working at a kindergarten. There are $n$ children and $m$ different toys. These children use well-defined protocols for playing with the toys:\n\n- Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set.\n- If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever.\n- Children request toys at distinct moments of time. No two children request a toy at the same time.\n- If a child is granted a toy, he never gives it back until he finishes playing with his lovely set.\n- If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting.\n- If two children are waiting for the same toy, then the child who requested it first will take the toy first.\n\nChildren don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy.\n\nChildren are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set.\n\nNow, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child $x$ that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child $x$ is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child $x$ will make his last request, how many children will start crying?\n\nYou will be given the scenario and $q$ \\textbf{independent} queries. Each query will be of the form $x$ $y$ meaning that the last request of the child $x$ is for the toy $y$. Your task is to help Sagheer find the size of the \\textbf{maximal} crying set when child $x$ makes his last request.",
    "tutorial": "Let's go through scenario requests one by one. For request $a$ $b$, if toy $b$ is free, then child $a$ can take it. Otherwise, child $a$ will wait until the last child $c$ who requested toy $b$ finishes playing. Since, no child can wait for two toys at the same time, each child depends on at most one other child. So we can put an edge from the $a$ to $c$. Thus, we can model the scenario as a forest (set of rooted trees) as each node has at most one outgoing edge (to its parent). For query $x$ $y$, if toy $y$ is free, then child $x$ can take it and no child will cry. Otherwise, toy $y$ is held by another child. Lets denote $z$ to be the last child who requested toy $y$. So $x$ now depends on $z$. If $z$ is in the subtree of $x$, then all children in the subtree of $x$ will cry. Otherwise, no child will cry. We can check that a node is in the subtree of another node using euler walk ($t_{in}$ and $t_{out}$) with preprocessing in $O(n)$ and query time $O(1)$ Complexity: $O(k + n + q)$",
    "code": "\"/**\\n * code generated by JHelper\\n * More info: https://g...content-available-to-author-only...b.com/AlexeyDmitriev/JHelper\\n * @author gainullin.ildar\\n */\\n\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n\\nusing namespace std;\\n\\nconst int N = 1e5 + 7;\\n\\nvector<int> g[N];\\nint tin[N], tout[N];\\nint sz[N];\\nint tt = 1;\\n\\nvoid dfs(int v)\\n{\\n    tin[v] = tt++;\\n    sz[v] = 1;\\n    for (auto to : g[v])\\n    {\\n        dfs(to);\\n        sz[v] += sz[to];\\n    }\\n    tout[v] = tt++;\\n}\\n\\nbool pr(int a, int b)\\n{\\n    return (tin[a] <= tin[b] && tout[a] >= tout[b]);\\n}\\n\\nclass Main\\n{\\npublic:\\n    void solve(std::istream &in, std::ostream &out)\\n    {\\n        int n, m, k, q;\\n        in >> n >> m >> k >> q;\\n        tt = 1;\\n        for (int i = 1; i <= n; i++)\\n        {\\n            tin[i] = tout[i] = 0;\\n            g[i].clear();\\n        }\\n        vector<int> ind(m + 1, -1);\\n        vector<bool> root(n + 1, true);\\n        for (int i = 0; i < k; i++)\\n        {\\n            int v, a;\\n            in >> v >> a;\\n            if (ind[a] != -1)\\n            {\\n                g[ind[a]].push_back(v);\\n                root[v] = false;\\n            }\\n            ind[a] = v;\\n        }\\n        for (int i = 1; i <= n; i++)\\n        {\\n            if (root[i])\\n            {\\n                dfs(i);\\n            }\\n        }\\n        for (int i = 0; i < q; i++)\\n        {\\n            int v, a;\\n            in >> v >> a;\\n            a = ind[a];\\n            if (a == -1)\\n            {\\n                out << 0 << '\\\\n';\\n            }\\n            else\\n            {\\n                if (pr(v, a))\\n                {\\n                    out << sz[v] << '\\\\n';\\n                }\\n                else\\n                {\\n                    out << 0 << '\\\\n';\\n                }\\n            }\\n        }\\n    }\\n};\\n\\n\\nint main()\\n{\\n    ios::sync_with_stdio(0);\\n    Main solver;\\n    std::istream &in(std::cin);\\n    std::ostream &out(std::cout);\\n    solver.solve(in, out);\\n    return 0;\\n}\\n\"",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "812",
    "index": "E",
    "title": "Sagheer and Apple Tree",
    "statement": "Sagheer is playing a game with his best friend Soliman. He brought a tree with $n$ nodes numbered from $1$ to $n$ and rooted at node $1$. The $i$-th node has $a_{i}$ apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).\n\nSagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.\n\nIn each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things:\n\n- eat the apples, if the node is a leaf.\n- move the apples to one of the children, if the node is non-leaf.\n\nBefore Soliman comes to start playing, Sagheer will make \\textbf{exactly one change} to the tree. He will pick two different nodes $u$ and $v$ and swap the apples of $u$ with the apples of $v$.\n\nCan you help Sagheer count the number of ways to make the swap (i.e. to choose $u$ and $v$) after which he will win the game if both players play optimally? $(u, v)$ and $(v, u)$ are considered to be the same pair.",
    "tutorial": "In the standard nim game, we xor the values of all piles, and if the xor value is $0$, then the first player loses. Otherwise, he has a winning strategy. One variant of the nim game has an extra move that allows players to add positive number of stones to a single pile (given some conditions to make the game finite). The solution for this variant is similar to the standard nim game because this extra move will be used by the winning player, and whenever the losing player does it, the winning player can cancel it by throwing away these added stones. This problem can be modeled as the mentioned variant. Lets color leaf nodes with blue. The parent of a blue node is red and the parent of a red node is blue (that's why all paths from root to leaves must have the same parity). Blue nodes are our piles while red nodes allow discarding apples or increasing piles. If the xor value of blue nodes $s = 0$, then Soliman loses on the initial tree. To keep this state after the swap, Sagheer can: swap any two blue nodes or any two red nodes. swap a blue node with a red node if they have the same number of apples. If the xor value of blue nodes $s  \\neq  0$, then Sagheer loses on the initial tree. To flip this state after the swap, Sagheer must swap a blue node $u$ with a red node $v$ such that $s\\oplus a[u]\\oplus a[v]=0$ Complexity: $O(n + maxA)$ where $maxA$ is the maximum value for apples in a single node.",
    "code": "\"import java.io.BufferedReader;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.io.InputStreamReader;\\nimport java.io.PrintWriter;\\nimport java.util.ArrayList;\\nimport java.util.StringTokenizer;\\n\\npublic class SagheerAppleTree_AC1 {\\n\\n\\tstatic final int MAXA = 10000000;\\n\\tstatic ArrayList<Integer>[] adjList;\\n\\tstatic boolean[] blue;\\n\\tstatic int xorValue, cnt, cntBlue[], cntRed[],a[];\\n\\t\\n\\tstatic void dfs(int u)\\n\\t{\\n\\t\\tfor(int v: adjList[u])\\n\\t\\t\\tdfs(v);\\n\\t\\tblue[u] = adjList[u].size() == 0 || !blue[adjList[u].get(0)]; \\n\\t\\tif(blue[u])\\n\\t\\t{\\n\\t\\t\\txorValue ^= a[u];\\n\\t\\t\\tcntBlue[a[u]]++;\\n\\t\\t\\t++cnt;\\n\\t\\t}\\n\\t\\telse\\n\\t\\t\\tcntRed[a[u]]++;\\n\\t}\\n\\t\\n\\tpublic static void main(String[] args) throws IOException {\\n\\t\\tScanner sc = new Scanner(System.in);\\n\\t\\tPrintWriter out = new PrintWriter(System.out);\\n\\t\\t\\n\\t\\tint n = sc.nextInt();\\n\\t\\ta = new int[n];\\n\\t\\tfor(int i = 0; i < n; ++i)\\n\\t\\t\\ta[i] = sc.nextInt();\\n\\t\\tadjList = new ArrayList[n];\\n\\t\\tfor(int i = 0; i < n; ++i)\\n\\t\\t\\tadjList[i] = new ArrayList<>(1);\\n\\t\\tfor(int i = 1; i < n; ++i)\\n\\t\\t\\tadjList[sc.nextInt() - 1].add(i);\\n\\t\\tblue = new boolean[n];\\n\\t\\tcntBlue = new int[MAXA + 1];\\n\\t\\tcntRed = new int[MAXA + 1];\\n\\t\\tdfs(0);\\n\\t\\tlong ans = 0;\\n\\t\\tif(xorValue == 0)\\n\\t\\t{\\n\\t\\t\\tfor(int i = 1; i <= MAXA; ++i)\\n\\t\\t\\t\\tans += 1l * cntBlue[i] * cntRed[i];\\n\\t\\t\\tlong x = cnt, y = n - x;\\n\\t\\t\\tans += x * (x - 1) / 2 + y * (y - 1) / 2;\\n\\t\\t}\\n\\t\\telse\\n\\t\\t{\\n\\t\\t\\tfor(int i = 1; i <= MAXA; ++i)\\n\\t\\t\\t{\\n\\t\\t\\t\\tint j = xorValue ^ i;\\n\\t\\t\\t\\tif(j <= MAXA)\\n\\t\\t\\t\\t\\tans += 1l * cntBlue[i] * cntRed[j];\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tout.println(ans);\\n\\t\\tout.flush();\\n\\t\\tout.close();\\n\\t}\\n\\n\\tstatic class Scanner \\n\\t{\\n\\t\\tStringTokenizer st;\\n\\t\\tBufferedReader br;\\n\\n\\t\\tpublic Scanner(InputStream s){\\tbr = new BufferedReader(new InputStreamReader(s));}\\n\\n\\t\\tpublic String next() throws IOException \\n\\t\\t{\\n\\t\\t\\twhile (st == null || !st.hasMoreTokens()) \\n\\t\\t\\t\\tst = new StringTokenizer(br.readLine());\\n\\t\\t\\treturn st.nextToken();\\n\\t\\t}\\n\\n\\t\\tpublic int nextInt() throws IOException {return Integer.parseInt(next());}\\n\\n\\t\\tpublic long nextLong() throws IOException {return Long.parseLong(next());}\\n\\n\\t\\tpublic String nextLine() throws IOException {return br.readLine();}\\n\\n\\t\\tpublic double nextDouble() throws IOException { return Double.parseDouble(next()); }\\n\\n\\t\\tpublic boolean ready() throws IOException {return br.ready();} \\n\\t}\\n}\\n\"",
    "tags": [
      "games",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "813",
    "index": "A",
    "title": "The Contest",
    "statement": "Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!\n\nThis contest consists of $n$ problems, and Pasha solves $i$th problem in $a_{i}$ time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. \\textbf{Pasha can send any number of solutions at the same moment.}\n\nUnfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during $m$ time periods, $j$th period is represented by its starting moment $l_{j}$ and ending moment $r_{j}$. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment $T$ iff there exists a period $x$ such that $l_{x} ≤ T ≤ r_{x}$.\n\nPasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have \\textbf{solutions to all problems submitted}, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.",
    "tutorial": "Notice that we can keep solved tasks and then submit all at once. So the solution goes down to this: you should find the first moment of time $t$ that the site works at that moment and $t\\geq\\sum_{i=1}^{n}a_{i}$. Also it's convinient that the intervals are already sorted in increasing order. Let's sum up all elements of array $a$ and write it to some variable $sum$. The answer is obtained this way: if the sum lies in the current interval then the answer is the sum. Otherwise there are two cases. If there exists some interval $j$ that $l_{j}  \\ge  sum$ then the answer is $l_{j}$. In other case the answer is \"-1\".",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "813",
    "index": "B",
    "title": "The Golden Age",
    "statement": "Unlucky year in Berland is such a year that its number $n$ can be represented as $n = x^{a} + y^{b}$, where $a$ and $b$ are non-negative integer numbers.\n\nFor example, if $x = 2$ and $y = 3$ then the years 4 and 17 are unlucky ($4 = 2^{0} + 3^{1}$, $17 = 2^{3} + 3^{2} = 2^{4} + 3^{0}$) and year 18 isn't unlucky as there is no such representation for it.\n\nSuch interval of years that there are no unlucky years in it is called The Golden Age.\n\nYou should write a program which will find maximum length of The Golden Age which starts no earlier than the year $l$ and ends no later than the year $r$. If all years in the interval $[l, r]$ are unlucky then the answer is 0.",
    "tutorial": "Notice that $x^{a}$ for $x  \\ge  2$ has no more than 60 powers which give numbers no greater than $10^{18}$. So let's store all possible sums of all powers of $x$ and $y$. Now the answer to the query can be obtained in linear time by checking difference between neighbouring unlucky years in sorted order. Don't forget that you should handle multiplying of such big numbers very carefully. For example, instead of writing or you should write to avoid getting overflow errors of 64-bit type. Integer division will work fine in that case because $num \\cdot x$ will never exceed $10^{18}$ if $num$ doesn't exceed $\\textstyle{\\frac{|0^{18}\\rangle}{x}}$. Overall complexity: $O(n\\cdot\\log n)$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "813",
    "index": "C",
    "title": "The Tag Game",
    "statement": "Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of $n$ vertices. Vertex 1 is the root of the tree.\n\nAlice starts at vertex 1 and Bob starts at vertex $x$ ($x ≠ 1$). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.\n\nThe game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.\n\nYou should write a program which will determine how many moves will the game last.",
    "tutorial": "If you check some games then you will notice that the most optimal strategy for Bob is always like this: Climb up for some steps (possibly zero) Go to the lowest vertex from it Stay in this vertex till the end Thus let's precalc the depth (the distance from the root) of the lowest vertex of each subtree (using dfs), distance from Alice's starting node and from Bob's starting node to the vertex (again dfs/bfs). Now iterate over all vertices and check if Bob can reach this vertex earlier than Alice. If he can then update the answer with the lowest vertex that can be reached from this one. The answer is doubled depth of the obtained lowest reachable vertex. That is the time which will take Alice to get there. Overall complexity: $O(n)$.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "813",
    "index": "D",
    "title": "Two Melodies",
    "statement": "Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time!\n\nAlice has a sheet with $n$ notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal.\n\nSubsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.\n\nSubsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7.\n\nYou should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.",
    "tutorial": "Let's solve this problem with dynamic programming. Let $dp[x][y]$ be the maximum answer if one melody finishes in note number $x$ and another melody - in note number $y$. $x$ and $y$ are $1$-indexed; if one of them is $0$, then the melody is empty. How shall we update $dp[x][y]$? First of all, we will update from previous $dp$ values only if $x > y$. If $x = y$, then obviously answer is $0$, and if $x < y$, then we take the answer for $dp[y][x]$. Secondly, to avoid intersections, we will update $dp[x][y]$ only using values of $dp[i][y]$, where $i  \\neq  y$ and $i < x$. Why? Because if we update $dp[x][y]$ from some $dp[x][i]$, and $x > y$, then it can lead to some intersection (we can't guarantee we didn't use $i$ in the first melody). How can we make fast updates? We will count $dp$ from $y = 0$ to $y = n$. Then, while counting $dp$ for some specific $y$, we will maintain two arrays: $maxmod[j]$ - the maximum value of $dp[i][y]$ encountered so far where $a[i] mod 7 = j$; $maxnum[j]$ - the maximum value of $dp[i][y]$ encountered so far where $a[i] = j$. So when we need to count $dp[x][y]$, it will be the maximum of four values: $maxmod[a[x] mod 7] + 1$ - if we add a note which is congruent modulo $7$ with the last one; $maxnum[a[x] + 1] + 1$ - if we add a note which is less by $1$ than the last note; $maxnum[a[x] - 1] + 1$ - if we add a note which is greater by $1$ than the last note; $dp[0][y] + 1$ - if we just start a melody. These values can be calculated in $O(n^{2})$.",
    "tags": [
      "dp",
      "flows"
    ],
    "rating": 2600
  },
  {
    "contest_id": "813",
    "index": "E",
    "title": "Army Creation",
    "statement": "As you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires.\n\nIn the game Vova can hire $n$ different warriors; $i$th warrior has the type $a_{i}$. Vova wants to create a balanced army hiring some subset of warriors. An army is called balanced if for each type of warrior present in the game there are not more than $k$ warriors of this type in the army. Of course, Vova wants his army to be as large as possible.\n\nTo make things more complicated, Vova has to consider $q$ different plans of creating his army. $i$th plan allows him to hire only warriors whose numbers are not less than $l_{i}$ and not greater than $r_{i}$.\n\nHelp Vova to determine the largest size of a balanced army for each plan.\n\n\\textbf{Be aware that the plans are given in a modified way. See input section for details.}",
    "tutorial": "Every time we process a plan, let's count only the first $k$ warriors of some type. When will the warrior on position $i$ be counted? Of course, he has to be present in the plan, so $l  \\le  i  \\le  r$. But also he has to be among $k$ first warriors of his type in this plan. Let's denote a function $prev(x, y)$: $prev(x, 1)$ is the position of previous warrior of the same type before warrior $x$ (that is, the greatest $i$ such that $i < x$ and $a_{i} = a_{x}$). If there's no any, then $prev(x, 1) = - 1$; $prev(x, y) = prev(prev(x, 1), y - 1))$ if $y > 1$. It is easy to prove that the warrior $x$ will be among $k$ first warriors in some plan iff $l > prev(x, k)$ and $x  \\le  r$. So we can make a new array $b$: $b_{i} = prev(i, k)$. Then we build a segment tree on this array. The node of the segment tree will store all values of $b_{i}$ from the segment corresponding to this node (in sorted order). Then to get answer to the plan, we have to count the number of elements on segment $[l, r]$ that are less than $l$. Complexity is $O((n+q)\\log^{2}n)$, or $O((n+q)\\log n)$ if you use fractional cascading technique.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "813",
    "index": "F",
    "title": "Bipartite Checking",
    "statement": "You are given an undirected graph consisting of $n$ vertices. Initially there are no edges in the graph. Also you are given $q$ queries, each query either adds one undirected edge to the graph or removes it. After each query you have to check if the resulting graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color).",
    "tutorial": "If the edges were only added and not deleted, it would be a common problem that is solved with disjoint set union. All you need to do in that problem is implement a DSU which maintains not only the leader in the class of some vertex, but also the distance to this leader. Then, if we try to connect two vertices that have the same leader in DSU and the sum of distances to this leader is even, then we get a cycle with odd length, and graph is no longer bipartite. But in this problem we need to somehow process removing edges from the graph. In the algorithm I will describe below we will need to somehow remove the last added edge from DSU (or even some number of last added edges). How can we process that? Each time we change some variable in DSU, we can store an address of this variable and its previous value somewhere (for example, in a stack). Then to remove last added edge, we rollback these changes - we rewrite the previous values of the variables we changed by adding the last edge. Now we can add a new edge and remove last added edge. All these operations cost $(O(logn))$ because we won't use path compression in DSU - path compression doesn't work in intended time if we have to rollback. Let's actually start solving the problem. For convinience, we change all information to queries like \"edge $(x, y)$ exists from query number $l$ till query number $r$\". It's obvious that there are no more than $q$ such queries. Let's use divide-and-conquer technique to make a function that answers whether the graph is bipartite or not after every query from some segment of queries $[a, b]$. First of all, we add to DSU all the edges that are present in the whole segment (and not added yet); then we solve it recursively for $\\left[a,\\left[{\\frac{a+b}{2}}\\right]\\right]$ and $\\left[\\left({\\frac{a+b}{2}}\\right)+1,b\\right]$; then we remove edges from DSU using the rollback technique described above. When we arrive to some segment $[a, a]$, then after adding the edges present in this segment we can answer if the graph is bipartite after query $a$. Remember to get rid of the edges that are already added and the edges that are not present at all in the segment when you make a recursive call. Of course, to solve the whole problem, we need to call our function from segment $[1, q]$. Time complexity is $O(q\\log^{2}q)$, because every edge will be added only in $O(\\log q)$ calls of the function.",
    "tags": [
      "data structures",
      "dsu",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "814",
    "index": "A",
    "title": "An abandoned sentiment from past",
    "statement": "A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed.\n\nTo get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long time, but now Kaiki provides an opportunity.\n\nHitagi's sequence $a$ has a length of $n$. Lost elements in it are denoted by zeros. Kaiki provides another sequence $b$, whose length $k$ equals the number of lost elements in $a$ (i.e. the number of zeros). Hitagi is to replace each zero in $a$ with an element from $b$ so that \\textbf{each element in $b$ should be used exactly once}. Hitagi knows, however, that, \\textbf{apart from $0$, no integer occurs in $a$ and $b$ more than once in total.}\n\nIf the resulting sequence is \\textbf{not} an increasing sequence, then it has the power to recover Hitagi from the oddity. You are to determine whether this is possible, or Kaiki's sequence is just another fake. In other words, you should detect whether it is possible to replace each zero in $a$ with an integer from $b$ so that each integer from $b$ is used exactly once, and the resulting sequence is \\textbf{not} increasing.",
    "tutorial": "The statement laid emphasis on the constraint that the elements are pairwise distinct. How is this important? In fact, this implies that if the resulting sequence is increasing, then swapping any two of its elements will result in another sequence which is not increasing. And we're able to perform a swap on any resulting sequence if and only if $k  \\ge  2$. Thus if $k  \\ge  2$, the answer would always be \"Yes\". For cases where $k = 1$, we replace the only zero in sequence $a$ with the only element in $b$, and check the whole sequence. Hackable solutions include those only checking the replaced element and its neighbours, and those missing the replaced element.",
    "code": "#include <cstdio>\n#include <algorithm>\nstatic const int MAXN = 102;\n\nint n, k;\nint a[MAXN], b[MAXN];\nint p[MAXN], r[MAXN];\n\ninline bool check()\n{\n    for (int i = 1; i < n; ++i) if (r[i] <= r[i - 1]) return true;\n    return false;\n}\n\nint main()\n{\n    scanf(\"%d%d\", &n, &k);\n    int last_zero = -1;\n    for (int i = 0; i < n; ++i) {\n        scanf(\"%d\", &a[i]);\n        if (a[i] == 0) last_zero = i;\n    }\n    for (int i = 0; i < k; ++i) scanf(\"%d\", &b[i]);\n\n    bool valid = false;\n    for (int i = 0; i < k; ++i) p[i] = i;\n    do {\n        for (int i = 0, ptr = 0; i < n; ++i) {\n            r[i] = (a[i] == 0) ? b[p[ptr++]] : a[i];\n        }\n        if (check()) { valid = true; break; }\n    } while (std::next_permutation(p, p + k));\n    puts(valid ? \"Yes\" : \"No\");\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "814",
    "index": "B",
    "title": "An express train to reveries",
    "statement": "Sengoku still remembers the mysterious \"colourful meteoroids\" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.\n\nOn that night, Sengoku constructed a permutation $p_{1}, p_{2}, ..., p_{n}$ of integers from $1$ to $n$ inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with $n$ meteorids, colours of which being integer sequences $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{n}$ respectively. Meteoroids' colours were also between $1$ and $n$ inclusive, and the two sequences were not identical, that is, at least one $i$ ($1 ≤ i ≤ n$) exists, such that $a_{i} ≠ b_{i}$ holds.\n\nWell, she almost had it all — each of the sequences $a$ and $b$ matched exactly $n - 1$ elements in Sengoku's permutation. In other words, there is exactly one $i$ ($1 ≤ i ≤ n$) such that $a_{i} ≠ p_{i}$, and exactly one $j$ ($1 ≤ j ≤ n$) such that $b_{j} ≠ p_{j}$.\n\nFor now, Sengoku is able to recover the actual colour sequences $a$ and $b$ through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.",
    "tutorial": "Permutating directly no longer works here. Let's try to dig something out from the constraints. Imagine that we take a permutation $p_{1... n}$, and change one of its elements to a different integer in $[1, n]$, resulting in the sequence $p'_{1... n}$. There are exactly $2$ positions $i, j$ ($i  \\neq  j$) such that $p'_{i} = p'_{j}$, while the other $n - 2$ elements are kept untouched. This is actually what $a$ and $b$ satisfy. Find out these two positions in $a$, and the two candidates for them - that is, the only two numbers not present in the remaining $n - 2$ elements. Iterate over their two possible orders, and check the validity against sequence $b$. Of course you can solve this with casework if you like.",
    "code": "#include <cstdio>\n#include <utility>\nstatic const int MAXN = 1e3 + 4;\n\nint n;\nint a[MAXN], b[MAXN];\n\nstd::pair<int, int> get_duplication(int *a)\n{\n    static int occ[MAXN];\n    for (int i = 1; i <= n; ++i) occ[i] = -1;\n    for (int i = 0; i < n; ++i) {\n        if (occ[a[i]] != -1) return std::make_pair(occ[a[i]], i);\n        else occ[a[i]] = i;\n    }\n    return std::make_pair(-1, -1);\n}\n\ninline void fix_permutation(int pos)\n{\n    static bool occ[MAXN];\n    for (int i = 1; i <= n; ++i) occ[i] = false;\n    for (int i = 0; i < n; ++i) if (i != pos) occ[a[i]] = true;\n    for (int i = 1; i <= n; ++i) if (!occ[i]) { a[pos] = i; return; }\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) scanf(\"%d\", &a[i]);\n    for (int i = 0; i < n; ++i) scanf(\"%d\", &b[i]);\n\n    std::pair<int, int> dup_a, dup_b;\n    dup_a = get_duplication(a);\n    dup_b = get_duplication(b);\n\n    if (dup_a == dup_b) {\n        a[dup_a.first] = b[dup_b.first];\n    } else if (dup_a.first == dup_b.first || dup_a.first == dup_b.second) {\n        a[dup_a.second] = b[dup_a.second];\n        fix_permutation(dup_a.first);\n    } else if (dup_a.second == dup_b.first || dup_a.second == dup_b.second) {\n        a[dup_a.first] = b[dup_a.first];\n        fix_permutation(dup_a.second);\n    } else {\n        a[dup_a.first] = b[dup_a.first];\n        a[dup_a.second] = b[dup_a.second];\n    }\n\n    for (int i = 0; i < n; ++i) printf(\"%d%c\", a[i], i == n - 1 ? '\\n' : ' ');\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1300
  },
  {
    "contest_id": "814",
    "index": "C",
    "title": "An impassioned circulation of affection",
    "statement": "Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!\n\nStill unsatisfied with the garland, Nadeko decided to polish it again. The garland has $n$ pieces numbered from $1$ to $n$ from left to right, and the $i$-th piece has a colour $s_{i}$, denoted by a lowercase English letter. Nadeko will repaint \\textbf{at most} $m$ of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour $c$ — Brother Koyomi's favourite one, and takes the length of the longest among them to be the \\underline{Koyomity} of the garland.\n\nFor instance, let's say the garland is represented by \"kooomo\", and Brother Koyomi's favourite colour is \"o\". Among all subsegments containing pieces of \"o\" only, \"ooo\" is the longest, with a length of $3$. Thus the \\underline{Koyomity} of this garland equals $3$.\n\nBut problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has $q$ plans on this, each of which can be expressed as a pair of an integer $m_{i}$ and a lowercase letter $c_{i}$, meanings of which are explained above. You are to find out the maximum \\underline{Koyomity} achievable after repainting the garland according to each plan.",
    "tutorial": "The first thing to notice is that we are only changing other colours to Koyomi's favourite one. Furthermore, we won't create disconnected segments of that colour, for that's no better than painting just around the longest among them. This leads us to a straightforward approach: when faced with a query $(m, c)$, we check each segment $[l, r]$ and determine whether it's possible to fill this segment with letter $c$, within at most $m$ replacements. This can be done by finding the number of times $c$ occurs in that segment (denote it by $t_{c}$), and checking whether $(r - l + 1) - t  \\le  m$. But this $O(n^{2} \\cdot q)$ solution would be too slow. Since the number of different queries is $26n$, we can calculate all answers beforehand. For each letter $c$ and a segment $[l, r]$, we'll be able to fill the whole segment with $c$ within $(r - l + 1) - t_{c}$ moves. Use this information to update the answers, and employing a \"prefix max\" method gives us a time complexity of $O(n^{2} \\cdot | \\Sigma | + q)$, where $| \\Sigma |$ equals $26$. Refer to the code for a possible implementation.",
    "code": "#include <cstdio>\n#include <algorithm>\nstatic const int MAXN = 1502;\nstatic const int ALPHABET = 26;\n\nint n;\nchar s[MAXN];\nint ans[ALPHABET][MAXN] = {{ 0 }};\nint q, m_i;\nchar c_i;\n\nint main()\n{\n    scanf(\"%d\", &n); getchar();\n    for (int i = 0; i < n; ++i) s[i] = getchar() &mdash; 'a';\n\n    for (char c = 0; c < ALPHABET; ++c) {\n        for (int i = 0; i < n; ++i) {\n            int replace_ct = 0;\n            for (int j = i; j < n; ++j) {\n                if (s[j] != c) ++replace_ct;\n                ans[c][replace_ct] = std::max(ans[c][replace_ct], j - i + 1);\n            }\n        }\n        for (int i = 1; i < MAXN; ++i)\n            ans[c][i] = std::max(ans[c][i], ans[c][i - 1]);\n    }\n\n    scanf(\"%d\", &q);\n    for (int i = 0; i < q; ++i) {\n        scanf(\"%d %c\", &m_i, &c_i);\n        printf(\"%d\\n\", ans[c_i - 'a'][m_i]);\n    }\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "strings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "814",
    "index": "D",
    "title": "An overnight dance in discotheque",
    "statement": "The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?\n\nThe discotheque can be seen as an infinite $xy$-plane, in which there are a total of $n$ dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area $C_{i}$ described by a center $(x_{i}, y_{i})$ and a radius $r_{i}$. \\textbf{No two ranges' borders have more than one common point}, that is for every pair $(i, j)$ ($1 ≤ i < j ≤ n$) either ranges $C_{i}$ and $C_{j}$ are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges.\n\nTsukihi, being one of them, defines the \\underline{spaciousness} to be \\textbf{the area covered by an odd number of movement ranges of dancers who are moving}. An example is shown below, with shaded regions representing the \\underline{spaciousness} if everyone moves at the same time.\n\nBut no one keeps moving for the whole night after all, so the whole night's time is divided into two halves — before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The \\underline{spaciousness} of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above.\n\nBy different plans of who dances in the first half and who does in the other, different sums of \\underline{spaciousness} over two halves are achieved. You are to find the largest achievable value of this sum.",
    "tutorial": "Circles' borders do not intersect, that is, each circle is \"directly\" contained in another circle, or is among the outermost ones. Can you see a tree/forest structure out of this? We create a node for each of the circles $C_{i}$, with weight equal to its area $ \\pi  r_{i}^{2}$. Its parent is the circle which \"directly\" contains it, namely the one with smallest radius among those circles containing $C_{i}$. If a circle is an outermost one, then it's made a root. This tree structure can be found in $O(n^{2})$ time. Consider what happens if there's only one group: the spaciousness equals the sum of weights of all nodes whose depths are even, minus the sum of weights of all nodes whose depths are odd. Now we are to split the original tree/forest into two disjoint groups. This inspires us to think of a DP approach - consider a vertex $u$, and the parity (oddness/evenness) of number of nodes in its ancestors from the first and the second group. Under this state, let $f[u][0 / 1][0 / 1]$ be the largest achievable answer in $u$'s subtree. The recursion can be done from bottom to top in $O(1)$, and the answer we need is the sum of $f[u][0][0]$ for all $u$ being roots. Time complexity is $O(n^{2})$ for the tree part and $O(n)$ for the DP part. See the code for the complete recursion.",
    "code": "#include <cstdio>\n#include <cmath>\n#include <algorithm>\n#include <vector>\ntypedef long long int64;\nstatic const int MAXN = 1004;\n#ifndef M_PI\nstatic const double M_PI = acos(-1.0);\n#endif\n\nint n;\nint x[MAXN], y[MAXN], r[MAXN];\nint par[MAXN];\nstd::vector<int> e[MAXN];\n\nbool level[MAXN];\n\n// Whether one of C[u] and C[v] is contained in another\ninline bool circle_contains(int u, int v)\n{\n    return ((int64)(x[u] - x[v]) * (x[u] - x[v]) + (int64)(y[u] - y[v]) * (y[u] - y[v]) <= (int64)(r[u] - r[v]) * (r[u] - r[v]));\n}\n\nvoid dfs_colour(int u, bool c)\n{\n    level[u] = c;\n    for (int v : e[u]) dfs_colour(v, c ^ 1);\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) scanf(\"%d%d%d\", &x[i], &y[i], &r[i]);\n\n    for (int i = 0; i < n; ++i) {\n        par[i] = -1;\n        for (int j = 0; j < n; ++j)\n            if (r[j] > r[i] && circle_contains(i, j)) {\n                if (par[i] == -1 || r[par[i]] > r[j]) par[i] = j;\n            }\n        e[par[i]].push_back(i);\n    }\n\n    for (int i = 0; i < n; ++i) if (par[i] == -1) dfs_colour(i, false);\n    int64 ans = 0;\n    for (int i = 0; i < n; ++i)\n        ans += (int64)r[i] * r[i] * (par[i] == -1 || (level[i] == true) ? +1 : -1);\n    printf(\"%.8lf\\n\", (double)ans * M_PI);\n\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "geometry",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "814",
    "index": "E",
    "title": "An unavoidable detour for home",
    "statement": "Those unwilling to return home from a long journey, will be affected by the oddity of the snail and lose their way. Mayoi, the oddity's carrier, wouldn't like this to happen, but there's nothing to do with this before a cure is figured out. For now, she would only like to know the enormous number of possibilities to be faced with if someone gets lost.\n\nThere are $n$ towns in the region, numbered from $1$ to $n$. The town numbered $1$ is called the capital. The traffic network is formed by bidirectional roads connecting pairs of towns. No two roads connect the same pair of towns, and no road connects a town with itself. The time needed to travel through each of the roads is the same. Lost travelers will not be able to find out how the towns are connected, but the residents can help them by providing the following facts:\n\n- Starting from each town other than the capital, the shortest path (i.e. the path passing through the minimum number of roads) to the capital exists, and is unique;\n- Let $l_{i}$ be the number of roads on the shortest path from town $i$ to the capital, then $l_{i} ≥ l_{i - 1}$ holds for all $2 ≤ i ≤ n$;\n- For town $i$, the number of roads connected to it is denoted by $d_{i}$, which equals either $2$ or $3$.\n\nYou are to count the number of different ways in which the towns are connected, and give the answer modulo $10^{9} + 7$. Two ways of connecting towns are considered different if a pair $(u, v)$ ($1 ≤ u, v ≤ n$) exists such there is a road between towns $u$ and $v$ in one of them but not in the other.",
    "tutorial": "Let's make it intuitive: the graph looks like this. Formally, if we find out the BFS levels of the graph, it will look like a tree with extra edges among vertices of the same level, and indices of vertices in the same level form a consecutive interval. Therefore we can add vertices from number $1$ to number $n$ to the graph, without missing or violating anything. Consider the case when we want to add vertex $u$ to a graph formed by the first $u - 1$ vertices. The state only depend on the current and the previous level (We can't start level $l + 1$ without finishing level $l - 1$, thus there are only two unfinished levels). The whole thing is described by four parameters: the number of \"1-plug\" (having one outgoing edge that is not determined) and \"2-plug\" (similar definition) vertices in the previous and the current level. Let $f[u][p_{1}][p_{2}][c_{1}][c_{2}]$ be the number of ways to build the graph with the first $u$ vertices, with $p_{1}$ \"1-plug\" vertices and $p_{2}$ \"2-plug\" vertices in the previous level, and $c_{1}$ and $c_{2}$ in the current one respectively. For vertex $u$, we must choose one vertex $v$ in the previous layer and connect $u$ to it. For the remaining degree(s) of $u$, we can choose either to connect them to vertices in the same layer, or simply leave them for future. Also, we may start a new level if $p_{1} = p_{2} = 0$. This gives us an $O(1)$ recursion. There are $O(n^{5})$ states, giving us a time complexity of $O(n^{5})$ and a space complexity of $O(n^{4})$ if the first dimension is reused. The constant factor can be rather small (since $p_{1} + p_{2} + c_{1} + c_{2}  \\le  n$). See solution 1 for detailed recursion. Let's try to improve this a bit. Instead of adding one vertex at a time, we consider the layer as a whole. Let $f[c_{0}][c_{1}][c_{2}]$ be the number of ways to build a single level with $c_{0}$ vertices (their \"plugs\" don't matter), and connect it to the previous layer which has $c_{1}$ \"1-plug\" vertices and $c_{2}$ \"2-plug\" ones. Recursion over $f$ can be done in $O(1)$. Then let $g[l][r]$ be the number of ways to build the graph with vertices from $l$ to $n$, while vertices from $l$ to $r$ form the first level - note that this level should be connected to another previous one. The recursion over $g$ can be done in $O(n)$. The final answer should be $g[2][d_{1}]$ since the capital must be directly connected to vertices from $2$ to $d_{1}$. The overall time complexity is $O(n^{3})$. Huge thanks to Nikolay Kalinin (KAN) for this!",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n\n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nconst int maxn = 55;\nconst int MOD = 1000000007;\n\nint ways[maxn][maxn][maxn];\nint answer[maxn][maxn];\nint n;\nint d[maxn];\nint sumd[maxn];\n\ninline void add(int &a, ll b)\n{\n    a = (a + b) % MOD;\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; i++) scanf(\"%d\", &d[i]);\n    \n    ways[0][0][0] = 1;\n    for (int c0 = 0; c0 <= n; c0++)\n    {\n        for (int c2 = 0; c2 <= n; c2++)\n        {\n            for (int c1 = 0; c1 <= n; c1++) if (c1 + c2 > 0)\n            {\n                if (c2 > 0)\n                {\n                    if (c0 > 1) add(ways[c0][c1][c2], (ll)ways[c0 - 2][c1][c2 - 1] * (c0 * (c0 - 1) / 2)); // 2-0, 2-0\n                    if (c2 > 1 && c0 > 0) add(ways[c0][c1][c2], (ll)ways[c0 - 1][c1 + 1][c2 - 2] * (c2 - 1) * c0); // 2-2, 2-0\n                    if (c2 > 2) add(ways[c0][c1][c2], (ll)ways[c0][c1 + 2][c2 - 3] * ((c2 - 1) * (c2 - 2) / 2)); // 2-2, 2-2\n                    if (c1 > 0 && c2 > 1) add(ways[c0][c1][c2], (ll)ways[c0][c1][c2 - 2] * c1 * (c2 - 1)); // 2-2, 2-1\n                    if (c1 > 0 && c0 > 0) add(ways[c0][c1][c2], (ll)ways[c0 - 1][c1 - 1][c2 - 1] * c1 * c0); // 2-1, 2-0\n                    if (c1 > 1) add(ways[c0][c1][c2], (ll)ways[c0][c1 - 2][c2 - 1] * (c1 * (c1 - 1) / 2)); // 2-1, 2-1\n                } else\n                {\n                    if (c0 > 0) add(ways[c0][c1][c2], (ll)ways[c0 - 1][c1 - 1][c2] * c0); // 1-0\n                    if (c1 > 1) add(ways[c0][c1][c2], (ll)ways[c0][c1 - 2][c2] * (c1 - 1)); // 1-1\n                }\n            }\n        }\n    }\n    \n    for (int i = 0; i < n; i++) sumd[i + 1] = sumd[i] + d[i];\n    answer[n][n - 1] = 1;\n    for (int l = n - 1; l > 0; l--)\n    {\n        for (int r = l; r < n; r++)\n        {\n            int cnt2 = sumd[r + 1] - sumd[l] - 2 * (r - l + 1);\n            int cnt1 = r - l + 1 - cnt2;\n            for (int nextlvl = 0; nextlvl <= 2 * cnt2 + cnt1 && nextlvl <= n; nextlvl++)\n            {\n                int curways = ways[nextlvl][cnt1][cnt2];\n                if (r + nextlvl < n)\n                {\n                    add(answer[l][r], (ll)answer[r + 1][r + nextlvl] * curways);\n                }\n            }\n        }\n    }\n    if (d[0] + 1 > n) cout << 0 << endl;\n    else cout << answer[1][d[0]] << endl;\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "815",
    "index": "A",
    "title": "Karen and Game",
    "statement": "On the way to school, Karen became fixated on the puzzle game on her phone!\n\nThe game is played as follows. In each level, you have a grid with $n$ rows and $m$ columns. Each cell originally contains the number $0$.\n\nOne move consists of choosing one row or column, and adding $1$ to all of the cells in that row or column.\n\nTo win the level, after all the moves, the number in the cell at the $i$-th row and $j$-th column should be equal to $g_{i, j}$.\n\nKaren is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!",
    "tutorial": "Fix the number of times we choose the first row. Say we choose the first row $k$ times. This actually uniquely determines the rest of the solution; consider the cells on the first row. There is no other way to increase these cells, except by choosing the columns they are on, and so we need to choose the $j$-th column $g_{1, j} - k$ times. Now, once we know the number of times we have to choose each column, we will also know how many times to choose the remaining rows. At this point, for any given row $i$, the remaining number of times we have to choose it is $g_{i, j} - (g_{1, j} - k)$, this should be the same for all $j$ in a given row (otherwise there is no solution). We can simply try all $k$, see if they can form a valid solution, and if so, calculate how many moves it will take. Find the smallest required number of moves, and then recover the solution. Implemented properly, it should run in $O(n)$ time, which should be fast enough. Note that there are $O(max g_{i, j})$ possible choices for $k$, and testing a certain $k$ can be done in $O(nm)$ time. A solution will have at most $O(max(n, m) \\cdot max g_{i, j})$ moves, so printing them will take that much time. Overall, this solution hence runs in $O(nm \\cdot max g_{i, j})$ time, which is acceptable. There is a faster solution to this, both in terms of runtime and implementation time, which we will describe below. Notice that, when there is a $0$ on the grid, all the moves are already fixed. If the $0$ is at $g_{i, j}$, then we need to choose row $i'$ exactly $g_{i', j}$ times, and column $j'$ exactly $g_{i, j'}$ times. What if there is no $0$ on the grid? Well, we intuitively want to reduce numbers as much as possible, and in fact the greedy algorithm works here. If there are not more rows $(n  \\le  m)$, we should keep choosing rows, and if there are fewer columns $(n > m)$, we should keep choosing columns, until there is a $0$. It doesn't even matter which particular rows or columns we choose; for example, if $n  \\le  m$, we could just keep choosing row $1$ until a $0$ appears, or we could choose all rows $1, 2, 3, ..., n$ in order and just keep cycling through them. The end result will be the same. We can just check that the grid is correct at the end and print $- 1$ otherwise. Implemented properly, this runs in $O(nm + max(n, m) \\cdot max g_{i, j})$, which is asymptotically optimal; it takes at least $O(nm)$ time to read the input, and $O(max(n, m) \\cdot max g_{i, j})$ to print the output.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "815",
    "index": "B",
    "title": "Karen and Test",
    "statement": "Karen has just arrived at school, and she has a math test today!\n\nThe test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.\n\nThere are $n$ integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.\n\nNote that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.\n\nThe teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.\n\nKaren has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?\n\nSince this number can be quite large, output only the non-negative remainder after dividing it by $10^{9} + 7$.",
    "tutorial": "There are a couple of ways to solve this problem. The easiest way is to calculate the coefficients, or \"contributions\", of each number to the final sequence. In fact, the contribution of any number is determined by its position as well as the $n$. To do this, using brute force, we can compute the contribution of each element by just running a brute-force on $0, 0, 0, ..., 1, ..., 0, 0, 0$ for all positions $1$ and then trying to observe patterns. In any case, one should eventually realize that the pattern depends on $n{\\mathrm{~mod~}}4$: When $n{\\mathrm{~mod~}}4=0$, the pattern is: $\\bigl(\\stackrel{(n-2)/2}{0}\\bigr),-\\Bigl(\\stackrel{(n-2)/2}{0}\\bigr),\\bigl(\\stackrel{(n-2)/2}{1}\\bigr),\\bigl(\\stackrel{(n-2)/2}{2}\\bigr),-\\bigl(\\stackrel{(n-2)/2}{1}\\bigr),-\\bigl(\\stackrel{(n-2)/2}\\bigr),\\nonumber\\bigr(\\stackrel{(n-2)/2}{2}\\bigr),\\ldots.$ When $n{\\mathrm{~mod~}}4=1$, the pattern is: $\\left(\\begin{array}{l}{{(n-1)/2}}\\\\ {{0}}\\end{array}\\right),(\\begin{array}{l}{{\\left(n-1\\right)/2}}\\\\ {{1}}\\end{array}\\right),(\\begin{array}{l}{{\\left(n-1\\right)/2}}\\\\ {{2}}\\end{array}\\right),(\\not=.$ When $n{\\mathrm{~mod~}}4=2$, the pattern is: $\\bigl(\\stackrel{(n-2)/2}{0}\\bigr),\\bigl(\\stackrel{(n-2)/2}{0}\\bigr),\\bigl(\\stackrel{(n-2)/2}{1}\\bigr),\\bigl(\\stackrel{(n-2)/2}{2}\\bigr),\\bigl(\\stackrel{(n-2)/2}\\bigr),\\bigl(\\stackrel{(n-2)/2}{2}\\bigr),\\nonumber\\cdot\\cdot\\cdot.$ When $n{\\mathrm{~mod~}}4=3$, the pattern is: $(^{(n-3)/2}),2{\\binom{(n-3)/2}{0}},({^{(n-3)/2}}),({^{(n-3)/2}})-{\\big(}^{(n-3)/2}{\\big)},2{\\binom{(n-3)/2}{1}},2{\\binom{(n-3)/2}{2}}{\\big)},2{\\big(}{^{(n-3)/2}}{\\big)},2{\\big(}{^{(n-3)/2}}{\\big)}...\\cdots$ This is perhaps what most contestants did in the contest. We will not prove that this is correct; instead, a more elegant solution will be suggested. First, simplify the problem so that only addition ever happens. In fact, this version is much easier: the contribution of the $\\textstyle\\int_{\\lambda}{\\mathrm{th}}$ element when there are $n$ elements is precisely $\\textstyle{\\binom{n-1}{k-1}}$. Now, let's go back to the original task. We will repeatedly perform the operation until the number of elements $n$ is even, and the first operation is addition, to reduce the number of cases we have to handle. It can be observed that, regardless of our starting $n$, this will happen somewhere within the first two rows. We can therefore just brute force it. Observe the following picture: Consider the blue elements only. Am I the only one whose mind is on the verge of exploding? Notice that they are doing precisely the simpler version of the task! In other words, if we consider only $a_{1}, a_{3}, a_{5}, ...$, we are basically solving the simple version of the task! In fact, the same can be said of $a_{2}, a_{4}, a_{6}, ...$. Why is this true? Well, look at the picture. Notice that, if we have an even number of elements with the first element being addition, then, after $4$ rows, it will again be even and the first element will also be addition, so the pattern simply continues! We can hence compute the final two values on the second to last row, and then add or subtract them, depending on what the final operation should be. In fact, this also explains the patterns we observed for $n{\\mathrm{~mod~}}4=0$ and $n{\\mathrm{~mod~}}4=2$! To compute $\\textstyle{\\binom{n}{k}}$ quickly, we can use the formula ${\\binom{n}{k}}={\\frac{n!}{k!(n-k)!}}$. We can just preprocess all relevant factorials in $O(n)$, and also their modular multiplicative inverses modulo $10^{9} + 7$ in order to perform the division. This runs in $O(n\\log(10^{9}+7))$ or just $O(n)$ if you are willing to consider the $\\log(10^{9}+7)$ a constant.",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "815",
    "index": "C",
    "title": "Karen and Supermarket",
    "statement": "On the way home, Karen decided to stop by the supermarket to buy some groceries.\n\nShe needs to buy a lot of goods, but since she is a student her budget is still quite limited. In fact, she can only spend up to $b$ dollars.\n\nThe supermarket sells $n$ goods. The $i$-th good can be bought for $c_{i}$ dollars. Of course, each good can only be bought once.\n\nLately, the supermarket has been trying to increase its business. Karen, being a loyal customer, was given $n$ coupons. If Karen purchases the $i$-th good, she can use the $i$-th coupon to decrease its price by $d_{i}$. Of course, a coupon cannot be used without buying the corresponding good.\n\nThere is, however, a constraint with the coupons. For all $i ≥ 2$, in order to use the $i$-th coupon, Karen must also use the $x_{i}$-th coupon (which may mean using even more coupons to satisfy the requirement for that coupon).\n\nKaren wants to know the following. What is the maximum number of goods she can buy, without exceeding her budget $b$?",
    "tutorial": "Instead of asking for the maximum number of items we can buy with $b$ dollars, let's ask instead for the minimum cost to buy $j$ items for all $j$. Afterwards, we can simply brute force all $j$ to find the largest $j$ that still fits within her budget $b$. Note this problem is actually on a rooted tree, with root at node $1$; the constraint $x_{i} < i$ guarantees there are no cycles in this problem. The coupon requirement essentially means that if we buy good $i$ at the discounted price, we also need to buy good $x_{i}$ at the discounted price, and so on. If we don't buy at discounted price there are no constraints (except that Karen can afford it. Unfortunately, she isn't a criminal.) There is a rather straightforward $O(n^{3})$ dynamic programming solution to this problem, as follows: Let $f_{i, j}$ be the minimum cost to buy $j$ items in the subtree of $i$ if we can still use coupons, and $g_{i, j}$ the minimum cost to buy $j$ items in the subtree of $i$ if we cannot use any more coupons. We know that for all leaves, $f_{i, j} = c_{i} - d_{i}$ and $g_{i, j} = c_{i}$. We can compute $g_{i, j}$ for all nodes as well; this is simply the sum of the $j$ smallest $c$'s in the subtree of $i$. This can be done straightforwardly in $O(n^{2})$ or $O(n^{2}\\log{n})$. To compute this $f_{i, j}$ for some non-leaf node $i$, we should initialize $f_{i, 1} = c_{i} - d_{i}$. Now, we can add each of the children of $i$ one by one, and try each $j$. Suppose we take $k$ elements from one of the children. Then we have $f_{i, j} = min(f_{i, j}, f_{i, j - k} + f_{i, k})$. We just have to make sure to implement it in a way that we don't inadvertently take elements multiple times, usually by making an auxiliary array. Finally, we set $f_{i, j} = min(f_{i, j}, g_{i, j})$ to consider not using the coupons. Note that we can't do this at the start, because otherwise it could cause conflicts. This runs in $O(n^{3})$, which is too slow. This is because there are $n$ nodes, and to compute $f_{i, j}$ for all $j$ in that node, it takes $O(n\\geq{}_{h\\in p_{i}}\\,s(h))$ where $p_{i}$ is the set of all of the children of $i$, and $s(h)$ is the subtree size of node $h$. This sum turns out to be $O(n^{2})$, and so the final runtime is $O(n^{3})$. How could we make it faster? Take the largest (in terms of nodes) child of subtree $i$. Can we avoid iterating through this? Yes, we can! Suppose our tree was binary. Now, we can compute $f_{i, j} = min_{0  \\le  k < j}(f_{a, j - k - 1} + f_{b, k} + c_{i} - d_{i})$, where $a$ and $b$ are the subtrees of $i$, with $s(a)  \\ge  s(b)$. This skips iterating through the larger subtree $a$. We can extend this to non-binary trees, too; just do this to skip the largest subtree, and then add the rest like before. The runtime of the transition is now $O(n(\\sum_{h\\in p_{i}}s(h)-s(a)))$, which turns out to be just $O(n)$. The final runtime is hence $O(n^{2})$ (or $O(n^{2}\\log{n})$, depending on the algorithm used for the greedy portion.) This is sufficient to solve this problem.",
    "tags": [
      "brute force",
      "dp",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "815",
    "index": "D",
    "title": "Karen and Cards",
    "statement": "Karen just got home from the supermarket, and is getting ready to go to sleep.\n\nAfter taking a shower and changing into her pajamas, she looked at her shelf and saw an album. Curious, she opened it and saw a trading card collection.\n\nShe recalled that she used to play with those cards as a child, and, although she is now grown-up, she still wonders a few things about it.\n\nEach card has three characteristics: strength, defense and speed. The values of all characteristics of all cards are positive integers. The maximum possible strength any card can have is $p$, the maximum possible defense is $q$ and the maximum possible speed is $r$.\n\nThere are $n$ cards in her collection. The $i$-th card has a strength $a_{i}$, defense $b_{i}$ and speed $c_{i}$, respectively.\n\nA card beats another card if at least two of its characteristics are strictly greater than the corresponding characteristics of the other card.\n\nShe now wonders how many different cards can beat all the cards in her collection. Two cards are considered different if at least one of their characteristics have different values.",
    "tutorial": "Let's say we have one card, with $a_{1} = 4$, $b_{1} = 2$ and $c_{1} = 3$. For simplicity, we have $p = q = r = 5$. Consider which cards will beat this one. Let's fix the $c$ of our card, and see what happens at all various $c$: Note that a green cell at $(a, b)$ in grid $c$ represents that the card $(a, b, c)$ can beat the card $(4, 2, 3)$. Hence, the total number of cards that can beat this card is simply the number of green cells across all $c$ grids. This representation is helpful, because we can easily account for more cards. For example, let's say we have another card $a_{2} = 2$, $b_{2} = 3$ and $c_{2} = 4$: Now, what happens when we want to consider the cards that beat both of these cards? Well, we simply have to consider the intersection of both sets of grids! Remember that we are simply trying to count the total number of green cells in all grids. It turns out that trying to count the number of green cells directly is quite difficult. Instead, it is more feasible to count the number of not green cells, and then simply subtract it from the number of cells $pqr$. How could we do this? We should exploit some properties of the grids. First, for any particular card $(a_{i}, b_{i}, c_{i})$, all the grids from $1$ to $c_{i}$ are the same, and all the grids from $c_{i} + 1$ to $r$ are the same. This means that we can avoid a lot of redundancy, and only perform some sort of update when we reach the change. Second, if some cell $(a, b)$ is not green for some fixed $c$, then neither are the cells $(a', b')$ for all $a'  \\le  a$ and $b'  \\le  b$ for the same $c$. This means that we can replace each grid with an array $u_{1}, u_{2}, u_{3}, ...$ where $u_{a}$ is the largest $b$ for which $(a, b)$ is not green. Additionally, $u_{1}  \\ge  u_{2}  \\ge  u_{3}  \\ge  ...  \\ge  u_{p}$. Third, for any card, there are only at most two distinct values in $u$ for any fixed $c$ in one card. Finally, for any card, no value $u_{i}$ in $c$ is less than $u_{i}$ in $c'$ if $c < c'$. These properties are all pretty easy to observe and prove, but they will form the bread and butter of our solution. Let's iterate cards from $c = r$ to $c = 1$. Suppose we maintain an array $s$ which will at first contain all $0$. This will be the number of cells that are not green. We will update it for all grids first. For each card, we are essentially setting, for all $i$, $s_{i}$ to $max(s_{i}, u_{i})$. Of course, doing this for each grid will take $O(np)$, which is too slow. To remedy this, initialize $s$ as a segment tree instead. Now, we are basically just setting $s_{1}, s_{2}, s_{3}, ..., s_{ai}$ to $max(s_{j}, b_{i})$ for all cards $i$. Because $s$ is essentially a maximum of a bunch of $u$'s, which are all nonincreasing by the second property, it follows that $s$ is also nonincreasing at all times. Therefore, these updates are easy to do; we are essentially setting $s_{k}, s_{k + 1}, s_{k + 2}, ..., s_{ai}$ to $b_{i}$ for the smallest $k$ where $b_{i}  \\ge  s_{k}$. We can find $k$ using binary search. Binary searching the segment tree can be done in $O(\\log p)$ time using an implicit binary search by going down the tree; an explicit $O(\\log^{2}p)$ binary search might have trouble passing the time limit. Using the aforementioned procedure, we are able to generate $s$ corresponding to the layer $c = r$ in $O(n\\log p)$ time. Using the segment tree, we should also be able to get the sum of all values in $s$ at all times. This will allow us to count the number of not green cells. Now, we will go backwards from $c = r$ to $c = 1$. We should decrement $c$, and then see which grids changed. (Just sort the cards by $c_{i}$ and do a two-pointers approach.) All the newly-changed grids can then be updated in a similar manner as before. When a grid changes, thanks to the fourth property, there is no worry of any $u_{i}$ getting smaller than it was before; they can only get bigger. So, we have to update two ranges $s_{1}, s_{2}, s_{3}, ..., s_{ai}$ to $r$ and $s_{ai + 1}, s_{a2 + 1}, s_{ai + 3}, ..., s_{p}$ to $max(s_{j}, b_{i})$. The former is a simple range update, the latter can be done using binary search like before. After we update all grids for a particular $c$, get the range sum, and decrement $c$ again, and so on until we reach $1$. We will have the found the total number of not green cells in all $c$, and from there we can recover all the green cells, and hence the final answer. Sorting the cards by $c_{i}$ takes $O(n\\log n)$ time, constructing the segment tree $s$ takes $O(p)$ time, there are $O(n)$ updates each taking $O(\\log p)$ time, and iterating takes $O(r)$ time. The final runtime is therefore $O(n(\\log n+\\log p)+p+r)$ time, which is sufficient to solve this problem. This solution can be modified to pass $p, q, r  \\le  10^{9}$, too; however, this was not done as it uses only standard ideas and just contains more tedious implementation. If you want, you can try to implement it.",
    "tags": [
      "binary search",
      "combinatorics",
      "data structures",
      "geometry"
    ],
    "rating": 2800
  },
  {
    "contest_id": "815",
    "index": "E",
    "title": "Karen and Neighborhood",
    "statement": "It's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood.\n\nThe neighborhood consists of $n$ houses in a straight line, labelled $1$ to $n$ from left to right, all an equal distance apart.\n\nEveryone in this neighborhood loves peace and quiet. Because of this, whenever a new person moves into the neighborhood, he or she always chooses the house whose minimum distance to any occupied house is maximized. If there are multiple houses with the maximum possible minimum distance, he or she chooses the leftmost one.\n\nNote that the first person to arrive always moves into house $1$.\n\nKaren is the $k$-th person to enter this neighborhood. If everyone, including herself, follows this rule, which house will she move into?",
    "tutorial": "Surprisingly, it is possible to solve this problem without knowledge of any sophisticated algorithms or data structures; this problem can be solved completely through observations, brutal case analysis and grunt work, which we will try to summarize here. The first and most obvious observation: the first person always goes to house $1$, and the second person always goes to house $n$. Consider these two guys as special cases; now, we're solving the problem on a segment of length $n - 2$. Note how we define segments here; a segment of length $l$ is a row of $l$ unoccupied houses, with the two houses just before and after both endpoints occupied. Notice that, for any segment, if a person moves into any house in this segment it will be the middle one; if there are two middles, it will be the left of the two middles. So, if we have a length $3$ segment, the person will move into the $2$-nd house in the segment. If we have a length $6$ segment, the person will move into the $3$-rd house in the segment, and so on. When a person moves into a house in a given segment of length $l$, if $l > 2$, it will also create two new segments; the left segment will be length $\\left\\lfloor{\\frac{l-1}{2}}\\right\\rfloor$ and the right segment will be length $\\textstyle{\\left|{\\frac{l}{2}}\\right|}$. Let's write down the segments in a binary tree, where the $i$-th layer contains all segments spawned by the $(i - 1)$-th layer, and the first layer contains precisely the segment of length $n - 2$. For example, consider $n = 46$. The binary tree will look like this: From this, we can make a number of observations. We can see that there are at most $2$ different segment lengths in any layer. Additionally, these values are always $l$ and $l + 1$, where $l$ is the smaller one. Let the two lengths in a given layer be $l$ and $l + 1$ (if there is only one, it's just $l$). Now, consider the following: If $l$ is odd, the segments of length $l$ and $l + 1$ will be processed in order from left to right. If $l$ is even, all segments of length $l + 1$ will be processed first, from left to right, then all segments of length $l$ will be processed, also from left to right. This makes sense; the \"minimum distance\" is actually just the smaller of the two children, and you can observe that in the above first case, the smaller of the two children is equal, while in the second case, the smaller of the two children of $l$ is smaller than the smaller of the two children of $l + 1$. Additionally, all segments in any particular layer are always processed before the segments in the next layer (except in the case $l = 2$-we will discuss the special cases later.) We can therefore determine, rather straightforwardly, what layer the $k$-th segment is. Since all the layers above this layer are now irrelevant, we can just subtract all the taken layers from $k$. Now, the problem has been reduced to finding what house the $k$-th guy in a fixed layer moves into. How will we find this? Well, note that there is exactly one house separating any two segments in a given layer. If we go to the $k$-th segment, the label of the house we actually went into is $k$ (number of houses occupied on previous layers), plus the total length of segments $1, 2, 3, ..., k - 1$ (unoccupied houses before this one), plus $\\left\\lfloor{\\frac{k+1}{2}}\\right\\rfloor$ (the middle house in the $k$-th segment). It is easy to determine $l$ and the number of length $l$ and length $l + 1$ segments for any particular layer. What's harder to compute are two crucial details: What's the relative position of the $k$-th processed segment in this layer? How many layers have length $l + 1$ before the segment at this relative position? If we can answer these two questions efficiently, we are basically done with the core of the solution, and just have to handle special cases. Let's answer the first question. If $l$ is odd, this is trivial; the $k$-th processed segment is precisely that at position $k$. If $l$ is even, things get a lot trickier. Luckily, we can perform more observations. Draw the tree with root segment $39$ $(n = 41)$, and observe the fourth row. Now, draw the trees with root segments $40, 41, 42, ..., 47$. Observe how the fourth row changes from root segment $39$ to $47$: Root segment is $39$: $4, 4, 4, 4, 4, 4, 4, 4$ Root segment is $40$: $4, 4, 4, 4, 4, 4, 4, 5$ Root segment is $41$: $4, 4, 4, 5, 4, 4, 4, 5$ Root segment is $42$: $4, 4, 4, 5, 4, 5, 4, 5$ Root segment is $43$: $4, 5, 4, 5, 4, 5, 4, 5$ Root segment is $44$: $4, 5, 4, 5, 4, 5, 5, 5$ Root segment is $45$: $4, 5, 5, 5, 4, 5, 5, 5$ Root segment is $46$: $4, 5, 5, 5, 5, 5, 5, 5$ Root segment is $47$: $5, 5, 5, 5, 5, 5, 5, 5$ In what order are the numbers increased? It's not immediately obvious, but we can try to write down the binary representations of the (zero-indexed) positions in the order they are increased: $7$: $111$ $3$: $011$ $5$: $101$ $1$: $001$ $6$: $110$ $2$: $010$ $4$: $100$ $0$: $000$ Actually, this is just the reversed binary numbers in reverse order! Remember that our goal is to find the relative position of the $k$-th processed element. Without loss of generality, suppose that the $k$-th processed element is of length $l + 1$ (the analysis when it is length $l$ is almost the same.) This is equivalent to asking for the $k$-th smallest element among the first $m$ numbers in that list ($m$ is the number of $l + 1$ segments in the given layer, which is easy to compute). Let's take root segment equal to $44$, as in the illustration earlier. Let's say we want the position of the $k = 4$-th occurrence of $5$. That's equivalent to finding the $4$-th smallest element in this list (obviously we never get to generate this list explicitly): $7$: $111$ $3$: $011$ $5$: $101$ $1$: $001$ $6$: $110$ Consider these binary numbers digit by digit starting from the largest. Notice that, at any point, the number of ones is always equal to or one more than the number of zeroes; above, there are $3$ ones and $2$ zeroes. We want the $4$-th smallest, and there are only $2$ zeroes, so we know it has to start with $1$. We throw out (again, not explicitly) all the numbers that start with zero, and we are now left with finding the $2$-nd smallest in this list: Our number so far: $1??$ $7$: $11$ $5$: $01$ $6$: $10$ Now, there are $2$ ones and $1$ zero. We want the $2$-nd smallest, and there is only $1$ zero, so we know the next digit is $1$. We throw out all the numbers that start with zero, and we are now left with finding the $1$-st smallest in this list: Our number so far: $11?$ $7$: $1$ $6$: $0$ Now, there is $1$ one and $1$ zero. We want the $1$-st smallest, and there is $1$ zero, which is enough. So, this is the next digit. The final number is $6$, which means that the position of the $4$-th $5$ is at $6$. ($7$ if one-indexed). This process works for any arbitrary numbers in $O(\\log n)$, and now we are able to answer the first required question in just $O(\\log n)$ time. Now, we need to answer the second question. How many layers have length $l + 1$ before the segment at this relative position? Actually, this question can be solved using almost the exact same binary digit analysis! The problem is equivalent to asking for how many numbers, among the first $m$ numbers in the earlier list, have a position less than $k$. We will omit the analysis here for brevity, but it uses virtually the same idea and also solves this question in $O(\\log n)$. Now, we have solved both questions, and have essentially finished the core of the problem. But we're not yet done! We still have to handle the corner cases. There are actually only two corner cases: $l = 1$ and $l = 2$. When $l = 1$, note that every segment of length $2$ is basically treated as two segments of length $1$. When $l = 2$, segments of length $3$ are handled first, each creating segments of length $1$. Then, the segments of length $1$ and $2$ are treated like with $l = 1$, despite the segments of length $1$ technically being on the next layer. Both of these cases can be solved using the same binary digit analysis, with some grunt-work formulas that can be a bit hard to get precisely correct. These cases can also be solved in $O(\\log n)$. Overall, the runtime of the solution is just $O(\\log n)$.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 2900
  },
  {
    "contest_id": "816",
    "index": "A",
    "title": "Karen and Morning",
    "statement": "Karen is getting ready for a new school day!\n\nIt is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.\n\nWhat is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?\n\nRemember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.",
    "tutorial": "This is a rather straightforward implementation problem. The only observation here is that there are only $1440$ different possible times. It is enough to iterate through all of them until we encounter a palindromic time, and count the number of times we had to check before we reached a palindromic time. How do we iterate through them? The most straightforward way is to simply convert the given string into two integers $h$ and $m$. We can do this manually or maybe use some functions specific to your favorite language. It is good to be familiar with how your language deals with strings. It is also possible, though inadvisable, to try to work with the string directly. To go to the next time, we simply increment $m$. If $m$ becomes $60$, then make it $0$ and increment $h$. If $h$ becomes $24$, then make it $0$. To check whether a given time is palindromic, we simply need to check if the tens digit of $h$ is the same as the ones digit of $m$, and if the ones digit of $h$ is the same as the tens digit of $m$. This can be done like so: check if $|\\underline{{{h}}}^{k}\\rangle=m\\ \\mathrm{mod}\\ 10$ and $h_{\\mathrm{\\scriptsize~IIDd}}\\left|0\\right|=\\left|\\frac{m}{10}\\right|$. Another way is to simply cross-check against a list of palindromic times. Just be careful not to miss any of them, and not to add any extraneous values. There are $16$ palindromic times, namely: $00: 00$, $01: 10$, $02: 20$, $03: 30$, $04: 40$, $05: 50$, $10: 01$, $11: 11$, $12: 21$, $13: 31$, $14: 41$, $15: 51$, $20: 02$, $21: 12$, $22: 22$ and $23: 32$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "816",
    "index": "B",
    "title": "Karen and Coffee",
    "statement": "To stay woke and attentive during classes, Karen needs some coffee!\n\nKaren, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed \"The Art of the Covfefe\".\n\nShe knows $n$ coffee recipes. The $i$-th recipe suggests that coffee should be brewed between $l_{i}$ and $r_{i}$ degrees, inclusive, to achieve the optimal taste.\n\nKaren thinks that a temperature is admissible if at least $k$ recipes recommend it.\n\nKaren has a rather fickle mind, and so she asks $q$ questions. In each question, given that she only wants to prepare coffee with a temperature between $a$ and $b$, inclusive, can you tell her how many admissible integer temperatures fall within the range?",
    "tutorial": "There are two separate tasks here: Efficiently generate an array $c$ where $c_{i}$ is the number of recipes that recommend temperature $i$. Efficiently answer queries \"how many numbers $c_{a}, c_{a + 1}, c_{a + 2}, ..., c_{b}$\" are at least $k$?\" where $k$ is fixed across all queries. There are some solutions to this task using advanced data structures or algorithms. For example, a conceptually straightforward idea is the following: create a segment tree $c$. We can treat all recipes as range update queries which we can do efficiently in $O(n\\log m)$ (where $m$ is the largest $a_{i}$ or $b_{i}$) time using lazy propagation. After all recipes, we replace all $c_{i}$ by $1$ if it's at least $k$, and $0$ otherwise. Afterwards, each of the next $q$ queries is a basic range sum query, which can be done simply in $O(q\\log m)$ time. Other solutions exist, too: Fenwick trees with range updates, event sorting, sqrt-decomposition with binary search, Mo's algorithm, and so on. These solutions all pass, but they are all overkill for this task. A very simple solution is as follows. Initialize $c$ with all zeroes. For recipe that recommends temperatures between $l_{i}$ and $r_{i}$, we should increment $c_{li}$ and decrement $c_{ri + 1}$. Cumulate all values. That is, set $c_{i}$ to $c_{1} + c_{2} + c_{3} + ... + c_{i}$. This can be done with one pass through the array. Now, magically, $c_{i}$ is now the number of recipes that recommend temperature $i$. If $c_{i}$ is at least $k$, set it to $1$, otherwise, set it to $0$. Cumulate all values again. Now, every query that asks for the number of admissible temperatures between $a$ and $b$ can be answered simply as $c_{b} - c_{a - 1}$. This runs in $O(n + q + m)$, which is really fast. Note that if your solution does this and still runs quite slow, chances are your solution is using slower input methods. We raised the time limit to 2.5 seconds in this problem in order to avoid failing slow input solutions.",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "817",
    "index": "A",
    "title": "Treasure Hunt",
    "statement": "Captain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure.\n\nBottle with potion has two values $x$ and $y$ written on it. These values define four moves which can be performed using the potion:\n\n- $(a,b)\\rightarrow(a+x,b+y)$\n- $(a,b)\\to(a+x,b-y)$\n- $(a,b)\\rightarrow(a-x,b+y)$\n- $(a,b)\\to(a-x,b-y)$\n\nMap shows that the position of Captain Bill the Hummingbird is $(x_{1}, y_{1})$ and the position of the treasure is $(x_{2}, y_{2})$.\n\nYou task is to tell Captain Bill the Hummingbird whether he should accept this challenge or decline. If it is possible for Captain to reach the treasure using the potion then output \"YES\", otherwise \"NO\" (without quotes).\n\n\\textbf{The potion can be used infinite amount of times.}",
    "tutorial": "Firstly, let's approach this problem as if the steps were $(a,b)\\to(a\\pm x,0)$ and $(a,b)\\rightarrow(0,b\\pm y)$. Then the answer is \"YES\" if $|x_{1} - x_{2}|$ $mod$ $x = 0$ and $|y_{1} - y_{2}|$ $mod$ $y = 0$. It's easy to see that if the answer to this problem is \"NO\" then the answer to the original one is also \"NO\". Let's return to the original problem and take a look at some sequence of steps. It ends in some point $(x_{e}, y_{e})$. Define $cnt_{x}$ as $\\textstyle{\\frac{|x_{e}-x_{1}|}{x}}$ and $cnt_{y}$ as $\\textstyle\\frac{|j_{i}-y_{i}|}{y}$. The parity of $cnt_{x}$ is the same as the parity of $cnt_{y}$. It is like this because every type of move changes parity of both $cnt_{x}$ and $cnt_{y}$. So the answer is \"YES\" if $|x_{1} - x_{2}|$ $mod$ $x = 0$, $|y_{1} - y_{2}|$ $mod$ $y = 0$ and $\\textstyle{\\frac{|x_{1}-x_{2}|}{x}}$ $mod$ $2={\\frac{\\vert y_{1}-y_{2}\\vert}{y}}$ $mod$ $2$. Overall complexity: $O(1)$.",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "817",
    "index": "B",
    "title": "Makes And The Product",
    "statement": "After returning from the army Makes received a gift — an array $a$ consisting of $n$ positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices $(i,  j,  k)$ ($i < j < k$), such that $a_{i}·a_{j}·a_{k}$ is minimum possible, are there in the array? Help him with it!",
    "tutorial": "Minimal product is obtained by multiplying three smallest elements of the array. Let's iterate over the middle element of these three and calc sum of all options. Firstly let's precalc two arrays of pairs - $mnl$ and $mnr$. $mnl[x]$ is minimum and number of its occurrences on the prefix of array $a$ up to index $x$ inclusive. $mnr[x]$ is minimum and number of its occurrences on the suffix of array $a$ up to index $x$ inclusive. It can be done with two traversals over the array. Let's also store set of three elements which give minimal product of the array. Consider every index $j$ from $1$ to $n - 2$ inclusive (0-indexed). If set ($a[j], mnl[j - 1].first, mnr[j + 1].first$) is equal to the stored set of three minimums then add to the answer number of ways to choose pair $(i, k)$, that is $mnl[j - 1].second  \\cdot  mnr[j + 1].second$. Overall complexity: $O(n)$.",
    "tags": [
      "combinatorics",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "817",
    "index": "C",
    "title": "Really Big Numbers",
    "statement": "Ivan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number $x$ is really big if the difference between $x$ and the sum of its digits (in decimal representation) is not less than $s$. To prove that these numbers may have different special properties, he wants to know how rare (or not rare) they are — in fact, he needs to calculate the quantity of really big numbers that are not greater than $n$.\n\nIvan tried to do the calculations himself, but soon realized that it's too difficult for him. So he asked you to help him in calculations.",
    "tutorial": "Let's prove that if $x$ is really big, then $x + 1$ is really big too. Since the sum of digits of $x + 1$ (let's call it $sumd(x + 1)$) is not greater than $sumd(x) + 1$, then $x + 1 - sumd(x + 1)  \\ge  x - sumd(x)$, and if $x - sumd(x)  \\ge  s$, then $x + 1 - sumd(x + 1)  \\ge  s$. So if $x$ is really big, then $x + 1$ is really big. This observation allows us to use binary search to find the minimum really big number (let's call it $y$). And if $y  \\le  n$, then all numbers in the segment $[y, n]$ are really big and not greater than $n$, so the quantity of these numbers is the answer to the problem.",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "817",
    "index": "D",
    "title": "Imbalanced Array",
    "statement": "You are given an array $a$ consisting of $n$ elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.\n\nFor example, the imbalance value of array $[1, 4, 1]$ is $9$, because there are $6$ different subsegments of this array:\n\n- $[1]$ (from index $1$ to index $1$), imbalance value is $0$;\n- $[1, 4]$ (from index $1$ to index $2$), imbalance value is $3$;\n- $[1, 4, 1]$ (from index $1$ to index $3$), imbalance value is $3$;\n- $[4]$ (from index $2$ to index $2$), imbalance value is $0$;\n- $[4, 1]$ (from index $2$ to index $3$), imbalance value is $3$;\n- $[1]$ (from index $3$ to index $3$), imbalance value is $0$;\n\nYou have to determine the imbalance value of the array $a$.",
    "tutorial": "First of all, we will calculate the sum of maximum and minimum values on all segments separatedly. Then the answer is the difference between the sum of maximum values and minimum values. How can we calculate the sum of minimum values, for example? For each element we will try to find the number of segments where it is the leftmost minimum element. So, we will calculate two arrays $left$ ($left[i] = j$ means that $j$ is the maximum index such that $a_{i}  \\ge  a_{j}$ and $j < i$) and $right$ ($right[i] = j$ means that $j$ is the minimum index such that $a_{i} > a_{j}$ and $j > i$). So actually, $left[i]$ and $right[i]$ represent the borders of the largest segment where $a_{i}$ is the leftmost minimum element (and we need to exclude those borders). While knowing these values, we can calculate the number of subsegments where $a_{i}$ is the leftmost minimum element. How can we calculate, for example, the array $left$? We will use a stack where we will store some indices in the array $a$ in such a way that, if we change all indices to the values in the array $a$, they will be in sorted order (the maximum element will be at the top of the stack, and the minimum - at the bottom). Let's calculate $left$ from the minimum index to the maximum. When we calculate $left[i]$, we remove all elements $j$ such that $a_{j} > a_{i}$ from the stack (since the stack is \"sorted\", all these elements will be at the top of the stack, and when we encounter the first element $j$ such that $a_{j}  \\le  a_{i}$, it is guaranteed that all elements below it don't need to be deleted). Then, if there's any element on top of the stack, it becomes the value of $left[i]$, then we push $i$ into the stack. Since every element will be added (and deleted) not more than one time, the complexity of this algorithm is linear. We can apply the same technique to calculate the values of $right$ and the sum of maximums.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dsu",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "817",
    "index": "E",
    "title": "Choosing The Commander",
    "statement": "As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.\n\nVova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.\n\nEach warrior is represented by his personality — an integer number $p_{i}$. Each commander has two characteristics — his personality $p_{j}$ and leadership $l_{j}$ (both are integer numbers). Warrior $i$ respects commander $j$ only if $p_{i}\\oplus p_{j}<l_{j}$ ($x\\oplus y$ is the bitwise excluding OR of $x$ and $y$).\n\nInitially Vova's army is empty. There are three different types of events that can happen with the army:\n\n- $1 p_{i}$ — one warrior with personality $p_{i}$ joins Vova's army;\n- $2 p_{i}$ — one warrior with personality $p_{i}$ leaves Vova's army;\n- $3 p_{i} l_{i}$ — Vova tries to hire a commander with personality $p_{i}$ and leadership $l_{i}$.\n\nFor each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.",
    "tutorial": "Let's use binary trie to store all personalities of warriors (that is, just use the trie data structure on binary representations of all $p_{i}$). For each subtree of this trie you have to maintain the number of $p_{i}$'s currently present in this subtree - when inserting a value of $p_{i}$, we increase the sizes of subtrees on the path from the node with $p_{i}$ to the root by $1$, and when removing $p_{i}$, we decrease the sizes of subtrees on this path by $1$. How can it help us with answering the events of third type? We will descend the trie. When descending, we will try to find the number $p_{i}\\oplus l_{i}$ in the structure. When we go to some subtree, we determine whether we add the quantity of numbers in the subtree we are not going into by checking if the current bit in $l_{i}$ is equal to $1$ (if so, then for all numbers from this subtree their bitwise xor with the current commander's personality is less than $l_{i}$). The answer to the event is the sum of sizes of all subtrees we \"added\" while descending into the trie.",
    "tags": [
      "bitmasks",
      "data structures",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "817",
    "index": "F",
    "title": "MEX Queries",
    "statement": "You are given a set of integer numbers, initially it is empty. You should perform $n$ queries.\n\nThere are three different types of queries:\n\n- 1 $l$ $r$ — Add all missing numbers from the interval $[l, r]$\n- 2 $l$ $r$ — Remove all present numbers from the interval $[l, r]$\n- 3 $l$ $r$ — Invert the interval $[l, r]$ — add all missing and remove all present numbers from the interval $[l, r]$\n\nAfter each query you should output MEX of the set — the smallest positive (MEX $ ≥ 1$) integer number which is not presented in the set.",
    "tutorial": "There are many ways to solve this problem, you can use cartesian tree, segment tree, sqrt decomposition, maybe something else. I personally see the solution with the segment tree the easiest one so let me describe it. Firstly, let's notice that the queries are offline. So we can compress the numbers by taking $L$ and $R + 1$ of each query. MEX will be either one of these numbers or 1. So now we have numbers up to $2 \\cdot 10^{5}$ and pretty basic task on segment tree. The first two types of queries are translated to \"assign value 1 or 0 on a segment\" (set the number on some position is either present or not). The third is \"for each $i$ in segment $[l, r]$ assign $x_{i}$ to $x_{i}\\oplus1$\" (this will inverse the segment as described in statement). Segment tree should keep sum of the segment in its nodes. XOR on segment will turn $val$ into $len - val$, $len$ is the length of the segment being covered by the node. The leftmost zero cell is MEX. While standing in some node $v$, check if its left son is full (has 1 in every cell of the segment, like $t[v * 2] = mid - left$ if you use 1-indexed tree and intervals for it). If it is full then go down to the right son, otherwise there exists some zero cell in a segment of the left child and you should go down to it. You should use lazy propagation to guarantee $\\log n$ per query. Overall complexity: $O(q\\cdot\\log q)$.",
    "tags": [
      "binary search",
      "data structures",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "818",
    "index": "A",
    "title": "Diplomas and Certificates",
    "statement": "There are $n$ students who have taken part in an olympiad. Now it's time to award the students.\n\nSome of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and certificates. The number of certificates must be \\textbf{exactly} $k$ times greater than the number of diplomas. The number of winners must \\textbf{not be greater than half of the number of all students} (i.e. not be greater than half of $n$). It's possible that there are no winners.\n\nYou have to identify the maximum possible number of winners, according to these rules. Also for this case you have to calculate the number of students with diplomas, the number of students with certificates and the number of students who are not winners.",
    "tutorial": "Let $a$ be the number of students with diplomas and $b$ - students with certificates. $b$ is always $a \\cdot k$. So the total number of winners is $a + a \\cdot k = a \\cdot (k + 1)$. It should not exceed $\\textstyle{\\left[{\\frac{n}{2}}\\right]}$, so the maximum value for $a$ will be hit in $(n$ $div$ $2)$ $div$ $(k + 1)$, where $a$ $div$ $b$ is $\\left\\lfloor{\\frac{\\Omega}{b}}\\right\\rfloor$. Overall complexity: $O(1)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "818",
    "index": "B",
    "title": "Permutation Game",
    "statement": "$n$ children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation $a_{1}, a_{2}, ..., a_{n}$ of length $n$. It is an integer sequence such that each integer from $1$ to $n$ appears exactly once in it.\n\nThe game consists of $m$ steps. On each step the current leader with index $i$ counts out $a_{i}$ people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.\n\nYou are given numbers $l_{1}, l_{2}, ..., l_{m}$ — indices of leaders in the beginning of each step. Child with number $l_{1}$ is the first leader in the game.\n\nWrite a program which will restore a possible permutation $a_{1}, a_{2}, ..., a_{n}$. If there are multiple solutions then print any of them. If there is no solution then print -1.",
    "tutorial": "Let's show by construction that there can be no ambiguity in values of $a_{j}$ of the children who were leaders at least once (except for probably the last leader). If $l_{i + 1} > l_{i}$ then on this step the value of $a_{l[i]}$ taken was exactly $l_{i + 1} - l_{i}$. Otherwise $l_{i} + a_{l[i]}$ went over $n$ and in circle ended up to the left or in the same position. So for this case $a_{l[i]}$ should be $(n - l_{i}) + l_{i + 1}$. Obviously counting cannot go over $n$ two or more times as this will result in $a_{l[i]} > n$. We only need to check if all the numbers are unique and fill the unvisited children with remaining values to form the permutation. Overall complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "818",
    "index": "C",
    "title": "Sofa Thief",
    "statement": "Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?\n\nFortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same!\n\nThe storehouse is represented as matrix $n × m$. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells.\n\nSofa $A$ is standing to the left of sofa $B$ if there exist two such cells $a$ and $b$ that \\textbf{$x_{a} < x_{b}$}, $a$ is covered by $A$ and $b$ is covered by $B$. Sofa $A$ is standing to the top of sofa $B$ if there exist two such cells $a$ and $b$ that \\textbf{$y_{a} < y_{b}$}, $a$ is covered by $A$ and $b$ is covered by $B$. Right and bottom conditions are declared the same way.\n\n\\textbf{Note that in all conditions $A ≠ B$.} Also some sofa $A$ can be both to the top of another sofa $B$ and to the bottom of it. The same is for left and right conditions.\n\nThe note also stated that there are $cnt_{l}$ sofas to the left of Grandpa Maks's sofa, $cnt_{r}$ — to the right, $cnt_{t}$ — to the top and $cnt_{b}$ — to the bottom.\n\nGrandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions.\n\nOutput the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1.",
    "tutorial": "Coordinates don't exceed $10^{5}$ so it's possible to use sweep line method to solve the problem. Let's calculate $cnt$ value separately for each side. I will show the algorithm for left side and all the others will be done similarly. Let $cnt_left[i]$ be the number of sofas which has smaller of their $x$ coordinates less than or equal to $i$. To count that let's firstly increment by one $cnt_left[min(x1_{i}, x2_{i})]$ for all sofas and then proceed from left to right and do $cnt_left[i] = cnt_left[i] + cnt_left[i - 1]$. Now $cnt_left[max(x1_{i}, x2_{i}) - 1]$ will represent number of sofas to the left of the current one but the sofa itself can also be counted. You need to decrement the result by one if $x1_{i}  \\neq  x2_{i}$. The same is for top value but with $y$ coordinates insted of $x$. For the right and bottom values you should calculate $cnt_right[max(x1_{i}, x2_{i})]$ and $cnt_bottom[max(y1_{i}, y2_{i})]$. Then take $cnt_right[min(x1_{i}, x2_{i}) + 1]$ and $cnt_bottom[min(y1_{i}, y2_{i}) + 1]$. The only thing left is to compare values of each sofa with given ones and find the suitable sofa. Overall complexity: $O(n)$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "818",
    "index": "D",
    "title": "Multicolored Cars",
    "statement": "Alice and Bob got very bored during a long car trip so they decided to play a game. From the window they can see cars of different colors running past them. Cars are going one after another.\n\nThe game rules are like this. Firstly Alice chooses some color $A$, then Bob chooses some color $B$ ($A ≠ B$). After each car they update the number of cars of their chosen color that have run past them. Let's define this numbers after $i$-th car $cnt_{A}(i)$ and $cnt_{B}(i)$.\n\n- If $cnt_{A}(i) > cnt_{B}(i)$ for every $i$ then the winner is Alice.\n- If $cnt_{B}(i) ≥ cnt_{A}(i)$ for every $i$ then the winner is Bob.\n- Otherwise it's a draw.\n\nBob knows all the colors of cars that they will encounter and order of their appearance. Alice have already chosen her color $A$ and Bob now wants to choose such color $B$ that he will win the game (draw is not a win). Help him find this color.\n\nIf there are multiple solutions, print any of them. If there is no such color then print -1.",
    "tutorial": "Let's maintain the current availability of colors and the amounts of cars of each color. Firstly color $A$ is never available. When car of some color $C$ ($C  \\neq  A$) goes, you check if the number of cars of color $C$ past before this one isn't smaller than the number of cars of color $A$. Only after that increment the amount by one. If it was less then set its availability to false. If car of color $A$ goes then simply increment its amount. In the end iterate over all colors and check if it's both available and has higher or equal amount than the amount of cars of color $A$. Okay, why this works? As all the amounts cannot decrease, color $C$ will become not available at some moment when car of color $A$ goes. And this will be encountered either when the new car of color $C$ goes, or in the end of the sequence. Amount of cars of color $C$ doesn't update between this periods. And if there was point when there became more cars of color $A$ than of color $C$ then this inequality will hold until the next moment we will check. Overall complexity: $O(n)$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "818",
    "index": "E",
    "title": "Card Game Again",
    "statement": "Vova again tries to play some computer card game.\n\nThe rules of deck creation in this game are simple. Vova is given an existing deck of $n$ cards and a magic number $k$. The order of the cards in the deck is fixed. Each card has a number written on it; number $a_{i}$ is written on the $i$-th card in the deck.\n\nAfter receiving the deck and the magic number, Vova removes $x$ (possibly $x = 0$) cards from the top of the deck, $y$ (possibly $y = 0$) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards $x + 1$, $x + 2$, ... $n - y - 1$, $n - y$ from the original deck.\n\nVova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by $k$. So Vova received a deck (possibly not a valid one) and a number $k$, and now he wonders, how many ways are there to choose $x$ and $y$ so the deck he will get after removing $x$ cards from the top and $y$ cards from the bottom is valid?",
    "tutorial": "Let's use two pointers. Firstly you need to learn to factorize any number in no more than $O(\\log n)$. We don't actually need any of their prime divisors except for those that are presented in $k$. So let's factorize $k$ in $O({\\sqrt{10^{9}}})$. After that check for the maximum power of each useful prime will work in $O(\\log10^{9})$ for each number. Now notice that if some segment $[l, r]$ has its product divisible by $k$ then all segments $[l, i]$ for ($r  \\le  i  \\le  n$) will also have products divisible by $k$. Now we have to find the smallest $r$ for each $l$ out there. That's where two pointers kick in. Let's maintain the current product of the segment in factorized form (only useful primes), as in normal form its enormous. The power of some prime in this form is the sum of powers of this prime in all the numbers in the segment. We firstly move the left border of the segment one step to the right and then keep moving the right border to the right until power of at least one prime number in the product is smaller than in $k$. It means that it is not divisible by $k$. Moving the left border means subtracting all the powers of useful primes of number $a_{l}$ from the product and moving the right border is adding all the powers of useful primes of $a_{r}$. The first time we reach such a segment, we add ($n - r$) to answer (consider $r$ $0$-indexed). Overall complexity: $O(n\\cdot\\log M A X N+\\sqrt{M A X M})$, where $MAXN$ is up to $10^{9}$.",
    "tags": [
      "binary search",
      "data structures",
      "number theory",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "818",
    "index": "F",
    "title": "Level Generation",
    "statement": "Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.\n\nIvan decided that there should be exactly $n_{i}$ vertices in the graph representing level $i$, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices $u$ and $v$ is called a bridge if this edge belongs to every path between $u$ and $v$ (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.\n\nSo the task Ivan gave you is: given $q$ numbers $n_{1}, n_{2}, ..., n_{q}$, for each $i$ tell the maximum number of edges in a graph with $n_{i}$ vertices, if at least half of the edges are bridges. \\textbf{Note that the graphs cannot contain multiple edges or self-loops}.",
    "tutorial": "The best way to build a graph is to make a $2$-edge-connected component with $k$ vertices and connect each of the remaining $n - k$ vertices to it with a single edge. Then we will have $n - k$ bridges outside the component and $m i n({\\frac{k\\cdot(k-1)}{2}},n-k)$ edges in the component. So the answer for some fixed $k$ and $n$ is $n-k+m i n({\\frac{k\\cdot(k-1)}{2}},n-k)$; let's denote is at $f(k)$. Now since $\\textstyle{\\frac{k(k-1)}{2}}$ is increasing, and $n - k$ is decreasing, there exists some $k_{0}$ such that if $k  \\le  k_{0}$, then ${\\frac{k\\cdot(k-1)}{2}}\\leq n-k$, and if $k > k_{0}$, then ${\\frac{k(k-1)}{2}}>n-k$. Then $f(k)$ is strictly increasing on the segment $[1, k_{0}]$, and strictly decreasing on the segment $[k_{0} + 1, n]$; and this proves that we can use ternary search to find its maximum.",
    "tags": [
      "binary search",
      "math",
      "ternary search"
    ],
    "rating": 2100
  },
  {
    "contest_id": "818",
    "index": "G",
    "title": "Four Melodies",
    "statement": "Author note: I think some of you might remember the problem \"Two Melodies\" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult!\n\nAlice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks.\n\nThis time Alice wants to form four melodies for her tracks.\n\nAlice has a sheet with $n$ notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal.\n\nSubsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.\n\nSubsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7.\n\nYou should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody.",
    "tutorial": "Let's build a directed graph where vertices represent notes and a directed edge comes from vertex $i$ to vertex $j$ iff $i < j$ and $a_{i}$ and $a_{j}$ can be consecutive notes in a melody. Now we have to find four longest vertex-disjoint paths in this graph. This problem can be solved with mincost $k$-flow algorithms. We build a network where each vertex of the graph is split into two (let's denote the vertices that we obtain when we are splitting some vertex $i$ as $v_{i, 1}$ and $v_{i, 2}$). Then each directed edge $i\\rightarrow j$ transforms into a directed edge from vertex $v_{i, 2}$ to vertex $v_{j, 1}$ in the network, the capacity of this edge is $1$, and the cost is $0$. Also we add directed edges from the source to every vertex $v_{i, 1}$ and from every vertex $v_{i, 2}$ to the sink (they have the same characteristics: capacity is $1$, cost is $0$). And for each $i$ we add a directed edge between $v_{i, 1}$ and $v_{i, 2}$; these edges actually represent that we are using some note in a melody, so their capacities are also equal to $1$, and their costs are $- 1$. The answer to the problem is equal to the absolute value of minimum cost of $4$-flow in this network. The bad thing is that the network is really large. So we have to use some advanced mincost algorithm here. Model solution uses Dijkstra's algorithm with Johnson's potentials to find augmenting paths of minimum cost. We set a number $p(v)$ for each vertex $v$ of the network (these numbers are called potentials). Then we modify costs of the edges: if some edge $i\\rightarrow j$ had cost $c_{i, j}$, now it's cost is ${c'}_{i, j} = c_{i, j} + p(i) - p(j)$. It's easy to prove that if some path from vertex $v$ to vertex $u$ was the shortest one between these vertices without modifying the costs with potentinals, then after modifying it will also be the shortest between these vertices. So instead of looking for an augmenting path in the original network we can try looking for it in a network with modified edges. Why? Because it is always possible to set all potentials in such a way that all costs of edges will be non-negative (and we will be able to use Dijkstra to find the shortest path from the source to the sink). Before looking for the first augmenting path, we calculate potentials recursively: $p(source) = 0$, $p(v) = min{p(u) + c_{u, v}}$ (we check all $u$'s such that there is an edge $u\\rightarrow v$ in the network). The network is acyclic before we push flow, so there is always a way to calculate these potentials with dynamic programming. Then each time we want to find an augmenting path, we run Dijkstra's algoritm on modified network, push flow through the path we found and modify the potentials: new potential of each vertex $v$ becomes $p'(v) = p(v) + d(v)$, where $d(v)$ is the distance between the source and vertex $v$ in the modified network (and we found this distance with Dijkstra). When we have found four augmenting paths, we are done and it's time to evaluate the cost of the flow.",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "819",
    "index": "A",
    "title": "Mister B and Boring Game",
    "statement": "\\textbf{Unfortunately, a mistake was found in the proof of the author's solution to this problem. Currently, we don't know the absolutely correct solution. However, you can solve this task, but if your solution passes all the tests, it is not guaranteed to be correct. If your solution has passed all the tests, and you are sure that it is correct, you can write to one of the contest authors about it.}\n\nSometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens.\n\nAll characters in this game are lowercase English letters. There are two players: Mister B and his competitor.\n\nInitially the players have a string $s$ consisting of the first $a$ English letters in alphabetical order (for example, if $a = 5$, then $s$ equals to \"abcde\").\n\nThe players take turns appending letters to string $s$. Mister B moves first.\n\nMister B must append exactly $b$ letters on each his move. He can arbitrary choose these letters. His opponent adds exactly $a$ letters on each move.\n\nMister B quickly understood that his opponent was just a computer that used a simple algorithm. The computer on each turn considers the suffix of string $s$ of length $a$ and generates a string $t$ of length $a$ such that all letters in the string $t$ are distinct and don't appear in the considered suffix. From multiple variants of $t$ lexicographically minimal is chosen (if $a = 4$ and the suffix is \"bfdd\", the computer chooses string $t$ equal to \"aceg\"). After that the chosen string $t$ is appended to the end of $s$.\n\nMister B soon found the game boring and came up with the following question: what can be the minimum possible number of different letters in string $s$ on the segment between positions $l$ and $r$, inclusive. Letters of string $s$ are numerated starting from $1$.",
    "tutorial": "Tutorial is not available",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "819",
    "index": "B",
    "title": "Mister B and PR Shifts",
    "statement": "Some time ago Mister B detected a strange signal from the space, which he started to study.\n\nAfter some transformation the signal turned out to be a permutation $p$ of length $n$ or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.\n\nLet's define the deviation of a permutation $p$ as $\\textstyle\\sum_{i=1}^{n-n}|p|i|-i|$.\n\nFind a cyclic shift of permutation $p$ with minimum possible deviation. If there are multiple solutions, print any of them.\n\nLet's denote id $k$ ($0 ≤ k < n$) of a cyclic shift of permutation $p$ as the number of right shifts needed to reach this shift, for example:\n\n- $k = 0$: shift $p_{1}, p_{2}, ... p_{n}$,\n- $k = 1$: shift $p_{n}, p_{1}, ... p_{n - 1}$,\n- ...,\n- $k = n - 1$: shift $p_{2}, p_{3}, ... p_{n}, p_{1}$.",
    "tutorial": "Let's see, how $p_{k}$ $(1  \\le  k  \\le  n)$ affects different shifts. Let's denote $d_{i}$ is deviation of the $i - th$ shift. At first all $d_{i} = 0$. Then $p_{k}$ affects it in following way: $d_{0} + = |p_{k} - k|$, $d_{1} + = |p_{k} - (k + 1)|$, $...$ $d_{n - k} + = |p_{k} - n|$, $d_{n - k + 1} + = |p_{k} - 1|$, $...$ $d_{n - 1} + = |p_{k} - (k - 1)|$. Then there are 2 cases: $p_{k}  \\ge  k$ or not. If $p_{k}  \\ge  k$ after removing modules we will get 3 query: to add $p_{k} - (k + i)$ to $d_{i}$ where $0  \\le  i  \\le  p_{k} - k$, to add $(k + i) - p_{k}$ to $d_{i}$ where $p_{k} - k < i  \\le  n - k$ and to add $p_{k} - i$ to $d_{n - k + i}$ where $0 < i < k$. Else if $p_{k} < k$ we need to perform next operation: to add $(k + i) - p_{k}$ to $d_{i}$ where $0  \\le  i  \\le  n - k$, to add $p_{k} - i$ to $d_{n - k + i}$ where $1  \\le  i  \\le  p_{k}$ and to add $i - p_{k}$ to $d_{n - k + i}$ where $p_{k} < i < k$. But in both cases we must add 3 arithmetic progression to the segment of array $d$. Or make operation of adding $k \\cdot (x - l) + b$ to segment $[l, r]$. Its known task, which can be done by adding/subtracting values in start and end of segment offline. To make such operation we need to remember, how to add value $b$ to segment $[l, r]$ of array $d$ offline. We can just do next operations: $d[l] + = b$ and $d[r + 1] - = b$. Now value in position $i$ $a n s_{i}=\\sum_{j=0}^{j=t}d[j]$. So what is adding progression with coef $k$? it's only adding to array $d$ value $k$ to all positions in segment $[l, r]$. That's why we need other array, for example $df$ and making $df[l] + = k$ and $df[r + 1] - = k$. In result, $d[i]=d[i]+\\sum_{j=0}^{j=i-1}d f[j]$. So algorithm to add $k \\cdot (x - l) + b$ to segment $[l, r]$ is next: $d[l] + = b$, $d[r + 1] - = k \\cdot (r - l + 1)$, $df[l] + = k$, $df[r + 1] - = k$. After all queries we need recover array $d$ with formula $d[i]=d[i]+\\sum_{j=0}^{j=i-1}d f[j]$. And after that get answer with formula $a n s_{i}=\\sum_{j=0}^{j=t}d[j]$. So complexity is $O(n)$.",
    "code": "#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) fore(i, 0, n)\n\ntypedef long long li;\n\nconst int N = 1000 * 1000 + 555;\n\nint n, p[N];\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\tforn(i, n)\n\t\tassert(scanf(\"%d\", &p[i]) == 1);\n\treturn true;\n}\n\nli sum[N], df[N], res[N];\n\ninline void add(int lf, int rg, int k, int b) {\n\tif(lf > rg)\n\t\treturn;\n\t\t\t\t\n\tsum[lf] += b;\n\tdf[lf] += k;\n\t\n\tsum[rg + 1] -= b + k * 1ll * (rg - lf);\n\tdf[rg] -= k;\n}\n\ninline void calc() {\n\tli curdf = 0;\n\tforn(i, n) {\n\t\tsum[i] += curdf;\n\t\tcurdf += df[i];\n\t}\n\t\n\tli cursm = 0;\n\tforn(i, n) {\t\n\t\tcursm += sum[i];\n\t\tres[i] += cursm;\n\t}\n}\n\ninline void solve() {\n\tmemset(sum, 0, sizeof sum);\n\tmemset(df, 0, sizeof df);\n\tmemset(res, 0, sizeof res);\n\t\n\tforn(i, n) {\n\t\tint c1 = i + 1, p1 = 0;\n\t\tint c2 = n,     p2 = p1 + c2 - c1;\n\t\tint c3 = i,     p3 = p2 + c3;\n\t\t\n\t\tif(p[i] <= c3) {\n\t\t\tadd(p1, p2, 1, c1 - p[i]);\n\t\t\tadd(p2 + 1, p2 + p[i], -1, p[i] - 1);\n\t\t\tadd(p2 + p[i] + 1, p3, 1, 1);\n\t\t} else {\n\t\t\tadd(p1, p1 + p[i] - c1, -1, p[i] - c1);\n\t\t\tadd(p1 + p[i] - c1 + 1, p2, 1, 1);\n\t\t\tadd(p2 + 1, p3, -1, p[i] - 1);\n\t\t}\n\t}\n\t\n\tcalc();\n\t\n\tint ans = 0;\n\tforn(i, n)\n\t\tif(res[ans] > res[i])\n\t\t\tans = i;\n\t\t\t\n\tcout << res[ans] << \" \" << ans << endl;\n}",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "819",
    "index": "C",
    "title": "Mister B and Beacons on Field",
    "statement": "Mister B has a house in the middle of a giant plain field, which attracted aliens life. For convenience, aliens specified the Cartesian coordinate system on the field in such a way that Mister B's house has coordinates $(0, 0)$. After that they sent three beacons to the field, but something went wrong. One beacon was completely destroyed, while the other two landed in positions with coordinates $(m, 0)$ and $(0, n)$, respectively, but shut down.\n\nMister B was interested in this devices, so he decided to take them home. He came to the first beacon, placed at $(m, 0)$, lifted it up and carried the beacon home choosing the shortest path. After that he came to the other beacon, placed at $(0, n)$, and also carried it home choosing the shortest path. When first beacon was lifted up, the navigation system of the beacons was activated.\n\nPartially destroyed navigation system started to work in following way.\n\nAt time moments when both survived beacons are at points with integer coordinates the system tries to find a location for the third beacon. It succeeds if and only if there is a point with integer coordinates such that the area of the triangle formed by the two survived beacons and this point is equal to $s$. In this case the system sends a packet of information with beacon positions to aliens, otherwise it doesn't.\n\nCompute how many packets of information system sent while Mister B was moving the beacons.",
    "tutorial": "There 2 stages in this task: moving of first beacon and moving of second. But at first we need factorization of $n$ and $s$. Since $n$ and $s$ are product of integers $ \\le  10^{6}$, it can be done in $O(log(n) + log(s))$ time by \"Sieve of Eratosthenes\". Start from second stage, when second beacon is moving: Position of beacons will look like pair of points: $(0, 0)$, $(0, k)$, where $0  \\le  k  \\le  n$. We need to check existing of point $(x, y)$ such, that area of triangle $(0, 0)$, $(0, k)$, $(x, y)$ equals to $s$. Using cross product $|((0, k) - (0, 0)) \\cdot ((x, y) - (0, 0))| = 2 \\cdot s$. After simplifying we get $|k \\cdot x| = 2 \\cdot s$ where $0  \\le  k  \\le  n$. So we can iterate all divisors of $2 \\cdot s$, using factorization of $s$ and recursive algorithm. Complexity of second stage is $O( \\sigma  (s))$, where $ \\sigma  (s)$ - number of divisors of $s$ and for $s  \\le  10^{18}$ $ \\sigma  (s)  \\le   \\approx  10^{5}$. In the first stage we have such points: $(k, 0)$, $(0, n)$, where $1  \\le  k  \\le  m$. We need to check existing of point $(x, y)$ such, that area of triangle $(k, 0)$, $(0, n)$, $(x, y)$ equals to $s$. Using cross product $|((k, 0) - (0, n)) \\cdot ((x, y) - (0, n))| = 2 \\cdot s$ we can get next equation: $|k \\cdot (y - n) + n \\cdot x| = 2 \\cdot s$. Then solution exists iff $gcd(k, n) | 2 \\cdot s$ $(2s % gcd(k, n) = 0)$. And we need to calculate how many $1  \\le  k  \\le  m$ such, that $gcd(k, n) | 2 \\cdot s$. We will solve it in next way: let's $n = p_{1}^{n1}p_{2}^{n2}... p_{l}^{nl}$ and $2s = p_{1}^{s1}p_{2}^{s2}... p_{l}^{sl}$ $(n_{i}, s_{i}  \\ge  0)$. Look at all $p_{i}$, that $n_{i} > s_{i}$. It's obvious, that if $p_{i}^{si + 1}$ is divisor of $k$, then $2s$ doesn't divide at $gcd(k, n)$. In result, we have some constrains on $k$, like $k$ doesn't divide at $a_{j} = p_{ij}^{sij + 1}$. Finally, we have next task: calculate number of $k$ $(1  \\le  k  \\le  n)$ such, that $k$ doesn't divide any of $a_{i}$. It can be done with inclusion-exclusion principle, where number of $k$ which divides $a_{i1}$, $a_{i2}$ ... $a_{ib}$ is $\\frac{n}{a_{i_{1}a_{2}\\cdots a_{i_{k}}}}$. Complexity of first stage is $O(2^{z(n)})$, where $z(x)$ - number of prime divisors of $x$, $z  \\le  15$ for integers up to $10^{18}$. Result complexity is $O( \\sigma  (s) + 2^{z(n)})$ per test.",
    "code": "#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) fore(i, 0, n)\n\n#define all(a) (a).begin(), (a).end()\n#define sqr(a) ((a) * (a))\n#define sz(a) int(a.size())\n#define mp make_pair\n#define pb push_back\n\ntypedef long long li;\ntypedef pair<int, int> pt;\ntypedef pair<li, li> ptl;\n\nconst int INF = int(1e9);\nconst li INF64 = li(INF) * INF;\n\nint n[3], m[3], s[3];\n\ninline bool read() {\n\tif(scanf(\"%d %d %d\", &n[0], &n[1], &n[2]) != 3)\n\t\treturn false;\n\tforn(i, 3)\n\t\tassert(scanf(\"%d\", &m[i]) == 1);\n\tforn(i, 3)\n\t\tassert(scanf(\"%d\", &s[i]) == 1);\n\treturn true;\n}\n\nconst int N = 2 * 1000 * 1000 + 55;\nint ls[N];\n\ninline void precalc() {\n\tmemset(ls, -1, sizeof ls);\n\t\n\tls[0] = ls[1] = 1;\n\tfore(i, 2, N) {\n\t\tif(ls[i] != -1)\n\t\t\tcontinue;\n\t\t\t\n\t\tls[i] = i;\n\t\tfor(li j = i * 1ll * i; j < N; j += i)\n\t\t\tif(ls[j] == -1)\n\t\t\t\tls[j] = i;\n\t}\n}\n\ninline vector<pt> fact(int n[3]) {\n\tvector<int> divs;\n\t\n\tforn(i, 3) {\n\t\tint cur = n[i];\n\t\twhile(ls[cur] != cur) {\n\t\t\tdivs.pb(ls[cur]);\n\t\t\tcur /= ls[cur];\n\t\t}\n\t\tif(cur > 1)\n\t\t\tdivs.pb(cur);\n\t}\n\t\n\tsort(all(divs));\n\tvector<pt> ans;\n\t\n\tint u = 0;\n\twhile(u < sz(divs)) {\n\t\tint v = u;\n\t\twhile(v < sz(divs) && divs[v] == divs[u])\n\t\t\tv++;\n\t\t\n\t\tans.pb(mp(divs[u], v - u));\n\t\tu = v;\n\t}\n\t\n\treturn ans;\n}\n\nli ans;\n\nli nn, mm, ss;\nvector<pt> fs;\nvector<li> bad;\n\nvoid calcDivs(int pos, li val) {\n\tif(pos >= sz(fs)) {\n\t\tans += (val <= nn);\n\t\treturn;\n\t}\n\t\n\tli cv = 1;\n\tforn(i, fs[pos].y + 1) {\n\t\tcalcDivs(pos + 1, val * cv);\n\t\t\n\t\tcv *= fs[pos].x;\n\t}\n}\n\nvoid calcInEx(int pos, li val, int cnt) {\n\tif(pos >= sz(bad)) {\n\t\tli k = cnt ? -1 : 1;\n\t\t\n\t\tans += k * (mm / val);\n\t\treturn;\n\t}\n\t\n\tcalcInEx(pos + 1, val, cnt);\n\tcalcInEx(pos + 1, val * bad[pos], cnt ^ 1);\n}\n\ninline void solve() {\n\tans = 0;\n\ts[0] *= 2;\n\t\n\tnn = n[0] * 1ll * n[1] * 1ll * n[2];\n\tmm = m[0] * 1ll * m[1] * 1ll * m[2];\n\tss = s[0] * 1ll * s[1] * 1ll * s[2];\n\t\n\tfs = fact(s);\n\tcalcDivs(0, 1);\n\t\n\tbad.clear();\n\tvector<pt> fn = fact(n);\n\t\n\tforn(i, sz(fn)) {\n\t\tli cv = fn[i].x;\n\t\tforn(k, fn[i].y) {\n\t\t\tif(ss % cv != 0) {\n\t\t\t\tbad.pb(cv);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcv *= fn[i].x;\n\t\t}\n\t}\n\t\n\tcalcInEx(0, 1, 0);\n\t\n\tprintf(\"%I64d\\n\", ans);\n}",
    "tags": [
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "819",
    "index": "D",
    "title": "Mister B and Astronomers",
    "statement": "After studying the beacons Mister B decided to visit alien's planet, because he learned that they live in a system of flickering star Moon. Moreover, Mister B learned that the star shines once in exactly $T$ seconds. The problem is that the star is yet to be discovered by scientists.\n\nThere are $n$ astronomers numerated from $1$ to $n$ trying to detect the star. They try to detect the star by sending requests to record the sky for $1$ second.\n\nThe astronomers send requests \\textbf{in cycle}: the $i$-th astronomer sends a request exactly $a_{i}$ second after the $(i - 1)$-th (i.e. if the previous request was sent at moment $t$, then the next request is sent at moment $t + a_{i}$); the $1$-st astronomer sends requests $a_{1}$ seconds later than the $n$-th. The first astronomer sends his first request at moment $0$.\n\nMister B doesn't know the first moment the star is going to shine, but it's obvious that all moments at which the star will shine are determined by the time of its shine moment in the interval $[0, T)$. Moreover, this interval can be split into $T$ parts of $1$ second length each of form $[t, t + 1)$, where $t = 0, 1, 2, ..., (T - 1)$.\n\nMister B wants to know how lucky each astronomer can be in discovering the star first.\n\nFor each astronomer compute how many segments of form $[t, t + 1)$ ($t = 0, 1, 2, ..., (T - 1)$) there are in the interval $[0, T)$ so that this astronomer is the first to discover the star if the first shine of the star happens in this time interval.",
    "tutorial": "Let's construct slow but clear solution and then, speed it up. Let's denote $s=\\sum_{i=1}^{i=n}a_{i}$. We can see, that, at first, all operation with time are modulo $T$ and the $i - th$ astronomer checks moments $st_{i}$, $(st_{i} + s)%T$, $(st_{i} + 2s)%T$ ..., where $s t_{i}=\\sum_{j=2}^{j=i}a_{i}$. More over, every astronomer, who checks moment $t$ will check moment $(t + S)%T$ by next time. So we now constructed functional graph with $T$ vertices. But this graph has very special type, since it can be divided on some cycles. More specifically, This graph consists of $gcd(T, s)$ oriented cycles and each cycle has length exactly $\\frac{T}{r e c(T,s)}$. Even more, vertices $u$ and $v$ belong to same cycle iff $u  \\equiv  v (mod gcd(T, s))$. So we can work with cycles independently. Let's look closely on one cycle. It's obviously, that all astronomers will walk on their cycles from their starting positions $st_{i} % T$. But what the answer for them. Answer for the $i - th$ astronomer is number of vertices, including starting vertex, to the nearest starting vertex of any other astronomer if count along the orientation of cycle, because if two astronomers came to same vertex, lucky is one, who came first. Other astronomer has this vertex as start, his time is $st_{j}$, $i - th$ time is $st_{i} + k \\cdot s$, $k  \\ge  1$ and $st_{i} + k \\cdot s > st_{j}$. If $st_{i}  \\equiv  st_{j} (mod T)$ and $st_{i} < st_{j}$ then answer for the $j - th$ astronomer is always $0$. So we must effectively calculate distance between two positions on cycle. For that, let's numerate vertices along the orientation of cycle using vertex with minimal label as $0$. If we will know position of $st_{i}% T$ for every astronomer calculation of distance between consecutive is trivial (sort, or set or other). For the $i - th$ astronomer let's denote vertex with label $0$ in his cycle as $z_{i}$. $z_{i} = st_{i} % gcd(T, s)$. But cycles very specific, because vertex with label $0$ is $z_{i}$, vertex with label $1$ is $(z_{i} + s) % T$, vertex with label $2$ is $(z_{i} + 2s) % T$. In other words, vertex with label $k$ is $(z_{i} + k \\cdot s) % T$. If we want to know position $k$ of $st_{i}$, we need to find $v$ such, that $v  \\equiv  (v% gcd(T, s)) + k \\cdot s(mod T)$ which is diofant equation and can be calculated in $O(log(T))$ time. Result complexity is $O(n \\cdot log(T))$.",
    "code": "#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) fore(i, 0, n)\n\n#define all(a) (a).begin(), (a).end()\n#define sqr(a) ((a) * (a))\n#define sz(a) int(a.size())\n#define mp make_pair\n#define pb push_back\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(INF) * INF;\n\nint gcd(int a, int b) {\n\tif(a == 0)\n\t\treturn b;\n\treturn gcd(b % a, a);\n}\n\nint exgcd(int a, li &x, int b, li &y) {\n\tif(a == 0) {\n\t\tx = 0, y = 1;\n\t\treturn b;\n\t}\n\t\n\tli xx, yy;\n\tint g = exgcd(b % a, xx, a, yy);\n\t\n\tx = yy - b / a * xx;\n\ty = xx;\n\t\n\treturn g;\n}\n\nconst int N = 200 * 1000 + 555;\nint t, n, a[N];\n\ninline bool read() {\n\tif(!(cin >> t >> n))\n\t    return false;\n\tforn(i, n)\n\t\tassert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nint pf[N], s;\n\ninline li up(li a, li b) {\n\treturn (a + b - 1) / b;\n}\n\ninline int findPos(int a, int b, int c) {\n\tli x, y;\n\tint g = exgcd(a, x, b, y);\n\tassert(c % g == 0);\n\t\n\tx *= +c / g;\n\ty *= -c / g;\n\tassert(a * 1ll * x - b * 1ll * y == c);\n\t\n\tint ag = a / g;\n\tint bg = b / g;\n\t\n\tli k = 0;\n\tif(x < 0)\n\t\tk = up(-x, bg);\n\tif(x >= bg)\n\t\tk = -up(x - bg, bg);\t\n\tx += bg * k;\n\ty += ag * k;\n\t\t\n\tassert(0 <= x && x < bg);\n\t\n\tk = 0;\n\tif(y < 0)\n\t\tk = up(-y, ag);\n\tx += bg * k;\n\ty += ag * k;\n\n\treturn x;\n}\n\nmap< int, set<pt> > cycle;\n\nint ans[N];\n\ninline void solve() {\n\tcycle.clear();\n\tpf[0] = 0;\n\tfore(i, 1, n)\n\t\tpf[i] = (pf[i - 1] + a[i]) % t;\n\t\n\ts = (a[0] + pf[n - 1]) % t;\n\tint g = gcd(s, t);\n\t\n\tforn(i, n) {\n\t\tint st = pf[i] % g;\n\t\tauto& cc = cycle[st];\n\t\t\n\t\tint pos = findPos(s, t, pf[i] - st);\n\t\t\n\t\tif(cc.empty()) {\n\t\t\tans[i] += t / g;\n\t\t\tcc.insert(pt(pos, -i));\n\t\t} else {\n\t\t\tauto rg = cc.lower_bound(pt(pos, -i));\n\t\t\tif(rg == cc.end()) {\n\t\t\t\tans[i] += t / g - pos;\n\t\t\t\trg = cc.begin();\n\t\t\t\tans[i] += rg->x;\n\t\t\t} else\n\t\t\t\tans[i] += rg->x - pos;\n\t\t\t\t\n\t\t\tauto lf = cc.lower_bound(pt(pos, -i));\n\t\t\tif(lf == cc.begin())\n\t\t\t\tlf = --cc.end();\n\t\t\telse\n\t\t\t\tlf--;\n\t\t\tans[ -(lf->y) ] -= ans[i];\n\t\t\t\n\t\t\tcc.insert(pt(pos, -i));\n\t\t} \n\t}\n\t\n\tforn(i, n)\n\t\tprintf(\"%d \", ans[i]);\n\tputs(\"\");\n}",
    "tags": [
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "819",
    "index": "E",
    "title": "Mister B and Flight to the Moon",
    "statement": "In order to fly to the Moon Mister B just needs to solve the following problem.\n\nThere is a complete indirected graph with $n$ vertices. You need to cover it with several simple cycles of length $3$ and $4$ so that each edge is in exactly $2$ cycles.\n\nWe are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?",
    "tutorial": "There are different constructive solutions in this problem. Here is one of them. Consider odd and even $n$ separately. Let $n$ be even. Let's build for each even $n  \\ge  4$ a solution such that there are triangles 1-2-x, 3-4-y, 5-6-z and so on. For $n = 4$ it's easy to construct such a solution. Then let's add two vertices at a time: $a = n - 1$ and $b = n$. Instead of triangle 1-2-x let's add triangle 1-a-2-x, square 1-a-2-b and square 1-2-b. The same with 3-4-y, 5-6-z and so on. Only one edge a-b is remaining, we should add it twice. To do this let's replace the square 1-a-2-b with triangles a-b-1 and a-b-2. Easy to see that the condition on triangles is satisfied, so we can proceed to adding two more vertices and so on. To deal with odd $n$ let's keep triangles 2-3-x, 4-5-y and so on. To add two more vertices replace each of these triangles with two squares and one triangle in the same way as for even $n$, and also add two triangles 1-a-b.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n\n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nconst int maxn = 305;\n\nint pair3[maxn];\nint n;\nvector<vector<int>> answer;\n\nvoid add3(int a, int b, int c)\n{\n    answer.pb({a, b, c});\n}\n\nvoid add4(int a, int b, int c, int d)\n{\n    answer.pb({a, b, c, d});\n}\n\nint main()\n{\n    cin >> n;\n    if (n % 2 == 0)\n    {\n        pair3[0] = 3; // 0 1 3\n        pair3[2] = 1; // 2 3 1\n        add3(0, 1, 2);\n        add3(2, 3, 0);\n        for (int i = 4; i < n; i += 2)\n        {\n            add4(0, pair3[0], 1, i);\n            add3(i, i + 1, 0);\n            pair3[i] = 1;\n            pair3[0] = i + 1;\n            for (int j = 2; j < i; j += 2)\n            {\n                add4(j, pair3[j], j + 1, i);\n                add4(j, i, j + 1, i + 1);\n                pair3[j] = i + 1;\n            }\n        }\n        for (int i = 0; i < n; i += 2)\n        {\n            add3(i, i + 1, pair3[i]);\n        }\n    } else\n    {\n        pair3[1] = 0; // 1 2 0\n        add3(0, 1, 2);\n        for (int i = 3; i < n; i += 2)\n        {\n            add3(i, i + 1, 0);\n            pair3[i] = 0;\n            for (int j = 1; j < i; j += 2)\n            {\n                add4(j, pair3[j], j + 1, i);\n                add4(j, i, j + 1, i + 1);\n                pair3[j] = i + 1;\n            }\n        }\n        for (int i = 1; i < n; i += 2)\n        {\n            add3(i, i + 1, pair3[i]);\n        }\n    }\n    printf(\"%d\\n\", (int)answer.size());\n    for (auto &t : answer)\n    {\n        printf(\"%d\", (int)t.size());\n        for (auto t2 : t) printf(\" %d\", t2 + 1);\n        printf(\"\\n\");\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "820",
    "index": "A",
    "title": "Mister B and Book Reading",
    "statement": "Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had $c$ pages.\n\nAt first day Mister B read $v_{0}$ pages, but after that he started to speed up. Every day, starting from the second, he read $a$ pages more than on the previous day (at first day he read $v_{0}$ pages, at second — $v_{0} + a$ pages, at third — $v_{0} + 2a$ pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than $v_{1}$ pages per day.\n\nAlso, to refresh his memory, every day, starting from the second, Mister B had to reread last $l$ pages he read on the previous day. Mister B finished the book when he read the last page for the first time.\n\nHelp Mister B to calculate how many days he needed to finish the book.",
    "tutorial": "All that needed - is to accurately simulate process. Create variable, which will contain count of read pages, subtract $l$, add $v_{0}$, check, what you still have unread pages, make $v_{0} = min(v_{1}, v_{0} + a)$ and again. Complexity is $O(c)$.",
    "code": "#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) fore(i, 0, n)\n\nint c, l, v0, v1, a;\n\ninline bool read() {\n\tif(!(cin >> c >> v0 >> v1 >> a >> l))\n\t\treturn false;\n\t\n\treturn true;\n}\n\ninline void solve() {\n\tint pos = v0;\n\tint t = 1;\n\t\n\tint add = v0;\n\t\n\twhile(pos < c) {\n\t\tadd = min(v1, add + a);\n\t\t\n\t\tpos += add - l;\n\t\tt++;\n\t}\n\t\n\tcout << t << endl;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "820",
    "index": "B",
    "title": "Mister B and Angle in Polygon",
    "statement": "On one quiet day all of sudden Mister B decided to draw angle $a$ on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is \\textbf{regular convex $n$-gon} (regular convex polygon with $n$ sides).\n\nThat's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices $v_{1}$, $v_{2}$, $v_{3}$ such that the angle $\\angle v_{1}v_{2}v_{3}$ (where $v_{2}$ is the vertex of the angle, and $v_{1}$ and $v_{3}$ lie on its sides) is as close as possible to $a$. In other words, the value $|Z v_{1}v_{2}v_{3}-a|$ should be minimum possible.\n\nIf there are many optimal solutions, Mister B should be satisfied with any of them.",
    "tutorial": "Since polygon is regular, all vertices of a regular polygon lie on a common circle (the circumscribed circle), so all possible angles are inscribed angles. And all inscribed angles subtending the same arc have same measure. More over, minor and major arcs between vertices $v_{i}$ and $v_{k}$ equals to minor and major arcs between vertices $v_{i + 1}$ and $v_{k + 1}$. And finally, length of arc can be calculated with formula as sum of minor arcs between consecutive vertices. Length of minor arcs between consecutive vertices equals to $360 / n$. Length of inscribed angle is half of arc it based on. In other words $\\displaystyle\\angle v_{1}v_{2}v_{3}={\\frac{190\\,(n-(v_{3}-v_{1}))}{n}}$ if $v_{1} < v_{2} < v_{3}$ or $\\textstyle{\\frac{|\\mathbf{x}|_{1}(x_{1})_{n}|}{n}}$ in other case. In the end, this task can be solved by checking all different $(v_{3} - v_{1})$ ($v_{1}$ can be fixed as $1$), or by formula, if we put in $|Z v_{1}v_{2}v_{3}-a|$ formula above. In result finding closest angle can be done in $O(n)$ or even $O(1)$ time.",
    "code": "int n, a;\n\ninline bool read() {\n\tif(!(cin >> n >> a))\n\t\treturn false;\n\t\n\treturn true;\n}\n\ninline void solve() {\n\tint base = n * a / 180;\n\tbase = max(1, min(n - 2, base));\n\t\n\tint bk = base;\n\tfor(int ck = max(1, base - 2); ck <= min(n - 2, base + 2); ck++) {\n\t\tif(abs(180 * ck - n * a) < abs(180 * bk - n * a))\n\t\t\tbk = ck;\n\t}\n\t\n\tcout << 2 << \" \" << 1 << \" \" << bk + 2 << endl;\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "821",
    "index": "A",
    "title": "Okabe and Future Gadget Laboratory",
    "statement": "Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an $n$ by $n$ square grid of integers. A good lab is defined as a lab in which every number not equal to $1$ can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every $x, y$ such that $1 ≤ x, y ≤ n$ and $a_{x, y} ≠ 1$, there should exist two indices $s$ and $t$ so that $a_{x, y} = a_{x, s} + a_{t, y}$, where $a_{i, j}$ denotes the integer in $i$-th row and $j$-th column.\n\nHelp Okabe determine whether a given lab is good!",
    "tutorial": "We can simulate exactly what's described in the statement: loop over all cells not equal to 1 and check if it doesn't break the city property. To check if a cell breaks the property, just loop over an element in the same row, and an element in the same column, and see if they can add to give the cell's number. The complexity is O($n^{4}$).",
    "code": "#include <queue>\n#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <stack>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <utility>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <complex>\n#include <fstream>\n#include <cstring>\n#include <string>\n#include <climits>\nusing namespace std;\n//macros\ntypedef long long ll;\ntypedef complex<double> point;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef vector< vector<int> > vvi;\n\n\n\n\n#define FOR(k,a,b) for(int k=(a); k<=(b); ++k)\n#define REP(k,a) for(int k=0; k<(a);++k)\n#define SZ(a) int((a).size())\n#define ALL(c) (c).begin(),(c).end()\n#define PB push_back\n#define MP make_pair\n#define INF 999999999\n#define INFLONG 1000000000000000000LL\n#define MOD 1000000007\n#define MAX 100\n#define ITERS 100\n#define pi 3.1415926\n#define MAXN 100000\n#define _gcd __gcd\n\nint main()\n{\n    int n;\n    cin >> n;\n    int grid[50][50];\n    REP(i,n){\n        REP(j,n){\n            cin >> grid[i][j];\n        }\n    }\n    REP(i,n){\n        REP(j,n){\n            if(grid[i][j]==1) continue;\n            bool pass = false;\n            for(int r = 0;r<n;r++){\n                if(r==i) continue;\n                for(int c = 0; c < n; c++){\n                    if(c==j) continue;\n                    int sum = grid[r][j]+grid[i][c];\n                    if(sum==grid[i][j]){\n                        pass=true;\n                        break;\n                    }\n                }\n                if(pass)break;\n            }\n            if(!pass){\n                cout << \"No\"<<endl;\n                return 0;\n            }\n        }\n    }\n    cout << \"Yes\"<<endl;\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "821",
    "index": "B",
    "title": "Okabe and Banana Trees",
    "statement": "Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.\n\nConsider the point $(x, y)$ in the 2D plane such that $x$ and $y$ are integers and $0 ≤ x, y$. There is a tree in such a point, and it has $x + y$ bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation $y=-{\\frac{x}{m}}+b$. Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point.\n\nHelp Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely.\n\nOkabe is sure that the answer does not exceed $10^{18}$. You can trust him.",
    "tutorial": "The critical observation to make is that the optimal rectangle should always have a lower-left vertex at the origin. This is due to the fact that the line has positive y-intercept and negative slope: any rectangle which doesn't have a vertex at the origin could easily be extended to have a vertex at the origin and even more bananas. Then, we just need to try every x-coordinate for the upper-right corner of the box and pick the maximum y-coordinate without going over the line. We can compute the sum of any rectangle in $O(1)$ using arithmetic series sums, so this becomes $O(bm)$ because the x-intercept can be up to $bm$. You can make it faster by trying every y-coordinate; this makes the complexity $O(b)$, but this was unnecessary to solve the problem.",
    "code": "\n#include <queue>\n#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <stack>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <utility>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <complex>\n#include <fstream>\n#include <cstring>\n#include <string>\n#include <climits>\nusing namespace std;\n\n//macros\ntypedef long long ll;\ntypedef complex<double> point;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef vector< vector<int> > vvi;\n\n\n\n\n#define FOR(k,a,b) for(int k=(a); k<=(b); ++k)\n#define REP(k,a) for(int k=0; k<(a);++k)\n#define SZ(a) int((a).size())\n#define ALL(c) (c).begin(),(c).end()\n#define PB push_back\n#define MP make_pair\n#define INF 999999999\n#define INFLONG 1000000000000000000\n#define MOD 1000000007\n#define MAX 100\n#define ITERS 100\n#define MAXM 200000\n#define MAXN 1000000\n#define _gcd __gcd\n#define eps 1e-9\nll series(ll x){\n\treturn x*(x+1)/2;\n}\nint main() {\n\tint m,b;\n\tcin >> m >> b;\n\tll best = 0;\n\tfor(int y = b; y >=0; y--){\n\t\t//y = -x/m + b\n\t\tll x = m*(b-y);\n\t\tll t = 0;\n\t\tt+=(x+1)*series(y)+(y+1)*series(x);\n\t\tbest = max(best,t);\n\t}\n\tcout << best << endl;\n}\n",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "821",
    "index": "C",
    "title": "Okabe and Boxes",
    "statement": "Okabe and Super Hacker Daru are stacking and removing boxes. There are $n$ boxes numbered from $1$ to $n$. Initially there are no boxes on the stack.\n\nOkabe, being a control freak, gives Daru $2n$ commands: $n$ of which are to add a box to the top of the stack, and $n$ of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from $1$ to $n$. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.\n\nThat's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.\n\nTell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.",
    "tutorial": "It looks like Daru should only reorder the boxes when he has to (i.e. he gets a remove operation on a number which isn't at the top of the stack). The proof is simple: reordering when Daru has more boxes is always not worse than reordering when he has less boxes, because Daru can sort more boxes into the optimal arrangement. Therefore, our greedy algorithm is as follows: simulate all the steps until we need to reorder, and then we resort the stack in ascending order from top to bottom. This has complexity $O(n^{2}$ $log$ $n)$. However, we can speed this up if we note that whenever we reorder boxes, any box currently on the stack can be put in an optimal position and we can pretty much forget about it. So whenever we reorder, we can just clear the stack as well and continue. This gives us $O(n)$ complexity because every element is added and removed exactly once.",
    "code": "#include <vector>\n#include <utility>\n#include <iostream>\n#include <cassert>\n#include <map>\n#include <climits>\n#include <deque>\n#include <algorithm>\n#include <set>\n#include <stack>\nusing namespace std;\n\n#define ll long long\n#define REP(i,a) for(int i = 0; i < (a); i++)\n#define PB push_back\n#define SZ(a) (a).size()\n#define MP make_pair\n#define ALL(a) (a).begin(),(a).end()\n#define fs first\ntypedef vector<int> vi;\ntypedef pair<int,int> pii;\n\n\n\nint main()\n{\n    int n;\n    cin >> n;\n    stack<int> st;\n    int curr=1;\n    int ans = 0;\n    REP(i,2*n){\n        string str;\n        cin >> str;\n        assert(str[0]=='a' || str[0]=='r');\n        if(str[0]=='a'){\n            int x;\n            cin >> x;\n            st.push(x);\n        }else if(str[0]=='r'){\n            if(!st.empty()){\n                if(st.top()==curr){ //last thing added is what we need to remove\n                    st.pop();\n                }else{ //last thing we added is NOT what we need to remove\n                    ans++;\n                    while(!st.empty()) st.pop(); //clears the stack\n                }\n            }\n            curr++;\n        }\n    }\n    cout << ans << endl;\n}\n",
    "tags": [
      "data structures",
      "greedy",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "821",
    "index": "D",
    "title": "Okabe and City",
    "statement": "Okabe likes to be able to walk through his city on a path lit by street lamps. That way, he doesn't get beaten up by schoolchildren.\n\nOkabe's city is represented by a 2D grid of cells. Rows are numbered from $1$ to $n$ from top to bottom, and columns are numbered $1$ to $m$ from left to right. Exactly $k$ cells in the city are lit by a street lamp. It's guaranteed that the top-left cell is lit.\n\nOkabe starts his walk from the top-left cell, and wants to reach the bottom-right cell. Of course, Okabe will only walk on lit cells, and he can only move to adjacent cells in the up, down, left, and right directions. However, Okabe can also temporarily light all the cells in any single row or column at a time if he pays $1$ coin, allowing him to walk through some cells not lit initially.\n\nNote that Okabe can only light a single row or column at a time, and has to pay a coin every time he lights a new row or column. To change the row or column that is temporarily lit, he must stand at a cell that is lit initially. Also, once he removes his temporary light from a row or column, all cells in that row/column not initially lit are now not lit.\n\nHelp Okabe find the minimum number of coins he needs to pay to complete his walk!",
    "tutorial": "First, let's make this problem into one on a graph. The important piece of information is the row and column we're on, so we'll create a node like this for every lit cell in the grid. Edges in the graph are 0 between 2 nodes if we can reach the other immediately, or 1 if we can light a row/column to get to it. Now it's a shortest path problem: we need to start from a given node, and with minimum distance, reach another node. Only problem is, number of edges can be large, causing the algorithm to time out. There are a lot of options here to reduce number of transitions. The most elegant one I found is Benq's solution, which I'll describe here. From a given cell, you can visit any adjacent lit cells. In addition, you can visit any lit cell with difference in rows at most 2, and any lit cell with difference in columns at most 2. So from the cell (r,c), you can just loop over all those cells. The only tricky part is asking whether the current lit row/column should be a part of our BFS state. Since we fill the entire row/col and can then visit anything on that row/col, it doesn't matter where we came from. This means that you can temporarily light each row/column at most once during the entire BFS search. So complexity is $O(n + m + k)$, with a log factor somewhere for map or priority queue. Interestingly enough, you can remove the priority queue log factor because the BFS is with weights 0 and 1 only, but it performs slower in practice. You can see the code implementing this approach below. Another approach to this problem was using \"virtual nodes\". Virtual nodes are an easy way to put transitions between related states while keeping number of edges low. In this problem, we can travel to any lit cell if its row differs by <=2, or its column differs by at most 2, but naively adding edges would cause O(k^2) edges. Instead, for every row, lets make a virtual node. For every lit cell in this row, put an edge between the lit cell and this virtual node with cost 1. We can do something similar for every column. Now, it's easy to see that the shortest path in this graph suffices. A minor detail is that we should divide the answer by 2 since every skipping of a row or column ends up costing 2 units of cost.",
    "code": "/*#include <ext/pb_ds/assoc_container.hpp> \n#include <ext/pb_ds/tree_policy.hpp>*/\n#include <bits/stdc++.h>\n\nusing namespace std;\n//using namespace __gnu_pbds;\n \ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef pair<int, int> pii;\n//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;\n\n#define FOR(i, a, b) for (int i=a; i<b; i++)\n#define F0R(i, a) for (int i=0; i<a; i++)\n#define FORd(i,a,b) for (int i = (b)-1; i >= a; i--)\n#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)\n \n#define mp make_pair\n#define pb push_back\n#define f first\n#define s second\n#define lb lower_bound\n#define ub upper_bound\n\nconst int MOD = 1000000007;\ndouble PI = 4*atan(1);\n\nint dr[10001], dc[10001];\nvi row[10001], col[10001];\npriority_queue<pii> todo;\nvector<pii> lights;\nint dist[10001];\nmap<pii,int> label;\nint xdir[4] = {1,0,-1,0}, ydir[4] = {0,1,0,-1};\nint n,m,k; \n\nvoid filrow(int i, int val){\n    if (i >= 1 && i <= n && dr[i] == 0) {\n        dr[i] = 1;\n        for (int x: row[i]) if (val < dist[x]) {\n            dist[x] = val;\n            todo.push({-dist[x],x});\n        }\n    }\n}\n\nvoid filcol(int i, int val) {\n    if (i >= 1 && i <= m && dc[i] == 0) {\n        dc[i] = 1;\n        for (int x: col[i]) if (val < dist[x]) {\n            dist[x] = val;\n            todo.push({-dist[x],x});\n        }\n    }\n}\n\nvoid ad(int x, int y, int val) {\n    if (label.find({x,y}) != label.end()) \n        if (dist[label[{x,y}]] > val) {\n            dist[label[{x,y}]] = val;\n            todo.push({-val,label[{x,y}]});\n        }\n}\n\nint main() {\n    cin >> n >> m >> k;\n    \n    F0R(i,k) {\n        int r,c; cin >> r >> c;\n        lights.pb({r,c});\n        row[r].pb(i);\n        col[c].pb(i);\n        label[{r,c}] = i;\n    }\n    \n    F0R(i,10001) dist[i] = MOD;\n    \n    if (label.find({n,m}) == label.end()) {\n        filrow(n-1,1);\n        filrow(n,1);\n        filcol(m-1,1);\n        filcol(m,1);\n    } else todo.push({0,label[{n,m}]});\n    \n    \n    while (todo.size()) {\n        auto a = todo.top(); todo.pop();\n        a.f = -a.f;\n        if (a.f > dist[a.s]) continue;\n        \n        F0R(i,4) ad(lights[a.s].f+xdir[i],lights[a.s].s+ydir[i],a.f);\n        FOR(i,lights[a.s].f-2,lights[a.s].f+3) filrow(i,a.f+1);\n        FOR(i,lights[a.s].s-2,lights[a.s].s+3) filcol(i,a.f+1);\n    }\n    \n    if (dist[0] != MOD) cout << dist[0];\n    else cout << -1;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "821",
    "index": "E",
    "title": "Okabe and El Psy Kongroo",
    "statement": "Okabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points $(x, y)$ such that $x$ and $y$ are non-negative. Okabe starts at the origin (point $(0, 0)$), and needs to reach the point $(k, 0)$. If Okabe is currently at the point $(x, y)$, in one step he can go to $(x + 1, y + 1)$, $(x + 1, y)$, or $(x + 1, y - 1)$.\n\nAdditionally, there are $n$ horizontal line segments, the $i$-th of which goes from $x = a_{i}$ to $x = b_{i}$ inclusive, and is at $y = c_{i}$. It is guaranteed that $a_{1} = 0$, $a_{n} ≤ k ≤ b_{n}$, and $a_{i} = b_{i - 1}$ for $2 ≤ i ≤ n$. The $i$-th line segment forces Okabe to walk with $y$-value in the range $0 ≤ y ≤ c_{i}$ when his $x$ value satisfies $a_{i} ≤ x ≤ b_{i}$, or else he might be spied on. This also means he is required to be under two line segments when one segment ends and another begins.\n\nOkabe now wants to know how many walks there are from the origin to the point $(k, 0)$ satisfying these conditions, modulo $10^{9} + 7$.",
    "tutorial": "You can get a naive DP solution by computing $f(x, y)$, the number of ways to reach the point $(x, y)$. It's just $f(x - 1, y + 1) + f(x - 1, y) + f(x - 1, y - 1)$, being careful about staying above x axis and under or on any segments. To speed it up, note that the transitions are independent of x. This is screaming matrix multiplication! First, if you don't know the matrix exponentiation technique for speeding up DP, you should learn it from here. Now, let's think of the matrix representation. Since the x dimension is the long one and the y dimension is small, lets store a vector of values $dp$ where $dp_{i}$ is the number of ways to get to a y value of i at the current x value. This will be the initial vector for matrix multiplication. Now, what about the transition matrix? Since our initial vector has length y and we need a matrix to multiply it with to map it to another vector with length y, we need a y by y matrix. Now, if you think about how matrix multiplication works, you come up with an idea like this: put a 1 in the entry (i,j) if from a y value of i we can reach a y value of j (i.e. $|i - j|  \\le  1$). Don't believe me, multiply some vector times a matrix of this form to see how and why the transition works. You can then build this matrix quickly and then matrix exponentiate for under every segment and multiply by the initial vector, then make the result as the new initial vector for the next segment. You should make sure to remove values from the vector if the next segment is lower, or add values to the vector if the next segment is higher. This gives complexity $O(nh^{3}$ log $w$) where $h = 16$ and $w = k$.",
    "code": "#include <queue>\n#include <vector>\n#include <list>\n#include <map>\n#include <set>\n#include <deque>\n#include <stack>\n#include <bitset>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include <utility>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cstdio>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <complex>\n#include <fstream>\n#include <cstring>\n#include <string>\n#include <climits>\n#include <chrono>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <assert.h>\nusing namespace std;\n\n//macros\ntypedef long long ll;\ntypedef complex<double> point;\ntypedef pair<int,int> ii;\ntypedef vector<int> vi;\ntypedef vector< vector<int> > vvi;\n\n\n\n\n#define FOR(k,a,b) for(int k=(a); k<=(b); ++k)\n#define REP(k,a) for(int k=0; k<(a);++k)\n#define SZ(a) int((a).size())\n#define ALL(c) (c).begin(),(c).end()\n#define PB push_back\n#define MP make_pair\n#define INF 1000000001\n#define INFLONG 1000000000000000000\n#define MOD 1000000007\n#define MAX 100\n#define ITERS 100\n#define MAXM 200000\n#define MAXN 1000000\n#define _gcd __gcd\n#define EPS 1e-7\n#define PI 3.1415926535897932384626\n#define ERR -987654321\n\n//multiplies m1 and m2 and stores in m3\nvector<vector<long long> > matmul(vector<vector<long long> > m1, vector<vector<long long> > m2, vector<vector<long long> > &m3){\n    m3.clear();\n    vector<vector<long long> > ans;\n    REP(i,SZ(m1)){\n        vector<long long> v;\n\n        REP(j,SZ(m2[0])){\n            v.PB(0);\n        }\n        ans.PB(v);\n    }\n\n    REP(r,SZ(m1)){\n        REP(c,SZ(m2[0])){\n            REP(k, SZ(m2)){\n                ans[r][c] += m1[r][k]*m2[k][c];\n                ans[r][c]%=MOD;\n            }\n        }\n    }\n\n    REP(i,SZ(m1)){\n        vector<long long> cur;\n        REP(j,SZ(m2[0])){\n            cur.PB(ans[i][j]);\n        }\n        m3.PB(cur);\n    }\n    return m3;\n\n\n}\nvector<ll> mymul(vector<ll> vec, vector<vector<ll> > mat, vector<ll> &ret){\n    vector<ll> res;\n    REP(i,SZ(vec)){\n        ll sum = 0;\n        for(int co = 0; co < SZ(mat); co++){\n            sum += vec[co]*mat[co][i];\n            sum%=MOD;\n        }\n        res.PB(sum);\n    }\n    ret.clear();\n    REP(i,SZ(res)) ret.PB(res[i]);\n    return ret;\n}\nvoid printmat(vector<vector<long long> > matr){\n    REP(i,SZ(matr)){\n        REP(j,SZ(matr[i])){\n            cout << matr[i][j] << \" \" ;\n        }\n        cout << endl;\n    }\n}\nvector<vector<long long> > matexp(vector<vector<long long> > matr, long long n){\n    vector<vector<long long> > ans;\n    REP(i,SZ(matr)){\n        vector<long long> v;\n        REP(j,SZ(matr[0])){\n            v.PB((i==j));\n        }\n        ans.PB(v);\n    }\n    long long t = n;\n\n    while(t>0){\n\n        if(t%2==0){\n            matmul(matr,matr,matr);\n            t/=2;\n        }\n        else{\n            matmul(ans,matr,ans);\n            t--;\n        }\n    }\n\n    return ans;\n}\n\nint main()\n{\n    int n;\n    ll k;\n    cin >> n >> k;\n    vector<ll> a1,a2,b;\n    REP(i,n){\n        ll a1r, a2r, br;\n        cin >> a1r >> a2r >> br;\n        a1.PB(a1r);\n        a2.PB(a2r);\n        b.PB(br);\n    }\n    vector<ll> ans;\n    ans.PB(1);\n    a2[SZ(a2)-1] = k;\n    REP(i,n){\n        //update ans size\n        while(SZ(ans) < b[i]+1) ans.PB(0);\n        while(SZ(ans) > b[i]+1) ans.erase(prev(ans.end()));\n        vector<vector<ll> > trans;\n        int len = b[i]+1;\n        REP(pr,len){\n            vector<ll> lol;\n            REP(pro,len){\n                lol.PB(0);\n            }\n            trans.PB(lol);\n        }\n        REP(co,len){\n            if(co>0) trans[co-1][co] = 1;\n            trans[co][co] = 1;\n            if(co+1<len) trans[co+1][co] = 1;\n        }\n        mymul(ans,matexp(trans,a2[i]-a1[i]),ans);\n    }\n    cout << ans[0] << endl;\n}\n",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2100
  },
  {
    "contest_id": "822",
    "index": "A",
    "title": "I'm bored with life",
    "statement": "Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!\n\nLeha came up with a task for himself to relax a little. He chooses two integers $A$ and $B$ and then calculates the greatest common divisor of integers \"$A$ factorial\" and \"$B$ factorial\". Formally the hacker wants to find out GCD$(A!, B!)$. It's well known that the factorial of an integer $x$ is a product of all positive integers less than or equal to $x$. Thus $x! = 1·2·3·...·(x - 1)·x$. For example $4! = 1·2·3·4 = 24$. Recall that GCD$(x, y)$ is the largest positive integer $q$ that divides (without a remainder) both $x$ and $y$.\n\nLeha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?",
    "tutorial": "Tutorial is not available",
    "code": "    int a, b;\n    scanf ( \"%d%d\", &a, &b );\n    int ans = 1;\n    for ( int j = 1; j <= min( a, b ); j++ )\n    \tans *= j;\n    printf ( \"%d\\n\", ans );",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "822",
    "index": "B",
    "title": "Crossword solving",
    "statement": "Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?\n\nLeha has two strings $s$ and $t$. The hacker wants to change the string $s$ at such way, that it can be found in $t$ as a substring. All the changes should be the following: Leha chooses one position in the string $s$ and replaces the symbol in this position with the question mark \"?\". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string $s$=\"ab?b\" as a result, it will appear in $t$=\"aabrbb\" as a substring.\n\nGuaranteed that the length of the string $s$ doesn't exceed the length of the string $t$. Help the hacker to replace in $s$ as few symbols as possible so that the result of the replacements can be found in $t$ as a substring. The symbol \"?\" should be considered equal to any other symbol.",
    "tutorial": "Let's consider all the positions $i$ $(1  \\le  i  \\le  m - n + 1)$ that denotes the begining of the occurrence of the string $s$ in the string $t$. Then let's find out how many symbols we should replace if the begining of the occurrence is position $i$. After the considering of all $m - n + 1$ positions the optimal answer will be found. Total complexity is $O(nm)$.",
    "code": "    const int maxn = 1050;\n\n    vector < int > ans;\n    vector < int > newAns;\n\n    char t1[maxn];\n    char t2[maxn];\n\n    int n, m;\n    scanf ( \"%d%d\\n\", &n, &m );\n    gets( t1 );\n    gets( t2 );\n\n    for ( int j = 0; j < n; j++ )\n    \tans.pb( j );\n\n    for ( int j = 0; j < m - n + 1; j++ ) {\n    \tnewAns.clear();\n    \tfor ( int i = 0; i < n; i++ )\n    \t\tif ( t1[i] != t2[i + j] )\n    \t\t\tnewAns.pb( i );\n    \tif ( newAns.size() < ans.size() )\n    \t\tans = newAns;\n    }\n    int sz = ans.size();\n    printf( \"%d\\n\", sz );\n    for ( int j = 0; j < sz; j++ ) \n    \tprintf( \"%d \", ans[j] + 1 );",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "822",
    "index": "C",
    "title": "Hacker, pack your bags!",
    "statement": "It's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha.\n\nSo the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly $x$ days. You know the majority of people prefer to go somewhere for a vacation, so Leha immediately went to the travel agency. There he found out that $n$ vouchers left. $i$-th voucher is characterized by three integers $l_{i}$, $r_{i}$, $cost_{i}$ — day of departure from Vičkopolis, day of arriving back in Vičkopolis and cost of the voucher correspondingly. The duration of the $i$-th voucher is a value $r_{i} - l_{i} + 1$.\n\nAt the same time Leha wants to split his own vocation into two parts. Besides he wants to spend as little money as possible. Formally Leha wants to choose exactly two vouchers $i$ and $j$ $(i ≠ j)$ so that they don't intersect, sum of their durations is \\textbf{exactly} $x$ and their total cost is as minimal as possible. Two vouchers $i$ and $j$ don't intersect if only at least one of the following conditions is fulfilled: $r_{i} < l_{j}$ or $r_{j} < l_{i}$.\n\nHelp Leha to choose the necessary vouchers!",
    "tutorial": "Let's sort all the vouchers by their left border $l_{i}$. Let's consider the vouchers in this sorted order. Now we want to consider $i$-th one. The duration of the $i$-th voucher is $r_{i} - l_{i} + 1$. Consequentally only the vouchers with the duration $x - r_{i} + l_{i} - 1$ can make a couple with the $i$-th one. At the same time you shouldn't forget that the value of this expression may be negative. You should check it. Besides let's find a couple for the $i$-th voucher among all the vouchers $k$ for which $r_{k} < l_{i}$. To implement this solution let's keep an array $bestCost$. $bestCost[j]$ denotes the minimal cost of the voucher with the duration equal to exactly $j$ on the considering prefix (i.e. we should consider only such vouchers $k$ with $r_{k} < l_{i}$ in $bestCost$). Thus, it's enough to consider vouchers in order of increasing of their left borders and update the array $bestCost$. Total complexity is $O(n\\log n)$.",
    "code": "const int maxn = 200500;\nconst int inf = ( 2e9 ) + 2;\n\nvector < pair < pair < int, int >, pair < int, int > > > queries;\nint bestCost[maxn];\n\nint l[maxn];\nint r[maxn];\nint cost[maxn];\n\nint solution( int n, int needLen ) {\n    queries.clear();\n    for ( int j = 0; j < n; j++ ) {\n        queries.pb( mp( mp( l[j], -1 ), mp( r[j], cost[j] ) ) );\n        queries.pb( mp( mp( r[j], 1 ), mp( l[j], cost[j] ) ) );\n    }\n    for ( int j = 0; j < maxn; j++ )\n        bestCost[j] = inf;\n    ll ans = 2LL * inf;\n    sort( queries.begin(), queries.end() );\n    int sz = queries.size();\n    for ( int j = 0; j < sz; j++ ) {\n        int type = queries[j].f.s;\n        if ( type == -1 ) {\n            int curLen = queries[j].s.f - queries[j].f.f + 1;\n            if ( curLen <= needLen )\n                ans = min( ans, 1LL * queries[j].s.s + 1LL * bestCost[needLen - curLen] );\n        }\n        if ( type == 1 ) {\n            int curLen = queries[j].f.f - queries[j].s.f + 1;\n            bestCost[curLen] = min( bestCost[curLen], queries[j].s.s );\n        }\n    }\n    return ans >= inf ? -1 : ans;\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "822",
    "index": "D",
    "title": "My pretty girl Noora",
    "statement": "In Pavlopolis University where Noora studies it was decided to hold beauty contest \"Miss Pavlopolis University\". Let's describe the process of choosing the most beautiful girl in the university in more detail.\n\nThe contest is held in several stages. Suppose that exactly $n$ girls participate in the competition initially. All the participants are divided into equal groups, $x$ participants in each group. Furthermore the number $x$ is chosen arbitrarily, i. e. on every stage number $x$ can be different. Within each group the jury of the contest compares beauty of the girls in the format \"each with each\". In this way, if group consists of $x$ girls, then $\\textstyle{\\frac{x(x-1)}{2}}$ comparisons occur. Then, from each group, the most beautiful participant is selected. Selected girls enter the next stage of the competition. Thus if $n$ girls were divided into groups, $x$ participants in each group, then exactly $\\frac{\\mathit{n}}{\\mathbb{Z}}$ participants will enter the next stage. The contest continues until there is exactly one girl left who will be \"Miss Pavlopolis University\"\n\nBut for the jury this contest is a very tedious task. They would like to divide the girls into groups in each stage so that the total number of pairwise comparisons of the girls is as few as possible. Let $f(n)$ be the minimal total number of comparisons that should be made to select the most beautiful participant, if we admit $n$ girls to the first stage.\n\nThe organizers of the competition are insane. They give Noora three integers $t$, $l$ and $r$ and ask the poor girl to calculate the value of the following expression: $t^{0}·f(l) + t^{1}·f(l + 1) + ... + t^{r - l}·f(r)$. However, since the value of this expression can be quite large the organizers ask her to calculate it modulo $10^{9} + 7$. If Noora can calculate the value of this expression the organizers promise her to help during the beauty contest. But the poor girl is not strong in mathematics, so she turned for help to Leha and he turned to you.",
    "tutorial": "Suppose we have already calculated $f(2), f(3), ..., f(r)$. Then calculating the value of the expression is easy. Consider process of calculating $f(x)$. Suppose we found optimal answer. Represent this answer as sequence of integers $d_{1}, d_{2}, ..., d_{k}$ - on the first stage we will divide girls into groups of $d_{1}$ participants, on the second stage into groups of $d_{2}$ participants and so on. Let us prove that all $d_{i}$ should be prime. Suppose some $d_{i}$ is a composite number. Then it can be decomposed into two numbers $d_{i} = a \\cdot b$. In addition, let $n$ girls are admitted to the $i$-th stage. Then on current $i$-th stage ${\\frac{n}{d_{i}}}\\cdot{\\frac{d_{i}\\langle d_{i}-1\\rangle}{j}}\\equiv{\\frac{n\\langle d_{i}-1\\rangle}{2}}$ comparisons will occur. But if we divide this stage into two new stages, then number of comparisons is ${\\frac{n\\cdot(a-1)}{2}}+{\\frac{n\\cdot(b-1)}{2\\cdot a}}\\leq{\\frac{n\\cdot(a-1)}{2}}+{\\frac{n\\cdot(b-1)}{2}}\\leq{\\frac{n\\cdot(a-1)}{2}}\\leq{\\frac{n\\cdot(a-1)}{2}}={\\frac{n\\cdot(a-1)}{2}}$. So, we proved that all $d_{i}$ should be prime. Then it's easy to write DP which will be calculated by transition from the state to the states given by dividing current state by prime divisors. For solving this task we can use Eratosthenes sieve. Total complexity is same as complexity of Eratosthenes sieve: $O(r\\log\\log r)$. In addition you can prove the fact that we should split the girls into groups by prime numbers in the order of their increasing. This optimization significantly accelerates the algorithm.",
    "code": "const int maxn = 5000500;\n\nint isPrime[maxn];\nll dp[maxn];\n\nint main()\n{\n    int t, l, r;\n    scanf ( \"%d%d%d\", &t, &l, &r );\n    for ( int j = 2; j < maxn; j++ )\n        isPrime[j] = j;\n    for ( int j = 2; j * j < maxn; j++ )\n        if ( isPrime[j] == j )\n            for ( int i = j * j; i < maxn; i += j )\n                isPrime[i] = min( j, isPrime[i] );\n\n    dp[1] = 0;\n    for ( int j = 2; j < maxn; j++ ) {\n        dp[j] = 1LL * inf * inf;\n        for ( int x = j; x != 1; x /= isPrime[x] )\n            dp[j] = min( dp[j], 1LL * dp[j / isPrime[x]] + 1LL * j * ( isPrime[x] - 1 ) / 2LL );\n    }\n\n    int ans = 0;\n    int cnt = 1;\n    for ( int j = l; j <= r; j++ ) {\n        dp[j] %= base;\n        ans = ( 1LL * ans + 1LL * cnt * dp[j] ) % base;\n        cnt = ( 1LL * cnt * t ) % base;\n    }\n    printf ( \"%d\\n\", ans );\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "822",
    "index": "E",
    "title": "Liar",
    "statement": "The first semester ended. You know, after the end of the first semester the holidays begin. On holidays Noora decided to return to Vičkopolis. As a modest souvenir for Leha, she brought a sausage of length $m$ from Pavlopolis. Everyone knows that any sausage can be represented as a string of lowercase English letters, the length of which is equal to the length of the sausage.\n\nLeha was very pleased with the gift and immediately ate the sausage. But then he realized that it was a quite tactless act, because the sausage was a souvenir! So the hacker immediately went to the butcher shop. Unfortunately, there was only another sausage of length $n$ in the shop. However Leha was not upset and bought this sausage. After coming home, he decided to cut the purchased sausage into several pieces and number the pieces starting from $1$ from left to right. Then he wants to select several pieces and glue them together so that the obtained sausage is equal to the sausage that Noora gave. But the hacker can glue two pieces together only when the number of the left piece is less than the number of the right piece. Besides he knows that if he glues more than $x$ pieces, Noora will notice that he has falsified souvenir sausage and will be very upset. Of course Leha doesn’t want to upset the girl. The hacker asks you to find out whether he is able to cut the sausage he bought, and then glue some of the pieces so that Noora doesn't notice anything.\n\nFormally, you are given two strings $s$ and $t$. The length of the string $s$ is $n$, the length of the string $t$ is $m$. It is required to select several pairwise non-intersecting substrings from $s$, so that their concatenation in the same order as these substrings appear in $s$, is equal to the string $t$. Denote by $f(s, t)$ the minimal number of substrings to be chosen so that their concatenation is equal to the string $t$. If it is impossible to choose such substrings, then $f(s, t) = ∞$. Leha really wants to know whether it’s true that $f(s, t) ≤ x$.",
    "tutorial": "Formally, you were given two strings $s$ and $t$. Also number $x$ was given. You need to determine whether condition $f(s, t)  \\le  x$ is satisfied. $f(s, t)$ is equal to the minimal number of non-intersect substrings of string $s$ which can be concatenated together to get $t$. Substrings should be concatenated in the same order they appear in $s$. Note that for short strings we can use $DP(prefS, prefT) = f(s[1... prefS], t[1... prefT])$. Note that we are not interested in such states in which value of $DP$ is greater than $x$. Also note that we can swap $DP$ value with one parameter to get new DP: $G(prefS, cnt) = prefT$, where $cnt$ - value of old DP, $prefT$ - maximal $prefT$ for which condition is satisfied: $DP(prefS, prefT) = cnt$. $G$ have $|s| \\cdot x$ states. But it's not clear how to make transitions to make total complexity smaller. Note that there is only two transitions: $G(p r e f S,c n t)=p r e f T\\to G(p r e f S+1,c n t)=p r e f T$ $G(p r e f S,c n t)=p r e f T\\to G(p r e f S+l c p,c n t+1)=p r e f T+l c p$ First transition is obviously, because we make prefix longer by one letter, i.e. $s[1... prefS + 1]$ can be split into several parts to get prefix of string $t$, i.e. $t[1... prefT]$. Second transition is not so obviously, but if we take some part from string $s$ to cover string $t$, it's easy to see that it's optimal to take the longest possible part. Length of such longest possible part is $lcp = LongestCommonPrefix(s[prefS + 1... |s|], t[prefT + 1... |t|])$. We can find $lcp$ using suffix array. Total complexity is $O(N\\log N+N x)$, where $N = |s| + |t|$. But solutions with complexity $O(N\\log^{2}N+N x)$ also passed. Also $lcp$ can be found by binary search with hashes. So the total complexity of such solution is $O(N x\\log N)$.",
    "code": "import java.io.*;\nimport java.util.*;\n\npublic class Main implements Runnable {\n    static class InputReader {\n        BufferedReader reader;\n        StringTokenizer tokenizer;\n\n        InputReader(InputStream in) {\n            reader = new BufferedReader(new InputStreamReader(in), 1 << 20);\n            tokenizer = null;\n        }\n\n        String next() {\n            while (tokenizer == null || !tokenizer.hasMoreTokens()) {\n                try {\n                    tokenizer = new StringTokenizer(reader.readLine());\n                } catch (IOException e) {\n                    e.printStackTrace();\n                    throw new RuntimeException(e);\n                }\n            }\n            return tokenizer.nextToken();\n        }\n\n        int nextInt() {\n            return Integer.parseInt(next());\n        }\n\n        long nextLong() {\n            return Long.parseLong(next());\n        }\n\n        double nextDouble() {\n            return Double.parseDouble(next());\n        }\n    }\n\n    static long[] unique(long[] arr) {\n        Arrays.sort(arr);\n        int newLen = 0;\n        for (int i = 0; i < arr.length; i++) {\n            if (i + 1 == arr.length || arr[i] != arr[i + 1]) {\n                arr[newLen++] = arr[i];\n            }\n        }\n        return Arrays.copyOf(arr, newLen);\n    }\n\n    static class SuffixArray {\n         int[][] classes;\n         String s;\n         int maxH;\n         SuffixArray(String s) {\n             this.s = s;\n             maxH = 0;\n             while ((1 << maxH) <= s.length()) maxH++;\n             classes = new int[maxH][];\n             for (int h = 0; h < maxH; h++) {\n                 classes[h] = new int[s.length()];\n             }\n             for (int i = 0; i < s.length(); i++) {\n                 classes[0][i] = s.charAt(i) - 'a';\n             }\n             for (int h = 1; h < maxH; h++) {\n                 long[] values = new long[s.length() - (1 << h) + 1];\n                 int valuesLen = 0;\n                 for (int i = 0; i + (1 << h) <= s.length(); i++) {\n                     int leftPart = classes[h - 1][i];\n                     int rightPart = classes[h - 1][i + (1 << (h - 1))];\n                     long curValue = ((long)leftPart << 30) ^ rightPart;\n                     values[valuesLen++] = curValue;\n                 }\n                 values = unique(values);\n                 for (int i = 0; i + (1 << h) <= s.length(); i++) {\n                     int leftPart = classes[h - 1][i];\n                     int rightPart = classes[h - 1][i + (1 << (h - 1))];\n                     long curValue = ((long)leftPart << 30) ^ rightPart;\n                     classes[h][i] = Arrays.binarySearch(values, curValue);\n                 }\n             }\n         }\n         int getLCP(int i, int j) {\n             int res = 0;\n             for (int h = maxH - 1; h >= 0; h--) {\n                 if (i + (1 << h) <= s.length() && j + (1 << h) <= s.length() && classes[h][i] == classes[h][j]) {\n                     res += (1 << h);\n                     i += (1 << h);\n                     j += (1 << h);\n                 }\n             }\n             return res;\n         }\n    }\n\n    @Override\n    public void run() {\n\n\n        InputReader in = new InputReader(System.in);\n        PrintWriter out = new PrintWriter(System.out);\n\n        int n = in.nextInt();\n        String s = in.next();\n        int m = in.nextInt();\n        String t = in.next();\n\n        int x = in.nextInt();\n\n        int[][] dp = new int[x + 1][n + 1];\n\n        for (int i = 0; i <= x; i++) {\n            for (int j = 0; j <= n; j++) {\n                dp[i][j] = Integer.MIN_VALUE;\n            }\n        }\n\n        String q = s + \"#\" + t;\n\n        SuffixArray sarr = new SuffixArray(q);\n\n        dp[0][0] = 0;\n\n        for (int cnt = 0; cnt <= x; cnt++) {\n            for (int prefS = 0; prefS <= n; prefS++) {\n                if (dp[cnt][prefS] == Integer.MIN_VALUE) continue;\n                //System.err.println(\"cnt = \" + cnt + \", prefS = \" + prefS + \", value = \" + dp[cnt][prefS]);\n                if (prefS + 1 <= n && dp[cnt][prefS + 1] < dp[cnt][prefS]) {\n                    dp[cnt][prefS + 1] = dp[cnt][prefS];\n                }\n                if (cnt + 1 <= x) {\n                    int prefT = dp[cnt][prefS];\n                    int lcp = sarr.getLCP(prefS, prefT + n + 1);\n                    if (dp[cnt + 1][prefS + lcp] < prefT + lcp) {\n                        dp[cnt + 1][prefS + lcp] = prefT + lcp;\n                    }\n                }\n            }\n        }\n\n        boolean ok = false;\n\n        for (int cnt = 0; cnt <= x; cnt++) {\n            if (dp[cnt][n] == m) {\n                ok = true;\n            }\n        }\n\n        out.println(ok ? \"YES\" : \"NO\");\n\n        out.close();\n    }\n\n    public static void main(String[] args) {\n        new Thread(null, new Main(), \"1\", 1L << 28).run();\n    }\n}",
    "tags": [
      "binary search",
      "dp",
      "hashing",
      "string suffix structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "822",
    "index": "F",
    "title": "Madness",
    "statement": "The second semester starts at the University of Pavlopolis. After vacation in Vičkopolis Noora needs to return to Pavlopolis and continue her study.\n\nSometimes (or quite often) there are teachers who do not like you. Incidentally Noora also has one such teacher. His name is Yury Dmitrievich and he teaches graph theory. Yury Dmitrievich doesn't like Noora, so he always gives the girl the most difficult tasks. So it happened this time.\n\nThe teacher gives Noora a tree with $n$ vertices. Vertices are numbered with integers from $1$ to $n$. The length of all the edges of this tree is $1$. Noora chooses a set of simple paths that pairwise don't intersect in edges. However each vertex should belong to at least one of the selected path.\n\nFor each of the selected paths, the following is done:\n\n- We choose \\textbf{exactly} one edge $(u, v)$ that belongs to the path.\n- On the selected edge $(u, v)$ there is a point at some selected distance $x$ from the vertex $u$ and at distance $1 - x$ from vertex $v$. But the distance $x$ chosen by Noora arbitrarily, i. e. it can be different for different edges.\n- One of the vertices $u$ or $v$ is selected. The point will start moving to the selected vertex.\n\nLet us explain how the point moves by example. Suppose that the path consists of two edges $(v_{1}, v_{2})$ and $(v_{2}, v_{3})$, the point initially stands on the edge $(v_{1}, v_{2})$ and begins its movement to the vertex $v_{1}$. Then the point will reach $v_{1}$, then \"turn around\", because the end of the path was reached, further it will move in another direction to vertex $v_{2}$, then to vertex $v_{3}$, then \"turn around\" again, then move to $v_{2}$ and so on. The speed of the points is $1$ edge per second. For example, for $0.5$ second the point moves to the length of the half of an edge.\n\nA stopwatch is placed at each vertex of the tree. The time that the stopwatches indicate at start time is $0$ seconds. Then at the starting moment of time, all points simultaneously start moving from the selected positions to selected directions along the selected paths, and stopwatches are simultaneously started. When one of the points reaches the vertex $v$, the stopwatch at the vertex $v$ is automatically reset, i.e. it starts counting the time from zero.\n\nDenote by $res_{v}$ the maximal time that the stopwatch at the vertex $v$ will show if the point movement continues infinitely. Noora is asked to select paths and points on them so that $res_{1}$ is as minimal as possible. If there are several solutions to do this, it is necessary to minimize $res_{2}$, then $res_{3}$, $res_{4}, ..., res_{n}$.\n\nHelp Noora complete the teacher's task.\n\nFor the better understanding of the statement, see the explanation for the example.",
    "tutorial": "Firstly let's notice the fact that in the optimal answer each of the paths consists of exactly one edge. Let's choose one particular vertex. Let's the degree of this vertex is $deg$. The most optimal answer for this vertex is $\\frac{2}{d e c g}$, because one point make a full loop of the edge in $2$ seconds. Vetrex with the degree $deg$ has exactly $deg$ adjacent edges. Consequentally $deg$ distinct points will visit this vertex. Therefore in the optimal answer we should select all the starting positions and directions in such way that they visit the vertex each $\\frac{2}{d e c g}$ seconds. Let us show that we are able to select starting positions and directions so that the answer for every vertex is the optimal one. Let's put points at the moment of time between $0$ and $2$ instead of putting somewhere on the edge. The moment of time between $0$ and $1$ will correspond to the coordinates from $0$ to $1$ in the direction from the vertex and the moment of time between $1$ and $2$ will correspond to the coordinates from $1$ to $0$ in the direction to the vertex. Let's select a root among the tree vertices. Let's consider a case of the root. If there are $deg$ adjacent edges we can put a point at $0.0$ seconds on the first edge, at $\\frac{2}{d e c g}$ seconds on the second edge, at $2\\cdot{\\frac{2}{d e g}}$ on the third edge, ..., at $(d e g-1)\\cdot{\\frac{2}{d e g}}$ on the edge number $deg$. Run the Depth First Search from the root (or Breadth First Search). Let's consider a case of another vertices. All these vertices will have a particular moment of time for the point in the upper edge. $upEdgeMoment$ denotes this moment. So if the vertex degree is $deg$ then the moments on the lower edges should be equal to $ule{d g E d g e M o m e n t}+{i\\cdot\\frac{2}{d e g}}$ (here if the value exceeds $2$, we calculate it modulo $2$, i.e. $1.2 + 1.3 = 0.5$), where $i$ is the number of lower edge. The lower edges are numbered from $1$ to $deg - 1$. All in all, we are able to put points on every edge so that the answers for each vertex are the optimal one. Total complexity is $O(n)$.",
    "code": "const int maxn = 105;\n\nvector < pair < int, int > > edge[maxn];\nint used[maxn];\nint from[maxn];\nint where[maxn];\nld dist[maxn];\n\nvoid dfs( int v, ld prevTime ) {\n    used[v] = true;\n    int sz = edge[v].size();\n    ld bestTime = 2.0L / sz;\n    ld nextTime = prevTime + bestTime;\n    if ( nextTime >= 2.0L )\n        nextTime -= 2.0L;\n    for ( int j = 0; j < sz; j++ ) {\n        int id = edge[v][j].f;\n        int to = edge[v][j].s;\n        if ( used[to] )\n            continue;\n\n        ld toTime;\n        if ( nextTime <= 1.0L ) {\n            from[id] = to;\n            where[id] = v;\n            dist[id] = 1.0L - nextTime;\n            toTime = nextTime + 1.0L;\n        } else {\n            from[id] = v;\n            where[id] = to;\n            dist[id] = 2.0L - nextTime;\n            toTime = nextTime - 1.0L;\n        }\n\n        dfs( to, toTime );\n\n        nextTime = nextTime + bestTime;\n        if ( nextTime >= 2.0L )\n            nextTime -= 2.0L;\n    }\n}\n\nint main()\n{\n    int n;\n    scanf ( \"%d\", &n );\n    for ( int j = 1; j < n; j++ ) {\n        int u, v;\n        scanf ( \"%d%d\", &u, &v );\n        edge[u].pb( mp( j, v ) );\n        edge[v].pb( mp( j, u ) );\n    }\n    dfs( 1, 0 );\n    printf( \"%d\\n\", n - 1 );\n    for ( int j = 1; j < n; j++ ) {\n        printf( \"%d %d %d %d \", 1, j, from[j], where[j] );\n        cout << fixed << setprecision( 10 ) << dist[j] << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "825",
    "index": "A",
    "title": "Binary Protocol",
    "statement": "Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm:\n\n- Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones).\n- Digits are written one by one in order corresponding to number and separated by single '0' character.\n\nThough Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number.",
    "tutorial": "Let's decode the number digit by digit starting from the leftmost. When you meet '1' in the string, increase the value of the current digit. For '0' print current digit and proceed to the next one. Don't forget to print the last digit when the string is over. Overall complexity: $O(|s|)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "825",
    "index": "B",
    "title": "Five-In-a-Row",
    "statement": "Alice and Bob play 5-in-a-row game. They have a playing field of size $10 × 10$. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts.\n\nIn current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately.\n\nAlice wins if some crosses in the field form line of length \\textbf{not smaller than 5}. This line can be horizontal, vertical and diagonal.",
    "tutorial": "This one is a pure implementation task. Just check every possible line of length 5. If the current one contains 4 crosses and 1 empty cell then the answer is 'YES'.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "825",
    "index": "C",
    "title": "Multi-judge Solving",
    "statement": "Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty $d$ on Decoforces is as hard as the problem with difficulty $d$ on any other judge).\n\nMakes has chosen $n$ problems to solve on Decoforces with difficulties $a_{1}, a_{2}, ..., a_{n}$. He can solve these problems in arbitrary order. Though he can solve problem $i$ with difficulty $a_{i}$ only if he had already solved some problem with difficulty $d\\geq{\\frac{a_{1}}{2}}$ (no matter on what online judge was it).\n\nBefore starting this chosen list of problems, Makes has already solved problems with maximum difficulty $k$.\n\nWith given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list.\n\nFor every positive integer $y$ there exist some problem with difficulty $y$ on at least one judge besides Decoforces.\n\nMakes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.\n\nMakes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.",
    "tutorial": "Obviously sorting the tasks by difficulty will always produce the most optimal order of solving. In that case ability to solve some task $i$ will mean ability to solve any task from $1$ to $i - 1$. Now let's maintain the upper limit of difficulty of problem Makes is able to solve. Right after solving some problem $i$ it will be $2 \\cdot max(k, a_{i})$. Initially it's just $2 \\cdot k$. Transition from $i$ to $i + 1$ will then look like this. If the upper limit it greater or equal to $a_{i + 1}$ then we solve this problem and update the upper limit. Otherwise we will need some problems from other judges. As our goal is to maximize the upper limit, the most optimal task to solve is the hardest possible. So you should solve task with the difficulty of upper limit and update the limit itself. Keep doing it until upper limit becomes grater or equal to $a_{i + 1}$. You will require no more then $\\lceil\\log a_{n}\\rceil$ tasks from the other judges. By algorithm it's easy to see that by solving task with difficulty $d$ we update upper limit with the value $2 \\cdot d$. This function produces such a estimate. Overall complexity: $O(n\\cdot\\log n+\\log\\operatorname*{max}a_{i})$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "825",
    "index": "D",
    "title": "Suitable Replacement",
    "statement": "You are given two strings $s$ and $t$ consisting of small Latin letters, string $s$ can also contain '?' characters.\n\nSuitability of string $s$ is calculated by following metric:\n\nAny two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings $s$, you choose the one with the largest number of \\textbf{non-intersecting} occurrences of string $t$. Suitability is this number of occurrences.\n\nYou should replace all '?' characters with small Latin letters in such a way that the suitability of string $s$ is maximal.",
    "tutorial": "Notice that the order of letters doesn't matter at all, suitability depends only on amount of each letter. Let $f_{i}$ be the possibility that string $t$ will occur in $s$ at least $i$ times after replacing all '?' signs and after some swaps. If $f_{i}$ is true then $f_{i - 1}$ is also true. That leads to binary search over the answer. Let $cntT_{j}$ be the amount of letters $j$ in $t$ and $cntS_{j}$ - the amount of letters $j$ in $s$. $qcnt$ is the number of '?' signs. $f_{i}$ is true if $\\sum_{j=^{\\prime}\\alpha^{\\prime}}^{^{\\prime}z^{\\prime}}(c n t T_{j}\\cdot i-m i n(c n t T_{j}\\cdot i,c n t S_{j}))\\leq q c n t$. If some letter appears in $s$ less times than needed then replace some '?' signs with it. Answer can be restored greedily by replacing '?' signs with the letters needed. Overall complexity: $O(n+A L\\cdot\\log{n})$, where $AL$ is the size of the alphabet.",
    "tags": [
      "binary search",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "825",
    "index": "E",
    "title": "Minimal Labels",
    "statement": "You are given a directed acyclic graph with $n$ vertices and $m$ edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.\n\nYou should assign labels to all vertices in such a way that:\n\n- Labels form a valid permutation of length $n$ — an integer sequence such that each integer from $1$ to $n$ appears exactly once in it.\n- If there exists an edge from vertex $v$ to vertex $u$ then $label_{v}$ should be smaller than $label_{u}$.\n- Permutation should be lexicographically smallest among all suitable.\n\nFind such sequence of labels to satisfy all the conditions.",
    "tutorial": "This problem is usually called \"Topological labelling\". Though it's pretty common problem, we decided that it might be educational to some of participants. Let's set labels in descending order starting from label $N$ to label $1$. Look at first step. Vertex with label $N$ should have out-degree equal to zero. Among all such vertices we should put the label on the one that has the largest index. Ok, but why will this produce the lexicographically smallest labelling? We can prove this by contradiction. Let this vertex be labeled $X$ ($X < N$). Change it to $N$ and renumerate vertices with label $X + 1, ..., N$ to labels $X, ..., N - 1$. Labelling will come lexicographically smaller than it was, this leads to contradiction. So the algorithm comes as following. On step $i$ ($i = N... 1$) we find vertices with out-degree equal to zero, select the one with the largest index, set its label to $i$ and remove this vertex (and all edges connected to it) from the graph. Current minimal out-degree can be maintained with set, for example. Overall complexity: $O((n+m)\\cdot\\log{n})$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "825",
    "index": "F",
    "title": "String Compression",
    "statement": "Ivan wants to write a letter to his friend. The letter is a string $s$ consisting of lowercase Latin letters.\n\nUnfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string $s$ instead of the string itself.\n\nThe compressed version of string $s$ is a sequence of strings $c_{1}, s_{1}, c_{2}, s_{2}, ..., c_{k}, s_{k}$, where $c_{i}$ is the decimal representation of number $a_{i}$ (without any leading zeroes) and $s_{i}$ is some string consisting of lowercase Latin letters. If Ivan writes string $s_{1}$ exactly $a_{1}$ times, then string $s_{2}$ exactly $a_{2}$ times, and so on, the result will be string $s$.\n\nThe length of a compressed version is $|c_{1}| + |s_{1}| + |c_{2}| + |s_{2}|... |c_{k}| + |s_{k}|$. Among all compressed versions Ivan wants to choose a version such that its length is minimum possible. Help Ivan to determine minimum possible length.",
    "tutorial": "Let $dp[i]$ be the answer for the prefix of $s$ consisting of $i$ first characters. How can we update $dp[j]$ from $dp[i]$ ($i < j$)? Suppose that we try to represent the substring from index $i$ to index $j - 1$ ($0$-indexed) by writing it as some other string $k$ times. Then this string has to be the smallest period of the substring, and $k={\\frac{j-i}{T}}$, where $T$ is the length of the smallest period. The smallest period of some string $t$ can be calculated as follows: compute prefix-function for $t$, and if $|t|$ is divisible by $|t| - p_{last}$ ($p_{last}$ is the last value of prefix-function), then the length of the smallest period is $|t| - p_{last}$ (if not, then the length of the smallest period is $|t|$). This allows us to write a solution with complexity $O(|s|^{3})$. To improve it to $O(|s|^{2})$, we can use the fact that when we compute prefix-function for some string, we compute it for every prefix of this string. So to obtain all values of $p_{last}$ we need in our solution, we only need to compute prefix-functions for every suffix of $s$.",
    "tags": [
      "dp",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "825",
    "index": "G",
    "title": "Tree Queries",
    "statement": "You are given a tree consisting of $n$ vertices (numbered from $1$ to $n$). Initially all vertices are white. You have to process $q$ queries of two different types:\n\n- $1$ $x$ — change the color of vertex $x$ to black. It is guaranteed that the first query will be of this type.\n- $2$ $x$ — for the vertex $x$, find the minimum index $y$ such that the vertex with index $y$ belongs to the simple path from $x$ to some black vertex (a simple path never visits any vertex more than once).\n\nFor each query of type $2$ print the answer to it.\n\n\\textbf{Note that the queries are given in modified way}.",
    "tutorial": "After the first query make the vertex that we painted black the root of the tree and for each other vertex calculate the minimum index on the path to the root. This can be done by simple DFS. Then suppose we are painting some vertex $x$ black. In can easily proved that for every vertex $y$ and every vertex $z$ that is on a path form $x$ to the root there exists a path from $y$ to some black vertex coming through $z$. So we have to store the minimum index among all vertices $z$ such that $z$ belongs to the path from the root to some black vertex (it is a global value, let's call it $globalMin$), and the answer to every query of type $2$ is just the minimum of the value we calculated in DFS and $globalMin$. To update $globalMin$ quickly after painting vertex $x$ black, we ascend from $x$ to the root until we arrive to some node that was visited during previous queries (and we stop there because this node and all nodes on the path from it to the root were used to update $globalMin$ in previous queries). This solution works in $O(n)$ time.",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "827",
    "index": "A",
    "title": "String Reconstruction",
    "statement": "Ivan had string $s$ consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string $s$. Ivan preferred making a new string to finding the old one.\n\nIvan knows some information about the string $s$. Namely, he remembers, that string $t_{i}$ occurs in string $s$ at least $k_{i}$ times or more, he also remembers exactly $k_{i}$ positions where the string $t_{i}$ occurs in string $s$: these positions are $x_{i, 1}, x_{i, 2}, ..., x_{i, ki}$. He remembers $n$ such strings $t_{i}$.\n\nYou are to reconstruct \\textbf{lexicographically minimal} string $s$ such that it fits all the information Ivan remembers. Strings $t_{i}$ and string $s$ consist of small English letters only.",
    "tutorial": "At first let's sort all given string by their positions and also determine the length of the answer string. After that fill the answer string with letters \"a\" because the answer string must be lexicographically minimal. Let's use variable $prev$ - the minimal index of letter in the answer string which did not already processed. After that we need to iterate through the sorted strings. If the next string ends before $prev$ we skip it. In the other case, we need to impose this string to the answer string beginning from necessary position and write down all letters beginning from $prev$ or from the beginning of impose (depending on which of these values is greater). If the imposing of string ends in position $endPos$ we need to make $prev = endPos + 1$ and move to the next string.",
    "tags": [
      "data structures",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "827",
    "index": "B",
    "title": "High Load",
    "statement": "Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of $n$ nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly $k$ of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.\n\nArkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.\n\nHelp Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.",
    "tutorial": "Hint: one of the optimal solutions is a star-like tree: one \"center\" node with $k$ paths with lengths difference at most one. Proof: let the optimal answer be something different from the structure described. If it is a star with $k$ paths, but the lengths differ by more than one, we can shorten the longest one and lengthen the shortest one, and the answer won't become greater. So, doing this operation once or more, we eventually get the described structure, that means that our answer is optimal. If the optimal answer is not a star, let's hang it on one of its centers, and let the diameter be $d$. Then the depths of all leaves are not greater than $\\textstyle{\\left[{\\frac{d}{2}}\\right]}$. Suppose there is some edge $e$ from the root that has more than one leaf in its subtree. Let $v$ be some leaf in this subtree, and its depth be $y$. Let's take the path from leaf $v$ all the way up to some vertex with degree more than $2$, and rehang this path to the root. The tree is now more star-like, and we are going to prove that the answer didn't become larger. Obviously, we're only interested in distances between $v$ and other leaves. Moreover, we can see that the current depth of $v$ is smaller than $y$, and the distance between $v$ and other leaves doesn't exceed $y-1+\\left[{\\frac{d}{2}}\\right]\\leq2\\left[{\\frac{d}{2}}\\right]-1\\leq d$. It is proved now.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "827",
    "index": "C",
    "title": "DNA Evolution",
    "statement": "Everyone knows that DNA strands consist of nucleotides. There are four types of nucleotides: \"A\", \"T\", \"G\", \"C\". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string $s$ initially.\n\nEvolution of the species is described as a sequence of changes in the DNA. Every change is a change of some nucleotide, for example, the following change can happen in DNA strand \"AAGC\": the second nucleotide can change to \"T\" so that the resulting DNA strand is \"ATGC\".\n\nScientists know that some segments of the DNA strand can be affected by some unknown infections. They can represent an infection as a sequence of nucleotides. Scientists are interested if there are any changes caused by some infections. Thus they sometimes want to know the value of impact of some infection to some segment of the DNA. This value is computed as follows:\n\n- Let the infection be represented as a string $e$, and let scientists be interested in DNA strand segment starting from position $l$ to position $r$, inclusive.\n- Prefix of the string $eee...$ (i.e. the string that consists of infinitely many repeats of string $e$) is written under the string $s$ from position $l$ to position $r$, inclusive.\n- The value of impact is the number of positions where letter of string $s$ coincided with the letter written under it.\n\nBeing a developer, Innokenty is interested in bioinformatics also, so the scientists asked him for help. Innokenty is busy preparing VK Cup, so he decided to delegate the problem to the competitors. Help the scientists!",
    "tutorial": "Note that there are only $4$ different characters and queries' lengths are only up to $10$. How does this help? Let's make $4$ arrays of length $|s|$ for each of the possible letters, putting $1$ where the letter in $s$ is that letter, and $0$ otherwise. We can update these arrays easily with update queries. Consider a letter in a query string $e$. It appears equidistantly in the string we write down under the string $s$. Thus, we should count the number of ones (in one of our four arrays) at positions which indices form an arithmetic progression, and bounded by some segment (the query segment $[l, r]$). This sounds hard, but we can note that the difference between the indices (i.e. the common difference of the arithmetic progression) is not larger than $10$. Thus, we can store $10$ copies of each of four arrays we created above. For the $x$-th copy of some letter, we reorder the elements so that first we put all positions $p$ for which $p\\bmod x\\equiv0$, then all positions $p$ for which $p\\bmod x\\equiv1$, and so on. This will make possible to change each query on an arithmetic progression to a sum query on a segment. Thus, we can just sum up answers for each letter in string $e$.",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "827",
    "index": "D",
    "title": "Best Edge Weight",
    "statement": "You are given a connected weighted graph with $n$ vertices and $m$ edges. The graph doesn't contain loops nor multiple edges. Consider some edge with id $i$. Let's determine for this edge the maximum integer weight we can give to it so that it is contained in all minimum spanning trees of the graph if we don't change the other weights.\n\nYou are to determine this maximum weight described above for each edge. You should calculate the answer for each edge independently, it means there can't be two edges with changed weights at the same time.",
    "tutorial": "Hint 1: Find some MST in the initial graph and name it $M$. Now there are edges of two types: in the tree, and not in the tree. Process them in a different way. Hint 2: For edges not in the MST, the answer is the maximum weight of MST edges on the path between the edge's ends, minus one. Proof: Consider the edge $E$ such that it doesn't appear in our MST and its weight is $W$ and consider the maximum weight of MST edges on the path between the edge's ends is $MX$. It's obvious that if $W  \\ge  MX$ there is an MST such that $E$ will not appear in that (at least it will not appear in $M$). Now let's prove that if $W = MX - 1$ it will appear in any MST. Consider an MST like $OM$ that $E$ does not appear in that, let's prove $M$ was not an MST and it's a contradiction. Let ends of $E$ be $v, u$. Look, consider the path between $v, u$ in $M$, there is an edge with weight $MX$ in this path but there isn't any edge in $OM$ with weight greater than or equal to $MX$. So $M$ is not an MST because when we build an MST we sort edges by their weight and add them greedily (Kruskal's algorithm). Hint 3: For an edge $E$ in the MST, let non-MST edges such that MST path between their ends go through $E$ be bad edges, the answer is the minimum weight of bad edges, minus one. Proof: Let the minimum weight of bad edges be $CW$ and weight of $E$ be $W$. It is obvious that if $W  \\ge  CW$ there is an MST such that $E$ will not appear in that. Now if $W < CW$ so we will check $E$ before bad edges and we will add it. The remaining part is easy: for non-MST edges, one can just query the maximum on a tree path with binary lifts or whatever other structure on a tree. For MST edges, we can do the same, but in the other direction, like range queries, or even easier with centroid decomposition, HLD or using sets and the smaller-to-larger optimization. Thanks Arpa for the proofs!",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "827",
    "index": "E",
    "title": "Rusty String",
    "statement": "Grigory loves strings. Recently he found a metal strip on a loft. The strip had length $n$ and consisted of letters \"V\" and \"K\". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written.\n\nGrigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter \"V\" or \"K\" on each unreadable position, which values can the period of the resulting string be equal to?\n\nA period of a string is such an integer $d$ from $1$ to the length of the string that if we put the string shifted by $d$ positions to the right on itself, then all overlapping letters coincide. For example, $3$ and $5$ are periods of \"VKKVK\".",
    "tutorial": "Let $s_{i}$ is symbol number $i$ from the given string. Statement: $k$ can be period of string $s$ when if and only if there are no two indices $i$ and $j$ for which $s_{i}\\neq s_{j},s_{i}\\neq?\\gamma,s_{j}\\neq7,t{\\mathrm{~}}\\mathrm{~}\\mathrm{mod}\\;k=j\\mathrm{~mod}\\;k$. Evidence: Necessity: Let it is not true. Then for any letter fill of omissions such paint $i$ and $j$ will left that $s_{i}  \\neq  s_{j}, s_{i}  \\neq  ?, s_{j}  \\neq  ?$ and this contradicts the definition of the period. Adequacy: Let fill omissions with constructive algorithm in a way that string after that is having a period $k$. Let's look on some remainder of division on $k$. There are two options. In the first option there are no such $i$ that $i$ gives needed remainder by divide on $k$ and $s_{i}  \\neq  ?$. Then let fill all positions with such remainder with symbol \"V\". In the second option there are $i$ such that $i$ gives this remainder by division on $k$ and $s_{i}  \\neq  ?$. Let fill all positions with this remainder symbol $s_{i}$. Now in all positions with equal remainder by division on $k$ in string stand equal symbols and it means that string has period $k$. Let's call a pair indices $i$ and $j$ contradictory, if $s_{i}  \\neq  s_{j}, s_{i}  \\neq  ?$ and $s_{j}  \\neq  ?$, then the string has period $k$ if and only if there are no contradictory pair $i$ and $j$ for which $|i - j|$ is divisible by $k$. This is a direct consequence of the statement proved above. Let's learn how to search for all such numbers $x$ that there is contradictory pair $i$ and $j$ that $i - j = x$. Let $A$ - the set of positions, where stand \"V\", and $B$ - the set of such positions $i$ that $s_{n - i} = K$. So our task reduced to finding such all possible numbers that it is representable as the sum of a number from $A$ and a number from $B$. Let's look on polynomials $P(x) = a_{1}x^{1} + a_{2}x^{2} + ..., Q(x) = b_{1}x^{1} + b_{2}x^{2} + ...$, where $a_{i}$ equals to $1$, if $i$ can be found in $A$ or $0$, otherwise. Similarly for set $B$ and $b_{i}$. Let's look on $P(x) * Q(x)$. Coefficient at $x^{i}$ is equal to $1$ if and only if when $i$ can be represented in sum of a number from $A$ and a number from $B$. It is correct because coefficient at $x^{i}$ equals to $\\sum_{j=0}^{i}a_{j}b_{i-j}$. But $a_{j}b_{i - j}  \\ge  0$ and equals to $1$ if and only if when $a_{j} = 1$ and $b_{i - j} = 1$, and it means that $j\\in A,(i-j)\\in B$, but $j + (i - j) = i$. Polynomials can be multiplied with help of Fast Fourier transform, so this part of solution works in $O(nlogn)$. It is only left to learn how to check that $k$ is a period of string. It can be done in $O({\\frac{n}{k}})$, with check all numbers like $ik  \\le  n$. Totally it works in $\\sum_{i=1}^{n}O(\\frac{n}{k})=O(n l o g n)$. So, all solution works in $O(nlogn)$.",
    "tags": [
      "fft",
      "math",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "827",
    "index": "F",
    "title": "Dirty Arkady's Kitchen",
    "statement": "Arkady likes to walk around his kitchen. His labyrinthine kitchen consists of several important places connected with passages. Unfortunately it happens that these passages are flooded with milk so that it's impossible to pass through them. Namely, it's possible to pass through each passage in any direction only during some time interval.\n\nThe lengths of all passages are equal and Arkady makes through them in one second. For security reasons, Arkady can never stop, also, he can't change direction while going through a passage. In other words, if he starts walking in some passage, he should reach its end and immediately leave the end.\n\nToday Arkady needs to quickly reach important place $n$ from place $1$. He plans to exit the place $1$ at time moment $0$ and reach the place $n$ as early as he can. Please find the minimum time he should spend on his way.",
    "tutorial": "Let's consider undirected edge$(u;v)$ as two directed edges $(u;v)$ and $(v;u)$. Let Arkady came to the vertex $u$ in moment of time $t$. Then he can come to $v$ in moments of time $t + 1, t + 3, ...$ until the edge is existing. We will expand each directed edge: on one of them we can come in even moments of time and leave in odd; on the other edge we can come in odd moments of time and leave in even. So, each of the edges from initial graph has turned in 4 edges of the new graph. Let's calculate for each edge $dp_{i}$ - the minimal moment of time when we can come on the edge $i$. Let's count this values with help of sorting of events like \"edge appeared\". For each vertex and parity we will remember the edge for which we can appear in this vertex in moments of time with such a parity which will disappear later than others. When the event of appearing edge became we need to check if it is possible in this moment of time come to the beginning of this edge. If it is possible then $dp_{i} = l_{i}$, where $l_{i}$ - the minimal moment of time when it is possible to come to the beginning of the edge to go through this edge. Every time when some vertex became reachable with needed parity we say that value of $dp$ is equals to this time for all edges which wait in this vertex this parity. Totally each edge will processed no more than two times, so totally solution works in $O(nlogn)$.",
    "tags": [
      "data structures",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 3200
  },
  {
    "contest_id": "828",
    "index": "A",
    "title": "Restaurant Tables",
    "statement": "In a small restaurant there are $a$ tables for one person and $b$ tables for two persons.\n\nIt it known that $n$ groups of people come today, each consisting of one or two people.\n\nIf a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group.\n\nIf a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.\n\nYou are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.",
    "tutorial": "We need to store three values: $a$ - the number of free tables for one person, $b$ - the number of free tables for two persons and $c$ - the number of tables for two persons occupied by single person. If the next group consisting of $2$ persons and there are no free tables for two persons (i. e. $b = = 0$) the restaurant denies service to this group and we need to add $2$ to the answer. In the other case, we need subtract one from $b$ and move to the next group. If the next group consisting of $1$ person and there is free table for one person (i. e. $a > 0$) we need to subtract one from $a$ and move to the next group. In the other case, if there is free table for two persons you need to put person for this table, subtract one from $b$ and add one to $c$. If there are no free tables but $c > 0$ we need to subtract one form $c$. If no one from the described conditions did not met the restaurant denies service to this group consisting of one person and we need to add one to the answer and move to the next group.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "828",
    "index": "B",
    "title": "Black Square",
    "statement": "Polycarp has a checkered sheet of paper of size $n × m$. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's \"Black Square\", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.\n\nYou are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.",
    "tutorial": "If there are no black cells on the field it is enough to paint any one cell. In the other case, we need to calculate $4$ values: $minX$ - the index of upper row with black cell; $maxX$ - the index of bottom row with black cell; $minY$ - the index of leftmost column with black cell; $maxY$ - the index of rightmost column with black cell. After that we can get the length of square side which should be obtained after repainting. Let this side equals to $len$ and $len = max(maxX - minX + 1, maxY - minY + 1)$. If $len$ more than $n$ or $len$ more than $m$ there is no solution. Else, the answer is equals to $len \\cdot len - cnt$, where $len \\cdot len$ is the number of cells in the resulting square and $cnt$ is the number of black cells on the initial field. The value $cnt$ can be calculated in one iteration through the given field.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "830",
    "index": "A",
    "title": "Office Keys",
    "statement": "There are $n$ people and $k$ keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.\n\nYou are to determine the minimum time needed for all $n$ people to get to the office with keys. Assume that people move a unit distance per $1$ second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.",
    "tutorial": "To solve this problem you need to understand the fact that all keys which people will take is continuous sequence of length $n$ in sorted array of keys. At first let's sort all keys in increasing order of their positions. Then brute which of the keys will take a leftmost person. Let it will be $i$-th key. Then the second person from the left will take the key $i + 1$, third - $(i + 2)$ and etc. So, we can determine the time after which all people can reach the office with keys if the sequence of keys beginning from $i$-th key. Now we need to update the answer with this value and move to the next position $i + 1$.",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "830",
    "index": "B",
    "title": "Cards Sorting",
    "statement": "Vasily has a deck of cards consisting of $n$ cards. There is an integer on each of the cards, this integer is between $1$ and $100 000$, inclusive. It is possible that some cards have the same integers on them.\n\nVasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.\n\nYou are to determine the total number of times Vasily takes the top card from the deck.",
    "tutorial": "First note that operation \"put a card under the deck\" is the same as \"stark viewing from the beginning when you reach the end\", and do not move cards anywhere. Then, let's proceed all cards with equal numbers on them at once. It's obvious that Vasily puts them away one after another. Let's denote the position where he was when he put the last card less than $x$ be position $p$ in the deck. Two cases are possible. If all cards equal to $x$ are after position $p$, then he looks all the cards until he takes the last card with $x$, and puts away all cards equal to $x$; Otherwise there is a card with $x$ that is before $p$. In this case Valisy looks at all cards from $p$ to the end, and after that - at all cards from the beginning of the deck to the last card with $x$ that is before $p$. It's easy to process both cases if we keep for each $x$ positions of all cards with $x$ from the top to the bottom of the deck. Aside of this we need any data structure that is capable of computing sum on a segment and changing a single value (we can store $1$ for a position with a card in the deck, and $0$ is the card is already put away). We can use segment tree or Fenwick tree for example.",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "830",
    "index": "C",
    "title": "Bamboo Partition",
    "statement": "Vladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are $n$ bamboos in a row, and the $i$-th from the left is $a_{i}$ meters high.\n\nVladimir has just planted $n$ bamboos in a row, each of which has height $0$ meters right now, but they grow $1$ meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.\n\nVladimir wants to check the bamboos each $d$ days (i.e. $d$ days after he planted, then after $2d$ days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than $k$ meters.\n\nWhat is the maximum value $d$ he can choose so that he can achieve what he wants without cutting off more than $k$ meters of bamboo?",
    "tutorial": "First fact: The problem is asking to maximize $d$ such that: $\\textstyle\\sum_{i=1}^{n}(d\\lceil{\\frac{a_{i}}{d}}\\rceil-a_{i})\\leq k$. $\\textstyle{\\sum_{i=1}^{n}(d\\left[{\\frac{a_{i}}{d}}\\right]-a_{i})\\leq k\\Rightarrow d\\sum_{i=1}^{n}\\left[{\\frac{a_{i}}{d}}\\right]\\leq k+\\sum_{i=1}^{n}a_{i}}$. Let $C=k+\\textstyle\\sum_{i=1}^{n}a_{i}$, then $d\\sum_{i=1}^{n}\\left[{\\frac{a_{i}}{d}}\\right]\\leq C$. Second fact: Number of possible values for $\\left[{\\frac{a}{b}}\\right]$ is $O({\\sqrt{a}})$. For $x$, let $A=\\lfloor{\\sqrt{x}}\\rfloor$ these values are $1... A$ and $\\left[{\\begin{array}{l}{x}\\\\ {1}\\end{array}}\\right]\\cdot\\cdot\\cdot\\left[{\\frac{x}{A}}\\right]$. So there is at most $O(n\\cdot{\\sqrt{m a x_{i=1}^{n}a_{i}}})$ segments for $d$ such that $\\textstyle\\sum_{i=1}^{n}\\left|{\\frac{a_{i}}{d}}\\right|$ will not change. Now generate all possible values and sort them, and for each segment check if there is a $d$ in that segment satisfying the condition and update the answer. My solution. Thanks Arpa for this editorial!",
    "code": "// God & me\n// Fly ...\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int maxn = 1e2 + 17, maxsq = sqrt(1e9);\nconst ll inf = 1e12;\n \nint n, a[maxn], sz;\nll C, seg[maxn * 2 * maxsq];\nint ceil(int n, int r){\n\treturn (n + r - 1) / r;\n}\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcin >> n >> C;\n\tseg[sz++] = 1;\n\tfor(int i = 0; i < n; i++){\n\t\tcin >> a[i];\n\t\tfor(int j = 1; j * j <= a[i]; j++)\n\t\t\tseg[sz++] = j, seg[sz++] = ceil(a[i], j);\n\t\tC += a[i];\n\t}\n\tseg[sz++] = inf;\n\tsort(seg, seg + sz);\n\tsz = unique(seg, seg + sz) - seg;\n\tll ans = 0;\n\tfor(int i = 0; i < sz - 1; i++){\n\t\tint l = seg[i], r = seg[i + 1];\n\t\tll cur = 0;\n\t\tfor(int j = 0; j < n; j++)\n\t\t\tcur += ceil(a[j], l);\n\t\tll d = C / cur;\n\t\tif(l <= d && ans < d)\n\t\t\tans = d;\n\t}\n\tcout << ans << '\\n';\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "math",
      "number theory",
      "sortings",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "830",
    "index": "D",
    "title": "Singer House",
    "statement": "It is known that passages in Singer house are complex and intertwined. Let's define a Singer $k$-house as a graph built by the following process: take complete binary tree of height $k$ and add edges from each vertex to all its successors, if they are not yet present.\n\n\\begin{center}\n{\\small Singer $4$-house}\n\\end{center}\n\nCount the number of non-empty paths in Singer $k$-house which do not pass the same vertex twice. Two paths are distinct if the sets or the orders of visited vertices are different. Since the answer can be large, output it modulo $10^{9} + 7$.",
    "tutorial": "Hint: Compute dp[k][c] \"what is the number of sets of $c$ non-intersecting paths in $k$-house?\" Yes, it works. The answer is dp[k][1]. $dp_{1, 0} = dp_{1, 1} = 1$. For updating $dp_{i}$ from $dp_{i - 1}$ for each $L, R(1  \\le  L, R  \\le  2^{i - 1})$ Let $X = dp_{i - 1, L} \\cdot dp_{i - 1, R}$: Take the root, and make itself a new path $\\longrightarrow\\bigcup$ $dp_{i, L + R + 1} + = X$. Don't take the root $\\longrightarrow\\bigcup$ $dp_{i, L + R} + = X$. Take the root, and connect it to a path in the left child $\\longrightarrow$ $dp_{i, L + R} + = X \\cdot L \\cdot 2$. Take the root, and connect it to a path in the right child $\\longrightarrow\\bigcup$ $dp_{i, L + R} + = X \\cdot R \\cdot 2$. Take the root, and it combines two paths $\\longrightarrow\\bigcup$ $dp_{i, L + R - 1} + = X \\cdot C(L + R, 2) \\cdot 2$. Now the important fact is because we need $dp_{k, 1}$ we only need first $k$ values of $dp_{i}$. So the complexity is $O(k^{3})$. Thanks Arpa for this editorial!",
    "tags": [
      "combinatorics",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "830",
    "index": "E",
    "title": "Perpetual Motion Machine",
    "statement": "Developer Petr thinks that he invented a perpetual motion machine. Namely, he has a lot of elements, which work in the following way.\n\nEach element has one controller that can be set to any non-negative real value. If a controller is set on some value $x$, then the controller consumes $x^{2}$ energy units per second. At the same time, any two elements connected by a wire produce $y·z$ energy units per second, where $y$ and $z$ are the values set on their controllers.\n\nPetr has only a limited number of wires, so he has already built some scheme of elements and wires, and is now interested if it's possible to set the controllers in such a way that the system produces \\textbf{at least as much} power as it consumes, and at least one controller is set on the value different from $0$. Help him check this, and if it's possible, find the required \\textbf{integer} values that should be set.\n\nIt is guaranteed that if there exist controllers' settings satisfying the above conditions, then there exist required integer values not greater than $10^{6}$.",
    "tutorial": "By default, all vertices contain $0$. We will solve problem in few steps, getting answer for our question in different cases. Graph contains cycle. In this case, solution exists, all vertices of cycle contain $1$, sum would be $0$. Graph contains vertex with degree more than $3$. Solution exists, this vertex has $2$ and its neighbours $1$. Sum will be $2^{2} + deg(v) - 2 * deg(v)  \\le  0$ when $deg(v)  \\ge  4$. Graph contains more than one vertex of degree $3$. In this case we can reduce to previous case: we put $2$ in the between these vertices and ones in other neighboors. Doing this, we \"contract\" path between vertices to one with the number $2$ and obtain vertex of degree $4$. Graph contains just one vertex of degree $3$. It is the most complicated point in our solution. We just state this and prove it later.Statement: There is only one vertex with degree $3$, with 'tails' of sizes $p - 1$, $q - 1$ and $r - 1$ (length of the tail = how many vertices lay on it). In this case expression can take only non-positive values if $\\textstyle{\\frac{1}{p}}+{\\frac{1}{q}}+{\\frac{1}{r}}\\leq1$. Statement: There is only one vertex with degree $3$, with 'tails' of sizes $p - 1$, $q - 1$ and $r - 1$ (length of the tail = how many vertices lay on it). In this case expression can take only non-positive values if $\\textstyle{\\frac{1}{p}}+{\\frac{1}{q}}+{\\frac{1}{r}}\\leq1$. All graph's vertices have degree less than $3$. This case can be easily reduced to previous one, having $p = 1$. We are going to prove this by two ways. First way: Let's look on tail, sized $k$, having form of the bamboo. Numbers in vertices are $a_{i}$ and have sum $A$. We are going to minimize $A$. As one can see, $2A = 2a_{1}^{2} - 2a_{1}a_{2} + 2a_{2}^{2} - 2a_{2}a_{3} + ... - 2a_{k - 1}a_{k} + 2a_{k}^{2} = a_{1}^{2} + (a_{2} - a_{1})^{2} + (a_{3} - a_{2})^{2} + ... + (a_{k} - a_{k - 1}^{2}) + a_{k}^{2}$ Let $a_{k} = S$, $d_{1} = a_{1}$, $d_{2} = a_{2} - a_{1}$, $d_{3} = a_{3} - a_{2}$, ..., $d_{k} = a_{k} - a_{k - 1}$. Then $2A = d_{1}^{2} + d_{2}^{2} + ... + d_{k}^{2} + S^{2}$ While $\\sum_{i=1}^{k}d_{i}=a_{1}+\\sum_{i=2}^{k}a_{i}-a_{i-1}=a_{k}=S$ We will use induction for proof. Base ($n = 1$) is evident. Step $n  \\rightarrow  n + 1$: $f(x)={\\frac{(S-x)^{2}}{n}}+x^{2}$ - optimal sum of squares if one of $n + 1$ numbers is $x$. We shall minmize this function. This is nearly equal to derivative being zero. $-2^{\\underline{{{S}}}-x}+2x=0\\Rightarrow S-(n+1)x=0\\Rightarrow x={\\frac{S}{n+1}}$, what we wanted to prove. Now we get back to construction where are three tails of sizes $p$, $q$ and $r$ are connected to 3-degree vertex. Number in 3-degree vertex is $S$, value of the whole graph is $D$, and values of tails are $A$, $B$ and $C$. $(2A - S^{2}) + (2B - S^{2}) + (2C - S^{2}) = 2D + S^{2}$. If we fix $S$, when, as it was shown before optimal values of tails are i$2A-S^{2}={\\frac{s^{2}}{p}}$, $2B-S^{2}={\\frac{S^{2}}{q}}$, $2C-S^{2}={\\frac{S^{2}}{r}}$. We have $(\\textstyle{\\frac{1}{p}}+\\textstyle{\\frac{1}{q}}+{\\frac{1}{r}}-1)S^{2}=2D$. It means that $D  \\le  0$ can be only if $\\textstyle{\\frac{1}{p}}+{\\frac{1}{q}}+{\\frac{1}{r}}\\leq1$. Second way: Let the tail of size $p$ have numbers in vertices $x_{1}, x_{2}, ... x_{p - 1}$ counting from the leaf, size $q$ - $y_{1}, y_{2}, ... y_{q - 1}$, size $r$ - $z_{1}, z_{2}, ... z_{r - 1}$. Root we will define as $v = x_{p} = y_{q} = z_{r}$. Let $A_{x} = x_{1}^{2} + x_{2}^{2} + ... + x_{p - 1}^{2} - x_{1x}_{2} - ... - x_{p - 2}x_{p - 1} - x_{p - 1}v,$ $A_{y} = y_{1}^{2} + y_{2}^{2} + ... + y_{q - 1}^{2} - y_{1y}_{2} - ... - y_{q - 2}y_{q - 1} - y_{q - 1}v,$ $A_{z} = z_{1}^{2} + z_{2}^{2} + ... + z_{r - 1}^{2} - z_{1z}_{2} - ... - z_{r - 2}z_{r - 1} - z_{r - 1}v.$ We want to compute $S = v^{2} + A_{x} + A_{y} + A_{z}$. One can see that $2A_{x}=\\sum_{i=1}^{p-1}\\frac{i+1}{i}(x_{i}-\\frac{i}{i+1}x_{i+1})^{2}-\\frac{p-1}{p}v^{2}=F(x)-\\frac{p-1}{p}v^{2},$ $2A_{y}=\\sum_{i=1}^{q-1}\\frac{i+1}{i}(y_{i}-\\frac{i}{i+1}y_{i+1})^{2}-\\frac{q-1}{q}v^{2}=F(y)-\\frac{q-1}{q}v^{2},$ $2A_{z}=\\sum_{i=1}^{r-1}\\frac{i+1}{i}(z_{i}-\\frac{i}{i+1}z_{i+1})^{2}-\\frac{r-1}{r}v^{2}=F(z)-\\frac{r-1}{r}v^{2}.$ Actually, if we calculate this expression, we will have $2A_{x}=2x_{1}^{2}-2x_{1}x_{2}+{\\frac{1}{2}}x_{2}^{2}+{\\frac{3}{2}}x_{3}^{2}-2x_{2}x_{3}+{\\frac{2}{3}}x_{3}^{2}+\\dots\\dots-2x_{p-1}x_{p}+{\\frac{p-1}{p}}x_{p}-{\\frac{p-1}{p}}x_{p}+\\cdots+x_{r}x_{p}+\\sum_{p}^{p-1}x_{p}-\\sum_{p}+\\cdots$ Each term with $x_{i}^{2}$ features once on both adjacent terms and gives the sum $\\d\\L_{i}^{\\underline{{\\varepsilon}}-1}x_{i}^{\\underline{{\\varepsilon}}}+\\displaystyle{\\frac{i+1}{i}}x_{i}^{\\underline{{\\varepsilon}}}=\\displaystyle{\\frac{2i}{i}}x_{i}^{2}=2x_{i}^{2}$ When, $2S=F(x)+F(y)+F(z)-{\\frac{p-1}{p}}v^{2}-{\\frac{q-1}{q}}v^{2}-{\\frac{r-1}{r}}v^{2}+2v^{2}$ $F(x)+F(y)+F(z)+\\left({\\frac{1}{p}}+{\\frac{1}{q}}+{\\frac{1}{r}}-1\\right)v^{2}.$ Because all $F  \\ge  0$, we should have other expression not greater than zero. However, $v  \\neq  0$, because in this case for having all squares zero all numbers would be zero. Because of this, $\\textstyle{\\frac{1}{p}}+{\\frac{1}{q}}+{\\frac{1}{r}}\\leq1$. Conclusion: Necessity of this criterion is proved. Sufficiency can be seen from definition $F$ in the second proof - we should put arithmetic progressions on all tails. In case of graph having form of bamboo, we have $1+{\\frac{1}{q}}+{\\frac{1}{r}}-1\\leq0$, equal to $\\textstyle{\\frac{1}{q}}+{\\frac{1}{r}}\\leq0$ while $q, r  \\ge  1$, what is obviously impossible. So answer is always <<NO>>. All mentioned above is made with few depth-first searches, so complexity of this solution is $O(V + E)$.",
    "tags": [
      "constructive algorithms",
      "dp",
      "graphs",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "831",
    "index": "A",
    "title": "Unimodal Array",
    "statement": "Array of integers is unimodal, if:\n\n- it is strictly increasing in the beginning;\n- after that it is constant;\n- after that it is strictly decreasing.\n\nThe first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.\n\nFor example, the following three arrays are unimodal: $[5, 7, 11, 11, 2, 1]$, $[4, 4, 2]$, $[7]$, but the following three are not unimodal: $[5, 5, 6, 6, 1]$, $[1, 2, 1, 2]$, $[4, 5, 5, 6]$.\n\nWrite a program that checks if an array is unimodal.",
    "tutorial": "Let use two variables $pos_{1}$ and $pos_{2}$. Initially $pos_{1} = 0$ and $pos_{2} = n - 1$. After that we need to iterate through the given array from the left to the right and increase $pos_{1}$ until the next element is strictly more than previous. After that we need to iterate through the given array from the right to the left and decrease $pos_{2}$ until $a[pos_{2} - 1] > a[pos_{2}]$. Now it is left only to check that all elements between positions $pos_{1}$ and $pos_{2}$ are equal to each other. If it is true the answer is \"YES\", otherwise, the answer is \"NO\".",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "831",
    "index": "B",
    "title": "Keyboard Layouts",
    "statement": "There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with $26$ letters which coincides with English alphabet.\n\nYou are given two strings consisting of $26$ distinct letters each: all keys of the first and the second layouts in the same order.\n\nYou are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.\n\nSince all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.",
    "tutorial": "At first we need to support the correspondence of letters on keyboards. For example, it can be done with help of $map < char, char >$. Let's call it $conformity$. Let the first layout equals to $s_{1}$ and the second - $s_{2}$. Now we need to iterate through the first string and make $conformity[s_{1}[i]] = s_{2}[i]$. Also we need to make $conformity[toupper(s_{1}[i])] = toupper(s_{2}[i])$, where function $toupper(c)$ gives the lowercase letter $c$ to the corresponding uppercase letter. After that simply iterate through the given text. Let the current symbol is $c$. If $c$ is a digit we need to print it. Otherwise, $c$ is a letter, so we need to print $conformity[c]$.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "831",
    "index": "C",
    "title": "Jury Marks",
    "statement": "Polycarp watched TV-show where $k$ jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the $i$-th jury member gave $a_{i}$ points.\n\nPolycarp does not remember how many points the participant had before this $k$ marks were given, but he remembers that among the scores announced after each of the $k$ judges rated the participant there were $n$ ($n ≤ k$) values $b_{1}, b_{2}, ..., b_{n}$ (it is guaranteed that all values $b_{j}$ are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. $n < k$. Note that the initial score wasn't announced.\n\nYour task is to determine the number of options for the score the participant could have before the judges rated the participant.",
    "tutorial": "At first let's calculate an array $sum$ where $sum[i]$ equals to sum of the first $i$ jury points. Now consider the value $b_{1}$. Let the initial score equals to $x$. Here we need to iterate by $m$ from $1$ to $k$ - how many members of jury rated the participant until Polycarp remembered $b_{1}$. Then $x = b_{1} - sum[m]$. Insert each initial scores in $set$. So, we got all possible initial participant scores. After that it is left only to check correctness of each initial score. Let the another candidate on initial score equals to $d$. We need to put in set $points$ all values $d + sum[i]$ for all $i$ from $1$ to $k$. After that we need to check that all elements of array $b$ can be find in $points$. If it is true the participant could has initial score $d$ points, so we need to increase the answer on one.",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1700
  },
  {
    "contest_id": "832",
    "index": "A",
    "title": "Sasha and Sticks",
    "statement": "It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.\n\nToday he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws $n$ sticks in a row. After that the players take turns crossing out exactly $k$ sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than $k$ sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.",
    "tutorial": "Note, that it's not important from which side sticks are being crossing out. Players will make summary $\\left\\lfloor{\\frac{22}{k}}\\right\\rfloor$ turns. If this number is odd, Sasha made $1$ more turn than Lena and won. Otherwise, Sasha and Lena made same number of turns and Sasha didn't win.",
    "code": "// God & me\n// Fly ...\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int maxn = 1e5 + 17, lg = 17;\n \nll n, k;\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcin >> n >> k;\n\tcout << ((n / k) & 1 ? \"YES\" : \"NO\") << '\\n';\n\treturn 0;\n}",
    "tags": [
      "games",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "832",
    "index": "B",
    "title": "Petya and Exam",
    "statement": "It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..\n\nThere is a glob pattern in the statements (a string consisting of lowercase English letters, characters \"?\" and \"*\"). It is known that character \"*\" occurs \\textbf{no more than once} in the pattern.\n\nAlso, $n$ query strings are given, it is required to determine for each of them if the pattern matches it or not.\n\nEverything seemed easy to Petya, but then he discovered that \\textbf{the special pattern characters differ from their usual meaning}.\n\nA pattern matches a string if it is possible to replace each character \"?\" with one good lowercase English letter, and the character \"*\" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.\n\nThe good letters are given to Petya. All the others are bad.",
    "tutorial": "If pattern doesn't contain \"*\", to match pattern, it's neccesary that string's size is equal to pattern size , all letters in pattern match with the letters in string, and in the positions on which pattern contains \"?\", the string contains good characters. If pattern contains \"*\", split it into two strings: $p_{1}$ contains all characters before \"*\" and $p_{2}$ after it. Note, that string doesn't match pattern, if it's size is less than $|p_{1}| + |p_{2}|$. Split the string into three: $s_{1}$ is prefix of size $|p_{1}|$, $s_{2}$ is suffix of size $|p_{2}|$, and $s_{3}$ is the remaining substring. The string mathes pattern, if $s_{1}$ matches $p_{1}$, $s_{2}$ matches $p_{2}$ and $s_{3}$ contains only bad characters. Obviously, that we can make all checks in time of $O(|s|)$. Final asymptotics is $O(\\sum_{i=1}^{n}|s|)$.",
    "code": "// God & me\n// Fly ...\n#include <bits/stdc++.h>\nusing namespace std;\nconst int maxn = 1e5 + 17, z = 26;\nint n;\nbool good[z];\nstring goods, pat;\nbool mat(string pat, string s){\n\tif(pat.size() != s.size())\n\t\treturn 0;\n\tfor(int i = 0; i < s.size(); i++)\n\t\tif(pat[i] != '?'){\n\t\t\tif(s[i] != pat[i])\n\t\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t\tif(!good[s[i] - 'a'])\n\t\t\t\treturn 0;\t\t\t\t\n\treturn 1;\n}\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcin >> goods >> pat >> n;\n\tfor(auto c : goods)\n\t\tgood[c - 'a'] = 1;\n\tauto p = pat.find('*');\n\tfor(string s; n--; ){\n\t\tcin >> s;\n\t\tif(s.size() < pat.size() - 1)\n\t\t\tcout << \"NO\" << '\\n';\n\t\telse if(p == string :: npos)\n\t\t\tcout << (mat(pat, s) ? \"YES\" : \"NO\") << '\\n';\n\t\telse{\n\t\t\tbool ok = 1;\n\t\t\tok &= mat(pat.substr(0, p), s.substr(0, p));\n\t\t\treverse(pat.begin(), pat.end());\n\t\t\treverse(s.begin(), s.end());\n\t\t\tp = pat.size() - p - 1;\n\t\t\tok &= mat(pat.substr(0, p), s.substr(0, p));\n\t\t\treverse(pat.begin(), pat.end());\n\t\t\treverse(s.begin(), s.end());\n\t\t\tp = pat.size() - p - 1;\n\t\t\tfor(int i = p; i < s.size() - (pat.size() - p - 1); i++)\n\t\t\t\tok &= !good[ s[i] - 'a' ];\n\t\t\tcout << (ok ? \"YES\" : \"NO\") << '\\n';\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "832",
    "index": "C",
    "title": "Strange Radiation",
    "statement": "$n$ people are standing on a coordinate axis in points with positive integer coordinates strictly less than $10^{6}$. For each person we know in which direction (left or right) he is facing, and his maximum speed.\n\nYou can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed $s$: one to the right, and one to the left. Of course, the speed $s$ is strictly greater than people's maximum speed.\n\nThe rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray.\n\nYou need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point $0$, and there is a person that has run through point $10^{6}$, is as small as possible. In other words, find the minimum time moment $t$ such that there is a point you can place the bomb to so that at time moment $t$ some person has run through $0$, and some person has run through point $10^{6}$.",
    "tutorial": "We'll use binary search by answer. Obviously, that answer is always less than $10^{6}$ and more than $0$. We denote the answer for $t$ at current iteration. For each person, running left, we have to find positions of bomb, at which he will have time to reach the point $0$ in time $t$. Let $d$ be the distance between the person and point $0$ and $d_{1}$ be the distance, which passed the person before he caught up with the ray. If ${\\frac{d}{v_{i}}}\\leq l$, we can place bomb in every point. Otherwise, we can place bomb in point $x$, ${\\begin{array}{c}{{\\left\\{{\\frac{d_{1}}{v_{i}}}+{\\frac{d-d_{1}}{v_{i}+s}}\\leq t,}}\\\\ {{\\left\\{x\\geq d,}}\\\\ {{x=\\left(d-d_{1}\\right)+{\\frac{d_{1}\\cdot s}{v_{i}}}}\\end{array}}$ Before the meeting with the ray, person ran a distance of $d_{1}$ at a speed of $v_{i}$, after the meeting he ran a distance of $d - d_{1}$ at a speed of $v_{i} + s$. We require the total time be no more than $t$. We need the person to be caught by rays, so bomb have to have coordinate more than person's initial coordinate. We know that rays and person met at the point of $d - d_{1}$ at the moment of $\\frac{d_{1}}{v_{i}}$. Rays moves at the speed of $s$. It means they started moving at the point of $(d-d_{1})+{\\frac{d_{1}\\cdot s}{v_{i}}}$. Note that solutions of this system form a segment on the coordinate line. For persons, running right, the reasoning is similar. We find all the segments for persons, runnig left, and persons, running right. If some point with the whole coordinate belongs to segment for person, running left and person, running right, we move right border of binary search and left border otherwise. To find this point we can use scanline or prefix sums. Let the binary search make $it$ iterations. Than final asymptotics is $O(n  \\cdot  log n  \\cdot  it)$, if we use scanline, or $O((n + max_{x})  \\cdot  it)$ if we use prefix sums.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n \n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \nconst int OPEN = 1;\nconst int CLOSE = -1;\n \nstruct tsob\n{\n    int x, t, id;\n};\n \ninline bool operator<(const tsob &a, const tsob &b)\n{\n    if (a.x != b.x) return a.x < b.x;\n    return a.t == OPEN && b.t == CLOSE;\n}\n \nconst int maxn = 100005;\nconst int DR = 1000000;\n \nint curb[2];\nvector<tsob> sobs;\nint x[maxn], v[maxn], dir[maxn], dist[maxn];\nint n, s;\n \nbool can(ld t)\n{\n    sobs.clear();\n    curb[0] = 0;\n    curb[1] = 0;\n    for (int i = 0; i < n; i++)\n    {\n        if (dist[i] <= (ll)v[i] * t)\n        {\n            curb[dir[i]]++;\n        } else if (dist[i] <= (ll)(v[i] + s) * t)\n        {\n            // A * r + B = 0\n            ld A = (ld)1 / (s - v[i]) - (ld)v[i] / (s - v[i]) / (s + v[i]);\n            ld B = (ld)dist[i] / (s + v[i]) - t;\n            ld r = -B / A;\n            if (dir[i] == 0)\n            {\n                sobs.pb({x[i], OPEN, dir[i]});\n                sobs.pb({lround(min((ld)DR + 1, floor(x[i] + r))), CLOSE, dir[i]});\n            } else\n            {\n                sobs.pb({lround(max((ld)-1.0, ceil(x[i] - r))), OPEN, dir[i]});\n                sobs.pb({x[i], CLOSE, dir[i]});\n            }\n        }\n    }\n    if (curb[0] > 0 && curb[1] > 0) return true;\n    sort(all(sobs));\n    for (auto t : sobs)\n    {\n        curb[t.id] += t.t;\n        if (curb[0] > 0 && curb[1] > 0) return true;\n    }\n    return false;\n}\n \nint main()\n{\n    scanf(\"%d%d\", &n, &s);\n    for (int i = 0; i < n; i++)\n    {\n        scanf(\"%d%d%d\", &x[i], &v[i], &dir[i]);\n        dir[i]--;\n        if (dir[i] == 0) dist[i] = x[i];\n        else dist[i] = DR - x[i];\n    }\n    ld l = 0;\n    ld r = 1e6;\n    for (int IT = 0; IT < 50; IT++)\n    {\n        ld m = (l + r) / 2;\n        if (can(m)) r = m;\n        else l = m;\n    }\n    cout.precision(20);\n    cout << (double)(l + r) / 2 << endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "832",
    "index": "D",
    "title": "Misha, Grisha and Underground",
    "statement": "Misha and Grisha are funny boys, so they like to use new underground. The underground has $n$ stations connected with $n - 1$ routes so that each route connects two stations, and it is possible to reach every station from any other.\n\nThe boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station $s$ to station $f$ by the shortest path, and will draw with aerosol an ugly text \"Misha was here\" on every station he will pass through (including $s$ and $f$). After that on the same day at evening Grisha will ride from station $t$ to station $f$ by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.\n\nThe boys have already chosen three stations $a$, $b$ and $c$ for each of several following days, one of them should be station $s$ on that day, another should be station $f$, and the remaining should be station $t$. They became interested how they should choose these stations $s$, $f$, $t$ so that the number Grisha will count is as large as possible. They asked you for help.",
    "tutorial": "Let vertex $1$ be the root of the tree. For each vertex $i$ we calculate value $h_{i}$ - distance to the root. Now we can represent way $v_{1}$ $\\to$ $v_{2}$ as two ways $v_{1}$ $\\to$ $lca(v_{1}, v_{2})$ and $lca(v_{1}, v_{2})$ $\\to$ $v_{2}$. Note that number of edges in the interseption of two such ways $v_{1}$ $\\to$ $v_{2}$ and $u_{1}$ $\\to$ $u_{2}$, $h_{v1}  \\le  h_{v2}$, $h_{u1}  \\le  h_{u2}$ is $max(0, h_{lca(u2, v2)} - max(h_{v1}, h_{u1}))$. We can calculate $lca$ in $O(log n)$, using binary lifting, or in $O(1)$, using $\\mathrm{SParSe~table}$. Using the formula we can easy calculate answer for fixed $s$, $f$ and $t$. To answer the query, we consider all possible permutations of $a$, $b$ and $c$, there are only $3!$. Final asymptotics is $O(n  \\cdot  log n + q  \\cdot  log n)$ or $O(n + q)$, depending on the $lca$ search algorithm.",
    "code": "// God & me\n// Fly ...\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int maxn = 1e5 + 17, lg = 17;\n \nint n, q, par[maxn][lg], h[maxn], ver[3];\nvector<int> g[maxn];\nvoid dfs(int v = 0){\n\tfor(int i = 1; i < lg; i++)\n\t\tpar[v][i] = par[ par[v][i - 1] ][i - 1];\n\tfor(auto u : g[v]){\n\t\th[u] = h[v] + 1;\n\t\tpar[u][0] = v;\n\t\tdfs(u);\n\t}\n}\nint lca(int v, int u){\n\tif(h[v] > h[u])  swap(v, u);\n\tfor(int i = 0; i < lg; i++)\n\t\tif(h[u] - h[v] >> i & 1)\n\t\t\tu = par[u][i];\n\tfor(int i = lg - 1; i >= 0; i--)\n\t\tif(par[v][i] != par[u][i])\n\t\t\tv = par[v][i], u = par[u][i];\n\treturn v == u ? v : par[v][0];\n}\nint calc(int f, int s, int t){\n\tint ans = 0;\n\tbool is1 = lca(f, s) == f, is2 = lca(f, t) == f;\n\tif(is1 != is2)  return 1;\n\tif(is1)\n\t\tans = max(ans, h[ lca(s, t) ] - h[ f ]);\n\telse if(lca(f, s) != lca(f, t))\n\t\tans = max(ans, h[ f ] - max(h[ lca(f, s) ], h[ lca(f, t) ]));\n\telse\n\t\tans = max(ans, h[ f ] + h[ lca(s, t) ] - 2 * h[ lca(f, t) ]);\n\treturn ans + 1;\n}\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcin >> n >> q;\n\tfor(int i = 1, p; i < n; i++){\n\t\tcin >> p, p--;\n\t\tg[p].push_back(i);\n\t}\n\tdfs();\n\twhile(q--){\n\t\tfor(int i = 0; i < 3; i++)\n\t\t\tcin >> ver[i], ver[i]--;\n\t\tcout << max({calc(ver[0], ver[1], ver[2]), calc(ver[1], ver[0], ver[2]), calc(ver[2], ver[1], ver[0])}) << '\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "832",
    "index": "E",
    "title": "Vasya and Shifts",
    "statement": "Vasya has a set of $4n$ strings of equal length, consisting of lowercase English letters \"a\", \"b\", \"c\", \"d\" and \"e\". Moreover, the set is split into $n$ groups of $4$ equal strings each. Vasya also has one special string $a$ of the same length, consisting of letters \"a\" only.\n\nVasya wants to obtain from string $a$ some fixed string $b$, in order to do this, he can use the strings from his set in any order. When he uses some string $x$, each of the letters in string $a$ replaces with the next letter in alphabet as many times as the alphabet position, counting from zero, of the corresponding letter in string $x$. Within this process the next letter in alphabet after \"e\" is \"a\".\n\nFor example, if some letter in $a$ equals \"b\", and the letter on the same position in $x$ equals \"c\", then the letter in $a$ becomes equal \"d\", because \"c\" is the second alphabet letter, counting from zero. If some letter in $a$ equals \"e\", and on the same position in $x$ is \"d\", then the letter in $a$ becomes \"c\". For example, if the string $a$ equals \"abcde\", and string $x$ equals \"baddc\", then $a$ becomes \"bbabb\".\n\nA used string disappears, but Vasya can use equal strings several times.\n\nVasya wants to know for $q$ given strings $b$, how many ways there are to obtain from the string $a$ string $b$ using the given set of $4n$ strings? Two ways are different if the number of strings used from some group of $4$ strings is different. Help Vasya compute the answers for these questions modulo $10^{9} + 7$.",
    "tutorial": "The first thing to notice is that the problem can be reduced to a matrix form. To do this quite easily, we note that if we denote $x_{i}$ as the number of times we apply the $i$-th row, then we will get the matrix, we will have exactly $n$ columns ($x_{i}$) and $m$ rows. That is, $A_{ij}$ will match the $i$-th symbol in the $j$-th row. Now we get the usual system of linear equations. Note that we have a restriction on $x_{i}$, $\\forall i:x_{i}\\leq4$, that is, we are interested in the number of SLE solutions, modulo $5$. Then for each query it would be possible to find the number of solutions using the Gauss algorithm (0 or $5^{n - rk(A)}$), but this solution will take $O(n^{3} \\cdot q)$ time, which does not fit under restrictions. One of the optimizations for improving the algorithm is to bring the matrix $A$ to a triangular matrix form (find the rank) and memorize the transformations. Then for each query string we could apply these transformations, then the algorithm will work $O(n^{3} + q \\cdot n^{2})$, which is already past Time Limit.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define ll long long\n#define ABS(x) ((x) < 0 ? -(x) : (x))\n \nconst int N = 500, MODM = 1e9 + 7;\n \nint matr_divide[5][5];\n \nll bin_pow(ll a, ll b, ll pp) {\n    if (b == 0)\n        return 1;\n    if (b == 1)\n        return a % pp;\n    if (b & 1)\n        return a * bin_pow(a, b - 1, pp) % pp;\n    ll x = bin_pow(a, b / 2, pp) % pp;\n    return x * x % pp;\n}\n \nvoid ini() {\n    for (int a = 0; a < 5; ++a)\n        for (int b = 0; b < 5; ++b) {\n            matr_divide[a][b] = a * bin_pow(b, 3, 5) % 5;\n        }\n}\n \nll get_independent(vector<vector<short int>> &matrix, int q = 0) {\n    int n = matrix.size();\n    int m = matrix[0].size() - q;\n \n    vector<int> where(m, -1);\n    for (int col = 0, row = 0; row < n && col < m; ++col) {\n        int cur = row;\n        for (int i = row; i < n; ++i)\n            if (matrix[i][col] > matrix[cur][col])\n                cur = i;\n            if (!matrix[cur][col])\n                continue;\n            for (int j = col; j < m + q; ++j)\n                swap(matrix[row][j], matrix[cur][j]);\n            where[col] = cur;\n            for (int i = 0; i < n; ++i) {\n                if (i != row) {\n                    ll tmp = matr_divide[matrix[i][col]][matrix[row][col]];\n                    for (int j = col; j < m + q; ++j) {\n                        matrix[i][j] -= matrix[row][j] * tmp % 5;\n                        if (matrix[i][j] < 0)\n                            matrix[i][j] += 5;\n                    }\n                }\n            }\n            ++row;\n    }\n    ll ans = 0;\n    for (int i = 0; i < m; ++i)\n        if (where[i] == -1)\n            ++ans;\n    return ans;\n}\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    ini();\n    int n, q, m;\n    cin >> n >> m;\n    vector<vector<short int>> mas;\n    mas.resize(m);\n    for (int i = 0; i < m; ++i)\n        mas[i].assign(n, 0);\n    for (int i = 0; i < n; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < s.size(); ++j) {\n            mas[j][i] = (s[j] - 'a') % 5;\n        }\n    }\n    cin >> q;\n    for (int i = 0; i < m; ++i) {\n        mas[i].resize(n + q);\n    }\n \n    // vector<vector<short int>> mm = {{2, 1, 3}, {0, 0, 0}, {1, 3, 3}, {1, 3, 2}, {3, 2, 1}, {1, 3, 1}};\n    for (int index = 0; index < q; ++index) {\n        string query;\n        cin >> query;\n        vector<int> now;\n        for (int j = 0; j < query.size(); ++j) {\n            mas[j][n + index] = (query[j] - 'a') % 5;\n        }\n    }\n    int ind_pow = get_independent(mas, q);\n    ll ans = bin_pow(5, ind_pow, MODM);\n    int max_i = -1;\n    for (int i = 0; i < m; ++i)\n        for (int j = 0; j < n; ++j)\n            if (mas[i][j])\n                max_i = max(max_i, i);\n    for (int i = 0; i < q; ++i) {\n        int ind_col = n + i;\n        int last = -1;\n        for (int j = 0; j < m; ++j) {\n            if (mas[j][ind_col])\n                last = j;\n            if (last > max_i)\n                break;\n        }\n        if (last > max_i)\n            cout << 0 << \"\\n\";\n        else\n            cout << ans << \"\\n\"; \n    }\n    return 0;\n}",
    "tags": [
      "matrices"
    ],
    "rating": 2600
  },
  {
    "contest_id": "833",
    "index": "A",
    "title": "The Meaningless Game",
    "statement": "Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.\n\nThe game consists of multiple rounds. Its rules are very simple: in each round, a natural number $k$ is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by $k^{2}$, and the loser's score is multiplied by $k$. In the beginning of the game, both Slastyona and Pushok have scores equal to one.\n\nUnfortunately, Slastyona had lost her notepad where the history of all $n$ games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.",
    "tutorial": "Prequisites: none (maybe binary search). Let $S$ denote the product of the set of numbers said by Slastyona, and $P$ denote the product of the set of numbers barked by Pushok (in case one of the sets is empty the corresponding product is assumed to be equal to one). Then, we can reformulate the problem in a following way: we need to find such $S$ and $P$ that the following holds: $\\binom{S^{2}\\cdot P=a}{P^{2}\\cdot S=b}$ We can already see a slow way to solve the problem. It is based on assumption that if $a  \\le  b$, then $S  \\le  P$ and $S^{3}  \\le  10^{9}$, so we can just enumerate all possible values of $S$. Unfortunately, we have as much as $350000$ games. So we need to find a more efficient solution. Note that $ab = S^{3} \\cdot P^{3}$, and $S\\cdot P={\\dot{\\sqrt{a b}}}$ (let us denote the cubic root as $X$). We can then easily find the required values: $\\begin{array}{c}{{\\left\\{S={\\frac{a}{X}}}}\\\\ {{P={\\frac{b}{X}}}}\\end{array}\\right.$ We only need to check whether $ab$ is a perfect cube and $\\lambda{\\sqrt{a b}}$ divides $a$ and $b$. Time complexity: $O(1)$ (or $O(log(ab))$ if binary search was used to find the cubic root).",
    "code": "#include <cmath>\n#include <cstdio>\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int MAXR = 1000005;\n \nll cubic_root(ll x)\n{\n    ll l = 0, r = MAXR;\n    while (l != r) {\n        ll m = (l + r + 1) / 2;\n        if (m * m * m > x)\n            r = m - 1;\n        else\n            l = m;\n    }\n    return l;\n}\n \nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n \n    for (int i = 0; i < n; i++) {\n        ll a, b;\n        scanf(\"%I64d %I64d\", &a, &b);\n        ll x = cubic_root(a * b);\n        if (x * x * x != a * b)\n            puts(\"No\");\n        else if (a % x == 0 && b % x == 0)\n            puts(\"Yes\");\n        else\n            puts(\"No\");\n    }\n \n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "833",
    "index": "B",
    "title": "The Bakery",
    "statement": "Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.\n\nSoon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more \\textbf{distinct} cake types a box contains (let's denote this number as the value of the box), the higher price it has.\n\nShe needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of $n$ cakes the oven is going to bake today. Slastyona has to pack exactly $k$ boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one \\textbf{right after another} (in other words, she has to put in a box a continuous segment of cakes).\n\nSlastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.",
    "tutorial": "Prerequisites: dp + segment trees All authors' solutions are based on the following dp idea: let's calculate $dp(k, n)$ - the maximum cost we can obtain if we assign the first $n$ cakes to $k$ boxes. For $k = 1$ the answer is equal to the number of distinct values on a prefix. For $k > 1$ the answer can be deduced as follows (here $c(i, n)$ denotes the number of distinct elements in range $(i, n)$): $dp(k, n) = max_{1  \\le  i < n}dp(k - 1, i - 1) + c(i, n)$ There are two possible approaches. Solution I: Imagine we're trying to compute the $k$-th dp layer and our currect position is $i$, maintaining a max segment tree with the sum $dp(k - 1, j) + c(j + 1, i)$ in $j$-th cell where $0  \\le  j < i$. The answer for $dp(k, n)$ is just a prefix query. How do we move $i$ the right? Let's denote $i$-th cake type as $y$. Notice that the $i$ $ \\rightarrow $ $i + 1$ transition increases the segment tree values for all cells $j$ such that there's no $y$ in range $[j + 1, i]$ by one (since we've added a new distinct element). More formal, we increase all $j$'s between the previous position of $y$ plus one (or the beginning of the array if we haven't marked $y$ before) to $i$. Hence we got a lazy update segment tree and a simple $prev[i]$ precalc. There's a single $O(\\log(n))$ for both updating and computing a single $dp(k, n)$ and a total complexity of $O(n k\\log(n))$. Solution II: Many tried this approach and failed. Albeit we didn't focus on cutting this solution much, it still required several optimizations to pass. Let's denote the leftmost $i$ such that $dp(k - 1, i)$ gives the optimal answer for $dp(n, k)$ as $opt(k, n)$. We claim that $opt(k, n)  \\le  opt(k, n + 1))$ (this one is a left as an exercise to the reader). With with assumption it is the right time for applying divide & conquer dp optimization (here persistent segment tree is used for counting the number of distinct cakes in a range, which is a well-known application of it; the divide and conquer technique is described here, for example: codeforces.com/blog/entry/8219). There are $O(n\\log(n))$ relaxes in a single dp layer, each of those is processed in $O(\\log(n))$. With a total of $k$ layers we get the overall complexity of $O(n k\\log^{2}(n))$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <unordered_set>\n#include <vector>\n#include <cmath>\n#include <string>\n#include <set>\n#include <map>\n#include <cstdio>\n#include <functional>\n#include <random>\n#include <ctime>\n#include <cassert>\n#include <bitset>\n#include <unordered_map>\n#include <math.h>\n#include <queue>\n \nusing namespace std;\n \n#define N 35005\n#define M 55\n#define F 200\nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define fornv(i, n) for (int i = n - 1; i >= 0; i--)\n#define pii pair<int, int>\n#define forlr(i, l, r) for (int i = l; i <= r; i++)\n#define forlrv(i, l, r) for (int i = r; i >= l; i--)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define mp make_pair\ntypedef long long ll;\ntypedef unsigned long long ull;\nconst long double eps = 1e-9;\nconst int inf = 2e9;\nconst int mod = 1e9 + 7;\nconst ll infinity = 2 * 1e18;\n#define p p2\n#define endl '\\n'\n \nint t[4 * N], d[4 * N], w[N];\n \nint dp[M][N];\n \nint n, k;\n \nvoid build(int k, int u, int l, int r)\n{\n\tif (l == r - 1)\n\t\treturn void(t[u] = dp[k][l]);\n \n\tint m = (l + r) / 2;\n\tbuild(k, 2 * u + 1, l, m);\n\tbuild(k, 2 * u + 2, m, r);\n}\n \nvoid push(int u, int len)\n{\n\tif (!d[u]) return;\n \n\tt[u] += d[u];\n \n\tif (len > 1)\n\t\td[2 * u + 1] += d[u], d[2 * u + 2] += d[u];\n \n\td[u] = 0;\n}\n \nvoid update(int u, int l, int r, int L, int R)\n{\n\tpush(u, r - l);\n \n\tif (l == L && r == R)\n\t{\n\t\td[u]++;\n\t\tpush(u, r - l);\n\t\treturn;\n\t}\n \n\tint m = (l + r) / 2;\n\tif (L < m)\n\t\tupdate(2 * u + 1, l, m, L, min(m, R));\n\telse\n\t\tpush(2 * u + 1, m - l);\n \n\tif (R > m)\n\t\tupdate(2 * u + 2, m, r, max(L, m), R);\n\telse\n\t\tpush(2 * u + 2, r - m);\n \n\tt[u] = max(t[2 * u + 1], t[2 * u + 2]);\n}\n \nint get(int u, int l, int r, int L, int R)\n{\n\tif (L >= R) return 0;\n \n\tpush(u, r - l);\n \n\tif (l == L && r == R) return t[u];\n \n\tint m = (l + r) / 2, ans = 0;\n \n\tif (L < m)\n\t\tans = max(ans, get(2 * u + 1, l, m, L, min(m, R)));\n\telse\n\t\tpush(2 * u + 1, m - l);\n \n\tif (R > m)\n\t\tans = max(ans, get(2 * u + 2, m, r, max(L, m), R));\n\telse\n\t\tpush(2 * u + 2, r - m);\n \n\treturn ans;\n}\n \nint p[N];\nmap<int, int> last;\n \nvoid solve(int k)\n{\n\tfill_n(t, 4 * N, 0), fill_n(d, 4 * N, 0);\n \n\tbuild(k - 1, 0, 0, n);\n \n\tforn(i, n)\n\t{\n\t\tif (p[i] < i)\n\t\t\tupdate(0, 0, n, p[i], i);\n\t\tdp[k][i] = max(dp[k - 1][i], get(0, 0, n, 0, i));\n\t}\n}\n \n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    \n\tcin >> n >> k;\n\tforn(i, n) cin >> w[i];\n \n\tforn(i, n)\n\t{\n\t\tp[i] = -1;\n\t\tif (last.count(w[i]))\n\t\t\tp[i] = last[w[i]];\n\t\telse\n\t\t\tp[i] = 0;\n \n\t\tlast[w[i]] = i;\n\t}\n \n\tset<int> s;\n\tforn(i, n)\n\t{\n\t\ts.insert(w[i]);\n\t\tdp[1][i] = s.size();\n\t}\n \n\tfor (int i = 2; i <= k; i++) solve(i);\n \n\tcout << dp[k][n - 1] << endl;\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dp",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "833",
    "index": "C",
    "title": "Ever-Hungry Krakozyabra",
    "statement": "Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner.\n\nIts favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabra dislikes them; moreover, they often cause it indigestion! So, as a necessary precaution, Krakozyabra prefers to sort the digits of a number in non-descending order before proceeding to feast. Then, the leading zeros of the resulting number are eaten and the remaining part is discarded as an inedible tail.\n\nFor example, if Krakozyabra is to have the number $57040$ for dinner, its inedible tail would be the number $457$.\n\nSlastyona is not really fond of the idea of Krakozyabra living in her castle. Hovewer, her natural hospitality prevents her from leaving her guest without food. Slastyona has a range of natural numbers from $L$ to $R$, which she is going to feed the guest with. Help her determine how many distinct inedible tails are going to be discarded by Krakozyabra by the end of the dinner.",
    "tutorial": "Prerequisites: Combinatorics or strong faith :) At first we might assume (without loss of generality) that both left and right bounds are strictly less than $10^{18}$ (otherwise we just append $1$ to the list of unedible tails) and hence consider only numbers with no more than 18 decimal digits. Notice that there are not than many numbers without leading zeros: they are no more than $\\textstyle{\\binom{18+9}{9}}$ (the number of solutions to $c_{1} + c_{2} + ... + c_{n}  \\le  18$, where $c_{i}$ - the number of $i$-s in a number). To be precise, there are only $4686824$ such numbers in range $1$ $ \\rightarrow $ $10^{18}$. Thus we might simply brute all such numbers and for a fixed candidate (let's denote it as $A$), whether it is possible (using some additional zeros if neccessary) to form the number $A'$ from the range $[L, R]$. How do we check it rapidly? Let's represent $L$ and $R$ as vectors of length $n$ (we might add some leading zeros to $L$ if neccessary), and $A$ - as an array $num$ (with possible additional zeros). We will brute it in the following way: $go(pos, l_{flag}, r_{flag})$, which keeps out current position and indicates whether the currently obtained number is equal to the corresponding prefix of $L$ / $R$. Several cases to consider: If $(pos = n)$, we return true. If $(l_{flag} = 1)$ and $(r_{flag} = 1)$, we strictly follow the prefixes of $L$ and $R$. There are two deeper cases: If $L(pos) = R(pos)$, the only way out is to place $L(pos)$, decrease the number of corresponding digits in $num$ and proceed to $go(pos + 1, 1, 1)$. Else if $L(pos) < R(pos)$, we have to check if there's an element in $[L(pos) + 1, R(pos) - 1]$. It's obvious that the answer is true in this case (since after we get right between $L$ and $R$ we can assign the suffix whichever way we want). Otherwise we first consider the possibility of placing $L(pos)$ and proceeding to $go(pos + 1, 1, 0)$ or placing $R(pos)$ and proceeding to $go(pos + 1, 0, 1)$. If nothing returns true, the answer is false; If only left flag is active $(l_{flag} = 1)$, we need a random digit from the suffix $[L(pos) + 1, 9]$. If we find it - the answer is true. If no - we try $L(pos)$ and $go(pos + 1, 1, 0)$ or return false. A lone right flag is processed in a simular way with the only difference that we try the $[0, R(pos) - 1]$ prefix or $R(pos)$ and $go(pos + 1, 0, 1)$. At a first glance it seems that out bruteforce will end up being $O(2^{n})$. But an easy observation shows that there can be no more that two separate branches here. The total bruteforce complexity is $O(10 \\cdot n)$. Complexity: $O\\left(\\!\\,\\!(stackrel{(K\\setminus\\emptyset)}{\\mathfrak{g}})\\cdot K\\right)$, where $K$ stands for the maximum number length.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <unordered_set>\n#include <vector>\n#include <cmath>\n#include <string>\n#include <set>\n#include <map>\n#include <cstdio>\n#include <functional>\n#include <random>\n#include <ctime>\n#include <cassert>\n#include <bitset>\n#include <unordered_map>\n#include <math.h>\n#include <queue>\n \nusing namespace std;\n \n#define N 200005\n#define M 20\n#define F 200\nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define fornv(i, n) for (int i = n - 1; i >= 0; i--)\n#define pii pair<int, int>\n#define forlr(i, l, r) for (int i = l; i <= r; i++)\n#define forlrv(i, l, r) for (int i = r; i >= l; i--)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define mp make_pair\ntypedef long long ll;\ntypedef unsigned long long ull;\nconst long double eps = 1e-9;\nconst int inf = 2e9;\nconst int mod = 1e9 + 7;\nconst ll infinity = 2 * 1e18;\n#define p p2\n#define endl '\\n'\n \nvector<int> L, R;\n \nint n;\n \nint ans = 0;\n \nint num[10];\nint keep[10];\n \ninline bool any(int l, int r)\n{\n\tif (l > r) return false;\n\tfor (int i = l; i <= r; i++)\n\t\tif (num[i]) return true;\n\treturn false;\n}\n \nbool dfs(int pos, bool lf, bool rf)\n{\n\tif (pos == n)\n\t\treturn true;\n \n\tint l = L[pos], r = R[pos];\n \n\tif (lf & rf)\n\t{\n\t\tif (l == r)\n\t\t{\n\t\t\tif (num[l])\n\t\t\t{\n\t\t\t\tnum[l]--;\n\t\t\t\tif (dfs(pos + 1, 1, 1))\n\t\t\t\t\treturn true;\n\t\t\t\tnum[l]++;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n \n\t\tif (any(l + 1, r - 1)) return true;\n \n\t\tif (num[l])\n\t\t{\n\t\t\tnum[l]--;\n\t\t\tif (dfs(pos + 1, 1, 0))\n\t\t\t\treturn true;\n\t\t\tnum[l]++;\n\t\t}\n \n\t\tif (num[r])\n\t\t{\n\t\t\tnum[r]--;\n\t\t\tif (dfs(pos + 1, 0, 1))\n\t\t\t\treturn true;\n\t\t\tnum[r]++;\n\t\t}\n \n\t\treturn false;\n\t}\n\telse\n\t\tif (lf)\n\t\t{\n\t\t\tif (any(l + 1, 9)) return true;\n \n\t\t\tif (num[l])\n\t\t\t{\n\t\t\t\tnum[l]--;\n\t\t\t\tif (dfs(pos + 1, 1, 0))\n\t\t\t\t\treturn true;\n\t\t\t\tnum[l]++;\n\t\t\t}\n \n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\tif (rf)\n\t\t\t{\n\t\t\t\tif (any(0, r - 1)) return true;\n \n\t\t\t\tif (num[r])\n\t\t\t\t{\n\t\t\t\t\tnum[r]--;\n\t\t\t\t\tif (dfs(pos + 1, 0, 1))\n\t\t\t\t\t\treturn true;\n\t\t\t\t\tnum[r]++;\n\t\t\t\t}\n \n\t\t\t\treturn false;\n\t\t\t}\n \n\treturn false;\n}\n \nvoid go(int n, int sum)\n{\n\tif (n == 10)\n\t{\n\t\tmemcpy(num, keep, sizeof keep);\n\t\tnum[0] += sum;\n \n\t\tif (dfs(0, 1, 1)) ans++;\n\t\treturn;\n\t}\n \n\tfor (int i = 0; i <= sum; i++)\n\t{\n\t\tkeep[n] = i;\n\t\tgo(n + 1, sum - i);\n\t}\n}\n \nint main()\n{\n\tll l, r;\n\tcin >> l >> r;\n \n\tif (l == r)\n\t{\n\t\tcout << 1;\n\t\treturn 0;\n\t}\n \n\tll sh_l = l, sh_r = r;\n \n\tfor (; l; l /= 10)\n\t\tL.push_back(l % 10);\n\tfor (; r; r /= 10)\n\t\tR.push_back(r % 10);\n \n\tn = R.size();\n \n\twhile (L.size() < n) L.push_back(0);\n \n\treverse(L.begin(), L.end());\n\treverse(R.begin(), R.end());\n \n\tgo(1, n);\n \n\tcout << ans << endl;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "greedy",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "833",
    "index": "D",
    "title": "Red-Black Cobweb",
    "statement": "Slastyona likes to watch life of nearby grove's dwellers. This time she watches a strange red-black spider sitting at the center of a huge cobweb.\n\nThe cobweb is a set of $n$ nodes connected by threads, each of the treads is either red of black. Using these threads, the spider can move between nodes. No thread connects a node to itself, and between any two nodes there is a unique sequence of threads connecting them.\n\nSlastyona decided to study some special qualities of the cobweb. She noticed that each of the threads has a value of clamminess $x$.\n\nHowever, Slastyona is mostly interested in jelliness of the cobweb. Consider those of the shortest paths between each pair of nodes on which the numbers of red and black threads differ at most twice. For each such path compute the product of the clamminess of threads on the path.The jelliness of the cobweb is the product of all obtained values among all paths. Those paths that differ by direction only are counted only once.\n\nOf course, this number can be huge, so Slastyona asks you to compute the jelliness of the given cobweb and print the answer modulo $10^{9} + 7$.",
    "tutorial": "Prequisites: centroid decomposition, segment tree / BIT / treap, modulo division Analogically to the vast variety of problems where we are to find some information about all the paths of the tree at once, we can use centroid decomposition as a basis. Let us fix some centroid and some path consisting of $r$ red and $b$ black vertices (let us denote it as a pair $(r, b)$). For this path, we need to somehow obtain (and do it fast!) information about all augmenting paths - such pairs $(r', b')$ that $2 \\cdot min(r + r', b + b')  \\ge  max(r + r', b + b')$. Let us simplify a problem for a little while: let's assume we are only interested in finding such paths $(r', b')$ that $2 \\cdot (r + r')  \\ge  (b + b')$. If we rewrite the inequality as $(2 \\cdot r - b)  \\ge  (b' - 2 \\cdot r')$, we can clearly see that the paths we are interested in comprise the suffix of some tree with nodes having indices $2 \\cdot x - y$. Unfortunately, this bound is not enough. We need to discard all the paths that satisfy not only this condition, but also have a red part which is too long, i.e. those having $2 \\cdot (b + b') < (r + r')$. With the same trick we the inequality turns into $2 \\cdot b - r < r' - 2 \\cdot b'$, describing some prefix of a $x - 2 \\cdot y$ tree. We should maintain $size$ and $product$ of clamminesses for all subtrees. Then the problem of calculating the contribution of a fixed path reduces to quering these two trees. More precisely, for a $(r, b)$ path with clamminess $x$ looks as follows. Denote $suffix(2 \\cdot r - b)$ as $(size, product)$ for the first tree, and $prefix(2 \\cdot b - r)$ as the corresponding pair for the second one. Then the first pair gives us the positive contribution of ($product \\cdot x^{size}$) whereas the second pair gives the same amount of negative contribution (in terms of the second tree this time). The only thing left is to divide them modulo $1e9 + 7$. We might get a little bit more tricky and use modulo givision only when we process all paths from this centroid; this will give us the total complexity of $O(n\\log^{2}(n)+n\\log(M))$, where $M = 1e9 + 7$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <unordered_set>\n#include <vector>\n#include <cmath>\n#include <string>\n#include <set>\n#include <map>\n#include <cstdio>\n#include <functional>\n#include <random>\n#include <ctime>\n#include <cassert>\n#include <bitset>\n#include <unordered_map>\n#include <math.h>\n#include <queue>\n \nusing namespace std;\n \n#define N 200005\n#define M 20\n#define F 200\nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define fornv(i, n) for (int i = n - 1; i >= 0; i--)\n#define pii pair<int, int>\n#define forlr(i, l, r) for (int i = l; i <= r; i++)\n#define forlrv(i, l, r) for (int i = r; i >= l; i--)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define mp make_pair\ntypedef long long ll;\ntypedef unsigned long long ull;\nconst long double eps = 1e-9;\nconst int inf = 2e9;\nconst int mod = 1e9 + 7;\nconst ll infinity = 2 * 1e18;\n#define p p2\n#define endl '\\n'\n \nint mul(int a, int b)\n{\n\treturn (a * 1LL * b) % mod;\n}\n \nint mpow(int x, int p)\n{\n\treturn (!p ? 1 : mul(mpow(mul(x, x), p / 2), (p & 1) ? x : 1));\n}\n \nint divide(int a, int b)\n{\n\treturn mul(a, mpow(b, mod - 2));\n}\n \nclass tree\n{\nprivate:\n\tstruct node\n\t{\n\t\tnode *l = nullptr, *r = nullptr;\n\t\tint y = gen(), size = 1, value, w, x, s = 1;\n \n\t\tnode(int x, int w) : x(x), w(w), value(w) {}\n\t};\n \n\ttypedef node * treap;\n\ttypedef pair<treap, treap> ptt;\n \n\ttreap root = nullptr;\n \n\tpair<int, int> values(treap t)\n\t{\n\t\tif (!t) return mp(0, 1);\n\t\treturn mp(t->size, t->value);\n\t}\n \n\ttreap mend(treap t)\n\t{\n\t\tif (t)\n\t\t{\n\t\t\tpair<int, int> l_values = values(t->l), r_values = values(t->r);\n\t\t\tt->size = l_values.first + r_values.first + t->s;\n\t\t\tt->value = mul(mul(l_values.second, r_values.second), t->w);\n\t\t}\n\t\treturn t;\n\t}\n \n\tptt split(treap t, int x) // >= x goes to the right\n\t{\n\t\tif (!t) return mp(t, t);\n \n\t\tif (x <= t->x)\n\t\t{\n\t\t\tptt p = split(t->l, x);\n\t\t\tt->l = p.second;\n \n\t\t\treturn mp(p.first, mend(t));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tptt p = split(t->r, x);\n\t\t\tt->r = p.first;\n \n\t\t\treturn mp(mend(t), p.second);\n\t\t}\n\t}\n \n\ttreap merge(treap u, treap v)\n\t{\n\t\tif (!u) return v;\n\t\tif (!v) return u;\n \n\t\tif (u->y > v->y)\n\t\t{\n\t\t\tu->r = merge(u->r, v);\n\t\t\treturn mend(u);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tv->l = merge(u, v->l);\n\t\t\treturn mend(v);\n\t\t}\n\t}\n \npublic:\n\ttree() {}\n \n\tvoid insert(int x, int w)\n\t{\n\t\tptt p = split(root, x);\n \n\t\tptt q = split(p.second, x + 1);\n \n\t\tif (!q.first)\n\t\t\troot = merge(merge(p.first, new node(x, w)), p.second);\n\t\telse\n\t\t{\n\t\t\tq.first->s++;\n\t\t\tq.first->w = mul(q.first->w, w);\n \n\t\t\tq.first = mend(q.first);\n \n\t\t\troot = merge(merge(p.first, q.first), q.second);\n\t\t}\n\t}\n \n\tpair<int, int> range(int x, bool flag) // 0 = [-inf, x), 1 = [x, +inf)\n\t{\n\t\tptt p = split(root, x);\n \n\t\tpair<int, int> rv = values(flag ? p.second : p.first);\n \n\t\troot = merge(p.first, p.second);\n \n\t\treturn rv;\n\t}\n \n\tvoid clear()\n\t{\n\t\troot = nullptr;\n\t}\n};\n \nnamespace cd\n{\n\tstruct edge\n\t{\n\t\tint to, w;\n\t\tbool color; // 1 = black, 0 = white\n\t};\n \n\tstruct path\n\t{\n\t\tint product, w_count, b_count;\n\t};\n \n\tll ans = 1;\n \n\tvector<edge> g[N];\n\tint n, lv[N];\n \n\tvoid add_edge(int u, int v, int w, bool color)\n\t{\n\t\tg[u].push_back({ v, w, color });\n\t\tg[v].push_back({ u, w, color });\n\t}\n \n\tint dfs(int u, int s, int &center, int e = -1)\n\t{\n\t\tint sz = 1;\n\t\tfor (auto v : g[u])\n\t\t\tif (lv[v.to] == -1 && v.to != e)\n\t\t\t\tsz += dfs(v.to, s, center, u);\n \n\t\tif (center == -1 && (2 * sz >= s || e == -1))\n\t\t\tcenter = u;\n\t\treturn sz;\n\t}\n \n\tvector<path> data;\n \n\tvoid calc(int u, int w_count = 0, int b_count = 0, int product = 1, int e = -1)\n\t{\n\t\tdata.push_back({ product, w_count, b_count });\n \n\t\tfor (auto v : g[u])\n\t\t\tif (lv[v.to] == -1 && v.to != e)\n\t\t\t\tcalc(v.to, w_count + !v.color, b_count + v.color, mul(product, v.w), u);\n\t}\n \n\tvoid cdc(int u, int s, int level = 0, int e = -1)\n\t{\n\t\tint center = -1;\n\t\tdfs(u, s, center);\n \n\t\tlv[center] = level;\n \n\t\ttree prefix = tree(), suffix = tree();\n \n\t\tint pos = 1, neg = 1;\n \n\t\tfor (auto v : g[center])\n\t\t\tif (lv[v.to] == -1)\n\t\t\t{\n\t\t\t\tdata.clear();\n\t\t\t\tcalc(v.to, !v.color, v.color, v.w);\n \n\t\t\t\tfor (auto v : data)\n\t\t\t\t{\n\t\t\t\t\t// (size, value)\n\t\t\t\t\tpair<int, int> positive = suffix.range(v.b_count - 2 * v.w_count, true);\n\t\t\t\t\tpair<int, int> negative = prefix.range(v.w_count - 2 * v.b_count, false);\n \n\t\t\t\t\t// *= dp_positive * product ^ size_positive\n\t\t\t\t\t// /= dp_negative * product ^ size_negative\n \n\t\t\t\t\t// -> dp_positive / dp_negative * product ^ (size_positive - size_negative)\n \n\t\t\t\t\t//pair<int, int> combine = mp(positive.first - negative.first, divide(positive.second, negative.second));\n \n\t\t\t\t\tpos = mul(pos, positive.second), neg = mul(neg, negative.second);\n \n\t\t\t\t\tans = mul(ans, mpow(v.product, positive.first - negative.first));\n \n\t\t\t\t\tif (min(v.w_count, v.b_count) * 2 >= max(v.w_count, v.b_count))\n\t\t\t\t\t\tans = mul(ans, v.product);\n\t\t\t\t}\n \n\t\t\t\tfor (auto v : data)\n\t\t\t\t{\n\t\t\t\t\tsuffix.insert(2 * v.w_count - v.b_count, v.product);\n\t\t\t\t\tprefix.insert(2 * v.b_count - v.w_count, v.product);\n\t\t\t\t}\n\t\t\t}\n \n\t\tans = mul(ans, divide(pos, neg));\n \n\t\tfor (auto v : g[center])\n\t\t\tif (lv[v.to] == -1)\n\t\t\t\tcdc(v.to, s / 2, level + 1, center);\n\t}\n \n\tll run()\n\t{\n\t\tfill_n(lv, N, -1);\n\t\tcdc(1, n);\n \n\t\treturn ans;\n\t}\n}\n \nint main()\n{\n\tscanf(\"%d\", &cd::n);\n \n\tint u, v, w;\n\tint color;\n \n\tforn(i, cd::n - 1)\n\t{\n\t\tscanf(\"%d %d %d %d\", &u, &v, &w, &color);\n\t\tcd::add_edge(u, v, w, color);\n\t}\n \n\tprintf(\"%I64d\\n\", cd::run());\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "implementation",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "833",
    "index": "E",
    "title": "Caramel Clouds",
    "statement": "It is well-known that the best decoration for a flower bed in Sweetland are vanilla muffins. Seedlings of this plant need sun to grow up. Slastyona has $m$ seedlings, and the $j$-th seedling needs at least $k_{j}$ minutes of sunlight to grow up.\n\nMost of the time it's sunny in Sweetland, but sometimes some caramel clouds come, the $i$-th of which will appear at time moment (minute) $l_{i}$ and disappear at time moment $r_{i}$. Of course, the clouds make shadows, and the seedlings can't grow when there is at least one cloud veiling the sun.\n\nSlastyona wants to grow up her muffins as fast as possible. She has exactly $C$ candies, which is the main currency in Sweetland.\n\nOne can dispel any cloud by paying $c_{i}$ candies. However, in order to comply with Sweetland's Department of Meteorology regulations, \\textbf{one can't dispel more than two clouds}.\n\nSlastyona hasn't decided yet which of the $m$ seedlings will be planted at the princess' garden, so she needs your help. For each seedling determine the earliest moment it can grow up if Slastyona won't break the law and won't spend more candies than she has. Note that each of the seedlings is considered independently.\n\nThe seedlings start to grow at time moment $0$.",
    "tutorial": "Prequisites: scanline. The key idea is that only minutes which are covered by no more than two clouds can contribute to the answer. Let us demonstrate how to solve the problem for a fixed $k$ using scanline. Let's create $2 \\cdot n$ events: for the start and the end of each cloud. We will then go through all the events in ascending order of their coordinates, maintaining the following values: the set of active clouds $open$; the count of sunny (from the beginning!) minutes $free$; the array $single(i)$, which denotes the number of minutes covered solely by cloud $i$; the variable $top$ - the largest number of sunny minutes we can obtain on a given prefix by deleting no more than two clouds; the sparse table $cross$, whose element $(a, b)$ holds the number of minutes of sunny minutes covered solely by $a$ and $b$; and finally, the array $opt(i)$ - the optimal number of sunny minutes we can obtain if we dispel $i$-th cloud as one of the selected ones. We will also construct a treap (or BIT/segment tree if we want to), where each leaf has the index in form of the pair $cost(i), i$, keeping best index relative to $single(i)$ in the subtree in each node. So, let us assume we are now considering some event with the coordinate $x$, which is going to add some segment with length $len$. If $open$ is empty, it's enough to just increase $free$ by $len$. If $open$ contains exactly two elements (let's denote them as $a$ and $b$), we need to increase $cross[a, b]$ by $len$ and try to update $opt(a)$ via using $b$ and $opt(b)$ via using $a$ if it's possible (i.e. if the sum of costs does not exceed the budget). The case when $open$ only one element is the most interesting. We have to try to increase both $single(a)$ and $opt(a)$ by len consequently. What clouds may optima have also updated for? Obviously, for every cloud which cost allows us to dispel it together the cloud $a$. But it's only necessary to update $opt$ only for cloud with maximal $single(x)$ (don't forget to delete $a$ from the tree) on range $[0..C - cost(a)]$. Why? We leave this as an excercise for the reader. After that, we will either need to remove the start of the cloud from $open$ if we are dealing with a closing event, or to put it into $open$ otherwise. Along with aforementioned operations we can also update the variable $top$. It's not that hard to observe that if $free + top  \\ge  k$, the answer would be some point of the last segment: we can find it as $x - (free + top) - k$. It's also worth noting that if we are to order all the queries in the non-descending order, the answers would be ordered the same way. We can then process them in one go. Time complexity: $O(n\\log(n)+m\\log(m))$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <unordered_set>\n#include <vector>\n#include <cmath>\n#include <string>\n#include <set>\n#include <map>\n#include <cstdio>\n#include <functional>\n#include <random>\n#include <ctime>\n#include <cassert>\n#include <bitset>\n#include <unordered_map>\n#include <math.h>\n#include <queue>\n \nusing namespace std;\n \n#define N 300005\n#define M 5000005\n#define F 200\nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define fornv(i, n) for (int i = n - 1; i >= 0; i--)\n#define pii pair<int, int>\n#define forlr(i, l, r) for (int i = l; i <= r; i++)\n#define forlrv(i, l, r) for (int i = r; i >= l; i--)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define mp make_pair\ntypedef long long ll;\ntypedef unsigned long long ull;\nconst long double eps = 1e-9;\nconst int inf = 1e9;\nconst int mod = 1e9 + 7;\nconst ll infinity = 2 * 1e18;\n#define p p2\n#define endl '\\n'\n \nstruct cloud\n{\n\tint l, r, c;\n};\n \ncloud cl[N];\nint n, C, m;\n \nstruct event\n{\n\tint x, t, i;\n\tbool operator < (const event &other)\n\t{\n\t\tif (x != other.x) return x < other.x;\n\t\tif (t != other.t) return t < other.t;\n\t\treturn i < other.i;\n\t}\n};\n \nint single[N], opt[N];\nmap<int, int> cross[N];\n \nclass tree\n{\nprivate:\n\tstruct node\n\t{\n\t\tnode *l = nullptr, *r = nullptr;\n\t\tint y = gen(), dp = -1;\n\t\tpii x = mp(0, 0);\n \n\t\tnode(pii x) : x(x), dp(x.second) {}\n\t};\n \n\ttypedef node * treap;\n\ttypedef pair<treap, treap> ptt;\n \n\ttreap root = nullptr;\n \n\tint choose(int u, int v)\n\t{\n\t\tif (u == -1) return v;\n\t\tif (v == -1) return u;\n\t\treturn (single[u] > single[v]) ? u : v;\n\t}\n \n\tint dp(treap t)\n\t{\n\t\treturn (t ? t->dp : -1);\n\t}\n \n\ttreap mend(treap t)\n\t{\n\t\tif (!t) return t;\n \n\t\tt->dp = choose(t->x.second, choose(dp(t->l), dp(t->r)));\n \n\t\treturn t;\n\t}\n \n\tptt split(treap t, pii x) // >= x goes to the right\n\t{\n\t\tif (!t) return mp(t, t);\n \n\t\tif (x <= t->x)\n\t\t{\n\t\t\tptt p = split(t->l, x);\n\t\t\tt->l = p.second;\n \n\t\t\treturn mp(p.first, mend(t));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tptt p = split(t->r, x);\n\t\t\tt->r = p.first;\n \n\t\t\treturn mp(mend(t), p.second);\n\t\t}\n\t}\n \n\ttreap merge(treap u, treap v)\n\t{\n\t\tif (!u) return v;\n\t\tif (!v) return u;\n \n\t\tif (u->y > v->y)\n\t\t{\n\t\t\tu->r = merge(u->r, v);\n\t\t\treturn mend(u);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tv->l = merge(u, v->l);\n\t\t\treturn mend(v);\n\t\t}\n\t}\n \n \npublic:\n\ttree() {}\n \n\tvoid insert(int i)\n\t{\n\t\tptt p = split(root, mp(cl[i].c, i));\n\t\troot = merge(merge(p.first, new node(mp(cl[i].c, i))), p.second);\n\t}\n \n\tvoid erase(int i)\n\t{\n\t\tptt p = split(root, mp(cl[i].c, i));\n\t\tptt q = split(p.second, mp(cl[i].c, i + 1));\n\t\troot = merge(p.first, q.second);\n\t}\n \n\tint go(int c)\n\t{\n\t\tptt p = split(root, mp(c + 1, -1));\n \n\t\tint\tret = dp(p.first);\n \n\t\troot = merge(p.first, p.second);\n\t\treturn ret;\n\t}\n};\n \npii q[N];\nint ans[N];\n \nvoid solve()\n{\n\tif (!n) {\n\t\tforn(i, m)\n\t\t\tans[q[i].second] = q[i].first;\n\t\treturn;\n\t}\n \n\tvector<event> e;\n \n\tforn(i, n)\n\t{\n\t\tauto &y = cl[i];\n\t\te.push_back({ y.l, 0, i });\n\t\te.push_back({ y.r, 1, i });\n\t}\n \n\tsort(e.begin(), e.end());\n \n\tint last = 0, free = 0, j = 0;\n \n\tint top = 0;\n \n\tset<int> open;\n \n\ttree root = tree();\n \n\tfor (auto v : e)\n\t{\n\t\tif (open.size() == 0)\n\t\t\tfree += v.x - last;\n\t\telse\n\t\t\tif (open.size() == 1 && cl[*open.begin()].c <= C)\n\t\t\t{\n\t\t\t\tint a = *open.begin();\n\t\t\t\troot.erase(a);\n \n\t\t\t\tsingle[a] += v.x - last;\n\t\t\t\topt[a] += v.x - last;\n \n\t\t\t\ttop = max(top, opt[a]);\n \n\t\t\t\tint chosen = root.go(C - cl[a].c);\n\t\t\t\tif (chosen != -1)\n\t\t\t\t{\n\t\t\t\t\tint u = single[a] + single[chosen] + (cross[a].count(chosen) ? cross[a][chosen] : 0);\n\t\t\t\t\topt[a] = max(opt[a], u);\n\t\t\t\t\ttop = max(top, opt[a]);\n\t\t\t\t}\n \n\t\t\t\troot.insert(a);\n\t\t\t}\n\t\t\telse if (open.size() == 2)\n\t\t\t{\n\t\t\t\tint a = *open.begin(), b = *open.rbegin();\n \n\t\t\t\tif (cl[a].c + cl[b].c <= C)\n\t\t\t\t{\n\t\t\t\t\tcross[a][b] += v.x - last, cross[b][a] += v.x - last;\n\t\t\t\t\topt[a] = max(opt[a], single[a] + single[b] + cross[a][b]);\n\t\t\t\t\topt[b] = max(opt[b], single[a] + single[b] + cross[a][b]);\n \n\t\t\t\t\ttop = max(top, max(opt[a], opt[b]));\n\t\t\t\t}\n\t\t\t}\n \n\t\tfor (; j < m && top + free >= q[j].first; j++)\n\t\t\tans[q[j].second] = (v.x - (top + free - q[j].first));\n \n\t\tlast = v.x;\n \n\t\tif (v.t)\n\t\t\topen.erase(v.i);\n\t\telse\n\t\t\topen.insert(v.i);\n\t}\n \n\tfor (; j < m; j++)\n\t\tans[q[j].second] = e.back().x - (top + free - q[j].first);\n}\n \nint main()\n{\n\t//ios_base::sync_with_stdio(0);\n\t//cin.tie(0);\n \n\tint k;\n\tscanf(\"%d %d\", &n, &C);\n \n\tint l, r, c;\n\tforn(i, n)\n\t{\n\t\tscanf(\"%d %d %d\", &l, &r, &c);\n\t\tcl[i] = { l, r, c };\n\t}\n \n\tint y;\n \n\tscanf(\"%d\", &m);\n\tforn(i, m)\n\t{\n\t\tscanf(\"%d\", &y);\n\t\tq[i] = mp(y, i);\n\t}\n \n\tsort(q, q + m);\n \n\tsolve();\n \n\tforn(i, m)\n\t\tprintf(\"%d\\n\", ans[i]);\n}",
    "tags": [
      "data structures",
      "dp",
      "sortings"
    ],
    "rating": 3400
  },
  {
    "contest_id": "834",
    "index": "A",
    "title": "The Useless Toy",
    "statement": "Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption.\n\nSpinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one):\n\nAfter the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in.\n\nSlastyona managed to have spinner rotating for exactly $n$ seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.",
    "tutorial": "Prequisites: none. The sole fact that the spinner has four positions, which are repeated periodically, leads us to the following observations that are easily verifiable: first thing is that no matter what the direction was, when $k$ is even we're going to get the same ending position; secondly, if we replace $n$ by $n{\\mathrm{~mod~}}4$, the resulting problem would have the same answer (basically we have removed full rotations of the spinner from consideration). Thus, if $n{\\mathrm{~mod~}}2=0$, the answer is \"undefined\". Otherwise, we have to find the aforementioned remainder and find the direction of the spin, which is pretty straightforward. Time complexity: $O(1)$.",
    "code": "DIRS = ['v', '<', '^', '>']\n \na, b = map(DIRS.index, input().split())\nn = int(input())\n \ndelta = (b - a + 4) % 4\n \nif delta == 0 or delta == 2:\n    print('undefined')\nelif delta == n % 4:\n    print('cw')\nelse:\n    print('ccw')",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "834",
    "index": "B",
    "title": "The Festive Evening",
    "statement": "It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in.\n\nThere are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously.\n\nFor an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are $k$ such guards in the castle, so if there are more than $k$ opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed.\n\nSlastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than $k$ doors were opened.",
    "tutorial": "Prerequisites: none. This problem is solved with two linear sweeps. In the first one, we determine the last position for each letter. In the second one, we just model the process: we mark the letter as active when we stumble upon it for the first time, and as inactive when we reach the last position for this letter. If there are more than $k$ letters active at some specific point of time, we output \"YES\". Otherwise, we output \"NO\". Time complexity: $O(n)$.",
    "code": "#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n \nusing namespace std;\n \nunordered_map<char, int> last_pos;\nunordered_set<char> active;\n \nint main()\n{\n    int n, k;\n    string s;\n    cin >> n >> k >> s;\n \n    for (int i = 0; i < n; i++) {\n        last_pos[s[i]] = i;\n    }\n \n    for (int i = 0; i < n; i++) {\n        active.insert(s[i]);\n        if (active.size() > k) {\n            cout << \"YES\" << endl;\n            return 0;\n        }\n        if (last_pos[s[i]] == i)\n            active.erase(s[i]);\n    }\n \n    cout << \"NO\" << endl;\n    return 0;\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "835",
    "index": "A",
    "title": "Key races",
    "statement": "Two boys decided to compete in text typing on the site \"Key races\". During the competition, they have to type a text consisting of $s$ characters. The first participant types one character in $v_{1}$ milliseconds and has ping $t_{1}$ milliseconds. The second participant types one character in $v_{2}$ milliseconds and has ping $t_{2}$ milliseconds.\n\nIf connection ping (delay) is $t$ milliseconds, the competition passes for a participant as follows:\n\n- Exactly after $t$ milliseconds after the start of the competition the participant receives the text to be entered.\n- Right after that he starts to type it.\n- Exactly $t$ milliseconds after he ends typing all the text, the site receives information about it.\n\nThe winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.\n\nGiven the length of the text and the information about participants, determine the result of the game.",
    "tutorial": "Information on the success of the first participant will come in $2 \\cdot t_{1} + v_{1} \\cdot s$ milliseconds, of the second participant - in $2 \\cdot t_{2} + v_{2} \\cdot s$ milliseconds. We need to compare these numbers and print the answer depending on the comparison result.",
    "code": "s, v1, v2, t1, t2 = map(int, input().split())\nq1 = 2 * t1 + s * v1\nq2 = 2 * t2 + s * v2\nif q1 < q2:\n    print('First')\nelif q1 > q2:\n    print('Second')\nelse:\n    print('Friendship')\n ",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "835",
    "index": "B",
    "title": "The number on the board",
    "statement": "Some natural number was written on the board. Its sum of digits was not less than $k$. But you were distracted a bit, and someone changed this number to $n$, replacing some digits with others. It's known that the length of the number didn't change.\n\nYou have to find the minimum number of digits in which these two numbers can differ.",
    "tutorial": "Let's rephrase the problem a little. Suppose that we initially have a number $n$ and we need to make a number from it with the sum of digits at least $k$, changing as fewer digits as possible. Obviously, it is optimal to replace the digit with $9$. When we replace digit $d$ with $9$, we increase the sum by $9 - d$. It means it's optimal to replace the minimal digit. Let $cnt_{i}$ be the number of occurrences of the digit $i$ in $n$. While the sum is less than $k$ we will repeat this Find minimal $i$ that $cnt_{i} > 0$. Decrease $cnt_{i}$ by $1$. Increase the answer by $1$. Increase the sum by $9 - i$ It's not hard to prove, that algorithm makes as less replaces as possible. Alogithm works in $O(\\log_{10}n)$ time and $O(1)$ additional memory.",
    "code": "k = int(input())\nn = input()\n \ndigits = []\n \nfor c in n:\n    digits.append(ord(c) - ord('0'))\n \ndigits.sort()\ncur = sum(digits)\nans = 0\n \nfor d in digits:\n    if cur < k:\n        cur += 9 - d\n        ans += 1\n \nprint(ans)\n ",
    "tags": [
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "835",
    "index": "C",
    "title": "Star sky",
    "statement": "The Cartesian coordinate system is set in the sky. There you can see $n$ stars, the $i$-th has coordinates ($x_{i}$, $y_{i}$), a maximum brightness $c$, equal for all stars, and an initial brightness $s_{i}$ ($0 ≤ s_{i} ≤ c$).\n\nOver time the stars twinkle. At moment $0$ the $i$-th star has brightness $s_{i}$. Let at moment $t$ some star has brightness $x$. Then at moment $(t + 1)$ this star will have brightness $x + 1$, if $x + 1 ≤ c$, and $0$, otherwise.\n\nYou want to look at the sky $q$ times. In the $i$-th time you will look at the moment $t_{i}$ and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates ($x_{1i}$, $y_{1i}$) and the upper right — ($x_{2i}$, $y_{2i}$). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.\n\nA star lies in a rectangle if it lies on its border or lies strictly inside it.",
    "tutorial": "The brightness of the $i$-th star in moment $t$ is $(s_{i}+t_{i})~\\mathrm{mod}~(c+1)$, where $\\mathrm{mod}$ is modulo operator. Let's precalc for each $p = 0...C$, $x = 1...100$, $y = 1...100$ $cnt[p][x][y]$ - the number of stars with the initial brightness $p$ in the rectangle ($1$; $1$)-($x$; $y$). It is calculated like calcuating of partial sums: $cnt[p][x][y] = cnt[p][x - 1][y] + cnt[p][x][y - 1] - cnt[p][x - 1][y - 1] + (the number of stars in the point (x;y) with the initial brightness p)$. Then the total brightness of stars at the $i$-th view is $\\sum_{p=0}^{c}\\big((p+t_{i})\\,\\bmod\\,\\big(c+1\\big)\\big)\\star\\mathrm{amount}\\big(p,x_{1i},y_{1i},x_{2i},y_{2i}\\big)$, where $\\operatorname{amount}(p,x_{1},y_{1},x_{2},y_{2})$ is the number of stars with the initial brightness $p$ in the given rectangle. This number can be calculated using array $\\mathrm{cnt}$, using the inclusion-exclusion principle: $amount(p, x_{1}, y_{1}, x_{2}, y_{2}) = cnt[p][x_{2}][y_{2}] - cnt[p][x_{1} - 1][y_{2}] - cnt[p][x2][y_{1} - 1] + cnt[p][x_{1} - 1][y_{1} - 1]$. Let $X$ is the maximum coordinate. Time complexity: $O(n + qc + cX^{2})$. Memory complexity: $O(cX^{2})$.",
    "code": "import java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.OutputStreamWriter;\nimport java.util.Scanner;\n \npublic class Main {\n    public static void main(String[] args) throws IOException {\n        new Solution().run();\n    }\n}\n \nclass Solution {\n    final int MAX_CORD = 100;\n \n    Scanner in;\n    BufferedWriter out;\n    int n, q, c;\n    int cnt[][][];\n \n    int get(int t, int x1, int y1, int x2, int y2) {\n        int res = 0;\n        for (int i = 0; i <= c; i++) {\n            int brightness = (i + t) % (c + 1);\n            int amount = cnt[i][x2][y2] - cnt[i][x1 - 1][y2] - cnt[i][x2][y1 - 1] + cnt[i][x1 - 1][y1 - 1];\n            res += amount * brightness;\n        }\n        return res;\n    }\n \n    void run() throws IOException {\n        in = new Scanner(System.in);\n        out = new BufferedWriter(new OutputStreamWriter(System.out));\n        n = in.nextInt();\n        q = in.nextInt();\n        c = in.nextInt();\n        cnt = new int[c + 1][MAX_CORD + 1][MAX_CORD + 1];\n        for (int i = 0; i < n; i++) {\n            int x = in.nextInt();\n            int y = in.nextInt();\n            int s = in.nextInt();\n            cnt[s][x][y]++;\n        }\n \n        for (int p = 0; p <= c; p++) {\n            for (int i = 1; i <= MAX_CORD; i++) {\n                for (int j = 1; j <= MAX_CORD; j++) {\n                    cnt[p][i][j] += cnt[p][i - 1][j] + cnt[p][i][j - 1] - cnt[p][i - 1][j - 1];\n                }\n            }\n        }\n \n        for (int i = 0; i < q; i++) {\n            int t = in.nextInt();\n            int x1 = in.nextInt();\n            int y1 = in.nextInt();\n            int x2 = in.nextInt();\n            int y2 = in.nextInt();\n            out.write(get(t, x1, y1, x2, y2) + \"\\n\");\n        }\n \n        out.flush();\n    }\n}",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "835",
    "index": "D",
    "title": "Palindromic characteristics",
    "statement": "Palindromic characteristics of string $s$ with length $|s|$ is a sequence of $|s|$ integers, where $k$-th number is the total number of non-empty substrings of $s$ which are $k$-palindromes.\n\nA string is $1$-palindrome if and only if it reads the same backward as forward.\n\nA string is $k$-palindrome ($k > 1$) if and only if:\n\n- Its left half equals to its right half.\n- Its left and right halfs are non-empty ($k - 1$)-palindromes.\n\nThe left half of string $t$ is its prefix of length $⌊|t| / 2⌋$, and right half — the suffix of the same length. $⌊|t| / 2⌋$ denotes the length of string $t$ divided by $2$, rounded down.\n\nNote that each substring is counted as many times as it appears in the string. For example, in the string \"aaa\" the substring \"a\" appears 3 times.",
    "tutorial": "Observation I. If the string is $k$-palindrome, then it is ($k - 1$)-palindrome. Observation II. The string is $k$-palindrome if and only if the both following conditions are true: It is a palindrome. It's left half is non-empty ($k - 1$)-palindrome. Solution. Let's calculate the following dp. $dp[l][r]$ is the maximum $k$ such that the substring built from characters from $l$ to $r$ is $k$-palindrome. The dynamics is calculated in the order of non-decreasing of substring lengths. The values for $l = r$ and $l = r - 1$ are computed trivially. Let $r - l > 1$. Then, if $s[l]  \\neq  s[r]$ or $dp[l + 1][r - 1] = 0$, $dp[l][r] = 0$. Otherwise $dp[l][r] = dp[l][m] + 1$, where $m=\\left\\lceil{\\frac{l+r}{2}}\\right\\rceil-1$. When we have dp values, we can calculate $cnt[k]$ - the number of substrings, which dp value is $k$. Then the number of substrings that are $k$-palindromes is $a n s[k]=\\sum_{i=k}^{\\mathrm{sl}}c n t[i]$. The solution works in $O(|s|^{2})$ time and uses $O(|s|^{2})$ memory. Also, you could notice that the string can be no more than $\\left|\\log_{2}\\left|s\\right|$-palindrome, and solve the problem in $O(|s|^{2}\\log|s|)$ time, reducing the memory usage to $O(|s|)$.",
    "code": "s = input()\nn = len(s)\n \ndp = [[0 for i in range(n - le + 1)] for le in range(n + 1)]\nans = [0 for i in range(n + 1)]\n \nfor le in range(1, n + 1):\n    for l in range(0, n - le + 1):\n        r = l + le\n        if s[l] != s[r - 1]:\n            continue\n        if le == 1:\n            dp[1][l] = 1\n            ans[1] += 1\n        elif le == 2:\n            ans[2] += 1\n            dp[2][l] = 2\n        elif dp[le - 2][l + 1]:\n            v = 1\n            m = (l + r) // 2\n            st = m + 1 if le & 1 else m\n            le2 = m - l\n            q = dp[le2][l]\n            if q:\n                v = q + 1\n \n            ans[v] += 1\n            dp[le][l] = v\n \n \nfor i in range(n - 1, 0, -1):\n    ans[i] += ans[i + 1]\n \nprint(*ans[1:])",
    "tags": [
      "brute force",
      "dp",
      "hashing",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "835",
    "index": "E",
    "title": "The penguin's game",
    "statement": "Pay attention: this problem is interactive.\n\nPenguin Xoriy came up with a new game recently. He has $n$ icicles numbered from $1$ to $n$. Each icicle has a temperature — an integer from $1$ to $10^{9}$. \\textbf{Exactly two} of these icicles are special: their temperature is $y$, while a temperature of all the others is $x ≠ y$. You have to find those special icicles. You can choose a non-empty subset of icicles and ask the penguin what is the bitwise exclusive OR (XOR) of the temperatures of the icicles in this subset. Note that you can't ask more than \\textbf{19} questions.\n\nYou are to find the special icicles.",
    "tutorial": "The solution can be separated into several parts. I. Finding the parity of the number of special icicles in the given subset using 1 question. Consider the following cases: Subset's size is even, the number of special icicles in it is even. Then the answer to such question is $0$. Subset's size is even, the number of special icicles in it is odd. Then the answer to such question is $x\\oplus y$. Subset's size is odd, the number of special icicles in it is even. Then the answer to such question is $x$. Subset's size is odd, the number of special icicles in it is odd. Then the answer to such question is $y$. $x, y  \\ge  1$ and $x  \\neq  y$, so the numbers $0$, $x$, $y$, $x\\oplus y$ are pairwise distinct. Therefore, we can find the parity of the number of special icicles on the given subset using 1 question. II. The solution for the problem for the only one special icicle. Suppose we have $n$ icicles, and one of them is special. Then you can find it using $\\lceil\\log_{2}n\\rceil$ questions. The algorithm is to use binary search over the minimum prefix that contains the special icicle. III. The solution of our problem. Each integer $n  \\le  1000$ can be written using no more than $\\lfloor\\log_{2}n\\rfloor+1$ bits. Iterate over the bits from $0$ to $\\lfloor\\log_{2}n\\rfloor$. Ask a question about the icicles that have $1$ in their numbers in the fixed bit. After that, we can determine if the numbers of the special icicles differ in this bit. Really, the bits differ if this subset's size is odd, and don't differ otherwise. Obviously, we will find at least one bit, where their numbers differ. Let $A$ is the subset of the icicles that have $1$ in this bit, and $B$ is the complement set. Let $m$ is the size of the smallest from these subsets. Then $m\\leq{\\frac{n}{2}}$. Let's solve the problem for the only one special icicle for the smallest of these subsets. Then it's easy to get the number of the other icicle: we know the number of the first icicle and we know in which bits the numbers differ and in which don't. This solution uses 19 question. It can be proven that in the given constraints you can't solve this problem in less than 19 questions.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint n, x, y;\n \nint ask(const vector<int> &a) {\n    if (a.empty()) {\n        return 0;\n    }\n    cout << \"? \";\n    cout << a.size() << \" \";\n    for (int el : a) {\n        cout << el << \" \";\n    }\n    cout << endl;\n    int res;\n    cin >> res;\n    return res;\n}\n \nint solve(const vector<int> &a) {\n    int left = 0;\n    int right = (int) a.size();\n    \n    while (right - left > 1) {\n        int mid = (left + right) / 2;\n        \n        vector<int> b;\n        for (int i = left; i < mid; i++) {\n            b.push_back(a[i]);\n        }\n        \n        int cur = ask(b);\n        if (cur == y || cur == (x ^ y)) {\n            right = mid;\n        } else {\n            left = mid;\n        }\n    }\n    \n    return a[left];\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    cin >> n >> x >> y;\n    \n    int diff = 0;\n    int diff_bit = -1;\n    \n    for (int bit = 0; bit <= 9; bit++) {\n        vector<int> a;\n        for (int i = 1; i <= n; i++) {\n            if (i & (1 << bit)) {\n                a.push_back(i);\n            }\n        }\n        \n        int cur = ask(a);\n        if (cur == y || cur == (x ^ y)) {\n            diff |= (1 << bit);\n            diff_bit = bit;\n        }\n    }\n    \n    assert(diff > 0 && diff_bit != -1);\n    \n    vector<int> a, b;\n    for (int i = 1; i <= n; i++) {\n        if (i & (1 << diff_bit)) {\n            a.push_back(i);\n        } else {\n            b.push_back(i);\n        }\n    }\n    \n    if (a.size() > b.size()) {\n        swap(a, b);\n    }\n    \n    int pos1 = solve(a);\n    int pos2 = pos1 ^ diff;\n    if (pos1 > pos2) {\n        swap(pos1, pos2);\n    }\n    cout << \"! \" << pos1 << \" \" << pos2 << endl;\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2400
  },
  {
    "contest_id": "835",
    "index": "F",
    "title": "Roads in the Kingdom",
    "statement": "In the Kingdom K., there are $n$ towns numbered with integers from $1$ to $n$. The towns are connected by $n$ bi-directional roads numbered with integers from $1$ to $n$. The $i$-th road connects the towns $u_{i}$ and $v_{i}$ and its length is $l_{i}$. There is no more than one road between two towns. Also, there are no roads that connect the towns with itself.\n\nLet's call the inconvenience of the roads the maximum of the shortest distances between all pairs of towns.\n\nBecause of lack of money, it was decided to close down one of the roads so that after its removal it is still possible to reach any town from any other. You have to find the minimum possible inconvenience of the roads after closing down one of the roads.",
    "tutorial": "Observation I. The given graph is a cycle with hanged trees. So, we can remove the edge only from the cycle, the resulting graph will be a tree. Observation II. We can minimize the distances only between the pairs of vertexes such that path between them goes through the cycle's edges. Let's say that these pairs are interesting. Solution. Let's find the cycle using dfs. Let its length be $k$. Let's number the vertices in it from $1$ to $k$ in round order. We will try to remove edges between $1$ and $2$, $2$ and $3$, ..., $1$ and $k$ and calculate the maximum distance between the interesting pairs. We need to pre-compute the following: $d_{i}$ - the maximum depth of the tree hanged to the $i$-th vertex of the cycle. $w_{i}$ - the length of the edge between the $i$-th vertex of the cycle and the next in the round order. $pref_diam_{i}$ - the maximum distance between the interesting pairs such that their vertexes are in the trees hanged to the vertexes $1$, $2$, ..., $i$ of the cycle. $suff_diam_{i}$ - the maximum distance between the interesting pairs such that their vertexes are in the trees hanged to the vertexes $i$, $i + 1$, ..., $k$ of the cycle. $pref_far_{i}$ - the maximum distance from the first vertex of the cycle to the vertexes that are in the trees hanged to the vertexes $1$, $2$, ..., $i$ of the cycle. $suff_far_{i}$ - the maximum distance from the first vertex of the cycle to the vertexes that are in the trees hanged to the vertexes $i$, $i + 1$, ..., $k$ of the cycle. Also $suff_diam_{k + 1} = suff_far_{k + 1} = -  \\infty $. These pre-computations can be done in linear time. If we delete the edge between the $i$-th vertex of the cycle and the next in the round order, then the maximum distance between the interesting pairs is $max(pref_far[i] + suff_far[i + 1], pref_diam[i], suff_diam[i + 1])$. After we found the optimal edge to remove, we remove it and find the diameter of the resulting tree. It can be done with 2 dfs'es. Let vertex $v$ be the farest from $1$. Let vertex $u$ be the farest from $v$. It's easy to prove that the path between $u$ and $v$ is the diameter. Time complexity: $O(n)$. Memory complexity: $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <algorithm>\n \nusing namespace std;\n \nconst int N = (int) 2e5 + 2;\nconst long long INF = (long long) 1e18 + 123;\n \nint n;\nvector<pair<int, int>> g[N];\nvector<int> cycle;\nint color[N];\nbool vis[N];\nlong long depth[N], weight[N];\nlong long pref_diam[N], suff_diam[N];\nlong long pref_far[N], suff_far[N];\n \nint dfs(int v, int from = -1) {\n\tstatic int cycle_start = -1;\n\tcolor[v] = 1;\n\tfor (auto &e : g[v]) {\n\t\tint u = e.first;\n\t\tif (u == from) {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (color[u] == 1) {\n\t\t\tcycle.push_back(v);\n\t\t\tcycle_start = u;\n\t\t\treturn 1;\n\t\t} else if (color[u] == 0) {\n\t\t\tint res = dfs(u, v);\n\t\t\tif (res == -1) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (res == 1) {\n\t\t\t\tcycle.push_back(v);\n\t\t\t\tif (v == cycle_start) {\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t}\n\tcolor[v] = 2;\n\treturn 0;\n}\n \npair<long long, int> farest(int v, pair<int, int> deny = {-1, -1}) {\n\tpair<long long, int> ans = {0, v};\n\tvis[v] = 1;\n\tfor (auto &e : g[v]) {\n\t\tint u = e.first;\n\t\tif (deny == make_pair(u, v) || deny == make_pair(v, u) || vis[u]) {\n\t\t\tcontinue;\n\t\t}\n\t\t\n        auto tmp = farest(u, deny);\n        tmp.first += e.second;\n\t\tans = max(ans, tmp);\n\t}\n\treturn ans;\n}\n \nlong long get_diam(pair<int, int> deny) {\n    fill(vis, vis + n + 1, 0);\n    auto tmp = farest(1, deny);\n    fill(vis, vis + n + 1, 0);\n    return farest(tmp.second, deny).first;\n}\n \nint main() {\n    scanf(\"%d\", &n);\n\tfor (int i = 0; i < n; i++) {\n\t\tint u, v, l;\n        scanf(\"%d%d%d\", &u, &v, &l);\n\t\tg[u].push_back({v, l});\n\t\tg[v].push_back({u, l});\n\t}\n\t\n\tdfs(1);\n\tint k = (int) cycle.size();\n\tassert(k >= 3);\n\t\n\tfor (int v : cycle) {\n\t\tvis[v] = 1;\n\t}\n\tfor (int i = 0; i < k; i++) {\n\t\tdepth[i] = farest(cycle[i]).first;\n\t}\n    cycle.push_back(cycle[0]);\n\tfor (int i = 0; i < k; i++) {\n\t\tint v = cycle[i];\n\t\tint u = cycle[i + 1];\n\t\tfor (auto &e : g[v]) {\n\t\t\tif (e.first == u) {\n\t\t\t\tweight[i] = e.second;\n\t\t\t}\n\t\t}\n\t}\n    \n    pref_diam[0] = depth[0];\n    pref_far[0] = depth[0];\n    long long cur_len = 0;\n    long long cur_far = -INF;\n    for (int i = 1; i < k; i++) {\n        cur_len += weight[i - 1];\n        cur_far = max(cur_far, depth[i - 1]) + weight[i - 1];\n        assert(cur_far >= 0);\n        pref_far[i] = max(pref_far[i - 1], cur_len + depth[i]);\n        pref_diam[i] = max(pref_diam[i - 1], cur_far + depth[i]);\n    }\n    \n    suff_diam[k] = -INF;\n    suff_far[k] = -INF;\n    cur_len = 0;\n    cur_far = -INF;\n    for (int i = k - 1; i > 0; i--) {\n        cur_len += weight[i];\n        cur_far = max(cur_far, depth[i + 1]) + weight[i];\n        assert(cur_far >= 0);\n        suff_far[i] = max(suff_far[i + 1], cur_len + depth[i]);\n        suff_diam[i] = max(suff_diam[i + 1], cur_far + depth[i]);\n    }\n    \n    pair<long long, int> ans = {INF, -1};\n    \n    for (int i = 0; i < k; i++) {\n        long long cur = max(pref_far[i] + suff_far[i + 1], max(pref_diam[i], suff_diam[i + 1]));\n        if (cur < ans.first) {\n            ans = {cur, i};\n        }\n    }\n    \n    assert(ans.second != -1);\n\tcout << get_diam({cycle[ans.second], cycle[ans.second + 1]}) << \"\\n\";\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "837",
    "index": "A",
    "title": "Text Volume",
    "statement": "You are given a text of single-space separated words, consisting of small and capital Latin letters.\n\nVolume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.\n\nCalculate the volume of the given text.",
    "tutorial": "Maintain the amount of capital letters taken by going from left to right, make it zero when you meet space. Overall complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "837",
    "index": "B",
    "title": "Flag of Berland",
    "statement": "The flag of Berland is such rectangular field $n × m$ that satisfies following conditions:\n\n- Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.\n- Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has \\textbf{exactly one color}.\n- Each color should be used in \\textbf{exactly one stripe}.\n\nYou are given a field $n × m$, consisting of characters 'R', 'G' and 'B'. Output \"YES\" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print \"NO\" (without quotes).",
    "tutorial": "There are lots of ways to check correctness. For example, you can keep boolean array with already used colors, check stripes naively and mark the color used if the stripe has single color. If all the colors are used in the end then the answer is YES. Overall complexity: $O(n \\cdot m)$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "837",
    "index": "C",
    "title": "Two Seals",
    "statement": "One very important person has a piece of paper in the form of a rectangle $a × b$.\n\nAlso, he has $n$ seals. Each seal leaves an impression on the paper in the form of a rectangle of the size $x_{i} × y_{i}$. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).\n\nA very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?",
    "tutorial": "If you can place two rectangles in some way (without rotations), then it's always possible to move one of them to the top left corner and stick the other either to the bottom of the first (and push it all the way to the left) or to the right of it (and push it all the way to the top). Now let's try all possible reorderings and rotations for every pair of seals. If there is at least one correct reordering then update the answer. Overall complexity: $O(8 \\cdot n^{2})$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "837",
    "index": "D",
    "title": "Round Subset",
    "statement": "Let's call the roundness of the number the number of zeros to which it ends.\n\nYou have an array of $n$ numbers. You need to choose a subset of exactly $k$ numbers so that the roundness of the product of the selected numbers will be maximum possible.",
    "tutorial": "Let's use dynamic programming to solve this task. Obviously, the roundness of the number is determined by minimum of powers of 2 and 5 in the number. Let $pw5_{i}$ be the maximal power of 5 in the number and $pw2_{i}$ be the maximal power of 2. Let $dp[i][j][l]$ be the maximum amount of twos we can collect by checking first $i$ numbers, taking $j$ of them with total power of five equal to $l$. It is usually called \"the knapsack problem\". There are two types of transitions. You can either take current element or skip it: $dp[i + 1][j + 1][l + pw5_{i}] = max(dp[i + 1][j + 1][l + pw5_{i}], dp[i][j][l] + pw2_{i})$ $dp[i + 1][j][l] = max(dp[i + 1][j][l], dp[i][j][l])$ The answer will be maximum of $min(i, dp[n][k][i])$ for every $i$. Also keeping this many states can cause ML, the first dimension should be stored in two layers and recalced on the fly. Overall complexity: $O(n^{3}\\cdot\\log10^{18})$.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "837",
    "index": "E",
    "title": "Vasya's Function",
    "statement": "Vasya is studying number theory. He has denoted a function $f(a, b)$ such that:\n\n- $f(a, 0) = 0$;\n- $f(a, b) = 1 + f(a, b - gcd(a, b))$, where $gcd(a, b)$ is the greatest common divisor of $a$ and $b$.\n\nVasya has two numbers $x$ and $y$, and he wants to calculate $f(x, y)$. He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.",
    "tutorial": "One important fact is that when we subtract $gcd(x, y)$ from $y$, new $gcd(x, y)$ will be divisible by old $gcd(x, y)$. And, of course, $x$ is always divisible by $gcd(x, y)$. Let's factorize $x$. Consider the moment when $gcd(x, y)$ changes. If we denote old value of $gcd(x, y)$ by $g$, the new value of $gcd(x, y)$ will be divisible by some $k \\cdot g$, where $k$ is a prime divisor of $x$. Let's check all prime divisors of $x$ and for each of these divisors find the number of times we need to subtract $g$ from $y$ to get $gcd(x, y)$ divisible by $k \\cdot g$; that is just $\\frac{y-|\\frac{r_{0}}{g}\\rangle k\\;g}$ (don't forget that $x$ also has to be divisible by $k \\cdot g$). Among all prime divisors of $x$ pick one with the minimum required number of operations (let this number of operations be $m$), add $m$ to answer, subtract $m \\cdot g$ from $y$ and repeat the process.",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "837",
    "index": "F",
    "title": "Prefix Sums",
    "statement": "Consider the function $p(x)$, where $x$ is an array of $m$ integers, which returns an array $y$ consisting of $m + 1$ integers such that $y_{i}$ is equal to the sum of first $i$ elements of array $x$ ($0 ≤ i ≤ m$).\n\nYou have an infinite sequence of arrays $A^{0}, A^{1}, A^{2}...$, where $A^{0}$ is given in the input, and for each $i ≥ 1$ $A^{i} = p(A^{i - 1})$. Also you have a positive integer $k$. You have to find minimum possible $i$ such that $A^{i}$ contains a number which is larger or equal than $k$.",
    "tutorial": "Let's delete all zeroes from the beginning of the array; they won't affect the answer. Also we will return an array of $m$ elements when calculating prefix sums (sum of zero elements becomes a zero in the beginning of the array, and so has to be removed). If the size of array is at least $10$, then we will get $k$ after calculating only a few prefix sums, so we can use simple iteration. So now we have to obtain the solution in case array has less than $10$ elements. If we remove zeroes from the beginning of each array, then $p(A) = A \\cdot T$, where $T$ is a matrix $m  \\times  m$, $T_{i, j} = 1$ if $i  \\le  j$, otherwise $T_{i, j} = 0$. Then we can use matrix exponentiation to check whether $A^{i}$ contains a number which is equal to or greater than $k$, and we can use binary search to find the answer. To avoid overflows, each time we get a number greater than $k$, we can set it to $k$.",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "math",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "837",
    "index": "G",
    "title": "Functions On The Segments",
    "statement": "You have an array $f$ of $n$ functions.The function $f_{i}(x)$ ($1 ≤ i ≤ n$) is characterized by parameters: $x_{1}, x_{2}, y_{1}, a, b, y_{2}$ and take values:\n\n- $y_{1}$, if $x ≤ x_{1}$.\n- $a·x + b$, if $x_{1} < x ≤ x_{2}$.\n- $y_{2}$, if $x > x_{2}$.\n\nThere are $m$ queries. Each query is determined by numbers $l$, $r$ and $x$. For a query with number $i$ ($1 ≤ i ≤ m$), you need to calculate the sum of all $f_{j}(x_{i})$ where $l ≤ j ≤ r$. The value of $x_{i}$ is calculated as follows: $x_{i} = (x + last)$ mod $10^{9}$, where $last$ is the answer to the query with number $i - 1$. The value of $last$ equals $0$ if $i = 1$.",
    "tutorial": "Let's build a data structure that allows us to find sum of functions on some prefix. The answer to the query can be obviously obtained using two answers on prefixes. We will use some persistent data structure that handles prefix sum queries - persistent segment tree, for example. We will actually use two different structures: let the sum of functions in some point $x_{0}$ be $x_{0} \\cdot k + m$; one structure will allow us to find $k$, and another one will allow us to find $m$. Obviously, for prefix of length $0$ both $k$ and $m$ are equal to $0$. Then when we advance from prefix of length $i$ to prefix of length $i + 1$, we do the following: in the structure that handles $k$ we add $k_{i}$ in position $x_{i, 1} + 1$ and add $( - k_{i})$ in position $x_{i, 2} + 1$, so it is added only on segment $[x_{1} + 1, x_{2}]$. The same approach can be used to find $m$: add $y_{i, 1}$ in position $0$, add $m_{i} - y_{i, 1}$ in position $x_{i, 1} + 1$ and add $y_{i, 2} - m_{i}$ in position $x_{i, 2} + 1$. And to get the value in point $x_{0}$ on some prefix, we just make a prefix sum query to the corresponding structure.",
    "tags": [
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "838",
    "index": "A",
    "title": "Binary Blocks",
    "statement": "You are given an image, that can be represented with a $2$-d $n$ by $m$ grid of pixels. Each pixel of the image is either on or off, denoted by the characters \"0\" or \"1\", respectively. You would like to compress this image. You want to choose an integer $k > 1$ and split the image into $k$ by $k$ blocks. If $n$ and $m$ are not divisible by $k$, the image is padded with only zeros on the right and bottom so that they are divisible by $k$. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some $k$. More specifically, the steps are to first choose $k$, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this $k$. The image must be compressible in that state.",
    "tutorial": "Let's define function $onesInRect(sx, sy, ex, ey)$ as number of ones in rectangle with top-left $(sx, sy)$ and down-right $(ex - 1, ey - 1)$ (0-based). Let $ps_{i, j}$ the number of ones in rectangle with top-left $(0, 0)$ and down-right $(i - 1, j - 1)$ (0-based). $ps_{i, j} = ps_{i - 1, j} + ps_{i, j - 1} - ps_{i - 1, j - 1}$ $onesInRect(sx, sy, ex, ey) = ps_{ex, ey} - ps_{sx, ey} - ps_{ex, sy} + ps_{sx, sy}$ Let $Cost(k)$ the answer if we compress the image with $k$. Let's find $Cost(k)$. int ans = 0; for(int i = k; i < n + k; i++)   for(int j = k; j < m + k; j++)     ans += min(onesInRect(i - k, j - k, i, j), k * k - onesInRect(i - k, j - k, i, j)); Time complexity of $Cost(k)$ is $O({\\frac{\\mu m}{k^{2}}})$. Now the answer is $min_{k = 2}^{max(n, m)}Cost(k)$. Overall time complexity is $O(n\\cdot m)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define sz(x) ((int) (x).size())\n#define all(x) (x).begin(), (x).end()\n\nconst int maxn = 2505;\nint pr[maxn][maxn];\nint n, m;\n\nint cost(int x1, int y1, int x2, int y2) {\n  if (x1 >= n || y1 >= m)\n    return 0;\n  int s = (x2 - x1) * (y2 - y1);\n  x2 = min(x2, n);\n  y2 = min(y2, m);\n  int ones = pr[x2][y2] + pr[x1][y1] - pr[x2][y1] - pr[x1][y2];\n  return min(ones, s - ones);\n}\n\nint cost(int k) {\n  int res = 0;\n  for (int i = 0; i < n; i += k)\n    for (int j = 0; j < m; j += k) {\n      res += cost(i, j, i + k, j + k);\n    }\n  return res;\n}\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"b.in\", \"r\", stdin));\n#endif\n  cin >> n >> m;\n  vector<string> s(n);\n  forn (i, n)\n    cin >> s[i];\n  forn (i, n)\n    forn (j, m)\n      pr[i + 1][j + 1] = pr[i][j + 1] + pr[i + 1][j] - pr[i][j] + (s[i][j] == '1');\n  int res = n * m;\n  for (int k = 2; k <= max(n, m); ++k) {\n    // cerr << \"cost \" << k << ' ' << cost(k) << endl;\n    res = min(res, cost(k));\n  }\n  cout << res << endl;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1400
  },
  {
    "contest_id": "838",
    "index": "B",
    "title": "Diverging Directions",
    "statement": "You are given a directed weighted graph with $n$ nodes and $2n - 2$ edges. The nodes are labeled from $1$ to $n$, while the edges are labeled from $1$ to $2n - 2$. The graph's edges can be split into two parts.\n\n- The first $n - 1$ edges will form a rooted spanning tree, with node $1$ as the root. All these edges will point away from the root.\n- The last $n - 1$ edges will be from node $i$ to node $1$, for all $2 ≤ i ≤ n$.\n\nYou are given $q$ queries. There are two types of queries\n\n- $1 i w$: Change the weight of the $i$-th edge to $w$\n- $2 u v$: Print the length of the shortest path between nodes $u$ to $v$\n\nGiven these queries, print the shortest path lengths.",
    "tutorial": "For each second type of query, there are two options: $u$ is an ancestor of $v$. $u$ isn't an ancestor of $v$.Let's define distance $v$ from root be $disFromRoot_{v}$. Answer of the first type of second query is obviously $disFromRoot_{v} - disFromRoot_{u}$. Let's define minimum possible distance $v$ from some node in this subtree of v + the distance from this node to root be $minSubTreeDis_{v}$. Answer of the second type of the second query is obviously $minSubTreeDis_{u} + disFromRoot_{v}$. Now, let's see how to find $disFromRoot_{v}$. For each vertex like $v$, let the weight of edge from its parent to it be $w$, you should add $w$ to all of the subtree of $v$. Use segment tree with range updates and single element queries, sort vertices in dfs order, add $w$ to $[startingTime_{v}, finishingTime_{v})$. Now $disFromRoot_{v} = get(startingTime_{v})$. We can handle update queries (first type) easily, just change the weight and update the segment tree again. Now, let's see how to find $minSubTreeDis_{v}$. Like above use segment tree with lazy propagation and minimum query.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define sz(x) ((int) (x).size())\n#define all(x) (x).begin(), (x).end()\n\nint n;\n\nconst int maxn = 200200;\nll wup[maxn];\nll wroot[maxn];\nint eid[maxn * 2];\nvector<int> g[maxn];\n\nconst int base = 1 << 18;\nll t[base * 2];\nll upd[base * 2];\n\nint in[maxn];\nint out[maxn];\nint timer;\n\nvoid push(int v) {\n  t[v * 2] += upd[v];\n  upd[v * 2] += upd[v];\n  t[v * 2 + 1] += upd[v];\n  upd[v * 2 + 1] += upd[v];\n  upd[v] = 0;\n}\n\nvoid add(int l, int r, int delta, int v = 1, int cl = 0, int cr = base) {\n  if (l <= cl && cr <= r) {\n    t[v] += delta;\n    upd[v] += delta;\n    return;\n  }\n  if (r <= cl || cr <= l)\n    return;\n  push(v);\n  int cc = (cl + cr) / 2;\n  add(l, r, delta, v * 2, cl, cc);\n  add(l, r, delta, v * 2 + 1, cc, cr);\n  t[v] = min(t[v * 2], t[v * 2 + 1]);\n}\n\nll get(int l, int r, int v = 1, int cl = 0, int cr = base) {\n  if (l <= cl && cr <= r)\n    return t[v];\n  if (r <= cl || cr <= l)\n    return 1e18;\n  push(v);\n  int cc = (cl + cr) / 2;\n  return min(get(l, r, v * 2, cl, cc), get(l, r, v * 2 + 1, cc, cr));\n}\n\nvoid pre(int u, ll h = 0) {\n  in[u] = timer++;\n  t[in[u] + base] = h + wroot[u];\n  for (int v: g[u])\n    pre(v, h + wup[v]);\n  out[u] = timer;\n}\n\nbool isPrev(int u, int v) {\n  return in[u] <= in[v] && out[v] <= out[u];\n}\n\nll pathUp(int u) {\n  return get(in[u], in[u] + 1) - wroot[u];\n}\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"d.in\", \"r\", stdin));\n#endif\n  int q;\n  scanf(\"%d%d\", &n, &q);\n  forn (i, 2 * (n - 1)) {\n    int u, v, w;\n    scanf(\"%d%d%d\", &u, &v, &w);\n    --u, --v;\n    if (i < n - 1) {\n      g[u].push_back(v);\n      wup[v] = w;\n      eid[i] = v;\n    } else {\n      wroot[u] = w;\n      eid[i] = u;\n    }\n  }\n\n  pre(0);\n  for (int i = base - 1; i > 0; --i)\n    t[i] = min(t[i * 2], t[i * 2 + 1]);\n\n  forn (i, q) {\n    int t, a, b;\n    scanf(\"%d%d%d\", &t, &a, &b);\n    if (t == 1) {\n      --a;\n      int u = eid[a];\n      if (a < n - 1) {\n        // cerr << \"tree\n\";\n        add(in[u], out[u], b - wup[u]);\n        wup[u] = b;\n      } else {\n        // cerr << \"root\n\";\n        add(in[u], in[u] + 1, b - wroot[u]);\n        wroot[u] = b;\n      }\n    } else {\n      --a, --b;\n      if (isPrev(a, b)) {\n        // cerr << \"prev \";\n        cout << pathUp(b) - pathUp(a) << '\n';\n      } else {\n        // cerr << \"huev \";\n        cout << get(in[a], out[a]) - pathUp(a) + pathUp(b) << '\n';\n      }\n    }\n  }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "838",
    "index": "C",
    "title": "Future Failure",
    "statement": "Alice and Bob are playing a game with a string of characters, with Alice going first. The string consists $n$ characters, each of which is one of the first $k$ letters of the alphabet. On a player’s turn, they can either arbitrarily permute the characters in the words, or delete exactly one character in the word (if there is at least one character). In addition, their resulting word cannot have appeared before throughout the entire game. The player unable to make a valid move loses the game.\n\nGiven $n, k, p$, find the number of words with exactly $n$ characters consisting of the first $k$ letters of the alphabet such that Alice will win if both Alice and Bob play optimally. Return this number modulo the prime number $p$.",
    "tutorial": "Let the frequencies of the characters be $a_{1}, a_{2}, ..., a_{k}$. Alice loses if and only if $\\left({}_{a_{1},a_{2},\\ldots,a_{k}}\\right)$ is odd and $n$ is even. So, if $n$ is odd, answer is $k^{n}$. Otherwise, we have to count number of $a_{1}, a_{2}, ..., a_{k}$ such that $a_{1} + a_{2} + ... + a_{k} = n$ and $\\frac{n}{a_{1}!a_{2}!\\cdots a_{k}!}$ is odd. Let the number of 1's in expansion of $x$ be $bp(x)$, the greatest power of $2$ in $x!$ is $x - bp(x)$ (More information). Now we want to count number of $a_{1}, a_{2}, ..., a_{k}$ such that $a_{1} + a_{2} + ... + a_{k} = n$ and $\\begin{array}{c}{{a_{1}-b p(a_{1})+a_{2}-b p(a_{k})+\\cdot\\cdot\\cdot\\cdot+a_{k}-b p(a_{k})\\,=\\,n-b p(n)\\,\\Rightarrow\\,b p(a_{1})+}}\\\\ {{b p(a_{2})+\\cdot\\cdot\\cdot+b p(a_{k})=b p(n)}}\\end{array}$. By Lucas's theorem, this is equivalent to $a_{1} + a_{2} + ... + a_{k} = a_{1}|a_{2}|... |a_{k}$. Let's define $dp_{i, mask}$ be the number of ways to choose $a_{1}, a_{2}, ..., a_{i}$ such that $\\textstyle\\sum a_{i}=a_{1}|a_{2}|\\cdot\\cdot\\cdot|a_{i}=m a s k$. Then, $dp_{i}$ can be computed with time complexity $O(3^{\\log_{2}^{n}}))$. For instance, the solutions is something like $d p_{i,m a s k}=\\sum\\textstyle{\\frac{1}{x^{i}}}\\cdot d p_{i-1,m a s k e j\\delta a}$ for $x$ as a subset of $mask$ (and then after, multiply $dp_{k, mask}$ by $mask!$). We can use the convolution to multiply $\\left[\\frac{1}{0!},\\,\\frac{1}{1!},\\,\\frac{1}{2!},\\,\\frac{1}{3!},\\,\\ddots\\,*\\right]$ and $dp_{i - 1}$ to find $dp_{i}$ (More information). Time complexity: $O(n\\cdot\\log^{k}{.}(\\log^{n})^{2})$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define sz(x) ((int) (x).size())\n#define all(x) (x).begin(), (x).end()\n\nint mod;\nvoid udd(int &a, int b) {\n  a += b;\n  if (a >= mod)\n    a -= mod;\n}\nvoid uub(int &a, int b) {\n  udd(a, mod - b);\n}\nint add(int a, int b) {\n  a += b;\n  if (a >= mod)\n    a -= mod;\n  return a;\n}\nint mul(ll a, ll b) {\n  return a * b % mod;\n}\nint bin(int a, int deg) {\n  int r = 1;\n  while (deg) {\n    if (deg & 1)\n      r = mul(r, a);\n    deg >>= 1;\n    a = mul(a, a);\n  }\n  return r;\n}\nint inv(int a) {\n  assert(a);\n  return bin(a, mod - 2);\n}\n\nconst int LG = 19;\nconst int B = 1 << LG;\nconst int maxk = 30;\nint fact[B];\nint ifact[B];\nint n, lg;\n\nint a[B][LG];\nint res[B];\n\nint vec[LG];\nint ways[LG];\nint nways[LG];\n\nvoid conv() {\n  forn (bit, lg + 1)\n    forn (i, n + 1) {\n      if (i & (1 << bit)) {\n        forn (j, lg + 1)\n          udd(a[i][j], a[i ^ (1 << bit)][j]);\n      }\n    }\n}\n\nvoid iconv() {\n  forn (bit, lg + 1)\n    forn (i, n + 1) {\n      if (i & (1 << bit)) {\n        uub(res[i], res[i ^ (1 << bit)]);\n      }\n    }\n}\n\nvoid mul(int n, int* a, int* b) {\n  forn (i, n) {\n    nways[i] = 0;\n    forn (j, i + 1)\n      udd(nways[i], mul(a[j], b[i - j]));\n  }\n}\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"f.in\", \"r\", stdin));\n#endif\n  int k;\n  cin >> n >> k >> mod;\n\n  int all = bin(k, n);\n  if (n % 2) {\n    cout << all << endl;\n    return 0;\n  }\n\n  lg = 1;\n  while ((1 << lg) <= n)\n    ++lg;\n\n  forn (i, n + 1)\n    fact[i] = i ? mul(i, fact[i - 1]) : 1;\n  for (int i = n; i >= 0; --i)\n    ifact[i] = i == n ? inv(fact[i]) : mul(ifact[i + 1], i + 1);\n\n  forn (i, n + 1)\n    a[i][__builtin_popcount(i)] = ifact[i];\n  conv();\n\n  int need = __builtin_popcount(n);\n\n  forn (x, n + 1) {\n    if ((x & n) != x)\n      continue;\n    forn (i, lg + 1) {\n      vec[i] = a[x][i];\n      ways[i] = i == 0;\n    }\n    int kk = k;\n    while (kk) {\n      if (kk & 1) {\n        mul(lg + 1, ways, vec);\n        memcpy(ways, nways, sizeof(nways));\n      }\n      kk >>= 1;\n      mul(lg + 1, vec, vec);\n      memcpy(vec, nways, sizeof(nways));\n    }\n    res[x] = ways[need];\n  }\n\n  iconv();\n  int ans = all;\n  uub(ans, mul(res[n], fact[n]));\n  cout << ans << endl;\n}",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 2800
  },
  {
    "contest_id": "838",
    "index": "D",
    "title": "Airplane Arrangements",
    "statement": "There is an airplane which has $n$ rows from front to back. There will be $m$ people boarding this airplane.\n\nThis airplane has an entrance at the very front and very back of the plane.\n\nEach person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person $1$. Each person can independently choose either the front entrance or back entrance to enter the plane.\n\nWhen a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.\n\nFind the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo $10^{9} + 7$.",
    "tutorial": "Consider adding an extra seat, and the plane is now circular. Now the number of ways such that $n + 1$-th seat becomes empty is the answer. For each seat there is $\\frac{(2\\cdot(n+1))^{2m}\\cdot(n+1\\!-\\!m)}{n\\!+\\!1}$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define sz(x) ((int) (x).size())\n#define all(x) (x).begin(), (x).end()\n\nconst int mod = 1e9 + 7;\nvoid udd(int &a, int b) {\n  a += b;\n  if (a >= mod)\n    a -= mod;\n}\nint mul(ll a, ll b) {\n  return a * b % mod;\n}\nint bin(int a, int deg) {\n  int r = 1;\n  while (deg) {\n    if (deg & 1)\n      r = mul(r, a);\n    deg >>= 1;\n    a = mul(a, a);\n  }\n  return r;\n}\nint inv(int a) {\n  assert(a);\n  return bin(a, mod - 2);\n}\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"a.in\", \"r\", stdin));\n#endif\n  int n, m;\n  cin >> n >> m;\n  int res = bin(mul(2, n + 1), m);\n  res = mul(res, n - m + 1);\n  res = mul(res, inv(n + 1));\n  cout << res << endl;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "838",
    "index": "E",
    "title": "Convex Countour",
    "statement": "You are given an strictly convex polygon with $n$ vertices. It is guaranteed that no three points are collinear. You would like to take a maximum non intersecting path on the polygon vertices that visits each point at most once.\n\nMore specifically your path can be represented as some sequence of distinct polygon vertices. Your path is the straight line segments between adjacent vertices in order. These segments are not allowed to touch or intersect each other except at the vertices in your sequence.\n\nGiven the polygon, print the maximum length non-intersecting path that visits each point at most once.",
    "tutorial": "Let $dp_{i, j}$ be the longest path given that we've included segment $i, j$ in our solution, and we are only considering points to the right of ray $i, j$ (so $dp_{i, j}$ and $dp_{j, i}$ may be different). This leads to an $O(n^{3})$ solution. The optimal solution will pass from all of the points, so let's define $dp_{i, j, 0}$ the best path in ray $i, j$ such that it has an end point in $i$ and $dp_{i, j, 1}$ the best path in ray $i, j$ such that it has an end point in $j$. Now the transitions are easy, take a loop on j - i, when reached state $i, j, k$, $d p_{i-1{\\mathrm{~mod~}}n_{3},0^{\\prime}}>d p_{i,j,0}+d i s(i-1\\mathrm{~mod~}n,i)$ $d p_{j+1}\\,\\,{\\mathrm{mod}}\\,\\,{n.}_{i,1}{\\ !}\\qquad\\qquad d p_{i,j,0}+d i s(j+1\\quad{\\mathrm{mod}}\\,\\,{n,i})$ $d p_{i-1{\\mathrm{~mod~}}n_{3},1}\\ref{'}^{?}>d p_{i,j,0}+d i s(i-1\\mod n,i)$ $d p_{j+1}\\,\\,{\\mathrm{mod}}\\,\\,{n.}_{i,0}{\\ !}\\,>d p_{i,j,0}+d i s(j+1)\\,\\,{\\mathrm{mod}}\\,\\,{n},\\,i)$ ($x? > y$ stands for $x = max(x, y)$).",
    "code": "#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() struct pt { ld x, y; pt operator-(const pt &p) const { return pt{x - p.x, y - p.y}; } ld abs() const { return hypotl(x, y); } }; const int maxn = 2505; pt p[maxn]; ld d[maxn][maxn][2]; ld dist[maxn][maxn]; void uax(ld &a, ld b) { a = max(a, b); } signed main() { #ifdef LOCAL assert(freopen(\"c.in\", \"r\", stdin)); #endif int n; cin >> n; forn (i, n) { cin >> p[i].x >> p[i].y; } forn (i, n) forn (j, n) { dist[i][j] = (p[i] - p[j]).abs(); forn (k, 2) d[i][j][k] = -1e18; } forn (i, n) d[i][i][0] = d[i][i][1] = 0; forn (len, n - 1) { forn (i, n) { int j = (i + len) % n; int ni = (i + n - 1) % n; int nj = (j + 1) % n; uax(d[ni][j][0], d[i][j][0] + dist[ni][i]); uax(d[nj][i][1], d[i][j][0] + dist[nj][i]); j = (i + n - len) % n; ni = (i + 1) % n; nj = (j + n - 1) % n; uax(d[ni][j][1], d[i][j][1] + dist[ni][i]); uax(d[nj][i][0], d[i][j][1] + dist[nj][i]); } } ld res = 0; forn (i, n) forn (j, n) forn (k, 2) uax(res, d[i][j][k]); cout << fixed; cout.precision(10); cout << res; }",
    "tags": [
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "838",
    "index": "F",
    "title": "Expected Earnings",
    "statement": "You are playing a game with a bag of red and black balls. Initially, you are told that the bag has $n$ balls total. In addition, you are also told that the bag has probability $p_{i} / 10^{6}$ of containing exactly $i$ red balls.\n\nYou now would like to buy balls from this bag. You really like the color red, so red balls are worth a unit of $1$, while black balls are worth nothing. To buy a ball, if there are still balls in the bag, you pay a cost $c$ with $0 ≤ c ≤ 1$, and draw a ball randomly from the bag. You can choose to stop buying at any point (and you can even choose to not buy anything at all).\n\nGiven that you buy optimally to maximize the expected profit (i.e. # red balls - cost needed to obtain them), print the maximum expected profit.",
    "tutorial": "We want to compute $dp_{i, j}$: expected value given we have seen $i$ red balls and $j$ black balls. Final answer is $dp_{0, 0}$. Now, to compute $dp_{i, j}$, we either take a ball or don't. Let $p_{i, j}$ be the probability that after we have seen $i$ red balls and $j$ black balls the next ball is red. Then, $dp_{i, j} = max(0, - c + p_{i, j} \\cdot (dp_{i + 1, j} + 1) + (1 - p_{i, j}) \\cdot (dp_{i, j + 1}))$. To compute $p_{i, j}$, we can compute $\\sum_{k=i}^{n}{\\frac{p({\\mathrm{there~are~}}k{\\mathrm{~red~balls~lseen~}}i{\\mathrm{~seen~}}i{\\mathrm{~red~badis~and~}}j{\\mathrm{~black~balls}})\\cdot(k-i)}{(n-i-i)}}$. By Bayes' theorem, ${p({\\mathrm{here~are~}}k{\\mathrm{~red~balk~ts~lank~}})}={\\frac{a-m+b a}{m}}{\\frac{\\langle{\\mathrm{ha}}\\rangle\\cdot{\\mathrm{a}}\\ |s\\ |s\\ |s\\ |s\\ |s\\ |s\\ |s\\ |s\\ |s\\ |s\\ |s\\rangle}{\\langle{\\frac{d-a-b a^{\\mathrm{fac}}}{m}}\\langle{\\frac{d-a^{\\mathrm{fac}}}{d t}}\\langle{\\frac{d^{\\mathrm{hadjs}}}{d t}}\\rangle}}$ This gives an $O(n^{3})$ solution. To speed this up to $O(n^{2})\\,$, let's figure out how to compute $p_{i, j}$ faster. Let's suppose that $i + j + 1 = n$. Then, it's easy, either $k = i$ or $k = i + 1$, so we can compute this in constant time. Now, suppose $i + j + 1 < n$. Let's throw out some balls at random without looking at them, and figure out new probabilities that there are $k$ red balls within the bag. You can see the code for more details on how to compute this new distribution. Codes here. P.S. Please notify me if there are any problems.",
    "code": "#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef double ld; #define forn(i, n) for (int i = 0; i < int(n); ++i) #define sz(x) ((int) (x).size()) #define all(x) (x).begin(), (x).end() ld fact[100100]; const int maxn = 10005; ld d[2][maxn]; ld p[2][maxn]; signed main() { #ifdef LOCAL assert(freopen(\"e.in\", \"r\", stdin)); #endif forn (i, 100100) fact[i] = i ? fact[i - 1] * i : 1; int q = 0; int N; ld C; cin >> N >> C; forn (i, N + 1) { cin >> p[q][i]; p[q][i] *= 1e-6; d[q][i] = i; } C *= 1e-6; for (int n = N - 1; n >= 0; --n, q ^= 1) { forn (w, n + 1) { p[q ^ 1][w] = p[q][w + 1] * (w + 1) / (n + 1) + p[q][w] * (n + 1 - w) / (n + 1); ld pr1 = p[q][w + 1] * (w + 1) / (n + 1); ld pr0 = p[q][w] * (n + 1 - w) / (n + 1); if (pr0 + pr1 == 0) continue; ld pr = pr1 / (pr0 + pr1); ld cur = pr * d[q][w + 1] + (1 - pr) * d[q][w] - C; d[q ^ 1][w] = max<ld>(w, cur); } } cout << fixed; cout.precision(10); cout << d[q][0] << endl; }",
    "tags": [],
    "rating": 2800
  },
  {
    "contest_id": "839",
    "index": "A",
    "title": "Arya and Bran",
    "statement": "Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.\n\nAt first, Arya and Bran have $0$ Candies. There are $n$ days, at the $i$-th day, Arya finds $a_{i}$ candies in a box, that is given by the Many-Faced God. Every day she can give Bran \\textbf{at most} $8$ of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.\n\nYour task is to find the minimum number of days Arya needs to give Bran $k$ candies \\textbf{before} the end of the $n$-th day. Formally, you need to output the minimum day index to the end of which $k$ candies will be given out (the days are indexed from 1 to $n$).\n\nPrint -1 if she can't give him $k$ candies during $n$ given days.",
    "tutorial": "Let $t$ be number of her candies. At $i$-th day , we increase $t$ by $a_{i}$ ,then we give Bran $min(8, t)$ . So we decrease $k$ from this value. We will print the answer once $k$ becomes smaller or equal to $0$ . Or we will print $- 1$ if it does'n happen after $n$ days.",
    "code": "// God & me\n// Fly ...\n#include <bits/stdc++.h>\nusing namespace std;\nconst int maxn = 1e2 + 17;\n \nint n, k, cur, ans;\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcin >> n >> k;\n\twhile(n--){\n\t\tint x;\n\t\tcin >> x;\n\t\tcur += x;\n\t\tint r = min(8, cur);\n\t\tcur -= r;\n\t\tk -= r;\n\t\tans++;\n\t\tif(k <= 0)\n\t\t\tbreak;\n\t}\n\tif(k > 0)\n\t\tcout << -1 << '\\n';\n\telse\n\t\tcout << ans << '\\n';\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "839",
    "index": "B",
    "title": "Game of the Rows",
    "statement": "Daenerys Targaryen has an army consisting of $k$ groups of soldiers, the $i$-th group contains $a_{i}$ soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has $n$ rows, each of them has $8$ seats. We call two seats neighbor, if they are in the same row and in seats ${1, 2}$, ${3, 4}$, ${4, 5}$, ${5, 6}$ or ${7, 8}$.\n\n\\begin{center}\n{\\small A row in the airplane}\n\\end{center}\n\nDaenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats.\n\nYour task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.",
    "tutorial": "Use greedy solution. Consider a group with $x  \\ge  4$ members, put $4$ of them in seats [3, 6] of some row, and throw the row. Now we have $x - 4$ members in this group now. Continue till all of the seats in the range $[3, 6]$ become full, continue with $[1, 2]$ and $[7, 8]$. Now handle groups with size $ \\le  3$. For groups with size $= 3$, allocate $4$ seats in range $[3, 6]$ or $4$ seats in range $[1, 2]$ or $[7, 8]$. For groups with size $= 2$, allocate $2$ seats in range $[1, 2]$ or $[7, 8]$ or $3$ seats in range $[3, 6]$. If no seat found, divide this group and make it two groups with size 1. Fill the other parts with groups with groups with size $= 1$. If in any part we ran out of seat, the answer is NO, YES otherwise.",
    "code": "// God & me\n// Fly ...\n#include <bits/stdc++.h>\nusing namespace std;\nconst int maxn = 1e2 + 17;\n \nint n, k, have[5], cnt[5];\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcin >> n >> k;\n\thave[2] = 2 * n, have[4] = n;\n\tfor(int i = 0; i < k; i++){\n\t\tint x;\n\t\tcin >> x;\n\t\twhile(x >= 3)\n\t\t\tif(have[4] > 0)\n\t\t\t\tx -= 4, have[4]--;\n\t\t\telse if(have[2] > 0)\n\t\t\t\tx -= 2, have[2]--;\n\t\t\telse\n\t\t\t\treturn cout << \"NO\" << '\\n', 0;\n\t\tif(x > 0)\n\t\t\tcnt[x]++;\n\t}\n\twhile(cnt[2])\n\t\tif(have[2] > 0)\n\t\t\tcnt[2]--, have[2]--;\n\t\telse if(have[4] > 0)\n\t\t\tcnt[2]--, have[4]--, have[1]++;\n\t\telse\n            cnt[2]--, cnt[1] += 2;\n\tif(cnt[1] > have[1] + have[2] + have[4] * 2)\n\t\treturn cout << \"NO\" << '\\n', 0;\n\tcout << \"YES\" << '\\n';\n\treturn 0;\n}\n ",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "839",
    "index": "C",
    "title": "Journey",
    "statement": "There are $n$ cities and $n - 1$ roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.\n\nTheon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities.\n\nLet the length of each road be $1$. The journey starts in the city $1$. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.",
    "tutorial": "Let the cities be vertices and roads be edges of a tree and vertex $1$ be the root of the tree. Let $ans[i]$ be the answer for the $i$-th vertex (the expected value if they start their journey from that vertex and the horse doesn't go to it's parent). Now we can calculate $ans[i]$ by knowing the answer for it's children. Let $v_{1}, v_{2},  \\dots ., v_{k}$ be the children of $i$-th vertex , then $a n s[i]={\\frac{a n s[v_{1}]+a n s[v_{2}]+\\dots+a n s[v_{k}]}{k}}+1$ . Because when we are at $i$-th vertex , we have $k$ choices with equal probabilities and $+ 1$ for going to one of them (length of the edge between $i$-th vertex and it's children). So if we know the answer of some vertex's children, we can calculate its expected value and we can do it by a simple DFS (note that the answer for a leave is $0$).",
    "code": "// God & me\n// Fly ...\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\nconst int maxn = 2e5 + 17, maxv = 1e6 + 17, mod = 1e9 + 7;\n \nint n;\nvector<int> g[maxn];\nld dfs(int v = 0, int p = -1){\n\tld sum = 0;\n\tfor(auto u : g[v])\n\t\tif(u != p)\n\t\t\tsum += dfs(u, v) + 1;\n\treturn sum ? sum / (g[v].size() - (p != -1)) : 0;\n}\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcin >> n;\n\tfor(int v, u, i = 1; i < n; i++){\n\t\tcin >> v >> u, v--, u--;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\tcout << fixed << setprecision(7) << dfs() << '\\n';\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "probabilities",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "839",
    "index": "D",
    "title": "Winter is here",
    "statement": "Winter is here at the North and the White Walkers are close. John Snow has an army consisting of $n$ soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.\n\nHe has created a method to know how strong his army is. Let the $i$-th soldier’s strength be $a_{i}$. For some $k$ he calls $i_{1}, i_{2}, ..., i_{k}$ a clan if $i_{1} < i_{2} < i_{3} < ... < i_{k}$ and $gcd(a_{i1}, a_{i2}, ..., a_{ik}) > 1$ . He calls the strength of that clan $k·gcd(a_{i1}, a_{i2}, ..., a_{ik})$. Then he defines the strength of his army by the sum of strengths of all possible clans.\n\nYour task is to find the strength of his army. As the number may be very large, you have to print it modulo $1000000007$ ($10^{9} + 7$).\n\nGreatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it.",
    "tutorial": "1st method: Let $cnt[i]$ be the number of such $j$s that $a_{j}$ is divisible by $i$. Also let $p[i]$ be $i$-th prime number. Let $f(m)$ be $\\textstyle\\sum_{x\\subseteq S}s i z e(x)$ for an arbitrary set with $m$ members(something like the sum of strengths of all possible subsets, but replace $1$ with the $gcd$ of the sequence) Finally let $ans[i]$ be the sum of strengths of clans which $gcd(strengths - of - clan's - soldiers) = i$. Now we can calculate $ans[i]$ by \"Inclusion-exclusion principle\" : $\\begin{array}{c}{{a n s[i]=i[\\sum_{j}f(c n t[p_{j}\\cdot i])-\\sum_{j\\leq k}f(c n t[p_{j}\\cdot p_{k}\\cdot i])+\\sum_{j\\leq k}f(c n t[p_{j}\\cdot p_{k}\\cdot p_{t}\\cdot i]).}}\\end{array}$ Because $i \\cdot f(i)$ includes all possible clans that their members are all multiples of $i$, not the ones with $gcd$ equal to $i$ .Now, we can do the above calculation by a \"foor-loop\" through the multiples of $i$. So all we have to do , is to calculate $f(x)$ very fast. Actually $f(x) = x \\cdot 2^{x - 1}$ because : $f(x)=\\sum_{i=0}^{x}i\\cdot{\\left(\\begin{array}{l}{x}\\\\ {i}\\end{array}\\right)}=x\\cdot2^{x-1}$ 2nd method: Let $cnt[i]$ be the number of such $j$s that $a_{j}$ is divisible by $i$. Than $cnt[i]$ is count of soliders with strength of $i, 2i, 3i, ...$. Let $ans[i]$ be count of people in clans with $gcd = i$. To find $ans[i]$ let's understand, how to find count of people in clans, in which every number is divided by $i$. If $cnt[i] = c$, it's $\\frac{1\\cdot\\left(_{1}^{c}\\right)+2\\cdot\\left(_{^{c}}^{c}\\right)+\\cdot\\cdot\\cdot\\cdot\\cdot\\left(_{_{c}}^{c}\\right)+\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\left(_{_{G}}^{\\left(1\\right)}=\\frac{_{V^{c}}}{\\left(c-1\\right)!\\,1}+\\frac{_{-c^{1}}}{\\left(c-1\\right)!\\,2}+\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot+\\frac{_{\\mathrm{-cl}}}{_{(C-1)}}\\left(\\frac{^{c}}{c-1}\\right)+\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\left(\\frac{_{_{C}}}{_{1}^{c}}\\right)=c\\cdot2^{c-1}\\left(\\frac{^{-1}}{c-1}\\right)\\left(\\frac{^{c-1}}{c-1}\\right)-\\cdot\\right)\\left(\\frac{_{V}}{c-1}\\right)}\\right)$ Let's calculate $ans[i]$ from the end. Then $ans[i] = cnt[i] \\cdot 2^{cnt[i] - 1} - ans[2i] - ans[3i] - ...$. Answer for problem's question is $\\sum_{i=2}^{1000000}i\\cdot a n s[i]$. Asymptotics of solution is $O(k+{\\frac{k}{2}}+{\\frac{k}{3}}+\\cdot\\cdot\\cdot)=O(k\\cdot l o g_{k})$, where $k$ is maximal value of $a_{i}$.",
    "code": "//sobskdrbhvk\n//remember the flying, the bird dies ):(\n#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long int LL;\ntypedef pair<int, int> pii;\ntypedef pair<LL, LL> pll;\n \n#define PB push_back\n#define MP make_pair\n#define L first\n#define R second\n#define sz(x) ((int)(x).size())\n#define smax(x, y) ((x) = max((x), (y)))\n#define smin(x, y) ((x) = min((x), (y)))\n#define all(x) x.begin(),x.end()\n \nconst int maxn = 1e6 + 10;\nconst LL Mod = 1e9 + 7;\nbool isp[maxn];\nint sign[maxn],\n\tcnt[maxn];\nLL P[maxn];\nint n;\n \nLL func(int x) {\n\treturn (x * P[x - 1]) % Mod;\n}\n \nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tmemset(isp, true, sizeof isp);\n\tfill(sign, sign + maxn, 1);\n\tisp[0] = isp[1] = false;\n\tfor (int i = 2; i < maxn; i++)\n\t\tif (isp[i])\n\t\t\tfor (int j = i; j < maxn; j += i) {\n\t\t\t\tisp[j] = i == j;\n\t\t\t\tif ((j / i) % i == 0)\n\t\t\t\t\tsign[j] = 0;\n\t\t\t\telse\n\t\t\t\t\tsign[j] *= -1;\n\t\t\t}\n\tP[0] = 1;\n\tfor (int i = 1; i < maxn; i++)\n\t\tP[i] = (P[i - 1] << 1) % Mod;\n\tcin >> n;\n\tfor (int x, i = 0; i < n; i++)\n\t\tcin >> x, cnt[x]++;\n\tfor (int i = 1; i < maxn; i++)\n\t\tfor (int j = i + i; j < maxn; j += i)\n\t\t\tcnt[i] += cnt[j];\n\tLL ans = 0;\n\tfor (int i = 2; i < maxn; i++) {\n\t\tLL rc = 0;\n\t\tfor (int j = i; j < maxn; j += i)\n\t\t\trc = (rc + sign[j / i] * func(cnt[j])) % Mod;\n\t\tans += rc * i;\n\t\tans %= Mod;\n\t}\n\tans = (ans + Mod) % Mod;\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "839",
    "index": "E",
    "title": "Mother of Dragons",
    "statement": "There are $n$ castles in the Lannister's Kingdom and some walls connect two castles, no two castles are connected by more than one wall, no wall connects a castle to itself.\n\nSir Jaime Lannister has discovered that Daenerys Targaryen is going to attack his kingdom soon. Therefore he wants to defend his kingdom. He has $k$ liters of a strange liquid. He wants to distribute that liquid among the castles, so each castle may contain some liquid (possibly zero or non-integer number of liters). After that the stability of a wall is defined as follows: if the wall connects two castles $a$ and $b$, and they contain $x$ and $y$ liters of that liquid, respectively, then the strength of that wall is $x·y$.\n\nYour task is to print the maximum possible sum of stabilities of the walls that Sir Jaime Lannister can achieve.",
    "tutorial": "Lemma : Let $G$ be a simple graph. To every vertex of $G$ we assign a nonnegative real number such that the sum of the numbers assigned to all vertices is $1$. For any two connected vertices (by an edge), compute the product of the numbers associated to these vertices. The maximal value of the sum of these products is when assign equal numbers to a maximal clique (a subgraph that all of its vertices are connected to each other) and $0$ to the rest of the graph. Proof : If the graph is complete of order $n$ then the problem reduces to finding the maximum of $\\sum_{1<i<i<n}x_{i}.x_{j}$ knowing that $x_{1} + x_{2} +  \\dots  + x_{n} = 1$. This is easy, since $\\sum_{1\\leq i<j\\leq n}x_{i}.x_{j}=\\textstyle{\\frac{1}{2}}(1-\\sum_{i=1}^{n}x_{i}^{2})\\leq\\textstyle{\\frac{1}{2}}(1-{\\frac{1}{n}})$. The last inequality is just the Cauchy-Schwarz inequality and we have equality when all variables are $\\textstyle{\\frac{1}{n}}$. Unfortunately, the problem is much more difficult in other cases, but at least we have an idea of a possible answer: indeed, it is easy now to find a lower bound for the maximum: if $H$ is the complete subgraph with maximal number of vertices $k$, then by assigning these vertices $\\textstyle{\\frac{1}{k}}$ and to all other vertices $0$, we find that the desired maximum is at least $\\textstyle{\\frac{1}{2}}(1-{\\frac{1}{k}})$. We still have to solve the difficult part: showing that the desired maximum is at most $\\textstyle{\\frac{1}{2}}(1-{\\frac{1}{k}})$. Let us proceed by induction on the number n of vertices of $G$. If $n = 1$ everything is clear, so assume the result true for all graphs with at most $n-1$ vertices and take a graph $G$ with $n$ vertices, numbered $1, 2, ... , n$. Let $A$ be the set of vectors with nonnegative coordinates and whose components add up to $1$ and $E$ the set of edges of $G$. Because the function $f(x_{1},x_{2},\\cdot\\cdot\\cdot,x_{n})=\\sum_{(i,j)\\in E}x_{i}\\cdot x_{j}$ is continuous on the compact set $A$ , it attains its maximum in a point $(x_{1}, x_{2}, ... , x_{n})$. If at least one of the $x_{i}$ is zero, then $f(G) = f(G_{1})$ where $G_{1}$ is the graph obtained by erasing vertex $i$ and all edges that are incident to this vertex. It suffices to apply the induction hypothesis to $G_{1}$ (clearly, the maximal complete subgraph of $G_{1}$ has at most as many vertices as the maximal complete subgraph of $G$). So, suppose that all $x_{i}$ are positive. We may assume that $G$ is not complete, since this case has already been discussed. So, let us assume for example that vertices $1$ and $2$ are not connected. Choose any number $0 < a  \\le  x_{1}$ and assign to vertices $1, 2, ... , n$ of $G$ the numbers $x_{1}-a, x_{2} + a, x_{3}, ... , x_{n}$. By maximality of $f(G)$, we must have $\\textstyle\\sum_{i\\in C_{1}}x_{i}\\leq\\sum_{i\\in C_{2}}x_{i}$ , where $C_{1}$ is the set of vertices that are adjacent to vertex 2 and not adjacent to vertex 1 (the definition of C2 being clear). By symmetry, we deduce that we must actually have $\\textstyle\\sum_{i\\in C_{1}}x_{i}=\\sum_{i\\in C_{2}}x_{i}$ , which shows that $f(x_{1}, x_{2}, ... , x_{n}) = f(0, x_{1} + x_{2}, x_{3}, ... , x_{n})$. Hence we can apply the previous case and the Lemma is solved. Now by the Lemma , we have to find the maximal clique and get the answer.(Let the maximal clique have $m$ vertices, then the answer is $\\frac{k^{2}\\!\\cdot\\!\\left(m\\!-\\!1\\right)}{2\\!\\cdot\\!m}$). We can find the maximal clique by the \"meet in the middle\" approach. Divide the vertices of the graph into 2 sets with equal number of vertices in each set(if $n$ is odd, one set will have a vertex more than the other). We can save the maximal clique for each subset of the first set in $dp[mask]$. Now ,for each clique $C$ in the second set, let $v_{1}, ... , v_{t}$ be vertices in the first set that are connected to all of the vertices of $C$. Then $m = max(m, dp[mask(v_{1}, ... , v_{t})] + sizeof(C))$ ($m$ is size of maximum clique). Note : finding the maximal clique is also possible by a wise brute forces.",
    "code": "// God & me\n// Fly ...\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int maxn = 40, C = 20;\n \nint n, k, dp[1 << C];\nll adj[maxn];\nint maxc(){\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0, x; j < n; j++)\n\t\t\tcin >> x, adj[i] |= (ll) (x || i == j) << j;\n\tfor(int i = 1; i < (1 << max(0, n - C)); i++){\n\t\tint x = i;\n\t\tfor(int j = 0; j < C; j++)\n\t\t\tif((i >> j) & 1)\n\t\t\t\tx &= adj[j + C] >> C;\n\t\tif(x == i)\n\t\t\tdp[i] = __builtin_popcount(i);\n\t}\n\tfor(int i = 1; i < (1 << max(0, n - C)); i++)\n\t\tfor(int j = 0; j < C; j++)\n\t\t\tif((i >> j) & 1)\n\t\t\t\tdp[i] = max(dp[i], dp[i ^ (1 << j)]);\n\tint ans = 0;\n\tfor (int i = 0; i < (1 << min(C, n)); i++){\n\t\tint x = i, y = (1 << max(0, n - C)) - 1;\n\t\tfor (int j = 0; j < min(C, n); j++)\n\t\t\tif ((i >> j) & 1)\n\t\t\t\tx &= adj[j] & ((1 << C) - 1), y &= adj[j] >> C;\n\t\tif (x != i)\tcontinue;\n\t\tans = max(ans, __builtin_popcount(i) + dp[y]);\n\t}\n\treturn ans;\n}\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcin >> n >> k;\n\tint ans = maxc();\n\tlong double x = (long double) k / ans;\n\tcout << fixed << setprecision(8) << x * x * ans * (ans - 1) / 2 << '\\n';\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "graphs",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 2700
  },
  {
    "contest_id": "840",
    "index": "A",
    "title": "Leha and Function",
    "statement": "Leha like all kinds of strange things. Recently he liked the function $F(n, k)$. Consider all possible $k$-element subsets of the set $[1, 2, ..., n]$. For subset find minimal element in it. $F(n, k)$ — mathematical expectation of the minimal element among all $k$-element subsets.\n\nBut only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays $A$ and $B$, each consists of $m$ integers. For all $i, j$ such that $1 ≤ i, j ≤ m$ the condition $A_{i} ≥ B_{j}$ holds. Help Leha rearrange the numbers in the array $A$ so that the sum $\\textstyle\\sum_{i=1}^{m}F(A_{i}^{\\prime},B_{i})$ is maximally possible, where $A'$ is already rearranged array.",
    "tutorial": "First of all, let's understand what is the value of $F(N, K)$. For any subset of size $K$, say, $a_{1}, a_{2}...a_{K}$, we can represent it as a sequence of numbers $d_{1}, d_{2}...d_{K + 1}$, so that $d_{1} = a_{1}$, $d_{1} + d_{2} = a_{2}$, ..., $\\sum_{i=1}^{K+1}d_{i}=N+1$. We're interested in $E[d_{1}]$, expected value of $d_{1}$. Knowing some basic facts about expected values, we can derive the following: $E[d_{1} + ... + d_{K + 1}] = N + 1$ $E[d_{1}] + ... + E[d_{K + 1}] = (K + 1) \\cdot E[d_{1}]$ And we immediately get that $E[d_{1}]={\\frac{N+1}{K+1}}$. We could also get the formula by using the Hockey Stick Identity, as Benq stated in his comment. Now, according to rearrangement inequality, $\\sum_{i=1}^{n}{\\frac{A_{1}+1}{B_{1}+1}}$ is maximized when $A$ is increasing and $B$ is decreasing. Complexity: $O(NlogN)$",
    "tags": [
      "combinatorics",
      "greedy",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "840",
    "index": "B",
    "title": "Leha and another game about graph",
    "statement": "Leha plays a computer game, where is on each level is given a connected graph with $n$ vertices and $m$ edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer $d_{i}$, which can be equal to $0$, $1$ or $ - 1$. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, $d_{i}$ = - 1 or it's degree modulo 2 is equal to $d_{i}$. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.",
    "tutorial": "Model solution uses the fact that the graph is connected. We'll prove that \"good\" subset exists iff $- 1$ values among $d_{i}$ can be changed to $0 / 1$ so that $\\sum_{i=1}^{n}d_{i}$ is even. If the sum can only be odd, there is no solution obviously (every single valid graph has even sum of degrees). Now we'll show how to build the answer for any case with even sum. First of all, change all $- 1$ values so that the sum becomes even. Then let's find any spanning tree and denote any vertex as the root. The problem is actually much easier now. Let's process vertices one by one, by depth: from leaves to root. Let's denote current vertex as $cur$. There are two cases: 1) $d_{cur} = 0$ In this case we ignore the edge from $cur$ to $parent_{cur}$ and forget about $cur$. Sum remains even. 2) $d_{cur} = 1$ In this case we add the edge from $cur$ to $parent_{cur}$ to the answer, change $d_{parentcur}$ to the opposite value and forget about $cur$. As you can see, sum changed its parity when we changed $d_{parentcur}$, but then it changed back when we discarded $cur$. So, again, sum remains even. Using this simple manipulations we come up with final answer. Complexity: $O(N + M)$",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "840",
    "index": "C",
    "title": "On the Bench",
    "statement": "A year ago on the bench in public park Leha found an array of $n$ numbers. Leha believes that permutation $p$ is right if for all $1 ≤ i < n$ condition, that $a_{pi}·a_{pi + 1}$ is not perfect square, holds. Leha wants to find number of right permutations modulo $10^{9} + 7$.",
    "tutorial": "Let's divide all numbers into groups. Scan all numbers from left to right. Suppose that current position is $i$. If $group_{i}$ is not calculated yet, $i$ forms a new group. Assign unique number to $group_{i}$. Then for all $j$ such that $j > i$ and $a[j] \\cdot a[i]$ is a perfect square, make $group_{j}$ equal to $group_{i}$. Now we can use dynamic programming to calculate the answer. $F(i, j)$ will denote the number of ways to place first $i$ groups having $j$ \"bad\" pairs of neighbors. Suppose we want to make a transition from $F(i, j)$. Let's denote size of group $i$ as $size$, and total count of numbers placed before as $total$. We will iterate $S$ from $1$ to $min(size, total + 1)$ and $D$ from $0$ to $min(j, S)$. $S$ is the number of subsegments we will break the next group in, and $D$ is the number of currently existing \"bad\" pairs we will eliminate. This transition will add $T$ to $F(i + 1, j - D + size - S)$ ($D$ \"pairs\" eliminated, $size - S$ new pairs appeared after placing new group). $T$ is the number of ways to place the new group according to $S$ and $D$ values. Actually it's $s i z e!\\cdot\\left(\\stackrel{s i z e-1}{S-1}\\right)\\cdot\\left(\\stackrel{j}{D}\\right)\\cdot\\left(\\stackrel{t o t a l+1-j}{S-D}\\right)$. Why? Because there are $\\textstyle{\\binom{s(s z e-1)}{S-1}}$ ways to break group of size $size$ into $S$ subsegments. $\\textstyle{\\binom{j}{D}}$ ways to select those $D$ \"bad\" pairs out of existing $j$ we will eliminate. And $\\stackrel{\\left(v a l a+1-3\\right)}{\\leq}$ ways to choose placements for $S - D$ subsegment (other $D$ are breaking some pairs so their positions are predefined). After all calculations, the answer is $F(g, 0)$, where $g$ is the total number of groups. Complexity: O(N^3)",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "840",
    "index": "D",
    "title": "Destiny",
    "statement": "Once, Leha found in the left pocket an array consisting of $n$ integers, and in the right pocket $q$ queries of the form $l$ $r$ $k$. If there are queries, then they must be answered. Answer for the query is minimal $x$ such that $x$ occurs in the interval $l$ $r$ strictly more than $\\textstyle{\\frac{r-l+1}{k}}$ times or $ - 1$ if there is no such number. Help Leha with such a difficult task.",
    "tutorial": "We will use classical divide and conquer approach to answer each query. Suppose current query is at subsegment $[L;R]$. Divide the original array into two parts: $[1;mid]$ and $[mid + 1;N]$, where $m i d={\\frac{L+R}{2}}$. If our whole query belongs to the first or the second part only, discard the other part and repeat the process of division. Otherwise, $L  \\le  mid  \\le  R$. We claim that if we form a set of $K$ most frequent values on $[L;mid]$ and $K$ most frequent values on $[mid + 1;R]$, one of the values from this set will be the answer, or there is no suitable value. $K$ most frequent values thing can be precalculated. Run recursive function $build(node, L, R)$. First, like in a segment tree, we'll run this function from left and right son of $node$. Then we need $K$ most frequent values to be precalculated for all subsegments $[L1;R1]$, such that $L  \\le  L1  \\le  R1  \\le  R$ and at least one of $L1$ and $R1$ is equal to $\\frac{L+R}{2}$. We will consider segments such that their left border is $mid$ in the following order: $[mid;mid], [mid;mid + 1], ...[mid;R]$. If we already have $K$ most frequent values and their counts for $[mid, i]$, it's rather easy to calculate them for $[mid, i + 1]$. We update the count of $a_{i + 1}$ and see if anything should be updated for the new list of most frequent values. Exactly the same process happens to the left side of $mid$: we are working with the subsegments in order $[mid;mid], [mid - 1;mid], ..., [L;mid]$. Now, having all this data precalculated, we can easily run divide and conquer and get the candidates for being the solution at any $[L;R]$ segment. Checking a candidate is not a problem as well: we can save all occurrences in the array for each number and then, using binary search, easily answer the following questions: \"How many times $x$ appears from $L$ to $R$?\". Complexity: O(KNlogN)",
    "tags": [
      "data structures",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "840",
    "index": "E",
    "title": "In a Trap",
    "statement": "Lech got into a tree consisting of $n$ vertices with a root in vertex number $1$. At each vertex $i$ written integer $a_{i}$. He will not get out until he answers $q$ queries of the form $u$ $v$. Answer for the query is maximal value $a_{i}\\oplus d i s t(i,v)$ among all vertices $i$ on path from $u$ to $v$ including $u$ and $v$, where $dist(i, v)$ is number of edges on path from $i$ to $v$. Also guaranteed that vertex $u$ is ancestor of vertex $v$. Leha's tastes are very singular: he believes that vertex is ancestor of itself.\n\nHelp Leha to get out.\n\nThe expression $x\\oplus y$ means the bitwise exclusive OR to the numbers $x$ and $y$.\n\nNote that vertex $u$ is ancestor of vertex $v$ if vertex $u$ lies on the path from root to the vertex $v$.",
    "tutorial": "The path from $u$ to $v$ can be divided into blocks of $256$ nodes and (possibly) a single block with less than $256$ nodes. We can consider this last block separately, by iterating all of its nodes. Now we need to deal with the blocks with length exactly $256$. They are determined by two numbers: $x$ - last node in the block, and $d$ - $8$ highest bits. We can precalculate this values and then use them to answer the queries. Let's now talk about precalculating $answer(x, d)$. Let's fix $x$ and $255$ nodes after $x$. It's easy to notice that lowest $8$ bits will always be as following: $0, 1, ..., 255$. We can xor this values: $0$ with $a_{x}$, $1$ with $a_{nextx}$ and so on, and store the results in a trie. Now we can iterate all possible values of $d$ (from $0$ to $255$) and the only thing left is to find a number stored in a trie, say $q$, such that $q$ xor $255 \\cdot d$ is maximized. Complexity: O(NsqrtNlogN)",
    "tags": [
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "841",
    "index": "A",
    "title": "Generous Kefa",
    "statement": "One day Kefa found $n$ baloons. For convenience, we denote color of $i$-th baloon as $s_{i}$ — lowercase letter of the Latin alphabet. Also Kefa has $k$ friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out \\textbf{all} baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.",
    "tutorial": "Consider each balloon color separately. For some color $c$, we can only assign all balloons of this color to Kefa's friends if $c  \\le  k$. Because otherwise, by pigeonhole principle, at least one of the friends will end up with at least two balloons of the same color. This leads us to a fairly simple solution: calculate number of occurrences for each color, like, $cnt_{c}$. Then just check that $cnt_{c}  \\le  k$ for each possible $c$. Complexity: $O(N + K)$",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "841",
    "index": "B",
    "title": "Godsend",
    "statement": "Leha somehow found an array consisting of $n$ integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?",
    "tutorial": "First player wins if there is at least one odd number in the array. Let's prove this. Let's denote total count of odd numbers at $T$. There are two cases to consider: 1) $T$ is odd. First player takes whole array and wins. 2) $T$ is even. Suppose that position of the rightmost odd number is $pos$. Then the strategy for the first player is as follows: in his first move, pick subarray $[1;pos - 1]$. The remaining suffix of the array will have exactly one odd number that second player won't be able to include in his subarray. So, regardless of his move, first player will take the remaining numbers and win.",
    "tags": [
      "games",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "842",
    "index": "A",
    "title": "Kirill And The Game",
    "statement": "Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.\n\nFor each two integer numbers $a$ and $b$ such that $l ≤ a ≤ r$ and $x ≤ b ≤ y$ there is a potion with experience $a$ and cost $b$ in the store (that is, there are $(r - l + 1)·(y - x + 1)$ potions).\n\nKirill wants to buy a potion which has efficiency $k$. Will he be able to do this?",
    "tutorial": "Let's denote the potion's amount of experience as $exp$ and its cost as $cost$. We want to know if there is a potion such that $exp$ and $cost$ meet the following condition: $\\stackrel{\\alpha,p}{\\omega,q}=k$. To do this, we can iterate on $cost$ from $x$ to $y$ and check that $exp = k \\cdot cost$ is not less than $l$ and not greater than $r$.",
    "code": "\"#include<bits/stdc++.h>\\n#define int long long\\nusing namespace std;\\n\\nsigned main()\\n{\\n    // k = exp / cost;\\n    int l, r, x, y, k;\\n    bool ans = 0;\\n    cin >> l >> r >> x >> y >> k;\\n    for (int i = x; i <= y; i++)\\n    {\\n        if (l <= i * k && i * k <= r)\\n        {\\n            ans = 1;\\n        }\\n    }\\n    if (ans)\\n    {\\n        cout << \\\"YES\\\";\\n    }\\n    else\\n    {\\n        cout << \\\"NO\\\";\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "brute force",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "842",
    "index": "B",
    "title": "Gleb And Pizza",
    "statement": "Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.\n\nThe pizza is a circle of radius $r$ and center at the origin. Pizza consists of the main part — circle of radius $r - d$ with center at the origin, and crust around the main part of the width $d$. Pieces of sausage are also circles. The radius of the $i$ -th piece of the sausage is $r_{i}$, and the center is given as a pair ($x_{i}$, $y_{i}$).\n\nGleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.",
    "tutorial": "To understand whether some piece of sausage intersects with pizza, we can check if their borders intersect. And to check this, since their borders are circles, we are interested in their radii and the distance between their centers. To check if a piece of sausage is inside the crust, we firstly check that it is inside the pizza $({\\sqrt{x^{2}+y^{2}}})+c r\\leq r$), and secondly check that it is completely outside the central part of the pizza $({\\sqrt{x^{2}+y^{2}}}\\geq r-d+c r$).",
    "code": "\"#include <iostream>\\n#include <iomanip>\\n#include <cstdio>\\n#include <map>\\n#include <set>\\n#include <queue>\\n#include <stack>\\n#include <vector>\\n#include <string>\\n#include <ctime>\\n#include <cassert>\\n#include <algorithm>\\n#include <cmath>\\n\\n//#include <unordered_set>\\n//#include <unordered_map>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define for1(i, n) for (int i = 1; i < int(n); i++)\\n#define forft(i, from, to) for (int i = int(from); i < int(to); i++)\\n#define forr(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define X first\\n#define Y second\\n#define mp make_pair\\n#define pb push_back\\n#define sz(a) int(a.size())\\n#define all(a) a.begin(), a.end()\\n#define ms(a, v) memset(a, v, sizeof(a))\\n#define correct(x, y, n, m) (x >= 0 && x < n && y >= 0 && y < m)\\n\\nusing namespace std;\\n\\ntemplate<typename T> T sqr(const T &x) {\\n    return x * x;\\n}\\n\\ntypedef long long ll;\\ntypedef long long li;\\ntypedef pair<int, int> pt;\\ntypedef long double ld;\\ntypedef pair<ld, ld> pd;\\n\\nconst int INF = int(1e9);\\nconst ll INF_LL = ll(4e18);\\nconst ll INF64 = ll(4e18);\\nconst ll LINF = ll(4e18);\\nconst ld EPS = 1e-9;\\nconst ld PI = 3.14159265358979323846264338;\\n\\nint r, d;\\nint n;\\n\\nbool read() {\\n    scanf(\\\"%d%d%d\\\", &r, &d, &n);\\n    return true;\\n}\\n\\nvoid solve() {\\n    int ans = 0;\\n\\n    forn(i, n) {\\n        int x, y, cr;\\n        scanf(\\\"%d%d%d\\\", &x, &y, &cr);\\n\\n        if (sqr(li(x)) + sqr(li(y)) <= sqr(li(r - cr)) && 2 * cr <= d && sqr(li(x)) + sqr(li(y)) >= sqr(li(r - d + cr))) {\\n            ++ans;\\n        }\\n    }\\n\\n    printf(\\\"%d\\\\n\\\", ans);\\n}\\n\\nint main() {\\n    srand((int) time(NULL));\\n    cout << setprecision(10) << fixed;\\n    \\n    read();\\n    solve();\\n\\n    cerr << clock() << endl;\\n\\n    return 0;\\n}\"",
    "tags": [
      "geometry"
    ],
    "rating": 1100
  },
  {
    "contest_id": "842",
    "index": "C",
    "title": "Ilya And The Tree",
    "statement": "Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex $1$. There is an integer number written on each vertex of the tree; the number written on vertex $i$ is equal to $a_{i}$.\n\nIlya believes that the beauty of the vertex $x$ is the greatest common divisor of all numbers written on the vertices on the path from the root to $x$, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to $0$ or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have.\n\nFor each vertex the answer must be considered independently.\n\nThe beauty of the root equals to number written on it.",
    "tutorial": "It's easy to see that if the number written on some vertex $i$ is not equal to $0$, then its beauty will be some divisor of $a_{i}$. Also if the number written on the root is $0$ then the beauty of each vertex can be easily calculated. Otherwise beauty of each vertex will be a divisor of the number in the root. Let's calculate the beauty of each vertex if the number in the root is 0. This can be done by traversing the tree, and the beauty of $i$ is $gcd(a_{i}, ans[par_{i}])$. If the number in the root is not $0$, then possible values of beauty for each vertex are among divisors of this number. For each of these divisors we can maintain how many numbers on the path from the root to current vertex are divisible by that divisor. When we enter or leave some vertex, we need to update this information by iterating on divisors of the number in the root. If we maintain it and current depth $d$, then we can calculate the possible beauty of current vertex. It is equal to greatest divisor such that there are at least $d - 1$ numbers on the path that are divisible by this divisor.",
    "code": "\"#include<bits/stdc++.h>\\n#define f first\\n#define s second\\nusing namespace std;\\n\\nint n;\\nvector<int>ans;\\nvector<bool>vis;\\nvector<int>mas;\\nvector<int>del;\\nvector<int>koll;\\nvector<vector<int>>edges;\\n\\nint nod(int a, int b)\\n{\\n    if (b == 0)\\n        return a;\\n    return nod(b, a % b);\\n}\\n\\nvoid dfs1(int v)\\n{\\n    vis[v] = 1;\\n    for (auto u : edges[v])\\n        if (! vis[u])\\n        {\\n            ans[u] = nod(ans[v], mas[u]);\\n            dfs1(u);\\n        }\\n}\\n\\nvoid dfs2(int v, int dist)\\n{\\n    vis[v] = 1;\\n    for (int i = 0; i < del.size(); i++)\\n    {\\n        koll[i] += (mas[v] % del[i] == 0);\\n        if (koll[i] >= dist)\\n            ans[v] = max(ans[v], del[i]);\\n    }\\n    for (auto u : edges[v])\\n        if (! vis[u])\\n            dfs2(u, dist + 1);\\n    for (int i = 0; i < del.size(); i++)\\n        koll[i] -= (mas[v] % del[i] == 0);\\n}\\n\\nsigned main()\\n{\\n    ios_base::sync_with_stdio(0);\\n    int n;\\n    cin>>n;\\n    ans.resize(n);\\n    vis.resize(n);\\n    mas.resize(n);\\n    edges.resize(n);\\n    for (int i = 0; i < n; i++)\\n        cin>>mas[i];\\n    for (int i = 0; i < n - 1; i++)\\n    {\\n        int a, b;\\n        cin>>a>>b;\\n        a--; b--;\\n        edges[a].push_back(b);\\n        edges[b].push_back(a);\\n    }\\n    int p = mas[0];\\n    mas[0] = 0;\\n    ans[0] = 0;\\n    dfs1(0);\\n    mas[0] = p;\\n    for (int i = 0; i < n; i++)\\n        vis[i] = 0;\\n    for (int i = 1; i*i <= mas[0]; i++)\\n    {\\n        if (mas[0] % i == 0)\\n        {\\n            del.push_back(i);\\n            del.push_back(mas[0] / i);\\n            if (i*i == mas[0])\\n                del.pop_back();\\n        }\\n    }\\n    sort(del.begin(), del.end());\\n    koll.resize(del.size());\\n    dfs2(0, 0);\\n    for (int i = 0; i < n; i++)\\n        cout<<ans[i]<<' ';\\n    return 0;\\n}\"",
    "tags": [
      "dfs and similar",
      "graphs",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "842",
    "index": "D",
    "title": "Vitya and Strange Lesson",
    "statement": "Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, $mex([4, 33, 0, 1, 1, 5]) = 2$ and $mex([1, 2, 3]) = 0$.\n\nVitya quickly understood all tasks of the teacher, but can you do the same?\n\nYou are given an array consisting of $n$ non-negative integers, and $m$ queries. Each query is characterized by one number $x$ and consists of the following consecutive steps:\n\n- Perform the bitwise addition operation modulo $2$ (xor) of each array element with the number $x$.\n- Find mex of the resulting array.\n\nNote that after each query the array changes.",
    "tutorial": "If the last query was $x_{i}$ and then we receive a query $x_{i + 1}$, then we can leave the original array unchanged and use the number $x_{i}\\oplus x_{i+1}$ as the second query. So we will maintain current xor of queries instead of changing the array. It's easy to see that if the array contains all numbers from zero to $2^{k} - 1$ and the number in the query is less than $2^{k}$, then the array will still contain all those numbers. Let's store all numbers from the array in binary trie and maintain the number of leaves in each subtree. To answer each query, we will descend the trie. We need to get the lowest possible answer, so if current bit of the number in the query equals $i$ ($i = 0$ or $i = 1$), so we firstly check the subtree that corresponds to bit $i$. We will descend into the vertex only if the subtree is not a complete binary tree (so there exists a number that would belong to this subtree but is not included in the array). When we try to descend into an empty subtree, then we set all remaining bits in the answer to zero.",
    "code": "\"#include <iostream>\\n#include <iomanip>\\n#include <cstdio>\\n#include <map>\\n#include <set>\\n#include <queue>\\n#include <stack>\\n#include <vector>\\n#include <string>\\n#include <ctime>\\n#include <cassert>\\n#include <algorithm>\\n#include <cmath>\\n\\n//#include <unordered_set>\\n//#include <unordered_map>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n#define for1(i, n) for (int i = 1; i < int(n); i++)\\n#define forft(i, from, to) for (int i = int(from); i < int(to); i++)\\n#define forr(i, n) for (int i = int(n) - 1; i >= 0; i--)\\n#define X first\\n#define Y second\\n#define mp make_pair\\n#define pb push_back\\n#define sz(a) int(a.size())\\n#define all(a) a.begin(), a.end()\\n#define ms(a, v) memset(a, v, sizeof(a))\\n#define correct(x, y, n, m) (x >= 0 && x < n && y >= 0 && y < m)\\n\\nusing namespace std;\\n\\ntemplate<typename T> T sqr(const T &x) {\\n    return x * x;\\n}\\n\\ntypedef long long ll;\\ntypedef long long li;\\ntypedef pair<int, int> pt;\\ntypedef long double ld;\\ntypedef pair<ld, ld> pd;\\n\\nconst int INF = int(1e9);\\nconst ll INF_LL = ll(4e18);\\nconst ll INF64 = ll(4e18);\\nconst ll LINF = ll(4e18);\\nconst ld EPS = 1e-9;\\nconst ld PI = 3.14159265358979323846264338;\\n\\nconst int N = 3e5 + 10;\\nconst int M = 20;\\n\\nint n, m;\\nint a[N];\\n\\nstruct node {\\n    int nxt[2];\\n    int d;\\n\\n    node() {\\n        nxt[0] = -1;\\n        nxt[1] = -1;\\n        d = 0;\\n    }\\n};\\n\\nnode t[N * M];\\nint len = 1;\\n\\nbool read() {\\n    scanf(\\\"%d%d\\\", &n, &m);\\n\\n    forn(i, n) {\\n        scanf(\\\"%d\\\", &a[i]);\\n    }\\n\\n    return true;\\n}\\n\\nvoid add(int v, int num, int pos) {\\n    if (pos < 0) {\\n        t[v].d = 1;\\n        return;\\n    }\\n\\n    int nxt = ((num >> pos) & 1);\\n\\n    if (t[v].nxt[nxt] == -1) {\\n        t[v].nxt[nxt] = len++;\\n    }\\n\\n    add(t[v].nxt[nxt], num, pos - 1);\\n    t[v].d = 0;\\n    \\n    if (t[v].nxt[0] != -1) {\\n        t[v].d += t[t[v].nxt[0]].d;\\n    }\\n    \\n    if (t[v].nxt[1] != -1) {\\n        t[v].d += t[t[v].nxt[1]].d;\\n    }\\n}\\n\\nvoid get(int v, int num, int pos, int &ans) {\\n    if (v == -1) {\\n        return;\\n    }\\n\\n    int nxt = ((num >> pos) & 1);\\n\\n    if (t[t[v].nxt[nxt]].d == (1 << pos)) {        \\n        nxt = 1 - nxt;\\n    }\\n\\n    ans |= ((nxt ^ ((num >> pos) & 1)) << pos);\\n    get(t[v].nxt[nxt], num, pos - 1, ans);\\n}\\n\\nvoid solve() {\\n    forn(i, n) {\\n        add(0, a[i], M - 1);\\n    }\\n\\n    int c = 0;\\n\\n    forn(i, m) {\\n        int k;\\n        scanf(\\\"%d\\\", &k);\\n        c ^= k;\\n\\n        int ans = 0;\\n        get(0, c, M - 1, ans);\\n        printf(\\\"%d\\\\n\\\", ans);\\n    }\\n}\\n\\nint main() {\\n    srand((int) time(NULL));\\n    cout << setprecision(10) << fixed;\\n    \\n    read();\\n    solve();\\n\\n    cerr << clock() << endl;\\n\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2000
  },
  {
    "contest_id": "842",
    "index": "E",
    "title": "Nikita and game",
    "statement": "Nikita plays a new computer game. There are $m$ levels in this game. In the beginning of each level a new class appears in the game; this class is a child-class of the class $y_{i}$ (and $y_{i}$ is called parent-class for this new class). Thus, the classes form a tree. Initially there is only one class with index $1$.\n\nChanging the class to its neighbour (child-class or parent-class) in the tree costs $1$ coin. You can not change the class back. The cost of changing the class $a$ to the class $b$ is equal to the total cost of class changes on the path from $a$ to $b$ in the class tree.\n\nSuppose that at $i$ -th level the maximum cost of changing one class to another is $x$. For each level output the number of classes such that for each of these classes there exists some other class $y$, and the distance from this class to $y$ is exactly $x$.",
    "tutorial": "The vertices in the answer are the endpoints of some diameter of the tree. Let's consider diameter ($a$, $b$), where $a$ and $b$ are its endpoints, and we add a new vertex $c$. Then the length of diameter either remains the same or increases by one (then new endpoints are vertices ($a$, $c$) or ($b$, $c$)). We have to maintain current centers of the tree (there are not more than two centers). If the length of diameter increases, then the number of centers changes (but there will always exist a vertex that was the center before the query and remains the center after the query). Let's build a segment tree on the eulerian tour of the tree. The vertex that maintains the segment $[l, r]$ will store current maximal distance to the center and the number of vertices that have this distance. Then the answer for the query will be stored in the root of the segment tree. When we add a new vertex, we need to check whether the length of diameter increases; this can be done with LCA. If the diameter increases, we update centers and distances to them.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nconst int INF = int(1e9), N = 1e6, M = 21;\\n\\nint n, up[M][N], tin[N], tout[N], p[4 * N], timer;\\npair<int, int> t[4 * N];\\nvector<int> g[N];\\n\\nvoid push(int now)\\n{\\n\\tif (p[now] == 0)\\n    {\\n\\t\\treturn;\\n\\t}\\n\\tt[now].first += p[now];\\n\\tif (now * 2 + 2 < 4 * N)\\n\\t{\\n\\t\\tp[now * 2 + 1] += p[now];\\n\\t\\tp[now * 2 + 2] += p[now];\\n\\t}\\n\\tp[now] = 0;\\n}\\n\\nvoid update1(int now)\\n{\\n\\tint l = now * 2 + 1;\\n\\tint r = now * 2 + 2;\\n\\tif (t[l].first > t[r].first)\\n    {\\n\\t\\tt[now] = t[l];\\n\\t}\\n\\telse if (t[r].first > t[l].first)\\n    {\\n        t[now] = t[r];\\n    }\\n    else\\n    {\\n        t[now] = t[l];\\n        t[now].second += t[r].second;\\n\\t}\\n}\\n\\nvoid change(int now, int l, int r, int pos, int val)\\n{\\n\\tpush(now);\\n\\tif (l == r)\\n    {\\n\\t\\tt[now] = {val, 1};\\n\\t\\treturn;\\n\\t}\\n\\tint mid = (l + r) / 2;\\n\\tif (pos <= mid)\\n\\t{\\n\\t\\tchange(now * 2 + 1, l, mid, pos, val);\\n\\t}\\n\\telse\\n    {\\n\\t\\tchange(now * 2 + 2, mid + 1, r, pos, val);\\n\\t}\\n\\tpush(now * 2 + 1);\\n\\tpush(now * 2 + 2);\\n\\tupdate1(now);\\n}\\n\\nvoid update(int now, int l, int r, int tl, int tr, int val)\\n{\\n    if (tl > tr)\\n    {\\n        return;\\n    }\\n\\tpush(now);\\n\\tif (l == tl && r == tr)\\n    {\\n\\t\\tp[now] += val;\\n\\t\\tpush(now);\\n\\t\\treturn;\\n\\t}\\n\\tint mid = (l + r) / 2;\\n\\tupdate(now * 2 + 1, l, mid, tl, min(mid, tr), val);\\n\\tupdate(now * 2 + 2, mid + 1, r, max(tl, mid + 1), tr, val);\\n\\tpush(now * 2 + 1);\\n\\tpush(now * 2 + 2);\\n\\tupdate1(now);\\n}\\n\\nvoid dfs(int v, int p = 0)\\n{\\n\\ttin[v] = timer++;\\n\\tup[0][v] = p;\\n\\tfor(int i = 1; i < M; i++)\\n\\t{\\n        up[i][v] = up[i - 1][up[i - 1][v]];\\n    }\\n\\tfor(int i = 0; i < g[v].size(); i++)\\n\\t{\\n\\t\\tint u = g[v][i];\\n\\t\\tif (u != p)\\n        {\\n\\t\\t\\tdfs(u, v);\\n\\t\\t}\\n\\t}\\n\\ttout[v] = timer++;\\n}\\n\\nbool anc(int p, int v)\\n{\\n\\treturn tin[p] <= tin[v] && tout[v] <= tout[p];\\n}\\n\\nint dist(int v1, int v2)\\n{\\n    if (anc(v1, v2))\\n    {\\n \\t    return 0;\\n    }\\n\\tint ans = 0;\\n\\tfor (int i = M - 1; i >= 0; i--)\\n\\t{\\n\\t\\tif (!anc(up[i][v1], v2))\\n\\t\\t{\\n\\t\\t\\tans += (1 << i);\\n\\t\\t\\tv1 = up[i][v1];\\n\\t\\t}\\n\\t}\\n\\treturn ans + 1;\\n}\\n\\nint lca(int v1, int v2)\\n{\\n\\tfor (int i = M - 1; i >= 0; i--)\\n\\t{\\n\\t\\tif (!anc(up[i][v1], v2))\\n        {\\n\\t\\t\\tv1 = up[i][v1];\\n\\t\\t}\\n\\t}\\n\\treturn v1;\\n}\\n\\nint main()\\n{\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(0);\\n    cout.tie(0);\\n    cin >> n;\\n    n++;\\n\\tfor(int i = 1; i < n; i++)\\n\\t{\\n\\t\\tint x;\\n\\t\\tcin >> x;\\n\\t\\tx--;\\n\\t\\tg[i].push_back(x);\\n\\t\\tg[x].push_back(i);\\n\\t}\\n\\tfor (int i = 0; i < N * 4; i++)\\n    {\\n        t[i] = {-INF, 0};\\n    }\\n    dfs(0);\\n\\tpair<int, int> c = {0, -1};\\n\\tchange(0, 0, 2 * n - 1, tin[0], 0);\\n\\tfor(int i = 1; i < n; i++)\\n\\t{\\n\\t\\tint cd = t[0].first;\\n\\t\\tint v = i;\\n\\t\\tint nd = dist(v, c.first) + dist(c.first, v);\\n\\t\\tif (c.second != -1)\\n        {\\n\\t\\t\\tint nd2 = dist(v, c.second) + dist(c.second, v);\\n\\t\\t\\tif (nd2 < nd)\\n            {\\n\\t\\t\\t\\tnd = nd2;\\n\\t\\t\\t\\tswap(c.first, c.second);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tchange(0, 0, 2 * n - 1, tin[v], nd);\\n\\t\\tif (nd > cd)\\n        {\\n            pair<int, int> nc;\\n            if (c.second != -1)\\n            {\\n                nc = {c.first, -1};\\n                if (anc(c.first, c.second))\\n                {\\n                    update(0, 0, 2 * n - 1, tin[c.second], tout[c.second], 1);\\n                }\\n                else\\n                {\\n                    if (c.first > 0)\\n                    {\\n                        update(0, 0, 2 * n - 1, 0, tin[c.first] - 1, 1);\\n                    }\\n                    if (c.first < 2 * n - 1)\\n                    {\\n                        update(0, 0, 2 * n - 1, tout[c.first] + 1, 2 * n - 1, 1);\\n                    }\\n                }\\n            }\\n            else\\n            {\\n                if (anc(c.first, v))\\n                {\\n                    nc = {lca(v, c.first), c.first};\\n                }\\n                else\\n                {\\n                    nc = {up[0][c.first], c.first};\\n                }\\n                if (anc(nc.first, nc.second))\\n                {\\n                    if (nc.second > 0)\\n                    {\\n                        update(0, 0, 2 * n - 1, 0, tin[nc.second] - 1, -1);\\n                    }\\n                    if (nc.second < 2 * n - 1)\\n                    {\\n                        update(0, 0, 2 * n - 1, tout[nc.second] + 1, 2 * n - 1, -1);\\n                    }\\n                }\\n                else\\n                {\\n                    update(0, 0, 2 * n - 1, tin[nc.first], tout[nc.first], -1);\\n                }\\n            }\\n            c = nc;\\n        }\\n        cout << t[0].second << \\\"\\\\n\\\";\\n\\t}\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "dfs and similar",
      "divide and conquer",
      "graphs",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "843",
    "index": "A",
    "title": "Sorting by Subsequences",
    "statement": "You are given a sequence $a_{1}, a_{2}, ..., a_{n}$ consisting of \\textbf{different} integers. It is required to split this sequence into the \\textbf{maximum} number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.\n\nSorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.\n\nEvery element of the sequence must appear in exactly one subsequence.",
    "tutorial": "Sorting any sequence means applying some permutation to its elements. All elements of sequence $a$ are different, so this permutation is unique and fixed. Let's call it $P$. One could split this permutation into simple cycles. The subsequences in the answer are subsequences formed by these simple cycles. One could prove that it's impossible to split the sequence into more subsequences because if we could split the sequence into more subsequences, we also could split permutation $P$ into more cycles.",
    "tags": [
      "dfs and similar",
      "dsu",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "843",
    "index": "B",
    "title": "Interactive LowerBound",
    "statement": "This is an interactive problem.\n\nYou are given a \\textbf{sorted} in increasing order singly linked list. You should find the minimum integer in the list which is greater than or equal to $x$.\n\nMore formally, there is a singly liked list built on an array of $n$ elements. Element with index $i$ contains two integers: $value_{i}$ is the integer value in this element, and $next_{i}$ that is the index of the next element of the singly linked list (or -1, if the current element is the last). The list is sorted, i.e. if $next_{i} ≠ - 1$, then $value_{nexti} > value_{i}$.\n\nYou are given the number of elements in the list $n$, the index of the first element $start$, and the integer $x$.\n\nYou can make up to $2000$ queries of the following two types:\n\n- ? i ($1 ≤ i ≤ n$) — ask the values $value_{i}$ and $next_{i}$,\n- ! ans — give the answer for the problem: the minimum integer, greater than or equal to $x$, or ! -1, if there are no such integers. Your program should terminate after this query.\n\nWrite a program that solves this problem.",
    "tutorial": "Let's ask the values in index $start$ and in 999 other random indexes, choose among them the largest value less or equal to $x$. Let's go from it in order to the elements of the list, until we meet the first element greater or equal to x, which will be the answer. The probability that this algorithm for 2000 of actions will not find the desired element is equal to the probability that among 1000 of previous before the correct answer of the list elements there will no one from our sample of 999 random elements. This probability can be estimated as $(1 - 999 / n)^{1000}  \\approx  1.7 \\cdot 10^{ - 9}$ In order to not be hacked in this problem, you should use high-precision current system time as a random seed.",
    "tags": [
      "brute force",
      "interactive",
      "probabilities"
    ],
    "rating": 2000
  },
  {
    "contest_id": "843",
    "index": "C",
    "title": "Upgrading Tree",
    "statement": "You are given a tree with $n$ vertices and you are allowed to perform \\textbf{no more than} $2n$ transformations on it. Transformation is defined by three vertices $x, y, y'$ and consists of deleting edge $(x, y)$ and adding edge $(x, y')$. Transformation $x, y, y'$ could be performed if all the following conditions are satisfied:\n\n- There is an edge $(x, y)$ in the current tree.\n- After the transformation the graph remains a tree.\n- After the deletion of edge $(x, y)$ the tree would consist of two connected components. Let's denote the set of nodes in the component containing vertex $x$ by $V_{x}$, and the set of nodes in the component containing vertex $y$ by $V_{y}$. Then condition $|V_{x}| > |V_{y}|$ should be satisfied, i.e. the size of the component with $x$ should be strictly larger than the size of the component with $y$.\n\nYou should \\textbf{minimize} the sum of squared distances between all pairs of vertices in a tree, which you could get after no more than $2n$ transformations and output any sequence of transformations leading initial tree to such state.\n\nNote that you don't need to minimize the number of operations. It is necessary to minimize only the sum of the squared distances.",
    "tutorial": "A centroid-vertex remains a centroid during such process. If we have two centroids in a tree, the edge between them couldn't change. The components that are attached to the centroid can not change centroid they attached to or separate to several components. Using the size of the component operations, one could turn it into a bamboo, then using the size of the component operations one could turn it into a hedgehog suspended from its centroid. The proof that the sum of squares of distances couldn't be less is an additional exercise. Complexity of solution is ${\\mathrm{on}}$",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "math",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "843",
    "index": "D",
    "title": "Dynamic Shortest Path",
    "statement": "You are given a weighted directed graph, consisting of $n$ vertices and $m$ edges. You should answer $q$ queries of two types:\n\n- 1 v — find the length of shortest path from vertex $1$ to vertex $v$.\n- {2 c $l_{1} l_{2} ... l_{c}$} — add $1$ to weights of edges with indices $l_{1}, l_{2}, ..., l_{c}$.",
    "tutorial": "Firstly, let's run an usual Dijkstra from $s$, find distances and make them a potentials of vertices. Then for each request let's recalculate all distances and make the potentials equal to these distances. To quickly recalculate the distance between requests, we can use the fact that in a graph with potentials, all distances are 0. When we increased the weight of some edges by 1, in the graph with potentials, all distances do not exceed the number of changed edges so we can run a Dijkstra on a vector per $O(V + E)$.",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 3400
  },
  {
    "contest_id": "843",
    "index": "E",
    "title": "Maximum Flow",
    "statement": "You are given a directed graph, consisting of $n$ vertices and $m$ edges. The vertices $s$ and $t$ are marked as source and sink correspondingly. Additionally, there are no edges ending at $s$ and there are no edges beginning in $t$.\n\nThe graph was constructed in a following way: initially each edge had capacity $c_{i} > 0$. A maximum flow with source at $s$ and sink at $t$ was constructed in this flow network. Let's denote $f_{i}$ as the value of flow passing through edge with index $i$. Next, all capacities $c_{i}$ and flow value $f_{i}$ were erased. Instead, indicators $g_{i}$ were written on edges — if flow value passing through edge $i$ was positive, i.e. $1$ if $f_{i} > 0$ and $0$ otherwise.\n\nUsing the graph and values $g_{i}$, find out what is the \\textbf{minimum} possible number of edges in the initial flow network that could be saturated (the passing flow is equal to capacity, i.e. $f_{i} = c_{i}$). Also construct the corresponding flow network with maximum flow in it.\n\nA flow in directed graph is described by flow values $f_{i}$ on each of the edges so that the following conditions are satisfied:\n\n- for each vertex, except source and sink, total incoming flow and total outcoming flow are equal,\n- for each edge $0 ≤ f_{i} ≤ c_{i}$\n\nA flow is maximum if the difference between the sum of flow values on edges from the source, and the sum of flow values on edges to the source (there are no such in this problem), is maximum possible.",
    "tutorial": "Let's find a minimal set of saturated edges. We will create new flow network consisting of the same set of vertices and a little bit different edges. For an each edge from original graph without any flow let's create a new edge with the same direction and $c = INF$ carrying capacity. For every edge with a flow let's create two edges: the first one with the same direction and $c = 1$ capacity and the second edge with reversed direction and $c = INF$. In the new network, we have to find the minimum cut, it will consist of edges with $f = 1$, corresponding edges of the initial graph will be a desired minimal set. If this minimal set was equal to infinity the description of the problem wouldn't be about maximum flow because it had to be increasing for sure. So now it's enough to create a non-zero flow for all edges needed in the task and to make $c = f$ on edges which we chose to be saturated and $c = f + 1$ on the rest. Let's consider directed graph with edges with a flow. Lemma: Every edge of a graph lies either on a cycle or on the way from source to flow. In the first situation we might make a circulation on a cycle $1$, in the second case, we can put a flow on the way from the source to the stream of $1$. Thus, for each edge on which something is to flow, something will flow. The proof of Lemma: Suppose the contrary. Let's take the edge of the form $u$->$v$. Well then, there is no way from $s$ to $u$ or no way from $v$ to $t$. Let the second be true without loss of generality. Let's consider the set of vertices attainable from $v$. If there are $u$ in this set, there is a cycle. Otherwise, this set is \"bad\", cause there are no $t$, in it something flows in and nothing follows, in a correct network this is impossible.",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "844",
    "index": "A",
    "title": "Diversity",
    "statement": "Calculate the minimum number of characters you need to change in the string $s$, so that it contains at least $k$ different letters, or print that it is impossible.\n\nString $s$ consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.",
    "tutorial": "One could note what in case $k > |s|$, we should always print <<impossible>>. Overwise the finding value is equal $max(0, k - d)$, where $d$ is a number of different letters in the original string. It is correct because if $k  \\le  d$ condition is satisfied and we shouldn't do anything, so the answer is zero. If $d < k  \\le  |s|$ we could change $k - d$ duplicated letters to a different letters initially weren't contained in $s$. Solution complexity is $\\mathbf{O}(|{\\hat{s}}|)$",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "844",
    "index": "B",
    "title": "Rectangles",
    "statement": "You are given $n × m$ table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that:\n\n- All cells in a set have the same color.\n- Every two cells in a set share row or column.",
    "tutorial": "One could note, that each appropriate set of cells is always contained in one row or in one column. We should calculate numbers of white and black cells $k_{0}$ and $k_{1}$ in every row and every column. For every $k$ we will summarize $2^{k} - 1$ (the number of non-empty subsets of this color contained in one row/column). In the end, we subtract $n \\cdot m$ from the whole sum (this is a number of one-cell sets, which we count twice). Solution complexity is $\\mathrm{Otn}\\cdot\\mathrm{m}\\rangle$",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "845",
    "index": "A",
    "title": "Chess Tourney",
    "statement": "Berland annual chess tournament is coming!\n\nOrganizers have gathered $2·n$ chess players who should be divided into two teams with $n$ people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.\n\nThus, organizers should divide all $2·n$ players into two teams with $n$ people each in such a way that the first team always wins.\n\nEvery chess player has its rating $r_{i}$. It is known that chess player with the greater rating always wins the player with the lower rating. If their ratings are equal then any of the players can win.\n\nAfter teams assignment there will come a drawing to form $n$ pairs of opponents: in each pair there is a player from the first team and a player from the second team. Every chess player should be in exactly one pair. Every pair plays once. The drawing is totally random.\n\nIs it possible to divide all $2·n$ players into two teams with $n$ people each so that the player from the first team in every pair wins \\textbf{regardless} of the results of the drawing?",
    "tutorial": "Let's sort the input array in non-decreasing order. Now we should take the first $n$ players to the first team and the last $n$ players - to the second team. That will guarantee that every member of the first team has greater or equal rating than every member of the second team. Now the only thing left is to check if all ratings in the first teams differ from all the ratings in the second team (if some are equal then $a_{n} = a_{n + 1}$ in sorted order).",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "845",
    "index": "B",
    "title": "Luba And The Ticket",
    "statement": "Luba has a ticket consisting of $6$ digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.\n\nThe ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.",
    "tutorial": "Let's iterate over all 6-digit numbers. Now we will calculate number of positions in which digit of current ticket differs from digit of input ticket and call it $res$. Then answer will be minimal value $res$ over all lucky tickets.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "845",
    "index": "C",
    "title": "Two TVs",
    "statement": "Polycarp is a great fan of television.\n\nHe wrote down all the TV programs he is interested in for today. His list contains $n$ shows, $i$-th of them starts at moment $l_{i}$ and ends at moment $r_{i}$.\n\nPolycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.\n\nPolycarp wants to check out all $n$ shows. Are two TVs enough to do so?",
    "tutorial": "Let's process all the segments on the line from left to right. For each segment we should push events ($l_{i}, 1$) and ($r_{i} + 1, - 1$) into some array. Sort this array of pair in increasing order (usual less comparator for pairs). Then we iterate over its elements and maintain $cnt$ - the current amount of open segments (we passed their left border and didn't pass their right border). When we meet the event of the first type, we increment the value of $cnt$, the second type - decrement $cnt$. If $cnt  \\ge  3$ in some moment then the answer is \"NO\". Overall complexity: $O(n\\cdot\\log n)$.",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "845",
    "index": "D",
    "title": "Driving Test",
    "statement": "Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types.\n\n- speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type);\n- overtake is allowed: this sign means that after some car meets it, it can overtake any other car;\n- no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign);\n- no overtake allowed: some car can't overtake any other car after this sign.\n\nPolycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more \"no overtake allowed\" signs go one after another with zero \"overtake is allowed\" signs between them. It works with \"no speed limit\" and \"overtake is allowed\" signs as well.\n\nIn the beginning of the ride overtake is allowed and there is no speed limit.\n\nYou are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types:\n\n- Polycarp changes the speed of his car to specified (this event comes with a positive integer number);\n- Polycarp's car overtakes the other car;\n- Polycarp's car goes past the \"speed limit\" sign (this sign comes with a positive integer);\n- Polycarp's car goes past the \"overtake is allowed\" sign;\n- Polycarp's car goes past the \"no speed limit\";\n- Polycarp's car goes past the \"no overtake allowed\";\n\nIt is guaranteed that the first event in chronological order is the event of type $1$ (Polycarp changed the speed of his car to specified).\n\nAfter the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?",
    "tutorial": "Let's notice that you should never say that you didn't notice signs \"no speed limit\" and \"overtake is allowed\". Also if you drive with speed $sp$, you don't want to remove signs \"speed limit\" with number greater or equal to $sp$. Thus, greedy solution will work. Process all the events in chronological order. We should maintain stack of signs \"speed limit\" and amount of signs \"no overtake allowed\". If we meet sign \"speed limit\", we push its limit to stack, sign \"no overtake allowed\" - increase $cnt$, \"no speed limit\" - clear stack, \"overtake is allowed\" - assign $cnt$ to zero. After every event we should check if our speed is fine. While value of sign on the top of the stack is less than current speed, pop it and increase answer. If we overtake someone, we add $cnt$ to answer and assign $cnt$ to zero. Overall complexity: $O(n)$.",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "845",
    "index": "E",
    "title": "Fire in the City",
    "statement": "The capital of Berland looks like a rectangle of size $n × m$ of the square blocks of same size.\n\nFire!\n\nIt is known that $k + 1$ blocks got caught on fire ($k + 1 ≤ n·m$). Those blocks are centers of ignition. Moreover positions of $k$ of these centers are known and one of these stays unknown. All $k + 1$ positions are distinct.\n\nThe fire goes the following way: during the zero minute of fire only these $k + 1$ centers of ignition are burning. Every next minute the fire goes to all neighbouring blocks to the one which is burning. You can consider blocks to burn for so long that this time exceeds the time taken in the problem. The neighbouring blocks are those that touch the current block by a side or by a corner.\n\nBerland Fire Deparment wants to estimate the minimal time it takes the fire to lighten up the whole city. Remember that the positions of $k$ blocks (centers of ignition) are known and ($k + 1$)-th can be positioned in any other block.\n\nHelp Berland Fire Department to estimate the minimal time it takes the fire to lighten up the whole city.",
    "tutorial": "We can use binary search to find the answer. When binary searching, to check whether the whole city will be lightened up after $t$ minutes, we can use sweep line technique to find the smallest $x$-coordinate of the cell that is not lightened by $k$ centers of ignition (and the smallest $y$-coordinate too). Suppose that $x_{0}$ and $y_{0}$ are these coordinates; then we can place the last center of ignition at coordinates $(x_{0} + t, y_{0} + t)$. Then we can use sweep line again to check whether the city is fully ignited.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "845",
    "index": "F",
    "title": "Guards In The Storehouse",
    "statement": "Polycarp owns a shop in the capital of Berland. Recently the criminal activity in the capital increased, so Polycarp is thinking about establishing some better security in the storehouse of his shop.\n\nThe storehouse can be represented as a matrix with $n$ rows and $m$ columns. Each element of the matrix is either . (an empty space) or x (a wall).\n\nPolycarp wants to hire some guards (possibly zero) to watch for the storehouse. Each guard will be in some cell of matrix and will protect every cell to the right of his own cell and every cell to the bottom of his own cell, until the nearest wall. More formally, if the guard is standing in the cell $(x_{0}, y_{0})$, then he protects cell $(x_{1}, y_{1})$ if all these conditions are met:\n\n- $(x_{1}, y_{1})$ is an empty cell;\n- either $x_{0} = x_{1}$ and $y_{0} ≤ y_{1}$, or $x_{0} ≤ x_{1}$ and $y_{0} = y_{1}$;\n- there are no walls between cells $(x_{0}, y_{0})$ and $(x_{1}, y_{1})$. \\textbf{There can be a guard between these cells, guards can look through each other.}\n\nGuards can be placed only in empty cells (and can protect only empty cells). The plan of placing the guards is some set of cells where guards will be placed (of course, two plans are different if there exists at least one cell that is included in the first plan, but not included in the second plan, or vice versa). Polycarp calls a plan suitable if there is \\textbf{not more than one} empty cell that is not protected.\n\nPolycarp wants to know the number of suitable plans. Since it can be very large, you have to output it modulo $10^{9} + 7$.",
    "tutorial": "This problem can be solved using dynamic programming with broken profile. First of all, we have to make the number of rows not larger than $15$; if it is larger, then we can just rotate the given matrix. Let's fill the matrix from left to right, and in each column from top to bottom. Let $dp[pos][mask][f1][f2]$ be the number of ways to achieve the following situation: we now want to fill cell with index $pos$, $mask$ denotes the rows which are already protected in this column (so there is a wall in this row or there is a guard to the left), $f1$ is a flag that denotes if current cell is protected by some guard above, and $f2$ is a flag that denotes if there was a cell that was not protected. When advancing from one column to another, we have to change the mask so we update the rows that are currently protected. The rows such that in the previous column there was a wall in this row become un-protected, and the rows such that there is a wall in current column in this row become protected. And, of course, $f1$ becomes zero. When we place a guard, we set $f1$ to one and make the corresponding row protected. And when we are at the wall, we have to set $f1$ to zero, so the guard from above doesn't protect next cell. The answer is the sum of all $dp[n \\cdot m][whatever][whatever][whatever]$ values.",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "845",
    "index": "G",
    "title": "Shortest Path Problem?",
    "statement": "You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path between vertex $1$ and vertex $n$.\n\n\\textbf{Note that graph can contain multiple edges and loops. It is guaranteed that the graph is connected.}",
    "tutorial": "Let's find some path from $1$ to $n$. Let its length be $P$, then the answer to the problem can be represented as $P\\oplus C$, where $C$ is the total length of some set of cycles in the graph (they can be disconnected; it doesn't matter because we can traverse the whole graph and return to the starting vertex with cost $0$). Let's treat each cycle's cost as a vector $(c_{0}, c_{1}, c_{2}...)$ where $c_{i}$ is the $i$-th bit in binary representation of cycle's cost. We can use Gaussian elimination to find the independent set of vectors that generates all these vectors. To do this, let's build any spanning tree of the graph, and then for any edge $(x, y)$ not belonging to the spanning tree we can try to add $d(x)\\oplus w_{(x,y)}\\oplus d(y)$ to the independent set ($d(x)$ is the length of the path from the root to $x$ in the spanning tree). When trying to add some vector, we firstly need to check if it can be represented as a combination of some vectors from the set, and only if it's impossible, then we add it to the set. The number of vectors in the set won't exceed $30$, so we can use Gaussian elimination to check if the vector is a combination of elements from the set. Then, after we found the basis, let's build the answer greedily from the most significant bit to the least: we will check if we can set the current bit so it is equal to the corresponding bit of $P$, while maintaining all the previous bit. To check it, we also can use Gaussian elimination.",
    "tags": [
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "846",
    "index": "A",
    "title": "Curriculum Vitae",
    "statement": "Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job.\n\nDuring all his career Hideo has produced $n$ games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV.\n\nMore formally, you are given an array $s_{1}, s_{2}, ..., s_{n}$ of zeros and ones. Zero corresponds to an unsuccessful game, one — to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one.\n\nBesides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.",
    "tutorial": "The statement literally asks for the longest subsequence which looks like $[0, 0, 0, ..., 1, 1, 1]$. Let's find out how many zeroes will be in this sequence and then take all ones which come after the last zero. On each step take the next zero from the beginning of the sequence and count ones after it. Update answer with the maximum value. You can precalc number of ones on suffix with partial sums but it was not necessary in this task. Overall complexity: $O(n^{2})$ (naively) or $O(n)$ (with partial sums).",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "846",
    "index": "B",
    "title": "Math Show",
    "statement": "Polycarp takes part in a math show. He is given $n$ tasks, each consists of $k$ subtasks, numbered $1$ through $k$. It takes him $t_{j}$ minutes to solve the $j$-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order.\n\nBy solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all $k$ of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is $k + 1$.\n\nPolycarp has $M$ minutes of time. What is the maximum number of points he can earn?",
    "tutorial": "Constraints tell us that we can avoid making any weird assumptions for any greedy solutions. You can easily count the answer for some fixed amount of tasks completed. Just sort all left subtasks (but the longest to solve in each uncompleted task) and take the easiest till the time is over. Now you can iterate from $0$ to $n$ tasks completed and take maximum over all options. Overall complexity: $O(n^{2} \\cdot k)$.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "846",
    "index": "C",
    "title": "Four Segments",
    "statement": "You are given an array of $n$ integer numbers. Let $sum(l, r)$ be the sum of all numbers on positions from $l$ to $r$ non-inclusive ($l$-th element is counted, $r$-th element is not counted). For indices $l$ and $r$ holds $0 ≤ l ≤ r ≤ n$. Indices in array are numbered from $0$.\n\nFor example, if $a = [ - 5, 3, 9, 4]$, then $sum(0, 1) = - 5$, $sum(0, 2) = - 2$, $sum(1, 4) = 16$ and $sum(i, i) = 0$ for each $i$ from $0$ to $4$.\n\nChoose the indices of three delimiters $delim_{0}$, $delim_{1}$, $delim_{2}$ ($0 ≤ delim_{0} ≤ delim_{1} ≤ delim_{2} ≤ n$) and divide the array in such a way that the value of $res = sum(0, delim_{0})$ - $sum(delim_{0}, delim_{1})$ + $sum(delim_{1}, delim_{2})$ - $sum(delim_{2}, n)$ is maximal.\n\nNote that some of the expressions $sum(l, r)$ can correspond to empty segments (if $l = r$ for some segment).",
    "tutorial": "Imagine the same task but without the first term in sum. As the sum of the array is fixed, the best second segment should be the one with the greatest sum. This can be solved in $O(n)$ with partial sums. When recalcing the best segment to end at position $i$, you should take minimal prefix sum from $0$ to $i$ inclusive (from the whole sum you want to subtract the lowest number). Now let's just iterate over all possible ends of the first segment and solve the task above on the array without this segment. Oveall complexity: $O(n^{2})$.",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "846",
    "index": "D",
    "title": "Monitor",
    "statement": "Recently Luba bought a monitor. Monitor is a rectangular matrix of size $n × m$. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square $k × k$ consisting entirely of broken pixels. She knows that $q$ pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all $q$ pixels stopped working).",
    "tutorial": "At first let's sort broken pixels in non-descending order by times they appear. Obviously, if the first $cnt$ broken pixels make monitor broken, $cnt + 1$ pixel won't fix it. Thus, binary search on answer will work. Let's search for the first moment in time when the monitor becomes broken. The function to check if in some moment $anst$ monitor is broken looks the following way. As we want to check if there is a submatrix of size $k  \\times  k$, which consists only of broken pixels, let's precalc the array of partial sums $cnt$, $cnt_{i, j}$ is the number of broken pixels on submatrix from $(1, 1)$ to $(i, j)$. $cnt_{i, j}$ is calculated as ($1$ if $a_{i, j}$ is broken pixel, $0$ otherwise) $+ cnt_{i - 1, j} + cnt_{i, j - 1} - cnt_{i - 1, j - 1}$. Sum on submatrix of size $k  \\times  k$ then looks like $cnt_{i, j} - cnt_{i - k, j} - cnt_{i, j - k} + cnt_{i - k, j - k}$. Check all possible $i$ and $j$ from $k$ to $n$ and find out if there exists submatrix with sum equal to $k \\cdot k$. Overall complexity: $O(n^{2}\\cdot\\log{q})$.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 1900
  },
  {
    "contest_id": "846",
    "index": "E",
    "title": "Chemistry in Berland",
    "statement": "Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment.\n\nFortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange.\n\nBerland chemists are aware of $n$ materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each $i$ $(2 ≤ i ≤ n)$ there exist two numbers $x_{i}$ and $k_{i}$ that denote a possible transformation: $k_{i}$ kilograms of material $x_{i}$ can be transformed into $1$ kilogram of material $i$, and $1$ kilogram of material $i$ can be transformed into $1$ kilogram of material $x_{i}$. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is \\textbf{always an integer number of kilograms}.\n\nFor each $i$ ($1 ≤ i ≤ n$) Igor knows that the experiment requires $a_{i}$ kilograms of material $i$, and the laboratory contains $b_{i}$ kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?",
    "tutorial": "Since $x_{i} < i$, then the transformation graph is a tree. Let's solve the problem recursively. Suppose that material $j$ is a leaf in the tree (there is no $y$ such that $x_{y} = j$). Then if we don't have enough material $j$, we have to transform some of material $x_{j}$ into $j$. Let's transform the amount required to set current amount of material $j$ to $a_{j}$; if we don't have the required amount of material $x_{j}$, then this amount will temporarily be negative. And if we have more material $j$ than we need to conduct the experiment, then we will transform it to $x_{j}$. The same algorithm can be applied to any non-root node, but we first need to do this for all its children. This algorithm is optimal because each time we take the minimum possible amount from the parent. After this the root will be the only node such that $a_{j}$ is not necessarily equal to current amount of material $j$. Since we solved the problem for all other materials and did it optimally, now the answer is YES iff current amount of material $1$ is not less than $a_{1}$. This must be implemented carefully. Since the total amount of materials never increases, then if some material's current amount is less than, for example, $- 2 \\cdot 10^{17}$, then the answer is already NO. Also overflows in multiplication must be avoided; to do this, we can firstly check if the result of multiplication is not too big by multiplying values as real numbers.",
    "tags": [
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "846",
    "index": "F",
    "title": "Random Query",
    "statement": "You are given an array $a$ consisting of $n$ positive integers. You pick two integer numbers $l$ and $r$ from $1$ to $n$, inclusive (numbers are picked randomly, equiprobably and independently). If $l > r$, then you swap values of $l$ and $r$. You have to calculate the expected value of the number of unique elements in segment of the array from index $l$ to index $r$, inclusive ($1$-indexed).",
    "tutorial": "For each index $i$ we will find the number of pairs $(l, r)$ (before swapping) such that $i$ is the first occurence of $a_{i}$ in the chosen segment. Let $f(i)$ be previous occurence of $a_{i}$ before $i$ (if $i$ is the first occurence, then $f(i) = 0$ if we suppose the array to be $1$-indexed). Let's find the number of pairs such that $l  \\le  r$, and then multiply it by $2$ and subtract $1$ for this index. $l$ has to be in segment $(f(i), i]$, and $r$ has to be in segment $[i, n]$, so the number of ways to choose this pair is $(i - f(i))(n - i + 1)$. The value we receive as the sum of these values over all segments is the total number of distinct elements over all pairs $(l, r)$, so we need to divide it by the number of these pairs.",
    "tags": [
      "data structures",
      "math",
      "probabilities",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "848",
    "index": "A",
    "title": "From Y to Y",
    "statement": "From beginning till end, this message has been waiting to be conveyed.\n\nFor a given unordered multiset of $n$ lowercase English letters (\"multi\" means that a letter may appear more than once), we treat all letters as strings of length $1$, and repeat the following operation $n - 1$ times:\n\n- Remove any two elements $s$ and $t$ from the set, and add their concatenation $s + t$ to the set.\n\nThe cost of such operation is defined to be $\\sum_{c\\in\\{{\\overset{*}{\\scriptstyle a}}}{\\overset{*}{\\underset{}{v_{b}}},\\dots*^{*}z}\\cdot\\}\\,f\\!\\left(s,c\\right)\\cdot f\\!\\left(t,c\\right)$, where $f(s, c)$ denotes the number of times character $c$ appears in string $s$.\n\nGiven a non-negative integer $k$, construct any valid non-empty set of no more than $100 000$ letters, such that the minimum accumulative cost of the whole process is \\textbf{exactly} $k$. It can be shown that a solution always exists.",
    "tutorial": "For a given string, how to calculate the cost? With several experiments, you may have found that the \"minimum cost\" doesn't make sense - the cost is always the same no matter how the characters are concatenated. Precisely, the cost of the process for a multiset of $c_{1}$ a's, $c_{2}$ b's, ... and $c_{26}$ z's, is $\\textstyle\\sum_{i=1}^{26}{\\frac{1}{2}}\\cdot c_{i}\\cdot(c_{i}-1)$. It's in this form because every pair of same characters will contribute $1$ to the total cost. Therefore we need to find such $c_{1}, c_{2}, ..., c_{26}$ so that $\\textstyle\\sum_{i=1}^{26}{\\frac{1}{2}}\\cdot c_{i}\\cdot\\left(c_{i}-1\\right)=k$. This can be done greedily and iteratively. Every time we subtract the maximum possible ${\\frac{1}{2}}\\cdot c\\cdot(c-1)$ from $k$, and add $c$ same new letters to the set, until $k$ becomes $0$. This $c$ can be solved by any reasonable way, say quadratic formula, binary search or brute force. Time complexity veries from $O(\\log^{2}k)$ to $O({\\sqrt{k}}\\log k)$ or any acceptable complexity, depending on the choice of the method for finding $c$. Of course, if a knapsack algorithm is used, it will use the minimum possible number of different letters, and works in $O(k{\\sqrt{k}})$.",
    "code": "#include <cstdio>\n#include <vector>\nstatic const int MAXK = 100002;\nstatic const int INF = 0x3fffffff;\n\nint f[MAXK];\nint pred[MAXK];\n\nint main()\n{\n    f[0] = 0;\n    for (int i = 1; i < MAXK; ++i) f[i] = INF;\n    for (int i = 0; i < MAXK; ++i) pred[i] = -1;\n\n    for (int i = 0; i < MAXK; ++i) if (f[i] != INF) {\n        for (int j = 2; i + j * (j - 1) / 2 < MAXK; ++j)\n            if (f[i + j * (j - 1) / 2] > f[i] + 1) {\n                f[i + j * (j - 1) / 2] = f[i] + 1;\n                pred[i + j * (j - 1) / 2] = j;\n            }\n    } else printf(\"Assertion failed at %d\\n\", i);\n\n    int k;\n    scanf(\"%d\", &k);\n    if (k == 0) { puts(\"a\"); return 0; }\n    std::vector<int> v;\n    for (; k > 0; k -= pred[k] * (pred[k] - 1) / 2) {\n        v.push_back(pred[k]);\n    }\n    for (int i = 0; i < v.size(); ++i) {\n        for (int j = 0; j < v[i]; ++j) putchar('a' + i);\n    }\n    putchar('\\n');\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "848",
    "index": "B",
    "title": "Rooter's Song",
    "statement": "Wherever the destination is, whoever we meet, let's render this song together.\n\nOn a Cartesian coordinate plane lies a rectangular stage of size $w × h$, represented by a rectangle with corners $(0, 0)$, $(w, 0)$, $(w, h)$ and $(0, h)$. It can be seen that no collisions will happen before one enters the stage.\n\nOn the sides of the stage stand $n$ dancers. The $i$-th of them falls into one of the following groups:\n\n- \\textbf{Vertical}: stands at $(x_{i}, 0)$, moves in positive $y$ direction (upwards);\n- \\textbf{Horizontal}: stands at $(0, y_{i})$, moves in positive $x$ direction (rightwards).\n\nAccording to choreography, the $i$-th dancer should stand still for the first $t_{i}$ milliseconds, and then start moving in the specified direction at $1$ unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.\n\nWhen two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on.\n\nDancers stop when a border of the stage is reached. Find out every dancer's stopping position.",
    "tutorial": "How to deal with \"waiting time\"? Move every dancer $t_{i}$ units backwards in the first place, that is to $(x_{i} - t_{i}, 0)$ for the vertical-moving group, and $(0, y_{i} - t_{i})$ for the horizontal-moving group. Then start the time, making everyone start moving immediately. When do dancers collide? What changes and what keeps the same? Notice that if two dancers collide before any other collision happens, then they have the same $x + y$ values for their initial positions. Furthermore, after a collision, the two dancers keep having the same $x + y$, and also with the same relative orders of $x$ and $y$. Also, after a collision, the union of all dancers' tracks will be the same as if they \"went through\" each other and no collision happened at all (see the figure for sample 1 to get a general idea on this). Therefore, divide dancers into groups by $p_{i} - t_{i}$, and collisions will happen within groups only. Dancers in the same group will move on the same $x + y$ line (a line of slope $- 1$), and however collisions take place, they will keep current relative order of $x$ and $y$. It's proved before that in each group, dancers' exiting positions is the same as if no collision happened at all (namely, $(x_{i}, h)$ for initially-vertical dancers, and $(w, y_{i})$ for initially-horizontal ones). For each group, find out all such positions. Sort all dancers according to their initial $x$ values, and sort these positions in the direction of $(0, h)$ to $(w, h)$ then $(w, 0)$. Match the sorted dancers to these sorted positions and obtain the answers for all dancers. This solution works in $O(n\\log n)$.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <vector>\nstatic const int MAXN = 100004;\nstatic const int MAXW = 100003;\nstatic const int MAXT = 100002;\n\nint n, w, h;\nint g[MAXN], p[MAXN], t[MAXN];\n\nstd::vector<int> s[MAXW + MAXT];\nint ans_x[MAXN], ans_y[MAXN];\n\nint main()\n{\n    scanf(\"%d%d%d\", &n, &w, &h);\n    for (int i = 0; i < n; ++i) {\n        scanf(\"%d%d%d\", &g[i], &p[i], &t[i]);\n        s[p[i] - t[i] + MAXT].push_back(i);\n    }\n\n    std::vector<int> xs, ys;\n    for (int i = 0; i < MAXW + MAXT; ++i) if (!s[i].empty()) {\n        for (int u : s[i]) {\n            if (g[u] == 1) xs.push_back(p[u]);\n            else ys.push_back(p[u]);\n        }\n        std::sort(xs.begin(), xs.end());\n        std::sort(ys.begin(), ys.end());\n        std::sort(s[i].begin(), s[i].end(), [] (int u, int v) {\n            if (g[u] != g[v]) return (g[u] == 2);\n            else return (g[u] == 2 ? p[u] > p[v] : p[u] < p[v]);\n        });\n        for (int j = 0; j < xs.size(); ++j) {\n            ans_x[s[i][j]] = xs[j];\n            ans_y[s[i][j]] = h;\n        }\n        for (int j = 0; j < ys.size(); ++j) {\n            ans_x[s[i][j + xs.size()]] = w;\n            ans_y[s[i][j + xs.size()]] = ys[ys.size() - j - 1];\n        }\n        xs.clear();\n        ys.clear();\n    }\n\n    for (int i = 0; i < n; ++i) printf(\"%d %d\\n\", ans_x[i], ans_y[i]);\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "geometry",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "848",
    "index": "C",
    "title": "Goodbye Souvenir",
    "statement": "I won't feel lonely, nor will I be sorrowful... not before everything is buried.\n\nA string of $n$ beads is left as the message of leaving. The beads are numbered from $1$ to $n$ from left to right, each having a shape numbered by integers between $1$ and $n$ inclusive. Some beads may have the same shapes.\n\nThe \\underline{memory} of a shape $x$ in a certain subsegment of beads, is defined to be the difference between the last position and the first position that shape $x$ appears in the segment. The \\underline{memory} of a subsegment is the sum of \\underline{memories} over all shapes that occur in it.\n\nFrom time to time, shapes of beads change as well as the \\underline{memories}. Sometimes, the past secreted in subsegments are being recalled, and you are to find the \\underline{memory} for each of them.",
    "tutorial": "Let's look at segment $[l, r]$. Let's $p_{1}^{x} < p_{2}^{x} < ... < p_{k}^{x}$ - positions of all occurences of shape $x$ at segment $[l, r]$. Then memory of shape $x$ at segment $[l, r]$ is $p_{k}^{x} - p_{1}^{x} = (p_{k}^{x} - p_{k - 1}^{x}) + (p_{k - 1}^{x} - p_{k - 2}^{x}) + ... + (p_{2}^{x} - p_{1}^{x})$. Then we can build array of pairs $b$: $b_{i} = (prev(i), i - prev(i))$, where $prev(i)$ - previous occurence of shape $a_{i}$ $(p r e v(i)=\\operatorname*{max}_{a_{i}=a_{i}}j)$. A query transforms to: $\\sum_{i\\leq i\\leq r\\leq i}b_{i}.s e c o n d$, which is variation of counting numbers of greater on segment. Queries of change in position can be proccessed by recounting values $prev(p)$ for $a_{p}$ and next occurence of that shape before and after changing shape. Processing of all queries can be done by building segment tree, which every node contains Fenwick tree by types of shape. For reducing memory usage we can, for every node, save only shapes, which appeared in any query for this node. Then Fenwick tree can be build only on this shapes by coordinate compressing. Result complexity - $O(n \\cdot log^{2}(n))$.",
    "code": "#include <bits/stdc++.h>\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) fore(i, 0, n)\n\n#define all(a) (a).begin(), (a).end()\n#define sqr(a) ((a) * (a))\n#define sz(a) int(a.size())\n#define mp make_pair\n#define pb push_back\n\n#define x first\n#define y second\n\nusing namespace std;\n\ntemplate<class A, class B> ostream& operator << (ostream &out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.first << \", \" << p.second << \")\";\n}\n\ntemplate<class A> ostream& operator << (ostream &out, const vector<A> &v) {\n\tout << \"[\";\n\tforn(i, sz(v)) {\n\t\tif(i > 0)\n\t\t\tout << \" \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nmt19937 myRand(time(NULL));\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ninline int gett() {\n\treturn clock() * 1000 / CLOCKS_PER_SEC;\n}\n\nconst ld EPS = 1e-9;\nconst int INF = int(1e9);\nconst li INF64 = li(INF) * INF;\nconst ld PI = 3.1415926535897932384626433832795;\n\nconst int N = 100 * 1000 + 555;\n\nint n, m, aa[N], a[N];\nint qt[N], qx[N], qy[N];\n\ninline bool read() {\n\tif(!(cin >> n >> m))\n\t\treturn false;\n\t\n\tforn(i, n)\n\t\tassert(scanf(\"%d\", &aa[i]) == 1);\n\t\t\n\tforn(i, m) {\n\t\tassert(scanf(\"%d%d%d\", &qt[i], &qx[i], &qy[i]) == 3);\n\t\tqx[i]--;\n\t}\n\t\t\n\treturn true;\n}\n\nvector<int> vars[4 * N];\nvector<li> f[4 * N];\nli sumAll[4 * N];\n\ninline void addValF(int k, int pos, int val) {\n\tsumAll[k] += val;\n\tfor(; pos < sz(f[k]); pos |= pos + 1)\n\t\tf[k][pos] += val;\n}\n\ninline li sum(int k, int pos) {\n\tli ans = 0;\n\tfor(; pos >= 0; pos = (pos & (pos + 1)) - 1)\n\t\tans += f[k][pos];\n\t\t\n\treturn ans;\n}\n\ninline li getSumF(int k, int pos) {\n\treturn sumAll[k] - sum(k, pos - 1);\n}\n\nli getSumST(int v, int l, int r, int lf, int rg, int val) {\n\tif(l >= r || lf >= rg)\n\t\treturn 0;\n\t\t\n\tif(l == lf && r == rg) {\n\t\tint pos = int(lower_bound(all(vars[v]), val) - vars[v].begin());\n\t\treturn getSumF(v, pos);\n\t}\n\t\n\tint mid = (l + r) >> 1;\n\t\n\tli ans = 0;\n\tif(lf < mid)\n\t\tans += getSumST(2 * v + 1, l, mid, lf, min(mid, rg), val);\n\tif(rg > mid)\n\t\tans += getSumST(2 * v + 2, mid, r, max(lf, mid), rg, val);\n\t\t\n\treturn ans;\n}\n\nvoid addValST(int k, int v, int l, int r, int pos, int pos2, int val) {\n\tif(l >= r)\n\t\treturn;\n\t\t\n\tif(!k)\n\t\tvars[v].pb(pos2);\n\telse {\n\t\tint cpos = int(lower_bound(all(vars[v]), pos2) - vars[v].begin());\n\t\taddValF(v, cpos, val);\n\t}\n\t\n\tif(l + 1 == r) {\n\t\tassert(l == pos);\n\t\treturn;\n\t}\n\t\n\tint mid = (l + r) >> 1;\n\t\n\tif(pos < mid)\n\t\taddValST(k, 2 * v + 1, l, mid, pos, pos2, val);\n\telse\n\t\taddValST(k, 2 * v + 2, mid, r, pos, pos2, val);\n}\n\nint pr[N];\nset<int> ids[N];\n\nvoid build(int k, int v, int l, int r) {\n\tfore(i, l, r)\n\t\tif(!k)\n\t\t\tvars[v].pb(pr[i]);\n\t\telse {\n\t\t\tint pos = int(lower_bound(all(vars[v]), pr[i]) - vars[v].begin());\n\t\t\taddValF(v, pos, i - pr[i]);\n\t\t}\n\t\t\t\n\tif(l + 1 == r)\n\t\treturn;\n\t\t\n\tint mid = (l + r) >> 1;\n\t\n\tbuild(k, 2 * v + 1, l, mid);\n\tbuild(k, 2 * v + 2, mid, r);\n}\n\ninline void eraseSets(int k, int pos) {\n\taddValST(k, 0, 0, n, pos, pr[pos], -(pos - pr[pos]));\n\tids[ a[pos] ].erase(pos);\n\t\n\tauto it2 = ids[ a[pos] ].lower_bound(pos);\n\t\n\tif(it2 != ids[ a[pos] ].end()) {\n\t\tint np = *it2;\n\t\tassert(a[np] == a[pos]);\n\t\tassert(pr[np] == pos);\n\t\t\n\t\taddValST(k, 0, 0, n, np, pr[np], -(np - pr[np]));\n\t\t\n\t\tpr[np] = pr[pos];\n\t\taddValST(k, 0, 0, n, np, pr[np], +(np - pr[np]));\n\t}\n\t\n\ta[pos] = -1;\n\tpr[pos] = -1;\n}\n\ninline void insertSets(int k, int pos, int nval) {\n\tauto it2 = ids[nval].lower_bound(pos);\n\tassert(it2 == ids[nval].end() || *it2 > pos);\n\t\n\tif(it2 != ids[nval].end()) {\n\t\tint np = *it2;\n\t\tassert(a[np] == nval);\n\t\t\n\t\taddValST(k, 0, 0, n, np, pr[np], -(np - pr[np]));\n\n\t\tpr[np] = pos;\n\t\taddValST(k, 0, 0, n, np, pr[np], +(np - pr[np]));\n\t}\n\t\n\tpr[pos] = -1;\n\tif(it2 != ids[nval].begin()) {\n\t\tauto it1 = it2; it1--;\n\t\tassert(*it1 < pos);\n\t\t\n\t\tpr[pos] = *it1;\n\t}\n\taddValST(k, 0, 0, n, pos, pr[pos], +(pos - pr[pos]));\n\t\n\tids[nval].insert(pos);\n\ta[pos] = nval;\n}\n\ninline void precalc() {\n\tforn(v, 4 * N) {\n\t\tsort(all(vars[v]));\n\t\tvars[v].erase(unique(all(vars[v])), vars[v].end());\n\t\t\n\t\tf[v].assign(sz(vars[v]), 0);\n\t\tsumAll[v] = 0;\n\t}\n}\n\ninline void solve() {\n\tforn(k, 2) {\n\t\tif(k) precalc();\n\t\t\n\t\tforn(i, N)\n\t\t\tids[i].clear();\n\t\tforn(i, n)\n\t\t\ta[i] = aa[i];\n\t\t\t\n\t\tvector<int> ls(n + 1, -1);\n\t\tforn(i, n) {\n\t\t\tpr[i] = ls[ a[i] ];\n\t\t\tls[ a[i] ] = i;\n\t\t\t\n\t\t\tids[ a[i] ].insert(i);\n\t\t}\n\t\t\n\t\tbuild(k, 0, 0, n);\n\t\t\n//\t\tcerr << k << \" \" << clock() << endl;\n\t\t\n\t\tforn(q, m) {\n\t\t\tif(qt[q] == 1) {\n\t\t\t\teraseSets(k, qx[q]);\n\t\t\t\tinsertSets(k, qx[q], qy[q]);\n\t\t\t} else\n\t\t\t\tif(k) printf(\"%I64d\\n\", getSumST(0, 0, n, qx[q], qy[q], qx[q]));\n\t\t}\n\t\t\n//\t\tcerr << k << \" \" << clock() << endl;\n\t}\n}\n\nint main(){\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n\t\n\tint t = gett();\n#endif\n\n\tsrand(time(NULL));\n\tcout << fixed << setprecision(10);\n\n\twhile(read()) {\n\t\tsolve();\t\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << gett() - t << endl;\n\t\tt = gett();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2600
  },
  {
    "contest_id": "848",
    "index": "D",
    "title": "Shake It!",
    "statement": "A never-ending, fast-changing and dream-like world unfolds, as the secret door opens.\n\nA \\underline{world} is an unordered graph $G$, in whose vertex set $V(G)$ there are two special vertices $s(G)$ and $t(G)$. An \\underline{initial world} has vertex set ${s(G), t(G)}$ and an edge between them.\n\nA total of $n$ changes took place in an \\underline{initial world}. In each change, a new vertex $w$ is added into $V(G)$, \\textbf{an existing edge} $(u, v)$ is chosen, and two edges $(u, w)$ and $(v, w)$ are added into $E(G)$. Note that it's possible that some edges are chosen in more than one change.\n\nIt's known that the capacity of the minimum $s$-$t$ cut of the resulting graph is $m$, that is, at least $m$ edges need to be removed in order to make $s(G)$ and $t(G)$ disconnected.\n\nCount the number of non-similar worlds that can be built under the constraints, modulo $10^{9} + 7$. We define two \\underline{worlds} similar, if they are isomorphic and there is isomorphism in which the $s$ and $t$ vertices are not relabelled. Formally, two \\underline{worlds} $G$ and $H$ are considered similar, if there is a bijection between their vertex sets $f:V(G)\\rightarrow V(H)$, such that:\n\n- $f(s(G)) = s(H)$;\n- $f(t(G)) = t(H)$;\n- Two vertices $u$ and $v$ of $G$ are adjacent in $G$ if and only if $f(u)$ and $f(v)$ are adjacent in $H$.",
    "tutorial": "Use DP. Let's try to find \"subproblems\" in this. A graph can be expressed as: an edge, in parallel with an unordered multiset of zero or more ordered pair of two graphs. That is, \"graph = edge [// (graph + graph) [// (graph + graph) [...]]]\". A graph can be represented by two parameters: number of operations needed to build it, and its minimum cut. Let $f[i][j]$ keep the number of graphs with $i$ operations and a minimum cut of $j$. The figure below shows one of the ways in which $f[8][5]$ can be built from other $f$'s. How to iterate over all such possible splitting into pairs, while keeping them unordered? One way is to iterate through pairs - instead of determining $f$'s one by one, we find all pairs of graph parameters and add them to graphs already formed with pairs considered before. (This is like how we do it in knapsack problems.) Iterate through the parameters of two graphs in a pair, $(a, b, c, d)$, and use a push-style transition to add each $f[i][j]$ into the corresponding state if the pair is added a number of times to a graph in $f[i][j]$. That is, for each $t$, add $f[i][j]\\times\\mathrm{MultiCombination}(f[a][b]\\cdot f[c][d],t)$ to $f[i + t \\cdot (a + c + 1)][j + t \\cdot min(b, d)]$ - this means a pair of graphs with parameters $[a][b]$ and $[c][d]$ is added $t$ times to a graph with parameters $[i][j]$. With $O(n^{4})$ such parameters we need to spend $O(n^{2})$ time updating all values, therefore time complexity is $O(n^{6})$ which is not sufficient to pass. Note: MultiCombination($n$, $r$) means number of ways to select an unordered multiset of $r$ elements out of $n$ distinct elements, where one element can be selected more than once. This equals to $\\textstyle{\\binom{n+r-1}{r}}$. Let's see the pair as a whole. Let $g[i][j]$ keep the number of ordered graph pairs with $i$ operations and a minimum cut of $j$. At each step, in stead of iterating over four parameters of a pair, we iterate over two parameters and use values of $g$ to perform the update. It can be seen that $f[i][j]$ and $g[i][j]$ only depend on such $f[p][q]$ and $g[p][q]$ that $p  \\le  i - 1$. Therefore, we can determine $f$ and $g$ values in order of increasing $i$. This solution works with $O(n^{2})$ states, each of which can be calculated in $O(n^{3})$ time with another $O(n)$ factor for MultiCombination, but since a harmonic series exists in the iteration of $t$, this is actually $O(n^{5}\\log{n})$. Author's implementation takes a bit lower than 800 milliseconds to find an answer. If MultiCombination is calculated along with the iteration of $t$ (see the model solution), this works in $O(n^{4}\\log{n})$ which is much faster. Bonus. Come up with a DP on dual graphs.",
    "code": "#include <cstdio>\n#include <cstring>\ntypedef long long int64;\nstatic const int MAXN = 53;\nstatic const int MODULUS = 1e9 + 7;\n#define _  %  MODULUS\n#define __ %= MODULUS\n\nint n, m;\n// f[# of operations][mincut] -- total number of graphs\n// g[# of operations][mincut] -- number of ordered pairs of two graphs\nint64 f[MAXN][MAXN] = {{ 0 }}, g[MAXN][MAXN] = {{ 0 }};\nint64 h[MAXN][MAXN];\n\ninline int64 qpow(int64 base, int exp) {\n    int64 ans = 1;\n    for (; exp; exp >>= 1, (base *= base)__) if (exp & 1) (ans *= base)__;\n    return ans;\n}\nint64 inv[MAXN];\n\nint main()\n{\n    for (int i = 0; i < MAXN; ++i) inv[i] = qpow(i, MODULUS - 2);\n\n    scanf(\"%d%d\", &n, &m);\n\n    f[0][1] = 1;\n    for (int i = 1; i <= n; ++i) {\n        for (int j = 1; j <= i + 1; ++j) {\n            // Calculate g[i][*]\n            // pair(i)(j) = graph(p)(r) in series with graph(q)(s)\n            // where p+q == i-1, min(r, s) == j\n            for (int p = 0; p <= i - 1; ++p) {\n                int q = i - 1 - p;\n                for (int r = j; r <= p + 1; ++r)\n                    (g[i][j] += (int64)f[p][r] * f[q][j])__;\n                for (int s = j + 1; s <= q + 1; ++s)\n                    (g[i][j] += (int64)f[p][j] * f[q][s])__;\n            }\n            // Update all f with g[i][*]\n            // Iterate over the number of times pair(i)(j) is appended in parallel, let it be t\n            // h is used as a temporary array\n            memset(h, 0, sizeof h);\n            for (int p = 0; p <= n; ++p)\n                for (int q = 1; q <= p + 1; ++q) {\n                    int64 comb = 1;\n                    for (int t = 1; p + t * i <= n; ++t) {\n                        comb = comb * (g[i][j] + t - 1)_ * inv[t]_;\n                        (h[p + t * i][q + t * j] += f[p][q] * comb)__;\n                    }\n                }\n            for (int p = 0; p <= n; ++p)\n                for (int q = 1; q <= p + 1; ++q)\n                    (f[p][q] += h[p][q])__;\n        }\n    }\n\n    printf(\"%lld\\n\", f[n][m]);\n\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "flows",
      "graphs"
    ],
    "rating": 2900
  },
  {
    "contest_id": "848",
    "index": "E",
    "title": "Days of Floral Colours",
    "statement": "The Floral Clock has been standing by the side of Mirror Lake for years. Though unable to keep time, it reminds people of the passage of time and the good old days.\n\nOn the rim of the Floral Clock are $2n$ flowers, numbered from $1$ to $2n$ clockwise, each of which has a colour among all $n$ possible ones. For each colour, there are exactly two flowers with it, the \\underline{distance} between which \\textbf{either is less than or equal to $2$, or equals $n$}. Additionally, if flowers $u$ and $v$ are of the same colour, then flowers opposite to $u$ and opposite to $v$ should be of the same colour as well — symmetry is beautiful!\n\nFormally, the \\underline{distance} between two flowers is $1$ plus the number of flowers on the minor arc (or semicircle) between them. Below is a possible arrangement with $n = 6$ that cover all possibilities.\n\nThe \\underline{beauty} of an arrangement is defined to be the product of the lengths of flower segments separated by all opposite flowers of the same colour. In other words, in order to compute the beauty, we remove from the circle all flowers that have the same colour as flowers opposite to them. Then, the beauty is the product of lengths of all remaining segments. Note that we include segments of length $0$ in this product. If there are no flowers that have the same colour as flower opposite to them, the beauty equals $0$. For instance, the \\underline{beauty} of the above arrangement equals $1 × 3 × 1 × 3 = 9$ — the segments are ${2}$, ${4, 5, 6}$, ${8}$ and ${10, 11, 12}$.\n\nWhile keeping the constraints satisfied, there may be lots of different arrangements. Find out the sum of \\underline{beauty} over all possible arrangements, modulo $998 244 353$. Two arrangements are considered different, if a pair $(u, v)$ ($1 ≤ u, v ≤ 2n$) exists such that flowers $u$ and $v$ are of the same colour in one of them, but not in the other.",
    "tutorial": "tl;dr Just look at recurrences of $g$, $f_{0}$, $f_{1}$ and $f_{2}$ and the part after $f_{2}$'s recurrence. Break the circle down into semicircles. We're basically pairing flowers under the restrictions. It's hard to deal with the whole circle, let's consider something simpler. Consider an arc of length $i$ (segment of $i$ flowers) and their opposite counterparts, surrounded by another two pairs of opposite flowers of the same colour. We will calculate their contribution to the total beauty, $f_{0}(i)$ - in other words, the total beauty if only this segment is required to be coloured (we will not pair them with flowers out of this segment). A such segment with $i = 7$. For clarity's sake, a flower's opposite counterpart is drawn directly below it. A such segment with $i = 7$. For clarity's sake, a flower's opposite counterpart is drawn directly below it. We come up with a function $g(i)$, denoting the number of ways to colour a segment of length $i$ with pairs of opposite $1$ and $2$ only. The recurrence is $g(0) = 1, g(1) = 0, g(i) = g(i - 2) + g(i - 4)$. First case: there are no opposite pairs within this segment. There are $g(i)$ ways to do this, giving a total beauty of $g(i) \\cdot i^{2}$. Second case: there is at least one opposite pair within this segment. Fix the position of the first opposite pair, $j$ (in the range of $0$ and $i - 1$ inclusive). Another two cases diverge. (a) No pair of distance $2$ crosses the flowers at position $j$. In this case, a subproblem of length $i - j - 1$ emerge, generating a total beauty of $g(j) \\cdot j^{2}  \\times  f_{0}(i - j - 1)$. (b) A pair of distance $2$ crosses the flowers at position $j$. In this case, new subproblems appear - an arc of length $i - j - 2$ and their opposite counterparts, surrounded by an opposite same-colour pair on one side, and an already-paired flower and an opposite same-colour pair on the other. Denote this subproblem as $f_{1}$, this case generates a total beauty of $g(j - 1) \\cdot j^{2}  \\times  f_{1}(i - j - 3)$. Summing up and simplifying a bit, we get the recurrence for $f_{0}$: $\\begin{array}{c}{{f_{0}(i)=g(i)\\cdot i^{2}}}\\\\ {{\\mathrm{}\\ \\!=\\!\\sum_{j=0}^{i-1}g(j)\\cdot j^{2}\\times f_{0}(i-j-1)}}\\\\ {{\\mathrm{}\\displaystyle\\prod_{i=0}^{i-3}g(j)\\cdot(j+1)^{2}\\times f_{1}(i-j-3)}}\\end{array}$ Doing almost the same (fix the opposite pair nearest to the side of an already-paired flower), we get the recurrence for $f_{1}$: $\\begin{array}{c}{{f_{1}(i)=g(i)\\cdot(i+1)^{2}}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!}}&{{\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!}}&{{\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!}^{{}\\!\\!\\!\\!\\!}\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!}^{{\\textstyle\\frac{i-3}{i=0}g(j)\\cdot(j+1)^{2}\\times f_{0}(i-j-3)}}\\end{array}$ Now we've solved the subproblem for a subsegment. Hooray! For the whole circle, let's fix a pair of opposite flowers. Let it be flowers $1$ and $n$. This can be rotated to generate other arrangements. But we don't know how many times it can be rotated without duplication. So we fix the second opposite pair, letting it be the first one starting from flower number $2$ and going clockwise. Let its position be $i$, then there shouldn't be any opposite pairs within $[2, i - 1]$, and all arrangements can be rotated in $j - 1$ different ways to generate all different arrangements. Example with $n = 9$ and $i = 5$. Example with $n = 9$ and $i = 5$. There may be or may be not pairs of distance $2$ crossing over flowers $1$ and $i$. Consider all four cases, we run into another subproblem with deja vu. We introduce a new function, $f_{2}(i)$, denoting the total beauty of a segment of length $i$, with an already-paired flower and an opposite same-colour pair on both sides. A subproblem of length $5$. A subproblem of length $5$. Following the method above, we get $\\begin{array}{c}{{f_{2}(i)=g(i)\\cdot(i+2)^{2}}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!}}&{{\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!}}&{{\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!\\!\\!}}\\\\ {{\\mathrm{~}\\!\\!\\!}}&{{\\!\\!\\!\\!}}\\end{array}$ Then the answer can be calculated in linear time, with $g$, $f_{0}$, $f_{1}$ and $f_{2}$ all calculated beforehand. Overall complexity is $O(n^{2})$. Refer to the square-time solution below for an implementation. Then, note that recurrences of $f_{0}$, $f_{1}$ and $f_{2}$ are in the form of convolutions, so we'd like to optimize it with FFT. However, they include convolutions of the previous parts of the function itself, with another function like $g(i) \\cdot i^{2}$, $g(i) \\cdot (i + 1)^{2}$ or $g(i) \\cdot (i + 2)^{2}$. Under this situation, apply FFT in a divide-and-conquer subroutine. solve(L, R) assumes that $f(1;L - 1)$ are already calculated, and all the terms that contribute to $f(L;R)$ and involve $f(1;L - 1)$ are already accumulated in their corresponding array positions. It finishes calculation of $f(L;R)$. First, it calls solve(L, M), then add all terms that contribute to $f(M + 1;R)$ involving $f(L;M)$ by convolving $f(L;M)$ with the other function (say $g(i)  \\times  i^{2}$), then call solve(M+1, R). Over complexity is $O(n\\log^{2}n)$. The model solution solves $f_{0}$ and $f_{1}$ in one pass, and $f_{2}$ in another. They can also be merged into a single pass. Big thanks to you for patiently reading till this point, and if you just want to enjoy the problem rather than implementation, feel free just to write a $O(n^{2})$ solution :)",
    "code": "#include <cstdio>\n#include <cstring>\ntypedef long long int64;\nstatic const int LOGN = 18;\nstatic const int MAXN = 1 << LOGN;\nstatic const int MODULUS = 998244353;\nstatic const int PRIMITIVE = 2192;\n#define _  %  MODULUS\n#define __ %= MODULUS\ntemplate <typename T> inline void swap(T &a, T &b) { static T t; t = a; a = b; b = t; }\n\nint n;\nint64 g[MAXN];\nint64 g0[MAXN], g1[MAXN], g2[MAXN];\nint64 f0[MAXN], f1[MAXN], f2[MAXN];\n\nint64 q0[MAXN], q1[MAXN];\nint64 t1[MAXN], t2[MAXN], t3[MAXN], t4[MAXN];\n\ninline int qpow(int64 base, int exp)\n{\n    int64 ans = 1;\n    for (; exp; exp >>= 1) { if (exp & 1) (ans *= base)__; (base *= base)__; }\n    return ans;\n}\n\nint bitrev[LOGN][MAXN];\nint root[2][LOGN];\ninline void fft(int n, int64 *a, int direction)\n{\n    int s = __builtin_ctz(n);\n    int64 u, v, r, w;\n    for (int i = 0; i < n; ++i) if (i < bitrev[s][i]) swap(a[i], a[bitrev[s][i]]);\n    for (int i = 1; i <= n; i <<= 1)\n        for (int j = 0; j < n; j += i) {\n            r = root[direction == -1][__builtin_ctz(i)];\n            w = 1;\n            for (int k = j; k < j + (i >> 1); ++k) {\n                u = a[k];\n                v = (a[k + (i >> 1)] * w)_;\n                a[k] = (u + v)_;\n                a[k + (i >> 1)] = (u - v + MODULUS)_;\n                w = (w * r)_;\n            }\n        }\n}\n\ninline void convolve(int n, int64 *a, int64 *b, int64 *c)\n{\n    static int64 a1[MAXN], b1[MAXN];\n    memcpy(a1, a, n * 2 * sizeof(int64));\n    memcpy(b1, b, n * 2 * sizeof(int64));\n    memset(a + n, 0, n * sizeof(int64));\n    memset(b + n, 0, n * sizeof(int64));\n    fft(n * 2, a, +1);\n    fft(n * 2, b, +1);\n    int64 q = qpow(n * 2, MODULUS - 2);\n    for (int i = 0; i < n * 2; ++i) c[i] = a[i] * b[i]_;\n    fft(n * 2, c, -1);\n    for (int i = 0; i < n; ++i) c[i] = c[i] * q _;\n    memcpy(a, a1, n * 2 * sizeof(int64));\n    memcpy(b, b1, n * 2 * sizeof(int64));\n}\n\n// Calcukates f0 and f1.\nvoid solve_1(int l, int r)\n{\n    if (l == r) {\n        (f0[l] += g0[l])__;\n        (f1[l] += g1[l])__;\n        return;\n    }\n\n    int m = (l + r) >> 1;\n\n    solve_1(l, m);\n\n    int len = 1;\n    while (len < r - l + 1) len <<= 1;\n    for (int i = 0; i < len; ++i) q0[i] = (i + l <= m ? f0[i + l] : 0);\n    for (int i = 0; i < len; ++i) q1[i] = (i + l <= m ? f1[i + l] : 0);\n    for (int i = len; i < len * 2; ++i) q0[i] = q1[i] = 0;\n    convolve(len, g0, q0, t1);\n    convolve(len, g1, q0, t2);\n    convolve(len, g1, q1, t3);\n    convolve(len, g2, q1, t4);\n\n    for (int i = 0; i < len; ++i) {\n        if (i + l >= m + 1 - 1 && i + l <= r - 1) {\n            (f0[i + l + 1] += t1[i])__;\n            (f1[i + l + 1] += t2[i])__;\n        }\n        if (i + l >= m + 1 - 3 && i + l <= r - 3) {\n            (f0[i + l + 3] += t3[i])__;\n            (f1[i + l + 3] += t4[i])__;\n        }\n    }\n\n    solve_1(m + 1, r);\n}\n\n// Calculates f2.\nvoid solve_2(int l, int r)\n{\n    if (l == r) {\n        (f2[l] += (g2[l] + (l >= 1 ? t1[l - 1] : 0)))__;\n        return;\n    }\n\n    int m = (l + r) >> 1;\n\n    solve_2(l, m);\n\n    int len = 1;\n    while (len < r - l + 1) len <<= 1;\n    for (int i = 0; i < len; ++i) q0[i] = (i + l <= m ? f2[i + l] : 0);\n    for (int i = len; i < len * 2; ++i) q0[i] = 0;\n    convolve(len, g2, q0, t2);\n\n    for (int i = 0; i < len; ++i) {\n        if (i + l >= m + 1 - 3 && i + l <= r - 3) {\n            (f2[i + l + 3] += t2[i])__;\n        }\n    }\n\n    solve_2(m + 1, r);\n}\n\nint main()\n{\n    for (int s = 0; s < LOGN; ++s)\n        for (int i = 0; i < (1 << s); ++i)\n            bitrev[s][i] = (bitrev[s][i >> 1] >> 1) | ((i & 1) << (s - 1));\n    for (int i = 0; i < LOGN; ++i) {\n        root[0][i] = qpow(PRIMITIVE, MAXN >> i);\n        root[1][i] = qpow(PRIMITIVE, MAXN - (MAXN >> i));\n    }\n\n    scanf(\"%d\", &n);\n\n    g[0] = 1;\n    g[2] = 1;\n    for (int i = 4; i <= n; i += 2) g[i] = (g[i - 4] + g[i - 2])_;\n    for (int i = 0; i <= n; ++i) {\n        g0[i] = g[i] * i _ * i _;\n        g1[i] = g[i] * (i + 1)_ * (i + 1)_;\n        g2[i] = g[i] * (i + 2)_ * (i + 2)_;\n    }\n\n    solve_1(0, n);\n\n    int len = 1;\n    while (len < n) len <<= 1;\n    convolve(len, g1, f1, t1);\n    solve_2(0, n);\n\n    int64 ans = 0;\n\n    ans += (g[n - 1] + g[n - 3]) * (n - 1)_ * (n - 1)_ * n _;\n    for (int i = 2; i <= n - 2; ++i) {\n        ans += g0[i - 1] * f0[n - i - 1]_ * i _;\n        ans += g1[i - 2] * f1[n - i - 2]_ * 2 * i _;\n        if (i >= 3 && i <= n - 3)\n            ans += g2[i - 3] * f2[n - i - 3]_ * i _;\n    }\n\n    printf(\"%lld\\n\", ans _);\n\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "849",
    "index": "A",
    "title": "Odds and Ends",
    "statement": "Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?\n\nGiven an integer sequence $a_{1}, a_{2}, ..., a_{n}$ of length $n$. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.\n\nA \\underline{subsegment} is a contiguous slice of the whole sequence. For example, ${3, 4, 5}$ and ${1}$ are subsegments of sequence ${1, 2, 3, 4, 5, 6}$, while ${1, 2, 4}$ and ${7}$ are not.",
    "tutorial": "What will the whole array satisfy if the answer is Yes? An odd number of segments, each having an odd length. Thus the whole array needs to have an odd length. All segments starts and ends with odd numbers, so the array begins and ends with odd numbers as well. Is that a sufficient condition? Yes, because for an array of odd length, and begins & ends with odd numbers, it's a single subsegment that satisfy the requirements itself. Thus the answer is Yes if and only if $n$ is odd, $a_{1}$ is odd, and $a_{n}$ is odd.",
    "code": "#include <cstdio>\nstatic const int MAXN = 102;\n\nint n;\nint a[MAXN];\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) scanf(\"%d\", &a[i]);\n\n    puts((n % 2 == 1) && (a[0] % 2 == 1) && (a[n - 1] % 2 == 1) ? \"Yes\" : \"No\");\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "849",
    "index": "B",
    "title": "Tell Your World",
    "statement": "Connect the countless points with lines, till we reach the faraway yonder.\n\nThere are $n$ points on a coordinate plane, the $i$-th of which being $(i, y_{i})$.\n\nDetermine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on \\textbf{exactly one} of them, and each of them passes through \\textbf{at least one} point in the set.",
    "tutorial": "First way: consider the first three points. What cases are there? Denote them as $P_{1}(1, y_{1})$, $P_{2}(2, y_{2})$ and $P_{3}(3, y_{3})$. A possible Yes solution falls into one of these three cases: one of the lines pass through $P_{1}$ and $P_{2}$; passes through $P_{1}$ and $P_{3}$; or passes through $P_{2}$ and $P_{3}$. With each case, find out all the points that will be covered if the line is extended infinitely, and if there are still remaining points and all of them are collinear, then the answer is Yes. Time complexity is $O(n)$. Second way: consider the first point. A possible Yes solution falls into one of these two cases: $P_{1}$ lies alone on a line; or some $i$ exists such that one of the lines passes through $P_{1}$ and $P_{i}$. For the second case, iterate over this $i$, and do it similarly as above to check whether a possible solution exists; for the first case, either check it specially, or reverse the array and apply the check for second case again. Time complexity is $O(n^{2})$. Note that in this problem, there is no need to worry about floating point errors, since all possible slopes are either integers, or $0.5$, which can be precisely stored with IEEE doubles.",
    "code": "#include <cstdio>\n#include <algorithm>\nstatic const int MAXN = 1004;\n\nint n;\nint y[MAXN];\n\nbool on_first[MAXN];\n\nbool check()\n{\n    for (int i = 1; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            if ((long long)i * (y[j] - y[0]) == (long long)j * (y[i] - y[0]))\n                on_first[j] = true;\n            else on_first[j] = false;\n        }\n        int start_idx = -1;\n        bool valid = true;\n        for (int j = 0; j < n; ++j) if (!on_first[j]) {\n            if (start_idx == -1) {\n                start_idx = j;\n            } else if ((long long)i * (y[j] - y[start_idx]) != (long long)(j - start_idx) * (y[i] - y[0])) {\n                valid = false; break;\n            }\n        }\n        if (valid && start_idx != -1) return true;\n    }\n    return false;\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) scanf(\"%d\", &y[i]);\n\n    bool ans = false;\n    ans |= check();\n    std::reverse(y, y + n);\n    ans |= check();\n\n    puts(ans ? \"Yes\" : \"No\");\n    return 0;\n}",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 1600
  },
  {
    "contest_id": "850",
    "index": "A",
    "title": "Five Dimensional Points",
    "statement": "You are given set of $n$ points in 5-dimensional space. The points are labeled from $1$ to $n$. No two points coincide.\n\nWe will call point $a$ bad if there are different points $b$ and $c$, not equal to $a$, from the given set such that angle between vectors $\\;{\\vec{a}}{\\vec{b}}$ and ${\\vec{a c}}$ is acute (i.e. strictly less than $90^{\\circ}$). Otherwise, the point is called good.\n\nThe angle between vectors $\\textstyle{\\bar{x}}$ and $\\overline{{y}}$ in 5-dimensional space is defined as $\\mathrm{aTCCOS}\\bigl(\\frac{\\vec{x}\\cdot\\vec{y}}{|\\vec{x}||\\vec{y}|}\\bigr)$, where $\\vec{x}\\cdot\\vec{y}=x_{1}y_{1}+x_{2}y_{2}+x_{3}y_{3}+x_{4}y_{4}+x_{5}y_{5}$ is the scalar product and $|{\\vec{x}}|={\\sqrt{{\\vec{x}}\\cdot{\\vec{x}}}}$ is length of $\\textstyle{\\vec{x}}$.\n\nGiven the list of points, print the indices of the good points in ascending order.",
    "tutorial": "It's easier to visualize this in 2D first. Fix a point $p$. If all other points form angles that are 90 degrees or greater, they must all be in different quadrants, so there can be at most 4 such points. In k dimension, this generalizes to 2*k such points, so for five dimensions, there can only be at most 10 other points. Thus, we can run the naive solution for small n and print 0 otherwise.",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "850",
    "index": "B",
    "title": "Arpa and a list of numbers",
    "statement": "Arpa has found a list containing $n$ numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is $1$.\n\nArpa can perform two types of operations:\n\n- Choose a number and delete it with cost $x$.\n- Choose a number and increase it by $1$ with cost $y$.\n\nArpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.\n\nHelp Arpa to find the minimum possible cost to make the list good.",
    "tutorial": "Let's define $cost(g)$ the cost if we want gcd of the array becomes $g$. The answer is $min cost(g)$ for $g > 1$. Now, let's see how to calculate $cost(g)$. For each number like $c$, we can delete it with cost $x$ or we can add it till $g$ divides it. So, we must pay $\\operatorname*{min}(x,y\\times(\\lceil{\\frac{\\epsilon}{g}}\\rceil\\times g-c))$. Let's iterate on possible values for $\\lceil{\\frac{c}{g}}\\rceil\\times g$. Before entering the main part of the solution, let's define two helper functions: - $cnt(l, r)$: this function returns the number of $i$'s such that $l  \\le  a_{i}  \\le  r$. - $sum(l, r)$: this function returns $\\textstyle\\sum_{i\\geq i\\leq n_{i}\\leq r}a_{i}$. To implement this function, define an array $ps$, such that $ps_{i}$ keeps the sum of values less than or equal to $i$. Then $sum(l, r) = ps_{r} - ps_{l - 1}$. Now for each multiple of $g$ like $k$, let's find the cost of numbers in the range $(k - g, k]$, and sum up these values. We must find the best $f$ and divide the range into two segments $(k - g, f]$ and $(f, k]$ and delete the numbers in the first range and add the numbers in second range till they become $k$. Now to find the best value for $f$, $(g-f)\\times y={\\textstyle\\frac{\\pi}{v}}\\Rightarrow f=g-\\operatorname*{min}(g,{\\textstyle\\frac{\\pi}{v}})$. So, the total cost for this range is $cnt(k - g + 1, k -  \\lfloor  f \\rfloor )  \\times  x + (cnt(k -  \\lfloor  f \\rfloor  + 1, k)  \\times  k - sum(k -  \\lfloor  f \\rfloor  + 1, k))  \\times  y$. Time complexity: $O(\\operatorname*{max}a_{i}\\log\\operatorname*{max}a_{i})$.",
    "tags": [
      "implementation",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "850",
    "index": "C",
    "title": "Arpa and a game with Mojtaba",
    "statement": "Mojtaba and Arpa are playing a game. They have a list of $n$ numbers in the game.\n\nIn a player's turn, he chooses a number $p^{k}$ (where $p$ is a prime number and $k$ is a positive integer) such that $p^{k}$ divides at least one number in the list. For each number in the list divisible by $p^{k}$, call it $x$, the player will delete $x$ and add $\\frac{\\mathcal{Z}}{p^{k}}$ to the list. The player who can not make a valid choice of $p$ and $k$ loses.\n\nMojtaba starts the game and the players alternatively make moves. Determine which one of players will be the winner if both players play optimally.",
    "tutorial": "The problem is separate for each prime, so we will calculate Grundy number for each prime and xor these number to find the answer. Now let's solve the problem for some prime like $p$. Let's show the game with a $mask$, $i$-th bit of $mask$ is true if and only if there is a number in the list such that it is divisible by $p^{i}$ and it isn't divisible by $p^{k + 1}$. When some player chooses $p$ and some $k$ in his turn, in fact, he converts $mask$ to $(mask>>k)|(mask&((1<<k) - 1))$. So, for each $k$, there is an edge between state $(mask>>k)|(mask&((1<<k) - 1))$ and $mask$. We can caluclate the grundy numbers by this way.",
    "tags": [
      "bitmasks",
      "dp",
      "games"
    ],
    "rating": 2200
  },
  {
    "contest_id": "850",
    "index": "D",
    "title": "Tournament Construction",
    "statement": "Ivan is reading a book about tournaments. He knows that a tournament is an oriented graph with exactly one oriented edge between each pair of vertices. The score of a vertex is the number of edges going outside this vertex.\n\nYesterday Ivan learned Landau's criterion: there is tournament with scores $d_{1} ≤ d_{2} ≤ ... ≤ d_{n}$ if and only if $d_{1}+\\cdot\\cdot\\cdot+d_{k}\\geqslant{\\frac{k(k-1)}{2}}$ for all $1 ≤ k < n$ and $d_{1}+d_{2}+\\cdot\\cdot\\cdot+d_{n}={\\frac{n(n-1)}{2}}$.\n\nNow, Ivan wanna solve following problem: given a \\textbf{set} of numbers $S = {a_{1}, a_{2}, ..., a_{m}}$, is there a tournament with given set of scores? I.e. is there tournament with sequence of scores $d_{1}, d_{2}, ..., d_{n}$ such that if we remove duplicates in scores, we obtain the required set ${a_{1}, a_{2}, ..., a_{m}}$?\n\nFind a tournament with \\textbf{minimum} possible number of vertices.",
    "tutorial": "Let $n$ be the number of players participating in the tournament. First of all, note that $n  \\le  61$, since the total number of wins must be $\\textstyle{\\frac{n\\times(n-1)}{2}}$, and there can be no more than $30  \\times  n$, therefore ${\\frac{n\\times(n-1)}{2}}\\leq30\\times n$, hence $n  \\le  61$. Next, we find an appropriate $n$, based on the criterion of the condition. We will go through all possible $n$ from 1 to 61 and use the dynamic programming method to determine whether there can be a given number of participants, the parameters will be: the current element in the sorted list $a_{pos}$ how many participants are already aware of their number of victories the total number of wins for the already known participants From these parameters, we store whether it is possible for the remaining participants to assign any $a_{pos}, a_{pos + 1}... a_{m}$ so that there is a tournament for these participants. Also, do not forget that each of $a_{i}$ should be taken at least once. Further, if we did not find $n$, then we print $- 1$. Otherwise, you can recover from the dynamics how many times we took each $a_{i}$, it remains to build a correct tournament on these values. To do this, each time we take the player with the smallest number of wins, let this number be $x$, and we make him win $x$ other players with the least number of wins, and loose to the remaining players. Next, delete this player, recompute for each remaining player how many times they have to win, and continue this process until all of the players are processed. The proof that a correct tournament is always built by this algorithm follows from the criterion. Thus, the first part works in $O(m^{5})$ the second part works in $O(m^{2}\\times\\log m)$.",
    "tags": [
      "constructive algorithms",
      "dp",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "850",
    "index": "E",
    "title": "Random Elections",
    "statement": "The presidential election is coming in Bearland next year! Everybody is so excited about this!\n\nSo far, there are three candidates, Alice, Bob, and Charlie.\n\nThere are $n$ citizens in Bearland. The election result will determine the life of all citizens of Bearland for many years. Because of this great responsibility, each of $n$ citizens will choose one of six orders of preference between Alice, Bob and Charlie uniformly at random, independently from other voters.\n\nThe government of Bearland has devised a function to help determine the outcome of the election given the voters preferences. More specifically, the function is $f(x_{1},x_{2},\\dots,x_{n}):\\{0,1\\}^{n}\\rightarrow\\{0,1\\}$ (takes $n$ boolean numbers and returns a boolean number). The function also obeys the following property: $f(1 - x_{1}, 1 - x_{2}, ..., 1 - x_{n}) = 1 - f(x_{1}, x_{2}, ..., x_{n})$.\n\nThree rounds will be run between each pair of candidates: Alice and Bob, Bob and Charlie, Charlie and Alice. In each round, $x_{i}$ will be equal to $1$, if $i$-th citizen prefers the first candidate to second in this round, and $0$ otherwise. After this, $y = f(x_{1}, x_{2}, ..., x_{n})$ will be calculated. If $y = 1$, the first candidate will be declared as winner in this round. If $y = 0$, the second will be the winner, respectively.\n\nDefine the probability that there is a candidate who won two rounds as $p$. $p·6^{n}$ is always an integer. Print the value of this integer modulo $10^{9} + 7 = 1 000 000 007$.",
    "tutorial": "$b_{k}(x)$ denotes $i$-th bit of $x$. ${\\mathrm{pop}}(x)$ denotes number of bits in $x$. Count number of ways where Alice wins. Suppose Alice wins in first round with mask $x$ and in third round with mask $y$ (so, $b_{i}(x) = 1$ or $b_{i}(y) = 1$ if $i$ voter preferred Alice in corresponding round). Necessary condition is $f(x) = f(y) = 1$. Assume we fixed $x$ and $y$. In how many ways we can choose orders for voters? If $b_{i}(x) = b_{i}(y)$, we can chose two valid permutations for $i$-th voter. If $b_{i}(x)\\neq b_{i}(y)$, only one permutation. So, total number of permutation is $2^{n-\\mathrm{pop}(x\\oplus y)}$. So, answer to the problem is $\\sum f(x){=}f(y){=}1\\ 2^{n-}\\mathrm{{pop}}(x{\\vec{\\omega}}y)\\,.$ Denote $S = {x|f(x) = 1}$. Lets solve more general problem, for each $z$, how many pairs $(x, y)$ are there such that $z=x\\oplus y$ and $x,y\\in S$? This is well-known problem. There are multiple $O(2^{nn})$ solutions. Probably first usage of this problem in competitive programming can be found here https://apps.topcoder.com/wiki/display/tc/SRM+518. If you interesting in understanding this approach more deeply from math perspective, you can start investigate from here https://en.wikipedia.org/wiki/Fourier_transform_on_finite_groups. Sorry for late editorial. Btw, in task D there are always an answer (for any set S), that's called Reid's conjectue and was proven by T.X. Yao in 1988 (and have very difficult proof that I didn't manage to find in English; if somebody succeed in search, please direct it to me).",
    "tags": [
      "bitmasks",
      "brute force",
      "divide and conquer",
      "fft",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "850",
    "index": "F",
    "title": "Rainbow Balls",
    "statement": "You have a bag of balls of $n$ different colors. You have $a_{i}$ balls of the $i$-th color.\n\nWhile there are at least two different colored balls in the bag, perform the following steps:\n\n- Take out two random balls without replacement one by one. These balls might be the same color.\n- Color the second ball to the color of the first ball. You are not allowed to switch the order of the balls in this step.\n- Place both balls back in the bag.\n- All these actions take exactly one second.\n\nLet $M = 10^{9} + 7$. It can be proven that the expected amount of time needed before you stop can be represented as a rational number $\\frac{P}{Q}$, where $P$ and $Q$ are coprime integers and where $Q$ is not divisible by $M$. Return the value $P\\cdot Q^{-1}\\mod{M}$.",
    "tutorial": "First, let's fix the final color of the balls. After fixing the final color, we can see the other colors don't matter. Define an \"interesting\" draw as one where we choose a ball of the final color and one of a different color. Once we do an interesting draw, we can see there is an equal probability of increasing or decreasing the number of balls of our final color. So, we can view this as a random walk, with equal probability of going in either direction. Let $X_{t}$ be the number of balls of the final color at time $t$. Let $T$ be the first time we hit 0 or $S$ balls. Now, we can write the expected value of time as follows: Let $t(r) = E(T|X_{0} = r, X_{T} = S)$ (i.e. in words, expected value of time, given we are at $r$, only counting the events that reach $X_{T} = S$ first). Let $p(r)$ be the probability of an interesting draw, so $p(r) = r  \\times  (S - r)  \\times  2 / (S  \\times  (S - 1))$. Then, we can write $t(r) = p / 2  \\times  t(r - 1) + p / 2  \\times  t(r + 1) + r / S$. Rearranging gives us $2  \\times  t(r) = t(r - 1) + t(r + 1) + (S - 1) / (S - r)$. So, in particular, $t(r) - t(r - 1) = t(r + 1) - t(r) + (S - 1) / (S - r)$ So, letting $g(r) = t(r) - t(r - 1)$, we get $g(r + 1) = g(r) - (S - 1) / (S - r)$. Doing some more manipulation can get us $t(r)=(S-1)\\times(S-r)\\sum_{i=0}^{r-1}1/(S-i)$. So, we just need to print the sum of $t(a_{i})$.",
    "tags": [
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "851",
    "index": "A",
    "title": "Arpa and a research in Mexican wave",
    "statement": "Arpa is researching the Mexican wave.\n\nThere are $n$ spectators in the stadium, labeled from $1$ to $n$. They start the Mexican wave at time $0$.\n\n- At time $1$, the first spectator stands.\n- At time $2$, the second spectator stands.\n- $...$\n- At time $k$, the $k$-th spectator stands.\n- At time $k + 1$, the $(k + 1)$-th spectator stands and the first spectator sits.\n- At time $k + 2$, the $(k + 2)$-th spectator stands and the second spectator sits.\n- $...$\n- At time $n$, the $n$-th spectator stands and the $(n - k)$-th spectator sits.\n- At time $n + 1$, the $(n + 1 - k)$-th spectator sits.\n- $...$\n- At time $n + k$, the $n$-th spectator sits.\n\nArpa wants to know how many spectators are standing at time $t$.",
    "tutorial": "Another solution: just print $min(t, k, n + k - t)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "851",
    "index": "B",
    "title": "Arpa and an exam about geometry",
    "statement": "Arpa is taking a geometry exam. Here is the last problem of the exam.\n\nYou are given three points $a, b, c$.\n\nFind a point and an angle such that if we rotate the page around the point by the angle, the new position of $a$ is the same as the old position of $b$, and the new position of $b$ is the same as the old position of $c$.\n\nArpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.",
    "tutorial": "If $a, b, c$ are on the same line or $dis(a, b)  \\neq  dis(b, c)$, the problem has not any solution.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "853",
    "index": "A",
    "title": "Planning",
    "statement": "Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are $n$ flights that must depart today, the $i$-th of them is planned to depart at the $i$-th minute of the day.\n\nMetropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first $k$ minutes of the day, so now the new departure schedule must be created.\n\nAll $n$ scheduled flights must now depart at different minutes between $(k + 1)$-th and $(k + n)$-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.\n\nHelen knows that each minute of delay of the $i$-th flight costs airport $c_{i}$ burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.",
    "tutorial": "We will show that following greedy is correct: let's for each moment of time use a plane, which can depart in this moment of time (and didn't depart earlier, of course) with minimal cost of delay. Proof is quite simple: it's required to minimize $\\sum_{i=1}^{n}c_{i}\\cdot(t_{i}-i)=\\sum_{i=1}^{n}c_{i}\\cdot t_{i}-\\sum_{i=1}^{n}c_{i}\\cdot i$. You can notice that $\\textstyle\\sum_{i=1}^{n}c_{i}\\cdot i$ is constant, so we just need to minimize $\\textstyle\\sum_{i=1}^{n}c_{i}\\cdot t_{i}$. Consider the optimal solution when plane $i$ departs at moment $b_{i}$ and solution by greedy algorithm in which plane $i$ departs at moment $a_{i}$. Let $x$ be plane with minimal $c_{x}$, such $a_{x}  \\neq  b_{x}$. At any moment greedy algorithm takes avaliable plane with lowest $c_{x}$, so $a_{x} < b_{x}$. Let $y$ be a plane, such that $b_{y} = a_{x}$. But $c_{y} > = b_{y}$, so $b_{x} \\cdot c_{x} + b_{y} \\cdot c_{y} > = b_{x} \\cdot c_{y} + b_{y} \\cdot c_{x}$ and it's possible to swap $b_{x}$ and $b_{y}$ in optimal solution without loosing of optimality. By performing this operation many times it's possible to make $b_{i} = a_{i}$ for each $i$ and it means that greedy solution is optimal. To make this solution work fast you need to use some data structures to find optimal plane faster for each moment. This data structure should be able to add number into set, give value of minimal element in set and erase minimal number from set. For this purpose you can use heap (or someting like std::set or std::priority_queue in C++).",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "853",
    "index": "B",
    "title": "Jury Meeting",
    "statement": "Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.\n\nThere are $n + 1$ cities consecutively numbered from $0$ to $n$. City $0$ is Metropolis that is the meeting point for all jury members. For each city from $1$ to $n$ there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires $k$ days of work. For all of these $k$ days each of the $n$ jury members should be present in Metropolis to be able to work on problems.\n\nYou know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.\n\nGather everybody for $k$ days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for $k$ days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than $k$ days.",
    "tutorial": "Obviously, each member of the jury needs to buy exactly two tickets - to the capital and back. Sort all flights by the day of departure. Now go through flights to the capital (forward flights) and one by one assume it is the last forward flight in answer (let's say it is scheduled on day $d$). Thus you are assuming that all forward flights are contained in some fixed prefix of flights. Make sure that there is at least one forward flight for every jury member in this prefix and find the cheapest forward flight among them for every person. All return flights we are interested in are contained in the suffix of flights list such that every flight's departure date is at least $d + k + 1$. Take similar steps: make sure that there is at least one return flight for every jury member in this suffix and find the cheapest return flight among them for every person as well. Select minimal cost among these variants or find out that the problem has no solution. Expected complexity: $O(nm^{2})$ or $O(m^{2} + n)$. Just as the boundary of considered prefix moves right, the boundary of considered suffix moves right as well. This suggests that the problem could be solved by the two pointers method. Assume you are storing minimum forward flight's cost on current prefix (infinity if no flight exists) for every person, and you are storing multiset (ordered by cost) of all return flights on current suffix for each person as well. To proceed next prefix and conforming suffix do the following: Move prefix boundary to the next forward flight. If its cost $c_{i}$ is less than minimum forward flight's cost $fwd_{fi}$ from that city, then you could improve total cost: decrease it by $c_{i} - fwd_{fi}$ and set $fwd_{fi}$ to $c_{i}$ since it's new minimal cost. Move suffix boundary to the next backward flight until there is such flight exists and it departure date difference with prefix boundary departure date is under $k + 1$. While moving suffix boundary, keep return flights multisets consistent: remove boundary flight right before moving that boundary to the next flight. Also check out if you are removing cheapest flight from multiset. If it is so, minimal flight cost for that city changed as well as total cost: it increases by difference between old minimal cost and new minimal cost. Keep in mind that if you are removing last flight from multiset, then there is no more appropriate return flight for this city and you should terminate the process. Proceed these steps moving boundaries to the right until the process terminates. In this way you've reviewed the same prefixes and corresponding suffixes as in slower solution described above. Expected complexity: $O(m\\cdot\\log m+n)$.",
    "tags": [
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "853",
    "index": "C",
    "title": "Boredom",
    "statement": "Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.\n\nFirst Ilya has drawn a grid of size $n × n$ and marked $n$ squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly $n·(n - 1) / 2$ beautiful rectangles.\n\nIlya has chosen $q$ query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.\n\nNow Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.",
    "tutorial": "We can't iterate over all interesting rectangles. Let's count number of rectangles that are not intersecting our rectangle. To do it let's calculate number of rectangles to the left, right, up and down of rectangle in query. It can be easily done in $O(1)$ time: suppose we have rectangle with corners $(i;p_{i})$ and $(j;p_{j})$. We have $min(i, j) - 1$ points to the left of rectangle, $n - max(i, j)$ to the right, $min(p_{i}, p_{j}) - 1$ to the down, etc. If we have $x$ points in some area, there are $\\textstyle{\\frac{x(x-1)}{2}}$ rectangles in that area. But now we calculated twice rectangles that are simultaneously to the left and up of our rectangle, left and down, etc. To find number of such rectangles we can iterate over all points and find points which are in these areas and find number of rectangles in area using formula $\\textstyle{\\frac{x(x-1)}{2}}$. The complexity is $O(q \\cdot n)$. To solve the problem we need to find number of points in some areas faster. It's quite easy to notice that we just have many queries of finding number of points in some subrectangle. It's classical problem that can be solved with some 2d tree in $O(q \\cdot log^{2})$ solution. But it can be too slow and can not fit into time limit in case of inaccurate implementation. However, you can notice that all queries are offline and find number of points in subrectangle in $O(q \\cdot logn)$ time. It's fast enough to pass all tests.",
    "tags": [
      "data structures"
    ],
    "rating": 2100
  },
  {
    "contest_id": "853",
    "index": "D",
    "title": "Michael and Charging Stations",
    "statement": "Michael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs.\n\nMichael's day starts from charging his electric car for getting to the work and back. He spends $1000$ burles on charge if he goes to the first job, and $2000$ burles if he goes to the second job.\n\nOn a charging station he uses there is a loyalty program that involves bonus cards. Bonus card may have some non-negative amount of bonus burles. Each time customer is going to buy something for the price of $x$ burles, he is allowed to pay an amount of $y$ ($0 ≤ y ≤ x$) burles that does not exceed the bonus card balance with bonus burles. In this case he pays $x - y$ burles with cash, and the balance on the bonus card is decreased by $y$ bonus burles.\n\nIf customer pays whole price with cash (i.e., $y = 0$) then 10% of price is returned back to the bonus card. This means that bonus card balance increases by $\\scriptstyle{\\frac{x}{10}}$ bonus burles. Initially the bonus card balance is equal to 0 bonus burles.\n\nMichael has planned next $n$ days and he knows how much does the charge cost on each of those days. Help Michael determine the minimum amount of burles in cash he has to spend with optimal use of bonus card. Assume that Michael is able to cover any part of the price with cash in any day. It is not necessary to spend all bonus burles at the end of the given period.",
    "tutorial": "Before solving problem one observation is required: suppose at day $i$ we have $x_{i}$ bonuses. Then exists optimal solution, which spends $0$ or $min(a_{i}, x_{i})$ bonuses every day. It's quite easy to proof: suppose we have some optimal solution and $i$ is a first day, when neither $0$ nor $min(a_{i}, x_{i})$ bonuses were spent. If $i$ is a last day on which non-zero amount of bonuses was spent, we can notice that solution spending $min(a_{i}, x_{i})$ bonuses that day is more optimal, so first solution was optimal. So let's consider next day after $i$, when non-zero amount of bonuses was spent, say $j$, and amount of bonuses spent at day $j$ is $s_{j}$ (Also, amount of bonuses spent on day $i$ is $s_{i}$). Let's look at solution that spends $s_{i} + min(s_{i} - min(a_{i}, x_{i}), s_{j})$ bonuses at day $i$ and $s_{j} - min(s_{i} - min(a_{i}, x_{i}), s_{j})$. That solution is still correct and still optimal, but it spends $min(a_{i}, x_{i})$ at day $i$ or $0$ at day $j$. Anyway this operation increases first day $i$ when neither $i$ nor $min(a_{i}, x_{i})$ bonuses were spent or first day $j$ after it, when non-zero amount of burles were spent. But we can't increase $i$ or $j$ infinitely, so, after some iterations of such transformation, solution, spending $0$ or $min(a_{i}, x_{i})$ bonuses in each day. To make an $O(n^{2})$ solution it's possible to consider dynamic programming approach: let $dp_{i, j}$ be minimum amount of money that is possible to spend at first $i$ days to pay for all chargings and have $100 \\cdot j$ bonuses on card. At first, $dp_{0, 0} = 0$ and $dp_{i, j} =  \\infty $. Then we can easy calculate all states going through all states with something like this code: Of course, $j$ can be up to $2 \\cdot n$, because at each day it's possible to earn at most 2 bonuses. To make this solution faster let's consider the following observation: there exists an optimal solution, which never has more $3000$ bonuses on bonus card. To proof it let's first proof following lemma: Lemma 1: There exists an optimal solution which spends only $0$ or $a_{i}$ bonuses at day $i$ if there are at least $3000$ bonuses at card at the beginning of day $i$. Lemma 1 proof: Let's introduce some designations. Let $x_{i}$ be amount of bonuses at the beginning of day $i$ and $s_{i}$ be amount of bonuses spent at day $i$. Also let's call day $i$ \"fractional\" if $s_{i}  \\neq  0$ and $s_{i}  \\neq  a_{i}$, and call day $i$ \"interesting\" if $s_{i}  \\neq  0$. Let's proof lemma2 and lemma3 at first: Lemma 2: Assume $x_{i}  \\ge  3000$ and $j$ - next after $i$ interesting day and $k$ - next after $j$ interesting day. Then there exists an optimal solution in which $k$ is not a fractional day or $j$ is not a fractional day. Lemma2 proof: Suppose is some optimal solution $j$ and $k$ are fractional days. Let's consider a solution spending $s_{j} + min(s_{k}, a_{j} - s{j})$ bonuses at day $j$ and $s_{k} - min(s_{k}, a_{j} - s{j})$ at day $k$. This solution is still correct, because $x_{i}  \\ge  3000$, so for days $j$ and $k$ there is enough bonuses and still optimal. Lemma2 is proved. Lemma 3: Assume $x_{i}  \\ge  3000$ and $j$ - next after $i$ interesting day. Then there exists an optimal solution is which $j$ is not a fractional day. Lemma 3 proof: Consider some optimal solution with fractional day $j$. At first let's proof that $j$ is not last interesting day. Suppose, $j$ is last interesting day in solution. But we can make a solution that spends $a_{i}$ bonuses at day $i$ (because $a_{i}  \\le  3000$) and it will be more optimal. Contradiction. So there exists next after $j$ interesting day. Let's call it $k$. Let's consider 2 cases: Case 1 ($a_{j} = 1000$): Let's spend consider solution spending $1000$ bonuses at day $j$ and $a_{k} - (1000 - s_{j}))$ at day $k$. It's still correct and optimal but $j$ is not a fractional day. Case 2 ($a_{j} = 2000$): There are two subcases: Case 2.1 ($a_{k} = 2000$): Let's spend consider solution spending $2000$ bonuses at day $j$ and $a_{k} - (2000 - s_{j}))$ at day $k$. It's still correct and optimal but $j$ is not a fractional day. Case 2.2 ($a_{k} = 1000$): Let's proof, $k$ is not last interesting day. Assume $k$ is last interesting day. Consider a solution spending $2000$ bonuses at day $j$ and 1000 bonuses at day $k$. It's correct but more optimal that initial solution. Conrtadiction. Now let $p$ be next after $k$ interesting day ($k$ is not a fractional day by lemma2). If $2000 - a_{j}  \\le  1000$ we can consider solution which spends $2000$ bonuses at day $j$, $1000 - (2000 - a_{k})$ bonuses at day $k$ and $s_{p}$ bonuses at day $p$. If $2000 - s_{j} > 1000$ let's consider a solution which spends $s_{j} + 1000$ bonuses at day $j$, $0$ bonuses at day $k$ and $s_{p}$ at day $p$. But by lemma2 $s_{p} = a_{p}$, so we can consider solution that spends $2000$ bonuses at day $j$ $0$ bonuses at day $k$ and $a_{p} - (2000 - s_{j} - a_{k})$ at day $k$. All of these solutions are correct and optimal. Lemma 1 proof (end): At first, of course there is at least one interesting day after $i$ (Otherwise, it's more optimal to charge at day $i$ using bounses, but in initial solution $s_{i} = 0$ because $x_{i - 1}  \\le  3000$ and $x_{i} > 3000$). Let's call that day $j$ and by lemma3 $j$ is not fractional day. Let's consider 4 cases now: Case 1: ($a_{i} = 1000, a_{j} = 1000$). Let's consider a solution with $s_{i} = 1000$ and $s_{j} = 0$. It's correct and still optimal, but $x_{i}  \\le  3000$. Case 2: ($a_{i} = 2000, a_{j} = 2000$). Same as case1. Case 3: ($a_{i} = 2000, a_{j} = 1000$). Let's consider 2 subcases: Case 3.1: $j$ is not last interesting day. Let $k$ be next interesting day. It $a_{k} = 1000$ consider a solution spending $2000$ bonuses at day $i$, $0$ bonuses at days $j$ and $k$. It's still correct and optimal, but $x_{i}  \\le  3000$. If $a_{k} = 2000$ consider a solution a spending $2000$ bonuses at day $i$, $1000$ bonuses at day $j$ and $0$ bonuses at day $k$. It's correct and optimal too, and $x_{i}  \\le  3000$ too. Case 3.2: $j$ is last interesting day. Let's construct solution this way. At first let's set $s_{i} = 1000$ and $s_{j} = 0$. Then let's iterate over all ineteresting days after $j$, say $k$, in order in increasing time and set $s_{i} = s_{i} + min(2000 - s_{i}, s_{k}), s_{k} = s_{k} - min(2000 - s_{i}, s_{k})$. If after this process we still have some bonus left just add it to $s_{i}$. At the end, $s_{i}$ will be equal $2000$ because we spent all bonuses, solution will still be correct and optimal, but $x_{i}  \\le  3000$. Case 4: ($a_{i} = 1000, a_{j} = 2000$). Let $p$ be last day before $i$ with $s_{p}  \\neq  0$. If $a_{p} = 1000$ consider a solution with $s_{p} = 0, s_{i} = 0, s_{j} = 2000$. It's correct, optimal and $x_{t}  \\le  3000$ for each $t  \\le  i$. If $a_{p} = 2000$, consider a solution with $s_{p} = 2000, s_{i} = 0, s_{j} = 0$. It's correct, optimal and $x_{t}  \\le  3000$ for each $t  \\le  i$, too. So for all cases we can make correct and optimal solution such there is no $x_{i}  \\le  3000$ for all $i$, or number of first day with $x_{i} > 3000$ increases, but it can't increase forever, so after some amount of opereations solution with $x_{i}  \\le  3000$ for all $i$ will be constructed. Because of this fact we can consider dynamic programming approach described before but notice, that we should consider only states with $j  \\le  30$. It will have $O(n)$ complexity. Moreover, looking at states with $j = 30$ is required. It's possible to make a test on which solution, that looks at states with $j  \\le  29$ will be incorrect.",
    "tags": [
      "binary search",
      "dp",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "853",
    "index": "E",
    "title": "Lada Malina",
    "statement": "After long-term research and lots of experiments leading Megapolian automobile manufacturer «AutoVoz» released a brand new car model named «Lada Malina». One of the most impressive features of «Lada Malina» is its highly efficient environment-friendly engines.\n\nConsider car as a point in $Oxy$ plane. Car is equipped with $k$ engines numbered from $1$ to $k$. Each engine is defined by its velocity vector whose coordinates are $(vx_{i}, vy_{i})$ measured in distance units per day. An engine may be turned on at any level $w_{i}$, that is a real number between $ - 1$ and $ + 1$ (inclusive) that result in a term of $(w_{i}·vx_{i}, w_{i}·vy_{i})$ in the final car velocity. Namely, the final car velocity is equal to\n\n\\[\n(w_{1}·vx_{1} + w_{2}·vx_{2} + ... + w_{k}·vx_{k},   w_{1}·vy_{1} + w_{2}·vy_{2} + ... + w_{k}·vy_{k})\n\\]\n\nFormally, if car moves with constant values of $w_{i}$ during the whole day then its $x$-coordinate will change by the first component of an expression above, and its $y$-coordinate will change by the second component of an expression above. For example, if all $w_{i}$ are equal to zero, the car won't move, and if all $w_{i}$ are equal to zero except $w_{1} = 1$, then car will move with the velocity of the first engine.\n\nThere are $n$ factories in Megapolia, $i$-th of them is located in $(fx_{i}, fy_{i})$. On the $i$-th factory there are $a_{i}$ cars «Lada Malina» that are ready for operation.\n\nAs an attempt to increase sales of a new car, «AutoVoz» is going to hold an international exposition of cars. There are $q$ options of exposition location and time, in the $i$-th of them exposition will happen in a point with coordinates $(px_{i}, py_{i})$ in $t_{i}$ days.\n\nOf course, at the «AutoVoz» is going to bring as much new cars from factories as possible to the place of exposition. Cars are going to be moved by enabling their engines on some certain levels, such that at the beginning of an exposition car gets exactly to the exposition location.\n\nHowever, for some of the options it may be impossible to bring cars from some of the factories to the exposition location by the moment of an exposition. Your task is to determine for each of the options of exposition location and time how many cars will be able to get there by the beginning of an exposition.",
    "tutorial": "In the original contest there were subtasks for this problem and it's more convinient to understand the editorial going through these subtasks, so we will leave them here. The key part of a solution is to understand what are the locations that may be accessed from the origin in $T$ seconds. First observation is that we should investigate it only in case when $T = 1$ because $T$ is simply a scale factor. Let's denote this set for $T = 1$ as $P$. Group #1. For the first group it's easy to see that P is a square with vertices in points $(  \\pm  2, 0), (0,  \\pm  2)$. So, the first group may be solved with a straightforward $O(qn)$ approach: we iterate through all the factories and check if it's possible to get for cars from $i$-th factories to the car exposition. We can rotate the plane by $45$ degrees (this may be done by the transformation $x' = x + y, y' = x - y$), after this each query region looks like a square. Therefore, it's necessary to check if point lies inside a square: $\\begin{array}{c}{{\\left\\{-2T\\le(p x_{i}-f x_{j})+(p y_{i}-f y_{j})\\le2T}}\\\\ {{\\left(-2T\\le(p x_{i}-f x_{j})-(p y_{i}-f y_{j})\\le2T}}\\end{array}\\right.$ Group #2. In the second group propeller velocities are two arbitrary vectors. It can be shown that $P$ will always be a parallelogram centered in the origin, built on vectors $2v_{1}$ and $2v_{2}$ as sides. Thus, this group is a matter of the same $O(qn)$ approach with a bit more complicated predicate: one should be able to check that an integer point belongs to an integer parallelogram. The key observation is that we may find an appropriate transformation of a plane that transforms this set into a rectangle. Indeed, there always exists an affine transformation performing what we want. As an additional requirement, we want to transform coordinates in such way that they are still integral and not much larger than the original coordinates. The transformation looks like following: $\\\\,{\\,\\binom{x^{\\prime}=v x_{1}\\cdot y-v y_{1}\\cdot x}{y^{\\prime}=v x_{2}\\cdot y-v y_{2}\\cdot x}}$ The first expression is a signed distance to the line parallel to the vector $v_{1}$, and the second one is the signed distance from the line parallel to the vector $v_{2}$. Easy to see that belonging to some query parallelogram can be formulated in terms of $x'$ and $y'$ independendly belonging to some ranges. Group #3. Second group should be a hint for the third group. One can find that the set $P = {w_{1v}_{1} + ... + w_{kv}_{k}||w_{i}|  \\le  1}$ is always a central-symmetric polygon with the center in the origin. Actually, this Polygon is a Minkowski sum of $k$ segments $[ - v_{i}, v_{i}]$. Minkowski sum of sets $A_{1}, A_{2}, ..., A_{k}$ is by definition the following set: $A_{1}+A_{2}+\\ldots+A_{k}=\\{a_{1}+a_{2}+\\ldots+a_{k}|a_{1}\\in A_{1},a_{2}\\in A_{2},\\ldots,a_{k}\\in A_{k}\\}$. It can be built in $O(k\\log k)$ time, although in this problem $k$ is very small, so one may use any inefficient approach that comes into his head, like building a convex hull of all points ${  \\pm  v_{1}  \\pm  v_{2}...  \\pm  v_{k}}$. After we found out a form of $P$, it's possible to solve the third group of tests in $O(qnk)$ by checking if each possible factory location belongs into a query polygon in $O(k)$ time. Following groups are exactly the same, but the constraints are higher, they require using some geometric data structure to deal with range queries. Groups #4 and #5. Fourth group and fifth group are very similar to first and second group correspondingly, but we need to process the requests faster. After the transformation of the plane, the request can be reformulated as \"find sum of all factories inside a square\", so any 2d data structure may be applied, like a segment tree of segment trees. Another approach is to use a sweeping line algorithm with a segment tree or an appropriate binary search tree, achieving a time complexity $O((q+n)\\log^{2}n)$ or $O((q+n)\\log n)$. Group #6. To solve the sixth group we need to use a trapezoidal polygon area calculation algorithm applied to our problem. Calculate the sum of points in each of $2k$ trapezoid areas below each of the sides of a polygon, and then take them with appropriate signs to achieve a result. Such trapezoid area can be seen as a set of points satisfying the inequalities $l  \\le  x  \\le  r$ and $y  \\le  kx + b$. Under transformation $x' = x, y' = y - kx$, this area becomes a rectangle, leading us to an $O((q+n)k\\log n)$ time solution.",
    "tags": [
      "data structures",
      "geometry"
    ],
    "rating": 3400
  },
  {
    "contest_id": "854",
    "index": "A",
    "title": "Fraction",
    "statement": "Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction $\\frac{a}{b}$ is called proper iff its numerator is smaller than its denominator ($a < b$) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive common divisors except $1$).\n\nDuring his free time, Petya thinks about proper irreducible fractions and converts them to decimals using the calculator. One day he mistakenly pressed addition button ($ + $) instead of division button ($÷$) and got sum of numerator and denominator that was equal to $n$ instead of the expected decimal notation.\n\nPetya wanted to restore the original fraction, but soon he realized that it might not be done uniquely. That's why he decided to determine maximum possible proper irreducible fraction $\\frac{a}{b}$ such that sum of its numerator and denominator equals $n$. Help Petya deal with this problem.",
    "tutorial": "It's possible to look over all possible values of the numerator $1\\leqslant a\\leqslant\\lfloor{\\frac{n}{2}}\\rfloor$. For the current value of $a$ we have to compute denominator as $b = n - a$, check that there are no common divisors (except $1$) of $a$ and $b$ (it also could be done by a linear search of possible common divisors $2  \\le  d  \\le  a$). The answer is the maximal fraction that was considered during the iteration over all possible values of the numerator and passed the irreducibility test. Pseudocode of the described solution is presented below: This solution have $O(n^{2})\\,$ time complexity. However, we can find answer to the problem analytically in the following way:",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "854",
    "index": "B",
    "title": "Maxim Buys an Apartment",
    "statement": "Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has $n$ apartments that are numbered from $1$ to $n$ and are arranged in a row. Two apartments are adjacent if their indices differ by $1$. Some of the apartments can already be inhabited, others are available for sale.\n\nMaxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly $k$ already inhabited apartments, but he doesn't know their indices yet.\n\nFind out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.",
    "tutorial": "Minimum number of good apartments is almost always $1$, since rooms with indices from $1$ to $k$ could be inhabited. Exceptions are cases in which $k = 0$ and $k = n$, in these cases both minimum and maximum number of good rooms is $0$ since there is no inhabitant or vacant apartments. Maximum number of good apartments could be reached, for example, as follows. Assume apartments with indices $2$, $5$, $8$ and so on are occupied as much as possible. Each of these apartments produces $2$ good rooms except from, if it exists, the one with index $n$ (that apartment produces $1$ good apartment). If number of inhabitant apartments is less than $k$ occupy any of rest rooms to reach that number, every such occupation will decrease number of good apartments by one). Simulate this process, than count the number of good rooms to find maximum possible number. Expected complexity: $O(n^{2})$ or $O(n)$. Instead of simulating the above process calculate number of apartments with indices $2$, $5$, $8$ and so on excluding the one with index $n$ if it exists. Number of that apartments is equal to $x=\\lfloor{\\frac{n}{3}}\\rfloor$, and if $k  \\le  x$ you can occupy some of these apartments to reach maximum number of good rooms equal to $2 \\cdot k$. Otherwise, if $k > x$, assume that apartments with indices $2$, $5$, $8$ and so on are occupied, so any room has at least one inhabited room adjacent to it. Therefore number of good apartments is equal to number of vacant apartments and is equal to $n - k$. Implementation of these formulas with keeping in mind cases in which $k = 0$ and $k = n$ will be scored as full solution of problem. Expected complexity: $O(1)$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "855",
    "index": "A",
    "title": "Tom Riddle's Diary",
    "statement": "Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.\n\nHe has names of $n$ people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.\n\nFormally, for a name $s_{i}$ in the $i$-th line, output \"YES\" (without quotes) if there exists an index $j$ such that $s_{i} = s_{j}$ and $j < i$, otherwise, output \"NO\" (without quotes).",
    "tutorial": "For each string $s_{i}$ iterate $j$ from $1$ to $i - 1$. Check if $s_{i} = s_{j}$ for any value of $j$. If it is output \"YES\", otherwise output \"NO\". Output will always be \"NO\" for the first string. The expected complexity was $O(n^{2}\\cdot\\operatorname*{max}_{1\\leq i\\leq n}(|s_{i}|))$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define sd(x) scanf(\"%d\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define ss(x) scanf(\"%s\",x)\n#define ll long long\n#define mod 1000000007\n#define bitcount    __builtin_popcountll\n#define pb push_back\n#define fi first\n#define se second\n#define mp make_pair\n#define pi pair<int,int>\nint main()\n{\n    //freopen(\"in.txt\",\"r\",stdin);\n    //freopen(\"out.txt\",\"w\",stdout);\n    int n,i,j;\n    string s[102];\n    sd(n);\n    for(i=0;i<n;i++)\n    {\n    \tcin>>s[i];\n    \tfor(j=0;j<i;j++)\n    \t{\n    \t\tif(s[i]==s[j])\n    \t\t\tbreak;\n    \t}\n    \tif(j==i)\n    \t\tprintf(\"NO\\n\");\n    \telse\n    \t\tprintf(\"YES\\n\");\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "855",
    "index": "B",
    "title": "Marvolo Gaunt's Ring",
    "statement": "Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly $x$ drops of the potion he made.\n\nValue of $x$ is calculated as maximum of $p·a_{i} + q·a_{j} + r·a_{k}$ for given $p, q, r$ and array $a_{1}, a_{2}, ... a_{n}$ such that $1 ≤ i ≤ j ≤ k ≤ n$. Help Snape find the value of $x$. Do note that the value of $x$ may be negative.",
    "tutorial": "There can be two approaches: First solution : Create a dynamic programming table of size $n \\cdot 3$. In this, $dp[i][0]$ stores maximum of value $p \\cdot a_{x}$ for $x$ between $1$ and $i$. Similarly $dp[i][1]$ stores the maximum value of $p \\cdot a_{x} + q \\cdot a_{y}$ such that $x  \\le  y  \\le  i$ and $dp[i][2]$ stores maximum value of $p \\cdot a_{x} + q \\cdot a_{y} + r \\cdot a_{z}$ for $x  \\le  y  \\le  z  \\le  i$. To calculate the dp: $dp[i][0] = max(dp[i - 1][0], p \\cdot a_{i})$ $dp[i][1] = max(dp[i - 1][1], dp[i][0] + q \\cdot a_{i})$ $dp[i][2] = max(dp[i - 1][2], dp[i][1] + r \\cdot a_{i})$ The answer will be stored in $dp[n][2]$ Second Solution : Maintain $4$ arrays, storing maximum and minimum from left, maximum and minimum from right. Let us call them $minLeft, minRight, maxLeft$ and $maxRight$. Then iterate $j$ through the array. Calculate $sum = q \\cdot a_{j}$. Now, if $p < 0$, add $minLeft_{i} \\cdot p$ to $sum$. Otherwise add $maxLeft_{i} \\cdot p$ to $sum$. Similarly, if $r > 0$, add $maxRight_{i} \\cdot r$, otherwise add $minRight_{i} \\cdot r$ to $sum$. Expected time complexity: $O(n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define sd(x) scanf(\"%d\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define ss(x) scanf(\"%s\",x)\n#define mod 1000000007\n#define bitcount __builtin_popcountll\n#define ll long long\n#define pb push_back\n#define pi pair<int,int>\n#define pii pair<pi,int>\n#define mp make_pair\nint minleft[100005],minright[100005],maxleft[100005],maxright[100005],a[100005];\nint main()\n{\n\tint i,j,k;\n\tint n,p,q,r;\n\tcin>>n>>p>>q>>r;\n\tfor(i=1;i<=n;i++)\n\t\tsd(a[i]);\n\tminleft[1]=maxleft[1]=a[1];\n\tminright[n]=maxright[n]=a[n];\n\tfor(i=2;i<=n;i++)\n\t{\n\t\tminleft[i]=min(minleft[i-1],a[i]);\n\t\tmaxleft[i]=max(maxleft[i-1],a[i]);\n\t}\n\tfor(i=n-1;i>=1;i--)\n\t{\n\t\tminright[i]=min(minright[i+1],a[i]);\n\t\tmaxright[i]=max(maxright[i+1],a[i]);\n\t}\n\tll ans=-3e18;\n\tfor(i=1;i<=n;i++)\n\t{\n\t\tll leftval = (p<0) ? 1ll*minleft[i]*p : 1ll*maxleft[i]*p;\n\t\tll rightval = (r<0) ? 1ll*minright[i]*r : 1ll*maxright[i]*r;\n\t\tans=max(ans,leftval+rightval+1ll*q*a[i]);\n\t}\n\tcout<<ans<<endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "855",
    "index": "C",
    "title": "Helga Hufflepuff's Cup",
    "statement": "Harry, Ron and Hermione have figured out that Helga Hufflepuff's cup is a horcrux. Through her encounter with Bellatrix Lestrange, Hermione came to know that the cup is present in Bellatrix's family vault in Gringott's Wizarding Bank.\n\nThe Wizarding bank is in the form of a tree with total $n$ vaults where each vault has some type, denoted by a number between $1$ to $m$. A tree is an undirected connected graph with no cycles.\n\nThe vaults with the highest security are of type $k$, and all vaults of type $k$ have the highest security.\n\n\\textbf{There can be at most $x$ vaults of highest security}.\n\nAlso, \\textbf{if a vault is of the highest security, its adjacent vaults are guaranteed to not be of the highest security and their type is guaranteed to be less than $k$}.\n\nHarry wants to consider every possibility so that he can easily find the best path to reach Bellatrix's vault. So, you have to tell him, given the tree structure of Gringotts, the number of possible ways of giving each vault a type such that the above conditions hold.",
    "tutorial": "This problem can be solved by using the concept of dp on trees. The dp table for this problem will be of the size $n \\cdot 3 \\cdot x$. We can assume any one node as the root and apply dfs while computing the dp array. Let the root be $1$. Here, $dp[curr][0][cnt]$ represent the number of ways of assigning type to each node in the subtree of $curr$ such that number of nodes with value $k$ in this subtree is $cnt$ and type at $curr$ is less than $k$. $dp[curr][1][cnt]$ represent the number of ways of assigning type to each node in the subtree of $curr$ such that number of nodes with value $k$ in this subtree is $cnt$ and type at $curr$ is equal to $k$. $dp[curr][2][cnt]$ represent the number of ways of assigning type to each node in the subtree of $curr$ such that number of nodes with value $k$ in this subtree is $cnt$ and type at $curr$ is greater than $k$. Now, to compute this dp for a node, curr, we assume this dp array is computed for its children. Then, we can combine them two nodes at a time to form the dp array for the node curr. While assigning the value to $dp[curr][1][cnt]$, we take into account only the values of $dp[childofcurr][0][cnt - z]$. Similarly for $dp[curr][2][cnt]$, we take into account only $dp[child of curr][0][cnt - z]$ and $dp[child of curr][2][cnt - z]$. For combining the value we make $x * x$ computations. Final answer will be $\\textstyle\\sum_{0\\leq i\\leq2}\\sum_{0\\leq j\\leq x}d p[1][i][j]$ The expected time complexity of the solution is: $O(n \\cdot 3 \\cdot x \\cdot x)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define sd(x) scanf(\"%d\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define ss(x) scanf(\"%s\",x)\n#define ll long long\n#define mod 1000000007\n#define bitcount    __builtin_popcountll\n#define pb push_back\n#define fi first\n#define se second\n#define mp make_pair\n#define pi pair<int,int>\nint dp[100005][3][12],x,k,m;\nint a[3][12],b[3][12];\nvector <int> q[100005];\nvoid dfs(int cur,int par)\n{\n\tint i,j=0,l,r,temp;\n\tfor(i=0;i<q[cur].size();i++)\n\t{\n\t\tif(q[cur][i]==par)\n\t\t\tcontinue;\n\t\tj=1;\n\t\tdfs(q[cur][i],cur);\n\t}\n\tif(!j)\n\t{\n\t\tdp[cur][0][0]=k-1;\n\t\tdp[cur][1][1]=1;\n\t\tdp[cur][2][0]=m-k;\n\t\treturn;\n\t}\n\tfor(i=0;i<3;i++)\n\t{\n\t\tfor(j=0;j<=x;j++)\n\t\t{\n\t\t\ta[i][j]=0;\n\t\t\tb[i][j]=0;\n\t\t}\n\t}\n\tfor(i=0;i<3;i++)\n\t\ta[i][0]=1;\n\tfor(i=0;i<q[cur].size();i++)\n\t{\n\t\tif(q[cur][i]==par)\n\t\t\tcontinue;\n\t\tfor(j=0;j<3;j++)\n\t\t{\n\t\t\tfor(l=0;l<=x;l++)\n\t\t\t{\n\t\t\t\tfor(r=0;r<=x;r++)\n\t\t\t\t{\n\t\t\t\t\tif(l+r>x)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif(j==0)\n\t\t\t\t\t{\n\t\t\t\t\t\ttemp=dp[q[cur][i]][0][r]+dp[q[cur][i]][1][r];\n\t\t\t\t\t\tif(temp>=mod)\n\t\t\t\t\t\t\ttemp-=mod;\n\t\t\t\t\t\ttemp+=dp[q[cur][i]][2][r];\n\t\t\t\t\t\tif(temp>=mod)\n\t\t\t\t\t\t\ttemp-=mod;\n\t\t\t\t\t\tb[j][l+r]+=(1ll*a[j][l]*temp)%mod;\n\t\t\t\t\t\tif(b[j][l+r]>=mod)\n\t\t\t\t\t\t\tb[j][l+r]-=mod;\n\t\t\t\t\t}\n\t\t\t\t\telse if(j==1)\n\t\t\t\t\t{\n\t\t\t\t\t\tb[j][l+r]+=(1ll*a[j][l]*(dp[q[cur][i]][0][r]))%mod;\n\t\t\t\t\t\tif(b[j][l+r]>=mod)\n\t\t\t\t\t\t\tb[j][l+r]-=mod;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ttemp=dp[q[cur][i]][0][r]+dp[q[cur][i]][2][r];\n\t\t\t\t\t\tif(temp>=mod)\n\t\t\t\t\t\t\ttemp-=mod;\n\t\t\t\t\t\tb[j][l+r]+=(1ll*a[j][l]*temp)%mod;\n\t\t\t\t\t\tif(b[j][l+r]>=mod)\n\t\t\t\t\t\t\tb[j][l+r]-=mod;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tfor(j=0;j<3;j++)\n\t\t{\n\t\t\tfor(l=0;l<=x;l++)\n\t\t\t{\n\t\t\t\ta[j][l]=b[j][l];\n\t\t\t\tb[j][l]=0;\n\t\t\t}\n\t\t}\n\t}\n\tfor(l=0;l<=x;l++)\n\t{\n\t\tdp[cur][0][l]=(1ll*a[0][l]*(k-1))%mod;\n\t\tif(l>=1)\n\t\t\tdp[cur][1][l]=a[1][l-1];\n\t\tdp[cur][2][l]=(1ll*a[2][l]*(m-k))%mod;\n\t}\n}\nint main()\n{\n    //freopen(\"in.txt\",\"r\",stdin);\n    //freopen(\"out.txt\",\"w\",stdout);\n    int n,i,j,ans;\n    sd(n);\n    sd(m);\n    for(i=1;i<n;i++)\n    {\n    \tsd(j);\n    \tsd(k);\n    \tq[j].pb(k);\n    \tq[k].pb(j);\n    }\n    sd(k);\n    sd(x);\n    dfs(1,0);\n    ans=0;\n    for(i=0;i<3;i++)\n    {\n    \tfor(j=0;j<=x;j++)\n    \t{\n    \t\t//printf(\"%d %d %d\\n\",i,j,dp[1][i][j]);\n    \t\tans+=dp[1][i][j];\n    \t\tif(ans>=mod)\n    \t\t\tans-=mod;\n    \t}\n    }\n    printf(\"%d\\n\",ans);\n    return 0;\n}",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "855",
    "index": "D",
    "title": "Rowena Ravenclaw's Diadem",
    "statement": "Harry, upon inquiring Helena Ravenclaw's ghost, came to know that she told Tom Riddle or You-know-who about Rowena Ravenclaw's diadem and that he stole it from her.\n\nHarry thought that Riddle would have assumed that he was the only one to discover the Room of Requirement and thus, would have hidden it there. So Harry is trying to get inside the Room of Requirement to destroy the diadem as he knows that it is a horcrux.\n\nBut he has to answer a puzzle in order to enter the room. He is given $n$ objects, numbered from $1$ to $n$. Some of the objects have a parent object, that has a lesser number. Formally, object $i$ may have a parent object $parent_{i}$ such that $parent_{i} < i$.\n\nThere is also a type associated with each parent relation, it can be either of type $1$ or type $2$. Type $1$ relation means that the child object is like a special case of the parent object. Type $2$ relation means that the second object is \\textbf{always} a part of the first object and all its special cases.\n\nNote that if an object $b$ is a special case of object $a$, and $c$ is a special case of object $b$, then $c$ is considered to be a special case of object $a$ as well. The same holds for parts: if object $b$ is a part of $a$, and object $c$ is a part of $b$, then we say that object $c$ is a part of $a$. Also note, that if object $b$ is a part of $a$, and object $c$ is a special case of $a$, then $b$ is a part of $c$ as well.\n\nAn object is considered to be neither a part of itself nor a special case of itself.\n\nNow, Harry has to answer two type of queries:\n\n- 1 u v: he needs to tell if object $v$ is a special case of object $u$.\n- 2 u v: he needs to tell if object $v$ is a part of object $u$.",
    "tutorial": "In this problem, the relations \"is a part of\" and \"is a special case of\" were transitive. And also, if some object \"a\" had \"b\" as its special case and \"c\" as its part, \"c\" was also a part of \"b\". Now, when we need to process the queries, we use the concept of lowest common ancestor (lca). For query $1 u v$, answer will be \"YES\" iff $u  \\neq  v$ (as u is not special case of itself) and $lca(u, v) = u$ and all the relations from $u$ to $v$ are of type $0$ (is a special case of) For query $2 u v$, answer will be \"YES\" iff the following conditions hold: If $w = lca(u, v)$, path from $w$ to $u$ has only edges of type $0$ (is a special case of) and those from $w$ to $v$ has only edges of type $1$ (is a part of). Also, $w  \\neq  v$. Expected time complexity: $O((n + q) \\cdot log(n))$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define sd(x) scanf(\"%d\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define ss(x) scanf(\"%s\",x)\n#define mod 1000000007\n#define bitcount __builtin_popcountll\n#define ll long long\n#define pb push_back\n#define pi pair<int,int>\n#define pii pair<pi,int>\n#define mp make_pair\nvector<int>v[100005],v2[100005];\nint inherit[100005],comp[100005],parent[100005][25],height[100005];\nint parr[100005];\nint findpar(int node)\n{\n\treturn parr[node]==node ? node : parr[node]=findpar(parr[node]);\n}\nvoid dfs(int node, int par, int inh, int com)\n{\n\tparent[node][0]=par;\n\tinherit[node]=inh;\n\tcomp[node]=com;\n\theight[node]=height[par]+1;\n\tfor(int i=1;i<=20;i++)\n\t{\n\t\tparent[node][i]=parent[parent[node][i-1]][i-1];\n\t}\n\tfor(int i=0;i<v[node].size();i++)\n\t{\n\t\tif(v[node][i]==par)\n\t\t\tcontinue;\n\t\tif(v2[node][i]==0)\n\t\t\tdfs(v[node][i],node,inh+1,com);\n\t\telse\n\t\t\tdfs(v[node][i],node,inh,com+1);\n\t}\n}\nint findlca(int u, int v)\n{\n\tif(height[u]>height[v])\n\t\tswap(u,v);\n\tfor(int i=20;i>=0;i--)\n\t{\n\t\tif(height[parent[v][i]]>=height[u])\n\t\t{\n\t\t\tv=parent[v][i];\n\t\t}\n\t}\n\tif(u!=v)\n\t{\n\t\tfor(int i=20;i>=0;i--)\n\t\t{\n\t\t\tif(parent[u][i]!=parent[v][i])\n\t\t\t{\n\t\t\t\tu=parent[u][i];\n\t\t\t\tv=parent[v][i];\n\t\t\t}\n\t\t}\n\t\tu=parent[u][0];\n\t\tv=parent[v][0];\n\t}\n\treturn u;\n}\nint main()\n{\n\tint i,j,k;\n\tint n,q;\n\tsd(n);\n\tfor(i=1;i<=n;i++)\n\t\tparr[i]=i;\n\tfor(i=1;i<=n;i++)\n\t{\n\t\tsd(j);\n\t\tsd(k);\n\t\tif(j==-1 && k==-1)\n\t\t\tcontinue;\n\t\tv[i].pb(j);\n\t\tv[j].pb(i);\n\t\tv2[i].pb(k);\n\t\tv2[j].pb(k);\n\t\tint x=findpar(i);\n\t\tint y=findpar(j);\n\t\tif(x!=y)\n\t\t\tparr[x]=y;\n\t}\n\tfor(i=1;i<=n;i++)\n\t{\n\t\tif(parent[i][0]==0)\n\t\t{\n\t\t\tdfs(i,i,0,0);\n\t\t}\n\t}\n\tsd(q);\n\twhile(q--)\n\t{\n\t\tsd(i);\n\t\tsd(j);\n\t\tsd(k);\n\t\tint x=findpar(j);\n\t\tint y=findpar(k);\n\t\tif(x!=y)\n\t\t{\n\t\t\tprintf(\"NO\\n\");\n\t\t\tcontinue;\n\t\t}\n\t\tx=findlca(j,k);\n\t\tif(i==1)\n\t\t{\n\t\t\tif(x!=j || comp[k]-comp[x]!=0 || j==k)\n\t\t\t{\n\t\t\t\tprintf(\"NO\\n\");\n\t\t\t}\n\t\t\telse\n\t\t\t\tprintf(\"YES\\n\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(inherit[k]-inherit[x]!=0 || comp[j]-comp[x]!=0 || x==k)\n\t\t\t\tprintf(\"NO\\n\");\n\t\t\telse\n\t\t\t\tprintf(\"YES\\n\");\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "855",
    "index": "E",
    "title": "Salazar Slytherin's Locket",
    "statement": "Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher.\n\nHarry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers $l$ and $r$ (both inclusive).\n\nHarry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base $b$, all the digits from $0$ to $b - 1$ appear even number of times in its representation without any leading zeros.\n\nYou have to answer $q$ queries to unlock the office. Each query has three integers $b_{i}$, $l_{i}$ and $r_{i}$, the base and the range for which you have to find the count of magic numbers.",
    "tutorial": "This problem can be solved using precomputation of dp table $dp[base][mask][len]$. This stores the number of integers in base $b$ and length $len$ that forms the given $mask$ in their representation. The $mask$ is defined as having $i - th$ bit as $1$, if the digit $i - 1$ occurs odd number of times in the representation. Using this precomputed $dp$ array, we can easily calculate the answer for the queries, by converting $l - 1$ and $r$ to the given base $b$, then adding the total integers less than equal to $r$ with $mask = 0$ and subtracting those less than $l$ with $mask = 0$. Now, to find the number of integers less than equal to $l - 1$ with $mask = 0$, we first add all the integers with $mask = 0$ who have length less than length of $l - 1$ in base $b$ representation. If length of $l - 1$ in base $b$ is $l_{b}$, this value can be calculated as $\\textstyle\\sum_{1<i<l a}d p[b][b](i)-d p[b][1][i-1]$. The second term is subtracted to take into account the trailing zeros. Now, we need to calculate the number of integers with length$= l_{b}$ and value$ \\le  l - 1$ and $mask = 0$. Let the number $l - 1$ in base $b$ representation be $l_{0}, l_{1}... l_{lb}$. Then, if we fix the first digit of our answer, $x$ from $0$ to $l_{0} - 1$, we can simply calculate the mask for remaining digits we need as $2^{x}$ and thus adding $dp[b][2^{x}][len - 1]$ to answer. Now, if we fix the first digit as $l_{0}$ only, we can simply perform the same operation for the second digit, selecting value of second digit, $y$ from $0$ to $l_{1} - 1$, and thus adding $d p[b](l e n-2][2^{x}\\oplus2^{y}]$ to answer. And, we can move forward to rest of the digits in the same way. The overall complexity of the solution will be $O(b\\cdot2^{b}\\cdot\\log_{b}10^{18}+q\\cdot b\\cdot\\log_{b}r)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define sd(x) scanf(\"%lld\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define ss(x) scanf(\"%s\",x)\n#define ll long long\n#define mod 1000000007\n#define bitcount    __builtin_popcountll\n#define pb push_back\n#define fi first\n#define se second\n#define mp make_pair\n#define pi pair<int,int>\nll dp[11][2][1030][70];\nll len[12],a[100];\nll f(ll b,ll in,ll m,ll pos)\n{\n\tif(dp[b][in][m][pos]!=-1)\n\t\treturn dp[b][in][m][pos];\n\tif(pos==0)\n\t{\n\t\tif(in!=0&&m==0)\n\t\t\treturn dp[b][in][m][pos]=1;\n\t\telse\n\t\t\treturn dp[b][in][m][pos]=0;\n\t\treturn dp[b][in][m][pos];\n\t}\n\tll j=0;\n\tif(in==0)\n\t\tj+=f(b,0,m,pos-1);\n\telse\n\t\tj+=f(b,1,(m^1),pos-1);\n\tfor(ll i=1;i<b;i++)\n\t\tj+=f(b,1,(m^(1<<i)),pos-1);\n\tdp[b][in][m][pos]=j;\n\treturn j;\n}\nint main()\n{\n    //freopen(\"in.txt\",\"r\",stdin);\n    //freopen(\"out.txt\",\"w\",stdout);\n    ll n,i,j,k,in;\n    ll ans,l,r,m,q,b;\n    k=1e18;\n    memset(dp,-1,sizeof dp);\n    for(i=2;i<=10;i++)\n    {\n    \tlen[i]=1;\n    \tj=i;\n    \twhile(j<k)\n    \t{\n    \t\tlen[i]++;\n    \t\tj*=i;\n    \t}\n    \tf(i,0,0,len[i]+1);\n    }\n    sd(q);\n    while(q--)\n    {\n    \tsd(b);\n    \tsd(l);\n    \tsd(r);\n    \tans=0;\n    \tl--;\n    \tif(l)\n    \t{\n    \t\tj=l;\n    \t\ti=0;\n    \t\twhile(j)\n    \t\t{\n    \t\t\ta[i]=j%b;\n    \t\t\tj/=b;\n    \t\t\ti++;\n    \t\t}\n    \t\tm=0;\n    \t\tin=0;\n    \t\tfor(j=i-1;j>=0;j--)\n    \t\t{\n    \t\t\tfor(k=0;k<a[j];k++)\n    \t\t\t{\n    \t\t\t\tif(k!=0)\n    \t\t\t\t\tin=1;\n    \t\t\t\tif(in==0)\n    \t\t\t\t\tans-=dp[b][0][m][j];\n    \t\t\t\telse\n    \t\t\t\t\tans-=dp[b][1][(m^(1<<k))][j];\n    \t\t\t}\n    \t\t\tif(in|a[j])\n    \t\t\t{\n    \t\t\t\tin=1;\n    \t\t\t\tm=(m^(1<<a[j]));\n    \t\t\t}\n    \t\t}\n    \t\tans-=dp[b][in][m][0];\n    \t}\n    \tj=r;\n    \ti=0;\n    \twhile(j)\n    \t{\n    \t\ta[i]=j%b;\n    \t\tj/=b;\n    \t\ti++;\n    \t}\n    \tin=0;\n    \tm=0;\n\t\tfor(j=i-1;j>=0;j--)\n\t\t{\n\t\t\tfor(k=0;k<a[j];k++)\n\t\t\t{\n\t\t\t\tif(k!=0)\n\t\t\t\t\tin=1;\n\t\t\t\tif(in==0)\n\t\t\t\t\tans+=dp[b][0][m][j];\n\t\t\t\telse\n\t\t\t\t\tans+=dp[b][1][(m^(1<<k))][j];\n\t\t\t}\n\t\t\tif(in|a[j])\n\t\t\t{\n\t\t\t\tin=1;\n\t\t\t\tm=(m^(1<<a[j]));\n\t\t\t}\n\t\t}\n\t\tans+=dp[b][in][m][0];\n\t\tprintf(\"%lld\\n\",ans);\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "855",
    "index": "F",
    "title": "Nagini",
    "statement": "Nagini, being a horcrux You-know-who created with the murder of Bertha Jorkins, has accumulated its army of snakes and is launching an attack on Hogwarts school.\n\nHogwarts' entrance can be imagined as a straight line (x-axis) from $1$ to $10^{5}$. Nagini is launching various snakes at the Hogwarts entrance. Each snake lands parallel to the entrance, covering a segment at a distance $k$ from $x = l$ to $x = r$. Formally, each snake can be imagined as being a line segment between points $(l, k)$ and $(r, k)$. Note that $k$ can be both positive and negative, but not $0$.\n\nLet, at some $x$-coordinate $x = i$, there be snakes at point $(i, y_{1})$ and point $(i, y_{2})$, such that $y_{1} > 0$ and $y_{2} < 0$. Then, if for any point $(i, y_{3})$ containing a snake such that $y_{3} > 0$, $y_{1} ≤ y_{3}$ holds and for any point $(i, y_{4})$ containing a snake such that $y_{4} < 0$, $|y_{2}| ≤ |y_{4}|$ holds, then the danger value at coordinate $x = i$ is $y_{1} + |y_{2}|$. If no such $y_{1}$ and $y_{2}$ exist, danger value is $0$.\n\nHarry wants to calculate the danger value of various segments of the Hogwarts entrance. Danger value for a segment $[l, r)$ of the entrance can be calculated by taking the sum of danger values for each integer $x$-coordinate present in the segment.\n\nFormally, you have to implement two types of queries:\n\n- 1 l r k: a snake is added parallel to entrance from $x = l$ to $x = r$ at y-coordinate $y = k$ ($l$ inclusive, $r$ exclusive).\n- 2 l r: you have to calculate the danger value of segment $l$ to $r$ ($l$ inclusive, $r$ exclusive).",
    "tutorial": "This problem can be solved by using the concept of square root decomposition. Let us divide the total range of x-axis, that is, from $1$ to $10^{5}$ in $\\sqrt{10^{5}}$. Then, blockSize = $\\sqrt{10^{5}}$, and number of blocks, $n_{b}$ = $10^{5} / blockSize$. Now, we maintain the following structures: An array $ans$ that stores the answer for each block. Two values $upper$ and $lower$ for each block. $upper$ stores the closest line segment with $y > 0$ that covers the complete block. Similarly $lower$ stores the closest line with $y < 0$ that covers the complete block. Maps $low$ and $up$ for each block. $up$ maps for each height $y > 0$, the number of x-coordinates with its minimum height as $y$. Similarly $low$ maps for each height $y < 0$, the number of x-coordinates with its maximum height as $y$. Also, note that this map stores the information only for those x-coordinates which have atleast one line segment on both sides of axis. Maps $vnotup$ and $vnotdown$ for each block. These are similar to maps $low$ and $up$ except that these stores value for those coordinates that do not have line on one of the sides. That is, $vnotup$ maps the height $y$ to its count for $y < 0$ such that at those coordinates, there do not exists any line for $y > 0$. Value $notboth$ for each block, this stores the number of x-coordinates that do not have line segments on any of the two sides of axis. Arrays $minup$ and $mindown$ for each value from $1$ to $10^{5}$. $minup$ stores the minimum value for $y$ such that $y > 0$ and there is a snake at that point and that snake does not cover the complete block. Similar value for $y < 0$ is stored by $mindown$ Now we have to maintain these structure throughout the update operation. To do so, we divide the update operations into two halves, the update for initial and final blocks which are only partially covered by a line, and the update for complete block. For now, let us assume that the update is for some $y > 0$. For $y < 0$, a similar approach can be done: Updating the initial and final blocks: Iterate through every x-coordinate in the range. There can be four cases: If all the values, $minup$, $mindown$ for that coordinate and value $lower$ and $upper$ for that block are inf, this means that this is the first time a line is coming at this coordinate. Reduce $notboth$ of the block by $1$ and update the map $vnotdown$. Else if $minup$ and $upper$ are inf, this means that for this x-coordinate there is a line below axis, but not above. Update $vnotup$, $up$, $low$ and $ans$ accordingly. Else if $mindown$ and $lower$ are inf, this means that there is no line with $y < 0$ at this x-coordinate. Just update $vnotdown$. Else if both side lines are there, just update $ans$ and $up$. Also, update the value of $minup$ for each coordinate. Updating the complete block Remove all the elements from $vnotup$ and update the $up$, $low$ maps and $ans$ for that block accordingly. Put $notboth$ as $0$ and update the map $vnotdown$ acccordingly. Remove elements from $vnotdown$ which are greater than this value of $y$ and update it again. Finally update the $up$ array and value of $ans$ for that block. Also update the value of $upper$. For answering the queries, you will need to answer the half-block(initial and final block) queries by iterating through each x-coordinate. For answering full-block queries, just return the $ans$ for that block. If we take $n = 10^{5}$, the expected complexity of the solution is $O(q\\cdot{\\sqrt{n}}\\cdot\\log n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define sd(x) scanf(\"%d\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define ss(x) scanf(\"%s\",x)\n#define mod 1000000007\n#define bitcount __builtin_popcountll\n#define ll long long\n#define pb push_back\n#define fi first\n#define se second\n#define pi pair<int,int>\n#define pii pair<pi,int>\n#define mp make_pair\nll ans[1000];\nint upper[1000],lower[1000];\nint block;\nmap <int,int> low[1000],up[1000];\nmap <int,int> vnotup[1000],vnotdown[1000];\nint notboth[1000];\nint minup[100005],mindown[100005];\nvoid updateup(int i,int l,int r,int val)\n{\n\tif(upper[i]<=val)\n\t\treturn;\n\t//map<int,int> m;\n\tmap<int,int> :: iterator it;\n\t//m.clear();\n\tfor(int j=l;j<=r;j++)\n\t{\n\t\tif(minup[j]>val)\n\t\t{\n\t\t\tif(minup[j]==mod&&mindown[j]==mod&&upper[i]==mod&&lower[i]==mod)\n\t\t\t{\n\t\t\t\tnotboth[i]--;\n\t\t\t\t//notdown[i]++;\n\t\t\t\tvnotdown[i][val]++;\n\t\t\t\t//notdownsum[i]+=val;\n\t\t\t}\n\t\t\telse if(minup[j]==mod&&upper[i]==mod)\n\t\t\t{\n\t\t\t\t//notup[i]--;\n\t\t\t\tint temp=min(lower[i],mindown[j]);\n\t\t\t\tvnotup[i][temp]--;\n\t\t\t\tif(vnotup[i][temp]==0)\n\t\t\t\t\tvnotup[i].erase(temp);\n\t\t\t\t//notupsum[i]-=min(lower[i],mindown[j]);\n\t\t\t\tup[i][val]++;\n\t\t\t\tlow[i][temp]++;\n\t\t\t\tans[i]+=val;\n\t\t\t\tans[i]+=min(lower[i],mindown[j]);\n\t\t\t}\n\t\t\telse if(mindown[j]==mod&&lower[i]==mod)\n\t\t\t{\n\t\t\t\tint temp=min(upper[i],minup[j]);\n\t\t\t\tvnotdown[i][temp]--;\n\t\t\t\tif(vnotdown[i][temp]==0)\n\t\t\t\t\tvnotdown[i].erase(temp);\n\t\t\t\tvnotdown[i][val]++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tans[i]+=val-min(upper[i],minup[j]);\n\t\t\t\tup[i][min(minup[j],upper[i])]--;\n\t\t\t\tup[i][val]++;\n\t\t\t}\n\t\t\tminup[j]=val;\n\t\t}\n\t}\n}\nvoid updatefullup(int i,int val)\n{\n\tif(val>=upper[i])\n\t\treturn;\n\tmap <int,int> :: iterator it; \n\tint n=up[i].size();\n\tn--;\n\tll sum=0;\n\tint len2=0;\n\tfor(it=vnotup[i].begin();it!=vnotup[i].end();it++)\n\t{\n\t\tans[i]+=1ll*(it->fi)*(it->se)+1ll*(it->se)*val;\n\t\tlen2+=it->se;\n\t\tlow[i][it->fi]+=it->se;\n\t}\n\tvnotup[i].clear();\n\tit=vnotdown[i].upper_bound(val);\n\tint temp=0;\n\tfor(it;it!=vnotdown[i].end();it++)\n\t{\n\t\ttemp+=it->se;\n\t}\n\tit=vnotdown[i].upper_bound(val);\n\tvnotdown[i].erase(it,vnotdown[i].end());\n\tvnotdown[i][val]+=temp+notboth[i];\n\tnotboth[i]=0;\n\tint len=0;\n\tit=up[i].upper_bound(val);\n\tfor(it;it!=up[i].end();it++)\n\t{\n\t\tsum+=1ll*(it->fi)*(it->se);\n\t\tlen+=it->se;\n\t}\n\tit=up[i].upper_bound(val);\n\tup[i].erase(it,up[i].end());\n\tans[i]+=1ll*len*val-sum;\n\tup[i][val]+=len+len2;\n\tupper[i]=val;\n}\nvoid updatedown(int i,int l,int r,int val)\n{\n\tif(lower[i]<=val)\n\t\treturn;\n\t//map<int,int> m;\n\tmap<int,int> :: iterator it;\n\t//m.clear();\n\tfor(int j=l;j<=r;j++)\n\t{\n\t\tif(mindown[j]>val)\n\t\t{\n\t\t\tif(mindown[j]==mod&&minup[j]==mod&&upper[i]==mod&&lower[i]==mod)\n\t\t\t{\n\t\t\t\tnotboth[i]--;\n\t\t\t\t//notup[i]++;\n\t\t\t\t//notupsum[i]+=val;\n\t\t\t\tvnotup[i][val]++;\n\t\t\t}\n\t\t\telse if(mindown[j]==mod&&lower[i]==mod)\n\t\t\t{\n\t\t\t\t//notdown[i]--;\n\t\t\t\tint temp=min(upper[i],minup[j]);\n\t\t\t\tvnotdown[i][temp]--;\n\t\t\t\tif(vnotdown[i][temp]==0)\n\t\t\t\t\tvnotdown[i].erase(temp);\n\t\t\t\tlow[i][val]++;\n\t\t\t\tup[i][temp]++;\n\t\t\t\t//notdownsum[i]-=min(upper[i],minup[j]);\n\t\t\t\tans[i]+=val;\n\t\t\t\tans[i]+=min(upper[i],minup[j]);\n\t\t\t}\n\t\t\telse if(minup[j]==mod&&upper[i]==mod)\n\t\t\t{\n\t\t\t\tint temp=min(lower[i],mindown[j]);\n\t\t\t\tvnotup[i][temp]--;\n\t\t\t\tif(vnotup[i][temp]==0)\n\t\t\t\t\tvnotup[i].erase(temp);\n\t\t\t\tvnotup[i][val]++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tans[i]+=val-min(lower[i],mindown[j]);\n\t\t\t\tlow[i][min(mindown[j],lower[i])]--;\n\t\t\t\tlow[i][val]++;\n\t\t\t}\n\t\t\tmindown[j]=val;\n\t\t}\n\t}\n}\nvoid updatefulldown(int i,int val)\n{\n\tif(val>=lower[i])\n\t\treturn;\n\tmap <int,int> :: iterator it; \n\tint n=low[i].size();\n\tn--;\n\tll sum=0;\n\tint len2=0;\n\tfor(it=vnotdown[i].begin();it!=vnotdown[i].end();it++)\n\t{\n\t\tans[i]+=1ll*(it->fi)*(it->se)+1ll*(it->se)*val;\n\t\tlen2+=it->se;\n\t\tup[i][it->fi]+=it->se;\n\t}\n\tvnotdown[i].clear();\n\tit=vnotup[i].upper_bound(val);\n\tint temp=0;\n\tfor(it;it!=vnotup[i].end();it++)\n\t{\n\t\ttemp+=it->se;\n\t}\n\tit=vnotup[i].upper_bound(val);\n\tvnotup[i].erase(it,vnotup[i].end());\n\tvnotup[i][val]+=temp+notboth[i];\n\tnotboth[i]=0;\n\tint len=0;\n\tit=low[i].upper_bound(val);\n\tfor(it;it!=low[i].end();it++)\n\t{\n\t\tsum+=1ll*(it->fi)*(it->se);\n\t\tlen+=it->se;\n\t}\n\tit=low[i].upper_bound(val);\n\tlow[i].erase(it,low[i].end());\n\tans[i]+=1ll*len*val-sum;\n\tlow[i][val]+=len+len2;\n\tlower[i]=val;\n}\nll query(int i,int l,int r)\n{\n\tll sum=0;\n\tfor(int j=l;j<=r;j++)\n\t{\n\t\tif(min(upper[i],minup[j])<mod&&min(lower[i],mindown[j])<mod)\n\t\t\tsum+=min(upper[i],minup[j])+min(lower[i],mindown[j]);\n\t}\n\treturn sum;\n}\nll queryfull(int i)\n{\n\treturn ans[i];\n}\nint main()\n{\n\tint i,j,k,q,n,t,l,r,val,block;\n\tll s;\n\tn=100000;\n\tfor(i=0;i<1000;i++)\n\t\tlower[i]=upper[i]=mod;\n\tfor(i=0;i<=100000;i++)\n\t\tminup[i]=mindown[i]=mod;\n\tblock=300;\n\tfor(i=1;i<=n;i++)\n\t{\n\t\tj=i/block;\n\t\tnotboth[j]++;\n\t}\n\tsd(q);\n\twhile(q--)\n\t{\n\t\tsd(t);\n\t\tsd(l);\n\t\tsd(r);\n\t\tr--;\n\t\tif(t==1)\n\t\t{\n\t\t\tsd(val);\n\t\t\ti=l/block;\n\t\t\tj=r/block;\n\t\t\tif(val>0)\n\t\t\t{\n\t\t\t\tif(i==j)\n\t\t\t\t\tupdateup(j,l,r,val);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tupdateup(i,l,(i+1)*block-1,val);\n\t\t\t\t\ti++;\n\t\t\t\t\twhile(i<j)\n\t\t\t\t\t{\n\t\t\t\t\t\t// updateup(i,i*block,(i+1)*block-1,val);\n\t\t\t\t\t\tupdatefullup(i,val);\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tupdateup(j,j*block,r,val);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(i==j)\n\t\t\t\t\tupdatedown(j,l,r,-val);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tupdatedown(i,l,(i+1)*block-1,-val);\n\t\t\t\t\ti++;\n\t\t\t\t\twhile(i<j)\n\t\t\t\t\t{\n\t\t\t\t\t\t// updatedown(i,i*block,(i+1)*block-1,-val);\n\t\t\t\t\t\tupdatefulldown(i,-val);\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\tupdatedown(j,j*block,r,-val);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\ts=0;\n\t\t\ti=l/block;\n\t\t\tj=r/block;\n\t\t\tif(i==j)\n\t\t\t\ts=query(j,l,r);\n\t\t\telse\n\t\t\t{\n\t\t\t\ts=query(i,l,(i+1)*block-1);\n\t\t\t\ti++;\n\t\t\t\twhile(i<j)\n\t\t\t\t{\n\t\t\t\t\t//s+=query(i,i*block,(i+1)*block-1);\n\t\t\t\t\ts+=queryfull(i);\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\ts+=query(j,j*block,r);\n\t\t\t}\n\t\t\tprintf(\"%lld\\n\",s);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "855",
    "index": "G",
    "title": "Harry Vs Voldemort",
    "statement": "After destroying all of Voldemort's Horcruxes, Harry and Voldemort are up for the final battle. They each cast spells from their wands and the spells collide.\n\nThe battle scene is Hogwarts, which can be represented in the form of a tree. There are, in total, $n$ places in Hogwarts joined using $n - 1$ undirected roads.\n\nRon, who was viewing this battle between Harry and Voldemort, wondered how many triplets of places $(u, v, w)$ are there such that if Harry is standing at place $u$ and Voldemort is standing at place $v$, their spells collide at a place $w$. This is possible for a triplet only when $u$, $v$ and $w$ are distinct, and there exist paths from $u$ to $w$ and from $v$ to $w$ which do not pass through the same roads.\n\nNow, due to the battle havoc, new paths are being added all the time. You have to tell Ron the answer after each addition.\n\nFormally, you are given a tree with $n$ vertices and $n - 1$ edges. $q$ new edges are being added between the nodes of the tree. After each addition you need to tell the number of triplets $(u, v, w)$ such that $u$, $v$ and $w$ are distinct and there exist two paths, one between $u$ and $w$, another between $v$ and $w$ such that these paths do not have an edge in common.",
    "tutorial": "At first let's solve the problem for the initial tree. You can use dynamic programming. The second part of the problem was to realize that we need to count the triple $(u, v, w)$ if and only if the following condition holds: $w$ is in a edge-2-connectivity component that is on the path from the edge-2-connectivity component of $u$ and the edge-2-connectivity of $v$. When an edge is added, it compresses all edge-2-connectivity components on the path between its ends. We can list all these components and then merge them in $O(number of the components)$ time, because once we list all these components, they disappear. In other words, each component is listed at most once through the entire process, and the total number of components is $O(n)$. How do we recalculate the answer given the components we need to merge into a single one? It can be done directly considering all cases of which of $u$, $v$ and $w$ are in this new component. The only tough idea may be that you need to, for each component, keep the number of pairs $(u, v)$ such that $u$ and $v$ are not in this component, and edges (bridges) towards $u$ and $v$ from this component are different. For more details about case-work see the code below.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n\n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nconst int maxn = 200005;\n\nstruct tpath\n{\n    int rep, sz;\n    ll ansmiddle;\n    int edgeleft, edgeright;\n};\n\nint p[maxn], s[maxn];\nint sz[maxn], down[maxn], up[maxn], top[maxn];\nvector<tpath> path, path2;\nvector<int> gr[maxn];\nll dp1[maxn], dp2[maxn], ansmiddle[maxn];\nint n, m;\nll answer;\nint tin[maxn], tout[maxn];\nint timer;\n\ninline int find(int a)\n{\n    return (a == p[a] ? a : p[a] = find(p[a]));\n}\n\ninline bool isparent(int a, int b)\n{\n    return tin[a] <= tin[b] && tout[a] >= tin[b];\n}\n\nvoid unite(int a, int b)\n{\n    a = find(a);\n    b = find(b);\n    if (a == b) return;\n    if (s[a] > s[b]) swap(a, b);\n    p[a] = b;\n    if (s[a] == s[b]) s[b]++;\n    if (tin[top[a]] < tin[top[b]])\n    {\n        sz[top[a]] += sz[top[b]];\n        top[b] = top[a];\n    } else\n    {\n        sz[top[b]] += sz[top[a]];\n    }\n}\n\nvoid findpath(int a, int b)\n{\n    a = top[find(a)];\n    b = top[find(b)];\n//     cout << \"findpath \" << a << ' ' << b << endl;\n    int lastdowna = 0;\n    while (!isparent(a, b))\n    {\n        path.pb({a, sz[a], ansmiddle[a], lastdowna, n - down[a]});\n        lastdowna = down[a];\n        a = top[find(up[a])];\n    }\n    path2.clear();\n    int lastdownb = 0;\n    while (a != b)\n    {\n        path2.pb({b, sz[b], ansmiddle[b], n - down[b], lastdownb});\n        lastdownb = down[b];\n        b = top[find(up[b])];\n    }\n    path.pb({a, sz[a], ansmiddle[a], lastdowna, lastdownb});\n    reverse(all(path2));\n    for (auto t : path2) path.pb(t);\n}\n\nvoid addedge(int a, int b)\n{\n    if (find(a) == find(b)) return;\n    path.clear();\n    findpath(a, b);\n    \n//     cout << \"addedge \" << a << ' ' << b << endl;\n//     for (auto t : path) cout << \"(\" << t.rep << ' ' << t.sz << ' ' << t.ansmiddle << ' ' << t.edgeleft << ' ' << t.edgeright << \")\" << endl;\n    \n    // 3\n    ll cnt0 = 1;\n    ll cnt1 = 0;\n    ll cnt2 = 0;\n    for (auto t : path)\n    {\n        answer -= t.sz * cnt2 * 2 + (ll)t.sz * (t.sz - 1) * cnt1 * 2 + (ll)t.sz * (t.sz - 1) * (t.sz - 2);\n        cnt2 += t.sz * cnt1 + (ll)t.sz * (t.sz - 1) * cnt0;\n        cnt1 += t.sz * cnt0;\n    }\n    ll sum = cnt1;\n    answer += ((ll)sum * (sum - 1) * (sum - 2));\n    \n//     cout << \"after 3: \" << answer << endl;\n    \n    // 2\n    cnt1 = 0;\n    for (auto t : path)\n    {\n        answer += cnt1 * (t.edgeleft - cnt1) * t.sz * 2;\n        cnt1 += t.sz;\n    }\n    cnt1 = 0;\n    for (int i = (int)path.size() - 1; i >= 0; i--)\n    {\n        auto &t = path[i];\n        answer += cnt1 * (t.edgeright - cnt1) * t.sz * 2;\n        cnt1 += t.sz;\n    }\n\n//     cout << \"after 2: \" << answer << endl;    \n    \n    // 1\n    cnt1 = 0;\n    cnt2 = 0;\n    for (auto t : path)\n    {\n        answer += cnt2 * t.sz * 2;\n        cnt2 += (n - t.edgeright - t.edgeleft - t.sz) * cnt1;\n        cnt1 += n - t.edgeright - t.edgeleft - t.sz;\n    }\n    cnt1 = 0;\n    cnt2 = 0;\n    for (int i = (int)path.size() - 1; i >= 0; i--)\n    {\n        auto &t = path[i];\n        answer += cnt2 * t.sz * 2;\n        cnt2 += (n - t.edgeleft - t.edgeright - t.sz) * cnt1;\n        cnt1 += n - t.edgeleft - t.edgeright - t.sz;\n    }\n//     cout << \"after 1 old: \" << answer << endl;\n    ll ttldown1 = 0;\n    ll ttldown2 = 0;\n    for (auto t : path)\n    {\n        ll curdown = n - t.edgeleft - t.edgeright - t.sz;\n        ll curdown2 = t.ansmiddle - curdown * (t.edgeleft + t.edgeright) * 2 - (ll)t.edgeleft * t.edgeright * 2;\n        answer += curdown2 * (sum - t.sz);\n        ttldown2 = ttldown2 + curdown2 + ttldown1 * curdown * 2;\n        ttldown1 += curdown;\n    }\n\n//     cout << \"after 1: \" << answer << endl;\n    \n    for (int i = 1; i < (int)path.size(); i++) unite(path[i - 1].rep, path[i].rep);\n    ansmiddle[top[find(path[0].rep)]] = ttldown2;\n}\n\nint go(int cur, int pr)\n{\n    down[cur] = 1;\n    up[cur] = pr;\n    dp1[cur] = 0;\n    ansmiddle[cur] = 0;\n    tin[cur] = timer++;\n    for (auto t : gr[cur]) if (t != pr)\n    {\n        down[cur] += go(t, cur);\n        answer += (ll)dp1[t] * dp1[cur] * 2;\n        answer += (ll)dp1[t] * dp2[cur] * 2 + dp2[t] * dp1[cur] * 2;\n        ansmiddle[cur] += (ll)dp1[t] * dp1[cur] * 2;\n        answer += dp2[t] * 2;\n        dp2[cur] += dp2[t];\n        dp1[cur] += dp1[t];\n    }\n    ansmiddle[cur] += (ll)(n - down[cur]) * dp1[cur] * 2;\n    dp2[cur] += dp1[cur];\n    dp1[cur] += 1;\n    tout[cur] = timer - 1;\n//     cout << \"exit \" << cur << ' ' << answer << ' ' << dp1[cur] << ' ' << dp2[cur] << endl;\n    return down[cur];\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n - 1; i++)\n    {\n        int a, b;\n        scanf(\"%d%d\", &a, &b);\n        a--, b--;\n        gr[a].pb(b);\n        gr[b].pb(a);\n    }\n    go(0, -1);\n    for (int i = 0; i < n; i++)\n    {\n        p[i] = i;\n        s[i] = 0;\n        top[i] = i;\n        sz[i] = 1;\n    }\n    printf(\"%lld\\n\", answer);\n    scanf(\"%d\", &m);\n    for (int i = 0; i < m; i++)\n    {\n        int a, b;\n        scanf(\"%d%d\", &a, &b);\n        a--, b--;\n        addedge(a, b);\n        printf(\"%lld\\n\", answer);\n    }\n    \n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "856",
    "index": "A",
    "title": "Set Theory",
    "statement": "Masha and Grisha like studying sets of positive integers.\n\nOne day Grisha has written a set $A$ containing $n$ different integers $a_{i}$ on a blackboard. Now he asks Masha to create a set $B$ containing $n$ different integers $b_{j}$ such that all $n^{2}$ integers that can be obtained by summing up $a_{i}$ and $b_{j}$ for all possible pairs of $i$ and $j$ are different.\n\nBoth Masha and Grisha don't like big numbers, so all numbers in $A$ are from $1$ to $10^{6}$, and all numbers in $B$ must also be in the same range.\n\nHelp Masha to create the set $B$ that satisfies Grisha's requirement.",
    "tutorial": "First let us prove that the answer is always YES. Let us iterate over $b_{j}$ and check if summing it up with all $a_{i}$ values don't result in values that we already have. If no conflict is found, add the corresponding $b_{j}$ to $B$. Let us give some estimate for the maximum element of $B$. The reason that we cannot include $b_{j2}$, to $B$ is the equality $a_{i1} + b_{j1} = a_{i2} + b_{j2}$, so $b_{j2} = b_{j1} - (a_{i2} - a_{i1})$. Each element of $B$ forbids $O(n^{2})$ values, so $max(B)$ is $O(n^{3})$. That means that the answer always exists for the given constraints. Now let us speed up the test that we can add a number to $B$. Let us use an array $bad$, that marks the numbers that we are not able to include to $B$. When trying the value $b_{j}$, we can add it to $B$ if it is not marked in $bad$. Now the numbers that are equal to $b_{j} + a_{i1} - a_{i2}$ are forbidden, let us mark them in $bad$. The complexity is $O(n^{3})$ for each test case.",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "856",
    "index": "B",
    "title": "Similar Words",
    "statement": "Let us call a non-empty sequence of lowercase English letters a \\underline{word}. \\underline{Prefix} of a word $x$ is a word $y$ that can be obtained from $x$ by removing zero or more last letters of $x$.\n\nLet us call two words \\underline{similar}, if one of them can be obtained from the other by removing its first letter.\n\nYou are given a set $S$ of words. Find the maximal possible size of set of non-empty words $X$ such that they satisfy the following:\n\n- each word of $X$ is prefix of some word from $S$;\n- $X$ has no similar words.",
    "tutorial": "Let us consider the following similarity graph: the vertices are the prefixes of the given words, two vertices are connected by an edge if the corresponding words are similar. Note that the set of vertices in this graph is the same as in the trie for the given words, so it doesn't exceed the sum of lengths of words. Let us prove that the resulting graph is a forest. If two words are similar, let us call the shorter one the parent of the longer one. Each vertex now has at most one parent, and there are no cycles, so the graph is a set of trees - a forest. Now the required set is the independent set in the constructed similarity graph, so we can use dynamic programming or greedy algorithm to find it. There are two ways to construct the similarity graph. Way 1. Hashes For each prefix find its hash, make a set of all hashes. Now for each prefix remove its first letter, check if such hash exists. If it does, connect them by an edge. Way 2. Aho-Corasick Let us build Aho-Corasick automaton for the given set of words. The vertices of the similarity graph are automaton vertices. An edge exists between two vertices if the suffix link from one of them goes to the other one, and their depths differ by exacly $1$.",
    "tags": [
      "dp",
      "hashing",
      "strings",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "856",
    "index": "C",
    "title": "Eleventh Birthday",
    "statement": "It is Borya's eleventh birthday, and he has got a great present: $n$ cards with numbers. The $i$-th card has the number $a_{i}$ written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers $1$, $31$, and $12$, and he puts them in a row in this order, he would get a number $13112$.\n\nHe is only 11, but he already knows that there are $n!$ ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because $13112 = 1192 × 11$, but if he puts the cards in the following order: $31$, $1$, $12$, he would get a number $31112$, it is not divisible by $11$, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.\n\nBorya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.\n\nHelp Borya, find the number of good ways to put the cards. This number can be large, so output it modulo $998244353$.",
    "tutorial": "Let us use divisibility rule for eleven. The number is divisible by eleven if the sum of digits at odd positions is equal to the sum of digits at even positions modulo 11. So for each number on a card there are only two parameters that we care about: the sign interchanging sum of its digits with digits at odd positions positive and digits at even position negative, and the parity of its digit count. Let us divide all cards to two groups: with even digit count and with odd digit count. Let us first put cards with numbers that have odd count of digits. Half of them (rounded up) will have their sign interchanging sum used as positive, other half as negative. Let us use dynamic programming to find the number of ways to sum them up to have a given sum modulo 11. The state includes the number of cards considered, the number of cards that are used as positive, and the current sum modulo 11. There are two transitions: take the current card as positive, and take it as negative. If there are no cards with odd digit count, no matter how you order even digit count cards the result modulo 11 is the same. So the answer is either $0$ or $n!$. In the other case each even digit count card can be used either as positive, or as negative, independent of the other cards. Use analogous dynamic programming to count the number of ways to get each possible sum modulo 11. Finally, combine results for even and odd digit count cards, getting the total sum modulo 11 equal to 0. Time complexity is $O(n^{2})$.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "856",
    "index": "D",
    "title": "Masha and Cactus",
    "statement": "Masha is fond of cacti. When she was a little girl, she decided to plant a tree. Now Masha wants to make a nice cactus out of her tree.\n\nRecall that \\underline{tree} is a connected undirected graph that has no cycles. \\underline{Cactus} is a connected undirected graph such that each vertex belongs to at most one cycle.\n\nMasha has some additional edges that she can add to a tree. For each edge she knows which vertices it would connect and the \\underline{beauty} of this edge. Masha can add some of these edges to the graph if the resulting graph is a cactus. \\underline{Beauty} of the resulting cactus is sum of beauties of all added edges.\n\nHelp Masha find out what maximum \\underline{beauty} of the resulting cactus she can achieve.",
    "tutorial": "Let us use dynamic programming for a rooted tree and some data structures. Denote as $f_{v}$ the maximal total beauty of edges that have both ends in a subtree of $v$, such that if we add them all to the subtree it would be a cactus. To calculate $f_{v}$ let us consider two cases: $v$ belongs to some cycle, or it doesn't. If it doesn't belong to any cycle, $f_{v}$ is equal to the sum of $f_{u}$ for all children $u$ of $v$. If $v$ belongs to a cycle, let us iterate over all possible cycles it can belong to. Such cycle is generated by an added edge $(x, y)$ such that $LCA(x, y) = v$. Try all possible such edges and then temporarily delete a path from $x$ to $y$ from a tree, calculate the sum of $f_{u}$ for all $u$ - roots of the isolated subtrees after the deletion of the path, and add it to the beauty of $(x, y)$. Now we have an $O(nm)$ solution. To speed up this solution let us use some data structures. First, we need to calculate $LCA$ for all endpoints of the given edges, any fast enough standard algorithm is fine. The second thing to do is to be able to calculate the sum of $f_{u}$ for all subtrees after removing the path. To do it, use the following additional values: $g_{u} = f_{p} - f_{u}$, where $p$ is the parent of $u$, and $s_{v} = sum(f_{u})$, where $u$ are the children of $v$. Now the sum of $f_{u}$ for all subtrees after $x - y$ path removal is the sum of the following values: $s_{x}$, $s_{y}$, $s_{v} - f_{x'} - f_{y'}$, the sum of $g_{i}$ for all $i$ at $[x, x')$, the sum of $g_{i}$ for all $i$ at $[y, y')$, where $x'$ is the child of $v$ that has $x$ in its subtree, and $y'$ is the child of $v$ that has $y$ in its subtree. We need some data structure for a tree that supports value change in a vertex and the sum for a path, range tree or Fenwick are fine. The complexity is $O((n + m)log(n))$.",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "856",
    "index": "E",
    "title": "Satellites",
    "statement": "Real Cosmic Communications is the largest telecommunication company on a far far away planet, located at the very edge of the universe. RCC launches communication satellites.\n\nThe planet is at the very edge of the universe, so its form is half of a circle. Its radius is $r$, the ends of its diameter are points $A$ and $B$. The line $AB$ is the edge of the universe, so one of the half-planes contains nothing, neither the planet, nor RCC satellites, nor anything else. Let us introduce coordinates in the following way: the origin is at the center of $AB$ segment, $OX$ axis coincides with line $AB$, the planet is completely in $y > 0$ half-plane.\n\nThe satellite can be in any point of the universe, except the planet points. Satellites are never located beyond the edge of the universe, nor on the edge itself — that is, they have coordinate $y > 0$. Satellite antennas are directed in such way that they cover the angle with the vertex in the satellite, and edges directed to points $A$ and $B$. Let us call this area the satellite \\underline{coverage area}.\n\nThe picture below shows coordinate system and coverage area of a satellite.\n\nWhen RCC was founded there were no satellites around the planet. Since then there have been several events of one of the following types:\n\n- 1 x y — launch the new satellite and put it to the point $(x, y)$. Satellites never move and stay at the point they were launched. Let us assign the number $i$ to the $i$-th satellite in order of launching, starting from one.\n- 2 i — remove satellite number $i$.\n- 3 i j — make an attempt to create a communication channel between satellites $i$ and $j$. To create a communication channel a repeater is required. It must not be located inside the planet, but can be located at its half-circle border, or above it. Repeater must be in coverage area of both satellites $i$ and $j$. To avoid signal interference, it must not be located in coverage area of any other satellite. Of course, the repeater must be within the universe, it must have a coordinate $y > 0$.\n\nFor each attempt to create a communication channel you must find out whether it is possible.\n\nSample test has the following satellites locations:",
    "tutorial": "Any point $X$ can be given by two angles $ \\alpha  = XAB$ and $ \\beta  = XBA$. The point $( \\alpha _{2},  \\beta _{2})$ is in coverage area of a satellite at the point $( \\alpha _{1},  \\beta _{1})$, if $ \\alpha _{2}  \\le   \\alpha _{1}$ and $ \\beta _{2}  \\le   \\beta _{1}$. Let two satellites that want to create a communication channel are at points $( \\alpha _{1},  \\beta _{1})$ and $( \\alpha _{2},  \\beta _{2})$. Repeater must be positioned in such point $( \\alpha _{0},  \\beta _{0})$, that $ \\alpha _{0}  \\le  min( \\alpha _{1},  \\alpha _{2})$ and $ \\beta _{0}  \\le  min( \\beta _{1},  \\beta _{2})$. To make it harder for it to get to other satellites coverage area, it is reasonable to maximize $ \\alpha _{0}$ and $ \\beta _{0}$: $ \\alpha _{0} = min( \\alpha _{1},  \\alpha _{2})$, $ \\beta _{0} = min( \\beta _{1},  \\beta _{2})$. Now let us move to a solution. Consider a query of type $3$: you are given two satellites at points $( \\alpha _{1},  \\beta _{1})$ and $( \\alpha _{2},  \\beta _{2})$. You must check whether the point $( \\alpha _{0},  \\beta _{0}) = (min( \\alpha _{1},  \\alpha _{2}), min( \\beta _{1},  \\beta _{2}))$ is not in the coverage area of any other satellite. That means that among all satellites with $ \\alpha   \\ge   \\alpha _{0}$ the maximum value of $ \\beta $ is smaller than $ \\beta _{0}$. The solution is offline, it considers all satellites from the test data and just turns them on and off. Sort all satellites by $ \\alpha $. Each moment for each satellite we store its $ \\beta $ if it exists, or $-  \\infty $ if it doesn't. Let us build a range tree for maximum, and update values as satellites come and go. The query is a range maximum. To avoid considering the satellites from the query, change their values to $-  \\infty $ before the query, and restore them afterwards. The next thing to do is to get rid of floating point numbers. Instead of calculating the angle values, we will only compare them using cross product. Similarly, instead of storing $ \\beta $ values in range tree, we will store indices and compare them by cross product in integers. The final remark: we need to check that the point $( \\alpha _{0},  \\beta _{0})$ is not inside the planet. The point is inside the planet, if the angle $AXB$ is obtuse, that can be checked by a scalar product of $XA$ and $XB$. The point $X$ can have non-integer coordinates, so we will not look for it, but will use colinear vectors from among those connecting satellite points to $A$ and $B$.",
    "tags": [],
    "rating": 3100
  },
  {
    "contest_id": "856",
    "index": "F",
    "title": "To Play or not to Play",
    "statement": "Vasya and Petya are playing an online game. As most online games, it has hero progress system that allows players to gain experience that make their heroes stronger. Of course, Vasya would like to get as many experience points as possible. After careful study of experience points allocation, he found out that if he plays the game alone, he gets one experience point each second. However, if two players are playing together, and their current experience values differ by at most $C$ points, they can boost their progress, and each of them gets 2 experience points each second.\n\nSince Vasya and Petya are middle school students, their parents don't allow them to play all the day around. Each of the friends has his own schedule: Vasya can only play during intervals $[a_{1};b_{1}], [a_{2};b_{2}], ..., [a_{n};b_{n}]$, and Petya can only play during intervals $[c_{1};d_{1}], [c_{2};d_{2}], ..., [c_{m};d_{m}]$. All time periods are given in seconds from the current moment. Vasya is good in math, so he has noticed that sometimes it can be profitable not to play alone, because experience difference could become too big, and progress would not be boosted even when played together.\n\nNow they would like to create such schedule of playing that Vasya's final experience was greatest possible. The current players experience is the same. Petya is not so concerned about his experience, so he is ready to cooperate and play when needed to maximize Vasya's experience.",
    "tutorial": "Let us introduce coordinates $y(x)$, where $x = exp_{1} - exp_{2}$, and $y = exp_{1}$ ($exp_{1}$, $exp_{2}$ - experience of the first and the second player, respectively). Let us proceed with time, and keep the set of possible states at this plane. It is a polygon. Lemma 1: in the optimal solution if at some moment both players can play the game simultaneously, they should do so. Now consider all moments of time, one after another. There are three transitions that modify the polygon: The first player can play for $t$ seconds. The new polygon is the Minkowski sum of the previous polygon and the degenerate polygon: segment with two vertices $(0, 0)$ and $(t, t)$. The second player can play for $t$ seconds. The new polygon is the Minkowski sum of the previous polygon and the segment with vertices $(0, 0)$ and $( - t, 0)$. Both players can play for $t$ seconds. Now all points with $x$-coordinates $[ - C;C]$ have $2t$ added to their $y$ coordinate, and other points have $t$ added to their $y$ coordinate. Let us now see how the polygon looks like. It is $x$-monotonous polygon (each line parallel to $y$-axis intersects it via a segment), the lower bound of this polygon is $y = 0$ if $x  \\le  0$ and $y = x$ if $x > 0$. Let us see how the upper bound of the polygon looks like. We want to prove that $y$-coordinate of the upper bound of the polygon doesn't decrease, and it only contains segments that move by vectors $( + 1, 0)$ and $( + 1, + 1)$. We attempt an induction, and the induction step is fine for the first two transitions. But the third transition can make the upper bound non-monotonous at a point $x = C$. To fix it, let us change the definition of our polygon. Instead of storing all possible reachable points, we will keep larger set, that contains the original set, and for each of its point we can get maximal experience for the first player not greater than what we could originally get. Lemma 2: if at some moment $t$ we take two points $P_{1} = (x_{1}, y_{1})$ and $P_{2} = (x_{2}, y_{2})$ such that $C  \\le  x_{1}  \\le  x_{2}$, and $y_{1}  \\ge  y_{2}$, and our player start training from those states, the maximal experience for point $P_{2}$ is not greater than for the point $P_{1}$. So we can expand our upper bound for $x$ from $[C; + inf)$ by a maximum value of the correct upper bound and $y = y(C)$. The similar proof works for a line $y = y(C) - (C - x)$ for $x$ in $( - inf;C]$. Now we have an upper bound as a polyline that contains $( + 1, 0)$ and $( + 1, + 1)$ segments. All is left to do is to modify the polyline using the described transitions. This can be done using some appropriate data structure, treap for example. The solution works in $O(nlog(n))$.",
    "tags": [
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "858",
    "index": "A",
    "title": "k-rounding",
    "statement": "For a given positive integer $n$ denote its $k$-rounding as the minimum positive integer $x$, such that $x$ ends with $k$ or more zeros in base $10$ and is divisible by $n$.\n\nFor example, $4$-rounding of $375$ is $375·80 = 30000$. $30000$ is the minimum integer such that it ends with $4$ or more zeros and is divisible by $375$.\n\nWrite a program that will perform the $k$-rounding of $n$.",
    "tutorial": "Notice that the number $x$ ends with $k$ or more zeros if the maximal power of $2$ that is a divisor of $x$ is at least $k$ and the maximal power of $5$ that is a divisor of $x$ is at least $k$. Let's calculate the maximal powers of $2$ and $5$ that are divisors of $n$. If any of the powers is less than $k$ then multiply the number by appropriate number of $2$ and $5$. The answer is also $LCM(n, 10^{k})$.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "858",
    "index": "B",
    "title": "Which floor?",
    "statement": "In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from $1$ from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from $1$.\n\nPolycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.\n\nGiven this information, is it possible to restore the exact floor for flat $n$?",
    "tutorial": "We will store our current answer in some variable $ans$. Initially it is -1. Let's iterate over the quantity of the flats on each floor (it will be from 1 to 100 inclusive). Let it be $cf$. Then we have to check that this quantity coincides with given input. If $\\textstyle\\left[{\\frac{k_{i}}{c f}}\\right]\\neq f_{i}$ for any $i\\in[1..m]$ then this quantity is incorrect. Now if $a n s\\neq-1\\ \\ \\&8\\times\\vert\\frac{n}{c f}\\vert\\neq a n s$ then we can't determine on which floor flat $n$ is situated. Print -1. In the other case set $\\begin{array}{r c l}{{a n s}}&{{=}}&{{\\left|{\\frac{n}{c f}}\\right|}}\\end{array}$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "858",
    "index": "C",
    "title": "Did you mean...",
    "statement": "Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.\n\nBeroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.\n\nFor example:\n\n- the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\";\n- the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\".\n\nWhen Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.\n\nImplement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.",
    "tutorial": "We will solve the problem greedily. Let's find the leftmost typo. It will be three consecutive characters $s_{i - 1}, s_{i}$ and $s_{i + 1}$ such that all of them are consonants and there are at least two diffirent letters. It is clear that we can cut this string after position $i$, because prefix will be correct and we will leave only one letter in the remaining part of the string. So each time we find the leftmost typo and cut out the prefix. Remember that after cutting the prefix you have to continue checking from index $i + 2$, not $i + 1$.",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "858",
    "index": "D",
    "title": "Polycarp's phone book",
    "statement": "There are $n$ phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from $0$. All the numbers are distinct.\n\nThere is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: $123456789$, $100000000$ and $100123456$, then:\n\n- if he enters $00$ two numbers will show up: $100000000$ and $100123456$,\n- if he enters $123$ two numbers will show up $123456789$ and $100123456$,\n- if he enters $01$ there will be only one number $100123456$.\n\nFor each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.",
    "tutorial": "Find the shortest substring of each string such that it doesn't appear in any other string as a substring. For each substring let's store the index of the string which contains this substring or $- 1$ if there are more than one such string. Iterate over all substrings which have values that are not $- 1$ and update the answer for the corresponding string.",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "858",
    "index": "E",
    "title": "Tests Renumeration",
    "statement": "The All-Berland National Olympiad in Informatics has just ended! Now Vladimir wants to upload the contest from the Olympiad as a gym to a popular Codehorses website.\n\nUnfortunately, the archive with Olympiad's data is a mess. For example, the files with tests are named arbitrary without any logic.\n\nVladimir wants to rename the files with tests so that their names are distinct integers starting from $1$ without any gaps, namely, \"1\", \"2\", ..., \"$n$', where $n$ is the total number of tests.\n\nSome of the files contain tests from statements (examples), while others contain regular tests. It is possible that there are no examples, and it is possible that all tests are examples. Vladimir wants to rename the files so that the examples are the first several tests, all all the next files contain regular tests only.\n\nThe only operation Vladimir can perform is the \"move\" command. Vladimir wants to write a script file, each of the lines in which is \"move file_1 file_2\", that means that the file \"file_1\" is to be renamed to \"file_2\". If there is a file \"file_2\" at the moment of this line being run, then this file is to be rewritten. After the line \"move file_1 file_2\" the file \"file_1\" doesn't exist, but there is a file \"file_2\" with content equal to the content of \"file_1\" before the \"move\" command.\n\nHelp Vladimir to write the script file with the minimum possible number of lines so that after this script is run:\n\n- all examples are the first several tests having filenames \"1\", \"2\", ..., \"$e$\", where $e$ is the total number of examples;\n- all other files contain regular tests with filenames \"$e + 1$\", \"$e + 2$\", ..., \"$n$\", where $n$ is the total number of all tests.",
    "tutorial": "Firstly we will get rid of all tests that are already named correctly. After this, let's call samples \"tests of 1 type\", and system tests \"tests of 2 type\". Let's denote \"free positions\" such indices $i\\ (i\\in[1..n])$ such that there is currently no test with the name $i$. If there are no any free positions, then we can't rename each test using only one operation $move$ because firstly we have to make its index a free position. Let's show that one free position is always enough. If there is one, then let's put some test of the corresponding type which has wrong name (a name that doesn't coincide with its type) into this position. It is clear that there will be at least one such test - otherwise all tests of corresponding type are at their positions, and there is no free position of this type. Then there are two cases - either we free a correct position (then we will have another free position) or we move a test which had illegal name (so we don't create any free positions). It's better to move a test which occupies some position so we will have a new free position after it. It is clear that when there are no tests such that their names are correct numbers, but they are in position of different type, then we can't keep the quantity of free positions as it is, and after moving any test this quantity will decrease. This approach is optimal because we will have to perform either $cnt$ ($cnt$ is the number of tests that aren't correctly named initially) or $cnt + 1$ operations. $cnt + 1$ will be the answer only if we have to make an operation that will create a free position (if there are no free positions initially). This number of operations is optimal because if we have $cnt$ incorrectly named tests, then we can't rename them in less than $cnt$ operations; and this is possible only if we have at least one free position initially; otherwise we have to free some position.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "858",
    "index": "F",
    "title": "Wizard's Tour",
    "statement": "All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland!\n\nIt is well-known that there are $n$ cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that the road network is connected, i.e. it is possible that you can't reach some city from some other.\n\nThe tour will contain several episodes. In each of the episodes:\n\n- the wizard will disembark at some city $x$ from the Helicopter;\n- he will give a performance and show a movie for free at the city $x$;\n- he will drive to some neighboring city $y$ using a road;\n- he will give a performance and show a movie for free at the city $y$;\n- he will drive to some neighboring to $y$ city $z$;\n- he will give a performance and show a movie for free at the city $z$;\n- he will embark the Helicopter and fly away from the city $z$.\n\nIt is known that the wizard doesn't like to use roads, so he agrees to use each road at most once (regardless of direction). In other words, for road between $a$ and $b$ he only can drive once from $a$ to $b$, or drive once from $b$ to $a$, or do not use this road at all.\n\nThe wizards wants to plan as many episodes as possible without violation the above rules. Help the wizard!\n\nPlease note that the wizard can visit the same city multiple times, the restriction is on roads only.",
    "tutorial": "Obviously the task can be solved independently for each component. Here is the algorithm that allows you to reach exactly $\\lfloor{\\frac{m}{2}}\\rfloor$ tours, where $m$ is the number of edges in the component. Let's take arbitrary tree built by depth-first search. While exiting vertex $v$, we can process all the edges to the vertices with greater height and the edge connecting vertex $v$ to its parent in the tree (if $v$ isn't a root). If the number of edges to the lower vertices is even then we can split then into pairs. Otherwise let's add the edge from the parent to this splitting and not handle it for the parent itself. This algorithm will find the pair to every edge for all the vertices but the root. There will be at most one edge without the pair so the answer is maximal.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "859",
    "index": "A",
    "title": "Declined Finalists",
    "statement": "This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible contestant must either accept or decline the invitation. Whenever a contestant declines, the highest ranked contestant not yet invited is invited to take the place of the one that declined. This continues until 25 contestants have accepted invitations.\n\nAfter the qualifying round completes, you know $K$ of the onsite finalists, as well as their qualifying ranks (which start at $1$, there are no ties). Determine the minimum possible number of contestants that declined the invitation to compete onsite in the final round.",
    "tutorial": "If all ranks are 25 or less, then the answer is 0, since it's possible that all of the top 25 accepted the invitation. Otherwise, notice that the highest invited rank is initially 25, and increases by 1 every time a contestant declines. Therefore the answer is simply the highest rank minus 25.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "859",
    "index": "B",
    "title": "Lazy Security Guard",
    "statement": "Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly $N$ city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly $N$ blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.",
    "tutorial": "Let's ask the problem a different way. For a fixed perimeter, what's the maximum number of city blocks we can fit in it? The maximum will always be achieved by a rectangle, because that's the only shape that doesn't contain any $270^{\\circ}$ angles. A $270^{\\circ}$ angle is not allowed because there would be a way to add another city block without affecting the perimeter. The problem is therefore equivalent to finding the minimum-perimeter rectangle with area at least $N$. A $H  \\times  W$ rectangle has a perimeter of $2 \\cdot (H + W)$. The constraints of the problem were low enough that one could loop through every possible value of $H$ and find the smallest corresponding $W$ such that $H \\cdot W  \\ge  N$. We can show that the best rectangle will always have $|W-H|\\leq1$. Consider what happens if $W  \\ge  H + 2$. Then $(W - 1) \\cdot (H + 1) = W \\cdot H + (W - H) - 1  \\ge  W \\cdot H + (2) - 1 = W \\cdot H + 1$. In other words, the $(W - 1)  \\times  (H + 1)$ rectangle has greater area than the $W  \\times  H$ rectangle, but the same perimeter. A direct solution therefore sets $W=\\lceil{\\sqrt{N}}\\rceil$ and $H =  \\lceil  N / W \\rceil $.",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "859",
    "index": "C",
    "title": "Pie Rules",
    "statement": "You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, and the other person should choose who gets which slice. Alice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person.\n\nThe way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the \"decider\" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, and the decider token to the other participant. They continue until no slices of pie are left.\n\nAll of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. Assuming both players make their decisions optimally, how much pie will each participant receive?",
    "tutorial": "Denote $Score(L)$ as the total sizes of slices that will be eaten by whoever holds the decider token, for a list of pies $L$, and denote $Total(L)$ as the total size of all slices, and $Rest(L)$ as the list of pies formed by removing the first pie. Note that the total sizes of slices eaten by whoever doesn't hold the decider token is given by $Total(L) - Score(L)$. Let's consider the options available to the participant with the decider token. If they choose to take the pie for themselves, they end up with $L[0] + Total(Rest(L)) - Score(Rest(L))$ total pie. If they let the other participant have the slice, they end up with $Score(Rest(L))$ total pie. They will choose whichever option is larger. To compute the answer, we simply start from the end of the game and work backwards to the beginning.",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 1500
  },
  {
    "contest_id": "859",
    "index": "D",
    "title": "Third Month Insanity",
    "statement": "The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of $2^{N}$ teams participating in the tournament, numbered from $1$ to $2^{N}$. The tournament lasts $N$ rounds, with each round eliminating half the teams. The first round consists of $2^{N - 1}$ games, numbered starting from $1$. In game $i$, team $2·i - 1$ will play against team $2·i$. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game $i$ the winner of the previous round's game $2·i - 1$ will play against the winner of the previous round's game $2·i$.\n\nEvery year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth $1$ point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth $2^{N - 1}$ points.\n\nFor every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.",
    "tutorial": "Denote $opp(r, t)$ as the set of teams that could play against team $t$ in round $r$, and $w[t][u]$ is the probability that team $t$ defeats team $u$. We would first like to compute the probability that team $t$ wins a game in round $r$, and call this $p[r][t]$. Set $p[0][t] = 1$ for all teams for convenience. Then for $r  \\ge  1$ we have that the probability $t$ wins a game in round $r$ is equal to the probability that they won a game in round $r - 1$, times the sum, over all opponents, of the probability of facing that opponent times the probability of defeating that opponent. In mathematical terms, $p[r][t]=p[r-1][t]*\\sum_{u\\in o p p(r,t)}p[r-1][u]*w[t][u]$. Now let us denote $S[r][t]$ as the maximum expected score that can be achieved after $r$ rounds, choosing team $t$ as a winner in round $r$, and only counting points scored in games played between teams that could play in the game that $t$ would play in in round $r$. In other words, consider the sub-bracket which contains $t$ but only goes for $r$ rounds. Our desired result is ${\\underset{[\\mathbf{R}[\\mathbf{x}[\\mathbf{x}]^{N}}}\\left(S[\\mathbf{N}][t]\\right)$. Begin by setting $S[0][t] = 0$ for all $t$. Then for each round and team compute $S[r][t]=\\operatorname*{max}_{u\\in o p p(r,t)}(S[r-1][t]+S[r-1][u]+p[r][t]\\wedge\\stackrel{x}{2}^{r-1})$.",
    "tags": [
      "dp",
      "probabilities",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "859",
    "index": "E",
    "title": "Desk Disorder",
    "statement": "A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.\n\nHow many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo $1000000007 = 10^{9} + 7$.",
    "tutorial": "Consider an undirected graph where the desks are vertices and the engineers are edges. For each engineer an edge connects their current desk to their desired desk. Each connected component of this graph can be assigned independently, with the final result being the product of the number of assignments over the individual components. What type of graphs are the connected components? We know because it's connected that $E  \\ge  V - 1$, where $E$ and $V$ are number of edges and vertices, respectively. Also note that $E  \\le  V$ due to the condition that no two engineers currently sit at the same desk. It follows that there are only 2 cases to consider. Case 1: $E = V - 1$. In this case the component is a tree. We claim that the number of assignments is equal to $V$ in this case. To see why this is true, consider that after we choose which of the $V$ desks to leave empty, there's always exactly 1 way to assign engineers to the remaining desks. Case 2: $E = V$. In this case the component has exactly one cycle. Engineers currently sitting at a desk on the cycle can either all stay at their current desk, or all move to their desired desk. Engineers currently sitting at a desk not on the cycle must remain at their current desks. Therefore there will be exactly 2 assignments, unless the cycle was a self-loop (an engineer whose desired desk is equal to their current desk), in which case there is only 1 assignment. To compute the result, we can use a Disjoint-set data structure. For each connected component, we keep track of its size and what type of cycle (if any) is present. Initially each desk is in a component by itself. For each engineer, we merge the components containing their current and desired desks, or mark the component as containing a cycle if the current and desired desks were already in the same component. Finally we multiply together the numbers of assignments of the components.",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "859",
    "index": "F",
    "title": "Ordering T-Shirts",
    "statement": "It's another Start[c]up, and that means there are T-shirts to order. In order to make sure T-shirts are shipped as soon as possible, we've decided that this year we're going to order all of the necessary T-shirts before the actual competition. The top $C$ contestants are going to be awarded T-shirts, but we obviously don't know which contestants that will be. The plan is to get the T-Shirt sizes of all contestants before the actual competition, and then order enough T-shirts so that no matter who is in the top $C$ we'll have T-shirts available in order to award them.\n\nIn order to get the T-shirt sizes of the contestants, we will send out a survey. The survey will allow contestants to either specify a single desired T-shirt size, or two adjacent T-shirt sizes. If a contestant specifies two sizes, it means that they can be awarded either size.\n\nAs you can probably tell, this plan could require ordering a lot of unnecessary T-shirts. We'd like your help to determine the minimum number of T-shirts we'll need to order to ensure that we'll be able to award T-shirts no matter the outcome of the competition.",
    "tutorial": "Let us first describe how to tell if a given set of T-shirts is sufficient to award the competitors. For any set of T-shirt sizes, it clearly must be the case that the total number of T-shirts ordered of sizes in the set must be at least as large as the maximum number of competitors that could require a T-shirt size from the set. We claim that this is sufficient as well, and will prove it using the max-flow min-cut theorem. Construct a flow graph with a source, one node for each type of survey response, one node for each T-shirt size, and a sink. Add an edge from the source to each survey response node with capacity equal to the number of winners with that response. Add an edge from each survey response to the corresponding T-shirt size(s) with unlimited capacity. Add an edge from each T-shirt size to the sink with capacity equal to the number of T-shirts ordered. Find a minimum cut in this graph. Then for any maximal contiguous range of T-shirt sizes in the cut, we can remove those T-shirt sizes from the cut and instead cut the corresponding survey responses. It follows that the cut consisting only of survey responses is minimal, and by the max-flow min-cut theorem, an assignment exists that awards all winners T-shirts. Note that we don't need to consider all sets of T-shirt sizes - only contiguous sets of T-shirts sizes are relevant. If a non-contiguous set of T-shirt sizes violates the constraint, then one of its contiguous subsections must also violate the constraint. In other words, if we order $t_{i}$ shirts of size $i$, we only need to satisfy $t_{i}+\\ldots+t_{j}\\geq m i n(c,s_{2i-1}+\\ldots+s_{2j-1}),\\forall\\ 1\\leq i\\leq j\\leq n$. We now will show that the algorithm that greedily orders as few of each T-shirt as possible, starting from the smallest size, produces an optimal result. Suppose, to the contrary, that a better solution exists, and consider the lexicographically smallest such solution. At the first point where the solutions differ, the optimal solution must order more T-shirts (due to the greedy nature of the algorithm). If we change the optimal solution by ordering one fewer of that size and one more of the next size up, the solution will remain valid. However this violates the lexicographical minimality of the solution, a contradiction. Our solution is for each index $j$ from $1$ to $n$, to set $t_{j}=\\operatorname*{max}_{1\\leq i\\leq j}(m i n(c,s_{2i-1}+\\dots+s_{2j-1})-(t_{i}+\\dots+t_{j-1}))$. This can easily be done in $O(n^{2})$ time if we compute cumulative sums of $t$ and $s$. In order to solve it faster, we need to be able to quickly find the index $i$ that maximizes the above expression. First lets consider the indexes where $c < s_{2i - 1} + ... + s_{2j - 1}$. Because all $t$ terms are non-negative, we only need to consider the largest such $i$ for which this is true, which can be found in amortized constant time. Now consider indexes where $c  \\ge  s_{2i - 1} + ... + s_{2j - 1}$. Denote $r[i][j] = (s_{2i - 1} + ... + s_{2j - 1}) - (t_{i} + ... + t_{j - 1})$. Notice that for indexes $i_{1}, i_{2} < j$, we have $r[i_{1}][j] - r[i_{2}][j] = r[i_{1}][j - 1] - r[i_{2}][j - 1]$. This implies that if $r[i_{1}][j] > r[i_{2}][j]$ for some index $j$, it is true for all valid indexes $j$. Create a list of indexes $l$ maintaining invariants $l[a]<l[b]\\land r[l[a]][j]>r[l[b]][j]\\forall a<b$. Delete entries from the front of $l$ whenever they no longer satisfy $c  \\ge  s_{2i - 1} + ... + s_{2j - 1}$. Insert $j$ at the end of the list on every iteration, deleting other indexes from the back of the list as necessary in order to maintain the invariants. At each step, the index that maximizes $r[i][j]$ can be found at the front of the list. Using a doubly-ended queue for $l$ makes all of these operations amortized constant time, for a total runtime of $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "859",
    "index": "G",
    "title": "Circle of Numbers",
    "statement": "$n$ evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number $k$. Then you may repeatedly select a set of $2$ or more points which are evenly spaced, and either increase all numbers at points in the set by $k$ or decrease all numbers at points in the set by $k$. You would like to eventually end up with all numbers equal to $0$. Is it possible?\n\nA set of $2$ points is considered evenly spaced if they are diametrically opposed, and a set of $3$ or more points is considered evenly spaced if they form a regular polygon.",
    "tutorial": "Construct polynomial $P(x) = s_{i} \\cdot x^{i}$. For $p|n$ denote $Q_{p}(x) = 1 + x^{n / p} + x^{2n / p} + ... + x^{(p - 1)n / p} = (x^{n} - 1) / (x^{n / p} - 1)$. Our task is to determine if $P(x)$ can be written as a linear combination of $Q_{i}(x)$ polynomials. Bézout's Identity tells us that a solution exists if the greatest common divisor of the $Q_{i}(x)$ polynomials also divides $P(x)$, and the familiar Extended Euclidean Algorithm could be used to construct a solution if needed. Let's compute the GCD of the $Q_{i}(x)$ polynomials, and call it $G(x)$. Let $ \\omega  = e^{2 \\pi  i / n}$. Then $Q_{p}(x)=\\prod_{0<i<n,\\lnot p|i}(x-\\omega^{i})$. Therefore $G(x)=\\prod_{0<i<n,a c d(i,n)=1}(x-\\omega^{i})$. This is equal to the Cyclotomic Polynomial $ \\Phi _{n}(x)$. Directly testing $P(x)$ for divisibility by $G(x)$ is quite expensive. Instead, denote $F$ as the set of prime factors of $n$ and let $R(x)=\\prod_{i\\in F}(x^{n/i}-1)$. Note that for each $i$, $(x-\\omega^{i})|R(x)\\iff g c d(i,n)\\neq1$. It follows that $G(x)|P(x)\\iff(x^{n}-1)|P(x)\\cdot R(x)$. The latter can be easily computed. Alternate solution: Note that a necessary condition is that if we place weights on each point equal in magnitude to the number, then the center of gravity must be at exactly the center of the circle. Attempting to compute the center of gravity numerically isn't guaranteed to work because it could be extremely close to the center (we were able to construct test cases where it was within $10^{ - 500}$ of the center). However, if we choose some integer $m$ relatively prime to $n$, and for each point $i$ move its number to point $m \\cdot i$, then the answer does not change, but the center of gravity might. We can check the center of gravity numerically for several random $m$, and if it's ever not within the margin of numerical error then the answer must be no. In theory this could still fail but in practice it was always easy to find a value of $m$ where the center of gravity is quite far from the actual center. Another way to probabilistically test if the center of gravity is at the center is to choose a random prime $p$ such that $n|p - 1$, and a random $r$ such that $r^{n}\\equiv1\\mod p$. Then it must be the case that $P(r)\\equiv0{\\pmod{p}}$.",
    "tags": [
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "860",
    "index": "E",
    "title": "Arkady and a Nobody-men",
    "statement": "Arkady words in a large company. There are $n$ employees working in a system of a strict hierarchy. Namely, each employee, with an exception of the CEO, has exactly one immediate manager. The CEO is a manager (through a chain of immediate managers) of all employees.\n\nEach employee has an integer rank. The CEO has rank equal to $1$, each other employee has rank equal to the rank of his immediate manager plus $1$.\n\nArkady has a good post in the company, however, he feels that he is nobody in the company's structure, and there are a lot of people who can replace him. He introduced the value of replaceability. Consider an employee $a$ and an employee $b$, the latter being manager of $a$ (not necessarily immediate). Then the replaceability $r(a, b)$ of $a$ with respect to $b$ is the number of subordinates (not necessarily immediate) of the manager $b$, whose rank is not greater than the rank of $a$. Apart from replaceability, Arkady introduced the value of negligibility. The negligibility $z_{a}$ of employee $a$ equals the sum of his replaceabilities with respect to all his managers, i.e. ${z_{a}}=\\sum_{b}r(a,b)$, where the sum is taken over all his managers $b$.\n\nArkady is interested not only in negligibility of himself, but also in negligibility of all employees in the company. Find the negligibility of each employee for Arkady.",
    "tutorial": "First of all, $ans[v] = ans[parent[v]] + depth[v] + ans'[v]$, where $ans'[v]$ is the sum of (number of descendants of the rank depth[v]) for all predecessors of $v$. All we need is to compute $ans'[v]$ now. Let's make a dfs in the graph. Let the dfs(v) return a vector $ret[v]$ such that $ret[v][d]$ is the following tuple: (number of vertices on depth $d$ in subtree of $v$, some vertex $x$ with depth $d$ in the subtree of $v$, the $ans'[x]$ if we consider only predecessors in the subtree of $v$). Also let's build some structure so that we can easily restore answers in this subtree if we know the final value of $ans'[x]$. We will see what is this structure later. To compute $ret[v]$ we need to be able to merge two $ret$s of its sons. Let's say we merge tuple $(cnt_{a}, a, ans'[a])$ with $(cnt_{b}, b, ans'[b])$. Then all we need to do is: $ans'[b] + = depth[v] * cnt_{a}$, $ans'[a] + = depth[v] * cnt_{b}$, return $(cnt_{a} + cnt_{b}, a, ans'[a])$ as the result. However, we must also be able to restore $ans'[b]$ after the dfs is complete (remind the unknown structure). So after performing $ans'[b] + = depth[v] * cnt_{a}$ let's add an edge $a  \\rightarrow  b$ to a new graph with weight $ans'[a] - ans'[b]$. Note that the difference between these values will be the same all the time after the tuples are merged, so using this edge we will be able to restore the answer $ans'[b]$. After the dfs is done, run another dfs on the new graph to restore the values $ans'[v]$ and then $ans[v]$. To perform the second step fast, we need to note that we can always merge smaller $ret$s into larger, and move them in $O(1)$ into parents. Since each tuple is merged into a larger vector only once, this solution works in total in $O(n)$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "862",
    "index": "A",
    "title": "Mahmoud and Ehab and the MEX",
    "statement": "Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.\n\nDr. Evil is interested in sets, He has a set of $n$ integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly $x$. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set ${0, 2, 4}$ is $1$ and the MEX of the set ${1, 2, 3}$ is $0$ .\n\nDr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?",
    "tutorial": "One can see that in the final set all the elements less than $x$ should exist, $x$ shouldn't exist and any element greater than $x$ doesn't matter, so we will count the number of elements less than $x$ that don't exist in the initial set and add this to the answer, If $x$ exists we'll add 1 to the answer because $x$ should be removed . Time complexity : $O(n + x)$ .",
    "code": "\"#include <iostream>\\nusing namespace std;\\nbool b[105];\\nint main()\\n{\\n\\tint n,x;\\n\\tscanf(\\\"%d%d\\\",&n,&x);\\n\\twhile (n--)\\n\\t{\\n\\t\\tint a;\\n\\t\\tscanf(\\\"%d\\\",&a);\\n\\t\\tb[a]=1;\\n\\t}\\n\\tint ans=b[x];\\n\\tfor (int i=0;i<x;i++)\\n\\tans+=!b[i];\\n\\tprintf(\\\"%d\\\",ans);\\n}\"",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "862",
    "index": "B",
    "title": "Mahmoud and Ehab and the bipartiteness",
    "statement": "Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.\n\nA tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into $2$ sets in such a way, that for each edge $(u, v)$ that belongs to the graph, $u$ and $v$ belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.\n\nDr. Evil gave Mahmoud and Ehab a tree consisting of $n$ nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?\n\nA loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. \\textbf{A cycle and a loop aren't the same} .",
    "tutorial": "The tree itself is bipartite so we can run a dfs to partition the tree into the 2 sets (called bicoloring), We can't add an edge between any 2 nodes in the same set and we can add an edge between every 2 nodes in different sets, so let the number of nodes in the left set be $l$ and the number of nodes in the right set be $r$, The maximum number of edges that can exist is $l * r$, but $n - 1$ edges already exist so the maximum number of edges to be added is $l * r - (n - 1)$. Time complexity : $O(n)$ .",
    "code": "\"#include <iostream>\\n#include <vector>\\nusing namespace std;\\nvector<int> v[100005];\\nlong long cnt[2];\\nvoid dfs(int node,int pnode,int color)\\n{\\n\\tcnt[color]++;\\n\\tfor (int i=0;i<v[node].size();i++)\\n\\t{\\n\\t\\tif (v[node][i]!=pnode)\\n\\t\\tdfs(v[node][i],node,!color);\\n\\t}\\n}\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tint a,b;\\n\\t\\tscanf(\\\"%d%d\\\",&a,&b);\\n\\t\\tv[a].push_back(b);\\n\\t\\tv[b].push_back(a);\\n\\t}\\n\\tdfs(1,0,0);\\n\\tprintf(\\\"%I64d\\\",cnt[0]*cnt[1]-n+1);\\n}\"",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "862",
    "index": "C",
    "title": "Mahmoud and Ehab and the xor",
    "statement": "Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.\n\nDr. Evil has his favorite evil integer $x$. He asks Mahmoud and Ehab to find a set of $n$ distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly $x$. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than $10^{6}$.",
    "tutorial": "$n = 2, x = 0$ is the only case with answer \"NO\" . Let $pw = 2^{17}$ . First print $1, 2, ..., n - 3$ (The first $n - 3$ positive integers), Let their bitwise-xor sum be $y$, If $x = y$ You can add $pw, pw * 2$ and $p w\\oplus(p w*2)$, Otherwise you can add $0, pw$ and $p w\\oplus x\\oplus y$, We handled the case $x = y$ in a different way because if we add $0, pw$ and $p w\\oplus x\\oplus y$ in this case, Then it's like adding $0, pw$ and $pw$, $pw$ appears twice so we'll get wrong answer. Handle $n = 1$ (print $x$) and $n = 2$ (print $0$ and $x$) .",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nconst int pw1=(1<<17);\\nconst int pw2=(1<<18);\\n\\nint main()\\n{\\n\\tint n,x;\\n\\tcin >> n >> x;\\n\\tif(n==1)\\n\\t\\tcout << \\\"YES\\\\n\\\"<<x<<\\\"\\\\n\\\";\\n\\telse if(n==2&&x==0)\\n\\t\\tcout << \\\"NO\\\\n\\\";\\n\\telse if(n==2)\\n\\t\\tcout << \\\"YES\\\\n0 \\\"<<x<<\\\"\\\\n\\\";\\n\\telse\\n\\t{\\n\\t\\tint i;\\n\\t\\tint ans=0;\\n\\t\\tcout << \\\"YES\\\\n\\\";\\n\\t\\tfor(i=1;i<=n-3;i++)\\n\\t\\t{\\n\\t\\t\\tcout << i << \\\" \\\";\\n\\t\\t\\tans^=i;\\n\\t\\t}\\n\\t\\tif(ans==x)\\n\\t\\t\\tcout << pw1+pw2 << \\\" \\\" << pw1 << \\\" \\\" << pw2<< \\\"\\\\n\\\";\\n\\t\\telse\\n\\t\\t\\tcout << pw1 << \\\" \\\" << ((pw1^x)^ans) << \\\" 0 \\\\n\\\";\\n\\t}\\n}\"",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "862",
    "index": "D",
    "title": "Mahmoud and Ehab and the binary string",
    "statement": "Mahmoud and Ehab are in the fourth stage now.\n\nDr. Evil has a hidden binary string of length $n$. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to $15$ questions. They tell Dr. Evil some binary string of length $n$, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below.\n\nHelp Mahmoud and Ehab find these two positions.\n\nYou will get Wrong Answer verdict if\n\n- Your queries doesn't satisfy interaction protocol described below.\n- You ask strictly more than $15$ questions and your program terminated after exceeding queries limit. Please note, that you can do up to $15$ ask queries and one answer query.\n- Your final answer is not correct.\n\nYou will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .",
    "tutorial": "In the editorial we suppose that the answer of some query is the number of correct guessed positions which is equal to $n$ minus hamming distance, The solutions in this editorial consider the answer of a query as $n$ minus real answer, For convenience. Common things : Let $zero(l, r)$ be a function that returns the number of zeros in the interval $[l;r]$ minus the number of ones in it, We can find it in one query after a preprocessing query, The preprocessing query is $1111...$, Let its answer be stored in $all$, If we made a query with a string full of ones except for the interval $[l;r]$ which will be full of zeros, If this query's answer is $cur$, $zero(l, r) = cur - all$, That's because $all$ is the number of ones in the interval $[l;r]$ plus some trash and $cur$ is the number of zeros in the interval plus the same trash . Let's have a searching interval, initially this interval is $[1;n]$ (The whole string), Let's repeat this until we reach our goal, Let $mid = (l + r) / 2$ Let's query to get $zero(l, mid)$, If it's equal to $r - l + 1$, This interval is full of zeros so we can print any index in it as the index with value 0 and continue searching for an index with the value 1 in the interval $[mid + 1;r]$, But if its value is equal to $l - r - 1$, This interval is full of ones so we can print any index in it as the index with value 1 and continue searching for a 0 in the interval $[mid + 1;r]$, Otherwise the interval contains both values so we can continue searching for both in the interval $[l;mid]$, Every time the searching interval length must be divided by 2 in any case so we perform $O(log(n))$ queries . Let's send $1111...$ and let the answer be $ans1$, Let's send $0111...$ and let the answer be $ans0$, We now know the value in the first index (1 if $ans1 > ans0$, 0 otherwise), We can binary search for the first index where the non-found value exists, which is to binary search on the first value $x$ where $zero(2, x) * sign(non - found$ $bit$ $value)  \\neq  x - 1$ where $sign(y)$ is $1$ if $y = 0$, $- 1$ otherwise .",
    "code": "\"#include <iostream>\\nusing namespace std;\\nchar s[1005];\\nint ans,pos0,pos1,n;\\nvoid send()\\n{\\n\\tprintf(\\\"? %s\\\\n\\\",s);\\n\\tfflush(stdout);\\n\\tscanf(\\\"%d\\\",&ans);\\n\\tans=n-ans;\\n}\\nint main()\\n{\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=0;i<n;i++)\\n\\ts[i]='1';\\n\\tsend();\\n\\tint mans=ans;\\n\\ts[0]='0';\\n\\tsend();\\n\\tif (mans>ans)\\n\\tpos1=1;\\n\\telse\\n\\tpos0=1;\\n\\ts[0]='1';\\n\\tint st=1,en=n;\\n\\twhile (st!=en)\\n\\t{\\n\\t\\tint mid=(st+en)/2;\\n\\t\\tfor (int i=1;i<=mid;i++)\\n\\t\\ts[i]='0';\\n\\t\\tsend();\\n\\t\\tif ((mans-ans)*(pos1? 1:-1)==mid)\\n\\t\\tst=mid+1;\\n\\t\\telse\\n\\t\\ten=mid;\\n\\t\\tfor (int i=1;i<=mid;i++)\\n\\t\\ts[i]='1';\\n\\t}\\n\\tif (!pos0)\\n\\tpos0=st+1;\\n\\telse\\n\\tpos1=st+1;\\n\\tprintf(\\\"! %d %d\\\",pos0,pos1);\\n\\tfflush(stdout);\\n}\"",
    "tags": [
      "binary search",
      "divide and conquer",
      "interactive"
    ],
    "rating": 2000
  },
  {
    "contest_id": "862",
    "index": "E",
    "title": "Mahmoud and Ehab and the function",
    "statement": "Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array $a$ of length $n$ and array $b$ of length $m$. He introduced a function $f(j)$ which is defined for integers $j$, which satisfy $0 ≤ j ≤ m - n$. Suppose, $c_{i} = a_{i} - b_{i + j}$. Then $f(j) = |c_{1} - c_{2} + c_{3} - c_{4}... c_{n}|$. More formally, $f(j)=|\\sum_{i=1}^{n}(-1)^{i-1}*(a_{i}-b_{i+j})|$.\n\nDr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid $j$. They found it a bit easy, so Dr. Evil made their task harder. He will give them $q$ update queries. During each update they should add an integer $x_{i}$ to all elements in $a$ in range $[l_{i};r_{i}]$ i.e. they should add $x_{i}$ to $a_{li}, a_{li + 1}, ... , a_{ri}$ and then they should calculate the minimum value of $f(j)$ for all valid $j$.\n\nPlease help Mahmoud and Ehab.",
    "tutorial": "Let's write $f(j)$ in another way:- $f(j)=\\vert\\sum_{i=1}^{n}(-1)^{i-1}*(a_{i}-b_{i+j})\\vert=\\vert\\sum_{i=1}^{n}(-1)^{i-1}*a_{i}+(-1)^{i}*b_{i+j}\\vert$ $=\\left|\\sum_{i=1}^{n}(-1)^{i-1}\\ast a_{i}+\\sum_{i=1}^{n}(-1)^{i}\\ast b_{i+j}\\right|$ Now we have 2 sums, The first one is constant (doesn't depend on $j$), For the second sum we can calculate all its possible values using sliding window technique, Now we want a data-structure that takes the value of the first sum and chooses the best second sum from all the choices . observation: We don't have to try all the possible values of $f(j)$ to minimize the expression, If the first sum is $c$, We can try only the least value greater than $- c$ and the greatest value less than $- c$ ($- c$ not $c$ because we are minimizing $c + second$ not $c - second$) because the absolute value means the distance between the two values on the number line, Any other value will be further than at least one of the chosen values, To do this we can keep all the values of $f(j)$ sorted and try the elements numbered lower_bound(-c) and lower_bound(-c)-1 and choose the better (In short we're trying the values close to $- c$ only). Now we have a data-structure that can get us the minimum value of the expression once given the value of the first sum in $O(log(n))$, Now we want to keep track of the value of the first sum . Let the initial value be $c$, In each update, If the length of the updated interval is even, The sum won't change because $x$ will be added as many times as it's subtracted, Otherwise $x$ will be added to $c$ or subtracted from $c$ depending of the parity of $l$ (the left-bound of the interval) . Time complexity : $O(n + (m + q)log(m))$ .",
    "code": "\"#include <iostream>\\n#include <set>\\nusing namespace std;\\nint sign(int x)\\n{\\n\\tif (x%2)\\n\\treturn -1;\\n\\treturn 1;\\n}\\nlong long absll(long long x)\\n{\\n\\tif (x>0)\\n\\treturn x;\\n\\treturn -x;\\n}\\nset<long long> s;\\nint b[100005];\\nlong long ans(long long x)\\n{\\n\\tset<long long>::iterator it=s.lower_bound(x);\\n\\tif (it==s.end())\\n\\tit--;\\n\\tlong long ret=absll((*it)-x);\\n\\tif (it!=s.begin())\\n\\tit--;\\n\\treturn min(ret,absll((*it)-x));\\n}\\nint main()\\n{\\n\\tint n,m,q;\\n\\tscanf(\\\"%d%d%d\\\",&n,&m,&q);\\n\\tlong long sumA=0;\\n\\tfor (int i=0;i<n;i++)\\n\\t{\\n\\t\\tint a;\\n\\t\\tscanf(\\\"%d\\\",&a);\\n\\t\\tsumA+=a*sign(i);\\n\\t}\\n\\tlong long cur=0;\\n\\tfor (int i=0;i<n;i++)\\n\\t{\\n\\t\\tscanf(\\\"%d\\\",&b[i]);\\n\\t\\tcur+=sign(i+1)*b[i];\\n\\t}\\n\\ts.insert(cur);\\n\\tfor (int i=n;i<m;i++)\\n\\t{\\n\\t\\tscanf(\\\"%d\\\",&b[i]);\\n\\t\\tcur+=b[i-n];\\n\\t\\tcur=-cur;\\n\\t\\tcur+=sign(n)*b[i];\\n\\t\\ts.insert(cur);\\n\\t}\\n\\tprintf(\\\"%I64d\\\\n\\\",ans(-sumA));\\n\\twhile (q--)\\n\\t{\\n\\t\\tint l,r,x;\\n\\t\\tscanf(\\\"%d%d%d\\\",&l,&r,&x);\\n\\t\\tif ((r-l)%2==0)\\n\\t\\t{\\n\\t\\t\\tif (l%2)\\n\\t\\t\\tsumA+=x;\\n\\t\\t\\telse\\n\\t\\t\\tsumA-=x;\\n\\t\\t}\\n\\t\\tprintf(\\\"%I64d\\\\n\\\",ans(-sumA));\\n\\t}\\n}\"",
    "tags": [
      "binary search",
      "data structures",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "862",
    "index": "F",
    "title": "Mahmoud and Ehab and the final stage",
    "statement": "Mahmoud and Ehab solved Dr. Evil's questions so he gave them the password of the door of the evil land. When they tried to open the door using it, the door gave them a final question to solve before they leave (yes, the door is digital, Dr. Evil is modern). If they don't solve it, all the work will be useless and they won't leave the evil land forever. Will you help them?\n\nMahmoud and Ehab are given $n$ strings $s_{1}, s_{2}, ... , s_{n}$ numbered from $1$ to $n$ and $q$ queries, Each query has one of the following forms:\n\n- $1$ $a$ $b$ $(1 ≤ a ≤ b ≤ n)$, For all the intervals $[l;r]$ where $(a ≤ l ≤ r ≤ b)$ find the maximum value of this expression:$(r - l + 1) * LCP(s_{l}, s_{l + 1}, ... , s_{r - 1}, s_{r})$ where $LCP(str_{1}, str_{2}, str_{3}, ... )$ is the length of the longest common prefix of the strings $str_{1}, str_{2}, str_{3}, ... $.\n- $2$ $x$ $y$ $(1 ≤ x ≤ n)$ where $y$ is a string, consisting of lowercase English letters. Change the string at position $x$ to $y$.",
    "tutorial": "First, Let's get rid of the $LCP$ part . observation: $L C P(s t r_{1},s t r_{2},\\cdot\\cdot\\cdot,s t r_{k})=\\operatorname*{min}_{i=1}^{k-1}L C P(s t r_{i},s t r_{i+1})$, That could make us transform the $LCP$ part into a minimization part by making an array $lcp$ where $lcp_{i} = LCP(s_{i}, s_{i + 1})$, You could calculate it naively, And when an update happens at index $a$, You should update $lcp_{a}$ (If exists) and $lcp_{a - 1}$ (If exists) naively . Now the problem reduces to finding $a  \\le  l  \\le  r  \\le  b$ that maximizes the value:- $(\\operatorname*{min}_{i=l}l c p_{i})*(r-l+1)$, If we have a histogram where the $i^{th}$ column has height $lcp_{i}$, The the size of the largest rectangle that fits in the columns from $l$ to $r - 1$ is $(\\operatorname*{min}_{i=l}l c p_{i})*(r-l)$, That's close to our formula not the same but it's not a problem (You'll see how to fix it later), so to get rid of finding the $l$ and $r$ part, We can make that histogram and the answer for a query will be the largest rectangle in the subhistogram that contains the columns from $a$ to $b - 1$, One of the ways to solve it is to try some heights $h$ and see the maximum width we can achieve if $h$ was the height, call it $w$, and maximize with $h * w$, To solve the slight difference in formulas problem we'll just maximize with $h * (w + 1)$!! Let $BU$ be a value the we'll choose later, We have 2 cases for our largest rectangle's height $h$, It could be either $h  \\le  BU$ or $h > BU$, We will solve both problems separately. For $h  \\le  BU$ we can maintain $BU$ segment trees, Segment tree number $i$ has $1$ at index $x$ if $lcp_{x}  \\ge  i$ and $0$ otherwise, When we query, It should get us the longest subsegment of ones in the query range, Let's see what we need for our merging operation, If we want the answer for the longest subsegment of ones in a range $[l;r]$, Let $mid = (l + r) / 2$, Then the answer is the maximum between the answer of $[l;mid]$, The answer of $[mid + 1;r]$, And the maximum suffix of ones in the range $[l;mid]$ added to the maximum prefix of ones in the range $[mid + 1;r]$ . So we need to keep all these information in our node and also the length of the interval, As it's a well-known problem I won't get into more detail. Back to our problem, We can loop over all $h  \\le  BU$, Let the answer for the query on range $[a;b - 1]$ in segment tree number $h$ be $w$, The maximum width of a rectangle of height $h$ in this range is $w$ and we'll maximize our answer with $h * (w + 1)$ . For $h > BU$, Let's call a column of height greater than $BU$ big, The heights we'll try are the heights of the big columns in the range, We don't have to try all the heights greater the $BU$, There are at most $\\frac{t o t}{B U}$ big columns (Where $tot$ is the total length of strings in input), Let's keep them in a set, When an update happens, You should add the column to the set or remove it depending on its new height, The set's size can't exceed $\\frac{t o t}{B U}$ now, Let's see how to answer a query, Let's loop over the big columns in range $[a;b - 1]$ only, If 2 of them aren't consecutive then the column after the first can't be big and the column before the second either, That's because if it were big, It would be in our set, So we can use this observation by making a new histogram with the big columns in the range only, And put a column with height 0 between any non-consecutive two, And get the largest rectangle in this histogram by the stack way for example in $O(\\underline{{{\\scriptscriptstyle(L d I)}}}^{i d I})$, The stack way will get us the maximum width $w$ we can achieve for a rectangle containing column number $i$, We'll maximize with $lcp_{i} * (w + 1)$. Also the answer for our main formula can be an interval of length one, All what I mentioned doesn't cover this, You should maintain another segment tree that gets the maximum length of a string in a range for this . Maximize all what we got, You have the answer, Now it's time to choose $BU$, It's optimal in time to choose $BU$ near $\\sqrt{{\\frac{t o t}{i\\omega g(t o t)}}}$ (Reason in tfg's comment below) . Optimization: The longest subsegment of ones problem is solved by $BU$ segment trees and each one has 4 integers in each node, You can make them 2 integers (max prefix and suffix of ones) and make another only one segment tree that has the rest of the integers, That would divide the memory by 2 . Time complexity : $O(t o t+q{\\sqrt{t o t*l o g(t o t)}})$",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\ntypedef long double ld;\\n\\nconst int BUBEN = (int)110;\\n\\nstruct Data {\\n  int goLeft[BUBEN], goRight[BUBEN];\\n  int res;\\n  int length;\\n  Data(int x) {\\n    x = min(x, BUBEN - 1);\\n    res = x;\\n    length = 1;\\n    for (int i = 0; i < BUBEN; i++) {\\n      if (i <= x) {\\n        goLeft[i] = goRight[i] = 1;\\n      } else {\\n        goLeft[i] = goRight[i] = 0;\\n      }\\n    }\\n  }\\n  Data() {}\\n};\\n\\nvoid merge(const Data &l, const Data &r, Data &res) {\\n  res.res = max(l.res, r.res);\\n  res.length = l.length + r.length;\\n  for (int i = 0; i < BUBEN; i++) {\\n    res.goLeft[i] = l.goLeft[i];\\n    if (res.goLeft[i] == l.length) res.goLeft[i] += r.goLeft[i];\\n    res.goRight[i] = r.goRight[i];\\n    if (res.goRight[i] == r.length) res.goRight[i] += l.goRight[i];\\n    if (r.goLeft[i] || l.goRight[i]) {\\n      res.res = max(res.res, i * (r.goLeft[i] + l.goRight[i] + 1));\\n    }\\n  }\\n}\\n\\nstruct SegmentTree {\\n  Data *t;\\n  Data tmp, tmp2;\\n  int n;\\n  SegmentTree(int n) : n(n) {\\n    t = new Data[4 * n + 3];\\n  }\\n  SegmentTree() {}\\n  void change(int v, int tl, int tr, int pos, int val) {\\n    if (tl == tr) {\\n      t[v] = Data(val);\\n    } else {\\n      int tm = (tl + tr) >> 1;\\n      if (pos <= tm) {\\n        change(v + v, tl, tm, pos, val);\\n      } else {\\n        change(v + v + 1, tm + 1, tr, pos, val);\\n      }\\n      merge(t[v + v], t[v + v + 1], t[v]);\\n    }\\n  }\\n  void build(int v, int tl, int tr, int *a) {\\n    if (tl == tr) {\\n      t[v] = Data(a[tl]);\\n    } else {\\n      int tm = (tl + tr) >> 1;\\n      build(v + v, tl, tm, a);\\n      build(v + v + 1, tm + 1, tr, a);\\n      merge(t[v + v], t[v + v + 1], t[v]);\\n    }\\n  }\\n  void build(int *a) {\\n    build(1, 1, n, a);\\n  }\\n  void change(int pos, int val) {\\n    change(1, 1, n, pos, val);\\n  }\\n  void get(int v, int tl, int tr, int l, int r) {\\n    if (r < tl || l > tr) return;\\n    if (tl >= l && tr <= r) {\\n      merge(tmp, t[v], tmp2);\\n      memcpy(&tmp, &tmp2, sizeof(tmp));\\n    } else {\\n      int tm = (tl + tr) >> 1;\\n      get(v + v, tl, tm, l, r);\\n      get(v + v + 1, tm + 1, tr, l, r);\\n    }\\n  }\\n  int solve(int l, int r) {\\n    memset(&tmp, 0, sizeof(tmp));\\n    memset(&tmp2, 0, sizeof(tmp2));\\n    get(1, 1, n, l, r);\\n    return tmp.res;\\n  }\\n};\\n\\n\\nint solveHistogram(const vector<int> &a) {\\n  int n = (int)a.size();\\n  vector<int> gol(n), gor(n);\\n  vector<int> st;\\n  st.reserve(n);\\n  for (int i = 0; i < n; i++) {\\n    while (!st.empty() && a[st.back()] >= a[i]) st.pop_back();\\n    if (st.empty()) {\\n      gol[i] = 0;\\n    } else {\\n      gol[i] = st.back() + 1;\\n    }\\n    st.push_back(i);\\n  }\\n  st.clear();\\n  for (int i = n - 1; i >= 0; i--) {\\n    while (!st.empty() && a[st.back()] >= a[i]) st.pop_back();\\n    if (st.empty()) {\\n      gor[i] = n - 1;\\n    } else {\\n      gor[i] = st.back() - 1;\\n    }\\n    st.push_back(i);\\n  }\\n  int res = 0;\\n  for (int i = 0; i < n; i++) {\\n    res = max(res, a[i] * (gor[i] - gol[i] + 2));\\n  }\\n  return res;\\n}\\n\\nstruct LargeSolver {\\n  int *a;\\n  int n;\\n  set<int> largePoses;\\n  LargeSolver(int n) : n(n) {\\n    a = new int[n + 1];\\n  }\\n  LargeSolver() {}\\n  void change(int pos, int val) {\\n    if (a[pos] >= BUBEN) {\\n      largePoses.erase(pos);\\n    }\\n    a[pos] = val;\\n    if (a[pos] >= BUBEN) {\\n      largePoses.insert(pos);\\n    }\\n  }\\n  int solve(int l, int r) {\\n    auto it = largePoses.lower_bound(l);\\n    int res = 0;\\n    vector<int> cur;\\n    int lst = -1;\\n    while (it != largePoses.end() && (*it) <= r) {\\n      int curPos = (*it);\\n      if (curPos != lst + 1 && !cur.empty()) {\\n        res = max(res, solveHistogram(cur));\\n        cur.clear();\\n      }\\n      cur.push_back(a[curPos]);\\n      lst = curPos;\\n      it++;\\n    }\\n    if (!cur.empty()) {\\n      res = max(res, solveHistogram(cur));\\n    }\\n    return res;\\n  }\\n};\\n\\nstruct MaxSegmentTree {\\n  int *t;\\n  int n;\\n  MaxSegmentTree(int n) : n(n) {\\n    t = new int[4 * n + 3];\\n  }\\n  MaxSegmentTree() {}\\n  void change(int v, int tl, int tr, int pos, int val) {\\n    if (tl == tr) {\\n      t[v] = val;\\n    } else {\\n      int tm = (tl + tr) >> 1;\\n      if (pos <= tm) {\\n        change(v + v, tl, tm, pos, val);\\n      } else {\\n        change(v + v + 1, tm + 1, tr, pos, val);\\n      }\\n      t[v] = max(t[v + v], t[v + v + 1]);\\n    }\\n  }\\n  void change(int pos, int val) {\\n    change(1, 1, n, pos, val);\\n  }\\n  int getMax(int v, int tl, int tr, int l, int r) {\\n    if (r < tl || l > tr) return 0;\\n    if (tl >= l && tr <= r) return t[v];\\n    int tm = (tl + tr) >> 1;\\n    return max(getMax(v + v, tl, tm, l, r), getMax(v + v + 1, tm + 1, tr, l, r));\\n  }\\n  int getMax(int l, int r) {\\n    return getMax(1, 1, n, l, r);\\n  }\\n};\\n\\nstruct DynamicHystogramSolver {\\n  SegmentTree st;\\n  LargeSolver ls;\\n  DynamicHystogramSolver() {}\\n  DynamicHystogramSolver(int *a, int n) {\\n    st = SegmentTree(n);\\n    st.build(a);\\n    ls = LargeSolver(n);\\n    for (int i = 1; i <= n; i++) {\\n      ls.change(i, a[i]);\\n    }\\n  }\\n  void change(int pos, int val) {\\n    st.change(pos, val);\\n    ls.change(pos, val);\\n  }\\n  int getMax(int l, int r) {\\n    if (l > r) return 0;\\n    return max(st.solve(l, r), ls.solve(l, r));\\n  }\\n};\\n\\nint getLCP(const string &s, const string &t) {\\n  int ptr = 0;\\n  while (ptr < (int)min(s.size(), t.size()) && s[ptr] == t[ptr]) ptr++;\\n  return ptr;\\n}\\nstruct Solver {\\n  string *s;\\n  int *lcp;\\n  int n;\\n  DynamicHystogramSolver dhs;\\n  MaxSegmentTree st;\\n  Solver(const vector<string> &a) {\\n    n = a.size();\\n    s = new string[n + 1];\\n    lcp = new int[n + 1];\\n    for (int i = 1; i <= n; i++) {\\n      s[i] = a[i - 1];\\n    }\\n    for (int i = 1; i < n; i++) {\\n      lcp[i] = getLCP(s[i], s[i + 1]);\\n    }\\n    dhs = DynamicHystogramSolver(lcp, n);\\n    st = MaxSegmentTree(n);\\n    for (int i = 1; i <= n; i++) {\\n      st.change(i, (int)s[i].size());\\n    }\\n  }\\n  void change(int pos, const string &str) {\\n    s[pos] = str;\\n    if (pos != 1) {\\n      lcp[pos - 1] = getLCP(s[pos - 1], s[pos]);\\n      dhs.change(pos - 1, lcp[pos - 1]);\\n    }\\n    if (pos != n) {\\n      lcp[pos] = getLCP(s[pos], s[pos + 1]);\\n      dhs.change(pos, lcp[pos]);\\n    }\\n    st.change(pos, (int)str.size());\\n  }\\n  int solve(int l, int r) {\\n    return max(dhs.getMax(l, r - 1), st.getMax(l, r));\\n  }\\n};\\n\\nconst int MX = 300 * 1000 + 7;\\n\\nchar buf[MX];\\n\\nstring getString() {\\n  scanf(\\\"%s\\\", buf);\\n  return string(buf);\\n}\\n\\nint main() {\\n#ifdef LOCAL\\n  freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n#endif\\n  int n, q;\\n  scanf(\\\"%d %d\\\", &n, &q);\\n  vector<string> s(n);\\n  for (int i = 0; i < n; i++) {\\n    s[i] = getString();\\n  }\\n  Solver solver(s);\\n  for (int i = 0; i < q; i++) {\\n    int type;\\n    scanf(\\\"%d\\\", &type);\\n    if (type == 1) {\\n      int l, r;\\n      scanf(\\\"%d %d\\\", &l, &r);\\n      printf(\\\"%d\\\\n\\\", solver.solve(l, r));\\n    } else {\\n      int pos;\\n      scanf(\\\"%d \\\", &pos);\\n      solver.change(pos, getString());\\n    }\\n  }\\n  return 0;\\n}\"",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "863",
    "index": "A",
    "title": "Quasi-palindrome",
    "statement": "Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string.\n\nString $t$ is called a palindrome, if it reads the same from left to right and from right to left.\n\nFor example, numbers $131$ and $2010200$ are quasi-palindromic, they can be transformed to strings \"$131$\" and \"$002010200$\", respectively, which are palindromes.\n\nYou are given some integer number $x$. Check if it's a quasi-palindromic number.",
    "tutorial": "You can check if the given is quasi-palindromic by removing all the trailing zeros and checking if resulting string is a palindrome.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "863",
    "index": "B",
    "title": "Kayaking",
    "statement": "Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.\n\nNow the party is ready to start its journey, but firstly they have to choose kayaks. There are $2·n$ people in the group (including Vadim), and they have exactly $n - 1$ tandem kayaks (each of which, obviously, can carry two people) and $2$ single kayaks. $i$-th person's weight is $w_{i}$, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.\n\nFormally, the instability of a single kayak is always $0$, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.\n\nHelp the party to determine minimum possible total instability!",
    "tutorial": "Firstly let's learn how to split persons in pairs as if there are no single kayaks. Let there be people with weights $a$, $b$, $c$ and $d$ ($a  \\le  b  \\le  c  \\le  d$). Obviously, the lowest instability you can achieve is $max(b - a, d - c)$. Swapping any two elements will only make the result greater. This greedy strategy can be used to distribute all the seats. Now you need to check every pair of persons to seat in single kayaks and calculate total instability for the rest. The answer will be the minimun instabily over all pairs. Overall complexity: $O(n^{3})$.",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "863",
    "index": "C",
    "title": "1-2-3",
    "statement": "Ilya is working for the company that constructs robots. Ilya writes programs for entertainment robots, and his current project is \"Bob\", a new-generation game robot. Ilya's boss wants to know his progress so far. Especially he is interested if Bob is better at playing different games than the previous model, \"Alice\".\n\nSo now Ilya wants to compare his robots' performance in a simple game called \"1-2-3\". This game is similar to the \"Rock-Paper-Scissors\" game: both robots secretly choose a number from the set ${1, 2, 3}$ and say it at the same moment. If both robots choose the same number, then it's a draw and noone gets any points. But if chosen numbers are different, then one of the robots gets a point: $3$ beats $2$, $2$ beats $1$ and $1$ beats $3$.\n\nBoth robots' programs make them choose their numbers in such a way that their choice in $(i + 1)$-th game depends only on the numbers chosen by them in $i$-th game.\n\nIlya knows that the robots will play $k$ games, Alice will choose number $a$ in the first game, and Bob will choose $b$ in the first game. He also knows both robots' programs and can tell what each robot will choose depending on their choices in previous game. Ilya doesn't want to wait until robots play all $k$ games, so he asks you to predict the number of points they will have after the final game.",
    "tutorial": "Notice that there are only $9$ possible patterns in this game. You can used in a following way. Simulate games till one of the patterns get repeated. Games between this pair of occurences will get you the same total outcome no matter when they are played. Let the distance between the games with the same pattern is $dif$ and index of these games are $idx_{1}$ and $idx_{2}$ (zero-indexed). Total score of some interval is $score(l, r)$. Then the answer will be $score(0, idx_{1})$ + $\\lfloor{\\frac{k-i d x_{1}}{d i J}}\\rfloor\\cdot s c o r e(i d x_{1}+1,i d x_{2})$ + $((k - idx_{1})$ $mod$ $dif) \\cdot score(idx_{1} + 1, idx_{1} + (k - idx_{1})$ $mod$ $dif)$.",
    "tags": [
      "graphs",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "863",
    "index": "D",
    "title": "Yet Another Array Queries Problem",
    "statement": "You are given an array $a$ of size $n$, and $q$ queries to it. There are queries of two types:\n\n- $1$ $l_{i}$ $r_{i}$ — perform a cyclic shift of the segment $[l_{i}, r_{i}]$ to the right. That is, for every $x$ such that $l_{i} ≤ x < r_{i}$ new value of $a_{x + 1}$ becomes equal to old value of $a_{x}$, and new value of $a_{li}$ becomes equal to old value of $a_{ri}$;\n- $2$ $l_{i}$ $r_{i}$ — reverse the segment $[l_{i}, r_{i}]$.\n\nThere are $m$ important indices in the array $b_{1}$, $b_{2}$, ..., $b_{m}$. For each $i$ such that $1 ≤ i ≤ m$ you have to output the number that will have index $b_{i}$ in the array after all queries are performed.",
    "tutorial": "One can guess from the constraits that complexity of the algorithm should be either $O(nm + q)$ or $O(qm)$. And there is a solution with the second one. Let's try to solve the reversed problem - answer what position will some number be at after all the queries. Check the impact of some query on position $pos$. Let the query be on some segment $[l, r]$. If $pos$ is outside this segment then you can skip it. Otherwise reverse will swap $a_{pos}$ and $a_{r - (pos - l)}$, shift will swap $a_{pos}$ and $a_{pos - 1}$ (if $pos = l$ then it will be $r$ instead of $(pos - 1)$). This task can be translated to the given one just by reversing the query list. Overall complexity: $O(qm)$. Obviously, you can also solve it with Cartesian tree online in $O(n+(q+m))\\log n)$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "863",
    "index": "E",
    "title": "Turn Off The TV",
    "statement": "Luba needs your help again! Luba has $n$ TV sets. She knows that $i$-th TV set will be working from moment of time $l_{i}$ till moment $r_{i}$, inclusive.\n\nLuba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of \\textbf{integer} moments of time when at least one of TV sets is working won't decrease. Luba will be very upset if she has to switch off a non-redundant TV set.\n\nHelp Luba by telling her the index of some redundant TV set. If there is no any, print -1.",
    "tutorial": "Firstly let's compress the moments of time. Note that storing only $l$ and $r$ isn't enough (consider pairs ($[1, 2], [3, 4]$) and ($[1, 2], [4, 5]$)), you also should take $(l - 1)$. Now moments of time are up to $6 \\cdot 10^{5}$. For every moment calculate the number of segments to cover it (make $cnt_{l} + = 1$ and $cnt_{r + 1} - = 1$ for each segment and take prefix sums over this array). Then let $pref_{i}$ be the number of moments of time covered by only one segment on some prefix up to $i$-th moment. And finally if for some segment $[l, r]$ from the input $pref_{r} - pref_{l - 1}$ is $0$ then you can safely delete this segment. Overall complexity: $O(n\\log n)$.",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "863",
    "index": "F",
    "title": "Almost Permutation",
    "statement": "Recently Ivan noticed an array $a$ while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug.\n\nIvan clearly remembers that there were $n$ elements in the array, and each element was not less than $1$ and not greater than $n$. Also he remembers $q$ facts about the array. There are two types of facts that Ivan remembers:\n\n- $1$ $l_{i}$ $r_{i}$ $v_{i}$ — for each $x$ such that $l_{i} ≤ x ≤ r_{i}$ $a_{x} ≥ v_{i}$;\n- $2$ $l_{i}$ $r_{i}$ $v_{i}$ — for each $x$ such that $l_{i} ≤ x ≤ r_{i}$ $a_{x} ≤ v_{i}$.\n\nAlso Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the $q$ facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the $cost$ of array as follows:\n\n$c o s t=\\sum_{i=1}^{n}(c n t(i))^{2}$, where $cnt(i)$ is the number of occurences of $i$ in the array.\n\nHelp Ivan to determine minimum possible $cost$ of the array that corresponds to the facts!",
    "tutorial": "This problem can be solved with mincost maxflow approach. Let's construct a following network: Construct a vertex for every number from $1$ to $n$. For each of these vertices add $n$ directed edges from the source to this vertex, the capacity of each edge will be $1$, and the costs will be $1, 3, 5, ..., 2n - 1$ (so pushing $k$ flow from the source to the vertex will cost exactly $k^{2}$); Also construct a vertex for every index of the array. For each number make add a directed edge with capacity $1$ and cost $0$ to every position in the array such that this number can be put into this position, and for every index make a directed edge from the vertex constructed for this index to the sink with capacity $1$ and cost $0$. Minimum cost maximum flow in this network will construct a suitable array with minimum cost, so the answer to the problem is minimum cost of maximum flow in the network.",
    "tags": [
      "flows"
    ],
    "rating": 2200
  },
  {
    "contest_id": "863",
    "index": "G",
    "title": "Graphic Settings",
    "statement": "Recently Ivan bought a new computer. Excited, he unpacked it and installed his favourite game. With his old computer Ivan had to choose the worst possible graphic settings (because otherwise the framerate would be really low), but now he wants to check, maybe his new computer can perform well even with the best possible graphics?\n\nThere are $m$ graphics parameters in the game. $i$-th parameter can be set to any positive integer from $1$ to $a_{i}$, and initially is set to $b_{i}$ ($b_{i} ≤ a_{i}$). So there are $p=\\prod_{i=1}^{m}a_{i}$ different combinations of parameters. Ivan can increase or decrease any of these parameters by $1$; after that the game will be restarted with new parameters (and Ivan will have the opportunity to check chosen combination of parameters).\n\nIvan wants to try all $p$ possible combinations. Also he wants to return to the initial settings after trying all combinations, because he thinks that initial settings can be somehow best suited for his hardware. But Ivan doesn't really want to make a lot of restarts.\n\nSo he wants you to tell the following:\n\n- If there exists a way to make exactly $p$ changes (each change either decreases or increases some parameter by $1$) to try all possible combinations and return to initial combination, then Ivan wants to know this way.\n- Otherwise, if there exists a way to make exactly $p - 1$ changes to try all possible combinations (including the initial one), then Ivan wants to know this way.\n\nHelp Ivan by showing him the way to change parameters!",
    "tutorial": "If $m = 1$, then everything is simple. Cycle exists if $a[1] = 2$, and path exists if $b[1] = 1$ or $b[1] = a[1]$. Let's consider the case when $m = 2$. Let's call the combination odd if the sum of parameters is odd for this combination, and even otherwise. It's easy to see that if $a[1]$ and $a[2]$ are both odd, then it's impossible to construct a cycle because the number of even combinations is greater than the number of odd combinations. Furthermore, it's impossible to construct a path if our initial combination is an odd one. Let's show how to construct answer in all other cases. Constructing a cycle is easy if at least one of $a[i]$ is even: And constructing a path can be divided into four cases. Starting point in corner: Start near the border: Both coordinates of starting point are even: Both coordinates are odd: So the case when $m = 2$ is solved. Now, if $m = 3$, then it can be reduced to $m = 2$ as follows: Suppose we have $a[1] = 3, a[2] = 3, a[3] = 3$. Then let's at first consider only combinations where the third parameter is equal to $1$: Then, if we need to add the combinations with third parameter equal to $2$, we mirror the \"layer\": And if we need to add the third \"layer\", we mirror it again: And so on. This way can also be used to reduce $m > 3$ to $m = 2$.",
    "tags": [],
    "rating": 3200
  },
  {
    "contest_id": "864",
    "index": "A",
    "title": "Fair Game",
    "statement": "Petya and Vasya decided to play a game. They have $n$ cards ($n$ is an even number). A single integer is written on each card.\n\nBefore the game Petya will choose an integer and after that Vasya will choose another integer (\\textbf{different} from the number that Petya chose). During the game each player takes all the cards with number he chose. For example, if Petya chose number $5$ before the game he will take all cards on which $5$ is written and if Vasya chose number $10$ before the game he will take all cards on which $10$ is written.\n\nThe game is considered fair if Petya and Vasya can take all $n$ cards, and the number of cards each player gets is the same.\n\nDetermine whether Petya and Vasya can choose integer numbers before the game so that the game is fair.",
    "tutorial": "This problem has many different solutions. Let's consider one of them. At first sort all numbers in non-descending order. Then the first $n / 2$ numbers must be equal to each other, the following $n / 2$ numbers must be equal to each other, and the number from the first half must be different from the number from the second half. So, if all conditions: $a[1] = a[n / 2]$ $a[n / 2 + 1] = a[n]$ $a[1]  \\neq  a[n]$ are met after sorting, the answer is <<YES>>. Vasya must choose before the game number $a[1]$ and Petya - $a[n]$ (or vice versa). If at least one from the described conditions is failed, the answer is <<NO>>.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "864",
    "index": "B",
    "title": "Polycarp and Letters",
    "statement": "Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string $s$ consisting only of lowercase and uppercase Latin letters.\n\nLet $A$ be a set of positions in the string. Let's call it pretty if following conditions are met:\n\n- letters on positions from $A$ in the string are all distinct and lowercase;\n- there are no uppercase letters in the string which are situated between positions from $A$ (i.e. there is no such $j$ that $s[j]$ is an uppercase letter, and $a_{1} < j < a_{2}$ for some $a_{1}$ and $a_{2}$ from $A$).\n\nWrite a program that will determine the maximum number of elements in a pretty set of positions.",
    "tutorial": "Let's solve the given problem in the following way. We will iterate through the letters in the string in order from left to right. If we are in position $pos$ and the next letter is uppercase we skip it. In the other case, we need to create $set$ and put letter $s_{pos}$ in it. After that we iterate through string to the right until we do not met uppercase letter or until the string does not ended. We put in $set$ each new lowercase letter. After we met uppercase letter (let position of this letter is $p$), or string is ended, we update the answer with the number of elements in $set$, and repeat described algorithm starting from position $p$.",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "864",
    "index": "C",
    "title": "Bus",
    "statement": "A bus moves along the coordinate line $Ox$ from the point $x = 0$ to the point $x = a$. After starting from the point $x = 0$, it reaches the point $x = a$, immediately turns back and then moves to the point $x = 0$. After returning to the point $x = 0$ it immediately goes back to the point $x = a$ and so on. Thus, the bus moves from $x = 0$ to $x = a$ and back. Moving from the point $x = 0$ to $x = a$ or from the point $x = a$ to $x = 0$ is called a bus journey. In total, the bus must make $k$ journeys.\n\nThe petrol tank of the bus can hold $b$ liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.\n\nThere is a gas station in point $x = f$. This point is between points $x = 0$ and $x = a$. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain $b$ liters of gasoline.\n\nWhat is the minimum number of times the bus needs to refuel at the point $x = f$ to make $k$ journeys? The first journey starts in the point $x = 0$.",
    "tutorial": "If the bus can not reach the first gas station (i.e. $b < f$) print -1. In the other case, the bus will reach the first gas station with $b - f$ liters in the gasoline tank. Then we need to iterate through journeys from $1$ to $k$ and calculate a value $need$ - how many liters of the gasoline needed to bus reach the next gas station. If $need$ more than $b$ - print -1, because it means that the bus can not reach the next gas station even with full gasoline tank. If $need$ more than current level of gasoline in the tank the bus needs to refuel. In the other case, refuel is not necessary. After described operations we need to move to the point of next gas station and recalculate the fuel level in the tank.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "864",
    "index": "D",
    "title": "Make a Permutation!",
    "statement": "Ivan has an array consisting of $n$ elements. Each of the elements is an integer from $1$ to $n$.\n\nRecently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from $1$ to $n$ was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.\n\nThus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.\n\nIn order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal — compare the second, and so on. If we have two permutations $x$ and $y$, then $x$ is lexicographically smaller if $x_{i} < y_{i}$, where $i$ is the first index in which the permutations $x$ and $y$ differ.\n\nDetermine the array Ivan will obtain after performing all the changes.",
    "tutorial": "We will use an array $cnt$ where we will store how many times the numbers from $1$ to $n$ met in the given array $a$. Put all numbers that never occur in the array $a$ in a vector $need$ - we must add this numbers in the array $a$ to make a permutation. We will add numbers from $need$ in ascending order because we want to get lexicographically minimal permutation. Let $pos$ is a pointer on the current number $need_{pos}$ which we need to add on the current move. Initially, $pos = 0$. We will iterate through the array $a$. Let the current number equals to $a_{i}$. If $cnt_{ai} = 1$, we move to the next number in the array. If we added not all numbers from $need$, and $a_{i} > need_{pos}$ or there already was $a_{i}$ on the prefix of the array (to check it we can use, for example, boolean array), then we put $need_{pos}$ in the current position, decrease $cnt_{ai}$ on one, increase $pos$ and answer on one. If we do not change anything on that step we mark that $a_{i}$ already was on the prefix of the array. After that we move to the next number in array $a$.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "864",
    "index": "E",
    "title": "Fire",
    "statement": "Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take $t_{i}$ seconds to save $i$-th item. In addition, for each item, he estimated the value of $d_{i}$ — the moment after which the item $i$ will be completely burned and will no longer be valuable for him at all. In particular, if $t_{i} ≥ d_{i}$, then $i$-th item cannot be saved.\n\nGiven the values $p_{i}$ for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item $a$ first, and then item $b$, then the item $a$ will be saved in $t_{a}$ seconds, and the item $b$ — in $t_{a} + t_{b}$ seconds after fire started.",
    "tutorial": "If Polycarp will save two items, it is more profitable to first save the one whose $d$ parameter is less. So, you can sort items by the parameter $d$. Let $dp_{i, j}$ be the maximum total value of items Polycarp can save by checking first $i - 1$ items in $j$ seconds. Here are two types of transitions. Polycarp can either save current item or skip it: $dp_{i + 1, j + ti} = max(dp_{i + 1, j + ti}, dp_{i, j} + p_{i})$, if $j + t_{i} < d_{i}$ $dp_{i + 1, j} = max(dp_{i + 1, j}, dp_{i, j})$ To restore the sequence of items Polycarp can save you can remember for each pair ($i, j$) whether you took a thing with the number $i - 1$ when updating the value $dp_{i, j}$. Overall complexity: $O(n \\cdot max_{1  \\le  i  \\le  n}d_{i})$.",
    "tags": [
      "dp",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "864",
    "index": "F",
    "title": "Cities Excursions",
    "statement": "There are $n$ cities in Berland. Some pairs of them are connected with $m$ directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities $(x, y)$ there is at most one road from $x$ to $y$.\n\nA path from city $s$ to city $t$ is a sequence of cities $p_{1}$, $p_{2}$, ... , $p_{k}$, where $p_{1} = s$, $p_{k} = t$, and there is a road from city $p_{i}$ to city $p_{i + 1}$ for each $i$ from $1$ to $k - 1$. The path can pass multiple times through each city except $t$. It can't pass through $t$ more than once.\n\nA path $p$ from $s$ to $t$ is ideal if it is the lexicographically minimal such path. In other words, $p$ is ideal path from $s$ to $t$ if for any other path $q$ from $s$ to $t$ $p_{i} < q_{i}$, where $i$ is the minimum integer such that $p_{i} ≠ q_{i}$.\n\nThere is a tourist agency in the country that offers $q$ unusual excursions: the $j$-th excursion starts at city $s_{j}$ and ends in city $t_{j}$.\n\nFor each pair $s_{j}$, $t_{j}$ help the agency to study the ideal path from $s_{j}$ to $t_{j}$. Note that it is possible that there is no ideal path from $s_{j}$ to $t_{j}$. This is possible due to two reasons:\n\n- there is no path from $s_{j}$ to $t_{j}$;\n- there are paths from $s_{j}$ to $t_{j}$, but for every such path $p$ there is another path $q$ from $s_{j}$ to $t_{j}$, such that $p_{i} > q_{i}$, where $i$ is the minimum integer for which $p_{i} ≠ q_{i}$.\n\nThe agency would like to know for the ideal path from $s_{j}$ to $t_{j}$ the $k_{j}$-th city in that path (on the way from $s_{j}$ to $t_{j}$).\n\nFor each triple $s_{j}$, $t_{j}$, $k_{j}$ ($1 ≤ j ≤ q$) find if there is an ideal path from $s_{j}$ to $t_{j}$ and print the $k_{j}$-th city in that path, if there is any.",
    "tutorial": "There is a direct graph. For each query, you need to find the $k_{j}$-th vertex in the lexicographically minimal path from $s_{j}$ to $t_{j}$. First group the queries on the vertex $t_{j}$ and find all vertices from which the vertex $t_{j}$ is achievable. For this you can invert all the arcs and run dfs from the vertex $t_{j}$. Now consider the query ($s_{j}$, $t_{j}$). For this query, you need to find the lexicographically minimal path from $s_{j}$ to $t_{j}$. If the vertex $t_{j}$ is not achievable from $s_{j}$, then the answer is '-1'. Otherwise, in the lexicographically minimal path $p$ from $s_{j}$ to $t_{j}$ the vertex $p_{i}$ ($i > 1$) is the minimal vertex from vertices $u$ such that there exists an arc ($p_{i - 1}, u$) and $t_{j}$ is achievable from $u$. Thus, we can build a new graph consisting of arcs satisfying the previous condition. Let us invert the arcs in this graph. Consider the vertices achievable from $t_{j}$ in this graph. They form an outgoing tree. Only for these vertices there is a lexicographically minimal path to $t_{j}$. The lexicographically minimal path from the vertex $s_{j}$ to the vertex $t_{j}$ is equal to the inverted path from $t_{j}$ to $s_{j}$ in this tree. So, we can use binary climb to get the $k$-th vertex on this path.",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "865",
    "index": "A",
    "title": "Save the problem!",
    "statement": "Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.\n\nPeople don't use cash as often as they used to. Having a credit card solves some of the hassles of cash, such as having to receive change when you can't form the exact amount of money needed to purchase an item. Typically cashiers will give you as few coins as possible in change, but they don't have to. For example, if your change is 30 cents, a cashier could give you a 5 cent piece and a 25 cent piece, or they could give you three 10 cent pieces, or ten 1 cent pieces, two 5 cent pieces, and one 10 cent piece. Altogether there are 18 different ways to make 30 cents using only 1 cent pieces, 5 cent pieces, 10 cent pieces, and 25 cent pieces. Two ways are considered different if they contain a different number of at least one type of coin. Given the denominations of the coins and an amount of change to be made, how many different ways are there to make change?\n\nAs we mentioned before, we lost all the test cases for this problem, so we're actually going to give you the number of ways, and want you to produce a test case for which the number of ways is the given number. There could be many ways to achieve this (we guarantee there's always at least one), so you can print any, as long as it meets the constraints described below.",
    "tutorial": "The simplest solution is to make the denominations always ${1, 2}$, and set $N = 2 \\cdot A - 1$. This provides exactly $A$ ways to make change, because you can choose any number of 2 cent pieces from $0$ to $A - 1$, then the rest must be 1 cent pieces.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1400
  },
  {
    "contest_id": "865",
    "index": "B",
    "title": "Ordering Pizza",
    "statement": "It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly $S$ slices.\n\nIt is known that the $i$-th contestant will eat $s_{i}$ slices of pizza, and gain $a_{i}$ happiness for each slice of type 1 pizza they eat, and $b_{i}$ happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?",
    "tutorial": "To simplify things, let's first add a dummy contestant who will eat all the \"leftover\" pizza but gain no happiness. Then let's sort the contestants by $b_{i} - a_{i}$. Now we can describe the optimal way to feed the contestants once the pizzas are already bought: we should line up the contestants in order, and line up the pizzas in order with the type 1 pizzas at the front and type 2 pizzas at the back. Then the first contestant should take the first $s_{1}$ slices, then the second contestant should take the next $s_{2}$ slices, and so on. Observe that there can be at most 1 pizza whose slices are taken by some contestants prefer type 1 and others prefer type 2. The remainder of pizzas will have only one type of preference (or possibly no preference), so those pizzas can be made of whichever type is preferred. For the final pizza we can check both possibilities and order the one that provides more happiness.",
    "tags": [
      "binary search",
      "sortings",
      "ternary search"
    ],
    "rating": 1900
  },
  {
    "contest_id": "865",
    "index": "C",
    "title": "Gotta Go Fast",
    "statement": "You're trying to set the record on your favorite video game. The game consists of $N$ levels, which must be completed sequentially in order to beat the game. You usually complete each level as fast as possible, but sometimes finish a level slower. Specifically, you will complete the $i$-th level in either $F_{i}$ seconds or $S_{i}$ seconds, where $F_{i} < S_{i}$, and there's a $P_{i}$ percent chance of completing it in $F_{i}$ seconds. After completing a level, you may decide to either continue the game and play the next level, or reset the game and start again from the first level. Both the decision and the action are instant.\n\nYour goal is to complete all the levels sequentially in at most $R$ total seconds. You want to minimize the expected amount of time playing before achieving that goal. If you continue and reset optimally, how much total time can you expect to spend playing?",
    "tutorial": "Let's change the game by adding a deterministic variant, which takes exactly $K$ seconds to complete. Initially, you play the original (random) game, but between levels (including before the first level), you're allowed to switch to the deterministic game (instead of restarting). You finish when you either complete the original game in at most $R$ seconds, or complete the deterministic game. This modified version is easier to analyze because there are no loops in the state graph. We can compute the optimal strategy by starting from the end and working backwards. For each level, and each amount of time it could have taken to reach this level, we can compute the expected time to completion for each of the 2 actions we can take, then perform whichever action is lower. Eventually we'll work our way back to the beginning of the game. If the optimal strategy is to immediately switch to the deterministic game, then the answer is greater than $K$. Otherwise it's less than $K$. This allows us to binary search the answer.",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "865",
    "index": "D",
    "title": "Buy Low Sell High",
    "statement": "You can perfectly predict the price of a certain stock for the next $N$ days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the $N$ days you would like to again own zero shares, but want to have as much money as possible.",
    "tutorial": "Let's introduce the idea of options to the problem. Instead of having to buy stock when it is at a given price, each day you gain the option to buy a share at that days price, which you can exercise at any time in the future. This way we only need to exercise an option in order to sell it, and we never need to \"hold\" any stock. Each day, 2 things happen. First, we get one more option. Second, if there is some option whose price is lower than today's price, we can be sure that we're going to exercise that option. What we don't know is when it's best to sell that option. However, we don't need to know when the best time is to sell - we can just sell it now, but give ourselves the option to buy it back at the price we just sold it for. Options can be stored in a heap since we only ever care about the cheapest one. Running time $O(N\\log N)$.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "865",
    "index": "E",
    "title": "Hex Dyslexia",
    "statement": "Copying large hexadecimal (base 16) strings by hand can be error prone, but that doesn't stop people from doing it. You've discovered a bug in the code that was likely caused by someone making a mistake when copying such a string. You suspect that whoever copied the string did not change any of the digits in the string, nor the length of the string, but may have permuted the digits arbitrarily. For example, if the original string was $0abc$ they may have changed it to $a0cb$ or $0bca$, but not $abc$ or $0abb$.\n\nUnfortunately you don't have access to the original string nor the copied string, but you do know the length of the strings and their numerical absolute difference. You will be given this difference as a hexadecimal string $S$, which has been zero-extended to be equal in length to the original and copied strings. Determine the smallest possible numerical value of the original string.",
    "tutorial": "First, observe that for a solution to exist, the sum of the digits in the input must be divisible by 15. This is because of the Casting out Nines rule, but applied in base 16. Furthermore, the sum of digits, when divided by 15, tells us how many carries must be performed when adding the answer to the input. We can try every possible set of positions for the carries, of which there are at most $\\textstyle{\\binom{13}{6}}=1716$ ways. Once the carries are fixed, for each position we know the exact difference between the original digit in that position and the permuted digit in that position. Now let's consider the permutation itself. Any permutation can be decomposed into cycles. Because we're looking for the minimum solution, it must be the case that every cycle in the permutation contains a zero. If there were a cycle without a zero, we could reduce every number in the cycle by the minimum value and produce a smaller solution. Furthermore, because every cycle contains a common element, that means the permutation can be written as a single cycle, since two cycles with a common element can be merged into one cycle using that element. To build such a cycle, we can start at a zero, and when we add a digit to the path we know based on its position what the difference must be between it and the previous digit. For each of the $2^{|S|}$ subsets of positions we can compute the minimum value that corresponds to a path through those positions. This step is $O(|S| \\cdot 2^{|S|})$. Side note: the answer, if it exists, always begins with 0. There are 2 cases to consider. If $S$ begins with an 'f', then the only possible solutions begin with a 0. Otherwise, the value given by $\\frac{\\mathrm{S}}{\\mathrm{L}5}$ is a valid solution, and starts with 0.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "graphs"
    ],
    "rating": 3300
  },
  {
    "contest_id": "865",
    "index": "F",
    "title": "Egg Roulette",
    "statement": "The game of Egg Roulette is played between two players. Initially $2R$ raw eggs and $2C$ cooked eggs are placed randomly into a carton. The shells are left on so there is no way to distinguish a raw egg from a cooked egg. One at a time, a player will select an egg, and then smash the egg on his/her forehead. If the egg was cooked, not much happens, but if the egg was raw, it will make quite the mess. This continues until one player has broken $R$ raw eggs, at which point that player is declared the loser and the other player wins.\n\nThe order in which players take turns can be described as a string of 'A' and 'B' characters, where the $i$-th character tells which player should choose the $i$-th egg. Traditionally, players take turns going one after the other. That is, they follow the ordering \"ABABAB...\". This isn't very fair though, because the second player will win more often than the first. We'd like you to find a better ordering for the players to take their turns. Let's define the unfairness of an ordering as the absolute difference between the first player's win probability and the second player's win probability. We're interested in orderings that minimize the unfairness. We only consider an ordering valid if it contains the same number of 'A's as 'B's.\n\nYou will also be given a string $S$ of length $2(R + C)$ containing only 'A', 'B', and '?' characters. An ordering is said to match $S$ if it only differs from $S$ in positions where $S$ contains a '?'. Of the valid orderings that minimize unfairness, how many match $S$?",
    "tutorial": "We can permute any prefix of an ordering containing at most $R - 1$ 'A's or $R - 1$ 'B's without changing the unfairness. This is because within that prefix one of the players cannot lose the game. This means that every ordering there is a unique ordering with the same unfairness that begins with exactly $R - 1$ 'A's followed by $R - 1$ 'B's and can be obtained by permuting such a prefix. Let's call this the canonical form of an ordering. To search for canonical forms, we need to consider the remaining $2 * (C + 1)$ turns. The constraints set this to at most 42, so we can split it into two halves, compute every possible ordering for the left $C + 1$ turns and right $C + 1$ turns, then use a meet-in-the-middle algorithm to find those that minimize unfairness. For each ordering in each half, we also need to compute how many corresponding orderings match the given string $S$. For the right half this is easy - every ordering either matches once or not at all. For the left half we have to consider non-canonical orderings. To compute this, we first need to find the longest prefix of the ordering that can be permuted. This is the longest prefix where every turn is the same as the first turn. Then we need to count how many 'A' and 'B' characters are in the ordering within that prefix, and how many 'A' and 'B' characters are in $S$ within that prefix. If there are more 'A' or 'B' characters in $S$ than the ordering, there are zero matches, otherwise the number of matches is given by a binomial coefficient. The total runtime is $O(C * 2^{C})$.",
    "tags": [
      "bitmasks",
      "brute force",
      "divide and conquer",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 3300
  },
  {
    "contest_id": "865",
    "index": "G",
    "title": "Flowers and Chocolate",
    "statement": "It's Piegirl's birthday soon, and Pieguy has decided to buy her a bouquet of flowers and a basket of chocolates.\n\nThe flower shop has $F$ different types of flowers available. The $i$-th type of flower always has exactly $p_{i}$ petals. Pieguy has decided to buy a bouquet consisting of exactly $N$ flowers. He may buy the same type of flower multiple times. The $N$ flowers are then arranged into a bouquet. The position of the flowers within a bouquet matters. You can think of a bouquet as an ordered list of flower types.\n\nThe chocolate shop sells chocolates in boxes. There are $B$ different types of boxes available. The $i$-th type of box contains $c_{i}$ pieces of chocolate. Pieguy can buy any number of boxes, and can buy the same type of box multiple times. He will then place these boxes into a basket. The position of the boxes within the basket matters. You can think of the basket as an ordered list of box types.\n\nPieguy knows that Piegirl likes to pluck a petal from a flower before eating each piece of chocolate. He would like to ensure that she eats the last piece of chocolate from the last box just after plucking the last petal from the last flower. That is, the total number of petals on all the flowers in the bouquet should equal the total number of pieces of chocolate in all the boxes in the basket.\n\nHow many different bouquet+basket combinations can Pieguy buy? The answer may be very large, so compute it modulo $1000000007 = 10^{9} + 7$.",
    "tutorial": "Let's first consider how to compute the number of ways to make a bouquet with exactly $K$ petals. Define a polynomial $P(x)=\\sum_{i=1}^{F}x^{p}$. Then if we compute $P(x)^{N}$, the coefficient of $x^{K}$ gives the number of ways to make a bouquet with exactly $K$ petals. This is because each possible bouquet produces a term with an exponent equal to its number of petals. Now lets consider how to compute the number of ways to make a basket with exactly $K$ chocolates. Define a polynomial $Q(x)=1-\\sum_{i=1}^{B}x^{c},$. Then if we compute $x^{-K}({\\mathrm{mod}}Q(x))$, the coefficient of $x^{0}$ gives the number of ways to make a basket with exactly $K$ chocolates. This can be derived from a Generating Function, but we will provide an alternate derivation. Consider the following algorithm for computing the number of ways to make a basket with $K$ chocolates: The final answer is the sum, over all values of $K$, of the number of bouquets with $K$ petals times the number of baskets with $K$ chocolates. The number of bouquets is given by the $x^{K}$ coefficient of $P(x)^{N}$, or equivalently, the $x^{ - K}$ coefficient of $P(x^{ - 1})^{N}$, and the number of baskets is given by the coefficient of $x^{0}$ of $x^{-K}({\\mathrm{mod}}Q(x))$. It follows that the answer is simply the coefficient of $x^{0}$ of $P(x^{-1})^{N}(\\mathrm{mod}Q(x))$. This can be computed using $O(\\log N+\\sum\\log p_{i})$ polynomial multiplications, each of which takes $O(max(c_{i})^{2})$ time, using naive multiplication, for a total runtime of $O((\\log N+\\sum\\log p_{i})\\cdot m a x(c_{i})^{2})$.",
    "tags": [
      "combinatorics",
      "math",
      "matrices"
    ],
    "rating": 3300
  },
  {
    "contest_id": "867",
    "index": "A",
    "title": "Between the Offices",
    "statement": "As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.\n\nYou prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't remember the number of flights you have made in either direction. However, for each of the last $n$ days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last $n$ days, or not.",
    "tutorial": "The answer is \"YES\" if the first character of the given string is 'S' and the last character is 'F', otherwise it's \"NO\".",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "868",
    "index": "A",
    "title": "Bark to Unlock",
    "statement": "As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.\n\nMu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark $n$ distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.",
    "tutorial": "If the answer is 'yes', then the password is either one of the given strings, or can be formed by taking the last letter and the first letter of some of the given strings (these strings can be the same). This can be checked straightforwardly in $O(n^{2})$ time.",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "868",
    "index": "B",
    "title": "Race Against Time",
    "statement": "Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other.\n\nThe entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time $h$ hours, $m$ minutes, $s$ seconds.\n\nLast time Misha talked with the coordinator at $t_{1}$ o'clock, so now he stands on the number $t_{1}$ on the clock face. The contest should be ready by $t_{2}$ o'clock. In the terms of paradox it means that Misha has to go to number $t_{2}$ somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction.\n\nClock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way).\n\nGiven the hands' positions, $t_{1}$, and $t_{2}$, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from $t_{1}$ to $t_{2}$ by the clock face.",
    "tutorial": "There are $12  \\times  60  \\times  60$ positions on the clock face that can be occupied by hands and start/finish positions. After marking the positions occupied by hands, we can straightforwardly try both directions of moving and check if we arrive to the finish without encountering any of the hands. Of course, there are many solutions that are more efficient.",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "868",
    "index": "C",
    "title": "Qualification Rounds",
    "statement": "Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of $n$ problems, and they want to select any non-empty subset of it as a problemset.\n\n$k$ experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.\n\nDetermine if Snark and Philip can make an interesting problemset!",
    "tutorial": "Let us show that if a solution exists, then there is always a solution that uses at most two problems. First, if there is a problem not known to any of the teams, that we can just take this only problem in the set. Next, suppose that there is a problem known only to one of the teams. If there is a problem this team doesn't know, then these two problems make a good set. Otherwise, the team knows all the problems, hence we cannot find a good set. In the rest case, each problem is known to at least two of the teams. Now, if there is a good set of problems, then each of the problems in the set must be known to exactly two of the teams. Indeed, let $p_{i}$ be the number of teams that knows the problem. If a good set contains $k$ problems, then we must have $\\textstyle\\sum p_{i}\\leq2k$, since otherwise we would have a team that knows more than half of the problems by pigeonhole principle. We also have $p_{i}  \\ge  2$, hence $\\textstyle\\sum p_{i}\\geq2k$, and only the case $p_{i} = 2$ is possible. At this point, if we can find a pair of problems with $p_{i} = 2$ and non-intersecting set of teams, then we are done. Otherwise, we can show that a good set does not exist by case analysis. To avoid $O(n^{2})$ solution, we can leave at most $2^{4}$ problems with unique types (sets of teams) and do pairwise checking on them. This solution has $O(n)$ complexity.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "868",
    "index": "D",
    "title": "Huge Strings",
    "statement": "You are given $n$ strings $s_{1}, s_{2}, ..., s_{n}$ consisting of characters $0$ and $1$. $m$ operations are performed, on each of them you concatenate two existing strings into a new one. On the $i$-th operation the concatenation $s_{ai}s_{bi}$ is saved into a new string $s_{n + i}$ (the operations are numbered starting from $1$). After each operation you need to find the maximum positive integer $k$ such that all possible strings consisting of $0$ and $1$ of length $k$ (there are $2^{k}$ such strings) are substrings of the new string. If there is no such $k$, print $0$.",
    "tutorial": "The key insight is that despite the strings can get very long, the answer for each string at most 9. Indeed, let us keep track of the number of distinct substrings of length 10 across all strings. Obviously, this number is at most 100 for the initial strings. Once we obtain a new string as a concatenation of two old ones, the only new substrings can arise on the border of these two strings, and there can be at most 9 of these substrings. Since $100 + 100 \\cdot 9 < 2^{10}$, it is impossible to construct a string with answer 10. Now, the solution is for each new string store the set of all distinct substrings of length at most 9. In order to construct this set for subsequent strings, we will have to store the first and the last 9 characters of each string (probably less if the string is shorter than 9). The number of operations is roughly $100 \\cdot 2^{10}$ if we store the distinct substrings in arrays, but can be made smaller if we use bitsets.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "868",
    "index": "E",
    "title": "Policeman and a Tree",
    "statement": "You are given a tree (a connected non-oriented graph without cycles) with vertices numbered from $1$ to $n$, and the length of the $i$-th edge is $w_{i}$. In the vertex $s$ there is a policeman, in the vertices $x_{1}, x_{2}, ..., x_{m}$ ($x_{j} ≠ s$) $m$ criminals are located.\n\nThe policeman can walk along the edges with speed $1$, the criminals can move with arbitrary large speed. If a criminal at some moment is at the same point as the policeman, he instantly gets caught by the policeman. Determine the time needed for the policeman to catch all criminals, assuming everybody behaves optimally (i.e. the criminals maximize that time, the policeman minimizes that time). Everybody knows positions of everybody else at any moment of time.",
    "tutorial": "Suppose that the policeman is moving from $v$ to $u$ via the tree edge. The criminals can now assume any positions in two halves of the tree (but cannot travel from one half to another). Let $dp_{e, k, a}$ be the resulting time to catch the criminals if the policeman have just started to travel along a (directed) edge $e$, there are $k$ criminals in total, and $a$ of them are in the half tree \"in front\" of the policeman. If the edge $e$ leads into a leaf of the tree, then the policeman catches everyone in this leaf, and his next step is to go back using the same edge. Otherwise, the criminals must have distributed optimally in the subtrees starting with edges $e_{1}, ..., e_{j}$. The policeman cannot win within time $T$ if there is a distribution $a_{1}, ..., a_{j}$ with $\\textstyle\\sum a_{i}=a$ such that $dp_{ei, k, ai} > T$ for every $i$. The optimal value of $T$ can be found with binary search: for a particular $T$ find the smallest $a_{i}$ such that $dp_{ei, k, ai} > T$, and check if $\\sum a_{i}\\leq a$. If this is the case, the criminals can distribute so that it will take $> T$ time to catch them. The total complexity of this solution is $O(n^{2}m^{2}\\log A)$, since we have $O(nm^{2})$ DP states, with each state having $O(n)$ transitions, and the last factor corresponding to binary search on the answer (assuming the answer is at most $A$).",
    "tags": [
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "868",
    "index": "F",
    "title": "Yet Another Minimization Problem",
    "statement": "You are given an array of $n$ integers $a_{1}... a_{n}$. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into $k$ non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.",
    "tutorial": "First, let us solve the problem in $O(kn^{2})$ time with a simple DP. Let $dp_{i, j}$ be the smallest cost of a partition of first $j$ elements into $i$ parts. Clearly, $dp_{i, j} = min_{j' < j}dp_{i - 1, j'} + cost(j', j)$. We can optimize the cost computation by moving $j'$ from right to left and maintaining frequency for each element, since by introducing an element $x$ into the segment, we increase the cost by $f_{x}$ - the number of occurences of $x$. To optimize this further, let us note that $p(j)$ - the (leftmost) optimal value of $j'$ for a particular $j$ is monotonous in $j$ on any step $i$. Indeed, suppose that $j_{1} < j_{2}$, and $dp_{i - 1, x} + cost(x, j_{2}) < dp_{i - 1, p(j1)} + cost(p(j_{1}), j_{2})$ for $x < p(j_{1})$. But $cost(x, j_{2}) - cost(p(j_{1}), j_{2})  \\ge  cost(x, j_{1}) - cost(p(j_{1}), j_{1})$, since introducing an element into a segment $[l, j_{2}]$ is at least as costly as introducing it into a segment $[l, j_{1}]$. Finally, $dp_{i - 1, p(j1)} - dp_{i - 1, x} > cost(x, j_{2}) - cost(p(j_{1}), j_{2})  \\ge  cost(x, j_{1}) - cost(p(j_{1}), j_{1})$, and $dp_{i - 1, p(j1)} + cost(p(j_{1}), j_{1}) > dp_{i - 1, x} + cost(x, j_{1})$, which contradicts the optimality of $p(j_{1})$. We can now apply the \"divide-and-conquer\" DP optimization: suppose that for a segment $[l, r]$ we know that $p(j)\\in[L,R]$ for each $j\\in[L,r]$. Choose $m$ as the midpoint of $[l, r]$ and find $p(m)$ by explicitly trying all values in $[L, R]$. We now proceed recursively into segments $[l, m - 1]$ with $p(j)\\in[L,M]$, and $[m + 1, r]$ with $p(j)\\in[M,R]$. Assuming unit cost for $cost(l, r)$ computation, one can show that the computation of all values of $dp_{i, j}$ for a particular $i$ takes $O(n\\log n)$ time. The final detail is that the time needed to compute $cost(l, r)$ can be made amortized constant (that is, $O(n\\log n)$ in total per layer) if we store the value $cost(p(m), m)$ from the parent segment, and add/remove segment elements one by one to obtain all subsequent values. The total complexity is now $O(k n\\log n)$.",
    "tags": [
      "divide and conquer",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "868",
    "index": "G",
    "title": "El Toll Caves",
    "statement": "The prehistoric caves of El Toll are located in Moià (Barcelona). You have heard that there is a treasure hidden in one of $n$ possible spots in the caves. You assume that each of the spots has probability $1 / n$ to contain a treasure.\n\nYou cannot get into the caves yourself, so you have constructed a robot that can search the caves for treasure. Each day you can instruct the robot to visit exactly $k$ distinct spots in the caves. If none of these spots contain treasure, then the robot will obviously return with empty hands. However, the caves are dark, and the robot may miss the treasure even when visiting the right spot. Formally, if one of the visited spots does contain a treasure, the robot will obtain it with probability $1 / 2$, otherwise it will return empty. Each time the robot searches the spot with the treasure, his success probability is independent of all previous tries (that is, the probability to miss the treasure after searching the right spot $x$ times is $1 / 2^{x}$).\n\nWhat is the expected number of days it will take to obtain the treasure if you choose optimal scheduling for the robot? Output the answer as a rational number modulo $10^{9} + 7$. Formally, let the answer be an irreducible fraction $P / Q$, then you have to output $P\\cdot Q^{-1}\\operatorname{mod}\\left(10^{9}+7\\right)$. It is guaranteed that $Q$ is not divisible by $10^{9} + 7$.",
    "tutorial": "Let $a_{i, j}$ be the number of times we have checked spot $j$ after $i$ days. Assuming that the spot $j$ contains the treasure, we can see that the expected number of days to find the treasure is $\\textstyle\\sum_{i=0}^{\\infty}2^{-a_{i,j}}$. Hence the unconditional expectation of the answer is ${\\frac{1}{n}}\\sum_{i=0}^{\\infty}\\sum_{j=0}^{n-1}2^{-a_{i,j}}$. This formula implies that the optimal strategy is to keep the visiting frequencies for all spots as close as possible, since the sum $\\textstyle\\sum_{j=0}^{n-1}2^{-n_{i,j}}$ is minimized under $\\textstyle{\\sum_{j=0}^{n-1}a_{i,j}=i k}$ when $a_{i, j}$ is the smoothest partition of $ik$. One implementation of this strategy is to visit spots $i k\\ {\\mathrm{mod}}\\ n,(i k+1)\\ {\\mathrm{mod}}\\ n,\\ldots,(i k+k-1)\\ {\\mathrm{mod}}\\ n$ on day $i$. Note further that this strategy always visits spots in batches of size $\\operatorname*{gcd}(n,k)$, hence we can divide both $n$ and $k$ by their GCD. Let us now consider an example of $n = 8$, $k = 3$. Let $E_{i}$ be the expected number of days to find the treasure in spot $i$ according to the optimal strategy above. We can see that $E_{3} = E_{0} + 1$, $E_{4} = E_{1} + 1$, $...$, $E_{7} = E_{4} + 1$, because a cell $j + k$ is visited on day $i$ iff the cell $j$ was visited on day $i - 1$. We also have $E_{0} = E_{5} / 2 + 1$ for the same reason except for that the cell $0$ was visited on the first day. This argument allows to express, say, $E_{0}$ as a linear expression of itself, and find the answer in $O(n)$ time. Another approach is to substitute the expressions until we cross the end of the sequence once: $E_{0} = E_{3} - 1 = E_{6} - 2 = 2E_{1} - 4$, also $E_{1} = 2E_{2} - 4$, but $E_{2} = E_{5} - 1 = 2E_{0} - 3$. We have obtained a similar set of linear relations of three spots with difference 2. To reduce to $n = 3$, $k = 2$ let us group $E_{j}$ by $j~{\\mathrm{mod}}~k$: $E_{0} + E_{3} + E_{6} = 3E_{0} + 3$, $E_{1} + E_{4} + E_{7} = 3E_{1} + 3$, $E_{2} + E_{5} = 2E_{2} + 1$. We can see that the total contribution of all $E_{j}$ for $j\\equiv x{\\mathrm{~(mod~}}k\\right)$ is a linear function in $E_{x}$, with coefficients depending on whether $x<\\eta\\operatorname{Inlol}k$. The main idea is that we continue this process with a different set of linear equations, effectively obtaining Euclid's algorithm that stores some additional data. Let us now describe the general solution. Assume that we have a set of variables $X_{0}, ..., X_{n - 1}$ satisfying $X_{i + k} = A(X_{i})$ for $i + k < n$, and $X_{i + k - n} = B(X_{i})$ for $i + k  \\ge  n$. Assume further that the answer $E=\\sum_{j=0}^{k-1}S_{1}(X_{j})+\\sum_{j=k}^{n-1}S_{2}(X_{j})$. Let $k^{\\prime}=n{\\mathrm{~mod~}}k$. For $j < k'$, by applying relations $A$ and $B$ successively we obtain $X_{j+k-k^{\\prime}}=B(A^{[n/k]}(X_{j}))$, hence $X_{j+k^{\\prime}-k}=A^{-\\left[n/k\\right]}(B^{-1}(X_{j}))$ for $j + k'  \\ge  k$. Similarly, $X_{j+k^{\\prime}}=A^{-\\,[n/k-1]}(B^{-1}(X_{j}))$ for $j + k' < k$. Also, $E=\\sum_{j=0}^{k^{\\prime}-1}S_{1}^{\\prime}(X_{j})+\\sum_{j=k^{\\prime}}^{k-1}S_{2}^{\\prime}(X_{j})$, where $S_{1}^{\\prime}=S_{1}+\\sum_{t=1}^{[n/k]}S_{2}(A^{t})$, $S_{2}^{\\prime}=S_{1}+\\sum_{t=1}^{\\left\\lfloor{n}/{k}-1\\right\\rfloor}S_{2}({A^{t}})$. It follows that the transformation $n  \\rightarrow  k$, $k  \\rightarrow  k'$, $A\\to A^{-\\left[n/k-1\\right]}(B^{-1}(X_{j}))$, $B\\rightarrow A^{-\\,[n/k]}(B^{-\\,1}(X_{j}))$, $S_{1}  \\rightarrow  S'_{1}$, $S_{2}  \\rightarrow  S'_{2}$ produces the same answer $E$. In the end of this process we have $n = 1$, $k = 0$, hence we have a linear equation $X_{0} = A(X_{0})$. After finding $X_{0}$, the answer is $S_{2}(X_{0})$. The number of reductions of the above type is $O(\\log n)$, with each transformation possible to do in $O(\\log(n/k))$ time, ($S_{1}  \\rightarrow  S'_{1}$ and $S_{2}  \\rightarrow  S'_{2}$ require fast matrix exponentation). The total number of operations is $O(\\log n)$ per test.",
    "tags": [
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "869",
    "index": "A",
    "title": "The Artful Expedient",
    "statement": "Rock... Paper!\n\nAfter Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.\n\nA positive integer $n$ is decided first. Both Koyomi and Karen independently choose $n$ distinct positive integers, denoted by $x_{1}, x_{2}, ..., x_{n}$ and $y_{1}, y_{2}, ..., y_{n}$ respectively. They reveal their sequences, and repeat until \\textbf{all of $2n$ integers become distinct}, which is the only final state to be kept and considered.\n\nThen they count the number of ordered pairs $(i, j)$ ($1 ≤ i, j ≤ n$) such that the value $x_{i}$ xor $y_{j}$ equals to one of the $2n$ integers. Here xor means the bitwise exclusive or operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.\n\nKaren claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.",
    "tutorial": "First approach: Optimize the straightforward solution. The $O(n^{3})$ solution is to iterate through $(i, j)$ pairs, then iterate over $k$ and check whether $x_{i}$ xor $y_{j}$ equals either $x_{k}$ or $y_{k}$. But it doesn't fit into the time limit. We try to get rid of the $k$ loop and make the check faster. Here's the insight: we create an array $a$, and let $a[i]$ denote \"whether value $i$ appears in the given $2n$ integers\". In this way we can make the check comsume $O(1)$ time (with $O(n)$ preprocessing for $a$), resulting in an $O(n^{2})$ overall time complexity. Please see the model solution for an implementation. A detail worth mentioning is that $x_{i}$ xor $y_{j}$ may exceed $2 \\cdot 10^{6}$ and become as large as $2097152 = 2^{21}$. Thus the array should be of size $2097152$ instead of $2 \\cdot 10^{6}$ and if not, invalid memory access may take place. Second approach: Believe in magic. Let's forget about all loops and algorithmic stuff and start fresh. What's the parity of the answer? Looking at the samples again, do note that Karen scores two consecutive wins. The fact is that, Karen always wins. Proof. For any pair $(i, j)$, if an index $k$ exists such that $x_{i}$ xor $y_{j}$ $= x_{k}$, then this $k$ is unique since all $2n$ integers are distinct. Then, pair $(k, j)$ also fulfills the requirement, since $x_{k}$ xor $y_{j}$ $= x_{i}$. The similar goes for cases where $x_{i}$ xor $y_{j}$ $= y_{k}$. Therefore, each valid pair satisfying the requirement can be mapped to exactly another valid pair, and the mapping is unique and involutory (that is, $f(f(u)) = u$). Thus, the number of such pairs is always even. So, Karen still claims her constant win. Maybe it's Koyomi's obscure reconciliation ;)",
    "code": "#include <stdio.h>\n\nint main()\n{\n    puts(\"Karen\");\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "869",
    "index": "B",
    "title": "The Eternal Immortality",
    "statement": "Even if the world is full of counterfeits, I still regard it as wonderful.\n\nPile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.\n\nThe phoenix has a rather long lifespan, and reincarnates itself once every $a!$ years. Here $a!$ denotes the factorial of integer $a$, that is, $a! = 1 × 2 × ... × a$. Specifically, $0! = 1$.\n\nKoyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of $b!$ years, that is, $\\frac{\\partial!}{\\alpha!}$. Note that when $b ≥ a$ this value is always integer.\n\nAs the answer can be quite large, it would be enough for Koyomi just to know \\textbf{the last digit of the answer in decimal representation}. And you're here to provide Koyomi with this knowledge.",
    "tutorial": "Multiply instead of divide. What happens to the last digit when multiplying? $\\frac{\\partial!}{\\alpha!}$ equals $(a + 1) \\cdot (a + 2) \\cdot ... \\cdot (b - 1) \\cdot b$. Consider the multiplicands one by one, and when the last digit of the product becomes $0$, it stays unchanged from then on. Hence we can multiply the integers one by one, only preserving the last digit (take it modulo $10$ whenever possible), and stop when it becomes $0$. It's obvious that at most $10$ multiplications are needed before stopping, and it's not hard to prove a tighter upper bound of $5$. Take care, integer overflow can emerge everywhere!",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nlong long L,R;\nint ans;\nint main()\n{\n\tscanf(\"%lld%lld\",&L,&R);\n\tif (R-L>=10) printf(\"%d\\n\",0);\n\telse\n\t{\n\t\tans=1;\n\t\tfor (long long i=L+1;i<=R;i++)\n\t\t\tans=(1LL*ans*(i%10))%10;\n\t\tprintf(\"%d\\n\",ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "869",
    "index": "C",
    "title": "The Intriguing Obsession",
    "statement": "— This is not playing but duty as allies of justice, Nii-chan!\n\n— Not allies but justice itself, Onii-chan!\n\nWith hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands!\n\nThere are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of $a$, $b$ and $c$ distinct islands respectively.\n\nBridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length $1$. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is \\textbf{at least $3$}, apparently in order to prevent oddities from spreading quickly inside a cluster.\n\nThe Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo $998 244 353$. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other.",
    "tutorial": "First step: Consider what does at least 3 mean? 'The shortest distance between them is at least 3' means it can't be 1 or 2. The distance can't be 1 means that no two islands with the same colour can be straightly connected. The distance can't be 2 means that for each island, no two islands with the same colour can both be straightly connected with it. Second step: Make the graph into 3 parts. The bridges between red and blue islands have no effection with those between red and purple ones. Therefore, we can make the graph into 3 parts: one between red and blue, one between blue and purple, and the last one between red and purple. Suppose there are $A$ red islands and $B$ blue islands, and there are $k$ bridges between them. Then, the answer will be $\\textstyle{\\binom{A}{k}}{\\binom{B}{k}}(k!)$. So, the answer of bridges between red and blue ones should be $\\sum_{k=0}^{\\operatorname*{min}(A,B)}\\left({\\begin{array}{l}{A}\\\\ {k}\\end{array}}\\right)\\left(k!\\right)$ Therefore, the final answer should be $ans1 * ans2 * ans3$. You can calculate it with an $O(n^{2})$ brute force. Also, you can make it into $O(n)$.",
    "code": "#include <bits/stdc++.h>\n#define Maxn 5007\n#define modp 998244353\nint p[Maxn][Maxn];\nint pre[Maxn];\nint a,b,c;\nint solve(int x,int y)\n{\n\tint res=0;\n\tfor (int k=0;k<=x&&k<=y;k++)\n\t{\n\t\tint del=pre[k];\n\t\tdel=(1LL*del*p[x][k])%modp;\n\t\tdel=(1LL*del*p[y][k])%modp;\n\t\tres=(res+del)%modp;\n\t}\n\treturn res;\n}\nint main()\n{\n\tscanf(\"%d%d%d\",&a,&b,&c);\n\tmemset(p,0,sizeof(p));\n\tp[0][0]=1;\n\tfor (int i=1;i<=5000;i++)\n\t{\n\t\tp[i][0]=1;\n\t\tfor (int j=1;j<=i;j++)\n\t\t\tp[i][j]=(p[i-1][j-1]+p[i-1][j])%modp;\n\t}\n\tmemset(pre,0,sizeof(pre));\n\tpre[0]=1;\n\tfor (int i=1;i<=5000;i++)\n\t\tpre[i]=(1LL*pre[i-1]*i)%modp;\n\tint ans=1;\n\tans=(1LL*ans*solve(a,b))%modp;\n\tans=(1LL*ans*solve(b,c))%modp;\n\tans=(1LL*ans*solve(a,c))%modp;\n\tprintf(\"%d\\n\",ans);\n\treturn 0;\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "869",
    "index": "D",
    "title": "The Overdosing Ubiquity",
    "statement": "The fundamental prerequisite for justice is not to be correct, but to be strong. That's why justice is always the victor.\n\nThe Cinderswarm Bee. Koyomi knows it.\n\nThe bees, according to their nature, live in a tree. To be more specific, a \\underline{complete binary tree} with $n$ nodes numbered from $1$ to $n$. The node numbered $1$ is the root, and the parent of the $i$-th ($2 ≤ i ≤ n$) node is $\\textstyle{\\left|{\\frac{1}{2}}\\right|}$. Note that, however, all edges in the tree are undirected.\n\nKoyomi adds $m$ extra undirected edges to the tree, creating more complication to trick the bees. And you're here to count the number of \\underline{simple paths} in the resulting graph, modulo $10^{9} + 7$. A \\underline{simple path} is an alternating sequence of adjacent nodes and undirected edges, which begins and ends with nodes and does not contain any node more than once. Do note that a single node is also considered a valid \\underline{simple path} under this definition. Please refer to the examples and notes below for instances.",
    "tutorial": "Iterate over all possible combination, order and direction of extra edges. There are no more than $O(m!2^{m})$ ways to go through these extra edges, each of which will bring us at most $O(n^{2})$ more simple paths. If we count all these simple paths using simple depth-first search, the time complexity will be $O(n^{2}m!2^{m})$, which is the same as the order of the answer. However, we can reduce the original graph to a pretty small one, for example, by keeping all the nodes on some cycle and compressing the others. Noticing that the longest simple path on a complete binary tree is just $O(\\log n)$, the compressed graph will contain at most $O(m\\log n)$ nodes. Running simple depth-first search on such a small graph will lead to an $O((m\\log n)^{2}m!2^{m})$ solution, which fits in with the small constraint of $m$ and works really fast in practice.",
    "code": "#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<cmath>\n#include<iostream>\n#include<algorithm>\n#include<map>\n\nusing namespace std;\n\nconst int MAXN=255;\n\nconst int Mod=1000000007;\ninline void add_mod(int &x,int y)\n{\n    x=(x+y<Mod ? x+y : x+y-Mod);\n}\n\nint u[MAXN],v[MAXN];\n\nmap<int,int> mp;\ninline int get_id(int x)\n{\n    if(!mp[x])mp[x]=(int)mp.size();\n    return mp[x];\n}\n\nvector<int> e[MAXN];\nvoid add_edge(int u,int v)\n{\n    e[u].push_back(v);\n    e[v].push_back(u);\n}\n\ninline int cal_size(int u,int n,int d)\n{\n    int t=u,c=0,res;\n    while(t)c++,t>>=1;\n    res=(1<<(d-c+1))-1,t=c;\n    while(t<d)t++,u=u<<1|1;\n    return res-max(min(u-n,1<<(d-c)),0);\n}\n\nint num[MAXN];\nvoid pre_dp(int u,int f)\n{\n    for(auto &v:e[u])\n    {\n        if(v==f)continue;\n        num[u]-=num[v];\n        pre_dp(v,u);\n    }\n}\n\nint vis[MAXN];\nvoid dfs(int u,int &tot)\n{\n    add_mod(tot,num[u]);\n    vis[u]=1;\n    for(auto &v:e[u])\n        if(!vis[v])dfs(v,tot);\n    vis[u]=0;\n}\n\nint main()\n{\n    int n,m,d=0;\n    scanf(\"%d%d\",&n,&m);\n    while((1<<d)<=n)d++;\n    get_id(1);\n    for(int i=0;i<m;i++)\n    {\n        scanf(\"%d%d\",&u[i],&v[i]);\n        int t=u[i];\n        while(t)get_id(t),t>>=1;\n        t=v[i];\n        while(t)get_id(t),t>>=1;\n    }\n    for(auto &t:mp)\n    {\n        int u=t.first,id=t.second;\n        if(u>1)add_edge(get_id(u),get_id(u>>1));\n        num[id]=cal_size(u,n,d);\n    }\n    pre_dp(1,0);\n    for(int i=0;i<m;i++)\n        add_edge(get_id(u[i]),get_id(v[i]));\n    int res=0;\n    for(int i=1;i<=(int)mp.size();i++)\n    {\n        int tot=0;\n        dfs(i,tot);\n        add_mod(res,1LL*tot*num[i]%Mod);\n    }\n    printf(\"%d\\n\",res);\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "869",
    "index": "E",
    "title": "The Untended Antiquity",
    "statement": "Adieu l'ami.\n\nKoyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.\n\nThe space is represented by a rectangular grid of $n × m$ cells, arranged into $n$ rows and $m$ columns. The $c$-th cell in the $r$-th row is denoted by $(r, c)$.\n\nOshino places and removes barriers \\textbf{around} rectangular areas of cells. Specifically, an action denoted by \"$1 r_{1} c_{1} r_{2} c_{2}$\" means Oshino's placing barriers around a rectangle with two corners being $(r_{1}, c_{1})$ and $(r_{2}, c_{2})$ and sides parallel to squares sides. Similarly, \"$2 r_{1} c_{1} r_{2} c_{2}$\" means Oshino's removing barriers around the rectangle. \\textbf{Oshino ensures that no barriers staying on the ground share any common points, nor do they intersect with boundaries of the $n × m$ area.}\n\nSometimes Koyomi tries to walk from one cell to another carefully without striding over barriers, in order to avoid damaging various items on the ground. \"$3 r_{1} c_{1} r_{2} c_{2}$\" means that Koyomi tries to walk from $(r_{1}, c_{1})$ to $(r_{2}, c_{2})$ without crossing barriers.\n\nAnd you're here to tell Koyomi the feasibility of each of his attempts.",
    "tutorial": "The barriers share no common points. Therefore two cells are connected iff the set of barriers containing each of them are the same. The reason is that no barrier can divide a barrier of larger area into two separate regions that are not reachable from each other. The inner barrier can't be any larger in either side (otherwise there will be common points), and thus cannot divide the outer one. The inner barrier can't be any larger in either side (otherwise there will be common points), and thus cannot divide the outer one. First approach: 2D segment tree or quadtree. In a 2D segment tree or quadtree, each node $u$ represents a rectangular area. On each node we use an array list (std::vector) to keep track of all barriers fully containing $u$'s represented rectangle. Each newly-added barrier will cause $O(\\log^{2}n)$ insertions and each removal will result in $O(\\log^{2}n)$ deletions. For queries, iterate over the list in all involved nodes (there are $O(\\log n)$ of them). It can be proved that a node of size $w  \\times  h$ with a corner $(r, c)$ can be contained in most $min{r - 1, c - 1, n - (r + h), m - (c + w)}$ barriers. Hence it can be shown that in the worst cases, a single query involves at most ${\\textstyle{\\frac{1}{2}}}\\cdot n\\cdot(\\log_{2}n-1)$ elements in all lists. The total space complexity is $O(n^{2}\\cdot\\log^{2}n)$, and time complexity is $O(q\\cdot n\\cdot\\log n)$, both with a small constant multiplier (less than $1 / 4$ for space and much less than $1 / 2$ for time), efficient enough to pass all tests. Tester's implementation works in under 800 ms in worst cases, so we decided to let such solutions pass. Also, a little randomization in partitioning may help avoid constructed worst cases and further reduce maximum running time on tests. Second approach: Randomization. We need to quickly check whether two sets are identical. Assign a random hash value to each barrier and use their sum or xor sum as the hash of the set. In this way, the creation/deletion of a barrier is equivalent to adding/subtracting/xoring a value to all cells in a rectangular region, and a query is equivalent to finding the values of two cells. The cells are reachable from each other iff their values are the same. This can be done efficiently with a 2D segment tree or 2D Fenwick tree, in $O(q\\cdot\\log^{2}n)$ time. With randomized values being 64-bit unsigned integers, the probability of a collision is $2^{ - 64}$. The probability to give $10^{5}$ correct answers is $(1 - 2^{ - 64})^{100 000}  \\approx  1 - 2^{ - 47}$. And the probability to give correct answers on all tests is approximately $1 - 2^{ - 40}$. If you're still afraid of collisions, you can: either (1) use a pair of 64-bit integers as the hash value, or (2) use the problemsetter's birthday, $20001206$, as the seed (kidding, lol). We are aware that a few implementations with sub-optimal time complexities passed all the tests, though we spared no effort in the preparation process to come up with various cases. We really look forward to doing better to eliminate all such possibilities in the future. Cheers! Tommyr7: I do hope you all enjoyed yourselves during the contest. See you next time!",
    "code": "#include <bits/stdc++.h>\n#define Maxn 2507\nusing namespace std;\nint n,m,q;\nmap<pair<pair<int,int>,pair<int,int> >,pair<unsigned long long,unsigned long long> > mp;\npair<unsigned long long,unsigned long long> s[Maxn][Maxn];\nvoid add(int x,int y,pair<unsigned long long,unsigned long long> del)\n{\n\tfor (int kx=x;kx<=2503;kx+=kx&(-kx))\n\t\tfor (int ky=y;ky<=2503;ky+=ky&(-ky))\n\t\t{\n\t\t\ts[kx][ky].first+=del.first;\n\t\t\ts[kx][ky].second+=del.second;\n\t\t}\n}\npair<unsigned long long,unsigned long long> query(int x,int y)\n{\n\tpair<unsigned long long,unsigned long long> res=make_pair(0,0);\n\tfor (int kx=x;kx;kx-=kx&(-kx))\n\t\tfor (int ky=y;ky;ky-=ky&(-ky))\n\t\t{\n\t\t\tres.first+=s[kx][ky].first;\n\t\t\tres.second+=s[kx][ky].second;\n\t\t}\n\treturn res;\n}\nint main()\n{\n\tscanf(\"%d%d%d\",&n,&m,&q);\n\tmemset(s,0,sizeof(s));\n\tsrand(20001206);\n\tmp.clear();\n\tfor (int i=1;i<=q;i++)\n\t{\n\t\tint t,r1,c1,r2,c2;\n\t\tscanf(\"%d%d%d%d%d\",&t,&r1,&c1,&r2,&c2);\n\t\tpair<unsigned long long,unsigned long long> del,udel;\n\t\tif (t==1)\n\t\t{\n\t\t\tdel.first=rand();\n\t\t\tdel.second=rand();\n\t\t\tudel=make_pair(-del.first,-del.second);\n\t\t\tmp[make_pair(make_pair(r1,c1),make_pair(r2,c2))]=del;\n\t\t\tadd(r1,c1,del);\n\t\t\tadd(r1,c2+1,udel);\n\t\t\tadd(r2+1,c1,udel);\n\t\t\tadd(r2+1,c2+1,del);\n\t\t} else if (t==2)\n\t\t{\n\t\t\tdel=mp[make_pair(make_pair(r1,c1),make_pair(r2,c2))];\n\t\t\tmp[make_pair(make_pair(r1,c1),make_pair(r2,c2))]=make_pair(0,0);\n\t\t\tudel=make_pair(-del.first,-del.second);\n\t\t\tadd(r1,c1,udel);\n\t\t\tadd(r1,c2+1,del);\n\t\t\tadd(r2+1,c1,del);\n\t\t\tadd(r2+1,c2+1,udel);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdel=query(r1,c1);\n\t\t\tudel=query(r2,c2);\n\t\t\tif (del==udel) printf(\"Yes\\n\"); else printf(\"No\\n\");\n\t\t}\n\t}\n\treturn 0;\n}\n\n",
    "tags": [
      "data structures",
      "hashing"
    ],
    "rating": 2400
  },
  {
    "contest_id": "870",
    "index": "A",
    "title": "Search for Pretty Integers",
    "statement": "You are given two lists of non-zero digits.\n\nLet's call an integer pretty if its (base $10$) representation has at least one digit from the first list and at least one digit from the second list. What is the smallest positive pretty integer?",
    "tutorial": "Note that the length of the answer does not exceed two because we can take one number from the first list and one number from the second lists and make up of them a pretty number. So we need to check two cases: 1) Iterate through the digits from the first list and check if digit belongs to the second list too. Make up the number of this digit. 2) Iterate through the numbers from the first list and from the second list. Make up the number of this two digits. There are two ways: digit from the first list, then from the second list and vice versa. Then you should choose the minimal number.",
    "code": "n, m = [int(i) for i in input().split()]\na = set(int(i) for i in input().split())\nb = set(int(i) for i in input().split())\nif a & b:\n    print(min(a & b))\nelse:\n    x = min(a)\n    y = min(b)\n    print(min(x, y), max(x, y), sep='')",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "870",
    "index": "B",
    "title": "Maximum of Maximums of Minimums",
    "statement": "You are given an array $a_{1}, a_{2}, ..., a_{n}$ consisting of $n$ integers, and an integer $k$. You have to split the array into exactly $k$ non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the $k$ obtained minimums. What is the maximum possible integer you can get?\n\nDefinitions of subsegment and array splitting are given in notes.",
    "tutorial": "To solve the problem, we need to consider three cases: $k  \\ge  3:$ then let $pos_max$ be the position of the element with the maximum value, then it is always possible to divide the array into subsegments so that one subsegment contains only this number, so the answer to the problem is $a_{pos_max}$. $k = 2:$ then all possible partitions are some prefix of nonzero length and coresponding suffix of nonzero length. You can iterate through all positions of the prefix end, and calculate the answer for this fixed partition, that equals to maximum of minima on the prefix and on the suffix. Minimum value for all suffixes and prefixes can be counted in advance. The answer is the maximum of the answers for all possible partitions. *Also it can be proved that for $k = 2$ the answer is the maximum of the first and last element. $k = 1:$ then the only possible partition is one segment equal to the whole array. So the answer is the minimum value on the whole array.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = (int)1e5;\n \nint a[MAXN];\nint n, k;\nint suf_min[MAXN];\n \nint main()\n{\n\tcin >> n >> k;\n\tfor (int i = 0; i < n; ++i)\n\t\tcin >> a[i];\n\tif (k == 1)\n\t{\n\t\tint ans = a[0];\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tans = min(ans, a[i]);\n\t\tcout << ans << endl;\n\t}\n\telse\n\tif (k == 2)\n\t{\n\t\tsuf_min[n - 1] = a[n - 1];\n\t\tfor (int i = n - 2; i >= 0; --i)\n\t\t\tsuf_min[i] = min(a[i], suf_min[i + 1]);\n\t\tint pref_min = a[0];\n\t\tint ans = max(pref_min, suf_min[1]);\n\t\tfor (int i = 1; i < n - 1; ++i)\n\t\t{\n\t\t\tpref_min = min(pref_min, a[i]);\n\t\t\tans = max(ans, max(suf_min[i + 1], pref_min));\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\telse\n\t{\n\t\tint ans = a[0];\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tans = max(ans, a[i]);\n\t\tcout << ans << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "870",
    "index": "C",
    "title": "Maximum splitting",
    "statement": "You are given several queries. In the $i$-th query you are given a single positive integer $n_{i}$. You are to represent $n_{i}$ as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.\n\nAn integer greater than $1$ is composite, if it is not prime, i.e. if it has positive divisors not equal to $1$ and the integer itself.",
    "tutorial": "Note that minimal composite number is equal to 4. So it is quite logical that there will be a lot of 4 in splitting of big numbers. Let's write for small numbers ($1  \\le  M  \\le  n$) $dp_{n}$ - number of composite summands in splitting of $n$. If our query $n$ is small number let's print $dp_{n}$. Else let's find minimal number $k$ such that $n - 4 \\cdot k$ is small number. Then print $k + dp_{n - 4 \\cdot k}$. We can find $dp_{n}$ in $O(M^{2})$ or any other reasonable complexity. We even can find all $dp_{n}$ by hands if we set $M$ to $15$ or something like that (it will be proved later that $15$ is enough). So now we have right solution but it is not obvious why this solution works. Proof (not very beautiful but such thoughts can lead to correct solution): Let's find answer for all numbers from $1$ to $15$. Several observations: 1) Only 4, 6, 9 occurs in optimal splittings. 2) It is not beneficial to use 6 or 9 more than once because $6 + 6 = 4 + 4 + 4$, $9 + 9 = 6 + 6 + 6$. 3) 12, 13, 14, 15 have valid splittings. Let's prove that all numbers that are greater than 15 will have 4 in optimal splitting. Let's guess that it is incorrect. If minimal number in splitting is neither 4 nor 6 nor 9 than this number will have some non-trivial splitting by induction. If this number either 6 or 9 and we will decrease query by this number then we will sooner or later get some small number (which is less or equal than $15$). There is no splitting of small numbers or it contains 4 in splitting (and it contradicts with minimality of the first number) or it contains 6 and 9. So we have contradiction in all cases. We can subtract 4 from any big query and our solution is correct.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int maxn = 16;\n \nsigned main() {\n    ios_base::sync_with_stdio(false); cin.tie(0);\n \n    vector<int> ans(maxn, -1);\n    ans[0] = 0;\n    for (int i = 1; i < maxn; ++i) {\n        for (auto j: vector<int>{4, 6, 9}) {\n            if (i >= j && ans[i - j] != -1) {\n                ans[i] = max(ans[i], ans[i - j] + 1);\n            }\n        }\n    }\n \n    int q;\n    cin >> q;\n    for (int i = 0; i < q; ++i) {\n        int n;\n        cin >> n;\n        if (n < maxn) {\n            cout << ans[n] << '\\n';\n        } else {\n            int t = (n - maxn) / 4 + 1;\n            cout << t + ans[n - 4 * t] << '\\n';\n        }\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "870",
    "index": "D",
    "title": "Something with XOR Queries",
    "statement": "This is an interactive problem.\n\nJury has hidden a permutation $p$ of integers from $0$ to $n - 1$. You know only the length $n$. Remind that in permutation all integers are distinct.\n\nLet $b$ be the inverse permutation for $p$, i.e. $p_{bi} = i$ for all $i$. The only thing you can do is to ask xor of elements $p_{i}$ and $b_{j}$, printing two indices $i$ and $j$ (not necessarily distinct). As a result of the query with indices $i$ and $j$ you'll get the value $p_{i}\\oplus b_{j}$, where $\\mathbb{C}$ denotes the xor operation. You can find the description of xor operation in notes.\n\nNote that some permutations can remain indistinguishable from the hidden one, even if you make all possible $n^{2}$ queries. You have to compute the number of permutations indistinguishable from the hidden one, and print one of such permutations, making no more than $2n$ queries.\n\nThe hidden permutation does not depend on your queries.",
    "tutorial": "The statement: those and only those permutations whose answers to the queries $(0, i)$ and $(i, 0)$ for all $i$ coincide with the answers given to the program, are suitable for all possible queries. The proof: $p_{i}\\oplus b_{j}=(p_{i}\\oplus b_{0})\\oplus(p_{0}\\oplus b_{j})\\oplus(p_{0}\\oplus b_{0})$, which means that with the answers to the queries $(0, i)$ and $(i, 0)$ you can restore the answers to all other queries. If we fix the value $b_{0}$, then we can restore the whole permutation, since we know the answers to the queries $(i, 0)$, and $p_{i}=(p_{i}\\oplus b_{0})\\oplus b_{0}$. You can iterate through the value $b_{0}$, restore the whole permutation, and if there were no contradictions in it (that is, every number from $0$ to $n - 1$ occurs $1$ time) and for all $i$ values $p_{0}\\oplus b_{i}$ and $p_{i}\\oplus b_{0}$ coincide with the answers given to the program, then this permutation is indistinguishable from the hidden permutation. The answer is the number of such permutations, and one of such permutations.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = (int)5e3;\nconst int MAX_QUESTIONS_CNT = 2 * MAXN;\n \nconst int E_QUESTIONS_LIMIT_EXCEEDED =\t\t\t \t1;\nconst int E_SMART_TEST_NOT_EQUAL_STUPID_TEST = \t\t2;\nconst int E_WA = \t\t\t\t\t\t\t\t\t3;\n \nint n;\nint P[MAXN], B[MAXN], ANSWERS_CNT;\nint questions[MAXN][MAXN];\nint questions_cnt;\n \nint que(int x, int y)\n{\n\tif (questions[x][y] != -1)\n\t\treturn questions[x][y];\n\t++questions_cnt;\n\tif (questions_cnt > MAX_QUESTIONS_CNT)\n\t\texit(E_QUESTIONS_LIMIT_EXCEEDED);\n\tcout << \"? \" << x << \" \" << y << \"\\n\";\n\tcout.flush();\n\tint res;\n\tcin >> res;\n\tquestions[x][y] = res;\n\treturn res;\n}\n \nint smart_test(vector <int>& p)\n{\n\tint n = p.size();\n\tvector <int> b(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tb[p[i]] = i;\n\tfor (int i = 0; i < n; ++i)\n\t\tif (que(0, i) != (p[0] ^ b[i]))\n\t\t\treturn 0;\n\tfor (int i = 0; i < n; ++i)\n\t\tif (que(i, 0) != (p[i] ^ b[0]))\n\t\t\treturn 0;\n\treturn 1;\n}\n \nvoid answer(vector <int>& ans, int answers_cnt)\n{\n\tcout << \"!\\n\";\n\tcout << answers_cnt << \"\\n\";\n\tfor (int i = 0; i < ans.size(); ++i)\n\t\tcout << ans[i] << \" \";\n\tcout << \"\\n\";\n\tcout.flush();\n}\n \nvoid init()\n{\n\tmemset(questions, -1, sizeof questions);\n\tquestions_cnt = 0;\n\tcin >> n;\n}\n \nvoid solve()\n{\n\tint answers_cnt = 0;\n\tinit();\n\tvector <int> ans;\n\tvector <int> p(n), t(n);\n\tfor (int b0 = 0; b0 < n; ++b0)\n\t{\n\t\tint flag = 1;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tt[i] = 0;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tp[i] = que(i, 0) ^ b0;\n\t\t\tif (p[i] > n || t[p[i]])\n\t\t\t{\n\t\t\t\tflag = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tt[p[i]] = 1;\n\t\t}\t\t\t\n\t\tif (flag && smart_test(p))\n\t\t{\n\t\t\t++answers_cnt;\n\t\t\tif (ans.size() == 0)\n\t\t\t\tans = p;\n\t\t}\n\t}\n\tanswer(ans, answers_cnt);\n}\n \nint main()\n{\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "interactive",
      "probabilities"
    ],
    "rating": 2000
  },
  {
    "contest_id": "870",
    "index": "E",
    "title": "Points, Lines and Ready-made Titles",
    "statement": "You are given $n$ distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.\n\nYou consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo $10^{9} + 7$.",
    "tutorial": "Let's build graph on points. Add edge from point to left, right, top and bottom neighbours (if such neigbour exist). Note that we can solve problem independently for each connected component and then print product of answer for components. So we can consider only connected graphs without loss of generality. Let's define X as number of different x-coords, Y as number of different y-coords. What if graph contains some cycle? Let's consider this cycle without immediate vertices (vertices that lie on the same line with previous and next vertices of cycle). Draw a line from each such vertex to the next vertex of cycle (and from last to the first). We got all lines that are corresponding to x-coords and y-coords of vertices of cycle. Let's prove by induction that we can got all such lines from the whole graph Run depth-first search from vertices of cycle. Let we enter in some vertex that is not from cycle. It mush have at least one visited neighbour. By induction for graph consisting of visited vertices we can get all lines. So there is line from visited neighbour. Draw line in another direction and continue depth-first search. Sooner or later we will get all lines for the whole graph. Please note that intermediate vertices of cycle will be processed correctly too. If we can get all lines the we can get all subsets of lines. Answer for cyclic graph is $2^{X + Y}$. Now look at another case - acyclic graph or tree. We can prove that we can get any incomplete subset of lines. Let's fix subset and some line not from this subset. Just draw this line without restriction. By similar induction as in cyclic graph case we can prove that we can get all lines (but fixed line doesn't exist really). Now let's prove that it is impossible to take all lines. For graph consisting of only one vertex it is obvious. Else fix some leaf. We must draw a line which are not directed to any neigbour because it is the only way to draw this line. But now we have tree with less number of vertices. So our statement is correct by induction. Answer for tree is $2^{X + Y} - 1$. So the problem now is just about building graph on points and checking each component on having cycles.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nconst int maxn = 1e5 + 5;\nconst int mod = 1e9 + 7;\n \nstruct point {\n\tint x, y;\n};\n \nint binpow(int x, int p) {\n\tif (p == 0) return 1;\n\tif (p & 1) return binpow(x, p - 1) * x % mod;\n\treturn binpow(x * x % mod, p >> 1);\n}\n \nint n;\nvector<point> pt;\nvector< pair<int, int> > vertical[maxn];\nvector< pair<int, int> > horizontal[maxn];\nvector<int> graph[maxn];\nchar used[maxn];\nset<int> different_x, different_y;\nint component_size, sum_of_degree;\n \nvoid dfs(int v) {\n\tused[v] = true;\n\t++component_size;\n\tsum_of_degree += graph[v].size();\n\tdifferent_x.insert(pt[v].x);\n\tdifferent_y.insert(pt[v].y);\n\tfor (auto to: graph[v]) {\n\t\tif (!used[to]) {\n\t\t\tdfs(to);\n\t\t}\n\t}\n}\n \nsigned main() {\n\tios_base::sync_with_stdio(false); cin.tie(0);\n\t\n\tcin >> n;\n\tpt.resize(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> pt[i].x >> pt[i].y;\n\t}\n\tvector<int> x, y;\n\tfor (int i = 0; i < n; ++i) {\n\t\tx.push_back(pt[i].x);\n\t\ty.push_back(pt[i].y);\n\t}\n\tsort(x.begin(), x.end());\n\tsort(y.begin(), y.end());\n\tfor (int i = 0; i < n; ++i) {\n\t\tpt[i].x = lower_bound(x.begin(), x.end(), pt[i].x) - x.begin();\n\t\tpt[i].y = lower_bound(y.begin(), y.end(), pt[i].y) - y.begin();\n\t}\n\tfor (int i = 0; i < n; ++i) {\n\t\tvertical[pt[i].x].emplace_back(pt[i].y, i);\n\t\thorizontal[pt[i].y].emplace_back(pt[i].x, i);\n\t}\n\tfor (int x = 0; x < n; ++x) {\n\t\tsort(vertical[x].begin(), vertical[x].end());\n\t\tfor (int i = 1; i < vertical[x].size(); ++i) {\n\t\t\tint a = vertical[x][i].second;\n\t\t\tint b = vertical[x][i - 1].second;\n\t\t\tgraph[a].push_back(b);\n\t\t\tgraph[b].push_back(a);\n\t\t}\n\t}\n\tfor (int y = 0; y < n; ++y) {\n\t\tsort(horizontal[y].begin(), horizontal[y].end());\n\t\tfor (int i = 1; i < horizontal[y].size(); ++i) {\n\t\t\tint a = horizontal[y][i].second;\n\t\t\tint b = horizontal[y][i - 1].second;\n\t\t\tgraph[a].push_back(b);\n\t\t\tgraph[b].push_back(a);\n\t\t}\n\t}\n\t\n\tint ans = 1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (!used[i]) {\n\t\t\tdfs(i);\n\t\t\tint k = binpow(2, different_x.size() + different_y.size());\n\t\t\tif (sum_of_degree / 2 == component_size - 1) --k;\n\t\t\tans = ans * k % mod;\n\t\t\tdifferent_x.clear();\n\t\t\tdifferent_y.clear();\n\t\t\tsum_of_degree = 0;\n\t\t\tcomponent_size = 0;\n\t\t}\n\t}\n\tcout << ans << '\\n';\n}\n\t",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "870",
    "index": "F",
    "title": "Paths",
    "statement": "You are given a positive integer $n$. Let's build a graph on vertices $1, 2, ..., n$ in such a way that there is an edge between vertices $u$ and $v$ if and only if $\\operatorname*{gcd}(u,v)\\neq1$. Let $d(u, v)$ be the shortest distance between $u$ and $v$, or $0$ if there is no path between them. Compute the sum of values $d(u, v)$ over all $1 ≤ u < v ≤ n$.\n\nThe $gcd$ (greatest common divisor) of two positive integers is the maximum positive integer that divides both of the integers.",
    "tutorial": "Integer $1  \\le  x  \\le  n$ is bad is $x = 1$ or $x$ is prime and $x > n / 2$. Otherwise integer is good. $prime_{x}$ for $1 < x  \\le  n$ is minimal prime divisor of $x$. Path between two vertices doesn't exist if at least one of them is bad. Distance equals to zero if this two vertices are the same. Distance equals to one if their numbers have common divisor. Distance between vertices $u$ and $v$ equals to two if $prime_{u} \\cdot prime_{v}  \\le  n$. Otherwise distance is three because path $u\\rightarrow2\\cdot p r i m e_{u}\\rightarrow2\\cdot p r i m e_{v}\\rightarrow v$ always exists. It is easy to find number of pairs of vertices between which there is no path. Number of pairs with distance 1 equals to sum over all good $x$ of expressions $x - 1 -  \\phi (x)$. Number of pairs with distance 3 can be found if we subtract number of pairs without path and number of pairs with distances 0 and 1 from number of all pairs. So it only remains to find number of pairs with distance 2. Let's divide such pairs on three types 1) Pairs of coprime composite numbers. 2) Good prime $p$ and good number $x$ such as $prime_{p} \\cdot prime_{x}  \\le  n$ and $x$ is not divided by $p$. 3) Two different good prime numbers, product of which is less or equal than $n$. Number of pairs with distance 2 equals to number of pairs of the first and the second types minus number of pairs of the third type. Number of pairs of the first type equals to sum over all composite $1  \\le  x  \\le  n$ of expressions $ \\phi (x) - ((number of noncomposite numbers which are less than x) - number of unique prime divisors of x)$. For the second type we should sum up over all prime $p$ number of good numbers $x$ such that $prime_{p} \\cdot prime_{x}  \\le  n$ and subtract number of such numbers divided by $p$. The first we can calculate with some additional precalculations, for the second we can just check all numbers divided by $p$. Number of the pairs of the third type can be found trivially.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nusing ll = long long;\nconst int maxn = 1e7 + 5;\n \nint n;\nint prime[maxn];\nchar bad[maxn];\nint phi[maxn];\nint number_of_prime_divisors[maxn];\nint pref_smallest_prime[maxn];\nint number_of_bad = 0;\n \nvoid calc_arrays() {\n    for (int i = 1; i <= n; ++i) {\n        phi[i] = i;\n    }\n    for (int i = 2; i <= n; ++i) {\n        if (prime[i]) continue;\n        for (int j = i; j <= n; j += i) {\n            if (!prime[j]) prime[j] = i;\n            phi[j] /= i;\n            phi[j] *= i - 1;\n        }\n    }\n    for (int i = 1; i <= n; ++i) {\n        if (i == 1 || prime[i] == i && i * 2 > n) {\n            bad[i] = true;\n            ++number_of_bad;\n        }\n    }\n    for (int i = 2; i <= n; ++i) {\n        if (prime[i] == i) {\n            number_of_prime_divisors[i] = 1;\n        } else if (prime[i / prime[i]] == prime[i]) {\n            number_of_prime_divisors[i] = number_of_prime_divisors[i / prime[i]];\n        } else {\n            number_of_prime_divisors[i] = number_of_prime_divisors[i / prime[i]] + 1;\n        }\n    }\n}\n \nll get_dist_one() {\n    ll ans = 0;\n    for (int i = 2; i <= n; ++i) {\n        if (!bad[i]) {\n            ans += i - 1 - phi[i];\n        }\n    }\n    return ans;\n}\n \nll get_dist_two() {\n    ll ans = 0;\n    int pref_noncomposite = 1;\n    for (int i = 2; i <= n; ++i) {\n        if (prime[i] != i) {\n            ans += phi[i];\n            ans -= pref_noncomposite;\n            ans += number_of_prime_divisors[i];\n        } else {\n            ++pref_noncomposite;\n        }\n    }\n \n    for (int i = 1; i <= n; ++i) {\n        if (!bad[i]) {\n            ++pref_smallest_prime[prime[i]];\n        }\n    }\n    for (int i = 1; i <= n; ++i) {\n        pref_smallest_prime[i] += pref_smallest_prime[i - 1];\n    }\n    for (int i = 2; i <= n; ++i) {\n        if (prime[i] != i || bad[i]) continue;\n        ans += pref_smallest_prime[n / i];\n        for (int j = i; j <= n; j += i) {\n            if (prime[j] <= n / i) {\n                --ans;\n            }\n        }\n    }\n    for (int i = 2; i <= n; ++i) {\n        int a = prime[i];\n        int b = i / a;\n        if (b != 1 && prime[b] == b && a != b) {\n            --ans;\n        }\n    }\n    return ans;\n}\n \nll solve(int _n) {\n    n = _n;\n    calc_arrays();\n    ll cnt_one = get_dist_one();\n    ll cnt_two = get_dist_two();\n    ll cnt_three = (ll) (n - number_of_bad) * (n - number_of_bad - 1) / 2 - cnt_one - cnt_two;\n    return cnt_one * 1 + cnt_two * 2 + cnt_three * 3;\n}\n \nint main() {\n    int n;\n    cin >> n;\n    cout << solve(n) << endl;\n}",
    "tags": [
      "data structures",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "871",
    "index": "E",
    "title": "Restore the Tree",
    "statement": "Petya had a tree consisting of $n$ vertices numbered with integers from $1$ to $n$. Accidentally he lost his tree.\n\nPetya remembers information about $k$ vertices: distances from each of them to each of the $n$ tree vertices.\n\nYour task is to restore any tree that satisfies the information that Petya remembers or report that such tree doesn't exist.",
    "tutorial": "In the beginning, it should be noted that it is possible to find out numbers of vertices from which distances are given, the number of the $i$th specified vertex is $id_{i}$, such that $d_{i, idi} = 0$. If there is no such a vertex, or more than one, then there is no answer. Fix the $root$ equal to some vertex from which distances are given in the input data. Assume $root = id_{1}$. For any vertex $id_{i}$, we can find vertices lying in the path from $root$ to this vertex, since for such and only for such vertices $d_{1, v} + d_{i, v} = d_{1, idi}$. And accordingly, the vertex $v$ suitable for this condition will be at a distance $d_{1, v}$ from $root$. So, we have learned to build a part of a tree that consists of vertices that lie on the path from $root$ to some vertex $id_{i}$. If we couldn't build the path in such a way, then there is no answer. Time complexity of this phase is $O(nk)$. Now consider the remaining vertices, in order of increasing depth (distance to the root). Let's consider a fixed vertex $v$, look at the path from it to $root$, this path can be divided into $2$ parts - $(root, u), (u, v)$ where $u$ is the vertex from the already constructed tree, let's find the deepest of such $u$, this can be done with $O(k)$ operations by using the fact that $u$ is the deepest vertex among all $lca(v, id_{i})$, which equals the vertex on the path from $root$ to $id_{i}$ at a depth of $d_{1, idi} + d_{1, v} - d_{i, v}$. Then the ancestor $v$ is the vertex that was added in the same way to the subtree $u$ but with a depth of $1$ less, or the vertex $u$ (if the depth $u$ is $1$ less than the depth of the vertex $v$). If no such vertices have been added yet, then there is no answer, since we considered the vertices in order of increasing depth. Time complexity of adding each vertex is $O(k)$. The resulting tree is also the desired tree. Time complexity of the whole algorithm is $O(nk)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid impossible() {\n\tputs(\"-1\");\n\texit(0);\n}\n \nint main() {\n\tint n, k;\n\tassert(scanf(\"%d %d\", &n, &k) == 2);\n\tassert(k > 0);\n \n\tvector <int> dist[k];\n\tvector <int> idx(n, 0);\n \n\tfor (int i = 0; i < k; ++i) {\n\t\tdist[i] = vector <int> (n, 0);\n\t\tfor (int j = 0; j < n; ++j)\n\t\t\tassert(scanf(\"%d\", &dist[i][j]) == 1);\n \n\t\tidx[i] = -1;\n\t\tfor (int j = 0; j < n; ++j)\t{\n\t\t\tif (dist[i][j] == 0) {\n\t\t\t\tif (idx[i] != -1)\n\t\t\t\t\timpossible();\n\t\t\t\telse\n\t\t\t\t\tidx[i] = j;\n\t\t\t}\n\t\t}\n \n\t\tif (idx[i] == -1)\n\t\t\timpossible();\n \n\t\tfor (int j = 0; j < i; ++j)\n\t\t\tif (idx[i] == idx[j])\n\t\t\t\timpossible();\n\t}\n \n\tvector <int> p(n, -1);\n\tvector <int> h = dist[0];\n\tint root = idx[0];\n \n\tvector <int> ps[k];\n\tfor (int i = 0; i < k; ++i)\n\t\tps[i] = vector <int> ();\n \n\tfor (int t = 1; t < k; ++t) {\n\t\tint v = idx[t];\n\t\tvector <int> &d = dist[t];\n \n\t\tvector <int> pars(n, -1);\n\t\tfor (int u = 0; u < n; ++u) {\n\t\t\tif (h[u] + d[u] == h[v]) {\n\t\t\t\tif (pars[h[u]] != -1)\n\t\t\t\t\timpossible();\n\t\t\t\tpars[h[u]] = u;\n\t\t\t}\n\t\t}\n \n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (pars[i] == -1 && i <= h[v])\n\t\t\t\timpossible();\n\t\t\tif (pars[i] != -1 && i > h[v])\n\t\t\t\timpossible();\n\t\t}\n \n\t\tfor (int i = 0; i < h[v]; ++i) {\n\t\t\tint pu = pars[i];\n\t\t\tint u = pars[i + 1];\n\t\t\tif (p[u] != -1 && p[u] != pu)\n\t\t\t\timpossible();\n\t\t\tp[u] = pu;\n\t\t}\n \n\t\tps[t] = pars;\n\t}\n \n\tif (p[root] != -1)\n\t\timpossible();\n \n\tvector <int> subs[n];\n\tfor (int i = 0; i < n; ++i)\n\t\tsubs[i] = vector <int> ();\n \n\tvector <int> vh[n];\n\tfor (int i = 0; i < n; ++i)\n\t\tvh[i] = vector <int> ();\n\tfor (int v = 0; v < n; ++v)\n\t\tvh[h[v]].push_back(v);\n \n\tfor (int hh = 0; hh < n; ++hh) {\n\t\tfor (int v: vh[hh]) {\n\t\t\tif (v == root || p[v] != -1)\n\t\t\t\tcontinue;\n \n\t\t\tint lp = root;\n\t\t\tint lt = 0;\n \n\t\t\tfor (int t = 1; t < k; ++t) {\n\t\t\t\tint u = idx[t];\n\t\t\t\tvector <int> &d = dist[t];\n\t\t\t\tvector <int> &pars = ps[t];\n \n\t\t\t\t// h[v] + h[u] - 2 * h[l] == d[v]\n\t\t\t\t// 2 * h[l] == h[v] + h[u] - d[v]\n \n\t\t\t\tint hl2 = h[v] + h[u] - d[v];\n\t\t\t\tif (hl2 % 2 != 0)\n\t\t\t\t\timpossible();\n \n\t\t\t\tint hl = hl2 / 2;\n\t\t\t\tif (hl < 0 || hl > h[u] || hl > h[v])\n\t\t\t\t\timpossible();\n \n\t\t\t\tint l = pars[hl];\n\t\t\t\tif (h[l] >= h[lp]) {\n\t\t\t\t\tif (pars[h[lp]] != lp)\n\t\t\t\t\t\timpossible();\n\t\t\t\t\tlp = l;\n\t\t\t\t\tlt = t;\n\t\t\t\t} else {\n\t\t\t\t\tif (ps[lt][h[l]] != l)\n\t\t\t\t\t\timpossible();\n\t\t\t\t}\n\t\t\t}\n \n\t\t\tsubs[lp].push_back(v);\n\t\t}\n\t}\n \n\tfor (int i = 0; i < n; ++i) {\n\t\tint prev = i;\n\t\tint nxt = -1;\n\t\tfor (int v: subs[i]) {\n\t\t\tassert(prev != -1);\n\t\t\tif (h[v] == h[prev] + 1) {\n\t\t\t\tp[v] = prev;\n\t\t\t\tnxt = v;\n\t\t\t} else {\n\t\t\t\tprev = nxt;\n\t\t\t\tif (prev != -1 && h[v] == h[prev] + 1) {\n\t\t\t\t\tp[v] = prev;\n\t\t\t\t\tnxt = v;\n\t\t\t\t} else\n\t\t\t\t\timpossible();\n\t\t\t}\n\t\t}\n\t}\n \n\tfor (int i = 0; i < n; ++i) {\n\t\tif (i == root)\n\t\t\tassert(p[i] == -1);\n\t\telse {\n\t\t\tprintf(\"%d %d\\n\", i + 1, p[i] + 1);\n\t\t}\n\t}\n \n\treturn 0;\n}",
    "tags": [
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "873",
    "index": "A",
    "title": "Chores",
    "statement": "Luba has to do $n$ chores today. $i$-th chore takes $a_{i}$ units of time to complete. It is guaranteed that for every $i\\in[2...n]$ the condition $a_{i} ≥ a_{i - 1}$ is met, so the sequence is sorted.\n\nAlso Luba can work really hard on some chores. She can choose not more than $k$ any chores and do each of them in $x$ units of time instead of $a_{i}$ ($x<\\operatorname*{min}_{i=1}a_{i}$).\n\nLuba is very responsible, so she has to do all $n$ chores, and now she wants to know the minimum time she needs to do everything. Luba cannot do two chores simultaneously.",
    "tutorial": "Since $x<\\operatorname*{min}_{i=1}a_{i}$, it is better to do exactly $k$ chores in time $x$. And since we need to minimize total time we need to spend, it's better to speed up the \"longest\" chores. So the answer is $k\\cdot x+\\sum_{i=1}^{n-k}a_{i}$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "873",
    "index": "B",
    "title": "Balanced Substring",
    "statement": "You are given a string $s$ consisting only of characters 0 and 1. A substring $[l, r]$ of $s$ is a string $s_{l}s_{l + 1}s_{l + 2}... s_{r}$, and its length equals to $r - l + 1$. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.\n\nYou have to determine the length of the longest balanced substring of $s$.",
    "tutorial": "Let $cnt_{0}(i)$ be the number of zeroes and $cnt_{1}(i)$ - the number of ones on prefix of length $i$; also let $balance(i) = cnt_{0}(i) - cnt_{1}(i)$ ($i  \\ge  0$). The interesting property of $balance$ is that the substring $[x, y]$ is balanced iff $balance(y) = balance(x - 1)$. That leads to a solution: for each value of $balance$ maintain the minimum $i$ where this $balance$ is obtained (let it be called $minIndex$), and for each index $i$ in the string update answer with $i - minIndex(balance(i))$.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "873",
    "index": "C",
    "title": "Strange Game On Matrix",
    "statement": "Ivan is playing a strange game.\n\nHe has a matrix $a$ with $n$ rows and $m$ columns. Each element of the matrix is equal to either $0$ or $1$. Rows and columns are $1$-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:\n\n- Initially Ivan's score is $0$;\n- In each column, Ivan will find the topmost $1$ (that is, if the current column is $j$, then he will find minimum $i$ such that $a_{i, j} = 1$). If there are no $1$'s in the column, this column is skipped;\n- Ivan will look at the next $min(k, n - i + 1)$ elements in this column (starting from the element he found) and count the number of $1$'s among these elements. This number will be added to his score.\n\nOf course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.",
    "tutorial": "Let's notice that this task can be solved independently for each column, total result will be the sum of results for columns. The ones you should remove will always be the top ones in column. It makes no profit to erase some one while there are still ones on top of it, score won't become higher. Go from the top of the column to the bottom and recalculate the score after removing every one. Take the first position of the maximal score and update global answer with it. Overall complexity: $O(n^{3})$. $O(n^{2})$ can be achieved with partial sums.",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "873",
    "index": "D",
    "title": "Merge Sort",
    "statement": "Merge sort is a well-known sorting algorithm. The main function that sorts the elements of array $a$ with indices from $[l, r)$ can be implemented as follows:\n\n- If the segment $[l, r)$ is already sorted in non-descending order (that is, for any $i$ such that $l ≤ i < r - 1$ $a[i] ≤ a[i + 1]$), then end the function call;\n- Let $m i d=\\lfloor{\\frac{l+r}{2}}\\rfloor$;\n- Call $mergesort(a, l, mid)$;\n- Call $mergesort(a, mid, r)$;\n- Merge segments $[l, mid)$ and $[mid, r)$, making the segment $[l, r)$ sorted in non-descending order. The merge algorithm doesn't call any other functions.\n\nThe array in this problem is $0$-indexed, so to sort the whole array, you need to call $mergesort(a, 0, n)$.\n\nThe number of calls of function $mergesort$ is very important, so Ivan has decided to calculate it while sorting the array. For example, if $a = {1, 2, 3, 4}$, then there will be $1$ call of $mergesort$ — $mergesort(0, 4)$, which will check that the array is sorted and then end. If $a = {2, 1, 3}$, then the number of calls is $3$: first of all, you call $mergesort(0, 3)$, which then sets $mid = 1$ and calls $mergesort(0, 1)$ and $mergesort(1, 3)$, which do not perform any recursive calls because segments $(0, 1)$ and $(1, 3)$ are sorted.\n\nIvan has implemented the program that counts the number of $mergesort$ calls, but now he needs to test it. To do this, he needs to find an array $a$ such that $a$ is a permutation of size $n$ (that is, the number of elements in $a$ is $n$, and every integer number from $[1, n]$ can be found in this array), and the number of $mergesort$ calls when sorting the array is exactly $k$.\n\nHelp Ivan to find an array he wants!",
    "tutorial": "First of all, if $k$ is even, then there is no solution, since the number of calls is always odd (one call in the beginning, and each call makes either $0$ or $2$ recursive calls). Then, if $k$ is odd, let's try to start with a sorted permutation and try to \"unsort\" it. Let's make a function $unsort(l, r)$ that will do it. When we \"unsort\" a segment, we can either keep it sorted (if we already made enough calls), or make it non-sorted and then call $unsort(l, mid)$ and $unsort(mid, r)$, if we need more calls. When we make a segment non-sorted, it's better to keep its both halves sorted; an easy way to handle this is to swap two middle element. It's easy to see that the number of $unsort$ calls is equal to the number of $mergesort$ calls to sort the resulting permutation, so we can use this approach to try getting exactly $k$ calls.",
    "tags": [
      "constructive algorithms",
      "divide and conquer"
    ],
    "rating": 1800
  },
  {
    "contest_id": "873",
    "index": "E",
    "title": "Awards For Contestants",
    "statement": "Alexey recently held a programming contest for students from Berland. $n$ students participated in a contest, $i$-th of them solved $a_{i}$ problems. Now he wants to award some contestants. Alexey can award the students with diplomas of three different degrees. Each student either will receive one diploma of some degree, or won't receive any diplomas at all. Let $cnt_{x}$ be the number of students that are awarded with diplomas of degree $x$ ($1 ≤ x ≤ 3$). The following conditions must hold:\n\n- For each $x$ ($1 ≤ x ≤ 3$) $cnt_{x} > 0$;\n- For any two degrees $x$ and $y$ $cnt_{x} ≤ 2·cnt_{y}$.\n\nOf course, there are a lot of ways to distribute the diplomas. Let $b_{i}$ be the degree of diploma $i$-th student will receive (or $ - 1$ if $i$-th student won't receive any diplomas). Also for any $x$ such that $1 ≤ x ≤ 3$ let $c_{x}$ be the maximum number of problems solved by a student that receives a diploma of degree $x$, and $d_{x}$ be the minimum number of problems solved by a student that receives a diploma of degree $x$. Alexey wants to distribute the diplomas in such a way that:\n\n- If student $i$ solved more problems than student $j$, then he has to be awarded not worse than student $j$ (it's impossible that student $j$ receives a diploma and $i$ doesn't receive any, and also it's impossible that both of them receive a diploma, but $b_{j} < b_{i}$);\n- $d_{1} - c_{2}$ is maximum possible;\n- Among all ways that maximize the previous expression, $d_{2} - c_{3}$ is maximum possible;\n- Among all ways that correspond to the two previous conditions, $d_{3} - c_{ - 1}$ is maximum possible, where $c_{ - 1}$ is the maximum number of problems solved by a student that doesn't receive any diploma (or $0$ if each student is awarded with some diploma).\n\nHelp Alexey to find a way to award the contestants!",
    "tutorial": "Let's consider naive solution: make three loops to fix amounts of people to get dimplomas of each degree, take the best. Obviously, sorting the scores will regroup optimal blocks for each degree in such a way that they come in segments of initial array. We tried to make these solutions fail but underestimated the abilities of contestants to optimize this kind of stuff and couple of such made it to the end of contest. :( To be honest, we just need to get rid of the last loop. Let $b_{i}$ be the difference between $a_{i}$ and $a_{i + 1}$ ($a$ is sorted, $b_{n - 1} = a_{n - 1}$). Then let $i_{2}$ be the position of the last diploma of second degree and $cnt_{1}$, $cnt_{2}$ be the amounts of diplomas of the first ans the second degrees. Thus the best position to put the separator between the third degree and no diploma is the postion with the maximum number in array $b$ over segment $[i_{2}+m a x(1,[\\frac{m a x(c n t_{1},c n t_{2})}{2}]),i_{2}+m i n(n-i_{2},2\\cdot m i n(c n t_{1},c n t_{2}))]$. This are the borders of possible amount of the dimplomas of the third degree. Maximum over segment can be implemented with segment tree, sparse table or even naive square matrix with $O(n^{2})$ precalc time and $O(n^{2})$ memory. Overall complexity: $O(n^{2})$/$O(n^{2}\\log{n})$.",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "873",
    "index": "F",
    "title": "Forbidden Indices",
    "statement": "You are given a string $s$ consisting of $n$ lowercase Latin letters. Some indices in this string are marked as forbidden.\n\nYou want to find a string $a$ such that the value of $|a|·f(a)$ is maximum possible, where $f(a)$ is the number of occurences of $a$ in $s$ such that these occurences end in non-forbidden indices. So, for example, if $s$ is aaaa, $a$ is aa and index $3$ is forbidden, then $f(a) = 2$ because there are three occurences of $a$ in $s$ (starting in indices $1$, $2$ and $3$), but one of them (starting in index $2$) ends in a forbidden index.\n\nCalculate the maximum possible value of $|a|·f(a)$ you can get.",
    "tutorial": "This problem can be solved with different suffix structures. Model solution uses suffix array. First of all, let's reverse $s$, so for $f(a)$ we will count only occurences that start in non-forbidden indices. Then, if there is at least one non-forbidden index, there are two cases: $f(a) = 1$, then the best option to choose $a$ is to use a suffix which begins in the leftmost (after reversing $s$) non-forbidden index. $f(a) > 1$, then $a$ is the longest common prefix of some two suffixes of $s$. Let's build a suffix array, then calculate the LCP array. Then recall the fact that a LCP of two suffixes is the minimum on the segment of LCP array between these two suffixes, so we can use a common stack algorithm that will for each LCP find the segment of suffixes such that this LCP is a prefix of these suffixes (to do this, for each element of LCP array we find the largest segment such that this element is minimal on that segment), and then we can use prefix sums to find the number of non-forbidden suffixes such that chosen LCP is a prefix of this suffix (and so calculate $f(a)$ easily for each LCP).",
    "tags": [
      "dsu",
      "string suffix structures",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "875",
    "index": "A",
    "title": "Classroom Watch",
    "statement": "Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number $n$. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that $n$ is the answer to the arithmetic task for first-graders. In the textbook, a certain \\textbf{positive integer} $x$ was given. The task was to add $x$ to the sum of the digits of the number $x$ written in decimal numeral system.\n\nSince the number $n$ on the board was small, Vova quickly guessed which $x$ could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number $n$ for all suitable values of $x$ or determine that such $x$ does not exist. Write such a program for Vova.",
    "tutorial": "For numbers that doesn't exceed $10^{9}$ sum of digits doesn't exceed $100$, so we can just iterate over all possible sums of digits $x$ and check if sum of digits of $n - x$ equals $x$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "875",
    "index": "B",
    "title": "Sorting the Coins",
    "statement": "Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation.\n\nFor arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following:\n\n- He looks through all the coins from left to right;\n- If he sees that the $i$-th coin is still in circulation, and $(i + 1)$-th coin is already out of circulation, he exchanges these two coins and continues watching coins from $(i + 1)$-th.\n\nDima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.\n\nToday Sasha invited Dima and proposed him a game. First he puts $n$ coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for $n$ times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence.\n\nThe task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task.",
    "tutorial": "We denote, for 0, a coin that has left circulation and for one coin in circulation. We solve the problem for a fixed array. If it consists of only 1, then the answer is 0, since the array is already sorted. Otherwise, consider the most right zero. If there is not a single 1 to the left of this zero, then the array is already sorted and the answer is $1$. Let 1 appears $k$ times to the left of the rightmost zero. For one iteration the nearest 1 on the left will move to the position of this zero, and zero will move one position to the left. After this iteration, $k - 1$ ones will remain to the left of the rightmost zero. Hence the answer is $k + 1$. Let us return to the original problem. We will keep the pointer to the rightmost zero. Since as a result of queries the zeros only disappear, the pointer moves only to the left. If the rightmost zero has disappeared, move the pointer to the left by a cycle, until we find the next zero. Consider pointer is at the position $x$ (numeration from zero), and there are only $p$ ones in the array. On the right of $x$ all the symbols are ones so on the right there are only $n-x-1$ ones. So on the left are $p-(n-x-1)$ ones. This solution works in $O(n + q)$.",
    "tags": [
      "dsu",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "875",
    "index": "C",
    "title": "National Property",
    "statement": "You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library.\n\nSome long and uninteresting story was removed...\n\nThe alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter $x$ is denoted by $x'$. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are \\textbf{before} all small letters. For example, the following conditions hold: $2 < 3$, $2' < 3'$, $3' < 2$.\n\nA word $x_{1}, x_{2}, ..., x_{a}$ is not lexicographically greater than $y_{1}, y_{2}, ..., y_{b}$ if one of the two following conditions holds:\n\n- $a ≤ b$ and $x_{1} = y_{1}, ..., x_{a} = y_{a}$, i.e. the first word is the prefix of the second word;\n- there is a position $1 ≤ j ≤ min(a, b)$, such that $x_{1} = y_{1}, ..., x_{j - 1} = y_{j - 1}$ and $x_{j} < y_{j}$, i.e. at the first position where the words differ the first word has a smaller letter than the second word has.\n\nFor example, the word \"$3'$ $7$ $5$\" is before the word \"$2$ $4'$ $6$\" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence.\n\nDenis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in \\textbf{all} words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet.\n\nHelp Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible.\n\nNote that some words can be \\textbf{equal}.",
    "tutorial": "Let the strings $s_{i}$ and $s_{i + 1}$ are not prefixes of each other. Then it is necessary that $s_{i, k} < s_{i + 1, k}$, where k is the first position, where $s_{i}$ and $s_{i + 1}$ differ. Consider strings $s_{i}$ and $s_{i + 1}$. Let $k$ be the first position in which they differ. Then there are two cases: If $s_{i, k} > s_{i + 1, k}$, you capitalize $s_{i, k}$ and not capitalize $s_{i, k + 1}$. If $s_{i, k} < s_{i + 1, k}$, both these letters should be capitalized or not capitalizes simultaneously. Let's make a graph in which letters will be vertexes. If $s_{i, k} > s_{i + 1, k}$, then mark $s_{i, k}$ as capitalized, otherwise make a directed edge between $s_{i + 1, k}$ and $s_{i, k}$. It means that if we capitalize $s_{i + 1, k}$, you also should capitalize $s_{i, k}$. Note that our graph is acyclic because the edges are directed from big letters to small letters. Using dfs we capitalize all the letters, that are reachable from the capitalized letters and check the answer. If the answer is wrong, there is no answer.",
    "tags": [
      "2-sat",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "875",
    "index": "D",
    "title": "High Cry",
    "statement": "Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :)\n\nRick and Morty like to go to the ridge High Cry for crying loudly — there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this ridge: if Rick and Morty begin crying simultaneously from different mountains, their cry would be heard between these mountains up to the height equal the bitwise OR of mountains they've climbed and all the mountains between them.\n\nBitwise OR is a binary operation which is determined the following way. Consider representation of numbers $x$ and $y$ in binary numeric system (probably with leading zeroes) $x = x_{k}... x_{1}x_{0}$ and $y = y_{k}... y_{1}y_{0}$. Then $z = x | y$ is defined following way: $z = z_{k}... z_{1}z_{0}$, where $z_{i} = 1$, if $x_{i} = 1$ or $y_{i} = 1$, and $z_{i} = 0$ otherwise. In the other words, digit of bitwise OR of two numbers equals zero if and only if digits at corresponding positions is both numbers equals zero. For example bitwise OR of numbers $10 = 1010_{2}$ and $9 = 1001_{2}$ equals $11 = 1011_{2}$. In programming languages C/C++/Java/Python this operation is defined as «|», and in Pascal as «or».\n\nHelp Rick and Morty calculate the number of ways they can select two mountains in such a way that if they start crying from these mountains their cry will be heard above these mountains and all mountains between them. More formally you should find number of pairs $l$ and $r$ ($1 ≤ l < r ≤ n$) such that bitwise OR of heights of all mountains between $l$ and $r$ (inclusive) is larger than the height of any mountain at this interval.",
    "tutorial": "First we find for each element the nearest element on the left and on the right more than it. It can be done by many ways, for example using stack. Then you find for each element $x$ the nearest on the left and on the right element $y$ so that $x|y > x$. For this note that in $y$ must be some bit set, which is not set in $x$. So you can just pass from left to the right (and then from right to the left) along the array, calculating $go_{i}$ - the nearest on the left (on the right) element in which the bit $i$ equals $1$. We fix the mountain which will be the highest on the segment from the answer (if the heights are equal - the most left, for example). Then the segment must be completely nested in the segment on which the given mountain is the highest and must cross at least one element, OR with which our element is greater than the element itself. This solution works in $O(n) + O(nlogc) + O(n) = O(nlogc)$.",
    "tags": [
      "binary search",
      "bitmasks",
      "combinatorics",
      "data structures",
      "divide and conquer"
    ],
    "rating": 2200
  },
  {
    "contest_id": "875",
    "index": "E",
    "title": "Delivery Club",
    "statement": "Petya and Vasya got employed as couriers. During the working day they are to deliver packages to $n$ different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate $s_{1}$, Vasya is at the point with the coordinate $s_{2}$, and the clients are at the points $x_{1}, x_{2}, ..., x_{n}$ in the order of the required visit.\n\nThe guys agree in advance who of them will deliver the package to which of the customers, and then they act as follows. When the package for the $i$-th client is delivered, the one who delivers the package to the $(i + 1)$-st client is sent to the path (it can be the same person who went to the point $x_{i}$, or the other). The friend who is not busy in delivering the current package, is standing still.\n\nTo communicate with each other, the guys have got walkie-talkies. The walkie-talkies work rather poorly at great distances, so Petya and Vasya want to distribute the orders so that the maximum distance between them during the day is as low as possible. Help Petya and Vasya to minimize the maximum distance between them, observing all delivery rules.",
    "tutorial": "We will learn to check that the answer is no more $p$. If we learn to do this, we can make a binary search for the answer and get the answer. To check we calculate $dp_{i}$ - is it possible to process the first $i$ orders so that the last order of one courier is $i$, and the second order is $i + 1$. In this case, the transition can be done immediately by several steps forward. Transition from $i$ to $j$ means that the first courier will execute the orders $i + 1, i + 2, ... j - 1$, and the second - the order with the number $j$. The transition can be made if $|x_{j} - x{j - 1}|  \\le  p$ and $|x_{k} - x{i - 1}|  \\le  p$ for all $k$ from $i$ to $j - 1$. It may be rewritten as $x_{i - 1} - p  \\le  x_{k}  \\le  x_{i - 1} + p$, and so the maximum $j$ for given $i$ can be found using segment tree or analogical structure. After that you only set $dp_{j} = 1$ to all possible $j$ on the segment. It can be done for example going along the massive and knowing maximum segment of possible $j$. The solution works in $O(nlognlogANS)$.",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "875",
    "index": "F",
    "title": "Royal Questions",
    "statement": "In a medieval kingdom, the economic crisis is raging. Milk drops fall, Economic indicators are deteriorating every day, money from the treasury disappear. To remedy the situation, King Charles Sunnyface decided make his $n$ sons-princes marry the brides with as big dowry as possible.\n\nIn search of candidates, the king asked neighboring kingdoms, and after a while several delegations arrived with $m$ unmarried princesses. Receiving guests, Karl learned that the dowry of the $i$ th princess is $w_{i}$ of golden coins.\n\nAlthough the action takes place in the Middle Ages, progressive ideas are widespread in society, according to which no one can force a princess to marry a prince whom she does not like. Therefore, each princess has an opportunity to choose two princes, for each of which she is ready to become a wife. The princes were less fortunate, they will obey the will of their father in the matter of choosing a bride.\n\nKnowing the value of the dowry and the preferences of each princess, Charles wants to play weddings in such a way that the total dowry of the brides of all his sons would be as great as possible. At the same time to marry all the princes or princesses is not necessary. Each prince can marry no more than one princess, and vice versa, each princess can marry no more than one prince.\n\nHelp the king to organize the marriage of his sons in the most profitable way for the treasury.",
    "tutorial": "Consider bipartite graph in which princesses are in the left part and princes in the right part. Because of the propriety of transversal matroid you can choose princesses greedily: let's sort princesses according to decrease in size of dowry and in this order try to add to matching. It can be done at $O(nm)$ every time finding alternating chain. But this solution can be speed up. Let's try to attribute to each (not isolated) vertex of right part the most expensive vertex of left part. If resulting set of edges is a matching it will be the solution. The set of edges can not form matching only if in the left part there are some vertexes for which both edges are taken. Let's name these vertexes \"popular\". Suppose that we didn't take any popular vertex in the optimal answer. Then you can take any its neighbor from right part and improve the answer. That' why weight of popular vertex can be added to the answer and remove it from the graph uniting its neighbors to one vertex. This vertex will describe the prince who has not got popular princess. As in the previous case we'll consider vertexes of left part in descending order and the vertexes of right part we will keep is disjoint set union. If the current vertex of right part has two neighbors in right part, we add its weight to the answer and unite its neighbors in DSU. In the vertex has one neighbor in right part, we add the weight of vertex to the answer and remove the vertex of right part. Otherwise we don't add the weight of vertex to the answer. Solution works in $O(nlogn)$.",
    "tags": [
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "876",
    "index": "A",
    "title": "Trip For Meal",
    "statement": "Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is $a$ meters, between Rabbit's and Eeyore's house is $b$ meters, between Owl's and Eeyore's house is $c$ meters.\n\nFor enjoying his life and singing merry songs Winnie-the-Pooh should have a meal $n$ times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store).\n\nWinnie-the-Pooh does not like physical activity. He wants to have a meal $n$ times, traveling minimum possible distance. Help him to find this distance.",
    "tutorial": "If minimum of numbers $a, b, c$ equals $a$ or $b$, or $n = 1$. Then answer equals $min(a, b) \\cdot (n - 1)$. Otherwise answer equals $min(a, b) + c \\cdot (n - 2)$. Also there is solution that uses dynamic programming.",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "876",
    "index": "B",
    "title": "Divisiblity of Differences",
    "statement": "You are given a multiset of $n$ integers. You should select exactly $k$ of them in a such way that the difference between any two of them is divisible by $m$, or tell that it is impossible.\n\nNumbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.",
    "tutorial": "If $x - y$ is divisible by $m$, then $x$ and $y$ have same reminder when divided by $m$. Let's divide number to groups by reminder by modulo $m$, and if there is a group with size at least $k$ print $k$ numbers from it.",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "877",
    "index": "A",
    "title": "Alex and broken contest",
    "statement": "One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.\n\nBut there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest by its name.\n\nIt is known, that problem is from this contest if and only if its name contains one of Alex's friends' name \\textbf{exactly once}. His friends' names are \"Danil\", \"Olya\", \"Slava\", \"Ann\" and \"Nikita\".\n\n\\textbf{Names are case sensitive.}",
    "tutorial": "You need just implement what is written in the statements. Count the total number of entries of the names and check if it's equal to $1$. 877B - Nikita and string",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "877",
    "index": "B",
    "title": "Nikita and string",
    "statement": "One day Nikita found the string containing letters \"a\" and \"b\" only.\n\nNikita thinks that string is beautiful if it can be cut into $3$ strings (possibly empty) without changing the order of the letters, where the $1$-st and the $3$-rd one contain only letters \"a\" and the $2$-nd contains only letters \"b\".\n\nNikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?",
    "tutorial": "Let $pref_{a}[i]$ be the count of letter \"a\" in prefix of length $i$ and $pref_{b}[i]$ be the count of letter \"b\" in prefix of length $i$. Let's fix two positions $i$ and $j$, $1  \\le  i  \\le  j  \\le  n$, so we remove all \"b\" from prefix, which ends in $i$, and suffix, which starts in $j$, and all \"a\" between positions $i$ and $j$. Then length of string is $(pref_{a}[n] - pref_{a}[j]) + (pref_{b}[j] - pref_{b}[i]) + (pref_{a}[i])$. Using two for loops we find optimal $i$ and $j$ and calculate answer. 877C - Slava and tanks",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "877",
    "index": "C",
    "title": "Slava and tanks",
    "statement": "Slava plays his favorite game \"Peace Lightning\". Now he is flying a bomber on a very specific map.\n\nFormally, map is a checkered field of size $1 × n$, the cells of which are numbered from $1$ to $n$, in each cell there can be one or several tanks. Slava doesn't know the number of tanks and their positions, because he flies very high, but he can drop a bomb in any cell. All tanks in this cell will be damaged.\n\nIf a tank takes damage for the first time, it instantly moves to one of the neighboring cells (a tank in the cell $n$ can only move to the cell $n - 1$, a tank in the cell $1$ can only move to the cell $2$). If a tank takes damage for the second time, it's counted as destroyed and never moves again. The tanks move only when they are damaged for the first time, they do not move by themselves.\n\nHelp Slava to destroy all tanks using as few bombs as possible.",
    "tutorial": "Let's call the tanks, which are initially in even positions even, and the tansk, which are initially in odd positions odd. Let's throw bombs in all even positions. Now all tanks are in odd positons. Now let's throw bombs in all odd positions. Now all even tanks are exterminated and all odd tanks are in even positions. Throw bombs in all even positions again. Now all tanks are extemintated. It's not hard to prove that this strategy is optimal. 877D - Olya and Energy Drinks",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "877",
    "index": "D",
    "title": "Olya and Energy Drinks",
    "statement": "Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.\n\nFormally, her room can be represented as a field of $n × m$ cells, each cell of which is empty or littered with cans.\n\nOlya drank a lot of energy drink, so now she can run $k$ meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from $1$ to $k$ meters in this direction. Of course, she can only run through empty cells.\n\nNow Olya needs to get from cell $(x_{1}, y_{1})$ to cell $(x_{2}, y_{2})$. How many seconds will it take her if she moves optimally?\n\nIt's guaranteed that cells $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ are empty. These cells can coincide.",
    "tutorial": "Note, that bfs can find right answer, but works in $O(n \\cdot m \\cdot k)$. It's too slow. We'll store all not visited cells in set. For each row and column we'll make own set. Now it's easy to find all not visited cell which is reachable from vertex in $O(cnt \\cdot log(n))$, where $cnt$ is number of this cells. Then summary it works in $O(n \\cdot m \\cdot log(n))$. 877E - Danil and a Part-time Job",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "877",
    "index": "E",
    "title": "Danil and a Part-time Job",
    "statement": "Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher.\n\nDanil works in a rooted tree (undirected connected acyclic graph) with $n$ vertices, vertex $1$ is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on.\n\nUnfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages.\n\nThere are two types of tasks:\n\n- pow v describes a task to switch lights in the subtree of vertex $v$.\n- get v describes a task to count the number of rooms in the subtree of $v$, in which the light is turned on. Danil should send the answer to his boss using Workforces messages.\n\nA subtree of vertex $v$ is a set of vertices for which the shortest path from them to the root passes through $v$. In particular, the vertex $v$ is in the subtree of $v$.\n\nDanil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him.",
    "tutorial": "Let's construct Euler tour tree. We'll put vertex in vector when first time visit it. For each vertext subtree is segment in this vector, borders of which we can calculate while constructing. Now we need to make inversion on segment and get sum of segment. Segment tree is good for it. 877F - Ann and Books",
    "tags": [
      "bitmasks",
      "data structures",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "877",
    "index": "F",
    "title": "Ann and Books",
    "statement": "In Ann's favorite book shop are as many as $n$ books on math and economics. Books are numbered from $1$ to $n$. Each of them contains non-negative number of problems.\n\nToday there is a sale: any subsegment of a segment from $l$ to $r$ can be bought at a fixed price.\n\nAnn decided that she wants to buy such non-empty subsegment that the sale operates on it and the number of math problems is greater than the number of economics problems \\textbf{exactly} by $k$. Note that $k$ may be positive, negative or zero.\n\nUnfortunately, Ann is not sure on which segment the sale operates, but she has $q$ assumptions. For each of them she wants to know the number of options to buy a subsegment satisfying the condition (because the time she spends on choosing depends on that).\n\nCurrently Ann is too busy solving other problems, she asks you for help. For each her assumption determine the number of subsegments of the given segment such that the number of math problems is greaten than the number of economics problems on that subsegment exactly by $k$.",
    "tutorial": "If $i$-th book is on economics, $a[i] = - a[i]$. Now problem is to calculate count of segments of sum $k$. Calculate prefix sums: $p[j]=\\sum_{i=1}^{J}a[i]$. Then $\\sum_{i=l}^{r}=p[r]-p[l-1]$. Now we can solve it in $O(n \\cdot q \\cdot log(n))$. We'll go along the segment and calculate $cnt[i]$ - number of occurences of $i$ in segment. Then we'll add $cnt[p[i] - k]$ to answer. $p[i]$ can be big enought, so we should use something like map. This is where the logarithm comes from. Note, that we can easily move both borders to the left and to the right. Then we can solve it using Mo's algorhitm in $O(q \\cdot sqrt(n) \\cdot log(n))$. Unfortunatelly, it's still too slow. Let's use coordinate compression. For each prefsum calculate $v[i]$ - compressed value of $p[i]$, $l[i]$ - compressed value $p[i] - k$ and $r[i]$ - compressed value $p[i] + k$. It allows us to get rid of logarithm.",
    "tags": [
      "data structures",
      "flows",
      "hashing"
    ],
    "rating": 2300
  },
  {
    "contest_id": "878",
    "index": "A",
    "title": "Short Program",
    "statement": "Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.\n\nIn the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from $0$ to $1023$. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.\n\nPetya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than $5$ lines. Your program should return the same integer as Petya's program for all arguments from $0$ to $1023$.",
    "tutorial": "Let's see what happens with a single bit. All operations work with each bit separately, so each bit of output depends only on the corresponding bit of input. There are only four options: bit doesn't change, bit always changes, bit is set to 0, bit is set to 1. For each bit it's easy to find which of these options happens to it. Now let's write a program of three lines: Depending on the implementation, it may works in $O(n)$ or $O(n\\log X)$. BONUS: solve a problem using at most two commands.",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "878",
    "index": "B",
    "title": "Teams Formation",
    "statement": "This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has $n$ passenger seats, seat $i$ can be occupied only by a participant from the city $a_{i}$.\n\nToday the bus has completed $m$ trips, each time bringing $n$ participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence $a_{1}, a_{2}, ..., a_{n}$ repeated $m$ times).\n\nAfter that some teams were formed, each consisting of $k$ participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no $k$ neighboring participants from the same city.\n\nHelp the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.",
    "tutorial": "First, let's see what happens inside one bus. We can use a stack containing pairs (city, number of participants from it). When the number of participants reaches $k$, we erase the pair. Suppose we build this stack. $r$ is its size, $(c_{i}, d_{i})$ are pairs in it. Now consider the interaction of two such buses. At the border, a team is formed, if $c_{1} = c_{r}$ and $d_{1} + d_{r}  \\ge  k$. If the inequality becomes an equality, then another team can be formed from the second and penultimate groups, etc. Let's find the greatest $p$ such that for each $i = 1... p$ we have $c_{i} = c_{r + 1 - i}$ and $d_{i} + d_{r + 1 - i} = k$. Since the condition on $i$ is symmetric with respect to $i\\mapsto r+1-i$, if $p  \\ge   \\lceil  r / 2 \\rceil $, then $p = r$. Consider the case $p = r$ separately. This means that the two buses are completely divided into teams. If $m$ is even, answer is zero, otherwise answer is the sum of $d_{i}$. Also, consider the case when $r$ is odd and $p =  \\lfloor  r / 2 \\rfloor $. In this case, after removing all teams at the borders of the buses, the queue looks like: left part of the first bus - $md_{p + 1}$ people from the $c_{p + 1}$ city - right part of the last bus. If the number of people in the middle is divisible by $k$, then they will be divided into the commands, and the first half will unite with the last, and the answer is zero. If it doesn't, then some teams will be formed in the middle, and the process will end there. Finally, if $r$ is even smaller, it can be seen that after the formation of teams at the borders of buses the process will end.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "878",
    "index": "C",
    "title": "Tournament",
    "statement": "Recently a tournament in $k$ kinds of sports has begun in Berland. Vasya wants to make money on the bets.\n\nThe scheme of the tournament is very mysterious and not fully disclosed. Competitions are held back to back, each of them involves two sportsmen who have not left the tournament yet. Each match can be held in any of the $k$ kinds of sport. Loser leaves the tournament. The last remaining sportsman becomes the winner. Apart of this, the scheme can be arbitrary, it is not disclosed in advance.\n\nVasya knows powers of sportsmen in each kind of sport. He believes that the sportsmen with higher power always wins.\n\nThe tournament is held every year, and each year one new participant joins it. In the first tournament, only one sportsman has participated, in the second there were two sportsmen, and so on. Vasya has been watching the tournament for the last $n$ years. Help him to find the number of possible winners for each of the $n$ tournaments.",
    "tutorial": "Imagine a directed graph, in which the vertices are participants, and the edge means that one participant can win the other in some kind of sports. A participant can win a tournament if there is a directed tree in this graph that contains all vertices, and this player is a root. Consider the condensation of this graph. Since for any two vertices there is an edge at least in one direction, condensation is a path. It is clear that the required tree exists if and only if the root lies in the first strongly connected component. We will maintain these strongly connected components. For each of them we will store its size, the greatest power and the smallest power in each kind of sports. What happens when the new sportsman is added? He can defeat the component if in some kind of sports he is stronger than the minimum in this component. Similarly, he can lose to a component if in some kind of sports he is weaker than the maximum in this component. We need to find the weakest of those components that he can lose, and the strongest of those components that he can defeat. If the first component is stronger than the second, the new sportsman forms a new component. Otherwise, all the components between the first and the second merge into one, and the new sportsman joins it. How to do it effectively? We will store the components in a some search tree and use the comparison by minimum in the first kind of sports as a comparator. It's easy to see that if you take any other sport or replace a minimum with a maximum, any two components will be compared in the same way. All we need is binsearch by one of the mentioned comparators: minimum or maximum for one of the kinds of sports. At each step the number of operations with the tree is $O(k)$ + $k \\cdot $ number of components merged into one. At each step at most one component can be added, so the amortized time of one step is $O(\\log n)$. Overall time complexity is $O(n k\\log n)$.",
    "tags": [
      "data structures",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "878",
    "index": "D",
    "title": "Magic Breeding",
    "statement": "Nikita and Sasha play a computer game where you have to breed some magical creatures. Initially, they have $k$ creatures numbered from $1$ to $k$. Creatures have $n$ different characteristics.\n\nSasha has a spell that allows to create a new creature from two given creatures. Each of its characteristics will be equal to the maximum of the corresponding characteristics of used creatures. Nikita has a similar spell, but in his spell, each characteristic of the new creature is equal to the minimum of the corresponding characteristics of used creatures. A new creature gets the smallest unused number.\n\nThey use their spells and are interested in some characteristics of their new creatures. Help them find out these characteristics.",
    "tutorial": "Let's consider a special case of the problem: all $a_{ij}$ are 0 or 1. In this case there are at most $2^{k}$ different characteristics. So we can use trivial solution, it works in $O(q2^{k})$. Also we can sped up it using bitset. Now we reduce the problem to this special case. We have a characteristic with values $x_{1}  \\le  x_{2}  \\le  ...  \\le  x_{k}$. Let's make $k$ characteristics from it. $i$-th of them is one if and only if the original characteristic is at least $x_{i}$, and zero otherwise. New characteristics behave correctly during our operations, and we can efficiently get old characteristics from them. Number of characteristics has increased, but is doesn't matter for our solution for the special case. This solution works in $O(q2^{k})$.",
    "tags": [
      "bitmasks"
    ],
    "rating": 2900
  },
  {
    "contest_id": "878",
    "index": "E",
    "title": "Numbers on the blackboard",
    "statement": "A sequence of $n$ integers is written on a blackboard. Soon Sasha will come to the blackboard and start the following actions: let $x$ and $y$ be two adjacent numbers ($x$ before $y$), then he can remove them and write $x + 2y$ instead of them. He will perform these operations until one number is left. Sasha likes big numbers and will get the biggest possible number.\n\nNikita wants to get to the blackboard before Sasha and erase some of the numbers. He has $q$ options, in the option $i$ he erases all numbers to the left of the $l_{i}$-th number and all numbers to the right of $r_{i}$-th number, i. e. all numbers between the $l_{i}$-th and the $r_{i}$-th, inclusive, remain on the blackboard. For each of the options he wants to know how big Sasha's final number is going to be. This number can be very big, so output it modulo $10^{9} + 7$.",
    "tutorial": "Let's find a strategy for Sasha. His result can be represented in the form $\\sum_{i=1}^{n}a_{i}2^{k_{i}}$, where $k_{1} = 0$, $1  \\le  k_{i}  \\le  k_{i - 1} + 1$ for $i > 1$. For all $k_{i}$ satisfying these conditions he can obtain such result. We prove this by induction. For $n = 1$ is't obvious. Let $n > 1$. Find the greatest $i$ such that $k_{i} = 1$. It always exists cause $k_{2} = 1$. By the induction hypothesis we can get $k_{1}, k_{2}... k_{i - 1}$ and $k_{i} - 1, k_{i + 1} - 1... k_{n} - 1$. Do this and merge them with the last move. Now we describe the strategy. Let the last number be negative. Then Sasha wants to minimize $k_{n}$. He always can use $k_{n} = 1$. If tha last number is non-negative, he can use $k_{n} = k_{n - 1} + 1$. In this case, Sasha first merges the last two numbers. Thus, the sequence $k_{i}$ consists of several blocks, in each of which $k_{i + 1} = k_{i} + 1$, and each of the blocks except the first begins with 1. Now we need to answer queries. We will do it offline. On the step $i$ add the number $a_{i}$ and and answer all queries with $r = i$. We will support the blocks for the query $[1, i]$. What happens when we add a number? If it's negative, it simply forms a separate block. Otherwise it becomes the end of some block. It is easy to see that the new block is the union of several old blocks. How to answer queries? $[l, r]$ is the union of some blocks and a suffix of another block. We can see that this is the partition into blocks for our query. How to do it fast? We will store the boundaries of blocks to do binary search on them and find the block in which the $l$ lies. We need to store the results for each block and prefix sums of these results. Also we need to find sums $\\sum_{j=1}^{i}a_{j}2^{j}$ to find out results for suffixes. Each step is processed in $O(\\log n)$ except for merging blocks. But we create at most one block on each step, so amortized time of each step is $O(\\log n)$. Also in this problem we need to be careful with overflows. Although we need to find the result modulo some prime, in some places the sign is important. We can use that if $|y|$ is more than maximum $a_{i}$, then $x + 2y$ is also big and have the same sign.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 3300
  },
  {
    "contest_id": "879",
    "index": "A",
    "title": "Borya's Diagnosis",
    "statement": "It seems that Borya is seriously sick. He is going visit $n$ doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor $1$, then doctor $2$, then doctor $3$ and so on). Borya will get the information about his health from the last doctor.\n\nDoctors have a strange working schedule. The doctor $i$ goes to work on the $s_{i}$-th day and works every $d_{i}$ day. So, he works on days $s_{i}, s_{i} + d_{i}, s_{i} + 2d_{i}, ...$.\n\nThe doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?",
    "tutorial": "Note that Borya can use a greedy algorithm. He will visit each doctor as soon as possible. We only need to find the earliest day when he can do it. Constraints are pretty low, so we can use almost any reasonable way. For example, we can just go through all the days, starting from the current one, and check if the doctor is working on that day. At the step $i$ we need to go through at most $max(s_{i}, d_{i})$ days. There is a more efficient way. We can find the smallest $x$ that is greater than the current day, such that $x\\equiv s_{i}{\\bmod{d}}_{i}$, in $O(1)$. If $x  \\ge  s_{i}$, Borya will visit a doctor on day $x$, otherwise on day $s_{i}$. This solution is $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "879",
    "index": "B",
    "title": "Table Tennis",
    "statement": "$n$ people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins $k$ games in a row. This player becomes the winner.\n\nFor each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.",
    "tutorial": "It's not very difficult to solve this problem in $O(k + n)$. The statement hints us that we can use the data structure queue. We need to maintain the queue of players, the current winner and the number of wins he has. Each game is processed in $O(1)$. It can be shown that number of games is less than $n + k$. Of course, this solution is too slow. Let's think what happens if $k$ is large. More precisely, assume that $k  \\ge  n - 1$. The winner need to win at least $n - 1$ games in a row, that is, he need to win against all the other players. Hence, the winner is just the strongest player. So, if $k  \\ge  n - 1$, we can solve the problem in $O(1)$. Otherwise simulation works in $O(n)$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "884",
    "index": "A",
    "title": "Book Reading",
    "statement": "Recently Luba bought a very interesting book. She knows that it will take $t$ seconds to read the book. Luba wants to finish reading as fast as she can.\n\nBut she has some work to do in each of $n$ next days. The number of seconds that Luba has to spend working during $i$-th day is $a_{i}$. If some free time remains, she can spend it on reading.\n\nHelp Luba to determine the minimum number of day when she finishes reading.\n\n\\textbf{It is guaranteed that the answer doesn't exceed $n$.}\n\n\\textbf{Remember that there are 86400 seconds in a day.}",
    "tutorial": "Let's read the book greedily. On $i$-th day Luba will read for $86400 - a_{i}$ seconds. Subtract value for each day from $t$ until $t$ becomes less or equal to zero. That will be the day Luba finishes the book. Overall complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "884",
    "index": "B",
    "title": "Japanese Crosswords Strike Back",
    "statement": "A one-dimensional Japanese crossword can be represented as a binary string of length $x$. An encoding of this crossword is an array $a$ of size $n$, where $n$ is the number of segments formed completely of $1$'s, and $a_{i}$ is the length of $i$-th segment. No two segments touch or intersect.\n\nFor example:\n\n- If $x = 6$ and the crossword is $111011$, then its encoding is an array ${3, 2}$;\n- If $x = 8$ and the crossword is $01101010$, then its encoding is an array ${2, 1, 1}$;\n- If $x = 5$ and the crossword is $11111$, then its encoding is an array ${5}$;\n- If $x = 5$ and the crossword is $00000$, then its encoding is an empty array.\n\nMishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is \\textbf{exactly one} crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!",
    "tutorial": "The only answer is when no segment can be moved one cell either to the left or to the right. So there should be exactly one cell between two consecutive segments and the first and the last segments should touch the borders. Thus total count of cells needed is $\\sum_{i=1}^{n}a_{i}+n-1$. Overall complexity; $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "884",
    "index": "C",
    "title": "Bertown Subway",
    "statement": "The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.\n\nThere are $n$ stations in the subway. It was built according to the Bertown Transport Law:\n\n- For each station $i$ there exists exactly one train that goes from this station. Its destination station is $p_{i}$, possibly $p_{i} = i$;\n- For each station $i$ there exists exactly one station $j$ such that $p_{j} = i$.\n\nThe President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs $(x, y)$ such that person can start at station $x$ and, after taking some subway trains (possibly zero), arrive at station $y$ ($1 ≤ x, y ≤ n$).\n\nThe mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of $p_{i}$ for \\textbf{not more than two subway stations}. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.\n\nThe mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!",
    "tutorial": "Let's notice that one swap can affect at most two cycles of this permutation. Moreover you can join two cycles into one with the length equal to the sums of lengths of initial ones. The function we are going to maximize is $f(a, b) = (a + b)^{2} - a^{2} - b^{2}$, where $a$ and $b$ are the lengths of the cycles we are joining together. $f(a, b) = (a^{2} + 2ab + b^{2}) - a^{2} - b^{2} = 2ab$. Now its easily seen that the maximum is achived when joining two cycles with the greatest product of lengths. Finally they are the two longest cycles in permutation. Overall complexity: $O(n)$.",
    "tags": [
      "dfs and similar",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "884",
    "index": "D",
    "title": "Boxes And Balls",
    "statement": "Ivan has $n$ different boxes. The first of them contains some balls of $n$ different colors.\n\nIvan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every $i$ ($1 ≤ i ≤ n$) $i$-th box will contain all balls with color $i$.\n\nIn order to do this, Ivan will make some turns. Each turn he does the following:\n\n- Ivan chooses any non-empty box and takes all balls from this box;\n- Then Ivan chooses any $k$ empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into $k$ non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either $k = 2$ or $k = 3$.\n\nThe penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.\n\nHelp Ivan to determine the minimum possible penalty of the game!",
    "tutorial": "Let's consider the process backwards: we will store the number of balls of each color in a multiset and then \"merge\" some of them. If $n$ is odd, then we can always pick three groups of balls with minimal sizes and replace them by one group (adding the size of this group to the penalty). Repeat until you have only one group. If $n$ is even, then we need to add an auxiliary group of size $0$. Then $n$ becomes odd, so we can use the above algorithm to solve this case. Why does it work? This algorithm is exactly the same as the algorithm of building a Huffman code with the alphabet of size $3$. And it can easily be seen that these problems are similar: by separating a group of balls into three groups, we add a new character to the codes of the colours present in that group, and our goal is to obtain a prefix code.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "884",
    "index": "E",
    "title": "Binary Matrix",
    "statement": "You are given a matrix of size $n × m$. Each element of the matrix is either 1 or 0. You have to determine the number of connected components consisting of 1's. Two cells belong to the same component if they have a common border, and both elements in these cells are 1's.\n\n\\textbf{Note that the memory limit is unusual!}",
    "tutorial": "The main idea is to read and process each row of the matrix separately. To do this, we will use DSU data structure. The answer will be equal to the difference between the number of 1's and the number of merge operations in DSU. When processing the row, we will keep the DSU for the previous row. When processing a certain index in the row, we will try to merge it with the element to the left of it and with the element to the top - that's all we have to check here. You also have to handle the fact that we cannot store the whole DSU since the number of components can be up to $\\frac{n I T I}{2}$, and it's impossible to store all required information for them. So each time we process a row, we have to renumerate all components in this row to ensure that every time we are operating with indices of components not greater than $2m$.",
    "tags": [
      "dsu"
    ],
    "rating": 2500
  },
  {
    "contest_id": "884",
    "index": "F",
    "title": "Anti-Palindromize",
    "statement": "A string $a$ of length $m$ is called antipalindromic iff $m$ is even, and for each $i$ ($1 ≤ i ≤ m$) $a_{i} ≠ a_{m - i + 1}$.\n\nIvan has a string $s$ consisting of $n$ lowercase Latin letters; $n$ is even. He wants to form some string $t$ that will be an antipalindromic permutation of $s$. Also Ivan has denoted the beauty of index $i$ as $b_{i}$, and the beauty of $t$ as the sum of $b_{i}$ among all indices $i$ such that $s_{i} = t_{i}$.\n\nHelp Ivan to determine maximum possible beauty of $t$ he can get.",
    "tutorial": "This problem has two different solutions: a mincost maxflow approach and a greedy one. We will tell you about the latter. First of all, let $t = s$. Then find all pairs of indices $(i, n - i + 1)$ such that $t_{i} = t_{n - i + 1}$ (let the number of these pairs be $m$). It's obvious that we have to replace at least one letter in each of these pairs. For each of these pairs let's replace the letter with lower $b_{i}$ with something. Let's analyze the letters we are going to replace. Let $cnt(x)$ be the number of occurences of letter $x$ that we have to replace. There are two cases: There is no letter $x$ such that $2 * cnt(x) > m$. Then we can replace these letters without involving anything else and get an antipalindromic string with minimal possible cost; There is a letter $x$ such that $2 * cnt(x) > m$. It's obvious that there is at most one such letter. Let's replace some occurences of $x$ with other letters that are to be replaced. Then we will still have some occurences of $x$ that need to be replaced. Let's take one letter from each pair such that both of letters in a pair are not equal to $x$. Among these possibilities choose the required number of letters with minimum values of $b_{i}$. Then we can replace remaining occurences of $x$ with these letters.",
    "tags": [
      "flows",
      "graphs",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "886",
    "index": "A",
    "title": "ACM ICPC",
    "statement": "In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only $6$ students who wished to participate, the decision was to build exactly two teams.\n\nAfter practice competition, participant number $i$ got a score of $a_{i}$. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.",
    "tutorial": "In this problem it's enough to iterate through all the triples checking whether its sum equals to the sum of remaining triple or not. Answer is \"YES\" if equality is possible and \"NO\" - otherwise.",
    "tags": [
      "brute force"
    ],
    "rating": 1000
  },
  {
    "contest_id": "886",
    "index": "B",
    "title": "Vlad and Cafes",
    "statement": "Vlad likes to eat in cafes very much. During his life, he has visited cafes $n$ times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.\n\nFirst of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.",
    "tutorial": "There are two steps to solve this problem: 1. Put in array last the last time when Petya visited each cafe. 2. Now you need to find the position of minimum in this array and print it.",
    "tags": [],
    "rating": 1000
  },
  {
    "contest_id": "886",
    "index": "C",
    "title": "Petya and Catacombs",
    "statement": "A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.\n\nCatacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute $i$, he makes a note in his logbook with number $t_{i}$:\n\n- If Petya has visited this room before, he writes down the minute he was in this room last time;\n- Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute $i$.\n\nInitially, Petya was in one of the rooms at minute $0$, he didn't write down number $t_{0}$.\n\nAt some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?",
    "tutorial": "First, we notice that if journal contains two equal notes $t_{i} = t_{j}, i < j$, then at least one of them was made in newly visited room, because otherwise $t_{j}$ would be at least $i$. Thus there could be at most one note corresponding to previously visited room among equal notes. Let's denote by $cnt_{i}$ number of occurrences of $i$ in the journal. From the previous statement we deduce that minimum possible number of rooms is at least $\\textstyle\\sum_{i=0}^{n-1}\\operatorname*{max}(0,c n t_{i}-1)$. Also, it's easy to see that this value can be achieved: we say that first occurrence of each value corresponds to revisiting the previous room and all other correspond to visiting new rooms. So the problem can be solved by calculating values $cnt_{i}$ for each $i$ between $0$ and $n$ and calculating the above sum. Overall complexity - $O(n)$.",
    "tags": [
      "dsu",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "886",
    "index": "D",
    "title": "Restoration of string",
    "statement": "A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.\n\nYou are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print \"NO\" (without quotes).\n\nA substring of a string is a contiguous subsequence of letters in the string. For example, \"ab\", \"c\", \"abc\" are substrings of string \"abc\", while \"ac\" is not a substring of that string.\n\nThe number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.\n\nString $a$ is lexicographically smaller than string $b$, if $a$ is a prefix of $b$, or $a$ has a smaller letter at the first position where $a$ and $b$ differ.",
    "tutorial": "If some string is the most frequent then all its substrings are the most frequent too. If string ab or similar is the most frequent then letter $a$ is always followed by letter $b$ and $b$ always follow $a$. Let's consider directed graph on letters where edge $a  \\rightarrow  b$ exists only if ab is the most frequent. If there is cycle in such graph then good string doesn't exist. So such graph can be represented as several non-intersecting paths. All strings which correspond to paths must occur in non-empty good string. So if we print them in lexicographical order then we will get the answer.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "886",
    "index": "E",
    "title": "Maximum Element",
    "statement": "One day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of $n$ positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter $k$, so now his function contains the following code:\n\n\\begin{verbatim}\nint fast_max(int n, int a[]) {\nint ans = 0;\nint offset = 0;\nfor (int i = 0; i < n; ++i)\nif (ans < a[i]) {\nans = a[i];\noffset = 0;\n} else {\noffset = offset + 1;\nif (offset == k)\nreturn ans;\n}\nreturn ans;\n}\n\\end{verbatim}\n\nThat way the function iteratively checks array elements, storing the intermediate maximum, and if after $k$ consecutive iterations that maximum has not changed, it is returned as the answer.\n\nNow Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from $1$ to $n$ such that the return value of his function on those permutations is not equal to $n$. Since this number could be very big, output the answer modulo $10^{9} + 7$.",
    "tutorial": "You asked to find the number of permutations $p$ of length $n$ such that exists index $i$, such that $p_{i}  \\neq  n$, $p_{i}$ is greater than any $p_{j}$ for j in $[1, i - 1]$ and greater then any $p_{j}$ for j in $[i + 1, i + k]$. We will call such permutations good. Define $D(n)$ as number of good permutations that have $p_{n} = n$. Notice that if $k  \\ge  n$, then $D(n) = 0$. Let $w$ be a permutations such that $w_{n} = n$. If index of element $n - 1$ is lesser than $n - k$, then $w$ is good. Otherwise if $n - 1$ index is $j, j  \\ge  n - k$, then because there are less then $k$ elements between $n - 1$ and $n$, $w$ could be good only if $i$ from the definition would be lesser than $j$. In that case permutation $w_{1}, ..., w_{j}$ would form a good permutation of length $j$ of some numbers with $w_{j}$ being the maximum. Therefore the following equation is correct: $D(n)=(n-k-1)\\cdot(n-2)!+\\sum_{h=n-k}^{n-1}D(h)\\cdot{\\frac{(n-2)!}{i\\,n-1!}}$ $D(n)=(n-k-1)\\cdot(n-2)!+(n-2)!\\cdot\\sum_{h=n-k}^{n-1}{\\frac{D(n)}{k-1!!}}$ The answer is than calculated as follows: $\\sum_{\\quad\\quad h=1}^{n}D(h)\\cdot{\\frac{(n-1)!}{(h-1)!}}$ Complexity: $O(n)$.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "886",
    "index": "F",
    "title": "Symmetric Projections",
    "statement": "You are given a set of $n$ points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines.\n\nMultiset is a set where equal elements are allowed.\n\nMultiset is called symmetric, if there is a point $P$ on the plane such that the multiset is centrally symmetric in respect of point $P$.",
    "tutorial": "Let us note that projection of set of points to line move center of mass of initial set to center of mass of initial set to center of mass of projections multiset. So if the line is good then the center of mass of initial set move to center of symmetry. Also If there is two points, which are symmetric with respect to center of mass then they will be symmetric under the projection on arbitrary line. So we can throw away these points. Fix arbitrary point from remaining set. Let us take point from set, which will be symmetric to the fixed point. There is only one line, which has property, that two projections of chosen points are symmetric: the line, which is perpendicular to line passing through the center of mass of initial set and center of segment connecting two chosen points. So we have no more then n candidates which can be a good line. It is possible to check, that line is good, in $O(nlogn)$ time. Time: $O(n^{2}\\log{n})$",
    "tags": [
      "geometry"
    ],
    "rating": 2900
  },
  {
    "contest_id": "887",
    "index": "A",
    "title": "Div. 64",
    "statement": "Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.\n\nHer problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.",
    "tutorial": "If the string contains no ones then the answer is \"NO\" as the remainig number must be positive. Otherwise we can find the leftmost one and check if it is followed by at least six zeroes.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "887",
    "index": "B",
    "title": "Cubes for Masha",
    "statement": "Absent-minded Masha got set of $n$ cubes for her birthday.\n\nAt each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural $x$ such she can make using her new cubes all integers from 1 to $x$.\n\nTo make a number Masha can rotate her cubes and put them in a row. After that, she looks at upper faces of cubes from left to right and reads the number.\n\nThe number can't contain leading zeros. It's not required to use all cubes to build a number.\n\nPay attention: Masha can't make digit 6 from digit 9 and vice-versa using cube rotations.",
    "tutorial": "The answer is always less or equal to 98. We can go through numbers from 1 to 99 and find the first one which we cannot make using cubes.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "887",
    "index": "C",
    "title": "Solution for Cube",
    "statement": "During the breaks between competitions, top-model Izabella tries to develop herself and not to be bored. For example, now she tries to solve Rubik's cube 2x2x2.\n\nIt's too hard to learn to solve Rubik's cube instantly, so she learns to understand if it's possible to solve the cube in some state using 90-degrees rotation of one face of the cube in any direction.\n\nTo check her answers she wants to use a program which will for some state of cube tell if it's possible to solve it using one rotation, described above.\n\nCube is called solved if for each face of cube all squares on it has the same color.\n\nhttps://en.wikipedia.org/wiki/Rubik's_Cube",
    "tutorial": "The amount of variants of input data for which the answer is \"YES\" is not more than 12 without considering rearrangement of colours. They all could be written in an array. The alternative solution is writing a function of rotating a specific edge of the cube and checking if it is solved.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "887",
    "index": "D",
    "title": "Ratings and Reality Shows",
    "statement": "There are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by $a$ and after each fashion show decreases by $b$ (designers do too many experiments nowadays). Moreover, sometimes top-models participates in talk shows. After participating in talk show model becomes more popular and increasing of her rating after photo shoots become $c$ and decreasing of her rating after fashion show becomes $d$.\n\nIzabella wants to participate in a talk show, but she wants to do it in such a way that her rating will never become negative. Help her to find a suitable moment for participating in the talk show.\n\nLet's assume that model's career begins in moment 0. At that moment Izabella's rating was equal to $start$. If talk show happens in moment $t$ if will affect all events in model's life in interval of time $[t..t + len)$ (including $t$ and not including $t + len$), where $len$ is duration of influence.\n\nIzabella wants to participate in a talk show, but she wants to do it in such a way that her rating will not become become negative before talk show or during period of influence of talk show. Help her to find a suitable moment for participating in the talk show.",
    "tutorial": "We can create two arrays of prefix sums of events given in input. The first one on values ($a$, $b$) and the second one on values ($c$, $d$). The answer is either 0 or the moment of time right after an event occured. Let's use the method of two pointers. One pointer will indicate an event $V$ after which we want to participate in the talk show and the other one at the moment of time right after its influence ends. Then we can participate in the talk show if the minimum of prefix sums on values ($c$, $d$) from elements between pointers is not less than the difference of prefix sums on values ($a$, $b$) and ($c$, $d$) from element $V$. Also we must check that Izabella's rating doesn't become negative before participating in the talk show or during its peroid of influence.",
    "tags": [
      "data structures",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "887",
    "index": "E",
    "title": "Little Brother",
    "statement": "Masha's little brother draw two points on a sheet of paper. After that, he draws some circles and gave the sheet to his sister.\n\nMasha has just returned from geometry lesson so she instantly noticed some interesting facts about brother's drawing.\n\nAt first, the line going through two points, that brother drew, doesn't intersect or touch any circle.\n\nAlso, no two circles intersect or touch, and there is no pair of circles such that one circle is located inside another.\n\nMoreover, for each circle, Masha drew a square of the minimal area with sides parallel axis such that this circle is located inside the square and noticed that there is no two squares intersect or touch and there is no pair of squares such that one square is located inside other.\n\nNow Masha wants to draw circle of minimal possible radius such that it goes through two points that brother drew and doesn't intersect any other circle, but other circles can touch Masha's circle and can be located inside it.\n\n\\textbf{It's guaranteed, that answer won't exceed $10^{12}$. It should be held for hacks as well.}",
    "tutorial": "The center of required circle is on a perpendicular to the middle of the segment $AB$ where $A$ and $B$ are two points from the input. If a circle with the center on the segment $AB$ and the radius equal to half of its length satisfies the conditions then it is the answer. Otherwise we can find on which side relative to AB the center of the circle is. Every drawn circle blocks a continious interval of allowed values for the requierd circle. The limits of this interval can be found by using binary search. Now we have to find the least allowed value for the radius. It can be done, for example, by using method of scanning line.",
    "tags": [
      "binary search",
      "geometry",
      "sortings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "887",
    "index": "F",
    "title": "Row of Models",
    "statement": "During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it.\n\nLike many other creative people, Izabella has a specific sense of beauty. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed $k$ (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc).\n\nShe wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.\n\nFashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.\n\nYou should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella.",
    "tutorial": "For every element of an array $a_{i}$ we can check $x$ elements on its right. If there are no elements less than $a_{i}$ we will mark it as \"-1\" and call it \"bad\". If there is exactly one element then make an edge from $a_{i}$ to this element. Otherwise swapping elements of the array will never make $a_{i}$ \"bad\". If there are no \"bad\" elements in the array then the answer is \"YES\". Otherwise we should find the leftmost \"bad\" element in the array bad. $X$ elements after it are not less than itself. All elements before it are also not less than itself because otherwise an element less than bad would be \"bad\" too. Swapping bad with an element in suffix also makes no sense because its place will be taken by lesser element and the position will remain \"bad\". Thus, swapping bad with other element of the array makes no sense. The only way to satisfy the conditions is to swap one of $x$ elements after $bad$ with other element in the remaining suffix without considering a segment with length $x$ after bad. Let's try to do it obviously. Then the following conditions must be satisfied. Consider choosing an element $y$ in the remaining suffix. Then the swap can be the answer if $y$ < $bad$. Also suffix after $y$ and the segment between $y$ and the segment with length $x$ after $bad$ must not contain \"bad\" elements. An element, which we swap $y$ with, from the segment with length $x$ after $bad$ must be less than any adress on $y$. Also we need to check that after the swap on the right side of $y$ we can find an element less than itself no further than $x$. Time: $O(n)$ or $O(nlogn)$.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "888",
    "index": "A",
    "title": "Local Extrema",
    "statement": "You are given an array $a$. Some element of this array $a_{i}$ is a local minimum iff it is strictly less than both of its neighbours (that is, $a_{i} < a_{i - 1}$ and $a_{i} < a_{i + 1}$). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, $a_{i} > a_{i - 1}$ and $a_{i} > a_{i + 1}$). Since $a_{1}$ and $a_{n}$ have only one neighbour each, they are neither local minima nor local maxima.\n\nAn element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.",
    "tutorial": "Iterate over indices from $2$ to $n - 1$ and check if at least one of given local extremum conditions holds. Overall complexity: $O(n)$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "888",
    "index": "B",
    "title": "Buggy Robot",
    "statement": "Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell $(0, 0)$. The robot can process commands. There are four types of commands it can perform:\n\n- U — move from the cell $(x, y)$ to $(x, y + 1)$;\n- D — move from $(x, y)$ to $(x, y - 1)$;\n- L — move from $(x, y)$ to $(x - 1, y)$;\n- R — move from $(x, y)$ to $(x + 1, y)$.\n\nIvan entered a sequence of $n$ commands, and the robot processed it. After this sequence the robot ended up in the starting cell $(0, 0)$, but Ivan doubts that the sequence is such that after performing it correctly the robot ends up in the same cell. He thinks that some commands were ignored by robot. To acknowledge whether the robot is severely bugged, he needs to calculate the maximum possible number of commands that were performed correctly. Help Ivan to do the calculations!",
    "tutorial": "Consider the final cell after original path. It has some distance $dx$ to $x = 0$ and $dy$ to $y = 0$. That means the path included at least $dx$ and $dy$ in corresponding directions. Let's remove just these minimal numbers of moves. Finally, the answer will be $n - dx - dy$, where $(dx, dy)$ are distances from the final cell of the original path to $(0, 0)$. Overall complexity: $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "888",
    "index": "C",
    "title": "K-Dominant Character",
    "statement": "You are given a string $s$ consisting of lowercase Latin letters. Character $c$ is called $k$-dominant iff each substring of $s$ with length at least $k$ contains this character $c$.\n\nYou have to find minimum $k$ such that there exists at least one $k$-dominant character.",
    "tutorial": "At first, notice that the final answer is minimum over answers for each character. The answer for one character can be obtained like this. Write down lengths of segments between two consecutive occurrences of this character, from the first occurrence to the start of the string and from the last to the end of the string. Take maximum of these values. Answer will be this maximum + 1. Overall complexity: $O(|Alpha| \\cdot n)$.",
    "tags": [
      "binary search",
      "implementation",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "888",
    "index": "D",
    "title": "Almost Identity Permutations",
    "statement": "A permutation $p$ of size $n$ is an array such that every integer from $1$ to $n$ occurs exactly once in this array.\n\nLet's call a permutation an almost identity permutation iff there exist at least $n - k$ indices $i$ ($1 ≤ i ≤ n$) such that $p_{i} = i$.\n\nYour task is to count the number of almost identity permutations for given numbers $n$ and $k$.",
    "tutorial": "Let's iterate on $m$ - the number of indices such that $p_{i}  \\neq  i$. Obviously, $0  \\le  m  \\le  k$. How to count the number of permutations with fixed $m$? First of all, we need to choose the indices that have the property $p_{i}  \\neq  i$ - there are $\\binom{n}{m}$ ways to do this. Secondly, we need to construct a permutation $q$ for chosen indices such that for every chosen index $q_{i}  \\neq  i$; permutations with this property are called derangements, and the number of derangements of fixed size can be calculated using exhaustive search (since $m  \\le  4$). So the answer is $\\sum_{m=0}^{k}{\\binom{n}{m}}d(m)$, where $d(m)$ is the number of derangements of size $m$.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "888",
    "index": "E",
    "title": "Maximum Subsequence",
    "statement": "You are given an array $a$ consisting of $n$ integers, and additionally an integer $m$. You have to choose some sequence of indices $b_{1}, b_{2}, ..., b_{k}$ ($1 ≤ b_{1} < b_{2} < ... < b_{k} ≤ n$) in such a way that the value of $\\sum_{i=1}^{k}a_{b_{i}}\\,m o d\\,m$ is maximized. Chosen sequence can be empty.\n\nPrint the maximum possible value of $\\sum_{i=1}^{k}a_{b_{i}}\\,m o d\\,m$.",
    "tutorial": "Let's consider the naive solution in $O(2^{n})$ or $O(2^{n} \\cdot n)$. Iterate over all subsets of original set, calculate sums and take maximum of them modulo $m$. Now we can use meet-in-the-middle technique to optimize it to $O(2^{\\lfloor{\\frac{n}{2}}\\rfloor}\\cdot\\log(2^{\\lfloor{\\frac{n}{2}}\\rfloor}))$. Preprocess the first $\\textstyle{\\left[\\!\\!{\\frac{n}{2}}\\right]\\!\\!}\\$ elements naively and push sums modulo $m$ to some array. After this process the second half with following algorithm. Take sum of the set and find the greatest total sum of current and some sum in the array. As any sum of two numbers less than $m$ can go no greater than $2m$, we can consider just two values: the greatest number in array and the greatest number less than $m - currentSum$ in the array. This can be found by binary search over sorted array. Overall complexity: $O(2^{\\lfloor{\\frac{n}{2}}\\rfloor}\\cdot\\log(2^{\\lfloor{\\frac{n}{2}}\\rfloor}))$.",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "meet-in-the-middle"
    ],
    "rating": 1800
  },
  {
    "contest_id": "888",
    "index": "F",
    "title": "Connecting Vertices",
    "statement": "There are $n$ points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw $n - 1$ segments, each connecting any two marked points, in such a way that all points have to be connected with each other (directly or indirectly).\n\nBut there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid).\n\nHow many ways are there to connect all vertices with $n - 1$ segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo $10^{9} + 7$.",
    "tutorial": "We can use dynamic programming to solve this problem, but we need to choose the states we maintain very carefully. One of the approaches might be: $dp[i][j]$ - the number of ways to connect the vertices between $i$ and $j$ to vertices $i$ or $j$ if $i$ and $j$ are already connected (so there is no possibility to connect any vertex between $i$ and $j$ to some vertex outside). What $dp$ values should we access if we, for example, try to connect $i$-th vertex to some vertex $x$? To get everything connected, we then have to connect vertices from interval $(i, x)$ to these two, and vertices from $(x, j)$ to $x$, $j$ or $i$ - and connections to $i$ from the second interval are difficult to handle. We need to somehow get rid of them, and the solution is to choose $x$ as the vertex with greatest index that we connect directly to $i$. And vice versa, if we connect something to $j$, then we choose the smallest index of vertex to be connected with $j$ directly. But that's not all we have to handle. Suppose we have four vertices, and $0$ is already connected to $3$. One of the possibilities to finish it is to connect $0$ to $1$ and $2$ to $3$, but if we process current dynamic programming as it is, we will count it twice (if we choose to connect $1$ to $0$ firstly, or if we connect $2$ to $3$). To get rid of this problem, we will use a flag that will denote whether we can connect anything to vertex $i$, and if we choose to pick the first connection from $j$, then we don't connect anything to $i$. So the solution is: $dp[i][j][flag]$ - the number of ways to connect the vertices from interval $(i, j)$ to $i$ and $j$, and $flag$ denotes if we can connect anything to $i$. How to calculate it: If $j = i + 1$, then $dp[i][j][flag] = 1$ (there is nothing left to connect); Otherwise set $dp[i][j][flag] = 0$; If $flag = 1$, then iterate on vertex $x$ we connect to $i$ and add $dp[i][x][flag] \\cdot dp[x][j][flag]$; Iterate on vertex $y$ we connect to $j$ and add $dp[i][y][0] \\cdot dp[y][j][1]$. The answer is $dp[0][n][0]$ (if vertices are $0$-indexed). Vertex $n$ is actually vertex $0$, so don't forget to update the matrix $a$ for it.",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "888",
    "index": "G",
    "title": "Xor-MST",
    "statement": "You are given a complete undirected graph with $n$ vertices. A number $a_{i}$ is assigned to each vertex, and the weight of an edge between vertices $i$ and $j$ is equal to $a_{i} xor a_{j}$.\n\nCalculate the weight of the minimum spanning tree in this graph.",
    "tutorial": "We can use Boruvka's algorithm to solve this problem. This algorithm usually works in $O(m\\log n)$: initially MST is empty, and then we run a number of iterations. During each iteration we find connected components in the graph formed by already added edges, and for each component we find the shortest edge that leads out of this component. Then we add the edges we found to the MST (but we should be careful to avoid adding edges that form cycles in MST). The number of iterations is at most $\\log n$, and each of iterations can be done in $O(m)$. However, in this problem we need to speed up this algorithm. We can do each iteration in $O(n\\log(\\operatorname*{max}_{i=1}a_{i}))$ time using a binary trie. We can store all values from $a$ in a trie. When we need to find the shortest edge that connects some component with vertices outside of it, we firstly remove all values contained in this component from the trie. After that, for each vertex in the component we can find the closest vertex outside the component in $O(\\log(\\operatorname*{max}_{i=1}a_{i}))$ by descending the trie. And then we insert the values of $a_{i}$ belonging to the component back into the trie. Since for each vertex we descend the trie three times (to remove it, to find closest vertex and to add it back), each iteration requries $O(n\\log(\\operatorname*{max}_{i=1}a_{i}))$, and the whole algorithm works in $O(n\\log n\\log(\\operatorname*{max}_{i=1}a_{i}))$ time.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "data structures"
    ],
    "rating": 2300
  },
  {
    "contest_id": "889",
    "index": "E",
    "title": "Mod Mod Mod",
    "statement": "You are given a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. Let $f(x,n)=x\\operatorname*{mod}\\,a_{n}$, and $f(x,i)=(x\\,\\mathrm{mod}\\,a_{i})+f(x\\,\\mathrm{mod}\\,a_{i},i+1)$ for $1 ≤ i < n$. Here, $\\mathrm{mod}$ denotes the modulus operation. Find the maximum value of $f(x, 1)$ over all nonnegative integers $x$.",
    "tutorial": "Hint 1: let $x_{i}=x{\\mathrm{~mod~}}a_{1}{\\mathrm{~mod~}}a_{2}{\\mathrm{~mod~}}a_{\\cdot}\\cdot{\\mathrm{~mod~}}a_{i}$. Can you define some interesting segments of value $x_{i}$? Hint 2: think of some dp. Hint 3: once you get the dp in $O(n^{2})$, to speed it up, note the following fact: if $c=a{\\mathrm{~mod~}}b$, then either $c = a$ or $c<{\\frac{a}{2}}$. Explanation of hint 1: let's call $ans_{i} = f(x, 1) - f(x_{i}, i + 1)$, in other words, it's the part of answer we gain from summands from $1$ to $i$. For $i = 1$ the following is true: $x_{1}$ can be any number from $0$ to $a_{1} - 1$, and $ans_{i} = x_{i}$. Suppose for some $i$ we have the following option: $x_{i}$ can be any number from $0$ to $r$, and in this case $ans_{i} = x_{i} * i + k$. We can describe this situation by triple $(i, r, k)$. We will show that this triple will produce at most two such triples for $i + 1$. Indeed, we can have many triples $(i + 1, a_{i + 1} - 1, k_{j})$ with different $k_{j}$ and one triple $(i+1,r\\mathrm{~mod~}a_{i+1},k+i\\cdot(r-r\\mathrm{~mod~}a_{i+1}))$. However, we can note that among triplets of the first type we can leave only one with maximum $k_{j}$, because we're interested in maximum answer. This $k_{j}$ will equal $(k+i\\cdot(r-r\\,\\operatorname*{mod}\\,a_{i+1}-a_{i+1}))$. Thus, we have two transitions from each triple, that leads us to $O(2^{n})$ bruteforce solution. Explanation of hint 2: when we have a bruteforce, we (almost) always can think of a dp. Indeed, we have triples, among those with equal $i$ and $r$ let's keep only one with the largest $k$. There are at most $i$ such triples on step $i$: on each step half of the generated triples have $r = a_{i + 1} - 1$, so we can merge them. This leads us to dp in $O(n^{2})$. Explanation of hint 3: Okay, what does the third hint say? It basically says that a number can only be taken by modulo $O(\\log(C))$ times until it becomes zero, where $C$ is the bound of its initial value. What do we get from this? We can note that if $r < a_{i + 1}$, we can just leave a triple $(i, r, k)$ untouched except changing $i$ to $i + 1$. Let's then keep pairs $(r, k)$, assuming triples $(i, r, k)$, where $i$ changes in a cycle. On each step we should change all pairs such that $r  \\ge  a_{i + 1}$, possibly adding one more pair with $r = a_{i + 1} - 1$. But when we change a pair, $r$ is get by modulo, so this won't happen with a pair more than $O(log(C))$ times! Overall, the total number of times we touch a pair is bounded by $O(n\\log(C))$. Adding $O(\\log(n))$ for map in which we keeps the pairs, we obtain the final complexity $O(n\\log(C)\\log(n))$. Also, map can be replaced with binary search, but the complexity remains the same.",
    "tags": [
      "binary search",
      "dp",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "891",
    "index": "A",
    "title": "Pride",
    "statement": "You have an array $a$ with length $n$, you can perform operations. Each operation is like this: choose two \\textbf{adjacent} elements from $a$, say $x$ and $y$, and replace one of them with $gcd(x, y)$, where $gcd$ denotes the greatest common divisor.\n\nWhat is the minimum number of operations you need to make all of the elements equal to $1$?",
    "tutorial": "Consider $cnt_{1}$ as number of $1$s in the $a$. If $0 < cnt_{1}$ then the answer is $n - cnt_{1}$. otherwise We should find a segment with its $gcd$ equal to 1 and minimum length. consider a segment as $(L, R)$ which $L  \\le  R$ and it's gcd as $D(L, R)$ We fix $L$ and then iterate through all $R$ in order. Consider we know that $D(L, R) = G$ then $D(L, R + 1) = gcd(G, A_{}(R + 1))$. If $D(L, R) = 1$ then you can make all the elements in $(R - L + 1) + (n - 1)$. Answer is minimum possible $D(L, R)$ over all possible segments.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "891",
    "index": "B",
    "title": "Gluttony",
    "statement": "You are given an array $a$ with $n$ distinct integers. Construct an array $b$ by permuting $a$ such that for every non-empty subset of indices $S = {x_{1}, x_{2}, ..., x_{k}}$ ($1 ≤ x_{i} ≤ n$, $0 < k < n$) the sums of elements on that positions in $a$ and $b$ are different, i. e.\n\n\\[\n\\textstyle\\sum_{i=1}^{k}a_{x_{i}}\\neq\\sum_{i=1}^{k}b_{x_{i}}.\n\\]",
    "tutorial": "Sort the array and shift it by one. This array will be an answer. Proof: When we shift the sorted array all of the elements become greater except the first one, consider $f = {1, 2, ..., n}$ and $t = {x_{1}, x_{2}, ..., x_{k}}$ if 1 wasn't in t we would have $\\textstyle\\sum_{i=1}^{k}b_{x_{i}}>\\sum_{i=1}^{k}a_{x_{i}}$ $\\textstyle\\sum_{i=1}^{n-k}b_{y_{i}}>\\sum_{i=1}^{n-k}a_{y}$ $\\textstyle\\sum_{i=1}^{k}b_{x_{i}}<\\sum_{i=1}^{k}a_{x_{i}},$",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "891",
    "index": "C",
    "title": "Envy",
    "statement": "For a connected undirected weighted graph $G$, MST (minimum spanning tree) is a subgraph of $G$ that contains all of $G$'s vertices, is a tree, and sum of its edges is minimum possible.\n\nYou are given a graph $G$. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jealous. You are given some queries, each query contains a set of edges of graph $G$, and you should determine whether there is a MST containing all these edges or not.",
    "tutorial": "It can be proven that there's a MST containing these edges if and only if there are MSTs that contain edges with same weight. So for each query we need to check if the edges with weight X have a MST. For checking this, if we remove all edges with weight greater than or equal to X, and consider each connected component of this graph as a vertex, the edges given in query with weight X should form a cycle in this new graph. We can check this for all queries offline by sorting edges from minimum weight and do simple dfs for each weight in each query.",
    "tags": [
      "data structures",
      "dsu",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "891",
    "index": "D",
    "title": "Sloth",
    "statement": "Sloth is bad, mkay? So we decided to prepare a problem to punish lazy guys.\n\nYou are given a tree, you should count the number of ways to remove an edge from it and then add an edge to it such that the final graph is a tree and has a perfect matching. Two ways of this operation are considered different if their removed edges or their added edges aren't the same. The removed edge and the added edge can be equal.\n\nA perfect matching is a subset of edges such that each vertex is an endpoint of exactly one of these edges.",
    "tutorial": "If graph had odd number of vertices the answer is $0$. Otherwise let's call edges that by removing them the remaining graph would have two even components good, and all the other edges are bad. If you remove a good edge and put another edge somewhere such that the final graph is a tree, then it would have prefect matching if and only if the input tree had prefect matching. If no two bad edges share a vertex, after removing a bad edge (lets call it $X$) we should chose the end points of the edge we want to add (lets call them $v$,$u$) such that the path between $v$ and $u$ in the input tree has alternately bad and good edges, the first and the last edges in the path are bad and $X$ is in this path too. So for any path in the tree that has alternately bad and good edges and the first and final edges in it are bad we should add the $\\frac{L e n g t h O f T h i s P a t h+1}$ to the answer. This can be done using dp. If there are bad edges that share vertices, we know that each vertex has odd number of bad edges to its neighbors, and if this number is greater than 3 then the answer is 0. So each vertex has 1 or 3 odd edges to its neighbors. The path between end points of added edge should contain all the vertices with 3 bad edges and also two of their bad edges should be in the path. So if the vertices with 3 bad edges aren't in a path with this condition then the answer is 0 and otherwise we can calculate the answer by checking some conditions in their path and counting the number of paths with some condition at the end points of their path.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n \n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \nconst int maxn = 500005;\n \nvector<int> gr[maxn];\nint ansdown[maxn][2];\nint ansdownif[maxn][2][3][2][2];\nint sz[maxn];\nint cntbad[maxn], cntodd[maxn];\nint n;\nll answer;\nbool isok[maxn];\n \nvoid calcdown(int cur, int pr)\n{\n    sz[cur] = 1;\n    for (auto t : gr[cur]) if (t != pr)\n    {\n        calcdown(t, cur);\n        sz[cur] += sz[t];\n    }\n    ansdown[cur][0] = 0;\n    ansdown[cur][1] = 0;\n    isok[cur] = true;\n    cntodd[cur] = 0;\n    cntbad[cur] = 0;\n    for (auto t : gr[cur]) if (t != pr)\n    {\n        isok[cur] &= isok[t];\n        cntbad[cur] += !isok[t];\n        cntodd[cur] += sz[t] % 2;\n    }\n    isok[cur] &= cntodd[cur] <= 1;\n    ansdown[cur][0] += (isok[cur] && cntodd[cur] + (n - sz[cur]) % 2 <= 1); // 0\n    ansdown[cur][1] += (isok[cur] && cntodd[cur] + (n - sz[cur] + 1) % 2 + 1 <= 1); // 1\n    for (auto t : gr[cur]) if (t != pr)\n    {\n        for (int kbad = 0; kbad <= 1; kbad++)\n        {\n            for (int kodd = 0; kodd <= 2; kodd++)\n            {\n                for (int oddabove = 0; oddabove <= 1; oddabove++)\n                {\n                    // try 0\n                    if ((kbad == 0 || !isok[t]) && kodd + oddabove == 1) // t has the same parity\n                    {\n                        ansdownif[cur][kbad][kodd][oddabove][0] += ansdown[t][0];\n                    }\n                    // try 1\n                    if ((kbad == 0 || !isok[t]) && kodd - sz[t] % 2 + (sz[t] + 1) % 2 + (oddabove + 1) % 2 == 1) // t has another parity\n                    {\n                        ansdownif[cur][kbad][kodd][oddabove][1] += ansdown[t][1];\n                    }\n                }\n            }\n        }\n    }\n    if (cntbad[cur] <= 1 && cntodd[cur] <= 2)\n    {\n        ansdown[cur][0] += ansdownif[cur][cntbad[cur]][cntodd[cur]][(n - sz[cur]) % 2][0];\n        ansdown[cur][1] += ansdownif[cur][cntbad[cur]][cntodd[cur]][(n - sz[cur]) % 2][1];\n    }\n}\n \nvoid calcup(int cur, int pr, int ansup0, int ansup1, bool isupok)\n{\n    if (pr != -1)\n    {\n        if (sz[cur] % 2 == 0)\n        {\n            answer += (ll)ansup0 * ansdown[cur][0];\n        } else\n        {\n            answer += (ll)ansup1 * ansdown[cur][1];\n        }\n    }\n    for (auto t : gr[cur]) if (t != pr)\n    {\n        int nowcntbad = cntbad[cur] + !isupok - !isok[t];\n        int nowcntodd = cntodd[cur] + (n - sz[cur]) % 2 - sz[t] % 2;\n        bool isnewok = isupok && (cntbad[cur] == 0 || (cntbad[cur] == 1 && !isok[t]));\n        isnewok &= nowcntodd <= 1;\n        if (nowcntbad > 1 || nowcntodd > 2) continue;\n        int curansup0 = ansdownif[cur][nowcntbad][nowcntodd][sz[t] % 2][0];\n        int curansup1 = ansdownif[cur][nowcntbad][nowcntodd][sz[t] % 2][1];\n \n        if (isnewok && nowcntodd + sz[t] % 2 <= 1) curansup0++;\n        if (isnewok && nowcntodd + 1 + (sz[t] + 1) % 2 <= 1) curansup1++;\n \n        if ((nowcntbad == 0 || !isupok) && nowcntodd + sz[t] % 2 == 1) curansup0 += ansup0;\n        if ((nowcntbad == 0 || !isupok) && nowcntodd - (n - sz[cur]) % 2 + (n - sz[cur] + 1) % 2 + (sz[t] + 1) % 2 == 1) curansup1 += ansup1;\n        \n        \n        // try 0\n        if ((nowcntbad == 0 || !isok[t]) && nowcntodd + sz[t] % 2 == 1) // t has the same parity\n        {\n            curansup0 -= ansdown[t][0];\n        }\n        // try 1\n        if ((nowcntbad == 0 || !isok[t]) && nowcntodd - sz[t] % 2 + (sz[t] + 1) % 2 + (sz[t] + 1) % 2 == 1) // t has another parity\n        {\n            curansup1 -= ansdown[t][1];\n        }\n        \n        calcup(t, cur, curansup0, curansup1, isnewok);\n    }\n}\n \nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n - 1; i++)\n    {\n        int a, b;\n        scanf(\"%d%d\", &a, &b);\n        a--, b--;\n        gr[a].pb(b);\n        gr[b].pb(a);\n    }\n    if (n % 2 == 1)\n    {\n        cout << 0 << endl;\n        return 0;\n    }\n    calcdown(0, -1);\n    calcup(0, -1, 0, 0, 1);\n    cout << answer << endl;\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graph matchings",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "891",
    "index": "E",
    "title": "Lust",
    "statement": "A false witness that speaketh lies!\n\nYou are given a sequence containing $n$ integers. There is a variable $res$ that is equal to $0$ initially. The following process repeats $k$ times.\n\nChoose an index from $1$ to $n$ uniformly at random. Name it $x$. Add to $res$ the multiply of all $a_{i}$'s such that $1 ≤ i ≤ n$, but $i ≠ x$. Then, subtract $a_{x}$ by $1$.\n\nYou have to find expected value of $res$ at the end of the process. It can be proved that the expected value of $res$ can be represented as an irreducible fraction $\\frac{P}{Q}$. You have to find $P\\cdot Q^{-1}\\mathrm{~mod~}10000000007$.",
    "tutorial": "Lemma : expected value of res is equal to multiply of $a_{i}$s minus expected value of multiply of $a_{i}$s at the end of process. Prove : Imagine that at the end of process, $a_{i}$ turns to $b_{i}$ ($b_{i}  \\le  a_{i}$). For this case, it is easy to prove that res is equal to multiply of $a_{i}$s minus multiply of $b_{i}$s (can be proved by induction). So we can see truth of lemma. Define $dp_{mask, k}$ as expected value of multiply of mask's subset after k'th repeat. Now we want to calculate this dp. Fix index of k'th chosen number. If mask's subset contains that fixed number, then expected value of multiply of mask's subset decreases by expected value of $dp_{mask2, k - 1}$ (mask2 is equal to subset of mask minus chosen fixed number). If mask's subset doesn't contains fixed index, then expected value of multiply of mask's subset doesn't change. More formally , for all indices i from 1 to n : $d p_{m a s k,k}+=\\operatorname*{i}_{n}*d p_{m a s k,k-1}-{\\mathfrak{i}}_{n}*d p_{m a s k-2^{i},k-1}$. (If mask contains i'th element). $d p_{m a s k,k}+={\\operatorname*{i}}_{n}^{1}*d p_{m a s k,k-1}$ (If mask dosent contains i'th element) So we can write : $dp_{mask, k} + = dp_{mask, k - 1}$ $d p_{m a s k,k}-\\mathrm{=\\frac{i}{n}*}d p_{m a s k-2i,k-1}$ (If mask contains i'th element) After calculating this dp, we can find expected value of res, using lemma and $dp_{2^{n} - 1, k}$. This algorithm runs in $O(2^{n} * k * n)$. Now we want to optimize this solution. First of all, we can calculate this dp , using matrix exponential; because $dp_{mask, k}$ updates by a coefficient from $dp_{mask2, k - 1}$. so if we write coefficient of update $dp_{mask, k}$ from $dp_{mask2, k - 1}$ in $matrix_{mask, mask2}$ , and write multiply of mask subset if $e_{mask}$, then $2^{n} - 1$'th element of $matrix^{k} * e$, equals to expected value of $a_{i}$s after k'th repeat process. After his optimization, algorithm runs in $O(2^{3n} * lgk)$. In our second solution, we learned that expected value of multiply of $a_{i}$'s after k'th operation (name it as $s$) equals to $2^{n} - 1$'th element of $matrix^{k} * e$. this element equals to $\\sum_{i=0}^{2^{n}}m a t r i x^{k}2^{n}-1.i\\star e_{i}$. Now we want to calculate coefficients of $matrix^{k}_{2^{n} - 1}$. by this coefficients, we can calculate value $s$. if we take a look at update of $dp_{mask, k}$, we can define another meaning for this $dp$. imagine directed hypercube $Q_{n}$ and add a self loop for every vertex. now $dp_{mask, k}$, can be this : for every walk that ends in $mask$ in $k$ moves, add $\\left(\\frac{-1}{n}\\right)^{n u m b e r o\\hat{f}n o n s e l f l o o p e d g e s}$ to $dp_{mask, k}$. So it's easy to see that all $mask$s that have equal number of elements, have equal $dp_{mask, k}$. (regardless of base of $dp$) So $matrix^{k}_{2^{n} - 1, mask}$ is equals to this value for walks from mask to $2^{n} - 1$. Now, by fixing non self loop edges, we can see that $matrix^{k}_{2^{n} - 1, mask}$ is equal to : $({\\frac{-1}{n}})^{n u m b e r o f z e r o s i n m a s k}*k*(k-1)*\\ldots*(k-(n u m b e r o f z e r o s i n m a s k+1)$ So this value is equal for all masks with equal ones. name this value by $Z_{numberofonesinmask}$. By our equation : $matrix^{k}_{2^{n} - 1, mask} * e_{mask}$ (for $0  \\le  mask < 2^{n}$) $Z_{numberofonesinmask} * e_{mask}$ (for $0  \\le  mask < 2^{n}$) $Z_{W}*\\left(\\sum_{a l l m a s k s a w i t h W o n e s}{\\mathcal{C}}_{m a s k}\\right)$(for $0  \\le  w  \\le  n$) So $Z_{w}$'s can be easily calculated in $O(n)$. Now we want to calculate $\\textstyle\\sum e_{m a s k}$ (for all masks with w ones). (for $0  \\le  w  \\le  n$). This value can be calculated by $dp_{i, j}$ (sigma of j_tuples multiplies in first i elements) in $O(n^{2})$. So, finally, this algorithm runs if $O(n^{2} + lg(k))$",
    "tags": [
      "combinatorics",
      "math",
      "matrices"
    ],
    "rating": 3000
  },
  {
    "contest_id": "892",
    "index": "A",
    "title": "Greed",
    "statement": "Jafar has $n$ cans of cola. Each can is described by two integers: remaining volume of cola $a_{i}$ and can's capacity $b_{i}$ ($a_{i}$ $ ≤ $ $b_{i}$).\n\nJafar has decided to pour all remaining cola into just $2$ cans, determine if he can do this or not!",
    "tutorial": "we sort the capacities in nonincreasing order and let $s = capacity_{1} + capacity_{2}$ if $s<\\sum_{i=1}^{n}a_{i}$",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "892",
    "index": "B",
    "title": "Wrath",
    "statement": "Hands that shed innocent blood!\n\nThere are $n$ guilty people in a line, the $i$-th of them holds a claw with length $L_{i}$. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the $i$-th person kills the $j$-th person if and only if $j < i$ and $j ≥ i - L_{i}$.\n\nYou are given lengths of the claws. You need to find the total number of alive people after the bell rings.",
    "tutorial": "The i'th person will be alive if $min(j - L_{j}) > i$ over all $j > i$. Consider you know the $j$th person is alive or not if $j > i$ and you have $x = min(j - L_{j})$ over all $j > i$. If $x > i$ then the $i$th person will be alive. And you can update $x$ easily.",
    "tags": [
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "893",
    "index": "A",
    "title": "Chess For Three",
    "statement": "Alex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three.\n\nSo they play with each other according to following rules:\n\n- Alex and Bob play the first game, and Carl is spectating;\n- When the game ends, the one who lost the game becomes the spectator in the next game, and the one who was spectating plays against the winner.\n\nAlex, Bob and Carl play in such a way that there are no draws.\n\nToday they have played $n$ games, and for each of these games they remember who was the winner. They decided to make up a log of games describing who won each game. But now they doubt if the information in the log is correct, and they want to know if the situation described in the log they made up was possible (that is, no game is won by someone who is spectating if Alex, Bob and Carl play according to the rules). Help them to check it!",
    "tutorial": "This task is about pure implementation. Maintain the number of current spectator and check if he doesn't win. With knowledge of current winner $w$ and current spectator $s$ you can easily get the third player by formula $6 - w - s$ (just the sum of all numbers without the known ones). Overall complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "893",
    "index": "B",
    "title": "Beautiful Divisors",
    "statement": "Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of $k + 1$ consecutive ones, and then $k$ consecutive zeroes.\n\nSome examples of beautiful numbers:\n\n- $1_{2}$ ($1_{10}$);\n- $110_{2}$ ($6_{10}$);\n- $1111000_{2}$ ($120_{10}$);\n- $111110000_{2}$ ($496_{10}$).\n\nMore formally, the number is beautiful iff there exists some positive integer $k$ such that the number is equal to $(2^{k} - 1) * (2^{k - 1})$.\n\nLuba has got an integer number $n$, and she wants to find its greatest beautiful divisor. Help her to find it!",
    "tutorial": "Let's notice that there are only $8$ beautiful numbers less than $10^{5}$. Generate them all and select the greatest one which is also divisor of $n$. Overall complexity: $O(1)$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "893",
    "index": "C",
    "title": "Rumor",
    "statement": "Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.\n\nNow he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.\n\nVova knows that there are $n$ characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; $i$-th character wants $c_{i}$ gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.\n\nThe quest is finished when all $n$ characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?\n\nTake a look at the notes if you think you haven't understood the problem completely.",
    "tutorial": "In this problem you are given an undirected graph with weighted vertices. And the problem is to calculate the sum of minimum values in every connected component. To do this we just need to run DFS or BFS several times.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "893",
    "index": "D",
    "title": "Credit Card",
    "statement": "Recenlty Luba got a credit card and started to use it. Let's consider $n$ consecutive days Luba uses the card.\n\n\\textbf{She starts with $0$ money on her account.}\n\nIn the \\textbf{evening} of $i$-th day a transaction $a_{i}$ occurs. If $a_{i} > 0$, then $a_{i}$ bourles are deposited to Luba's account. If $a_{i} < 0$, then $a_{i}$ bourles are withdrawn. And if $a_{i} = 0$, then the amount of money on Luba's account is checked.\n\nIn the \\textbf{morning} of any of $n$ days Luba can go to the bank and deposit any \\textbf{positive} integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed $d$.\n\n\\textbf{It can happen that the amount of money goes greater than $d$ by some transaction in the evening. In this case answer will be «-1».}\n\nLuba must not exceed this limit, and also she wants that \\textbf{every day her account is checked} (the days when $a_{i} = 0$) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!",
    "tutorial": "The following greedy solution works. Firstly, deposite money only on days with $a_{i} = 0$. Secondly, every time the balance is negative to the day with $a_{i} = 0$, refill it to maximal possible value such that it won't go over $d$ later. Days with $a_{i}  \\neq  0$ can only lead to invalid state by going over card limit. We can only add money to the balance. Adding zero money in those days won't make invalid states if all were valid previously. Finally, if it's possible to get valid state in every day then it's possible to get it by refilling the same day the check happens. For example, you can make $max(0, currentBalance)$ balance in those days. Then you will never have negative balance there. Though it's not the most optimal way. Let $delta$ be some value you deposite in some day with $a_{i} = 0$ to pass all conditions till the next day with $a_{j} = 0$. I state that function of number of game's moves dependancy on $delta$ is monotonious. Let's check it for some fixed $x$. Define minimum balance you will get on any suffix from now as $minBal$. Obviously, taking $x - 1$ will make it $minBal - 1$. If it goes negative then you will need an extra move to finish the game. Thus taking maximal $delta$ will lead to the lowest score possible. And last but not least - realization part. What will be the maximum possible value to deposite? Actually, it's such a value that optimal game after this will lead to maximum balance of $d$ in some day. Thus, you want to check what will be the maximum balance $maxBal$ if you add zero money and take $delta$ as $d - maxBal$. Obviously, if it's negative then output $- 1$. Naively this still works on $O(n)$ per day and lead to $O(n^{2})$ overall. Notice that by depositing $delta$ you increase maximums on each suffix for now by $delta$. So, you can calculate it as you will do nothing and add sum $deltaSum$ of your $delta$'s to get actual value. You store prefix sum of $a_{j}$ up to $i$ in $pr_{i}$. Then take maximum on suffix for every $i$ ($su_{i}$ is the maxumum $pr_{j}$ for $j$ from $i$ to $n$). $delta = d - (deltaSum + su_{i})$. I hope I made it clear enough. :D Overall comlpexity: $O(n)$.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "893",
    "index": "E",
    "title": "Counting Arrays",
    "statement": "You are given two positive integer numbers $x$ and $y$. An array $F$ is called an $y$-factorization of $x$ iff the following conditions are met:\n\n- There are $y$ elements in $F$, and all of them are integer numbers;\n- $\\prod_{i=1}^{y}F_{i}=x$.\n\nYou have to count the number of pairwise distinct arrays that are $y$-factorizations of $x$. Two arrays $A$ and $B$ are considered different iff there exists at least one index $i$ ($1 ≤ i ≤ y$) such that $A_{i} ≠ B_{i}$. Since the answer can be very large, print it modulo $10^{9} + 7$.",
    "tutorial": "Fill the array with ones. Now we should take every prime divisor $i$ of $x$ and distribute $cnt_{i}$ (maximum power of this prime to appear in $x$) of it into some cells of the array. It is pretty well-known problem, it's equal to $\\left\\langle\\int_{0}^{+\\left|{\\mathcal{H}}\\left|t_{\\mathrm{i}}-\\right|}\\right\\rangle$. Take product of this values for every prime $i$. This will be the answer if there were no negative numbers. But we should also multiply it by number of ways to select even number of position to put unary minuses - $2^{y - 1}$ (like you can fill in $y - 1$ position anyhow and the final one will be determined by parity of current count). To process many queries you should factorize numbers in $O(\\log n)$ (by precalcing the smallest prime divisor of every number up to $10^{6}$ with sieve of Eratosthenes), get $\\textstyle{\\binom{n}{k}}$ in $O(1)$ (by precalcing factorials and inverse factorials) and get $2^{k}$ in $O(\\log n)$ (binary exponentiation). Overall complexity: $O(M A X N\\cdot\\log M A X\\,\\textstyle N+n\\cdot\\log M A X\\,\\textstyle A X\\,\\textstyle N\\,)$.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "893",
    "index": "F",
    "title": "Subtree Minimum Query",
    "statement": "You are given a rooted tree consisting of $n$ vertices. Each vertex has a number written on it; number $a_{i}$ is written on vertex $i$.\n\nLet's denote $d(i, j)$ as the distance between vertices $i$ and $j$ in the tree (that is, the number of edges in the shortest path from $i$ to $j$). Also let's denote the $k$-blocked subtree of vertex $x$ as the set of vertices $y$ such that both these conditions are met:\n\n- $x$ is an ancestor of $y$ (every vertex is an ancestor of itself);\n- $d(x, y) ≤ k$.\n\nYou are given $m$ queries to the tree. $i$-th query is represented by two numbers $x_{i}$ and $k_{i}$, and the answer to this query is the minimum value of $a_{j}$ among such vertices $j$ such that $j$ belongs to $k_{i}$-blocked subtree of $x_{i}$.\n\nWrite a program that would process these queries quickly!\n\n\\textbf{Note that the queries are given in a modified way}.",
    "tutorial": "The main idea is to use a two-dimensional data structure: one dimension is depth of vertices, and other dimension is the time we entered a vertex during DFS. Model solution uses sparse table for these purposes. First of all, let's renumerate the vertices so we can handle them easier. We run DFS from the root and then sort the vertices by their depth (and if depths are equal, by time we entered them in DFS). Then we renumerate vertices in this sorted order. We need to denote some functions in order to continue: $D(x)$ - depth of vertex $x$ in the tree; $tin(x)$ - the time we entered $x$ during DFS; $tout(x)$ - the time we left $x$ during DFS. For each depth we can store a sorted array of vertices belonging do this depth. This will allow us to build an auxiliary sparse table $lf$, where $lf[i][x]$ is such vertex $j$ that: $D(j) = D(x) + 2^{i}$; $tin(j) > tin(x)$; $tin(j)$ is minimal among all vertices that meet first two conditions. We also need a second sparse table $rg$, where $rg[i][x]$ is $j$ iff: $D(j) = D(x) + 2^{i}$; $tout(j) > tout(x)$; $tout(j)$ is minimal among all vertices that meet first two conditions. These sparse tables can be built using binary search in arrays we created for depths. Okay, why do we need them? To create a third sparse table that will process the queries themselves: $table[i][j][x]$ - the minimum value of $a_{y}$ among vertices $y$ such that $y$ belongs to $2^{j}$-blocked subtree of some vertex with index included in $[x, x + 2^{i})$. This table can be built backwards with the help of auxiliary tables. So, how do we answer the queries? We need to look at the binary representation of $k + 1$ and do something like binary lifting (but descending the tree instead of ascending) and maintain the leftmost and the rightmost vertices on current depth which belong to the subtree we are interested in (and make queries to $table$ on the segment between these two vertices). This solution works in $O(n\\log^{2}n+m\\log n)$, but, unfortunately (or fortunately to some participants), we made the time limit too high so the structures that require $O(\\log^{2}n)$ time to process each query, such as two-dimensional segment trees, might also get AC.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "894",
    "index": "A",
    "title": "QAQ",
    "statement": "\"QAQ\" is a word to denote an expression of crying. Imagine \"Q\" as eyes with tears and \"A\" as a mouth.\n\nNow Diamond has given Bort a string consisting of only uppercase English letters of length $n$. There is a great number of \"QAQ\" in the string (Diamond is so cute!).\n\n\\begin{center}\n{\\tiny illustration by 猫屋 https://twitter.com/nekoyaliu}\n\\end{center}\n\nBort wants to know how many subsequences \"QAQ\" are in the string Diamond has given. Note that the letters \"QAQ\" don't have to be consecutive, but the order of letters should be exact.",
    "tutorial": "Since $n  \\le  100$, we can iterate on the place of first 'Q','A' and second 'Q'. The brute force solution will work in $O(n^{3})$ time which can surely pass. If we only iterate on the place of 'A', we can get the number of 'Q' before and after it using prefix sums, and it leads to $O(n)$ solution.",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 800
  },
  {
    "contest_id": "894",
    "index": "B",
    "title": "Ralph And His Magic Field",
    "statement": "Ralph has a magic field which is divided into $n × m$ blocks. That is to say, there are $n$ rows and $m$ columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to $k$, where $k$ is either 1 or -1.\n\nNow Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo $1000000007 = 10^{9} + 7$.\n\nNote that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity.",
    "tutorial": "First, it's obvious that the numbers put can be only 1 or -1. If $k$ equals to -1 and the parity of $n$ and $m$ differ, the answer is obviously $0$. Otherwise, for the first $(n - 1)$ lines and the first $(m - 1)$ columns, we can put either 1 or -1 in it, and there're $pow(2, [(n - 1) * (m - 1)])$ ways in total. Then it's obvious that the remaining numbers are uniquely determined because the product of each row and each column is known already. So in this case the answer is $pow(2, [(n - 1) * (m - 1)])$ .",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "894",
    "index": "C",
    "title": "Marco and GCD Sequence",
    "statement": "In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.\n\nWhen he woke up, he only remembered that the key was a sequence of positive integers of some length $n$, but forgot the exact sequence. Let the elements of the sequence be $a_{1}, a_{2}, ..., a_{n}$. He remembered that he calculated $gcd(a_{i}, a_{i + 1}, ..., a_{j})$ for every $1 ≤ i ≤ j ≤ n$ and put it into a set $S$. $gcd$ here means the greatest common divisor.\n\nNote that even if a number is put into the set $S$ twice or more, it only appears once in the set.\n\nNow Marco gives you the set $S$ and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set $S$, in this case print -1.",
    "tutorial": "If the minimum element isn't the gcd of the given set, the answer is -1. Otherwise, we can insert the minimum element between two consecutive elements of the set. And the length of the sequence is $2n - 1$ which satisfies the constraints.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "894",
    "index": "D",
    "title": "Ralph And His Tour in Binary Country",
    "statement": "Ralph is in the Binary Country. The Binary Country consists of $n$ cities and $(n - 1)$ bidirectional roads connecting the cities. The roads are numbered from $1$ to $(n - 1)$, the $i$-th road connects the city labeled $\\textstyle{\\left\\lfloor{\\frac{(i+1)}{2}}\\right\\rfloor}$ (here $⌊ x⌋$ denotes the $x$ rounded down to the nearest integer) and the city labeled $(i + 1)$, and the length of the $i$-th road is $L_{i}$.\n\nNow Ralph gives you $m$ queries. In each query he tells you some city $A_{i}$ and an integer $H_{i}$. He wants to make some tours starting from this city. He can choose any city in the Binary Country (including $A_{i}$) as the terminal city for a tour. He gains happiness $(H_{i} - L)$ during a tour, where $L$ is the distance between the city $A_{i}$ and the terminal city.\n\nRalph is interested in tours from $A_{i}$ in which he can gain positive happiness. For each query, compute the sum of happiness gains for all such tours.\n\nRalph will never take the same tour twice or more (in one query), he will never pass the same city twice or more in one tour.",
    "tutorial": "Before answering each query, pre-process on the tree. On each vertice, we can get a sorted array of all the vertices in its subtree sorted by distance to this vertex. And it costs $O(nlog(n))$ time using merge sort or $O(n(log(n))^{2})$ time using std::sort. If you use std::sort, you should implement it carefully or it won't be able to fit in the time limit. Because the tree is an almost complete binary tree, one vertex will appear at most $[log(n)]$ times in all $n$ sorted arrays,so the memory complexity is $O(nlog(n))$. To answer each query, we can iterate on the highest vertex on the tour and do binary search on the sorted array to get the answer. We'll do at most $[log(n)]$ times of iteration and the binary search is $O(log(n))$ per iteration, so we can answer each query in $O((log(n))^{2})$ time. Overall, the time complexity is $O(nlog(n) + m(log(n))^{2})$ and the memory complexity is $O(nlog(n))$. If you use std::sort, the time complexity will be $O((n + m)(log(n))^{2})$ and the memory complexity is the same.",
    "tags": [
      "brute force",
      "data structures",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "894",
    "index": "E",
    "title": "Ralph and Mushrooms",
    "statement": "Ralph is going to collect mushrooms in the Mushroom Forest.\n\nThere are $m$ directed paths connecting $n$ trees in the Mushroom Forest. On each path grow some mushrooms. When Ralph passes a path, he collects all the mushrooms on the path. The Mushroom Forest has a magical fertile ground where mushrooms grow at a fantastic speed. New mushrooms regrow as soon as Ralph finishes mushroom collection on a path. More specifically, after Ralph passes a path the $i$-th time, there regrow $i$ mushrooms less than there was before this pass. That is, if there is initially $x$ mushrooms on a path, then Ralph will collect $x$ mushrooms for the first time, $x - 1$ mushrooms the second time, $x - 1 - 2$ mushrooms the third time, and so on. However, the number of mushrooms can never be less than $0$.\n\nFor example, let there be $9$ mushrooms on a path initially. The number of mushrooms that can be collected from the path is $9$, $8$, $6$ and $3$ when Ralph passes by from first to fourth time. From the fifth time and later Ralph can't collect any mushrooms from the path (but still can pass it).\n\nRalph decided to start from the tree $s$. How many mushrooms can he collect using only described paths?",
    "tutorial": "For collecting the most mushrooms, when in a strongly-connected component we can pass all the edges in the component until the mushrooms on the edges are all $0$. So we can run Tarjan's algorithm to find all the SCCs in $O(n + m)$ time and calculate the sum of mushrooms picked in each component by binary search or maths knowledge in $O(m)$ time. Then we can regard each SCC as a new vertex and get a DAG, and the remaining work is just to find the longest path on the DAG from a given vertex, where the length of an edge is the number of mushrooms in it initially, since we can only pass through it once. We can use topological sort and apply dynamic programming on the DAG in $O(n + m)$ time. Overall, the time complexity is $O(n + m)$.",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "895",
    "index": "A",
    "title": "Pizza Separation",
    "statement": "Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into $n$ pieces. The $i$-th piece is a sector of angle equal to $a_{i}$. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.",
    "tutorial": "We can notice that if one of the sectors is continuous then all the remaining pieces also form a continuous sector.If angle of the first sector is equal to $x$ then difference between angles of first and second sectors is $|x - (360 - x)| = |2 * x - 360| = 2 * |x - 180|$. So for each possible continuous sector we can count it's angle and update answer. Time complexity $O(n^{2})$ or $O(n)$.",
    "code": "\"#include <iostream>\\n#include <algorithm>\\n\\nusing namespace std;\\n\\nint n;\\nint sum;\\nint l, r;\\nint ans = 360;\\nint a[360];\\n\\nint main()\\n{\\n\\tcin >> n;\\n\\tfor (int i = 0; i < n; i++)\\n\\t\\tcin >> a[i];\\n\\twhile (r < n)\\n\\t{\\n\\t\\tsum += a[r];\\n\\t\\twhile (sum >= 180)\\n\\t\\t{\\n\\t\\t\\tans = min(ans, 2 * abs(180 - sum));\\n\\t\\t\\tsum -= a[l];\\n\\t\\t\\tl++;\\n\\t\\t}\\n\\t\\tans = min(ans, 2 * abs(180 - sum));\\n\\t\\tr++;\\n\\t}\\n\\tcout << ans << endl;\\n}\"",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "895",
    "index": "B",
    "title": "XK Segments",
    "statement": "While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array $a$ and integer $x$. He should find the number of different ordered pairs of indexes $(i, j)$ such that $a_{i} ≤ a_{j}$ and there are exactly $k$ integers $y$ such that $a_{i} ≤ y ≤ a_{j}$ and $y$ is divisible by $x$.\n\nIn this problem it is meant that pair $(i, j)$ is equal to $(j, i)$ only if $i$ is equal to $j$. For example pair $(1, 2)$ is not the same as $(2, 1)$.",
    "tutorial": "First, we need to understand how to find the number of integers in $[l, r]$ segment which are divisible by $x$. It is $r / x-(l - 1) / x$. After that we should sort array in ascending order. For each left boundary of the segment $l = a[i]$ we need to find minimal and maximal index of good right boundaries. All right boundaries $r = a[j]$ should satisfy the following condition $a[j] / x-(a[i] - 1) / x = k$. We already know $(a[i] - 1) / x$, $a[j] / x$ is increasing while $a[j]$ increases. So we can do binary search on sorted array to find minimal/maximal index of good right boundaries and that mean we can find the number of good right boundaries. Time complexity $O(n * log(n))$.",
    "code": "\"#include <iostream>\\n#include <algorithm>\\n\\nusing namespace std;\\ntypedef long long ll;\\n\\nll n, x, k;\\nll a[100100];\\nll ans;\\n\\nll solve(ll le, ll ri)\\n{\\n\\tif (le > a[n - 1] || ri < a[0])\\n\\t\\treturn 0;\\n\\tll res = 0;\\n\\tint l = 0;\\n\\tint r = n - 1;\\n\\tint m;\\n\\twhile (r - l > 1)\\n\\t{\\n\\t\\tm = (l + r) / 2;\\n\\t\\tif (a[m] >= le)\\n\\t\\t\\tr = m;\\n\\t\\telse\\n\\t\\t\\tl = m;\\n\\t}\\n\\tif (a[l] >= le)\\n\\t\\tm = l;\\n\\telse\\n\\t\\tm = r;\\n\\tres = m;\\n\\tl = 0;\\n\\tr = n - 1;\\n\\twhile (r - l > 1)\\n\\t{\\n\\t\\tm = (l + r) / 2;\\n\\t\\tif (a[m] <= ri)\\n\\t\\t\\tl = m;\\n\\t\\telse\\n\\t\\t\\tr = m;\\n\\t}\\n\\tif (a[r] <= ri)\\n\\t\\tm = r;\\n\\telse\\n\\t\\tm = l;\\n\\treturn m - res + 1;\\n}\\n\\nint main()\\n{\\n\\tcin >> n >> x >> k;\\n\\tfor (int i = 0; i < n; i++)\\n\\t\\tcin >> a[i];\\n\\tsort(a, a + n);\\n\\tfor (int i = 0; i < n; i++)\\n\\t{\\n\\t\\tll y = a[i] - 1;\\n\\t\\ty /= x;\\n\\t\\tll le = max(x*(k + y), a[i]);\\n\\t\\tll ri = x*(k + y + 1) - 1;\\n\\t\\tans += solve(le, ri);\\n\\t}\\n\\tcout << ans << endl;\\n}\"",
    "tags": [
      "binary search",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "895",
    "index": "C",
    "title": "Square Subsets",
    "statement": "Petya was late for the lesson too. The teacher gave him an additional task. For some array $a$ Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer.\n\nTwo ways are considered different if sets of indexes of elements chosen by these ways are different.\n\nSince the answer can be very large, you should find the answer modulo $10^{9} + 7$.",
    "tutorial": "We can notice that $x$ is a perfect square of some integer if and only if each prime number enters decomposition of $x$ into prime factors even times. There are only $19$ prime numbers less than $70$. Now we should find the bitmask for each integer in $[1, 70]$ by the following way: There is $1$ in bit representation of mask in $k$-th place if $k$-th prime number enters decomposition of that number odd times. Else there is $0$. For each integer between $1$ and $70$ we need to find the number of ways we can take odd and even amount of it from $a$. Let $f1[i]$, $f0[i]$ be that number of ways relatively. Let $dp[i][j]$ be the number of ways to choose some elements which are <= $i$ from $a$, and their product has only those prime numbers in odd degree on whose index number $j$ has $1$ in binary representation. Initially $dp[0][0] = 1$. $d p[i+1][j\\oplus m a s k[i+1]]+=d p[i][j]*f][i+1]$ $dp[i + 1][j] + = dp[i][j] * f0[i + 1]$ The answer is $dp[70][0]$. Time complexity is $O$($max$*2^cnt(max)), where $max$ is maximal integer $a[i]$, and $cnt(max)$ is the number of prime numbers less than $max$.",
    "code": "\"#define _CRT_SECURE_NO_WARNINGS\\n#include <iostream>\\n#include <fstream>\\n#include <string>\\n#include <iomanip>\\n#include <iterator>\\n#include <bitset>\\n#include <vector>\\n#include <math.h>\\n#include <queue>\\n#include <map>\\n#include <set>\\n#include <list>\\n#include <time.h>\\n#include <algorithm>\\n#define mkp make_pair\\n#define inf 1000000000\\n#define MOD 1000000007\\n#define eps 1e-7\\n\\nusing namespace std;\\ntypedef long long ll;\\n\\nint n;\\nint mask[72];\\nll f[2][72];\\nll dp[2][1 << 20];\\n\\nbool prime(int x)\\n{\\n\\tfor (int i = 2; i*i <= x; i++)\\n\\t\\tif (x%i == 0)\\n\\t\\t\\treturn 0;\\n\\treturn 1;\\n}\\n\\nvoid init()\\n{\\n\\tfor (int i = 0; i < 72; i++)\\n\\t\\tf[0][i] = 1;\\n\\tint cnt = 0;\\n\\tfor (int i = 2; i < 72; i++)\\n\\t{\\n\\t\\tif (!prime(i))\\n\\t\\t\\tcontinue;\\n\\t\\tfor (int j = 1; j < 72; j++)\\n\\t\\t{\\n\\t\\t\\tint x = j;\\n\\t\\t\\twhile (x%i == 0)\\n\\t\\t\\t{\\n\\t\\t\\t\\tx /= i;\\n\\t\\t\\t\\tmask[j] ^= (1 << cnt);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tcnt++;\\n\\t}\\n}\\n\\nint main()\\n{\\n\\tios_base::sync_with_stdio(0);\\n\\tinit();\\n\\tcin >> n;\\n\\tfor (int i = 0; i < n; i++)\\n\\t{\\n\\t\\tint x;\\n\\t\\tcin >> x;\\n\\t\\tf[0][x] = f[1][x] = (f[0][x] + f[1][x]) % MOD;\\n\\t}\\n\\tdp[0][0] = 1;\\n\\tfor (int i = 0; i <= 70; i++)\\n\\t{\\n\\t\\tint nxt = (i + 1) % 2;\\n\\t\\tint cur = i % 2;\\n\\t\\tfor (int msk = 0; msk < (1<<20); msk++)\\n\\t\\t{\\n\\t\\t\\tdp[nxt][msk^mask[i]] = dp[nxt][msk^mask[i]] + dp[cur][msk] * f[1][i];\\n\\t\\t\\tdp[nxt][msk] = dp[nxt][msk] + dp[cur][msk] * f[0][i];\\n\\t\\t\\tif (dp[nxt][msk^mask[i]] >= MOD)\\n\\t\\t\\t\\tdp[nxt][msk^mask[i]] %= MOD;\\n\\t\\t\\tif (dp[nxt][msk] >= MOD)\\n\\t\\t\\t\\tdp[nxt][msk] %= MOD;\\n\\t\\t}\\n\\t\\tfor (int msk = 0; msk < (1<<20); msk++)\\n\\t\\t\\tdp[cur][msk] = 0;\\n\\t}\\n\\tcout << (dp[1][0] - 1 + MOD)%MOD << endl;\\n}\"",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "895",
    "index": "D",
    "title": "String Mark",
    "statement": "At the Byteland State University marks are strings of the same length. Mark $x$ is considered better than $y$ if string $y$ is lexicographically smaller than $x$.\n\nRecently at the BSU was an important test work on which Vasya recived the mark $a$. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark $b$, such that every student recieved mark strictly smaller than $b$.\n\nVasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.\n\nMore formally: you are given two strings $a$, $b$ of the same length and you need to figure out the number of different strings $c$ such that:\n\n1) $c$ can be obtained from $a$ by swapping some characters, in other words $c$ is a permutation of $a$.\n\n2) String $a$ is lexicographically smaller than $c$.\n\n3) String $c$ is lexicographically smaller than $b$.\n\nFor two strings $x$ and $y$ of the same length it is true that $x$ is lexicographically smaller than $y$ if there exists such $i$, that $x_{1} = y_{1}, x_{2} = y_{2}, ..., x_{i - 1} = y_{i - 1}, x_{i} < y_{i}$.\n\nSince the answer can be very large, you need to find answer modulo $10^{9} + 7$.",
    "tutorial": "Suppose that we can calculate the function $f(s)$ equal to the number of permutations of the string $a$ strictly less than $s$. Then the answer is $f(b) - f(a) - 1$. Now we need to understand how to find $f(s)$. First we should count the number of occurrences of each letter in the string $a$, $cnt[26]$.Than we can iterate through the position of the first different symbol in the permutation $a$ and the string $s$ and update the number of remaining symbols $cnt[26]$. For each such position, we need to iterate through the symbol in the permutation of $a$ which will stand in this position. It must be less than the character at this position in the $s$ string. For each such situation we can calculate and add to the answer the number of different permutations that can be obtained using symbols not currently involved. Their number is stored in $cnt[26]$. In its simplest form, this solution works in $O(n * k^{2})$, where $k$ is the size of the alphabet. Such a solution can't pass the tests, but it can be optimized to $O(n * k)$, and that is enough to solve the problem. Time complexity $O(n * k)$, where $k$ is the size of alphabet.",
    "code": "// God & me\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n \nconst int maxn = 1e6 + 17, z = 26, mod = 1e9 + 7;\n \nint n;\nstring a, b;\nint cnt[z], c[z], fac[maxn], rfac[maxn], save_rev[maxn];\n \nint solve(string &s){\n\tmemcpy(c, cnt, sizeof c);\n\tint cur = fac[n];\n\tfor(int i = 0; i < z; i++)\n\t\tif(c[i])\n\t\t\tcur = (ll) cur * rfac[ c[i] ] % mod;\n\tint ans = 0;\n\tfor(int i = 0; i < n; i++){\n\t\tfor(int x = 0; x < s[i] - 'a'; x++)\n\t\t\tif(c[x]){\n\t\t\t\tint now = cur;\n\t\t\t\tnow = (ll) now * save_rev[n - i] % mod;\n\t\t\t\tnow = (ll) now * c[x] % mod;\n\t\t\t\tans = (ans + now) % mod;\n\t\t\t}\n\t\tif(c[ s[i] - 'a' ]){\n\t\t\tcur = (ll) cur * save_rev[n - i] % mod;\n\t\t\tcur = (ll) cur * c[ s[i] - 'a' ] % mod;\n\t\t\tc[ s[i] - 'a' ]--;\n\t\t}\n\t\telse\n\t\t\tbreak;\n\t}\n\treturn ans;\n}\nint rev(int a){\n\tint ret = 1;\n\tfor(int b = mod - 2; b; b >>= 1, a = (ll) a * a % mod)\n\t\tif(b & 1)\n\t\t\tret = (ll) ret * a % mod;\n\treturn ret;\n}\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tfac[0] = rfac[0] = 1;\n\tfor(int i = 1; i < maxn; i++){\n\t\tfac[i] = (ll) i * fac[i - 1] % mod;\n\t\tsave_rev[i] = rev(i);\n\t\trfac[i] = (ll) save_rev[i] * rfac[i - 1] % mod;\n\t}\n\tcin >> a >> b;\n\tn = a.size();\n\tfor(auto c : a)\n\t\tcnt[c - 'a']++;\n\tcout << ((solve(b) + mod - solve(a)) % mod + mod - 1) % mod << '\\n';\n}",
    "tags": [
      "combinatorics",
      "math",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "895",
    "index": "E",
    "title": "Eyes Closed",
    "statement": "Vasya and Petya were tired of studying so they decided to play a game. Before the game begins Vasya looks at array $a$ consisting of $n$ integers. As soon as he remembers all elements of $a$ the game begins. Vasya closes his eyes and Petya does $q$ actions of one of two types:\n\n$1)$ Petya says 4 integers $l1, r1, l2, r2$ — boundaries of two non-intersecting segments. After that he swaps one random element from the $[l1, r1]$ segment with another random element from the $[l2, r2]$ segment.\n\n$2)$ Petya asks Vasya the sum of the elements of $a$ in the $[l, r]$ segment.\n\nVasya is a mathematician so he answers Petya the mathematical expectation of the sum of the elements in the segment.\n\nYour task is to write a program which will answer the second type questions as Vasya would do it. In other words your program should print the mathematical expectation of the sum of the elements of $a$ in the $[l, r]$ segment for every second type query.",
    "tutorial": "For each position we need to maintain mathematical expectation of the value on it. Initially, for position $i$, it is $a[i]$. Let's process the query of the first type. Each number from the interval $[l1, r1]$ remains on its place with probability $(r1 - l1) / (r1 - l1 + 1)$. The probability that it will be replaced by a number from $[l2, r2]$ is $1 / (r1 - l1 + 1)$. The mathematical expectation of the number to which it will be replaced is the arithmetic mean of sum of the mathematical expectation of numbers in $[l2, r2]$, let it be $x$. Then, to update the expectation of a number from $[l1, r1]$, we need to multiply it by $(r1 - l1) / (r1 - l1 + 1)$ and add $x / (r1 - l1 + 1)$ to it. That is, the query of the first type is reduced to the query multiplying all the numbers in a segment and adding to them a number. To process the second type query, you must find the sum of the numbers in the segment. All these queries can be processed with the help of segment tree. Time complexity $O(x + q * log(n))$",
    "code": "// God & me\n#include <bits/stdc++.h>\nusing namespace std;\n \nconst int maxn = 1e5 + 17, lg = 32;\n \nint n, q;\n \n \ndouble iman[maxn << 2];\nstruct lz{\n\tdouble a, b;\n\tlz() : a(1), b(0) {}\n\tlz(double x, double y) : a(x), b(y) {}\n}  sina[maxn << 2];\n \nlz& operator += (lz &a, const lz &b){\n\ta.a *= b.a;\n\ta.b *= b.a;\n\ta.b += b.b;\n\treturn a;\n}\nvoid arpa(int l = 0, int r = n, int id = 1){\n\tif(l + 1 == r){\n\t\tint x;\n\t\tcin >> x;\n\t\timan[id] = x;\n\t\treturn ;\n\t}\n\tint mid = l + r >> 1;\n\tarpa(l, mid, id << 1);\n\tarpa(mid, r, id << 1 | 1);\n\timan[id] = iman[id << 1] + iman[id << 1 | 1];\n}\nvoid sadra(int id, int l, int r){\n\tint mid = l + r >> 1;\n\tlz &x = sina[id];\n\timan[id << 1] = iman[id << 1] * x.a + x.b * (mid - l);\n\timan[id << 1 | 1] = iman[id << 1 | 1] * x.a + x.b * (r - mid);\n\tsina[id << 1] += sina[id];\n\tsina[id << 1 | 1] += sina[id];\n\tsina[id] = lz();\n}\nvoid majid(int s, int e, lz x, int l = 0, int r = n, int id = 1){\n\tif(s <= l && r <= e){\n\t\timan[id] = iman[id] * x.a + x.b * (r - l);\n\t\tsina[id] += x;\n\t\treturn ;\n\t}\n\tif(e <= l || r <= s)\n\t\treturn ;\n\tint mid = l + r >> 1;\n\tsadra(id, l, r);\n\tmajid(s, e, x, l, mid, id << 1);\n\tmajid(s, e, x, mid, r, id << 1 | 1);\n\timan[id] = iman[id << 1] + iman[id << 1 | 1];\n}\ndouble hamid(int s, int e, int l = 0, int r = n, int id = 1){\n\tif(s <= l && r <= e)\n\t\treturn iman[id];\n\tif(e <= l || r <= s)\n\t\treturn 0;\n\tint mid = l + r >> 1;\n\tsadra(id, l, r);\n\treturn hamid(s, e, l, mid, id << 1) + hamid(s, e, mid, r, id << 1 | 1);\n}\nint main(){\n\tios::sync_with_stdio(0), cin.tie(0);\n\tcout << fixed << setprecision(5);\n\tcin >> n >> q;\n\tarpa();\n\twhile(q--){\n\t\tint t, l, r, x, y;\n\t\tcin >> t >> l >> r;\n\t\tl--;\n\t\tif(t == 1){\n\t\t\tcin >> x >> y;\n\t\t\tx--;\n\t\t\tdouble a = hamid(l, r) / (r - l), b = hamid(x, y) / (y - x);\n\t\t\tmajid(l, r, lz({(double) (r - l - 1) / (r - l), b / (r - l)}));\n\t\t\tmajid(x, y, lz({(double) (y - x - 1) / (y - x), a / (y - x)}));\n\t\t}\n\t\telse\n\t\t\tcout << hamid(l, r) << '\\n';\n\t}\n}",
    "tags": [
      "data structures",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "896",
    "index": "A",
    "title": "Nephren gives a riddle",
    "statement": "\\begin{quote}\nWhat are you doing at the end of the world? Are you busy? Will you save us?\n\\end{quote}\n\nNephren is playing a game with little leprechauns.\n\nShe gives them an infinite array of strings, $f_{0... ∞}$.\n\n$f_{0}$ is \"What are you doing at the end of the world? Are you busy? Will you save us?\".\n\nShe wants to let more people know about it, so she defines $f_{i} = $ \"What are you doing while sending \"$f_{i - 1}$\"? Are you busy? Will you send \"$f_{i - 1}$\"?\" for all $i ≥ 1$.\n\nFor example, $f_{1}$ is\n\n\"What are you doing while sending \"What are you doing at the end of the world? Are you busy? Will you save us?\"? Are you busy? Will you send \"What are you doing at the end of the world? Are you busy? Will you save us?\"?\". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of $f_{1}$.\n\nIt can be seen that the characters in $f_{i}$ are letters, question marks, (possibly) quotation marks and spaces.\n\nNephren will ask the little leprechauns $q$ times. Each time she will let them find the $k$-th character of $f_{n}$. The characters are indexed starting from $1$. If $f_{n}$ consists of less than $k$ characters, output '.' (without quotes).\n\nCan you answer her queries?",
    "tutorial": "$f(n) = str_{1} + f(n - 1) + str_{2} + f(n - 1) + str_{3}$. First we can compute the length of $f(n)$ for all possible $n$. For a pair of $(n, k)$, we can easily determine which part the $k$-th character is in. If it's in $f(n - 1)$, we can solve the problem recursively. The complexity of this algorithm is $O(n)$, which is sufficient to pass all tests. Obviously, $length(f(n))  \\ge  length(f(n - 1)) \\cdot 2$, so $length(f(60))  \\ge  k_{max}$. It means that for all $n > 60$, the $k$-th character of $f(n)$ can only be in $str_{1}$ or the first $f(n - 1)$. Then we can answer a query in $O(\\log k)$ time.",
    "tags": [
      "binary search",
      "dfs and similar"
    ],
    "rating": 1700
  },
  {
    "contest_id": "896",
    "index": "B",
    "title": "Ithea Plays With Chtholly",
    "statement": "This is an interactive problem. Refer to the Interaction section below for better understanding.\n\nIthea and Chtholly want to play a game in order to determine who can use the kitchen tonight.\n\nInitially, Ithea puts $n$ clear sheets of paper in a line. They are numbered from $1$ to $n$ from left to right.\n\nThis game will go on for $m$ rounds. In each round, Ithea will give Chtholly an integer between $1$ and $c$, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).\n\nChtholly wins if, at any time, all the sheets are filled with a number and the $n$ numbers are in non-decreasing order looking from left to right from sheet $1$ to sheet $n$, and if after $m$ rounds she still doesn't win, she loses the game.\n\nChtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.",
    "tutorial": "As the initial sheet \"has already\" in a non-decreasing order (although it has no numbers), what we should do is just \"maintain\" this order. We use a simple method to do so: find the first sheet whose number is strictly greater than the given number (or it's an empty sheet) and replace it with the new number. For each round, we either replace an existing number with a strictly smaller one, or fill in an empty sheet. The first case will happen at most $c - 1$ times for each sheet, and the second case will happen only once for each sheet. Thus in total, we will modify a sheet for at most $c$ times. Thus, the total rounds won't be more than $n  \\times  c$. To pass all the tests, we only need to maintain 2 similar sequences, one non-decreasing from the first and one non-increasing from the last, which makes a total round of $(n-1)\\times\\lceil{\\frac{c}{2}}\\rceil+1$, precisely, and use binary search or brute force to complete the \"finding\" process.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "games",
      "greedy",
      "interactive"
    ],
    "rating": 2000
  },
  {
    "contest_id": "896",
    "index": "C",
    "title": "Willem, Chtholly and Seniorious",
    "statement": "\\begin{quote}\n— Willem...\n\n— What's the matter?\n\n— It seems that there's something wrong with Seniorious...\n\n— I'll have a look...\n\\end{quote}\n\nSeniorious is made by linking special talismans in particular order.\n\nAfter over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly.\n\nSeniorious has $n$ pieces of talisman. Willem puts them in a line, the $i$-th of which is an integer $a_{i}$.\n\nIn order to maintain it, Willem needs to perform $m$ operations.\n\nThere are four types of operations:\n\n- $1 l r x$: For each $i$ such that $l ≤ i ≤ r$, assign $a_{i} + x$ to $a_{i}$.\n- $2 l r x$: For each $i$ such that $l ≤ i ≤ r$, assign $x$ to $a_{i}$.\n- $3 l r x$: Print the $x$-th smallest number in the index range $[l, r]$, i.e. the element at the $x$-th position if all the elements $a_{i}$ such that $l ≤ i ≤ r$ are taken and sorted into an array of non-decreasing integers. It's guaranteed that $1 ≤ x ≤ r - l + 1$.\n- $4 l r x y$: Print the sum of the $x$-th power of $a_{i}$ such that $l ≤ i ≤ r$, modulo $y$, i.e. $(\\sum_{i=l}^{r}a_{i}^{~x})\\operatorname{mod}~y$.",
    "tutorial": "This is an interesting algorithm which can easily deal with many data structure problems------if the data is random... I initially named it as \"Old Driver Tree\" ( Which is my codeforces ID ). (But now I call it Chtholly Tree~). We can find that there is an operation that makes a range of number the same. We can use an interval tree (std::set is enough) to maintain every interval that consists of the same number. And for operation $2$, we destory all the intervals in range $[l, r]$ , and put in a new interval $[l, r]$ into the interval tree. For operations $1$, $3$, $4$, we can brute-forcely walk on the tree, find every interval in range $[l, r]$, and do the required operation on it. Proof of time complexity: We suppose that we have a randomly selected range $[l, r]$ now, and we randomly choose which operation it is, suppose that there are $x$ intervals in this range. 1/4 possibility we use $O(x)$ time to erase $O(x)$ nodes. 2/4 possibility we use $O(x)$ time to erase nothing. 1/4 possibility we use $O(x)$ time to erase nothing and add 2 new nodes into the tree. So we are expected to use $O(x)$ time to erase $O(x)$ nodes. By using interval tree to maintain, the time complexity of this problem is $O(m\\log n)$. If operation $3$ and $4$ are changed into output the sum of $a_{i}$ for every $i$ range $[l, r]$, it seems that the time complexity may change into $O(m\\log\\log n)$ , but I do not know how to prove it... Solution using map",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <map>\n \nusing namespace std;\n \ntypedef long long int64;\n \nstruct IO_Tp\n{\n\tbool is_digit(const char ch)\n\t{\n\t\treturn '0' <= ch && ch <= '9';\n\t}\n\t\n\tIO_Tp& operator>>(int& res)\n\t{\n\t\tres = 0;\n\t\tstatic char ch;\n\t\twhile (ch = getchar(), !is_digit(ch))\n\t\t\t;\n\t\tdo\n\t\t\t(res *= 10) += ch & 15;\n\t\twhile (ch = getchar(), is_digit(ch));\n\t\treturn *this;\n\t}\n\t\n\tIO_Tp& operator>>(int64& res)\n\t{\n\t\tres = 0;\n\t\tstatic char ch;\n\t\twhile (ch = getchar(), !is_digit(ch))\n\t\t\t;\n\t\tdo\n\t\t\t(res *= 10) += ch & 15;\n\t\twhile (ch = getchar(), is_digit(ch));\n\t\treturn *this;\n\t}\n} IO;\n \nint64 Power(int64 Base, int64 Exp, int64 Mod)\n{\n\tBase %= Mod;\n\tint64 res(1);\n\tdo\n\t{\n\t\tif (Exp & 1) \n\t\t\t(res *= Base) %= Mod;\n\t\t(Base *= Base) %= Mod;\n\t}\n\twhile (Exp >>= 1);\n\treturn res;\n}\n \nint64 seed;\nint rnd()\n{\n\tint res(seed);\n\tseed = (seed * 7 + 13) % 1000000007;\n\treturn res;\n}\n \nint N, M, V_Max;\nmap<int, int64> A;\n \nint main(int argc, char** argv)\n{\n\tIO >> N >> M >> seed >> V_Max;\n\t\n\tfor (int i(1); i <= N; ++i)\n\t\tA.insert(A.end(), make_pair(i, rnd() % V_Max + 1));\n\tA.insert(A.end(), make_pair(N + 1, 0));\n\twhile (M--)\n\t{\n\t\tint op((rnd() % 4) + 1);\n\t\tint l((rnd() % N) + 1);\n\t\tint r((rnd() % N) + 1);\n\t\tint x, y;\n\t\tif (l > r)\n\t\t\tswap(l, r);\n\t\tif (op == 3)\n\t\t\tx = (rnd() % (r - l + 1)) + 1;\n\t\telse\n\t\t\tx = (rnd() % V_Max) + 1;\n\t\tif (op == 4)\n\t\t\ty = (rnd() % V_Max) + 1;\n\t\t\n\t\tauto it_l(--A.upper_bound(l));\n\t\tif (it_l->first != l)\n\t\t\tA[l] = it_l->second, ++it_l;\n\t\tauto it_r(--A.upper_bound(r + 1));\n\t\tif (it_r->first != r + 1)\n\t\t\tA[r + 1] = it_r->second, ++it_r;\n\t\tswitch (op)\n\t\t{\n\t\t\tstatic vector<pair<int64, int>> v;\n\t\t\tstatic int64 res;\n\t\t\t\n\t\t\tcase 1:\n\t\t\t\twhile (it_l != it_r)\n\t\t\t\t\t(--it_r)->second += x;\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 2:\n\t\t\t\twhile (it_l != it_r)\n\t\t\t\t\tA.erase(it_l++);\n\t\t\t\tA[l] = x;\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 3:\n\t\t\t\tv.clear();\n\t\t\t\tfor (int ub; it_l != it_r; )\n\t\t\t\t\tub = (it_r--)->first, v.push_back(make_pair(it_r->second, ub - it_r->first));\n\t\t\t\tsort(v.begin(), v.end());\n\t\t\t\tfor (int i(0), cnt(0); ; ++i)\n\t\t\t\t\tif (x <= (cnt += v[i].second))\n\t\t\t\t\t{\n\t\t\t\t\t\tprintf(\"%I64d\\n\", v[i].first);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 4:\n\t\t\t\tres = 0;\n\t\t\t\tfor (int ub; it_l != it_r; )\n\t\t\t\t\tub = (it_r--)->first, (res += Power(it_r->second, x, y) * (ub - it_r->first)) %= y;\n\t\t\t\tprintf(\"%I64d\\n\", res);\n\t\t\t\tbreak;\n\t\t} \n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "896",
    "index": "D",
    "title": "Nephren Runs a Cinema",
    "statement": "Lakhesh loves to make movies, so Nephren helps her run a cinema. We may call it No. 68 Cinema.\n\nHowever, one day, the No. 68 Cinema runs out of changes (they don't have 50-yuan notes currently), but Nephren still wants to start their business. (Assume that yuan is a kind of currency in Regulu Ere.)\n\nThere are three types of customers: some of them bring exactly a 50-yuan note; some of them bring a 100-yuan note and Nephren needs to give a 50-yuan note back to him/her; some of them bring VIP cards so that they don't need to pay for the ticket.\n\nNow $n$ customers are waiting outside in queue. Nephren wants to know how many possible queues are there that they are able to run smoothly (i.e. every customer can receive his/her change), and that the number of 50-yuan notes they have after selling tickets to all these customers is between $l$ and $r$, inclusive. Two queues are considered different if there exists a customer whose type is different in two queues. As the number can be large, please output the answer modulo $p$.",
    "tutorial": "First let's consider a simpler problem that there are no customers with VIP cards and there are no 50-$yuan$ notes left. For convinence, we suppose that $n$ is an even number. The situation that $n$ is an odd number will be similar. By defining points (number of customers currently, number of 50-$yuan$ note left) on a 2d-plane, the answer to our second question is the ways of drawing lines from (0,0) to (n,0), such that two adjacent points' y-axis have a difference of 1, and that all the points are above the x-axis. The total routes will be $C_{n}^{n / 2}$, but some of them are invalid. Consider another route starting from (0,-2). For each invalid way in the previous route, consider the first point (x,y) that y<0 (y=-1). By creating a symmetry route with y=-1 for the route before this point, this route will become exactly one route starting from (0,-2), and every route starting from (0,-2) will become an invalid route in a similar way. So the number of invalid routes is $C_{n}^{n / 2 - 1}$ (that is the number of routes from (0,-2) to (n,0)). Thus the answer will be $C_{n}^{n / 2} - C_{n}^{n / 2 - 1}$. Similarly if there are [l,r] 50-$yuan$ notes left, the answer will be $C_{n}^{n / 2 - r / 2} - C_{n}^{n / 2 - l / 2 - 1}$. Now let's enumerate how many customers are there with VIP cards. If there are $i$ of them, the answer will time a factor $C_{n}^{i}$. One last question is about the modulo number. First separate it into forms like $(p_{1}^{a1}) * (p_{2}^{a2})$... where $p_{1}...$ are primes. We can calculate how many factor $p_{i}$ are there in $(j!)$, and the modulo value of the remaining ones. Each time we take out a facter $p_{i}$ in $(j!)$, and it becomes some product of numbers that are not divisble by $p_{i}$ as well as a remaining part $(j / p_{i})!$. For example, we want to calculate the number of factor 3 in (16!), and the product of numbers that are not divisble by 3 in (16!) mod (3^2). Then we have: 16! = (1 * 2 * 4 * 5 * 7 * 8 * 10 * 11 * 13 * 14 * 16) * (1 * 2 * 3 * 4 * 5) * (3^5) The first part are not divisble by 3, so we can calculate their value (mod 3^2) in advance, the second part is a smaller problem (5!), so we can solve it recursively. For the number of factor 3, just add 5 in this case and solve it recursively. After calculating how many factor $p_{i}$ in $(j!)$ and the modulo value of the remaining ones, we can calculate the combnation numbers correctly. Finally use Chinese Remainder Algorithm to combine them.",
    "tags": [
      "chinese remainder theorem",
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "896",
    "index": "E",
    "title": "Welcome home, Chtholly",
    "statement": "\\begin{quote}\n— I... I survived.\n\n— Welcome home, Chtholly.\n\n— I kept my promise...\n\n— I made it... I really made it!\n\\end{quote}\n\nAfter several days of fighting, Chtholly Nota Seniorious miraculously returned from the fierce battle.\n\nAs promised, Willem is now baking butter cake for her.\n\nHowever, although Willem is skilled in making dessert, he rarely bakes butter cake.\n\nThis time, Willem made a big mistake — he accidentally broke the oven!\n\nFortunately, Chtholly decided to help him.\n\nWillem puts $n$ cakes on a roll, cakes are numbered from $1$ to $n$, the $i$-th cake needs $a_{i}$ seconds of baking.\n\nWillem needs Chtholly to do $m$ operations to bake the cakes.\n\nOperation 1: $1 l r x$\n\nWillem asks Chtholly to check each cake in the range $[l, r]$, if the cake needs to be baked for more than $x$ seconds, he would bake it for $x$ seconds and put it back in its place. More precisely, for every $i$ in range $[l, r]$, if $a_{i}$ is strictly more than $x$, $a_{i}$ becomes equal $a_{i} - x$.\n\nOperation 2: $2 l r x$\n\nWillem asks Chtholly to count the number of cakes in the range $[l, r]$ that needs to be cooked for exactly $x$ seconds. More formally you should find number of such $i$ in range $[l, r]$, that $a_{i} = x$.",
    "tutorial": "My solution to this problem: Split the array into $O({\\sqrt{n}})$ blocks, each containing $O({\\sqrt{n}})$ numbers. In each block, for example block $x$, use $f[x][v]$ to represent the number of $v$ in block $x$. For each number $i$, $belong[i]$ is the the block that $i$ is in. We need to maintain each number in the block. This can be maintained by using DSU or linked list. By maintaining this, we can get the value of every number in a block in $O({\\sqrt{n}})$ time. Notice that this two operations are the same: $1.$For every number that is bigger than $x$, decrease it by $x$ $2.$Decrease every number by $x$, and for every number that is less than $1$, increase it by $x$ For operation $1$: We get the value of each number in block $belong[l]$ and $belong[r]$ using the DSU or linked list, then for every number that should change, we change them. Then we build block $belong[l]$ and $belong[r]$ up again. For blocks numbered from $belong[l] + 1$ to $belong[r] - 1$: If $x  \\times  2$ $ \\le $ max value in block $p$ We merge all the numbers in range $[1, x]$ to $[x + 1, x  \\times  2]$, and add $x$ to $tag[p]$ , $tag[p]$ means that all the numbers in block $p$ has decreased by $tag[p]$. If $x  \\times  2$ ${}_{\\sim}\\geq$ max value in block $p$ We merge all the numbers in range $[x + 1, maxvalue]$ to $[1, maxvalue - x]$. For operation $2$: We get the value of each number in block $belong[l]$ and $belong[r]$ using the DSU or linked list. We only need to traverse all the numbers in blocks $belong[l]$ and $belong[r]$, and traverse all the blocks between $belong[l]$ and $belong[r]$. For block $i$ in range $[l, r]$, $f[i][x + tag[i]]$ is the number of $x$ in block $i$, so we just need to add this into the answer Proof of time complexity: There are $O({\\sqrt{n}})$ blocks. The difference between the max number and the min number in each block is initially $n$. So the sum of this in every block is $O(n{\\sqrt{n}})$. For each operation $1$, we use $O(x)$ time or $O(max - x)$ time to make the difference of max and min element $O(x)$ or $O(max - x)$ smaller. For each operation $2$, we traverse $O({\\sqrt{n}})$ numbers and $O({\\sqrt{n}})$ blocks. So the total time complexity if $O(n{\\sqrt{n}}+m{\\sqrt{n}})$ There seems to be another algorithm with the same time complexity, and has a smaller constant, but I couldn't prove its complexity so I used this algorithm instead.",
    "code": "#include <iostream>\n#include <stdio.h>\n#include <math.h>\n#define block 254\n#define MAXD 400\n#define MAXN 100010 + MAXD\n#define Merge( p , a , b ) if( V[p][a].root ) merge( p , a , b )\n#define l( x ) ( x * 254 - 253 )\n#define r( x ) ( x * 254 )\n \nusing namespace std;\n \nint n , m , belong[ MAXN ] , a[ MAXN ];\nint pre[ MAXN ] , pos[ MAXN ] , L[ MAXN ] , R[ MAXN ];\n \nstruct point\n{\n\tunsigned char num , root;\n} V[ MAXD ][ MAXN ];\n \ninline void merge( int p , int a , int b )\n{\n\tregister point x = V[p][a] , y = V[p][b];\n\ty.root ? pre[ x.root + l( p ) - 1 ] = y.root + l( p ) - 1 : ( y.root = x.root , pos[ y.root + l( p ) - 1 ] = b );\n\ty.num += x.num , * ( short * ) & x = 0;\n\tV[p][a] = x , V[p][b] = y;\n}\n \ninline int find( int x )\n{\n\twhile( x != pre[x] )\n\t\tx = pre[x] = pre[ pre[x] ];\n\treturn x;\n}\n \ninline void pushdown( int v )\n{\n\tfor( register int i = l( v ) ; i <= r( v ) ; i++ )\n\t\ta[i] = pos[ find( i ) ] , V[v][ a[i] ].root = 0 , V[v][ a[i] ].num = 0 , a[i] -= L[v];\n\tfor( register int i = l( v ) ; i <= r( v ) ; i++ )\n\t\tpre[i] = 0; \n\tL[v] = 0;\n}\n \ninline void update( int v )\n{\n\tR[v] = 0;\n\tfor( register int i = l( v ) ; i <= r( v ) ; i++ )\n\t{\n\t\tif( a[i] > R[v] ) R[v] = a[i];\n\t\tif( !V[v][ a[i] ].root ) pre[i] = i , V[v][ a[i] ].root = i - l( v ) + 1 , pos[i] = a[i];\n\t\telse pre[i] = V[v][ a[i] ].root + l( v ) - 1;\n\t\tV[v][ a[i] ].num++;\n\t}\n}\n \ninline void modify( int x , int v )\n{\n\tint & p = L[x] , & q = R[x];\n\tif( v * 2 <= q - p )\n\t{\n\t\tfor( register int i = p + 1 ; i <= p + v ; i++ )\n\t\t\tMerge( x , i , i + v );\n\t\tp += v;\n\t}\n\telse\n\t{\n\t\tfor( register int i = q ; i > p + v ; i-- )\n\t\t\tMerge( x , i , i - v );\n\t\tq = min( q , p + v );\n\t}\n}\n \ninline void modify( int x , int y , int v )\n{\n\tint p = belong[x] , q = belong[y];\n\tif( p == q )\n\t{\n\t\tpushdown( p );\n\t\tfor( register int i = x ; i <= y ; i++ )\n\t\t\tif( a[i] > v )\n\t\t\t\ta[i] -= v;\n\t\tupdate( p );\n\t}\n\telse\n\t{\n\t\tpushdown( p ) , pushdown( q );\n\t\tfor( register int i = x ; i <= r( p ) ; i++ )\n\t\t\tif( a[i] > v )\n\t\t\t\ta[i] -= v;\n\t\tfor( register int i = l( q ) ; i <= y ; i++ )\n\t\t\tif( a[i] > v )\n\t\t\t\ta[i] -= v;\n\t\tfor( int i = p + 1 ; i <= q - 1 ; i++ )\n\t\t\tmodify( i , v );\n\t\tupdate( p ) , update( q );\n\t}\n}\n \ninline int find( int x , int y , int v )\n{\n\tint ans = 0 , p = belong[x] , q = belong[y];\n\tif( p == q )\n\t\tfor( register int i = x ; i <= y ; i++ )\n\t\t\tif( pos[ find( i ) ] - L[ p ] == v )\n\t\t\t\tans++;\n\t\t\telse;\n\telse\n\t{\n\t\tfor( register int i = x ; i <= r( p ) ; i++ )\n\t\t\tif( pos[ find( i ) ] - L[ p ] == v )\n\t\t\t\tans++;\n\t\t\telse;\n\t\tfor( register int i = l( q ) ; i <= y ; i++ )\n\t\t\tif( pos[ find( i ) ] - L[ q ] == v )\n\t\t\t\tans++;\n\t\tfor( register int i = p + 1 ; i <= q - 1 ; i++ )\n\t\t\tif( v + L[i] <= 100000 )\n\t\t\t\tans += V[i][ v + L[i] ].num;\n\t}\n\treturn ans;\n}\n \nstruct io\n{\n\tchar ibuf[1 << 22] , * s , obuf[1 << 20] , * t;\n\tint a[24];\n\tio() : t( obuf )\n\t{\n\t\tibuf[ fread( s = ibuf , 1 , 1 << 22 , stdin ) ] = 0;\n\t}\n\t~io()\n\t{\n\t\tfwrite( obuf , 1 , t - obuf , stdout );\n\t}\n\tinline int read()\n\t{\n\t\tregister int u = 0;\n\t\twhile( * s < 48 )\n\t\t\ts++;\n\t\twhile( * s > 32 )\n\t\t\tu = u * 10 + * s++ - 48;\n\t\treturn u;\n\t}\n\ttemplate < class T >\n\tinline void print( T u , int v )\n\t{\n\t\tprint( u );\n\t\t* t++ = v;\n\t}\n\ttemplate< class T >\n\tinline void print( register T u )\n\t{\n\t\tstatic int * q = a;\n\t\tif( !u ) * t++ = 48;\n\t\telse\n\t\t{\n\t\t\tif( u < 0 )\n\t\t\t\t* t++ = 45 , u *= -1;\n\t\t\twhile( u ) * q++ = u % 10 + 48 , u /= 10;\n\t\t\twhile( q != a )\n\t\t\t\t* t++ = * --q;\n\t\t}\n\t}\n} ip;\n \n#define read ip.read\n#define print ip.print\n \nint main()\n{\n\tn = read() , m = read();\n\tfor( register int i = 1 ; i <= n ; i++ ) a[i] = read() , belong[i] = ( i - 1 ) / block + 1;\n\tfor( int i = 1 ; i <= belong[n] ; i++ )\n\t\tupdate( i );\n\twhile( m-- )\n\t{\n\t\tint opt = read() , l = read() , r = read() , v = read();\n\t\tif( opt == 1 ) modify( l , r , v );\n\t\telse print( find( l , r , v ) , 10 );\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 3100
  },
  {
    "contest_id": "897",
    "index": "A",
    "title": "Scarborough Fair",
    "statement": "\\begin{quote}\nAre you going to Scarborough Fair?Parsley, sage, rosemary and thyme.\n\nRemember me to one who lives there.\n\nHe once was the true love of mine.\n\\end{quote}\n\nWillem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.\n\nWillem asks his friend, Grick for directions, Grick helped them, and gave them a task.\n\nAlthough the girl wants to help, Willem insists on doing it by himself.\n\nGrick gave Willem a string of length $n$.\n\nWillem needs to do $m$ operations, each operation has four parameters $l, r, c_{1}, c_{2}$, which means that all symbols $c_{1}$ in range $[l, r]$ (from $l$-th to $r$-th, including $l$ and $r$) are changed into $c_{2}$. String is 1-indexed.\n\nGrick wants to know the final string after all the $m$ operations.",
    "tutorial": "For every $i$ in range $[l, r]$, if $c_{i}$ is $c_{1}$ then change it into $c_{2}$... Because $n, m$ are all very small, $O(nm)$ can easily pass it. PS. You can use binary search tree to solve it in $O(m\\log n)$ time.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "897",
    "index": "B",
    "title": "Chtholly's request",
    "statement": "\\begin{quote}\n— Thanks a lot for today.— I experienced so many great things.\n\n— You gave me memories like dreams... But I have to leave now...\n\n— One last request, can you...\n\n— Help me solve a Codeforces problem?\n\n— ......\n\n— What?\n\\end{quote}\n\nChtholly has been thinking about a problem for days:\n\nIf a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.\n\nGiven integers $k$ and $p$, calculate the sum of the $k$ smallest zcy numbers and output this sum modulo $p$.\n\nUnfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!",
    "tutorial": "The $k$-th smallest zcy number is $conn(str(k), rev(str(k)))$, where $str$ denotes the decimal representation of a positive integer as a string, $conn$ denotes the concatenation two strings, and $rev$ denotes the reverse of a string. Then go over the smallest $k$ such numbers and sum them up to obtain the answer.",
    "tags": [
      "brute force"
    ],
    "rating": 1300
  },
  {
    "contest_id": "898",
    "index": "A",
    "title": "Rounding",
    "statement": "Vasya has a non-negative integer $n$. He wants to round it to nearest integer, which ends up with $0$. If $n$ already ends up with $0$, Vasya considers it already rounded.\n\nFor example, if $n = 4722$ answer is $4720$. If $n = 5$ Vasya can round it to $0$ or to $10$. Both ways are correct.\n\nFor given $n$ find out to which integer will Vasya round it.",
    "tutorial": "At first let's round down the given number $n$ to the nearest integer which ends with $0$ and store this value in a variable $a$: $a = (n / 10) * 10$. So, the round up $n$ (call it $b$) is $b = a + 10$. If $n - a > b - n$ then the answer is $b$. In the other case, the answer is $a$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "898",
    "index": "B",
    "title": "Proper Nutrition",
    "statement": "Vasya has $n$ burles. One bottle of Ber-Cola costs $a$ burles and one Bars bar costs $b$ burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.\n\nFind out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend \\textbf{exactly} $n$ burles.\n\nIn other words, you should find two non-negative integers $x$ and $y$ such that Vasya can buy $x$ bottles of Ber-Cola and $y$ Bars bars and $x·a + y·b = n$ or tell that it's impossible.",
    "tutorial": "To solve this problem we need to brute how many bottles of Ber-Cola Vasya will buy. Let this number equals to $x$. Then, if $n - a \\cdot x$ is non-negative and divided by $b$ we found the answer - Vasya should by $x$ bottles of Ber-Cola and $(n - a \\cdot x) / b$ Bars bars. In case that $(n - a \\cdot x)$ became negative there is no answer and we should print \"NO\".",
    "tags": [
      "brute force",
      "implementation",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "898",
    "index": "C",
    "title": "Phone Numbers",
    "statement": "Vasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.\n\nVasya decided to organize information about the phone numbers of friends. You will be given $n$ strings — all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.\n\nVasya also believes that if the phone number $a$ is a suffix of the phone number $b$ (that is, the number $b$ ends up with $a$), and both numbers are written by Vasya as the phone numbers of the same person, then $a$ is recorded without the city code and it should not be taken into account.\n\nThe task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers $x$ and $y$, and $x$ is a suffix of $y$ (that is, $y$ ends in $x$), then you shouldn't print number $x$. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.\n\nRead the examples to understand statement and format of the output better.",
    "tutorial": "Let's use map from string to vector of strings to simplify implementation. The map keys is friend names, and the values - list of phone numbers. At first let's put all input data in map, but if vector for a current friend already contains a current number we should not put this number in the vector (for example, we can check it with help of set). After that we need only to remove for each friend the numbers which are the suffixes of other number of that friend. The time limit allows to make it in time equals to square of phone number count for a current friend. Now we need to iterate through map key set (it will be names of all Vasya's friends) and print all remaining phone numbers for each friend.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "898",
    "index": "D",
    "title": "Alarm Clock",
    "statement": "Every evening Vitalya sets $n$ alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer $a_{i}$ — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute.\n\nVitalya will definitely wake up if during some $m$ consecutive minutes at least $k$ alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time.\n\nVitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on.",
    "tutorial": "At first we need to sort all alarms in increasing order of their times. Also we will use set, where we will store alarm times. We will iterate through the alarms beginning from the first. Let current alarm time equals to $x$. Until set does not empty and the first set element less than $x - m + 1$ we should remove the first set element. After that only alarm with times not before $m - 1$ minutes relatively $x$ will be in set. If after that the set size less than $k - 1$ we should insert $x$ in the set (we will not turn off this alarm). In the other case, we should turn off this alarm, so we increase the answer on one and do not insert $x$ in the set.",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "898",
    "index": "E",
    "title": "Squares and not squares",
    "statement": "Ann and Borya have $n$ piles with candies and $n$ is even number. There are $a_{i}$ candies in pile with number $i$.\n\nAnn likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile).\n\nFind out minimal number of moves that is required to make exactly $n / 2$ piles contain number of candies that is a square of some integer and exactly $n / 2$ piles contain number of candies that is not a square of any integer.",
    "tutorial": "At first we need to implement a function to check integer $a$ if it is a square of an integer. Let $x$ is a round down square root of $x$. If $x \\cdot x = = a$ then $a$ is a square of an integer. Let's calculate two values: $cnt_{1}$ - how many given numbers are integer squares and $cnt_{2}$ - how many given numbers are not integer squares. If $cnt_{1} = = cnt_{2}$, then we should not to change anything and the answer is $0$. If $cnt_{1} > cnt_{2}$, then we should to make $(cnt_{1} - cnt_{2}) / 2$ numbers-squares not to be squares. To make it we need to take $(cnt_{1} - cnt_{2}) / 2$ numbers-squares, which do not equal to $0$ and increase them by $1$. If such numbers do not enough we should take needed number of $0$ and increase them by $2$. If $cnt_{1} < cnt_{2}$, then we should to make $(cnt_{2} - cnt_{1}) / 2$ numbers, which do not squares, to be squares. Let's calculate for each such number the number of operations to make this number square-number and put this value in separate vector. After than we should sort vector in increasing order and print the sum of first $(cnt_{2} - cnt_{1}) / 2$ vector elements.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "898",
    "index": "F",
    "title": "Restoring the Expression",
    "statement": "A correct expression of the form a+b=c was written; $a$, $b$ and $c$ are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that:\n\n- character'+' is placed on the left of character '=',\n- characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle part — b and the right part — c),\n- all the three parts a, b and c do not contain leading zeros,\n- it is true that a+b=c.\n\nIt is guaranteed that in given tests answer always exists.",
    "tutorial": "At first we should calculate \"hash\" by big prime module from the given string, and the base must be equal to $10$ because we work with numbers. We can use prime module about $10^{15}$, if we will use multiple of long longs by module with help of long doubles. After that we will brute the length of the result of summation, let this value is $len_{3}$. Because when two numbers are added the result may have the same length as the larger term, or may have a length one greater than the length of the larger term it is enough to check the following cases ($len_{1}$ - the length of the first term, $len_{2}$ - the length of the second term): $len_{1} = len_{3}$, $len_{2} = n - len_{1} - len_{3}$ $len_{1} = len_{3} - 1$, $len_{2} = n - len_{1} - len_{3}$ $len_{2} = len_{3}$, $len_{1} = n - len_{2} - len_{3}$ $len_{2} = len_{3} - 1$, $len_{1} = n - len_{2} - len_{3}$ For each case the check algorithm is the same. At first we should check that all parts have positive length, that the length $len_{3}$ satisfies the conditions described at the beginning of the tutorial and that it part has no trailing spaces. Now we should divide each part on $10$ in the needed power, to bring the value of the calculated \"hash\" to the desired degree. To make it we can multiply each part on element, which is reverse to $10$ by the used module, in the desired power. To find $r$ which is reverse to $10$ be the prime module $MOD$ we should raising $10$ to the power $(MOD - 2)$ with help of binary power raising. If after the described operations the sum of first to parts by used module equals to the value of third part, we found the answer and we should print corresponding parts. You could also perform calculations on several smaller modules.",
    "tags": [
      "brute force",
      "hashing",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "899",
    "index": "A",
    "title": "Splitting in Teams",
    "statement": "There were $n$ groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.\n\nThe coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.",
    "tutorial": "it is profitably to the coach to unite groups from two students with groups from one student and after that unite in teams three groups from one student. Let's calculate two values: $cnt_{1}$ - the number of groups from one student, and $cnt_{2}$ - the number of groups from two students. Then if $cnt_{1} > cnt_{2}$ - the answer is $cnt_{2} + (cnt_{1} - cnt_{2}) / 3$. In the other case, the answer is $cnt_{1}$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "899",
    "index": "B",
    "title": "Months and Years",
    "statement": "Everybody in Russia uses Gregorian calendar. In this calendar there are $31$ days in January, $28$ or $29$ days in February (depending on whether the year is leap or not), $31$ days in March, $30$ days in April, $31$ days in May, $30$ in June, $31$ in July, $31$ in August, $30$ in September, $31$ in October, $30$ in November, $31$ in December.\n\nA year is leap in one of two cases: either its number is divisible by $4$, but not divisible by $100$, or is divisible by $400$. For example, the following years are leap: $2000$, $2004$, but years $1900$ and $2018$ are not leap.\n\nIn this problem you are given $n$ ($1 ≤ n ≤ 24$) integers $a_{1}, a_{2}, ..., a_{n}$, and you have to check if these integers could be durations in days of $n$ consecutive months, according to Gregorian calendar. Note that these months could belong to several consecutive years. In other words, check if there is a month in some year, such that its duration is $a_{1}$ days, duration of the next month is $a_{2}$ days, and so on.",
    "tutorial": "Note, that $n  \\le  24$, so we should consider the following cycle: not leap-year - leap-year - not leap-year - not leap-year. This cycle repeats every $4$ years, except in some cases. We should generate an array describing the duration of the months in the described cycle. After that we should check that the given sequence can be found in the generated array. For example, we can brute the beginning of the sequence in the array and check the correspondence of the elements of the given sequence to the corresponding elements of the generated array.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "899",
    "index": "C",
    "title": "Dividing the numbers",
    "statement": "Petya has $n$ integers: $1, 2, 3, ..., n$. He wants to split these integers in \\textbf{two non-empty} groups in such a way that the absolute difference of sums of integers in each group is as small as possible.\n\nHelp Petya to split the integers. Each of $n$ integers should be exactly in one group.",
    "tutorial": "To solve this problem we should consider $4$ cases. If $n$ divided by $4$ without remnant than the sum of all numbers from $1$ to $n$ is even. Then we can divide numbers on two groups in such a way that absolute difference between sum of numbers in each part is $0$. To make it we should take in one group all numbers which give a remainder $0$ or $1$ when dividing by $4$. If $n$ gives a remainder $2$ when dividing by $4$ than the sum of all numbers from $1$ to $n$ is odd. Then we can divide numbers on two groups in such a way that absolute difference between sum of numbers in each part is $1$ (because the sum of all numbers is odd, then we can not improve the answer). To make this, we need to take the same numbers in the same group as in the previous case. If $n$ gives a remainder $3$ when dividing by $4$ than the sum of all numbers from $1$ to $n$ is even. Then we can divide numbers on two groups in such a way that absolute difference between sum of numbers in each part is $0$. To make this, we need to take in one group all numbers from $1$ to $n / 4$, inclusively, and all last $(n / 4 + 1)$ numbers (i.e. numbers from $(n - n / 4)$ to $n$, inclusively). If $n$ gives a remainder $1$ when dividing by $4$ than the sum of all numbers from $1$ to $n$ is odd. Then we can divide numbers on two groups in such a way that absolute difference between sum of numbers in each part is $1$ (because the sum of all numbers is odd, then we can not improve the answer). To make this, we need to take in one group all numbers from $1$ to $(n / 4 + 1)$, inclusively, and all last $n / 4$ numbers (i.e. numbers from $(n - n / 4 + 1)$ to $n$, inclusively).",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "899",
    "index": "D",
    "title": "Shovel Sale",
    "statement": "There are $n$ shovels in Polycarp's shop. The $i$-th shovel costs $i$ burles, that is, the first shovel costs $1$ burle, the second shovel costs $2$ burles, the third shovel costs $3$ burles, and so on. Polycarps wants to sell shovels in pairs.\n\nVisitors are more likely to buy a pair of shovels if their total cost ends with several $9$s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs $12345$ and $37454$, their total cost is $49799$, it ends with two nines.\n\nYou are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other.",
    "tutorial": "At first let's check that the sum $sum = n + (n - 1)$ consisting of only digits nine. If it is true then the answer is $1$. In the other case, we should calculate the number of digits in the number $sum$. Let this value if $len$. We should construct the number $cur$ which consisting of $(len - 1)$ digits nine. After that we should try to write each digit from $0$ to $8$ to the beginning of $cur$. Let we wrote next digit $c$ and $cur$ became equal to $p$ (i.e. the first digit is $c$ and other digits are nines). So we need to add to the answer the number of ways to take two different digits from $1$ to $n$ in such a way that their sum equals to $p$. If $p  \\le  (n + 1)$, we should add to the answer $p / 2$. If $p > n + (n - 1)$ we should to add to the answer nothing. Else we should add to the answer the value $(n + (n - 1) - sum) / 2$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "899",
    "index": "E",
    "title": "Segments Removal",
    "statement": "Vasya has an array of integers of length $n$.\n\nVasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is $[13, 13, 7, 7, 7, 2, 2, 2]$, then after one operation it becomes $[13, 13, 2, 2, 2]$.\n\nCompute the number of operations Vasya should make until the array becomes empty, i.e. Vasya removes all elements from it.",
    "tutorial": "We will use to set of pairs. In the first set (call it $len$) we will store all segments consisting of the same numbers in a format - the length of the segment multiplied on $- 1$ and the position of the beginning of the segment. In the second set (call it $segments$) we will store all segments consisting of the same numbers in a format - the position of the beginning of the segment and the length of the segment. Initially we will put in the sets all segments from the given array consisting of the same numbers. After that we will repeat the following algorithm until in sets there are non-deleted segments: increase answer on $1$; take from $lens$ the longest and the leftmost segment (it will be in the beginning of the $lens$, because we store here all length multiplied on $- 1$) and remove it from $lens$. Let this segment beginning in the position $st$ and has length $len$; with help of $lower_{bound}$ we can find in $segments$ the left and the right segments relatively the segment from the previous article. After that we should remove from the segments the segment $(st, len)$; if both left and right relatively of the current longest segment there are non-deleted segments and they consisting of the same numbers, we should to unite them in one segment. To do this, we should remove the left and right segments from $lens$ and $segments$ and put the new merged segment in $lens$ and $segments$ in the described format.",
    "tags": [
      "data structures",
      "dsu",
      "flows",
      "implementation",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "899",
    "index": "F",
    "title": "Letters Removing",
    "statement": "Petya has a string of length $n$ consisting of small and large English letters and digits.\n\nHe performs $m$ operations. Each operation is described with two integers $l$ and $r$ and a character $c$: Petya removes from the string all characters $c$ on positions between $l$ and $r$, inclusive. It's obvious that the length of the string remains the same or decreases after each operation.\n\nFind how the string will look like after Petya performs all $m$ operations.",
    "tutorial": "For each character $c$ we should use set, where we will store positions of all non-deleted characters $c$. Let the next query equals to $l, r, c$. Then at first we should transform the given positions $l$ and $r$ to the positions of the initial string, taking into account already deleted characters. We can do it with help of segments tree or sqrt-decomposition. After we transformed $l$ and $r$ we should find the first position in set for character $c$ (with help of lower_bound) which is in range $[l, r]$ and remove positions from the corresponding set until they are in range $[l, r]$. Also we need to update information in data structure which we use to transform the given in the query $l$ and $r$ to the positions in the initial string. This algorithm will fit into the time limit, because we will delete each position no more than once. After we process all queries we should iterate through all sets, find all non-deleted positions and print characters, which are in that positions in the initial string (do not forget before that to sort all non-deleted positions in increasing order).",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "900",
    "index": "A",
    "title": "Find Extra One",
    "statement": "You have $n$ distinct points on a plane, none of them lie on $OY$ axis. Check that there is a point after removal of which the remaining points are located on one side of the $OY$ axis.",
    "tutorial": "Count number of points located on left and right side of the $OY$ axis. Answer will be \"Yes\" if number of points of one of the sets is smaller than two, \"No\" - otherwise. Time complexity $O(n)$.",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "900",
    "index": "B",
    "title": "Position in Fraction",
    "statement": "You have a fraction $\\overset{\\stackrel{\\alpha}{b}}$. You need to find the first occurrence of digit $c$ into decimal notation of the fraction after decimal point.",
    "tutorial": "In this task you should complete long division and stop, when one period passed. Period can't be more than $b$ by pigeonhole principle. So you need to complete $b$ iterations and if $c$ digit hasn't been met, print $- 1$. Time complexity $O(b)$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "900",
    "index": "C",
    "title": "Remove Extra One",
    "statement": "You are given a permutation $p$ of length $n$. Remove one element from permutation to make the number of records the maximum possible.\n\nWe remind that in a sequence of numbers $a_{1}, a_{2}, ..., a_{k}$ the element $a_{i}$ is a record if for every integer $j$ ($1 ≤ j < i$) the following holds: $a_{j} < a_{i}$.",
    "tutorial": "In this problem you have to find an element after which removal the number of records is maximum possible. Let $r_{i}$ be an array consisting of $0$ and $1$ depending on whether the $i$-th element was a record initially or not. We can compute it easily in $O(N)$. Let $x_{i}$ be the difference between the number of records after removal the $i$-th element and initial number of records. Let's think of how does removal of $a_{i}$ influence the array $r_{i}$. First of all, $r_{i}$ becomes $0$. $r_{j}$ ($j < i$) do not change in this case. Some of $r_{j}$ ($j > i$), change from $0$ to $1$. These elements are not records initially, but become records after the removal. These elements are elements which have only one greater element in front of them - $a_{i}$. Here follows an $O(n^{2})$ solution. Let's fix $a_{i}$ - the element we are going to remove. Let $x_{i}$ = $- r_{i}$ $+$ the number of such $j$ that $j > i$, $a_{i} > a_{j}$, and for all $k$ ($k  \\neq  i, k < j$) $a_{k} < a_{j}$. We can compute this just looping through all j and keeping the maximum over all elements but the $i$-th. Now note that it's not required to fix $a_{i}$. $r_{j}$ can become $1$ from $0$ only when a certain element from the left is removed. Let's loop through all $a_{j}$ and determine if there is an element to the left such that it is greater than $a_{j}$, but all other elements are less than $a_{j}$. We can check this using ordered set. If there is such a $a_{i}$, then increase $x_{i}$ by $1$. After the loop the array $x_{i}$ is fully computed, so we can just find the element which brings the maximum number of records, and minimum among such.",
    "tags": [
      "brute force",
      "data structures",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "900",
    "index": "D",
    "title": "Unusual Sequences",
    "statement": "Count the number of distinct sequences $a_{1}, a_{2}, ..., a_{n}$ ($1 ≤ a_{i}$) consisting of positive integers such that $gcd(a_{1}, a_{2}, ..., a_{n}) = x$ and $\\textstyle\\sum_{i=1}^{n}a_{i}=y$. As this number could be large, print the answer modulo $10^{9} + 7$.\n\n$gcd$ here means the greatest common divisor.",
    "tutorial": "It's obvious that if $y$ is not divisible by $x$, then the answer is $0$. Let $f(t)$ be the number of sequences such that their sum is $t$, and $gcd$ is $1$. Then the answer for the problem is $f{\\bigl(}{\\frac{y}{x}}{\\bigr)}$. How to compute $f(t)$?. Let's denote the number of sequences such that their sum is $t$ as $g(t)$. Then $g(t)$ is $2^{(t - 1)}$: represent all integers in the sequence in unary system with zeros, and split them with $t - 1$ ones. Note that $g(t)=\\sum_{i=1}^{|t_{i}|}f({\\frac{t}{t}})$, where ${t_{i}}$ are divisors of $t$. Then $f(t)=g(t)-\\sum_{i=2}^{s_{z}}f({\\frac{t}{t_{i}}})=2^{(t-1)}-\\sum_{i=2}^{|t_{i}|}f({\\frac{t}{t_{i}}})$. What's the complexity?. We know that the number of divisors of $t$ is not greater than $O(\\lambda^{\\prime}t)$. We can also note than every divisor of divisor of $t$ is a divisor of $t$. Thus we need for compute only $f(t_{i})$ for every $t_{i}|t$. Thus computing $f(t_{i})$ takes $O(\\lambda^{\\sqrt{t}})=O(\\lambda^{\\sqrt{t}})$ steps when all $f(t_{j})$, $t_{j} < t_{i}$ are already computed. The total complexity is $O(\\lambda^{\\widehat{2}})$, but on practice it works much faster than one can expect. Also, we can use Möbius function to solve this problem. This solution has a better complexity, but we will leave this solution as an exercise for readers.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "900",
    "index": "E",
    "title": "Maximum Questions",
    "statement": "Vasya wrote down two strings $s$ of length $n$ and $t$ of length $m$ consisting of small English letters 'a' and 'b'. What is more, he knows that string $t$ has a form \"abab...\", namely there are letters 'a' on odd positions and letters 'b' on even positions.\n\nSuddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string $s$ were replaced by character '?'.\n\nLet's call a sequence of positions $i, i + 1, ..., i + m - 1$ as occurrence of string $t$ in $s$, if $1 ≤ i ≤ n - m + 1$ and $t_{1} = s_{i}, t_{2} = s_{i + 1}, ..., t_{m} = s_{i + m - 1}$.\n\nThe boy defines the beauty of the string $s$ as maximum number of disjoint occurrences of string $t$ in $s$. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string $s$ is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.",
    "tutorial": "Let's find all positions $i$ in string $s$ such that occurrence $t$ can start at position $i$ after making some replacements. How to find them? As $t$ has a form \"abab...\" letters $s_{i}, s_{i + 2}, s_{i + 4}, ..., s_{(i + m - 1|i + m - 2)}$ should be equal to '?' or 'a' and $s_{i + 1}, s_{i + 3}..., s_{(i + m - 1|i + m - 2)}$ should be equal to '?' or 'b'. Let's calculate $f[i][c]$ - how many consecutive letters $s_{i}, s_{i + 2}, ..., s_{(f[i][c] - 1) \\cdot 2}$ are equal to '?' or $c$. Than it is left to verify for position $i$ or $f[i][a]  \\ge  cell(n / 2)$ and $f[i][b]  \\ge  floor(n / 2)$. We found all positions where occurrence of $t$ can start. Remaining task can be solved using dynamic programming. Let $dp[i][j]$ - the minimum number of replacements should be done that the number of occurrences in prefix $i$ is exactly maximum possible minus $j$. How to calculate this dp? If from position $i + 1$ can be started occurrence than $dp[i + m][MaxOccur_{i + m} - (MaxOccur_{i} - j)] = best(dp[i + m][MaxOccur_{i + m} - (MaxOccur_{i} - j)], dp[i][j] + CountQuestions_{i + 1, }_{i + m})$. Where $CountQuestions_{i, }_{j}$ means the number of letter '?' in substring from position $i$ to $j$ and $MaxOccur_{i}$ means the maximum number of occurrences in prefix from position $1$ to $i$, that can be calculated greedily. Actually considering $j > 1$ is redundant. Really, if we consider such set of occurrences that exists prefix for which the number of occurrences at least two less than maximum possible than we always can find the larger set of occurrences taking the maximum possible in this prefix and maybe deleting one that intersects with the prefix. The answer is $dp[n][0]$. Time complexity $O(n)$.",
    "tags": [
      "data structures",
      "dp",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "901",
    "index": "A",
    "title": "Hashing Trees",
    "statement": "Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence $a_{0}, a_{1}, ..., a_{h}$, where $h$ is the height of the tree, and $a_{i}$ equals to the number of vertices that are at distance of $i$ edges from root.\n\nUnfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence $a_{i}$, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.\n\nTwo rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.\n\nThe height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.",
    "tutorial": "There are many ways to solve the problem. First of all you should build any single tree. To do this, you first build the longest path from the root and then attach remained vertices on proper heights. Thus each vertex is either on the longest path or has parent on this path. To build the second tree you should use different vertices from previous levels during construction to make it different from first tree. This is always possible if there are two consecutive $a_{i} > 1$. Otherwise the tree is determined uniquely by $a_{i}$ sequence.",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "901",
    "index": "B",
    "title": "GCD of Polynomials",
    "statement": "Suppose you have two polynomials $A(x)=\\sum_{k=\\mathbf{a}}^{n}a_{k}x^{k}$ and $B(x)=\\sum_{k=\\mathbb{Q}}^{m}b_{k}x^{k}$. Then polynomial $A(x)$ can be uniquely represented in the following way:\n\n\\[\nA(x)=B(x)\\cdot D(x)+R(x),\\deg R(x)<\\deg B(x).\n\\]\n\nThis can be done using long division. Here, $\\deg P(x)$ denotes the degree of polynomial $P(x)$. $R(x)$ is called the remainder of division of polynomial $A(x)$ by polynomial $B(x)$, it is also denoted as $A\\bmod B$.\n\nSince there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials $(A,B)$. If the polynomial $B(x)$ is zero, the result is $A(x)$, otherwise the result is the value the algorithm returns for pair $(B,A{\\mathrm{~mod~}}B)$. On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question.\n\nYou are given an integer $n$. You have to build two polynomials with degrees not greater than $n$, such that their coefficients are integers not exceeding $1$ by their absolute value, the leading coefficients (ones with the greatest power of $x$) are equal to one, and the described Euclid's algorithm performs exactly $n$ steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair $(A,B)$ to pair $(B,A{\\mathrm{~mod~}}B)$.",
    "tutorial": "As for integers it is well known that worst case are consequent Fibonacci's numbers $F_{n + 1} = F_{n} + F_{n - 1}$. Solutions to this problem are based on the same idea. There were two main intended solutions. First of all you should note that sequence $p_{0} = 1, p_{1} = x,$ $p_{n + 1} = x \\cdot p_{n}  \\pm  p_{n - 1}$ Gives us the family of solutions, we just have to output $p_{n}$ and $p_{n - 1}$. It can be directly checked for given constraints that you can always choose $+$ or $-$ to satisfy coefficients constraints. The other solution is the same sequence but you use $+$ instead of $ \\pm $ and take coefficients modulo $2$. That's true because if remainders sequence has $k$ steps while you consider numbers by some modulo it will have at least $k$ steps in rational numbers. So the second intended solution is $p_{0} = 1, p_{1} = x,$ $p_{n+1}=x\\cdot p_{n}+p_{n-1}\\,\\,{\\mathrm{mod}}\\,\\,2$",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "901",
    "index": "C",
    "title": "Bipartite Segments",
    "statement": "You are given an undirected graph with $n$ vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from $1$ to $n$.\n\nYou have to answer $q$ queries. Each query is described by a segment of vertices $[l; r]$, and you have to count the number of its subsegments $[x; y]$ ($l ≤ x ≤ y ≤ r$), such that if we delete all vertices except the segment of vertices $[x; y]$ (including $x$ and $y$) and edges between them, the resulting graph is bipartite.",
    "tutorial": "If two cycles of odd length intersect, then they can be bypassed so as to obtain an edge-simple cycle of even length. It follows that the given graph is a vertex cactus, with cycles of odd length, then the vertex segment is good - if there is no loop, that the vertex with the minimum number from this cycle is present on this segment and the vertex with the maximum number from this cycle is present on this segment. Then we can select all the cycles, and now we work with the segments. Let us find for each vertex a maximal right boundary such that the interval $[i$..$mx_{i}]$ is a bipartite graph. Then $mx_{i}$ is equal to the minimal right boundary of the segment, which was opened later $i$. This can be considered a minimum on the suffix, initially setting for all cycles $mx$[minimum on the cycle] = maximum on the cycle To answer the query, we need to take the sum over $mx_{i} - i + 1$ for those who have $mx_{i}  \\ge  r$ and the sum over $r - i + 1$ for those who have $mx_{i}  \\ge  r$ then we note that $mx_{i}$ increases and we simply need to find the first moment when $mx_{i}$ becomes $ \\ge  r$ (we can do it with binary search) And take two prefix sums - sum of ($mx_{i} - i + 1$) and sum of $i$.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "901",
    "index": "D",
    "title": "Weighting a Tree",
    "statement": "You are given a connected undirected graph with $n$ vertices and $m$ edges. The vertices are enumerated from $1$ to $n$.\n\nYou are given $n$ integers $c_{1}, c_{2}, ..., c_{n}$, each of them is between $ - n$ and $n$, inclusive. It is also guaranteed that the parity of $c_{v}$ equals the parity of degree of vertex $v$. The degree of a vertex is the number of edges connected to it.\n\nYou are to write a weight between $ - 2·n^{2}$ and $2·n^{2}$ (inclusive) on each edge in such a way, that for each vertex $v$ the sum of weights on edges connected to this vertex is equal to $c_{v}$, or determine that this is impossible.",
    "tutorial": "Let's solve two cases. First case is when graph is the bipartite graph Then the sum of weights of the left part should be equal to the sum of weights of the right part (because each edge will bring an equal contribution to the sums of both part). We will leave any spanning tree of this graph, then for it the solution is unique (take the edges entering the leafs, their weights are uniquely determined, subtract weights from weights of the second ends of this edges, delete the leafs, recursively) this solution can be found with dfs, then in the end, the root will has weight 0 (because sum of weights of the left part equal to the sum of weights of the right part) Thus, the answer exists when the sum of the weights of the left part is equal to the sum of the weights of the right part. Second case when graph has the odd cycle. We find an odd cycle, root the tree for any of its vertices, solve the tree. Then, we add to the weights of the edges of the cycle adjacent to the root minus its weight divided by 2 (it is even, because it is the sum of the weights of all vertices (with different signs) equal to the sum of the degrees of vertices by modulo 2). , and for all others we alternate the signs with which we add this value, then for all vertices except the root the sum does not change, but for the root we get the required value.",
    "code": "\"#include <cmath>\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n#include <unordered_map>\\n#include <iomanip>\\n#include <bitset>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\nmt19937 rnd(228);\\n\\nconst int N = 1e5 + 7;\\n\\nvector <pair <int, int> > g[N];\\n\\nll c[N];\\nll cur[N];\\nll ans[N];\\nbool u[N];\\nint col[N];\\nint par[N];\\nint d[N];\\nint par_ind[N];\\n\\nint s = -1, t = -1;\\nint edge_ind = -1;\\n\\nvoid dfs(int v)\\n{\\n    u[v] = true;\\n    for (auto x : g[v])\\n    {\\n        int to = x.first, ind = x.second;\\n        if (!u[to])\\n        {\\n            d[to] = d[v] + 1;\\n            col[to] = (col[v] ^ 1);\\n            par[to] = v;\\n            par_ind[to] = ind;\\n            dfs(to);\\n            ans[ind] = cur[to];\\n            cur[v] -= cur[to];\\n        }\\n        else if (d[to] < d[v])\\n        {\\n            if (col[to] == col[v])\\n            {\\n                s = v, t = to;\\n                edge_ind = ind;\\n            }\\n        }\\n    }\\n}\\n\\nvoid solve_tree(int v)\\n{\\n    u[v] = true;\\n    for (auto x : g[v])\\n    {\\n        int to = x.first, ind = x.second;\\n        if (ind != edge_ind && !u[to])\\n        {\\n            solve_tree(to);\\n            ans[ind] = c[to];\\n            c[v] -= c[to];\\n        }\\n    }\\n}\\n\\n\\nint main()\\n{\\n#ifdef ONPC\\n    freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n    int n, m;\\n    scanf(\\\"%d%d\\\", &n, &m);\\n    for (int i = 0; i < n; i++)\\n    {\\n        scanf(\\\"%lld\\\", &c[i]);\\n        cur[i] = c[i];\\n    }\\n    for (int i = 0; i < m; i++)\\n    {\\n        int a, b;\\n        scanf(\\\"%d%d\\\", &a, &b);\\n        a--, b--;\\n        g[a].push_back({b, i});\\n        g[b].push_back({a, i});\\n    }\\n    dfs(0);\\n    if (cur[0] == 0)\\n    {\\n        puts(\\\"YES\\\");\\n        for (int i = 0; i < m; i++)\\n        {\\n            printf(\\\"%lld\\\\n\\\", ans[i]);\\n        }\\n        return 0;\\n    }\\n    if (edge_ind != -1)\\n    {\\n        for (int i = 0; i < m; i++)\\n        {\\n            ans[i] = 0;\\n        }\\n        for (int i = 0; i < n; i++)\\n        {\\n            u[i] = 0;\\n        }\\n        solve_tree(s);\\n        ll get = c[s] / 2;\\n        int cur = s;\\n        int sign = 1;\\n        while (cur != t)\\n        {\\n            ans[par_ind[cur]] += sign * get;\\n            sign *= -1;\\n            cur = par[cur];\\n        }\\n        ans[edge_ind] += sign * get;\\n        puts(\\\"YES\\\");\\n        for (int i = 0; i < m; i++)\\n        {\\n            printf(\\\"%lld\\\\n\\\", ans[i]);\\n        }\\n    }\\n    else\\n    {\\n        puts(\\\"NO\\\");\\n        return 0;\\n    }\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "901",
    "index": "E",
    "title": "Cyclic Cipher",
    "statement": "Senor Vorpal Kickass'o invented an innovative method to encrypt integer sequences of length $n$. To encrypt a sequence, one has to choose a secret sequence $\\{b_{i}\\}_{i=0}^{n-1}$, that acts as a key.\n\nVorpal is very selective, so the key should be such a sequence $b_{i}$, that its cyclic shifts are linearly independent, that is, there is no non-zero set of coefficients $x_{0}, x_{1}, ..., x_{n - 1}$, such that $\\sum_{i=0}^{n-1}x_{i}b_{k-i\\,\\mathrm{mod}\\,n}=0$ for all $k$ at the same time.\n\nAfter that for a sequence $\\{a_{i}\\}_{i=0}^{n-1}$ you should build the following cipher:\n\n\\[\nc_{i}=\\sum_{k=0}^{n-1}\\left(b_{k-i\\,\\mathrm{mod}\\,n}-a_{k}\\right)^{2}\n\\]\n\nIn other words, you are to compute the quadratic deviation between each cyclic shift of $b_{i}$ and the sequence $a_{i}$. The resulting sequence is the Kickass's cipher. The cipher is in development right now and Vorpal wants to decipher a sequence after it has been encrypted. You are to solve this problem for him. You are given sequences $c_{i}$ and $b_{i}$. You are to find all suitable sequences $a_{i}$.",
    "tutorial": "$(a - b)^{2} = a^{2} + b^{2} - 2ab$, hence, $c_{k}-c_{k-1}=-2\\sum_{i=1}^{n-1}b_{i}(a_{i+k}-a_{i+k-1})$. Let $a'_{i} = a_{i} - a_{i - 1}$, $c_{k}^{\\prime}={\\frac{c_{k-1}-c_{k}}{2}}$. Then $c_{k}^{\\prime}=\\sum_{i=0}^{n-1}b_{i}a_{i+k}^{\\prime}\\;\\;\\mathrm{mod}\\;n=\\sum_{u-x=k}\\sum_{\\mathrm{mod}\\;n}b_{x}a_{y}^{\\prime}$. This corresponds to cyclic convolution of polynomials $B=\\sum_{k=0}^{n-1}b_{k}x^{k}$ and $A=\\sum_{k=0}^{n-1}a_{k}x^{n-k}$. These polynomials uniquely determined by values in roots of unity of degree $n$. Thus we can divide values of $C$ by values of $B$ in this points and return to polynomials from values in roots of unity. To do this one should compute discrete Fourier Transform in arbitrary length polynomial which can be done by Bluestein's algorithm. Note that you can't use complex fft here because real values can be very close to zero leading to great precision issues. Thus you should find some mod having root of unity of degree $2n$ and compute discrete transform over it. Thus we will find $d_{k} = a_{k} - a_{0}$ for each $k$, which will allow us to recover $a_{0}$, because $c_{0}=\\sum_{i=0}^{n-1}(b_{i}-a_{i})^{2}=\\sum_{i=1}^{n-1}(b_{i}-d_{i}-a_{0})^{2}=\\sum_{i=1}^{n-1}(b_{i}-d_{i})^{2}-2a_{0}\\sum_{i=1}^{n-1}(b_{i}-d_{i})+n a_{0}^{2}$. It can be proven that values of polynomial in roots of unity are eigenvalues of matrix of linear system thus cyclic shifts are linearly independent iff there is such mod which has root of unity of degree $n$ and values of polynomial in all such roots doesn't equal zero. If it's true for polynomial in field of real numbers there will be only finite number of mods in which this may not be true (it only true if $\\operatorname{gcd}$ of polynomial and $x^{n} - 1$ isn't equal $1$ in such mod).",
    "tags": [
      "fft",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "902",
    "index": "A",
    "title": "Visiting a Friend",
    "statement": "Pig is visiting a friend.\n\nPig's house is located at point $0$, and his friend's house is located at point $m$ on an axis.\n\nPig can use teleports to move along the axis.\n\nTo use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.\n\nFormally, a teleport located at point $x$ with limit $y$ can move Pig from point $x$ to any point within the segment $[x; y]$, including the bounds.\n\nDetermine if Pig can visit the friend using teleports only, or he should use his car.",
    "tutorial": "Note that if we can get to some point x, then we can get to all points <= x. So we can support the rightmost point where we can get to. Then if this point can use the teleport (if this point is to the right of the teleport), we'll try to move it (If the limit of the teleport is to the right of the current point, then move it there). Then in the end we need to check that the rightmost point where we can get is equal to M.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "902",
    "index": "B",
    "title": "Coloring a Tree",
    "statement": "You are given a rooted tree with $n$ vertices. The vertices are numbered from $1$ to $n$, the root is the vertex number $1$.\n\nEach vertex has a color, let's denote the color of vertex $v$ by $c_{v}$. Initially $c_{v} = 0$.\n\nYou have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex $v$ and a color $x$, and then color all vectices in the subtree of $v$ (including $v$ itself) in color $x$. In other words, for every vertex $u$, such that the path from root to $u$ passes through $v$, set $c_{u} = x$.\n\nIt is guaranteed that you have to color each vertex in a color different from $0$.\n\nYou can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).",
    "tutorial": "Consider the process from the end, we will \"delete\" any subtree from the tree, whose color of the ancestor of the highest vertex differs from the color of the highest vertex and the colors of all vertices in the subtree are the same. Thus, we can show that the answer is the number of edges whose ends have different colors + 1.",
    "tags": [
      "dfs and similar",
      "dsu",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "903",
    "index": "A",
    "title": "Hungry Student Problem",
    "statement": "Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.\n\nCFK sells chicken chunks in small and large portions. A small portion contains $3$ chunks; a large one — $7$ chunks. Ivan wants to eat exactly $x$ chunks. Now he wonders whether he can buy exactly this amount of chicken.\n\nFormally, Ivan wants to know if he can choose two non-negative integers $a$ and $b$ in such a way that $a$ small portions and $b$ large ones contain exactly $x$ chunks.\n\nHelp Ivan to answer this question for several values of $x$!",
    "tutorial": "There are lots of different approaches to this problem. For example, you could just iterate on the values of $a$ and $b$ from $0$ to $33$ and check if $3a + 7b = x$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "903",
    "index": "B",
    "title": "The Modcrab",
    "statement": "Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.\n\nAfter two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has $h_{2}$ health points and an attack power of $a_{2}$. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.\n\nVova's character has $h_{1}$ health points and an attack power of $a_{1}$. Also he has a large supply of healing potions, each of which increases his current amount of health points by $c_{1}$ when Vova drinks a potion. All potions are identical to each other. It is guaranteed that $c_{1} > a_{2}$.\n\nThe battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by $a_{1}$) or drink a healing potion (it increases Vova's health by $c_{1}$; \\textbf{Vova's health can exceed $h_{1}$}). Then, \\textbf{if the battle is not over yet}, the Modcrab attacks Vova, reducing his health by $a_{2}$. The battle ends when Vova's (or Modcrab's) health drops to $0$ or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.\n\nOf course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.\n\nHelp Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.",
    "tutorial": "A simple greedy solution works: simulate the process until the Modcrab is dead, and make Vova drink a potion if his current health is less than $a_{2} + 1$, and monster's current health is greater than $a_{1}$ (because in this case Vova can't finish the Modcrab in one strike, but the Modcrab can win if Vova doesn't heal). In any other situation Vova must attack. Since all parameters are up to $100$, the number of phases won't exceed $9901$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "903",
    "index": "C",
    "title": "Boxes Packing",
    "statement": "Mishka has got $n$ empty boxes. For every $i$ ($1 ≤ i ≤ n$), $i$-th box is a cube with side length $a_{i}$.\n\nMishka can put a box $i$ into another box $j$ if the following conditions are met:\n\n- $i$-th box is not put into another box;\n- $j$-th box doesn't contain any other boxes;\n- box $i$ is smaller than box $j$ ($a_{i} < a_{j}$).\n\nMishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.\n\nHelp Mishka to determine the minimum possible number of visible boxes!",
    "tutorial": "You can always show that the answer is equal to the amount of boxes of the size appearing the most in array. Result can be easily obtained by constructive algorithm: take these most appearing boxes, put smaller boxes in decreasing order of their size into free ones (there always be space) and put resulting boxes into the larger ones in increasing order. Overall complexity: $O(n\\cdot\\log n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "903",
    "index": "D",
    "title": "Almost Difference",
    "statement": "Let's denote a function\n\n$d(x,y)=\\left\\{y-x,\\quad\\mathrm{if}\\ |x-y|>1$\n\nYou are given an array $a$ consisting of $n$ integers. You have to calculate the sum of $d(a_{i}, a_{j})$ over all pairs $(i, j)$ such that $1 ≤ i ≤ j ≤ n$.",
    "tutorial": "Starting pretty boring this came out as the most fun and controversial problem of the contest... Well, here is the basis of the solution. You maintain some kind of map/hashmap with amounts each number appeared in array so far. Processing each number you subtract $a_{i}$ $i$ times ($1$-indexed), add prefix sum up to $(i - 1)$-th number, subtract $cnt_{ai - 1} * (a_{i} - 1)$, $cnt_{ai} * a_{i}$ and $cnt_{ai + 1} * (a_{i} + 1)$ and add $a_{i}$ $cnt_{ai - 1} + cnt_{ai} + cnt_{ai + 1}$ times. Then update $cnt$ with $a_{i}$. And now we have to treat numbers greater than long long limits. Obviously, you can use built-in bigints from java/python ot write your own class with support of addition and printing of such numbers. However, numbers were up to $10^{19}$ by absolute value. Then you can use long double, its precision is enough for simple multiplication and addition. You can also use unsigned long long numbers: one for negative terms and the other one for positive terms, in the end you should handle printing negative numbers. Overall complexity: $O(n\\cdot\\log n)$.",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "903",
    "index": "E",
    "title": "Swapping Characters",
    "statement": "We had a string $s$ consisting of $n$ lowercase Latin letters. We made $k$ copies of this string, thus obtaining $k$ identical strings $s_{1}, s_{2}, ..., s_{k}$. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).\n\nYou are given $k$ strings $s_{1}, s_{2}, ..., s_{k}$, and you have to restore any string $s$ so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, $k·n ≤ 5000$).",
    "tutorial": "If we don't have two distinct strings then we just have to swap any pair of characters in any of the given strings and print it. Otherwise we have to find two indices $i$ and $j$ such that $s_{i}  \\neq  s_{j}$. Then let's store all positions $p$ such that $s_{i, p}  \\neq  s_{j, p}$ in array $pos$. If the number of those positions will exceed 4 then the answer will be <<-1>>. Otherwise we need to iterate over all positions $diffpos$ in array $pos$, try to swap $s_{i, diffpos}$ with any other character of $s_{i}$ and check that current string can be the answer. We also should try the same thing with string $s_{j}$. It is clear how we can check string $t$ to be the answer. Let's iterate over all strings $s_{1}, s_{2}, ..., s_{k}$ and for each string $s_{i}$ count the number of positions $p$ such that $s_{i, p}  \\neq  t_{p}$. Let's call it $diff(s_{i}, t)$. If for any given string $diff(s_{i}, t)$ is not equal to 0 or 2 then string $t$ can't be the answer. Otherwise if for any given string $diff(s_{i}, t)$ is equal to 0 and all characters in string $s_{i}$ are distinct then $t$ can't be the answer. If there is no string that satisfies all aforementioned conditions then the answer will be <<-1>>.",
    "tags": [
      "brute force",
      "hashing",
      "implementation",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "903",
    "index": "F",
    "title": "Clear The Matrix",
    "statement": "You are given a matrix $f$ with $4$ rows and $n$ columns. Each element of the matrix is either an asterisk (*) or a dot (.).\n\nYou may perform the following operation arbitrary number of times: choose a square submatrix of $f$ with size $k × k$ (where $1 ≤ k ≤ 4$) and replace each element of the chosen submatrix with a dot. Choosing a submatrix of size $k × k$ costs $a_{k}$ coins.\n\nWhat is the minimum number of coins you have to pay to replace all asterisks with dots?",
    "tutorial": "Constraints lead us to some kind of dp solution (is it usually called dp on broken profile?). Let $dp[i][j][mask]$ will be the minimum price to get to $i$-th column and $j$-th row with $mask$ selected. $mask$ is the previous $12$ cells inclusive from $(i, j)$ (if $j = 4$ then its exactly current column and two previous ones). Transitions for submatrices $1  \\times  1$, $2  \\times  2$ and $3  \\times  3$ are straighforward, just update mask with new ones and add $a_{k}$ to current value. If the first cell of these $12$ is empty or $1$ is set in this position, then you can go to $dp[i][j + 1][mask>>1]$ (or $(i + 1)$ and $1$ if $j = 4$) for free. Finally you can go to $dp[i + 1][j][2^{12} - 1]$ with the price of $a_{4}$. Initial value can be $0$ in $dp[3][4][0]$ (the first $12$ cells of the matrix). The answer will be stored in some valid $mask$ of $dp[n][1][mask]$. However, you can add $4$ extra empty columns and take the answer right from $dp[n + 4][1][0]$, it will be of the same price. Overall complexity: $O(n \\cdot 4 \\cdot 2^{12})$.",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "903",
    "index": "G",
    "title": "Yet Another Maxflow Problem",
    "statement": "In this problem you will have to deal with a very special network.\n\nThe network consists of two parts: part $A$ and part $B$. Each part consists of $n$ vertices; $i$-th vertex of part $A$ is denoted as $A_{i}$, and $i$-th vertex of part $B$ is denoted as $B_{i}$.\n\nFor each index $i$ ($1 ≤ i < n$) there is a directed edge from vertex $A_{i}$ to vertex $A_{i + 1}$, and from $B_{i}$ to $B_{i + 1}$, respectively. Capacities of these edges are given in the input. Also there might be several directed edges going from part $A$ to part $B$ (but never from $B$ to $A$).\n\nYou have to calculate the maximum flow value from $A_{1}$ to $B_{n}$ in this network. Capacities of edges connecting $A_{i}$ to $A_{i + 1}$ might sometimes change, and you also have to maintain the maximum flow value after these changes. Apart from that, the network is fixed (there are no changes in part $B$, no changes of edges going from $A$ to $B$, and no edge insertions or deletions).\n\nTake a look at the example and the notes to understand the structure of the network better.",
    "tutorial": "First of all, let's calculate minimum cut instead of maximum flow. The value of the cut is minimum if we choose $S$ (the first set of the cut) as $x$ first vertices of part $A$ and $y$ first vertices of part $B$ ($1  \\le  x  \\le  n$, $0  \\le  y < n$). That's because if $i$ is the minimum index such that $A_{i}\\notin S$, then we don't have to add any vertices $A_{j}$ such that $j > i$ to $S$, because that would only increase the value of the cut. Similarly, if $i$ is the maximum index such that $B_{i}\\in S$, then it's optimal to add every vertex $B_{j}$ such that $j < i$ to $S$. Okay, so we can try finding minimum cut as a function $F(x, y)$ - value of the cut if we choose $S$ as the union of $x$ first vertices in $A$ and $y$ first vertices in $B$. To find its minimum, let's rewrite it as $F(x, y) = F_{1}(x) + F_{2}(y) + F_{3}(x, y)$, where $F_{1}(x)$ is the sum of capacities of edges added to the cut in part $A$ (it doesn't depend on part $B$), $F_{2}(y)$ is the sum of capacities added to the cut from part $B$, and $F_{3}(x, y)$ is the sum of capacities added to the cut by edges going from $A$ to $B$. These functions can be denoted this way: $F_{1}(x) = 0$ if $x = n$; otherwise $F_{1}(x)$ is the capacity of the edge going from $A_{x}$ to $A_{x + 1}$; $F_{2}(y) = 0$ if $y = 0$; otherwise $F_{2}(y)$ is the capacity of the edge going from $B_{y}$ to $B_{y + 1}$; $F_{3}(x, y)$ is the sum of capacities over all edges $A_{i}  \\rightarrow  B_{j}$ such that $i  \\le  x$ and $j > y$. Since only the values of $F_{1}$ are not fixed, we can solve this problem with the following algorithm: For each $x$ ($1  \\le  x  \\le  n$), find the minimum possible sum of $F_{2}(y) + F_{3}(x, y)$. Let's denote this as $best(x)$, and let's denote $T(x) = F_{1}(x) + best(x)$; Build a segment tree that allows to get minimum value and modify a single value over the values of $T(x)$. When we need to change capacity of an edge, we add the difference between new and old capacities to $T(x)$; and to calculate the maximum flow, we query minimum over the whole tree. But how can we calculate the values of $best(x)$? We can do it using another segment tree that allows to query minimum on segment and add some value to the segment. First of all, let's set $x = 0$ and build this segment tree over values of $F_{2}(y) + F_{3}(x, y)$. The value of $F_{2}(y)$ is fixed for given $y$, so it is not modified; the value of $F_{3}(x, y)$ is initially $0$ since when $x = 0$, there are no vertices belonging to $S$ in the part $A$. And then we calculate the values of $best(x)$ one by one. When we increase $x$, we need to process all edges leading from $A_{x}$ to part $B$. When we process an edge leading to vertex $B_{i}$ with capacity $c$, we have to add $c$ to every value of $F_{3}(x, y)$ such that $i > y$ (since if $i > y$, then $B_{i}\\notin S$), and this can be performed by addition on segment in the segment tree. After processing each edge leading from $A_{x}$ to part $B$, we can query $best(x)$ as the minimum value in the segment tree. Time complexity of this solution is $O((n+m+q)\\log n)$.",
    "tags": [
      "data structures",
      "flows",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "906",
    "index": "A",
    "title": "Shockers",
    "statement": "Valentin participates in a show called \"Shockers\". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.\n\nValentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.",
    "tutorial": "From last action, selected letter can be found; let it be $c$ (without loss of generality). For each of other $25$ letters, answers on some actions are contradicting with assumption that this letter was selected; moreover, for each letter $d$ not equal to $c$, we can find the earlest such action with number $A_{d}$ (for each action, we can easily check if assumption \"$d$ is selected\" is contradicting with the action or not on linear time). Then, the answer is a number of electric shocks after action with number which is maximal among all such $A_{d}$-s.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "906",
    "index": "B",
    "title": "Seating of Students",
    "statement": "Students went into a class to write a test and sat in some way. The teacher thought: \"Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating.\"\n\nThe class can be represented as a matrix with $n$ rows and $m$ columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.\n\nLet's enumerate students from $1$ to $n·m$ in order of rows. So a student who initially sits in the cell in row $i$ and column $j$ has a number $(i - 1)·m + j$. You have to find a matrix with $n$ rows and $m$ columns in which all numbers from $1$ to $n·m$ appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.",
    "tutorial": "The problem has many solutions, including random ones. Consider one of deterministic solutions. Without loss of generality, assume that $n  \\le  m$. There are a couple of corner cases: $n = 1, m = 1$. In this case, good seating exists. $n = 1, m = 2$. In this case, seating does not exist (obviously). $n = 1, m = 3$. In any seating, one of neighbours of student 2 will be one of his former neighbours, so correct seating does not exist. $n = 2, m = 2$. Only student 4 can be a neighbour of student 1, but there should be 2 neighbours for student 1; then, correct seating does not exist. $n = 2, m = 3$. Both students 5 and 2 have 3 neighbours in the initial seating; then, in new seating, these students should be in non-neighbouring corner cells. Moreover, these corner cells can not be in one row because in this case it's impossible to find a student for cell between 2 and 5. So, without loss of generality, let 5 be in lower left corner, and 2 - in upper right corner. Then, only students 1 and 3 can seat on lower middle cell; but if sduent 1 seats in the cell, then student 4 is impossible to seat at any of the remaining cells, so do student 6 in case of student 3 seating at the cell. So, correct seating does not exist in this case too. $n = 1, m = 4$. In this case, one of correct seatings is 2 4 1 3. $n = 1;5  \\le  m$. In this case, let students with odd numbers in increasing order will be in first half of the row, and others in increasing order - in second half. For example, for $m = 7$ the seating will be 1 3 5 7 2 4 6. $n = m = 3$. One of possible correct seatings is:6 1 8 7 5 3 2 9 4; 6 1 8 7 5 3 2 9 4; If $2  \\le  n;4  \\le  m$, then shift each even row cyclically on two symbols in the right, and then shift each even column cyclically on one symbol upwards. If students are vertical neighbours in the initial seating, then in new seating, they will be in different columns on the distance 2 (possibly through the edge of the table); but if students are horizontal neighbours in the initial seating, then in new seating they will be in neighbouring rows and neighbouring columns (possibly thorugh the edges again). So, for case $2  \\le  n, 4  \\le  m$, we build a correct seating.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "906",
    "index": "C",
    "title": "Party",
    "statement": "Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.\n\nAt each step he selects one of his guests $A$, who pairwise introduces all of his friends to each other. After this action any two friends of $A$ become friends. This process is run until all pairs of guests are friends.\n\nArseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it.",
    "tutorial": "Let's formulate and prove several facts. 1. If we change an call order, the result doesn't change. Let's consider two vertices which are called consecutively. If they are not connected by edge, then regardless of the order, we get that at the end, neighbours of each vertex form a clique. If they are connected, then independently on the order, we get clique from 2 vertices and all neighbours of them. 2. If graph is a tree, it's sufficient to take as an answer all its vertices except leaves. Indeed, if we consider any 2 tree vertices, we get that all vertices on the way between them are in the answer. Each vertex reduces on 1 the distance between those 2, it means that the distance between them is 1. 3. Let's select from source graph spanning tree, that has the largest number of leaves. One can say that we can use all vertices except leaves as an answer. Obviously from point 2, that after all our operations with such set graph will become complete. Let's show that it is minimal number of vertices. Let we selected some set of vertices, that is the answer. Then subgraph of given graph, built on the selected set of vertices, should be connected (otherwise between connected component can't appear the edge and graph can't be complete. Also, each of vertices, that isn't in an answer should have at least one of neighbours selected (otherwise it is impossible to add new edge to it). Now let's select a spanning tree in selected set (it's possible because our set is connected) and add non-selected vertices into the tree as leafs. Then we see that our selected can be represented as spanning tree in the initial graph, in which all selected vertices are all non-leaf vertices and possibly, some leafs; but leafs can be obviously removed from the selected set by proved above. So, one of optimal answers can be described as set of non-leaf vertices of spanning tree with minimal possible number of non-leaves and, as a consequence, with maximal possible number of leaves, QED. 4. Implementation. It is necessary to implement an algorithm that should work for $2^{n} \\cdot n$ or faster or with worse asymptotic but with non-asymptotical optimization. One of possible solutions is following. Let contain any subset of vertices as a $n$-bit mask; for example, mask of a subset containing vertices ${v_{1}, v_{2}, ..., v_{k}}$ will be equal to $2^{v}_{1} + 2^{v}_{2} + ... + 2^{v}_{k}$. Then, for subset with mask $m$, vertex $v$ is in set iff $m & 2^{v}$ is not equal to 0; here $&$ is a bitwise AND. Let for each vertex $v$, $neighbours[v]$ be a mask of subset of vertices containing vertex $v$ and it's neighbours. Array $neighbours[v]$ can be calculated easily. Then, let $bool isConnected[m]$ be 1 for some mask $m$ iff subset coded by $m$ is connected. Array $isConnected$ can be calculated in $O(2^{n} * n)$ by the following algorithm: for all vertices $v\\in[0.n-1]$ (let vertices be enumerated in 0-indexation), $isCalculated[2^{v}]$ is assigned to 1; for all other masks, $isCalculated$ should be equal to 0; then, go through all masks in increasing order by a simple cycle; let $m$ be current mask in the cycle; if $isConnected[m] = 0$, then go to the next iteration of cycle; otherwise, let $v_{1}, v_{2}, ..., v_{k}$ be vertices of subset coded by $m$. Then, mask $m': = maskNeighbours[m]: = neighbours[v_{1}]|neighbours[v_{2}]|... |neighbours[v_{k}]$ for | as bitwise OR is a mask coding a subset of vertices containing vertices of mask $m$ and their neighbours. Then, for each vertex $w$ in subset of mask $m'$ we assign $isConnected[m|2^{w}]$ to be 1. The described algorithm works in $O(2^{n} * n)$; it can be proved by induction that at the end, $isConnected[m] = 1$ for mask $m$ iff $m$ is a code of connected subset of vertices. But how to find an answer? Notice that mask $m = 2^{v}_{1} + 2^{v}_{2} + ... + 2^{v}_{k}$ is a code of good (for our purposes) subset iff $isConnected[m] = 1$ and $maskNeighbours[m] = 2^{n} - 1 = 2^{0} + 2^{1} + ... + 2^{n - 1}$. For each mask $m$, we can check if it's good in $O(n)$ time having an array $isConnected$ calculated; the answer is a good mask with minimal possible number of elements in the corresponding set.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "906",
    "index": "D",
    "title": "Power Tower",
    "statement": "Priests of the Quetzalcoatl cult want to build a tower to represent a power of their god. Tower is usually made of power-charged rocks. It is built with the help of rare magic by levitating the current top of tower and adding rocks at its bottom. If top, which is built from $k - 1$ rocks, possesses power $p$ and we want to add the rock charged with power $w_{k}$ then value of power of a new tower will be ${w_{k}}^{p}$.\n\nRocks are added from the last to the first. That is for sequence $w_{1}, ..., w_{m}$ value of power will be\n\n\\[\n\\sqrt{\\left(w_{2}^{\\left(w_{3}^{\\left(w_{2}^{\\left.3\\right)^{w}m}}\\right)}}\\right)}\n\\]\n\nAfter tower is built, its power may be extremely large. But still priests want to get some information about it, namely they want to know a number called cumulative power which is the true value of power taken modulo $m$. Priests have $n$ rocks numbered from $1$ to $n$. They ask you to calculate which value of cumulative power will the tower possess if they will build it from rocks numbered $l, l + 1, ..., r$.",
    "tutorial": "Let's learn to calculate $a_{1}^{a_{2}^{\\ldots a n}}\\mathrm{\\\\\\,mod{\\}}m$. Assume that we want to find $n^{x}\\ {\\mathrm{mod}}\\ m$ where $n$ and $m$ non necessary co-prime, and $x$ is some big number which we can calculate only modulo some value. We can solve this problem for co-prime $n$ and $m$ via Euler's theorem. Let's reduce general case to that one. Note that $a n\\ \\ m\\!\\mathrm{od\\}a m=a(n\\ \\mathrm{mod\\}m)$. Indeed if $n = d \\cdot m + r, |r| < m$, then $an = d \\cdot am + ar, |ar| < |am|$. Let $p_{1}, ..., p_{t}$ to be common prime divisors of $n$ and $m$, $a = p_{1}^{k1}... p_{t}^{kt}$ to be such number that it divisible by such divisors to the power they occur in $m$, and $k$ to be least number such that $n^{k}=0\\;\\;\\;\\mathrm{mod}\\;a$. Then we have a chain $n^{x}\\;\\mathrm{\\mod\\}\\;m=\\left(\\frac{n^{k}}{a}\\right)a n^{x-k}\\;\\mathrm{\\mod\\}a\\left(\\frac{m}{a}\\right)=n^{k}\\left[n^{x-k}\\;\\mathrm{\\mod\\}\\left(\\frac{m}{a}\\right)\\right]\\;\\;\\mathrm{\\mod\\}m$ Here $n$ and $m / a$ are co-prime so we can calculate power value module $\\varphi\\left({\\frac{m}{a}}\\right)$. Moreover, $k\\leq\\log_{2}m$, thus case $x < k$ can be considered in $O(\\log m)$. This is already enough to solve the problem, but continuing one can prove that for $x\\geq\\log_{2}m$ it holds $n^{x}\\;\\mathrm{\\mod\\}\\;m=n^{\\varphi(m)+x\\,\\mathrm{mod\\}\\varphi(m)\\mod\\Pi}$ Where $ \\phi (m)$ is Euler totient function of $m$. Finally, to solve the problem one shoud note that $\\varphi(\\varphi(m))\\leq{\\frac{m}{2}}$ so it will take only $O(\\log m)$ steps before $m$ turns into $1$.",
    "tags": [
      "chinese remainder theorem",
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "906",
    "index": "E",
    "title": "Reverses",
    "statement": "Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing minimum possible number of its substrings and find out which substrings you should reverse.\n\nYou are given a string $s$ — original state of your string and string $t$ — state of the string after hurricane. You should select $k$ non-intersecting substrings of $t$ in such a way that after reverse of these substrings string will be equal $s$ and $k$ is minimum possible.",
    "tutorial": "After inverses we have transform $A_{1}B_{1}A_{2}B_{2}... A_{k}B_{k}A_{k + 1}  \\rightarrow  A_{1}B_{1}^{r}A_{2}B_{2}^{r}... A_{k}B_{k}^{r}A_{k + 1}$. Consider operator $mix(A, B) = a_{1}b_{1}a_{2}b_{2}... a_{n}b_{n}$ for strings of equal lengths. Under such operator string will turn into $X_{1}Y_{1}X_{2}Y_{2}... X_{k}Y_{k}X_{k + 1}$ where $X_{k}$ is string which has all characters doubled and $Y_{k}$ is arbitrary palindrome of even length. Let's move through letters from left to right and keep minimum number on which we can split current prefix. Last letter will either be in some palindrome or is doubled. For doubled letters we consider $ans_{i} = min(ans_{i}, ans_{i - 2})$. As for palindromes of even length, one can fit standard algorithm of splitting string into the minimum number of palindromes in such way that it will consider only splittings on even palindromes. For example, one can consider only such spits that every palindrome in the split end up in even index.",
    "tags": [
      "dp",
      "string suffix structures",
      "strings"
    ],
    "rating": 3300
  },
  {
    "contest_id": "907",
    "index": "A",
    "title": "Masha and Bears",
    "statement": "A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car.\n\nMasha came to test these cars. She could climb into all cars, but she liked only the smallest car.\n\nIt's known that a character with size $a$ can climb into some car with size $b$ if and only if $a ≤ b$, he or she likes it if and only if he can climb into this car and $2a ≥ b$.\n\nYou are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.",
    "tutorial": "Sizes of cars should satisfy the following constraints: in $i$-th car, Masha and corresponding bear are able to get into, so size of the car should not be less than $max(V_{i}, V_{m})$; each bear likes its car, so size of $i$-th car is no more than $2 \\cdot V_{i}$; Masha doesn't like first two cars, then their sizes are more than $2 \\cdot V_{m}$; Masha likes last car, so it's size is not more than $2 \\cdot V_{m}$; Sizes of cars are strictly ordered. It means that size of father's car is strictly more than size of mother's one, and size of mother's car is strictly more than son's car. Sizes of bears don't exceed 100; then, sizes of cars does not exceed 200, and there are only $200^{3}$ possible variants of sizes of cars. In given constraints, one can just go through all possible triples of sizes and check if each of them satisfies the constrains above or not.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "907",
    "index": "B",
    "title": "Tic-Tac-Toe",
    "statement": "Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.\n\nThe game is played on the following field.\n\nPlayers are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates $(x_{l}, y_{l})$ in some small field, the next move should be done in one of the cells of the small field with coordinates $(x_{l}, y_{l})$. For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.\n\nYou are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.\n\nA hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.",
    "tutorial": "Let us describe each cell of the field by four numbers $(x_{b}, y_{b}, x_{s}, y_{s})$, $0  \\le  x_{b}, y_{b}, x_{s}, y_{s}  \\le  2)$, where $(x_{b}, y_{b})$ are coordinates of small field containing the cell, and $(x_{s}, y_{s})$ are coordinates of the cell in it's small field. It can be seen that for cell with \"usual\" coordinates $(x, y)$, $1  \\le  x, y  \\le  9$ and our new $(x_{b}, y_{b}, x_{s}, y_{s})$, there are following equalities which give us a key to go between coordinate systems: $x_{b} =  \\lfloor ((x - 1) / 3) \\rfloor $, $y_{b} =  \\lfloor ((y - 1) / 3) \\rfloor $; $x_{s} = (x - 1) mod 3$, $y_{b} = (y - 1) mod 3$; $x = 3 * x_{b} + x_{s} + 1$, $y = 3 * y_{b} + y_{s} + 1$. In terms of new coordinates, if last move was in cell $(x_{b}, y_{b}, x_{s}, y_{s})$, then next move should be in arbitrary free cell with coordinates $(x_{s}, y_{s}, x', y')$ for some $x^{\\prime},y^{\\prime}\\in[0,2]$ if it's possible; otherwise, next move can be done in arbitrary free cell. To solve the problem, one can go through all such pairs $(x', y')$ and write \"!\" in each empty cell $(x_{s}, y_{s}, x', y')$; if there are not such empty cells, write \"!\" in all empty cells of the field.",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "908",
    "index": "A",
    "title": "New Year and Counting Cards",
    "statement": "Your friend has $n$ cards.\n\nYou know that each card has a lowercase English letter on one side and a digit on the other.\n\nCurrently, your friend has laid out the cards on a table so only one side of each card is visible.\n\nYou would like to know if the following statement is true for cards that your friend owns: \"If a card has a vowel on one side, then it has an even digit on the other side.\" More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.\n\nFor example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.\n\nTo determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.",
    "tutorial": "Let's start off a bit more abstractly. We would like to know if the statement \"if P then Q\" is true, where P and Q are some statements (in this case, P is \"card has vowel\", and Q is \"card has even number\"). To do determine this, we need to flip over any cards which could be counter-examples (i.e. could make the statement false). Let's look at the truth table for if P then Q (see here: http://www.math.hawaii.edu/~ramsey/Logic/IfThen.html). The statement is only false when Q is false and P is true. Thus, it suffices to flip cards when P is true or Q is false. To solve this problem, we need to print the count of vowels and odd digits in the string.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"test.in\", \"r\", stdin));\n#endif\n  string s;\n  cin >> s;\n  int res = 0;\n  string v = \"aeiou\";\n  for (auto c : s) {\n    if (find(v.begin(), v.end(), c) != v.end() || (isdigit(c) && (c - '0') % 2))\n      ++res;\n  }\n  cout << res << '\n';\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "908",
    "index": "B",
    "title": "New Year and Buggy Bot",
    "statement": "Bob programmed a robot to navigate through a 2d maze.\n\nThe maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.\n\nThere is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.\n\nThe robot can only move up, left, right, or down.\n\nWhen Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.\n\nThe robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.\n\nBob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.",
    "tutorial": "This problem is intended as an implementation problem. The bounds are small enough that a brute force works. We can iterate through all mapping of numbers to directions (i.e. using next permutation in C++ or doing some recursive DFS if there is no built in next permutation in your language), and simulate the robot's movements. We have to be careful that if the robot ever gets in an invalid state, we break out early and say the mapping is invalid.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\n\nconst int maxn = 55;\nstring s[maxn];\n\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"test.in\", \"r\", stdin));\n#endif\n  int n, m;\n  cin >> n >> m;\n  int sx = -1, sy = -1;\n  for (int i = 0; i < n; ++i) {\n    cin >> s[i];\n    for (int j = 0; j < m; ++j) {\n      if (s[i][j] == 'S')\n        sx = i, sy = j;\n    }\n  }\n  string w;\n  cin >> w;\n  vector<int> p{0, 1, 2, 3};\n  const int dx[] = {-1, 0, 1, 0};\n  const int dy[] = {0, -1, 0, 1};\n  int res = 0;\n  do {\n    int x = sx, y = sy;\n    bool fail = false;\n    for (auto c : w) {\n      x += dx[p[c - '0']];\n      y += dy[p[c - '0']];\n      if (x >= n || x < 0 || y >= m || y < 0 || s[x][y] == '#') {\n        fail = true;\n        break;\n      }\n      if (s[x][y] == 'E')\n        break;\n    }\n    if (!fail && s[x][y] == 'E') {\n      ++res;\n    }\n  } while (next_permutation(p.begin(), p.end()));\n  cout << res << '\n';\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "908",
    "index": "C",
    "title": "New Year and Curling",
    "statement": "Carol is currently curling.\n\nShe has $n$ disks each with radius $r$ on the 2D plane.\n\nInitially she has all these disks above the line $y = 10^{100}$.\n\nShe then will slide the disks towards the line $y = 0$ one by one in order from $1$ to $n$.\n\nWhen she slides the $i$-th disk, she will place its center at the point $(x_{i}, 10^{100})$. She will then push it so the disk’s $y$ coordinate continuously decreases, and $x$ coordinate stays constant. The disk stops once it touches the line $y = 0$ or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk.\n\nCompute the $y$-coordinates of centers of all the disks after all disks have been pushed.",
    "tutorial": "This is another simulation problem with some geometry. As we push a disk, we can iterate through all previous disks and see if their $x$-coordinates are $ \\le  2r$. If so, then that means these two circles can possibly touch. If they do, we can compute the difference of heights between these two circles using pythagorean theorem. In particular, we want to know the change in $y$ coordinate between the two touching circles. We know the hypotenuse (it is $2r$ since the circles are touching), and the change in $x$-coordinate is given, so the change in $y$ coordinate is equal to $\\sqrt{4r^{2}-d x^{2}}$, where $dx$ is the change in $x$-coordinate. We can then take the maximum over all of these cases to get our final $y$-coordinate, since this is where this disk will first stop. Overall, this takes $O(n^{2})$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\n\nconst int maxn = 2018;\nld x[maxn];\nld y[maxn];\n\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"test.in\", \"r\", stdin));\n#endif\n  cout << fixed;\n  cout.precision(10);\n  int n;\n  ld r;\n  cin >> n >> r;\n  for (int i = 0; i < n; ++i) {\n    cin >> x[i];\n    ld my = r;\n    for (int j = 0; j < i; ++j) {\n      if (fabsl(x[i] - x[j]) > 2 * r) {\n        continue;\n      }\n      auto sqr = [](ld x) { return x * x; };\n      ld cy = y[j] + sqrtl(sqr(2 * r) - sqr(x[i] - x[j]));\n      my = max(my, cy);\n    }\n    y[i] = my;\n    cout << my << ' ';\n  }\n  cout << '\n';\n}",
    "tags": [
      "brute force",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "908",
    "index": "D",
    "title": "New Year and Arbitrary Arrangement",
    "statement": "You are given three integers $k$, $p_{a}$ and $p_{b}$.\n\nYou will construct a sequence with the following algorithm: Initially, start with the empty sequence. Each second, you do the following. With probability $p_{a} / (p_{a} + p_{b})$, add 'a' to the end of the sequence. Otherwise (with probability $p_{b} / (p_{a} + p_{b})$), add 'b' to the end of the sequence.\n\nYou stop once there are at least $k$ subsequences that form 'ab'. Determine the expected number of times 'ab' is a subsequence in the resulting sequence. It can be shown that this can be represented by $P / Q$, where $P$ and $Q$ are coprime integers, and $Q\\neq0{\\mathrm{~mod~}}(10^{9}+7)$. Print the value of $P\\cdot Q^{-1}\\operatorname{mod}\\left(10^{9}+7\\right)$.",
    "tutorial": "The main trickiness of this problem is that the sequence could potentially get arbitrary long, but we want an exact answer. In particular, it helps to think about how to reduce this problem to figuring out what state we need to maintain from a prefix of the sequence we've built in order to simulate our algorithm correctly. This suggests a dynamic programming approach. For our dp state, we need to keep track of something in our prefix. First, the most obvious candidate is we need to keep track of the number of times 'ab' occurs in the prefix (this is so we know when to stop). However, using only this is not enough, as we can't distinguish between the sequences 'ab' and 'abaaaa'. So, this suggests we also need to keep track of the number of 'a's. Let $dp[i][j]$ be the expected answer given that there are $i$ subsequences of the form 'a' in the prefix and $j$ subsequences of the form 'ab' in the prefix. Then, we have something like $dp[i][j] = (p_{a} * dp[i + 1][j] + p_{b} * dp[i][i + j]) / (p_{a} + p_{b})$. The first term in this sum comes from adding another 'a' to our sequence, and the second comes from adding a 'b' to our sequence. We also have $dp[i][j] = j$ if $j  \\ge  k$ as a base case. The answer should be $dp[0][0]$. However, if we run this as is, we'll notice there are still some issues. One is that $i$ can get arbitrarily large here, as we can keep adding 'a's indefinitely. Instead, we can modify our base case to when $i + j  \\ge  k$. In this case, the next time we get a 'b', we will stop, so we can find a closed form for this scenario. The second is that any 'b's that we get before any occurrences of 'a' can essentially be ignored. To fix this, we can adjust our answer to be $dp[1][0]$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\n\nconst int mod = 1e9 + 7;\ntemplate<typename T>\nT add(T x) {\n  return x;\n}\ntemplate<typename T, typename... Ts>\nT add(T x, Ts... y) {\n  T res = x + add(y...);\n  if (res >= mod)\n    res -= mod;\n  return res;\n}\ntemplate<typename T, typename... Ts>\nT sub(T x, Ts... y) {\n  return add(x, mod - add(y...));\n}\ntemplate<typename T, typename... Ts>\nvoid udd(T &x, Ts... y) {\n  x = add(x, y...);\n}\ntemplate<typename T>\nT mul(T x) {\n  return x;\n}\ntemplate<typename T, typename... Ts>\nT mul(T x, Ts... y) {\n  return (x * 1ll * mul(y...)) % mod;\n}\ntemplate<typename T, typename... Ts>\nvoid uul(T &x, Ts... y) {\n  x = mul(x, y...);\n}\nint bin(int a, ll deg) {\n  int r = 1;\n  while (deg) {\n    if (deg & 1)\n      uul(r, a);\n    deg >>= 1;\n    uul(a, a);\n  }\n  return r;\n}\nint inv(int x) {\n  assert(x);\n  return bin(x, mod - 2);\n}\n\n\nconst int maxn = 1005;\nint d[maxn][maxn];\nint k;\nint pa, pb;\n\n\nint calc(int n, int m) {\n  if (m >= k) {\n    return m;\n  }\n  assert(n <= k);\n  if (n == k) {\n    int mean = mul(sub(1, pb), inv(pb));\n    return add(m, k, mean);\n  }\n  if (d[n][m] != -1) {\n    return d[n][m];\n  }\n  int& res = d[n][m];\n  res = add(mul(pa, calc(n + 1, m)), mul(pb, calc(n, n + m)));\n  return res;\n}\n\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"test.in\", \"r\", stdin));\n#endif\n  cin >> k >> pa >> pb;\n  memset(d, -1, sizeof(d));\n  for (int i = 0; i < maxn; ++i) {\n    for (int j = 0; j < maxn; ++j) {\n      d[i][j] = -1;\n    }\n  }\n  int isum = inv(pa + pb);\n  uul(pa, isum);\n  uul(pb, isum);\n  cout << calc(1, 0) << '\n';\n}",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "908",
    "index": "E",
    "title": "New Year and Entity Enumeration",
    "statement": "You are given an integer $m$.\n\nLet $M = 2^{m} - 1$.\n\nYou are also given a set of $n$ integers denoted as the set $T$. The integers will be provided in base 2 as $n$ binary strings of length $m$.\n\nA set of integers $S$ is called \"good\" if the following hold.\n\n- If $a\\in S$, then $a\\mathrm{\\XOR}\\,\\,M\\in S$.\n- If $a.b\\in S$, then $a\\mathrm{{\\AND}}\\ b\\in S$\n- $T\\subseteq S$\n- All elements of $S$ are less than or equal to $M$.\n\nHere, $\\mathrm{XOR}$ and $\\mathrm{AND}$ refer to the bitwise XOR and bitwise AND operators, respectively.\n\nCount the number of good sets $S$, modulo $10^{9} + 7$.",
    "tutorial": "Let's ignore $T$ for now, and try to characterize good sets $S$. For every bit position $i$, consider the bitwise AND of all elements of $S$ which have the $i$-th bit on (note, there is at least one element in $S$ which has the $i$-th bit on, since we can always $\\mathrm{XOR}$ by $m$). We can see that this is equivalent to the smallest element of $S$ that contains the $i$-th bit. Denote the resulting number as $f(i)$. We can notice that this forms a partition of the bit positions, based on the final element that we get. In particular, there can't be a scenario where there is two positions $x, y$ with $f(x)\\neq f(y)$ such that $f(x)\\ \\mathrm{AND}\\ f(y)\\neq0$. To show this, let $b=f(x)\\ \\mathrm{AND}\\ f(y)$, and without loss of generality, let's assume $b\\neq f(x)$ (it can't be simultaneously equal to $f(x), f(y)$ since $f(x)\\neq f(y)$). If the $x$-th bit in $b$ is on, we get a contradiction, since $b$ is a smaller element than $f(x)$ that contains the $x$-th bit. If the $x$-th bit in $b$ is off, then, $f(x)\\ {\\mathrm{AND~}}(b\\ {\\mathrm{XOR}}\\ M)$ is a smaller element of $S$ that contains the $x$-th bit. So, we can guess at this point that good sets $S$ correspond to partitions of ${1, 2, ..., m}$ one to one. Given a partition, we can construct a valid good set as follows. We can observe that a good set $S$ must be closed under bitwise OR also. To prove this, for any two elements $a.b\\in S$, $a\\mathrm{\\OR\\}b=(\\left(a\\mathrm{\\boldmath~XOR\\}\\mathcal{M}\\right)\\,\\mathrm{AND}\\left(b\\mathrm{\\boldmath~XOR~}M\\right)\\right)\\,\\mathrm{XOR~}M$. Since the latter is some composition of XORs and ANDs, it it also in $S$. So, given a partition, we can take all unions of some subset of the partitions to get $S$. For an actual solution, partitions can be computed with bell numbers, which is an $O(m^{2})$ dp (see this: http://mathworld.wolfram.com/BellNumber.html ). Now, back to $T$, we can see that this decides some partitions beforehand. In particular, for each bit position, we can make a $n$-bit mask denoting what its value is in each of the $n$ given values. The partitions are based on what these masks are. We can find what the sizes of these splits are, then multiply the ways to partition each individual split together to get the answer.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\n\nconst int mod = 1e9 + 7;\ntemplate<typename T>\nT add(T x) {\n  return x;\n}\ntemplate<typename T, typename... Ts>\nT add(T x, Ts... y) {\n  T res = x + add(y...);\n  if (res >= mod)\n    res -= mod;\n  return res;\n}\ntemplate<typename T, typename... Ts>\nT sub(T x, Ts... y) {\n  return add(x, mod - add(y...));\n}\ntemplate<typename T, typename... Ts>\nvoid udd(T &x, Ts... y) {\n  x = add(x, y...);\n}\ntemplate<typename T>\nT mul(T x) {\n  return x;\n}\ntemplate<typename T, typename... Ts>\nT mul(T x, Ts... y) {\n  return (x * 1ll * mul(y...)) % mod;\n}\ntemplate<typename T, typename... Ts>\nvoid uul(T &x, Ts... y) {\n  x = mul(x, y...);\n}\nint bin(int a, ll deg) {\n  int r = 1;\n  while (deg) {\n    if (deg & 1)\n      uul(r, a);\n    deg >>= 1;\n    uul(a, a);\n  }\n  return r;\n}\nint inv(int x) {\n  assert(x);\n  return bin(x, mod - 2);\n}\n\n\nconst int maxn = 1005;\nint b[maxn][maxn];\nint bsum[maxn];\n\n\nvoid pre() {\n  b[0][0] = 1;\n  for (int i = 0; i < maxn - 1; ++i) {\n    for (int j = 0; j <= i; ++j) {\n      udd(bsum[i], b[i][j]);\n      udd(b[i + 1][j], mul(b[i][j], j));\n      udd(b[i + 1][j + 1], b[i][j]);\n    }\n  }\n}\n\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"test.in\", \"r\", stdin));\n#endif\n  pre();\n  int m, n;\n  cin >> m >> n;\n  vector<string> v(m, string(n, ' '));\n  for (int i = 0; i < n; ++i) {\n    string s;\n    cin >> s;\n    for (int j = 0; j < m; ++j) {\n      v[j][i] = s[j];\n    }\n  }\n  sort(v.begin(), v.end());\n  int res = 1;\n  for (int i = 0; i < m; ++i) {\n    int r = i;\n    while (r < m && v[r] == v[i]) {\n      ++r;\n    }\n    cerr << \"cnt: \" << r - i << '\n';\n    uul(res, bsum[r - i]);\n    i = r - 1;\n  }\n  cout << res << '\n';\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "908",
    "index": "F",
    "title": "New Year and Rainbow Roads",
    "statement": "Roy and Biv have a set of $n$ points on the infinite number line.\n\nEach point has one of 3 colors: red, green, or blue.\n\nRoy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.\n\nThey want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).\n\nHowever, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.\n\nTherefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).\n\nHelp them compute the minimum cost way to choose edges to satisfy the above constraints.",
    "tutorial": "Let's make a few simplifying observations It is not optimal to connect a red and blue point directly: Neither Roy or Biv will see this edge. If we have a sequence like red green red (or similarly blue green blue), it is not optimal to connect the outer two red nodes. We can replace the outer edge with two edges that have the same weight. This replacement will form some cycle in the red-green points, so we can remove one of these edges for a cheaper cost. With these two observations, we can construct a solution as follows. First, split the points by the green points. Each section is now independent. There are then two cases, the outer green points are not directly connected, in which case, we must connect all the red/blue points in the line (for 2 * length of segment weight), or the outer green points are directly connected, in which case, we can omit the heaviest red and blue segment (for 3 * length of segment - heaviest red - heaviest blue). Thus, this problem can be solved in linear time. Be careful about the case with no green points.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"test.in\", \"r\", stdin));\n#endif\n  int n;\n  cin >> n;\n  ll pr = -1e12;\n  ll gmin = 1e12, gmax = -1e12;\n  ll bmin = 1e12, bmax = -1e12;\n  ll rmin = 1e12, rmax = -1e12;\n  vector<int> p[2];\n  ll res = 0;\n  for (int i = 0; i <= n; ++i) {\n    ll x;\n    char c;\n    if (i < n) {\n      cin >> x >> c;\n    } else {\n      x = 1e12, c = 'G';\n    }\n    if (c == 'G') {\n      if (i < n) {\n        gmin = min<ll>(gmin, x);\n        gmax = max<ll>(gmax, x);\n      }\n      ll cur1 = x - pr, cur2 = (x - pr) * 2;\n      if (cur1 >= 1e11) {\n        cur1 = 0;\n      }\n      for (int q = 0; q < 2; ++q) {\n        if (!p[q].empty()) {\n          cur1 += x - pr;\n          ll mx = max<ll>(p[q].front() - pr, x - p[q].back());\n          for (int j = 0; j < (int) p[q].size() - 1; ++j) {\n            mx = max<ll>(mx, p[q][j + 1] - p[q][j]);\n          }\n          cur1 -= mx;\n          p[q].clear();\n        }\n      }\n      res += min(cur1, cur2);\n      pr = x;\n    } else if (c == 'R') {\n      p[0].push_back(x);\n      rmin = min<ll>(rmin, x);\n      rmax = max<ll>(rmax, x);\n    } else {\n      p[1].push_back(x);\n      bmin = min<ll>(bmin, x);\n      bmax = max<ll>(bmax, x);\n    }\n  }\n  if (gmin > gmax) {\n    ll res = 0;\n    if (rmin < rmax) {\n      res += rmax - rmin;\n    }\n    if (bmin < bmax) {\n      res += bmax - bmin;\n    }\n    cout << res << '\n';\n    return 0;\n  }\n  cout << res << '\n';\n}",
    "tags": [
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "908",
    "index": "G",
    "title": "New Year and Original Order",
    "statement": "Let $S(n)$ denote the number that represents the digits of $n$ in sorted order. For example, $S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555$.\n\nGiven a number $X$, compute $\\textstyle\\sum_{1\\leq k\\leq X}S(k)$ modulo $10^{9} + 7$.",
    "tutorial": "This is a digit dp problem. Let's try to solve the subproblem \"How many ways can the i-th digit be at least j?\". Let's fix j, and solve this with dp. We have a dp state dp[a][b][c] = number of ways given we've considered the first $a$ digits of $X$, we need $b$ more occurrences of digits at least $j$, and $c$ is a boolean saying whether or not we are strictly less than $X$ or not yet. For a fixed digit, we can compute this dp table in $O(n^{2})$ time, and then compute the answers to our subproblem for each $i$ (i.e. by varying $b$ in our table).",
    "code": "// vvvvvvvvvvvvvvvvv Library code start\n\n\n\n\n#define NDEBUG\nNDEBUG\n\n\n\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cstring>\n#include <cmath>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n#include <memory>\n#include <queue>\n#include <random>\n\n\n\n\n#define forn(t, i, n) for (t i = 0; i < (n); ++i)\n#define foran(t, i, a, n) for (t i = (a); i < (n); ++i)\n#define rforn(t, i, n) for (t i = (n) - 1; i >= 0; --i)\n\n\n\n\nusing namespace std;\n\n\n// TC_REMOVE_BEGIN\n/// caide keep\nbool __hack = std::ios::sync_with_stdio(false);\n/// caide keep\nauto __hack1 = cin.tie(nullptr);\n// TC_REMOVE_END\n\n\n\n\n// Section with adoption of array and vector algorithms.\n\n\n\n\nnamespace option_detail {\n    /// caide keep\n    struct NoneHelper {};\n}\n\n\n\n\ntemplate<class Value>\nclass Option {\npublic:\n    \n\n\n    static_assert(!std::is_reference<Value>::value,\n                  \"Option may not be used with reference types\");\n    static_assert(!std::is_abstract<Value>::value,\n                  \"Option may not be used with abstract types\");\n\n\n    \n    Value* get_pointer() && = delete;\n\n\n    \n    // Return b copy of the value if set, or b given default if not.\n    \n\n\n    // Return b copy of the value if set, or b given default if not.\n    \n\n\nprivate:\n    \n\n\n    struct StorageTriviallyDestructible {\n        // uninitialized\n        \n        bool hasValue;\n\n\n        \n    };\n\n\n    /// caide keep\n    struct StorageNonTriviallyDestructible {\n        // uninitialized\n        union { Value value; };\n        bool hasValue;\n\n\n        \n        ~StorageNonTriviallyDestructible() {\n            clear();\n        }\n\n\n        void clear() {\n            if (hasValue) {\n                hasValue = false;\n                value.~Value();\n            }\n        }\n    };\n\n\n    /// caide keep\n    using Storage =\n    typename std::conditional<std::is_trivially_destructible<Value>::value,\n            StorageTriviallyDestructible,\n            StorageNonTriviallyDestructible>::type;\n\n\n    Storage storage_;\n};\n\n\n\n\n// Comparisons.\n\n\n\n\ntemplate<class V> bool operator< (const Option<V>&, const V& other) = delete;\ntemplate<class V> bool operator<=(const Option<V>&, const V& other) = delete;\ntemplate<class V> bool operator>=(const Option<V>&, const V& other) = delete;\ntemplate<class V> bool operator> (const Option<V>&, const V& other) = delete;\ntemplate<class V> bool operator< (const V& other, const Option<V>&) = delete;\ntemplate<class V> bool operator<=(const V& other, const Option<V>&) = delete;\ntemplate<class V> bool operator>=(const V& other, const Option<V>&) = delete;\ntemplate<class V> bool operator> (const V& other, const Option<V>&) = delete;\n\n\n\n\n#define ENABLE_IF(e) typename enable_if<e>::type* = nullptr\n\n\nnamespace template_util {\n    \n\n\n    constexpr int bytecount(uint64_t x) {\n        return x ? 1 + bytecount(x >> 8) : 0;\n    }\n\n\n    template<int N>\n    struct bytetype {\n        typedef uint64_t type;\n    };\n\n\n    template<>\n    struct bytetype<4> {\n        typedef uint32_t type;\n    };\n\n\n    \n    template<>\n    struct bytetype<1> {\n        typedef uint8_t type;\n    };\n\n\n    template<>\n    struct bytetype<0> {\n        typedef uint8_t type;\n    };\n\n\n    /// caide keep\n    template<uint64_t N>\n    struct minimal_uint : bytetype<bytecount(N)> {\n    };\n}\n\n\n\n\nnamespace index_iterator_impl {\n    template <class T>\n    struct member_dispatch_helper {\n        \n\n\n    private:\n        T value;\n    };\n\n\n    // Have to caide keep all the members to comply to iterator concept\n    // Otherwise generated code won't be portable between clang and g++\n    template <class C, bool reverse = false>\n    struct index_iterator {\n        /// caide keep\n        typedef random_access_iterator_tag iterator_category;\n        /// caide keep\n        typedef decltype(((C*)nullptr)->operator[](size_t(0))) reference;\n        /// caide keep\n        typedef typename remove_reference<reference>::type value_type;\n        /// caide keep\n        typedef ptrdiff_t difference_type;\n        /// caide keep\n        typedef conditional<\n                is_reference<reference>::value,\n                typename add_pointer<value_type>::type,\n                member_dispatch_helper<value_type>> pointer;\n\n\n        /// caide keep\n        typedef index_iterator<C, reverse> self_t;\n\n\n        /// caide keep\n        static const difference_type dir = reverse ? -1 : 1;\n\n\n        /// caide keep\n        index_iterator() = default;\n\n\n        \n        /// caide keep\n        inline bool operator!=(const self_t& o) { return index != o.index; }\n        /// caide keep\n        inline bool operator<(const self_t& o) { return reverse ? index > o.index : index < o.index; }\n        /// caide keep\n        inline bool operator>(const self_t& o) { return reverse ? index < o.index : index > o.index; }\n        /// caide keep\n        inline bool operator<=(const self_t& o) { return reverse ? index >= o.index : index <= o.index; }\n        /// caide keep\n        inline bool operator>=(const self_t& o) { return reverse ? index <= o.index : index >= o.index; }\n\n\n        /// caide keep\n        inline reference operator*() { return (*container)[index]; }\n        /// caide keep\n        inline const reference operator*() const { return (*container)[index]; }\n        /// caide keep\n        inline pointer operator->() { return pointer((*container)[index]); }\n\n\n        /// caide keep\n        inline self_t& operator++() { index += dir; return *this; }\n        /// caide keep\n        inline self_t operator++(int) { auto copy = *this; index += dir; return copy; }\n        /// caide keep\n        inline self_t& operator--() { index -= dir; return *this; }\n        /// caide keep\n        inline self_t operator--(int) { auto copy = *this; index -= dir; return copy; }\n\n\n        /// caide keep\n        inline self_t& operator+=(difference_type n) { index += dir * n; return *this; };\n        /// caide keep\n        inline self_t& operator-=(difference_type n) { index -= dir * n; return *this; };\n        /// caide keep\n        inline friend self_t operator-(self_t a, difference_type n) { return a -= n; };\n        /// caide keep\n        inline friend self_t operator+(difference_type n, self_t a) { return a += n; };\n        /// caide keep\n        inline friend self_t operator+(self_t a, difference_type n) { return a += n; };\n        /// caide keep\n        inline friend difference_type operator-(const self_t& a, const self_t& b) { return dir * (a.index - b.index); };\n\n\n        /// caide keep\n        inline reference operator[](difference_type n) { return (*container)[index + dir * n]; };\n        /// caide keep\n        inline const reference operator[](difference_type n) const { return (*container)[index + dir * n]; };\n\n\n    private:\n        C* container;\n        difference_type index;\n    };\n}\n\n\n\n\nnamespace multivec_impl {\n    template <size_t NDIMS>\n    struct shape {\n        size_t dim, stride;\n        shape<NDIMS - 1> subshape;\n        \n        shape(size_t dim_, shape<NDIMS - 1>&& s): dim(dim_), stride(s.size()), subshape(std::move(s)) {}\n        size_t size() const { return dim * stride; }\n        \n        \n    };\n    template <> struct shape<0> { size_t size() const { return 1; } };\n    \n\n\n    template <size_t I, size_t NDIMS>\n    struct __shape_traverse {\n        \n\n\n        ///caide keep\n        static const shape<NDIMS - I>& get_subshape(const shape<NDIMS>& s) {\n            return __shape_traverse<I - 1, NDIMS - 1>::get_subshape(s.subshape);\n        }\n    };\n\n\n    template <size_t NDIMS>\n    struct __shape_traverse<0, NDIMS> {\n        \n        static const shape<NDIMS>& get_subshape(const shape<NDIMS>& s) { return s; }\n    };\n\n\n    \n    ///caide keep\n    template <size_t I, size_t NDIMS>\n    const shape<NDIMS - I>& get_subshape(const shape<NDIMS>& s) { return __shape_traverse<I, NDIMS>::get_subshape(s); }\n\n\n    \n    template <class Index, class... Rest, size_t NDIMS, ENABLE_IF(is_integral<Index>::value)>\n    size_t get_shift(const shape<NDIMS>& s, size_t cur_shift, Index i, Rest... is) {\n        assert(0 <= i && i < s.dim);\n        return get_shift(s.subshape, cur_shift + i * s.stride, is...);\n    }\n\n\n    template <size_t NDIMS> size_t get_shift(const shape<NDIMS>&, size_t cur_shift) { return cur_shift; }\n\n\n    \n    template <class... T> shape<sizeof...(T)> make_shape(T... dims);\n\n\n    template <class Dim, class... Rest, ENABLE_IF(is_integral<Dim>::value)>\n    shape<sizeof...(Rest) + 1> make_shape(Dim dim, Rest... dims) {\n        assert(dim >= 0);\n        return {(size_t)dim, make_shape<Rest...>(dims...)};\n    }\n\n\n    template <> shape<0> make_shape() { return {}; }\n\n\n    \n    ///caide keep\n    template <class T, size_t NDIMS>\n    struct vec_view_base;\n\n\n    template <template<class, size_t> class Base, class T, size_t NDIMS>\n    struct vec_mixin : public Base<T, NDIMS> {\n        using Base<T, NDIMS>::Base;\n        /// caide keep\n        typedef Base<T, NDIMS> B;\n        \n        \n        ///caide keep\n        template <class... Indices, bool enabled = NDIMS == sizeof...(Indices), ENABLE_IF(enabled)>\n        inline T& operator()(Indices... is) {\n            size_t i = multivec_impl::get_shift(B::s, 0, is...);\n            return B::data[i];\n        }\n\n\n        ///caide keep\n        template <class... Indices, bool enabled = sizeof...(Indices) < NDIMS, ENABLE_IF(enabled)>\n        inline vec_mixin<vec_view_base, T, NDIMS - sizeof...(Indices)> operator()(Indices... is) {\n            size_t shift = multivec_impl::get_shift(B::s, 0, is...);\n            const auto& subshape = multivec_impl::get_subshape<sizeof...(Indices)>(B::s);\n            return {subshape, &B::data[shift]};\n        }\n\n\n        \n        inline void fill(const T& val) {\n            std::fill(raw_data(), raw_data() + B::s.size(), val);\n        };\n\n\n        \n//    protected:\n        inline T* raw_data() {\n            return &B::data[0];\n        }\n\n\n        \n    };\n\n\n    template <class T, size_t NDIMS>\n    struct vec_view_base {\n        inline vec_view_base(const multivec_impl::shape<NDIMS>& s_, T* data_): s(s_), data(data_) {}\n        \n    protected:\n        multivec_impl::shape<NDIMS> s;\n        T* data;\n    };\n\n\n    template <class T, size_t NDIMS>\n    struct vec_base {\n        inline vec_base(multivec_impl::shape<NDIMS>&& s_): s(move(s_)), data(new T[s.size()]) {}\n        \n        \n        inline vec_base(const vec_base& o): s(o.s), data(new T[s.size()]) {\n            memcpy(data.get(), o.data.get(), sizeof(T) * s.size());\n        }\n        \n    protected:\n        multivec_impl::shape<NDIMS> s;\n        unique_ptr<T[]> data;\n    };\n}\n\n\n/*\nTODO\n - do we need vec_view_const?\n - add more features (lambda initialization etc.)\n - properly use const\n - proper tests coverage\n*/\n\n\ntemplate <class T, size_t NDIMS>\nusing vec = multivec_impl::vec_mixin<multivec_impl::vec_base, T, NDIMS>;\n\n\n\n\ntemplate <class T, class... NDIMS>\ninline vec<T, sizeof...(NDIMS)> make_vec(NDIMS... dims) {\n    return {multivec_impl::make_shape(dims...)};\n}\n\n\n\n\n/*\nTODOs:\n primitive root\n discrete log\n\n\n tests!!!\n*/\n\n\nnamespace mod_impl {\n    /// caide keep\n    template <class T>\n    constexpr inline T mod(T MOD) {\n        return MOD;\n    }\n\n\n    /// caide keep\n    template <class T>\n    constexpr inline T mod(T* MOD) {\n        return *MOD;\n    }\n\n\n    /// caide keep\n    template <class T>\n    constexpr inline T max_mod(T MOD) {\n        return MOD - 1;\n    }\n\n\n    /// caide keep\n    template <class T>\n    constexpr inline T max_mod(T*) {\n        return numeric_limits<T>::max() - 1;\n    }\n\n\n    \n    constexpr inline uint64_t combine_max_sum(uint64_t a, uint64_t b) {\n        return a > ~b ? 0 : a + b;\n    }\n\n\n    constexpr inline uint64_t combine_max_mul(uint64_t a, uint64_t b) {\n        return a > numeric_limits<uint64_t>::max() / b ? 0 : a * b;\n    }\n\n\n    /// caide keep\n    template <class T>\n    constexpr inline uint64_t next_divisible(T mod, uint64_t max) {\n        return max % mod == 0 ? max : combine_max_sum(max, mod - max % mod);\n    }\n\n\n    /// caide keep\n    template <class T>\n    constexpr inline uint64_t next_divisible(T*, uint64_t) {\n        return 0;\n    }\n\n\n    //caide keep\n    constexpr int IF_THRESHOLD = 2;\n\n\n    template <class T, T MOD_VALUE, uint64_t MAX,\n            class RET = typename template_util::minimal_uint<max_mod(MOD_VALUE)>::type,\n            ENABLE_IF(MAX <= max_mod(MOD_VALUE) && !is_pointer<T>::value)>\n    inline RET smart_mod(typename template_util::minimal_uint<MAX>::type value) {\n        return value;\n    }\n\n\n    template <class T, T MOD_VALUE, uint64_t MAX,\n            class RET = typename template_util::minimal_uint<max_mod(MOD_VALUE)>::type,\n            ENABLE_IF(max_mod(MOD_VALUE) < MAX && MAX <= IF_THRESHOLD * max_mod(MOD_VALUE) && !is_pointer<T>::value)>\n    inline RET smart_mod(typename template_util::minimal_uint<MAX>::type value) {\n        while (value >= mod(MOD_VALUE)) {\n            value -= mod(MOD_VALUE);\n        }\n        return (RET)value;\n    }\n\n\n    template <class T, T MOD_VALUE, uint64_t MAX,\n             class RET = typename template_util::minimal_uint<max_mod(MOD_VALUE)>::type,\n             ENABLE_IF(IF_THRESHOLD * max_mod(MOD_VALUE) < MAX || is_pointer<T>::value)>\n    inline RET smart_mod(typename template_util::minimal_uint<MAX>::type value) {\n        return (RET)(value % mod(MOD_VALUE));\n    }\n}\n\n\n\n\n#define MAX_MOD mod_impl::max_mod(MOD_VALUE)\n\n\nstruct DenormTag {};\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX = MAX_MOD, ENABLE_IF(MAX_MOD >= 2)>\nstruct ModVal {\n    typedef typename template_util::minimal_uint<MAX>::type storage;\n    storage value;\n\n\n    /// caide keep\n    inline ModVal(): value(0) {\n        assert(MOD >= 2);\n    }\n\n\n    \n    inline ModVal(storage v, DenormTag): value(v) {\n        assert(MOD >= 2);\n        assert(v <= MAX);\n    };\n\n\n    inline operator ModVal<T, MOD_VALUE>() {\n        return {v(), DenormTag()};\n    };\n\n\n    \n    typename template_util::minimal_uint<mod_impl::max_mod(MOD_VALUE)>::type v() const {\n        return mod_impl::smart_mod<T, MOD_VALUE, MAX>(value);\n    }\n};\n\n\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX1, uint64_t MAX2,\n        uint64_t NEW_MAX = mod_impl::combine_max_sum(MAX1, MAX2),\n        ENABLE_IF(NEW_MAX != 0), class Ret = ModVal<T, MOD_VALUE, NEW_MAX>>\ninline Ret operator+(ModVal<T, MOD_VALUE, MAX1> o1, ModVal<T, MOD_VALUE, MAX2> o2) {\n    return {typename Ret::storage(typename Ret::storage() + o1.value + o2.value), DenormTag()};\n}\n\n\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX1, uint64_t MAX2,\n        uint64_t NEW_MAX = mod_impl::combine_max_mul(MAX1, MAX2),\n        ENABLE_IF(NEW_MAX != 0), class Ret = ModVal<T, MOD_VALUE, NEW_MAX>>\ninline Ret operator*(ModVal<T, MOD_VALUE, MAX1> o1, ModVal<T, MOD_VALUE, MAX2> o2) {\n    return {typename Ret::storage(typename Ret::storage(1) * o1.value * o2.value), DenormTag()};\n}\n\n\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX>\ninline ModVal<T, MOD_VALUE>& operator+=(ModVal<T, MOD_VALUE>& lhs, const ModVal<T, MOD_VALUE, MAX>& rhs) {\n    lhs = lhs + rhs;\n    return lhs;\n}\n\n\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX>\ninline ModVal<T, MOD_VALUE>& operator*=(ModVal<T, MOD_VALUE>& lhs, const ModVal<T, MOD_VALUE, MAX>& rhs) {\n    lhs = lhs * rhs;\n    return lhs;\n}\n\n\n\n\ntemplate <class T, T MOD_VALUE, class MOD_TYPE>\nstruct ModCompanion {\n    typedef MOD_TYPE mod_type;\n    typedef ModVal<mod_type, MOD_VALUE> type;\n    \n\n\n    template <uint64_t C>\n    inline static constexpr ModVal<mod_type, MOD_VALUE, C> c() {\n        return {C, DenormTag()};\n    };\n\n\n    template <uint64_t MAX = numeric_limits<uint64_t>::max()>\n    inline static ModVal<mod_type, MOD_VALUE, MAX> wrap(uint64_t x) {\n        assert(x <= MAX);\n        return {typename ModVal<mod_type, MOD_VALUE, MAX>::storage(x), DenormTag()};\n    };\n\n\n    \n};\n\n\n\n\n#undef MAX_MOD\n\n\ntemplate <uint64_t MOD_VALUE>\nstruct Mod : ModCompanion<uint64_t, MOD_VALUE, typename template_util::minimal_uint<MOD_VALUE>::type> {\n    template<uint64_t VAL>\n    static constexpr uint64_t literal_builder() {\n        return VAL;\n    }\n\n\n    template<uint64_t VAL, char DIGIT, char... REST>\n    static constexpr uint64_t literal_builder() {\n        return literal_builder<(10 * VAL + DIGIT - '0') % MOD_VALUE, REST...>();\n    }\n};\n\n\n\n\n#define REGISTER_MOD_LITERAL(mod, suffix) template <char... DIGITS> mod::type operator \"\" _##suffix() {     return mod::c<mod::literal_builder<0, DIGITS...>()>(); }\n\n\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX>\ninline ostream& operator<<(ostream& s, ModVal<T, MOD_VALUE, MAX> val) {\n    s << val.v();\n    return s;\n}\n\n\n\n\ntemplate<class T>\nT next(istream& in) {\n    T ret;\n    in >> ret;\n    return ret;\n}\n\n\n\n\n#define dbg(...) ;\n\n\n\n\n// ^^^^^^^^^^^^^^^^^ Library code end\n\n\nusing md = Mod<1000000007>;\n/// caide keep\nusing mt = md::type;\nREGISTER_MOD_LITERAL(md, mod)\n\n\nconstexpr int MAX_LEN = 700;\n\n\nauto precalc = []() {\n    auto precalc = make_vec<mt>(MAX_LEN, MAX_LEN, 10);\n    precalc(0, 0).fill(1_mod);\n    foran (int, len, 1, MAX_LEN) {\n        forn (int, cnt, len + 1) {\n            forn (int, d, 10) {\n                precalc(len, cnt, d) = md::wrap<10>(d) * precalc(len - 1, cnt, d);\n                if (cnt > 0) {\n                    precalc(len, cnt, d) += md::wrap<10>(10 - d) * precalc(len - 1, cnt - 1, d);\n                }\n            }\n        }\n    }\n    return precalc;\n}();\n\n\nvoid solve(istream& in, ostream& out) {\n    auto x = next<string>(in);\n    int n = x.size();\n    auto din = make_vec<mt>(n + 1, 10);\n    din.fill(0_mod);\n    auto prefixCounts = make_vec<int>(10);\n    prefixCounts.fill(0);\n    forn (int, i, n) {\n        dbg(prefixCounts);\n        int restLen = n - i - 1;\n        forn (int, d, x[i] - '0' + (i == n - 1 ? 1 : 0)) {\n            dbg(i, d);\n            forn (int, c, 10) {\n                forn (int, cnt, restLen + 1) {\n                    din(cnt + prefixCounts(c) + (d >= c ? 1 : 0), c) += precalc(restLen, cnt, c);\n                }\n            }\n        }\n        forn (int, d, x[i] - '0' + 1) {\n            prefixCounts(d)++;\n        }\n    }\n    forn (int, c, 10) {\n        rforn (int, i, n) {\n            din(i, c) += din(i + 1, c);\n        }\n    }\n    auto ans = 0_mod;\n    auto pow10 = 1_mod;\n    foran (int, i, 1, n + 1) {\n        auto sum = 0_mod;\n        foran (int, c, 1, 10) {\n            sum += din(i, c);\n        }\n        ans += sum * pow10;\n        pow10 *= 10_mod;\n    }\n    out << ans << \"\n\";\n}\n\n\n\n\nint main() {\n    solve(cin, cout);\n    return 0;\n}",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "908",
    "index": "H",
    "title": "New Year and Boolean Bridges",
    "statement": "Your friend has a hidden directed graph with $n$ nodes.\n\nLet $f(u, v)$ be true if there is a directed path from node $u$ to node $v$, and false otherwise. For each pair of distinct nodes, $u, v$, you know at least one of the three statements is true:\n\n- $f(u,v)\\ \\mathrm{AND}\\ f(v,u)$\n- $f(u,v)\\ \\mathrm{OR}\\ \\,f(v,u)$\n- $f(u,v)\\times0\\mathbb{R}\\ f(v,u)$\n\nHere AND, OR and XOR mean AND, OR and exclusive OR operations, respectively.\n\nYou are given an $n$ by $n$ matrix saying which one of the three statements holds for each pair of vertices. The entry in the $u$-th row and $v$-th column has a single character.\n\n- If the first statement holds, this is represented by the character 'A'.\n- If the second holds, this is represented by the character 'O'.\n- If the third holds, this is represented by the character 'X'.\n- The diagonal of this matrix will only contain the character '-'.\n\nNote that it is possible that a pair of nodes may satisfy multiple statements, in which case, the character given will represent one of the true statements for that pair. This matrix is also guaranteed to be symmetric.\n\nYou would like to know if there is a directed graph that is consistent with this matrix. If it is impossible, print the integer -1. Otherwise, print the minimum number of edges that could be consistent with this information.",
    "tutorial": "First, let's find connected components using only AND edges. If there are any XOR edges between two nodes in the same component, the answer is -1. Now, we can place all components in a line. However, it may be optimal to merge some components together. It only makes sense to merge components of size 2 or more, of which there are at most $k = n / 2$ of them. We can make a new graph with these $k$ components. Two components have an edge if all of the edges between them are OR edges, otherwise, there is no edge. We want to know what is the minimum number of cliques needed to cover all the nodes in this graph. To solve this, we can precompute which subsets of nodes forms a clique and put this into some array. Then, we can use the fast walsh hadamard transform to multiply this array onto itself until the element $2^{k} - 1$ is nonzero. Naively, this is $O(2^{k} * k^{2})$, but we can save a factor of $k$ by noticing we only need to compute the last element, and we don't need to re-transform our input array at each iteration.",
    "code": "// vvvvvvvvvvvvvvvvv Library code start\n\n\n\n\n#define NDEBUG\nNDEBUG\n\n\n\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cstring>\n#include <cmath>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n#include <memory>\n#include <queue>\n#include <random>\n\n\n\n\n#define forn(t, i, n) for (t i = 0; i < (n); ++i)\n\n\n#define rforn(t, i, n) for (t i = (n) - 1; i >= 0; --i)\n\n\n\n\nusing namespace std;\n\n\n// TC_REMOVE_BEGIN\n/// caide keep\nbool __hack = std::ios::sync_with_stdio(false);\n/// caide keep\nauto __hack1 = cin.tie(nullptr);\n// TC_REMOVE_END\n\n\n\n\ntemplate <class T>\nT gen_pow(T ret, T x, uint64_t pow) {\n    while (pow) {\n        if (pow & 1) {\n            ret *= x;\n        }\n        pow /= 2;\n        if (pow) {\n            x *= x;\n        }\n    }\n    return ret;\n}\n\n\n\n\n// Section with adoption of array and vector algorithms.\n\n\n\n\nnamespace template_util {\n    \n\n\n    constexpr int bytecount(uint64_t x) {\n        return x ? 1 + bytecount(x >> 8) : 0;\n    }\n\n\n    template<int N>\n    struct bytetype {\n        \n    };\n\n\n    \n    /// caide keep\n    template<uint64_t N>\n    struct minimal_uint : bytetype<bytecount(N)> {\n    };\n}\n\n\n\n\ntemplate<class T>\nT next(istream& in) {\n    T ret;\n    in >> ret;\n    return ret;\n}\n\n\ntemplate<class T>\nvector<T> next_vector(istream& in, size_t n) {\n    vector<T> ret(n);\n    for (size_t i = 0; i < n; ++i) {\n        ret[i] = next<T>(in);\n    }\n    return ret;\n}\n\n\n\n\ntemplate <class T>\ninline T set_bit(T mask, int bit) {\n    assert(0 <= bit && bit < numeric_limits<T>::digits);\n    return mask | ((T)(1) << bit);\n}\n\n\n\n\ntemplate <class T>\ninline bool get_bit(T mask, int bit) {\n    assert(0 <= bit && bit < numeric_limits<T>::digits);\n    return mask & ((T)(1) << bit);\n}\n\n\n\n\ninline int bitcnt(unsigned int mask) {\n    return __builtin_popcount(mask);\n}\n\n\n\n\ninline int bitcnt(unsigned long long mask) {\n    return __builtin_popcountll(mask);\n}\n\n\n\n\n// ^^^^^^^^^^^^^^^^^ Library code end\n\n\nvoid solve(istream& in, ostream& out) {\n    int n = next<int>(in);\n    vector<string> g0 = next_vector<string>(in, n);\n    vector<uint64_t> comps;\n    uint64_t col = 0;\n    function<uint64_t(int)> dfs = [&](int i) -> uint64_t {\n        if (get_bit(col, i)) {\n            return 0;\n        }\n        col = set_bit(col, i);\n        uint64_t ret = 1ULL << i;\n        forn (int, j, n) {\n            if (g0[i][j] == 'A' || g0[j][i] == 'A') {\n                ret |= dfs(j);\n            }\n        }\n        return ret;\n    };\n    forn (int, i, n) {\n        uint64_t comp = dfs(i);\n        if (bitcnt(comp) > 1) {\n            comps.push_back(comp);\n        }\n    }\n    vector<uint32_t> g(comps.size());\n    forn (int, i, comps.size()) {\n        uint64_t ns = 0;\n        forn (int, u, n) {\n            if (!get_bit(comps[i], u)) {\n                continue;\n            }\n            forn (int, v, n) {\n                if (g0[u][v] == 'X' || g0[v][u] == 'X') {\n                    ns |= 1ULL << v;\n                }\n            }\n        }\n        forn (int, j, comps.size()) {\n            if ((ns & comps[j]) != 0) {\n                g[i] |= 1 << j;\n            }\n        }\n        if (get_bit(g[i], i)) {\n            out << \"-1\n\";\n            return;\n        }\n    }\n    vector<uint32_t> f(1 << comps.size());\n    rforn (int, i, 1 << comps.size()) {\n        forn (int, u, comps.size()) {\n            if (get_bit(i, u) ? ((g[u] & i) != 0) : f[set_bit(i, u)]) {\n                goto cont;\n            }\n        }\n        f[i] = 1;\n        cont:;\n    }\n    forn (int, u, comps.size()) {\n        forn (int, i, 1 << comps.size()) {\n            if (get_bit(i, u)) {\n                f[i] += f[i ^ (1 << u)];\n            }\n        }\n    }\n    vector<uint64_t> counts(comps.size() + 1);\n    forn (uint32_t, i, 1 << comps.size()) {\n        uint64_t pow = bitcnt(i) % 2 ? -1ULL : 1ULL;\n        uint64_t val = f[i];\n        forn (int, k, comps.size() + 1) {\n            counts[k] += pow;\n            pow *= val;\n        }\n    }\n    int k = 0;\n    while (counts[k] == 0) {\n        k++;\n    }\n    out << n - 1 + k << \"\n\";\n}\n\n\n\n\nint main() {\n    solve(cin, cout);\n    return 0;\n}",
    "tags": [],
    "rating": 3100
  },
  {
    "contest_id": "909",
    "index": "A",
    "title": "Generate Login",
    "statement": "The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.\n\nYou are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).\n\nAs a reminder, a prefix of a string $s$ is its substring which occurs at the beginning of $s$: \"a\", \"ab\", \"abc\" etc. are prefixes of string \"{abcdef}\" but \"b\" and 'bc\" are not. A string $a$ is alphabetically earlier than a string $b$, if $a$ is a prefix of $b$, or $a$ and $b$ coincide up to some position, and then $a$ has a letter that is alphabetically earlier than the corresponding letter in $b$: \"a\" and \"ab\" are alphabetically earlier than \"ac\" but \"b\" and \"ba\" are alphabetically later than \"ac\".",
    "tutorial": "The most straightforward solution is to generate all possible logins (by trying all non-empty prefixes of first and last names and combining them) and find the alphabetically earliest of them. To get a faster solution, several observations are required. First, in the alphabetically earliest login the prefix of the last name is always one letter long; whatever login is generated using two or more letter of the last name, can be shortened further by removing extra letter to get an alphabetically earlier login. Second, the prefix of the first name should not contain any letter greater than or equal to the first letter of the last name, other than the first letter. Thus, a better solution is: iterate over letter of the first name, starting with the second one. Once a letter which is greater than or equal to the first letter of the last name is found, stop, and return all letter until this one plus the first letter of the last name. If such a letter is not found, return the whole first name plus the first letter of the last name.",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "909",
    "index": "B",
    "title": "Segments",
    "statement": "You are given an integer $N$. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and $N$, inclusive; there will be $\\textstyle{\\frac{n(n+1)}{2}}$ of them.\n\nYou want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You \\textbf{can not} move the segments to a different location on the coordinate axis.\n\nFind the minimal number of layers you have to use for the given $N$.",
    "tutorial": "Consider a segment $[i, i + 1]$ of length 1. Clearly, all segments that cover this segment must belong to different layers. To cover it, the left end of the segment must be at one of the points $0, 1, ..., i$ ($i + 1$ options), and the right end - at one of the points $i + 1, i + 2, ..., N$ ($N - i$ options). So the number of segments covering $[i, i + 1]$ is equal to $M_{i} = (i + 1)(N - i)$. The maximum of $M_{i}$ over all $i = 0, ..., N - 1$ gives us a lower bound on the number of layers. Because the problem doesn't require explicit construction, we can make a guess that this bound is exact. $max M_{i}$ can be found in $O(N)$; alternatively, it can be seen that the maximum is reached for $i=\\lfloor{\\frac{N}{2}}\\rfloor$ (for a central segment for odd $N$ or for one of two central segments for even $N$). The answer is $\\left(\\left[{\\frac{N}{2}}\\right]+1\\right)\\cdot\\left[{\\frac{N}{2}}\\right]$. We can also prove this by an explicit construction. Sort all segments in non-decreasing order of their left ends and then in increasing order of their right ends. Try to find a place for each next segment greedily: if $i$ is the left end of current segment, and segment $[i, i + 1]$ is free in some layer, add the current segment to that layer; otherwise, start a new layer with the current segment. and yes, this is our $O(1)$ problem! :-)",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "909",
    "index": "C",
    "title": "Python Indentation",
    "statement": "In Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.\n\nWe will consider an extremely simplified subset of Python with only two types of statements.\n\n\\textbf{Simple statements} are written in a single line, one per line. An example of a simple statement is assignment.\n\n\\textbf{For statements} are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with \"for\" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.\n\nYou are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.",
    "tutorial": "This problem can be solved using dynamic programming. Let's consider all possible programs which end with a certain statement at a certain indent. Dynamic programming state will be an array $dp[i][j]$ which stores the number of such programs ending with statement $i$ at indent $j$. The starting state is a one-dimensional array for $i = 0$: there is exactly one program which consists of the first statement only, and its last statement has indent 0. The recurrent formula can be figured out from the description of the statements. When we add command $i + 1$, its possible indents depend on the possible indents of command $i$ and on the type of command $i$. If command $i$ is a for loop, command $i + 1$ must have indent one greater than the indent of command $i$, so $dp[i + 1][0] = 0$ and $dp[i + 1][j] = dp[i][j - 1]$ for $j > 0$. If command $i$ is a simple statement, command $i + 1$ can belong to the body of any loop before it, and have any indent from 0 to the indent of command $i$. If we denote the indent of command $i$ (simple statement) as $k$, the indent of command $i + 1$ as $j$, we need to sum over all cases where $k  \\ge  j$: $d p[i+1][j]=\\sum_{k=j}^{N-1}d p[i][k]$. The answer to the task is the total number of programs which end with the last command at any indent: $\\textstyle\\sum_{k=0}^{N-1}d p[N-1][k]$. The complexity of this solution is $O(N^{2})$.",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "909",
    "index": "D",
    "title": "Colorful Points",
    "statement": "You are given a set of points on a straight line. Each point has a color assigned to it. For point $a$, its neighbors are the points which don't have any other points between them and $a$. Each point has at most two neighbors - one from the left and one from the right.\n\nYou perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.\n\nHow many operations will you need to perform until the next operation does not have any points to delete?",
    "tutorial": "We can simulate the process described in the problem step by step, but this is too slow - a straightforward simulation (iterate over all points when deciding which ones to delete) has an $O(N^{2})$ complexity and takes too long. A solution with better complexity is required. Let's consider continuous groups of points of same color. Any points inside a group are safe during the operation; only points at the border of a group are deleted (except for the leftmost point of the leftmost group and the rightmost point of the rightmost group, if these groups have more than one point). So, if current group sizes are, from left to right, $N_{1}, N_{2}, ..., N_{G - 1}, N_{G}$, group sizes after performing the first operation are $N_{1} - 1, N_{2} - 2, ..., N_{G - 1} - 2, N_{G} - 1$, after the second operation - $N_{1} - 2, N_{2} - 4, ..., N_{G - 1} - 4, N_{G} - 2$ and so on. This process continues until at least one of the groups disappears completely, at which point its adjacent groups may get merged if they are of the same color. This way, multiple operations can be simulated at once: Find the number of operations that are required for at least one group to disappear. Update group sizes after this number of operations. Remove empty groups. Merge adjacent groups of the same color. One update done this way requires $O(G)$ time. During such an update at least one point from each group is deleted, so at least $O(G)$ points are removed. If $N$ is the initial number of points, we can remove at most $N$ points in total. Therefore, running time of the algorithm is $O(N)$.",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "909",
    "index": "E",
    "title": "Coprocessor",
    "statement": "You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depends on have already completed.\n\nSome of the tasks in the graph can only be executed on a coprocessor, and the rest can only be executed on the main processor. In one coprocessor call you can send it a set of tasks which can only be executed on it. For each task of the set, all tasks on which it depends must be either already completed or be included in the set. The main processor starts the program execution and gets the results of tasks executed on the coprocessor automatically.\n\nFind the minimal number of coprocessor calls which are necessary to execute the given program.",
    "tutorial": "We want to minimize the number of communications between main processor and the coprocessor. Thus, we need to always act greedily: while there are tasks that can be executed on the main processor right away, execute them; then switch to the coprocessor and execute all tasks that can be executed there; then switch back to the main processor and so on. This can be done using breadth-first search. To run reasonably fast, this solution has to be implemented carefully: instead of searching for available tasks at each step, we want to maintain two queues of available tasks (for main processor and coprocessor) and add a task to a corresponding queue once all tasks it depends on has been executed. Alternatively, we can define $T_{i}$ as the lowest number of coprocessor calls required to execute $i$-th task, and derive a recurrent formula for $T_{i}$. If $u$ is a task and $v_{1}, ..., v_{k}$ are its dependencies, then clearly for each $i$ $T_{u}  \\ge  T_{vi}$ because $u$ must be executed after $v_{i}$. Moreover, if $v_{i}$ is executed on the main processor and $u$ - on the coprocessor, then executing $u$ will require an additional coprocessor call. Therefore, $T_{u} = max_{i}(T_{vi} + s_{i})$, where $s_{i} = 1$ if $u$ is executed on the coprocessor and $v_{i}$ - on the main processor; otherwise, $s_{i} = 0$. Now all $T_{i}$ can be calculated by recursive traversal of the dependency graph (or traversing the tasks in topological order). The answer to the problem is $max T_{i}$.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "909",
    "index": "F",
    "title": "AND-permutations",
    "statement": "Given an integer $N$, find two permutations:\n\n- Permutation $p$ of numbers from 1 to $N$ such that $p_{i} ≠ i$ and $p_{i} & i = 0$ for all $i = 1, 2, ..., N$.\n- Permutation $q$ of numbers from 1 to $N$ such that $q_{i} ≠ i$ and $q_{i} & i ≠ 0$ for all $i = 1, 2, ..., N$.\n\n$&$ is the bitwise AND operation.",
    "tutorial": "If $N$ is odd, the answer is NO. Indeed, any number in odd-numbered position $i$ $p_{i}$ must be even, otherwise the last bit of $p_{i}&i$ is 1. For odd $N$ there are less even numbers than odd-numbered positions, so at least one of the positions will hold an odd number, thus it's impossible to construct a required permutation. If $N$ is even, the required permutation exists. To build it, first observe that $(2^{k} - i)&(2^{k} + i - 1) = 0$. For example, for $k = 5$: $100000 = 2^{5}$ $011111 = 2^{5} - 1$ $100001 = 2^{5} + 1$ $011110 = 2^{5} - 2$ and so on. We can use this fact to always match $2^{k} - i$ and $2^{k} + i - 1$ with each other, that is, set $p_{2^{k} - i} = 2^{k} + i - 1$ and $p_{2^{k} + i - 1} = 2^{k} - i$. The full procedure for constructing the required permutation is as follows. For a given even $N$, find the maximum power of two that is less than or equal to $N$ $2^{k}$. Match pairs of numbers $2^{k} - i$ and $2^{k} + i - 1$ for each $i = 1..N - 2^{k} + 1$. If we are not done yet, numbers from $1$ to $2^{k} - (N - 2^{k} + 1) - 1 = 2^{k + 1} - N - 2$ are still unmatched. Repeat the process for $N' = 2^{k + 1} - N - 2$. For example, for $N = 18$ on the first step we set $2^{k} = 16$ and match numbers 15-16, 14-17 and 13-18. On the second step unmatched numbers are from 1 to 12, so we set $2^{k} = 8$ and match numbers 7-8, 6-9, 5-10, 4-11 and 3-12. On the third and the last step the remaining unmatched numbers are 1 and 2, so we set $2^{k} = 2$ and match numbers 1 and 2 with each other. After this no unmatched numbers are left, and we are done. We can do a simple case analysis for $N = 1..7$ manually, noticing that the answer is NO for $N = 1..5$, a possible answer for $N = 6$ is \\textbf{3 6 2 5 1 4} as given in problem statement, and a possible answer for $N = 7$ is \\textbf{7 3 6 5 1 2 4}. If $N$ is a power of two, then it is represented in binary as $10..0$. We must have $q_{N}  \\neq  N$, therefore $q_{N} < N$, so the binary representation of $q_{N}$ is shorter than that of $N$. It follows that $q_{N}&N = 0$, so the answer is NO in this case. Finally, if $N > 7$ and $N$ is not a power of two, the required permutation always exists, and can be built in the following way. Split all numbers from 1 to $N$ into the following groups ($k$ is the largest power of two which is still less than $N$): 1..7 8..15 16..31 \\ldots $2^{k - 1}..2^{k} - 1$ $2^{k}..N$ For the first group use the permutation that we found manually. For each of the remaining groups, use any permutation of numbers in this group (for example, a cyclic permutation). The numbers in each group have leading non-zero bit at the same position (which corresponds to the power of two at the beginning of the group), so it is guaranteed that $q_{i}&i$ contains a non-zero bit at least in that position.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2500
  },
  {
    "contest_id": "911",
    "index": "A",
    "title": "Nearest Minimums",
    "statement": "You are given an array of $n$ integer numbers $a_{0}, a_{1}, ..., a_{n - 1}$. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.",
    "tutorial": "This task can be done by one array traversal. Maintain $cur$ - current minimum value, $pos$ - position of the last occurrence of $cur$, $ans$ - current minumum distance between two occurrences of $cur$. Now for each $i$ if $a_{i} < cur$ then do $cur: = a_{i}$, $pos: = i$, $ans: =  \\infty $. For $a_{i} = cur$ do $ans = min(ans, i - pos)$, $pos: = i$. In the end $cur$ will be the global minimum of array and $ans$ will keep the closest its occurrences. Overall complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "911",
    "index": "B",
    "title": "Two Cakes",
    "statement": "It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into $a$ pieces, and the second one — into $b$ pieces.\n\nIvan knows that there will be $n$ people at the celebration (including himself), so Ivan has set $n$ plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met:\n\n- Each piece of each cake is put on some plate;\n- Each plate contains at least one piece of cake;\n- No plate contains pieces of both cakes.\n\nTo make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number $x$ such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least $x$ pieces of cake.\n\nHelp Ivan to calculate this number $x$!",
    "tutorial": "Let's fix $x$ - number of plates to have pieces of the first cake. $n - x$ plates left for the other cake. Obviously, the most optimal way to distribute $a$ pieces to $x$ plates will lead to the minimum of $\\left\\lfloor{\\frac{\\Omega}{x}}\\right\\rfloor$ pieces on a plate. Now try every possible $x$ and take maximum of $m i n(\\lfloor{\\frac{a}{x}}\\rfloor,\\lfloor{\\frac{b}{n-x}}\\rfloor)$. Overall complexity: $O(n)$.",
    "tags": [
      "binary search",
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "911",
    "index": "C",
    "title": "Three Garlands",
    "statement": "Mishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.\n\nWhen a garland is switched on, it periodically changes its state — sometimes it is lit, sometimes not. Formally, if $i$-th garland is switched on during $x$-th second, then it is lit only during seconds $x$, $x + k_{i}$, $x + 2k_{i}$, $x + 3k_{i}$ and so on.\n\nMishka wants to switch on the garlands in such a way that during each second after switching the garlands on there would be at least one lit garland. Formally, Mishka wants to choose three integers $x_{1}$, $x_{2}$ and $x_{3}$ (not necessarily distinct) so that he will switch on the first garland during $x_{1}$-th second, the second one — during $x_{2}$-th second, and the third one — during $x_{3}$-th second, respectively, and during each second starting from $max(x_{1}, x_{2}, x_{3})$ at least one garland will be lit.\n\nHelp Mishka by telling him if it is possible to do this!",
    "tutorial": "There are pretty few cases to have YES: One of $k_{i}$ is equal to $1$; At least two of $k_{i}$ are equal to $2$; All $k_{i}$ equal $3$; $k = {2, 4, 4}$. It's easy to notice that having minimum of $k_{i}$ equal to $3$ produce the only case, greater numbers will always miss some seconds. Let's consider minimum of $2$, let it cover all odd seconds. Now you should cover all even seconds and $2$ and $4, 4$ are the only possible solutions. Overall complexity: $O(1)$.",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1400
  },
  {
    "contest_id": "911",
    "index": "D",
    "title": "Inversion Counting",
    "statement": "A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. An inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i > j$ and $a_{i} < a_{j}$. For example, a permutation $[4, 1, 3, 2]$ contains $4$ inversions: $(2, 1)$, $(3, 1)$, $(4, 1)$, $(4, 3)$.\n\nYou are given a permutation $a$ of size $n$ and $m$ queries to it. Each query is represented by two indices $l$ and $r$ denoting that you have to reverse the segment $[l, r]$ of the permutation. For example, if $a = [1, 2, 3, 4]$ and a query $l = 2$, $r = 4$ is applied, then the resulting permutation is $[1, 4, 3, 2]$.\n\nAfter each query you have to determine whether the number of inversions is odd or even.",
    "tutorial": "Permutaion with one swap is called transposition. Any permutation can be expressed as the composition (product) of transpositions. Simpler, you can get any permutation from any other one of the same length by doing some number of swaps. The sign of the permutation is the number of transpositions needed to get it from the identity permutation. Luckily (not really, this is pure math, check out all proofs at wiki, e.g) the sign can also tell us the parity of inversion count. Now you can start with computing parity of inversion count of the original permutation (naively, check all pairs of indices). Finally you can decompose queries into swaps, any method will be ok. Like, you can swap $a_{l}$ and $a_{r}$, then $a_{l + 1}$ and $a_{r - 1}$ and so on (this is $\\frac{|-I+1}{2}]$ swaps). Then parity of inversion count of the resulting permutation will change if you applied odd number of swaps. Overall complexity: $O(n^{2} + m)$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "911",
    "index": "E",
    "title": "Stack Sorting",
    "statement": "Let's suppose you have an array $a$, a stack $s$ (initially empty) and an array $b$ (also initially empty).\n\nYou may perform the following operations until both $a$ and $s$ are empty:\n\n- Take the first element of $a$, push it into $s$ and remove it from $a$ (if $a$ is not empty);\n- Take the top element from $s$, append it to the end of array $b$ and remove it from $s$ (if $s$ is not empty).\n\nYou can perform these operations in arbitrary order.\n\nIf there exists a way to perform the operations such that array $b$ is sorted in non-descending order in the end, then array $a$ is called stack-sortable.\n\nFor example, $[3, 1, 2]$ is stack-sortable, because $b$ will be sorted if we perform the following operations:\n\n- Remove $3$ from $a$ and push it into $s$;\n- Remove $1$ from $a$ and push it into $s$;\n- Remove $1$ from $s$ and append it to the end of $b$;\n- Remove $2$ from $a$ and push it into $s$;\n- Remove $2$ from $s$ and append it to the end of $b$;\n- Remove $3$ from $s$ and append it to the end of $b$.\n\nAfter all these operations $b = [1, 2, 3]$, so $[3, 1, 2]$ is stack-sortable. $[2, 3, 1]$ is not stack-sortable.\n\nYou are given $k$ first elements of some permutation $p$ of size $n$ (recall that a permutation of size $n$ is an array of size $n$ where each integer from $1$ to $n$ occurs exactly once). You have to restore the remaining $n - k$ elements of this permutation so it is stack-sortable. If there are multiple answers, choose the answer such that $p$ is lexicographically maximal (an array $q$ is lexicographically greater than an array $p$ iff there exists some integer $k$ such that for every $i < k$ $q_{i} = p_{i}$, and $q_{k} > p_{k}$). \\textbf{You may not swap or change any of first $k$ elements of the permutation}.\n\nPrint the lexicographically maximal permutation $p$ you can obtain.\n\nIf there exists no answer then output -1.",
    "tutorial": "Let's denote $A(l, r)$ as some stack-sortable array which contains all integers from $l$ to $r$ (inclusive). We can see that if the first element of $A(l, r)$ is $x$, then $A(l, r) = [x] + A(l, x - 1) + A(x + 1, r)$, where by $+$ we mean concatenation of arrays. It's easy to prove this fact: if the first element is $x$, then we have to store it in the stack until we have processed all elements less than $x$, so in $A(l, r)$ no element that is greater than $x$ can precede any element less than $x$. This way we can represent the prefix we are given. For example, if $n = 7$, $k = 3$ and prefix is $[6, 3, 4]$, then we can rewrite the permutation we have to obtain as: $A(1, 7) = [6] + A(1, 5) + A(7, 7) = [6] + [3] + A(1, 2) + A(4, 5) + A(7, 7) = [6] + [3] + [1] + A(2, 2) + A(4, 5) + A(7, 7)$. So the unknown suffix is a contatenation of some stack-sortable arrays. It's easy to see that if an array is sorted in non-increasing order, then it is stack-sortable. So we can replace each block $A(x, y)$ with an array $[y, y - 1, y - 2, ..., x]$. If during rewriting the given prefix we obtain some impossible situation (for example, when $n = 7$ and given prefix is $[6, 7]$, we have $[6] + A(1, 5) + A(7, 7)$ and $7$ can't be the beginning of $A(1, 5)$), then answer is $- 1$.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "911",
    "index": "F",
    "title": "Tree Destruction",
    "statement": "You are given an unweighted tree with $n$ vertices. Then $n - 1$ following operations are applied to the tree. A single operation consists of the following steps:\n\n- choose two leaves;\n- add the length of the simple path between them to the answer;\n- remove one of the chosen leaves from the tree.\n\nInitial answer (before applying operations) is $0$. Obviously after $n - 1$ such operations the tree will consist of a single vertex.\n\nCalculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer!",
    "tutorial": "The solution is to choose some diameter of given tree, then delete all the leaves which don't belong to diameter (iteratively), and then delete the diameter. I.e. while tree includes vertices aside from the ones forming diameter we choose some leaf, increase answer by the length of the path between this leaf and farthest endpoint of the diameter (from this leaf) and delete this leaf. Then while tree consists of more than one vertex we choose two endpoints of diameter, increase answer by the length of the path between it and delete any of them. At first we need to prove that we can choose any diameter. It can be proved by next fact: we can find the diameter by two graph traversals (DFS/BFS) (we need to find farthest vertex and then again find farthest vertex from found farthest vertex, given path is a diameter of the tree). It means that for each vertex that doesn't belongs to the diameter we will add maximal possible path length by the algorithm described above. And finally obviously that at some moment we need to delete the diameter and there is no way to do this better than we do it in described solution.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "911",
    "index": "G",
    "title": "Mass Change Queries",
    "statement": "You are given an array $a$ consisting of $n$ integers. You have to process $q$ queries to this array; each query is given as four numbers $l$, $r$, $x$ and $y$, denoting that for every $i$ such that $l ≤ i ≤ r$ and $a_{i} = x$ you have to set $a_{i}$ equal to $y$.\n\nPrint the array after all queries are processed.",
    "tutorial": "We can represent a query as a function $f$: $f(i) = i$ if $i  \\neq  x$, $f(x) = y$. If we want to apply two functions, then we can calculate a composition of these functions in time $O(max a_{i})$; in this problem $max a_{i}$ is $100$. So we can do the following: Use scanline technique. Build a segment tree over queries where we store a composition of functions on segment in each vertex. Initially all transformations are $f(i) = i$. When a segment where we apply a query begins, we update the segment tree: we change the transformations on this query's index to the following: $f(i) = i$ if $i  \\neq  x$, $f(x) = y$. When a segment ends, we revert the transformation on this index to $f(i) = i$. The trick is that the composition of all current transformations is stored in the root of the segment tree, so we can easily calculate the result of transformation.",
    "tags": [
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "912",
    "index": "A",
    "title": "Tricky Alchemy",
    "statement": "During the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already $2018$, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.\n\nGrisha needs to obtain some yellow, green and blue balls. It's known that to produce a \\textbf{yellow} ball one needs two yellow crystals, \\textbf{green} — one yellow and one blue, and for a \\textbf{blue} ball, three blue crystals are enough.\n\nRight now there are $A$ yellow and $B$ blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.",
    "tutorial": "Note that the crystals of each color are bought independently. One needs $2 \\cdot x + y$ yellow and $3 \\cdot z + y$ blue crystals. The answer therefore is $max(0, 2 \\cdot x + y - A) + max(0, 3 \\cdot z + y - B)$.",
    "code": "a, b = map(int, input().split())\nx, y, z = map(int, input().split())\n \nyellow = 2 * x + y\nblue = y + 3 * z\nans = max(0, yellow - a) + max(0, blue - b)\n \nprint(ans)",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "912",
    "index": "B",
    "title": "New Year's Eve",
    "statement": "Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains $n$ sweet candies from the good ol' bakery, each labeled from $1$ to $n$ corresponding to its tastiness. No two candies have the same tastiness.\n\nThe choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest ones — but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!\n\nA xor-sum of a sequence of integers $a_{1}, a_{2}, ..., a_{m}$ is defined as the bitwise XOR of all its elements: $a_{1}\\oplus a_{2}\\oplus\\ldots\\leftrightarrow a_{m}$, here $\\mathbb{C}$ denotes the bitwise XOR operation; more about bitwise XOR can be found here.\n\nDed Moroz warned Grisha he has more houses to visit, so Grisha can take \\textbf{no more than $k$} candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.",
    "tutorial": "If $k = 1$, the answer is $n$. Otherwise, let's take a look at the most significant bit of answer and denote it by $p$ (with the $0$-th bit being the least possible). It must be the same as the most significant bit of $n$. This means the answer cannot exceed $2^{p + 1} - 1$. Consider the numbers $2^{p}$ and $2^{p} - 1$. Obviously, they both do not exceed $n$. At the same time, their xor is $2^{p + 1} - 1$. Hence, the maximum answer can always be obtained if $k > 1$.",
    "code": "import sys\n \n \nn, k = map(int, input().split())\n \nif k == 1:\n    print(n)\n    sys.exit(0)\n \n# Calculate 2^(p+1) - 1 using recursive formula\nans = 1\nwhile ans < n:\n    ans = ans * 2 + 1\n \nprint(ans)",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "912",
    "index": "C",
    "title": "Perun, Ult!",
    "statement": "A lot of students spend their winter holidays productively. Vlad has advanced very well in doing so! For three days already, fueled by salads and tangerines — the leftovers from New Year celebration — he has been calibrating his rating in his favorite MOBA game, playing as a hero named Perun.\n\nPerun has an ultimate ability called \"Thunderwrath\". At the instant of its activation, each enemy on the map ($n$ of them in total) loses $d a m a g e$ health points as a single-time effect. It also has a restriction: it can only activated when the moment of time is an \\textbf{integer}. The initial bounty for killing an enemy is $b o u n t y$. Additionally, it increases by $i n c r e a s e$ each second. Formally, if at some second $t$ the ability is activated and the $i$-th enemy is killed as a result (i.e. his health drops to zero or lower), Vlad earns $b o u n t y+t\\cdot i n c r e a s e$ units of gold.\n\nEvery enemy can receive damage, as well as be healed. There are multiple ways of doing so, but Vlad is not interested in details. For each of $n$ enemies he knows:\n\n- $m a x_{-}h e a l t h_{i}$ — maximum number of health points for the $i$-th enemy;\n- $s t a r t_{-}h e a l t h_{i}$ — initial health of the enemy (on the $0$-th second);\n- $r e g e n_{i}$ — the amount of health the $i$-th enemy can regenerate per second.\n\nThere also $m$ health updates Vlad knows about:\n\n- $t i m e_{j}$ — time when the health was updated;\n- $\\epsilon n e m y_{j}$ — the enemy whose health was updated;\n- $h e a l t h_{j}$ — updated health points for $enemy_{j}$.\n\nObviously, Vlad wants to maximize his profit. If it's necessary, he could even wait for years to activate his ability at the right second. Help him determine the exact second (note that it must be \\textbf{an integer}) from $0$ (inclusively) to $ + ∞$ so that a single activation of the ability would yield Vlad the maximum possible amount of gold, and print this amount.",
    "tutorial": "The statement almost directly states the formula for the answer - it is calculated as $\\operatorname*{max}_{t\\in[0,+\\infty)}f(t)\\cdot(b o u n t y+i n c r e a s e\\cdot t)$, where $f(t)$ is amount of enemies we can kill at $t$-th second. Thus, we need to learn how to calculate $f(t)$ and find such values of $t$ that are potential candidates for the point the maximum is achieved at. First, let's consider the case we have no enemies with maximum health exceeding $d a m a g e$. Additionally, let $i n c r e a s e>0$. So, how we can calculate $f(t)$? Let's model the process. There are three kinds of events that affect its value: Some enemy has his health updated, it is now less than or equal to $d a m a g e$, thus we can kill the enemy; Some enemy has his health updated, it is now greater than $d a m a g e$, thus we can't kill the enemy; The enemy has regenerated enough health to become invincible again. One can observe that the optimal answer is reached at the second exactly preceeding the events of the second and the third kind. Indeed, otherwise we can move on to the next second: the bounty is increased and $f(t)$ doesn't decrease, thus providing us with a better answer. What remains for us is to calculate the time when the aforementioned events occur to run scanline. The first two kinds correspond directly to the updates (and initial values - we can treat them as updates occuring at zeroth second). Let's calculate when the events of third kind would occur. Let the second $t$ be the moment when one of the enemies' health became equal to $h$. Let $r$ be the regeneration rate of the enemy. At the second $t+\\lfloor{\\frac{d a m a g e-h}{r}}\\rfloor+1$ he will regenerate enough health to become invincible again. One also needs take care of the case when $r = 0$: if there are no health updates after the enemy became killable, one can kill him at any moment and earn infinitely large amount of money. Note that one should need when did the last event of the first kind happen as updates cancel the potentially planned events of the third kind. Now, consider the case when some enemy has maximum health less than or equal to $d a m a g e$. In that case, there is always an enemy to kill, and, since the bounty increases over time, the answer can be infinitely large. Finally, if $i n c r e a s e=0$, the bounty stays constant and we cannot obtain the infinitely large answer. Since the bounty is constant, we are to find the maximum value of $f(t)$ and multiply it by bounty. This is a simple task and is left as an excersise :) Time complexity - $O((n+m)\\cdot\\log(n+m))$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <unordered_set>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <random>\n#include <set>\n#include <cassert>\n#include <functional>\n#include <queue>\n#include <numeric>\n#include <bitset>\n \nusing namespace std;\n \nconst int N = 100005, M = 350;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nvector<pii> events[N];\n \nint maxhp[N], regen[N];\n \nmap<ll, int> add;\nmap<ll, int> erase;\n \nvoid solve() {\n\tint n = read(), m = read();\n\tint amount = read(), bonus = read();\n\tint damage = read();\n \n\tforn(i, n) {\n\t\tmaxhp[i] = read();\n\t\tint base_hp = read();\n\t\tregen[i] = read();\n\t\tevents[i].push_back(mp(0, base_hp));\n\t}\n \n\tforn(i, m) {\n\t\tint time = read(), j = read(), hp = read();\n\t\tj--;\n\t\tevents[j].push_back(mp(time, hp));\n\t}\n\t\n\tforn(i, n)\n\t    sort(all(events[i]));\n \n\tif (bonus > 0) \n\t\tforn(i, n) \n\t\t\tif (maxhp[i] <= damage || (regen[i] == 0 && events[i].back().second <= damage)) {\n\t\t\t\tputs(\"-1\");\n\t\t\t\treturn;\n\t\t\t}\n \n\tforn(i, n) {\n        auto &v = events[i];\n\t\tforn(j, v.size()) {\n\t\t\tpii e = v[j];\n \n\t\t\tif (e.second > damage) continue;\n \n\t\t\tadd[e.first]++;\n \n\t\t\tpii q;\n\t\t\tif (j < v.size() - 1)\n\t\t\t\tq = v[j + 1];\n\t\t\telse\n\t\t\t\tq = mp(2e9, 0);\n \n\t\t\tll delta_t = min(q.first - e.first - 1, regen[i] == 0 ? (int)2e9 : (min(damage, maxhp[i]) - e.second) / regen[i]);\n\t\t\terase[e.first + delta_t]++;\n\t\t}\n\t}\n \n\tint alive = 0;\n\tset<ll> timeline;\n\tfor (auto v : add) timeline.insert(v.first);\n\tfor (auto v : erase) timeline.insert(v.first);\n \n\tll ans = 0;\n \n\tfor (auto v : timeline) {\n\t\talive += add[v];\n\t\tans = max(ans, alive * (amount + bonus * 1LL * v));\n\t\talive -= erase[v];\n\t}\n \n\tprintf(\"%lld\\n\", ans);\n}\n \nsigned main() {\n\tint t = 1;\n \n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "912",
    "index": "D",
    "title": "Fishes",
    "statement": "While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size $n × m$, divided into cells of size $1 × 1$, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).\n\nThe gift bundle also includes a square scoop of size $r × r$, designed for fishing. If the lower-left corner of the scoop-net is located at cell $(x, y)$, all fishes inside the square $(x, y)...(x + r - 1, y + r - 1)$ get caught. Note that the scoop-net should lie completely inside the pond when used.\n\nUnfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release $k$ fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put $k$ fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among $(n - r + 1)·(m - r + 1)$ possible positions, the average number of caught fishes is as high as possible.",
    "tutorial": "Let's solve a simplified problem first. Assume we know all fishes' positions $(x_{i}, y_{i})$ ($1$-indexed). Denote as $g(x, y)$ the amount of fish that is inside a scoop with lower-left angle located at $(x, y)$. Then the expected value is equal to: ${\\bf E}={\\frac{1}{(n-r+1)\\cdot(m-r+1)}}\\cdot\\sum_{x=1}^{n-r+1\\cdot m\\sum_{y=1}^{n-r+1}g(x,y)}$ It's quite obvious that straightforward computation will result into $O(n \\cdot m)$ time. However, we can invert the problem and calculate for each fish $f(x_{i}, y_{i})$ - how many scoops it is covered by. $f$ is given by the following formula: $f(x,y)=(\\operatorname*{min}(n+1,x+r)-\\operatorname*{max}(x,r))\\cdot(\\operatorname*{min}(m+1,y+r)-\\operatorname*{max}(y,r))$ Let's get back to $\\mathbf{E}$ and transform it into: $\\mathrm{E}={\\frac{1}{(n-r+1)\\cdot(m-r+1)}}\\cdot\\sum_{i=1}^{k}f(x_{i},y_{i})$ In other words, in order to maximize the expected value we have to choose $k$ best values among $n \\cdot m$ possibilities. From now on there are several approaches. Solution I.Imagine we're considering $f(x_{0}, y)$, i.e. with a fixed coordinate $x_{0}$. Note that in this case $f$ is $y$-convex, i.e. it's non-decreasing until some point, and after - non-increasing. Moreover, it always reaches its maximum at $y=\\lfloor{\\frac{m+1}{2}}\\rfloor$. Denote the points to the left of this one $D$, and to the right (inclusive) - $I$. The rest of the solution looks as follows: initially we put $2 \\cdot n$ points into the set, two per each $x$-coordinate, one for $D$ and one for $I$. On each step we take the point with maximum value of $f$ and replace it with its left or right neighbour (depending on which part it was from: $D$ means that the substitute will be to the left, $I$ - to the right). Complexity: $O((n+k)\\log n)$. Imagine we're considering $f(x_{0}, y)$, i.e. with a fixed coordinate $x_{0}$. Note that in this case $f$ is $y$-convex, i.e. it's non-decreasing until some point, and after - non-increasing. Moreover, it always reaches its maximum at $y=\\lfloor{\\frac{m+1}{2}}\\rfloor$. Denote the points to the left of this one $D$, and to the right (inclusive) - $I$. The rest of the solution looks as follows: initially we put $2 \\cdot n$ points into the set, two per each $x$-coordinate, one for $D$ and one for $I$. On each step we take the point with maximum value of $f$ and replace it with its left or right neighbour (depending on which part it was from: $D$ means that the substitute will be to the left, $I$ - to the right). Complexity: $O((n+k)\\log n)$. Solution II.Let's enhance the contemplations from the previous paragraph. Notice that $f$ is convex by both values. Then we can take $(\\lfloor{\\frac{n+1}{2}}\\rfloor,\\lfloor{\\frac{m+1}{2}}\\rfloor$) as the starting point and launch a breadth-first search with a priority queue, erasing the most significant point according to $f$ from the queue and checking all of its yet unvisited neighbours in a $4$-connected area. Complexity: $O(k\\log k)$ with a greater constant compared with solution one. Let's enhance the contemplations from the previous paragraph. Notice that $f$ is convex by both values. Then we can take $(\\lfloor{\\frac{n+1}{2}}\\rfloor,\\lfloor{\\frac{m+1}{2}}\\rfloor$) as the starting point and launch a breadth-first search with a priority queue, erasing the most significant point according to $f$ from the queue and checking all of its yet unvisited neighbours in a $4$-connected area. Complexity: $O(k\\log k)$ with a greater constant compared with solution one.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <random>\n#include <set>\n#include <cassert>\n#include <functional>\n#include <queue>\n#include <numeric>\n#include <bitset>\n \nusing namespace std;\n \nconst int N = 100005, M = 350;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nint n, m, r, k;\n \nll get(int x, int y) {\n\treturn (min(n + 1, x + r) - max(x, r)) * 1LL * (min(m + 1, y + r) - max(y, r));\n}\n \nbool ok(int x, int y) {\n\treturn min(x, y) > 0 && x <= n && y <= m;\n}\n \nstruct cmp {\n\tbool operator()(const pii &a, const pii &b) {\n\t\tll f_a = get(a.first, a.second);\n\t\tll f_b = get(b.first, b.second);\n\t\treturn f_a > f_b || (f_a == f_b && a > b);\n\t}\n};\n \nset<pii, cmp> s;\n \nset<int> used[N];\nint dx[4] = { -1, 0, 0, 1 };\nint dy[4] = { 0, -1, 1, 0 };\n \ndouble get() {\n\ts.insert(mp((n + 1) / 2, (m + 1) / 2));\n\tused[(n + 1) / 2].insert((m + 1) / 2);\n \n\tll total = 0;\n\tforn(i, k) {\n\t\tauto e = *s.begin();\n\t\ts.erase(s.begin());\n \n\t\tint x = e.first, y = e.second;\n\t\ttotal += get(x, y);\n \n\t\tforn(j, 4) {\n\t\t\tint _x = x + dx[j], _y = y + dy[j];\n\t\t\tif (!ok(_x, _y) || used[_x].count(_y)) continue;\n \n\t\t\ts.insert(mp(_x, _y));\n\t\t\tused[_x].insert(_y);\n\t\t}\n\t}\n \n\treturn (double)total / ((n - r + 1) * 1LL * (m - r + 1));\n}\n \nvoid solve() {\n\tn = read(), m = read(), r = read(), k = read();\n\tif (n > m) swap(n, m);\n \n\tif (n == 1 && m == 1)\n\t\tprintf(\"%.10f\\n\", 1.0);\n\telse\n\t\tprintf(\"%.10f\\n\", get());\n}\n \nsigned main() {\n\tint t = 1;\n \n\twhile (t--)\n\t{\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Elapsed Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "data structures",
      "graphs",
      "greedy",
      "probabilities",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "912",
    "index": "E",
    "title": "Prime Gift",
    "statement": "Opposite to Grisha's nice behavior, Oleg, though he has an entire year at his disposal, didn't manage to learn how to solve number theory problems in the past year. That's why instead of Ded Moroz he was visited by his teammate Andrew, who solemnly presented him with a set of $n$ \\textbf{distinct prime} numbers alongside with a simple task: Oleg is to find the $k$-th smallest integer, such that \\textbf{all} its prime divisors are in this set.",
    "tutorial": "The initial idea that emerges in such kind of problems is to use binary search to determine the $k$-th element. Still we have to somehow answer the following query: \"how many elements no greater than $x$ satisfy the conditions?\" It's easy to see that all such numbers can be represented as $p_{1}^{a1} \\cdot ... \\cdot p_{n}^{an}$. Denote $D(G)$ as a set of numbers not exceeding $10^{18}$ such that all their prime divisors lie inside $G$. Let $N$ be our initial set. Sadly we cannot just generate $D(N)$ since its size might be of the order of $8 \\cdot 10^{8}$. Actually, the goal is to invent a way to obtain information about all elements without having to generate them explicitly. Imagine we split $N$ into two such sets $A$ and $B$ that $A\\cup B=N$ and $A\\cap B=\\emptyset$. According to the fact that each element of $D(N)$ can be represented as product of some element of $D(A)$ and some element of $D(B)$, we can explicitly generate $D(A)$ and $D(B)$, then sort them and find out how many pairwise products do not exceed $x$ in $O(|D(A)| + |D(B)|)$ using two pointers approach. This gives $O(\\log10^{18}\\cdot(1D(A)|+|D(B)|))$ in total. The main part is to find the optimal partition. The first thought is to send the first $\\frac{n t}{2}$ elements to $A$ and the rest to $B$. However, this is not enough; in this case the approximate size of $D(A)$ might reach $7 \\cdot 10^{6}$ which is way too much to pass. To speed it up we can, for example, comprise $A$ of elements with even indexes (i.e $p_{0}, p_{2}, ...$) so that sizes of both $D(A)$ and $D(B)$ do not exceed $10^{6}$ and the solution runs swiftly.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <unordered_set>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <random>\n#include <set>\n#include <cassert>\n#include <functional>\n#include <queue>\n#include <numeric>\n#include <bitset>\n \nusing namespace std;\n \nconst int N = 200001, M = 800;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nstruct hamming {\n\tvector<int> p;\n\tint n;\n\tvector<ll> A, B;\n \n\tll U = 1e18;\n \n\tvoid go(ll u, int i, vector<int> &p, vector<ll> &out) {\n\t\tif (i == p.size()) {\n\t\t\tout.push_back(u);\n\t\t\treturn;\n\t\t}\n \n\t\tgo(u, i + 1, p, out);\n\t\tfor (; u <= U / p[i]; )\n\t\t\tgo(u *= p[i], i + 1, p, out);\n\t}\n \n\thamming(vector<int> p) : p(p), n(p.size()) {\n\t\tvector<int> lp, rp;\n\t\tfor (int i = 0; i < n; i += 2)\n\t\t\tlp.push_back(p[i]);\n\t\tfor (int i = 1; i < n; i += 2)\n\t\t\trp.push_back(p[i]);\n\t\tgo(1, 0, lp, A);\n\t\tgo(1, 0, rp, B);\n \n\t\tsort(all(A), greater<ll>());\n\t\tsort(all(B));\n\t}\n \n\tll get(ll x) {\n\t\tint j = 0;\n\t\tll ans = 0;\n \n\t\tforn(i, A.size()) {\n\t\t\twhile (j < B.size() && B[j] <= x / A[i]) j++;\n\t\t\tans += j;\n\t\t}\n\t\treturn ans;\n\t}\n \n\tll order(ll k) {\n\t\tassert(k <= get(U));\n \n\t\tll l = 0, r = U;\n\t\twhile (l < r - 1) {\n\t\t\tll m = (l + r) / 2;\n\t\t\tif (get(m) < k)\n\t\t\t\tl = m;\n\t\t\telse\n\t\t\t\tr = m;\n\t\t}\n \n\t\treturn r;\n\t}\n};\n \nvoid solve() {\n\tint n = read();\n\tvector<int> vals(n);\n\tfor (auto &v : vals) v = read();\n \n\tauto T = hamming(vals);\n \n\tprintf(\"%lld\\n\", T.order(read<ll>()));\n\t//printf(\"%lld\\n\", T.get(1e18));\n}\n \nsigned main() {\n\tint t = 1;\n \n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\t//debug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "math",
      "meet-in-the-middle",
      "number theory",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "913",
    "index": "A",
    "title": "Modular Exponentiation",
    "statement": "The following problem is well-known: given integers $n$ and $m$, calculate\n\n\\begin{center}\n$2^{n}\\operatorname{mod}m$,\n\\end{center}\n\nwhere $2^{n} = 2·2·...·2$ ($n$ factors), and $x\\ {\\mathrm{mod}}\\ y$ denotes the remainder of division of $x$ by $y$.\n\nYou are asked to solve the \"reverse\" problem. Given integers $n$ and $m$, calculate\n\n\\begin{center}\n$m{\\bmod{2^{n}}}$.\n\\end{center}",
    "tutorial": "Why is it hard to calculate the answer directly by the formula in the problem statement? The reason is that $2^{n}$ is a very large number, for $n = 10^{8}$ it consists of around 30 million decimal digits. (Anyway, it was actually possible to get the problem accepted directly calculating the result in Python or Java using built-in long arithmetics.) The main thing to notice in this problem: $x\\ {\\mathrm{mod}}\\ y=x$ if $x < y$. Hence, $m{\\mathrm{~mod~}}2^{n}=m$ if $m < 2^{n}$. Since $m  \\le  10^{8}$ by the constraints, for $n  \\ge  27$ the answer is always equal to $m$. If $n < 27$, it's easy to calculate the answer directly.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int n, m;\n  scanf(\"%d %d\", &n, &m);\n  printf(\"%d\\n\", n >= 31 ? m : m % (1 << n));\n  return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "913",
    "index": "B",
    "title": "Christmas Spruce",
    "statement": "Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex $u$ is called a child of vertex $v$ and vertex $v$ is called a parent of vertex $u$ if there exists a directed edge from $v$ to $u$. A vertex is called a leaf if it doesn't have children and has a parent.\n\nLet's call a rooted tree a spruce if its every non-leaf vertex has at least $3$ leaf children. You are given a rooted tree, check whether it's a spruce.\n\nThe definition of a rooted tree can be found here.",
    "tutorial": "Lets calculate amount of children for each vertex. To do that lets increase by $1$ $c[p_{i}]$ for every $p_{i}$. Then iterate over all vertexes. If $i$-th vertex has $0$ children (i.e. $c[i] = 0$), skip this vertex. Else again iterate over all vertexes and calculate number of vertexes $j$ such that $c[j] = 0$ and $p_{j} = i$. If this number is lower than $3$, answer is \"No\". Else answer is \"Yes\".",
    "code": "n = int(input())\np = [int(input()) - 1 for _ in range(n - 1)]\nleafs = list(filter(lambda x: not x in p, range(n)))\nlp = [x for i, x in enumerate(p) if i + 1 in leafs]\nx = min(lp.count(k) for k in p)\nprint(\"Yes\" if x >= 3 else \"No\")",
    "tags": [
      "implementation",
      "trees"
    ],
    "rating": 1200
  },
  {
    "contest_id": "913",
    "index": "C",
    "title": "Party Lemonade",
    "statement": "A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.\n\nYour favorite store sells lemonade in bottles of $n$ different volumes at different costs. A single bottle of type $i$ has volume $2^{i - 1}$ liters and costs $c_{i}$ roubles. The number of bottles of each type in the store can be considered infinite.\n\nYou want to buy at least $L$ liters of lemonade. How many roubles do you have to spend?",
    "tutorial": "Note that if $2 \\cdot a_{i}  \\le  a_{i + 1}$, then it doesn't make sense to buy any bottles of type $i + 1$ - it won't ever be worse to buy two bottles of type $i$ instead. In this case let's assume that we actually have an option to buy a bottle of type $i + 1$ at the cost of $2 \\cdot a_{i}$ and replace $a_{i + 1}$ with $min(a_{i + 1}, 2 \\cdot a_{i})$. Let's do this for all $i$ from 1 to $n - 1$ in increasing order. Now for all $i$ it's true that $2 \\cdot a_{i}  \\ge  a_{i + 1}$. Note that now it doesn't make sense to buy more than one bottle of type $i$ if $i < n$. Indeed, in this case it won't ever be worse to buy a bottle of type $i + 1$ instead of two bottles of type $i$. From now on, we'll only search for options where we buy at most one bottle of every type except the last one. Suppose that we had to buy exactly $L$ liters of lemonade, as opposed to at least $L$. Note that in this case the last $n - 1$ bits of $L$ uniquely determine which bottles of types less than $n$ we have to buy. Indeed, if $L$ is odd, then we have to buy a bottle of type 0, otherwise we can't do that. By the same line of thought, it's easy to see that bit $j$ in the binary representation of $L$ is responsible for whether we should buy a bottle of type $j$. Finally, we have to buy exactly $ \\lfloor  L / 2^{n - 1} \\rfloor $ bottles of type $n$. But what to do with the fact that we're allowed to buy more than $L$ liters? Suppose we buy $M > L$ liters. Consider the highest bit $j$ in which $M$ and $L$ differ. Since $M > L$, the $j$-th bit in $M$ is 1, and the $j$-th bit in $L$ is 0. But then all bits lower than the $j$-th in $M$ are 0 in the optimal answer, since these bits are responsible for the \"extra\" bottles - those for which we spend money for some reason, but without which we would still have $M > L$. Thus, here is the overall solution. Loop over the highest bit $j$ in which $M$ differs from $L$. Form the value of $M$, taking bits higher than the $j$-th from $L$, setting the $j$-th bit in $M$ to 1, and bits lower than the $j$-th to 0. Calculate the amount of money we have to pay to buy exactly $M$ liters of lemonade. Take the minimum over all $j$. The complexity of the solution is $O(n)$ or $O(n^{2})$, depending on the implementation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int n, L;\n  scanf(\"%d %d\", &n, &L);\n  vector<int> c(n);\n  for (int i = 0; i < n; i++) {\n    scanf(\"%d\", &c[i]);\n  }\n  for (int i = 0; i < n - 1; i++) {\n    c[i + 1] = min(c[i + 1], 2 * c[i]);\n  }\n  long long ans = (long long) 4e18;\n  long long sum = 0;\n  for (int i = n - 1; i >= 0; i--) {\n    int need = L / (1 << i);\n    sum += (long long) need * c[i];\n    L -= need << i;\n    ans = min(ans, sum + (L > 0) * c[i]);\n  }\n  cout << ans << endl;\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "913",
    "index": "D",
    "title": "Too Easy Problems",
    "statement": "You are preparing for an exam on scheduling theory. The exam will last for exactly $T$ milliseconds and will consist of $n$ problems. You can either solve problem $i$ in exactly $t_{i}$ milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.\n\nUnfortunately, your teacher considers some of the problems too easy for you. Thus, he assigned an integer $a_{i}$ to every problem $i$ meaning that the problem $i$ can bring you a point to the final score only in case you have solved no more than $a_{i}$ problems overall (including problem $i$).\n\nFormally, suppose you solve problems $p_{1}, p_{2}, ..., p_{k}$ during the exam. Then, your final score $s$ will be equal to the number of values of $j$ between 1 and $k$ such that $k ≤ a_{pj}$.\n\nYou have guessed that the real first problem of the exam is already in front of you. Therefore, you want to choose a set of problems to solve during the exam maximizing your final score in advance. Don't forget that the exam is limited in time, and you must have enough time to solve all chosen problems. If there exist different sets of problems leading to the maximum final score, any of them will do.",
    "tutorial": "The first observation is that if we solve a problem which doesn't bring us any points, we could as well ignore it and that won't make our result worse. Therefore, there exists an answer in which all problems we solve bring us points. Let's consider only such answers from now on. Fix $k$. How to check if we can get exactly $k$ final points? Consider all problems with $a_{i}  \\ge  k$. Obviously, only these problems suit us in this case. If there are less than $k$ such problems, we can't get the final score of $k$. Otherwise, let's choose $k$ problems with the lowest $t_{i}$ from them. If the sum of these $t_{i}$ doesn't exceed $T$, then the final score of $k$ is possible, and impossible otherwise. Now we can loop over the value of $k$ and make the check above for each of them. The complexity of such solution is $ \\Omega (n^{2})$, though. There are at least two ways to optimize this idea: 1) Use binary search on $k$. Indeed, if we can get the final score of $k$, the final score of $k - 1$ is also possible. In this case, the complexity of the solution will be $O(n\\log n)$ or $O(n\\log^{2}n)$, depending on the implementation. 2) Let's slowly decrease $k$ from $n$ to 0 and keep the set of problems with $a_{i}  \\ge  k$ and the smallest $t_{i}$, and the sum of $t_{i}$ in the set. Every time there are more than $k$ problems in the set, remove the problem with the highest $t_{i}$. Find the largest $k$ such that the set contains at least $k$ problems and the sum of their $t_{i}$ doesn't exceed $T$. This $k$ is the answer. The complexity of this solution is $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int n, T;\n  scanf(\"%d %d\", &n, &T);\n  vector< vector< pair<int, int> > > at(n + 1);\n  for (int i = 0; i < n; i++) {\n    int foo, bar;\n    scanf(\"%d %d\", &foo, &bar);\n    at[foo].emplace_back(bar, i);\n  }\n  vector<int> res;\n  set< pair<int, int> > s;\n  int sum = 0;\n  for (int k = n; k > 0; k--) {\n    for (auto &p : at[k]) {\n      sum += p.first;\n      s.emplace(p);\n    }\n    while ((int) s.size() > k) {\n      sum -= (--s.end())->first;\n      s.erase(--s.end());\n    }\n    if ((int) s.size() == k && sum <= T) {\n      for (auto &p : s) {\n        res.push_back(p.second);\n      }\n      break;\n    }\n  }\n  int sz = (int) res.size();\n  printf(\"%d\\n%d\\n\", sz, sz);\n  for (int i = 0; i < sz; i++) {\n    if (i > 0) {\n      putchar(' ');\n    }\n    printf(\"%d\", res[i] + 1);\n  }\n  printf(\"\\n\");\n  return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "913",
    "index": "E",
    "title": "Logical Expression",
    "statement": "You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:\n\n- Operation AND ('&', ASCII code 38)\n- Operation OR ('|', ASCII code 124)\n- Operation NOT ('!', ASCII code 33)\n- Variables x, y and z (ASCII codes 120-122)\n- Parentheses ('(', ASCII code 40, and ')', ASCII code 41)\n\nIf more than one expression of minimum length exists, you should find the lexicographically smallest one.\n\nOperations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:\n\nE ::= E '|' T | T\n\nT ::= T '&' F | F\n\nF ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'",
    "tutorial": "The number of functions of three variables is $2^{23} = 256$. Note that for an expression, we're only interested in its truth table and the nonterminal from which this expression can be formed. So, there are $3 \\cdot 256$ different states. And the problem is to find an expression of minimum length, and the lexicographically smallest out of these, for every state. You can do it in different ways. For example, there's a solution which works in $O(n^{3})$, where $n$ is the number of states. While there are states without answer, let's perform iterations. On every iteration, loop over all pairs of fixed states and apply rules from the grammar for this pair if it's possible (i.e. these states match nonterminals from the right part of the rule). Similarly, apply rules with one nonterminal in the right part. After that let's find and fix the state with the shortest found expression over all states that haven't been fixed yet. If there is more than one shortest expression, choose the lexicographically smallest. Any fixed state would never change its expression in the future, so the found expression is the answer for this state. This is true in the same way as in Dijkstra's algorithm. The answer for a function is the same as the answer for the state defined by this function and non-terminal E, since any other nonterminal for this function can be reached from E using rules which don't change the expression. Thus, the number of iterations is $n$ and every iteration works in $O(n^{2})$, so this solution works in $O(n^{3})$. Such a solution might or might not be fast enough to get accepted. But if your solution gets TL 1, you can calculate the answer for every possible function (remember, there are only $256$ of them) locally and then submit a solution with an array of answers. A solution which works in $O(n^{2})$ is also possible. This solution uses an analogue of Dijkstra's algorithm as well, but on every iteration it only applies rules which contain the new fixed state. This was not necessary to get accepted.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring res[256][3];\nbool changed;\n\nvoid update(string &a, string &b) {\n  if (a == \"\" || (b.length() < a.length() || (b.length() == a.length() && b < a))) {\n    changed = true;\n    a = b;\n  }\n}\n\nint main() {\n  res[(1 << 4) + (1 << 5) + (1 << 6) + (1 << 7)][0] = \"x\";\n  res[(1 << 2) + (1 << 3) + (1 << 6) + (1 << 7)][0] = \"y\";\n  res[(1 << 1) + (1 << 3) + (1 << 5) + (1 << 7)][0] = \"z\";\n  changed = true;\n  while (changed) {\n    changed = false;\n    for (int i = 0; i < 256; i++) {\n      for (int j = 0; j < 3; j++) {\n        if (res[i][j] == \"\") {\n          continue;\n        }\n        { // op == 0\n          string s = res[i][j];\n          if (j > 0) {\n            s = \"(\" + s + \")\";\n          }\n          s = \"!\" + s;\n          update(res[i ^ 255][0], s);\n        }\n        for (int ii = 0; ii < 256; ii++) {\n          for (int jj = 0; jj < 3; jj++) {\n            if (res[ii][jj] == \"\") {\n              continue;\n            }\n            for (int op = 1; op <= 2; op++) {\n              string s = res[i][j];\n              if (j > op) {\n                s = \"(\" + s + \")\";\n              }\n              string t = res[ii][jj];\n              if (jj > op) {\n                t = \"(\" + t + \")\";\n              }\n              string w = s + (op == 1 ? '&' : '|') + t;\n              update(res[op == 1 ? (i & ii) : (i | ii)][op], w);\n            }\n          }\n        }\n      }\n    }\n  }\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    string z;\n    cin >> z;\n    int mask = 0;\n    for (int i = 0; i < 8; i++) {\n      mask |= (z[i] - '0') << i;\n    }\n    string best = \"\";\n    for (int j = 0; j < 3; j++) {\n      update(best, res[mask][j]);\n    }\n    cout << best << endl;\n  }\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "913",
    "index": "F",
    "title": "Strongly Connected Tournament",
    "statement": "There is a chess tournament in All-Right-City. $n$ players were invited to take part in the competition. The tournament is held by the following rules:\n\n- Initially, each player plays one game with every other player. There are no ties;\n- After that, the organizers build a complete directed graph with players as vertices. For every pair of players there is exactly one directed edge between them: the winner of their game is the startpoint of this edge and the loser is the endpoint;\n- After that, the organizers build a condensation of this graph. The condensation of this graph is an acyclic complete graph, therefore it has the only Hamiltonian path which consists of strongly connected components of initial graph $A_{1} → A_{2} → ... → A_{k}$.\n- The players from the first component $A_{1}$ are placed on the first $|A_{1}|$ places, the players from the component $A_{2}$ are placed on the next $\\left|{\\mathcal{A}}_{2}\\right|$ places, and so on.\n- To determine exact place of each player in a strongly connected component, all the procedures from 1 to 5 are repeated recursively inside each component, i.e. for every $i = 1, 2, ..., k$ players from the component $A_{i}$ play games with each other again, and so on;\n- If a component consists of a single player, then he has no more rivals, his place is already determined and the process stops.\n\nThe players are enumerated with integers from $1$ to $n$. The enumeration was made using results of a previous tournament. It is known that player $i$ wins player $j$ ($i < j$) with probability $p$.\n\nYou need to help to organize the tournament. Find the expected value of total number of games played by all the players.\n\nIt can be shown that the answer can be represented as $\\frac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q\\not\\equiv0{\\mathrm{~(mod~998244353)}}$. Print the value of $P·Q^{ - 1}$ modulo $998244353$.\n\nIf you are not familiar with any of the terms above, you can read about them here.",
    "tutorial": "Probability of player $i$ to win player $j$ depends on whether $i < j$ only, so the answer for subset of players of size $s$ doesn't depend on the set, only on its size. Let $ans(s)$ be the answer for set of $s$ players. Lets calculate the answer using dynamic programming. $ans(0) = ans(1) = 0$. For larger $s$ lets use law of total expected value. Let $i$ be size of the last strongly connected component. $a n s(s)=\\sum_{i=1}^{s}s t r o n g(i)\\cdot c p(s,i)\\cdot(i\\cdot(s-i)+\\frac{i\\cdot(i-1)}{2}+a n s(i)+a n s(s-i))$ - equation (1). $i$-th term consists of three factors. The first factor $strong(i)$ is the probability of graph of $i$ players be strong connected. We'll describe how to calculate it below. The second factor $cp(s, i)$ is the probability of existing $i$ players in set of $s$ players such that these $i$ players lost all the rest players. The product of these two factors is the probability that size of the last strongly connected component is $i$. The third factor is expected value of number of games with the condition of the last component has size $i$. $i \\cdot (s - i)$ is number of games between players of the last component and the rest players. $\\textstyle{\\frac{n(n-1)}{2}}$ is number of games inside of the last component. $ans(i)$ is the expected value of number of games in the last component on the next round. After that we need to add number of games between all the players except for the last component and the value of $ans$ for sizes of other components. Note that this terms describe the game on set of players except the last component. Therefore the sum of these terms is $ans(s - i)$. Also note that the right part of equation (1) contains term that uses $ans(s)$. So $ans(s)$ is using $ans(s)$ for calculating itself. To overcome this lets move this term to the left side and solve linear equation with variable $ans(s)$. How to calculate $strong(s)$? $strong(1) = 1$ because the graph with one vertice is strong connected. When $s  \\ge  2$ we have $s t r o n g(s)=1-\\sum_{i=1}^{s-1}s t r o n g(i)\\cdot c p(s,i)$. Here we use law of total probability and calculate the answer by iterating $i$ over possible values of size of the last component. How to calculate $cp(s, i)$? $cp(s, 0) = 1$ because there are $0$ players who lost games to the others. $cp(s, i) = cp(s - 1, i) \\cdot (1 - p)^{i} + cp(s - 1, i - 1) \\cdot p^{s - i}$ where $p$ is the probability of winning the player with less index. Here we use law of total probability again. The first term describe the case when player with the largest index is not in the set of players that lost to the others, so he should win all the players from the set. The second term describes the case when player with the largest index is in the set. In this case he should lose the game to all the players who is not in the set. In summary, value of $ans(n)$ can be calculated in time $O(n^{2})\\,$ and this value is the answer for the problem.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int md = 998244353;\n\ninline void add(int &a, int b) {\n  a += b;\n  if (a >= md) a -= md;\n}\n\ninline void sub(int &a, int b) {\n  a -= b;\n  if (a < 0) a += md;\n}\n\ninline int mul(int a, int b) {\n  return (int) ((long long) a * b % md);\n}\n\ninline int power(int a, long long b) {\n  int res = 1;\n  while (b > 0) {\n    if (b & 1) {\n      res = mul(res, a);\n    }\n    a = mul(a, a);\n    b >>= 1;\n  }\n  return res;\n}\n\ninline int inv(int a) {\n  return power(a, md - 2);\n}\n\nint main() {\n  int n, P, Q;\n  cin >> n >> P >> Q;\n  int p = mul(P, inv(Q));\n  vector< vector<int> > p_win(n + 1, vector<int>(n + 1, 0));\n  p_win[0][0] = 1;\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j <= i; j++) {\n      add(p_win[i + 1][j], mul(p_win[i][j], power(p, j)));\n      add(p_win[i + 1][j + 1], mul(p_win[i][j], power((1 - p + md) % md, i - j)));\n    }\n  }\n  vector<int> p_strong(n + 1);\n  for (int i = 1; i <= n; i++) {\n    p_strong[i] = 1;\n    for (int j = 1; j < i; j++) {\n      sub(p_strong[i], mul(p_strong[j], p_win[i][j]));\n    }\n  }\n  vector<int> res(n + 1);\n  res[1] = 0;\n  for (int i = 2; i <= n; i++) {\n    res[i] = 0;\n    for (int j = 1; j < i; j++) {\n      int coeff = mul(p_strong[j], p_win[i][j]);\n      int games = (res[j] + res[i - j]) % md;\n      add(games, j * (j - 1) / 2 + j * (i - j));\n      add(res[i], mul(coeff, games));\n    }\n    add(res[i], mul(i * (i - 1) / 2, p_strong[i]));\n    res[i] = mul(res[i], inv((1 - p_strong[i] + md) % md));\n  }\n  cout << res[n] << endl;\n  return 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "math",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "913",
    "index": "G",
    "title": "Power Substring",
    "statement": "You are given $n$ positive integers $a_{1}, a_{2}, ..., a_{n}$.\n\nFor every $a_{i}$ you need to find a positive integer $k_{i}$ such that the decimal notation of $2^{ki}$ contains the decimal notation of $a_{i}$ as a substring among its last $min(100, length(2^{ki}))$ digits. Here $length(m)$ is the length of the decimal notation of $m$.\n\nNote that you don't have to minimize $k_{i}$. The decimal notations in this problem do not contain leading zeros.",
    "tutorial": "Lets solve the problem for every $a_{i}$ separately. Let $n = length(a_{i})$. Let us choose $m$ and $b$ such that $0  \\le  b < 10^{m}$. Lets find $k$ such that decimal notation of $2^{k}$ ends with $x = a_{i} \\cdot 10^{m} + b$. Equation $2^{k}\\equiv x\\mathrm{~~mod~}10^{n+m}$ is necessary and sufficient for that. Lets find such $k$ that $k  \\ge  n + m$. In this case $2^{n+m}\\mid2^{k}$ and $\\iiint_{a\\setminus{\\mathbb{H}}}\\mid\\mathbf{\\sqrt{}}\\mid\\mathbf{\\sqrt{}}\\mid^{n+H_{\\mathrm{i}}}$. Therefore we need $2^{n+m}\\mid x$ - equation (1). Also $\\textstyle\\bigcap{}\\left|{\\Big|}^{\\left|1+j\\right|}$ and $5\\mid2^{k}$. Therefore we need $5\\mid x$ - equation (2). For fixed $m$ we have $10^{m}$ ways to set value of $b$. These values generate segment of $10^{m}$ consecutive integer values of $x$. If we choose large enough value of $m$, e.g. such $m$ that $10^{m}  \\ge  2 \\cdot 2^{n + m}$, we can choose value of $x$ from set of size $10^{m}$ satisfying (1) and (2). Consider equation $2^{k}\\equiv x\\;\\;\\mathrm{mod}\\;10^{n+m}$. Every number in the equation is divisible by $2^{n + m}$, lets divide all the numbers by this. The result is $2^{k-n-m}\\equiv y\\;\\;\\mathrm{mod}\\;5^{n+m}$ - equation (3) where $y={\\frac{z^{n}}{2^{n+m}}}$. Use the following lemma: Lemma For every positive integer $t$ number $2$ is primitive root modulo $5^{t}$. Proof The proof of this lemma is left to the reader as exercise. It follows from the lemma that for every $y$ there exists $k$ satisfying equation (3). It is $k = n + m + log_{2}(y)$ where $log$ is discrete logarithm modulo $5^{n + m}$. In this problem $n  \\le  11$. $m = 6$ is enough for such $n$, so $5^{n + m}  \\le  5^{17}$. For such modulo Baby-step-giant-step method works too slow. Lets use the following algorithm for searching logarithm modulo $p^{ \\alpha }$ in time $O(p\\alpha)$: Lets find $log_{g}(x)$. Let $d_{i}=l o g_{g}(x)\\mod p^{i}$. Calculate $d_{1}$ in naive way in time ${\\cal O}(p)$. After that we can find $d_{i + 1}$ by the value of $d_{i}$. $d_{i + 1} = d_{i} + j \\cdot  \\phi (p^{i})$ for some $j$ in range $0... p - 1$. For every such $j$ check the equation $g^{d_{i}+3\\circ\\phi(p^{*})}\\equiv x~~\\mathrm{mod}~p^{i+1}$ and choose the suitable one.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline long long mul(long long a, long long b, long long md) {\n  long long res = 0;\n  while (b > 0) {\n    if (b & 1) {\n      res += a; if (res >= md) res -= md;\n    }\n    a += a; if (a >= md) a -= md;\n    b >>= 1;\n  }\n  return res;\n}\n\ninline long long power(long long a, long long b, long long md) {\n  long long res = 1;\n  while (b > 0) {\n    if (b & 1) {\n      res = mul(res, a, md);\n    }\n    a = mul(a, a, md);\n    b >>= 1;\n  }\n  return res;\n}\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    long long a;\n    cin >> a;\n    int n = (int) to_string(a).length();\n    for (int m = 0; ; m++) {\n      long long b = (-a) & ((1LL << (n + m)) - 1);\n      if ((a + b) % 5 == 0) {\n        b += (1LL << (n + m));\n      }\n      if ((b == 0 && m == 0) || (int) to_string(b).length() <= m) {\n        long long c = (a + b) >> (n + m);\n        long long t = vector<long long>{-1, 0, 1, 3, 2}[c % 5];\n        long long p5 = 5;\n        for (int i = 1; i < n + m; i++) {\n          while (power(2, t, p5 * 5) != c % (p5 * 5)) {\n            t += p5 / 5 * 4;\n          }\n          p5 *= 5;\n        }\n        t += n + m;\n        cout << t << endl;\n        break;\n      }\n      a *= 10;\n    }\n  }\n  return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 3200
  },
  {
    "contest_id": "913",
    "index": "H",
    "title": "Don't Exceed",
    "statement": "You generate real numbers $s_{1}, s_{2}, ..., s_{n}$ as follows:\n\n- $s_{0} = 0$;\n- $s_{i} = s_{i - 1} + t_{i}$, where $t_{i}$ is a real number chosen independently uniformly at random between 0 and 1, inclusive.\n\nYou are given real numbers $x_{1}, x_{2}, ..., x_{n}$. You are interested in the probability that $s_{i} ≤ x_{i}$ is true for all $i$ simultaneously.\n\nIt can be shown that this can be represented as $\\frac{P}{Q}$, where $P$ and $Q$ are coprime integers, and $Q\\not\\equiv0{\\mathrm{~(mod~998244353)}}$. Print the value of $P·Q^{ - 1}$ modulo $998244353$.",
    "tutorial": "If $t_{i}$ were random integers and not reals, it would be natural to solve the problem using dynamic programming: $f(i, j)$ - the probability that the required inequalities are satisfied if $s_{i} = j$. But in case of real numbers, the probability that a random real number equals to something is zero. What to do then? A natural solution is to maintain $f(i, x)$ as a function of $x$, that is, $f(i, x)$ will be the probability density function of $s_{i}$. What is the form of $f(i, x)$ of $x$ for fixed $i$? It turns out that this function is piecewise polynomial. Indeed, for $i = 1$ we have $f(i, x) = 1$ for $x < min(1, x_{1})$ and $f(i, x) = 0$ otherwise. For all $i > 1$ for $x > x_{i}$ we have $f(i, x) = 0$, while for $x  \\le  x_{i}$ the following identity is true: $f(i,x)=\\textstyle\\int_{x-1}^{x}f(i-1,y)d y$. For fixed $x$, what is the value of this integral? Several pieces of $f(i - 1, x)$ fall inside the integration range. The integral of pieces which fall inside entirely is a constant. The integral of the single piece which is close to $x$ (so the start of this piece falls inside the range, but the end of this piece doesn't) is the integral of the corresponding piece of $f(i - 1, x)$, which is an integral of a polynomial, which is a polynomial. Similarly, the integral of the opposite piece (close to $x - 1$) is the integral of the corresponding piece of $f(i - 1, x)$ under substitution of $x - 1$, which is also a polynomial. By induction we can see that $f(i, x)$ is a piecewise polynomial function of $x$. The solution of the problem is indeed maintaining $f(i, x)$ as polynomials on the corresponding intervals. It's easy to see that polynomials in $f(i, x)$ have degree at most $i - 1$ (by induction). To estimate the complexity of this solution, note that the ends of the pieces have the following form: $x_{i} + c$, where $c$ is an integer. Since we're only interested in the ends of the pieces which are between 0 and $n$, we have $O(n^{2})$ pieces overall. Since we have to calculate $n$ layers of DP, each function is a polynomial of degree at most $n$, and substituting $x - 1$ into a polynomial takes $O(n^{2})$, the overall complexity of the solution is $O(n^{5})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int md = 998244353;\n\ninline void add(int &a, int b) {\n  a += b;\n  if (a >= md) a -= md;\n}\n\ninline void sub(int &a, int b) {\n  a -= b;\n  if (a < 0) a += md;\n}\n\ninline int mul(int a, int b) {\n  return (int) ((long long) a * b % md);\n}\n\ninline int power(int a, long long b) {\n  int res = 1;\n  while (b > 0) {\n    if (b & 1) {\n      res = mul(res, a);\n    }\n    a = mul(a, a);\n    b >>= 1;\n  }\n  return res;\n}\n\ninline int inv(int a) {\n  return power(a, md - 2);\n}\n\ntypedef vector<int> poly;\n\npoly integrate(poly a) {\n  poly b = {0};\n  for (int i = 0; i < (int) a.size(); i++) {\n    b.push_back(mul(a[i], inv(i + 1)));\n  }\n  return b;\n}\n\nvoid sub(poly &a, poly b) {\n  while (a.size() < b.size()) {\n    a.push_back(0);\n  }\n  for (int i = 0; i < (int) b.size(); i++) {\n    sub(a[i], b[i]);\n  }\n}\n\nint eval(poly a, int x) {\n  int res = 0;\n  for (int i = (int) a.size() - 1; i >= 0; i--) {\n    res = mul(res, x);\n    add(res, a[i]);\n  }\n  return res;\n}\n\nconst int COEFF = 1000000;\n\nint main() {\n  int n;\n  cin >> n;\n  vector<int> x(n), fracs;\n  for (int i = 0; i < n; i++) {\n    double foo;\n    cin >> foo;\n    x[i] = (int) (foo * COEFF + 0.5);\n    fracs.push_back(x[i] % COEFF);\n  }\n  fracs.push_back(0);\n  sort(fracs.begin(), fracs.end());\n  fracs.resize(unique(fracs.begin(), fracs.end()) - fracs.begin());\n  int cnt = (int) fracs.size();\n  vector<int> point(n * cnt + 1);\n  for (int i = 0; i <= n * cnt; i++) {\n    point[i] = i / cnt * COEFF + fracs[i % cnt];\n  }\n  vector<int> cut(n);\n  for (int i = 0; i < n; i++) {\n    cut[i] = (int) (find(point.begin(), point.end(), x[i]) - point.begin());\n  }\n  vector<int> sz(n * cnt);\n  for (int i = 0; i < n * cnt; i++) {\n    sz[i] = mul((point[i + 1] - point[i] + md) % md, inv(COEFF));\n  }\n  vector<poly> a(n * cnt);\n  vector<int> sum(n * cnt);\n  for (int i = 0; i < n * cnt; i++) {\n    a[i] = i < min(cnt, cut[0]) ? vector<int>{0, 1} : vector<int>{0};\n    sum[i] = a[i].size() == 1 ? 0 : sz[i];\n  }\n  for (int id = 1; id < n; id++) {\n    for (int i = n * cnt - 1; i >= 0; i--) {\n      if (i >= cut[id]) {\n        a[i] = {0};\n        sum[i] = 0;\n      } else {\n        for (int j = i - 1; j >= i - cnt && j >= 0; j--) {\n          add(a[i][0], sum[j]);\n        }\n        if (i - cnt >= 0) {\n          sub(a[i], a[i - cnt]);\n        }\n        a[i] = integrate(a[i]);\n        sum[i] = eval(a[i], sz[i]);\n      }\n    }\n  }\n  int ans = 0;\n  for (int i = 0; i < n * cnt; i++) {\n    add(ans, sum[i]);\n  }\n  printf(\"%d\\n\", ans);\n  return 0;\n}",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 3400
  },
  {
    "contest_id": "914",
    "index": "A",
    "title": "Perfect Squares",
    "statement": "Given an array $a_{1}, a_{2}, ..., a_{n}$ of $n$ integers, find the largest number in the array that is not a perfect square.\n\nA number $x$ is said to be a perfect square if there exists an integer $y$ such that $x = y^{2}$.",
    "tutorial": "For each number, check whether the number is a square or not (by checking factors smaller than the square root of the number or using sqrt function). The answer is the largest number which isn't a square. (negative numbers can't be squares) Make sure you initialize your max variable to $- 10^{6}$ instead of $0$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n  long long ans=LLONG_MIN, n, x;\n  cin>>n;\n  for (long long i = 0; i < n; i++)\n  {\n    cin>>x;\n    for (long long j = 0; j*j<=x; j++)\n    if (j*j == x)\n      x = LLONG_MIN;\n    ans = max(ans, x);\n  }\n  cout << ans << endl;\n  return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "914",
    "index": "B",
    "title": "Conan and Agasa play a Card Game",
    "statement": "Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has $n$ cards, and the $i$-th card has a number $a_{i}$ written on it.\n\nThey take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the $i$-th card, he removes that card and removes the $j$-th card for all $j$ such that $a_{j} < a_{i}$.\n\nA player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.",
    "tutorial": "Let $A = max (a_{1}, a_{2}, ..., a_{n})$. Observe that if $A$ occurs an odd number of times, Conan can simply begin by removing one instance of $A$. If there are any cards left, they all have the same number $A$ on them. Now each player can only remove one card in their turn, and they take turns doing so. Since there were an odd number of cards having $A$ on them initially, this keeps continuing until finally, in one of Agasa's turns, there are no cards left. However, if $A$ occurs an even number of times, Conan cannot choose a card having $A$ on it because it will leave Agasa with an odd number of cards having $A$. This will result in both players picking cards one by one, ending with Agasa picking the last card, and thus winning. In such a case, Conan can consider picking the next distinct largest number in the array, say $B$. If $B$ occurs an odd number of times, then after Conan's turn there will be an even number of cards having $B$ and an even number of cards having $A$. If Agasa takes a card having $A$ then it becomes the same as the previous case and Conan wins. Otherwise, they take turns choosing a card having $B$ until finally, on one of Agasa's turns, there are no cards having $B$ and Agasa is forced to pick a card having $A$. Now it is Conan's turn and there are an odd number of cards having $A$, so it is again the same as the first case and Conan wins. By a similar argument, we can show that if Conan plays optimally, he starts by picking a card having the greatest number that occurs an odd number of times. Conan loses if and only if there is no such number, i.e., Conan loses if and only if every number occurs an even number of times.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint cnt[100005];\n\nint main() {\n  ios::sync_with_stdio(false);\n\n  int n;\n  cin >> n;\n  while(n--) {\n    int x;\n    cin >> x;\n    cnt[x]++;\n  }\n\n  for (int i = 1; i <= 1e5; i++) {\n    if (cnt[i] % 2 == 1) {\n      cout << \"Conan\\n\";\n      return 0;\n    }\n  }\n  cout << \"Agasa\\n\";\n  return 0;\n}",
    "tags": [
      "games",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "914",
    "index": "C",
    "title": "Travelling Salesman and Special Numbers",
    "statement": "The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer $x$ and reduce it to the number of bits set to $1$ in the binary representation of $x$. For example for number $13$ it's true that $13_{10} = 1101_{2}$, so it has $3$ bits set and $13$ will be reduced to $3$ in one operation.\n\nHe calls a number special if the minimum number of operations to reduce it to $1$ is $k$.\n\nHe wants to find out how many special numbers exist which are not greater than $n$. Please help the Travelling Salesman, as he is about to reach his destination!\n\nSince the answer can be large, output it modulo $10^{9} + 7$.",
    "tutorial": "Let us denote the minimum number of steps it takes to reduce a number to $1$ as the order of that number. Since the number of set bits in numbers smaller than $2^{1000}$ is less than $1000$, any number smaller than $2^{1000}$ would reduce to a number less than $1000$ in one step. We can precompute the order of the first $1000$ numbers. For each $x$ ($x < 1000$) such that $x$ has order $k - 1$, we need to compute the number of numbers less than or equal to $n$ that have $k$ set bits. Let $k$ be the number of digits in the binary representation of $n$. Every number $x < n$ satisfies the property that, for some $i$ ($1  \\le  i < k$), the first $i - 1$ digits of $x$ are the same as that of $n$, the $i^{th}$ digit of $n$ is $1$, and the $i$-th digit of $x$ is $0$. We can iterate through all possible $i$ and compute the answer using binomial coefficients, that can be computed in $O(l)$ where $l$ is the length of binary representation of n. Time Complexity: $O(l)$ where $l$ is the length of binary representation of n.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n\n#define MOD 1000000007\n\nint dp[1004];\nlong long ncr[1004][1004];\n\nint ones(int n)\n{\n  int cnt = 0;\n  while(n)\n  {\n    if(n%2 == 1)\n    {\n      cnt++;\n    }\n    n /= 2;\n  }\n  return cnt;\n}\n\nvoid calcncr()\n{\n  for(int i = 0; i <= 1000; i++)\n  {\n    ncr[i][0] = 1;\n  }\n  for(int i = 1; i <= 1000; i++)\n  {\n    for(int j = 1; j <= 1000; j++)\n    {\n      ncr[i][j] = (ncr[i-1][j-1] + ncr[i-1][j])%MOD;\n    }\n  }\n}\n\nint main()\n{\n  string n;\n  int k;\n  calcncr();\n\n  dp[1] = 0;\n  for(int i = 2; i <= 1000; i++)\n  {\n    dp[i] = dp[ones(i)] + 1;\n  }\n\n  cin >> n >> k;\n\n  if(k == 0)\n  {\n    cout << \"1\\n\";\n    return 0;\n  }\n\n  long long nones = 0, ans = 0;\n  for(int i = 0; i < n.size(); i++)\n  {\n    if(n[i] == '0')\n    {\n      continue;\n    }\n    for(int j = max(nones, 1LL); j < 1000; j++)\n    {\n      if(dp[j] == k-1)\n      {\n        ans = (ans + ncr[n.size()-i-1][j-nones])%MOD;\n        if(i == 0 && k == 1)\n        {\n          ans = (ans+MOD-1)%MOD;\n        }\n      }\n    }\n    nones++;\n  }\n\n  int cnt = 0;\n  for(int i = 0; i < n.size(); i++)\n  {\n    if(n[i] == '1')\n    {\n      cnt++;\n    }\n  }\n  if(dp[cnt] == k-1)\n  {\n    ans = (ans + 1)%MOD;\n  }\n  cout << ans << endl;\n\n  return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "914",
    "index": "D",
    "title": "Bash and a Tough Math Puzzle",
    "statement": "Bash likes playing with arrays. He has an array $a_{1}, a_{2}, ... a_{n}$ of $n$ integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.\n\nSuppose he guesses that the gcd of the elements in the range $[l, r]$ of $a$ is $x$. He considers the guess to be almost correct if he can change \\textbf{at most} one element in the segment such that the gcd of the segment is $x$ after making the change. Note that when he guesses, he doesn't actually change the array — he just wonders if the gcd of the segment can be made $x$. Apart from this, he also sometimes makes changes to the array itself.\n\nSince he can't figure it out himself, Bash wants you to tell him which of his guesses are almost correct. Formally, you have to process $q$ queries of one of the following forms:\n\n- $1 l r x$ — Bash guesses that the gcd of the range $[l, r]$ is $x$. Report if this guess is almost correct.\n- $2 i y$ — Bash sets $a_{i}$ to $y$.\n\n\\textbf{Note:} The array is $1$-indexed.",
    "tutorial": "Build a segment tree on the array to answer range gcd queries. We can handle single element updates in the segment tree. Let us see how to answer an $(l, r, x)$ query. The segment tree decomposes the query range into $O(logn)$ nodes that cover the range. If the gcds of all of these nodes are multiples of $x$, then the answer is YES. If the gcd of two or more of these nodes is not a multiple of $x$, then the answer is NO. If the gcd of exactly one node is not a multiple of $x$, then we need to know how many elements in this node are not multiples of $x$. We can find this by traversing the descendents of that node. If at a point only one child is not a multiple of $x$, recurse into it. If at any point, there are two children whose gcds are not multiples of $x$, then the answer is NO. Otherwise, if we reach a node that doesn't have any children, then the answer is YES.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nint tree[2000000];\nint trstp = 1;\n\nint gcd(int x, int y) {\n  return y == 0 ? x : gcd(y, x % y);\n}\n\nvoid query(int root, int u, int v, int x, int s, int e, int& ans) {\n  if (e < s || v < u || e < u || v < s) {\n    return;\n  } else if (u <= s && e <= v) {\n    if (tree[root] % x == 0) {\n      return;\n    } else {\n      while (root < trstp) {\n        if (tree[2*root] % x != 0) {\n          if (tree[2*root + 1] % x != 0) {\n            ans += 2;\n            return;\n          }\n          root = 2*root;\n        } else {\n          root = 2*root + 1;\n        }\n      }\n      ans++;\n      return;\n    }\n  }\n  int mid = (s + e)/2;\n  query(2*root, u, v, x, s, mid, ans);\n  if (ans > 1) {\n    return;\n  }\n  query(2*root + 1, u, v, x, mid + 1, e, ans);\n}\n\nvoid update(int p, int x) {\n  p += trstp - 1;\n  tree[p] = x;\n\n  p /= 2;\n  while (p > 0) {\n    tree[p] = gcd(tree[2*p], tree[2*p + 1]);\n    p /= 2;\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n   cin.tie(NULL);\n\n  int n;\n  cin >> n;\n  while (trstp < n) {\n    trstp *= 2;\n  }\n\n  for (int i = trstp; i < trstp + n; i++) {\n    cin >> tree[i];\n  }\n  for (int i = trstp - 1; i >= 1; i--) {\n    tree[i] = gcd(tree[2*i], tree[2*i + 1]);\n  }\n\n  int q;\n  cin >> q;\n  while (q--) {\n    int t;\n    cin >> t;\n    if (t == 1) {\n      int l, r;\n      int x;\n      cin >> l >> r >> x;\n      int ans = 0;\n      query(1, l, r, x, 1, trstp, ans);\n      cout << (ans <= 1 ? \"YES\\n\" : \"NO\\n\");\n    } else {\n      int i;\n      int y;\n      cin >> i >> y;\n      update(i, y);\n    }\n  }\n\n  return 0;\n}",
    "tags": [
      "data structures",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "914",
    "index": "E",
    "title": "Palindromes in a Tree",
    "statement": "You are given a tree (a connected acyclic undirected graph) of $n$ vertices. Vertices are numbered from $1$ to $n$ and each vertex is assigned a character from a to t.\n\nA path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.\n\nFor each vertex, output the number of palindromic paths passing through it.\n\n\\textbf{Note:} The path from vertex $u$ to vertex $v$ is considered to be the same as the path from vertex $v$ to vertex $u$, and this path will be counted only once for each of the vertices it passes through.",
    "tutorial": "The problem can be solved by centroid decomposition. A path will be palindromic at most one letter appears odd number of times in the path. We maintain a bitmask for each node, where $i$-th bit is $1$ if the $i$-th character occurs odd number of times, otherwise $0$. The path from $u$ to $v$ is valid if mask[$u$] ^ mask[$v$] has at most one bit set to $1$. Consider a part as the subtree of the immediate children of the root of the the centroid tree. For a node, we need to consider the paths that go from its subtree to any other part. We add the contribution of nodes in the subtree of a node using a simple dfs and propagating the values above and add the corresponding contribution to the answer of the node currently in consideration(dfs). Complexity is n*log(n)*20",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define ll long long\n#define db long double\n#define ii pair<int,int>\n#define vi vector<int>\n#define fi first\n#define se second\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(),(a).end()\n#define pb emplace_back\n#define mp make_pair\n#define FN(i, n) for (int i = 0; i < (int)(n); ++i)\n#define FEN(i,n) for (int i = 1;i <= (int)(n); ++i)\n#define rep(i,a,b) for(int i=a;i<b;i++)\n#define repv(i,a,b) for(int i=b-1;i>=a;i--)\n#define SET(A, val) memset(A, val, sizeof(A))\ntypedef tree<int ,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set ;\n// order_of_key (val): returns the no. of values less than val\n// find_by_order (k): returns the kth largest element.(0-based)\n#define TRACE\n#ifdef TRACE\n#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)\ntemplate <typename Arg1>\nvoid __f(const char* name, Arg1&& arg1){\n  cerr << name << \" : \" << arg1 << std::endl;\n}\ntemplate <typename Arg1, typename... Args>\nvoid __f(const char* names, Arg1&& arg1, Args&&... args){\n  const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << \" : \" << arg1<<\" | \";__f(comma+1, args...);\n}\n#else\n#define trace(...)\n#endif\nconst int L=200005,N=(1<<20);\n//call dfsMCT,change solve and dfs1\nvi vpart[L],ad[L]; bool vis[L];//par:parent in cent|H:depth\nint SZ[L],par[L],part[L],H[L],cpart;//cpart:no of parts in cent\nll ans[L],dp[L];\nstring s;\nint dfsSZ(int u,int p=-1)\n{\n  SZ[u]=1;//vpart[i]:nodes in part i\n  for(int v:ad[u])\n    if(!vis[v] && v!=p)\n      SZ[u]+=dfsSZ(v,u);\n  return SZ[u];\n}\nint dfsFC(int u,int r,int p=-1)\n{\n  for(int v:ad[u])\n    if(!vis[v] && v!=p)\n      {\n  if(SZ[v]>SZ[r]/2)\n    return dfsFC(v,r,u);\n      }\n  return u;\n}\nint cnt[N],val[L],tmp[N];\nvoid dfs1(int u,int r,int p=-1)\n{\n  dp[u]=0;\n  if(p==r)\n    {\n      part[u]=++cpart;\n      vpart[cpart].clear();\n    }\n  else if(p!=-1) part[u]=part[p];\n  if(p!=-1) vpart[cpart].pb(u);\n  for(int v1:ad[u])\n    if(!vis[v1]&&v1!=p)\n      {\n  H[v1]=H[u]+1;\n  val[v1]=(val[u]^(1<<(s[v1-1]-'a')));\n  dfs1(v1,r,u);\n      }\n}\nvoid dfs2(int u,int r,int par=-1)\n{\n  dp[u]=cnt[val[u]];\n  rep(i,0,20)\n    dp[u]+=cnt[val[u]^(1<<i)];\n  for(int v1:ad[u])\n    {\n      if(vis[v1] || v1==par) continue;\n      dfs2(v1,r,u);\n      dp[u]+=dp[v1];\n    }\n  ans[u]+=dp[u];\n}\nvoid solve(int r,int szr)\n{\n  H[r]=cpart=0;\n  val[r]=(1<<(s[r-1]-'a'));\n  dfs1(r,r);\n  rep(i,1,cpart+1)\n    for(int v1:vpart[i])\n      cnt[val[v1]]++;\n  cnt[val[r]]++;\n  rep(i,1,cpart+1)\n    {\n      for(int v1:vpart[i])\n  {\n    cnt[val[v1]]--;\n    val[v1]^=(1<<(s[r-1]-'a'));\n    tmp[val[v1]]++;\n  }\n      for(int v1:vpart[i])\n  {\n    if(tmp[val[v1]])\n      {\n        dp[r]+=(ll)tmp[val[v1]]*cnt[val[v1]];\n        rep(j,0,20)\n    dp[r]+=(ll)tmp[val[v1]]*cnt[val[v1]^(1<<j)];\n        tmp[val[v1]]=0;\n      }\n  }\n      dfs2(vpart[i][0],r,r);\n      for(int v1:vpart[i])\n  {\n    val[v1]^=(1<<(s[r-1]-'a'));\n    cnt[val[v1]]++;\n  }\n    }\n  cnt[val[r]]--;\n  dp[r]+=cnt[0];\n  rep(i,0,20)\n    dp[r]+=cnt[(1<<i)];\n  ans[r]+=dp[r]/2;\n  rep(i,1,cpart+1)\n    for(int v1:vpart[i]) cnt[val[v1]]--;\n}\nvoid dfsMCT(int u,int p=-1)\n{\n  dfsSZ(u);\n  int r=dfsFC(u,u);\n  par[r]=p; solve(r,SZ[u]); vis[r]=true;\n  for(int v:ad[r])\n    if(!vis[v]) dfsMCT(v,r);\n}\nint main()\n{\n  std::ios::sync_with_stdio(false);\n  cin.tie(NULL) ; cout.tie(NULL) ;\n  int n,x,y;\n  cin>>n;\n  rep(i,1,n)\n    {\n      cin>>x>>y;\n      ad[x].pb(y); ad[y].pb(x);\n    }\n  cin>>s;\n  dfsMCT(1);\n  rep(i,1,n+1) cout<<ans[i]+1<<\" \";\n  cout<<endl;\n  return 0 ;\n}\n",
    "tags": [
      "bitmasks",
      "data structures",
      "divide and conquer",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "914",
    "index": "F",
    "title": "Substrings in a String",
    "statement": "Given a string $s$, process $q$ queries, each having one of the following forms:\n\n- $1 i c$ — Change the $i$-th character in the string to $c$.\n- $2 l r y$ — Consider the substring of $s$ starting at position $l$ and ending at position $r$. Output the number of times $y$ occurs as a substring in it.",
    "tutorial": "Let $N = |s|$. Divide the given string into blocks of size $K={\\sqrt{N}}$ and use any suffix structure for each block. Complexity: $O(|s|)$. To update a character in the string, rebuild a suffix structure for that block. This takes $O(K)$ per update. We answer queries as follows. Remember that it's given that the total length of all the query strings is at most $10^{5}$. If the size of the query string is greater than $K$, then the number of such strings will be at most $y / K$ and hence we can directly use KMP in the string for the given range for all such strings. Overall Complexity: $O(N * y / K)$ If the size of the query string is less than $K$, we proceed as follows. For the occurrences of query string within a block, we can calculate them using the suffix structures for each block. This can be done in $O(|y|)$ for each block, $O(|y| * (N / k))$ for the given range. For the occurrences that lie across two (adjacent) blocks, we only need to consider a string of $2 * |y|$, we can simply use KMP for finding such occurrences. We need to choose the string carefully to avoid over counting (for more details, see the author's solution). Its complexity will be $O(N / k * 2 * |y|)$. For left and right blocks of the query range, we can again use KMP. The complexity would be $O(2 * k)$. The overall complexity for the small query strings is therefore $O(N / k * |y|)$. Hence, complexity over all such string would be $O(y * N / k)$. Hence, the overall complexity is $O(N * k + y * N / k)$. So choose any optimal $K$. Any $K$ from $150$ to $400$ will fit in the time limit. Expected Complexity: $O(N * sqrt(N))$ There was an unexpected solution that involved bitset that runs in complexity $O(N^{2} / 32)$.",
    "code": "#include <bits/stdc++.h>\n#define fr(x) scanf(\"%d\", &x)\n#define SQRN 150\nusing namespace std;\n\nconst int sa = 2 * SQRN + 10;\nconst int LEN = 100010;\nchar s[LEN], sq[LEN], zstring[2*LEN];\nint z[2*LEN];\nstring temps;\n\nstruct SuffixAutomaton {\n  int edges[26][sa], link[sa], length[sa], isTerminal[sa], dp1[sa], last;\n  int sz;\n  SuffixAutomaton() {\n    last = 0;\n    sz = 0;\n  }\n\n  void set(int k) {\n    for(int i = 0; i < 26; ++i) edges[i][k] = -1;\n  } \n\n  void build(string &s) { \n    link[0] = -1;\n    length[0] = 0;\n    last = 0;\n    sz = 1;\n    set(0);\n\n    for(int i=0;i<s.size();i++) {\n      set(sz);\n      length[sz] = i+1;\n      link[sz] = 0;\n      int r = sz;\n      ++sz;\n\n      int p = last;\n      while(p >= 0 && edges[s[i]-'a'][p] == -1) {\n        edges[s[i] - 'a'][p] = r;\n        p = link[p];\n      }\n      if(p != -1) {\n        int q = edges[s[i] - 'a'][p];\n        if(length[p] + 1 == length[q]) {\n          link[r] = q;\n        } else {\n          for(int i = 0; i < 26; ++i) {\n            edges[i][sz] = edges[i][q];\n          }\n          length[sz] = length[p] + 1;\n          link[sz] = link[q];\n          int qq = sz;\n          ++sz;\n          link[q] = qq;\n          link[r] = qq;\n          while(p >= 0 && edges[s[i] - 'a'][p] == q) {\n            edges[s[i] - 'a'][p] = qq;\n            p = link[p];\n          }\n        }\n      }\n      last = r;\n    }\n    for(int i = 0; i < sz; ++i) isTerminal[i] = 0, dp1[i] = -1; \n    int p = last;\n    while(p > 0) {\n      isTerminal[p] = 1;\n      p = link[p];\n    }\n  }\n\n  int solve(int pos) {\n    if(dp1[pos] != -1) return dp1[pos];\n    dp1[pos] = isTerminal[pos];\n    for(int i=0; i<26; ++i){\n      if(edges[i][pos] != -1) dp1[pos] += solve(edges[i][pos]);\n    }\n    return dp1[pos];\n  }\n\n  int run() {\n    int cur = 0;\n    for(int i=1; sq[i] != '\\0'; ++i) {\n      auto it = edges[sq[i] - 'a'][cur];\n      if(it == -1) return 0;\n      else cur = it;\n    }\n    return solve(cur);\n  }\n} SA[800];\n\nvoid computeZ() {\n  int l, r;\n  z[0] = 0;\n  l = r = -1;\n  for(int i=1; zstring[i] != '\\0'; ++i) {\n    z[i]=0;\n    if(r>i) {\n      z[i]=min(z[i-l], r-i+1);\n    }\n    while(zstring[i+z[i]] == zstring[z[i]]) ++z[i];\n    if(i+z[i]-1 > r) {\n      r = i+z[i]-1;\n      l = i;\n    }\n  }\n}\n\nint computeBrute(int l, int r, int sqlen) {\n  int zslen = 0, ans = 0;\n  for(int i=1; i<=sqlen; ++i) {\n    zstring[zslen++] = sq[i];\n  }\n  zstring[zslen++] = '$';\n  for(int i=l; i<=r; ++i) {\n    zstring[zslen++] = s[i];\n  }\n  zstring[zslen] = '\\0';\n  computeZ();\n  for(int i=1; i<zslen; ++i) {\n    if(z[i] >= sqlen) {\n      ++ans;\n    }\n  }\n  return ans;\n}\n\nint main() {\n  int q, typ, l, r, slen;\n  char ch;\n  scanf(\" %s\", &s[1]);\n  slen = strlen(&s[1]);\n  fr(q);\n  for(int i=0; i<=slen; i+=SQRN) {\n    temps = \"\";\n    int tempr = min(i+SQRN-1, slen);\n    for(int j=max(1, i); j<=tempr; ++j) {\n      temps += s[j];\n    }\n    SA[i/SQRN].build(temps);\n  }\n  while(q--) {\n    fr(typ);\n    if(typ == 1) {\n      scanf(\"%d %c\", &l, &ch);\n      s[l] = ch;\n      temps = \"\";\n      int bkt = l/SQRN;\n      int tempr = min(slen, (bkt+1)*SQRN-1);\n      for(int i=max(1,bkt*SQRN); i<=tempr; ++i) {\n        temps += s[i];\n      }\n      SA[bkt].build(temps);\n    }\n    else {\n      scanf(\"%d %d %s\", &l, &r, &sq[1]);\n      int sqlen = strlen(&sq[1]);\n      if(sqlen >= SQRN || r-l <= 2*SQRN) {\n        printf(\"%d\\n\", computeBrute(l, r, sqlen));\n      }\n      else {\n        int lbkt = l/SQRN, rbkt = r/SQRN, ans = 0;\n        for(int i=lbkt+1; i<rbkt; ++i) {\n          ans += SA[i].run();\n        }\n        ans += computeBrute(l, (lbkt+1)*SQRN-1, sqlen);\n        ans += computeBrute(rbkt*SQRN, r, sqlen);\n        for(int i=lbkt+1; i<=rbkt; ++i) {\n          ans += computeBrute(max(l, i*SQRN - sqlen + 1), min(r, i*SQRN + sqlen - 2), sqlen);\n        }\n        printf(\"%d\\n\", ans);\n      }\n    }\n  }\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "string suffix structures",
      "strings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "914",
    "index": "G",
    "title": "Sum the Fibonacci",
    "statement": "You are given an array $s$ of $n$ non-negative integers.\n\nA 5-tuple of integers $(a, b, c, d, e)$ is said to be valid if it satisfies the following conditions:\n\n- $1 ≤ a, b, c, d, e ≤ n$\n- $(s_{a}$ | $s_{b})$ & $s_{c}$ & $(s_{d}$ ^ $s_{e}) = 2^{i}$ for some integer $i$\n- $s_{a}$ & $s_{b} = 0$\n\nHere, '|' is the bitwise OR, '&' is the bitwise AND and '^' is the bitwise XOR operation.\n\nFind the sum of $f(s_{a}$|$s_{b}) * f(s_{c}) * f(s_{d}$^$s_{e})$ over all valid 5-tuples $(a, b, c, d, e)$, where $f(i)$ is the $i$-th Fibonnaci number ($f(0) = 0, f(1) = 1, f(i) = f(i - 1) + f(i - 2)$).\n\nSince answer can be is huge output it modulo $10^{9} + 7$.",
    "tutorial": "Apologies, we didn't expect an $O(3^{17})$ solution. The expected solution was as follows. Let $A[i]$ be the number of pairs $(x, y)$ in the array such that their bitwise OR is $i$ and $x&y = 0$, multiplied by $Fib[i]$. This can be done using subset convolution. Let $B[i]$ be the count of each element in array, multiplied by $Fib[i]$. Let $C[i]$ be the number of pairs $(x, y)$ such that their bitwise xor is $i$, multiplied by $Fib[i]$. This can be done using Xor convolution. Let $D$ be the And Convolution of $A$, $B$, and $C$. Then the answer is given by the expression $\\textstyle\\sum_{i=0}^{16}D[2^{i}]$. Complexity: $O(2^{17} * (17^{3}))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define ll long long\n#define db long double\n#define ii pair<int,int>\n#define vi vector<int>\n#define fi first\n#define se second\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(),(a).end()\n#define pb push_back\n#define mp make_pair\n#define FN(i, n) for (int i = 0; i < (int)(n); ++i)\n#define FEN(i,n) for (int i = 1;i <= (int)(n); ++i)\n#define rep(i,a,b) for(int i=a;i<b;i++)\n#define repv(i,a,b) for(int i=b-1;i>=a;i--)\n#define SET(A, val) memset(A, val, sizeof(A))\ntypedef tree<int ,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set ;\n// order_of_key (val): returns the no. of values less than val\n// find_by_order (k): returns the kth largest element.(0-based)\n#define TRACE\n#ifdef TRACE\n#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)\n  template <typename Arg1>\n  void __f(const char* name, Arg1&& arg1){\n    cerr << name << \" : \" << arg1 << std::endl;\n  }\n  template <typename Arg1, typename... Args>\n  void __f(const char* names, Arg1&& arg1, Args&&... args){\n    const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << \" : \" << arg1<<\" | \";__f(comma+1, args...);\n  }\n#else\n#define trace(...)\n#endif\nconst int L = 17 ;\nconst int L2 = 1<<L ;\nconst int mod = 1e9+7 ;\nint sbits[L2] ;\nvi oddbits ;\ninline int add(int x,int y)\n{\n  x+=y;\n  if(x>=mod) x-=mod;\n  if(x<0) x+=mod;\n  return x;\n}\ninline int mult(int x,int y)\n{\n  ll tmp=(ll)x*y;\n  if(tmp>=mod) tmp%=mod;\n  return tmp;\n}\ninline int pwmod(int x,int y)\n{\n  int ans=1;\n  while(y){if(y&1)ans=mult(ans,x);y>>=1;x=mult(x,x);}\n  return ans;\n}\nvector<ii> nus[L] ;\nvoid zeta(int A[L2])\n{\n  FN(i,L)\n  {\n    for(ii m:nus[i]) A[m.fi]=add(A[m.fi],A[m.se]) ;\n  }\n}\n\nvoid meu(int A[L2])\n{\n    for(int i:oddbits) A[i] = mod - A[i] ;\n    zeta(A) ;\n  for(int i:oddbits) A[i] = mod - A[i] ;\n}\nvoid conv(int A[L2],int B[L2])\n{\n     zeta(A), zeta(B);//return\n     FN(i,L2) A[i]=mult(A[i],B[i]);\n     meu(A);\n}\nint t[L+1][L2],t1[L2] ;\nvoid subsetconv(int A[L2],int ans[L2])\n{\n  FN(i,L2) t[sbits[i]][i] = A[i] ;\n  FN(i,L+1) zeta(t[i]) ;\n  FN(c,L+1) FN(a,c+1)\n    {\n    int *t2 = t[a], *t3 = t[c-a] ;\n    FN(i,L2) t1[i]=mult(t2[i],t3[i]) ;\n    meu(t1) ;\n        FN(i,L2) if(sbits[i] == c) ans[i]=add(ans[i],t1[i]) ;\n    }\n}\nvector<ii> su[L] ;\n\nvoid transform(int p[L2],bool inv=false){ int u,v;\nfor(int len=1,l=2;l<=L2;len<<=1,l<<=1)for(int\ni=0;i<L2;i+=l) FN(j,len){\nu=p[i+j],v=p[i+j+len] ;\nif(inv) {p[i+j]=add(u,v),p[i+j+len]=add(u,-v);}\nelse {p[i+j]=add(u,v),p[i+j+len]=add(u,-v);}}\nif(inv){int d=pwmod(L2,mod-2);FN(i,L2)p[i]=mult(p[i],d);} }\n\nint cnt[L2],fib[L2],A[L2],B[L2],C[L2],a[L2],b[L2],c[L2] ;\n\nint main()\n{\n  std::ios::sync_with_stdio(false);\n  cin.tie(NULL) ; cout.tie(NULL) ;\n  FN(i,L2)\n  {\n    sbits[i] = __builtin_popcount(i) ;\n    if(sbits[i] & 1) oddbits.emplace_back(i) ;\n    FN(j,L)\n    {\n      if(i&(1<<j)) nus[j].emplace_back(mp(i,i^(1<<j))) ;\n      if((i&(1<<j)) == 0) su[j].emplace_back(mp(i,i^(1<<j))) ;\n    }\n  }\n  FN(i,L) reverse(all(su[i])) ;\n  fib[1] = 1 ; rep(i,2,L2) fib[i] = add(fib[i-1],fib[i-2]) ;\n\n  int N,x ; cin>>N ;\n  FN(i,N)\n  {\n    cin>>x, ++cnt[x] ;\n  }\n\n  subsetconv(cnt,A) ;\n  FN(i,L2) A[i]=mult(A[i],fib[i]) ;\n\n  FN(i,L2) B[i]=mult(cnt[i],fib[i]);\n  FN(i,L2) C[i]=cnt[i] ;\n  transform(C) ;\n  FN(i,L2) C[i]=mult(C[i],C[i]) ;\n  transform(C,1) ;\n  FN(i,L2) C[i]=mult(C[i],fib[i]) ;\n  int ans = 0 ;\n  FN(p,L)\n  {\n    FN(i,L2) a[i]=b[i]=c[i]=0 ;\n    for(ii m:nus[p]) a[m.se]=A[m.fi],b[m.se]=B[m.fi],c[m.se]=C[m.fi] ;\n    FN(i,L)\n    {\n      for(ii m:su[i])\n      {\n        a[m.fi]=add(a[m.fi],a[m.se]) ;\n        b[m.fi]=add(b[m.fi],b[m.se]) ;\n        c[m.fi]=add(c[m.fi],c[m.se]) ;\n      }\n    }\n    FN(i,L2) a[i]=mult(a[i],mult(b[i],c[i])) ;\n    meu(a) ;\n    ans = add(ans,a[(1<<L)-1]) ;\n  }\n  ans = ans == 0 ? 0 : mod - ans ;\n  cout << ans << \"\\n\" ;\n  return 0 ;\n}",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "914",
    "index": "H",
    "title": "Ember and Storm's Tree Game",
    "statement": "Ember and Storm play a game. First, Ember picks a labelled tree $T$ of $n$ vertices, such that the degree of every vertex is at most $d$. Then, Storm picks two distinct vertices $u$ and $v$ in this tree and writes down the labels of the vertices in the path from $u$ to $v$ in a sequence $a_{1}, a_{2}... a_{k}$. Finally, Ember picks any index $i$ ($1 ≤ i < k$) in the array. Now he performs one of the following two operations exactly once:\n\n- flip the subrange $[i + 1, k]$ and add $a_{i}$ to it. After this, the sequence becomes $a_{1}, ... a_{i}, a_{k} + a_{i}, a_{k - 1} + a_{i}, ... a_{i + 1} + a_{i}$\n- negate the subrange $[i + 1, k]$ and add $a_{i}$ to it. i.e., the array becomes $a_{1}, ... a_{i}, - a_{i + 1} + a_{i}, - a_{i + 2} + a_{i}, ... - a_{k} + a_{i}$\n\nEmber wins if the array is monotonically increasing or decreasing after this. Otherwise Storm wins.\n\nThe game can be described by the tuple $(T, u, v, i, op)$ where $op$ is «flip» or «negate» depending on the action Ember chose in the last turn. Find the number of tuples that can occur if Ember and Storm play optimally. When they play optimally, if there are multiple moves by which they are guaranteed to win, then they may play any of the winning moves. Otherwise, if someone loses no matter what they play, then they may play any of the possible moves.\n\nReport the answer modulo $m$.",
    "tutorial": "Ember wins if the path chosen by Storm is monotonic or bitonic. In this case, there can be two $(i, op)$ pairs. Let $S$ be the set of trees having $n$ vertices in which all paths are bitonic or monotonic. We need to find $2n(n - 1)|S|$. For every tree in $S$, there exists at least one vertex such that every path starting or ending at that vertex is monotonically increasing or decreasing. First, let's count the number of rooted trees such that all paths starting at the root are increasing. Later we'll combine this with trees having decreasing paths. Let $tree[i][deg]$ be the number of trees having $i$ vertices and maximum degree $d$ such that all paths starting at vertex $1$ are monotonically increasing and the degree of the vertex $1$ is $deg$. We can find this quantity by a kind of knapsack DP in $O(n^{3}\\log{n})$, as follows. We can construct a tree of $k + i \\cdot j$ vertices and degree of root $deg + j$ by taking a tree of $k$ vertices having root degree $deg$ and attaching $j$ trees of $i$ vertices each to its root. Let the set of vertices be $V = {1, ... k + i \\cdot j}$. Initially we remove $k$ vertices from $V$ and use these vertices to construct the tree of $k$ vertices. Let $W$ be the set of remaining vertices. We partition $W$ into $j$ subsets of $i$ vertices each. Sort these subsets by their minimum element. Now we make $j$ trees of $i$ vertices each, and use the $l$-th set of vertices to construct the $l$-th tree. Therefore, the number of ways to do this is: $C\\equiv\\ {\\textstyle\\frac{(k+i\\cdot j-1)!t r e e^{\\textstyle\\left[k\\right]\\left[d e g|t r e e[i\\right]\\left[a n y\\right]^{3}}}{\\left(k-1\\right)!(i!)j}}$ where $tree[i][any]$ is the number of trees of $i$ vertices with any root degree from $1$ to $d - 1$. Note that there is a bijection from trees in which all paths from root are increasing and trees in which all paths from root are decreasing. ($v\\mapsto n-v+1$) Note that $tree[i + 1][j] \\cdot tree[n - i][k]$ is the number of trees such that all paths starting at the root are monotonic, and there are $i$ vertices lying on the increasing paths and there are $n - i - 1$ vertices lying on the decreasing paths, and the degree of the root is $j + k$ Therefore the quantity $a=\\sum_{i=0}^{n-1}\\sum_{j+k\\leq d}t r e e[i+1][j]\\cdot t r e e[n-i][k]$ is the number of rooted trees of $n$ vertices such that all paths starting at the root are monotonically increasing or decreasing. However, we want to count unrooted trees. Note that if a tree in $S$ has $k$ possible roots, then these roots form a chain of consecutive numbers with an increasing tree of size $i$ on the larger end of the chain and a decreasing tree of size $n - k - i$ on the smaller end of the chain. Such a tree gets counted $k$ times in $a$. But for all of these roots except one, there is exactly one child of the root smaller than it. Therefore the total number of unrooted trees is $|S|=\\sum_{i=0}^{n-1}\\sum_{j+k<d,k\\neq1}t r e e[i+1][j]\\cdot t r e e[n-i][k]$ Time Complexity: $O(n^{3}\\log{n})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nll mod;\nconst int maxn = 2e2 + 2;\nll tree[maxn][maxn][maxn];\nll c[maxn][maxn];\n\nint main() {\n  ios::sync_with_stdio(false);\n\n  int n, d;\n  cin >> n >> d >> mod;\n\n  c[0][0] = 1;\n  for (int i = 1; i <= n; i++) {\n    c[i][0] = 1;\n    for (int j = 1; j <= i; j++) {\n      c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod;\n    }\n  }\n\n  tree[1][1][0] = 1;\n\n  for (int i = 1; i < n; i++) { // adding trees of size i\n    for (int j = 1; j <= n; j++) {\n      for (int k = 0; k <= d; k++) {\n        tree[i + 1][j][k] = tree[i][j][k];\n      }\n    }\n    ll tree_i = 0;\n    for (int j = 0; j < d; j++) {\n      tree_i = (tree_i + tree[i][i][j]) % mod;\n    }\n\n    ll ways = 1;\n    for (int j = 1; i*j <= n && j <= d; j++) { // adding j such trees\n      ways = (ways * c[i*j - 1][i - 1]) % mod; // ((ij)! tree[i]^(j-1))/(i!^j j!)\n      for (int k = 1; k + i*j <= n; k++) { // adding to trees of size k\n        ll cc = (ways * c[k + i*j - 1][k - 1]) % mod;\n        for (int deg = 0; deg + j <= d; deg++) {\n          tree[i + 1][k + i*j][deg + j] = (tree[i + 1][k + i*j][deg + j] + cc*((tree[i][k][deg]*tree_i) % mod)) % mod;\n        }\n      }\n      ways = (ways * tree_i) % mod;\n    }\n  }\n\n  ll total_trees = 0;\n  for (int i = 0; i <= n - 1; i++) { // there are i vertices lying on paths increasing from the root\n    for (int j = 0; j <= d; j++) {\n      for (int k = 0; j + k <= d; k++) {\n        if (k == 1) {\n          continue;\n        }\n        total_trees = (total_trees + ((tree[n][i + 1][j]*tree[n][n - i][k]) % mod)) % mod;\n      }\n    }\n  }\n\n  cout << (2*((n*(n-1)) % mod)*total_trees) % mod << '\\n';\n\n  return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "games",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "915",
    "index": "A",
    "title": "Garden",
    "statement": "Luba thinks about watering her garden. The garden can be represented as a segment of length $k$. Luba has got $n$ buckets, the $i$-th bucket allows her to water some continuous subsegment of garden of length \\textbf{exactly} $a_{i}$ each hour. \\textbf{Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden}.\n\nLuba has to choose \\textbf{one} of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length $a_{i}$ if she chooses the $i$-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.\n\nSee the examples for better understanding.",
    "tutorial": "In this problem we just need to find maximum divisor of $k$ that belongs to array $a$. Let's call it $r$. Then we need to print $\\displaystyle{\\frac{k}{r}}$.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "915",
    "index": "B",
    "title": "Browser",
    "statement": "Luba is surfing the Internet. She currently has $n$ opened tabs in her browser, indexed from $1$ to $n$ from left to right. The mouse cursor is currently located at the $pos$-th tab. Luba needs to use the tabs with indices from $l$ to $r$ (inclusive) for her studies, and she wants to close all the tabs that don't belong to this segment as fast as possible.\n\nEach second Luba can either try moving the cursor to the left or to the right (if the cursor is currently at the tab $i$, then she can move it to the tab $max(i - 1, a)$ or to the tab $min(i + 1, b)$) or try closing all the tabs to the left or to the right of the cursor (if the cursor is currently at the tab $i$, she can close all the tabs with indices from segment $[a, i - 1]$ or from segment $[i + 1, b]$). In the aforementioned expressions $a$ and $b$ denote the minimum and maximum index of an unclosed tab, respectively. For example, if there were $7$ tabs initially and tabs $1$, $2$ and $7$ are closed, then $a = 3$, $b = 6$.\n\nWhat is the minimum number of seconds Luba has to spend in order to leave \\textbf{only the tabs with initial indices from $l$ to $r$ inclusive} opened?",
    "tutorial": "If $l = 1$ and $r = n$ then the answer is $0$. If $l = 1$ and $r  \\neq  n$ or $l  \\neq  1$ and $r = n$ then answer is $|pos - l| + 1$ or $|pos - r| + 1$ respectively. And in the other case (when $l  \\neq  1$ and $r  \\neq  n$) the answer is $r - l + min(|pos - l|, |pos - r|) + 2$.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "915",
    "index": "C",
    "title": "Permute Digits",
    "statement": "You are given two positive integer numbers $a$ and $b$. Permute (change order) of the digits of $a$ to construct maximal number not exceeding $b$. No number in input and/or output can start with the digit 0.\n\nIt is allowed to leave $a$ as it is.",
    "tutorial": "Let's construct the answer digit by digit starting from the leftmost. Obviously, we are asked to build lexicographically maximal answer so in this order we should choose the greatest digit on each step. Precalc $cnt_{i}$ - number of digits $i$ in number $a$. Iterate over all possible digits starting from the greatest. For each digit check if it's possible to put it in this position. For this you construct minimal suffix (greedily put the lowest digit) and compare the resulting number with number $b$. If it became less or equal then proceed to the next digit. Overall complexity: $O(|a|^{2} \\cdot |AL|)$, where $AL$ is digits from $0$ to $9$.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "915",
    "index": "D",
    "title": "Almost Acyclic Graph",
    "statement": "You are given a directed graph consisting of $n$ vertices and $m$ edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.\n\nCan you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).",
    "tutorial": "The constraits are set in such a way that naive $O(m \\cdot (n + m))$ solution won't pass (unmark every edge one by one and check if graph of marked edges doesn't contain cycles with dfs/bfs). Thus we should somehow limit the number of edges to check. Let's take arbitrary cycle in graph. Do dfs, store the vertex you used to travel to any other vertex and restore edges with this data if cycle is met. With this algo length of cycle will not exceed $n$. Then do the naive algo but check only edges from this cycle. Overall complexity: $O(n \\cdot (n + m))$.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "915",
    "index": "E",
    "title": "Physical Education Lessons",
    "statement": "This year Alex has finished school, and now he is a first-year student of Berland State University. For him it was a total surprise that even though he studies programming, he still has to attend physical education lessons. The end of the term is very soon, but, unfortunately, Alex still hasn't attended a single lesson!\n\nSince Alex doesn't want to get expelled, he wants to know the number of working days left until the end of the term, so he can attend physical education lessons during these days. But in BSU calculating the number of working days is a complicated matter:\n\nThere are $n$ days left before the end of the term (numbered from $1$ to $n$), and initially all of them are working days. Then the university staff sequentially publishes $q$ orders, one after another. Each order is characterised by three numbers $l$, $r$ and $k$:\n\n- If $k = 1$, then all days from $l$ to $r$ (inclusive) become non-working days. If some of these days are made working days by some previous order, then these days still become non-working days;\n- If $k = 2$, then all days from $l$ to $r$ (inclusive) become working days. If some of these days are made non-working days by some previous order, then these days still become working days.\n\nHelp Alex to determine the number of working days left after each order!",
    "tutorial": "Let's store current intervals with non-working days in set sorted by the right border. When new query comes you search for the first interval to have its right border greater or equal than the currect left border and update all intervals to intersect the query (either fully delete or insert back its part which doesn't intersect query). Finally, if $k = 1$ then insert the query into current set. Updates on the number of working days can be done while deleting segments on the fly. Overall complexity: $O(q\\log q)$.",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "915",
    "index": "F",
    "title": "Imbalance Value of a Tree",
    "statement": "You are given a tree $T$ consisting of $n$ vertices. A number is written on each vertex; the number written on vertex $i$ is $a_{i}$. Let's denote the function $I(x, y)$ as the difference between maximum and minimum value of $a_{i}$ on a simple path connecting vertices $x$ and $y$.\n\nYour task is to calculate $\\sum_{i=1}^{n}\\sum_{j=i}^{n}I(i,j)$.",
    "tutorial": "Let's calculate the answer as the difference between sum of maxima and sum of minima over all paths. These sums can be found by the following approach: Consider the sum of maxima. Let's sort all vertices in ascending order of values of $a_{i}$ (if two vertices have equal values, their order doesn't matter). This order has an important property that we can use: for every path, the maximum on this path is written on the vertex that has the greatest position in sorted order. This allows us to do the following: Let's denote as $t(i)$ a tree, rooted at vertex $i$, that is formed by the set of such vertices $j$ that are directly connected to $i$ or some other vertex from the set, and have $a_{j} < a_{i}$. Consider the vertices that are connected to $i$ in this tree. Let's denote them as $v_{1}$, $v_{2}$, ..., $v_{k}$ (the order doesn't matter), and denote by $s_{j}$ the size of the subtree of $v_{j}$ in the tree $t(i)$. Let's try to calculate the number of paths going through $i$ in this tree: $\\sum_{j=1}^{k}s_{j}+1$ paths that have $i$ as its endpoint; $\\sum_{j=2}^{k}\\sum_{x=1}^{j-1}s_{j}\\cdot s_{j}.$ paths (connecting a vertex from subtree of $v_{x}$ to a vertex from subtree of $v_{j}$). So vertex $i$ adds the sum of these values, multiplied by $a_{i}$, to the sum of maxima. To calculate these sums, we will use the following algorithm: Initialize a DSU (disjoint set union), making a set for each vertex. Process the vertices in sorted order. When we process some vertex $i$, find all its already processed neighbours (they will be $v_{1}$, $v_{2}$, ..., $v_{k}$ in $t(i)$). For every neighbour $v_{j}$, denote the size of its set in DSU as $s_{j}$. Then calculate the number of paths going through $i$ using aforementioned formulas (to do it in linear time, use partial sums). Add this number, multiplied by $a_{i}$, to the sum of maxima, and merge $i$ with $v_{1}$, $v_{2}$, ..., $v_{k}$ in DSU. To calculate the sum of minima, you can do the same while processing vertices in reversed order. Time complexity of this solution is $O(n\\log n)$.",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "915",
    "index": "G",
    "title": "Coprime Arrays",
    "statement": "Let's call an array $a$ of size $n$ coprime iff $gcd(a_{1}, a_{2}, ..., a_{n}) = 1$, where $gcd$ is the greatest common divisor of the arguments.\n\nYou are given two numbers $n$ and $k$. For each $i$ ($1 ≤ i ≤ k$) you have to determine the number of coprime arrays $a$ of size $n$ such that for every $j$ ($1 ≤ j ≤ n$) $1 ≤ a_{j} ≤ i$. Since the answers can be very large, you have to calculate them modulo $10^{9} + 7$.",
    "tutorial": "For a fixed upper bound $i$, this is a well-known problem that can be solved using inclusion-exclusion: Let's denote by $f(j)$ the number of arrays with elements in range $[1, i]$ such that $gcd(a_{1}, ..., a_{n})$ is divisible by $j$. Obviously, $f(j)=(\\lfloor{\\frac{i}{j}}\\rfloor)^{n}$. With the help of inclusion-exclusion formula we can prove that the number of arrays with $gcd = 1$ is the sum of the following values over all possible sets $S$: $( - 1)^{|S|}f(p(S))$, where $S$ is some set of prime numbers (possibly an empty set), and $p(S)$ is the product of all elements in the set. $f(p(S))$ in this formula denotes the number of arrays such that their $gcd$ is divisible by every number from set $S$. However, the number of such sets $S$ is infinite, so we need to use the fact that $f(j) = 0$ if $j > i$. With the help of this fact, we can rewrite the sum over every set $S$ in such a way: $\\sum_{j=1}^{i}\\mu(j)f(j)$, where $ \\mu  (j)$ is $0$ if there is no any set of prime numbers $S$ such that $p(S) = j$, $| \\mu  (j)| = 1$ if this set $S$ exists, and the sign is determined by the size of $S$ ($ \\mu  (j) = 1$ if $|S|$ is even, otherwise $ \\mu  (j) = - 1$). An easier way to denote and calculate $ \\mu  (j)$ is the following (by the way, it is called Möbius function): $ \\mu (j) = 0$, if there is some prime number p such that $p^{2}|j$. Otherwise $ \\mu (j) = ( - 1)^{x}$, where $x$ is the number of primes in the factorization of $j$. Okay, so we found a solution for one upper bound $i$, it's $\\sum_{j=1}^{i}\\mu(j)f(j)$. How can we calculate it for every $i$ from $1$ to $k$? Suppose we have calculated all values of $f(j)$ for some $i - 1$ and we want to recalculate them for $i$. The important fact is that these values change (and thus need recalculation) only for the numbers $j$ such that $j|i$. So if we recalculate only these values $f(j)$ (and each recalculation can be done in $O(1)$ time if we precompute the $x^{n}$ for every $x\\in[1,k]$), then we will have to do only $O(k\\log k)$ recalculations overall.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "916",
    "index": "A",
    "title": "Jamie and Alarm Snooze",
    "statement": "Jamie loves sleeping. One day, he decides that he needs to wake up at exactly $hh: mm$. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every $x$ minutes until $hh: mm$ is reached, and only then he will wake up. He wants to know what is the smallest number of times he needs to press the snooze button.\n\nA time is considered lucky if it contains a digit '$7$'. For example, $13: 07$ and $17: 27$ are lucky, while $00: 48$ and $21: 34$ are not lucky.\n\nNote that it is not necessary that the time set for the alarm and the wake-up time are on the same day. It is guaranteed that there is a lucky time Jamie can set so that he can wake at $hh: mm$.\n\nFormally, find the smallest possible non-negative integer $y$ such that the time representation of the time $x·y$ minutes before $hh: mm$ contains the digit '$7$'.\n\nJamie uses 24-hours clock, so after $23: 59$ comes $00: 00$.",
    "tutorial": "Let's use brute force the find the answer. We first set the alarm time as $hh: mm$ and initialize the answer as 0. While the time is not lucky, set the alarm time to $x$ minute before and add 1 to the answer. Why does this solution run in time? As $x  \\le  60$, $hh$ decrease at most $1$ for every iteration. Also, after at most 60 iterations, $hh$ must decrease at least once. All time representation that $hh = 07$ (07:XX) is lucky so at most 24 times decrement of $hh$ will lead to a lucky time. Therefore, the max. number of iteration possible is $24 * 60 = 1440$ which is very small for 1 sec TL. In fact, the largest possible answer is $390$ where $x = 2$, $hh = 06$ and $mm = 58$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long lint; typedef pair<int, int> ii;\nconst int MOD = 1'000'000'007, MOD2 = 1'000'000'009;\nconst int INF = 0x3f3f3f3f; const lint BINF = 0x3f3f3f3f3f3f3f3fLL;\n \nint x, n, m;\n \nint solve(){\n\tcin >> x >> n >> m;\n\tint ti = n * 60 + m;\n\tfor(int i=0;;i++){\n\t\tint h = ti / 60, m = ti % 60;\n\t\tif(h / 10 == 7 || h % 10 == 7 || m / 10 == 7 || m % 10 == 7)\n\t\t \treturn cout << i << endl, 0;\n\t\tti = (ti - x + 1440) % 1440;\n\t}\n\treturn 0;\n}\n \nint main(){\n\tios::sync_with_stdio(0);\n\t// int t; cin >> t; while(t--)\n\tsolve();\n\t// cout << (solve() ? \"YES\" : \"NO\") << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "916",
    "index": "B",
    "title": "Jamie and Binary Sequence (changed after round)",
    "statement": "Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:\n\nFind $k$ integers such that the sum of two to the power of each number equals to the number $n$ and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one.\n\nTo be more clear, consider all integer sequence with length $k$ $(a_{1}, a_{2}, ..., a_{k})$ with $\\textstyle\\sum_{i=1}^{k}2^{a_{i}}=n$. Give a value $y=\\operatorname*{max}_{1\\leq i\\leq k}a_{i}$ to each sequence. Among all sequence(s) that have the minimum $y$ value, output the one that is the lexicographically largest.\n\nFor definitions of powers and lexicographical order see notes.",
    "tutorial": "The main idea of the solution is $2^{x} = 2 \\cdot 2^{x - 1}$, that means you can replace 1 $x$ element with 2 $(x - 1)$ elements. To start with, express $n$ in binary - powers of two. As we can only increase the number of elements, there is no solution if there exists more than $k$ elements. Let's fix the $y$ value first. Observe that we can decrease the $y$ value only if all $y$ can be changed to $y - 1$. So we scan from the largest power and try to break it down if doing so does not produce more than $k$ elements. After $y$ is fixed, we can greedily decrease the smallest element while the number of elements is less than $k$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long lint; typedef pair<int, int> ii;\nconst int MOD = 1'000'000'007, MOD2 = 1'000'000'009;\nconst int INF = 0x3f3f3f3f; const lint BINF = 0x3f3f3f3f3f3f3f3fLL;\n \nlint n;\nint m = 0, k;\n \nmap<int, int> cnt;\n \nint solve(){\n\tcin >> n >> k;\n\tfor(int i=0;i<=63;i++) if((n >> i) & 1) cnt[i]++, m++;\n\tif(m > k) return cout << \"No\" << endl, 0;\n\tfor(int i=63;i>=-63;i--){\n\t\tif(m + cnt[i] <= k)\n\t\t\tm += cnt[i], cnt[i - 1] += cnt[i] * 2, cnt[i] = 0;\n\t\telse\n\t\t\tbreak;\n\t}\n\tcout << \"Yes\" << endl;\n\tmultiset<int> ms;\n\tfor(int i=63;i>=-63;i--) for(int j=0;j<cnt[i];j++) ms.insert(i);\n\twhile(ms.size() < k){\n\t\tint u = *ms.begin();\n\t\tms.erase(ms.begin());\n\t\tms.insert(u - 1); ms.insert(u - 1);\n\t}\n\tfor(auto it=ms.rbegin();it!=ms.rend();it++) cout << *it << \" \";\n\tcout << endl;\n    return 0;\n}\n \nint main(){\n\tios::sync_with_stdio(0);\n\t// int t; cin >> t; while(t--)\n\tsolve();\n\t// cout << (solve() ? \"YES\" : \"NO\") << endl;\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "916",
    "index": "C",
    "title": "Jamie and Interesting Graph",
    "statement": "Jamie has recently found undirected weighted graphs with the following properties very interesting:\n\n- The graph is connected and contains exactly $n$ vertices and $m$ edges.\n- All edge weights are integers and are in range $[1, 10^{9}]$ inclusive.\n- The length of shortest path from $1$ to $n$ is a prime number.\n- The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.\n- The graph contains no loops or multi-edges.\n\nIf you are not familiar with some terms from the statement you can find definitions of them in notes section.\n\nHelp Jamie construct any graph with given number of vertices and edges that is interesting!",
    "tutorial": "First, observe that only $n - 1$ edges are required to fulfil the requirement, so we will make the other $m - n + 1$ edges with a very large number so they would not contribute to the shortest path or the MST. Now, the problem is reduced to building a tree with prime weight sum and two nodes in the tree have prime distance. Recall that a path graph is also a tree! If we join $(i, i + 1)$ for all $1  \\le  i < n$, the shortest path will lie on the whole tree. We are left with a problem finding $n - 1$ numbers that sum to a prime. Let's make 1 edge with weight $p - n + 2$ and others with weight $1$. Choosing a prime slightly larger than $n$ (e.g. $100003$) will fulfil the requirement for all cases.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long lint; typedef pair<int, int> ii;\nconst int MOD = 1'000'000'007, MOD2 = 1'000'000'009;\nconst int INF = 0x3f3f3f3f; const lint BINF = 0x3f3f3f3f3f3f3f3fLL;\n \nint n, m;\nconst int LPRIME = 100'003;\nconst int LNUM = 1'000'000'000;\n \nint solve(){\n\tcin >> n >> m;\n\tcout << LPRIME << ' ' << LPRIME << endl;\n\tcout << 1 << ' ' << 2 << ' ' << LPRIME - (n - 2) << endl;\n\tfor(int i=1;i<n-1;i++) cout << i + 1 << ' ' << i + 2 << ' ' << 1 << endl;\n\tint lo = 1, hi = 3;\n\tfor(int i=0;i<m-(n-1);i++){\n\t\tcout << lo << ' ' << hi << ' ' << LNUM << endl;\n\t\thi++;\n\t\tif(hi > n) lo++, hi = lo + 2;\n\t}\n\treturn 0;\n}\n \nint main(){\n\tios::sync_with_stdio(0);\n\t// int t; cin >> t; while(t--)\n\tsolve();\n\t// cout << (solve() ? \"YES\" : \"NO\") << endl;\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "916",
    "index": "D",
    "title": "Jamie and To-do List",
    "statement": "Why I have to finish so many assignments???\n\nJamie is getting very busy with his school life. He starts to forget the assignments that he has to do. He decided to write the things down on a to-do list. He assigns a value priority for each of his assignment \\textbf{(lower value means more important)} so he can decide which he needs to spend more time on.\n\nAfter a few days, Jamie finds out the list is too large that he can't even manage the list by himself! As you are a good friend of Jamie, help him write a program to support the following operations on the to-do list:\n\n- $set a_{i} x_{i}$ — Add assignment $a_{i}$ to the to-do list if it is not present, and set its priority to $x_{i}$. If assignment $a_{i}$ is already in the to-do list, its priority \\textbf{is changed} to $x_{i}$.\n- $remove a_{i}$ — Remove assignment $a_{i}$ from the to-do list if it is present in it.\n- $query a_{i}$ — Output the number of assignments that are more important (have a \\textbf{smaller} priority value) than assignment $a_{i}$, so Jamie can decide a better schedule. Output $ - 1$ if $a_{i}$ is not in the to-do list.\n- $undo d_{i}$ — Undo all changes that have been made in the previous $d_{i}$ days (not including the day of this operation)\n\nAt day $0$, the to-do list is empty. In each of the following $q$ days, Jamie will do \\textbf{exactly one} out of the four operations. If the operation is a $query$, you should \\textbf{output the result of the query before proceeding to the next day}, or poor Jamie cannot make appropriate decisions.",
    "tutorial": "Let's solve a version that does not consist of undo operation first. The task can be divided to two parts: finding the priority of a string and finding the rank of a priority. Both parts can be solved using trie trees. The first part is basic string trie with get and set operation so I will not describe it here in details. The second part is finding a rank of the number which can be supported by a binary trie. To support the undo operation, observe that each operation only add at most 31 nodes to the trie trees. Therefore, we can make use the idea of persistent data structure and store all versions by reusing old versions of the data structure with pointers. Remember to flush the output after each query operation. As pointed out by some of you, there exists alternative solutions using persistent dynamic segment trees.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long lint; typedef pair<int, int> ii;\nconst int MOD = 1'000'000'007, MOD2 = 1'000'000'009;\nconst int INF = 0x3f3f3f3f; const lint BINF = 0x3f3f3f3f3f3f3f3fLL;\n \nstruct StringTrie{\n \n\tStringTrie *chi[26];\n\tint dat;\n \n\tStringTrie(){\n\t\tfor(int i=0;i<26;i++) chi[i] = nullptr;\n\t\tdat = -1;\n\t}\n \n\tStringTrie(StringTrie *old){\n\t\tfor(int i=0;i<26;i++) chi[i] = old->chi[i];\n\t\tdat = old->dat;\n\t}\n \n\tStringTrie *set(string &s, int val, int pos = 0){\n\t\tStringTrie *rt = new StringTrie(this);\n\t\tif(pos >= s.size()){\n\t\t\trt->dat = val;\n\t\t}else{\n\t\t\tint v = s[pos] - 'a';\n\t\t\tif(!chi[v]) chi[v] = new StringTrie();\n\t\t\trt->chi[v] = chi[v]->set(s, val, pos + 1);\n\t\t}\n\t\treturn rt;\n\t}\n \n\tint get(string &s, int pos = 0){\n\t\tif(pos >= s.size()){\n\t\t\treturn dat;\n\t\t}else{\n\t\t\tint v = s[pos] - 'a';\n\t\t\tif(!chi[v]) return -1;\n\t\t\treturn chi[v]->get(s, pos + 1);\n\t\t}\n\t}\n \n};\n \nstruct BinaryTrie{\n \n\tBinaryTrie *chi[2];\n\tint dat;\n \n\tBinaryTrie(){\n\t\tchi[0] = chi[1] = nullptr;\n\t\tdat = 0;\n\t}\n \n\tBinaryTrie(BinaryTrie *old){\n\t\tchi[0] = old->chi[0];\n\t\tchi[1] = old->chi[1];\n\t\tdat = old->dat;\n\t}\n \n\tBinaryTrie *add(int s, int val, int pos = 30){\n\t\tBinaryTrie *rt = new BinaryTrie(this);\n\t\trt->dat += val;\n\t\tif(pos >= 0){\n\t\t\tint v = (s >> pos) & 1;\n\t\t\tif(!chi[v]) chi[v] = new BinaryTrie();\n\t\t\trt->chi[v] = chi[v]->add(s, val, pos - 1);\n\t\t}\n\t\treturn rt;\n\t}\n \n\tint get(int s, int pos = 30){\n\t\tif(pos < 0){\n\t\t\treturn 0;\n\t\t}else{\n\t\t\tint v = (s >> pos) & 1;\n\t\t\tif(v){\n\t\t\t\tint ans = 0;\n\t\t\t\t// add 0\n\t\t\t\tif(chi[0]) ans += chi[0]->dat;\n\t\t\t\t// query 1\n\t\t\t\tif(chi[1]) ans += chi[1]->get(s, pos - 1);\n\t\t\t\treturn ans;\n\t\t\t}else{\n\t\t\t\t// query 0\n\t\t\t\tif(chi[0])\n\t\t\t\t\treturn chi[0]->get(s, pos - 1);\n\t\t\t\telse\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n \n};\n \nint solve(){\n\tint q; cin >> q;\n\tStringTrie **st = new StringTrie*[q + 5];\n\tBinaryTrie **bt = new BinaryTrie*[q + 5];\n\tst[0] = new StringTrie();\n\tbt[0] = new BinaryTrie();\n\tfor(int i=1;i<=q;i++){\n\t\tstring op; cin >> op;\n\t\tif(op == \"set\"){\n\t\t\tstring str; int val;\n\t\t\tcin >> str >> val;\n\t\t\tint x = st[i-1]->get(str);\n\t\t\tst[i] = st[i-1]->set(str, val);\n\t\t\tif(x >= 0){\n\t\t\t\tbt[i] = bt[i-1]->add(x, -1);\n\t\t\t\tbt[i] = bt[i]->add(val, 1);\n\t\t\t}else{\n\t\t\t\tbt[i] = bt[i-1]->add(val, 1);\n\t\t\t}\n\t\t}else if(op == \"remove\"){\n\t\t\tstring str; cin >> str;\n\t\t\tint x = st[i-1]->get(str);\n\t\t\tst[i] = st[i-1]->set(str, -1);\n\t\t\tif(x >= 0)\n\t\t\t\tbt[i] = bt[i-1]->add(x, -1);\n\t\t\telse\n\t\t\t\tbt[i] = bt[i-1];\n\t\t}else if(op == \"undo\"){\n\t\t\tint x; cin >> x;\n\t\t\tst[i] = st[i - x - 1];\n\t\t\tbt[i] = bt[i - x - 1];\n\t\t}else{\n\t\t\tst[i] = st[i - 1];\n\t\t\tbt[i] = bt[i - 1];\n\t\t\tstring str; cin >> str;\n\t\t\tint x = st[i]->get(str);\n\t\t\tif(x >= 0)\n\t\t\t\tcout << bt[i]->get(x) << endl;\n\t\t\telse\n\t\t\t\tcout << -1 << endl;\n\t\t}\n\t}\n\treturn 0;\n}\n \nint main(){\n\tios::sync_with_stdio(0);\n\t// int t; cin >> t; while(t--)\n\tsolve();\n\t// cout << (solve() ? \"YES\" : \"NO\") << endl;\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "interactive",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "916",
    "index": "E",
    "title": "Jamie and Tree",
    "statement": "To your surprise, Jamie is the final boss! Ehehehe.\n\nJamie has given you a tree with $n$ vertices, numbered from $1$ to $n$. Initially, the root of the tree is the vertex with number $1$. Also, each vertex has a value on it.\n\nJamie also gives you three types of queries on the tree:\n\n$1 v$ — Change the tree's root to vertex with number $v$.\n\n$2 u v x$ — For each vertex in the subtree of smallest size that contains $u$ and $v$, add $x$ to its value.\n\n$3 v$ — Find sum of values of vertices in the subtree of vertex with number $v$.\n\nA subtree of vertex $v$ is a set of vertices such that $v$ lies on shortest path from this vertex to root of the tree. Pay attention that subtree of a vertex can change after changing the tree's root.\n\nShow your strength in programming to Jamie by performing the queries accurately!",
    "tutorial": "Let's solve the problem without operation 1 first. That means the subtree of a vertex does not change. For operation 2, the subtree of smallest size that contains $u$ and $v$ means the lowest common ancestor ($lca$) of $u$ and $v$, and we update the subtree of $lca$. For operation 3, we query the sum of the subtree rooted at the given vertex. To do this, we can flatten a tree into an one dimensional array by considering the DFS order of the vertices starting from vertex $1$. If a vertex has DFS order $x$ and its subtree has size $y$, then the update/query range is $[x..x + y - 1]$. This can be done by standard data structures, such as binary indexed tree with range update function, or segment tree with lazy propagation. Things get more complicated when the root of the tree $r$ changes. One should notice that in order to reduce time complexity, we should not recalculate everything when $r$ changes. We just need to keep a variable storing the current root. Now let's discuss the two main problems we face (In the following context, subtree of a vertex is defined according to vertex $1$ unless otherwise stated): How to find the LCA of $u$ and $v$ using the precomputed LCA table that assumes the root is vertex $1$? Let's separate the situation into several cases. If both $u$ and $v$ are in the subtree of $r$, then query the LCA directly is fine. If exactly one of $u$ and $v$ is in the subtree of $r$, the LCA must be $r$. If none of $u$ and $v$ is in the subtree of $r$, we can first find the lowest nodes $p$ and $q$ such that $p$ is an ancestor of both $u$ and $r$, and $q$ is an ancestor of both $v$ and $r$. If $p$ and $q$ are different, we choose the deeper one. If they are the same, then we query the LCA directly. Combining the above cases, one may find the LCA is the lowest vertex among $lca(u, v), lca(u, r), lca(v, r)$. After we have found the origin $w$ of update (for query, it is given), how to identify the subtree of a vertex and carry out updates/queries on it? Again, separate the situation into several cases. If $w = r$, update/query the whole tree. If $w$ is in the subtree of $r$, or $w$ isn't an ancestor of $r$, update/query the subtree of $w$. Otherwise, update/query the whole tree, then undo update/exclude the results of the subtree of $w'$, such that $w'$ is a child of $w$ and the subtree of $w'$ contains $r$. The above ideas can be verified by working with small trees on paper.",
    "code": "#include <bits/stdc++.h>\n#define pb push_back\n#define fi first\n#define se second\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\n \nll arr[100010], seg_t[400010], seg_lazy[400010];\nint ord[100010], uord[100010], dep[100010], subt_size[100010], ancs[100010][18], now_ord;\nvector<int> edge[100010];\nint root_now, root_lbound, root_rbound;\n \nvoid dfs(int now, int prev) {\n\tord[now] = now_ord; uord[now_ord] = now; now_ord++;\n\tsubt_size[now] = 1; ancs[now][0] = prev;\n\tfor (int i=0;i<edge[now].size();i++) if (edge[now][i]!=prev) {\n\t\tdep[edge[now][i]] = dep[now] + 1;\n\t\tdfs(edge[now][i], now);\n\t\tsubt_size[now] += subt_size[edge[now][i]];\n\t}\n}\n \nvoid build_seg(int l, int r, int pos) {\n\tif (l==r) {\n\t\tseg_t[pos] = arr[uord[l]];\n\t\treturn;\n\t}\n\tint mid = (l+r)>>1;\n\tbuild_seg(l, mid, 2*pos+1);\n\tbuild_seg(mid+1, r, 2*pos+2);\n\tseg_t[pos] = seg_t[2*pos+1] + seg_t[2*pos+2];\n}\n \nvoid update_seg(int l, int r, int ql, int qr, int pos, ll val) {\n\tif (seg_lazy[pos]) {\n\t\tseg_t[pos] += seg_lazy[pos]*(r-l+1);\n\t\tif (l!=r) {\n\t\t\tseg_lazy[2*pos+1] += seg_lazy[pos];\n\t\t\tseg_lazy[2*pos+2] += seg_lazy[pos];\n\t\t}\n\t\tseg_lazy[pos] = 0;\n\t}\n\tif (ql>r||qr<l) return;\n\tif (ql<=l&&r<=qr) {\n\t\tseg_t[pos] += val*(r-l+1);\n\t\tif (l!=r) {\n\t\t\tseg_lazy[2*pos+1] += val;\n\t\t\tseg_lazy[2*pos+2] += val;\n\t\t}\n\t\treturn;\n\t}\n\tint mid = (l+r)>>1;\n\tupdate_seg(l, mid, ql, qr, 2*pos+1, val);\n\tupdate_seg(mid+1, r, ql, qr, 2*pos+2, val);\n\tseg_t[pos] = seg_t[2*pos+1] + seg_t[2*pos+2];\n}\n \nll query_seg(int l, int r, int ql, int qr, int pos) {\n\tif (seg_lazy[pos]) {\n\t\tseg_t[pos] += seg_lazy[pos]*(r-l+1);\n\t\tif (l!=r) {\n\t\t\tseg_lazy[2*pos+1] += seg_lazy[pos];\n\t\t\tseg_lazy[2*pos+2] += seg_lazy[pos];\n\t\t}\n\t\tseg_lazy[pos] = 0;\n\t}\n\tif (ql>r||qr<l) return 0;\n\tif (ql<=l&&r<=qr) return seg_t[pos];\n\tint mid = (l+r)>>1;\n\treturn query_seg(l, mid, ql, qr, 2*pos+1) + query_seg(mid+1, r, ql, qr, 2*pos+2);\n}\n \nint nth_ancs(int u, int n) {\n\tfor (int i=16;i>=0;i--) if (n&(1<<i)) u = ancs[u][i];\n\treturn u;\n}\n \nint LCA(int u, int v) {\n\tif (dep[u]<dep[v]) swap(u, v);\n\tint dep_dif = dep[u]-dep[v];\n\tu = nth_ancs(u, dep_dif);\n\tif (u==v) return u;\n\tfor (int i=16;i>=0;i--) if (ancs[u][i]!=ancs[v][i]) {\n\t\tu = ancs[u][i];\n\t\tv = ancs[v][i];\n\t}\n\treturn ancs[u][0];\n}\n \nint main() {\n\tios_base::sync_with_stdio(0);\n\tint n, q; cin >> n >> q;\n\troot_now = 1, root_lbound = 0, root_rbound = n-1;\n\tfor (int i=1;i<=n;i++) cin >> arr[i];\n\tfor (int i=0;i<n-1;i++) {\n\t\tint a, b; cin >> a >> b;\n\t\tedge[a].pb(b); edge[b].pb(a);\n\t}\n\tdfs(1, 0); build_seg(0, n-1, 0);\n\tfor (int j=1;j<17;j++) for (int i=1;i<=n;i++) ancs[i][j] = ancs[ancs[i][j-1]][j-1];\n\tfor (int i=0;i<q;i++) {\n\t\tint op; cin >> op;\n\t\tif (op==1) {\n\t\t\tcin >> root_now;\n\t\t\troot_lbound = ord[root_now]; root_rbound = ord[root_now]+subt_size[root_now]-1;\n\t\t} else if (op==2) {\n\t\t\tint u, v; ll c; cin >> u >> v >> c;\n\t\t\tint in_subt_cnt = 0, origin;\n\t\t\tif (root_lbound<=ord[u]&&ord[u]<=root_rbound) in_subt_cnt++;\n\t\t\tif (root_lbound<=ord[v]&&ord[v]<=root_rbound) in_subt_cnt++;\n\t\t\tif (in_subt_cnt==2) {\n\t\t\t\torigin = LCA(u, v);\n\t\t\t} else if (in_subt_cnt==1) {\n\t\t\t\torigin = root_now;\n\t\t\t} else {\n\t\t\t\tint x = LCA(u, root_now), y = LCA(v, root_now), z = LCA(u, v);\n\t\t\t\torigin = dep[x]>dep[y]? x: y;\n\t\t\t\torigin = dep[z]>dep[origin]? z: origin;\n\t\t\t}\n\t\t\tif (origin==root_now) {\n\t\t\t\tupdate_seg(0, n-1, 0, n-1, 0, c);\n\t\t\t} else if (root_lbound<ord[origin]&&ord[origin]<=root_rbound) {\n\t\t\t\tupdate_seg(0, n-1, ord[origin], ord[origin]+subt_size[origin]-1, 0, c);\n\t\t\t} else if (ord[origin]<ord[root_now]&&ord[root_now]<=ord[origin]+subt_size[origin]-1) {\n\t\t\t\tupdate_seg(0, n-1, 0, n-1, 0, c);\n\t\t\t\tint dep_dif = dep[root_now]-dep[origin];\n\t\t\t\tint undo = nth_ancs(root_now, dep_dif-1);\n\t\t\t\tupdate_seg(0, n-1, ord[undo], ord[undo]+subt_size[undo]-1, 0, -c);\n\t\t\t} else {\n\t\t\t\tupdate_seg(0, n-1, ord[origin], ord[origin]+subt_size[origin]-1, 0, c);\n\t\t\t}\n\t\t} else {\n\t\t\tint origin; cin >> origin;\n\t\t\tll ans;\n\t\t\tif (origin==root_now) {\n\t\t\t\tans = query_seg(0, n-1, 0, n-1, 0);\n\t\t\t} else if (root_lbound<ord[origin]&&ord[origin]<=root_rbound) {\n\t\t\t\tans = query_seg(0, n-1, ord[origin], ord[origin]+subt_size[origin]-1, 0);\n\t\t\t} else if (ord[origin]<ord[root_now]&&ord[root_now]<=ord[origin]+subt_size[origin]-1) {\n\t\t\t\tans = query_seg(0, n-1, 0, n-1, 0);\n\t\t\t\tint dep_dif = dep[root_now]-dep[origin];\n\t\t\t\tint undo = nth_ancs(root_now, dep_dif-1);\n\t\t\t\tans -= query_seg(0, n-1, ord[undo], ord[undo]+subt_size[undo]-1, 0);\n\t\t\t} else {\n\t\t\t\tans = query_seg(0, n-1, ord[origin], ord[origin]+subt_size[origin]-1, 0);\n\t\t\t}\n\t\t\tcout << ans << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "917",
    "index": "A",
    "title": "The Monster",
    "statement": "As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him.\n\nThus, he came up with a puzzle to tell his mom his coordinates. His coordinates are the answer to the following problem.\n\nA string consisting only of parentheses ('(' and ')') is called a bracket sequence. Some bracket sequence are called correct bracket sequences. More formally:\n\n- Empty string is a correct bracket sequence.\n- if $s$ is a correct bracket sequence, then $(s)$ is also a correct bracket sequence.\n- if $s$ and $t$ are correct bracket sequences, then $st$ (concatenation of $s$ and $t$) is also a correct bracket sequence.\n\nA string consisting of parentheses and question marks ('?') is called pretty if and only if there's a way to replace each question mark with either '(' or ')' such that the resulting string is a \\textbf{non-empty} correct bracket sequence.\n\nWill gave his mom a string $s$ consisting of parentheses and question marks (using Morse code through the lights) and his coordinates are the number of pairs of integers $(l, r)$ such that $1 ≤ l ≤ r ≤ |s|$ and the string $s_{l}s_{l + 1}... s_{r}$ is pretty, where $s_{i}$ is $i$-th character of $s$.\n\nJoyce doesn't know anything about bracket sequences, so she asked for your help.",
    "tutorial": "First, let's denote $s[l..r]$ as the substring $s_{l}s_{l + 1}... s_{r}$ of string $s$. Also $s.count(t)$ is the number of occurrences of $t$ in $s$. A string consisting of parentheses and question marks is pretty if and only if: $|s|$ is even. $0  \\le  s[1..i].count('(') + s[1..i].count('?') - s[1..i].count(')')$ for each $1  \\le  i  \\le  |s|$. $0  \\le  s[i..|s|].count(')') + s[i..|s|].count('?') - s[i..|s|].count('(')$ for each $1  \\le  i  \\le  |s|$. Proof: If $s.count('?') = 0$ then $s$ is a correct bracket sequence. Otherwise, let $q$ be an integer between $1$ to $|s|$ such that $s_{q} = '?'$. Lemma: We can replace $s_{q}$ by either '(' or ')' such that the three conditions above remain satisfied. Proof: We'll use proof by contradiction. If we can replace $s_{q}$ by either '(' or ')' such that the conditions remain satisfied, the lemma is proven. Otherwise, the conditions will be violated if we replace $s_{q}$ by '(' or ')'. Let's denote $f(s)$ as $s.count('(') + s.count('?') - s.count(')')$ and $g(s)$ as $s.count(')') + s.count('?') - s.count('(')$. Please note that $f(s) = - g(s) + 2  \\times  s.count('?')$ and $g(s) = - f(s) + 2  \\times  s.count('?')$. By assumption, if we replace $s_{q}$ by '(' the conditions will be violated. By replacing $s_{q}$ the second condition can't be violated, thus the third condition will be violated. So, there's an integer $i$ such that $1  \\le  i  \\le  q$ and $g(t[i..|t|]) < 0$ ($t$ is $s$ after replacing $s_{q}$ by '('). Thus, $g(s[i..|s|]) < 2$. Similarly, there's an integer $j$ such that $q  \\le  j  \\le  |s|$ and $f(s[1..j]) < 2$. Since all three conditions are satisfied for $s$ (by assumption), then $0  \\le  g(s[i..|s|]), f(s[1..j])  \\le  1$. Let's break $s$ into three parts (they could be empty): $a = s[1..(i - 1)]$, $b = s[i..j]$ and $c = s[(j + 1)..|s|]$. $g(s[i..|s|]) = g(b) + g(c)$ and $f(s[1..j]) = f(a) + f(b)$. Since the three conditions are satisfied for $s$, then $0  \\le  g(c), f(a)$. $f(a) + f(b)  \\le  1$ so $f(a) - 1  \\le  - f(b)$. Thus $f(a) - 1  \\le  g(b) - 2  \\times  b.count('?')$, so $f(a) - 1 + 2  \\times  b.count('?')  \\le  g(b)$. So $f(a) - 1 + 2  \\times  b.count('?') + g(c)  \\le  g(b) + g(c)  \\le  1$. So $f(a) - 1 + 2  \\times  b.count('?') + g(c)  \\le  1$. Since $i  \\le  q  \\le  j$, then $2  \\le  2  \\times  b.count('?')$. Also, $0  \\le  g(c), f(a)$. So, $1  \\le  f(a) - 1 + 2  \\times  b.count('?') + g(c)  \\le  1$. So $f(a) - 1 + 2  \\times  b.count('?') + g(c) = 1$. This requires that $f(a) = g(c) = 0$ and $b.count('?') = 1$. Since $f(a)$ and $g(c)$ are even, then $|a|$ and $|c|$ are even, and since $|s|$ is even (first condition), then $|b|$ is also even (because $|s| = |a| + |b| + |c|$). $f(a) = g(c) = 0$ and $0  \\le  f(a) + f(b)$ and $0  \\le  g(b) + g(c)$, thus $0  \\le  f(b), g(b)$. Also, $f(a) + f(b), g(b) + g(c)  \\le  1$, thus $0  \\le  f(b), g(b)  \\le  1$, since $|b|$ is even, $f(b)$ and $g(b)$ are also even, thus, $f(b) = g(b) = 0$. $g(b) = - f(b) + 2  \\times  b.count('?')$ and since $1  \\le  b.count('?')$ then $g(b)  \\neq  0$. Thus, we have $0  \\neq  0$, which is false. So the lemma is true. Using the lemma above, each time we can replace a question mark by parentheses and at the end we get a correct bracket sequence. After proof: Knowing this fact, we can find all such substrings by checking the three conditions. Total time complexity: $O(n^{2})\\,$ where $n = |s|$",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "917",
    "index": "B",
    "title": "MADMAX",
    "statement": "As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with $n$ vertices and $m$ edges. There's a character written on each edge, a lowercase English letter.\n\nMax and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex $v$ to vertex $u$ if there's an outgoing edge from $v$ to $u$). If the player moves his/her marble from vertex $v$ to vertex $u$, the \"character\" of that round is the character written on the edge from $v$ to $u$. There's one additional rule; the ASCII code of character of round $i$ should be \\textbf{greater than or equal} to the ASCII code of character of round $i - 1$ (for $i > 1$). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.\n\nSince the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?\n\nYou have to determine the winner of the game for all initial positions of the marbles.",
    "tutorial": "Denote $dp(v, u, c)$ as the winner of the game (the person that starts it or the other one?, a boolean, true if first person wins) if the first person's marble is initially at vertex $v$ and the second one's initially at $u$ and our set of letters is ${ichar(c), ichar(c + 1), ..., 'z'}$ if $ichar(i) = char('a' + i)$ ($c$ is an integer). Denote $a d j(v)=\\{x;v\\to x\\}$ and $ch(x, y)$ as the character written on edge from $x$ to $y$. Now if there's some $x$ in $adj(v)$ such that $c < int(ch(v, x) - 'a')$ and $dp(u, x, ch(v, x)) = false$, then the first person can move his/her marble to vertex $x$ and win the game, thus $dp(v, u, c) = true$, otherwise it's false. Because the graph is a DAG there's no loop in this dp, thus we can use memoization. The answer for $i, j$ is $dp(i, j, 0)$. Total time complexity: $O(|s i g m a|\\times n\\times(n+m))$",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "917",
    "index": "C",
    "title": "Pollywog",
    "statement": "As we all know, Dart is some kind of creature from Upside Down world. For simplicity, we call their kind pollywogs. Dart and $x - 1$ other pollywogs are playing a game. There are $n$ stones in a row, numbered from $1$ through $n$ from left to right. At most $1$ pollywog may be sitting on each stone at a time. Initially, the pollywogs are sitting on the first $x$ stones (one pollywog on each stone).\n\nDart and his friends want to end up on the last $x$ stones. At each second, the leftmost pollywog should jump to the right. A pollywog can jump at most $k$ stones; more specifically, a pollywog can jump from stone number $i$ to stones $i + 1, i + 2, ... i + k$. A pollywog can't jump on an occupied stone. Jumping a distance $i$ takes $c_{i}$ amounts of energy from the pollywog.\n\nAlso, $q$ stones are special Each time landing on a special stone $p$, takes $w_{p}$ amounts of energy (in addition to the energy for jump) from the pollywog. $w_{p}$ could be negative, in this case, it means the pollywog absorbs $|w_{p}|$ amounts of energy.\n\nPollywogs want to spend as little energy as possible (this value could be negative).\n\nThey're just pollywogs, so they asked for your help. Tell them the total change in their energy, in case they move optimally.",
    "tutorial": "What would we do if $n$ was small? Notice that at any given time if $i$ is the position of the leftmost pollywog and $j$ is the position of the rightmost pollywog, then $j - i < k$. Thus, at any given time there's an $i$ such that all pollywogs are on stones $i, i + 1, ... i + k - 1$, in other words, $k$ consecutive stones. $x$ pollywogs are on $k$ consecutive stones, thus, there are $\\textstyle{{\\binom{k}{x}}$ different ways to sit these pollywogs on $k$ stones, that's about $70$ at most. Denote $dp[i][state]$ as the minimum amount of energy the pollywogs need to end up on stones $i, i + 1, ... i + k - 1$, and their positions are contained in $state$ (there are $\\textstyle{\\binom{k}{x}}$ states in total). We assume $init$ is the initial state (pollywogs on the $x$ first stones) and $final$ is the final state (pollywogs on the $x$ last stones). Thus, we could easily update $dp$ in ${\\cal O}(k)$ (where would the first pollywog jump?) using dynamic programming and this would work in $O(n\\times k\\times{\\bigl(}\\leq_{e}^{k}{\\bigr)}$ since the answer is $dp[n - k + 1][final]$. But $n$ is large, so what we could do is using matrix multiplication (similar to matrix multiplication, but when multiplying two matrices, we use minimum instead of sum and sum instead of multiplication, that means if $C = A  \\times  B$ then $C[i][j] = min(A[i][k] + B[k][j])$ for all $k$) to update the dp, in case $q = 0$ to solve the problem in $O((_{x}^{k})^{3}\\times\\log(n))$. For $q > 0$, we combine the dynamic programming without matrix and with matrix. Note that the special stones only matter in updating the dp when there's a special stone among $i, i + 1, ... i + k - 1$, that means at most for $k  \\times  q$ such $i$, for the rest we could use matrices for updating. Total time complexity: $O(\\log(n){\\binom{k}{x}}^{3}+q k^{2}{\\binom{k}{x}})$",
    "tags": [
      "combinatorics",
      "dp",
      "matrices"
    ],
    "rating": 2900
  },
  {
    "contest_id": "917",
    "index": "D",
    "title": "Stranger Trees",
    "statement": "Will shares a psychic connection with the Upside Down Monster, so everything the monster knows, Will knows. Suddenly, he started drawing, page after page, non-stop. Joyce, his mom, and Chief Hopper put the drawings together, and they realized, it's a labeled tree!\n\nA tree is a connected acyclic graph. Will's tree has $n$ vertices. Joyce and Hopper don't know what that means, so they're investigating this tree and similar trees. For each $k$ such that $0 ≤ k ≤ n - 1$, they're going to investigate all labeled trees with $n$ vertices that share exactly $k$ edges with Will's tree. Two labeled trees are different if and only if there's a pair of vertices $(v, u)$ such that there's an edge between $v$ and $u$ in one tree and not in the other one.\n\nHopper and Joyce want to know how much work they have to do, so they asked you to tell them the number of labeled trees with $n$ vertices that share exactly $k$ edges with Will's tree, for each $k$. The answer could be very large, so they only asked you to tell them the answers modulo $1000000007 = 10^{9} + 7$.",
    "tutorial": "Solution #1: First, for every $K$ such that $0  \\le  K  \\le  N - 1$ we are going to find for every $K$ edges in the original tree we are going to find the number of labeled trees having these $K$ edges, then we will add them all to $res[K]$. But Mr. Author aren't we going to count some tree that has exactly $E$ (where $E > K$) common edges with the original tree in $res[K]$? Yes, that's true. But we only count it $\\textstyle{\\binom{E}{K}}$ times! So, after computing the res array we are going to iterate from $N - 1$ to $0$ assuming that the res is correct for all $J > I$ (our current iteration), and then reduce $r e s[J]\\times\\binom{J}{I}$ (the fixed res) from $res[I]$. Then we'll have the correct value for $res[I]$. But Mr. Author, how are we going to find $res[K]$ in the first place? Let's first find out for a fixed $K$ edges forest, in how ways we connect the remaining vertices to get a tree. Let's look at the components in the forest. Only their sizes are relevant because we can't connect anything inside them. Let the sizes be $sz[0]... sz[N - 1]$. (if you assume that the sizes are all $1$, the number of resulting trees are $N^{N - 2}$ (Kayley's theorem)). To solve this subproblem, let's go to another subproblem. Let's assume that for every additional edge, we know which components it is going to go connect. Then, the number of resulting trees is $\\prod_{i=0}^{N-1}s z[i]^{d[i]}$ where $d[i]$ is the degree of component $i$ (edges between this component and other components). The reason is that we have $sz[v]$ vertices inside component $v$ to give to every edge that has one endpoint in $v$. Ok going back to the parent subproblem. $d[i]$ huh? I've heard that vertex $v$ appears in the Prufer code of a tree $d[v] - 1$ times. so we've gotta multiply the answer by $sz[v]$ every time it appears in Prufer code. It's also multiplied by $\\prod_{i=0}^{N-1}s z[i]$ because we haven't multiplied it one time ($d[v] - 1$ not $d[v]$). But how to make it get multiplied by $sz[v]$ every time component $v$ is chosen? Look at this product. $(sz[0] + sz[1] + ... + sz[N - 1])^{N - 2}$. If in the $i$-th parenthesis $sz[v]$ is chosen, then let the $i$-th place on the Prufer code of the tree connecting the components be the component $v$. The good thing about this product is that if component $v$ has come in the Prufer code $K$ times, then the multiplication of the parenthesis has $sz[v]^{K}$ in it. So it counts exactly what we want to count. ${\\bigl(}\\prod_{i=0}^{N-1}s z[i]{\\bigr)}\\times{\\bigl(}\\sum_{i=0}^{N-1}s z[i]{\\bigr)}^{N-2}$ is the answer for some fixed $K$ edges. $\\sum_{i=0}^{N-1}$ corresponds to $N$ in the original problem and $N - 2$ corresponds to $Number_of_components - 2$. so we want to count $\\left(\\prod_{i=0}^{N-1}s z[i]\\right)\\times\\,N^{n u m b e r}{}_{-}^{o f}{}_{-}^{c o m p o n e n t s-2}$ Okay Mr. Author so how do we count this for every $K$ fixed edges in the original tree. Lets count $dp[top_vertex v][size_of_component_containing_top_vertex s][the_number_of_edges_we_have_fixed e]$ which contains $\\prod_{i=0}^{N-1}s z[i]$ of every component inside $v$'s subtree which doesn't include $v$'s component and $N^{the_number_of_components_not_including_v's}$. We can update this from $v$'s children. Let's add $v$'s children one by one to the $dp$ by assuming that the children we didn't go over don't exist in $v$'s subtree. let's go over $old_dp[v][vs][ve]$ and $dp[u][us][ue]$, we either fix the edge between $u$ and $v$ then it'll add $dp[u][us][ue]  \\times  dp[v][vs][ve]$ to $next_dp[v][us + vs][ve + ue + 1]$ and otherwise it'll add $dp[u][us][ue]  \\times  dp[v][vs][ve]  \\times  N  \\times  us$ to $dp[v][vs][ve + ue]$. We can also divide it by $N^{2}$ at the end with modulo inverses. We can find $res[K]$ with the sum of $dp[root][s][K]  \\times  s  \\times  N$. (with $s = N$ as a corner case). The solution may look that it's $N^{5}$ because it's inside $5$ fors. But it's actually $N^{4}$ if the $us$ and $vs$ fors go until $sz[u]$ and $sz[v]$ (actually only the subtree of $v$ that we've iterated on). So the cost is $sz[u]  \\times  sz[v]  \\times  N^{2}$. Let's look at it like every vertex from $u$'s subtree is handshaking with every vertex of $v$'s subtree and the cost of their handshaking is $N^{2}$. We know that two vertices handshake only once. That's why it'll be $\\textstyle{\\binom{N}{2}}\\times N^{2}$ which is of $O(N^{4})$. Solution #2: Let's define $F(X)$ as the number of spanning trees of the graph $K_{N}$ plus $X - 1$ copies of $T$ (the original tree). If we look at $F(X)$ we'll see that it is actually $\\sum_{i=0}^{N-1}X^{i}\\times n u m b e r_{-}{}^{o f}_{-}e^{i r e e s_{-}}{}^{w i t h}_{-}i_{-}{}^{i}_{-}{}^{c o m m o n_{-}e d g e s_{-}w i t h}_{-}T$ because it has $X^{i}$ ways to choose which of the $X$ multiple edges it should choose for the common edges. So the problem is to find $F$'s coefficients. We can do that by polynomial interpolation if we have $N$ sample answers of $F$. Let's just get $N$ instances of $F$ for $X = 1$ till $X = N$. We can find that using Kirchhoff's matrix tree theorem to find the number of spanning trees of a graph. So the complexity is $O(i n t e r p o l a t i o n)+\\ O(D e t e r m i n a n t\\times N)$. So we have an $O(N^{4})$ complexity. This is how to do it in $N^{2}$ -> (I don't know it yet, I'll update it when I have it ready)",
    "tags": [
      "dp",
      "math",
      "matrices",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "917",
    "index": "E",
    "title": "Upside Down",
    "statement": "As we all know, Eleven has special abilities. Thus, Hopper convinced her to close the gate to the Upside Down World with her mind. Upside down monsters like to move between the worlds, so they are going to attack Hopper and Eleven in order to make them stop. The monsters live in the vines. The vines form a tree with $n$ vertices, numbered from $1$ through $n$. There's a lowercase English letter written in each tunnel (edge).\n\nUpside down is a magical world. There are $m$ types of monsters in upside down, numbered from $1$ through $m$. Each type of monster has a special word that gives them powers. The special word of type $i$ is $s_{i}$. There are $q$ monsters in upside down. Each one is at a junction (vertex) and is going to some other junction. If monster of type $k$ goes from junction $i$ to junction $j$, the power it gains is the number of times it sees its special world ($s_{k}$) consecutively in the tunnels. More formally:\n\nIf $f(i, j)$ is the string we get when we concatenate the letters written in the tunnels on the shortest path from $i$ to $j$, then the power the monster gains is the number of occurrences of $s_{k}$ in $f(i, j)$.\n\nHopper and Eleven want to get prepared, so for each monster, they want to know the power the monster gains after moving.",
    "tutorial": "Assume $t_{i}$ is reverse of $s_{i}$. Use centroid-decomposition. When solving the problem for subtree $S$, assume its centroid is $c$. For a fixed query, assume $v$ and $u$ are both in $S$ and path from $v$ to $u$ goes through the centroid $c$ (this happens exactly one time for each $v$ and $u$). Assume $x$ is string of path from $c$ to $v$ and $y$ is string of path from $c$ to $u$. We should find the number of occurrences of $s_{k}$ in $reverse(x) + y$. If number of occurrences of $s$ in $t$ is $f(s, t)$ then $f(s_{k}, reverse(x) + y) = f(t_{k}, x) + f(s_{k}, y) + A$. First two variables can be calculated using aho-corasick and segment tree. $A$ is the number of occurrences of $s_{k}$ in the path such that some part of it belongs to $reverse(x)$ and some to $y$. So, so far the the time complexity is $O(n\\log^{2}(n))$. Now for counting $A$, first calculate the suffix tree for each string (for each $s_{k}$ and $t_{k}$). A suffix tree is a trie, so let $sf(v, s)$ be the vertex we reach when we ask the string of path from $c$ (root) to $v$ one by in the suffix tree of string $s$. We can calculate this fast for every $v$ and $s$ if we merge this suffix trees into one trie (we do this before we start the centroid-decomposition algorithm in per-process). We associate a value $val$ to each vertex of the trie, initially zero for every vertex. Now we traverse this trie like DFS. When we reach a vertex $x$, we iterate over all suffixes (there are $2(|s_{1}| + ... + |s_{n}|)$ suffixes) that end in $x$ (the suffixes that equal the string of path from root of the trie to vertex $x$), and for each suffix $(s, k)$ (suffix of string $s$ with length $k$), we add $1$ to the $val$ of each vertex in the subtree of the vertex where the suffix $(reverese(s), |s| - k)$ ends and we subtract this number when we're exiting vertex $x$ (in DFS). Now back to the centroid-decomposition, $A$ equals $val$ of vertex in trie where the suffix $(t_{k}, b)$ when in DFS we're at vertex in trie where $(s_{k}, a)$ ends where $a$ is the size of the longest suffix of $s_{k}$ that is a prefix of the string of the path from $c$ (root) to $u$ and similarly, $b$ is the size of the longest suffix of $t_{k}$ that is a prefix of the string of the path from $c$ (root) to $v$. For achieving this goal, we can use persistent segment tree on the starting time-finishing time range of vertices in the trie (or without using persistent segment tree, we could calculate every $A$ after the centroid-decomposition is finished, kind of offline). Total time complexity: $O(N\\log^{2}(N))$ where $N = n + q + |s_{1}| + |s_{2}| + ... + |s_{n}|$.",
    "tags": [
      "data structures",
      "string suffix structures",
      "strings",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "918",
    "index": "A",
    "title": "Eleven",
    "statement": "Eleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly $n$ characters.\n\nHer friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the $i$-th letter of her name should be 'O' (uppercase) if $i$ is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from $1$ to $n$. Fibonacci sequence is the sequence $f$ where\n\n- $f_{1} = 1$,\n- $f_{2} = 1$,\n- $f_{n} = f_{n - 2} + f_{n - 1}$ ($n > 2$).\n\nAs her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.",
    "tutorial": "Calculate the first $x$ Fibonacci sequence elements, where $x$ is the greatest integer such that $f_{x}  \\le  n$. Let $s$ be a string consisting of $n$ lowercase 'o' letters. Then for each $i  \\le  x$, perform $s_{fi}$ = 'O'. The answer is $s$. Total time complexity: ${\\mathcal{O}}(n)$",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "918",
    "index": "B",
    "title": "Radio Station",
    "statement": "As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has $n$ servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form \"command ip;\" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers.\n\nEach ip is of form \"a.b.c.d\" where $a$, $b$, $c$ and $d$ are non-negative integers less than or equal to $255$ (with no leading zeros). The nginx configuration file Dustin has to add comments to has $m$ commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is \"command ip;\" Dustin has to replace it with \"command ip; #name\" where name is the name of the server with ip equal to ip.\n\nDustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.",
    "tutorial": "Save the names and ips of the servers. Then for each command find the server in ${\\mathcal{O}}(n)$ and print its name. Total time complexity: $O(n m)$",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "919",
    "index": "A",
    "title": "Supermarket",
    "statement": "We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $a$ yuan for $b$ kilos (You don't need to care about what \"yuan\" is), the same as $a/b$ yuan for a kilo.\n\nNow imagine you'd like to buy $m$ kilos of apples. You've asked $n$ supermarkets and got the prices. Find the minimum cost for those apples.\n\nYou can assume that there are enough apples in all supermarkets.",
    "tutorial": "We can use greedy algorithm. Obviously, if you can pay the least money for per kilo, you can pay the least money for $m$ kilos. So you can find the minimum of $a_i/b_i$, we say it is $x$. Then $m \\cdot x$ is the final answer. Time complexity: $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n#define N 5010\nusing namespace std; \n \nint n, m, a[N], b[N];\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 1; i <= n; i++){\n\t\tscanf(\"%d%d\", &a[i], &b[i]);\n\t}\n\t\n\tint minA = a[1], minB = b[1];\n\tfor (int i = 2; i <= n; i++){\n\t\tif (minA * b[i] > minB * a[i]){\n\t\t\tminA = a[i];\n\t\t\tminB = b[i];\n\t\t}\n\t}\n\t\n\tprintf(\"%.8lf\\n\", (double) minA * m / (double) minB);\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "919",
    "index": "B",
    "title": "Perfect Number",
    "statement": "We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer.",
    "tutorial": "Let's use brute force the find the answer. You may find the answer is not too large (i.e. not bigger than $2 \\cdot 10^7$), then you can find it in the given time limit. You can check every possible answer from $1$ (or from $19$), until we find the $k$-th perfect integer. That's all what we need to do. :P Time complexity: $\\mathcal{O}(answer)$. :P",
    "code": "def cal(x):\n    ans = 0\n    while (x):\n        ans += x % 10\n        x /= 10\n    return ans\n \nn = input()\nnow = 0\nwhile (n):\n    now += 1\n    if cal(now) == 10:\n        n -= 1\nprint now",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "implementation",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "919",
    "index": "C",
    "title": "Seat Arrangements",
    "statement": "Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.\n\nThe classroom contains $n$ rows of seats and there are $m$ seats in each row. Then the classroom can be represented as an $n \\times m$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $k$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. \\textbf{Two ways are considered different if sets of places that students occupy differs.}",
    "tutorial": "We can find out how many consecutive empty positions in every row and column separately and add them together to form the final answer. If the length of consecutive empty positions is no smaller than $k$, we assume that it is $len$. Then we can add $len-k+1$ to the final answer. But, be careful. When $k=1$, the algorithm shown above is completely wrong. (Why?) So we need to deal with that situation separately. (I guess there will be lots of hacks :P) Time complexity: $\\mathcal{O}(nm)$.",
    "code": "a = raw_input().split()\nn, m, k = int(a[0]), int(a[1]), int(a[2])\nmat = []\n \nfor i in range(n):\n    s = raw_input()\n    mat.append([])\n    for j in range(m):\n        if s[j] == '*':\n            mat[i].append(0)\n        else:\n            mat[i].append(1)\n \nans = 0\nfor i in range(n):\n    res = 0\n    for j in range(m):\n        if mat[i][j]:\n            res += 1\n            if res >= k:\n                ans += 1\n        else:\n            res = 0\n \nfor i in range(m):\n    res = 0\n    for j in range(n):\n        if mat[j][i]:\n            res += 1\n            if res >= k:\n                ans += 1\n        else:\n            res = 0\n \nif k == 1:\n    ans /= 2\n \nprint ans",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "919",
    "index": "D",
    "title": "Substring",
    "statement": "You are given a graph with $n$ nodes and $m$ \\textbf{directed} edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are \"abaca\", then the value of that path is $3$. Your task is find a path whose value is the largest.",
    "tutorial": "It is obvious that we can use dynamic programming algorithm to solve this stupid problem. :P We can make an array $f[i][j]$ to respect when you are at the point $i$, then how many letters $j$ you can get. Note that $i$ is ranging from $1$ to $n$ and $j$ is from $1$ to $26$. Then, you can do this dynamic programming algorithm by topological sorting. Specifically, you can use $deg[i]$ to show how many edges that end at point $i$. First put all points $i$ which satisfy $deg[i]=0$ into a queue. When the queue is not empty, do the following steps repeatedly. Take one point from the front of the queue. We say it is $i$. Iterate all edges which begin at the point $i$. We say the endpoint of the edge is $k$. Then we update $f[k][\\cdot]$ using $f[i][\\cdot]$. Finally we make $deg[k]$ minus by $1$. If $deg[k] = 0$, then we add the point $k$ into the queue. Make a variable $cnt$ plus by $1$. When there is no cycle in the graph, the queue will be empty with $cnt = n$. Then the answer is the maximum number among $f[i][j]$. If there are cycles in the graph, then $cnt$ cannot be $n$. Thus the answer can be arbitrarily large. In that situation, we should output -1. Time complexity: $\\mathcal{O}(m \\cdot alpha)$, where $alpha$ is the size of the alphabet (i.e. $alpha = 26$). Memory complexity: $\\mathcal{O}(n \\cdot alpha)$.",
    "code": "#include <bits/stdc++.h>\n#define N 300010\nusing namespace std;\n \nstruct Edge{\n\tint from, to, next;\n} edge[N];\n \nint head[N], tot;\n \ninline void addedge(int u, int v){\n\tedge[++tot] = (Edge){u, v, head[u]}, head[u] = tot;\n}\n \nint f[N][26], n, m, d[N];\nchar s[N];\nqueue<int> Q;\n \nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tscanf(\"%s\", s + 1);\n\tfor (int i = 1; i <= m; i++){\n\t\tint x, y;\n\t\tscanf(\"%d%d\", &x, &y);\n\t\taddedge(x, y);\n\t\td[y] ++;\n\t}\n\t\n\tfor (int i = 1; i <= n; i++){\n\t\tif (!d[i]){\n\t\t\tQ.push(i);\n\t\t\tf[i][s[i] - 'a'] = 1;\n\t\t}\n\t}\n\t\n\tint rem = n;\n\twhile (!Q.empty()){\n\t\tint now = Q.front();\n\t\tQ.pop();\n\t\trem --;\n\t\tfor (int i = head[now]; i; i = edge[i].next){\n\t\t\tEdge e = edge[i];\n\t\t\tfor (int j = 0; j < 26; j++){\n\t\t\t\tf[e.to][j] = max(f[e.to][j], f[now][j] + (s[e.to] - 'a' == j));\n\t\t\t}\n\t\t\td[e.to] --;\n\t\t\tif (!d[e.to]) Q.push(e.to);\n\t\t}\n\t}\n\t\n\tif (rem) return puts(\"-1\"), 0;\n\t\n\tint ans = 0;\n\tfor (int i = 1; i <= n; i++){\n\t\tfor (int j = 0; j < 26; j++){\n\t\t\tans = max(ans, f[i][j]);\n\t\t}\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "919",
    "index": "E",
    "title": "Congruence Equation",
    "statement": "Given an integer $x$. Your task is to find out how many positive integers $n$ ($1 \\leq n \\leq x$) satisfy $$n \\cdot a^n \\equiv b \\quad (\\textrm{mod}\\;p),$$ where $a, b, p$ are all known constants.",
    "tutorial": "Trying all integers from $1$ to $x$ is too slow to solve this problem. So we need to find out some features of that given equation. Because we have $a^{p-1} \\equiv 1 \\quad (\\textrm{mod}\\;p)$ when $p$ is a prime, it is obvious that $a^z \\; \\textrm{mod} \\; p$ falls into a loop and the looping section is $p-1$. Also, $z \\; \\textrm{mod} \\; p$ has a looping section $p$. We can try to list a chart to show what $n \\cdot a^n$ is with some specific $i, j$. (In the chart shown below, $n$ is equal to $i \\cdot (p-1) + j$) Proof for the chart shown above: For a certain $i, j$, we can see that Therefore, we can enumerate $j$ from $1$ to $p - 1$ and calculate $b \\cdot a^{-j}$. Let's say the result is $y$, then we have $j - i \\equiv y \\quad (\\textrm{mod} \\; p)$ (You can refer to the chart shown above to see if it is). So for a certain $j$, the possible $i$ can only be $(j - y), p + (j - y), \\ldots, p \\cdot t + (j - y)$. Then we can calculate how many possible answers $n$ in this situation (i.e. decide the minimum and maximum possible $t$ using the given lower bound $1$ and upper bound $x$). Finally we add them together and get the answer. Time complexity: $\\mathcal{O}(p \\log p)$ or $\\mathcal{O}(p)$ depending on how you calculate $y = b \\cdot a^{-j}$. By the way, you can also try Chinese Reminder Theorem to solve this problem.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\n \nint a, b, p;\nLL x;\n \ninline int pow(int a, int b, int p){\n\tLL ans = 1, base = a;\n\twhile (b){\n\t\tif (b & 1){\n\t\t\t(ans *= base) %= p;\n\t\t}\n\t\t(base *= base) %= p;\n\t\tb >>= 1;\n\t}\n\treturn (int)ans;\n}\n \ninline int inv(int x, int p){\n\treturn pow(x, p - 2, p);\n}\n \nint main(){\n\tscanf(\"%d%d%d%I64d\", &a, &b, &p, &x);\n\tLL ans = 0;\n\tfor (int i = 1; i <= p - 1; i++){\n\t\tint now = (LL)b * inv((LL)pow(a, i, p), p) % p;\n\t\tLL first = (LL)(p - 1) * ((i - now + p) % p) + i;\n\t\tif (first > x) continue;\n\t\tans += (x - first) / ((LL)p * (p - 1)) + 1;\n\t}\n\tprintf(\"%I64d\\n\", ans);\n}",
    "tags": [
      "chinese remainder theorem",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "919",
    "index": "F",
    "title": "A Game With Numbers",
    "statement": "Imagine that Alice is playing a card game with her friend Bob. They both have exactly $8$ cards and there is an integer on each card, ranging from $0$ to $4$. In each round, Alice or Bob in turns choose two cards from different players, let them be $a$ and $b$, where $a$ is the number on the player's card, and $b$ is the number on the opponent's card. It is necessary that $a \\cdot b \\ne 0$. Then they calculate $c = (a + b) \\bmod 5$ and replace the number $a$ with $c$. The player who ends up with numbers on all $8$ cards being $0$, wins.\n\nNow Alice wants to know who wins in some situations. She will give you her cards' numbers, Bob's cards' numbers and the person playing the first round. Your task is to determine who wins if both of them choose the best operation in their rounds.",
    "tutorial": "First we should notice that the useful number of states isn't something like $(8^5)^2$, because the order of the numbers in each player's hand does not matter. Therefore, the useful states of each player is $\\binom{5 + 8 - 1}{8}$. Then the useful states is estimated as $\\binom{5 + 8 - 1}{8}^2$, which is $245\\,025$. Then we can abstract those states as nodes, then link those nodes with directed edges which shows the transformation between two states (i.e. one can make one step to the other). Then we run BFS (or topological sort) on that graph. For a certain state, if all states it links out: has a state that the current player will win. Then the current player will win. has a state that the will get into a deal. Then the current player will make it deal. are all lose states. Then the current player will lose. It is because the current player can choose the best way to go. So we can do some initialization to get the \"Win\", \"Lose\" or \"Deal\" status for all possible states. Follow these steps shown below. Give all states that is easily to identify a status \"Win\" or \"Lose\". Then push them into a queue. For other states, give \"Deal\" temporarily. Take a state from the front of the queue. Update all states that can reach this state in one step (i.e. has an edge between them) using the rule shown above. If the state can be defined as one status, push it into the queue and go to the second step. Or you can ignore it and go to the second step instantly. After this step (or we can say \"Initialization\"), we can answer those $T$ queries easily. Time complexity: $\\mathcal{O}(k^2 \\cdot \\binom{m + k - 1}{k}^2 + T)$, where $k$ is the card number one player has, and $m$ is the modulo. Here we have $m = 5$ and $k = 8$.",
    "code": "#include <bits/stdc++.h>\n \n \nusing namespace std;\n \n#define re return\n#define sz(a) (int)a.size()\n#define mp(a, b) make_pair(a, b)\n#define fi first\n#define se second\n#define re return\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef pair<int, int> pii;\ntypedef pair<long long, long long> pll;\ntypedef long double ld;\ntypedef unsigned long long ull;\nconst ll mod = int(1e9) + 7;\n \nint ans[500][500], st[500][500];\nvector<pair<int, int> > go[500][500];\nvector<vector<int> > cc;\nvector<int> c;\nint mv[(1 << 20)];\n \nint it = 0;\n \nvoid pr(int n, int k) {\n\tif (k == 1) {\n\t\tc.push_back(n);\n\t\tmv[(((c[4] * 16 + c[3]) * 16 + c[2]) * 16 + c[1]) * 16 + c[0]] = it;\n\t\tcc.push_back(c);\n\t\tit++;\n\t\tc.pop_back();\n\t\tre;\n\t}\n\tfor (int j = 0; j <= n; j++) {\n\t\tc.push_back(j);\n\t\tpr(n - j, k - 1);\n\t\tc.pop_back();\n\t}\n}\nint kkk[5] = {1, 16, 256, 4096, 65536};\nvoid get_int(int &ans) {\n\tans = 0;\n\tchar c = getchar();\n\twhile (c < '0' || c > '9') c = getchar();\n\twhile (c >= '0' && c <= '9') {\n\t\tans = ans * 10 + c - '0';\n\t\tc = getchar();\n\t}\n\t//re ans;\n}\nint main() {\n\t//iostream::sync_with_stdio(0), cin.tie(0);\n\tpr(8, 5);\n\tqueue<pair<int, int> > pp;\n\t//exit(0); \n \n\tforn (j, sz(cc)) {\n\t\tvector<int> vv = cc[j];\n\t\tint cnum = (((vv[4] * 16 + vv[3]) * 16 + vv[2]) * 16 + vv[1]) * 16 + vv[0];\n\t\tbool ok = true;\n\t\tforn (q, sz(cc)) {\n\t\t\tbool ok1 = true;\n\t\t\tfor (int ii = 1; ii < 5; ii++)\n\t\t\t\tif (cc[j][ii]) {\n\t\t\t\t\tok = false;\n\t\t\t\t\tfor (int jj = 1; jj < 5; jj++)\n\t\t\t\t\t\tif (cc[q][jj]) {\n\t\t\t\t\t\t\tok1 = false;\n\t\t\t\t\t\t\tcnum -= kkk[ii];\n\t\t\t\t\t\t\tcnum += kkk[(ii + jj) % 5];\n\t\t\t\t\t\t\t//assert(cnum >= 0 && cnum < (1 << 20));\n\t\t\t\t\t\t\tgo[q][mv[cnum]].push_back(mp(j, q));\n\t\t\t\t\t\t\tst[j][q]++;\n\t\t\t\t\t\t\tcnum += kkk[ii];\n\t\t\t\t\t\t\tcnum -= kkk[(ii + jj) % 5];\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif (ok) {\n\t\t\t\tans[j][q] = 1;\n\t\t\t\tpp.push(mp(j, q));\n\t\t\t} else\n\t\t\tif (ok1) {\n\t\t\t\tans[j][q] = 2;\n\t\t\t\tpp.push(mp(j, q));\n\t\t\t}\n\t\t}\n\t}\n\t//exit(0);\n\twhile (!pp.empty()) {\n\t\tint j = pp.front().fi;\n\t\tint q = pp.front().se;\n\t\tpp.pop();\n\t\tfor (auto v : go[j][q]) {\n\t\t\tif (ans[v.fi][v.se]) continue;\n\t\t\tif (ans[j][q] == 2) {\n\t\t\t\tans[v.fi][v.se] = 1;\n\t\t\t\tpp.push(v);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tst[v.fi][v.se]--;\n\t\t\tif (st[v.fi][v.se] == 0) {\n\t\t\t\tans[v.fi][v.se] = 2;\n\t\t\t\tpp.push(v);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\t//exit(0);\n\tint t;\n\tget_int(t);\n\t//cin >> t;\n\tforn (i, t) {\n\t\tint f;\n\t\tget_int(f);\n\t\t//cin >> f;\n\t\tint a = 0, b = 0;\n\t\t//vector<int> a(5, 0), b(5, 0);\n\t\tforn (i, 8) {\n\t\t\tint j;\n\t\t\tget_int(j);\n\t\t\t//cin >> j;\n\t\t\ta += (1 << (j * 4));\n\t\t}\n\t\tforn (i, 8) {\n\t\t\tint j;\n\t\t\tget_int(j);\n\t\t\t//cin >> j;\n\t\t\tb += (1 << (j * 4));\n\t\t}\n\t\tint k1 = mv[a], k2 = mv[b];\n\t\tif (f == 0) {\n\t\t\tif (ans[k1][k2] == 1) printf(\"Alice\\n\");\n\t\t\tif (ans[k1][k2] == 2) printf(\"Bob\\n\");\n\t\t\tif (ans[k1][k2] == 0) printf(\"Deal\\n\");\n\t\t} else {\n\t\t\tswap(k1, k2);\n\t\t\tif (ans[k1][k2] == 2) printf(\"Alice\\n\");\n\t\t\tif (ans[k1][k2] == 1) printf(\"Bob\\n\");\n\t\t\tif (ans[k1][k2] == 0) printf(\"Deal\\n\");\n\t\t}\n\t}\n}",
    "tags": [
      "games",
      "graphs",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "920",
    "index": "A",
    "title": "Water The Garden",
    "statement": "It is winter now, and Max decided it's about time he watered the garden.\n\nThe garden can be represented as $n$ consecutive garden beds, numbered from $1$ to $n$. $k$ beds contain water taps ($i$-th tap is located in the bed $x_{i}$), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed $x_{i}$ is turned on, then after one second has passed, the bed $x_{i}$ will be watered; after two seconds have passed, the beds from the segment $[x_{i} - 1, x_{i} + 1]$ will be watered (if they exist); after $j$ seconds have passed \\textbf{($j$ is an integer number)}, the beds from the segment $[x_{i} - (j - 1), x_{i} + (j - 1)]$ will be watered (if they exist). \\textbf{Nothing changes during the seconds, so, for example, we can't say that the segment $[x_{i} - 2.5, x_{i} + 2.5]$ will be watered after $2.5$ seconds have passed; only the segment $[x_{i} - 2, x_{i} + 2]$ will be watered at that moment.}\n\n\\begin{center}\nThe garden from test $1$. White colour denotes a garden bed without a tap, red colour — a garden bed with a tap.\n\\end{center}\n\n\\begin{center}\nThe garden from test $1$ after $2$ seconds have passed after turning on the tap. White colour denotes an unwatered garden bed, blue colour — a watered bed.\n\\end{center}\n\nMax wants to \\textbf{turn on all the water taps at the same moment}, and now he wonders, what is the minimum number of seconds that have to pass after he turns on some taps until the whole garden is watered. Help him to find the answer!",
    "tutorial": "The answer is the maximal value among the following values: $\\operatorname*{min}_{i=2}^{k}|\\frac{a(i)-a(i,-1)+2}{2}\\rfloor$ (to cover all water beds within some segment), $a[1]$ (to cover water beds before the first tap), $n - a[k] + 1$ (to cover all water beds after the last tap).",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "920",
    "index": "B",
    "title": "Tea Queue",
    "statement": "Recently $n$ students from city S moved to city P to attend a programming camp.\n\nThey moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.\n\n$i$-th student comes to the end of the queue at the beginning of $l_{i}$-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of $r_{i}$-th second student $i$ still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea.\n\nFor each student determine the second he will use the teapot and get his tea (if he actually gets it).",
    "tutorial": "Let's store the last moment when somebody gets a tea in the variable $lst$. Then if for the $i$-th student $lst  \\ge  r_{i}$ then he will not get a tea. Otherwise he will get it during $max(lst + 1, l_{i})$ second. And if he gets a tea then $lst$ will be replaced with the answer for this student.",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "920",
    "index": "C",
    "title": "Swap Adjacent Elements",
    "statement": "You have an array $a$ consisting of $n$ integers. Each integer from $1$ to $n$ appears exactly once in this array.\n\nFor some indices $i$ ($1 ≤ i ≤ n - 1$) it is possible to swap $i$-th element with $(i + 1)$-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap $i$-th element with $(i + 1)$-th (if the position is not forbidden).\n\nCan you make this array sorted in ascending order performing some sequence of swapping operations?",
    "tutorial": "Take a look at some pair $(i, j)$ such that $i < j$ and initial $a_{i} > a_{j}$. It means that all the swaps from $i$ to $j - 1$ should be allowed. Then it's easy to notice that it's enough to check only $i$ and $i + 1$ as any other pair can be deducted from this. You can precalc $pos[a_{i}]$ for each $i$ and prefix sums over the string of allowed swaps to check it in no time. Overall complexity: $O(n)$.",
    "tags": [
      "dfs and similar",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "920",
    "index": "D",
    "title": "Tanks",
    "statement": "Petya sometimes has to water his field. To water the field, Petya needs a tank with exactly $V$ ml of water.\n\nPetya has got $N$ tanks, $i$-th of them initially containing $a_{i}$ ml of water. The tanks are really large, any of them can contain any amount of water (no matter how large this amount is).\n\nAlso Petya has got a scoop that can contain up to $K$ ml of water (initially the scoop is empty). This scoop can be used to get some water from some tank, and after that pour it all into some tank (it is impossible to get water from multiple tanks without pouring it, or leave some water in the scoop when pouring it). When Petya tries to get some water from a tank, he gets $min(v, K)$ water, where $v$ is the current volume of water in the tank.\n\nIs it possible to obtain a tank with exactly $V$ ml of water using these operations? If it is possible, print a sequence of operations that allows to do it. If there are multiple ways to obtain needed amount of water in some tank, print any of them.",
    "tutorial": "Eliminate the obvious corner case when we don't have enough water ($\\sum_{i=1}^{N}a_{i}<V$). Now we don't consider it in editorial. Let's fix some set of tanks $S$, and let $d$ be $\\sum_{i\\in G}a_{i}$ (the total amount of water in the set). If $d  \\equiv  V (mod K)$ ($d$ and $V$ have the same remainders modulo $k$), then we can transfer all water from $S$ to one tank $x$, transfer all water from $[1,N]\\setminus S$ to another tank $y$, and then using some number of operations transfer required amount of water from $x$ to $y$ (or from $y$ to $x$). So we have a solution when we have some set of tanks $S$ such that $d  \\equiv  V(mod K)$. What if we don't have such set? In this case it is impossible to solve the problem since we cannot obtain a tank with $d$ water such that $d  \\equiv  V (mod K)$ (and, obviously, we cannot obtain a tank with exactly $V$ water). To find this set $S$, we may use some sort of knapsack dynamic programming.",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "920",
    "index": "E",
    "title": "Connected Components?",
    "statement": "You are given an undirected graph consisting of $n$ vertices and ${\\frac{n(n-1)}{2}}-m$ edges. Instead of giving you the edges that exist in the graph, we give you $m$ unordered pairs ($x, y$) such that there is no edge between $x$ and $y$, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.\n\nYou have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices $X$ such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to $X$ violates this rule.",
    "tutorial": "Let $S$ be the set of unvisited vertices. To store it, we will use some data structure that allows us to do the following: insert $s$ - insert some value $s$ into the set; erase $s$ - delete $s$ from the set; upper_bound $s$ - find the smallest integer $y$ from the set such that $y > s$. For example, std::set<int> from C++ allows us to do all these operations fastly. Also we can use this structure to store the adjacency lists. We will use a modified version of depth-first-search. When we are entering a vertex with $dfs$, we erase it from the set of unvisited vertices. The trick is that in $dfs$ we will iterate over the set of unvisited vertices using its upper_bound function. And we will make not more than $O(m + n)$ iterations overall because when we skip an unvisited vertex, that means there is no edge from this vertex to the vertex we are currently traversing in $dfs$, so there will be no more than $2m$ skips; and each iteration we don't skip decreases the number of unvisited vertices.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "920",
    "index": "F",
    "title": "SUM and REPLACE",
    "statement": "Let $D(x)$ be the number of positive divisors of a positive integer $x$. For example, $D(2) = 2$ ($2$ is divisible by $1$ and $2$), $D(6) = 4$ ($6$ is divisible by $1$, $2$, $3$ and $6$).\n\nYou are given an array $a$ of $n$ integers. You have to process two types of queries:\n\n- REPLACE $l$ $r$ — for every $i\\in[l,r]$ replace $a_{i}$ with $D(a_{i})$;\n- SUM $l$ $r$ — calculate $\\sum_{i=1}^{r}a_{i}$.\n\nPrint the answer for each SUM query.",
    "tutorial": "At first let's notice that this function converges very quickly, for values up to $10^{6}$ it's at most $6$ steps. Now we should learn how to skip updates on the numbers $1$ and $2$. The function values can be calculated from the factorization of numbers in $O(M A X N\\log M A X N)$ with Eratosthenes sieve. Let's write two segment trees - one will store maximum value on segment, the other will store the sum. When updating some segment, check if its maximum is greater than $2$. Updates are done in the manner one can usually write build function, you go down to the node corresponding to the segment of length $1$ and update the value directly. Overall complexity: $O(q\\log n)$ as we access any segment no more than $6$ times.",
    "tags": [
      "brute force",
      "data structures",
      "dsu",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "920",
    "index": "G",
    "title": "List Of Integers",
    "statement": "Let's denote as $L(x, p)$ an infinite sequence of integers $y$ such that $gcd(p, y) = 1$ and $y > x$ (where $gcd$ is the greatest common divisor of two integer numbers), sorted in ascending order. The elements of $L(x, p)$ are $1$-indexed; for example, $9$, $13$ and $15$ are the first, the second and the third elements of $L(7, 22)$, respectively.\n\nYou have to process $t$ queries. Each query is denoted by three integers $x$, $p$ and $k$, and the answer to this query is $k$-th element of $L(x, p)$.",
    "tutorial": "Let's use binary searching to find the answer. Denote as $A(p, y)$ the number of positive integers $z$ such that $z  \\le  y$ and $gcd(z, p) = 1$; the answer is the smallest integer $d$ such that $A(p, d)  \\ge  A(p, x) + k$. We may use, for example, $10^{18}$ as the right border of segment where we use binary searching; although the answers are a lot smaller than this number, for $y = 10^{18}$ it is obvious that $A(p, y)$ will be really large for any $p$ from $[1;10^{6}]$. How can we calculate $A(p, y)$ fastly? Let's factorize $p$ and use inclusion-exclusion. Let $S$ be a subset of the set of prime divisors of $p$, and $P(S)$ be the product of all numbers from $S$. For each possible subset $S$, we have to add $(-1)^{|S|}\\cdot\\left|\\frac{y}{P l(S)}\\right|$ to the result (since there are exactly $\\left|{\\frac{y}{P(S)}}\\right|$ integers from $[1, y]$ divisible by every prime from $S$). Since any number from $[1, 10^{6}]$ has at most $7$ prime divisors, there are at most $2^{7}$ subsets to process.",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "922",
    "index": "A",
    "title": "Cloning Toys",
    "statement": "Imp likes his plush toy a lot.\n\nRecently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.\n\nInitially, Imp has only one original toy. He wants to know if it is possible to use machine to get exactly $x$ \\textbf{copied} toys and $y$ \\textbf{original} toys? He can't throw toys away, and he can't apply the machine to a copy if he doesn't currently have any copies.",
    "tutorial": "Consider a few cases: If $y = 0$, the answer is always <<No>>. If $y = 1$, then the answer <<Yes>> is possible only if $x = 0$; if $x > 0$, the answer is <<No>>. We can observe that the original was cloned $y - 1$ times to produce the requested amount of originals, then the additional copies were created by cloning the copies emerged from cloning the original. As every cloning of a copy results in additional two, we need to check whether $(x - y + 1)$ is divisible by 2. We also need to take care of the case when $(x - y + 1)$ is less than zero - in this case, the answer is also <<NO>>. Time complexity: $O(1)$.",
    "code": "x, y = map(int, input().split())\n \nif y == 0:\n    print('No')\n    exit(0)\n \nif y == 1:\n    if x == 0:\n        print('Yes')\n    else:\n        print('No')\n    exit(0)\n \nprint('Yes' if x >= y - 1 and (x - y + 1) % 2 == 0 else 'No')",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "922",
    "index": "B",
    "title": "Magic Forest",
    "statement": "Imp is in a magic forest, where xorangles grow (wut?)\n\nA xorangle of order $n$ is such a non-degenerate triangle, that lengths of its sides are integers not exceeding $n$, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order $n$ to get out of the forest.\n\nFormally, for a given integer $n$ you have to find the number of such triples $(a, b, c)$, that:\n\n- $1 ≤ a ≤ b ≤ c ≤ n$;\n- $a\\oplus b\\oplus c=0$, where $x\\oplus y$ denotes the bitwise xor of integers $x$ and $y$.\n- $(a, b, c)$ form a non-degenerate (with strictly positive area) triangle.",
    "tutorial": "Consider some triple $(a, b, c)$ for which $a\\oplus b\\oplus c=0$ holds. Due to xor invertibility, we can see that $a\\oplus b=c$. So, we only need to iterate through two of three possible sides of the xorangle as the third can be deduced uniquely. Time complexity: $O(n^{2})$ One could also apply some constant optimizations (and put some pragmas) get $O(n^{3})$ solution with small constant accepted.",
    "code": "#pragma GCC optimize(\"unroll-loops\")\n \n#define _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 100002, M = 350;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nvoid solve() {\n\tshort n = read();\n\tint ans = 0;\n\tshort y, x;\n\tfor (short i = 1; i <= n; ++i)\n\t\tfor (short j = i; j <= n; ++j) {\n\t\t    x = i + j;\n\t\t\tfor (short k = j; k < x; ++k) {\n\t\t\t    y = (i ^ j);\n\t\t\t\tif (y >= j)\n\t\t\t\t\tif (y <= n)\n\t\t\t\t\t\tif (y == k)\n\t\t\t\t\t\t\tans++;\n\t\t\t}\n\t\t}\n \n\tprintf(\"%d\\n\", ans);\n}\n \nvoid precalc() {}\n \nsigned main() {\n\tint t = 1;\n \n\tprecalc();\n \n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1300
  },
  {
    "contest_id": "922",
    "index": "C",
    "title": "Cave Painting",
    "statement": "Imp is watching a documentary about cave painting.\n\nSome numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number $n$ by all integers $i$ from $1$ to $k$. Unfortunately, there are too many integers to analyze for Imp.\n\nImp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all $n{\\mathrm{~mod~}}i$, $1 ≤ i ≤ k$, are distinct, i. e. there is no such pair $(i, j)$ that:\n\n- $1 ≤ i < j ≤ k$,\n- $n\\,\\mathrm{mod}\\,i=n\\,\\mathrm{mod}\\,j$, where $x\\ {\\mathrm{mod}}\\ y$ is the remainder of division $x$ by $y$.",
    "tutorial": "Consider the way remainders are obtained. Remainder $k - 1$ can be obtained only when $n$ is taken modulo $k$. Remainder $k - 2$ can either be obtained when taken modulo $k - 1$ or $k$. Since the remainder modulo $k$ is already fixed, the only opportunity left is $k - 1$. Proceeding this way, we come to a conclusion that if answer exists, then $\\forall i$ $n{\\mathrm{~mod~}}i$ = $i - 1$ holds. This condition is equal to $(n + 1)$ mod $i$ = $0$, i. e. $(n + 1)$ should be divisible by all numbers between $1$ and $k$. In other words, $(n + 1)$ must be divisible by their LCM. Following the exponential growth of LCM, we claim that when $k$ is huge enough, the answer won't exists (more precisely at $k  \\ge  43$). And for small $k$ we can solve the task naively. Complexity: $O(\\operatorname{min}(k,\\log n))$.",
    "code": "n, k = map(int, input().split())\n \nif k > 70:\n    print('No')\n    exit(0)\n \ns = set()\nfor i in range(1, k + 1):\n    s.add(n % i)\n \nprint('Yes' if len(s) == k else 'No')",
    "tags": [
      "brute force",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "922",
    "index": "D",
    "title": "Robot Vacuum Cleaner",
    "statement": "Pushok the dog has been chasing Imp for a few hours already.\n\nFortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner.\n\nWhile moving, the robot generates a string $t$ consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string $t$ as the number of occurrences of string \"sh\" as a \\textbf{subsequence} in it, in other words, the number of such pairs $(i, j)$, that $i < j$ and $t_{i}=\\mathbf{s}$ and $t_{j}=\\mathbf{h}$.\n\nThe robot is off at the moment. Imp knows that it has a sequence of strings $t_{i}$ in its memory, and he can arbitrary change their order. When the robot is started, it generates the string $t$ as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.\n\nHelp Imp to find the maximum noise he can achieve by changing the order of the strings.",
    "tutorial": "Denote $\\mathbf{f}(t)$ as the noise function. We are gonna sort the string set in the following way: for each pair $(a, b)$ we will put $a$ earlier if $\\mathbf{f}(a+b)>\\mathbf{f}(b+a)$. The claim is that the final concatenation will be optimal. Let $A$ be the number of subsequences $sh$ in $a$, $B$ - in $b$. Then $\\mathbf{f}(a+b)=A+B+s_{a}\\cdot h_{b}$, $\\mathbf{f}(b+a)=A+B+s_{b}\\cdot h_{a}$. $A$ and $B$ are reduced, and the comparator turns into $s_{a} \\cdot h_{b} > s_{b} \\cdot h_{a}$. This is almost equivalent to $\\frac{s a}{h_{a}}\\,>\\,\\frac{s_{b}}{h_{b}}$ (except the degenerate case when the string consists of $s$ only), meaning that the sort is transitive. Now suppose that this is all false and in the optimal concatenation for some pair of strings $(a, b)$ the aforementioned statement doesn't hold. Then it can be easily shown that you can change their positions and the answer will only get better. Time complexity: $O(n\\log n)$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 20000;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n \n\tvector<string> a(n);\n\tfor (auto &v : a) cin >> v;\n \n\tauto f = [](string s) -> ll {\n\t\tll total = 0;\n\t\tint open = 0;\n\t\tfor (char c : s)\n\t\t\tif (c == 's')\n\t\t\t\topen++;\n\t\t\telse\n\t\t\t\ttotal += open;\n\t\treturn total;\n\t};\n \n\tsort(all(a), [&](string s, string t) {\n\t\treturn f(s + t) > f(t + s);\n\t});\n \n\tstring s = \"\";\n\tfor (auto v : a) s += v;\n \n\tcout << f(s) << endl;\n}\n \nsigned main() {\n\tint t = 1;\n \n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "922",
    "index": "E",
    "title": "Birds",
    "statement": "Apart from plush toys, Imp is a huge fan of little yellow birds!\n\nTo summon birds, Imp needs strong magic. There are $n$ trees in a row on an alley in a park, there is a nest on each of the trees. In the $i$-th nest there are $c_{i}$ birds; to summon one bird from this nest Imp needs to stay under this tree and it costs him $cost_{i}$ points of mana. However, for each bird summoned, Imp increases his mana capacity by $B$ points. Imp summons birds one by one, he can summon any number from $0$ to $c_{i}$ birds from the $i$-th nest.\n\nInitially Imp stands under the first tree and has $W$ points of mana, and his mana capacity equals $W$ as well. He can only go forward, and each time he moves from a tree to the next one, he restores $X$ points of mana (but it can't exceed his current mana capacity). Moving only forward, what is the maximum number of birds Imp can summon?",
    "tutorial": "The problem can be solved by utilizing dynamic programming. Let us denote by $\\mathrm{d}\\mathbf{p}[n][k]$ the maximum possible remaining amount mana for the state $(n, k)$, where $n$ stands for the number of nests passed by and $k$ stands for the number of birds summoned. The base is $\\mathrm{d}{\\mathfrak{p}}[0](0)=W$ as we have passed by no nests, have summoned no birds and have $W$ mana at our disposal in the beginning. Let us also initialize all other states with $ \\infty $. The transitions are as follows: consider us having walked to the next nest and summoned $k$ additional birds from there, therefore proceeding from the state $(i - 1, j - k)$ to $(i, j)$ (of course, it is reasonable to require that the answer for $(i - 1, j - k)$ is not $ \\infty $). After we have proceeded, $X$ units of mana would be replenished (taking summoned birds into consideration, the amount of mana at the moment is bounded above by $W + (j - k) \\cdot B$). The summoning would cost us $\\cosh_{i}\\cdot k$ mana. If after the replenishing and the summoning the remaining amount of mana is nonnegative, we update the answer for the state $(i, j)$: $\\mathrm{d}{\\bf p}[i][j]=\\mathrm{max}\\left(\\mathrm{d}{\\bf p}[i][j],\\mathrm{min}(\\mathrm{d}{\\bf p}[i-1][j-k]+X,W+(j-k)\\cdot B)-\\mathrm{cost}_{i}\\cdot k\\right)$ The answer is the maximal $k$ among reachable states (those not equal to $ \\infty $). Time complexity: $O(n\\sum_{i=1}^{n}\\mathrm{c}_{i}+(\\sum_{i=1}^{n}\\mathrm{c}_{i})^{2})$. Note that the constant in the square is no more than $\\frac{1}{4}$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 1005, M = 10005;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nll dp[N][M];\nint c[N];\nll cost[N];\n \nvoid relax(ll &u, ll v) {\n\tu = max(u, v);\n}\n \nvoid solve() {\n\tint n = read();\n\tll W = read(), B = read(), X = read();\n \n\tforn(i, n) c[i] = read();\n\tforn(i, n) cost[i] = read();\n \n\tfill_n(&dp[0][0], N * M, -1);\n\tdp[0][0] = W;\n \n\tforn(i, n)\n\t\tfor (int j = 0; j < M && dp[i][j] != -1; j++)\n\t\t\tfor (int k = 0; k <= c[i] && dp[i][j] - k * cost[i] >= 0; k++)\n\t\t\t\trelax(dp[i + 1][k + j], min(W + (k + j) * B, dp[i][j] - k * cost[i] + X));\n \n\tint ans = 0;\n\tforn(i, M)\n\t\tif (dp[n][i] != -1)\n\t\t\tans = max(ans, i);\n \n\tprintf(\"%d\\n\", ans);\n}\n \nsigned main() {\n\tint t = 1;\n \n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "922",
    "index": "F",
    "title": "Divisibility",
    "statement": "Imp is really pleased that you helped him. But it you solve the last problem, his gladness would raise even more.\n\nLet's define $f(1)$ for some set of integers $\\left\\vert\\right.\\L$ as the number of pairs $a$, $b$ in $\\left.\\right]_{}^{}$, such that:\n\n- $a$ is \\textbf{strictly less} than $b$;\n- $a$ \\textbf{divides} $b$ without a remainder.\n\nYou are to find such a set $\\left\\vert\\right.\\left\\vert\\right.\\right\\lbrace\\left\\vert\\right.\\right\\vert$, which is a subset of ${1, 2, ..., n}$ (the set that contains all positive integers not greater than $n$), that $f(\\Gamma)=k$.",
    "tutorial": "Let the sought pairs be the edges in a graph with $n$ vertices. Then the problem is reduced to finding such a vertex subset that the induced graph contains exactly $k$ edges. Let $e(n)$ be the number of edges in the graph on ${1, 2, ..., n}$ and $d(n)$ be the number of divisors of $n$ (strictly less than $n$). We claim that the answer always exists if $k  \\le  e(n)$ (otherwise it's obviously NO). Let's enlighten it a bit. Let's find the minimum possible $m$ such that $e(m)  \\ge  k$ and try to paraphrase the problem: we have to throw away some vertices from the graph on $m$ vertices to leave exactly $k$ edges. Note that the degree of vertex $x$ is equal to $d(x)+\\left[{\\frac{m}{x}}\\right]-1$: hence the most interesting numbers for us are primes strictly larger than $\\textstyle{\\frac{m}{2}}$ since their degree is equal to $1$. Now it's time to expose the most important fact of the day: we claim that $e(m)-k\\leq C\\cdot m^{\\frac{1}{3}}$. At the same time the number of primes greater than $\\textstyle{\\frac{m}{2}}$, is about $\\frac{m}{2\\log m}$. Quite intuitive that asymptotically it's almost enough to throw only them away (there are only $16$ possible counters and they all appear with $m  \\le  120$ which could be solved manually). This observation is sufficient to get AC. You could've chosen the parallel way and note that vertices greater than $\\textstyle{\\frac{m}{2}}$ - do not share edges, therefore they can be thrown away independently (adding the statement from the previous paragraph, greedy approach will do). You could've even written recursive bruteforce :D Summarizing the aforementioned, it works well. Time complexity: $O(n\\log n)$. Note that the solutions might not fully match the editorial, though the ideas are still the same.",
    "code": "#include <iostream>\n#include <map>\n#include <vector>\n \nusing namespace std;\n \nconst int MAXN = 300005;\n \nint smallest_divisor[MAXN];\nint nd[MAXN];\nbool ban[MAXN];\n \nint num_divisors(int x)\n{\n    if (nd[x] == 0) {\n        int i = x;\n        if (i == 0) {\n            return 0;\n        }\n        map<int, int> cnt;\n        while (i > 1) {\n            cnt[smallest_divisor[i]]++;\n            i /= smallest_divisor[i];\n        }\n        int ans = 1;\n        for (const auto &kvp : cnt) {\n            ans *= kvp.second + 1;\n        }\n        nd[x] = ans;\n    }\n    return nd[x];\n}\n \nint main()\n{\n    int n, k;\n    cin >> n >> k;\n \n    if (k == 0) {\n        cout << \"Yes\" << endl << 1 << endl << 1 << endl;\n        return 0;\n    }\n \n    for (int i = 0; i < MAXN; i++) {\n        smallest_divisor[i] = i;\n    }\n \n    for (int i = 2; i * i < MAXN; i++) {\n        if (smallest_divisor[i] != i) {\n            continue;\n        }\n        for (int j = i * i; j < MAXN; j += i) {\n            if (smallest_divisor[j] == j) {\n                smallest_divisor[j] = i;\n            }\n        }\n    }\n \n    int taken;\n    int cur = 0;\n    for (taken = 1; taken <= n && cur < k; taken++) {\n        cur += num_divisors(taken) - 1;\n    }\n    taken--;\n    \n    if (taken == n && k > cur) {\n        cout << \"No\" << endl;\n        return 0;\n    }\n \n    int excess = cur - k;\n    // cerr << excess << endl;\n \n    if (taken > 500) {\n        for (int i = taken; excess > 0 && i >= 1; i--) {\n            if (smallest_divisor[i] == i) {\n                ban[i] = true;\n                excess--;\n            }\n        }\n    }\n    else {\n        bool found = false;\n        for (int i = 1; i <= taken; i++) {\n            int pairs = 0;\n            for (int j = 1; j <= taken; j++) {\n                if (i == j) {\n                    continue;\n                }\n                if (max(i, j) % min(i, j) == 0) {\n                    pairs++;\n                }\n            }\n            // cerr << i << \" \" << pairs << endl;\n            if (pairs == excess) {\n                ban[i] = true;\n                found = true;\n                break;\n            }\n        }\n        for (int i1 = 1; !found && i1 <= taken; i1++) {\n            for (int i2 = i1 + 1; !found && i2 <= taken; i2++) {\n                int pairs = i2 % i1 == 0;\n                for (int j = 1; j <= taken; j++) {\n                    if (i1 == j || i2 == j) {\n                        continue;\n                    }\n                    if (max(i1, j) % min(i2, j) == 0) {\n                        pairs++;\n                    }\n                    if (max(i2, j) % min(i2, j) == 0) {\n                        pairs++;\n                    }\n                }\n                if (pairs == excess) {\n                    ban[i1] = ban[i2] = true;\n                    found = true;\n                }\n            }\n        }\n    }\n \n    cout << \"Yes\" << endl;\n    vector<int> ans;\n    for (int i = 1; i <= taken; i++) {\n        if (!ban[i]) {\n            ans.push_back(i);\n        }\n    }\n    \n    cout << ans.size() << endl;\n    for (int x : ans) {\n        cout << x << \" \";\n    }\n    cout << endl;\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "923",
    "index": "A",
    "title": "Primal Sport",
    "statement": "Alice and Bob begin their day with a quick game. They first choose a starting number $X_{0} ≥ 3$ and try to reach one million by the process described below.\n\nAlice goes first and then they take alternating turns. In the $i$-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.\n\nFormally, he or she selects a prime $p < X_{i - 1}$ and then finds the minimum $X_{i} ≥ X_{i - 1}$ such that $p$ divides $X_{i}$. Note that if the selected prime $p$ already divides $X_{i - 1}$, then the number does not change.\n\nEve has witnessed the state of the game after two turns. Given $X_{2}$, help her determine what is the smallest possible starting number $X_{0}$. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.",
    "tutorial": "Let $P(N)$ be the largest prime factor of $N$. Clearly, we can obtain $N$ from any number in interval $[N - P(N) + 1, N]$ by picking $P(N)$ as the prime, and we cannot obtain $N$ from any other number. By factorizing $X_{2}$, we can find the range for $X_{1}$. By factorizing all numbers from the range of $X_{1}$, we can find intervals for $X_{0}$. The answer is the minimum of their union. The solution works in $O(N{\\sqrt{N}})$, which is fast in practice. Bonus: Solve it for $Q$ queries of $X_{K}$ in $O(N\\log N+Q\\log K)$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "923",
    "index": "B",
    "title": "Producing Snow",
    "statement": "Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day $i$ he will make a pile of snow of volume $V_{i}$ and put it in her garden.\n\nEach day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is $T_{i}$, each pile will reduce its volume by $T_{i}$. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other.\n\nNote that the pile made on day $i$ already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day.\n\nYou are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day.",
    "tutorial": "We can directly simulate the process, but it takes $O(N^{2})$ time, which is too slow. There are multiple approaches how to make this simulation faster. We present two of them. In the first solution, instead of calculating the total volume of the snow melted, we first calculate two quantities: $F[i]$ - the number of piles left after day $i$, and $M[i]$ - the total volume of piles that disappear on day $i$. The answer will then be $F[i] * T[i] + M[i]$.Calculate prefix sums of the temperatures. This way, when a snow pile is formed on day $i$, we can use binary search to determine on which day it will disappear completely. Denote this day by $j$ and put $j = N + 1$ if the pile survives. We can note that on every day $k$ between $i$ and $j - 1$ inclusive, this pile will lose $T[k]$ of its volume, which corresponds to increasing $F[k]$ by one. Furthermore, we add the remaining volume to $M[j]$. To calculate all $F[i]$'s fast, we can again use prefix sums - adding 1 to interval can then be done by two additions. Calculate prefix sums of the temperatures. This way, when a snow pile is formed on day $i$, we can use binary search to determine on which day it will disappear completely. Denote this day by $j$ and put $j = N + 1$ if the pile survives. We can note that on every day $k$ between $i$ and $j - 1$ inclusive, this pile will lose $T[k]$ of its volume, which corresponds to increasing $F[k]$ by one. Furthermore, we add the remaining volume to $M[j]$. To calculate all $F[i]$'s fast, we can again use prefix sums - adding 1 to interval can then be done by two additions. The second solution can handle queries online. For each pile, we calculate how big it would be if it was created on the first day: $V^{\\prime}[i]=V[i]+\\sum_{j=1}^{i-1}T[j]$. We maintain all existing piles in a multiset. When a day $i$ starts, we add $V'[i]$ into the multiset. Then we remove all piles with $V^{\\prime}[k]\\leq\\sum_{j=1}^{i}T[j]$ - those are the piles that disappear on day $i$ - and easily calculate the total volume of melted snow in them. All the piles left in the multiset contribute exactly $T[i]\\cdot\\mathrm{size~of~multise}]$. As the multiset is sorted, and each pile is added and removed only once, the total complexity is $O(N\\log N)$. We maintain all existing piles in a multiset. When a day $i$ starts, we add $V'[i]$ into the multiset. Then we remove all piles with $V^{\\prime}[k]\\leq\\sum_{j=1}^{i}T[j]$ - those are the piles that disappear on day $i$ - and easily calculate the total volume of melted snow in them. All the piles left in the multiset contribute exactly $T[i]\\cdot\\mathrm{size~of~multise}]$. As the multiset is sorted, and each pile is added and removed only once, the total complexity is $O(N\\log N)$.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 1600
  },
  {
    "contest_id": "923",
    "index": "C",
    "title": "Perfect Security",
    "statement": "Alice has a very important message $M$ consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key $K$ of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key ($A_{i}:=M_{i}\\oplus K_{i}$, where $\\mathbb{C}$ denotes the bitwise XOR operation) and stores this encrypted message $A$. Alice is smart. Be like Alice.\n\nFor example, Alice may have wanted to store a message $M = (0, 15, 9, 18)$. She generated a key $K = (16, 7, 6, 3)$. The encrypted message is thus $A = (16, 8, 15, 17)$.\n\nAlice realised that she cannot store the key with the encrypted message. Alice sent her key $K$ to Bob and deleted her own copy. Alice is smart. Really, be like Alice.\n\nBob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.\n\nIn the above example, Bob may have, for instance, selected a permutation $(3, 4, 1, 2)$ and stored the permuted key $P = (6, 3, 16, 7)$.\n\nOne year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?\n\nBob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message $A$ and the permuted key $P$. What is the lexicographically smallest message that could have resulted in the given encrypted text?\n\nMore precisely, for given $A$ and $P$, find the lexicographically smallest message $O$, for which there exists a permutation $π$ such that ${\\cal O}_{i}\\oplus\\pi(P_{i})=A_{i}$ for every $i$.\n\nNote that the sequence $S$ is lexicographically smaller than the sequence $T$, if there is an index $i$ such that $S_{i} < T_{i}$ and for all $j < i$ the condition $S_{j} = T_{j}$ holds.",
    "tutorial": "We decrypt the message greedily, one number at a time. Note that $f(X):X\\oplus Y$ is a bijection on non-negative integers. For that reason, there is always a unique number from the key that lexicographically minimises the string. We can always pick and remove that number, output its xor with the current number from the encrypted text. It remains to show how to do the above faster than $O(N^{2})$. We build a trie on the numbers from the key, more precisely on their binary representation, starting from the most significant bit. To find the number $K_{j}$ that minimises $K_{j}\\oplus A_{i}$, one can simply search for $A_{i}$, bit by bit. That is, if the $k$-th most significant bit of $A_{i}$ is $1$, we try to follow the edge labelled $1$, and $0$ otherwise. If we always succeed in that, we have found $A_{i}$ in the key multiset, and hence $K_{j}\\oplus A_{i}=0$, which is clearly minimal. If at some bit, we do not succeed, we select the other branch (that is, if $k$-th bit of $A_{i}$ is $1$, but there is no such number in the key set, we pick $0$ instead and continue. This solution uses $O(N W)$ time, where $W$ is the number of bits (here it is 30). The same approach can be also implemented using multiset, which is probably faster to write, but has an extra $O(\\log N)$ multiplicative factor, which may or may not fit into TL.",
    "tags": [
      "data structures",
      "greedy",
      "strings",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "923",
    "index": "D",
    "title": "Picking Strings",
    "statement": "Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:\n\n- A $\\to$ BC\n- B $\\to$ AC\n- C $\\to$ AB\n- AAA $\\to$ empty string\n\nNote that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.",
    "tutorial": "First note that $B$ can be always changed to $C$ and vice versa: $\\mathbf{B}\\rightarrow A\\mathbf{C}\\rightarrow A A\\mathbf{B}\\rightarrow\\mathbf{AAA}C\\rightarrow C$. Hence we can replace all $C$'s with $B$'s. Furthermore, see that: $A\\mathbf{B}\\rightarrow A A\\mathbf{C}\\rightarrow\\mathbf{AAA}B\\rightarrow B$. The above implies the set of following rules: $A\\to B B$ $B\\rightarrow A B$ $A B\\to B$ $A A A\\rightarrow\\mathrm{empty\\string}$ We can translate these rules to the following: the number of $B$s can be increased by any non-negative even number the number of $A$s before any $B$ may change arbitrarily The only remaining thing is to determine what should happen to the number of trailing $A$'s. There are three cases: The number of $B$'s is the same in the source and target $\\longrightarrow$ the number of trailing $A$'s can decrease by any non-negative multiple of 3, as no application of the first rule occurs, and the second and third rule cannot affect trailing $A$'s. There are some $B$'s in the source and the number of $B$'s increases $\\longrightarrow\\bigcup$ the number of trailing $A$'s can decrease by any non-negative number. To decrease the number to $k$, just morph the $k + 1$-th $A$ from the end to $BB$. To keep it the same, morph any $B$ to $AB$ and then to $BBB$ to introduce extra $B$'s as needed. There are no $B$'s in the source, but some $B$'s in the target $\\longrightarrow\\bigcup$ the number of trailing $A$'s has to decrease by any positive integer. It is now easy to calculate prefix sums of the $B$ and $C$ occurrences, and calculate the number of trailing $A$'s for every end position. The rest is just casework.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "923",
    "index": "E",
    "title": "Perpetual Subtraction",
    "statement": "There is a number $x$ initially written on a blackboard. You repeat the following action a fixed amount of times:\n\n- take the number $x$ currently written on a blackboard and erase it\n- select an integer uniformly at random from the range $[0, x]$ inclusive, and write it on the blackboard\n\nDetermine the distribution of final number given the distribution of initial number and the number of steps.",
    "tutorial": "We can model this process as a Markov chain with $N + 1$ states with transition matrix $\\frac{\\|\\mathbf{\\hat{l}}\\|\\mathbf{\\hat{l}}\\mathbf{\\hat{l}}}{\\|\\mathbf{\\hat{l}}\\|}_{\\hat{l}}\\mathbf{\\hat{l}}$ The task is to find $R = A^{M} \\cdot P$. A naive solution using Matrix exponentiation is obviously too slow, as it uses $O(N^{3}\\log M)$ time. We need to improve upon it and we look for eigenvalue decomposition. This is a triangular matrix, thus its eigenvalues are the elements on the main diagonal. Hence $\\Lambda=\\left(\\begin{array}{c c c c c c}{{1}}&{{0}}&{{0}}&{{0}}&{{\\dots}}&{{0}}\\\\ {{0}}&{{1/2}}&{{0}}&{{0}}&{{\\dots}}&{{0}}\\\\ {{0}}&{{0}}&{{1/3}}&{{0}}&{{\\dots}}&{{0}}\\\\ {{0}}&{{0}}&{{1/4}}&{{\\vdots}}&{{\\ddots}}&{{0}}\\\\ {{\\vdots}}&{{\\vdots}}&{{}}&{{\\vdots}}&{{\\ddots}}&{{1/(N+1)\\right)$ We can show that the eigenvector corresponding to $\\lambda_{i}=\\operatorname*{in}_{i+1}$ is $v_{i}=((-1)^{i+j}\\cdot{\\binom{i}{j}})_{j=0}^{N}$ (consult proof at the end). Thus, we have ${\\cal O}=\\left(\\begin{array}{c c c c c}{{1}}&{{-1}}&{{-1}}&{{\\dots}}&{{(-1)^{N}}}\\\\ {{0}}&{{1}}&{{-2}}&{{3}}&{{\\dots}}&{{(-1)^{N+1}\\left(N\\right)}}\\\\ {{}}&{{}}&{{}}&{{}}&{{\\ddots}}&{{\\left(-1\\right)^{N+1}\\left(N\\right)}}\\\\ {{\\vdots}}&{{}}&{{}}&{{}}\\\\ {{0}}&{{0}}&{{}}&{{\\vdots}}&{{\\ddots}}&{{}}&{{}}\\\\ {{\\vdots}}&{{}}&{{}}&{{}}&{{}}\\\\ {{0}}&{{}}&{{}}&{{}}&{{}}&{{}}\\end{array}\\right)$ To finalise the eigenvalue decomposition, we need to find the inverse of $Q$. It can be shown $Q$ and $Q^{ - 1}$ are the same up to the sign (consult proof at the end): $Q^{-1}=\\left(\\begin{array}{c c c c c c}{{1}}&{{1}}&{{1}}&{{\\cdot\\cdot\\cdot}}&{{1}}\\\\ {{0}}&{{1}}&{{2}}&{{3}}&{{\\cdot\\cdot\\cdot}}&{{\\binom{N}{\\sqrt}}}\\\\ {{0}}&{{0}}&{{1}}&{{3}}&{{\\cdot\\cdot}}&{{\\binom{N}{2}}}\\\\ {{\\vdots}}&{{\\vdots}}&{{\\vdots}}&{{\\ddots}}&{{\\vdots}}\\\\ {{0}}&{{0}}&{{0}}&{{0}}&{{\\cdot\\cdot\\cdot}}&{{1}}\\end{array}\\right)$ The advantage of eigendecomposition is that $A^{M} = Q \\cdot  \\Lambda ^{M} \\cdot Q^{ - 1},$ where the diagonal matrix $ \\Lambda $ can be exponentiated in $O(N\\log M)$. We can calculate the result as $R = A^{M} \\cdot P = Q \\cdot ( \\Lambda ^{M} \\cdot (Q^{ - 1} \\cdot P)) .$ Performed naively, this runs in $O(N^{2}+N\\log M)$, which is still too slow. We obviously need to multiply with $Q$ (and its inverse) faster. Fortunately, both linear functions $Q$ and $Q^{ - 1}$ are a convolution and we can compute the multiplication in $O(N\\log N)$ using FFT, which is a bit hinted by the modulus in which to compute the answer. Proof of the eigenvectors We show that $\\forall i\\in[0,N],k\\in[0,N]$ it holds $\\begin{array}{l}{{\\sum_{j=0}^{N}v_{i,j}\\cdot A_{k,j}=\\sum_{j=k}^{i}\\left(-1\\right)^{i+j}\\cdot\\left({}_{j}\\right)\\cdot\\frac{1}{j+1}}}\\\\ {{\\sum_{j=k}^{i+1}\\left(\\stackrel{i+j}{\\left(i+1\\right)^{i+j}\\Big(\\stackrel{i+1}{i+1}\\right)\\cdot\\stackrel{i+1}{i+1}}\\cdot\\cdots\\left(-1\\right)^{i+j}\\Big({}_{i+1}^{i+1}\\right)\\cdot\\stackrel{1}{j+1}}}\\\\ {{\\frac{1}{i+1}\\left(-1\\right)^{i+k}\\Big({}_{i+1}\\right)^{i+k}\\Big)\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\left(-1\\right)^{i+k}\\Big({}_{i+1}^{i+1}\\right)\\Big)}}\\end{array}$ where the fifth equality can be proven by induction on $i - k$. Proof of the inverse Denote $P = QQ^{ - 1}$. First, we show that the diagonal of the product only contains ones. This is easy, since the $i$-th row of $Q$ has zeroes until $i - 1$-th column, $i$-th column of $Q^{ - 1}$ has zeroes starting from $i + 1$-th row, and $Q_{i, i} = Q^{ - 1}_{i, i} = 1$. Thus, $P_{i, i} = 1$. Next we show that the $P_{i, j} = 0$ for $i  \\neq  j$. When $i > j$, all the summands in the inner product are zero. It remains to show the claim for $i < j$. $\\begin{array}{l}{{P_{i j}=\\sum_{k=0}^{N}Q_{i k}Q_{k j}^{-1}}}\\\\ {{\\sum_{k=0}^{N}(-1)^{i+k}{\\binom{k}{j}}\\cdot{\\binom{j}{k-i}}^{i+k}{\\binom{j-k}{j-k}}(-1)^{k}{\\binom{j-i}{k-i}}}}\\\\ {{\\frac{j}{k}}\\end{array}$ Proof that $Q$ and $Q^{ - 1}$ are convolutions Put $y = Q^{ - 1}x$. We want to show that $y$ can be computed by convolution. See that $\\begin{array}{l}{{y_{i}=\\sum_{j=0}^{N}Q_{i,j}^{-1}x_{j}}}\\\\ {{=\\sum_{(-1)^{i}}(-1)^{i+j}\\left(j^{i}\\right)x_{j}}}\\\\ {{=\\left.\\frac{(-1)^{i}}{i!}\\sum_{j=i}^{N}(-1)^{j}\\cdot j!\\cdot x_{j}\\cdot\\frac{1}{j-i}}}\\\\ {{=\\frac{(-1)^{i}}{i!}\\sum_{j=i}^{N}f_{x}(j)\\cdot g(j-i)\\,,}}\\end{array}$ hence $y$ is a convolution of functions $f$ and $g$ up to some multiplicative factors. The proof for $Q$ is similar, we can just remove all the $( - 1)^{ \\alpha }$ terms.",
    "tags": [
      "fft",
      "math",
      "matrices"
    ],
    "rating": 3100
  },
  {
    "contest_id": "923",
    "index": "F",
    "title": "Public Service",
    "statement": "There are $N$ cities in Bob's country connected by roads. Some pairs of cities are connected by public transport. There are two competing transport companies — \\textbf{Boblines} operating buses and \\textbf{Bobrail} running trains. When traveling from $A$ to $B$, a passenger always first selects the mode of transport (either bus or train), and then embarks on a journey. For every pair of cities, there are exactly two ways of how to travel between them without visiting any city more than once — one using only bus routes, and the second using only train routes. Furthermore, there is no pair of cities that is directly connected by both a bus route and a train route.\n\nYou obtained the plans of each of the networks. Unfortunately, each of the companies uses different names for the same cities. More precisely, the bus company numbers the cities using integers from $1$ to $N$, while the train company uses integers between $N + 1$ and $2N$. Find one possible mapping between those two numbering schemes, such that no pair of cities is connected directly by both a bus route and a train route. Note that this mapping has to map different cities to different cities.",
    "tutorial": "For $k  \\ge  0$, we call graph $G$ a $k$-star, if we can remove $k$ vertices to form a star, and we cannot remove $k - 1$ vertices to form a star. In this terminology, a $0$-star is a star. It should be rather obvious that if one of the graphs is a 0-star, then the answer is clearly No. This is because the minimum degree of a vertex in a tree is $1$, and star has a vertex of degree $N - 1$, and the corresponding vertex in the merged graph would have degree at least $N$, which is clearly impossible. Surprisingly, the answer is Yes in all other cases. We prove this by giving an explicit construction. There are three cases: Assume that one of the graphs is 1-star. Without loss of generality let it be $G$. Denote $v$ the vertex that can be removed to turn $G$ into star, $u$ its only neighbor, and $w$ be the vertex of degree $N - 2$. In graph $H$, find any leaf and denote it $w'$. Let its only neighbour be $u'$. Furthermore, pick $v'$ a vertex that is not adjacent to $u'$ (such vertex always exists as $H$ is not a star). Observe that mapping $u\\rightarrow u^{\\prime}$, $v\\to v^{\\prime}$ and $w\\to w^{\\prime}$ does not introduce multiedges in the merged graph. Furthermore, all other edges in $G$ are incident to $w$, but none of the unprocessed edges in $H$ are incident to $w'$. We can thus map the remaining $N - 3$ vertices arbitrarily. Mapping a 1-star $G$ (in red), to arbitrary tree $H$ (in blue). See that there are no multiedges between $u, v, w$, no multiedges from $u, v, w$ to the rest of the graph (since $u$, $v$ and $w'$ have no neighbours there), and no multiedges in the rest of the graph (since $G\\setminus\\{u,v,w\\}$ is a graph with zero edges). Mapping a 1-star $G$ (in red), to arbitrary tree $H$ (in blue). See that there are no multiedges between $u, v, w$, no multiedges from $u, v, w$ to the rest of the graph (since $u$, $v$ and $w'$ have no neighbours there), and no multiedges in the rest of the graph (since $G\\setminus\\{u,v,w\\}$ is a graph with zero edges). $N = 4$ or $N = 5$: There are only five non-isomorphic trees on this many vertices. Two of them are 0-stars (for which the answer is No), two of them are 1-stars (that we handled in previous case). The only remaining graph is a path on five vertices. Two such graphs can always be merged together. For simplicity of implementation, we can simply try all $5!$ possible mappings. All trees on 4 or 5 vertices. All trees on 4 or 5 vertices. Otherwise, we use induction. In $G$, find two leaves $u$ and $v$ such that $d(u, v)  \\ge  3$ and $G\\setminus\\{u,v\\}$ is not a star. This is always possible: either $G$ is a 2-star, and then we can pick one of the neighbouring leaves of the vertex with highest degree and one other leaf, or we can pick any two leaves that are not adjacent to the same vertex. Do the same thing for $H$, finding $u'$ and $v'$. Remove these pairs of vertices from the respective graphs and use induction to merge those smaller graphs. Now we can either map $u\\to u^{\\prime}$, $v\\to v^{\\prime}$ or $u\\to v^{\\prime}$, $v\\to u^{\\prime}$ - as only one of these mappings may introduce a multiedge. The above is relatively simple to implement in $O(n^{2})\\,$. To turn it into an $O(n\\log n)$ algorithm, we need to maintain a few additional information about the graph. Furthemore, note that a graph $G$ is a $k$-star if and only if the maximum degree is $|G| - k - 1$. The list vertices sorted by their degree, for instance using set of pairs. This is so that we can find the vertex with maximum degree easily, which is useful for testing $k$-starness. the set of vertices with a leaf neighbour, and the set of leaves neighbouring a given vertex, so that we can find the leaves quickly Using the above, we can always find appropriate leaf and remove it in $O(\\log n)$, which is sufficient.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "924",
    "index": "A",
    "title": "Mystical Mosaic",
    "statement": "There is a rectangular grid of $n$ rows of $m$ initially-white cells each.\n\nArkady performed a certain number (possibly zero) of operations on it. In the $i$-th operation, a non-empty subset of rows $R_{i}$ and a non-empty subset of columns $C_{i}$ are chosen. For each row $r$ in $R_{i}$ and each column $c$ in $C_{i}$, the intersection of row $r$ and column $c$ is coloured black.\n\nThere's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of $(i, j)$ ($i < j$) exists such that $R_{i}\\cap R_{j}\\neq\\varnothing$ or $C_{i}\\cap C_{j}\\neq\\varnothing$, where $\\bigcap{}$ denotes intersection of sets, and $\\textstyle{\\mathcal{O}}$ denotes the empty set.\n\nYou are to determine whether a valid sequence of operations exists that produces a given final grid.",
    "tutorial": "No row or column can be selected more than once, hence whenever a row $r$ is selected in an operation, all cells in it uniquely determine the set of columns that need to be selected - let's call it $S_{r}$. Let's assume a valid set of operations exists. Take out any two rows, $i$ and $j$. If rows $i$ and $j$ are selected in the same operation, we can deduce that $S_{i} = S_{j}$; if they're in different operations, we get $S_{i}\\cap S_{j}=\\varnothing$. Therefore, if $S_{i}  \\neq  S_{j}$ and $S_{i}\\cap S_{j}\\neq\\varnothing$ hold for any pair of rows $(i, j)$, no valid operation sequence can be found. Otherwise (no pair violates the condition above), a valid sequence of operations can be constructed: group all rows with the same $S$'s and carry out an operation with each group. Thus, it's a necessary and sufficient condition for the answer to be \"Yes\", that for each pair of rows $(i, j)$, either $S_{i} = S_{j}$ or $S_{i}\\cap S_{j}=\\varnothing$ holds. The overall complexity is $O(n^{2}m)$. It can be divided by the system's word size if you're a bitset enthusiast, and a lot more if hashes and hash tables release their full power.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <vector>\nstatic const int MAXN = 1004;\n\nstatic int n, m;\nstatic bool g[MAXN][MAXN];\n// c[i] = set of rows where the i-th column is coloured\nstatic std::vector<int> c[MAXN];\nstatic bool checked[MAXN] = { false };\n\nint main()\n{\n    scanf(\"%d%d\", &n, &m); getchar();\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j <= m; ++j) {\n            g[i][j] = (getchar() == '#');\n            if (g[i][j]) c[j].push_back(i);\n        }\n\n    for (int i = 0; i < n; ++i) if (!checked[i]) {\n        std::vector<int> r;\n        for (int j = 0; j < m; ++j) if (g[i][j])\n            for (int k : c[j]) r.push_back(k);\n        std::sort(r.begin(), r.end());\n        r.resize(std::unique(r.begin(), r.end()) - r.begin());\n\n        for (int k : r) {\n            if (checked[k]) { puts(\"No\"); return 0; }\n            checked[k] = true;\n            for (int p = 0; p < m; ++p)\n                if (g[i][p] != g[k][p]) { puts(\"No\"); return 0; }\n        }\n    }\n\n    puts(\"Yes\"); return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "924",
    "index": "B",
    "title": "Three-level Laser",
    "statement": "An atom of element X can exist in $n$ distinct states with energies $E_{1} < E_{2} < ... < E_{n}$. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme.\n\nThree distinct states $i$, $j$ and $k$ are selected, where $i < j < k$. After that the following process happens:\n\n- initially the atom is in the state $i$,\n- we spend $E_{k} - E_{i}$ energy to put the atom in the state $k$,\n- the atom emits a photon with useful energy $E_{k} - E_{j}$ and changes its state to the state $j$,\n- the atom spontaneously changes its state to the state $i$, losing energy $E_{j} - E_{i}$,\n- the process repeats from step 1.\n\nLet's define the energy conversion efficiency as $\\eta={\\frac{E_{k}-E_{i}}{E_{k}-E_{i}}}$, i. e. the ration between the useful energy of the photon and spent energy.\n\nDue to some limitations, Arkady can only choose such three states that $E_{k} - E_{i} ≤ U$.\n\nHelp Arkady to find such the maximum possible energy conversion efficiency within the above constraints.",
    "tutorial": "First of all, you can note that for fixed $i$ and $k$ setting $j = i + 1$ is always the best choice. Indeed, if $X > Y$, then ${\\frac{A-X}{B}}<{\\frac{A-Y}{B}}$ for positive $B$. Then, let's fix $i$. Then $j = i + 1$, and what is the optimal $k$? We can define the energy loss as $l=1-\\eta={\\frac{E_{i}-E_{i}}{E_{i}-E}}$. As we need to minimize the loss, it's obvious that we should maximize $E_{k}$, so we should choose as large $k$ as possible satisfying $E_{k} - E_{i}  \\le  U$. This is a classic problem that can be solved with two pointers approach, this leads to $O(n)$ solution, or with binary search approach, this leads to $O(n\\log n)$ solution. Both are acceptable.",
    "code": "#include <iostream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n#include <cmath>\n#include <queue>\n#include <string>\n#include <cstring>\n#include <cassert>\n#include <iomanip>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <ctime>\n#include <cmath>\n\n#define forn(i, n) for(int i=0;i<n;++i)\n#define fore(i, l, r) for(int i = int(l); i <= int(r); ++i)\n#define sz(v) int(v.size())\n#define all(v) v.begin(), v.end()\n#define pb push_back\n#define mp make_pair\n#define x first\n#define y1 ________y1\n#define y second\n#define ft first\n#define sc second\n#define pt pair<int, int>\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntypedef long long li;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int INF = 1000 * 1000 * 1000;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n\nconst int N = 100 * 1000 + 13;\n\nint n, u;\nint a[N];\nint idx1 = -1, idx2, idx3;\n\ninline void read() {\t\n\tscanf(\"%d%d\", &n, &u);\n\tfor (int i = 0; i < n; i++) {\n\t\tscanf(\"%d\", &a[i]);\n\t}\n}\n\ninline void solve() {\n\tint k = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tk = max(k, i);\n\t\twhile (k + 1 < n && a[k + 1] - a[i] <= u) {\n      \t\tk++;\n\t\t}\n        if (k - i - 1 <= 0) {\n        \tcontinue;\n        }\n        int j = i + 1;\n\n        if (idx1 == -1 || (a[k] - a[j]) * 1ll * (a[idx3] - a[idx1]) > (a[idx3] - a[idx2]) * 1ll * (a[k] - a[i])) {\n\t\t\tidx1 = i, idx2 = j, idx3 = k;        \t\n        }\n\t}\t\n\n\tif (idx1 == -1) {\n\t\tcout << -1 << endl;\n\t\treturn;\n\t}\n\n\tcout.precision(20);\n    cout << (double)(a[idx3] - a[idx2]) / (a[idx3] - a[idx1]) << endl;\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    srand(time(NULL));\n    cerr << setprecision(10) << fixed;\n    \n    read();\n    solve();\n \n    //cerr << \"TIME: \" << clock() << endl;\n}",
    "tags": [
      "binary search",
      "greedy",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "924",
    "index": "C",
    "title": "Riverside Curio",
    "statement": "Arkady decides to observe a river for $n$ consecutive days. The river's water level on each day is equal to some real value.\n\nArkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the $i$-th day this value is equal to $m_{i}$.\n\nDefine $d_{i}$ as the number of marks strictly under the water level on the $i$-th day. You are to find out the minimum possible sum of $d_{i}$ over all days. There are no marks on the channel before the first day.",
    "tutorial": "Define $t_{i}$ as the total number of marks (above or at or under the water level) on the $i$-th day. As $t_{i} = m_{i} + 1 + d_{i}$, minimizing $\\textstyle\\sum d_{i}$ is equivalent to minimizing $\\textstyle\\sum t_{i}$. For the $i$-th day we would like to find the minimum value of $t_{i}$. Needless to say $t_{i}  \\ge  max{t_{i - 1}, m_{i} + 1}$ should hold. On each day we can increase $t$ by at most one, thus $t_{i}  \\ge  t_{i + 1} - 1$, which is equivalent to the condition that $t_{i}  \\ge  t_{j} - (j - i)$ holds for all $j > i$. The first condition is straightforward - just go over from left to right and keep a record; but how to ensure that the second condition hold? One of the approaches is going backwards. Go from right to left and keep a counter which, on each day, decreases by $1$ and then is taken maximum with the $t_{i}$ currently at hand. This counter always records the minimum required $t_{i}$ value that satisfies the second condition. Assign this counter to $t_{i}$ along the way. Based on such minimum decisions, raising any $t_{i}$ by any positive value does not allow other $t_{i}$'s to be reduced. Hence summing this value over all days provides us with an optimal answer in $O(n)$ time.",
    "code": "#include <cstdio>\n#include <algorithm>\n\ntypedef long long int64;\nstatic const int MAXN = 1e5 + 4;\n\nstatic int n, m[MAXN];\nstatic int t[MAXN];\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) scanf(\"%d\", &m[i]);\n\n    for (int i = n - 1, cur = 0; i >= 0; --i) {\n        cur = std::max(0, cur - 1);\n        cur = std::max(cur, m[i] + 1);\n        t[i] = cur;\n    }\n\n    int64 ans = 0;\n    for (int i = 0, cur = 0; i < n; ++i) {\n        cur = std::max(cur, t[i]);\n        ans += cur;\n    }\n\n    for (int i = 0; i < n; ++i) ans -= (m[i] + 1);\n    printf(\"%lld\\n\", ans);\n\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "924",
    "index": "D",
    "title": "Contact ATC",
    "statement": "Arkady the air traffic controller is now working with $n$ planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point $0$ on it. The $i$-th plane, small enough to be represented by a point, currently has a coordinate of $x_{i}$ and is moving with speed $v_{i}$. It's guaranteed that $x_{i}·v_{i} < 0$, i.e., all planes are moving towards the station.\n\nOccasionally, the planes are affected by winds. With a wind of speed $v_{wind}$ (not necessarily positive or integral), the speed of the $i$-th plane becomes $v_{i} + v_{wind}$.\n\nAccording to weather report, the current wind has a steady speed falling inside the range $[ - w, w]$ (inclusive), but the exact value cannot be measured accurately since this value is rather small — smaller than the absolute value of speed of any plane.\n\nEach plane should contact Arkady at the exact moment it passes above his station. And you are to help Arkady count the number of pairs of planes $(i, j)$ ($i < j$) there are such that there is a possible value of wind speed, under which planes $i$ and $j$ contact Arkady at the same moment. This value needn't be the same across different pairs.\n\nThe wind speed is the same for all planes. You may assume that the wind has a steady speed and lasts arbitrarily long.",
    "tutorial": "Stuck in tedious fractions produced by kinematic formulae? No, that's not the way to go. Forgetting about all physics, how does wind speed affect the time when a plane flies over the origin? Consider a plane flying from left to right, passing through the origin. Initially it has speed $v_{i} - w$ and meets the origin at time $t$. As the wind speed goes from $- w$ to $+ w$, the plane's speed continually rises to $v_{i} + w$, with $t$ becoming smaller and smaller (this is true because $w < |v_{i}|$). The similar holds for planes going from right to left, with the exception that $t$ becomes greater and greater. Then, how does wind speed affect the order in which a pair of planes pass the origin? Imagine two planes, $A$ and $B$. With wind speed $- w$, they arrive at the origin at moments $t_{A}$ and $t_{B}$, respectively. As the wind speed goes from $- w$ to $+ w$, $t_{A}$ moves smoothly and so does $t_{B}$ and suddenly... Uh! They become the same! That makes them a valid pair. From this perspective we can conclude that for such a pair of planes $A$ and $B$, if $A$ arrives at the origin at moment $t_{A}$ and $t'_{A}$ with wind speed $- w$ and $+ w$, and $B$ at $t_{B}$ and $t'_{B}$ respectively, they possibly meet at the origin iff $(t_{A} - t_{B}) \\cdot (t'_{A} - t'_{B})  \\le  0$. Oh, what's this? Inversion pairs, of course! Apply wind $- w$ and $+ w$ to all the planes, find out the orders in which they arrive at the origin under the two winds, and count the pairs $(A, B)$ where $A$ goes before $B$ in the first permutation, and after $B$ in the second one. One detail to note is that in case of ties, pairs should be sorted by descending values of speed in the first pass and ascending in the second (the speeds cannot be the same since all planes are distinct). That leaves us only with a binary indexed tree to be implemented. The overall time complexity is $O(n\\log n)$. Please note that it's recommended to use an integer pair to represent a fraction, since the difference between arrival times can be as little as $10^{ - 10}$ - though a floating point error tolerance of $5  \\times  10^{ - 12}$ passes all tests, its robustness is not so easy to control.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <utility>\n\ntypedef long long int64;\nstatic const int MAXN = 1e5 + 4;\nstatic const int MAXX = 1e8 + 4;\n\nstatic int n, w;\nstatic int x[MAXN], v[MAXN];\n\nstruct fraction {\n    template <typename T> static inline T gcd(const T a, const T b) {\n        return (b == 0) ? a : gcd(b, a % b);\n    }\n\n    int64 num, deno;\n    inline void simplify() {\n        if (deno < 0) { num *= -1; deno *= -1; }\n        int64 g = gcd(num < 0 ? -num : num, deno); num /= g; deno /= g;\n    }\n\n    fraction() { }\n    fraction(int64 num, int64 deno) : num(num), deno(deno) { simplify(); }\n\n    inline bool operator < (const fraction &rhs) const {\n        return num * rhs.deno < deno * rhs.num;\n    }\n    inline bool operator != (const fraction &rhs) const {\n        return num * rhs.deno != deno * rhs.num;\n    }\n};\n\n// Time bounds at which clouds can arrive at the origin\nstatic std::pair<fraction, fraction> t[MAXN];\n// Used at discretization\nstatic std::pair<fraction, int> d[MAXN];\nstatic int p[MAXN];\n\nstruct bit {\n    static const int MAXN = ::MAXN;\n    int f[MAXN];\n    bit() { std::fill(f, f + MAXN, 0); }\n    inline void add(int pos, int inc) {\n        for (++pos; pos < MAXN; pos += (pos & -pos)) f[pos] += inc;\n    }\n    inline int sum(int rg) {\n        int ans = 0;\n        for (++rg; rg; rg -= (rg & -rg)) ans += f[rg];\n        return ans;\n    }\n    inline int sum(int lf, int rg) {\n        return sum(rg) - sum(lf - 1);\n    }\n} arkady;\n\nint main()\n{\n    scanf(\"%d%d\", &n, &w);\n    for (int i = 0; i < n; ++i) scanf(\"%d%d\", &x[i], &v[i]);\n\n    for (int i = 0; i < n; ++i) {\n        int64 v1 = v[i] - w, v2 = v[i] + w;\n        t[i] = {fraction(-x[i], v1), fraction(-x[i], v2)};\n    }\n\n    for (int i = 0; i < n; ++i) t[i].second.num *= -1;\n    std::sort(t, t + n);\n    for (int i = 0; i < n; ++i) t[i].second.num *= -1;\n    for (int i = 0; i < n; ++i) d[i] = {t[i].second, i};\n    std::sort(d, d + n);\n    for (int i = 0, rk = -1; i < n; ++i) {\n        if (i == 0 || d[i].first != d[i - 1].first) ++rk;\n        p[d[i].second] = rk;\n    }\n    /*for (int i = 0; i < n; ++i)\n        printf(\"%.4lf %.4lf | %d\\n\",\n            (double)t[i].first.num / t[i].first.deno,\n            (double)t[i].second.num / t[i].second.deno, p[i]);*/\n\n    int64 ans = 0;\n    for (int i = 0; i < n; ++i) {\n        ans += arkady.sum(p[i], MAXN - 1);\n        arkady.add(p[i], 1);\n    }\n\n    printf(\"%lld\\n\", ans);\n\n    return 0;\n}",
    "tags": [],
    "rating": 2500
  },
  {
    "contest_id": "924",
    "index": "E",
    "title": "Wardrobe",
    "statement": "Olya wants to buy a custom wardrobe. It should have $n$ boxes with heights $a_{1}, a_{2}, ..., a_{n}$, stacked one on another in some order. In other words, we can represent each box as a vertical segment of length $a_{i}$, and all these segments should form a single segment from $0$ to $\\textstyle\\sum_{i=1}^{n}a_{i}$ without any overlaps.\n\nSome of the boxes are important (in this case $b_{i} = 1$), others are not (then $b_{i} = 0$). Olya defines the convenience of the wardrobe as the number of important boxes such that their bottom edge is located between the heights $l$ and $r$, inclusive.\n\nYou are given information about heights of the boxes and their importance. Compute the maximum possible convenience of the wardrobe if you can reorder the boxes arbitrarily.",
    "tutorial": "The first idea of the author's solution is to reverse the problem: change $l$ to $H - r$ and $r$ to $H - l$, where $H$ is the total height of the wardrobe. Now an important box is counted in the answer if and only if its top edge is within the segment $[l, r]$. We'll see later the profit of this operation. Now, we'll build a wardrobe of arbitrary height using only a subset of the boxes, and choose the maximum possible answer. Why can we remove the constraint to use all boxes? We can always assume that we add all the boxes we don't take at the top of the boxes we take, and the answer won't decrease. So, we can do some kind of knapsack, where not taking a box means putting it on the top after considering all boxes. What we don't know is how to compute the answer and in which order to consider the boxes in the knapsack. Ok, if we consider them in such an order that there is an optimal answer in which the boxes we \"take\" in the knapsack always come in this order, then computing the answer is easy: we can always assume that we put a new box on the top of already taken ones, and add $1$ to the current answer if it is an important box and its top edge falls in the range $[l, r]$. Now we should find such an order. Note that in an optimal answer we can always arrange boxes in this order: some number of unimportant boxes, then some number of important boxes that don't increase the answer, then some number of important boxes that increase the answer, and after that a mix of important and unimportant boxes which don't count in the answer and that we consider as \"not taken\" in the knapsack. This means that we can first consider all unimportant boxes in the knapsack, and then all important ones. It's also easy to see that the order of unimportant boxes does not matter. However, it turns out that the order of important boxes matters. To choose the order of important boxes, we can use an old, but good trick. Suppose two important boxes with heights $a_{i}$ and $a_{j}$ stand one on the other. Answer the question: \"What is the condition such that if it is satisfied, then it is always better to put $a_{j}$ on the top of $a_{i}$, and not vice versa?\" Here we consider only the boxes that count in the answer and those under them, because other we simply \"don't take\" in the knapsack. It turns out that the condition is simple: $a_{j}  \\le  a_{i}$, no matter do these boxes count in the answer or not. Here we used the fact that we inversed the problem, and the position of the top edge matters, not the bottom one. So, as we now know that it is always optimal to put the important boxes from largest to smallest (in the inversed problem), we can sort them in that order and perform the knapsack. The complexity is $O(n\\cdot\\sum a_{i})$. This can also be reduced to $O(H{\\sqrt{H}})$ where $H$ is the height of the wardrobe, using a standard optimization for the knapsack.",
    "code": "/**\n * This is a solution for problem wardrobe\n * This is nk_ok.cpp\n * \n * @author: Nikolay Kalinin\n * @date: Tue, 20 Mar 2018 21:48:33 +0300\n */\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n\n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nstruct tbox\n{\n    int h, t;\n};\n\ninline bool operator<(const tbox &a, const tbox &b)\n{\n    if (a.t != b.t) return a.t < b.t;\n    return a.h > b.h;\n}\n\nconst int maxn = 10005;\nconst int inf = 1e9;\n\ntbox b[maxn];\nint ans[maxn];\nint n, l, r;\n\nint main()\n{\n    scanf(\"%d%d%d\", &n, &l, &r);\n    int sumh = 0;\n    for (int i = 0; i < n; i++)\n    {\n        scanf(\"%d\", &b[i].h);\n        sumh += b[i].h;\n    }\n    tie(l, r) = pair{sumh - r, sumh - l};\n    for (int i = 0; i < n; i++) scanf(\"%d\", &b[i].t);\n    sort(b, b + n);\n    for (int i = 0; i <= sumh; i++) ans[i] = -inf;\n    ans[0] = 0;\n    for (int i = 0; i < n; i++)\n    {\n        for (int h = sumh - b[i].h; h >= 0; h--) ans[h + b[i].h] = max(ans[h + b[i].h], ans[h] + b[i].t * (h + b[i].h >= l && h + b[i].h <= r));\n    }\n    cout << *max_element(ans, ans + sumh + 1) << endl;\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "924",
    "index": "F",
    "title": "Minimal Subset Difference",
    "statement": "We call a positive integer $x$ a $k$-beautiful integer if and only if it is possible to split the multiset of its digits in the decimal representation into two subsets such that the difference between the sum of digits in one subset and the sum of digits in the other subset is \\textbf{less than or equal to} $k$. Each digit should belong to exactly one subset after the split.\n\nThere are $n$ queries for you. Each query is described with three integers $l$, $r$ and $k$, which mean that you are asked how many integers $x$ between $l$ and $r$ (inclusive) are $k$-beautiful.",
    "tutorial": "Let $f(x)$ be the minimal subset difference mentioned in the problem statement. The problem seems like a regular digit DP problem. However, it's a bit hard to reduce the number of DP states. Let's take a careful consideration. For a given integer $x$, we can use knapsack DP to determine $f(x)$. Denote the sum of digits of $x$ as $s(x)$. You can just calculate whether there is a subset such that the sum of the subset is a fixed number $y$, and then find the maximal $y$ $\\left(0\\leq y\\leq{\\frac{s(x)}{2}}\\right)$ which concludes $f(x) = s(x) - 2y$. By the way, this type of knapsack DP could be implemented by bitwise operation. If we defined $dp(len, sum, state)$ as the number of integers $x$ such that the length of $x$ is $len$, the digit sum is $sum$, and the knapsack DP array is $state$ (an array only consisting $0$ and $1$, which could be represented as bit vector), the problem would be difficult to solve. For example, to represent $x = 88888888899999999$, a case of $f(x) = 0$, the length of $state$ might be $73$, which is a bit long vector. Although most of $state$s satisfy $dp(len, sum, state) = 0$, there are still many $state$s which might be used. You may notice the order of digits is unnecessary for the knapsack DP. If we defined $state$ as the number of appearance of digits $1, 2, ..., 9$ (digit $0$ is unnecessary), the number of $state$s would be ${\\binom{18+9}{9}}\\approx5\\cdot10^{6}$. Hence, we can apply knapsack DP for each $state$ first and then calculate for digit DP. Here are more details. Let's redefine $dp(len, k, state)$ as the number of ways to arrange the lowest $len$ digits of $x$ such that $f(x) = k$ and the other digits (higher than the lowest $len$ digits) form the $state$ (i. e. the number of appearance of digits $1, 2, ..., 9$). We firstly search all the $state$s such that the total number of appearance $ \\le  18$ and $f(x) = k$, and then set $dp(0, k, state) = 1$. After searching, we calculate $dp(len, k, new state)$ from $dp(len - 1, k, state) > 0$ by enumerating the $len$-th digit. However, the number of $dp(len, k, state) > 0$ is still too large to calculate for digit DP. You should notice that in decimal representation it always has $0  \\le  f(x)  \\le  9$ for any integer $x$. Furthermore, because of the distribution of digits, most of $state$s are in cases of $f(x) = 0, 1$ (you can make a knapsack DP to prove). In addition, it is easy to show $f(x)$ and $s(x)$ always have the same parity, so we can apply inclusion-exclusion principle to solve the problem only in the cases of $f(x)  \\ge  2$ and another counting problem with fixed parity of $s(x)$. The total time complexity in above is $\\cal O\\left(\\!\\!\\begin{array}{c}{{(L+D)}}\\\\ {{D}}\\end{array}\\!\\!\\right)+L D S\\log S+n(9-k)L D\\log S\\!\\!\\!\\mathrm{\\!}\\ \\!\\!\\mathrm{\\!}\\ \\!\\right)$, where $L$ $( = 18)$ is the maximal length of $x$, $D$ $( = 9)$ is the maximal digit, and $S$ $(  \\approx  3 \\cdot 10^{4})$ is the number of distinct $state$s such that there exists $dp(len, k, state) > 0$ $(0  \\le  len  \\le  L, 2  \\le  k  \\le  9)$. However, it can hardly pass the tests with $n = 5 \\cdot 10^{4}$, because we have some fairly worse tests to maximize the times of $dp$ access (e. g. $l$ and $r$ have a lot of $9$ as digits and $k = 1$). We could make a tradeoff between pretreatment and queries by several ways. For example, define $dp(len, k, state, upp)$ as the similar but it memorizes that the $len$-th digit is less than $upp$. If we did that, the total time complexity would be $\\ O\\left({(\\stackrel{(L+D)}{D})}+L D S\\log S+n(9-k)L\\log S\\right)$, which is acceptable. The aforementioned solution is not easy to code; you can use some advanced approach to get accepted, though.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\nconst int maxd = 10, maxl = 18, maxs = 81, BLEN = 5, BMSK = 31;\nstruct States {\n\tvector<LL> keys, vals[maxd + 1];\n\tvoid insert(LL key) {\n\t\tkeys.push_back(key);\n\t}\n\tvoid initialize(LL val = 0) {\n\t\tsort(keys.begin(), keys.end());\n\t\tkeys.erase(unique(keys.begin(), keys.end()), keys.end());\n\t\tfor(int i = 0; i < maxd; ++i)\n\t\t\tvals[i].assign(keys.size(), val);\n\t}\n\tvoid summation() {\n\t\tfor(int i = 1; i < maxd; ++i)\n\t\t\tfor(vector<LL>::iterator it = vals[i - 1].begin(), jt = vals[i].begin(); jt != vals[i].end(); ++it, ++jt)\n\t\t\t\t*jt += *it;\n\t}\n\tsize_t size() const {\n\t\treturn keys.size();\n\t}\n\tvoid update(int upp, LL key, LL adt) {\n\t\tvals[upp][lower_bound(keys.begin(), keys.end(), key) - keys.begin()] += adt;\n\t}\n\tLL find(int upp, LL key) {\n\t\tvector<LL>::iterator it = lower_bound(keys.begin(), keys.end(), key);\n\t\tif(it == keys.end() || *it != key)\n\t\t\treturn 0;\n\t\treturn vals[upp][it - keys.begin()];\n\t}\n} f[maxd + 1][maxl + 1];\nLL c[2][maxl + 1], bit[maxd + 1];\nbitset<maxs + 1> vis[maxd + 1];\nvoid dfs(int dep, int cnt, int sum, LL msk) {\n\tif(dep == maxd) {\n\t\tfor(int i = sum >> 1; i >= 0; --i)\n\t\t\tif(vis[dep - 1].test(i)) {\n\t\t\t\tint dif = sum - i - i;\n\t\t\t\tif(dif > 1)\n\t\t\t\t\tf[dif][0].insert(msk);\n\t\t\t\tbreak;\n\t\t\t}\n\t\treturn;\n\t}\n\tvis[dep] = vis[dep - 1];\n\tdfs(dep + 1, cnt, sum, msk);\n\twhile(cnt < maxl) {\n\t\tvis[dep] |= vis[dep] << dep;\n\t\tdfs(dep + 1, ++cnt, sum += dep, msk += bit[dep]);\n\t}\n}\nLL solve(int dif, LL lim) {\n\tchar dig[maxl + 3];\n\tint len = sprintf(dig, \"%lld\", lim);\n\tLL ret = 0, msk = 0;\n\tStates *F = f[dif];\n\tfor(int i = 0; i < len; ++i) {\n\t\tdig[i] -= '0';\n\t\tif(len - i > maxl) {\n\t\t\tfor(int j = 0; j < dig[i]; ++j)\n\t\t\t\tret += F[len - i - 1].find(maxd - 1, msk);\n\t\t} else if(dig[i]) {\n\t\t\tret += F[len - i].find(dig[i] - 1, msk);\n\t\t\tmsk += bit[dig[i]];\n\t\t}\n\t}\n\treturn ret;\n}\nLL solve2(LL lim) {\n\tchar dig[maxl + 3];\n\tint len = sprintf(dig, \"%lld\", lim), part = 0;\n\tLL ret = 0;\n\tfor(int i = 0; i < len; ++i) {\n\t\tdig[i] -= '0';\n\t\tint odd = dig[i] >> 1, even = (dig[i] + 1) >> 1;\n\t\tret += c[part][len - 1 - i] * odd + c[part ^ 1][len - 1 - i] * even;\n\t\tpart ^= dig[i] & 1;\n\t}\n\treturn ret;\n}\nint main() {\n\tc[0][0] = 1;\n\tfor(int i = 0; i < maxl; ++i) {\n\t\tint odd = maxd >> 1, even = (maxd + 1) >> 1;\n\t\tc[0][i + 1] = c[0][i] * even + c[1][i] * odd;\n\t\tc[1][i + 1] = c[0][i] * odd + c[1][i] * even;\n\t}\n\tbit[1] = 1;\n\tfor(int i = 2; i < maxd; ++i)\n\t\tbit[i] = bit[i - 1] << BLEN;\n\tvis[0].set(0);\n\tdfs(1, 0, 0, 0);\n\tfor(int i = 2; i < maxd; ++i) {\n\t\tf[i][0].initialize(1);\n\t\tfor(int j = 0; j < maxl; ++j) {\n\t\t\tStates &cur = f[i][j], &nxt = f[i][j + 1];\n\t\t\tfor(int idx = 0, sz = cur.size(); idx < sz; ++idx) {\n\t\t\t\tint cnt = j;\n\t\t\t\tLL msk = cur.keys[idx], tmp = msk;\n\t\t\t\tfor(int k = 1; k < maxd; ++k, tmp >>= BLEN) {\n\t\t\t\t\tint rem = tmp & BMSK;\n\t\t\t\t\tif(!rem)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tcnt += rem;\n\t\t\t\t\tnxt.insert(msk - bit[k]);\n\t\t\t\t}\n\t\t\t\tif(cnt < maxl)\n\t\t\t\t\tnxt.insert(msk);\n\t\t\t}\n\t\t\tnxt.initialize(0);\n\t\t\tfor(int idx = 0, sz = cur.size(); idx < sz; ++idx) {\n\t\t\t\tint cnt = j;\n\t\t\t\tLL msk = cur.keys[idx], ways = cur.vals[maxd - 1][idx], tmp = msk;\n\t\t\t\tfor(int k = 1; k < maxd; ++k, tmp >>= BLEN) {\n\t\t\t\t\tint rem = tmp & BMSK;\n\t\t\t\t\tif(!rem)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tcnt += rem;\n\t\t\t\t\tnxt.update(k, msk - bit[k], ways);\n\t\t\t\t}\n\t\t\t\tif(cnt < maxl)\n\t\t\t\t\tnxt.update(0, msk, ways); \n\t\t\t}\n\t\t\tnxt.summation();\n\t\t}\n\t}\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int Case = 1; Case <= t; ++Case) {\n\t\tLL L, R;\n\t\tint k;\n\t\tscanf(\"%lld%lld%d\", &L, &R, &k);\n\t\tLL ans = R + 1 - L;\n\t\tif(!k) {\n\t\t\tans -= solve2(R + 1) - solve2(L);\n\t\t\tfor(int i = 2; i < maxd; i += 2)\n\t\t\t\tans -= solve(i, R + 1) - solve(i, L);\n\t\t} else {\n\t\t\tfor(int i = k + 1; i < maxd; ++i)\n\t\t\t\tans -= solve(i, R + 1) - solve(i, L);\n\t\t}\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 3200
  },
  {
    "contest_id": "925",
    "index": "A",
    "title": "Stairs and Elevators",
    "statement": "In the year of $30XX$ participants of some world programming championship live in a single large hotel. The hotel has $n$ floors. Each floor has $m$ sections with a single corridor connecting all of them. The sections are enumerated from $1$ to $m$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $n$ and width $m$. We can denote sections with pairs of integers $(i, j)$, where $i$ is the floor, and $j$ is the section number on the floor.\n\nThe guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $(1, x)$, $(2, x)$, $\\ldots$, $(n, x)$ for some $x$ between $1$ and $m$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $v$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.\n\nYou are to process $q$ queries. Each query is a question \"what is the minimum time needed to go from a room in section $(x_1, y_1)$ to a room in section $(x_2, y_2)$?\"",
    "tutorial": "First thing to mention is that we can use no more than one stairs or elevator per query. Indeed, optimal path is always a few sections horizontally, then a stair of elevator, then a few sections horizontally. Then, we can note that we can always use one of the nearest stairs/elevators to start/finish. Using this fact, we can binary search in the sequence of stairs/elevators to find the optimal one, and choose the optimum between using a stairs and an elevator. Don't forget about the case where you don't have to reach any stairs/elevators. The complexity is $O(q \\log{n})$.",
    "tags": [
      "binary search"
    ],
    "rating": 1600
  },
  {
    "contest_id": "925",
    "index": "B",
    "title": "Resource Distribution",
    "statement": "One department of some software company has $n$ servers of different specifications. Servers are indexed with consecutive integers from $1$ to $n$. Suppose that the specifications of the $j$-th server may be expressed with a single integer number $c_j$ of artificial resource units.\n\nIn order for production to work, it is needed to deploy two services $S_1$ and $S_2$ to process incoming requests using the servers of the department. Processing of incoming requests of service $S_i$ takes $x_i$ resource units.\n\nThe described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $S_i$ is deployed using $k_i$ servers, then the load is divided equally between these servers and each server requires only $x_i / k_i$ (that may be a fractional number) resource units.\n\nEach server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.\n\nDetermine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.",
    "tutorial": "Suppose that the load of the first service was divided among $k_1$ servers and the load of the second service was divided among $k_2$ servers. In such case first service will be running on $k_1$ servers of resource at least $p_1 = \\lceil x_1 / k_1 \\rceil$ and second service will be run on $k_2$ servers of resource at least $p_2 = \\lceil x_2 / k_2 \\rceil$. Suppose that $p_1 \\leq p_2$, the remaining case will be dealt in the similar way. Remove all servers that have less than $p_1$ resources, we are not going to use them. We may consider only assignments in which any server assigned to the first service has at most as many resources as any server assigned to the second service (otherwise we may swap them and the answer will still be correct). In such manner we may show that the first service may be assigned to the first $k_1$ servers having at least $p_1$ resource units and the second service may be assigned to the last $k_2$ servers in ascending order of available resources. Finally notice that if we fix $k_1$, the optimal value of $k_2$ is minimum such that the last $k_2$ servers have at least $p_2$ resource units. Calculate the minimum possible $k_2$ in linear time, after that try each possible value of $k_1$ and check if the first $k_1$ servers having at least $p_1$ resource units do not intersect with the last $k_2$ servers (it may be checked in a single binary search). We got a solution with running time of $O(n \\log n)$.",
    "tags": [
      "binary search",
      "implementation",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "925",
    "index": "C",
    "title": "Big Secret",
    "statement": "Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer \\sout{54} 42, but an increasing integer sequence $a_1, \\ldots, a_n$. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence $b_1, \\ldots, b_n$ using the following rules:\n\n- $b_1 = a_1$;\n- $b_i = a_i \\oplus a_{i - 1}$ for all $i$ from 2 to $n$, where $x \\oplus y$ is the bitwise XOR of $x$ and $y$.\n\nIt is easy to see that the original sequence can be obtained using the rule $a_i = b_1 \\oplus \\ldots \\oplus b_i$.\n\nHowever, some time later Vitya discovered that the integers $b_i$ in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers $b_i$ so that the sequence $a_i = b_1 \\oplus \\ldots \\oplus b_i$ is strictly increasing. Help him find such a permutation or determine that it is impossible.",
    "tutorial": "Let's assume that we've found a suitable permutation of all numbers, except all occurences of the number $1$. When can we insert the $1$'s so that the new arrangement of numbers is again good? We can see that the XOR of all numbers before any occurence of the number $1$ must be even, so there should an even number of odd numbers before it. Suppose that there are $x$ $1$'s in the input, and $y$ odd numbers greater than $1$. If $x > y + 1$, then in any arrangement there is going to be a pair of $1$'s such that there are no odd numbers between them, hence the condition above cannot hold for both of them simultaneously. On the other hand, if $x \\leq y + 1$, then it is possible to insert the $1$'s into any permutation of greater numbers. Indeed, we can place one instance of $1$ at the start, and then place remaining $1$'s immediately after greater odd numbers. Note that this argument works just as well if we consider numbers in the range $[2^k, 2^{k + 1})$ as \"$1$'s\", and numbers in $[2^{k + 1}, \\infty)$ as \"numbers greater than $1$\". Note further that it doesn't matter how exactly we insert the \"$1$'s\" since number of available gaps doesn't depend on that. Hence, we can go as follows: group the numbers by their leading bits. Make an empty list for the answer, and process the numbers in groups by decreasing of their leading bits. Suppose there are $x$ numbers with leading bit $k$, and $y$ greater numbers that have $1$ in the $k$-th bit. If $x > y + 1$, then there is no answer. Otherwise, insert the numbers from the current group as described above. The complexity of this solution is $O(n \\log A)$, where $A$ is the largest value among the numbers in the input.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "925",
    "index": "D",
    "title": "Aztec Catacombs",
    "statement": "Indiana Jones found ancient Aztec catacombs containing a golden idol. The catacombs consists of $n$ caves. Each pair of caves is connected with a two-way corridor that can be opened or closed. The entrance to the catacombs is in the cave $1$, the idol and the exit are in the cave $n$.\n\nWhen Indiana goes from a cave $x$ to a cave $y$ using an open corridor, all corridors connected to the cave $x$ change their state: all open corridors become closed, all closed corridors become open. Indiana wants to go from cave $1$ to cave $n$ going through as small number of corridors as possible. Help him find the optimal path, or determine that it is impossible to get out of catacombs.",
    "tutorial": "Let us formualate a problem in terms of graph theory and make some observation. Denote the start and the finish vertices as $s$ and $t$. Observation 1. If vertices $s$ and $t$ are connected with a simple path consisting of $k$ edges, then by the statement of the problem Indiana Johns may use it leading us to the answer of length $k$. Thus, the answer does not exceed $d$ where $d$ is the length of the shortest path between $s$ and $t$ if $s$ and $t$ are connected and $\\infty$ otherwise. Let us call path consisting only of the original edges of the graph trivial and the paths including originally non-existent edges non-trivial. Observation 2. The length of any non-trivial path is at least 4. Indeed, let $s = v_0 \\xrightarrow{e_1} v_2 \\xrightarrow{e_2} \\cdots \\xrightarrow{e_k} v_k = t$ be the valid path in which some of the edges $e_i$ is missing in the original graph. Notice that the edge $e_1$ may not be missing as by the moment we follow it, nothing was flipped yet, and $e_2$ also may not be missing as it requires $e_2$ to be same with $e_1$ which was just flipped. Also note that $e_3$ may not be the last edge in our path because otherwise it must be missing in the original graph (since the path is non-trivial), and we did not visit vertex $v_2$ yet as $v_2 \\neq v_1$ and $v_2 \\neq v_0 = 1$. Thus, $k \\geq 4$. Observation 3. If $d \\leq 4$, then the answer is $d$. It immediately follows from two previous observations: shortest trivial path has the length of $d$ and shortest non-trivial has the length of at least $4$. Observation 4. If $d \\geq 4$ and there exists a vertex $v_2$ at the distance of $2$ from $v_0 = s$, then there exists a non-trivial path of length $4$. Indeed, $v_0 \\rightarrow v_1 \\rightarrow v_2 \\rightarrow v_0 \\rightarrow t$ is such path where $v_1$ is a vertex through which the path of length $2$ between $v_0$ and $v_2$ passes. Finally, note that $v_2$ and $v_0$ are not initially connected (otherwise the distance between $v_0$ and $v_2$ would be 1), hence when we visit $v_2$, the edge $v_2 \\rightarrow v_0$ is present. Similarly, by the moment of second visit of vertex $v_0$ originally missing edge $v_0 \\rightarrow t$ appears. Observation 5. Any non-trivial path of length $4$ looks exactly as described in an observation 4, first two initially existent edges, then newly appeared edge leading to $s$ and finally newly appeared edge leading to $t$. It immediately follows from the explanation of the observation 2. Observation 6. If $d \\geq 4$ and there no vertex $v_2$ located at the distance $2$ from $s$, then $s$ is connected with all vertices in its connected component and this component does not contain $t$. Observation 7. If, under conditions of the previous observation, it we remove vertex $s$, then all the vertices initially adjacent to it will be distributed into several connected components. If all connected components are cliques, there are no valid paths. Indeed, after first transition we get into some clique and then we may only move inside it and it keeps shrinking until we get to an isolated vertex from which we can not go anywhere. Observation 8. If any of the connected components adjacent with $s$ is not a clique, then the shortest valid non-trivial path has a length of $5$. Indeed, consider a connected component $C$ initially connected with $s$ that is not a clique. It is not a clique, hence it contains a vertex $v_1$ of degree less than $|C| - 1$. This vertex is not connected with a whole component $C$, thus there are vertices $v_2, v_3 \\in C$ such that $v_3$ is not connected with $v_1$, while $v_1$ and $v_2$ are connected and $v_2$ and $v_3$ are also connected with an edge. It means that there is a non-trivial path $v_0 \\rightarrow v_1 \\rightarrow v_2 \\rightarrow v_3 \\rightarrow v_1 \\rightarrow t$. The observations above cover all possible cases in this problem and also yield a solution working in linear time in terms of a size of the original graph.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2600
  },
  {
    "contest_id": "925",
    "index": "E",
    "title": "May Holidays",
    "statement": "It's May in Flatland, and there are $m$ days in this month. Despite the fact that May Holidays are canceled long time ago, employees of some software company still have a habit of taking short or long vacations in May.\n\nOf course, not all managers of the company like this. There are $n$ employees in the company that form a tree-like structure of subordination: each employee has a unique integer id $i$ between $1$ and $n$, and each employee with id $i$ (except the head manager whose id is 1) has exactly one direct manager with id $p_i$. The structure of subordination is not cyclic, i.e. if we start moving from any employee to his direct manager, then we will eventually reach the head manager. We define that an employee $u$ is a subordinate of an employee $v$, if $v$ is a direct manager of $u$, or the direct manager of $u$ is a subordinate of $v$. Let $s_i$ be the number of subordinates the $i$-th employee has (for example, $s_1 = n - 1$, because all employees except himself are subordinates of the head manager).\n\nEach employee $i$ has a bearing limit of $t_i$, which is an integer between $0$ and $s_i$. It denotes the maximum number of the subordinates of the $i$-th employee being on vacation at the same moment that he can bear. If at some moment strictly more than $t_i$ subordinates of the $i$-th employee are on vacation, and the $i$-th employee himself is not on a vacation, he becomes displeased.\n\nIn each of the $m$ days of May exactly one event of the following two types happens: either one employee leaves on a vacation at the beginning of the day, or one employee returns from a vacation in the beginning of the day. You know the sequence of events in the following $m$ days. Your task is to compute for each of the $m$ days the number of displeased employees on that day.",
    "tutorial": "In terms of trees we have a rooted tree whose vertices may be activated and deactivated, and each vertex has a limit for the number of deactivated vertices among its descendants. We are required to switch the state of some vertex, and after each query we report the number of activated vertices unsatisfied vertices. Let the balance of a vertex be equal to the difference between its limit of deactivated descendants and the actual number of deactivated vertices among its descendants. In such terms we are interested in the number of activated vertices with the negative balance. Let's utilize the idea of sqrt-optimization. Consider a block of $k$ consecutive queries, let us answer all of them. Suppose this query affects the state of vertices $v_1, v_2, \\ldots, v_l$ ($l \\leq k$), let us call such vertices interesting. Then, during the current query block, the balance will change only for the vertices that have at least one interesting vertex in its subtree. Let's perform a classical trick of building the condensed tree containing the given interesting vertices. Namely, sort all the interesting vertices in order of their visit when doing DFS, and add all vertices of form $lca(v_i, v_{i+1})$ for all $1 \\leq i < l$ to the set of interesting vertices. After such procedure all vertices whose balance may change may be splitted into $O(k)$ vertical paths each of which ends in an interesting vertex. Now we are going to consider separately the interesting vertices and the interior vertices of all paths between interesting vertices. In each of the paths the balance of all vertices is changed simultaneously, thus we may sort all the vertices in each path by balance and then group all vertices having the same balance together. Introduce a pointer that initially stands at the first satisfied group (with non-negative balance). When the balance of all groups is changed by 1, instead of actually changing the value of balance we may just shift the pointer by at most one position to the left or to the right (artificially changing the origin) and accounting at most one group the pointer has passed in the answer. On each query we have to perform such an operation with every path and interesting vertex that is located above the queried vertex. Since each vertex and each path is processed in $O(1)$, processing a single query takes $O(k)$ time and processing all queries inside a block takes $O(k^2)$ time. It is possible to build all paths and groups in running time of a single DFS plus sort time (std::sort or counting sort) for grouping vertices of equal balance. This part of solution takes $O(n)$ per each query block or $O(n \\log n)$ depending on used sorting algorithm. If we use count sort, the resulting complexity will be $O(\\frac{m}{k} \\left(k^2 + n\\right))$, finally we can take $k = \\Theta(\\sqrt{n})$ and get $O(m \\sqrt{n})$ running time.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "925",
    "index": "F",
    "title": "Parametric Circulation",
    "statement": "Vova has recently learned what a circulaton in a graph is. Recall the definition: let $G = (V, E)$ be a directed graph. A circulation $f$ is such a collection of non-negative real numbers $f_e$ ($e \\in E$), that for each vertex $v \\in V$ the following conservation condition holds:\n\n$$\\sum\\limits_{e \\in \\delta^{-}(v)} f_e = \\sum\\limits_{e \\in \\delta^{+}(v)} f_e$$\n\nwhere $\\delta^{+}(v)$ is the set of edges that end in the vertex $v$, and $\\delta^{-}(v)$ is the set of edges that start in the vertex $v$. In other words, for each vertex the total incoming flow should be equal to the total outcoming flow.\n\nLet a $lr$-circulation be such a circulation $f$ that for each edge the condition $l_e \\leq f_e \\leq r_e$ holds, where $l_e$ and $r_e$ for each edge $e \\in E$ are two non-negative real numbers denoting the lower and upper bounds on the value of the circulation on this edge $e$.\n\nVova can't stop thinking about applications of a new topic. Right now he thinks about the following natural question: let the graph be fixed, and each value $l_e$ and $r_e$ be a linear function of a real variable $t$:\n\n$$l_e(t) = a_e t + b_e$$ $$r_e(t) = c_e t + d_e$$\n\nNote that $t$ is the \\textbf{same} for all edges.\n\nLet $t$ be chosen at random from uniform distribution on a segment $[0, 1]$. What is the probability of existence of $lr$-circulation in the graph?",
    "tutorial": "First, let's use the classical reduction of $lr$-circulation problem to the maximum flow problem. Consider a network $G' = (V \\cup \\{s, t\\}, E')$ where for each $e = uv \\in E$ there are three edges: $e_0 = uv$ with capacity $c_{e_0} = r_e - l_e$ $e_1 = sv$ with capacity $c_{e_1} = l_e$ $e_2 = ut$ with capacity $c_{e_2} = l_e$ Statement: it is possible to provide a bisection between $s-t$ flows of value $\\sum \\limits_{e \\in E} l_e$ in $G'$ and $lr$-circulations in $G$. Indeed, consider a flow $f'$ in $G'$, that saturates all edges going from $s$ (and all the edges leading into $t$ at the same time). Let $f_e = f'_{e_0} + l_e$. Notice that it is a correct circulation: for any vertex $v$ where the middle equation is immediately following from the conservation condition for any vertex from $V$ for a flow $f'$. On the other hand, the obtained circulation is indeed an $lr$-circulation because of how we got values of $f'_e$. By performing all the steps in the reverse direction, we may recover a maximum flow in $G'$ by any $lr$-circulation that finishes our proof. Now we are going to answer the following question: we have a parametric network $G'(t)$ in which all capacities linearly depend on $t$, we have to find the probability that $G'$ allows a flow that saturates all edges from the source under condition that $t$ is sampled from $U[0, 1]$. Let us show that the set of $t$ that allow existence of a sought flow is a segment. It follows from the fact that the value $maxflow(t)$ of a maximum flow in $G'(t)$ is concave: suppose $f'(t_1)$ is a an admissible flow in $G'(t_1)$ and $f'(t_2)$ is an admissible flow in $G'_{t_2}$. Then it is easy to see that $\\lambda f'(t_1) + (1 - \\lambda) f'(t_2)$ is an admissible flow in $G'\\left(\\lambda t_1 + (1 - \\lambda) t_2\\right)$ for any $\\lambda \\in [0, 1]$ (as all the constraints on variables $f'_{e}$ are linear inequalities), from which immediately follows that $maxflow(\\lambda t_1 + (1 - \\lambda) t_2) \\geq \\lambda maxflow(t_1) + (1 - \\lambda) maxflow(t_2)$. Denote $suml(t) = \\sum\\limits_{e \\in E}l(t)$. Let us notices that $gap(t) = suml(t) - maxflow(t) \\geq 0$ for any $t$ and we are interested in precisely those values of $t$, such that $gap(t) = 0$. Thus, the sought values of $t$ form a segment as the function $gap(t)$ is convex. The remaining part of the solution is very simple: find a minimum of a convexvalue $gap(t)$ over a segment $[0, 1]$. If it is non-zero, then the answer is 0. Otherwise, we can locate the boundaries of an answer segment using two binary searches and print the difference between them. While implementing such a solution, one may face several difficulties arising from the precision issues, so we will provide two observations that may help you deal with them. One may notice that $maxflow(t)$ is actually a piecewise linear function, all pieces of which have the integer slope. Actually, $maxflow(t) = mincut(t) = \\min\\limits_{\\text{cut }C} cost(C, t)$, and the cost of any fixed cut in $G'(t)$ is a linear function of $t$ with an integer slope. Thus, $maxflow(t)$ is a lower envelope of a family of linear functions with integer slopes. The similar fact holds for a function $gap(t)$ also. And we are interested in a horizontal segment in $gap(t)$ which may be found using the binary search over a sign of a derivative $gap'(t)$. Finally notice that calculating a derivative $gap'(t)$ may be done by finding a maximum flow and adding up all slopes of capacities of the edges defining a minimum cut restricting given maximum flow (since exactly this cut provides a linear constraint defining a segment of a function $gap(t)$, which a point $t$ belongs to). An alternative observation - consider only the points $t$ such that $t = \\frac{k}{10^7}$ where $k$ is integer. If we keep only such points on the sought segment, its length will decrease by no more than $2 \\cdot 10^{-7}$ which is allowed by a required answer precision. Finally, we can multiply all $b_e$ and $d_e$ by $10^7$ and consider $t$ to be an integer between $0$ and $10^7$ which allows you to implement a solution that only uses integer data types. We get a solution with a running time of $O(maxflow \\cdot \\log prec^{-1})$ where $prec$ is a required precision equal to $10^{-6}$ under conditions of a given problem and $maxflow$ is a running time of your favourite maximum flow algorithm. Practically you could use Dinic algorithm or Edmonds-Karp algorithm with capacity scaling.",
    "tags": [
      "binary search",
      "flows"
    ],
    "rating": 3100
  },
  {
    "contest_id": "928",
    "index": "A",
    "title": "Login Verification",
    "statement": "When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.\n\nLogin is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins $s$ and $t$ are considered similar if we can transform $s$ to $t$ via a sequence of operations of the following types:\n\n- transform lowercase letters to uppercase and vice versa;\n- change letter «O» (uppercase latin letter) to digit «0» and vice versa;\n- change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other.\n\nFor example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.\n\nYou're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.",
    "tutorial": "At first let's format all existing logins. For each login we will do the following: change all uppercase letters on lowercase letters; change all letters o on the digit 0; change all letters i and l on the digit 1. If new login is equal to some of the formatted login, the user can not register new login. In the other case, he will be able to do this.",
    "tags": [
      "*special",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "928",
    "index": "B",
    "title": "Chat",
    "statement": "There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.\n\nMore formal, your message history is a sequence of messages ordered by time sent numbered from $1$ to $n$ where $n$ is the total number of messages in the chat.\n\nEach message might contain a link to an earlier message which it is a reply to. When opening a message $x$ or getting a link to it, the dialogue is shown in such a way that $k$ previous messages, message $x$ and $k$ next messages are visible (with respect to message $x$). In case there are less than $k$ messages somewhere, they are yet all shown.\n\nDigging deep into your message history, you always read all visible messages and then go by the link in the current message $x$ (if there is one) and continue reading in the same manner.\n\nDetermine the number of messages you'll read if your start from message number $t$ for all $t$ from $1$ to $n$. Calculate these numbers independently. If you start with message $x$, the initial configuration is $x$ itself, $k$ previous and $k$ next messages. Messages read multiple times are considered as one.",
    "tutorial": "Let's use the dynamic. We will calculate the answer for the messages in the order of increasing their numbers. Let the current message has number $x$, then the answer was calculated for each $y$ from $1$ to $(x - 1)$ and equals to $cnt_{y}$. If there is no a link in the message $y$ then the answer for this message - is a length of the segment $[y - k, y + k]$ (it is necessary not to forget that the left boundary of the segment should be positive, and the right boundary should not exceed $n$). In the other case, the message $y$ contains the link to the message $z$. We know that $z < y$, so the $cnt_{z}$ has been already calculated. All messages which were counted for message $z$ should be counted in the answer for message $y$. Also new messages should be added - it is messages from the segment $[y - k, y + k]$ which do not included in the segment $[z - k, y + k]$. Also we remember that the left boundary of the segment should be positive, and the right boundary should not exceed $n$. After we considered all messages - simply print the array $cnt$.",
    "tags": [
      "*special",
      "dp"
    ],
    "rating": 1400
  },
  {
    "contest_id": "930",
    "index": "A",
    "title": "Peculiar apple-tree",
    "statement": "In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are $n$ inflorescences, numbered from $1$ to $n$. Inflorescence number $1$ is situated near base of tree and any other inflorescence with number $i$ ($i > 1$) is situated at the top of branch, which bottom is $p_{i}$-th inflorescence and $p_{i} < i$.\n\nOnce tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in $a$-th inflorescence gets to $p_{a}$-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they \\textbf{annihilate}. This happens with each pair of apples, e.g. if there are $5$ apples in same inflorescence in same time, only one will not be annihilated and if there are $8$ apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.\n\nHelp Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.",
    "tutorial": "Firstly, let's formalize problem: we have tree with root in first inflorescence. Let's examine apples that can roll down to the base of tree in $t$-th moment of time. It is obvious this are apples initially situated in nodes at $t$ distance from root. Key idea of solution is that we can suppose that apples in nonroot nodes don't annihilate but roll down to the very root and annihilate in it. This assumption is correct because number of apples in root at the $t$-th moment depends only on parity of apples that got there at that moment. Thus let's calculate $cnt_{t}$ - number of apples that will appear in root in root in $t$-th moment of time for each $t$. This can be performed by BFS or DFS. Answer for this problem is sum of all $cnt_{t} mod 2$ ($a mod b$ means calculating remainder $a$ modulo $b$) for each $t$ from $0$ up to $d$, where $d$ is maximal distance from root to node of tree.",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "930",
    "index": "B",
    "title": "Game with String",
    "statement": "Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string $s$, consisting of small English letters, and uniformly at random chooses an integer $k$ from a segment $[0, len(s) - 1]$. He tells Vasya this string $s$, and then shifts it $k$ letters to the left, i. e. creates a new string $t = s_{k + 1}s_{k + 2}... s_{n}s_{1}s_{2}... s_{k}$. Vasya does not know the integer $k$ nor the string $t$, but he wants to guess the integer $k$. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.\n\nVasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability.\n\nNote that Vasya wants to know the value of $k$ uniquely, it means, that if there are at least two cyclic shifts of $s$ that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.",
    "tutorial": "Idea. Let's consider all possible $c_{1}$ that will be first in $t$. Then, let's consider all possible numbers of second letter that Vasya will ask about - this will be $d$. If pair of letters ($c_{1}$, $c_{2}$) occurs only once at $d$ distance, than if $c_{2}$ opens second time, Vasya will be able to determine shift. Solution. Let's loop through all letters at $d$ distance from all $c_{1}$ letters and for each symbol $c_{2}$ we will calculate number of such letters. This can be done in $O(cnt(c_{1}))$, where $cnt(c_{1})$ is number of letters $c_{1}$ in initial string. Now, if we fix such $d$ after opening $c_{1}$, that maximizes number of unique pairs(we will name it $p$) ($c_{1}$, $c_{2}$) at $d$ distance, this will be optimal $d$, and conditional probability of victory in situation of fixed $c_{1}$ equals $p / cnt(c_{1})$. Now we only need to sum up conditional probabilities for different $c_{1}$. Probability of $c_{1}$ equals $cnt(c_{1}) / n$, thus answer is $\\sum{\\frac{p}{c n t(c_{1})}}\\cdot{\\frac{c n t(c_{1})}{n}}=\\sum_{n}$.",
    "tags": [
      "implementation",
      "probabilities",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "930",
    "index": "C",
    "title": "Teodor is not a liar!",
    "statement": "Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge $[1;m]$ segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha.\n\nSasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point $x_{i}$, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions.\n\nBoth boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice.",
    "tutorial": "Idea. The main idea is that set of point $x_{i}$ is bad(meaning that Sasha can't be sure, that Teodor hasn't lied, relying only on this information) $\\iff c n t(x_{i})$ satisfies the following property: $\\begin{array}{c}{{\\exists i:1\\ \\le\\ i\\le n\\circ n t(x_{1})\\ \\le\\ c n t(x_{2})\\ \\le\\ \\cdot\\cdot\\cdot\\ \\le\\ c n t(x_{i})\\ \\ge\\ c n t(x_{i+1})\\ \\ge\\ \\cdot\\cdot\\cdot}}\\\\ {{c n t(x_{i+2})\\ \\ge\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\cdot\\quad c n t(x_{n})}}\\end{array}\\$. Solution. Firstly let's calculate $cnt(x_{i})$ for each integer point in $[1;m]$. One way to do this is scanning line, which asymptotics is $O(m + n)$. Other approach uses segment tree supporting segment addition queries. In this case asymptotics is $O(n \\cdot log(m))$ . Now we only need to find longest sequence satisfying this property. Let's consider all possible $x_{i}$ in previous inequation(element that has peak $cnt(x_{i})$). Now the answer is length of longest nondecreasing sequence ending in $x_{i} +$ length of longest nonincreasing sequence, starting in $x_{i} - 1$. Both lengths can be found in $O(1)$ if one precalculates this lengths for each $1  \\le  i  \\le  m$, using dynamic programming. Note that you should use $O(m \\cdot log(m))$ algorithm for calculating this dp, not $O(m^{2})$, otherwise you will end up with TL verdict. Total asymptotics of this solution is $O(m \\cdot log(m))$ for solution using scanning line or $O((n + m) \\cdot log(m))$ for solution using segment tree.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "930",
    "index": "D",
    "title": "Game with Tokens",
    "statement": "Consider the following game for two players. There is one white token and some number of black tokens. Each token is placed on a plane in a point with integer coordinates $x$ and $y$.\n\nThe players take turn making moves, white starts. On each turn, a player moves \\textbf{all} tokens of their color by $1$ to up, down, left or right. Black player can choose directions for each token independently.\n\nAfter a turn of the white player the white token can not be in a point where a black token is located. There are no other constraints on locations of the tokens: positions of black tokens can coincide, after a turn of the black player and initially the white token can be in the same point with some black point. If at some moment the white player can't make a move, he loses. If the white player makes $10^{100500}$ moves, he wins.\n\nYou are to solve the following problem. You are given initial positions of all black tokens. It is guaranteed that initially all these positions are distinct. In how many places can the white token be located initially so that if both players play optimally, the black player wins?",
    "tutorial": "Note that if black and white chip are placed in the beginning in points ${x, y}$ with the same parity of $x + y$ then black chip can't be on the manhattan distance $1$ from white chip before white's move. So black chip can't block white chip and can't somehow affect the game. We can solve the problem independently for black chips with odd $x + y$, white chip with even $x + y$ and for black chips with even $x + y$, white chip with odd $x + y$. Note that we can solve the problem for black chips with even $x + y$ if we move all of them on $1$ upward and then solve the problem for odd $x + y$. Let's now consider only black chips with odd $x + y$. Look at the image. If black chip is placed in black point then it can stop white chip placed in red, blue, yellow, green points if it will move up, down, left, right, respectively (i.e. white point can't make infinite number of move in these directions whatever moves it will make). Note that one black chip can stop white chip only in one or zero directions. If there are four black chips that can stop white chip in different directions then black will win. Else white chip can move in some direction infinitely and white will win. So, every black chip generates four angles of different types. If point ${x, y}$ is contained in intersection of four angles of different types and $x + y$ is even then we should count this point in answer. Let's substitute every point ${x, y}$ to point ${x + y, x - y}$. There are still four types of angles but now every coordinate of white chip must be even number. In particular, the first image will look like this: Let's leave only points with even coordinates and divide every coordinate by two. Still every black chip generates four angles, white chip must be in intersection of four angles of different types but now there are no restrictions about parity of anything. How to count points in intersection of four angles of different types effectively? Find for each type of angles and for each $x$-coordinate half-interval of $y$-coordinates such that every point in this half-interval will be in some angle of current type. If we can find these half-intervals then we can find for every $x$-coordinate length of intersections of four half-intervals and answer will be equal to sum of these lengths. Let's consider angles of only one type because for other types we can do something symmetric. Let's these angles will have sides directed upward and rightward. Then for each x-coordinate half-interval is $[L_{x},  \\infty )$ where $L_{x}$ is minimal y-coordinate of vertices of angles which aren't placed to the right from $x$. So we can sort all vertices by $x$ and then write some easy scanline.",
    "tags": [
      "data structures",
      "games",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "930",
    "index": "E",
    "title": "Coins Exhibition",
    "statement": "Arkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from $1$ to $k$, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up.\n\nArkady and Kirill made some photos of the coins, each photo contained a segment of neighboring coins. Akrady is interested in obverses, so on each photo made by him there is at least one coin with obverse side up. On the contrary, Kirill is interested in reverses, so on each photo made by him there is at least one coin with its reverse side up.\n\nThe photos are lost now, but Arkady and Kirill still remember the bounds of the segments of coins each photo contained. Given this information, compute the remainder of division by $10^{9} + 7$ of the number of ways to choose the upper side of each coin in such a way, that on each Arkady's photo there is at least one coin with obverse side up, and on each Kirill's photo there is at least one coin with reverse side up.",
    "tutorial": "Denote obverse-up coin as $0$ and reverse-up coin as $1$. Then we are to compute the number of binary strings of length $k$ such that $n$ of the given segments have atleast one $0$ and other $m$ ones - atleast one $1$. Let $dp[i][l_{0}][l_{1}]$ be the number of binary strings of length $i$ such that the last zero is at position $l_{0}$, the last one is at $l_{1}$ and all restrictions are satisfied for all segments with right borders not exceeding $i$. The transitions then are straighforward: check all possible values for position $i + 1$ and relax $l_{0}$ and $l_{1}$ accordingly. Let the new values be $l_{0}'$ and $l_{1}'$. Now consider all segments ending at $i + 1$. If there are such $[l, r]$ among them demanding zero while $l > l_{0}'$ or demanding one while $l > l_{1}'$, this continuation doesn't suit. Otherwise add $dp[i][l_{0}][l_{1}]$ to $dp[i + 1][l_{0}'][l_{1}']$. This works in $O(k^{3} + n + m)$ if we precompute all segments ending in $r$ for all $r$. Anyway, this is too slow. The first thing to enhance is to notice that either $l_{0} = i$ or $l_{1} = i$. Then we have to deal with $dp_{0}[i][l_{1}]$ (implying $l_{0} = i$) and $dp_{1}[i][l_{0}]$ (implying $l_{1} = i$). The transitions are the same, and the complexity becomes $O(k^{2} + n + m)$. Still too slow :( The further improvement is that all positions with no segments endings can be treated similarly since the transitions are equal. At the same time it doesn't matter whether the last zero is at $l_{0}$ or $l_{0} + 1$ if there are no segments beginning at $l_{0} + 1$. Same applies to $l_{1}$. Let's compress coordinates then, i.e. find all $x_{i}$ such that $x_{i}$ and $x_{i} + 1$ are covered by different sets of segments. Now it's time to slightly change the dp definition: let $dp_{0}[i][l_{1}]$be the number of binary strings of length $x_{i}$ such that the last digit is $0$, the last $1$ is somewhere between $x_{l1 - 1} + 1$ and $x_{l1}$ and all restrictions are satisfied for all segments with endings not exceeding $x_{i}$. $dp_{1}[i][l_{0}]$ is denoted in a similar fashion. Consider the possible transitions. Without loss of generality we'll account for transitions from $dp_{0}[i][l_{1}]$ to some $dp_{?}[i + 1][?]$. The goal is to somehow append a binary string of length $(x_{i + 1} - x_{i})$ to the existing one. There are three major cases: All additional digits are $0$, then we jump to $dp_{0}[i + 1][l_{1}]$ with coefficient $1$ (there's only one way to construct a string of zeros). All additional digits are $1$, then we jump to $dp_{1}[i + 1][i]$ with coefficient $1$. Note that the last zero remains at $x_{i}$. There are some $0$ and some $1$. Then the jump is to $dp_{0}[i + 1][i + 1]$ and $dp_{1}[i + 1][i + 1]$ with coefficients equal to $2^{xi + 1 - xi - 1} - 1$ since only the last digit if fixed. This is possible iff $x_{i + 1} - x_{i} > 1$. Moreover, we have to consider all segments ending at $x_{i + 1}$ and discard those not satisfying the restrictions. This works in $O((n+m)^{2}\\cdot\\log\\left(k\\right))$ (extra logarithm is for fast powers). There's only one step left to a full solution. Note that in the dp above you can separate digit-adding from constraint-accounting transitions and treat them one after another. That means that you can first apply all transitions from $d p_{*}[i][*]$ to $d p_{*}[i+1][*]$ disregarding segments endings at $x_{i + 1}$ and then null $dp_{0}[i + 1][l_{1}]$, where $l_{1} < l$, where $[l, x_{i}]$ is an arbitrary segment applying $1$-constraint and null $dp_{1}[i + 1][l_{0}]$, where $l_{0} < l$, where $[l, x_{i}]$ is an arbitrary segment applying $0$-constraint. Futhermore note that transitions with coeffitients not equal to $1$ are applied only to $d p_{*}[i+1][i]$ and $d p_{*}[i+1][i+1]$ while values of $d p_{*}[i+1][j]$ where $j < i$ are either $d p_{*}[i|[j]$ or $0$. That means we can store two arrays $dp_{0}[l_{1}]$ and $dp_{1}[l_{0}]$, implying $i$ being equal to the current value. Now when jumping from $i$ to $i + 1$ we have to relax $d p_{*}[i]$ and $d p_{*}[i+1]$, and null some prefix of $dp_{0}$ and some prefix of $dp_{1}$ depending on beginnins of segments ending at $x_{i}$. The new values of $d p_{*}[i]$ and $d p_{*}[i+1]$ are easy to obtain via sum of elements in this arrays and $x_{i + 1} - x_{i}$. With a properly chosen data structure the complexity becomes ${\\cal O}((n+m)\\log{(n+m)}\\log{(k)})$ with $O(n + m)$ memory. This is now enough to get ac. There's an alternative approach: you can just keep track of the first non-nulled element since it can only increase. This also helps maintain the current sum of values without using specific data structures. This works in $O((n+m)\\cdot(\\log\\left(n+m)+\\log\\left(k\\right)))$ (including sort).",
    "tags": [
      "data structures",
      "dp",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "931",
    "index": "A",
    "title": "Friends Meeting",
    "statement": "Two friends are on the coordinate axis $Ox$ in points with integer coordinates. One of them is in the point $x_{1} = a$, another one is in the point $x_{2} = b$.\n\nEach of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by $1$, the second move increases the tiredness by $2$, the third — by $3$ and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to $1 + 2 + 3 = 6$.\n\nThe friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.",
    "tutorial": "At first understand the fact that friend should make their moves one be one and the friend who initially was left should move to the right and other friend should move to the left. Let $len = |a - b|$. Then the first friend will make $cntA = len / 2$ moves, and the second friend - $cntB = len - len / 2$ moves. So the answer is the sum of two arithmetic progressions $cntA \\cdot (cntA + 1) / 2$ and $cntB \\cdot (cntB + 1) / 2$. The given constrains allowed to calculate this sums in linear time - simply iterate from $1$ to $cntA$ for the first sum and from $1$ to $cntB$ to the second.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "931",
    "index": "B",
    "title": "World Cup",
    "statement": "The last stage of Football World Cup is played using the play-off system.\n\nThere are $n$ teams left in this stage, they are enumerated from $1$ to $n$. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over.\n\nArkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids $a$ and $b$ can meet.",
    "tutorial": "Initially, we need to understand the following fact. Since the number of teams in each round is even, $n$ should be a power of two. We will solve the problem for the 0-indexing commands, so we decrease the given $a$ and $b$ on one. For each round we will determine the number of the match, in which the teams with initial numbers $a$ and $b$ will play. The command $a$ will play in the match number $a / 2$, and the command $b$ will play in the match number $b / 2$. If $a / 2 = b / 2$, then these teams will play in the same match, and we need to print the number of the current round as an answer. If the number of remaining teams equals to two - this will be the final match of the tournament. If the match numbers not equal we consider the next round. In this case, the number of command $a$ becomes $a / 2$ and the number of number $b$ becomes $b / 2$. The number of teams which will go to the next round is $n = n / 2$. This process is always finite, because sooner or later will remain only $2$ teams and in this round will be only one match - the final match of the tournament.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "931",
    "index": "C",
    "title": "Laboratory Work",
    "statement": "Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value $n$ times, and then compute the average value to lower the error.\n\nKirill has already made his measurements, and has got the following integer values: $x_{1}$, $x_{2}$, ..., $x_{n}$. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is \\textbf{at most $2$}.\n\nAnya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values $y_{1}$, $y_{2}$, ..., $y_{n}$ in her work, that the following conditions are met:\n\n- the average value of $x_{1}, x_{2}, ..., x_{n}$ is equal to the average value of $y_{1}, y_{2}, ..., y_{n}$;\n- all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values;\n- the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of \\textbf{strike off} values in Anya's work.\n\nHelp Anya to write such a set of measurements that the conditions above are met.",
    "tutorial": "The average value of Anya measurements should be equal to the average value of Kirill's measurements, so the sum of all Anya measurements should be equal to the sum of all Kirill dimensions. Let the minimum number in the Kirill's measurements is $min$ and the maximum - $max$. Then, if $(max - min)$ is less than or equal to one, Anya will not be able to write down any measurements that Kirill do not have, so all her measurements will coincide with his measurements. There remains the case when $(max - min) = 2$. Each Anya measurement should be at least $min$ and not more than $max$. We need to brute how many of minimal measurements equal to $min$ Anya will write down from $0$ to $n$. Then the numbers of measurements equal to $(min + 1)$ and $max$ can be uniquely determined. Let $sum$ is the necessary sum of all measurements, which is equal to the sum of all Kirill measurements, and $cntMin$ is the current number of minimal measurements that Anya will write down. Then Anya needs to write remaining number of measurements such that their sum equals to $leftSum = sum - cntMin cdotmin$. The minimum sum that Anya can get with the remaining measurements is $minSum = (n - cntMin) cdot(min + 1)$, and the maximum is $maxSum = (n - cntMin) cdotmax$. Then, if $leftSum < minSum$ or $leftSum > maxSum$, Anya can not take $cntMin$ minimum values and get the desired sum. Otherwise, Anya should write the measurements equal to $(min + 1)$ in the amount of $(leftSum - minSum)$, and all remaining measurements will be equal to the $max$. After that, we need to update the answer with the number of coinciding values of $min$, $(min + 1)$ and $max$ in Anya's and Kirill's measurements. After we updated the answer, move to the next value $cntMin$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "932",
    "index": "A",
    "title": "Palindromic Supersequence",
    "statement": "You are given a string $A$. Find a string $B$, where $B$ is a palindrome and $A$ is a subsequence of $B$.\n\nA subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, \"cotst\" is a subsequence of \"contest\".\n\nA palindrome is a string that reads the same forward or backward.\n\nThe length of string $B$ should be at most $10^{4}$. It is guaranteed that there always exists such string.\n\nYou do not need to find the shortest answer, the only restriction is that the length of string $B$ should not exceed $10^{4}$.",
    "tutorial": "Let $reverse(s)$ be the reverse of string $s$. Now, $s + reverse(s)$ will always have $s$ as a subsequence (as first half) and it is a palindrome with size less than $10^{4}$. So, it may be one of the possible solutions.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n    string s;\n    cin>>s;\n    cout<<s;\n    reverse(s.begin(),s.end());\n    cout<<s;\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "932",
    "index": "B",
    "title": "Recursive Queries",
    "statement": "Let us define two functions $f$ and $g$ on positive integer numbers.\n\n\\begin{center}\n$f(n)=\\mathrm{product~of~non}{\\mathrm{-zero~digits~of~}}n$$g(n)={\\binom{n}{g(f(n))}}\\quad{\\begin{array}{l l}{{\\mathrm{if~}}n<10}\\\\ {{\\mathrm{otherwise}}}\\end{array}}$\n\\end{center}\n\nYou need to process $Q$ queries. In each query, you will be given three integers $l$, $r$ and $k$. You need to print the number of integers $x$ between $l$ and $r$ inclusive, such that $g(x) = k$.",
    "tutorial": "If we can show that for all integers $n  \\ge  10$, we have $n > f(n)$ then we can use bottom up dp for calculating $g(n)$ for all the integers $1  \\le  n  \\le  10^{6}$ in $O(n)$. And as $1  \\le  g(n)  \\le  9$, using partial sum arrays for each possible value of $g(n)$, we can answer the queries in $O(1)$. For the proof that for all integers $n  \\ge  10$, we have $n > f(n)$, let us assume an integer $n  \\ge  10$ of length $k  \\ge  2$ which can be represented as $n_{k}n_{k - 1}... n_{2}n_{1}$ where $n_{i}  \\neq  0$ for all $1  \\le  i  \\le  k$. We have assumed that $n_{i}  \\neq  0$, as even if any of the $n_{i} = 0$, it will neither affect $n$ nor $f(n)$ in our proof given below. Given, $f(n) = n_{k}  \\times  n_{k - 1}  \\times  ...  \\times  n_{2}  \\times  n_{1}$ and $n = n_{1} + 10  \\times  n_{2} + ... + 10^{k - 1}  \\times  n_{k}$. As $f(n)  \\le  9^{k - 1}  \\times  n_{k}$, $9^{k - 1}  \\times  n_{k} < 10^{k - 1}  \\times  n_{k}$ and $10^{k - 1}  \\times  n_{k}  \\le  n$. So, $f(n) < n$ and hence we can use bottom up dp for calculating $g(n)$ for all values of $n$. Also, we can observe that the integer $n$ reduces pretty much quickly to a single digit while calculating $g(n)$, so we can directly calculate $g(n)$ for all $1  \\le  n  \\le  10^{6}$ without using dp as well.",
    "code": "#include \"bits/stdc++.h\"\n\n#ifdef PRINTERS\n#include \"printers.hpp\"\nusing namespace printers;\n#define tr(a)\t\tcerr<<#a<<\" : \"<<a<<endl\n#else\n#define tr(a)    \n#endif\n\n#define ll          long long\n#define pb          push_back\n#define mp          make_pair\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (int)x.size()\n#define hell        1000000007\n#define endl        '\\n'\n#define rep(i,a,b)\tfor(int i=a;i<b;i++)\nusing namespace std;\n\nint x[10][1000005];\n\nint f(int x){\n\tif(x<10)return x;\n\tint prod=1;\n\twhile(x){\n\t\tif(x%10)prod*=(x%10);\n\t\tx/=10;\n\t}\n\treturn f(prod);\n}\n\nvoid solve(){\n\tfor(int i=1;i<=1000000;i++){\n\t\tx[f(i)][i]++;\n\t}\n\tfor(int i=1;i<10;i++){\n\t\tfor(int j=1;j<=1000000;j++){\n\t\t\tx[i][j]+=x[i][j-1];\n\t\t}\n\t}\n\tint Q;\n\tcin>>Q;\n\twhile(Q--){\n\t\tint l,r,k;\n\t\tcin>>l>>r>>k;\n\t\tcout<<x[k][r]-x[k][l-1]<<endl;\n\t}\n}\n\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\tint t=1;\n//\tcin>>t;\n\twhile(t--){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar"
    ],
    "rating": 1300
  },
  {
    "contest_id": "932",
    "index": "C",
    "title": "Permutation Cycle",
    "statement": "For a permutation $P[1... N]$ of integers from $1$ to $N$, function $f$ is defined as follows:\n\n\\begin{center}\n$f(i,j)={\\binom{P[i]}{f(P[i],j-1)}}\\quad\\quad{\\mathrm{if~}}j=1$\n\\end{center}\n\nLet $g(i)$ be the minimum positive integer $j$ such that $f(i, j) = i$. We can show such $j$ always exists.\n\nFor given $N, A, B$, find a permutation $P$ of integers from $1$ to $N$ such that for $1 ≤ i ≤ N$, $g(i)$ equals either $A$ or $B$.",
    "tutorial": "For $f(i, j) = i$ and $g(i) = k$, there must exist a cycle of length $k$ beginning from index $i$ and ending at the same index $i$ of permutation $P$. While generating a permutation $P$, we are constrained to generate cycles of length either $A$ or $B$ as $g(i)$ for all $1  \\le  i  \\le  N$ must be equal to either of them. Let us try to generate a cycle of length $k$ for indices $i$ till $i + k - 1$ using only the integers $i$ till $i + k - 1$, each once. If $P[i] = i + k - 1$ and $P[j] = j - 1$ for all $i < j  \\le  i + k - 1$, we in turn get a cycle of length $k$ for each of the indices $i$ till $i + k - 1$, that is $f(j, k) = j$ for all $i  \\le  j  \\le  i + k - 1$. So, if there exists a solution $(x, y)$ where $x  \\ge  0$ and $y  \\ge  0$, for $Ax + By = N$, we can in turn generate a permutation $P$ satisfying our needs. Otherwise, no such permutation is possible. So, now for any one of the solution $(x, y)$, generate $x$ cycles of length $A$, beginning from indices $1$, $A + 1$, $A * 2 + 1$ ... $A * (x - 1) + 1$ and then beginning from indices $A * x + 1$, $A * x + 1 + B$, ... $A * x + 1 + B * (y - 1)$, generate $y$ cycles of length $B$.",
    "code": "#include \"bits/stdc++.h\"\n\n#define ll          long long\n#define pb          push_back\n#define mp          make_pair\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (int)x.size()\n#define hell        1000000007\n#define endl        '\\n'\n#define rep(i,a,b)\tfor(int i=a;i<b;i++)\nusing namespace std;\n\nvoid solve(){\n\tint n,a,b;\n\tcin>>n>>a>>b;\n\tvector<int>v(n);\n\tiota(all(v),1);\n\tint i=0;\n\twhile(i<n){\n\t\tif((n-i)%b==0){\n\t\t\tif(b>1)rotate(v.begin()+i,v.begin()+i+1,v.begin()+i+b);\n\t\t\ti+=b;\n\t\t}\n\t\telse{\n\t\t\tif(i+a>n){\n\t\t\t\tcout<<-1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(a>1)rotate(v.begin()+i,v.begin()+i+1,v.begin()+i+a);\n\t\t\ti+=a;\n\t\t}\n\t}\n\tfor(auto j:v)cout<<j<<\" \";\n}\n\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\tint t=1;\n//\tcin>>t;\n\twhile(t--){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "932",
    "index": "D",
    "title": "Tree",
    "statement": "You are given a node of the tree with index $1$ and with weight $0$. Let $cnt$ be the number of nodes in the tree at any instant (initially, $cnt$ is set to $1$). Support $Q$ queries of following two types:\n\n- $\\mathrm{i}\\ \\mathrm{R}\\ \\mathrm{W}:$ Add a new node (index $cnt + 1$) with weight $W$ and add edge between node $R$ and this node.\n- $2\\ \\mathrm{R}\\ \\mathrm{X}:$ Output the maximum length of sequence of nodes which\n\n- starts with $R$.\n- Every node in the sequence is an ancestor of its predecessor.\n- Sum of weight of nodes in sequence does not exceed $X$.\n- For some nodes $i, j$ that are consecutive in the sequence if $i$ is an ancestor of $j$ then $w[i] ≥ w[j]$ and there should not exist a node $k$ on simple path from $i$ to $j$ such that $w[k] ≥ w[j]$\n\nThe tree is rooted at node $1$ at any instant.\n\n\\textbf{Note that the queries are given in a modified way.}",
    "tutorial": "The main idea is that we will use binary lifting. Twice. Let's consider the following $O(Q  \\times  N)$ algorithm - for every vertex $u$ (when inserted) find the closest vertex $v$ above it with $w[v]  \\ge  w[u]$. Lets have an array $nxt[]$, such that $nxt[u] = v$. Then the query will be done by simply jumping to the vertex in $nxt[]$, until our sum becomes larger than $X$. Obviously this is $O(Q  \\times  Depth) = O(Q  \\times  N)$. To speed it up, we will have $2$ binary liftings. The first one will be for finding the $nxt[]$ and the second one will be for answering the queries. For the first one we will store the $2^{i}$-th parent and the maximum weight on the path and for the second one, we will store the $2^{i}$-th $nxt[]$ vertex and the sum of the weights on the path. Well that's all and in such a way you can achieve $O(Q\\log N)$. Thanks to radoslav11 for nice and short editorial in comments.",
    "code": "#include \"bits/stdc++.h\"\n\n#ifdef PRINTERS\n#include \"printers.hpp\"\nusing namespace printers;\n#define tr(a)\t\tcerr<<#a<<\" : \"<<a<<endl\n#else\n#define tr(a)    \n#endif\n#define ll          long long\n#define pb          push_back\n#define mp          make_pair\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (int)x.size()\n#define hell        1000000007\n#define endl        '\\n'\n#define rep(i,a,b)\tfor(int i=a;i<b;i++)\nusing namespace std;\n\nint par[20][400000];\nll par_sum[20][400000];\nint w[400000];\n\nvoid solve(){\n\tint Q;\n\tcin>>Q;\n\tw[0]=INT_MAX;\n\tint last=0;\n\tint cur=1;\n\tfor(int i=0;i<20;i++)par_sum[i][1]=1e16;\n\twhile(Q--){\n\t\tint ch;\n\t\tcin>>ch;\n\t\tif(ch==1){\n\t\t\tll p,q;\n\t\t\tcin>>p>>q;\n\t\t\tp^=last;\n\t\t\tq^=last;\n\t\t\tcur++;\n\t\t\tw[cur]=q;\n\t\t\tif(w[p]>=w[cur]){\n\t\t\t\tpar[0][cur]=p;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tint from=p;\n\t\t\t\tfor(int i=19;i>=0;i--){\n\t\t\t\t\tif(w[par[i][from]]<w[cur])\n\t\t\t\t\t\tfrom=par[i][from];\n\t\t\t\t}\n\t\t\t\tpar[0][cur]=par[0][from];\n\t\t\t}\n\t\t\tpar_sum[0][cur]=(par[0][cur]==0?1e16:w[par[0][cur]]);\n\t\t\tfor(int i=1;i<20;i++){\n\t\t\t\tpar[i][cur]=par[i-1][par[i-1][cur]];\n\t\t\t\tpar_sum[i][cur]=(par[i][cur]==0?1e16:par_sum[i-1][cur]+par_sum[i-1][par[i-1][cur]]);\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tll p,q;\n\t\t\tcin>>p>>q;\n\t\t\tp^=last;\n\t\t\tq^=last;\n\t\t\tif(w[p]>q){\n\t\t\t\tcout<<0<<endl;\n\t\t\t\tlast=0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tq-=w[p];\n\t\t\t\tint ans=1;\n\t\t\t\tfor(int i=19;i>=0;i--){\n\t\t\t\t\tif(par_sum[i][p]<=q){\n\t\t\t\t\t\tans+=(1<<i);\n\t\t\t\t\t\tq-=par_sum[i][p];\n\t\t\t\t\t\tp=par[i][p];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcout<<ans<<endl;\n\t\t\t\tlast=ans;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\tint t=1;\n//\tcin>>t;\n\twhile(t--){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "932",
    "index": "E",
    "title": "Team Work",
    "statement": "You have a team of $N$ people. For a particular task, you can pick any non-empty subset of people. The cost of having $x$ people for the task is $x^{k}$.\n\nOutput the sum of costs over all non-empty subsets of people.",
    "tutorial": "The required sum can be expressed as $\\sum_{r=1}^{n}{\\binom{n}{r}}r^{k}$. $f(x)=(1+x)^{n}=\\sum_{r=0}^{n}{\\binom{n}{r}}x^{r}$ Differentiating the above equation and multiplying by $x$, we get $n x(1+x)^{n-1}=\\sum_{r=1}^{n}{\\binom{n}{r}}r x^{r}$ Differentiating and multiplying by $x$ again, we get $x{\\frac{\\mathrm{d}}{\\mathrm{d}x}}\\left(n x(1+x)^{n-1}\\right)=\\sum_{r=1}^{n}{\\binom{n}{r}}r^{2}x$ Repeating the process (multiplying by $x$ and differentiating) $k$ times, and replacing $x = 1$, we get the desired sum. This can be done using dynamic programming. Consider $dp[a][b][c]$ to be the value of the function $x^{b}(1 + x)^{c}$ after performing the differentiation and multiplying by $x$, $a$ times at $x = 1$. So, our final answer will be $dp[k][0][n]$. $x^{b}(1+x)^{c}$ after 1 operation, the above function becomes: $x(b x^{b-1}(1+x)^{c}+c x^{b}(1+x)^{c-1})$ or $b x^{b}(1+x)^{c}+c x^{b+1}(1+x)^{c-1})$ So, $dp[a][b][c] = b * dp[a - 1][b][c] + c * dp[a - 1][b + 1][c - 1]$ Take care of special cases when $a = 0$ or $b = 0$. The above $dp$ seems to be $3$ dimensional but actually has $O(k^{2})$ states since $b + c$ is constant reducing one dimension.",
    "code": "#include \"bits/stdc++.h\"\n\n#define ll          long long\n#define pb          push_back\n#define mp          make_pair\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (int)x.size()\n#define hell        1000000007\n#define endl        '\\n'\n#define rep(i,a,b)\tfor(int i=a;i<b;i++)\nusing namespace std;\n\nint dp[5001][5001];\nll expo(ll base, ll exponent, ll mod) {\n    ll ans = 1;\n    while(exponent !=0 ) {\n        if((exponent&1) == 1) {\n            ans = ans*base ;\n            ans = ans%mod;\n        }\n        base = base*base;\n        base %= mod;\n        exponent>>= 1;\n    }\n    return ans%mod;\n}\nint fill(int diffs,int a,int tot){\n\tif(dp[diffs][a]>=0)return dp[diffs][a];\n\tint b=tot-a;\n\tif(diffs==0){\n\t\treturn dp[diffs][a]=expo(2,b,hell);\n\t}\n\treturn dp[diffs][a]=((b?1LL*b*fill(diffs-1,a+1,tot):0LL)+(a?1LL*a*fill(diffs-1,a,tot):0LL))%hell;\n}\n\nvoid solve(){\n\tint N,k;\n\tcin>>N>>k;\n\tmemset(dp,-1,sizeof dp);\n\tcout<<fill(k,0,N)<<endl;\n}\n\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\tint t=1;\n//\tcin>>t;\n\twhile(t--){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "932",
    "index": "F",
    "title": "Escape Through Leaf",
    "statement": "You are given a tree with $n$ nodes (numbered from $1$ to $n$) rooted at node $1$. Also, each node has two values associated with it. The values for $i$-th node are $a_{i}$ and $b_{i}$.\n\nYou can jump from a node to any node in its subtree. The cost of one jump from node $x$ to node $y$ is the product of $a_{x}$ and $b_{y}$. The total cost of a path formed by one or more jumps is sum of costs of individual jumps. For every node, calculate the minimum total cost to reach any leaf from that node. Pay attention, that root can never be leaf, even if it has degree $1$.\n\nNote that you cannot jump from a node to itself.",
    "tutorial": "The problem can be solved by dynamic programming. Let $dp[i]$ be the minimum cost to reach a leaf from $i^{th}$ node. Then, $d p[i]=\\operatorname*{min}_{\\forall j\\in s u b t r e e(i)}(a[i]\\ast b[j]+d p[j])$ where $j  \\neq  i$. This is equivalent to finding the minimum $y$ at $x = a[i]$ among lines $y = b[j] * x + dp[j]$. Thus, convex hull trick of dp optimization can be used to find the minimum value. Once the value is calculated for a node, a line with slope $b[i]$ and y-intercept $dp[i]$ is added to the hull. However,at all times, we need to maintain a lower convex hull of only the nodes in the current subtree. The trick of merging small to large can be used here. While we are at a node $i$, we form a convex hull for the subtree rooted at each child. The convex hulls of the light children can then be merged into the convex hull of the heavy child. Once the convex hull for the entire subtree is formed, a query for the minimum value at x-coordinate $a[i]$ in the lower hull gives the value of $dp[i]$. The merging of small to large has time complexity of $O(nlogn)$ while the addition of a line into the hull requires time $O(logn)$. Complexity: $O(nlog^{2}n)$",
    "code": "#include \"bits/stdc++.h\"\n\n\n#define ll          long long\n#define pb          push_back\n#define mp          make_pair\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (int)x.size()\n#define hell        1000000007\n#define endl        '\\n'\n#define rep(i,a,b)    for(int i=a;i<b;i++)\nusing namespace std;\n\nbool Q;\nstruct Line {\n    mutable ll k, m, p;\n    bool operator<(const Line& o) const {\n        return Q ? p < o.p : k < o.k;\n    }\n};\nstruct LineContainer : multiset<Line> {\n    const ll inf = LLONG_MAX;\n    ll div(ll a, ll b){\n        return a / b - ((a ^ b) < 0 && a % b);\n    }\n    bool isect(iterator x, iterator y) {\n        if (y == end()) { x->p = inf; return false; }\n        if (x->k == y->k) x->p = x->m > y->m ? inf : -inf;\n        else x->p = div(y->m - x->m, x->k - y->k);\n        return x->p >= y->p;\n    }\n    void add(ll k, ll m) {\n        auto z = insert({k, m, 0}), y = z++, x = y;\n        while (isect(y, z)) z = erase(z);\n        if (x != begin() && isect(--x, y)) isect(x, y = erase(y));\n        while ((y = x) != begin() && (--x)->p >= y->p)\n            isect(x, erase(y));\n    }\n    ll query(ll x) {\n        assert(!empty());\n        Q = 1; auto l = *lower_bound({0,0,x}); Q = 0;\n        return l.k * x + l.m;\n    }\n};\n\nvector<int> x,y;\nvector<vi> adj;\nvector<ll> ans;\nvector<int> subsize;\nvoid dfs1(int u,int v){\n    subsize[u]=1;\n    for(auto i:adj[u]){\n        if(i==v)continue;\n        dfs1(i,u);\n        subsize[u]+=subsize[i];\n    }\n}\n\nvoid dfs2(int v, int p,LineContainer& cur){\n    int mx=-1,bigChild=-1;\n    bool leaf=1;\n    for(auto u:adj[v]){\n        if(u!=p and subsize[u]>mx){\n            mx=subsize[u];\n            bigChild=u;\n            leaf=0;\n        }\n    }\n    if(bigChild!=-1){\n        dfs2(bigChild,v,cur);\n    }\n    for(auto u:adj[v]){\n        if(u!=p and u!=bigChild){\n            LineContainer temp;\n            dfs2(u,v,temp);\n            for(auto i:temp){\n                cur.add(i.k,i.m);\n            }\n        }\n    }\n    if(!leaf)ans[v]=-cur.query(x[v]);\n    else ans[v]=0;\n    cur.add(-y[v],-ans[v]);\n}\nvoid solve(){\n    int n;\n    cin>>n;\n    x.resize(n+1);\n    y.resize(n+1);\n    ans.resize(n+1);\n    subsize.resize(n+1);\n    adj.resize(n+1);\n    rep(i,1,n+1)cin>>x[i];\n    rep(i,1,n+1)cin>>y[i];\n    rep(i,1,n){\n        int u,v;\n        cin>>u>>v;\n        adj[u].pb(v);\n        adj[v].pb(u);\n    }\n    dfs1(1,0);\n    LineContainer lc;\n    dfs2(1,0,lc);\n    rep(i,1,n+1)cout<<ans[i]<<\" \";\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int t=1;\n//    cin>>t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "geometry"
    ],
    "rating": 2700
  },
  {
    "contest_id": "932",
    "index": "G",
    "title": "Palindrome Partition",
    "statement": "Given a string $s$, find the number of ways to split $s$ to substrings such that if there are $k$ substrings $(p_{1}, p_{2}, p_{3}, ..., p_{k})$ in partition, then $p_{i} = p_{k - i + 1}$ for all $i$ $(1 ≤ i ≤ k)$ and $k$ is even.\n\nSince the number of ways can be large, print it modulo $10^{9} + 7$.",
    "tutorial": "Let n be the length of the string $s$. Consider the string $t = s[0]s[n - 1]s[1]s[n - 2]s[2]s[n - 3]...s[n / 2 - 1]s[n / 2]$. The problem can be reduced to finding the number of ways to partition string $t$ into palindromic substrings of even length. Proof: Let $k$ be the total number of partitions. Let $p_{i} = p_{k - i + 1} = x_{1}x_{2}x_{3}...x_{m}$ where $m$ denotes length of $p_{i}$ and $x_{j}$ denotes $j^{th}$ character of $p_{i}$. The part of string $t$ corresponding to these two partitions is $x_{1}x_{m}x_{2}x_{m - 1}...x_{m - 1}x_{2}x_{m}x_{1}$ which is an even length palindrome. Similarly, the converse is also true. Dynamic programming can be used to solve the problem. Let $dp[i]$ be the number of ways to partition $t[1...i]$ into even length palindromes. Then, $d p[i]=\\sum d p[j]$ where $t[j + 1...i]$ is an even length palindrome. Of course for odd $i$, $dp[i] = 0$. As discussed in thisblog, we can use an eertree to implement the solution. On the other hand, we can avoid the use of any suffix structure by following the algorithm described in thispaper. Complexity: $O(|s|log|s|)$",
    "code": "#define NDEBUG\nNDEBUG\n\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cstring>\n#include <cmath>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n#include <memory>\n#include <queue>\n#include <random>\n\n\n#define forn(t, i, n) for (t i = 0; i < (n); ++i)\n\n\nusing namespace std;\n\n// TC_REMOVE_BEGIN\n/// caide keep\nbool __hack = std::ios::sync_with_stdio(false);\n/// caide keep\nauto __hack1 = cin.tie(nullptr);\n// TC_REMOVE_END\n\n\n// Section with adoption of array and vector algorithms.\n\n\n#define ENABLE_IF(e) typename enable_if<e>::type* = nullptr\n\nnamespace template_util {\n    \n\n    constexpr int bytecount(uint64_t x) {\n        return x ? 1 + bytecount(x >> 8) : 0;\n    }\n\n    template<int N>\n    struct bytetype {\n        \n    };\n\n    template<>\n    struct bytetype<4> {\n        typedef uint32_t type;\n    };\n\n    \n    template<>\n    struct bytetype<1> {\n        typedef uint8_t type;\n    };\n\n    \n    /// caide keep\n    template<uint64_t N>\n    struct minimal_uint : bytetype<bytecount(N)> {\n    };\n}\n\n\ntemplate<class T>\nT next(istream& in) {\n    T ret;\n    in >> ret;\n    return ret;\n}\n\n\n/*\nTODOs:\n primitive root\n discrete log\n\n tests!!!\n*/\n\nnamespace mod_impl {\n    /// caide keep\n    template <class T>\n    constexpr inline T mod(T MOD) {\n        return MOD;\n    }\n\n    /// caide keep\n    template <class T>\n    constexpr inline T mod(T* MOD) {\n        return *MOD;\n    }\n\n    /// caide keep\n    template <class T>\n    constexpr inline T max_mod(T MOD) {\n        return MOD - 1;\n    }\n\n    /// caide keep\n    template <class T>\n    constexpr inline T max_mod(T*) {\n        return numeric_limits<T>::max() - 1;\n    }\n\n    \n    constexpr inline uint64_t combine_max_sum(uint64_t a, uint64_t b) {\n        return a > ~b ? 0 : a + b;\n    }\n\n    \n    /// caide keep\n    template <class T>\n    constexpr inline uint64_t next_divisible(T mod, uint64_t max) {\n        return max % mod == 0 ? max : combine_max_sum(max, mod - max % mod);\n    }\n\n    /// caide keep\n    template <class T>\n    constexpr inline uint64_t next_divisible(T*, uint64_t) {\n        return 0;\n    }\n\n    //caide keep\n    constexpr int IF_THRESHOLD = 2;\n\n    template <class T, T MOD_VALUE, uint64_t MAX,\n            class RET = typename template_util::minimal_uint<max_mod(MOD_VALUE)>::type,\n            ENABLE_IF(MAX <= max_mod(MOD_VALUE) && !is_pointer<T>::value)>\n    inline RET smart_mod(typename template_util::minimal_uint<MAX>::type value) {\n        return value;\n    }\n\n    template <class T, T MOD_VALUE, uint64_t MAX,\n            class RET = typename template_util::minimal_uint<max_mod(MOD_VALUE)>::type,\n            ENABLE_IF(max_mod(MOD_VALUE) < MAX && MAX <= IF_THRESHOLD * max_mod(MOD_VALUE) && !is_pointer<T>::value)>\n    inline RET smart_mod(typename template_util::minimal_uint<MAX>::type value) {\n        while (value >= mod(MOD_VALUE)) {\n            value -= mod(MOD_VALUE);\n        }\n        return (RET)value;\n    }\n\n    \n}\n\n\n#define MAX_MOD mod_impl::max_mod(MOD_VALUE)\n\nstruct DenormTag {};\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX = MAX_MOD, ENABLE_IF(MAX_MOD >= 2)>\nstruct ModVal {\n    typedef typename template_util::minimal_uint<MAX>::type storage;\n    storage value;\n\n    /// caide keep\n    inline ModVal(): value(0) {\n        assert(MOD >= 2);\n    }\n\n    \n    inline ModVal(storage v, DenormTag): value(v) {\n        assert(MOD >= 2);\n        assert(v <= MAX);\n    };\n\n    inline operator ModVal<T, MOD_VALUE>() {\n        return {v(), DenormTag()};\n    };\n\n    \n    typename template_util::minimal_uint<mod_impl::max_mod(MOD_VALUE)>::type v() const {\n        return mod_impl::smart_mod<T, MOD_VALUE, MAX>(value);\n    }\n};\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX1, uint64_t MAX2,\n        uint64_t NEW_MAX = mod_impl::combine_max_sum(MAX1, MAX2),\n        ENABLE_IF(NEW_MAX != 0), class Ret = ModVal<T, MOD_VALUE, NEW_MAX>>\ninline Ret operator+(ModVal<T, MOD_VALUE, MAX1> o1, ModVal<T, MOD_VALUE, MAX2> o2) {\n    return {typename Ret::storage(typename Ret::storage() + o1.value + o2.value), DenormTag()};\n}\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX>\ninline ModVal<T, MOD_VALUE>& operator+=(ModVal<T, MOD_VALUE>& lhs, const ModVal<T, MOD_VALUE, MAX>& rhs) {\n    lhs = lhs + rhs;\n    return lhs;\n}\n\n\ntemplate <class T, T MOD_VALUE, class MOD_TYPE>\nstruct ModCompanion {\n    typedef MOD_TYPE mod_type;\n    typedef ModVal<mod_type, MOD_VALUE> type;\n    \n\n    template <uint64_t C>\n    inline static constexpr ModVal<mod_type, MOD_VALUE, C> c() {\n        return {C, DenormTag()};\n    };\n\n    \n};\n\n\n#undef MAX_MOD\n\ntemplate <uint64_t MOD_VALUE>\nstruct Mod : ModCompanion<uint64_t, MOD_VALUE, typename template_util::minimal_uint<MOD_VALUE>::type> {\n    template<uint64_t VAL>\n    static constexpr uint64_t literal_builder() {\n        return VAL;\n    }\n\n    template<uint64_t VAL, char DIGIT, char... REST>\n    static constexpr uint64_t literal_builder() {\n        return literal_builder<(10 * VAL + DIGIT - '0') % MOD_VALUE, REST...>();\n    }\n};\n\n\n#define REGISTER_MOD_LITERAL(mod, suffix) \\\ntemplate <char... DIGITS> mod::type operator \"\" _##suffix() { \\\n    return mod::c<mod::literal_builder<0, DIGITS...>()>(); \\\n}\n\n\ntemplate <class T, T MOD_VALUE, uint64_t MAX>\ninline ostream& operator<<(ostream& s, ModVal<T, MOD_VALUE, MAX> val) {\n    s << val.v();\n    return s;\n}\n\nusing md = Mod<1000000007>;\nusing mt = md::type;\nREGISTER_MOD_LITERAL(md, mod)\n\nstruct Triple {\n    int start, delta, count;\n\n    int end() {\n        return start + delta * (count - 1);\n    }\n};\n\n// ostream& operator<<(ostream& out, const Triple& t) {\n//     out << \"(\" << t.start << \", \" << t.delta << \", \" << t.count << \")\";\n//     return out;\n// }\n\nvoid solve(istream& in, ostream& out) {\n    auto s = next<string>(in);\n    string s1;\n    s1.reserve(2 * s.length());\n    forn (int, i, s.length() / 2) {\n        s1.push_back(s[i]);\n        s1.push_back(s[s.length() - i - 1]);\n    }\n    int n = s1.length();\n    vector<Triple> g;\n    vector<mt> d(n + 1), cache(n + 1);\n    d[0] = 1_mod;\n    forn (int, i, n) {\n        vector<Triple> g1;\n        int prev = -i - 1;\n        auto push = [&](Triple t) {\n            if (g1.empty() || t.delta != g1.back().delta) {\n                g1.push_back(t);\n            } else {\n                g1.back().count += t.count;\n            }\n        };\n        for (auto t : g) {\n            if (t.start > 0 && s1[t.start - 1] == s1[i]) {\n                t.start--;\n                if (prev != t.start - t.delta) {\n                    push(Triple{t.start, t.start - prev, 1});\n                    t.start += t.delta;\n                    t.count--;\n                }\n                if (t.count > 0) {\n                    push(t);\n                }\n                prev = t.end();\n            }\n        }\n        if (i >= 1 && s1[i - 1] == s1[i]) {\n            push(Triple{i - 1, i - 1 - prev, 1});\n        }\n        g = move(g1);\n        for (auto& t : g) {\n            mt add = d[t.end()];\n            if (t.count > 1) {\n                add += cache[t.start - t.delta];\n            }\n            if (t.start - t.delta >= 0) {\n                cache[t.start - t.delta] = add;\n            }\n            d[i + 1] += add;\n        }\n    }\n    out << d[n] << endl;\n}\n\n\nint main() {\n    solve(cin, cout);\n    return 0;\n}\n",
    "tags": [
      "dp",
      "string suffix structures",
      "strings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "933",
    "index": "A",
    "title": "A Twisty Movement",
    "statement": "A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.\n\nA performer holding the rod low is represented by a $1$, while one holding it high is represented by a $2$. Thus, the line of performers can be represented by a sequence $a_{1}, a_{2}, ..., a_{n}$.\n\nLittle Tommy is among them. He would like to choose an interval $[l, r]$ ($1 ≤ l ≤ r ≤ n$), then reverse $a_{l}, a_{l + 1}, ..., a_{r}$ so that the length of the longest non-decreasing subsequence of the new sequence is maximum.\n\nA non-decreasing subsequence is a sequence of indices $p_{1}, p_{2}, ..., p_{k}$, such that $p_{1} < p_{2} < ... < p_{k}$ and $a_{p1} ≤ a_{p2} ≤ ... ≤ a_{pk}$. The length of the subsequence is $k$.",
    "tutorial": "Since $1  \\le  a_{i}  \\le  2$, it's equivalent to find a longest subsequence like $1^{} * 2^{} * 1^{} * 2^{} *$. By an easy dynamic programming we can find it in $O(n)$ or $O(n^{2})$ time. You can see $O(n^{2})$ solution in the model solution below. Here we introduce an O(n) approach: Since the subsequence can be split into 4 parts ($11...22...11...22...$) , we can set $dp[i][j](i = 1...n, j = 0..3)$ be the longest subsequence of $a[1...i]$ with first $j$ parts.",
    "code": "#include <bits/stdc++.h>\n\n#define rep(i, x, y) for (int i = (x), _ = (y); i < _; ++i)\n#define down(i, x, y) for (int i = (x) - 1, _ = (y); i >= _; --i)\n#define fi first\n#define se second\n#define mp(x, y) make_pair(x, y)\n#define pb(x) push_back(x)\n#define bin(x) (1 << (x))\n#define SZ(x) int((x).size())\n\nusing namespace std;\ntypedef pair<int, int> pii;\ntypedef vector<int> Vi;\ntypedef long long ll;\n\ntemplate<typename T> inline bool upmax(T &x, T y) { return x < y ? (x = y, 1) : 0; }\ntemplate<typename T> inline bool upmin(T &x, T y) { return x > y ? (x = y, 1) : 0; }\n\nconst int MAX_N = 2005;\n\nint pre[MAX_N][2], suf[MAX_N][2];\nint g[MAX_N][MAX_N][2][2];\nint w[MAX_N], N;\n\nint main() {\n\tscanf(\"%d\", &N);\n\trep (i, 0, N) { scanf(\"%d\", &w[i]); w[i]--; }\n\trep (i, 0, N) {\n\t\tif (i) memcpy(pre[i], pre[i - 1], sizeof pre[i]);\n\t\tdown (j, 2, w[i]) upmax(pre[i][j], pre[i][w[i]] + 1);\n\t}\n\tdown (i, N, 0) {\n\t\tif (i < N - 1) memcpy(suf[i], suf[i + 1], sizeof suf[i]);\n\t\trep (j, 0, w[i] + 1) upmax(suf[i][j], suf[i][w[i]] + 1);\n\t}\n\tint ans = pre[N - 1][1];\n\trep (i, 0, N) {\n\t\trep (a, 0, w[i] + 1) rep (b, w[i], 2) {\n\t\t\tg[i][i][a][b] = 1;\n\t\t}\n\t}\n\trep (l, 1, N) rep (i, 0, N - l) {\n\t\tint j = i + l;\n\t\trep (l, 0, 2) rep (a, 0, 2 - l) {\n\t\t\tint b = a + l;\n\t\t\tg[i][j][a][b] = max((a < 1 ? g[i][j][a + 1][b] : 0), (b ? g[i][j][a][b - 1] : 0));\n\t\t\tupmax(g[i][j][a][b], g[i + 1][j][a][b] + (b == w[i]));\n\t\t\tupmax(g[i][j][a][b], g[i][j - 1][a][b] + (a == w[j]));\n\t\t\tupmax(ans, (i ? pre[i - 1][a] : 0) + g[i][j][a][b] + (j < N - 1 ? suf[j + 1][b] : 0));\n\t\t}\n\t}\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}\n",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "933",
    "index": "B",
    "title": "A Determined Cleanup",
    "statement": "In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.\n\nLittle Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...\n\nGiven two integers $p$ and $k$, find a polynomial $f(x)$ with non-negative integer coefficients strictly less than $k$, whose remainder is $p$ when divided by $(x + k)$. That is, $f(x) = q(x)·(x + k) + p$, where $q(x)$ is a polynomial (not necessarily with integer coefficients).",
    "tutorial": "For simplicity's sake, we present a rather intuitive approach rather than a rigorous proof (can be obtained by induction). For a given polynomial $f(x)$, what's its remainder taken modulo $(x + k)$? Let $f(x) = q(x) \\cdot (x + k) + p$. Let Simulating the process of polynomial long division $f(x)$ divided by $(x + k)$, we get Try it yourself! A simple pattern emerges from the results. Let's take a closer look! $p = a_{0} + ( - k) \\cdot a_{1} + ... + ( - k)^{d} \\cdot a^{d}$ And there's another constraint: $0  \\le  a_{i} < k$. Base negative $k$, that's it! The coefficients $a_{0}, a_{1}, ..., a_{d}$ is the base $- k$ representation of $p$. It surely exists, and is unique! We can also deduce that $d=O(\\log n)$, which is why there is no constraint on the output $d$. If you aren't familiar with negative bases, please refer to Wikipedia. But that doesn't matter! You may as well come up with an algorithm for converting to negative bases on your own. For an example, refer to the \"Calculation\" section in the aforementioned page.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nlong long p;\nint k;\nint cnt=0;\nint ans[107];\nint get()\n{\n\tint x=p%k;\n\tif (x<0) x+=k;\n\treturn x%k;\n}\nint main()\n{\n\tscanf(\"%lld%d\",&p,&k);\n\twhile (p!=0)\n\t{\n\t\t++cnt;\n\t\tans[cnt]=get();\n\t\tp-=get();\n\t\tp/=(-k);\n\t}\n\tprintf(\"%d\\n\",cnt);\n\tfor (int i=1;i<=cnt;i++)\n\t\tprintf(\"%d \",ans[i]);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n",
    "tags": [
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "933",
    "index": "C",
    "title": "A Colourful Prospect",
    "statement": "Firecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement.\n\nLittle Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve.\n\nA wonder strikes Tommy. How many regions are formed by the circles on the sky? We consider the sky as a flat plane. A region is a connected part of the plane with positive area, whose bound consists of parts of bounds of the circles and is a curve or several curves without self-intersections, and that does not contain any curve other than its boundaries. Note that exactly one of the regions extends infinitely.",
    "tutorial": "It seems the problem can be solved with case analysis at first sight. Okay let's try to do so... For $n = 1$, it's trivial and the answer is, of course, $2$. For $n = 2$, there are two cases: If the two circles are intersect, the answer is $4$; Otherwise, the answer is $3$. For $n = 3$... well I think it's really a tough job, so think about general case will probably make our lives better. The main solution is based on Euler's formula for planar graph. This formula tells us that if we denote the number of vertices in a connected graph by $v$, the number of edges by $e$ and the number of faces (or regions) by $f$, we have $f = e - v + 2$. Since the circles can form several components, denoted the number of which by $c$, the formula for general planar graph should be $f = e - v + c + 1$. So what we need to do is to calculate $v$, $e$, and $c$. It's easy to see that $v$ is the number of unique intersection between circles. As for $e$, we can calculate the number of edges on each circle, which is equal to the unique intersection on each circle. The only special case is a single circle, and we can consider it as a graph without vertices and edges but forms one component, or a vertex with an edge to itself. Anyway it doesn't matter when $v = e$. The last one is $c$, which can be obtained easily with the help of dsu or dfs/bfs. The total complexity is $O(n^{2}\\log{n})$, but why I leave this special case as a problem instead of a general case? Reread the first sentence of this tutorial and you will get the answer :) Here I want to show you the test #113, which is made by hands. Guess how many regions in this graph?",
    "code": "#include <cmath>\n#include <cstdio>\n#include <algorithm>\n\nstatic const int MAXN = 3;\nstatic const double EPS = 1e-9;\n\nstatic int n;\nstatic int x[MAXN], y[MAXN], r[MAXN];\n\n// -2: internally separate\n// -1: internally tangent\n//  0: intersecting\n// +1: externally tangent\n// +2: externally separate\nstatic int g[MAXN][MAXN];\n// Number of points passed by all three circles\nstatic int conc;\n\ninline int rel(int a, int b)\n{\n    int dssq = (x[a] - x[b]) * (x[a] - x[b]) + (y[a] - y[b]) * (y[a] - y[b]),\n        dfsq = (r[a] - r[b]) * (r[a] - r[b]),\n        smsq = (r[a] + r[b]) * (r[a] + r[b]);\n\n    if (dssq < dfsq) return -2;\n    else if (dssq == dfsq) return -1;\n    else if (dssq < smsq) return 0;\n    else if (dssq == smsq) return +1;\n    else return +2;\n}\n\ninline void get_intersections(int a, int b, double ix[2], double iy[2])\n{\n    double angle = atan2(y[b] - y[a], x[b] - x[a]);\n    double ds = sqrt((x[a] - x[b]) * (x[a] - x[b]) + (y[a] - y[b]) * (y[a] - y[b]));\n    double delta = acos((ds * ds + r[a] * r[a] - r[b] * r[b]) / (2.0 * r[a] * ds));\n    ix[0] = x[a] + r[a] * cos(angle + delta);\n    iy[0] = y[a] + r[a] * sin(angle + delta);\n    ix[1] = x[a] + r[a] * cos(angle - delta);\n    iy[1] = y[a] + r[a] * sin(angle - delta);\n}\n\ninline bool on_circle(int a, double x0, double y0)\n{\n    return fabs((x[a] - x0) * (x[a] - x0) + (y[a] - y0) * (y[a] - y0) - r[a] * r[a]) <= EPS;\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) scanf(\"%d%d%d\", &x[i], &y[i], &r[i]);\n\n    for (int i = 0; i < n - 1; ++i)\n        for (int j = i + 1; j < n; ++j)\n            g[i][j] = g[j][i] = rel(i, j);\n\n    conc = 0;\n    if (n == 3) {\n        for (int i = 0; i < 2; ++i) {\n            for (int j = i + 1; j < 3; ++j) if (g[i][j] >= -1 && g[i][j] <= +1) {\n                int k = 3 - i - j;\n                double ix[2], iy[2];\n                get_intersections(i, j, ix, iy);\n                if (on_circle(k, ix[0], iy[0])) ++conc;\n                if (on_circle(k, ix[1], iy[1]) && g[i][j] == 0) ++conc;\n                break;\n            }\n            if (conc != 0) break;\n        }\n    }\n\n    if (n == 1) {\n        puts(\"2\");\n    } else if (n == 2) {\n        puts(g[0][1] == 0 ? \"4\" : \"3\");\n    } else if (n == 3) {\n        int x[3] = { g[0][1], g[0][2], g[1][2] };\n        std::sort(x, x + 3);\n        if (x[0] == -2) {\n            printf(\"%d\\n\", 4 + (x[1] == 0) + (x[2] == 0));\n        } else if (x[0] == -1) {\n            if (x[1] == -1) {\n                printf(\"%d\\n\", x[2] == -1 ? 4 : (6 - x[2]));\n            } else {\n                switch (x[1] * 10 + x[2]) {\n                    case 00: printf(\"%d\\n\", 7 - conc); break;\n                    case 01: puts(\"6\"); break;\n                    case 02: puts(\"5\"); break;\n                    case 11: case 12: case 22: puts(\"4\"); break;\n                    default: puts(\"> <\");\n                }\n            }\n        } else if (x[0] >= +1) {\n            puts(x[0] == +1 && x[2] == +1 ? \"5\" : \"4\");\n        } else {    // x[0] == 0\n            switch (x[1] * 10 + x[2]) {\n                case 00: printf(\"%d\\n\", 8 - conc); break;\n                case 01: printf(\"%d\\n\", 7 - conc); break;\n                case 02: puts(\"6\"); break;\n                case 11: puts(\"6\"); break;\n                case 12: puts(\"5\"); break;\n                case 22: puts(\"5\"); break;\n                default: puts(\"> <\");\n            }\n        }\n    } else puts(\"> <\");\n\n    return 0;\n}\n",
    "tags": [
      "geometry",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "933",
    "index": "D",
    "title": "A Creative Cutout",
    "statement": "Everything red frightens Nian the monster. So do red paper and... you, red on Codeforces, potential or real.\n\nBig Banban has got a piece of paper with endless lattice points, where lattice points form squares with the same area. His most favorite closed shape is the circle because of its beauty and simplicity. Once he had obtained this piece of paper, he prepares it for paper-cutting.\n\nHe drew $n$ concentric circles on it and numbered these circles from $1$ to $n$ such that the center of each circle is the same lattice point and the radius of the $k$-th circle is $\\sqrt{k}$ times the length of a lattice edge.\n\nDefine the degree of beauty of a lattice point as the summation of the \\textbf{indices} of circles such that this lattice point is inside them, or on their bounds. Banban wanted to ask you the total degree of beauty of all the lattice points, but changed his mind.\n\nDefining the total degree of beauty of all the lattice points on a piece of paper with $n$ circles as $f(n)$, you are asked to figure out $({\\sum_{k=1}^{m}}f(k)){\\mathrm{~mod~}}(10^{9}+7)$.",
    "tutorial": "For the sake of explanation, let's use $\\textstyle{\\binom{n}{k}}$ to represent the binomial coefficient $\\frac{n!}{k!(n-k)!}$ and construct a coordinate system such that each coordinate axis parallels to one of the lattice edges, the origin is the center of concentric circles and each unit of length in this system is as long as the length of a lattice edge. For $f(n)$, we could figure out the contribution of each lattice point $(x, y)$ is $\\textstyle\\sum_{k=x^{2}+u^{2}}^{n}k={\\binom{n+1}{2}}-{\\binom{x^{2}+y^{2}}{2}}.$ Defining $L$ as $x^{2} + y^{2}$, we could conclude for the answer the contribution of each lattice point $(x, y)$ is $\\begin{array}{l}{{\\displaystyle\\sum_{k=L}^{m}\\left(\\left(k+1\\atop2\\atop1}\\right)-\\left(\\displaystyle=\\left(2\\right)\\right)\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad\\qquad}}\\\\ {{\\left(m+2\\right)-\\left(L+1\\right)L+m(m+1)(m+2)\\right)}}\\end{array}$ By using $(x^{2}+y^{2})^{n}=\\sum_{k=0}^{n}{\\binom{n}{k}}x^{2k}y^{2(n-k)}$, we could form the answer as $\\sum_{x^{2}+y^{2}\\leq m}\\sum_{p+q\\leq3}\\mathrm{GOe}\\Pi_{p,q}x^{2p}y^{2q}$ The remaining part to solve this problem is just to enumerate all the possible integers $x, q$ and then calculate ${\\sum}_{p=0}^{35-q}\\mathrm{CO}\\mathrm{e}\\Pi_{p,q}x^{2p}$, $\\sum_{y\\in\\mathbb{Z}^{*},\\|y\\|\\leq{\\sqrt{m-x^{2}}}}\\ y^{2q}$ in constant time. The total complexity is $O({\\sqrt{m}})$. By the way, the standard solution has hardcoded some closed forms to calculate the partial sum of small powers fast, but you can precalculate $s_{q}(k)=\\sum_{\\stackrel{U\\in{\\mathcal{Z}},|y|<k}{\\leq k}}y^{2q}$ and then enumerate $x$. Please be careful with 64-bit integer overflow, for example, $10^{12} \\cdot 10^{9}  \\ge  2^{64}$. Although there is a pretest in case of $m = 2^{32}$ to reject brute force and some solutions with obvious overflow, it is highly probable to fail in the case of large input such as $m = 10^{12}$. The probability of failure is increasing when the number increases. Take care.",
    "code": "#include <bits/stdc++.h>\n\n\nusing namespace std;\n\n#define re return\n#define sz(a) (int)a.size()\n#define mp(a, b) make_pair(a, b)\n#define fi first\n#define se second\n#define re return\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define bend(a) a.begin(),a.end()\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef pair<int, int> pii;\ntypedef pair<long long, long long> pll;\ntypedef long double ld;\ntypedef unsigned long long ull;\nconst ll mod = int(1e9) + 7;\n\nll n, sum1, sum2, sum3, sum4, ans;\nvector<ll> cp;\n\nll mdd(ll c) {\n\tc %= mod;\n\tif (c < 0) c += mod;\n\tre c;\n}\n\nll pow1(ll k, ll st) {\n\tll ans = 1;\n\twhile (st) {\n\t\tif (st & 1) ans = mdd(ans * k);\n\t\tk = mdd(k * k);\n\t\tst >>= 1;\n\t}\n\tre ans;\n}\n\nll get_sum(ll n) {\n\tn %= mod;\n\tn += mod;\n\tn %= mod;\n\tre (n * (n + 1) / 2LL) % mod;\n}\n\nll get_cnt(ll a) {\n\ta = mdd(a);\n\tre mdd(mdd(2LL * mdd(a * a) * a) - mdd(3LL * mdd(a * a) * mdd(n + 2)) + mdd(mdd(a) * mdd(3LL * n + 4)) + mdd(n) * mdd(mdd(mdd(n) * mdd(n)) + 3LL * n + 2LL));\n}\n\nint main() {\n\tiostream::sync_with_stdio(0), cin.tie(0);\n\tcin >> n;\n\tfor (ll k = 1; k * k <= n; k++) {\n\t\tll c = mdd(k * k);\n\t\tcp.push_back(k * k);\n\t\tsum1 = mdd(sum1 + c);\n\t\tsum2 = mdd(sum2 + mdd(c * c));\n\t\tsum3 = mdd(sum3 + mdd(mdd(c * c) * c));\n\t\tsum4 = mdd(sum4 + get_cnt(c));\n\t\t//cout << sum4 << \"\\n\";\n\t}\n\tans = mdd(get_cnt(1) + 4LL * sum4);\n\tll k1 = 2, k2 = mdd(-3LL * (n + 2)), k3 = mdd(3LL * n + 4);\n\tfor (ll a = 0; ; a++){\n\t\twhile (sz(cp) && cp.back() + (a+1LL) * (a + 1LL) > n) {\n\t\t\tll c = mdd(cp.back() + a * a);\n\t\t\tsum1 = mdd(sum1 - c);\n\t\t\tsum2 = mdd(sum2 - mdd(c * c));\n\t\t\tsum3 = mdd(sum3 - mdd(mdd(c * c) * c));\n\t\t\tsum4 = mdd(sum4 - mdd(get_cnt(c)));\n\t\t\tcp.pop_back();\n\t\t\tcontinue;\n\t\t}\t\t\n\t\tif (sz(cp) == 0) break;\n\t\tll k = mdd(2LL * a + 1), ksq = mdd(k * k), ktr = mdd(ksq * k);\n\t\t//cout << sum4 << \"\\n\";\n\t\tsum4 = mdd(sum4 + mdd(ll(sz(cp)) * mdd(k1 * ktr + k2 * ksq + k3 * k)) +\n\t\t\t   mdd(sum1 * mdd(2LL * k * k2 + 3LL * k1 * ksq)) +\n\t\t\t   mdd(sum2 * mdd(3LL * k * k1)));\n\t\t//cout << sum4 << \"\\n\";\n\t\tans = mdd(ans + 4LL * sum4);\n\t\tsum3 = mdd(sum3 + mdd(ll(sz(cp)) * ktr) + mdd(sum2 * 3LL * k) + mdd(ksq * 3LL * sum1));\n\t\tsum2 = mdd(sum2 + mdd(ll(sz(cp)) * ksq) + mdd(2LL * sum1 * k));\n\t\tsum1 = mdd(sum1 + mdd(ll(sz(cp)) * k));\n\t\t//cout << sum3 << \" \" << sum2 << \" \" << sum1 << \"\\n\";\n\t}\n\t//cout << ans /6<< \"\\n\";\n\tans = mdd(ans * pow1(6, mod - 2));\n\tcout << ans;\n} \n",
    "tags": [
      "brute force",
      "combinatorics",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "933",
    "index": "E",
    "title": "A Preponderant Reunion",
    "statement": "East or west, home is best. That's why family reunion, the indispensable necessity of Lunar New Year celebration, is put in such a position.\n\nAfter the reunion dinner, Little Tommy plays a game with the family. Here is a concise introduction to this game:\n\n- There is a sequence of $n$ non-negative integers $p_{1}, p_{2}, ..., p_{n}$ in the beginning. It is ruled that each integer in this sequence should be non-negative \\textbf{at any time}.\n- You can select two \\textbf{consecutive positive} integers in this sequence, $p_{i}$ and $p_{i + 1}$ $(1 ≤ i < n)$, and then decrease them by their minimum (i. e. $min(p_{i}, p_{i + 1})$), the cost of this operation is equal to $min(p_{i}, p_{i + 1})$. We call such operation as a descension.\n- The game immediately ends when there are no two consecutive positive integers. Your task is to end the game so that the total cost of your operations is as small as possible.\n\nObviously, every game ends after at most $n - 1$ descensions. Please share your solution of this game with the lowest cost.",
    "tutorial": "The author was inspired by 100705B1 - Rasta-making and then made this problem. Noticing that there are no two consecutive positive integers after the game ends, the final sequence can be divided into some intervals which consist only zero elements such that the gap between every two adjacent intervals is at most one element (may positive). Let's try to solve a general version of this problem first. In this version, we don't need to decrease two consecutive positive integers by their minimum. We can decrease any two consecutive integers by $1$ many times (even if integers are negative) and our task is to eliminate all two consecutive positive integers such that the cost as small as possible. We can prove by contradiction or adjustment that there are no negative elements in the best solution for the general version (because the original elements are non-negative). Furthermore, the cost of the best solution for the general version is less or equal to that of the best solution for the original version. Let's consider the cost for the general version to make such an interval $[l, r]$ (i. e. $p_{l}, p_{l + 1}, ..., p_{r}$) become all non-positive $(1  \\le  l  \\le  r  \\le  n)$. Before concluding the formula, you may assume $p_{0} = p_{n + 1} = 0$. Let $c_{l} = p_{l},$ $c_{i} = max(p_{i} - c_{i - 1}, 0)$ $(i = l + 1, l + 2, ..., r)$. We can construct a series of operations to make them become non-positive such that the cost can be represented as $\\textstyle\\sum_{i=1}^{r}c_{i}$. Let's call the cost of such an interval $[l, r]$ as $f(l, r)$. Similarly, we know the actual minimal cost is less or equal to $f(l, r)$. If the length of an interval $[l, r]$ is greater than $2$, there is an observation that $\\begin{array}{c}{{f(l,r)}}\\\\ {{{}=\\left(\\sum_{i=}^{r-2}c_{i}\\right)+c_{r-1}+\\operatorname*{max}(p_{r}-c_{r}-1)}}\\\\ {{=f(l,r-2)+\\operatorname*{max}(p_{r},c_{r-1})}}\\\\ {{{}=f(l,r-2)+p_{r}}}\\\\ {{{}=f(l,r-2)+f(r,r)}}\\end{array}$ We can easily prove that $f(l, r)$ is the actual minimal cost in the cases of length $1$ and $2$. In addition, if we get any of the best solutions for the general version, we can construct a series of operations which is valid both in the general version and the original version. So we can conclude that the cost of the best solution for the general version is greater or equal to that for the original version. With one conclusion we mentioned above, we know that the minimal costs for the original version and the general version are equivalent. Denote $dp(i)$ as the minimum cost the first $i$ elements have used if the $i$-th element is going to be the right endpoint of such an interval. It's easy to compute $dp(n)$ in ${\\mathcal{O}}(n)$. After picking up all the intervals for the best solution, construction can be implemented by greedy. For example, utilize the descensions at the inner of intervals first, and then make use of the descensions at the edge of intervals. Please note that there may be at most one element that belongs to no interval at the head or the tail of the final sequence. Also, the descensions should operate on positive integers.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\nconst int maxn = (int)3e5 + 3;\nint n, a[maxn], cnt, p[maxn], m, out[maxn];\nLL f[maxn];\nbool v[maxn];\nint descension(int pos) {\n\tint dt = min(a[pos], a[pos + 1]);\n\tif(dt)\n\t\tout[++m] = pos;\n\ta[pos] -= dt;\n\ta[pos + 1] -= dt;\n\treturn dt;\n}\nint main() {\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", a + i);\n\t\tLL odd = f[max(i - 2, 0)] + a[i], even = f[max(i - 3, 0)] + max(a[i - 1], a[i]);\n\t\tf[i] = min(odd, even);\n\t\tv[i] = f[i] != odd;\n\t}\n\t// a[n + 1] = 0;\n\tLL ans = min(f[n - 1], f[n]);\n\t// printf(\"%lld\\n\", ans);\n\tfor(int i = n - (ans == f[n - 1]); i > 0; i -= 2 + v[i])\n\t\tp[++cnt] = i;\n\treverse(p + 1, p + cnt + 1);\n\tfor(int i = 1; i <= cnt; ++i) {\n\t\tint pre = p[i - 1], cur = p[i], ctr = 0;\n\t\tif(v[cur])\n\t\t\tctr += descension(cur - 1);\n\t\tctr += descension(pre + 1);\n\t\tctr += descension(cur);\n\t\tassert(ctr == f[cur] - f[pre]);\n\t}\n\tprintf(\"%d\\n\", m);\n\tfor(int i = 1; i <= m; ++i)\n\t\tprintf(\"%d\\n\", out[i]);\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "dp"
    ],
    "rating": 3200
  },
  {
    "contest_id": "934",
    "index": "A",
    "title": "A Compatible Pair",
    "statement": "Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.\n\nLittle Tommy has $n$ lanterns and Big Banban has $m$ lanterns. Tommy's lanterns have brightness $a_{1}, a_{2}, ..., a_{n}$, and Banban's have brightness $b_{1}, b_{2}, ..., b_{m}$ respectively.\n\nTommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.\n\nTommy wants to make the product as small as possible, while Banban tries to make it as large as possible.\n\nYou are asked to find the brightness of the chosen pair if both of them choose optimally.",
    "tutorial": "We can do as what we are supposed to do - hide one of the Tommy's lantern, and then take one non-hidden lantern from Tommy and one lantern from Banban so that the product of their brightness is maximized and the minimum between all cases becomes our answer. This is a straightforward $O(n^{2}m)$ solution. Also, there are many other ways to solve the problem but needs overall consideration. By the way, there were 10 pretests at first where most of contestants failed on the last one. However, considering not to make the judger running with heavy loads, I took away 3 pretests and the pretest 10 was taken by mistake. I must apologize for the extremely weak pretests that make tons of hacks now. But it looks not so bad from the result...",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll INF=(1LL<<60)-1;\nll a[55],b[55];\nint main()\n{\n    int n,m;\n    scanf(\"%d%d\",&n,&m);\n    for(int i=1;i<=n;i++)\n        scanf(\"%lld\",&a[i]);\n    for(int i=1;i<=m;i++)\n        scanf(\"%lld\",&b[i]);\n    ll res=INF;\n    for(int i=1;i<=n;i++)\n    {\n        ll now=-INF;\n        for(int j=1;j<=n;j++)if(j!=i)\n            for(int k=1;k<=m;k++)\n                now=max(now,a[j]*b[k]);\n        res=min(res,now);\n    }\n    printf(\"%lld\\n\",res);\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "games"
    ],
    "rating": 1400
  },
  {
    "contest_id": "934",
    "index": "B",
    "title": "A Prosperous Lot",
    "statement": "Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.\n\nBig Banban is hesitating over the amount of money to give out. He considers loops to be lucky since it symbolizes unity and harmony.\n\nHe would like to find a positive integer $n$ not greater than $10^{18}$, such that there are exactly $k$ \\underline{loops} in the decimal representation of $n$, or determine that such $n$ does not exist.\n\nA \\underline{loop} is a planar area enclosed by lines in the digits' decimal representation written in Arabic numerals. For example, there is one loop in digit $4$, two loops in $8$ and no loops in $5$. Refer to the figure below for all exact forms.",
    "tutorial": "What's the maximum number of loops in an integer no greater than $10^{18}$? Since $8$ is the only digit with two loops, we tend to use as many eights as possible. It can be seen that the answer is $36$, achieved by $888 888 888 888 888 888$. Thus if $k > 36$, the answer does not exist under the constraints. There are tons of approaches to the following part. Share yours in the comments! The author considers $8$ and $9$ as lucky numbers and uses only $8$ and $9$ to construct a valid answer. In particular, the output consists of $\\textstyle{\\left\\lfloor{\\frac{k}{2}}\\right\\rfloor}$ eight(s) and $(k{\\mathrm{~mod~}}2)$ nine(s).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint n,k;\nint main()\n{\n\tscanf(\"%d\",&k);\n\tif (k>36) printf(\"%d\\n\",-1);\n\telse\n\t{\n\t\twhile (k>0)\n\t\t{\n\t\t\tif (k>=2)\n\t\t\t{\n\t\t\t\tprintf(\"%d\",8);\n\t\t\t\tk-=2;\n\t\t\t} else\n\t\t\t{\n\t\t\t\tprintf(\"%d\",9);\n\t\t\t\tk-=1;\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "935",
    "index": "A",
    "title": "Fafa and his Company",
    "statement": "Fafa owns a company that works on huge projects. There are $n$ employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.\n\nFafa finds doing this every time is very tiring for him. So, he decided to choose the best $l$ employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.\n\nGiven the number of employees $n$, find in how many ways Fafa could choose the number of team leaders $l$ in such a way that it is possible to divide employees between them evenly.",
    "tutorial": "Let's try all values of $l$ from 1 to $n - 1$ and check whether the remaining people could be distributed equally over team leaders (that is, $l$ divides $n - l$). The number of valid values of $l$ is our answer. Complexity: $O(n)$. The problem is also equivalent to finding the number of ways to divide the $n$ employees into equal teams where each team contains more than one employee. It can also be solved in $O({\\sqrt{n}})$ by finding the number of divisors of $n$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "935",
    "index": "B",
    "title": "Fafa and the Gates",
    "statement": "Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.\n\nThe world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation $x = y$). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points $(0, 0)$, $(1, 1)$, $(2, 2)$, ...). The wall and the gates do not belong to any of the kingdoms.\n\nFafa is at the gate at position $(0, 0)$ and he wants to walk around in the two kingdoms. He knows the sequence $S$ of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from $(x, y)$ to $(x, y + 1)$) and 'R' (move one step right, from $(x, y)$ to $(x + 1, y)$).\n\nFafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence $S$. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point $(0, 0)$, i. e. he is initially on the side he needs.",
    "tutorial": "Fafa visits the gates when he stands on the line $y = x$. This happens only when he makes an equal number of up and right moves. Fafa will pass the gates if he is currently at a gate and will make a move similar to the last one. So, we can iterate over the moves in order from left to right keeping track of the number of up and right moves till now, and increment the answer if the next move is similar to the current one and the number of up and right moves are equal. Complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "935",
    "index": "C",
    "title": "Fifa and Fafa",
    "statement": "Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of $r$ meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius $R$. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.\n\nThe world is represented as an infinite 2D plane. The flat is centered at $(x_{1}, y_{1})$ and has radius $R$ and Fafa's laptop is located at $(x_{2}, y_{2})$, not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.",
    "tutorial": "Let $p$ be Fafa's position and $c$ be the flat center. Obviously, the largest wifi circle we can draw will touch the point $p$ and a point on the flat circle border $q$. The diameter of the circle will be the distance between $p$ and $q$. To maximize the area of the wifi circle, we will choose $q$ to be the furthest point on the border from $p$. This point lies on the line connecting $p$ and $c$. The center of wifi circle $w$ will be the midpoint of the line segment connecting $p$ and $q$. If the point $p$ is outside the circle, then the wifi circle will be the flat circle ($w = c$). If the point $p$ lies on the flat center ($p = c$), then there are infinite number of solutions as $q$ can be any point on the flat circle border. Complexity: $O(1)$",
    "tags": [
      "geometry"
    ],
    "rating": 1600
  },
  {
    "contest_id": "935",
    "index": "D",
    "title": "Fafa and Ancient Alphabet",
    "statement": "Ancient Egyptians are known to have used a large set of symbols $\\textstyle\\mathbf{\\hat{Z}}$ to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words $S_{1}$ and $S_{2}$ of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set $\\textstyle\\sum$ have equal probability for being in the position of any erased symbol.\n\nFifa challenged Fafa to calculate the probability that $S_{1}$ is lexicographically greater than $S_{2}$. Can you help Fafa with this task?\n\nYou know that $|\\sum|=m$, i. e. there were $m$ distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from $1$ to $m$ in alphabet order. A word $x$ is lexicographically greater than a word $y$ of the same length, if the words are same up to some position, and then the word $x$ has a larger character, than the word $y$.\n\nWe can prove that the probability equals to some fraction $P\\ /Q$, where $P$ and $Q$ are coprime integers, and $Q\\not\\equiv0\\mod{(10^{9}+7)}$. Print as the answer the value $R=P\\cdot Q^{-1}\\mathrm{\\mod\\(10^{9}+7)}$, i. e. such a non-negative integer less than $10^{9} + 7$, such that $R\\cdot Q\\equiv P\\mod\\left(10^{9}+7\\right)$, where $a\\equiv b\\mod(m)$ means that $a$ and $b$ give the same remainders when divided by $m$.",
    "tutorial": "Let $Suff_{1}(i)$ and $Suff_{2}(i)$ be the suffixes of $S_{1}$ and $S_{2}$ starting from index $i$, respectively. Also, let $P(i)$ be the probability of $Suff_{1}(i)$ being lexicographically larger than $Suff_{2}(i)$. $P(i)$ is equal to the probability that: $S_{1}[i]$ is greater than $S_{2}[i]$, or $S_{1}[i]$ is equal to $S_{2}[i]$ and $Suff_{1}(i + 1)$ is lexicographically greater than $Suff_{2}(i + 1)$. More formally, The answer to the problem is $P(0)$. Complexity: $O(n)$",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 1900
  },
  {
    "contest_id": "935",
    "index": "E",
    "title": "Fafa and Ancient Mathematics",
    "statement": "Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression.\n\nAn Ahmes arithmetic expression can be defined as:\n\n- \"$d$\" is an Ahmes arithmetic expression, where $d$ is a one-digit positive integer;\n- \"$(E_{1} op E_{2})$\" is an Ahmes arithmetic expression, where $E_{1}$ and $E_{2}$ are valid Ahmes arithmetic expressions (without spaces) and $op$ is either plus $( + )$ or minus $( - )$.\n\nFor example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions.On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task:\n\nGiven the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators.",
    "tutorial": "We can represent the arithmetic expression as a binary tree where: each leaf node is a digit. each non-leaf node is an operator and the left and right subtrees are the operands. To maximize the value of the sub-expression represented by a subtree rooted at $v$, we will either: put a plus (+) operator at $v$, and maximize the values of $left(v)$ and $right(v)$ subtrees, or put a minus (-) operator at $v$, and maximize the value of $left(v)$ subtree and minimize the value of $right(v)$ subtree. We can solve this task using DP keeping in mind the number of remaining operators of each type. The DP state will be ($v, rem^{ + }, rem^{ - }$). However, this state will not fit in time or memory limits. Since $min(P, M)  \\le  100$, we can drop the larger of the last two parameters and implicitly calculate it from the other parameter and the subtree size.",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "935",
    "index": "F",
    "title": "Fafa and Array",
    "statement": "Fafa has an array $A$ of $n$ positive integers, the function $f(A)$ is defined as $\\textstyle{\\sum_{i=1}^{n-1}|a_{i}-a_{i+1}|}$. He wants to do $q$ queries of two types:\n\n- $1 l r x$ — find the maximum possible value of $f(A)$, if $x$ is to be added to one element in the range $[l, r]$. You can choose to which element to add $x$.\n- $2 l r x$ — increase all the elements in the range $[l, r]$ by value $x$.\n\nNote that queries of type $1$ don't affect the array elements.",
    "tutorial": "Let's have a look at the relation of each element $a_{i}$ with its adjacent elements. Without loss of generality, assume $a_{i}$ has two adjacent elements $b_{i}$ and $c_{i}$ where $b_{i}  \\le  c_{i}$. One of the following cases will hold for $a_{i}$, $b_{i}$ and $c_{i}$: $a_{i}  \\ge  b_{i}$ and $a_{i}  \\ge  c_{i}$. $a_{i}  \\ge  b_{i}$ and $a_{i} < c_{i}$. $a_{i} < b_{i}$ and $a_{i} < c_{i}$. For a query $1 l r x$: if there exists an element $a_{i}$, where $i\\in[l,r]$, such that case $1$ holds, then it is the best element on which we can apply the add operation because it will increment $f(A)$ by $2 \\cdot x$. if case $1$ doesn't exist, then there is at most one element for which case $3$ holds (you can prove this by contradiction). Let's assume that this case holds for element $a_{i}$, where $i\\in[l,r]$. Then we will either: increment the element $a_{j}$ where $j\\in[L,r]$, $j  \\neq  i$ and $j = argmin_{k}{c_{k} - a_{k}}$. The value of $f(A)$ will be incremented by $2 \\cdot max(0, x - (c_{k} - a_{k}))$. increment the element $a_{i}$. The value of $f(A)$ will be incremented by $2 \\cdot max(0, x - (c_{i} - a_{i})) - 2 \\cdot min(b_{i} - a_{i}, x)$. if neither case $1$ nor case $3$ exists, then we can only the second option of the previous case. For a query $2 l r x$: the only affected elements will be $a_{l - 1}, a_{l}, a_{r}, a_{r + 1}$. We can use segment trees to answer queries in $O(logn)$ time. Complexity: $O(n+q\\cdot\\log n)$",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "936",
    "index": "A",
    "title": "Save Energy!",
    "statement": "Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after $k$ minutes after turning on.\n\nDuring cooking, Julia goes to the kitchen every $d$ minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.\n\nIt is known that the chicken needs $t$ minutes to be cooked on the stove, if it is turned on, and $2t$ minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.",
    "tutorial": "There are repeated segments in the cooking process, that are between two consecutive moments, when Julia turns the stove on. Let's call such segment a period. Consider two cases: If $k  \\le  d$, when Julia comes, the stove is always off, that means $period = d$. In other case Julia comes to the kitchen $p$ times between two turnings on, when the stove is still on, and does nothing. In this case $p$ is a number such that $p \\cdot d < k$ - the stove is on, $(p + 1) \\cdot d  \\ge  k$ - the stove is off. Then the period is $(p + 1) \\cdot d$ and $p$ is equal to $ \\lceil  k / d \\rceil  - 1$. So $period =  \\lceil  k / d \\rceil  \\cdot d$. If $carry > 2k$, chicken will be prepared after $carry - k$ minutes: $k$ minutes the stove will be on and $carry - 2k$ it will be off. Thus the answer is $num \\cdot period + carry - k$ Otherwise $carry$ parts become ready after $carry / 2$ minutes and answer is $num \\cdot period + carry / 2$.",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "936",
    "index": "B",
    "title": "Sleepy Game",
    "statement": "Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of $n$ vertices and $m$ edges. One of the vertices contains a chip. Initially the chip is located at vertex $s$. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for $10^{6}$ turns the draw is announced.\n\nVasya was performing big laboratory work in \"Spelling and parts of speech\" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves.\n\nYour task is to help Petya find out if he can win the game or at least draw a tie.",
    "tutorial": "Note that the answer is sequence of adjacent vertices of even length such that the last vertex of this sequence has no outgoing edges. Build state graph as follows: State is pair $(v, parity)$, where $v$ is vertex of initial graph and $parity$ is parity of count of vertices on path from $s$ to $v$. For every edge $uv$ of initial graph add edges $(u,0)\\rightarrow(v,1)$ and $(u,1)\\rightarrow(v,0)$ in state graph. So there exists path from $(s, 1)$ to $(v, parity)$ if and only if there exists path from $s$ to $v$ in initial graph of parity $parity$. Lets find all reachable from $(s, 1)$ states using BFS or DFS. If there is state $(v, 0)$ among them such that $v$ has no outgoing edges in initial graph, then Petya can win. He can move along vertices in path from $(s, 1)$ to $(v, 0)$ in state graph. Otherwise we need to check if Petya can make $10^{6}$ moves for drawing a tie. If there is a tie then the chip visited some vertex twice, because $n < 10^{6}$. Therefore it is sufficient to check if there is a cycle in initial graph reachable from $s$. In this case Petya can play as follows: move to any vertex of cycle and then move along the cycle as long as it requires to draw a tie.",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "936",
    "index": "C",
    "title": "Lock Puzzle",
    "statement": "Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!\n\nOf course, there is a code lock is installed on the safe. The lock has a screen that displays a string of $n$ lowercase Latin letters. Initially, the screen displays string $s$. Whitfield and Martin found out that the safe will open when string $t$ will be displayed on the screen.\n\nThe string on the screen can be changed using the operation «shift $x$». In order to apply this operation, explorers choose an integer $x$ from 0 to $n$ inclusive. After that, the current string $p = αβ$ changes to $β^{R}α$, where the length of $β$ is $x$, and the length of $α$ is $n - x$. In other words, the suffix of the length $x$ of string $p$ is reversed and moved to the beginning of the string. For example, after the operation «shift $4$» the string «abcacb» will be changed with string «bcacab », since $α = $ab, $β = $cacb, $β^{R} = $bcac.\n\nExplorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string $t$ on the screen, using no more than $6100$ operations.",
    "tutorial": "The answer is <<NO>> only in the case when multisets of letters in $s$ and $t$ differ. In all other cases there is a solution. Let's construct the solution uses $\\textstyle{\\frac{5}{2}}n$ operations. To do that, you need to <<add>> two symbols to current already built substring using five operations. You can do it, for example, using the following method (the underlined string is chosen as $ \\beta $): ...x...abc $\\to$ cba......x cba......x $\\to$ x......abc x......abc $\\to$ cbax...... cbax...y.. $\\to$ ..ycbax... ..ycbax... $\\to$ .....ycbax If we had abc as suffix, after these operations, we get ycbax, which is two symbols longer. Choosing x and y accordingly, we can maintain maintain the invariant, that the suffix of current string always contains monotone (increasing or decreasing) sequence. After we make this sequence have length $n$, the entire string is either a cyclic shift or a reversed cyclic shift of $t$. You can do cyclic shift by $k$ in three operations: <<shift $n - k$>>, <<shift $k$>>, <<shift $n$>>. This way, we get a ${\\textstyle{\\frac{5}{2}}}n+O(1)$ solution.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "936",
    "index": "D",
    "title": "World of Tank",
    "statement": "Vitya loves programming and problem solving, but sometimes, to distract himself a little, he plays computer games. Once he found a new interesting game about tanks, and he liked it so much that he went through almost all levels in one day. Remained only the last level, which was too tricky. Then Vitya remembered that he is a programmer, and wrote a program that helped him to pass this difficult level. Try do the same.\n\nThe game is organized as follows. There is a long road, two cells wide and $n$ cells long. Some cells have obstacles. You control a tank that occupies one cell. Initially, the tank is located before the start of the road, in a cell with coordinates $(0, 1)$. Your task is to move the tank to the end of the road, to the cell $(n + 1, 1)$ or $(n + 1, 2)$.\n\nEvery second the tank moves one cell to the right: the coordinate $x$ is increased by one. When you press the up or down arrow keys, the tank instantly changes the lane, that is, the $y$ coordinate. When you press the spacebar, the tank shoots, and the nearest obstacle along the lane in which the tank rides is instantly destroyed. In order to load a gun, the tank needs $t$ seconds. Initially, the gun is not loaded, that means, the first shot can be made only after $t$ seconds after the tank starts to move.\n\nIf at some point the tank is in the same cell with an obstacle not yet destroyed, it burns out. If you press the arrow exactly at the moment when the tank moves forward, the tank will first move forward, and then change the lane, so it will not be possible to move diagonally.\n\nYour task is to find out whether it is possible to pass the level, and if possible, to find the order of actions the player need to make.",
    "tutorial": "At first arrange a pair of facts: If there is a path which doesn't contain blowed cell you can easily convert it to path which does. So it's enough to check such paths to determine answer. Tank can accumulate shots when it moves without turns. In other words: consider tank makes 100 steps without turns and shots, so lets say that tank accumulate 100 steps. If $t$ equals to 3 tank was able to make 33 shots on that part of path. Accumulating steps is the same as deferred shots. Tank gains steps and when it's necessary to make some shots we can choose position of shots on this straight part of path in such way that tank blows obstacles. But when the tank changes its row you should flush accumulated steps to minimum of $t$ and old value because accumulated steps has sense only on hte straight line without shots because otherwise it may be impossible to choose correct positions for shots. The second step is solution with asymptotics $O(n)$: Using dynamic programming: $dp[i][j]$ - maximal number of accumulated step if tank is in cell with coordinates $(i, j)$ and -1 if it's impossible. You should update dynamic's values from previous cell in the same row or cell in another row but in the same column. Check that $dp[i][j - 1]  \\neq  - 1$ (otherwise tank can't be in the $(i, j - 1)$ cell) after that update value by $dp[i][j - 1] + 1$ if there is no obstacle in cell $(i, j)$ and by $dp[i][j - 1] - t + 1$ otherwise. Before updating by cell in another row you should update both of them ($(1, j)$ and $(2, j)$ if rows numerated from 1) by cells in previous column and only after that you can update them be each other. Store for each cell $(i, j)$ was it updated from $(3 - i, j)$ or $(i, j - 1)$. Start from last column and iterate to the zero one to restore the path. When you restore path you can easily calculate number of obstacles which should be blowed for each part of path without shots. So now you have to choose places for them. Consider any part of the path from any turn to the next one. Let there are $s$ obstacles, so all of them must be destroyed by the tank. Let the first cell of this path's part has coordinates $(i, j)$ and $dp[i][j]$ equal to $k$, so the first shot on this part can be not earlier than $(i, j + t - k)$, the next one not earlier than $(i, j + 2t - k)$ and so on. Place shots in that position and tank will correctly blow up all obstacles. It obviously follows from dynamic programming's definition. Complexity: $O(n)$. The third step is prooving that tank can turn only to cells which are immediately after an obstacle (if obstacle is in cell with coordinates $(i, j)$ then tank turns to cell $(i, j + 1)$). Consider any path which is one of soloutions. Consider the first turn in this path which doesn't fit the constraint above. Then consider the nearest obstacle in the same row as row where tank will be after turn, but with smaller number of a column. If tank turns to the cell which immediately after that obstacle then it can move along that row to current position, eliminates unnecessary turns, so the considered turn will be eliminated. Otherwise tank was in another row, so you can easily turn and do the same actions to eliminate such turn. Repeat this actions you transform any path to path which has only turns to cells immediately after obstacles. Sort obstacles in order of increasing their column's number. So due to fact that tank can turn only in certain points it isn't necessary calculates DP for all $2 \\cdot n$ cells. Now $m_{1} + m_{2}$ cells enough. So calculate the same DP for cells which are immediatel after obstacles, strore for each point the point where it was updated from to restore path. Restore path and for each part without turns calculate number of obstacles to destroy and place shots. Complexity $O(m_{1} + m_{2})$.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "936",
    "index": "E",
    "title": "Iqea",
    "statement": "Gridland is placed on infinite grid and has a shape of figure consisting of cells. Every cell of Gridland is a city. Two cities that are placed in adjacent cells are connected by the road of length $1$. It's possible to get from any city to any other city using roads. The \\underline{distance} between two cities is the minimum total road length on path from one city to another. It's possible to get from any cell that doesn't belong to Gridland to any other cell that doesn't belong to Gridland by using only cells which don't belong to Gridland. In other words, Gridland is connected and complement of Gridland is also connected.\n\nAt the moment no city in Gridland has Iqea famous shop. But Iqea has great plans for building shops in Gridland. For customers' convenience Iqea decided to develop an application. Using this application everyone can learn the distance to the nearest Iqea. You are to develop this application.\n\nYou are asked to process two types of queries:\n\n- new Iqea shop has been opened in the city with coordinates $(x, y)$;\n- customer wants to know the distance to the nearest already opened Iqea shop from his city located in a cell with coordinates $(x, y)$.\n\nPay attention that customer can move only by roads and can never leave Gridland on his way to the shop.",
    "tutorial": "Let's cut the figure into strips of consecutive cells which lie in the same column. Consider strips as vertices. Connect two vertices by an edge if their strips have common edge. It can be proved that resulting graph is a tree. Consider two cells (x_a, y_a) and (x_b, y_b). Cell (x_a, y_a) lies on strip v_a, cell (x_b, y_b) lies on strip v_b. Then any shortest path between these two cells goes only through strips corresponding to vertices on path from v_a to v_b. And every such strip has non-empty intersection with path between this two cells. So if we build centroid decomposition of tree of strips, shortest path between two cells will surely go through strip of centroid which divide vertices of these two cells. Thus, you can solve standard problem on tree: sometimes vertices are turning on, and you are to find the distance to the nearest vertex that is turned on. To solve this problem you can use centroid decomposition. Only one question left. How to combine distances from centroid to two cells? Consider two cells (x_a, y_a) and (x_b, y_b), and path between them. Let this path goes through strip v_c. Let d_a be a distance from (x_a, y_a) to the strip v_c, z_a be a y coordinate of nearest cell on strip v_c. The same way define d_b and z_b for cell (x_b, y_b). Then the distance between (x_a, y_a) and (x_b, y_b) equals to d_a + d_b + |z_a - z_b|. So we can store h values in every vertex and change them in the following way: val_i = \\min(val_i, d_a + |z_i - z_a|), h is the size of strip, z_i is the y coordinate of i-th cell on strip. This can be done using segment tree. Example of building a tree. Blue and yellow colors mark cells (x_a, y_a) and (x_b, y_b). Green color marks strip v_c. The values are: d_a = 6, d_b = 7, z_a = 8, z_b = 5. I honestly don't know if this is the picture originally drawn for this tutorial. The original picture in Metapost doesn't compile, and I asked ChatGPT to redraw it for me... Values d_a and z_a for every pair cell and vertex can be calculated during building of centroid decomposition. Complexity of the solution is O(n\\cdot log(n) + q\\cdot log^2(n)) time and O(n\\cdot log(n)) memory.",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "shortest paths",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "937",
    "index": "A",
    "title": "Olympiad",
    "statement": "The recent All-Berland Olympiad in Informatics featured $n$ participants with each scoring a certain amount of points.\n\nAs the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:\n\n- At least one participant should get a diploma.\n- None of those with score equal to zero should get awarded.\n- When someone is awarded, all participants with score \\textbf{not less} than his score should also be awarded.\n\nDetermine the number of ways to choose a subset of participants that will receive the diplomas.",
    "tutorial": "Drop all participants with zero points. Then the answer is simply the number of distinct points among the remaining participants.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "937",
    "index": "B",
    "title": "Vile Grasshoppers",
    "statement": "The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.\n\nThe pine's trunk includes several branches, located one above another and numbered from $2$ to $y$. Some of them (more precise, from $2$ to $p$) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch $x$ can jump to branches $2\\cdot x\\,,\\,>\\,\\cdot\\,x\\,,\\,\\ \\,\\left\\lfloor{\\frac{y}{x}}\\right\\rfloor\\cdot\\,x$.\n\nKeeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.\n\nIn other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.",
    "tutorial": "The first observation is that the optimal branch shouldn't be divisible by anything in range $[2..p]$. Let us decrease $y$ until its minimal divisor (other than one) is greater than $p$. Why does this approach work? Note that the the nearest prime less or equal to $y$ is valid. At the same time the prime gap of numbers less than billion doesn't exceed $300$ and we're gonna factorize no more than $300$ numbers in total. Therefore the complexity is $300\\cdot{\\sqrt{10^{9}}}$.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "938",
    "index": "A",
    "title": "Word Correction",
    "statement": "Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.\n\nVictor thinks that if a word contains two \\textbf{consecutive} vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is \\textbf{another vowel right before it}. If there are no two consecutive vowels in the word, it is considered to be correct.\n\nYou are given a word $s$. Can you predict what will it become after correction?\n\n\\textbf{In this problem letters a, e, i, o, u and y are considered to be vowels}.",
    "tutorial": "Iterate over the string, output only consonants and vowels which don't have a vowel before them.",
    "code": "\"#include<bits/stdc++.h>\\n\\nusing namespace std;\\n\\nconst string V = \\\"aeiouy\\\";\\n\\nbool vowel(char c)\\n{\\n\\treturn V.find(c) != -1;\\n}\\n\\nint main()\\n{\\n\\tint n;\\n\\tcin >> n;\\n\\tstring s;\\n\\tcin >> s;\\n\\tcout << s[0];\\n\\tfor(int i = 1; i < n; i++)\\n\\t\\tif (!vowel(s[i - 1]) || !vowel(s[i]))\\n\\t\\t\\tcout << s[i];\\n\\tcout << endl;\\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "938",
    "index": "B",
    "title": "Run For Your Prize",
    "statement": "You and your friend are participating in a TV show \"Run For Your Prize\".\n\nAt the start of the show $n$ prizes are located on a straight line. $i$-th prize is located at position $a_{i}$. Positions of all prizes are distinct. You start at position $1$, your friend — at position $10^{6}$ (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.\n\nYou know that it takes exactly $1$ second to move from position $x$ to position $x + 1$ or $x - 1$, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.\n\nNow you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.\n\nWhat is the minimum number of seconds it will take to pick up all the prizes?",
    "tutorial": "You can find the total time with the knowledge of the prefix length. The final formula is $\\operatorname*{min}(a_{n}-1,10^{6}-a_{1},\\operatorname*{min}_{i=1}^{n-1}(\\operatorname*{max}(a_{i}-1,10^{6}-a_{i+1})))$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n\\nusing namespace std;\\n\\nconst int INF = 1e7;\\n\\nint n;\\nvector<int> pos;\\n\\nint main() {\\n\\tscanf(\\\"%d\\\", &n);\\n\\tpos.resize(n);\\n\\tforn(i, n)\\n\\t\\tscanf(\\\"%d\\\", &pos[i]);\\n\\t\\n\\tint ans = INF;\\n\\t\\n\\tforn(i, n + 1){\\n\\t\\tint cur = 0;\\n\\t\\tif (i) cur = max(cur, pos[i - 1] - 1);\\n\\t\\tif (i != n) cur = max(cur, 1000000 - pos[i]);\\n\\t\\t\\n\\t\\tans = min(ans, cur);\\n\\t}\\n\\t\\n\\tprintf(\\\"%d\\\\n\\\", ans);\\n}\"",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "938",
    "index": "C",
    "title": "Constructing Tests",
    "statement": "Let's denote a $m$-free matrix as a binary (that is, consisting of only $1$'s and $0$'s) matrix such that every square submatrix of size $m × m$ of this matrix contains at least one zero.\n\nConsider the following problem:\n\n{You are given two integers $n$ and $m$. You have to construct an $m$-free square matrix of size $n × n$ such that \\textbf{the number of $1$'s in this matrix is maximum possible}. Print the maximum possible number of $1$'s in such matrix.}\n\nYou don't have to solve this problem. Instead, you have to construct a few tests for it.\n\nYou will be given $t$ numbers $x_{1}$, $x_{2}$, ..., $x_{t}$. For every $i\\in[1,t]$, find two integers $n_{i}$ and $m_{i}$ ($n_{i} ≥ m_{i}$) such that the answer for the aforementioned problem is exactly $x_{i}$ if we set $n = n_{i}$ and $m = m_{i}$.",
    "tutorial": "Now that you know the formula, you can iterate over $n$ and find the correct value. The lowest non-zero value you can get for some $n$ is having $k = 2$. So you can estimate $n$ as about $\\frac{4{\\sqrt{x}}}{3}$. Now let's get $k$ for some fixed $n$. $n^{2}-\\lfloor{\\frac{n}{k}}\\rfloor^{2}=x$ $\\to$ $\\lfloor{\\frac{n}{k}}\\rfloor^{2}=n^{2}-x$ $\\to$ $\\lfloor{\\frac{n}{k}}\\rfloor)={\\sqrt{n^{2}-x}}$ $\\to$ $k={\\frac{n}{\\sqrt{n^{2}-x}}}$. Due to rounding down, it's enough to check only this value of $k$.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n\\nusing namespace std;\\n\\nint getSqr(int x){\\n\\tint l = sqrt(x);\\n\\tfor (int i = -2; i <= 2; ++i)\\n\\t\\tif (l + i >= 0 && (l + i) * (l + i) == x)\\n\\t\\t\\treturn l;\\n\\treturn -1;\\n}\\n\\nvoid solve(){\\n    int x;\\n\\tscanf(\\\"%d\\\", &x);\\n\\tfor (int n = 1; n == 1 || n * n - (n / 2) * (n / 2) <= x; ++n){\\n\\t\\tint lk = n * n - x;\\n\\t\\tif (lk < 0) continue;\\n\\t\\tint sq = getSqr(lk);\\n\\t\\tif (sq <= 0) continue;\\n\\t\\t\\n\\t\\tint k = n / sq;\\n\\t\\tif (k > 0 && n * n - (n / k) * (n / k) == x){\\n\\t\\t\\tprintf(\\\"%d %d\\\\n\\\", n, k);\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\t}\\n\\t\\n\\tputs(\\\"-1\\\");\\n}\\n\\nint main() {\\n    int tc;\\n    scanf(\\\"%d\\\", &tc);\\n\\tforn(i, tc)\\n\\t    solve();\\n}\"",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1700
  },
  {
    "contest_id": "938",
    "index": "D",
    "title": "Buy a Ticket",
    "statement": "Musicians of a popular band \"Flayer\" have announced that they are going to \"make their exit\" with a world tour. Of course, they will visit Berland as well.\n\nThere are $n$ cities in Berland. People can travel between cities using two-directional train routes; there are exactly $m$ routes, $i$-th route can be used to go from city $v_{i}$ to city $u_{i}$ (and from $u_{i}$ to $v_{i}$), and it costs $w_{i}$ coins to use this route.\n\nEach city will be visited by \"Flayer\", and the cost of the concert ticket in $i$-th city is $a_{i}$ coins.\n\nYou have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city $i$ you have to compute the minimum number of coins a person from city $i$ has to spend to travel to some city $j$ (or possibly stay in city $i$), attend a concert there, and return to city $i$ (if $j ≠ i$).\n\nFormally, for every $i\\in[1,n]$ you have to calculate $\\operatorname*{min}_{j=1}^{n}2d(i,j)+a_{j}$, where $d(i, j)$ is the minimum number of coins you have to spend to travel from city $i$ to city $j$. If there is no way to reach city $j$ from city $i$, then we consider $d(i, j)$ to be infinitely large.",
    "tutorial": "The function of the path length is not that different from the usual one. You can multiply edge weights by two and run Dijkstra in the following manner. Set $dist_{i} = a_{i}$ for all $i\\in[1,n]$ and push these values to heap. When finished, $dist_{i}$ will be equal to the shortest path.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define forn(i, n) for (int i = 0; i < int(n); i++)\\n\\nusing namespace std;\\n\\ntypedef long long li;\\n\\nconst int N = 200 * 1000 + 13;\\nconst li INF64 = 1e18;\\n\\nint n, m;\\nli a[N];\\nvector<pair<int, li>> g[N];\\n\\nli dist[N];\\n\\nvoid Dijkstra(){\\n\\tset<pair<li, int>> q;\\n\\tforn(i, n){\\n\\t\\tdist[i] = a[i];\\n\\t\\tq.insert({dist[i], i});\\n\\t}\\n\\t\\n\\twhile (!q.empty()){\\n\\t\\tint v = q.begin()->second;\\n\\t\\tq.erase(q.begin());\\n\\t\\t\\n\\t\\tfor (auto it : g[v]){\\n\\t\\t\\tint u = it.first;\\n\\t\\t\\tli w = it.second;\\n\\t\\t\\t\\n\\t\\t\\tif (dist[u] > dist[v] + w){\\n\\t\\t\\t\\tq.erase({dist[u], u});\\n\\t\\t\\t\\tdist[u] = dist[v] + w;\\n\\t\\t\\t\\tq.insert({dist[u], u});\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\\n\\nint main() {\\n\\tscanf(\\\"%d%d\\\", &n, &m);\\n\\tforn(_, m){\\n\\t\\tint f, t;\\n\\t\\tli w;\\n\\t\\tscanf(\\\"%d%d%lld\\\", &f, &t, &w);\\n\\t\\t--f, --t;\\n\\t\\tw *= 2;\\n\\t\\tg[f].push_back({t, w});\\n\\t\\tg[t].push_back({f, w});\\n\\t}\\n\\tforn(i, n){\\n\\t\\tscanf(\\\"%lld\\\", &a[i]);\\n\\t}\\n\\t\\n\\tDijkstra();\\n\\tforn(i, n)\\n\\t\\tprintf(\\\"%lld \\\", dist[i]);\\n\\tputs(\\\"\\\");\\n\\treturn 0;\\n}\"",
    "tags": [
      "data structures",
      "graphs",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "938",
    "index": "E",
    "title": "Max History",
    "statement": "You are given an array $a$ of length $n$. We define $f_{a}$ the following way:\n\n- Initially $f_{a} = 0$, $M = 1$;\n- for every $2 ≤ i ≤ n$ if $a_{M} < a_{i}$ then we set $f_{a} = f_{a} + a_{M}$ and then set $M = i$.\n\nCalculate the sum of $f_{a}$ over all $n!$ permutations of the array $a$ modulo $10^{9} + 7$.\n\nNote: two elements are considered different if their indices differ, so for every array $a$ there are exactly $n!$ permutations.",
    "tutorial": "It is easy to see that $i$-th element appears in $f_{a}$ if and only if all elements appearing before it in the array are less than it, so if we define $l_{i}$ as the number of elements less than $a_{i}$ the answer will be equal to: $\\textstyle\\sum_{i=1}^{n}a_{i}\\times[\\sum_{i=1}^{l_{i}+1}{\\binom{l_{i}}{j_{-1}}}\\times(j-1)!\\times(n-j)!]$By determining the index of $a_{i}$, if it is on the index $j$ then we have to choose $j - 1$ of the $l_{i}$ elements smaller than it and then permuting them and then permuting the other elements. We can find all $l_{i}$ with complexity of $O(n log n)$. If we were to implement this, the complexity would equal to $O(n^{2})$. Now let's make our formula better. So let's open it like so: $\\textstyle{\\sum_{i=1}^{n}a_{i}\\times[\\sum_{j=1}^{l_{i+1}}{\\frac{l_{i}!}{(j-1)!\\times(l_{i-};+1)!}}\\times(j-1)!\\times(n-j)!]}$and then it equals to: $\\sum_{i=1}^{n}a_{i}\\times\\ [\\sum_{j=1}^{l_{i}+1}\\,\\frac{l_{i}!}{(l_{i-i+1})!}\\,\\times\\,\\left(m-j\\right)!\\right]$and now let's take out the $l_{i}!$ , $\\textstyle{\\sum_{i=1}^{n}a_{i}\\times\\,l_{i}!\\times\\left[\\sum_{j=1}^{l_{i}+1}{\\frac{(n-j)!}{(l_{i}-j+1)!}}\\right]}$now let's multiply the inside the first sigma by $\\frac{1}{(n-l_{i}-1)!}$ and the second sigma by $(n - l_{i} - 1)!$ and it gets equal to: $\\textstyle\\sum_{i=1}^{n}a_{i}\\times l_{i}!\\times(n-l_{i}-1)!\\times[\\sum_{j=1}^{l_{i+1}}{\\frac{(n-j)!}{(n-l_{i}-1)!\\times(l_{i}-j+1)!}}]$and it is easy to see it equals to: $\\textstyle\\sum_{i=1}^{n}a_{i}\\times l_{i}!\\times(n-l_{i}-1)!\\times[\\sum_{j=1}^{l_{i+1}}{\\binom{n-j}{n-l_{i}-1}}]$and using the fact that $\\ {(_{k}^{k})}\\,+\\,{\\binom{k+1}{k}}\\,+\\,\\cdot\\,\\cdot\\,\\cdot\\,\\cdot\\,\\cdot\\,\\cdot\\,\\quad+\\,{\\binom{n}{k+1}}\\qquad(k\\leq n)$it will equal to: $\\textstyle\\sum_{i=1}^{n}a_{i}\\times l_{i}!\\times(n-l_{i}-1)!\\times(\\O_{n-l})$So the final answer will equal to: $\\sum_{i=1}^{n}{\\frac{a_{i}\\times n!}{n-l!}}$of which can be easily implemented in $O(n log n)$. Make sure to not add the answer for maximum number in the sequence.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\ntypedef long long ll;\\nconst int MAX_N = 1e6+10;\\nconst int mod = 1e9+7;\\n\\nll a[MAX_N],n,fact[MAX_N],rfact[MAX_N];\\nll num(int t){\\n    return fact[n-t-1]*rfact[n-t+1]%mod;\\n}\\nmain(){\\n    scanf(\\\"%lld\\\", &n);\\n    for(ll i=1;i<=n;i++)\\n        scanf(\\\"%lld\\\", &a[i]);\\n    fact[0]=rfact[n+1]=1;\\n    for(int i=1;i<=n+1;i++)\\n        fact[i]=(fact[i-1]*i)%mod;\\n    for(int i=n;i>=1;i--)\\n        rfact[i]=(rfact[i+1]*i)%mod;\\n    sort(a+1,a+n+1);\\n    ll cnt=0,curr=0,ans=0;\\n    for(ll i=1;i<=n&&a[i]!=a[n];i++){\\n        if(a[i]==a[i-1])\\n            cnt++;\\n        else\\n            curr+=cnt,cnt=1;\\n        ans=(ans+num(curr)*a[i]%mod)%mod;\\n    }\\n    printf(\\\"%d\\\",ans);\\n}\"",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "938",
    "index": "F",
    "title": "Erasing Substrings",
    "statement": "You are given a string $s$, initially consisting of $n$ lowercase Latin letters. After that, you perform $k$ operations with it, where $k=\\lfloor\\log_{2}(n)\\rfloor$. During $i$-th operation you \\textbf{must} erase some substring of length exactly $2^{i - 1}$ from $s$.\n\nPrint the lexicographically minimal string you may obtain after performing $k$ such operations.",
    "tutorial": "Let's try to apply some greedy observations. Since each state represents a possible prefix of the resulting string, then among two states $dp[m_{1}][mask_{1}]$ and $dp[m_{2}][mask_{2}]$ such that the lenghts of corresponding prefixes are equal, but the best answers for states are not equal, we don't have to consider the state with lexicographically greater answer. So actually for every length of prefix there exists only one best prefix we will get, and we may store a boolean in each state instead of a string. The boolean will denote if it is possible to get to corresponding state with minimum possible prefix. To calculate this, we iterate on the lengths of prefixes of the resulting string. When we fix the length of prefix, we firstly consider dynamic programming transitions that denote deleting a substring (since they don't add any character). Then among all states $dp[m][mask]$ that allow us to reach some fixed length of prefix and have $dp[m][mask] = true$ we pick the best character we can use to proceed to next prefix (and for a fixed state that's actually $(m + 1)$-th character of the string). This is $O(n^{2}\\log{n})$, but in fact it's pretty fast.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nconst int N = 5043;\\nconst int M = 12;\\n\\nbool dp[N][(1 << M)];\\n\\ntypedef pair<int, int> pt;\\n\\n#define x first\\n#define y second\\n\\nvector<int> bits[(1 << M)];\\n\\nint main()\\n{\\n\\tstring s;\\n\\tcin >> s;\\n\\tint n = s.size();\\n\\tstring ans;\\n\\tdp[0][0] = 1;\\n\\tvector<pt> cur;\\n\\tcur.push_back(make_pair(0, 0));\\n\\tint final_sz = n;\\n\\tint cur_len = 1;\\n\\tint cnt = 0;\\n\\twhile((1 << cnt) < n)\\n\\t\\tcnt++;\\n\\tcnt--;\\n\\t\\n\\tfor(int i = 0; i < (1 << cnt); i++)\\n\\t\\tfor(int j = 0; j < cnt; j++)\\n\\t\\t\\tif ((i & (1 << j)) == 0)\\n\\t\\t\\t\\tbits[i].push_back(j);\\n\\twhile(final_sz > cur_len)\\n\\t{\\n\\t\\tfinal_sz -= cur_len;\\n\\t\\tcur_len *= 2;\\n\\t}\\n\\twhile(ans.size() < final_sz)\\n\\t{\\n\\t\\tchar min_chr = 'z';\\n\\t\\tfor(int i = 0; i < cur.size(); i++)\\n\\t\\t{\\n\\t\\t\\tauto x = cur[i];\\n\\t\\t\\tfor(auto y : bits[x.y])\\n\\t\\t\\t{\\n\\t\\t\\t\\tif (dp[x.x + (1 << y)][x.y ^ (1 << y)] == 0)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tcur.push_back(make_pair(x.x + (1 << y), x.y ^ (1 << y)));\\n\\t\\t\\t\\t\\tdp[x.x + (1 << y)][x.y ^ (1 << y)] = 1;\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\t\\n\\t\\t\\tmin_chr = min(min_chr, s[x.x]);\\n\\t\\t}\\n\\t\\tvector<pt> new_cur;\\n\\t\\tans.push_back(min_chr);\\n\\t\\tfor(auto x : cur)\\n\\t\\t\\tif (s[x.x] == min_chr)\\n\\t\\t\\t{\\n\\t\\t\\t\\tdp[x.x + 1][x.y] = 1;\\n\\t\\t\\t\\tnew_cur.push_back(make_pair(x.x + 1, x.y));\\n\\t\\t\\t}\\n\\t\\tcur = new_cur;\\n\\t}\\n\\tcout << ans << endl;\\n}\"",
    "tags": [
      "bitmasks",
      "dp",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "938",
    "index": "G",
    "title": "Shortest Path Queries",
    "statement": "You are given an undirected connected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times).\n\nThere are three types of queries you have to process:\n\n- $1$ $x$ $y$ $d$ — add an edge connecting vertex $x$ to vertex $y$ with weight $d$. It is guaranteed that there is no edge connecting $x$ to $y$ before this query;\n- $2$ $x$ $y$ — remove an edge connecting vertex $x$ to vertex $y$. It is guaranteed that there was such edge in the graph, and the graph stays connected after this query;\n- $3$ $x$ $y$ — calculate the length of the shortest path (possibly non-simple) from vertex $x$ to vertex $y$.\n\nPrint the answers for all queries of type $3$.",
    "tutorial": "This is a more complex version of problem G from Educational Round 27. You can find its editorial here. To solve the problem we consider now, you have to use a technique known as dynamic connectivity. Let's build a segment tree over queries: each vertex of the segment tree will contain a list of all edges existing in the graph on the corresponding segment of queries. If some edge exists from query $l$ to query $r$, then it's like an addition operation on segment $[l, r]$ in segment tree (but instead of addition, we insert this edge into the list of edges on a segment, and we make no pushes). Then if we write some data structure that will allow to add an edge and rollback operations we applied to the structure, then we will be able to solve the problem by DFS on segment tree: when we enter a vertex, we add all edges in the list of this vertex; when we are in a leaf, we calculate the required answer for the corresponding moment of time; and when we leave a vertex, we rollback all changes we made there. What data structure do we need? Firstly, we will have to use DSU maintaining the distance to the leader (to maintain the length of some path between two vertices). Don't use path compression, this won't work well since we have to do rollbacks. Secondly, we have to maintain the base of all cycles in the graph (since the graph is always connected, it doesn't matter that some cycles may be unreachable: by the time we get to leaves of the segment tree, these cycles will become reachable, so there's no need to store a separate base for each component). A convenient way to store the base is to make an array of $30$ elements, initially filled with zeroes (we denote this array as $a$). $i$-th element of the array will denote some number in a base such that $i$-th bit is largest in the number. Adding some number $x$ to this base is really easy: we iterate on bits from $29$-th to $0$-th, and if some bit $j$ is equal to $1$ in $x$, and $a[j]  \\neq  0$, then we just set $x:=x\\oplus a[j]$ (let's call this process reduction, we will need it later). If we get $0$ after doing these operations, then the number we tried to add won't affect the base, and we don't need to do anything; otherwise, let $k$ be the highmost bit equal to $1$ in $x$, and then we set $a[k]: = x$. This method of handling the base of cycles also allows us to answer queries of type $3$ easily: firstly, we pick the length of some path from DSU (let it be $p$), and secondly, we just apply reduction to $p$, and this will be our answer.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef pair<pair<int, int>, int> edge;\\n\\n#define x first\\n#define y second\\n\\nconst int M = 2000043;\\nconst int N = 200043;\\nconst int B = 30;\\nconst int IDX = 200002;\\n\\nint* where[M];\\nint val[M];\\nint st = 0;\\n\\ninline void rollback(int new_st)\\n{\\n\\twhile(st != new_st)\\n\\t{\\n\\t\\tst--;\\n\\t\\t(*where[st]) = val[st];\\n\\t}\\n}\\n\\ninline void change(int& address, int new_val)\\n{\\n\\twhere[st] = &address;\\n\\tval[st] = address;\\n\\tst++;\\n\\taddress = new_val;\\n}\\n\\nvector<edge> T[4 * N];\\nvector<edge> Q[4 * N];\\nint ans[N];\\n\\nvoid add_edge(int v, int l, int r, int L, int R, edge e)\\n{\\n\\tif (L >= R)\\n\\t\\treturn;\\n\\tif (l == L && r == R)\\n\\t{\\n\\t\\tT[v].push_back(e);\\n\\t\\treturn;\\n\\t}\\n\\tint mid = (l + r) >> 1;\\n\\tadd_edge(v * 2 + 1, l, mid, L, min(mid, R), e);\\n\\tadd_edge(v * 2 + 2, mid, r, max(L, mid), R, e);\\n}\\n\\nint base[B];\\n\\ninline void try_gauss(int v)\\n{\\n\\tfor(int i = 29; i >= 0; i--)\\n\\t\\tif (base[i] != -1 && (v & (1 << i)))\\n\\t\\t\\tv ^= base[i];\\n\\tif (v != 0)\\n\\t\\tfor(int i = 29; i >= 0; i--)\\n\\t\\t\\tif (v & (1 << i))\\n\\t\\t\\t\\treturn change(base[i], v);\\n}\\n\\nint rnk[N];\\nint dsu[N];\\nint dist[N];\\n\\ninline int get_p(int x)\\n{\\t\\n\\twhile(dsu[x] != x)\\n\\t\\tx = dsu[x];\\n\\treturn x;\\n}\\n\\ninline int get_dist(int x)\\n{\\n\\tint res = 0;\\n\\twhile(dsu[x] != x)\\n\\t{\\n\\t\\tres ^= dist[x];\\n\\t\\tx = dsu[x];\\n\\t}\\n\\treturn res;\\n}\\n\\ninline bool merge(int x, int y, int d)\\n{\\n\\tint dist_x = get_dist(x);\\n\\tint dist_y = get_dist(y);\\n\\tx = get_p(x);\\n\\ty = get_p(y);\\n\\tif (x == y)\\n\\t\\treturn false;\\n\\td ^= (dist_x ^ dist_y);\\n\\tif (rnk[x] < rnk[y])\\n\\t\\tswap(x, y);\\n\\tchange(dsu[y], x);\\n\\tchange(rnk[x], rnk[x] + rnk[y]);\\n\\tchange(dist[y], d);\\n\\treturn true;\\n}\\n\\ninline void process(int v)\\n{\\n\\tfor(auto x : T[v])\\n\\t\\tif (!merge(x.x.x, x.x.y, x.y))\\n\\t\\t{\\n\\t\\t\\tint cycle_len = x.y ^ get_dist(x.x.x) ^ get_dist(x.x.y);\\n\\t\\t\\ttry_gauss(cycle_len);\\n\\t\\t}\\n}\\n\\ninline int answer(int x, int y)\\n{\\n\\tint d = get_dist(x) ^ get_dist(y);\\n\\tfor(int i = 29; i >= 0; i--)\\n\\t\\tif (base[i] != -1 && (d & (1 << i)))\\n\\t\\t\\td ^= base[i];\\n\\treturn d;\\n}\\n\\nvoid dfs(int v, int l, int r)\\n{\\n\\tint rollback_to = st;\\n\\tprocess(v);\\n\\tif (l == r - 1)\\n\\t{\\n\\t\\tfor(auto x : Q[v])\\n\\t\\t\\tans[x.y] = answer(x.x.x, x.x.y);\\n\\t}\\n\\telse\\n\\t{\\n\\t\\tint mid = (l + r) >> 1;\\n\\t\\tdfs(v * 2 + 1, l, mid);\\n\\t\\tdfs(v * 2 + 2, mid, r);\\t\\t\\n\\t}\\n\\trollback(rollback_to);\\n}\\n\\nvoid add_query(int v, int l, int r, int pos, edge e)\\n{\\n\\tif (l == r - 1)\\n\\t\\tQ[v].push_back(e);\\n\\telse\\n\\t{\\n\\t\\tint mid = (l + r) >> 1;\\n\\t\\tif (pos < mid)\\n\\t\\t\\tadd_query(v * 2 + 1, l, mid, pos, e);\\n\\t\\telse\\n\\t\\t\\tadd_query(v * 2 + 2, mid, r, pos, e);\\n\\t}\\n}\\n\\nint main() {\\n\\tint n, m;\\n\\tscanf(\\\"%d %d\\\", &n, &m);\\n\\tfor(int i = 0; i < n; i++)\\n\\t{\\n\\t\\tdsu[i] = i;\\n\\t\\tdist[i] = 0;\\n\\t\\trnk[i] = 1;\\n\\t}\\n\\tint cur = 0;\\n\\tmap<pair<int, int>, pair<int, int> > z;\\n\\tfor(int i = 0; i < m; i++)\\n\\t{\\n\\t\\tint x, y, d;\\n\\t\\tscanf(\\\"%d %d %d\\\", &x, &y, &d);\\n\\t\\t--x;\\n\\t\\t--y;\\n\\t\\tz[make_pair(x, y)] = make_pair(0, d);\\n\\t}\\n\\tint cnt_q = 0;\\n\\tint q;\\n\\tscanf(\\\"%d\\\", &q);\\n\\tfor(int i = 0; i < q; i++)\\n\\t{\\n\\t\\tint t;\\n\\t\\tscanf(\\\"%d\\\", &t);\\n\\t\\tif (t == 1)\\n\\t\\t{\\n\\t\\t\\tint x, y, d;\\n\\t\\t\\tscanf(\\\"%d %d %d\\\", &x, &y, &d);\\n\\t\\t\\tcur++;\\n\\t\\t\\t--x;\\n\\t\\t\\t--y;\\n\\t\\t\\tz[make_pair(x, y)] = make_pair(cur, d);\\n\\t\\t}\\n\\t\\tif (t == 2)\\n\\t\\t{\\n\\t\\t\\tint x, y;\\n\\t\\t\\tscanf(\\\"%d %d\\\", &x, &y);\\n\\t\\t\\t--x;\\n\\t\\t\\t--y;\\n\\t\\t\\tcur++;\\n\\t\\t\\tadd_edge(0, 0, IDX, z[make_pair(x, y)].x, cur, make_pair(make_pair(x, y), z[make_pair(x, y)].y));\\n\\t\\t\\tz.erase(make_pair(x, y));\\n\\t\\t}\\n\\t\\tif (t == 3)\\n\\t\\t{\\n\\t\\t\\tint x, y;\\n\\t\\t\\tscanf(\\\"%d %d\\\", &x, &y);\\n\\t\\t\\t--x;\\n\\t\\t\\t--y;\\n\\t\\t\\tadd_query(0, 0, IDX, cur, make_pair(make_pair(x, y), cnt_q));\\n\\t\\t\\tcnt_q++; \\n\\t\\t}\\n\\t}\\n\\tcur++;\\n\\tfor(auto x : z)\\n\\t\\tadd_edge(0, 0, IDX, x.y.x, cur, make_pair(x.x, x.y.y));\\n\\tdfs(0, 0, IDX);\\n\\tfor(int i = 0; i < cnt_q; i++)\\n\\t\\tprintf(\\\"%d\\\\n\\\", ans[i]);\\n\\treturn 0;\\n}\"",
    "tags": [
      "bitmasks",
      "data structures",
      "dsu",
      "graphs"
    ],
    "rating": 2900
  },
  {
    "contest_id": "939",
    "index": "A",
    "title": "Love Triangle",
    "statement": "As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are $n$ planes on Earth, numbered from $1$ to $n$, and the plane with number $i$ likes the plane with number $f_{i}$, where $1 ≤ f_{i} ≤ n$ and $f_{i} ≠ i$.\n\nWe call a love triangle a situation in which plane $A$ likes plane $B$, plane $B$ likes plane $C$ and plane $C$ likes plane $A$. Find out if there is any love triangle on Earth.",
    "tutorial": "It is enough to check if there is some $i$ such that $f_{ffi} = i$, i. e. f[f[f[i]]] == i.",
    "tags": [
      "graphs"
    ],
    "rating": 800
  },
  {
    "contest_id": "939",
    "index": "B",
    "title": "Hamster Farm",
    "statement": "Dima has a hamsters farm. Soon $N$ hamsters will grow up on it and Dima will sell them in a city nearby.\n\nHamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.\n\nDima can buy boxes at a factory. The factory produces boxes of $K$ kinds, boxes of the $i$-th kind can contain in themselves $a_{i}$ hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.\n\nOf course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.\n\nFind out how many boxes and of which type should Dima buy to transport maximum number of hamsters.",
    "tutorial": "The easies way to solve this problem is to find the minimum number of hamsters that can be left on the farm. If Dima byes boxes of the $i$-th type, there are $n\\ \\mathrm{mod}\\ a_{i}$ hamsters left on the farm. So we should find such a type $x$, that the value $n{\\mathrm{~mod~}}a_{x}$ is minimum among all $x$; The number of boxes to buy is then equal to $n\\dim a_{x}$.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "939",
    "index": "C",
    "title": "Convenient For Everybody",
    "statement": "In distant future on Earth day lasts for $n$ hours and that's why there are $n$ timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from $1$ to $n$ are used, i.e. there is no time \"0 hours\", instead of it \"$n$ hours\" is used. When local time in the $1$-st timezone is $1$ hour, local time in the $i$-th timezone is $i$ hours.\n\nSome online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are $a_{i}$ people from $i$-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than $s$ hours 00 minutes local time and ends not later than $f$ hours 00 minutes local time. Values $s$ and $f$ are equal for all time zones. If the contest starts at $f$ hours 00 minutes local time, the person won't participate in it.\n\nHelp platform select such an hour, that the number of people who will participate in the contest is maximum.",
    "tutorial": "Initially, compute prefix sums: for each $i$ the total number of people in timezones from the first to the $i$-th. Let's loop through all possible starting times of the competition. Each starting time gives as one or two segments of timezones, in which people will compete in the contest. We can easily compute the total number of participants in $O(1)$ with the use of prefix sums. The total complexity is $O(N)$.",
    "tags": [
      "binary search",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "939",
    "index": "D",
    "title": "Love Rescue",
    "statement": "Valya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.\n\nThis story could be very sad but fairy godmother (Tolya's grandmother) decided to help them and restore their relationship. She secretly took Tolya's t-shirt and Valya's pullover and wants to make the letterings on them same. In order to do this, for one unit of mana she can buy a spell that can change some letters on the clothes. Your task is calculate the minimum amount of mana that Tolya's grandmother should spend to rescue love of Tolya and Valya.\n\nMore formally, letterings on Tolya's t-shirt and Valya's pullover are two strings with same length $n$ consisting only of lowercase English letters. Using one unit of mana, grandmother can buy a spell of form $(c_{1}, c_{2})$ (where $c_{1}$ and $c_{2}$ are some lowercase English letters), which can arbitrary number of times transform a single letter $c_{1}$ to $c_{2}$ and vise-versa on both Tolya's t-shirt and Valya's pullover. You should find the minimum amount of mana that grandmother should spend to buy a set of spells that can make the letterings equal. In addition you should output the required set of spells.",
    "tutorial": "Let's build a graph with 26 vertices representing the 26 letters of English alphabet. When we buy a spell of form $(c_{1}, c_{2})$, add an edge between vertices $c_{1}$ and $c_{2}$. It's easy to see, that it is possible to change a letter $a$ to a letter $b$ if and only if there is a path between corresponding vertices in the graph. So our task is to add the minimum possible number of edges such that characters $s_{1}[i]$ and $s_{2}[i]$ are in one connected component for each $i$ (here $s_{1}$ and $s_{2}$ are the given strings). Let's now take an empty graph and add edges between vertices $s_{1}[i]$ and $s_{2}[i]$ for each $i$. These edges, as we already know, add constraints on the final graph (these letters should be in a single connected component in the final graph). Let's compute the number of connected components in the graph - let it be $k$. Let's consider one connected component, let its size be $x_{i}$. Note that the spell we should buy should connect all these vertices in a single component. We can do this using at least $x_{i} - 1$ edges, and the edges that suit us are any spanning tree of this component, that can be found using a dfs, or just connect one vertex of this component to all the others. So the total number of spells is $\\textstyle\\sum_{i=1}^{k}(x_{i}-1)=\\sum_{i=1}^{k}x_{i}-k=n-k$. This is the answer to the problem.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "939",
    "index": "E",
    "title": "Maximize!",
    "statement": "You are given a multiset $S$ consisting of positive integers (initially empty). There are two kind of queries:\n\n- Add a positive integer to $S$, the newly added integer is not less than any number in it.\n- Find a subset $s$ of the set $S$ such that the value ${\\mathrm{max}}(s)-{\\mathrm{mean}}(s)$ is maximum possible. Here $max(s)$ means maximum value of elements in $s$, $\\operatorname{mean}(s)$ — the average value of numbers in $s$. Output this maximum possible value of ${\\mathrm{max}}(s)-{\\mathrm{mean}}(s)$.",
    "tutorial": "Let's first prove some lemmas we will use in the solution. Let $a_{0}, ..., a_{n}$ be integers that are at the current moment in $S$, sorted in increasing order. Lemma 1. Let the maximum element in optimal $s$ be $a_{n}$. Then the rest of the elements in $s$ form a prefix of $a$. Proof: let it be wrong. Let's consider $a_{i}$ $(i < n)$ - the first element of $a$, that is not in $s$. We know that in $s$ some element $a_{j}$ is presented $(i < j < n)$. Let's replace in $s$ $a_{j}$ with $a_{i}$, the average $mean(s)$ will not increase, because $a_{i}  \\le  a_{j}$, $max(s)$ will not change, so $max(s) - mean(s)$ will not decrease. Lemma 2. Let $m_{i}=a_{n}-\\frac{a_{n}+\\sum_{j=0}^{i-1}a_{j}}{i+1}$ - the value that we want to maximize in case of $s$ consisting of $a_{n}$, and a prefix of $a$ of length $i$, i. e. elements $a_{0}, ..., a_{i - 1}$. A claim: $s i g n(m_{i+1}-m_{i})=s i g n(a_{n}+\\sum_{j=0}^{i-1}a_{j}-a_{i}(i+1)$, where $sign(x)$ denotes the sign of $x$. Proof: $m_{i+1}-m_{i}={\\frac{(-a_{n}-\\sum_{j=0}^{n}a_{j})(i+1)+(a_{n}+\\sum_{j=0}^{n-1}a_{j})(i+2)}{(t+1)!(i+1)!(i+2)}}={\\frac{a_{n}+\\sum_{j=1}^{n}a_{j}-a_{i}(i+1))}{(t+1)!(i+2)}}$. Because the denominator is always $> 0$, then $s i g n(m_{i+1}-m_{i})=s i g n(a_{n}+\\sum_{j=0}^{i-1}a_{j}-a_{i}(i+1)$. Lemma 3. Let's denote for a fixed $n$ $f(i)=a_{n}+\\sum_{j=0}^{i-1}a_{j}-a_{i}(i+1)$. $f(i)$ is non-decreasing for increasing $i$. Proof: $f(i + 1) = f(i) + a_{i} - a_{i + 1}(i + 2) + a_{i}(i + 1) = f(i) - (i + 2)(a_{i + 1} - a_{i})$. $a_{i + 1} - a_{i}  \\ge  0$, because $a$ is sorted. Then $f(i + 1) - f(i) = - (i + 2)(a_{i + 1} - a_{i})  \\le  0$, i. e. $f(i + 1) - f(i)  \\le  0$, this means that $f(i)$ does not decrease when $i$ increases. Let's solve the problem now. Let's keep the current answer for the query of type $2$, let it be $ans$. When a new operation of type $1$ comes, let's update it with the optimal value of $max(s) - mean(s)$ in case $max(s) = a_{n}$, where $a_{n}$ is the newly added element. To find this optimal value, let's do binary search for $f(i)$ and find the minimum value of $i$, such that $f(i)  \\le  0$. Lemmas prove us that this prefix of length $i$ is optimal for fixed $max(s) = a_{n}$. Now update the value of $ans$ with the value $a_{n}-\\frac{a_{n}+\\sum_{j=0}^{i-1}a_{j}}{i+1}$. To compute the values $\\textstyle\\sum_{j=0}^{k}a_{j}$ fast, we should maintain the array of prefix sums in $a$ - one more element is added to this array each time a query of type $1$ comes.",
    "tags": [
      "binary search",
      "greedy",
      "ternary search",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "939",
    "index": "F",
    "title": "Cutlet",
    "statement": "Arkady wants to have a dinner. He has just returned from a shop where he has bought a semifinished cutlet. He only needs to fry it. The cutlet should be fried for $2n$ seconds, in particular, it should be fried for $n$ seconds on one side and $n$ seconds on the other side. Arkady has already got a frying pan and turn on fire, but understood that maybe he won't be able to flip the cutlet exactly after $n$ seconds after the beginning of cooking.\n\nArkady is too busy with sorting sticker packs in his favorite messenger and can flip the cutlet only in some periods of time. Namely, there are $k$ periods of time in which he can do it, the $i$-th of them is an interval of time from $l_{i}$ seconds after he starts cooking till $r_{i}$ seconds, inclusive. Arkady decided that it's not required to flip the cutlet exactly in the middle of cooking, instead, he will flip it several times in such a way that the cutlet will be fried exactly $n$ seconds on one side and $n$ seconds on the other side in total.\n\nHelp Arkady and find out if it's possible for him to cook the cutlet, if he is able to flip the cutlet only in given periods of time; and if yes, find the minimum number of flips he needs to cook the cutlet.",
    "tutorial": "Let's use dynamic programming approach. Solve the following subproblem: let $t$ be the seconds passed since the start of cooking, and $t_{0}$ seconds among them the cutlet was preparing on the current side; what is the minimum number of flips needed to reach this state? This can be easily computed using answers for subproblems $(t - 1, t_{0})$, $(t - 1, t_{0} - 1)$, in which the cutlet lays on the same side, and $(t - 1, t - 1 - t_{0})$ and $(t - 1, t - t_{0})$, in which the cutlet lays on the other side. You should carefully consider the number of flips needed for each transition, and check if it is possible, according to Arkady's availability. The complexity of this solution is $O(n^{2})$, which is not enough. For full solution, it is enough to consider only moments that correspond to start of some segment Arkady's availability, because between these moments we can make at most two flips, otherwise the result is obviously not optimal. In such case to compute the answer for subproblem $(t = l_{i}, t_{0})$ it is enough to compute minimum among answers for subproblems $(t' = l_{i - 1}, t'_{0})$, where $t'$ - the time of the start of the previous time segment - is fixed, and $t'_{0}$ changes within several segments, the bounds of which depend on the number of flips between moments $l_{i - 1}$ and $l_{i}$ seconds, and parameters $l_{i - 1}$, $r_{i - 1}$, $l_{i}$, $t_{0}$. For effective computing of minimums you can use the queue of minimums, because the bounds of the segments increase with the increase of $t_{0}$. The total complexity is $O(nk)$. You can also use other data structures for computing minimum, and the complexity of such solutions is $O(n k\\log\\left(n\\right))$.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "940",
    "index": "A",
    "title": "Points on the line",
    "statement": "We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round.\n\nThe \\textbf{diameter} of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset ${1, 3, 2, 1}$ is 2.\n\nDiameter of multiset consisting of one point is 0.\n\nYou are given $n$ points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed $d$?",
    "tutorial": "It's clear that diameter of the multiset of points equals to difference of coordinates of point with maximum coordinate and point with minimum coordinate. So we can iterate over all possible pairs of maximum and minimum point and check number of remaining points in $O(n)$. This solution works in $O(n^{3})$. Of course, there are faster solutions.",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "940",
    "index": "B",
    "title": "Our Tanya is Crying Out Loud",
    "statement": "Right now she actually isn't. But she will be, if you don't solve this problem.\n\nYou are given integers $n$, $k$, $A$ and $B$. There is a number $x$, which is initially equal to $n$. You are allowed to perform two types of operations:\n\n- Subtract 1 from $x$. This operation costs you $A$ coins.\n- Divide $x$ by $k$. Can be performed only if $x$ is divisible by $k$. This operation costs you $B$ coins.\n\nWhat is the minimum amount of coins you have to pay to make $x$ equal to $1$?",
    "tutorial": "If $k = 1$, then answer is obvious, $(n-1)\\cdot\\,A$, otherwise we will greedily decrease number. During each moment of time we should consider following three cases: If $n < k$, we can only $n - 1$ decrease number by 1, paying $A$ coins each time. It can be done in $O(1)$ using formula. If $n > k$ and $n$ is not divisible by $k$, we can only decrease number $(n\\,m o d\\,k)$ times by 1 paying $A$ coins each time. This case can be also handled in $O(1)$ using formula. If $n$ is divisible by $k$, it's always optimal to make number equals $\\begin{array}{l}{{\\frac{n}{k}}}\\end{array}$ paying $m i n(B,(n-\\frac{n}{k})\\cdot A)$ coins. If $B<(n-{\\frac{n}{k}})\\cdot A$ then optimality is obvious. Otherwise assume we didn't make decreasing to t $\\begin{array}{l}{{\\frac{n}{k}}}\\end{array}$ now, but did it on interval $\\textstyle{\\binom{n}{k}},n)$ from number $\\quad n-i\\cdot k$. In this case we paid $m i n(B,(m-i\\cdot k-\\textstyle{\\frac{n}{k}}+i)\\cdot A)+i\\cdot k\\cdot A$ coins. It equals $(n-i\\cdot k-{\\frac{n}{k}}+i)\\cdot A+i\\cdot k\\cdot A=(n-{\\frac{n}{k}})\\cdot A-i\\cdot(k-1)\\cdot A+i\\cdot k\\cdot A=(n-{\\frac{n}{k}})\\cdot A+i\\cdot A+i\\cdot k\\cdot A=(n-{\\frac{n}{k}})\\cdot A+i\\cdot A+i\\cdot k\\cdot A.$ or $B+i\\cdot k\\cdot A$, with is not more optimal then decreasing to $\\begin{array}{l}{{\\frac{n}{k}}}\\end{array}$ and decreasing to ${\\begin{array}{l}{{\\frac{n}{k}}-i}\\end{array}}\\,$ after that. Each case should be handled at most $\\log_{k}n$ times, so complexity of the solution is $O(\\log_{k}n)$.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "940",
    "index": "C",
    "title": "Phone Numbers",
    "statement": "And where the are the phone numbers?\n\nYou are given a string $s$ consisting of lowercase English letters and an integer $k$. Find the lexicographically smallest string $t$ of length $k$, such that its set of letters is a subset of the set of letters of $s$ and $s$ is lexicographically smaller than $t$.\n\nIt's guaranteed that the answer exists.\n\nNote that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is ${a, b, d}$.\n\nString $p$ is lexicographically smaller than string $q$, if $p$ is a prefix of $q$, is not equal to $q$ or there exists $i$, such that $p_{i} < q_{i}$ and for all $j < i$ it is satisfied that $p_{j} = q_{j}$. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa \\textbf{is not} lexicographically smaller than ab and a \\textbf{is not} lexicographically smaller than a.",
    "tutorial": "Consider $2$ cases: If $n < k$ we should simply add $k - n$ minimum symbols from $s$. If $n  \\ge  k$ we need to replace all symbols in the suffix of first $k$ symbols of string consisting of largest symbols to smallest symbols and next symbol before this suffix replace with next symbol that exists in the string. Complexity of this solution is $O(n+k)$.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "940",
    "index": "D",
    "title": "Alena And The Heater",
    "statement": "\"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme.\"\n\n\"Little Alena got an array as a birthday present$...$\"\n\nThe array $b$ of length $n$ is obtained from the array $a$ of length $n$ and two integers $l$ and $r$ ($l ≤ r$) using the following procedure:\n\n$b_{1} = b_{2} = b_{3} = b_{4} = 0$.\n\nFor all $5 ≤ i ≤ n$:\n\n- $b_{i} = 0$ if $a_{i}, a_{i - 1}, a_{i - 2}, a_{i - 3}, a_{i - 4} > r$ and $b_{i - 1} = b_{i - 2} = b_{i - 3} = b_{i - 4} = 1$\n- $b_{i} = 1$ if $a_{i}, a_{i - 1}, a_{i - 2}, a_{i - 3}, a_{i - 4} < l$ and $b_{i - 1} = b_{i - 2} = b_{i - 3} = b_{i - 4} = 0$\n- $b_{i} = b_{i - 1}$ otherwise\n\nYou are given arrays $a$ and $b'$ of the same length. Find two integers $l$ and $r$ ($l ≤ r$), such that applying the algorithm described above will yield an array $b$ equal to $b'$.\n\nIt's guaranteed that the answer exists.",
    "tutorial": "Notice, that constraints on ${\\mathit{l}}_{}^{}$ and ${\\boldsymbol{J}}^{*}$ generates only sequences $b_{i}$ that equals 00001, 00000, 11110, 11111. 00000 on positions $[i;i+4]$ means that $l\\leq\\operatorname*{max}_{i\\leq j\\leq i+4}a_{j}$. 00001 on positions $[i;i+4]$ means that $l\\geq\\operatorname*{max}_{i\\leq j\\leq i+4}a_{j}+1$. 11111 on positions $[i;i+4]$ means that $r\\geq\\operatorname*{min}_{i\\leq j\\leq i+4}a_{j}$. 11110 on positions $[i;i+4]$ means that $r\\leq\\operatorname*{min}_{i<j<i+4}a_{j}-1$. After all we get some constraints for minimum and maximum possible values of ${\\mathit{l}}_{}^{}$ and ${\\boldsymbol{J}}^{*}$. Since it's guaranteed that answer exists minimum possbile value of ${\\mathit{l}}_{}^{}$ and maximum possible value ${\\boldsymbol{J}}^{*}$ will always be a correct answer. Pay attention that $-10^{9}\\leq l$ and $r\\leq10^{9}$. This solution works in $O(n)$.",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "940",
    "index": "E",
    "title": "Cashback",
    "statement": "Since you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.\n\nYou are given an array $a$ of length $n$ and an integer $c$.\n\nThe value of some array $b$ of length $k$ is the sum of its elements except for the $\\left\\lfloor{\\frac{k}{x_{-}}}\\right\\rfloor$ smallest. For example, the value of the array $[3, 1, 6, 5, 2]$ with $c = 2$ is $3 + 6 + 5 = 14$.\n\nAmong all possible partitions of $a$ into contiguous subarrays output the smallest possible sum of the values of these subarrays.",
    "tutorial": "At first let's solve this problem with $O(n^{2}\\log{n})$ complexity. It can be done using dynamic programming. Let $d p_{i}$ be minimum cost of splitting prefix with length $i$.$d p_{0}=0$, $d p_{i}=\\operatorname*{min}_{j<i}d p_{j}+c o s t_{j+1,i}$ where $c o s t_{l,r}$ is a cost of $\\left(r-l+1\\right)-\\left.{\\bigl\\lfloor}{\\frac{r-l+1}{c}}\\right\\rfloor$ maximums on interval $[i,r]$. During finding these values we can iterate over $j$ from $i - 1$ to $0$, storing sum of $\\left|{\\frac{r-l+1}{c}}\\right|$ minimums in some structure like std::multiset. The important observation for faster solution is that it's always optimal to take segments with lengths $1$ or $c$. Suppose we took segment with length less than $c$, then its cost doesn't depend on the way, we split it and it's possible to take it using segments with length $1$. Suppose we took segment with length $\\textstyle{\\bar{\\mathbf{Z}}}$, $c\\leq x\\leq2\\cdot c-1$, then it's possible to split it to some segment with length $c$ and split other elements to segments with length $1$. Suppose we took a segment with length $2\\cdot c$, then it's not worse to take it as two segments with length ${\\mathit{\\mathbb{C}}}_{-}^{*}$. In other cases it's also possible to split segment to segments with lengths $1$ and ${\\mathit{\\mathbb{C}}}_{-}^{*}$ without loosing of optimality. It's easy to find cost of segment with length $1$, to find cost of segment with length $c$, it's possible to store elements in range $[i-c+1;i]$ in some data structure which can find minimum value fast. It can be queue with minimum or std::multiset; Complexity is $O(n\\log n)$ or $O(n)$ depending on structure used.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "940",
    "index": "F",
    "title": "Machine Learning",
    "statement": "You come home and fell some unpleasant smell. Where is it coming from?\n\nYou are given an array $a$. You have to answer the following queries:\n\n- You are given two integers $l$ and $r$. Let $c_{i}$ be the number of occurrences of $i$ in $a_{l: r}$, where $a_{l: r}$ is the subarray of $a$ from $l$-th element to $r$-th inclusive. Find the \\textbf{Mex} of ${c_{0}, c_{1}, ..., c_{10^{9}}}$\n- You are given two integers $p$ to $x$. Change $a_{p}$ to $x$.\n\nThe \\textbf{Mex} of a multiset of numbers is the smallest non-negative integer \\textbf{not in} the set.\n\nNote that in this problem all elements of $a$ are positive, which means that $c_{0}$ = 0 and $0$ is never the answer for the query of the second type.",
    "tutorial": "At first let's find out minimum length of array, such that answer for it is $c$. For it on this segment there should be a number that has one occurrence, some number that has two occurrences, etc. Length of this segment will be $1\\ +\\ 2\\ +\\ 3\\ +\\ \\cdots\\ +c\\ =\\ {\\frac{c(c+1)}{2}}$. That's why answer won't exceed $2\\cdot{\\sqrt{n}}$ for any query. Let's compress numbers in such a way that numbers from array and from queries will be in range from $1$ to $n + q$. Obviously this modification won't change answer, but now elements won't exceed $\\;n\\!+q$. Suppose for interval $[i,r]$ we know number $c n t_{i}$ of occurrences of each number and number of occurrences of each number of occurrences $s i z e_{i}$. Then we can find Mex of this set in $O({\\sqrt{n}})$. Moreover it's easy to update arrays $c n t_{i}$ and $s i z e_{i}$ for segments $[l-1;r]$, $[l+1;r]$, $[i;r-1]$ and $[i;r+1]$ in $O(1)$ time. We will represent each query as tuple of integers $(t,l,r)$ where t - is a number of change queries before this, and segment $[i,r]$. It's easy to see that $t$ can also be changed by one in $O(1)$ time. Because of $q\\approx n$ will replace $\\boldsymbol{\\mathit{I}}$ to $\\;n$ in following part of editorial. Let $P=n^{\\frac{2}{3}}$ and let's sort queries by triples $(\\lfloor{\\frac{t}{P}}\\rfloor,\\lfloor{\\frac{l}{P}}\\rfloor,r)$ and will answer queries in this order. Border ${\\boldsymbol{J}}^{*}$ will be increased by $O(n)$ for each sqaure of size ${\\frac{n^{2}}{P^{2}}}={\\frac{n^{2}}{n^{3}}}=n^{{\\frac{2}{3}}}$ $\\longrightarrow\\bigcup$ sum of movements of right border is $O(n^{\\frac{9}{3}})$. For each query borders ${\\mathit{l}}_{}^{}$ and $l$ are moved by not more than $O(n^{\\frac{2}{3}})$ $\\longrightarrow\\bigcup$ sum of movements is $O(n^{\\frac{9}{3}})$. Solution has time complexity $O(n^{\\frac{9}{3}})$.",
    "tags": [
      "brute force",
      "data structures"
    ],
    "rating": 2600
  },
  {
    "contest_id": "946",
    "index": "A",
    "title": "Partition",
    "statement": "You are given a sequence $a$ consisting of $n$ integers. You may partition this sequence into two sequences $b$ and $c$ in such a way that every element belongs exactly to one of these sequences.\n\nLet $B$ be the sum of elements belonging to $b$, and $C$ be the sum of elements belonging to $c$ (if some of these sequences is empty, then its sum is $0$). What is the maximum possible value of $B - C$?",
    "tutorial": "The answer for this problem can be calculated by the next simple formula: $\\sum_{i=1}^{n}\\left|a_{i}\\right|$, where $|a_{i}|$ is the absolute value of $a_{i}$.",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "946",
    "index": "B",
    "title": "Weird Subtraction Process",
    "statement": "You have two variables $a$ and $b$. Consider the following sequence of actions performed with these variables:\n\n- If $a = 0$ or $b = 0$, end the process. Otherwise, go to step $2$;\n- If $a ≥ 2·b$, then set the value of $a$ to $a - 2·b$, and repeat step $1$. Otherwise, go to step $3$;\n- If $b ≥ 2·a$, then set the value of $b$ to $b - 2·a$, and repeat step $1$. Otherwise, end the process.\n\nInitially the values of $a$ and $b$ are positive integers, and so the process will be finite.\n\nYou have to determine the values of $a$ and $b$ after the process ends.",
    "tutorial": "The answer can be calculated very easy by Euclid algorithm (which is described in the problem statement), but all subtractions will be replaced by taking by modulo.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "946",
    "index": "C",
    "title": "String Transformation",
    "statement": "You are given a string $s$ consisting of $|s|$ small english letters.\n\nIn one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.\n\nYour target is to make some number of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible.",
    "tutorial": "The problem can be solved by the next greedy algorithm. At first we need to store the last character of the alphabet we haven't obtained, for example, in variable $c$ (initially it will be equal to 'a'). Then we will just iterate over all characters of the string from left to right and if the current character of the string is not greater than $c$, we just replace it to $c$ and increase $c$ by 1. If in any moment $c$ will be greater than 'z', we got the answer. And if after iterating over the string $c$ will be not greater than 'z', the answer is <<-1>>.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "946",
    "index": "D",
    "title": "Timetable",
    "statement": "Ivan is a student at Berland State University (BSU). There are $n$ days in Berland week, and each of these days Ivan might have some classes at the university.\n\nThere are $m$ working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during $i$-th hour, and last lesson is during $j$-th hour, then he spends $j - i + 1$ hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends $0$ hours in the university.\n\nIvan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than $k$ lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.\n\nGiven $n$, $m$, $k$ and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than $k$ lessons?",
    "tutorial": "The problem can be solved in the following dynamic programming manner. Let $dp[i][j]$ be the smallest number of hours Ivan can spend in university in the first $i$ days while having $j$ lessons skipped. To calculate it we can store $mn[i][j]$ - minimal number of hours Ivan is required to spend in the $i$-th day so that he attends $j$ lessons. Then we can iterate over all lengths from $0$ to $k$ and update $dp[i + 1][j + length_{cur}]$ with $dp[i][j] + mn[i][length_{cur}]$. Precalc works in $O(nm^{2})$ and dp can be processed in $O(nk^{2})$.",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "946",
    "index": "E",
    "title": "Largest Beautiful Number",
    "statement": "Yes, that's another problem with definition of \"beautiful\" numbers.\n\nLet's call a positive integer $x$ beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, $4242$ is a beautiful number, since it contains $4$ digits, and there exists a palindromic permutation $2442$.\n\nGiven a positive integer $s$, find the largest beautiful number which is less than $s$.",
    "tutorial": "This is pretty typical problem on greedy construction: you are asked to build lexicographically maximal string. In the majority of cases it's done like this. Imagine you've built some prefix of length $i$ with all numbers equal to the prefix of length $i$ of the original string. You are also sure there exists some suffix for it that will give proper beautiful number. Now you have two options: you either put $s_{i}$ if possible and proceed to the same task of longer prefix or you put the smaller number and fill the entire suffix with the maximum possible beautiful number you can obtain. Now you should learn how to check if any valid suffix exists. It means at least the smallest possible beautiful number with current prefix is smaller than $s$. It's built like this. Let $cnt$ be the number of digits which currently have odd number of occurences. You put all zeroes but the last $cnt$ digits and then output these odd occurence number digits in increasing order. The first part can be checked with partial sums on the number of zeroes on segment in the original string and the second part has its length not greater than $10$ and can be checked naively. Overall complexity: $O(|s|)$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "946",
    "index": "F",
    "title": "Fibonacci String Subsequences",
    "statement": "You are given a binary string $s$ (each character of this string is either 0 or 1).\n\nLet's denote the cost of string $t$ as the number of occurences of $s$ in $t$. For example, if $s$ is 11 and $t$ is 111011, then the cost of $t$ is $3$.\n\nLet's also denote the Fibonacci strings sequence as follows:\n\n- $F(0)$ is 0;\n- $F(1)$ is 1;\n- $F(i) = F(i - 1) + F(i - 2)$ if $i > 1$, where $ + $ means the concatenation of two strings.\n\nYour task is to calculate the sum of costs of all subsequences of the string $F(x)$. Since answer may be large, calculate it modulo $10^{9} + 7$.",
    "tutorial": "If $F(x)$ was not really large, then we could run the following dynamic programming solution: Let $dp[i][j]$ be the number of ways to process first $i$ characters of $F(x)$ so that the suffix of the subsequence of length $j$ matches the prefix of $s$ with length $j$. This is not really different from a usual approach with dynamic programming on KMP (constraints in this problem allow us to build KMP automaton naively without the help of any fast prefix-function algorithm). However, the length of $F(x)$ is really large. Let's consider the traversions we make in dynamic programming. Let $A$ be the KMP automaton matrix (that is, let $A[p][c]$ be the new value of prefix-function if the previous value was $p$ and we added a character $c$). Then from the state $dp[i][j]$, if the following character is $0$, we make traversions to $dp[i + 1][j]$ and to $dp[i][A[p][0]]$. This actually leads to rewriting traversions as a matrix. Let $d_{i}$ be the vector such that its $j$-th element is equal to $dp[i][j]$. Then advancing from $d_{i}$ to $d_{i + 1}$, if $i$-th character is $0$, can be represented as follows: $d_{i + 1} = d_{i}  \\times  M_{0}$, where $M_{0}$ can be filled with the help of KMP automaton: for every $k\\in[0,n]$ we add $1$ to $M_{0}[k][k]$, and also add $1$ to $M_{0}[k][A[k][0]]$. The same approach can be used to form matrix $M_{1}$ that denotes adding character $1$, and if we want to add the string $F(x)$, we can actually represent its matrix as $M_{x} = M_{x - 1}  \\times  M_{x - 2}$. This matrix multiplication approach will run in $O(xn^{3})$, but the problem is that it doesn't give us the answer. To obtain it, we may add an auxiliary state $n + 1$ to the dynamic programming, add $1$ to it each time we traverse to state $n$, multiply it by $2$ each time we add a character, and rewrite it into matrix form.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef vector<int> vec;\\ntypedef vector<vec> mat;\\n\\nconst int MOD = 1000 * 1000 * 1000 + 7;\\n\\nint add(int x, int y)\\n{\\n\\tint z = x + y;\\n\\twhile(z >= MOD)\\n\\t\\tz -= MOD;\\n\\treturn z;\\t\\n}\\n\\nint mul(int x, int y)\\n{\\n\\treturn (x * 1ll * y) % MOD;\\n}\\n\\nvec mul(const vec& a, const mat& b)\\n{\\n\\tint n = a.size();\\n\\tvec c(n, 0);\\n\\tfor(int i = 0; i < n; i++)\\n\\t\\tfor(int j = 0; j < n; j++)\\n\\t\\t\\tc[i] = add(c[i], mul(a[j], b[j][i]));\\n\\treturn c;\\n}\\n\\nmat mul(const mat& a, const mat& b)\\n{\\n\\tint n = a.size();\\n\\tmat c(n, vec(n, 0));\\n\\tfor(int i = 0; i < n; i++)\\n\\t\\tfor(int j = 0; j < n; j++)\\n\\t\\t\\tfor(int k = 0; k < n; k++)\\n\\t\\t\\t\\tc[i][k] = add(c[i][k], mul(a[i][j], b[j][k]));\\n\\treturn c;\\n}\\n\\nint main() { \\n\\tint x, n;\\n\\tcin >> n >> x;\\n\\tstring s;\\n\\tcin >> s;\\n\\tvector<int> p(n);\\n\\tfor(int i = 1; i < n; i++)\\n\\t{\\n\\t\\tint j = p[i - 1];\\n\\t\\twhile(s[j] != s[i] && j > 0)\\n\\t\\t{\\n\\t\\t\\tj = p[j - 1];\\n\\t\\t}\\n\\t\\tif(s[j] == s[i])\\n\\t\\t\\tj++;\\n\\t\\tp[i] = j;\\n\\t}\\n\\tvector<vector<int> > a(n + 1, vector<int>(2, 0));\\n\\ta[n][0] = a[n][1] = n;\\n\\tfor(int i = 0; i <= n; i++)\\n\\t{\\n\\t\\tif (s[i] == '0')\\n\\t\\t\\ta[i][0] = i + 1;\\n\\t\\telse if (i > 0)\\n\\t\\t\\ta[i][0] = a[p[i - 1]][0];\\n\\t\\tif (s[i] == '1')\\n\\t\\t\\ta[i][1] = i + 1;\\n\\t\\telse if (i > 0)\\n\\t\\t\\ta[i][1] = a[p[i - 1]][1];\\n\\t}\\n\\tvec v(n + 2, 0);\\n\\tv[0] = 1;\\n\\tvector<mat> f;\\n\\tmat f0(n + 2, vec(n + 2, 0));\\n\\tfor(int i = 0; i < n + 1; i++)\\n\\t{\\n\\t\\tf0[i][i] = add(f0[i][i], 1);\\n\\t\\tint z = a[i][0];\\n\\t\\tf0[i][z] = add(f0[i][z], 1);\\n\\t\\tif (z == n)\\n\\t\\t\\tf0[i][n + 1] = add(f0[i][n + 1], 1);\\n\\t}\\n\\tf0[n + 1][n + 1] = add(f0[n + 1][n + 1], 2);\\n\\tmat f1(n + 2, vec(n + 2, 0));\\n\\tfor(int i = 0; i < n + 1; i++)\\n\\t{\\n\\t\\tf1[i][i] = add(f1[i][i], 1);\\n\\t\\tint z = a[i][1];\\n\\t\\tf1[i][z] = add(f1[i][z], 1);\\n\\t\\tif (z == n)\\n\\t\\t\\tf1[i][n + 1] = add(f1[i][n + 1], 1);\\n\\t}\\n\\t\\n\\tf1[n + 1][n + 1] = add(f1[n + 1][n + 1], 2);\\n\\tf.push_back(f0);\\n\\tf.push_back(f1);\\n\\tfor(int i = 2; i <= x; i++)\\n\\t\\tf.push_back(mul(f[i - 1], f[i - 2]));\\n\\tv = mul(v, f[x]);\\n\\tcout << v.back() << endl;\\n\\treturn 0;\\n}\"",
    "tags": [
      "combinatorics",
      "dp",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "946",
    "index": "G",
    "title": "Almost Increasing Array",
    "statement": "We call an array almost increasing if we can erase not more than one element from it so that the array becomes strictly increasing (that is, every element is striclty greater than every element before it).\n\nYou are given an array $a$ consisting of $n$ elements. You are allowed to replace any element with any integer number (and you may do so any number of times you need). What is the minimum number of replacements you have to perform in order to make the array almost increasing?",
    "tutorial": "If the problem was to make the array strictly increasing, then we could use the following approach: for every element subtract its index from it, find the longest non-decreasing subsequence, and change every element not belonging to this sequence. In this problem we can use a similar technique. Let's iterate on the element we will remove after changing everything we need (let's call it $k$). For every $i < k$ we will subtract $i$ from $a_{i}$, and for every $i > k$ we will subtract $i - 1$ from $a_{i}$. Let's maintain the longest non-decreasing subsequence ending in every element on prefix, and the longest non-decreasing subsequence starting in every element on suffix (this can be done by a lot of different techniques, for example, two segment trees and rollbacking, which is used in our model solution). Then we need to somehow merge these sequences. The easiest way to do it is to consider only the subsequence ending in element $k - 1$ (since if we will need to consider the subsequence ending in some index less than $k - 1$, we would check this possibility choosing other value of $k$) and use some data structure (BIT, segment tree or something similar) to find the longest subsequence that can be appended to the one we fixed. After checking if we need to delete element $k$, we add it to the data structure on prefix, remove element $k + 1$ from the data structure on suffix, check if we have to remove element $k + 1$ and so on.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nmap<int, int> comp;\\n\\nvoid compress(const vector<int>& a)\\n{\\n\\tvector<int> z;\\n\\tfor(int i = 0; i < a.size(); i++)\\n\\t{\\n\\t\\tz.push_back(a[i] - i);\\n\\t\\tz.push_back(a[i] - i + 1);\\n\\t}\\n\\tsort(z.begin(), z.end());\\n\\tz.erase(unique(z.begin(), z.end()), z.end());\\n\\tfor(int i = 0; i < z.size(); i++)\\n\\t\\tcomp[z[i]] = i;\\n}\\n\\nconst int N = 400043;\\nconst int M = 8000043;\\n\\nint T[4 * N];\\nint* where[M];\\nint val[M];\\nint st = 0;\\n\\nvoid change(int& x, int y)\\n{\\n\\twhere[st] = &x;\\n\\tval[st] = x;\\n\\tst++;\\n\\tx = y;\\n}\\n\\nvoid rollback(int new_st)\\n{\\n\\twhile(st > new_st)\\n\\t{\\n\\t\\tst--;\\n\\t\\t*(where[st]) = val[st];\\n\\t}\\n}\\n\\nvoid build(int v, int l, int r)\\n{\\n\\tT[v] = 0;\\n\\tif(l < r - 1)\\n\\t{\\n\\t\\tint mid = (l + r) / 2;\\n\\t\\tbuild(v * 2 + 1, l, mid);\\n\\t\\tbuild(v * 2 + 2, mid, r);\\n\\t}\\n}\\n\\nvoid upd(int v, int l, int r, int pos, int val)\\n{\\n\\tchange(T[v], max(T[v], val));\\n\\tif (l < r - 1)\\n\\t{\\n\\t\\tint mid = (l + r) / 2;\\n\\t\\tif (pos < mid)\\n\\t\\t\\tupd(v * 2 + 1, l, mid, pos, val);\\n\\t\\telse\\n\\t\\t\\tupd(v * 2 + 2, mid, r, pos, val);\\n\\t}\\n}\\n\\nint query(int v, int l, int r, int L, int R)\\n{\\n\\tif (L >= R)\\n\\t\\treturn 0;\\n\\tif (l == L && r == R)\\n\\t\\treturn T[v];\\n\\tint mid = (l + r) / 2;\\n\\treturn max(query(v * 2 + 1, l, mid, L, min(R, mid)), query(v * 2 + 2, mid, r, max(L, mid), R));\\n}\\n\\nint T2[4 * N];\\n\\nvoid build2(int v, int l, int r)\\n{\\n\\tT2[v] = 0;\\n\\tif(l < r - 1)\\n\\t{\\n\\t\\tint mid = (l + r) / 2;\\n\\t\\tbuild2(v * 2 + 1, l, mid);\\n\\t\\tbuild2(v * 2 + 2, mid, r);\\n\\t}\\n}\\n\\nvoid upd2(int v, int l, int r, int pos, int val)\\n{\\n\\tT2[v] = max(T2[v], val);\\n\\tif (l < r - 1)\\n\\t{\\n\\t\\tint mid = (l + r) / 2;\\n\\t\\tif (pos < mid)\\n\\t\\t\\tupd2(v * 2 + 1, l, mid, pos, val);\\n\\t\\telse\\n\\t\\t\\tupd2(v * 2 + 2, mid, r, pos, val);\\n\\t}\\n}\\n\\nint query2(int v, int l, int r, int L, int R)\\n{\\n\\tif (L >= R)\\n\\t\\treturn 0;\\n\\tif (l == L && r == R)\\n\\t\\treturn T2[v];\\n\\tint mid = (l + r) / 2;\\n\\treturn max(query2(v * 2 + 1, l, mid, L, min(R, mid)), query2(v * 2 + 2, mid, r, max(L, mid), R));\\n}\\n\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\", &n);\\n\\tvector<int> a(n);\\n\\tfor(int i = 0; i < n; i++)\\n\\t\\tscanf(\\\"%d\\\", &a[i]);\\n\\tcompress(a);\\n\\tint mx = comp.size();\\n\\tint ans = 0;\\n\\tvector<int> states;\\n\\tbuild(0, 0, mx);\\n\\tfor(int i = n - 1; i > 0; i--)\\n\\t{\\n\\t\\tstates.push_back(st);\\n\\t\\tint cur = comp[a[i] - i + 1];\\n\\t\\tint val = query(0, 0, mx, cur, mx);\\n\\t\\tupd(0, 0, mx, cur, val + 1);\\n\\t}\\n\\tbuild2(0, 0, mx);\\n\\tans = max(ans, query(0, 0, mx, 0, mx));\\n\\tfor(int i = 0; i < n - 1; i++)\\n\\t{\\n\\t\\trollback(states.back());\\n\\t\\tstates.pop_back();\\n\\t\\tint cur = comp[a[i] - i];\\n\\t\\tint val = query2(0, 0, mx, 0, cur + 1);\\n\\t\\tupd2(0, 0, mx, cur, val + 1);\\n\\t\\tans = max(ans, val + 1 + query(0, 0, mx, cur, mx));\\n\\t}\\n\\tcout << n - 1 - ans << endl;\\n}\"",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "948",
    "index": "A",
    "title": "Protect Sheep",
    "statement": "Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.\n\nThe pasture is a rectangle consisting of $R × C$ cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.\n\nInitially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do \\textbf{not} need to minimize their number.",
    "tutorial": "Suppose that there is a wolf and a sheep in adjacent cells. It is obvious that in this case, the answer \"NO\" - this particular wolf can always attack this sheep. Otherwise, the answer is always \"YES\". The simplest way of protecting all sheep is to place a dog in every empty cell. Then no wolf can move and all sheep are safe and happy.",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "949",
    "index": "A",
    "title": "Zebras",
    "statement": "Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.\n\nOleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several \\textbf{subsequences}, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.",
    "tutorial": "Simple greedy works here. Let's go from left to right and assign each element to some subsequence. At each moment we have two types of already built subsequences: zebras (\"0\", \"010\", \"01010\", ...) and \"almost zebras\" (\"01\", \"0101\", \"010101\"). If next element of the string is '1' we should add it to some zebra making it \"almost zebra\". If there are no zebras at this moment it's impossible to divide string into zebra subsequences. If next element of the string is '0' we should add it so some \"almost zebra\" making it simple zebra. If there are no \"almost zebra\"'s now just create new zebra consisting of this '0'. If there are no \"almost zebra\"'s at the end answer exists and built zebras satisfy all requirements otherwise there is no answer.",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "949",
    "index": "B",
    "title": "A Leapfrog in the Array",
    "statement": "Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.\n\nLet's consider that initially array contains $n$ numbers from $1$ to $n$ and the number $i$ is located in the cell with the index $2i - 1$ (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all $n$ numbers will appear in the first $n$ cells of the array. For example if $n = 4$, the array is changing as follows:\n\nYou have to write a program that allows you to determine what number will be in the cell with index $x$ ($1 ≤ x ≤ n$) after Dima's algorithm finishes.",
    "tutorial": "In odd position $p$ value $\\textstyle{\\frac{p+1}{2}}$ will be set. For even position $p$ let's find out position from which value has arrived and iterate over such position until we will arrive to odd position for which we know answer. At the moment of jumping to cell $p$ there are $\\textstyle{\\frac{p}{2}}$ elements to the right of the position $p$. So there are $n-{\\frac{p}{2}}$ elements to the right of this position and jump to cell $p$ was done from position $p+(n-{\\frac{p}{2}})$. During each such jump length of jump decreases at least by 2 times, so there are no more than $O(\\log n)$ jumps and solution works in $O(q\\log n)$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "949",
    "index": "C",
    "title": "Data Center Maintenance",
    "statement": "BigData Inc. is a corporation that has $n$ data centers indexed from $1$ to $n$ that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!).\n\nMain feature of services offered by BigData Inc. is the access availability guarantee even under the circumstances of any data center having an outage. Such a guarantee is ensured by using the two-way replication. Two-way replication is such an approach for data storage that any piece of data is represented by two identical copies that are stored in two different data centers.\n\nFor each of $m$ company clients, let us denote indices of two different data centers storing this client data as $c_{i, 1}$ and $c_{i, 2}$.\n\nIn order to keep data centers operational and safe, the software running on data center computers is being updated regularly. Release cycle of BigData Inc. is one day meaning that the new version of software is being deployed to the data center computers each day.\n\nData center software update is a non-trivial long process, that is why there is a special hour-long time frame that is dedicated for data center maintenance. During the maintenance period, data center computers are installing software updates, and thus they may be unavailable. Consider the day to be exactly $h$ hours long. For each data center there is an integer $u_{j}$ ($0 ≤ u_{j} ≤ h - 1$) defining the index of an hour of day, such that during this hour data center $j$ is unavailable due to maintenance.\n\nSumming up everything above, the condition $u_{ci, 1} ≠ u_{ci, 2}$ should hold for each client, or otherwise his data may be unaccessible while data centers that store it are under maintenance.\n\nDue to occasional timezone change in different cities all over the world, the maintenance time in some of the data centers may change by one hour sometimes. Company should be prepared for such situation, that is why they decided to conduct an experiment, choosing some non-empty subset of data centers, and shifting the maintenance time for them by an hour later (i.e. if $u_{j} = h - 1$, then the new maintenance hour would become $0$, otherwise it would become $u_{j} + 1$). Nonetheless, such an experiment should not break the accessibility guarantees, meaning that data of any client should be still available during any hour of a day after the data center maintenance times are changed.\n\nSuch an experiment would provide useful insights, but changing update time is quite an expensive procedure, that is why the company asked you to find out the minimum number of data centers that have to be included in an experiment in order to keep the data accessibility guarantees.",
    "tutorial": "Formally you are given a properly colored graph and you are asked to find out size of smallest non-empty subset such that after addition $1$ modulo $h$ to colors of vertices in this subset coloring will remain proper. Let's build a directed graph with $n$ vertices and edge from $u$ to $v$ iff $u$ and $v$ are connected by edge in original graph and $\\left(c o l o r_{u}+1\\right)\\ \\mathrm{In}00|\\ h=c o l o r_{v}$. Now let's fix some vertex which color will be changed. It's clear that we should take into its set all vertices which are reachable from it. Now our problem is reduced to following problem: \"Given directed graph find vertex with smallest number reachable from it vertices\". It's just any vertex from smallest strongly connected component which is sink (strongly connected component such there is no strongly connected component reachable from it).",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1900
  },
  {
    "contest_id": "949",
    "index": "D",
    "title": "Curfew",
    "statement": "Instructors of Some Informatics School make students go to bed.\n\nThe house contains $n$ rooms, in each room exactly $b$ students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from $1$ to $n$. Initially, in $i$-th room there are $a_{i}$ students. All students are currently somewhere in the house, therefore $a_{1} + a_{2} + ... + a_{n} = nb$. Also $2$ instructors live in this house.\n\nThe process of curfew enforcement is the following. One instructor starts near room $1$ and moves toward room $n$, while the second instructor starts near room $n$ and moves toward room $1$. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if $n$ is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends.\n\nWhen an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to $b$, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students.\n\nWhile instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most $d$ rooms, that is she can move to a room with number that differs my at most $d$. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously.\n\nFormally, here is what's happening:\n\n- A curfew is announced, at this point in room $i$ there are $a_{i}$ students.\n- Each student can run to another room but not further than $d$ rooms away from her initial room, or stay in place. After that each student can optionally hide under a bed.\n- Instructors enter room $1$ and room $n$, they count students there and lock the room (after it no one can enter or leave this room).\n- Each student from rooms with numbers from $2$ to $n - 1$ can run to another room but not further than $d$ rooms away from her \\textbf{current} room, or stay in place. Each student can optionally hide under a bed.\n- Instructors move from room $1$ to room $2$ and from room $n$ to room $n - 1$.\n- This process continues until all rooms are processed.\n\nLet $x_{1}$ denote the number of rooms in which the first instructor counted the number of non-hidden students different from $b$, and $x_{2}$ be the same number for the second instructor. Students know that the principal will only listen to one complaint, therefore they want to minimize the maximum of numbers $x_{i}$. Help them find this value if they use the optimal strategy.",
    "tutorial": "Let's solve the problem in case when there is only one instructor (which moves from left to right and the only goal is to minimize number of bad rooms) I claim, that the following greedy works: Move through rooms from left to right If there are too many students inside room, send the excess students to the next room If there are not enough students, but it is possible to fulfill this room from rooms on the right (the sum $\\sum_{j=i}^{\\mathrm{min}(\\,n-1,i+d*)(\\,i+1))}\\ Q_{j}$ is at least $b$), then do it. If it's not possible, then send all students to the following room. If it is the last room, say that those students are hiding in it. This greedy can be implemented in ${\\mathcal{O}}(n)$ time: calculate the prefix sums on the initial $a_{i}$, this way you can check if it is possible to move students from following rooms here fast. To handle the removal students from following rooms you can maintain the current \"debt\" of students. When you first consider room you can repay the debt as much as you can and then check one of the cases above. Since the both left and right borders of segments are moving monotonously the debt will be \"inherited\" correctly. Notice, that you can only consider \"paths of different students never cross\", that means if first student was initially in room $i$ and moved to $a$, while the second student was in $j$ and moved to $b$, then if $i  \\le  j$ than $a  \\le  b$. Because otherwise you can swap students and nothing will change. The proof of the greedy (you can possibly skip it). Suppose there is a better answer, which completes the rooms $a_{1}$, $...$, $a_{k}$, while the greedy solutions completes rooms $b_{1}$, $...$, $b_{l}$, $l < k$. We will assume that in optimal solution paths of students don't intersect, that all \"excessive\" students are hiding in last room and that all rooms in optimal answer are either full ($b$) or empty ($0$). Otherwise it's possible to change the \"correct answer in such way, that number of good rooms will not decrease. Let's $i$ is smallest index when $a_{i}  \\neq  b_{i}$. Then $a_{i} > b_{i}$, because greedy solution would always fulfill the room $a_{i}$ if it would be possible (actually, greedy solution builts the lexmin solution). But if $a_{i} > b_{i}$ we can \"patch\" the supposed optimal solution and move all students which were sent to room $b_{i}$ to $a_{i}$ (we know it is possible by the greedy solution's answer). This way we can increase the common prefix with any possible \"best\" answer hence contradiction. Back to the problem with two instructors. Recall, that \"paths of different students don't cross\", hence there exists a \"border\", the number $x$ from $0$ to $nb$, where the first $x$ students are going to the first instructor and all others to second. One could have bruteforced that border and solved the both halfs of the array by the method above, but then the complexity will be $n^{2} \\cdot b$ which is too much. We need to search for the border more efficiently. Let $f(m)$ will be the answer for first instructor, when he is given $m$ first students and $g(m)$ is the answer for second instructor when he is given all students except first $m$ ones. It is easy to see, that $f(m)$ in decreasing, while $g(m)$ is increasing (both times it is not strict monotonicity). Indeed, the more students are given to instructor, than more opportunities he has (all excessive students can always hide, so it is not a problem). We are searching for $m$ where $ans(m) = max(f(m), g(m))$ is smallest possible.Let's introduce function $z(m) = g(m) - f(m)$ - increasing (but still not strict). Let's call $m_{0}$ the smallest index, such that $z(m_{0})  \\ge  0$. One can see, that a $min(ans(m_{0} - 1), ans(m_{0}))$ is the final answer. Indeed, if one will try greater $m$'s than $m_{0}$, than the $g(m)$ will be dominating in max, and hence $ans(m_{0})$ is more optimal. Otherwise, if $m < m_{0} - 1$, then $ans(m)$ is better.",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "949",
    "index": "E",
    "title": "Binary Cards",
    "statement": "It is never too late to play the fancy \"Binary Cards\" game!\n\nThere is an infinite amount of cards of positive and negative ranks that are used in the game. The absolute value of any card rank is a power of two, i.e. each card has a rank of either $2^{k}$ or $ - 2^{k}$ for some integer $k ≥ 0$. There is an infinite amount of cards of any valid rank.\n\nAt the beginning of the game player forms his deck that is some multiset (possibly empty) of cards. It is allowed to pick any number of cards of any rank but the small deck is considered to be a skill indicator. Game consists of $n$ rounds. In the $i$-th round jury tells the player an integer $a_{i}$. After that the player is obligated to draw such a subset of his deck that the sum of ranks of the chosen cards is equal to $a_{i}$ (it is allowed to not draw any cards, in which case the sum is considered to be equal to zero). If player fails to do so, he loses and the game is over. Otherwise, player takes back all of his cards into his deck and the game proceeds to the next round. Player is considered a winner if he is able to draw the suitable set of cards in each of the rounds.\n\nSomebody told you which numbers $a_{i}$ the jury is going to tell you in each round. Now you want to pick a deck consisting of the minimum number of cards that allows you to win the \"Binary Cards\" game.",
    "tutorial": "There are two observations required to solve this problem: You don't have to take two cards with same number. If you took two cards with number $x$ you can take card with number $2x$ and card with number $x$ and answer will remain correct. If you took card with number $x$ you don't have to take card with number $- x$. You can take cards $2x$ and $- x$ instead. Consider all numbers. If there are no odd numbers you don't have to take $1$ or $- 1$ cards. Otherwise you have to take either $1$ or $- 1$. Try both possibilities and add value of taken card to all odd numbers. After this step all numbers are even, so you can just divide them by $2$ and solve the same problem with divided number. After each step of this algorithm maximum possible absolute value of card is also divided by $2$, so in worst case complexity will be $T(C)=2\\cdot T({\\frac{C}{2}})+O(C)$, where $C$ is a maximum absolute value of number. Solution of the equation is $T(C)=O(C\\log C)$ so it's fast enough.",
    "tags": [
      "brute force"
    ],
    "rating": 2700
  },
  {
    "contest_id": "949",
    "index": "F",
    "title": "Astronomy",
    "statement": "\\url{CDN_BASE_URL/571a7070e5784ace821a58b11e4350fb}",
    "tutorial": "Let's shuffle lines randomly. Select some 4 points and find their intersection point. If it's not integer or is not in bounding box it's definitely not an answer. Otherwise let's check it. Iterate over points and check if there is another point on the line that going through answer and this point. To check it we need to build some structure that can check if some line is inside it. For example you can for each point sort other points by polar angle, or store polar angles in hash table (multiplying it by number of order $C^{2}$ making different angles different). If there is no pair for some point let's stop checking it. This solution works in $O(n^{3})$. In fact no, it's $O(n^{2})$. I will write full formal proof soon, now I'll write just sketch of it. Consider planar graph where vertices are all intersection points of some lines passing through two given points. Let's find expected number of lines checking. Divide vertices into 2 classes: heavy (with degree $\\mathbf{z}_{\\overline{{{\\ell}}}}^{\\overline{{{\\nu}}}}$) and light (with degree $<\\frac{|V|}{2}$) Expected time of checking is sum of expected time checking light vertices and heavy vertices It's quite easy to prove it for light vertices. To proof it for heavy vertices Szemerédi-Trotter theorem might be useful",
    "tags": [
      "geometry",
      "probabilities"
    ],
    "rating": 3300
  },
  {
    "contest_id": "950",
    "index": "A",
    "title": "Left-handers, Right-handers and Ambidexters",
    "statement": "You are at a water bowling training. There are $l$ people who play with their left hand, $r$ people, who play with their right hand, and $a$ ambidexters, who can play with left or right hand.\n\nThe coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands.\n\nAmbidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand.\n\nPlease find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.",
    "tutorial": "Iterate over size of the team. Now you know how many players should play with left hand, but are not left-handed (because there are no so much left-handed players). The same with right hand. Just check if sum of these values is not more than number of ambidexters.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "950",
    "index": "B",
    "title": "Intercepted Message",
    "statement": "Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.\n\nZhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred through the network: if an archive consists of $k$ files of sizes $l_{1}, l_{2}, ..., l_{k}$ bytes, then the $i$-th file is split to one or more blocks $b_{i, 1}, b_{i, 2}, ..., b_{i, mi}$ (here the total length of the blocks $b_{i, 1} + b_{i, 2} + ... + b_{i, mi}$ is equal to the length of the file $l_{i}$), and after that all blocks are transferred through the network, maintaining the order of files in the archive.\n\nZhorik thinks that the two messages contain the same archive, because their total lengths are equal. However, each file can be split in blocks in different ways in the two messages.\n\nYou are given the lengths of blocks in each of the two messages. Help Zhorik to determine what is the maximum number of files could be in the archive, if the Zhorik's assumption is correct.",
    "tutorial": "Let's define $\\mathbf{{\\mu}_{i}}$ and $p_{i}$ as sums of first $\\overline{{i}}$ elements of $\\textstyle{\\bar{\\mathbf{Z}}}$ and $\\mathbf{\\mathbf{y}}$ ($s_{0}=0$, $s_{i}=s_{i-1}+x_{i}$, $p_{0}=0$, $p_{i}=p_{i-1}+y_{i}$). ${\\mathcal{L}}_{l_{1}},{\\mathcal{L}}_{l_{1}+1},\\cdot\\cdot,{\\mathcal{L}}_{r_{1}}$ and $y l_{2},y l_{2}+1,\\cdot\\cdot\\cdot,y r_{2}$ can be same file iff this three conditions are true: $s_{l_{1}-1}=p_{l_{2}-1}$ because we need to divide prefix into files. $s_{n}-s_{r_{1}}=p_{m}-p_{r_{2}}$ because we need to divide suffix into files. $s_{r_{1}}\\-\\ s_{l_{1}-1}\\ =p_{r_{2}}\\ -p_{l_{2}-1}$ segments have same sum. It's easy to see that if two first conditions are true then the third are true too because $s_{n}=p_{m}$ and because of this fact and condition from statement $x_{i}\\geq1,y_{i}\\geq1$ answer is a number of non-empty prefixes with the same sum. Time complexity is $O(n+m)$ if you use two pointers or $O((n+m)\\log{(n+m)}$ if you use some data structure.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "954",
    "index": "A",
    "title": "Diagonal Walking",
    "statement": "Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.\n\nIn the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.\n\nYour problem is to print the minimum possible length of the sequence of moves after the replacements.",
    "tutorial": "Let's iterate over all characters of the string from left to right (excluding last character). Suppose $i$ is a position of the current element of the string. If $s_{i}  \\neq  s_{i + 1}$, increase answer by $1$ and increase $i$ by $2$, else just increase $i$ by $1$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "954",
    "index": "B",
    "title": "String Typing",
    "statement": "You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to type this string using your keyboard.\n\nInitially, you have an empty string. Until you type the whole string, you may perform the following operation:\n\n- add a character to the end of the string.\n\nBesides, \\textbf{at most once} you may perform one additional operation: copy the string and append it to itself.\n\nFor example, if you have to type string abcabca, you can type it in $7$ operations if you type all the characters one by one. However, you can type it in $5$ operations if you type the string abc first and then copy it and type the last character.\n\nIf you have to type string aaaaaaaaa, the best option is to type $4$ characters one by one, then copy the string, and then type the remaining character.\n\nPrint the minimum number of operations you need to type the given string.",
    "tutorial": "Let's consider $s[i; j)$ as a substring of string $s$ from position $i$ to position $j$ ($j$ is not included). Let's iterate over all lenghts of the copied prefix from $\\textstyle{\\left|{\\frac{n}{2}}\\right|}$ to 0 inclusive, and then if $s[0; len) = s[len; 2 \\cdot len)$ then answer will be $min(n, n - len + 1)$ and iterating over smaller lenghts is not necessary.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "954",
    "index": "C",
    "title": "Matrix Walk",
    "statement": "There is a matrix $A$ of size $x × y$ filled with integers. For every $i\\in[1...x]$, $j\\in[1..y]$ $A_{i, j} = y(i - 1) + j$. Obviously, every integer from $[1..xy]$ occurs exactly once in this matrix.\n\nYou have traversed some path in this matrix. Your path can be described as a sequence of visited cells $a_{1}$, $a_{2}$, ..., $a_{n}$ denoting that you started in the cell containing the number $a_{1}$, then moved to the cell with the number $a_{2}$, and so on.\n\nFrom the cell located in $i$-th line and $j$-th column (we denote this cell as $(i, j)$) you can move into one of the following cells:\n\n- $(i + 1, j)$ — only if $i < x$;\n- $(i, j + 1)$ — only if $j < y$;\n- $(i - 1, j)$ — only if $i > 1$;\n- $(i, j - 1)$ — only if $j > 1$.\n\nNotice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know $x$ and $y$ exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer $a_{1}$, then move to the cell containing $a_{2}$ (in one step), then move to the cell containing $a_{3}$ (also in one step) and so on. Can you choose $x$ and $y$ so that they don't contradict with your sequence of moves?",
    "tutorial": "You can notice that moves of kind $(i - 1, j)$ and $(i + 1, j)$ are changing value $x$ to $x - m$ and $x + m$. Thus, you can determine $m$ by checking adjacent nodes in the path. The answer is YES if there are one or zero distinct values of differences not counting difference of $1$. You can also set $n$ to arbitrary big value, it doesn't really matter until you can fit all values. $10^{9}$ will work just fine. Finally, knowing $n$ and $m$, simulate the process and check that all moves are valid. Overall complexity: $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "954",
    "index": "D",
    "title": "Fight Against Traffic",
    "statement": "Little town Nsk consists of $n$ junctions connected by $m$ bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.\n\nIn order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction $s$ to work located near junction $t$. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.\n\nYou are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between $s$ and $t$ won't decrease.",
    "tutorial": "Let's use bfs to calculate the smallest distances to all vertices from the vertex $s$ and from the vertex $t$. These will be $d_{s}[i]$ and $d_{t}[i]$ for all $i$. $d_{s}[t] = d_{t}[s] = D$ is the the current smallest distance between $s$ and $t$. What you need is to iterate over all pairs $(u, v)$ and check if the edge between them doesn't exist and neither $(d_{s}[u] + d_{t}[v] + 1)$ nor $(d_{s}[v] + d_{t}[u] + 1)$ is smaller than $D$. Overall complexity: $O(n^{2})$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "954",
    "index": "E",
    "title": "Water Taps",
    "statement": "Consider a system of $n$ water taps all pouring water into the same container. The $i$-th water tap can be set to deliver any amount of water from $0$ to $a_{i}$ ml per second (this amount may be a real number). The water delivered by $i$-th tap has temperature $t_{i}$.\n\nIf for every $i\\in[1,n]$ you set $i$-th tap to deliver exactly $x_{i}$ ml of water per second, then the resulting temperature of water will be $\\frac{\\frac{\\hbar}{\\hbar}^{2}\\,x_{i}t_{i}}{\\frac{\\hbar}{\\hbar}}{x_{i}}$ (if $\\sum_{i=1}^{n}x_{i}=0$, then to avoid division by zero we state that the resulting water temperature is $0$).\n\nYou have to set all the water taps in such a way that the resulting temperature is exactly $T$. What is the maximum amount of water you may get per second if its temperature has to be $T$?",
    "tutorial": "The following greedy strategy work. Let's turn all the taps at full power. If total temperature is greater than $T$ then we would like to decrease power on some taps with higher temperature. We want to decrease as low power as possible, so we should prioritize taps with the highest temperature. Sort all taps by temperature and find the total power on suffix you should decrease to have equal temperatures. This can be done with binary search. The same works for smaller initial temperature. Overall complexity: $O(n\\log n)$.",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "954",
    "index": "F",
    "title": "Runner's Problem",
    "statement": "You are running through a rectangular field. This field can be represented as a matrix with $3$ rows and $m$ columns. $(i, j)$ denotes a cell belonging to $i$-th row and $j$-th column.\n\nYou start in $(2, 1)$ and have to end your path in $(2, m)$. From the cell $(i, j)$ you may advance to:\n\n- $(i - 1, j + 1)$ — only if $i > 1$,\n- $(i, j + 1)$, or\n- $(i + 1, j + 1)$ — only if $i < 3$.\n\nHowever, there are $n$ obstacles blocking your path. $k$-th obstacle is denoted by three integers $a_{k}$, $l_{k}$ and $r_{k}$, and it forbids entering any cell $(a_{k}, j)$ such that $l_{k} ≤ j ≤ r_{k}$.\n\nYou have to calculate the number of different paths from $(2, 1)$ to $(2, m)$, and print it modulo $10^{9} + 7$.",
    "tutorial": "There is a simple dynamic programming solution that works in $O(m)$. Let's try to improve it. Firstly, if there are no obstacles in some column $i$ and we have calculated the number of paths to every cell of the previous column, then we may get the values in column $i$ by multiplying the vector of values in column $i - 1$ by the following matrix: $\\left(\\begin{array}{l l l}{1}&{1}&{0}\\\\ {1}&{1}&{1}\\\\ {0}&{1}&{1}\\end{array}\\right)$ Then we may use binary exponentiation to skip long segments without obstacles in $O(logk)$, where $k$ is the length of the segment. Let's try to modify this matrix if we have to forbid some rows. All we need to change is to set every value in $i$-th row to $0$ if $i$-th row is forbidden. So we may skip long segments not only if they don't contain any obstacles, but also if the set of forbidden rows doesn't change on this segment. So the solution is the following: divide the whole matrix into $2n + 1$ segments by the endpoints of the obstacles, then in every segment the set of forbidden rows doesn't change (so we can skip it using fast matrix exponentiation).",
    "tags": [
      "dp",
      "matrices",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "954",
    "index": "G",
    "title": "Castle Defense",
    "statement": "Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into $n$ sections. At this moment there are exactly $a_{i}$ archers located at the $i$-th section of this wall. You know that archer who stands at section $i$ can shoot orcs that attack section located at distance not exceeding $r$, that is all such sections $j$ that $|i - j| ≤ r$. In particular, $r = 0$ means that archers are only capable of shooting at orcs who attack section $i$.\n\nDenote as \\underline{defense level} of section $i$ the total number of archers who can shoot at the orcs attacking this section. \\underline{Reliability} of the defense plan is the minimum value of defense level of individual wall section.\n\nThere is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of $k$ archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.",
    "tutorial": "Firstly, if we may obtain reliability at least $x$, then we may obtain reliability not less than $x - 1$ with the same number of archers. So we may use binary search and check whether we may obtain reliability at least $x$. How can we check it? Let's find the leftmost section such that its defense level is less than $x$. Let its index be $i$. We obviously have to add some archers controlling this section, and since every section to the left of it is already controlled, the best option where to add archers is the section with index $min(i + r, n)$. After we added enough archers, we move to next section such that its defense level is less than $x$ and do the same. If we run out of archers without protecting all the sections, then it's impossible to obtain reliability $x$. To do checking in $O(n)$, we may use prefix sums or \"sliding window\" technique.",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "954",
    "index": "H",
    "title": "Path Counting",
    "statement": "You are given a rooted tree. Let's denote $d(x)$ as depth of node $x$: depth of the root is $1$, depth of any other node $x$ is $d(y) + 1$, where $y$ is a parent of $x$.\n\nThe tree has the following property: every node $x$ with $d(x) = i$ has exactly $a_{i}$ children. Maximum possible depth of a node is $n$, and $a_{n} = 0$.\n\nWe define $f_{k}$ as the number of unordered pairs of vertices in the tree such that the number of edges on the simple path between them is equal to $k$.\n\nCalculate $f_{k}$ modulo $10^{9} + 7$ for every $1 ≤ k ≤ 2n - 2$.",
    "tutorial": "At first when we read the problem, a simple solution comes to our mind, take a look at the LCA (Lowest Common Ancestor) of that starting and ending vertices of the path and then use combinatorics to calculate the number of the paths, but after trying to implement this or solve this on paper it doesn't seem to be easy at all and it may even be impossible to implement this. So lets try to solve this problem in a different way. For calculating the answer, we count the number of times each path starts or ends at every vertex, and then divide them by $2$ to get the answer for each vertex. For calculating the answer to the above, it is easy to see that all vertices with the same height have the same number of paths going through them, so if we calculate the number of paths going through one of them and then multiply it by the number of the vertices in that height (let it be $c_{h}$) it gets equal to our answer. We can calculate the answer for a certain height. So to do that, we divide the paths into two types, paths that go only into the subtree of a vertex (let's call it $d_{h}$), and paths that go up (let's call it $u_{h}$). For the ones that are in the subtree, it is easy to see if there are at least $k$ other vertices that go down, we can go all paths going down (let the number of them be $p_{h, k}$), and the answer for this part, equals to: $d_{k}=\\sum_{h=1}^{n}c_{h}\\times p_{h,k}$ For the ones that go up, we use dynamic-programming, and we define $dp_{h, k}$ the number of paths that start at a vertex with height $h$ and have length $k$ and do not use the leftmost edge exiting the vertex at height $h$. To update this either we go down on one of the $a_{h} - 1$ paths and then we go through a path of length $k - 1$, or we go up and get a path of length $k - 1$ starting at a vertex from height $h - 1$, so the answer for this one equals to: $u_{k}=\\sum_{h=1}^{n}c_{h}\\times d p_{h,k}$ Now $f_{k}={\\frac{d_{k}+u_{k}}{2}}$. And the final complexity of the solution will be $O(n^{2})$, but because of the large constant of the solution the time limit is higher.",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "954",
    "index": "I",
    "title": "Yet Another String Matching Problem",
    "statement": "Suppose you have two strings $s$ and $t$, and their length is equal. You may perform the following operation any number of times: choose two different characters $c_{1}$ and $c_{2}$, and replace every occurence of $c_{1}$ in both strings with $c_{2}$. Let's denote the distance between strings $s$ and $t$ as the minimum number of operations required to make these strings equal. For example, if $s$ is abcd and $t$ is ddcb, the distance between them is $2$ — we may replace every occurence of a with b, so $s$ becomes bbcd, and then we may replace every occurence of b with d, so both strings become ddcd.\n\nYou are given two strings $S$ and $T$. For every substring of $S$ consisting of $|T|$ characters you have to determine the distance between this substring and $T$.",
    "tutorial": "Unfortunately, it seems we failed to eliminate bitset solutions. The approach in our model solution is the following: Firstly, let's try to find some \"naive\" solution for calculating the distance between two strings. We may build an undirected graph where vertices represent letters, and edges represent that one letter must be transformed into another. Then all letters in the same component should become one letter, so the answer is the number of distinct letters minus the number of components. Then let's get back to original problem. For every substring of $S$ we have to find which letters have to be merged to make it equal with $T$. This can be done with the help of FFT: to find all positions in substrings of $S$ with character $a$ that coincide with occurences of $b$ in $T$, we may compute a convolution of two following arrays: set $1$ to every position in $S$ where occurs $a$, and to every position in $T$ where $b$ occurs (all other elements should be $0$). After trying these convolutions for every pair of different characters, we compute the answer for every substring using DFS (or any other method).",
    "tags": [
      "fft",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "955",
    "index": "A",
    "title": "Feed the cat",
    "statement": "After waking up at $hh$:$mm$, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is $H$ points, moreover each minute without food increases his hunger by $D$ points.\n\nAt any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs $C$ roubles and decreases hunger by $N$ points. Since the demand for bakery drops heavily in the evening, there is a special $20%$ discount for buns starting from $20$:$00$ (note that the cost might become rational). Of course, buns cannot be sold by parts.\n\nDetermine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.",
    "tutorial": "It's optimal to buy buns either right after waking up or at $20$:$00$ (if possible) because between the awakening and $20$:$00$ cost doesn't change but cat's hunger does. There was one extra case when Andrew wakes up after $20$:$00$ and has only one possible option of buying everything since he cannot turn back time.",
    "code": "hh, mm = map(int, input().split())\nH, D, cost, nutr = map(int, input().split())\n \nhh = 60 * hh + mm\nif hh >= 1200:\n    print('{:.4f}'.format((H + nutr - 1) // nutr * cost * 0.8))\nelse:\n    print('{:.4f}'.format(min((H + nutr - 1) // nutr * cost, (H + (1200 - hh) * D + nutr - 1) // nutr * cost * 0.8)))",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "955",
    "index": "B",
    "title": "Not simply beatiful strings",
    "statement": "Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of $a$-s and others — a group of $b$-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.\n\nYou're given a string $s$. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.",
    "tutorial": "Since order of letters in adorable strings doesn't matter, it doesn't matter in the initial string as well. Let $d$ be the number of distinct letters in $s$. Consider the following cases one after another: If $|s| < 4$ answer is <<No>> since lengths of adorable strings cannot be less than two; If $d$ is more than $4$ answer is also <<No>> since adorable strings contain two distinct letters; If $d$ is equal to $4$ answer is always <<Yes>> (we give two types of letters to string one and other two to string two); If $d$ is equal to three answer is also <<Yes>> (based on the fact that length of $s$ is no less than $4$); If $d$ is equal to two answer depends on whether there's a letter occuring only once (because that means that one of the strings will consist of letters of the same kind); If all letters are the same, answer is <<No>> (same as the previous case).",
    "code": "from collections import Counter\nd = Counter(input())\n \nif sum(d.values()) < 4 or len(d) > 4 or len(d) == 1:\n    print('No')\nelif len(d) >= 3:\n    print('Yes')\nelif any(d[k] == 1 for k in d):\n    print('No')\nelse:\n    print('Yes')",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "955",
    "index": "C",
    "title": "Sad powers",
    "statement": "You're given $Q$ queries of the form $(L, R)$.\n\nFor each query you have to find the number of such $x$ that $L ≤ x ≤ R$ and there exist integer numbers $a > 0$, $p > 1$ such that $x = a^{p}$.",
    "tutorial": "Let's fix some power $p$. It's obvious that there are no more than $10^{\\frac{13}{p}}$ numbers $x$ such that $x^{p}$ does not exceed $10^{18}$. At the same time, only for $p = 2$ this amoung is relatively huge; for all other $p  \\ge  3$ the total amount of such numbers will be of the order of $10^{6}$. Let's then generate all of them and dispose of all perfect squares among them. Then answer to query $(L, R)$ is equal to the amount of generated numbers between $L$ and $R$ plus some perfect squared in range. The first value can be calculated via two binary searches. The second one is $\\lfloor{\\sqrt{R}}\\rfloor-\\lfloor{\\sqrt{L-1}}\\rfloor$. Note that due to precision issues the standard sqrt might produce incorrect values, so you can use additional binary searches instead. Complexity: $O(10^{6}+q\\cdot\\log10^{18})$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n//#pragma GCC optimize(\"Ofast, unroll-loops\")\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <unordered_set>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <random>\n#include <set>\n#include <cassert>\n#include <functional>\n#include <queue>\n#include <numeric>\n#include <bitset>\n#include <iterator>\n \nusing namespace std;\n \nconst int N = 303, M = 18;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nvector<ll> cand;\n \nll root(ll x) {\n\tll l = 0, r = 1e9 + 1;\n\twhile (l < r - 1) {\n\t\tll m = (l + r) / 2;\n\t\tif (m * m > x)\n\t\t\tr = m;\n\t\telse\n\t\t\tl = m;\n\t}\n\treturn l;\n}\n \nvoid solve() {\n\tll l = read<ll>(), r = read<ll>();\n\tll ans = upper_bound(all(cand), r) - lower_bound(all(cand), l);\n\tans += root(r) - root(l - 1);\n\tprintf(\"%lld\\n\", ans);\n}\n \nvoid precalc() {\n\tll U = 1e18;\n\tvector<ll> _cand = { 1 };\n\tfor (ll i = 2; i <= 1e6; i++)\n\t\tfor (ll curr = i * i * i; curr <= U; curr *= i) {\n\t\t\t_cand.push_back(curr);\n\t\t\tif (curr > U / i) break;\n\t\t}\n \n\tsort(all(_cand));\n\t_cand.erase(unique(all(_cand)), _cand.end());\n \n\tfor (const ll &u : _cand) {\n\t\tll x = root(u);\n\t\tif (x * x == u) continue;\n\t\tcand.push_back(u);\n\t}\n \n    debug(\"Precalc: %.3f\\n\", (double)(clock()) / CLOCKS_PER_SEC);\n}\n \nsigned main() {\n    precalc();\n\tint t = read();\n    clock_t tot = clock();\n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\t//debug(\"Test: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n    debug(\"Total Time: %.3f\\n\", (double)(clock() - tot) / CLOCKS_PER_SEC);\n}",
    "tags": [
      "binary search",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "955",
    "index": "D",
    "title": "Scissors",
    "statement": "Jenya has recently acquired quite a useful tool — $k$-scissors for cutting strings. They are generally used for cutting out two non-intersecting substrings of length $k$ from an arbitrary string $s$ (its length should be at least $2·k$ in order to perform this operation) and concatenating them afterwards (preserving the initial order). For example, with the help of $2$-scissors you can cut $ab$ and $de$ out of $abcde$ and concatenate them into $abde$, but not $ab$ and $bc$ since they're intersecting.\n\nIt's a nice idea to test this tool before using it in practice. After looking through the papers, Jenya came up with two strings $s$ and $t$. His question is whether it is possible to apply his scissors to string $s$ such that the resulting concatenation contains $t$ as a substring?",
    "tutorial": "Denote $lpos(x)$ - the minimum index in $s$ that prefix of $t$ of length $x$ might start at, provided $lpos(x) + x  \\ge  k$ (so this prefix can be enclosed in some $k$-substring of $s$ as a suffix) or $- 1$ if there are none. Denote $rpos(x)$ in the same manner - the maximum index in $s$ that suffix of $t$ of length $x$ might end at, under the same conditions (enclosing suffix in some $k$-substring of $s$ as a prefix). It's clear that these array allow us to iterate over all possible prefix/suffix partitions of $t$ and check their correctness. Note that $rpos$ is calculated as $lpos$ on reversed strings. How do we obtain $lpos$? Let's calculate $z$-function of $s$ with respect to $t$ and say that $z(i)$ is the maximum prefix of $t$ starting at position $i$ in $s$. Which $z(i)$ might influence $lpos(x)$? First of all, they must satisfy $z(i)  \\ge  x$. Second, as mentioned above, $i + x  \\ge  k$. This allows us to apply all updates naively and achieve $O(n^{2})$. To speed this up we will iterate over $z$ in decreasing order and maintain viewed indexes in a set in such a way that at the moment we are up to calculate $lpos(x)$ all $i$-s such that $z(i)  \\ge  x$ will be in. Then $lpos(x)$ will be equal to minimum $j$ in the set satisfying $j  \\ge  k - x$. This allows us to reduce the complexity to $O(n\\log n)$. Reverse both $s$ and $t$ and calculate $rpos$ in the same way. Then the only thing left is to check whether for some $x  \\le  k$ values $lpos(x)$ and $rpos(m - x)$ can be combined to obtain the answer.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n//#pragma GCC optimize(\"Ofast, unroll-loops\")\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <unordered_set>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <random>\n#include <set>\n#include <cassert>\n#include <functional>\n#include <queue>\n#include <numeric>\n#include <bitset>\n#include <iterator>\n \nusing namespace std;\n \nconst int N = 303, M = 18;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nint n, m, k;\n \nvector<int> zf(string s, string t) {\n\ts = t + '#' + s;\n\tvector<int> z(n + m + 1);\n\tint l = 0, r = 1;\n\tfor (int i = 1; i <= n + m; i++) {\n\t\tif (i < r) z[i] = min(z[i - l], r - i);\n\t\twhile (i + z[i] <= n + m && s[i + z[i]] == s[z[i]]) z[i]++;\n\t\tif (i + z[i] > r)\n\t\t\ttie(l, r) = mp(i, i + z[i]);\n\t}\n\tvector<int> ret_z(n);\n\tforn(i, n) ret_z[i] = z[i + m + 1];\n\treturn ret_z;\n}\n \nvector<int> pos(string s, string t) {\n\tvector<int> pos(m + 1, -1);\n\tauto z = zf(s, t);\n\tvector<vector<int>> ord(m + 1);\n\tforn(i, n) ord[z[i]].push_back(i);\n \n\tset<int> st;\n\tfor (int i = m; i > 0; i--) {\n\t\tfor (const int v : ord[i])\n\t\t\tst.insert(v);\n\t\tauto it = st.lower_bound(k - i);\n\t\tif (it == st.end()) continue;\n\t\tpos[i] = *it;\n\t}\n\treturn pos;\n}\n \nvoid solve() {\n\tn = read(), m = read(), k = read();\n\tstring s, t; cin >> s >> t;\n \n\tauto z = zf(s, t);\n\tforn(i, n)\n\t\tif (z[i] >= m) {\n\t\t\tputs(\"Yes\");\n\t\t\tint L = min(i + 1, n - 2 * k + 1);\n\t\t\tint R = L + k;\n\t\t\tprintf(\"%d %d\\n\", L, R);\n\t\t\treturn;\n\t\t}\n \n\tauto lpos = pos(s, t);\n \n\treverse(all(s)), reverse(all(t));\n\tauto rpos = pos(s, t);\n \n\treverse(all(s));\n \n\tfor (int i = 1; i <= min(m - 1, k); i++) {\n\t\tif (m - i > k) continue;\n\t\tif (lpos[i] == -1 || rpos[m - i] == -1) continue;\n\t\tint L = lpos[i] + i - 1, R = rpos[m - i] + (m - i) - 1;\n\t\tif (L + R >= n - 1) continue;\n\t\tputs(\"Yes\");\n\t\tprintf(\"%d %d\\n\", lpos[i] + i - (k - 1), n - rpos[m - i] - ((m - i) - 1));\n\t\treturn;\n\t}\n\tputs(\"No\");\n}\n \nvoid precalc() {\n \n}\n \nsigned main() {\n\tint t = 1;\n \n\tprecalc();\n \n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "955",
    "index": "E",
    "title": "Icicles",
    "statement": "Andrew's favourite Krakozyabra has recenly fled away and now he's eager to bring it back!\n\nAt the moment the refugee is inside an icy cave with $n$ icicles dangling from the ceiling located in integer coordinates numbered from $1$ to $n$. The distance between floor and the $i$-th icicle is equal to $a_{i}$.\n\nAndrew is free to choose an arbitrary integer point $T$ in range from $1$ to $n$ inclusive and at time instant $0$ launch a sound wave spreading into both sides (left and right) at the speed of one point per second. Any icicle touched by the wave starts falling at the same speed (that means that in a second the distance from floor to icicle decreases by one but cannot become less that zero). While distance from icicle to floor is more than zero, it is considered passable; as soon as it becomes zero, the icicle blocks the path and prohibits passing.\n\nKrakozyabra is initially (i.e. at time instant $0$) is located at point $\\textstyle{\\frac{1}{2}}$ and starts running in the right direction at the speed of one point per second. You can assume that events in a single second happen in the following order: first Krakozyabra changes its position, and only then the sound spreads and icicles fall; in particular, that means that if Krakozyabra is currently at point $i-{\\frac{1}{2}}$ and the falling (i.e. already touched by the sound wave) icicle at point $i$ is $1$ point from the floor, then Krakozyabra will pass it and find itself at $i+{\\frac{1}{2}}$ and only after that the icicle will finally fall and block the path.\n\nKrakozyabra is considered entrapped if there are fallen (i.e. with $a_{i} = 0$) icicles both to the left and to the right of its current position. Help Andrew find the minimum possible time it takes to entrap Krakozyabra by choosing the optimal value of $T$ or report that this mission is impossible.",
    "tutorial": "Fix some point $T$ and launch the wave. Icicle at $i$ will reach the floor in $f_{T}(i) = a_{i} + |T - i|$ seconds. Krakozyabra will definitely stop at minimum icicle $j$ such that $f_{T}(j) < j$ and wait for something to the left of it to fall. Note that some icicle to the right of $j$ might also fall earlier than $j$ itself. So the answer for this fixed $T$ is $max(min_{1  \\le  i < j}f_{T}(i), min_{j  \\le  i  \\le  n}f_{T}(i))$. This approach gives us a $O(n^{2})$ solution. How to speed this up? Let's get rid of the absolute value. For $i  \\le  T$ absolute value is unfolded as $f_{T}(i) = a_{i} + T - i$ and for $i > T$ as $f_{T}(i) = a_{i} - T + i$. Rewrite the inequality $f_{T}(i) < i$ according to the observations above. It's easy to see that for $i  \\le  T$ it is equal to $T < 2 \\cdot i - a_{i}$ and for $i > T$ - $a_{i} < T$. Build some range max/min structure and find $j$ assuming $j < T$, and if unsuccessfully - assuming $j  \\le  T$ with respect to the given inequalities. The only thing left is to carefully find minimums on suffix/prefix. Complexity: $O(n\\log n)$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <unordered_set>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <random>\n#include <set>\n#include <cassert>\n#include <functional>\n#include <queue>\n#include <numeric>\n#include <bitset>\n \nusing namespace std;\n \nconst int N = 105000, M = 350;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nll a[N], falls[N];\n \nstruct spt {\n\tvector<vector<ll>> dp;\n\tvector<int> log;\n\tint n;\n\tbool isMax;\n \n\tvoid init(vector<int> a) {\n\t\tfor (int i = 1; i <= n; i++) dp[0][i] = a[i];\n\t\tfor (int k = 1; (1 << k) <= n; k++)\n\t\t\tfor (int i = 1; i + (1 << k) <= n + 1; i++) {\n\t\t\t\tll lval = dp[k - 1][i], rval = dp[k - 1][i + (1 << (k - 1))];\n\t\t\t\tif (isMax)\n\t\t\t\t\tdp[k][i] = max(lval, rval);\n\t\t\t\telse\n\t\t\t\t\tdp[k][i] = min(lval, rval);\n\t\t\t}\n\t}\n \n\tll get(int l, int r) {\n\t\tif (l > r) assert(0);\n\t\tint k = log[r - l + 1];\n\t\tll lval = dp[k][l], rval = dp[k][r - (1 << k) + 1];\n\t\treturn isMax ? max(lval, rval) : min(lval, rval);\n\t}\n \n\tspt(int n, bool isMax = true) : n(n), isMax(isMax) {\n\t\tlog.resize(n + 1);\n\t\tfor (int i = 2; i <= n; i++) log[i] = log[i / 2] + 1;\n \n\t\tdp.resize(20);\n\t\tforn(i, 20) {\n\t\t\tdp[i].resize(n + 1);\n\t\t\tif (!isMax) fill(all(dp[i]), 1e18);\n\t\t}\n\t}\n};\n \n/*\n1. i < T => a[i] + T - i - i < 0 => T < 2i - a[i]\n2. i >= T => a[i] + i - T - i < 0 ==> T > a[i]\nmin(i) : T > a[i]\nif found => ans\n*/\n \nll lm[N], rm[N];\n \nint ws1[N], n;\n \nvoid solve() {\n\tn = read();\n\tfor (int i = 1; i <= n; i++)\n\t\ta[i] = read();\n \n\tll ans = 1e18;\n\tint L = 1, R = 1;\n\tfill_n(lm, N, 1e18), fill_n(rm, N, 1e18);\n \n\tfor (int i = 1; i <= n; i++) ws1[i] = 2 * i - a[i];\n \n\tauto S = spt(n, false);\n\tS.init(vector<int>(a, a + n + 1));\n \n\tauto LS = spt(n, false);\n\tvector<int> la(n + 1);\n\tfor (int i = 1; i <= n; i++) la[i] = a[i] - i;\n\tLS.init(la);\n\tauto RS = spt(n, false);\n\tfor (int i = 1; i <= n; i++) la[i] = a[i] + i;\n\tRS.init(la);\n \n\tfor (int T = 1; T <= n; T++) {\n\t\twhile (L <= T && T >= 2 * L - a[L]) L++;\n \n\t\tint j = -1;\n\t\tif (L <= T) j = L;\n\t\telse {\n\t\t\tint lx = T, rx = n;\n\t\t\tint ind_ans = -1;\n \n\t\t\twhile (lx <= rx) {\n\t\t\t\tint mx = (lx + rx) / 2;\n\t\t\t\tif (S.get(T, mx) >= T) {\n\t\t\t\t\tlx = mx + 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tind_ans = mx;\n\t\t\t\t\trx = mx - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ind_ans == -1) continue;\n\t\t\tj = ind_ans;\n\t\t}\n \n\t\tll lp = 0, rp = 0;\n\t\tdebug(\"[%d -> %d]\\n\", T, j);\n\t\tif (j <= T) {\n\t\t\tlp = LS.get(1, j - 1) + T;\n\t\t\trp = min(LS.get(j, T) + T, RS.get(T, n) - T);\n\t\t}\n\t\telse {\n\t\t\tlp = min(LS.get(1, T) + T, RS.get(T, j - 1) - T);\n\t\t\trp = RS.get(j, n) - T;\n\t\t}\n \n\t\tdebug(\"%lld %lld\\n\", lp, rp);\n \n\t\tans = min(ans, max(lp, rp));\n\t}\n \n\tif (ans == 1e18)\n\t\tputs(\"-1\");\n\telse\n\t\tprintf(\"%lld\\n\", ans);\n}\n \nvoid precalc() {\n \n}\n \nsigned main() {\n\tint t = 1;\n \n\tprecalc();\n \n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [],
    "rating": 2900
  },
  {
    "contest_id": "955",
    "index": "F",
    "title": "Heaps",
    "statement": "You're given a tree with $n$ vertices rooted at $1$.\n\nWe say that there's a $k$-ary heap of depth $m$ located at $u$ if the following holds:\n\n- For $m = 1$ $u$ itself is a $k$-ary heap of depth $1$.\n- For $m > 1$ vertex $u$ is a $k$-ary heap of depth $m$ if \\textbf{at least} $k$ of its children are $k$-ary heaps of depth \\textbf{at least} $m - 1$.\n\nDenote $dp_{k}(u)$ as maximum depth of $k$-ary heap in the subtree of $u$ (including $u$). Your goal is to compute $\\sum_{k=1}^{n}\\sum_{u=1}^{n}d p_{k}(u)$.",
    "tutorial": "Denote $heap_{k}(u)$ as maximum depth of $k$-ary heap rooted at $u$, and $dp_{k}(u)$ as maximum depth of $k$-ary heap in the subtree of $u$ (including $u$). Let $v_{i}$ - children of vertex $u$; sort them in order of descending $heap_{k}{v_{i}}$. Then $heap_{k}(u) = heap_{k}(v_{k}) + 1$, and $dp_{k}(u) = max(heap_{k}(u), max_{j}(dp_{k}(v_{j})))$. So we can calculate dp for fixed $k$ in $O(n\\log n)$ or in $O(n)$, if we will use $nth_element$, so we can solve the problem in $O(n^{2})$. For simplicity, denote $dp_{k}(1)$ as $p_{k}$. Let's suppose that $k > 1$. Note three facts: $p_{k}  \\le  log_{k}(n)$; $dp_{k}(u)  \\le  2$ when $k\\geq{\\sqrt{n}}$. $heap_{k}(u)  \\ge  heap_{k + 1}(u)$. So we can solve the problem in $O(n{\\sqrt{n}})$. Let's solve task in $O(n)$ when $k\\leq{\\sqrt{n}}$. For other $k$'s let's go in descending order, and set the value of dp to $2$ and push this value up to the root for each vertices, that have exactly $k$ children. Note, that the total number of vertices visited in pushes does not exceed $n$ (Because if we arrive at vertex with $dp = 2$, it is useless to go up, because everything there has already been updated. Each vertex will be added exactly one time, so complexity of this part is $O(n)$. Let's use this idea to solve the problem in $n^{\\frac{1}{3}}$. For each $k\\leq n^{{\\frac{1}{3}}}$ let's solve in $O(n)$, and for $k\\geq{\\sqrt{n}}$ let's use the idea above. And when $n^{\\frac{1}{3}}\\leq k\\leq{\\sqrt{n}}$, $dp_{k}(u)$ does not exceed $3$. Let $f_{3}(u)$ will be minimal $k$, such that $heap_{k}(u)$ is equal to $3$. By definition, $u$ will have at least $k$ children, which are the heaps of depth 2, that is also vertices with at least $k$ children. Let's sort $v$ by number of their children; Then answer for $u$ will be maximal $k$, such that $children(v_{k})  \\ge  k$. Let's precalculate it, and when let's go in descending order by $k$ pushing up value $3$ from each $u$ with $f_{3}(u) = k$. The total number of vertices visited in pushes does not exceed $2 \\cdot n$ (At worst case, in each vertex will be pushed at first with value $2$, and then with value $3$). So we can solve the problem in $O(n^{\\frac{1}{3}})$, which is better but still not enough. Let $val(u, depth)$ - maximal $k > 1$, such that vertex $u$ contain $k$-ary heap of depth $depth$ (or $- 1$, if there are no such vertex). This dp have $n\\log n$ states; To recalculate $val(u, depth)$ we need to sort $val(v_{i}, depth - 1)$ by descending order, and find maximal $k$, such that $val(v_{k}, depth - 1)  \\ge  k$. So, with sort, complexity of this solution will be $O(n\\log^{2}n)$. Let's go in descending order by $k$ pushing up value $x$ from each $u$ with $val(u, x) = k$. The total number of vertices visited in pushes does not exceed $n \\cdot logn$ because $dp_{k}(u)  \\le  log_{k}(n)$. So, the complexity of this solution wil be $O(n\\log n)$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <unordered_set>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <random>\n#include <set>\n#include <cassert>\n#include <functional>\n#include <queue>\n#include <numeric>\n#include <bitset>\n \nusing namespace std;\n \nconst int N = 300500, M = 20;\n \nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n \ntypedef long long ll;\n \ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n \nvector<int> g[N];\nvector<int> children[N];\nint p[N], ch[N];\nint dp[N][M], n;\n \nvoid dfs_init(int u, int e) {\n\tp[u] = e;\n\tfor (const int &v : g[u])\n\t\tif (v != e) {\n\t\t\tch[u]++;\n\t\t\tdfs_init(v, u);\n\t\t\tchildren[u].push_back(v);\n\t\t}\n}\n \nvector<pii> up[N];\nint val[N];\nint vis = 0;\n \nvoid dfs(int u) {\n\tfor (const int &v : children[u]) dfs(v);\n \n\tauto &_dp = dp[u];\n\t_dp[1] = n;\n \n\tfor (int k = 2; k < M; k++) {\n\t\tvector<int> heaps;\n\t\tfor (const int &v : children[u])\n\t\t\tif (dp[v][k - 1] != -1) heaps.push_back(dp[v][k - 1]);\n\t\tsort(all(heaps), greater<int>());\n\t\tfor (int sz = (int)heaps.size() - 1; sz > 0; sz--) \n\t\t\tif (heaps[sz] >= sz + 1) {\n\t\t\t\t_dp[k] = sz + 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif (_dp[k] != -1)\n\t\t\tup[_dp[k]].emplace_back(u, k), vis++;\n\t}\n}\n \nll ans = 0;\n \nint dfs_one(int u) {\n\tif (!ch[u]) {\n\t\tans++;\n\t\treturn 1;\n\t}\n\tint mx = 0;\n\tfor (const int &v : children[u])\n\t\tmx = max(mx, dfs_one(v));\n\tans += mx + 1;\n\treturn mx + 1;\n}\n \nvoid solve() {\n\tn = read();\n\tforn(i, n - 1) {\n\t\tint u = read(), v = read();\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n \n\tdfs_init(1, -1);\n\tfill_n(&dp[0][0], N * M, -1);\n \n\tdfs(1);\n\tdfs_one(1);\n \n\tll add = n;\n\tfill_n(val, N, 1);\n\t\n\tfprintf(stderr, \"%d\\n\", vis);\n \n\tfor (int k = n; k > 1; k--) {\n\t\tfor (const auto &Q : up[k]) {\n\t\t\tint u = Q.first, v = Q.second;\n\t\t\tfor (; u != -1 && val[u] < v; u = p[u])\n\t\t\t\tadd += v - val[u], val[u] = v;\n\t\t}\n\t\tans += add;\n\t}\n \n\tprintf(\"%lld\\n\", ans);\n}\n \nvoid precalc() {\n \n}\n \nsigned main() {\n\tint t = 1;\n \n\tprecalc();\n \n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "957",
    "index": "A",
    "title": "Tritonic Iridescence",
    "statement": "Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.\n\nArkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into $n$ consecutive segments, each segment needs to be painted in one of the colours.\n\nArkady has already painted some (possibly none or all) segments and passes the paintbrush to you. You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour. Two ways are considered different if and only if a segment is painted in different colours in them.",
    "tutorial": "The problem can be solved in different approaches. Here we describe one based on manually finding out all cases. What causes the answer to be \"Yes\"? Of course, there cannot be adjacent segments that already have the same colour; but what else? We can figure out that whenever two consecutive question marks appear, there are at least two ways to fill them. But the samples lead us to ponder over cases with one single question mark: a question mark can be coloured in two different colours if it lies on the boundary of the canvas, or is between two adjacent segments of the same colour. Putting it all together, we get a simple but correct solution. There surely are dynamic programming solutions to this problem, and if you'd like a harder version, try this USACO problem. So to me seems like a notorious coincidence ._.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid NO() {\n\tputs(\"No\");\n\texit(0);\n}\nvoid YES() {\n\tputs(\"Yes\");\n\texit(0);\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tfor(int i = 0; i < n - 1; ++i)\n\t\tif(s[i] != '?' && s[i] == s[i+1])\n\t\t\tNO();\n\tfor(int i = 0; i < n; ++i) if(s[i] == '?') {\n\t\tif(i == 0 || i == n - 1) YES();\n\t\tif(s[i+1] == '?') YES();\n\t\tif(s[i-1] == s[i+1]) YES();\n\t}\n\tNO();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "959",
    "index": "A",
    "title": "Mahmoud and Ehab and the even-odd game",
    "statement": "Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer $n$ and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer $a$ and subtract it from $n$ such that:\n\n- $1 ≤ a ≤ n$.\n- If it's Mahmoud's turn, $a$ has to be even, but if it's Ehab's turn, $a$ has to be odd.\n\nIf the current player can't choose any number satisfying the conditions, he loses. Can you determine the winner if they both play optimally?",
    "tutorial": "It's easy to see that if $n = 0$, the next player loses. If $n$ is even, Mahmoud will choose $a = n$ and win. Otherwise, Mahmoud will have to choose $a < n$. $n$ is odd and $a$ is even, so $n - a$ is odd. Ehab will then subtract it all and win. Therefore, if $n$ is even Mahmoud wins. Otherwise, Ehab wins. $n = 1$ doesn't follow our proof, yet Ehab still wins at it because Mahmoud won't be even able to choose $a$. Time complexity : $O(1)$.",
    "code": "\"#include <iostream>\\nusing namespace std;\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tif (n%2)\\n\\tprintf(\\\"Ehab\\\");\\n\\telse\\n\\tprintf(\\\"Mahmoud\\\");\\n}\"",
    "tags": [
      "games",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "959",
    "index": "B",
    "title": "Mahmoud and Ehab and the message",
    "statement": "Mahmoud wants to send a message to his friend Ehab. Their language consists of $n$ words numbered from $1$ to $n$. Some words have the same meaning so there are $k$ groups of words such that all the words in some group have the same meaning.\n\nMahmoud knows that the $i$-th word can be sent with cost $a_{i}$. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?\n\nThe cost of sending the message is the sum of the costs of sending every word in it.",
    "tutorial": "It's easy to see that for every word, the minimum cost of sending it is the minimum cost of sending any word in its group. For each group, we'll maintain the minimum cost for sending a word in it (let it be $cost_{i}$) and for each word, we'll maintain its group (let it be $group_{i}$). For every word $i$ in the message, we'll add $cost_{groupi}$ to the answer. Time complexity : $O((n + m)log(n) * len)$.",
    "code": "\"#include <iostream>\\n#include <map>\\nusing namespace std;\\nmap<string,int> d;\\nint arr[100005],cost[100005],group[100005];\\nint main()\\n{\\n\\tint n,k,m;\\n\\tcin >> n >> k >> m;\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\tstring s;\\n\\t\\tcin >> s;\\n\\t\\td[s]=i;\\n\\t}\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\tcin >> arr[i];\\n\\t\\tcost[i]=(1<<30);\\n\\t}\\n\\tfor (int i=1;i<=k;i++)\\n\\t{\\n\\t\\tint x;\\n\\t\\tcin >> x;\\n\\t\\twhile (x--)\\n\\t\\t{\\n\\t\\t\\tint a;\\n\\t\\t\\tcin >> a;\\n\\t\\t\\tgroup[a]=i;\\n\\t\\t\\tcost[i]=min(cost[i],arr[a]);\\n\\t\\t}\\n\\t}\\n\\tlong long ans=0;\\n\\twhile (m--)\\n\\t{\\n\\t\\tstring s;\\n\\t\\tcin >> s;\\n\\t\\tans+=cost[group[d[s]]];\\n\\t}\\n\\tcout << ans;\\n}\"",
    "tags": [
      "dsu",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "959",
    "index": "C",
    "title": "Mahmoud and Ehab and the wrong algorithm",
    "statement": "Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:\n\nGiven an undirected tree consisting of $n$ nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge $(u, v)$ that belongs to the tree, either $u$ is in the set, or $v$ is in the set, \\textbf{or both are in the set}. Mahmoud has found the following algorithm:\n\n- Root the tree at node $1$.\n- Count the number of nodes at an even depth. Let it be $evenCnt$.\n- Count the number of nodes at an odd depth. Let it be $oddCnt$.\n- The answer is the minimum between $evenCnt$ and $oddCnt$.\n\nThe depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.\n\nEhab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of $n$ nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.",
    "tutorial": "For $n  \\ge  6$, you can connect nodes $2$, $3$, and $4$ to node $1$ and connect the rest of the nodes to node $2$. The real vertex cover is the set ${1, 2}$ of size $2$ while the found vertex cover will have size $min(3, n - 3)$. As $n  \\ge  6$, that value will be $3$ which is incorrect. For $n < 6$, the answer doesn't exist. There are multiple ways to construct it. One easy way is the star tree. Connect all the nodes to node $1$. The real and the found vertex cover will be simply ${1}$. Another easy way is a path. Connect node $i$ to node $i + 1$ for all $1  \\le  i < n$. The real and the found vertex cover has size $\\lfloor{\\frac{n}{2}}\\rfloor$. Time complexity : $O(n)$.",
    "code": "\"#include <iostream>\\nusing namespace std;\\nint main()\\n{\\n\\tint n;\\n\\tcin >> n;\\n\\tif (n<=5)\\n\\tputs(\\\"-1\\\");\\n\\telse\\n\\t{\\n\\t\\tfor (int i=2;i<=4;i++)\\n\\t\\tprintf(\\\"1 %d\\\\n\\\",i);\\n\\t\\tfor (int i=5;i<=n;i++)\\n\\t\\tprintf(\\\"2 %d\\\\n\\\",i);\\n\\t}\\n\\tfor (int i=2;i<=n;i++)\\n\\tprintf(\\\"1 %d\\\\n\\\",i);\\n}\"",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "959",
    "index": "D",
    "title": "Mahmoud and Ehab and another array construction task",
    "statement": "Mahmoud has an array $a$ consisting of $n$ integers. He asked Ehab to find another array $b$ \\textbf{of the same length} such that:\n\n- $b$ is lexicographically greater than or equal to $a$.\n- $b_{i} ≥ 2$.\n- $b$ is pairwise coprime: for every $1 ≤ i < j ≤ n$, $b_{i}$ and $b_{j}$ are coprime, i. e. $GCD(b_{i}, b_{j}) = 1$, where $GCD(w, z)$ is the greatest common divisor of $w$ and $z$.\n\nEhab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?\n\nAn array $x$ is lexicographically greater than an array $y$ if there exists an index $i$ such than $x_{i} > y_{i}$ and $x_{j} = y_{j}$ for all $1 ≤ j < i$. An array $x$ is equal to an array $y$ if $x_{i} = y_{i}$ for all $1 ≤ i ≤ n$.",
    "tutorial": "Common things : Let's call a number \"ok\" if it could be inserted to array $b$, as a new element, without breaking any of the conditions (i.e it should be coprime with all the previously inserted elements). Let's call the maximum number that could be inserted in the worst case $mx$. For each integer from 2 to $mx$, we'll precompute its prime divisors with sieve. Create an std::set that contains all the numbers from $2$ to $mx$. That set has all the \"ok\" numbers and will be updated each time we insert a new element to array $b$. We'll insert the elements to array $b$ greedily one by one. At index $i$, let $cur$ be the minimum number in the set greater than or equal to $a_{i}$ i.e std::lower_bound(a[i]). If cur isn't equal to $a_{i}$, the lexicographically greater condition is satisfied and we're no longer restricted to $a$, so, starting from index $i + 1$, we'll greedily choose $cur$ to be the first (minimum) number in the set instead. We'll insert $cur$ to $b$. Each time, we'll remove all the integers that aren't coprime with $cur$ from the set. To do that, we'll loop over the multiples of its precomputed prime divisors and remove them from the set. Let $used[i]$ indicate whether some prime is already a factor of one of elements in $b$ (so we shouldn't use it). Each time we insert an element to $b$, we update $used$ by iterating over its precomputed prime divisors and make them all used. We'll start inserting elements to $b$ greedily one by one. To check if a number is \"ok\", we'll iterate over its precomputed prime divisors and check that all of them aren't used. While $a_{i}$ is \"ok\", we'll keep inserting it to $b$. We'll reach an integer that isn't \"ok\". In this case, we'll iterate naiively until we find an integer that is \"ok\" and insert it to $b$. The lexicographically greater condition is now satisfied and we can insert whatever we want (no restriction to $a$). Notice that starting from now, $b$ will be sorted in increasing order. That's because if it's not, we can sort it and reach a better answer without breaking any of the conditions. The naiive solution is to loop starting from 2 until we find an \"ok\" integer for each $i$. However, as the array is sorted, we can loop starting from 2 the first time and then loop starting from $b_{i - 1} + 1$ and save a lot of loops that we're sure will fail! Time complexity : $O(mxlog(mx))$. $mx$ has an order of $\\begin{array}{c l c r}{{\\displaystyle{\\cal{O}}\\displaystyle{\\left((n+\\frac{m a x A i}{l o q(m a x A i)}}\\right)l o g\\displaystyle(n+\\frac{m a x A i}{l o q(m a x A i)}}\\bigg)\\bigg)}}\\end{array}$ because the $n^{th}$ prime is expected to be $O(nlog(n))$ and the number of primes less that $n$ is expected to be $O(\\underline{{{i m}}}_{o p(n)}^{n})$.",
    "code": "\"#include <iostream>\\n#include <vector>\\nusing namespace std;\\nvector<int> d[2000005];\\nbool p[2000005],used[2000005];\\nbool ok(int x)\\n{\\n\\tbool ret=1;\\n\\tfor (int i:d[x])\\n\\tret&=!used[i];\\n\\treturn ret;\\n}\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=2;i<2000005;i++)\\n\\t{\\n\\t\\tif (!p[i])\\n\\t\\t{\\n\\t\\t\\tfor (int x=i;x<2000005;x+=i)\\n\\t\\t\\t{\\n\\t\\t\\t\\td[x].push_back(i);\\n\\t\\t\\t\\tp[x]=1;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tbool eq=1;\\n\\tint cur=2;\\n\\tfor (int i=0;i<n;i++)\\n\\t{\\n\\t\\tint a;\\n\\t\\tscanf(\\\"%d\\\",&a);\\n\\t\\tint out=a;\\n\\t\\tif (eq)\\n\\t\\t{\\n\\t\\t\\twhile (!ok(out))\\n\\t\\t\\tout++;\\n\\t\\t\\tif (out!=a)\\n\\t\\t\\teq=0;\\n\\t\\t}\\n\\t\\telse\\n\\t\\t{\\n\\t\\t\\twhile (!ok(cur))\\n\\t\\t\\tcur++;\\n\\t\\t\\tout=cur;\\n\\t\\t}\\n\\t\\tprintf(\\\"%d \\\",out);\\n\\t\\tfor (int x:d[out])\\n\\t\\tused[x]=1;\\n\\t}\\n}\"",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "959",
    "index": "E",
    "title": "Mahmoud and Ehab and the xor-MST",
    "statement": "Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of $n$ vertices numbered from $0$ to $n - 1$. For all $0 ≤ u < v < n$, vertex $u$ and vertex $v$ are connected with an undirected edge that has weight $u\\oplus v$ (where $\\mathbb{C}$ is the bitwise-xor operation). Can you find the weight of the minimum spanning tree of that graph?\n\nYou can read about complete graphs in https://en.wikipedia.org/wiki/Complete_graph\n\nYou can read about the minimum spanning tree in https://en.wikipedia.org/wiki/Minimum_spanning_tree\n\nThe weight of the minimum spanning tree is the sum of the weights on the edges included in it.",
    "tutorial": "For convenience, let $n$ be the label of the last node not the number of nodes (i.e $n = n_{input} - 1$). Denote $lsb(x) = x&( - x)$ as the value of the least significant bit set to 1 in $x$. The answer is $\\sum_{i=1}^{n}l s b(i)$, which means that node $u$ is connected to node $u\\oplus l s b(u)$ for all $1  \\le  u  \\le  n$ (node $u$ is connected to node $u$ without that bit). Let's take a look at a version of Boruvka's algorithm for the MST. It starts with an empty MST and then at each step, it chooses some components. For each of them, it finds the edge with the minimum cost connecting this component to any other component and adds this edge to the minimum spanning tree. Let's apply this algorithm here. Assume that at step #$x$, the components are of the form of intervals of length $2^{x}$ i.e component #$i$ has nodes in $[i * 2^{x};(i + 1) * 2^{x} - 1]$. Let's see what the algorithm does. Let's see what happens for components where $i$ is odd. Assume the minimum cost for connecting this component is $c$. You can see that $c$ can't be less than $2^{x}$. That's because this intervals contains integers that have all the possible combinations of the first $x$ bits. Take $x = 2$ and $i = 1$, for example: the numbers are (in binary) $100$, $101$, $110$, $111$. All the possible combinations for the first $x$ bits are there! Notice that if you choose $c < 2^{x}$, you're changing the first $x$ bits. We have all possible combinations of them in the component so we'll make a cycle. That makes the minimum cost $2^{x}$. There's always a way to make a connection with cost $2^{x}$ which is connecting the first node of this component with the first node of the previous component (i.e connect node $i * 2^{x}$ with node $(i - 1) * 2^{x}$). Notice that $i*2^{x}\\oplus(i-1)*2^{x}=2^{x}$ because $i$ is odd (Can you see why this is false for even $i$?). After that happens, the 2 components will form one big component and the components will be in the form of intervals of length $2^{x + 1}$ and the algorithm will repeat the same pattern!! Notice that at the beginning, the nodes are of the form of intervals with length 1 so the algorithm will work like that until the MST is constructed. Each node is the first node of its component and its component will have an odd index exactly once because after that it'll be in the middle of another big component. When that happens, it'll be when $2^{x} = lsb(x)$. Therefore, node $u$ adds $lsb(u)$ to the answer! Now let's see how to calculate that quickly. Let $f(x)$ be the number of integers $y$ such that $1  \\le  y  \\le  n$ and $lsb(y) = x$, then $\\sum_{i=1}^{n}l s b(i)=\\sum_{i=1}^{n}f(i)*i$. $f(i) > 0$ if and only if $i$ is a power of 2 so this sum is equivalent to $\\sum_{i=1}^{[l o g(n)]}f(2^{i})*2^{i}$. Basically, the first number $y$ such that $lsb(y) = x$ is $x$ and then the period is $2 * x$. Take 4 to see that. The integers $y$ such that $lsb(y) = 4$ are ${4, 12, 20, 28, etc.}$ Therefore, $f(x)=\\lfloor{\\frac{n-x}{2\\cdot x}}\\rfloor+1$ for $1  \\le  x  \\le  n$ and x is a power of 2. Let's see how the sequence of $lsb(x)$ is constructed. We start with ${1}$ and at the $i^{th}$ step, we copy the sequence and concatenate it to itself and add $2^{i}$ in the middle. $\\{1\\}\\implies\\{1,2,1\\}\\implies\\{1,2,1,4,1,2,1\\}\\implies\\{1,2,1,4,1,2,1,8,1,2,1,4,1,2,1\\}$ Let $f(x)=\\sum_{i=1}^{x}l s b(i)$. Let $dp[i] = f(2^{i} - 1)$. You can see from the pattern above that $dp[i] = 2 * dp[i - 1] + 2^{i - 1}$ for $1 < i$ (with the base case that $dp[1] = 1$). Let's find a recurrence for $f(x)$. Denote $msb(x)$ as the value of the most significant bit set to 1. The sum can be split into 2 parts : the sum from 1 to $msb(x)$ and the sum from $msb(x) + 1$ to $x$. You can see that in the second sum, $lsb(i)$ can never be equal to $msb(x)$, so we can remove that bit safely without affecting the answer. Removing that bit is like xoring with $msb(x)$ which makes the sum start at 1 and end at $x\\oplus m s b(x)$ which is $f(x\\oplus m s b(x))$. Therefore, $f(x)=f(m s b(x))+f(x\\oplus m s b(x))$. The first part can be calculated with the help of our $dp$ because $msb(x)$ is a power of 2 and the second part goes recursively. Basically, for each $i$ such that the $i^{th}$ bit is set to 1, we add $dp[i] + 2^{i}$ to the answer. Time complexity : $O(log(n))$.",
    "code": "\"#include <iostream>\\nusing namespace std;\\nlong long dp[50];\\nint main()\\n{\\n\\tlong long n;\\n\\tscanf(\\\"%I64d\\\",&n);\\n\\tfor (int i=1;i<50;i++)\\n\\tdp[i]=2LL*dp[i-1]+(1LL<<(i-1));\\n\\tn--;\\n\\tlong long ans=0;\\n\\tfor (int i=0;i<50;i++)\\n\\t{\\n\\t\\tif (n&(1LL<<i))\\n\\t\\tans+=dp[i]+(1LL<<i);\\n\\t}\\n\\tprintf(\\\"%I64d\\\",ans);\\n}\"",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "959",
    "index": "F",
    "title": "Mahmoud and Ehab and yet another xor task",
    "statement": "Ehab has an array $a$ of $n$ integers. He likes the bitwise-xor operation and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud $q$ queries. In each of them, he gave Mahmoud 2 integers $l$ and $x$, and asked him to find the number of subsequences of the first $l$ elements of the array such that their bitwise-xor sum is $x$. Can you help Mahmoud answer the queries?\n\nA subsequence can contain elements that are not neighboring.",
    "tutorial": "Let's solve a simpler version of the problem. Assume the queries only ask you to see whether the answer is 0 or positive instead of the exact answer. We can answer all the queries offline. We can keep a set containing all the possible xors of subsequences and update it for each prefix. Initially, the set contains only 0 (the xor of the empty subsequence). For each index $i$ in the array, we can update the set by adding $x\\oplus a_{i}$ to the set for all $x$ in the set. The intuition behind it is that there's a subsequence with xor equal to $x$ (as $x$ is in the set) and if we add $a_{i}$ to it, its xor will be $x\\oplus a_{i}$, so we should add it to the set. That's a slow solution to update the set, but we have some observations:- If $x$ is in the set and $y$ is in the set, $x\\oplus y$ must be in the set. To see that, let $x$ be the xor of some elements and $y$ be the xor of other elements. $x\\oplus y$ must be the xor of the non-common elements (because the common elements will annihilate) so it must be in the set. If $x$ is in the set and $y$ isn't in the set, $x\\oplus y$ can't be in the set. This could be proved by contradiction. Assume $x\\oplus y$ is in the set, then, by the first observation, $(x\\oplus y)\\oplus x$ must be in the set. This is equivalent to $y$ which we said that it isn't in the set. Therefore, $x\\oplus y$ isn't in the set. Basically, if $a_{i}$ is already in the set, we do nothing because updating the set would do nothing but extra operations according to the first observation, and if $a_{i}$ isn't in the set, we don't even waste a single operation without extending the set! That makes the total complexity $O(n + maxAi)$ or $O((n + maxAi)log(maxAi))$ depending on implementation because each element is added to the set exactly once. To solve our problem, let's see the naiive dynamic programming solution. Let $dp[i][x]$ be the number of subsequences of the first $i$ elements with xor $x$. $d p[i][x]=d p[i-1][x]+d p[i-1][x\\oplus a_{i}]$. The intuition behind it is exactly the same as the intuition behind the set construction. Let's prove that $dp[i][x]$ is equal for all $x$ belonging to the set! Let's assume this holds true for $i - 1$ and see what happens in the transition to $i$. Notice that it holds true for $i = 0$. Let $j$ be the value that $dp[i - 1][x]$ is equal to for all $x$ belonging to the set. If $a_{i}$ is in the set, and $x$ is in the set, $x\\oplus a_{i}$ is in the set (observation #1). Therefore, $dp[i - 1][x] = j$ and $d p[i-1][x\\oplus a_{i}]=j$ which makes $dp[i][x] = 2 * j$ for all $x$ in the set. Notice that the set doesn't change so $dp[i][x] = 0$ for all $x$ that aren't in the set. If $a_{i}$ isn't in the set, we have 3 cases for $x$. If $x$ is in the set, $x\\oplus a_{i}$ isn't in the set. Therefore, $dp[i][x] = j + 0 = j$. If $x$ is to be added to the set in this step, $x\\oplus a_{i}$ is in the set. Therefore, $dp[i][x] = 0 + j = j$. Otherwise, $dp[i][x] = 0$. To summarize, we'll maintain the set. For each integer, if it's in the set, we'll just multiply $j$ by 2. Otherwise, we'll update the set. We'll then answer all the queries for that prefix (saying 0 or $j$) depending on whether $x$ is in the set. Time complexity : $O(n + maxAi)$ if you implement the \"set\" with a vector and an array.",
    "code": "\"#include <iostream>\\n#include <vector>\\nusing namespace std;\\n#define mod 1000000007\\nvector<pair<int,int> > v[100005];\\nint arr[100005],a[100005];\\nvector<int> s;\\nbool b[(1<<20)];\\nint main()\\n{\\n\\tint n,q;\\n\\tscanf(\\\"%d%d\\\",&n,&q);\\n\\tfor (int i=0;i<n;i++)\\n\\tscanf(\\\"%d\\\",&arr[i]);\\n\\tfor (int i=0;i<q;i++)\\n\\t{\\n\\t\\tint l,x;\\n\\t\\tscanf(\\\"%d%d\\\",&l,&x);\\n\\t\\tv[l-1].push_back({x,i});\\n\\t}\\n\\ts.push_back(0);\\n\\tb[0]=1;\\n\\tint ans=1;\\n\\tfor (int i=0;i<n;i++)\\n\\t{\\n\\t\\tif (b[arr[i]])\\n\\t\\tans=(ans*2)%mod;\\n\\t\\telse\\n\\t\\t{\\n\\t\\t\\tint tmp=s.size();\\n\\t\\t\\tfor (int x=0;x<tmp;x++)\\n\\t\\t\\t{\\n\\t\\t\\t\\ts.push_back(s[x]^arr[i]);\\n\\t\\t\\t\\tb[s.back()]=1;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor (int x=0;x<v[i].size();x++)\\n\\t\\ta[v[i][x].second]=ans*b[v[i][x].first];\\n\\t}\\n\\tfor (int i=0;i<q;i++)\\n\\tprintf(\\\"%d\\\\n\\\",a[i]);\\n}\"",
    "tags": [
      "bitmasks",
      "dp",
      "math",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "960",
    "index": "A",
    "title": "Check the string",
    "statement": "A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, \\textbf{at least one 'a' and one 'b'} exist in the string.\n\nB now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.\n\nYou have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print \"YES\", otherwise print \"NO\" (without the quotes).",
    "tutorial": "Traverse the string once and check if the ASCII value of all characters is greater than or equal or the ASCII value of the previous character. This ensures that the string does not have a,b,c in wrong order. Also, while traversing the string, keep three separate counters for the number of 'a', 'b' and 'c' along. Now, do a simple check on the condition for the count of 'c'. The hack case for many solutions was to check that the count of 'a' is atleast 1 and the count of 'b' is atleast 1.",
    "code": "#include<bits/stdc++.h>\n#define rep(i,start,lim) for(lld i=start;i<lim;i++)\n#define repd(i,start,lim) for(lld i=start;i>=lim;i--)\n#define scan(x) scanf(\"%lld\",&x)\n#define print(x) printf(\"%lld \",x)\n#define f first\n#define s second\n#define pb push_back\n#define mp make_pair\n#define br printf(\"\\n\")\n#define sz(a) lld((a).size())\n#define YES printf(\"YES\\n\")\n#define NO printf(\"NO\\n\")\n#define all(c) (c).begin(),(c).end()\n#define INF         1011111111\n#define LLINF       1000111000111000111LL\n#define EPS         (double)1e-10\n#define MOD         1000000007\n#define PI          3.14159265358979323\nusing namespace std;\ntypedef long double ldb;\ntypedef long long lld;\nlld powm(lld base,lld exp,lld mod=MOD) {lld ans=1;while(exp){if(exp&1) ans=(ans*base)%mod;exp>>=1,base=(base*base)%mod;}return ans;}\nlld ctl(char x,char an='a') {return (lld)(x-an);}\nchar ltc(lld x,char an='a') {return (char)(x+an);}\n#define bit(x,j) ((x>>j)&1)\ntypedef vector<lld> vlld;\ntypedef pair<lld,lld> plld;\ntypedef map<lld,lld> mlld;\ntypedef set<lld> slld;\n#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define mxm(a,b) a = max(a,b)\n#define mnm(a,b) a = min(a,b)\n#define endl '\\n'\n#define fre freopen(\"1.in\",\"r\",stdin); freopen(\"1.out\",\"w\",stdout);\n#define N 1000005\nint main()\n{\n    //sync;\n    string s;\n    map<char,lld> m;\n    cin>>s;\n    lld k = sz(s);\n    string tmp = \"\";\n    tmp += s[0];\n    rep(i,1,k) if(s[i]!=s[i-1]) tmp+=s[i];\n    rep(i,0,k) m[s[i]]++;\n    if(tmp != \"abc\") return 0*NO;\n    if(m['c']!=m['a'] and m['c']!=m['b']) return 0*NO;\n    if(m['a']>=1 and m['b']>=1) return 0*YES;\n    else return 0*NO;\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "960",
    "index": "B",
    "title": "Minimize the error",
    "statement": "You are given two arrays $A$ and $B$, each of size $n$. The error, $E$, between these two arrays is defined $E=\\sum_{i=1}^{n}(a_{i}-b_{i})^{2}$. You have to perform \\textbf{exactly} $k_{1}$ operations on array $A$ and \\textbf{exactly} $k_{2}$ operations on array $B$. In one operation, you have to choose one element of the array and increase or decrease it by $1$.\n\nOutput the minimum possible value of error after $k_{1}$ operations on array $A$ and $k_{2}$ operations on array $B$ have been performed.",
    "tutorial": "The problem can be interpreted as follows: array $B$ is fixed and a total of $k_{1} + k_{2} = K$ operations allowed on $A$. Let the array $C$ be defined as $Ci = |Ai - Bi|$ Now this is just a simple greedy problem where value of $E=\\sum_{i=1}^{n}C_{i}^{2}$ is to be minimized after exactly $K$ subtraction/addition operations spread over the elements of array $C$. Till $E$ is non-zero, the largest element is chosen and $1$ is subtracted from it. This is done as currently we want to maximize the reduction in error per operation and decreasing an element $x$ by $1$ reduces error by $x^{2} - (x - 1)^{2} = 2 \\cdot x - 1$. Once all the elements become zero, we can use the remaining moves to alternately increase and decrease the same element till we run out of moves. This can be implemented using a priority queue or by sorting the array $C$ and iterating over it. Expected complexity: $O(N \\cdot K \\cdot log(N))$ or $O(N \\cdot log(N))$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\npriority_queue<ll> pq;\n\nint main(){\n    int n, k1, k2, k;\n    cin>>n>>k1>>k2;\n    k = k1+k2;\n    vector<ll> a(n), b(n), arr(n);\n    for(int i=0 ; i<n ; ++i)\n        cin>>a[i];\n    for(int i=0 ; i<n ; ++i){\n        cin>>b[i];\n        arr[i] = abs(a[i]-b[i]);\n        pq.push(arr[i]);\n    }\n    while(k>0){\n        ll curr = pq.top();\n        pq.pop();\n        pq.push(abs(curr-1));\n        k--;\n    }\n    ll ans = 0;\n    while(!pq.empty()){\n        ll curr = pq.top();\n        ans += (curr*curr);\n        pq.pop();\n    }\n    cout<<ans;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "960",
    "index": "C",
    "title": "Subsequence Counting",
    "statement": "Pikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size $n$ has $2^{n} - 1$ non-empty subsequences in it.\n\nPikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence $ - $ Minimum_element_of_subsequence $ ≥ d$\n\nPikachu was finally left with $X$ subsequences.\n\nHowever, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers $X$ and $d$. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than $10^{18}$.\n\nNote the number of elements in the output array should not be more than $10^{4}$. If no answer is possible, print $ - 1$.",
    "tutorial": "Let's call a subsequence valid if the difference of maximum element and minimum element is less than d. For an array of size $n$ with all the elements equal, there are $2^{n} - 1$ non-empty subsequences and all of them are valid. This is because for any subsequence, the difference of maximum element and minimum element is always zero. We will use this observation in constructing the answer. Let's look at the binary representation of $X$. If the $i^{th}$ bit is set in X, we will add $i$ equal elements (let's say $y$) in our final array. However this would give us $2^{i} - 1$ non-empty valid subsequences. To correct this, we will add a separate element $y + d$ in the final array so that the final contribution of $i^{th}$ bit becomes $2^{i}$. We will carry out the same process for all the bits, keeping a counter of the previous In this way, the length of the final array will never exceed 600 elements. Expected Complexity : O(logX * logX)",
    "code": "#include<bits/stdc++.h>\n#define rep(i,start,lim) for(lld i=start;i<lim;i++)\n#define repd(i,start,lim) for(lld i=start;i>=lim;i--)\n#define scan(x) scanf(\"%lld\",&x)\n#define print(x) printf(\"%lld \",x)\n#define f first\n#define s second\n#define pb push_back\n#define mp make_pair\n#define br printf(\"\\n\")\n#define sz(a) lld((a).size())\n#define YES printf(\"YES\\n\")\n#define NO printf(\"NO\\n\")\n#define all(c) (c).begin(),(c).end()\n#define INF         1011111111\n#define LLINF       1000111000111000111LL\n#define EPS         (double)1e-10\n#define MOD         1000000007\n#define PI          3.14159265358979323\nusing namespace std;\ntypedef long double ldb;\ntypedef long long lld;\nlld powm(lld base,lld exp,lld mod=MOD) {lld ans=1;while(exp){if(exp&1) ans=(ans*base)%mod;exp>>=1,base=(base*base)%mod;}return ans;}\nlld ctl(char x,char an='a') {return (lld)(x-an);}\nchar ltc(lld x,char an='a') {return (char)(x+an);}\n#define bit(x,j) ((x>>j)&1)\ntypedef vector<lld> vlld;\ntypedef pair<lld,lld> plld;\ntypedef map<lld,lld> mlld;\ntypedef set<lld> slld;\n#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define mxm(a,b) a = max(a,b)\n#define mnm(a,b) a = min(a,b)\n#define endl '\\n'\n#define fre freopen(\"1.in\",\"r\",stdin); freopen(\"1.out\",\"w\",stdout);\n#define N 1000005\nint main()\n{\n    //sync;\n    lld x,d;\n    vector<lld> ans;\n    cin>>x>>d;\n    lld num = 1, cnt = 0;\n    repd(i,60,1) if(bit(x,i)) {\n        rep(j,0,i) ans.pb(num);\n        cnt++;\n        num+=(d+1);\n    }\n    while(cnt--) ans.pb(num),num+=(d+1);\n    if(x%2) ans.pb(num);\n    cout<<sz(ans)<<endl;\n    for(auto i:ans) cout<<i<<\" \";\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "960",
    "index": "D",
    "title": "Full Binary Tree Queries",
    "statement": "You have a full binary tree having infinite levels.\n\nEach node has an initial value. If a node has value $x$, then its left child has value $2·x$ and its right child has value $2·x + 1$.\n\nThe value of the root is $1$.\n\nYou need to answer $Q$ queries.\n\nThere are $3$ types of queries:\n\n- Cyclically shift the \\textbf{values} of all nodes on the same level as node with value $X$ by $K$ units. (The values/nodes of any other level are not affected).\n- Cyclically shift the \\textbf{nodes} on the same level as node with value $X$ by $K$ units. (The subtrees of these nodes will move along with them).\n- Print the value of every node encountered on the simple path from the node with value $X$ to the root.\n\nPositive $K$ implies right cyclic shift and negative $K$ implies left cyclic shift.\n\nIt is guaranteed that atleast one type $3$ query is present.",
    "tutorial": "Let us define the root of the tree to be at level $L = 1$. Now, the level $L$ for any value $X$ can be found using this formula: $L = 64 -$ (Number of leading unset bits in $X$). In C++, you can conveniently calculate the leading unset bits by using __builtin_clzll($X$). Let us imagine each level of the tree as an array $A_{L}$. Observe that we only need to consider $L$ upto $60$ due to the constraint that $X  \\le  10^{18}$. Queries of type $1$ are equivalent to performing a cyclic shift of $K$ on array $A_{L}$. Queries of type $2$ are equivalent to performing a cyclic shift of $K$ on array $A_{L}$ , $2 \\cdot K$ on array $A_{L + 1}$ , $2^{2} \\cdot K$ on array $A_{L + 2}$ ... $2^{Z} \\cdot K$ on array $A_{L + Z}$ and so on. Since we only care about the first $60$ levels, $0  \\le  Z  \\le  60 - L$. Now,we can store the net shift $S_{L}$ of each level. Note that, for level $L$, we calculate $S_{L}$ under modulo $2^{L - 1}$ because there are exactly $2^{L - 1}$ values in some $A_{L}$. Finally, to answer queries of type $3$, do the following: Let the original index(0-indexed) of $X$ in $A_{L}$ be $P$ ($P = X - 2^{L - 1}$). The new index after the shift will be $\\bar{\\boldsymbol{P}}$ $((P+S_{L})\\;\\mathrm{mod}\\;2^{L-1}+2^{L-1})\\;\\mathrm{mod}\\;2^{L-1}$. The original value at this index was $V=2^{L-1}+{\\bar{P}}$. We can find the parent of this value in the original tree by dividing $V$ by $2$ (Integer Division).Thus, We can now find all the values in the path from $V$ to the root in the original tree. To get the values in the current tree, we just apply the opposite shift at each level to find the value and print it. Let the original value at index $P$ in $A_{L}$ at some level $L$ be $V$. The current value at this position after the shift will be the same as the value at index $\\bar{\\boldsymbol{P}}$ $((P+S_{L}\\cdot-1)\\mathrm{~mod~}2^{L-1}+2^{L-1})\\mathrm{~mod~}2^{L-1}$ in the original array. Let this value be $Z$. Now,$Z=2^{L-1}+\\bar{P}$. Print $Z$ and set $V = V / 2$. Repeat Step $2$ and stop when $V = 0$. Complexities of: Query $1$: $O(1)$. Query $2$: $O(60)$. Query $3$: $O(60)$. Overall: $O(60 \\cdot Q)$ Refer to the code for further understanding.",
    "code": "//Gvs Akhil (Vicennial)\n#include<bits/stdc++.h>\n#define int long long\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define mt make_tuple\n#define ld(a) while(a--)\n#define tci(v,i) for(auto i=v.begin();i!=v.end();i++)\n#define tcf(v,i) for(auto i : v)\n#define all(v) v.begin(),v.end()\n#define rep(i,start,lim) for(long long (i)=(start);i<(lim);i++)\n#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define osit ostream_iterator\n#define INF \t\t0x3f3f3f3f\n#define LLINF       1000111000111000111LL\n#define PI \t\t\t3.14159265358979323\n#define endl '\\n'\n#define trace1(x)                cerr<<#x<<\": \"<<x<<endl\n#define trace2(x, y)             cerr<<#x<<\": \"<<x<<\" | \"<<#y<<\": \"<<y<<endl\n#define trace3(x, y, z)          cerr<<#x<<\":\" <<x<<\" | \"<<#y<<\": \"<<y<<\" | \"<<#z<<\": \"<<z<<endl\n#define trace4(a, b, c, d)       cerr<<#a<<\": \"<<a<<\" | \"<<#b<<\": \"<<b<<\" | \"<<#c<<\": \"<<c<<\" | \"<<#d<<\": \"<<d<<endl\n#define trace5(a, b, c, d, e)    cerr<<#a<<\": \"<<a<<\" | \"<<#b<<\": \"<<b<<\" | \"<<#c<<\": \"<<c<<\" | \"<<#d<<\": \"<<d<<\" | \"<<#e<< \": \"<<e<<endl\n#define trace6(a, b, c, d, e, f) cerr<<#a<<\": \"<<a<<\" | \"<<#b<<\": \"<<b<<\" | \"<<#c<<\": \"<<c<<\" | \"<<#d<<\": \"<<d<<\" | \"<<#e<< \": \"<<e<<\" | \"<<#f<<\": \"<<f<<endl\nconst int N=1000006;\nusing namespace std;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef long long ll;\ntypedef vector<long long> vll;\ntypedef vector<vll> vvll;\ntypedef long double ld;\ntypedef pair<int,int> ii;\ntypedef vector<ii> vii;\ntypedef vector<vii> vvii;\ntypedef tuple<int,int,int> iii;\ntypedef set<int> si;\ntypedef complex<double> pnt;\ntypedef vector<pnt> vpnt;\ntypedef priority_queue<ii,vii,greater<ii> > spq;\nconst ll MOD=1000000007LL;\ntemplate<typename T> T gcd(T a,T b){if(a==0) return b; return gcd(b%a,a);}\ntemplate<typename T> T power(T x,T y,ll m=MOD){T ans=1;while(y>0){if(y&1LL) ans=(ans*x)%m;y>>=1LL;x=(x*x)%m;}return ans%m;}\nint shift[66];\ninline int getlev(int x){\n\tint z=__builtin_clzll(x);\n\treturn 64-z;\n}\ninline int getmod(int x){\n\treturn (1LL<<(x-1));\n}\nvoid addshift(int x,int k){\n\tint m=getmod(x);\n\tif(k>=m) k%=m;\n\tshift[x]+=k;\n\tif(shift[x]>=m) shift[x]-=m;\n\tif(shift[x]<0) shift[x]+=m;\t\n}\nint getorig(int V,int l){\n\tint fval=(1LL<<(l-1)); // 2^(L-1)\n\tint mod=getmod(l);\n\tint P= V-fval; \n\tint Z= fval+((P-shift[l])%mod + mod)%mod;\n\treturn Z;\n}\nint32_t main(){\n\tsync;\n\tint q; cin>>q;\n\twhile(q--){\n\t\tint t,x,k;\n\t\tcin>>t>>x;\n\t\tint l=getlev(x);\n\t\tif(t==1){ \n\t\t\tcin>>k; k%=getmod(l);\n\t\t\taddshift(l,k);\n\t\t}\n\t\telse if(t==2){// propogating\n\t\t\tcin>>k; \n\t\t\tk%=getmod(l);\n\t\t\tif(k<0) k+=getmod(l);\n\t\t\t int curr=1;\n\t\t\tfor(int i=l;i<=60;i++){\n\t\t\t\taddshift(i,k*curr);\n\t\t\t\tcurr<<=1;\n\t\t\t}\n\t\t}\n\t\telse{ // printing\n\t\t\tint P= x - (1LL<<(l-1)); // Finding index in array\n\t\t\tint V= (1LL<<(l-1)) + ((P+shift[l])%(1LL<<(l-1)) + (1LL<<(l-1)) )%(1ll<<(l-1)); //Finding original value at the new index of X after performing the shift.\n\t\t\tfor(int i=l;i>=1;i--){\n\t\t\t\tint Z = getorig(V,i); // Finding the current value\n\t\t\t\tcout<<Z<<\" \"; // printing the current value\n\t\t\t\tV>>=1; // dividing the original value by 2 to get its parent value\n\t\t\t}\n\t\t\tcout<<endl;\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "implementation",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "960",
    "index": "E",
    "title": "Alternating Tree",
    "statement": "Given a tree with $n$ nodes numbered from $1$ to $n$. Each node $i$ has an associated value $V_i$.\n\nIf the simple path from $u_1$ to $u_m$ consists of $m$ nodes namely $u_1 \\rightarrow u_2 \\rightarrow u_3 \\rightarrow \\dots u_{m-1} \\rightarrow u_{m}$, then its alternating function $A(u_{1},u_{m})$ is defined as $A(u_{1},u_{m}) = \\sum\\limits_{i=1}^{m} (-1)^{i+1} \\cdot V_{u_{i}}$. A path can also have $0$ edges, i.e. $u_{1}=u_{m}$.\n\nCompute the sum of alternating functions of all unique simple paths. Note that the paths are directed: two paths are considered different if the starting vertices differ or the ending vertices differ. The answer may be large so compute it modulo $10^{9}+7$.",
    "tutorial": "An important observation for the question is $A(u,v) = -A(v,u)$ if there are even number of nodes on the simple path from $u$ to $v$ $A(u,v) = A(v,u)$ if there are odd number of nodes on the simple path from $u$ to $v$ Hence $A(u,v) + A(v,u)=0$ for paths with even number of nodes. Hence the task has been reduced to finding the total sum of alternating function of paths with odd number of nodes. Also we can make use of the fact that $A(u,v) + A(v,u) = 2*A(u,v)$ , but this does not hold true when $u=v$, hence we must handle this case by subtracting $\\sum\\limits_{i=1}^{n} V_{i}$ from the final answer. Now with the help of a single dfs we can calculate $odd_i$ the number of paths in the subtree of $i$ with odd number of nodes ending at node $i$. $even_i$ the number of paths in the subtree of $i$ with even number of nodes ending at node $i$. In the first part of the solution, for each node $i$, we calculate its contribution to the alternating function for paths passing through this node but strictly lying within its subtree. For doing this we can merge two paths with either both having even or both having odd number of nodes ending at its children to create odd length paths. For the case where both the paths have even number of nodes, the current node's contribution to the summation is $V_i$ because its position in the sequence of nodes is odd . Similarly, we add $-V_i$ for the other case. This can be done using a single dfs in $O(n)$ time as we have $odd_i$ and $even_i$ for all the nodes. Now for the second part of the question, we have to consider the paths which end up outside the subtree. We have the information $odd_i$ and $even_i$ . We have to merge these paths with those ending at $parent_i$. How do we get this information? Note that $odd_i$ and $even_i$ just represent paths strictly lying within the subtree of $i$ but not the entire tree. An important observation for this computation is - If node $u$ has a total of $x$ odd and $y$ even length paths ending at it then, if $v$ is the neighbour of $u$ then $v$ has a total of $y$ odd and $x$ even length paths ending at it. It is fairly simple to observe. We know $odd_{root}$ and $even_{root}$ and since the subtree of $root$ is the entire tree, we can use these values for our requirement. Now let's represent the total number of odd and even length paths ending at $i$ by $todd_i$ and $teven_i$ respectively. From our previous observation, if $i$ is odd number of nodes away from the $root$ node - $todd_i = even_{root}$ $teven_i = odd_{root}$ if $i$ is even number of nodes away from the $root$ node - $todd_i = odd_{root}$ $teven_i = even_{root}$ The number of paths ending at $parent_i$ but lying strictly outside the subtree of $i$ can be calculated - odd length paths $= todd_{parent_i}-even_i$ even length paths $= teven_{parent_i}-odd_i$ Now we have to construct odd-length paths by merging paths in the subtree of $i$ ending at node $i$ with paths ending at $parent_i$ but strictly lying outside the subtree of $i$. For paths with odd-length component ending at $i$ we must add $V_i$ to the summation and $-V_i$ otherwise. Finally, the summation of contributions of each node yields you the total summation of alternating functions for all pair of nodes. This can be done for each node in $O(n)$ time. The overall time complexity of the solution is $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int M=1000005,mod=1e9+7;\nvector<int> adj[M];\nint par[M],lev[M];\nll v[M];\nll e[M],o[M];\nll ans,res,n;\nll powmod(ll base, ll exponent)\n{ \n\t//cout<<base<<\" \"<<exponent<<endl;\n\n\tll ans=1;\n\t\n\t\twhile(exponent)\n\t\t{ \n\t\t\twhile(exponent%2==0)\n\t\t\t{\n\t\t\t\tbase=(base*base)%mod;\n\t\t\t\texponent/=2;\n\t\t\t}\n\t\t\t\n\t\t\texponent--;\n\t\t\tans=(ans*base)%mod;\n\t\t}\n\t\t\n\treturn ans;\n}\nvoid dfs(int x,int depth)\n{\n\t//o[x]++;\n\n\tlev[x]=depth;\n\t\n\tint cno=0;\n\n\tfor(int i=0;i<adj[x].size();i++)\n\t{\n\t\tint c=adj[x][i];\n\t\n\t\tif(c!=par[x])\n\t\t{\n\t\t\tpar[c]=x;\n\t\n\t\t\tdfs(c,depth+1);\n\t\t\n\t\t\tif(cno>0)\n\t\t\t{\n\t\t\t\tans=( (ans+ 2*( o[x]*e[c]%mod - e[x]*o[c]%mod + mod)%mod*v[x]%mod)+mod )%mod;\n\t\t\t}\n\t\t\t\n\t\t\tcno++;\n\t\t\n\t\t\to[x]+=e[c];\n\t\t\te[x]+=o[c];\n\t\t\n\t\t}\n\t\n\t}\n\t\n\to[x]++;\n\n\t\n}\nint main()\n{\n\t//freopen(\"o.out\",\"r\",stdin);\n\n\tcin>>n;\n\t\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tcin>>v[i];\n\t}\n\t\n\tfor(int i=1;i<n;i++)\n\t{\n\t\tint u,v;\n\t\t\n\t\tcin>>u>>v;\n\t\t\n\t\tadj[u].push_back(v);\n\t\tadj[v].push_back(u);\n\t}\n\t\n\tdfs(1,0); \n\t\n\t//cout<<ans<<endl;\n\t\n\tfor(int i=1;i<=n;i++)\n\t{\t\n\t\t//cout<<\"###\"<<i<<endl;\n\t\tif(lev[i]%2)\n\t\t{\n\t\t\tans=((ans+2*(o[i]*(e[1]-o[i]+1)%mod - e[i]*(o[1]-e[i])%mod +mod)%mod*v[i]%mod)%mod+mod )%mod;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tans=((ans+2*(o[i]*(o[1]-o[i]+1)%mod - e[i]*(e[1]-e[i])%mod +mod)%mod*v[i]%mod)%mod+mod )%mod;\n\t\t}\n\t\t\n\t\t//cout<<ans<<endl;\n\t\t\n\t\tans=((ans-v[i])%mod+mod)%mod;\n\t\t\n//\t\tcout<<i<<\" \"<<ans<<endl;\n\t\t//cout<<ans<<endl;\n\t}\n\t\n\tcout<<ans<<endl;\n\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "divide and conquer",
      "dp",
      "probabilities",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "960",
    "index": "F",
    "title": "Pathwalks",
    "statement": "You are given a directed graph with $n$ nodes and $m$ edges, with all edges having a certain weight.\n\nThere might be multiple edges and self loops, and the graph can also be disconnected.\n\nYou need to choose a path (possibly passing through same vertices multiple times) in the graph such that the weights of the edges are in strictly increasing order, and these edges come in the order of input. Among all such paths, you need to find the the path that has the maximum possible number of edges, and report this value.\n\nPlease note that the edges picked don't have to be consecutive in the input.",
    "tutorial": "The problem is similar to Longest Increasing Subsequence, done on a graph instead of an array. The solution for this problem can be obtained in the following ways:- $Approach1$ Maintain a map for every node, consisting of weights and the corresponding max no of edges you can achieve for some path ending at that node at a given point. Now when you process the next edge, suppose $a_{i}$ $b_{i}$ $w_{i}$ , you query max no of edges having weight $< w_{i}$ in map of node $a_{i}$ . Let's call this $X$. Now, you try to insert $X + 1$ for weight $w_{i}$ in map of node $b_{i}$. Maintain it in such a way that no of edges for higher weights in a particular node is always larger than that for smaller weights. You can do this with (kind of) the conventional sliding window idea, by removing higher weight edges with smaller values than the current inserted answer in the map, or not inserting the current value at all because an equivalent or better answer exists for weights $ \\le  w_{i}$ for the node $b_{i}$. Finally the max of all such $X + 1$ you encounter during processing the graph is the maximum number of edges in any given path. $Approach2$ You can also solve this problem with the help of sparse/dynamic/persistent segment tree on every node of the graph. Suppose you are at the $i^{th}$ edge at some point in your processing, and the query was $a_{i}$ $b_{i}$ $w_{i}$. Do a Range Max Query on segtree at node $a_{i}$, uptil value $w_{i - 1}$. Suppose this answer was $X$. Now update segtree at location $b_{i}$ with value of $(X + 1)$. Store the max of all such $(X + 1)$, and this is the length of longest path in your graph.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvector<map<int,int> > s;\nint getedgelen(int a, int w)\n{\n    auto it = s[a].lower_bound(w);\n    if(it == s[a].begin()) return 1;\n    it--;\n    return (it->second)+1;\n}\nint32_t main() {\n    ios::sync_with_stdio(false);cin.tie(0);\n    int n,m,a,b,w;\n    cin>>n>>m;\n    s.resize(n+1);\n    int ans = 0;\n    while(m--)\n    {\n        cin>>a>>b>>w;\n        int val = getedgelen(a,w);\n        if(getedgelen(b,w+1) > val)\n            continue;\n        s[b][w] = max(s[b][w],val);\n        auto it = s[b].upper_bound(w);\n        while(!(it==s[b].end() || it->second > val))\n        {\n            it = s[b].erase(it);\n        }\n        ans = max(ans,val);\n    }\n    cout<<ans;\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "960",
    "index": "G",
    "title": "Bandit Blues",
    "statement": "Japate, while traveling through the forest of Mala, saw $N$ bags of gold lying in a row. Each bag has some \\textbf{distinct} weight of gold between $1$ to $N$. Japate can carry only one bag of gold with him, so he uses the following strategy to choose a bag.\n\nInitially, he starts with an empty bag (zero weight). He considers the bags in some order. If the current bag has a higher weight than the bag in his hand, he picks the current bag.\n\nJapate put the bags in some order. Japate realizes that he will pick $A$ bags, if he starts picking bags from the front, and will pick $B$ bags, if he starts picking bags from the back. By picking we mean replacing the bag in his hand with the current one.\n\nNow he wonders how many permutations of bags are possible, in which he picks $A$ bags from the front and $B$ bags from back using the above strategy.\n\nSince the answer can be very large, output it modulo $998244353$.",
    "tutorial": "The problem can be seen as to count the number of permutations such that the number of records from the front is A and the number of records from the back is B, where a record is an element greater than all previous. let $s(A, N)$ be the number of permutations such that for $N$ elements exactly $A$ records are present from front. Then $s(A, N)$ can be calculated as $s(A, N) = s(A - 1, N - 1) + (N - 1) * s(A, N - 1)$ Let's consider the smallest element if we have it as a record then we can place it on front and have the remaining $A - 1$ records in $s(A - 1, N - 1)$ ways or we don't have it as a record than we can have the remaining $A$ records in $s(A, N - 1)$ ways and place this smallest element at any of the remaining $N - 1$ positions. let $h(A, B, N)$ be the number of permutations such that the number of records from the front is $A$ and the number of records from the back is $B$. $h(A,B,N)=\\sum_{k=0}^{N-1}s(k,A-1)*s(N-k-1,B-1)*{\\binom{N-1}{k}}$ $k$ elements are chosen and placed before the largest record such that exactly $A - 1$ records are present in them in $s(k, A - 1)$ ways and the remaining $N - k - 1$ after the largest record such that $B - 1$ records are present in $s(N - k - 1, B - 1)$ ways.We choose the $k$ elements in $\\textstyle{\\binom{N-1}{k}}$ ways. Now we claim that $h(A,B,N)=s(A+B-2,N-1)*{\\binom{A+B-2}{A-1}}$ Proof - Consider permutations of length $N - 1$ with $A + B - 2$ records of which $A - 1$ are colored blue and $B - 1$ are colored green. Note - Coloring a record means coloring the record and every element between this record and previous record. We can choose permutations of $N - 1$ with $A + B - 2$ records ,then choose $A - 1$ of these records to be blue in $s(A+B-2,N-1)*{\\binom{A+B-2}{A-1}}$ ways. Also for any $k$ between $0$ and $N - 1$ we choose $k$ elements to be in blue then make permutations in these $k$ elements with $A - 1$ records and make permutations with exactly $B - 1$ records on remaining $N - k - 1$ elements, thus we have in total $\\sum_{k=\\mathbb{N}}^{N-1}s(k,A-1)*s(N-k-1,B-1)*{\\binom{N-1}{k}}$ ways. Hence both are equivalent. Therefore calculating $s(A + B - 2, N - 1)$ gives our answer. $s(k, n)$ forms stirling number of first kind which can be calculated by coefficent of $x^{k}$ in $x * (x + 1) * (x + 2) * ..... * (x + n - 1)$ using FFT.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define pb push_back\nconst int mod = 998244353;\nconst int root = 15311432;\nconst int root_1 = 469870224;\nconst int root_pw = 1 << 23;\nconst int N = 400004;\n\nvector<int> v[N];\n\nll modInv(ll a, ll mod = mod){\n\tll x0 = 0, x1 = 1, r0 = mod, r1 = a;\n\twhile(r1){\n\t\tll q = r0 / r1;\n\t\tx0 -= q * x1; swap(x0, x1);\n\t\tr0 -= q * r1; swap(r0, r1);\n\t}\n\treturn x0 < 0 ? x0 + mod : x0;\n}\n\nvoid fft (vector<int> &a, bool inv) {\n\tint n = (int) a.size();\n\n\tfor (int i=1, j=0; i<n; ++i) {\n\t\tint bit = n >> 1;\n\t\tfor (; j>=bit; bit>>=1)\n\t\t\tj -= bit;\n\t\tj += bit;\n\t\tif (i < j)\n\t\t\tswap (a[i], a[j]);\n\t}\n\n\tfor (int len=2; len<=n; len<<=1) {\n\t\tint wlen = inv ? root_1 : root;\n\t\tfor (int i=len; i<root_pw; i<<=1)\n\t\t\twlen = int (wlen * 1ll * wlen % mod);\n\t\tfor (int i=0; i<n; i+=len) {\n\t\t\tint w = 1;\n\t\t\tfor (int j=0; j<len/2; ++j) {\n\t\t\t\tint u = a[i+j],  v = int (a[i+j+len/2] * 1ll * w % mod);\n\t\t\t\ta[i+j] = u+v < mod ? u+v : u+v-mod;\n\t\t\t\ta[i+j+len/2] = u-v >= 0 ? u-v : u-v+mod;\n\t\t\t\tw = int (w * 1ll * wlen % mod);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(inv) {\n\t\tint nrev = modInv(n, mod);\n\t\tfor (int i=0; i<n; ++i)\n\t\t\ta[i] = int (a[i] * 1ll * nrev % mod);\n\t}\n}\n\nvoid pro(const vector<int> &a, const vector<int> &b, vector<int> &res) {\n\tvector<int> fa(a.begin(), a.end()),  fb(b.begin(), b.end());\n\tint n = 1;\n\twhile (n < (int) max(a.size(), b.size()))  n <<= 1;\n\tn <<= 1;\n\tfa.resize (n),  fb.resize (n);\n\n\tfft(fa, false), fft (fb, false);\n\tfor (int i = 0; i < n; ++i)\n\t\tfa[i] = 1LL * fa[i] * fb[i] % mod;\n\tfft (fa, true);\n\tres = fa;\n}\n\nint S(int n, int r) {\n\n\tint nn = 1;\n\twhile(nn < n) nn <<= 1;\n\n\tfor(int i = 0; i < n; ++i) {\n\t\tv[i].push_back(i);\n\t\tv[i].push_back(1);\n\t}\n\tfor(int i = n; i < nn; ++i) {\n\t\tv[i].push_back(1);\n\t}\n\n\tfor(int j = nn; j > 1; j >>= 1){\n\t\tint hn = j >> 1;\n\t\tfor(int i = 0; i < hn; ++i){\n\t\t\tpro(v[i], v[i + hn], v[i]);\n\t\t}\n\t}\n\n\treturn v[0][r];\n}\n\nint fac[N], ifac[N], inv[N];\n\nvoid prencr(){\n\tfac[0] = ifac[0] = inv[1] = 1;\n    for(int i = 2; i < N; ++i)\n    \tinv[i] = mod - 1LL * (mod / i) * inv[mod % i] % mod;\n    for(int i = 1; i < N; ++i){\n    \tfac[i] = 1LL * i * fac[i - 1] % mod;\n    \tifac[i] = 1LL * inv[i] * ifac[i - 1] % mod;\n    }\n}\n\nint C(int n, int r){\n\treturn (r >= 0 && n >= r) ? (1LL * fac[n] * ifac[n - r] % mod * ifac[r] % mod) : 0;\n}\n\nint main(){\n\tprencr();\n\tint n, p, q;\n\tcin >> n >> p >> q;\n\tll ans = C(p + q - 2, p - 1);\n\tans *= S(n - 1, p + q - 2);\n\tans %= mod;\n\tcout << ans;\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "960",
    "index": "H",
    "title": "Santa's Gift",
    "statement": "Santa has an infinite number of candies for each of $m$ flavours. You are given a rooted tree with $n$ vertices. The root of the tree is the vertex $1$. Each vertex contains exactly one candy. The $i$-th vertex has a candy of flavour $f_i$.\n\nSometimes Santa fears that candies of flavour $k$ have melted. He chooses any vertex $x$ randomly and sends the subtree of $x$ to the Bakers for a replacement. In a replacement, all the candies with flavour $k$ are replaced with a new candy of the same flavour. The candies which are not of flavour $k$ are left unchanged. After the replacement, the tree is restored.\n\nThe actual cost of replacing one candy of flavour $k$ is $c_k$ (given for each $k$). The Baker keeps the price fixed in order to make calculation simple. Every time when a subtree comes for a replacement, the Baker charges $C$, no matter which subtree it is and which flavour it is.\n\nSuppose that for a given flavour $k$ the probability that Santa chooses a vertex for replacement is same for all the vertices. You need to find out the expected value of error in calculating the cost of replacement of flavour $k$. The error in calculating the cost is defined as follows.\n\n$$ Error\\ E(k) =\\ (Actual Cost\\ –\\ Price\\ charged\\ by\\ the\\ Bakers) ^ 2.$$\n\nNote that the actual cost is the cost of replacement of one candy of the flavour $k$ multiplied by the number of candies in the subtree.\n\nAlso, sometimes Santa may wish to replace a candy at vertex $x$ with a candy of some flavour from his pocket.\n\nYou need to handle two types of operations:\n\n- Change the flavour of the candy at vertex $x$ to $w$.\n- Calculate the expected value of error in calculating the cost of replacement for a given flavour $k$.",
    "tutorial": "The actual cost of replacing all candies of flavour $k$ in the subtree of vertex $x$ is $h_k(x) \\cdot c_k$. Here, $h_k(x)$ is the number of vertices (candy) in the subtree of $x$ with value (flavour) $k$ and $c_k$ is the cost of replacing each candy of flavour $k$. Error $E(v)$ is defined as $(h_k(x) \\cdot c_k - C) ^ 2$ = $h_k(x)^2 \\cdot c_k^2 + C^2 - 2 \\cdot h_k(x) \\cdot c_k \\cdot C$. Expectation of error $E(v)$ can be written $Exp[E(v)]$ = $Exp[h_k(x)^2 \\cdot c_k^2 + C^2 - 2 \\cdot h_k(x) \\cdot c_k \\cdot C]$ = $c_k ^ 2 \\cdot Exp[h_k(x)^2] + Exp[C^2] - 2 \\cdot c_k \\cdot C \\cdot Exp[h_k(x)]$. $Exp[h_k(x)]$ can be expressed as $\\frac{\\sum_{x=1}^{n} h_k(x)}{n}$. The above sum can be managed by adding or by subtracting the depth of node (assuming root to be of depth 1). $Exp[{h_k(x)}^2]$ can be expressed as $\\frac{\\sum_{x=1}^{n} h_k(x)^2}{n}$. It can be observed that for every pair of vertices with value $k$ we need to add depth of LCA to the answer. Now we need to find the summation $\\sum\\nolimits_{f_i=k} \\sum\\nolimits_{f_j=k} Dist(i,j)$. To find sum we use centroid decomposition. We create a centroid tree from the given tree. Initially, no vertices have been inserted or updated. We update vertices one by one. While inserting a vertex with value $k$. We need to calculate its distance with all other vertices with the same value and add to the answer. To do so we maintain few things for a given vertex $x$ in the centroid tree. $p(x)$ - Parent of vertex $x$ in the centroid tree $h_k(x)$ - Number of vertices currently present in the subtree of $x$ with value $v$ $a_k(x)$ - $\\sum\\nolimits_{i \\in subtree(x)} distance(x,i)$ $b_k(x)$ - $\\sum\\nolimits_{i \\in subtree(x)} distance(p(x),i)$ The distance of any given vertex $x$ with value $k$ with other vertices of same value is given as $a_k(x) + d_k(x)$. Here, $d_k(x)$ is $\\sum\\nolimits_{i \\in all\\ ancestor\\ of\\ x} distance(i,x) \\cdot (h_k(p(i) - h_k(i)) + a_k(p(i)) - b_k(i))$ For each vertex, we need to store for all values $k$ present in the subtree. We can use a map for this purpose. In worst case, $O(n \\cdot log(n))$ memory will be used.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define pb push_back\nconst int N = 400004;\n\nint n;\nvector<int> e[N];\nint sz[N], par[N], sp[30][N];\nint V[N], L[N], CS[N];\nbool mark[N];\n\nstruct tri {\n\tlong long A, B;\n\tint C;\n};\n\nmap<int, tri> nmp[N];\n\nlong long D[N]; // Sum of Distances\nlong long S[N]; // Sum of Depth\nint T[N]; // Count\n\n//======================================PRE-PROCESS=========================================\n\nvoid getLevel(int u, int p = -1){\n\tsp[0][u] = p;\n\tfor(auto x : e[u]) if(x != p) {\n\t\tL[x] = 1 + L[u];\n\t\tgetLevel(x, u);\n\t}\n}\n\nvoid prepAncestor(){\n\tfor(int i = 1; (1 << i) <= n; ++i) {\n\t\tfor(int j = 1; j <= n; ++j) {\n\t\t\tsp[i][j] = sp[i - 1][sp[i - 1][j]];\n\t\t}\n\t}\n}\n\nint dist(int u, int v){\n\tif(L[u] < L[v]) swap(u, v);\n\tint lgn = 0;\n\twhile((1 << lgn) < n) lgn++;\n\tint ans = 0;\n\tfor(int i = lgn; i >= 0; --i){\n\t\tif(L[u] - (1 << i) >= L[v]){\n\t\t\tu = sp[i][u];\n\t\t\tans += (1 << i);\n\t\t}\n\t}\n\tif(u == v) return ans;\n\tfor(int i = lgn; i >= 0; --i){\n\t\tif(sp[i][u] != sp[i][v]){\n\t\t\tans += 1 << (i + 1);\n\t\t\tu = sp[i][u];\n\t\t\tv = sp[i][v];\n\t\t}\n\t}\n\treturn ans + 2;\n}\n\n//=================================CENTROID DECOMPOSITION===================================\n\nvoid getSize(int u, int p = -1) {\n      sz[u] = 1;\n      for(auto v : e[u]) if(v != p && !mark[v]) {\n            getSize(v, u);\n            sz[u] += sz[v];\n      }\n}\n \nint getCentroid(int u, int p, int lim) {\n      for(auto v : e[u]) if(v != p && !mark[v] && sz[v] > lim) {\n            return getCentroid(v, u, lim);\n      }\n      return u;\n}\n\nvoid decompose(int u, int p = -1) {\n      getSize(u);\n      int cen = getCentroid(u, -1, sz[u] / 2);\n      par[cen] = p == -1 ? cen : p;\n      mark[cen] = true;\n       \n      for(auto v : e[cen]) if(v != p && !mark[v]) {\n            decompose(v, cen);\n      }\n}\n\n//==========================================QUERY-HANDLER===============================================\n\nvoid updAns(int u, int add) {\n\n\tint Z = V[u];\n\t\n\ttri tY = nmp[u][Z];\n\tll ret = tY.A;\n\tint y = u, x = par[u];\n\twhile(y != x) {\n\t\ttri tX = nmp[x][Z];\n\t\tret += 1LL * (tX.C - tY.C) * dist(x, u) + (tX.A - tY.B);\n\t\ty = x;\n\t\ttY = tX;\n\t\tx = par[x];\n\t}\n\tret <<= 1;\n\n\tint mul = add ? 1 : -1;\n\tD[Z] += mul * ret;\n\tS[Z] += mul * L[u];\n\tT[Z] += mul;\n}\n\nvoid updTree(int u, bool add) {\n\tint Z = V[u];\n\tint mul = add ? 1 : -1;\n\tfor(int x = u; ; x = par[x]) {\n\t\ttri &tX = nmp[x][Z];\n\t\ttX.C += mul;\n\t\tif(!tX.C) {\n\t\t\tnmp[x].erase(Z);\n\t\t} else {\n\t\t\ttX.A += mul * dist(u, x);\n\t\t\ttX.B += mul * dist(u, par[x]);\n\t\t}\n\t\tif(x == par[x]) break;\n\t}\n}\n\nvoid upd(int u, bool add) {\n\tif(add) {\n\t\tupdTree(u, add);\n\t\tupdAns(u, add);\n\t} else {\n\t\tupdAns(u, add);\n\t\tupdTree(u, add);\n\t} \n}\n\n//=========================================MAIN============================================\n\nint main(){\n\t\n\tint m, q, ac;\n\tscanf(\"%d %d %d %d\", &n, &m, &q, &ac);\n\n\tfor(int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &V[i]);\n\t}\n\t\n\tfor(int i = 2; i <= n; ++i) {\n\t\tint v;\n\t\tscanf(\"%d\", &v);\n\t\te[v].pb(i);\n\t\te[i].pb(v);\n\t}\n\n\tfor(int i = 1; i <= m; ++i) {\n\t\tscanf(\"%d\", &CS[i]);\n\t}\n\n\tL[1] = 1;\n\tgetLevel(1);\n\tprepAncestor();\n\tdecompose(1);\n\t\n\tfor(int i = 1; i <= n; ++i) {\n\t\tupd(i, true);\n\t}\n\n\twhile(q--) {\n\t\tint t;\n\t\tscanf(\"%d\", &t);\n\t\tif(t == 1) {\n\t\t\tint u, v;\n\t\t\tscanf(\"%d %d\", &u, &v);\n\t\t\tupd(u, false);\n\t\t\tV[u] = v; \n\t\t\tupd(u, true);\n\t\t}\n\t\telse if(t == 2) {\n\t\t\tint v;\n\t\t\tscanf(\"%d\", &v);\n\t\t\tlong double ans = S[v] * T[v] - D[v] / 2;\n\n\t\t\tans *= 1LL * CS[v] * CS[v];\n\n\n\t\t\tans += 1LL * n * ac * ac;\n\n\t\t\t\n\t\t\tlong long anst = 2LL * CS[v] * ac * S[v];\n\t\t\t\n\t\t\tans -= anst;\n\n\t\t\tcout << fixed << setprecision(12) << ans / n << \"\\n\"; \n\t\t}\n\t}\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "961",
    "index": "A",
    "title": "Tetris",
    "statement": "You are given a following process.\n\nThere is a platform with $n$ columns. $1 \\times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.\n\nWhen all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row.\n\nYou task is to calculate the amount of points you will receive.",
    "tutorial": "The answer will be equal to $\\min\\limits_{i = 1}^{n} cnt_i$, where $cnt_i$ is the number of squares that will appear in the $i$-th column.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint n, m;\n\tcin >> n >> m;\n\tvector<int> cnt(n);\n\n\tfor (int i = 0; i < m; ++i) {\n\t\tint col;\n\t\tcin >> col;\n\t\t++cnt[col - 1];\n\t}\n\t\n\tcout << *min_element(cnt.begin(), cnt.end()) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "961",
    "index": "B",
    "title": "Lecture Sleep",
    "statement": "Your friend Mishka and you attend a calculus lecture. Lecture lasts $n$ minutes. Lecturer tells $a_{i}$ theorems during the $i$-th minute.\n\nMishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array $t$ of Mishka's behavior. If Mishka is asleep during the $i$-th minute of the lecture then $t_{i}$ will be equal to $0$, otherwise it will be equal to $1$. When Mishka is awake he writes down all the theorems he is being told — $a_{i}$ during the $i$-th minute. Otherwise he writes nothing.\n\nYou know some secret technique to keep Mishka awake for $k$ minutes straight. However you can use it \\textbf{only once}. You can start using it at the beginning of any minute between $1$ and $n - k + 1$. If you use it on some minute $i$ then Mishka will be awake during minutes $j$ such that $j\\in[i,i+k-1]$ and will write down all the theorems lecturer tells.\n\nYou task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique \\textbf{only once} to wake him up.",
    "tutorial": "Let's iterate over all $i$ from $1$ to $n$ and if $t_{i}$ is equal to $1$ then add $a_{i}$ to the some variable $res$ and replace $a_{i}$ with $0$. Then answer will be equal to $r e s+\\operatorname*{m}_{i=k}^{n}a_{j}{}=\\underline{{{i}}}^{i}-k+1}a_{j}$, where $\\sum_{j=i-k+1}^{i}a_{j}$ can be easily calculated with prefix sums for each $i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint n, k;\n\tscanf(\"%d %d\", &n, &k);\n\t\n\tvector<int> a(n);\n\tvector<int> t(n);\n\t\n\tint overall = 0;\n\t\n\tfor (int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\tfor (int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", &t[i]);\n\t\t\n\tvector<int> pr(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (i) pr[i] += pr[i - 1];\n\t\tif (t[i] == 0) pr[i] += a[i];\n\t\telse overall += a[i];\n\t}\n\t\n\tint add = 0;\n\tfor (int i = k - 1; i < n; ++i)\n\t\tadd = max(add, pr[i] - (i >= k ? pr[i - k] : 0));\n\t\n\tprintf(\"%d\\n\", overall + add);\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "961",
    "index": "C",
    "title": "Chessboard",
    "statement": "Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into $4$ pieces, each of size $n$ by $n$, $n$ is \\textbf{always odd}. And what's even worse, some squares were of wrong color. $j$-th square of the $i$-th row of $k$-th piece of the board has color $a_{k, i, j}$; $1$ being black and $0$ being white.\n\nNow Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be $2n$ by $2n$. You are allowed to move pieces but \\textbf{not allowed to rotate or flip them}.",
    "tutorial": "Since $n$ is odd, exactly $2$ pieces of the board will have upper left corner colored black (and exactly $2$ - white). Let's check every option to choose two pieces of the board so their upper left corners will be painted white when we assemble the board, calculate the number of board cells that have to be recolored, and find the minimum of this value among all possible choices.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 109;\n\nint n;\nstring a[4][N];\n\nint main() {\n\tcin >> n;\n\tfor(int k = 0; k < 4; ++k)\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tcin >> a[k][i];\n\t\t\t\tfor(int j = 0; j < n; ++j)\n\t\t\t    a[k][i][j] -= '0';\n\t\t}\n\t\n\tvector <int> v;\n\tfor(int k = 0; k < 4; ++k){\n\t\tint sum = 0;\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tfor(int j = 0; j < n; ++j)\n\t\t\t\tif((i + j) % 2 != a[k][i][j])\n\t\t\t\t\t++sum;\n\t\tv.push_back(sum);\n\t}\n\t\n\tint res = int(1e9);\n\tvector <int> perm;\n\tfor(int k = 0; k < 4; ++k) perm.push_back(k);\n\tdo{\n\t\tint sum = 0;\n\t\tfor(int k = 0; k < 4; ++k){\n\t\t\tint id = perm[k];\n\t\t\tif(k & 1)\n\t\t\t\tsum += v[id];\n\t\t\telse\n\t\t\t\tsum += n * n - v[id];\n\t\t}\n\t\t\n\t\tres = min(res, sum);\n\t}while(next_permutation(perm.begin(), perm.end()));\n\n\tcout << res << endl;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "961",
    "index": "D",
    "title": "Pair Of Lines",
    "statement": "You are given $n$ points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct.\n\nYou may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?",
    "tutorial": "If the number of points is less than $3$, then the answer is obviously YES. Else let's fix first $3$ points. Check if there is a solution if $1$-st and $2$-nd points lie on the same line. Just erase all points which lie on this line and check the remaining points if they belong to one line. If we didn't find the answer, let's check points $1$ and $3$ in the same way. If its failed again then line which contains point $1$ can't contain points $2$ and $3$, so points $2$ and $3$ must lie on one line. If we didn't succeed again, then there is no way to do it, so the answer is NO. Checking that points $a$, $b$ and $c$ belong to the same line can be done by calculating 2d version of cross product $(b - a)  \\times  (c - a)$. It equals to $0$ if vectors $(b - a)$ and $(c - a)$ are collinear.",
    "code": "#include <bits/stdc++.h>\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int(a.size())\n#define mp make_pair\n\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ninline pt operator -(const pt &a, const pt &b) {\n\treturn {a.x - b.x, a.y - b.y};\n}\n\ninline li cross(const pt &a, const pt &b) {\n\treturn a.x * 1ll * b.y - a.y * 1ll * b.x;\n}\n\nconst int N = 200 * 1000 + 555;\n\nint n;\npt p[N];\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\t\n\tfore(i, 0, n)\n\t\tscanf(\"%d%d\", &p[i].x, &p[i].y);\n\treturn true;\n}\n\nbool used[N];\n\nbool check() {\n\tint i1 = -1, i2 = -1;\n\tfore(i, 0, n) {\n\t\tif(used[i])\n\t\t\tcontinue;\n\t\tif(i1 == -1)\n\t\t\ti1 = i;\n\t\telse if(i2 == -1)\n\t\t\ti2 = i;\n\t}\n\tif(i2 == -1)\n\t\treturn true;\n\t\t\n\tfore(i, 0, n) {\n\t\tif(used[i])\n\t\t\tcontinue;\n\t\tif(cross(p[i2] - p[i1], p[i] - p[i1]) != 0)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool check2(pt a, pt b) {\n\tmemset(used, 0, sizeof used);\n\tfore(i, 0, n)\n\t\tif(cross(b - a, p[i] - a) == 0)\n\t\t\tused[i] = 1;\n\treturn check();\n}\n\ninline void solve() {\n\tif(n <= 2) {\n\t\tputs(\"YES\");\n\t\treturn;\n\t}\n\t\n\tif(check2(p[0], p[1]) || check2(p[0], p[2]) || check2(p[1], p[2]))\n\t\tputs(\"YES\");\n\telse\n\t\tputs(\"NO\");\n}\n\nint main(){\n\tif(read()) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "geometry"
    ],
    "rating": 2000
  },
  {
    "contest_id": "961",
    "index": "E",
    "title": "Tufurama",
    "statement": "One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series \"Tufurama\". He was pretty surprised when he got results only for season 7 episode 3 with his search query of \"Watch Tufurama season 3 episode 7 online full hd free\". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.\n\nTV series have $n$ seasons (numbered $1$ through $n$), the $i$-th season has $a_{i}$ episodes (numbered $1$ through $a_{i}$). Polycarp thinks that if for some pair of integers $x$ and $y$ ($x < y$) exist both season $x$ episode $y$ and season $y$ episode $x$ then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!",
    "tutorial": "At first, it doesn't matter if some season has more than $n$ episodes, so we can set $a_{i} = min(a_{i}, n)$. Let's maintain next invariant: when we proceed $i$-th season we will have only seasons containing the episodes with indices $ \\ge  i$. Then the number of pairs $(i, y)$ is just number of seasons with index $ \\le  a_{i}$. One of the ways to maintain this invariant is the following: for each number of episodes $a_{i}$ store a list with indices of seasons with exactly $a_{i}$ episodes. Then after proceeding of $i$-th season just erase all seasons with exactly $i$ episodes. Maintaining seasons and counting them can be done by BIT with zeros and ones. Finally, notice, that we counted each pair $(x < y)$ twice, and also counted the pairs $(x, x)$, so we must subtract the number of pairs $(x, x)$ (where $a_{x}  \\ge  x$) and divide the result by two.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 9;\n\nint n;\nint a[N];\nint f[N];\nvector <int> v[N];\n\nvoid upd(int pos, int d){\n\tfor(; pos < N; pos |= pos + 1)\n\t\tf[pos] += d;\n}\n\nint get(int pos){\n\tint res = 0;\n\tfor(; pos >= 0; pos = (pos & (pos + 1)) - 1)\n\t\tres += f[pos];\n\treturn res;\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; ++i){\n\t\tscanf(\"%d\", a + i);\n\t\t--a[i];\n\t}\n\t\t\n\tfor(int i = 0; i < n; ++i){\n\t\tif(a[i] < N)\n\t\t\tv[a[i]].push_back(i);\n\t\tupd(i, 1);\n\t}\n\t\n\tlong long res = 0;\n\tfor(int i = 0; i < n; ++i){\n\t\tint to = min(N - 1, a[i]);\n\t\tres += get(to);\n\t\tfor(auto x : v[i])\n\t\t\tupd(x, -1);\n\t}\n\t\n\tfor(int i = 0; i < n; ++i)\n\t    if(i <= a[i])\n\t        --res;\n    assert(res % 2 == 0);\n    \n\tcout << res / 2 << endl;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 1900
  },
  {
    "contest_id": "961",
    "index": "F",
    "title": "k-substrings",
    "statement": "You are given a string $s$ consisting of $n$ lowercase Latin letters.\n\nLet's denote $k$-substring of $s$ as a string $subs_{k} = s_{k}s_{k + 1}..s_{n + 1 - k}$. Obviously, $subs_{1} = s$, and there are exactly $\\textstyle{\\left[\\!\\!{\\frac{n}{2}}\\right]}$ such substrings.\n\nLet's call some string $t$ an \\textbf{odd proper suprefix} of a string $T$ iff the following conditions are met:\n\n- $|T| > |t|$;\n- $|t|$ is an odd number;\n- $t$ is simultaneously a prefix and a suffix of $T$.\n\nFor evey $k$-substring ($k\\in[1,[{\\frac{n}{2}}]]$) of $s$ you have to calculate the maximum length of its odd proper suprefix.",
    "tutorial": "Let's look at suprefix of fixed $k$-substring: we can't find its maximal length via binary search because this function isn't monotone in general case. But, by fixing not the left border but the center of the prefix, we also fix the center of the corresponding suffix (center of a prefix in position $i$ is tied with the center of the suffix in position $n + 1 - i$), and, more important, function becomes monotone. So solution is next: iterate over all valid centers of prefix $i$ and try to binary search maximal length $2x + 1$ of such substring that its center is in position $i$, and it's equal to the substing with center in $n + 1 - i$. $ans_{i - x}$ then can be updated with value $2x + 1$. And don't forget to update each $ans_{i}$ with value $ans_{i - 1} - 2$. Easy way to check substrings for equality is to use hashes. Harder way is to use string suffix structures (like bundle of Suffix Array + LCP + Sparse Table or Suffix Tree + LCA). Note for SuffArray users: don't forget about changing sort to stable_sort (merge sort) and breaking if all suffixes are different. This optimizations can save you from writing radix (or bucket) sort.",
    "code": "#include <bits/stdc++.h>\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int(a.size())\n#define mp make_pair\n\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef long long li;\n\nconst li MOD = li(1e18) + 3;\nconst li BASE = 1009;\n\ninline li norm(li a) {\n\twhile(a >= MOD)\n\t\ta -= MOD;\n\twhile(a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\ninline li mul(li a, li b) {\n\tli m = ((long double)(a) * b) / MOD;\n\treturn norm(a * b - m * MOD);\n}\n\nconst int N = 1000 * 1000 + 555;\n\nint n;\nstring s;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\t\n\tchar buf[N];\n\tassert(scanf(\"%s\", buf) == 1);\n\ts = buf;\n\treturn true;\n}\n\nli h[N], pw[N];\n\ninline void precalc() {\n\th[0] = 0;\n\tfore(i, 0, n)\n\t\th[i + 1] = norm(mul(h[i], BASE) + s[i] - 'a' + 1);\n\t\t\n\tpw[0] = 1;\n\tfore(i, 1, N)\n\t\tpw[i] = mul(pw[i - 1], BASE);\n}\n\ninline li getHash(int l, int r) {\n\treturn norm(h[r] - mul(h[l], pw[r - l]));\n}\n\ninline bool eq(int i1, int i2, int l) {\n\tif(i1 == i2) return true;\n\treturn getHash(i1, i1 + l) == getHash(i2, i2 + l);\n}\n\nint l[N], mx[N];\n\ninline void solve() {\n\tprecalc();\n\t\n\tfore(i, 0, n / 2) {\n\t\tint c1 = i, c2 = n - 1 - i;\n\t\tif(s[c1] != s[c2]) {\n\t\t\tl[i] = -1;\n\t\t\tcontinue;\n\t\t}\n\t\tint lf = 0, rg = min(c1, n - 1 - c2) + 1;\n\t\twhile(rg - lf > 1) {\n\t\t\tint mid = (lf + rg) >> 1;\n\t\t\t\n\t\t\tif(eq(c1 - mid, c2 - mid, 2 * mid + 1))\n\t\t\t\tlf = mid;\n\t\t\telse\n\t\t\t\trg = mid;\n\t\t}\n\t\tl[i] = lf;\n\t}\n\t\n\tfore(i, 0, n / 2) {\n\t\tif(l[i] < 0)\n\t\t\tcontinue;\n\t\tmx[i - l[i]] = max(mx[i - l[i]], 2 * l[i] + 1);\n\t}\n\tfore(i, 1, n / 2)\n\t\tmx[i] = max(mx[i], mx[i - 1] - 2);\n\n\tfore(i, 0, (n + 1) / 2) {\n\t\tif(i) printf(\" \");\n\t\tif(mx[i] == 0) mx[i] = -1;\n\t\tprintf(\"%d\", mx[i]);\n\t}\n\tputs(\"\");\n}\n\nint main(){\n\tif(read()) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "hashing",
      "string suffix structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "961",
    "index": "G",
    "title": "Partitions",
    "statement": "You are given a set of $n$ elements indexed from $1$ to $n$. The weight of $i$-th element is $w_{i}$. The weight of some subset of a given set is denoted as $W(S)=|S|\\cdot\\sum_{i\\in S}w_{i}$. The weight of some partition $R$ of a given set into $k$ subsets is $W(R)=\\sum_{S\\in R}W(S)$ (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition).\n\nCalculate the sum of weights of all partitions of a given set into exactly $k$ \\textbf{non-empty} subsets, and print it modulo $10^{9} + 7$. Two partitions are considered different iff there exist two elements $x$ and $y$ such that they belong to the same set in one of the partitions, and to different sets in another partition.",
    "tutorial": "Let's look at some facts. At first, the answer is the sum of weights $w_{i}$ taken with some coefficients $cf_{i}$. So, it's enough to calculate those coefficients. Then $cf_{i}$ can be calculated by iterating on the size of the subset containing $i$-th element: $c f_{i}=\\sum_{s i z e=1}^{s i z e=n+1-k}s i z e\\cdot f(n,k,s i z e)$, where $f(n, k, size)$ is the number of partitions of set with $n$ elements into $k$ nonempty subsets with one subset of fixed size $size$ where $i$ belongs. This solution is still quite slow, so the next fact is: if two elements $i$ and $j$ belong to the same subset, then $j$ \"increases\" the coefficient before $w_{i}$. So for each element $i$ we can iterate over all elements $j$ which will lie in one subset with $i$. In other words, $c f_{i}=\\sum_{i=1}^{\\scriptscriptstyle{J=n}}g(n,k,i,j)=g(n,k,i,i)+\\sum_{i\\neq i}g(n,k,i,j)$. $g(n, k, i, j)$ is the number of ways to divide set with $n$ elements into $k$ subsets in such a way that elements $i$ and $j$ wil lie in one subset. $g(n, k, i, j)$ can be calculated using Stirling numbers of the second kind: let $\\textstyle\\{{}_{k}^{n}\\}$ be the number of partitions of set with $n$ elements into $k$ non-empty subsets. If $i = j$ then $g(n,k,i,j)={\\dot{\\{}}_{k}^{n}\\}$, else we just merge $i$ and $j$ into one element and let $g(n,k,i,j)={\\binom{n-1}{k}}$. Final formula is $c f_{i}=\\left\\{{}_{k}^{n}\\right\\}+\\sum_{j\\neq i}\\left\\{{}^{n-1}\\right\\}=\\left\\{{}_{k}^{n}\\right\\}+\\left(n-1\\right)\\cdot\\left\\{{}_{k}^{n-1}\\right\\}$. And the answer is $\\sum_{i=1}^{n-n}w_{i}\\cdot c f_{i}=c f_{0}\\sum_{i=1}^{n-n}w$. Counting Stirling numbers can be done with inclusion-exclusion principle or by searching Wiki: $\\{{}_{k}^{n}\\}={\\textstyle\\frac{1}{k!}}\\sum_{j=0}^{j=k}(-1)^{k+j}({}_{j}^{k})j^{n}$. Resulting complexity is $O(nlog(n))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) fore(i, 0, n)\n\nconst int MOD = int(1e9) + 7;\n\ninline int norm(int a) {\n\twhile(a >= MOD)\n\t\ta -= MOD;\n\twhile(a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\ninline int mul(int a, int b) {\n\treturn int((a * 1ll * b) % MOD);\n}\n\ninline int binPow(int a, int k) {\n\tint ans = 1;\n\twhile(k > 0) {\n\t\tif(k & 1) ans = mul(ans, a);\n\t\ta = mul(a, a);\n\t\tk >>= 1;\n\t}\n\treturn ans;\n}\n\nconst int N = 200 * 1000 + 555;\n\nint f[N], inf[N];\n\nvoid precalc() {\n\tf[0] = inf[0] = 1;\n\tfore(i, 1, N) {\n\t\tf[i] = mul(f[i - 1], i);\n\t\tinf[i] = mul(inf[i - 1], binPow(i, MOD - 2));\n\t}\n}\n\nint n, k, w[N];\n\ninline bool read() {\n\tif(!(cin >> n >> k))\n\t\treturn false;\n\tforn(i, n)\n\t\tcin >> w[i];\n\treturn true;\n}\n\ninline int c(int n, int k) {\n\tif(k > n || n < 0) return 0;\n\tif(k == 0 || n == k) return 1;\n\t\n\treturn mul(f[n], mul(inf[n - k], inf[k]));\n}\n\ninline int s(int n, int k) {\n\tif(n == 0) return k == 0;\n\tif(k == 0) return n == 0;\n\t\n\tint ans = 0, sg[2] = {1, MOD - 1};\n\tforn(cnt, k)\n\t\tans = norm(ans + mul(sg[cnt & 1], mul(c(k, cnt), binPow(k - cnt, n))));\n\treturn mul(ans, inf[k]);\n}\n\ninline void solve() {\n\tint sum = 0;\n\tforn(i, n)\n\t\tsum = norm(sum + w[i]);\n\t\t\n\tint s0 = s(n, k);\n\tint s1 = mul(n - 1, s(n - 1, k));\n\t\n\tcout << mul(sum, norm(s0 + s1)) << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tprecalc();\n\t\n\tassert(read());\n\tsolve();\n\n#ifdef _DEBUG\n\tcerr << \"TIME = \" << clock() << endl;\n#endif\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "962",
    "index": "A",
    "title": "Equator",
    "statement": "Polycarp has created his own training plan to prepare for the programming contests. He will train for $n$ days, all days are numbered from $1$ to $n$, beginning from the first.\n\nOn the $i$-th day Polycarp will necessarily solve $a_i$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.\n\nDetermine the index of day when Polycarp will celebrate the equator.",
    "tutorial": "To solve the problem we need to know the total number of problems which Polycarp planned to solve. We count it in one iteration through the given array and save the total number of problems in the variable $sum$. After that, we will again iterate through the array and count the number of problems that Polycarp will solve on the first $i$ days. Let this sum is equal to $l$. We need to find the smallest $i$ for which it is true that $l \\cdot 2 \\ge sum$. This day will be the answer.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "962",
    "index": "B",
    "title": "Students in Railway Carriage",
    "statement": "There are $n$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.\n\nThe university team for the Olympiad consists of $a$ student-programmers and $b$ student-athletes. Determine the largest number of students from all $a+b$ students, which you can put in the railway carriage so that:\n\n- no student-programmer is sitting next to the student-programmer;\n- and no student-athlete is sitting next to the student-athlete.\n\nIn the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.\n\nConsider that initially occupied seat places are occupied by jury members (who obviously are not students at all).",
    "tutorial": "We will iterate from the left to the right through the given string and take the maximal substrings consisting from the dots only (bounded by asterisks/string bounds). Let the length of the current such substring is $len$. If $len$ is even, in the places corresponding to this substring, you can put maximum $len / 2$ students of each type, simply alternating them. Considering remaining $a$ and $b$, you can put $\\min(a, len / 2)$ student-programmers and $\\min(b, len / 2)$ student-athletes in these places. If $len$ is odd, then in the places corresponding to this substring, you can put $(len + 1) / 2$ students of the one type and $len / 2$ students of the other type. If $a > b$, then you need to start put students from a student-programmer. So, $\\ min(a, (len + 1) / 2)$ of student-programmers and $\\ min(b, len / 2)$ of student-athletes can be put in this substring. Otherwise, you need to put students in the same way, but starting from a student-athlete. Also, you need to remember to maintain the number of remaining students $a$ and $b$ after processing the current substring and move on to the next substring consisting of the dots only.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "962",
    "index": "C",
    "title": "Make a Square",
    "statement": "You are given a positive integer $n$, written without leading zeroes (for example, the number 04 is incorrect).\n\nIn one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.\n\nDetermine the minimum number of operations that you need to consistently apply to the given integer $n$ to make from it the square of some positive integer or report that it is impossible.\n\nAn integer $x$ is the square of some positive integer if and only if $x=y^2$ for some positive integer $y$.",
    "tutorial": "Consider the given integer as a string $s$. Use the masks to brute all possible ways to delete digits. Let the remaining integer for the current mask is a string $t$. If the first character of $t$ is zero, skip this mask. Otherwise, we revert the string $t$ into the integer $cur$. Now we need to check does the $cur$ is a square of some integer. It can be done in many ways, for example, by adding all the integer squares less than $2 \\cdot 10^{9}$ into the $set$ (its size will be approximately equal to the square root of $2 \\cdot 10^{9}$) and check that $cur$ is in this set. If this is the case, we should update the answer with the difference between the string $s$ and the string $t$, because this difference is equal to the number of deleted digits for the current mask.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "962",
    "index": "D",
    "title": "Merge Equals",
    "statement": "You are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value $x$ that occurs in the array $2$ or more times. Take the first two occurrences of $x$ in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, $2 \\cdot x$).\n\nDetermine how the array will look after described operations are performed.\n\nFor example, consider the given array looks like $[3, 4, 1, 2, 2, 1, 1]$. It will be changed in the following way: $[3, 4, 1, 2, 2, 1, 1]~\\rightarrow~[3, 4, 2, 2, 2, 1]~\\rightarrow~[3, 4, 4, 2, 1]~\\rightarrow~[3, 8, 2, 1]$.\n\nIf the given array is look like $[1, 1, 3, 1, 1]$ it will be changed in the following way: $[1, 1, 3, 1, 1]~\\rightarrow~[2, 3, 1, 1]~\\rightarrow~[2, 3, 2]~\\rightarrow~[3, 4]$.",
    "tutorial": "To solve this problem we should use a set of pairs, let's call it $b$. We will store in it all the elements of the current array (the first number in the pair)and the positions of these elements in the current array (the second number in the pair). The first elements of pairs should have type long long, because the result of merging the array elements can become large and the type int will overflow. Initially, you need to put in $b$ all elements of the given array with their positions. While there are elements in $b$, we will perform the following algorithm. Let $x$ be a pair in the beginning of $b$. Then look at the next element of $b$. If it does not exist, the algorithm is complete. Otherwise, let the next element is equal to $y$. If $x.first \\neq y.first$, then there is no pair number for the element $x.first$, which is in the position $x.second$, and it will never appear, because all elements can only increase. So, remove $x$ from $b$ and repeat the algorithm from the beginning. Otherwise, the number at the position $x.second$ will be deleted, and the number in the position $y.second$ will be double up. So, remove $x$ and $y$ from $b$, put $(y.first \\cdot 2, y.second)$ in $b$ and repeat the algorithm from the beginning. For the convenience of restoring the answer, you can mark deleted positions of the given array in an additional array, so, in this case you need to mark $x.second$ as a deleted position.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "962",
    "index": "E",
    "title": "Byteland, Berland and Disputed Cities",
    "statement": "The cities of Byteland and Berland are located on the axis $Ox$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $Ox$ there are three types of cities:\n\n- the cities of Byteland,\n- the cities of Berland,\n- disputed cities.\n\nRecently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected.\n\nThe countries agreed to connect the pairs of cities with BNET cables in such a way that:\n\n- If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables,\n- If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables.\n\nThus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities.\n\nThe cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected.\n\nEach city is a point on the line $Ox$. It is technically possible to connect the cities $a$ and $b$ with a cable so that the city $c$ ($a < c < b$) is not connected to this cable, where $a$, $b$ and $c$ are simultaneously coordinates of the cities $a$, $b$ and $c$.",
    "tutorial": "We will call the disputed cities - purple points, the cities of Byteland - blue points, and the cities of Berland - red points. If there are no any purple points among the given points, you just need to connect all the neighboring red points between each other and all the neighboring blue points with each other. Thus, the answer is the sum of the distances between the leftmost red point and the rightmost red point and between the leftmost blue point and the rightmost red point. Otherwise, you firstly should connect all the neighboring purple points with each other. Consider what you should do to connect the red points. All the red points to the left of the leftmost purple point should be connected as follows: first from the left with the second from the left, second from the left with the third from the left and so on. The rightmost of these red points should be connected to the leftmost purple point. All the red points to the right of the rightmost purple point are connected in a similar way. Consider all the gaps between the neighboring purple points, and all the red and blue points between them. They should be connected in one of two ways. The first way is to connect the left purple with the leftmost red, the rightmost red with the right purple, and also connect all the neighboring red dots. Similarly we should make for the blue points. Let the total length of the edges for such a connection is equal to $len_1$. The second way is to connect the left and right purple point. Now consider only the purple points and the red ones. All adjacent points need to be connected to each other, except those which are on the maximum distance from all other pairs. If there are several, then we do not connect any pair. Similarly we make for the purple and blue points. Let the total length of the edges for such a connection is equal to $len_2$. If $len_1 > len_2$ we should connect points from the current gap in the second way, otherwise, in the first.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "962",
    "index": "F",
    "title": "Simple Cycles Edges",
    "statement": "You are given an undirected graph, consisting of $n$ vertices and $m$ edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself).\n\nA cycle in a graph is called a simple, if it contains each own vertex exactly once. So simple cycle doesn't allow to visit a vertex more than once in a cycle.\n\nDetermine the edges, which belong to exactly on one simple cycle.",
    "tutorial": "To solve this problem, it is good to know about fundamental set of cycles. Briefly, in the graph it is easy to select such a minimal set of cycles $C$ that any other cycle can be obtained as XOR of some subset of cycles from $C$. This set is also called the fundamental set of cycles. To find it in a connected graph, you can find any carcass and, alternately, independently add to this carcass each of the edges that are not entered into it. When each such edge is added to the carcass, its cycle closes. The set of these cycles is a fundamental set of cycles. Thus, if the graph is connected, then the size of the fundamental set of cycles is exactly $m-n+1$. It is easy to see that if an edge belongs to exactly one cycle from the fundamental set of cycles, then it belongs to exactly one simple cycle. We solve the problem independently for each connected component. For a connected component, it finds its carcass by a search in depth, and each edge that does not enter the search tree into the depth will close a cycle. We only take into account those cycles that do not intersect along the edges. We should print only them in the form of a set of edges. If the carcass was built with a search in depth, then each cycle represents a path from the vertex to the child (plus the reverse edge). Thus, the problem now is: a set of pairs of vertices (a vertex and its descendant) that specify a set of paths from top to bottom is given in the tree. It is required to select those paths that do not intersect with any other paths from this set. To find such ways quickly it is possible with help of DSU (system of non-intersecting subsets) on paths. On the edge, you should store the -1 mark or the path number to which it belongs. When passing the edges without marking, it should be marked by this path. When passing an edge with a mark, it is necessary to merge two paths into the DSU, because they intersect. After processing the path, for all the vertices of the path, the ancestor should be reassign to the top vertex of the path. Because if we do not make this we will repeatedly go through the same path. Using the following code, we find for each vertex its depth in the depth search tree and all the back edges (an array be): Using the following code, we process all paths (actually cycles), merging the intersecting ones. Let $pp$ - it is an original array of ancestors in depth search tree (because array $p$ has been changed by the code above). Now, it is sufficient to the answer to take such paths plus the corresponding reverse edge that do not intersect with others (that is, the size of the DSU component is 1): This problem has another solution, based on the allocation of the doubly connected components with the help of the corresponding linear algorithm.",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "962",
    "index": "G",
    "title": "Visible Black Areas",
    "statement": "Petya has a polygon consisting of $n$ vertices. All sides of the Petya's polygon are parallel to the coordinate axes, and each two adjacent sides of the Petya's polygon are perpendicular. It is guaranteed that the polygon is simple, that is, it doesn't have self-intersections and self-touches. All internal area of the polygon (borders are not included) was painted in black color by Petya.\n\nAlso, Petya has a rectangular window, defined by its coordinates, through which he looks at the polygon. A rectangular window can not be moved. The sides of the rectangular window are parallel to the coordinate axes.\n\n\\begin{center}\n{\\small Blue color represents the border of a polygon, red color is the Petya's window. The answer in this case is 2.}\n\\end{center}\n\nDetermine the number of black connected areas of Petya's polygon, which can be seen through the rectangular window.",
    "tutorial": "First, lets build a graph that represents only part of the polygon that is inside the window, as well as borders of the window. Do do this, for each segment of the polygon, find the intersection of that segment with the window, and, if it still is a segment with non-zero length, add it to the graph (add both endpoints as vertices and the segment itself as an edge). Next, add four corners of the window as vertices. Last, connect all the points on each of the four borders of the window with edges. This way, we have a planar graph, and we can find faces in this graph which will represent all the connected areas inside the window, both belonging to the polygon and not. To count only those that belong to the polygon one can mark those oriented edges, that were created while intersecting polygon's segments with the window, as important. Only mark an edge if it is directed the same way as the corresponding segment of the polygon. This way, those faces of the graph that are to the left of important edges, are the ones belonging to the polygon. But there is one bad case - when no segment of the polygon intersects with the window. It such case, the window is either entirely outside of the polygon, or entirely inside of it. To check this, find number of intersections of the polygon with a ray starting from inside of the window. If the number of intersections is even, the window is outside of the polygon. If it is odd, the window is outside.",
    "tags": [
      "data structures",
      "dsu",
      "geometry",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "963",
    "index": "A",
    "title": "Alternating Sum",
    "statement": "You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \\dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \\leq i \\leq n$ it's satisfied that $s_{i} = s_{i - k}$.\n\nFind out the \\textbf{non-negative} remainder of division of $\\sum \\limits_{i=0}^{n} s_{i} a^{n - i} b^{i}$ by $10^{9} + 9$.\n\n\\textbf{Note that the modulo is unusual!}",
    "tutorial": "Let $Z = \\sum \\limits_{i=0}^{k - 1} s_{i} a^{n - i} b^{i}$ and $q = (\\frac{b}{a})^k$. Let's notice that according equality is true: $\\sum \\limits_{i=0}^{n} s_{i} a^{n - i} b^{i} = \\sum \\limits_{i=0}^{(n + 1) / k - 1} Z \\cdot q^{i}$ We can easily get values of $Z$, $q$. We only have to count the value of geometric progression. Remember to handle the situation when $q = 1$. In this case it is not necessarily means that $a = b$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "963",
    "index": "B",
    "title": "Destruction of a Tree",
    "statement": "You are given a tree (a graph with $n$ vertices and $n - 1$ edges in which it's possible to reach any vertex from any other vertex using only its edges).\n\nA vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted.\n\nDestroy all vertices in the given tree or determine that it is impossible.",
    "tutorial": "If $n$ is even, then the answer is always $NO$, because such trees have odd degree, but we can destroy only even number of edges. For any odd $n$ the answer exists. Let's call $dfs(i)$ from subtree $i$ and destroy such nodes, that new subtree will be empty or for all alive nodes in connected component will be true, that they have odd degree. Realisation of this $dfs$: Call it from sons of $i$ and recount degree of $i$, if it is even we destroy all subtree. Assume, that after the destruction we have nonempty subtree. All nodes have odd degree, so amount of left nodes is even. So number of left edges is odd, but in start we have even count of edges, contradiction. That means, that we destroyed all nodes.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "963",
    "index": "C",
    "title": "Cutting Rectangle",
    "statement": "A rectangle with sides $A$ and $B$ is cut into rectangles with cuts parallel to its sides. For example, if $p$ horizontal and $q$ vertical cuts were made, $(p + 1) \\cdot (q + 1)$ rectangles were left after the cutting. After the cutting, rectangles were of $n$ different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles $a \\times b$ and $b \\times a$ are considered different if $a \\neq b$.\n\nFor each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle.\n\nCalculate the amount of pairs $(A; B)$ such as the given rectangles could be created by cutting the rectangle with sides of lengths $A$ and $B$. Note that pairs $(A; B)$ and $(B; A)$ are considered different when $A \\neq B$.",
    "tutorial": "There are a lot of ways to solve this problem. Let $a_i$ occurs in input $cnt_{a_{i}}$ (sum of $c$) times and $a_j$ occurs $cnt_{a_{j}}$. Then on a side of initial rectangle number of times $a_i$ occurs $/$ number of times $a_j$ occurs is a ratio $(cnt_{a_{i}}: cnt_{a_{j}})$. Analogically for $b$. Let's build the smallest rectangle which satisfies this ratio and call him the base one. Then initial rectangle should consist of it. The last step is to check that initial rectangle consists of base ones. To do this we'll iterate over all types of rectangles in input and if we find a mistake - print 0. In this way we will check no more than $n + 1$ types of recktangles. An answer for this task is number of divisors of ratio between the initial rectangle and the base one (it's not hard to see that this ratio equals to $GCD$ of all $c_i$)",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "963",
    "index": "D",
    "title": "Frequency of String",
    "statement": "You are given a string $s$. You should answer $n$ queries. The $i$-th query consists of integer $k_i$ and string $m_i$. The answer for this query is the minimum length of such a string $t$ that $t$ is a substring of $s$ and $m_i$ has at least $k_i$ occurrences as a substring in $t$.\n\nA substring of a string is a continuous segment of characters of the string.\n\nIt is guaranteed that for any two queries the strings $m_i$ from these queries are different.",
    "tutorial": "Let $M$ be the summary length of $m_i$ Number of different lengths of $m_i$ is $O(\\sqrt{M})$. All $m_i$ are distinct, so summary number of their entries in $s$ is $O(M\\sqrt{M}))$. Let's find all entries of every $m_i$. To do this we can use Aho-Corasick's algorithm. Then we know entries of $m_i$, it is not hard to calculate the answer.",
    "tags": [
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "963",
    "index": "E",
    "title": "Circles of Waiting",
    "statement": "A chip was placed on a field with coordinate system onto point $(0, 0)$.\n\nEvery second the chip moves randomly. If the chip is currently at a point $(x, y)$, after a second it moves to the point $(x - 1, y)$ with probability $p_{1}$, to the point $(x, y - 1)$ with probability $p_{2}$, to the point $(x + 1, y)$ with probability $p_{3}$ and to the point $(x, y + 1)$ with probability $p_{4}$. It's guaranteed that $p_{1} + p_{2} + p_{3} + p_{4} = 1$. The moves are independent.\n\nFind out the expected time after which chip will move away from origin at a distance greater than $R$ (i.e. $x^{2}+y^{2}\\!>R^{2}$ will be satisfied).",
    "tutorial": "Let's call a sell \"good\", if for its coordinates the following condition is satisfied $x^{2} + y^{2}  \\le  R^{2}$. For each good cell we consider the equation of its expected value: $f(x, y) = p_{1} \\cdot f(x - 1, y) + p_{2} \\cdot f(x, y + 1) + p_{3} \\cdot f(x + 1, y) + p_{4} \\cdot f(x, y - 1) + 1$. Then this problem can be reduced to solving the system of linear equations. We can do this using Gauss's method with a complexity of $O(R^{6})$, but this solution gets TL. Now, we can see that we only need to calculate $f(0, 0)$. So we will handle cells top down. While handling each row, we will relax values of all previous rows and a row of cell $(0;0)$. Also we will iterate only for non-zero elements of each row. This solution has a complexity of $O(R^{4})$. Prove of the complexity: Let's dye yellow all cells that we have already passed, green - all cells adjacent to them and black - all other cells. Then next cell which we will add is green. Note that its equation(for a moment of adding) doesn't include yellow cells. It consists of initially adjacent black cells and green cells. It's not hard to see, that then row includes only $O(R)$ non-zero elements and the current green cell is inside of $O(R)$ not visited rows. So one row in Gauss's method is handled in$O(R^{2})$ and there are $O(R^{2})$ rows. That's why this Gauss's method works in $O(R^{4})$.",
    "tags": [
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "964",
    "index": "A",
    "title": "Splits",
    "statement": "Let's define a split of $n$ as a nonincreasing sequence of positive integers, the sum of which is $n$.\n\nFor example, the following sequences are splits of $8$: $[4, 4]$, $[3, 3, 2]$, $[2, 2, 1, 1, 1, 1]$, $[5, 2, 1]$.\n\nThe following sequences aren't splits of $8$: $[1, 7]$, $[5, 4]$, $[11, -3]$, $[1, 1, 4, 1, 1]$.\n\nThe weight of a split is the number of elements in the split that are equal to the first element. For example, the weight of the split $[1, 1, 1, 1, 1]$ is $5$, the weight of the split $[5, 5, 3, 3, 3]$ is $2$ and the weight of the split $[9]$ equals $1$.\n\nFor a given $n$, find out the number of different weights of its splits.",
    "tutorial": "There are 2 cases: If weight of the split equals $n$, then the split consist of ones. Here we have only 1 option. Else maximum number in the split is more then 1. Then we can replace all maximum numbers with twos and the rest we split into ones and weight will be the same. So, here we have $\\frac{n}{2}$ options. Answer for this problem is $\\frac{n}{2}$ + 1.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "964",
    "index": "B",
    "title": "Messages",
    "statement": "There are $n$ incoming messages for Vasya. The $i$-th message is going to be received after $t_{i}$ minutes. Each message has a cost, which equals to $A$ initially. After being received, the cost of a message decreases by $B$ each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at $0$.\n\nAlso, each minute Vasya's bank account receives $C·k$, where $k$ is the amount of received but unread messages.\n\nVasya's messages are very important to him, and because of that he wants to have all messages read after $T$ minutes.\n\nDetermine the maximum amount of money Vasya's bank account can hold after $T$ minutes.",
    "tutorial": "Adding $C \\cdot k$ to account is equivalent to adding $C$ to prices of all come, but not read messages. Then after every minute to every unread messages adds $C - B$. If $C - B$ is positive, then answer is maximum when we read all messages at the time $T$. Otherwise we should read every message at the time it comes.",
    "tags": [
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "965",
    "index": "A",
    "title": "Paper Airplanes",
    "statement": "To make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make $s$ airplanes.\n\nA group of $k$ people decided to make $n$ airplanes each. They are going to buy several packs of paper, each of them containing $p$ sheets, and then distribute the sheets between the people. Each person should have enough sheets to make $n$ airplanes. How many packs should they buy?",
    "tutorial": "Each person should receive $\\lceil \\frac{n}{s} \\rceil$ sheets. So, there should be at least $k \\cdot \\lceil \\frac{n}{s} \\rceil$ sheets in total, for them $\\lceil \\frac{k \\cdot \\lceil \\frac{n}{s} \\rceil}{p} \\rceil$ packs are needed.",
    "code": "## This is a solution for problem make-planes\n#  This is nk_ok.py\n#\n#  @author: Nikolay Kalinin\n#  @date: Mon, 23 Apr 2018 16:28:50 +0300\n \nk, n, s, p = map(int, input().split())\nsheets_per_person = (n + s - 1) // s\nsheets = k * sheets_per_person\nprint((sheets + p - 1) // p)",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "965",
    "index": "B",
    "title": "Battleship",
    "statement": "Arkady is playing Battleship. The rules of this game aren't really important.\n\nThere is a field of $n \\times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.\n\nConsider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.",
    "tutorial": "Let's compute for each cell four values: the number of cells where a part of the ship can be located to the right ($r$), to the left ($l$), up ($u$) and down ($d$), including the cell itself. Then, if $k > 1$, then there are $\\min(k, \\max(0, l + r - k)) + \\min(k, \\max(0, u + d - k))$ positions of the ship containing this cell, and if $k = 1$ it's easy to check whether this value is $1$ or $0$. After that you should just print the maximum among all cells. This solution works in $O(n^3)$.",
    "code": "## This is a solution for problem sea-battle-best-shot\n#  This is nk_ok.py\n#\n#  @author: Nikolay Kalinin\n#  @date: Mon, 23 Apr 2018 16:48:18 +0300\n \nn, k = map(int, input().split())\na = []\nfor i in range(n):\n    a.append(input())\nmaxans = 0\nxans = 0\nyans = 0\nfor i in range(n):\n    for j in range(n):\n        curans = 0\n        l = 0\n        while l < k and i - l >= 0 and a[i - l][j] == '.':\n            l += 1\n        r = 0\n        while r < k and i + r < n and a[i + r][j] == '.':\n            r += 1\n        curans += max(0, r + l - k)\n        if k != 1:\n            l = 0\n            while l < k and j - l >= 0 and a[i][j - l] == '.':\n                l += 1\n            r = 0\n            while r < k and j + r < n and a[i][j + r] == '.':\n                r += 1\n            curans += max(0, r + l - k)\n        if curans > maxans:\n            maxans = curans\n            xans = i\n            yans = j\nprint(\"{} {}\".format(xans + 1, yans + 1))",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "965",
    "index": "C",
    "title": "Greedy Arkady",
    "statement": "$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away.\n\nThe people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away.\n\nArkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting.\n\nPlease find what is the maximum number of candies Arkady can receive by choosing some valid $x$.",
    "tutorial": "As the limits on $D$ are small, let's try all possible values of $d$ - the number of times Arkady will receive candies. For a given $d$ it's easy to compute $x_{min}$ and $x_{max}$ - the maximum and minimum values of $x$ that suit these $d$ and $M$. Then, with a fixed $d$ it's easy to write the formula of how many candies Arkady gets: it's $x \\cdot d$ candies. So it's obvious that we should choose $x_{max}$ for the given $d$ and update the answer. Bonus 1: can you solve the task when the leftover is not thrown away, but is given to the next person? Bonus 2: can you solve the task from bonus 1, but without the $D \\le 1000$ condition (just $1 \\le D \\le n$)?",
    "code": "## This is a solution for problem candies-splitting\n#  This is nk_ok.py\n#\n#  @author: Nikolay Kalinin\n#  @date: Mon, 23 Apr 2018 21:58:46 +0300\n \nn, k, M, D = map(int, input().split())\n \nans = 0\nfor d in range(1, D + 1):\n    # (d - 1) * k * x + x <= n\n    maxx = M\n    maxx = min(n // ((d - 1) * k + 1), maxx)\n    \n    if maxx == 0:\n        continue\n    reald = (n // maxx + k - 1) // k\n    if reald != d:\n        continue\n    \n    def f(x):\n        return x * (d - 1) + x\n    \n    ans = max(ans, f(maxx))\nprint(ans)",
    "tags": [
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "965",
    "index": "D",
    "title": "Single-use Stones",
    "statement": "A lot of frogs want to cross a river. A river is $w$ units width, but frogs can only jump $l$ units long, where $l < w$. Frogs can also jump on lengths shorter than $l$. but can't jump longer. Hopefully, there are some stones in the river to help them.\n\nThe stones are located at integer distances from the banks. There are $a_i$ stones at the distance of $i$ units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.\n\nWhat is the maximum number of frogs that can cross the river, given that then can only jump on the stones?",
    "tutorial": "This problem can be solved using many different approaches, most of them are based on different greedy solutions. We will discuss a solution with an easy-provable greedy. First, let's do binary search for the answer. Let it be $k$. Then, assume that the stones are given by their positions $x_1, x_2, \\ldots, x_m$, where $m$ is the total number of stones. Also assume $x_0 = 0$ and $x_{m+1} = w$ - the banks. Then, if for some $i$ the condition $x_{i+k} - x_i \\le l$ is not satisfied, then $k$ frogs can't cross the river. Indeed, consider the first jump for each frog that ends at a position further than $x_i$. It can't end at $x_{i+k}$ or further because of the length of the jump, so it has to end at some stone at $x_{i+1}$, $x_{i+2}$, ..., or $x_{i+k-1}$. But there are only $k - 1$ such stones, so some stone is used by two frogs which is prohibited. Now, if $x_{i+k} - x_i \\le l$ is satisfied, the frogs can easily cross the river by using the route $0 \\to x_i \\to x_{i+k} \\to x_{i + 2k} \\to \\ldots$ for the $i$-th frog. So, the solution is to do the binary search for the answer and then compute the maximum distance between stones $x_{i+k}$ and $x_i$. This can be done using two pointers technique.",
    "code": "/**\n * This line was copied from template\n * This is nk_ok.cpp\n * \n * @author: Nikolay Kalinin\n * @date: Mon, 23 Apr 2018 23:38:49 +0300\n */\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n \n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \nconst int maxn = 100005;\nconst int inf = 1e9 + 9;\n \nint a[maxn];\nint w, len;\n \nbool can(int k)\n{\n//     cout << \"can \" << k << endl;\n    int curj = 0;\n    int j = 0;\n    int curdiff = 0;\n    for (int i = 0; i < w; i++)\n    {\n        while ((curdiff < k - 1 || a[j] == 0) && j < w)\n        {\n            if (curdiff + a[j] - curj <= k - 1)\n            {\n                curdiff += a[j] - curj;\n                curj = 0;\n                j++;\n            } else\n            {\n                curj += k - 1 - curdiff;\n                curdiff = k - 1;\n            }\n//             cout << \"at \" << i << ' ' << j << ' ' << curj << endl;\n        }\n        if (j > i + len) return false;\n        curdiff -= a[i + 1];\n        if (j == w) break;\n    }\n    return true;\n}\n \nint main()\n{\n    scanf(\"%d%d\", &w, &len);\n    for (int i = 1; i < w; i++) scanf(\"%d\", &a[i]);\n    a[w] = 1;\n    int l = 0;\n    int r = inf;\n    while (r - l > 1)\n    {\n        int m = (l + r) / 2;\n        if (can(m)) l = m;\n        else r = m;\n    }\n    cout << l << endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "flows",
      "greedy",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "965",
    "index": "E",
    "title": "Short Code",
    "statement": "Arkady's code contains $n$ variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code.\n\nHe wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names.\n\nA string $a$ is a prefix of a string $b$ if you can delete some (possibly none) characters from the end of $b$ and obtain $a$.\n\nPlease find this minimum possible total length of new names.",
    "tutorial": "First, let's construct a trie of the names. Now a name is a token on some node in the graph, and we can move the token freely up to the root with the only constraint that no two tokens share the same node. We have to minimize the total depth of the nodes with tokens. For each subtree let's compute the optimal positions of tokens that were initially in the subtree assuming that no token moves higher than the root of the subtree. It can be done easily with dynamic programming: if the current note has a token initially, then the answer is simply the union of this node and all the answers for the children. Otherwise, one of the tokens from children's answer should be moved to the current node. Obviously, it is the token with the highest depth. We can easily maintaining this using sets and smaller-to-larger optimization. This solution runs in $O(m \\log^2{m})$, where $m$ is the total length of the strings. Also, due to the specific structure of the tree (because it is a trie and there is a constraint on the total length of the strings), we can do the same simulation without any data structures in $O(m)$ time.",
    "code": "/**\n * This line was copied from template\n * This is nk_ok.cpp\n * \n * @author: Nikolay Kalinin\n * @date: Tue, 24 Apr 2018 19:13:31 +0300\n */\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n \n#ifdef WIN32\n    #define LLD \"%I64d\"\n#else\n    #define LLD \"%lld\"\n#endif\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \nstruct tnode\n{\n    tnode *go[26];\n    bool term;\n    \n    tnode()\n    {\n        for (int i = 0; i < 26; i++) go[i] = NULL;\n        term = false;\n    }\n};\n \nusing pnode = tnode*;\n \npnode root;\nchar s[100005];\nint n;\n \nvoid add()\n{\n    pnode cur = root;\n    char *t = s;\n    while (*t != '\\0')\n    {\n        if (cur->go[*t - 'a'] == NULL) cur->go[*t - 'a'] = new tnode();\n        cur = cur->go[*t - 'a'];\n        t++;\n    }\n    cur->term = true;\n}\n \nusing tans = multiset<int>;\nusing pans = tans*;\n \npans merge(pans a, pans b)\n{\n    if (a->size() > b->size()) swap(a, b);\n    for (auto t : *a) b->insert(t);\n    delete a;\n    return b;\n}\n \npans calc(pnode cur, int curd)\n{\n    pans ans = new tans;\n    for (int i = 0; i < 26; i++) if (cur->go[i] != NULL)\n    {\n        auto t = calc(cur->go[i], curd + 1);\n        ans = merge(ans, t);\n    }\n    if (cur->term) ans->insert(curd);\n    else if (curd != 0)\n    {\n        ans->erase(prev(ans->end()));\n        ans->insert(curd);\n    }\n    return ans;\n}\n \nint main()\n{\n    root = new tnode();\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; i++)\n    {\n        scanf(\"%s\", s);\n        add();\n    }\n    auto ans = calc(root, 0);\n//     for (auto t : *ans) cout << t << ' ';\n//     cout << endl;\n    cout << accumulate(all(*ans), 0) << endl;\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "strings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "967",
    "index": "A",
    "title": "Mind the Gap",
    "statement": "These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $1$ minute.\n\nHe was asked to insert one takeoff in the schedule. The takeoff takes $1$ minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least $s$ minutes from both sides.\n\nFind the earliest time when Arkady can insert the takeoff.",
    "tutorial": "This problem requires you to carefully read and understand the statement. First, scan all the landing times, transforming each $h$ and $m$ pair into the number of minutes from the starting moment $60h + m$. Then, there are three possibilities: The first plane takes of not earlier than $s + 1$ minutes from now. In this case we may put new takeoff right now. Otherwise, if there is a pair of planes with at least $2 + 2s$ minutes between them. In this case we may choose the earliest such pair and put a new takeoff at $1 + s$ minutes after the first of these planes. Otherwise, we may always put a new plane in $1 + s$ minutes after the last plane. Finally, print the answer in an $h~m$ format.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "967",
    "index": "B",
    "title": "Watering System",
    "statement": "Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.\n\nArkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \\ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\\frac{s_i \\cdot A}{S}$ liters of water will flow out of it.\n\nWhat is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?",
    "tutorial": "It's obvious that we should block several largest holes. Let's first sort them. After that, let's iterate through the number of blocked holes, maintaining the sum of sizes of non-blocked holes $S$. With the value $S$ it is easy to compute if the flow from the first hole is large enough or not. Just output the number of blocked pipes at the first moment when the flow is large enough. The complexity is $O(n)$.",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "975",
    "index": "A",
    "title": "Aramic script",
    "statement": "In Aramic language words can only represent objects.\n\nWords in Aramic have special properties:\n\n- A word is a root if it does not contain the same letter more than once.\n- A root and all its permutations represent the same object.\n- The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of \"aaaa\", \"aa\", \"aaa\" is \"a\", the root of \"aabb\", \"bab\", \"baabb\", \"ab\" is \"ab\".\n- Any word in Aramic represents the same object as its root.\n\nYou have an ancient script in Aramic. What is the number of \\textbf{different objects} mentioned in the script?",
    "tutorial": "One can easily notice that we only differentiate between words when different letters exit, so one easy way to consider all the different words that belong to the same root as one, is to map every word to a mask of 26 bits; that is, for example, if letter 'b' exits in the ith word then we set the second bit in the ith mask to one, eventually, we insert all the masks in a set and the set size is the required answer.",
    "code": "\"#include<bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define sc(a) scanf(\\\"%d\\\",&a)\\n#define scs(a) scanf(\\\" %s\\\",a)\\n\\n\\ntypedef long long ll;\\n\\nconst int MAX = 1e3 + 11;\\n\\nchar in[MAX];\\nset<int> s;\\n\\nint main()\\n{\\n    int n;\\n    sc(n);\\n\\n    for(int i=0;i<n;++i)\\n    {\\n        scs(in);\\n        int l = strlen(in);\\n        int cur = 0;\\n        for(int j=0;j<l;++j)\\n            cur = cur | (1<<(in[j]-'a'));\\n        s.insert(cur);\\n    }\\n\\n    cout<<s.size();\\n\\n    return 0;\\n}\"",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "975",
    "index": "B",
    "title": "Mancala",
    "statement": "Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.\n\nInitially, each hole has $a_i$ stones. When a player makes a move, he chooses a hole which contains a \\textbf{positive} number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.\n\nNote that the counter-clockwise order means if the player takes the stones from hole $i$, he will put one stone in the $(i+1)$-th hole, then in the $(i+2)$-th, etc. If he puts a stone in the $14$-th hole, the next one will be put in the first hole.\n\nAfter the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.\n\nResli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.",
    "tutorial": "in this problem, we brute-force on the optimal hole to choose since there are only 14 holes, but how to calculate how many stones there will be after we start from the ith hole? the process of putting stones is repeating every 14 holes, suppose k is the number of stones in hand now so k/14 will be added to all holes and we simulate adding k mod 14 then we take the maximum answer from all the holes.",
    "code": "\"#include<bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define sc(a) scanf(\\\"%lld\\\",&a)\\n\\ntypedef long long ll;\\n\\nconst int MAX = 5e3 + 11;\\n\\nll a[22];\\nll pro[22];\\n\\nint main()\\n{\\n    for(int i=0;i<14;++i)\\n        sc(a[i]);\\n\\n    ll res = 0;\\n\\n    for(int i=0;i<14;++i)\\n    {\\n        for(int j=0;j<14;++j)\\n            pro[j] = a[j];\\n        ll tmp = pro[i];\\n        pro[i] = 0;\\n        for(int j=0;j<14;++j)\\n            pro[j] += tmp/14;\\n        tmp %= 14;\\n        int k = i+1;\\n        while(tmp--)\\n        {\\n            if(k == 14)\\n                k = 0;\\n            pro[k++]++;\\n        }\\n        ll score = 0;\\n        for(int j=0;j<14;++j)\\n        {\\n            if(pro[j] & 1)\\n                continue;\\n            score += pro[j];\\n        }\\n        res = max(res,score);\\n    }\\n\\n    cout<<res;\\n\\n\\n    return 0;\\n}\"",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "975",
    "index": "C",
    "title": "Valhalla Siege",
    "statement": "Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.\n\nIvar has $n$ warriors, he places them on a straight line in front of the main gate, in a way that the $i$-th warrior stands right after $(i-1)$-th warrior. The first warrior leads the attack.\n\nEach attacker can take up to $a_i$ arrows before he falls to the ground, where $a_i$ is the $i$-th warrior's strength.\n\nLagertha orders her warriors to shoot $k_i$ arrows during the $i$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $t$, they will all be standing to fight at the end of minute $t$.\n\nThe battle will last for $q$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.",
    "tutorial": "naive simulations will get TLE, so how to calculate fast how many people are going to die after the ith query, we can binary search on the prefix sum. Thus, we can tell how many people are going to die in O(log n) per query. Note: beware to handle the queries that do a partial damage for some warrior and include that partial damage in the later queries.",
    "code": "\"#include<bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define sc(a) scanf(\\\"%d\\\",&a)\\n#define scll(a) scanf(\\\"%lld\\\",&a)\\n\\ntypedef long long ll;\\n\\nconst int MAX = 2e5 + 11;\\n\\nll a[MAX],csum[MAX];\\nint n;\\n\\nint bs(int pos,ll &hits,ll val)\\n{\\n    if(val + hits < a[pos])\\n    {\\n        hits += val;\\n        return pos;\\n    }\\n    int st = pos,en = n;\\n    int ret;\\n    while(st <= en)\\n    {\\n        int md = (st + en)>>1;\\n        if(csum[md] - csum[pos - 1] - hits <= val)\\n            st = md + 1,ret = md;\\n        else\\n            en = md - 1;\\n    }\\n    if(ret == n)\\n    {\\n        hits = 0;\\n        return 1;\\n    }\\n    ret++;\\n    ll tmp = csum[ret] - csum[pos - 1] - hits - val;\\n    hits = a[ret] - tmp;\\n    return ret;\\n}\\n\\nint main()\\n{\\n    int q;\\n    sc(n);\\n    sc(q);\\n\\n    ll sm = 0;\\n\\n    for(int i=1;i<=n;++i)\\n    {\\n        scll(a[i]);\\n        csum[i] = csum[i - 1] + a[i];\\n    }\\n\\n    int cur = 1;\\n    ll hits = 0;\\n\\n    for(int i=0;i<q;++i)\\n    {\\n        ll x;\\n        scll(x);\\n        cur = bs(cur,hits,x);\\n        printf(\\\"%d\\\\n\\\",n - cur + 1);\\n    }\\n\\n    return 0;\\n}\"",
    "tags": [
      "binary search"
    ],
    "rating": 1400
  },
  {
    "contest_id": "975",
    "index": "D",
    "title": "Ghosts",
    "statement": "Ghosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.\n\nThere are $n$ ghosts in the universe, they move in the $OXY$ plane, each one of them has its own velocity that does not change in time: $\\overrightarrow{V} = V_{x}\\overrightarrow{i} + V_{y}\\overrightarrow{j}$ where $V_{x}$ is its speed on the $x$-axis and $V_{y}$ is on the $y$-axis.\n\nA ghost $i$ has experience value $EX_i$, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.\n\nAs the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind $GX = \\sum_{i=1}^{n} EX_i$ will never increase.\n\nTameem is a red giant, he took a picture of the cartesian plane at a certain moment of time $T$, and magically all the ghosts were aligned on a line of the form $y = a \\cdot x + b$. You have to compute what will be the experience index of the ghost kind $GX$ in the indefinite future, this is your task for today.\n\nNote that when Tameem took the picture, $GX$ may already be greater than $0$, because many ghosts may have scared one another at any moment between $[-\\infty, T]$.",
    "tutorial": "The condition for two points to meet in a moment of time T is for them to have the same X coordinates and the same Y coordinates. Time when they have the same X coordinates is $X_{0i} + V_{xi} T_x = X_{0j} + V_{xj} T_x$ So $T_x$ should be $T_x = (X_{0i} - X_{0j})/ (V_{xj} - V_{xi})$ Time when they will meet on Y axis $T_y = (aX_{0i} - aX_{0j} + b -b)/ (V_{yj} - V_{yi})$ In order for them to collide $T_y = T_x$ so $(X_{0i} - X_{0j})/ (V_{xj} - V_{xi}) = (aX_{0i} - aX_{0j} + b -b)/ (V_{yj} - V_{yi})$ so $1/(V_{xj} - V_{xi}) = a/(V_{yj} - V_{yi})$ So $a V_{xj} - V_{yj} = a V_{xi} - V_{yi}$ Meaning that all ghosts with the same $a V_{x} - V_{y}$ will collide except if they were parallel. the answer is two times the number of collisions.",
    "code": "\"#include <bits/stdc++.h>\\nconst int MX = 2e5+5;\\nusing namespace std;\\ntypedef long long ll;\\nint main() {\\n  int n;cin>>n;ll a,b;cin>>a>>b;\\n  map<ll,ll> vis;\\n  map<pair<int,int>,int> sim;\\n  ll ans = 0;\\n  for(int i=1;i<=n;i++)\\n  {\\n        int x,vx,vy;\\n       scanf(\\\"%d%d%d\\\",&x,&vx,&vy);\\n        ans += vis[a*vx-vy] - sim[{vx,vy}];\\n        vis[a*vx-vy]++;\\n        sim[{vx,vy}]++;\\n  }\\n  cout<<2*ans<<endl;\\n}\"",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "975",
    "index": "E",
    "title": "Hag's Khashba",
    "statement": "Hag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering.\n\nYesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance.\n\nHag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a \\textbf{strictly convex} polygon with $n$ vertices.\n\nHag brought two pins and pinned the polygon with them in the $1$-st and $2$-nd vertices to the wall. His dad has $q$ queries to Hag of two types.\n\n- $1$ $f$ $t$: pull a pin from the vertex $f$, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex $t$.\n- $2$ $v$: answer what are the coordinates of the vertex $v$.\n\nPlease help Hag to answer his father's queries.\n\nYou can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.",
    "tutorial": "In this problem, we calculate the center of mass of the polygon (ie its centroid) and then we make it our reference point. we maintain its coordinates after each and every rotation. Now when the pin is taken out from a vertex it leaves the other pin as a pivot for rotation we calculate the angle of current rotation. calculate the new coordinates of the center of mass after rotation, we should also store the initial distances from the center of mass, and the angle that the polygon had rotated around itself. from the angle, coordinates of the center of mass and the initial distances from the center of mass it is possible to calculate the coordinates of any point in the polygon. Note: when calculating the center of mass we should shift the polygon to the (0,0) because in some algorithms it uses point (0,0) in triangulation the polygon. if the polygon is very far from (0,0) accuracy will be lost. so better to either shift the polygon to (0,0) or use the first point of the polygon to form the sub-triangles of the polygon when calculating the center of mass.",
    "code": "\"#include <algorithm>\\n#include <bitset>\\n#include <complex>\\n#include <cassert>\\n#include <deque>\\n#include <iostream>\\n#include <iomanip>\\n#include <istream>\\n#include <iterator>\\n#include <map>\\n#include <math.h>\\n#include <memory>\\n#include <ostream>\\n#include <queue>\\n#include <set>\\n#include <sstream>\\n#include <stack>\\n#include <string>\\n#include <string.h>\\n#include <time.h>\\n#include <vector>\\n\\n#define INF_MAX 2147483647\\n#define INF_MIN -2147483647\\n#define INF_LL 4000000000000000000LL\\n#define INF 1000000000\\n#define EPS 1e-8\\n#define LL long long\\n#define mod 1000000007\\n#define pb push_back\\n#define mp make_pair\\n#define f first\\n#define s second\\n#define setzero(a) memset(a,0,sizeof(a))\\n#define setdp(a) memset(a,-1,sizeof(a))\\n#define bits(a) __builtin_popcountll(a)\\n\\nusing namespace std;\\n\\ntypedef pair<long double, long double> point;\\n\\nconst long double PI = acosl(-1);\\n\\npoint arr[200009];\\nlong double dist[200009], ang[200009];\\n\\npoint get_centroid(int n) {\\n  long double area = 0.0, tmp;\\n  point a, b, res = point(0, 0);\\n  for (int i = 0; i < n; i++) {\\n    a = arr[i], b = arr[(i + 1) % n];\\n    tmp = a.f * b.s - b.f * a.s;\\n    area += tmp;\\n    res.f += (a.f + b.f) * tmp;\\n    res.s += (a.s + b.s) * tmp;\\n  }\\n  area *= 0.5;\\n  res.f /= (area * 6);\\n  res.s /= (area * 6);\\n  return res;\\n}\\n\\npoint get(int ind, const point &centroid, const double &angle) {\\n  point ans;\\n  ans.f = centroid.f + dist[ind] * cosl(angle + ang[ind]);\\n  ans.s = centroid.s + dist[ind] * sinl(angle + ang[ind]);\\n  return ans;\\n}\\n\\nlong double get_dist(const point &a, const point &b) {\\n  return sqrtl((a.f - b.f) * (a.f - b.f) + (a.s - b.s) * (a.s - b.s));\\n}\\n\\nint main() {\\n  int n, q;\\n  double a, b;\\n  cin >> n >> q;\\n  for (int i = 0; i < n; i++) {\\n    scanf(\\\"%lf %lf\\\", &a, &b);\\n    arr[i] = point(a, b);\\n  }\\n  long double zbx=arr[0].first,zby=arr[0].second;\\n  for(int i=0; i < n; i++)\\n  {\\n      arr[i].first-=zbx;\\n      arr[i].second-=zby;\\n  }\\n  int i = 0, j = 1, c, x, y;\\n  point centroid = get_centroid(n), top, nxt;\\n  long double angle = 0;\\n  for (int i = 0; i < n; i++) {\\n    dist[i] = get_dist(arr[i], centroid);\\n    ang[i] = atan2l(arr[i].s - centroid.s, arr[i].f - centroid.f);\\n    if (ang[i] < 0)\\n      ang[i] += 2 * PI;\\n  }\\n  while (q--) {\\n    scanf(\\\"%d\\\", &c);\\n    if (c == 1) {\\n      scanf(\\\"%d %d\\\", &x, &y);\\n      x--, y--;\\n      if (x == i) {\\n        i = y;\\n        top = get(j, centroid, angle);\\n        nxt = point(top.f, top.s - dist[j]);\\n      } else {\\n        j = y;\\n        top = get(i, centroid, angle);\\n        nxt = point(top.f, top.s - dist[i]);\\n      }\\n      angle += -PI / 2 - atan2l(centroid.s - top.s, centroid.f - top.f);\\n      while (angle < 0)\\n        angle += 2 * PI;\\n      while (angle > 2 * PI)\\n        angle -= 2 * PI;\\n      centroid = nxt;\\n    } else {\\n      scanf(\\\"%d\\\", &x);\\n      top = get(x - 1, centroid, angle);\\n      printf(\\\"%.10lf %.10lf\\\\n\\\", (double) (top.f+zbx), (double) (top.s+zby));\\n    }\\n  }\\n  return 0;\\n}\"",
    "tags": [
      "geometry"
    ],
    "rating": 2600
  },
  {
    "contest_id": "976",
    "index": "A",
    "title": "Minimum Binary Number",
    "statement": "String can be called correct if it consists of characters \"0\" and \"1\" and there are no redundant leading zeroes. Here are some examples: \"0\", \"10\", \"1001\".\n\nYou are given a correct string $s$.\n\nYou can perform two different operations on this string:\n\n- swap any pair of adjacent characters (for example, \"{1\\underline{01}}\" $\\to$ \"{1\\underline{10}}\");\n- replace \"11\" with \"1\" (for example, \"{\\underline{11}0}\" $\\to$ \"{\\underline{1}0}\").\n\nLet $val(s)$ be such a number that $s$ is its binary representation.\n\nCorrect string $a$ is less than some other correct string $b$ iff $val(a) < val(b)$.\n\nYour task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).",
    "tutorial": "If $n = 1$ then the answer is equal to $s$. Otherwise answer will be equal to $2^{cnt0}$, where $cnt_{0}$ is the count of the zeroes in the given string (i.e. the answer is the binary string of length $cnt_{0} + 1$, in which the first character is one and the other characters are zeroes).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\tif (n == 1) {\n\t\tcout << s << endl;\n\t} else {\n\t\tint cnt0 = 0;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tcnt0 += s[i] == '0';\n\t\tcout << 1;\n\t\tfor (int i = 0; i < cnt0; ++i)\n\t\t\tcout << 0;\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "976",
    "index": "B",
    "title": "Lara Croft and the New Game",
    "statement": "You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.\n\nLara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of $n$ rows and $m$ columns. Cell $(x, y)$ is the cell in the $x$-th row in the $y$-th column. Lara can move between the neighbouring by side cells in all four directions.\n\nMoreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell $(1, 1)$, that is top left corner of the matrix. Then she goes down all the way to cell $(n, 1)$ — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in $2$-nd column, one cell up. She moves until she runs out of non-visited cells. $n$ and $m$ given are such that she always end up in cell $(1, 2)$.\n\nLara has already moved to a neighbouring cell $k$ times. Can you determine her current position?",
    "tutorial": "Naive solution would be just simulate the tranversal and break when $k$ steps are made. Obviously, this won't fit into time limit. Then we can decompose the path to some parts which can be calculated separately. Walk from the top left to the bottom left corner; Walk from second column to $m$-th on even rows; Walk from $m$-th column to second on odd rows. If $k < n$ then it's the first part. Otherwise you can use the fact that rows are of the same length. $(k - n)div(m - 1)$ will tell you the row and $(k - n)mod(m - 1)$ will get you the number of steps Lara have made along this row. Overall complexity: $O(1)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n, m;\nlong long k;\n\nint main() {\n\tscanf(\"%d%d%lld\", &n, &m, &k);\n\tif (k < n){\n\t\tprintf(\"%lld 1\\n\", k + 1);\n\t\treturn 0;\n\t}\n\tk -= n;\n\tlong long row = k / (m - 1);\n\tprintf(\"%lld \", n - row);\n\tif (row & 1)\n\t\tprintf(\"%lld\\n\", m - k % (m - 1));\n\telse\n\t\tprintf(\"%lld\\n\", k % (m - 1) + 2);\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "976",
    "index": "C",
    "title": "Nested Segments",
    "statement": "You are given a sequence $a_{1}, a_{2}, ..., a_{n}$ of one-dimensional segments numbered $1$ through $n$. Your task is to find two distinct indices $i$ and $j$ such that segment $a_{i}$ lies within segment $a_{j}$.\n\nSegment $[l_{1}, r_{1}]$ lies within segment $[l_{2}, r_{2}]$ iff $l_{1} ≥ l_{2}$ and $r_{1} ≤ r_{2}$.\n\nPrint indices $i$ and $j$. If there are multiple answers, print any of them. If no answer exists, print -1 -1.",
    "tutorial": "Let's sort segments firstly by their left border in increasing order and in case of equal by their right border in decreasing order. If there is any valid pair then the inner segment will always go after the outer one. Now you can go from left to right, keep the maximum right border of processed segments and compare it to the current segment. Overall complexity: $O(n\\cdot\\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef pair<int, int> pt;\n\nconst int N = 300 * 1000 + 13;\n\nint n;\npair<pt, int> a[N];\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n){\n\t\tscanf(\"%d%d\", &a[i].x.x, &a[i].x.y);\n\t\ta[i].y = i + 1;\n\t}\n\t\n\tsort(a, a + n, [&](pair<pt, int> a, pair<pt, int> b){if (a.x.x != b.x.x) return a.x.x < b.x.x; return a.x.y > b.x.y;});\n\t\n\tset<pt> cur;\n\tforn(i, n){\n\t\twhile (!cur.empty() && cur.begin()->x < a[i].x.x)\n\t\t\tcur.erase(cur.begin());\n\t\tif (!cur.empty() && (--cur.end())->x >= a[i].x.y){\n\t\t\tprintf(\"%d %d\\n\", a[i].y, (--cur.end())->y);\n\t\t\treturn 0;\n\t\t}\n\t\tcur.insert({a[i].x.y, a[i].y});\n\t}\n\t\n\tputs(\"-1 -1\");\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "976",
    "index": "D",
    "title": "Degree Set",
    "statement": "You are given a sequence of $n$ positive integers $d_{1}, d_{2}, ..., d_{n}$ ($d_{1} < d_{2} < ... < d_{n}$). Your task is to construct an undirected graph such that:\n\n- there are exactly $d_{n} + 1$ vertices;\n- there are no self-loops;\n- there are no multiple edges;\n- there are no more than $10^{6}$ edges;\n- its degree set is equal to $d$.\n\nVertices should be numbered $1$ through $(d_{n} + 1)$.\n\nDegree sequence is an array $a$ with length equal to the number of vertices in a graph such that $a_{i}$ is the number of vertices adjacent to $i$-th vertex.\n\nDegree set is a sorted in increasing order sequence of all distinct values from the degree sequence.\n\nIt is guaranteed that there exists such a graph that all the conditions hold, and it contains no more than $10^{6}$ edges.\n\nPrint the resulting graph.",
    "tutorial": "We prove that the answer always always exists by constructing it. Graph for $n = 0$ is a single vertex; Graph for $n = 1$ is a clique of $d_{1} + 1$ vertices; Graph for some $(d_{1}, d_{2}, ..., d_{k})$ is obtained from the graph $(d_{2} - d_{1}, d_{3} - d_{1}, ..., d_{k - 1} - d_{1})$ by adding $(d_{k} - d_{k - 1})$ vertices initially connected to nothing and $d_{1}$ vertices connected to all previously mentioned ones. The vertices connected to nothing got degrees $d_{1}$, the vertices from the previous step increased their degrees by $d_{1}$ and finally there appeared vertices of degree $d_{k}$. The number is vertices is $d_{k} + 1$ as needed.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\ntypedef pair<int, int> pt;\n\nconst int N = 100 * 1000 + 13;\n\nint n;\nvector<int> d;\nvector<int> g[N];\n\nvector<pt> construct(int st, vector<int> d){\n\tif (d.empty())\n\t\treturn vector<pt>();\n\t\n\tvector<pt> res;\n\tforn(i, d[0])\n\t\tfor (int j = st + i + 1; j <= st + d.back(); ++j)\n\t\t\tres.push_back({st + i, j});\n\t\n\tint nxt = st + d[0];\n\tfor (int i = 1; i < int(d.size()); ++i)\n\t\td[i] -= d[0];\n\td.erase(d.begin());\n\tif (!d.empty())\n\t\td.pop_back();\n\t\n\tauto tmp = construct(nxt, d);\n\tfor (auto it : tmp)\n\t\tres.push_back(it);\n\t\n\treturn res;\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\td.resize(n);\n\tforn(i, n)\n\t\tscanf(\"%d\", &d[i]);\n\tauto res = construct(0, d);\n\tprintf(\"%d\\n\", int(res.size()));\n\tfor (auto it : res)\n\t\tprintf(\"%d %d\\n\", it.first + 1, it.second + 1);\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "976",
    "index": "E",
    "title": "Well played!",
    "statement": "Recently Max has got himself into popular CCG \"BrainStone\". As \"BrainStone\" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them:\n\nMax owns $n$ creatures, $i$-th of them can be described with two numbers — its health $hp_{i}$ and its damage $dmg_{i}$. Max also has two types of spells in stock:\n\n- Doubles health of the creature ($hp_{i}$ := $hp_{i}·2$);\n- Assigns value of \\textbf{health} of the creature to its \\textbf{damage} ($dmg_{i}$ := $hp_{i}$).\n\nSpell of first type can be used no more than $a$ times in total, of the second type — no more than $b$ times in total. Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells.\n\nMax is really busy preparing for his final exams, so he asks you to determine what is the maximal total damage of all creatures he can achieve if he uses spells in most optimal way.",
    "tutorial": "At first let's prove that in optimal solution all spells of 1-st type are assigned to single creature. By contradiction: let's optimal answer contains indices $i  \\neq  j$ where $hp'_{i} = hp_{i} \\cdot 2^{x}$ and $hp'_{j} = hp_{j} \\cdot 2^{y}$. If $hp'_{i(j)}  \\le  dmg_{i(j)}$ using spells of 1-st type is meaningless. Otherwise, if (in general case) $hp'_{i}  \\ge  hp'_{j}$ then $hp_{i} \\cdot 2^{x + 1} + hp_{j} \\cdot 2^{y - 1} > hp'_{i} + hp'_{j}$. Contradiction. So, we can check for each creature maximal damage with its health multiplied. At second, if we sort all creatures in order by decreasing $(hp_{i} - dmg_{i})$, using $b$ spells on first $b$ creatures gives best answer $ans$. So, calculating answer for chosen creature invokes 2 cases: if chosen creature is belong to first $b$ creatures, then subtract from $ans$ its contribution, calculate new value and add it to $ans$; otherwise, we need one spell of second type, which is optimal to take from $b$-th creature, so along with replacing old value of chosen one we need to replace in $ans$ contribution of $b$-th creature. Result complexity is $O(n \\cdot log(n))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 9;\n\nint n, a, b;\nint hp[N], dmg[N];\n\nbool cmp(int i, int j){\n\tif(hp[i] - dmg[i] != hp[j] - dmg[j])\n\t\treturn hp[i] - dmg[i] > hp[j] - dmg[j];\n\treturn i < j;\n}\n\nint get(int id){\n\treturn  hp[id] > dmg[id]? hp[id] : dmg[id];\n}\n\nint main(){\n\tscanf(\"%d %d %d\", &n, &a, &b);\n\tfor(int i = 0; i < n; ++i)\n\t\tscanf(\"%d %d\", hp + i, dmg + i);\n\t\n\tb = min(b, n);\n\tvector <int> p(n);\n\tfor(int i = 0; i < n; ++i) p[i] = i;\n\tsort(p.begin(), p.end(), cmp);\n\tlong long res = 0, sum = 0;\n\tfor(int i = 0; i < n; ++i){\n\t\tint id = p[i];\n\t\tif(i < b) sum += get(id);\n\t\telse sum += dmg[id];\n\t}\n\tres = sum; \n\n\tif(b == 0){\n\t\tprintf(\"%lld\\n\", res);\n\t\treturn 0;\n\t}\n\t\n\tlong long x = (1LL << a);\n\tfor(int i = 0; i < n; ++i){\n\t\tint id = p[i];\n\t\tlong long nres = sum;\n\t\tif(i < b){ \n\t\t\tnres -= get(id);\n\t\t\tnres += hp[id] * x;\n\t\t\tres = max(res, nres);\n\t\t}\n\t\telse{\n\t\t\tnres -= dmg[id];\n\t\t\tnres += hp[id] * x;\t\t\t\n\t\t\tint id2 = p[b - 1];\n\t\t\tnres -= get(id2);\n\t\t\tnres += dmg[id2];\n\t\t\tres = max(res, nres);\n\t\t\t\n\t\t}\t\t\n\t}\n\t\n\tprintf(\"%lld\\n\", res);\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "976",
    "index": "F",
    "title": "Minimal k-covering",
    "statement": "You are given a bipartite graph $G = (U, V, E)$, $U$ is the set of vertices of the first part, $V$ is the set of vertices of the second part and $E$ is the set of edges. There might be multiple edges.\n\nLet's call some subset of its edges $\\bar{E}$ $k$-covering iff the graph ${\\bar{G}}=(U,V,{\\bar{E}})$ has each of its vertices incident to at least $k$ edges. Minimal $k$-covering is such a $k$-covering that the size of the subset $\\bar{E}$ is minimal possible.\n\nYour task is to find minimal $k$-covering for each $k\\in[0..m i n D e g r e e]$, where $minDegree$ is the minimal degree of any vertex in graph $G$.",
    "tutorial": "To get the answer for some $k$ we can build the following network: connect the source to every vertex of the first part with edge with capacity $deg_{x} - k$ (where $deg_{x}$ is the degree of vertex), then transform every edge of the original graph into a directed edge with capacity $1$, and then connect each vertex from the second part to the sink with capacity $deg_{x} - k$. Then edges saturated by the maxflow are not present in the answer (and all other edges are in the answer). To solve it fastly, we might just iterate on $k$ from its greatest value to $0$ and each time augment the flow we found on previous iteration. Since maxflow in the network is at most $m$, and we will do not more than $m$ searches that don't augment the flow, this solution is $O((n + m)^{2})$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define sz(a) int((a).size())\n#define x first\n#define y second\n\nconst int INF = int(1e9);\nconst int N = 4221;\n\nstruct edge {\n    int to, c, f, id;\n\n    edge(int to = 0, int c = 0, int f = 0, int id = -1) : to(to), c(c), f(f), id(id) {}\n};\n\nvector<edge> es;\nvector<int> g[N];\n\nvoid add_edge(int fr, int to, int cap, int id) {\n    g[fr].push_back(sz(es));\n    es.emplace_back(to, cap, 0, id);\n    g[to].push_back(sz(es));\n    es.emplace_back(fr, 0, 0, id);\n}\n\nint pw[N];\nint n1, n2, m;\n\ninline bool read() {\n    if(!(cin >> n1 >> n2 >> m))\n        return false;\n\n    fore(id, 0, m) {\n        int u, v;\n        assert(cin >> u >> v);\n        u--, v--;\n\n        pw[u]++;\n        pw[n1 + v]++;\n\n        add_edge(u, n1 + v, 1, id);\n    }\n    return true;\n}\n\nint d[N], q[N], hd, tl;\ninline bool bfs(int s, int t, int n) {\n    fore(i, 0, n)\n        d[i] = INF;\n    hd = tl = 0;\n\n    d[s] = 0;\n    q[tl++] = s;\n    while(hd != tl) {\n        int v = q[hd++];\n        if(v == t)\n            break;\n\n        for(int id : g[v]) {\n            if(es[id].c - es[id].f == 0)\n                continue;\n\n            int to = es[id].to;\n            if(d[to] > d[v] + 1) {\n                d[to] = d[v] + 1;\n                q[tl++] = to;\n            }\n        }\n    }\n    return d[t] < INF;\n}\n\nint nxt[N];\n\nint dfs(int v, int t, int mx) {\n    if(v == t) return mx;\n    if(mx == 0) return 0;\n\n    int sum = 0;\n    for(; nxt[v] < sz(g[v]); nxt[v]++) {\n        int id = g[v][nxt[v]];\n        int rem = es[id].c - es[id].f;\n        int to = es[id].to;\n\n        if(rem == 0 || d[to] != d[v] + 1)\n            continue;\n\n        int cur = 0;\n        if((cur = dfs(to, t, min(mx - sum, rem))) > 0) {\n            es[id].f += cur;\n            es[id ^ 1].f -= cur;\n            sum += cur;\n        }\n\n        if(sum == mx)\n            break;\n    }\n    return sum;\n}\n\ninline int dinic(int s, int t, int n) {\n    int mf = 0;\n    while(bfs(s, t, n)) {\n        fore(i, 0, n)\n            nxt[i] = 0;\n\n        int cf = 0;\n        while((cf = dfs(s, t, INF)) > 0)\n            mf += cf;\n    }\n    return mf;\n}\n\nvector<int> res[N];\n\ninline void getCert(int k) {\n    fore(v, 0, n1) {\n        for(int id : g[v]) {\n            if(es[id].to < n1 || es[id].to >= n1 + n2)\n                continue;\n            assert(es[id].c > 0);\n            if(es[id].f > 0)\n                continue;\n\n            res[k].push_back(es[id].id);\n        }\n    }\n}\n\nvoid solve() {\n    int cnt = *min_element(pw, pw + n1 + n2);\n\n    int s = n1 + n2; int t = s + 1;\n    fore(i, 0, n1)\n        add_edge(s, i, pw[i] - cnt, -1);\n    fore(i, n1, n1 + n2)\n        add_edge(i, t, pw[i] - cnt, -1);\n\n    int mf = 0, mn = cnt;\n    while(mn >= 0) {\n        mf += dinic(s, t, n1 + n2 + 2);\n        getCert(mn);\n\n        if(mn > 0) {\n            for (int id : g[s]) {\n                assert(es[id].id < 0);\n                assert((id & 1) == 0);\n                es[id].c++;\n            }\n            for (int id : g[t]) {\n                assert(es[id].id < 0);\n                assert(es[id].c == 0);\n                es[id ^ 1].c++;\n            }\n        }\n        mn--;\n    }\n\n    fore(i, 0, cnt + 1) {\n        printf(\"%d \", sz(res[i]));\n        for(int id : res[i])\n            printf(\"%d \", id + 1);\n        puts(\"\");\n    }\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n#endif\n\n    if(read()) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "977",
    "index": "A",
    "title": "Wrong Subtraction",
    "statement": "Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:\n\n- if the last digit of the number is non-zero, she decreases the number by one;\n- if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit).\n\nYou are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions.\n\nIt is guaranteed that the result will be positive integer number.",
    "tutorial": "In this problem you just need to simulate the process described in the statement (i.e. $k$ times repeat the following operation: if $n \\% 10 = 0$ then $n := n / 10$ else $n := n - 1$) and print the result.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint n, k;\n\tcin >> n >> k;\n\t\n\tfor (int i = 0; i < k; ++i) {\n\t\tif (n % 10 == 0) n /= 10;\n\t\telse n--;\n\t}\n\t\n\tcout << n << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "977",
    "index": "B",
    "title": "Two-gram",
    "statement": "Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, \"AZ\", \"AA\", \"ZA\" — three distinct two-grams.\n\nYou are given a string $s$ consisting of $n$ capital Latin letters. Your task is to find \\textbf{any} two-gram contained in the given string \\textbf{as a substring} (i.e. two consecutive characters of the string) maximal number of times. For example, for string $s$ = \"BBAABBBA\" the answer is two-gram \"BB\", which contained in $s$ three times. In other words, find any most frequent two-gram.\n\nNote that occurrences of the two-gram can overlap with each other.",
    "tutorial": "There are at least two different approaches to this problem: You can iterate over all substrings of $s$ of length $2$ and calculate for each of them the number of its occurrences in $s$ (and try to update the result with the current substring). Also you can iterate over all two-grams in the alphabet and do the same as in the aforementioned solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\t\n\tint res = 0;\n\tstring ans;\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint cur = 0;\n\t\tfor (int j = 0; j < n - 1; ++j)\n\t\t\tif (s[j] == s[i] && s[j + 1] == s[i + 1])\n\t\t\t\t++cur;\n\t\tif (res < cur) {\n\t\t\tres = cur;\n\t\t\tans = string(1, s[i]) + string(1, s[i + 1]);\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "977",
    "index": "C",
    "title": "Less or Equal",
    "statement": "You are given a sequence of integers of length $n$ and integer number $k$. You should print \\textbf{any integer} number $x$ in the range of $[1; 10^9]$ (i.e. $1 \\le x \\le 10^9$) such that exactly $k$ elements of given sequence are less than or equal to $x$.\n\nNote that the sequence can contain equal elements.\n\nIf there is no such $x$, print \"-1\" (without quotes).",
    "tutorial": "In this problem you can do the following thing: firstly, let's sort our array. Let $ans$ will be the answer. Then you have two cases: if $k = 0$ then $ans := a_0 - 1$ otherwise $ans := a_{k - 1}$ (for 0-indexed array). Then you need to calculate the number of the elements of the array $a$ that are less than or equal to $ans$. Let it be $cnt$. Then if $ans < 1$ or $cnt \\ne k$ then print \"-1\" otherwise print $ans$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tscanf(\"%d %d\", &n, &k);\n\t\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tsort(a.begin(), a.end());\n\t\n\tint ans;\n\t\n\tif (k == 0) {\n\t\tans = a[0] - 1;\n\t} else {\n\t\tans = a[k - 1];\n\t}\n\t\n\tint cnt = 0;\n\t\n\tfor (int i = 0; i < n; ++i)\n\t\tif (a[i] <= ans) ++cnt;\n\t\n\tif (cnt != k || !(1 <= ans && ans <= 1000 * 1000 * 1000)) {\n\t\tputs(\"-1\");\n\t\treturn 0;\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n\t\n\treturn 0;\n}",
    "tags": [
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "977",
    "index": "D",
    "title": "Divide by three, multiply by two",
    "statement": "Polycarp likes to play with numbers. He takes some integer number $x$, writes it down on the board, and then performs with it $n - 1$ operations of the two kinds:\n\n- divide the number $x$ by $3$ ($x$ must be divisible by $3$);\n- multiply the number $x$ by $2$.\n\nAfter each operation, Polycarp writes down the result on the board and replaces $x$ by the result. So there will be $n$ numbers on the board after all.\n\nYou are given a sequence of length $n$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.\n\nYour problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.\n\nIt is guaranteed that the answer exists.",
    "tutorial": "Let $deg_3(x)$ be the maximum integer $y$ such that $3^y | x$ ($x$ is divisible by $3^y$). Our problem is to rearrange the given array in such a way that (easy to see it if we look at our operations) if it looks like $a_{i_1}, a_{i_2}, \\dots, a_{i_n}$, then for each $k \\in [1..n - 1]$ the next inequality will be satisfied: $deg_3(a_{i_k}) \\ge deg_3(a_{i_k + 1})$. And if $deg_3(a_{i_k}) = deg_3(a_{i_k + 1})$ then numbers must be placed in increasing order (because of our operations). So we can store an array of pairs $ans$, when $ans_i = (x_i, y_i)$, $x_i = -deg_3(a_i)$, $y_i = a_i$. Then if we sort it in lexicographical order we can just print the second elements of the sorted array $ans$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\nint count3(LL x){\n  int ret=0;\n  while(x % 3 == 0){\n    ret++;\n    x /= 3;\n  }\n  return ret;\n}\nint n;\nvector<pair<int,LL>> v;\nint main(){\n  cin>>n;\n  v.resize(n);\n  for(int i=0; i<n; i++){\n    cin>>v[i].second;\n    v[i].first=-count3(v[i].second);\n  }\n  sort(v.begin(), v.end());\n  for(int i=0; i<n; i++)\n    printf(\"%lld%c\", v[i].second, \" \\n\"[i + 1 == n]);\n}",
    "tags": [
      "dfs and similar",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "977",
    "index": "E",
    "title": "Cyclic Components",
    "statement": "You are given an undirected graph consisting of $n$ vertices and $m$ edges. Your task is to find the number of connected components which are cycles.\n\nHere are some definitions of graph theory.\n\nAn undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex $a$ is connected with a vertex $b$, a vertex $b$ is also connected with a vertex $a$). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.\n\nTwo vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$.\n\nA connected component is a cycle if and only if its vertices can be reordered in such a way that:\n\n- the first vertex is connected with the second vertex by an edge,\n- the second vertex is connected with the third vertex by an edge,\n- ...\n- the last vertex is connected with the first vertex by an edge,\n- all the described edges of a cycle are distinct.\n\nA cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.\n\n\\begin{center}\n{\\small There are $6$ connected components, $2$ of them are cycles: $[7, 10, 16]$ and $[5, 11, 9, 15]$.}\n\\end{center}",
    "tutorial": "Let's solve this problem for each connected component of the given graph separately. It is easy to see that the connected component is a cycle iff the degree of each its vertex equals to $2$. So the solution is to count the number of components such that every vertex in the component has degree $2$. The connected components of the graph can be easily found by simple dfs or bfs.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 11;\n\nint n, m;\nint deg[N];\nbool used[N];\nvector<int> comp;\nvector<int> g[N];\n\nvoid dfs(int v) {\n\tused[v] = true;\n\tcomp.push_back(v);\n\t\n\tfor (auto to : g[v])\n\t\tif (!used[to])\n\t\t\tdfs(to);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tscanf(\"%d %d\", &n, &m);\n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t\t++deg[x];\n\t\t++deg[y];\n\t}\n\t\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (!used[i]) {\n\t\t\tcomp.clear();\n\t\t\tdfs(i);\n\t\t\tbool ok = true;\n\t\t\tfor (auto v : comp) ok &= deg[v] == 2;\n\t\t\tif (ok) ++ans;\n\t\t}\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "977",
    "index": "F",
    "title": "Consecutive Subsequence",
    "statement": "You are given an integer array of length $n$.\n\nYou have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to $[x, x + 1, \\dots, x + k - 1]$ for some value $x$ and length $k$.\n\nSubsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array $[5, 3, 1, 2, 4]$ the following arrays are subsequences: $[3]$, $[5, 3, 1, 2, 4]$, $[5, 1, 4]$, but the array $[1, 3]$ is not.",
    "tutorial": "Let $dp[x]$ be the answer for our problem if the last element of our subsequence equals to $x$. Then we have an easy solution: let's store $dp$ as a \"std::map\" (C++) or \"HashMap\" (Java). Initially for each $i \\in [1..n]$ $dp[a_i] = 0$. Then let's iterate over all $a_i$ in order of input and try to update $dp[a_i]$ with a $dp[a_i - 1] + 1$ ($dp[a_i] = max(dp[a_i], dp[a_i - 1] + 1)$). Then the maximum element of $dp$ will be our answer. Let it be $ans$. Then let's find any $a_i$ such that $dp[a_i] = ans$. Let it be $lst$. Then for restoring the answer we need to iterate over all elements of our array in reverse order and if the current element $a_k = lst$ then push $k$ to the array of positions of our subsequence and make $lst := lst - 1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tmap<int, int> dp;\n\t\n\tint ans = 0;\n\tint lst = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x = a[i];\n\t\tdp[x] = dp[x - 1] + 1;\n\t\tif (ans < dp[x]) {\n\t\t\tans = dp[x];\n\t\t\tlst = x;\n\t\t}\n\t}\n\t\n\tvector<int> res;\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tif (a[i] == lst) {\n\t\t\tres.push_back(i);\n\t\t\t--lst;\n\t\t}\n\t}\n\treverse(res.begin(), res.end());\n\t\n\tprintf(\"%d\\n\", ans);\n\tfor (auto it : res)\n\t\tprintf(\"%d \", it + 1);\n\tputs(\"\");\n\t\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "978",
    "index": "A",
    "title": "Remove Duplicates",
    "statement": "Petya has an array $a$ consisting of $n$ integers. He wants to remove duplicate (equal) elements.\n\nPetya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.",
    "tutorial": "We will store integers which we already met in a set $exist$. Let's iterate through the given array from the right to the left. Let the current element is equal to $x$. So, if $x$ does not contain in $exist$ we add $x$ in a vector-answer $ans$ and add $x$ in $exist$. After we considered all elements the answer sequence contains in the vector $ans$ in reversed order. So we should reverse the vector $ans$ and simply print all its elements.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "978",
    "index": "B",
    "title": "File Name",
    "statement": "You can not just take the file and send it. When Polycarp trying to send a file in the social network \"Codehorses\", he encountered an unexpected problem. If the name of the file contains three or more \"x\" (lowercase Latin letters \"x\") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.\n\nDetermine the minimum number of characters to remove from the file name so after that the name does not contain \"xxx\" as a substring. Print 0 if the file name does not initially contain a forbidden substring \"xxx\".\n\nYou can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string \"exxxii\", then the resulting string is \"exxii\".",
    "tutorial": "Let's iterate through the given string from the left to the right. In a variable $cnt$ we will store the number of letters \"x\" which were before the current letter in a row. If the current letter does not equal to \"x\" we should make $cnt = 0$. In the other case, the current letter equals to \"x\". If $cnt < 2$, we should increase $cnt$ by one. In the other case, we should add one to the answer because the current letter should be removed.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "978",
    "index": "C",
    "title": "Letters",
    "statement": "There are $n$ dormitories in Berland State University, they are numbered with integers from $1$ to $n$. Each dormitory consists of rooms, there are $a_i$ rooms in $i$-th dormitory. The rooms in $i$-th dormitory are numbered from $1$ to $a_i$.\n\nA postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $n$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $1$ to $a_1 + a_2 + \\dots + a_n$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.\n\nFor example, in case $n=2$, $a_1=3$ and $a_2=5$ an envelope can have any integer from $1$ to $8$ written on it. If the number $7$ is written on an envelope, it means that the letter should be delivered to the room number $4$ of the second dormitory.\n\nFor each of $m$ letters by the room number among all $n$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.",
    "tutorial": "We should use that the letter queries are given in increasing order of room numbers. We will store in a variable $sum$ the number of rooms in already considered dormitories (this variable should have 64-bit type) and in a variable $idx$ we will store the minimum number of dormitory where the room from the current letter possibly is. Initially, $sum = 0$ and $idx = 1$. We will iterate through the letters. Let the current letter should be delivered to the room $x$. While $sum + a_{idx} < x$, we increase $sum$ by $a_{idx}$ and increase $idx$ by one. So, we got the dormitory number where room $x$ is. It only remains to print two integers: $idx$ (the dormitory number) and $(x - sum)$ (the room number in this dormitory).",
    "tags": [
      "binary search",
      "implementation",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "978",
    "index": "D",
    "title": "Almost Arithmetic Progression",
    "statement": "Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \\dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \\le i < n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 11, 20, 29]$ and $[3, 2, 1, 0]$ are arithmetic progressions, but $[1, 0, 1]$, $[1, 3, 9]$ and $[2, 3, 1]$ are not.\n\nIt follows from the definition that any sequence of length one or two is an arithmetic progression.\n\nPolycarp found some sequence of positive integers $[b_1, b_2, \\dots, b_n]$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $1$, an element can be increased by $1$, an element can be left unchanged.\n\nDetermine a minimum possible number of elements in $b$ which can be changed (by exactly one), so that the sequence $b$ becomes an arithmetic progression, or report that it is impossible.\n\nIt is possible that the resulting sequence contains element equals $0$.",
    "tutorial": "If $n \\le 2$ we can print $0$, because each such sequence is an arithmetic progression. Note, that an arithmetic progression is uniquely determined by the first two terms. So we should brute $d_1$ from $-1$ to $1$ - the change of the first element of the given sequence, and $d_2$ from $-1$ to $1$ - the change of the second element of the given sequence. Then $a_1 = b_1 + d_1$ and $a_2 = b_2 + d_2$. Also we will store $cnt$ - the number of changed elements in the sequence. Initially $cnt = |d_1| + |d_2|$. Now we need to iterate through the sequence from the third element to $n$-th. Let current element in the position $i$. It should be equals to $a_i = a_1 + (i - 1) \\cdot (a_2 - a_1)$. If $|a_i - b_i| > 1$, then such arithmetic progression is unreachable. Else, if $a_i \\ne b_i$ we should increase $cnt$ on one. After we considered all elements we should update the answer with the value of $cnt$, if for all $i$ it was true that $|a_i - b_i| \\le 1$.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "978",
    "index": "E",
    "title": "Bus Video System",
    "statement": "The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.\n\nIf $x$ is the number of passengers in a bus just before the current bus stop and $y$ is the number of passengers in the bus just after current bus stop, the system records the number $y-x$. So the system records show how number of passengers changed.\n\nThe test run was made for single bus and $n$ bus stops. Thus, the system recorded the sequence of integers $a_1, a_2, \\dots, a_n$ (exactly one number for each bus stop), where $a_i$ is the record for the bus stop $i$. The bus stops are numbered from $1$ to $n$ in chronological order.\n\nDetermine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $w$ (that is, at any time in the bus there should be from $0$ to $w$ passengers inclusive).",
    "tutorial": "Firstly we should find the minimum and maximum numbers of passengers, which could be in a bus if initially it was empty. Let $b = 0$. We should iterate through the bus stops. For the $i$-th bus stop, we add $a_i$ to $b$ and update with a value of $b$ the minimum number of passengers $minB$ and the maximum number of passengers $maxB$. If $maxB > w$, it is an invalid case and we should print 0, because the maximum number of passengers should be less or equal to $w$. Let $lf$ is a minimum possible number of passengers in the bus before the first stop and $rg$ - maximum possible. If $minB < 0$ then in the bus initially were at least $-minB$ passengers. Because we should make $lf = -minB$, else, $lf = 0$. If $maxB \\le 0$, then $rg = w$, else, $rg = w - maxB$. After that we should compare $lf$ and $rg$. If $lf > rg$ - print 0. In the other case, print $rg - lf + 1$, because each of those values is correct.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "978",
    "index": "F",
    "title": "Mentors",
    "statement": "In BerSoft $n$ programmers work, the programmer $i$ is characterized by a skill $r_i$.\n\nA programmer $a$ can be a mentor of a programmer $b$ if and only if the skill of the programmer $a$ is strictly greater than the skill of the programmer $b$ $(r_a > r_b)$ and programmers $a$ and $b$ are not in a quarrel.\n\nYou are given the skills of each programmers and a list of $k$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $i$, find the number of programmers, for which the programmer $i$ can be a mentor.",
    "tutorial": "Firstly we should sort all programmers in non-decreasing order of their skills. Also we need to store initially numbers of the programmers (we can user array of pairs - skill and initial number of the programmer). We will iterate through the programmers from the left to the right. The current programmer can be a mentor of all programmers to the left of him after sort and with who he are not in a quarrel. Let the number of programmers to the left is $x$. Subtract from $x$ the number of already considered programmers, who skill equals to the skill of the current programmer (it can be done, for example, with help of $map$). Also lets brute all programmers with who the current programmer in a quarrel (we can initially save for each programmer the vector of programmers with who he in a quarell; by analogy with the stoe of graphs) and if the skill of the current programmer more than the skill of a programmers, with which he in a quarrel, we should decrease $x$ on one, because this programmer is to the left of the current after sort and has been counted in $x$. We should store by a number of the current programmer the value $x$ as answer for him.",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "978",
    "index": "G",
    "title": "Petya's Exams",
    "statement": "Petya studies at university. The current academic year finishes with $n$ special days. Petya needs to pass $m$ exams in those special days. The special days in this problem are numbered from $1$ to $n$.\n\nThere are three values about each exam:\n\n- $s_i$ — the day, when questions for the $i$-th exam will be published,\n- $d_i$ — the day of the $i$-th exam ($s_i < d_i$),\n- $c_i$ — number of days Petya needs to prepare for the $i$-th exam. For the $i$-th exam Petya should prepare in days between $s_i$ and $d_i-1$, inclusive.\n\nThere are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the $i$-th exam in day $j$, then $s_i \\le j < d_i$.\n\nIt is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.\n\nFind the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.",
    "tutorial": "If in the current day there is no exam, we should prepare for an exam, for which questions already given, for which we prepare less than needed and which will be before other remaining exams. For this we will use array $cnt$, where $cnt_i$ equals to the number of days, which we already prepared for exam $i$. Initially, array $cnt$ consists of zeroes. Let's iterate through the days. Suppose exam $x$ is in the current day. If $cnt_x < d_x$, we did not have time to prepare for it and we should print -1. In the other case, in this day we will pass the exam $x$. In the other case, let iterate through all exams and choose exam $x$, for which we need still to prepare (i. e. $cnt_x < d_x$), for which already given the questions, and which will be before other remaining exams. If there is no such exam, we should relax in this day, else, in this day we should prepare for exam $x$. Also, we should increase $cnt_x$ by one.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "979",
    "index": "A",
    "title": "Pizza, Pizza, Pizza!!!",
    "statement": "Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.\n\nToday is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.\n\nShe has ordered a very big round pizza, in order to serve her many friends. Exactly $n$ of Shiro's friends are here. That's why she has to divide the pizza into $n + 1$ slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.\n\nShiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.\n\nAs usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?",
    "tutorial": "If $n = 0$, the answer is obviously $0$. If $n + 1$ is even, we can make $\\textstyle{\\frac{n+1}{2}}$ diametric cuts. Otherwise, the only way is to make $n + 1$ cuts. Time complexity: $O(1)$.",
    "code": "#include <stdio.h>\nusing namespace std;\n\nlong long n;\n\nint main()\n{\n    scanf(\"%I64d\", &n);\n    n++;\n    if (n == 1) printf(\"0\"); else if (n % 2 == 0) printf(\"%I64d\", n / 2); else printf(\"%I64d\", n);\n    return 0;\n}\n",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "979",
    "index": "B",
    "title": "Treasure Hunt",
    "statement": "After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.\n\nThe three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.\n\nA random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $7$ because its subribbon a appears $7$ times, and the ribbon abcdabc has the beauty of $2$ because its subribbon abc appears twice.\n\nThe rules are simple. The game will have $n$ turns. Every turn, each of the cats must change strictly \\textbf{one} color (at one position) in his/her ribbon to an arbitrary color which is \\textbf{different} from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $n$ turns wins the treasure.\n\nCould you find out who is going to be the winner if they all play optimally?",
    "tutorial": "We all knew that the substrings with length $1$ appear at most in the string. So, to make a string as beautiful as possible, we will choose the letter that firstly appears at most in the string and replace all the other letters with the chosen letter. There is some cases. If $n$ is less than or equal to the number of remaining letters, just add $n$ to the beauty. If $n$ is even after replacing all letters with the chosen, we can choose an arbitrary letter, replace it with some other letter, return it back and repeat the work till $n$ reach $0$. Otherwise, we will not replace all the other letters. Instead, we will replace the letters until there is $1$ letter left (now $n$ is even) then replace that one with another letter different from our chosen letter. After that, replace that letter with our chosen letter. Now $n$ is even again, we repeat the work discussed above. In conclusion, let's call our string $s$, our chosen letter $a$ and its number of occurrences in the string $f_{a}$, then our answer is $min(f_{a} + n, |s|)$. Be careful with $n = 1$. Time complexity: $O(\\Sigma\\backslash|S|)$, where $\\textstyle\\sum|S|$ is the total length of the three strings.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint a[256], b[256], c[256], n, ma, mb, mc;\nstring p, q, r;\n\nint main() {\n      cin >> n >> p >> q >> r;\n      for (char x: p) ma = max(ma, ++a[x]);\n      for (char x: q) mb = max(mb, ++b[x]);\n      for (char x: r) mc = max(mc, ++c[x]);\n      if (n == 1 && ma == (int)p.length()) p.pop_back();\n      if (n == 1 && mb == (int)q.length()) q.pop_back();\n      if (n == 1 && mc == (int)r.length()) r.pop_back();\n      ma = min(ma + n, (int)p.length());\n      mb = min(mb + n, (int)q.length());\n      mc = min(mc + n, (int)r.length());\n      if (ma > mb && ma > mc) {\n            puts(\"Kuro\");\n            return 0;\n      }\n      if (mb > ma && mb > mc) {\n            puts(\"Shiro\");\n            return 0;\n      }\n      if (mc > ma && mc > mb) {\n            puts(\"Katie\");\n            return 0;\n      }\n      puts(\"Draw\");\n      return 0;\n}\n",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "979",
    "index": "C",
    "title": "Kuro and Walking Route",
    "statement": "Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ and $b$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $(u, v)$ ($u \\neq v$) and walk from $u$ using the shortest path to $v$ (note that $(u, v)$ is considered to be different from $(v, u)$).\n\nOddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $x$) and Beetopia (denoted with the index $y$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $(u, v)$ if on the path from $u$ to $v$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.\n\nKuro wants to know how many pair of city $(u, v)$ he can take as his route. Since he’s not really bright, he asked you to help him with this problem.",
    "tutorial": "We can consider the city as a graph, in which every town is a vertex and every road connecting two towns is an edge. Since $m$ < $n$, we can deduce that this graph is a tree. Now, instead of finding the number of pairs that Kuro can choose, we can find the number of pairs that Kuro cannot choose. In other words, we must find the number of pairs of vertices $(u, v)$, in which the shortest path from $u$ to $v$ passes through $x$ and then through $y$. But how can we do this? If we take vertex $y$ as the root of the tree, we can see that every pair of vertices that Kuro cannot choose begins from any node within the subtree of node $x$, and finishes at any node but within the subtree of node $z$, which $z$ is a direct child of $y$ lying on the shortest path from $x$ to $y$. In total, the number of pairs of vertices that we are looking for is equal of $n \\cdot (n - 1) - s[x] \\cdot (s[y] - s[z])$, which $s[i]$ denotes the size of the subtree of node $i$. We can implement this using simple DFS. Time complexity: $O(n)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <vector>\nusing namespace std;\n\nconst int MAXN = 3e5;\n\nint n, m, u, v, x, y, sub_size[MAXN + 5];\nbool vis[MAXN + 5], chk_sub[MAXN + 5];\nvector<int> adj[MAXN + 5];\n\nint DFS(int u)\n{\n    vis[u] = true; sub_size[u] = 1;\n    if (u == x)\n        chk_sub[u] = true;\n    else chk_sub[u] = false;\n    for (int v: adj[u])\n        if (!vis[v])\n        {\n            sub_size[u] += DFS(v);\n            chk_sub[u] |= chk_sub[v];\n        }\n    return sub_size[u];\n}\n\nint main()\n{\n    scanf(\"%d%d%d\", &n, &x, &y);\n    m = n - 1;\n    while (m--)\n    {\n        scanf(\"%d%d\", &u, &v);\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    DFS(y);\n\n    long long fin;\n    for (int v: adj[y])\n        if (chk_sub[v])\n        {\n            fin = sub_size[y] - sub_size[v];\n            break;\n        }\n\n    printf(\"%I64d\", 1LL * n * (n - 1) - fin * sub_size[x]);\n    return 0;\n}\n",
    "tags": [
      "dfs and similar",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "979",
    "index": "D",
    "title": "Kuro and GCD and XOR and SUM",
    "statement": "Kuro is currently playing an educational game about numbers. The game focuses on the greatest common divisor (GCD), the XOR value, and the sum of two numbers. Kuro loves the game so much that he solves levels by levels day by day.\n\nSadly, he's going on a vacation for a day, and he isn't able to continue his solving streak on his own. As Katie is a reliable person, Kuro kindly asked her to come to his house on this day to play the game for him.\n\nInitally, there is an empty array $a$. The game consists of $q$ tasks of two types. The first type asks Katie to add a number $u_i$ to $a$. The second type asks Katie to find a number $v$ existing in $a$ such that $k_i \\mid GCD(x_i, v)$, $x_i + v \\leq s_i$, and $x_i \\oplus v$ is maximized, where $\\oplus$ denotes the bitwise XOR operation, $GCD(c, d)$ denotes the greatest common divisor of integers $c$ and $d$, and $y \\mid x$ means $x$ is divisible by $y$, or report -1 if no such numbers are found.\n\nSince you are a programmer, Katie needs you to automatically and accurately perform the tasks in the game to satisfy her dear friend Kuro. Let's help her!",
    "tutorial": "We first look at the condition $k_{i}\\mid G C D(x_{i},v)$. This condition holds iff both $x_{i}$ and $v$ are divisible by $k_{i}$. Therefore, if $k_{i}\\uparrow x_{i}$, we return -1 immediately, else we only consider numbers in $a$ that are divisible by $k_{i}$. Finding the maximum XOR of $x_{i}$ with $v$ in the array $a$ reminds us of a classic problem, where the data structure trie is used to descend from the higher bit positions to the lower bit positions. But since we only consider $v$ such that $k_{i}\\mid v$ and $x_{i} + v  \\le  s_{i}$, we build $10^{5}$ tries, where the $i^{th}$ trie holds information of numbers in $a$ that are divisible by $i$, and we only descend to a branch in the trie if the branch is not empty and the minimum value in the branch is $ \\le  s_{i} - x_{i}$. Adding a number into $a$ is trivial by now: we update every $u^{th}$ trie where $u$ divides the number we need to add into the array. Notice that we only add a number if the number doesn't exist in the array yet. Time complexity: $O(MAXlog(MAX) + qlog(MAX)^{2})$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <vector>\nusing namespace std;\n\nconst int MAX = 1E5 + 5;\n\nstruct SNode\n{\n    int mi;\n    SNode *bit[2];\n\n    SNode()\n    {\n        mi = MAX;\n        bit[0] = bit[1] = nullptr;\n    }\n} *rt[MAX];\nvector<int> di[MAX];\nint q, t, u, k, x, s;\nbool chk[MAX];\n\nvoid init()\n{\n    for (int i = 1; i < MAX; i++)\n    {\n        for (int j = i; j < MAX; j += i)\n            di[j].push_back(i);\n        rt[i] = new SNode();\n    }\n}\n\nvoid add(int k, int u)\n{\n    SNode *cur = rt[k];\n    cur->mi = min(cur->mi, u);\n    for (int i = 18; i >= 0; i--)\n    {\n        if (cur->bit[u >> i & 1] == nullptr)\n            cur->bit[u >> i & 1] = new SNode();\n        cur = cur->bit[u >> i & 1];\n        cur->mi = min(cur->mi, u);\n    }\n}\n\nint que(int x, int k, int s)\n{\n    SNode *cur = rt[k];\n    if (x % k != 0 || cur->mi + x > s)\n        return -1;\n    int ret = 0;\n    for (int i = 18; i >= 0; i--)\n    {\n        int bi = x >> i & 1;\n        if (cur->bit[bi ^ 1] != nullptr && cur->bit[bi ^ 1]->mi + x <= s)\n        {\n            ret += ((bi ^ 1) << i);\n            cur = cur->bit[bi ^ 1];\n        }\n        else\n        {\n            ret += (bi << i);\n            cur = cur->bit[bi];\n        }\n    }\n    return ret;\n}\n\nint main()\n{\n    init();\n    scanf(\"%d\", &q);\n    while (q--)\n    {\n        scanf(\"%d\", &t);\n        if (t == 1)\n        {\n            scanf(\"%d\", &u);\n            if (!chk[u])\n            {\n                chk[u] = true;\n                for (int k : di[u])\n                    add(k, u);\n            }\n        }\n        else\n        {\n            scanf(\"%d%d%d\", &x, &k, &s);\n            printf(\"%d\\n\", que(x, k, s));\n        }\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "data structures",
      "dp",
      "dsu",
      "greedy",
      "math",
      "number theory",
      "strings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "979",
    "index": "E",
    "title": "Kuro and Topological Parity",
    "statement": "Kuro has recently won the \"Most intelligent cat ever\" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games.\n\nKuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot of arrows (you can assume that the number of arrows is infinite). Immediately, Katie came up with the game called Topological Parity.\n\nThe paper is divided into $n$ pieces enumerated from $1$ to $n$. Shiro has painted some pieces with some color. Specifically, the $i$-th piece has color $c_{i}$ where $c_{i} = 0$ defines black color, $c_{i} = 1$ defines white color and $c_{i} = -1$ means that the piece hasn't been colored yet.\n\nThe rules of the game is simple. Players must put some arrows between some pairs of different pieces in such a way that for each arrow, the number in the piece it starts from is less than the number of the piece it ends at. Also, two different pieces can only be connected by \\textbf{at most} one arrow. After that the players must choose the color ($0$ or $1$) for each of the unpainted pieces. The score of a valid way of putting the arrows and coloring pieces is defined as the number of paths of pieces of alternating colors. For example, $[1 \\to 0 \\to 1 \\to 0]$, $[0 \\to 1 \\to 0 \\to 1]$, $[1]$, $[0]$ are valid paths and will be counted. You can only travel from piece $x$ to piece $y$ if and only if there is an arrow from $x$ to $y$.\n\nBut Kuro is not fun yet. He loves parity. Let's call his favorite parity $p$ where $p = 0$ stands for \"even\" and $p = 1$ stands for \"odd\". He wants to put the arrows and choose colors in such a way that the score has the parity of $p$.\n\nIt seems like there will be so many ways which satisfy Kuro. He wants to count the number of them but this could be a very large number. Let's help him with his problem, but print it modulo $10^{9} + 7$.",
    "tutorial": "The problem asks us to find the number of different simple directed acyclic graphs with $1  \\rightarrow  n$ forming its topological order to ensure the parity of the number of alternating paths to be equal to $p$. We will solve this problem using the dynamic programming approach. Let's define even-white as the number of different nodes $u$ colored in white that has an even number of alternating paths that end in $u$. In the same fashion, let's define odd-white as the number of different nodes $u$ colored in white that has an odd number of alternating paths that end in $u$, even-black - the number of different nodes $u$ colored in black that has an even number of alternating paths that end in $u$, and odd-black - the number of different nodes $u$ colored in black that has an odd number of alternating paths that end in $u$. Let's also define $dp[i][ew][ow][eb]$ as the number of different graphs following the requirements that can be built using the first $i$ nodes, with $ew$ even-white nodes, $ow$ odd-white nodes and $eb$ even-black nodes (the number of odd-black nodes $ob = i - ew - ow - eb$). We will figure out how to calculate such value. For the sake of simplicity, let's consider the current node - the ${i}^{th}$ node to be a white node. We can notice a few things: If none of the previous $i - 1$ nodes connects to the current node, the current node becomes an odd-white node (the only alternating path that ends the current node is the node itself). If none of the previous $i - 1$ nodes connects to the current node, the current node becomes an odd-white node (the only alternating path that ends the current node is the node itself). How the previous white nodes connect to the current node does not matter. There are $2^{ow + ew - 1}$ ways to add edges between the previous white nodes and the current node. How the previous white nodes connect to the current node does not matter. There are $2^{ow + ew - 1}$ ways to add edges between the previous white nodes and the current node. How the previous even-black nodes connect to the current node does not matter, as it does not change the state of the current white node (i.e. odd-white to even-white or even-white to odd-white). There are $2^{eb}$ ways to add edges between the previous even-black nodes and the current node. How the previous even-black nodes connect to the current node does not matter, as it does not change the state of the current white node (i.e. odd-white to even-white or even-white to odd-white). There are $2^{eb}$ ways to add edges between the previous even-black nodes and the current node. If there are an odd number of previous odd-black nodes that have edges to the current node, the current node becomes an even-white node. There are $\\sum_{\\begin{array}{l}{\\scriptstyle\\in\\;\\bigcup_{i=1}^{0,b}}\\\\ {\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad}}\\\\ {\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad$ ways to do this. If there are an odd number of previous odd-black nodes that have edges to the current node, the current node becomes an even-white node. There are $\\sum_{\\begin{array}{l}{\\scriptstyle\\in\\;\\bigcup_{i=1}^{0,b}}\\\\ {\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad}}\\\\ {\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad$ ways to do this. If there are an even number of previous odd-black nodes that have edges to the current node, the current node becomes an odd-white node. There are $\\sum_{k=0}^{\\left\\lfloor{\\frac{\\alpha\\beta}{2\\delta}}\\right\\rfloor}\\;\\left({\\frac{\\partial\\beta}{\\delta k}}\\right)$ ways to do this. If there are an even number of previous odd-black nodes that have edges to the current node, the current node becomes an odd-white node. There are $\\sum_{k=0}^{\\left\\lfloor{\\frac{\\alpha\\beta}{2\\delta}}\\right\\rfloor}\\;\\left({\\frac{\\partial\\beta}{\\delta k}}\\right)$ ways to do this. In conclusion, we can figure out that: $\\begin{array}{c}{{d p[i][e w][o w][e b]=2^{o w+e w+e b-1}\\cdot\\left(d p[i-1][e w-1][e w][e b]\\cdot\\sum_{k=0}^{\\lfloor\\frac{g b}{2}\\rfloor}\\left({\\frac{g b}{2k+1}}\\right)+}}\\\\ {{d p[i-1][e w][o w-1][e w][o w-1][e b]\\cdot\\sum_{k=0}^{\\lfloor\\frac{g b}{2k}\\rfloor}\\left({\\frac{g b}{2k}}\\right)}}\\end{array}$ It is worth mentioning that we can use the same analogy to process when the current node is black. In total, we process through $n^{4}$ states, with an $O(n)$ iteration for each stage, so the time complexity is $O(n^{5})$. However, with precomputation of $\\sum_{\\begin{array}{l}{\\scriptstyle\\in\\;\\bigcup_{i=1}^{0,b}}\\\\ {\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad\\quad}\\end{array}\\quad\\quad$ and $\\sum_{k=0}^{\\left\\lfloor{\\frac{\\left\\lfloor{\\frac{\\omega}{k}}\\right\\rfloor}{k}}\\setminus\\left({\\frac{\\partial}{\\partial k}}\\right)}$ for every value of $ob$, we can optimize the time complexity to $O(n^{4})$. Time complexity: $O(n^{4})$.",
    "code": "#include <iostream>\nusing namespace std;\n\nconst int N = 55, MOD = 1E9 + 7;\n\nint n, p, c[N];\nlong long ans = 0, pw[N], fct[N], inv[N], od[N], ev[N], f[N][N][N][N];\n\nlong long power(int u, int p)\n{\n    if (p == 0)\n        return 1;\n    long long ret = power(u, p >> 1);\n    (ret *= ret) %= MOD;\n    if (p & 1)\n        (ret *= u) %= MOD;\n    return ret;\n}\n\nlong long C(int n, int k)\n{\n    return fct[n] * inv[k] % MOD * inv[n - k] % MOD;\n}\n\nvoid init()\n{\n    f[0][0][0][0] = 1;\n    pw[0] = 1;\n    fct[0] = 1;\n    for (int i = 1; i < N; i++)\n    {\n        pw[i] = pw[i - 1] * 2 % MOD;\n        fct[i] = fct[i - 1] * i % MOD;\n    }\n    inv[N - 1] = power(fct[N - 1], MOD - 2);\n    for (int i = N - 2; i >= 0; i--)\n        inv[i] = inv[i + 1] * (i + 1) % MOD;\n    for (int i = 0; i < N; i++)\n    {\n        for (int j = 0; j <= i; j += 2)\n            (ev[i] += C(i, j)) %= MOD;\n        for (int j = 1; j <= i; j += 2)\n            (od[i] += C(i, j)) %= MOD;\n    }\n}\n\nvoid find_ans(int ob, int eb, int ow, int ew, int col, long long &ret)\n{\n    // current node is even-white\n    if (col != 0 && ew != 0)\n        (ret += f[ob][eb][ow][ew - 1] * pw[ow + ew - 1 + eb] % MOD * od[ob] % MOD) %= MOD;\n\n    // current node is odd-white\n    if (col != 0 && ow != 0)\n        (ret += f[ob][eb][ow - 1][ew] * pw[ow - 1 + ew + eb] % MOD * ev[ob] % MOD) %= MOD;\n\n    // current node is even-black\n    if (col != 1 && eb != 0)\n        (ret += f[ob][eb - 1][ow][ew] * pw[ob + eb - 1 + ew] % MOD * od[ow] % MOD) %= MOD;\n\n    // current node is odd-black\n    if (col != 1 && ob != 0)\n        (ret += f[ob - 1][eb][ow][ew] * pw[ob - 1 + eb + ew] % MOD * ev[ow] % MOD) %= MOD;\n}\n\nint main()\n{\n    init();\n    scanf(\"%d%d\", &n, &p);\n    for (int i = 1; i <= n; i++)\n        scanf(\"%d\", c + i);\n    for (int i = 1; i <= n; i++)\n        for (int ob = 0; ob <= i; ob++)\n            for (int eb = 0; ob + eb <= i; eb++)\n                for (int ow = 0; ob + eb + ow <= i; ow++)\n                {\n                    int ew = i - ob - eb - ow;\n                    find_ans(ob, eb, ow, ew, c[i], f[ob][eb][ow][ew]);\n                    if (i == n && ((ob + ow) & 1) == p)\n                        (ans += f[ob][eb][ow][ew]) %= MOD;\n                }\n    printf(\"%lld\", ans);\n    return 0;\n}\n",
    "tags": [
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "980",
    "index": "A",
    "title": "Links and Pearls",
    "statement": "A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one.\n\nYou can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts.\n\nCan you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them.\n\nNote that the final necklace should remain as one circular part of the same length as the initial necklace.",
    "tutorial": "The problem can be viewed as the following: You have a cyclic array with the characters '-' and 'o', you want to rearrange the elements of the array such that the number of '-' characters after every 'o' character is the same. So we want to distribute the '-' characters over the 'o' characters so that all the 'o' characters have the same number of '-' characters after them. If we have $a$ of 'o' and $b$ of '-', then that can be done if and only if $b \\bmod a = 0$. When $a = 0$, the answer is YES since the condition still holds.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "980",
    "index": "B",
    "title": "Marlin",
    "statement": "The city of Fishtopia can be imagined as a grid of $4$ rows and an \\textbf{odd} number of columns. It has two main villages; the first is located at the top-left cell $(1,1)$, people who stay there love fishing at the Tuna pond at the bottom-right cell $(4, n)$. The second village is located at $(4, 1)$ and its people love the Salmon pond at $(1, n)$.\n\nThe mayor of Fishtopia wants to place $k$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.\n\nA person can move from one cell to another if those cells are not occupied by hotels and share a side.\n\nCan you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond?",
    "tutorial": "Instead of looking at the second path from $(4, 1)$ to $(1, n)$, consider it as from $(1, n)$ to $(4, 1)$. Now when $k$ is even, we can do the following: start from (2,2), put a hotel in that cell and another hotel in (2,n-1), then a hotel in (2,3) and one in (2, n-2), and so on until either the second row is full (expect for the middle column) or the number of hotels is $k$, if you still need more hotels then just do the same for the third row. This works because going from $(1, 1)$ to $(4, n)$ is identical to going from $(1, n)$ to $(4, 1)$ since the constructed grid is symmetric. Now if $k = 2*(n-2)$ then just fill the the middle column (second and third row), and if $k$ is odd then just add a hotel in middle column.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "980",
    "index": "C",
    "title": "Posterized",
    "statement": "Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.\n\nTheir algorithm will be tested on an array of integers, where the $i$-th integer represents the color of the $i$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).\n\nTo implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $k$, and each color should belong to exactly one group.\n\nFinally, the students will replace the color of each pixel in the array with that color’s assigned group key.\n\nTo better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $k$ to the right.\n\nTo make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.",
    "tutorial": "First, it's obvious that for each group we should choose the color with minimum value as the group's key. Now since we want to find the lexicographically smallest array, we iterate from the leftmost number in the array and minimize it as much as possible without considering the numbers to its right. There are many ways to implement this, one of them is the following: Iterate from left to right, for each number $x$, if it is already assigned to a group then ignore it. Otherwise, check the colors less than $x$ in decreasing order until you find a color $y$ that is assigned. If we can extend the group of $y$ to include $x$ and the size won't be exceeding $k$, then we do extend it and assign all the colors between $y+1$ and $x$ to the key of $y$'s group. If the size will exceed $k$ or such $y$ was not found (set it to $-1$ in this case), we create a new group with key equals to $max(y+1,x-k+1)$ and assign all colors in the range to it. The complexity of this solution is $O(n + c)$, where $c$ is the size of the color range.",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "980",
    "index": "D",
    "title": "Perfect Groups",
    "statement": "SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square.\n\nEach integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array.\n\nSaMer wishes to create more cases from the test case he already has. His test case has an array $A$ of $n$ integers, and he needs to find the number of contiguous subarrays of $A$ that have an answer to the problem equal to $k$ for each integer $k$ between $1$ and $n$ (inclusive).",
    "tutorial": "First let us examine perfect squares; a perfect square is a number $x$ that can be written as the product of an integer and itself $y*y$. This means that for each prime factor of the number $x$, the frequency of that factor must be even so it can be distributed evenly between each of the two $y$'s. This leads to the idea that for every two numbers $a$ and $b$ in a group, for a prime factor $p_{i}$, either both $a$ and $b$ have an even frequency of $p_{i}$, or they both have an odd frequency of it. So using that observation, for each number $x$ in the array we can discard all pairs of equal prime factors (keeping one copy of each factor with an odd frequency). For example, number $40$ has factors ${2, 2, 2, 5}$, so we can just ignore the first pair of $2's$ because they're redundant and transform it into ${2, 5}$, which is the number $10$. Now after replacing each number with the product of its odd factors, we can just count the number of distinct elements in each subarray as each element can be only grouped with its copies. This can be done by checking all possible subarrays and keeping a frequency array to count the number of distinct elements in it. - Elements need to be mapped to non-negative integers between $1$ and $n$ so we don't use a set to count them. - Need to be careful in case there's a zero in the subarray. Zeros can join any group, so unless the subarray contains only zeros, we can ignore them. Solution Complexity: $O(n\\times sqrt(max a_i) + n^{2})$",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "980",
    "index": "E",
    "title": "The Number Games",
    "statement": "The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.\n\nThe nation has $n$ districts numbered from $1$ to $n$, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district $i$ is equal to $2^i$.\n\nThis year, the president decided to reduce the costs. He wants to remove $k$ contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts.\n\nThe president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants.\n\nWhich contestants should the president remove?",
    "tutorial": "As the final set of remaining districts need to be reachable from each other, this means that the resulting tree is a sub-graph of the original one. Now, looking at the number of fans in each district, district $i$ has $2^{i}$ fans. This means that if we had a choice of including a district $i$ in our solution and discarding all the districts with indices less than $i$ then it'd be better than discarding district $i$ and including all the others, as $2^{i} = 2^{i-1} + 2^{i-2} + ... + 2^{0} + 1$. This leads us to the following greedy solution: Let's try to find which districts to keep instead of which to discard, let's first root the tree at district $n$, as we can always keep it, and go through the remaining districts by the order of decreasing index. Now at each step, if we can include district $i$ into our solution by taking it and all of the nodes on the path connecting it to our current sub-graph, then we should surely do so, otherwise we can just ignore it and move on to the next district. This can be implemented by building a parent sparse-table and using Binary Lifting at each district $i$ to find the first of its ancestors that has been already included in our sub-graph. The distance to this ancestor represents the number of districts that need to be included in the games to have district $i$ included. So if we can still include that many districts in our sub-graph then we will traverse through the path and mark them as included. Solution Complexity: $O(nlogn)$",
    "tags": [
      "data structures",
      "greedy",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "980",
    "index": "F",
    "title": "Cactus to Tree",
    "statement": "You are given a special connected undirected graph where each vertex belongs to at most one simple cycle.\n\nYour task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles).\n\nFor each node, independently, output the maximum distance between it and a leaf in the resulting tree, assuming you were to remove the edges in a way that minimizes this distance.",
    "tutorial": "The following solution is implemented in 136 lines, but most of it is a simple BFS and two DFS functions for finding bridges and marking cycles, the main part of the solution is implemented in 38 lines. Please check the code after (or while?) reading if it is not clear. Note that if we run a BFS from a node $u$, the BFS spanning tree will represent the edges that we should keep to minimize the answer for node $u$. So we actually need to find the maximum length out of all shortest paths that starts at $u$ and end at every other node. We will first focus on finding the answer for each node on one cycle: For each node $u$ on the cycle, we can compute $L[u]$, the length of the longest shortest path that starts at node $u$ and uses only the edges that do not belong to the cycle. This can be done using BFS in $O(n+m)$ for one cycle. Using the computed values, we can find the final answer for all nodes on the cycle in $O(klogk)$, or $O(k)$, where $k$ is the number of nodes on the cycle. For a node $u$, we need to find a node $v$ on the cycle such that $L[v] + distance(u, v)$ is maximized, where $distance(u,v)$ is the length of the shortest path between $u$ and $v$ on the cycle. Therefore, the answer with regards to each node $u$ will be the maximum between $L[u]$ and $L[v] + distance(u, v)$, for each node $v$ in the same cycle as $u$. We can do this using a heap and prefix sums idea as follows: loop for $2k$ iterations over the cycle nodes, in the $i^{th}$ iteration ($0 \\leq i < 2k$) add the value $L[cycle[i \\bmod k]]+2k-i$ to the heap with the time it was added in ($time = 2k-i$, time is decreasing), that is, add the pair ($L[cycle[i \\bmod k]]+2k-i, 2k-i$). Now at a given iteration $j$, pop from the heap all top values added at time greater than $2k-j+k/2$, as $distance(u,v)$ can't exceed $k/2$. Now assuming the top pair in the queue is ($x, y$), then $x-(2k-j)$ is a possible answer for this node. We need to do this again in counter-clockwise. Since we will visit each node four times, keep the maximum distance $Z_i$ found for each node $i$ in the cycle and the final answer for that node will be $max(L_i, Z_i)$. Now if we have the answer for one cycle, when we move using an edge ($a, b$) to another cycle (or node), we only need to know one value to be able to solve the next cycle, that value is the maximum between $Z_a$ and the length of the longest path that goes through bridges other than ($a, b$). This value is increased by $1$ when passed since we will move through the edge ($a, b$). Implementation: Marking the bridges will help in deciding if an edge will take us outside a cycle or not so we can compute $L_i$. Also removing the bridges will make it easy to find which nodes form each cycle. We can find any BFS spanning tree and use it to find the length of the longest path that starts at a node and uses a bridge first, note that this distance goes only down as the tree is rooted at the starting node, but the values $L_u$ for every $u$ in the first cycle will be correct so we can start with them.",
    "code": "\"#include <stdio.h>\\n#include <vector>\\n#include <queue>\\n#include <memory.h>\\n#include <algorithm>\\nusing namespace std;\\ntypedef long long ll;\\nconst int N = 500000;\\nint n, m;\\nint L[N], Z[N], maxLen[N];\\nvector<vector<pair<int, int> > > g;\\nbool isBridge[2 * N];\\nint low[N], idx[N], dfs;\\nbool vis[N];\\nint parent[N];\\nvoid markBridges(int u, int p) {\\n\\tlow[u] = idx[u] = ++dfs;\\n\\tfor (int i = 0; i < g[u].size(); ++i) {\\n\\t\\tint v = g[u][i].first;\\n\\t\\tif (idx[v] == 0) {\\n\\t\\t\\tmarkBridges(v, u);\\n\\t\\t\\tlow[u] = min(low[u], low[v]);\\n\\t\\t\\tif (low[v] > idx[u])\\n\\t\\t\\t\\tisBridge[g[u][i].second] = true;\\n\\t\\t}\\n\\t\\telse if (v != p)\\n\\t\\t\\tlow[u] = min(low[u], idx[v]);\\n\\t}\\n}\\nvoid findASpanningTreeAndInitializeL(int startingNode) {\\n\\tqueue<int> q;\\n\\tvector<int> nodesByDepth;\\n\\tq.push(startingNode);\\n\\tmemset(vis, 0, sizeof(vis));\\n\\tvis[startingNode] = true;\\n\\tparent[startingNode] = -1;\\n\\twhile (!q.empty()) {\\n\\t\\tint u = q.front();\\n\\t\\tq.pop();\\n\\t\\tnodesByDepth.push_back(u);\\n\\t\\tfor (auto e : g[u]) {\\n\\t\\t\\tint v = e.first;\\n\\t\\t\\tif (vis[v])\\n\\t\\t\\t\\tcontinue;\\n\\t\\t\\tvis[v] = true;\\n\\t\\t\\tparent[v] = u;\\n\\t\\t\\tq.push(v);\\n\\t\\t}\\n\\t}\\n\\tfor (int i = n - 1; i >= 0; --i) {\\n\\t\\tint u = nodesByDepth[i];\\n\\t\\tfor (auto e : g[u]) {\\n\\t\\t\\tint v = e.first;\\n\\t\\t\\tif (parent[v] == u) {\\n\\t\\t\\t\\tmaxLen[u] = max(maxLen[u], 1 + maxLen[v]);\\n\\t\\t\\t\\tif (isBridge[e.second])\\n\\t\\t\\t\\t\\tL[u] = max(L[u], 1 + maxLen[v]);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\\nvector<vector<int> > cycles; // actually components after removing bridges, not cycles (as there can be a single node).\\nint cycleIdx[N];\\nvoid findCycles(int u) {\\n\\tvis[u] = true;\\n\\tcycles.back().push_back(u);\\n\\tcycleIdx[u] = cycles.size() - 1;\\n\\tfor (auto e : g[u])\\n\\t\\tif (!isBridge[e.second] && !vis[e.first])\\n\\t\\t\\tfindCycles(e.first);\\n}\\nvoid solveCycles(int u, int p, int upValue) {\\n\\tL[u] = max(L[u], upValue);\\n\\tvector<int> &cycle = cycles[cycleIdx[u]];\\n\\tint k = cycle.size();\\n\\tfor (int it = 0; it < 2; ++it) { // two iterations, clockwise and counter clockwise\\n\\t\\tpriority_queue<pair<int, int> > q;\\n\\t\\tfor (int i = 0; i < 2 * k; ++i) {\\n\\t\\t\\tint d = 2 * k - i;\\n\\t\\t\\twhile (!q.empty() && q.top().second - d > k / 2)\\n\\t\\t\\t\\tq.pop();\\n\\t\\t\\tif (!q.empty())\\n\\t\\t\\t\\tZ[cycle[i%k]] = max(Z[cycle[i%k]], q.top().first - d);\\n\\t\\t\\tq.push({ L[cycle[i%k]] + d,d });\\n\\t\\t}\\n\\t\\treverse(cycle.begin(), cycle.end());\\n\\t}\\n\\tfor (auto u : cycle) {\\n\\t\\tint firstMax = 0, secondMax = 0;\\n\\t\\tfor (auto e : g[u])\\n\\t\\t\\tif (e.first != p && isBridge[e.second]) {\\n\\t\\t\\t\\tint v = e.first;\\n\\t\\t\\t\\tif (secondMax < 1 + maxLen[v]) {\\n\\t\\t\\t\\t\\tsecondMax = 1 + maxLen[v];\\n\\t\\t\\t\\t\\tif (firstMax < secondMax)\\n\\t\\t\\t\\t\\t\\tswap(firstMax, secondMax);\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\tfor (auto e : g[u])\\n\\t\\t\\tif (e.first != p && isBridge[e.second]) {\\n\\t\\t\\t\\tint v = e.first;\\n\\t\\t\\t\\tint passValue = max(upValue, Z[u]);\\n\\t\\t\\t\\tif (firstMax == 1 + maxLen[v])\\n\\t\\t\\t\\t\\tpassValue = max(passValue, secondMax);\\n\\t\\t\\t\\telse\\n\\t\\t\\t\\t\\tpassValue = max(passValue, firstMax);\\n\\t\\t\\t\\tsolveCycles(v, u, passValue + 1);\\n\\t\\t\\t}\\n\\t}\\n}\\nint main()\\n{\\n\\tscanf(\\\"%d%d\\\", &n, &m);\\n\\tg.resize(n);\\n\\tfor (int i = 0, u, v; i < m; ++i) {\\n\\t\\tscanf(\\\"%d%d\\\", &u, &v);\\n\\t\\t--u; --v;\\n\\t\\tg[u].push_back({ v,i });\\n\\t\\tg[v].push_back({ u,i });\\n\\t}\\n\\tmarkBridges(0, -1);\\n\\tfor (int i = 0; i < n; ++i)\\n\\t\\tif (!vis[i]) {\\n\\t\\t\\tcycles.push_back(vector<int>());\\n\\t\\t\\tfindCycles(i);\\n\\t\\t}\\n\\tfindASpanningTreeAndInitializeL(0);\\n\\tsolveCycles(0, -1, 0);\\n\\tfor (int i = 0; i < n; ++i) {\\n\\t\\tif (i > 0)\\n\\t\\t\\tprintf(\\\" \\\");\\n\\t\\tprintf(\\\"%d\\\", max(L[i], Z[i]));\\n\\t}\\n\\tprintf(\\\"\\\\n\\\");\\n\\treturn 0;\\n}\"",
    "tags": [
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "981",
    "index": "A",
    "title": "Antipalindrome",
    "statement": "A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings \"kek\", \"abacaba\", \"r\" and \"papicipap\" are palindromes, while the strings \"abb\" and \"iq\" are not.\n\nA substring $s[l \\ldots r]$ ($1 \\leq l \\leq r \\leq |s|$) of a string $s = s_{1}s_{2} \\ldots s_{|s|}$ is the string $s_{l}s_{l + 1} \\ldots s_{r}$.\n\nAnna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $s$ is changed into its longest substring that is not a palindrome. If all the substrings of $s$ are palindromes, she skips the word at all.\n\nSome time ago Ann read the word $s$. What is the word she changed it into?",
    "tutorial": "You can just check all substrings on palindromity in $O(n^3)$. Also you can note that if all characters in the string are same, then answer is $0$, else, if string is not a palindrome, answer is $n$, else you can delete last char and get answer $n-1$, so you can solve the task in $O(n)$.",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "981",
    "index": "B",
    "title": "Businessmen Problems",
    "statement": "Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.\n\nIn order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies.\n\nAll elements are enumerated with integers. The ChemForces company has discovered $n$ distinct chemical elements with indices $a_1, a_2, \\ldots, a_n$, and will get an income of $x_i$ Berland rubles if the $i$-th element from this list is in the set of this company.\n\nThe TopChemist company discovered $m$ distinct chemical elements with indices $b_1, b_2, \\ldots, b_m$, and it will get an income of $y_j$ Berland rubles for including the $j$-th element from this list to its set.\n\nIn other words, the first company can present any subset of elements from $\\{a_1, a_2, \\ldots, a_n\\}$ (possibly empty subset), the second company can present any subset of elements from $\\{b_1, b_2, \\ldots, b_m\\}$ (possibly empty subset). There shouldn't be equal elements in the subsets.\n\nHelp the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.",
    "tutorial": "With $map$ data structure for each chemical element that presents in input find maximal cost that you can get, and then just sum up these costs",
    "tags": [
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "981",
    "index": "C",
    "title": "Useful Decomposition",
    "statement": "Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!\n\nHe created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!\n\nThe decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.\n\nHelp Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.",
    "tutorial": "Let's prove that all paths in this decomposition have one intersection vertex. 1) Any pair of paths have exactly one intersecting vertex, because else there are common edge (so it is not a decomposition) or cycle (so graph is not a tree). 2) Let's assume that there are several intersection points. Let us have three paths $A$, $B$, $C$, and intersecting points are $P(AB), P(AC), P(BC)$. Then these intersecting points are pairwise different, but $P(AB) \\to P(AC) \\to P(BC)$ - cycle in the tree, so we get a contradiction. So we proved that for each triple of paths all intersection points are the same, $\\to$ all paths in this decomposition have one intersecting vertex. So we proved that we can decompose the tree only if the tree looks like a vertex and several paths incoming from it. So you can choose the root in this tree - vertex with degree bigger than two (if there are no such vertex then the tree is bamboo and you can check that case separately or take any vertex as root). If there are several such vertices, when there is no decomposition. And then you can connect root with all leaves.",
    "code": "\"#include <cmath>\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n#include <unordered_map>\\n#include <unordered_set>\\n#include <iomanip>\\n#include <bitset>\\n#include <sstream>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\nmt19937 rnd(228);\\n\\nconst int N = 1e5 + 1;\\n\\nvector <int> g[N];\\n\\nvector <int> leafs;\\n\\nvoid dfs(int v, int pr)\\n{\\n    int deg = 0;\\n    for (int to : g[v])\\n    {\\n        if (to != pr)\\n        {\\n            deg++;\\n            dfs(to, v);\\n        }\\n    }\\n    if (deg == 0)\\n    {\\n        leafs.push_back(v);\\n    }\\n}\\n\\nint main()\\n{\\n#ifdef ONPC\\n    freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n    ios::sync_with_stdio(0);\\n    cin.tie(0);\\n    int n;\\n    cin >> n;\\n    for (int i = 1; i < n; i++)\\n    {\\n        int a, b;\\n        cin >> a >> b;\\n        a--, b--;\\n        g[a].push_back(b);\\n        g[b].push_back(a);\\n    }\\n    int root = 0;\\n    int cnt = 0;\\n    for (int i = 0; i < n; i++)\\n    {\\n        if ((int) g[i].size() > 2)\\n        {\\n            cnt++;\\n            root = i;\\n        }\\n    }\\n    if (cnt > 1)\\n    {\\n        cout << \\\"No\\\\n\\\";\\n    }\\n    else\\n    {\\n        cout << \\\"Yes\\\\n\\\";\\n        dfs(root, -1);\\n        cout << (int) leafs.size() << '\\\\n';\\n        for (int i = 0; i < (int) leafs.size(); i++)\\n        {\\n            cout << root + 1 << ' ' << leafs[i] + 1 << '\\\\n';\\n        }\\n    }\\n}\"",
    "tags": [
      "implementation",
      "trees"
    ],
    "rating": 1400
  },
  {
    "contest_id": "981",
    "index": "D",
    "title": "Bookshelves",
    "statement": "Mr Keks is a typical white-collar in Byteland.\n\nHe has a bookshelf in his office with some books on it, each book has an integer positive price.\n\nMr Keks defines the value of a shelf as the sum of books prices on it.\n\nMiraculously, Mr Keks was promoted and now he is moving into a new office.\n\nHe learned that in the new office he will have not a single bookshelf, but exactly $k$ bookshelves. He decided that the beauty of the $k$ shelves is the bitwise AND of the values of all the shelves.\n\nHe also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $k$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.",
    "tutorial": "Let's build answer from significant bit to least significant bit. We want to check, is there some partition in $k$ segments, such that all segment's sums have significant bit? We can check it with $dp_{n, k}$ - is there some partition of first $n$ elements on $k$ segments such that all segment's sums have significant bit? And then we will do the same with all other bits, we will try set $1$ in the bit, and then we want to check for fixed prefix of bits, is there some partition in $k$ segments, such that all prefixes with same length of all segment's sums are supermasks of current check mask (we will check that with the same dp, $dp_{n, k}$ - is there some partition of first $n$ elements on $k$ segments such that all prefixes of same length of all segment's sums are supermasks of current check mask?)",
    "code": "\"#include <cstdio>\\n#include <cstring>\\n\\ntypedef long long int64;\\nstatic const int MAXN = 52;\\nstatic const int LOGA = 56;\\n\\nstatic int k, n;\\nstatic int64 a[MAXN], s[MAXN];\\n\\nstatic bool feas[MAXN][MAXN];\\n\\ninline bool dp_check(int64 targ, int64 mask)\\n{\\n    memset(feas, false, sizeof feas);\\n    feas[0][0] = true;\\n    for (int i = 1; i <= n; ++i) {\\n        for (int j = 0; j < i; ++j)\\n            if (((s[i] - s[j]) & mask & targ) == targ) {\\n                for (int k = 0; k < MAXN - 1; ++k)\\n                    if (feas[j][k]) feas[i][k + 1] = true;\\n            }\\n    }\\n    return feas[n][k];\\n}\\n\\nint main()\\n{\\n    scanf(\\\"%d%d\\\", &n, &k);\\n    for (int i = 0; i < n; ++i) scanf(\\\"%lld\\\", &a[i]);\\n    s[0] = 0;\\n    for (int i = 0; i < n; ++i) s[i + 1] = s[i] + a[i];\\n\\n    int64 ans = 0;\\n    for (int i = LOGA - 1; i >= 0; --i) {\\n        if (dp_check(ans | (1LL << i), ~((1LL << i) - 1))) ans |= (1LL << i);\\n    }\\n    printf(\\\"%lld\\\\n\\\", ans);\\n\\n    return 0;\\n}\"",
    "tags": [
      "bitmasks",
      "dp",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "981",
    "index": "E",
    "title": "Addition on Segments",
    "statement": "Grisha come to a contest and faced the following problem.\n\nYou are given an array of size $n$, initially consisting of zeros. The elements of the array are enumerated from $1$ to $n$. You perform $q$ operations on the array. The $i$-th operation is described with three integers $l_i$, $r_i$ and $x_i$ ($1 \\leq l_i \\leq r_i \\leq n$, $1 \\leq x_i \\leq n$) and means that you should add $x_i$ to each of the elements with indices $l_i, l_i + 1, \\ldots, r_i$. After all operations you should find the maximum in the array.\n\nGrisha is clever, so he solved the problem quickly.\n\nHowever something went wrong inside his head and now he thinks of the following question: \"consider we applied some subset of the operations to the array. What are the possible values of the maximum in the array?\"\n\nHelp Grisha, find all integers $y$ between $1$ and $n$ such that if you apply some subset (possibly empty) of the operations, then the maximum in the array becomes equal to $y$.",
    "tutorial": "Suppose we know the index where the maximum is. Let's examine which requests we decided to take. Surely there is no need to take requests which doesn't contain the index of maximum. Because if you delete them, they will not impact maximum and nothing will change. This way we can see, that any possible answer is a sum of x's of some set of intersecting segments. We can go with a sweepline. Then when some request segment opens add new item to the knapsack. And delete one when it closes. The answer it the set of all possible sums we can obtain at some points. So we need to implement the following operations: 1) Add some number to the multiset. 2) Delete some number from the multiset. 3) Find all sums we can can obtain using the numbers from multiset. Let's store the following dp: $dp_x$ is the number of ways to get weight $x$. When we add new element $a$ we should go from the end of dp and recalculate it as $dp_i = dp_i + dp_{i-a}$, And when removing, doing the reverse transition: going from the beginning and relaxing as $dp_i = dp_i - dp_{i - a}$. And to find all achievable sums we should just print all $i$, such that $dp_i \\neq 0$. However the exact values of $dp$ can be really large, so we can resort to a trick: let's cound all the dp values by some prime modulo, to avoid being hacked you should probably randomize it.",
    "code": "\"#include <cmath>\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n#include <unordered_map>\\n#include <iomanip>\\n#include <bitset>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\nmt19937 rnd(time(0));\\n\\nconst int N = 1e4 + 7;\\nint MOD;\\n\\nbool prime(int x)\\n{\\n    for (int i = 2; i * i <= x; i++)\\n    {\\n        if (x % i == 0)\\n        {\\n            return false;\\n        }\\n    }\\n    return (x != 1);\\n}\\n\\nint dp[N];\\nvector <pair <int, int> > e[N];\\n\\nvoid add(int x)\\n{\\n    for (int i = N - 1 - x; i >= 0; i--)\\n    {\\n        dp[i + x] += dp[i];\\n        if (dp[i + x] >= MOD) dp[i + x] -= MOD;\\n    }\\n}\\n\\nvoid del(int x)\\n{\\n    for (int i = x; i < N; i++)\\n    {\\n        dp[i] -= dp[i - x];\\n        if (dp[i] < 0) dp[i] += MOD;\\n    }\\n}\\n\\nint main()\\n{\\n#ifdef ONPC\\n    freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n    ios::sync_with_stdio(0);\\n    cin.tie(0);\\n    MOD = 5e8 + rnd() % (int) 5e8;\\n    while (!prime(MOD)) MOD--;\\n    int n, q;\\n    cin >> n >> q;\\n    dp[0] = 1;\\n    vector <bool> ans(n + 1);\\n    for (int i = 0; i < q; i++)\\n    {\\n        int l, r, x;\\n        cin >> l >> r >> x;\\n        l--, r--;\\n        e[l].push_back({x, 1});\\n        e[r + 1].push_back({x, -1});\\n    }\\n    for (int i = 0; i < n; i++)\\n    {\\n        for (auto c : e[i])\\n        {\\n            if (c.second == 1)\\n            {\\n                add(c.first);\\n            }\\n            else\\n            {\\n                del(c.first);\\n            }\\n        }\\n        for (int j = 1; j <= n; j++)\\n        {\\n            if (dp[j])\\n            {\\n                ans[j] = true;\\n            }\\n        }\\n    }\\n    vector <int> res;\\n    for (int i = 1; i <= n; i++)\\n    {\\n        if (ans[i])\\n        {\\n            res.push_back(i);\\n        }\\n    }\\n    cout << res.size() << '\\\\n';\\n    for (int x : res)\\n    {\\n        cout << x << ' ';\\n    }\\n    cout << '\\\\n';\\n}\"",
    "tags": [
      "bitmasks",
      "data structures",
      "divide and conquer",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "981",
    "index": "F",
    "title": "Round Marriage",
    "statement": "It's marriage season in Ringland!\n\nRingland has a form of a circle's boundary of length $L$. There are $n$ bridegrooms and $n$ brides, and bridegrooms decided to marry brides.\n\nOf course, each bridegroom should choose exactly one bride, and each bride should be chosen by exactly one bridegroom.\n\nAll objects in Ringland are located on the boundary of the circle, including the capital, bridegrooms' castles and brides' palaces. The castle of the $i$-th bridegroom is located at the distance $a_i$ from the capital in clockwise direction, and the palace of the $i$-th bride is located at the distance $b_i$ from the capital in clockwise direction.\n\nLet's define the inconvenience of a marriage the maximum distance that some bride should walk along the circle from her palace to her bridegroom's castle in the shortest direction (in clockwise or counter-clockwise direction).\n\nHelp the bridegrooms of Ringland to choose brides in such a way that the inconvenience of the marriage is the smallest possible.",
    "tutorial": "Key idea is that there there is a cut which is not crossed by anyoner (in other words, it is not profitable if brides will travel whole circle) So we can solve the problem in $O(n \\cdot L)$ - fix the cut, and match $i$-th bridegrom (in increasing order) with $i$-th bride (if we will order brides in the traversal order starting from border), and relax answer with current inconvenience. Later we can note, that cuts not at brides are useless, so we can just choose cut from brides coordinates and get solution in $O(n^2)$. Later we can note, that we are just searching for optimal cyclical shift of brides coordinates (of course if we will sort everything in increasing order). Alright, then we want to find such $x < n$, so that $max(min(|a_i - b_{i + x}|, L - |a_i - b_{i + x}|))$ is minimal. (Where $i+x$ is by modulo $n$, of course). Let's make binary search on $ans$, then we want to check is there such $x$, so that $min(|a_i - b_{i + x}|, L - |a_i - b_{i + x}|) \\leq ans$? If we will fix $i$, then set of good $x$ is just cyclical segment (you can find it with binary search or two pointers), and then we want to check that intersection of these segments is not empty. How to check it? We can split cyclic segment into two non-cyclic, and then just add on the segment offline, and then you need to check that there are some point with value $n$. So we can solve the problem in $O(n \\cdot log L)$.",
    "code": "\"#include <cmath>\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n#include <unordered_map>\\n#include <iomanip>\\n#include <bitset>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\nmt19937 rnd(228);\\n\\nvoid add(int my_l, int my_r, const vector <int> &b, vector <int> &cnt, int i)\\n{\\n    int n = (int) b.size();\\n    int get_l = lower_bound(b.begin(), b.end(), my_l) - b.begin();\\n    int get_r = upper_bound(b.begin(), b.end(), my_r) - b.begin() - 1;\\n    if (get_l <= get_r)\\n    {\\n        int add_l = get_l - i + n;\\n        int add_r = get_r - i + n;\\n        if (add_l >= n) add_l -= n;\\n        if (add_r >= n) add_r -= n;\\n        if (add_l <= add_r)\\n        {\\n            cnt[add_l]++;\\n            cnt[add_r + 1]--;\\n        }\\n        else\\n        {\\n            cnt[add_l]++;\\n            cnt[0]++;\\n            cnt[add_r + 1]--;\\n        }\\n    }\\n}\\n\\nint main()\\n{\\n#ifdef ONPC\\n    freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n    ios::sync_with_stdio(0);\\n    cin.tie(0);\\n    int n, L;\\n    cin >> n >> L;\\n    vector <int> a(n), b(n);\\n    for (int i = 0; i < n; i++)\\n    {\\n        cin >> a[i];\\n    }\\n    for (int i = 0; i < n; i++)\\n    {\\n        cin >> b[i];\\n    }\\n    sort(a.begin(), a.end());\\n    sort(b.begin(), b.end());\\n    int vl = -1, vr = L;\\n    while (vl < vr - 1)\\n    {\\n        int x = (vl + vr) / 2;\\n        vector <int> cnt(n + 1);\\n        for (int i = 0; i < n; i++)\\n        {\\n            int my_l = max(0, a[i] - x), my_r = min(L - 1, a[i] + x);\\n            int pref_add = -1, suf_add = L;\\n            if (a[i] - (L - x) >= my_l)\\n            {\\n                my_l = 0;\\n            }\\n            else\\n            {\\n                pref_add = max(-1, a[i] - (L - x));\\n            }\\n            if (a[i] + (L - x) <= my_r)\\n            {\\n                my_r = L - 1;\\n            }\\n            else\\n            {\\n                suf_add = min(L, a[i] + (L - x));\\n            }\\n            add(my_l, my_r, b, cnt, i);\\n            add(0, pref_add, b, cnt, i);\\n            add(suf_add, L - 1, b, cnt, i);\\n        }\\n        bool good = false;\\n        for (int i = 1; i <= n; i++)\\n        {\\n            cnt[i] += cnt[i - 1];\\n        }\\n        for (int i = 0; i < n; i++)\\n        {\\n            if (cnt[i] == n)\\n            {\\n                good = true;\\n            }\\n        }\\n        if (good)\\n        {\\n            vr = x;\\n        }\\n        else\\n        {\\n            vl = x;\\n        }\\n    }\\n    cout << vr << '\\\\n';\\n}\"",
    "tags": [
      "binary search",
      "graph matchings",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "981",
    "index": "G",
    "title": "Magic multisets",
    "statement": "In the School of Magic in Dirtpolis a lot of interesting objects are studied on Computer Science lessons.\n\nConsider, for example, the magic multiset. If you try to add an integer to it that is already presented in the multiset, each element in the multiset duplicates. For example, if you try to add the integer $2$ to the multiset $\\{1, 2, 3, 3\\}$, you will get $\\{1, 1, 2, 2, 3, 3, 3, 3\\}$.\n\nIf you try to add an integer that is not presented in the multiset, it is simply added to it. For example, if you try to add the integer $4$ to the multiset $\\{1, 2, 3, 3\\}$, you will get $\\{1, 2, 3, 3, 4\\}$.\n\nAlso consider an array of $n$ initially empty magic multisets, enumerated from $1$ to $n$.\n\nYou are to answer $q$ queries of the form \"add an integer $x$ to all multisets with indices $l, l + 1, \\ldots, r$\" and \"compute the sum of sizes of multisets with indices $l, l + 1, \\ldots, r$\". The answers for the second type queries can be large, so print the answers modulo $998244353$.",
    "tutorial": "For each value of $x$, let's maintain the set of elements on which this value is present. We will do this by maintaining segments in the set (don't worry, we will get rid of this unpleasant part later). Then you just need to take all the segments crossing $l$ or $r$, cut them into two smaller ones, and then everything inside all the segments inside the segment $[l..r]$ must be multiplied by $2$, and to the rest we must add $1$. How to do that? To do this, we store the segment tree, in each vertex modifiers $a$, $b$, such that all numbers $x$ in the subtree are equal to $a \\cdot x + b$, not $x$. We can simply push and recalculate sum with these modifiers (look at the example code for more information about this). Then you need to add segment $[l..r]$ to the set. So we got the solution in $O((n + q) \\cdot log n)$. But the not very nice part is maintaining the segments in the set. Let's get rid of this, take all the left and right bounds of the queries where it occurs, divide all the numbers into segments where the values will always be equal, and maintain (set? no, DSU!), if the segment does not contain a number, then let $par[i] = i$, otherwise $par[i] = i + 1$, (and, of course, use the path compression heuristics) then you can just start jumping from the left segment of the query, and merge neighboring segments, this solution is with the same asympotitcs, but much nicer for implementation.",
    "code": "\"/*\\n    Author: isaf27 (Ivan Safonov)\\n*/\\n\\n//#pragma GCC optimize(\\\"O3\\\")\\n#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\n//defines\\ntypedef long long ll;\\ntypedef double ld;\\n#define TIME clock() * 1.0 / CLOCKS_PER_SEC\\n#define fast_read cin.sync_with_stdio(0)\\n#define nul point(0, 0)\\n#define str_to_int(stroka) atoi(stroka.c_str())\\n#define str_to_ll(stroka) atoll(stroka.c_str())\\n#define str_to_double(stroka) atof(stroka.c_str())\\n#define what_is(x) cerr << #x << \\\" is \\\" << x << endl\\n#define solve_system int number; cin >> number; for (int i = 0; i < number; i++) solve()\\n#define solve_system_scanf int number; scanf(\\\"%d\\\", &number); forn(i, 0, number) solve()\\n\\n//permanent constants\\nconst ld pi = 3.141592653589793238462643383279;\\nconst ld log23 = 1.58496250072115618145373894394781;\\nconst ld eps = 1e-10;\\nconst ll INF = 1e18 + 239;\\nconst ll prost = 239;\\nconst int two = 2;\\nconst int th = 3;\\nconst ll MOD = 1e9 + 7;\\nconst ll MOD2 = MOD * MOD;\\nconst int BIG = 1e9 + 239;\\nconst int alf = 26;\\nconst int dx[4] = {-1, 0, 1, 0};\\nconst int dy[4] = {0, 1, 0, -1};\\nconst int dxo[8] = {-1, -1, -1, 0, 1, 1, 1, 0};\\nconst int dyo[8] = {-1, 0, 1, 1, 1, 0, -1, -1};\\nconst int dig = 10;\\nconst string str_alf = \\\"abcdefghijklmnopqrstuvwxyz\\\";\\nconst string str_alf_big = \\\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\\";\\nconst int day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\\nconst int digarr[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};\\nconst int bt = 31;\\n\\n//easy functions\\ntemplate< typename T >\\ninline T gcd(T a, T b) { return a ? gcd(b % a, a) : b; }\\ntemplate< typename T >\\ninline T lcm(T a, T b) { return (a / gcd(a, b)) * b; }\\ninline bool is_down(char x) { return ('a' <= x && x <= 'z'); }\\ninline bool is_upper(char x) { return ('A' <= x && x <= 'Z'); }\\ninline bool is_digit(char x) { return ('0' <= x && x <= '9'); }\\nll power(ll a, int k)\\n{\\n    ll ans = 1;\\n    while (k)\\n    {\\n        if (k & 1) ans = (ans * a) % MOD;\\n        ans = (ans * ans) % MOD;\\n        k >>= 1;\\n    }\\n    return ans;\\n}\\n\\n//random\\nmt19937 rnd(239);\\n\\n//constants\\nconst int M = 2 * 1e5 + 239;\\nconst int N = 2 * 1e3 + 239;\\nconst int L = 20;\\nconst int T = (1 << 19);\\nconst int B = trunc(sqrt(M)) + 1;\\nconst int X = 1e4 + 239;\\nconst ll D = 998244353;\\n\\n// Code starts here\\n\\nstruct dsu\\n{\\n    vector<int> parent, rg, r;\\n\\n    dsu()\\n    {\\n        parent = rg = r = {};\\n    }\\n\\n    dsu(int n)\\n    {\\n        parent.resize(n);\\n        rg.resize(n);\\n        r.resize(n);\\n        for (int i = 0; i < n; i++)\\n            parent[i] = i, r[i] = 0, rg[i] = i + 1;\\n    }\\n\\n    int find_set(int a)\\n    {\\n        if (parent[a] == a)\\n            return a;\\n        return parent[a] = find_set(parent[a]);\\n    }\\n\\n    void merge_set(int a, int b)\\n    {\\n        a = find_set(a);\\n        b = find_set(b);\\n        if (a == b)\\n            return;\\n        if (r[a] > r[b])\\n            swap(a, b);\\n        rg[b] = max(rg[b], rg[a]);\\n        parent[a] = b;\\n        if (r[a] == r[b]) r[b]++;\\n    }\\n\\n    bool is_connect(int a, int b)\\n    {\\n        return find_set(a) == find_set(b);\\n    }\\n\\n    int getnxt(int a)\\n    {\\n        return rg[find_set(a)];\\n    }\\n};\\n\\n//segtree\\nll tree[T];\\nll a[T], b[T];\\n\\ninline void build(int i, int l, int r)\\n{\\n    a[i] = 1;\\n    b[i] = 0;\\n    tree[i] = 0;\\n    if (r - l == 1) return;\\n    int mid = (l + r) >> 1;\\n    build(2 * i + 1, l, mid);\\n    build(2 * i + 2, mid, r);\\n}\\n\\ninline void push(int i, int l, int r)\\n{\\n    tree[i] = (tree[i] * a[i] + b[i] * (ll)(r - l)) % D;\\n    if (r - l != 1)\\n    {\\n        a[2 * i + 1] = (a[2 * i + 1] * a[i]) % D;\\n        b[2 * i + 1] = (b[2 * i + 1] * a[i] + b[i]) % D;\\n        a[2 * i + 2] = (a[2 * i + 2] * a[i]) % D;\\n        b[2 * i + 2] = (b[2 * i + 2] * a[i] + b[i]) % D;\\n    }\\n    a[i] = 1;\\n    b[i] = 0;\\n}\\n\\ninline void change(int i, int l, int r, int ql, int qr, int t)\\n{\\n    push(i, l, r);\\n    if (qr <= l || r <= ql) return;\\n    if (ql <= l && r <= qr)\\n    {\\n        if (t == 0)\\n        {\\n            a[i] = (a[i] * 2LL) % D;\\n            b[i] = (b[i] * 2LL) % D;\\n        }\\n        else\\n        {\\n            b[i] = (b[i] + 1) % D;\\n        }\\n        push(i, l, r);\\n        return;\\n    }\\n    int mid = (l + r) >> 1;\\n    change(2 * i + 1, l, mid, ql, qr, t);\\n    change(2 * i + 2, mid, r, ql, qr, t);\\n    tree[i] = (tree[2 * i + 1] + tree[2 * i + 2]) % D;\\n}\\n\\ninline ll getsum(int i, int l, int r, int ql, int qr)\\n{\\n    push(i, l, r);\\n    if (qr <= l || r <= ql) return 0;\\n    if (ql <= l && r <= qr) return tree[i];\\n    int mid = (l + r) >> 1;\\n    return (getsum(2 * i + 1, l, mid, ql, qr) + getsum(2 * i + 2, mid, r, ql, qr)) % D;\\n}\\n//end\\n\\nint n, q;\\nvector<vector<int> > qr;\\nvector<vector<int> > vx(M);\\nvector<vector<pair<int, int> > > seg(M);\\nvector<vector<bool> > used(M);\\nvector<dsu> d;\\n\\ninline void upd(int x, int l, int r)\\n{\\n    vector<int> nw;\\n    int i = lower_bound(seg[x].begin(), seg[x].end(), make_pair(l, 0)) - seg[x].begin();\\n    while (i < seg[x].size())\\n    {\\n        if (seg[x][i].second > r) break;\\n        if (used[x][i])\\n        {\\n            i = d[x].getnxt(i);\\n            continue;\\n        }\\n        nw.push_back(i);\\n        i = d[x].getnxt(i);\\n    }\\n    for (int i : nw) change(0, 0, n, seg[x][i].first, seg[x][i].second + 1, 1);\\n    vector<int> a;\\n    a.push_back(l);\\n    for (int i : nw)\\n    {\\n        a.push_back(seg[x][i].first - 1);\\n        a.push_back(seg[x][i].second + 1);\\n    }\\n    a.push_back(r);\\n    for (int i = 0; i < a.size(); i += 2)\\n    {\\n        if (a[i] > a[i + 1]) continue;\\n        change(0, 0, n, a[i], a[i + 1] + 1, 0);\\n    }\\n    for (int i : nw)\\n    {\\n        used[x][i] = true;\\n        if (i != 0 && used[x][i - 1]) d[x].merge_set(i - 1, i);\\n        if (i != (int)seg[x].size() - 1 && used[x][i + 1]) d[x].merge_set(i, i + 1);\\n    }\\n}\\n\\ninline ll gett(int l, int r)\\n{\\n    return getsum(0, 0, n, l, r + 1);\\n}\\n\\nint main()\\n{   /*\\n    #ifndef ONLINE_JUDGE\\n    freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    freopen(\\\"output.txt\\\", \\\"w\\\", stdout);\\n    #endif /**/\\n    fast_read;\\n    cin >> n >> q;\\n    for (int i = 0; i < q; i++)\\n    {\\n        int t;\\n        cin >> t;\\n        if (t == 1)\\n        {\\n            int l, r, x;\\n            cin >> l >> r >> x;\\n            l--, r--, x--;\\n            qr.push_back({l, r, x});\\n            vx[x].push_back(l);\\n            vx[x].push_back(r);\\n        }\\n        else\\n        {\\n            int l, r;\\n            cin >> l >> r;\\n            l--, r--;\\n            qr.push_back({l, r});\\n        }\\n    }\\n    d.resize(n);\\n    for (int i = 0; i < n; i++)\\n    {\\n        sort(vx[i].begin(), vx[i].end());\\n        vx[i].resize(unique(vx[i].begin(), vx[i].end()) - vx[i].begin());\\n        for (int x = 0; x < vx[i].size(); x++)\\n        {\\n            seg[i].push_back(make_pair(vx[i][x], vx[i][x]));\\n            if (x + 1 != vx[i].size())\\n                if (vx[i][x + 1] - vx[i][x] != 1)\\n                    seg[i].push_back(make_pair(vx[i][x] + 1, vx[i][x + 1] - 1));\\n        }\\n        used[i].assign(seg[i].size(), false);\\n        d[i] = dsu(seg[i].size());\\n    }\\n    build(0, 0, n);\\n    for (int z = 0; z < q; z++)\\n    {\\n        if (qr[z].size() == 3)\\n            upd(qr[z][2], qr[z][0], qr[z][1]);\\n        else\\n            cout << gett(qr[z][0], qr[z][1]) << \\\"\\\\n\\\";\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "981",
    "index": "H",
    "title": "K Paths",
    "statement": "You are given a tree of $n$ vertices. You are to select $k$ (not necessarily distinct) simple paths in such a way that it is possible to split all edges of the tree into three sets: edges not contained in any path, edges that are a part of exactly one of these paths, and edges that are parts of all selected paths, and the latter set should be non-empty.\n\nCompute the number of ways to select $k$ paths modulo $998244353$.\n\nThe paths are enumerated, in other words, two ways are considered distinct if there are such $i$ ($1 \\leq i \\leq k$) and an edge that the $i$-th path contains the edge in one way and does not contain it in the other.",
    "tutorial": "For each vertex $v$ let's calculate $f_v$ - number of ways to choose $k$ ends for paths in their subtree, such that these paths are edge-intersecting, and $g_v$ - sum of $f_u$ by all vertices $u$ in subtree of $v$. Let $sz_v$ will be number of vertices in subtree of $v$. Then let $P(x) = (1 + x \\cdot sz_{u_{0}}) \\cdot (1 + x \\cdot sz_{u_{1}}) \\ldots \\cdot (1 + x \\cdot sz_{u_{deg - 1}})$, (where $u_0, u_1, \\ldots, u_{deg - 1}$ are the childs of vertex $v$), $= \\sum(a_k \\cdot x^k)$ How to calculate $P(x)$? We will use divide and conquer, let's recursively calculate answer for first half of element, for second, and then multiplicate. $T(n) = 2 T(n / 2) + O(n log n) = O(n log^2 n)$ Note, that degree of polynom is not $n$, but $deg_v$!. Then $f_v = \\sum(a_x \\cdot C_k^x \\cdot x!)$. Then for fixed non-vertical path $u \\to v$, number of ways to choose $k$ paths, such that their intersection is $u \\to v$ is $f_u \\cdot f_v$. We can sum this up for each non-vertical path with simple tree dp. So we are working in $O(deg_v log^2 n)$ for fixed $v$, summing up for each vertex we can get that this part of solution is working in $O(n log^2 n)$. Let fix one end of vertical path $v$ and it's son $u$, such that second end of vertical path is inside his subtree, Then let $Q(x) = P(x) \\cdot(1 + x \\cdot (n - sz_v)) / (1 + x \\cdot sz_u) = \\sum(b_k \\cdot x^k)$, when we need add $\\sum(b_x \\cdot C_k^x \\cdot x!) \\cdot g_u$ to answer. Then we can note, that (for fixed $v$) number of distinct $sz_u$'s - $O(\\sqrt{n})$ And for each $sz_u$ we can get $Q(x)$ in $O(deg_v)$, at first we need to calculate (one time!) $P(x) \\cdot(1 + x \\cdot (n - sz_v)) = \\sum(c_k \\cdot x^k)$, and then $b_0 = 1$, and $b_x = c_x - b_{x-1} \\cdot sz_u$. So, this part is working in $O(deg_v \\cdot \\sqrt{n})$ for fixed $v$, summing up for each vertices we can get that this part of solution is working in $O(n \\sqrt{n})$, so we solved the task in $O(n log^2 n + n \\sqrt{n})$",
    "code": "\"#pragma GCC optimize(\\\"O3\\\")\\n#include <cmath>\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n#include <unordered_map>\\n#include <unordered_set>\\n#include <iomanip>\\n#include <bitset>\\n#include <sstream>\\n\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\ntypedef long double ld;\\n\\n#define TIME (clock() * 1.0 / CLOCKS_PER_SEC)\\n\\nmt19937 rnd(239);\\n\\nconst ld pi = acos(-1.0);\\nconst ll INF = 1e18 + 239;\\nconst int BIG = 1e9 + 239;\\n//const ll MOD = 1e9 + 7;\\n//const ll MOD2 = MOD * MOD;\\nconst int M = 2e5 + 239;\\nconst int T = (1 << 19);\\n\\nconst ll MOD = 998244353;\\nconst ll root = 3;\\nconst ll sub = 15311432;\\n\\nll st[T];\\n\\ninline ll power(ll a, ll b)\\n{\\n    if (b == 0)\\n        return 1;\\n    ll t = power(a, (b >> 1));\\n    t = (t * t) % MOD;\\n    if (b & 1)\\n        return (t * a) % MOD;\\n    return t;\\n}\\n\\ninline int inv(int n, int b)\\n{\\n    int ans = 0;\\n    for (int i = 0; i < b; i++)\\n    {\\n        ans = (ans << 1) + (n & 1);\\n        n >>= 1;\\n    }\\n    return ans;\\n}\\n\\nint p;\\nll w;\\n\\nmap <vector <ll>, vector <ll> > pq;\\n\\ninline void fft(const vector<ll> &a, vector <ll> &b)\\n{\\n    if (pq.count(a))\\n    {\\n        b = pq[a];\\n        return;\\n    }\\n    b.resize(a.size());\\n    for (int i = 0; i < a.size(); i++)\\n        b[i] = a[inv(i, p)];\\n    for (int z = 0; z < p; z++)\\n    {\\n        int u = (1 << z);\\n        for (int i = 0; i < (1 << p); i++)\\n        {\\n            int ps = i >> z;\\n            if ((ps & 1) == 0)\\n            {\\n                int t = i & (u - 1);\\n                ll bi = (b[i] + st[t << (p - z - 1)] * b[i + u]) % MOD;\\n                ll bii = (b[i] + st[(t + u) << (p - z - 1)] * b[i + u]) % MOD;\\n                b[i] = bi;\\n                b[i + u] = bii;\\n            }\\n        }\\n    }\\n    pq[a] = b;\\n}\\n\\ninline vector<ll> sum(vector<ll> a, vector<ll> b)\\n{\\n\\tint n = max((int)a.size(), (int)b.size());\\n\\tvector<ll> ans(n, 0);\\n\\twhile (a.size() < n) a.push_back(0);\\n\\twhile (b.size() < n) b.push_back(0);\\n\\tfor (int i = 0; i < n; i++) ans[i] = (a[i] + b[i]) % MOD;\\n\\treturn ans;\\n}\\n\\nvector <ll> ta, tb;\\nvector<ll> as;\\n\\n\\ninline vector<ll> multiply(vector<ll> a, vector<ll> b)\\n{\\n    int k = (a.size() + b.size() + 1);\\n    p = trunc(log2(k)) + 1;\\n    while (a.size() < (1 << p)) a.push_back(0);\\n    while (b.size() < (1 << p)) b.push_back(0);\\n    w = power(sub, (1 << (23 - p)));\\n    st[0] = 1LL;\\n    for (int i = 1; i < (1 << p); i++)\\n        st[i] = (st[i - 1] * w) % MOD;\\n    fft(a, ta);\\n    fft(b, tb);\\n    vector<ll> v;\\n    for (int i = 0; i < (1 << p); i++)\\n        v.push_back((ta[i] * tb[i]) % MOD);\\n    fft(v, as);\\n    ll d = power((1 << p), MOD - 2);\\n    for (int i = 0; i < (1 << p); i++)\\n        as[i] = (d * as[i]) % MOD;\\n    reverse(as.begin() + 1, as.end());\\n    while (as.back() == 0) as.pop_back();\\n    return as;\\n}\\n\\nint n, k, kol[M];\\nvector <int> v[M];\\nll f[M], ans;\\nll mlt;\\nint sz;\\nll a[M], s[M];\\nll u, kf[M], fact[M];\\n\\ninline pair<vector<ll>, vector<ll> > func(int l, int r)\\n{\\n\\tif (r - l == 1)\\treturn {{s[l], (u * s[l]) % MOD}, {1, a[l]}};\\n\\tint mid = (l + r) >> 1;\\n\\tpair<vector<ll>, vector<ll> > a1 = func(l, mid);\\n\\tpair<vector<ll>, vector<ll> > a2 = func(mid, r);\\n\\treturn make_pair(sum(multiply(a1.first, a2.second), multiply(a1.second, a2.first)), multiply(a1.second, a2.second));\\n}\\n\\nll dfs(int p, int pr)\\n{\\n    kol[p] = 1;\\n    int szt = 0;\\n    vector <ll> aa, sa;\\n    for (int i : v[p])\\n        if (pr != i)\\n        {\\n            ll now = dfs(i, p);\\n            kol[p] += kol[i];\\n            aa.push_back(kol[i]);\\n            sa.push_back(now);\\n        }\\n    sz = aa.size();\\n    for (int i = 0; i < sz; i++)\\n    {\\n        a[i] = aa[i];\\n        s[i] = sa[i];\\n    }\\n    u = n - kol[p];\\n    ll sum = 0;\\n    for (int i = 0; i < sz; i++) sum = (sum + s[i]) % MOD;\\n    ll sqr = 0;\\n    for (int i = 0; i < sz; i++) sqr = (sqr + s[i] * s[i]) % MOD;\\n    sqr = (sum * sum - sqr) % MOD;\\n    if (sqr < 0) sqr += MOD;\\n    ans = (ans + sqr * mlt) % MOD;\\n    if (sz == 0)\\n    {\\n        return 1;\\n    }\\n    pair<vector<ll>, vector<ll> > t = func(0, sz);\\n    int s = max((int)t.first.size(), (int)t.second.size());\\n    for (int i = 0; i < min(s, k + 1); i++)\\n    {\\n\\t\\tif ((int)t.first.size() > i) ans = (ans + kf[i] * t.first[i]) % MOD;\\n\\t\\tif ((int)t.second.size() > i)\\n\\t\\t{\\n            sum = (sum + kf[i] * t.second[i]) % MOD;\\n\\t\\t}\\n\\t}\\n\\treturn sum;\\n}\\n\\nint main()\\n{   //*\\n    //freopen(\\\"test.in\\\", \\\"r\\\", stdin);\\n    //freopen(\\\"test.out\\\", \\\"w\\\", stdout); /**/\\n    ios::sync_with_stdio(0);\\n    cin.tie(0);\\n\\tcin >> n >> k;\\n\\tif (k == 1)\\n\\t{\\n\\t\\tcout << (((ll)n * (ll)(n - 1)) / 2) % MOD;\\n\\t\\treturn 0;\\n\\t}\\n\\tfor (int i = 0; i < n - 1; i++)\\n\\t{\\n\\t\\tint s, f;\\n\\t\\tcin >> s >> f;\\n\\t\\ts--, f--;\\n\\t\\tv[s].push_back(f);\\n\\t\\tv[f].push_back(s);\\n\\t}\\n\\tfact[0] = 1;\\n\\tfor (int i = 0; i < k; i++) fact[i + 1] = (fact[i] * (ll)(i + 1)) % MOD;\\n\\tfor (int i = 0; i <= k; i++) kf[i] = (fact[k] * power(fact[k - i], MOD - 2)) % MOD;\\n    ans = 0;\\n    mlt = power(2, MOD - 2);\\n    dfs(0, -1);\\n    cout << ans;\\n    return 0;\\n}\"",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "982",
    "index": "A",
    "title": "Row",
    "statement": "You're given a row with $n$ chairs. We call a seating of people \"maximal\" if the two following conditions hold:\n\n- There are no neighbors adjacent to anyone seated.\n- It's impossible to seat one more person without violating the first rule.\n\nThe seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is \"maximal\".\n\nNote that the first and last seats are \\textbf{not} adjacent (if $n \\ne 2$).",
    "tutorial": "Seating is the maximum when it does not exist two ones or three zeros together. It is also necessary to carefully process the ends of the series - it is necessary to check that you can not put a person on the most right or the most left chairs.",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1200
  },
  {
    "contest_id": "982",
    "index": "B",
    "title": "Bus of Characters",
    "statement": "In the Bus of Characters there are $n$ rows of seat, each having $2$ seats. The width of both seats in the $i$-th row is $w_i$ centimeters. All integers $w_i$ are distinct.\n\nInitially the bus is empty. On each of $2n$ stops one passenger enters the bus. There are two types of passengers:\n\n- an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it;\n- an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it.\n\nYou are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.",
    "tutorial": "Note that the final introvert-extrovert pairs are uniquely determined, and that using the stack, it is possible to recover which extrovert to which introvert will sit (note that the zeros and ones will form the correct bracket sequence). Then one of the solutions may be as follows: Sort the array of the lengths of the rows in ascending order For each introvert write the number of the next free row and add it to the stack For each extrovert write the last number from the stack and remove it from there",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "982",
    "index": "C",
    "title": "Cut 'em all!",
    "statement": "You're given a tree with $n$ vertices.\n\nYour task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.",
    "tutorial": "Note that if there is an edge that can be removed, we can do it without any problem. Let's consider such edge that in one of the obtained subtrees it is impossible to delete more anything else, and its removal is possible. What happens if we delete it in the tree? Relative to the other end of the edge, the odd-even balance of the subtree has not changed, which means that the edge has not been affected by further deletions. Which means if we remove it, the answer will be better. This is followed by a greedy solution: in dfs we count the size of the subtree for each vertex, including the current vertex, and if it is even, then the edge from the parent (if it exists) can be removed.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "982",
    "index": "D",
    "title": "Shark",
    "statement": "For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.\n\nMax is a young biologist. For $n$ days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer $k$ that if the shark in some day traveled the distance strictly less than $k$, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to $k$; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least $k$.\n\nThe shark never returned to the same location after it has moved from it. Thus, in the sequence of $n$ days we can find consecutive nonempty segments when the shark traveled the distance less than $k$ in each of the days: each such segment corresponds to one location. Max wants to choose such $k$ that the lengths of all such segments are equal.\n\nFind such integer $k$, that the number of locations is as large as possible. If there are several such $k$, print the smallest one.",
    "tutorial": "Let's sort the array and insert the numbers in the sort order from smaller to larger. Using the data structure \"disjoint set union\" we can easily maintain information about the current number of segments, as well as using the map within the function of union, and information about the current size of segments (locations) too. Then it remains only to update the answer when it's needed.",
    "tags": [
      "brute force",
      "data structures",
      "dsu",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "982",
    "index": "E",
    "title": "Billiard",
    "statement": "Consider a billiard table of rectangular size $n \\times m$ with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture).\n\nThere is one ball at the point $(x, y)$ currently. Max comes to the table and strikes the ball. The ball starts moving along a line that is parallel to one of the axes or that makes a $45^{\\circ}$ angle with them. We will assume that:\n\n- the angles between the directions of the ball before and after a collision with a side are equal,\n- the ball moves indefinitely long, it only stops when it falls into a pocket,\n- the ball can be considered as a point, it falls into a pocket if and only if its coordinates coincide with one of the pockets,\n- initially the ball is not in a pocket.\n\nNote that the ball can move along some side, in this case the ball will just fall into the pocket at the end of the side.\n\nYour task is to determine whether the ball will fall into a pocket eventually, and if yes, which of the four pockets it will be.",
    "tutorial": "If you symmetrically reflect a rectangle on the plane relative to its sides, the new trajectory of the ball will be much easier. Linear trajectory if be correct. One possible solution is: If the vector is directed at an angle of 90 degrees to the axes, then write the if-s. Otherwise, turn the field so that the impact vector becomes $(1, 1)$. Write the equation of the direct motion of the ball: $- 1 \\cdot x + 1 \\cdot y + C = 0$. If we substitute the initial position of the ball, we find the coefficient $C$. Note that in the infinite tiling of the plane the coordinates of any holes representable in the form $(k_{1} \\cdot n, k_{2} \\cdot m)$. Substitute the coordinates of the points in the equation of the line of the ball. The Diophantine equation $a \\cdot k_{1} + B \\cdot k_{2} = C$is obtained. It is solvable if $C | gcd(A, B)$. Otherwise, there are no solutions. Of all the solutions of this Diophantine equation, we are interested in the smallest on the positive half-axis. By finding $k_{1}, k_{2}$ it is easy to get the coordinates of the corresponding pocket Rotate the field back if required.",
    "tags": [
      "geometry",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "982",
    "index": "F",
    "title": "The Meeting Place Cannot Be Changed",
    "statement": "Petr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping.\n\nPetr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two intersections. Petr wants to select one intersection such that if the robbers continue to drive the roads indefinitely, they will sooner or later come to that intersection. The initial position of the robbers is unknown. Find such an intersection that fits the requirements.",
    "tutorial": "Let's assume that solution exists and will looking for solution relying on this assumption. At the end will check found \"solution\" in linear time, and if it is not real solution, then assumption wasn't right. If solution exists, then intersection (by vertices) of all cycles is not empty. Let's take any one cycle and call it \"main cycle\". Let's imagine this \"main cycle\" as circle directed clockwise. And let's mark all required vertices of intersection of all cycles on this circle (this vertices are the answer). Consider only cycles which leave \"main cycle\", come back to the \"main cycle\", and then moves on the \"main cycle\" to the begining. Every such cycle when comes back to the \"main cycle\" DOES NOT jump over any marked vertex of the answer, in terms of direction of the \"main cycle\" (otherwise answer not exists, but we assumed, that it exists) (if cycle comes back to the same vertex, then by definition it jumped over the whole \"main cycle\", not 0). Draw the arc from the vertex, where cycle comes back to the \"main cycle\" till the vertex, where it leaves \"main cycle\", in the direction of the \"main cycle\". Vertices not covered by this arc can't be the answer. Intersection of all considered cycles is marked by intersection of all such arcs. Now was not considered only cycles which some times leave \"main cycle\" and some times comes back to it. But intersection of such cycle with the \"main cycle\" is the same as intersection of simple cycles from previous paragraph between adjacent leave/comebacks. Therefore such cycles may be ignored. For searching the answer we must mark arcs between leaves/comebacks of the main cycle. We do this by starting dfs from all vertices of the \"main cycle\" and trying to come back to it as far as possible (distance measured as the number of vertices of the \"main cycle\" between leave and comeback). As were noticed early, cycles does not jump over the answer. Therefore dfses started between boundaries of the answer are aspires to this boundary in direction of the \"main cycle\". Therefore if we selected the most far vertex in one dfs(u) reached from one start point v0, this vertex for dfs(u) reached from other start point v1 will be the most far too. And we can run all dfses with common \"used\" array, caching the most far vertex in it. Finally the solution is so: 1) find the \"main cycle\" and sort vertices in it, 2) start dfses from vertices of the \"main cycle\" and mark arcs between finish and start, 3) intersect all arcs and take answer from intersection, 4) verify answer by deleting it from graph and trying to find any other cycle, if it founded, then assumption was wrong and solution doesn't exists else print the answer.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "983",
    "index": "A",
    "title": "Finite or not?",
    "statement": "You are given several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction.\n\nA fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.",
    "tutorial": "First, if $p$ and $q$ are not coprime, divide them on $\\gcd(p,q)$. Fraction is finite if and only if there is integer $k$ such that $q \\mid p \\cdot b^k$. Since $p$ and $q$ are being coprime now, $q \\mid b^k \\Rightarrow$ all prime factors of $q$ are prime factors of $b$. Now we can do iterations $q = q \\div \\gcd(b,q)$ while $\\gcd(q,b) \\ne 1$. If $q \\ne 1$ after iterations, there are prime factors of $q$ which are not prime factors of $b \\Rightarrow$ fraction is Infinite, else fraction is Finite. But this solution works in $O(nlog^210^{18})$. Let's add $b=\\gcd(b,q)$ in iterations and name iterations when $\\gcd(b,q)$ changes iterations of the first type and when it doesn't change - iterations of the second type. Iterations of second type works summary in $O(\\log10^{18})$. Number of iterations of the first type is $O(\\log10^{18})$ too but on each iteration $b$ decreases twice. Note that number of iterations in Euclid's algorithm is equal to number of this decreases. So iterations of first type works in $O(\\log10^{18})$ summary. Total time complexity is $O(n\\log10^{18})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tcout.tie(nullptr);\n\tint n;\n\tcin >> n;\n\twhile (n--) {\n\t\tlong long p, q, b;\n\t\tcin >> p >> q >> b;\n\t\tlong long g = gcd(p, q);\n\t\tq /= g;\n\t\tb = gcd(q, b);\n\t\twhile (b != 1) {\n\t\t\twhile (q % b == 0) q /= b;\n\t\t\tb = gcd(q, b);\n\t\t}\n\t\tif (q == 1)\n\t\t\tcout << \"Finite\\n\";\n\t\telse\n\t\t\tcout << \"Infinite\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "983",
    "index": "B",
    "title": "XOR-pyramid",
    "statement": "For an array $b$ of length $m$ we define the function $f$ as\n\n\\begin{center}\n$ f(b) = \\begin{cases} b[1] & \\quad \\text{if } m = 1 \\\\ f(b[1] \\oplus b[2],b[2] \\oplus b[3],\\dots,b[m-1] \\oplus b[m]) & \\quad \\text{otherwise,} \\end{cases} $\n\\end{center}\n\nwhere $\\oplus$ is bitwise exclusive OR.\n\nFor example, $f(1,2,4,8)=f(1\\oplus2,2\\oplus4,4\\oplus8)=f(3,6,12)=f(3\\oplus6,6\\oplus12)=f(5,10)=f(5\\oplus10)=f(15)=15$\n\nYou are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \\ldots, a_r$.",
    "tutorial": "Let's calculate $f(a)$ recursively and save arrays from each level of recursion. We get two-dimencional array $dp[n][n]$ and $dp[n][1]=f(a)$. Now let's view recursive calculation for $f(a_l \\ldots a_r)$. You can see what array of $i$-th level of recursion is $dp[i][l\\ldots r-i+1]\\Rightarrow dp[r-l+1][l]=f(a_l \\ldots a_r)$ (numbeer of levels of recursion is length of segment). To calculate maximum of all sub-segments for each segment, replace $dp[i][j]$ on $\\max(dp[i][j],dp[i-1][j],dp[i-1][j+1])$. Now answer of question $l,r$ is $dp[r-l+1][l]$. Overall time complexity is $O(n^2 + q)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint run();\n \nint main() {\n#ifdef home\n  freopen(\"i\", \"r\", stdin);\n  freopen(\"d\", \"w\", stderr);\n#endif\n  cout.precision(15);\n \n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n \n  run();\n}\n \nconst int N = 5000;\n \nint a[N];\n \nint dp[N][N];\n \nint run() {\n  int n;\n  cin >> n;\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n    dp[0][i] = a[i];\n  }\n  for (int i = 1; i < n; i++) {\n    for (int j = 0; j <= n - i; j++) {\n      dp[i][j] = dp[i - 1][j + 1] ^ dp[i - 1][j];\n    }\n  }\n \n  for (int i = 1; i < n; i++) {\n    for (int j = 0; j < n - i; j++) {\n      dp[i][j] = max({dp[i][j], dp[i - 1][j], dp[i - 1][j + 1]});\n    }\n  }\n \n  int q;\n  cin >> q;\n \n  for (int i = 0; i < q; i++) {\n    int l, r;\n    cin >> l >> r;\n    --l;\n    int len = r - l - 1;\n    cout << dp[len][l] << '\\n';\n  }\n}",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "983",
    "index": "C",
    "title": "Elevator",
    "statement": "You work in a big office. It is a $9$ floor building with an elevator that can accommodate up to $4$ people. It is your responsibility to manage this elevator.\n\nToday you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.\n\nAccording to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.\n\nThe elevator has two commands:\n\n- Go up or down one floor. The movement takes $1$ second.\n- Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends $1$ second to get inside and outside the elevator.\n\nInitially the elevator is empty and is located on the floor $1$.\n\nYou are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor $1$.",
    "tutorial": "This problem is inspired by living in the house of $9$ floors with the elevator, which can accommodate up to $4$ people. What a surprise! We have a strict order. So let's make $dp[i][state] =$ minimal possible time, where $i$ means that first $i$ employees already came in the elevator (and possibly came out). So, what is a $state$? Let's store something what will allow us to determine the state. For this purpose we want to know the floor, where the elevator currently is, and number of people, who want to reach each floor. So, it's $10$ integers. Let's estimate the number of states: floor takes $9$ values, $state$ can take ${\\binom{9}{4}}+{\\binom{9}{3}}+{\\binom{9}{1}}+{\\binom{9}{0}}+{\\binom{9}{0}}=256$ (Wow!). Also let's notice, that we don't want to visit floor of nobody in the elevator don't want to go there and the next person isn't on that floor. So we have not more than $5$ interesting floors for each $state$. Let's say the total count of states is $s = 5 \\cdot 256$. Now we've got two different solutions. The fast one is we say we go from the floor $a[i]$ to the floor $a[i + 1]$ and iterate over the persons who we let come in on the way. The slow one is to run Dijkstra for each $i$: from $state$ we can go to the floor and let somebody come out or go to the floor $a[i + 1]$. Now, when we calculated answers for $i - 1$, we can calculate $dp[i][state] = 1 + dp[i - 1][state]$, if state has floor equals to $a_{i}$ and there are no more than $3$ people inside. The answer will be in $dp[n][floor = j & elevator is empty]$ for $j\\in[1,9]$. Asymptotics is $O(n \\cdot s)$ or $O(n \\cdot s \\cdot log(s))$",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <set>\n#include <bitset>\n#include <queue>\n#include <stack>\n#include <sstream>\n#include <cstring>\n#include <numeric>\n#include <ctime>\n#include <cassert>\n \n#define re return\n#define fi first\n#define se second\n#define mp make_pair\n#define pb emplace_back\n#define all(x) (x).begin(), (x).end()\n#define sz(x) ((int) (x).size())\n#define rep(i, n) for (int i = 0; i < (n); i++)\n#define rrep(i, n) for (int i = (n) - 1; i >= 0; i--)\n#define y0 y32479\n#define y1 y95874\n#define fill(x, y) memset(x, y, sizeof(x))\n#define sqr(x) ((x) * (x))\n#define sqrt(x) sqrt(abs(x))\n#define unq(x) (x.resize(unique(all(x)) - x.begin()))\n#define spc(i,n) \" \\n\"[i == n - 1]\n#define next next239\n#define prev prev239\n#define ba back()\n#define last(x) x[sz(x) - 1]\n#define deb(x) cout << #x << \" = \" << (x) << endl\n#define deba(x) do { cout << #x << \" (size: \" << sz(x) << \") = \" << \\\n\t\"{\"; for (auto o : x) cout << o << \",\"; cout << \"}\" << endl;} while (0)\n \nusing namespace std;\n \ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef pair<int, int> ii;\ntypedef vector<ii> vii;\ntypedef vector<string> vs;\ntypedef long long ll;\ntypedef pair<ll, ll> pll;\ntypedef vector<ll> vll;\ntypedef long double LD;\ntypedef double D;\n \ntemplate<class T> T abs(T x) { return x > 0 ? x : -x;}\n \ntemplate<class T> T toString(T x) {\n\tostringstream sout;\n\tsout << x;\n\treturn sout.str();\n}\n \nint nint() {\n\tint x;\n\tscanf(\"%d\", &x);\n\tre x;\n}\n \nconst ll mod = 1000000000 + 7;\n \nint m;\nint n;\nll ans;\n \nint a[2050], b[2050];\n \nint table[2050][1050];\n \nvi split(int x) {\n\tvi ans;\n\trep(i, 3) {\n\t\tif (x % 10)\n\t\t\tans.pb(x % 10);\n\t\tx /= 10;\n\t}\n\tre ans;\n}\n \ninline int merge(vi &v, int x) {\n\tint ans = 0;\n\trep(i, 3) {\n\t\tans *= 10;\n\t\tif (i < sz(v) && v[i] != x)\n\t\t\tans += v[i];\n\t}\n\tre ans;\n}\n \ninline int get1(int l, int r, int x) {\n\tre min(abs(x - l), abs(x - r)) + r - l;\n}\n \ninline int get2(int l, int r, int x1, int x2) {\n\tre min(abs(x1 - l) + abs(x2 - r), abs(x1 - r) + abs(x2 - l)) + r - l;\n}\n \nint getans(int p, int cur) {\n\tint &ans = table[p][cur];\n\tif (ans != -1)\n\t\tre ans;\n \n\tint pos = a[p];\n\tvi v = split(cur);\n\tv.pb(b[p]);\n\tsort(all(v));\n \n\tif (p == n - 1) {\n\t\tans = get1(v[0], v.back(), pos);\n\t\tre ans;\n\t}\n \n\tans = mod;\n\tint ne = a[p + 1];\n \n\tif (sz(v) < 4)\n\t\tans = min(ans, getans(p + 1, merge(v, ne)) + abs(ne - pos));\n \n\trep(i, sz(v)) {\n\t\tif (i && (v[i] == v[i - 1]))\n\t\t\tcontinue;\n \n\t\tfor (int j = i; j < sz(v); j++) {\n\t\t\tif (j < sz(v) - 1 && v[j] == v[j + 1])\n\t\t\t\tcontinue;\n \n\t\t\tint tmp = get2(v[i], v[j], pos, ne);\n \n\t\t\tvi tv;\n\t\t\trep(k, sz(v)) {\n\t\t\t\tif (k < i || k > j)\n\t\t\t\t\ttv.pb(v[k]);\n\t\t\t}\n \n\t\t\tans = min(ans, tmp + getans(p + 1, merge(tv, ne)));\n\t\t}\n\t}\n \n\tre ans;\n}\n \nint main() {\n#ifdef LOCAL_BOBER\n\tfreopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\tsrand((int)time(0));\n#else\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n#endif\n \n\tcin >> n;\n\trep(i, n)\n\t\tcin >> a[i] >> b[i];\n \n\tfill(table, -1);\n\tcout << getans(0, 0) + a[0] - 1 + 2 * n;\n}\n \n \n \n \n \n ",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "983",
    "index": "D",
    "title": "Arkady and Rectangles",
    "statement": "Arkady has got an infinite plane painted in color $0$. Then he draws $n$ rectangles filled with paint with sides parallel to the Cartesian coordinate axes, one after another. The color of the $i$-th rectangle is $i$ (rectangles are enumerated from $1$ to $n$ in the order he draws them). It is possible that new rectangles cover some of the previous ones completely or partially.\n\nCount the number of different colors on the plane after Arkady draws all the rectangles.",
    "tutorial": "First let's compress the coordinates. Now all the coordinates are in $[0, 2n)$. Now we do scanline on $x$ coordinate with segment tree on $y$ coordinate. Let's talk about segment tree structute. In each vertex we store: Set of colors which cover the whole segment. If color covers a segment, we don't push it to it childs ($colors[v]$) Maximal visible color in subtree which isn't in the answer ($max[v]$) Minimal visible color in subtree ($min[v]$) For the vertex max and min can be calculated as: If $colors$ isn't empty and max value in $colors$ is more than max in children: If it's already in the answer or it's less than min in children, $max = -1$. Otherwise $max = max \\ in \\ colors$ Otherwise $max = max \\ in \\ children$ If $colors$ isn't empty $min = max(max \\ in \\ colors, min \\ in \\ children)$ Otherwise $min = min \\ in \\ children$ Now in scanline we: Add all the segments, starting at this point Remove all the segments, ending at this point While $max[root]$ isn't $-1$ we put it into $answer$ and recalculate everything by readding this segment to tree. At the end we know all visible colors and print the number of them. Asymptotics is $O(n \\cdot log(n) + n \\cdot log^2(n))$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nnamespace solution {\nint run();\n}\n \nint main() {\n#ifdef home\n  freopen(\"i\", \"r\", stdin);\n  freopen(\"d\", \"w\", stderr);\n#endif\n  cout.precision(15);\n \n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n \n  solution::run();\n}\nnamespace solution {\n \nconst int SZ = 1500500;\n \nconst int N = 100500;\n \nint x1[N], x2[N], y1[N], y2[N];\n \nbool erased[N];\n \npriority_queue<int> els[SZ];\n \nint mn[SZ];\nint mx[SZ];\n \nbool seen[N];\n \nenum {\n  ACTION_ADD,\n  ACTION_ERASE,\n  ACTION_VOID\n};\n \nvoid recalc(int cur) {\n  int max_in_child = max(mx[cur * 2], mx[cur * 2 + 1]);\n \n  while (!els[cur].empty() && erased[els[cur].top()]) {\n    els[cur].pop();\n  }\n \n  int max_in_vertex = els[cur].empty() ? -1 : els[cur].top();\n  int min_in_child = min(mn[cur * 2], mn[cur * 2 + 1]);\n \n  if (max_in_vertex > max_in_child) {\n    if (seen[max_in_vertex] || max_in_vertex < min_in_child) {\n      mx[cur] = -1;\n    } else {\n      mx[cur] = max_in_vertex;\n    }\n  } else {\n    mx[cur] = max_in_child;\n  }\n  mn[cur] = max(max_in_vertex, min_in_child);\n}\n \nvoid add(int cur, int lb, int rb, int id, int action, int l = 0, int r = 2 * N) {\n  if (lb >= r || rb <= l) {\n    return;\n  }\n \n  if (lb <= l && rb >= r) {\n    if (action == ACTION_ADD) {\n      els[cur].push(id);\n    }\n \n    recalc(cur);\n    return;\n  }\n \n  int mid = (l + r) / 2;\n \n  add(cur * 2, lb, rb, id, action, l, mid);\n  add(cur * 2 + 1, lb, rb, id, action, mid, r);\n \n  recalc(cur);\n}\n \nset<int> cx, cy;\n \nunordered_map<int, int> id_x, id_y;\n \nvector<pair<int, int> > events[2 * N];\n \nint run() {\n  int n;\n  cin >> n;\n  for (int i = 0; i < n; i++) {\n    cin >> x1[i] >> y1[i] >> x2[i] >> y2[i];\n \n    cx.insert(x1[i]);\n    cx.insert(x2[i]);\n \n    cy.insert(y1[i]);\n    cy.insert(y2[i]);\n  }\n \n  int j = 0;\n  for (auto x : cx) {\n    id_x[x] = j++;\n  }\n \n  j = 0;\n  for (auto y : cy) {\n    id_y[y] = j++;\n  }\n \n  for (int i = 0; i < n; i++) {\n    x1[i] = id_x[x1[i]];\n    x2[i] = id_x[x2[i]];\n \n    y1[i] = id_y[y1[i]];\n    y2[i] = id_y[y2[i]];\n \n    events[x1[i]].push_back({i, ACTION_ADD});\n \n    events[x2[i]].push_back({i, ACTION_ERASE});\n  }\n \n  for (int i = 0; i < SZ; i++) {\n    mx[i] = -1;\n  }\n \n  int cnt_x = id_x.size();\n \n  for (int i = 0; i < cnt_x; i++) {\n    for (auto e : events[i]) {\n      int id = e.first;\n      int action = e.second;\n      if (action == ACTION_ERASE) {\n        erased[id] = true;\n      }\n      add(1, y1[id], y2[id], id, action);\n    }\n    while (mx[1] >= mn[1]) {\n      int id = mx[1];\n      seen[id] = true;\n      add(1, y1[id], y2[id], id, ACTION_VOID);\n    }\n  }\n \n  int ans = 1;\n  for (int i = 0; i < n; i++) {\n    if (seen[i]) {\n      ans++;\n    }\n  }\n  cout << ans;\n \n}\n \n}",
    "tags": [
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "983",
    "index": "E",
    "title": "NN country",
    "statement": "In the NN country, there are $n$ cities, numbered from $1$ to $n$, and $n - 1$ roads, connecting them. There is a roads path between any two cities.\n\nThere are $m$ bidirectional bus routes between cities. Buses drive between two cities taking the shortest path with stops in every city they drive through. Travelling by bus, you can travel from any stop on the route to any other. You can travel between cities only by bus.\n\nYou are interested in $q$ questions: is it possible to get from one city to another and what is the minimum number of buses you need to use for it?",
    "tutorial": "Let's say we go down when we go towards the root, and we go up when we go against the root. Also we say that vertex $a$ lower than vertex $b$ if $a$ is closer to the root. Each way from $v$ to $u$ can be represented as two parts: at first we go down from $v$ to $lca$ and then we go up from $lca$ to $u$. Let's say we have to use $a$ buses to go from $v$ to $lca$ and $b$ buses to go from $lca$ to $u$. Let's learn how to calculate $a$ and $b$ fast. Firstly, notice that we can move down greedily. So we calculate $lowest[v]$ as the lowest vertex, where we can go from $v$ using only one bus. Secondly, notice that we can now build binary lifting on $lowest$. The answer is either $a + b$ or $a + b - 1$. Let's say the lowest vertex we can go from $v$ using $a - 1$ buses is $l_v$ and for $u$ and $b - 1$ buses it's $l_u$. $l_v$ and $l_u$ can be also calculated using binary lifting on $lowest$. Then, if there is a route connecting $l_v$ and $l_u$, the answer is $a + b - 1$ and it's $a + b$ otherwise. Let's calculate $l_v$ and $l_u$ for all the queries. Now we build an euler's tour. For each we now know the interval, corresponding to it's subtree. Let's say it is $[time\\_in[v], time\\_out[v])$. Then we run dfs again and do the following: when we came into $l_v$ we ask for sum on $[time\\_in[l_u], time\\_out[l_u])$. Now for each way, starting in $l_v$ we add $1$ to its other end. Now we run dfs for all of its children. And now we ask for sum on $[time\\_in[l_u], time\\_out[l_u])$ for the second time. If it changed the route connecting $l_v$ and $l_u$ exists. Asymptotics is $O(n \\cdot log(n) + m \\cdot log(n) + q \\cdot log(n))$. Read the solution for better understanding. It tried to make it as readable as possible.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint run();\n \nint main() {\n#ifdef home\n  freopen(\"i\", \"r\", stdin);\n  freopen(\"d\", \"w\", stderr);\n#endif\n  cout.precision(15);\n \n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n \n  run();\n}\n \nconst int N = 200000;\nconst int logN = 19;\n \nint n;\n \nvector<int> graph[N];\n \nint binary_lift_lca[N][logN];\nint time_in[N];\nint time_out[N];\nint current_time;\nint height[N];\n// Dfs to calculate all important things\n// Also generate Euler's tour\nvoid dfs_precalc_lca(int v, int ancestor = -1) {\n  binary_lift_lca[v][0] = ancestor;\n \n  height[v] = (ancestor != -1 ? height[ancestor] + 1 : 0);\n  if (v < 0 || v >= N) {\n    cerr << \"Fuck!\";\n  }\n  time_in[v] = current_time++;\n \n  for (int i = 1; i < logN; i++) {\n    if (binary_lift_lca[v][i - 1] == -1) {\n      binary_lift_lca[v][i] = -1;\n    } else {\n      binary_lift_lca[v][i] = binary_lift_lca[binary_lift_lca[v][i - 1]][i - 1];\n    }\n  }\n \n  for (auto to : graph[v]) {\n    dfs_precalc_lca(to, v);\n  }\n \n  time_out[v] = current_time;\n}\n \nint lowest[N];\nint dfs_precalc_lowest(int v) {\n  for (auto to : graph[v]) {\n    lowest[v] = min(lowest[v], dfs_precalc_lowest(to));\n  }\n  return lowest[v];\n}\n \n// Dfs to calculate lowest vertices we can get from current in 2 ** i turns\nint binary_lift_way[N][logN];\nvoid dfs_precalc_binary_lift_way(int v) {\n  binary_lift_way[v][0] = lowest[v];\n  for (int i = 1; i < logN; i++) {\n    binary_lift_way[v][i] = binary_lift_way[binary_lift_way[v][i - 1]][i - 1];\n  }\n  for (auto to : graph[v]) {\n    dfs_precalc_binary_lift_way(to);\n  }\n}\n \n// Check if v is ancestor of u\nbool isAncestor(int v, int u) {\n  if (v == -1) {\n    return true;\n  }\n  if (u == -1) {\n    return false;\n  }\n  return time_in[v] <= time_in[u] && time_out[v] >= time_out[u];\n}\n \nint lca(int v, int u) {\n  if (isAncestor(v, u)) {\n    return v;\n  }\n  if (isAncestor(u, v)) {\n    return u;\n  }\n  for (int i = logN - 1; i >= 0; i--) {\n    if (!isAncestor(binary_lift_lca[v][i], u)) {\n      v = binary_lift_lca[v][i];\n    }\n  }\n  return binary_lift_lca[v][0];\n}\n \n// Check if it's possible to get from v to u using routes\nbool reachable(int v, int u) {\n  for (int i = logN - 1; i >= 0; i--) {\n    if (!isAncestor(binary_lift_way[v][i], u)) {\n      v = binary_lift_way[v][i];\n    }\n  }\n  v = binary_lift_way[v][0];\n  return isAncestor(v, u);\n}\n \n// We go up from v, using as little number of buses as possible, until we get to the vertex\n// From which we can get to u in one turn\n// Returns pair<int, int> --- penultimate vertex on the way and the number of buses we used\npair<int, int> penultimate(int v, int u) {\n  int cnt = 0;\n  for (int i = logN - 1; i >= 0; i--) {\n    if (!isAncestor(binary_lift_way[v][i], u)) {\n      cnt += (1 << i);\n      v = binary_lift_way[v][i];\n    }\n  }\n  return {v, cnt};\n}\n \n// Here is just classical fenwick we'll use in dfs_calculate_answer\nint fenwick[N + 1];\n \nint f(int a) {\n  return a & (-a);\n}\n \nvoid fenwickAdd(int v, int val = 1) {\n  v++; // Fenwick is 1 indexed, v is 0 indexed\n  for (; v <= N; v += f(v)) {\n    fenwick[v] += val;\n  }\n}\n \nint fenwickGet(int r) {\n  int ans = 0;\n  for (; r > 0; r -= f(r)) {\n    ans += fenwick[r];\n  }\n  return ans;\n}\n \nint fenwickGet(int l, int r) {\n  return fenwickGet(r) - fenwickGet(l);\n}\nint answer[N];\nvector<pair<int, int>> query_for_vertex[N];\n \nint cnt_on_segment[N];\n \nvector<int> way_end[N];\n \nvoid dfs_calculate_answer(int v) {\n  for (auto query : query_for_vertex[v]) {\n    int u, id;\n    tie(u, id) = query;\n    cnt_on_segment[id] -= fenwickGet(time_in[u], time_out[u]);\n  }\n \n  for (auto end : way_end[v]) {\n    fenwickAdd(time_in[end]);\n  }\n \n  for (auto to : graph[v]) {\n    dfs_calculate_answer(to);\n  }\n \n  // The same thing as at the beginning\n  for (auto query : query_for_vertex[v]) {\n    int u, id;\n    tie(u, id) = query;\n    cnt_on_segment[id] += fenwickGet(time_in[u], time_out[u]);\n \n    // That means that exists the route, connecting v and u\n    if (cnt_on_segment[id] > 0) {\n      answer[id]--; // So our assuming is incorrect and we should decrease answer\n    }\n  }\n}\n \npair<int, int> way[N];\n \nbool bad[N];\n \nint run() {\n  cin >> n;\n  for (int i = 1; i < n; i++) {\n    int p;\n    cin >> p;\n    --p;\n    graph[p].push_back(i);\n  }\n \n  int m;\n  cin >> m;\n  for (int i = 0; i < m; i++) {\n    int v, u;\n    cin >> v >> u;\n    --v;\n    --u;\n    way_end[v].push_back(u); // We will know where routes starting in this vertex end\n    way_end[u].push_back(v); // We'll need it in dfs_calculate_answer\n    way[i] = {v, u};\n  }\n \n  // Precalc lca, Euler's tour and heights\n  dfs_precalc_lca(0);\n \n  // For each vertex we store lowest possible vertex\n  // In one turn\n  // Initially it's just its height\n  for (int i = 0; i < n; i++) {\n    lowest[i] = i;\n  }\n \n  // Split way to vertical\n  for (int i = 0; i < m; i++) {\n    int v, u;\n    tie(v, u) = way[i];\n    int lca_ = lca(v, u);\n    if (height[lowest[v]] > height[lca_] ) {\n      lowest[v] = lca_;\n    }\n    if (height[lowest[u]] > height[lca_]) {\n      lowest[u] = lca_;\n    }\n  }\n \n  dfs_precalc_lowest(0);\n \n  // Now we precalc binary lifts to answer queries\n  dfs_precalc_binary_lift_way(0);\n \n  int q;\n  cin >> q;\n  for (int i = 0; i < q; i++) {\n    int v, u;\n    cin >> v >> u;\n    --v; --u;\n    int len_v, len_u;\n    int lca_ = lca(v, u);\n \n    if (!reachable(v, lca_) || !reachable(u, lca_)) { // It's impossible to get from vertex to lca\n      bad[i] = true;\n    }\n \n    tie(v, len_v) = penultimate(v, lca_);\n    tie(u, len_u) = penultimate(u, lca_);\n \n    if (v != lca_ && u != lca_) { // Route isn't vertical\n      query_for_vertex[v].push_back({u, i}); // Here we store query's second vertex and id\n    }\n \n    answer[i] = len_v + len_u;\n \n    // We assume there is no direct route between v and u\n    // Overwise we'll decrement it later\n    if (v != lca_) {\n      answer[i]++;\n    }\n    if (u != lca_) {\n      answer[i]++;\n    }\n  }\n \n  dfs_calculate_answer(0);\n \n  for (int i = 0; i < q; i++) {\n    cout << (bad[i] ? -1 : answer[i]) << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "data structures",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "984",
    "index": "A",
    "title": "Game",
    "statement": "Two players play a game.\n\nInitially there are $n$ integers $a_1, a_2, \\ldots, a_n$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $n - 1$ turns are made. The first player makes the first move, then players alternate turns.\n\nThe first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.\n\nYou want to know what number will be left on the board after $n - 1$ turns if both players make optimal moves.",
    "tutorial": "First let's notice that the first player makes $\\lceil \\frac{n - 1}{2} \\rceil$ turns and the second one makes $\\lfloor \\frac{n - 1}{2} \\rfloor$. So, if numbers are $1$-indexed and sorted, first player can make the answer not more than $(n - \\lceil \\frac{n - 1}{2} \\rceil)$-th by deleting maximal number every time. The second can make it not less than $(\\lfloor \\frac{n - 1}{2} \\rfloor + 1)$-th. But $n - \\lceil \\frac{n - 1}{2} \\rceil = \\lfloor \\frac{n - 1}{2} \\rfloor + 1$, because $n - 1 = \\lceil \\frac{n - 1}{2} \\rceil + \\lfloor \\frac{n - 1}{2} \\rfloor$. So the answer has minimal and maximal values, which are the same. So the answer is $(\\lfloor \\frac{n - 1}{2} \\rfloor + 1)$-th number ascending. Asymptotics is $O(n \\cdot log(n)$ or $O(n^2)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint a[1000];\n \nint main() {\n  int n;\n  cin >> n;\n \n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n  }\n \n  sort(a, a + n);\n \n  cout << a[(n - 1) / 2];\n}",
    "tags": [
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "984",
    "index": "B",
    "title": "Minesweeper",
    "statement": "One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.\n\nAlex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?\n\nHe needs your help to check it.\n\nA Minesweeper field is a rectangle $n \\times m$, where each cell is either empty, or contains a digit from $1$ to $8$, or a bomb. The field is valid if for each cell:\n\n- if there is a digit $k$ in the cell, then exactly $k$ neighboring cells have bombs.\n- if the cell is empty, then all neighboring cells have no bombs.\n\nTwo cells are neighbors if they have a common side or a corner (i. e. a cell has at most $8$ neighboring cells).",
    "tutorial": "Let's make two-dimensional array $d[n][m]$. For each cell $i,j$ if it has bomb in it we add $1$ in $d[g][h]$ where $g,h$ is neighboring cell for $i,j$. Now $d[i][j]$ is a number of bombs in neighboring cells of $i,j$ and we can check validity of field according to the condition of the problem: If there is a number $k$ in the cell, then exacly $k$ of neighboring cells have bombs. Otherwise, if cell has no bomb, then neighboring cells have no bombs.",
    "code": "#include <iostream>\n#include <vector>\nusing std::vector;\nusing std::cin;\nusing std::cout;\nvoid setbomb(int x, int y, int n, int m, vector<vector<int>> &ans)\n{\n\tif (x > 0)\n\t{\n\t\tif (y > 0)\n\t\t\tans[x - 1][y - 1]++;\n\t\tans[x - 1][y]++;\n\t\tif (y < m - 1)\n\t\t\tans[x - 1][y + 1]++;\n\t}\n\tif (x < n - 1)\n\t{\n\t\tif (y > 0)\n\t\t\tans[x + 1][y - 1]++;\n\t\tans[x + 1][y]++;\n\t\tif (y < m - 1)\n\t\t\tans[x + 1][y + 1]++;\n\t}\n\tif (y > 0)\n\t\tans[x][y - 1]++;\n\tif (y < m - 1)\n\t\tans[x][y + 1]++;\n}\nint main(int argc, char *argv[])\n{\n\tint n, m;\n\tcin >> n >> m;\n\tvector<vector<char>> v(n, vector<char>(m));\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfor (int j = 0; j < m; j++)\n\t\t{\n\t\t\tcin >> v[i][j];\n\t\t}\n\t}\n\tvector<vector<int>> ans(n, vector<int>(m));\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < m; j++)\n\t\t{\n\t\t\tif (v[i][j] == '*')\n\t\t\t\tsetbomb(i, j, n, m, ans);\n\t\t}\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < m; j++)\n\t\t{\n\t\t\tif (v[i][j] == '.')\n\t\t\t{\n\t\t\t\tif (ans[i][j] != 0)\n\t\t\t\t{\n\t\t\t\t\tcout << \"NO\";\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (v[i][j] != '*')\n\t\t\t\tif (ans[i][j] != v[i][j] - '0')\n\t\t\t\t{\n\t\t\t\t\tcout << \"NO\";\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t}\n\tcout << \"YES\";\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "985",
    "index": "A",
    "title": "Chess Placing",
    "statement": "You are given a chessboard of size $1 × n$. It is guaranteed that \\textbf{$n$ is even}. The chessboard is painted like this: \"BWBW$...$BW\".\n\nSome cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to $\\frac{n t}{2}$.\n\nIn one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.\n\nYour task is to place all the pieces in the cells of the same color \\textbf{using the minimum number of moves} (all the pieces must occupy only the black cells or only the white cells after all the moves are made).",
    "tutorial": "Firstly let's sort our array $p$ (pay the attention that there are $\\frac{n t}{2}$ elements in this array, not $n$). Then for 0-indexed array $p$ answer will be equal to $m i n{\\Bigl(}\\sum_{i=0}^{n/2-1}|p_{i}-(i\\cdot2+1)|,\\sum_{i=0}^{n/2-1}|p_{i}-(i\\cdot2+2)|{\\Bigr)}$, where $|a - b|$ is an absolute value of difference between $a$ and $b$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\tvector<int> pos(n / 2);\n\tfor (int i = 0; i < n / 2; ++i)\n\t\tcin >> pos[i];\n\tsort(pos.begin(), pos.end());\n\t\n\tint ans1 = 0, ans2 = 0;\n\tfor (int i = 0; i < n / 2; ++i) {\n\t\tans1 += abs(pos[i] - (i * 2 + 1));\n\t\tans2 += abs(pos[i] - (i * 2 + 2));\n\t}\n\t\n\tcout << min(ans1, ans2) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "985",
    "index": "B",
    "title": "Switches and Lamps",
    "statement": "You are given $n$ switches and $m$ lamps. The $i$-th switch turns on some subset of the lamps. This information is given as the matrix $a$ consisting of $n$ rows and $m$ columns where $a_{i, j} = 1$ if the $i$-th switch turns on the $j$-th lamp and $a_{i, j} = 0$ if the $i$-th switch is not connected to the $j$-th lamp.\n\nInitially all $m$ lamps are turned off.\n\nSwitches change state only from \"off\" to \"on\". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.\n\nIt is guaranteed that if you push all $n$ switches then \\textbf{all $m$ lamps will be turned on}.\n\nYour think that you have too many switches and you would like to ignore one of them.\n\nYour task is to say if there exists such a switch that if you will ignore (not use) it but press all the other $n - 1$ switches then all the $m$ lamps will be turned on.",
    "tutorial": "Let's maintain an array $cnt$ of size $m$, where $cnt_{i}$ will be equal to the number of switches that are connected to the $i$-th lamp. Then answer will be \"YES\" if and only if there exists some switch such that for each lamp $i$ that is connected to this switch $cnt_{i} > 1$. Otherwise the answer will be \"NO\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint n, m;\n\tcin >> n >> m;\n\tvector<string> s(n);\n\tvector<int> cnt(m);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> s[i];\n\t\tfor (int j = 0; j < m; ++j)\n\t\t\tif (s[i][j] == '1') ++cnt[j];\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tbool ok = true;\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tif (s[i][j] == '1' && cnt[j] == 1)\n\t\t\t\tok = false;\n\t\t}\n\t\tif (ok) {\n\t\t\tputs(\"YES\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tputs(\"NO\");\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "985",
    "index": "C",
    "title": "Liebig's Barrels",
    "statement": "You have $m = n·k$ wooden staves. The $i$-th stave has length $a_{i}$. You have to assemble $n$ barrels consisting of $k$ staves each, you can use any $k$ staves to construct a barrel. Each stave must belong to exactly one barrel.\n\nLet volume $v_{j}$ of barrel $j$ be equal to the length of the \\textbf{minimal} stave in it.\n\nYou want to assemble exactly $n$ barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed $l$, i.e. $|v_{x} - v_{y}| ≤ l$ for any $1 ≤ x ≤ n$ and $1 ≤ y ≤ n$.\n\nPrint maximal total sum of volumes of equal enough barrels or $0$ if it's impossible to satisfy the condition above.",
    "tutorial": "At first, sort all $a_{i}$ in non-decreasing order. Let $rg$ be first position that $a_{rg} > a_{1} + l$ (if $a_{m}  \\le  a_{1} + l$, $rg = m + 1$). Then each barrel should have at least one stave from segment $[1, rg)$. So if $rg - 1 < n$ answer is $0$. Otherwise, for each $i$ from $1$ to $n$ let's take no more than $k$ smallest staves from this segment in the $i$-th barrel, but in such way, that there are at least $n - i$ staves left for next barrels.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\ntypedef long long li;\n\nint n, k, l, m;\nvector<li> a;\n\ninline bool read() {\n\tif(!(cin >> n >> k >> l))\n\t\treturn false;\n\tm = n * k;\n\ta.assign(m, 0);\n\tfore(i, 0, m)\n\t\tassert(scanf(\"%lld\", &a[i]) == 1);\n\treturn true;\n}\n\ninline void solve() {\n\tsort(a.begin(), a.end());\n\tint rg = int(upper_bound(a.begin(), a.end(), a[0] + l) - a.begin());\n\t\n\tif(rg < n) {\n\t\tputs(\"0\");\n\t\treturn;\n\t}\n\tli ans = 0;\n\t\n\tint u = 0;\n\tfore(i, 0, n) {\n\t\tans += a[u++];\n\t\t\n\t\tfore(j, 0, k - 1) {\n\t\t\tif(rg - u > n - i - 1)\n\t\t\t\tu++;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcerr << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "985",
    "index": "D",
    "title": "Sand Fortress",
    "statement": "You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered $1$ through infinity from left to right.\n\nObviously, there is not enough sand on the beach, so you brought $n$ packs of sand with you. Let height $h_{i}$ of the sand pillar on some spot $i$ be the number of sand packs you spent on it. \\textbf{You can't split a sand pack to multiple pillars, all the sand from it should go to a single one.} There is a fence of height equal to the height of pillar with $H$ sand packs to the left of the first spot and you should prevent sand from going over it.\n\nFinally you ended up with the following conditions to building the castle:\n\n- $h_{1} ≤ H$: no sand from the leftmost spot should go over the fence;\n- For any $i\\in[1;\\infty)$ $|h_{i} - h_{i + 1}| ≤ 1$: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen;\n- $\\sum_{i=1}^{\\infty}h_{i}=n$: you want to spend all the sand you brought with you.\n\nAs you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible.\n\nYour task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.",
    "tutorial": "Let's consider the optimal answer to always look like $h_{1}  \\le  h_{2}  \\le  ...  \\le  h_{k}  \\ge  h_{k + 1}  \\ge  ...$ $k$ will be the leftmost position of a pillar with maximum height. We will heavily use the fact that all integers from $1$ to $h_{k} - 1$ appear in this sequence to the right of $k$. If you are able to construct any answer, it is easy to rearrange it to this pattern: select the leftmost maximum $k$, sort $[1..k - 1]$ in non-decreasing order and $[k + 1.. \\infty )$ in non-increasing order. Sorted sequence will also be valid. Let a pyramid of height $k$ be such a valid castle that it occupies exactly $2k - 1$ consecutive spots and $1 = h_{1} < h_{2} < ... < h_{k} > h_{k + 1} > ... > h_{2k - 1} = 1$. Exactly $k^{2}$ sand packs are required to build it. At first let's solve the problem without even touching the fence. This won't always give the minimal answer but it'll help us further. Given some $k$ you can build the pyramid of height $k$ and get $n - k^{2}$ sand packs left over. This can fit in exactly $\\textstyle{\\left[\\!\\!leftfrac{n-k^{2}}{k}\\right]}$ pillars (you can place any pillar of height $ \\le  k$ next to some pillar of the same height). That way we see that $a n s(k)=2k-1+\\textstyle{\\lceil{\\frac{n-k^{2}}{k}}}\\rfloor$. This function is non-increasing, let's show that for any $k$ from $2$ to $\\lfloor{\\sqrt{n}}\\rfloor$ $ans(k) - ans(k - 1)$ is non-positive. $ans(k) - ans(k - 1)$ = $2k-1+\\lceil{\\frac{n-k^{2}}{k}}\\rceil-2\\cdot(k-1)+1-\\lceil{\\frac{n-(k-1)^{2}}{k-1}}\\rceil$ = $\\nabla_{\\frac{n}{2}}=\\frac{M_{s}(k)}{k}+\\sum_{p=1}^{\\pi_{s}(k)}\\d t=1\\d t$ = $2+\\left\\lceil{\\frac{n}{k}}\\right\\rceil-k-\\left\\lceil{\\frac{n}{k-1}}\\right\\rceil+\\left(k-1\\right)$ = $\\textstyle{{1}+{\\left[{\\frac{n}{k}}\\right]}}-{{\\left[{\\frac{n}{k-1}}\\right]}}$ = $\\lceil{\\frac{n+k}{k}}\\rceil-\\lceil{\\frac{n}{k-1}}\\rfloor$ = $\\textstyle{\\left[\\frac{(n+k)(k-1)}{k(k-1)}\\right]}-\\left[\\frac{n k}{k(k-1)}\\right]$. $\\lceil{\\frac{(n+k)(k-1)}{k(k-1)}}\\rceil\\leq\\lceil{\\frac{n k}{k(k-1)}}\\rceil$ $\\stackrel{\\longrightarrow}{\\longleftrightarrow}$ $(n + k)(k - 1)  \\le  nk + k(k - 1) - 1$ $\\stackrel{\\longrightarrow}{\\longleftrightarrow}$ $nk - n + k^{2} - k  \\le  nk + k^{2} - k - 1$ $\\stackrel{\\longrightarrow}{\\longleftrightarrow}$ $n  \\ge  1$. Now we can show that it is always optimal to push the initial pyramid to the left as far as possible, probably removing some pillars on positions less than $k$. That way the leftmost pillar will have height $h_{1} = min(k, H)$. The total number of sand packs required to build it is $k^{2}-{\\frac{h_{1}\\cdot(h_{1}-1)}{2}}$. This pattern will also include all the integers from $1$ to $k$ and will have the minimal width you can achieve. Monotonicity of this function can be proven in the similar manner. Finally, the answer can be calculated using the following algorithm: Find the maximum $k$ such that $k^{2}-{\\frac{h_{1}\\cdot(h_{1}-1)}{2}}\\leq n$, where $h_{1} = min(k, H)$. Solve the equation or just do the binary search; Output the width of resulting truncated pyramid plus the minimal number of additional pillars it will take to distribute leftover sand packs. You should also take into consideration the upper bound on $k$ to avoid multiplying huge numbers. It's about $\\sqrt{2n}$, so $64$-bit integer type will be enough for all the calculations. Overall complexity: $O(1)$ or $O(\\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\ntypedef long long li;\n\nusing namespace std;\n\nconst int INF = 2e9;\nli n, h;\n\nbool check(li maxh){\n\tli k = min(h, maxh);\n\tli cnt = maxh * maxh - k * (k - 1) / 2;\n\treturn (cnt <= n);\n}\n\nli get(li maxh){\n\tli k = min(h, maxh);\n\tli cnt = maxh * maxh - k * (k - 1) / 2;\n\tli len = (2 * maxh - 1) - (k - 1);\n\tn -= cnt;\n\treturn len + (n + maxh - 1) / maxh;\n}\n\nint main() {\n\tscanf(\"%lld%lld\", &n, &h);\n\tli l = 1, r = INF;\n\t\n\twhile (l < r - 1){\n\t\tli m = (l + r) / 2;\n\t\t\n\t\tif (check(m))\n\t\t\tl = m;\n\t\telse\n\t\t\tr = m;\n\t}\n\t\n\tprintf(\"%lld\\n\", check(r) ? get(r) : get(l));\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "985",
    "index": "E",
    "title": "Pencils and Boxes",
    "statement": "Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence $a_{1}, a_{2}, ..., a_{n}$ of $n$ integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that:\n\n- Each pencil belongs to \\textbf{exactly} one box;\n- Each non-empty box has at least $k$ pencils in it;\n- If pencils $i$ and $j$ belong to the same box, then $|a_{i} - a_{j}| ≤ d$, where $|x|$ means absolute value of $x$. Note that the opposite is optional, there can be pencils $i$ and $j$ such that $|a_{i} - a_{j}| ≤ d$ and they belong to different boxes.\n\nHelp Mishka to determine if it's possible to distribute all the pencils into boxes. Print \"YES\" if there exists such a distribution. Otherwise print \"NO\".",
    "tutorial": "At first you need to sort the sequence. Then if there exists some answer, there also exists an answer such that every box in it contains some segment of pencils. Now it's pretty standard dp approach. Let $dp_{i}$ be $1$ if it's possible to distribute the first $i$ pencils into boxes correctly, $0$ otherwise, $dp_{0} = 1$ initially. Now you can come up with straightforward $O(n^{2})$ implementation. Let's iterate over every $j\\in[0..i]$ and set $dp_{i + 1}$ to $1$ if for some $j$ $dp_{j} = 1$, $i - j + 1  \\ge  k$ and $a_{i} - a_{j}  \\le  d$. Now we should optimize it a bit. Notice that the second and the third conditions actually form some segment of indices. You need to check if there is at least one $1$ value on this segment. This can be maintained with two pointers, set, BIT, segment tree. Anything you can code to get update in point and sum/max on segment queries. Overall complexity: $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nconst int N = 500 * 1000 + 13;\n\nint f[N];\n\nvoid upd(int x){\n    for (int i = x; i < N; i |= i + 1)\n        ++f[i];\n}\n\nint sum(int x){\n    int res = 0;\n    for (int i = x; i >= 0; i = (i & (i + 1)) - 1)\n        res += f[i];\n    return res;\n}\n\nint get(int l, int r){\n\tif (l > r) return 0;\n\treturn sum(r) - sum(l - 1);\n}\n\nint main(){\n\tint n, k, dif;\n\tscanf(\"%d%d%d\", &n, &k, &dif);\n\tvector<int> a(n);\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\tsort(a.begin(), a.end());\n\t\n\tvector<int> dp(n + 1, 0);\n\t\n\tdp[0] = 1;\n\tupd(0);\n\t\n\tint l = 0;\n\tforn(i, n){\n\t\twhile (l < i && a[i] - a[l] > dif)\n\t\t\t++l;\n\t\tdp[i + 1] = (get(l, i - k + 1) >= 1);\n\t\tif (dp[i + 1]) upd(i + 1);\n\t}\n\t\n\tputs(dp[n] ? \"YES\" : \"NO\");\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "985",
    "index": "F",
    "title": "Isomorphic Strings",
    "statement": "You are given a string $s$ of length $n$ consisting of lowercase English letters.\n\nFor two given strings $s$ and $t$, say $S$ is the set of distinct characters of $s$ and $T$ is the set of distinct characters of $t$. The strings $s$ and $t$ are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) $f$ between $S$ and $T$ for which $f(s_{i}) = t_{i}$. Formally:\n\n- $f(s_{i}) = t_{i}$ for any index $i$,\n- for any character $x\\in S$ there is exactly one character $y\\in T$ that $f(x) = y$,\n- for any character $y\\in T$ there is exactly one character $x\\in S$ that $f(x) = y$.\n\nFor example, the strings \"aababc\" and \"bbcbcz\" are isomorphic. Also the strings \"aaaww\" and \"wwwaa\" are isomorphic. The following pairs of strings are not isomorphic: \"aab\" and \"bbb\", \"test\" and \"best\".\n\nYou have to handle $m$ queries characterized by three integers $x, y, len$ ($1 ≤ x, y ≤ n - len + 1$). For each query check if two substrings $s[x... x + len - 1]$ and $s[y... y + len - 1]$ are isomorphic.",
    "tutorial": "Yes, authors also implemented hashes. Note that if substrings $s$ and $t$ are isomophic, then position $pos$ of first encounter of some character $s_{i}$ in $s$ must be position of first encounter of some character $t_{j}$ in $t$. More over, if we sort all positions $pos_{i}^{s}$ for all distict characters in $s$ and sort all positions $pos_{j}^{t}$ for $t$, then $pos_{i}^{s}$ must be equal $pos_{i}^{t}$ for any $i$. This observation gives us fact, that $f(s[pos_{i}^{s}]) = t[pos_{i}^{t}]$. So, to check isomorphism of $s$ and $t$ we need check for each $i$, that positions of all encounters of character $s[pos_{i}^{s}]$ equal to posistions of all encounters of character $t[pos_{i}^{t}]$. To do that we can generate for each character boolean array with checked positions of its encounter and calculate prefix hashes on this arrays. Also we need precalculate order of first encounters $ord_{k}$ for each suffix of string $s$. To do it fast note that in transition from $ord_{k + 1}$ to $ord_{k}$ only $s_{k}$ can change its relative order. Result complexity is $O(n \\cdot A)$ with quite big constant from hashing.",
    "code": "#include <bits/stdc++.h>\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int(a.size())\n\n#define x first\n#define y second\n\nusing namespace std;\n\nconst int B = 2;\n\ntypedef array<int, B> ht;\n\nht MOD, BASE;\n\ninline int norm(int a, const int &MOD) {\n\twhile(a >= MOD)\n\t\ta -= MOD;\n\twhile(a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\ninline int mul(int a, int b, const int &MOD) {\n\treturn int(a * 1ll * b % MOD);\n}\n\ninline ht operator +(const ht &a, const ht &b) {\n\tht ans;\n\tfore(i, 0, sz(ans))\n\t\tans[i] = norm(a[i] + b[i], MOD[i]);\n\treturn ans;\n}\n\ninline ht operator -(const ht &a, const ht &b) {\n\tht ans;\n\tfore(i, 0, sz(ans))\n\t\tans[i] = norm(a[i] - b[i], MOD[i]);\n\treturn ans;\n}\n\ninline ht operator *(const ht &a, const ht &b) {\n\tht ans;\n\tfore(i, 0, sz(ans))\n\t\tans[i] = mul(a[i], b[i], MOD[i]);\n\treturn ans;\n}\n\nint CMODS[] = {int(1e9) + 7, int(1e9) + 9, int(1e9) + 21, int(1e9) + 33, int(1e9) + 87, int(1e9) + 93, int(1e9) + 97, int(1e9) + 103};\nint CBASE[] = {1009, 1013, 1019, 1021};\n\nconst int N = 200 * 1000 + 555;\n\nint n, m;\nchar s[N];\nint x[N], y[N], len[N];\n\ninline bool read() {\n\tif(!(cin >> n >> m))\n\t\treturn false;\n\tassert(scanf(\"%s\", s) == 1);\n\t\n\tfore(i, 0, m) {\n\t\tassert(scanf(\"%d%d%d\", &x[i], &y[i], &len[i]) == 3);\n\t\tx[i]--, y[i]--;\n\t}\n\treturn true;\n}\nvoid setMods() {\n\tmt19937 rnd;\n\tunsigned int seed = n;\n\tfore(i, 0, n)\n\t\tseed = (seed * 3) + s[i];\n\tfore(i, 0, m) {\n\t\tseed = (seed * 3) + x[i];\n\t\tseed = (seed * 3) + y[i];\n\t\tseed = (seed * 3) + len[i];\n\t}\n\trnd.seed(seed);\n\t\n\tset<int> mids;\n\twhile(sz(mids) < sz(MOD))\n\t\tmids.insert(rnd() % 8);\n\tvector<int> vmids(mids.begin(), mids.end());\n\tfore(i, 0, sz(MOD)) {\n\t\tMOD[i] = CMODS[vmids[i]];\n\t\tBASE[i] = CBASE[i];\n\t}\n}\n\nht pBase[N];\nht ph[27][N];\nvector<int> ord[N];\n\nht getHash(int id, int l, int r) {\n\treturn ph[id][r] - ph[id][l] * pBase[r - l];\n}\n\ninline void solve() {\n\tsetMods();\n\t\n\tpBase[0] = {1, 1};\n\tfore(i, 1, N)\n\t\tpBase[i] = pBase[i - 1] * BASE;\n\t\t\n\tfore(c, 0, 26) {\n\t\tph[c][0] = {0, 0};\n\t\tfore(i, 0, n) {\n\t\t\tint val = (s[i] == c + 'a');\n\t\t\tph[c][i + 1] = ph[c][i] * BASE + ht{val, val};\n\t\t}\n\t}\n\t\n\tvector<int> curOrd(26, 0);\n\tiota(curOrd.begin(), curOrd.end(), 0);\n\tfor(int i = n - 1; i >= 0; i--) {\n\t\tord[i] = curOrd;\n\t\tauto it = find(ord[i].begin(), ord[i].end(), int(s[i] - 'a'));\n\t\tord[i].erase(it);\n\t\tord[i].insert(ord[i].begin(), int(s[i] - 'a'));\n\t\tcurOrd = ord[i];\n\t}\n\t\n\tfore(q, 0, m) {\n\t\tint s1 = x[q], s2 = y[q];\n\t\tbool ok = true;\n\t\t\n\t\tfore(i, 0, 26) {\n\t\t\tif(getHash(ord[s1][i], s1, s1 + len[q]) != \n\t\t\t\tgetHash(ord[s2][i], s2, s2 + len[q])) {\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tputs(ok ? \"YES\" : \"NO\");\n\t}\n}\n\nint main(){\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n#endif\n\tif(read()) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "hashing",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "985",
    "index": "G",
    "title": "Team Players",
    "statement": "There are $n$ players numbered from $0$ to $n-1$ with ranks. The $i$-th player has rank $i$.\n\nPlayers can form teams: the team should consist of three players and \\textbf{no pair} of players in the team should have a conflict. The rank of the team is calculated using the following algorithm: let $i$, $j$, $k$ be the ranks of players in the team and $i < j < k$, then the rank of the team is equal to $A \\cdot i + B \\cdot j + C \\cdot k$.\n\nYou are given information about the pairs of players who \\textbf{have} a conflict. Calculate the total sum of ranks over all possible valid teams modulo $2^{64}$.",
    "tutorial": "Let's solve this task in several steps. At first, let's calculate $all$ - sum of all triples. For each player $i$ consider three cases: $j<k<i$ - there are exactly ${i}\\choose{2}$ ways to choose triple; $j<i<k$ - there are $i \\cdot (n-i-1)$ ways; $i<j<k$ - there are ${n-i-1}\\choose{2}$ ways. At second, let's calculate $sub_1$ - sum over all triples $j<k<i$ such that exists pair $(j,i)$ or $(k,i)$. To calculate it we need for each $i$ iterate over all neighbors $x<i$ of $i$. Again some cases: if $x=j<k<i$ then there are exactly $(i-j-1)$ ways to choose $k$; if $j<x=k<i$, there are $x$ ways to choose $j$. At third, let's calculate $sub_2$ - sum over all triple $j<k<i$ where exists pair $(j,k)$, but pairs $(j,i)$ and $(k,i)$ are not. $sub_2 = sub_2^0 - sub_2^1 - sub_2^2 + sub_2^{12}$. $sub_2^0$ is a sum of all triples $j<k<i$ where pair $(j,k)$ exists. It can be calculated while iterating $i$ in increasing order. $sub_2^1$ is a sum of all triples $j<k<i$ where pairs $(j,k)$ and $(j,i)$ exists. It can be calculated while iterating $(j,i)$ and asking sum on segment of adjacency list of $j$ ($O(1)$ with prefix sums for each vertex $j$). $sub_2^2$ is a sum of all triples $j<k<i$ where pairs $(j,k)$ and $(k,i)$ exists. It can be calculated while iterating $(k,i)$ and asking sum on prefix of adjacency list of $k$ (same $O(1)$). $sub_2^{12}$ is a sum of all triples $j<k<i$ where all pairs $(j,k)$, $(j,i)$ and $(k,i)$ exists. It is modification of calculating number of triangles in graph. It can be done in $O(M\\sqrt{M})$ and will be explained below. Then result $res = all - sub_1 - sub_2$. The algorithm of finding all triangles in the given graph $G$ is following: Let's call vertex heavy if $|G(v)| \\ge \\sqrt{M}$ and light otherwise. For each heavy vertex $v$ precalculate $has_v[i]$ - boolean array of adjacency of vertex $v$. It's cost $O(N \\sqrt{M})$ of memory and time but memory can be reduced by using bitsets. To calculate number of triangles $j<k<i$ let's iterate over $i$. There are two cases: if $i$ is heavy, then just iterate over all edges $(j,k)$ and check $has_i[j]$ and $has_i[k]$. This part works with $O(M\\sqrt{M})$ time since there are $O(\\sqrt{M})$ heavy vertices. if $i$ is light, then iterate over all pair $(j,k)$, where $j,k \\in G(i)$ (at first fix $k$, then iterate $j<k$). To check existence of edge $(j,k)$ consider two more cases: if $k$ is heavy, just check $has_k[j]$. It works in $O(1)$. if $k$ is light, just check in some global array $curHas$ all neighbors of $k$, check all $j$ with $curHas[j]$ and uncheck neighbors of $k$. Checking in array $curHas$ require $O(|G(k)|)$ time and will be done $O(|G(k)|)$ times. So it will be $O(\\sum{|G(v)|^2})=O(\\sqrt{M}\\sum{|G(v)|})=O(M\\sqrt{M})$ in total. Similarly, iterating pairs $j,k\\in G(i)$ works with $O(\\sum{|G(i)|^2})=O(M\\sqrt{M})$ in total. if $k$ is heavy, just check $has_k[j]$. It works in $O(1)$. if $k$ is light, just check in some global array $curHas$ all neighbors of $k$, check all $j$ with $curHas[j]$ and uncheck neighbors of $k$. Checking in array $curHas$ require $O(|G(k)|)$ time and will be done $O(|G(k)|)$ times. So it will be $O(\\sum{|G(v)|^2})=O(\\sqrt{M}\\sum{|G(v)|})=O(M\\sqrt{M})$ in total. So comlexity of algorithm and all task is $O(M\\sqrt{M})$.",
    "code": "#include <bits/stdc++.h>\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int(a.size())\n\nusing namespace std;\n\ntypedef unsigned long long uli;\n\nconst int N = 200 * 1000 + 555;\n\nint n, m;\nuli a, b, c;\nvector<int> g[N];\n\ninline bool read() {\n\tif(!(cin >> n >> m))\n\t\treturn false;\n\tassert(cin >> a >> b >> c);\n\tfore(i, 0, m) {\n\t\tint u, v;\n\t\tassert(scanf(\"%d%d\", &u, &v) == 2);\n\t\t\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\treturn true;\n}\n\nvector<uli> ps[N];\n\ninline uli getSum(int v, int l, int r) {\n\treturn ps[v][r] - ps[v][l];\n}\n\nconst int MX = 700;\nint id[N];\n\nconst int B = 1111;\nbitset<N> has[B];\nint szh = 0;\n\ninline void solve() {\n\tmemset(id, -1, sizeof id);\n\tszh = 0;\n\tfore(v, 0, n) {\n\t\tsort(g[v].begin(), g[v].end());\n\t\t\n\t\tps[v].assign(sz(g[v]) + 1, 0);\n\t\tfore(i, 0, sz(g[v]))\n\t\t\tps[v][i + 1] = ps[v][i] + g[v][i];\n\t\t\n\t\tif(sz(g[v]) >= MX) {\n\t\t\tassert(szh < B);\n\t\t\tid[v] = szh++;\n\t\t\t\n\t\t\tfor(int to : g[v])\n\t\t\t\thas[id[v]][to] = 1;\n\t\t}\n\t}\n\t\n\tuli all = 0;\n\tfore(v, 0, n) {\n\t\tuli lw = v, gr = n - v - 1;\n\t\tall += a * v * (gr * (gr - 1) / 2);\n\t\tall += b * v * (lw * gr);\n\t\tall += c * v * (lw * (lw - 1) / 2);\n\t}\n\t\n\tuli sub1 = 0;\n\tfore(v, 0, n) {\n\t\tfor(int to : g[v]) {\n\t\t\tif(to > v)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tuli cnt = to;\n\t\t\tuli sum = cnt * (cnt - 1) / 2;\n\t\t\tsub1 += a * sum + cnt * (b * to + c * v);\n\t\t\t\n\t\t\tcnt = v - to - 1;\n\t\t\tsum = (2 * to + cnt + 1) * cnt / 2;\n\t\t\tsub1 += b * sum + cnt * (a * to + c * v);\n\t\t}\n\t\t\n\t\tuli sum = 0;\n\t\tfore(i, 0, sz(g[v])) {\n\t\t\tif(g[v][i] > v)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tuli cnt = i;\n\t\t\tsub1 -= a * sum + cnt * (b * g[v][i] + c * v);\n\t\t\tsum += g[v][i];\n\t\t}\n\t}\n\tall -= sub1;\n\t\n\tuli sub2 = 0;\n\tuli cntE = 0, sumE = 0;\n\tfore(v, 0, n) {\n\t\tsub2 += sumE + cntE * c * v;\n\t\tfor(int to : g[v]) {\n\t\t\tif(to > v)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcntE++;\n\t\t\tsumE += a * to + b * v;\n\t\t}\n\t}\n\t\n\tfore(v, 0, n) {\n\t\tfor(int to : g[v]) {\n\t\t\tif(to > v)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tint pos = int(lower_bound(g[to].begin(), g[to].end(), to) - g[to].begin());\n\t\t\tsub2 -= a * getSum(to, 0, pos) + pos * (b * to + c * v);\n\t\t\t\n\t\t\tint pos2 = int(lower_bound(g[to].begin(), g[to].end(), v) - g[to].begin());\n\t\t\tsub2 -= b * getSum(to, pos, pos2) + (pos2 - pos) * (a * to + c * v);\n\t\t}\n\t}\n\t\n\tvector<char> curh(n + 5, 0);\n\tfore(v, 0, n) {\n\t\tif(id[v] == -1) {\n\t\t\tfore(i2, 0, sz(g[v])) {\n\t\t\t\tint u2 = g[v][i2];\n\t\t\t\tif(u2 > v)\n\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\tif(id[u2] != -1) {\n\t\t\t\t\tfore(i1, 0, i2) {\n\t\t\t\t\t\tint u1 = g[v][i1];\n\t\t\t\t\t\tif(has[id[u2]][u1])\n\t\t\t\t\t\t\tsub2 += a * u1 + b * u2 + c * v;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor(int to : g[u2]) {\n\t\t\t\t\t\tif(to > u2)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcurh[to] = 1;\n\t\t\t\t\t}\n\t\t\t\t\tfore(i1, 0, i2) {\n\t\t\t\t\t\tint u1 = g[v][i1];\n\t\t\t\t\t\tif(curh[u1])\n\t\t\t\t\t\t\tsub2 += a * u1 + b * u2 + c * v;\n\t\t\t\t\t}\n\t\t\t\t\tfor(int to : g[u2]) {\n\t\t\t\t\t\tif(to > u2)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcurh[to] = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfore(u2, 0, v) {\n\t\t\t\tif(!has[id[v]][u2])\n\t\t\t\t\tcontinue;\n\t\t\t\tfor(int u1 : g[u2]) {\n\t\t\t\t\tif(u1 > u2)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(has[id[v]][u1])\n\t\t\t\t\t\tsub2 += a * u1 + b * u2 + c * v;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tall -= sub2;\n\tcout << all << endl;\n}\n\nint main(){\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(10);\n\n\tif(read()) {\n\t\tsolve();\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics"
    ],
    "rating": 2700
  },
  {
    "contest_id": "986",
    "index": "A",
    "title": "Fair",
    "statement": "Some company is going to hold a fair in Byteland. There are $n$ towns in Byteland and $m$ two-way roads between towns. Of course, you can reach any town from any other town using roads.\n\nThere are $k$ types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least $s$ different types of goods. It costs $d(u,v)$ coins to bring goods from town $u$ to town $v$ where $d(u,v)$ is the length of the shortest path from $u$ to $v$. Length of a path is the number of roads in this path.\n\nThe organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of $n$ towns.",
    "tutorial": "Let's find a cost to bring a good $t$ in each town. To do this we will run BFS from all towns producing good $t$ at once. Just add all that towns in queue and run usual BFS. Complexity of BFS is $O(n+m)$, so total complexity of $k$ BFSs will be $O(k(n+m))$. Now for each town we should choose $s$ cheapest goods. We can sort them in $O(k \\log k)$, but we can use nth_element instead. It will put the $s$-th element in sorted order on place $s$, and all elements smaller will be to the left. Since we are interested only in their sum, we can just sum up first $s$ elements after calling nth_element. Another way to achieve $O(k(m+n))$ complexity is to run all $k$ BFSs simultaneously, then for each town first $s$ goods to reach it are the cheapest. Bonus: solve the problem in $O(s(m+n))$ time.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n\t#define eprintf(...) 42\n#endif\n \ntypedef long long ll;\ntypedef pair<int, int> pii;\n#define mp make_pair\n \nconst int INF = (int)1e7;\nconst int N = 100010;\nconst int K = 302;\nvector<int> g[N];\nvector<int> forCol[K];\nint q[N];\nint topQ;\nint dist[N];\nint ans[N][K];\nint n, m, k, s;\n \nint main()\n{\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tscanf(\"%d%d%d%d\", &n, &m, &k, &s);\n\tfor (int i = 0; i < n; i++) {\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\tx--;\n\t\tforCol[x].push_back(i);\n\t}\n\twhile(m--) {\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\tv--;u--;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\tfor (int c = 0; c < k; c++) {\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tdist[i] = INF;\n\t\ttopQ = 0;\n\t\tfor (int x : forCol[c]) {\n\t\t\tdist[x] = 0;\n\t\t\tq[topQ++] = x;\n\t\t}\n\t\tfor (int i = 0; i < topQ; i++) {\n\t\t\tint v = q[i];\n\t\t\tfor (int u : g[v]) {\n\t\t\t\tif (dist[u] <= dist[v] + 1) continue;\n\t\t\t\tdist[u] = dist[v] + 1;\n\t\t\t\tq[topQ++] = u;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tans[i][c] = dist[i];\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tnth_element(ans[i], ans[i] + s, ans[i] + k);\n\t\tint res = 0;\n\t\tfor (int j = 0; j < s; j++)\n\t\t\tres += ans[i][j];\n\t\tprintf(\"%d \", res);\n\t}\n\tprintf(\"\\n\");\n \n\treturn 0;\n}",
    "tags": [
      "graphs",
      "greedy",
      "number theory",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "986",
    "index": "B",
    "title": "Petr and Permutations",
    "statement": "Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $7n+1$ times instead of $3n$ times. Because it is more random, OK?!\n\nYou somehow get a test from one of these problems and now you want to know from which one.",
    "tutorial": "Each swap change the parity of permutation. $3n$ and $7n+1$ always have different parities, so the solution is just to calculate the parity of the given permutation and check if it is equal to parity of $3n$ or to parity of $7n+1$. To calculate the parity you can just calculate the number of inversions with your favorite method (Fenwick tree, Segment tree, mergesort or whatever) in $O(n \\log n)$ time. But it is easier to calculate the number of cycles in permutation in $O(n)$ time.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n\t#define eprintf(...) 42\n#endif\n \ntypedef long long ll;\ntypedef pair<int, int> pii;\n#define mp make_pair\n \nconst int N = (int)1e6 + 7;\nint n;\nint a[N];\nint ans;\n \nint main()\n{\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tscanf(\"%d\", &n);\n\tfor (int i = 0; i < n; i++) {\n\t\tscanf(\"%d\", &a[i]);\n\t\ta[i]--;\n\t}\n\tans = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (a[i] == -1) continue;\n\t\tans ^= 1;\n\t\tint x = i;\n\t\twhile(x != -1) {\n\t\t\tint y = a[x];\n\t\t\ta[x] = -1;\n\t\t\tx = y;\n\t\t}\n\t}\n\tif (ans)\n\t\tprintf(\"Um_nik\\n\");\n\telse\n\t\tprintf(\"Petr\\n\");\n \n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "986",
    "index": "C",
    "title": "AND Graph",
    "statement": "You are given a set of size $m$ with integer elements between $0$ and $2^{n}-1$ inclusive. Let's build an undirected graph on these integers in the following way: connect two integers $x$ and $y$ with an edge if and only if $x \\& y = 0$. Here $\\&$ is the bitwise AND operation. Count the number of connected components in that graph.",
    "tutorial": "Let's build directed graph on $m+2^n$ vertices. There will be two types of vertices: $(x, 1)$ is a vertex for $x$ from input and $(x, 2)$ is a vertex for all $x$ between $0$ and $2^{n}-1$. There will be edges of three classes: $(x, 1) \\rightarrow (x, 2)$ for all $x$ from input $(x, 2) \\rightarrow (x | (1 \\ll k), 2)$ for all $x$ and $k$ such that $k$-th bit of $x$ is $0$ $(\\sim x, 2) \\rightarrow (x, 1)$ for all $x$ from input. Here $\\sim x = ((2^n-1) - x)$ - the complement of $x$ Let's look at some path of form $(a, 1) \\rightarrow (x_1, 2) \\rightarrow (x_2, 2) \\rightarrow \\ldots \\rightarrow (x_k, 2) \\rightarrow (b, 1)$. The transition from $x_1$ to $x_k$ just change some $0$ bits to $1$. So, $x_1$ is a submask of $x_k$. $a$ is $x_1$ and $b$ is the complement of $x_k$. Now it is clear that $a \\& b = 0$. The opposite is also true: whenever $a \\& b = 0$, there is a path from $(a, 1)$ to $(b, 1)$. The solution is simple now: iterate over all $x$ from input, and if the vertex $(x, 1)$ is not visited yet, run a DFS from it and increase the answer by $1$. It is clear that we will run DFS exactly once for each connected component of original graph. Complexity - $O(n2^n)$",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n\t#define eprintf(...) 42\n#endif\n \ntypedef long long ll;\ntypedef pair<int, int> pii;\n#define mp make_pair\n \nconst int N = (1 << 22) + 5;\nint n, m;\nbool used[N];\nint cnt[N];\n \nvoid add(int x, int d) {\n\tint Z = x & ((1 << m) - 1);\n\tint y = x - Z;\n\tZ ^= (1 << m) - 1;\n\tfor(int z = Z; z > 0; z = (z - 1) & Z)\n\t\tcnt[y + (1 << m) - 1 - z] += d;\n\tcnt[y + (1 << m) - 1] += d;\n}\n \nvoid dfs(int x) {\n//\tcerr << \"dfs \" << x << endl;\n\tused[x] = 1;\n\tadd(x, -1);\n\tx ^= (1 << n) - 1;\n\tint Z = x & ((1 << m) - 1);\n\tint Y = x - Z;\n\tfor(int y = Y;; y = (y - 1) & Y) {\n\t\twhile (cnt[y + Z] > 0) {\n\t\t\tint z = Z;\n\t\t\tfor (int i = 0; i < m; i++) {\n\t\t\t\tif (((z >> i) & 1) && cnt[y + z ^ (1 << i)] > 0) z ^= 1 << i;\n\t\t\t}\n\t\t\tif (used[y + z]) throw;\n\t\t\tdfs(y + z);\n\t\t}\n\t\tif (y == 0) break;\n\t}\n}\n \nint main()\n{\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 0; i < (1 << n); i++)\n\t\tused[i] = 1;\n\twhile(m--) {\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\tused[x] = 0;\n\t}\n\tm = n / 2;\n\tfor (int x = 0; x < (1 << n); x++) {\n\t\tif (used[x]) continue;\n\t\tadd(x, 1);\n\t}\n\tint ans = 0;\n\tfor (int x = 0; x < (1 << n); x++) {\n\t\tif (!used[x]) {\n\t\t\tdfs(x);\n\t\t\tans++;\n\t\t}\n\t}\n\tprintf(\"%d\\n\", ans);\n \n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "986",
    "index": "D",
    "title": "Perfect Encoding",
    "statement": "You are working as an analyst in a company working on a new system for big data storage. This system will store $n$ different objects. Each object should have a unique ID.\n\nTo create the system, you choose the parameters of the system — integers $m \\ge 1$ and $b_{1}, b_{2}, \\ldots, b_{m}$. With these parameters an ID of some object in the system is an array of integers $[a_{1}, a_{2}, \\ldots, a_{m}]$ where $1 \\le a_{i} \\le b_{i}$ holds for every $1 \\le i \\le m$.\n\nDevelopers say that production costs are proportional to $\\sum_{i=1}^{m} b_{i}$. You are asked to choose parameters $m$ and $b_{i}$ so that the system will be able to assign unique IDs to $n$ different objects and production costs are minimized. Note that you don't have to use all available IDs.",
    "tutorial": "The problem asks to find integers $b_i$ such that $\\prod b_i \\ge n$ and $\\sum b_i$ is minimized. Let's suppose that in optimal solution there is $x \\ge 4$ among $b_i$. It is better to split it to $2$ and $(x-2)$: the sum remains the same and the product is increased (or stays the same). So we will use only $2$ and $3$ as our $b_i$. If there are at least three $2$ among $b_i$, we can replace them with two $3$: the sum remains the same, the product is increased. So, optimal solution looks like this: zero, one or two $2$s and some $3$s. For now let's say that we try all three possibilities for the number of $2$s. The problem now looks like \"find $\\left\\lceil \\log_{3} n \\right\\rceil$\". The trick here is that we can estimate the answer very accurately. Let's say that the length of decimal form of $n$ is $L$. Then $\\log_{3} n$ is very close to $L \\frac{\\log 10}{\\log 3}$, the difference is not greater than $3$. So it is easy to calculate the number $p$ such that $3^p < n / 4 < n < 3^{p+6}$. If we will calculate $3^p$, then we should adjust this a little bit by multiplying by $3$ a few number of times. Multiplying by $3$ can be done in linear time, comparing two numbers also in linear time. Let's now remember that we have tried all the possibilities for the number of $2$s. We will do it not beforehand, but only now, because now each option can be checked in linear time. To calculate $3^p$ we will use binary exponentiation with FFT. If the length of the result is $L$, then the running time will be $O(L \\log L + \\frac{L}{2} \\log L + \\frac{L}{4} \\log L + \\ldots) = O(L \\log L)$. To reduce the running time you should store the numbers in base $1000$, not in base $10$. This will reduce the length of the number $3$ times, and the numbers we are getting in FFT will be at most $5 \\cdot 10^{11}$ which is good enough to avoid precision issues. In the end, running time is roughly equivalent to 4 FFT calls of size $2^{19}$ which is not that big. Total complexity - $O(L \\log L)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n\t#define eprintf(...) 42\n#endif\n \ntypedef long long ll;\ntypedef pair<int, int> pii;\n#define mp make_pair\n \ntypedef complex<double> cd;\n \nconst double PI = 4 * atan(1);\n \nconst ll B = (ll)1000;\nconst int LOG = 19;\nconst int N = (1 << LOG);\nconst int NN = N + 5;\ncd w[NN];\nint rev[NN];\n \nvoid printVec(vector<ll> a) {\n\tfor (ll x : a)\n\t\teprintf(\"%lld \", x);\n\teprintf(\"\\n\");\n}\n \nvoid initFFT() {\n\tfor (int i = 0; i < N; i++)\n\t\tw[i] = cd(cos(2 * PI * i / N), sin(2 * PI * i / N));\n\trev[0] = 0;\n\tfor (int mask = 1; mask < N; mask++) {\n\t\tint k = 0;\n\t\twhile(((mask >> k) & 1) == 0) k++;\n\t\trev[mask] = rev[mask ^ (1 << k)] ^ (1 << (LOG - 1 - k));\n\t}\n}\n \ncd F[2][NN];\nvoid FFT(cd* A, int k) {\n\tint L = 1 << k;\n\tfor (int i = 0; i < L; i++)\n\t\tF[0][rev[i] >> (LOG - k)] = A[i];\n\tint t = 0, nt = 1;\n\tfor (int lvl = 0; lvl < k; lvl++) {\n\t\tint len = 1 << lvl;\n\t\tfor (int st = 0; st < L; st += (len << 1))\n\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\tcd ad = F[t][st + len + i] * w[i << (LOG - 1 - lvl)];\n\t\t\t\tF[nt][st + i] = F[t][st + i] + ad;\n\t\t\t\tF[nt][st + len + i] = F[t][st + i] - ad;\n\t\t\t}\n\t\tswap(t, nt);\n\t}\n\tfor (int i = 0; i < L; i++)\n\t\tA[i] = F[t][i];\n}\n \ncd A[NN];\n \nbool ls(vector<ll> a, vector<ll> b) {\n\tif ((int)a.size() != (int)b.size()) return (int)a.size() < (int)b.size();\n\tfor (int i = (int)a.size() - 1; i >= 0; i--) {\n\t\tif (a[i] == b[i]) continue;\n\t\treturn a[i] < b[i];\n\t}\n\treturn false;\n}\n \nvector<ll> sqr(vector<ll> a) {\n\tint L = (int)a.size();\n\tint k = 0;\n\twhile(L > (1 << k)) k++;\n\tk++;\n\tL = 1 << k;\n\tfor (int i = 0; i < L; i++)\n\t\tA[i] = 0;\n\tfor (int i = 0; i < (int)a.size(); i++)\n\t\tA[i] = a[i];\n\tFFT(A, k);\n\tfor (int i = 0; i < L; i++)\n\t\tA[i] *= A[i];\n\tFFT(A, k);\n\tvector<ll> res;\n\tres.resize(L);\n\tfor (int i = 0; i < L; i++)\n\t\tres[i] = (ll)(A[i].real() / L + 0.5);\n\treverse(res.begin() + 1, res.end());\n\tll d = 0;\n\tfor (int i = 0; i < L; i++) {\n\t\td += res[i];\n\t\tres[i] = d % B;\n\t\td /= B;\n\t}\n\twhile((int)res.size() > 1 && res.back() == 0) res.pop_back();\n\treturn res;\n}\n \nvector<ll> multBy(vector<ll> a, ll x) {\n\tll d = 0;\n\tfor (int i = 0; i < (int)a.size() || d; i++) {\n\t\tif (i >= (int)a.size()) a.push_back(0LL);\n\t\td += a[i] * x;\n\t\ta[i] = d % B;\n\t\td /= B;\n\t}\n\treturn a;\n}\n \nvector<ll> pow3(int pw) {\n\tvector<ll> res;\n\tres.push_back(1LL);\n\tint k = 0;\n\twhile(pw >= (1 << k)) k++;\n\tfor (int i = k - 1; i >= 0; i--) {\n\t\tres = sqr(res);\n\t\tif ((pw >> i) & 1)\n\t\t\tres = multBy(res, 3);\n\t}\n\treturn res;\n}\n \nchar s[3 * NN];\nvector<ll> c;\nint ANS = (int)1e9;\n \nint read() {\n\tscanf(\"%s\", s);\n\tint L = strlen(s);\n\tfor (int pos = L; pos > 0; pos -= 3) {\n\t\tll x = 0;\n\t\tfor (int i = pos - 3; i < pos; i++) {\n\t\t\tif (i < 0) continue;\n\t\t\tx = x * 10 + (ll)(s[i] - '0');\n\t\t}\n\t\tc.push_back(x);\n\t}\n\treturn L;\n}\n \nint main()\n{\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tinitFFT();\n/*\n\tvector<ll> a = pow3(59);\n\tprintVec(a);\n\treturn 0;\n*/\n \n\tint pw = (int)(read() * log(10) / log(3)) - 6;\n\tpw = max(pw, 0);\n\tvector<ll> st = pow3(pw);\n \n//\tprintVec(st);\n \n\tfor (int k = 0; k < 3; k++) {\n\t\tint curAns = pw * 3 + k * 2;\n\t\tvector<ll> cur = multBy(st, 1LL << k);\n\t\twhile(ls(cur, c)) {\n\t\t\tcurAns += 3;\n\t\t\tcur = multBy(cur, 3LL);\n\t\t}\n\t\tANS = min(ANS, curAns);\n\t}\n\tANS = max(ANS, 1);\n\tprintf(\"%d\\n\", ANS);\n \n\treturn 0;\n}",
    "tags": [
      "fft",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "986",
    "index": "E",
    "title": "Prince's Problem",
    "statement": "Let the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem.\n\nYou are given a tree with $n$ vertices.\n\nIn each vertex $v$ there is positive integer $a_{v}$.\n\nYou have to answer $q$ queries.\n\nEach query has a from $u$ $v$ $x$.\n\nYou have to calculate $\\prod_{w \\in P} gcd(x, a_{w}) \\mod (10^{9} + 7)$, where $P$ is a set of vertices on path from $u$ to $v$. In other words, you are to calculate the product of $gcd(x, a_{w})$ for all vertices $w$ on the path from $u$ to $v$. As it might be large, compute it modulo $10^9+7$. Here $gcd(s, t)$ denotes the greatest common divisor of $s$ and $t$.\n\nNote that the numbers in vertices \\textbf{do not} change after queries.\n\nI suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them.",
    "tutorial": "Let's solve the problem offline and independently for all primes, then multiply the answers. The sum of powers of all primes is $O((n+q) \\log C)$. To factorize numbers we will precalculate smallest prime divisor for all numbers using sieve. For fixed prime $p$ let's write its power $b_v$ in every vertex. Then if $p$ is in $x$ from query in power $z$, then the query become \"calculate $\\sum_{v} min(b_v, z)$\". Let's do the following. We will start with $c_v = 0$ in all vertices. Then we will iterate over $w$ - the power of $p$ - from $1$ to maximal power in queries. If $b_v \\ge w$, then increase $c_v$ by $1$. Now in all vertices $c_v = min(b_v, w)$ so to answer all queries with $z=w$ we should just take sum on path. This can be done if we will maintain $c_v$ in Fenwick tree over Euler tour of our tree (this allows to calculate sum on path to root in $O(\\log n)$ time, to get sum on arbitrary path we also need to compute LCA). The number of queries to Fenwick tree is $O((n+q) \\log C)$, so total complexity is $O((n+q) \\log C \\log n)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n\t#define eprintf(...) 42\n#endif\n \ntypedef long long ll;\ntypedef pair<int, int> pii;\n#define mp make_pair\n \nconst ll MOD = (ll)1e9 + 7;\nll mult(ll x, ll y) {\n\treturn (x * y) % MOD;\n}\n \nconst int N = 100100;\nconst int LOG = 17;\nconst int C = (int)1e7 + 10;\nconst int M = (int)1e6 + 3;\nint d[C];\nint pr[M];\nint prSz;\nvector<pii> nodesForPrime[M];\nvector<pii> queryForPrime[M];\nvector<ll> primePowers[M];\n \nvector<int> g[N];\nint n;\nint par[N][LOG];\nint h[N];\nint T1, T2;\nint t[N][3];\n \nvoid dfs(int v) {\n\tt[v][0] = T1++;\n\tfor (int u : g[v]) {\n\t\tif (h[u] != -1) continue;\n\t\th[u] = h[v] + 1;\n\t\tpar[u][0] = v;\n\t\tfor (int k = 0; k < LOG - 1; k++) {\n\t\t\tint w = par[u][k];\n\t\t\tif (w != -1)\n\t\t\t\tpar[u][k + 1] = par[w][k];\n\t\t}\n\t\tdfs(u);\n\t}\n\tt[v][1] = T1;\n\tt[v][2] = T2++;\n}\n \nint up(int v, int dh) {\n\tfor (int k = LOG - 1; k >= 0; k--) {\n\t\tif (dh < (1 << k)) continue;\n\t\tdh -= 1 << k;\n\t\tv = par[v][k];\n\t}\n\treturn v;\n}\nint LCA(int v, int u) {\n\tif (h[v] > h[u]) swap(v, u);\n\tu = up(u, h[u] - h[v]);\n\tif (v == u) return v;\n\tfor (int k = LOG - 1; k >= 0; k--) {\n\t\tif (par[v][k] != par[u][k]) {\n\t\t\tv = par[v][k];\n\t\t\tu = par[u][k];\n\t\t}\n\t}\n\treturn par[v][0];\n}\n \nint fenv[2][N];\nvoid fenvAdd(int k, int r, int dx) {\n\tfor(; r < n; r |= r + 1)\n\t\tfenv[k][r] += dx;\n}\nint fenvGet(int k, int r) {\n\tint res = 0;\n\tfor (; r >= 0; r = (r & (r + 1)) - 1)\n\t\tres += fenv[k][r];\n\treturn res;\n}\n \nint m;\nint qu[N][4];\nll ANS[N];\n \nvoid precalc() {\n\tfor (int i = 1; i < C; i++)\n\t\td[i] = -1;\n\tfor (int x = 2; x < C; x++) {\n\t\tif (d[x] != -1) continue;\n\t\tpr[prSz] = x;\n\t\tfor (int y = x; y < C; y += x)\n\t\t\tif (d[y] == -1)\n\t\t\t\td[y] = prSz;\n\t\tprimePowers[prSz].push_back(1);\n\t\tprSz++;\n\t}\n}\n \nvoid addPrimeNode(int p, int id, int pw) {\n//\teprintf(\"add prime node %d %d %d\\n\", pr[p], id, pw);\n\tnodesForPrime[p].push_back(mp(pw, id));\n\tfor (int i = 1; i <= pw; i++) {\n\t\tprimePowers[p].push_back(mult(primePowers[p].back(), pr[p]));\n\t}\n}\nvoid addPrimeQuery(int p, int id, int pw) {\n//\teprintf(\"add prime query %d %d %d\\n\", pr[p], id, pw);\n\tqueryForPrime[p].push_back(mp(pw, id));\n}\n \nvoid read() {\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i < n; i++) {\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\tv--;u--;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\tfor (int v = 0; v < n; v++) {\n\t\th[v] = -1;\n\t\tfor (int i = 0; i < LOG; i++)\n\t\t\tpar[v][i] = -1;\n\t}\n\th[0] = 0;\n\tdfs(0);\n//\teprintf(\"times:\\n\");\n//\tfor (int v = 0; v < n; v++)\n//\t\teprintf(\"%d %d %d\\n\", t[v][0], t[v][1], t[v][2]);\n\tfor (int i = 0; i < n; i++) {\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\twhile(x > 1) {\n\t\t\tint p = d[x];\n\t\t\tint pw = 0;\n\t\t\twhile(d[x] == p) {\n\t\t\t\tpw++;\n\t\t\t\tx /= pr[p];\n\t\t\t}\n\t\t\taddPrimeNode(p, i, pw);\n\t\t}\n\t}\n\tscanf(\"%d\", &m);\n\tfor (int i = 0; i < m; i++) {\n\t\tANS[i] = 1;\n\t\tint v, u, x;\n\t\tscanf(\"%d%d%d\", &v, &u, &x);\n\t\tv--;u--;\n\t\tqu[i][0] = v;\n\t\tqu[i][1] = u;\n\t\tqu[i][2] = LCA(v, u);\n\t\tqu[i][3] = par[qu[i][2]][0];\n//\t\teprintf(\"%d %d %d %d\\n\", qu[i][0], qu[i][1], qu[i][2], qu[i][3]);\n\t\twhile(x > 1) {\n\t\t\tint p = d[x];\n\t\t\tint pw = 0;\n\t\t\twhile(d[x] == p) {\n\t\t\t\tpw++;\n\t\t\t\tx /= pr[p];\n\t\t\t}\n\t\t\taddPrimeQuery(p, i, pw);\n\t\t}\n\t}\n\tfor (int i = 0; i < prSz; i++) {\n\t\tsort(nodesForPrime[i].begin(), nodesForPrime[i].end());\n\t\treverse(nodesForPrime[i].begin(), nodesForPrime[i].end());\n\t\tsort(queryForPrime[i].begin(), queryForPrime[i].end());\n\t}\n}\n \nvoid addInV(int v, int dx) {\n\tfenvAdd(0, t[v][0], dx);\n\tfenvAdd(1, t[v][2], dx);\n}\n \nint getSumV(int v) {\n\tif (v == -1) return 0;\n\treturn fenvGet(0, t[v][1] - 1) - fenvGet(1, t[v][2] - 1);\n}\n \nint main()\n{\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tprecalc();\n\tread();\n \n\tfor (int id = 0; id < m; id++) {\n\t\tint it = 0;\n\t\tint k = 0;\n\t\twhile(it < (int)queryForPrime[id].size()) {\n\t\t\tk++;\n\t\t\tfor (int i = 0; i < (int)nodesForPrime[id].size() && nodesForPrime[id][i].first >= k; i++) {\n\t\t\t\taddInV(nodesForPrime[id][i].second, 1);\n\t\t\t}\n\t\t\twhile(it < (int)queryForPrime[id].size() && queryForPrime[id][it].first == k) {\n\t\t\t\tint s = queryForPrime[id][it].second;\n\t\t\t\tit++;\n\t\t\t\tint pw = 0;\n\t\t\t\tpw += getSumV(qu[s][0]);\n\t\t\t\tpw += getSumV(qu[s][1]);\n\t\t\t\tpw -= getSumV(qu[s][2]);\n\t\t\t\tpw -= getSumV(qu[s][3]);\n\t\t\t\tANS[s] = mult(ANS[s], primePowers[id][pw]);\n\t\t\t}\n\t\t}\n\t\twhile(k > 0) {\n\t\t\tfor (int i = 0; i < (int)nodesForPrime[id].size() && nodesForPrime[id][i].first >= k; i++) {\n\t\t\t\taddInV(nodesForPrime[id][i].second, -1);\n\t\t\t}\n\t\t\tk--;\n\t\t}\n\t}\n \n\tfor (int i = 0; i < m; i++)\n\t\tprintf(\"%lld\\n\", ANS[i]);\n \n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "986",
    "index": "F",
    "title": "Oppa Funcan Style Remastered",
    "statement": "Surely you have seen insane videos by South Korean rapper PSY, such as \"Gangnam Style\", \"Gentleman\" and \"Daddy\". You might also hear that PSY has been recording video \"Oppa Funcan Style\" two years ago (unfortunately we couldn't find it on the internet). We will remind you what this hit looked like (you can find original description here):\n\nOn the ground there are $n$ platforms, which are numbered with integers from $1$ to $n$, on $i$-th platform there is a dancer with number $i$. Further, every second all the dancers standing on the platform with number $i$ jump to the platform with the number $f(i)$. The moving rule $f$ is selected in advance and is not changed throughout the clip.\n\nThe duration of the clip was $k$ seconds and the rule $f$ was chosen in such a way that after $k$ seconds all dancers were in their initial positions (i.e. the $i$-th dancer stood on the platform with the number $i$). That allowed to loop the clip and collect even more likes.\n\nPSY knows that enhanced versions of old artworks become more and more popular every day. So he decided to release a remastered-version of his video.\n\nIn his case \"enhanced version\" means even more insanity, so the number of platforms can be up to $10^{18}$! But the video director said that if some dancer stays on the same platform all the time, then the viewer will get bored and will turn off the video immediately. Therefore, for all $x$ from $1$ to $n$ $f(x) \\neq x$ must hold.\n\nBig part of classic video's success was in that looping, so in the remastered version all dancers should return to their initial positions in the end of the clip as well.\n\nPSY hasn't decided on the exact number of platforms and video duration yet, so he asks you to check if there is a good rule $f$ for different options.",
    "tutorial": "Let's understand the problem first. The rule $f(x)$ must be bijective, because otherwise some platforms will be empty in $k$ seconds. So we are looking for permutations $p$ of size $n$. Let's say that cycles of the permutation have lengths $c_1, c_2, \\ldots, c_m$. $p^k$ is an identity permutation if and only if $c_i$ divides $k$ for all $i$. Also $c_i \\ne 1$. So, we need to check if there are such numbers $c_i$ for which all these holds: $n = \\sum c_i$ $c_i \\ne 1$ $c_i$ is a divisor of $k$ It is not profitable to use composite divisors of $k$ because we can substitute each of them with any its prime divisor repeated necessary number of times. Let's say that $p_1 < p_2 < \\ldots < p_m$ - the list of all distinct prime divisors of $k$. Then the problem is essentially: Check if there are nonnegative coefficients $b_i$ such that $n = \\sum b_i \\cdot p_i$. If $m=0$ ($k=1$) answer is NO. If $m=1$, then the answer is YES if and only if $n$ is divisible by $p_1$. If $m=2$, then you have to say if there is a nonnegative solution to Diophantine equation. It can be done using extended Euclid algorithm. And if $m \\ge 3$, then $p_1 \\le k^{1/m} \\le k^{1/3} \\le 10^5$. Let's find $d(r)$ - the minimal number equal to $r$ modulo $p_1$ that can be written in form $\\sum b_i \\cdot p_i$. If we do this, the answer is obvious: YES if and only if $n \\ge d(n \\mod p_1)$. To find all the $d$ we'll build a directed graph. It's vertices are the remainders modulo $p_1$, and there is a directed edge from $x$ to $(x + p_i) \\mod p_1$ with weight $p_i$ for all $x$ and $i$. Let's see that the path from $0$ in this graph is a set of $p_i$, its weight is the sum of $p_i$ and it leads to a remainder of this sum modulo $p_1$. Therefore, $d(r)$ is shortest path from $0$ to $r$ in this graph. There are $p_1$ vertices and $p_1 \\cdot m$ edges in this graph, so dijkstra's running time is $O(mp_1 \\log p_1) = O(m k^{1/m} \\log (k^{1/m})) = O(k^{1/m} \\log k) = O(k^{1/3} \\log k)$. We also need to factorize $k$. Let's build sieve once and find all the primes up to $\\sqrt{K}$ ($K=10^{15}$). Then we can factorize numbers up to $K$ in $O(\\frac{\\sqrt{K}}{\\log K})$ just like in trivial $O(\\sqrt{K})$ algorithm but trying only prime divisors. Let's calculate complexity now. Let's say that number of all tests is $t \\le 10^4$ and number of different $k$ is $q \\le 50$. Solutions for $m=1$ and $m=2$ works in $O(1)$ and $O(\\log n)$ time, so total time is $O(t \\log n)$. Solution for $m \\ge 3$ works in $O(k^{1/3} \\log k)$, but this dijkstra should be done once for each $k$, for different $n$ we should only check one condition using calculated distances. Therefore, total time for these solutions is $O(q k^{1/3} \\log k + t)$. Also there is sieve in $O(\\sqrt{K} \\log \\log K)$ and factorization in $O(\\frac{\\sqrt{k}}{\\log k})$ $q$ times. Total complexity - $O(\\sqrt{K} \\log \\log K + q (\\frac{\\sqrt{k}}{\\log k} + k^{1/3} \\log k) + t \\log n)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n\t#define eprintf(...) 42\n#endif\n \ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef pair<ll, int> pli;\n#define mp make_pair\n \nmap<ll, vector<pli>> mapchik;\n \nconst ll INF = (ll)2e18;\n \nconst int M = (int)35e6;\nconst int PSZ = (int)3e6;\nbool p[M];\nint pr[PSZ];\nint prSz;\n \nconst int N = (int)1e5 + 10;\nbool ANS[N];\nll dist[N];\n \nll euclid(ll x, ll y, ll &k, ll &l) {\n\tif (y == 0) {\n\t\tk = 1;\n\t\tl = 0;\n\t\treturn x;\n\t}\n\tll g = euclid(y, x % y, l, k);\n\tl -= k * (x / y);\n\treturn g;\n}\n \nvector<ll> factorize(ll x) {\n\tvector<ll> res;\n\tfor (int i = 0; i < prSz; i++) {\n\t\tif (x % pr[i]) continue;\n\t\tres.push_back(pr[i]);\n\t\twhile(x % pr[i] == 0) x /= pr[i];\n\t}\n\tif (x > 1) res.push_back(x);\n\treturn res;\n}\n \nvoid solve(ll k, vector<pli> queries) {\n\tvector<ll> a = factorize(k);\n\tint n = (int)a.size();\n\tif (n == 0) {\n\t\treturn;\n\t} else if (n == 1) {\n\t\tfor (pli q : queries) {\n\t\t\tANS[q.second] = q.first % a[0] == 0;\n\t\t}\n\t\treturn;\n\t} else if (n == 2) {\n\t\tll r = 0, s = 0;\n\t\tif (euclid(a[0], a[1], r, s) != 1) throw;\n\t\ts %= a[0];\n\t\tif (s < 0) s += a[0];\n\t\tfor (pli q : queries) {\n\t\t\tll z = ((s * (q.first % a[0])) % a[0]) * a[1];\n\t\t\tANS[q.second] = z <= q.first;\n\t\t}\n\t\treturn;\n\t}\n\tint m = a[0];\n\tfor (int i = 0; i < m; i++)\n\t\tdist[i] = INF;\n\tdist[0] = 0;\n\tset<pli> setik;\n\tfor (int i = 0; i < m; i++)\n\t\tsetik.insert(mp(dist[i], i));\n\twhile(!setik.empty()) {\n\t\tint v = setik.begin()->second;\n\t\tsetik.erase(setik.begin());\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tint u = (v + a[i]) % m;\n\t\t\tll w = dist[v] + a[i];\n\t\t\tif (w >= dist[u]) continue;\n\t\t\tsetik.erase(mp(dist[u], u));\n\t\t\tdist[u] = w;\n\t\t\tsetik.insert(mp(dist[u], u));\n\t\t}\n\t}\n\tfor (pli q : queries) {\n\t\tANS[q.second] = dist[q.first % m] <= q.first;\n\t}\n}\n \nint main()\n{\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tfor (int i = 2; i < M; i++)\n\t\tp[i] = 1;\n\tfor (int x = 2; x < M; x++) {\n\t\tif (!p[x]) continue;\n\t\tpr[prSz++] = x;\n\t\tfor (int y = 2 * x; y < M; y += x)\n\t\t\tp[y] = 0;\n\t}\n \n\tint t;\n\tscanf(\"%d\", &t);\n\tfor (int i = 0; i < t; i++) {\n\t\tll n, k;\n\t\tscanf(\"%lld%lld\", &n, &k);\n\t\tmapchik[k].push_back(mp(n, i));\n\t}\n\tfor (auto it : mapchik) {\n\t\tsolve(it.first, it.second);\n\t}\n \n\tfor (int i = 0; i < t; i++)\n\t\tif (ANS[i])\n\t\t\tprintf(\"YES\\n\");\n\t\telse\n\t\t\tprintf(\"NO\\n\");\n \n\treturn 0;\n}",
    "tags": [
      "graphs",
      "math",
      "number theory",
      "shortest paths"
    ],
    "rating": 3300
  },
  {
    "contest_id": "987",
    "index": "A",
    "title": "Infinity Gauntlet",
    "statement": "You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:\n\n- the Power Gem of purple color,\n- the Time Gem of green color,\n- the Space Gem of blue color,\n- the Soul Gem of orange color,\n- the Reality Gem of red color,\n- the Mind Gem of yellow color.\n\nUsing colors of Gems you saw in the Gauntlet determine the names of \\textbf{absent} Gems.",
    "tutorial": "Just do what is written in the statement. Convenient way is to use map in C++ or dict in Python.",
    "code": "d = {\"purple\":\"Power\", \"green\":\"Time\", \"blue\":\"Space\", \"orange\":\"Soul\", \"red\":\"Reality\", \"yellow\":\"Mind\"}\ns = set()\nn = int(input())\nfor _ in range(n):\n\tw = input()\n\ts.add(w)\nprint(6 - n)\nfor (key, value) in d.items():\n\tif key not in s:\n\t\tprint(value)\n ",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "987",
    "index": "B",
    "title": "High School: Become Human",
    "statement": "Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.\n\nIt turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids.\n\nOne of the popular pranks on Vasya is to force him to compare $x^y$ with $y^x$. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers.\n\nPlease help Vasya! Write a fast program to compare $x^y$ with $y^x$ for Vasya, maybe then other androids will respect him.",
    "tutorial": "We need to compare $x^y$ with $y^x$. Let's take logarithms of both sides. Now we need to compare $y \\ln x$ with $x \\ln y$. If you will compare this numbers with appropriate epsilon, it will get AC, but let's analyze a bit more and get solution in integers. Let's divide both sides by $xy$, now we need to compare $\\frac{\\ln x}{x}$ with $\\frac{\\ln y}{y}$. That's the values of some function $f(x)=\\frac{\\ln x}{x}$ taken in two points. Let's take a closer look on this function. You can take derivative or just look at the plot at WolframAlpha. It's clear that this function have maximum at point $e$, and it is increasing on $[1,e]$ and decreasing on $[e, +\\infty)$. Considering only integer points, $f(1)=0$, $f(3)$ is maximal, $f(2)=f(4)$ (because $2^4=4^2=16$), and values in points greater than $4$ are decreasing but always positive. So, the order of $x$ from larger $f(x)$ to smaller $f(x)$ is $3, 2=4, 5, 6, \\ldots, +\\infty, 1$.",
    "code": "def main():\n\tx, y = map(int, input().split())\n\tif x == y:\n\t\tprint('=')\n\t\treturn\n\tif x == 1:\n\t\tprint('<')\n\t\treturn\n\tif y == 1:\n\t\tprint('>')\n\t\treturn\n\tif x + y == 6:\n\t\tprint('=')\n\t\treturn\n\tif x == 3:\n\t\tprint('>')\n\t\treturn\n\tif y == 3:\n\t\tprint('<')\n\t\treturn\n\tif x < y:\n\t\tprint('>')\n\telse:\n\t\tprint('<')\n \nmain()",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "987",
    "index": "C",
    "title": "Three displays",
    "statement": "It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.\n\nThere are $n$ displays placed along a road, and the $i$-th of them can display a text with font size $s_i$ only. Maria Stepanovna wants to rent such three displays with indices $i < j < k$ that the font size increases if you move along the road in a particular direction. Namely, the condition $s_i < s_j < s_k$ should be held.\n\nThe rent cost is for the $i$-th display is $c_i$. Please determine the smallest cost Maria Stepanovna should pay.",
    "tutorial": "Let's fix $j$. Now we can see that $i$ and $k$ are independent, so we can find best $i$ by iterating over all $i < j$, checking if $s_i < s_j$ holds and choosing the one with smallest $c_i$. Then do the same for $k$. There are $O(n)$ options for $j$, for each of them we will do $O(n)$ operations. Total complexity is $O(n^2)$",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n\t#define eprintf(...) 42\n#endif\n \ntypedef long long ll;\ntypedef pair<int, int> pii;\n#define mp make_pair\n \nconst int INF = (int)1e9;\nconst int N = 3222;\nint n;\nint ans = INF;\nint a[N][2];\n \nint main()\n{\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tscanf(\"%d\", &n);\n\tfor (int k = 0; k < 2; k++)\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tscanf(\"%d\", &a[i][k]);\n\tfor (int i = 0; i < n; i++) {\n\t\tint b = -1;\n\t\tint cost = a[i][1];\n\t\tfor (int j = 0; j < i; j++) {\n\t\t\tif (a[j][0] >= a[i][0]) continue;\n\t\t\tif (b == -1 || a[b][1] > a[j][1])\n\t\t\t\tb = j;\n\t\t}\n\t\tif (b == -1) continue;\n\t\tcost += a[b][1];\n\t\tb = -1;\n\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\tif (a[j][0] <= a[i][0]) continue;\n\t\t\tif (b == -1 || a[b][1] > a[j][1])\n\t\t\t\tb = j;\n\t\t}\n\t\tif (b == -1) continue;\n\t\tcost += a[b][1];\n\t\tans = min(ans, cost);\n\t}\n\tif (ans == INF)\n\t\tprintf(\"-1\\n\");\n\telse\n\t\tprintf(\"%d\\n\", ans);\n \n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "988",
    "index": "A",
    "title": "Diverse Team",
    "statement": "There are $n$ students in a school class, the rating of the $i$-th student on Codehorses is $a_i$. You have to form a team consisting of $k$ students ($1 \\le k \\le n$) such that the ratings of all team members \\textbf{are distinct}.\n\nIf it is impossible to form a suitable team, print \"NO\" (without quotes). Otherwise print \"YES\", and then print $k$ distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.",
    "tutorial": "Let's write our \"unique\" function. Keep the array of the taken elements $used$. Iterate over all elements in the array $a$ and if the current element is not used ($used[a_i] = false$) then add its index $i$ to the answer and set $used[a_i] := true$. When finished, check the number of distinct values (that is the size of answer array). If it is less than $k$, print \"NO\". Otherwise print \"YES\" and output the first $k$ elements of the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tset<int> el;\n\tvector<int> ans;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\tif (!el.count(x)) {\n\t\t\tans.push_back(i);\n\t\t\tel.insert(x);\n\t\t}\n\t}\n\t\n\tif (int(ans.size()) < k) {\n\t\tcout << \"NO\\n\";\n\t} else {\n\t\tcout << \"YES\\n\";\n\t\tfor (int i = 0; i < k; ++i)\n\t\t\tcout << ans[i] + 1 << \" \";\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "988",
    "index": "B",
    "title": "Substrings Sort",
    "statement": "You are given $n$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.\n\nString $a$ is a substring of string $b$ if it is possible to choose several consecutive letters in $b$ in such a way that they form $a$. For example, string \"for\" is contained as a substring in strings \"codeforces\", \"for\" and \"therefore\", but is not contained as a substring in strings \"four\", \"fofo\" and \"rof\".",
    "tutorial": "Firstly, sort all the strings by their lengths (if there are several strings of the same length, their order does not matter because if the answer is \"YES\" then all the strings of the same length should be equal). Then for each $i \\in [1..n - 1]$ check that $s_i$ is a substring of $s_{i + 1}$. If it doesn't hold for some $i$ then the answer is \"NO\". Otherwise the answer is \"YES\" and the sorted array is the correct order of strings.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<string> s(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tcin >> s[i];\n\t\t\n\tsort(s.begin(), s.end(), [&] (const string &s, const string &t) {\n\t\treturn s.size() < t.size();\n\t});\n\t\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tif (s[i + 1].find(s[i]) == string::npos) {\n\t\t\tcout << \"NO\\n\";\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << \"YES\\n\";\n\tfor (auto it : s)\n\t\tcout << it << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "sortings",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "988",
    "index": "C",
    "title": "Equal Sums",
    "statement": "You are given $k$ sequences of integers. The length of the $i$-th sequence equals to $n_i$.\n\nYou have to choose exactly two sequences $i$ and $j$ ($i \\ne j$) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence $i$ (its length will be equal to $n_i - 1$) equals to the sum of the changed sequence $j$ (its length will be equal to $n_j - 1$).\n\nNote that it's \\textbf{required} to remove exactly one element in each of the two chosen sequences.\n\nAssume that the sum of the empty (of the length equals $0$) sequence is $0$.",
    "tutorial": "Let's calculate the array of triples $t$. Triple $t_i = (sum_i, seq_i, el_i)$ means that the sum of the sequence $seq_i$ without the element at position $el_i$ will be equal to $sum_i$. Triples can be easily calculated in a following manner: for each sequence find its sum, then iterate over all its elements and subtract each of them one after another. Now sort array $t$ with the standard compare function. Finally the answer is \"YES\" if and only if there exist two adjacent elements with equal sums and different sequences (it is very easy to see). So if we find such a pair, then the answer will be \"YES\", otherwise the answer will be \"NO\". Time complexity of the solution is $O(\\sum\\limits_{i = 0}^{k - 1}n_i \\cdot \\log\\sum\\limits_{i = 0}^{k - 1}n_i$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint k;\n\tcin >> k;\n\tvector<pair<int, pair<int, int>>> a;\n\tfor (int i = 0; i < k; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> x(n);\n\t\tfor (int j = 0; j < n; ++j)\n\t\t\tcin >> x[j];\n\t\tint sum = accumulate(x.begin(), x.end(), 0);\n\t\tfor (int j = 0; j < n; ++j)\n\t\t\ta.push_back(make_pair(sum - x[j], make_pair(i, j)));\n\t}\n\t\n\tstable_sort(a.begin(), a.end());\n\tfor (int i = 0; i < int(a.size()) - 1; ++i) {\n\t\tif (a[i].first == a[i + 1].first && (a[i].second.first != a[i + 1].second.first)) {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tcout << a[i + 1].second.first + 1 << \" \" << a[i + 1].second.second + 1 << endl;\n\t\t\tcout << a[i].second.first + 1 << \" \" << a[i].second.second + 1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << \"NO\\n\";\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "988",
    "index": "D",
    "title": "Points and Powers of Two",
    "statement": "There are $n$ distinct points on a coordinate line, the coordinate of $i$-th point equals to $x_i$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.\n\nIn other words, you have to choose the maximum possible number of points $x_{i_1}, x_{i_2}, \\dots, x_{i_m}$ such that for each pair $x_{i_j}$, $x_{i_k}$ it is true that $|x_{i_j} - x_{i_k}| = 2^d$ where $d$ is some non-negative integer number (not necessarily the same for each pair of points).",
    "tutorial": "Firstly, let's prove that the size of the answer is not greater than $3$. Suppose that the answer equals to $4$. Let $a, b, c, d$ be coordinates of the points in the answer (and $a < b < c < d$). Let $dist(a, b) = 2^k$ and $dist(b, c) = 2^l$. Then $dist(a, c) = dist(a, b) + dist(b, c) = 2^k + 2^l = 2^m$ (because of the condition). It means that $k = l$. Conditions must hold for a triple $b, c, d$ too. Now it is easy to see that if $dist(a, b) = dist(b, c) = dist(c, d) = 2^k$ then $dist(a, d) = dist(a, b) * 3$ that is not a power of two. So the size of the answer is not greater than $3$. Firstly, let's check if the answer is $3$. Iterate over all middle elements of the answer and over all powers of two from $0$ to $30$ inclusively. Let $x_i$ be the middle element of the answer and $j$ - the current power of two. Then if there are elements $x_i - 2^j$ and $x_i + 2^j$ in the array then the answer is $3$. Now check if the answer is $2$. Do the same as in the previous solution, but now we have left point $x_i$ and right point $x_i + 2^j$. If we did not find answer of lengths $3$ or $2$ then print any element of the array. The solution above have time complexity $O(n \\cdot \\log n \\cdot \\log 10^9)$ (because of we can check if the element is in the array with some data structure in $O(\\log n)$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> x(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> x[i];\n\t}\n\t\n\tsort(x.begin(), x.end());\n\tvector<int> res = { x[0] };\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < 31; ++j) {\n\t\t\tint lx = x[i] - (1 << j);\n\t\t\tint rx = x[i] + (1 << j);\n\t\t\tbool isl = binary_search(x.begin(), x.end(), lx);\n\t\t\tbool isr = binary_search(x.begin(), x.end(), rx);\n\t\t\tif (isl && isr && int(res.size()) < 3) {\n\t\t\t\tres = { lx, x[i], rx };\n\t\t\t}\n\t\t\tif (isl && int(res.size()) < 2) {\n\t\t\t\tres = { lx, x[i] };\n\t\t\t}\n\t\t\tif (isr && int(res.size()) < 2) {\n\t\t\t\tres = { x[i], rx };\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << int(res.size()) << endl;\n\tfor (auto it : res)\n\t\tcout << it << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "988",
    "index": "E",
    "title": "Divisibility by 25",
    "statement": "You are given an integer $n$ from $1$ to $10^{18}$ without leading zeroes.\n\nIn one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, \\textbf{after each move} the number you have cannot contain any leading zeroes.\n\nWhat is the minimum number of moves you have to make to obtain a number that is divisible by $25$? Print -1 if it is impossible to obtain a number that is divisible by $25$.",
    "tutorial": "Let's iterate over all pairs of digits in the number. Let the first digit in the pair be at position $i$ and the second at position $j$. Let's place these digits to the last two positions in the number. The first greedily goes to the last position and then the second goes to the position next to that. Now the number can contain a leading zero. Find the leftmost non-zero digit and move it to the first position. Then if the current number is divisible by $25$ try to update the answer with the number of swaps. It is easy to show that the number of swaps is minimal in this algorithm. The only difference we can introduce is the number of times digit $i$, digit $j$ and the leftmost non-zero digit swap among themselves. And that is minimized. You can also notice that the order of swaps doesn't matter and you can rearrange them in such a way that no leading zero appears on any step. This solution has time complexity $O(\\log^3 n)$. You can also solve this problem with $O(\\log n)$ complexity because you have to check only four options of the two last digits ($25$, $50$, $75$, $00$). It is always optimal to choose both rightmost occurrences of the corresponding digits. You can show that even if you are required to swap the chosen ones, there will be no other pair with smaller total amount of moves.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1000 * 1000 * 1000;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tlong long n;\n\tcin >> n;\n\t\n\tstring s = to_string(n);\n\t\n\tint ans = INF;\n\t\n\tint len = s.size();\n\tfor (int i = 0; i < len; ++i) {\n\t\tfor (int j = 0; j < len; ++j) {\n\t\t\tif (i == j) continue;\n\t\t\tstring t = s;\n\t\t\tint cur = 0;\n\t\t\tfor (int k = i; k < len - 1; ++k) {\n\t\t\t\tswap(t[k], t[k + 1]);\n\t\t\t\t++cur;\n\t\t\t}\n\t\t\t\n\t\t\tfor (int k = j - (j > i); k < len - 2; ++k) {\n\t\t\t\tswap(t[k], t[k + 1]);\n\t\t\t\t++cur;\n\t\t\t}\n\t\t\t\n\t\t\tint pos = -1;\n\t\t\tfor (int k = 0; k < len; ++k) {\n\t\t\t\tif (t[k] != '0') {\n\t\t\t\t\tpos = k;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor (int k = pos; k > 0; --k) {\n\t\t\t\tswap(t[k], t[k - 1]);\n\t\t\t\t++cur;\n\t\t\t}\n\t\t\t\n\t\t\tlong long nn = atoll(t.c_str());\n\t\t\tif (nn % 25 == 0)\n\t\t\t\tans = min(ans, cur);\n\t\t}\n\t}\n\t\n\tif (ans == INF)\n\t\tans = -1;\n\t\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "988",
    "index": "F",
    "title": "Rain and Umbrellas",
    "statement": "Polycarp lives on a coordinate line at the point $x = 0$. He goes to his friend that lives at the point $x = a$. Polycarp can move only from left to right, he can pass one unit of length each second.\n\nNow it's raining, so some segments of his way are in the rain. Formally, it's raining on $n$ non-intersecting segments, the $i$-th segment which is in the rain is represented as $[l_i, r_i]$ ($0 \\le l_i < r_i \\le a$).\n\nThere are $m$ umbrellas lying on the line, the $i$-th umbrella is located at point $x_i$ ($0 \\le x_i \\le a$) and has weight $p_i$. When Polycarp begins his journey, he doesn't have any umbrellas.\n\nDuring his journey from $x = 0$ to $x = a$ Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from $x$ to $x + 1$ if a segment $[x, x + 1]$ is in the rain (i.e. if there exists some $i$ such that $l_i \\le x$ and $x + 1 \\le r_i$).\n\nThe condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.\n\nEach unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.\n\nCan Polycarp make his way from point $x = 0$ to point $x = a$? If yes, find the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.",
    "tutorial": "Any experienced contestant can easily guess that the problem can be solved with dynamic programming. Coordinates are not really large so you can precalculate the array $rain_0, rain_1, \\dots, rain_{a -1 }$, where $rain_i$ is a boolean value - $True$ if there exists some segment of rain to cover the segment between positions $i$ and $i + 1$ and $False$ otherwise. This can be done in $O(n \\cdot a)$ with the most straightforward algorithm. You can also precalculate another array $umb_0, umb_1, \\dots, umb_a$, where $umb_i$ is the index of the umbrella of minimal weight at position $i$ or $-1$ if there is no such umbrella. Now let $dp[i][j]$ be the minimal total fatigue you can take if you are holding umbrella number $j$ on the end of the walk up to position $i$. If $j = 0$ then you hold no umbrella. Initially all the values are $\\infty$ and $dp[0][0]$ is $0$. You can either hold your umbrella, drop it or pick up the best one lying there (and drop the current one if any) when going from some position $i$ to $i + 1$. So here are the transitions for these cases: $dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + weight_j)$ if $j > 0$; $dp[i + 1][0] = min(dp[i + 1][0], dp[i][j])$ if $rain[i] = False$; $dp[i + 1][umb_i] = min(dp[i + 1][umb_i], dp[i][j] + weight[umb_i])$ if $umb_i \\neq -1$. The answer is equal to $\\min\\limits_{i = 0}^{m} dp[a][i]$. If it is $\\infty$ then there is no answer. So you have $a \\cdot m$ states and all the transitions are $O(1)$. Overall complexity: $O(a \\cdot (n + m))$. There is also a solution in $O(a \\log^2 a)$ with Convex Hull Trick using Li Chao tree. You can probably even achieve $(n + m) \\log^2 (n + m)$ with some coordinate compression. Obviously this wasn't required for the problem as the constraints are small enough.",
    "code": "//#pragma comment(linker, \"/stack:200000000\")\n//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n//#pragma GCC optimize(\"unroll-loops\")\n \n#include <stdio.h>\n#include <bits/stdc++.h>\n \n#define uint unsigned int\n#define ll long long\n#define ull unsigned long long\n#define ld long double\n#define rep(i, l, r) for (int i = l; i < r; i++)\n#define repb(i, r, l) for (int i = r; i > l; i--)\n#define sz(a) (int)a.size()\n#define fi first\n#define se second\n#define mp(a, b) make_pair(a, b)\n \nusing namespace std;\n \ninline void setmin(int &x, int y) { if (y < x) x = y; }\ninline void setmax(int &x, int y) { if (y > x) x = y; }\ninline void setmin(ll &x, ll y) { if (y < x) x = y; }\ninline void setmax(ll &x, ll y) { if (y > x) x = y; }\n \nconst int N = 2001;\nconst int inf = (int)1e9 + 1;\nconst ll big = (ll)1e18 + 1;\nconst int P = 239;\nconst int MOD = (int)1e9 + 7;\nconst int MOD1 = (int)1e9 + 9;\nconst double eps = 1e-9;\nconst double pi = atan2(0, -1);\nconst int ABC = 26;\n\nstruct Line\n{\n    ll k, b;\n    Line() {}\n    Line(ll k, ll b) : k(k), b(b) {}\n    ll val(ll x) { return k * x + b; }\n};\n\nint cnt_v;\nLine tree[N * 4];\n\nvoid build(int n)\n{\n    cnt_v = 1;\n    while (cnt_v < n)\n        cnt_v <<= 1;\n    rep(i, 0, cnt_v * 2 - 1)\n        tree[i] = Line(0, inf);\n}\n\nvoid upd(int x, int lx, int rx, int l, int r, Line line)\n{\n    if (lx >= r || l >= rx)\n        return;\n    else if (lx >= l && rx <= r)\n    {\n        int m = (lx + rx) / 2;\n        if (line.val(m) < tree[x].val(m))\n            swap(tree[x], line);\n        if (rx - lx == 1)\n            return;\n        if (line.val(lx) < tree[x].val(lx))\n            upd(x * 2 + 1, lx, (lx + rx) / 2, l, r, line);\n        else\n            upd(x * 2 + 2, (lx + rx) / 2, rx, l, r, line);\n    }\n    else\n    {\n        upd(x * 2 + 1, lx, (lx + rx) / 2, l, r, line);\n        upd(x * 2 + 2, (lx + rx) / 2, rx, l, r, line);\n    }\n}\n\nll get(ll p)\n{\n    int x = p + cnt_v - 1;\n    ll res = tree[x].val(p);\n    while (x > 0)\n    {\n        x = (x - 1) / 2;\n        setmin(res, tree[x].val(p));\n    }\n    return res;\n}\n\nint add[N];\nint best[N];\n\nll dp[N];\n\nint main()\n{\n    //freopen(\"a.in\", \"r\", stdin);\n    //freopen(\"a.out\", \"w\", stdout);\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.precision(20);\n    cout << fixed;\n    //ll TL = 0.95 * CLOCKS_PER_SEC;\n    //clock_t time = clock();\n    int L, n, m;\n    cin >> L >> n >> m;\n\n    rep(i, 0, n)\n    {\n        int l, r;\n        cin >> l >> r;\n        add[l]++;\n        add[r]--;\n    }\n    rep(i, 1, L + 1)\n        add[i] += add[i - 1];\n\n    fill(best, best + L + 1, inf);\n    rep(i, 0, m)\n    {\n        int x, p;\n        cin >> x >> p;\n        setmin(best[x], p);\n    }\n\n    // dp[i] + best[i] * (j - i) = best[i] * j + (dp[i] - best[i] * i)\n    build(L + 1);\n    fill(dp, dp + L + 1, inf);\n    dp[0] = 0;\n    upd(0, 0, cnt_v, 0 + 1, cnt_v, Line(best[0], dp[0] - best[0] * 0));\n    rep(i, 1, L + 1)\n    {\n        dp[i] = get(i);\n        if (add[i - 1] == 0)\n            setmin(dp[i], dp[i - 1]);\n        upd(0, 0, cnt_v, i + 1, cnt_v, Line(best[i], dp[i] - best[i] * i));\n    }\n    cout << (dp[L] != inf ? dp[L] : -1) << \"\\n\";\n    return 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "989",
    "index": "A",
    "title": "A Blend of Springtime",
    "statement": "\\begin{quote}\nWhen the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead.\"What a pity it's already late spring,\" sighs Mino with regret, \"one more drizzling night and they'd be gone.\"\n\n\"But these blends are at their best, aren't they?\" Absorbed in the landscape, Kanno remains optimistic.\n\\end{quote}\n\nThe landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.\n\nWhen a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.\n\nYou are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.",
    "tutorial": "A cell can get its colours from at most three cells: itself and its two neighbouring cells (if they exist). In order to collect all three colours, all these three cells should contain a blossom, and their colours must be pairwise different. Therefore, the answer is \"Yes\" if and only if there are three consecutive cells containing all three letters. Implement it in any way you like.",
    "code": "puts gets.codepoints.each_cons(3).any?{|x,y,z|x*y*z==287430}?'Yes':'No'",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "989",
    "index": "B",
    "title": "A Tide of Riverscape",
    "statement": "\\begin{quote}\nWalking along a riverside, Mino silently takes a note of something.\"Time,\" Mino thinks aloud.\n\n\"What?\"\n\n\"Time and tide wait for no man,\" explains Mino. \"My name, taken from the river, always reminds me of this.\"\n\n\"And what are you recording?\"\n\n\"You see it, tide. Everything has its own period, and I think I've figured out this one,\" says Mino with confidence.\n\nDoubtfully, Kanno peeks at Mino's records.\n\\end{quote}\n\nThe records are expressed as a string $s$ of characters '0', '1' and '.', where '0' denotes a low tide, '1' denotes a high tide, and '.' denotes an unknown one (either high or low).\n\nYou are to help Mino determine whether it's possible that after replacing each '.' independently with '0' or '1', a given integer $p$ is \\textbf{not} a period of the resulting string. In case the answer is yes, please also show such a replacement to Mino.\n\nIn this problem, a positive integer $p$ is considered a period of string $s$, if for all $1 \\leq i \\leq \\lvert s \\rvert - p$, the $i$-th and $(i + p)$-th characters of $s$ are the same. Here $\\lvert s \\rvert$ is the length of $s$.",
    "tutorial": "Our very first observation is that when $p \\leq \\frac n 2$, the answer can never be \"No\". Under this case, find any dot $s_i = \\texttt{\".\"}$. At least one of $s_{i-p}$ and $s_{i+p}$ exists because $p \\leq \\frac n 2$ and $1 \\leq i \\leq n$. We want to make $s_i$ different from this character. In case this character is $\\texttt{\"0\"}$ or $\\texttt{\"1\"}$, replace the dot the other way round. In case it's a dot, replace the two dots differently with $\\texttt{\"0\"}$ and $\\texttt{\"1\"}$. After that, fill the remaining dots arbitrarily, and we obtain a valid answer. If $p \\gt \\frac n 2$, we'd like to find a dot with a similiar property. That is, $s_i = \\texttt{\".\"}$, and $s_{i-p}$ or $s_{i+p}$ exists. Go over all dots, try find one, and carry out the same operation as above. If no such dot exists, the answer is \"No\".",
    "code": "#include <algorithm>\n#include <cstdio>\n\nstatic const int MAXN = 2005;\n\nstatic int n, p;\nstatic char s[MAXN];\n\nstatic int dots_ct = 0, dots[MAXN];\n\nint main()\n{\n    scanf(\"%d%d%s\", &n, &p, s);\n\n    for (int i = 0; i < n; ++i) if (s[i] == '.') {\n        dots[dots_ct++] = i;\n        s[i] = '0';\n    }\n\n    for (int i = 1; i <= (1 << std::min(dots_ct, 19)); ++i) {\n        bool is_period = true;\n        for (int j = 0; j < n - p; ++j)\n            if (s[j] != s[j + p]) { is_period = false; break; }\n        if (!is_period) {\n            puts(s);\n            return 0;\n        }\n        for (int j = 0; j <= __builtin_ctz(i); ++j)\n            s[dots[j]] ^= 1;\n    }\n\n    puts(\"No\");\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "989",
    "index": "C",
    "title": "A Mist of Florescence",
    "statement": "\\begin{quote}\nAs the boat drifts down the river, a wood full of blossoms shows up on the riverfront.\"I've been here once,\" Mino exclaims with delight, \"it's breathtakingly amazing.\"\n\n\"What is it like?\"\n\n\"Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?\"\n\\end{quote}\n\nThere are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses.\n\nThe wood can be represented by a rectangular grid of $n$ rows and $m$ columns. In each cell of the grid, there is exactly one type of flowers.\n\nAccording to Mino, the numbers of connected components formed by each kind of flowers are $a$, $b$, $c$ and $d$ respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers.\n\nYou are to help Kanno depict such a grid of flowers, with $n$ and $m$ arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem.\n\nNote that you can choose arbitrary $n$ and $m$ under the constraints below, they are not given in the input.",
    "tutorial": "A picture is worth a thousand words. There are enormous ways to solve this problem. What's yours? Fine-tune your input and parameters, depict your woods here and share with us in the comments! (Remember to clip and scale the image, though. You can surround the image with a spoiler tag to avoid taking up too much space.) Note: in case jscolor doesn't load properly (a pop-up should appear when the colour inputs are clicked on), try refreshing once. Shoutouts to Alexander Golovanov (Golovanov399) for his grid-drawing tool, on which our utility is based!",
    "code": "#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <string>\n#include <utility>\n#include <vector>\n\nstatic const int MAXM = 50;\n\nint main()\n{\n    srand(1);\n\n    int a[4];\n    scanf(\"%d%d%d%d\", &a[0], &a[1], &a[2], &a[3]);\n\n    int M = std::max(2, std::min(MAXM, *std::max_element(a, a + 4)));\n    std::vector<std::string> g;\n\n    for (int k = 0; k < 4; ++k) {\n        int islands = a[(k + 1) % 4] - 1;\n        std::string s(M, 'A' + k);\n        std::vector<std::pair<int, int>> pos;\n\n        g.push_back(s);\n        for (int x = 0; x < (islands + (M - 2)) / (M - 1); ++x) {\n            for (int i = 0; i < 3; ++i) g.push_back(s);\n            for (int i = (x & 1); i < M - !(x & 1); ++i)\n                pos.push_back({(int)g.size() - 2 - ((i ^ x) & 1), i});\n        }\n\n        std::random_shuffle(pos.begin(), pos.end());\n        for (int i = 0; i < islands; ++i)\n            g[pos[i].first][pos[i].second] = 'A' + (k + 1) % 4;\n    }\n\n    if (g.size() <= M) {\n        printf(\"%lu %d\\n\", g.size(), M);\n        for (int i = 0; i < g.size(); ++i) puts(g[i].c_str());\n    } else {\n        printf(\"%d %lu\\n\", M, g.size());\n        for (int i = 0; i < M; ++i) {\n            for (int j = 0; j < g.size(); ++j) putchar(g[j][i]);\n            putchar('\\n');\n        }\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 1800
  },
  {
    "contest_id": "989",
    "index": "D",
    "title": "A Shade of Moonlight",
    "statement": "\\begin{quote}\nGathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river.\"To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature.\" Intonates Mino.\n\n\"See? The clouds are coming.\" Kanno gazes into the distance.\n\n\"That can't be better,\" Mino turns to Kanno.\n\\end{quote}\n\nThe sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is $0$.\n\nThere are $n$ clouds floating in the sky. Each cloud has the same length $l$. The $i$-th initially covers the range of $(x_i, x_i + l)$ (\\textbf{endpoints excluded}). Initially, it moves at a velocity of $v_i$, which equals either $1$ or $-1$.\n\nFurthermore, no pair of clouds intersect initially, that is, for all $1 \\leq i \\lt j \\leq n$, $\\lvert x_i - x_j \\rvert \\geq l$.\n\nWith a wind velocity of $w$, the velocity of the $i$-th cloud becomes $v_i + w$. That is, its coordinate increases by $v_i + w$ during each unit of time. Note that the wind can be strong and clouds can change their direction.\n\nYou are to help Mino count the number of pairs $(i, j)$ ($i < j$), such that with a proper choice of wind velocity $w$ not exceeding $w_\\mathrm{max}$ in absolute value (possibly negative and/or fractional), the $i$-th and $j$-th clouds both cover the moon at the same future moment. This $w$ doesn't need to be the same across different pairs.",
    "tutorial": "There are some ways to play around with formulae of kinematics, but here's an intuitive way. With the concept of relative motion, let's not change the velocities of clouds, but the velocity of the moon instead. Namely, under a wind speed of $w$, consider the moon to be moving at a velocity of $-w$ (seriously). This doesn't affect the relative positions of all objects. Our next insight is to represent the passage of time with a vertical $y$ axis. In this way, a cloud becomes a stripe of width $\\frac l {\\sqrt 2}$ tilted at $45^\\circ$, and the moon becomes a ray passing through the origin arbitrarily chosen above the curve $y = \\frac {\\lvert x \\rvert} {w_\\mathrm{max}}$. The diagram for the first sample, where $l = 1$ and $w_\\mathrm{max} = 2$. Square-shaped intersections of sky blue stripes denote the intersections of clouds at different moments. The moon's track can be chosen in the range painted light yellow. Now we'd like to count how many squares above the $x$ axis (because of the \"future moment\" constraint) have positive-area intersections with the yellow range. Since $w_\\mathrm{max} \\geq 1$, the tilt angle of the curve does not exceed $45^\\circ$ in either half-plane. Thus, a square has positive intersection with the range, if and only if its top corner lies strictly inside the range. For a pair of rightwards-moving cloud $u$ and leftwards-moving cloud $v$, their intersection in the diagram has a top corner of $(\\frac 1 2 (x_u + x_v + l), \\frac 1 2 (x_v - x_u + l))$. One additional constraint is $x_u < x_v$, which is a requirement for the square to be above the $x$ axis. For this point to be inside the allowed range, we need $x_v - x_u + l > \\frac {\\lvert x_u + x_v + l \\rvert} {w_\\mathrm{max}}$. Going into two cases where $x_u + x_v + l \\geq 0$ and $x_u + x_v + l < 0$ and solving linear inequalities, we get the following necessary and sufficient condition of valid pairs: According to these formulae, go over each leftwards-moving cloud $v$, and find the number of $u$'s with binary search. The overall time complexity is $O(n \\log n)$. It's recommended to calculate the fractions with integer floor-division, but... Lucky you.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <vector>\n\nstatic const int MAXN = 1e5 + 3;\nstatic const int INF32 = 0x7fffffff;\ntypedef long long int64;\n\nstatic int n, l, w;\nstatic int x[MAXN], v[MAXN];\nstatic std::vector<int> pos, neg;\n\ninline int div_floor(int64 a, int b)\n{\n    if (b == 0) return (a > 0 ? +INF32 : -INF32);\n    if (a % b < 0) a -= (b + a % b);\n    return a / b;\n}\n\nint main()\n{\n    scanf(\"%d%d%d\", &n, &l, &w);\n\n    for (int i = 0; i < n; ++i) {\n        scanf(\"%d%d\", &x[i], &v[i]);\n        (v[i] == +1 ? pos : neg).push_back(x[i]);\n    }\n    std::sort(pos.begin(), pos.end());\n    std::sort(neg.begin(), neg.end());\n\n    int64 ans = 0;\n    for (int v : neg) {\n        auto barrier = std::lower_bound(pos.begin(), pos.end(), -v - l);\n        int u_max_0 = div_floor((int64)(v + l) * (w + 1) - 1, w - 1),\n            u_max_1 = div_floor((int64)(v + l) * (w - 1) - 1, w + 1);\n        ans +=\n            (std::upper_bound(pos.begin(), barrier, u_max_0) - pos.begin()) +\n            (std::upper_bound(barrier, pos.end(), std::min(v, u_max_1)) - barrier);\n    }\n\n    printf(\"%lld\\n\", ans);\n    return 0;\n}",
    "tags": [
      "binary search",
      "geometry",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "989",
    "index": "E",
    "title": "A Trance of Nightfall",
    "statement": "\\begin{quote}\nThe cool breeze blows gently, the flowing water ripples steadily.\"Flowing and passing like this, the water isn't gone ultimately; Waxing and waning like that, the moon doesn't shrink or grow eventually.\"\n\n\"Everything is transient in a way and perennial in another.\"\n\nKanno doesn't seem to make much sense out of Mino's isolated words, but maybe it's time that they enjoy the gentle breeze and the night sky — the inexhaustible gifts from nature.\n\nGazing into the sky of stars, Kanno indulges in a night's tranquil dreams.\n\\end{quote}\n\nThere is a set $S$ of $n$ points on a coordinate plane.\n\nKanno starts from a point $P$ that can be chosen on the plane. $P$ is not added to $S$ if it doesn't belong to $S$. Then the following sequence of operations (altogether called a move) is repeated several times, in the given order:\n\n- Choose a line $l$ such that it passes through at least two elements in $S$ and passes through Kanno's current position. If there are multiple such lines, one is chosen equiprobably.\n- Move to one of the points that belong to $S$ and lie on $l$. The destination is chosen equiprobably among all possible ones, including Kanno's current position (if it does belong to $S$).\n\nThere are $q$ queries each consisting of two integers $(t_i, m_i)$. For each query, you're to help Kanno maximize the probability of the stopping position being the $t_i$-th element in $S$ after $m_i$ moves with a proper selection of $P$, and output this maximum probability. Note that according to rule 1, $P$ should belong to at least one line that passes through at least two points from $S$.",
    "tutorial": "Is this a graph theory problem? Yes. Let's consider a graph $G = (V, E)$, where there is a vertex for each point in $S$ (the terms \"vertices\" and \"points\" are used interchangeably hereafter), and an edge $(u, v)$ of weight $w$ whenever $v$ can be reached from $u$ in one move with a probability of $w$. Finding out all the lines, removing duplicates, and building the graph can be done straightforwardly in $O(n^3)$ time. Represent the graph as an adjacency matrix $A$. Now, given a fixed target vertex $t$, we'd like to calculate for each vertex $u$ the probability of reaching $t$ from $u$ after $m$ moves. Let ${f^{(m)}}_u$ be this probability. We can represent $f^{(m)}$ as an $n \\times 1$ vector. Obviously $f^{(0)} = (0, \\ldots, 0, 1, 0, \\ldots, 0)^\\mathrm{T}$, where only the $t$-th element is $1$. Here $v^\\mathrm{T}$ denotes transpose of $v$. It's not hard to see that ${f^{(m)}}_u = \\sum_{(u, v) \\in E} A_{u, v} \\cdot {f^{(m-1)}}_v$. Thus we can deduce that $f^{(m)} = A \\cdot f^{(m-1)}$. By induction, $f^{(m)} = A^m \\cdot f^{(0)}$. In this way, for each query $(t, m)$, we can calculate $f^{(m-1)}$ in order to get for each $u$ the probability of reaching $t$ in $m - 1$ steps. You may ask, why $m - 1$? It's because after the first move, the whole process can be determined by Kanno's position; but the first step is up to us to decide. To be more precise, the process, therefore the desired probability, is determined after the $l$ in the first move has been chosen. We should observe that if we select a point from which there are multiple candidates of $l$, we can always select a point on one of the candidates, making it the only candidate without decreasing the whole probability. It's because the average of a set of numbers never exceeds the largest among them. Hence, we've proved that we only need to consider cases where there is only one candidate for $l$, and such cases are always valid. For each $l$, we should calculate the average of ${f^{(m-1)}}_u$ such that the $u$-th point lies on $l$. With $f^{(m-1)}$ calculated, this should take no more than $O(n^2)$ time. Now, one last thing remains: how to calculate $f^{(m-1)}$ quickly? We utilize a trick that a multiplication of an $n \\times n$ matrix and an $n \\times 1$ vector takes $O(n^2)$ time. With $A^{2^i}$ preprocessed for all non-negative integers $i \\leq \\log_2 m$ in $O(n^3 \\log m)$ time, we can perform $O(\\log m)$ matrix-vector multiplications in order to calculate $f^{(m-1)}$ in $O(n^2 \\log m)$ time. Overall, the time complexity for the problem is $O((n + q) \\cdot n^2 \\cdot \\log m)$. If anybody is ever too lazy (:P) to do the fast-exponentiation step, setting $m' = \\min\\{m, 100\\}$ and applying $O(m)$ matrix-vector multiplications also work well with the error toleration.",
    "code": "#include <cassert>\n#include <cstdio>\n#include <algorithm>\n#include <utility>\n#include <vector>\n\nstatic const int MAXN = 202;\nstatic const int LOGM = 15;\n\nstatic int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }\n\nstruct point {\n    int x, y;\n    point(int x = 0, int y = 0) : x(x), y(y) { }\n};\n\nstruct line {\n    // ax + by + c = 0\n    int a, b, c;\n\n    line() : a(0), b(0), c(0) { }\n    line(const point &p, const point &q)\n        : a(p.y - q.y)\n        , b(q.x - p.x)\n        , c(q.y * p.x - q.x * p.y)\n    {\n        int g = gcd(gcd(a, b), c);\n        if (g != 1) { a /= g; b /= g; c /= g; }\n        if (a < 0) { a = -a; b = -b; c = -c; }\n    }\n\n    inline bool contains(const point &p) {\n        return a * p.x + b * p.y + c == 0;\n    }\n\n    // For sorting & duplicate removing\n    inline bool operator < (const line &other) const {\n        return a != other.a ? a < other.a :\n            b != other.b ? b < other.b : c < other.c;\n    }\n    inline bool operator == (const line &other) const {\n        return a == other.a && b == other.b && c == other.c;\n    }\n};\n\nstruct mat {\n    static const int N = ::MAXN;\n    int sz;\n    double a[N][N];\n\n    mat(int sz = N, int id = 0) : sz(sz) {\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < N; ++j)\n                a[i][j] = (i == j ? id : 0);\n    }\n\n    inline mat operator * (const mat &other) {\n        assert(other.sz == this->sz);\n        mat ret(sz, 0);\n        for (int i = 0; i < sz; ++i)\n            for (int k = 0; k < sz; ++k)\n                for (int j = 0; j < sz; ++j)\n                    ret.a[i][j] += this->a[i][k] * other.a[k][j];\n        return ret;\n    }\n\n    inline std::vector<double> operator * (const std::vector<double> &u) {\n        assert(u.size() == this->sz);\n        std::vector<double> v(sz);\n        for (int i = 0; i < sz; ++i)\n            for (int j = 0; j < sz; ++j)\n                v[i] += a[i][j] * u[j];\n        return v;\n    }\n};\n\nstatic int n, q;\nstatic point p[MAXN];\n\nstatic line l[MAXN * MAXN / 2];\n// Lists of lines that pass through points\nstatic std::vector<int> pl[MAXN];\n// Lists of points that lie on lines\nstatic std::vector<int> lp[MAXN * MAXN / 2];\n\nstatic mat A, Ap[LOGM];\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) scanf(\"%d%d\", &p[i].x, &p[i].y);\n\n    int l_num = 0;\n    for (int i = 0; i < n; ++i)\n        for (int j = i + 1; j < n; ++j)\n            l[l_num++] = line(p[i], p[j]);\n    std::sort(l, l + l_num);\n    l_num = std::unique(l, l + l_num) - &l[0];\n\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < l_num; ++j)\n            if (l[j].contains(p[i])) {\n                pl[i].push_back(j);\n                lp[j].push_back(i);\n            }\n\n    A = mat(n, 0);\n    for (int i = 0; i < n; ++i) {\n        for (int j : pl[i])\n            for (int k : lp[j])\n                A.a[i][k] += 1.0L / (pl[i].size() * lp[j].size());\n    }\n\n    Ap[0] = A;\n    for (int i = 1; i < LOGM; ++i) Ap[i] = Ap[i - 1] * Ap[i - 1];\n\n    scanf(\"%d\", &q);\n    std::vector<double> u(n);\n    for (int i = 0, t, m; i < q; ++i) {\n        scanf(\"%d%d\", &t, &m); --t;\n\n        std::fill(u.begin(), u.end(), 0);\n        u[t] = 1.0;\n        for (int j = 0; j < LOGM; ++j)\n            if ((m - 1) & (1 << j)) u = Ap[j] * u;\n\n        double max = -1.0;\n        for (int j = 0; j < l_num; ++j) {\n            double cur = 0.0;\n            for (int k : lp[j]) cur += u[k];\n            cur /= lp[j].size();\n            max = std::max(max, cur);\n        }\n        printf(\"%.12lf\\n\", (double)max);\n    }\n\n    return 0;\n}",
    "tags": [
      "dp",
      "geometry",
      "matrices",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "990",
    "index": "A",
    "title": "Commentary Boxes",
    "statement": "Berland Football Cup starts really soon! Commentators from all over the world come to the event.\n\nOrganizers have already built $n$ commentary boxes. $m$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.\n\nIf $n$ is not divisible by $m$, it is impossible to distribute the boxes to the delegations at the moment.\n\nOrganizers can build a new commentary box paying $a$ burles and demolish a commentary box paying $b$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.\n\nWhat is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $m$)?",
    "tutorial": "Notice that you need to check just two numbers: the closest one less or equal to $n$ and the closest one greater than $n$. Distances to them are $(n \\mod m)$ and $(m - (n \\mod m))$ respectively. Now you should multiply the first result by $b$, the second result by $a$ and compare the products. Overall complexity: $O(1)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for(int i = 0; i < int(n); i++)\n \nusing namespace std;\n\nint main() {\n\tlong long n, m;\n\tint a, b;\n\t\n\tcin >> n >> m >> a >> b;\n\tcout << min(n % m * b, (m - n % m) * a) << endl;\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "990",
    "index": "B",
    "title": "Micro-World",
    "statement": "You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.\n\nYou know that you have $n$ bacteria in the Petri dish and size of the $i$-th bacteria is $a_i$. Also you know intergalactic positive integer constant $K$.\n\nThe $i$-th bacteria can swallow the $j$-th bacteria if and only if $a_i > a_j$ and $a_i \\le a_j + K$. The $j$-th bacteria disappear, but the $i$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $i$ can swallow any bacteria $j$ if $a_i > a_j$ and $a_i \\le a_j + K$. The swallow operations go one after another.\n\nFor example, the sequence of bacteria sizes $a=[101, 53, 42, 102, 101, 55, 54]$ and $K=1$. The one of possible sequences of swallows is: $[101, 53, 42, 102, \\underline{101}, 55, 54]$ $\\to$ $[101, \\underline{53}, 42, 102, 55, 54]$ $\\to$ $[\\underline{101}, 42, 102, 55, 54]$ $\\to$ $[42, 102, 55, \\underline{54}]$ $\\to$ $[42, 102, 55]$. In total there are $3$ bacteria remained in the Petri dish.\n\nSince you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.",
    "tutorial": "It can be proved that the optimal answer equals to a number of bacteria which can't be eaten by any other bacteria. So for each bacteria $i$ you need to check existence of any bacteria $j$ satisfying condition $a_i < a_j \\le a_i + K$. There plenty of ways to check this condition. One of them is to sort array $a$ and for each $i$ find minimal $a_j > a_i$ with upper_bound or with two-pointers technique. Or you can use the fact that $a_i \\le 10^6$ and build solution around it. Result complexity is $O(n \\log{n})$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 555;\nint n, k, a[N];\n\ninline bool read() {\n\tif(!(cin >> n >> k))\n\t\treturn false;\n\tfor(int i = 0; i < n; i++)\n\t\tassert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\ninline void solve() {\n\tsort(a, a + n);\n\ta[n++] = int(2e9);\n\t\n\tint ans = 0, u = 0;\n\tfor(int i = 0; i < n - 1; i++) {\n\t\twhile(u < n && a[i] == a[u])\n\t\t\tu++;\n\t\tif(a[u] - a[i] > k)\n\t\t\tans++;\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\n\tif(read()) {\n\t\tsolve();\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "990",
    "index": "C",
    "title": "Bracket Sequences Concatenation Problem",
    "statement": "A bracket sequence is a string containing only characters \"(\" and \")\".\n\nA regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()()\", \"(())\" are regular (the resulting expressions are: \"(1)+(1)\", \"((1+1)+1)\"), and \")(\" and \"(\" are not.\n\nYou are given $n$ bracket sequences $s_1, s_2, \\dots , s_n$. Calculate the number of pairs $i, j \\, (1 \\le i, j \\le n)$ such that the bracket sequence $s_i + s_j$ is a regular bracket sequence. Operation $+$ means concatenation i.e. \"()(\" + \")()\" = \"()()()\".\n\nIf $s_i + s_j$ and $s_j + s_i$ are regular bracket sequences and $i \\ne j$, then both pairs $(i, j)$ and $(j, i)$ must be counted in the answer. Also, if $s_i + s_i$ is a regular bracket sequence, the pair $(i, i)$ must be counted in the answer.",
    "tutorial": "Let $f(s)$ be the mirror reflection of the string $s$. For example: $f$(\"((\") = \"))\", $f$(\"))(\") = \")((\", $f$(\"()\") = \"()\". Let string be good if it does not have a prefix, which have more closing brackets than opening ones. For example, \"((\", \"(())(\", \"()()\" are good, and \"())\", \")((\", \"()())\" are not. The balance $bal(s)$ of the string $s$ is the difference between number of opening and closing brackets in $s$. For example, $bal$(\"(()\") = 1, $bal$(\"()\") = 0. Let $cnt[x]$ be the number of good strings with a balance $x$. The answer to the problem is $\\sum\\limits_{s,\\ where\\ f(s)\\ is\\ good} cnt [bal(f(s))]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 7;\n\nint n;\nstring s[N];\nchar buf[N];\nint cnt[N];\n\nint getBalance(string &s){\n\tint bal = 0;\n\tfor(int i = 0; i < s.size(); ++i){\n\t\tif(s[i] == '(')\n\t\t\t++bal;\n\t\telse\n\t\t\t--bal;\n\t\t\n\t\tif(bal < 0)\n\t\t\treturn -1;\n\t}\n\t\n\treturn bal;\n}\n\nstring rev(string &s){\n\tstring revs = s;\n\treverse(revs.begin(), revs.end());\n\tfor(int i = 0; i < revs.size(); ++i)\n\t\tif(revs[i] == '(')\n\t\t\trevs[i] = ')';\n\t\telse\n\t\t\trevs[i] = '(';\n\t\t\n\treturn revs;\n}\n\nint main(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; ++i){\n\t\tscanf(\"%s\", buf);\n\t\ts[i] = buf;\n\t}\n\n\tfor(int i = 0; i < n; ++i){\n\t\tint bal = getBalance(s[i]);\n\t\tif(bal != -1)\n\t\t\t++cnt[bal];\n\t}\n\t\n\tlong long res = 0;\t\n\tfor(int i = 0; i < n; ++i){\n\t\ts[i] = rev(s[i]);\n\t\tint bal = getBalance(s[i]);\n\t\tif(bal != -1)\n\t\t\tres += cnt[bal];\n\t}\n\t\n\tprintf(\"%I64d\\n\", res);\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "990",
    "index": "D",
    "title": "Graph And Its Complement",
    "statement": "Given three numbers $n, a, b$. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to $a$, and the number of components in its complement is $b$. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.\n\nIn an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.\n\nThe adjacency matrix of an undirected graph is a square matrix of size $n$ consisting only of \"0\" and \"1\", where $n$ is the number of vertices of the graph and the $i$-th row and the $i$-th column correspond to the $i$-th vertex of the graph. The cell $(i,j)$ of the adjacency matrix contains $1$ if and only if the $i$-th and $j$-th vertices in the graph are connected by an edge.\n\nA connected component is a set of vertices $X$ such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to $X$ violates this rule.\n\nThe complement or inverse of a graph $G$ is a graph $H$ on the same vertices such that two distinct vertices of $H$ are adjacent if and only if they are not adjacent in $G$.",
    "tutorial": "Let's prove that if $a > 1$, then $b = 1$. Let $G$ be the original graph, and $H$ - the complement of the graph $G$. Let's look at each pair of vertices $(u, v)$. If $u$ and $v$ belong to different components of the graph $G$, then there is an edge between them in the graph $H$. Otherwise, $u$ and $v$ belong to the same component of the graph $G$, but since $G$ has more than one component, there is vertex $x$ in other component of $G$, and there are edges $\\{u,x\\}$ and $\\{v, x\\}$ in $H$. That's why, there is a connected path for any pair of vertices $(u, v)$, and the graph $H$ is connected. Similarly, the case $b > 1$ is proved. So, if $min(a, b) > 1$, then the answer is \"NO\". Otherwise, $min(a, b) = 1$. Consider the case where $b = 1$ (if $b > a$, we can swap $a$ and $b$, and output complement of the constructed graph). To have $a$ components in the graph $G$, it is enough to connect the vertex $1$ with the vertex $2$, the vertex $2$ with the vertex $3$, $\\cdots$, the vertex $n - a$ with the vertex $n - a + 1$. A particular cases are the tests $n = 2, a = 1, b = 1$ and $n = 3, a = 1, b = 1$. There is no suitable graph for them.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(1e3) + 7;\n\nint n, a, b;\nbool mat[N][N];\n\nint main(){\n\tscanf(\"%d %d %d\", &n, &a, &b);\n\n\tif(min(a, b) > 1){\n\t\tputs(\"NO\");\n\t\treturn 0;\n\t}\n\t\n\tif(a == 1 && b == 1){\n\t\tif(n == 2 || n == 3){\n\t\t\tputs(\"NO\");\n\t\t\treturn 0;\n\t\t}\n\t\tputs(\"YES\");\n\t\tfor(int i = 1; i < n; ++i)\n\t\t\tmat[i][i - 1] = mat[i - 1][i] = true;\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tfor(int j = 0; j < n; ++j)\n\t\t\t\tprintf(\"%c\", '0' + mat[i][j]);\n\t\t\tputs(\"\");\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tbool x = false;\n\tif(a == 1){\n\t\tswap(a, b);\n\t\tx = true;\n\t}\n\tfor(int i = n - a; i > 0; --i)\n\t\tmat[i][i - 1] = mat[i - 1][i] = true;\n\tputs(\"YES\");\n\tfor(int i = 0; i < n; ++i){\n\t\t\tfor(int j = 0; j < n; ++j)\n\t\t\t\tprintf(\"%c\", '0' + ((x ^ mat[i][j]) && (i != j)));\n\t\t\tputs(\"\");\n\t\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "990",
    "index": "E",
    "title": "Post Lamps",
    "statement": "Adilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has $n$ positions to install lamps, they correspond to the integer numbers from $0$ to $n - 1$ on the OX axis. However, some positions are blocked and no post lamp can be placed there.\n\nThere are post lamps of different types which differ only by their power. When placed in position $x$, post lamp of power $l$ illuminates the segment $[x; x + l]$. The power of each post lamp is always a positive integer number.\n\nThe post lamp shop provides an infinite amount of lamps of each type from power $1$ to power $k$. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power $l$ cost $a_l$ each.\n\nWhat is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment $[0; n]$ of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power $3$ in position $n - 1$ (even though its illumination zone doesn't completely belong to segment $[0; n]$).",
    "tutorial": "Let's start with learning how to place lamps of fixed power to cover the segment with the minimal number of them. The following greedy strategy works: find the rightmost non-blocked position that is covered by lamps and place lamp there until either everything is covered or rightmost free position is to the left of the last placed lamp. Initially you only consider $0$ to be covered. Function $f(i)$ - the minimal number of post lamps to cover segment $[0; i]$ is clearly monotonous, thus you want to update states as early as possible. Okay, now you iterate over all $l \\in [1; k]$ and update the answer with the results multiplied by cost. Now, why will this work fast? You obviously precalculate the rightmost free position for each prefix segment. If there are any free positions to the right of last placed lamp then the rightmost of them will always be the rightmost for the entire prefix segment. Finally, any two consecutive iterations of the algorithm will either move you by $k + 1$ positions or return -1. This can be easily proven by contradiction. Overall complexity: $O(n \\cdot \\log n)$, as you do about $\\frac n l$ steps for each $l$ and that is a common series sum.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int INF = 1e9;\nconst long long INF64 = 1e18;\nconst int N = 1000 * 1000 + 13;\n\nint n, m, k;\nbool pos[N];\nint lst[N], s[N], a[N];\n\nint get(int l){\n\tint r = 0, i = -1, res = 0;\n\twhile (r < n){\n\t\tif (lst[r] <= i)\n\t\t\treturn INF;\n\t\ti = lst[r];\n\t\tr = lst[r] + l;\n\t\t++res;\n\t}\n\treturn res;\n}\n\nint main() {\n\tscanf(\"%d%d%d\", &n, &m, &k);\n\tforn(i, m) scanf(\"%d\", &s[i]);\n\tforn(i, k) scanf(\"%d\", &a[i]);\n\tforn(i, n) pos[i] = true;\n\tforn(i, m) pos[s[i]] = false;\n\tforn(i, n){\n\t\tif (pos[i])\n\t\t\tlst[i] = i;\n\t\telse if (i)\n\t\t\tlst[i] = lst[i - 1];\n\t\telse\n\t\t\tlst[i] = -1;\n\t}\n\tlong long ans = INF64;\n\tforn(i, k){\n\t\tlong long t = get(i + 1);\n\t\tif (t != INF)\n\t\t\tans = min(ans, a[i] * t);\n\t}\n\tprintf(\"%lld\\n\", ans == INF64 ? -1 : ans);\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "990",
    "index": "F",
    "title": "Flow Control",
    "statement": "You have to handle a very complex water distribution system. The system consists of $n$ junctions and $m$ pipes, $i$-th pipe connects junctions $x_i$ and $y_i$.\n\nThe only thing you can do is adjusting the pipes. You have to choose $m$ integer numbers $f_1$, $f_2$, ..., $f_m$ and use them as pipe settings. $i$-th pipe will distribute $f_i$ units of water per second from junction $x_i$ to junction $y_i$ (if $f_i$ is negative, then the pipe will distribute $|f_i|$ units of water per second from junction $y_i$ to junction $x_i$). It is allowed to set $f_i$ to any integer from $-2 \\cdot 10^9$ to $2 \\cdot 10^9$.\n\nIn order for the system to work properly, there are some constraints: for every $i \\in [1, n]$, $i$-th junction has a number $s_i$ associated with it meaning that the difference between incoming and outcoming flow for $i$-th junction must be \\textbf{exactly} $s_i$ (if $s_i$ is not negative, then $i$-th junction must receive $s_i$ units of water per second; if it is negative, then $i$-th junction must transfer $|s_i|$ units of water per second to other junctions).\n\nCan you choose the integers $f_1$, $f_2$, ..., $f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied?",
    "tutorial": "The answer is \"Impossible\" if and only if the sum of values is not equal to $0$. Writing some number on edge does not change the total sum and the goal of the problem is to make $0$ in each vertex, thus getting $0$ in total. The algorithm is simple: you get an arbitrary spanning tree (with dfs or dsu), output the difference between sums of values of subtrees (can be calculated with dfs) for edges in this tree and $0$ for the rest of edges. Let's take an arbitrary correct answer. If is has some cycle in graph of edges with non-zero numbers on them, then you can remove it. For example, select any edge on it and subtract the number on it from all the edges of the cycle. This doesn't break the correctness of the answer, as you change both in and out flows for each vertex by the same value. Now that edge has $0$. This way, any answer can be transformed to tree. And for any edge on tree we want to tranfer excess water units from the larger subtree to the smaller. Overall complexity: $O(n + m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nmt19937 rnd(time(NULL));\n\nconst int N = 1'000'013;\n\nint n, m;\npair<int, int> e[N];\nint a[N], rk[N];\nlong long sum[N], ans[N];\n\nint p[N];\n\nint getP(int a){\n\treturn (a == p[a] ? a : p[a] = getP(p[a]));\n}\n\nbool merge(int a, int b){\n\ta = getP(a);\n\tb = getP(b);\n\tif (a == b) return false;\n\tif (rk[a] > rk[b]) swap(a, b);\n\tp[a] = b;\n\trk[b] += rk[a];\n\treturn true;\n}\n\nbool used[N];\nvector<int> g[N];\nint h[N];\n\nvoid dfs(int v, int p){\n\tsum[v] = a[v];\n\tfor (auto u : g[v]){\n\t\tif (u != p){\n\t\t\th[u] = h[v] + 1;\n\t\t\tdfs(u, v);\n\t\t\tsum[v] += sum[u];\n\t\t}\n\t}\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tforn(i, n) p[i] = i, rk[i] = 1;\n\tscanf(\"%d\", &m);\n\tforn(i, m){\n\t\tint &v = e[i].first;\n\t\tint &u = e[i].second;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tif (merge(v, u)){\n\t\t\tg[v].push_back(u);\n\t\t\tg[u].push_back(v);\n\t\t\tused[i] = true;\n\t\t}\n\t}\n\t\n\tlong long tot = 0;\n\tforn(i, n) tot += a[i];\n\tif (tot != 0){\n\t\tputs(\"Impossible\");\n\t\treturn 0;\n\t}\n\t\n\tdfs(0, -1);\n\t\n\tputs(\"Possible\");\n\tforn(i, m){\n\t\tif (used[i]){\n\t\t\tint v = e[i].first, u = e[i].second;\n\t\t\tif (h[v] < h[u])\n\t\t\t\tans[i] = sum[u];\n\t\t\telse\n\t\t\t\tans[i] = -sum[v];\n\t\t}\n\t\tprintf(\"%lld\\n\", ans[i]);\n\t}\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "990",
    "index": "G",
    "title": "GCD Counting",
    "statement": "You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.\n\nLet's denote the function $g(x, y)$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $x$ to vertex $y$ (including these two vertices).\n\nFor every integer from $1$ to $2 \\cdot 10^5$ you have to count the number of pairs $(x, y)$ $(1 \\le x \\le y \\le n)$ such that $g(x, y)$ is equal to this number.",
    "tutorial": "Firstly, for every $i \\in [1, 2 \\cdot 10^5]$ we can calculate the number of paths such that $g(x, y)$ is divisible by $i$. We can do it as follows: generate all divisors of numbers $a_i$ (numbers not exceeding $2 \\cdot 10^5$ have at most $160$ divisors, so this will be fast enough), and then for every $i \\in [1, 2 \\cdot 10^5]$ analyze the graph containing the vertices that have $i$ as its divisor. Each component of this graph gives us $\\frac{k(k + 1)}{2}$ paths (if its size is $k$), and this is the only formula we need to calculate the number of paths where $g(x, y)$ is divisible by $i$ (let this be $h(i)$). How can we get the answer if we know the values of $h(i)$? We can use inclusion-exclusion with Mobius function, for example, to prove that $ans(1) = \\sum \\limits_{i = 1}^{2 \\cdot 10^5} \\mu(i) h(i)$; and then if we want to apply the same technique for finding $ans(x)$ with any possible $x$, we could divide all numbers $a_i$ by $x$ and do the same thing. But it might be too slow, so it's better to rewrite this formula as $ans(x) = \\sum \\limits_{i = 1}^{\\lfloor \\frac{2 \\cdot 10^5}{x} \\rfloor} \\mu(i) h(xi)$, because we will do exactly the same when dividing all numbers by $x$. In fact, most contestants have written a much easier version of this solution, so this might be a bit too complicated. This problem can also be solved with centroid decomposition.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream &out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\n\ntemplate<class A> ostream& operator <<(ostream &out, const vector<A> &v) {\n\tout << \"[\";\n\tfor(auto &e : v)\n\t\tout << e << \", \";\n\treturn out << \"]\";\n}\n\nconst int N = 1000 * 1000 + 555;\nconst int LOGN = 21;\nint mind[N];\nint pw[LOGN][N];\n\nint n, a[N];\nvector<int> g[N];\nli res[N];\n\nbool gen() {\n\tmt19937 rnd(42);\n\tn = 200 * 1000;\n\tfore(i, 0, n)\n\t\ta[i] = 831600;\n\tfore(i, 1, n) {\n\t\tint u = rnd() % i, v = i;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\treturn true;\n}\n\ninline bool read() {\n//\treturn gen();\n\tif(!(cin >> n))\n\t\treturn false;\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%d\", &a[i]) == 1);\n\tfore(i, 0, n - 1) {\n\t\tint u, v;\n\t\tassert(scanf(\"%d%d\", &u, &v) == 2);\n\t\tu--, v--;\n\t\t\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\treturn true;\n}\n\nvector<pt> dv[N];\n\ninline int gcd(int a, int b) {\n\tint ans = 1;\n\tunsigned int u = 0, v = 0;\n\twhile(u < dv[a].size() && v < dv[b].size()) {\n\t\tif(dv[a][u].x < dv[b][v].x)\n\t\t\tu++;\n\t\telse if(dv[a][u].x > dv[b][v].x)\n\t\t\tv++;\n\t\telse {\n\t\t\tans *= pw[min(dv[a][u].y, dv[b][v].y)][dv[a][u].x];\n\t\t\tu++, v++;\n\t\t}\n\t}\n\treturn ans;\n}\n\nbool used[N];\nint sz[N];\n\nvoid calcSz(int v, int p) {\n\tsz[v] = 1;\n\tfor(int to : g[v]) {\n\t\tif(to == p || used[to])\n\t\t\tcontinue;\n\t\tcalcSz(to, v);\n\t\tsz[v] += sz[to];\n\t}\n}\n\nint findC(int v, int p, int all) {\n\tfor(int to : g[v]) {\n\t\tif(to == p || used[to])\n\t\t\tcontinue;\n\t\tif(sz[to] > all / 2)\n\t\t\treturn findC(to, v, all);\n\t}\n\treturn v;\n}\n\nint u[N], T = 0;\nint cntD[N];\n\ninline void addDiv(int d, int cnt) {\n\tif(u[d] != T)\n\t\tu[d] = T, cntD[d] = 0;\n\tcntD[d] += cnt;\n}\n\nint cds[N], szcds;\n\nvoid calcDs(int v, int p, int gc) {\n\tgc = gcd(a[v], gc);\n\tcds[szcds++] = gc;\n\tfor(int to : g[v]) {\n\t\tif(to == p || used[to])\n\t\t\tcontinue;\n\t\tcalcDs(to, v, gc);\n\t}\n}\n\nvector<int> cps, cmx, vmx;\n\nvoid check(int curd, int curg, int pos, int add) {\n\tif(pos >= (int)cps.size()) {\n\t\tif(u[curd] == T)\n\t\t\tres[curg] += cntD[curd] * 1ll * add;\n\t\treturn;\n\t}\n\t\n\tfore(st, 0, cmx[pos] + 1) {\n\t\tcheck(curd, curg, pos + 1, add);\n\t\t\n\t\tcurd *= cps[pos];\n\t\tif(st < vmx[pos])\n\t\t\tcurg *= cps[pos];\n\t}\n}\n\npt ops[N]; int szops;\nint cntDiff[N];\n\nvoid calc(int v) {\n\tcalcSz(v, -1);\n\tint c = findC(v, -1, sz[v]);\n\tused[c] = 1;\n\t\n//\tcerr << \"C = \"<< c << endl;\n\t\n\tcps.resize(dv[a[c]].size());\n\tcmx.resize(cps.size());\n\tvmx.resize(cmx.size());\n\t\n\tfore(i, 0, cps.size()) {\n\t\tcps[i] = dv[a[c]][i].x;\n\t\tcmx[i] = dv[a[c]][i].y;\n\t}\n\t\n\tT++;\n\taddDiv(a[c], 1);\n\t\n\tfor(int to : g[c]) {\n\t\tif(used[to]) continue;\n\t\t\n\t\tszcds = 0;\n\t\tcalcDs(to, c, a[c]);\n\t\tfore(i, 0, szcds)\n\t\t\tcntDiff[cds[i]]++;\n\t\t\t\n\t\tszops = 0;\n\t\tfore(j, 0, szcds) {\n\t\t\tif(cntDiff[cds[j]] == 0)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tint p = 0, val = cds[j];\n\t\t\tfore(i, 0, vmx.size()) {\n\t\t\t\tif(p >= (int)dv[val].size() || dv[val][p].x > cps[i])\n\t\t\t\t\tvmx[i] = 0;\n\t\t\t\telse\n\t\t\t\t\tvmx[i] = dv[val][p].y, p++;\n\t\t\t}\n\t\t\t\n\t\t\tcheck(1, 1, 0, cntDiff[cds[j]]);\n\t\t\tops[szops++] = {cds[j], cntDiff[cds[j]]};\n\t\t\tcntDiff[cds[j]] = 0;\n\t\t}\n\t\t\n\t\tfore(j, 0, szops)\n\t\t\taddDiv(ops[j].x, ops[j].y);\n\t}\n\t\n\tfor(int to : g[c]) {\n\t\tif(used[to]) continue;\n\t\tcalc(to);\n\t}\n}\n\ninline void solve() {\n\tiota(mind, mind + N, 0);\n\tfore(i, 2, N) {\n\t\tif(mind[i] != i)\n\t\t\tcontinue;\n\t\t\n\t\tpw[0][i] = 1;\n\t\tfore(st, 1, LOGN)\n\t\t\tpw[st][i] = pw[st - 1][i] * i;\n\t\t\n\t\tfor(li j = i * 1ll * i; j < N; j += i)\n\t\t\tmind[j] = min(mind[j], i);\n\t}\n\tfore(i, 2, N) {\n\t\tint val = i;\n\t\twhile(mind[val] > 1) {\n\t\t\tif(dv[i].empty() || dv[i].back().x != mind[val])\n\t\t\t\tdv[i].emplace_back(mind[val], 0);\n\t\t\tdv[i].back().y++;\n\t\t\tval /= mind[val];\n\t\t}\n\t}\n\t\n\tmemset(res, 0, sizeof res);\n\t\n\tT = 0;\n\tcalc(0);\n\t\n\tfore(i, 0, n)\n\t\tres[a[i]]++;\n\t\n\tfore(i, 1, 1000'000 + 1) {\n\t\tif(res[i])\n\t\t\tprintf(\"%d %lld\\n\", i, res[i]);\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\n\tif(read()) {\n\t\tsolve();\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "divide and conquer",
      "dp",
      "dsu",
      "number theory",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "991",
    "index": "A",
    "title": "If at first you don't succeed...",
    "statement": "Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam.\n\nSome of them celebrated in the BugDonalds restaurant, some of them — in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by $A$ students, BeaverKing — by $B$ students and $C$ students visited both restaurants. Vasya also knows that there are $N$ students in his group.\n\nBased on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time?",
    "tutorial": "There are 4 groups of students - those who visited only the first restaurant, who visited only the second, who visited both places and who stayed at home. One of the easiest ways to detect all the incorrect situations is to calculate number of students in each group. For the first group it is $A - C$, for the second: $B - C$, for the third: $C$ and for the fourth: $N - A - B + C$. Now we must just to check that there are non-negative numbers in the first three groups and the positive number for the last group. If such conditions are met the answer is the number of students in the fourth group. In general you are recommended to view inclusion-exclusion principle. Moreover the limitations allow to go over all possible numbers of students for each group (except for the third) in $O(N^{3})$ and to check whether such numbers produce a correct solution. If no correct numbers found, just print $- 1$:",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nint main() {\\n\\tint a, b, c, n;\\n\\tcin >> a >> b >> c >> n;\\n\\n\\tint n1 = a - c;\\n\\tint n2 = b - c;\\n\\tint n3 = c;\\n\\tint n4 = n - n1 - n2 - n3;\\n\\n\\tif (n1 >= 0 && n2 >= 0 && n3 >= 0 && n4 > 0)\\n\\t\\tcout << n4;\\n\\telse\\n\\t\\tcout << -1;\\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "991",
    "index": "B",
    "title": "Getting an A",
    "statement": "Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.\n\nThe term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically  — he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student — $4.5$ would be rounded up to $5$ (as in example 3), but $4.4$ would be rounded down to $4$.\n\nThis does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than $5$ (maybe even the dreaded $2$). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get $5$ for the course. Of course, Vasya will get $5$ for the lab works he chooses to redo.\n\nHelp Vasya — calculate the minimum amount of lab works Vasya has to redo.",
    "tutorial": "It is necessary to use the greedy approach: of course Vasya should redo the lowest grades firstly. So we have to sort the values in the ascending order and begin to replace the values by 5 until we get the desired result. In order to check whether the current state is suitable we may calculate the mean value after each iteration ($O(N^{2})$ complexity in total), or just update sum of the grades and calculate the arithmetic mean in $O(1)$ with $O(N)$ total complexity (excluding sorting). For example: Of course, both approaches easily fit TL. Finally, it is recommended to avoid floating-point operations while calculating the mean value.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nbool check(int sum, int n) {\\n\\t// integer representation of sum / n >= 4.5\\n\\treturn sum * 10 >= n * 45;\\n}\\n\\nint main() {\\n\\tvector<int> v;\\n\\tint sum = 0;\\n\\n\\tint n;\\n\\tcin >> n;\\n\\tfor (int i = 0; i < n; i++) {\\n\\t\\tint x;\\n\\t\\tcin >> x;\\n\\t\\tv.push_back(x);\\n\\t\\tsum += x;\\n\\t}\\n\\n\\tsort(v.begin(), v.end());\\n\\tint ans = 0;\\n\\twhile (!check(sum, n)) {\\n\\t\\tsum += 5 - v[ans];\\n\\t\\tans++;\\n\\t}\\n\\n\\tcout << ans;\\n}\"",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "991",
    "index": "C",
    "title": "Candies",
    "statement": "After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.\n\nThis means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\\%$ of the candies \\textbf{remaining} in the box. If there are still candies left in the box, the process repeats — next day Vasya eats $k$ candies again, and Petya — $10\\%$ of the candies left in a box, and so on.\n\nIf the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all.\n\nYour task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer.",
    "tutorial": "It is easy to check that if for some value $k$ the necessary condition is met (Vasya eats at least half of the candies), then it is met for each integer greater $k$. Let's consider the number of candies remaining at the evening of each day for some selected $k_{1}$ - let $a_{i}$ candies remain at day $i$. If Vasya will use another number $k_{2}$ > $k_{1}$ we will have less candies in the first day: $b_{1}$ < $a_{1}$. So Petya will eat no more candies than in the first case (for $k_{1}$), but in the next day the number of candies will be not greater than in the first case (if $n_{1}$ > $n_{2}$ then $n_{1} - n_{1} / 10  \\ge  n_{2} - n_{2} / 10$). The same way, including that $k_{2}$ > $k_{1}$ at the evening of the second day we get $b_{2}$ < $a_{2}$ and so on. In general, for each $i$ we have $b_{i}$ < $a_{i}$, so Petya will eat not more candies than in the first case in total. It means that Vasya will eat not less candies than in the first case. So this problem can be solved using the binary search (answer) approach. In order to check whether selected $k$ is applicable it necessary just to implement the process described in the problem statement. Since Petya eats $10%$ of candies, its amount decreases exponentially, so there will be only few days before all the candies will be eaten. In the worst case it is necessary 378 days. Formally the complexity of the solution is $O(log(n)^{2})$. Like in the previous problem it is recommended to avoid floating operations and to use only integer types.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nbool check(long long k, long long n) {\\n\\tlong long sum = 0;\\n\\tlong long cur = n;\\n\\twhile (cur > 0) {\\n\\t\\tlong long o = min(cur, k);\\n\\t\\tsum += o;\\n\\t\\tcur -= o;\\n\\t\\tcur -= cur / 10;\\n\\t}\\n\\treturn sum * 2 >= n;\\n}\\n\\nint main() {\\n\\tlong long n;\\n\\tcin >> n;\\n\\n\\tlong long l = 1, r = n;\\n\\tlong long ans = r;\\n\\twhile (l <= r) {\\n\\t\\tlong long k = (l + r) / 2;\\n\\t\\tif (check(k, n)) {\\n\\t\\t\\tans = k;\\n\\t\\t\\tr = k - 1;\\n\\t\\t}\\n\\t\\telse\\n\\t\\t\\tl = k + 1;\\n\\t}\\n\\n\\tcout << ans << endl;\\n}\"",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "991",
    "index": "D",
    "title": "Bishwock",
    "statement": "Bishwock is a chess figure that consists of three squares resembling an \"L-bar\". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states:\n\n\\begin{center}\n\\begin{verbatim}\nXX XX .X X.\nX. .X XX XX\n\\end{verbatim}\n\\end{center}\n\nBishwocks don't attack any squares and can even occupy on the adjacent squares as long as they don't occupy the same square.\n\nVasya has a board with $2\\times n$ squares onto which he wants to put some bishwocks. To his dismay, several squares on this board are already occupied by pawns and Vasya can't put bishwocks there. However, pawns also don't attack bishwocks and they can occupy adjacent squares peacefully.\n\nKnowing the positions of pawns on the board, help Vasya to determine the maximum amount of bishwocks he can put onto the board so that they wouldn't occupy the same squares and wouldn't occupy squares with pawns.",
    "tutorial": "In this problem we may use the greedy approach. Let's go through columns from left to right. If we are currently considering column $i$ and we may place a figure occupying only cells at columns $i$ and $i + 1$, we have to place this figure. Really if the optimal solution doesn't contain a bishwock at column $i$ then column $i + 1$ may be occupied by at most one bishwock. So we can remove this figure and place it at columns $i$ and $i + 1$, the result will be at least the same. A bit harder question is - how exactly we should place the figure if all 4 cells of columns $i$ and $i + 1$ are empty (in other cases there will be only one way to place a bishwock)? Of course, we should occupy both cells of column $i$. Moreover it does not matter which cell we will occupy at column $i + 1$ in this case. The cells of $i + 1$ may be used only for placing a bishwock in columns $i + 1$,$i + 2$. If column $i + 2$ has at most one empty cell we are unable to place such figure and the remaining empty cells of column $i + 1$ are useless at all. If both cells of column $i + 2$ are empty we may place a bishwock regardless of the position of the remaining empty cell at column $i + 1$. It means that we don't have to place the figures actually - we have to calculate and update number of empty cells in columns. According to the described algorithm we may write such code: Moreover this implementation can be simplified to just two cases: Formally such algorithm may be considered as the dynamic programming. Of course it is not necessary to have a deep understanding of DP to write such implementation and solve the problem. This problem also can be solved by more ''obvious'' DP approach (for example we may consider index of current column and state of the cells of the previous column as a state of DP). In this case the implementation will be a bit more complicated but it won't be necessary to prove described solution.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nint main() {\\n\\tstring s[2];\\n\\n\\tint n = 2;\\n\\tint m;\\n\\tfor (int i = 0; i < n; i++) {\\n\\t\\tcin >> s[i];\\n\\t\\tm = s[i].length();\\n\\t}\\n\\n\\tint ans = 0;\\n\\tint previous = 0;\\n\\tfor (int i = 0; i < m; i++) {\\n\\t\\tint current = (s[0][i] == '0') + (s[1][i] == '0');\\n\\n\\t\\tif (current == 0)\\n\\t\\t\\tprevious = 0;\\n\\n\\t\\tif (current == 1) {\\n\\t\\t\\tif (previous == 2) {\\n\\t\\t\\t\\tans++;\\n\\t\\t\\t\\tprevious = 0;\\n\\t\\t\\t}\\n\\t\\t\\telse\\n\\t\\t\\t\\tprevious = 1;\\n\\t\\t}\\n\\n\\t\\tif (current == 2) {\\n\\t\\t\\tif (previous > 0) {\\n\\t\\t\\t\\tans++;\\n\\t\\t\\t\\tif (previous == 2)\\n\\t\\t\\t\\t\\tprevious = 1;\\n\\t\\t\\t\\telse\\n\\t\\t\\t\\t\\tprevious = 0;\\n\\t\\t\\t}\\n\\t\\t\\telse\\n\\t\\t\\t\\tprevious = 2;\\n\\t\\t}\\n\\t}\\n\\n\\tcout << ans;\\n}\"",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "991",
    "index": "E",
    "title": "Bus Number",
    "statement": "This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all.\n\nIn the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number $n$.\n\nIn the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could \"see\" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too.\n\nGiven $n$, determine the total number of possible bus number variants.",
    "tutorial": "According to the statement, digits of original bus number form a subset of digits of the number seen by Vasya. It is possible to iterate through all the subsets in $2^{k}$ operations (where $k$ is length of $n$). For each subset we need to check whether it is correct (contains all necessary digits) and transform it to ''normal'' state (sort the digits for example), in order to avoid conflicts with another subsets which differ only at the digits order. We have to keep only unique subsets. Now for each subset of digits we have to calculate amount of corresponding correct bus numbers. It can be calculated in $O(k)$ operations using permutations of multisets formula (see ''Permutations of multisets'' at the article about permutations and multinomial coefficients) $C = k! / (c_{0}! * c_{1}! * ... * c_{9}!)$, where $k$ - total number of digits in the subset and $c_{i}$ - number of digits $i$: Now, we have to subtract amount of bus numbers with leading zeroes from the result for this subset if it contains digit $0$. This can be done in the very same way: if we place digit $0$ at the first position of the number, we have to decrease $k$ by $1$ and decrease $c_{0}$ by 1; the formula described above will calculate amount of ways to place remaining digits of the subset and this number should be subtract from the answer: In total, even with such rough evaluation of complexity and naive implementation we get $O(2^{k} * k)$ operations, where $k  \\le  19$ - amount of digits in $n$. It is easy to check that the answer doesn't exceed $10^{18}$ so the standard 64-bit integer type will be enough.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nlong long fact[20];\\n\\nset<string> was;\\nint c0[10];\\nint c[10];\\n\\nvoid split(string s, int *c) {\\n\\tfor (int i = 0; i < 10; i++)\\n\\t\\tc[i] = 0;\\n\\tfor (char ch : s)\\n\\t\\tc[ch - 48]++;\\n}\\n\\nlong long getCount() {\\n\\tlong long ans = fact[accumulate(c, c + 10, 0)];\\n\\tfor (int i = 0; i < 10; i++)\\n\\t\\tans /= fact[c[i]];\\n\\treturn ans;\\n}\\n\\nlong long getans(string s) {\\n\\tsplit(s, c);\\n\\n\\t// check whether the string contains all digits\\n\\tfor (int i = 0; i < 10; i++)\\n\\t\\tif (c0[i] && !c[i])\\n\\t\\t\\treturn 0;\\n\\n\\t// check whether we already processed such string\\n\\tsort(s.begin(), s.end());\\n\\tif (was.count(s))\\n\\t\\treturn 0;\\n\\twas.insert(s);\\n\\n\\tlong long ans = getCount();\\n\\tif (c[0] > 0) {\\n\\t\\tc[0]--;\\n\\t\\tans -= getCount();\\n\\t}\\n\\n\\treturn ans;\\n}\\n\\nint main() {\\n\\tfact[0] = 1;\\n\\tfor (int i = 1; i < 20; i++)\\n\\t\\tfact[i] = i * fact[i - 1];\\n\\n\\tstring n;\\n\\tcin >> n;\\n\\n\\tint k = n.length();\\n\\tsplit(n, c0);\\n\\n\\tlong long ans = 0;\\n\\tfor (int i = 1; i <= (1 << k); i++) {\\n\\t\\tstring c;\\n\\t\\tfor (int j = 0; j < k; j++)\\n\\t\\t\\tif (i & (1 << j))\\n\\t\\t\\t\\tc += n[j];\\n\\t\\tans += getans(c);\\n\\t}\\n\\n\\tcout << ans;\\n}\"",
    "tags": [
      "brute force",
      "combinatorics",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "991",
    "index": "F",
    "title": "Concise and clear",
    "statement": "Vasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important — factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the number at the first glance. Could it be shortened? For example, instead of 1000000 you could write $10^{6}$, instead of 1000000000  —$10^{9}$, instead of 1000000007 — $10^{9}+7$.\n\nVasya decided that, to be concise, the notation should follow several rules:\n\n- the notation should only consist of numbers, operations of addition (\"+\"), multiplication (\"*\") and exponentiation (\"^\"), in particular, the use of braces is forbidden;\n- the use of several exponentiation operations in a row is forbidden, for example, writing \"2^3^4\" is unacceptable;\n- the value of the resulting expression equals to the initial number;\n- the notation should consist of the minimal amount of symbols.\n\nGiven $n$, find the equivalent concise notation for it.",
    "tutorial": "All the problem numbers (except for $10^{10}$, which is given in the samples) contain at most 10 digits. It means that we have to use at most 9 digits if we want to find a shorter representation. Notice that the length of sum of two integers is not greater than sum of the lengths of these integers, so in the optimal representation at most one term is a number while other terms are expressions containing * and/or ^. Each expression (not a number) contains at least 3 symbols, so the optimal representation can contain at most 3 terms. The maximal integer that can be represented in such manner is 9^9+9^9+9, but it contains only 9 digits while expressions with 3 terms always contain at least 9 symbols. So we proved that there always exists an optimal representation which is a sum of at most two terms. So there exist only 3 types of representation of the original number: n = a^b n = x+y n = x*y where $x$ and $y$ - some expressions (in the first case $a$ and $b$ are numbers), which doesn't contain +. Moreover in all the cases such expressions should contain at most 7 digits. Let's find for each $x  \\le  n$ a shortest valid representation $m[x]$, containing at most 7 symbols (if it exists and contains less digits than simple number $x$), and for each length $d$ - set of integers $s[d]$ which can be represented by an expression of length $d$. The standard containers (std::map and std::set in C++) are suitable for that: Firstly let's add all expressions a^b, there are about sqrt(n) such expressions. Now lets consider the expressions containing several multipliers. The same way (as for addition) in such representation at most one multiplier is a number. Including that the expression can contain at most 7 digits we have only 2 possible ways: x = a^b*c^d x = a^b*c where $a$, $b$, $c$ and $d$ are some numbers. Lets iterate through $i$ - the length of the representation of the first multiplier and go over all values stored in $s[i]$. The second multiplier can have length at most $d = 7 - i - 1$ and the total number of ways to choose two multipliers will be small enough. The second multiplier should be selected from containers $s[j]$ for length at most $d$ (in the first case), or we should iterate from $1$ to $10^{d}$ (in the second case). After that we will have about $k = 150000$ numbers in $m$ in total: Now lets go back to the representation of the original number. For the first case - a^b - we have already stored such values in $m$. For the cases x+y and x*y we may assume that the length of expression of $x$ is not greater than 4. Now lets iterate through $x$ among found representations of length up to 4, and among integers from 1 to $10^{4}$. For each such $x$ and for each of 2 cases we determine value of $y$ uniquely, and the optimal representation of $y$ is already stored in $m$ or it is just a number. So, for each such $x$ we can find optimal answer for $n$ by at most two addressing to $m$ i.e. in $log(k)$ operations. Finally, the total algorithm complexity is $O((sqrt(n) + k + 10^{4}) * log(k))$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nlong long n;\\nlong long p10[10];\\nmap<long long, string> m;\\nset<long long> s[10];\\n\\ntemplate<class T> string toString(T x) {\\n\\tostringstream sout;\\n\\tsout << x;\\n\\treturn sout.str();\\n}\\n\\nint getlen(long long x) {\\n\\tint ans = 0;\\n\\twhile (x) {\\n\\t\\tx /= 10;\\n\\t\\tans++;\\n\\t}\\n\\treturn max(ans, 1);\\n}\\n\\nstring get(long long x) {\\n\\tif (m.count(x))\\n\\t\\treturn m[x];\\n\\treturn toString(x);\\n}\\n\\nvoid relax(long long x, string str) {\\n\\t// obviously not optimal\\n\\tif (x > n || str.length() >= getlen(x))\\n\\t\\treturn;\\n\\n\\t// already have better\\n\\tif (m.count(x) && m[x].length() <= str.length())\\n\\t\\treturn;\\n\\n\\ts[m[x].length()].erase(x);\\n\\tm[x] = str;\\n\\ts[str.length()].insert(x);\\n}\\n\\nvoid generatePowers() {\\n\\tfor (long long x = 2; x * x <= n; x++) {\\n\\t\\tlong long c = x * x;\\n\\t\\tint p = 2;\\n\\t\\twhile (c <= n) {\\n\\t\\t\\tstring tmp = toString(x) + \\\"^\\\" + toString(p);\\n\\t\\t\\trelax(c, tmp);\\n\\t\\t\\tc *= x;\\n\\t\\t\\tp++;\\n\\t\\t}\\n\\t}\\n}\\n\\nvoid generatePowerAndPower(int maxlen) {\\n\\tfor (int i = 1; i <= maxlen; i++)\\n\\t\\tfor (int j = i; i + j + 1 <= maxlen; j++)\\n\\t\\t\\tfor (auto x : s[i])\\n\\t\\t\\t\\tfor (auto y : s[j])\\n\\t\\t\\t\\t\\trelax(x * y, get(x) + \\\"*\\\" + get(y));\\n}\\n\\nvoid generateSimpleAndPower(int maxlen) {\\n\\tfor (int i = 1; i + 2 <= maxlen; i++)\\n\\t\\tfor (long long x = 1; x < p10[maxlen - 1 - i]; x++)\\n\\t\\t\\tfor (long long y : s[i])\\n\\t\\t\\t\\trelax(x * y, toString(x) + \\\"*\\\" + get(y));\\n}\\n\\nvoid precalc() {\\n\\tgeneratePowers();\\n\\tgeneratePowerAndPower(7);\\n\\tgenerateSimpleAndPower(7);\\n}\\n\\nstring ans;\\nvoid relaxAns(string s) {\\n\\tif (ans.length() > s.length())\\n\\t\\tans = s;\\n}\\n\\nvoid check2() {\\n\\tfor (int i = 1; i * 2 + 1 < ans.length(); i++) {\\n\\t\\tfor (long long x = 1; x <= p10[i]; x++) {\\n\\t\\t\\trelaxAns(get(n - x) + \\\"+\\\" + get(x));\\n\\t\\t\\tif (n % x == 0)\\n\\t\\t\\t\\trelaxAns(get(n / x) + \\\"*\\\" + get(x));\\n\\t\\t}\\n\\t\\tfor (auto x : s[i]) {\\n\\t\\t\\trelaxAns(get(n - x) + \\\"+\\\" + get(x));\\n\\t\\t\\tif (n % x == 0)\\n\\t\\t\\t\\trelaxAns(get(n / x) + \\\"*\\\" + get(x));\\n\\t\\t}\\n\\t}\\n}\\n\\nint main() {\\n\\tp10[0] = 1;\\n\\tfor (int i = 1; i < 10; i++)\\n\\t\\tp10[i] = 10 * p10[i - 1];\\n\\n\\tcin >> n;\\n\\n\\tprecalc();\\n\\tans = get(n);\\n\\tcheck2();\\n\\tcout << ans;\\n}\"",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "992",
    "index": "A",
    "title": "Nastya and an Array",
    "statement": "Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:\n\n- In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero.\n- When all elements of the array become equal to zero, the array explodes.\n\nNastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.",
    "tutorial": "Let's notice that after one second we aren't able to decrease the number of distinct non-zero elements in the array more than by 1. It means that we can't make all elements equal to zero faster than after $X$ seconds, where $X$ is the number of distinct elements in the array initially. And let's notice that we are able to make it surely after $X$ second, if we will subtract every second some number which is in the array, so all elements equal this number in the array will have become zero, and the number of distinct non-zero elements will be decreased. So the answer is the number of distinct non-zero elements initially. Complexity is $O(n\\cdot l o g(n))$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    \n    int n;\n    cin >> n;\n    set <int> ms;\n    for (int i = 0; i < n; ++i) {\n        int x; cin >> x;\n        if (x) ms.insert(x);\n    }\n \n    cout << ms.size() << '\\n';\n    return 0;\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "992",
    "index": "B",
    "title": "Nastya Studies Informatics",
    "statement": "Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well.\n\nWe define a pair of integers $(a, b)$ good, if $GCD(a, b) = x$ and $LCM(a, b) = y$, where $GCD(a, b)$ denotes the greatest common divisor of $a$ and $b$, and $LCM(a, b)$ denotes the least common multiple of $a$ and $b$.\n\nYou are given two integers $x$ and $y$. You are to find the number of good pairs of integers $(a, b)$ such that $l ≤ a, b ≤ r$. Note that pairs $(a, b)$ and $(b, a)$ are considered different if $a ≠ b$.",
    "tutorial": "Let's consider some suitable pair $(a,b)$. As $G C D(a,b)=x$, we can present number ${\\boldsymbol{Q}}$ as $c\\cdot x$, and number ${\\boldsymbol{b}}$ as $d\\cdot x$, where we know that $c,d\\geq1$ and $G C D(c,d)=1$. Let's consider too that from the restriction from the problem $l\\leq a,b\\leq r$ we surely know the restriction for ${\\mathit{\\mathbb{C}}}_{-}^{*}$ and $d$, that is $\\frac{\\iota}{x}\\leq c,d\\leq\\frac{\\L_{\\L}}{x}$. Let's remember we know that $x\\cdot y=a\\cdot b$ (because $\\textstyle{\\bar{\\mathbf{Z}}}$ is $G C D(a,b)$, $\\mathbf{\\mathbf{y}}$ is $L C M(a,b)$). Then we can get $x\\cdot y=c\\cdot x\\cdot d\\cdot x$. Dividing by $\\textstyle{\\bar{\\mathbf{Z}}}$: $y=c\\cdot d\\cdot x$. $\\textstyle{\\frac{\\nu}{x}}=c\\cdot d\\,$. Now if $y\\forall_{c x}\\neq0$, answer equals 0. Else as $\\frac{y}{x}$ is surely less than $10^{9}$, we can just sort out all possible pairs $(c,d)$ of divisors $\\frac{y}{x}$, such that $c\\cdot d={\\frac{\\nu}{x}}$ , and then to check that $G C D(c,d)=1$ and $c.d$ are in the getting above restrictions. Complexity of this solution is $O({\\sqrt{y}})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint gcd(int a, int b) {\n    while (b) {\n        int t = a % b;\n        a = b;\n        b = t;\n    }\n    return a;\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int l, r, x, y;\n    cin >> l >> r >> x >> y;\n    if (y % x != 0){\n        cout << 0 << '\\n';\n        return 0;\n    }\n    int ans = 0;\n    int n = y / x;\n    for (int d = 1; d * d <= n; ++d) {\n        if (n % d == 0) {\n            int c = n / d;\n            if (l <= c * x && c * x <= r && l <= d * x && d * x <= r && gcd(c, d) == 1) {\n                if (d * d == n) ++ans;\n                else ans += 2;\n            }\n        }\n    }\n \n    cout << ans << '\\n';\n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "992",
    "index": "C",
    "title": "Nastya and a Wardrobe",
    "statement": "Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).\n\nUnfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the $50%$ probability. It happens every month except the last one in the year.\n\nNastya owns $x$ dresses now, so she became interested in the expected number of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for $k + 1$ months.\n\nNastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo $10^{9} + 7$, because it is easy to see that it is always integer.",
    "tutorial": "Let's present we have initially $X=Y+{\\frac{1}{2}}$ dresses. What does occur in the first month? Initially the number of dresses is multiplied by 2, that is becomes $2\\cdot Y+1$. Then with probability $\\mathbf{z}=\\mathbf{z}(\\mathbf{z})^{(y)}{\\mathcal{V}}$ the wardrobe eats a dress, that is expected value of the number of dresses becomes $2\\cdot Y+{\\frac{1}{2}}$. The same way after the second month expected value becomes $\\textstyle1\\cdot Y+{\\frac{1}{2}}$. It's easy to notice that after $D\\!\\!\\!\\!/$-th month(if $p\\leq k$) expected value equals $2^{p}\\cdot Y+{\\frac{1}{2}}$. Eventually it will be only doubled(as the wardrobe doesn't eat a dress in the last month), that is will be equal $2^{k+1}\\cdot Y+1$. Thus, answer of the problem is $2^{k+1}\\cdot Y+1$. Expressing it with $X$, we get: $\\boldsymbol{M}$ = $2^{k+1}\\cdot(X-{\\frac{1}{2}})+1$. $\\boldsymbol{M}$ = $2^{k+1}\\cdot X-2^{k}+1$. Thus, we need to calculate degree of 2 right up to $10^{18}$. Complexity of the soltion is $O(l o g(k))$. Let's notice that the case $x=0$ we need to calculate separately, because wardrobe can't eat a dress when it doesn't exist. If $x>0$ it's easy to proof that the number of dresses is never negative, that is the formula works.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n#define int long long\n \nconst int MOD = 1000 * 1000 * 1000 + 7;\n \nint mod(int n) {\n    return (n % MOD + MOD) % MOD;\n}\n \nint fp(int a, int b) {\n    if (b == 0) return 1;\n    int t = fp(a, b / 2);\n    if (b % 2 == 0) return mod(t * t);\n    else return mod(mod(t * t) * a);\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int x, k;\n    cin >> x >> k;\n \n    if (x == 0) {\n        cout << \"0\\n\";\n        return 0;\n    }\n \n    if (k == 0) cout << mod(2 * x) << '\\n';\n    else {\n        int a = mod(2 * x - 1);\n        cout << mod(2 * a * fp(2, k - 1) + 1) << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "992",
    "index": "D",
    "title": "Nastya and a Game",
    "statement": "Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that $\\overset{p}{s}=k$, where $p$ is the product of all integers on the given array, $s$ is their sum, and $k$ is a given constant for all subsegments.\n\nNastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.",
    "tutorial": "Let's call numbers which are more than 1 as good. Notice the following fact: If a subsegment is suitable, it contains not more than 60 good numbers. Indeed, let's assume that a subsegment contains more than 60 good numbers. In this subsegment $p\\geq2^{61}>2\\cdot10^{18}$. At the same time, as $k\\leq10^{5}$, and $s\\leq n\\cdot10^{8}=2\\cdot10^{15}$, there is $s\\cdot k\\leq2\\cdot10^{18}$. Therefore, this subsegment can't be suitable due to $s\\cdot k<p$. Let's keep all positions of good numbers in a sorted array. We sort out possible left border of a subsegment and then with binary search we find the next good number to the right of this left border. Then let's iterate from this found number to the right by the good numbers(that is we sort out the rightmost good number in a subsegment), until product of all numbers in the subsegment becomes more than $2\\cdot10^{18}$ (it's flag which shows us, that product is too big for a suitable subsgment and we need to finish to iterate). We have shown above the number of iterations isn't more than 60. Now for sorted out the left border and the rightmost good number we only need to know the number of 1's which needs to be added to the right of the rightmost good number, as we can easily maintain sum and product in the subsegment during iterating. Then we need to check whether found number of 1's exists to the right of the rightmost good number. It can be checked if we look at the next good number's position. Complexity is $O(n\\cdot l o g(10^{18}))$. In order to check that $a\\cdot b$ is more than $2\\cdot10^{18}$, you shouldn't calculate ${\\boldsymbol{Q}}$ multiply by ${\\boldsymbol{b}}$, due to overflow. You must only check that ${\\frac{210^{18}}{a}}\\geq b$. (Idea of the problem - DmitryGrigorev)",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n#define int long long\n \nconst int MAXN = 2e5 + 7;\nconst int INF = 1e18 + 2007;\n \nint a[MAXN];\nint go[MAXN];\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int n, k;\n    cin >> n >> k;\n    for (int i = 0; i < n; ++i) cin >> a[i];\n \n    go[n - 1] = n;\n    for (int i = n - 2; i >= 0; --i) {\n        if (a[i + 1] != 1) go[i] = i + 1;\n        else go[i] = go[i + 1];\n    }\n \n    int ans = 0;\n    for (int l = 0; l < n; ++l) {\n        int r = l;\n        ans += (k == 1);\n \n        int f = a[l];\n        int s = a[l];\n        while (go[r] != n && a[go[r]] <= (INF / f)) {\n            f *= a[go[r]];\n            s += go[r] - r - 1 + a[go[r]];\n            r = go[r];\n            int want = -1;\n            if (f % k == 0) want = f / k;\n            int have = go[r] - r - 1;\n            ans += (s <= want && want <= s + have);\n        } \n    }\n \n    cout << ans << '\\n';\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "992",
    "index": "E",
    "title": "Nastya and King-Shamans",
    "statement": "Nastya likes reading and even spends whole days in a library sometimes. Today she found a chronicle of Byteland in the library, and it stated that there lived shamans long time ago. It is known that at every moment there was exactly one shaman in Byteland, and there were $n$ shamans in total enumerated with integers from $1$ to $n$ in the order they lived. Also, each shaman had a magic power which can now be expressed as an integer.\n\nThe chronicle includes a list of powers of the $n$ shamans. Also, some shamans can be king-shamans, if they gathered all the power of their predecessors, i.e. their power is exactly the sum of powers of all previous shamans. Nastya is interested in whether there was at least one king-shaman in Byteland.\n\nUnfortunately many of the powers are unreadable in the list, so Nastya is doing the following:\n\n- Initially she supposes some power for each shaman.\n- After that she changes the power of some shaman $q$ times (the shamans can differ) and after that wants to check if there is at least one king-shaman in the list. If yes, she wants to know the index of any king-shaman.\n\nUnfortunately the list is too large and Nastya wants you to help her.",
    "tutorial": "This problem was inspired by idea which was offered by my unbelievable girlfriend :) Solution I In this problem we maintain two segment trees - with maximum and with sum. After every query we recalculate these trees in $O(l o g N)$ for a query. Now we only have to understand, how to answer for a query? Let's call a prefix of the array as good in the case if we surely know that it doesn't contain a king-shaman. So either the first shaman is king and we are able to answer for the query, or we call the prefix with length 1 as good. Then let's repeat the following operation: We call $p_{i}$ as sum in the good prefix now. We find it using the segment tree with sums. We find the leftmost element which may be king-shaman yet. We can realise that it's the leftmost element, which doesn't lie in the good prefix (as there isn't king-shaman according the definition), which have a value at least $p_{i}$. It can be done using segment tree with maximums, with descent. We check if this found shaman is king. If isn't, we can say that the good prefix finishes in this shaman now, because it was the leftmost shaman who might be king. Every operation works in $O(l o g N)$. Let's notice, that one operation increases sum in the good prefix at least by two times. So, after $O(l o g M a x(A_{i}))$ operations sum in the good prefix will become more than a maximal possible number in the array, so that we will be able to finish, because we will be sure that answer will be -1. Complexity of the solution is $O(N\\cdot l o g N\\times l o g M a x(a_{i}))$. Solution II Let $p_{i}$ be the prefix sums of $a$. We're gonna introduce $f_{i} = p_{i} - 2 \\cdot a_{i}$ and reformulate the queries using these new terms. Imagine we wanna change the value at $j$ to $val$. Let $ \\delta  = val - a_{j}$. Then $f_{j}$ will decrease by $ \\delta $ whereas $f_{i > j}$ will increase by $ \\delta $. Imagine we wanna find the answer. Then it's sufficient to find any $i$ satisfying $f_{i} = 0$. Split $f$ into blocks of size $M$. Each block will be comprised of pairs $(f_{i}, i)$ sorted by $f$. At the same time we will maintain $overhead$ array responsible for lazy additions to blocks. How does this help? Let $b = j / M$. The goal is to find the position of $j$, decrease its value and increase values for all $i > j$ within this block. It can be done in a smart way in $O(M)$ (actually, this can be represented as merging sorted vectors). You should also take care of the tail, i.e add $ \\delta $ to $overhead_{j > b}$ in $O(n / M)$ time. We're asked to find such $i$ that $f_{i} + overhead_{j / M} = 0$. All blocks are sorted, thus we can simply apply binary search in $O((n/M)\\cdot\\log M)$ overall. The optimal assignment is $M={\\sqrt{n\\log n}}$ which results into $O(q{\\sqrt{n\\log n}})$ total runtime. The huge advantage of this approach is its independency from constraints on $a$ (i.e non-negativity). Although we didn't succeed in squeezing this into TL :) Solution III Group the numbers according to their highest bits (with groups of the form $[2^{k}... 2^{k + 1}]$ and separately for zeros). Inside each groups (no more than $\\log10^{9}$ of them) we maintain elements in increasing order of indexes. It's easy to see that each group contains no more than two candidates for answer (since their sum is guaranteed to be greater than any of the remaining ones). This observation leads to an easy solution in $O(q\\log n\\log10^{9})$ - we iterate over groups and check prefix sums for these candidates. There's actually further space for optimizations. Let's maintain prefix sums for our candidates - this allows us to get rid of the extra log when quering the tree. Almost everything we need at this step is to somehow process additions and deletions - change the order inside two blocks and probably recalculate prefix sums. The only thing left is to stay aware of prefix sum changes for the remaining blocks. Luckily, they can be fixed in $O(1)$ per block (if $i > j$ then the sum increases by $val - a_{j}$ and stays the same otherwise). The resulting comlexity is $O(q\\cdot(\\log10^{9}+\\log n))$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <set>\n \ntemplate <class T>\nclass FenwickTree {\npublic:\n\tvoid init(int n) {\n\t\tthis->n = n;\n\t\tbit.assign(n + 1, 0);\n\t}\n \n\tvoid init(const std::vector<T> &a) {\n\t\tn = a.size();\n\t\tbit.assign(n + 1, 0);\n\t\tfor(int i = 1; i <= n; i++) {\n\t\t\tbit[i] += a[i - 1];\n\t\t\tif(i + (i & -i) <= n) {\n\t\t\t\tbit[i + (i & -i)] += bit[i];\n\t\t\t}\n\t\t}\n\t}\n \n\tT qry(int x) {\n\t\tx = std::min(x, (int)bit.size() - 1);\n\t\tT ans = 0;\n\t\tfor(; x > 0; x -= x & -x) {\n\t\t\tans += bit[x];\n\t\t}\n\t\treturn ans;\n\t}\n \n\tvoid upd(int x, T v) {\n\t\tif(x <= 0) return;\n\t\tfor(; x <= n; x += x & -x) {\n\t\t\tbit[x] += v;\n\t\t}\n\t}\nprivate:\n\tint n;\n\tstd::vector<T> bit;\n};\n \nint getGroup(int x) {\n\treturn x == 0 ? 0 : 1 + getGroup(x / 2);\n}\n \nint main() {\n\t//std::ios_base::sync_with_stdio(false); std::cin.tie(NULL);\n\tint n, q;\n\tstd::cin >> n >> q;\n\tstd::vector<long long> base(n);\n\tconst int me = 33;\n\tstd::set<int> groups[me];\n\tint cands[me][2];\n\tlong long sum[me][2];\n\t\n\tfor(int i = 0; i < n; i++) {\n\t\t//std::cin >> base[i];\n\t\tscanf(\"%lld\", &base[i]);\n\t\tgroups[getGroup(base[i])].insert(i);\n\t}\n\tFenwickTree<long long> tree;\n\tauto reconstruct = [&](int idx) {\n\t\tint i = 0;\n\t\tfor(auto it = groups[idx].begin(); i < std::min(2, (int)groups[idx].size()); i++, it++) {\n\t\t\tcands[idx][i] = *it;\n\t\t\tsum[idx][i] = tree.qry(*it);\n\t\t}\n\t};\n\tauto getAnswer = [&](int idx) {\n\t\tfor(int i = 0; i < std::min(2, (int)groups[idx].size()); i++) {\n\t\t\tif(base[cands[idx][i]] == sum[idx][i]) {\n\t\t\t\treturn cands[idx][i] + 1;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t};\n\ttree.init(base);\n\tfor(int i = 0; i < me; i++) {\n\t\treconstruct(i);\n\t}\n\twhile(q--) {\n\t\tint pos, v;\n\t\t//std::cin >> pos >> v;\n\t\tscanf(\"%d %d\", &pos, &v);\n\t\tpos--;\n\t\tint diff = v - base[pos];\n\t\tint a = getGroup(base[pos]);\n\t\tint b = getGroup(v);\n\t\tgroups[a].erase(pos);\n\t\tbase[pos] = v;\n\t\tgroups[b].insert(pos);\n\t\tfor(int i = 0; i < me; i++) {\n\t\t\tfor(int j = 0; j < std::min(2, (int)groups[i].size()); j++) {\n\t\t\t\tif(pos < cands[i][j]) {\n\t\t\t\t\tsum[i][j] += diff;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttree.upd(pos + 1, diff);\n\t\treconstruct(a);\n\t\treconstruct(b);\n\t\tint ans = -1;\n\t\tfor(int i = 0; i < me && ans == -1; i++) {\n\t\t\tans = getAnswer(i);\n\t\t}\n\t\tprintf(\"%d\\n\", ans);\n\t}\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "993",
    "index": "A",
    "title": "Two Squares",
    "statement": "You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.\n\nThe interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.",
    "tutorial": "It can be shown that if two squares intersect, then at least for one of the squares it is true that either one of its corners lies within the other square, or its center lies within the other square. It is very easy to check if any corner or the center of the square rotated by 45 degrees lies within the square with sides parallel to the axes. To check in the opposite directions in a similarly simple fashion, it is enough to rotate both squares by 45 degrees. To turn both squares by 45 degrees (with some scaling, which is OK) it is sufficient to replace each $x$ coordinate with $x + y$ and each $y$ coordinate with $x - y$.",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "993",
    "index": "B",
    "title": "Open Communication",
    "statement": "Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you.\n\nBoth participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers.\n\nDetermine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not.",
    "tutorial": "One way to approach this problem is to 1. Iterate over each pair $p1$ communicated by the first participant, and do the following: Iterate over all pairs $p2$ of the second participant that are not equal to $p1$ and count whether the first number of $p1$ appears in any of them and whether the second number of $p1$ appears in any of them. If only one of them appears, that number is a candidate to be the matching number. If after iterating over all pairs communicated by the first participant only one candidate number was observed, then we know with certainty that that number is the one, and can immediately return it. 2. Do (1) but iterating over the numbers communicated by the second participant in the outer loop. 3. If at this point no number was returned, the answer is either -1 or 0. It is -1 iff for some pair $(a,b)$ communicated by one of the participants, there are both pairs $(a, c)$ and $(b, d)$ among pairs communicated by the other participants, such that $c \\ne b$ and $d \\ne a$ (but possibly $c = d$), since in that case if the first participant indeed has the pair $(a, b)$, they can't tell whether the actual number is $a$ or $b$. Otherwise the answer is 0.",
    "tags": [
      "bitmasks",
      "brute force"
    ],
    "rating": 1900
  },
  {
    "contest_id": "993",
    "index": "C",
    "title": "Careful Maneuvering",
    "statement": "There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $-100$, while the second group is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $100$.\n\nEach spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $x=0$ (with not necessarily integer $y$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.",
    "tutorial": "One way to solve the problem is to fix one spaceship in the left half and one spaceship in the right half, and assume that they shoot each other by the means of shooting towards one of the small spaceships. This gives us a coordinate of one small spaceship. Once we have it, iterate over all the large spaceships, mark those that are already shot. Now all that is left is to find the best place to position the second spaceship. To do that, create a map from a coordinate to number of unmarked spaceships that would be destroyed if the second small spaceship is at that coordinate. Iterate over each unique spaceship coordinate on the left and each unique spaceship coordinate on the right, and increment the value in the map that corresponds to the position of the second small spaceship that would result in those two large spaceships shooting each other down by the number of large unmarked spaceships at the fixed coordinates. Then update the final answer with the largest value in the map plus the number of marked spaceships and move to the next pair of spaceships in the outer loop. This is a $O((n \\times m) ^ 2)$ solution.",
    "tags": [
      "bitmasks",
      "brute force",
      "geometry"
    ],
    "rating": 2100
  },
  {
    "contest_id": "993",
    "index": "D",
    "title": "Compute Power",
    "statement": "You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.\n\nYou have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.\n\nIf the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.\n\nDue to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.",
    "tutorial": "First observe that if for some threshold there's a way to assign tasks in a way that they will finish computation, it is also possible for all higher thresholds. Because of that, we can use binary search to find the threshold. Now the problem is reduced to figuring out if for a given threshold the tasks can be assigned in a way that the system doesn't blow up too early. For that, observe that if the average power per processor exceeds a given threshold, it also means that the average power exceeds the threshold multiplied by the number of processors, which in turn means that the average power minus threshold multiplied by the number of processors exceeds 0. By regrouping summands, we can associate the value $(power - threshold * num_of_processors)$ to each task, and reduce the problem to finding the mapping of tasks to computers that minimizes the sum of values of all the tasks assigned as the first task, and compare it to zero. To do that, we can use sort the tasks by the power value in decreasing order and use dynamic programming. The dimensions are: $i$: The current task considered $j$: How many tasks that use strictly more power than the $i - 1$st task are assigned as the first task to some computer that doesn't have a second task yet. $k$: How many tasks that use exactly as much power as the $i - 1$st task are assigned as the first task to some computer that doesn't have a second task yet. Transitions involve either assigning the task as a first task to some computer that has no tasks yet (increasing $k$, increasing the value by the value of the $i$-th task) or assigning the task to some computer that has a first task (decreasing $j$, not changing the value). Whenever $i$-th task's power differs from $i - 1$st task, $j$ increases by $k$, and $k$ becomes equal to zero. The minimal sum of task values is then equal to the minimum of $dp[n][j][k]$ over all $j, k$. Update the state of the binary search depending on whether the minimal sum is greater than zero or not. Note that this is $O(n^{3})  \\times  log(precision)$. As an exercise, find a solution that is $O(n^{2})  \\times  log(precision)$",
    "tags": [
      "binary search",
      "dp",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "993",
    "index": "E",
    "title": "Nikita and Order Statistics",
    "statement": "Nikita likes tasks on order statistics, for example, he can easily find the $k$-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number $x$ is the $k$-th number in increasing order on this segment. In other words, you should find the number of segments of a given array such that there are exactly $k$ numbers of this segment which are less than $x$.\n\nNikita wants to get answer for this question for each $k$ from $0$ to $n$, where $n$ is the size of the array.",
    "tutorial": "First, we can find amount of numbers that less than $x$ for each prefix of $a$ (including empty prefix). We get array $s$ of this values. You can see that for each $i,j, i < j$ the truth that $s[i] \\leq s[j]$ and if $s[i]<s[j]$ then $i<j$. Let's count array $r$ such that $r[i]$ is number of occurences $i$ in $s$. Then answer for each $d$ from $1$ to $k$ answer $ans[d]$ is $\\sum_{i,j,i-j=d} r[i] \\cdot r[j]$. Let's create array $v$, $v[i]=r[n-i]$. If $p = r \\times v$ then $p[n+d]=\\sum_{i,h,i+h=n+d} r[i] \\cdot v[h] =\\sum_{i,j,i+n-j=n+d} r[i] \\cdot r[j] = \\sum_{i,j,i-j=d} r[i] \\cdot r[j]= ans[d]$. Multiplication $r$ and $v$ can be done by FFT. You should write it accuracy or use extended floating point types because values in $p$ can reach $10^{10}$. Also you can use NTT by two modules and Chinese Remainder Theorem. Case $k=0$ should be processed separately because of if $s[i] \\leq s[j]$ it's not true that $i<j$. We can get answer easily by using set or array of labels. Time complexity is $O(n \\cdot \\log (n))$.",
    "tags": [
      "chinese remainder theorem",
      "fft",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "993",
    "index": "F",
    "title": "The Moral Dilemma",
    "statement": "Hibiki and Dita are in love with each other, but belong to communities that are in a long lasting conflict. Hibiki is deeply concerned with the state of affairs, and wants to figure out if his relationship with Dita is an act of love or an act of treason.\n\nHibiki prepared several binary features his decision will depend on, and built a three layer logical circuit on top of them, each layer consisting of one or more logic gates. Each gate in the circuit is either \"or\", \"and\", \"nor\" (not or) or \"nand\" (not and). Each gate in the first layer is connected to exactly two features. Each gate in the second layer is connected to exactly two gates in the first layer. The third layer has only one \"or\" gate, which is connected to all the gates in the second layer (in other words, the entire circuit produces 1 if and only if at least one gate in the second layer produces 1).\n\nThe problem is, Hibiki knows very well that when the person is in love, his ability to think logically degrades drastically. In particular, it is well known that when a person in love evaluates a logical circuit in his mind, every gate evaluates to a value that is the opposite of what it was supposed to evaluate to. For example, \"or\" gates return 1 if and only if both inputs are zero, \"t{nand}\" gates produce 1 if and only if both inputs are one etc.\n\nIn particular, the \"or\" gate in the last layer also produces opposite results, and as such if Hibiki is in love, the entire circuit produces 1 if and only if all the gates on the second layer produced 0.\n\nHibiki can’t allow love to affect his decision. He wants to know what is the smallest number of gates that needs to be removed from the second layer so that the output of the circuit for all possible inputs doesn't depend on whether Hibiki is in love or not.",
    "tutorial": "First lets observe that for the original and the inverted circuit to return the same value for each input, for each possible input one of the two conditions must be met: either in the original circuit all the gates in the second layer return 0, or in the inverted circuit all the gates in the second layer return 0. This in turn means, that for each input *each* gate in the second layer must return zero in either original or inverted circuit. Since its output only depends on at most two gates in the first layer, and at most four inputs, we can iterate over all possible configurations of gates in the first layer, gate in the second layer, and connections to the inputs to find all configurations that meet this criteria. All these configurations will share an important property: for a gate to return zero for each input in either the original or inverted circuit, it must either return zero in the original circuit for all inputs, or return zero in the inverted circuit for all inputs. Some of these configurations (e.g. $and(nand(a,b),and(a,b))$) always return 0 in one circuit, and 1 in the opposite circuit. Other configurations (e.g. $and(and(a,b), nor(a,c))$) return 0 in one circuit, and something depending on the input in another, but critically 0 for the case of all inputs equal to 1. For a circuit to meet the condition in the problem, it needs to have gates such that all of them return zero in either original or inverted circuit, and at least one of them to return one in the other circuit. WLOG let's consider the case of all gates returning zero in the original configuration, and at least one returning zero in the inverted configuration. Such circuit has two properties: 1. The circuit only contains the following gates in the second layer: $and(nand(a,b), and(a,b))$, $and(or(a,b), nor(a,b))$, $nor(nand(a,b), and(a,b))$, $nor(or(a,b), nor(a,b))$, $and(and(a,b), nor(a,c))$, $nor(nand(a,b), or(a,b))$. The first four of them in the inverted graph will always return 1, and the last two will return something depending on the input. 2. The circuit contains at least one of the first four gate kinds, and having at least one such gate is sufficient for the circuit to meet the condition from the problem. The latter is easy to show: since each of the first four gate kinds always returns 1 in the inverted mode, having it is sufficient to have at least one gate return 1 in the second layer. To show the former, remember that the last two gates return zero in the inverted mode when all three inputs are ones. It means that no matter how many of last two kinds of gates we have, and no matter how they are wired with the inputs, if all the inputs are equal to 1, all such gates will return 0, and at least one gate of the first four kinds will be necessary to have at least one gate to return 1. From here the solution is trivial: to find the largest subset of the gates in the second layer that would all return 0 in the original circuit, and at least one return 1 in the inverted, we choose the largest set of gates that belong to the abovementioned set, for as long as at least one of them belongs to the first four kinds. If no gate in the second layer belongs to the first four kinds, the desired subset doesn't exist. Solution for the case when the inverted circuit has all gates in the second layer always return zero and original has at least one that returns one is solved similarly.",
    "tags": [],
    "rating": 3200
  },
  {
    "contest_id": "994",
    "index": "A",
    "title": "Fingerprints",
    "statement": "You are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.\n\nSome keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subsequence of the sequence you have that only contains digits with fingerprints on the corresponding keys. Find such code.",
    "tutorial": "The problem can be solved by iterating over every number of the sequence, then iterating over the sequence of fingerprints to check if the number corresponds to a key with a fingerprint, resulting in an $O(n \\times m)$ solution.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "994",
    "index": "B",
    "title": "Knights of a Polygonal Table",
    "statement": "Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $k$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.\n\nNow each knight ponders: how many coins he can have if only he kills other knights?\n\nYou should answer this question for each knight.",
    "tutorial": "Sort the knights by increasing the power. Now we can iterate over an array and greedy store set of $k$ prevous knights with maximum if coins. After handling knight, if set contains less than $k$ elements, we add current knight in set. Else if number of coins from current knight greater than from knight with minimum coins in set, we can replace this knight with current knight. You can store the set in vector, multiset or priority_queue. Be careful with overflowing and corner case $k=0$. Time complexity is $O(n \\cdot k)$ or $O(n \\cdot \\log(k))$.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "995",
    "index": "A",
    "title": "Tesla",
    "statement": "Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.\n\nAllen's future parking lot can be represented as a rectangle with $4$ rows and $n$ ($n \\le 50$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $k$ ($k \\le 2n$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.\n\n\\begin{center}\n{\\small Illustration to the first example.}\n\\end{center}\n\nHowever, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.\n\nAllen knows he will be a very busy man, and will only have time to move cars at most $20000$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.",
    "tutorial": "First, whenever any cars are directly to their parking spot, we should move them into the correct parking spot. Now, we can view rows $2$ and $3$ as a cycle. In at most $k$ moves, we can spin the entire cycle of cars counterclockwise. By repeating this $2n$ times, each car will have been adjacent to each parking space, and will have had some chance to park. The exception to this rule is when there are no empty spaces in rows $2$ and $3$. In this case, no cars can even make a valid move, so the answer is $-1$. (This requires $k = 2n$ and no cars are initially adjacent to their parking space) This process will can be implemented in $O(nk)$ or $O(n^2)$ time, with at most $2nk + k \\le 10100$, which fits below the $20000$ move limit.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "995",
    "index": "B",
    "title": "Suit and Tie",
    "statement": "Allen is hosting a formal dinner party. $2n$ people come to the event in $n$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $2n$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.\n\nHelp Allen find the minimum number of swaps of \\textbf{adjacent} positions he must perform to make it so that each couple occupies adjacent positions in the line.",
    "tutorial": "We describe a greedy algorithm that achieves the minimum number of swaps. If the leftmost person is in pair $a$, swap the other person in pair $a$ left, to the second position. Now the first two people are both in pair $a$, and we repeat the process on the remaining $n-1$ pairs of people recursively. We now prove that this number of swaps is optimal, and we accomplish this by showing that every swap we made is 'necessary'. For two pairs numbered $a$ and $b$, we can consider the number of times people of pair $a$ and $b$ are swapped by our process. There are $3$ possible relative orderings: $a a b b$, $a b a b$, and $a b b a$. In the case $a a b b$, our algorithm will never swap $a$ and $b$. In the case $a b a b$, any correct swap sequence must swap $a$ and $b$ at least once, and our algorithm will swap the second $a$ left of the first $b$ when $a$ is the leftmost person. In the case $a b b a$, any correct swap sequence must swap $a$ and $b$ at least twice, and our algorithm will swap the second $a$ left of both $b$ when $a$ is the leftmost person. Therefore every swap in our greedy algorithm is necessary, so it is optimal. We can directly simulate this algorithm in $O(n^2)$ time. We can also use data structures such as a binary indexed tree, or balanced binary search tree to compute the answer in $O(n \\log n)$. (Maybe it can be even done in $O(n)$, anyone?).",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "995",
    "index": "C",
    "title": "Leaving the Bar",
    "statement": "For a vector $\\vec{v} = (x, y)$, define $|v| = \\sqrt{x^2 + y^2}$.\n\nAllen had a bit too much to drink at the bar, which is at the origin. There are $n$ vectors $\\vec{v_1}, \\vec{v_2}, \\cdots, \\vec{v_n}$. Allen will make $n$ moves. As Allen's sense of direction is impaired, during the $i$-th move he will either move in the direction $\\vec{v_i}$ or $-\\vec{v_i}$. In other words, if his position is currently $p = (x, y)$, he will either move to $p + \\vec{v_i}$ or $p - \\vec{v_i}$.\n\nAllen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position $p$ satisfies $|p| \\le 1.5 \\cdot 10^6$ so that he can stay safe.",
    "tutorial": "We first prove a claim which will help us significantly. The claim is that among any three vectors $\\vec{v_1}, \\vec{v_2}, \\vec{v_3}$ of lengths at most $r$, then some sum $\\vec{v_i} + \\vec{v_j}$ or difference $\\vec{v_i} - \\vec{v_j}$ has at length at most $r$. Draw a circle with radius $r$ centered at the origin. If we plot the vectors $\\vec{v_1}, \\vec{v_2}, \\vec{v_3}, -\\vec{v_1}, -\\vec{v_2},-\\vec{v_3}$ from the origin, two of these will lie in the same $60^{\\circ}$ sector. Any two points in this sector will have distance at most $r$. Therefore, as long as there are at least $3$ vectors, two of them can be combined and the input constraints will still be satisfied. In the final step, we can combine two vectors of length at most $r$ into one of length at most $\\sqrt{2} r$. Implementation can be done in a number of ways: for example, constructing a binary tree with the input vectors as leaves, or maintaining sets of signed vectors and merging small sets to large sets. These approaches can take $O(n)$ or $O(n \\log n)$.",
    "tags": [
      "brute force",
      "data structures",
      "geometry",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "995",
    "index": "D",
    "title": "Game",
    "statement": "Allen and Bessie are playing a simple number game. They both know a function $f: \\{0, 1\\}^n \\to \\mathbb{R}$, i. e. the function takes $n$ binary arguments and returns a real value. At the start of the game, the variables $x_1, x_2, \\dots, x_n$ are all set to $-1$. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an $i$ such that $x_i = -1$ and either setting $x_i \\to 0$ or $x_i \\to 1$.\n\nAfter $n$ rounds all variables are set, and the game value resolves to $f(x_1, x_2, \\dots, x_n)$. Allen wants to maximize the game value, and Bessie wants to minimize it.\n\nYour goal is to help Allen and Bessie find the expected game value! They will play $r+1$ times though, so between each game, exactly one value of $f$ changes. In other words, between rounds $i$ and $i+1$ for $1 \\le i \\le r$, $f(z_1, \\dots, z_n) \\to g_i$ for some $(z_1, \\dots, z_n) \\in \\{0, 1\\}^n$. You are to find the expected game value in the beginning and after each change.",
    "tutorial": "One can show by induction that the expected value of the game is $\\mathbb{E}[f] = 2^{-n} \\sum_{x \\in \\{0, 1\\}^n} f(x)$. Consider the first turn. For notation, let $v_{i, 0}$ be the expected value of the game when $x_i$ is set to $0$, and let $v_{i, 1}$ be the expected value of the game when $x_i$ is set to $1$. By induction, it is easy to see that $\\frac{v_{i, 0} + v_{i, 1}}{2} = \\mathbb{E}[f].$ Consider Allen's strategy. If it is Allen's turn, he will set $x_s = t$, where $0 \\le s < n, 0 \\le t \\le 1$ are such that $v_{s, t}$ is maximal. As $\\frac{v_{i, 0} + v_{i, 1}}{2} = \\mathbb{E}[f]$ for all $i$, it is clear that $v_{s, 1-t}$ is actually minimal among all the $v_{i, j}$. This means that Bessie would have chosen to set $x_s = 1-t$ if it were her turn. Therefore, the expected game value is $\\frac{v_{s, t} + v_{s, 1-t}}{2} = \\mathbb{E}[f].$",
    "tags": [
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "995",
    "index": "E",
    "title": "Number Clicker",
    "statement": "Allen is playing Number Clicker on his phone.\n\nHe starts with an integer $u$ on the screen. Every second, he can press one of 3 buttons.\n\n- Turn $u \\to u+1 \\pmod{p}$.\n- Turn $u \\to u+p-1 \\pmod{p}$.\n- Turn $u \\to u^{p-2} \\pmod{p}$.\n\nAllen wants to press at most 200 buttons and end up with $v$ on the screen. Help him!",
    "tutorial": "Our first observation is that the game can be modeled the following way. Construct an undirected graph on $\\{0, 1, \\dots, p-1\\}$ such that $i$ is connected to $i-1, i+1,$ and $i^{p-2} \\pmod{p}.$ We want to find a path of length at most 200 between $u$ and $v$ in this graph. Running a BFS will take too long, so we need different techniques. We present two solutions, which both essentially use the fact that the graph is almost \"random\". This follows from some known number theoretic results on expander graphs (keyword is \"Margulis expanders\"). Solution 1: Generate $\\sqrt{p}$ random paths of length $100$ from vertex $u$. Now, generate random paths from $v$ of length $100$ until some pair of endpoints coincide. By the birthday paradox, assuming that the graph is approximately random, the runtime will be $O(\\sqrt{p} \\log p).$ Solution 2: We can try running a simultaneous BFS from both directions (starting at $u$ and $v$). When they meet, make that path. If you are careful, it should be possible to cover $\\le 10^7$ vertices, which should then run in time. Additionally, our tester found a different solution. It suffices to find a path from $u \\to 1$ of length $100.$ The way we do this is: pick a random $x \\pmod{p}.$ Now run the Euclidean algorithm on $(ux \\pmod{p}, x)$, using operation $2$ for a normal subtraction step, and a $3$ for the flipping the two entries step. It happens to take a few steps in most cases, but we have no proof.",
    "tags": [
      "divide and conquer",
      "graphs",
      "meet-in-the-middle",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "995",
    "index": "F",
    "title": "Cowmpany Cowmpensation",
    "statement": "Allen, having graduated from the MOO Institute of Techcowlogy (MIT), has started a startup! Allen is the president of his startup. He also hires $n-1$ other employees, each of which is assigned a direct superior. If $u$ is a superior of $v$ and $v$ is a superior of $w$ then also $u$ is a superior of $w$. Additionally, there are no $u$ and $v$ such that $u$ is the superior of $v$ and $v$ is the superior of $u$. Allen himself has no superior. Allen is employee number $1$, and the others are employee numbers $2$ through $n$.\n\nFinally, Allen must assign salaries to each employee in the company including himself. Due to budget constraints, each employee's salary is an integer between $1$ and $D$. Additionally, no employee can make strictly more than his superior.\n\nHelp Allen find the number of ways to assign salaries. As this number may be large, output it modulo $10^9 + 7$.",
    "tutorial": "A immediate simple observation is that we can compute the answer in $O(nD)$ with a simple dynamic program. How to speed it up though? To speed it up, we need the following lemma. Lemma 1: For a tree with $n$ vertices, the answer is a polynomial in $D$ of degree at most $n$. We can prove this via induction, and the fact that for any polynomial $p(x)$ of degree $d$, the sum $p(0) + p(1) + \\dots + p(n)$ is a polynomial in $n$ of degree $d+1.$ Now the solution is easy: compute the answer for $0 \\le D \\le n$ and use interpolation to compute the answer for $D > n.$ The complexity is $O(n^2)$ for the initial dp and $O(n)$ for the interpolation step.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "996",
    "index": "A",
    "title": "Hit the Lottery",
    "statement": "Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance?",
    "tutorial": "The problem is to minimize $x_1 + x_2 + x_3 + x_4 + x_5$ given that $x_1 + 5x_2 + 10x_3 + 20x_4 + 100x_5 = n.$ It is pretty simple to see that we can operate greedily: take as many $100$ as we can, then $20$, then $10$, etc. The solutions works because each number in the sequence $1, 5, 10, 20, 100$ is a divisor of the number after it.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "996",
    "index": "B",
    "title": "World Cup",
    "statement": "Allen wants to enter a fan zone that occupies a round square and has $n$ entrances.\n\nThere already is a queue of $a_i$ people in front of the $i$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.\n\nAllen uses the following strategy to enter the fan zone:\n\n- Initially he stands in the end of the queue in front of the first entrance.\n- Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance).\n\nDetermine the entrance through which Allen will finally enter the fan zone.",
    "tutorial": "For gate $k$ (where $1 \\le k \\le n$) we visit the gate at times $k, k+n, k+2n, \\cdots$ Therefore, the earliest Allen could enter from gate $k$ is the time $k + tn$ such that $k + tn \\ge a_k.$ Now, for each $k$, compute the minimal integer $b_k = k+tn$ such that $k+tn \\ge a_k$. Now, find the integer $k$ with minimum $b_k$ and output $k$.",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "997",
    "index": "A",
    "title": "Convert to Ones",
    "statement": "You've got a string $a_1, a_2, \\dots, a_n$, consisting of zeros and ones.\n\nLet's call a sequence of consecutive elements $a_i, a_{i + 1}, \\ldots, a_j$ ($1\\leq i\\leq j\\leq n$) a substring of string $a$.\n\nYou can apply the following operations any number of times:\n\n- Choose some substring of string $a$ (for example, you can choose entire string) and reverse it, paying $x$ coins for it (for example, «{01\\underline{011}01}» $\\to$ «{01\\underline{110}01}»);\n- Choose some substring of string $a$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $y$ coins for it (for example, «{01\\underline{011}01}» $\\to$ «{01\\underline{100}01}»).\n\nYou can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.\n\nWhat is the minimum number of coins you need to spend to get a string consisting only of ones?",
    "tutorial": "Let's partite consecutive elements of the same color into groups. For example, we will split <<00011001110>> into <<000>> + <<11>> + <<00>> + <<111>> + <<0>>. Then it is obvious that it is useless to make moves within one group, and then (if we have at least two groups of color $0$) for one move we can reduce by one (and can't reduce by two) the number of segments of color $0$, paying for it either $x$ or $y$ (whatever). Let's consider, for example, if we have a string <<11001100>>, we can flip the segment $[5 \\dots 8]$, and turn it into a string <<11000011>>, or, for example, invert the segment $[3 \\dots 4]$, turning the string into <<111111111100> (Then the number of color groups $0$ decreased from two to one). But in the end you still need to do at least one inverting of the segment (which will be one at the end). Then let $p$ - number of groups of color $0$. If $p = 0$, the answer is $0$. Otherwise, the answer is $(p-1) \\cdot \\min(x, y) + y$",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "997",
    "index": "B",
    "title": "Roman Digits",
    "statement": "Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $1$, $5$, $10$ and $50$ respectively. The use of other roman digits is not allowed.\n\nNumbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it.\n\nFor example, the number XXXV evaluates to $35$ and the number IXI — to $12$.\n\nPay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means $11$, not $9$.\n\nOne can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by \\textbf{exactly} $n$ roman digits I, V, X, L.",
    "tutorial": "TL; DR - among all the sequences, select the one, which contains the maximum number of $50$, in case of tie, select one with largest number of $9$. Bruteforce all configurations in such way, that each number is counted only in it's \"maximum\" configuration. Since the length of sequence is fixed, we can solve problem not for digits $\\{1, 5, 10, 50\\}$, but for digits $\\{0, 4, 9, 49\\}$. Let's solve the problem for digits $\\{0, 4, 9\\}$ first. We have a problem that some numbers have many representations. But this, in fact, is easy to deal with - if we have at least nine digits \"4\" than we can convert them no some number of \"9\" digits, and fill the rest with zeroes. In this case, the solution is to bruteforce the number of \"4\" from $0$ to $min(8, n)$, and then from the remaining digits select any arbitrary number of \"9\", each such choice leads to an unique number. Let's return to the original problem with $\\{0, 4, 9, 49\\}$. In this case we can also face the situation, when the number of $49$ can be increased. We need to identify all pairs $(x, y)$ where $x, y \\le 50$, such that they can be transformed to other pair $(x', y')$ with detachment of few $49$. We can bruteforce all $x$, $y$, $x'$, $y'$ with four nested for-loops and check, that the sum of first differs from sum of latter by few number of $49$ removed, in such case we mark the pair $(x, y)$ as broken. We can also note, that if some pair is marked as broken, than all \"dominating\" pairs also marked as broken. When we discovered which pairs are good we can simply: --- Another solution: if you examine the solution above precisely, you will notice that starting some reasonable $n$ (you can easy proof a lowerbound like $50$ or $100$, but it is, in fact, $12$), the function grows linearly. So if $n \\le 12$, you count the answer in any stupid way, and otherwise, simply approximate it linearly using $answer(12)$ and $answer(13)$.",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "997",
    "index": "C",
    "title": "Sky Full of Stars",
    "statement": "On one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game.\n\nIt is well known that one month on this planet consists of $n^2$ days, so calendars, represented as square matrix $n$ by $n$ are extremely popular.\n\nWeather conditions are even more unusual. Due to the unique composition of the atmosphere, when interacting with sunlight, every day sky takes one of three colors: blue, green or red.\n\nTo play the bingo, you need to observe the sky for one month — after each day, its cell is painted with the color of the sky in that day, that is, blue, green or red.\n\nAt the end of the month, students examine the calendar. If at least one row or column contains only cells of one color, that month is called lucky.\n\nLet's call two colorings of calendar different, if at least one cell has different colors in them. It is easy to see that there are $3^{n \\cdot n}$ different colorings. How much of them are lucky? Since this number can be quite large, print it modulo $998244353$.",
    "tutorial": "Let $A_i$ be the set of all colorings, where $i$-th line contains only one color, and $B_i$ be the set of colorings, where $i$-th column contains only one color. This way, you need to calculate $|A_1 \\cup A_2 \\ldots A_n \\cup B_1 \\cup B_2 \\ldots B_n|$. As usual, we can use inclusion-exclusion formula to reduce the calculation of multiplications to calculation all possible intersections of sets above. More over, due to the obvious symmetry, to calculate the size of intersection of some set of $A_i$ and $B_i$ it is not important to know exact indices - only number of taken $A$-s and number of $B$-s. This way $ans = \\sum_{i=0 \\ldots n, j=0 \\ldots n, i + j > 0} C_n^i C_n^j (-1)^{i + j + 1} f(i, j)$ Where $f(i, j)$ - is the number of colorings, where first $i$ rows and first $j$ columns are onecolored. It turns out, that formula for $f$ differs significantly depending on presence of zero in it's arguments. Let's examine the case where zero is present, the $f(0, k) = 3^k \\cdot 3^{n (n - k)}$. Indeed, you should choose one color in each of the first $k$ columns, and the rest should be painted in any way. -- If both arguments are $> 0$, that is, there is at least one one-colored column and at least one-colored row, than we can notice, that all one-colored rows and columns are in fact of one color. This way, $f(i, j) = 3 \\cdot 3^{(n - i)(n - j)}$ Since we should first select the globally common color, and then paint all the rest in any way. Summation of all $f$-s gives solution with $\\mathcal{O}(n^2)$ or $\\mathcal{O}(n^2 \\log)$ complexity, depending on implementation. But we need to go faster. -- Let's sum all summands with $i = 0$ or $j = 0$ in a stupid way, in $\\mathcal{O}(n)$. Then examine all other summands. We have a formula: $ans = \\sum_{i=1}^{n} \\sum_{j=1}^{n} C_n^i C_n^j (-1)^{i + j + 1} 3 \\cdot 3^{(n - i)(n - j)}$ Let's replace our variables: $i \\to n - i$, $j \\to n - j$. $ans = 3 \\sum_{i=0}^{n - 1} \\sum_{j = 0}^{n - 1} C_n^{n - i} C_n^{n - j} (-1)^{n - i + n - j + 1} \\cdot 3^{ij}$ Since $C_n^{n - i} = C_n^i$, $(-1)^{2n} = 1$, $(-1)^{-i} = (-1)^{i}$ we have $ans = 3 \\sum_{i=0}^{n - 1} \\sum_{j = 0}^{n - 1} C_n^i C_n^j (-1)^{i + j + 1} \\cdot 3^{ij}$ Note, that $(a + b)^n = \\sum_{i = 0}^{n} C_n^i a^i b^{n - i}$. Using this, we can collect all summands for fixed $i$, however with fixed $i$ we have not $n$ summands, but $n - 1$. We can workaround it by adding and removing the missing summand. -- Let's go: $ans = 3 \\sum_{i=0}^{n - 1} \\sum_{j = 0}^{n - 1} C_n^i C_n^j (-1)^{i + j + 1} \\cdot 3^{ij}$ $ans = 3 \\sum_{i=0}^{n - 1} C_n^i (-1)^{i+1} \\sum_{j = 0}^{n - 1} C_n^j (-1)^{j} \\cdot (3^i)^j$ $ans = 3 \\sum_{i=0}^{n - 1} C_n^i (-1)^{i+1} \\sum_{j = 0}^{n - 1} C_n^j (- 3^i)^j$ $ans = 3 \\sum_{i=0}^{n - 1} C_n^i (-1)^{i+1} [(1 + (-3^i))^n - (-3^i)^n]$ -- This formula has only $\\mathcal{O}(n)$ summands, and hence can be evaluated fast enough. To calculate powers of number fast, we can use binary pow method.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "997",
    "index": "D",
    "title": "Cycles in product",
    "statement": "Consider a tree (that is, an undirected connected graph without loops) $T_1$ and a tree $T_2$. Let's define their cartesian product $T_1 \\times T_2$ in a following way.\n\nLet $V$ be the set of vertices in $T_1$ and $U$ be the set of vertices in $T_2$.\n\nThen the set of vertices of graph $T_1 \\times T_2$ is $V \\times U$, that is, a set of ordered pairs of vertices, where the first vertex in pair is from $V$ and the second — from $U$.\n\nLet's draw the following edges:\n\n- Between $(v, u_1)$ and $(v, u_2)$ there is an undirected edge, if $u_1$ and $u_2$ are adjacent in $U$.\n- Similarly, between $(v_1, u)$ and $(v_2, u)$ there is an undirected edge, if $v_1$ and $v_2$ are adjacent in $V$.\n\nPlease see the notes section for the pictures of products of trees in the sample tests.\n\nLet's examine the graph $T_1 \\times T_2$. How much cycles (not necessarily simple) of length $k$ it contains? Since this number can be very large, print it modulo $998244353$.\n\nThe sequence of vertices $w_1$, $w_2$, ..., $w_k$, where $w_i \\in V \\times U$ called cycle, if any neighboring vertices are adjacent and $w_1$ is adjacent to $w_k$. Cycles that differ only by the cyclic shift or direction of traversal are still considered \\textbf{different}.",
    "tutorial": "Consider an arbitrary cycle in a graph product. Due to the definition of the product, the adjacent vertices in the cycle correspond to the transition by the edge either in the first tree or in the second tree. This way, if you write the edges corresponding to one tree in a separate list, you will get a cycle in this tree. Also, if we have a cycle in one tree of length $a$ and a cycle of length $b$ in the second tree, we can make $C_{a+b}^a$ cycles in the product. Thus, the problem is reduced to calculating for each length up to $k$ the number of cycles in each tree separately, and then mixing them into cycles in the product. -- Let's select the centroid $c$ of the tree and count all cycles, which go through it, delete centroid and then recursively count in remaining components. How looks cycle which goes through $c$? We need to start in some vertex $v$, then go to $c$ (not going through $c$ in between), and then go back to $v$, possibly going through $c$. Let's define two dp's: $f[v][k]$ - number of ways to go from $c$ to $v$ by exactly $k$ steps not going through $c$ in between, $g[v][k]$ - number of ways to go from $c$ to $v$, but without previous limitation. This way the answer for $v$ through centroid $c$ in convolution of $f[v]$ and $g[v]$: $ans[i+j] += f[v][i] * g[v][j]$. Case where $v = c$ should be processed separately, in this case we can simply $ans[i] += g[c][i]$. How much time it takes to compute dp? In fact, it is $\\mathcal{O}(nk)$, $g[v][i]$ is equal to sum of $g[u][i - 1]$ where $u$ is neighbor of $v$. Since the graph is tree, there are $\\mathcal{O}(n)$ neighbors in total and $\\mathcal{O}(nk)$ transitions. $f[v]$ is counted the same way, but with removed transitions through $c$. -- The final complextiy is: $\\mathcal{O}(n k^2 log(n))$. $\\O(\\log(n))$ is for centroid decomposition. On one level we need to compute dp $\\mathcal{O}(nk)$ and then compute convolution $\\mathcal{O}(nk^2)$, so it is $\\mathcal{O}(n k^2 log(n))$. Solution can be optimized with fast polynomial multiplication, leading to complexity $\\mathcal{O}(n k \\log(k) log(n))$, but it wasn't required.",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "997",
    "index": "E",
    "title": "Good Subsegments",
    "statement": "A permutation $p$ of length $n$ is a sequence $p_1, p_2, \\ldots, p_n$ consisting of $n$ distinct integers, each of which from $1$ to $n$ ($1 \\leq p_i \\leq n$) .\n\nLet's call the subsegment $[l,r]$ of the permutation \\textbf{good} if all numbers from the minimum on it to the maximum on this subsegment occur among the numbers $p_l, p_{l+1}, \\dots, p_r$.\n\nFor example, good segments of permutation $[1, 3, 2, 5, 4]$ are:\n\n- $[1, 1]$,\n- $[1, 3]$,\n- $[1, 5]$,\n- $[2, 2]$,\n- $[2, 3]$,\n- $[2, 5]$,\n- $[3, 3]$,\n- $[4, 4]$,\n- $[4, 5]$,\n- $[5, 5]$.\n\nYou are given a permutation $p_1, p_2, \\ldots, p_n$.\n\nYou need to answer $q$ queries of the form: find the number of good subsegments of the given segment of permutation.\n\nIn other words, to answer one query, you need to calculate the number of good subsegments $[x \\dots y]$ for some given segment $[l \\dots r]$, such that $l \\leq x \\leq y \\leq r$.",
    "tutorial": "Let's look at two solutions for all array, and each of them can be upgraded to subquadratic time for queries on subsegments. First solution is Divide&Conquer. Let's take a middle of the array and find number of segments, that contain it. If minimum and maximum are at one side of middle, then by the end on the half where they are, you can restore the entire segment and check that it is correct (and remember it somewhere). Else let them be on different sides. Then let maximum will be at the right (other case are symmetric and you can solve them similarly), so we need $r - l = \\max - \\min$, but we already know $r$ and $\\max$ , so we can get $r - \\max = l - \\min$. Then let's partite the elements into equivalence classes, where we broke into classes by $r - \\max$ if element on the left and $l - \\min$ if element on the right (where the $\\max$ and $\\min$ is the minimum and maximum on the segment to the middle $m$), then the segment $l \\leq m < r$ (where the maximum on the left) is good if and only if when in the interval $[l \\dots m]$ there are no numbers less than minimum on the interval $(m, \\dots r]$ and the interval $(m, \\dots r]$ has no numbers larger than maximum on the interval $[l \\dots m]$, and $l$ and $r$ are in the same class. Then, for one segment end, some interval of elements from its class is suitable (these intervals can be selected, for example, by stack or a binary search). Also you need (don't forget it!) to go recursively to the left half and to the right half :) And then you can apply the Mo's algorithm! Let's move the left and right ends, run through the classes where this end lies, and add/subtract from the answer the size of the intersection of the interval of this class that fits this end and the interval of this class that current segment now contains, so this part works for $O(n \\sqrt{n} \\log {n})$ (but operations are not so heavy, so it is working fast). Also you need to not forget about the segments where the minimum and maximum contained at one side of the middle, they can be processed, for example, by passing with a sweep line with a fenwick tree, this part works in $O(n \\log {n})$. So we can upgrade D&C idea to $O(n \\sqrt{n} \\log {n})$. But let's look at the geometric interpretation of the problem. Let good segments be points $(l, r)$ on the plane! Then the query is just the sum on the rectangle $[1 \\dots l] [r \\dots n]$. To solve the problem on the whole array, let's move the right end of the query, and for each left we will store $r - l - (\\max - \\min)$, this can be stored in the segment tree (and you can recalculate it with stacks), and then you can note that values always are $\\leq 0$, so you can simply store in the segment tree the maximum and number of maximums, and at each time add this value to the answer. In order to generalize this idea for a complete solution, let's split the field $N \\times N$ into squares $K \\times K$ (Colors are not important, they are just for convenience). Then let's go with the same sweep line from left to right, but we will store everything not in the segment tree, but in the sqrt decomposition. And we will store for a piece of size $K$ by $y$-coordinate the number of (good segments) points that we have already met in it. So we can cut off from the original query The lower part, leaving a horizontal strip of size $\\leq K$. We made it in $O(n \\cdot k + n \\cdot \\frac{n}{k})$. With similar sweep line from top to bottom, and not from left to right, we can cut off the left part, leaving as a query a rectangle with sides $< K$. Then you can create $< K$ events of the form: \"Add the sum on the vertical segment to the answer to $i$-th query\", and these events can be processed by a sweep line from left to right with the segment tree , so you can solve this part in $O(n \\cdot k \\cdot \\log{n})$. So we can get a solution in $O(n \\cdot \\frac{n}{k} + n \\cdot k \\cdot \\log{n})$, and choosing $k = \\sqrt{\\frac{n}{\\log{n}}}$ allows to solve the task in $O(n \\cdot \\sqrt{n \\cdot \\log{n}})$.",
    "tags": [
      "data structures"
    ],
    "rating": 3000
  },
  {
    "contest_id": "998",
    "index": "A",
    "title": "Balloons",
    "statement": "There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.\n\nGrigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ packets with inflatable balloons, where $i$-th of them has exactly $a_i$ balloons inside.\n\nThey want to divide the balloons among themselves. In addition, there are several conditions to hold:\n\n- Do not rip the packets (both Grigory and Andrew should get unbroken packets);\n- Distribute all packets (every packet should be given to someone);\n- Give both Grigory and Andrew at least one packet;\n- To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets.\n\nHelp them to divide the balloons or determine that it's impossible under these conditions.",
    "tutorial": "It is easy to show, that if at least one solution exists, than it is possible to use the answer, which contains only one, minimal, element. Suppose, that this set is not valid. Then one of the following holds: Either $n = 1$, and then there is no solution Or $n = 2$, and other element is equal to minimum, in this case it is ease to see that there are not solution too. Also, the limits were set in such way, that solution which bruteforces all $2^n$ subsets and checks them also passes.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "998",
    "index": "B",
    "title": "Cutting",
    "statement": "There are a lot of things which could be cut — trees, paper, \"the rope\". In this problem you are going to cut a sequence of integers.\n\nThere is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulting segment will have the same number of odd and even integers.\n\nCuts separate a sequence to continuous (contiguous) segments. You may think about each cut as a break between two adjacent elements in a sequence. So after cutting each element belongs to exactly one segment. Say, $[4, 1, 2, 3, 4, 5, 4, 4, 5, 5]$ $\\to$ two cuts $\\to$ $[4, 1 | 2, 3, 4, 5 | 4, 4, 5, 5]$. On each segment the number of even elements should be equal to the number of odd elements.\n\nThe cost of the cut between $x$ and $y$ numbers is $|x - y|$ bitcoins. Find the maximum possible number of cuts that can be made while spending no more than $B$ bitcoins.",
    "tutorial": "It is possible to proof, that cut after $i$-th number can be done if and only if the prefix of length $i$ contains equal number of odd and even numbers. This way each cut can be done or not done independently of all other cuts (except the budget issue). Why it is true? Let's proof that criterion is sufficient. If you make some set of cuts, where each cut is valid according to criterion above, than the result would be correct - each part of result lies between to cuts, and if prefixes which correspond to cuts have same number of odds-evens, than the part between also will have these numbers equal. Let's show that the condition is required - if there is some set of cuts, which produces correct parts, than each part has same number of odds-evens, and than all prefixes, which correspond to cuts also have the same number of odds-evens. This way each cut can be done independently, so you can identify all valid cuts, order them by cut-price, and take greedy from the beginning of the list while the budget allows.",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "999",
    "index": "A",
    "title": "Mishka and Contest",
    "statement": "Mishka started participating in a programming contest. There are $n$ problems in the contest. Mishka's problem-solving skill is equal to $k$.\n\nMishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses which end (left or right) he will solve the next problem from. Thus, each problem Mishka solves is either the leftmost or the rightmost problem in the list.\n\nMishka cannot solve a problem with difficulty greater than $k$. When Mishka solves the problem, it disappears from the list, so the length of the list decreases by $1$. Mishka stops when he is unable to solve any problem from any end of the list.\n\nHow many problems can Mishka solve?",
    "tutorial": "You can iterate over all the elements of the array from left to right. Count the number of problems Mishka will solve from the left end of the list and break if he cannot solve the next one. Let's denote the number of problems Mishka will solve from the left end of the list by $\\mathit{lf}$. Do the same thing independently from right to left. Denote the number of problems Mishka will solve from the right end of the list by $\\mathit{rg}$. Then the answer is $\\min(n, \\mathit{lf} + \\mathit{rg})$. Time complexity - $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tcin >> a[i];\n\t\n\tint ans = 0;\n\twhile (!a.empty() && a.back() <= k) {\n\t\t++ans;\n\t\ta.pop_back();\n\t}\n\treverse(a.begin(), a.end());\n\twhile (!a.empty() && a.back() <= k) {\n\t\t++ans;\n\t\ta.pop_back();\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "999",
    "index": "B",
    "title": "Reversing Encryption",
    "statement": "A string $s$ of length $n$ can be encrypted by the following algorithm:\n\n- iterate over all divisors of $n$ in decreasing order (i.e. from $n$ to $1$),\n- for each divisor $d$, reverse the substring $s[1 \\dots d]$ (i.e. the substring which starts at position $1$ and ends at position $d$).\n\nFor example, the above algorithm applied to the string $s$=\"codeforces\" leads to the following changes: \"codeforces\" $\\to$ \"secrofedoc\" $\\to$ \"orcesfedoc\" $\\to$ \"rocesfedoc\" $\\to$ \"rocesfedoc\" (obviously, the last reverse operation doesn't change the string because $d=1$).\n\nYou are given the encrypted string $t$. Your task is to decrypt this string, i.e., to find a string $s$ such that the above algorithm results in string $t$. It can be proven that this string $s$ always exists and is unique.",
    "tutorial": "To solve the problem, we can implement the encryption algorithm with a single change: we have to iterate over all divisors of $n$ in increasing order. Time complexity - $O(n~ \\cdot d(n))$, where $d(n)$ is a divisor count function for $n$. For example, $\\max\\limits_{i = 1}^{10^6}d(i) = 240$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tif (n % i == 0) {\n\t\t\treverse(s.begin(), s.begin() + i);\n\t\t}\n\t}\n\tcout << s << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "999",
    "index": "C",
    "title": "Alphabetic Removals",
    "statement": "You are given a string $s$ consisting of $n$ lowercase Latin letters. Polycarp wants to remove exactly $k$ characters ($k \\le n$) from the string $s$. Polycarp uses the following algorithm $k$ times:\n\n- if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;\n- if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;\n- ...\n- remove the leftmost occurrence of the letter 'z' and stop the algorithm.\n\nThis algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $k$ times, thus removing exactly $k$ characters.\n\nHelp Polycarp find the resulting string.",
    "tutorial": "Let the lowercase Latin letters be indexed from $0$ to $25$. There are exists at least two different solutions: If $k = n$ exit the program. Otherwise, count the number of occurrences of each letter $i$ from $0$ to $25$. Let it be $\\mathit{cnt}$. Now, find the (alphabetically) smallest letter that will be in the resulting string. It can be done as follows: iterate over all $i$ from $0$ to $25$, and if $\\mathit{cnt}_i \\le k$ then subtract it from $k$, otherwise, $i$ will be the smallest letter that will be in the resulting string. But we (possibly) need to remove some number of its leftmost occurrences. It is obvious that letters smaller than $i$ will not appear in the resulting string. Also, the $k$ leftmost occurrences of letter $i$ will be removed. Now, let's iterate over all letters in string $s$ from left to right and construct the resulting string $\\mathit{res}$. If the current character of $s$ (let it be $s_j$) is smaller than $i$, then do nothing. If $s_j$ is greater than $i$, then add it to $\\mathit{res}$. Otherwise $s_j = i$. If $k > 0$, then decrease $k$ by one, otherwise, add $s_j$ to $\\mathit{res}$. The time complexity is $O(n)$. Another solution is the following. Let's carry the vector of pairs $(s_i, i)$ where $s_i$ is the $i$-th character of $s$ and $i$ is its position. If we sort this vector with the standard compare function, it is easy to see that the first $k$ elements of this vector will be removed from the input string. Then if we will sort the last $n - k$ elements of this vector by its positions in the input string in increasing order, we will obtain the answer. The time complexity is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tstring s;\n\tcin >> s;\n\n\tvector<pair<char, int>> c(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tc[i] = make_pair(s[i], i);\n\tsort(c.begin(), c.end());\n\tsort(c.begin() + k, c.end(), [&] (const pair<char, int> &a, const pair<char, int> &b) {\n\t\treturn a.second < b.second;\n\t});\n\t\n\tfor (int i = k; i < n; ++i)\n\t\tcout << c[i].first;\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "999",
    "index": "D",
    "title": "Equalize the Remainders",
    "statement": "You are given an array consisting of $n$ integers $a_1, a_2, \\dots, a_n$, and a positive integer $m$. It is guaranteed that $m$ is a divisor of $n$.\n\nIn a single move, you can choose any position $i$ between $1$ and $n$ and increase $a_i$ by $1$.\n\nLet's calculate $c_r$ ($0 \\le r \\le m-1)$ — the number of elements having remainder $r$ when divided by $m$. In other words, for each remainder, let's find the number of corresponding elements in $a$ with that remainder.\n\nYour task is to change the array in such a way that $c_0 = c_1 = \\dots = c_{m-1} = \\frac{n}{m}$.\n\nFind the minimum number of moves to satisfy the above requirement.",
    "tutorial": "For each $i$ from $0$ to $m - 1$, find all elements of the array that are congruent to $i$ modulo $m$, and store their indices in a list. Also, create a vector called $\\mathit{free}$, and let $k$ be $\\frac{n}{m}$. We have to cycle from $0$ to $m - 1$ twice. For each $i$ from $0$ to $m - 1$, if there are in list too many (i.e., $> k$) elements congruent to $i$ modulo $m$, remove the extra elements from this list and add them to $\\mathit{free}$. If instead there are too few (i.e., $< k$) elements congruent to $i$ modulo $m$, remove the last few elements from the vector $\\mathit{free}$. For every removed index $\\mathit{idx}$, increase $a_\\mathit{idx}$ by $(i - a_\\mathit{idx}) \\bmod m$. After doing so (after two passes), we print the total increase and the updated array. It is obvious that after the first $m$ iterations, every list will have size at most $k$, and after $m$ more iterations, all lists will have the same sizes. It can be easily proved that this algorithm produces an optimal answer. The time complexity is $O(n + m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tint k = n / m;\n\tvector<int> a(n);\n\tvector<vector<int>> val(m);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\tval[a[i] % m].push_back(i);\n\t}\n\t\n\tlong long ans = 0;\n\tvector<pair<int, int>> fre;\n\tfor (int i = 0; i < 2 * m; ++i) {\n\t\tint cur = i % m;\n\t\twhile (int(val[cur].size()) > k) {\n\t\t\tint elem = val[cur].back();\n\t\t\tval[cur].pop_back();\n\t\t\tfre.push_back(make_pair(elem, i));\n\t\t}\n\t\twhile (int(val[cur].size()) < k && !fre.empty()) {\n\t\t\tint elem = fre.back().first;\n\t\t\tint mmod = fre.back().second;\n\t\t\tfre.pop_back();\n\t\t\tval[cur].push_back(elem);\n\t\t\ta[elem] += i - mmod;\n\t\t\tans += i - mmod;\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\tfor (int i = 0; i < n; ++i)\n\t\tcout << a[i] << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "999",
    "index": "E",
    "title": "Reachability from the Capital",
    "statement": "There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.\n\nWhat is the minimum number of new roads that need to be built to make all the cities reachable from the capital?\n\nNew roads will also be one-way.",
    "tutorial": "This problem is (almost) equivalent to the following: count the number of sources (the vertices with indegree equal to $0$) in the given graph's condensation. Thus, there exist solutions with complexity $O(n + m)$. However, the constraints in the problem are small, so solutions with complexity $O(n \\cdot m)$ also pass. One of these solutions is the following: first, let's mark all the vertices reachable from $s$ as good, using a simple DFS. Then, for each bad vertex $v$, count the number of bad vertices reachable from $v$ (it also can be done by simple DFS). Let this number be $\\mathit{cnt}_v$. Now, iterate over all bad vertices in non-increasing order of $\\mathit{cnt}_v$. For the current bad vertex $v$, if it is still not marked as good, run a DFS from it, marking all the reachable vertices as good, and increase the answer by $1$ (in fact, we are implicitly adding the edge $(s, v)$). It can be proved that this solution gives an optimal answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5010;\n\nint n, m, s;\nvector<int> g[N];\nvector<int> tg[N];\nvector<int> cg[N];\nvector<int> ord;\nint indeg[N];\nbool ucomp[N];\nbool used[N];\nint comp[N];\nint cnt;\n\nvoid dfs1(int v) {\n\tused[v] = true;\n\tfor (auto to : g[v])\n\t\tif (!used[to])\n\t\t\tdfs1(to);\n\tord.push_back(v);\n}\n\nvoid dfs2(int v) {\n\tcomp[v] = cnt;\n\tfor (auto to : tg[v])\n\t\tif (comp[to] == -1)\n\t\t\tdfs2(to);\n}\n\nvoid dfs3(int v) {\n\tucomp[v] = true;\n\tfor (auto to : cg[v])\n\t\tif (!ucomp[to])\n\t\t\tdfs3(to);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m >> s;\n\t--s;\n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\ttg[y].push_back(x);\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (!used[i]) {\n\t\t\tdfs1(i);\n\t\t}\n\t}\n\t\n\treverse(ord.begin(), ord.end());\n\tmemset(comp, -1, sizeof(comp));\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (comp[ord[i]] == -1) {\n\t\t\tdfs2(ord[i]);\n\t\t\t++cnt;\n\t\t}\n\t}\n\t\n\tfor (int v = 0; v < n; ++v) {\n\t\tfor (auto to : g[v]) {\n\t\t\tif (comp[v] != comp[to]) {\n\t\t\t\tcg[comp[v]].push_back(comp[to]);\n\t\t\t\t++indeg[comp[to]];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tdfs3(comp[s]);\n\tint ans = 0;\n\tfor (int i = 0; i < cnt; ++i)\n\t\tif (!ucomp[i] && indeg[i] == 0)\n\t\t\t++ans;\n\t\t\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "999",
    "index": "F",
    "title": "Cards and Joy",
    "statement": "There are $n$ players sitting at the card table. Each player has a favorite number. The favorite number of the $j$-th player is $f_j$.\n\nThere are $k \\cdot n$ cards on the table. Each card contains a single integer: the $i$-th card contains number $c_i$. Also, you are given a sequence $h_1, h_2, \\dots, h_k$. Its meaning will be explained below.\n\nThe players have to distribute all the cards in such a way that each of them will hold exactly $k$ cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals $h_t$ if the player holds $t$ cards containing his favorite number. If a player gets no cards with his favorite number (i.e., $t=0$), his joy level is $0$.\n\nPrint the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence $h_1, \\dots, h_k$ is the same for all the players.",
    "tutorial": "It is obvious that we can solve the problem separately for each favorite number because each player has only one favorite number, and if the player gets a card not having his favorite number, his joy will not change. Let $\\mathit{dp}[x][y]$ be the maximum possible total joy of $x$ players with the same favorite number (it doesn't matter which one) and $y$ cards (containing their favorite number) if the cards are distributed among the players optimally. Note that $x \\in [0, n]$ and $y \\in [0, k \\cdot n]$. At the beginning, all entries of the $\\mathit{dp}$ table are zeroes. The transition in this dynamic programming depends on how many cards the $x$-th player will receive (which is between $0$ and $k$). In other words, the dynamic programming transition will look like: where $h[i]$ is the joy of the player if he receives exactly $i$ cards containing his favorite number. Note that $h[0] = 0$. After filling the $\\mathit{dp}$ table, the answer can be calculated very easily: $\\mathit{ans} = \\sum\\limits_{i = 1}^{10^5}\\mathit{dp}[f_i][c_i]$, where $f_i$ is the number of players with favorite number $i$ and $c_i$ is the number of cards containing the number $i$. Time complexity is $O(n^2 \\cdot k^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 520;\nconst int K = 12;\nconst int C = 100 * 1000 + 11;\n\nint n, k;\nint c[C];\nint f[C];\nvector<int> h;\n\nint dp[N][K * N];\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> k;\n\th = vector<int>(k + 1);\n\tfor (int i = 0; i < n * k; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\t++c[x];\n\t}\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\t++f[x];\n\t}\n\tfor (int i = 1; i <= k; ++i)\n\t\tcin >> h[i];\n\t\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j <= n * k; ++j) {\n\t\t\tfor (int cur = 0; cur <= k; ++cur) {\n\t\t\t\tdp[i + 1][j + cur] = max(dp[i + 1][j + cur], dp[i][j] + h[cur]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\tfor (int i = 0; i < C; ++i) {\n\t\tif (f[i] != 0) ans += dp[f[i]][c[i]];\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1000",
    "index": "A",
    "title": "Codehorses T-shirts",
    "statement": "Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.\n\nThe valid sizes of T-shirts are either \"M\" or from $0$ to $3$ \"X\" followed by \"S\" or \"L\". For example, sizes \"M\", \"XXS\", \"L\", \"XXXL\" are valid and \"XM\", \"Z\", \"XXXXL\" are not.\n\nThere are $n$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office.\n\nOrganizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.\n\nWhat is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?\n\nThe lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.",
    "tutorial": "At first, let's remove all coinciding entries of both lists. The most convinient way is to use map/hashmap but it's not the only option. Now divide entries into categories by their length. You can notice that it takes exactly one second to remove an entry in each category (to make it equal to an entry of the opposing list). Thus the answer is $n - (number~of~coinciding~entries)$. Overall complexity: $O(n \\log n)$ or $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n\tint n;\n\tcin >> n;\n\t\n\tvector<string> a(n), b(n);\n\tforn(i, n) cin >> a[i];\n\tforn(i, n) cin >> b[i];\n\t\n\tmap<string, int> cnta, cntb;\n\tforn(i, n) ++cnta[a[i]];\n\tforn(i, n) ++cntb[b[i]];\n\t\n\tint ans = n;\n\tfor (auto it : cnta) ans -= min(it.second, cntb[it.first]);\n\t\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1000",
    "index": "B",
    "title": "Light It Up",
    "statement": "Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are \"lights on\" and \"lights off\"). Unfortunately, some program is already installed into the lamp.\n\nThe lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 < a_1 < a_2 < \\dots < a_{|a|} < M$. All $a_i$ must be integers. Of course, preinstalled program is a good program.\n\nThe lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state.\n\nSince you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can \\textbf{insert at most one} element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$.\n\nFind such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up.",
    "tutorial": "At first, let's insert $0$ and $M$ in array $a$, so all possible positions for inserting will always belong to $(a_i, a_{i + 1})$. At second, let $x$ be value to insert and $a_i < x < a_{i + 1}$. It can be proven, that it's always optimal to move $x$ to $a_i$ or to $a_{i + 1}$. So, for each $(a_i, a_{i + 1})$ we need to check only $x = a_i + 1$ and $x = a_{i + 1} - 1$. To check it fast enough, we need to know total time of lamp is lit for each prefix and precalculate for each $i$, total time of lamp is lit if starting from $a_i$ light is on / lights is off. Result complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n, M;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n >> M))\n\t\treturn false;\n\ta.assign(n, 0);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d\", &a[i]);\n\treturn true;\n}\n\nvector<int> f[2];\n\ninline void solve() {\n\ta.insert(a.begin(), 0);\n\ta.push_back(M);\n\t\n\tf[0].assign(a.size(), 0);\n\tf[1].assign(a.size(), 0);\n\t\n\tfor(int i = int(a.size()) - 2; i >= 0; i--) {\n\t\tf[0][i] = f[1][i + 1];\n\t\tf[1][i] = (a[i + 1] - a[i]) + f[0][i + 1];\n\t}\n\t\n\tint ans = f[1][0];\n\tfor(int i = 0; i + 1 < int(a.size()); i++) {\n\t\tif(a[i + 1] - a[i] < 2)\n\t\t\tcontinue;\n\t\t\n\t\tint tp = (i & 1) ^ 1;\n\t\tint pSum = f[1][0] - f[tp][i];\n\t\tans = max(ans, pSum + (a[i + 1] - a[i] - 1) + f[tp][i + 1]);\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tif(read())\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1000",
    "index": "C",
    "title": "Covered Points Count",
    "statement": "You are given $n$ segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.\n\nYour task is the following: for every $k \\in [1..n]$, calculate the number of points with integer coordinates such that the number of segments that cover these points equals $k$. A segment with endpoints $l_i$ and $r_i$ covers point $x$ if and only if $l_i \\le x \\le r_i$.",
    "tutorial": "This problem with small coordinates can be solved using partial sums and some easy counting. Let's carry an array $cnt$, where $cnt_i$ will be equal to the number of segments that cover the point with coordinate $i$. How to calculate $cnt$ in $O(n + maxX)$? For each segment ($l_i, r_i$) let's add $+1$ to $cnt_{l_i}$ and $-1$ to $cnt_{r_i + 1}$. Now build on this array prefix sums and notice that $cnt_i$ equals the number of segments that cover the point with coordinate $i$. Then $ans_i$ will be equal to $\\sum\\limits_{j = 0}^{maxX} cnt_j = i$. All the answers can be calculated in $O(maxX)$ in total. So the total complexity of this solution is $O(n + maxX)$. But in our problem it is too slow to build an entire array $cnt$. So what should we do? It is obvious that if any coordinate $j$ is not equals some $l_i$ or some $r_i + 1$ then $cnt_i = cnt_{i - 1}$. So we do not need carry all the positions explicitly. Let's carry all $l_i$ and $r_i + 1$ in some logarithmic data structure or let's use the coordinate compression method. The coordinate compression method allows us to transform the set of big sparse objects to the set of small compressed objects maintaining the relative order. In our problems let's make the following things: push all $l_i$ and $r_i + 1$ in vector $cval$, sort this vector, keep only unique values and then use the position of elements in vector $cval$ instead of original value (any position can be found in $O(\\log n)$ by binary search or standard methods as lower_bound in C++). So the first part of the solution works in $O(n \\log n)$. Answer can be calculated using almost the same approach as in solution to this problem with small coordinates. But now we know that between two adjacent elements $cval_i$ and $cval_{i + 1}$ there is exactly $cval_{i + 1} - cval_{i}$ points with answer equals to $cnt_i$. So if we will iterate over all pairs of the adjacent elements $cval_i$ and $cval_{i + 1}$ and add $cval_{i + 1} - cval_i$ to the $ans_{cnt_i}$, we will calculate all the answers in $O(n)$. So the total complexity of the solution is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<pair<long long, long long>> a(n);\n\tvector<long long> cval;\n\tfor (auto &i : a) {\n\t\tscanf(\"%lld %lld\", &i.first, &i.second);\n\t\tcval.push_back(i.first);\n\t\tcval.push_back(i.second + 1);\n\t\t\n\t}\n\tsort(cval.begin(), cval.end());\n\tcval.resize(unique(cval.begin(), cval.end()) - cval.begin());\n\t\n\tvector<int> cnt(2 * n);\n\tfor (auto &i : a) {\n\t\tint posl = lower_bound(cval.begin(), cval.end(), i.first) - cval.begin();\n\t\tint posr = lower_bound(cval.begin(), cval.end(), i.second + 1) - cval.begin();\n\t\t++cnt[posl];\n\t\t--cnt[posr];\n\t}\n\tfor (int i = 1; i < 2 * n; ++i)\n\t\tcnt[i] += cnt[i - 1];\n\t\t\n\tvector<long long> ans(n + 1);\n\tfor (int i = 1; i < 2 * n; ++i)\n\t\tans[cnt[i - 1]] += cval[i] - cval[i - 1];\n\t\n\tfor (int i = 1; i <= n; ++i)\n\t\tprintf(\"%lld \", ans[i]);\n\tputs(\"\");\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1000",
    "index": "D",
    "title": "Yet Another Problem On a Subsequence",
    "statement": "The sequence of integers $a_1, a_2, \\dots, a_k$ is called a good array if $a_1 = k - 1$ and $a_1 > 0$. For example, the sequences $[3, -1, 44, 0], [1, -99]$ are good arrays, and the sequences $[3, 7, 8], [2, 5, 4, 1], [0]$ — are not.\n\nA sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences $[2, -3, 0, 1, 4]$, $[1, 2, 3, -3, -9, 4]$ are good, and the sequences $[2, -3, 0, 1]$, $[1, 2, 3, -3 -9, 4, 1]$ — are not.\n\nFor a given sequence of numbers, count the number of its \\textbf{subsequences} that are good sequences, and print the number of such subsequences modulo \\textbf{998244353}.",
    "tutorial": "The problem is solved by the dynamic programming. Let $dp_i$ be the answer for the prefix of the array starting at $i$ (it contains the indices $i, i + 1, \\dots, n$). If $a_i \\le 0$, then $dp_i = 0$. Otherwise, let's go over the position $j$, with which the next good array begins. Then we need to select $a_i$ positions among $j-i-1$ positions, which will be elements of the array. The number of ways to choose an unordered set of $k$ items from $n$ of different objects is calculated using the formula $C_n^k = \\frac{n!}{K!(N -k)!}$. Thus, the dynamics is as follows: $dp_i = \\sum\\limits_{j = i + a_i + 1}^{n + 1} {C_{j - i - 1}^{a_i} \\cdot dp_j}$. The basis of dynamics is the value $dp_{n + 1} = 1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1009;\nconst int MOD = 998244353;\n\nint n;\nint a[N];\nint dp[N];\nint C[N][N];\n\nint main() {\n\tfor(int i = 0; i < N; ++i){\n\t\tC[i][0] = C[i][i] = 1;\n\t\tfor(int j = 1; j < i; ++j)\n\t\t\tC[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD;\n\t}\n\t\n\tcin >> n;\n\tfor(int i = 0; i < n; ++i)\n\t\tcin >> a[i];\n\t\n\tdp[n] = 1;\n\tfor(int i = n - 1; i >= 0; --i){\n\t\tif(a[i] <= 0) continue;\n\t\t\n\t\tfor(int j = i + a[i] + 1; j <= n; ++j){\n\t\t\t\tdp[i] += (dp[j] * 1LL * C[j - i - 1][a[i]]) % MOD;\n\t\t\t\tdp[i] %= MOD;\n\t\t}\n\t}\n\n\tint sum = 0;\n\tfor(int i = 0; i < n; ++i){\n\t\tsum += dp[i];\n\t\tsum %= MOD;\n\t}\n\tcout << sum << endl;\n\t\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1000",
    "index": "E",
    "title": "We Need More Bosses",
    "statement": "Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of $n$ locations connected by $m$ \\textbf{two-way} passages. The passages are designed in such a way that it should be possible to get from any location to any other location.\n\nOf course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called \\textbf{bosses}). And your friend wants you to help him place these bosses.\n\nThe game will start in location $s$ and end in location $t$, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from $s$ to $t$ without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as $s$ or as $t$.",
    "tutorial": "It's quite obvious that we can place bosses only on the bridges of the given graph - if an edge is not a bridge, then removing it doesn't make the graph disconnected, so there still exists a path between any pair of vertices. And if we fix two vertices $s$ and $t$, and then find some simple path between them, then we will place the bosses on all bridges belonging to this path (since the set of bridges would stay the same no matter which simple path between $s$ and $t$ we choose). If we find bridges in the given graph and compress all 2-edge-connected components (two vertices belong to the same 2-edge-connected component iff there exists a path between these vertices such that there are no bridges on this path) into single vertices, we will obtain a special tree called bridge tree. Every edge of a bridge tree corresponds to a bridge in the original graph (and vice versa). Since we want to find the path with maximum possible number of bridges, we only need to find the diameter of the bridge tree, and this will be the answer to the problem.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 500043;\n\nvector<int> g[N];\nvector<int> t[N];\nint tin[N], tout[N], fup[N];\nint p[N];\nint T = 1;\nint rnk[N];\nvector<pair<int, int> > bridges;\nint st;\nint d[N];\nint n, m;\n\nint get(int x)\n{\n \treturn (p[x] == x ? x : p[x] = get(p[x]));\n}\n\nvoid link(int x, int y)\n{\n \tx = get(x);\n \ty = get(y);\n \tif(x == y) return;\n \tif(rnk[x] > rnk[y])\n \t\tswap(x, y);\n \tp[x] = y;\n \trnk[y] += rnk[x];\t\n}\n\nint dfs(int x, int par = -1)\n{\n\ttin[x] = T++;\n\tfup[x] = tin[x];\n\tfor(auto y : g[x])\n\t{\n\t \tif(tin[y] > 0)\n\t \t{\n\t \t\tif(par != y)\n\t \t\t\tfup[x] = min(fup[x], tin[y]);\n\t \t}\n\t \telse\n\t \t{\n\t \t \tint f = dfs(y, x);\n\t \t \tfup[x] = min(fup[x], f);\n\t \t \tif(f > tin[x])\n\t \t \t\tbridges.push_back(make_pair(x, y));\n\t \t \telse\n\t \t \t\tlink(x, y);\n\t \t}\n\t}\n\ttout[x] = T++;                                      \n\treturn fup[x];\n}      \n\nvoid build()\n{\n \tfor(auto z : bridges)\n \t{\n \t \tint x = get(z.first);\n \t \tint y = get(z.second);\n \t \tst = x;\n \t \tt[x].push_back(y);\n \t \tt[y].push_back(x);\n \t}\n}\n\npair<int, int> bfs(int x)\n{\n\tfor(int i = 0; i < n; i++)\n\t\td[i] = n + 1;\n\td[x] = 0;\n\tqueue<int> q;\n\tq.push(x);\n\tint last = 0;\n\twhile(!q.empty())\n\t{\n\t \tlast = q.front();\n\t \tq.pop();\n\t \tfor(auto y : t[last])\n\t \t\tif(d[y] > d[last] + 1)\n\t \t\t{\n\t \t\t \td[y] = d[last] + 1;\n\t \t\t \tq.push(y);\n\t \t\t}\n\t}\n\treturn make_pair(last, d[last]);\n}\n\nint main()\n{                \n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 0; i < n; i++)\n\t\trnk[i] = 1, p[i] = i;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t \tint x, y;\n\t \tscanf(\"%d %d\", &x, &y);\n\t \t--x;\n\t \t--y;\n\t \tg[x].push_back(y);\n\t \tg[y].push_back(x);\n\t}\n\tdfs(0);\n\tbuild();\n\tpair<int, int> p1 = bfs(st);\n\tpair<int, int> p2 = bfs(p1.first);\n\tprintf(\"%d\\n\", p2.second);\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1000",
    "index": "F",
    "title": "One Occurrence",
    "statement": "You are given an array $a$ consisting of $n$ integers, and $q$ queries to it. $i$-th query is denoted by two integers $l_i$ and $r_i$. For each query, you have to find \\textbf{any} integer that occurs \\textbf{exactly once} in the subarray of $a$ from index $l_i$ to index $r_i$ (a subarray is a contiguous subsegment of an array). For example, if $a = [1, 1, 2, 3, 2, 4]$, then for query $(l_i = 2, r_i = 6)$ the subarray we are interested in is $[1, 2, 3, 2, 4]$, and possible answers are $1$, $3$ and $4$; for query $(l_i = 1, r_i = 2)$ the subarray we are interested in is $[1, 1]$, and there is no such element that occurs exactly once.\n\nCan you answer all of the queries?",
    "tutorial": "Suppose all queries have the same right border $r$. Then the answer for the query can be some integer $i$ such that the last occurence of $i$ on the prefix $[1, r]$ of the array is inside the segment, but the second to last occurence is outside the segment (or even does not exist). More formally, let $f(i)$ be the maximum index $j$ such that $j < i$ and $a_j = a_i$ (or $-1$ if there is no such $j$); the answer to the query is some number $a_k$ such that $l \\le k \\le r$ and $f(k) < l$ (and $k$ is the rightmost occurence of $a_k$ in the segment $[1, r]$). For a fixed right border $r$, we can build a segment tree which for every index $x$ such that $x$ is the rightmost occurence of $a_x$ on $[1, r]$ stores the value of $f(x)$; and if we query minimum on the segment $[l, r]$ in such tree, we can try to find the answer. Let the position of minimum be $m$. If $f(m) < l$, then $a_m$ can be the answer; otherwise there is no answer. But this is too slow since we can't afford to build a segment tree for every possible value of $r$. There are two methods how to deal with this problem: you may sort all queries by their right borders and maintain the segment tree while shifting the right border (when going from $r$ to $r + 1$, we have to update the values in the positions $f(r + 1)$ and $r + 1$), or we may use a persistent segment tree and get an online solution. We tried to eliminate solutions using Mo's algorithm, but in fact it's possible to squeeze some implementations of it into TL. There are two optimizations that might help there. When dividing the elements into blocks, we may sort the first block in the ascending order of right borders, the second - in descending, the third - in ascending order again, and so on. And also it's possible to obtain a Mo-based solution with worst case complexity of $O((n + q) \\sqrt{n})$ if we maintain the set of possible answers using sqrt decomposition on it.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++) \n#define x first\n#define y second\n\nconst int N = 500 * 1000 + 13;\nconst int P = 800;\nconst int INF = 1e9;\n\nbool comp(const pair<pair<int, int>, int> &a, const pair<pair<int, int>, int> &b){\n\tint num = a.x.x / P;\n\tif (num != b.x.x / P)\n\t\treturn a.x.x < b.x.x;\n\tif (num & 1)\n\t\treturn a.x.y < b.x.y;\n\treturn a.x.y > b.x.y;\n}\n\nint val[N];\nint cnt[N];\nint bl[P];\nint tot;\n\ninline void add(int x){\n\t++cnt[x];\n\tif (cnt[x] == 1){\n\t\t++val[x];\n\t\t++bl[x / P];\n\t\t++tot;\n\t}\n\telse if (cnt[x] == 2){\n\t\t--val[x];\n\t\t--bl[x / P];\n\t\t--tot;\n\t}\n}\n\ninline void sub(int x){\n\t--cnt[x];\n\tif (cnt[x] == 1){\n\t\t++val[x];\n\t\t++bl[x / P];\n\t\t++tot;\n\t}\n\telse if (cnt[x] == 0){\n\t\t--val[x];\n\t\t--bl[x / P];\n\t\t--tot;\n\t}\n}\n\nint get(){\n\tif (tot == 0) \n\t\treturn 0;\n\t\n\tforn(i, P){\n\t\tif (bl[i] > 0){\n\t\t\tfor (int j = i * P;; ++j){\n\t\t\t\tif (val[j]){\n\t\t\t\t\treturn j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tassert(false);\n}\n\nint n, m;\nint a[N], ans[N];\npair<pair<int, int>, int> q[N];\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tscanf(\"%d\", &m);\n\tforn(i, m){\n\t\tscanf(\"%d%d\", &q[i].x.x, &q[i].x.y);\n\t\t--q[i].x.x, --q[i].x.y;\n\t\tq[i].y = i;\n\t}\n\tsort(q, q + m, comp);\n\t\n\tint l = 0, r = -1;\n\t\n\tforn(i, m){\n\t\tint L = q[i].x.x;\n\t\tint R = q[i].x.y;\n\t\t\n\t\twhile (r < R){\n\t\t\t++r;\n\t\t\tadd(a[r]);\n\t\t}\n\t\t\n\t\twhile (r > R){\n\t\t\tsub(a[r]);\n\t\t\t--r;\n\t\t}\n\t\t\n\t\twhile (l > L){\n\t\t\t--l;\n\t\t\tadd(a[l]);\n\t\t}\n\t\t\n\t\twhile (l < L){\n\t\t\tsub(a[l]);\n\t\t\t++l;\n\t\t}\n\t\t\n\t\tans[q[i].y] = get();\n\t}\n\t\n\tforn(i, m)\n\t\tprintf(\"%d\\n\", ans[i]);\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1000",
    "index": "G",
    "title": "Two-Paths",
    "statement": "You are given a weighted tree (undirected connected graph with no cycles, loops or multiple edges) with $n$ vertices. The edge $\\{u_j, v_j\\}$ has weight $w_j$. Also each vertex $i$ has its own value $a_i$ assigned to it.\n\nLet's call a path starting in vertex $u$ and ending in vertex $v$, where each edge can appear no more than twice (regardless of direction), a 2-path. Vertices can appear in the 2-path multiple times (even start and end vertices).\n\nFor some 2-path $p$ profit $\\text{Pr}(p) = \\sum\\limits_{v \\in \\text{distinct vertices in } p}{a_v} - \\sum\\limits_{e \\in \\text{distinct edges in } p}{k_e \\cdot w_e}$, where $k_e$ is the number of times edge $e$ appears in $p$. That is, vertices are counted once, but edges are counted the number of times they appear in $p$.\n\nYou are about to answer $m$ queries. Each query is a pair of vertices $(qu, qv)$. For each query find 2-path $p$ from $qu$ to $qv$ with maximal profit $\\text{Pr}(p)$.",
    "tutorial": "Let's solve this task in several steps. Step 1. Calculate $dp_i$ for each vertex. Let $dp_i$ be maximal profit of some 2-path starting at $i$ and finishing at $i$. If vertex $i$ is a root of the tree, then $dp_i$ equivalent to $d'_i$, where $d'_i$ - maximal profit of 2-path $(i, i)$, when we can go only in subtree of $i$. The $d'_i$ can be calculated with next approach: $d'_v = a_v + \\sum\\limits_{to \\in \\text{Children}(v)}{\\max(0, d'_{to} - 2 \\cdot w(v, to))}$. To calculate $dp_i$ we can use next technique. Let's manage next invariant: when processing vertex $v$ all its neighbours (even parent) will hold $d'_i$ as if $v$ its parent. Then $dp_v = a_v + \\sum\\limits_{to \\in \\text{Neighbours}(v)}{\\max(0, d'_{to} - 2 \\cdot w(v, to))}$. After that, we can proceed with each child $to$ of $v$, but before moving to it we must change value $d'_v$ since we must keep invariant true. To keep it true, it's enough to set $d'_v = dp_v - \\max(0, d'_{to} - 2 \\cdot w(v, to))$. Also let's memorize value $\\max(0, d'_{to} - 2 \\cdot w(v, to))$ as $dto(v, to)$. Step 2. Processing queries. Let simple path $(qu, qv)$ be $qu \\rightarrow p_1 \\rightarrow p_2 \\rightarrow \\dots \\rightarrow p_k \\rightarrow qv$. If $qu = qv$ then answer is $dp_{qu}$. Otherwise, each edge on this simple path must be used exactly once. But, while travelling from $qu$ to $qv$ using this simple path, at each vertex $v$ we can go somewhere and return to $v$ - the only condition is not use edges from simple path. And we can do it using precalculated values $dp_i$ and $dto(v, to)$. So, if we want to find max profit of 2-path $(v, v)$ with prohibited edges $(v, to_1)$, $(v, to_2)$, so we can use value $dp_v - dto(v, to_1) - dto(v, to_2)$. Finally, to process queries, let's find $l = lca(qu, qv)$, divide it on two queries $(qu, l)$, $(qv, l)$. Now we can handle all queries offline, travelling on tree in dfs order. Let's manage some data structure on current path from current vertex to the root (this DS can be based on array of depths). Then, when we come to vertex $v$, just add value $dp_v - dto(v, \\text{parent}(v))$ to DS in position $\\text{depth}(v)$ (and erase it before exit). Each query $(v, l)$ becomes a query of sum to some subsegment in DS (don't forget carefully handle value in lca). And, before moving from $v$ to $to$, you need subtract $dto(v, to)$ from current value of $v$ (here you can at once subtract weight of edge $(v, to)$). Don't forget to return each change in DS, when it needed. As we can see, DS is just a BIT with sum on segment and change in position. Result complexity is $O((n + m) \\log{n})$. Fast IO are welcome.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\n\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nconst int M = 400 * 1000 + 555;\nconst int N = 300 * 1000 + 555;\nconst int LOGN = 19;\n\nint n, m, a[N];\nvector<pt> g[N];\n\ninline bool read() {\n\tif(!(cin >> n >> m))\n\t\treturn false;\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%d\", &a[i]) == 1);\n\tfore(i, 0, n - 1) {\n\t\tint u, v, w;\n\t\tassert(scanf(\"%d%d%d\", &u, &v, &w) == 3);\n\t\tu--, v--;\n\t\t\n\t\tg[u].emplace_back(v, w);\n\t\tg[v].emplace_back(u, w);\n\t}\n\tfore(i, 0, n)\n\t\tsort(all(g[i]));\n\treturn true;\n}\n\nint tin[N], tout[N], T = 0;\nint p[N][LOGN];\n\nint h[N];\nli d1[N];\n\nvoid calc1(int v, int pr) {\n\ttin[v] = T++;\n\tp[v][0] = pr;\n\tfore(st, 1, LOGN)\n\t\tp[v][st] = p[p[v][st - 1]][st - 1];\n\t\n\td1[v] = a[v];\n\tfore(i, 0, sz(g[v])) {\n\t\tint to = g[v][i].x;\n\t\tint w = g[v][i].y;\n\t\t\n\t\tif(to == pr)\n\t\t\tcontinue;\n\n\t\th[to] = h[v] + 1;\n\t\tcalc1(to, v);\n\t\td1[v] += max(0ll, d1[to] - 2ll * w);\n\t}\n\ttout[v] = T++;\n}\n\nli dp[N];\nvector<li> dto[N];\n\nvoid calcRRT(int v) {\n\tdp[v] = a[v];\n\tdto[v].assign(sz(g[v]), 0ll);\n\t\n\tfore(i, 0, sz(g[v])) {\n\t\tint to = g[v][i].x;\n\t\tint w = g[v][i].y;\n\t\t\n\t\tli curVal = max(0ll, d1[to] - 2ll * w);\n\t\tdp[v] += curVal;\n\t\tdto[v][i] = curVal;\n\t}\n\t\n\tfore(i, 0, sz(g[v])) {\n\t\tint to = g[v][i].x;\n\t\tif(h[to] < h[v])\n\t\t\tcontinue;\n\t\t\n\t\tli tmp = d1[v];\n\t\td1[v] = dp[v] - dto[v][i];\n\t\tcalcRRT(to);\n\t\td1[v] = tmp;\n\t}\n}\n\ninline bool isP(int l, int v) {\n\treturn tin[l] <= tin[v] && tout[v] <= tout[l];\n}\n\nint lca(int u, int v) {\n\tif(isP(u, v)) return u;\n\tif(isP(v, u)) return v;\n\t\n\tfor(int st = LOGN - 1; st >= 0; st--)\n\t\tif(!isP(p[v][st], u))\n\t\t\tv = p[v][st];\n\treturn p[v][0];\n}\n\n\nli getDto(int v, int to) {\n\tint pos = int(lower_bound(all(g[v]), pt(to, -1)) - g[v].begin());\n\tif(pos >= sz(g[v]) || g[v][pos].x != to)\n\t\treturn 0;\n\treturn dto[v][pos];\n}\n\nli f[N];\n\ninline void inc(int pos, li val) {\n\tfor(; pos < N; pos |= pos + 1)\n\t\tf[pos] += val;\n}\n\ninline li sum(int pos) {\n\tli ans = 0;\n\tfor(; pos >= 0; pos = (pos & (pos + 1)) - 1)\n\t\tans += f[pos];\n\treturn ans;\n}\n\ninline li getSum(int l, int r) {\n\treturn sum(r) - sum(l);\n}\n\nli ans[M];\nvector<pt> qs[N];\n\nvoid calcAns(int v) {\n\tli vAdd = dp[v] - getDto(v, p[v][0]);\n\tinc(h[v], vAdd);\n\t\n\tfor(pt &q : qs[v]) {\n\t\tint up = q.x, id = q.y;\n\t\tans[id] += getSum(h[up] - 1, h[v]) + getDto(up, p[up][0]);\n\t}\n\t\n\tfore(i, 0, sz(g[v])) {\n\t\tint to = g[v][i].x;\n\t\tint w = g[v][i].y;\n\t\tif(h[to] < h[v])\n\t\t\tcontinue;\n\t\t\n\t\tli curSub = dto[v][i] + w;\n\t\tinc(h[v], -curSub);\n\t\t\n\t\tcalcAns(to);\n\t\tinc(h[v], +curSub);\n\t}\n\tinc(h[v], -vAdd);\n}\n\ninline void solve() {\n\tT = 0;\n\th[0] = 0;\n\tcalc1(0, 0);\n\tcalcRRT(0);\n\t\n\tfore(i, 0, m) {\n\t\tint u, v;\n\t\tassert(scanf(\"%d%d\", &u, &v) == 2);\n\t\tu--, v--;\n\t\t\n\t\tint l = lca(u, v);\t\t\n\t\tans[i] = -dp[l];\n\t\t\n\t\tqs[u].emplace_back(l, i);\n\t\tqs[v].emplace_back(l, i);\n\t}\n\t\n\tcalcAns(0);\n\tfore(i, 0, m)\n\t\tprintf(\"%lld\\n\", ans[i]);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1003",
    "index": "A",
    "title": "Polycarp's Pockets",
    "statement": "Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.\n\nFor example, if Polycarp has got six coins represented as an array $a = [1, 2, 4, 3, 3, 2]$, he can distribute the coins into two pockets as follows: $[1, 2, 3], [2, 3, 4]$.\n\nPolycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.",
    "tutorial": "We have to find the maximum number of elements with the same value (it can be done by counting). This number will be the answer because if there are no more than $k$ elements with the same value in the array it is obvious that we cannot use less than $k$ pockets, but we also doesn't need to use more than $k$ pockets because of the other values can be also distributed using $k$ pockets. Overall complexity is $O(n + maxAi)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\t\n\tvector<int> cnt(101);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\t++cnt[x];\n\t}\n\t\n\tcout << *max_element(cnt.begin(), cnt.end()) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1003",
    "index": "B",
    "title": "Binary String Constructing",
    "statement": "You are given three integers $a$, $b$ and $x$. Your task is to construct a binary string $s$ of length $n = a + b$ such that there are exactly $a$ zeroes, exactly $b$ ones and exactly $x$ indices $i$ (where $1 \\le i < n$) such that $s_i \\ne s_{i + 1}$. It is guaranteed that the answer always exists.\n\nFor example, for the string \"01010\" there are four indices $i$ such that $1 \\le i < n$ and $s_i \\ne s_{i + 1}$ ($i = 1, 2, 3, 4$). For the string \"111001\" there are two such indices $i$ ($i = 3, 5$).\n\nRecall that binary string is a non-empty sequence of characters where each character is either 0 or 1.",
    "tutorial": "This problem has several general cases: $x$ is even and $a > b$, then the answer is 01 repeated $\\frac{x}{2}$ times, then $b - \\frac{x}{2}$ ones and $a - \\frac{x}{2}$ zeroes; $x$ is even and $a \\le b$, then the answer is 10 repeated $\\frac{x}{2}$ times, then $a - \\frac{x}{2}$ zeroes and $b - \\frac{x}{2}$ ones; $x$ is odd and $a > b$, then the answer is 01 repeated $\\lfloor\\frac{x}{2}\\rfloor$ times, then $a - \\lfloor\\frac{x}{2}\\rfloor$ zeroes and $b - \\lfloor\\frac{x}{2}\\rfloor$ ones; $x$ is odd and $a \\le b$, then the answer is 10 repeated $\\lfloor\\frac{x}{2}\\rfloor$ times, then $b - \\lfloor\\frac{x}{2}\\rfloor$ ones and $a - \\lfloor\\frac{x}{2}\\rfloor$ zeroes. I am sure that there are other more beautiful solution, but for me the easiest way to solve this problem is to extract general cases and handle it. Overall complexity is $O(a + b)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint a, b, x;\n\tcin >> a >> b >> x;\n\t\n\tif (x % 2 == 0) {\n\t\tif (a > b) {\n\t\t\tfor (int i = 0; i < x / 2; ++i)\n\t\t\t\tcout << \"01\";\n\t\t\tcout << string(b - x / 2, '1');\n\t\t\tcout << string(a - x / 2, '0');\n\t\t} else {\n\t\t\tfor (int i = 0; i < x / 2; ++i)\n\t\t\t\tcout << \"10\";\n\t\t\tcout << string(a - x / 2, '0');\n\t\t\tcout << string(b - x / 2, '1');\n\t\t}\n\t} else if (a > b) {\n\t\tfor (int i = 0; i < x / 2; ++i)\n\t\t\tcout << \"01\";\n\t\tcout << string(a - x / 2, '0');\n\t\tcout << string(b - x / 2, '1');\n\t} else {\n\t\tfor (int i = 0; i < x / 2; ++i)\n\t\t\tcout << \"10\";\n\t\tcout << string(b - x / 2, '1');\n\t\tcout << string(a - x / 2, '0');\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1003",
    "index": "C",
    "title": "Intense Heat",
    "statement": "The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.\n\nMathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:\n\nSuppose we want to analyze the segment of $n$ consecutive days. We have measured the temperatures during these $n$ days; the temperature during $i$-th day equals $a_i$.\n\nWe denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $x$ to day $y$, we calculate it as $\\frac{\\sum \\limits_{i = x}^{y} a_i}{y - x + 1}$ (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than $k$ consecutive days. For example, if analyzing the measures $[3, 4, 1, 2]$ and $k = 3$, we are interested in segments $[3, 4, 1]$, $[4, 1, 2]$ and $[3, 4, 1, 2]$ (we want to find the maximum value of average temperature over these segments).\n\nYou have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?",
    "tutorial": "This task is very straight-forward implementation problem. So we can iterate over all segments of the given array, calculate their sum, and if the length of the current segment is not less than $k$, try to update the answer with the mean of this segment. Overall complexity is $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define sqr(a) ((a) * (a))\n#define sz(a) int(a.size())\n#define all(a) a.begin(), a.end()\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {\n\treturn out << \"(\" << a.x << \", \" << a.y << \")\";\n}\n\ntemplate <class A> ostream& operator << (ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tforn(i, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nmt19937 rnd(time(NULL));\n\nconst int INF = int(2e9);\nconst li INF64 = li(1e18);\nconst int MOD = INF + 7;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n\nconst int N = 10000 + 7;\n\nint n, k;\nint a[N];\n\nbool read () {\n\tif (scanf(\"%d%d\", &n, &k) != 2)\n\t\treturn false;\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\treturn true;\n}\n\nint pr[N];\n\nvoid solve() {\n\tpr[0] = 0;\n\tforn(i, n) pr[i + 1] = pr[i] + a[i];\n\t\n\tld ans = 0;\n\tforn(r, n) forn(l, r + 1){\n\t\tif (r - l + 1 >= k){\n\t\t\tans = max(ans, (pr[r + 1] - pr[l]) / ld(r - l + 1));\n\t\t}\n\t}\n\t\n\tprintf(\"%.15f\\n\", double(ans));\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n\t\n\tint tt = clock();\n\t\n#endif\n\t\n\tcerr.precision(15);\n\tcout.precision(15);\n\tcerr << fixed;\n\tcout << fixed;\n\n\twhile(read()) {\t\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\tcerr << \"TIME = \" << clock() - tt << endl;\n\ttt = clock();\n#endif\n\n\t}\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1003",
    "index": "D",
    "title": "Coins and Queries",
    "statement": "Polycarp has $n$ coins, the value of the $i$-th coin is $a_i$. It is guaranteed that all the values are integer powers of $2$ (i.e. $a_i = 2^d$ for some \\textbf{non-negative} integer number $d$).\n\nPolycarp wants to know answers on $q$ queries. The $j$-th query is described as integer number $b_j$. The answer to the query is the minimum number of coins that is necessary to obtain the value $b_j$ using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value $b_j$, the answer to the $j$-th query is -1.\n\nThe queries are independent (the answer on the query doesn't affect Polycarp's coins).",
    "tutorial": "We can solve the problem by the following way: firstly, for each power of $2$ let's calculate the number of coins with the value equals this degree. Let's call it $cnt$. It is obvious that we can obtain the value $b_j$ greedily (because all less values of coins are divisors of all greater values of coins). Now let's iterate over all powers of $2$ from $30$ to $0$. Let's $deg$ be the current degree. We can take $min(\\lfloor\\frac{b_j}{2^{deg}}\\rfloor, cnt_{deg})$ coins with the value equals $2^{deg}$. Let it be $cur$. Add $cur$ to the answer and subtract $2^{deg} \\cdot cur$ from $b_j$. If after iterating over all powers $b_j$ still be non-zero, print -1. Otherwise print the answer. Overall complexity: $O((n + q) \\log maxAi)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, q;\n\tcin >> n >> q;\n\t\n\tvector<int> cnt(31);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\t++cnt[__builtin_ctz(x)];\n\t}\n\t\n\twhile (q--) {\n\t\tint x;\n\t\tcin >> x;\n\t\t\n\t\tint ans = 0;\n\t\tfor (int i = 30; i >= 0 && x > 0; --i) {\n\t\t\tint need = min(x >> i, cnt[i]);\n\t\t\tans += need;\n\t\t\tx -= (1 << i) * need;\n\t\t}\n\t\t\n\t\tif (x > 0)\n\t\t\tans = -1;\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1003",
    "index": "E",
    "title": "Tree Constructing",
    "statement": "You are given three integers $n$, $d$ and $k$.\n\nYour task is to construct an undirected tree on $n$ vertices with diameter $d$ and degree of each vertex at most $k$, or say that it is impossible.\n\nAn undirected tree is a connected undirected graph with $n - 1$ edges.\n\nDiameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.\n\nDegree of a vertex is the number of edges incident to this vertex (i.e. for a vertex $u$ it is the number of edges $(u, v)$ that belong to the tree, where $v$ is any other vertex of a tree).",
    "tutorial": "Let's construct a tree by the following algorithm: if $d \\ge n$, let's print \"NO\" and terminate the program. Otherwise let's keep the array $deg$ of the length $n$ which will represent degrees of vertices. The first step is to construct the diameter of the tree. Let first $d + 1$ vertices form it. Let's add $d$ edges to the answer, increase degrees of vertices corresponding to this edges, and if some vertex has degree greater than $k$, print \"NO\" and terminate the program. The second (and the last) step is to attach the remaining $n - d - 1$ vertices to the tree. Let's call the vertex free if its degree is less than $k$. Also let's keep all free vertices forming the diameter in some data structure which allows us to take the vertex with the minimum maximal distance to any other vertex and remove such vertices. It can be done by, for example, set of pairs ($dist_v, v$), where $dist_v$ is a maximum distance from the vertex $v$ to any other vertex. Now let's add all vertices from starting from the vertex $d + 1$ (0-indexed) to the vertex $n - 1$, let the current vertex be $u$. We get the vertex with the minimum maximal distance to any other vertex, let it be $v$. Now we increase the degree of vertices $u$ and $v$, add the edge between they, and if $v$ still be free, return it to the data structure, otherwise remove it. The same with the vertex $u$ (it is obvious that its maximal distance to any other vertex will be equals $dist_v + 1$). If at any step our data structure will be empty or the minimum maximal distance will be equals $d$, the answer is \"NO\". Otherwise we can print the answer. See my solution to better understanding. Overall complexity: $O(n \\log n)$ or $O(n)$ (depends on implementation).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, d, k;\n\tcin >> n >> d >> k;\n\t\n\tif (d >= n) {\n\t\tcout << \"NO\" << endl;\n\t\treturn 0;\n\t}\n\t\n\tvector<int> deg(n);\n\tvector<pair<int, int>> ans;\n\tset<pair<int, int>> q;\n\t\n\tfor (int i = 0; i < d; ++i) {\n\t\t++deg[i];\n\t\t++deg[i + 1];\n\t\tif (deg[i] > k || deg[i + 1] > k) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tans.push_back(make_pair(i, i + 1));\n\t}\n\tfor (int i = 1; i < d; ++i)\n\t\tq.insert(make_pair(max(i, d - i), i));\n\t\n\tfor (int i = d + 1; i < n; ++i) {\n\t\twhile (!q.empty() && deg[q.begin()->second] == k)\n\t\t\tq.erase(q.begin());\n\t\tif (q.empty() || q.begin()->first == d) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\treturn 0;\n\t\t}\n\t\t++deg[i];\n\t\t++deg[q.begin()->second];\n\t\tans.push_back(make_pair(i, q.begin()->second));\n\t\tq.insert(make_pair(q.begin()->first + 1, i));\n\t}\n\t\n\tassert(int(ans.size()) == n - 1);\n\tcout << \"YES\" << endl;\n\tvector<int> p(n);\n\tfor (int i = 0; i < n; i++)\n\t    p[i] = i;\n\trandom_shuffle(p.begin(), p.end());\n\tfor (int i = 0; i < n - 1; ++i)\n\t    if (rand() % 2)\n\t\t    cout << p[ans[i].first] + 1 << \" \" << p[ans[i].second] + 1 << endl;\n\t\telse\n\t\t    cout << p[ans[i].second] + 1 << \" \" << p[ans[i].first] + 1 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1003",
    "index": "F",
    "title": "Abbreviation",
    "statement": "You are given a text consisting of $n$ space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. $w_i$ is the $i$-th word of text. All words consist only of lowercase Latin letters.\n\nLet's denote a segment of words $w[i..j]$ as a sequence of words $w_i, w_{i + 1}, \\dots, w_j$. Two segments of words $w[i_1 .. j_1]$ and $w[i_2 .. j_2]$ are considered \\textbf{equal} if $j_1 - i_1 = j_2 - i_2$, $j_1 \\ge i_1$, $j_2 \\ge i_2$, and for every $t \\in [0, j_1 - i_1]$ $w_{i_1 + t} = w_{i_2 + t}$. For example, for the text \"to be or not to be\" the segments $w[1..2]$ and $w[5..6]$ are equal, they correspond to the words \"to be\".\n\nAn abbreviation is a replacement of some segments of words with their first \\textbf{uppercase} letters. In order to perform an abbreviation, you have to choose \\textbf{at least two} non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text \"a ab a a b ab a a b c\" you can replace segments of words $w[2..4]$ and $w[6..8]$ with an abbreviation \"AAA\" and obtain the text \"a AAA b AAA b c\", or you can replace segments of words $w[2..5]$ and $w[6..9]$ with an abbreviation \"AAAB\" and obtain the text \"a AAAB AAAB c\".\n\nWhat is the minimum length of the text after at most one abbreviation?",
    "tutorial": "Let $eq_{i, j}$ equals true if words $s_i$ and $s_j$ are equal, otherwise it will be equals false. We can iterate over all pairs of words and compare they just using standard string comparator (constraints are really small so we can do it naively). The next step is to calculate dynamic programming $dp_{i, j}$, which will be equal to the maximum length of coinciding segments of words which starts in positions $i$ and $j$, respectively. In other words, if $dp_{i, j}$ equals $k$, then $s[i..i+k-1] = s[j..j+k-1]$, word by word. We can calculate this dynamic programming in reverse order ($i := n - 1 .. 0, j := n - 1 .. 0$) and $dp_{i, j} := 0$ if $s_i \\ne s_j$, else if $i < n - 1$ and $j < n - 1$, then $dp_{i, j} := dp_{i + 1, j + 1} + 1$, otherwise $dp_{i, j} := 1$. Let's keep the length of the text in the variable $allsum$. Then iterate over all starting positions of the possible abbreviation and all its possible lengths. Let the current starting position will be equals $i$ (0-indexed) and its length will be equal $j$. Then we need to calculate the number of possible replacements by its abbreviation. Let it be $cnt$ and now it equals $1$. Let's iterate over all positions $pos$, at the beginning $pos = i + j$ (0-indexed). If $dp_{i, pos} \\ge j$ then we can replace the segment of words which starts at the position $pos$ with its abbreviation, so $cnt := cnt + 1$ and $pos := pos + j$ (because we cannot replace intersecting segments), otherwise $pos := pos + 1$. After this we need to update the answer. The length of the segment of words $s[i..j]$ can be calculated easily, let it be $seglen$. Also let $segcnt$ be the number of words in the current segment of words. Then we can update the answer with the value $allsum - seglen * cnt + cnt * segcnt$. Overall complexity is $O(n^3 + n \\cdot \\sum\\limits_{i = 0}^{n - 1}|s_i|)$, where $|s_i|$ is the length of the $i$-th word.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 303;\n\nint n;\nbool eq[N][N];\nint dp[N][N];\nstring s[N];\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tcin >> n;\n\tint allsum = n - 1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> s[i];\n\t\tallsum += s[i].size();\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\teq[i][i] = true;\n\t\tfor (int j = 0; j < i; ++j) {\n\t\t\teq[i][j] = eq[j][i] = s[i] == s[j];\n\t\t}\n\t}\n\t\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tfor (int j = n - 1; j >= 0; --j) {\n\t\t\tif (eq[i][j]) {\n\t\t\t\tif (i + 1 < n && j + 1 < n)\n\t\t\t\t\tdp[i][j] = dp[i + 1][j + 1] + 1;\n\t\t\t\telse\n\t\t\t\t\tdp[i][j] = 1;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint ans = allsum;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint sum = 0;\n\t\tfor (int j = 0; i + j < n; ++j) {\n\t\t\tsum += s[i + j].size();\n\t\t\tint cnt = 1;\n\t\t\tfor (int pos = i + j + 1; pos < n; ++pos) {\n\t\t\t\tif (dp[i][pos] > j) {\n\t\t\t\t\t++cnt;\n\t\t\t\t\tpos += j;\n\t\t\t\t}\n\t\t\t}\n\t\t\tint cur = allsum - sum * cnt + (j + 1) * cnt - j * cnt;\n\t\t\tif (cnt > 1 && ans > cur) {\n\t\t\t\tans = cur;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "hashing",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1004",
    "index": "A",
    "title": "Sonya and Hotels",
    "statement": "Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.\n\nThe country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordinate $x_i$. Sonya is a smart girl, so she does not open two or more hotels in the same city.\n\nSonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $d$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel.\n\nBecause Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $n$ hotels to the new one is equal to $d$.",
    "tutorial": "One hotel always can be built to the left of the first hotel. One more can be built to the right of the last hotel. Let's look at each pair of the adjacent hotels. If the distance between these two hotels is greater than $2\\cdot d$, we can build one hotel at a distance of $d$ to the right from the left hotel and one more at a distance of $d$ to the left from the right hotel. If the distance between these two hotels is equal to $2\\cdot d$, we can build only one hotel in the middle of them. Otherwise, we can not build a hotel between them.",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1004",
    "index": "B",
    "title": "Sonya and Exhibition",
    "statement": "Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.\n\nThere are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions should contain exactly one flower: a rose or a lily.\n\nShe knows that exactly $m$ people will visit this exhibition. The $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.\n\nSonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.",
    "tutorial": "Note, that it is always optimal to use roses in even positions and lilies in odd positions. That is, the string $01010101010\\ldots$ is always optimal.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1004",
    "index": "C",
    "title": "Sonya and Robots",
    "statement": "Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.\n\nSonya has drawn $n$ numbers in a row, $a_i$ is located in the $i$-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position.\n\nSonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one.\n\nFor example, if the numbers $[1, 5, 4, 1, 3]$ are written, and Sonya gives the number $1$ to the first robot and the number $4$ to the second one, the first robot will stop in the $1$-st position while the second one in the $3$-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number $4$ to the first robot and the number $5$ to the second one, they will meet since the first robot will stop in the $3$-rd position while the second one is in the $2$-nd position.\n\nSonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot.\n\nSonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs ($p$, $q$), where she will give $p$ to the first robot and $q$ to the second one. Pairs ($p_i$, $q_i$) and ($p_j$, $q_j$) are different if $p_i\\neq p_j$ or $q_i\\neq q_j$.\n\nUnfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of pairs that she can give to robots so that they will not meet.",
    "tutorial": "Let's assume that our left robot is located in the $p$ position. The robot could be there only if the value that is written there did not occur earlier. The number of possible locations of the second robot is equal to the number of distinct numbers on the segment $[(p+1)\\ldots n]$. Let $dp_i$ be the number of different numbers on $[(p+1)\\ldots n]$. Let's find these number from right to left. If $a_i$ occurs the first time $dp_i=dp_{i+1} + 1$, otherwise, $dp_i=dp_{i+1}$.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1004",
    "index": "D",
    "title": "Sonya and Matrix",
    "statement": "Since Sonya has just learned the basics of matrices, she decided to play with them a little bit.\n\nSonya imagined a new type of matrices that she called rhombic matrices. These matrices have exactly one zero, while all other cells have the Manhattan distance to the cell containing the zero. The cells with equal numbers have the form of a rhombus, that is why Sonya called this type so.\n\nThe Manhattan distance between two cells ($x_1$, $y_1$) and ($x_2$, $y_2$) is defined as $|x_1 - x_2| + |y_1 - y_2|$. For example, the Manhattan distance between the cells $(5, 2)$ and $(7, 1)$ equals to $|5-7|+|2-1|=3$.\n\n\\begin{center}\n{\\small Example of a rhombic matrix.}\n\\end{center}\n\nNote that rhombic matrices are uniquely defined by $n$, $m$, and the coordinates of the cell containing the zero.\n\nShe drew a $n\\times m$ rhombic matrix. She believes that you can not recreate the matrix if she gives you only the elements of this matrix in some arbitrary order (i.e., the sequence of $n\\cdot m$ numbers). Note that Sonya will not give you $n$ and $m$, so only the sequence of numbers in this matrix will be at your disposal.\n\nWrite a program that finds such an $n\\times m$ rhombic matrix whose elements are the same as the elements in the sequence in some order.",
    "tutorial": "Suppose that a matrix has sizes $n\\times m$, zero is located at $(x,y)$. Let $a$ be the distance to the cell $(1,1)$, and let $b$ the distance to the cell $(n,m)$. Obvious that the farthest distance from the zero cell will be to a corner cell. The maximum number in the list is equal to the maximum distance to a corner cell (let's assume that it is $b$). We know that $n\\cdot m = t$; $a=x-1+y-1$; $b=n-x+m-y$; $n+m=a+b+2$. And $a=n+m-b-2$; $x-1+y-1=n+m-b-2$; $y=n+m-b-x$. Let's find the minimum $i$ $(i>0$) such that the number of occurrences of $i$ in the list is not equal to $4\\cdot i$. We can notice that $x=i$. Let's look at each pair $(n, m)$ ($n\\cdot m=t$). If we know $n, m, x$, and $b$, we can find $y$ and restore the matrix. If it could be done, we already found the answer.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1004",
    "index": "E",
    "title": "Sonya and Ice Cream",
    "statement": "Sonya likes ice cream very much. She eats it even during programming competitions. That is why the girl decided that she wants to open her own ice cream shops.\n\nSonya lives in a city with $n$ junctions and $n-1$ streets between them. All streets are two-way and connect two junctions. It is possible to travel from any junction to any other using one or more streets. City Hall allows opening shops only on junctions. The girl cannot open shops in the middle of streets.\n\nSonya has exactly $k$ friends whom she can trust. If she opens a shop, one of her friends has to work there and not to allow anybody to eat an ice cream not paying for it. Since Sonya does not want to skip an important competition, she will not work in shops personally.\n\nSonya wants all her ice cream shops to form a simple path of the length $r$ ($1 \\le r \\le k$), i.e. to be located in different junctions $f_1, f_2, \\dots, f_r$ and there is street between $f_i$ and $f_{i+1}$ for each $i$ from $1$ to $r-1$.\n\nThe girl takes care of potential buyers, so she also wants to minimize the maximum distance between the junctions to the nearest ice cream shop. The distance between two junctions $a$ and $b$ is equal to the sum of all the street lengths that you need to pass to get from the junction $a$ to the junction $b$. So Sonya wants to minimize\n\n$$\\max_{a} \\min_{1 \\le i \\le r} d_{a,f_i}$$\n\nwhere $a$ takes a value of all possible $n$ junctions, $f_i$ — the junction where the $i$-th Sonya's shop is located, and $d_{x,y}$ — the distance between the junctions $x$ and $y$.\n\nSonya is not sure that she can find the optimal shops locations, that is why she is asking you to help her to open not more than $k$ shops that will form a simple path and the maximum distance between any junction and the nearest shop would be minimal.",
    "tutorial": "The editorial for the main solution with centroid decomposition will be published later. Another Solution (without really formal proof) It is possible to show, that if we have all weights equal to $1$, then optimal answer is always a middle part of diameter of right length. However, weights are arbitrary. Then we need to select a \"weighted\" middle part. We can do it in a following way: set two pointers - one to the diameter beginning, and one to the end. And while the number of vertices is greater $k$ we move the pointer, which has moved less from it's end. However, in fact, sometimes we need to look at the neighboring $\\pm 1$ possible subpaths -- for example if the last step was the same distance, then the optimal move depends on where the edge was longer. This way we need to count answer for $\\le 3$ paths. To count the answer for path we can run few dfs's, each of them will cover only part of graph, which hangs on related vertex of the path. Complexity is $\\mathcal{O}(n)$. The sketch of the proof is something like this: Examine the diameter. Notice, that the answer should contain it's middle point (vertex, which is most close to $1/2$) because the answer would be greater than the largest half of this diameter otherwise. From this we already bounded our answer, but we need more. Then we want to start to grow the way to the ends of the diameter, so that at least from the end of the diameter of the distance was small. Not the fact that this will be enough (for example, if there are several diameters), but it is necessary. Two pointers are needed because growing in two directions may be necessary unevenly.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "shortest paths",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1005",
    "index": "A",
    "title": "Tanya and Stairways",
    "statement": "Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $1$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $3$ steps, and the second contains $4$ steps, she will pronounce the numbers $1, 2, 3, 1, 2, 3, 4$.\n\nYou are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.\n\nThe given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.",
    "tutorial": "The answer contains such elements $a_i$ that $a_{i+1}=1$. Also add to the answer the last element $a_n$.",
    "code": "int n;\ncin >> n;\nvector<int> a;\nint p = -1;\nforn(i, n) {\n    int x;\n    cin >> x;\n    if (x == 1 && p != -1)\n        a.push_back(p);\n    p = x;    \n}\na.push_back(p);\ncout << a.size() << endl;\nfor (int i: a)\n    cout << i << \" \";",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1005",
    "index": "B",
    "title": "Delete from the Left",
    "statement": "You are given two strings $s$ and $t$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $1$. You can't choose a string if it is empty.\n\nFor example:\n\n- by applying a move to the string \"where\", the result is the string \"here\",\n- by applying a move to the string \"a\", the result is an empty string \"\".\n\nYou are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.\n\nWrite a program that finds the minimum number of moves to make two given strings $s$ and $t$ equal.",
    "tutorial": "Let's find the value $w$ - the length of the longest common suffix of $s$ and $t$. You can easily find it in one linear loop: just compare the last letters of $s$ and $t$. If they are equal then compare before the last letters of $s$ and $t$. And so on. The last $w$ letters of $s$ and $t$ are two equal strings which will be the result of after optimal moves. So the answer is $|s|+|t|-2 \\cdot w$.",
    "code": "string s, t;\ncin >> s >> t;\nint w = 0;\nwhile (true) {\n    int i = s.length() - w - 1;\n    int j = t.length() - w - 1;\n    if (i >= 0 && j >= 0 && s[i] == t[j])\n        w++;\n    else\n        break;\n}\ncout << s.length() + t.length() - 2 * w << endl;",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1005",
    "index": "C",
    "title": "Summarize to the Power of Two",
    "statement": "A sequence $a_1, a_2, \\dots, a_n$ is called good if, for each element $a_i$, there exists an element $a_j$ ($i \\ne j$) such that $a_i+a_j$ is a power of two (that is, $2^d$ for some non-negative integer $d$).\n\nFor example, the following sequences are good:\n\n- $[5, 3, 11]$ (for example, for $a_1=5$ we can choose $a_2=3$. Note that their sum is a power of two. Similarly, such an element can be found for $a_2$ and $a_3$),\n- $[1, 1, 1, 1023]$,\n- $[7, 39, 89, 25, 89]$,\n- $[]$.\n\nNote that, by definition, an empty sequence (with a length of $0$) is good.\n\nFor example, the following sequences are not good:\n\n- $[16]$ (for $a_1=16$, it is impossible to find another element $a_j$ such that their sum is a power of two),\n- $[4, 16]$ (for $a_1=4$, it is impossible to find another element $a_j$ such that their sum is a power of two),\n- $[1, 3, 2, 8, 8, 8]$ (for $a_3=2$, it is impossible to find another element $a_j$ such that their sum is a power of two).\n\nYou are given a sequence $a_1, a_2, \\dots, a_n$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.",
    "tutorial": "You should delete only such $a_i$ for which there is no such $a_j$ ($i \\ne j$) that $a_i+a_j$ is a power of $2$. For each value let's find the number of its occurrences. You can use simple $map$ standard data-structure. Do $c[a[i]] := c[a[i]]+1$ for each element $a[i]$. Now you can easily check that $a_i$ doesn't have a pair $a_j$. Let's iterate over all possible sums $s=2^0, 2^1, \\dots, 2^{30}$ and for each $s$ find calculate $s-a[i]$. If for some $s$: $c[s-a[i]] \\ge 2$ or $c[s-a[i]] = 1$ && $s-a[i] \\ne a[i]$ then a pair $a_j$ exists. Note that in C++ solutions, it's better to first check that $s-a[i]$ is a key in $c$, and only after it calculate $c[s - a[i]]$. This needs to be done, since in C++ when you access a key using the \"square brackets\" operator, a default mapping key-value is created on the absence of the key. This increases both the running time and the memory consumption.",
    "code": "int n;\ncin >> n;\nvector<int> a(n);\nmap<int,int> c;\nforn(i, n) {\n    cin >> a[i];\n    c[a[i]]++;\n}\nint ans = 0;\nforn(i, n) {\n    bool ok = false;\n    forn(j, 31) {\n        int x = (1 << j) - a[i];\n        if (c.count(x) && (c[x] > 1 || (c[x] == 1 && x != a[i])))\n            ok = true;\n    }\n    if (!ok)\n        ans++;\n}\ncout << ans << endl;",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1005",
    "index": "D",
    "title": "Polycarp and Div 3",
    "statement": "Polycarp likes numbers that are divisible by 3.\n\nHe has a huge number $s$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $3$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $m$ such cuts, there will be $m+1$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $3$.\n\nFor example, if the original number is $s=3121$, then Polycarp can cut it into three parts with two cuts: $3|1|21$. As a result, he will get two numbers that are divisible by $3$.\n\nPolycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.\n\nWhat is the maximum number of numbers divisible by $3$ that Polycarp can obtain?",
    "tutorial": "There are multiple approaches to solve this problem. We will use dynamic programming approach. Let's calculate values of the array $z[0 \\dots n]$, where $z[i]$ is the answer for prefix of the length $i$. Obviously, $z[0] := 0$, since for the empty string (the prefix of the length $0$) the answer is $0$. For $i>0$ you can find $z[i]$ in the following way. Let's look in the last digit of the prefix of length $i$. It has index $i-1$. Either it doesn't belong to segment divisible by $3$, or it belongs. If it doesn't belongs, it means we can't use the last digit, so $z[i] = z[i-1]$. If it belongs we need to find shortest $s[j \\dots i-1]$ that is divisible by $3$ and try to update $z[i]$ with the value $z[j]+1$. It means that we \"bite off\" the shortest divisible by $3$ suffix and reduce the problem to a previous. A number is divisible by $3$ if and only if sum of its digits is divisible by $3$. So the task is to find the shortest suffix of $s[0 \\dots i-1]$ with sum of digits divisible by $3$. If such suffix is $s[j \\dots i-1]$ then $s[0 \\dots j-1]$ and $s[0 \\dots i-1]$ have the same remainder of sum of digits modulo $3$. Let's maintain $fin[0 \\dots 2]$ - array of the length $3$, where $fin[r]$ is the length of the longest processed prefix with sum of digits equal to $r$ modulo $3$. Use $fin[r]=-1$ if there is no such prefix. It is easy to see that $j=fin[r]$ where $r$ is the sum of digits on the $i$-th prefix modulo $3$. So to find the maximal $j \\le i-1$ that substring $s[j \\dots i-1]$ is divisible by $3$, just check that $fin[r] \\ne -1$ and use $j=fin[r]$, where $r$ is the sum of digits on the $i$-th prefix modulo $3$. It means that to handle case that the last digit belongs to divisible by $3$ segment, you should try to update $z[i]$ with value $z[fin[r]] + 1$. In other words, just do if (fin[r] != -1) z[i] = max(z[i], z[fin[r]] + 1). Sequentially calculating the values of $z [0 \\dots n]$, we obtain a linear $O(n)$ solution.",
    "code": "string s;\ncin >> s;\nint n = s.length();\n\nint r = 0;\nvector<int> fin(3, -1);\nfin[0] = 0;\n\nvector<int> z(n + 1);\nfor (int i = 1; i <= n; i++) {\n    r = (r + s[i - 1] - '0') % 3;\n    z[i] = z[i - 1];\n    if (fin[r] != -1)\n        z[i] = max(z[i], z[fin[r]] + 1);\n    fin[r] = i;\n}\n\ncout << z[n] << endl;",
    "tags": [
      "dp",
      "greedy",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1005",
    "index": "E1",
    "title": "Median on Segments (Permutations Edition)",
    "statement": "You are given a permutation $p_1, p_2, \\dots, p_n$. A permutation of length $n$ is a sequence such that each integer between $1$ and $n$ occurs exactly once in the sequence.\n\nFind the number of pairs of indices $(l, r)$ ($1 \\le l \\le r \\le n$) such that the value of the median of $p_l, p_{l+1}, \\dots, p_r$ is exactly the given number $m$.\n\nThe median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.\n\nFor example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence.\n\nWrite a program to find the number of pairs of indices $(l, r)$ ($1 \\le l \\le r \\le n$) such that the value of the median of $p_l, p_{l+1}, \\dots, p_r$ is exactly the given number $m$.",
    "tutorial": "The segment $p[l \\dots r]$ has median equals $m$ if and only if $m$ belongs to it and $less=greater$ or $less=greater-1$, where $less$ is number of elements in $p[l \\dots r]$ that strictly less than $m$ and $greater$ is number of elements in $p[l \\dots r]$ that strictly greater than $m$. Here we've used a fact that $p$ is a permutation (on $p[l \\dots r]$ there is exactly one occurrence of $m$). In other words, $m$ belongs $p[l \\dots r]$ and the value $greater-less$ equals $0$ or $1$. Calculate prefix sums $sum[0 \\dots n]$, where $sum[i]$ the value $greater-less$ on the prefix of the length $i$ (i.e. on the subarray $p[0 \\dots i-1]$). For fixed value $r$ it is easy to calculate number of such $l$ that $p[l \\dots r]$ is suitable. At first, check that $m$ met on $[0 \\dots r]$. Valid values $l$ are such indices that: no $m$ on $[0 \\dots l-1]$ and $sum[l]=sum[r]$ or $sum[r]=sum[l]+1$. Let's maintain number of prefix sums $sum[i]$ to the left of $m$ for each value. We can use just a map $c$, where $c[s]$ is number of such indices $l$ that $sum[l]=s$ and $l$ is to the left of $m$. So for each $r$ that $p[0 \\dots r]$ contains $m$ do ans += c[sum] + c[sum - 1], where $sum$ is the current value $greater-less$. Time complexity is $O(n \\log n)$ if a standard map is used or $O(n)$ if classical array for $c$ is used (remember about possible negative indices, just use an offset).",
    "code": "int n, m;\ncin >> n >> m;\nvector<int> p(n);\nforn(i, n)\n    cin >> p[i];\nmap<int,int> c;\nc[0] = 1;\nbool has = false;\nint sum = 0;\nlong long ans = 0;\nfor (int r = 0; r < n; r++) {\n    if (p[r] < m)\n        sum--;\n    else if (p[r] > m)\n        sum++;\n\n    if (p[r] == m)\n        has = true;\n    if (has)\n        ans += c[sum] + c[sum - 1];\n    else\n        c[sum]++;\n}\ncout << ans << endl;",
    "tags": [
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1005",
    "index": "E2",
    "title": "Median on Segments (General Case Edition)",
    "statement": "You are given an integer sequence $a_1, a_2, \\dots, a_n$.\n\nFind the number of pairs of indices $(l, r)$ ($1 \\le l \\le r \\le n$) such that the value of median of $a_l, a_{l+1}, \\dots, a_r$ is exactly the given number $m$.\n\nThe median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.\n\nFor example, if $a=[4, 2, 7, 5]$ then its median is $4$ since after sorting the sequence, it will look like $[2, 4, 5, 7]$ and the left of two middle elements is equal to $4$. The median of $[7, 1, 2, 9, 6]$ equals $6$ since after sorting, the value $6$ will be in the middle of the sequence.\n\nWrite a program to find the number of pairs of indices $(l, r)$ ($1 \\le l \\le r \\le n$) such that the value of median of $a_l, a_{l+1}, \\dots, a_r$ is exactly the given number $m$.",
    "tutorial": "Let's define a function greaterCount($m$) - number of subarrays with median greater or equal than $m$. In this case, the answer on the problem is greaterCount($m$) $-$ greaterCount($m + 1$). The subarray $a[l \\dots r]$ has median greater or equal than $m$, if and only if $notLess>less$, where $notLess$ is the number equal or greater than $m$ elements, and $less$ is the number of less than $m$ elements. In other words, instead of processing $a[l \\dots r]$ you can use the sequence $x[l \\dots r]$ containing $-1$ or/and $+1$. An element $x[i]=-1$, if $a[i]<m$. An element $x[i]=+1$, if $a[i] \\ge m$. Now, the median of $a[l \\dots r]$ is greater or equal than $m$ if and only if $x[l] + x[l+1] + \\dots + x[r] > 0$. Let's iterate over $a$ from left to right. Maintain the current partial sum $sum=x[0]+x[1]+\\dots+x[i]$. Additionally, in the array $s$ let's maintain the number of partial sum for each its value. It means that before increase of $i$ you should do s[sum]++. So if $i$ is the index of the right endpoint of a subarray (i.e. $r=i$), then number of suitable indices $l$ is number of such $j$ that $x[0]+x[1]+\\dots+x[j]<sum$. In other words, find sum of all $s[w]$, where $w<sum$ - it is exactly number of indices with partial sum less than $sum$. Each time partial sum changes on $-1$ or $+1$. So the value \"sum of all $s[w]$, where $w<sum$\" is easy to recalculate on each change. If you decrease $sum$, just subtract the value $s[sum]$. If you increase $sum$, before increasing just add $s[sum]$. Since indices in $s$ can be from $-n$ to $n$, you can use 0-based indices using an array $s[0 \\dots 2 \\cdot n]$. In this case, initialize $sum$ as $n$ but not as $0$ (it makes $sum$ to be non-negative on each step). This solution works in $O(n)$.",
    "code": "long long greaterCount(int m) {\n    vector<int> s(2 * n + 1);\n    int sum = n;\n    long long result = 0;\n    s[sum] = 1;\n    long long add = 0;\n    forn(i, n) {\n        if (a[i] < m)\n            sum--, add -= s[sum];\n        else\n            add += s[sum], sum++;\n        result += add;\n        s[sum]++;\n    }\n    return result;\n}\n\ncin >> n >> m;\na = vector<int>(n);\nforn(i, n)\n    cin >> a[i];\ncout << greaterCount(m) - greaterCount(m + 1) << endl;",
    "tags": [
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1005",
    "index": "F",
    "title": "Berland and the Shortest Paths",
    "statement": "There are $n$ cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from $1$ to $n$.\n\nIt is known that, from the capital (the city with the number $1$), you can reach any other city by moving along the roads.\n\nThe President of Berland plans to improve the country's road network. The budget is enough to repair exactly $n-1$ roads. The President plans to choose a set of $n-1$ roads such that:\n\n- it is possible to travel from the capital to any other city along the $n-1$ chosen roads,\n- if $d_i$ is the number of roads needed to travel from the capital to city $i$, moving only along the $n-1$ chosen roads, then $d_1 + d_2 + \\dots + d_n$ is minimized (i.e. as minimal as possible).\n\nIn other words, the set of $n-1$ roads should preserve the connectivity of the country, and the sum of distances from city $1$ to all cities should be minimized (where you can only use the $n-1$ chosen roads).\n\nThe president instructed the ministry to prepare $k$ possible options to choose $n-1$ roads so that both conditions above are met.\n\nWrite a program that will find $k$ possible ways to choose roads for repair. If there are fewer than $k$ ways, then the program should output all possible valid ways to choose roads.",
    "tutorial": "Use BFS to precalculate an array $d$ - the array of the shortest path lengths from the Capital. The condition to minimize sum of distances in each tree is equal to the fact that each tree is a shortest path tree. Let's think about them as about oriented outgoing from the Capital trees. Moving along edges of such trees, you always move by shortest paths. An edge $(u,v)$ can be included into such a tree if and only if $d[u]+1=d[v]$ (since original edges are bidirectional, you should consider each of them twice: as $(u,v)$ and as $(v,u)$). Let's focus only on edges for which $d[u]+1=d[v]$. Call them \"red\" edges. To build a tree for each city (except the Capital) you should choose exactly one red edge finishing in this city. That's why the number of suitable trees is a product of numbers of incoming edges over all vertices (cities). But we need to find only $k$ of such trees. Let's start from some such tree and rebuild it on each step. As initial tree you can choose the first incoming red edge into each vertex (except the City). Actually, we will do exactly increment operation for number in a mixed radix notation. To rebuild a tree iterate over vertices and if the current used red edge is not the last for the vertex, use the next and stop algorithm. Otherwise (the last red edge is used), use the first red edge for this vertex (and go to the next vertex) and continue with the next vertex. Compare this algorithm with simple increment operation for long number.",
    "code": "int n, m, k;\ncin >> n >> m >> k;\nvector<vector<int>> g(n);\nvector<int> a(m), b(m);\nforn(i, m) {\n    cin >> a[i] >> b[i];\n    a[i]--, b[i]--;\n    g[a[i]].push_back(b[i]);\n    g[b[i]].push_back(a[i]);\n}\n\nqueue<int> q;\nq.push(0);\nvector<int> d(n, INT_MAX);\nd[0] = 0;\n\nwhile (!q.empty()) {\n    int u = q.front();\n    q.pop();\n    for (int v: g[u])\n        if (d[v] == INT_MAX) {\n            d[v] = d[u] + 1;\n            q.push(v);\n        }\n}\n\nvector<vector<int>> inc(n);\nforn(i, m) {\n    if (d[a[i]] + 1 == d[b[i]])\n        inc[b[i]].push_back(i);\n    if (d[b[i]] + 1 == d[a[i]])\n        inc[a[i]].push_back(i);\n}\n\nvector<int> f(n);\nvector<string> result;\n\nforn(i, k) {\n    string s(m, '0');\n    for (int j = 1; j < n; j++)\n        s[inc[j][f[j]]] = '1';\n    result.push_back(s);\n\n    bool ok = false;\n    for (int j = 1; j < n; j++)\n        if (f[j] + 1 < inc[j].size()) {\n            ok = true;\n            f[j]++;\n            break;\n        } else\n            f[j] = 0;\n    if (!ok)\n        break;\n}\n\ncout << result.size() << endl;\nforn(i, result.size())\n    cout << result[i] << endl;",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1006",
    "index": "A",
    "title": "Adjacent Replacements",
    "statement": "Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).\n\nMishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it \"Mishka's Adjacent Replacements Algorithm\". This algorithm can be represented as a sequence of steps:\n\n- Replace each occurrence of $1$ in the array $a$ with $2$;\n- Replace each occurrence of $2$ in the array $a$ with $1$;\n- Replace each occurrence of $3$ in the array $a$ with $4$;\n- Replace each occurrence of $4$ in the array $a$ with $3$;\n- Replace each occurrence of $5$ in the array $a$ with $6$;\n- Replace each occurrence of $6$ in the array $a$ with $5$;\n- $\\dots$\n- Replace each occurrence of $10^9 - 1$ in the array $a$ with $10^9$;\n- Replace each occurrence of $10^9$ in the array $a$ with $10^9 - 1$.\n\nNote that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($2i - 1, 2i$) for each $i \\in\\{1, 2, \\ldots, 5 \\cdot 10^8\\}$ as described above.\n\nFor example, for the array $a = [1, 2, 4, 5, 10]$, the following sequence of arrays represents the algorithm:\n\n$[1, 2, 4, 5, 10]$ $\\rightarrow$ (replace all occurrences of $1$ with $2$) $\\rightarrow$ $[2, 2, 4, 5, 10]$ $\\rightarrow$ (replace all occurrences of $2$ with $1$) $\\rightarrow$ $[1, 1, 4, 5, 10]$ $\\rightarrow$ (replace all occurrences of $3$ with $4$) $\\rightarrow$ $[1, 1, 4, 5, 10]$ $\\rightarrow$ (replace all occurrences of $4$ with $3$) $\\rightarrow$ $[1, 1, 3, 5, 10]$ $\\rightarrow$ (replace all occurrences of $5$ with $6$) $\\rightarrow$ $[1, 1, 3, 6, 10]$ $\\rightarrow$ (replace all occurrences of $6$ with $5$) $\\rightarrow$ $[1, 1, 3, 5, 10]$ $\\rightarrow$ $\\dots$ $\\rightarrow$ $[1, 1, 3, 5, 10]$ $\\rightarrow$ (replace all occurrences of $10$ with $9$) $\\rightarrow$ $[1, 1, 3, 5, 9]$. The later steps of the algorithm do not change the array.\n\nMishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.",
    "tutorial": "It is easy to see that for the odd elements there is no changes after applying the algorithm described in the problem statement, and for the even elements there is only one change: each of the even elements will be decreased by $1$. So we can iterate over all the elements of the array and print $a_i - (a_i \\% 2)$, where $x \\% y$ is taking $x$ modulo $y$. Overall complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\tcout << x - !(x & 1) << \" \";\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1006",
    "index": "B",
    "title": "Polycarp's Practice",
    "statement": "Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \\dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $n$ problems in exactly $k$ days.\n\nThus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $k$ days he will solve all the $n$ problems.\n\nThe profit of the $j$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $j$-th day (i.e. if he solves problems with indices from $l$ to $r$ during a day, then the profit of the day is $\\max\\limits_{l \\le i \\le r}a_i$). The total profit of his practice is the sum of the profits over all $k$ days of his practice.\n\nYou want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $n$ problems between $k$ days satisfying the conditions above in such a way, that the total profit is maximum.\n\nFor example, if $n = 8, k = 3$ and $a = [5, 4, 2, 6, 5, 1, 9, 2]$, one of the possible distributions with maximum total profit is: $[5, 4, 2], [6, 5], [1, 9, 2]$. Here the total profit equals $5 + 6 + 9 = 20$.",
    "tutorial": "The maximum possible total profit you can obtain is the sum of the $k$ largest values of the given array. This is obvious because we can always separate these $k$ maximums and then extend the segments corresponding to them to the left or to the right and cover the entire array. I suggest the following: extract $k$ largest values of the given array and place a separator right after each of them (except the rightmost one). Overall complexity is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin); \n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<pair<int, int>> res(n);\n\tvector<int> a(n); \n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> res[i].first;\n\t\ta[i] = res[i].first;\n\t\tres[i].second = i + 1;\n\t}\n\t\n\tsort(res.begin(), res.end());\n\treverse(res.begin(), res.end());\n\tsort(res.begin(), res.begin() + k, [&](pair<int, int> a, pair<int, int> b) { return a.second < b.second; });\n\t\n\tint lst = 0, sum = 0;\n\tfor (int i = 0; i < k - 1; ++i) {\n\t    sum += *max_element(a.begin() + lst, a.begin() + res[i].second);\n\t\tlst = res[i].second;\t\n\t}\n\tsum += *max_element(a.begin() + lst, a.end());\n\tcout << sum << endl;\n\t\n\n\tlst = 0;\n\tfor (int i = 0; i < k - 1; ++i) {\n\t\tcout << res[i].second - lst << \" \";\n\t\tlst = res[i].second;\t\n\t}\n\tcout << n - lst << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1006",
    "index": "C",
    "title": "Three Parts of the Array",
    "statement": "You are given an array $d_1, d_2, \\dots, d_n$ consisting of $n$ integer numbers.\n\nYour task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array.\n\nLet the sum of elements of the first part be $sum_1$, the sum of elements of the second part be $sum_2$ and the sum of elements of the third part be $sum_3$. Among all possible ways to split the array you have to choose a way such that $sum_1 = sum_3$ and $sum_1$ is maximum possible.\n\nMore formally, if the first part of the array contains $a$ elements, the second part of the array contains $b$ elements and the third part contains $c$ elements, then:\n\n$$sum_1 = \\sum\\limits_{1 \\le i \\le a}d_i,$$ $$sum_2 = \\sum\\limits_{a + 1 \\le i \\le a + b}d_i,$$ $$sum_3 = \\sum\\limits_{a + b + 1 \\le i \\le a + b + c}d_i.$$\n\nThe sum of an empty array is $0$.\n\nYour task is to find a way to split the array such that $sum_1 = sum_3$ and $sum_1$ is maximum possible.",
    "tutorial": "Since the given array consists of positive integers, for each value of $a$, there can be at most one value of $c$ such that $sum_1 = sum_3$. We can use binary search on the array of prefix sums of $d$ to find the correct value of $c$, given that it exists. If it does exist and $a+c \\le n$, this is a candidate solution so we store it. Alternatively, we can use the two pointers trick - when $a$ increases, $c$ cannot decrease. Be careful to use 64 bit integers to store sums. Overall complexity is $O(n \\log n)$ or $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\n\nint n;\nint a[200005];\n\nint main() {\n\tios_base::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tcout.tie(nullptr);\n\tcerr.tie(nullptr);\n\n\tcin >> n;\n\tfor (int i=1; i<=n; i++)\n\t\tcin >> a[i];\n\n\tint i = 0, j = n+1;\n\tll zi = 0, zj = 0, solidx = 0;\n\twhile (i < j) {\n\t\tif (zi < zj)\n\t\t\tzi += a[++i];\n\t\telse if (zi > zj)\n\t\t\tzj += a[--j];\n\t\telse {\n\t\t\tsolidx = i;\n\t\t\tzi += a[++i];\n\t\t\tzj += a[--j];\n\t\t}\n\t}\n\t\n\tcout << accumulate(a+1, a+solidx+1, 0ll); // here\n}",
    "tags": [
      "binary search",
      "data structures",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1006",
    "index": "D",
    "title": "Two Strings Swaps",
    "statement": "You are given two strings $a$ and $b$ consisting of lowercase English letters, both of length $n$. The characters of both strings have indices from $1$ to $n$, inclusive.\n\nYou are allowed to do the following changes:\n\n- Choose any index $i$ ($1 \\le i \\le n$) and swap characters $a_i$ and $b_i$;\n- Choose any index $i$ ($1 \\le i \\le n$) and swap characters $a_i$ and $a_{n - i + 1}$;\n- Choose any index $i$ ($1 \\le i \\le n$) and swap characters $b_i$ and $b_{n - i + 1}$.\n\nNote that if $n$ is odd, you are formally allowed to swap $a_{\\lceil\\frac{n}{2}\\rceil}$ with $a_{\\lceil\\frac{n}{2}\\rceil}$ (and the same with the string $b$) but this move is useless. Also you can swap two equal characters but this operation is useless as well.\n\nYou have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.\n\nIn one preprocess move you can replace a character in $a$ with another character. In other words, in a single preprocess move you can choose any index $i$ ($1 \\le i \\le n$), any character $c$ and set $a_i := c$.\n\nYour task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings $a$ and $b$ equal by applying some number of changes described in the list above.\n\nNote that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string $b$ or make any preprocess moves after the first change is made.",
    "tutorial": "Let's divide all characters of both strings into groups in such a way that characters in each group can be swapped with each other with changes. So, there will be following groups: $\\{a_1, a_n, b_1, b_n\\}$, $\\{a_2, a_{n - 1}, b_2, b_{n - 1}\\}$ and so on. Since these groups don't affect each other, we can calculate the number of preprocess moves in each group and then sum it up. How to determine if a group does not need any preprocess moves? For a group consisting of $2$ characters (there will be one such group if $n$ is odd, it will contain $a_{\\lceil\\frac{n}{2}\\rceil}$ and $b_{\\lceil\\frac{n}{2}\\rceil}$), that's easy - if the characters in this group are equal, the answer is $0$, otherwise it's $1$. To determine the required number of preprocess moves for a group consising of four characters, we may use the following fact: this group doesn't require preprocess moves iff the characters in this group can be divided into pairs. So if the group contains four equal characters, or two pairs of equal characters, then the answer for this group is $0$. Otherwise we may check that replacing only one character of $a_i$ and $a_{n - i + 1}$ will be enough; if so, then the answer is $1$, otherwise it's $2$. Overall complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define sqr(a) ((a) * (a))\n#define sz(a) int(a.size())\n#define all(a) a.begin(), a.end()\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n \ntemplate <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {\n\treturn out << \"(\" << a.x << \", \" << a.y << \")\";\n}\n \ntemplate <class A> ostream& operator << (ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tforn(i, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n \nmt19937 rnd(time(NULL));\n \nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst int MOD = INF + 7;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n \nint n;\nstring s, t;\n\nbool read() {\n\tif (!(cin >> n >> s >> t))\n\t\treturn false;\n\treturn true;\n}\n\nvoid solve() {\n\tint ans = 0;\n\tforn(i, n / 2) {\n\t\tmap<char, int> a;\n\t\ta[s[i]]++; a[s[n - i - 1]]++;\n\t\ta[t[i]]++; a[t[n - i - 1]]++;\n\t\tif (sz(a) == 4)\n\t\t\tans += 2;\n\t\telse if (sz(a) == 3)\n\t\t\tans += 1 + (s[i] == s[n - i - 1]);\n\t\telse if (sz(a) == 2)\n\t\t\tans += a[s[i]] != 2;\n\t}\n\t\n\tif (n % 2 == 1 && s[n / 2] != t[n / 2])\n\t\tans++;\n\t\t\n\tcout << ans << endl;\n}\n \nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tint tt = clock();\n \n#endif\n \n\tcerr.precision(15);\n\tcout.precision(15);\n\tcerr << fixed;\n\tcout << fixed;\n\t\n#ifdef _DEBUG\n\twhile (read()) {\t\n#else\n\tif (read()) {\n#endif\n\t\tsolve();\n \n#ifdef _DEBUG\n\tcerr << \"TIME = \" << clock() - tt << endl;\n\ttt = clock();\n#endif\n \n\t}\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1006",
    "index": "E",
    "title": "Military Problem",
    "statement": "In this problem you will have to help Berland army with organizing their command delivery system.\n\nThere are $n$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $a$ is the direct superior of officer $b$, then we also can say that officer $b$ is a direct subordinate of officer $a$.\n\nOfficer $x$ is considered to be a subordinate (direct or indirect) of officer $y$ if one of the following conditions holds:\n\n- officer $y$ is the direct superior of officer $x$;\n- the direct superior of officer $x$ is a subordinate of officer $y$.\n\nFor example, on the picture below the subordinates of the officer $3$ are: $5, 6, 7, 8, 9$.\n\nThe structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army.\n\nFormally, let's represent Berland army as a tree consisting of $n$ vertices, in which vertex $u$ corresponds to officer $u$. The parent of vertex $u$ corresponds to the direct superior of officer $u$. The root (which has index $1$) corresponds to the commander of the army.\n\nBerland War Ministry has ordered you to give answers on $q$ queries, the $i$-th query is given as $(u_i, k_i)$, where $u_i$ is some officer, and $k_i$ is a positive integer.\n\nTo process the $i$-th query imagine how a command from $u_i$ spreads to the subordinates of $u_i$. Typical DFS (depth first search) algorithm is used here.\n\nSuppose the current officer is $a$ and he spreads a command. Officer $a$ chooses $b$ — one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then $a$ chooses the one having minimal index. Officer $a$ gives a command to officer $b$. Afterwards, $b$ uses exactly the same algorithm to spread the command to its subtree. After $b$ finishes spreading the command, officer $a$ chooses the next direct subordinate again (using the same strategy). When officer $a$ cannot choose any direct subordinate who still hasn't received this command, officer $a$ finishes spreading the command.\n\nLet's look at the following example:\n\nIf officer $1$ spreads a command, officers receive it in the following order: $[1, 2, 3, 5 ,6, 8, 7, 9, 4]$.\n\nIf officer $3$ spreads a command, officers receive it in the following order: $[3, 5, 6, 8, 7, 9]$.\n\nIf officer $7$ spreads a command, officers receive it in the following order: $[7, 9]$.\n\nIf officer $9$ spreads a command, officers receive it in the following order: $[9]$.\n\nTo answer the $i$-th query $(u_i, k_i)$, construct a sequence which describes the order in which officers will receive the command if the $u_i$-th officer spreads it. Return the $k_i$-th element of the constructed list or -1 if there are fewer than $k_i$ elements in it.\n\nYou should process queries independently. A query doesn't affect the following queries.",
    "tutorial": "Let's form the following vector $p$: we run DFS from the first vertex and push the vertex $v$ to the vector when entering this vertex. Let $tin_v$ be the position of the vertex $v$ in the vector $p$ (the size of the vector $p$ in moment we call DFS from the vertex $v$) and $tout_v$ be the position of the first vertex pushed to the vector after leaving the vertex $v$ (the size of the vector $p$ in moment when we return from DFS from the vertex $v$). Then it is obvious that the subtree of the vertex $v$ lies in half-interval $[tin_v; tout_v)$. After running such DFS we can answer the queries. Let $pos_i = v_i + k_i - 1$ (answering the $i$-th query). If $pos_i$ is greater than or equal to $n$ then answer to the $i$-th query is \"-1\". We need to check if the vertex $p_{pos_i}$ lies in the subtree of the vertex $v_i$. The vertex $a$ is in the subtree of the vertex $b$ if and only if $[tin_a; tout_a) \\subseteq [tin_b; tout_b)$. If the vertex $p_{pos_i}$ is not in the subtree of the vertex $v_i$ then answer is \"-1\". Otherwise the answer is $p_{pos_i}$. Overall complexity is $O(n + q)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, q;\nvector<vector<int>> tree;\n\nint current_preorder;\nvector<int> preorder, max_preorder;\nvector<int> sorted_by_preorder;\n\nvoid Dfs(int w) {\n  sorted_by_preorder[current_preorder] = w;\n  preorder[w] = current_preorder++;\n  for (int c : tree[w]) {\n    Dfs(c);\n  }\n  max_preorder[w] = current_preorder - 1;\n}\n\nint main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  cin >> n >> q;\n  assert(2 <= n);\n  assert(1 <= q);\n  tree.resize(n);\n  for (int i = 1; i < n; i++) {\n    int p;\n    cin >> p;\n    p--;\n    assert(0 <= p and p < n);\n    tree[p].push_back(i);\n  }\n\n  preorder.resize(n);\n  max_preorder.resize(n);\n  sorted_by_preorder.resize(n);\n  current_preorder = 0;\n  Dfs(0);\n\n  for (int i = 0; i < q; i++) {\n    int u, k;\n    cin >> u >> k;\n    u--; k--;\n    assert(0 <= u and u < n);\n    assert(0 <= k and k < n);\n    k += preorder[u];\n    int answer = -1;\n    if (k <= max_preorder[u]) {\n      answer = sorted_by_preorder[k] + 1;\n      assert(1 <= answer and answer <= n);\n    }\n    cout << answer << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1006",
    "index": "F",
    "title": "Xor-Paths",
    "statement": "There is a rectangular grid of size $n \\times m$. Each cell has a number written on it; the number on the cell ($i, j$) is $a_{i, j}$. Your task is to calculate the number of paths from the upper-left cell ($1, 1$) to the bottom-right cell ($n, m$) meeting the following constraints:\n\n- You can move to the right or to the bottom only. Formally, from the cell ($i, j$) you may move to the cell ($i, j + 1$) or to the cell ($i + 1, j$). The target cell can't be outside of the grid.\n- The xor of all the numbers on the path from the cell ($1, 1$) to the cell ($n, m$) must be equal to $k$ (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and \"xor\" in Pascal).\n\nFind the number of such paths in the given grid.",
    "tutorial": "This is a typical problem on the meet-in-the-middle technique. The number of moves we will made equals $n + m - 2$. So if $n + m$ would be small enough (25 is the upper bound, I think), then we can just run recursive backtracking in $O(2^{n + m - 2})$ or in $O($${n + m - 2}\\choose{m - 1}$$\\cdot (n + m - 2))$ to iterate over all binary masks of lengths $n + m - 2$ containing exactly $m - 1$ ones and check each path described by such mask ($0$ in this mask is the move to the bottom and $1$ is the move to the right) if its xor is $k$. But it is too slow. So let's split this mask of $n + m - 2$ bits into two parts - the left part will consist of $mid = \\lfloor\\frac{n + m - 2}{2}\\rfloor$ bits and the right part will consist of $n + m - 2 - mid$ bits. Note that each left mask (and each right mask too) uniquely describes the endpoint of the path and the path itself. Let's carry $n \\times m$ associative arrays $cnt$ where $cnt_{x, y, c}$ for the endpoint $(x, y)$ and xor $c$ will denote the number of paths which end in the cell $(x, y)$ having xor $c$. Let's run recursive backtracking which will iterate over paths starting from the cell $(1, 1)$ and move to the right or to the bottom and maintain xor of the path. If we made $mid$ moves and we are currently in the cell $(x, y)$ with xor $c$ right now, set $cnt_{x, y, c} := cnt_{x, y, c} + 1$ and return from the function. Otherwise try to move to the bottom or to the right changing xor as needed. Let's run another recursive backtracking which will iterate over paths starting from the cell $(n, m)$ and move to the left or to the top and maintain xor of the path except the last cell. The same, if we made $n + m - 2 - mid$ moves and we are currently in the cell $(x, y)$ with xor $c$ right now, let's add $cnt_{x, y, k ^ c}$ to the answer (obvious, that way we \"complement\" our xor from the right part of the path with the suitable xor from the left part of the path). Otherwise try to move to the left or to the top changing xor as needed. So, this is the meet-in-the-middle technique (at least the way I code it). Overall complexity is $O(2^{\\frac{n + m - 2}{2}} \\cdot \\frac{n + m - 2}{2})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 20;\n\nmap<long long, int> v[N][N];\n\nint n, m;\nint half;\nlong long k;\nlong long a[N][N];\nlong long ans;\n\nvoid calclf(int x, int y, long long val, int cnt) {\n\tval ^= a[x][y];\n\tif (cnt == half) {\n\t\t++v[x][y][val];\n\t\treturn;\n\t}\n\tif (x + 1 < n)\n\t\tcalclf(x + 1, y, val, cnt + 1);\n\tif (y + 1 < m)\n\t\tcalclf(x, y + 1, val, cnt + 1);\n}\n\nvoid calcrg(int x, int y, long long val, int cnt) {\n\tif (cnt == n + m - 2 - half) {\n\t\tif (v[x][y].count(k ^ val))\n\t\t\tans += v[x][y][k ^ val];\n\t\treturn;\n\t}\n\tif (x > 0)\n\t\tcalcrg(x - 1, y, val ^ a[x][y], cnt + 1);\n\tif (y > 0)\n\t\tcalcrg(x, y - 1, val ^ a[x][y], cnt + 1);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m >> k;\n\thalf = (n + m - 2) / 2;\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tcin >> a[i][j];\n\t\t}\n\t}\n\t\n\tcalclf(0, 0, 0, 0);\n\tcalcrg(n - 1, m - 1, 0, 0);\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "meet-in-the-middle"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1007",
    "index": "A",
    "title": "Reorder the Array",
    "statement": "You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.\n\nFor instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case.\n\nHelp Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.",
    "tutorial": "The answer is $n$ minus maximal number of equal elements. Let the maximal number of equals be $x$. Let's proove that $n-x$ is reachable. It's clear that for every permutation of the array the answer will be the same, so let's sort the array in non-decreasing order. Now we should just make a left shift on $x$. After it the $n-x$ right elements will move to a position of a smaller element. Now let's proove that the answer is no more than $n-x$. Let's consider some permutation. It's known that every permutation breaks into cycles. Let's look at two occurences of the same number in the same cycle. Then there is at least one number between them which will move on a postion of a non-smaller element. Even if it the same occurence and even if the length of the cycle is $1$, we can say that for every occurence of this number there is at least one number which moves on a postion of a non-smaller one. So if some number occurs $x$ times, there are at least $x$ bad positions and therefore no more than $n-x$ good positions. To count the number of equals you can, for instance, use std::map.",
    "tags": [
      "combinatorics",
      "data structures",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1007",
    "index": "B",
    "title": "Pave the Parallelepiped",
    "statement": "You are given a rectangular parallelepiped with sides of positive integer lengths $A$, $B$ and $C$.\n\nFind the number of different groups of three integers ($a$, $b$, $c$) such that $1\\leq a\\leq b\\leq c$ and parallelepiped $A\\times B\\times C$ can be paved with parallelepipeds $a\\times b\\times c$. Note, that all small parallelepipeds \\textbf{have to be rotated in the same direction}.\n\nFor example, parallelepiped $1\\times 5\\times 6$ can be divided into parallelepipeds $1\\times 3\\times 5$, but can not be divided into parallelepipeds $1\\times 2\\times 3$.",
    "tutorial": "First solution. First, for every natural number up to $10^5$ we count its number of divisors in $O(\\sqrt{n})$. Also for every unordered set of $3$ masks $(m_1, m_2, m_3)$ of length $3$ we check if there is a way to enumerate them in such a way that $1 \\in m_1$, $2 \\in m_2$ and $3 \\in m_3$. We will call such sets acceptable. Now let's consider two parallelepipeds. For each dimension of the second parallelepiped let's construct a mask of length $3$ which contains the numbers of the dimensions of the first parallelepiped for which the length of the first parallelepiped along this dimension is divisible by the length of the second parallelepiped along the chosen dimension. Now these three masks form an acceptable set iff we can pave the first parallelepiped with the second one. Now for a given parallelepiped let's calculate for every mask of length $3$ the number of possible lengths of the second parallelepiped which would produce this mask. We can do this by taking the GCD of the lengths of the first parallelepiped along the dimensions whose numbers are in the mask, and subtracting from it the calculated numbers for every submask. Now let's iterate over acceptable sets of masks. For each different mask from the set which is included into the set $k$ times we need to calculate the number of ways to take $k$ unordered lengths which produce this mask, and multiply these numbers. The sum of these numbers is the answers to the query. So for every query we need $O \\left( 2^{m^2} \\right)$ operations, where $m = 3$ is the number of dimensions of the parallelepiped. Second solution. First, for every natural number up to $10^5$ we count its number of divisors in $O(\\sqrt{n})$. Then for every query for every subset of numbers in it we keep their GCD and the number of its divisors. So for every subset of this three numbers we know the number of their common divisors. Let's look at the parallelepiped $(a, b, c)$. The way we orient it with respect to the large parallelepiped is determined by a permutation of size $3$ - that is, which dimension would correspond to every dimension in the large one. Using the inclusion-exclusion principle on this permutations we can count how many there are such parallelepipeds (considering the orientation) that we can orient some way to then pave the large parallelepiped with it. Namely, we fix the set of permutations for which our parallelepiped shall satisfy. Then for every side of the small parallelepiped we know which sides of the large one it shall divide. To find the number of such sides of the small one we shall take the number of common divisors of the corresponding sides of the large one. Now to find the number of such small parallelepipeds we must multiply the three resultant numbers. In such way every satisfying this criteria parallelepiped (not considering the orientation) with three different side lengths was counted $6$ times, with two different lengths was counted $3$ times, with one different length was counted $1$ time. But it won't be difficult for us to use the same approach in counting such parallelepipeds, but with no less than two same side lengths: let's say the first and the second. To do this when we fix which permutations this parallelepiped shall satisfy we should just add the condition that its first and second side lengths must be equal, this means they both must divide both of the sets corresponding to them, so instead of this two sets we must take their union. Let's add the resultant number multiplied by three to the answer. Now every parallelepiped with three different side length is still counted $6$ times, with two different is now counted also $6$ times, and with one different is counted $4$ times. The number of satisfying parallelepipeds with equal sides is just the number of common divisors of all the sides of the large parallelepiped. Let's add it multiplied by two, and now every needed parallelepiped is counted $6$ times. We divide this number by $6$ and get the answer. So for every query we need $O \\left( p(m) \\cdot 2^{m!} \\cdot m \\right)$ operations, where $p(m)$ is the number of partitions of $m$, and $m = 3$ is the number of dimensions of the parallelepiped.",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1007",
    "index": "C",
    "title": "Guess two numbers",
    "statement": "\\textbf{This is an interactive problem.}\n\nVasya and Vitya play a game. Vasya thought of two integers $a$ and $b$ from $1$ to $n$ and Vitya tries to guess them. Each round he tells Vasya two numbers $x$ and $y$ from $1$ to $n$. If both $x=a$ and $y=b$ then Vitya wins. Else Vasya must say one of the three phrases:\n\n- $x$ is less than $a$;\n- $y$ is less than $b$;\n- $x$ is greater than $a$ or $y$ is greater than $b$.\n\nVasya can't lie, but if multiple phrases are true, he may choose any of them. For example, if Vasya thought of numbers $2$ and $4$, then he answers with the phrase $3$ to a query $(3, 4)$, and he can answer with the phrase $1$ or phrase $3$ to a query $(1, 5)$.\n\nHelp Vitya win in no more than $600$ rounds.",
    "tutorial": "First solution: Let's keep the set of possible answers as a union of three rectangles forming an angle: $A = \\left[ x_l, x_m \\right) \\times \\left[ y_l, y_m \\right)$, $B = \\left[ x_l, x_m \\right) \\times \\left[ y_m, y_r \\right)$ and $C = \\left[ x_m, x_r \\right) \\times \\left[ y_l, y_m \\right)$, where $x_l < x_m \\leq x_r$ and $y_l < y_m \\leq y_r$. Let $S_A$, $S_B$ and $S_C$ be their areas. We will denote such state as $(x_l, x_m, x_r, y_l, y_m, y_r)$. The initial state is $(0, n + 1, n + 1, 0, n + 1, n + 1)$. Now there are three cases. $S_B \\leq S_A + S_C$ and $S_B \\leq S_A + S_B$, then we will make a query $\\left( \\left\\lfloor \\frac{x_l + x_m}{2} \\right\\rfloor, \\left\\lfloor \\frac{y_l + y_m}{2} \\right\\rfloor \\right)$. If $S_B > S_A + S_C$, we will make a query $\\left( \\left\\lfloor \\frac{x_l + x_m}{2} \\right\\rfloor, y_m \\right)$. Finally, if $S_C > S_A + S_B$, we will make a query $\\left( x_m, \\left\\lfloor \\frac{y_l + y_m}{2} \\right\\rfloor \\right)$. In case of every response to every query, the new set of possible answers will also form an angle. Now we want to prove that the area of the angle decreases at least by a quarter every two requests. In case (1) if the answer is $1$, then we move to a state $\\left( \\left\\lfloor \\frac{x_l + x_m}{2} \\right\\rfloor + 1, x_m, x_r, y_l, y_m, y_r \\right)$. We cut off at least half of $A$ and at least half of $B$. But $\\frac{S_A}{2} + \\frac{S_B}{2} = \\frac{S_A + S_B}{4} + \\frac{S_A + S_B}{4} \\geq \\frac{S_A + S_B}{4} + \\frac{S_C}{4} = \\frac{S_A + S_B + S_C}{4}$. I.e. We have cut off at least a quarter already within just one request. If the answer is $2$, the situation is similar. Finally, if the answer is $3$, then we move to a state $\\left( x_l, \\left\\lfloor \\frac{x_l + x_m}{2} \\right\\rfloor, x_r, y_l, \\left\\lfloor \\frac{y_l + y_m}{2} \\right\\rfloor, y_r \\right)$. We cut off at least quarter of $A$, at least half of $B$ and at least half of $C$. But $\\frac{S_A}{4} + \\frac{S_B}{2} + \\frac{S_C}{2} \\geq \\frac{S_A}{4} + \\frac{S_B}{4} + \\frac{S_C}{4} = \\frac{S_A + S_B + S_C}{4}$. We also have cut off at least a quarter within just one request. Thus in case (1) we cut off at least a quarter within one request. In case (2) if the answer is $1$, then we move to a state $\\left( \\left\\lfloor \\frac{x_l + x_m}{2} \\right\\rfloor + 1, x_m, x_r, y_l, y_m, y_r \\right)$. We cut off at least half of $A$ and at least half of $B$. But $\\frac{S_A}{2} + \\frac{S_B}{2} \\geq \\frac{S_B}{2} \\geq \\frac{S_B}{4} + \\frac{S_B}{4} \\geq \\frac{S_B}{4} + \\frac{S_A + S_C}{4} = \\frac{S_A + S_B + S_C}{4}$. We have cut off at least a quarter within just one request. If the answer is $2$, then we move to a state $(x_l, x_r, x_r, y_m + 1, y_r, y_r)$. But then if will be case (1), thus we will cut off at least a quarter with the next request. Finally, if the answer is $3$, then we move to a state $\\left( x_l, \\left\\lfloor \\frac{x_l + x_m}{2} \\right\\rfloor, x_r, y_l, y_m, y_r \\right)$. We cut off at at least half of $B$. But $\\frac{S_B}{2} \\geq \\frac{S_B}{4} + \\frac{S_B}{4} \\geq \\frac{S_B}{4} + \\frac{S_A + S_C}{4} = \\frac{S_A + S_B + S_C}{4}$. We also have cut off at least a quarter within just one request. Case (3) is similar to case (2). Thus the maximal number of requests will be no more than $1 + 2 * \\log_{4/3} \\left( \\left( 10^{18} \\right)^2 \\right) \\approx 577$. Second solution: Let's keep the set of possible answers in form of a ladder $A$. Then lets find minimal $X$ such that $S \\left( A \\cap \\{x \\leq X\\} \\right) \\geq \\frac{S(A)}{3}$. And lets find minimal $Y$ such that $S \\left( A \\cap \\{y \\leq Y\\} \\right) \\geq \\frac{S(A)}{3}$. Then Thus the maximal number of requests will be no more than $1 + \\log_{3/2} \\left( \\left( 10^{18} \\right)^2 \\right) \\approx 205$.",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1007",
    "index": "D",
    "title": "Ants",
    "statement": "There is a tree with $n$ vertices. There are also $m$ ants living on it. Each ant has its own color. The $i$-th ant has two favorite pairs of vertices: ($a_i, b_i$) and ($c_i, d_i$). You need to tell if it is possible to paint the edges of the tree in $m$ colors so that every ant will be able to walk between vertices from one of its favorite pairs using only edges of his color; if it is possible, you need to print which pair every ant should use.",
    "tutorial": "Slow solution. We need to choose one of two paths for each ant so that they will not contain a common edge. Let's make a 2-SAT, and for each ant, we will create two contrary vertices: one will denote that we take the first path, and another will denote that we take the second path. Then for every two paths which share an edge, we add a condition that they can't be taken together. Now we just need to check that the 2-SAT has a solution. The complexity is $O(n m^2)$. First solution. Let's build a binary tree with $m$ leaves for each edge. Each vertex of the tree will be associated with some vertex of the 2-SAT. The vertex of the tree which covers leaves from $l$ to $r$ will be associated with a vertex of the 2-SAT which says if the edge should be painted with a color from $l$ to $r$. To build a vertex which is associated with a leaf we just need to add for every path of the ant which covers the current edge a condition which tells that if we take this path, then this vertex is true. And for every non-leaf vertex of the tree we need to add three conditions. First and second: if any of the vertices associated with the two sons is true, then the vertex associated with the current vertex is also true ($l\\rightarrow v$, $r\\rightarrow v$). And third: both vertices associated with the two sons can't be true ($l\\rightarrow !r$). The trees will be persistent, which means that if the vertex we want already exists, we will reuse it. Now we will build such trees recursively. First for the children, and then for the current edge. To build a tree for a new edge we first take an empty tree, then for each child, we recursively merge its tree with the current. If during the merge one of the vertices is empty, we return the second vertex. Then we add the paths which end in the current vertex. You have to be careful not to add the edges which will not be present in the final tree. For example, you can first build a tree, and then go through the new vertices one more time and add the edges. Then as in the previous solution, we check if there is a solution of this 2-SAT. It can be shown that for a vertex of the binary tree which covers $k$ leaves there will be created no more than $8k$ instances of this vertex, because there are at most $4k$ ends of the paths connected with these leaves and at most $8k - 1$ vertices which are the LCA of some set of these vertices. Now if we summarize it over all the vertices of the binary tree, we get approximately $8 m \\log(m)$. So the total complexity is $O(m \\log(m))$ Second solution. Let $L = 64$ be the number of bits in a machine word. Let's calculate a matrix $2m \\times 2m$ of ones and zeros, where cell $(i, j)$ is filled with $1$ iff the paths $i$ and $j$ have a common edge. We will store this matrix as an array of bitsets. Let's run a DFS which for every edge will return a set of paths that cover it. We will store such sets in a map from number of block to a bitmask of length $L$. We recursively calculate the sets for the children. Also for every path which starts in the vertex, we make a set containing only this path. Then if some sets share the same path, we remove it from both. Then we merge them by always adding the smaller map to the larger. While doing so we iterate over the elements of the smaller map and over the blocks of the larger map and add a block of edges to the matrix. For now, it is enough to add each edge to the matrix only in one direction. It can be shown that it works in $O \\left( m \\log^2(m) + m^2 \\cdot \\frac{\\log(L)}{L} \\right)$. Now we want to transpose the matrix and add it to itself to make it complete. To do it we divide it into blocks $L \\times L$, and transpose them one by one, then swap the blocks. Here is how we transpose a block. Assume $L = 2^K$. We will make $K$ iterations. On the $i-th$ iteration we will divide the block into subblocks $2^i \\times 2^i$ and in each block, we will swap the top right quarter and the bottom left quarter. Each iteration can be performed in $O(L)$. We can prove by induction that after $i$ iterations each subblock $2^i \\times 2^i$ will be transposed. This step works in $O \\left( m^2 \\cdot \\frac{\\log(L)}{L} \\right)$. It is easy to get a bitset of straight edges and a bitset of reversed edges of the 2-SAT for every vertex using this matrix. Now if we store the visited vertices in a bitset, we can implement the 2-SAT algorithm in $O \\left( \\frac{m^2}{L} \\right)$. The total complexity is $O \\left( m \\log^2(m) + m^2 \\cdot \\frac{\\log(L)}{L} \\right)$.",
    "tags": [
      "2-sat",
      "data structures",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1007",
    "index": "E",
    "title": "Mini Metro",
    "statement": "In a simplified version of a \"Mini Metro\" game, there is only one subway line, and all the trains go in the same direction. There are $n$ stations on the line, $a_i$ people are waiting for the train at the $i$-th station at the beginning of the game. The game starts at the beginning of the $0$-th hour. At the end of each hour (couple minutes before the end of the hour), $b_i$ people instantly arrive to the $i$-th station. If at some moment, the number of people at the $i$-th station is larger than $c_i$, you lose.\n\nA player has several trains which he can appoint to some hours. The capacity of each train is $k$ passengers. In the middle of the appointed hour, the train goes from the $1$-st to the $n$-th station, taking as many people at each station as it can accommodate. A train can not take people from the $i$-th station if there are people at the $i-1$-th station.\n\nIf multiple trains are appointed to the same hour, their capacities are being added up and they are moving together.\n\nThe player wants to stay in the game for $t$ hours. Determine the minimum number of trains he will need for it.",
    "tutorial": "Let's enumerate the hours and the stations starting from zero. Let's add a station to the end with an infinite number of people and infinite capacity. It is obvious that it will not affect the answer. Also, every train now will be filled completely. Let's calculate $sa[p]$, $sb[p]$ and $sc[p]$: the sum of $a[i]$, $b[i]$ and $c[i]$ over the first $p$ stations respectively. Let $d[p][s][z]$ ($0 \\leq p \\leq n + 1$, $0 \\leq s \\leq t$, $0 \\leq z \\leq 1$) be the minimal number of trains (or $\\infty$, if impossible) needed to hold on for $s$ hours, if there were only the first $p$ stations, so that every train we used would be filled completely. Herewith the initial number of people on the $i$-th station equals $z \\cdot a[i]$. Let $g[p][s][z]$ ($0 \\leq p \\leq n + 1$, $0 \\leq s \\leq t$, $0 \\leq z \\leq 1$)be the minimal number of trains (or $\\infty$, if impossible) needed to hold on for $s$ with a half hours (so that we can send some trains at the end), if there were only the first $p$ stations, so that every train we used would be filled completely and every station except for the last would contain in the end $0$ people. Herewith the initial number of people on the $i$-th station equals $z \\cdot a[i]$. Then the answer for the problem is $d[n + 1][t][1]$. Lets calculate $d$ and $g$ using dynamic programming. In order to calculate $d[p][s][z]$ and $g[p][s][z]$ lets consider the last hour from $0$ to $s - 1$ in which some train will take a person from the last station. Notice that in case of $g[p][s][z]$ we do not consider the $s$-th hour though there could be such trains during this hour. First case: There were no such trains. In this case we just need to check that the last station won't overflow and that $d[p - 1][s][z] \\neq \\infty$. Then we can make transitions: (*) In case of $g[p][s][z]$ it is obvious that such number will be needed in order to set to zero all the stations except for the last one, and this number can be achieved since we can hold on for $s$ hours without taking a person from the last station. Second case: denote the number of this hour by $r$. Then the plan is as follows: First, we need to hold on for $r$ with a half hours and do so that on every station except for the last there will be $0$ people. Then we possibly send some more trains during the $r$-th hour. Then we need to hold on for $s - r$ without the first half hours without sending a train which will take a person from the last station. Then in case of $g[p][s][z]$ we send some more trains during the $s$-th hour. On the phase (2) we cat calculate the initial number of people on the last station: $m = z \\cdot sa[p] + r \\cdot sb[p] - k \\cdot g[p][r][z]$, and then calculate the minimal number of trains we need to send so that the last station doesn't overflow by the end of the$(s-1)$-th hour: $x = \\left\\lceil \\frac{\\max(m + (s - r) \\cdot b[p - 1] - c[p - 1], 0)}{k} \\right\\rceil$. If $x \\cdot k > m$, then the transition is impossible, else it is benificial to send $x$ trains. During the phase (3) it is beneficial to send as few trains as possible, be'cause in case of $d[p][s][z]$ it is the last phase, and in case of $g[p][s][z]$ we can always send additional trains during the phase (4) and nothing will change. Notice in the beginning of phase (3) the first $p - 1$ are empty and also we can assume we are starting from the beginning of an hour and we need to hold on for $s - r$ hours. Thus we need to send $d[p - 1][s - r][0]$ trains. If $d[p - 1][s - r][0] = \\infty$, then the transition is impossible. Finally, on the phase (4) we need to send as few trains as possible so that all the stations except for the last one would contain $0$ people. As in (*) we can see that on phases (3) and (4) we need to send in total at least val = $\\left\\lceil \\frac{(s - r) \\cdot sb[p - 1]}{k} \\right\\rceil$ trains, and we can achieve this number. We can make transitions: Solution time is $O(n t^2)$.",
    "tags": [
      "dp"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1008",
    "index": "A",
    "title": "Romaji",
    "statement": "Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are \"a\", \"o\", \"u\", \"i\", and \"e\". Other letters are consonant.\n\nIn Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant \"n\"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words \"harakiri\", \"yupie\", \"man\", and \"nbo\" are Berlanese while the words \"horse\", \"king\", \"my\", and \"nz\" are not.\n\nHelp Vitya find out if a word $s$ is Berlanese.",
    "tutorial": "You need to check if after every letter except one of for these \"aouien\", there goes one of these \"aouie\". Do not forget to check the last letter.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1008",
    "index": "B",
    "title": "Turn the Rectangles",
    "statement": "There are $n$ rectangles in a row. You can either turn each rectangle by $90$ degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. \\textbf{You can not change the order of the rectangles.}\n\nFind out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such).",
    "tutorial": "You need to iterate over the rectangles from left to right and turn each rectangle in such a way that its height is as big as possible but not greater than the height of the previous rectangle (if it's not the first one). If on some iteration there is no such way to place the rectangle, the answer is \"NO\".",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1009",
    "index": "A",
    "title": "Game Shopping",
    "statement": "Maxim wants to buy some games at the local game shop. There are $n$ games in the shop, the $i$-th game costs $c_i$.\n\nMaxim has a wallet which can be represented as an array of integers. His wallet contains $m$ bills, the $j$-th bill has value $a_j$.\n\nGames in the shop are ordered from left to right, Maxim tries to buy every game in that order.\n\nWhen Maxim stands at the position $i$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $i$-th game using this bill. After Maxim tried to buy the $n$-th game, he leaves the shop.\n\nMaxim buys the $i$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $i$-th game. If he successfully buys the $i$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet \\textbf{(this bill still remains the first one)} and proceeds to the next game.\n\nFor example, for array $c = [2, 4, 5, 2, 4]$ and array $a = [5, 3, 4, 6]$ the following process takes place: Maxim buys the first game using the first bill (its value is $5$), the bill disappears, after that the second bill (with value $3$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $c_2 > a_2$, the same with the third game, then he buys the fourth game using the bill of value $a_2$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $a_3$.\n\nYour task is to get the number of games Maxim will buy.",
    "tutorial": "Let's keep the variable $pos$ which will represent the number of games Maxim buy. Initially $pos = 0$. Assume that arrays $a$ and $c$ are 0-indexed. Then let's iterate over all $i = 0 \\dots n - 1$ and if $pos < m$ and $a[pos] \\ge c[i]$ make $pos := pos + 1$. So $pos$ will be the answer after this cycle.",
    "code": "n, m = map(int, input().split())\na = list(map(int, input().split()))\nb = list(map(int, input().split()))\npos = 0\nfor i in a:\n\tpos += (pos < len(b) and b[pos] >= i)\nprint(pos)",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1009",
    "index": "B",
    "title": "Minimum Ternary String",
    "statement": "You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').\n\nYou can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace \"01\" with \"10\" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace \"12\" with \"21\" or vice versa).\n\nFor example, for string \"010210\" we can perform the following moves:\n\n- \"{\\underline{01}0210}\" $\\rightarrow$ \"{\\underline{10}0210}\";\n- \"{0\\underline{10}210}\" $\\rightarrow$ \"{0\\underline{01}210}\";\n- \"{010\\underline{21}0}\" $\\rightarrow$ \"{010\\underline{12}0}\";\n- \"{0102\\underline{10}}\" $\\rightarrow$ \"{0102\\underline{01}}\".\n\nNote than you cannot swap \"{\\underline{02}}\" $\\rightarrow$ \"{\\underline{20}}\" and vice versa. You cannot perform any other operations with the given string excluding described above.\n\nYou task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).\n\nString $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \\le i \\le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.",
    "tutorial": "Let's notice that described swaps allows us to place any '1' character to any position of the string $s$ (relative order of '0' and '2' obviously cannot be changed). Let's remove all '1' characters from the string $s$ (and keep their count in some variable). Now more profitable move is to place all the '{1}' characters right before the first '2' character of $s$ (and if there is no '2' character in $s$, then place they after the end of the string).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tstring s;\n\tcin >> s;\n\t\n\tstring ans;\n\t\n\tint cnt = 0;\n\tfor (auto c : s) {\n\t\tif (c == '1') ++cnt;\n\t\telse ans += c;\n\t}\n\t\n\tint n = ans.size();\n\tint pos = -1;\n\twhile (pos + 1 < n && ans[pos + 1] == '0') ++pos;\n\tans.insert(pos + 1, string(cnt, '1'));\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1009",
    "index": "C",
    "title": "Annoying Present",
    "statement": "Alice got an array of length $n$ as a birthday present once again! This is the third year in a row!\n\nAnd what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.\n\nBob has chosen $m$ changes of the following form. For some integer numbers $x$ and $d$, he chooses an arbitrary position $i$ ($1 \\le i \\le n$) and for every $j \\in [1, n]$ adds $x + d \\cdot dist(i, j)$ to the value of the $j$-th cell. $dist(i, j)$ is the distance between positions $i$ and $j$ (i.e. $dist(i, j) = |i - j|$, where $|x|$ is an absolute value of $x$).\n\nFor example, if Alice currently has an array $[2, 1, 2, 2]$ and Bob chooses position $3$ for $x = -1$ and $d = 2$ then the array will become $[2 - 1 + 2 \\cdot 2,~1 - 1 + 2 \\cdot 1,~2 - 1 + 2 \\cdot 0,~2 - 1 + 2 \\cdot 1]$ = $[5, 2, 1, 3]$. Note that Bob can't choose position $i$ outside of the array (that is, smaller than $1$ or greater than $n$).\n\nAlice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.\n\nWhat is the maximum arithmetic mean value Bob can achieve?",
    "tutorial": "Judging by constraints, you can guess that the greedy approach is the right one. Firstly, let's transition from maximizing the arithmetic mean to the sum, it's the same thing generally. Secondly, notice that each $x$ is being added to each element regardless of the chosen position. Finally, take a look at a function $f(d, i)$ - total sum obtained by applying change with $d$ to position $i$ and notice that it is non-strictly convex. Its maximum or minimum values can always be found in one of these positions: $\\frac{n}{2}$ (method of rounding doesn't matter), $1$ and $n$. Thus, the solution will look like this: for positive $d$ you apply the change to position $1$ and for non-positive $d$ - to position $\\lfloor \\frac{n}{2} \\rfloor$. The impact of the change can be calculated with the formula of the sum of arithmetic progression. Also, you should either do all of your calculations in long double (10-byte type) or maintain sum in long long (you can estimate it with $m \\cdot n^2 \\cdot MAXN \\le 10^{18}$, so it fits) and divide it by $n$ in the end (then double will work). Overall complexity: $O(m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\ntypedef long long li;\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\t\n\tli neg = ((n - 1) / 2) * li((n - 1) / 2 + 1);\n\tif (n % 2 == 0) neg += n / 2;\n\tli pos = n * li(n - 1) / 2;\n\t\n\tli ans = 0;\n\tforn(i, m){\n\t\tint x, d;\n\t\tscanf(\"%d%d\", &x, &d);\n\t\tans += x * li(n);\n\t\tif (d < 0)\n\t\t\tans += neg * d;\n\t\telse\n\t\t\tans += pos * d;\n\t}\n\t\n\tprintf(\"%.15f\\n\", double(ans) / n);\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1009",
    "index": "D",
    "title": "Relatively Prime Graph",
    "statement": "Let's call an undirected graph $G = (V, E)$ relatively prime if and only if for each edge $(v, u) \\in E$  $GCD(v, u) = 1$ (the greatest common divisor of $v$ and $u$ is $1$). If there is no edge between some pair of vertices $v$ and $u$ then the value of $GCD(v, u)$ doesn't matter. The vertices are numbered from $1$ to $|V|$.\n\nConstruct a relatively prime graph with $n$ vertices and $m$ edges such that it is connected and it contains neither self-loops nor multiple edges.\n\nIf there exists no valid graph with the given number of vertices and edges then output \"Impossible\".\n\nIf there are multiple answers then print any of them.",
    "tutorial": "Even though $n$ is up to $10^5$, straightforward $O(n^2 \\log n)$ solution will work. You iterate for $i$ from $1$ to $n$ in the outer loop, from $i + 1$ to $n$ in the inner loop and check $GCD$ each time. When $m$ edges are found, you break from both loops. Here is why this work fast enough. The total number of pairs $(x, y)$ with $1 \\le x, y \\le n, gcd(x, y) = 1$ is $\\varphi(1) + \\varphi(2) + \\dots + \\varphi(n)$, where $\\varphi$ is Euler's totient function. We also want to substract a single pair $(1, 1)$. And this sum grows so fast that after about $600$ iteratons $\\varphi(1) + \\varphi(2) + \\dots + \\varphi(600)$ will be greater than $100000$ for any $n$. The only thing left is to check that $m$ is big enough to build a connected graph ($m \\ge n - 1$) and small enough to fit all possible edges for given $n$ (the formula above). Overall complexity: $O(n^2 \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 100000;\n\npair<int, int> ans[N];\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\t\n\tif (m < n - 1) {\n\t\tputs(\"Impossible\");\n\t\treturn 0;\n\t}\n\t\n\tint cur = 0;\n\t\n\tforn(i, n) for (int j = i + 1; j < n; ++j){\n\t\tif (cur == m)\n\t\t\tbreak;\n\t\tif (__gcd(i + 1, j + 1) == 1)\n\t\t\tans[cur++] = make_pair(j, i);\n\t}\n\t\n\tif (cur != m){\n\t\tputs(\"Impossible\");\n\t\treturn 0;\n\t}\n\t\n\tputs(\"Possible\");\n\tforn(i, m)\n\t\tprintf(\"%d %d\\n\", ans[i].first + 1, ans[i].second + 1);\n\t\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1009",
    "index": "E",
    "title": "Intercity Travelling",
    "statement": "Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.\n\nThe path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is $n$ km. Let's say that Moscow is situated at the point with coordinate $0$ km, and Saratov — at coordinate $n$ km.\n\nDriving for a long time may be really difficult. Formally, if Leha has already covered $i$ kilometers since he stopped to have a rest, he considers the difficulty of covering $(i + 1)$-th kilometer as $a_{i + 1}$. It is guaranteed that for every $i \\in [1, n - 1]$ $a_i \\le a_{i + 1}$. The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey.\n\nFortunately, there may be some rest sites between Moscow and Saratov. Every integer point from $1$ to $n - 1$ may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty $a_1$, the kilometer after it — difficulty $a_2$, and so on.\n\nFor example, if $n = 5$ and there is a rest site in coordinate $2$, the difficulty of journey will be $2a_1 + 2a_2 + a_3$: the first kilometer will have difficulty $a_1$, the second one — $a_2$, then Leha will have a rest, and the third kilometer will have difficulty $a_1$, the fourth — $a_2$, and the last one — $a_3$. Another example: if $n = 7$ and there are rest sites in coordinates $1$ and $5$, the difficulty of Leha's journey is $3a_1 + 2a_2 + a_3 + a_4$.\n\nLeha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are $2^{n - 1}$ different distributions of rest sites (two distributions are different if there exists some point $x$ such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate $p$ — the expected value of difficulty of his journey.\n\nObviously, $p \\cdot 2^{n - 1}$ is an integer number. You have to calculate it modulo $998244353$.",
    "tutorial": "Let's consider each kilometer of the journey separatedly and calculate the expected value of its difficulty (and then use linearity of expectation to obtain the answer). The difficulty of each kilometer depends on the rest site right before it (or, if there were no rest sites, on the distance from Moscow to this kilometer). So when considering the difficulty of $i$-th kilometer (one-indexed), we may obtain a formula: $diff_i = \\frac{a_1}{2} + \\frac{a_2}{2^2} + \\dots + \\frac{a_{i - 1}}{2^{i - 1}} + \\frac{a_i}{2^{i - 1}}$. The denominator of the last summand is $2^{i - 1}$ because it represents the situation where the last rest was in Moscow, and its probability is exactly $\\frac{1}{2^{i - 1}}$. We can actually rewrite this as follows: $diff_1 = a_1$, $diff_{i + 1} = diff_i - \\frac{a_i}{2^i} + \\frac{a_{i + 1}}{2^i}$, thus calculating all that we need in linear time.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD)\n        x -= MOD;\n    while(x < 0)\n        x += MOD;\n    return x;\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n    vector<int> a(n);\n    for(int i = 0; i < n; i++)\n        scanf(\"%d\", &a[i]);\n        \n    int ans = 0;\n    vector<int> pw2(1, 1);\n    while(pw2.size() < n)\n        pw2.push_back(mul(pw2.back(), 2));\n    int cur = mul(pw2[n - 1], a[0]);\n    for(int i = 0; i < n; i++)\n    {\n        ans = add(ans, cur);\n        if(i < n - 1)\n        {\n            cur = add(cur, -mul(pw2[n - 2 - i], a[i]));\n            cur = add(cur, mul(pw2[n - 2 - i], a[i + 1]));\n        }\n    }\n    printf(\"%d\\n\", ans);\n}",
    "tags": [
      "combinatorics",
      "math",
      "probabilities"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1009",
    "index": "F",
    "title": "Dominant Indices",
    "statement": "You are given a rooted undirected tree consisting of $n$ vertices. Vertex $1$ is the root.\n\nLet's denote a depth array of vertex $x$ as an infinite sequence $[d_{x, 0}, d_{x, 1}, d_{x, 2}, \\dots]$, where $d_{x, i}$ is the number of vertices $y$ such that both conditions hold:\n\n- $x$ is an ancestor of $y$;\n- the simple path from $x$ to $y$ traverses exactly $i$ edges.\n\nThe dominant index of a depth array of vertex $x$ (or, shortly, the dominant index of vertex $x$) is an index $j$ such that:\n\n- for every $k < j$, $d_{x, k} < d_{x, j}$;\n- for every $k > j$, $d_{x, k} \\le d_{x, j}$.\n\nFor every vertex in the tree calculate its dominant index.",
    "tutorial": "In this problem we can use small-to-large merging trick (also known as DSU on tree): when building a depth array for a vertex, we firstly build depth arrays recursively for its children, then pull them upwards and merge them with small-to-large technique. In different blogs on this technique it was mentioned that this will require $O(n \\log n)$ operations with structures we use to maintain depth arrays overall. However, in this problem we may prove a better estimate: it will require $O(n)$ operations. That's because the size of depth array (if considering only non-zero elements) for a vertex is equal to the height of its subtree, not to the number of vertices in it. To prove that the number of operations is $O(n)$, one can use the intuitive fact that when we merge two depth arrays, all elements of the smaller array are \"destroyed\" in the process, so if the size of smaller array is $k$, then we require $O(k)$ operations to \"destroy\" $k$ elements. The main problem is that we sometimes need to \"pull\" our depth arrays upwards, thus inserting a $1$ to the beginning of the array. Standard arrays don't support this operation, so we need to either use something like std::map (and the complexity will be $O(n \\log n)$), or keep the depth arrays in reversed order and handle them using std::vector (and then complexity will be $O(n)$).",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n\n#include <vector>\n#include <cstdio>\n#include <iostream>\n#include <algorithm>\n\n// RJ? No, thanks\n\nusing namespace std;\n\nconst int N = 1000043;\n\nstruct state\n{\n\tvector<int>* a;\n\tint cur_max;\n\tint sz()\n\t{\n\t\treturn a->size();\n\t}\n\tvoid add(int i, int val)\n\t{\n\t\t(*a)[i] += val;\n\t\tif(make_pair((*a)[i], i) > make_pair((*a)[cur_max], cur_max))\n\t\t\tcur_max = i;\n\t}\n};\n\nstate pull(state z)\n{\n\tif(z.sz() == 0)\n\t{\n\t\tstate c;\n\t\tc.a = new vector<int>(1, 1);\n\t\tc.cur_max = 0;\n\t\treturn c;\n\t}\n\telse\n\t{\n\t\tstate c;\n\t\tc.a = z.a;\n\t\tc.cur_max = z.cur_max;\n\t\tc.a->push_back(0);\n\t\tc.add(c.sz() - 1, 1);\n\t\treturn c;\n\t}\n}\n\nstate merge(state a, state b)\n{\n\tif(a.sz() < b.sz())\n\t\tswap(a, b);\n\tstate c;\n\tc.a = a.a;\n\tc.cur_max = a.cur_max;\n\tint as = c.sz();\n\tint bs = b.sz();\n\tfor(int i = 0; i < bs; i++)\n\t\ta.add(as - i - 1, (*(b.a))[bs - i - 1]);\n\treturn a;\n}\n\nstate s[N];\nint ans[N];\nvector<int> g[N];\n\nvoid dfs(int x, int p = -1)\n{\n\ts[x].a = new vector<int>(0);\n\ts[x].cur_max = 0;\n\tfor(auto y : g[x])\n\t\tif(y != p)\n\t\t{\n\t\t\tdfs(y, x);\n\t\t\ts[x] = merge(s[x], s[y]);\n\t\t}\n\ts[x] = pull(s[x]);\n\tans[x] = s[x].sz() - s[x].cur_max - 1;\n}\n\nint main()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n - 1; i++)\n\t{\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t--x;\n\t\t--y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\tdfs(0);\n\tfor(int i = 0; i < n; i++)\n\t\tprintf(\"%d\\n\", ans[i]);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1009",
    "index": "G",
    "title": "Allowed Letters",
    "statement": "Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup!\n\nActually, Polycarp has already came up with the name but some improvement to it will never hurt. So now he wants to swap letters at some positions in it to obtain the better name. It isn't necessary for letters to be adjacent.\n\nIn addition, each of the investors has chosen some index in the name and selected a set of letters that can go there. Indices chosen by different investors are pairwise distinct. If some indices aren't chosen by any investor then any letter can go there.\n\nFinally, Polycarp is sure that the smallest lexicographically name is the best. (Like why do you think Google decided to become Alphabet?)\n\nMore formally, you are given a string consisting of lowercase Latin letters from \"a\" to \"f\". You can swap letters at any positions arbitrary number of times (zero swaps is also possible).\n\nWhat is the smallest lexicographically name you can obtain such that the letter at every position is among the allowed letters?\n\nIf Polycarp can't produce any valid name then print \"Impossible\".",
    "tutorial": "The idea of solution is the following: we build the answer letter-by-letter; when choosing a character for some position, we try all possible characters and check that we can build the suffix after placing this character. But we need to somehow do this checking fast. As in many previous Educational Rounds, in this round some participants' solutions were much easier to write and understand than our own model solution. Authors' solution (uses network flows): Let's build a flow network, where we have $6$ vertices representing the characters of the string and $2^6$ vertices representing the masks of characters. Add directed edges from the source to every node representing some character with capacity equal to the number of such characters in the original string; also add directed edges from every node representing some character to all vertices representing masks where this character is contained (with infinite capacity); and finally, add a directed edge from every \"mask\"-node to the sink with capacity equal to the number of positions where this mask of characters is allowed. If we find maximum flow in this network, we can check that the answer exists, and if it exists, build some answer. Now let's try to build optimal answer by somehow rebuilding the flow in the network. Suppose we are trying to place a character $x$ to position containing mask $m$. To check whether we can do it, we have to try rebuilding the flow in such a way that the edge from vertex corresponding to $x$ to vertex corresponding to $m$ has non-zero flow. If it is already non-zero, then we are done; otherwise we may cancel a unit of flow going through an edge from source to $x$-vertex, then cancel a unit of flow going through an edge from $m$-vertex to sink, decrease the capacity of these two edges by $1$ and check that there exists an augmenting path. If it exists, then returning the capacities back and adding one unit of flow through the path $source \\rightarrow x \\rightarrow m \\rightarrow sink$ actually builds some answer where some character $x$ is placed on some position with mask $m$, so we may place it there; otherwise it's impossible. When we finally decided to place $x$ on position $m$, we have to decrease the flow through $source \\rightarrow x \\rightarrow m \\rightarrow sink$ and the capacities of edges $source \\rightarrow x$ and $m \\rightarrow sink$. All this algorithm runs in $O(n \\cdot 2^A \\cdot A^2)$, where $A$ is the size of the alphabet. Participants' solution (uses Hall's theorem): Hall's theorem allows us to check that we may build the suffix of the answer much easier. Each time we try to place some character, we need to iterate on all possible subsets of characters we still need to place and check that the number of positions that are suitable for at least one character in a subset is not less than the size of subset (just like in regular Hall's theorem). The key fact here is that if we have, for example, $3$ characters a yet to place, then we don't need to check any subset containing exactly $1$ or $2$ characters a, since the number of \"suitable\" positions for this subset won't become larger if we add all remaining characters a to a subset. So the subsets we have to consider are limited by the masks of possible characters, and there will be only $64$ of them.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) ((int)(a).size())\n\nstruct edge\n{\n    int y;\n    int c;\n    int f;\n    edge() {};\n    edge(int y, int c, int f) : y(y), c(c), f(f) {};\n};\n\nconst int N = 100;\n\nvector<edge> e;\nvector<int> g[N];\nint edge_num[N][N];\nint char_vertex[6];\nint mask_vertex[N];\nint used[N];\nint cc = 0;\nint s, t;\n\nvoid add_edge(int x, int y, int c)\n{\n    edge_num[x][y] = sz(e);\n    g[x].push_back(sz(e));\n    e.push_back(edge(y, c, 0));\n    edge_num[y][x] = sz(e);\n    g[y].push_back(sz(e));\n    e.push_back(edge(x, 0, 0));\n}\n\nint rem(int num)\n{\n    return e[num].c - e[num].f;\n}\n\nint dfs(int x, int mx)\n{\n    if(x == t) return mx;\n    if(used[x] == cc) return 0;\n    used[x] = cc;\n    for(auto num : g[x])\n    {\n        if(rem(num))\n        {\n            int pushed = dfs(e[num].y, min(mx, rem(num)));\n            if(pushed)\n            {\n                e[num].f += pushed;\n                e[num ^ 1].f -= pushed;\n                return pushed;\n            }\n        }\n    }\n    return 0;\n}\n\nbool check(int ch, int mask)\n{\n    if((mask & (1 << ch)) == 0)\n        return false;\n    int cv = char_vertex[ch];\n    int mv = mask_vertex[mask];\n    int e1 = edge_num[s][cv];\n    int e2 = edge_num[mv][t];\n    if(e[e1].f == 0 || e[e2].f == 0)\n        return false;\n    e[e1].f--;\n    e[e1 ^ 1].f++;\n    vector<int> affected_edges;\n    affected_edges.push_back(e1);\n    for(auto x : g[cv])\n    {\n        if((x & 1) == 0 && e[x].f > 0)\n        {\n            affected_edges.push_back(x);\n            e[x].f--;\n            e[x ^ 1].f++;\n            int y = e[x].y;\n            for(auto x2 : g[y])\n            {\n                if((x2 & 1) == 0)\n                {\n                    affected_edges.push_back(x2);\n                    e[x2].f--;\n                    e[x2 ^ 1].f++;\n                    break;\n                }\n            }\n            break;\n        }\n    }\n    if(e[e2].f < e[e2].c)\n    {\n        e[e1].c--;\n        e[e2].c--;\n        return true;\n    }\n    affected_edges.push_back(e2);\n    e[e2].f--;\n    e[e2 ^ 1].f++;\n    for(auto x : g[mv])\n    {\n        if((x & 1) == 1 && e[x].f < 0)\n        {\n            affected_edges.push_back(x ^ 1);\n            e[x].f++;\n            e[x ^ 1].f--;\n            int y = e[x].y;\n            for(auto x2 : g[y])\n            {\n                if((x2 & 1) == 1)\n                {\n                    affected_edges.push_back(x2 ^ 1);\n                    e[x2].f++;\n                    e[x2 ^ 1].f--;\n                    break;\n                }\n            }\n            break;\n        }\n    }\n    cc++;\n    e[e1].c--;\n    e[e2].c--;\n    if(dfs(s, 1))\n        return true;\n    else\n    {\n        e[e1].c++;\n        e[e2].c++;\n        for(auto x : affected_edges)\n        {\n            e[x].f++;\n            e[x ^ 1].f--;\n        }\n        return false;\n    }\n}\n\nchar buf[100043];\nstring allowed[100043];\nint allowed_mask[100043];\n\nint main()\n{\n    s = 70;\n    t = 71;\n    scanf(\"%s\", buf);\n    string z = buf;\n    int n = sz(z);\n    int m;\n    scanf(\"%d\", &m);\n    for(int i = 0; i < n; i++)\n    {\n        allowed[i] = \"abcdef\";\n        allowed_mask[i] = 63;\n    }\n    for(int i = 0; i < m; i++)\n    {\n        int idx;\n        scanf(\"%d\", &idx);\n        --idx;\n        scanf(\"%s\", buf);\n        allowed[idx] = buf;\n        allowed_mask[idx] = 0;\n        for(auto x : allowed[idx])\n        {\n            allowed_mask[idx] |= (1 << (x - 'a'));\n        }\n    }\n    for(int i = 0; i < 6; i++)\n        char_vertex[i] = i;\n    for(int i = 0; i < (1 << 6); i++)\n        mask_vertex[i] = i + 6;\n    for(int i = 0; i < (1 << 6); i++)\n        for(int j = 0; j < 6; j++)\n            if(i & (1 << j))\n                add_edge(char_vertex[j], mask_vertex[i], 100000);\n    for(int i = 0; i < 6; i++)\n    {\n        int cnt = 0;\n        for(int j = 0; j < n; j++)\n            if(z[j] == 'a' + i)\n                cnt++;\n        add_edge(s, char_vertex[i], cnt);\n    }\n    for(int i = 0; i < (1 << 6); i++)\n    {\n        int cnt = 0;\n        for(int j = 0; j < n; j++)\n            if(allowed_mask[j] == i)\n                cnt++;\n        add_edge(mask_vertex[i], t, cnt);\n    }\n    int flow = 0;\n    while(true)\n    {\n        cc++;\n        int p = dfs(s, 100000);\n        if(p)\n            flow += p;\n        else\n            break;\n    }\n    if(flow != n)\n    {\n        puts(\"Impossible\");\n        return 0;\n    }\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < 6; j++)\n        {\n            if(check(j, allowed_mask[i]))\n            {\n                printf(\"%c\", j + 'a');\n                break;\n            }\n        }\n    puts(\"\");\n}",
    "tags": [
      "bitmasks",
      "flows",
      "graph matchings",
      "graphs",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1010",
    "index": "A",
    "title": "Fly",
    "statement": "Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $n - 2$ intermediate planets. Formally: we number all the planets from $1$ to $n$. $1$ is Earth, $n$ is Mars. Natasha will make exactly $n$ flights: $1 \\to 2 \\to \\ldots n \\to 1$.\n\nFlight from $x$ to $y$ consists of two phases: take-off from planet $x$ and landing to planet $y$. This way, the overall itinerary of the trip will be: the $1$-st planet $\\to$ take-off from the $1$-st planet $\\to$ landing to the $2$-nd planet $\\to$ $2$-nd planet $\\to$ take-off from the $2$-nd planet $\\to$ $\\ldots$ $\\to$ landing to the $n$-th planet $\\to$ the $n$-th planet $\\to$ take-off from the $n$-th planet $\\to$ landing to the $1$-st planet $\\to$ the $1$-st planet.\n\nThe mass of the rocket together with all the useful cargo (but without fuel) is $m$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $1$ ton of fuel can lift off $a_i$ tons of rocket from the $i$-th planet or to land $b_i$ tons of rocket onto the $i$-th planet.\n\nFor example, if the weight of rocket is $9$ tons, weight of fuel is $3$ tons and take-off coefficient is $8$ ($a_i = 8$), then $1.5$ tons of fuel will be burnt (since $1.5 \\cdot 8 = 9 + 3$). The new weight of fuel after take-off will be $1.5$ tons.\n\nPlease note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.\n\nHelp Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.",
    "tutorial": "First, we learn how to determine if a rocket can fly the entire route. Consider an element from an array $a[]$ or $b[]$. We denote it by $t$. If $t=1$ (that is, one ton of fuel can carry only one ton (cargo + fuel)), then fuel can only take it to ourselves, and we need to take a rocket and a useful cargo (the mass of which is positive). That is, if $t=1$ at least for one $t$, it is necessary to deduce $-1$, otherwise, do the following calculations. It is clear that arrays $a[]$ and $b[]$ will be processed by the computer of the rocket in that order: $a_1,b_2,a_2,b_3,a_3,b_4,a_4,\\ldots,b_{n-1},a_{n-1},b_n,a_n,b_1$. We will process this sequence from the end. Let at the current iteration the mass of the payload (including fuel that will not be used at this iteration) is $s$ tons, the current element from the array $a[]$ or $b[]$ is $t$, the mass of fuel that will be used at this iteration (it must be found), is $x$. We assign before the iterations $s=m$. We form the equation: total mass = mass that all fuel can transport $s+x=tx$ $x=\\dfrac s{t-1}$ By this formula, you can find fuel in this iteration. For the next iteration to the payload weight, you need to add mass of fuel (since this fuel needs to be brought to this iteration), that is, perform the assignment $s=s+x$. In the end, it is necessary to deduce $s-m$. Complexity: $O(n)$. Bonus. In fact, it does not matter in which order to process arrays $a[]$ and $b[]$ (from the beginning, from the end or in general mixed): the answer from this will not change. Try to prove it by yourself.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int n,m;\n    cin>>n>>m;\n    int a[n];\n    for(int i=0;i<n;i++)\n    {\n        cin>>a[i];\n        if(a[i]<=1)\n        {\n            printf(\"-1\\n\");\n            exit(0);\n        }\n    }\n    int b[n];\n    for(int i=0;i<n;i++)\n    {\n        cin>>b[i];\n        if(b[i]<=1)\n        {\n            printf(\"-1\\n\");\n            exit(0);\n        }\n    }\n    double s=m;\n    s+=s/(a[0]-1);\n    for(int i=n-1;i>=1;i--)\n    {\n        s+=s/(b[i]-1);\n        s+=s/(a[i]-1);\n    }\n    s+=s/(b[0]-1);\n    printf(\"%.10lf\\n\",s-m);\n}\n",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1010",
    "index": "B",
    "title": "Rocket",
    "statement": "\\textbf{This is an interactive problem.}\n\nNatasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.\n\nLet's define $x$ as the distance to Mars. Unfortunately, Natasha does not know $x$. But it is known that $1 \\le x \\le m$, where Natasha knows the number $m$. Besides, $x$ and $m$ are positive integers.\n\nNatasha can ask the rocket questions. Every question is an integer $y$ ($1 \\le y \\le m$). The correct answer to the question is $-1$, if $x<y$, $0$, if $x=y$, and $1$, if $x>y$. But the rocket is broken — it does not always answer correctly. Precisely: let the correct answer to the current question be equal to $t$, then, if the rocket answers this question correctly, then it will answer $t$, otherwise it will answer $-t$.\n\nIn addition, the rocket has a sequence $p$ of length $n$. Each element of the sequence is either $0$ or $1$. The rocket processes this sequence in the cyclic order, that is $1$-st element, $2$-nd, $3$-rd, $\\ldots$, $(n-1)$-th, $n$-th, $1$-st, $2$-nd, $3$-rd, $\\ldots$, $(n-1)$-th, $n$-th, $\\ldots$. If the current element is $1$, the rocket answers correctly, if $0$ — lies. Natasha doesn't know the sequence $p$, but she knows its length — $n$.\n\nYou can ask the rocket no more than $60$ questions.\n\nHelp Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.\n\nYour solution will not be accepted, if it does not receive an answer $0$ from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).",
    "tutorial": "First we learn the sequence $p[]$. For this print the query \"1\" $n$ times. If the answer is \"0\" (that is, the distance to Mars is equal to one), then immediately terminate the program. Otherwise, it is clear that the correct answer is \"1\" (that is, the distance to Mars is greater than one). If $i$-th answer of rocket is \"1\", then $p[i]=1$ (that is, the rocket answered the truth), otherwise $p[i]=0$ (untruth). On this, we will spend no more than $n$ queries, within the given constraints it is $30$. Now you can find the number $x$ using binary search. For each answer, you need to check: if the corresponding element of the sequence $p$ equals to $0$, then the answer sign must be changed. On this, we will spend no more than $\\lceil\\log_2 m\\rceil$ queries, within the given constraints it is $30$. The total number of queries does not exceed $n+\\lceil\\log_2 m\\rceil\\le 30+30=60$. Complexity: $O(n+\\log m)$ Bonus. Try to solve a similar problem but with a constraint $1 \\le m \\le 1073741853$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint query(int y)\n{\n    cout<<y<<\"\\n\";\n    fflush(stdout);\n    int t;\n    cin>>t;\n    if(t==0||t==-2)\n        exit(0);\n    return t;\n}\n\nint main()\n{\n    int m,n;\n    cin>>m>>n;\n    int p[n];\n    for(int i=0;i<n;i++)\n    {\n        int t=query(1);\n        p[i]=t==1;\n    }\n    int l=2,r=m;\n    for(int q=0;;q++)\n    {\n        int y=(l+r)/2;\n        int t=query(y);\n        if(!p[q%n])\n            t*=-1;\n        if(t==1)\n            l=y+1;\n        else\n            r=y-1;\n    }\n}",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1010",
    "index": "C",
    "title": "Border",
    "statement": "Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.\n\nThere are $n$ banknote denominations on Mars: the value of $i$-th banknote is $a_i$. Natasha has an infinite number of banknotes of each denomination.\n\nMartians have $k$ fingers on their hands, so they use a number system with base $k$. In addition, the Martians consider the digit $d$ (in the number system with base $k$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $k$ is $d$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.\n\nDetermine for which values $d$ Natasha can make the Martians happy.\n\nNatasha can use only her banknotes. Martians don't give her change.",
    "tutorial": "Note that the condition \"the last digit in the record of Natasha's tax amount in the number system with the base $k$ will be $d$\" is equivalent to the condition \"the remainder of dividing the tax on $k$ will be $d$\". Let $g=GCD(a_1,a_2,\\ldots,a_n)$. It is stated that the original problem is equivalent to the problem where $n=1$ and the only banknote is $g$. Evidence. We prove this with the help of the Bézout's identity. It follows that an equation of the form $a_1$$x_1+a_2$$x_2+\\dots+a_n$$x_n=c$, where at least one of the parameters $a_1,a_2,\\dots,a_n$ is not zero, has a solution in integers if and only if $c \\hspace{2pt} \\vdots \\hspace{2pt} GCD(a_1,a_2, \\dots ,a_n)$. Then in this task Natasha can pay $x_i$ banknotes of the $i$-th nominal value for each $i$, where $1\\le i\\le n$, and the amount of tax ($a_1$$x_1+a_2$$x_2+\\dots+a_n$$x_n$) can be any number $c$, multiple $g$. (Here some $x_i<0$, But Natasha can add for each par a sufficiently large number, multiple $k$, that $x_i$ became greater than zero, the balance from dividing the amount of tax on $k$ from this will not change.) Therefore, you can replace all pars with one par $g$ and the answer from this will not change. Now we can sort out all the numbers of the form $gx\\bmod k$, where $0\\le x<k$ (further the remainder of the sum, divided by $k$ will cycle repeatedly) and output them in ascending order. Complexity: $O(n+\\log m+k\\log k)$, where $m$ is the greatest $a_i$. Bonus. Try to improve the complexity to $O(n+k)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint gcd(int a,int b)\n{\n    if(a<b)\n        swap(a,b);\n    return (b==0)?a:gcd(b,a%b);\n}\n\nint main()\n{\n    int n,k;\n    scanf(\"%d%d\",&n,&k);\n    int g=0;\n    for(int i=0;i<n;i++)\n    {\n        int t;\n        scanf(\"%d\",&t);\n        g=gcd(g,t);\n    }\n    set<int> ans;\n    for(long long i=0,s=0;i<k;i++,s+=g)\n        ans.insert(s%k);\n    printf(\"%d\\n\",ans.size());\n    for(set<int>::iterator i=ans.begin();i!=ans.end();i++)\n        printf(\"%d \",*i);\n}",
    "tags": [
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1010",
    "index": "D",
    "title": "Mars rover",
    "statement": "Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex $1$, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output.\n\nThere are four types of logical elements: AND ($2$ inputs), OR ($2$ inputs), XOR ($2$ inputs), NOT ($1$ input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input.\n\nFor each input, determine what the output will be if Natasha changes this input.",
    "tutorial": "Let's count the bit at each vertex. This can be done using depth-first search on this tree. Now for each vertex, let's check: whether the bit on the output of the scheme will change if the bit in the current vertex is changed. If all the vertices on the path from this vertex to the output of the scheme. If at least one of them does not change, then the output of the scheme does not change, and vice versa: if the output of the scheme is changed, then each vertex on the path under consideration will change. Now the solution can be implemented as follows. For each vertex, let's make a note: whether the bit on the output of the scheme will be changed if the bit on the current vertex is changed. For output of the scheme, this note is $true$. Now let's do the depth-first search on this tree. If note at the current vertex is equal to $false$, then at the inputs to it we make the note equal $false$, otherwise, for each input to this vertex, we do the following. Let's see if the current vertex is changed if the current input is changed. If it is changed, then at this input we will make the note equal $true$, otherwise $false$. Complexity: $O(n)$.",
    "code": "#pragma GCC optimize(\"O3\")\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nstruct vertex\n{\n    char type;\n    vector<int>in;\n    bool val;\n    bool change;\n};\n\nint n;\nvector<vertex> g;\n\nint dfs1(int v)\n{\n    switch(g[v].type)\n    {\n    case 'A':\n        g[v].val = dfs1(g[v].in[0]) & dfs1(g[v].in[1]);\n        break;\n    case 'O':\n        g[v].val = dfs1(g[v].in[0]) | dfs1(g[v].in[1]);\n        break;\n    case 'X':\n        g[v].val = dfs1(g[v].in[0]) ^ dfs1(g[v].in[1]);\n        break;\n    case 'N':\n        g[v].val = ! dfs1(g[v].in[0]);\n        break;\n    }\n    return g[v].val;\n}\n\nvoid dfs2(int v)\n{\n    if(g[v].change==false)\n        for(int i=0;i<g[v].in.size();i++)\n            g[g[v].in[i]].change=false;\n    else\n        switch(g[v].type)\n        {\n        case 'A':\n            if(g[v].val==(!g[g[v].in[0]].val&g[g[v].in[1]].val)) /// equal to if(g[g[v].in[1]].val==false)\n                g[g[v].in[0]].change=false;\n            else\n                g[g[v].in[0]].change=true;\n            if(g[v].val==(g[g[v].in[0]].val&!g[g[v].in[1]].val)) /// equal to if(g[g[v].in[0]].val==false)\n                g[g[v].in[1]].change=false;\n            else\n                g[g[v].in[1]].change=true;\n            break;\n        case 'O':\n            if(g[v].val==(!g[g[v].in[0]].val|g[g[v].in[1]].val)) /// equal to if(g[g[v].in[1]].val==true)\n                g[g[v].in[0]].change=false;\n            else\n                g[g[v].in[0]].change=true;\n            if(g[v].val==(g[g[v].in[0]].val|!g[g[v].in[1]].val)) /// equal to if(g[g[v].in[0]].val==true)\n                g[g[v].in[1]].change=false;\n            else\n                g[g[v].in[1]].change=true;\n            break;\n        case 'X':\n            if(g[v].val==(!g[g[v].in[0]].val^g[g[v].in[1]].val)) /// equal to if(false)\n                g[g[v].in[0]].change=false;\n            else\n                g[g[v].in[0]].change=true;\n            if(g[v].val==(g[g[v].in[0]].val^!g[g[v].in[1]].val)) /// equal to if(false)\n                g[g[v].in[1]].change=false;\n            else\n                g[g[v].in[1]].change=true;\n            break;\n        case 'N':\n            if(g[v].val==(!!g[g[v].in[0]].val)) /// equal to if(false)\n                g[g[v].in[0]].change=false;\n            else\n                g[g[v].in[0]].change=true;\n            break;\n        }\n    for(int i=0;i<g[v].in.size();i++)\n        dfs2(g[v].in[i]);\n}\n\nint main()\n{\n    scanf(\"%d\",&n);\n    g.resize(n);\n    for(int i=0;i<n;i++)\n    {\n        char c[4];\n        scanf(\"%s\",c);\n        g[i].type=c[0];\n        int x;\n        switch(g[i].type)\n        {\n        case 'I':\n            scanf(\"%d\",&x);\n            g[i].val=x;\n            break;\n        case 'N':\n            scanf(\"%d\",&x);\n            g[i].in.push_back(x-1);\n            break;\n        default:\n            scanf(\"%d\",&x);\n            g[i].in.push_back(x-1);\n            scanf(\"%d\",&x);\n            g[i].in.push_back(x-1);\n            break;\n        }\n    }\n    dfs1(0);\n    g[0].change=true;\n    dfs2(0);\n    for(int i=0;i<n;i++)\n        if(g[i].type=='I')\n            printf(\"%d\",g[0].val^g[i].change);\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1010",
    "index": "E",
    "title": "Store",
    "statement": "Natasha was already going to fly back to Earth when she remembered that she needs to go to the Martian store to buy Martian souvenirs for her friends.\n\nIt is known, that the Martian year lasts $x_{max}$ months, month lasts $y_{max}$ days, day lasts $z_{max}$ seconds. Natasha also knows that this store works according to the following schedule: 2 months in a year were selected: $x_l$ and $x_r$ ($1\\le x_l\\le x_r\\le x_{max}$), 2 days in a month: $y_l$ and $y_r$ ($1\\le y_l\\le y_r\\le y_{max}$) and 2 seconds in a day: $z_l$ and $z_r$ ($1\\le z_l\\le z_r\\le z_{max}$). The store works at all such moments (month $x$, day $y$, second $z$), when simultaneously $x_l\\le x\\le x_r$, $y_l\\le y\\le y_r$ and $z_l\\le z\\le z_r$.\n\nUnfortunately, Natasha does not know the numbers $x_l,x_r,y_l,y_r,z_l,z_r$.\n\nOne Martian told Natasha: \"I went to this store $(n+m)$ times. $n$ times of them it was opened, and $m$ times — closed.\" He also described his every trip to the store: the month, day, second of the trip and whether the store was open or closed at that moment.\n\nNatasha can go to the store $k$ times. For each of them, determine whether the store at the time of the trip is open, closed, or this information is unknown.",
    "tutorial": "Consider $2$ options: $m=0$. This means that Natasha does not know about any moment when the store was closed. Let's find the numbers $x_l=min(x_i)$, $x_r=max(x_i)$, $y_l=min(y_i)$, $y_r=max(y_i)$, $z_l=min(z_i)$, $z_r=max(z_i)$, where $(x_i,y_i,z_i)$ are moments when store is open. For each query $(x_t,y_t,z_t)$ answer \"OPEN\", if $x_l\\le x_t\\le x_r$, $y_l\\le y_t\\le y_r$, and $z_l\\le z_t\\le z_r$. Answer \"UNKNOWN\" otherwise. $m\\ne0$. Let's find the numbers $x_l=min(x_i)$, $x_r=max(x_i)$, $y_l=min(y_i)$, $y_r=max(y_i)$, $z_l=min(z_i)$, $z_r=max(z_i)$, where $(x_i,y_i,z_i)$ are moments when store is open. If there is at least one moment $(x_j,y_j,z_j)$, when the store is closed, and $x_l\\le x_j\\le x_r$, $y_l\\le y_j\\le y_r$ and $z_l\\le z_j\\le z_r$, then the answer is \"INCORRECT\". Otherwise, let's create a compressed two-dimensional segment tree. The first coordinate is number of the month in the year, the second coordinate is number of the day in a month. At each vertex of the tree of segments we store a pair of numbers - the greatest such number of a second $z$, when the store was closed, in this day of this month, that $z\\le z_r$, and the smallest such number of a second $z$, when the store was closed, in this day of this month, that $z\\ge z_l$. Now every query $(x_t,y_t,z_t)$ we will handle like this. If $x_l\\le x_t\\le x_r$, $y_l\\le y_t\\le y_r$ and $z_l\\le z_t\\le z_r$, answer \"OPEN\". Otherwise, consider the parallelepiped given by the coordinates of opposite vertices $(x_l,y_l,z_l)$ and $(x_r,y_r,z_r)$ and consider each vertex in turn $(x_p,y_p,z_p)$ the parallelepiped under consideration. Let's make the query in the segment tree $(x_p,x_t)$, $(y_p,y_t)$. Let the received answer is $(z_{first},z_{second})$. If the number $z_{first}$ or number $z_{second}$ is between numbers $z_p$ and $z_t$, this means that there is such a time point $(x_j,y_j,z_j)$, when the store is closed, that $x_j$ is between $x_p$ and $x_t$ (the month of the year when the store is closed, is between the month in the year when the store is open, and the month in the year in the query), $y_j$ is between $y_p$ and $y_t$ (the day in the month when the store is closed is between the day in the month when the store is open and the day in the month in the query), $z_j$ is between $z_p$ and $z_t$ (second in a day, when the store is closed, is between a second in a day, when the store is open and a second in a day in the query), hence the answer to the query is \"CLOSED\". If the condition is not satisfied for any vertex of the parallelepiped, the answer is \"UNKNOWN\". Complexity: $O(n+m\\log m+k\\log^2m)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint xmax,ymax,zmax,n,m,k;\n\nmap< int , map< int , pair< int ,int > > > pmap;\nvector< pair< int , map< int , pair< int ,int > > > > pvector;\nvector< pair< vector< pair< int , pair< int , int > > > , vector< pair< int , int > > > > tree;\nint oxl,oxr,oyl,oyr,ozl,ozr;\n\npair<int,int> comb(pair<int,int> p1,pair<int,int> p2)\n{\n    return make_pair(max(p1.first,p2.first),\n                     min(p1.second,p2.second));\n}\n\nvoid build_y(int vx,int lxt, int rxt,int vy,int lyt, int ryt)\n{\n    if(lyt==ryt)\n    {\n        if(lxt==rxt)\n            tree[vx].second[vy]=tree[vx].first[lyt].second;\n        else\n        {\n            int sl,sr;\n            sl=0,sr=tree[vx*2+1].first.size()-1;\n            while(sr>sl)\n            {\n                int sm=(sl+sr)/2;\n                if(tree[vx*2+1].first[sm].first>=tree[vx].first[lyt].first)\n                    sr=sm;\n                else\n                    sl=sm+1;\n            }\n            pair<int,int> res1=(tree[vx*2+1].first[sl].first==tree[vx].first[lyt].first)?\n                               (tree[vx*2+1].first[sl].second):\n                                make_pair(0,(int)zmax+1);\n            sl=0,sr=tree[vx*2+2].first.size()-1;\n            while(sr>sl)\n            {\n                int sm=(sl+sr)/2;\n                if(tree[vx*2+2].first[sm].first>=tree[vx].first[lyt].first)\n                    sr=sm;\n                else\n                    sl=sm+1;\n            }\n            pair<int,int> res2=(tree[vx*2+2].first[sl].first==tree[vx].first[lyt].first)?\n                               (tree[vx*2+2].first[sl].second):\n                                make_pair(0,(int)zmax+1);\n            tree[vx].second[vy]=comb(res1,res2);\n        }\n    }\n    else\n    {\n        int myt=(lyt+ryt)/2;\n        build_y(vx,lxt,rxt,vy*2+1,lyt,myt);\n        build_y(vx,lxt,rxt,vy*2+2,myt+1,ryt);\n        tree[vx].second[vy]=comb(tree[vx].second[vy*2+1],tree[vx].second[vy*2+2]);\n    }\n}\n\nvoid build_x(int vx,int lxt, int rxt)\n{\n    if(lxt==rxt)\n        tree[vx].first=vector< pair< int , pair< int , int > > >(pvector[lxt].second.begin(),pvector[lxt].second.end());\n    else\n    {\n        int mxt=(lxt+rxt)/2;\n        build_x(2*vx+1,lxt,mxt);\n        build_x(2*vx+2,mxt+1,rxt);\n        for(vector< pair< int , pair< int , int > > >::iterator i=tree[2*vx+1].first.begin(),j=tree[2*vx+2].first.begin();;)\n        {\n            if(i==tree[2*vx+1].first.end())\n            {\n                for(;j!=tree[2*vx+2].first.end();j++)\n                    tree[vx].first.push_back(*j);\n                break;\n            }\n            if(j==tree[2*vx+2].first.end())\n            {\n                for(;i!=tree[2*vx+1].first.end();i++)\n                    tree[vx].first.push_back(*i);\n                break;\n            }\n            if(i->first<j->first)\n            {\n                tree[vx].first.push_back(*i);\n                i++;\n            }\n            else if(j->first<i->first)\n            {\n                tree[vx].first.push_back(*j);\n                j++;\n            }\n            else\n            {\n                tree[vx].first.push_back(make_pair(i->first,comb(i->second,j->second)));\n                i++;\n                j++;\n            }\n        }\n    }\n    tree[vx].second.resize(tree[vx].first.size()*4);\n    build_y(vx,lxt,rxt,0,0,tree[vx].first.size()-1);\n}\n\npair<int,int> get_y(int vx, int vy, int lyt, int ryt, int lyc, int ryc)\n{\n    if(lyc>ryc)\n        return make_pair(0,zmax+1);\n    if(lyc==lyt&&ryt==ryc)\n        return tree[vx].second[vy];\n    int myt=(lyt+ryt)/2;\n    return comb(get_y(vx,vy*2+1,lyt,myt,lyc,min(ryc,myt)),\n                get_y(vx,vy*2+2,myt+1,ryt,max(lyc,myt+1),ryc));\n}\n\npair<int,int> get_x(int vx, int lxt, int rxt, int lxc, int rxc, int ly, int ry)\n{\n    if(lxc>rxc)\n        return make_pair(0,zmax+1);\n    if(lxc==lxt&&rxt==rxc)\n    {\n        int sl,sr;\n        sl=0,sr=tree[vx].first.size()-1;\n        while(sr>sl)\n        {\n            int sm=(sl+sr)/2;\n            if(tree[vx].first[sm].first>=ly)\n                sr=sm;\n            else\n                sl=sm+1;\n        }\n        int lyc=sl;\n        sl=0,sr=tree[vx].first.size()-1;\n        while(sr>sl)\n        {\n            int sm=(sl+sr+1)/2;\n            if(tree[vx].first[sm].first<=ry)\n                sl=sm;\n            else\n                sr=sm-1;\n        }\n        int ryc=sr;\n        return (tree[vx].first[lyc].first>=ly&&tree[vx].first[ryc].first<=ry)?\n               get_y(vx,0,0,tree[vx].first.size()-1,lyc,ryc):\n               make_pair(0,(int)zmax+1);\n    }\n    int mxt=(lxt+rxt)/2;\n    return comb(get_x(vx*2+1,lxt,mxt,lxc,min(rxc,mxt),ly,ry),\n                get_x(vx*2+2,mxt+1,rxt,max(lxc,mxt+1),rxc,ly,ry));\n}\n\nint main()\n{\n    scanf(\"%d%d%d%d%d%d\",&xmax,&ymax,&zmax,&n,&m,&k);\n    oxl=xmax;\n    oxr=1;\n    oyl=ymax;\n    oyr=1;\n    ozl=zmax;\n    ozr=1;\n    for(int i=0;i<n;i++)\n    {\n        int x,y,z;\n        scanf(\"%d%d%d\",&x,&y,&z);\n        oxl=min(oxl,x);\n        oxr=max(oxr,x);\n        oyl=min(oyl,y);\n        oyr=max(oyr,y);\n        ozl=min(ozl,z);\n        ozr=max(ozr,z);\n    }\n    for(int i=0;i<m;i++)\n    {\n        int x,y,z;\n        scanf(\"%d%d%d\",&x,&y,&z);\n        if(oxl<=x&&x<=oxr&&oyl<=y&&y<=oyr&&ozl<=z&&z<=ozr)\n        {\n            printf(\"INCORRECT\\n\");\n            exit(0);\n        }\n        map< int , pair< int ,int > >::iterator it=pmap[x].insert(make_pair(y,make_pair(0,zmax+1))).first;\n        if(z<=ozr)\n            it->second.first=max(it->second.first,z);\n        if(z>=ozl)\n            it->second.second=min(it->second.second,z);\n    }\n    printf(\"CORRECT\\n\");\n    if(m>0)\n    {\n        pvector=vector< pair< int , map< int , pair< int ,int > > > >(pmap.begin(),pmap.end());\n        tree.resize(pvector.size()*4);\n        build_x(0,0,pvector.size()-1);\n    }\n    for(int i=0;i<k;i++)\n    {\n        int x,y,z;\n        scanf(\"%d%d%d\",&x,&y,&z);\n        if(oxl<=x&&x<=oxr&&oyl<=y&&y<=oyr&&ozl<=z&&z<=ozr)\n        {\n            printf(\"OPEN\\n\");\n            continue;\n        }\n        if(m==0)\n        {\n            printf(\"UNKNOWN\\n\");\n            continue;\n        }\n        bool closed=false;\n        for(int ii=0;ii<=1;ii++)\n            for(int jj=0;jj<=1;jj++)\n            {\n                if(closed)\n                    break;\n                int i=oxl+ii*(oxr-oxl);\n                int j=oyl+jj*(oyr-oyl);\n                int lx=min(x,i),rx=max(x,i);\n                int sl,sr;\n                sl=0,sr=pvector.size()-1;\n                while(sr>sl)\n                {\n                    int sm=(sl+sr)/2;\n                    if(pvector[sm].first>=lx)\n                        sr=sm;\n                    else\n                        sl=sm+1;\n                }\n                int lxc=sl;\n                sl=0,sr=pvector.size()-1;\n                while(sr>sl)\n                {\n                    int sm=(sl+sr+1)/2;\n                    if(pvector[sm].first<=rx)\n                        sl=sm;\n                    else\n                        sr=sm-1;\n                }\n                int rxc=sr;\n                if(pvector[lxc].first>=lx&&pvector[rxc].first<=rx)\n                {\n                    pair<int,int> p=get_x(0,0,pvector.size()-1,lxc,rxc,min(y,j),max(y,j));\n                    if(min({z,ozl,ozr})<=p.first||max({z,ozl,ozr})>=p.second)\n                        closed=true;\n                }\n            }\n        if(closed)\n            printf(\"CLOSED\\n\");\n        else\n            printf(\"UNKNOWN\\n\");\n    }\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1010",
    "index": "F",
    "title": "Tree",
    "statement": "The Main Martian Tree grows on Mars. It is a binary tree (a rooted tree, with no more than two sons at each vertex) with $n$ vertices, where the root vertex has the number $1$. Its fruits are the Main Martian Fruits. It's summer now, so this tree does not have any fruit yet.\n\nAutumn is coming soon, and leaves and branches will begin to fall off the tree. It is clear, that if a vertex falls off the tree, then its entire subtree will fall off too. In addition, the root will remain on the tree. Formally: the tree will have some connected subset of vertices containing the root.\n\nAfter that, the fruits will grow on the tree (only at those vertices which remain). Exactly $x$ fruits will grow in the root. The number of fruits in each remaining vertex will be not less than the sum of the numbers of fruits in the remaining sons of this vertex. It is allowed, that some vertices will not have any fruits.\n\nNatasha wondered how many tree configurations can be after the described changes. Since this number can be very large, output it modulo $998244353$.\n\nTwo configurations of the resulting tree are considered different if one of these two conditions is true:\n\n- they have different subsets of remaining vertices;\n- they have the same subset of remaining vertices, but there is a vertex in this subset where they have a different amount of fruits.",
    "tutorial": "Let $b_v = a_v - \\sum{a_{to}}$, (for each $(v, to)$, such that $to$ - is a son of $v$ and tree have both vertices $v$ and $to$), then all that we need is $b_v \\geq 0$ and $\\sum{b_v} = x$, so for fixed subset of vertices number of ways to arrange weights is just number of ways to partite $x$ into such number of parts. So let $f_i$ be number of ways to choose connected subtree of $i$ vertices, that contains vertex $1$, then answer is $\\sum{f_i C_{x+i-1}^{i-1}}$. Then we need to calculate $f_i$ for each $1 \\leq i \\leq n$, and calculate $C_{x+i-1}^{i-1}$ for each $1 \\leq i \\leq n$. Let's use generating functions to calc $f_i$. Let $dp_v$ be generating function of $\\sum{f_i \\cdot x^i}$, (if we will assume that $v$ - root and we will look only at vertices inside subtree of $v$). Then if vertex $v$ - leaf, then $dp_v = x + 1$, if this vertex have one son, $dp_v = dp_{to} x + 1$, and if two, then $dp_v = dp_l dp_r x + 1$. Then let maintain $dp_v$ as a sequence of polynomials $a_1, a_2, \\ldots, a_k$, such that $dp_v = (((a_1 + 1) a_2 + 1) \\ldots) a_k + 1$). Then if we have the representation of $dp_v$ in such format, we can find the exact value of polynomial in the sum of sizes of polynomials $\\cdot \\log^2{n}$. For it you can note, that $dp_v$ is just $a_1 a_2 a_3 \\ldots a_k + a_2 a_3 \\ldots a_k + \\ldots + a_k + 1$. And then with FFT you can calculate value and multiplication for left half ($P_l(x)$ and $Q_l(x)$), and for right half ($P_r(x)$ and $Q_r(x)$). Then $P(x) = (P_l(x) - 1) Q_r(x) + P_r(x)$, a $Q(x) = Q_l(x) Q_r(x)$. So, you can calculate exact value of $dp_v$ in $T(n) = 2T(n/2) + O(n \\log {n}) = O(n \\log^2 {n})$ (Where $n$ is sum of sizes of polynomials). Then if $v$ - leaf just add $x$ into the sequence of polynomials. If $v$ have one son, then add $x$ into the sequence of polynomials of a son, and take his sequence as a sequence for vertex $v$. And if $v$ have two sons, Let's take a son with the smaller size of a subtree, find its exact value as written, and add it into the sequence of another son. Sum of sizes of smaller subtrees is $O(n \\log {n})$, so we can find $f$ in $O(n \\log^3{n})$. Note, that you can find similar value when the tree is not binary too, for it you can find the exact value of all children without largest, and multiply it in $O(n \\log^2 (n))$ with D&C. To calculate $C_{x+i-1}^{i-1}$ for each $1 \\leq i \\leq n$ you can note, that when $i=1$ it is just $1$, and to get a value for $i+1$ you need multiply current value on $x+i-1$ and divide on $i$. Then you can find scalar multiplication of these two vectors, and solve the task in $O(n \\log^3{n}$).",
    "code": "#include <cmath>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <cassert>\n#include <unordered_map>\n#include <unordered_set>\n#include <iomanip>\n#include <bitset>\n#include <sstream>\n\nusing namespace std;\n\ntypedef long long ll;\n\nmt19937 rnd(228);\n\nconst int md = 998244353;\n\ninline void add(int &a, int b) {\n  a += b;\n  if (a >= md) a -= md;\n}\n\ninline void sub(int &a, int b) {\n  a -= b;\n  if (a < 0) a += md;\n}\n\n\ninline int mul(int a, int b) {\n#if !defined(_WIN32) || defined(_WIN64)\n  return (int) ((long long) a * b % md);\n#endif\n  unsigned long long x = (long long) a * b;\n  unsigned xh = (unsigned) (x >> 32), xl = (unsigned) x, d, m;\n  asm(\n    \"divl %4; \\n\\t\"\n    : \"=a\" (d), \"=d\" (m)\n    : \"d\" (xh), \"a\" (xl), \"r\" (md)\n  );\n  return m;\n}\n\ninline int power(int a, long long b) {\n  int res = 1;\n  while (b > 0) {\n    if (b & 1) {\n      res = mul(res, a);\n    }\n    a = mul(a, a);\n    b >>= 1;\n  }\n  return res;\n}\n\ninline int inv(int a) {\n  a %= md;\n  if (a < 0) a += md;\n  int b = md, u = 0, v = 1;\n  while (a) {\n    int t = b / a;\n    b -= t * a; swap(a, b);\n    u -= t * v; swap(u, v);\n  }\n  assert(b == 1);\n  if (u < 0) u += md;\n  return u;\n}\n\nnamespace ntt {\n  int base = 1;\n  vector<int> roots = {0, 1};\n  vector<int> rev = {0, 1};\n  int max_base = -1;\n  int root = -1;\n\n  void init() {\n    int tmp = md - 1;\n    max_base = 0;\n    while (tmp % 2 == 0) {\n      tmp /= 2;\n      max_base++;\n    }\n    root = 2;\n    while (true) {\n      if (power(root, 1 << max_base) == 1) {\n        if (power(root, 1 << (max_base - 1)) != 1) {\n          break;\n        }\n      }\n      root++;\n    }\n  }\n\n  void ensure_base(int nbase) {\n    if (max_base == -1) {\n      init();\n    }\n    if (nbase <= base) {\n      return;\n    }\n    assert(nbase <= max_base);\n    rev.resize(1 << nbase);\n    for (int i = 0; i < (1 << nbase); i++) {\n      rev[i] = (rev[i >> 1] >> 1) + ((i & 1) << (nbase - 1));\n    }\n    roots.resize(1 << nbase);\n    while (base < nbase) {\n      int z = power(root, 1 << (max_base - 1 - base));\n      for (int i = 1 << (base - 1); i < (1 << base); i++) {\n        roots[i << 1] = roots[i];\n        roots[(i << 1) + 1] = mul(roots[i], z);\n      }\n      base++;\n    }\n  }\n\n  void fft(vector<int> &a) {\n    int n = (int) a.size();\n    assert((n & (n - 1)) == 0);\n    int zeros = __builtin_ctz(n);\n    ensure_base(zeros);\n    int shift = base - zeros;\n    for (int i = 0; i < n; i++) {\n      if (i < (rev[i] >> shift)) {\n        swap(a[i], a[rev[i] >> shift]);\n      }\n    }\n    for (int k = 1; k < n; k <<= 1) {\n      for (int i = 0; i < n; i += 2 * k) {\n        for (int j = 0; j < k; j++) {\n          int x = a[i + j];\n          int y = mul(a[i + j + k], roots[j + k]);\n          a[i + j] = x + y - md;\n          if (a[i + j] < 0) a[i + j] += md;\n          a[i + j + k] = x - y + md;\n          if (a[i + j + k] >= md) a[i + j + k] -= md;\n        }\n      }\n    }\n  }\n\n  vector<int> multiply(vector<int> a, vector<int> b, int eq = 0) {\n    int need = (int) (a.size() + b.size() - 1);\n    int nbase = 0;\n    while ((1 << nbase) < need) nbase++;\n    ensure_base(nbase);\n    int sz = 1 << nbase;\n    a.resize(sz);\n    b.resize(sz);\n    fft(a);\n    if (eq) b = a; else fft(b);\n    int inv_sz = inv(sz);\n    for (int i = 0; i < sz; i++) {\n      a[i] = mul(mul(a[i], b[i]), inv_sz);\n    }\n    reverse(a.begin() + 1, a.end());\n    fft(a);\n    a.resize(need);\n    while (!a.empty() && a.back() == 0) {\n        a.pop_back();\n    }\n    return a;\n  }\n\n  vector<int> square(vector<int> a) {\n    return multiply(a, a, 1);\n  }\n};\n\nconst int N = 1e5 + 1;\n\nvector <vector <int> > polys[N];\nint l[N], r[N];\nint who[N];\nint sz[N];\n\nvector <int> slozh(const vector <int> &a, const vector <int> &b)\n{\n    int n = (int) a.size(), m = (int) b.size();\n    vector <int> c(max(n, m));\n    for (int i = 0; i < n; i++) add(c[i], a[i]);\n    for (int i = 0; i < m; i++) add(c[i], b[i]);\n    return c;\n}\n\npair <vector <int>, vector <int> > eval(const vector <vector <int> > &a)\n{\n    if (a.size() == 1)\n    {\n        auto ret = a[0];\n        ret[0]++;\n        return {ret, a[0]};\n    }\n    else\n    {\n        int m = (int) a.size() / 2;\n        vector <vector <int> > l, r;\n        for (int i = 0; i < m; i++)\n        {\n            l.push_back(a[i]);\n        }\n        for (int i = m; i < (int) a.size(); i++)\n        {\n            r.push_back(a[i]);\n        }\n        auto lf = eval(l), rf = eval(r);\n        add(lf.first[0], -1);\n        auto P = slozh(ntt::multiply(lf.first, rf.second), rf.first);\n        auto Q = ntt::multiply(lf.second, rf.second);\n        return {P, Q};\n    }\n}\n\nvector <int> g[N];\n\nvoid dfs(int v, int pr)\n{\n    vector <int> go;\n    int deg = 0;\n    for (int to : g[v])\n    {\n        if (to != pr)\n        {\n            go.push_back(to);\n            deg++;\n        }\n    }\n    if (deg == 0)\n    {\n        polys[v].push_back({0, 1});\n        sz[v] = 1;\n        who[v] = v;\n    }\n    else\n    {\n        if (deg == 2)\n        {\n            l[v] = go[0];\n            r[v] = go[1];\n            dfs(l[v], v);\n            dfs(r[v], v);\n            sz[v] = sz[l[v]] + sz[r[v]] + 1;\n            if (sz[l[v]] < sz[r[v]])\n            {\n                swap(l[v], r[v]);\n            }\n            auto go = eval(polys[who[r[v]]]).first;\n            go.insert(go.begin(), 0);\n            polys[who[l[v]]].push_back(go);\n            who[v] = who[l[v]];\n        }\n        else\n        {\n            int son = go[0];\n            dfs(son, v);\n            sz[v] = sz[son] + 1;\n            who[v] = who[son];\n            polys[who[v]].push_back({0, 1});\n        }\n    }\n}\n\nvector <int> binom(ll n, int k)\n{\n    if (n == 0)\n    {\n        vector <int> ret(k + 1);\n        ret[0] = 1;\n        return ret;\n    }\n    else if (n % 2 == 0)\n    {\n        auto a = binom(n / 2, k);\n        a = ntt::square(a);\n        a.resize(k + 1);\n        return a;\n    }\n    else\n    {\n        auto a = binom(n - 1, k);\n        for (int i = k; i >= 0; i--)\n        {\n            if (i != 0)\n            {\n                add(a[i], a[i - 1]);\n            }\n        }\n        return a;\n    }\n}\n\nint main()\n{\n#ifdef ONPC\n    freopen(\"a.in\", \"r\", stdin);\n#endif\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    int n;\n    cin >> n;\n    ll x;\n    cin >> x;\n    vector <int> fact(n + 1), rev_fact(n + 1);\n    fact[0] = 1;\n    for (int i = 1; i <= n; i++)\n    {\n        fact[i] = mul(fact[i - 1], i);\n    }\n    for (int i = 0; i <= n; i++)\n    {\n        rev_fact[i] = inv(fact[i]);\n    }\n    for (int i = 1; i < n; i++)\n    {\n        int a, b;\n        cin >> a >> b;\n        a--, b--;\n        g[a].push_back(b);\n        g[b].push_back(a);\n    }\n    dfs(0, -1);\n    auto solve = eval(polys[who[0]]).first;\n    auto big_binoms = binom(x, n);\n    for (int i = 0; i <= n; i++)\n    {\n        big_binoms[i] = mul(big_binoms[i], rev_fact[i]);\n    }\n    rev_fact.insert(rev_fact.begin(), 0);\n    big_binoms = ntt::multiply(big_binoms, rev_fact);\n    int ans = 0;\n    for (int i = 1; i <= n; i++)\n    {\n        add(ans, mul(mul(solve[i], big_binoms[i]), fact[i - 1]));\n    }\n    cout << ans << '\\n';\n}",
    "tags": [
      "fft",
      "graphs",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1011",
    "index": "A",
    "title": "Stages",
    "statement": "Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.\n\nThere are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.\n\nFor the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $26$ tons.\n\nBuild the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.",
    "tutorial": "The problem can be solved by the following greedy algorithm. Sort letters in increasing order. Let's try to add letters in this order. If the current letter is the first in the string, then add it to the answer. Otherwise, check: if the current letter is at least two positions later in the alphabet than the previous letter of the answer, add it to the response, otherwise go over to the next letter. As soon as there are $k$ letters in the answer, print it. If after this algorithm the answer has less than $k$ letters, print -1. Complexity: $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int n,k;\n    cin>>n>>k;\n    string s;\n    cin>>s;\n    sort(s.begin(),s.end());\n    char last='a'-2;\n    int ans=0;\n    int len=0;\n    for(int i=0;i<n;i++)\n        if(s[i]>=last+2)\n        {\n            last=s[i];\n            ans+=s[i]-'a'+1;\n            len++;\n            if(len>=k)\n                cout<<ans,exit(0);\n        }\n    cout<<-1;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1011",
    "index": "B",
    "title": "Planning The Expedition",
    "statement": "Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant.\n\nThe warehouse has $m$ daily food packages. Each package has some food type $a_i$.\n\nEach participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food.\n\nFormally, for each participant $j$ Natasha should select his food type $b_j$ and each day $j$-th participant will eat one food package of type $b_j$. The values $b_j$ for different participants may be different.\n\nWhat is the maximum possible number of days the expedition can last, following the requirements above?",
    "tutorial": "Let $c_i$ be the number of food packages that equal to $i$. Calculate the array $c$. For any $d$ we can calculate the maximum number of people $k$, who can participate in the expedition for $d$ days. To do this, we'll go over all the elements of the array $c$. Let now be considered $c_i$. If $c_i \\ge d$, we can decrease $c_i$ by $d$ and increase $k$ by $1$, that is, take $d$ daily food packages for one person. If still $c_i \\ge d$, repeat the algorithm, and so on. That is for $i$-th iteration number $k$ increases by $\\left\\lfloor \\dfrac{c_i}d \\right\\rfloor$. After all the iterations the number $k$ will be the required number of people. It is clear that the answer does not exceed $m$ (every day at least one food package is used). Let's iterate $d$ from $m$ to $1$, each time checking whether the answer can be equal $d$. To do this, we calculate the maximum number of people $k$, who can participate in the expedition for $d$ days. If $k \\ge n$, then the answer is $d$. If no answer was received on any iteration, then the answer is $0$. Complexity: $O(m^2)$. Bonus. Try to improve the complexity to $O(m \\log m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 100;\n\nint main() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> c(N + 1);\n    for (int i = 0; i < m; i++) {\n        int a;\n        cin >> a;\n        c[a]++;\n    }\n    for (int d = N; d >= 1; d--) {\n        vector<int> cc(c);\n        int k = 0;\n        for (int i = 1; i <= N; i++)\n            while (cc[i] >= d) {\n                k++;\n                cc[i] -= d;\n            }\n        if (k >= n) {\n            cout << d << endl;\n            return 0;\n        }\n    }\n    cout << 0 << endl;\n}",
    "tags": [
      "binary search",
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1012",
    "index": "A",
    "title": "Photo of The Sky",
    "statement": "Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.\n\nStrictly speaking, it makes a photo of all points with coordinates $(x, y)$, such that $x_1 \\leq x \\leq x_2$ and $y_1 \\leq y \\leq y_2$, where $(x_1, y_1)$ and $(x_2, y_2)$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.\n\nAfter taking the photo, Pavel wrote down coordinates of $n$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.\n\nPavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.\n\nPavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.",
    "tutorial": "At first let's sort array $a$, so we can assume that $a_1 \\leq a_2 \\leq \\dots \\leq a_{2 \\cdot n}$. Note that area of rectangle with bottom-left corner in $(x_1, y_1)$, and up-right corner in $(x_2, y_2)$ is $(x_2 - x_1) \\cdot (y_2 - y_1)$. So the task is to partite array $a$ into $2$ multisets (sets with equal elements) $X$ and $Y$ of size $n$, such that $(max(X) - min(X)) \\cdot (max(Y) - min(Y))$ is minimal among all such partitions ($min(X)$ - minimum in multiset $X$, $max(X)$ - maximum in multiset $X$). Let's look at such partition There are $2$ cases: Minimum and maximum are in one multiset. Let's assume that they are both in $X$. Then $max(X) - min(X) = a_{2 \\cdot n} - a_1$. We need to minimize $max(Y) - min(Y)$. If index of $min(Y)$ in $a$ is $i$, and $max(Y)$ is $j$, htne $j - i \\geq n - 1$, because there are $n$ elements in $Y$. So we can use $Y = \\{a_i, a_{i+1}, \\dots, a_{i+n-1}\\}$ and desired difference will not increase. So as $Y$ it is optimial to use some segment of length $n$. Minimum and maximum are not in one multiset. Let's assume that minimum in $X$, and maximum in $Y$. Then note, that maximum in $X$ always $\\geq a_n$, because size of $X$ is $n$. And minimum in $Y$ will be $\\leq a_{n+1}$, because size of $Y$ is $n$. So $(max(X) - min(X)) \\cdot (max(Y) - min(Y)) \\geq (a_n - a_1) \\cdot (a_{2 \\cdot n} - a_{n+1})$, so you can use prefix of length $n$ as $X$ and suffix of length $n$ as $Y$. So answer is minimum of $(a_{2 \\cdot n} - a_1) \\cdot (a_{i+n-1} - a_i)$ for each $2 \\leq i \\leq n$ and $(a_n - a_1) \\cdot (a_{2 \\cdot n} - a_{n+1})$. That is, you can simply check all contigious subsets as first set and all the remaints as the second one. Complexity is $O(n \\cdot log(n))$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int M = 2e5 + 239;\nconst int BIG = 1e9 + 239;\n \nint n, a[M];\n \nint main()\n{\n\tcin.sync_with_stdio(0);\n\tcin >> n;\n\tfor (int i = 0; i < (2 * n); i++)\n\t\tcin >> a[i];\n\tsort(a, a + (2 * n));\n\tif (n == 1)\n\t{\n\t\tcout << \"0\";\n\t\treturn 0;\n\t}\n\tint now = BIG;\n\tfor (int i = 1; i < n; i++) now = min(now, a[i + n - 1] - a[i]); \n\tcout << min((ll)(a[2 * n - 1] - a[0]) * (ll)now, (ll)(a[n - 1] - a[0]) * (ll)(a[2 * n - 1] - a[n]));\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1012",
    "index": "B",
    "title": "Chemical table",
    "statement": "Innopolis University scientists continue to investigate the periodic table. There are $n·m$ known elements and they form a periodic table: a rectangle with $n$ rows and $m$ columns. Each element can be described by its coordinates $(r, c)$ ($1 ≤ r ≤ n$, $1 ≤ c ≤ m$) in the table.\n\nRecently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions $(r_{1}, c_{1})$, $(r_{1}, c_{2})$, $(r_{2}, c_{1})$, where $r_{1} ≠ r_{2}$ and $c_{1} ≠ c_{2}$, then we can produce element $(r_{2}, c_{2})$.\n\nSamples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.\n\nInnopolis University scientists already have samples of $q$ elements. They want to obtain samples of all $n·m$ elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.",
    "tutorial": "One of the way to solve this problem is to interprete the cells in 2d matrix as an edge in the bipartite graph, that is a cell $(i, j)$ is an edge between $i$ of the left part and $j$ of the right part. Note, that each fusion operation (we have edges $(r_{1}, c_{1})$, $(r_{1}, c_{2})$, $(r_{2}, c_{1})$ and get edge $(r_{2}, c_{2})$) doesn't change the connected components of the graph. Moreover, we can prove, that we can obtain each edge in the connected component by fusion. Let's examine example edge $(x, y)$, and some path between $x$ and $y$ (since they lay in one connected component). Since the graph is bipartite, the length of this path must be odd, and it is $ \\ge  3$, otherwise the edge already exists. So we have this path. Take first three edges and make the corresponding fusion, replace this three edges with the brand new fused edge. The length of the path decreased by $2$. Repeat until the path is a mere edge. This way, the number of edges to add (cells to buy) is just number of connected components minus one.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "matrices"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1012",
    "index": "C",
    "title": "Hills",
    "statement": "Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction.\n\nFrom the window in your room, you see the sequence of $n$ hills, where $i$-th of them has height $a_{i}$. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appearance, a house can be only built on the hill, which is strictly higher than neighbouring hills (if they are present). For example, if the sequence of heights is $5, 4, 6, 2$, then houses could be built on hills with heights $5$ and $6$ only.\n\nThe Innopolis administration has an excavator, that can decrease the height of an arbitrary hill by one in one hour. The excavator can only work on one hill at a time. It is allowed to decrease hills up to zero height, or even to negative values. Increasing height of any hill is impossible. The city administration wants to build $k$ houses, so there must be at least $k$ hills that satisfy the condition above. What is the minimum time required to adjust the hills to achieve the administration's plan?\n\nHowever, the exact value of $k$ is not yet determined, so could you please calculate answers for all $k$ in range $1\\leq k\\leq\\,\\lceil\\frac{n}{2}\\rceil$? Here $\\textstyle{\\left[\\!\\!{\\frac{n}{2}}\\right]\\!\\!}\\$ denotes $n$ divided by two, rounded up.",
    "tutorial": "The problem's short statement is: \"we allowed to decrease any element and should create at least $k$ local maximums, count the minimum number of operations for all $k$\". Notice, that any set of positions, where no positions are adjacent could be made to be local maximums - we just need to decrease the neighbouring hills to some value. Let's introduce the following dynamic programming: dp[prefix][local_maxs] - the minimum cost if we analyze only given prefix, have the specified number of local maximums (\"good hills to build on\") and we make a local maximum in the last hill of this prefix. Th dumb implementation of this leads to $O(n^{2})$ states and $O(n^{4})$ time - in each state we can brute force the previous position of local maximum ($n$) and then calculate the cost of patching the segment from previous local maximum to current one. A more attentive look says that it is, in fact $O(n^{3})$ solution - on the segment only first and last elements need to be decreased (possibly first and last elements are same). To get the full solution full solution in $O(n^{2})$ we need to optimize dp a little bit. As we noticed in the previous paragraph, there is one extreme situation, when the first and elements are same, let's handle this transition by hand in $O(1)$ for each state. Otherwise, funny fact, the cost of the segment strictly between local maximums is the cost of it's left part plus it'cost of it's right part. Seems like something we can decompose, right? Since our goal is to update state $(prefix, local)$ now the right part is fixed constant for all such transitions. And we need to select minimum value of $dp[i][local - 1] + cost(i, i + 1)$ where $i < = prefix - 3$. This can be done by calculating a supplementary dp during the primarily dp calculation - for example we can calculate f[pref][j] = min dp[i][j] + cost(i, i + 1) for $i  \\le  pref$.",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1012",
    "index": "D",
    "title": "AB-Strings",
    "statement": "There are two strings $s$ and $t$, consisting only of letters a and b. You can make the following operation several times: choose a prefix of $s$, a prefix of $t$ and swap them. Prefixes \\underline{can be empty}, also a prefix can coincide with a whole string.\n\nYour task is to find a sequence of operations after which one of the strings consists only of a letters and the other consists only of b letters. The number of operations should be \\underline{minimized}.",
    "tutorial": "The solution is basically like following: Note that we can compress equal adjacent letters. Now we can do a dynamic programming with params (first letter of $s$, length of $s$, first letter of $t$, length of $t$). However, the amount of transactions and even states is too large. But we can write a slow, but surely correct solution, and examine the transactions, which are made in dp. Basically, the most typical transaction is to just make a swap of first group in $s$ with first group in $t$. However there special cases, like when the first letters are the same or when the lengths are very small. Running a slow dynamic programming helps to get all the cases for the solution. Formally, the correctness of this algorithm can be proven by induction and the large cases analyses, which we skip for clarity. Another approach is to consider different first operations, and then go a greedy after it algorithm. See the second solution for the details. We don't prove it.",
    "code": "import java.io.*;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.StringTokenizer;\n \n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n */\npublic class swap_prefixes_av_n {\n    public static void main(String[] args) {\n        InputStream inputStream = System.in;\n        OutputStream outputStream = System.out;\n        FastScanner in = new FastScanner(inputStream);\n        PrintWriter out = new PrintWriter(outputStream);\n        SwapPrefixesDp solver = new SwapPrefixesDp();\n        solver.solve(1, in, out);\n        out.close();\n    }\n \n    static class SwapPrefixesDp {\n        public void solve(int testNumber, FastScanner in, PrintWriter out) {\n            String s = in.next(), t = in.next();\n            List<Integer> ans1 = solve(\"a\" + s, \"b\" + t);\n            List<Integer> ans2 = solve(\"b\" + s, \"a\" + t);\n            if (ans1.size() > ans2.size()) {\n                ans1 = ans2;\n            }\n            out.println(ans1.size() / 2);\n            for (int i = 0; i < ans1.size(); i += 2) {\n                out.println(ans1.get(i) + \" \" + ans1.get(i + 1));\n            }\n        }\n \n        private void makeSwap(List<Integer> realAns, List<Pair> compressedS, List<Pair> compressedT, int lenS, int lenT) {\n            List<Pair> newS = new ArrayList<>();\n            List<Pair> newT = new ArrayList<>();\n \n            int realLenS = 0, realLenT = 0;\n            for (int i = 0; i < lenS; i++) {\n                realLenS += compressedS.get(i).count;\n            }\n            for (int i = 0; i < lenT; i++) {\n                realLenT += compressedT.get(i).count;\n            }\n            realAns.add(realLenS - 1);\n            realAns.add(realLenT - 1);\n            concatLists(compressedS, compressedT, lenS, lenT, newS);\n            concatLists(compressedT, compressedS, lenT, lenS, newT);\n            compressedS.clear();\n            compressedS.addAll(newS);\n            compressedT.clear();\n            compressedT.addAll(newT);\n        }\n \n        private void concatLists(List<Pair> compressedS, List<Pair> compressedT, int lenS, int lenT, List<Pair> newS) {\n            newS.addAll(compressedT.subList(0, lenT));\n            newS.addAll(compressedS.subList(lenS, compressedS.size()));\n            if (lenT < newS.size() && newS.get(lenT - 1).ch == newS.get(lenT).ch) {\n                newS.get(lenT - 1).count += newS.get(lenT).count;\n                newS.remove(lenT);\n            }\n        }\n \n        private List<Integer> solve(String s, String t) {\n            List<Pair> compressedS = compress(s);\n            List<Pair> compressedT = compress(t);\n            if (compressedS.size() == 1 && compressedT.size() == 1) {\n                return new ArrayList<>();\n            }\n            int curI = compressedS.size(), curJ = compressedT.size();\n \n            int bestI = -1, bestJ = -1;\n            int bestCost = Integer.MAX_VALUE;\n \n            for (int lenI = 1; lenI <= compressedS.size(); lenI++) {\n                for (int lenJ = 1; lenJ <= compressedT.size(); lenJ++) {\n                    if (lenI % 2 != lenJ % 2) {\n                        continue;\n                    }\n                    if (lenI > 3 && lenJ > 3) {\n                        break;\n                    }\n                    int nextI = lenJ + (curI - lenI) - ((curI != lenI && lenJ % 2 == lenI % 2) ? 1 : 0);\n                    int nextJ = lenI + (curJ - lenJ) - ((curJ != lenJ && lenJ % 2 == lenI % 2) ? 1 : 0);\n \n                    int cost = 1 + Math.max(nextI, nextJ);\n                    if (cost < bestCost) {\n                        bestCost = cost;\n                        bestI = lenI;\n                        bestJ = lenJ;\n                    }\n                }\n            }\n \n            List<Integer> ans = new ArrayList<>();\n            makeSwap(ans, compressedS, compressedT, bestI, bestJ);\n \n            int nextI = compressedS.size(), nextJ = compressedT.size();\n \n            int prefixA = 0, prefixB = 0;\n            for (int i = 0; i < Math.max(nextI, nextJ) - 1; i++) {\n                if (i % 2 == 0) {\n                    prefixA += i >= compressedS.size() ? 0 : compressedS.get(i).count;\n                    prefixB += i >= compressedT.size() ? 0 : compressedT.get(i).count;\n                    ans.add(prefixA - 1);\n                    ans.add(prefixB - 1);\n                } else {\n                    prefixA += i >= compressedT.size() ? 0 : compressedT.get(i).count;\n                    prefixB += i >= compressedS.size() ? 0 : compressedS.get(i).count;\n                    ans.add(prefixB - 1);\n                    ans.add(prefixA - 1);\n                }\n            }\n \n            return ans;\n        }\n \n        private List<Pair> compress(String s) {\n            List<Pair> result = new ArrayList<>();\n            for (int i = 0; i < s.length(); ) {\n                int j = i;\n                while (j < s.length() && s.charAt(i) == s.charAt(j)) {\n                    j++;\n                }\n                result.add(new Pair(s.charAt(i), j - i));\n                i = j;\n//                System.err.println(result);\n            }\n            return result;\n        }\n \n        class Pair {\n            char ch;\n            int count;\n \n            public Pair(char ch, int count) {\n                this.ch = ch;\n                this.count = count;\n            }\n \n            @Override\n            public String toString() {\n                return \"Pair{\" +\n                        \"ch=\" + ch +\n                        \", count=\" + count +\n                        '}';\n            }\n        }\n \n    }\n \n    static class FastScanner {\n        BufferedReader br;\n        StringTokenizer st;\n \n        public FastScanner(InputStream in) {\n            br = new BufferedReader(new InputStreamReader(in));\n        }\n \n        public String next() {\n            while (st == null || !st.hasMoreElements()) {\n                String line = null;\n                try {\n                    line = br.readLine();\n                } catch (IOException e) {\n                }\n                st = new StringTokenizer(line);\n            }\n            return st.nextToken();\n        }\n \n    }\n}\n ",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1012",
    "index": "E",
    "title": "Cycle sort",
    "statement": "You are given an array of $n$ positive integers $a_1, a_2, \\dots, a_n$. You can perform the following operation any number of times: select several distinct indices $i_1, i_2, \\dots, i_k$ ($1 \\le i_j \\le n$) and move the number standing at the position $i_1$ to the position $i_2$, the number at the position $i_2$ to the position $i_3$, ..., the number at the position $i_k$ to the position $i_1$. In other words, the operation cyclically shifts elements: $i_1 \\to i_2 \\to \\ldots i_k \\to i_1$.\n\nFor example, if you have $n=4$, an array $a_1=10, a_2=20, a_3=30, a_4=40$, and you choose three indices $i_1=2$, $i_2=1$, $i_3=4$, then the resulting array would become $a_1=20, a_2=40, a_3=30, a_4=10$.\n\nYour goal is to make the array sorted in non-decreasing order with the minimum number of operations. The additional constraint is that the sum of cycle lengths over all operations should be less than or equal to a number $s$. If it's impossible to sort the array while satisfying that constraint, your solution should report that as well.",
    "tutorial": "Let's solve an array if $a$ is permutation and the sum of cycle sizes is unlimited. It's known that each permutation is composition of some non-intersecting cycles. If permutation is sorted answer is $0$. If permutation is $1$ cycle and some fixed indexes answer is $1$, you should take this cycle to get this answer. If permutation is composition of $\\geq 2$ cycles answer should be $\\geq 2$, because it's impossible to use $1$ cycle. In this case it's possible to make the answer with $2$ cycles. Let's define inversed permutation for our permutation as composition of this cycles $(p_{{1}{1}} \\to p_{{1}{2}} \\to \\dots \\to p_{{1}{k_1}} \\to p_{{1}{1}}), \\dots, (p_{{m}{1}} \\to p_{{m}{2}} \\to \\dots \\to p_{{m}{k_m}} \\to p_{{m}{1}})$ (all cycles, except cycles with length $1$). We can sort permutations using this $2$ cycles: $(p_{{1}{1}} \\to p_{{1}{2}} \\to \\dots \\to p_{{1}{k_1}} \\to p_{{2}{1}} \\to \\dots \\to p_{{m}{1}} \\to p_{{m}{2}} \\to \\dots \\to p_{{m}{k_m}} \\to p_{{1}{1}})$ (all cycles, written in a row) and $(p_{{m}{1}} \\to p_{{m-1}{1}} \\to \\dots p_{{1}{1}} \\to p_{{m}{1}})$ (first elements of cycles in inversed order). This solution used sum of cycle sizes $t+m$, there $t$ - number of non-fixed elements and $m$ - number of cycles with size $1$. Now let's solve problem for permutation, if we can use sum of cycle sizes $\\leq s$. Each solution should use sum of cycle sizes $\\geq t$, because we should shift each non-fixed element. So if $s < t$ answer is $-1$. Let's call each cycle from $m$ cycles bad, if each of it's element shifted exactly $1$ time in the answer. It can be proved, that each bad cycle should be used in the answer. Let's define $x$ as number of bad cycles and $y$ number of other cycles. So $x+y=m$. Sum of cycles in the answer $\\geq t+y$. So, $t+y \\leq s$ ==> $y \\leq s-t$ ==> $x=m-y \\geq m+t-s$. Number of cycles in the answer $\\geq x + min(y, 2)$. It's true, because each of $x$ bad cycles are in answer and other $y$ cycles can be sorted using $\\geq min(y, 2)$ cycles. We should take $x$ as maximal as possible, because if we increase $x$ by $1$ sum $min(y, 2) + x$ won't increase. Minimal $x$, that we can use is $max(0, m+t-s)$. So we get $y=m-max(0,m+t-s)=m+min(s-t-m, 0)=min(s-t, 0)=s-t$ (because $s \\geq t$). So answer in this case if $max(0, m+t-s)+min(s-t, 2)$. We can build it, if we use $x=max(0, m+t-s)$ any of $m$ cycles, and for other $y=s-t$ cycles do same construction as in previous case. Let's solve problem for array. Let's define $b$ as sorted array $a$ and $t$ as count of $1 \\leq i \\leq n$, such that $a_i \\neq b_i$. Our solution will sort some permutation $p$, such that $a_{p_i} = b_i$, for all $i$. Answer for permutation is $max(0, m+t-s)+min(s-t, 2)$. In this formula $s$ and $t$ fixed. So to minimize the answer we should minimize $m$. So we should sort array using array with as minumal as possible number of cycles. To do it let's build directed graph: vertexes is number in array, let's add edge from $a_i$ to $b_i$ for all $i$, such that $a_i \\neq b_i$. It's easy to see, that we should take euler cycle in each component of this graph and build permutation with this cycles to make number of cycles in permutation as minimal as possible. To code this solution without building graph let's take first any sorting permutation. After that, we can merge cycles. If $a_i = a_j$ and $i$ and $j$ in different cycles of permutation, we can merge this cycles using $swap(p_i, p_j)$. So let's merge all possible cycles using DSU for components. Time complexity: $O(n * log(n))$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int M = 2e5 + 239;\n \nint n, s, a[M], p[M];\npair<int, int> b[M];\n \nint parent[M], r[M];\n \ninline void init()\n{\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tparent[i] = i;\n\t\tr[i] = 0;\n\t}\n}\n\t\ninline int find_set(int p)\n{\n\tif (parent[p] == p) return p;\n\treturn (parent[p] = find_set(parent[p]));\n}\n \ninline void merge_set(int i, int j)\n{\n\ti = find_set(i);\n\tj = find_set(j);\n\tif (i == j) return;\n\tif (r[i] > r[j]) swap(i, j);\n\tif (r[i] == r[j]) r[j]++;\n\tparent[i] = j;\n}\n \ninline bool is_connect(int i, int j)\n{\n\treturn (find_set(i) == find_set(j));\n}\n \nint t;\nbool used[M];\nvector<int> c[M];\n \nvoid dfs(int x)\n{                         \n\tused[x] = true;\n\tc[t].push_back(x);\n\tif (!used[p[x]]) dfs(p[x]);\t\n}\n \nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin >> n >> s;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tcin >> a[i];\n\t\tb[i] = make_pair(a[i], i);\n\t}\n\tsort(b, b + n);\n\tfor (int i = 0; i < n; i++) p[b[i].second] = i;\n\tfor (int i = 0; i < n; i++)\n\t\tif (a[i] == b[i].first && p[i] != i)\n\t\t{                                  \n\t\t\tp[b[i].second] = p[i];\n\t\t\tb[p[i]].second = b[i].second;\n\t\t\tp[i] = i;\n\t\t\tb[i].second = i;\n\t\t}              \n\tinit();\n\tfor (int i = 0; i < n; i++) merge_set(p[i], i);\n\tint ls = -1;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tif (p[b[i].second] == b[i].second) continue;\n\t\tif (ls >= 0 && a[ls] == a[b[i].second])\n\t\t{\n\t\t\tint x = ls;\n\t\t\tint y = b[i].second;\n\t\t\tif (is_connect(x, y)) continue;\n\t\t\tmerge_set(x, y);\n\t\t\tswap(p[x], p[y]);\t\t\n\t\t}\n\t\tls = b[i].second;\n\t}\n\tt = 0;\n\tfor (int i = 0; i < n; i++)\n\t\tif (!used[i] && p[i] != i)\n\t\t{\n\t\t\tdfs(i);\n\t\t\tt++;\n\t\t}    \n\tint kol = 0;\n\tfor (int i = 0; i < t; i++)\n\t\tkol += (int)c[i].size();\n\tif (kol > s)\n\t{\n\t\tcout << \"-1\";\n\t\treturn 0;\n\t}\n\ts -= kol; \n\ts = min(s, t);\n\tif (s <= 1)\n\t{\n\t\tcout << t << \"\\n\";\n\t\tfor (int i = 0; i < t; i++)\n\t\t{\n\t\t\tcout << c[i].size() << \"\\n\";\n\t\t\tfor (int x : c[i])\n\t\t\t\tcout << (x + 1) << \" \";\n\t\t\tcout << \"\\n\";\n\t\t}\n\t\treturn 0;\n\t}\n\tcout << (t - s + 2) << \"\\n\";\n\tfor (int i = 0; i < t - s; i++)\n\t{\n\t\tcout << c[i + s].size() << \"\\n\";\n\t\tfor (int x : c[i + s])\n\t\t\tcout << (x + 1) << \" \";\n\t\tcout << \"\\n\";\n\t\tkol -= (int)c[i + s].size();\t\t\n\t}   \n\tcout << kol << \"\\n\";\n\tfor (int i = 0; i < s; i++)\n\t\tfor (int x : c[i])\n\t\t\tcout << (x + 1) << \" \"; \n\tcout << \"\\n\";\n\tcout << s << \"\\n\";\n\tfor (int i = s - 1; i >= 0; i--)\n\t\tcout << (c[i][0] + 1) << \" \";\n\tcout << \"\\n\";\n\treturn 0;\n}",
    "tags": [
      "dsu",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1012",
    "index": "F",
    "title": "Passports",
    "statement": "Gleb is a famous competitive programming teacher from Innopolis. He is planning a trip to $N$ programming camps in the nearest future. Each camp will be held in a different country. For each of them, Gleb needs to apply for a visa.\n\nFor each of these trips Gleb knows three integers: the number of the first day of the trip $s_{i}$, the length of the trip in days $len_{i}$, and the number of days $t_{i}$ this country's consulate will take to process a visa application and stick a visa in a passport. Gleb has $P$ ($1 ≤ P ≤ 2$) valid passports and is able to decide which visa he wants to put in which passport.\n\nFor each trip, Gleb will have a flight to that country early in the morning of the day $s_{i}$ and will return back late in the evening of the day $s_{i} + len_{i} - 1$.\n\nTo apply for a visa on the day $d$, Gleb needs to be in Innopolis in the middle of this day. So he can't apply for a visa while he is on a trip, including the first and the last days. If a trip starts the next day after the end of the other one, Gleb can't apply for a visa between them as well. The earliest Gleb can apply for a visa is day 1.\n\nAfter applying for a visa of country $i$ on day $d$, Gleb will get his passport back in the middle of the day $d + t_{i}$. Consulates use delivery services, so Gleb can get his passport back even if he is not in Innopolis on this day. Gleb can apply for another visa on the same day he received his passport back, if he is in Innopolis this day.\n\nGleb will not be able to start his trip on day $s_{i}$ if he doesn't has a passport with a visa for the corresponding country in the morning of day $s_{i}$. In particular, the passport should not be in another country's consulate for visa processing.\n\nHelp Gleb to decide which visas he needs to receive in which passport, and when he should apply for each visa.",
    "tutorial": "Let's solve the $P = 1$ case first. We'll use dynamic programming on subsets. Let's try to add visas to subset in order of application. Notice that if we only have one passport, every visa processing segment should lie between some two consecutive trips. For convenience, let's find all these segments beforehand. Define $dp[A]$ as the minimum day, before which all visas from set $A$ can be acquired. Try all possible $i$ as a visa which Gleb will apply for next. Now we have to find minimum possible day of application $d$, such that $d  \\ge  dp[A]$, segment $[d, d + t_{i}]$ does not intersect with any trip, and $d + t_{i} < s_{i}$. Such $d$ can be found in $O(n)$ by a linear search over precalculated free segment. Relax the value of $d p[A\\cup\\{i\\}]$ with $d + t_{i}$. If $dp[{1..n}] < +  \\infty $ then there is a solution that can be restored using standard techniques. Total time complexity is $O(2^{n} n^{2})$, that can be too slow for $n = 22$. Let's generalize this solution for $P = 2$. Still, Gleb can apply for a visa only when he is in Innopolis. However, the last day of visa processing can be during some trip, but only if all trips between the day of visa application and the day of visa acquisition use another passport. We will slightly change the definition of $dp[A]$: now this value is equal to the minimum possible day, by which it's possible to finish processing all visas from set $A$ with one passport, assuming all trips not from $A$ use another passport. By this definition, calculation of DP transition is a little bit different: when trying to add visa $i$ we have to find minimum $d$, such that $d  \\ge  dp[A]$, during day $d$ Gleb is in Innopolis, and segment $[d, d + t_{i}]$ does not intersect with half-closed intervals $[s_{j}, s_{j} + len_{j})$ for all $j\\in A$. This can be implemented similarly to the first part in $O(n)$. Total running time is $O(2^{n} n^{2})$, that can pass system tests with some optimizations. We'll optimize the solution down to $O(2^{n} n)$. To do that, we process all transition from set $A$ in $O(n)$ total time. Sort all visas in order of increasing $t_{i}$. Then the optimal visa application day $d$ will be increasing if visa processing time $t_{i}$ increases. Now we can apply two pointers technique to get $O(n)$ total processing time for one set and $O(2^{n} n)$ for all sets. After calculating $dp[A]$ for all subsets, we have to try all partitions of ${1..n}$ into two sets $A$ and $B$ and check if both $A$ and $B$ can be done with one passport each. This is equivalent to $dp[A] < +  \\infty $. If there are two such sets that $dp[A] < +  \\infty $ and $dp[B] < +  \\infty $, then we have found the answer, otherwise there is no answer.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1013",
    "index": "A",
    "title": "Piles With Stones",
    "statement": "There is a beautiful garden of stones in Innopolis.\n\nIts most beautiful place is the $n$ piles with stones numbered from $1$ to $n$.\n\nEJOI participants have visited this place twice.\n\nWhen they first visited it, the number of stones in piles was $x_1, x_2, \\ldots, x_n$, correspondingly. One of the participants wrote down this sequence in a notebook.\n\nThey visited it again the following day, and the number of stones in piles was equal to $y_1, y_2, \\ldots, y_n$. One of the participants also wrote it down in a notebook.\n\nIt is well known that every member of the EJOI jury during the night either sits in the room $108$ or comes to the place with stones. Each jury member who comes there either takes one stone for himself or moves one stone from one pile to another. We can assume that there is an unlimited number of jury members. No one except the jury goes to the place with stones at night.\n\nParticipants want to know whether their notes can be correct or they are sure to have made a mistake.",
    "tutorial": "It can be simply showed that the answer is <<Yes>> if and only if the sum in the first visit is not less than the sum in the second visit.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1013",
    "index": "B",
    "title": "And",
    "statement": "There is an array with $n$ elements $a_{1}, a_{2}, ..., a_{n}$ and the number $x$.\n\nIn one operation you can select some $i$ ($1 ≤ i ≤ n$) and replace element $a_{i}$ with $a_{i} & x$, where $&$ denotes the bitwise and operation.\n\nYou want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices $i ≠ j$ such that $a_{i} = a_{j}$. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.",
    "tutorial": "Clearly, if it is possible then there are no more than $2$ operations needed. So we basically need to distinguish $4$ outcomes - $- 1$, $0$, $1$ and $2$. The answer is zero if there are already equal elements in the array. To check if the answer is -1 we can apply the operation to each element of the array. If all elements are still distinct, then it couldn't be helped. To check if the answer is one we can bruteforce the element $a$ to apply the operation to, and if this operation changes this element, we can check if there is an $a & x$ element in the array. In all other cases answer is two.",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1015",
    "index": "A",
    "title": "Points in Segments",
    "statement": "You are given a set of $n$ segments on the axis $Ox$, each segment has integer endpoints between $1$ and $m$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $l_i$ and $r_i$ ($1 \\le l_i \\le r_i \\le m$) — coordinates of the left and of the right endpoints.\n\nConsider all integer points between $1$ and $m$ inclusive. Your task is to print all such points that don't belong to any segment. The point $x$ belongs to the segment $[l; r]$ if and only if $l \\le x \\le r$.",
    "tutorial": "In this problem all you need is to check for each point from $1$ to $m$ if it cannot belongs to any segment. It can be done in $O(n \\cdot m)$ by two nested loops or in $O(n + m)$ by easy prefix sums calculation. Both solutions are below.",
    "code": "n, m = map(int, input().split())\nseg = [list(map(int, input().split())) for i in range(n)]\ndef bad(x):\n\tfor i in range(n):\n\t\tif (seg[i][0] <= x and x <= seg[i][1]): return False\n\treturn True\nans = list(filter(bad, [i for i in range(1, m + 1)]))\nprint(len(ans))\nprint(' '.join([str(x) for x in ans]))",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1015",
    "index": "B",
    "title": "Obtaining the String",
    "statement": "You are given two strings $s$ and $t$. Both strings have length $n$ and consist of lowercase Latin letters. The characters in the strings are numbered from $1$ to $n$.\n\nYou can successively perform the following move any number of times (possibly, zero):\n\n- swap any two adjacent (neighboring) characters of $s$ (i.e. for any $i = \\{1, 2, \\dots, n - 1\\}$ you can swap $s_i$ and $s_{i + 1})$.\n\nYou can't apply a move to the string $t$. The moves are applied to the string $s$ one after another.\n\nYour task is to obtain the string $t$ from the string $s$. Find any way to do it with at most $10^4$ such moves.\n\nYou do not have to minimize the number of moves, just find any sequence of moves of length $10^4$ or less to transform $s$ into $t$.",
    "tutorial": "This problem can be solved using the next greedy approach: let's iterate over all $i$ from $1$ to $n$. If $s_i = t_i$, go further. Otherwise let's find any position $j > i$ such that $s_j = t_i$ and move the character from the position $j$ to the position $i$. If there is no such position in $s$, the answer is \"-1\". Upper bound on time complexity (and the size of the answer) of this solution is $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s, t;\n\tcin >> n >> s >> t;\n\t\n\tvector<int> ans;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (s[i] == t[i]) continue;\n\t\tint pos = -1;\n\t\tfor (int j = i + 1; j < n; ++j) {\n\t\t\tif (s[j] == t[i]) {\n\t\t\t        pos = j;\n\t\t\t        break;\n\t\t\t}\n\t\t}\n\t\tif (pos == -1) {\n\t\t\tcout << -1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tfor (int j = pos - 1; j >= i; --j) {\n\t\t\tswap(s[j], s[j + 1]);\n\t\t\tans.push_back(j);\n\t\t}\n\t}\n\t\n\tassert(s == t);\n\t\n\tcout << ans.size() << endl;\n\tfor (auto it : ans) cout << it + 1 << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1015",
    "index": "C",
    "title": "Songs Compression",
    "statement": "Ivan has $n$ songs on his phone. The size of the $i$-th song is $a_i$ bytes. Ivan also has a flash drive which can hold at most $m$ bytes in total. Initially, his flash drive is empty.\n\nIvan wants to copy all $n$ songs to the flash drive. He can compress the songs. If he compresses the $i$-th song, the size of the $i$-th song reduces from $a_i$ to $b_i$ bytes ($b_i < a_i$).\n\nIvan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most $m$. He can compress any subset of the songs (not necessarily contiguous).\n\nIvan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to $m$).\n\nIf it is impossible to copy all the songs (even if Ivan compresses all the songs), print \"-1\". Otherwise print the minimum number of songs Ivan needs to compress.",
    "tutorial": "If we will no compress songs, the sum of the sizes will be equal $\\sum\\limits_{i = 1}^{n} a_i$. Let it be $sum$. Now, if we will compress the $j$-th song, how do $sum$ will change? It will decrease by $a_j - b_j$. This suggests that the optimal way to compress the songs is the compress it in non-increasing order of $a_j - b_j$. Let's create the array $d$ of size $n$, where $d_j = a_j - b_j$. Let's sort it in non-increasing order, and then iterate over all $j$ from $1$ to $n$. If at the current step $sum \\le m$, we print $j - 1$ and terminate the program. Otherwise we set $sum := sum - d_j$. After all we have to check again if $sum \\le m$ then print $n$ otherwise print \"-1\". Time complexity is $O(n \\log n)$ because of sorting.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tvector<pair<int, int>> a(n);\n\tlong long sum = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i].first >> a[i].second;\n\t\tsum += a[i].first;\n\t}\n\t\n\tsort(a.begin(), a.end(), [&](pair<int, int> a, pair<int, int> b) { return a.first - a.second > b.first - b.second; });\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (sum <= m) {\n\t\t\tcout << i << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tsum -= a[i].first - a[i].second;\n\t}\n\t\n\tif (sum <= m)\n\t\tcout << n << endl;\n\telse\n\t\tcout << -1 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1015",
    "index": "D",
    "title": "Walking Between Houses",
    "statement": "There are $n$ houses in a row. They are numbered from $1$ to $n$ in order from left to right. Initially you are in the house $1$.\n\nYou have to perform $k$ moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house $x$ to the house $y$, the total distance you walked increases by $|x-y|$ units of distance, where $|a|$ is the absolute value of $a$. It is possible to visit the same house multiple times (but you can't visit the same house in sequence).\n\nYour goal is to walk exactly $s$ units of distance in total.\n\nIf it is impossible, print \"NO\". Otherwise print \"YES\" and any of the ways to do that. Remember that you should do exactly $k$ moves.",
    "tutorial": "The solution for this problem is very simple: at first, if $k > s$ or $k \\cdot (n - 1) < s$ the answer is \"NO\". Otherwise let's do the following thing $k$ times: let $dist$ be $min(n - 1, s - k + 1)$ (we have to greedily decrease the remaining distance but we also should remember about the number of moves which we need to perform). We have to walk to any possible house which is located at distance $dist$ from the current house (also don't forget to subtract $dist$ from $s$). The proof of the fact that we can always walk to the house at distance $dist$ is very simple: one of the possible answers (which is obtained by the algorithm above) will looks like several moves of distance $n-1$, (possibly) one move of random distance less than $n-1$ and several moves of distance $1$. The first part of the answer can be obtained if we are stay near the leftmost or the rightmost house, second and third parts always can be obtained because distances we will walk in every of such moves is less than $n-1$. Time complexity is $O(k)$.",
    "code": "def step(cur, x):\n    if(cur - x > 0):\n        return cur - x\n    else:\n        return cur + x\n\n\n\nn, k, s = map(int, input().split())\ncur = 1\n\nif(k > s or k * (n - 1) < s):\n    print('NO')\nelse:\n    print('YES')\n    while(k > 0):\n        l = min(n - 1, s - (k - 1))\n        cur = step(cur, l)\n        print(cur, end = ' ')\n        s -= l\n        k -= 1",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1015",
    "index": "E1",
    "title": "Stars Drawing (Easy Edition)",
    "statement": "A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $0$ are not allowed).\n\nLet's consider empty cells are denoted by '.', then the following figures are stars:\n\n\\begin{center}\n{\\small The leftmost figure is a star of size $1$, the middle figure is a star of size $2$ and the rightmost figure is a star of size $3$.}\n\\end{center}\n\nYou are given a rectangular grid of size $n \\times m$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $1$ to $n$, columns are numbered from $1$ to $m$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $n \\cdot m$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.\n\nIn this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $n \\cdot m$ stars.",
    "tutorial": "Since we are almost unlimited in the number of stars in the answer, the following solution will works. We iterate over all possible stars centers and try to extend rays of the current star as large as possible. It can be done by the simple iterating and checking in $O(n)$. If the size of the current star is non-zero, let's add it to the answer. It is obvious that the number of stars in such answer will not exceed $n \\cdot m$. Then let's try to draw all these stars on the empty grid. Drawing of each star is also can be done in $O(n)$. If after drawing our grid equals to the input grid, the answer is \"YES\" and our set of stars is the correct answer. Otherwise the answer is \"NO\". Time complexity: $O(n^3)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nconst int dx[] = {1, 0, -1,  0};\nconst int dy[] = {0, 1,  0, -1};\nconst int N = 1001;\n\nint n, m;\nvector<string> f;\nint d[N][N][4];\nint r[N][N], a[N][N], b[N][N];\n\nint getd(int i, int j, int k) {\n    int dxk = dx[k];\n    int dyk = dy[k];\n    int result = 0;\n    while (i >= 0 && i < n && j >= 0 && j < m && f[i][j] == '*')\n        result++, i += dxk, j += dyk;\n    return result;\n}\n\nint main() {\n    cin >> n >> m;\n    f = vector<string>(n);\n    forn(i, n)\n        cin >> f[i];\n    \n    memset(d, -1, sizeof(d));\n    int result = 0;\n    for (int i = 1; i + 1 < n; i++)\n        for (int j = 1; j + 1 < m; j++)\n            if (f[i][j] == '*') {\n                bool around = true;\n                forn(k, 4)\n                    around = around && (f[i + dx[k]][j + dy[k]] == '*');\n                if (around) {\n                    r[i][j] = INT_MAX;\n                    forn(k, 4)\n                        r[i][j] = min(r[i][j], getd(i, j, k) - 1);\n                    result++;\n                    a[i][j - r[i][j]] = max(a[i][j - r[i][j]], 2 * r[i][j] + 1);\n                    b[i - r[i][j]][j] = max(b[i - r[i][j]][j], 2 * r[i][j] + 1);\n                }\n            }\n\n    vector<string> g(n, string(m, '.'));\n    forn(i, n) {\n        int v = 0;\n        forn(j, m) {\n            v = max(v - 1, a[i][j]);\n            if (v > 0)\n                g[i][j] = '*';\n        }\n    }\n    forn(j, m) {\n        int v = 0;\n        forn(i, n) {\n            v = max(v - 1, b[i][j]);\n            if (v > 0)\n                g[i][j] = '*';\n        }\n    }\n    \n    if (f == g) {\n        cout << result << endl;\n        forn(i, n)\n            forn(j, m)\n                if (r[i][j] > 0)\n                    cout << i + 1 << \" \" << j + 1 << \" \" << r[i][j] << endl;\n    } else\n        cout << -1 << endl;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1015",
    "index": "E2",
    "title": "Stars Drawing (Hard Edition)",
    "statement": "A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $0$ are not allowed).\n\nLet's consider empty cells are denoted by '.', then the following figures are stars:\n\n\\begin{center}\n{\\small The leftmost figure is a star of size $1$, the middle figure is a star of size $2$ and the rightmost figure is a star of size $3$.}\n\\end{center}\n\nYou are given a rectangular grid of size $n \\times m$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $1$ to $n$, columns are numbered from $1$ to $m$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $n \\cdot m$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.\n\nIn this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $n \\cdot m$ stars.",
    "tutorial": "I am sorry that some $O(n^3)$ solutions pass tests in this problem also. I was supposed to increase constraints or decrease time limit. The general idea of this problem is the same as in the previous problem. But now we should do all what we were doing earlier faster. The solution is divided by two parts. The first part. Let's calculate four matrices of size $n \\times m$ - $up$, $down$, $left$ and $right$. $up_{i, j}$ will denote the distance to the nearest dot character to the top from the current position. The same, $down_{i, j}$ will denote the distance to the nearest dot character to the bottom from the current position, $left_{i, j}$ - to the left and $right_{i, j}$ - to the right. We can calculate all these matrices in $O(n^2)$ using easy dynamic programming. If we will iterate over all possible $i$ from $1$ to $n$ and $j$ from $1$ to $m$, we can easy see the next: if the current character is dot, then $up_{i, j} = left_{i, j} = 0$. Otherwise if $i > 1$ then $up_{i, j} = up_{i - 1, j}$, and if $j > 1$ then $left_{i, j} = left_{i, j - 1}$. Rest two matrices can be calculated the as well as these two matrices but we should iterate over all $i$ from $n$ to $1$ and $j$ from $m$ to $1$. So, this part of the solution works in $O(n^2)$. After calculating all these matrices the maximum possible length of rays of the star with center in position $(i, j)$ is $min(up_{i, j}, down_{i, j}, left_{i, j}, right_{i, j}) - 1$. The second part is to draw all stars in $O(n^2)$. Let's calculate another two matrices of size $n \\times m$ - $h$ and $v$. Let's iterate over all stars in our answer. Let the center of the current star is $(i, j)$ and its size is $s$. Let's increase $h_{i, j - s}$ by one and decrease $h_{i, j + s + 1}$ by one (if $j + s + 1 \\le m$). The same with the matrix $v$. Increase $v_{i - s, j}$ and decrease $v_{i + s + 1, j}$ (if $i + s + 1 \\le n$). Then let's iterate over all possible $i$ from $1$ to $n$ and $j$ from $1$ to $m$. If $i > 1$ then set $v_{i, j} := v_{i, j} + v_{i - 1, j}$ and if $j > 1$ set $h_{i, j} := h_{i, j} + h_{i, j - 1}$. How to know that the character at the position $(i, j)$ is asterisk character or dot character? If either $h_{i, j}$ or $v_{i, j}$ greater than zero, then the character at the position $(i, j)$ in our matrix will be the asterisk character. Otherwise it is the dot character. This part works also in $O(n^2)$. Time complexity of the solution: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nvector<string> s;\n\nvector<string> draw(const vector<pair<pair<int, int>, int>> &r) {\n\tvector<string> f(n, string(m, '.'));\n\tvector<vector<int>> h(n, vector<int>(m));\n\tvector<vector<int>> v(n, vector<int>(m));\n\tfor (auto it : r) {\n\t\tint x = it.first.first;\n\t\tint y = it.first.second;\n\t\tint len = it.second;\n\t\t++v[x - len][y];\n\t\tif (x + len + 1 < n)\n\t\t\t--v[x + len + 1][y];\n\t\t++h[x][y - len];\n\t\tif (y + len + 1 < m)\n\t\t\t--h[x][y + len + 1];\t\n\t}\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tif (i > 0) v[i][j] += v[i - 1][j];\n\t\t\tif (j > 0) h[i][j] += h[i][j - 1];\n\t\t\tif (v[i][j] > 0 || h[i][j] > 0)\n\t\t\t\tf[i][j] = '*';\n\t\t}\n\t}\n\treturn f;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m;\n\ts = vector<string>(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> s[i];\n\t}\n\t\n\tvector<vector<int>> l(n, vector<int>(m));\n\tvector<vector<int>> r(n, vector<int>(m));\n\tvector<vector<int>> u(n, vector<int>(m));\n\tvector<vector<int>> d(n, vector<int>(m));\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tif (i > 0) {\n\t\t\t\tif (s[i][j] != '.')\n\t\t\t\t\tu[i][j] = u[i - 1][j] + 1;\n\t\t\t} else {\n\t\t\t\tu[i][j] = s[i][j] != '.';\n\t\t\t}\n\t\t\tif (j > 0) {\n\t\t\t\tif (s[i][j] != '.')\n\t\t\t\t\tl[i][j] = l[i][j - 1] + 1;\n\t\t\t} else {\n\t\t\t\tl[i][j] = s[i][j] != '.';\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tfor (int j = m - 1; j >= 0; --j) {\n\t\t\tif (i < n - 1) {\n\t\t\t\tif (s[i][j] != '.')\n\t\t\t\t\td[i][j] = d[i + 1][j] + 1;\n\t\t\t} else {\n\t\t\t\td[i][j] = s[i][j] != '.';\n\t\t\t}\n\t\t\tif (j < m - 1) {\n\t\t\t\tif (s[i][j] != '.')\n\t\t\t\t\tr[i][j] = r[i][j + 1] + 1;\n\t\t\t} else {\n\t\t\t\tr[i][j] = s[i][j] != '.';\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvector<pair<pair<int, int>, int>> ans;\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tif (s[i][j] == '*') {\n\t\t\t\tint len = min(min(u[i][j], l[i][j]), min(d[i][j], r[i][j])) - 1;\n\t\t\t\tif (len != 0) {\n\t\t\t\t\tans.push_back(make_pair(make_pair(i, j), len));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (draw(ans) != s) {\n\t\tcout << -1 << endl;\n\t} else {\n\t\tcout << ans.size() << endl;\n\t\tfor (auto it : ans) {\n\t\t\tcout << it.first.first + 1 << \" \" << it.first.second + 1 << \" \" << it.second << endl; \n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1015",
    "index": "F",
    "title": "Bracket Substring",
    "statement": "You are given a bracket sequence $s$ (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'.\n\nA regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\"), and \")(\", \"(\" and \")\" are not.\n\nYour problem is to calculate the number of regular bracket sequences of length $2n$ containing the given bracket sequence $s$ as a substring (consecutive sequence of characters) modulo $10^9+7$ ($1000000007$).",
    "tutorial": "At first, let's calculate the matrix $len$ of size $(n + 1) \\times 2$. Let $len_{i, j}$ will denote the maximum length of the prefix of $s$ which equals to the suffix of the prefix of $s$ of length $i$ with the additional character '(' if $j = 0$ and ')' otherwise. In other words, $len_{i, j}$ is denote which maximum length of the prefix of $s$ we can reach if now we have the prefix of $s$ of length $i$ and want to add the character '(' if $j = 0$ and ')' otherwise, and only one possible move is to remove characters from the beginning of this prefix with an additional character. This matrix can be easily calculated in $O(n^3)$ without any dynamic programming. It can be also calculated in $O(n)$ using prefix-function and dynamic programming. Now let's calculate the following dynamic programming $dp_{i, j, k, l}$. It means that now we have gained $i$ characters of the regular bracket sequence, the balance of this sequence is $j$, the last $k$ characters of the gained prefix is the prefix of $s$ of length $k$ and $l$ equals to $1$ if we obtain the full string $s$ at least once and $0$ otherwise. The stored value of the $dp_{i, j, k, l}$ is the number of ways to reach this state. Initially, $dp_{0, 0, 0, 0} = 1$, all other values equal $0$. The following recurrence works: try to add to the current prefix character '(' if the current balance is less than $n$, then we will move to the state $dp{i + 1, j + 1, len_{k, 0}, f~ |~ (len_{k, 0} = |s|)}$. $|s|$ is the length of $s$ and $|$ is OR operation (if at least one is true then the result is true). Let's add to the number of ways to reach the destination state the number of ways to reach the current state. The same with the character ')'. Try to add to the current prefix character ')' if the current balance is greater than $0$, then we will move to the state $dp{i + 1, j - 1, len_{k, 1}, f~ |~ (len_{k, 1} = |s|)}$. Also add to the number of ways to reach the destination state the number of ways to reach the current state. After calculating this dynamic programming, the answer is $\\sum\\limits_{i = 0}^{|s|} dp_{2n, 0, i, 1}$. Time complexity is $O(n^3)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 203;\nconst int MOD = 1e9 + 7;\n\nint n, ssz;\nstring s;\nint len[N][2];\nint dp[N][N][N][2];\n\nint calc(const string &t) {\n\tint tsz = t.size();\n\tfor (int i = tsz; i > 0; --i) {\n\t\tif (s.substr(0, i) == t.substr(tsz - i, i))\n\t\t\treturn i;\n\t}\n\treturn 0;\n}\n\nvoid add(int &a, int b) {\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> s;\n\tssz = s.size();\n\t\n\tif (s[0] == '(')\n\t\tlen[0][0] = 1;\n\telse\n\t\tlen[0][1] = 1;\n\t\n\tstring pref;\n\tfor (int i = 0; i < ssz; ++i) {\n\t\tpref += s[i];\n\t\tpref += '(';\n\t\tlen[i + 1][0] = calc(pref);\n\t\tpref.pop_back();\n\t\tpref += ')';\n\t\tlen[i + 1][1] = calc(pref);\n\t\tpref.pop_back();\n\t}\n\t\n\tdp[0][0][0][0] = 1;\n\tfor (int i = 0; i < 2 * n; ++i) {\n\t\tfor (int j = 0; j <= n; ++j) {\n\t\t\tfor (int pos = 0; pos <= ssz; ++pos) {\n\t\t\t\tfor (int f = 0; f < 2; ++f) {\n\t\t\t\t\tif (dp[i][j][pos][f] == 0) continue;\n\t\t\t\t\tif (j + 1 <= n)\n\t\t\t\t\t\tadd(dp[i + 1][j + 1][len[pos][0]][f | (len[pos][0] == ssz)], dp[i][j][pos][f]);\n\t\t\t\t\tif (j > 0)\n\t\t\t\t\t\tadd(dp[i + 1][j - 1][len[pos][1]][f | (len[pos][1] == ssz)], dp[i][j][pos][f]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\tfor (int i = 0; i <= ssz; ++i)\n\t\tadd(ans, dp[2 * n][0][i][1]);\n\t\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1016",
    "index": "A",
    "title": "Death Note",
    "statement": "You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: \"You have to write names in this notebook during $n$ consecutive days. During the $i$-th day you have to write exactly $a_i$ names.\". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).\n\nOf course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $m$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.\n\nNow you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $1$ to $n$.",
    "tutorial": "In this problem all we need is to maintain the variable $res$ which will represent the number of names written on the current page. Initially this number equals zero. The answer for the $i$-th day equals $\\lfloor\\frac{res + a_i}{m}\\rfloor$. This value represents the number of full pages we will write during the $i$-th day. After the answering we need to set $res := (res + a_i) \\% m$, where operation $x \\% y$ is taking $x$ modulo $y$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint n, m;\n\tcin >> n >> m;\n\t\n\tint r = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\t\n\t\tr += x;\n\t\tcout << r / m << ' ';\n\t\tr %= m;\n\t}\n\tcout << '\\n';\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1016",
    "index": "B",
    "title": "Segment Occurrences",
    "statement": "You are given two strings $s$ and $t$, both consisting only of lowercase Latin letters.\n\nThe substring $s[l..r]$ is the string which is obtained by taking characters $s_l, s_{l + 1}, \\dots, s_r$ without changing the order.\n\nEach of the occurrences of string $a$ in a string $b$ is a position $i$ ($1 \\le i \\le |b| - |a| + 1$) such that $b[i..i + |a| - 1] = a$ ($|a|$ is the length of string $a$).\n\nYou are asked $q$ queries: for the $i$-th query you are required to calculate the number of occurrences of string $t$ in a substring $s[l_i..r_i]$.",
    "tutorial": "Let's take a look at a naive approach: for each query $[l, r]$ you iterate over positions $i \\in [l, r - |m| + 1]$ and check if $s[i, i + |m| - 1] = t$. Okay, this is obviously $O(q \\cdot n \\cdot m)$. Now we notice that there are only $O(n)$ positions for $t$ to start from, we can calculate if there is an occurrence of $t$ starting in this position beforehand in $O(n \\cdot m)$. Thus, we transition to $O(q \\cdot n)$ solution. Finally, we calculate a partial sum array over this occurrence check array and answer each query in $O(1)$. Overall complexity: $O(n \\cdot m + q)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 1000 + 7;\n\nint pr[N];\nbool ok[N];\n\nint main() {\n\tint n, m, q;\n\tscanf(\"%d%d%d\", &n, &m, &q);\n\tstring s, t;\n\tstatic char buf[N];\n\tscanf(\"%s\", buf);\n\ts = buf;\n\tscanf(\"%s\", buf);\n\tt = buf;\n\t\n\tpr[0] = 0;\n\tforn(i, n - m + 1){\n\t\tbool fl = true;\n\t\tforn(j, m)\n\t\t\tif (s[i + j] != t[j])\n\t\t\t\tfl = false;\n\t\tok[i] = fl;\n\t\tpr[i + 1] = pr[i] + ok[i];\n\t}\n\tfor (int i = max(0, n - m + 1); i < n; ++i){\n\t\tpr[i + 1] = pr[i];\n\t}\n\t\n\tforn(i, q){\n\t\tint l, r;\n\t\tscanf(\"%d%d\", &l, &r);\n\t\t--l, r -= m - 1;\n\t\tprintf(\"%d\\n\", r >= l ? pr[r] - pr[l] : 0);\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1016",
    "index": "C",
    "title": "Vasya And The Mushrooms",
    "statement": "Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into $n$ consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.\n\nVasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells \\textbf{exactly once} and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of $0$. Note that Vasya doesn't need to return to the starting cell.\n\nHelp Vasya! Calculate the maximum total weight of mushrooms he can collect.",
    "tutorial": "A route visiting each cell exactly once can always be denoted as follows: several (possibly zero) first columns of the glade are visited in a zigzag pattern, then Vasya goes to the right until the end of the glade, makes one step up or down and goes left until he visits all remaining cells: There are $n - 1$ such routes. To calculate the weight of collected mushrooms quickly, we will precompute three arrays for the first row of the glade - $sum123, sum321$ and $sum111$. $sum123$ will be used to compute the weight of mushrooms collected when Vasya moves to the right until the last column of the glade, $sum321$ - when Vasya moves to the left from the last column, and $sum111$ - to handle the growth of mushrooms. $s u m123_{i}=\\sum_{k=i}^{n}a_{i}\\cdot k$ $s u m321_{i}=\\sum_{k=i}^{n}a_{i}\\cdot(n-k+1)$ $s u m11_{i}=\\sum_{k=i}^{n}a_{i}$ Also we have to compute the same arrays for the second row of the glade. Let's iterate on the number of columns Vasya will pass in a zigzag pattern and maintain the weight of mushrooms he will collect while doing so. Then we have to add the weight of the mushrooms Vasya will gather while moving to the right, and then - while moving to the left. The first can be handled by arrays $sum123$ and $sum111$, the second - by arrays $sum321$ and $sum111$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300 * 1000 + 9;\n\nint n;\nint a[2][N];\nlong long sum123[2][N];\nlong long sum321[2][N];\nlong long sum111[2][N];\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < 2; ++i)\n\t\tfor(int j = 0; j < n; ++j)\n\t\t\tscanf(\"%d\", &a[i][j]);\n\t\n\tfor(int i = 0; i < 2; ++i)\n\t\tfor(int j = n - 1; j >= 0; --j){\n\t\t\tsum123[i][j] = sum123[i][j + 1] + (j + 1) * 1LL * a[i][j];\n\t\t\tsum321[i][j] = sum321[i][j + 1] + (n - j) * 1LL * a[i][j];\n\t\t\tsum111[i][j] = sum111[i][j + 1] + a[i][j];\n\t\t}\n\t\t\n/*\tfor(int i = 0; i < 2; ++i)\n\t\tfor(int j = n - 1; j >= 0; --j){\n\t\t\tcout << i << ' ' << j << \" : \";\n\t\t\tcout << sum123[i][j] << \"  \" << sum321[i][j] << \"  \" << sum111[i][j] << endl;\n\t\t}\t\t\t*/\n\t\t\n\tlong long res = 0, sum = 0;\n\tfor(int i = 0, j = 0; j < n; ++j, i ^= 1){\n\t\tlong long nres = sum;\n\t\tnres += sum123[i][j] + j * 1LL * sum111[i][j];\n\t\tnres += sum321[i ^ 1][j] + (j + n) * 1LL * sum111[i ^ 1][j];\n\t\tres = max(res, nres);\n\t\t\n\t\tsum += a[i][j] * 1ll * (j + j + 1);\n\t\tsum += a[i ^ 1][j] * 1ll * (j + j + 2);\n\t}\n\t\n\tfor(int j = 0; j < n; ++j) res -= a[0][j] + a[1][j];\n\tprintf(\"%I64d\\n\", res);\n\t\n    return 0;\n}                             \t",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1016",
    "index": "D",
    "title": "Vasya And The Matrix",
    "statement": "Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!\n\nVasya knows that the matrix consists of $n$ rows and $m$ columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence $a_{1}, a_{2}, ..., a_{n}$ denotes the xor of elements in rows with indices $1$, $2$, ..., $n$, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence $b_{1}, b_{2}, ..., b_{m}$ denotes the xor of elements in columns with indices $1$, $2$, ..., $m$, respectively.\n\nHelp Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.",
    "tutorial": "If $a_{1}\\oplus a_{2}\\oplus\\cdot\\cdot\\cdot\\oplus a_{n}\\neq b_{1}\\oplus b_{2}\\oplus\\cdot\\cdot\\cdot\\oplus b_{m}$, then there is no suitable matrix. The operation $\\mathbb{C}$ means xor. Otherwise, we can always construct a suitable matrix by the following method: the first element of the first line will be equal to $a_{1}\\oplus b_{2}\\oplus b_{3}\\oplus\\cdot\\cdot\\Leftrightarrow b_{m}$. The second element of the first line is $b_{2}$, the third element is $b_{3}$, the last one is $b_{m}$. The first element of the second line will be $a_{2}$, the first element of the third line is $a_{3}$, the first element of the last line is $a_{n}$. The rest of the elements will be zero. It is not difficult to verify that the matrix obtained satisfies all the restrictions.",
    "code": "#include <bits/stdc++.h>\n#include \"testlib.h\"\n\nusing namespace std;\n\nconst int N = 109;\n\nint n, m;\nint a[N], b[N];\nint res[N][N];\n\nint main() {\n\tint cur = 0;\n\tcin >> n >> m;\n\tfor(int i = 0; i < n; ++i)\n\t\tcin >> a[i], cur ^= a[i];\n\tfor(int i = 0; i < m; ++i)\n\t\tcin >> b[i], cur ^= b[i];\n\t\n\tif(cur != 0){\n\t\tputs(\"NO\");\n\t\treturn 0;\n\t}\n\t\n\tputs(\"YES\");\n\tfor(int i = 1; i < m; ++i) \n\t\tcur ^= b[i];\n\tcur ^= a[0];\n\t\n\tcout << cur << ' ';\n\tfor(int i = 1; i < m; ++i)\n\t\tcout << b[i] << ' ';\n\tcout << endl;\n\tfor(int i = 1; i < n; ++i){\n\t\tcout << a[i] << ' ';\n\t\tfor(int j = 1; j < m; ++j)\n\t\t\tcout << 0 << ' ';\n\t\tcout << endl;\n\t}\n    return 0;\n}                             \t",
    "tags": [
      "constructive algorithms",
      "flows",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1016",
    "index": "E",
    "title": "Rest In The Shades",
    "statement": "There is a light source on the plane. This source is so small that it can be represented as point. The light source is moving from point $(a, s_y)$ to the $(b, s_y)$ $(s_y < 0)$ with speed equal to $1$ unit per second. The trajectory of this light source is a straight segment connecting these two points.\n\nThere is also a fence on $OX$ axis represented as $n$ segments $(l_i, r_i)$ (so the actual coordinates of endpoints of each segment are $(l_i, 0)$ and $(r_i, 0)$). The point $(x, y)$ is in the shade if segment connecting $(x,y)$ and the current position of the light source intersects or touches with any segment of the fence.\n\nYou are given $q$ points. For each point calculate total time of this point being in the shade, while the light source is moving from $(a, s_y)$ to the $(b, s_y)$.",
    "tutorial": "Let's calculate the answer for a fixed point $P$. If you project with respect of $P$ each segment of the fence to the line containing light source you can see that the answer is the length of intersection of fence projection with segment $(A, B)$ of the trajectory light source. Key idea is the fact that the length of each fence segment is multiplied by the same coefficient $k = \\frac{P_y + |s_y|}{P_y}$. On the other hand, fence segments whose projections lie inside $(A, B)$ form a subsegment in the array of segments, so its total length can be obtained with partial sums. And at most two fence segment are included in the answer partially, their positions can be calculated with lower_bound if you project points $A$ and $B$ on $OX$ axis. So now you can answer the query with $O(\\log{n})$ time (and quite small hidden constant) and resulting complexity is $O(n + q \\log{n})$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<li, li> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst double EPS = 1e-9;\n\nconst int N = 200 * 1000 + 555;\n\nli sy, a, b;\nint n, q;\npt s[N], p[N];\n\ninline bool read() {\n\tif(!(cin >> sy >> a >> b))\n\t\treturn false;\n\tassert(cin >> n);\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%lld%lld\", &s[i].x, &s[i].y) == 2);\n\tassert(cin >> q);\n\tfore(i, 0, q)\n\t\tassert(scanf(\"%lld%lld\", &p[i].x, &p[i].y) == 2);\n\treturn true;\n}\n\nint getGE(ld x) {\n\tfor(int pos = max(int(lower_bound(s, s + n, pt(li(x), -1)) - s) - 2, 0); pos < n; pos++)\n\t\tif(x <= s[pos].x)\n\t\t\treturn pos;\n\treturn n;\n}\n\nli ps[N];\n\nli getSum(int l, int r) {\n\tli ans = r > 0 ? ps[r - 1] : 0;\n\tans -= l > 0 ? ps[l - 1] : 0;\n\treturn ans;\n}\n\ninline void solve() {\n\tfore(i, 0, n) {\n\t\tps[i] = s[i].y - s[i].x;\n\t\tif(i > 0)\n\t\t\tps[i] += ps[i - 1];\n\t}\n\t\n\tfore(i, 0, q) {\n\t\tld lx = p[i].x + (a - p[i].x) * (ld(p[i].y) / (p[i].y - sy));\n\t\tld rx = p[i].x + (b - p[i].x) * (ld(p[i].y) / (p[i].y - sy));\n\t\t\n\t\tint posL = getGE(lx);\n\t\tint posR = getGE(rx) - 1;\n\t\t\n\t\tld sum = getSum(posL, posR);\n\t\tif(posL > 0)\n\t\t\tsum += max(ld(0.0), s[posL - 1].y - max((ld)s[posL - 1].x, lx));\n\t\tif(posR >= 0)\n\t\t\tsum += max(ld(0.0), min((ld)s[posR].y, rx) - s[posR].x);\n\t\t\n\t\tsum *= ld(p[i].y - sy) / p[i].y;\n\t\tprintf(\"%.15f\\n\", double(sum));\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1016",
    "index": "F",
    "title": "Road Projects",
    "statement": "There are $n$ cities in the country of Berland. Some of them are connected by bidirectional roads in such a way that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each road has its own length. Cities are numbered from $1$ to $n$.\n\nThe travelling time between some cities $v$ and $u$ is the total length of the roads on the shortest path from $v$ to $u$.\n\nThe two most important cities in Berland are cities $1$ and $n$.\n\nThe Berland Ministry of Transport decided to build a single new road to decrease the traffic between the most important cities. However, lots of people are used to the current travelling time between the most important cities, so the new road shouldn't change it too much.\n\nThe new road can only be built between such cities $v$ and $u$ that $v \\neq u$ and $v$ and $u$ aren't already connected by some road.\n\nThey came up with $m$ possible projects. Each project is just the length $x$ of the new road.\n\nPolycarp works as a head analyst at the Berland Ministry of Transport and it's his job to deal with all those $m$ projects. For the $i$-th project he is required to choose some cities $v$ and $u$ to build the new road of length $x_i$ between such that the travelling time between the most important cities is \\textbf{maximal possible}.\n\nUnfortunately, Polycarp is not a programmer and no analyst in the world is capable to process all projects using only pen and paper.\n\nThus, he asks you to help him to calculate the maximal possible travelling time between the most important cities for each project. Note that the choice of $v$ and $u$ can differ for different projects.",
    "tutorial": "The first solution (editorial by PikMike) Firtsly, we can notice that we get the most profit by placing the edge in a same position, no matter the query. Moreover, once you have calculated the minimum difference you can apply to the shortest path $dif_{min}$ by adding edge of the weight $0$, you can answer the queries in $O(1)$ each. Let the current shortest distance between $1$ and $n$ be $curd$. Then the answer to some query $x$ is $min(curd, curd - mind + x)$. Let's proceed to proofs of the following. Consider any of the optimal positions for the edge of weight $0$. Then weight $1$ will add $1$ to the answer in this position (if the path isn't $curd$ already but that is trivial). Let there be another position such that the answer in it is less than the current one. That means that the answer for weight $0$ in it is less by $1$ which is smaller than the first one we got, which leads to contradiction. The second fact can deduced from the first one. Then let me introduce the next bold statement. We root the tree with vertex $1$. Then if there exists such a vertex in that it's not an ancestor of vertex $n$ and the number of vertices in its subtree (inclusive) is greater than $1$ then $dif_{min} = 0$. That is simple: just put the edge between the parent of this vertex and any of vertices of the subtree, there always be such that the edge doesn't exist yet. That won't change the shortest path, no matter which $x$ it is. Then, we have a graph of the following kind: That is the simple path between $1$ and $n$ and some vetices on it have additional children leaves. Finally, let's proceed to the solution. We want to choose such a pair of vertices that the sum of edge on a path between them, which are also a part of the path between $1$ and $n$ plus the weights of the newly included to shortest path edges (if any) is minimal possible. Let's precalc $d_v$ - the sum of weights of edges from vertex $1$ to vertex $v$ and $p_v$ - parent of vertex $v$. Let $w(v, u)$ be the weight of an edge between $v$ and $u$. Then we end up with the four basic cases for these vertices $v$ and $u$ with $v$ having greater or equal number of edges on path to $1$ than $u$: each of the form (whether $v$ belongs to the simple path between $1$ and $n$, whether $u$ belongs to it). $u$ doesn't belong: the answer is $d_v + w(p_u, u) - d[p_u]$; $u$ belongs, $v$ doesn't: $d_u + w(p_v, v) - d[p_v]$; both belongs: $d_v - d_u$. Each of these formulas can be broken down to parts with exacly one of the vertices. Let's call them $pt_v$ and $pt_u$. That means minimizing the result is be the same as minimizing each of the parts. We run depth-first search on vertices which belong to a simple path between $1$ and $n$ inclusive. Maintain the minimum value of $pt_u$ you have already passed by. Try connecting each vertex with this $u$ and also parent of the parent of the current vertex using all the possible formulas and updating $dif_{min}$ with the resulting value. Finally, after the precalc is finished, asnwer the queries in $O(1)$ with $dif_{min}$. Overall complexity: $O(n + q)$. The second solution (editorial by BledDest) Let's denote the distance from vertex $1$ to vertex $x$ in the tree as $d_1(x)$. Similarly, denote the distance from $n$ to $x$ in the tree as $d_n(x)$. Suppose we try to add a new edge between vertices $x$ and $y$ with length $w$. Then two new paths from $1$ to $n$ are formed: one with length $d_1(x) + w + d_n(y)$, and another with length $d_1(y) + w + d_n(x)$. Then the new length of shortest path becomes $min(d_1(n), d_1(x) + w + d_n(y), d_1(y) + w + d_n(x))$. So if we find two non-adjacent vertices such that $min(d_1(x) + d_n(y), d_1(y) + d_n(x))$ is maximum possible, then it will always be optimal to add an edge between these two vertices. How can we find this pair of vertices? Firstly, let's suppose that $d_1(x) + d_n(y) \\le d_1(y) + d_n(x)$ - when we pick vertex $x$, we will try to pair it only with vertices $y$ corresponding to the aforementioned constraint. This can be done by sorting vertices by the value of $d_1(x) - d_n(x)$ and then for each vertex $x$ pairing it only with vertices that are later than $x$ in the sorted order. How do we find the best pair for $x$? The best pair could be just the vertex with maximum possible $d_n(y)$, but it is not allowed to connect a vertex with itself or its neighbour. To handle it, we may maintain a set of possible vertices $y$, delete all neighbours of $x$ from it, pick a vertex with maximum $d_n$, and then insert all neighbours of $x$ back into the set. This solution works in $O(n \\log n + q)$ time.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvector<vector<pair<int, int> > > g;\nvector<long long> d;\nvector<long long> d1;\nvector<long long> dn;\n\nint n, q;\n\nbool read()\n{\n\tscanf(\"%d %d\", &n, &q);\n\tg.resize(n);\n\td.resize(n);\n\tfor(int i = 0; i < n - 1; i++)\n\t{\n\t\tint x, y, w;\n\t\tscanf(\"%d %d %d\", &x, &y, &w);\n\t\t--x;\n\t\t--y;\n\t\tg[x].push_back(make_pair(y, w));\n\t\tg[y].push_back(make_pair(x, w));\n\t}\n\treturn true;\n}\n\nvoid dfs(int x, int p = -1, long long dist = 0)\n{\n\td[x] = dist;\n\tfor (auto e : g[x])\n\t\tif (p != e.first)\n\t\t\tdfs(e.first, x, e.second + dist);\n}\n\nvoid solve()\n{\n\tdfs(0);\n\td1 = d;\n\tdfs(n - 1);\n\tdn = d;\n\tset<pair<long long, int> > dists_n;\n\tvector<pair<long long, int> > order;\n\tfor(int i = 0; i < n; i++)\n\t    order.push_back(make_pair(d1[i] - dn[i], i));\n\tsort(order.begin(), order.end());\n\tfor(int i = 0; i < n; i++)\n\t    dists_n.insert(make_pair(dn[i], i));\n\tvector<int> pos(n);\n\tfor(int i = 0; i < n; i++)\n\t\tpos[order[i].second] = i;\n\tlong long T = (long long)(1e18);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint v = order[i].second;\n\t\tdists_n.erase(make_pair(dn[v], v));\n\t\tfor (auto e : g[v])\n\t\t\tif (pos[e.first] > pos[v])\n\t\t\t\tdists_n.erase(make_pair(dn[e.first], e.first));\n\t\tif (!dists_n.empty())\n\t\t\tT = min(T, d1[n - 1] - d1[v] - dists_n.rbegin()->first);\n\t\tfor (auto e : g[v])\n\t\t\tif (pos[e.first] > pos[v])\n\t\t\t\tdists_n.insert(make_pair(dn[e.first], e.first));\n\t}\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\tprintf(\"%lld\\n\", d1[n - 1] - max(0ll, T - x));\n\t}\n}\n\nint main()\n{\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\tif (read())\n\t{\n\t\tsolve();\n\t}\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1016",
    "index": "G",
    "title": "Appropriate Team",
    "statement": "Since next season are coming, you'd like to form a team from two or three participants. There are $n$ candidates, the $i$-th candidate has rank $a_i$. But you have weird requirements for your teammates: if you have rank $v$ and have chosen the $i$-th and $j$-th candidate, then $GCD(v, a_i) = X$ and $LCM(v, a_j) = Y$ must be met.\n\nYou are very experienced, so you can change your rank to any non-negative integer but $X$ and $Y$ are tied with your birthdate, so they are fixed.\n\nNow you want to know, how many are there pairs $(i, j)$ such that there exists an integer $v$ meeting the following constraints: $GCD(v, a_i) = X$ and $LCM(v, a_j) = Y$. It's possible that $i = j$ and you form a team of two.\n\n$GCD$ is the greatest common divisor of two number, $LCM$ — the least common multiple.",
    "tutorial": "At first, $X \\mid Y$ must be met (since $X \\mid v$ and $v \\mid Y$). Now let $Y = p_1^{py_1} p_2^{py_2} \\dots p_z^{py_z}$ and $X = p_1^{px_1} p_2^{px_2} \\dots p_z^{px_z}$. From now on let's consider only $p_k$ such that $px_k < py_k$. Now let's look at $a_i$: $X \\mid a_i$ must be met. Let $a_i = p_1^{pa_1} p_2^{pa_2} \\dots p_l^{pa_l} \\cdot a'$. Since $GCD(v, a_i) = X$, if $pa_k > px_k$ then $v$ must have $p_k$ to the power of $px_k$ in its factorization; otherwise power of $p_k$ can be any non-negative integer $\\ge px_k$. It leads us to the bitmask of restrictions $min_i$ ($min_i[k] = (pa_k > px_k)$) with size equal to the number of different prime divisors of $Y$. In the same way let's process $a_j$. Of course, $a_j \\mid Y$ and if $pa_k < py_k$ then $v$ must have $p_k$ to the power of $py_k$ in its factorization. This is another restriction bitmask $max_j$ ($max_j[k] = (pa_k < py_k)$). So, for any pair $(i, j)$ there exists $v$ if and only if $min_i\\ \\text{AND}\\ max_j = 0$. Since we look only at $p_k$ where $px_k < py_k$ then $v$ can't have power of $p_k$ equal to $px_k$ and $py_k$ at the same time. For any other $p$ it is enough to have power of $p$ in $v$ equal to the power of $p$ in $Y$ (even if it's equal to $0$). So, for each $max_j$ we need to know the number of $a_i$ such that $min_i$ is a submask of $\\text{NOT}\\ max_j$. So we just need to calculate sum of submasks for each mask; it can be done with $O(n\\cdot 2^n)$ or $O(3^n)$. Finally, how to factorize number $A$ up to $10^{18}$. Of course, Pollard algorithm helps, but there is another way, which works sometimes. Let's factorize $A$ with primes up to $10^6$. So after that if $A > 1$ there is only three cases: $A = p$, $A = p^2$ or $A = p \\cdot q$. $A = p^2$ is easy to check ($\\text{sqrtl}$ helps). Otherwise, just check $GCD$ with all $a_i$, $X$ and $Y$: if you have found $GCD \\neq 1$ and $GCD \\neq A$, then $A = p \\cdot q$ and you have found $p$. Otherwise you can assume that $A = p$, because this probable mistake doesn't break anything in this task. Result complexity is $O(A^{\\frac{1}{3}} + n \\log{A} + z \\cdot 2^z)$ where $z$ is the number of prime divisors of $Y$ $(z \\le 15)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<li, li> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nconst int N = 200 * 1000 + 555;\nint n; li x, y;\nli a[N];\n\ninline bool read() {\n\tif(!(cin >> n >> x >> y))\n\t\treturn false;\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%lld\", &a[i]) == 1);\n\treturn true;\n}\n\nli gcd(li a, li b) {\n\twhile(a > 0) {\n\t\tb %= a;\n\t\tswap(a, b);\n\t}\n\treturn b;\n}\n\nvector<pt> factorize(li v) {\n\tvector<pt> f;\n\tfor(li x = 2; x <= 1'000'000 && x * x <= v; x++) {\n\t\tint cnt = 0;\n\t\twhile(v % x == 0)\n\t\t\tv /= x, cnt++;\n\t\tif(cnt > 0)\n\t\t\tf.emplace_back(x, cnt);\n\t}\n\tif(v > 1) {\n\t\tfor(li s = max(1ll, (li)sqrtl(v) - 2); s * s <= v; s++)\n\t\t\tif(s * s == v) {\n\t\t\t\tf.emplace_back(s, 2);\n\t\t\t\tv = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif(v > 1) {\n\t\t\tvector<li> cnd(a, a + n);\n\t\t\tcnd.push_back(x);\n\t\t\tcnd.push_back(y);\n\t\t\t\n\t\t\tfor(li c : cnd) {\n\t\t\t\tli g = gcd(v, c);\n\t\t\t\tif(g != 1 && g != v) {\n\t\t\t\t\tli a = g, b = v / g;\n\t\t\t\t\tif(a > b)\n\t\t\t\t\t\tswap(a, b);\n\t\t\t\t\t\t\n\t\t\t\t\tf.emplace_back(a, 1);\n\t\t\t\t\tf.emplace_back(b, 1);\n\t\t\t\t\tv = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(v > 1)\n\t\t\t\tf.emplace_back(v, 1), v = 1;\n\t\t}\n\t}\n\treturn f;\n}\n\nint d[(1 << 18) + 3];\n\ninline void solve() {\n\tif(y % x != 0) {\n\t\tputs(\"0\");\n\t\treturn;\n\t}\n\t\n\tvector<pt> fy = factorize(y);\n\tvector<pt> fx;\n\tli cx = x;\n\tfor(auto p : fy) {\n\t\tint cnt = 0;\n\t\twhile(cx % p.x == 0)\n\t\t\tcx /= p.x, cnt++;\n\t\tfx.emplace_back(p.x, cnt);\n\t}\n\t\n\tvector<li> ps;\n\tvector<pt> bb;\n\t\n\tfore(i, 0, sz(fy)) {\n\t\tif(fx[i].y < fy[i].y) {\n\t\t\tps.push_back(fy[i].x);\n\t\t\tbb.emplace_back(fx[i].y, fy[i].y);\n\t\t}\n\t}\n\t\n\tfore(i, 0, n) {\n\t\tif(a[i] % x != 0)\n\t\t\tcontinue;\n\t\t\n\t\tint mask = 0;\n\t\tli ca = a[i];\n\t\tfore(j, 0, sz(ps)) {\n\t\t\tint cnt = 0;\n\t\t\twhile(ca % ps[j] == 0)\n\t\t\t\tca /= ps[j], cnt++;\n\t\t\tassert(cnt >= bb[j].x);\n\t\t\t\n\t\t\tmask |= (cnt > bb[j].x) << j;\n\t\t}\n\t\td[mask]++;\n\t}\n\t\n\tfor(int i = 0; i < sz(ps); i++) {\n\t\tfore(mask, 0, 1 << sz(ps))\n\t\t\tif((mask >> i) & 1)\n\t\t\t\td[mask] += d[mask ^ (1 << i)];\n\t}\n\t\n\tli ans = 0;\n\tfore(i, 0, n) {\n\t\tif(y % a[i] != 0)\n\t\t\tcontinue;\n\t\t\n\t\tint mask = 0;\n\t\tli ca = a[i];\n\t\tfore(j, 0, sz(ps)) {\n\t\t\tint cnt = 0;\n\t\t\twhile(ca % ps[j] == 0)\n\t\t\t\tca /= ps[j], cnt++;\n\t\t\tassert(cnt <= bb[j].y);\n\t\t\t\n\t\t\tmask |= (cnt < bb[j].y) << j;\n\t\t}\n\t\tans += d[mask ^ ((1 << sz(ps)) - 1)];\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1017",
    "index": "A",
    "title": "The Rank",
    "statement": "John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.\n\nThere are $n$ students, each of them has a \\textbf{unique} id (from $1$ to $n$). Thomas's id is $1$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.\n\nIn the table, the students will be sorted by \\textbf{decreasing} the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by \\textbf{increasing} their ids.\n\nPlease help John find out the rank of his son.",
    "tutorial": "For each student, add his/her $4$ scores together and count how many students have strictly lower scores than Thomas. Complexity: $O(n)$ or $O(n \\log n)$.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    int n;\n\tcin >> n;\n\tint a, b, c, d;\n\tcin >> a >> b >> c >> d;\n\tint S = a + b + c + d;\n\tint Ans = 1;\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t    cin >> a >> b >> c >> d;\n\t    if(a + b + c + d > S)\n\t    {\n\t        Ans++;\n\t    }\n\t}\n\tprintf(\"%d\\n\",Ans);\n\treturn 0;\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1017",
    "index": "B",
    "title": "The Bits",
    "statement": "Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:\n\nGiven two binary numbers $a$ and $b$ of length $n$. How many different ways of swapping two digits in $a$ (only in $a$, not $b$) so that bitwise OR of these two numbers will be changed? In other words, let $c$ be the bitwise OR of $a$ and $b$, you need to find the number of ways of swapping two bits in $a$ so that bitwise OR will not be equal to $c$.\n\nNote that binary numbers can contain leading zeros so that length of each number is exactly $n$.\n\nBitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $01010_2$ OR $10011_2$ = $11011_2$.\n\nWell, to your surprise, you are not Rudolf, and you don't need to help him$\\ldots$ You are the security staff! Please find the number of ways of swapping two bits in $a$ so that bitwise OR will be changed.",
    "tutorial": "Let $t_{xy}$ be the number of indexes $i$ such that $a_i=x$ and $b_i=y$. The answer is $t_{00}\\cdot t_{10} + t_{00}\\cdot t_{11} + t_{01}\\cdot t_{10}$.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\nlong long ar[4];\nchar c1[4] = {'0', '0', '1', '1'};\nchar c2[4] = {'0', '1', '0', '1'};\n\nint main() {\n    int n;\n    cin >> n;\n    string a, b;\n    cin >> a >> b;\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < 4; j++){\n            if(c1[j] == a[i] && c2[j] == b[i]){\n                ar[j]++;\n            }\n        }\n    }\n    cout << ar[0] * ar[2] + ar[0] * ar[3] + ar[1] * ar[2] << endl;\n    return 0;\n}\n",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1017",
    "index": "C",
    "title": "The Phone Number",
    "statement": "Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!\n\nThe only thing Mrs. Smith remembered was that any permutation of $n$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.\n\nThe sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.\n\nThe secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).\n\nA subsequence $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$ where $1\\leq i_1 < i_2 < \\ldots < i_k\\leq n$ is called increasing if $a_{i_1} < a_{i_2} < a_{i_3} < \\ldots < a_{i_k}$. If $a_{i_1} > a_{i_2} > a_{i_3} > \\ldots > a_{i_k}$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.\n\nFor example, if there is a permutation $[6, 4, 1, 7, 2, 3, 5]$, LIS of this permutation will be $[1, 2, 3, 5]$, so the length of LIS is equal to $4$. LDS can be $[6, 4, 1]$, $[6, 4, 2]$, or $[6, 4, 3]$, so the length of LDS is $3$.\n\nNote, the lengths of LIS and LDS can be different.\n\nSo please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.",
    "tutorial": "Show an example of $n = 22$: \"' 19 20 21 22 15 16 17 18 11 12 13 14 7 8 9 10 3 4 5 6 1 2 \"' You can use [Dilworth's theorem](https://en.wikipedia.org/wiki/Dilworth So assume we've already known that $LIS = L$, then we can achieve $LDS = \\big\\lceil\\frac{n}{L}\\big\\rceil$. So after enumerating all possible $L$ and find the minimum of function $L \\big\\lceil\\frac{n}{L}\\big\\rceil$, we can construct the sequence easily just as the case when $n = 22$. Actually, $L = \\big\\lfloor \\sqrt n \\big\\rfloor$ will always work. Complexity: $O(n)$.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n#define MAXN 100000\n#define rint register int\ninline int rf(){int r;int s=0,c;for(;!isdigit(c=getchar());s=c);for(r=c^48;isdigit(c=getchar());(r*=10)+=c^48);return s^45?r:-r;}\nint n, L, A[MAXN+5];\nint main()\n{\n\tn = rf();\n\tL = (int)sqrt(n);\n\tfor(rint i = 1, o = n, j; i <= n; i += L)\n\t\tfor(j = min(i+L-1,n); j >= i; A[j--] = o--);\n\tfor(rint i = 1; i <= n; i++)\n\t\tprintf(\"%d%c\",A[i],\"\\n \"[i<n]);\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1017",
    "index": "D",
    "title": "The Wu",
    "statement": "Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of \"Wu\" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called \"personal treasure\" necklace.\n\nThis \"personal treasure\" is a multiset $S$ of $m$ \"01-strings\".\n\nA \"01-string\" is a string that contains $n$ characters \"0\" and \"1\". For example, if $n=4$, strings \"0110\", \"0000\", and \"1110\" are \"01-strings\", but \"00110\" (there are $5$ characters, not $4$) and \"zero\" (unallowed characters) are not.\n\n\\textbf{Note that the multiset $S$ can contain equal elements.}\n\nFrequently, Mr. Kasoura will provide a \"01-string\" $t$ and ask Childan how many strings $s$ are in the multiset $S$ such that the \"Wu\" value of the pair $(s, t)$ is \\textbf{not greater} than $k$.\n\nMrs. Kasoura and Mr. Kasoura think that if $s_i = t_i$ ($1\\leq i\\leq n$) then the \"Wu\" value of the character pair equals to $w_i$, otherwise $0$. The \"Wu\" value of the \"01-string\" pair is the sum of the \"Wu\" values of every character pair. Note that the length of every \"01-string\" is equal to $n$.\n\nFor example, if $w=[4, 5, 3, 6]$, \"Wu\" of (\"1001\", \"1100\") is $7$ because these strings have equal characters only on the first and third positions, so $w_1+w_3=4+3=7$.\n\nYou need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset $S$ such that the \"Wu\" value of the pair is not greater than $k$.",
    "tutorial": "We can regard a $01-string$ as a binary number. Notice that $n \\le 12$, so $\\frac{n}{2} \\le 6$, so we can do something like meet-in-the-middle, split the numbers into higher $6$ bits and lower $6$ bits: $f[S_1][S_2][j]$ count the number of binary numbers with higher bits equal to $S_1$ and $f((\\text{lower bits}) \\oplus S2) = j$. Then one can easily get $g[S][k]$ stores the answer and then answer queries in $O(1)$ time. If you don't understand, see the code. Complexity: $O(|S|2^{\\frac{n}{2}}+2^{\\frac{3n}{2}}+q)$.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n#define MAXN 100000\n#define rint register int\ninline int rf(){int r;int s=0,c;for(;!isdigit(c=getchar());s=c);for(r=c^48;isdigit(c=getchar());(r*=10)+=c^48);return s^45?r:-r;}\nint Wu[4096], f[64][64][104], g[4096][104], w[16], m, n, q, E, K, B = 6, L = 63, H = 4032; char _[16];\nint main()\n{\n\tm = rf();\n\tn = rf();\n\tq = rf();\n\tgenerate(w,w+m,rf);\n\tE = 1<<m;\n\tfor(rint S = 0, j; S < E; S++)\n\t{\n\t\tfor(j = 0; j < m; j++)\n\t\t\tS&1<<j?:Wu[S]+=w[j];\n\t\tWu[S] = min(Wu[S],101);\n\t}\n\tfor(rint i = 1, j, S; i <= n; i++)\n\t{\n\t\tscanf(\"%s\",_+1);\n\t\tfor(S = 0, j = m; j; j--)\n\t\t\tS = S<<1|(_[j]^'0');\n\t\tfor(j = 0; j < 64; j++)\n\t\t\t++f[(S&H)>>B][j][Wu[((j^(S&L))|H)&~-E]];\n\t}\n\tfor(rint S = 0, a, b, j; S < E; S++)\n\t{\n\t\tfor(j = 0; j < 64; j++)\n\t\t\tfor(a = 0, b = Wu[(((j<<B)^(S&H))|L)&~-E]; b <= 100; a++, b++)\n\t\t\t\tg[S][b] += f[j][S&L][a];\n\t\tpartial_sum(g[S],g[S]+101,g[S]);\n\t}\n\tfor(rint i = 1, j, S; i <= q; i++)\n\t{\n\t\tscanf(\"%s\",_+1);\n\t\tfor(S = 0, j = m; j; j--)\n\t\t\tS = S<<1|(_[j]^'0');\n\t\tprintf(\"%d\\n\",g[S][rf()]);\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1017",
    "index": "E",
    "title": "The Supersonic Rocket",
    "statement": "After the war, the supersonic rocket became the most common public transportation.\n\nEach supersonic rocket consists of \\textbf{two} \"engines\". Each engine is a set of \"power sources\". The first engine has $n$ power sources, and the second one has $m$ power sources. A power source can be described as a point $(x_i, y_i)$ on a 2-D plane. All points in each engine are different.\n\nYou can manipulate each engine \\textbf{separately}. There are two operations that you can do with each engine. You can do each operation as many times as you want.\n\n- For every power source as a whole in that engine: $(x_i, y_i)$ becomes $(x_i+a, y_i+b)$, $a$ and $b$ can be any real numbers. In other words, all power sources will be shifted.\n- For every power source as a whole in that engine: $(x_i, y_i)$ becomes $(x_i \\cos \\theta - y_i \\sin \\theta, x_i \\sin \\theta + y_i \\cos \\theta)$, $\\theta$ can be any real number. In other words, all power sources will be rotated.\n\nThe engines work as follows: after the two engines are powered, their power sources are being combined (here power sources of different engines may coincide). If two power sources $A(x_a, y_a)$ and $B(x_b, y_b)$ exist, then for all real number $k$ that $0 \\lt k \\lt 1$, a new power source will be created $C_k(kx_a+(1-k)x_b,ky_a+(1-k)y_b)$. \\textbf{Then, this procedure will be repeated again with all new and old power sources}. After that, the \"power field\" from all power sources will be generated (can be considered as an infinite set of all power sources occurred).\n\nA supersonic rocket is \"safe\" if and only if after you manipulate the engines, destroying any power source and then power the engine, the power field generated won't be changed (comparing to the situation where no power source erased). Two power fields are considered the same if and only if any power source in one field belongs to the other one as well.\n\nGiven a supersonic rocket, check whether it is safe or not.",
    "tutorial": "The statement is complicated, it is actually: Given two sets of points, check whether their convex hulls are isomorphic. The standard solution is: get the convex hulls, make it into a string of traversal: \"edge-angle-edge-angle-edge-...\". Then double the first string and KMP them. There can be other ways to solve this problem, because there is a useful condition: all coordinates are integers. Complexity: $O(|S_1| \\log |S_1| + |S_2| \\log |S_2|)$.",
    "code": "\n#pragma comment(linker, \"/STACK:512000000\")\n#define _CRT_SECURE_NO_WARNINGS\n//#include \"testlib.h\"\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define all(a) a.begin(), a.end()\nusing li = long long;\nusing ld = long double;\nvoid solve(bool);\nvoid precalc();\nclock_t start;\nint main() {\n#ifdef AIM\n  freopen(\"/home/alexandero/CLionProjects/ACM/input.txt\", \"r\", stdin);\n//freopen(\"/home/alexandero/CLionProjects/ACM/output.txt\", \"w\", stdout);\n//freopen(\"out.txt\", \"w\", stdout);\n#else\n  //freopen(\"input.txt\", \"r\", stdin);\n//freopen(\"output.txt\", \"w\", stdout);\n#endif\n  start = clock();\n  int t = 1;\n#ifndef AIM\n  cout.sync_with_stdio(0);\n  cin.tie(0);\n#endif\n  cout.precision(20);\n  cout << fixed;\n//cin >> t;\n  precalc();\n  while (t--) {\n    solve(true);\n  }\n  cout.flush();\n\n#ifdef AIM1\n  while (true) {\nsolve(false);\n}\n#endif\n\n#ifdef AIM\n  cerr << \"\\n\\n time: \" << (clock() - start) / 1.0 / CLOCKS_PER_SEC << \"\\n\\n\";\n#endif\n  return 0;\n}\n\n//BE CAREFUL: IS INT REALLY INT?\n\ntemplate<typename T>\nT binpow(T q, T w, T mod) {\n  if (!w)\n    return 1 % mod;\n  if (w & 1)\n    return q * 1LL * binpow(q, w - 1, mod) % mod;\n  return binpow(q * 1LL * q % mod, w / 2, mod);\n}\n\ntemplate<typename T>\nT gcd(T q, T w) {\n  while (w) {\n    q %= w;\n    swap(q, w);\n  }\n  return q;\n}\ntemplate<typename T>\nT lcm(T q, T w) {\n  return q / gcd(q, w) * w;\n}\n\ntemplate <typename T>\nvoid make_unique(vector<T>& vec) {\n  sort(all(vec));\n  vec.erase(unique(all(vec)), vec.end());\n}\n\ntemplate<typename T>\nvoid relax_min(T& cur, T val) {\n  cur = min(cur, val);\n}\n\ntemplate<typename T>\nvoid relax_max(T& cur, T val) {\n  cur = max(cur, val);\n}\n\nvoid precalc() {\n\n}\n\n#define int li\n//const li mod = 1000000007;\n//using ull = unsigned long long;\n\nstruct Point {\n  int x, y;\n  Point() {}\n  Point(int x, int y) : x(x), y(y) {}\n  Point operator - (const Point& ot) const {\n    return Point(x - ot.x, y - ot.y);\n  }\n  int operator * (const Point& ot) const {\n    return x * ot.y - y * ot.x;\n  }\n  void scan() {\n    cin >> x >> y;\n  }\n  bool operator < (const Point& ot) const {\n    return make_pair(x, y) < make_pair(ot.x, ot.y);\n  }\n  int sqr_len() const {\n    return x * x + y * y;\n  }\n  long double get_len() const {\n    return sqrtl(sqr_len());\n  }\n  int operator % (const Point& ot) const {\n    return x * ot.x + y * ot.y;\n  }\n};\n\nstruct Polygon {\n  vector<Point> hull;\n  Polygon(int n) {\n    vector<Point> points(n);\n    for (int i = 0; i < n; ++i) {\n      points[i].scan();\n    }\n    sort(all(points));\n    vector<Point> up, down;\n    for (auto& pt : points) {\n      while (up.size() > 1 && (up[up.size() - 2] - up.back()) * (pt - up.back()) >= 0) {\n        up.pop_back();\n      }\n      up.push_back(pt);\n      while (down.size() > 1 && (down[down.size() - 2] - down.back()) * (pt - down.back()) <= 0) {\n        down.pop_back();\n      }\n      down.push_back(pt);\n    }\n    hull = up;\n    for (int i = (int)down.size() - 2; i > 0; --i) {\n      hull.push_back(down[i]);\n    }\n  }\n  int sqr_len(int pos) const {\n    return (hull[(pos + 1) % hull.size()] - hull[pos]).sqr_len();\n  }\n  int size() const {\n    return (int)hull.size();\n  }\n  long double get_angle(int pos) const {\n    auto a = hull[(pos + 1) % hull.size()] - hull[pos], b = hull[(pos + hull.size() - 1) % hull.size()] - hull[pos];\n    long double co = (a % b) / a.get_len() / b.get_len();\n    return co;\n  }\n};\n\nvoid solve(bool read) {\n  vector<Polygon> polys;\n  int n[2];\n  cin >> n[0] >> n[1];\n  for (int i = 0; i < 2; ++i) {\n    polys.emplace_back(n[i]);\n  }\n  if (polys[0].size() != polys[1].size()) {\n    cout << \"NO\\n\";\n    return;\n  }\n  vector<long double> all_lens;\n  int m = polys[0].size();\n  for (int i = 0; i < m; ++i) {\n    all_lens.push_back(polys[0].sqr_len(i));\n    all_lens.push_back(polys[0].get_angle(i));\n  }\n  all_lens.push_back(-1);\n  for (int j = 0; j < 2; ++j) {\n    for (int i = 0; i < m; ++i) {\n      all_lens.push_back(polys[1].sqr_len(i));\n      all_lens.push_back(polys[1].get_angle(i));\n    }\n  }\n  /*for (int x : all_lens) {\n    cout << x << \" \";\n  }\n  cout << \"\\n\";*/\n  vector<int> p(all_lens.size());\n  for (int i = 1; i < p.size(); ++i) {\n    int j = p[i - 1];\n    while (j > 0 && all_lens[i] != all_lens[j]) {\n      j = p[j - 1];\n    }\n    if (all_lens[i] == all_lens[j]) {\n      ++j;\n    }\n    p[i] = j;\n    if (p[i] == 2 * m) {\n      cout << \"YES\\n\";\n      return;\n    }\n  }\n  cout << \"NO\\n\";\n\n}\n",
    "tags": [
      "geometry",
      "hashing",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1017",
    "index": "F",
    "title": "The Neutral Zone",
    "statement": "\\textbf{Notice: unusual memory limit!}\n\nAfter the war, destroyed cities in the neutral zone were restored. And children went back to school.\n\nThe war changed the world, as well as education. In those hard days, a new math concept was created.\n\nAs we all know, logarithm function can be described as: $$ \\log(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 \\log p_1 + a_2 \\log p_2 + ... + a_k \\log p_k $$ Where $p_1^{a_1}p_2^{a_2}...p_k^{a_2}$ is the prime factorization of a integer. A problem is that the function uses itself in the definition. That is why it is hard to calculate.\n\nSo, the mathematicians from the neutral zone invented this: $$ \\text{exlog}_f(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 f(p_1) + a_2 f(p_2) + ... + a_k f(p_k) $$\n\nNotice that $\\text{exlog}_f(1)$ is always equal to $0$.\n\nThis concept for any function $f$ was too hard for children. So teachers told them that $f$ can only be a polynomial of degree no more than $3$ in daily uses (i.e., $f(x) = Ax^3+Bx^2+Cx+D$).\n\n\"Class is over! Don't forget to do your homework!\" Here it is: $$ \\sum_{i=1}^n \\text{exlog}_f(i) $$\n\nHelp children to do their homework. Since the value can be very big, you need to find the answer modulo $2^{32}$.",
    "tutorial": "First forget about the memory limit part. Instead of enumerating all integers and count its $\\text{exlog}_f$ value, we enumerate all primes and count its contribution. It is obvious that prime $p$'s contribution is: Brute-force this thing is actually $O(n)$: since there are only $O(\\frac{n}{\\ln n})$ primes less than or equal to $n$ and calculate the second part for each of them cost $O(\\log_p n)$ times. Now the problem is on sieving the primes. Use Eratosthenes's sieve instead of Euler's, then the only memory cost is the cross-out table. Use a 'bitset' to store the cross-out table and you'll get a memory cost for about $37.5 MB$. Key observation: except $2$ and $3$, all primes $p$ satisfy $p \\equiv \\pm 1 \\pmod 6$. Then just store these positions with $\\frac{37.5MB}{3} = 12.5 MB$. You can also use this observation to optimize your code's running time. Complexity: $O(n \\log \\log n)$. That's the running time of Eratosthenes's sieve.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef unsigned int ll;\nconst ll maxn=4e8;\nconst ll maxp=sqrt(maxn)+10;\nll f[4][maxp],g[4][maxp];\nll n,m,A,B,C,D,ans,res,tmp,rt;\n\nll p1(ll x){\n    ll y=x+1; if (x%2==0) x/=2; else y/=2;\n    return x*y;\n}\nll p2(ll x){\n    long long y=x+1,z=x*2+1;\n    if (x%2==0) x/=2; else y/=2;\n    if (z%3==0) z/=3; else if (x%3==0) x/=3; else y/=3;\n    return (ll)x*y*z;\n}\nll p3(ll x){\n    ll y=p1(x);\n    return y*y;\n}\nbool is_prime(ll x){\n    for (ll i=2;i*i<=x;i++) if (x%i==0) return false;\n    return true;\n}\n\nll solve(ll n)\n{\n    ll i,j,rt,o[4];\n    for (m=1;m*m<=n;m++) {\n        f[0][m]=(n/m-1);\n        f[1][m]=(p1(n/m)-1)*C;\n        f[2][m]=(p2(n/m)-1)*B;\n        f[3][m]=(p3(n/m)-1)*A;\n    }\n    for (i=1;i<=m;i++) {\n        g[0][i]=(i-1);\n        g[1][i]=(p1(i)-1)*C;\n        g[2][i]=(p2(i)-1)*B;\n        g[3][i]=(p3(i)-1)*A;\n    }\n    for (i=2;i<=m;i++) {\n        if (g[0][i]==g[0][i-1]) continue;\n        o[0]=1; for (int w=1;w<4;w++) o[w]=o[w-1]*i;\n        for (j=1;j<=min(m-1,n/i/i);j++)\n            for (int w=0;w<4;w++)\n                if (i*j<m) f[w][j]-=o[w]*(f[w][i*j]-g[w][i-1]);\n                else f[w][j]-=o[w]*(g[w][n/i/j]-g[w][i-1]);\n        for (j=m;j>=i*i;j--)\n            for (int w=0;w<4;w++)\n                g[w][j]-=o[w]*(g[w][j/i]-g[w][i-1]);\n    }\n    for (int i=1;i<=m+1;i++) f[0][i]*=D,g[0][i]*=D;\n    rt=0;\n    for (ll i=1;n/i>m;i++) {\n        for (int w=0;w<4;w++) rt+=(f[w][i]-g[w][m]);\n        //cout<<\"H\"<<rt<<endl;\n    }\n    return rt;\n}\n\nint main()\n{\n    //freopen(\"input.txt\",\"r\",stdin);\n    ll n; cin >> n >> A >> B >> C >> D;\n    ans=solve(n);\n    for (ll i=2;i<=m;i++){\n        if (is_prime(i)){\n            res=A*i*i*i+B*i*i+C*i+D; tmp=n;\n            while (tmp){\n                ans+=res*(tmp/i);\n                tmp/=i;\n            }\n        }\n    }\n    cout << ans << endl;\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1017",
    "index": "G",
    "title": "The Tree",
    "statement": "Abendsen assigned a mission to Juliana. In this mission, Juliana has a rooted tree with $n$ vertices. Vertex number $1$ is the root of this tree. Each vertex can be either black or white. At first, all vertices are white. Juliana is asked to process $q$ queries. Each query is one of three types:\n\n- If vertex $v$ is white, mark it as black; otherwise, perform this operation on all direct sons of $v$ instead.\n- Mark all vertices in the subtree of $v$ (including $v$) as white.\n- Find the color of the $i$-th vertex.\n\n\\begin{center}\n{\\small An example of operation \"1 1\" (corresponds to the first example test). The vertices $1$ and $2$ are already black, so the operation goes to their sons instead.}\n\\end{center}\n\nCan you help Juliana to process all these queries?",
    "tutorial": "The problem can be solved using HLD or sqrt-decomposition on queries. Here, I will explain to you the second solution. Let $s$ be a constant. Let's split all queries on $\\frac{n}{s}$ blocks. Each block will contain $s$ queries. In each block, since we have $s$ queries, we will have at most $s$ different vertices there. Therefore, we can squeeze the tree using only those $s$ different vertices. There will be a directed edge from $i$ to $j$ if they are both in that set of $s$ different vertices and $i$ is an ancestor of $j$ in the original tree. A weight of such edge will be the number of white vertices on the way between those two vertices (exclusively $i$ and $j$). If we want to find answers for the queries in the black, we need to make every operation in $\\mathcal{O}(s)$. In each vertex, we will have $p_i$ - the number of operations of the first type that need to be processed on that vertex. Also, each vertex will have $c_i$ - the boolean variable that means that we need to clear the subtree. Obviously, when we are doing the second operation, we need to clear every $p_i$ in that subtree. After we answer the queries of the $i$-th block, we need to update the full graph. So, the complexity will be $\\mathcal{O}(\\frac{n}{s}\\cdot n + n\\cdot s)$. If you make $s = \\sqrt{n}$, the complexity will be $\\mathcal{O}(n\\cdot \\sqrt{n})$. For better understanding, you can check the code below.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX = 1e5 + 10;\n\nbool black[MAX]; // is it vertex black now\nvector<int> vec[MAX]; // main edges\nbool old_black[MAX]; // to remember the tree before block\n\nconst int MAX_BLOCK_SIZE = 600;\n\nint t[MAX], v[MAX]; // queries\n\nbool used[MAX]; // is in mini-tree\nvector<pair<pair<int, int>, int> > v2[MAX]; // mini-tree edges (son, number of white vertices, dist)\nint push[MAX]; // push of the i-th vertex in mini-tree\nbool clear[MAX]; // do we need to clear first\n\nvoid dfs_1(int pos, int prev = -1, int white = 0, int dist = 0){\n    if(used[pos]){\n        if(prev != -1){\n            v2[prev].push_back(make_pair(make_pair(pos, white), dist));\n        }\n        for(int a : vec[pos]){\n            dfs_1(a, pos, 0, 0);\n        }\n    }else{\n        if(!black[pos]){\n            white++;\n        }\n        for(int a : vec[pos]){\n            dfs_1(a, prev, white, dist + 1);\n        }\n    }\n}\n\nvoid make_1(int pos){\n    if(!black[pos]){\n        black[pos] = true;\n        return;\n    }\n    push[pos]++;\n    for(auto a : v2[pos]){\n        if(a.first.second + 1 <= push[pos]){\n            make_1(a.first.first);\n        }\n    }\n}\n\nvoid make_2(int pos){\n    black[pos] = false;\n    push[pos] = 0;\n    clear[pos] = true;\n    for(auto &a : v2[pos]){\n        a.first.second = a.second;\n        make_2(a.first.first);\n    }\n}\n\nvoid dfs_2(int pos, int p = 0, bool cl = false){\n    if(used[pos]){\n        p = push[pos];\n        cl |= clear[pos];\n    }else{\n        black[pos] = old_black[pos];\n        if(cl){\n            black[pos] = false;\n        }\n        if(!black[pos] && p){\n            black[pos] = true;\n            p--;\n        }\n    }\n    for(int a : vec[pos]){\n        dfs_2(a, p, cl);\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio();\n    cin.tie(0);\n    cout.tie(0);\n    int n, q;\n    cin >> n >> q;\n    for(int i = 2; i <= n; i++){\n        int a;\n        cin >> a;\n        vec[a].push_back(i);\n    }\n    for(int i = 1; i <= q; i++){\n        cin >> t[i] >> v[i];\n    }\n    int root = 1;\n    for(int i = 1; i <= q; i += MAX_BLOCK_SIZE){\n        for(int j = 1; j <= n; j++){\n            used[j] = false;\n            v2[j].clear();\n            old_black[j] = black[j];\n            push[j] = 0;\n            clear[j] = false;\n        }\n        for(int j = 0; j < MAX_BLOCK_SIZE && i + j <= q; j++){\n            used[v[i + j]] = true;\n        }\n        dfs_1(root);\n        for(int j = 0; j < MAX_BLOCK_SIZE && i + j <= q; j++){\n            int t = ::t[i + j];\n            int v = ::v[i + j];\n            if(t == 1){\n                make_1(v);\n            }else if(t == 2){\n                make_2(v);\n            }else{\n                cout << (black[v] ? \"black\" : \"white\") << \"\\n\";\n            }\n        }\n        dfs_2(root);\n    }\n    return 0;\n}\n",
    "tags": [
      "data structures"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1017",
    "index": "H",
    "title": "The Films",
    "statement": "In \"The Man in the High Castle\" world, there are $m$ different film endings.\n\nAbendsen owns a storage and a shelf. At first, he has $n$ ordered films on the shelf. In the $i$-th month he will do:\n\n- Empty the storage.\n- Put $k_i \\cdot m$ films into the storage, $k_i$ films for each ending.\n- He will think about a question: if he puts all the films from the shelf into the storage, then randomly picks $n$ films (from all the films in the storage) and rearranges them on the shelf, what is the probability that sequence of endings in $[l_i, r_i]$ on the shelf will not be changed? Notice, he just thinks about this question, so the shelf will not actually be changed.\n\nAnswer all Abendsen's questions.\n\nLet the probability be fraction $P_i$. Let's say that the total number of ways to take $n$ films from the storage for $i$-th month is $A_i$, so $P_i \\cdot A_i$ is always an integer. Print for each month $P_i \\cdot A_i \\pmod {998244353}$.\n\n$998244353$ is a prime number and it is equal to $119 \\cdot 2^{23} + 1$.\n\nIt is guaranteed that there will be only no more than $100$ different $k$ values.",
    "tutorial": "First, we claim the probability is this: Proof: For each position in $[l,r]$ with ending $i$, you can choose any film with the same ending, there are $(t_i+k)$ of them for the first candidate, and $(t_i+k-1)$ of them for the second candidate, ... So you can satisfy the conditions with $\\prod_{i=1}^m (t_i +k)^{\\underline c_i}$ number of ways. After that, other $n-(r-l+1)$ positions can be filled arbitrarily, there are $(mk+n-(r-l+1))^{\\underline{n-(r-l+1)}}$ ways of doing that. And the total number of ways is $(mk+n)^{\\underline n}$ obviously. If $k = 0$, we can maintain the expression using Mo-algorithm with complexity about $O(n\\sqrt n)$. More precisely, it is $O(n \\sqrt q)$ or $O(n \\sqrt q\\log m)$. Key observation: There can only be $O(\\sqrt n)$ different occuring times at most. Proof: In the worst case, the occurring times are $1 + 2 + 3 + ... + x = \\frac{x(x+1)}{2} \\le n$, so $x = O(\\sqrt n)$. Similarly, that there are at most $O(n^\\frac{2}{3})$ different combinations of $t_i$ and $c_i$. Proof: In the worst case, pairs of $(t_i,c_i)$ are like: $t_i$ : 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 ... $c_i$ : 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 ... Let its length of same $c_i$ be $A$ and repeat time be $B$. Then from the total occurring times we get $\\frac{A(A+1)}{2}B \\le n$ , and from the occurring times in segment we get $\\frac{B(B+1)}{2} A \\le r-l+1$ . So around $A = B = O(n^{\\frac{1}{3}})$ we achieve the minimum. Use a hash table (actually an array of size $O(m\\sqrt n)$) to remember them, and brute-force them for each query. We're done. About the $\\frac{(mk+n-(r-l+1))^{\\underline{n-(r-l+1)}}}{(mk+n)^{\\underline n}}$ part, since there are no more than $K = 100$ different $k$ value, preprocess that for each $k$. Complexity: $O(Kn + n \\sqrt q + qn^{\\frac{2}{3}} \\log m)$. Actually, due to limit of $K$, if one simply run mo-algorithm $K$ times, it will reach a $O(n\\sqrt{qK})$. Under this limit it can be faster than standard solution.",
    "code": "\n#pragma comment(linker, \"/STACK:512000000\")\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define all(a) a.begin(), a.end()\ntypedef long long li;\ntypedef long double ld;\nvoid solve(__attribute__((unused)) bool);\nvoid precalc();\nclock_t start;\n#define FILENAME \"\"\n\nint main() {\n#ifdef AIM\n    string s = FILENAME;\n//    assert(!s.empty());\n    freopen(\"/home/alexandero/ClionProjects/cryptozoology/input.txt\", \"r\", stdin);\n  //freopen(\"/home/alexandero/ClionProjects/cryptozoology/output.txt\", \"w\", stdout);\n#else\n//    freopen(FILENAME \".in\", \"r\", stdin);\n//    freopen(FILENAME \".out\", \"w\", stdout);\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    start = clock();\n    int t = 1;\n#ifndef AIM\n    cout.sync_with_stdio(0);\n    cin.tie(0);\n#endif\n  precalc();\n    cout.precision(10);\n    cout << fixed;\n    //cin >> t;\n    int testNum = 1;\n    while (t--) {\n        //cout << \"Case #\" << testNum++ << \": \";\n        solve(true);\n    }\n    cout.flush();\n#ifdef AIM1\n    while (true) {\n      solve(false);\n  }\n#endif\n\n#ifdef AIM\n    cout.flush();\n    auto end = clock();\n\n    usleep(10000);\n    print_stats(end - start);\n    usleep(10000);\n#endif\n\n    return 0;\n}\n\ntemplate<typename T>\nT binpow(T q, T w, T mod) {\n    if (!w)\n        return 1 % mod;\n    if (w & 1)\n        return q * 1LL * binpow(q, w - 1, mod) % mod;\n    return binpow(q * 1LL * q % mod, w / 2, mod);\n}\n\ntemplate<typename T>\nT gcd(T q, T w) {\n    while (w) {\n        q %= w;\n        swap(q, w);\n    }\n    return q;\n}\ntemplate<typename T>\nT lcm(T q, T w) {\n    return q / gcd(q, w) * w;\n}\n\ntemplate <typename T>\nvoid make_unique(vector<T>& a) {\n    sort(all(a));\n    a.erase(unique(all(a)), a.end());\n}\n\ntemplate<typename T>\nvoid relax_min(T& cur, T val) {\n    cur = min(cur, val);\n}\n\ntemplate<typename T>\nvoid relax_max(T& cur, T val) {\n    cur = max(cur, val);\n}\n\nvoid precalc() {\n}\n\n#define int li\nconst int mod = 998244353;\n\nstruct Query {\n  int l, r, id;\n};\n\nvector<int> res;\nvector<int> a;\nint n;\n\nint TIMER = 0;\nconst int C = 200500;\nint used[C];\nint cur_cnt[C];\nint rev[C];\nmap<int, vector<int>> down;\nvector<int> init;\n\nvoid kill(vector<Query>& all_q, int block_size, int k) {\n  vector<vector<Query>> by_block(n / block_size + 1);\n  for (auto& cur_q : all_q) {\n    by_block[cur_q.l / block_size].push_back(cur_q);\n  }\n  for (int i = 0; i < by_block.size(); ++i) {\n    ++TIMER;\n    auto& q = by_block[i];\n    sort(all(q), [&] (const Query& o1, const Query& o2) {\n      return o1.r < o2.r;\n    });\n    int cur_l = min(n, (i + 1) * block_size);\n    int cur_r = cur_l;\n    int cur_prod = 1;\n\n    auto add_item = [&] (int val) {\n      if (used[val] != TIMER) {\n        used[val] = TIMER;\n        cur_cnt[val] = 0;\n      }\n      int cur_k = k + init[val];\n      ++cur_cnt[val];\n        cur_prod = cur_prod * (cur_k - cur_cnt[val] + 1) % mod;\n    };\n    auto remove_item = [&] (int val) {\n      int cur_k = k + init[val];\n        cur_prod = cur_prod * rev[cur_k - cur_cnt[val] + 1] % mod;\n      --cur_cnt[val];\n    };\n\n    for (auto& cur_q : q) {\n      while (cur_r < cur_q.r) {\n        add_item(a[cur_r++]);\n      }\n      while (cur_l > cur_q.l) {\n        add_item(a[--cur_l]);\n      }\n      while (cur_r > cur_q.r) {\n        remove_item(a[--cur_r]);\n      }\n      while (cur_l < cur_q.l) {\n        remove_item(a[cur_l++]);\n      }\n        res[cur_q.id] = cur_prod * down[k][n - cur_q.r + cur_q.l] % mod;\n    }\n  }\n}\n\nvoid solve(__attribute__((unused)) bool read) {\n  for (int i = 1; i < C; ++i) {\n    rev[i] = binpow(i, mod - 2, mod);\n  }\n  int m, Q;\n  //read = false;\n  if (read) {\n    cin >> n >> m >> Q;\n  } else {\n    n = 50000;\n    m = 100000;\n    Q = 50000;\n  }\n  a.resize(n);\n  init.assign(m, 0);\n  for (int i = 0; i < n; ++i) {\n    if (read) {\n      cin >> a[i];\n      --a[i];\n    } else {\n      a[i] = rand() % m;\n    }\n    ++init[a[i]];\n  }\n  map<int, vector<Query>> q;\n  for (int i = 0; i < Q; ++i) {\n    int l, r, k;\n    if (read) {\n      cin >> l >> r >> k;\n    } else {\n      do {\n        l = rand() % n + 1;\n        r = rand() % n + 1;\n      } while (l > r);\n      k = rand() % 100;\n    }\n    --l;\n    q[k].push_back({l, r, i});\n    down[k] = vector<int>();\n  }\n  res.assign(Q, 0);\n  for (auto& item : down) {\n    int init_val = (item.first * m) % mod;\n    auto& vec = item.second;\n    vec.assign(n + 1, 1);\n    for (int i = 1; i < vec.size(); ++i) {\n      vec[i] = vec[i - 1] * (init_val + i) % mod;\n    }\n  }\n  for (auto& item : q) {\n    int k = item.first;\n    auto& cur_q = item.second;\n    int block_size = std::max((int)(n / sqrt((int)cur_q.size())), 1LL);\n    kill(cur_q, block_size, k);\n  }\n\n  for (int i = 0; i < Q; ++i) {\n    cout << res[i] << \"\\n\";\n  }\n\n}\n",
    "tags": [
      "brute force"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1019",
    "index": "A",
    "title": "Elections",
    "statement": "As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.\n\nElections are coming. You know the number of voters and the number of parties — $n$ and $m$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $i$-th voter $c_i$ bytecoins you can ask him to vote for any other party you choose.\n\nThe United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.",
    "tutorial": "Let's iterate over final number of votes for The United Party of Berland. We can see that all opponents should get less votes than our party, and our party should get at least our chosen number of votes. We can sort all voters by their costs, and solve the problem in two passes. First, if we need to get $x$ votes, we should definitely buy all cheap votes for parties that have at least $x$ votes. Second, if we don't have $x$ votes yet, we should by the cheapest votes to get $x$ votes. We can see that this solution is optimal: consider the optimal answer, and see how many votes The United Party got. We tried such number of votes, and we tried to achieve this number of votes by cheapest way, so we couldn't miss the optimal answer. This can be implemented in $O(n^2 \\log n)$ or even $O(n \\log n)$.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1019",
    "index": "B",
    "title": "The hat",
    "statement": "\\textbf{This is an interactive problem.}\n\nImur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by $n$ students, where $n$ is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant $i$ and participant $i + 1$ ($1 ≤ i ≤ n - 1$) are adjacent, as well as participant $n$ and participant $1$. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.\n\nAs you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers $i$ and $i+{\\frac{n}{2}}$ sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.\n\nYou can ask questions of form «which number was received by student $i$?», and the goal is to determine whether the desired pair exists in no more than $60$ questions.",
    "tutorial": "Let $a(i)$ be a number given to the $i$-th student. Let's introduce function $b(i)=a(i)-a(i+{\\frac{n}{2}})$. As $n$ is even, $\\frac{n t}{2}$ is integer, and $b(i)$ is defined correctly. Notice two facts: first, $b(i)=-b(i+{\\frac{n}{2}})$, and second, $|b(i)-b(i+1)|\\in\\{-2,0,2\\}$. The problem is to find an $i$ such that $b(i) = 0$. Second note leads us to observation that all $b(i)$ have the same oddity. So, let's find $b(0)$, and if it is odd, then there is no answer, and we need to print $- 1$ - all $b(i)$ have the same oddity (odd), and zero, as a number of different oddity, won't appear in $b(i)$. Otherwise, suppose we know $b(0)$, and it is equal to $x$ (without loss of generality $x > 0$). Notice that $b(0+{\\textstyle{\\frac{n}{2}}})=-b(0)=-x$. As we remember from second observation that all $b(i)$ have the same oddity, and neighboring numbers differ by no more than 2, we can use discrete continuity. Lemma: if you have two indices $i$ and $j$ with values $b(i)$ and $b(j)$, then on segment between $i$ and $j$ there are all values with the same oddity from $min(b(i), b(j))$ to $max(b(i), b(j))$. Indeed, as neighboring $b$ differ by no more than 2, we couldn't skip any number with the same oddity. Now we can use a binary search. At the start $l = 0$, $r={\\frac{n}{2}}$, and values $b(l)$ and $b(r)$ are even numbers with the different signs. By lemma, on segment between $l$ and $r$ there is a zero that we want to find. Let's take $m={\\frac{l+r}{2}}$. If $b(m) = 0$, we found the answer. Otherwise, based on sign of $b(m)$ we can replace one of $l$, $r$ in binary search to $m$, and reduce the problem to the same with smaller size. There will be no more than $\\log n$ iterations, and as calculation of $b(i)$ requires two queries, we solved the problem in $2\\log n$ queries.",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1019",
    "index": "C",
    "title": "Sergey's problem",
    "statement": "Sergey just turned five years old! When he was one year old, his parents gave him a number; when he was two years old, his parents gave him an array of integers. On his third birthday he received a string. When he was four, his mother woke him up in a quiet voice, wished him to be a good boy and gave him a rooted tree. Today he celebrates his birthday again! He found a directed graph without loops as a present from his parents.\n\nSince Sergey is a very curious boy, he immediately came up with a thing to do. He decided to find a set $Q$ of vertices in this graph, such that no two vertices $x, y \\in Q$ are connected by an edge, and it is possible to reach any vertex $z \\notin Q$ from some vertex of $Q$ in no more than two moves.\n\nAfter a little thought, Sergey was able to solve this task. Can you solve it too?\n\nA vertex $y$ is reachable from a vertex $x$ in at most two moves if either there is a directed edge $(x,y)$, or there exist two directed edges $(x,z)$ and $(z, y)$ for some vertex $z$.",
    "tutorial": "Let's build the solution by induction. Suppose we have to solve the problem for $n$ vertices and we can solve this problem for all $k$ ($k < n$). Take an arbitrary vertex $A$. Remove $A$ from the graph, as well as all vertices that $A$ has an outgoing edge to. Resulting graph has less than $n$ vertices, so by induction, we can build the solution for it. Let's call the answer set for the new graph $M$. After this we have two cases: either there is an edge from set $M$ to vertex $A$ or there is not. If there is an edge from $M$ to $A$, then $M$ is a correct answer for initial graph, because every removed vertex can be reached from $M$ in at most two steps. Otherwise, we can add $A$ to $M$ and, again, this set will satisfy the required condition. This also proves the answer always exists. How to implement it? Let's iterate over all vertices in order from $1$ to $n$ and remember whether each vertex is currently present in the graph or not. Whenever we encounter a currently present vertex $u$, we save $u$ and mark $u$ and all vertices reachable from $u$ in one step as removed. After that, we go over all saved vertices in reverse order and add them to answer set if it's not reachable from the answer set in one step. This solutions works in $O(V + E)$ time and space.",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1019",
    "index": "D",
    "title": "Large Triangle",
    "statement": "\\begin{quote}\nThere is a strange peculiarity: if you connect the cities of Rostov, Taganrog and Shakhty, peculiarly, you get a triangle\n\\hfill «Unbelievable But True»\n\\end{quote}\n\nStudents from many different parts of Russia and abroad come to Summer Informatics School. You marked the hometowns of the SIS participants on a map.\n\nNow you decided to prepare an interesting infographic based on this map. The first thing you chose to do is to find three cities on this map, such that they form a triangle with area $S$.",
    "tutorial": "Let's fix one of edge of the triangle. We need to find a third point so the area of triangle is equal to $s$. Notice that area of triangle is proportional to scalar product of the normal vector to the chosen edge and radius-vector of third point. So, if we had all other points sorted by scalar product with normal to the edge, we could find the third point by binary search. It is the main goal of the solution. There are $O(n^2)$ interesting directions - two normal vectors to each of edges, defined by all pairs of points. For each pair of points you can see that for some directions one of points has larger scalar product with this direction, and for some other direction another point has larger scalar product. We can see that points $a_i$ and $a_j$ have the same scalar product with vector $rotate_{90}(a_i-a_j)$ - with normal vector edge defined by these two points. If you look at all directions on unit circle, this vector and the opposite vector change the order of points $a_i$ and $a_j$ in sorted order by scalar product. Also, as there are no three points lying on one line, these two points will be neighboring in sorting order by this direction. So, we can maintain the sorting order. Let's take all events on unit circle as all vectors of type $rotate_{90}(a_i - a_j)$, and for every such event swap two neighboring points $a_i$ and $a_j$ in sorting order. After swap we can do a binary search for third point to find a required triangle with area $s$. This works in $O(n^2 \\log n)$ time.",
    "tags": [
      "binary search",
      "geometry",
      "sortings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1019",
    "index": "E",
    "title": "Raining season",
    "statement": "By the year 3018, Summer Informatics School has greatly grown. Hotel «Berendeetronik» has been chosen as a location of the school. The camp consists of $n$ houses with $n-1$ pathways between them. It is possible to reach every house from each other using the pathways.\n\nEverything had been perfect until the rains started. The weather forecast promises that rains will continue for $m$ days. A special squad of teachers was able to measure that the $i$-th pathway, connecting houses $u_i$ and $v_i$, before the rain could be passed in $b_i$ seconds. Unfortunately, the rain erodes the roads, so with every day the time to pass the road will increase by $a_i$ seconds. In other words, on the $t$-th (from zero) day after the start of the rain, it will take $a_i \\cdot t + b_i$ seconds to pass through this road.\n\nUnfortunately, despite all the efforts of teachers, even in the year 3018 not all the students are in their houses by midnight. As by midnight all students have to go to bed, it is important to find the maximal time between all the pairs of houses for each day, so every student would know the time when he has to run to his house.\n\nFind all the maximal times of paths between every pairs of houses after $t=0$, $t=1$, ..., $t=m-1$ days.",
    "tutorial": "Let's use centroid decomposition on edges of the tree to solve this task. Centroid decomposition on edges is about finding an edge that divides a tree of $n$ vertices into two subtrees, each of which contains no more than $cn$ vertices for some fixed constant $c<1$. It is easy to see that such decomposition has only logarithmic depth in terms of initial number of nodes. There is a problem - it is easy to construct an example, where it is impossible to choose such edge. For example, star tree with $n$ vertices and $n-1$ leaves is fine for that - every edge has a leaf as one of its ends. To solve this problem, we can add new vertices and edges to the tree. Let's fix arbitrary root of the tree, and make tree binary: if some vertex $v$ has more than two children - $u_1, u_2, \\ldots, u_k$, we may replace vertex $v$ to vertex $v_1$ with children $u_1$ and $v_2$, $v_2$ with children $u_2$ and $v_3$, and so on. Edge between $v_i$ and $u_i$ has the same length as in initial tree between $v$ and $u_i$, and edge between $v_i$ and $v_{i+1}$ has length 0. It is easy to see that the distance between any pair of vertices in new tree is the same as the distance between them in initial tree. Also, the degree of the each vertex is at most three, so we can take the centroid of the new tree, and there will be a subtree of centroid with $[{n \\over 3}; {n \\over 2}]$ vertices, so, we will wind an edge that we need in centroid decomposition on edges. After choosing an edge for decomposition, we should solve the problem recursively for subtrees, and find the diameters which contain the chosen edge. It is quite easy - we can calculate a linear function of length of path from . After that we need to take one linear function from both subtrees and get the sum of these functions. We can say that if length of path looks like linear function $at+b$, then we have a point $(a, b)$ on plane. Then it is obvious that we should only keep points on the convex hull of this set. Instead of choosing pairs of vertices in subtrees of edge we can just build a Minkowski sum of their convex hulls - we will get exactly the diameters that contain the chosen edge in linear time. After computing the convex hulls of diameters containing each edge in decomposition, we can put all these points in one big array and build one big convex hull for all these points again. This way we get all interesting diameters in the tree. To get the length of diameter in time $t$, we have to find the most distant point on convex hull in direction $(t, 1)$. Building the convex hull for all points for diameters containing the edge of decomposition works in $O(k \\log k)$, where $k$ is size of current connected component. With knowledge that we have logarithmic depth of decomposition, overall complexity is $O(n \\log^2 n)$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1020",
    "index": "A",
    "title": "New Building for SIS",
    "statement": "You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.\n\nThe building consists of $n$ towers, $h$ floors each, where the towers are labeled from $1$ to $n$, the floors are labeled from $1$ to $h$. There is a passage between any two adjacent towers (two towers $i$ and $i + 1$ for all $i$: $1 ≤ i ≤ n - 1$) on every floor $x$, where $a ≤ x ≤ b$. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building.\n\n\\begin{center}\n{\\small The picture illustrates the first example.}\n\\end{center}\n\nYou have given $k$ pairs of locations $(t_{a}, f_{a})$, $(t_{b}, f_{b})$: floor $f_{a}$ of tower $t_{a}$ and floor $f_{b}$ of tower $t_{b}$. For each pair you need to determine the minimum walking time between these locations.",
    "tutorial": "In this problem you need to find a shortest path between some locations in a building. You need to look at some cases to solve this problem. First, if locations are in the same tower ($t_{a} = t_{b}$), you don't need to use a passages between two towers at all, and answer is $f_{a} - f_{b}$. In other case, you have to use some passage between towers. Obviously, you need to use only passage on one floor. The easiest way to do this is to write down interesting floors in array - the floor where you start, the floor where you end your path, first and last floors with passages. After that you can choose interesting floor $x$ where you will use a passage, check if there is a passage at this floor ($a  \\le  x  \\le  b$), and update answer with an expression like $|t_{a} - t_{b}| + |f_{a} - x| + |f_{b} - x|$. Another method is to choose a floor where you use a passage by case handling. If you start on the floor $f_{a}$, and there is a passage, you can just use this passage. Otherwise, you choose between floors $a$ and $b$, whichever is closer to the start.",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1020",
    "index": "B",
    "title": "Badge",
    "statement": "In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $n$ students doing yet another trick.\n\nLet's assume that all these students are numbered from $1$ to $n$. The teacher came to student $a$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $p_a$.\n\nAfter that, the teacher came to student $p_a$ and made a hole in his badge as well. The student in reply said that the main culprit was student $p_{p_a}$.\n\nThis process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.\n\nAfter that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.\n\nYou don't know the first student who was caught by the teacher. However, you know all the numbers $p_i$. Your task is to find out for every student $a$, who would be the student with two holes in the badge if the first caught student was $a$.",
    "tutorial": "In this problem you are given a graph, with one outgoing edge from each vertex. You are asked which vertex is first to be visited twice, if you start in some vertex, and go by outgoing edge from current vertex until you visited some vertex twice. The problem can be solved by straightforward implementation. You choose a starting vertex (which student is first to get a hole in their badge), and keep the current vertex, and for all vertices how many times it was visited. After transition to the next vertex you just check if it has been already visited, and update visited mark for it. This solution works in $O(n^2)$, and is very easy in implementation. It can be optimized to $O(n)$, but it was not necessary in this problem. It an easy and useful exercise left to reader.",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1023",
    "index": "A",
    "title": "Single Wildcard Pattern Matching",
    "statement": "You are given two strings $s$ and $t$. The string $s$ consists of lowercase Latin letters and \\textbf{at most one} wildcard character '*', the string $t$ consists only of lowercase Latin letters. The length of the string $s$ equals $n$, the length of the string $t$ equals $m$.\n\nThe wildcard character '*' in the string $s$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $s$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $s$ to obtain a string $t$, then the string $t$ matches the pattern $s$.\n\nFor example, if $s=$\"aba*aba\" then the following strings match it \"abaaba\", \"abacaba\" and \"abazzzaba\", but the following strings do not match: \"ababa\", \"abcaaba\", \"codeforces\", \"aba1aba\", \"aba?aba\".\n\nIf the given string $t$ matches the given string $s$, print \"YES\", otherwise print \"NO\".",
    "tutorial": "If there is no wildcard character in the string $s$, the answer is \"YES\" if and only if strings $s$ and $t$ are equal. In the other case let's do the following thing: while both strings are not empty and their last characters are equal, let's erase them. Then do the same for the first characters, i.e. while both strings are not empty and their first characters are equal, let's erase them. Now if $s$ is empty or $s=$\"*\" the answer is \"YES\", otherwise the answer is \"NO\".",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1023",
    "index": "B",
    "title": "Pair of Toys",
    "statement": "Tanechka is shopping in the toy shop. There are exactly $n$ toys in the shop for sale, the cost of the $i$-th toy is $i$ burles. She wants to choose two toys in such a way that their total cost is $k$ burles. How many ways to do that does she have?\n\nEach toy appears in the shop exactly once. Pairs $(a, b)$ and $(b, a)$ are considered equal. Pairs $(a, b)$, where $a=b$, are not allowed.",
    "tutorial": "The problem is to calculate the number of ways to choose two distinct integers from $1$ to $n$ with sum equals $k$. If $k \\le n$ then the answer is $\\lfloor\\frac{k}{2}\\rfloor$ because this is the number of ways to choose two distinct integers from $1$ to $k - 1$ with the sum equals $k$. Otherwise let $mn = n - k$ will be the minimum possible term in the correct pair of integers. Also let $mx = n$ will be the maximum possible term in the correct pair of integers. Then the answer is $max(0, \\lfloor\\frac{mx - mn + 1}{2}\\rfloor)$ because this is the number of ways to choose two distinct integers from $mn$ to $mx$ with the sum equals $k$.",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1023",
    "index": "C",
    "title": "Bracket Subsequence",
    "statement": "A bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\"), and \")(\", \"(\" and \")\" are not.\n\nSubsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.\n\nYou are given a regular bracket sequence $s$ and an integer number $k$. Your task is to find a regular bracket sequence of length exactly $k$ such that it is also a subsequence of $s$.\n\nIt is guaranteed that such sequence always exists.",
    "tutorial": "Let the array $used$ of $n$ boolean values describe if the corresponding bracket of string $s$ is included in answer or not. The algorithm goes like this: iterate over the string from $1$ to $n$, maintain the stack of positions of currenly unmatched opening brackets $st$. When opening bracket is met at position $i$, push $i$ to $st$, and when closing bracket is met, set $used[st.top()] = True$, $used[i] = True$ and pop the top of $st$. When $k$ values are marked True in $used$ then break, iterate from $1$ to $n$ and print the brackets at positions where $used[i] = True$. Obviously, this algorithm produces a subsequence of $s$ of length $k$. Why will it be a regular bracket sequence? The requirements for it are: no prefix contains more closing brackets than opening ones; the total number of closing bracket equals the total number of opening brackets. The first requirement is met by construction, we couldn't pop more elements from the stack than it had. The second requirement is also met as we marked brackets in pairs. Overall complexity: $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1023",
    "index": "D",
    "title": "Array Restoration",
    "statement": "Initially there was an array $a$ consisting of $n$ integers. Positions in it are numbered from $1$ to $n$.\n\nExactly $q$ queries were performed on the array. During the $i$-th query some segment $(l_i, r_i)$ $(1 \\le l_i \\le r_i \\le n)$ was selected and values of elements on positions from $l_i$ to $r_i$ inclusive got changed to $i$. The order of the queries couldn't be changed and all $q$ queries were applied. It is also known that every position from $1$ to $n$ got covered by at least one segment.\n\nWe could have offered you the problem about checking if some given array (consisting of $n$ integers with values from $1$ to $q$) can be obtained by the aforementioned queries. However, we decided that it will come too easy for you.\n\nSo the enhancement we introduced to it is the following. Some set of positions (possibly empty) in this array is selected and values of elements on these positions are set to $0$.\n\nYour task is to check if this array can be obtained by the aforementioned queries. Also if it can be obtained then restore this array.\n\nIf there are multiple possible arrays then print any of them.",
    "tutorial": "Let's firstly solve the problem as if there are no zeroes in the given array. Let $l_i$ be the leftmost occurrence of $i$ in the array and $r_i$ be the rightmost occurrence of $i$. The main observation is that you can choose segments $(l_i; r_i)$ for the corresponding queries and this sequence will be correct if and only if there exists any answer for the given array. If there is no occurrence of some value in the array then you can put the segment for it under the segment of some greater value. If there is no occurrence of $q$ in the array then the answer doesn't exist. For sure, segment $(l_i, r_i)$ is the minimum segment you can choose. You can expand it in both directions but it will never matter: these positions either will get covered by the segments of greater values or will replace the smaller values with $i$ (and turn YES to NO if the answer existed). Finally, each position will be covered as each element is a left bound of a segment, a right bound of a segment or just covered by the segment of its value. That problem can be solved with any data structure that allows you to assign values on segment and get the value of every position (segment tree, sqrt decomposition). However, all the queries are performed offline (the resulting values are only needed after the queries) and the operation can be replaced with assigning maximum of the current value of element and the value of the query. This can also be done using set. For each position you should keep the segments which start there and end there. For each segment $(l_i, r_i)$ you push $i$ to the list for $l_i$ and push $i$ to the list for $r_i$. Now you iterate from $1$ to $n$, when entering $i$ you add all values of opening segments to the set, assign the element at position $i$ the maximum value of the set and remove all the values of closing segments from the set. The complexity of this algorithm is $O(n \\log q)$. This algorithm can be easily applied to the problem with zeroes in the array. At the beginning you fill the resulting array with ones. After you performed the algorithm with set on the values from $1$ to $q$, while constructing the segments from the non-zero elements of the given array, you check if the values you assigned are less or equal than the corresponding values of the given array. If that holds then the resulting array is already the correct one. Otherwise the answer doesn't exist. The only corner case there is if no value $q$ was in array and there were some zeroes. That way you should just change any zero to $q$. Overall complexity: $O(n \\log q)$.",
    "tags": [
      "constructive algorithms",
      "data structures"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1023",
    "index": "E",
    "title": "Down or Right",
    "statement": "This is an interactive problem.\n\nBob lives in a square grid of size $n \\times n$, with rows numbered $1$ through $n$ from top to bottom, and columns numbered $1$ through $n$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $n$.\n\nBob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move \\textbf{down or right} to an adjacent cell, if it is allowed.\n\nYou can ask at most $4 \\cdot n$ queries of form \"?$r_1$ $c_1$ $r_2$ $c_2$\" ($1 \\le r_1 \\le r_2 \\le n$, $1 \\le c_1 \\le c_2 \\le n$). The answer will be \"YES\" if Bob can get from a cell $(r_1, c_1)$ to a cell $(r_2, c_2)$, and \"NO\" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is \"NO\" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least $n - 1$, i.e. the following condition must be satisfied: $(r_2 - r_1) + (c_2 - c_1) \\ge n - 1$.\n\nIt's guaranteed that Bob can get from the top-left corner $(1, 1)$ to the bottom-right corner $(n, n)$ and your task is to find a way to do it. You should print the answer in form \"! S\" where $S$ is a string of length $2 \\cdot n - 2$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by $1$, the right move increases the second coordinate by $1$. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.",
    "tutorial": "Hint: Move from $(1, 1)$ to the middle by asking queries 'query(row, col, n, n)', starting with $row = col = 1$. Similarly, move from $(n, n)$ to the middle by asking queries 'query(1, 1, row, col)'. How to ensure that we will meet in the same cell in the middle? The unusual condition in this problem is $(r_2 - r_1) + (c_2 - c_1) \\ge n - 1$ that must be satisfied in every query. Without it, the following simple code would solve the problem: This program starts in $(1,1)$ and greedily moves down if after this move we could still reach the cell $(n, n)$. Otherwise, it must move right. But in this problem, we can only get half the way this method. We must stop at the antidiagonal (one of cells: $(1, n), (2, n-1), \\ldots, (n, 1)$). So maybe it's a good idea to move backward from $(n, n)$ the same way, and meet at the antidiagonal? Not really :( We indeed can apply the same algorithm starting from $(n, n)$ and going towards $(1, 1)$, but possibly we will end in a different cell in the middle. It's possible even for an empty grid, without any blocked cells. We are very close to a correct solution, but let's focus on a thought process for a moment. Analyzing some other possible approach might help with that. The limitation about the distance at least $n - 1$ is just enough to ask a query between $(1, 1)$ and a cell from the antidiagonal, and also that cell and $(n, n)$. This pseudocode would print reasonable candidates for a middle cell in our path - a cell reachable from $(1, 1)$ and from which the $(n, n)$ is reachable. But after choosing some cell like this, it isn't that easy to find a way to the corner cells. In our first idea, we were able to get from $(1, 1)$ to one of the reasonable candidates and from $(n, n)$ to one of the reasonable candidates, but maybe a different one. Now a very important observation is: the first piece of code in this editorial will reach the leftmost (equivalently: downmost) reasonable candidate, because we always prefer moving down instead of right. For example, in an empty we would reach the bottom left corner. Now we see that we need to guarantee the same when moving from $(n, n)$. So we should prioritize left direction over the up direction:",
    "tags": [
      "constructive algorithms",
      "interactive",
      "matrices"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1023",
    "index": "F",
    "title": "Mobile Phone Network",
    "statement": "You are managing a mobile phone network, and want to offer competitive prices to connect a network.\n\nThe network has $n$ nodes.\n\nYour competitor has already offered some connections between some nodes, with some fixed prices. These connections are bidirectional. There are initially $m$ connections the competitor is offering. The $i$-th connection your competitor is offering will connect nodes $fa_i$ and $fb_i$ and costs $fw_i$.\n\nYou have a list of $k$ connections that you want to offer. It is guaranteed that this set of connection does not form any cycle. The $j$-th of these connections will connect nodes $ga_j$ and $gb_j$. These connections are also bidirectional. The cost of these connections have not been decided yet.\n\nYou can set the prices of these connections to any arbitrary integer value. These prices are set independently for each connection. After setting the prices, the customer will choose such $n - 1$ connections that all nodes are connected in a single network and the total cost of chosen connections is minimum possible. If there are multiple ways to choose such networks, the customer will choose an arbitrary one that also maximizes the number of your connections in it.\n\nYou want to set prices in such a way such that \\textbf{all} your $k$ connections are chosen by the customer, and the sum of prices of your connections is maximized.\n\nPrint the maximum profit you can achieve, or $-1$ if it is unbounded.",
    "tutorial": "Consider the forest of your edges. Let's add edges into this forest greedily from our competitor's set in order of increasing weight until we have a spanning tree. Remember, we don't need to sort, the input is already given in sorted order. Now, consider the competitor's edges one by one by increasing weight. Since we have a spanning tree, each competitor edge spans some path on our tree. To process a competitor's edge, we can collapse all the nodes in the path into one single large node, and fix the cost of our edges along this path to be equal to the cost of the currently considered competitor's edge. We know this is an upper bound on cost since if any were higher, then by the cycle property of MSTs, the customer can ignore one of the higher cost edge on this cycle and choose the customer's edge instead. In addition, this still allows us to satisfy the condition of the customer choosing all of our edges, since by Kruskal's algorithm, the customer will try to greedily add our edges first into their spanning tree and won't be able to add the customer edge since it now forms a cycle). This shows that this cost is the maximum possible profit since we have an upper bound on each edge, and this upper bound also gives a valid solution. To determine if our answer can be unbounded, we can check if any of our edges remains uncollapsed after processing all competitor edges. To do this efficiently, we can just do it naively (even without needing to compute LCAs!). To show it's already fast enough, there are only a total of at most $n$ merges overall and each merge can be done in $\\alpha(n)$ time, where $\\alpha(n)$ is the inverse ackermann function, so the overall complexity is $O(m + (n + k)\\alpha(n))$. Unfortunately, this is too hard to separate from solution with logarithms, so those were also allowed to pass (though TL might have been a bit more strict in those cases).",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1023",
    "index": "G",
    "title": "Pisces",
    "statement": "A group of researchers are studying fish population in a natural system of lakes and rivers. The system contains $n$ lakes connected by $n - 1$ rivers. Each river has integer length (in kilometers) and can be traversed in both directions. It is possible to travel between any pair of lakes by traversing the rivers (that is, the network of lakes and rivers form a tree).\n\nThere is an unknown number of indistinguishable fish living in the lakes. On day $1$, fish can be at arbitrary lakes. Fish can travel between lakes by swimming the rivers. Each fish can swim a river $l$ kilometers long in any direction in $l$ days. Further, each fish can stay any number of days in any particular lake it visits. No fish ever appear or disappear from the lake system. Each lake can accomodate any number of fish at any time.\n\nThe researchers made several observations. The $j$-th of these observations is \"on day $d_j$ there were at least $f_j$ distinct fish in the lake $p_j$\". Help the researchers in determining the smallest possible total number of fish living in the lake system that doesn't contradict the observations.",
    "tutorial": "First, how do we find the answer in any time complexity? Let us construct a partially ordered set where each element is a single fish in one of the observations. For two elements $x = (v_1, d_1)$ and $y = (v_2, d_2)$ we put $x < y$ if $x$ and $y$ could possibly be two occurences of the same fish one after the other, that is, there is enough time to get from one observation to another, so that $\\rho(v_1, v_2) \\leq d_2 - d_1$, where $\\rho(v_1, v_2)$ is the distance between the tree vertices, and $d_1$ and $d_2$ are respective day numbers of the two observations. We can now see that the answer is the smallest number of chains needed to cover all the vertices (a chain is a set of pairwise comparable elements of a p.o.set). By Dilworth's theorem, this is equal to the size of the largest antichain (a set of pairwise incomparable elements). Clearly, if a largest antichain contains a fish from an observation, than it must include all fish from this observation as well. We can now solve the problem in something like $O(2^k)$ time by trying all subsets of observations. To get a better complexity we need to use the tree structure. To start, how do we check if a set of observations forms an antichain? Here's one criterion that works: Proposition. A set $S$ of observations is an antichain iff: For each subtree of the root $v$, a subset of $S$ lying in that subtree is an antichain. There exists a time moment $T$ such that it is impossible to reach $v$ at time $T$ from any observation in $S$ (possibly travelling back in time). Indeed, if both of these conditions hold, than for any two observations $(v_1, d_1)$ and $(v_2, d_2)$ happening in different subtrees we have $\\rho(v_1, v_2) = \\rho(v, v_1) + \\rho(v, v_2) > |d_1 - T| + |d_2 - T| \\geq |d_1 - d_2|$, hence these observations are incomparable. On the other hand, if $S$ is an antichain, for any observation $(v_i, d_i) \\in S$ there is an interval of time moments $(l_i, r_i)$ such that we cannot reach the root at any of times in $(l_i, r_i)$. If two observations $i$ and $j$ are incomparable, then$(l_i, r_i) \\cap (l_j, r_j) \\neq \\varnothing$. But since we have a set of intervals with pairwise non-empty intersections, they must all share a common point, hence our time moment $T$ exists. Note that in some cases $T$ is necessarily a non-integer: if there are two vertices at distance $1$ from the root, and there are observations happening at days $1$ and $2$ respectively at these vertices, than any $T \\in (1, 2)$ will suffice. However, $T$ can always be either an integer or a half-integer, hence we can multiply all times and distances by $2$ and assume $T$ is integer. The solution is going to be subtree dynamic programming $dp_{v, t}$ - the total weight of the largest antichain in the subtree of $v$ such that no observation can reach $v$ at time $t$. Recalculation is a bit tricky, so let's go step by step. First, if we have values of $dp_{v, t}$, and no observations take place at $v$, how do we change $dp_{v, t}$ as we travel up the edge to the top of $v$? If the length of this edge is $l$, then the new values $dp'_{v, t}$ satisfy $dp'_{v, t} = \\max_{t' = t - l}^{t + l} dp_{v, t'}$. Let's call this procedure \"advancing $l$ steps forward\". How do we account for observations at $v$? For an observation $(v, t)$ with $f$ fishes we cannot simply add $f$ to $dp_{v, t}$ since we can obviously reach $v$ at time $t$ from this observation. Instead, the correct procedure is: advance the values $1$ step; apply $dp'_{v, t} = \\max(dp'_{v, t}, dp_{v, t} + f)$ for all observations; advance the new values $l - 1$ steps. Finally, to combine the answers from the subtrees $u_1, \\ldots, u_k$ of a vertex $v$ (after the advancements were made in them), we simply add them element-wise for each $t$: $dp_{v, t} = \\sum_{u_i} dp_{u_i, t}$. Of course, we cannot store the DP values themselves since there are too much of them to store. Instead, we will need to use a data structure that will maintain a piecewise constant function. More specifically, let us maintain the positions where the function changes values: for each $t$ such that $dp_{v, t} \\neq dp_{v, t + 1}$ we store the pair $(t, dp_{v, t + 1} - dp_{v, t})$. How all of the above manipulations look like in terms of this difference structure? Element-wise sum of two functions is simply the union of the difference sets. (We may want to combine the differences with the same $t$ value, but for most implementations this is not necessary) When we advance $l$ steps forward, the borders with positive differences will more $l$ units to the left, and negative differences will move to the right. When two borders collide, then some of them get eliminated. Consider the function $10, 1, 5$, with two differences $(1, -9)$ and $(2, 4)$. After advancing this one step, the new function is $10, 10, 5$, so there is now a single difference $(2, -5)$. If we keep track of when and where these collisions take place, we can make changes to the structure accordingly. The structure of choice here is a treap of differences. When we add two functions, we insert all elements of the smaller treap into the larger one; a standard argument shows that at most $O(k \\log k)$ insertions will take place overall. To keep track of collisions, we'll have to maintain collision times for all adjacent border pairs, and store the minimal value in the root of each subtree. This may seem cumbersome, but every adjacent pair of elements occurs either as (the rightmost vertex in the left subtree of $v$, $v$), or ($v$, the leftmost vertex in the right subtree of $v$), hence the standard relax function in the treap implementation can handle this. One further detail is that we don't want to change the time values in our treaps. Instead, we'll use \"lazy\" time shifting, that is, we'll keep an additional value $\\Delta$ associated with each treap, and assume that for entries $(t, d)$ with $d > 0$ the actual time should be $t - \\Delta$, and with $d < 0$ the time should be $t + \\Delta$. This way, we won't need to actually change anything in the treap when advancing (apart from resolving collisions). The total complexity of this solution is $O(n + k \\log^2 k)$.",
    "tags": [
      "data structures",
      "flows",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1025",
    "index": "A",
    "title": "Doggo Recoloring",
    "statement": "Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.\n\nThe committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.\n\nUnfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color $x$ such that there are currently \\textbf{at least two} puppies of color $x$ and recolor \\textbf{all} puppies of the color $x$ into some arbitrary color $y$. Luckily, this operation can be applied multiple times (including zero).\n\nFor example, if the number of puppies is $7$ and their colors are represented as the string \"abababc\", then in one operation Slava can get the results \"zbzbzbc\", \"bbbbbbc\", \"aaaaaac\", \"acacacc\" and others. However, if the current color sequence is \"abababc\", then he can't choose $x$='c' right now, because currently only one puppy has the color 'c'.\n\nHelp Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.",
    "tutorial": "It's easy to see that, if there exists such a color $x$ that at least two puppies share this color, the answer is \"Yes\" as we can eliminate colors one by one by taking the most numerous color and recoloring all puppies of this color into some other (the number of colors will decrease, but the more-than-one property for the most numerous color will hold, so apply induction). If all puppies' colors are distinct, the answer is \"No\" except for the case when $n = 1$ (since there's no need to recolor the only puppy).",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1025",
    "index": "B",
    "title": "Weakened Common Divisor",
    "statement": "During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.\n\nFor a given list of pairs of integers $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$ their WCD is arbitrary integer greater than $1$, such that it divides at least one element in each pair. WCD may not exist for some lists.\n\nFor example, if the list looks like $[(12, 15), (25, 18), (10, 24)]$, then their WCD can be equal to $2$, $3$, $5$ or $6$ (each of these numbers is strictly greater than $1$ and divides at least one number in each pair).\n\nYou're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.",
    "tutorial": "The obvious solution of finding all divisors of all numbers in $\\mathcal{O}(n \\cdot \\sqrt{a_{max}})$ definitely won't pass, so we have to come up with a slight optimization. One may notice that is's sufficient to take a prime WCD (because if some value is an answer, it can be factorized without losing the answer property). To decrease the number of primes to check, let's get rid of the redundant ones. Take an arbitrary pair of elements ($a_i$, $b_i$) and take the union of their prime factorizations. It's easy to see at this point that the cardinality of this union doesn't exceed $2 \\cdot \\log{a_{max}}$. The rest is to check whether there exists such prime that divides at least one element in each pair in $\\mathcal{O}(n \\cdot \\log{a_{max}})$ time.",
    "tags": [
      "brute force",
      "greedy",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1025",
    "index": "C",
    "title": "Plasticine zebra",
    "statement": "Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras.\n\nInspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now wants to select several consequent (contiguous) pieces of alternating colors to create a zebra. Let's call the number of selected pieces the length of the zebra.\n\nBefore assembling the zebra Grisha can make the following operation $0$ or more times. He splits the sequence in some place into two parts, then reverses each of them and sticks them together again. For example, if Grisha has pieces in the order \"bwbbw\" (here 'b' denotes a black strip, and 'w' denotes a white strip), then he can split the sequence as bw|bbw (here the vertical bar represents the cut), reverse both parts and obtain \"wbwbb\".\n\nDetermine the maximum possible length of the zebra that Grisha can produce.",
    "tutorial": "Imagine just for a second, that in reality our string is cyclic with a cut at point $0$ and clockwise traversal direction. Now let's apply the cut & reverse operation at point $i$. The key fact here is that nothing happens to the cyclic string - it's just the traversal direction and the cut point (now $i$ instead of $0$) that change. Here's an example. Let the string be $bwwbwbbw$ and we cut it after the $2$-nd letter ($1$-indexed). It's easy to see that it transforms to $wbwbbwbw$, which equals the initial one after shifting it to the left by $2$ and inverting the traversal direction. This observation helps us see that all strings obtained within these operations are in fact just cuts of one cyclic strings with precision up to traversal direction. In other words, it's enough to find the longest zebra inside the cyclic string - this value will be the answer to the problem.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1025",
    "index": "D",
    "title": "Recovering BST",
    "statement": "Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees!\n\nRecently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and sees his creation demolished, he'll get extremely upset.\n\nTo not let that happen, Dima has to recover the binary search tree. Luckily, he noticed that any two vertices connected by a direct edge had their greatest common divisor value exceed $1$.\n\nHelp Dima construct such a \\textbf{binary search tree} or determine that it's impossible. The definition and properties of a binary search tree can be found here.",
    "tutorial": "Let $\\mathcal{dp}(l, r, root)$ be a dp determining whether it's possible to assemble a tree rooted at $root$ from the subsegment $[l..r]$. It's easy to see that calculating it requires extracting such $root_{left}$ from $[l..root - 1]$ and $root_{right}$ from $[root + 1..right]$ that: $\\mathcal{gcd}(a_{root}, a_{root_{left}}) > 1$; $\\mathcal{gcd}(a_{root}, a_{root_{right}}) > 1$; $\\mathcal{dp}(l, root - 1, root_{left}) = 1$; $\\mathcal{dp}(root + 1, r, root_{right}) = 1$. This can be done in $\\mathcal{O}(r - l)$ provided we are given all $\\mathcal{dp}(x, y, z)$ values for all subsegments of $[l..r]$. Considering a total of $\\mathcal{O}(n^3)$ dp states, the final complexity is $\\mathcal{O}(n^4)$. That's too much. Let's turn our dp into $\\mathcal{dp_{new}}(l, r, side)$ where $side$ can be either $0$ or $1$ - is it possible to make a tree from $[l..r]$ rooted at $l - 1$ or $r + 1$ respectively. It immediately turns out that $\\mathcal{dp}(l, r, root)$ is inherited form $\\mathcal{dp_{new}}(l, root - 1, 1)$ and $\\mathcal{dp_{new}}(root + 1, r, 0)$. Now we have $\\mathcal{O}(n^2)$ states, but at the same time all transitions are performed in linear time; thus final complexity is $\\mathcal{O}(n^3)$ which is sufficient to pass.",
    "tags": [
      "brute force",
      "dp",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1025",
    "index": "E",
    "title": "Colored Cubes",
    "statement": "Vasya passes all exams! Despite expectations, Vasya is not tired, moreover, he is ready for new challenges. However, he does not want to work too hard on difficult problems.\n\nVasya remembered that he has a not-so-hard puzzle: $m$ colored cubes are placed on a chessboard of size $n \\times n$. The fact is that $m \\leq n$ and all cubes have distinct colors. Each cube occupies exactly one cell. Also, there is a designated cell for each cube on the board, the puzzle is to place each cube on its place. The cubes are fragile, so in one operation you only can move one cube onto one of four neighboring by side cells, if only it is empty. Vasya wants to be careful, so each operation takes exactly one second.\n\nVasya used to train hard for VK Cup Final, so he can focus his attention on the puzzle for at most $3$ hours, that is $10800$ seconds. Help Vasya find such a sequence of operations that all cubes will be moved onto their designated places, and Vasya won't lose his attention.",
    "tutorial": "We're gonna show how to turn an arbitrary arrangement of cubes into the arrangement where $i$-th cube is located at $(i, i)$ (we call such an arrangement basic) in no more than $2*n^{2}$ operations. For simplicity, we imply that we have exactly $n$ cubes where $n$ is even. Say we have some arrangement where $i$-th cube occupies some cell $(x_i, y_i)$. On the first step, we turn it into the arrangement where all cubes have distinct $x$ coordinates. In order to do this, we sort cubes in ascending order of their $x$ coordinates $x$ (with ties broken arbitrarily) . If cube $i$ is at position $j$ in the sorted list, we say that its desired coordinates are $(j, y_i)$. It's easy to check that such choice always allows to move at least one cube from its current position to the desired one through the $y = y_i$ line. If we perform this operation $n$ times, we'll move all cubes to their desired positions. In addition, the maximum number of operations will occur if all the cubes were initially located on the line $x = 1$ or $x = n$, and in this case the number of operations will be equal to $0 + 1 + ... + (n-1)$ < $n^{2}/2$. The formal proof of this inequality can be given using the induction principle. Indeed, the base ($n = 1$) is obvious. Now let the statement be true for all $k \\leq n$. Let's prove that if the number of cubes (and the size of the board) changes from $n$ to $(n+1)$, the upper limit of the number of operations increases by no more than $n$. Consider the cube $i$ with maximum $x$ coordinate which we have to move to $x_i = n$. If initially $x_i$ is less than $n$, we move this cube to the desired position in no more than $n$ operations, and other $n$ cubes have coordinates $x_j \\leq n$ which implies the upper limit of $n*(n-1)/2$ operations by definition. But if $x_i$ is initially $n$, we don't have to move it whereas each of the remaining $n$ cubes requires one more additional (i.e $n$ total) operation since we added only one diagonal. In total we'll make a total of $n + n*(n-1)/2 = n*(n+1)/2$ operations. Now all $x$ coordinates are distinct and that means that nothing restricts us from changing their $y$ coordinates. Let's move the cubes in such a way that $i$-th cube ends at position $y_i = i$. One cube can be processed in no more than $min(i-1, n-i)$ operations. According to this, we need at most $(n-1) + (n-2) + ... + n/2 + n/2 + ... + (n-1) = 2*((n/2)*(n/2 + n - 1)/2) = 3*n*(n-2)/4 \\leq 3*n^{2}/4$ operations in total. Now we obtain an arrangement where all $y$ coordinates are also distinct. If we apply the same operation to cubes' $x$ coordinates, we will end up with $i$-th cube at position $(i, i)$. This requires no more than $n^{2}/2 + 2*(3*n^{2}/4) = 2*n^{2}$ operations. Now we can switch any arrangement to the basic one. Let's get the list of operations for turning the initial position to basic and the final position to basic. Now it's sufficient to reverse one of the lists and concatenate these actions. This yields no more than $4*n^{2} \\leq 10000$ operations in total. Note that this estimate is quite rough; however, this is enough under given constraints.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1025",
    "index": "F",
    "title": "Disjoint Triangles",
    "statement": "A point belongs to a triangle if it lies inside the triangle or on one of its sides. Two triangles are disjoint if there is no point on the plane that belongs to both triangles.\n\nYou are given $n$ points on the plane. No two points coincide and no three points are collinear.\n\nFind the number of different ways to choose two disjoint triangles with vertices in the given points. Two ways which differ only in order of triangles or in order of vertices inside triangles are considered equal.",
    "tutorial": "The most challenging part of the problem is to think of the way how to count each pair of triangles exactly once. It turns out, that this can be done in a nice and geometrical way. Each pair of triangles has exactly two inner tangents between them. Moreover, exactly one of them (if we direct tangent from point of the first polygon to the point of the second polygon) leaves the first rectangle on the right side and the other tangent leaves it on the left side. So let's brute-force the inner tangent. If we continue the tangent to draw the line and count the number of points on the left and on the right of it, say $k_1$ and $k_2$ respectively, then we simply need to add $\\frac{k_1 (k_1 - 1)}{2} \\frac{k_2 (k_2 - 1)}{2}$ to our answer, since if we select arbitrary pair of vertices on each halfplanes, together with tangent points we will form a pair of triangles with such a tangent. The question is how to count $k_1$ and $k_2$ for each tangent efficiently. If the points would be sorted by direction, perpendicular to the tangent, we could have answered this query with binary search (since points of one halfplane form a prefix of the sorted array and the other - suffix). However, if we wrote down all the interesting directions, sort them by angle, and make a scanline on it, we could maintain the points in sorted order. Basically, points $a_i$ and $a_j$ change their order in the sorted array at the direction $rotate_{90}(a_i - a_j)$, and, since there are no three points on one line, these points are neighbours in the sorted array at the moment of the swap. The complexity is $\\mathcal{O}(n^2 \\log(n))$ since we need to sort all $n^2$ directions and for each direction make a binary search on the sorted array.",
    "tags": [
      "geometry"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1025",
    "index": "G",
    "title": "Company Acquisitions",
    "statement": "There are $n$ startups. Startups can be active or acquired. If a startup is acquired, then that means it has exactly one active startup that it is following. An active startup can have arbitrarily many acquired startups that are following it. An active startup cannot follow any other startup.\n\nThe following steps happen until there is exactly one active startup. The following sequence of steps takes exactly 1 day.\n\n- Two distinct active startups $A$, $B$, are chosen uniformly at random.\n- A fair coin is flipped, and with equal probability, $A$ acquires $B$ or $B$ acquires $A$ (i.e. if $A$ acquires $B$, then that means $B$'s state changes from active to acquired, and its starts following $A$).\n- When a startup changes from active to acquired, all of its previously acquired startups become active.\n\nFor example, the following scenario can happen: Let's say $A$, $B$ are active startups. $C$, $D$, $E$ are acquired startups under $A$, and $F$, $G$ are acquired startups under $B$:\n\n\\begin{center}\n{\\small Active startups are shown in red.}\n\\end{center}\n\nIf $A$ acquires $B$, then the state will be $A$, $F$, $G$ are active startups. $C$, $D$, $E$, $B$ are acquired startups under $A$. $F$ and $G$ have no acquired startups:\n\nIf instead, $B$ acquires $A$, then the state will be $B$, $C$, $D$, $E$ are active startups. $F$, $G$, $A$ are acquired startups under $B$. $C$, $D$, $E$ have no acquired startups:\n\nYou are given the initial state of the startups. For each startup, you are told if it is either acquired or active. If it is acquired, you are also given the index of the active startup that it is following.\n\nYou're now wondering, what is the expected number of days needed for this process to finish with exactly one active startup at the end.\n\nIt can be shown the expected number of days can be written as a rational number $P/Q$, where $P$ and $Q$ are co-prime integers, and $Q \\not= 0 \\pmod{10^9+7}$. Return the value of $P \\cdot Q^{-1}$ modulo $10^9+7$.",
    "tutorial": "You can solve this most likely by brute forcing small cases and looking for a pattern. Here's a proof of the pattern. Let's define a potential of a startup with $k$ followers to be equal to $2^k - 1$. For example, an active startup with zero followers has potential zero. Now, in one day, if we choose a startup with $p$ followers, and a startup with $q$ followers, the expected change in sum of potentials is equal to $\\frac{1}{2}((2^{p+1} - 1 - 2^p + 1) - 2^q + 1) + \\frac{1}{2}((2^{q+1} - 1 - 2^q + 1) - 2^p + 1) = 1$, regardless of the values of $p$ and $q$. The potential of the final state is $2^{n-1} - 1$, and we can compute the current potential in linear time, so the expected number of turns is the difference between them. To prove this more rigorously, we can use show that this process is a martingale, so we can use https://en.wikipedia.org/wiki/Optional_stopping_theorem to show that the expected number of days is exactly equal to this difference.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1027",
    "index": "A",
    "title": "Palindromic Twist",
    "statement": "You are given a string $s$ consisting of $n$ lowercase Latin letters. $n$ is even.\n\nFor each position $i$ ($1 \\le i \\le n$) in string $s$ you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed \\textbf{exactly once}.\n\nFor example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.\n\nThat way string \"codeforces\", for example, can be changed to \"dpedepqbft\" ('c' $\\rightarrow$ 'd', 'o' $\\rightarrow$ 'p', 'd' $\\rightarrow$ 'e', 'e' $\\rightarrow$ 'd', 'f' $\\rightarrow$ 'e', 'o' $\\rightarrow$ 'p', 'r' $\\rightarrow$ 'q', 'c' $\\rightarrow$ 'b', 'e' $\\rightarrow$ 'f', 's' $\\rightarrow$ 't').\n\nString $s$ is called a palindrome if it reads the same from left to right and from right to left. For example, strings \"abba\" and \"zz\" are palindromes and strings \"abca\" and \"zy\" are not.\n\nYour goal is to check if it's possible to make string $s$ a palindrome by applying the aforementioned changes to every position. Print \"YES\" if string $s$ can be transformed to a palindrome and \"NO\" otherwise.\n\nEach testcase contains several strings, for each of them you are required to solve the problem separately.",
    "tutorial": "If some string can't be transformed to palindrom then it has some pair of positions $(i, n - i + 1)$ with different letters on them (as no such pair affects any other pair). Thus you need to check each pair for $i$ from $1$ to $\\frac n 2$ and verify that the distance between the corresponding letters is either $0$ or $2$. Overall complexity: $O(T \\cdot n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n    int T;\n    cin >> T;\n    \n    int n;\n    string s;\n    forn(_, T){\n        cin >> n >> s;\n        bool ok = true;\n        forn(i, n){\n            int k = abs(s[i] - s[n - i - 1]);\n            if (k > 2 || k % 2 == 1){\n                ok = false;\n                break;\n            }\n        }\n        cout << (ok ? \"YES\" : \"NO\") << endl;\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1027",
    "index": "B",
    "title": "Numbers on the Chessboard",
    "statement": "You are given a chessboard of size $n \\times n$. It is filled with numbers from $1$ to $n^2$ in the following way: the first $\\lceil \\frac{n^2}{2} \\rceil$ numbers from $1$ to $\\lceil \\frac{n^2}{2} \\rceil$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $n^2 - \\lceil \\frac{n^2}{2} \\rceil$ numbers from $\\lceil \\frac{n^2}{2} \\rceil + 1$ to $n^2$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $\\lceil\\frac{x}{y}\\rceil$ means division $x$ by $y$ rounded up.\n\nFor example, the left board on the following picture is the chessboard which is given for $n=4$ and the right board is the chessboard which is given for $n=5$.\n\nYou are given $q$ queries. The $i$-th query is described as a pair $x_i, y_i$. The answer to the $i$-th query is the number written in the cell $x_i, y_i$ ($x_i$ is the row, $y_i$ is the column). Rows and columns are numbered from $1$ to $n$.",
    "tutorial": "Let's see the following fact: if we will decrease $\\lceil \\frac{n^2}{2} \\rceil$ from all numbers written in cells with an odd sum of coordinates and write out the numbers obtained on the board from left to right from top to bottom, the sequence will looks like $1, 1, 2, 2, \\dots, \\lceil \\frac{n^2}{2} \\rceil, \\lceil \\frac{n^2}{2} \\rceil$ for even $n$ (for odd $n$ there is only one number $\\lceil \\frac{n^2}{2} \\rceil$ at the end of the sequence, but, in general, it does not matter). Let's try to find out the answer for some query ($x, y$). Let $cnt=(x - 1) \\cdot n + y$ (1-indexed). There $cnt$ is the position of our cell in order of the written sequence. The first approximation of the answer is $\\lceil\\frac{cnt}{2}\\rceil$. But now we are remember that we decreased $\\lceil \\frac{n^2}{2} \\rceil$ from all numbers written in cells with an odd sum of coordinates. So if $x + y$ is even then the answer is $\\lceil\\frac{cnt}{2}\\rceil$, otherwise the answer is $\\lceil\\frac{cnt}{2}\\rceil + \\lceil\\frac{n^2}{2}\\rceil$. Note that you should be careful with integer overflow in C++, Java or similar languages. 64-bit datatype is quite enough. Time complexity: $O(q)$.",
    "code": "import sys\n\nlst = sys.stdin.readlines()\nn, q = map(int, lst[0].split())\n\nfor i in range(q):\n    x, y = map(int, lst[i + 1].split())\n    cnt = (x - 1) * n + y\n    ans = (cnt + 1) // 2\n    if ((x + y) % 2 == 1): ans += (n * n + 1) // 2\n    sys.stdout.write(str(ans) + '\\n')",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1027",
    "index": "C",
    "title": "Minimum Value Rectangle",
    "statement": "You have $n$ sticks of the given lengths.\n\nYour task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks.\n\nLet $S$ be the area of the rectangle and $P$ be the perimeter of the rectangle.\n\nThe chosen rectangle should have the value $\\frac{P^2}{S}$ minimal possible. The value is taken without any rounding.\n\nIf there are multiple answers, print any of them.\n\nEach testcase contains several lists of sticks, for each of them you are required to solve the problem separately.",
    "tutorial": "Let's work with the formula a bit: $\\frac{P^2}{s}$ $=$ $\\frac{4(x + y)^2}{xy}$ $=$ $4(2 + \\frac x y + \\frac y x)$ $=$ $8 + 4(\\frac x y + \\frac y x)$ Let $a = \\frac x y$, then the formula becomes $8 + 4(a + \\frac 1 a)$. Considering $x \\ge y$, $a = \\frac x y \\ge 1$, thus $(a + \\frac 1 a)$ is strictly increasing and has its minimum at $a = 1$. So the solution will be to sort the list, extract the pairs of sticks of equal length and check only neighbouring pairs in sorted order for the answer. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\ntypedef long long li;\n\nusing namespace std;\n\nconst int N = 1000 * 1000 + 13;\n\nint n, m;\nint a[N];\nint b[N];\n\nint main() {\n    int T;\n    scanf(\"%d\", &T);\n    forn(_, T){\n        scanf(\"%d\", &n);\n        forn(i, n)\n            scanf(\"%d\", &a[i]);\n        sort(a, a + n);\n    \n        m = 0;\n        forn(i, n - 1){\n            if (a[i] == a[i + 1]){\n                b[m++] = a[i];\n                ++i;\n            }\n        }\n    \n        int A = b[0], B = b[1];\n        li P2 = (A + B) * li(A + B);\n        li S = A * li(B);\n    \n        forn(i, m - 1){\n            li p2 = (b[i] + b[i + 1]) * li(b[i] + b[i + 1]);\n            li s = b[i] * li(b[i + 1]);\n            if (s * P2 > S * p2){\n                A = b[i];\n                B = b[i + 1];\n                S = s;\n                P2 = p2;\n            }\n        }\n    \n        printf(\"%d %d %d %d\\n\", A, A, B, B);\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1027",
    "index": "D",
    "title": "Mouse Hunt",
    "statement": "Medicine faculty of Berland State University has just finished their admission campaign. As usual, about $80\\%$ of applicants are girls and majority of them are going to live in the university dormitory for the next $4$ (hopefully) years.\n\nThe dormitory consists of $n$ rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number $i$ costs $c_i$ burles. Rooms are numbered from $1$ to $n$.\n\nMouse doesn't sit in place all the time, it constantly runs. If it is in room $i$ in second $t$ then it will run to room $a_i$ in second $t + 1$ without visiting any other rooms inbetween ($i = a_i$ means that mouse won't leave room $i$). It's second $0$ in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.\n\nThat would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from $1$ to $n$ at second $0$.\n\nWhat it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?",
    "tutorial": "Mouse jumps on a cycle at some point, no matter the starting vertex, thus it's always the most profitable to set traps on cycles. The structure of the graph implies that there are no intersecting cycles. Moreover, mouse will visit each vertex of the cycle, so it's enough to set exactly one trap on each cycle. The only thing left is to find the cheapest vertex of each cycle. This can be done by a simple dfs. Overall complexity: $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) fore(i, 0, n)\n\n#define mp make_pair\n#define pb push_back\n\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define sqr(a) ((a) * (a))\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<li, li> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n    return out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n    out << \"[\";\n    forn(i, sz(v)) {\n        if(i) out << \", \";\n        out << v[i];\n    }\n    return out << \"]\";\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nint n;\nvector<int> a, c;\n\ninline bool read() {\n    if(!(cin >> n))\n        return false;\n    c.assign(n, 0);\n    a.assign(n, 0);\n\n    forn(i, n)\n        assert(scanf(\"%d\", &c[i]) == 1);\n    forn(i, n) {\n        assert(scanf(\"%d\", &a[i]) == 1);\n        a[i]--;\n    }\n    return true;\n}\n\nvector< vector<int> > cycles;\n\nvector<char> used;\nvector<int> path;\n\nvoid dfs(int v) {\n    path.push_back(v);\n    used[v] = 1;\n\n    int to = a[v];\n    if(used[to] != 2) {\n        if(used[to] == 1) {\n            cycles.emplace_back();\n\n            int id = sz(path) - 1;\n            while(path[id] != to)\n                cycles.back().push_back(path[id--]);\n            cycles.back().push_back(to);\n        } else\n            dfs(to);\n    }\n    path.pop_back();\n    used[v] = 2;\n}\n\ninline void solve() {\n    used.assign(n, 0);\n\n    forn(i, n) {\n        if (!used[i])\n            dfs(i);\n    }\n\n    li ans = 0;\n    for(auto &cur : cycles) {\n        int mn = c[cur[0]];\n        for(int v : cur)\n            mn = min(mn, c[v]);\n        ans += mn;\n    }\n    cout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    cout << fixed << setprecision(15);\n\n    if(read()) {\n        solve();\n\n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1027",
    "index": "E",
    "title": "Inverse Coloring",
    "statement": "You are given a square board, consisting of $n$ rows and $n$ columns. Each tile in it should be colored either white or black.\n\nLet's call some coloring beautiful if each pair of adjacent rows are either the same or different in every position. The same condition should be held for the columns as well.\n\nLet's call some coloring suitable if it is beautiful and there is no \\textbf{rectangle} of the single color, consisting of at least $k$ tiles.\n\nYour task is to count the number of suitable colorings of the board of the given size.\n\nSince the answer can be very large, print it modulo $998244353$.",
    "tutorial": "You can notice that every coloring can be encoded by the two binary strings of length $n$. You firstly generate one string to put as a first row and then use the second string to mark if you put the first string as it is or inverting each color. That way, you can also guess that the area of maximum rectangle of a single color you will get in you coloring is the product of maximum lengths of segments of a single color in both of the strings. Let's consider the following dynamic programming solution: $dp[i][j][k]$ is the number of binary strings of length $i$, such the current last segment of a single color has length $j$ and the maximum segment of a single color has length $k$. The transitions are: $dp[i + 1][j + 1][max(k, j + 1)]$ += $dp[i][j][k]$ - color the new tile the same as the previous one; $dp[i + 1][1][max(k, 1)]$ += $dp[i][j][k]$ - color the new tile the opposite from the previous one. The starting state is $dp[0][0][0] = 1$. Let's sum the values of this dp to an array $cnt[i]$ - the number of binary strings of length $n$ such that the maximum segment of a single color in them has length $i$. You can also do another dp to calculate this not in $O(n^3)$ but in $O(n^2)$ using some partial sums in it. Finally, you iterate over the first side of the resulting rectangle (the maximum length of segment of a single color in a first binary string) and multiply the number of ways to get it by the total number of ways to get the second side of the resulting rectangle, so that the area doesn't $(k - 1)$. Overall complexity: $O(n^3)$ or $O(n^2)$.",
    "code": "def norm(x):\n    return (x % 998244353 + 998244353) % 998244353\n\nn, k = map(int, input().split())\n\ndp1 = [0]\ndp2 = [0]\n\nfor i in range(n):\n    l = [1]\n    cur = 0\n    for j in range(n + 1):\n        cur += l[j]\n        if(j > i):\n            cur -= l[j - i - 1]\n        cur = norm(cur)\n        l.append(cur)\n    dp1.append(l[n])\n    dp2.append(norm(dp1[i + 1] - dp1[i]))\n\nans = 0\nfor i in range(n + 1):\n    for j in range(n + 1):\n        if(i * j < k):\n            ans = norm(ans + dp2[i] * dp2[j])\n\nans = norm(ans * 2)\n\nprint(ans)",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1027",
    "index": "F",
    "title": "Session in BSU",
    "statement": "Polycarp studies in Berland State University. Soon he will have to take his exam. He has to pass exactly $n$ exams.\n\nFor the each exam $i$ there are known two days: $a_i$ — day of the first opportunity to pass the exam, $b_i$ — day of the second opportunity to pass the exam ($a_i < b_i$). Polycarp can pass at most one exam during each day. For each exam Polycarp chooses by himself which day he will pass this exam. He has to pass all the $n$ exams.\n\nPolycarp wants to pass all the exams as soon as possible. Print the minimum index of day by which Polycarp can pass all the $n$ exams, or print -1 if he cannot pass all the exams at all.",
    "tutorial": "This problem has many approaches (as Hall's theorem, Kuhn algorithm (???) and so on), I will explain one (or two) of them. Let's find the answer using binary search. It is obvious that if we can pass all the exams in $k$ days we can also pass them in $k+1$ days. For the fixed last day $k$ let's do the following thing: firstly, if there exists some exam with the day of the first opportunity to pass it greater than $k$, then the answer for the day $k$ is false. Next, while there exist exams having only one possibility to pass them (because of the upper bound of the maximum possible day or constraints imposed by the other exams), we choose this day for this exam and continue (after choosing such day there can appear some new exams with the same property). Now there are no exams having only one day to pass them. Let's take a look on the graph where vertices represent days and edges represent exams (the edge between some vertices $u$ and $v$ ($u < v$) exists iff there is an exam with the first day to pass it equal to $u$ and the second day to pass it equal to $v$). Let's remove all the exams for which we identified the answer. Now let's take a look on the connected components of this graph and analyze the problem which we have now. Our problem is to choose exactly one vertex incident to each edge of the connected component such that no vertex is chosen twice (and we have to do this for all the connected components we have). Let $cntv$ be the number of vertices in the current connected component and $cnte$ be the number of edges in the current connected component. The answer for the connected component is true iff $cnte \\le cntv$, for obvious reasons. There is very easy constructive method to see how we can do this. If $cnte < cntv$ then the current connected component is a tree. Let's remove some leaf of this tree and set it as the chosen vertex for the edge incident to this leaf (and remove this edge too). If $cnte = cntv$ then let's remove all leaves as in the algorithm for the tree. For the remaining cycle let's choose any edge and any vertex incident to it, set this vertex as the chosen to this edge and remove them. Now we have a chain. Chain is a tree, so let's apply the algorithm for the tree to this chain. So, if for some connected component $c$ holds $cnte_c > cntv_c$ then the answer for the day $k$ is false. Otherwise the answer is true. Overall complexity $O(n \\log n)$ because of numbers compressing or using logarithmic data structures to maintain the graph. Also there is another solution (which can be too slow, I don't know why it works). It is well-known fact that if we will apply Kuhn algorithm to the some bipartite graph in order of increasing indices of vertices of the left part, then the last vertex in the left part of this graph which is in the matching will be minimum possible. Oh, that's what we need! Let the left part of this graph consist of days and the right part consist of exams. The edge between some vertices $u$ from the left part and $v$ from the right part exists iff $u$ is one of two days to pass the exam $v$. Let's apply Kuhn algorithm to this graph, considering days in increasing order. The first day when matching becomes $n$ (all exams are in the matching) will be the answer. I don't know its complexity, really. Maybe it works too fast because of the special properties of the graph... If someone can explain in which time it works I will very happy!",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nmt19937 rnd(time(NULL));\n\nconst int N = 2 * 1000 * 1000 + 11;\nconst int INF = 1e9;\n\nint n;\nint a[N][2];\n\nvector<int> nums;\nint m;\n\nvector<int> g[N];\nint mt[N];\nint used[N];\nint T = 1;\n\nbool try_kuhn(int v) {\n    if (used[v] == T)\n        return false;\n    used[v] = T;\n    \n    for (auto to : g[v]) {\n        if (mt[to] == -1) {\n            mt[to] = v;\n            return true;\n        }\n    }\n    \n    for (auto to : g[v]) {\n        if (try_kuhn(mt[to])) {\n            mt[to] = v;\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < 2; ++j) {\n            scanf(\"%d\", &a[i][j]);\n            nums.push_back(a[i][j]);\n        }\n    }\n    \n    sort(nums.begin(), nums.end());\n    nums.resize(unique(nums.begin(), nums.end()) - nums.begin());\n    m = nums.size();\n    \n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < 2; ++j) {\n            a[i][j] = lower_bound(nums.begin(), nums.end(), a[i][j]) - nums.begin();\n        }\n    }\n    \n    for (int i = 0; i < n; ++i) {\n        g[a[i][0]].push_back(i);\n        g[a[i][1]].push_back(i);\n    }\n\n    memset(mt, -1, sizeof(mt)); \n    int match = 0;\n    for (int i = 0; i < m; ++i) {\n        if (try_kuhn(i)) {\n            ++T;\n            ++match;\n            if (match == n) {\n                printf(\"%d\\n\", nums[i]);\n                return 0;\n            }\n        }\n    }\n    \n    puts(\"-1\");\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "dsu",
      "graph matchings",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1027",
    "index": "G",
    "title": "X-mouse in the Campus",
    "statement": "The campus has $m$ rooms numbered from $0$ to $m - 1$. Also the $x$-mouse lives in the campus. The $x$-mouse is not just a mouse: each second $x$-mouse moves from room $i$ to the room $i \\cdot x \\mod{m}$ (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the $x$-mouse is unknown.\n\nYou are responsible to catch the $x$-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the $x$-mouse enters a trapped room, it immediately gets caught.\n\nAnd the only observation you made is $\\text{GCD} (x, m) = 1$.",
    "tutorial": "Some notes: At first, there is $x^{-1} \\mod{m}$ since $(x, m) = 1$ (lets define $\\text{GCD}(a,b)$ as $(a, b)$). That means that for each $v = 0..m-1$ there is exactly one $u$ that $u \\cdot x = v$. So if we look at this problem as the graph then it consists of cycles (consider loops as cycles of length one). So we need to know number of cycles in this graph. At second, $(v, m) = (v \\cdot x \\mod{m}, m)$ since $(x, m) = 1$, $v \\cdot x \\mod{m} = v \\cdot x - m \\cdot k$ and $(v, m) \\mid v$ and $(v, m) \\mid m$. So all $v$ can be divided in groups by its $(v,m)$. And we can calculate number of cylces in each group independently. Let fix some $\\text{GCD}$ equal to $g$. All numbers $v$ such that $(v, m) = g$ can be represented as $v = g \\cdot v'$ and $(v', m) = 1$. Number of such $v$ equals to $\\varphi(\\frac{m}{g})$. Moreover $gv' \\cdot x \\equiv gv' \\cdot (x \\mod{\\frac{m}{g}}) \\mod{m}$. Here we can shift from $v$, $x$ and $m$ to $v'$, $(x \\mod{\\frac{m}{g}})$ and $\\frac{m}{g}$. In result we need for each $d \\mid m$ calculate number of cycles created by $x \\mod{d}$ from numbers $v$, that $1 \\le v < d$ and $(v, d) = 1$. Lets set $x = x \\mod{d}$. Next step is to find minimal $k > 0$ such that $x^k \\equiv 1 \\mod{d}$, let's name it order of $x$ or $\\text{ord}(x)$. Then for each $0 \\le i,j < k$ if $i \\neq j$ then $x^i \\not\\equiv x^j$ and $v \\cdot x^i \\not\\equiv v \\cdot x^j$, so each cycle will have length equal to $\\text{ord}(x)$ and number of cycles will be equal to $\\frac{\\varphi(d)}{\\text{ord}(x \\mod d)}$. Last step is calculate $\\text{ord}(x)$ for each $d \\mid m$. There is a fact that $\\text{ord}(x) \\mid \\varphi(d)$ so can try to iterate over all divisors $df$ of $\\varphi(d)$ and check $x^{df} \\equiv 1$ by binary exponentiation (It seems as $O(divs(m)^2 \\log{m})$ but it's faster and author's version work around 2 seconds. It doesn't pass but somebody can write better). But we'll speed it up. Let $\\varphi(d) = p_1^{a_1} p_2^{a_2} \\dots p_k^{a_k}$. So we can independently for each $p_i$ find its minimal power $b_i \\le a_i$ such that $x^{\\varphi(d) \\cdot p_i^{b_i - a_i}} \\equiv 1$. We can just iterate over all $p_i$ and $a_i$ since $\\sum{a_i} = O(\\log{m})$. Some words about finding $\\varphi(d)$ - its factorization differs from factorization of $d$ just by lowering degrees of primes and adding factorizations of some $(p_i - 1)$. But we can manually find factorization of $(p_i - 1)$ with memorization (or even without it) since $\\sum{\\sqrt{p_i}} \\le \\prod{\\sqrt{p_i}} = O(\\sqrt{m})$. So our steps are next: factorize $m$, recursively iterate over all divisors of $m$, find $\\varphi(d)$ and $\\text{ord}(x \\mod d)$, and add to the answer $\\frac{\\varphi(d)}{\\text{ord}(x \\mod d)}$. Result complexity is $O(\\sqrt{m} + \\text{divs}(m) \\cdot \\log^2{m})$. And the last note is how to multiply $a, b < 10^{14}$ modulo $mod \\le 10^{14}$. You can use binary multiplification which will give you extra $\\log{m}$ what is not critically in this task (in C++, of course). Or you can use multiplification from hashes, which will work with 64 bit double, since it's only $10^{14}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<li, li> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nli m, x;\n\ninline bool read() {\n    if(!(cin >> m >> x))\n        return false;\n    return true;\n}\n\nmap< li, vector<pt> > dFact;\nvector<pt> fact(li v) {\n    if(dFact.count(v))\n        return dFact[v];\n    \n    li oldv = v;\n    vector<pt> fs;\n    for(li d = 2; d * d <= v; d++) {\n        int cnt = 0;\n        while(v % d == 0)\n            v /= d, cnt++;\n        \n        if(cnt > 0)\n            fs.emplace_back(d, cnt);\n    }\n    if(v > 1)\n        fs.emplace_back(v, 1), v = 1;\n    return dFact[oldv] = fs;\n}\n\nvector<pt> merge(const vector<pt> &a, const vector<pt> &b) {\n    vector<pt> ans;\n    int u = 0, v = 0;\n    while(u < sz(a) && v < sz(b)) {\n        if(a[u].x < b[v].x)\n            ans.push_back(a[u++]);\n        else if(a[u].x > b[v].x)\n            ans.push_back(b[v++]);\n        else {\n            ans.emplace_back(a[u].x, a[u].y + b[v].y);\n            u++, v++;\n        }\n    }\n    while(u < sz(a))\n        ans.push_back(a[u++]);\n    while(v < sz(b))\n        ans.push_back(b[v++]);\n    return ans;\n}\n\nli getPw(li a, li b) {\n    li ans = 1;\n    fore(i, 0, b)\n        ans *= a;\n    return ans;\n}\n\nli mul(li a, li b, li mod) {\n    li m = li(ld(a) * b / mod);\n    li rem = a * b - m * mod;\n    while(rem < 0)\n        rem += mod;\n    while(rem >= mod)\n        rem -= mod;\n    return rem;\n}\n\nli binPow(li a, li k, li mod) {\n    li ans = 1 % mod;\n    while(k > 0) {\n        if(k & 1)\n            ans = mul(ans, a, mod);\n        a = mul(a, a, mod);\n        k >>= 1;\n    }\n    return ans;\n}\n\nli findOrder(li x, li mod, const vector<pt> &f) {\n    li phi = 1;\n    fore(i, 0, sz(f)) fore(k, 0, f[i].y)\n        phi *= f[i].x;\n        \n    if(phi == 1 || x == 0)\n        return 1;\n    \n    li ord = 1;\n    fore(i, 0, sz(f)) {\n        li basePw = phi;\n        fore(k, 0, f[i].y)\n            basePw /= f[i].x;\n        \n        li curV = binPow(x, basePw, mod);\n        \n        int curPw = -1;\n        fore(k, 0, f[i].y + 1) {\n            if(curV != 1)\n                curPw = k;\n            curV = binPow(curV, f[i].x, mod);\n        }\n        \n        ord *= getPw(f[i].x, curPw + 1);\n    }\n    return ord;\n}\n\nvector<pt> fm;\nvector<int> pw;\n\nli calc(int pos, li dv) {\n    if(pos >= sz(fm)) {\n        vector<pt> cf = fm;\n        fore(i, 0, sz(fm))\n            cf[i].y = max(pw[i] - 1, 0);\n        \n        li phi = dv;\n        fore(i, 0, sz(fm)) {\n            if(pw[i] > 0) {\n                cf = merge(cf, fact(fm[i].x - 1));\n                phi -= phi / fm[i].x;\n            }\n        }\n        li k = findOrder(x % dv, dv, cf);\n        return phi / k;\n    }\n    \n    li ans = 0;\n    fore(i, 0, fm[pos].y + 1) {\n        pw[pos] = i;\n        ans += calc(pos + 1, dv);\n        dv *= fm[pos].x;\n    }\n    return ans;\n}\n\ninline void solve() {\n    fm = fact(m);\n    \n    pw.assign(sz(fm), 0);\n    li ans = calc(0, 1);\n    \n    cout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1028",
    "index": "A",
    "title": "Find Square",
    "statement": "Consider a table of size $n \\times m$, initially fully white. Rows are numbered $1$ through $n$ from top to bottom, columns $1$ through $m$ from left to right. Some square inside the table with \\textbf{odd} side length was painted black. Find the center of this square.",
    "tutorial": "There are lots of possible solutions. For example, run through rows from the top until you find one with at least one 'B'. Do the same for the bottom. Average of the two row numbers is the number of the middle row. Now find the first and last 'B' in that row, their average value is the number of the middle column. Alternative approach is to print $\\dfrac{\\sum\\limits_{i=1}^{cnt}x_i}{cnt}, \\dfrac{\\sum\\limits_{i=1}^{cnt}y_i}{cnt}$, where $cnt$ is the number of black points and $\\{(x_i, y_i)\\}_{i=1}^{cnt}$ is a list of black points.",
    "code": "static class SquareInside {\n        final int inf = (int) 1e9;\n\n        public void solve(int testNumber, InputReader in, PrintWriter out) {\n            int n = in.readInt(), m = in.readInt();\n            char[][] s = new char[n][];\n            for (int i = 0; i < n; i++) {\n                s[i] = in.readWord().toCharArray();\n            }\n            int minX = inf, maxX = -inf, minY = inf, maxY = -inf;\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < m; j++) {\n                    if (s[i][j] == 'B') {\n                        minX = Math.min(minX, i);\n                        minY = Math.min(minY, j);\n                        maxX = Math.max(maxX, i);\n                        maxY = Math.max(maxY, j);\n                    }\n                }\n            }\n            out.print((minX + maxX) / 2 + 1);\n            out.print(' ');\n            out.println((minY + maxY) / 2 + 1);\n        }\n\n    }",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1028",
    "index": "B",
    "title": "Unnatural Conditions",
    "statement": "Let $s(x)$ be sum of digits in decimal representation of positive integer $x$. Given two integers $n$ and $m$, find some positive integers $a$ and $b$ such that\n\n- $s(a) \\ge n$,\n- $s(b) \\ge n$,\n- $s(a + b) \\le m$.",
    "tutorial": "First note, that if some output is correct for test with $n = 1129$ and $m = 1$, then it's correct for any valid test. After noticing this, we don't need to read input and output one answer for any test. One of many possible answers is $a = 99..9900..001$ (200 nines, 199 zeroes, 1 one) $b = 99..99$ (200 nines) $a + b = 10^{400}$ $s(a) = 1801, s(b) = 1800, s(a+b) = 1$",
    "code": "  int len = 400;\n  cout << string(len, '5') << \"\\n\";\n  cout << (string(len - 1, '4') + '5') << \"\\n\";",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1028",
    "index": "C",
    "title": "Rectangles",
    "statement": "You are given $n$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $(n-1)$ of the given $n$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.\n\nFind any point with integer coordinates that belongs to at least $(n-1)$ given rectangles.",
    "tutorial": "Note that intersection of any number of rectangles is a rectangle too (possibly, empty). Calculate $pref(i)$ - intersection of rectangles with numbers $1, 2, \\ldots, i$, and $suf(i)$ - intersection of rectangles with numbers $i, i + 1, \\ldots, n$. If $i$ is the index of the rectangle not included in the answer, then intersection of $pref(i-1)$ and $suf(i+1)$ must be non-empty. So, for some $i$ this condition is held, and we can print any integer point inside this rectangle.",
    "code": "static class Rectangle {\n        public Point topLeft, bottomRight;\n\n        public Rectangle(Point topLeft, Point bottomRight) {\n            this.topLeft = topLeft;\n            this.bottomRight = bottomRight;\n        }\n\n        public Rectangle intersect(Rectangle other) {\n            if (other == null) {\n                return null;\n            }\n            int x0 = Math.max(topLeft.x, other.topLeft.x);\n            int y0 = Math.max(topLeft.y, other.topLeft.y);\n            int x1 = Math.min(bottomRight.x, other.bottomRight.x);\n            int y1 = Math.min(bottomRight.y, other.bottomRight.y);\n            if (x0 > x1 || y0 > y1) {\n                return null;\n            }\n            return new Rectangle(new Point(x0, y0), new Point(x1, y1));\n        }\n    }\n\n    private void solve() throws IOException {\n        int rectanglesCount = nextInt();\n        Rectangle[] rectangles = new Rectangle[rectanglesCount];\n        for (int i = 0; i < rectanglesCount; i++) {\n            Point topLeft = new Point(nextInt(), nextInt());\n            Point bottomRight = new Point(nextInt(), nextInt());\n            rectangles[i] = new Rectangle(topLeft, bottomRight);\n        }\n        Rectangle[] prefixIntersection = new Rectangle[rectanglesCount + 1];\n        Rectangle[] suffixIntersection = new Rectangle[rectanglesCount + 1];\n        prefixIntersection[0] = suffixIntersection[0] = new Rectangle(\n            new Point(Integer.MIN_VALUE, Integer.MIN_VALUE),\n            new Point(Integer.MAX_VALUE, Integer.MAX_VALUE)\n        );\n        for (int i = 1; i <= rectanglesCount; i++) {\n            prefixIntersection[i] = rectangles[i - 1].intersect(prefixIntersection[i - 1]);\n            suffixIntersection[i] = rectangles[rectanglesCount - i].intersect(suffixIntersection[i - 1]);\n        }\n\n        for (int i = 0; i <= rectanglesCount; i++) {\n            if (prefixIntersection[i] != null) {\n                Rectangle intersection = prefixIntersection[i].intersect(suffixIntersection[rectanglesCount - i - 1]);\n                if (intersection != null) {\n                    out.println(intersection.topLeft);\n                    return;\n                }\n            }\n        }\n        throw new AssertionError();\n    }",
    "tags": [
      "geometry",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1028",
    "index": "D",
    "title": "Order book",
    "statement": "Let's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.\n\nAt every moment of time, every SELL offer has higher price than every BUY offer.\n\n\\textbf{In this problem no two ever existed orders will have the same price.}\n\nThe lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below.\n\n\\begin{center}\n{\\small The presented order book says that someone wants to sell the product at price $12$ and it's the best SELL offer because the other two have higher prices. The best BUY offer has price $10$.}\n\\end{center}\n\nThere are two possible actions in this orderbook:\n\n- Somebody adds a new order of some direction with some price.\n- Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.\n\nIt is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer \"SELL $20$\" if there is already an offer \"BUY $20$\" or \"BUY $25$\" — in this case you just accept the best BUY offer.\n\nYou have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types:\n\n- \"ADD $p$\" denotes adding a new order with price $p$ and unknown direction. The order must not contradict with orders still not removed from the order book.\n- \"ACCEPT $p$\" denotes accepting an existing best offer with price $p$ and unknown direction.\n\nThe directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo $10^9 + 7$. If it is impossible to correctly restore directions, then output $0$.",
    "tutorial": "Keep track of a lower bound for the best sell $s_{best}$ and an upper bound for the best buy $b_{best}$ in the order book. If we have ACCEPT $p$ with $p > s_{best}$ or $p < b_{best}$, it's a contradiction and the answer does not exist. If either $b_{best} = p$ or $s_{best} = p$, then the answer stay the same, and if $b_{best} < p < s_{best}$, the answer is multiplied by $2$, because the removed order could've had any direction. After an ACCEPT $p$, the price of the order above it is the new $s_{best}$ and the price of the order below it is the new $b_{best}$. If in the end there are $m$ orders with undetermined direction, the answer is multiplied by $m+1$. To maintain sets of orders with determined direction (i.e. with prices $p \\le b_{best}$ or $p \\ge s_{best}$) one can use std::set or std::priority_queue in C++ or TreeSet or PriorityQueue in Java.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\nconst int mod = 1e9 + 7;\n\nsigned main() {\n#ifdef LOCAL\n  assert(freopen(\"test.in\", \"r\", stdin));\n#endif\n  int n;\n  cin >> n;\n  map<int, int> a{{INT_MIN, 1}, {INT_MAX, 0}};\n  set<int*> non0{&a.begin()->second};\n  for (int i = 0; i < n; ++i) {\n    string t;\n    int x;\n    cin >> t >> x;\n    if (t == \"ADD\") {\n      auto it = a.lower_bound(x);\n      assert(it != a.begin());\n      --it;\n      int ways = it->second;\n      auto m = a.emplace(x, ways).first;\n      non0.insert(&m->second);\n    } else {\n      auto m = a.find(x);\n      assert(m != a.end() && m != a.begin());\n      auto it = prev(m);\n      auto& w = it->second;\n      w = (w + m->second) % mod;\n      non0.insert(&it->second);\n      non0.erase(&m->second);\n      a.erase(m);\n      for (auto it2 = non0.begin(); it2 != non0.end(); ) {\n        if (*it2 == &it->second) {\n          ++it2;\n        } else {\n          *(*it2) = 0;\n          it2 = non0.erase(it2);\n        }\n      }\n    }\n  }\n  int res = 0;\n  for (auto p : a) {\n    res = (res + p.second) % mod;\n  }\n  cout << res << '\\n';\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1028",
    "index": "E",
    "title": "Restore Array",
    "statement": "While discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers $a_1, a_2, \\ldots, a_n$. Since the talk was long and not promising, Kostya created a new cyclic array $b_1, b_2, \\ldots, b_{n}$ so that $b_i = (a_i \\mod a_{i + 1})$, where we take $a_{n+1} = a_1$. Here $mod$ is the modulo operation. When the talk became interesting, Kostya completely forgot how array $a$ had looked like. Suddenly, he thought that restoring array $a$ from array $b$ would be an interesting problem (unfortunately, not A).",
    "tutorial": "Let's consider a special case at first: all numbers are equal to $M$. Then the answer exists only if $M = 0$ (prove it as an exercise). Now let $M$ be the maximum value in array $b$. Then there exists an index $i$ such that $b_i = M$ and $b_{i-1} < M$ (we assume $b_0 = b_n$). We assume it's $b_n$, otherwise we just shift the array to make this happen. Then $a_n = b_n$ and $a_n < a_1$, $a_i - a_{i+1} = b_i$ for $i < n$, $b_i < a_{i+1}$ for $i < n - 1$ because $b_n$ is maximum value, which is greater than $0$, $b_{n-1} < b_n = M$, $b_n < a_1$ because $b_n < 2 b_n$. Note that without multiplier $2$ before $b_n$ in the formula solution won't work if all numbers in the array except for one are zeroes, because in this case $a_n \\mod a_{1} = 0$. Also instead of $2b_n$ it's possible to use something like $b_n + 10^{10}$, the proof doesn't change much in this case.",
    "code": "void solve(__attribute__((unused)) bool read) {\n  int n;\n  cin >> n;\n  vector<int> b(n, 0);\n  for (int i = 0; i < n; ++i) {\n    cin >> b[i];\n  }\n  int mx = *max_element(all(b));\n  int start_pos = -1;\n  for (int i = 0; i < n; ++i) {\n    if (b[i] == mx && b[(i - 1 + n) % n] != mx) {\n      start_pos = i;\n      break;\n    }\n  }\n  if (start_pos == -1) {\n    if (mx == 0) {\n      cout << \"YES\\n\";\n      for (int i = 0; i < n; ++i) {\n        cout << 1 << \" \\n\"[i + 1 == n];\n      }\n      return;\n    }\n    cout << \"NO\\n\";\n    return;\n  }\n  auto a = b;\n  for (int i = 1; i < n; ++i) {\n    int pos = (start_pos - i + n) % n, prev_pos = (start_pos + 1 - i + n) % n;\n    a[pos] += a[prev_pos];\n    if (i == 1) {\n      a[pos] += mx;\n    }\n  }\n  cout << \"YES\\n\";\n  for (int x : a) {\n    cout << x << \" \";\n  }\n  cout << \"\\n\";\n\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1028",
    "index": "F",
    "title": "Make Symmetrical",
    "statement": "Consider a set of points $A$, initially it is empty. There are three types of queries:\n\n- Insert a point $(x_i, y_i)$ to $A$. It is guaranteed that this point does not belong to $A$ at this moment.\n- Remove a point $(x_i, y_i)$ from $A$. It is guaranteed that this point belongs to $A$ at this moment.\n- Given a point $(x_i, y_i)$, calculate the minimum number of points required to add to $A$ to make $A$ symmetrical with respect to the line containing points $(0, 0)$ and $(x_i, y_i)$. Note that these points are not actually added to $A$, i.e. these queries are independent from each other.",
    "tutorial": "The key idea is the fact that the number of points $(x, y)$, where $x, y \\ge 0$, with fixed $x^2 + y^2 = C$ is not large. Actually it is equal to the number of divisors of $C$ after removing all prime divisors of $4k+3$ form (because if $C$ has such prime divisor, then both $x, y$ are divisible by it). For the problem constraints it can be checked by brute force that maximum number of points with fixed $C \\le 2 \\cdot 10^{10}$ is $M = 144$. Since the circumference with the center in origin is symmetrical with respect to any line containing origin, let's solve the problem for each circumference independently. We maintain two maps: $L$ holds the number of points for each line containing origin, $S$ holds the number of pairs of points that are symmetrical with respect to each line containing origin. When the point $p$ is added or removed on some circumference, we iterate over points $q_i$ lying on it and add or remove $1$ to $S[l(p + q_i)]$, as well as add or remove $1$ to $L[l(p)]$ (where $l(p)$ is the line through $(0, 0)$ and $p$). The answer for query $l$ is $n - L[l] - 2 \\cdot H[l]$, where $n$ is the number of points at the moment. This solution makes $O(q_{changes} \\cdot M + q_{asks})$ queries to map or unordered_map, which is fast enough since $M = 144$.",
    "code": "struct Point {\n  int x, y;\n  Point() {}\n  Point(int x, int y) : x(x), y(y) {}\n  void scan() {\n    cin >> x >> y;\n  }\n  auto key() const {\n    return make_pair(x, y);\n  }\n  bool operator < (const Point& ot) const {\n    return key() < ot.key();\n  }\n  bool operator == (const Point& ot) const {\n    return key() == ot.key();\n  }\n  Point operator + (const Point& ot) const {\n    return Point(x + ot.x, y + ot.y);\n  }\n  li sqr_dist() {\n    return x * 1LL * x + y * 1LL * y;\n  }\n  void normalize() {\n    auto g = gcd(x, y);\n    x /= g;\n    y /= g;\n  }\n};\n\nstruct Hasher {\n  size_t operator () (const Point& pt) const {\n    return pt.x * 2352345 + pt.y;\n  }\n};\n\nenum Type {\n  INSERT = 1,\n  REMOVE = 2,\n  QUERY = 3\n};\n\nstruct Query {\n  Type type;\n  Point pt;\n  int dist_id;\n  void scan() {\n    int type1;\n    cin >> type1;\n    type = Type(type1);\n    pt.scan();\n  }\n};\n\nvoid solve(__attribute__((unused)) bool read) {\n  int Q;\n  cin >> Q;\n  vector<Query> queries(Q);\n  map<li, vector<Point>> all_points;\n  vector<li> dists;\n  set<Point> have;\n  for (int i = 0; i < Q; ++i) {\n    queries[i].scan();\n    auto& pt = queries[i].pt;\n    if (queries[i].type != QUERY) {\n      all_points[pt.sqr_dist()].push_back(pt);\n      dists.push_back(pt.sqr_dist());\n    } else {\n      pt.normalize();\n    }\n  }\n  make_unique(dists);\n  for (auto& q : queries) {\n    q.dist_id = (int)(lower_bound(all(dists), q.pt.sqr_dist()) - dists.begin());\n  }\n  vector<vector<char>> has_point(dists.size());\n  vector<vector<Point>> points_by_dist_id(dists.size());\n  vector<vector<vector<Point>>> sum_points(dists.size());\n  unordered_map<Point, pair<int, int>, Hasher> point_position;\n  for (auto& item : all_points) {\n    make_unique(item.second);\n    int dist_id = (int)(lower_bound(all(dists), item.first) - dists.begin());\n    has_point[dist_id].assign(item.second.size(), false);\n    points_by_dist_id[dist_id] = item.second;\n    sum_points[dist_id].assign(item.second.size(), vector<Point>(item.second.size()));\n    for (int i = 0; i < item.second.size(); ++i) {\n      point_position[item.second[i]] = {dist_id, i};\n      for (int j = 0; j < item.second.size(); ++j) {\n        sum_points[dist_id][i][j] = item.second[i] + item.second[j];\n        sum_points[dist_id][i][j].normalize();\n      }\n    }\n  }\n  unordered_map<Point, int, Hasher> on_line;\n  unordered_map<Point, int, Hasher> good_pairs;\n\n  auto change_on_line = [&] (Point pt, bool add) {\n    pt.normalize();\n    if (add) {\n      ++on_line[pt];\n    } else {\n      assert(on_line[pt] > 0);\n      --on_line[pt];\n    }\n  };\n\n  int n_points = 0;\n  for (auto& cur_q : queries) {\n    auto& pt = cur_q.pt;\n    int dist_id = cur_q.dist_id;\n    if (cur_q.type == INSERT) {\n      ++n_points;\n      int pos = point_position[pt].second;\n      assert(!has_point[dist_id][pos]);\n      change_on_line(pt, true);\n      for (int i = 0; i < points_by_dist_id[dist_id].size(); ++i) {\n        if (i == pos || !has_point[dist_id][i]) {\n          continue;\n        }\n        ++good_pairs[sum_points[dist_id][i][pos]];\n      }\n      has_point[dist_id][pos] = true;\n    } else if (cur_q.type == REMOVE) {\n      --n_points;\n      int pos = point_position[pt].second;\n      assert(has_point[dist_id][pos]);\n      change_on_line(pt, false);\n      for (int i = 0; i < points_by_dist_id[dist_id].size(); ++i) {\n        if (i == pos || !has_point[dist_id][i]) {\n          continue;\n        }\n        --good_pairs[sum_points[dist_id][i][pos]];\n      }\n      has_point[dist_id][pos] = false;\n    } else if (cur_q.type == QUERY) {\n      pt.normalize();\n      cout << n_points - 2 * good_pairs[pt] - on_line[pt] << \"\\n\";\n    }\n  }\n\n}",
    "tags": [
      "brute force"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1028",
    "index": "G",
    "title": "Guess the number",
    "statement": "This problem is interactive.\n\nYou should guess hidden number $x$ which is between $1$ and $M = 10004205361450474$, inclusive.\n\nYou could use up to $5$ queries.\n\nIn each query, you can output an increasing sequence of $k \\leq x$ integers, each between $1$ and $M$, inclusive, and you will obtain one of the following as an answer:\n\n- either the hidden number belongs to your query sequence, in this case you immediately win;\n- or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an $i$ that the hidden number $x$ is between the $i$-th and the $(i+1)$-st numbers of your sequence.\n\nSee the interaction section for clarity.\n\nBe aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.\n\nHacks are allowed only with fixed hidden number. A hack is represented by a single integer between $1$ and $M$. In all pretests the hidden number is fixed as well.",
    "tutorial": "Although it looks strange, the bound on the number from the problem statement is actually tight for $5$ queries of length up to $10^4$. Let's find out how to obtain this number. Let $dp(l, q)$ is the maximum $(r - l)$ such that we can guess the number which is known to be in $[l; r)$ using $q$ queries. The number $l$ is the bound for the number of guesses in the next query, except for the case $l > 10^4$ - then $dp(l, q) = dp(10^4, q)$, since from that time the bound for this number will be $10^4$. The following process calculates $dp(l,q)$: $r_0 = l$ $r_{i + 1} = r_i + dp(r_i, q - 1) + 1$ $dp(l,q) = r_{l + 1} - l$. The complexity of the solution can be estimated as $O(M_q \\cdot M_{guesses}^2)$, where $M_q = 5$ and $M_{guesses} = 10^4$, but actually it's much faster if we calculate $dp$ only for reachable states.",
    "code": "private static final int MAX_WIDTH = 10000;\n    private static final int QUERIES = 5;\n    public static final long INF = 20000000000000000L;\n    long[][] memo = new long[QUERIES + 1][MAX_WIDTH + 1];\n\n    long dp(int guesses, long l) {\n        if (guesses == 0) {\n            return l;\n        }\n        if (l > MAX_WIDTH) {\n            return Math.min(INF, dp(guesses, MAX_WIDTH) + l - MAX_WIDTH);\n        }\n\n        if (memo[guesses][(int) l] != 0) {\n            return memo[guesses][(int) l];\n        }\n        long ans = l;\n        for (int i = 0; i < l; ++i) {\n            ans = dp(guesses - 1, ans);\n            ++ans;\n        }\n        ans = dp(guesses - 1, ans);\n        return memo[guesses][(int) l] = Math.min(ans, INF);\n    }\n    private void run() throws IOException {\n        long l = 1;\n        long r = dp(QUERIES, 1);\n        for (int queriesNext = QUERIES - 1; queriesNext >= 0; --queriesNext) {\n            List<Long> query = new ArrayList<>();\n            long curL = l;\n            for (int i = 0, e = (int)Math.min(l, MAX_WIDTH); i < e; ++i) {\n                long end = dp(queriesNext, curL);\n                query.add(end);\n                curL = end + 1;\n            }\n            assert r == dp(queriesNext, curL);\n            out.print(query.size());\n            for (long x: query) {\n                out.print(\" \");\n                out.print(x);\n            }\n            out.println();\n            out.flush();\n            System.out.flush();\n\n            int ans = readInt();\n            if (ans < 0) {\n                return;\n            }\n            if (ans > 0) {\n                l = query.get(ans - 1) + 1;\n            }\n            if (ans != query.size()) {\n                r = query.get(ans);\n            }\n\n            assert dp(queriesNext, l) == r;\n        }\n    }",
    "tags": [
      "dp",
      "interactive"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1028",
    "index": "H",
    "title": "Make Square",
    "statement": "We call an array $b_1, b_2, \\ldots, b_m$ good, if there exist two indices $i < j$ such that $b_i \\cdot b_j$ is a perfect square.\n\nGiven an array $b_1, b_2, \\ldots, b_m$, in one action you can perform one of the following:\n\n- multiply any element $b_i$ by any prime $p$;\n- divide any element $b_i$ by prime $p$, if $b_i$ is divisible by $p$.\n\nLet $f(b_1, b_2, \\ldots, b_m)$ be the minimum number of actions needed to make the array $b$ good.\n\nYou are given an array of $n$ integers $a_1, a_2, \\ldots, a_n$ and $q$ queries of the form $l_i, r_i$. For each query output $f(a_{l_i}, a_{l_i + 1}, \\ldots, a_{r_i})$.",
    "tutorial": "Firstly, we can divide out all squares from the $a_i$, since they make no difference. Thus, each $a_i$ is then a product of unique primes. If we want to transform $a_i$ and $a_j$ so that their product becomes a square, the cost is the number of primes that appear in one but not in another. Each $a_i$ can have at most $7$ primes ($2 \\cdot 3 \\cdot 5 \\cdot 7 \\cdot 11 \\cdot 13 \\cdot 17 \\cdot 19$ is too big), so at most $128$ divisors. Sweep from left to right, maintaining $dp[val][dist]$ - the rightmost index $i$ so far that $a_i$ can be expressed as $val \\cdot x$, where $x$ has $dist$ primes in its factorization. Also maintain $best[D]$ - the rightmost $l$ such that the answer for the segment $[l; i]$ is $D$, for current index $i$. To add a new $a_i$ in $dp$, consider each divisor $val$ in it, calculate $dist$ as the number of primes in $\\dfrac{a_i}{val}$ and relax $dp[val][dist]$ with $i$. Before doing this for $i$, we need to update $best$ array: for each $val~|~a_i$ and $\\dfrac{a_i}{val}$ having $dist$ primes in factorization and for each $k \\le 7$ relax $best[k + dist]$ with $dp[val][dist]$. Then all queries with right border equal to $i$ can be answered in $O(M_{ans})$ time, where $M_{ans} \\le 14$. The complexity of this solution is $O(n \\cdot M_{primes} \\cdot 2^{M_{primes}} + q \\cdot M_{ans})$, where $M_{primes} = 7$, $M_{ans} \\le 2 M_{primes}$. Actually, the maximum possible answer for a query in this problem is $11$. You can find two numbers generating it as an exercise.",
    "code": "const int C = 5032107 + 1;\nint lp[C];\nint fred[C];\nint num_primes[C];\n\nconst int MAX_DIVISORS = 7;\nconst int MAX_ANS = 2 * MAX_DIVISORS;\n\nint max_left[MAX_DIVISORS + 1][C];\nint max_border[MAX_ANS + 1];\n\nvector<int> cur_primes;\n\nvector<int> divs;\n\nvoid get_divisors(int n) {\n    divs = {1};\n    while (n > 1) {\n        int p = lp[n];\n        n /= p;\n        int sz = divs.size();\n        for (int i = 0; i < sz; ++i) {\n            divs.push_back(divs[i] * p);\n        }\n    }\n}\n\nvoid solve(bool read) {\n    vector<int> pr;\n    for (int i = 2; i < C; ++i) {\n        if (lp[i] == 0) {\n            lp[i] = i;\n            pr.push_back(i);\n        }\n        for (int j = 0; j < pr.size() && pr[j] <= lp[i] && i * pr[j] < C; ++j) {\n            lp[i * pr[j]] = pr[j];\n        }\n    }\n    fred[1] = 1;\n    for (int i = 2; i < C; ++i) {\n        int p = lp[i];\n        int cur = i / p;\n        if (cur % p == 0) {\n            fred[i] = fred[cur / p];\n            num_primes[i] = num_primes[cur / p];\n        } else {\n            fred[i] = p * fred[cur];\n            num_primes[i] = num_primes[cur] + 1;\n        }\n    }\n\n    for (int i = 0; i < C; ++i) {\n        for (int j = 0; j <= MAX_DIVISORS; ++j) {\n            max_left[j][i] = -1;\n        }\n    }\n    memset(max_border, -1, sizeof(max_border));\n\n    int n;\n    cin >> n;\n    int Q;\n    cin >> Q;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n        a[i] = fred[a[i]];\n    }\n\n    vector<vector<pair<int, int>>> queries(n);\n\n    vector<int> res(Q);\n    for (int i = 0; i < Q; ++i) {\n        int l, r;\n        cin >> l >> r;\n        --l; --r;\n        queries[r].push_back({l, i});\n    }\n\n    for (int i = 0; i < n; ++i) {\n        get_divisors(a[i]);\n        for (int d : divs) {\n            int first_add = num_primes[a[i]] - num_primes[d];\n            for (int prev_ans = 0; prev_ans <= MAX_DIVISORS; ++prev_ans) {\n                int cur_left = max_left[prev_ans][d];\n                int cur_ans = first_add + prev_ans;\n                if (cur_ans <= MAX_ANS) {\n                    relax_max(max_border[cur_ans], cur_left);\n                }\n            }\n        }\n        for (int d : divs) {\n            int first_add = num_primes[a[i]] - num_primes[d];\n            relax_max(max_left[first_add][d], i);\n        }\n        for (auto q : queries[i]) {\n            res[q.second] = MAX_ANS + 1;\n            for (int cur_ans = 0; cur_ans <= MAX_ANS; ++cur_ans) {\n                if (max_border[cur_ans] >= q.first) {\n                    res[q.second] = cur_ans;\n                    break;\n                }\n            }\n            assert(res[q.second] <= MAX_ANS);\n        }\n    }\n\n    int sum_ans = 0;\n    for (int i = 0; i < Q; ++i) {\n        cout << res[i] << '\\n';\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1029",
    "index": "A",
    "title": "Many Equal Substrings",
    "statement": "You are given a string $t$ consisting of $n$ lowercase Latin letters and an integer number $k$.\n\nLet's define a substring of some string $s$ with indices from $l$ to $r$ as $s[l \\dots r]$.\n\nYour task is to construct such string $s$ of minimum possible length that there are exactly $k$ positions $i$ such that $s[i \\dots i + n - 1] = t$. In other words, your task is to construct such string $s$ of minimum possible length that there are exactly $k$ substrings of $s$ equal to $t$.\n\nIt is guaranteed that the answer is always unique.",
    "tutorial": "Let's carry the current answer as $ans$, the last position we're checked as $pos$ and the number of occurrences as $cnt$. Initially, the answer is $t$, $cnt$ is $1$ and $pos$ is $1$ (0-indexed). We don't need to check the position $0$ because there is the beginning of the occurrence of $t$ at this position. Also $cnt$ is $1$ by the same reason. Let's repeat the following algorithm while $cnt < k$: if $pos >= |ans|$, where |ans| is the length of the answer, let's add $t$ to the answer, increase $cnt$ and $pos$ by $1$. In the other case let's check if there is a prefix of $t$ starting from $pos$. If it is, let $len$ be its length. Then we need to add the suffix of $t$ starting from $len$ till the end of $t$, increase $cnt$ and $pos$ by $1$. If there is no prefix of $t$ starting from $pos$ the we just increase $pos$. The other idea is the following: we have to find the period of the string $t$. Let this period will be $p$. Then the answer is $p$ repeated $k-1$ times and $t$. The period of the string $s$ is the minimum prefix of this string such that we can repeat this prefix infinite number of times so the prefix of this infinite string will be $s$. For example, the period of the string $ababa$ is $ab$, the period of the string $abc$ is $abc$ and the period of the string $aaaaa$ is $a$. The period of the string can be found using prefix-function of the string or in $O(n^2)$ naively.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tstring t;\n\tcin >> n >> k >> t;\n\t\n\tvector<int> p(n);\n\tfor (int i = 1; i < sz(t); ++i) {\n\t\tint j = p[i - 1];\n\t\twhile (j > 0 && t[j] != t[i])\n\t\t\tj = p[j - 1];\n\t\tif (t[i] == t[j])\n\t\t\t++j;\n\t\tp[i] = j;\n\t}\n\t\n\tint len = sz(t) - p[n - 1];\n\t\n\tfor (int i = 0; i < k - 1; ++i)\n\t\tcout << t.substr(0, len);\n\tcout << t << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1029",
    "index": "B",
    "title": "Creating the Contest",
    "statement": "You are given a problemset consisting of $n$ problems. The difficulty of the $i$-th problem is $a_i$. It is guaranteed that all difficulties are distinct and are given in the increasing order.\n\nYou have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $a_{i_1}, a_{i_2}, \\dots, a_{i_p}$ be the difficulties of the selected problems in increasing order. Then for each $j$ from $1$ to $p-1$ $a_{i_{j + 1}} \\le a_{i_j} \\cdot 2$ should hold. It means that the contest consisting of only one problem is always valid.\n\nAmong all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.",
    "tutorial": "The answer is always a segment of the initial array. The authors solution uses two pointers technique: let's iterate over all left bounds of the correct contests and try to search maximum by inclusion correct contest. Let's iterate over all $i$ from $0$ to $n-1$ and let the current left bound be $i$. Let $j$ be the maximum right bound of the correct contest starting from the position $i$. Initially $j=i$. Now while $j + 1 < n$ and $a_{j + 1} \\le a_j \\cdot 2$ let's increase $j$. Try to update the answer with the value $j - i + 1$. It is obvious that all positions from $i + 1$ to $j$ cannot be left bounds of the maximum by inclusion correct contests, so let's set $i=j$ and go on. Because each element will be processed once, time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\t\t\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint j = i;\n\t\twhile (j + 1 < n && a[j + 1] <= a[j] * 2)\n\t\t\t++j;\n\t\tans = max(ans, j - i + 1);\n\t\ti = j;\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1029",
    "index": "C",
    "title": "Maximal Intersection",
    "statement": "You are given $n$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.\n\nThe intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $0$ in case the intersection is an empty set.\n\nFor example, the intersection of segments $[1;5]$ and $[3;10]$ is $[3;5]$ (length $2$), the intersection of segments $[1;5]$ and $[5;7]$ is $[5;5]$ (length $0$) and the intersection of segments $[1;5]$ and $[6;6]$ is an empty set (length $0$).\n\nYour task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $(n - 1)$ segments has the maximal possible length.",
    "tutorial": "Intersection of some segments $[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]$ is $[\\max \\limits_{i = 1}^n l_i; \\min \\limits_{i = 1}^n r_i]$. If this segment has its left bound greater than its right bound then the intersection is empty. Removing some segment $i$ makes the original sequence equal to $[l_1, r_1], \\dots, [l_{i - 1}, r_{i - 1}], \\dots [l_{i + 1}, r_{i + 1}], \\dots, [l_n, r_n]$. That can be split up to a prefix of length $i - 1$ and a suffix of length $n - i$. Intersections for them can be precalced separately and stored in some partial sum-like arrays. Finally, you have to iterate over the position of the removed segment and calculate the intersection of prefix and suffix without this segment. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 300 * 1000 + 13;\nconst int INF = int(1e9);\n\nint n;\nint prl[N], prr[N], sul[N], sur[N];\nint l[N], r[N];\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n)\n\t\tscanf(\"%d%d\", &l[i], &r[i]);\n\t\n\tprl[0] = sul[n] = 0;\n\tprr[0] = sur[n] = INF;\n\t\n\tforn(i, n){\n\t\tprl[i + 1] = max(prl[i], l[i]);\n\t\tprr[i + 1] = min(prr[i], r[i]);\n\t}\n\t\n\tfor (int i = n - 1; i >= 0; --i){\n\t\tsul[i] = max(sul[i + 1], l[i]);\n\t\tsur[i] = min(sur[i + 1], r[i]);\n\t}\n\t\n\tint ans = 0;\n\tforn(i, n)\n\t\tans = max(ans, min(prr[i], sur[i + 1]) - max(prl[i], sul[i + 1]));\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1029",
    "index": "D",
    "title": "Concatenated Multiples",
    "statement": "You are given an array $a$, consisting of $n$ positive integers.\n\nLet's call a concatenation of numbers $x$ and $y$ the number that is obtained by writing down numbers $x$ and $y$ one right after another without changing the order. For example, a concatenation of numbers $12$ and $3456$ is a number $123456$.\n\nCount the number of ordered pairs of positions $(i, j)$ ($i \\neq j$) in array $a$ such that the concatenation of $a_i$ and $a_j$ is divisible by $k$.",
    "tutorial": "Let's rewrite concatenation in a more convenient form. $conc(a_i, a_j) = a_i \\cdot 10^{len_j} + a_j$, where $len_j$ is the number of digits in $a_j$. Then this number is divisible by $k$ if and only if the sum of ($a_{j}~ mod~ k$) and ($(a_i \\cdot 10^{len_j})~ mod~ k$) is either $0$ or $k$. Let's calculate $10$ arrays of remainders $rem_1, rem_2, \\dots, rem_{10}$. For each $i$ $a_i$ adds ($a_{i}~ mod~ k$) to $rem_{len_i}$. That's the first term of the sum. Now iterate over the second term, for $i \\in [1..n]$ and for $j \\in [1..10]$ you binary search for ($k - ((a_i \\cdot 10^j)~ mod~ k)$) in $rem_j$. The number of its occurrences should be added to answer. You also might have calculated some pairs $(i, i)$, iterate over them and subtract them naively. Overall complexity: $O(10 \\cdot n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\ntypedef long long li;\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\nconst int LOGN = 11;\n\nint n, k;\nint a[N];\nint len[N];\nvector<int> rems[LOGN];\nint pw[LOGN];\n\nint main() {\n\tscanf(\"%d%d\", &n, &k);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\n\tpw[0] = 1;\n\tforn(i, LOGN - 1)\n\t\tpw[i + 1] = pw[i] * 10 % k;\n\t\n\tforn(i, n){\n\t\tint x = a[i];\n\t\twhile (x > 0){\n\t\t\t++len[i];\n\t\t\tx /= 10;\n\t\t}\n\t\trems[len[i]].push_back(a[i] % k);\n\t}\n\t\n\tforn(i, LOGN)\n\t\tsort(rems[i].begin(), rems[i].end());\n\t\n\tli ans = 0;\n\tforn(i, n){\n\t\tfor (int j = 1; j < LOGN; ++j){\n\t\t\tint rem = (a[i] * li(pw[j])) % k;\n\t\t\tint xrem = (k - rem) % k;\n\t\t\tauto l = lower_bound(rems[j].begin(), rems[j].end(), xrem);\n\t\t\tauto r = upper_bound(rems[j].begin(), rems[j].end(), xrem);\n\t\t\tans += (r - l);\n\t\t\tif (len[i] == j && (rem + a[i] % k) % k == 0)\n\t\t\t\t--ans;\n\t\t}\n\t}\n\t\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1029",
    "index": "E",
    "title": "Tree with Small Distances",
    "statement": "You are given an undirected tree consisting of $n$ vertices. An undirected tree is a connected undirected graph with $n - 1$ edges.\n\nYour task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex $1$ to any other vertex is at most $2$. Note that you are not allowed to add loops and multiple edges.",
    "tutorial": "The first idea is the following: it is always profitable to add the edges from the vertex $1$ to any other vertex. The proof is the following: if we will add two edges $(1, u)$ and $(u, v)$ then the distance to the vertex $u$ will be $1$, the distance to the vertex $v$ will be $2$. But we can add edges $(1, u)$ and $(1, v)$ and this will be better (in fact, you cannot obtain the less answer by adding two edges in the other way). The main idea is the following. Let's carry all vertices of the tree with the distance more than $2$ in the set. Let the vertex with the maximum distance be $v$. What we will obtain if we will add the edge $(1, v)$? The distance to the vertex $v$ will be $1$ and the distance to the vertex $p_v$ (where $p_v$ is the parent of the vertex $v$ if we will root the tree by the vertex $1$) will be $2$. So we will make reachable at most two vertices (if the vertex $p_v$ is already reachable then it will be not counted in the answer). Now what we will obtain if we will add the edge $(1, p_v)$? We will make reachable all the vertices adjacent to the vertex $p_v$ and the vertex $p_v$ (the number of such vertices is not less than $1$ so this move won't make the answer greater instead of any other way to add the edge). After adding such edge let's remove the vertex $p_v$ and all vertices adjacent to it from the set. We need to repeat this algorithm until the set will not become empty. Time complexity is $O(n \\log n)$. I sure that there exists the solution with the dynamic programming in the linear time, I will be very happy if someone will explain it to other participants.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 11;\n\nint p[N];\nint d[N];\nvector<int> g[N];\n\nvoid dfs(int v, int pr = -1, int dst = 0) {\n\td[v] = dst;\n\tp[v] = pr;\n\tfor (auto to : g[v]) {\n\t\tif (to != pr) {\n\t\t\tdfs(to, v, dst + 1);\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\t\n\tdfs(0);\n\tset<pair<int, int>> st;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (d[i] > 2) {\n\t\t\tst.insert(make_pair(-d[i], i));\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\twhile (!st.empty()) {\n\t\tint v = st.begin()->second;\n\t\tv = p[v];\n\t\t++ans;\n\t\tauto it = st.find(make_pair(-d[v], v));\n\t\tif (it != st.end()) {\n\t\t\tst.erase(it);\n\t\t}\n\t\tfor (auto to : g[v]) {\n\t\t\tauto it = st.find(make_pair(-d[to], to));\n\t\t\tif (it != st.end()) {\n\t\t\t\tst.erase(it);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "dp",
      "graphs",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1029",
    "index": "F",
    "title": "Multicolored Markers",
    "statement": "There is an infinite board of square tiles. Initially all tiles are white.\n\nVova has a red marker and a blue marker. Red marker can color $a$ tiles. Blue marker can color $b$ tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly $a$ red tiles and exactly $b$ blue tiles across the board.\n\nVova wants to color such a set of tiles that:\n\n- they would form a \\textbf{rectangle}, consisting of exactly $a+b$ colored tiles;\n- all tiles of at least one color would also form a \\textbf{rectangle}.\n\nHere are some examples of correct colorings:\n\nHere are some examples of incorrect colorings:\n\nAmong all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?\n\nIt is guaranteed that there exists at least one correct coloring.",
    "tutorial": "$a+b$ should be area of the outer rectangle. It means that its sides are divisors of $a+b$. The same holds for the inner rectangle. Let's assume that red color forms a rectangle, we'll try it and then swap $a$ with $b$ and solve the same problem again. Write down all the divisors of $a$ up to $\\sqrt a$, these are the possible smaller sides of the inner rectangle. Divisors of $a+b$ up to $\\sqrt{a+b}$ are possible smaller sides of the outer rectangle. Let's put inner rectangle to the left bottom corner of the outer rectangle and choose smaller sides of both of them as bottom and top ones. Iterate over the divisors $d1$ of $a+b$, for each of them choose the greatest divisor $d2$ of $a$ smaller or equal to it and check that $\\frac{a+b}{d1} \\ge \\frac{a}{d2}$. Update the answer with $2(d1 + \\frac{a+b}{d1})$ if it holds. You can use both binary search or two pointers, both get AC pretty easily. The number of divisors of $n$ can usually be estimated as $n^{\\frac 1 3}$. Overall complexity: $O(\\sqrt{a+b})$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\ntypedef long long li;\n\nusing namespace std;\n\nconst int N = 1000 * 1000;\n\nint lens[N];\nint k;\n\nli solve(li a, li b){\n\tk = 0;\n\tfor (li i = 1; i * i <= b; ++i)\n\t\tif (b % i == 0)\n\t\t\tlens[k++] = i;\n\t\n\tli ans = 2 * (a + b) + 2;\n\tli x = a + b;\n\tint l = 0;\n\tfor (li i = 1; i * i <= x; ++i){\n\t\tif (x % i == 0){\n\t\t\twhile (l + 1 < k && lens[l + 1] <= i)\n\t\t\t\t++l;\n\t\t\tif (b / lens[l] <= x / i)\n\t\t\t\tans = min(ans, (i + x / i) * 2);\n\t\t}\n\t}\n\t\n\treturn ans;\n}\n\nint main() {\n\tli a, b;\n\tscanf(\"%lld%lld\", &a, &b);\n\tprintf(\"%lld\\n\", min(solve(a, b), solve(b, a)));\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1030",
    "index": "A",
    "title": "In Search of an Easy Problem",
    "statement": "When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked $n$ people about their opinions. Each person answered whether this problem is easy or hard.\n\nIf at least one of these $n$ people has answered that the problem is hard, the coordinator decides to change the problem. For the given responses, check if the problem is easy enough.",
    "tutorial": "Codebait. Comforting problem. Find $\\max\\limits_{i=1..n}{(\\text{answer}_i)}$, if it's equal to $1$ then answer is HARD, otherwise - EASY.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint n; cin >> n;\n\t\n\tint curMax = 0;\n\tfor(int i = 0; i < n; i++) {\n\t\tint curAns; cin >> curAns;\n\t\tcurMax = max(curMax, curAns);\n\t}\n\tputs(curMax > 0 ? \"HARD\" : \"EASY\");\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1030",
    "index": "B",
    "title": "Vasya and Cornfield",
    "statement": "Vasya owns a cornfield which can be defined with two integers $n$ and $d$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $(0, d), (d, 0), (n, n - d)$ and $(n - d, n)$.\n\n\\begin{center}\n{\\small An example of a cornfield with $n = 7$ and $d = 2$.}\n\\end{center}\n\nVasya also knows that there are $m$ grasshoppers near the field (maybe even inside it). The $i$-th grasshopper is at the point $(x_i, y_i)$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.\n\nHelp Vasya! For each grasshopper determine if it is inside the field (including the border).",
    "tutorial": "For each point $(x, y)$ let's look at values of two diagonals: $x + y$ and $x - y$. Borders of the cornfield, in fact, give limits to this values in the next way: $d \\le x + y \\le 2n - d$ and $-d \\le x - y \\le d$ - that's all we need to check. There is a picture below for the further explanation.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n, d;\nint m;\n\nint main() {\n\tios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n\tcin >> n >> d;\n\tcin >> m;\n\tfor(int i = 0; i < m; ++i){\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t\n\t\tbool ok = true;\n\t\tif(!((x - y) <= d && (x - y) >= -d)) \n\t\t\tok = false;\n\t\tif(!((x + y) <= n + n - d && (x + y) >= d))\n\t\t\tok = false;\n\n\t\tif(ok) puts(\"YES\");\n\t\telse puts(\"NO\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "geometry"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1030",
    "index": "C",
    "title": "Vasya and Golden Ticket",
    "statement": "Recently Vasya found a golden ticket — a sequence which consists of $n$ digits $a_1a_2\\dots a_n$. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket $350178$ is lucky since it can be divided into three segments $350$, $17$ and $8$: $3+5+0=1+7=8$. Note that each digit of sequence should belong to \\textbf{exactly} one segment.\n\nHelp Vasya! Tell him if the golden ticket he found is lucky or not.",
    "tutorial": "Let's iterate over all possible lengths $len$ of the first segment of the partition. Now, knowing this length, we also can calculate sum $S$ of each segment. Now we can form partition with greedy solution: starting from position $len + 1$ we will find maximal prefix (strictly, segment starting at $len + 1$) with sum lower or equal to $S$, cut it and again. If all formed segments have sums equal to $S$ then it's valid partition and answer is \"YES\". Otherwise, there is no valid length of the first segment, there is no valid partition, so answer is \"NO\".",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nstring s;\n\nint main() {\n\tios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n\tcin >> n >> s;\n\tint sum = 0;\n\tfor(int i = 0; i < n - 1; ++i){\n\t\tsum += s[i] - '0';\n\t\t\n\t\tbool ok = true;\n\t\tint pos = i + 1;\n\t\tint sum2 = 0;\n\t\twhile(pos < n){\n\t\t\tsum2 = s[pos++] - '0';\n\t\t\twhile(pos < n && sum2 + s[pos] - '0' <= sum){\n\t\t\t\tsum2 += s[pos] - '0';\n\t\t\t\t++pos;\n\t\t\t}\n\t\t\tif(sum2 != sum) ok = false;\n\t\t}\n\t\t\n\t\tif(sum2 != sum) ok = false;\n\t\tif(ok){\n\t\t\tputs(\"YES\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tputs(\"NO\");\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1030",
    "index": "D",
    "title": "Vasya and Triangle",
    "statement": "Vasya has got three integers $n$, $m$ and $k$. He'd like to find three integer points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$, such that $0 \\le x_1, x_2, x_3 \\le n$, $0 \\le y_1, y_2, y_3 \\le m$ and the area of the triangle formed by these points is equal to $\\frac{nm}{k}$.\n\nHelp Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.",
    "tutorial": "Doubled area of any triangle with integer coordinates is always integer. That's why if $2 n m$ is not divisible by $k$ then there is no valid triangle. Otherwise, it's always possible to find required triangle. We will construct the answer with next algorithm. At first, if $k$ is even then divide it by $2$. Next, find $g = \\gcd(k, n)$, where $\\gcd(x, y)$ is greatest common divisor of $x$ and $y$. Denote $k' = \\frac{k}{g}$ and assign $a = \\frac{n}{g}$ as length of the first side. Next assign $b = \\frac{m}{k'}$ as length of the second side. Now, if $k$ was odd we need to multiply one of the sides by $2$. If $a < n$ then $a = 2a$, otherwise $b = 2b$. $b$ still won't be greater than $m$ since if $a = n$ then $b$ was strictly lower than $m$. The answer is the triangle with vertices $(0, 0), (a, 0), (0, b)$. You can check that its area is equal to $\\frac{nm}{k}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nlong long gcd(long long a, long long b){\n\treturn a? gcd(b % a, a) : b;\n}\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t\n    long long n, m, k;\n    cin >> n >> m >> k;\n    \n    bool isEven = k % 2 == 0;\n    long long p = n * m;\n\tif(isEven) k /= 2;\n\t\n\tif(p % k != 0){\n\t\tcout << \"NO\" << endl;\n\t\treturn 0;\n\t}\n\t\n\tlong long x = gcd(n, k);\n\tk /= x;\n\tlong long a = n / x;\n\t\t\n\tx = gcd(m, k);\n\tk /= x;\n\tassert(k == 1);\n\tlong long b = m / x;\n\t\t\n\t\n\tif(!isEven){\n\t\tif(a < n)\n\t\t\ta += a;\n\t\telse{\n\t\t\tassert(b < m);\n\t\t\tb += b;\n\t\t}\n\t}\n\t\n\tcout << \"YES\" << endl;\n\tcout << \"0 0\\n\";\n\tcout << 0 << ' ' << b << endl;\n\tcout << a << ' ' << 0 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "geometry",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1030",
    "index": "E",
    "title": "Vasya and Good Sequences",
    "statement": "Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \\dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\\dots 00000000110_2)$ into $3$ $(\\dots 00000000011_2)$, $12$ $(\\dots 000000001100_2)$, $1026$ $(\\dots 10000000010_2)$ and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.\n\nVasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to $0$.\n\nFor the given sequence $a_1, a_2, \\ldots, a_n$ Vasya'd like to calculate number of integer pairs $(l, r)$ such that $1 \\le l \\le r \\le n$ and sequence $a_l, a_{l + 1}, \\dots, a_r$ is good.",
    "tutorial": "Since we can swap any pair of bits in the number, so all we need to know is just the number of ones in its binary representation. Let create array $b_1, b_2, \\dots , b_n$, where $b_i$ is number of ones in binary representation of $a_i$. Forget about array $a$, we will work with array $b$. Let's find a way to decide whether fixed segment is good or not. It can be proven that two conditions must be met. At first, sum of $b_i$ at this segment should be even. At second, maximal element should be lower or equal to the sum of all other elements. We will iterate over left borders of subsegments in descending order and for each left border $l$ calculate number of right borders $r$ such that $[l, r]$ is good. Let's, as first, \"forget\" about condition on maximum and calculate $cntAll(l)$ - number of right borders $r$, such that sum on segment $[l,r]$ is even and left border $l$ is fixed. We can calculate it by counting $S_0$ and $S_1$ - the number of suffixes of array with even sum of $b_i$ and number of suffixes with odd sum. If the current sum $\\sum\\limits_{i=l}^{n}{b_i}$ is even then $cntAll(l) = S_0$ since $\\sum\\limits_{i=l}^{r}{b_i} = \\sum\\limits_{i=l}^{n}{b_i} - \\sum\\limits_{i=r+1}^{n}{b_i}$. If $\\sum\\limits_{i=l}^{n}{b_i}$ is odd then $cntAll(l) = S_1$. Since we forgot about condition on maximum, some bad segments were counted. Since $a_i \\le 10^{18}$ then $b_i < 61$. That's why if length of the segment $\\ge 61$, condition on the maximum is always true. So, for a fixed $l$ we can iterate over all right borders in the $[l, l + 61]$ and subtract number of segments with even sum and too large maximum (since these segments were counted in the answer).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 9;\n\nint n;\nlong long a[N];\nint b[N];\nint cnt[2][N];\n\nint main() {\n\tios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n\tcin >> n;\n\tfor(int i = 0; i <n; ++i){\n\t\tcin >> a[i];\n\t\tb[i] = __builtin_popcountll(a[i]);\t\n\t}\n\t\n\tlong long res = 0;\n\tint sufSum = 0;\n\tcnt[0][n] = 1;\n\tfor(int i = n - 1; i >= 0; --i){\n\t\tint sum = 0, mx = 0;\n\t\tint lstJ = i;\n\t\tint add = 0;\n\t\tfor(int j = i; j < n && j - i < 65; ++j){\n\t\t\tsum += b[j];\n\t\t\tmx = max(mx, b[j]);\n\t\t\tif(mx > sum - mx && sum % 2 == 0) --add;\n\t\t\tlstJ = j;\n\t\t}\t\t\n\t\t\n\t\tsufSum += b[i];\n\t\tadd += cnt[sufSum & 1][i + 1];\n\t\tres += add;\t\n\t\t\n\t\tcnt[0][i] = cnt[0][i + 1];\n\t\tcnt[1][i] = cnt[1][i + 1];\n\t\tif(sufSum & 1) ++cnt[1][i];\n\t\telse ++cnt[0][i];\n\t}\n\t\n\tcout << res << endl;\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1030",
    "index": "F",
    "title": "Putting Boxes Together",
    "statement": "There is an infinite line consisting of cells. There are $n$ boxes in some cells of this line. The $i$-th box stands in the cell $a_i$ and has weight $w_i$. All $a_i$ are distinct, moreover, $a_{i - 1} < a_i$ holds for all valid $i$.\n\nYou would like to put together some boxes. Putting together boxes with indices in the segment $[l, r]$ means that you will move some of them in such a way that their positions will form some segment $[x, x + (r - l)]$.\n\nIn one step you can move any box to a neighboring cell if it isn't occupied by another box (i.e. you can choose $i$ and change $a_i$ by $1$, all positions should remain distinct). You spend $w_i$ units of energy moving the box $i$ by one cell. You can move any box any number of times, in arbitrary order.\n\nSometimes weights of some boxes change, so you have queries of two types:\n\n- $id$ $nw$ — weight $w_{id}$ of the box $id$ becomes $nw$.\n- $l$ $r$ — you should compute the minimum total energy needed to put together boxes with indices in $[l, r]$. Since the answer can be rather big, print the remainder it gives when divided by $1000\\,000\\,007 = 10^9 + 7$. Note that the boxes are not moved during the query, you only should compute the answer.\n\n\\textbf{Note that you should minimize the answer, not its remainder modulo $10^9 + 7$. So if you have two possible answers $2 \\cdot 10^9 + 13$ and $2 \\cdot 10^9 + 14$, you should choose the first one and print $10^9 + 6$, even though the remainder of the second answer is $0$.}",
    "tutorial": "Firstly, let's prove that it's always optimal to leave one of the boxes untouched. By contradiction: if all boxes will move, so some left part will move right and right part will move left. Let the total cost of shifting the whole left part by one be equal to $S_l$ and cost of the right part be $S_r$. We can replace the move of one of the parts by extra move of the other part, so we can change $\\max(S_l, S_r)$ by $\\min(S_l, S_r)$ - total cost doesn't increase - contradiction. Let $S(l, r) = \\sum\\limits_{i=l}^{r}{w_i}$. Then, secondly, let's prove that for some segment $[l, r]$ it's always optimal to choose untouched box $k$ such that $S(l, k-1) \\le \\frac{S(l, r)}{2}$, but $S(l, k) \\ge \\frac{S(l, r)}{2}$. Again: if it is not true then either $S(l,k - 1) > \\frac{S(l, r)}{2}$ or $S(k+1, r) > \\frac{S(l, r)}{2}$. And we again can replace either $S(l, k - 1)$ by $S(k, r)$ or $S(k + 1, r)$ by $S(l, k)$. Total cost is decreasing - contradiction. So, finally, all we need is to process the following queries: for given $[l, r]$ find maximum $k$ that $S(l, k-1) \\le \\frac{S(l, r)}{2}$, but $S(l, k) > \\frac{S(l, r)}{2}$ ($>$ or $\\ge$ doesn't really matter). It can be done with binary search + BIT in $O(\\log^2 n)$ time or by \"descending\" down the Segment Tree in $O(\\log n)$ time. Next part is how to calculate the answer for the known $k$. Since the cost of moving box $i$ to the right place is equal to $w_i (a_k - a_i - (k - i))$ if $i < k$ and $w_i (a_i - a_k - (i - k))$ otherwise so, if we shift from $a_i$ to $a_i - i$ then the cost to move all left indices are equal to $\\sum\\limits_{i=l}^{k-1}{w_i (a_k - a_i)} = a_k \\cdot S(l, k-1) - \\sum\\limits_{i=l}^{k-1}{w_i a_i}$. The right part transforms in the same way. Since answer is modulo $10^9 + 7$ we can calculate $\\sum\\limits_{i=l}^{k-1}{(w_i a_i \\mod 10^9 + 7)}$ using another BIT. Result complexity is $O(n \\log n + q \\log^2 n)$ or $O((n + q) \\log n)$ (which isn't really faster in this task).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\n\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tfore(i, 1, int(v.size())) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nconst int MOD = int(1e9) + 7;\n\nint norm(int a) {\n\twhile(a >= MOD)\n\t\ta -= MOD;\n\twhile(a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint norm(const li &a) {\n\treturn norm(int(a % MOD));\n}\n\nint mul(int a, int b) {\n\treturn int((a * 1ll * b) % MOD);\n}\n\nconst int N = 300 * 1000 + 555;\n\nint n, q;\nint a[N], w[N];\n\ninline bool read() {\n\tif(!(cin >> n >> q))\n\t\treturn false;\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%d\", &a[i]) == 1);\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%d\", &w[i]) == 1);\n\treturn true;\n}\n\nli TW[4 * N], TAW[4 * N];\n\nvoid addVAl(li T[4 * N], int v, int l, int r, int pos, int val) {\n\tif(l + 1 == r) {\n\t\tassert(l == pos);\n\t\tT[v] += val;\n\t\treturn;\n\t}\n\tint mid = (l + r) >> 1;\n\tif(pos < mid)\n\t\taddVAl(T, 2 * v + 1, l, mid, pos, val);\n\telse\n\t\taddVAl(T, 2 * v + 2, mid, r, pos, val);\n\tT[v] = T[2 * v + 1] + T[2 * v + 2];\n}\n\nli getSum(li T[4 * N], int v, int l, int r, int lf, int rg) {\n\tif(l == lf && r == rg)\n\t\treturn T[v];\n\tint mid = (l + r) >> 1;\n\tli ans = 0;\n\tif(lf < mid)\n\t\tans += getSum(T, 2 * v + 1, l, mid, lf, min(mid, rg));\n\tif(rg > mid)\n\t\tans += getSum(T, 2 * v + 2, mid, r, max(lf, mid), rg);\n\treturn ans;\n}\n\nint getNSum(li T[4 * N], int l, int r) {\n\tif(l >= r) return 0;\n\treturn int(getSum(T, 0, 0, n, l, r) % MOD);\n}\n\npair<int, li> getPos(int v, int l, int r, int lf, int rg, li val) {\n\tif(l == lf && r == rg) {\n\t\tif(TW[v] <= val)\n\t\t\treturn make_pair(INF, TW[v]);\n\t\tif(l + 1 == r)\n\t\t\treturn make_pair(l, 0);\n\t}\n\tint mid = (l + r) >> 1;\n\t\n\tint res = INF;\n\tli sum = 0;\n\tif(lf < mid) {\n\t\tauto cur = getPos(2 * v + 1, l, mid, lf, min(mid, rg), val);\n\t\tres = min(res, cur.x);\n\t\tsum += cur.y;\n\t}\n\tif(rg > mid && res == INF) {\n\t\tauto cur = getPos(2 * v + 2, mid, r, max(lf, mid), rg, val - sum);\n\t\tres = min(res, cur.x);\n\t\tsum += cur.y;\n\t}\n\treturn make_pair(res, sum);\n}\n\ninline void solve() {\n\tfore(i, 0, n) {\n\t\ta[i] -= i;\n\t\taddVAl(TW, 0, 0, n, i, w[i]);\n\t\taddVAl(TAW, 0, 0, n, i, mul(a[i], w[i]));\n\t}\n\t\n\tfore(_, 0, q) {\n\t\tint x, y;\n\t\tassert(scanf(\"%d%d\", &x, &y) == 2);\n\t\tif(x < 0) {\n\t\t\tx = -x - 1;\n\t\t\taddVAl(TW, 0, 0, n, x, -w[x]);\n\t\t\taddVAl(TAW, 0, 0, n, x, -mul(a[x], w[x]));\n\t\t\t\n\t\t\tw[x] = y;\n\t\t\taddVAl(TW, 0, 0, n, x, w[x]);\n\t\t\taddVAl(TAW, 0, 0, n, x, mul(a[x], w[x]));\n\t\t} else {\n\t\t\tx--;\n\t\t\tli sum = getSum(TW, 0, 0, n, x, y);\n\t\t\tint pos = getPos(0, 0, n, x, y, sum / 2).x;\n\t\t\tassert(x <= pos && pos < y);\n\t\t\t\n\t\t\tint ans = norm(mul(a[pos], getNSum(TW, x, pos)) - getNSum(TAW, x, pos));\n\t\t\tans = norm(ans + norm(getNSum(TAW, pos, y) - mul(a[pos], getNSum(TW, pos, y))) );\n\t\t\tprintf(\"%d\\n\", ans);\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1030",
    "index": "G",
    "title": "Linear Congruential Generator",
    "statement": "You are given a tuple generator $f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \\dots, f_n^{(k)})$, where $f_i^{(k)} = (a_i \\cdot f_i^{(k - 1)} + b_i) \\bmod p_i$ and $f^{(0)} = (x_1, x_2, \\dots, x_n)$. Here $x \\bmod y$ denotes the remainder of $x$ when divided by $y$. All $p_i$ are primes.\n\nOne can see that with fixed sequences $x_i$, $y_i$, $a_i$ the tuples $f^{(k)}$ starting from some index will repeat tuples with smaller indices. Calculate the maximum number of different tuples (from all $f^{(k)}$ for $k \\ge 0$) that can be produced by this generator, if $x_i$, $a_i$, $b_i$ are integers in the range $[0, p_i - 1]$ and can be chosen arbitrary. The answer can be large, so print the remainder it gives when divided by $10^9 + 7$",
    "tutorial": "Each generator $f_i^{(k)}$ can be represented as functional graph so the number of different values equal to the legth of the cycle $c$ plus the length of pre-period $pp$. Generalizing on tuples leads to next observation: number of different tuples equals to $\\max\\limits_{i = 1..n}(pp_i) + \\mathop{\\text{lcm}}\\limits_{i = 1..n}(c_i)$. ---- Some proof ---- Let's take a look at some generator $f_i$ to find out its possible $c_i$ and $pp_i$. If $a_i = 0$ then $f_i = x_i, b_i, b_i, b_i, \\dots$. the $c_i = 1$ and $pp_i = 0$ or $pp_i = 1$. If $a_i = 1$ then $f_i^{(k)} = (x_i + (k - 1) b_i) \\mod p_i$. Since $p_i$ is a prime then $c_i = 1$ or $c_i = p_i$ and $pp_i = 0$. If $a_i > 1$ then exists $a_i^{-1}$ and $(a_i - 1)^{-1}$, thus $pp_i = 0$. Since there is not pre-period we need to find minimal positive $k$ such that Since $p_i$ is a prime if $a \\cdot b \\equiv 0$ then $a \\equiv 0$ or $b \\equiv 0$. So if $(x_i + b_i \\cdot (a_i - 1)^{-1}) \\equiv 0$ and since it doesn't depend on $k$ then $k = 1$, so $c_i = 1$ and $pp_i = 0$. Otherwise, $(a_i^k - 1) \\equiv 0$ and by Lagrange's theorem $k \\mid (p_i - 1)$. Finally, since $p_i$ is a prime there exist $a_i$ such that $k = p_i - 1$. ---- End of some proof ---- At the end we can understand that only three cases are matter: $(c_i = 1, pp_i = 1)$, $(c_i = p_i, pp_i = 0)$ and $(c_i = p_i - 1, pp_i = 0)$. Here some greedy ideas works: it always optimal try at first $(p_i, 0)$, then $(p_i - 1, 0)$ and only then $(1, 1)$; we can process elements in the descending order. But there is one problem: since we maximaize $\\max\\limits_{i = 1..n}(pp_i) + \\mathop{\\text{lcm}}\\limits_{i = 1..n}(c_i)$ then there are cases, where we can make $\\max\\limits_{i = 1..n}(pp_i) = 1$ without lowering $\\mathop{\\text{lcm}}\\limits_{i = 1..n}(c_i)$. Here comes two approaches: The first solution (hard to prove correctness, the proven complexity): Let's add to some structure $p_i$ in non ascending order: let's maintain $\\text{lcm}$ as pairs: maximal power of prime $a_j$ and number of maximums $cnt_j$ for each prime number up to $2 \\cdot 10^6$ . For each $p_i$ we will try to add it as $p_i$ to the $\\text{lcm}$. If this structure already have $p_i$ then we will add it as $p_i - 1$, so we need factorization of $p_i - 1$. After that we will iterate over all $p_i$ again and check \"can we remove it from structure without decreasing $\\text{lcm}$\". We will check it in the next way: for index $i$ just check for each prime divisor $pd_j$ of $p_i - 1$ if it was added as $p_i - 1$ (or of $p_i$ if it was added as $p_i$) is it true that ($a_{pd_j}$ > power of $pd_j$) or ($a_{pd_j}$ = power of $pd_j$ and $cnt_{pd_j} > 1$). If we can remove some index $i$ so we can make $\\max(pp_i) = 1$ - profit. Otherwise, it's impossible to get $\\max(pp_i) = 1$. Here should be proof of correctness, but it is quite complicated (but I proved this solution to KAN and he agreed (hm, notorious coincidence)). At the end, we need factorization of all numbers up to $2 \\cdot 10^6$ it can be done with Sieve of Eratosthenes if we will remember minimal divisor for each number. So, the result complexity is $O((n + MAX) \\log(n))$. The second solution (the proven correctness, hard to prove the complexity): Let's maintain same structure for $\\text{lcm}$ but with some modification: we don't need $cnt_j$ but for each prime we will have a flag $mark_j$ - does this prime is occupied by $p_i$ from the input. Now, let's get to know a way to add arbitrary prime $p_i$ from the input to this structure. Name this function as $insert(v)$. If the structure doesn't have $v$ - just add it (recalc $a_v$ and $mark_v$ flag). Otherwise, we'll move to $v - 1$ and for each prime divisor $pd_k$ of $v - 1$ we'll try to update $pd_k$ in the structure - final trick is next: if we update $pd_k$ which have $mark_{pd_k}$ we will unmark it call a $insert(pd_k)$ recursively. Now we can insert some $p_i$. We will at first find maximum $a_j$ for each prime. Then we will make $n$ quieries - calculate $\\text{lcm}$ without $p_i$. This queries can be processed with dynamic connectivity. Final question is to evaluate number of operation done by $insert(v)$. We can limit it with number of prime divisors of all different primes we can reach from each $v$ up to $2 \\cdot 10^6$. It was less than $D = 30$. So result complexity is $O(n \\log(n) \\cdot D)$. P.S.: Main correct is the second solution.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int MOD = int(1e9) + 7;\n\nint mul(int a, int b) {\n\treturn int(a * 1ll * b % MOD);\n}\n\nint binPow(int a, int k) {\n\tint ans = 1;\n\twhile(k > 0) {\n\t\tif(k & 1) ans = mul(ans, a);\n\t\ta = mul(a, a);\n\t\tk >>= 1;\n\t}\n\treturn ans;\n}\n\nconst int M = 2000 * 1000 + 555;\n\nint minD[M];\nvector<pt> ps[M];\n\ninline void precalc() {\n\tiota(minD, minD + M, 0);\n\t\n\tfore(val, 2, M) {\n\t\tif(minD[val] < val)\n\t\t\tcontinue;\n\t\t\t\n\t\tfor(li j = val * 1ll * val; j < M; j += val)\n\t\t\tminD[j] = min(minD[j], val);\n\t}\n\t\n\tfore(i, 2, M) {\n\t\tint v = i;\n\t\tps[i].clear();\n\t\t\n\t\twhile(v > 1) {\n\t\t\tint md = minD[v];\n\t\t\tif(ps[i].empty() || ps[i].back().x != md)\n\t\t\t\tps[i].emplace_back(md, 0);\n\t\t\tps[i].back().y++;\n\t\t\tv /= md;\n\t\t}\n\t}\n}\n\nint n;\nvector<int> p;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\tp.assign(n, 0);\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%d\", &p[i]) == 1);\n\treturn true;\n}\n\nint a[M], cnt[M];\n\ninline void solve() {\n\tsort(p.begin(), p.end(), greater<int>());\n\t\n\tfor(int& cp : p) {\n\t\tif(a[cp] == 0) {\n\t\t\ta[cp] = 1;\n\t\t\tcnt[cp] = 1;\n\t\t} else {\n\t\t\tcp--;\n\t\t\tfor(auto np : ps[cp]) {\n\t\t\t\tif(a[np.x] < np.y) {\n\t\t\t\t\ta[np.x] = np.y;\n\t\t\t\t\tcnt[np.x] = 1;\n\t\t\t\t} else if(a[np.x] == np.y)\n\t\t\t\t\tcnt[np.x]++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint add = 0;\n\tfor(int cp : p) {\n\t\tbool un = false;\n\t\tfor(auto np : ps[cp])\n\t\t\tun |= (a[np.x] == np.y && cnt[np.x] == 1);\n\t\tif(!un)\n\t\t\tadd = 1;\n\t}\n\t\n\tint lcm = 1;\n\tfore(i, 2, M)\n\t\tlcm = mul(lcm, binPow(i, a[i]));\n\tcout << (lcm + add) % MOD << endl;\n}\n\nint main(){\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint t = clock();\n#endif\n\tcout << fixed << setprecision(10);\n\n\tprecalc();\n\tif(read()) {\n\t\tsolve();\t\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - t << endl;\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1031",
    "index": "A",
    "title": "Golden Plate",
    "statement": "You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into $w\\times h$ cells. There should be $k$ gilded rings, the first one should go along the edge of the plate, the second one — $2$ cells away from the edge and so on. Each ring has a width of $1$ cell. Formally, the $i$-th of these rings should consist of all bordering cells on the inner rectangle of size $(w - 4(i - 1))\\times(h - 4(i - 1))$.\n\n\\begin{center}\n{\\small The picture corresponds to the third example.}\n\\end{center}\n\nYour task is to compute the number of cells to be gilded.",
    "tutorial": "The number of gilded cells in the first (outer) ring is the number of border cells, that is, $2(w + h) - 4$, in the second ring - the number of border cells of the center rectangle with side lengths 4 less, that is, $2(w - 4 + h - 4) - 4$, and so on. This sum can be calculated in a single loop.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1031",
    "index": "B",
    "title": "Curiosity Has No Limits",
    "statement": "When Masha came to math classes today, she saw two integer sequences of length $n - 1$ on the blackboard. Let's denote the elements of the first sequence as $a_i$ ($0 \\le a_i \\le 3$), and the elements of the second sequence as $b_i$ ($0 \\le b_i \\le 3$).\n\nMasha became interested if or not there is an integer sequence of length $n$, which elements we will denote as $t_i$ ($0 \\le t_i \\le 3$), so that for every $i$ ($1 \\le i \\le n - 1$) the following is true:\n\n- $a_i = t_i | t_{i + 1}$ (where $|$ denotes the bitwise OR operation) and\n- $b_i = t_i \\& t_{i + 1}$ (where $\\&$ denotes the bitwise AND operation).\n\nThe question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence $t_i$ of length $n$ exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them.",
    "tutorial": "Let's solve the problem for $0 \\leq a_i, b_i, t_i \\leq 1$, that is, for binary sequences. There are two options for $t_1$, the remaining part can be determined one number by one after this: If $t_1 = 0$ and $a_1 = 0$ and $b_1 = 0$ then $t_2$ = 0; If $t_1 = 0$ and $a_1 = 0$ and $b_1 = 1$ then there is no such $t_2$. If $t_1 = 0$ and $a_1 = 1$ and $b_1 = 0$ then $t_2$ = 1; If $t_1 = 0$ and $a_1 = 1$ and $b_1 = 1$ then $t_2$ = 1; If $t_1 = 1$ and $a_1 = 0$ and $b_1 = 0$ then there is no such $t_2$. If $t_1 = 1$ and $a_1 = 0$ and $b_1 = 1$ then there is no such $t_2$. If $t_1 = 1$ and $a_1 = 1$ and $b_1 = 0$ then $t_2$ = 0; If $t_1 = 1$ and $a_1 = 1$ and $b_1 = 1$ then $t_2$ = 1; One can similarly find all other $t_i$-s ($3 \\leq i \\leq n$) or get a contradiction. For bitwise operations from the statement one can solve the problem independently for every bit and restore the original sequence $t_1, t_2, \\ldots, t_n$.",
    "tags": [],
    "rating": 1500
  },
  {
    "contest_id": "1031",
    "index": "C",
    "title": "Cram Time",
    "statement": "In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.\n\nLesha knows that today he can study for at most $a$ hours, and he will have $b$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $k$ in $k$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.\n\nThus, the student has to fully read several lecture notes today, spending at most $a$ hours in total, and fully read several lecture notes tomorrow, spending at most $b$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?",
    "tutorial": "Consider any answer with maximal $n + m$. If we used numbers $d_1, d_2, \\ldots, d_k$ ($d_i \\gt n + m$), then we didn't use some numbers $h_1, h_2, \\ldots, h_k$ ($h_i \\leq n + m$). Replacing all $d_i$ by $h_i$ ($1 \\leq i \\leq k$) doesn't violate the restriction. That means that we can assume that the answer consists of all numbers from $1$ to $x$, and $x = n + m$. The sum of all numbers from $1$ to $x$ equals $\\frac{x(x + 1)}{2}$. It's clear that the following inequality must hold: $\\frac{x(x + 1)}{2} \\leq a + b$. Let's find the maximal $x$ for which it's true. The answer can't exceed $x$, and we can build the answer for $x$ iteratively. Let's iterate over all lecture notes from $x$ to $1$, and on each step we put it into the first day if we can, otherwise if in the first day we have $w > 0$ free time then we put the lecture note $w < x$ to the first day. All other lecture notes can be read during the second day since the either there are none of them, or the first day is full and hence the second day contains a sufficient amount of hours to read'em all.",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1031",
    "index": "D",
    "title": "Minimum path",
    "statement": "You are given a matrix of size $n \\times n$ filled with lowercase English letters. You can change no more than $k$ letters in this matrix.\n\nConsider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $2n - 1$.\n\nFind the lexicographically smallest string that can be associated with a path after changing letters in at most $k$ cells of the matrix.\n\nA string $a$ is lexicographically smaller than a string $b$, if the first different letter in $a$ and $b$ is smaller in $a$.",
    "tutorial": "First, let's find the number of a-s in the beginning of the answer. To do this one can calculate dp[i][j] standing for the minimal number of non-a-s among all paths from the initial corner to (i, j). The number of a-s is simply the greatest $(i + j)$ among all pairs $(i, j)$ such that $dp[i][j]\\le k$ (or $0$, if there are no). Consider all cells where we can go right after obtaining the prefix of a-s. Now we repeat the following: append the minimal symbol in these cells to the answer, choose those cells and go from them in both possible directions to obtain the new set of cells. One can see that the answer we obtain is indeed the required answer.",
    "tags": [
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1031",
    "index": "E",
    "title": "Triple Flips",
    "statement": "You are given an array $a$ of length $n$ that consists of zeros and ones.\n\nYou can perform the following operation multiple times. The operation consists of two steps:\n\n- Choose three integers $1 \\le x < y < z \\le n$, that form an arithmetic progression ($y - x = z - y$).\n- Flip the values $a_x, a_y, a_z$ (i.e. change $1$ to $0$, change $0$ to $1$).\n\nDetermine if it is possible to make all elements of the array equal to zero. If yes, print the operations that lead the the all-zero state. Your solution should not contain more than $(\\lfloor \\frac{n}{3} \\rfloor + 12)$ operations. Here $\\lfloor q \\rfloor$ denotes the number $q$ rounded down. We can show that it is possible to make all elements equal to zero in no more than this number of operations whenever it is possible to do so at all.",
    "tutorial": "This problem has a lot of solutions including those ones which are difficult to prove. Let's describe one of the author's solutions. We can find answer with bruteforce if size of array is rather small. For example we can check all combinations of arithmetic progressions with length equals to three. We can find by hand or bruteforce that for $3 \\le n \\le 7$ arrays with no solution exists but for $n = 8$ (and consequently for $n \\ge 8$) we always can make all elements be equal to zero. We want solution with such steps: If $n$ is small just run bruteforce Else try to make all elements besides the first $k$ ($k \\ge 8$) be equal to zero Run bruteforce on the first $k$ elements. How to make the second step? Let's try to make three last elements of array be equal to zero with only one operation. We can use previous elements. So if we have array $\\dots, 0, 0, 1$ we can change values of the first, the fourth and the seventh elements from the end. But $\\dots, 0, 1, 1$ is counter-example. Ok, let's try to make six last elements of array be equal to zero with two operations. We can check by hand or bruteforce that it can be done and $n \\ge 11$ is enough. So we have such solution: Let $k$ is the number of first elements of array which we didn't try to make be equal to zero. In the start $k = n$ While $k \\ge 11$ make $k$-th, $(k - 1)$-th,.., $(k - 5)$-th elements be equal to zero. Subtract 6 from $k$. If $k \\le 10$ run bruteforce on the first $10$ elements or on the whole array if $n < 10$. How many operations will be done? In the second item the number of operations is less or equal than $2 \\cdot \\lfloor \\frac{n}{6} \\rfloor \\le \\lfloor \\frac{n}{3} \\rfloor$ In the third item the number of operations is less or equal than 6 (can be checked by hand or bruteforce) So the total number of operations is less or equal than $\\lfloor \\frac{n}{3} \\rfloor + 6$, what is good enough.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1031",
    "index": "F",
    "title": "Familiar Operations",
    "statement": "You are given two positive integers $a$ and $b$. There are two possible operations:\n\n- multiply one of the numbers by some prime $p$;\n- divide one of the numbers on its prime factor $p$.\n\nWhat is the minimum number of operations required to obtain two integers having the same number of divisors? You are given several such pairs, you need to find the answer for each of them.",
    "tutorial": "Note that if $a = \\prod\\limits_{i=1}^{k} p_i ^ {x_i}$ then $d(a) = \\prod\\limits_{i=1}^{k}(x_i+1)$. This implies that we can map $a$ to vector $(x_1, x_2, \\ldots, x_k)$, where $x_1 \\ge x_2 \\ge \\ldots \\ge x_k$, because the order of the powers doesn't matter. The operations correspond to adding 1 to some item or appending 1 to the end of the vector or decreasing 1 from some item and sorting the vector after that, erasing zeros. There are only 289 different such vectors for numbers up to $10^6$, so we need to calculate only 41616 distances. The first thought could be to just run Floyd-Warshall algorithm on these 289 vertices, which would fit in time. After that for each pair $(x, d)$ we can find the minimum number of operations needed to make with vector $x$ so that the generated number has $d$ divisors. To find the answer for $(x, y)$, we could simply iterate over all possible values of $d$. But there are some tricky cases. For example, for numbers $2^{19}$ and $2^2 3^6$ the answer is 1, because after multiplying the first number by 2 both numbers have 21 divisors. But the number $2^{20} > 10^6$, and the vector $(20)$ is not among these 289 vertices. So, we need to consider some other vectors too. Anyway, let's run this algorithm to see what could be the maximal distance between the two numbers up to $10^6$. It turns out that in 10 operations any two numbers can be led to have the same number of divisors when all numbers in the path don't exceed $10^6$ too. This means that each possible number in the optimal path satisfies $\\sum\\limits_{i=1}^{k} x_i < 30$, because for the numbers in the input this sum doesn't exceed 19, and there can be no more than 10 operations with each number. This condition gives us all vectors of powers necessary to consider as middle points for the pairs which can be in the input. There are 28629 such vectors. Now we run 289 bfs instances on the generated graph with the start in each possible vector from the input and build the same data structure for pairs $(x, d)$ as explained before, which allows us to find the answers for all vectors of numbers up to $10^6$. This solution works in 2.5s on cf servers, which is still too slow. But the thing is that we found answers for all pairs of the vectors from the input. So we can try to get rid of some unnecessary vertices and simply check if the sum of answers is unchanged. One of the possible speedups is to consider only vectors generating the number of divisors not more than some reasonable number. The maximum number of divisors of some necessary vector is 288, so magic constants like 300 or more will work. Another possible speedup is to decrease the border on the sum of powers from 30 to 22, which is precise.",
    "tags": [
      "brute force",
      "graphs",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1032",
    "index": "A",
    "title": "Kitchen Utensils",
    "statement": "The king's birthday dinner was attended by $k$ guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.\n\nAll types of utensils in the kingdom are numbered from $1$ to $100$. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife.\n\nAfter the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils.",
    "tutorial": "Suppose we've found the minimum possible number $p$ of dishes served for each person. If the input contains utensils of $t$ types exactly, it's clear that the total number of utensils used is at least $p \\cdot t \\cdot k$ and the number of utensils stolen is at least $p \\cdot t \\cdot k - n$. Moreover, it's easy to construct an example with this exact number of stolen utensils having our $n$ objects served. It is also easy to note that the minimum $p$ is equal to the ratio of the maximum number of utensils of one type and the number of guests, rounded up.",
    "tags": [],
    "rating": 900
  },
  {
    "contest_id": "1032",
    "index": "B",
    "title": "Personalized Cup",
    "statement": "At many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.\n\nThe nameplate is to be rectangular and the text on it will be printed as a table of several rows and columns. Having some measurements done, the organizers have found out that the number $a$ of rows cannot be greater than $5$ while the number $b$ of columns cannot exceed $20$. Every cell of the table will contain either an asterisk («*») or a letter of user's handle.\n\nFurthermore, the organizers want the rows of the table to be uniform, which means that the number of asterisks used in different rows should differ by at most one (i.e. you can't have two asterisks in the first row and none in the second). The main goal, however, is to obtain the winner's handle precisely when reading the table from top to bottom and from left to right in every row (skipping asterisks).\n\nThe organizers want for the nameplate to have as few rows as possible and among all valid tables with the minimum number of rows they want to choose the one that has the minimum number of columns.\n\nThe winner is not yet determined so your task is to write a program that, given a certain handle, generates the necessary table.",
    "tutorial": "Let's iterate over all possible pairs $(a, b)$ with $1 \\leq a \\leq 5$ and $1 \\leq b \\leq 20$ to find the optimal one satisfying the inequality $a \\cdot b \\geq |s|$. So now we need to place the characters of $s$ in the same relative order through the table. Possibly, several cells will remain unused, but we will distribute them over the table and place at most one asterisk in every row. One can show that we will have at most one asterisk in each row, because otherwise we would have been able to reduce the value of $b$.",
    "tags": [],
    "rating": 1200
  },
  {
    "contest_id": "1032",
    "index": "C",
    "title": "Playing Piano",
    "statement": "Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence $a_1, a_2, \\ldots, a_n$ of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.\n\nPaul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.\n\nLet's denote the fingers of hand by numbers from $1$ to $5$. We call a fingering any sequence $b_1, \\ldots, b_n$ of fingers numbers. A fingering is convenient if for all $1\\leq i \\leq n - 1$ the following holds:\n\n- if $a_i < a_{i+1}$ then $b_i < b_{i+1}$, because otherwise Paul needs to take his hand off the keyboard to play the $(i+1)$-st note;\n- if $a_i > a_{i+1}$ then $b_i > b_{i+1}$, because of the same;\n- if $a_i = a_{i+1}$ then $b_i\\neq b_{i+1}$, because using the same finger twice in a row is dumb. \\textbf{Please note that there is $\\neq$, not $=$ between $b_i$ and $b_{i+1}$.}\n\nPlease provide any convenient fingering or find out that there is none.",
    "tutorial": "Let $dp[i][j]$ be $-1$ if we cannot play the first $i$ notes in such a way that the $i$-th note is played by the $j$-th finger, otherwise let this be the number of the previous finger in any of possible fingerings. This $dp$ can be easily calculated for about $5n\\cdot 5$ operations.",
    "tags": [
      "constructive algorithms",
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1032",
    "index": "D",
    "title": "Barcelonian Distance",
    "statement": "In this problem we consider a very simplified model of Barcelona city.\n\nBarcelona can be represented as a plane with streets of kind $x = c$ and $y = c$ for every integer $c$ (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points $(x, y)$ for which $ax + by + c = 0$.\n\nOne can walk along streets, including the avenue. You are given two integer points $A$ and $B$ somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to $B$ from $A$.",
    "tutorial": "One way is to handle some cases: intersect the line with the border of the bounding box of $(x_1, y_1)$ and $(x_2, y_2)$, and relax answer by some values depending on the mutual location of intersection points, as on the pics below. Another way is to intersect horizontal and vertical lines through $(x_1, y_1)$ and $(x_2, y_2)$, intersect them with the $ax + by + c = 0$ line, consider the obtained 6 points as vertices of a graph, add all horizontal and vertical edges in this graph, run Floyd/Ford-Bellman/Dijkstra algorithm.",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1032",
    "index": "E",
    "title": "The Unbearable Lightness of Weights",
    "statement": "You have a set of $n$ weights. You know that their masses are $a_1$, $a_2$, ..., $a_n$ grams, but you don't know which of them has which mass. You can't distinguish the weights.\n\nHowever, your friend does know the mass of each weight. You can ask your friend to give you exactly $k$ weights with the total mass $m$ (both parameters $k$ and $m$ are chosen by you), and your friend will point to any valid subset of weights, if it is possible.\n\nYou are allowed to make this query only once. Find the maximum possible number of weights you can reveal after this query.",
    "tutorial": "Suppose the numbers $a_{1}, a_{2}, \\ldots, a_{n}$ can have only up to two different values. Then we can unambiguously determine the masses of all the weights (e.g., suppose there are $t$ weights with a mass of $w$ each, then we can ask our friend about a set of $t$ weights with a total mass of $t \\cdot w$; the only thing he can do is to return all the weights with the mass $w$, so we can reveal the masses of all the weights). If the masses of the weights have at least three different values then the only thing we can do is to determine several weights of the same mass (because if the friend tells us a set having distinct masses, we cannot distinguish them from one another; the same holds for the set of remaining weights). So we need to ask our friend such values $(k, m)$ that the only way to obtain the mass $m$ using $k$ weights is to take $k$ weights of mass $\\frac{m}{k}$ each. So now we have reduced our problem to finding for every $w \\leq \\sum\\limits_{i = 1}^{n} a_{i}$ and every number of weights $k \\leq n$ the number of ways (regardless of the order of the weights) to obtain a mass of $w$ using precisely $k$ weights. This value $cnt(w, k)$ can be computed via a simple dynamic programming. Finally, the answer will be equal to the maximum such $k$ that for some $b$ there exist at least $k$ weights with mass $b$ each and the mass $k \\cdot b$ can be obtained uniquely. One should note that it's sufficient to calculate, say, $\\min(2, cnt(w, k))$ instead of $cnt(w, k)$ since the latter can be quite large.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1032",
    "index": "F",
    "title": "Vasya and Maximum Matching",
    "statement": "Vasya has got a tree consisting of $n$ vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove.\n\nA matching in the graph is a subset of its edges such that there is no vertex incident to two (or more) edges from the subset. A maximum matching is a matching such that the number of edges in the subset is maximum possible among all matchings in this graph.\n\nSince the answer may be large, output it modulo $998244353$.",
    "tutorial": "Firstly let's understand when the maximum matching in the tree is unique - and it is unique if and only if it's perfect (i. e. every vertex having at least one incident edge is saturated). So the problem is reduced to counting the number of ways to split the tree so that each component having size $2$ or more has a perfect matching. Let's use dynamic programming to do this. Let $dp_{v,0 \\dots 2}$ be the number of ways to delete edges in the subtree of $v$ so that in this subtree every component is valid (if its size is more than $1$, then it has a perfect matching). The second parameter can take one of three values: $dp_{v,0}$ - $v$ can be used for the matching (but it's not necessary to do it). $dp_{v,1}$ - $v$ is already used in the matching. $dp_{v,2}$ - $v$ is not used in the matching yet, but we have to match it to some vertex. Then $dp_{v, 0} = \\prod\\limits_{to}{dp_{to, 0}} + \\sum\\limits_{to} (dp_{to, 1} \\cdot \\prod\\limits_{to', to' \\ne to}(dp_{to', 0} + dp_{to', 2}) )$, $dp_{v, 1} = \\prod\\limits_{to}(dp_{to, 0} + dp_{to, 2})$, $dp_{v, 2} = \\sum\\limits_{to} (dp_{to, 1} \\cdot \\prod\\limits_{to', to' \\ne to}(dp_{to', 0} + dp_{to', 2}) )$, where $to$ and $to'$ are children of $v$.",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1032",
    "index": "G",
    "title": "Chattering",
    "statement": "There are $n$ parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely $r_i$. When a parrot with respect level $x$ starts chattering, $x$ neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, and so on, until all the birds begin to chatter.\n\nYou are given the respect levels of all parrots. For each parrot answer a question: if this certain parrot starts chattering, how many seconds will pass until all other birds will start repeating it?",
    "tutorial": "Let us for a moment think that parrots stand in a line. We want to compute a series of values $r_{i, k}$ and $l_{i, k}$. $l_{i, k}$ is the index of the leftmost parrot that will chatter in $2^k$ seconds after the $i$-th parrot starts chattering. $r_{i, k}$ is defined similarly. Clearly, $l_{i, 0} = i - a_i$ and $r_{i, 0} = i + a_i$. We calculate $l_{i, k}$ using the values with lesser $k$. Precisely, $l_{i, k} = \\min l_{t, k-1}$, where $t$ goes in range $[l_{i, k-1}, r_{i, k-1}]$. Explanation: the $i$-th parrot triggered some $t$-th parrot in $2^{k-1}$ seconds, then the $t$-th parrot triggered some other parrot in next $2^{k-1}$ seconds. Thus we want to find such $t$ that the leftmost parrot triggered by $t$ is minimum possible. We use a segment tree or a sparse table on the values of the $(k-1)$-th level to compute the value of the DP on the $k$-th level. The idea for the solution on a circle is essentially the same, but you must consider segments more carefully. One rather simple way to do it is to duplicate all the parrots, now numbering them $\\dots, -2, -1, 0, 1, \\dots, n-1, n, n+1, \\dots$ such that the numbers with the same remainder modulo $n$ denote the same parrot. Then we can bound the values for $l_{i, k}$ and $r_{i, k}$ between $-n$ and $2n$. Now a range query over a circle transforms to a constant number of range queries over a segment. Time complexity: $O(n \\log^2 n)$.",
    "tags": [],
    "rating": 2900
  },
  {
    "contest_id": "1033",
    "index": "A",
    "title": "King Escape",
    "statement": "Alice and Bob are playing chess on a huge chessboard with dimensions $n \\times n$. Alice has a single piece left — a queen, located at $(a_x, a_y)$, while Bob has only the king standing at $(b_x, b_y)$. Alice thinks that as her queen is dominating the chessboard, victory is hers.\n\nBut Bob has made a devious plan to seize the victory for himself — he needs to march his king to $(c_x, c_y)$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, \\textbf{she no longer moves any pieces around, and it is only Bob who makes any turns.}\n\nBob will win if he can move his king from $(b_x, b_y)$ to $(c_x, c_y)$ \\textbf{without ever getting in check}. Remember that a king can move to any of the $8$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen.\n\nFind whether Bob can win or not.",
    "tutorial": "Imagine a two-dimensional plane with origin positioned on the black queen. We notice that the queen partitions the board into up to four connected components, with each quadrant being one of them. The answer is thus \"YES\" if and only if the source king position and the target position are in the same quadrant. This condition can be checked in $\\mathcal O(1)$ using few simple ifs. In case you prefer brute force over case analysis, it is also possible to construct the grid graph and find the connected components or use DFS to find the path. This runs in $\\mathcal O(n^2)$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1033",
    "index": "B",
    "title": "Square Difference",
    "statement": "Alice has a lovely piece of cloth. It has the shape of a \\textbf{square} with a side of length $a$ centimeters. Bob also wants such piece of cloth. He would prefer a \\textbf{square} with a side of length $b$ centimeters (where $b < a$). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to Bob. Now she is left with an ugly L shaped cloth (see pictures below).\n\nAlice would like to know whether the area of her cloth expressed in square centimeters is prime. Could you help her to determine it?",
    "tutorial": "The task looks simple enough, but there is a problem. The number we want to check might be very large - it might not even fit into 64-bit integer. Checking primality for it certainly cannot be performed naively. However, the input is no ordinary number. It is of form $A^2 - B^2$, which can be expressed as $(A-B)(A+B)$. This is prime if and only if $A-B = 1$ and $A+B$ is a prime. Since $A + B$ is at most $2*10^{11}$, we can use trial division to check its primality. Complexity: $O(T \\sqrt{A + B})$. Alternatively, you could cheat and use big integers and test primality using Miller-Rabin algorithm. With Java's BigInteger.isProbablePrime it's not too much work.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1033",
    "index": "C",
    "title": "Permutation Game",
    "statement": "After a long day, Alice and Bob decided to play a little game. The game board consists of $n$ cells in a straight line, numbered from $1$ to $n$, where each cell contains a number $a_i$ between $1$ and $n$. Furthermore, no two cells contain the same number.\n\nA token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell $i$ to cell $j$ only if the following two conditions are satisfied:\n\n- the number in the new cell $j$ must be strictly larger than the number in the old cell $i$ (i.e. $a_j > a_i$), and\n- the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. $|i-j|\\bmod a_i = 0$).\n\nWhoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.",
    "tutorial": "The game is finite thanks to the first restriction on possible moves: the number on which the token lies must strictly increase with each turn. More importantly, this means that if we model the cells as vertices of a graph and create a directed edge between $i$ and $j$ if $i \\rightarrow j$ is a valid move, the resulting graph will be acyclic. For each vertex we want to know whether it is losing or winning. A vertex is winning if and only if there exists an edge to a losing state. This is easily solved on a directed acyclic graph - we process the vertices in reverse topological ordering. Let $v$ denote the current vertex. We already know the outcome of the game for all vertices adjacent to $v$, hence it is easy to determine whether $v$ is winning. This process needs $\\mathcal O(n + m)$ time, where $m$ is the number of edges in the graph. In general, this could be quadratic in $n$, but in this particular graph it's actually much less than that! Thanks to the second restriction on possible moves, there are at most $\\lfloor \\frac{n}{a_i} \\rfloor$ possible moves from cell with $a_i$ written in it. As $a_i$ is a permutation, we have at most $\\sum_{i=1}^{n} \\lfloor \\frac{n}{i} \\rfloor$ potential edges, which is of order $\\mathcal O(n \\log n)$.",
    "tags": [
      "brute force",
      "dp",
      "games"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1033",
    "index": "D",
    "title": "Divisors",
    "statement": "You are given $n$ integers $a_1, a_2, \\ldots, a_n$. Each of $a_i$ has between $3$ and $5$ divisors. Consider $a = \\prod a_i$ — the product of all input integers. Find the number of divisors of $a$. As this number may be very large, print it modulo prime number $998244353$.",
    "tutorial": "Given a prime factorisation $a = p_1^{e_1} \\cdot p_2^{e_2} \\cdot \\dots \\cdot p_k^{e_k}$, one can conclude that the number of divisors of $a$ is $\\prod (e_i + 1)$. Note that we do not need to know the values of $p_i$. Can we perhaps find the exponents, without factorising all inputs? A number with between 3 and 5 divisors is of a form $pq$, $p^2$, $p^3$ or $p^4$, where $p$ and $q$ are primes. We can factorise numbers of all forms except the first easily. How about the rest? We can use Euclidean algorithm to find $gcd(a_i, a_j)$ for all pairs $a_i \\neq a_j$. If $g \\neq 1$, we can use it to factorise both $a_i$ and $a_j$. After this process, some $a_i$ all still left unfactorised. We can conclude that they do not share any prime factor with any other number (except the number itself if there are multiple copies). This means that it contributes to the factorisation with two prime factors of multiplicity 1. For all other prime factors, we simply calculate how many times they occur in all factorised $a_i$ combined. This combined, we can evaluate $\\prod (e_i + 1)$. The time complexity is $O(n^2 \\cdot \\log \\max a_i)$. Note that we can factorise all input using Pollard rho algorithm (which has unknown complexity, but it is presumed to be the square root of the smallest prime factor) in $\\mathcal O(\\sum \\sqrt[\\leftroot{-2}\\uproot{2}4]{a_i})$. This looks good enough, but in practice is very slow and doesn't pass the TL by a large margin.",
    "tags": [
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1033",
    "index": "E",
    "title": "Hidden Bipartite Graph",
    "statement": "Bob has a simple undirected connected graph (without self-loops and multiple edges). He wants to learn whether his graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color) or not. As he is not very good at programming, he asked Alice for help. He does not want to disclose his graph to Alice, but he agreed that Alice can ask him some questions about the graph.\n\nThe only question that Alice can ask is the following: she sends $s$ — a subset of vertices of the original graph. Bob answers with the number of edges that have both endpoints in $s$. Since he doesn't want Alice to learn too much about the graph, he allows her to ask no more than $20000$ questions. Furthermore, he suspects that Alice might introduce false messages to their communication channel, so when Alice finally tells him whether the graph is bipartite or not, she also needs to provide a proof — either the partitions themselves or a cycle of odd length.\n\nYour task is to help Alice to construct the queries, find whether the graph is bipartite.",
    "tutorial": "Denote by $e(A)$ the number of edges in a vertex set $A$, and by $e(A,B)$ the number of edges between $A$ and $B$. Note that $e(A,B) = e(A \\cup B) - e(A) - e(B)$ can be answered by three queries. Now we learn how to find an edge in this graph in logarithmic time. Given two sets $X$ and $Y$, such that $e(X,Y) \\neq 0$, we can binary search on $X$, i.e. partition $X$ into disjoint $X_1$ and $X_2$ of roughly equal size. If $e(X_1, Y) \\neq 0$, we continue to find an edge between $X_1$ and $Y$, otherwise certainly $e(X_2, Y) = e(X,Y) \\neq 0$ and we can search for an edge between $X_2$ and $Y$. Once $|X| = 1$, we can do a similar binary search on $Y$. Finally, when both $|X| = 1$ and $|Y| = 1$ while $e(X,Y) \\neq 0$, we have found an edge in graph G. How do we use the above construction? We can find a spanning tree of graph $G$, as follows. Start with $S = \\{1\\}$ and find an edge between $S$ and $V \\setminus S$. We remember this edge, add its second endpoint to $S$ and repeat until $S = V$. Ugh! Next question? Once we have a spanning tree, the task is much easier. As the knowledge of a spanning tree on a bipartite graph uniquely identifies the partitions (using a simple DFS, for instance), we can use two queries to determine whether the graph is bipartite or not. If it is, we have already found the partition and can report it. Otherwise, we can use similar binary search to find an edge in one of the partitions. Again, we use DFS to find the required cycle of odd length. The total number of queries is roughly $6 N \\log N$, as for each vertex, we perform two binary searches and each operation of binary search requires 3 queries. This totals up to 36000, which seems like too much. However, most of the time, one or two of the three queries have already been asked before and we can cache the answers. Furthermore, we can avoid asking queries of size 1 - we know that the answer is simply 0. With these optimisations, we can find out that the actual number of queries is actually around 17000 in the worst case.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "interactive"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1033",
    "index": "F",
    "title": "Boolean Computer",
    "statement": "Alice has a computer that operates on $w$-bit integers. The computer has $n$ \\textbf{registers} for values. The current content of the registers is given as an array $a_1, a_2, \\ldots, a_n$.\n\nThe computer uses so-called \"number gates\" to manipulate this data. Each \"number gate\" takes two registers as inputs and calculates a function of the two values stored in those registers. Note that you can use the same register as both inputs.\n\nEach \"number gate\" is assembled from bit gates. There are six types of bit gates: AND, OR, XOR, NOT AND, NOT OR, and NOT XOR, denoted \"A\", \"O\", \"X\", \"a\", \"o\", \"x\", respectively. Each \\textbf{bit gate} takes two bits as input. Its output given the input bits $b_1$, $b_2$ is given below:\n\n\\begin{center}\n$\\begin{matrix} b_1 & b_2 & A & O & X & a & o & x \\\\ 0 & 0 & 0 & 0 & 0 & 1 & 1 & 1 \\\\ 0 & 1 & 0 & 1 & 1 & 1 & 0 & 0 \\\\ 1 & 0 & 0 & 1 & 1 & 1 & 0 & 0 \\\\ 1 & 1 & 1 & 1 & 0 & 0 & 0 & 1 \\\\ \\end{matrix}$\n\\end{center}\n\nTo build a \"number gate\", one takes $w$ bit gates and assembles them into an array. A \"number gate\" takes two $w$-bit integers $x_1$ and $x_2$ as input. The \"number gate\" splits the integers into $w$ bits and feeds the $i$-th bit of each input to the $i$-th bit gate. After that, it assembles the resulting bits again to form an output word.\n\nFor instance, for $4$-bit computer we might have a \"number gate\" \"AXoA\" (AND, XOR, NOT OR, AND). For two inputs, $13 = 1101_2$ and $10 = 1010_2$, this returns $12 = 1100_2$, as $1$ and $1$ is $1$, $1$ xor $0$ is $1$, not ($0$ or $1$) is $0$, and finally $1$ and $0$ is $0$.\n\nYou are given a description of $m$ \"number gates\". For each gate, your goal is to report the number of register pairs for which the \"number gate\" outputs the number $0$. In other words, find the number of ordered pairs $(i,j)$ where $1 \\leq i,j \\leq n$, such that $w_k(a_i, a_j) = 0$, where $w_k$ is the function computed by the $k$-th \"number gate\".",
    "tutorial": "First we count $C[i]$ the number of occurrences of $i$ in the input for each number between $0$ and $2^w - 1$. We can then notice that each bit gate $G$ maps between $1$ and $3$ two-bit patterns to $0$ (e.g. for xor gate, this is 00 and 11, for and gate this is 00, 01 and 10). This means that we can calculate the answer for each number gate in $\\mathcal O(3^w)$, which yields $\\mathcal O(m \\cdot 3^w)$ algorithm, that is clearly too slow. How do we make this faster? There are at least two approaches. Interpret each binary input as if it were ternary. For instance, $11 = 1011_2 \\approx 1011_3$. Consider two ternary numbers consisting only of digits $0$ and $1$ and their sum - e.g. $1001_3 + 1010_3 = 2011_3$. Since there are no carryovers, the $i$-th digit of the sum tells us how many of the two summands have the respective digit equal to $1$. In the example above, the most significant digit is $2$, and we can observe that both inputs have $1$ as the most significant digit.Each of the six binary gates in the output behaves identically on two bit patterns $01$ and $10$. It follows that each number gate $G$ can be expressed as some function $G'$, such that $G(i,j) = G'(i+j)$, i.e. the outcome of the number gate depends only on their sum. For example, the bit gate AND maps $0$, $1$ to $0$ and $2$ to $1$, the gate NOT XOR maps $0$ and $2$ to $1$ and $1$ to $0$. Furthermore, each gate maps between $1$ and $2$ digits to $0$. For each $G'$, there are thus at most $2^w$ values of $x$ such that $G'(x) = 0$, and those values can be found efficiently. To find the answer, we need to find for each $x \\in [0, 3^w)$ how many pairs of inputs sum to $x$ in ternary. This amount is equal to the sum $\\sum_{i+j = x} C[i] * C[j]$ where $C[i]$ is the number of occurrences of $i$ in the array $A$. This can be precomputed once, either by FFT in $\\mathcal O(w \\cdot 3^w)$ since it is a convolution, or by brute force in $\\mathcal O(4^w)$. The latter has much better constant factor and is in fact slightly faster. Combined, this yields a $\\mathcal O(n + w \\cdot 3^w + m \\cdot 2^w)$ algorithm. Each of the six binary gates in the output behaves identically on two bit patterns $01$ and $10$. It follows that each number gate $G$ can be expressed as some function $G'$, such that $G(i,j) = G'(i+j)$, i.e. the outcome of the number gate depends only on their sum. For example, the bit gate AND maps $0$, $1$ to $0$ and $2$ to $1$, the gate NOT XOR maps $0$ and $2$ to $1$ and $1$ to $0$. Furthermore, each gate maps between $1$ and $2$ digits to $0$. For each $G'$, there are thus at most $2^w$ values of $x$ such that $G'(x) = 0$, and those values can be found efficiently. To find the answer, we need to find for each $x \\in [0, 3^w)$ how many pairs of inputs sum to $x$ in ternary. This amount is equal to the sum $\\sum_{i+j = x} C[i] * C[j]$ where $C[i]$ is the number of occurrences of $i$ in the array $A$. This can be precomputed once, either by FFT in $\\mathcal O(w \\cdot 3^w)$ since it is a convolution, or by brute force in $\\mathcal O(4^w)$. The latter has much better constant factor and is in fact slightly faster. Combined, this yields a $\\mathcal O(n + w \\cdot 3^w + m \\cdot 2^w)$ algorithm. The second approach was suggested by arsijo. Let's introduce a wildcard in the bit patterns: e.g. $1?0?$ matches all of $1000$, $1001$, $1100$, $1101$. This can be found in $\\mathcal O(w \\cdot 3^w)$ from the array $C$ by substituting the bits with the wildcard bit by bit, and denote this array of counts by $D$.The zero values of each bit gate can be expressed as at most two bit patterns while using wildcards. For instance, the AND gate yields zero with $0?$ and $10$. With the help of the arrays $C$ and $D$, the answer for each number gate can be found in $\\mathcal O(2^w)$. This also yields a $\\mathcal O(n + w \\cdot 3^w + m \\cdot 2^w)$ algorithm. The zero values of each bit gate can be expressed as at most two bit patterns while using wildcards. For instance, the AND gate yields zero with $0?$ and $10$. With the help of the arrays $C$ and $D$, the answer for each number gate can be found in $\\mathcal O(2^w)$. This also yields a $\\mathcal O(n + w \\cdot 3^w + m \\cdot 2^w)$ algorithm.",
    "tags": [
      "bitmasks",
      "brute force",
      "fft",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1033",
    "index": "G",
    "title": "Chip Game",
    "statement": "Alice and Bob decided to play one ultimate game. They have $n$ piles, the $i$-th pile initially contain $v_i$ chips. Alice selects a positive integer $a$ from interval $[1, m]$, and Bob selects a number $b$ the same way.\n\nThen the game starts. In her turn, Alice can select any pile containing at least $a$ chips, and remove exactly $a$ chips from it. Similarly, in his turn, Bob can choose any pile with at least $b$ chips, and remove exactly $b$ chips from it. If a player cannot make a move, he or she loses.\n\nIf both players play optimally, the outcome ultimately depends on the choice of $a$ and $b$, and on the starting player. Consider a fixed pair $(a,b)$. There are four types of games:\n\n- \\textbf{Alice} wins, regardless of who starts.\n- \\textbf{Bob} wins, regardless of who starts.\n- If Alice starts, she wins. If Bob starts, he wins. We say that the \\textbf{first} player wins.\n- If Alice starts, Bob wins. If Bob starts, Alice wins. We say that the \\textbf{second} player wins.\n\nAmong all choices of $a$ and $b$ (i.e. for each pair $(a, b)$ such that $1\\leq a, b\\leq m$), determine how many games are won by Alice (regardless of who starts), how many are won by Bob (regardless of who starts), how many are won by the first player, and how many are won by the second player.",
    "tutorial": "Let's solve the task for a fixed tuple $(a, b)$. If $a = b$, this is a very simple symmetric game, where the parity of $\\sum \\lfloor \\frac{v_i}{a} \\rfloor$ determines the winner (regardless of the players' choices). Without loss of generality, let $a < b$ as the case where $a > b$ is symmetrical. It is obvious that Bob never has an advantage in this game. Furthermore, the game outcome doesn't change if we set $v'_i = v_i \\mod (a + b)$. To see why this is true, consider a strategy $S'$ for a winning player in the modified game $G'$, and build strategy $S$ for the original game: If the winner takes first turn in $G'$, take the same first turn in $G$ - this is always valid as $v'_i \\leq v_i$. If the loser's last turn was valid in the game $G'$, follow the strategy $S'$ in the game $G$. Again, this is valid as $v'_i \\leq v_i$. If the loser's last turn was invalid in the game $G'$, this means that he reduced the state from $x_1 \\cdot (a+b) + y_1$ to $(x_1-1) \\cdot (a+b) + y_2$ for some $x_1 > 0$ and $0 \\leq y_1 < y_2 < a + b$. The winner can play in the same pile to reduce it to $(x_1-1) \\cdot (a+b) + y_1$, and the corresponding $v'_i$ doesn't change. In essence, these two moves are a no-op in the game $G'$. Let's break down the single pile games $P$ based on the number of chips modulo $a+b$: $0 \\leq v'_i < a$: As neither Alice nor Bob can make a move, this is a zero game ($P = 0$). $a \\leq v'_i < b$: Alice can take at least one move in this pile, and Bob none. This is a strictly positive game ($P > 0$). $b \\leq v'_i < 2a$: If either of the players makes a move, it changes to a zero game. This is thus a fuzzy game ($P || 0$). Note that this interval may be empty. $\\max(2a, b) \\leq v'_i < a + b$: If Alice makes a move, she can turn this game into a positive game for her. Bob can turn this into a zero game. This is a fuzzy game ($P || 0$). As we see, there are no negative games. Hence, in the combined game, we can ignore the zero games in our calculation (type $1$) and if there is at least one positive game (type $2$), the game is won for Alice. If there is at least one game of type $4$ and Alice starts, or at least two games of type $4$, Alice can always play one of them to make herself a positive game, thus winning. Otherwise, it is always optimal to play in a game of type $3$ or $4$ if there is one, and the game is subsequently turned into a zero game. The parity of the number of these games thus determines whether the starting player wins or loses. For a fixed $(a, b)$, we are now able to determine the outcome of the game in $\\mathcal O(n)$ time, leading to $\\mathcal O(m^2n)$ total runtime, which is too slow. To make this faster, let's group the games by the sum $a + b$. For a fixed $v'_i$, define function $f(a)$ which tells us the type of the single-pile game based on the value of $a$ for this particular $v'_i$. We can see that this function is not arbitrary - we can partition the interval $[0, a+b)$ into constantly many intervals on which the function is constant (e.g. if $a \\in (v'_i, a+b)$, this is a zero game. We simply collect all these intervals for all values of $v'_i$ and using a linear sweep determine the outcome of each game. This needs $\\mathcal O(n \\log n)$ for sorting and $\\mathcal O(n)$ for the sweep. All combined, this yields a $\\mathcal O(m n \\log n)$ algorithm. Bonus: Can you get rid of the log factor?",
    "tags": [
      "games"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1034",
    "index": "A",
    "title": "Enlarge GCD",
    "statement": "Mr. F has $n$ positive integers, $a_1, a_2, \\ldots, a_n$.\n\nHe thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.\n\nBut this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.\n\nYour task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.",
    "tutorial": "First we divide all numbers by GCD of them. Then we should find a subset with maximum number of integers GCD of which is bigger than $1$. We can enumerate a prime $p$ that GCD of the remaining integers can be divided by. And the number of integers can be divided by $p$ is the maximum size of the subset. We can use Sieve of Euler to factor all integers in $O(m a x(a_{i})+\\sum\\log a_{i})$ time. Then we find the prime that can divide most integers. The answer is $n$ minus the number of integers can be divided by this prime. If all integers are $1$ (after dividing their GCD), there is no solution.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define MN 300000\n#define MX 15000000\nint a[MN+5],u[MX+5],p[MX+5],pn,s[MX+5];\nint gcd(int x,int y){return y?gcd(y,x%y):x;}\nint main()\n{\n\tint n,i,j,g,x,ans=0;\n\tfor(i=2;i<=MX;++i)\n\t{\n\t\tif(!u[i])u[i]=p[++pn]=i;\n\t\tfor(j=1;i*p[j]<=MX;++j){u[i*p[j]]=p[j];if(i%p[j]==0)break;}\n\t}\n\tscanf(\"%d\",&n);\n\tfor(g=0,i=1;i<=n;++i)scanf(\"%d\",&a[i]),g=gcd(g,a[i]);\n\tfor(i=1;i<=n;++i)for(j=a[i]/g;j>1;)for(++s[x=u[j]];u[j]==x;)j/=u[j];\n\tfor(i=1;i<=MX;++i)ans=max(ans,s[i]);\n\tprintf(\"%d\",ans?n-ans:-1);\n}",
    "tags": [
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1034",
    "index": "B",
    "title": "Little C Loves 3 II",
    "statement": "Little C loves number «3» very much. He loves all things about it.\n\nNow he is playing a game on a chessboard of size $n \\times m$. The cell in the $x$-th row and in the $y$-th column is called $(x,y)$. Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between which is exactly $3$. The Manhattan distance between two cells $(x_i,y_i)$ and $(x_j,y_j)$ is defined as $|x_i-x_j|+|y_i-y_j|$.\n\nHe want to place as many chessmen as possible on the chessboard. Please help him find the maximum number of chessmen he can place.",
    "tutorial": "Following the rules in the problem, the $1  \\times  6$, $2  \\times  4$, $2  \\times  5$ and $3  \\times  4$ grids full of chessmen can be easily constructed. Let the number denote the time when the chessman placed. Grids of $1  \\times  6$ : 1 2 3 1 2 3 Grids of $2  \\times  4$ : 1 2 3 4 3 4 1 2 Grids of $2  \\times  5$ : 1 3 2 1 5 2 4 5 3 4 Grids of $3  \\times  4$ : 1 3 4 2 5 2 1 5 6 4 3 6 Assume that $n  \\le  m$. Consider the following cases: If $n = 1$, obviously the answer is $6\\cdot\\left[{\\frac{m}{6}}\\right]+2\\cdot m a x((m\\,\\mathrm{mod}\\,6)-3,0)$. If $n = 2$, only the $2  \\times  2$, $2  \\times  3$ and $2  \\times  7$ grids cannot be completely constructed. The others can be constructed by using the $2  \\times  4$, $2  \\times  5$ and $2  \\times  6$(constructed by two $1  \\times  6$ grids) girds. You can write a brute force or enumerate all the possibilities by yourself. If you consider each grid from left to right and choose the grid it matched with, there are only several possible conditions. So I think it can be proved in several minutes :) If $n > 2$, the following things we can consider: We know that using the $2  \\times  4$ and $3  \\times  4$ grids we can construct the $4  \\times  x$($x > 2$) grid, and using several $1  \\times  6$ grids we can construct the $6  \\times  x$($x > 2$) grid, so using the $4  \\times  x$ and $6  \\times  x$ grids we can construct the $x  \\times  y$ grid while $x, y > 2$ and $y$ is an even number. Therefore we only need to consider the $n  \\times  m$ grid that $n$ and $m$ are both odd numbers. Since $n  \\times  m$ is an odd integer, we can place $nm - 1$ chessmen at most, so we try to reach the maximum. Then we can easily construct the $3  \\times  3$, $3  \\times  5$ and $5  \\times  5$ grids that have only one empty grid. According to the above-mentioned conclusions, any $n  \\times  m$ grids can be reduce to one of the three grids by using some $x  \\times  y$($x$ or $y$ is even) grids. The maximum is reached. Grids of $3  \\times  3$ : 1 2 3 3 0 4 4 1 2 Grids of $3  \\times  5$ : 1 3 4 6 7 2 5 1 0 5 3 4 2 7 6 Grids of $5  \\times  5$ : 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 10 8 9 12 7 11 12 10 11 0 It seems that the chessboard is a little bit big but you can match them arbitrarily and get correct solution with a big possibility :) This problem is a matching problem. And we found that two grids can be matched only if they have different parities of the sum of two coordinates. So it's actually a biparite graph matching problem :) So we can calculate the answer for all small $n$ and $m$. When $n = 1$ or $m = 1$, the answer is easy to get. Otherwise, we found that if $n$ or $m$ is big enough, the answer will be the maximum. So just keep the answers for small $n$ and $m$, you will get AC easily :)",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint n,m;\n\tscanf(\"%d%d\",&n,&m);\n\tif(n>m)swap(n,m);\n\tif(n==1)printf(\"%d\",m/6*3+max(m%6-3,0)<<1);\n\telse if(n==2)printf(\"%d\",m==2?0:m==3?4:m==7?12:m<<1);\n\telse printf(\"%lld\",1LL*n*m/2*2);\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "flows",
      "graph matchings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1034",
    "index": "C",
    "title": "Region Separation",
    "statement": "There are $n$ cities in the Kingdom of Autumn, numbered from $1$ to $n$. People can travel between any two cities using $n-1$ two-directional roads.\n\nThis year, the government decides to separate the kingdom. There will be regions of different levels. The whole kingdom will be the region of level $1$. Each region of $i$-th level should be separated into several (at least two) regions of $i+1$-th level, unless $i$-th level is the last level. Each city should belong to exactly one region of each level and for any two cities in the same region, it should be possible to travel between them passing the cities in the same region only.\n\nAccording to research, for each city $i$, there is a value $a_i$, which describes the importance of this city. All regions of the same level should have an equal sum of city importances.\n\nYour task is to find how many plans there are to determine the separation of the regions that all the conditions are satisfied. Two plans are considered different if and only if their numbers of levels are different or there exist two cities in the same region of one level in one plan but in different regions of this level in the other plan. Since the answer may be very large, output it modulo $10^9+7$.",
    "tutorial": "First, we try to find whether it's possible to separate the kingdom into $k$ regions of level-$2$ with the same sum of values. We calculate $S$, the sum of all the values, so each region should have sum $\\mathbf{\\Sigma}_{k}^{\\infty}$. Let $s_{i}$ be the sum of values in the subtree of root $i$. We consider all the cities from the leaves to the root, when a subtree $i$ has sum $s_{i}={\\frac{\\mathrm{s}}{k}}$, separating it from the tree. We find that only the $i$ with $s_{i}\\equiv0{\\mathrm{~(mod~}}\\frac{S}{k}){\\mathrm{)}}$ will be considered. So there should be at least $k$ cities satisfying this condition. And if there exist such $k$ cities, we cut the edge to their father (if it is not the root), so the size of each connected part will be multiple of $\\mathbf{\\Sigma}_{k}^{\\infty}$. Since all the values are positive, all the connected parts have size $\\mathbf{\\Sigma}_{k}^{\\infty}$. So we just need to count how many cities $i$ with $s_{i}\\equiv0{\\mathrm{~(mod~}}\\frac{\\mathrm{s}}{k}\\mathrm{)}$ there are. Let the equation be $\\textstyle{\\frac{a}{k}}={\\frac{x}{k}}$, where $x$ is a positive integer, so $k$ should be a multiple of $\\frac{S}{\\operatorname{eqd}(S,s_{i})}$. Now we can use a simple dp with $O(n\\log n)$ time to find whether it's possible to separate the kingdom into $k$ regions of level-$2$ for all the $k$. And it's not difficult to find that there can be $k_{i}$ regions of level-$i$ if and only if there can be $k_{i}$ regions of level-$2$ and $k_{i - 1}$ is a factor of $k_{i}$. Let $f_{i}$ be the number of plans with $i$ regions of the last level, and we enumerate the factors of $i$ to transform. So the total time of this solution is $O(n\\ (\\log n+\\log10^{9}))$ (including the time to calculate the gcd).",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define MN 1000000\n#define MOD 1000000007\nll s[MN+5];int f[MN+5],p[MN+5],F[MN+5];\ninline void rw(int&x,int y){if((x+=y)>=MOD)x-=MOD;}\nint main()\n{\n\tint n,i,j,ans=0;\n\tscanf(\"%d\",&n);\n\tfor(i=1;i<=n;++i)scanf(\"%lld\",&s[i]);\n\tfor(i=2;i<=n;++i)scanf(\"%d\",&p[i]);\n\tfor(i=n;i>1;--i)s[p[i]]+=s[i];\n\tfor(i=n;i;--i)if((s[i]=s[1]/__gcd(s[1],s[i]))<=n)++f[s[i]];\n\tfor(i=n;i;--i)for(j=i;(j+=i)<=n;)f[j]+=f[i];\n\tfor(F[1]=i=1;i<=n;++i)if(f[i]==i)for(rw(ans,F[j=i]);(j+=i)<=n;)rw(F[j],F[i]);\n\tprintf(\"%d\",ans);\n}",
    "tags": [
      "combinatorics",
      "dp",
      "number theory",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1034",
    "index": "D",
    "title": "Intervals of Intervals",
    "statement": "Little D is a friend of Little C who loves intervals very much instead of number \"$3$\".\n\nNow he has $n$ intervals on the number axis, the $i$-th of which is $[a_i,b_i]$.\n\nOnly the $n$ intervals can not satisfy him. He defines the value of an interval of intervals $[l,r]$ ($1 \\leq l \\leq r \\leq n$, $l$ and $r$ are both integers) as the total length of the union of intervals from the $l$-th to the $r$-th.\n\nHe wants to select exactly $k$ different intervals of intervals such that the sum of their values is maximal. Please help him calculate the maximal sum.",
    "tutorial": "First we consider how to calculate the value of an interval of intervals $[l, r]$. We can consider intervals in order from $1$ to $n$ and, for each position on the axis, maintain a timestamp denoting the last time it was covered. When the $r$-th interval is taken into consideration, the timestamps for positions $[a_{r}, b_{r}]$ should all be updated to $r$. Right after that, the desired answer of a query $[l, r]$ is the number of positions whose timestamp is not smaller than $l$. We would like to, for each $r$, keep the desired answer for every $l$. To achieve this, when we change the timestamps of $k$ positions from $r'$ to $r$, the answers for $l$ in $[r' + 1, r]$ should each be increased by $k$. To do it fast, we can merge consecutive positions with the same timestamp into a segment, and use a balanced tree (e.g. std::set) to maintain the segments. $O(1)$ new segments appear when adding an interval, and when a segment is completely covered by later intervals, it will be deleted. By amortized analysis, the total number of balanced tree operations and the number of range modifications of answers (see above) are both $O(n)$. We spend $O(n\\log n)$ time in this part. Now we consider how to get the answer. It's obvious that we will select the $k$ largest values. We can use binary search to find the minimum we finally select, i.e. we should, for several integers $x$, count how many values of $[l, r]$ are not smaller than $x$ and count the sum of these values by the way to get the answer. For each $i$, we will select all $[l, i]$'s such that their interval of intervals values is not smaller than $x$. As the value of $[l, r]$ is not smaller than $[l + 1, r]$ or $[l, r - 1]$, it's obvious that all $l$'s smaller than an integer $L_{i}$ will be taken and $L_{i + 1}$ will be not smaller than $L_{i}$. Now we can iterate $i$ from $1$ to $n$, maintaining the sum of values of $[l, i]$ ($1  \\le  l < L_{i}$) and the value of $[L_{i}, i]$ by maintaining the difference between the answers for $l$ and $l + 1$ (in this way we carry out a range increment in $O(1)$ time). Similar to the sliding-window method, we try to increase $L_{i}$ when $i$ changes to $i + 1$. Therefore, we spend $O(n)$ time for each $x$ we check with. Summing everything up, the total time complexity of this problem is $O(n\\ (\\log n+\\log\\operatorname*{max}b))$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define MN 300000\n#define p make_pair\n#define pb push_back\n#define A first\n#define B second\nset< pair<int,int> > st;\nset< pair<int,int> >::iterator it,tt;\nvector< pair<int,int> > v[MN+5];\nint f[MN+5]; \nint main()\n{\n\tint n,m,i,j,k,l,r,x,X,t2;long long s1,s2,S1,S2,t1;\n\tscanf(\"%d%d\",&n,&m);\n\tst.insert(p(1,0));st.insert(p(1e9,0));\n\tfor(i=1;i<=n;++i)\n\t{\n\t\tscanf(\"%d%d\",&l,&r);\n\t\ttt=(it=st.upper_bound(p(l,n)))--;\n\t\tv[i].pb(p(x=it->B,it->A-tt->A));\n\t\tif(it->A<l)v[i].pb(p(x,l-it->A));\n\t\telse st.erase(it);\n\t\tv[i].pb(p(i,r-l));st.insert(p(l,i));\n\t\twhile(tt->A<r)it=tt++,v[i].pb(p(x=it->B,it->A-tt->A)),st.erase(it);\n\t\tif(tt->A>r)v[i].pb(p(x,tt->A-r)),st.insert(p(r,x));\n\t}\n\tfor(l=1,r=1e9;l<=r;)\n\t{\n\t\tx=l+r>>1;\n\t\tmemset(f,0,sizeof(f));\n\t\tfor(i=j=1,s1=s2=t1=t2=0;i<=n;++i)\n\t\t{\n\t\t\tfor(k=0;k<v[i].size();++k)\n\t\t\t\tif(v[i][k].A<j)t1+=1LL*v[i][k].A*v[i][k].B;\n\t\t\t\telse t1+=1LL*(j-1)*v[i][k].B,t2+=v[i][k].B,f[v[i][k].A]+=v[i][k].B;\n\t\t\twhile(j<=i&&t2>=x)t1+=t2,t2-=f[j++];\n\t\t\ts1+=t1;s2+=j-1;\n\t\t}\n\t\tif(s2>=m)X=x,S1=s1,S2=s2,l=x+1;else r=x-1;\n\t}\n\tprintf(\"%lld\",S1-(S2-m)*X);\n}",
    "tags": [
      "binary search",
      "data structures",
      "two pointers"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1034",
    "index": "E",
    "title": "Little C Loves 3 III",
    "statement": "Little C loves number «3» very much. He loves all things about it.\n\nNow he is interested in the following problem:\n\nThere are two arrays of $2^n$ intergers $a_0,a_1,...,a_{2^n-1}$ and $b_0,b_1,...,b_{2^n-1}$.\n\nThe task is for each $i (0 \\leq i \\leq 2^n-1)$, to calculate $c_i=\\sum a_j \\cdot b_k$ ($j|k=i$ and $j\\&k=0$, where \"$|$\" denotes bitwise or operation and \"$\\&$\" denotes bitwise and operation).\n\nIt's amazing that it can be proved that there are exactly $3^n$ triples $(i,j,k)$, such that $j|k=i$, $j\\&k=0$ and $0 \\leq i,j,k \\leq 2^n-1$. So Little C wants to solve this excellent problem (because it's well related to $3$) excellently.\n\nHelp him calculate all $c_i$. Little C loves $3$ very much, so he only want to know each $c_i \\& 3$.",
    "tutorial": "If we only need to calculate $c_{i}=\\sum a_{j}\\cdot b_{k}$ ($j|k = i$), we can do these: Let $A_{i}=\\sum a_{j},B_{i}=\\sum b_{j}$ ($j|i = i$). Let $A_{i}=\\sum a_{j},B_{i}=\\sum b_{j}$ ($j|i = i$). Let $C_{i} = A_{i} \\cdot Bi$, it can be found that $C_{i}=\\sum c_{j}$ ($j|i = i$). Let $C_{i} = A_{i} \\cdot Bi$, it can be found that $C_{i}=\\sum c_{j}$ ($j|i = i$). So $c_{i}=C_{i}-\\sum c_{j}$ ($j|i = i$ and $j  \\neq  i$). So $c_{i}=C_{i}-\\sum c_{j}$ ($j|i = i$ and $j  \\neq  i$). To calculate $A_{i}$ fast ($B_{i}$ is the same), let $f(x, i)$ be the sum of $a_{j}$ which $j|i = i$ and the lower $x$ binary bits of $j$ is equal to $i$'s. So $f(n, i) = a_{i}$, $f(x - 1, i) = f(x, i)$ if $i&2^{x} = 0$ , $f(x - 1, i) = f(x, i) + f(x, i - 2^{x})$ if $i&2^{x} = 2^{x}$, and $A_{i} = f(0, i)$. We can calculate all $A_{i}$ and $B_{i}$ in $O(n \\cdot 2^{n})$ time. Getting $c_{i}$ from $C_{i}$ is the inversion of getting $A_{i}$ from $a_{i}$. So we can use $f(x, i)$ once again. $f(x, i) = f(x - 1, i)$ if $i&2^{x} = 0$, $f(x, i) = f(x - 1, i) - f(x - 1, i - 2^{x})$ if $i&2^{x} = 2^{x}$. So we can get all $c_{i}$ in $O(n \\cdot 2^{n})$ total time. But in this problem we need to calculate $c_{i}=\\sum a_{j}\\cdot b_{k}$ ($j|k = i$ and $j&k = 0$). In fact, there is a well-known algorithm for this problem. The main idea of this algorithm is consider the number of \"$1$\" binary bits. First, let $BC(x)$ be the number of \"$1$\" binary bits in $x$. Let $A(x,i)=\\sum a_{j},B(x,i)=\\sum b_{j}$ ($j|i = i$ and $BC(j) = x$). Then we calculate $C(x,i)=\\sum A(y,i)\\cdot B(z,i)$ ($y + z = x$), and $c(x,i)=C(x,i)-\\sum c(x,j)$ ($j|i = i$ and $j  \\neq  i$). So $c(x,i)=\\sum a_{j}\\cdot b_{k}$ ($j|k = i$ and $BC(j) + BC(k) = x$). Finally $c_{i}$ we need to calculate is equal to $c(BC(i), i)$, because if $j|k = i$ and $BC(j) + BC(k) = BC(i)$, $j&k$ must be $0$. This algorithm cost $O(n^{2} \\cdot 2^{n})$ time. Unfortunately, it may be too slow in this problem. In this problem, we only need to calculate $c_{i}&3$, equal to $c_{i}$ modulo $4$. In fact, when the answer is modulo $p$, an arbitrary integer, my solution works. Let $A_{i}=\\sum a_{j}\\cdot p^{B C(j)}(j|i=i)$. Then we calculate $F_{i} = A_{i} \\cdot B_{i}$, and $f_{i}=F_{i}-\\sum f_{j}$ ($j|i = i$ and $j  \\neq  i$). So $f_{i}=\\sum a_{j}\\cdot b_{k}\\cdot p^{B C(j)+B C(i)}$ ($j|k = i$). If $j|k = i$, $BC(j) + BC(k)  \\ge  BC(i)$. If $j|k = i$ and $j&k = 0$, $BC(j) + BC(k) = BC(i)$. We find that $c_{i}\\equiv\\frac{f_{i}}{p^{B C(i)}}\\ \\left(\\mathrm{mod}\\ p\\right)$, because if $BC(j) + BC(k) > BC(i)$, $a_{j} \\cdot b_{k} \\cdot p^{BC(j) + BC(k) - BC(i)}$ can be divided by $p$. So the total time is $O(n \\cdot 2^{n})$. A remainder problem is it can not be modulo $p$ when calculating in this algorithm, so the number may be very large. Fortunately, in this problem, $p$ is only $4$. We can use 128-bit integers or merge two 64-bit integers into one number when calculating. But in fact, we only care $\\frac{f_{1}}{p P C(t)}$ modulo $p$, so we can let all number be modulo $p^{n + 1}$. Single 64-bit integer is enough.",
    "code": "#include<cstdio>\ntypedef long long ll;\n#define MN (1<<21)\nchar A[MN+5],B[MN+5];\nint s[MN+5];ll a[MN+5],b[MN+5];\nint main()\n{\n\tint n,i,j;\n\tscanf(\"%d%s%s\",&n,A,B);\n\tfor(i=0;i<1<<n;++i)s[i]=s[i>>1]+((i&1)<<1),a[i]=(ll)(A[i]-'0')<<s[i],b[i]=(ll)(B[i]-'0')<<s[i];\n\tfor(i=0;i<n;++i)for(j=0;j<1<<n;++j)if(j&(1<<i))a[j]+=a[j^(1<<i)],b[j]+=b[j^(1<<i)];\n\tfor(i=0;i<1<<n;++i)a[i]*=b[i];\n\tfor(i=0;i<n;++i)for(j=0;j<1<<n;++j)if(j&(1<<i))a[j]-=a[j^(1<<i)];\n\tfor(i=0;i<1<<n;++i)putchar(((a[i]>>s[i])&3)+'0');\n}",
    "tags": [
      "bitmasks",
      "dp",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1036",
    "index": "A",
    "title": "Function Height",
    "statement": "You are given a set of $2n+1$ integer points on a Cartesian plane. Points are numbered from $0$ to $2n$ inclusive. Let $P_i$ be the $i$-th point. The $x$-coordinate of the point $P_i$ equals $i$. The $y$-coordinate of the point $P_i$ equals zero (initially). Thus, initially $P_i=(i,0)$.\n\nThe given points are vertices of a plot of a piecewise function. The $j$-th piece of the function is the segment $P_{j}P_{j + 1}$.\n\nIn one move you can increase the $y$-coordinate of any point with odd $x$-coordinate (i.e. such points are $P_1, P_3, \\dots, P_{2n-1}$) by $1$. Note that the corresponding segments also change.\n\nFor example, the following plot shows a function for $n=3$ (i.e. number of points is $2\\cdot3+1=7$) in which we increased the $y$-coordinate of the point $P_1$ three times and $y$-coordinate of the point $P_5$ one time:\n\nLet the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).\n\nLet the height of the plot be the maximum $y$-coordinate among all initial points in the plot (i.e. points $P_0, P_1, \\dots, P_{2n}$). The height of the plot on the picture above is 3.\n\nYour problem is to say which minimum possible height can have the plot consisting of $2n+1$ vertices and having an area equal to $k$. Note that it is unnecessary to minimize the number of moves.\n\nIt is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $10^{18}$.",
    "tutorial": "It is easy to see that the area of the plot is the sum of areas of all triangles in this plot. Each move increases area by one. We cannot obtain the answer less than $\\lceil\\frac{k}{n}\\rceil$ but we always can obtain such an answer.",
    "code": "n, k = map(int, input().split())\nprint((k + n - 1) // n)",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1036",
    "index": "B",
    "title": "Diagonal Walking v.2",
    "statement": "Mikhail walks on a Cartesian plane. He starts at the point $(0, 0)$, and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point $(0, 0)$, he can go to any of the following points in one move:\n\n- $(1, 0)$;\n- $(1, 1)$;\n- $(0, 1)$;\n- $(-1, 1)$;\n- $(-1, 0)$;\n- $(-1, -1)$;\n- $(0, -1)$;\n- $(1, -1)$.\n\nIf Mikhail goes from the point $(x1, y1)$ to the point $(x2, y2)$ in one move, and $x1 \\ne x2$ and $y1 \\ne y2$, then such a move is called a diagonal move.\n\nMikhail has $q$ \\textbf{queries}. For the $i$-th query Mikhail's target is to go to the point $(n_i, m_i)$ from the point $(0, 0)$ in \\textbf{exactly} $k_i$ moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point $(0, 0)$ to the point $(n_i, m_i)$ in $k_i$ moves.\n\nNote that Mikhail \\textbf{can} visit any point any number of times (even the destination point!).",
    "tutorial": "There are several cases in this problem. If $n < m$ then let's swap them. Let $\\%$ be the modulo operator. Firstly, if $n \\% 2 \\ne m \\% 2$ then let's decrease $k$ and $n$ by one. Otherwise if $n \\% 2 \\ne k \\% 2$ let's decrease $n$, $m$ by one and $k$ by two. Now if $k < n$ then the answer is -1, otherwise the answer is $k$. You can get more clear description of these cases if you will draw some cases on the paper.",
    "code": "q = int(input())\n\nfor i in range(q):\n    n, m, k = map(int, input().split())\n    if (n < m): n, m = m, n\n    if (n % 2 != m % 2):\n        k -= 1\n        n -= 1\n    elif (n % 2 != k % 2):\n        k -= 2\n        n -= 1\n        m -= 1\n    print(-1 if k < n else k)",
    "tags": [
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1036",
    "index": "C",
    "title": "Classy Numbers",
    "statement": "Let's call some positive integer classy if its decimal representation contains no more than $3$ non-zero digits. For example, numbers $4$, $200000$, $10203$ are classy and numbers $4231$, $102306$, $7277420000$ are not.\n\nYou are given a segment $[L; R]$. Count the number of classy integers $x$ such that $L \\le x \\le R$.\n\nEach testcase contains several segments, for each of them you are required to solve the problem separately.",
    "tutorial": "There are quite a few approaches to the problem. I'll describe the two of them which I actually implemented. First approach - combinatoric one: Problems of the form \"count the number of beautiful numbers from $L$ to $R$\" usually require counting the numbers on $[1; R]$ and $[1; L - 1]$ (or not inclusively $[1; R + 1)$ and $[1; L)$) and subtracting one from another. Let's try this thing here, counting $calc(R + 1) - calc(L)$ not inclusively. Let's fix some prefix of the upper border number. We want to calculate the amount of numbers having the same prefix but being smaller in the next digit. If we count it for all prefixes (including the empty one), we will get the answer. And that is pretty easy. Let the prefix include $k$ non-zero digits, the length of the suffix be $x$ and the digit after the chosen prefix is $d$. If $d$ is zero then there the result is obviously zero. Otherwise we can either put $0$ or any of the $(d - 1)$ non-zero digits. Then the formula is: $\\sum \\limits_{i = 0}^{3 - k} \\binom{x - 1}{i} \\cdot 9^i$ + $(d - 1) \\cdot \\sum \\limits_{i = 0}^{3 - k - 1} \\binom{x - 1}{i} \\cdot 9^i$. We choose $i$ positions from the suffix to put non-zero digits in them (any digit from $1$ to $9$) and fill the rest with zeros. Overall complexity: $O(T \\cdot \\log n)$. Second approach - precalc one: This is a bit easier to implement. Actually, there are just about 700000 valid numbers, you can generate them all, put them into the array in sorted order and binary search for the given queries. Overall complexity: $O(T \\cdot \\log ANSCNT)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nvector<long long> res;\n\nvoid brute(int pos, int cnt, long long cur){\n    if (pos == 18){\n        res.push_back(cur);\n        return;\n    }\n    \n    brute(pos + 1, cnt, cur * 10);\n    \n    if (cnt < 3)\n        for (int i = 1; i <= 9; ++i)\n            brute(pos + 1, cnt + 1, cur * 10 + i);\n}\n\nint main() {\n    brute(0, 0, 0);\n    res.push_back(1000000000000000000);\n    \n    int T;\n    scanf(\"%d\", &T);\n    forn(i, T){\n        long long L, R;\n        scanf(\"%lld%lld\", &L, &R);\n        printf(\"%d\\n\", int(upper_bound(res.begin(), res.end(), R) - lower_bound(res.begin(), res.end(), L)));\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1036",
    "index": "D",
    "title": "Vasya and Arrays",
    "statement": "Vasya has two arrays $A$ and $B$ of lengths $n$ and $m$, respectively.\n\nHe can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $[1, 10, 100, 1000, 10000]$ Vasya can obtain array $[1, 1110, 10000]$, and from array $[1, 2, 3]$ Vasya can obtain array $[6]$.\n\nTwo arrays $A$ and $B$ are considered equal if and only if they have the same length and for each valid $i$ $A_i = B_i$.\n\nVasya wants to perform some of these operations on array $A$, some on array $B$, in such a way that arrays $A$ and $B$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.\n\nHelp Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $A$ and $B$ equal.",
    "tutorial": "Let's prove that next greedy solution works: each step we will find prefixes of minimal length of arrays $A$ and $B$ such that its sums are equal and we will cut them forming next block. If we will get valid partition in result so it is an optimal solution, otherwise there is no solution. Since length of prefix proportional to its sum, so prefixes are minimal since its sums are minimal. Let's prove this algorithm: let optimal solution have alternative partition. Since our solution cuts minimal possible prefixes, so (at some step) optimal solution cuts prefix with greater sum (and greater length). But this prefixes in optimal solutions contain smaller prefixes, found by greedy solution, so it can be divided on two parts - contradiction. So we can keep prefixes and increase one which have smaller sum. Result complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300 * 1000 + 9;\n\nint n, m;\nint a[N], b[N];\n\nint main() {\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; ++i) scanf(\"%d\", a + i);\n    scanf(\"%d\", &m);\n    for(int i = 0; i < m; ++i) scanf(\"%d\", b + i);\n    \n    long long sum = 0;\n    for(int i = 0; i < n; ++i) sum += a[i];\n    for(int i = 0; i < m; ++i) sum -= b[i];\n    if(sum != 0){\n        puts(\"-1\");\n        return 0;\n    }\n    \n    int posa = 0, posb = 0;\n    int res = 0;\n    while(posa < n){\n        ++res;\n        long long suma = a[posa++], sumb = b[posb++];\n                \n        while(suma != sumb){\n            if(suma < sumb) suma += a[posa++];\n            else sumb += b[posb++];\n        }\n    }\n    \n    printf(\"%d\\n\", res);\n    return 0;\n}",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1036",
    "index": "E",
    "title": "Covered Points",
    "statement": "You are given $n$ segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line.\n\nCount the number of distinct points with \\textbf{integer coordinates}, which are covered by at least one segment.",
    "tutorial": "I won't tell all the small geometric details, just cover some major points. The problem asks you the following thing. Sum up the total number of points covered by each segment and for each unique point subtract the number of segments covering it minus one. Let's reformulate it. For each segment add the number of points covered by it and subtract the number of points covered by it and by some already processed segment. The first part is easy. Segment covers exactly $GCD(|x1 - x2|, |y1 - y2|) + 1$ points with integer coordinates. The proof left to the reader as an exercise. The second part can be done in the following manner. Intersect the segment $i$ with all segments $j < i$, insert all the points of intersection into set and take its size. You can consider only integer points of intersection and use no floating-point numbers in your program. Overall complexity: $O(n^2 \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 1000 + 7;\n\nstruct seg{\n    int x1, y1, x2, y2;\n    seg(){};\n};\n\nstruct line{\n    long long A, B, C;\n    line(){};\n    line(seg a){\n        A = a.y1 - a.y2;\n        B = a.x2 - a.x1;\n        C = -A * a.x1 - B * a.y1;\n    };\n};\n\nint n;\nseg a[N];\n\nint get(seg a){\n    int dx = a.x1 - a.x2;\n    int dy = a.y1 - a.y2;\n    return __gcd(abs(dx), abs(dy)) + 1;\n}\n\nlong long det(long long a, long long b, long long c, long long d){\n    return a * d - b * c;\n}\n\nbool in(int x, int l, int r){\n    if (l > r) swap(l, r);\n    return (l <= x && x <= r);\n}\n\nbool inter(seg a, seg b, int& x, int& y){\n    line l1(a), l2(b);\n    long long dx = det(l1.C, l1.B, l2.C, l2.B);\n    long long dy = det(l1.A, l1.C, l2.A, l2.C);\n    long long d = det(l1.A, l1.B, l2.A, l2.B);\n    if (d == 0)\n        return false;\n    if (dx % d != 0 || dy % d != 0)\n        return false;\n    x = -dx / d;\n    y = -dy / d;\n    if (!in(x, a.x1, a.x2) || !in(y, a.y1, a.y2))\n        return false;\n    if (!in(x, b.x1, b.x2) || !in(y, b.y1, b.y2))\n        return false;\n    return true;\n}\n\nint main() {\n    scanf(\"%d\", &n);\n    forn(i, n)\n        scanf(\"%d%d%d%d\", &a[i].x1, &a[i].y1, &a[i].x2, &a[i].y2);\n    \n    int ans = 0;\n    int x, y;\n    forn(i, n){\n        ans += get(a[i]);\n        set<pair<int, int>> pts;\n        forn(j, i)\n            if (inter(a[i], a[j], x, y))\n                pts.insert({x, y});\n        ans -= pts.size();\n    }\n    \n    printf(\"%d\\n\", ans);\n    return 0;\n}",
    "tags": [
      "fft",
      "geometry",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1036",
    "index": "F",
    "title": "Relatively Prime Powers",
    "statement": "Consider some positive integer $x$. Its prime factorization will be of form $x = 2^{k_1} \\cdot 3^{k_2} \\cdot 5^{k_3} \\cdot \\dots$\n\nLet's call $x$ elegant if the greatest common divisor of the sequence $k_1, k_2, \\dots$ is equal to $1$. For example, numbers $5 = 5^1$, $12 = 2^2 \\cdot 3$, $72 = 2^3 \\cdot 3^2$ are elegant and numbers $8 = 2^3$ ($GCD = 3$), $2500 = 2^2 \\cdot 5^4$ ($GCD = 2$) are not.\n\nCount the number of elegant integers from $2$ to $n$.\n\nEach testcase contains several values of $n$, for each of them you are required to solve the problem separately.",
    "tutorial": "Whoops, it seems, this problem can be done in a similar manner as in problem $C$. Firstly, is some number $x$ has $GCD$ of the prime powers not equal to $1$, then you can take root $GCD$'th power from it. That is the same as dividing all powers by $GCD$. Now it turned out, there are really a small amount of these numbers up to $10^{18}$ (if you take the squares out). Actually, our solution wasn't that. Let's count the answer using inclusion-exclusion principle. For this Mobius function can be used. The answer is: $\\sum \\limits_{i = 1}^{\\infty} (\\lfloor n^{\\frac 1 i} \\rfloor - 1) \\cdot \\mu_i$. The power part is the amount of numbers, which raised to the $i$-th power becomes less ot equal to $n$. This turns zero for like $60$ iterations on $i$ for any $n$ up to $10^{18}$. However, calculating each log as it is will lead to a $O(T \\cdot \\log^2 n)$ solution, which might be too slow. Let's process the queries in the decreasing order of $n$. $\\sqrt n$ will be calculated naively each time (in $O(1)$ (or however complexity has the built-in function, $O(\\log \\log n)$ maybe) or $O(\\log n)$). The rest powers will be initialized with their upper limits in the start (like $10^6$ for $3$, $10^3$ for $6$ and so on). Now proceeding to the next number will only decrease the current maximum number for each power. Subtract one until you reach the needed number and check in $\\log n$. Overall complexity: $O(T \\cdot (\\log n + \\log T))$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int K = 100;\nconst int N = 100 * 1000 + 13;\nconst long long INF64 = 3e18;\n\nint mu[K];\n\nvoid precalc(){\n    static bool prime[K];\n    static int lst[K];\n    \n    memset(prime, false, sizeof(prime));\n    forn(i, K) lst[i] = i;\n    \n    for (int i = 2; i < K; ++i){\n        if (lst[i] == i) mu[i] = 1;\n        for (int j = 2 * i; j < K; j += i){\n            lst[j] = min(lst[j], lst[i]);\n            if (lst[j] == lst[i])\n                mu[j] = 0;\n            else\n                mu[j] = -mu[i];\n        }\n    }\n}\n\nint mx[K];\n\nlong long binpow(long long a, int b){\n    long long res = 1;\n    while (b){\n        if (b & 1){\n            if (res < INF64 / a) res *= a;\n            else return INF64;\n        }\n        if (b > 1){\n            if (a < INF64 / a) a *= a;\n            else return INF64;\n        }\n        b >>= 1;\n    }\n    return res;\n}\n\nlong long calc(long long n){\n    int pw = 63 - __builtin_clzll(n);\n    for (int i = 3; i <= pw; ++i){\n        if (mu[i] == 0) continue;\n        while (binpow(mx[i], i) > n)\n            --mx[i];\n    }\n    \n    long long res = n - 1;\n    for (int i = 2; i <= pw; ++i)\n        res -= mu[i] * (mx[i] - 1);\n    \n    return res;\n}\n\nint get_sqrt(long long n){\n    int l = 1, r = 1000000000;\n    while (l < r - 1){\n        int m = (l + r) / 2;\n        if (m * 1ll * m <= n)\n            l = m;\n        else\n            r = m;\n    }\n    return (r * 1ll * r <= n ? r : l);\n}\n\nlong long ans[N];\n\nint main() {\n    precalc();\n    int T;\n    scanf(\"%d\", &T);\n    vector<pair<long long, int>> q;\n    \n    forn(i, T){\n        long long n;\n        scanf(\"%lld\", &n);\n        q.push_back({n, i});\n    }\n    \n    sort(q.begin(), q.end(), greater<pair<long long, int>>());\n    mx[3] = 1000000;\n    mx[4] = 31622;\n    mx[5] = 3981;\n    for (int i = 6; i < K; ++i)\n        mx[i] = 1000;\n    \n    forn(z, T){\n        long long n = q[z].first;\n        mx[2] = get_sqrt(n);\n        ans[q[z].second] = calc(n);\n    }\n    \n    forn(i, T)\n        printf(\"%lld\\n\", ans[i]);\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1036",
    "index": "G",
    "title": "Sources and Sinks",
    "statement": "You are given an acyclic directed graph, consisting of $n$ vertices and $m$ edges. The graph contains no multiple edges and no self-loops.\n\nThe vertex is called a source if it has no incoming edges. The vertex is called a sink if it has no outgoing edges. These definitions imply that some vertices can be both source and sink.\n\nThe number of sources in the given graph is equal to the number of sinks in it, and each of these numbers doesn't exceed $20$.\n\nThe following algorithm is applied to the graph:\n\n- if the graph has no sources and sinks then quit;\n- choose arbitrary source $s$, arbitrary sink $t$, add an edge from $t$ to $s$ to the graph and go to step $1$ (that operation pops $s$ out of sources and $t$ out of sinks). Note that $s$ and $t$ may be the same vertex, then a self-loop is added.\n\nAt the end you check if the graph becomes strongly connected (that is, any vertex is reachable from any other vertex).\n\nYour task is to check that the graph becomes strongly connected no matter the choice of sources and sinks on the second step of the algorithm.",
    "tutorial": "Since the graph is acyclic, then for every vertex there exists a path to some sink, and to every vertex there exists a path from some source. So our problem can be reduced to the following: check that after running our algorithm, all vertices from the initial set of sources and sinks belong to the same strongly connected component. Let $C$ be the number of sources (or sinks) in the initial graph. First of all, let's run DFS (or any other graph traversal) from every source to form a set of reachable sinks for every source. This part of solution has complexity of $O(C(n + m))$. If $X$ is some set of sources of the original graph, let $f(X)$ be the set of sinks such that every sink from $f(X)$ is reachable from at least one source from $X$. It's easy to see that there exists some set $X$ such that $|X| \\ne 0$, $|X| \\ne C$ and $|X| \\ge |f(X)|$, then the answer is NO - if we connected the sinks from $f(X)$ with the sources from $X$, then any sink not belonging to $f(X)$ would be unreachable from any sink belonging to $f(X)$. Checking every possible set $X$ can be done in $O(C^2 2^C)$ or in $O(C 2^C)$. Let's prove that there is no such set $X$, then the answer is YES. Let $s$ be an arbitrary sink of the original graph. Also, if $S$ is some set of sinks, let $h(S)$ be the set of sources containing every source directly connected to some sink from $S$. We can use mathematical induction to prove that every source and every sink is reachable from $s$ in the resulting graph: Initially we state that $s$ is reachable from $s$ (quite obvious); If there is a set of sinks $S$ reachable from $s$, then either $|S| = C$ (and the whole graph is reachable from $s$), or the number of sinks reachable from $h(S)$ is at least $|S| + 1$, so some set of $|S| + 1$ sinks is reachable from $s$. So in fact checking every possible subset of sources is enough.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000043;\n\nvector<int> g[N];\nvector<int> gt[N];\nvector<int> src;\nvector<int> snk;\nint reach[20];\nint used[N];\n\nvoid dfs(int x)\n{\n    if(used[x]) return;\n    used[x] = 1;\n    for(auto y : g[x]) dfs(y);\n}\n\nint main()\n{\n    int n, m;\n    scanf(\"%d %d\", &n, &m);\n    for(int i = 0; i < m; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        --x;\n        --y;\n        g[x].push_back(y);\n        gt[y].push_back(x);\n    }\n    for(int i = 0; i < n; i++)\n    {\n        if(g[i].empty())\n            snk.push_back(i);\n        if(gt[i].empty())\n            src.push_back(i);\n    }\n    int cnt = src.size();\n    for(int i = 0; i < cnt; i++)\n    {\n        memset(used, 0, sizeof used);\n        dfs(src[i]);\n        for(int j = 0; j < cnt; j++)\n            if(used[snk[j]])\n                reach[i] ^= (1 << j);\n    }\n    bool ok = true;\n    for(int mask = 0; mask < (1 << cnt); mask++)\n    {\n        int res = 0;\n        for(int j = 0; j < cnt; j++)\n            if(mask & (1 << j))\n                res |= reach[j];\n        int cnt1 = __builtin_popcount(mask);\n        int cnt2 = __builtin_popcount(res);\n        if(cnt2 < cnt1 || (cnt2 == cnt1 && cnt1 != 0 && cnt1 != cnt))\n            ok = false;\n    }\n    if(!ok)\n        puts(\"NO\");\n    else\n        puts(\"YES\");\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1037",
    "index": "A",
    "title": "Packets",
    "statement": "You have $n$ coins, each of the same value of $1$.\n\nDistribute them into packets such that any amount $x$ ($1 \\leq x \\leq n$) can be formed using some (possibly one or all) number of these packets.\n\nEach packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single $x$, however it may be reused for the formation of other $x$'s.\n\nFind the minimum number of packets in such a distribution.",
    "tutorial": "The best possible way to distribute the coins is to create packets with coins $1, 2, 4, \\ldots 2^k$ with maximum possible $k$ such that $2\\cdot 2^k-1 \\le n$. Using them, we can make all possible numbers which can be written using first $k+1$ bits in binary representation. For representing the remaining numbers, we must include $n-2\\cdot 2^k+1$ remaining coins in one packets. Complexity: $O(LogN)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n    int n;\n    cin>>n;\n    int k=1,z=0;\n    while(true)\n    {\n        if(n>0) z++;\n        else break;\n        n-=k;\n        k*=2;\n    }\n    cout<<z;\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1037",
    "index": "B",
    "title": "Reach Median",
    "statement": "You are given an array $a$ of $n$ integers and an integer $s$. It is guaranteed that $n$ is odd.\n\nIn one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $s$.\n\nThe median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $6, 5, 8$ is equal to $6$, since if we sort this array we will get $5, 6, 8$, and $6$ is located on the middle position.",
    "tutorial": "For changing the median of the array, sort the given array and then the best possible candidate for making median is the middle element, because it will be better to reduce the numbers before the middle element as they are smaller and increase the numbers after the middle element as they are larger. Complexity: $O(NLogN)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n    int n,S;\n    cin>>n>>S;\n    vector<int> a(n);\n    for(int i=0;i<n;i++) cin>>a[i];\n    long long z=LLONG_MAX;\n    sort(a.begin(),a.end());\n    long long fh=0,sh=0;\n    for(int i=0;i<n/2;i++)\n    {\n    \tif(a[i]>S) fh+=a[i]-S;\n    \tif(a[n-1-i]<S) sh+=S-a[n-1-i];\n    }\n    cout<<fh+sh+abs(a[n/2]-S);\n    return 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1037",
    "index": "C",
    "title": "Equalize",
    "statement": "You are given two binary strings $a$ and $b$ of the same length. You can perform the following two operations on the string $a$:\n\n- Swap any two bits at indices $i$ and $j$ respectively ($1 \\le i, j \\le n$), the cost of this operation is $|i - j|$, that is, the absolute difference between $i$ and $j$.\n- Select any arbitrary index $i$ ($1 \\le i \\le n$) and flip (change $0$ to $1$ or $1$ to $0$) the bit at this index. The cost of this operation is $1$.\n\nFind the minimum cost to make the string $a$ equal to $b$. It is not allowed to modify string $b$.",
    "tutorial": "This can be seen that to minimize the cost, we should use the swap operation only when there are two consecutive positions(and with opposite values) to fix. For all other positions to fix, we can use the flip operation. Complexity: $O(N)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\ntypedef pair<ll,int> pli;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<pii> vpii;\ntypedef vector<pll> vpll;\n#define F first\n#define S second\ntypedef vector<pli> vpli;\n#define hell 1000000007\n#define mp make_pair\n#define pb push_back\n#define all(v) v.begin(),v.end() \n#define tests int t; cin>>t; while(t--)\n#define take(a,b,c) for(b=0;b<c;b++) scanf(\"%d\",&a[b]);\n \nint main(){\n\tios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);\n\tint n;\n\tcin>>n;\n\tstring s,t;\n\tcin>>s>>t;\n\tint i=0;\n\tint ans=0;\n\twhile(i<n)\n\tif(s[i]!=t[i])\n\t{\n\t\tif(i+1<n&&s[i+1]!=t[i+1]&&s[i]!=s[i+1])\n\t\t{\n\t\t\tans++;\n\t\t\ti+=2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tans++;\n\t\t\ti++;\n\t\t}\n\t}\n\telse\n\ti++;\n\tcout<<ans<<endl;\n\treturn 0;\n\t\n}",
    "tags": [
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1037",
    "index": "D",
    "title": "Valid BFS?",
    "statement": "The BFS algorithm is defined as follows.\n\n- Consider an undirected graph with vertices numbered from $1$ to $n$. Initialize $q$ as a new queue containing only vertex $1$, mark the vertex $1$ as used.\n- Extract a vertex $v$ from the head of the queue $q$.\n- Print the index of vertex $v$.\n- Iterate in arbitrary order through all such vertices $u$ that $u$ is a neighbor of $v$ and is not marked yet as used. Mark the vertex $u$ as used and insert it into the tail of the queue $q$.\n- If the queue is not empty, continue from step 2.\n- Otherwise finish.\n\nSince the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.\n\nIn this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree \\textbf{starting from vertex $1$}. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.",
    "tutorial": "We can store the neighbors of the nodes in their adjacency lists. After that, we can sort the adjacency lists of all the nodes in the order in which they are present in the input BFS Sequence. Now we can do the standard BFS traversal starting from node $1$ and check if this BFS traversal is same as the input BFS Sequence. If its not, the answer will be \"No\". Complexity: $O(NLogN)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\ntypedef pair<ll,int> pli;\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\ntypedef vector<pii> vpii;\ntypedef vector<pll> vpll;\n#define F first\n#define S second\ntypedef vector<pli> vpli;\n#define hell 1000000007\n#define mp make_pair\n#define pb push_back\n#define all(v) v.begin(),v.end() \n#define tests int t; cin>>t; while(t--)\n#define take(a,b,c) for(b=0;b<c;b++) cin>>a[b];\ntypedef long long ll;\nvector<int> ans,adj[200007];\nbool vis[200007];\nint inputorder[200007],relorder[200007];\t\nbool cmp(int a,int b){\n\treturn relorder[a]<relorder[b];\n}\nint main()\n{\t\n    ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);\n    int n,x,a,b,i,j;\n\tcin>>n;\n\tfor(i=0;i<n-1;i++){\t\n\t\tcin>>a>>b;\n\t\tadj[a].pb(b);\n\t\tadj[b].pb(a);\n\t}\n\tfor(i=0;i<n;i++){\n\t\tcin>>inputorder[i];\n\t\trelorder[inputorder[i]]=i;\n\t}\t\n\tfor(i=1;i<=n;i++)\n\t\tsort(all(adj[i]),cmp);\n\tqueue<int> q;\t\t\n\tq.push(1);\t\n\tmemset(vis,false,sizeof(vis));\n\twhile(!(q.empty())){\n\t\tqueue<int> temp;\n\t\twhile(!(q.empty())){\n\t\t\tint x= q.front();\n\t\t\tq.pop();\n\t\t\tans.pb(x);\n\t\t\tvis[x]=true;\n\t\t\tfor(j=0;j<adj[x].size();j++)\n\t\t\t\tif(vis[adj[x][j]]==false)\n\t\t\t\t\ttemp.push(adj[x][j]);\n\t\t\t}\n\t\tq=temp;\t\t\t\n\t}\n\tfor(i=0;i<n;i++)\n\t\tif(inputorder[i]!=ans[i]){\n\t\t\tcout<<\"No\"; return 0;}\n\tcout<<\"Yes\";\t\t\n\t\t\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1037",
    "index": "E",
    "title": "Trips",
    "statement": "There are $n$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.\n\nWe want to plan a trip for every evening of $m$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold:\n\n- Either this person does not go on the trip,\n- Or at least $k$ of his friends also go on the trip.\n\nNote that the friendship is not transitive. That is, if $a$ and $b$ are friends and $b$ and $c$ are friends, it does not necessarily imply that $a$ and $c$ are friends.\n\nFor each day, find the maximum number of people that can go on the trip on that day.",
    "tutorial": "Scan the list of all the edges and create a set S of pair<int,int> (degree of node, id of node), now keep deleting elements from set till degree of smallest element of S is less than k, while deleting a node u, update the set S using adjacency list of u i.e. all elements v which are in S and adj(u) 1. delete (degree[v],v) 2. degree[v] = degree[v] - 1 3. insert(degree[v],v) Now iterate the edges scanned in reverse order and subtract the degree of nodes by 1 and update S as described above if both nodes of edge are in S. Take the size of S after each step as solution. Complexity: $O(NLogN)$",
    "code": "/*\n[ C O D E    T I L L    I N F I N I T Y ]\n*/\n#include <set>          \n#include <map>           \n#include <list>\n#include <ctime>\n#include <deque>   \n#include <queue>      \n#include <bitset>        \n#include <vector>\n#include <list>\n#include <stack>\n#include <random>\t\t \n#include <string>       \n#include <numeric>      \n#include <utility>     \n#include <iterator> \n#include <fstream>\n#include <iostream> \n#include <iomanip>  \n#include <algorithm> \n#include <functional>  \n#include <unordered_map>  \n#include <unordered_set>\n#include <cmath>   \n#include <cstring>  \n#include <cstdio>    \n#if !defined Header_DR\n#define Header_DR\n#pragma warning(disable:4996)\n#define intt long long\n#define cin user_input\n#define cout output\n#define pi 3.14159265358979323846\n#define code_jam 0\n#define code_chef 0\n#define rep(i,a,b) for(long long i=a;i<b;i++)\n#define all(v) v.begin(),v.end() \n#define ve vector\n#define pb push_back                    \n#define srt(x) sort(x.begin(),x.end())         \n#define mod static_cast<long long> (998244353)     \n#define sumx(x) accumulate(x.begin(),x.end(),0LL)\n#define endl \"\\n\"\n#endif\n#ifdef _WIN32\n#define getcx _getchar_nolock\n#endif\n#ifdef __unix__\n#define getcx getchar_unlocked\n#endif\n#ifdef __APPLE__\n#define getcx getchar_unlocked\n#endif\n#if!defined FAST_IO\n#undef cin\n#undef cout\n#define FAST_IO ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);\n#define cin user_input\n#define cout output\n#endif\nusing namespace std;\nnamespace Xrocks {}\nusing namespace Xrocks;\nnamespace Xrocks\n{\n\tclass in {}user_input;\n\tclass out {}output;\n\tin& operator >> (in& X, int &Y)\n\t{\n\t\tscanf(\"%d\", &Y);\n\t\treturn X;\n\t}\n\tin& operator >> (in& X, char *Y)\n\t{\n\t\tscanf(\"%s\", Y);\n\t\treturn X;\n\t}\n\tin& operator >> (in& X, float &Y)\n\t{\n\t\tscanf(\"%f\", &Y);\n\t\treturn X;\n\t}\n\tin& operator >> (in& X, double &Y)\n\t{\n\t\tscanf(\"%lf\", &Y);\n\t\treturn X;\n\t}\n\tin& operator >> (in& X, char &C)\n\t{\n\t\tscanf(\"%c\", &C);\n\t\treturn X;\n\t}\n\tin& operator >> (in& X, string &Y)\n\t{\n#undef cin\n\t\tcin >> Y;\n#define cin user_input\n\t\treturn X;\n\t}\n\tin& operator >> (in& X, long long &Y)\n\t{\n\t\tscanf(\"%lld\", &Y);\n\t\treturn X;\n\t}\n\ttemplate<typename T>\n\tin& operator >> (in& X, vector<T> &Y)\n\t{\n\t\tfor (auto &x : Y)\n\t\t\tcin >> x;\n\t\treturn X;\n\t}\n \n\ttemplate<typename T>\n\tout& operator << (out& X, const  T &Y)\n\t{\n#undef cout\n\t\tcout << Y;\n#define cout output\n\t\treturn X;\n\t}\n\ttemplate<typename T>\n\tout& operator << (out& X, vector<T> &Y)\n\t{\n\t\tfor (auto &x : Y)\n\t\t\tcout << x << \" \";\n\t\treturn X;\n\t}\n\tout& operator <<(out& X, const int &Y)\n\t{\n\t\tprintf(\"%d\", Y);\n\t\treturn X;\n\t}\n\tout& operator <<(out& X, const char &C)\n\t{\n\t\tprintf(\"%c\", C);\n\t\treturn X;\n\t}\n\tout& operator <<(out& X, const string &Y)\n\t{\n\t\tprintf(\"%s\", Y.c_str());\n\t\treturn X;\n\t}\n\tout& operator <<(out& X, const long long &Y)\n\t{\n\t\tprintf(\"%lld\", Y);\n\t\treturn X;\n\t}\n\tout& operator <<(out& X, const float &Y)\n\t{\n\t\tprintf(\"%f\", Y);\n\t\treturn X;\n\t}\n\tout& operator <<(out& X, const double &Y)\n\t{\n\t\tprintf(\"%lf\", Y);\n\t\treturn X;\n\t}\n\tout& operator <<(out& X, const char Y[])\n\t{\n\t\tprintf(\"%s\", Y);\n\t\treturn X;\n\t}\n\ttemplate<typename T>\n\tT max(T A)\n\t{\n\t\treturn A;\n\t}\n\ttemplate<typename T, typename... args>\n\tT max(T A, T B, args... S)\n\t{\n\t\treturn max(A > B ? A : B, S...);\n\t}\n\ttemplate<typename T>\n\tT min(T A)\n\t{\n\t\treturn A;\n\t}\n\ttemplate<typename T, typename... args>\n\tT min(T A, T B, args... S)\n\t{\n\t\treturn min(A < B ? A : B, S...);\n\t}\n\ttemplate<typename T>\n\tvoid vectorize(int y, ve<T> &A)\n\t{\n\t\tA.resize(y);\n\t}\n\ttemplate<typename T, typename... args>\n\tvoid vectorize(int y, ve<T> &A, args&&... S)\n\t{\n\t\tA.resize(y);\n\t\tvectorize(y, S...);\n\t}\n\tlong long fast(long long a, long long b, long long pr)\n\t{\n\t\tif (b == 0)\n\t\t\treturn 1 % pr;\n\t\tlong long ans = 1 % pr;\n\t\twhile (b)\n\t\t{\n\t\t\tif (b & 1)\n\t\t\t\tans = (ans * a) % pr;\n\t\t\tb >>= 1;\n\t\t\ta = (a * a) % pr;\n\t\t}\n\t\treturn ans;\n\t}\n\tint readInt()\n\t{\n\t\tint n = 0;\n\t\t//\tscanf(\"%d\", &n);\n\t\t//\treturn n;\n\t\tint ch = getcx();\n\t\tint sign = 1;\n\t\twhile (ch < '0' || ch > '9') { if (ch == '-')sign = -1; ch = getcx(); }\n \n\t\twhile (ch >= '0' && ch <= '9')\n\t\t\tn = (n << 3) + (n << 1) + ch - '0', ch = getcx();\n\t\tn = n * sign;\n\t\treturn n;\n\t}\n\tlong long readLong()\n\t{\n\t\tlong long n = 0;\n\t\t//scanf(\"%lld\",&n);\n\t\t//return n;\n\t\tint ch = getcx(); int sign = 1;\n\t\twhile (ch < '0' || ch > '9') { if (ch == '-')sign = -1; ch = getcx(); }\n \n\t\twhile (ch >= '0' && ch <= '9')\n\t\t\tn = (n << 3) + (n << 1) + ch - '0', ch = getcx();\n\t\tn = n * sign;\n\t\treturn n;\n\t}\n\tlong long readBin()\n\t{\n\t\tlong long n = 0;\n\t\t//scanf(\"%lld\",&n);\n\t\t//return n;\n\t\tint ch = getcx(); int sign = 1;\n\t\twhile (ch < '0' || ch > '1') { if (ch == '-')sign = -1; ch = getcx(); }\n \n\t\twhile (ch >= '0' && ch <= '1')\n\t\t\tn = (n << 1) + (ch - '0'), ch = getcx();\n\t\treturn n;\n\t}\n\tlong long inv_(long long val, long long pr = mod)\n\t{\n\t\treturn fast(val, pr - 2, pr);\n\t}\n}\nclass solve\n{\n \npublic:\n\tsolve()\n\t{\n\t\tint n, m, k;\n\t\tcin >> n >> m >> k;\n\t\tve<pair<int, int> > Edges(m);\n\t\tve<int> Ans(m);\n\t\tve<int> degree(n);\n\t\tve<ve<pair<int, int> > > adj(n);\n\t\tset<pair<int, int> > Good_set;\n\t\tve<int> in_good_set(n, true);\n\t\tfor (int i = 0; i<m; i++)\n\t\t{\n\t\t\tcin >> Edges[i].first >> Edges[i].second;\n\t\t\tEdges[i].first--;\n\t\t\tEdges[i].second--;\n\t\t\tadj[Edges[i].first].pb({ Edges[i].second,i });\n\t\t\tadj[Edges[i].second].pb({ Edges[i].first,i });\n\t\t\tdegree[Edges[i].first]++;\n\t\t\tdegree[Edges[i].second]++;\n\t\t}\n\t\tfor (int i = 0; i<n; i++)\n\t\t{\n\t\t\tGood_set.insert({ degree[i],i });\n\t\t}\n\t\twhile (!Good_set.empty() && Good_set.begin()->first<k)\n\t\t{\n\t\t\tint node = Good_set.begin()->second;\n\t\t\tfor (auto &y : adj[node])\n\t\t\t{\n\t\t\t\tint x = y.first;\n\t\t\t\tif (in_good_set[x])\n\t\t\t\t{\n\t\t\t\t\tGood_set.erase({ degree[x],x });\n\t\t\t\t\t--degree[x];\n\t\t\t\t\tGood_set.insert({ degree[x],x });\n\t\t\t\t}\n\t\t\t}\n\t\t\tGood_set.erase({degree[node],node});\n\t\t\tin_good_set[node] = false;\n\t\t}\n \n\t\tfor (int i = m - 1; i >= 0; i--)\n\t\t{\n\t\t\tAns[i] = Good_set.size();\n \n\t\t\tint u = Edges[i].first, v = Edges[i].second;\n\t\t\tif (in_good_set[u] && in_good_set[v])\n\t\t\t{\n\t\t\t\tGood_set.erase({ degree[u],u });\n\t\t\t\t--degree[u];\n\t\t\t\tGood_set.insert({ degree[u],u });\n \n\t\t\t\tGood_set.erase({ degree[v],v });\n\t\t\t\t--degree[v];\n\t\t\t\tGood_set.insert({ degree[v],v });\n \n\t\t\t\twhile (!Good_set.empty() && Good_set.begin()->first<k)\n\t\t\t\t{\n\t\t\t\t\tint node = Good_set.begin()->second;\n\t\t\t\t\tfor (auto &y : adj[node])\n\t\t\t\t\t{\n\t\t\t\t\t\tint x = y.first;\n\t\t\t\t\t\tif (y.second >= i)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (in_good_set[x])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tGood_set.erase({ degree[x],x });\n\t\t\t\t\t\t\t--degree[x];\n\t\t\t\t\t\t\tGood_set.insert({ degree[x],x });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tGood_set.erase({degree[node],node});\n\t\t\t\t\tin_good_set[node] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i<m; i++)\n\t\t{\n\t\t\tcout << Ans[i] << \"\\n\";\n\t\t}\n\t}\n};\n \nint32_t main()\n{\n\tint t = 1, i = 1;\n\t//freopen(\"C:\\\\Users\\\\Xenor\\\\Downloads\\\\B.in\",\"r\",stdin);\n\t//freopen(\"C:\\\\Users\\\\Xenor\\\\Downloads\\\\gb2.txt\",\"w\",stdout);\n\tif (code_chef || code_jam)\n\t\tscanf(\"%d\", &t);\n\twhile (t--)\n\t{\n\t\tif (code_jam)\n\t\t\tprintf(\"Case #%d: \", i++);\n\t\tnew solve;\n\t}\n#ifdef __unix__\n\tcout << \"\\n\";\n#endif\n\treturn 0;\n}",
    "tags": [
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1037",
    "index": "F",
    "title": "Maximum Reduction",
    "statement": "Given an array $a$ of $n$ integers and an integer $k$ ($2 \\le k \\le n$), where each element of the array is denoted by $a_i$ ($0 \\le i < n$). Perform the operation $z$ given below on $a$ and print the value of $z(a,k)$ modulo $10^{9}+7$.\n\n\\begin{verbatim}\nfunction z(array a, integer k):\nif length(a) < k:\nreturn 0\nelse:\nb = empty array\nans = 0\nfor i = 0 .. (length(a) - k):\ntemp = a[i]\nfor j = i .. (i + k - 1):\ntemp = max(temp, a[j])\nappend temp to the end of b\nans = ans + temp\nreturn ans + z(b, k)\n\\end{verbatim}",
    "tutorial": "For each element $a[i]$, find maximum $r$ such that $a[i]>a[j]$ for every $i \\leq j \\leq r$ and minimum $l$ such that $a[i]>a[j]$ for every $l \\leq j \\leq i$. Now, let us count the no. of times $a[i]$ contributes to our answer, which can be calculated as (the no. of subsegments of length $k$ which contain $i$)+(the no. of subsegments of length $2*k$ which contain $i$) + ... + (the no. of subsegments of length $k*[n/k]$ which contain $i$) where each subsegment should be between $[l,r]$. Let $x=i-l , y=r-i , x<y$ then above sum can be represented as $k+2k+3k+4k \\ldots nk (nk \\le x) + x + x + x \\ldots m$ times $(m=(x+y)/k-n) + x-k + x-2k + x-3k$ $\\ldots$ until 0 which equals $k*n*(n+1)/2 + m*x + n*x - k*h*(h+1)/2$ where $n=x/k$, $m=(x+y)/k-n$, $h=x/k$. The last part is mostly mathematical with some case work. Complexity: $O(N)$",
    "code": "#include <bits/stdc++.h>\n#define pb          push_back\n#define hell        1000000007\n#define endl        '\\n'\n#define rep(i,a,b)  for(int i=a;i<b;i++)\nusing namespace std;\nint n,k,A[1000005],l[1000005],r[1000005],ans;\nint mul(int x,int y){\n    return (1LL*x*y)%hell;\n}\nvoid solve(){\n    cin>>n>>k;\n    rep(i,0,n){\n        cin>>A[i];\n    }\n    stack<int> s;\n    s.push(0);\n    l[0]=0;\n    rep(i,1,n){     \n        while(!s.empty() && A[s.top()]<A[i]){\n            s.pop();\n        }\n        if(s.empty()) l[i]=0;\n        else l[i]=s.top()+1;\n        s.push(i);\n    }\n    while(!s.empty()) s.pop();\n    s.push(n-1);\n    r[n-1]=n-1;\n    for(int i=n-2;i>=0;--i){\n        while(!s.empty() && A[s.top()]<=A[i]){\n            s.pop();\n        }\n        if(s.empty()) r[i]=n-1;\n        else r[i]=s.top()-1;\n        s.push(i);\n    }\n    rep(i,0,n){\n        int t1=(min(i-l[i],r[i]-i)-k)/(k-1)+1;\n        if(min(i-l[i],r[i]-i)-k>=0){\n            int cur;\n            if(t1%2){\n                cur=mul(A[i],t1);\n                cur=mul(cur,(k+1LL*(t1-1)*(k-1)/2)%hell);\n            }\n            else{\n                cur=mul(A[i],t1/2);\n                cur=mul(cur,(2*k+1LL*(t1-1)*(k-1))%hell);                \n            }\n            ans=(ans+cur)%hell;\n        }\n        if(i-l[i]+1<=k){\n            int t2=(r[i]-i-k)/(k-1)+1;\n            if(r[i]-i-k>=0){\n                int cur=mul(A[i],t2);\n                ans=(ans+mul(cur,i-l[i]+1))%hell;\n            }\n        }\n        else{\n            int ft=k+((i-l[i]-1)/(k-1))*(k-1);\n            int t2=(r[i]-i-ft)/(k-1)+1;\n            if(r[i]-i-ft>=0){\n                int cur=mul(A[i],t2);\n                ans=(ans+mul(cur,i-l[i]+1))%hell;\n            }\n        }\n        if(r[i]-i+1<=k){\n            int t3=(i-l[i]-k)/(k-1)+1;\n            if(i-l[i]-k>=0){\n                int cur=mul(A[i],t3);\n                ans=(ans+mul(cur,r[i]-i+1))%hell;\n            }\n        }\n        else{\n            int ft=k+((r[i]-i-1)/(k-1))*(k-1);\n            int t3=(i-l[i]-ft)/(k-1)+1;\n            if(i-l[i]-ft>=0){\n                int cur=mul(A[i],t3);\n                ans=(ans+mul(cur,r[i]-i+1))%hell;\n            }\n        }\n        int d=max(i-l[i]+1,r[i]-i+1);\n        if(d<=k){\n            int t4=(r[i]-l[i]+1-k)/(k-1)+1;\n            if(r[i]-l[i]+1-k>=0){\n                int cur;\n                if(t4%2){\n                    cur=(mul(r[i]-l[i]+2,t4)-mul(t4,(k+1LL*(t4-1)*(k-1)/2)%hell)+hell)%hell;\n                }\n                else{\n                    cur=(mul(r[i]-l[i]+2,t4)-mul(t4/2,(2*k+1LL*(t4-1)*(k-1))%hell)+hell)%hell;\n                }\n                ans=(ans+mul(A[i],cur))%hell;\n            }\n        }\n        else{\n            int ft=k+((d-2)/(k-1))*(k-1);\n            int t4=(r[i]-l[i]+1-ft)/(k-1)+1;\n            if(r[i]-l[i]+1-ft>=0){\n                int cur;\n                if(t4%2){\n                    cur=(mul(r[i]-l[i]+2,t4)-mul(t4,(ft+1LL*(t4-1)*(k-1)/2)%hell)+hell)%hell;\n                }\n                else{\n                    cur=(mul(r[i]-l[i]+2,t4)-mul(t4/2,(2*ft+1LL*(t4-1)*(k-1))%hell)+hell)%hell;\n                }\n                ans=(ans+mul(A[i],cur))%hell;                \n            }\n        }\n    }\n    cout<<ans<<endl;\n}\n \nsigned main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int t=1;\n    // cin>>t;\n    while(t--)\n        solve();\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1037",
    "index": "G",
    "title": "A Game on Strings",
    "statement": "Alice and Bob are playing a game on strings.\n\nInitially, they have some string $t$. In one move the first player selects the character $c$ present in $t$ and erases all it's occurrences in $t$, thus splitting $t$ into many smaller strings. The game then goes independently with each of the strings — to make the move player selects one of the strings and one of the characters there, deletes all occurrences and adds the remaining string back to the game.\n\nAlice always starts the game, and then Alice and Bob take turns making moves. The player who is unable to make a move (because there is no string left) loses.\n\nAlice and Bob used to always start with a string $s$, but recently they found out that this became too boring. Now before each game they choose two integers $l$ and $r$ such that $1 \\le l \\le r \\le |s|$ and play the game with the string $s_{l} s_{l+1} s_{l+2} \\ldots s_{r}$ instead.\n\nGiven the string $s$ and integers $l$, $r$ for each game. Find who is going to win each game assuming they are smart and are playing optimally.",
    "tutorial": "Say, we have a string $s$. For each character, say $c$, $s$ has $c$ at $k$ positions $(a_1,a_2,...,a_k)$. Now, if we calculate grundy for strings $s[a_i+1:a_(i+1)-1]$ for $1 \\leq i < k$, and also for every prefix and suffix for such strings, we can calculate the result using grundy. For a query $[l,r]$, we can iterate on the character removed in first move, and the resultant grundy number can be calculated using range xor of the precomputed grundys. To precalculate grundys, we can compute grundy in sorted order of length and treat them as separate queries. Complexity: $O(26^{2} * N + 26 * Q)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\ntypedef long double ld;  \n \nconst int M = 1e5 + 239; \nconst int alf = 26;\n \nint n, q;\nstring s;\nint posr[alf][M], posl[alf][M], dpl[alf][M], dpr[alf][M], z[alf][M];\nint k, kols[alf], id[M];           \n \ninline int gett_slow(int l, int r)\n{\n    int mask = 0;\n\tfor (int x = 0; x < alf; x++)\n\t{\n\t\tif (posr[x][l] > r) continue;\n\t\tint lf = posr[x][l];\n\t\tint rf = posl[x][r];\n\t\tint now = 0;\n\t\tfor (int i = id[lf]; i < id[rf]; i++) now ^= z[x][i + 1];\n\t\tif (l < lf)\n\t\t{\n\t\t\tif (dpr[x][l] == -1) dpr[x][l] = gett_slow(l, lf - 1);\n\t\t\tnow ^= dpr[x][l];\t\n\t\t}\n\t\tif (rf < r)\n\t\t{\n\t\t\tif (dpl[x][r] == -1) dpl[x][r] = gett_slow(rf + 1, r);\n\t\t\tnow ^= dpl[x][r];\t\n\t\t}\n\t\tif (now < alf) mask |= (1 << now);\n\t}\n\tfor (int i = 0; i < alf; i++)\n\t    if (((mask >> i) & 1) == 0)\n\t        return i;\n\treturn alf;\t\n}\n \ninline int gett_fast(int l, int r)\n{\n\tint mask = 0;\n\tfor (int x = 0; x < alf; x++)\n\t{\n\t\tif (posr[x][l] > r) continue;\n\t\tint lf = posr[x][l];\n\t\tint rf = posl[x][r];\n\t\tint now = (z[x][id[lf]] ^ z[x][id[rf]]);\n\t\tif (l < lf)\n\t\t{\n\t\t\tif (dpr[x][l] == -1) dpr[x][l] = gett_fast(l, lf - 1);\n\t\t\tnow ^= dpr[x][l];\t\n\t\t}\n\t\tif (rf < r)\n\t\t{\n\t\t\tif (dpl[x][r] == -1) dpl[x][r] = gett_fast(rf + 1, r);\n\t\t\tnow ^= dpl[x][r];\t\n\t\t}\n\t\tif (now < alf) mask |= (1 << now);\n\t}\n\tfor (int i = 0; i < alf; i++)\n\t    if (((mask >> i) & 1) == 0)\n\t        return i;\n\treturn alf;\n}\n \nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin >> s;\n\tn = (int)s.size();\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tid[i] = kols[s[i] - 'a'];\n\t\tkols[s[i] - 'a']++;\n\t}\n\tfor (int i = 0; i < alf; i++)\n\t\tposr[i][n] = n;\n\tfor (int i = n - 1; i >= 0; i--)\n\t{\n\t\tfor (int x = 0; x < alf; x++)\n\t\t\tposr[x][i] = posr[x][i + 1];\n\t\tposr[s[i] - 'a'][i] = i;\n\t}\n\tfor (int i = 0; i < alf; i++)\n\t\tposl[i][0] = -1;\n\tposl[s[0] - 'a'][0] = 0;         \n\tfor (int i = 1; i < n; i++)\n\t{\n\t\tfor (int x = 0; x < alf; x++)\n\t\t\tposl[x][i] = posl[x][i - 1];\n\t\tposl[s[i] - 'a'][i] = i;\n\t}\n\tmemset(dpl, -1, sizeof(dpl));\n\tmemset(dpr, -1, sizeof(dpr));\n\tmemset(z, 0, sizeof(z));\n\tvector<tuple<int, int, int> > seg;\n\tfor (int x = 0; x < alf; x++)\n\t{\n\t\tvector<int> pos;\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tif (s[i] - 'a' == x)\n\t\t\t\tpos.push_back(i);\n\t\tfor (int t = 0; t < (int)pos.size() - 1; t++)\n\t\t\tseg.push_back(make_tuple(pos[t + 1] - pos[t] - 1, pos[t], pos[t + 1]));\n\t}\n\tsort(seg.begin(), seg.end());\n\tfor (tuple<int, int, int> t : seg)\n\t{\n\t\tint l = get<1>(t);\n\t\tint r = get<2>(t);\n\t\tif (r == l + 1) continue;\n\t\tint x = gett_slow(l + 1, r - 1);\n\t\tz[s[r] - 'a'][id[r]] = x;\n\t}\n\tfor (int x = 0; x < alf; x++)\n\t\tfor (int i = 1; i < kols[x]; i++)\n \t\t\tz[x][i] ^= z[x][i - 1];\t\n\tcin >> q;\n\tfor (int i = 0; i < q; i++)\n\t{\n\t\tint l, r;\n\t\tcin >> l >> r;\n\t\tl--, r--;\n\t\tcout << (gett_fast(l, r) == 0 ? \"Bob\\n\" : \"Alice\\n\");\n\t}\t\n\treturn 0;\n}                                                              ",
    "tags": [
      "games"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1037",
    "index": "H",
    "title": "Security",
    "statement": "Some programming website is establishing a secure communication protocol. For security reasons, they want to choose several more or less random strings.\n\nInitially, they have a string $s$ consisting of lowercase English letters. Now they want to choose $q$ strings using the following steps, and you are to help them.\n\n- A string $x$ consisting of lowercase English letters and integers $l$ and $r$ ($1 \\leq l \\leq r \\leq |s|$) are chosen.\n- Consider all non-empty distinct substrings of the $s_l s_{l + 1} \\ldots s_r$, that is all distinct strings $s_i s_{i+1} \\ldots s_{j}$ where $l \\le i \\le j \\le r$. Among all of them choose all strings that are lexicographically greater than $x$.\n- If there are no such strings, you should print $-1$. Otherwise print the lexicographically smallest among them.\n\nString $a$ is lexicographically less than string $b$, if either $a$ is a prefix of $b$ and $a \\ne b$, or there exists such a position $i$ ($1 \\le i \\le min(|a|, |b|)$), such that $a_i < b_i$ and for all $j$ ($1 \\le j < i$) $a_j = b_j$. Here $|a|$ denotes the length of the string $a$.",
    "tutorial": "The solution does the following: 1. Build the suffix tree of the whole string (we can construct a suffix tree in $O(|S|log|S|)$ time using Suffix Array and LCP Array or in O($|S|$) using any well known algorithm like Ukkonen's algorithm). 2. Note that in a suffix tree, any path from root to leaf is a suffix of the given string. Since we have appended an additional character at the end of S, whose ascii value is smaller than all the literals of string $S$, we have $|S| + 1$ leaves in our suffix tree. 3. For example consider the suffix tree of $aabcaba$. It will look like image shown. 4. Create appropriate type segment tree for the leaves from left to right storing starting position of that leaves. i.e segment tree for $S = aabcaba$ is $[7, 6, 0, 4, 1, 5, 2, 3]$ (starting positions are using 0 based indexing for string S). 5. To answer the request $L R X$, start descending with this string in the suffix tree from root. To make the larger string we can end the descent process and go on the other edge (which contains a larger symbol), to do this we need to have at least one valid suffix in this subtree - Valid suffix: it's beginning $i$ should be $L \\leq i$, $i \\leq R$ and if you stand in the vertex of subtree with length $len$, then $i + len \\leq R$, that is $i \\leq R - len$. So the request is too see if any leaf in subtree of matching character from current node has at least on value $L \\leq i \\leq R-len$. The rest is to handle the descent, i.e for example if going to a node with match character from current node, in the middle if we encounter the character to be greater than corresponding character of X, then we will stop the descent process, or if the character of S is smaller than corresponding character of X, then we must ascend till we find a node having valid suffix and matching character greater than corresponding character of S. Complexity of the solution is $O(|x|log(n)*26)$ per request. Consider processing the query for $S = aabcaba$: 2 5 abca Modify for 0 based indexes i.e. 1 4 abca Matching character a, $1 \\leq i \\leq 5$: The node 3 matches with a, its subtree have leaves with [6,0,4,1] values and [1,4] are acceptable, so we can ascend. Matching character b, $1 \\leq i \\leq 4$: The node 6 matches with b, its subtree have leaves with [4,1] both are acceptable values for i, so we can ascend to node 6. Matching character c, $1 \\leq i \\leq 3$: The node 8 matches with c, has leaf with value 1, and it is valid, now we start matching subsequent characters to reach node 8, match c, $1 \\leq i \\leq2$ match a, $1 \\leq i \\leq1$ match $ , $1 \\leq i \\leq 0$ (can't match so start ascent process) Current node 6: No node with character > c exists, so move to its parent 3. Current node 3: No node with character > b exists, so move to its parent 1. Current node 1: Node 9 has starting character b, which is greater than a, also the subtree of node 9 contains leaves with values [5,2], $1 \\leq i \\leq 5$, so we can take b and print the currently traversed string so far. Complexity: $O(|x| * LogN * 26)$ per request.",
    "code": "#include <cstring>\n#include <vector>\n#include <algorithm>\n#include <map>\n#include <iostream>\nusing namespace std;\n#define ve vector\n#define MaxN 500010\n#pragma warning(disable:4996)\n/* Persistent segment tree\n*/\nint Slen=100001;\nconst int SZ = MaxN * 21;\nint seg_tree[SZ], L_ptr[SZ], R_ptr[SZ], Next = 1;\nint add(int c, int l, int r, int pos)\n{\n\tif (l>pos || r < pos)\n\t\treturn c;\n\tint ID = Next++;\n\tif (l == r)\n\t{\n\t\tseg_tree[ID] = seg_tree[c] + 1;\n\t\treturn ID;\n\t}\n\tint mid = (l + r) >> 1;\n\tL_ptr[ID] = add(L_ptr[c], l, mid, pos);\n\tR_ptr[ID] = add(R_ptr[c], mid + 1, r, pos);\n\tseg_tree[ID] = seg_tree[L_ptr[ID]] + seg_tree[R_ptr[ID]];\n\treturn ID;\n}\nint find_sum(int l_tree_c, int r_tree_c, int l, int r, int qry_l, int qry_r)\n{\n\tif (qry_l > r || qry_r < l)\n\t\treturn 0;\n\tif (l >= qry_l && r <= qry_r)\n\t{\n\t\treturn seg_tree[r_tree_c] - seg_tree[l_tree_c];\n\t}\n\tint mid = (l + r) >> 1;\n\treturn find_sum(L_ptr[l_tree_c], L_ptr[r_tree_c], l, mid, qry_l, qry_r) + \\\n\t\tfind_sum(R_ptr[l_tree_c], R_ptr[r_tree_c], mid + 1, r, qry_l, qry_r);\n}\nint find_first(int l_tree_c, int r_tree_c, int l, int r, int qry_l, int qry_r)\n{\n\tif (qry_l > r || qry_r < l || (seg_tree[r_tree_c] - seg_tree[l_tree_c]) == 0)\n\t\treturn -1;\n\tif (l == r)\n\t{\n\t\treturn l;\n\t}\n\tint mid = (l + r) >> 1;\n\tint val = find_first(L_ptr[l_tree_c], L_ptr[r_tree_c], l, mid, qry_l, qry_r);\n\tif (val == -1)\n\t\treturn find_first(R_ptr[l_tree_c], R_ptr[r_tree_c], mid + 1, r, qry_l, qry_r);\n\treturn val;\n}\n/*Standard Suffix array implementation*/\n \nchar T[MaxN], S[MaxN];\nint n;\nint RA[MaxN], tempRA[MaxN];\nint SA[MaxN], tempSA[MaxN];\nint LCP[MaxN], Phi[MaxN], PLCP[MaxN];\nint c[MaxN], cnt = 1;\nvoid countingSort(int k)\n{\n\tint i, sum, maxi = max(300, n); // up to 255 ASCII chars or length of n\n\tmemset(c, 0, sizeof c); // clear frequency table\n\tfor (i = 0; i < n; i++) // count the frequency of each integer rank\n\t\tc[i + k < n ? RA[i + k] : 0]++;\n\tfor (i = sum = 0; i < maxi; i++)\n\t{\n\t\tint t = c[i]; c[i] = sum; sum += t;\n\t}\n\tfor (i = 0; i < n; i++) // shuffle the suffix array if necessary\n\t\ttempSA[c[SA[i] + k < n ? RA[SA[i] + k] : 0]++] = SA[i];\n\tfor (i = 0; i < n; i++) // update the suffix array SA\n\t\tSA[i] = tempSA[i];\n}\nvoid constructSA() { // this version can go up to 100000 characters\n\tint i, k, r;\n\tfor (i = 0; i < n; i++) RA[i] = T[i]; // initial rankings\n\tfor (i = 0; i < n; i++) SA[i] = i; // initial SA: {0, 1, 2, ..., n-1}\n\tfor (k = 1; k < n; k <<= 1)\n\t{ // repeat sorting process log n times\n\t\tcountingSort(k); // actually radix sort: sort based on the second item\n\t\tcountingSort(0); // then (stable) sort based on the first item\n\t\ttempRA[SA[0]] = r = 0; // re-ranking; start from rank r = 0\n\t\tfor (i = 1; i < n; i++) // compare adjacent suffixes\n\t\t\ttempRA[SA[i]] = // if same pair => same rank r; otherwise, increase r\n\t\t\t(RA[SA[i]] == RA[SA[i - 1]] && RA[SA[i] + k] == RA[SA[i - 1] + k]) ? r : ++r;\n\t\tfor (i = 0; i < n; i++) // update the rank array RA\n\t\t\tRA[i] = tempRA[i];\n\t\tif (RA[SA[n - 1]] == n - 1) break; // nice optimization trick\n\t}\n}\nvoid computeLCP()\n{\n\tint i, L;\n\tPhi[SA[0]] = -1; // default value\n\tfor (i = 1; i < n; i++) // compute Phi in O(n)\n\t\tPhi[SA[i]] = SA[i - 1]; // remember which suffix is behind this suffix\n\tfor (i = L = 0; i < n; i++) { // compute Permuted LCP in O(n)\n\t\tif (Phi[i] == -1) { PLCP[i] = 0; continue; } // special case\n\t\twhile (T[i + L] == T[Phi[i] + L]) L++; // L increased max n times\n\t\tPLCP[i] = L;\n\t\tL = max(L - 1, 0); // L decreased max n times\n\t}\n\tfor (i = 0; i < n; i++) // compute LCP in O(n)\n\t\tLCP[i] = PLCP[SA[i]]; // put the permuted LCP to the correct position\n}\nstruct node\n{\n\tint lf, sp, depth;\n\tmap<char, node*> M;\n\tnode* parent;\n\tnode() :lf(0), depth(0), parent(NULL), sp(0) {}\n\t/*\n\tsp = starting index of suffix in string\n\tdepth = length of string from that suffix\n\t*/\n}*rt;\nnode pool[MaxN * 2 + 4];\nint CNT = 0;\nnode& get_node()\n{\n\treturn pool[CNT++];\n}\nvoid split(node *&n, int id, int lcp)\n{\n\tnode *x = n->parent;\n\tnode *y = &get_node();\n\tnode *z = &get_node();\n\tx->M[T[n->sp + x->depth]] = y;\n\ty->depth = lcp;\n\ty->sp = id;\n\ty->M[T[lcp + id]] = z;\n\ty->M[T[n->sp + lcp]] = n;\n\ty->parent = x;\n\tn->parent = y;\n\tz->depth = ::n - id;\n\tz->sp = id;\n\tz->parent = y;\n\tn = z;\n}\nvoid add(node *&n, int id, int lcp)\n{\n\tif (lcp == 0)\n\t{\n\t\tnode *y = &get_node();\n\t\ty->depth = ::n - id;\n\t\ty->sp = id;\n\t\ty->parent = rt;\n\t\trt->M[T[id]] = y;\n\t\tn = y;\n\t\treturn;\n\t}\n\twhile (n->parent->depth > lcp)\n\t\tn = n->parent;\n\tif (n->parent->depth == lcp)\n\t{\n\t\tn = n->parent;\n\t\tnode *y = &get_node();\n\t\ty->depth = ::n - id;\n\t\ty->sp = id;\n\t\ty->parent = n;\n\t\tn->M[T[id + lcp]] = y;\n\t\tn = y;\n\t\treturn;\n\t}\n\tsplit(n, id, lcp);\n}\nve<int> start_idx(1 + MaxN * 2), end_idx(MaxN), tree_id(MaxN * 2 + 1);\nvoid dfs(node *n)\n{\n\tn->lf = cnt++;\n\tstart_idx[n->lf] = n->lf;\n\tif (!(n->M.size()))\n\t\ttree_id[n->lf] = add(tree_id[n->lf - 1], 0, Slen, n->sp);\n\telse\n\t\ttree_id[n->lf] = tree_id[n->lf - 1];\n\tfor (auto &x : n->M)\n\t{\n\t\tdfs(x.second);\n\t}\n\tend_idx[n->lf] = cnt - 1;\n}\n/*\n1 Exist\n1.1 Exact match\n1.2 Greater\n2 Do not exist\n*/\nvoid climb_up_for_greater(node *cr, int L, int R)\n{\n\tint match = cr->depth;\n\twhile (true)\n\t{\n\t\tmatch = cr->depth;\n\t\tif (cr->M.upper_bound(S[match]) == cr->M.end())\n\t\t{\n\t\t\tif (cr == rt)\n\t\t\t\tbreak;\n\t\t\tcr = cr->parent;\n\t\t\tcontinue;\n\t\t}\n\t\tauto it = cr->M.upper_bound(S[match]);\n\t\tint start, end;\n\t\tint left_valid = -1;\n\t\twhile (it != cr->M.end() && left_valid == -1)\n\t\t{\n\t\t\tstart = it->second->lf, end = it->second->lf;\n\t\t\tleft_valid = find_first(tree_id[start_idx[start] - 1], tree_id[end_idx[end]], 0, Slen, L, R - cr->depth);\n\t\t\tif (left_valid != -1)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++it;\n\t\t}\n\t\tif (left_valid == -1)\n\t\t{\n\t\t\tif (cr == rt)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcr = cr->parent;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (int i = left_valid; i <= left_valid + match; i++)\n\t\t{\n\t\t\tputchar(T[i]);\n\t\t}\n\t\tputchar('\\n');\n\t\treturn;\n\t}\n\tprintf(\"-1\\n\");\n}\nvoid query(int L, int R)\n{\n\tnode *cr = rt;\n\tint match = 0;\n\tint Len = strlen(S);\n\twhile (true)\n\t{\n\t\tif (cr->M.lower_bound(S[match]) == cr->M.end())\n\t\t{\n\t\t\tclimb_up_for_greater(cr, L, R);\n\t\t\treturn;\n\t\t}\n\t\tauto it = cr->M.lower_bound(S[match]);\n\t\tint start, end;\n\t\tint left_valid = -1;\n\t\twhile (it != cr->M.end() && left_valid == -1)\n\t\t{\n\t\t\tstart = it->second->lf, end = it->second->lf;\n\t\t\tleft_valid = find_first(tree_id[start_idx[start] - 1], tree_id[end_idx[end]], 0, Slen, L, R - cr->depth);\n\t\t\tif (left_valid != -1)\n\t\t\t{\n\t\t\t\tcr = it->second;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++it;\n\t\t}\n\t\tif (left_valid == -1)\n\t\t{\n\t\t\tclimb_up_for_greater(cr, L, R);\n\t\t\treturn;\n\t\t}\n\t\t/*\n\t\tmatch till required characters are matched\n\t\tfirst mismatch\n\t\t< : climp_up_for_greater\n\t\t> : print and return\n\t\texceeded Len\n\t\tprint and return\n\t\t*/\n\t\tstart = left_valid + match;\n\t\twhile (match < Len && match < cr->depth && start <= R && T[start] == S[match])\n\t\t\t++match, ++start;\n\t\tif (match == cr->depth)\n\t\t\tcontinue;\n\t\tif (start > R)\n\t\t{\n\t\t\tcr = cr->parent;\n\t\t\tclimb_up_for_greater(cr, L, R);\n\t\t\treturn;\n\t\t}\n\t\tif (match == Len || T[start]>S[match])\n\t\t{\n\t\t\tfor (int i = left_valid; i <= start; i++)\n\t\t\t\tputchar(T[i]);\n\t\t\tputchar('\\n');\n\t\t\treturn;\n\t\t}\n\t\tif (T[start] < S[match])\n\t\t{\n\t\t\tcr = cr->parent;\n\t\t\tclimb_up_for_greater(cr, L, R);\n\t\t\treturn;\n\t\t}\n \n\t}\n}\nint main()\n{\n\tscanf(\"%s\", T);\n\tn = strlen(T);\n\tT[n++] = '$'; // add terminating character\n\tconstructSA();\n\tcomputeLCP();\n\tnode *ty;\n\trt = &get_node();\n\tty = rt;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tadd(ty, SA[i], LCP[i]);\n\t}\n\tdfs(rt);\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; i++)\n\t{\n\t\tint L, R;\n\t\tscanf(\"%d%d%s\", &L, &R, S);\n\t\t--L, --R;\n\t\tquery(L, R);\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "string suffix structures"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1038",
    "index": "A",
    "title": "Equality",
    "statement": "You are given a string $s$ of length $n$, which consists only of the first $k$ letters of the Latin alphabet. All letters in string $s$ are uppercase.\n\nA subsequence of string $s$ is a string that can be derived from $s$ by deleting some of its symbols without changing the order of the remaining symbols. For example, \"ADE\" and \"BD\" are subsequences of \"ABCDE\", but \"DEA\" is not.\n\nA subsequence of $s$ called good if the number of occurences of each of the first $k$ letters of the alphabet is the same.\n\nFind the length of the longest good subsequence of $s$.",
    "tutorial": "First we need to find the frequencies of the first $k$ alphabets in the string. Let the minimum frequency among these frequencies be $m$. Then we cannot select $m+1$ characters of one kind, and we can definitely select $m$ characters of each kind, hence the answer is given by $\\mathrm{min}$(frequency of first $k$ characters) * $k$ Overall Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n \nint n, k;\nstring s;\nint f[26];\n \nint32_t main()\n{\n\tIOS;\n\tcin>>n>>k>>s;\n\tfor(auto &it:s)\n\t\tf[it-'A']++;\n\tint ans=f[0];\n\tfor(int i=0;i<k;i++)\n\t\tans=min(ans, f[i]);\n\tans*=k;\n\tcout<<ans;\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1038",
    "index": "B",
    "title": "Non-Coprime Partition",
    "statement": "Find out if it is possible to partition the first $n$ positive integers into two \\textbf{non-empty} disjoint sets $S_1$ and $S_2$ such that:\n\n\\begin{center}\n$\\mathrm{gcd}(\\mathrm{sum}(S_1), \\mathrm{sum}(S_2)) > 1$\n\\end{center}\n\nHere $\\mathrm{sum}(S)$ denotes the sum of all elements present in set $S$ and $\\mathrm{gcd}$ means thegreatest common divisor.\n\nEvery integer number from $1$ to $n$ should be present in \\textbf{exactly one} of $S_1$ or $S_2$.",
    "tutorial": "There are many ways to solve this question. The easiest way perhaps was to note that the sum of first $n$ numbers is given by $\\frac{n*(n+1) }{2}$, and one of $\\frac{n}{2}$ or $\\frac{n+1}{2}$ has to be an integer, suppose $k$. Then we can partition the numbers into two sets, one containing $k$ and the other containing the remaining integers, both of which will have $k$ as a common factor. Special Case: There is no answer for $n \\le 2$ Overall Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N=1e5+5;\n \nint32_t main()\n{\n\tIOS;\n\tint n;\n\tcin>>n;\n\tif(n<=2)\n\t{\n\t\tcout<<\"No\";\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tcout<<\"Yes\"<<endl;\n\t\tint k=(n%2==0)?(n/2):((n+1)/2);\n\t\tcout<<\"1 \"<<k<<endl;\n\t\tcout<<n-1<<\" \";\n\t\tfor(int i=1;i<=n;i++)\n\t\t{\n\t\t\tif(i==k)\n\t\t\t\tcontinue;\n\t\t\tcout<<i<<\" \";\n\t\t}\n\t\tcout<<endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1038",
    "index": "C",
    "title": "Gambling",
    "statement": "Two players A and B have a list of $n$ integers each. They both want to maximize the subtraction between their score and their opponent's score.\n\nIn one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).\n\nNote, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $\\{1, 2, 2, 3\\}$ in a list and you decided to choose $2$ for the next turn, only a single instance of $2$ will be deleted (and added to the score, if necessary).\n\nThe player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.\n\nOptimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.",
    "tutorial": "This problem was greedy. First, it is obvious that both the players will try to either take their own maximum value or remove the opponent's maximum value. Hence, the arrays should be sorted and two pointers should be maintained to keep track of how many elements from each array have been counted/removed already. In every move, if the person has a choice to either take his own value $A$ or remove his opponent's value $B$, then he will make the choice dependent on the values of $A$ and $B$. In fact, it turns out that it is optimal just to select the choice with a greater number (in case of tie any will do). How to prove it? One can show by induction that it does the same as the dynamic programming of size $n^2$. However, there is a more nice way. Let's say that initially each player gets $0.5$ of all numbers in his list. This way when you choose a number from your own list you add the rest $0.5$ of it to the score. And when you remove the number from opponent's list you remove the $0.5$ of it from your opponent's score. Clearly, all moves become symmetrical to both players now! So each player can make a decision just based on which of the moves is greater. If $A \\gt B$, then he will take his number. If $A \\lt B$, he will discard the opponent's number $B$. If $A=B$, he can make either of the above moves, it will not make a difference. Complexity: $O(n \\log n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N=1e5+5;\n \nint n;\nint a[N], b[N];\n \nint32_t main()\n{\n\tIOS;\n\tcin>>n;\n\tfor(int i=1;i<=n;i++)\n\t\tcin>>a[i];\n\tfor(int i=1;i<=n;i++)\n\t\tcin>>b[i];\n\tsort(a+1, a+n+1);\n\tsort(b+1, b+n+1);\n\treverse(a+1, a+n+1);\n\treverse(b+1, b+n+1);\n\tint i=1, j=1, player=0, moves=0, asum=0, bsum=0;\n\twhile(moves<2*n)\n\t{\n\t\tmoves++;\n\t\tif(!player)\n\t\t{\n\t\t\tif(a[i]>=b[j])\n\t\t\t{\n\t\t\t\tasum+=a[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse\n\t\t\t\tj++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(b[j]>=a[i])\n\t\t\t{\n\t\t\t\tbsum+=b[j];\n\t\t\t\tj++;\n\t\t\t}\n\t\t\telse\n\t\t\t\ti++;\n\t\t}\n\t\tplayer^=1;\n\t}\n\tcout<<asum-bsum;\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1038",
    "index": "D",
    "title": "Slime",
    "statement": "There are $n$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.\n\nAny slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists).\n\nWhen a slime with a value $x$ eats a slime with a value $y$, the eaten slime disappears, and the value of the remaining slime changes to $x - y$.\n\nThe slimes will eat each other until there is only one slime left.\n\nFind the maximum possible value of the last slime.",
    "tutorial": "For every slime, its value will either be added in the final answer or subtracted. Let us give each slime a sign $+$ or $-$ to denote whether its value will be added or subtracted. The key observation to solving the problem is that any combination of $+$ and $-$ is obtainable, except where all signs are $+$ or all are $-$ (exception n=1, where the answer is the value of the slime itself) If the array contains a combination of non-zero positive elements and non-zero negative elements, then we can simply add all their absolute values (since we can put $+$ in front of positive-valued slimes and $-$ in front of negative-valued slimes) However, if the array contains only positive-valued slimes, we put $-$ in front of the least valued slime and $+$ in front of all the others. Similarly, for negative-valued slimes, we put $+$ in front of minimum absolute valued slime. It could have also been solved with DP where we check if - sign has been taken or not, and + sign has been taken or not. ($4n$ states) Overall Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N=5e5+5;\n \nint n, minval=1e9, ans=0;\nint a[N];\nbool checkpos=0, checkneg=0;\n \nint32_t main()\n{\n\tIOS;\n\tcin>>n;\n\tif(n==1)\n\t{\n\t    int k;\n\t    cin>>k;\n\t    cout<<k;\n\t    exit(0);\n\t}\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tcin>>a[i];\n\t\tminval=min(abs(a[i]), minval);\n\t\tcheckpos|=(a[i]>=0);\n\t\tcheckneg|=(a[i]<=0);\n\t\tans+=abs(a[i]);\n\t}\n\tif(checkpos&&checkneg)\n\t\tcout<<ans;\n\telse\n\t\tcout<<ans-2*minval;\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1038",
    "index": "E",
    "title": "Maximum Matching",
    "statement": "You are given $n$ blocks, each of them is of the form [color$_1$|value|color$_2$], where the block can also be flipped to get [color$_2$|value|color$_1$].\n\nA sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.\n\nThe value of the sequence is defined as the sum of the values of the blocks in this sequence.\n\nFind the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.",
    "tutorial": "Create a graph with $4$ nodes $1-4$ representing the colors. Then the value of a block serves as an edge between the two colors of that block. Then the question reduces to finding an euler tour in the graph with the maximum sum of edges traveled. An euler tour may not exist with all the given edges, so the question is: Which edges do we remove? One can note that there are $16$ types of edges. (Edges connecting 1 to 1, 1 to 2 and so on). There may be multiple edges of a specific type, however atmost 1 of it will be removed to form a valid euler tour. This is because if we have $2x + y$ edges between node $A$ and node $B$ where $0 \\le y \\le 1$, we can simply loop back and forth between $A$ and $B$ $x$ times to end up at the node we started from. Since there are only $16$ types of edges, we can use bitmask to iterate over all the possibilities, and checking whether an euler tour exists in the graph with the marked edges removed (if there are multiple edges between node $A$ and node $B$, we remove only one edge, the one with the least value). Refer to author's solution/any AC codes to see implementation details. Overall Complexity: $O(2^{16} \\times n)$ Bonus: Can you solve this question in $O(n^2)$? How about $O(n)$?",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N=1005;\nconst int M=16;\n \nstruct data\n{\n\tint c1, c2, val, idx;\n \n\tbool operator<(data &b)\n\t{\n\t\treturn val<b.val;\n\t}\n};\n \nint n, sum=0, ans=0;\nbool ban[N], vis[N];\nint cnt[M], taken[M];\ndata blocks[N];\nvector<data> g[M], edges[M];\nvector<int> path;\n \nint compress(int c1, int c2)\n{\n\tif(c1>c2)\n\t\tswap(c1, c2);\n\treturn c1*4 + c2;\n}\n \nbool checker()\n{\n\tmemset(cnt, 0, sizeof(cnt));\n\tfor(int i=1;i<path.size();i++)\n\t\tcnt[compress(path[i-1], path[i])]++;\n\tfor(int i=0;i<M;i++)\n\t\tif(cnt[i]>taken[i])\n\t\t\treturn 0;\n\treturn 1;\n}\n \nvoid euler(int u)\n{\n\tfor(auto &it:g[u])\n\t{\n\t\tint v=it.c2;\n\t\tint idx=it.idx;\n\t\tif(vis[idx]||ban[idx])\n\t\t\tcontinue;\n\t\ttaken[compress(u, v)]++;\n\t\tvis[idx]=1;\n\t\tsum+=it.val;\n\t\teuler(v);\n\t}\n\tpath.push_back(u);\n}\n \nint32_t main()\n{\n\tIOS;\n\tcin>>n;\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tint c1, val, c2;\n\t\tcin>>c1>>val>>c2;\n\t\tc1--;\n\t\tc2--;\n\t\tblocks[i]=(data){c1, c2, val, i};\n\t\tg[c1].push_back((data){c1, c2, val, i});\n\t\tg[c2].push_back((data){c2, c1, val, i});\n\t\tedges[compress(c1, c2)].push_back(blocks[i]);\n\t}\n\tfor(int i=0;i<M;i++)\n\t\tif(edges[i].size())\n\t\t\tsort(edges[i].begin(), edges[i].end());\n\tfor(int mask=0;mask<(1<<M);mask++)\n\t{\n\t\tif(mask>>compress(0, 0)&1)\n\t\t\tcontinue;\n\t\tif(mask>>compress(1, 1)&1)\n\t\t\tcontinue;\n\t\tif(mask>>compress(2, 2)&1)\n\t\t\tcontinue;\n\t\tif(mask>>compress(3, 3)&1)\n\t\t\tcontinue;\n \n\t\tint check=0;\n\t\tmemset(ban, 0, sizeof(ban));\n\t\tfor(int i=0;i<M;i++)\n\t\t{\n\t\t\tif(!(mask>>i & 1))\n\t\t\t\tcontinue;\n\t\t\tif(edges[i].empty())\n\t\t\t\tcheck=1;\n\t\t\telse\n\t\t\t\tban[edges[i][0].idx]=1;\n\t\t}\n\t\tif(!check)\n\t\t\tcontinue;\n \n\t\tfor(int i=0;i<4;i++)\n\t\t{\n\t\t\tmemset(vis, 0, sizeof(vis));\n\t\t\tpath.clear();\n\t\t\tsum=0;\n\t\t\tmemset(taken, 0, sizeof(taken));\n\t\t\teuler(i);\n\t\t\tif(checker())\n\t\t\t\tans=max(ans, sum);\n\t\t}\n\t}\n\tcout<<ans;\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1038",
    "index": "F",
    "title": "Wrap Around",
    "statement": "You are given a binary string $s$.\n\nFind the number of distinct cyclical binary strings of length $n$ which contain $s$ as a substring.\n\nThe cyclical string $t$ contains $s$ as a substring if there is some cyclical shift of string $t$, such that $s$ is a substring of this cyclical shift of $t$.\n\nFor example, the cyclical string \"000111\" contains substrings \"001\", \"01110\" and \"10\", but doesn't contain \"0110\" and \"10110\".\n\nTwo cyclical strings are called different if they differ from each other as strings. For example, two different strings, which differ from each other by a cyclical shift, are still considered \\textbf{different} cyclical strings.",
    "tutorial": "The idea was to solve the problem using Dynamic Programming. The constraints of the question were set low to allow even the most basic Dynamic Programming approaches to pass (see the author's solution to see an easy, but time-costly implementation). The solution idea was to use $2n^4$ DP with 4 states: $DP[A][B][C][D]$ $\\\\$ $A$ = Current matching suffix length of string ($n$) $\\\\$ $B$ = Length of string $t$ so far ($n$) $\\\\$ $C$ = Whether string $t$ contains $s$ as a substring (non-cyclical) so far ($2$) $\\\\$ $D$ = Length of the suffix of $t$ that is a prefix of $s$ ($n^2$) You can refer to AC codes for transitions. We may add more details by tomorrow. You can see author's code for an unoptimised approach, and to tester's code for an optimised solution. Overall Complexity: $O(n^4)$",
    "code": "// 2018, Sayutin Dmitry.\n \n#include <bits/stdc++.h>\n \nusing std::cin;\nusing std::cout;\nusing std::cerr;\n \nusing std::vector;\nusing std::map;\nusing std::array;\nusing std::set;\nusing std::string;\n \nusing std::pair;\nusing std::make_pair;\n \nusing std::min;\nusing std::abs;\nusing std::max;\n \nusing std::unique;\nusing std::sort;\nusing std::generate;\nusing std::reverse;\nusing std::min_element;\nusing std::max_element;\n \n#ifdef LOCAL\n#define LASSERT(X) assert(X)\n#else\n#define LASSERT(X) {}\n#endif\n \ntemplate <typename T>\nT input() {\n    T res;\n    cin >> res;\n    LASSERT(cin);\n    return res;\n}\n \ntemplate <typename IT>\nvoid input_seq(IT b, IT e) {\n    std::generate(b, e, input<typename std::remove_reference<decltype(*b)>::type>);\n}\n \n#define SZ(vec)         int((vec).size())\n#define ALL(data)       data.begin(),data.end()\n#define RALL(data)      data.rbegin(),data.rend()\n#define TYPEMAX(type)   std::numeric_limits<type>::max()\n#define TYPEMIN(type)   std::numeric_limits<type>::min()\n \n#define pb push_back\n#define eb emplace_back\n \nconst int max_n = 100;\nint64_t dp[max_n + 5][max_n + 5][max_n + 5];\n \nvector<int> get_pi(const string& s) {\n    vector<int> res(SZ(s), 0);\n \n    for (int i = 1; i != SZ(s); ++i) {\n        int k = res[i - 1];\n        \n        while (k != -1 and s[i] != s[k])\n            k = (k == 0 ? -1 : res[k - 1]);\n \n        res[i] = k + 1;\n    }\n    return res;\n}\n \nint64_t solve(const string& s, int n) {        \n    vector<int> pi = get_pi(s);\n \n    vector<int> go[2];\n    go[0] = go[1] = vector<int>(SZ(s) + 1, -1);\n    \n    go[0][SZ(s)] = go[1][SZ(s)] = SZ(s);\n \n    go[s[0] - '0'][0] = 1;\n    go[(s[0] - '0') ^ 1][0] = 0;\n    \n    for (int i = 1; i != SZ(s); ++i) {\n        int alp = s[i] - '0';\n        go[alp][i] = i + 1;\n        go[alp ^ 1][i] = go[alp ^ 1][pi[i - 1]];\n    }\n \n    // (state_fin, len, go(state_fin, cur_prefix), go(0, cur_prefix))\n \n    int64_t ans = 0;\n    for (int state_fin = 0; state_fin <= SZ(s); ++state_fin) {\n        for (int i = 0; i <= n; ++i)\n            for (int j = 0; j <= SZ(s); ++j)\n                for (int k = 0; k <= SZ(s); ++k)\n                    dp[i][j][k] = 0;\n \n        auto next = [&](int i, int j, int k, int64_t val) {\n            dp[i][j][k] += val;\n        };\n        \n        dp[0][state_fin][0] = 1;\n        for (int len = 0; len < n; ++len)\n            for (int st1 = 0; st1 <= SZ(s); ++st1)\n                for (int st2 = 0; st2 <= SZ(s); ++st2) {\n                    next(len + 1, go[0][st1], go[0][st2], dp[len][st1][st2]);\n                    next(len + 1, go[1][st1], go[1][st2], dp[len][st1][st2]);\n                }\n \n \n        ans += dp[n][SZ(s)][state_fin];\n    }\n \n    return ans;\n}\n \nint main() {\n    std::iostream::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n \n    int n = input<int>();\n    string s = input<string>();\n        \n    \n    cout << solve(s, n) << \"\\n\";\n    \n    return 0;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1039",
    "index": "A",
    "title": "Timetable",
    "statement": "There are two bus stops denoted A and B, and there $n$ buses that go from A to B every day. The shortest path from A to B takes $t$ units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route.\n\nAt each station one can find a sorted list of moments of time when a bus is at this station. We denote this list as $a_1 < a_2 < \\ldots < a_n$ for stop A and as $b_1 < b_2 < \\ldots < b_n$ for stop B. The buses always depart from A and arrive to B according to the timetable, but the order in which the buses arrive may differ. Let's call an order of arrivals valid if each bus arrives at least $t$ units of time later than departs.\n\nIt is known that for an order to be valid the latest possible arrival for the bus that departs at $a_i$ is $b_{x_i}$, i.e. $x_i$-th in the timetable. In other words, for each $i$ there exists such a valid order of arrivals that the bus departed $i$-th arrives $x_i$-th (and all other buses can arrive arbitrary), but there is no valid order of arrivals in which the $i$-th departed bus arrives $(x_i + 1)$-th.\n\nFormally, let's call a permutation $p_1, p_2, \\ldots, p_n$ valid, if $b_{p_i} \\ge a_i + t$ for all $i$. Then $x_i$ is the maximum value of $p_i$ among all valid permutations.\n\nYou are given the sequences $a_1, a_2, \\ldots, a_n$ and $x_1, x_2, \\ldots, x_n$, but not the arrival timetable. Find out any suitable timetable for stop B $b_1, b_2, \\ldots, b_n$ or determine that there is no such timetable.",
    "tutorial": "If there is at least one valid ordering $p$'s (and it surely exists since the $x$ is defined), then the ordering $p_i = i$ is also valid. Hence if for some $i$ doesn't hold $x_i \\ge i$ then the answer is no. Also, from this follows that $b_i \\ge a_i + t$. Otherwise, what it means that $x_i = c$? It means that there is an ordering $p$, in which the $i$-th bus comes as $c$, where the other buses will come then? It turns out, that the least restricting way to complete the ordering is following: $i \\to c$, $i + 1 \\to i$, $i + 2 \\to i$, ..., $c \\to c - 1$. Note that since ordering $p_i = i$, it is also allowed for $i$ to go to $c$ (it wouldn't be too fast), but we can doubt whether $i + 1 \\to i$, $i + 2 \\to i$ and etc are good. More over, since $x_i = c$ (not, say, $c + 1$), it must hold that $i + 1 \\to i$, $i + 2 \\to i$, ..., $c \\to c - 1$ are \"good\" (not fast enough), but doesn't hold $c + 1 \\to c$ (too fast). So for each $i$ we can use scanline to calculate whether it is good or not. And then we can restore $b$'s in negative order. What conditions must hold on $b$? $b_i \\ge a_i + i$, and depending on whether some $i$ is good or not $b_i \\ge a_{i + 1} + t$ or $b_i < a_{i + 1} + t$. We can go in reverse order and select the value of $b_i$ on the basis of the cases above. Also, since $b_i < b_{i + 1}$ if there are many options for $b_i$ it is best to select the largest of them.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1039",
    "index": "B",
    "title": "Subway Pursuit",
    "statement": "This is an interactive problem.\n\nIn the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.\n\nThe subway of the Metropolis is one line (regular straight line with no self-intersections) with $n$ stations, indexed consecutively from $1$ to $n$. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.\n\nTo find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers $l$ and $r$ ($l \\le r$), and then check, whether the train is located on a station with index between $l$ and $r$, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most $k$ stations away. Formally, if the train was at the station $x$ when the gadget was applied, then at the next application of the gadget the train can appear at any station $y$ such that $\\max(1, x - k) \\leq y \\leq \\min(n, x + k)$.\n\nNote that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.\n\nAfter an examination of the gadget you found that it is very old and can hold no more than $4500$ applications, after which it will break and your mission will be considered a failure.\n\nCan you find the station with the train using no more than $4500$ applications of the gadgets?",
    "tutorial": "Notice that we can make segment in which we are located small enough using binary search. Let $[l; r]$ be the last segment about which we knew for sure that train is in it (at the beginning it's $[1; n]$). Let $m = \\frac{l + r}{2}$. Let's ask about segment $[l; m]$. If we receive answer <<YES>>, after this query train for sure will be in segment $[l - k; m + k]$, otherwise in $[m - k; r + k]$. So, after each query length of segment is divided by $2$ and increased by $2k$. After segment length becomes irreducible ($4k$), let's ask about some random station in this segment. If we guessed right, let's finish the program, otherwise make the binary search again. To get the OK let's make one more observation: for all binary searches except the first one initial segment can be made $[l - k; r + k]$ instead of $[1; n]$.",
    "tags": [
      "binary search",
      "interactive",
      "probabilities"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1039",
    "index": "C",
    "title": "Network Safety",
    "statement": "The Metropolis computer network consists of $n$ servers, each has an encryption key in the range from $0$ to $2^k - 1$ assigned to it. Let $c_i$ be the encryption key assigned to the $i$-th server. Additionally, $m$ pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms specifics, a data communication channel can only be considered safe if the two servers it connects have \\textbf{distinct} encryption keys. The initial assignment of encryption keys is guaranteed to keep all data communication channels safe.\n\nYou have been informed that a new virus is actively spreading across the internet, and it is capable to change the encryption key of any server it infects. More specifically, the virus body contains some unknown number $x$ in the same aforementioned range, and when server $i$ is infected, its encryption key changes from $c_i$ to $c_i \\oplus x$, where $\\oplus$ denotes the bitwise XOR operation.\n\nSadly, you know neither the number $x$ nor which servers of Metropolis are going to be infected by the dangerous virus, so you have decided to count the number of such situations in which all data communication channels remain safe. Formally speaking, you need to find the number of pairs $(A, x)$, where $A$ is some (possibly empty) subset of the set of servers and $x$ is some number in the range from $0$ to $2^k - 1$, such that when all servers from the chosen subset $A$ and none of the others are infected by a virus containing the number $x$, all data communication channels remain safe. Since this number can be quite big, you are asked to find its remainder modulo $10^9 + 7$.",
    "tutorial": "Consider a virus containing a fixed number $x$. Let's investigate two servers connected by a data communication channel, denoting their encryption keys equal as $a$ and $b$ respectively. Since $a \\neq b$, it follows that $a \\oplus x \\neq b \\oplus x$. Therefore, if the servers are infected simultaneously the channel remains safe. The same can be said if neither of the servers is infected. When the virus infects exactly one of the two servers the channel between them can cease to be safe only when $x = (a \\oplus b)$ (since $a \\oplus x = b$, it follows that $x = x \\oplus (a \\oplus a) = (x \\oplus a) \\oplus a = (a \\oplus x) \\oplus a = b \\oplus a = a \\oplus b$). Define $a \\oplus b$ as the value of the respective data channel (connecting servers with keys $a$ and $b$). From this it can be inferred that all servers connected by a path of channels with value $x$ can only be infected simultaneously. Thus the answer when the parameter $x$ is fixed is equal to $2^q$, where $q$ is the number of connected components in a graph where servers are considered vertices and data channels with value x are considered edges. This value can be computed in time linearly proportional to the number of edges with value x. When processing the values which are not found on any edge separately this gives us a solution in total time O(E).",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "math",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1039",
    "index": "D",
    "title": "You Are Given a Tree",
    "statement": "A tree is an undirected graph with exactly one simple path between each pair of vertices. We call a set of simple paths $k$-valid if each vertex of the tree belongs to no more than one of these paths (including endpoints) and each path consists of exactly $k$ vertices.\n\nYou are given a tree with $n$ vertices. For each $k$ from $1$ to $n$ inclusive find what is the maximum possible size of a $k$-valid set of simple paths.",
    "tutorial": "Let's examine a solution in $O(n^2)$ first. Introudce a dynamic programming on subtree, the dp of the vertex is the number of paths, which can be taken from the subtree and the maximum length of incomplete path, which ends exactly in vertex v. Notice that this dp can be maximised as pair - the more of complete paths than better, and if the number of complete paths coincides, then it's better to have the incomplete path as long as possible. This dp allows to get an answer in $O(n)$ for a single $k$ How to calculate this dp for a vertex? We need to sum the number of complete paths over all children and also either take one of the incomplete path of children and attach the current vertex to it or try to form a new path from two longest incomplete paths of children. It is possible to use $O(n^2)$ solution to get $O(n \\sqrt(n) log)$ solution. Notice, that $f(k) \\le \\frac{n}{k}$. From this we get, that $f$ takes no more than $O(\\sqrt(n))$ values. Indeed, there are values $f(1), f(2), \\ldots f(\\sqrt(n))$ and for all $m \\ge \\sqrt{n} f(m) \\le \\sqrt{n}$. To find the corresponding bounds we can use binary search - this way we get solution in $O(n \\sqrt(n) log)$. This is already enough to get Accepted on codeforces, however I want to share some more insights about faster, $O(n \\log^2(n))$ solution, it wasn't required to get OK, mostly because we found out that writing this solution is really complicated and making it work faster then sqrt-log solution is even more harder. The funny thing is that we can do a dynamic programming for all $k$ from $1$ to $n$ simultaneously. In fact, we will use cartesian tree (more precisely, it is better to have segment tree for efficiency). We will return from subtree of vertex $v$ structure of size size[v], containing the dp values for all $k$ from $1$ to size[v], where $size$ - it the size of the subtree. So we need to be able to merge results from subtrees. In particular, from the subtree dp's of sizes $s_1, \\ldots, s_t$ ($s_1 \\ge s_2 \\ge \\ldots \\ge s_t$) we want to get $\\sum s_i$. Let's take the result corresponding to $s_1$ as a basis, new-borned end can be appended naively. Also, more or less naively we can make the merge of prefix part of length $s_2$ (because this work \"is paid\" by the fact that we will not return the dp structure of size $s_2$). So we have to deal with a part from $s_2$ to $s_1$. In the structure we store pairs of numbers - how much complete paths, and the length of the incomplete path. Note that there are two types of relaxation - when we increase the number of complete paths and when we simply relax the length of incomplete path. Notice, that $f(k) \\le \\frac{n}{k}$, and hence $\\sum f(k) = O(n \\log(n))$. This way the number of transitions of first type is small and we can perform them naively, we just need to find all such transitions fast. We can maintain in the above mentioned data structure maximums on the segments and fast pull all such transitions. Other transitions can be handled with max= on a suffix and +1 on the whole data structure, the latter we store together with the instance of data structures and handle them when we merge one data structure into the other. The overall complexity is $O(n \\log^2)$.",
    "tags": [
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1039",
    "index": "E",
    "title": "Summer Oenothera Exhibition",
    "statement": "While some people enjoy spending their time solving programming contests, Dina prefers taking beautiful pictures. As soon as Byteland Botanical Garden announced Summer Oenothera Exhibition she decided to test her new camera there.\n\nThe exhibition consists of $l = 10^{100}$ Oenothera species arranged in a row and consecutively numbered with integers from $0$ to $l - 1$. Camera lens allows to take a photo of $w$ species on it, i.e. Dina can take a photo containing flowers with indices from $x$ to $x + w - 1$ for some integer $x$ between $0$ and $l - w$. We will denote such photo with $[x, x + w - 1]$.\n\nShe has taken $n$ photos, the $i$-th of which (in chronological order) is $[x_i, x_i + w - 1]$ in our notation. She decided to build a time-lapse video from these photos once she discovered that Oenothera blossoms open in the evening.\n\nDina takes each photo and truncates it, leaving its segment containing exactly $k$ flowers, then she composes a video of these photos keeping their original order and voilà, a beautiful artwork has been created!\n\nA scene is a contiguous sequence of photos such that the set of flowers on them is the same. The change between two scenes is called a cut. For example, consider the first photo contains flowers $[1, 5]$, the second photo contains flowers $[3, 7]$ and the third photo contains flowers $[8, 12]$. If $k = 3$, then Dina can truncate the first and the second photo into $[3, 5]$, and the third photo into $[9, 11]$. First two photos form a scene, third photo also forms a scene and the transition between these two scenes which happens between the second and the third photos is a cut. If $k = 4$, then each of the transitions between photos has to be a cut.\n\nDina wants the number of cuts to be as small as possible. Please help her! Calculate the minimum possible number of cuts for different values of $k$.",
    "tutorial": "Let's reconsider this task in terms of segments: we need to split sequence of photos-segments into minimum number of contiguous groups such that there exists a subsegment in each group of length $k$, which contains inside of each segment of the group. It's easy to see that if we move right edge of each segment to the left by $k$, it's required to find a single point which is inside of each segments of the group. Let's consider $k$ as the length of each segment. Next, it's always good to include in next group maximum number of segments until they have a on-empty intersection. Therefore, we have solution in $O(n \\cdot q)$ - let's iterate through all segments. If we can add current segment to last group, we add it, else - we create a new group with single current segment. Furthermore, to find next group, we can use segment tree to perform it in $O(\\log n)$. Let's store minimum and maximum values of $x_i$, then we descend the tree to find first segment such that maximum left edge is on the right of minimum left edge. For each $i$ and $x \\le n^{1/3}$ let's calculate minimum length of segments such that group that starts at element $i$ contains at least next $x$ segments. Let's sort all requests in increasing order. We will answer requests in exactly this order. Let's maintain $p_i$ - length of group for current $k$, starting at element $i$ (but $p_i \\le n^{1/3}$). There are $n^{4/3}$ events of changing this value at most. Let's also maintain values $log_i$ - minimum number of groups (and last element of last group) required to jump to element $x \\ge i + n^{1/3}$ or to jump to element $x$ such that $p_x \\ge n^{1/3}$. It's easy to see that when $p_i$ changes, only area of radius $O(n^{1/3})$ is changed for $long$. Therefore $long$ may be recalculated in $O(n^{5/3} \\cdot \\log n)$ in total. Now we can simulate requests: we jump using $long_i$ to the right at least on $n^{1/3}$, therefore there will be $O(q \\cdot n^{2/3})$ jumps in total. The solution became $O(n^{5/3} \\cdot \\log n + n^{5/3})$ for $n = q$. Let's speed up the solution to $O(n^{5/3})$. Let's change the meaning of $long_i$ - we allow the last group to be not maximal. Therefore we are now allowed not to recalculate where exactly last maximal group ends. During simulation we need to perform request on segment tree to understand where exactly last maximal group ends. Now let's do the following: after jump $long_i$ we iterate through next elements and try to add it to last non-maximal group. If we already added more than $n^{2/3}$, let's perform a request on tree in $\\log n$. Therefore the solution performs in $O(n^{5/3} + n^{4/3} \\cdot \\log n)$.",
    "tags": [
      "data structures"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1040",
    "index": "A",
    "title": "Palindrome Dance",
    "statement": "A group of $n$ dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future.\n\nOn the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on.\n\nThe director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending.",
    "tutorial": "Consider a pair of dancers located symmetrically with respect to the center of the stage. If they already have different suits, the answer is definitely \"impossible\". If they both have same suits, they are fine. If one of them doesn't have a suit, buy him a matching one. Finally, if both don't have suits, buy them two same suits of the cheaper color. Also, if $n$ is odd and the central dancer doesn't have a suit, buy him a cheaper one.",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1040",
    "index": "B",
    "title": "Shashlik Cooking",
    "statement": "Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.\n\nThis time Miroslav laid out $n$ skewers parallel to each other, and enumerated them with consecutive integers from $1$ to $n$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $i$, it leads to turning $k$ closest skewers from each side of the skewer $i$, that is, skewers number $i - k$, $i - k + 1$, ..., $i - 1$, $i + 1$, ..., $i + k - 1$, $i + k$ (if they exist).\n\nFor example, let $n = 6$ and $k = 1$. When Miroslav turns skewer number $3$, then skewers with numbers $2$, $3$, and $4$ will come up turned over. If after that he turns skewer number $1$, then skewers number $1$, $3$, and $4$ will be turned over, while skewer number $2$ will be in the initial position (because it is turned again).\n\nAs we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $n$ skewers with the minimal possible number of actions. For example, for the above example $n = 6$ and $k = 1$, two turnings are sufficient: he can turn over skewers number $2$ and $5$.\n\nHelp Miroslav turn over all $n$ skewers.",
    "tutorial": "The funny thing about this problem that it is entirely based on real facts, in the real life the $k$ was equal to $1$ and one skewer really turned two more. So it is easy to see, that answer is at least $\\lceil \\frac{n}{2k + 1} \\rceil$ (because in smaller number of operations we wouldn't simply able to touch all skewers), where the $\\lceil a \\rceil$ denotes rounding up. Set's build an answer with exactly this number of operations. We will make our answer in such way, that each skewer belongs exactly to one operation. That is, we need to put segments of length $2k + 1$ over the array, such that the ends are touching and that the first and last segments don't pop out of the array too much. Let's define $x = \\lceil \\frac{n}{2k + 1} \\rceil (2k + 1) - n$, $a = min(n, k)$, $b = x - a$. Note that $0 \\le a, b \\le k$ and $a + b = x$. Let's make segments described above in such way, that the first segments outweighs over the array exactly by $a$ and the last one exactly by $b$. Since $a, b \\le k$ it follows, that the centre of this segments stays inside the array. Some example: $n = 7$, $k = 2$, $x = 3$, $a = 2$, $b = 1$ The answer is then as in follows: [#|#|@|@|@] [@|@|@|@|#], where @ denotes skewer, and one block of square brackets corresponds to one operation.",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1041",
    "index": "A",
    "title": "Heist",
    "statement": "There was an electronic store heist last night.\n\nAll keyboards which were in the store yesterday were numbered in ascending order from some integer number $x$. For example, if $x = 4$ and there were $3$ keyboards in the store, then the devices had indices $4$, $5$ and $6$, and if $x = 10$ and there were $7$ of them then the keyboards had indices $10$, $11$, $12$, $13$, $14$, $15$ and $16$.\n\nAfter the heist, only $n$ keyboards remain, and they have indices $a_1, a_2, \\dots, a_n$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $x$ nor the number of keyboards in the store before the heist.",
    "tutorial": "Let $x$ - the minimal number from the given numbers and $y$ - the maximal. So we consider that $x$ and $y$ were minimal and maximal keyboard numbers before the heist. All given numbers are distinct, so the answer is $y - x + 1 - n$ (initial number of the keyboards is $(y - x + 1)$ minus the remaining number of keyboards $n$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n;\n    cin >> n;\n    int mn = 1e9, mx = 0;\n    for (int i = 1; i <= n; i++){\n        int x;\n        cin >> x;\n        mn = min(mn, x);\n        mx = max(mx, x);\n    }\n    cout << max(0, (mx-mn)-n+1);    \n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1041",
    "index": "B",
    "title": "Buying a TV Set",
    "statement": "Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than $a$ and screen height not greater than $b$. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is $w$, and the height of the screen is $h$, then the following condition should be met: $\\frac{w}{h} = \\frac{x}{y}$.\n\nThere are many different TV sets in the shop. Monocarp is sure that for any pair of \\textbf{positive integers} $w$ and $h$ there is a TV set with screen width $w$ and height $h$ in the shop.\n\nMonocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of \\textbf{positive integers} $w$ and $h$, beforehand, such that $(w \\le a)$, $(h \\le b)$ and $(\\frac{w}{h} = \\frac{x}{y})$.\n\nIn other words, Monocarp wants to determine the number of TV sets having aspect ratio $\\frac{x}{y}$, screen width not exceeding $a$, and screen height not exceeding $b$. Two TV sets are considered different if they have different screen width or different screen height.",
    "tutorial": "Firstly let's make $x$ and $y$ coprime. To do so, we calculate $g = gcd(x, y)$ and then divide both numbers by $g$. Then the pair $(w, h)$ is included in the answer if the following conditions are met: $w \\le a$, $h \\le b$, and there exists some positive integer $k$ such that $w = kx$ and $h = ky$. Furthermore, each such pair is uniquely determined by this integer $k$. So we can reduce our task to counting the number of positive integers $k$ such that $kx \\le a$ and $ky \\le b$, and that is just $min(\\lfloor \\frac{a}{x} \\rfloor, \\lfloor \\frac{b}{y} \\rfloor)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    \n    ll a, b, c, d;\n    cin >> a >> b >> c >> d;\n    ll gc = __gcd(c, d);\n    c /= gc;\n    d /= gc;\n    cout << min(a/c, b/d);\n}",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1041",
    "index": "C",
    "title": "Coffee Break",
    "statement": "Recently Monocarp got a job. His working day lasts exactly $m$ minutes. During work, Monocarp wants to drink coffee at certain moments: there are $n$ minutes $a_1, a_2, \\dots, a_n$, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute).\n\nHowever, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute $a_i$, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least $d$ minutes pass between any two coffee breaks. Monocarp also wants to take these $n$ coffee breaks in a minimum possible number of \\textbf{working} days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than $d$ minutes pass between the end of any working day and the start of the following working day.\n\nFor each of the $n$ given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.",
    "tutorial": "Let put in set the pairs in the following format: $a_i$ - the time for $i$-th break and the number of this break in the input data. So, we got pairs sorted by $a_i$. While set contains elements we will determine the breaks, which should be done in a single day. For the next day the first break should be dine in the time, which is at the beginning of the set (let this time is $x$). So, next break should be done after at least $d$ minutes. We should find a pair in the set, where the first element not less than $x + d + 1$. It can be done with $lower\\_bound$. In the same way, we can find the next breaks in this day. With help of the second elements of pairs, we can easily remember the answer days for breaks. Also, we should erase from set all considered pairs. If for some pair we cannot find the needed element, we should go to the next day.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 200100;\n\nset<pair<int, int> > q;\n\nint ans[N], n, a[N], m, k;\n\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    \n    cin >> n >> m >> k;\n    for (int i = 1; i <= n; i++){\n        cin >> a[i];\n        q.insert({a[i], i});\n    }\n    int cnt = 0;\n    while(!q.empty()){\n        ++cnt;\n        int pos = q.begin()->second;\n        ans[pos] = cnt;\n        q.erase(q.begin());\n        while(true){\n            auto it = q.lower_bound({a[pos]+1+k, 0});\n            if (it == q.end())\n                break;\n            pos = it->second;\n            q.erase(it);\n            ans[pos] = cnt;\n        }\n    }\n    cout << cnt << \"\\n\";\n    for (int i = 1; i <= n; i++)\n        cout << ans[i] << ' ';\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1041",
    "index": "D",
    "title": "Glider",
    "statement": "A plane is flying at a constant height of $h$ meters above the ground surface. Let's consider that it is flying from the point $(-10^9, h)$ to the point $(10^9, h)$ parallel with $Ox$ axis.\n\nA glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to $Ox$ axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.\n\nThere are ascending air flows on certain segments, each such segment is characterized by two numbers $x_1$ and $x_2$ ($x_1 < x_2$) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along $Ox$ axis, covering one unit of distance every second.\n\n\\begin{center}\n{\\small If the glider jumps out at $1$, he will stop at $10$. Otherwise, if he jumps out at $2$, he will stop at $12$.}\n\\end{center}\n\nDetermine the maximum distance along $Ox$ axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is $0$.",
    "tutorial": "At first, let's prove that it is always optimal to jump out at the beginning of any ascending air flows: if his point of jump is out of any air flow, he can move his point to $+1$ - answer will not decrease, in the same way, if his point of jump in some air flow but not in its beginning, he can move his point to $-1$. Next observation: height of glider is non-ascending function for the fixed point of jump, so we can for each optimal point of jump use binary search of the answer. Let glider jump out at position $x$ and we need to calculate its height at some position $y \\ge x$, then height is equal to $h - (y - x) + sum(x,y)$, where $sum(x,y)$ is a total length of all flows of segment $[x, y]$ and can be calculated using prefix sums (yes, and $lower\\_bound$). Result complexity - $O(n \\log(10^9) \\log(n))$ of time and $O(n)$ of memory. Of course, you can note that this task can be solved with two pointers technique, what is faster, but it is not necessary since built in $lower\\_bound$ function is fast enough (unlike some $set$ or segment tree, which should be written optimally). On the other hand, java-users need to do some extra work by writing its own $lower\\_bound$ function for $int[]$ since $binary\\_search(List<>)$ will cause a slowdown.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nconst int N = 200 * 1000 + 555;\n\nint n, h;\npt a[N];\n\ninline bool read() {\n\tif(!(cin >> n >> h))\n\t\treturn false;\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%d%d\", &a[i].x, &a[i].y) == 2);\n\tsort(a, a + n);\n\treturn true;\n}\n\nint ps[N];\n\nint getH(int lf, int rg) {\n\tint l = int(lower_bound(a, a + n, pt(lf, -1)) - a);\n\tint r = int(lower_bound(a, a + n, pt(rg, -1)) - a);\n\t\n\tint sum = ps[r] - ps[l];\n\tif(l > 0)\n\t\tsum += max(0, a[l - 1].y - lf);\n\t\n\tassert(rg - lf - sum >= 0);\n\treturn rg - lf - sum;\n}\n\ninline void solve() {\n\tps[0] = 0;\n\tfore(i, 0, n)\n\t\tps[i + 1] = ps[i] + (a[i].y - a[i].x);\t\n\t\n\tint ans = 0;\n\tfore(i, 0, n) {\n\t\tint lx = a[i].y + 1;\n\t\t\n\t\tint lf = -(h + 1), rg = lx;\n\t\twhile(rg - lf > 1) {\n\t\t\tint mid = (lf + rg) / 2;\n\t\t\tif(getH(mid, lx) > h)\n\t\t\t\tlf = mid;\n\t\t\telse\n\t\t\t\trg = mid;\n\t\t}\n\t\tassert(getH(rg, lx) == h);\n\t\tans = max(ans, lx - rg);\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n\tif(read()) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1041",
    "index": "E",
    "title": "Tree Reconstruction",
    "statement": "Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $1$ to $n$. For every edge $e$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $e$ (and only this edge) is erased from the tree.\n\nMonocarp has given you a list of $n - 1$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.",
    "tutorial": "First of all, if there exists some $b_i < n$, then the answer is clearly NO. Then let's consider that every $b_i = n$ and analyze only the values of $a_i$ (and furthermore, let's sort all values of $a_i$ beforehand). Suppose that we have constructed a tree satisfying all the requirements and rooted it at vertex $n$. Then for any $k$ such that $1 \\le k \\le n - 1$ there exist no more than $k$ subtrees containing only vertices with indices not exceeding $k$ (because there are no more than $k$ vertices that can be the roots of such subtrees). So, if for some constant $k$ the number of $a_i \\le k$ is greater than $k$, then the answer is NO since it would imply that there are more than $k$ subtrees containing only values not greater then $k$. Now we consider only the case such that for every $k \\in [1, n - 1]$ the number of $i$ such that $a_i \\le k$ is not greater than $k$. In this case the answer is YES; let's prove it with an algorithm that constructs a tree meeting the constraints. Actually, we can always build a bamboo (a tree where no vertex has degree greater than $2$, or simply a path) according to these constraints. Let's put vertex $n$ at one of the ends of the bamboo and start building a bamboo from the other end. It's obvious that if we make some vertex $x$ a leaf, then the array $a$ will contain only values not less than $x$. So, if we consider values of $a_i$ to be sorted, then the leaf has index $a_1$. Then let's repeat the following process for every $i \\in [2, n - 1]$: if $a_i > a_{i - 1}$, then let's use the vertex with index $a_i$ as the parent of the previous vertex; otherwise, let's find any index $j$ such that $j < a_i$ and index $j$ is not used yet, and use vertex with index $j$ as the parent of the previous vertex (there will be at least one such vertex since for every $k \\in [1, n - 1]$ the number of $i$ such that $a_i \\le k$ is not greater than $k$). It's easy to prove that the bamboo we construct in such a way meets the constraints given in the statement.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\n\nint cnt[N];\n\nint main()\n{                \n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n - 1; i++)\n\t{\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\tif(y != n)\n\t\t{\n\t\t\tputs(\"NO\");\n\t\t\treturn 0;\n\t\t}\n\t\tcnt[x]++;\n\t}\n\tint cur = 0;\n\tfor(int i = 1; i < n; i++)\n\t{\n\t\tcur += cnt[i];\n\t\tif(cur > i)\n\t\t{\n\t\t\tputs(\"NO\");\n\t\t\treturn 0;\n\t\t}\n\t}\n\tint last = -1;\n\tputs(\"YES\");\n\tset<int> unused;\n\tfor(int i = 1; i < n; i++)\n\t\tunused.insert(i);\n\tfor(int i = 1; i < n; i++)\n\t{\n\t\tif(cnt[i] > 0)\n\t\t{\n\t\t\tunused.erase(i);\n\t\t\tif(last != -1)\n\t\t\t\tprintf(\"%d %d\\n\", last, i);\n\t\t\tlast = i;\n\t\t\tcnt[i]--;\n\t\t}\n\t\twhile(cnt[i] > 0)\n\t\t{\n\t\t\tprintf(\"%d %d\\n\", last, *unused.begin());\n\t\t\tlast = *unused.begin();\n\t\t\tcnt[i]--;\n\t\t\tunused.erase(unused.begin());\n\t\t}\n\t}\n\tprintf(\"%d %d\\n\", last, n);\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1041",
    "index": "F",
    "title": "Ray in the tube",
    "statement": "You are given a tube which is reflective inside represented as two non-coinciding, but parallel to $Ox$ lines. Each line has some special integer points — positions of sensors on sides of the tube.\n\nYou are going to emit a laser ray in the tube. To do so, you have to choose \\textbf{two} integer points $A$ and $B$ on the first and the second line respectively (coordinates can be negative): the point $A$ is responsible for the position of the laser, and the point $B$ — for the direction of the laser ray. The laser ray is a ray starting at $A$ and directed at $B$ which will reflect from the sides of the tube (it doesn't matter if there are any sensors at a reflection point or not). A sensor will only register the ray if the ray hits exactly at the position of the sensor.\n\n\\begin{center}\n{\\small Examples of laser rays. Note that image contains two examples. The $3$ sensors (denoted by black bold points on the tube sides) will register the blue ray but only $2$ will register the red.}\n\\end{center}\n\nCalculate the maximum number of sensors which can register your ray if you choose points $A$ and $B$ on the first and the second lines respectively.",
    "tutorial": "At first, $y$ coordinates don't matter. Let $dx$ be signed difference between $x$ coordinates of $B$ and $A$, then on the first line all points with coordinates $x_A + dx \\cdot (2k)$ will be chosen, and on the second line all points with coordinates $x_A + dx \\cdot (2k + 1)$ will be chosen. Let's prove that it is always optimal to take $dx = 2^l$ where $l \\ge 0$. Let $dx$ is not a power of two, then $dx = m \\cdot 2^l$, where $m$ is odd. Note that $dx / m$ hits all points which is hitted by $dx$ that why answer will not decrease. So, we need to check only $dx = 2^l$, number of such $dx$ is equal to $O(\\log(10^9))$. For the fixed $dx$ note that ray hits both points on the same line iff $x_1 \\equiv x_2 \\mod{(2 \\cdot dx)}$. Analogically, the ray hits both points on the different lines iff $x_1 + dx \\equiv x_2 \\mod{(2 \\cdot dx)}$. That's why we can split all point on the equivalent classes modulo $2 \\cdot dx$ and take the size of the biggest class. We can do it by sort and two pointers or by $map$. Result complexity is $O(n \\log{(10^9)} \\log n)$ time and $O(n)$ memory.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nconst int N = 100 * 1000 + 555;\n\nint n[2], y[2];\nint x[2][N];\n\ninline bool read() {\n\tfore(k, 0, 2) {\n\t\tif(!(cin >> n[k] >> y[k]))\n\t\t\treturn false;\n\t\tfore(i, 0, n[k])\n\t\t\tassert(scanf(\"%d\", &x[k][i]) == 1);\n\t}\n\treturn true;\n}\n\ninline void solve() {\n\tint ans = 2;\n\tfor(int dx = 1; dx < int(1e9); dx *= 2) {\n\t\tint mod = 2 * dx;\n\t\tmap<int, int> cnt;\n\t\t\n\t\tint add[2] = {0, dx};\n\t\tfore(k, 0, 2) {\n\t\t\tfore(i, 0, n[k])\n\t\t\t\tcnt[(x[k][i] + add[k]) & (mod - 1)]++;\n\t\t}\n\t\t\n\t\tfor(auto curAns : cnt)\n\t\t\tans = max(ans, curAns.second);\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n\tif(read()) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1042",
    "index": "A",
    "title": "Benches",
    "statement": "There are $n$ benches in the Berland Central park. It is known that $a_i$ people are currently sitting on the $i$-th bench. Another $m$ people are coming to the park and each of them is going to have a seat on some bench out of $n$ available.\n\nLet $k$ be the maximum number of people sitting on one bench after additional $m$ people came to the park. Calculate the minimum possible $k$ and the maximum possible $k$.\n\nNobody leaves the taken seat during the whole process.",
    "tutorial": "The maximum value of $k$ should be determined in the following way: let's find the maximum number of people already sitting on the same bench (i. e. the maximum value in the array $a$). Let this number be $t$. Then if all additional $m$ people will seat on this bench, we will get the maximum value of $k$, so the answer is $t + m$. To determine the minimum value of $k$ let's perform $m$ operations. During each operation we put a new person on the bench currently having minimum number of people occupying it. The answer is the maximum number of people on the bench after we perform this operation for each of $m$ newcomers.",
    "code": "#include <set>\n#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <cassert>\n\nusing namespace std;\n\nconst int N = 100 + 13;\n\nint n, m;\nint a[N];\n\nint main() {\n    cin >> n >> m;\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    int ans2 = *max_element(a, a + n) + m;\n    for (int it = 0; it < m; it++) {\n        int pos = -1;\n        for (int i = 0; i < n; i++) {\n            if (pos == -1 || a[i] < a[pos]) {\n                pos = i;\n            }\n        }\n        assert(pos != -1);\n        a[pos]++;\n    }\n    int ans1 = *max_element(a, a + n);\n    cout << ans1 << ' ' << ans2 << endl;\n}",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1042",
    "index": "B",
    "title": "Vitamins",
    "statement": "Berland shop sells $n$ kinds of juices. Each juice has its price $c_i$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin \"A\", vitamin \"B\" and vitamin \"C\". Each juice can contain one, two or all three types of vitamins in it.\n\nPetya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.",
    "tutorial": "Let's calculate the minimum cost of the juice containing only the vitamin \"A\", only the vitamin \"B\" and only the vitamin \"C\". Also let's calculate the minimum cost of the juice containing all three vitamins. If there is at least one juice containing only the vitamin \"A\", at least one juice containing only the vitamin \"B\" and at least one juice containing only the vitamin \"C\", let's update the answer with the sum of the corresponding minimum costs. If there is at least one juice containing all three vitamins, let's update the answer with its cost. Only one case remains - when Petya has to buy two juices. Let's iterate over all pairs of juices using nested loops. Let the index of the first juice we iterate be $a$, the index of the second juice be $b$. We have to check that the strings $s_a$ and $s_b$ contain all three letters \"A\", \"B\", \"C\" (i.e. these juices contain all the vitamins). If they do, let's update the answer with the value $c_a + c_b$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint n;\nmap<string, int> was;\n\ninline void read() {\t\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tint c;\n\t\tstring s;\n\t\tcin >> c >> s;\n\t\tsort(s.begin(), s.end());\n\t\tif (was.count(s) == 0) {\n\t\t\twas[s] = c;\n\t\t} else {\n\t\t\twas[s] = min(was[s], c);\n\t\t}\n\t}\n}\n\ninline int getC(string a, string b) {\n \tif (!was.count(a) || !was.count(b)) {\n \t\treturn INF;\n \t}\n \treturn was[a] + was[b];\n}\n\ninline void solve() {\n\tint ans = INF;\n\tif (was.count(\"A\") && was.count(\"B\") && was.count(\"C\")) {\n\t\tans = was[\"A\"] + was[\"B\"] + was[\"C\"];\n\t}\n    if (was.count(\"ABC\")) {\n    \tans = min(ans, was[\"ABC\"]);\n    }\n    ans = min(ans, getC(\"AB\", \"C\"));\n    ans = min(ans, getC(\"A\", \"BC\"));\n    ans = min(ans, getC(\"AC\", \"B\"));\n    ans = min(ans, getC(\"AB\", \"BC\"));\n    ans = min(ans, getC(\"AC\", \"BC\"));\n    ans = min(ans, getC(\"AC\", \"AB\"));\n    if (ans == INF) {\n    \tans = -1;\n    }\n    cout << ans << endl;\n}\n\nint main () {\n    read();\n    solve();\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1042",
    "index": "C",
    "title": "Array Product",
    "statement": "You are given an array $a$ consisting of $n$ integers. You can perform the following operations with it:\n\n- Choose some positions $i$ and $j$ ($1 \\le i, j \\le n, i \\ne j$), write the value of $a_i \\cdot a_j$ into the $j$-th cell and \\textbf{remove the number} from the $i$-th cell;\n- Choose some position $i$ and \\textbf{remove the number} from the $i$-th cell (this operation can be performed \\textbf{no more than once and at any point of time, not necessarily in the beginning}).\n\nThe number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.\n\nYour task is to perform exactly $n - 1$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print \\textbf{any} sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.",
    "tutorial": "There are several cases in the problem. Let the number of zeroes in the array be $cntZero$ and the number of negative elements be $cntNeg$. Also let $maxNeg$ be the position of the maximum negative element in the array, or $-1$ if there are no negative elements in the array. Let the answer part be the product of all the numbers which will be in the answer and the removed part be the product of all the numbers which will be removed by the second type operation. The first case is the following: $cntZero = 0$ and $cntNeg = 0$. Then the answer part is the product of all the numbers in the array. The removed part is empty. The second case is the following: $cntNeg$ is odd. Then the answer part is the product of all the numbers in the array except all zeroes and $a_{maxNeg}$. The removed part is the product of all zeroes and $a_{maxNeg}$. And the third case is the following: $cntNeg$ is even. Then the answer part is the product of all the numbers in the array except all zeroes. The removed part is the product of all zeroes in the array (be careful in case $cntNeg = 0$ and $cntZero = n$). Be careful with printing the answer because my first solution printed $n$ operations instead of $n-1$ operations in case $cntZero = n$ or $cntZero = n-1$ and $cntNeg = 1$. And the funniest part of this problem is the checker. The first thing I thought was \"Well, I want to write a fair checker on this problem\". I did exactly that. What do we need? Split all the numbers in the array into two parts? Okay, let's write DSU to do that. What's next? Multiply $2 \\cdot 10^5$ numbers from $1$ to $10^9$? Okay, let's use FFT and Divide and Conquer! And the last part is the comparing two numbers of length about $2 \\cdot 10^6$. So writing this checker was pretty easy problem. But the coordinator didn't like that and I replaced it with very easy checker which uses some ideas from the solution. :(",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tint cntneg = 0;\n\tint cntzero = 0;\n\tvector<int> used(n);\n\tint pos = -1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (a[i] == 0) {\n\t\t\tused[i] = 1;\n\t\t\t++cntzero;\n\t\t}\n\t\tif (a[i] < 0) {\n\t\t\t++cntneg;\n\t\t\tif (pos == -1 || abs(a[pos]) > abs(a[i]))\n\t\t\t\tpos = i;\n\t\t}\n\t}\n\tif (cntneg & 1)\n\t\tused[pos] = 1;\n\t\t\n\tif (cntzero == n || (cntzero == n - 1 && cntneg == 1)) {\n\t\tfor (int i = 0; i < n - 1; ++i)\n\t\t\tprintf(\"1 %d %d\\n\", i + 1, i + 2);\n\t\treturn 0;\n\t}\n\t\n\tint lst = -1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (used[i]) {\n\t\t\tif (lst != -1) printf(\"1 %d %d\\n\", lst + 1, i + 1);\n\t\t\tlst = i;\n\t\t}\n\t}\n\tif (lst != -1) printf(\"2 %d\\n\", lst + 1);\n\t\n\tlst = -1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (!used[i]) {\n\t\t\tif (lst != -1) printf(\"1 %d %d\\n\", lst + 1, i + 1);\n\t\t\tlst = i;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1042",
    "index": "D",
    "title": "Petya and Array",
    "statement": "Petya has an array $a$ consisting of $n$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.\n\nNow he wonders what is the number of segments in his array with the sum less than $t$. Help Petya to calculate this number.\n\nMore formally, you are required to calculate the number of pairs $l, r$ ($l \\le r$) such that $a_l + a_{l+1} + \\dots + a_{r-1} + a_r < t$.",
    "tutorial": "Let's reformulate the problem. Now the problem is to calculate the difference between the prefix sums to the right border and to the left border instead of the sum on the segment. Let $pref[i] = \\sum\\limits_{j=1}^{i} a[j]$, a $pref[0] = 0$. Then the answer to the problem is $\\sum\\limits_{L=1}^{n}\\sum\\limits_{R=L}^{n} pref[R] - pref[L - 1] < t$. It's easy to see that the answer for the fixed $L$ is $\\sum\\limits_{R=L}^{n} pref[R] < t + pref[L - 1]$. We can calculate this formula using some data structure which allows us to get the number of elements less than given and set the value at some position. For example, segment tree or BIT (Fenwick tree).",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\n\nint n;\nlong long T;\nint a[N];\nint f[N];\n\nvoid upd(int x){\n\tfor (int i = x; i < N; i |= i + 1)\n\t\t++f[i];\n}\n\nint get(int x){\n\tint res = 0;\n\tfor (int i = x; i >= 0; i = (i & (i + 1)) - 1)\n\t\tres += f[i];\n\treturn res;\n}\n\nint main() {\n\tscanf(\"%d%lld\", &n, &T);\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tvector<long long> sums(1, 0ll);\n\tlong long pr = 0;\n\tforn(i, n){\n\t\tpr += a[i];\n\t\tsums.push_back(pr);\n\t}\n\t\n\tsort(sums.begin(), sums.end());\n\tsums.resize(unique(sums.begin(), sums.end()) - sums.begin());\n\t\n\tlong long ans = 0;\n\tpr = 0;\n\tupd(lower_bound(sums.begin(), sums.end(), 0ll) - sums.begin());\n\t\n\tforn(i, n){\n\t\tpr += a[i];\n\t\t\n\t\tint npos = upper_bound(sums.begin(), sums.end(), pr - T) - sums.begin();\n\t\tans += (i + 1 - get(npos - 1));\n\t\t\n\t\tint k = lower_bound(sums.begin(), sums.end(), pr) - sums.begin();\n\t\tupd(k);\n\t}\n\t\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1042",
    "index": "E",
    "title": "Vasya and Magic Matrix",
    "statement": "Vasya has got a magic matrix $a$ of size $n \\times m$. The rows of the matrix are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $m$ from left to right. Let $a_{ij}$ be the element in the intersection of the $i$-th row and the $j$-th column.\n\nVasya has also got a chip. Initially, the chip is in the intersection of the $r$-th row and the $c$-th column (that is, in the element $a_{rc}$). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.\n\nAfter moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.\n\nEuclidean distance between matrix elements with coordinates $(i_1, j_1)$ and $(i_2, j_2)$ is equal to $\\sqrt{(i_1-i_2)^2 + (j_1-j_2)^2}$.\n\nCalculate the expected value of the Vasya's final score.\n\nIt can be shown that the answer can be represented as $\\frac{P}{Q}$, where $P$ and $Q$ are coprime integer numbers, and $Q \\not\\equiv 0~(mod ~ 998244353)$. Print the value $P \\cdot Q^{-1}$ modulo $998244353$.",
    "tutorial": "Let's iterate over all the elements of the matrix in order of increasing their values and calculate the expected value for these elements to solve the problem. Suppose that now we consider the element at intersection of the $R$-th row and the $C$-th column. Let the elements having value less than the value of the current element be $(r_1, c_1), (r_2, c_2), \\dots , (r_k, c_k)$, where $r_i$ is the row of the $i$-th element and $c_i$ is the column of the $i$-th element. Then the expected value for the current element can be calculated as follows: $\\frac{\\sum\\limits_{i=1}^{k}{(ev_i + (R - r_i)^2 + (C - c_i)^2)}}{k}$, where $ev_i$ is the expected value of the $i$-th element. We can rewrite the formula to the following form using equivalent transforms: $\\frac{\\sum\\limits_{i=1}^{k}{ ev_i }}{k} + R^2 + C^2 + \\frac{\\sum\\limits_{i=1}^{k}{ {r_i}^2 }}{k} + \\frac{\\sum\\limits_{i=1}^{k}{ {c_i}^2 }}{k} - 2\\frac{\\sum\\limits_{i=1}^{k}{ Rr_i }}{k} -2\\frac{\\sum\\limits_{i=1}^{k}{ Cc_i }}{k}$. So we need to maintain five sums for the elements having value less than current element: sum of their values, sum of their row indices, sum of their column indices, sum of squares of their row indices and sum of squares of their column indices. We can maintain all these sums if we will iterate over all the elements continuously in order of increasing their values. It is also necessary to note that we need to process all the elements having equal values at once and recalculate all the sums right after calculating the expected values for these elements.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 1009;\n\nint mul(int a, int b){\n\treturn int(a * 1LL * b % MOD);\n}\n\nvoid upd(int &a, int b){\n\ta += b;\n\twhile(a >= MOD) a -= MOD;\n\twhile(a < 0) a += MOD;\n}\n\nint bp(int a, int n){\n\tint res = 1;\n\tfor(; n > 0; n >>= 1){\n\t\tif(n & 1) res = mul(res, a);\n\t\ta = mul(a, a);\n\t}\n\t\n\treturn res;\n}\n\nint inv(int a){\n\tint ia = bp(a, MOD - 2);\n\tassert(mul(a, ia) == 1);\n\treturn ia;\n}\n\nint n, m;\nint a[N][N];\nint dp[N][N];\nint si, sj;\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 0; i < n; ++i) \n\t\tfor(int j = 0; j < m; ++j)\n\t\t\tscanf(\"%d\", &a[i][j]);\n\tscanf(\"%d %d\", &si, &sj);\n\t--si, --sj;\n\t\n\tvector <pair<int, pair<int, int> > > v;\n\tfor(int i = 0; i < n; ++i)\n\t\tfor(int j = 0; j < m; ++j)\n\t\t\tv.push_back(make_pair(a[i][j], make_pair(i, j)));\n\n\tsort(v.begin(), v.end());\n\tint l = 0;\n\tint sumDP = 0, sumX = 0, sumY = 0, sumX2 = 0, sumY2 = 0;\n\twhile(l < int(v.size())){\n\t\tint r = l;\n\t\twhile(r < int(v.size()) && v[r].first == v[l].first) ++r;\n\t\t\n\t\tint il = -1;\n\t\tif(l != 0) il = inv(l);\n\t\tfor(int i = l; i < r; ++i){\n\t\t\tint x = v[i].second.first, y = v[i].second.second;\n\t\t\tif(il == -1){\n\t\t\t\tdp[x][y] = 0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tupd(dp[x][y], mul(sumDP, il));\n\t\t\t\n\t\t\tupd(dp[x][y], mul(x, x));\n\t\t\tupd(dp[x][y], mul(y, y));\n\t\t\t\n\t\t\tupd(dp[x][y], mul(sumX2, il));\n\t\t\tupd(dp[x][y], mul(sumY2, il));\n\t\t\t\n\t\t\tupd(dp[x][y], mul(mul(-x - x, sumX), il));\n\t\t\tupd(dp[x][y], mul(mul(-y - y, sumY), il));\t\t\n\t\t}\n\t\t\n\t\tfor(int i = l; i < r; ++i){\n\t\t\tint x = v[i].second.first, y = v[i].second.second;\n\t\t\t\n\t\t\tupd(sumDP, dp[x][y]);\n\t\t\t\n\t\t\tupd(sumX2, mul(x, x));\n\t\t\tupd(sumY2, mul(y, y));\n\t\t\t\n\t\t\tupd(sumX, x);\n\t\t\tupd(sumY, y);\n\t\t}\n\t\t\n\t\tl = r;\n\t\t\n\t}\n\t\n\tprintf(\"%d\\n\", dp[si][sj]);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1042",
    "index": "F",
    "title": "Leaf Sets",
    "statement": "You are given an undirected tree, consisting of $n$ vertices.\n\nThe vertex is called a leaf if it has exactly one vertex adjacent to it.\n\nThe distance between some pair of vertices is the number of edges in the shortest path between them.\n\nLet's call some set of leaves beautiful if the maximum distance between any pair of leaves in it is less or equal to $k$.\n\nYou want to split \\textbf{all} leaves into \\textbf{non-intersecting} beautiful sets. What is the minimal number of sets in such a split?",
    "tutorial": "Let's use the following technique, which is pretty common for tree problems. Let the root of the tree be some none-leaf vertex. Run dfs from the root and let the vertex yield all the resulting sets in the optimal answer for its subtree. For each vertex you iterate over its children and merge the yielded sets. The first thing to notice is that you only need the deepest vertex from each set to check its mergeability. Let's call the distance between the vertex $v$ and the deepest vertex in some set $u$ in its subtree $d_u$. Now two sets $a$ and $b$ can be merged only if $d_a + d_b \\le k$. Moreover, $d$ value of the resulting the set is $max(d_a, d_b)$. The time has come to reveal the merging process. We will heavily rely on a fact that the resulting $d$ doesn't change after merging. Let's merge the sets with the smallest $d$ to any other possible sets. Now we can deduce the small-to-large solution from it. Let the vertex yield the whole multiset of the depths of the resulting sets. Now take the child with the largest number of resulting sets and add all the values from the other children to its multiset. Then merge the maximum possible number of sets and yield the result. The size of set yielded by the root is the answer. The complexity of this solution is $O(n \\cdot log^2{n})$, which still can be too slow. You can notice that if you have a pair of sets $a$ and $b$ such that $d_a \\le d_b, d_a + d_b > k$, set $b$ will never affect the answer. If some set $c$ could later be merged with $b$, it can be with $a$ as well. Thus, you can erase set $b$ from the result and add $1$ to the answer. Then the vertex will always yield a single set. The solution mentioned above works in $O(n \\log n)$ with this modification. This can later be modified a bit to a $O(n)$ solution but that is totally unnecessary and works about the same time as $O(n \\log n)$. It still takes most of the time to read the input.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define sz(a) int((a).size())\n\nconst int N = 1000 * 1000 + 13;\n\nint n, k;\nvector<int> g[N];\nint ans;\n\nint dfs(int v, int p = -1){\n\tif (g[v].size() == 1)\n\t\treturn 0;\n\t\n\tvector<int> cur;\n\tfor (auto u : g[v]){\n\t\tif (u == p) continue;\n\t\tcur.push_back(dfs(u, v) + 1);\n\t}\n\t\n\tint pos = -1;\n\tforn(i, sz(cur)) {\n\t\tif (cur[i] * 2 <= k && (pos == -1 || cur[pos] < cur[i]))\n\t\t\tpos = i;\n\t}\n\t\n\tif (pos == -1) {\n\t\tans += sz(cur) - 1;\n\t\treturn *min_element(cur.begin(), cur.end());\n\t}\n\t\n\tint res = -1;\n\tforn(i, sz(cur)) {\n\t\tif (cur[pos] >= cur[i]) continue;\n\t\tif (cur[i] + cur[pos] <= k && (res == -1 || cur[i] < cur[res]))\n\t\t\tres = i;\n\t}\n\t\n\tforn(i, sz(cur))\n\t\tans += (cur[i] > cur[pos]);\n\tif (res != -1)\n\t\t--ans;\n\t\n\treturn (res == -1 ? cur[pos] : cur[res]);\n}\n\nint main(){\n\tscanf(\"%d%d\", &n, &k);\n\tforn(i, n - 1) {\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\t\n\tforn(i, n) {\n\t\tif (sz(g[i]) > 1) {\n\t\t\tdfs(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tprintf(\"%d\\n\", ans + 1);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1043",
    "index": "A",
    "title": "Elections",
    "statement": "Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are $n$ students in the school. Each student has exactly $k$ votes and is obligated to use all of them. So Awruk knows that if a person gives $a_i$ votes for Elodreip, than he will get exactly $k - a_i$ votes from this person. Of course $0 \\le k - a_i$ holds.\n\nAwruk knows that if he loses his life is over. He has been speaking a lot with his friends and now he knows $a_1, a_2, \\dots, a_n$ — how many votes for Elodreip each student wants to give. Now he wants to change the number $k$ to win the elections. Of course he knows that bigger $k$ means bigger chance that somebody may notice that he has changed something and then he will be disqualified.\n\nSo, Awruk knows $a_1, a_2, \\dots, a_n$ — how many votes each student will give to his opponent. Help him select the smallest winning number $k$. In order to win, Awruk needs to get strictly more votes than Elodreip.",
    "tutorial": "We can observe that result cannot exceed $201$ - Awruk gets at least $101$ votes from one person and Elodreip cannot get more than $100$ votes from one person. So we can iterate over every possible integer from $1$ to $201$ and check if Awruk wins with $k$ set to this integer. We have to remember that $k$ - $a_{i}$ is always at least $0$, so we have to check this condition too. Complexity $O(n * M)$, where $M$ denotes maximum possible value of $a_{i}$. Try to solve it in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nint mx = 0, sum = 0;\n\nint main(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i){\n\t\tint a;\tscanf(\"%d\", &a);\n\t\tmx = max(mx, a);\n\t\tsum += a;\n\t}\n\t\n\tsum *= 2;\n\tsum += n;\n\tsum /= n;\n\t\n\tprintf(\"%d\", max(sum, mx));\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1043",
    "index": "B",
    "title": "Lost Array",
    "statement": "Bajtek, known for his unusual gifts, recently got an integer array $x_0, x_1, \\ldots, x_{k-1}$.\n\nUnfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array $a$ of length $n + 1$. As a formal description of $a$ says, $a_0 = 0$ and for all other $i$ ($1 \\le i \\le n$) $a_i = x_{(i-1)\\bmod k} + a_{i-1}$, where $p \\bmod q$ denotes the remainder of division $p$ by $q$.\n\nFor example, if the $x = [1, 2, 3]$ and $n = 5$, then:\n\n- $a_0 = 0$,\n- $a_1 = x_{0\\bmod 3}+a_0=x_0+0=1$,\n- $a_2 = x_{1\\bmod 3}+a_1=x_1+1=3$,\n- $a_3 = x_{2\\bmod 3}+a_2=x_2+3=6$,\n- $a_4 = x_{3\\bmod 3}+a_3=x_0+6=7$,\n- $a_5 = x_{4\\bmod 3}+a_4=x_1+7=9$.\n\nSo, if the $x = [1, 2, 3]$ and $n = 5$, then $a = [0, 1, 3, 6, 7, 9]$.\n\nNow the boy hopes that he will be able to restore $x$ from $a$! Knowing that $1 \\le k \\le n$, help him and find all possible values of $k$ — possible lengths of the lost array.",
    "tutorial": "First, let's observe that we can replace array $a_{i}$ with array $b_{i}$ = $a_{i}$ $-$ $a_{i - 1}$, because all we care about are differences between neighboring elements. Now, we can see that our lost array can have length $d$ if and only if for every $j$ such that $j$ $+$ $d$ $ \\le $ $n$, $b_{j}$ $=$ $b_{j + d}$. So we can iterate over every possible $d$ from $1$ to $n$ and check if it is correct in $O(n)$. Complexity of whole algorithm is $O(n^{2})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1007;\n\nint n;\nint in[N];\n\nbool ok(int d){\n\tfor(int i = 0; i + d < n; ++i)\n\t\tif(in[i + 1] - in[i] != in[i + d + 1] - in[i + d])\n\t\t\treturn false;\n\treturn true;\n}\n\nint main(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &in[i]);\n\t\n\tvector <int> res;\n\tfor(int i = 1; i <= n; ++i)\n\t\tif(ok(i))\n\t\t\tres.push_back(i);\n\t\n\tprintf(\"%d\\n\", res.size());\n\tfor(int v: res)\n\t\tprintf(\"%d \", v);\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1043",
    "index": "C",
    "title": "Smallest Word",
    "statement": "IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.\n\nToday, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. \"It would look much better when I'll swap some of them!\" — thought the girl — \"but how to do it?\". After a while, she got an idea. IA will look at all prefixes with lengths from $1$ to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Basically in problem we are given a word in which for every $i$ we can reverse prefix of first $i$ elements and we want to get the smallest lexicographically word. We will show that we can always achieve word in form $a^{j}b^{n - j}$. Let's say that we solved our problem for prefix of length $i$ and for this prefix we have word $a^{j}b^{i - j}$ (at the beginning it's just empty word). If our next letter is $b$ then we do nothing, because we will get word $a^{j}b^{i - j + 1}$ which is still the smallest lexicographically word. Otherwise we want to reverse prefix of length $i$, add letter $a$ and reverse prefix of length $i$ $+$ $1$, so we get a word $a^{j + 1}b^{i - j}$, which is still fine for us. There is still a problem - what if we have already reversed prefix $i$ and we just said that we will reverse it second time. But instead of reversing it second time, we can deny it's first reverse. Final complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1007;\n\nstring s;\nbool write[N];\n\nint main(){\n\tcin >> s;\n\tfor(int i = 1; i < s.size(); ++i)\n\t\tif(s[i] == 'a'){\n\t\t\twrite[i - 1] ^= 1;\n\t\t\twrite[i] = 1;\n\t\t}\n\t\n\tfor(int i = 0; i < s.size(); ++i)\n\t\tprintf(\"%d%c\", write[i], i + 1 == (int)s.size() ? '\\n' : ' ');\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1043",
    "index": "D",
    "title": "Mysterious Crime",
    "statement": "Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked $m$ neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from $1$ to $n$. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour.\n\nHowever, some facts are very suspicious – how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? \"In the morning some of neighbours must have been sleeping!\" — thinks Gawry — \"and in the evening there's been too dark to see somebody's face...\". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that — some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other.\n\nIn how many ways he can do it? Two ways are called different if the remaining common part is different.",
    "tutorial": "Deleting prefix and suffix is nothing more than taking a subarray. If subarray is common for all permutations then it has to appear in first permutation. We renumber all permutations such that first permutation is $1$, $2$, ..., $n$ $-$ $1$, $n$. Now for every $i$ in every permutation we count how long is subarray starting at $i$ which looks like $i$, $i$ $+$ $1$, ..., $i$ $+$ $k$. It can be easily done in $O(n)$ for one permutation with two pointers technique. Now for every element $i$ we compute $reach[i]$ equal the longest subarray starting in $i$ which looks like $i$, $i$ $+$ $1$, ..., $i$ $+$ $k$ and it apears in all subarrays. It is just minimum over previously calculated values for all permutations. Now we can see that our result is $\\sum_{i=1}^{n}r e a c h[i]-i$. Final complexity $O(nm)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long int LL;\n\nconst int N = 1e5 + 7;\n\nint n, m;\nint mn[N];\nint ren[N];\nint perm[15][N];\n\nint main(){\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 1; i <= m; ++i)\n\t\tfor(int j = 1; j <= n; ++j)\n\t\t\tscanf(\"%d\", &perm[i][j]);\n\t\n\tfor(int i = 1; i <= n; ++i)\n\t\tren[perm[1][i]] = i;\n\t\n\tfor(int i = 1; i <= m; ++i)\n\t\tfor(int j = 1; j <= n; ++j)\n\t\t\tperm[i][j] = ren[perm[i][j]];\n\t\t\n\tfor(int i = 1; i <= n; ++i)\n\t\tmn[i] = n;\n\t\t\n\tfor(int i = 1; i <= m; ++i){\n\t\tint cur = 1;\n\t\tfor(int j = 1; j <= n; ++j){\n\t\t\tif(cur < j)\n\t\t\t\t++cur;\n\n\t\t\twhile(cur < n && perm[i][cur + 1] == perm[i][cur] + 1)\n\t\t\t\t++cur;\n\t\t\tmn[perm[i][j]] = min(mn[perm[i][j]], perm[i][cur]);\n\t\t}\n\t}\n\t\n\tLL res = 0;\n\tint now = 1;\n\twhile(now <= n){\n\t\tint cur = mn[now] - now + 1;\n\t\tres += 1LL * (cur + 1) * cur / 2LL;\n\t\tnow = mn[now] + 1;\n\t}\n\t\n\tprintf(\"%lld\\n\", res);\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "math",
      "meet-in-the-middle",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1043",
    "index": "E",
    "title": "Train Hard, Win Easy",
    "statement": "Zibi is a competitive programming coach. There are $n$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.\n\nRules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the \\textbf{less} the score is, the better).\n\nWe know that the $i$-th competitor will always have score $x_i$ when he codes the first task and $y_i$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.\n\nZibi wants all competitors to write a contest with each other. However, there are $m$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?",
    "tutorial": "Let's compute result if there are no edges, we can add them later. If there are no edges then result for pair ($i$, $j$) is min($x_{i}$ $+$ $y_{j}$, $x_{j}$ $+$ $y_{i}$). First let's fix $i$ for which we want to compute result. Then calculate result with all pairs $j$ such that $x_{i}$ $+$ $y_{j}$ $ \\le $ $x_{j}$ $+$ $y_{i}$. After some transformations we get that $x_{i}$ $-$ $y_{i}$ $ \\le $ $x_{j}$ $-$ $y_{j}$. Similarly we have that $y_{i}$ $+$ $x_{j}$ $<$ $x_{i}$ $+$ $y_{j}$ if $x_{i}$ $-$ $y_{i}$ $>$ $y_{j}$ $-$ $x_{j}$. So let's sort over differences of $x_{i}$ $-$ $y_{i}$ and compute prefix sums of $x_{i}$ and suffix sums of $y_{i}$. Now we can compute for every $i$ result in $O(1)$. Then we can iterate over every edge ($u$, $v$) and subtract min($x_{u}$ $+$ $y_{v}$, $x_{v}$ $+$ $y_{u}$) from result of $u$ and $v$. Complexity $O(nlogn)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long int LL;\n\n#define st first\n#define nd second\n#define PII pair <int, int>\n\nconst int N = 3e5 + 7;\n\nint n, m;\nPII diff[N];\nint place[N];\nvector <int> G[N];\n\nLL ans[N];\nint x[N], y[N];\nLL pref[N], suf[N];\n\nint main(){\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 1; i <= n; ++i){\n\t\tscanf(\"%d %d\", &x[i], &y[i]);\n\t\tdiff[i] = {y[i] - x[i], i};\n\t}\n\t\n\tfor(int i = 1; i <= m; ++i){\n\t\tint u, v;\n\t\tscanf(\"%d %d\", &u, &v);\n\n\t\tG[u].push_back(v);\n\t\tG[v].push_back(u);\n\t}\n\t\n\tsort(diff + 1, diff + n + 1);\n\tfor(int i = 1; i <= n; ++i)\n\t\tplace[diff[i].nd] = i;\n\t\n\tfor(int i = 1; i <= n; ++i)\n\t\tpref[i] = pref[i - 1] + y[diff[i].nd];\n\t\n\tfor(int i = n; i >= 1; --i)\n\t\tsuf[i] = suf[i + 1] + x[diff[i].nd];\n\t\n\tfor(int i = 1; i <= n; ++i){\n\t\tint u = diff[i].nd;\n\t\tLL res = pref[i - 1] + suf[i + 1] + 1LL * (i - 1) * x[u] + 1LL * (n - i) * y[u];\n\t\t\n\t\tfor(int v: G[u])\n\t\t\tres -= min(x[u] + y[v], x[v] + y[u]);\n\t\tans[u] = res;\n\t}\n\t\n\tfor(int i = 1; i <= n; ++i)\n\t\tprintf(\"%lld \", ans[i]);\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1043",
    "index": "F",
    "title": "Make It One",
    "statement": "Janusz is a businessman. He owns a company \"Januszex\", which produces games for teenagers. Last hit of Januszex was a cool one-person game \"Make it one\". The player is given a sequence of $n$ integers $a_i$.\n\nIt is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $1$. Now Janusz wonders, for given sequence, how much elements should the player choose?",
    "tutorial": "First let's observe that if there exists valid subset then it's size is at most $7$ (because product of $7$ smallest primes is bigger then $3 * 10^{5}$). Let's define $dp[i][j]$ - number of ways to pick $i$ different elements such that their gcd is equal to $j$. We can use inclusion--exclusion principle to calculate it. Then $dp[i][j]$ = $\\textstyle{\\binom{-n i j}{i}}$ - $\\sum_{k=2}^{\\infty}d p[i][k*j]$, where $cnt_{j}$ denotes number of $a_{i}$ such that $j$ $|$ $a_{i}$. Because for $k * j$ $>$ $3 * 10^{5}$, $dp[i][k * j]$ $=$ $0$ we have to check only $k * j$ $ \\le $ $3 * 10^{5}$. Our answer is the smallest $i$ such that $dp[i][1]$ is non-zero. Since $dp[i][j]$ can be quite big we should compute it modulo some big prime. Final complexity is $O(logM * (n + M))$, where M is equal to maximum of $a_{i}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 3e5 + 7;\n\nint n;\nint cnt[N];\nint roz[N];\nint dist[N];\nqueue <int> Q;\nvector <int> dv[N];\n\nint base(int a){\n\tint ret = 1;\n\twhile(a > 1){\n\t\tif(ret%roz[a] != 0)\n\t\t\tret *= roz[a];\n\t\ta /= roz[a];\n\t}\n\t\n\treturn ret;\n}\n\nvoid getEdges(int u, int d){\n\tvector <int> cur;\n\tvector <int> val;\n\t\n\twhile(u > 1){\n\t\tcur.push_back(roz[u]);\n\t\tu /= roz[u];\n\t}\n\t\n\tfor(int v: cur)\n\t\tu *= v;\n\t\n\tint T = 1 << (int)cur.size();\n\tval.resize(T);\n\t\n\tfor(int i = 0; i < T; ++i){\n\t\tval[i] = u;\n\t\tfor(int j = 0; j < (int)cur.size(); ++j)\n\t\t\tif(i & (1 << j))\n\t\t\t\tval[i] /= cur[j];\n\t}\n\t\n\tfor(int i = 0; i < T; ++i){\n\t\tint s = 0;\n\t\tfor(int j = i; true; j = (j - 1) & i){\n\t\t\tif(__builtin_popcount(i ^ j) & 1)\n\t\t\t\ts -= cnt[val[j]];\n\t\t\telse\n\t\t\t\ts += cnt[val[j]];\n\t\t\t\n\t\t\tif(j == 0)\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tassert(s >= 0);\n\t\tif(s && dist[val[i]] == -1){\n\t\t\tdist[val[i]] = d;\n\t\t\tQ.push(val[i]);\n\t\t}\n\t}\n}\n\nint main(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 2; i < N; ++i){\n\t\tif(roz[i] != 0)\n\t\t\tcontinue;\n\n\t\tfor(int j = i; j < N; j += i)\n\t\t\troz[j] = i;\n\t}\n\t\n\tfor(int i = 1; i < N; ++i)\n\t\tfor(int j = i; j < N; j += i)\n\t\t\tdv[j].push_back(i);\n\t\n\tfor(int i = 1; i < N; ++i)\n\t\tdist[i] = -1;\n\t\n\tfor(int i = 1; i <= n; ++i){\n\t\tint a;\n\t\tscanf(\"%d\", &a);\n\t\ta = base(a);\n\t\t\n\t\tif(dist[a] != -1)\n\t\t\tcontinue;\n\n\t\tdist[a] = 1;\n\t\tQ.push(a);\n\t\t\n\t\tfor(int v: dv[a])\n\t\t\tcnt[v]++;\n\t}\n\t\n\twhile(!Q.empty()){\n\t\tint u = Q.front();\n\t\tQ.pop();\n\t\tgetEdges(u, dist[u] + 1);\n\t}\n\t\n\tprintf(\"%d\\n\", dist[1]);\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math",
      "number theory",
      "shortest paths"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1043",
    "index": "G",
    "title": "Speckled Band",
    "statement": "Ildar took a band (a thin strip of cloth) and colored it. Formally, the band has $n$ cells, each of them is colored into one of $26$ colors, so we can denote each color with one of the lowercase letters of English alphabet.\n\nIldar decided to take some segment of the band $[l, r]$ ($1 \\le l \\le r \\le n$) he likes and cut it from the band. So he will create a new band that can be represented as a string $t = s_l s_{l+1} \\ldots s_r$.\n\nAfter that Ildar will play the following game: he cuts the band $t$ into some new bands and counts the number of different bands among them. Formally, Ildar chooses $1 \\le k \\le |t|$ indexes $1 \\le i_1 < i_2 < \\ldots < i_k = |t|$ and cuts $t$ to $k$ bands-strings $t_1 t_2 \\ldots t_{i_1}, t_{i_1 + 1} \\ldots t_{i_2}, \\ldots, {t_{i_{k-1} + 1}} \\ldots t_{i_k}$ and counts the number of different bands among them. He wants to know the minimal possible number of different bands he can get under the constraint that at least one band repeats at least two times. The result of the game is this number. If it is impossible to cut $t$ in such a way, the result of the game is -1.\n\nUnfortunately Ildar hasn't yet decided which segment he likes, but he has $q$ segments-candidates $[l_1, r_1]$, $[l_2, r_2]$, ..., $[l_q, r_q]$. Your task is to calculate the result of the game for each of them.",
    "tutorial": "Let's solve the problem for some string $s$ for any time. Let's say, that partition of string $s$ into $k$ strings $s_{1s}_{2}... s_{i1}, s_{i1 + 1}... s_{i2}, ..., {s_{ik - 1 + 1}}... s_{ik}$ is good if at least one pair of this strings are equal. We want to find a minimal possible number of different strings in all good partitions. It's easy to see, that the answer is $- 1$ if and only if all symbols in $s$ are different. And if we have two equal symbols $s_{i} = s_{j}$ ($i < j$) we can cut a string into strings $s_{1}... s_{i - 1}, s_{i}, s_{i + 1}... s_{j - 1}, s_{j}, s_{j + 1}... s_{n}$ and it is a good partition. In this partition there is at most $4$ different strings. So the answer can be $- 1$, $1$, $2$, $3$, $4$. The answer is $- 1$ if all symbols in $s$ are different (case $0$). The answer is $1$ if the string $s = aaa... a$, for some string $a$ (case $1$). The answer is $2$ if the string $s$ is $aab$, $aba$ or $baa$ for some strings $a$ and $b$ (case $2$). The answer is $3$ if the string $s$ is $baac$, $bcaa$ or $aabc$ for some strings $a$, $b$, $c$. In two last cases it's easy to see, that $|a| = 1$ (case $3$). To solve our problem let's build suffix array with lcp for string $s$. And let's find $lt_{i}$~--- minimal possible number $r$, such that $s_{is}_{i + 1}... s_{r}$ is a tandem (the string, that can be presented as $aa$ for some string $a$) and $rt_{i}$~--- maximal possible number $l$ such that $s_{ls}_{l + 1}... s_{i}$ is a tandem. This numbers can be found using Main and Lorentz algorithm for finding tandem repetitions in the string. Now we can solve query for segment $[l, r]$: \\begin{itemize} \\item Case $0$: if $r - l  \\ge  26$, there exists equal symbols, otherwise we can check it by $O(r - l)$; \\item Case $1$: to check that $s[l... r] = aa... a$ we can see that $|a|$ is a divisor of $(r - l + 1)$ and $(r - l + 1) / |a|$ is a prime number (if we take a longest possible string $a$). So we should check only $O(log(n))$ lenghts of string $a$; \\item Case $2$: $s = aab$ $\\displaystyle{\\hat{\\mathbf{c}}}\\,{\\hat{\\mathbf{-}}}$ $lt_{l}  \\le  r$, $s = baa$ $\\displaystyle{\\hat{\\mathbf{\\omega}}}\\,{\\hat{\\mathbf{\\Lambda}}}$ $rt_{r}  \\ge  l$. In the last case we should check, that $s[l... r]$ has a border. It's the most interesting part of the problem, let's solve it in the end; \\item Case $3$: $s = abac$ $\\displaystyle{\\hat{\\mathbf{\\omega}}}\\,{\\hat{\\mathbf{\\Lambda}}}$ $s_{l}$ exists on $s_{l + 1}... s_{r}$ (can be done using prefix sums), $s = baca$ $\\displaystyle{\\hat{\\mathbf{\\omega}}}\\,{\\hat{\\mathbf{-}}}$ $s_{r}$ exists on $s_{l}... s_{r - 1}$ (can be done using prefix sums). To check $s = baac$ we can check, that $lt_{i}  \\le  r$ for some $l  \\le  i  \\le  r$, that can be done using minimum on segment in the array $lt$. \\end{itemize} Now we should the hardest part of this problem~--- we have some segments $[l, r]$. For all of them, we should check that the border of $s[l... r]$ exists. Here I know two methods, that uses only suffix array. Easiest of them: We have segment $[l, r]$. Let's check for all lengths $b\\leq{\\sqrt{n}}$, that $s[l... (l + b - 1)] = s[(r - b + 1)... r]$. If we don't find border, if it exists, it's length $\\geqslant{\\sqrt{n}}$. Let's define $i$~--- maximal index $i$ such that $lcp(l, i)  \\ge  r - i + 1$, and string $s[i... r]$ is a border of $s[l... r]$. So $l c p(l,i)>\\sqrt{n}$. But it's easy to see, that the distance between $l$ and $i$ in suffix array $\\leq{\\sqrt{n}}$ , so we need to check only $O({\\sqrt{n}})$ variants of $i$. Another method can check that border exists for all segments $[l, r]$ using offline algorithm by $O(q \\cdot log(n)^{2})$ time. So the total complexity will be $O((n+q)\\cdot{\\sqrt{n}})$ or $O((n + q) \\cdot log(n)^{2})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define TIME (clock() * 1.0 / CLOCKS_PER_SEC)\n\nconst int BIG = 1e9 + 239;\nconst int M = 2 * 1e5 + 239;\nconst int L = 19;\nconst int A = 30;\nconst int T = (1 << 19);\nconst int two = 2;\n\nint flm[two][M];\n\ninline void z_function(string &s, int c)\n{\n\tint n = s.length();\n\tflm[c][0] = 0;\n\tint l = 0;\n\tint r = 0;\n\tfor (int i = 1; i < n; i++)\n\t{\n\t\tflm[c][i] = min(flm[c][i - l], r - i);\n\t\tif (flm[c][i] < 0) flm[c][i] = 0;\n\t\twhile (i + flm[c][i] < n && s[flm[c][i]] == s[i + flm[c][i]]) flm[c][i]++;\n\t\tif (i + flm[c][i] > r)\n\t\t{\n\t\t\tl = i;\n\t\t\tr = i + flm[c][i];\n\t\t}\n\t}        \n}\n\nint a[M], lcp[M], pos[M];\n\ninline void suffix_array(string s)\n{\n\ts += (char)(31);\n\tint n = s.length();\n\tvector<pair<char, int> > v;\n\tfor (int i = 0; i < n; i++)\n\t\tv.push_back(make_pair(s[i], i));\n\tsort(v.begin(), v.end());\n\tvector<pair<int, int> > num;\n\tint last = 0;\n\tfor (int i = 0; i < n - 1; i++)\n\t{\n\t\tnum.push_back(make_pair(last, v[i].second));\n\t\tif (v[i].first != v[i + 1].first) last++;\n\t}\n\tnum.push_back(make_pair(last, v.back().second));\n\tvector<int> u(n);\n\tfor (int i = 0; i < n; i++) u[num[i].second] = num[i].first;\n\tint d = 1;\n\tvector<pair<pair<int, int>, int> > t;\n\tvector<vector<pair<int, int> > > h;\n\twhile (d < n)\n\t{\n\t\tt.clear();\n\t\th.clear();\n\t\th.resize(n);\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tint l = num[i].second - d;\n\t\t\tif (l < 0) l += n;\n\t\t\th[u[l]].push_back(make_pair(num[i].first, l));\n\t\t}\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tfor (pair<int, int> r : h[i])\n\t\t\t\tt.push_back(make_pair(make_pair(i, r.first), r.second));\n\t\tlast = 0;\n\t\tnum.clear();\n\t\tfor (int i = 0; i < n - 1; i++)\n\t\t{\n\t\t\tnum.push_back(make_pair(last, t[i].second));\n\t\t\tif (t[i].first != t[i + 1].first) last++;\n\t\t}\n\t\tnum.push_back(make_pair(last, t.back().second));\n\t\tfor (int i = 0; i < n; i++) u[num[i].second] = num[i].first;\n\t\td <<= 1;\n\t}                           \n\tfor (int i = 1; i < n; i++) a[i - 1] = num[i].second;\n}\n\nstring s;                 \n\ninline void kasai()\n{\n\tint n = s.size();\n\tsuffix_array(s); \n\tfor (int i = 0; i < n; i++)\n\t\tpos[a[i]] = i;\n\tint k = 0;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tif (pos[i] == n - 1) continue;\n\t\twhile (s[i + k] == s[a[pos[i] + 1] + k] && a[pos[i] + 1] + k < n && i + k < n) k++;\n\t\tlcp[pos[i]] = k;\n\t\tk = max(0, k - 1);\n\t}\n}\n\nint n, lw[M], rw[M]; \nstring prr, rvl;                     \nvector<int> open_l[M], close_l[M];   \nvector<int> open_r[M], close_r[M];\nmultiset<int> nw;\n\ninline void func(int l, int r)\n{\n\tif (r - l == 1) return;\n\tint mid = (l + r) >> 1;\n\tfunc(l, mid);\n\tfunc(mid, r);\n\trvl = \"\";\n\tfor (int i = mid - 1; i >= l; i--) rvl += s[i];\n\tz_function(rvl, 0);\n\tprr = \"\";\n\tfor (int i = mid; i < r; i++) prr += s[i];\n\tprr += '#';\n\tfor (int i = l; i < mid; i++) prr += s[i];\n\tz_function(prr, 1);\t\n\tfor (int c = l; c < mid; c++)\n\t{\n\t\tint k1 = 0;\n\t\tif (c > l) k1 = flm[0][mid - c];\n\t\tint k2 = flm[1][r - mid + 1 + c - l];\n\t\tint len = mid - c;\n\t\tint lg = max(len - k2, 0);\n\t\tint rg = min(len - 1, k1);\n\t\tif (rg >= lg)\n\t\t{\n\t\t\topen_l[c - rg].push_back((2 * len));\n\t\t\tclose_l[c - lg].push_back((2 * len));\n\t\t\topen_r[c - rg + 2 * len - 1].push_back((2 * len));\n\t\t\tclose_r[c - lg + 2 * len - 1].push_back((2 * len));\n\t\t}\t\n\t}\n\trvl = \"\";\n\tfor (int i = mid; i < r; i++) rvl += s[i];\n\tz_function(rvl, 0);\n\tprr = \"\";\n\tfor (int i = mid - 1; i >= l; i--) prr += s[i];\n\tprr += '#';\n\tfor (int i = r - 1; i >= mid; i--) prr += s[i];\n\tz_function(prr, 1); \n\tfor (int c = mid; c < r; c++)\n\t{\n\t\tint k1 = 0;\n\t\tif (c != r - 1) k1 = flm[0][c + 1 - mid];\n\t\tint k2 = flm[1][r - c + mid - l];\n\t\tint len = c - mid + 1;\n\t\tint lg = max(len - k2, 0);\n\t\tint rg = min(len - 1, k1);\n\t\tif (rg >= lg)\n\t\t{                                            \n\t\t\topen_l[c + lg - 2 * len + 1].push_back((2 * len));\n\t\t\tclose_l[c + rg - 2 * len + 1].push_back((2 * len));\n\t\t\topen_r[c + lg].push_back((2 * len));\n\t\t\tclose_r[c + rg].push_back((2 * len));\n\t\t}\t\n\t}\n\tfor (int i = l; i < r; i++)\n\t{\n\t\tfor (int len : open_l[i]) nw.insert(len);\n\t\tif (!nw.empty()) lw[i] = min(lw[i], *nw.begin());\n\t\tfor (int len : close_l[i]) nw.erase(nw.lower_bound(len));\n\t\topen_l[i].clear();\n\t\tclose_l[i].clear();\n\t}          \n\tfor (int i = l; i < r; i++)\n\t{\n\t\tfor (int len : open_r[i]) nw.insert(len);\n\t\tif (!nw.empty()) rw[i] = min(rw[i], *nw.begin());\n\t\tfor (int len : close_r[i]) nw.erase(nw.lower_bound(len));\n\t\topen_r[i].clear();\n\t\tclose_r[i].clear();\n\t}\n}\n\nint mn[L][M], st2[M], lc[L][M], kol[A][M];\n\ninline int getmin(int l, int r)\n{\n\tint u = st2[r - l + 1];\n\treturn min(mn[u][l], mn[u][r - (1 << u) + 1]);\n}\n\ninline int gett(int l, int r)\n{\n\tif (l == r) return (n - l);\n\tl = pos[l];\n\tr = pos[r];\n\tif (l > r) swap(l, r);\n\tr--;\n\tint u = st2[r - l + 1];\n\treturn min(lc[u][l], lc[u][r - (1 << u) + 1]);\n}\n\nint q, mnp[M];\n\ninline void init()\n{\n\tfor (int i = 0; i < n; i++) mn[0][i] = lw[i];\n\tfor (int i = 0; i < n - 1; i++) lc[0][i] = lcp[i];\n\tfor (int i = 1; i < L; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t{\n\t\t\tint r = (j + (1 << (i - 1)));\n\t\t\tif (r >= n)\n\t\t\t{\n\t\t\t\tmn[i][j] = mn[i - 1][j];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmn[i][j] = min(mn[i - 1][j], mn[i - 1][r]);\n\t\t}\n\tfor (int i = 1; i < L; i++)\n\t\tfor (int j = 0; j < n - 1; j++)\n\t\t{\n\t\t\tint r = (j + (1 << (i - 1)));\n\t\t\tif (r >= n - 1)\n\t\t\t{\n\t\t\t\tlc[i][j] = lc[i - 1][j];\n\t\t\t\tcontinue;\n\t\t\t}                                          \n\t\t\tlc[i][j] = min(lc[i - 1][j], lc[i - 1][r]);\n\t\t}\t\n\tst2[1] = 0;\n\tfor (int i = 2; i <= n; i++)\n\t{\n\t\tst2[i] = st2[i - 1];\n\t\tif ((1 << (st2[i] + 1)) <= i) st2[i]++;\n\t}\t\n}\n\nint u, len;\n\ninline bool check(int l, int r)\n{\n\tfor (int t = 1; t <= min(len, ((r - l + 1) / 2)); t++)\n\t\tif (gett(l, r - t + 1) >= t)\n\t\t\treturn true;\n\tfor (int i = max(0, pos[l] - len); i <= min(n - 1, pos[l] + len); i++)\n\t\tif (l < a[i] && a[i] <= r && gett(l, a[i]) >= r - a[i] + 1) \n\t\t\treturn true;\n\treturn false;\n}\n\ninline bool checkno(int l, int r)\n{\n\tif (r - l + 1 > 26) return false;\n\tvector<int> kol(26, 0);\n\tfor (int x = l; x <= r; x++)\n\t{\n\t\tif (kol[s[x] - 'a'] > 0) return false;\n\t\tkol[s[x] - 'a']++;\n\t}\t\n\treturn true;\n}\n\ninline bool try_kol(int l, int r, int p)\n{\n\tint len = (r - l + 1) / p;\n\treturn (gett(l, l + len) >= (r - l + 1 - len));\n}\n\ninline bool ison(int l, int r, char x)\n{\n\treturn (kol[x - 'a'][r + 1] > kol[x - 'a'][l]);\t\n}\n\ninline int query(int l, int r)\n{         \n\tif (checkno(l, r)) return -1;\n\tint len = (r - l + 1);\n\twhile (len > 1)\n\t{\n\t\tint p = mnp[len];\n\t\tif (try_kol(l, r, p)) return 1;\n\t\twhile ((len % p) == 0) len /= p;\n\t}\n\tif (lw[l] <= r) return 2;\n\tif (rw[r] >= l) return 2;\n\tif (check(l, r)) return 2;\n\tif (ison(l + 1, r, s[l])) return 3;\n\tif (ison(l, r - 1, s[r])) return 3;\n\tif (getmin(l, r) <= r) return 3;\t\n\treturn 4;\n}\n\nint main()\n{\n\tcin.sync_with_stdio(0); \n\tcin >> n >> s;\n\tmemset(mnp, -1, sizeof(mnp));\n\tfor (int i = 2; i <= n; i++)\n\t\tif (mnp[i] == -1)\n\t\t\tfor (int j = i; j <= n; j += i)\n\t\t\t\tif (mnp[j] == -1)\n\t\t\t\t\tmnp[j] = i;\n\tmemset(kol[0], 0, sizeof(kol[0]));\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfor (int x = 0; x < 26; x++) kol[x][i + 1] = kol[x][i];\n\t\tkol[s[i] - 'a'][i + 1]++;\n\t}\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tlw[i] = n + 1;\n\t\trw[i] = n + 1;\n\t}\n\tfunc(0, n);  \n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tif (lw[i] == n + 1) lw[i] = n;\n\t\telse lw[i] += (i - 1);  \n\t\tif (rw[i] == n + 1) rw[i] = -1;\n\t\telse rw[i] = (i - rw[i] + 1);\n\t}\n\tkasai();                                                                        \n\tinit();  \n\tcin >> q;\n\tfor (int i = 0; i < n; i++)\n\t\tif (i * i >= n)\n\t\t{\n\t\t\tlen = i + 3;\n\t\t\tbreak;\n\t\t}\n\tfor (int i = 0; i < q; i++)\n\t{\n\t\tint l, r;\n\t\tcin >> l >> r;\n\t\tl--, r--;\n\t\tcout << query(l, r) << \"\\n\";                       \n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1044",
    "index": "A",
    "title": "The Tower is Going Home",
    "statement": "On a chessboard with a width of $10^9$ and a height of $10^9$, the rows are numbered from bottom to top from $1$ to $10^9$, and the columns are numbered from left to right from $1$ to $10^9$. Therefore, for each cell of the chessboard you can assign the coordinates $(x,y)$, where $x$ is the column number and $y$ is the row number.\n\nEvery day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates $(1,1)$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the \\textbf{upper side} of the field (that is, in any cell that is in the row with number $10^9$).\n\nEverything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:\n\n- Vertical. Each of these is defined by one number $x$. Such spells create an infinite blocking line between the columns $x$ and $x+1$.\n- Horizontal. Each of these is defined by three numbers $x_1$, $x_2$, $y$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $y$ and in columns from $x_1$ to $x_2$ inclusive. The peculiarity of these spells is that it is \\textbf{impossible} for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.\n\n\\begin{center}\n{\\small An example of a chessboard.}\n\\end{center}\n\nLet's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $(r_0,c_0)$ into the cell $(r_1,c_1)$ only under the condition that $r_1 = r_0$ or $c_1 = c_0$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).\n\nFortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!",
    "tutorial": "Observation 1. If we remove all the horizontal spells, than the rook can move straightforward up to the upper side of the field. So the only purpose of removing the vertical spells is to reduce the number of horizontal spells to be removed. Observation 2. If we want to remove the $i$-th vertical spell, then we should also remove all such vertical spells $j$, that $x_j<x_i$. It is obvious, because when we delete a vertical spell, we suppose that the rook would be able to outflank some horizontal spells by getting at rows that have greater number than $x_i$. If there remains at least one vertical spell $j$, such that $x_j<x_i$, than we will never be able to move to the rows with number greater than $x_j$, including $x_i$. Let's find some observations about the horizontal spells: Let's assume that we deleted $i$ vertical spells. It means, that the rook can move freely left and right at columns between $1$ and $x_{i+1}$ inclusive. Let's say that our rook is on the row $y$. If there is at least one cell which is located at row $y$ at any column between $1$ and $x_{i+1}$, that there is no blocking segment on the top of it, then the rook can move to this cell and move upwards into the row $y+1$. It means that if there is at least one gap in the blocking segments in row $y$ and in columns between $1$ and $x_{i+1}$ incluse, then there is no need to remove any of horizontal spells in the row. Observation 3. We care only about such horizontal spells, in which $x_1=1$. We have already proved, that we only care about such rows, that there are no gaps in blocking segments in them. If there is no such horizontal spell with $x_1 = 1$, it means that there is a gap in the row at column $1$. If there is such horizontal spell, then if there are more spells in that row, there would be a gap between any pair of neighbouring segments. Since we only care only about segments with $x_1 = 1$ and it is guaranteed that no horizontal segments share a common point, it means that we might not care about the $y$ of any horizontal spell, because there is no such pair of segments that both $x_1$ and $y$ of these are equal. So now while reading the descriptions of the horizontal spells, if the $x_1$ of $i$-th horizontal spell is not equal to $1$, we can ignore it. Otherwise, we add $x_2$ to some array. Now we can sort the array of $x_2$-s, and solve the task using the two-pointer technique. Here is the final algorithm: Add fake vertical spell with $x=10^9$. Sort all the vertical spells in ascending order. While reading the descriptions of the horizontal spells, we ignore ones with $x_1$ not equal to $1$. In other case, we add $x_2$ to the array. Sort the array of $x_2$-s in ascending order. Now we use the two pointer technique in the following way: we iterate $i$ from 0 to n - the number of vertical spells to be deleted and on each step we advance the pointer while the $x_2$ at which the pointer points is less then $x$ of the $(i+1)$-th vertical spell. Let's denote the position of the pointer as $p$. The number of horizontal spells, that we need to remove with $i$ vertical spells removed is $m-p+1$. Let's define the position of the pointer at $i$-th step as $p_i$. The answer to the problem in minival value of $i + m - p_i + 1$ among all $i$ from $0$ to $n$. Overall complexity $O(n \\log n + m \\log m)$",
    "tags": [
      "binary search",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1044",
    "index": "B",
    "title": "Intersecting Subtrees",
    "statement": "You are playing a strange game with Li Chen. You have a tree with $n$ nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you \\textbf{independently} labeled the vertices from $1$ to $n$. Neither of you know the other's labelling of the tree.\n\nYou and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled $x_1, x_2, \\ldots, x_{k_1}$ in \\textbf{your labeling}, Li Chen's subtree consists of the vertices labeled $y_1, y_2, \\ldots, y_{k_2}$ in \\textbf{his labeling}. The values of $x_1, x_2, \\ldots, x_{k_1}$ and $y_1, y_2, \\ldots, y_{k_2}$ are known to both of you.\n\n\\begin{center}\n{\\small The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes.}\n\\end{center}\n\nYou want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most $5$ questions, each of which is in one of the following two forms:\n\n- A x: Andrew will look at vertex $x$ in your labeling and tell you the number of this vertex in Li Chen's labeling.\n- B y: Andrew will look at vertex $y$ in Li Chen's labeling and tell you the number of this vertex in your labeling.\n\nDetermine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.",
    "tutorial": "I'll split this into two parts, first is the solution, second is why it works. The intended solution only uses two questions. Choose an arbitrary $y_j$, and ask \"B y_j\". Let the response be $R$. Find a node $x_i$ that is the closest to node $R$. This can be done with a BFS or DFS. Ask \"A x_i\". Let the response be $Q$. If $Q$ is one of $y_1,y_2,\\ldots,y_{k_2}$, print \"C x_i\", otherwise, print \"C -1\". Here is why it works. Let's use the fact that if the two subtrees don't intersect, there is an edge in the tree such that if we cut the tree on this edge, it will split it into two components, each containing one of the subtrees. Suppose we did step 1 and we have $R$. Let's root our tree at $R$. There is a unique node $x_i$ that has lowest depth in this tree which we can find (given that $x_1,x_2,\\ldots,x_{k_1}$ form a subtree). Now, we claim that the two subtrees intersect if and only if Li Chen owns a node that lies in the subtree rooted by $x_i$ (and in particular, we will show it is sufficient to only check node $x_i$). If none of Li Chen's nodes lie in the subtree rooted by $x_i$, then the edge $x_i$ to its parent cuts the tree into two components with one subtree completely lying in one component and the other in the second, so the two subtrees are disjoint. Otherwise, there is a node $W$ that is in Li Chen's subtree that lies in the subtree rooted by $x_i$. All nodes in the path of $R$ to $W$ must also belong to Li Chen's subtree, and in particular this includes node $x_i$, so the two trees intersect. This also shows we can just check if $x_i$ belongs in Li Chen's subtree by asking a question about it.",
    "tags": [
      "dfs and similar",
      "interactive",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1044",
    "index": "C",
    "title": "Optimal Polygon Perimeter",
    "statement": "You are given $n$ points on the plane. The polygon formed from all the $n$ points is \\textbf{strictly convex}, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $1$ to $n$, in clockwise order.\n\nWe define the distance between two points $p_1 = (x_1, y_1)$ and $p_2 = (x_2, y_2)$ as their Manhattan distance: $$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$\n\nFurthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as $p_1, p_2, \\ldots, p_k$ $(k \\geq 3)$, then the perimeter of the polygon is $d(p_1, p_2) + d(p_2, p_3) + \\ldots + d(p_k, p_1)$.\n\nFor some parameter $k$, let's consider all the polygons that can be formed from the given set of points, having \\textbf{any} $k$ vertices, such that the polygon is \\textbf{not} self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define $f(k)$ to be the maximal perimeter.\n\nPlease note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:\n\nIn the middle polygon, the order of points ($p_1, p_3, p_2, p_4$) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is ($p_1, p_2, p_3, p_4$), which is the left polygon.\n\nYour task is to compute $f(3), f(4), \\ldots, f(n)$. In other words, find the maximum possible perimeter for each possible number of points (i.e. $3$ to $n$).",
    "tutorial": "I will show 2 solutions, both of which work in $\\mathcal{O}(n)$ time. First, it is not hard to notice that we can only consider polygons that are convex. Observation: For a convex polygon, the given definition of \"polygon perimeter\" is equivalent to the perimeter of the bounding rectangle (aligned with the axis), of our polygon. If we look at some convex polygon, and 4 values $max_x, min_x, max_y, min_y$ representing the maximal $x$ coordinate of a point, minimal $x$, maximal and minimal $y$, then the perimeter of the bounding rectangle is simply $2 * (max_x - min_x + max_y - min_y)$. This simple rephrase gives us a bonus, and crucial observation: It is enough for us to take 4 points from the input, such that the perimeter of their polygon is the maximal possible (and is equal to the perimeter of the polygon formed from $n$ points). We will consider these the extreme points. Note that after taking the extreme points, it does not matter which other points we take. So, this solves all $f(4), \\ldots, f(n)$. We are left with $f(3)$ to compute (maximal triangle perimeter). Following are 2 solutions to do it: Solution 1: Let's show that the optimal triangle uses at least 2 of the extreme points. Imagine some optimal triangle, and its bounding rectangle. Notice that since each edge of the bounding rectangle must touch some vertex of the triangle (it is bounding after all), and we have 4 edges and 3 vertices, then there must be some vertex of the triangle that touches 2 edges of the rectangle (so it coincides with a rectangle vertex). If this is the case, we know that in comparison with the 2 other vertices, this vertex has \"extremal\" X and Y coordinates (minimal/maximal X, and minimal/maximal Y). Without loss of generality, assume this vertex has maximum X and Y. Then to optimize the perimeter, the other two vertices should have smallest possible X and smallest possible Y. We can pick these 2 vertices to be 2 of the extreme points (one with minimal X and one with minimal Y). So, this shows we just need to iterate over every adjacent pair of extreme vertices, and over all other points as the last vertex. This takes $\\mathcal{O}(n)$. Solution 2: This solution is more general, and is an extension of the problem to find the 2 most distant points (manhattan distance). The triangle perimeter is an expression with 6 terms: $|x_1 - x_2| + |y_1 - y_2| + \\ldots + |y_3 - y_1|$. We wish the maximize this expression, but the absolute value is troubling us. For each term, there are 2 cases: either it is positive, so the absolute value does nothing, or it is negative, so the absolute value negates it. In total, for the 6 terms we have $2^6 = 64$ options to place signs between them. We will call such option a setting. For any setting, the advantage now is that we can accumulate terms: For example the setting $++---+$, evaluates the expression to: $(2x_1 + 0y_1) + (-2x_2 - 2y_2) + (0x_3 + 2y_3)$ We solve every setting by its own, and over all settings we take the maximal answer. Please note, that this strategy only works to find the maximal value of the expression, not minimal. The proof of this is left as an exercise to the reader :) (I promise it is not difficult). Given 6 constants $c_1, c_2, ..., c_6$, we want to find 3 indicies $i < j < k$ to maximize: $c_1 * x_i + c_2 * y_i + ... + c_6 * y_k$. We define 3 arrays: $P_i = c_1 \\cdot x_i + c_2 \\cdot y_i$ $Q_i = c_3 \\cdot x_i + c_4 \\cdot y_i$ $R_i = c_5 \\cdot x_i + c_6 \\cdot y_i$ So this whole solution is $\\mathcal{O}(n)$, with a constant of 64. In general, to compute $f(k)$ this solution takes $\\mathcal{O}(n \\cdot 4^k \\cdot k)$ time, without any observations.",
    "tags": [
      "dp",
      "geometry"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1044",
    "index": "D",
    "title": "Deduction Queries",
    "statement": "There is an array $a$ of $2^{30}$ integers, indexed from $0$ to $2^{30}-1$. Initially, you know that $0 \\leq a_i < 2^{30}$ ($0 \\leq i < 2^{30}$), but you do not know any of the values. Your task is to process queries of two types:\n\n- 1 l r x: You are informed that the \\textbf{bitwise xor} of the subarray $[l, r]$ (ends inclusive) is equal to $x$. That is, $a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_{r-1} \\oplus a_r = x$, where $\\oplus$ is the bitwise xor operator. In some cases, the received update contradicts past updates. In this case, you should \\textbf{ignore} the contradicting update (the current update).\n- 2 l r: You are asked to output the bitwise xor of the subarray $[l, r]$ (ends inclusive). If it is still impossible to know this value, considering all past updates, then output $-1$.\n\nNote that the queries are \\textbf{encoded}. That is, you need to write an \\textbf{online} solution.",
    "tutorial": "First, let's learn how to handle information we have not recieved in updates. Let the function $W(l, r)$ be equal to the xor of the subarray $[l, r]$. Also, we define $W(l, r) = W(r, l)$. Assume 3 indicies $a \\leq b \\leq c$. There are 2 rules: $W(a, b) \\oplus W(b + 1, c) = W(a, c)$. $W(a, c) \\oplus W(b, c) = W(a, b - 1)$ (holds when $a < b$). These rules require a lot of conditions (and also plenty of $\\pm$ 1). We can simplify them greatly: Let's index the borders between cells in our array (there are $2^{30} + 1$ of them). Now, instead of defining a subarray $[l, r]$ by its 2 endpoint cells, we will define a subarray by its 2 endpoint borders. Technically it just means, that we should increase $r$ by 1, and then we get the 2 end borders. From now I will assume that our input is given in such a way, that subarrays are defined by their borders (So I will not mention the addition of 1 to $r$). Notice that the function $W(l, r)$ is also affected by this. If we take a look at our rules again, they boil down to just 1 rule: $W(a, b) \\oplus W(b, c) = W(a, c)$, for any 3 indicies $a,b,c$ ($a \\leq b \\leq c$ doesn't need to hold now, for instance $W(3, 5) \\oplus W(5, 2) = W(3, 2)$). This transformation also shows an observation; Assume every border is a vertex in a graph, and every update $W(l, r) = x$ describes an undirected edge between the vertices $l, r$ with weight $x$. We let the distance between 2 nodes $a, b$ be the xor of edge weights on the path between them. Notice that this distance is equal to $W(a, b)$. In other words, an update adds an edge and a query asks for some distance. Another observation is that, we do not care about all the $2^{30} + 1$ nodes, but only about the ones we recieved in queries and updates. Moreover, their order is irrelevant, so we can do an online mapping of new nodes to the next free indicies. Thus, the number of nodes will be worstcase $\\mathcal{O}(q)$. Claim: We can know the answer to some query $[l, r]$, if and only if there exists a path between the nodes $l, r$ (they are in the same connected component). //start spoiler of proof There will be some subset of edges we take, to form the xor between nodes $l$ and $r$. Assume every vertex has 2 states, on/off. Initially all vertices are off, and our current answer is $0$. When we take an edge we flip the state of its 2 ends, and xor our answer by its weight. Suppose at some moment of time the nodes with \"on\" state are {$x_0, x_1, x_2, ..., x_k$} (in sorted order). Observe that our current answer is equal to $W(x_0, x_1) \\oplus W(x_2, x_3) \\oplus \\ldots \\oplus W(x_{k-1}, x_k)$. This implies we want our subset of edges to end up having only the nodes {$l, r$} activated. We look at the connected components. Observe that in each connected component, the number of nodes activated at any time is even. If the nodes $l$ and $r$ are in different component, then in our final result we would want to have only 1 activated node in the component of $l$, and same with $r$, but this is impossible. //end spoiler of proof First, we need to know whether a query gives us 2 nodes that are in different components (to know whether the answer is $-1$ or not). For this we need to use the Union-Find structure. Also notice, that our Union-Find structure will only need to handle a forest of trees (if an update gives us an edge that creates a cycle, it means there is no contribution, so we ignore it). Provided that an answer does exist, we need to also handle finding a xor path between 2 nodes in a tree, and to support merging of trees. Generally to find a property over some path in a tree, it is common to use LCA or binary lifting. This turns out very difficult when we also need to merge trees (unless you insist on implementing Link-Cut/ETT). Fortunately, we can still abuse the xor operator. In some tree, mark $x_v$ as the xor of edges on the path from $v$ to some arbitrary root in the tree. The xor path between nodes ($u, v$) turns out to be $x_u \\oplus x_v$. So we would like to maintain for each tree some arbitrary root and all those values. Notice that we can augment our Union-Find structure to support this as well: For each node $v$ in the structure, we maintain $p_v$ as its parent in the structure, and $x_v$ as the xor on the path from $v$ to $p_v$. Notice that $x_v$ can be easily updated together with $p_v$ during the $find()$ operation in the structure. To summarize, when we are given $W(l, r) = x$ in some update, we transform it to $W(p_l, p_r) = x \\oplus x_l \\oplus x_r$, and then we add the edge between the parents. Finally, the complexity is $\\mathcal{O}(q \\log{q})$, but this is only due to the online mapping if we use a regular map; You can use a hash table and get a running time of $\\mathcal{O}(q \\times \\alpha(q))$, but I suggest being careful with a hash table (you may want to read this: https://codeforces.com/blog/entry/62393).",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1044",
    "index": "E",
    "title": "Grid Sort",
    "statement": "You are given an $n \\times m$ grid. Each grid cell is filled with a unique integer from $1$ to $nm$ so that each integer appears exactly once.\n\nIn one operation, you can choose an arbitrary cycle of the grid and move all integers along that cycle one space over. Here, a cycle is any sequence that satisfies the following conditions:\n\n- There are at least four squares.\n- Each square appears at most once.\n- Every pair of adjacent squares, and also the first and last squares, share an edge.\n\nFor example, if we had the following grid:\n\nWe can choose an arbitrary cycle like this one:\n\nTo get the following grid:\n\nIn this particular case, the chosen cycle can be represented as the sequence $[1, 2, 3, 6, 5, 8, 7, 4]$, the numbers are in the direction that we want to rotate them in.\n\nFind any sequence of operations to sort the grid so that the array created by concatenating the rows from the highest to the lowest is sorted (look at the first picture above).\n\nNote you do not need to minimize number of operations or sum of cycle lengths. The only constraint is that the sum of all cycles lengths must not be greater than $10^5$. We can show that an answer always exists under the given constraints. Output any valid sequence of moves that will sort the grid.",
    "tutorial": "The solution is more of a coding one than an algorithmic one. There are many different approaches, and it's important to be careful in how it is implemented. I'll explain one of the implementations. First, we can always move a particular block left, up, down, or right with an appropriate 2x2 square around it. Let's code some functions that let us do that for each direction. Next is to make sure that these moves don't mess up previous block spaces as we move blocks to the correct place. We can almost place blocks correctly in their spaces one by one in row major order, but there are some special cases. - We can do all blocks except the last two rows, which we'll handle separately (in paragraph below) - For each row, we can correctly place all blocks except the last one. The last one requires a bit more careful work, but is easy to handle if we have at least two free rows. For the last two rows, we can fill it in column by column from left to right. This is a similar startegy to fitting in the last column of the previous rows. We can almost do this except for the last 2x2 square. For the last 2x2 square, we can use the following sequence of moves to swap two blocks: Thus, we can shift the last block into the right position, then do at most three swaps (using the above sequence of moves) to fix the remaining blocks. The number of moves for this strategy can be computed and estimated to be about 50k in the worst case.",
    "tags": [
      "implementation"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1044",
    "index": "F",
    "title": "DFS",
    "statement": "Let $T$ be a tree on $n$ vertices. Consider a graph $G_0$, initially equal to $T$. You are given a sequence of $q$ updates, where the $i$-th update is given as a pair of two distinct integers $u_i$ and $v_i$.\n\nFor every $i$ from $1$ to $q$, we define the graph $G_i$ as follows:\n\n- If $G_{i-1}$ contains an edge $\\{u_i, v_i\\}$, then remove this edge to form $G_i$.\n- Otherwise, add this edge to $G_{i-1}$ to form $G_i$.\n\nFormally, $G_i := G_{i-1} \\triangle \\{\\{u_i, v_i\\}\\}$ where $\\triangle$ denotes the set symmetric difference.\n\nFurthermore, it is guaranteed that $T$ is always a subgraph of $G_i$. In other words, an update never removes an edge of $T$.\n\nConsider a connected graph $H$ and run a depth-first search on it. One can see that the tree edges (i.e. the edges leading to a not yet visited vertex at the time of traversal) form a spanning tree of the graph $H$. This spanning tree is not generally fixed for a particular graph — it depends on the starting vertex, and on the order in which the neighbors of each vertex are traversed.\n\nWe call vertex $w$ good if one can order the neighbors of each vertex in such a way that the depth-first search started from $w$ produces $T$ as the spanning tree. For every $i$ from $1$ to $q$, find and report the number of good vertices.",
    "tutorial": "Let's consider an arbitrary run of DFS producing some tree. Let's root the tree at the starting vertex. It can be shown that on a directed graph, there are only two types of edges. The first are the tree edges (those are the ones that are used to visit a new vertex). The second are edges which, upon being traversed, lead to a vertex that was already visited. It can be shown that, in the rooted tree, those edges always connect a vertex with one of its ancestors. In other words, all the edges that are dynamically added to the tree must connect a vertex with one of their ancestors. This means that the staring vertex must not lie on the path connecting the two endpoints of such edge, or any of the vertices in some of the subtrees. For instance, on the second sample, the edge $\\{2,4\\}$ disallows the vertex $1$ from being the starting vertex, as it lies on the path from $2$ to $4$, and also vertex $6$. Each edge thus forbids a certain set of vertices from being the starting point. This yields a straightforward $\\mathcal O(n^2)$ solution. To optimize it further, we can root the tree arbitrarily and renumber the vertices using their DFS visit times. When we do this, we notice that the set of a forbidden vertices for each edge is a union of at most three intervals of vertices. This lets us build an $\\mathcal O(n \\log n)$ solution using a segment tree. The operation is add a constant on interval, and then find the minimum on interval and the number of occurrences of said minimum. We add $1$ to forbid a vertex because of an edge, subtract $1$ to revert that when the edge is subsequently removed. The answer is the number of minimums on the whole tree if that minimum is $0$, and $0$ otherwise.",
    "tags": [
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1047",
    "index": "A",
    "title": "Little C Loves 3 I",
    "statement": "Little C loves number «3» very much. He loves all things about it.\n\nNow he has a positive integer $n$. He wants to split $n$ into $3$ positive integers $a,b,c$, such that $a+b+c=n$ and none of the $3$ integers is a multiple of $3$. Help him to find a solution.",
    "tutorial": "If $n - 2$ is not a multiple of $3$, $a = 1, b = 1, c = n - 2$ is OK. Otherwise, $a = 1, b = 2, c = n - 3$ is OK.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tif((n-2)%3)printf(\"1 1 %d\",n-2);\n\telse printf(\"1 2 %d\",n-3);\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1047",
    "index": "B",
    "title": "Cover Points",
    "statement": "There are $n$ points on the plane, $(x_1,y_1), (x_2,y_2), \\ldots, (x_n,y_n)$.\n\nYou need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.",
    "tutorial": "To cover a point $(x_{i}, y_{i})$, the length of the shorter side of the triangle should be at least $x_{i} + y_{i}$. So the answer is $max(x_{i} + y_{i})$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint n,x,y,ans=0;\n\tscanf(\"%d\",&n);\n\twhile(n--)scanf(\"%d%d\",&x,&y),ans=max(ans,x+y);\n\tprintf(\"%d\",ans);\n}",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1051",
    "index": "A",
    "title": "Vasya And Password",
    "statement": "Vasya came up with a password to register for EatForces — a string $s$. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.\n\nBut since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords \"abaCABA12\", \"Z7q\" and \"3R24m\" are valid, and the passwords \"qwerty\", \"qwerty12345\" and \"Password\" are not.\n\nA substring of string $s$ is a string $x = s_l s_{l + 1} \\dots s_{l + len - 1} (1 \\le l \\le |s|, 0 \\le len \\le |s| - l + 1)$. $len$ is the length of the substring. Note that the empty string is also considered a substring of $s$, it has the length $0$.\n\nVasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed \\textbf{exactly} once, and \\textbf{the chosen string should have the minimal possible length}.\n\n\\textbf{Note that the length of $s$ should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits.}",
    "tutorial": "There are just a few general cases in the task to consider: If the password $s$ is already valid, nothing has to be changed, just print $s$. Try to change exactly one character, iterate over all positions in $s$ and all three options for character (any digit, any lowercase or uppercase Latin letter). After the replacement the string is checked for the validity and printed if it turned out to be valid. We weren't able to replace a substring of length 0 or 1, then the answer is at least 2. We can obtain it in a following manner: replace the first two characters to \"a1\" if the third character is an uppercase Latin letter, to \"A1\" if the third character is a lowercase Latin letter and to \"aA\" if the third character is a digit.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring s;\n\nbool ok(string t){\n    int msk = 0;\n    \n    for(int i = 0; i < int(t.size()); ++i){\n\t    if(isupper(t[i])) msk |= 1;\n\t    if(islower(t[i])) msk |= 2;\n\t    if(isdigit(t[i])) msk |= 4;\n\t}\n\t\n\treturn msk == 7;\n}\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; ++i){\n    \tcin >> s;\n    \tif(ok(s)){\n    \t    cout << s << endl;\n    \t    continue;\n    \t}\n    \tbool fnd = false;\n        for(int i = 0; i < int(s.size()); ++i){\n            string t = s;\n            \n            t[i] = '1';\n            if(ok(t)){\n    \t        cout << t << endl;\n    \t        fnd = true;\n    \t        break;\n    \t    }\n            t[i] = 'a';\n            if(ok(t)){\n    \t        cout << t << endl;\n    \t        fnd = true;\n    \t        break;\n    \t    }\n    \t    t[i] = 'A';\n            if(ok(t)){\n    \t        cout << t << endl;\n    \t        fnd = true;\n    \t        break;\n    \t    }\n        }\n    \t\n    \tif(fnd) continue;\n    \t\n    \tif(isupper(s[2])){\n    \t    s[0] = 'a';\n    \t    s[1] = '1';\n    \t    cout << s << endl;\n    \t    continue;\n    \t}\n    \tif(islower(s[2])){\n    \t    s[0] = 'A';\n    \t    s[1] = '1';\n    \t    cout << s << endl;\n    \t    continue;\n    \t}\n    \tif(isdigit(s[2])){\n    \t    s[0] = 'a';\n    \t    s[1] = 'A';\n    \t    cout << s << endl;\n    \t    continue;\n    \t}\n\t}\n\treturn  0;\n}\n\n",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1051",
    "index": "B",
    "title": "Relatively Prime Pairs",
    "statement": "You are given a set of all integers from $l$ to $r$ inclusive, $l < r$, $(r - l + 1) \\le 3 \\cdot 10^5$ and $(r - l)$ is always odd.\n\nYou want to split these numbers into exactly $\\frac{r - l + 1}{2}$ pairs in such a way that for each pair $(i, j)$ the greatest common divisor of $i$ and $j$ is equal to $1$. Each number should appear in exactly one of the pairs.\n\nPrint the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.",
    "tutorial": "Numbers with the difference of $1$ are always relatively prime. That's the only thing I should mention for this editorial. Overall complexity: $O(r - l)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nint main() {\n\tlong long l, r;\n\tscanf(\"%lld%lld\", &l, &r);\n\tputs(\"YES\");\n\tforn(i, (r - l) / 2 + 1)\n\t\tprintf(\"%lld %lld\\n\", l + i * 2, l + i * 2 + 1);\n}\n",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1051",
    "index": "C",
    "title": "Vasya and Multisets",
    "statement": "Vasya has a multiset $s$ consisting of $n$ integer numbers. Vasya calls some number $x$ nice if it appears in the multiset exactly once. For example, multiset $\\{1, 1, 2, 3, 3, 3, 4\\}$ contains nice numbers $2$ and $4$.\n\nVasya wants to split multiset $s$ into two multisets $a$ and $b$ \\textbf{(one of which may be empty)} in such a way that the quantity of nice numbers in multiset $a$ would be the same as the quantity of nice numbers in multiset $b$ (the quantity of numbers to appear exactly once in multiset $a$ and the quantity of numbers to appear exactly once in multiset $b$).",
    "tutorial": "Write down all the numbers, which appear exactly once, let there be $k$ of them. If $k$ is even, put the first $\\frac{k}{2}$ of them into the first multiset and put the other $\\frac{k}{2}$ into the second multiset. All the other numbers (which appear more than once) also go into the first multiset. The only nice numbers will be the initial $k$, thus the answer is valid. If $k$ is odd and there is no number to appear more than twice, then the answer is \"NO\", as all the numbers to appear exactly twice don't change the difference of the amounts of the nice numbers at all. If there is a number to appear more than twice (let it be $x$), then let's firstly add $\\lceil \\frac{k}{2} \\rceil$ of the numbers to appear exactly once to the first multiset, add $\\lfloor \\frac{k}{2} \\rfloor$ others of them to the second multiset. Then the first occurrence of $x$ goes to the second multiset and all the other numbers go to the first multiset. It's easy to notice that multisets will contain equal number of the nice numbers after all the partitioning.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 109;\n\nint n;\nint a[N];\nmap<int, int> m;\nset <int> s[2];\n\nint main() {\n\tint n;\n\tcin >> n;\n\tfor(int i = 0; i < n; ++i){\n\t\tcin >> a[i];\n\t\tm[a[i]]++;\n\t}\n\n\tint pos = 0;\n\tfor(auto p : m)\n\t\tif(p.second == 1){\n\t\t\ts[pos].insert(p.first);\n\t\t\tpos = 1 - pos;\n\t\t}\n\t\t\n\tif(s[0].size() == s[1].size()){\n\t\tstring res(n, 'A');\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tif(s[1].count(a[i]))\n\t\t\t\tres[i] = 'B';\n\t\t\n\t\tcout << \"YES\" << endl;\n\t\tfor(auto c : res) cout << c;\n\t\tcout << endl;\n\t\treturn 0;\n\t}\n\telse{\n\t\tassert(int(s[0].size()) - 1 == int(s[1].size()));\n\t\tstring res(n, 'A');\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tif(s[1].count(a[i]))\n\t\t\t\tres[i] = 'B';\n\t\t\n\t\tint id = -1;\n\t\tfor(auto p : m)\n\t\t\tif(p.second >= 3){\n\t\t\t\tid = p.first;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\tif(id == -1){\n\t\t\tcout << \"NO\" << endl;\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tbool flag = false;\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tif(a[i] == id)\n\t\t\t\tif(!flag){\n\t\t\t\t\tflag = true;\n\t\t\t\t\tres[i] = 'B';\n\t\t\t\t}\n\t\t}\n\t\t\n\t\tcout << \"YES\" << endl;\n\t\tfor(auto c : res) cout << c;\n\t\tcout << endl;\n\t\treturn 0;\n\t}\n\treturn 0;\n}\n                             \t",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1051",
    "index": "D",
    "title": "Bicolorings",
    "statement": "You are given a grid, consisting of $2$ rows and $n$ columns. Each cell of this grid should be colored either black or white.\n\nTwo cells are considered neighbours if they have a \\textbf{common border} and share the same color. Two cells $A$ and $B$ belong to the same component if they are neighbours, or if there is a neighbour of $A$ that belongs to the same component with $B$.\n\nLet's call some bicoloring beautiful if it has exactly $k$ components.\n\nCount the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $998244353$.",
    "tutorial": "The problem is about counting the number of some combinatoric objects. Thus, dynamic programming is always the answer. Let $dp[i][j][mask]$ be the number of beautiful bicolorings of the first $i$ columns such that $j$ components are already created and can't be modified and the colors of the $i$-th column are determined by $mask$ (its first bit is the color of the lower cell and its second bit the color of the upper cell). Component can be modified if the cell from the $i$-th column belongs to it. The initial states are $dp[0][0][mask] = 1$ for each $mask = 0..3$ and $dp[i][j][mask] = 0$ for any other state. You should iterate over the possible $nmask$ for the next column and recalculate the number of components. You can easily show that the current number of components and the last column is actually enough to get the new number of components. In my code I have some function $get(mask, nmask)$ to determine the added number of components while transitioning from $mask$ to $nmask$. These are just the couple of cases to handle carefully. Then all the transitions are: $dp[i + 1][j + get(mask, nmask)][nmask]$ += $dp[i][j][mask]$. However, the last column won't contain the answer as it is, the number of components will be incorrect. Let's add some dummy column $n + 1$ equal to $mask \\oplus 3$ for each $mask$. This will add all the real component to the total number. So the answer is the sum of $dp[n][k - get(mask, mask \\oplus 3)][mask]$ over all $mask = 0..3$. Overall complexity: $O(n^2 \\cdot 4^m)$, where $m$ is the number of rows (2 for this problem).",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nconst int N = 1000 + 7;\nconst int MOD = 998244353;\n\nint dp[N][2 * N][4];\n\nint add(int a, int b){\n\treturn (a + b) % MOD;\n}\n\nbool full(int mask){\n\treturn (mask == 0 || mask == 3);\n}\n\nint get(int mask, int nmask){\n\tint cnt = __builtin_popcount(mask ^ nmask);\n\tif (cnt == 0) return 0;\n\tif (cnt == 2) return (full(mask) ? 1 : 2);\n\treturn (full(mask) ? 0 : 1);\n}\n\nint main() {\n\tint n, k;\n\tscanf(\"%d%d\", &n, &k);\n\tforn(i, 4)\n\t\tdp[1][0][i] = 1;\n\t\n\tfor (int i = 1; i < n; ++i){\n\t\tforn(j, k + 1){\n\t\t\tforn(mask, 4){\n\t\t\t\tforn(nmask, 4){\n\t\t\t\t\tdp[i + 1][j + get(mask, nmask)][nmask] = add(dp[i + 1][j + get(mask, nmask)][nmask], dp[i][j][mask]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\tforn(mask, 4){\n\t\tint nw = get(mask, mask ^ 3);\n\t\tif (k >= nw)\n\t\t\tans = add(ans, dp[n][k - nw][mask]);\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}        \t",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1051",
    "index": "E",
    "title": "Vasya and Big Integers",
    "statement": "Vasya owns three big integers — $a, l, r$. Let's define a partition of $x$ such a sequence of strings $s_1, s_2, \\dots, s_k$ that $s_1 + s_2 + \\dots + s_k = x$, where $+$ is a concatanation of strings. $s_i$ is the $i$-th element of the partition. For example, number $12345$ has the following partitions: [\"1\", \"2\", \"3\", \"4\", \"5\"], [\"123\", \"4\", \"5\"], [\"1\", \"2345\"], [\"12345\"] and lots of others.\n\nLet's call some partition of $a$ beautiful if each of its elements \\textbf{contains no leading zeros}.\n\nVasya want to know the number of beautiful partitions of number $a$, which has each of $s_i$ satisfy the condition $l \\le s_i \\le r$. Note that the comparison is the integer comparison, not the string one.\n\nHelp Vasya to count the amount of partitions of number $a$ such that they match all the given requirements. The result can be rather big, so print it modulo $998244353$.",
    "tutorial": "Let's use dynamic programming to solve the problem. Let $dp_x$ be the number of correct partitions for the long integer $a_x a_{x+1} \\dots a_{n}$. It's easy to see that if we have two big integers without leading zeroes, we know the lengths of these integers, and these lengths are not equal, then we can determine which integer is greater in $O(1)$. We will calculate the answers in the following order: $dp_{|a|}, dp_{|a| - 1} \\dots dp_1$. Suppose we want to calculate $dp_x$. Let $L$ be the minimum position such that the number $a_x a_x+1 \\dots a_L$ meets the following condition: $l \\le a_x a_x+1 \\dots a_L \\le r$. Let $R$ be the maximum position such that the number $a_x a_x+1 \\dots a_R$ meets the following condition $l \\le a_x a_x+1 \\dots a_R \\le r$. Initially let's consider $L = x + |l|$ and $R = x + |r|$. $L$ will be less if $a_x a_{x + 1} ... a_{x + |l|} < l$. $R$ will be less if $a_x a_{x + 1} ... a_{x + |r|} > r$. To determine which of the numbers $a_x a_{x + 1} ... a_{x + |l|}$ and $l$ is greater let's calculate z-function for the string $l + \\# + a$, where $\\#$ is any character that doesn't occur in $a$ and $l$. After calculating z-function we can easily find the first non-equal character in $a_x a_{x + 1} ... a_{x + |l|}$ and $l$, and this character will determine which number is greater. To compare $a_x a_{x + 1} ... a_{x + |r|}$ and $r$ we can act the same. All that's left is to set $dp_x$ to the sum of $dp$ values from $L$ to $R$. This can be done by maintaining suffix sums. There is a corner case, which applies when $a_x = 0$. If $l > 0$, then $dp_x = 0$ because we cannot afford any leading zeroes. Otherwise $dp_x = dp_{x + 1}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) (int)(a.size())\n\nconst int N = int(1e6) + 9;\nconst int MOD = 998244353;\n\nint n;\nstring s, l, r;\nint dp[N];\nint sumDP[N];\n\nint sum(int a, int b){\n\ta += b;\n\tif(a >= MOD) a -= MOD;\n\treturn a;\n}\n\nvector <int> z_function(string s){\n\tint n = sz(s);\n\tvector <int> z(n);\n\tfor(int i = 1, l = 0, r = 0; i < n; ++i){\n\t\tif(i <= r)\n\t\t\tz[i] = min(r - i + 1, z[i - l]);\n\t\twhile(i + z[i] < n && s[z[i]] == s[i + z[i]])\n\t\t\t++z[i];\n\t\tif(i + z[i] - 1 > r)\n\t\t\tl = i,  r = i + z[i] - 1;\n\t}\n\treturn z;\n}\n\n//s[pos..] ? t\nchar cmp(vector <int> &zf, string &t, int pos){\n\tint len = sz(t);\n\tassert(pos + len + 1 < sz(zf));\n\tif(sz(s) - pos < len) return '<';\n\t\n\tint x = zf[len + 1 + pos];\n\tassert(x <= len);\n\tif(x == len) return '=';\n\tassert(pos + x < sz(s));\n\tassert(s[pos + x] != t[x]);\n\tif(s[pos + x] < t[x]) return '<';\n\treturn '>';\n}\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t\n\tios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n\tcin >> s >> l >> r;\n\tn = int(s.size());\n\tvector <int> zl = z_function(l + \"#\" + s);\n\tvector <int> zr = z_function(r + \"#\" + s);\n\t\n\tsumDP[n] = dp[n] = 1;\n\tfor(int i = n - 1; i >= 0; --i){\n\t\tif(s[i] == '0'){\n\t\t\tif(l == \"0\") dp[i] = dp[i + 1];\t\t\n\t\t\telse dp[i] = 0;\n\t\t\tsumDP[i] = sum(dp[i], sumDP[i + 1]);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tint L = sz(l) + i;\n\t\tchar cl = cmp(zl, l, i);\n\t\tif(cl == '<') ++L;\n\t\t\n\t\tint R = sz(r) + i;\n\t\tchar cr = cmp(zr, r, i);\n\t\tif(cr == '>') --R;\n\n\t \tint cur = 0;\n\t \tif(L <= R && L <= n){\n\t \t\tR = min(R, n);\n\t \t\tcur = sumDP[L];\n\t \t\tif(R != n) cur = sum(cur, MOD - sumDP[R + 1]);\n\t \t}\n\t \tdp[i] = cur;\n\t \tsumDP[i] = sum(dp[i], sumDP[i + 1]);\n\t}\n\t\n\tcout << dp[0] << endl;\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "hashing",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1051",
    "index": "F",
    "title": "The Shortest Statement",
    "statement": "You are given a weighed undirected \\textbf{connected} graph, consisting of $n$ vertices and $m$ edges.\n\nYou should answer $q$ queries, the $i$-th query is to find the shortest distance between vertices $u_i$ and $v_i$.",
    "tutorial": "Firstly let's find any spanning tree and root it at any vertex. For each vertex we calculate the distance to the root (let it be $h_v$ for vertex $v$). There are no more than $21$ edges that don't belong to the tree. For each of these edges, let's run Dijkstra's algorithm from some vertex incident to this edge. Suppose we are answering a query $u$ $v$. If the shortest path between these vertices passes only along the edges of the tree, then it can be calculated by the formula $h_v + h_u - 2h_{lca(u, v)}$, where $lca(u, v)$ is the lowest common ancestor of vertices $u$ and $v$. You may use any fast enough algorithm you know to calculate $lca(u, v)$. Otherwise there exists at least one vertex such that we ran Dijkstra's algorithm from it, and it belongs to the shortest path. Just iterate on every vertex for which we ran Dijkstra and update the answer with the value of $d_u + d_v$, where $d_x$ is the shortest path to the vertex $x$ from the fixed vertex.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300 * 1000 + 9;\nconst int LOGN = 19;\nconst int M = 21;\nconst long long INF64 = 1e18;\n\nint n, m, q;\nvector <pair<int, int> > g[N];\nint p[LOGN][N];\nint tin[N], tout[N], T;\nlong long h[N];\nset <pair<int, int> > badEdges;\nlong long d[M + M][N];\nbool u[N];\n\nvoid dfs(int v, int pr){\n\ttin[v] = T++;\n\tp[0][v] = pr;\n\tu[v] = true;\n\tfor(int i = 1; i < LOGN; ++i)\n\t\tp[i][v] = p[i - 1][ p[i - 1][v] ];\n\t\t\n\tfor(auto e : g[v]){\n\t\tint to = e.first, len = e.second;\n\t\tif(!u[to]){\n\t\t\th[to] = h[v] + len;\n\t\t\tdfs(to, v);\n\t\t\t\n\t\t\tif(v < to)\n\t\t\t\tbadEdges.erase(make_pair(v, to));\n\t\t\telse\n\t\t\t\tbadEdges.erase(make_pair(to, v));\t\t\t\n\t\t}\n\t}\t\n\t\t\n\ttout[v] = T;\n}\n\nbool isAncestor(int a, int b){\n\treturn tin[a] <= tin[b] && tout[a] >= tout[b];\n}\n\nint getLCA(int a, int b){\n\tif(isAncestor(a, b)) return a;\n\tif(isAncestor(b, a)) return b;\n\t\n\tfor(int i = LOGN - 1; i >= 0; --i)\n\t\tif(!isAncestor(p[i][a], b))\n\t\t\ta = p[i][a];\n\t\n\treturn p[0][a];\n}\n\nvoid dij(int st, long long d[N]){\n\tset<pair<long long, int> > q;\n\tfor(int i = 0; i < n; ++i) d[i] = INF64;\n\td[st] = 0;\n\tq.insert(make_pair(d[st], st));\n\t\n\twhile(!q.empty()){\n\t\tint v = q.begin()->second;\n\t\tq.erase(q.begin());\n\t\t\n\t\tfor(auto e : g[v]){\n\t\t\tint to = e.first, len = e.second;\n\t\t\tif(d[to] > d[v] + len){\n\t\t\t\tq.erase(make_pair(d[to], to));\n\t\t\t\td[to] = d[v] + len;\n\t\t\t\tq.insert(make_pair(d[to], to));\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t\n\tscanf(\"%d %d\", &n, &m);\n    for(int i = 0; i < m; ++i){\n    \tint u, v, w;\n    \tscanf(\"%d %d %d\", &u, &v, &w);\n    \t--u, --v;\n    \tg[u].push_back(make_pair(v, w));\n       \tg[v].push_back(make_pair(u, w));\n    }\n\t\n    for(int v = 0; v < n; ++v)\n    \tfor(auto e : g[v])\n    \t\tif(v < e.first)\n    \t\t\tbadEdges.insert(make_pair(v, e.first));\n\n    dfs(0, 0);\n\n    int cpos = 0;\n    for(auto e : badEdges)\n    \tdij(e.first, d[cpos++]);\n    scanf(\"%d\", &q);\n    for(int tc = 0; tc < q; ++tc){\n    \tint u, v;\n    \tscanf(\"%d %d\", &u, &v);\n    \t--u, --v;\n    \tint lca = getLCA(u, v);\n    \tlong long ans = h[u] + h[v] - 2 * h[lca];\n    \tfor(int i = 0; i < badEdges.size(); ++i)\n    \t\tans = min(ans, d[i][u] + d[i][v]);\n    \t\t\n    \tprintf(\"%lld\\n\", ans);\n    }\t\n    return 0;\n}",
    "tags": [
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1051",
    "index": "G",
    "title": "Distinctification",
    "statement": "Suppose you are given a sequence $S$ of $k$ pairs of integers $(a_1, b_1), (a_2, b_2), \\dots, (a_k, b_k)$.\n\nYou can perform the following operations on it:\n\n- Choose some position $i$ and \\textbf{increase} $a_i$ by $1$. That can be performed only if there exists at least one such position $j$ that $i \\ne j$ and $a_i = a_j$. The cost of this operation is $b_i$;\n- Choose some position $i$ and \\textbf{decrease} $a_i$ by $1$. That can be performed only if there exists at least one such position $j$ that $a_i = a_j + 1$. The cost of this operation is $-b_i$.\n\nEach operation can be performed arbitrary number of times (possibly zero).\n\nLet $f(S)$ be minimum possible $x$ such that there exists a sequence of operations with total cost $x$, after which all $a_i$ from $S$ are pairwise distinct.\n\nNow for the task itself ...\n\nYou are given a sequence $P$ consisting of $n$ pairs of integers $(a_1, b_1), (a_2, b_2), \\dots, (a_n, b_n)$. All $b_i$ are pairwise distinct. Let $P_i$ be the sequence consisting of the first $i$ pairs of $P$. Your task is to calculate the values of $f(P_1), f(P_2), \\dots, f(P_n)$.",
    "tutorial": "Let's firstly try to come up with some naive solution. Suppose we have a list $S$ and want to calculate $f(S)$ for it. Let's sort this list, comparing the pairs by their values of $a_i$, and then process them one-by-one. We will divide this list into some parts (we will call them components) with the following process: when processing the first pair in the sorted order, let's iterate on the next pairs (also in the sorted order) and add them to the first pair's component until the following condition is met: $a_y - a_x > y - x$, where $x$ is the index of the first pair we added, and $y$ is the index of the pair we are currently trying to add to $x$'s component (remember that we consider all these pairs in the sorted order). What is the meaning of this condition? $a_y - a_x \\le y - x$ means that the number of pairs between $x$ and $y$ (including these two) is not less that the number of integers in $[a_x, a_y]$ - and while this condition is met, we can use the first operation in order to make a pair having $a_i = z$ for every $z \\in [x, y]$. And the first time when the condition $a_y - a_x > y - x$ is met, we obviously cannot \"expand\" the segment in such a way. It means that the $a$-value of $y$ will always be greater than $a$-value of $x$, and $y$ won't belong to the same component with $x$ (and will start creating its own component instead). These components we form have one special property. Suppose we \"expanded\" the component so that there are no two equal values of $a_i$ in it. Then we may reorder the pairs in this component as we wish (to do so, we may \"contract\" the component using the second operation, and then \"expand\" it again). Of course, the best course of action is to sort the pairs in the component by their values of $b_i$ in descending order. After doing this for every component, we will obtain an optimal configuration such that all values of $a_i$ are distinct, and it's easy to calculate the answer. Okay, now we need to do it fast. The following will help us: DSU; Some implicit logarithmic data structure (the operations we need are \"count the sum of elements less than $x$\" and \"count the number of elements greater than $y$\"; your implementation might use other operations); Small-to-large merging. DSU will help us maintain the components. A data structre will be built for each component containing the values of $b_i$ in it; it will help us to maintain the sum of $opt(i) b_i$, where $opt(i)$ is the optimal index of $b_i$ in this component. Depending on your implementation, you may or may not need to store the minimum value of $a_i$ in the component. When inserting some element having $b_i = b$ into some component, the elements having $b_i > b$ don't change their position, the new element will be added right after them, and the remaining elements will be shifted to the right; so the sum of $opt(i) b_i$ can be maintained if we query the number of elements greater than $b$ and the sum of elements less than $b$. Okay, but we still don't know how we create the components and how we determine if two components are to merge. We will keep these components in \"expanded\" form; that is, when processing a pair $(a_i, b_i)$, let's find the leftmost unoccupied position after $a_i$ (or $a_i$, if it is not occupied) and occupy it with the new pair, creating a new component for it. If the newly occupied index is $pos$, let's try to merge new component with components occupying $pos - 1$ and $pos + 1$ (if there are any); to merge two components, do the required operations in DSU and unite the data structures built in these components with small-to-large method. All this works in $O(n \\log^2 n)$, the most time-consuming part is merging the data structures.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n\ntypedef long long li;\n\nmt19937 rnd(time(NULL));\n\nstruct node\n{\n\tint x;\n\tint y;\n\tli sum;\n\tint siz;\n\tnode* l;\n\tnode* r;\n\tnode() {};\n\tnode(int x, int y, li sum, int siz, node* l, node* r) : x(x), y(y), sum(sum), siz(siz), l(l), r(r) {};\n};\n\ntypedef node* treap;\ntypedef pair<treap, treap> ptt;\n\nint getSiz(treap t)\n{\n\treturn (t ? t->siz : 0);\n}\n\nli getSum(treap t)\n{\n\treturn (t ? t->sum : 0);\n}\n\ntreap fix(treap t)\n{\n\tif(!t) return t;\n\tt->sum = getSum(t->l) + t->x + getSum(t->r);\n\tt->siz = getSiz(t->l) + 1 + getSiz(t->r);\n\treturn t;\n}\n\nptt split(treap t, int l)\n{\n\tt = fix(t);\n\tif(!t) return make_pair(t, t);\n\tif(t->x < l)\n\t{\n\t\tauto z = split(t->r, l);\n\t\tt->r = z.x;\n\t\treturn make_pair(fix(t), z.y);\n\t}\n\telse\n\t{\n\t\tauto z = split(t->l, l);\n\t\tt->l = z.y;\n\t\treturn make_pair(z.x, fix(t));\n\t}\n}\n\ntreap merge(treap a, treap b)\n{\n\ta = fix(a);\n\tb = fix(b);\n\tif(!a) return b;\n\tif(!b) return a;\n\tif(a->y > b->y)\n\t{\n\t\ta->r = merge(a->r, b);\n\t\treturn fix(a);\n\t}\n\telse\n\t{\n\t\tb->l = merge(a, b->l);\n\t\treturn fix(b);\n\t}\n}\n\nstruct comp\n{\n\tli cur_sum;\n\tint beg;\n\tli treap_sum;\n\ttreap t;\n\t\n\tvoid upd()\n\t{\n\t\tcur_sum = treap_sum + beg * 1ll * getSum(t);\n\t}\n\t\n\tvoid insert(int bi)\n\t{\n\t\tptt p = split(t, bi);\n\t\ttreap_sum += getSum(p.x) + getSiz(p.y) * 1ll * bi;\n\t\tt = merge(p.x, merge(new node(bi, rnd(), bi, 1, NULL, NULL), p.y));\n\t\tupd();\n\t}\n\t\n\tvoid fill_treap(treap t)\n\t{\n\t\tif(!t) return;\n\t\tinsert(t->x);\n\t\tfill_treap(t->l);\n\t\tfill_treap(t->r);\n\t}\n};\n\ncomp merge(comp a, comp b)\n{\n\tif(getSiz(a.t) < getSiz(b.t))\n\t\tswap(a, b);\n\ta.beg = min(a.beg, b.beg);\n\ta.fill_treap(b.t);\n\tdelete b.t;\n\ta.upd();\n\treturn a;\n}\n\nset<int> free_pos;\n\nconst int N = 400043;\n\nint p[N];\nint siz[N];\ncomp cc[N];\n\nli start_sum = 0;\nli end_sum = 0;\n\nint get(int x)\n{\n\treturn (p[x] == x ? x : (p[x] = get(p[x])));\n}\n\nvoid merge(int x, int y)\n{\n\tx = get(x);\n\ty = get(y);\n\tif(x == y) return;\n\tif(siz[x] < siz[y]) swap(x, y);\n\tend_sum -= cc[x].cur_sum;\n\tend_sum -= cc[y].cur_sum;\n\tp[y] = x;\n\tsiz[x] += siz[y];\n\tcc[x] = merge(cc[x], cc[y]);\n\tend_sum += cc[x].cur_sum;\n}\n\nvoid process(int ai, int bi)\n{\n\tstart_sum += ai * 1ll * bi;\n\tint pos = *free_pos.lower_bound(ai);\n\tfree_pos.erase(pos);\n\tsiz[pos] = 1;\n\tp[pos] = pos;\n\tcc[pos].beg = pos;\n\tcc[pos].insert(bi);\n\tend_sum += cc[pos].cur_sum;\n\tif(!free_pos.count(pos - 1))\n\t\tmerge(pos, pos - 1);\n\tif(!free_pos.count(pos + 1))\n\t\tmerge(pos, pos + 1);\n\tprintf(\"%lld\\n\", end_sum - start_sum);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n    int n;\n    scanf(\"%d\", &n);\n  \tfor(int i = 0; i < N; i++)\n  \t\tfree_pos.insert(i);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint a, b;\n\t\tscanf(\"%d %d\", &a, &b);\n\t\tprocess(a, b);\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1053",
    "index": "E",
    "title": "Euler tour",
    "statement": "Euler is a little, cute squirrel. When the autumn comes, he collects some reserves for winter. The interesting fact is that Euler likes to collect acorns in a specific way. A tree can be described as $n$ acorns connected by $n - 1$ branches, such that there is exactly one way between each pair of acorns. Let's enumerate the acorns from $1$ to $n$.\n\nThe squirrel chooses one acorn (not necessary with number $1$) as a start, and visits them in a way called \"Euler tour\" (see notes), collecting each acorn when he visits it for the last time.\n\nToday morning Kate was observing Euler. She took a sheet of paper and wrote down consecutive indices of acorns on his path. Unfortunately, during her way to home it started raining and some of numbers became illegible. Now the girl is very sad, because she has to present the observations to her teacher.\n\n\"Maybe if I guess the lacking numbers, I'll be able to do it!\" she thought. Help her and restore any valid Euler tour of some tree or tell that she must have made a mistake.",
    "tutorial": "First let's try to find some conditions whether it is possible to recover correct euler tour. Of course for every euler tour $a_i$ $\\neq$ $a_{i+1}$ and $a_1$ $=$ $a_{2n-1}$ (because we start and finish in root). Moreover if there exist four index $i_1$ $<$ $i_2$ $<$ $i_3$ $<$ $i_4$ such that $a_{i_1}$ $=$ $a_{i_3}$ and $a_{i_2}$ $=$ $a_{i_4}$ and $a_{i_1}$ $\\neq$ $a_{i_2}$ than answer is $NO$ (because vertex is an ancestor of another o there is no relation between them). There is one more tricky condition - parity of positions of all occurences of element $x$ is the same. Also, between two equal elements with distance $2k$ there can be at most $k$ distinct elements. It turns out that those conditions are sufficient - we will prove it by constructing an answer. So first let's observe that if we have to equal elements it means that there is subtree between them - we can solve it independently from the rest of a tree and then forget about this subtree. So as long as we have two equal elements $i$ $<$ $j$ than we can first solve euler tour between them and then delete elements $i+1,i+2...,j$. So now we want to solve euler tour where no element occur more than once. Let's say that this tour has length $2k-1$ then if we have less than $k$ elements we can replace any $0$ with any unused elements. Now if there are three elements in a row with values $x,y,0$ or $0,y,x$ than we can replace them with $x,y,x$ and forget about it. If we get rid of all triplets like this than we have tour in form of $a_1,0,a_2,0,...,0,a_k$. It's easy to observe that we can replace every $0$ with our root (subtree's root). There is a special case when we don't have any root (if solving for whole tree), than we have to find any vertex which can be root and then solve our problem. Straightforward implementation will be $O(n^2)$ but it can be easily reduced to $O(nlogn)$ and it can be even reduced to $O(n)$, but $O(nlogn)$ was enough to be accepted. More details about reducing $O(n^2)$ to $O(n)$ in code.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define st first\n#define nd second\n#define PII pair <int, int>\n\nconst int N = 1e6 + 7;\n\nint n;\nint in[N];\nint ans[N];\nbool used[N];\nvector <int> unused;\n\nint cnt;\ndeque <PII> cur;\nvector <PII> getEqual;\n\nset <int> S;\nvector <int> place[N];\nvector <pair <int, int> > order;\n\nbool check(){\n\tif(in[1] != 0 && in[n + n - 1] != 0 && in[1] != in[n + n - 1])\n\t\treturn false;\n\t\n\tfor(int i = 1; i + 1 < n + n; ++i)\n\t\tif(in[i] == in[i + 1] && in[i] != 0)\n\t\t\treturn false;\n\t\n\tfor(int i = 1; i < n + n; ++i){\n\t\tif(in[i] == 0)\n\t\t\tcontinue;\n\n\t\tif(place[in[i]].size() == 0)\n\t\t\torder.push_back({i, in[i]});\n\t\tplace[in[i]].push_back(i);\n\t}\n\t\n\tfor(int i = 1; i <= n; ++i)\n\t\tfor(int j = 1; j < place[i].size(); ++j)\n\t\t\tif(place[i][j]%2 != place[i][j - 1]%2)\n\t\t\t\treturn false;\n\t\n\tS.insert(n + n);\n\tsort(order.begin(), order.end());\n\t\n\tfor(auto v: order){\n\t\tauto it = S.lower_bound(v.first);\n\t\tif(*it < place[v.second].back())\n\t\t\treturn false;\n\t\t\n\t\tfor(int c: place[v.second])\n\t\t\tS.insert(c);\n\t}\n\t\n\treturn true;\n}\n\ninline int get(){\n    if(unused.size() == 0){\n        puts(\"no\");\n        exit(0);\n    }\n\n\tint ret = unused.back();\n\tunused.pop_back();\n\treturn ret;\n}\n\nvoid go(){\n\tdeque <PII> help;\n\twhile(help.size() + cur.size() >= 3){\n\t\tif(help.size() < 3){\n\t\t\thelp.push_back(cur.front());\n\t\t\tcur.pop_front();\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tPII v1 = help.back(); help.pop_back();\n\t\tPII v2 = help.back(); help.pop_back();\n\t\tPII v3 = help.back(); help.pop_back();\n\t\t\n\t\tif(v1.st == 0 && v2.st != 0 && v3.st != 0){\n\t\t\tans[v1.nd] = v3.st;\n\t\t\thelp.push_back(v3);\n\t\t}\n\t\telse{\n\t\t\thelp.push_back(v3);\n\t\t\thelp.push_back(v2);\n\t\t\thelp.push_back(v1);\n\t\t}\n\t\t\n\t\tif(cur.size() == 0)\n\t\t\tbreak;\n\t\t\n\t\thelp.push_back(cur.front());\n\t\tcur.pop_front();\n\t}\n\t\n\twhile(help.size()){\n\t\tcur.push_back(help.front());\n\t\thelp.pop_front();\n\t}\n}\n\nvoid solve(int root){\n\tint need = (cur.size() + 1) / 2 - cnt;\n\tif(need < 0){\n\t    puts(\"no\");\n\t    exit(0);\n\t}\n\tdeque <PII> help;\n\t\n\twhile(cur.size()){\n\t\tauto v = cur.front();\n\t\tcur.pop_front();\n\n\t\tif(need > 0 && v.st == 0){\n\t\t\t--need;\n\t\t\tv.st = get();\n\t\t\tans[v.nd] = v.st;\n\t\t}\n\t\t\n\t\thelp.push_back(v);\n\t}\n\t\n\twhile(help.size()){\n\t\tcur.push_front(help.front());\n\t\thelp.pop_front();\n\t}\n\n\tgo();\n\tif(root == -1 && cur.back().st == 0){\n\t\troot = cur.front().st;\n\t\tans[cur.back().nd] = root;\n\n\t\tcur.pop_front();\n\t\tcur.pop_back();\n\t\tsolve(root);\n\t\treturn;\n\t}\n\t\n\treverse(cur.begin(), cur.end());\n\tgo();\n\t\n\twhile(cur.size() > 0){\n\t\tauto v = cur.front();\n\t\tcur.pop_front();\n\t\t\n\t\tif(v.st == 0)\n\t\t\tans[v.nd] = root;\n\t}\n\t\n}\n\nint main(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i < n + n; ++i){\n\t\tscanf(\"%d\", &in[i]);\n\t\tused[in[i]] = true;\n\t}\n\t\n\tif(!check()){\n\t\tputs(\"no\");\n\t\treturn 0;\n\t}\n\t\n\tif(in[1] != 0)\n\t\tin[n + n - 1] = in[1];\n\telse if(in[n + n - 1] != 0)\n\t\tin[1] = in[n + n - 1];\n\t\n\tfor(int i = 1; i <= n; ++i){\n\t\tif(!used[i])\n\t\t\tunused.push_back(i);\n\t\tused[i] = false;\n\t}\n\t\n\tfor(int i = 1; i < n + n; ++i)\n\t\tans[i] = in[i];\n\t\n\tfor(int i = 1; i < n + n; ++i){\n\t\tif(in[i] == 0){\n\t\t\tgetEqual.push_back({in[i], i});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(used[in[i]]){\n\t\t\tcnt = 0;\n\t\t\twhile(getEqual.back().st != in[i]){\n\t\t\t\tif(getEqual.back().st > 0){\n\t\t\t\t\t++cnt;\n\t\t\t\t\tused[getEqual.back().st] = false;\n\t\t\t\t}\n\n\t\t\t\tcur.push_front(getEqual.back());\n\t\t\t\tgetEqual.pop_back();\n\t\t\t}\n\t\t\t\n\t\t\tsolve(in[i]);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tgetEqual.push_back({in[i], i});\n\t\tused[in[i]] = true;\n\t}\n\t\n\tcnt = 0;\n\twhile(getEqual.size()){\n\t\tif(getEqual.back().st > 0){\n\t\t\t++cnt;\n\t\t\tused[getEqual.back().st] = false;\n\t\t}\n\n\t\tcur.push_front(getEqual.back());\n\t\tgetEqual.pop_back();\n\t}\n\t\n\tsolve(-1);\n\tputs(\"yes\");\n\tfor(int i = 1; i < n + n; ++i)\n\t\tprintf(\"%d%c\", ans[i], i == n + n - 1 ? '\\n' : ' ');\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1054",
    "index": "A",
    "title": "Elevator or Stairs?",
    "statement": "Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor $x$, Egor on the floor $y$ (not on the same floor with Masha).\n\nThe house has a staircase and an elevator. If Masha uses the stairs, it takes $t_1$ seconds for her to walk between adjacent floors (in each direction). The elevator passes between adjacent floors (in each way) in $t_2$ seconds. The elevator moves with doors closed. The elevator spends $t_3$ seconds to open or close the doors. We can assume that time is not spent on any action except moving between adjacent floors and waiting for the doors to open or close. If Masha uses the elevator, it immediately goes directly to the desired floor.\n\nComing out of the apartment on her floor, Masha noticed that the elevator is now on the floor $z$ and has closed doors. Now she has to choose whether to use the stairs or use the elevator.\n\nIf the time that Masha needs to get to the Egor's floor by the stairs is \\textbf{strictly} less than the time it will take her using the elevator, then she will use the stairs, otherwise she will choose the elevator.\n\nHelp Mary to understand whether to use the elevator or the stairs.",
    "tutorial": "The time needed if we use stairs is $|x - y| \\cdot t_1$. The time needed if we use elevator is $|z - x| \\cdot t_2 + |x - y| \\cdot t_2 + 3 \\cdot t_3$. We can simply compute this values and compare them. Time complexity: $O(1)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint x, y, z, t1, t2, t3;\n  \nint main()\n{\n\tcin >> x >> y >> z >> t1 >> t2 >> t3;\n\tif (abs(z - x) * t2 + abs(x - y) * t2 + 3 * t3 <= abs(x - y) * t1)\n\t\tcout << \"YES\";\n\telse\n\t\tcout << \"NO\"; \n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1054",
    "index": "B",
    "title": "Appending Mex",
    "statement": "Initially Ildar has an empty array. He performs $n$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array.\n\nThe mex of an multiset of integers is the smallest \\textbf{non-negative} integer not presented in the multiset. For example, the mex of the multiset $[0, 2, 3]$ is $1$, while the mex of the multiset $[1, 2, 1]$ is $0$.\n\nMore formally, on the step $m$, when Ildar already has an array $a_1, a_2, \\ldots, a_{m-1}$, he chooses some subset of indices $1 \\leq i_1 < i_2 < \\ldots < i_k < m$ (possibly, empty), where $0 \\leq k < m$, and appends the $mex(a_{i_1}, a_{i_2}, \\ldots a_{i_k})$ to the end of the array.\n\nAfter performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $a_1, a_2, \\ldots, a_n$ the minimum step $t$ such that he has definitely made a mistake on at least one of the steps $1, 2, \\ldots, t$, or determine that he could have obtained this array without mistakes.",
    "tutorial": "Ildar has written an array correctly if there exists numbers $0, 1, \\ldots, a_i-1$ to the left of $a_i$ for all $i$. This is equivalent to $a_i \\leq max(-1, a_1, a_2, \\ldots, a_{i-1}) + 1$ for all $i$. If this condition is false for some $i$ we made a mistake. So the solution is to check that $a_i \\leq max(-1, a_1, a_2, \\ldots, a_{i-1}) + 1$ in the increasing order of $i$. If it is false $i$ is answer. If it is always true answer is $-1$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint n, a, m;\n \nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin >> n;\n\tm = -1;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tcin >> a;\n\t\tif (a > m + 1)\n\t\t{\n\t\t\tcout << i + 1;\n\t\t\treturn 0;\n\t\t}\n\t\tm = max(m, a);\n\t}\n\tcout << -1;\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1054",
    "index": "C",
    "title": "Candies Distribution",
    "statement": "There are $n$ children numbered from $1$ to $n$ in a kindergarten. Kindergarten teacher gave $a_i$ ($1 \\leq a_i \\leq n$) candies to the $i$-th child. Children were seated in a row in order from $1$ to $n$ from left to right and started eating candies.\n\nWhile the $i$-th child was eating candies, he calculated two numbers $l_i$ and $r_i$ — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.\n\nFormally, $l_i$ is the number of indices $j$ ($1 \\leq j < i$), such that $a_i < a_j$ and $r_i$ is the number of indices $j$ ($i < j \\leq n$), such that $a_i < a_j$.\n\nEach child told to the kindergarten teacher the numbers $l_i$ and $r_i$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $l$ and $r$ determine whether she could have given the candies to the children such that all children correctly calculated their values $l_i$ and $r_i$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.",
    "tutorial": "Let's note that for any $i$, the value of $(l_i + r_i)$ is equal to the number of children who got more candies than $i$-th. So, $(n - l_i - r_i)$ is equal to the number of children who got less or equal number of candies than $i$-th (including himself). So, if there exists an array $a$ satisfying the conditions, then its numbers are ordered exactly as well as the numbers in the array $(n - l_i - r_i)$ (if the numbers at two positions are equal in one of the arrays, then they are equal in the other; if in one of the arrays at one position the number is less than the number at the other position, it is true for the other array). Also $1 \\leq (n - l_i - r_i) \\leq n$ for any $i$. Thus, if there exists an array $a$ satisfying the conditions, then the array $a_i = (n - l_i-r_i)$ also satisfies the conditions. So, you just need to take the array ai=(n-li-ri) and check it. If it satisfies conditions, the answer is this array, otherwise, there are no such arrays at all. The check can be performed using a trivial algorithm that works for O(n2) time. Time complexity: O(n2).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int M = 1010;\n \nint n, a[M], l[M], r[M];\n \nint main()\n{\n        cin >> n;\n\tfor (int i = 0; i < n; i++) cin >> l[i];\n\tfor (int i = 0; i < n; i++) cin >> r[i];\n\tfor (int i = 0; i < n; i++) a[i] = (n - l[i] - r[i]);\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < i; j++)\n\t\t\tl[i] -= (a[j] > a[i]);\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = i + 1; j < n; j++)\n\t\t\tr[i] -= (a[j] > a[i]);\n\tfor (int i = 0; i < n; i++)\n\t\tif (l[i] != 0 || r[i] != 0)\n\t\t{\n\t\t\tcout << \"NO\\n\";\n\t\t\treturn 0;\n\t\t}\n\tcout << \"YES\\n\";\n\tfor (int i = 0; i < n; i++)\n\t\tcout << a[i] << \" \";\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1054",
    "index": "D",
    "title": "Changing Array",
    "statement": "At a break Vanya came to the class and saw an array of $n$ $k$-bit integers $a_1, a_2, \\ldots, a_n$ on the board. An integer $x$ is called a $k$-bit integer if $0 \\leq x \\leq 2^k - 1$.\n\nOf course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $i$ ($1 \\leq i \\leq n$) and replace the number $a_i$ with the number $\\overline{a_i}$. We define $\\overline{x}$ for a $k$-bit integer $x$ as the $k$-bit integer such that all its $k$ bits differ from the corresponding bits of $x$.\n\nVanya does not like the number $0$. Therefore, he likes such segments $[l, r]$ ($1 \\leq l \\leq r \\leq n$) such that $a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_r \\neq 0$, where $\\oplus$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.",
    "tutorial": "We need to maximize the number of segments with XOR-sum of its elements not equal to 0. Let's note that the total number of segments is (n+12)=n \\cdot (n+1)/2 so we need to minimize the number of segments with XOR-sum of its elements equal to 0. Let's call such segments bad. Consider the prefix XOR sums of array a. Let's define pi=a1 \\oplus  \\dots  \\oplus ai for any 0 \\le i \\le n. Note that the segment [l,r] is bad if prl-1=prr. How does an array p changes in a single operation with an array a? Let's note that  \\bar x=x \\oplus (2k-1). If we do operation with the element i then in array p all elements pj (j \\ge i) will change to pj \\oplus (2k-1) or  \\bar pj. So after all operations, element of p will be either equal to itself before operations or will be equal to itself before operations but with all changed bits. But p0=0 still. On the other hand. Suppose that there are some changes of this kind in the array p. Let's prove that we could make some operations in the array a so that p will be changed and became exactly the same. To prove this, note that ai=pi-1 \\oplus pi, so all values of ai have either not changed or have changed to numbers with all changed bits. So let's just assume that we are changing the array p (all its elements except the element with index 0), not the array a. Let's note that two numbers x and y can become equal after all operations with them if they are equal or x= \\bar y. So we can replace pi with min(pi, \\bar pi) for any i in the array p. The answer will be the same if we do this. But it will be impossible to get equal numbers from different numbers in the new array. Let's calculate for each number c the number of its occurrences in the array p and denote it for k. Some of this k numbers we can leave equal to c, and some of them we change to  \\bar c. Let's change 0 \\le a \\le k numbers. Then we want to minimize the number of pairs of equal numbers, which is (k-a+12)+(a+12). To do this, we need to change and not change the approximately equal number of numbers, that is, the minimum is reached at a= \\lfloor k/2 \\rfloor . It can be proved simply. So we should divide the numbers this way for any c and sum the answers. For each number c, the number of its occurrences in the array can be calculated using the sorting algorithm or the std::map structure into the C++ language. Time complexity: O(n \\cdot log(n)).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nint n, k;\n \nll gett(int k)\n{\n\treturn ((ll)k * (ll)(k - 1)) / 2LL;\n}\n \nint main()\n{\n\tcin.sync_with_stdio(0); \n\tcin >> n >> k;\n\tint a = 0;\n\tll ans = 0;\n\tmap<int, int> kol;\n\tkol[0] = 1;\n\tfor (int i = 1; i <= n; i++)\n\t{\n\t\tint b;\n\t\tcin >> b;\n\t\ta ^= min(b, (1 << k) - 1 - b);\n\t\tkol[a]++;\n\t}\t\t\n\tfor (pair<int, int> t : kol)\n\t{\n\t\tans += gett(t.second / 2);\n\t\tans += gett((t.second + 1) / 2);\t\n\t}\n\tcout << gett(n + 1) - ans;\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1054",
    "index": "E",
    "title": "Chips Puzzle",
    "statement": "Egor came up with a new chips puzzle and suggests you to play.\n\nThe puzzle has the form of a table with $n$ rows and $m$ columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip), possibly empty, and the whole puzzle can be described as a table, where each cell is a string of zeros and ones. The task is to get from one state of the puzzle some other state.\n\nTo do this, you can use the following operation.\n\n- select 2 different cells $(x_1, y_1)$ and $(x_2, y_2)$: the cells must be in the same row or in the same column of the table, and the string in the cell $(x_1, y_1)$ must be non-empty;\n- in one operation you can move the last character of the string at the cell $(x_1, y_1)$ to the beginning of the string at the cell $(x_2, y_2)$.\n\nEgor came up with two states of the table for you: the initial state and the final one. It is guaranteed that the number of zeros and ones in the tables are the same. Your goal is with several operations get the final state from the initial state. Of course, Egor does not want the number of operations to be very large. Let's denote as $s$ the number of characters in each of the tables (which are the same). Then you should use no more than $4 \\cdot s$ operations.",
    "tutorial": "Our usual operation - is to move the last character of a string in one cell to the beginning of a string in another cell. If we do the reverse operation - to move the first character of a string in one cell to the end of a string in another cell, then it's like we will do our operation for reversed strings and at the end, we will reverse them again. Let's learn how to bring a table to a fixed one for  \\le 2 \\cdot s operations. After that, to solve our problem, we can bring the initial state to a fixed and final state (we should reverse all the strings in it) to a fixed. After that, if you reverse the second order of operations and add to the first, we get the solution to the problem. Our fixed table is a table in which the cell (2,1) contains all 1 and the cell (1,2) contains all 0. How to make this table from any table using  \\le 2 \\cdot s operations? First, we move all the characters of the first column and the first row to the cell (1,1). Next, let's move all the characters of the rectangle with angles of (2,2) and (n,m) to the first column if it is 1, and to the first row if it is 0. This will take  \\le s operations. Next, let's move all the characters in the first column (except the (1,1)) into the (2,1) cell and all the characters in the first row (except the (1,1) cell) into the (1,2) cell. Finally, let's move the symbols of (1,1) to (2,1) if it is 1 or (1,2) if it is 0. Time complexity: O(s). Bonus: What is the minimum constant c you can get so that the algorithm always performs  \\le c \\cdot s operations? (c may depends on n, m)",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int two = 2;\nconst int N = 310;\nconst int S = 200100;\n \nint n, m;\nstring s[two][N][N];\nint k[two];\ntuple<int, int, int, int> ans[two][S];\nqueue<char> in[N][N];\n \nvoid func(int c)\n{\n\tk[c] = 0;\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < m; j++)\n\t\t{\n\t\t\twhile (!in[i][j].empty()) in[i][j].pop();\n\t\t\tfor (int x = (int)s[c][i][j].size() - 1; x >= 0; x--)\n\t\t\t\tin[i][j].push(s[c][i][j][x]);\n\t\t}\n\tfor (int i = 1; i < m; i++)\n\t\twhile (!in[0][i].empty())\n\t\t{\n\t\t\tans[c][k[c]] = make_tuple(0, i, 0, 0);\n\t\t\tin[0][0].push(in[0][i].front());\n\t\t\tin[0][i].pop();\n\t\t\tk[c]++;\n\t\t}\t\n\tfor (int i = 1; i < n; i++)\n\t\twhile (!in[i][0].empty())\n\t\t{\n\t\t\tans[c][k[c]] = make_tuple(i, 0, 0, 0);\n\t\t\tin[0][0].push(in[i][0].front());\n\t\t\tin[i][0].pop();\n\t\t\tk[c]++;\n\t\t}\t           \n\twhile (!in[0][0].empty())\n\t{\n\t\tif (in[0][0].front() == '0')\n\t\t{\n\t\t\tans[c][k[c]] = make_tuple(0, 0, 0, 1);\n\t\t\tin[0][1].push(in[0][0].front());\n\t\t\tin[0][0].pop();\n\t\t\tk[c]++;\n\t\t}\n\t\telse\n\t\t{\n            ans[c][k[c]] = make_tuple(0, 0, 1, 0);\n\t\t\tin[1][0].push(in[0][0].front());\n\t\t\tin[0][0].pop();\n\t\t\tk[c]++;\n\t\t}\n\t}\n\tfor (int i = 1; i < n; i++)\n\t\tfor (int j = 1; j < m; j++)\n\t\t\twhile (!in[i][j].empty())\n\t\t\t{\n\t\t\t\tif (in[i][j].front() == '0')\n\t\t\t\t{\n\t\t\t\t\tans[c][k[c]] = make_tuple(i, j, 0, j);\n\t\t\t\t\tin[0][j].push(in[i][j].front());\n\t\t\t\t\tin[i][j].pop();\n\t\t\t\t\tk[c]++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n                    ans[c][k[c]] = make_tuple(i, j, i, 0);\n\t\t\t\t\tin[i][0].push(in[i][j].front());\n\t\t\t\t\tin[i][j].pop();\n\t\t\t\t\tk[c]++;\n\t\t\t\t}\t\n\t\t\t}\n\tfor (int i = 2; i < m; i++)\n\t\twhile (!in[0][i].empty())\n\t\t{\n\t\t\tans[c][k[c]] = make_tuple(0, i, 0, 1);\n\t\t\tin[0][1].push(in[0][i].front());\n\t\t\tin[0][i].pop();\n\t\t\tk[c]++;\n\t\t}\t\n\tfor (int i = 2; i < n; i++)\n\t\twhile (!in[i][0].empty())\n\t\t{\n\t\t\tans[c][k[c]] = make_tuple(i, 0, 1, 0);\n\t\t\tin[0][1].push(in[i][0].front());\n\t\t\tin[i][0].pop();\n\t\t\tk[c]++;\n\t\t}\n}\n \nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin >> n >> m;\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < m; j++)\n\t\t\tcin >> s[0][i][j];\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < m; j++)\n\t\t\tcin >> s[1][i][j];\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < m; j++)\n\t\t\treverse(s[1][i][j].begin(), s[1][i][j].end());\n\tfunc(0);\n\tfunc(1);\n\treverse(ans[1], ans[1] + k[1]);\n\tcout << (k[0] + k[1]) << \"\\n\";\n\tfor (int i = 0; i < k[0]; i++)\n\t\tcout << get<0>(ans[0][i]) + 1 << \" \" << get<1>(ans[0][i]) + 1 << \" \" << get<2>(ans[0][i]) + 1 << \" \" << get<3>(ans[0][i]) + 1 << \"\\n\";\n\tfor (int i = 0; i < k[1]; i++)\n\t\tcout << get<2>(ans[1][i]) + 1 << \" \" << get<3>(ans[1][i]) + 1 << \" \" << get<0>(ans[1][i]) + 1 << \" \" << get<1>(ans[1][i]) + 1 << \"\\n\";\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1054",
    "index": "F",
    "title": "Electric Scheme",
    "statement": "Pasha is a young technician, nevertheless, he has already got a huge goal: to assemble a PC. The first task he has to become familiar with is to assemble an electric scheme.\n\nThe scheme Pasha assembled yesterday consists of several wires. Each wire is a segment that connects two points on a plane with integer coordinates within the segment $[1, 10^9]$.\n\nThere are wires of two colors in the scheme:\n\n- red wires: these wires are horizontal segments, i.e. if such a wire connects two points $(x_1, y_1)$ and $(x_2, y_2)$, then $y_1 = y_2$;\n- blue wires: these wires are vertical segments, i.e. if such a wire connects two points $(x_1, y_1)$ and $(x_2, y_2)$, then $x_1 = x_2$.\n\nNote that if a wire connects a point to itself, it may be blue, and it can be red. Also, in Pasha's scheme no two wires of the same color intersect, i.e. there are no two wires of same color that have common points.\n\nThe imperfection of Pasha's scheme was that the wires were not isolated, so in the points where two wires of different colors intersect, Pasha saw sparks. Pasha wrote down all the points where he saw sparks and obtained a set of $n$ distinct points. After that he disassembled the scheme.\n\nNext morning Pasha looked at the set of $n$ points where he had seen sparks and wondered how many wires had he used. Unfortunately, he does not remember that, so he wonders now what is the smallest number of wires he might have used in the scheme. Help him to determine this number and place the wires in such a way that in the resulting scheme the sparks occur in the same places.",
    "tutorial": "Let's reduce this problem to the problem of finding the minimum vertex cover in a bipartite graph. We need to build the following graph: in one part all horizontal segments between adjacent points by x from the set of points having the same y, in the other part all vertical segments between adjacent points by y from the set of points having the same x. We will make an edge between segments from different parts if they intersect strictly by internal point. It can be proved that the answer is equal to (the number of distinct x in the set) + (the number of distinct y in the set) + (the maximum matching in this graph). To prove this, you need to understand how the answer looks like. In any case, for any x from the set there will be  \\ge 1 vertical segment, with x1=x2=x and for any y from the set there will be  \\ge 1 horizontal segment, with y1=y2=y. If we draw such segments, some of them will intersect at a point that not from the set. In this case, we will have to cut some of these segments. At the same time, we want to cut as little number of segments as possible (cutting - erase part of the segment between adjacent points on this segment's horizontal/vertical). We can see, that all erased segments form a vertex cover (in the graph we built). But if you erase the segments from the minimum vertex cover, you will get the answer, and this answer will have the smallest size. So, it is necessary to find the minimum vertex cover in the constructed bipartite graph. This can be done by the standard algorithm uses O(V \\cdot E)=O(n3) time. We can prove that E \\le n2/4 and on practice it works very fast even for n=1000. Time complexity: O(n3). Bonus: how to solve this problem faster than for O(n3)? (if you don't need to find segments, only their number)",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int M = 1010;\n \nint n;\nvector<pair<int, int> > pt;\nvector<int> vx, vy;\nvector<int> gx[M], gy[M];\nvector<tuple<int, int, int> > sh, sv;\nint pa[M], pb[M], ln, lm;\nvector<int> v[M];\nbool used[M], used1[M];\nvector<int> dx[M], dy[M];\n \nbool dfs(int p)\n{\n\tused[p] = true;\n\tfor (int i : v[p])\n\t{\n\t\tif (pb[i] == -1 || (!used[pb[i]] && dfs(pb[i])))\n\t\t{\n\t\t\tpa[p] = i;\n\t\t\tpb[i] = p;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n \nvoid dfs_set(int p)\n{\n\tused[p] = true;\n\tfor (int i : v[p])\n\t{\n\t\tused1[i] = true;\n\t\tif (pb[i] != -1 && !used[pb[i]])\n\t\t\tdfs_set(pb[i]);\n\t}\n}\n \n \nvoid kuhn()\n{\n\tmemset(pa, -1, sizeof(pa));\n\tmemset(pb, -1, sizeof(pb));\n\tfor (int i = 0; i < ln; i++)\n\t{\n\t\tmemset(used, 0, sizeof(used));\n\t\tif (dfs(i)) continue;\n\t}\n\tmemset(used, 0, sizeof(used));\n\tmemset(used1, 0, sizeof(used1));\n\tfor (int i = 0; i < ln; i++)\n\t\tif (pa[i] == -1) \n\t\t\tdfs_set(i);\n\tfor (int i = 0; i < ln; i++)\n\t\tused[i] = (!used[i]);\t\n}\n \nint main()\n{\n\tios::sync_with_stdio(0);\n        cin >> n;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\tvx.push_back(x);\n\t\tvy.push_back(y);\n\t\tpt.push_back(make_pair(x, y));\n\t}\n\tsort(vx.begin(), vx.end());\n\tvx.resize(unique(vx.begin(), vx.end()) - vx.begin());\n\tsort(vy.begin(), vy.end());\n\tvy.resize(unique(vy.begin(), vy.end()) - vy.begin());\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tpt[i].first = lower_bound(vx.begin(), vx.end(), pt[i].first) - vx.begin();\n\t\tpt[i].second = lower_bound(vy.begin(), vy.end(), pt[i].second) - vy.begin();\n\t}\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tgx[pt[i].first].push_back(pt[i].second);\n\t\tgy[pt[i].second].push_back(pt[i].first);\n\t}\t\n\tfor (int i = 0; i < n; i++)\n\t\tsort(gx[i].begin(), gx[i].end());\n\tfor (int i = 0; i < n; i++)\n\t\tsort(gy[i].begin(), gy[i].end());\n\tfor (int y = 0; y < n; y++)\n\t\tif ((int)gy[y].size() > 1)\n\t\t\tfor (int i = 0; i < (int)gy[y].size() - 1; i++)\n\t\t\t\tsh.push_back(make_tuple(gy[y][i], gy[y][i + 1], y));\n\tfor (int x = 0; x < n; x++)\n\t\tif ((int)gx[x].size() > 1)\n\t\t\tfor (int i = 0; i < (int)gx[x].size() - 1; i++)\n\t\t\t\tsv.push_back(make_tuple(gx[x][i], gx[x][i + 1], x)); \n\tsort(sh.begin(), sh.end());\n\tsort(sv.begin(), sv.end());\n\tln = sh.size();\n\tlm = sv.size();                  \n\tfor (int i = 0; i < ln; i++)\n\t\tfor (int j = 0; j < lm; j++)\n\t\t{               \n\t\t\tif (!(get<0>(sh[i]) < get<2>(sv[j]) && get<2>(sv[j]) < get<1>(sh[i]))) continue;\n\t\t\tif (!(get<0>(sv[j]) < get<2>(sh[i]) && get<2>(sh[i]) < get<1>(sv[j]))) continue;\n\t\t\tv[i].push_back(j);\n\t\t}\t\t\t\n\tkuhn();\n\tfor (int y = 0; y < n; y++)\n\t\tif ((int)gy[y].size() >= 1)\n\t\t\tdy[y].push_back(gy[y][0]);\n\tfor (int x = 0; x < n; x++)\n\t\tif ((int)gx[x].size() >= 1)\n\t\t\tdx[x].push_back(gx[x][0]);\n\tfor (int i = 0; i < ln; i++)\n\t\tif (used[i])\n\t\t{\n\t\t\tdy[get<2>(sh[i])].push_back(get<0>(sh[i]));\n\t\t\tdy[get<2>(sh[i])].push_back(get<1>(sh[i]));\n\t\t}\n\tfor (int i = 0; i < lm; i++)\n\t\tif (used1[i])\n\t\t{\n\t\t\tdx[get<2>(sv[i])].push_back(get<0>(sv[i]));\n\t\t\tdx[get<2>(sv[i])].push_back(get<1>(sv[i]));\n\t\t}\n\tfor (int y = 0; y < n; y++)\n\t\tif ((int)gy[y].size() >= 1)\n\t\t\tdy[y].push_back(gy[y].back());\n\tfor (int x = 0; x < n; x++)\n\t\tif ((int)gx[x].size() >= 1)\n\t\t\tdx[x].push_back(gx[x].back());\n\tint ans = 0;\n\tfor (int y = 0; y < n; y++)\n\t\tans += (int)dy[y].size();\n\tans /= 2;\n\tcout << ans << \"\\n\";\t\n\tfor (int y = 0; y < n; y++)\n\t\tfor (int i = 0; i < (int)dy[y].size(); i += 2)                                                  \n\t\t\tcout << vx[dy[y][i]] << \" \" << vy[y] << \" \" << vx[dy[y][i + 1]] << \" \" << vy[y] << \"\\n\";\n\tans = 0;\n\tfor (int x = 0; x < n; x++)\n\t\tans += (int)dx[x].size();\n\tans /= 2;\n\tcout << ans << \"\\n\";\t\n\tfor (int x = 0; x < n; x++)\n\t\tfor (int i = 0; i < (int)dx[x].size(); i += 2)                                                  \n\t\t\tcout << vx[x] << \" \" << vy[dx[x][i]] << \" \" << vx[x] << \" \" << vy[dx[x][i + 1]] << \"\\n\";\n\treturn 0;\n}",
    "tags": [
      "flows",
      "graph matchings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1054",
    "index": "G",
    "title": "New Road Network",
    "statement": "The king of some country $N$ decided to completely rebuild the road network. There are $n$ people living in the country, they are enumerated from $1$ to $n$. It is possible to construct a road between the house of any citizen $a$ to the house of any other citizen $b$. There should not be more than one road between any pair of citizens. The road network must be connected, i.e. it should be possible to reach every citizen starting from anyone using roads. To save funds, it was decided to build exactly $n-1$ road, so the road network should be a tree.\n\nHowever, it is not that easy as it sounds, that's why the king addressed you for help. There are $m$ secret communities in the country, each of them unites a non-empty subset of citizens. The king does not want to conflict with any of the communities, so he wants to build the network such that the houses of members of each society form a connected subtree in network. A set of vertices forms a connected subtree if and only if the graph remains connected when we delete all the other vertices and all edges but ones that connect the vertices from the set.\n\nHelp the king to determine if it is possible to build the desired road network, and if it is, build it.",
    "tutorial": "Let us denote for Ai the set of sets (or secret comunities, as in our problem), which contains i-th vertex. Note that if some set Ai contains an element that does not belong to any other set Aj, it can be thrown out and it will not affect to the answer. Let's make this. Let the tree exist. Then it has a leaf (let this vertex i). Let the only edge from i be to vertex j. Any element Ai is contained in  \\ge 2-x sets and in the tree all sets (which secret comunities) form connected subtrees. This implies that Ai \\subset Aj. So, if in A1, \\dots ,An there are no two sets such that one subset of the other, then the tree does not exist. Otherwise, let us find any pair Ai \\subset Aj. We prove that there exists a tree in which i is a leaf that has an edge to j. It is possible to change the edges of any tree-solution that i becomes a leaf that has an edge to j, but the tree will still be a solution (it is the exercise for the reader). Let's find a good pair (i,j), remove i and continue the process. At the same time, at each step, it is necessary to remove the elements contained in  \\le 1 sets. If we implement such an algorithm in this form it will work for O(n3 \\cdot m/64) time, which is too big. To improve the algorithm's complexity, for each set Ai, we store a set of indices j, such that Ai \\subset Aj. Then at each step, you can quickly find the needed pair (i,j). At the same time, removing i, you can quickly update this structure. In this problem, there is a simpler solution, but it is more difficult to prove it. Let's build a weighted undirected graph on n vertices with weight wij=|Ai \\cap Aj|. Let's construct the maximum spanning tree in this graph. It is can be proved that either it is the answer, or there is no solution. This can be understood from the proof of the previous solution, which essentially simulates the search for such a spanning tree. Time complexity: O(n2 \\cdot m/64).",
    "code": "#include <iostream>\n#include <tuple>\n#include <sstream>\n#include <vector>\n#include <cmath>\n#include <ctime>\n#include <bitset>\n#include <cassert>\n#include <cstdio>\n#include <queue>\n#include <set>\n#include <map>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <cstring>\n#include <algorithm>\n#include <numeric>\n \n#define mp make_pair\n#define mt make_tuple\n#define fi first\n#define se second\n#define pb push_back\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\n#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)\n#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)\n#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)\n \nusing namespace std;\n \ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<pii> vpi;\ntypedef vector<vi> vvi;\ntypedef long long i64;\ntypedef vector<i64> vi64;\ntypedef vector<vi64> vvi64;\ntypedef pair<i64, i64> pi64;\ntypedef double ld;\n \ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n \nconst int maxn = 2011, maxm = 2011;\ntypedef bitset<maxm> bs;\nbs b[maxn];\nchar buf[maxm];\nint dist[maxn][maxn];\npii me[maxn];\nint used[maxn];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.precision(10);\n    cout << fixed;\n#ifdef LOCAL_DEFINE\n    freopen(\"input.txt\", \"rt\", stdin);\n#endif\n \n    int T;\n    scanf(\"%d\", &T);\n    while (T--) {\n        int n, m;\n        scanf(\"%d%d\", &n, &m);\n        forn(i, n) forn(j, maxm) b[i][j] = 0;\n        vi cnt(m);\n        forn(i, m) {\n            scanf(\"%s\", buf);\n            forn(j, n) if (buf[j] == '1') b[j].set(i), ++cnt[i];\n        }\n        forn(i, n) forn(j, n) {\n            dist[i][j] = (b[i] & b[j]).count();\n        }\n \n        forn(i, n) me[i] = {-1e9, -1}, used[i] = 0;\n        int Z = 0;\n        vector<pii> e;\n        forn(i, n) {\n            int v = -1;\n            forn(j, n) {\n                if (used[j]) continue;\n                if (v == -1 || me[j] > me[v]) v = j;\n            }\n            used[v] = 1;\n            if (me[v].se != -1) e.pb({v, me[v].se});\n            forn(j, n) uax(me[j], mp(dist[v][j], v));\n        }\n \n        bool ok = true;\n        forn(j, m) {\n            int z = 0;\n            for (auto w: e) if (b[w.fi][j] && b[w.se][j]) ++z;\n            ok &= z == cnt[j] - 1;\n        }\n        if (ok) {\n            cout << \"YES\\n\";\n            for (auto w: e) cout << w.fi + 1 << ' ' << w.se + 1 << '\\n';\n        } else cout << \"NO\\n\";\n    }\n \n#ifdef LOCAL_DEFINE\n    cerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n#endif\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1054",
    "index": "H",
    "title": "Epic Convolution",
    "statement": "You are given two arrays $a_0, a_1, \\ldots, a_{n - 1}$ and $b_0, b_1, \\ldots, b_{m-1}$, and an integer $c$.\n\nCompute the following sum:\n\n$$\\sum_{i=0}^{n-1} \\sum_{j=0}^{m-1} a_i b_j c^{i^2\\,j^3}$$\n\nSince it's value can be really large, print it modulo $490019$.",
    "tutorial": "The given modulo 490019 is a prime one. Note, that value of c(i2j3), according to the Fermat's theorem, depends only on the (i2j3)mod(490019-1). The main idea is that we want to end up with something like polynomial  \\sum ctxt, where t would be (i2j3)mod(490019-1) and ct is sum of corresponding aibj. If we have such a polynomial, we can easily compute the final answer. Now time to notice, that the given modulo was... a bit non standard. Notice, that phi=490019-1=490018=2 \\cdot 491 \\cdot 499. As chinese remainder theorem suggests, xmodphi is equivalent to (xmod2,xmod491,xmod499) (for all x) And instead of multiplying resiudes modulo phi we can multiply (and computing squares and cubes) the elements of this tuple pairwise. Let's ignore the first component for a while (suppose xmod2=0). Since the numbers 491 and 499 are prime, they have a primitive roots. Let's compute discrete logarithms of the residues of i2's and j3's modulo 491 and 499. (There is some trouble if the residue is zero, but let's skip for now). And now we left only with multiplication. But since we have taken log's multiplication becomes summation. So we can apply a polynomial multiplication to solve the problem. Basically, we have two polynomials of form  \\sum i,jci,jxiyj (from array a and array b), where i is logarithm of residue modulo 491 and j is logarithm of residue modulo 499. We can multiply these polynomials with fft! A 2d polynomial is matrix of it's coefficients. A 2d fft is matrix of it's values in (win,wjm). One can prove, that to have 2d fft we can just apply fft on all lines and then on all columns (or vice versa). The rest is as usual, multiply fft's values pointwise, then inverse fft and examine the result as we stated in the begining of editorial. We need to deal with cases when residue is equal to zero modulo 2, 491 or 499. Since the timelimit was really generous we can deal with latter two just by handling all pairs (i,j) where either i is zero modulo 491 or 499 or j is zero modulo 491 or 499 in a naive way. This is roughly nm/sqrt(mod) pairs which takes roughly a second with the given constraints. Residues modulo 2 must be handled specifically (because there are too much pairs), but it is easy since there are only two of them. Basically the end residue is 1 only if original residues are 1 as well.",
    "code": "// 2018, Sayutin Dmitry.\n \n#include <bits/stdc++.h>\n \nusing std::cin;\nusing std::cout;\nusing std::cerr;\n \nusing std::vector;\nusing std::map;\nusing std::array;\nusing std::set;\nusing std::string;\n \nusing std::pair;\nusing std::make_pair;\n \nusing std::tuple;\nusing std::make_tuple;\nusing std::get;\n \nusing std::min;\nusing std::abs;\nusing std::max;\n \nusing std::unique;\nusing std::sort;\nusing std::generate;\nusing std::reverse;\nusing std::min_element;\nusing std::max_element;\n \n#ifdef LOCAL\n#define LASSERT(X) assert(X)\n#else\n#define LASSERT(X) {}\n#endif\n \ntemplate <typename T>\nT input() {\n    T res;\n    cin >> res;\n    LASSERT(cin);\n    return res;\n}\n \ntemplate <typename IT>\nvoid input_seq(IT b, IT e) {\n    std::generate(b, e, input<typename std::remove_reference<decltype(*b)>::type>);\n}\n \n#define SZ(vec)         int((vec).size())\n#define ALL(data)       data.begin(),data.end()\n#define RALL(data)      data.rbegin(),data.rend()\n#define TYPEMAX(type)   std::numeric_limits<type>::max()\n#define TYPEMIN(type)   std::numeric_limits<type>::min()\n \n#define pb push_back\n#define eb emplace_back\n \nconst int mod = 490019;\nconst int phi = mod - 1; // = 2 * 491 * 499\n \nint add(int a, int b) {\n    return (a + b >= mod ? a + b - mod : a + b);\n}\n \nint sub(int a, int b) {\n    return (a >= b ? a - b : mod + a - b);\n}\n \nint mult(int a, int b) {\n    return (int64_t(a) * b) % mod;\n}\n \nint fastpow(int a, int n, int md, int r = 1) {\n    while (n) {\n        if (n % 2)\n            r = (int64_t(r) * a) % md;\n        \n        a = (int64_t(a) * a) % md;\n        n /= 2;\n    }\n \n    return r;\n}\n \nconst int LOG_N = 10;\nconst int FFT_N = (1 << LOG_N);\n \nstruct complex {\n    complex(): x(0), y(0) {}\n    complex(double x, double y = 0): x(x), y(y) {}\n \n    complex operator+(complex other) {return complex(x + other.x, y + other.y);}\n    complex operator+=(complex other) {x += other.x; y += other.y; return *this;}\n    complex operator-(complex other) {return complex(x - other.x, y - other.y);}\n \n    complex operator*(complex other) {return complex(x * other.x - y * other.y, x * other.y + y * other.x);}\n \n    complex operator/=(int val) {x /= val; y /= val; return *this;}\n    \n    inline double real() {return x;}\n    inline double imag() {return y;}\n    \n    double x;\n    double y;\n};\n \ncomplex w[FFT_N];\nint rev[FFT_N];\n \n#if 1\n \nvoid precalc() {\n    // /2 [0;1) -> [1;1]\n    // /4 [0;2) -> [2;3]\n    // /8 [0;4) -> [4;7]\n    // ..\n    // /FFT_N [0;FFT_N / 2) -> [FFT_N / 2; FFT_N - 1]\n    \n    double pi = acos(-1);\n \n    for (int i = 0; i != FFT_N / 2; ++i)\n        w[FFT_N / 2 + i] = complex(cos(2.0 * pi * double(i) / FFT_N), sin(2.0 * pi * double(i) / FFT_N));\n \n    for (int n = FFT_N / 2; n >= 2; n /= 2)\n        for (int i = 0; i != n / 2; ++i)\n            w[n / 2 + i] = w[n + 2 * i];\n \n    rev[0] = 0;\n    int last = 0;\n    for (int i = 1; i != FFT_N; ++i) {\n        if (i == (2 << last))\n            ++last;\n \n        rev[i] = rev[i ^ (1 << last)] | (1 << (LOG_N - 1 - last));\n    }\n}\n \nvoid fft(complex* a) {\n    for (int i = 0; i < FFT_N; ++i)\n        if (i < rev[i])\n            std::swap(a[i], a[rev[i]]);\n \n    for (int n = 1; n < FFT_N; n = n << 1)\n        for (int start = 0; start < FFT_N; start += (n << 1))\n            for (int off = 0; off < n; ++off) {\n                complex x = a[start + off];\n                complex y = a[start + off + n] * w[n + off];\n \n                a[start + off]     = x + y;\n                a[start + off + n] = x - y;\n            }\n}\n \n#else\n \nvoid precalc() {\n    double pi = acos(-1);\n    for (int i = 0; i != FFT_N; ++i)\n        w[i] = complex(cos(2.0 * pi * double(i) / FFT_N), sin(2.0 * pi * double(i) / FFT_N));\n \n    rev[0] = 0;\n    int last = 0;\n    for (int i = 1; i != FFT_N; ++i) {\n        if (i == (2 << last))\n            ++last;\n \n        rev[i] = rev[i ^ (1 << last)] | (1 << (LOG_N - 1 - last));\n    }\n}\n \n \nvoid fft(complex* a) {\n    for (int i = 0; i < FFT_N; ++i)\n        if (i < rev[i])\n            std::swap(a[i], a[rev[i]]);\n \n    for (int lvl = 0; lvl < LOG_N; ++lvl)\n        for (int start = 0; start < FFT_N; start += (2 << lvl))\n            for (int off = 0; off < (1 << lvl); ++off) {\n                complex x = a[start + off];\n                complex y = a[start + off + (1 << lvl)] * w[off << (LOG_N - 1 - lvl)];\n \n                a[start + off + (0 << lvl)] = x + y;\n                a[start + off + (1 << lvl)] = x - y;\n            }\n}\n \n#endif \n \n \nvoid inv_fft(complex* a) {\n    fft(a);\n    std::reverse(a + 1, a + FFT_N);\n    for (int i = 0; i != FFT_N; ++i)\n        a[i] /= FFT_N;\n}\n \nint inverse(int a, int md) {\n    return fastpow(a % md, md - 2, md);\n}\n \n// [0; phi) -> [0; 2) x [0; 491) x [0; 499)\ntuple<int, int, int> chinese_it(int num) {\n    return make_tuple(num % 2, num % 491, num % 499);\n}\n \nvoid chinese_it(int num, int& a, int& b, int& c) {\n    a = num % 2;\n    b = num % 491;\n    c = num % 499;\n}\n \n// [0; 2) x [0; 491) x [0; 499) -> [0; phi)\nint un_chinese_it(int a, int b, int c) {\n    static int X = (int64_t(491 * 499) * inverse(491 * 499, 2)) % phi;\n    static int Y = (int64_t(2 * 499) * inverse(2 * 499, 491)) % phi;\n    static int Z = (int64_t(2 * 491) * inverse(2 * 491, 499)) % phi;\n \n    return (a * X + b * Y + c * Z) % phi;\n}\n \nint primitive491 = 7;\nint primitive499 = 7;\n \nint pr_pows491[491];\nint pr_pows499[499];\n \nint log491[491];\nint log499[499];\n \n#ifndef LOCAL\n#define STAMP(msg) {fprintf(stderr, \"%0.2lf: %s\\n\", clock() / double(CLOCKS_PER_SEC), msg);}\n#else\n#define STAMP(msg)\n#endif\n \nint main() {\n    STAMP(\"start\");\n    \n    // code here\n    int n, m, c;\n    scanf(\"%d%d%d\", &n, &m, &c);\n \n    vector<int> a(n);\n    vector<int> b(m);\n \n    for (int& elem: a)\n        scanf(\"%d\", &elem);\n    for (int& elem: b)\n        scanf(\"%d\", &elem);\n    \n    vector<int> pows(phi);\n    pows[0] = 1;\n    for (int i = 1; i != phi; ++i)\n        pows[i] = mult(pows[i - 1], c);\n \n    // handle all \"% 491 == 0\" and \"% 499 == 0\"\n \n    vector<int> spec;\n    for (int i = 0; i < max(n, m); i += 491)\n        spec.push_back(i);\n    for (int i = 0; i < max(n, m); i += 499)\n        spec.push_back(i);\n \n    std::sort(ALL(spec));\n    spec.resize(std::unique(ALL(spec)) - spec.begin());\n    \n    int res = 0;\n \n    STAMP(\"before\");\n \n    fprintf(stderr, \"spec: %d\\n\", SZ(spec));\n \n    for (int j = 0; j != m; ++j) {\n        int j3 = (j * int64_t(j) * j) % phi;\n \n        int64_t sum = 0;\n        \n        for (int i: spec) {\n            if (i > n)\n                break;\n \n            int i2 = (i * int64_t(i)) % phi;\n            \n            int k = a[i] * b[j];\n    \n            sum += int64_t(k) * pows[(i2 * int64_t(j3)) % phi];\n        }\n \n        res = (res + sum) % mod;\n    }\n \n    STAMP(\"stage1 done\");\n \n    for (int j: spec) {\n        int j3 = (j * int64_t(j) * j) % phi;\n \n        int64_t sum = 0;\n        for (int i = 0; i != n; ++i) {\n            int i2 = (i * int64_t(i)) % phi;\n            if (j > m)\n                break;\n            \n            int k = (a[i] * b[j]);\n            \n            sum += int64_t(k) * pows[(i2 * int64_t(j3)) % phi];\n        }\n \n        res = (res + sum) % mod;\n    }\n \n    STAMP(\"stage2 done\");\n    \n    for (int i: spec)\n        for (int j: spec) {\n            if (i > n or j > m)\n                break;\n \n            int k = (a[i] * b[j]);\n            \n            int i2 = (i * int64_t(i)) % phi;\n \n            int j3 = (j * int64_t(j) * j) % phi;\n            \n            res = (res - int64_t(k) * pows[(i2 * int64_t(j3)) % phi]) % mod;\n \n            if (res < 0)\n                res += mod;\n        }\n \n    STAMP(\"stage3 done\");\n    \n    pr_pows491[0] = 1;\n    for (int i = 1; i < 491; ++i)\n        pr_pows491[i] = (pr_pows491[i - 1] * primitive491) % 491;\n \n    for (int i = 0; i < 490; ++i)\n        log491[pr_pows491[i]] = i;\n    \n    pr_pows499[0] = 1;\n    for (int i = 1; i < 499; ++i)\n        pr_pows499[i] = (pr_pows499[i - 1] * primitive499) % 499;\n \n    for (int i = 0; i < 498; ++i)\n        log499[pr_pows499[i]] = i;\n    \n    STAMP(\"before ffts\");\n \n    complex arr[2][1024][1024];\n \n    for (int i = 0; i != 2; ++i)\n        for (int j = 0; j != 1024; ++j)\n            for (int k = 0; k != 1024; ++k)\n                arr[i][j][k] = 0.0;\n \n    for (int i = 0; i != n; ++i) {\n        int x, y, z;\n        chinese_it(i, x, y, z);\n \n        if (y == 0 or z == 0)\n            continue;\n \n        y = (2 * log491[y]) % 490;\n        z = (2 * log499[z]) % 498;\n \n        arr[x][y][z] += complex(a[i], 0);\n        if (x == 1)\n            arr[0][y][z] += complex(a[i], 0);\n    }\n \n    for (int i = 0; i != m; ++i) {\n        int x, y, z;\n        chinese_it(i, x, y, z);\n \n        if (y == 0 or z == 0)\n            continue;\n \n        y = (3 * log491[y]) % 490;\n        z = (3 * log499[z]) % 498;\n \n        arr[x][y][z] += complex(0, b[i]);\n        if (x == 1)\n            arr[0][y][z] += complex(0, b[i]);\n    }\n \n    STAMP(\"prepare done\");\n    \n    precalc();\n \n    STAMP(\"precalc done\");\n \n    for (int i = 0; i != 2; ++i) {\n        for (int j = 0; j != 1024; ++j)\n            fft(arr[i][j]);\n \n        complex tmp[1024];\n        for (int k = 0; k != 1024; ++k) {\n            for (int j = 0; j != 1024; ++j)\n                tmp[j] = arr[i][j][k];\n \n            fft(tmp);\n \n            for (int j = 0; j != 1024; ++j)\n                arr[i][j][k] = tmp[j];\n        }\n    }\n \n    STAMP(\"fft1\");\n    for (int i = 0; i != 2; ++i)\n        for (int j = 0; j != 1024; ++j)\n            for (int k = 0; k != 1024; ++k)\n                arr[i][j][k] = arr[i][j][k] * arr[i][j][k];\n \n    STAMP(\"fft+fft\");\n \n    for (int i = 0; i != 2; ++i) {\n        for (int j = 0; j != 1024; ++j)\n            inv_fft(arr[i][j]);\n \n        complex tmp[1024];\n        for (int k = 0; k != 1024; ++k) {\n            for (int j = 0; j != 1024; ++j)\n                tmp[j] = arr[i][j][k];\n \n            inv_fft(tmp);\n \n            for (int j = 0; j != 1024; ++j)\n                arr[i][j][k] = tmp[j];\n        }\n    }        \n    \n    STAMP(\"fft2\");\n    \n    // cout << \"====\\n\";\n    \n    for (int i = 0; i != 2; ++i)\n        for (int j = 0; j != 1024; ++j)\n            for (int k = 0; k != 1024; ++k) {\n                int64_t val = round(arr[i][j][k].imag() / 2.0);\n \n                if (i == 0)\n                    val -= round(arr[1][j][k].imag() / 2.0);\n                \n                val %= mod;\n \n                int ip = i;\n                int jp = pr_pows491[j % 490];\n                int kp = pr_pows499[k % 498];\n        \n                res = (res + val * pows[un_chinese_it(ip, jp, kp)]) % mod;\n            }\n \n    STAMP(\"fi\");\n \n    printf(\"%d\\n\", res);\n \n    return 0;\n}",
    "tags": [
      "chinese remainder theorem",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1055",
    "index": "A",
    "title": "Metro",
    "statement": "Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.\n\nIn the city in which Alice and Bob live, the first metro line is being built. This metro line contains $n$ stations numbered from $1$ to $n$. Bob lives near the station with number $1$, while Alice lives near the station with number $s$. The metro line has two tracks. Trains on the first track go from the station $1$ to the station $n$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.\n\nSome stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.\n\nWhen the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.",
    "tutorial": "Either Bob may go directly to Alice's station, or if his train doesn't stop there, he will need to change trains as soon as possible to go in the opposite direction. It's not hard to prove that he may only need to change the trains once. If neither of the options are possible, then Bob can't come to Alice by train.",
    "tags": [
      "graphs"
    ],
    "rating": 900
  },
  {
    "contest_id": "1055",
    "index": "B",
    "title": "Alice and Hairdresser",
    "statement": "Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...\n\nTo prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $l$ centimeters after haircut, where $l$ is her favorite number. Suppose, that the Alice's head is a straight line on which $n$ hairlines grow. Let's number them from $1$ to $n$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $l$, given that \\textbf{all} hairlines on that segment had length \\textbf{strictly greater} than $l$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.\n\nAlice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types:\n\n- $0$ — Alice asks how much time the haircut would take if she would go to the hairdresser now.\n- $1$ $p$ $d$ — $p$-th hairline grows by $d$ centimeters.\n\nNote, that in the request $0$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.",
    "tutorial": "Let's consider number of current non-expandable segments that have all elements more than $l$. When an element (in this case a hairline) grows up, we can recalculate this number of segments looking at the neighbours.",
    "tags": [
      "dsu",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1055",
    "index": "C",
    "title": "Lucky Days",
    "statement": "Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days $[l_a; r_a]$ are lucky, then there are some unlucky days: $[r_a + 1; l_a + t_a - 1]$, and then there are lucky days again: $[l_a + t_a; r_a + t_a]$ and so on. In other words, the day is lucky for Alice if it lies in the segment $[l_a + k t_a; r_a + k t_a]$ for some non-negative integer $k$.\n\nThe Bob's lucky day have similar structure, however the parameters of his sequence are different: $l_b$, $r_b$, $t_b$. So a day is a lucky for Bob if it lies in a segment $[l_b + k t_b; r_b + k t_b]$, for some non-negative integer $k$.\n\nAlice and Bob want to participate in team competitions together and so they want to find out what is the largest possible number of consecutive days, which are lucky for both Alice and Bob.",
    "tutorial": "All possible shifts of Alice's and Bobs' pattern periods are the multiples of $\\mathrm{gcd}(t_a, t_b)$. You want to use such a shift that the start of their lucky days is as close as possible. Also if they can't coincide precisely, you need to try shifting in such way that Alice's lucky days start before Bob's, and the opposite.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1055",
    "index": "D",
    "title": "Refactoring",
    "statement": "Alice has written a program and now tries to improve its readability. One of the ways to improve readability is to give sensible names to the variables, so now Alice wants to rename some variables in her program. In her IDE there is a command called \"massive refactoring\", which can replace names of many variable in just one run. To use it, Alice needs to select two strings $s$ and $t$ and after that for each variable the following algorithm is performed: if the variable's name contains $s$ as a substring, then the first (and only first) occurrence of $s$ is replaced with $t$. If the name doesn't contain $s$, then this variable's name stays the same.\n\nThe list of variables is known and for each variable both the initial name and the name Alice wants this variable change to are known. Moreover, for each variable the lengths of the initial name and the target name are equal (otherwise the alignment of the code could become broken). You need to perform renaming of all variables in \\textbf{exactly one} run of the massive refactoring command or determine that it is impossible.",
    "tutorial": "Let's take all variable names that have changed. First observation is that if you trim coinciding prefixes and suffixes from the original variable names and the resulting name, you will find the part that needs to be changed. We will call it \"the core\" of the replacement. All those parts need to be exactly the same. However we don't want to create string $s$ that matches things that we don't want to get changed, so we will try to expand the pattern to the left and to the right as much as possible. Each time we will check if adjacent symbols coincide, and, if so, expand the pattern. In the end we will obtain longest possible $s$ and $t$ that may explain the differences. The final part is to check whether they actually work (this can be done with any kind of string search). Overall complexity is proportional to the size of the input.",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1055",
    "index": "E",
    "title": "Segments on the Line",
    "statement": "You are a given a list of integers $a_1, a_2, \\ldots, a_n$ and $s$ of its segments $[l_j; r_j]$ (where $1 \\le l_j \\le r_j \\le n$).\n\nYou need to select exactly $m$ segments in such a way that the $k$-th order statistic of the multiset of $a_i$, where $i$ is contained in at least one segment, is the smallest possible. If it's impossible to select a set of $m$ segments in such a way that the multiset contains at least $k$ elements, print -1.\n\nThe $k$-th order statistic of a multiset is the value of the $k$-th element after sorting the multiset in non-descending order.",
    "tutorial": "Let's find the answer using binary search. Sort segments in the order of increasing right ends. Now we are solving the following problem: how many numbers $\\le x$ we cover by $m$ segments. This may be solved with a DP along the scan line. We count how many numbers can we cover using at most $j$ of the first $i$ segments, making sure that we must always take the $i$-th segment. There are two options - either the new segment overlaps with the previous one, or not (we will ignore the case that two segments may be inside each other, because in the end it just means we can choose fewer than $m$ segments). In the case of overlap it's always optimal to choose the previous segment such that it spans as far as possible to the left (i.e. its left end is lowest). Which segment that would be for a given $i$ is easy to precompute. The case when the segments don't overlap can be implemented by a maintaining prefix maximum for all $j$. Overall complexity is $O(1500^2 \\cdot \\log 10^9)$.",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1055",
    "index": "F",
    "title": "Tree and XOR",
    "statement": "You are given a connected undirected graph without cycles (that is, a tree) of $n$ vertices, moreover, there is a non-negative integer written on every edge.\n\nConsider all pairs of vertices $(v, u)$ (that is, there are exactly $n^2$ such pairs) and for each pair calculate the bitwise exclusive or (xor) of all integers on edges of the simple path between $v$ and $u$. If the path consists of one vertex only, then xor of all integers on edges of this path is equal to $0$.\n\nSuppose we sorted the resulting $n^2$ values in non-decreasing order. You need to find the $k$-th of them.\n\nThe definition of xor is as follows.\n\nGiven two integers $x$ and $y$, consider their binary representations (possibly with leading zeros): $x_k \\dots x_2 x_1 x_0$ and $y_k \\dots y_2 y_1 y_0$ (where $k$ is any number so that all bits of $x$ and $y$ can be represented). Here, $x_i$ is the $i$-th bit of the number $x$ and $y_i$ is the $i$-th bit of the number $y$. Let $r = x \\oplus y$ be the result of the xor operation of $x$ and $y$. Then $r$ is defined as $r_k \\dots r_2 r_1 r_0$ where:\n\n$$ r_i = \\left\\{ \\begin{aligned} 1, ~ \\text{if} ~ x_i \\ne y_i \\\\ 0, ~ \\text{if} ~ x_i = y_i \\end{aligned} \\right. $$",
    "tutorial": "First observation is that we may first assign a number to each vertex that is equal to xor of all values on the path from this vertex to the root (the root itself will be assigned $0$). Then the value of any path will be equal to xor of the values written in its first and last vertices. Since the order of those values doesn't matter, let's build a binary trie of those numbers. In every node of the trie we will also store the number of values in its subtree. It's relatively easy to solve the reverse problem - to find number of paths having value not exceeding $v$. However the complexity of this is already $O(62 \\cdot n)$, so adding binary search on top of it may not work. It's possible though to recover bits of the answer one by one by descending the trie level by level and maintaining the pairs of trie nodes that give us the correct higher bits of the answer (node may be in pair with itself). At each step let's find the number of paths, whose next bit equals to $0$. In order to do this, we will go over the list of pairs. In every pair there may be two ways of obtaining $0$ as the next bit of the result: the corresponding bits of the values in the trie can be both zeros or both ones. In both cases we may compute number of paths as a product of the number of values in the corresponding subtrees. Then we sum all those numbers up over all the pairs. If the sum is greater or equal to $k$ then the next bit will be equal to $0$, otherwise it will be equal to $1$ (in this case we need to reduce $k$ by this number before proceeding to the next level). The amount of pairs at most doubles when we go one level deeper, but in total we will encounter the same node at most twice in the pairs. The complexity of this algorithm is $O(62 \\cdot n)$. Since the full trie likely won't fit into memory, so we will build it implicitly - first sort the values first and then represent trie node with a range of indices on the sorted array. This will not change the overall complexity of the solution.",
    "tags": [
      "strings",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1055",
    "index": "G",
    "title": "Jellyfish Nightmare",
    "statement": "Bob has put on some weight recently. In order to lose weight a bit, Bob has decided to swim regularly in the pool. However, the day before he went to the pool for the first time he had a weird dream. In this dream Bob was swimming along one of the pool's lanes, but also there were some jellyfish swimming around him. It's worth mentioning that jellyfish have always been one of Bob's deepest childhood fears.\n\nLet us assume the following physical model for Bob's dream.\n\n- The pool's lane is an area of the plane between lines $x=0$ and $x=w$. Bob is not allowed to swim outside of the lane, but he may touch its bounding lines if he wants.\n- The jellyfish are very small, but in Bob's dream they are extremely swift. Each jellyfish has its area of activity around it. Those areas are circles of various radii, with the jellyfish sitting in their centers. The areas of activity of two jellyfish may overlap and one area of activity may even be fully contained within another one.\n- Bob has a shape of a convex polygon.\n- Unfortunately, Bob's excess weight has made him very clumsy, and as a result he can't rotate his body while swimming. So he swims in a parallel translation pattern. However at any given moment of time he can choose any direction of his movement.\n- Whenever Bob swims into a jellyfish's activity area, it will immediately notice him and sting him very painfully. We assume that Bob has swum into the activity area if at some moment of time the intersection of his body with the jellyfish's activity area had a positive area (for example, if they only touch, the jellyfish does not notice Bob).\n- Once a jellyfish stung Bob, it happily swims away and no longer poses any threat to Bob.\n\nBob wants to swim the lane to its end and get stung the least possible number of times. He will start swimming on the line $y=-h$, and finish on the line $y=h$ where $h = 10^{10}$.",
    "tutorial": "First of all, we will solve a simpler problem: you need to check if it is possible for Bob to swim along the whole lane without any jellyfish stinging him. The position of Bob is identified by the location of his first vertex. Let's find out what are the prohibited areas for it. If a jellyfish had no activity zone and would only sting Bob only if he was swimming over it, the prohibited areas would look like polygons around every jellyfish. If we add the activity zone of radius $r$, prohibited areas will become \"inflated\" polygons. To be more precise, if the shape of Bob is a polygon $P$ they would have a shape of Minkowski sum of a polygon $-P$ with a circle of radius $r$. $-P$ here stands for the polygon inverted relative to the origin. Now, some of the areas will overlap and prohibit passing between two jellyfishes. If those two jellyfishes have activity areas of radii $r_1$ and $r_2$, centered at $(x_1, y_1)$ and $(x_2, y_2)$ respectively, Bob may not swim between them if the vector $(x_1 - x_2, y_1 - y_2)$ belongs to the Minkowski sum of $P$, $-P$ and a circle of radius $r_1 + r_2$. This may be checked by finding the distance from that vector to the polygon $P \\oplus -P$ (here $\\oplus$ stands for Minkowski sum) and comparing it with $r_1 + r_2$. One thing you need to note here is that at given constraints you can't do those computations in floating point numbers, because the relative difference between $r_1 + r_2$ and the distance from a vector to a polygon may be as low as $10^{-17}$. Therefore, you need to do all calculations in integers. Once you know pair of jellyfishes between which you cannot pass, you also need to find out if you are able to pass between the boundaries of the lane ($x=0$ and $x=w$) and the jellyfish. This allows you to construct a graph where every jellyfish and both boundaries are vertices, and the is an edge between two vertices if you cannot pass between them. One may notice that if the left boundary and right boundary are in the same connected component, then it's not possible for Bob to swim without being stung by any jellyfish. It's also possible to prove is that if they are not in the same component, then there is a safe path for Bob. Returning to the original problem, we may rephrase it like this: remove the least possible number of jellyfishes so that Bob can swim without being stung. This can be solved using min-cut by a standard trick of splitting every vertex corresponding to the jellyfish into two and adding an edge of capacity $1$ between them. The rest of the edges will have capacity $+\\infty$, left boundary will be the source, and the right boundary will be the target.",
    "tags": [],
    "rating": 3500
  },
  {
    "contest_id": "1056",
    "index": "A",
    "title": "Determine Line",
    "statement": "Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.\n\nDuring his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?",
    "tutorial": "This is a simple implementation problem. A tram line is suitable if it appears at all stops, i.e. exactly $n$ times. Make an array of $100$ integers and count how many times each integer appears. Then just output each index where the array hits $n$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1056",
    "index": "B",
    "title": "Divide Candies",
    "statement": "Arkady and his friends love playing checkers on an $n \\times n$ field. The rows and the columns of the field are enumerated from $1$ to $n$.\n\nThe friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set of candies per each cell of the field: the set of candies for cell $(i, j)$ will have exactly $(i^2 + j^2)$ candies of unique type.\n\nThere are $m$ friends who deserve the present. How many of these $n \\times n$ sets of candies can be split equally into $m$ parts without cutting a candy into pieces? Note that each set has to be split independently since the types of candies in different sets are different.",
    "tutorial": "We are asked to count the number of pairs $(i, j)$ so that $(i^2 + j^2) \\bmod m = 0$. Note that $(i^2 + j^2) \\bmod m = ((i \\bmod m)^2 + (j \\bmod m)^2) \\bmod m$. Thus the answer is equal for all pairs $(i, j)$ that have equal values $(i \\bmod m, j \\bmod m) = (x, y)$. Let's loop through all possible pairs of $(x, y)$ (there are $m^2$ of them), check if $(x^2 + y^2) \\bmod m = 0$ and if yes, add to the answer the number of suitable pairs $(i, j)$, that is easy to compute in $O(1)$. The complexity of the solution is $O(m^2)$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1056",
    "index": "C",
    "title": "Pick Heroes",
    "statement": "\\begin{quote}\nDon't you tell me what you think that I can be\n\\end{quote}\n\nIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.\n\nThere are $2$ teams each having $n$ players and $2n$ heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.\n\nThe friends estimate the power of the $i$-th of the heroes as $p_i$. Each team wants to maximize the total power of its heroes. However, there is one exception: there are $m$ pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team \\textbf{must} choose the other one on its turn. Each hero is in at most one such pair.\n\nThis is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of $q$ or greater regardless of jury's program choices, you must get $q$ or greater to pass a test.",
    "tutorial": "First suppose we have the first turn. Let's look at what total power we can grab. There are two types of heroes: those who have a special pair and those who don't. In each pair, one of the heroes will go into your team and one into the other. So the maximum we can get here is the sum of powers of the best in corresponding pairs heroes. Now consider only the heroes that don't have pairs. I claim that you and your opponent will pick heroes from this list alternating turns. Indeed, picking a \"paired\" hero doesn't change the turns order because the opponent will also pick a \"paired\" hero. From this point it is easy to see that the best you can get from \"unpaired\" heroes is the sum of powers of the first, the third, the fifth and so on heroes, if sorted in decreasing order of power. Now that we have proved the maximum constraint on our total power, let's build an algorithm that always reaches this power. If the first turn is ours, we have the initiative and the natural idea is not to lose it. Indeed, we can first pick all best \"paired\" heroes and then just keep picking the best remaining hero till the end. Since in the first part the opponent has to follow the rule about \"paired\" heroes, he won't be able to prevent us from taking the desired sum of power. If our turn is the second one, we don't have any option until all \"paired\" heroes are gone or the opponent gives the initiative back to us choosing an \"unpaired\" hero. Starting from this point we can use the same strategy as if we had the first turn. The solution can be implemented in linear time.",
    "tags": [
      "greedy",
      "implementation",
      "interactive",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1056",
    "index": "D",
    "title": "Decorate Apple Tree",
    "statement": "There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $1$ to $n$, the junction $1$ is called the root.\n\nA subtree of a junction $v$ is a set of junctions $u$ such that the path from $u$ to the root must pass through $v$. Note that $v$ itself is included in a subtree of $v$.\n\nA leaf is such a junction that its subtree contains exactly one junction.\n\nThe New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction $t$ that all light bulbs in the subtree of $t$ have different colors.\n\nArkady is interested in the following question: for each $k$ from $1$ to $n$, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to $k$?",
    "tutorial": "I'll try two describe two different approaches to this problem. A more intuitive solution. We are asked to output the number of colors for all $k$, let's reverse the problem and count the maximum $k$ for all possible number of colors $c$. We can see that if we a junction is happy then all junctions in its subtree are also happy. So we're interested in selecting some set of junctions so that their subtrees are disjoint and have no more than $c$ leaves, and we want to maximize the total size of these subtrees. This can be done greedily from the root: if a subtree is small enough, take it all, in the other case go to its children instead. We can see that a subtree is in the answer set for all $c$ not less than the size of the subtree and less than the size of the parent's subtree. We can easily compute this range for all junction in one deep-first search and sum the answer on these segments. A more professional solution. Note that a junction can be happy only when the number of colors is at least the number of leaves in it. The rule is that this is the only condition needed: indeed, if we color the leaves cyclically in the order of Euler tour, all such junctions will be happy. So the answer for the number of colors is simply the number of junctions that have at most $c$ leaves in the subtree Both solutions can be implemented in $O(n)$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1056",
    "index": "E",
    "title": "Check Transcription",
    "statement": "One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $s$ towards a faraway galaxy. Recently they've received a response $t$ which they believe to be a response from aliens! The scientists now want to check if the signal $t$ is similar to $s$.\n\nThe original signal $s$ was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal $t$, however, does not look as easy as $s$, but the scientists don't give up! They represented $t$ as a sequence of English letters and say that $t$ is similar to $s$ if you can replace all zeros in $s$ with some string $r_0$ and all ones in $s$ with some other string $r_1$ and obtain $t$. The strings $r_0$ and $r_1$ must be different and non-empty.\n\nPlease help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings $r_0$ and $r_1$) that transform $s$ to $t$.",
    "tutorial": "The solution builds on one key observation. Suppose we know the length of $r_0$. Then, since the number of '0' and '1' is fixed and the length of the resulting string is also fixed, we know the length of $r_1$ (or know, that there is no integer-sized $r_1$ possible). So let's bruteforce the length of $r_0$, calculate the length of $r_1$ and then check whether the corresponding substrings of $t$ are equal (so $r_0$ and $r_1$ can be defined correctly). Sounds like $O(|s| |t|)$ (since the number of candidates is $\\le |t|$ and check can be done in $|s|$, for example with hashes)? Haha, it is $O(|t|)$. First, notice that it is not exactly important whether we bruteforce length of $r_0$ or $r_1$ - one of them defines the other one. So suppose we are bruteforcing over the letter with larger number of occurrences in pattern string $s$. Let's denote it's number of occurrences as $c$, this way, clearly, there are at most $\\frac{|t|}{c}$ candidates. And each candidate is checked in $|s|$. So the whole time is $\\frac{|t|}{c} |s|$ Since we used the more frequent letter, $c \\ge \\frac{|s|}{2}$. And hence $\\frac{|t|}{c} |s| \\le 2|t|$.",
    "tags": [
      "brute force",
      "data structures",
      "hashing",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1056",
    "index": "F",
    "title": "Write The Contest",
    "statement": "Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of $n$ problems and lasts for $T$ minutes. Each of the problems is defined by two positive integers $a_i$ and $p_i$ — its difficulty and the score awarded by its solution.\n\nPolycarp's experience suggests that his skill level is defined with positive real value $s$, and initially $s=1.0$. To solve the $i$-th problem Polycarp needs $a_i/s$ minutes.\n\nPolycarp loves to watch series, and before solving each of the problems he will definitely watch one episode. After Polycarp watches an episode, his skill decreases by $10\\%$, that is skill level $s$ decreases to $0.9s$. Each episode takes exactly $10$ minutes to watch. When Polycarp decides to solve some problem, he firstly has to watch one episode, and only then he starts solving the problem without breaks for $a_i/s$ minutes, where $s$ is his current skill level. In calculation of $a_i/s$ no rounding is performed, only division of integer value $a_i$ by real value $s$ happens.\n\nAlso, Polycarp can train for some time. If he trains for $t$ minutes, he increases his skill by $C \\cdot t$, where $C$ is some given positive real constant. Polycarp can train only before solving any problem (and before watching series). Duration of the training can be arbitrary real value.\n\nPolycarp is interested: what is the largest score he can get in the contest? It is allowed to solve problems in any order, while training is only allowed \\textbf{before solving the first problem}.",
    "tutorial": "Firstly, if we fix some set of problems to solve, it's always optimal to solve them from the hardest one to the easiest one. That implies a solution which processes all problems and decides which of them will be solved in sorted order. Secondly, suppose Polycarp doesn't train at all, and for some fixed set of $k$ problems it will take him $10k + m$ minutes, where $10k$ is the time spent on watching the series, and $m$ is the time spent on actually solving the problems. If Polycarp would raise his skill to $s$ before solving all the problems, then it would take him $10k + \\frac{m}{s}$ minutes to solve the same set of problems in the same order. So if we fix a set of problems and compute $m$ for it, it's easy to see that if Polycarp trains for $t$ minutes, then it will take him $10k + \\frac{m}{1 + Ct} + t$ minutes to train and solve all the problems. This function $f(t) = 10k + \\frac{m}{1 + Ct} + t$ can be minimized with ternary search or some pen and paper work. This function also gives us the following: among two sets of problems with equal total score and equal number of problems it's optimal to choose the set having smaller value of $m$. So we can write a knapsack-like dynamic programming: $dp_{x, k}$ - the smallest possible value of $m$ for a set of $k$ problems with total score $x$. After computing these dynamic programming values, for a given pair $(x, k)$ it's easy to check if the time required to obtain this result does not exceed $T$: just minimize the function $f(t) = 10k + \\frac{dp_{x, k}}{1 + Ct} + t$.",
    "tags": [
      "binary search",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1056",
    "index": "G",
    "title": "Take Metro",
    "statement": "Having problems with tram routes in the morning, Arkady decided to return home by metro. Fortunately for Arkady, there is only one metro line in the city.\n\nUnfortunately for Arkady, the line is circular. It means that the stations are enumerated from $1$ to $n$ and there is a tunnel between any pair of consecutive stations as well as between the station $1$ and the station $n$. Trains that go in clockwise direction visit the stations in order $1 \\to 2 \\to 3 \\to \\ldots \\to n \\to 1$ while the trains that go in the counter-clockwise direction visit the stations in the reverse order.\n\nThe stations that have numbers from $1$ to $m$ have interior mostly in red colors while the stations that have numbers from $m + 1$ to $n$ have blue interior. Arkady entered the metro at station $s$ and decided to use the following algorithm to choose his way home.\n\n- Initially he has a positive integer $t$ in his mind.\n- If the current station has red interior, he takes a clockwise-directed train, otherwise he takes a counter-clockwise-directed train.\n- He rides exactly $t$ stations on the train and leaves the train.\n- He decreases $t$ by one. If $t$ is still positive, he returns to step $2$. Otherwise he exits the metro.\n\nYou have already realized that this algorithm most probably won't bring Arkady home. Find the station he will exit the metro at so that you can continue helping him.",
    "tutorial": "There were a variety of approaches to this problem. In all of them you first have to note that there are only $n^2$ different positions describes as pairs (station, $T \\bmod n$). Now if you manually perform several first steps to make $T \\bmod n = 0$, you will have to perform $T / n$ large steps, each of them is to have $n$ rides with $T = n$, $T = n - 1$, ..., $T = 1$. If you compute for each station the station you will end up after a large step, you will get a functional graph where you will easily find the answer, computing a period and a pre-period. The question is how to get the graph. The first approach is to be strong and code a persistent treap (or any other persistent data structure that supports split and merge). This approach is $O(n \\log(n))$. The second approach is... to rely that the cycle is not large and compute all large tests in a straightforward way. This also works fast, but we don't have a proof for that.",
    "tags": [
      "brute force",
      "data structures",
      "graphs"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1056",
    "index": "H",
    "title": "Detect Robots",
    "statement": "You successfully found poor Arkady near the exit of the station you've perfectly predicted. You sent him home on a taxi and suddenly came up with a question.\n\nThere are $n$ crossroads in your city and several bidirectional roads connecting some of them. A taxi ride is a path from some crossroads to another one without passing the same crossroads twice. You have a collection of rides made by one driver and now you wonder if this driver can be a robot or they are definitely a human.\n\nYou think that the driver can be a robot if for every two crossroads $a$ and $b$ the driver always chooses the same path whenever he drives from $a$ to $b$. Note that $a$ and $b$ here do not have to be the endpoints of a ride and that the path from $b$ to $a$ can be different. On the contrary, if the driver ever has driven two different paths from $a$ to $b$, they are definitely a human.\n\nGiven the system of roads and the description of all rides available to you, determine if the driver can be a robot or not.",
    "tutorial": "The solution is sqrt decomposition. Let's divide the rides into two groups: with length greater than $R$ and with length smaller than $R$. Now let's reformulate the problem a bit: for each pair of paths you have to check the following: for each $a$ and $b$ that appear in this order in both paths, the next crossroads after $a$ should be same in both paths. Now it's easy to check this condition for a pair of paths from the second set in a straightforward way. Now iterate through a path from the first set and any other set. Let's first the last common crossroads in the paths. Now when you iterate through all common points, it is easy to check the aforementioned condition. Choosing $R = O(\\sqrt{n})$, the solution can be implemented in $O(n\\sqrt{n})$.",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1059",
    "index": "A",
    "title": "Cashier",
    "statement": "Vasya has recently got a job as a cashier at a local store. His day at work is $L$ minutes long. Vasya has already memorized $n$ regular customers, the $i$-th of which comes after $t_{i}$ minutes after the beginning of the day, and his service consumes $l_{i}$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer.\n\nVasya is a bit lazy, so he likes taking smoke breaks for $a$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day?",
    "tutorial": "There are only $n + 1$ possible segments of time when Vasya can take breaks: between the consecutive clients, before the first client, and after the last client. If the length of the $i$-th such segment is $s$, Vasya may take at most $\\left \\lfloor \\frac{s}{a}\\right\\rfloor$ breaks, so we just sum those values over the $n + 1$ possible segments. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 1e5 + 5;\n\nint n, L, a;\nint t[maxn], l[maxn];\n\nint main(){\n\tscanf(\"%d%d%d\", &n, &L, &a);\n\tfor(int i = 0; i < n; i++){\n\t\tscanf(\"%d%d\", &t[i], &l[i]);\n\t}\n\tint start = 0;\n\tint ans = 0;\n\tfor(int i = 0; i < n; i++){\n\t\tans += (t[i] - start)/a;\n\t\tstart = t[i] + l[i];\n\t}\n\tans += (L - start)/a;\n\tprintf(\"%d\", ans);\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1059",
    "index": "B",
    "title": "Forgery",
    "statement": "Student Andrey has been skipping physical education lessons for the whole term, and now he must somehow get a passing grade on this subject. Obviously, it is impossible to do this by legal means, but Andrey doesn't give up. Having obtained an empty certificate from a local hospital, he is going to use his knowledge of local doctor's handwriting to make a counterfeit certificate of illness. However, after writing most of the certificate, Andrey suddenly discovered that doctor's signature is impossible to forge. Or is it?\n\nFor simplicity, the signature is represented as an $n\\times m$ grid, where every cell is either filled with ink or empty. Andrey's pen can fill a $3\\times3$ square without its central cell if it is completely contained inside the grid, as shown below.\n\n\\begin{center}\n\\begin{verbatim}\nxxx\nx.x\nxxx\n\\end{verbatim}\n\\end{center}\n\nDetermine whether is it possible to forge the signature on an empty $n\\times m$ grid.",
    "tutorial": "Each empty cell forbids to put a pen into every neighbor. Also, the border of the grid is forbidden. Let's mark all the forbidden cells. Now we have to check if for each filled cell there is at least one non-forbidden neighbor. Time complexity is $O(nm)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = (int)1e3 + 3;\n\nint n, m;\nchar a[maxn][maxn];\nbool can[maxn][maxn];\nvector<int> must_have[maxn][maxn];\n\ninline bool inside(int x, int y){\n\treturn x >= 0 && y >= 0 && x < n && y < m;\n}\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < m; j++)\n\t\t\tcan[i][j] = true;\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < m; j++){\n\t\t\tdo{\n\t\t\t\ta[i][j] = getc(stdin);\n\t\t\t}while(a[i][j] != '.' && a[i][j] != '#');\n\t\t\tfor(int dx = -1; dx <= 1; dx++)\n\t\t\t\tfor(int dy = -1; dy <= 1; dy++){\n\t\t\t\t\tif(abs(dx) + abs(dy) == 0 || !inside(i + dx, j + dy))continue;\n\t\t\t\t\tif(a[i][j] == '.')can[i + dx][j + dy] = false;\n\t\t\t\t\telse if (i + dx != 0 && j + dy != 0 && i + dx != n - 1 && j + dy != m - 1)must_have[i][j].push_back((i + dx) * m + j + dy);\n\t\t\t\t}\n\t\t}\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < m; j++){\n\t\t\tbool good = false;\n\t\t\tif(a[i][j] == '.')continue;\n\t\t\tfor(int cand : must_have[i][j]){\n\t\t\t\tint x = cand/m, y = cand%m;\n\t\t\t\tgood |= can[x][y];\n\t\t\t}\n\t\t\tif(!good){printf(\"NO\"); return 0;}\n\t\t}\n\tprintf(\"YES\");\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1059",
    "index": "C",
    "title": "Sequence Transformation",
    "statement": "Let's call the following process a transformation of a sequence of length $n$.\n\nIf the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $n$ integers: the greatest common divisors of all the elements in the sequence before each deletion.\n\nYou are given an integer sequence $1, 2, \\dots, n$. Find the lexicographically maximum result of its transformation.\n\nA sequence $a_1, a_2, \\ldots, a_n$ is lexicographically larger than a sequence $b_1, b_2, \\ldots, b_n$, if there is an index $i$ such that $a_j = b_j$ for all $j < i$, and $a_i > b_i$.",
    "tutorial": "The answers for $n \\le 3$ are given in the samples. Now suppose that $n \\ge 4$. The maximum result must have the earliest appearance of an integer different from $1$. If $n \\ge 4$, the earliest integer that may appear is $2$. So initially we must remove all odd integers and for each of them append $1$ to the answer. But now the rest of the answer is simply the answer for $\\left\\lfloor\\frac{n}{2}\\right\\rfloor$ multiplied by $2$. That gives us an $O(n)$ solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 1e6 + 6;\n\nint seq[maxn];\nint ans[maxn];\nint ptr = 0;\n\nvoid solve(int n, int mul){\n\tif(n == 1){ans[ptr++] = mul; return;}\n\tif(n == 2){ans[ptr++] = mul; ans[ptr++] = mul * 2; return;}\n\tif(n == 3){ans[ptr++] = mul; ans[ptr++] = mul; ans[ptr++] = mul * 3; return;}\n\tfor(int i = 0; i < n; i++)if(seq[i]&1)ans[ptr++] = mul;\n\tfor(int i = 0; i < n/2; i++)seq[i] = seq[2*i + 1]/2;\n\tsolve(n/2, mul * 2);\n}\n\nint main(){\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; i++)seq[i] = i + 1;\n\tsolve(n, 1);\n\tfor(int i = 0; i < n; i++)printf(\"%d \", ans[i]);\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1059",
    "index": "D",
    "title": "Nature Reserve",
    "statement": "There is a forest that we model as a plane and live $n$ rare animals. Animal number $i$ has its lair in the point $(x_{i}, y_{i})$. In order to protect them, a decision to build a nature reserve has been made.\n\nThe reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.\n\nFor convenience, scientists have made a transformation of coordinates so that the river is defined by $y = 0$. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve.",
    "tutorial": "If there are both positive and negative $y_i$, the answer is $-1$. Now assume that $y_i > 0$. Key observation: the answer can be binary searched. How to check if there is a valid circle with radius $R$? Firstly, the center of such circle is on the line $y = R$. Every point must be not farther than $R$ from the center. It means that the center is inside or on the boundary of all circles $(p_i, R)$. The intersection of every such circle with $y = R$ creates a segment (possibly empty). If the intersection of all such segments is non-empty, there exists some valid circle. Total complexity is $O(n\\log C)$. There is also an $O(n\\log n)$ solution, but it's much harder to implement.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long double dbl;\n\nconst dbl eps = 1e-9;\n\ninline bool gt(const dbl & x, const dbl & y){\n\treturn x > y + eps;\n}\n\ninline bool lt(const dbl & x, const dbl & y){\n\treturn y > x + eps;\n}\n\ninline dbl safe_sqrt(const dbl & D){\n\treturn D < 0 ? 0 : sqrt(D);\n}\n\nstruct pt{\n\tdbl x, y;\n\tpt(){}\n\tpt(dbl a, dbl b):x(a), y(b){}\n};\n\n\nconst int N = 1e5 + 5;\nconst int STEPS = 150;\n\nint n;\npt p[N];\n\ninline bool can(dbl R){\n\tdbl l = -1e16 - 1, r = 1e16 + 1;\n\tfor(int i = 0; i < n; i++){\n\t\tdbl b = -2 * p[i].x;\n\t\tdbl c = p[i].x * p[i].x + p[i].y * p[i].y - 2 * p[i].y * R;\n\t\tdbl D = b * b - 4 * c;\n\t\tif(lt(D, 0))\n\t\t\treturn false;\n\t\tD = safe_sqrt(D);\n\t\tdbl x1 = p[i].x - D/2, x2 = p[i].x + D/2;\n\t\tl = max(l, x1);\n\t\tr = min(r, x2);\n\t}\n\treturn !gt(l, r);\n}\n\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcin >> n;\n\tbool has_positive = false, has_negative = false;\n\tfor(int i = 0; i < n; i++){\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\tp[i] = pt(x, y);\n\t\tif(y > 0)has_positive = true;\n\t\telse has_negative = true;\n\t}\n\tif(has_positive && has_negative){\n\t\tcout << -1 << endl;\n\t\treturn 0;\n\t}\n\tif(has_negative){\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tp[i].y = -p[i].y;\n\t}\n\tdbl L = 0, R = 1e16;\n\tstd::function<dbl(dbl, dbl)> get_mid;\n\tif(can(1)){\n\t\tR = 1;\n\t\tget_mid = [](dbl l, dbl r){return (l + r)/2.0;};\n\t}\n\telse{\n\t\tL = 1;\n\t\tget_mid = [](dbl l, dbl r){return sqrt(l * r);};\n\t}\n\tfor(int step = 0; step < STEPS; step++){\n\t\tdbl mid = get_mid(L, R);\n\t\tif(can(mid))\n\t\t\tR = mid;\n\t\telse\n\t\t\tL = mid;\n\t}\n\tcout.precision(16);\n\tcout << fixed << get_mid(L, R) << endl;\n}",
    "tags": [
      "binary search",
      "geometry",
      "ternary search"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1059",
    "index": "E",
    "title": "Split the Tree",
    "statement": "You are given a rooted tree on $n$ vertices, its root is the vertex number $1$. The $i$-th vertex contains a number $w_i$. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than $L$ vertices and the sum of integers $w_i$ on each path does not exceed $S$. Each vertex should belong to exactly one path.\n\nA vertical path is a sequence of vertices $v_1, v_2, \\ldots, v_k$ where $v_i$ ($i \\ge 2$) is the parent of $v_{i - 1}$.",
    "tutorial": "There are two solutions. Both of them find the answer for each subtree in dfs: firstly for children, then for the vertex itself. In both solutions, we firstly calculate for each vertex how far up a vertical path starting at this vertex may go. It can be done with binary lifting in $O(n\\log n)$. Now let's describe the first solution. Let $dp_i$ be the answer for the subtree of the $i$-th vertex. Let $dp\\_sum_i$ be the sum of $dp_j$ where $j$ is a child of $i$. Suppose we want to include the $i$-th vertex in the path starting at some vertex $j$. Let $\\{v_k\\}$ be the set of vertices on the path between $i$ and $j$. Then the answer for $i$ in this case equals $1 + \\sum\\limits_{v_k} (dp\\_sum_{v_k} - dp_{v_k})$ (if we assume that initially $dp_i = 0$). So we need to calculate the minimum such value for all $j$ in the subtree of $i$, for which we can create a path from $j$ to $i$. Let's build a segment tree over the Euler tour of the tree. After processing vertex $i$, we add $dp\\_sum_i - dp_i$ on the segment that corresponds to the subtree of $i$. If after processing the vertex there are some vertices in it's subtree, for which there can be a vertical path to $i$, but there cannot be a vertical path to $p_i$, we set the value at the corresponding position in the Euler tour to $\\infty$. The second solution is much simpler. When calculating the answers, in case of tie let's choose the answer where the path going through the root of the subtree may go further. Then the answers can be updated greedily. Both solutions work in $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int maxn = 1e5 + 5;\nconst int lg = 20;\nconst ll inf = 1e18;\n\nint n, L;\nll S;\nint w[maxn];\nvector<int> down[maxn];\nll sum[maxn];\nint up[maxn];\nint h[maxn];\nint p[maxn][lg];\nint path[maxn];\n\ninline ll get_sum(int v){\n\treturn v == -1 ? 0 : sum[v];\n}\n\nvoid preprocess(int v, int pr = -1){\n\tsum[v] = get_sum(pr) + w[v];\n\tp[v][0] = pr;\n\th[v] = pr == -1 ? 0 : (1 + h[pr]);\n\tup[v] = v;\n\tfor(int i = 1; i < lg; i++)\n\t\tp[v][i] = p[v][i - 1] == -1 ? -1 : p[p[v][i - 1]][i - 1];\n\tint dist = L - 1;\n\tfor(int i = lg - 1; i >= 0; i--){\n\t\tif(p[up[v]][i] == -1 || (1<<i) > dist)continue;\n\t\tif(get_sum(v) - get_sum(p[up[v]][i]) + w[p[up[v]][i]] <= S){\n\t\t\tdist -= 1<<i;\n\t\t\tup[v] = p[up[v]][i];\n\t\t}\n\t}\n\tfor(int u : down[v]){\n\t\tpreprocess(u, v);\n\t}\n}\n\nint solve(int v){\n\tint ans = 0;\n\tint best = -1;\n\tfor(int u : down[v]){\n\t\tans += solve(u);\n\t\tif(path[u] == u)continue;\n\t\tif(best == -1 || h[best] > h[path[u]])\n\t\t\tbest = path[u];\n\t}\n\tif(best == -1){\n\t\tbest = up[v];\n\t\t++ans;\n\t}\n\tpath[v] = best;\n\treturn ans;\n}\n\nint main(){\n\tscanf(\"%d%d%lld\", &n, &L, &S);\n\tfor(int i = 0; i < n; i++){\n\t\tscanf(\"%d\", &w[i]);\n\t\tif(w[i] > S){printf(\"-1\"); return 0;}\n\t}\n\tfor(int i = 1; i < n; i++){\n\t\tint j;\n\t\tscanf(\"%d\", &j);\n\t\tdown[--j].push_back(i);\n\t}\n\tpreprocess(0);\n\tprintf(\"%d\", solve(0));\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1061",
    "index": "A",
    "title": "Coins",
    "statement": "You have unlimited number of coins with values $1, 2, \\ldots, n$. You want to select some set of coins having the total value of $S$.\n\nIt is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum $S$?",
    "tutorial": "Notice that using maximum value coin whenever possible will be always optimal. Hence, we can use $floor(S / n)$ coins of value $n$. Now, if $S \\mod n$ is not equal to $0$, then we need to use one more coin of valuation $S \\mod n$. Hence, our answer can be written as $ceil(S / n)$. Overall Complexity: $O(1)$",
    "code": "import java.util.*;\n \npublic class Main {\n    public static void main(String args[]) {\n        Scanner sc = new Scanner(System.in);\n \n        long n = sc.nextLong();\n        long s = sc.nextLong();\n \n        long ans = (s - 1) / n + 1;\n        System.out.print(ans);\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1061",
    "index": "B",
    "title": "Views Matter",
    "statement": "You came to the exhibition and one exhibit has drawn your attention. It consists of $n$ stacks of blocks, where the $i$-th stack consists of $a_i$ blocks resting on the surface.\n\nThe height of the exhibit is equal to $m$. Consequently, the number of blocks in each stack is less than or equal to $m$.\n\nThere is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks.\n\nFind the maximum number of blocks you can remove such that the views for both the cameras would not change.\n\nNote, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is \\textbf{no gravity} in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.",
    "tutorial": "Let's sort the array in increasing order and find the minimum number of blocks $X$ required to retain the same top and right views. Then, the answer would be $\\sum_{i=1}^{n} A_i - X$. For every $i$ from $1$ to $N$, we need to keep at least $1$ block for this stack to retain the top view. Thus, $X = X + 1$ for every $i$. However, we also need to maintain the maximum height we can cover till now, by keeping $1$ block in this stack. Let the previous best height we had be $Y$. Then, if $A[i] > Y$, then we managed to increase the height $Y$ by $1$, by keeping the block at $Y + 1$. However, if $A[i] = Y$, then we cannot increase the number of blocks in the right view, since we are only allowed to keep the current block in range $[1, Y]$. In the end, when we finish processing all the stacks, we also need to keep $max(A_i) - Y$ blocks in the longest stack, to retain the right view as it was originally. Overall complexity: $O(n \\log n)$ Refer to solution code for clarity.",
    "code": "import java.util.*;\n \npublic class Main {\n    public static void main(String args[]) {\n        Scanner sc = new Scanner(System.in);\n \n        int n = sc.nextInt();\n        int m = sc.nextInt();\n \n        long totalBlocks = 0;\n        long a[] = new long[n];\n        for(int i = 0; i < n; ++i) {\n            a[i] = sc.nextLong();\n            totalBlocks += a[i];\n        }\n \n        Arrays.sort(a);\n \n        long selected = 0;\n        for(int i = 0; i < n; ++i) {\n            if(a[i] > selected)\n                selected++;\n        }\n \n        long leftCols = a[n - 1] - selected;\n        long remBlocks = totalBlocks - leftCols - n;\n \n        System.out.print(remBlocks);\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1061",
    "index": "C",
    "title": "Multiplicity",
    "statement": "You are given an integer array $a_1, a_2, \\ldots, a_n$.\n\nThe array $b$ is called to be a subsequence of $a$ if it is possible to remove some elements from $a$ to get $b$.\n\nArray $b_1, b_2, \\ldots, b_k$ is called to be good if it is not empty and for every $i$ ($1 \\le i \\le k$) $b_i$ is divisible by $i$.\n\nFind the number of good subsequences in $a$ modulo $10^9 + 7$.\n\nTwo subsequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, the array $a$ has exactly $2^n - 1$ different subsequences (excluding an empty subsequence).",
    "tutorial": "Let's introduce the following dynamic programming approach, $dp[n][n]$, where $dp[i][j]$ indicates the number of ways to select a good subsequence of size $j$ from elements $a_1, a_2, ..., a_i$. Our final answer will be $\\sum_{i=1}^{n} dp[n][i]$. $dp[i][j] = \\begin{cases} dp[i - 1][j] + dp[i - 1][j - 1] & \\quad \\text{if } a[i] \\text{ is a multiple of } j\\\\ dp[i - 1][j] & \\quad \\text{otherwise} \\end{cases}$ Now, maintaining a 2-D dp will exceed memory limit, however notice that $dp[i]$ is calculated only on the basis of $dp[i - 1]$, hence mainitaining a 1-D dp will work. Also, now $dp[j]$ is updated if and only if $j$ is a divisor of $a[i]$. We can find divisors of a number $x$ in $O(\\sqrt{x})$. Overall Complexity : $O(n \\cdot (maxD + \\sqrt{maxA}))$. Here, $maxD$ indicates maximum number of divisors possible and $maxA$ indicates maximum value of $a_i$ possible. Also, we can use sieve to compute divisors of each number and achieve complexity of $O(maxA\\cdot log(maxA) + n \\cdot maxD)$.",
    "code": "import java.util.*;\n \npublic class Main {\n    public static void main(String args[]) {\n        Scanner sc = new Scanner(System.in);\n \n        int n = sc.nextInt();\n \n        int a[] = new int[n];\n        for(int i = 0; i < n; ++i)\n            a[i] = sc.nextInt();\n \n        int divCnt[] = new int[1000001];\n        for(int i = 1000000; i >= 1; --i) {\n            for(int j = i; j <= 1000000; j += i)\n                divCnt[j]++;\n        }\n \n        int div[][] = new int[1000001][];\n        for(int i = 1; i <= 1000000; ++i)\n            div[i] = new int[divCnt[i]];\n \n        int ptr[] = new int[1000001];\n        for(int i = 1000000; i >= 1; --i) {\n            for(int j = i; j <= 1000000; j += i)\n                div[j][ptr[j]++] = i;\n        }\n \n        long mod = (long)1e9 + 7;\n        \n        long ans[] = new long[1000001];\n        ans[0] = 1;\n \n        for(int i = 0; i < n; ++i) {\n            for(int j : div[a[i]]) {\n                ans[j] = (ans[j] + ans[j - 1]) % mod;\n            }\n        }\n \n        long fans = 0;\n        for(int i = 1; i <= 1000000; ++i) {\n            fans = (fans + ans[i]) % mod;\n        }\n \n        System.out.print(fans);\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1061",
    "index": "D",
    "title": "TV Shows",
    "statement": "There are $n$ TV shows you want to watch. Suppose the whole time is split into equal parts called \"minutes\". The $i$-th of the shows is going from $l_i$-th to $r_i$-th minute, both ends inclusive.\n\nYou need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $[l_i, r_i]$ and $[l_j, r_j]$ intersect, then shows $i$ and $j$ can't be watched simultaneously on one TV.\n\nOnce you start watching a show on some TV it is not possible to \"move\" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.\n\nThere is a TV Rental shop near you. It rents a TV for $x$ rupees, and charges $y$ ($y < x$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $[a; b]$ you will need to pay $x + y \\cdot (b - a)$.\n\nYou can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $10^9 + 7$.",
    "tutorial": "Solution: Sort the TV shows on the basis of their starting time. Now, we start allocating TVs greedily to the shows. For any show $i$, we allocate a new TV only if there is no old TV where the show ends at $r_o$, such that $r_o < l_i$ and $(l_i - r_o) \\cdot y <= x$. Also, if there are many such old TVs, then we use the TV where $r_o$ is maximum. Proof: Notice that there is a minimal cost of $\\sum_{i=1}^{n} (r_i - l_i) \\cdot y$, which will always be added. Hence, the optimal solution completely depends on the rent of new TV and the time wasted on old TVs. Now, lets try to prove that allocating an old TV with maximum $r_o$ is optimal. Suppose we are allocating a TV to show $i$. Let's consider two old TVs $o1$ and $o2$, such that $r_{o1} < r_{o2} < l_i$ and $(l_i - r_{o1}) \\cdot y <= x$. In such a case, it is possible to allocate both the TVs to this show. For choosing which TV to be allocated let's consider the three possible cases: Case I: There is no show $j (j > i)$, such that $(l_j - r_{o2}) \\cdot y <= x$. In this case, it would be better to allocate TV $o2$ to show $i$, since $(l_i - r_{o2}) \\cdot y < (l_i - r_{o1}) \\cdot y$. Hence, allocating TV $o2$ to show $i$ is optimal in this case. Case II: There are shows $j (j > i)$, such that $(l_j - r_{o2}) \\cdot y <= x$; but there is no show $j (j > i)$, such that $(l_j - r_{o1}) \\cdot y <= x$. In this case, if we allocate TV $o1$ to show $i$ and TV $o2$ to show $j$, then the cost will be $(l_j - r_{o2}) \\cdot y + (l_i - r_{o1}) \\cdot y$. And, if we allocate TV $o2$ to show $i$, then we need to buy a new TV for show $j$ and our cost will be $x +(l_i - r_{o2}) \\cdot y$. Now, as $(l_j - r_{o1}) \\cdot y > x$, $(l_j - r_{o2}) \\cdot y + (l_i - r_{o1}) \\cdot y > x +(l_i - r_{o2}) \\cdot y$. Hence, allocating TV $o2$ instead of TV $o1$ to show $i$ is optimal in this case. Case III: There are shows $j (j > i)$, such that $(l_j - r_{o1}) \\cdot y <= x$. In this case, if we allocate TV $o1$ to show $i$, cost will be $(l_i - r_{o1}) \\cdot y + (l_j - r_{o2}) \\cdot y$. If we allocate TV $o2$ to show $i$, cost will be $(l_i - r_{o2}) \\cdot y + (l_j - r_{o1}) \\cdot y$. Here, we can see that in both of the allocations, the cost is $(l_i + l_j - r_{o1} - r_{o2}) \\cdot y$ and so any allocation is optimal here. Hence, we can see that if more than one old TVs are available, allocating the one with maximum $r_o$ is always optimal. Overall Complexity: $O(n \\cdot \\log n)$",
    "code": "import java.util.*;\n \npublic class Main {\n    public static void main(String args[]) {\n        Scanner sc = new Scanner(System.in);\n \n        int n = sc.nextInt();\n \n        long x = sc.nextLong();\n        long y = sc.nextLong();\n \n        Show show[] = new Show[n];\n        for(int i = 0; i < n; ++i)\n            show[i] = new Show(sc.nextLong(), sc.nextLong());\n \n        Arrays.sort(show, new Comparator<Show>() {\n            public int compare(Show s1, Show s2) {\n                if(s1.l > s2.l)\n                    return 1;\n                if(s1.l < s2.l)\n                    return -1;\n                return 0;\n            }\n        });\n \n        PriorityQueue<Long> queue = new PriorityQueue<>(new Comparator<Long>() {\n            public int compare(Long l1, Long l2) {\n                if(l1 < l2)\n                    return -1;\n                if(l1 > l2)\n                    return 1;\n                return 0; \n            }\n        });\n \n        long ans = 0;\n        Stack<Long> stack = new Stack<>();\n        for(int i = 0; i < n; ++i) {\n            long l = show[i].l;\n            long r = show[i].r;\n \n            while(queue.size() != 0 && queue.peek() < l)\n                stack.push(queue.poll());\n \n            if(stack.size() == 0) {\n                ans += x + (r - l) * y;\n                ans %= 1000000007;\n            }\n            else {\n                if((l - stack.peek()) * y < x) {\n                    ans += (r - stack.pop()) * y;\n                    ans %= 1000000007;\n                }\n                else {\n                    ans += x + (r - l) * y;\n                    ans %= 1000000007;\n                }\n            }\n \n            queue.add(r);\n        }\n \n        System.out.print(ans);\n    }\n}\nclass Show {\n    long l, r;\n    Show(long a, long b) {\n        l = a;\n        r = b;\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1061",
    "index": "E",
    "title": "Politics",
    "statement": "There are $n$ cities in the country.\n\nTwo candidates are fighting for the post of the President. The elections are set in the future, and both candidates have already planned how they are going to connect the cities with roads. Both plans will connect all cities using $n - 1$ roads only. That is, each plan can be viewed as a tree. Both of the candidates had also specified their choice of the capital among $n$ cities ($x$ for the first candidate and $y$ for the second candidate), which may or may not be same.\n\nEach city has a potential of building a port (one city can have at most one port). Building a port in $i$-th city brings $a_i$ amount of money. However, each candidate has his specific demands. The demands are of the form:\n\n- $k$ $x$, which means that the candidate wants to build exactly $x$ ports in the subtree of the $k$-th city of his tree (the tree is rooted at the capital of his choice).\n\nFind out the maximum revenue that can be gained while fulfilling all demands of both candidates, or print -1 if it is not possible to do.\n\nIt is additionally guaranteed, that each candidate has specified the port demands for the capital of his choice.",
    "tutorial": "Let's create a graph with a source, sink and two layers. Let the left layer denote the nodes of tree $1$ and right layer denote the nodes of tree $2$. Let's denote $x_i$ as the demand of the $i^{th}$ node. For a demand $(k, x)$ in tree 1, we add an edge from source to node $k$ in the left layer with $cost = 0$ and $capacity = x - \\sum x_j$, such that $j$ is not equal to $i$ and $j$ belongs to the subtree of $i$. Similarly for a demand $(k, x)$ in tree 2, we add an edge from node $k$ in the right layer to sink with $cost = 0$ and $capacity = x - \\sum x_j$, such that $j$ is not equal to $i$ and $j$ belongs to the subtree of $i$. Now, for every node $i$, let $\\text{col1}_i$ be the closest node to $i$, such that $i$ belongs to subtree of $\\text{col1}_i$ and the demand of $\\text{col1}_i$ in tree $1$ has been provided. Similarly $\\text{col2}_i$ be the closest node to $i$, such that $i$ belongs to subtree of $\\text{col2}_i$ and the demand of $\\text{col2}_i$ in tree $2$ has been provided. For every node $i$, we add an edge from $\\text{col}1_i$ in left layer to $\\text{col2}_i$ in right layer with $capacity = 1$ and $cost = -a_i$. Now, when we run min cost max flow on this graph, our answer will be negative of the minimum cost obtained. Overall Complexity: $O(n^3)$ using MCMF with bellman ford; $O(n^2 \\cdot \\log n)$ using MCMF with Dijkstra.",
    "code": "import java.util.*;\nimport static java.lang.Math.*;\n \npublic class MainE {\n    static int dfs(int i, int par, int[] flow, int[] col, int curCol) {\n        if(req[i] != -1)\n            curCol = i;\n        col[i] = curCol;\n \n        int cost = 0;\n \n        for(int j : adj[i]) {\n            if(j != par)\n                cost += dfs(j, i, flow, col, curCol);\n        }\n \n        if(req[i] != -1) {\n            if(cost > req[i]) {\n                flag = 1;\n            }\n            flow[i] = req[i] - cost;\n            cost = req[i];\n        }\n \n        return cost;\n    }\n \n    static int flag = 0;\n    static ArrayList<Integer> adj[];\n    static int req[];\n \n    public static void main(String args[]) {\n        Scanner sc = new Scanner(System.in);\n \n        int n = sc.nextInt();\n        int capital1 = sc.nextInt() - 1;\n        int capital2 = sc.nextInt() - 1;\n \n        int maxVal = 0;\n        int a[] = new int[n];\n        for(int i = 0; i < n; ++i) {\n            a[i] = sc.nextInt();\n            maxVal = max(maxVal, a[i]);\n        }\n \n        ArrayList<Integer> adj1[] = new ArrayList[n];\n        for(int i = 0; i < n; ++i)\n            adj1[i] = new ArrayList<>();\n        for(int i = 0; i < n - 1; ++i) {\n            int u = sc.nextInt() - 1;\n            int v = sc.nextInt() - 1;\n            adj1[u].add(v);\n            adj1[v].add(u);\n        }\n \n        ArrayList<Integer> adj2[] = new ArrayList[n];\n        for(int i = 0; i < n; ++i)\n            adj2[i] = new ArrayList<>();\n        for(int i = 0; i < n - 1; ++i) {\n            int u = sc.nextInt() - 1;\n            int v = sc.nextInt() - 1;\n            adj2[u].add(v);\n            adj2[v].add(u);\n        }\n \n        adj = new ArrayList[n];\n        for(int i = 0; i < n; ++i)\n            adj[i] = adj1[i];\n \n        req = new int[n];\n        int q = sc.nextInt();\n        Arrays.fill(req, -1);\n \n        for(int i = 0; i < q; ++i) {\n            int ind = sc.nextInt() - 1;\n            req[ind] = sc.nextInt();\n        }\n        int reqFlow1 = req[capital1];\n \n        int col[] = new int[n];\n        int flow[] = new int[n];\n        Arrays.fill(flow, 1000);\n        dfs(capital1, -1, flow, col, capital1); \n        if(flag == 1) {\n            System.out.print(\"-1\");\n            return;\n        }\n \n        adj = new ArrayList[n];\n        for(int i = 0; i < n; ++i)\n            adj[i] = adj2[i];\n \n        req = new int[n];\n        q = sc.nextInt();\n        Arrays.fill(req, -1);\n \n        for(int i = 0; i < q; ++i) {\n            int ind = sc.nextInt() - 1;\n            req[ind] = sc.nextInt();\n        }\n        int reqFlow2 = req[capital2];\n \n        if(reqFlow1 != reqFlow2) {\n            System.out.print(\"-1\");\n            return;\n        }\n \n        int col2[] = new int[n];\n        int flow2[] = new int[n];\n        Arrays.fill(flow2, 1000);\n        dfs(capital2, -1, flow2, col2, capital2);  \n        if(flag == 1) {\n            System.out.print(\"-1\");\n            return;\n        }\n \n        List<Edge>[] graph = createGraph(2 * n + 2);\n        int source = 0, sink = 2 * n + 1;\n        for(int i = 0; i < n; ++i) {\n            addEdge(graph, source, i + 1, flow[i], 0);\n            addEdge(graph, n + i + 1, sink, flow2[i], 0);\n            addEdge(graph, col[i] + 1, n + col2[i] + 1, 1, -a[i] + maxVal);\n        }\n \n        int[] ans = minCostFlow(graph, source, sink, n);\n        if(ans[0] != reqFlow1) {\n            System.out.print(\"-1\");\n            return;\n        }\n \n        int fans = ans[1] - maxVal * reqFlow1;\n        fans = -fans;\n \n        System.out.print(fans);\n    }\n \n    static class Edge {\n        int to, f, cap, cost, rev;\n \n        Edge(int v, int cap, int cost, int rev) {\n          this.to = v;\n          this.cap = cap;\n          this.cost = cost;\n          this.rev = rev;\n        }\n    }\n \n    static List<Edge>[] createGraph(int n) {\n        List<Edge>[] graph = new List[n];\n        for (int i = 0; i < n; i++)\n            graph[i] = new ArrayList<>();\n        return graph;\n    }\n \n    static void addEdge(List<Edge>[] graph, int s, int t, int cap, int cost) {\n        graph[s].add(new Edge(t, cap, cost, graph[t].size()));\n        graph[t].add(new Edge(s, 0, -cost, graph[s].size() - 1));\n    }\n \n    static void bellmanFord(List<Edge>[] graph, int s, int[] dist) {\n        int n = graph.length;\n        Arrays.fill(dist, Integer.MAX_VALUE);\n        dist[s] = 0;\n        boolean[] inqueue = new boolean[n];\n        int[] q = new int[n];\n        int qt = 0;\n        q[qt++] = s;\n        for (int qh = 0; (qh - qt) % n != 0; qh++) {\n          int u = q[qh % n];\n          inqueue[u] = false;\n          for (int i = 0; i < graph[u].size(); i++) {\n            Edge e = graph[u].get(i);\n            if (e.cap <= e.f)\n              continue;\n            int v = e.to;\n            int ndist = dist[u] + e.cost;\n            if (dist[v] > ndist) {\n              dist[v] = ndist;\n              if (!inqueue[v]) {\n                inqueue[v] = true;\n                q[qt++ % n] = v;\n              }\n            }\n          }\n        }\n      }\n \n    static int[] minCostFlow(List<Edge>[] graph, int s, int t, int maxf) {\n        int n = graph.length;\n        int[] prio = new int[n];\n        int[] curflow = new int[n];\n        int[] prevedge = new int[n];\n        int[] prevnode = new int[n];\n        int[] pot = new int[n];\n \n        // bellmanFord invocation can be skipped if edges costs are non-negative\n        bellmanFord(graph, s, pot);\n        int flow = 0;\n        int flowCost = 0;\n        while (flow < maxf) {\n            PriorityQueue<Long> q = new PriorityQueue<>();\n            q.add((long) s);\n            Arrays.fill(prio, Integer.MAX_VALUE);\n            prio[s] = 0;\n            boolean[] finished = new boolean[n];\n            curflow[s] = Integer.MAX_VALUE;\n            while (!finished[t] && !q.isEmpty()) {\n                long cur = q.remove();\n                int u = (int) (cur & 0xFFFF_FFFFL);\n                int priou = (int) (cur >>> 32);\n                if (priou != prio[u])\n                  continue;\n                finished[u] = true;\n                for (int i = 0; i < graph[u].size(); i++) {\n                    Edge e = graph[u].get(i);\n                    if (e.f >= e.cap)\n                        continue;\n                    int v = e.to;\n                    int nprio = prio[u] + e.cost + pot[u] - pot[v];\n                    if (prio[v] > nprio) {\n                        prio[v] = nprio;\n                        q.add(((long) nprio << 32) + v);\n                        prevnode[v] = u;\n                        prevedge[v] = i;\n                        curflow[v] = Math.min(curflow[u], e.cap - e.f);\n                    }\n                }\n            }\n            if (prio[t] == Integer.MAX_VALUE)\n                break;\n            for (int i = 0; i < n; i++)\n                if (finished[i])\n                    pot[i] += prio[i] - prio[t];\n            int df = Math.min(curflow[t], maxf - flow);\n            flow += df;\n            for (int v = t; v != s; v = prevnode[v]) {\n                Edge e = graph[prevnode[v]].get(prevedge[v]);\n                e.f += df;\n                graph[v].get(e.rev).f -= df;\n                flowCost += df * e.cost;\n            }\n        }\n        return new int[]{flow, flowCost};\n    }\n}",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1061",
    "index": "F",
    "title": "Lost Root",
    "statement": "The graph is called tree if it is connected and has no cycles. Suppose the tree is rooted at some vertex. Then tree is called to be perfect $k$-ary tree if each vertex is either a leaf (has no children) or has exactly $k$ children. Also, in perfect $k$-ary tree all leafs must have same depth.\n\nFor example, the picture below illustrates perfect binary tree with $15$ vertices:\n\nThere is a perfect $k$-ary tree with $n$ nodes. The nodes are labeled with distinct integers from $1$ to $n$, however you don't know how nodes are labelled. Still, you want to find the label of the root of the tree.\n\nYou are allowed to make at most $60 \\cdot n$ queries of the following type:\n\n- \"? $a$ $b$ $c$\", the query returns \"Yes\" if node with label $b$ lies on the path from $a$ to $c$ and \"No\" otherwise.\n\nBoth $a$ and $c$ are considered to be lying on the path from $a$ to $c$.\n\nWhen you are ready to report the root of the tree, print\n\n- \"! $s$\", where $s$ is the label of the root of the tree.\n\nIt is possible to report the root only once and this query is not counted towards limit of $60 \\cdot n$ queries.",
    "tutorial": "This solution had many randomized approaches, some with higher probability of passing and some with lower probability of passing. The author's solution (there exist better solutions with even lower probability of failure - comment yours below) is as follows: Part 1: Checking if a node is a leaf node: It can be done in $O(n)$ queries. Suppose candidate node is $X$ Generate a random node $Y (!=X)$ For all $Z$, if $Y$ $X$ $Z$ is $false$, then $X$ is a leaf node, otherwise is not. Part 2: Finding a leaf node: Generate a random node and check if it is a leaf node. Probability of getting a lead node is $>=0.5$. Higher the $K$, higher the probability. So we can find a leaf node in $O(20\\cdot n)$ queries with failure probability $(1/2)^{20}$ Part 3: Generating a leaf node in other subtree of the actual root: Fix a random node (that is not the same as the leaf node, $L1$, that we found), check if it is a leaf node, and if it is a leaf node and check if $2h-1$ nodes separate Leaf $1$ and this current leaf. If yes, we have found two separate leaf nodes and the $2h-1$ candidate nodes for the root. We can use $O(40\\cdot n)$ queries to ensure a failure probability of $(1/2)^{20}$ Finally: Instead of checking all of them separately in $2H\\cdot N$, we can fix their order in $O(H^2)$ by finding each node's appropriate position by placing them incrementally. Let the initial path be $L1$ $L2$, then we add $X$ to get $L1$ $X$ $L2$. Now to find $Y$'s appropriate position, we check if it lies between $L1$, $X$ or $X$, $L2$. And so on. In the final order, the middle node would be the root.",
    "code": "import java.util.*;\n \npublic class Main {\n\tstatic HashMap<Long, Boolean> map = new HashMap<>();\n    static long getHash(long a, long b, long c) {\n        return (long)(n + 1) * (long)(n + 1) * a + (long)(n + 1) * b + c;\n    }\n    static boolean check(int a, int b, int c) {\n        long hashV = getHash(a, b, c);\n \n        if(map.get(hashV) != null)\n            return map.get(hashV);\n \n        // b in path a -> c\n        System.out.println(\"? \" + a + \" \" + b + \" \" + c);\n        System.out.flush();\n        String s = sc.next();\n \n        map.put(hashV, s.equals(\"Yes\"));\n \n        return map.get(hashV);\n    }\n    static int findHeight(int x) {\n        int nodes = 0;\n \n        int anotherNode = rand.nextInt(n) + 1;\n        while(anotherNode == x)\n            anotherNode = rand.nextInt(n) + 1;\n \n        for(int i = 1; i <= n; ++i) {\n            if(check(anotherNode, x, i))\n                nodes++;\n        }\n \n        if(level.get(nodes) == null) \n            return level.get(n - nodes) + 1;\n        else\n            return level.get(nodes);\n    }\n    static int findDist(int a, int b) {\n        int ans = 0;\n        for(int i = 1; i <= n; ++i) {\n            if(check(a, i, b))\n                ans++;\n        }\n        return ans;\n    }\n    static void printAns(int ans) {\n        System.out.println(\"! \" + ans);\n        System.out.flush();\n    }\n    static int findLCA(int a, int b) {\n        ArrayList<Integer> list = new ArrayList<>();\n        for(int i = 1; i <= n; ++i) {\n            if(i == a || i == b)\n                continue;\n \n            if(check(a, i, b))\n                list.add(i);\n        }\n \n        ArrayList<Integer> path = new ArrayList<>();\n        path.add(a);\n \n        int vis[] = new int[list.size()];\n        for(int i = 0; i < list.size(); ++i) {\n            int selectedInd = -1;\n            for(int j = 0; j < list.size(); ++j) {\n                if(vis[j] == 0) {\n                    if(selectedInd == -1)\n                        selectedInd = j;\n                    else if(check(a, list.get(j), list.get(selectedInd)))\n                        selectedInd = j;\n                }\n            }\n            path.add(list.get(selectedInd));\n            vis[selectedInd] = 1;\n        }\n \n        int rootInd = height - height1;\n \n        return path.get(rootInd);\n    }\n    static int n, k;\n    static HashMap<Integer, Integer> level;\n    static int height, height1;\n    static Random rand;\n    static Scanner sc;\n    public static void main(String args[]) {\n        sc = new Scanner(System.in);\n        rand = new Random();\n \n        n = sc.nextInt();\n        k = sc.nextInt();\n \n        if(n == 1) {\n            printAns(1);\n            return;\n        }\n \n        height = 0;\n        int remNodes = n * k - n + 1;\n        while(remNodes != 1) {\n            height++;\n            remNodes /= k;\n        }\n \n        int nodes[] = new int[height + 1];\n        nodes[1] = 1;\n        level = new HashMap<>();\n        level.put(1, 1);\n        for(int i = 2; i <= height; ++i) {\n            nodes[i] = k * nodes[i - 1] + 1;\n            level.put(nodes[i], i);\n        }\n \n        int node1 = rand.nextInt(n) + 1;\n        height1 = findHeight(node1);\n \n        if(height1 == height) {\n            printAns(node1);\n            return;\n        }\n \n        HashSet<Integer> alrSet = new HashSet<>();\n        alrSet.add(node1);\n \n        int node2 = -1;\n \n        while(true) {\n            node2 = rand.nextInt(n) + 1;\n            while(alrSet.contains(node2)) \n                node2 = rand.nextInt(n) + 1;\n \n            alrSet.add(node2);\n            \n            int height2 = findHeight(node2);\n \n            if(height2 == height) {\n                printAns(node2);\n                return;\n            }\n \n            int dist = findDist(node1, node2);\n \n            if(height1 + height2 + dist - 2 == 2 * height - 1) \n                break;\n        }\n \n        int fans = findLCA(node1, node2);\n        printAns(fans);\n    }\n}",
    "tags": [
      "interactive",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1062",
    "index": "A",
    "title": "A Prank",
    "statement": "JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array $a_1$, $a_2$, ..., $a_n$ of integers, such that $1 \\le a_1 < a_2 < \\ldots < a_n \\le 10^3$, and then went to the bathroom.\n\nJATC decided to prank his friend by erasing some \\textbf{consecutive elements} in the array. Since he doesn't want for the prank to go too far, he will only erase in a way, such that Giraffe can still restore the array using the information from the remaining elements. Because Giraffe has created the array, he's \\textbf{also aware} that it's an increasing array and all the elements are integers in the range $[1, 10^3]$.\n\nJATC wonders what is the greatest number of elements he can erase?",
    "tutorial": "Since $1 \\le a_i \\le 10^3$ for all $i$, let set $a_0=0$ and $a_{n+1}=1001$. For every $i,j$ such that $0 \\le i<j \\le n+1$, if $a_j-j=a_i-i$ then we can erase all the elements between $i$ and $j$ (not inclusive). So just check for all the valid pairs and maximize the answer. Time complexity: $O(n^2)$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1062",
    "index": "B",
    "title": "Math",
    "statement": "JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer $n$, you can perform the following operations zero or more times:\n\n- mul $x$: multiplies $n$ by $x$ (where $x$ is an arbitrary positive integer).\n- sqrt: replaces $n$ with $\\sqrt{n}$ (to apply this operation, $\\sqrt{n}$ must be an integer).\n\nYou can perform these operations as many times as you like. What is the minimum value of $n$, that can be achieved and what is the minimum number of operations, to achieve that minimum value?\n\nApparently, no one in the class knows the answer to this problem, maybe you can help them?",
    "tutorial": "By factorizing $n$ we get $n={p_1}^{a_1}{p_2}^{a_2}\\dots{p_k}^{a_k}$ ($k$ is the number of prime factors). Because we can't get rid of those prime factors then the smallest $n$ is ${p_1}{p_2}\\dots{p_k}$. For each $a_i$, let $u_i$ be the positive integer so that $2^{u_i} \\ge a_i>2^{u_i-1}$. Let $U$ be $max(u_i)$. It's clear that we have to apply the \"$sqrt$\" operation at least $U$ times, since each time we apply it, $a_i$ is divided by $2$ for all $i$. If for all $i$, $a_i=2^U$ then the answer is $U$, obviously. Otherwise, we need to use the operation \"$mul$\" $1$ time to make all the $a_i$ equal $2^U$ and by now the answer is $U+1$. Complexity: $O(sqrt(N))$",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1062",
    "index": "C",
    "title": "Banh-mi",
    "statement": "JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.\n\nFirst, he splits the Banh-mi into $n$ parts, places them on a row and numbers them from $1$ through $n$. For each part $i$, he defines the deliciousness of the part as $x_i \\in \\{0, 1\\}$. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the $i$-th part then his enjoyment of the Banh-mi will increase by $x_i$ and the deliciousness of all the remaining parts will also increase by $x_i$. The initial enjoyment of JATC is equal to $0$.\n\nFor example, suppose the deliciousness of $3$ parts are $[0, 1, 0]$. If JATC eats the second part then his enjoyment will become $1$ and the deliciousness of remaining parts will become $[1, \\_, 1]$. Next, if he eats the first part then his enjoyment will become $2$ and the remaining parts will become $[\\_, \\_, 2]$. After eating the last part, JATC's enjoyment will become $4$.\n\nHowever, JATC doesn't want to eat all the parts but to save some for later. He gives you $q$ queries, each of them consisting of two integers $l_i$ and $r_i$. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range $[l_i, r_i]$ in some order.\n\nAll the queries are independent of each other. Since the answer to the query could be very large, print it modulo $10^9+7$.",
    "tutorial": "For each part that we choose, we need to calculate how many times that element is added to our score. You can see that, the first element that we choose is added $2^{k-1}$ times in our score ($k=r-l+1$), the second element is added $2^{k-2}$ times and so on. Therefore, we just need to choose all the $1s$ first and then all the remaining parts. The final score is $(2^x-1) \\cdot 2^y$, where $x$ is the number of $1s$ and $y$ is the number of $0s$. Complexity: $O(n + Q)$.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1062",
    "index": "D",
    "title": "Fun with Integers",
    "statement": "You are given a positive integer $n$ greater or equal to $2$. For every pair of integers $a$ and $b$ ($2 \\le |a|, |b| \\le n$), you can transform $a$ into $b$ if and only if there exists an integer $x$ such that $1 < |x|$ and ($a \\cdot x = b$ or $b \\cdot x = a$), where $|x|$ denotes the absolute value of $x$.\n\nAfter such a transformation, your score increases by $|x|$ points and you are \\textbf{not allowed} to transform $a$ into $b$ nor $b$ into $a$ anymore.\n\nInitially, you have a score of $0$. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?",
    "tutorial": "For every integer $x$ $(1 \\le x \\le n)$, let's call $D$ the set of integers that are able to be transformed into $x$. As you can see, if $a$ could be transformed into $b$ then $-a$ could also be transformed into $b$. Therefore $|D|$ is always even. Let's build a graph consists of $2n-2$ nodes, numbered $-n$ through $n$ (except for $-1$, $0$, and $1$). There is an weighted undirected edge between node $u$ and $v$ if and only if $u$ can be transformed into $v$. The weight of the edge is the score of the transformation. Every node in the graph has an even degree so you can split the graph into some connected components so that each components is an Euler circuit (a circuit that contains all the edges). Therefore you just need to find all those Euler circuits and maximize your score. Moreover, you can see that, if an integer $a$ can be transformed into $b$ then $x$ and $2$ are in the same component. Proof: Suppose $a<b$, there exists an integer $x=b/a$. If $x=2$ then it is proved, otherwise there exists an integer $c=2x<b \\le n$. $c$ and $2$ are in the same component so $x$ and $2$ are also in the same component. Therefore, if we ignore all the nodes that have no edges attached to it, the graph will be connected. So you need to simply get the sum of all the weights of the edges. The complexity is $O(n + nlog(n))$ since the number of edges can go up to $nlog(n)$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1062",
    "index": "E",
    "title": "Company",
    "statement": "The company $X$ has $n$ employees numbered from $1$ through $n$. Each employee $u$ has a direct boss $p_u$ ($1 \\le p_u \\le n$), except for the employee $1$ who has no boss. It is guaranteed, that values $p_i$ form a tree. Employee $u$ is said to be in charge of employee $v$ if $u$ is the direct boss of $v$ or there is an employee $w$ such that $w$ is in charge of $v$ and $u$ is the direct boss of $w$. Also, any employee is considered to be in charge of himself.\n\nIn addition, for each employee $u$ we define it's level $lv(u)$ as follow:\n\n- $lv(1)=0$\n- $lv(u)=lv(p_u)+1$ for $u \\neq 1$\n\nIn the near future, there are $q$ possible plans for the company to operate. The $i$-th plan consists of two integers $l_i$ and $r_i$, meaning that all the employees in the range $[l_i, r_i]$, and only they, are involved in this plan. To operate the plan smoothly, there must be a project manager who is an employee in charge of \\textbf{all} the involved employees. To be precise, if an employee $u$ is chosen as the project manager for the $i$-th plan then for every employee $v \\in [l_i, r_i]$, $u$ must be in charge of $v$. Note, that $u$ is not necessary in the range $[l_i, r_i]$. Also, $u$ is always chosen in such a way that $lv(u)$ is as large as possible (the higher the level is, the lower the salary that the company has to pay the employee).\n\nBefore any plan is operated, the company has JATC take a look at their plans. After a glance, he tells the company that for every plan, it's possible to reduce the number of the involved employees \\textbf{exactly} by one without affecting the plan. Being greedy, the company asks JATC which employee they should kick out of the plan so that the level of the project manager required is as large as possible. JATC has already figured out the answer and challenges you to do the same.",
    "tutorial": "Let's call $in_u$ the time that we reach the node $u$ in depth first search and $out_u=max(in_{v1}, in_{v2}, \\cdots, in_{vk})$ where $v_i$ is a child of $u$. If node $u$ is in charge of node $v$ ($u$ is an ancestor of $v$) then $in_u \\le in_v \\le out_u$. Suppose we don't have to ignore any node then the answer to each query is the LCA of two nodes $u$ and $v$ ($l \\le u,v \\le r$), where $u$ and $v$ are chosen so that $in_u=max(in_l, in_{l+1}, \\dots, in_r)$ and $in_v=min(in_l,in_{l+1}, \\dots, in_r)$. Proof: Let $r$ be the LCA of $u$ and $v$, then $in_r \\le in_v \\le in_u \\le out_r$. For every node $w \\in [l,r]$, $in_v \\le in_w \\le in_u \\Rightarrow in_r \\le in_w \\le out_r \\Rightarrow r$ is an ancestor of $w$. Therefore, the node that needs to be ignored is either $u$ or $v$. Suppose we ignore $u$, the query splits into two halves $[l,u-1] \\cup [u+1,r]$. We find the LCA to each half and get the LCA of them. We do similarly for $v$ and optimize the answer. Complexity: $O(Nlog(N) + Qlog(N))$.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1062",
    "index": "F",
    "title": "Upgrading Cities",
    "statement": "There are $n$ cities in the kingdom $X$, numbered from $1$ through $n$. People travel between cities by some \\textbf{one-way} roads. As a passenger, JATC finds it weird that from any city $u$, he can't start a trip in it and then return back to it using the roads of the kingdom. That is, the kingdom can be viewed as an acyclic graph.\n\nBeing annoyed by the traveling system, JATC decides to meet the king and ask him to do something. In response, the king says that he will upgrade some cities to make it easier to travel. Because of the budget, the king will only upgrade those cities that are important or semi-important. A city $u$ is called important if for every city $v \\neq u$, there is either a path from $u$ to $v$ or a path from $v$ to $u$. A city $u$ is called semi-important if it is not important and we can destroy exactly one city $v \\neq u$ so that $u$ becomes important.\n\nThe king will start to act as soon as he finds out all those cities. Please help him to speed up the process.",
    "tutorial": "The main idea of this problem is to calculate $in_u$ and $out_u$ for every node $u$, where $in_u$ denotes the number of nodes that can reach $u$ and $out_u$ denotes the number of nodes that can be reached by $u$. If $in_u+out_u=N+1$ then $u$ is important or $N$ if $u$ is semi-important. However, it may not possible to calculate $in_u$ and $out_u$ for every node $u$ in given time (please tell me if it's possible) so we have to do some tricks. First of all, we need to find an arbitrary longest path ($P$)$=s_1 \\rightarrow s_2 \\rightarrow... \\rightarrow s_k$ on the graph ($k$ is the number of nodes on this path). If a node is important then it must lie on this path ($1$). Proof: Assume there is a node $u$ that is important and doesn't lie on ($P$). Let $s_i$ be the rightmost node on ($P$) and can reach $u$. It's true that $i < k$, because if $i=k$ then we have a longer path than the one we found so it's not possible. By definition of $i$, $s_{i+1}$ cannot reach $u$. Therefore $u$ must be able to reach $s_{i+1}$ (because $u$ is important). This leads to a conflict: We have a path that is longer than the one we found: $s_1 \\rightarrow s_2 \\rightarrow \\dots \\rightarrow s_i \\rightarrow u \\rightarrow s_{i+1} \\rightarrow \\dots \\rightarrow s_k$. Therefore statement ($1$) is proved. It takes $O(N+M)$ to find ($P$). Let's deal with important nodes first. Because all important nodes lie on the path ($P$) so it makes no sense to calculate $in$ and $out$ for those nodes that don't belong to ($P$). We can calculate $out$ by iterate through $P$ from $s_k$ to $s_1$. At each node $s_i$, we just need to use bfs or dfs to search for the nodes that can be reached by $s_i$. Because we visit each node $1$ time then it takes $O(N+M)$ to do this. To calculate $in$ we just need to reverse the direction of the edges and do similarly. Now we need to find the semi nodes. There are two types of semi nodes: those belong to ($P$) and those don't. For the ones belong to ($P$), we just need to check if $in_u+out_u=N$. For the ones don't belong to ($P$), suppose we are dealing with node $u$. Let $s_i$ be the rightmost node on ($P$) that can reach $u$ and $s_j$ be the leftmost node on ($P$) that can be reached by $u$. It's obvious that $i<j-1$. Let $L_u=i$ and $R_u=j$, let $leng$ equal $j-i-1$. If $leng>1$ then u is not a semi node (because we have to delete all nodes between i and j not inclusive), or else we must erase $s_{i+1}$ to make $u$ a semi important node. We can see that the path from $s_i$ to $u$ contains only $s_i$ and $u$, and the path from $u$ to $s_j$ contains only $u$ and $s_j$, because otherwise there exists a longer path than ($P$), which is false. So we consider $u$ as a candidate. Moreover, if exists a node $v$ that is a candidate and $L_u=L_v$ (also leads to $R_u=R_v$) then both $u$ and $v$ are not semi important nodes. Proof: After we delete $s_{i+1}$, for $u$, exists a path that is as long as ($P$) and does not go through $u$ (it goes through $v$) so $u$ is not a important node, based on statement ($1$). Same for $v$. Briefly, at this point we have the path ($P$) and a list of nodes $u_1, u_2, ..., u_t$. For every $i$, $u_i$ is a candidate and $L_{ui}+1=R_{ui}-1$. For every $i$, $j$, $L_{ui}!=L_{uj}$. So now we are going to calculate $in$ and $out$ for those candidate nodes. We can do this similarly as when we find the important nodes. To calculate $out$, iterate through $s_k$ to $s_1$. At each node $s_i$, bfs or dfs to search for nodes that can be reached by $s_i$. Additionally, if there is a candidate node $v$ that $R_v=i-1$, we start a search from $v$ to find those nodes that can be reached by $v$, we have $out_v=out_{si}+$ the number of nodes we just found. After that we pop those nodes from the stack (or whatever), mark them as not visited and continue to iterate to $s_{i-1}$. To calculate $in$ we reverse the directs of the edges and do the same. Because each node is visited $1$ time by nodes on ($P$) and at most $2$ times by candidate nodes so it takes $O(3(N+M))$. The total complexity is $O(N+M)$.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1063",
    "index": "A",
    "title": "Oh Those Palindromes",
    "statement": "A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, \"abcba\", \"a\", and \"abba\" are palindromes, while \"abab\" and \"xy\" are not.\n\nA string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, \"abc\", \"ab\", and \"c\" are substrings of the string \"abc\", while \"ac\" and \"d\" are not.\n\nLet's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string \"aaa\" is $6$ because all its substrings are palindromes, and the palindromic count of the string \"abc\" is $3$ because only its substrings of length $1$ are palindromes.\n\nYou are given a string $s$. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.",
    "tutorial": "One possible solution is just to sort the string. Why so? Note that each palindrome have equal character at their ends. Suppose this character is $c$ with $x$ number of occurences. Then there are at most $x(x + 1)/2$ palindromes with this character. So we have a clear upper bound on answer. It is easy to see, that the sorted string fulfills that bound and hence it is the optimal answer.",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1063",
    "index": "B",
    "title": "Labyrinth",
    "statement": "You are playing some computer game. One of its levels puts you in a maze consisting of $n$ lines, each of which contains $m$ cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row $r$ and column $c$. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.\n\nUnfortunately, your keyboard is about to break, so you can move left no more than $x$ times and move right no more than $y$ times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.\n\nNow you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?",
    "tutorial": "Suppose we started in cell $(i_{0}, j_{0})$ and examining whether we can reach cell $(i_{1}, j_{1})$. Let's denote the number of taken moves to the right as $R$ and number of moves to the left as $L$ Clearly, $j_{0} + R - L = j_{1}$ That is, $R - L = j_{1} - j_{0} = const$. Or, put otherwise $R = L + const$, where $const$ only depends on the starting cell and the target cell. So in fact we just need to minimize any of the left or right moves - the other one will be optimal as well. To calculate the minimum possible number of L-moves to reach some cell we can use 0-1 bfs. Solution is $O(nm)$.",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1063",
    "index": "C",
    "title": "Dwarves, Hats and Extrasensory Abilities",
    "statement": "\\textbf{This is an interactive problem.}\n\nIn good old times dwarves tried to develop extrasensory abilities:\n\n- Exactly $n$ dwarves entered completely dark cave.\n- Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves.\n- Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information.\n- The task for dwarves was to got diverged into two parts — one with dwarves with white hats and one with black hats.\n\nAfter many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?\n\nYou are asked to successively name $n$ different integer points on the plane. After naming each new point you will be given its color — black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.\n\nIn this problem, the interactor is adaptive — the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output.",
    "tutorial": "The solution is just.. binary search! We will use just a single line to put our points on. Let's maintain an invariant that all white colored points are on the left and all black colored on the right. Put a new point in the middle of the gap between white points and black points. Depending on the color said by jury shrink the gap to the left or to the right. In the end draw a diagonal line between white points and black points. The initializing binary search may look complicated but it isn't. Put a first point on the leftmost ($x = 0$) position, suppose that this point is white (if it is black just revert all colors), and then play as if there is a white point in $x = 0$ and black point in $x = 10^{9}$.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "geometry",
      "interactive"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1063",
    "index": "D",
    "title": "Candies for Children",
    "statement": "At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly $k$ candies \"Wilky May\". Lena is not a greedy person, so she decided to present all her candies to her friends in the circle. Lena knows, that some of her friends have a sweet tooth and others do not. Sweet tooth takes out of the box two candies, if the box has at least two candies, and otherwise takes one. The rest of Lena's friends always take exactly one candy from the box.\n\nBefore starting to give candies, Lena step out of the circle, after that there were exactly $n$ people remaining there. Lena numbered her friends in a clockwise order with positive integers starting with $1$ in such a way that index $1$ was assigned to her best friend Roma.\n\nInitially, Lena gave the box to the friend with number $l$, after that each friend (starting from friend number $l$) took candies from the box and passed the box to the next friend in clockwise order. The process ended with the friend number $r$ taking the last candy (or two, who knows) and the empty box. Please note that it is possible that some of Lena's friends took candy from the box several times, that is, the box could have gone several full circles before becoming empty.\n\nLena does not know which of her friends have a sweet tooth, but she is interested in the maximum possible number of friends that can have a sweet tooth. If the situation could not happen, and Lena have been proved wrong in her observations, please tell her about this.",
    "tutorial": "Solution works in $min(n^2, k / n)$ time. Also I will drop the case about the last person being sweet tooth and eating one candy instead of two. This adds few more cases but the idea stays the same. Basically in the formulas below just few $-1$ will appear, however there must be condition that there is at least one sweet tooth in corresponding part of the circle. So how to solve problem in $n^2$? Note, that basically we have two parts of the circle - the part between $[l; r]$ which get's candies one times more than the rest and the other one. Since we don't care about absolute values we can only worry about the lengths of this parts, let's denote them as $x$ and $y$. To solve in $n^2$ let's bruteforce the number of sweet tooth on first part ($a$) and the number of sweet tooth on the second part ($b$). Suppose that there were full $t$ loops. This way the number of eaten candies is $a * 2 * (t + 1) + (x - a) * 1 * (t + 1) + b * 2 * t + (y - b) * 1 * t$. This should be equal to $k$. Since we just bruteforced the values of $a$ and $b$ we now just have linear equation. If it is solvable, consider relaxing answer with $a + b$. How to solve problem in $k / n$? So as the asymptotic suggests the amount of turns $\\le k / n$, so we can bruteforce it instead. Also it is worthy to handle case of $0$ turns specifically here since it produces some unpleasant effects otherwise. So each person in \"$x$\" part of the circle eats candies $t + 1$ times (so each person contributes $t + 1$ or $2t + 2$) and the other persons have eaten candies $t$ times (so each person contributes $t$ or $2t$). Let's account all persons as if they are not sweet tooths. So now each person in $x$ contributes $0$ or $t + 1$ and each person in $y$ contributes $0$ or $t$. So we basically have $(t + 1) a + t b = \\gamma$. A Diophantine equation. Careful analysis or bits of theory suggest that the solutions are $a = a_0 - t z$, $b = b_0 + (t + 1) z$, for all integer $z$. Where $a_0$ and $b_0$ some arbitrary solutions which we can get with formulas. Also we need to have $0 \\le a \\le x$, $0 \\le b \\le y$, and the $a + b \\to max$. These bounds imply that $t$ takes values only in some range $[t_1; t_2]$. Since the $a + b$ is linear function we can only consider $t_1$ and $t_2$ while searching for maximum $a + b$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1063",
    "index": "E",
    "title": "Lasers and Mirrors",
    "statement": "Oleg came to see the maze of mirrors. The maze is a $n$ by $n$ room in which each cell is either empty or contains a mirror connecting opposite corners of this cell. Mirrors in this maze reflect light in a perfect way, which causes the interesting visual effects and contributes to the loss of orientation in the maze.\n\nOleg is a person of curious nature, so he decided to install $n$ lasers facing internal of the maze on the south wall of the maze. On the north wall of the maze, Oleg installed $n$ receivers, also facing internal of the maze. Let's number lasers and receivers from west to east with distinct integers from $1$ to $n$. Each laser sends a beam of some specific kind and receiver with number $a_i$ should receive the beam sent from laser number $i$. Since two lasers' beams can't come to the same receiver, these numbers form a permutation — each of the receiver numbers occurs exactly once.\n\nYou came to the maze together with Oleg. Help him to place the mirrors in the initially empty maze so that the maximum number of lasers' beams will come to the receivers they should. There are no mirrors outside the maze, so if the laser beam leaves the maze, it will not be able to go back.",
    "tutorial": "The answer is always $n$ (if the permutation is identity) lasers or $n - 1$ (otherwise). Clearly, we can't have more than $n - 1$ matching lasers if the permutation is not identity. Consider just the very first line with mirrors. If the first mirror in this line is <<\\>> then we miss the laser below this mirror, if the very last mirror is <</>> we miss the laser below it. Otherwise there are neighbouring <</>> and <<\\>> and we lost two lasers now. The proof of $n - 1$ is constructive one. Ignore all fixed points in permutation (all $x$, that $p_x = x$). Select arbitrary cycle and select one point in it as <<dead>>. We can spend $|cycle| - 1$ operations to fix all points in this cycle. But we also need to fix all other cycles. We can do it in $|cycle| + 1$ operations: move arbitrary beam to the wasted laser, fix all other points and move that point back. But this is a bit too much lines. The trick is that we can perform movement of arbitrary beam to the wasted point and the first operation of fixing in just one line, if we select as the trash beam the rightmost point. See the following picture for an example (trash beam is the rightmost column):",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1063",
    "index": "F",
    "title": "String Journey",
    "statement": "We call a sequence of strings $t_{1}, ..., t_{k}$ a journey of length $k$, if for each $i > 1$ $t_{i}$ is a substring of $t_{i - 1}$ and length of $t_{i}$ is strictly less than length of $t_{i - 1}$. For example, ${ab, b}$ is a journey, but ${ab, c}$ and ${a, a}$ are not.\n\nDefine a journey on string $s$ as journey $t_{1}, ..., t_{k}$, such that all its parts can be nested inside $s$ in such a way that there exists a sequence of strings $u_{1}, ..., u_{k + 1}$ (each of these strings can be empty) and $s = u_{1} t_{1} u_{2} t_{2}... u_{k} t_{k} u_{k + 1}$. As an example, ${ab, b}$ is a journey on string $abb$, but not on $bab$ because the journey strings $t_{i}$ should appear from the left to the right.\n\nThe length of a journey on a string is the number of strings in it. Determine the maximum possible length of a journey on the given string $s$.",
    "tutorial": "This problem required quite a lot of nice observations! Observation 1. We can only consider journeys in which neighboring strings differ exactly by removing one symbol. All other journeys can be modified a bit to match the criterion above. Observation 2. If it is possible to start a journey at the symbol $i$ with lengths of strings $k$, $k - 1$, ..., $1$, it is always possible to start a journey at the same symbol $i$ with lengths $t$, $t - 1$, ..., $1$, given that $t  \\le  k$. This suggests doing dynamic programming: $dp[i]$ is the maximum possible $k$ such that there is a journey starting at position $i$ of $k$ strings with lengths $k$, ..., $1$. Due to observation $1$ we only care about maximum - if we know maximum, we also known that all lesser values are also OK. So let's calculate this dynamic programming from right to left. How to check whether $dp[i]  \\ge  k$ (given that tool, we can just use binary search for example)? There must be such $j$, that $j  \\ge  i + k$, $dp[j]  \\ge  k - 1$ and string $s_{j}, ..., s_{j + k - 2}$ must be a substring of string $s_{i}s_{i + 1}... s_{i + k - 1}$ (basically just two cases \"left substring\" or \"right substring\"). This almost gives us a solution, but we need few more observations to have $O(n\\log n)$, and not $O(n\\log^{e}n)$. Observation 3. If $dp[i] = k$, then $dp[i + 1]  \\ge  k - 1$. We can use this to kick binary search from the solution - when you calculate $dp[i]$ you can start trying with $dp[i + 1] + 1$, descending until the success. Since there are exactly $n$ grows, there will be at most $n$ descendings and the total number of checks is linear. ?Observation? 4. We need to check whether such $j$ exists in a fast way. Recall there are few conditions for us to follow, $dp[j]  \\ge  const$, $j  \\ge  const$ and some string equality. If you carefully look at the restriction $j  \\ge  const$ you can see, that when we move our dp calculation $i  \\rightarrow  i - 1$ or make dp[i] -= 1 this lower bound on $j$ also moves only left, like in two pointers. So each moment some indexes $j$ are \"available\" and some are not, and the border moves only left. Finally, time for some structures. Build Suffix Array and build segment tree over it. Let's store in the leaf of the segment tree $dp[j]$ if it's already available or $- 1$ otherwise. Let's check whether $dp[i] = k$ is good. We want for string starting at $j$ be either $s_{i}, s_{i + 1}, ..., s_{i + k - 2}$, or $s_{i + 1}, s_{i + 2}, ..., s_{i + k - 1}$. Consider these cases independently (however the procedure is pretty much same). All such strings form a segment of Suffix Array, we can for example use LCP + binary search over sparse tables to find corresponding bounds. Then we just need to query this segment and check if the maximum on it is at least $k - 1$. The solution is $O(n\\log n)$",
    "tags": [
      "data structures",
      "dp",
      "string suffix structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1064",
    "index": "A",
    "title": "Make a triangle!",
    "statement": "Masha has three sticks of length $a$, $b$ and $c$ centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.\n\nWhat is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a triangle of positive area. Sticks should be used as triangle's sides (one stick for one side) and their endpoints should be located at triangle's vertices.",
    "tutorial": "Suppose $c$ is the largest stick. It is known, that we can build a triangle iff $c \\le a + b - 1$. So if we can build a triangle the answer is zero. Otherwise we can just increase $a$ or $b$ until the inequality above holds. So the answer is $max(0, c - (a + b - 1))$. Another approach: just bruteforce all possible triangles we can extend to (with sides $\\le 100$) and select the one with smallest $a + b + c$.",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1064",
    "index": "B",
    "title": "Equations of Mathematical Magic",
    "statement": "\\begin{quote}\nColossal! — exclaimed Hawk-nose. — A programmer! That's exactly what we are looking for.\n\\hfill Arkadi and Boris Strugatsky. Monday starts on Saturday\n\\end{quote}\n\nReading the book \"Equations of Mathematical Magic\" Roman Oira-Oira and Cristobal Junta found an interesting equation: $a - (a \\oplus x) - x = 0$ for some given $a$, where $\\oplus$ stands for a bitwise exclusive or (XOR) of two integers (this operation is denoted as ^ or xor in many modern programming languages). Oira-Oira quickly found some $x$, which is the solution of the equation, but Cristobal Junta decided that Oira-Oira's result is not interesting enough, so he asked his colleague how many \\textbf{non-negative} solutions of this equation exist. This task turned out to be too difficult for Oira-Oira, so he asks you to help.",
    "tutorial": "Rewriting equation we have $a \\oplus x = a - x$. If you look in the xor definition, it is easy to see, that $a \\oplus x \\ge a - x$, no matter $a$ and $x$ (just look at the each bit of the $a \\oplus x$). And the equality handles only if bits of $x$ form a subset of bits of $a$. So the answer is $2^t$, where $t$ is the number of bits in $a$ (also known as popcount).",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1065",
    "index": "A",
    "title": "Vasya and Chocolate",
    "statement": "There is a special offer in Vasya's favourite supermarket: if the customer buys $a$ chocolate bars, he or she may take $b$ additional bars for free. This special offer can be used any number of times.\n\nVasya currently has $s$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $c$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!",
    "tutorial": "Number of chocolate bars Vasya can buy without offer is $cnt = \\lfloor \\frac{s}{c} \\rfloor$. Number of \"bundles\" with $a$ bars $x = \\lfloor \\frac{cnt}{a} \\rfloor$. Then number of additional bars $add = x \\cdot b$. In result, total number of bars is $add + cnt$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int s, a, b, c;\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; ++i){\n        cin >> s >> a >> b >> c;\n        \n        s /= c;\n        int x = s / a;\n        s %= a;\n        long long res = x * 1LL * (a + b);\n        res += s;\n        \n        cout << res << endl;\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1065",
    "index": "B",
    "title": "Vasya and Isolated Vertices",
    "statement": "Vasya has got an undirected graph consisting of $n$ vertices and $m$ edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges $(1, 2)$ and $(2, 1)$ is considered to be multiple edges. Isolated vertex of the graph is a vertex such that there is no edge connecting this vertex to any other vertex.\n\nVasya wants to know the minimum and maximum possible number of isolated vertices in an undirected graph consisting of $n$ vertices and $m$ edges.",
    "tutorial": "Vasya can decrease number of isolated vertices up to $2$ using one edge and pairing them. So minimum number of isolated vertices is $max(0, n - 2m)$. To calculate maximum number of isolated vertices let's keep number of non-isolated vertices knowing that each pair connected by edge (i.e. size of clique). Let we have size of clique $cur$ and $rem$ edges remained unassigned at current step. If $rem = 0$ then answer is $n - cur$. Otherwise we need to increase clique with one vertex. Maximum number of edges we can add to connect this vertex is $add = min~(rem, cur)$. So, subtract it from $rem$ and increase $cur$ by one. Repeat this step while $rem$ greater than zero. Answer is $n - cur$. One corner case is next: if $cur = 1$, then answer is $n$, not $n - cur$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int n;\n    long long m;\n    cin >> n >> m;\n    long long cur = 1;\n    long long rem = m;\n    while(rem > 0){\n        long long d = min(cur, rem);\n        rem -= d;\n        ++cur;\n    }\n    assert(rem == 0);\n    \n    long long res = n;\n    if(cur > 1) res = n - cur;\n    \n    cout << max(0ll, n - m * 2) << ' ' << res << endl;\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1065",
    "index": "C",
    "title": "Make It Equal",
    "statement": "There is a toy building consisting of $n$ towers. Each tower consists of several cubes standing on each other. The $i$-th tower consists of $h_i$ cubes, so it has height $h_i$.\n\nLet's define operation slice on some height $H$ as following: for each tower $i$, if its height is greater than $H$, then remove some top cubes to make tower's height equal to $H$. Cost of one \"slice\" equals to the total number of removed cubes from all towers.\n\nLet's name slice as good one if its cost is lower or equal to $k$ ($k \\ge n$).\n\nCalculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.",
    "tutorial": "Let's iterate over height $pos$ of slice in decreasing order. All we need to know is a number of towers with height more than $pos$ (name it $c$) and sum of its heights $sum$. Current slice on height $pos$ is good if $k \\ge sum - c \\cdot pos$. Let's greedily decrease value $pos$ while slice on $pos$ is good keeping correct values $c$ and $sum$. When we found minimal good slice we can perform it increasing answer by one and \"changing tower heights\" just by setting new value to $sum$ equal to $c \\cdot pos$. Finish algorithm when $pos$ becomes equal to minimal height of towers and make final slice.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(2e5) + 9;\n\nint n, k, h;\nint need = int(1e9);\nint cnt[N];\n\nint main() {\n    scanf(\"%d %d\", &n, &k);\n    for(int i = 0; i < n; ++i){\n        int x;\n        scanf(\"%d\", &x);\n        h = max(h, x);\n        need = min(need, x);\n        ++cnt[x];\n    }\n    \n    int pos = N - 1;\n    int res = 0;\n    long long sum = 0;\n    int c = 0;\n    while(true){\n        long long x = sum - c * 1LL * (pos - 1);\n        if(x > k){\n            ++res;\n            h = pos;\n            sum = pos * 1LL * c;\n        }   \n    \n        --pos;\n        if(pos == need) break;\n        c += cnt[pos];\n        sum += cnt[pos] * 1LL * pos;\n    }\n    \n    if(h != need) ++res;\n    \n    cout << res << endl;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1065",
    "index": "D",
    "title": "Three Pieces",
    "statement": "You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily $8 \\times 8$, but it still is $N \\times N$. Each square has some number written on it, all the numbers are from $1$ to $N^2$ and all the numbers are pairwise distinct. The $j$-th square in the $i$-th row has a number $A_{ij}$ written on it.\n\nIn your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number $1$ (you can choose which one). Then you want to reach square $2$ (possibly passing through some other squares in process), then square $3$ and so on until you reach square $N^2$. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. \\textbf{Each square can be visited arbitrary number of times}.\n\nA knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.\n\nYou want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.\n\nWhat is the path you should take to satisfy all conditions?",
    "tutorial": "There are a lot of different solutions for the problem. Most of them have the similar structure. The first part is to find the shortest distance between the states $(x_1, y_1, p_1)$ and $(x_2, y_2, p_2)$, where $x$ and $y$ are the coordinates of the square and $p$ is the current piece. This can be done with 0-1 bfs, Floyd or Dijkstra. Just represent the triple as a single integer by transforming it to $(x \\cdot n \\cdot 3 + y \\cdot 3 + p)$ and do everything on that graph. The second part is to write some dp to go from $i$-th square with piece $p_1$ to $(i + 1)$-th square with piece $p_2$. The value of this $dp[n][3]$ is a pair (moves, replacements). It is easy to see that you can always choose the minimum of two such pairs while updating. Overall complexity may vary. We believe, $O(n^4)$ is achievable. However, the particular solution I coded works in $O(n^6)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define mp make_pair\n#define x first\n#define y second\n\nusing namespace std;\n\ntypedef pair<int, int> pt;\n\nconst int N = 12;\nconst int M = 305;\nconst int INF = 1e9;\n\nint n;\nint a[N][N];\npt pos[N * N];\npt dist[M][M];\n\npt operator +(const pt &a, const pt &b){\n    return mp(a.x + b.x, a.y + b.y);\n}\n\nint dx[] = {-2, -1, 1, 2,  2,  1, -1, -2};\nint dy[] = { 1,  2, 2, 1, -1, -2, -2, -1};\n\nbool in(int x, int y){\n    return (0 <= x && x < n && 0 <= y && y < n);\n}\n\nint get(int x, int y, int p){\n    return x * n * 3 + y * 3 + p;\n}\n\npt dp[N * N][3];\n\nint main() {\n    scanf(\"%d\", &n);\n    forn(i, n) forn(j, n){\n        scanf(\"%d\", &a[i][j]);\n        --a[i][j];\n        pos[a[i][j]] = mp(i, j);\n    }\n    \n    forn(i, M) forn(j, M) dist[i][j] = mp(INF, INF);\n    forn(i, M) dist[i][i] = mp(0, 0);\n    \n    forn(x, n) forn(y, n){\n        forn(i, 8){\n            int nx = x + dx[i];\n            int ny = y + dy[i];\n            if (in(nx, ny))\n                dist[get(x, y, 0)][get(nx, ny, 0)] = mp(1, 0);\n        }\n        \n        for (int i = -n + 1; i <= n - 1; ++i){\n            int nx = x + i;\n            int ny = y + i;\n            if (in(nx, ny))\n                dist[get(x, y, 1)][get(nx, ny, 1)] = mp(1, 0);\n            ny = y - i;\n            if (in(nx, ny))\n                dist[get(x, y, 1)][get(nx, ny, 1)] = mp(1, 0);\n        }\n        \n        forn(i, n){\n            int nx = x;\n            int ny = i;\n            dist[get(x, y, 2)][get(nx, ny, 2)] = mp(1, 0);\n            nx = i;\n            ny = y;\n            dist[get(x, y, 2)][get(nx, ny, 2)] = mp(1, 0);\n        }\n        \n        forn(i, 3) forn(j, 3){\n            if (i != j){\n                dist[get(x, y, i)][get(x, y, j)] = mp(1, 1);\n            }\n        }\n    }\n    \n    forn(k, M) forn(i, M) forn(j, M)\n        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);\n    \n    forn(i, N * N) forn(j, 3) dp[i][j] = mp(INF, INF);\n    dp[0][0] = dp[0][1] = dp[0][2] = mp(0, 0);\n    forn(i, n * n - 1) forn(j, 3) forn(k, 3)\n        dp[i + 1][k] = min(dp[i + 1][k], dp[i][j] + dist[get(pos[i].x, pos[i].y, j)][get(pos[i + 1].x, pos[i + 1].y, k)]);\n    \n    pt ans = mp(INF, INF);\n    ans = min(ans, dp[n * n - 1][0]);\n    ans = min(ans, dp[n * n - 1][1]);\n    ans = min(ans, dp[n * n - 1][2]);\n    \n    printf(\"%d %d\\n\", ans.x, ans.y);\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1065",
    "index": "E",
    "title": "Side Transmutations",
    "statement": "Consider some set of distinct characters $A$ and some string $S$, consisting of exactly $n$ characters, where each character is present in $A$.\n\nYou are given an array of $m$ integers $b$ ($b_1 < b_2 < \\dots < b_m$).\n\nYou are allowed to perform the following move on the string $S$:\n\n- Choose some valid $i$ and set $k = b_i$;\n- Take the first $k$ characters of $S = Pr_k$;\n- Take the last $k$ characters of $S = Su_k$;\n- Substitute the first $k$ characters of $S$ with the reversed $Su_k$;\n- Substitute the last $k$ characters of $S$ with the reversed $Pr_k$.\n\nFor example, let's take a look at $S =$ \"abcdefghi\" and $k = 2$. $Pr_2 =$ \"ab\", $Su_2 =$ \"hi\". Reversed $Pr_2 =$ \"ba\", $Su_2 =$ \"ih\". Thus, the resulting $S$ is \"{\\textbf{ih}cdefg\\textbf{ba}}\".\n\nThe move can be performed arbitrary number of times (possibly zero). Any $i$ can be selected multiple times over these moves.\n\nLet's call some strings $S$ and $T$ equal if and only if there exists such a sequence of moves to transmute string $S$ to string $T$. For the above example strings \"abcdefghi\" and \"ihcdefgba\" are equal. Also note that this implies $S = S$.\n\nThe task is simple. Count the number of distinct strings.\n\nThe answer can be huge enough, so calculate it modulo $998244353$.",
    "tutorial": "Let's take a look at any operation. You can notice that each letter can only go from position $i$ to $n - i - 1$ ($0$-indexed). Then, doing some operation twice is the same as doing that operation zero times. Now consider some set of operations $l_1, l_2, \\dots, l_k$, sorted in increasing order. Actually, they do the following altogether. Replace segment $[l_{k - 1}..l_k)$ with the reversed segment $((n - l_k - 1)..(n - l_{k - 1} - 1)]$ and vice versa. Then replace segment $[l_{k - 3}..l_{k - 2})$ with the reversed segment $((n - l_{k - 2} - 1)..(n - l_{k - 3} - 1)]$ and vice versa. And continue until you reach the first pair. Segment $[0..l_1)$ might also be included in the answer when the parity is right. Moreover, every subset of segments $[0..l_1), [l_1, l_2), \\dots [l_{k - 1}, l_k)$ is achievable. So for each segment you can either swap it or not. Let's translate it to math language. Let $cnt_i$ be the number of such pairs of strings $x$ and $y$ that $x \\le y$. Why is there such an order? You want to consider only unique strings, thus, you need to pick exactly one of equal strings from each component. Let it be the smallest one. Then for each segment of the set you have $cnt_{len}$ pairs to choose from, where $len$ is the length of that segment. And that part of the formula is: $cnt_{b_1} \\cdot \\prod \\limits_{i = 1}^{m} cnt_{b_i - b_{i - 1}}$. However, the part covered by zero segments is left. There are $AL^{n - 2b_m}$ possible strings up there. $cnt_i$ is actually a number of all pairs of strings of length $i$ plus the number of all pairs of equal strings of length $i$ divided by $2$. $cnt_i = \\frac{AL^{2i} + AL^i}{2}$. Overall complexity: $O(m \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\nconst int MOD = 998244353;\n\nint n, m, A;\nint b[N];\n\nint add(int a, int b){\n    a += b;\n    if (a >= MOD)\n        a -= MOD;\n    return a;\n}\n\nint mul(int a, int b){\n    return (a * 1ll * b) % MOD;\n}\n\nint binpow(int a, int b){\n    int res = 1;\n    while (b){\n        if (b & 1)\n            res = mul(res, a);\n        a = mul(a, a);\n        b >>= 1;\n    }\n    return res;\n}\n\nint cnt(int x){\n    int base = binpow(A, x);\n    return mul(add(mul(base, base), base), (MOD + 1) / 2);\n}\n\nint main() {\n    scanf(\"%d%d%d\", &n, &m, &A);\n    forn(i, m)\n        scanf(\"%d\", &b[i]);\n    \n    int ans = binpow(A, n - b[m - 1] * 2);\n    ans = mul(ans, cnt(b[0]));\n    forn(i, m - 1)\n        ans = mul(ans, cnt(b[i + 1] - b[i]));\n    \n    printf(\"%d\\n\", ans);\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1065",
    "index": "F",
    "title": "Up and Down the Tree",
    "statement": "You are given a tree with $n$ vertices; its root is vertex $1$. Also there is a token, initially placed in the root. You can move the token to other vertices. Let's assume current vertex of token is $v$, then you make any of the following two possible moves:\n\n- move down to any \\textbf{leaf} in subtree of $v$;\n- if vertex $v$ is a leaf, then move up to the parent no more than $k$ times. In other words, if $h(v)$ is the depth of vertex $v$ (the depth of the root is $0$), then you can move to vertex $to$ such that $to$ is an ancestor of $v$ and $h(v) - k \\le h(to)$.\n\nConsider that root is not a leaf (even if its degree is $1$). Calculate the maximum number of different leaves you can visit during one sequence of moves.",
    "tutorial": "Let's calculate answer in two steps. At first, let's calculate for each vertex $v$ $drev(v)$ - what we can gain if we must return from subtree of $v$ in the end. We need only pair of values: minimal possible depth we can acquire to move up from subtree of $v$ and maximal number of different leaves we can visit. Note, that this two values are independent since we must return from $v$ and if for some child $to$ of $v$ we can return from it, it's profitable to visit $to$ and return. But if we can't return from $to$ so we are prohibited to descent to $to$. So, $drev(v).second$ (number of visited leaves) is just a sum of all $drev(to).second$ if $drev(to).first \\le h_v$. Also note that we can always reorder all children in such way that last visited vertex $to$ will have minimal $drev(to).first$. So $drev(to).first$ (minimal possible depth) is a minimum over all $drev(to).first$. At second, let's calculate $d(v)$ - maximal number of different leaves we can visit if we don't need to return from subtree of $v$. It can be calculated quite easy using array $drev(v)$. We just need to choose child $to$ we will not return from, so from vertex $to$ we will take value $d(to)$ and from other childen (which we can return from) value $drev(v).second$. Result complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n    return out << \"(\" << p.x << \", \" << p.y << \")\";\n}\n\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n    out << \"[\";\n    fore(i, 0, v.size()) {\n        if(i) out << \", \";\n        out << v[i];\n    }\n    return out << \"]\";\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nconst int N = 1000 * 1000 + 555;\n\nint n, k;\nvector<int> g[N];\n\ninline bool read() {\n    if(!(cin >> n >> k))\n        return false;\n    fore(i, 1, n) {\n        int p; assert(scanf(\"%d\", &p) == 1);\n        p--;\n        \n        g[p].push_back(i);\n        g[i].push_back(p);\n    }\n    return true;\n}\n\nint h[N];\npt drev[N];\n\nvoid calcRev(int v, int p) {\n    drev[v] = pt(INF, 0);\n    for(int to : g[v]) {\n        if(to == p) continue;\n        \n        h[to] = h[v] + 1;\n        calcRev(to, v);\n        \n        if(drev[to].x <= h[v]) {\n            drev[v].x = min(drev[v].x, drev[to].x);\n            drev[v].y += drev[to].y;\n        }\n    }\n    \n    if(p >= 0 && g[v].size() == 1)\n        drev[v] = pt(h[v] - k, 1);\n}\n\nint d[N];\n\nvoid calcAns(int v, int p) {\n    d[v] = (p >= 0 && g[v].size() == 1);\n    for(int to : g[v]) {\n        if(to == p) continue;\n        calcAns(to, v);\n        \n        int tmp = drev[v].y;\n        if(drev[to].x <= h[v])\n            tmp -= drev[to].y;\n        \n        d[v] = max(d[v], tmp + d[to]);\n    }\n}\n\ninline void solve() {\n    h[0] = 0;\n    calcRev(0, -1);\n    calcAns(0, -1);\n    cout << d[0] << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1065",
    "index": "G",
    "title": "Fibonacci Suffix",
    "statement": "Let's denote (yet again) the sequence of Fibonacci strings:\n\n$F(0) = $ 0, $F(1) = $ 1, $F(i) = F(i - 2) + F(i - 1)$, where the plus sign denotes the concatenation of two strings.\n\nLet's denote the \\textbf{lexicographically sorted} sequence of suffixes of string $F(i)$ as $A(F(i))$. For example, $F(4)$ is 01101, and $A(F(4))$ is the following sequence: 01, 01101, 1, 101, 1101. Elements in this sequence are numbered from $1$.\n\nYour task is to print $m$ first characters of $k$-th element of $A(F(n))$. If there are less than $m$ characters in this suffix, then output the whole suffix.",
    "tutorial": "Suppose we added all the suffixes of $F(n)$ into a trie. Then we can find $k$-th suffix by descending the trie, checking the sizes of subtrees to choose where to go on each iteration. The model solution actually does that, but computes the sizes of subtrees without building the whole trie. Recall that if we insert all suffixes of a string into the trie, then the size of subtree of some vertex is equal to the number of occurences of the string denoted by this vertex in the original string. Since in our problem the strings are recurrent, we may use prefix automaton to count the number of occurences. To calculate the number of occurences of string $s$ in $F(x)$, let's build prefix function for $s$, and an automaton $A_{p, c}$ which tells the value of prefix function, if the previous value was $p$, and we appended $c$ to the string (the same approach is used in KMP substring search algorithm). Then, let's build another automaton that will help us work with Fibonacci string: $F_{p, x}$ - what will be the value of prefix function, if we append $F(x)$ to the string? For $x = 0$ and $x = 1$, this automaton can be easily built using $A_{p, 0}$ and $A_{p, 1}$; and for $x > 1$, we may build $F_{p, x}$ using the automatons for $x - 2$ and $x - 1$. We also have to keep track of the number of occurences, that can be done with another automaton on fibonacci strings. There is a corner case when we need to stop descending the trie; to handle it, we need to check whether some string is a suffix of $F(n)$, but that can be easily made by checking if $F_{0, n} = |s|$. Each step in trie forces us to do up to three (depending on your implementation) queries like \"count the number of occurences of some string in $F(n)$\", so overall the solution works in $O(n m^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\nconst li INF64 = li(1e18);\n\nli add(li x, li y)\n{\n    return min(x + y, INF64);\n}\n\nconst int N = 243;\n\nint A1[N][2];\nli A2[N][N];\nint A3[N][N];\nint n, m;\nli k;\nint z;\nint p[N];\n\nvoid build(const string& s)\n{\n    z = (int)(s.size());\n    p[0] = 0;\n    for(int i = 1; i < z; i++)\n    {\n        int j = p[i - 1];\n        while(j > 0 && s[j] != s[i])\n            j = p[j - 1];\n        if(s[j] == s[i])\n            j++;\n        p[i] = j;\n    }\n    for(int i = 0; i <= z; i++)\n        for(int j = 0; j < 2; j++)\n        {\n            if(i < z && s[i] == char('0' + j))\n                A1[i][j] = i + 1;\n            else if(i == 0)\n                A1[i][j] = 0;\n            else\n                A1[i][j] = A1[p[i - 1]][j];\n        }\n    for(int i = 0; i <= z; i++)\n        for(int j = 0; j < 2; j++)\n        {\n            A3[i][j] = A1[i][j];\n            A2[i][j] = (A3[i][j] == z ? 1 : 0);\n        }\n    for(int i = 2; i <= n; i++)\n        for(int j = 0; j <= z; j++)\n        {\n            A3[j][i] = A3[A3[j][i - 2]][i - 1];\n            A2[j][i] = add(A2[j][i - 2], A2[A3[j][i - 2]][i - 1]);\n        }\n}\n\nint main()\n{\n    cin >> n >> k >> m;\n    string cur = \"\";\n    for(int i = 0; i < m; i++)\n    {\n        if(cur != \"\") build(cur);\n        li x = 0;\n        if(cur != \"\" && A3[0][n] == i)\n            x = 1;\n        if(k == 1 && x == 1)\n            break;\n        k -= x;\n        build(cur + '0');\n        li x1 = A2[0][n];\n        if(k > x1)\n        {\n            cur += '1';\n            k -= x1;\n        }\n        else\n            cur += '0';\n    }\n    cout << cur << endl;\n    return 0;\n}",
    "tags": [
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1066",
    "index": "A",
    "title": "Vova and Train",
    "statement": "Vova plans to go to the conference by train. Initially, the train is at the point $1$ and the destination point of the path is the point $L$. The speed of the train is $1$ length unit per minute (i.e. at the first minute the train is at the point $1$, at the second minute — at the point $2$ and so on).\n\nThere are lanterns on the path. They are placed at the points with coordinates divisible by $v$ (i.e. the first lantern is at the point $v$, the second is at the point $2v$ and so on).\n\nThere is also \\textbf{exactly} one standing train which occupies all the points from $l$ to $r$ inclusive.\n\nVova can see the lantern at the point $p$ if $p$ is divisible by $v$ and there is no standing train at this position ($p \\not\\in [l; r]$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.\n\nYour problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $t$ different conferences, so you should answer $t$ \\textbf{independent} queries.",
    "tutorial": "What is the number of lanterns Vova will see from $1$ to $L$? This number is $\\lfloor\\frac{L}{v}\\rfloor$. Now we have to subtract the number of lanters in range $[l; r]$ from this number. This number equals to $\\lfloor\\frac{r}{v}\\rfloor - \\lfloor\\frac{l - 1}{v}\\rfloor$. So the answer is $\\lfloor\\frac{L}{v}\\rfloor$ - $\\lfloor\\frac{r}{v}\\rfloor$ + $\\lfloor\\frac{l - 1}{v}\\rfloor$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\t\n\tfor (int i = 0; i < t; ++i) {\t\n\t\tint L, v, l, r;\n\t\tcin >> L >> v >> l >> r;\n\t\tcout << L / v - r / v + (l - 1) / v << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1066",
    "index": "B",
    "title": "Heaters",
    "statement": "Vova's house is an array consisting of $n$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $i$-th element of the array is $1$ if there is a heater in the position $i$, otherwise the $i$-th element of the array is $0$.\n\nEach heater has a value $r$ ($r$ is the same for all heaters). This value means that the heater at the position $pos$ can warm up all the elements in range $[pos - r + 1; pos + r - 1]$.\n\nVova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater.\n\nVova's target is to warm up the whole house (all the elements of the array), i.e. if $n = 6$, $r = 2$ and heaters are at positions $2$ and $5$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $3$ elements will be warmed up by the first heater and the last $3$ elements will be warmed up by the second heater).\n\nInitially, all the heaters are off.\n\nBut from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the \\textbf{minimum} number of heaters on in such a way that each element of his house is warmed up by at least one heater.\n\nYour task is to find this number of heaters or say that it is impossible to warm up the whole house.",
    "tutorial": "Let's solve this problem greedily. Let $last$ be the last position from the left covered by at least one heater. Initially, $last$ equals -1. While $last < n - 1$, lets repeat the following process: firstly, we have to find the rightmost heater in range $(max(-1, last - r + 1); last + r]$. It can be done in time $O(n)$ because of given constrains or in $O(1)$ using precalculated prefix values for each $i$ in range $[0; n - 1]$. If there is no such heater then the answer is -1, otherwise let's set $last := pos + r - 1$, increase the answer by $1$ and repeat the process if $last < n - 1$. There is another one solution to this problem. Assume that the initial answer equals to the total number of heaters. Let's calculate an array $cnt$ of length $n$, where $cnt_i$ means the number of heaters covering the $i$-th element. It can be done in $O(n^2)$. This array will mean that we are switch all the heaters on and we know for each element the number of heaters covers this element. Now if for at least $i \\in [0, n - 1]$ holds $cnt_i = 0$ then the answer is -1. Otherwise let's switch useless heaters off. Let's iterate over all heaters from left to right. Let the current heater have position $i$. We need to check if it is useless or not. Let's iterate in range $[max(0, i - r + 1), min(n - 1, i + r - 1)]$ and check if there is at least one element $j$ in this segment such that $cnt_j = 1$. If there is then the current heater is not useless and we cannot switch it off. Otherwise we can decrease the answer by $1$, switch this heater off (decrease $cnt_j$ for all $j$ in range $[max(0, i - r + 1), min(n - 1, i + r - 1)]$) and continue the process.",
    "code": "#include <vector>\n#include <iostream>\n\n#define forn(i,n) for (int i=0; i<int(n); i++)\n\nusing namespace std;\n\nconst int N = 2e5;\n\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint n, r; cin >> n >> r;\n\tvector<int> a(n);\n\tvector<int> cnt(n);\n\tint ans = 0;\n\tforn(i, n)\n        {\n            cin >> a[i];\n            if (a[i])ans++;\n            if (a[i])\n                for (int j = max(0, i - r + 1); j < min(n, i + r); ++j)\n                    cnt[j]++;\n        }\n    forn(i, n)\n        if (!cnt[i])\n        {\n            cout << -1;\n            return 0;\n        }\n    forn(i, n)\n    {\n        bool fl = true;\n        if (a[i])\n            for (int j = max(0, i - r + 1); j < min(n, i + r); ++j)\n                if (cnt[j] == 1)\n                {\n                    fl = false;\n                    break;\n                }\n        if (fl && a[i])\n        {\n            ans--;\n            for (int j = max(0, i - r + 1); j < min(n, i + r); ++j)\n                cnt[j]--;\n        }\n    }\n    cout << ans;\n\n}",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1066",
    "index": "C",
    "title": "Books Queries",
    "statement": "You have got a shelf and want to put some books on it.\n\nYou are given $q$ queries of three types:\n\n- L $id$ — put a book having index $id$ on the shelf to the left from the leftmost existing book;\n- R $id$ — put a book having index $id$ on the shelf to the right from the rightmost existing book;\n- ? $id$ — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $id$ will be leftmost or rightmost.\n\nYou can assume that the first book you will put can have any position (it does not matter) and queries of type $3$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $id$s don't repeat in queries of first two types.\n\nYour problem is to answer all the queries of type $3$ in order they appear in the input.\n\nNote that after answering the query of type $3$ all the books remain on the shelf and the relative order of books does not change.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "Let imagine our shelf as an infinite array. Let's carry the rightmost free position from the left of our shelf (let it be $l$ and initially it equals to $0$) and the leftmost free position from the right of our shelf (let it be $r$ and initially it equals to $0$). Also let's carry the array $pos$ of length $2 \\cdot 10^5$ where $pos_i$ will be equal to the position in our imaginary array of the book with a number $i$. Let's put the first book to the position $0$. Also let's save that $pos_{id}$ (where $id$ is the number of the first book) equals to $0$. How will change $l$ and $r$? $l$ will become $-1$ and $r$ will become $1$. Now let's process queries one by one. If now we have the query of type $1$ with a book with a number $id$, then let's set $pos_{id} := l$ and set $l := l - 1$. The query of type $2$ can be processed similarly. Now what about queries of type $3$? The answer to this query equals to $min(|pos_{id} - l|, |pos_{id} - r|) - 1$, where $|v|$ is the absolute value of $v$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 200 * 1000 + 11;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\t\n\tvector<int> pos(M);\n\tint curl = 0;\n\tint curr = 0;\n\t\n\tfor (int i = 0; i < q; ++i) {\n\t\tstring type;\n\t\tint id;\n\t\tcin >> type >> id;\n\t\tif (i == 0) {\n\t\t\tpos[id] = curl;\n\t\t\t--curl;\n\t\t\t++curr;\n\t\t} else {\n\t\t\tif (type == \"L\") {\n\t\t\t\tpos[id] = curl;\n\t\t\t\t--curl;\n\t\t\t} else if (type == \"R\") {\n\t\t\t\tpos[id] = curr;\n\t\t\t\t++curr;\n\t\t\t} else {\n\t\t\t\tcout << min(abs(pos[id] - curl), abs(pos[id] - curr)) - 1 << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1066",
    "index": "D",
    "title": "Boxes Packing",
    "statement": "Maksim has $n$ objects and $m$ boxes, each box has size exactly $k$. Objects are numbered from $1$ to $n$ in order from left to right, the size of the $i$-th object is $a_i$.\n\nMaksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the $i$-th object fits in the current box (the remaining size of the box is greater than or equal to $a_i$), he puts it in the box, and the remaining size of the box decreases by $a_i$. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.\n\nMaksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, \\textbf{he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has}. Your task is to say the maximum number of objects Maksim can pack in boxes he has.\n\nEach time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).",
    "tutorial": "The first solution is some kind of a straight-forward understanding the problem. Let's do binary search on the answer. So our problem is to find the smallest $x$ such that the suffix of the array $a$ starting from the position $x$ can be packed in boxes. It is easy to see that if we can do it for some $x$ then we always can do it for $x+1$. And to find the answer for the fixed $x$ we have to simulate the process described in the problem statement starting from the position $x$. Okay, this is $O(n \\log n)$ solution. The second solution is more interesting than the first one. The approach is to reverse the initial array, simulate the process from the first position of reversed array and then all the objects we can pack are in the best answer and there is no better answer at all. Why it works? Let's take a look on the last box in the best answer if we will go from left to right in the initial array. Let objects in this box be $a_{lst_1}, a_{lst_2}, \\dots, a_{lst_x}$. What do we see? $\\sum\\limits_{i = 1}^{x}a_{lst_i} \\le k$. So all these objects are fit in the last box (obviously). Now if we will iterate over objects from right to left, these objects will fit also! It means that we cannot do worse by such a transform (reversing) at least for the last box. But what will happen if we can put some of the previous objects in this box? Well, it will not make worse for this box, but what about next boxes (previous boxes in straight notation)? Let objects in the penultimate box be $a_{prev_1}, a_{prev_2}, \\dots, a_{prev_y}}$. What do we see? These objects are fit in this box (obviously again). What will happen if we will put in the last box one or more objects of this box? Then the left border of objects which we will put in it will not increase because we decrease the number of object in this box. So we can see that for previous boxes this condition is also satisfied. So we can solve the problem with this approach. Time complexity of this solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\treverse(a.begin(), a.end());\n\tint rem = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (rem - a[i] < 0) {\n\t\t\tif (m == 0) {\n\t\t\t\tcout << i << endl;\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\t--m;\n\t\t\t\trem = k - a[i];\n\t\t\t}\n\t\t} else {\n\t\t\trem -= a[i];\n\t\t}\n\t}\n\t\n\tcout << n << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1066",
    "index": "E",
    "title": "Binary Numbers AND Sum",
    "statement": "You are given two huge binary integer numbers $a$ and $b$ of lengths $n$ and $m$ respectively. You will repeat the following process: if $b > 0$, then add to the answer the value $a~ \\&~ b$ and divide $b$ by $2$ rounding down (i.e. remove the last digit of $b$), and repeat the process again, otherwise stop the process.\n\nThe value $a~ \\&~ b$ means bitwise AND of $a$ and $b$. Your task is to calculate the answer modulo $998244353$.\n\nNote that you should add the value $a~ \\&~ b$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $a = 1010_2~ (10_{10})$ and $b = 1000_2~ (8_{10})$, then the value $a~ \\&~ b$ will be equal to $8$, not to $1000$.",
    "tutorial": "To solve this problem let's take a look which powers of $2$ in $a$ will be affected by powers of $2$ in $b$. Firstly, let's reverse numbers. Let's carry the current power of $2$ (let it be $pw$), the current sum of powers of $2$ in $a$ from the position $0$ to the current position inclusive (let it be $res$) and the answer is $ans$. Initially, $pw = 1$, $res = 0$ and $ans = 0$. Let's iterate over all bits of $b$ from $0$ to $m - 1$. Let the current bit in $b$ have the number $i$. Firstly, if $i < n$ and $a_i = 1$ then set $res := res + pw$ (in other words, we add to the sum of powers of $2$ in $a$ the current power of $2$). If $b_i = 1$ then this bit will add to the answer all the powers of $2$ in $a$ from $0$ to $i$ inclusive (in other words, $res$), so if it is, then set $ans := ans + res$. And after all we can set $pw := pw + pw$ and go on to $i+1$. And don't forget to take all values modulo $998244353$ to avoid overflow.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int a, int b) {\n\ta += b;\n\tif (a < 0) a += MOD;\n\tif (a >= MOD) a -= MOD;\n\treturn a;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tstring s, t;\n\tcin >> s >> t;\n\t\n\tint pw = 1;\n\tint res = 0;\n\tint ans = 0;\n\t\n\tfor (int i = 0; i < m; ++i) {\n\t\tif (i < n && s[n - i - 1] == '1') {\n\t\t\tres = add(res, pw);\n\t\t}\n\t\tif (t[m - i - 1] == '1') {\n\t\t\tans = add(ans, res);\n\t\t}\n\t\tpw = add(pw, pw);\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1066",
    "index": "F",
    "title": "Yet another 2D Walking",
    "statement": "Maksim walks on a Cartesian plane. Initially, he stands at the point $(0, 0)$ and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point $(0, 0)$, he can go to any of the following points in one move:\n\n- $(1, 0)$;\n- $(0, 1)$;\n- $(-1, 0)$;\n- $(0, -1)$.\n\nThere are also $n$ \\textbf{distinct} key points at this plane. The $i$-th point is $p_i = (x_i, y_i)$. It is guaranteed that $0 \\le x_i$ and $0 \\le y_i$ and there is no key point $(0, 0)$.\n\nLet the first level points be such points that $max(x_i, y_i) = 1$, the second level points be such points that $max(x_i, y_i) = 2$ and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level $i + 1$ if he does not visit all the points of level $i$. He starts visiting the points from the minimum level of point from the given set.\n\nThe distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$ where $|v|$ is the absolute value of $v$.\n\nMaksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "The main idea is that we don't need more than $2$ border points on each level. So if we consider than the point $p = (x_p, y_p)$ is less than point $q = (x_q, y_q)$ when $p_x < q_x$ or $p_x = q_x$ and $p_y > q_y$ then let's distribute all the points by their levels using std::map or something like it, sort points on each level by the comparator above and remain the first one and the last one on each level. Also let's add the fictive level $0$ with the point $(0, 0)$. It is always true to remain at most $2$ points and can be easily proved but this fact is very intuitive I think. Now let's do dynamic programming on the points. $dp_{i, j}$ means that now we are at the level $i$ and stay in the first point (if $j = 0$) or in the last point (if $j = 1$) and we are already visit all the points on the level $i$. The value of this dynamic programming is the minimum possible total distance to reach this state. Initially, $dp_{0, 0} = dp_{0, 1} = 0$, other values are equal to $\\infty$. Let's calculate this dynamic programming in order of increasing levels. Let $p_{lvl, 0}$ be the first key point at the level $lvl$ and $p_{lvl, 1}$ be the last key point at the level $lvl$. Now if we are at the level $lvl$ and the previous level is $plvl$, these $4$ transitions are sufficient to calculate states of dynamic programming on the current level: $dp_{lvl, 0} = min(dp_{lvl, 0}, dp_{plvl, 0} + dist(p_{plvl, 0}, p_{lvl, 1}) + dist(p_{lvl, 1}, p_{lvl, 0})$; $dp_{lvl, 0} = min(dp_{lvl, 0}, dp_{plvl, 1} + dist(p_{plvl, 1}, p_{lvl, 1}) + dist(p_{lvl, 1}, p_{lvl, 0})$; $dp_{lvl, 1} = min(dp_{lvl, 1}, dp_{plvl, 0} + dist(p_{plvl, 0}, p_{lvl, 0}) + dist(p_{lvl, 0}, p_{lvl, 1})$; $dp_{lvl, 1} = min(dp_{lvl, 1}, dp_{plvl, 1} + dist(p_{plvl, 1}, p_{lvl, 0}) + dist(p_{lvl, 0}, p_{lvl, 1})$. There $dist(p, q)$ means the distance between points $p$ and $q$. Let last level we have be $lst$. After calculating this dynamic programming the answer is $min(dp_{lst, 0}, dp_{lst, 1})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long INF64 = 1e18;\n\nlong long dist(pair<int, int> a, pair<int, int> b) {\n\treturn abs(a.first - b.first) + abs(a.second - b.second);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tmap<int, vector<pair<int, int>>> pts;\n\tcin >> n;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\tpts[max(x, y)].push_back(make_pair(x, y));\n\t}\n\tpts[0].push_back(make_pair(0, 0));\n\t\n\tfor (auto &it : pts) {\n\t\tsort(it.second.begin(), it.second.end(), [&](pair<int, int> a, pair<int, int> &b) {\n\t\t\tif (a.first == b.first)\n\t\t\t\treturn a.second > b.second;\n\t\t\treturn a.first < b.first;\n\t\t});\n\t}\n\t\n\tvector<vector<long long>> dp(int(pts.size()) + 1, vector<long long>(2, INF64));\n\tdp[0][0] = dp[0][1] = 0;\n\t\n\tint lvl = 0;\n\tint prv = 0;\n\tfor (auto &it : pts) {\n\t\t++lvl;\n\t\t\n\t\tpair<int, int> curl = it.second[0];\n\t\tpair<int, int> curr = it.second.back();\n\t\t\n\t\tpair<int, int> prvl = pts[prv][0];\n\t\tpair<int, int> prvr = pts[prv].back();\n\t\t\n\t\tdp[lvl][0] = min(dp[lvl][0], dp[lvl - 1][0] + dist(prvl, curr) + dist(curl, curr));\n\t\tdp[lvl][0] = min(dp[lvl][0], dp[lvl - 1][1] + dist(prvr, curr) + dist(curl, curr));\n\t\tdp[lvl][1] = min(dp[lvl][1], dp[lvl - 1][0] + dist(prvl, curl) + dist(curl, curr));\n\t\tdp[lvl][1] = min(dp[lvl][1], dp[lvl - 1][1] + dist(prvr, curl) + dist(curl, curr));\n\t\t\n\t\tprv = it.first;\n\t}\n\t\n\tcout << min(dp[lvl][0], dp[lvl][1]) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1067",
    "index": "A",
    "title": "Array Without Local Maximums ",
    "statement": "Ivan unexpectedly saw a present from one of his previous birthdays. It is array of $n$ numbers from $1$ to $200$. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally:\n\n$a_{1} \\le a_{2}$,\n\n$a_{n} \\le a_{n-1}$ and\n\n$a_{i} \\le max(a_{i-1}, \\,\\, a_{i+1})$ for all $i$ from $2$ to $n-1$.\n\nIvan does not remember the array and asks to find the number of ways to restore it. Restored elements also should be integers from $1$ to $200$. Since the number of ways can be big, print it modulo $998244353$.",
    "tutorial": "Let's find solution with complexity $O(n \\cdot a^2)$. We can count $dp[prefix][a][flag]$ - quantity of ways to restore element from $1$ to $pref$ with last element equalls to $a$, $flag = 0$ means that previous element is less then the last or last element is first, $flag = 1$ - the opposite. So $dp[pref][a][0] = \\sum_{i=1}^{a-1} (dp[pref-1][i][1] + dp[pref-1][i][0])$, $dp[pref][a][1] = dp[pref-1][a][0] + \\sum_{i=a}^{200} dp[pref-1][i][1]$. Now let's count $prefix \\_ sums[a][flag] = \\sum_{i=1}^{a} dp[pref][i][flag]$ on each prefix before counting all $dp[pref]$, so we can recalculate dp in O(1) time. Complexity is $O(n \\cdot a)$.",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1067",
    "index": "B",
    "title": "Multihedgehog",
    "statement": "Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least $3$ (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself $k$-multihedgehog.\n\nLet us define $k$-multihedgehog as follows:\n\n- $1$-multihedgehog is hedgehog: it has one vertex of degree at least $3$ and some vertices of degree 1.\n- For all $k \\ge 2$, $k$-multihedgehog is $(k-1)$-multihedgehog in which the following changes has been made for each vertex $v$ with degree 1: let $u$ be its only neighbor; remove vertex $v$, create a new hedgehog with center at vertex $w$ and connect vertices $u$ and $w$ with an edge. New hedgehogs can differ from each other and the initial gift.\n\nThereby $k$-multihedgehog is a tree. Ivan made $k$-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed $k$-multihedgehog.",
    "tutorial": "Solution 1: Firstly let's find all vertices with degree $1$. Now we can delete them and all, verticies which were incident to them must became verticies with degree $1$. And also for each new veretice with degree $1$ we must have already deleted not less then $3$ verticies. If initial graph was $k$-multihedgehog, after deleting vertices with degree $1$ it would became $k-1$-multihedgehog. It could be realised using bfs starting from all initial vertices with degree $1$. Complexity is $O(n)$. Solution 2: First of all let's find diametr of the graph. After that we can find middle vertex in diameter and check if it is a center of $k$-multihedgehog using simple dfs. Complexity is $O(n)$.",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1067",
    "index": "C",
    "title": "Knights",
    "statement": "Ivan places knights on infinite chessboard. Initially there are $n$ knights. If there is free cell which is under attack of at least $4$ knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the end does not depend on the order in which new knights are placed.\n\nIvan asked you to find initial placement of exactly $n$ knights such that in the end there will be at least $\\lfloor \\frac{n^{2}}{10} \\rfloor$ knights.",
    "tutorial": "If after some loops of the process we will have two neighboring lines with length $x$ total complexity of knights would be not less than $O( \\frac{x^2}{4} )$. In this construction: $0$ - initial placement. $1, \\,\\, 2$ - added knights. Would be two neighboring lines with length $O(\\frac{2 \\cdot n}{3})$ so total complexity of knights would be $O( \\frac{(\\frac{2 \\cdot n}{3})^2}{4} ) = O( \\frac{n^2}{9} )$. The possible way to facilitate the invention this (or over) solutions is to write process modeling. Bonus: Solve this problem with complexity $O( \\frac{n^2}{6} )$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1067",
    "index": "D",
    "title": "Computer Game",
    "statement": "Ivan plays some computer game. There are $n$ quests in the game. Each quest can be upgraded once, this increases the reward for its completion. Each quest has $3$ parameters $a_{i}$, $b_{i}$, $p_{i}$: reward for completing quest before upgrade, reward for completing quest after upgrade ($a_{i} < b_{i}$) and probability of successful completing the quest.\n\nEach second Ivan can try to complete one quest and he will succeed with probability $p_{i}$. In case of success Ivan will get the reward and opportunity to upgrade any one quest (not necessary the one he just completed). In case of failure he gets nothing. Quests \\textbf{do not vanish} after completing.\n\nIvan has $t$ seconds. He wants to maximize expected value of his total gain after $t$ seconds. Help him to calculate this value.",
    "tutorial": "Let's denote $max(b_{i} p_{i})$ as $M$. Independent of our strategy we cannot get more than $M$ in one second (in expected value). But if we could upgrade one quest, we would upgrade the quest which maximizes $b_{i} p_{i}$ and then try to complete only this quest each second, thus getting $+M$ to expected value each second. Therefore, our strategy looks like this: try to complete quests in some order, once we complete one quest we will always get $+M$ to expected value each second. This observation leads to DP solution. Once we have one quest completed we already know what we will get, so interesting states are only those in which no quests are completed yet. Then it is not important what quests we tried to complete before, the only important parameter is remaining time. $dp_{t+1} = max(p_{i} (a_{i} + tM) + (1 - p_{i}) dp_{t})$. If we succeed then we will get $a_{i}$ as a reward and for remaining $t$ seconds we will get $M$ each second, otherwise we get nothing and now only $t$ seconds left. This solution works in $O(nT)$ time which is too slow. We can slightly rewrite the formula for transition: $dp_{t+1} = max(p_{i} (a_{i} + tM) + (1 - p_{i}) dp_{t}) = dp_{t} + max(p_{i} (tM - dp_{t}) + p_{i} a_{i})$. Now we can see that we take maximum value of functions $p_{i} \\cdot x + p_{i} a_{i}$ in point $x_{t} = tM - dp_{t}$. We can build convex hull on these lines thus getting $O(n \\log n + T \\log n)$ solution. But that's not all. We can actually prove that $x_{t} \\le x_{t+1}$ or, after some substitutions and simplifications, $dp_{t+1} - dp_{t} \\le M$. This we will prove by actual meaning of $dp_{t}$. Take optimal solution for $t+1$ seconds and do the same for $t$ seconds, except that we don't have last second, so we will just drop our action. But we can't gain more than $M$ in one second, so this drop cannot decrease answer more than $M$. Thus the inequality is proven. This means that we only move right along over convex hull, so for each line there will be consecutive seconds in which we are using that line. If we could somehow determine these segments of times for each line and learn how to make many DP transitions at once then we would solve the problem even faster. Let's start with learning how to make many DP transitions (when we are staying on one line for the whole time). It is more clear using first formula for DP transition: $dp_{t+1} = p_{i} (a_{i} + tM) + (1 - p_{i}) dp_{t}$ (we don't have max now because we already know which line to use). We can see that to get vector $\\begin{pmatrix} dp_{t+1} & t+1 & 1 \\end{pmatrix}^{T}$ from vector $\\begin{pmatrix} dp_{t} & t & 1 \\end{pmatrix}^{T}$ we can apply linear transformation i.e. multiply by some matrix: $\\begin{pmatrix} dp_{t+1} \\\\ t+1 \\\\ 1 \\end{pmatrix} = \\begin{pmatrix} 1 - p_{i} & p_{i} M & p_{i} a_{i} \\\\ 0 & 1 & 1 \\\\ 0 & 0 & 1 \\end{pmatrix} \\begin{pmatrix} dp_{t} \\\\ t \\\\ 1 \\end{pmatrix}$ To apply it $k$ times just use binary exponentiation to get $k$-th power of transition matrix. To determine how long we actually have to stay on given line we will use binary search on answer. We know for which value of $x$ we should move to the next line and we know that $x$ increases with each second, so we can try to stay on given line for some time and see if we should actually change the line. This is already $O(n (\\log n + \\log ^{2} T) )$ solution, but we can improve it one more time by making binary exponentiation and binary search on power for this exponentiation at the same time. Final complexity is $O(n (\\log n + \\log T) )$",
    "tags": [
      "dp",
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1067",
    "index": "E",
    "title": "Random Forest Rank",
    "statement": "Let's define rank of undirected graph as rank of its adjacency matrix in $\\mathbb{R}^{n \\times n}$.\n\nGiven a tree. Each edge of this tree will be deleted with probability $1/2$, all these deletions are independent. Let $E$ be the expected rank of resulting forest. Find $E \\cdot 2^{n-1}$ modulo $998244353$ (it is easy to show that $E \\cdot 2^{n-1}$ is an integer).",
    "tutorial": "I'll try to explain how to come up with this solution rather than just state the fact. For those who are more interested in getting AC, here is your fact: rank of a forest is twice the size of maximal matching. When we see expected value, we usually want to somehow rewrite the thing under the expected value, apply linearity of expectation and then calculate some independent values. But that's not the case: rank behave strangely and we cannot rewrite it as sum of something, at least I don't know any such solutions (if you do, please write them in the comments). So it looks like we are forced to understand what rank is. The rank of a matrix is a size of its largest non-vanishing minor. But our matrix is symmetric, maybe we can look only at symmetric minors (in a sense that we use the same set of rows and columns)? This is actually true but it is just a fact from linear algebra (seems to be not very well known) and has little to do with our problem, so I'll drop its proof and if someone is interested, ask me in comments. Why do we like symmetric minors? Because they correspond to induced subgraphs of our graph. And all induced subgraphs of a forest are forests too! So let's study when a forest has full rank. To do it, let's calculate determinant of its matrix. Matrix has full rank iff its determinant is non-zero. Let's write a determinant as a sum over all permutations. $det A = \\sum_{\\pi} \\prod_{i=1}^{n} A_{i \\pi_{i}}$ If $A_{i \\pi_{i}} \\ne 0$ then we have edge $(i, \\pi_{i})$ in our forest. Each permutation is a product of independent cycles. So to have non-zero product $\\prod_{i=1}^{n} A_{i \\pi_{i}}$ all the permutation cycles should be cycles in the forest. But forests have no cycles without repeating vertices! Well, actually they do: each edge generate one cycle of length $2$. And that's all, there are no other cycles in forest ($1$ vertex is not a cycle, because we don't have self-loops). To have non-zero product $\\prod_{i=1}^{n} A_{i \\pi_{i}}$ all cycles of permutation must have length $2$ and correspond to edges of forest. So we can divide all vertices in pairs, and in each pair there is an edge. That's the definition of perfect matching. Why can't they still result in zero sum? Because if there is a perfect matching in a forest then it is unique, so we actually have no more than one non-zero summand. OK, forest has full rank is equivalent to forest has perfect matching. Suppose that $m$ is the size of maximal matching of a forest. Then no its induced subgraph of size strictly greater than $2m$ can have perfect matching. And there is a subgraph of size exactly $2m$ which does have perfect matching: the ends of edges in maximal matching. Cool, we have proven the fact from the beginning. If you just want AC, continue reading from here. Now we have to calculate expected size of maximal matching. That sound much easier: we already have a linear DP which calculates maximal matching, and its values are exactly sizes of current maximal matching. To remind: $dp[v][taken]$ is a size of maximal matching in subtree rooted at $v$ where boolean flag $taken$ means did we already cover vertex $v$ or is it still free. All we have to do is to change the value stored in DP for expected value and also calculate probabilities to actually be in state with given flag $taken$. Complexity - $O(n)$.",
    "tags": [
      "dp",
      "graph matchings",
      "math",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1068",
    "index": "A",
    "title": "Birthday",
    "statement": "Ivan is collecting coins. There are only $N$ different collectible coins, Ivan has $K$ of them. He will be celebrating his birthday soon, so all his $M$ freinds decided to gift him coins. They all agreed to three terms:\n\n- Everyone must gift as many coins as others.\n- All coins given to Ivan must be different.\n- Not less than $L$ coins from gifts altogether, must be new in Ivan's collection.\n\nBut his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.",
    "tutorial": "To get $L$ new coins irrespective of the Ivan's collection he must get not less than $L+K$ coins as a present. Therefore each friend should gift at least $X = \\lceil \\frac{L+K}{M} \\rceil$ coins. But it may be not possible for all friends to gift $X$ coins if $X \\cdot M > N$. Complexity is $O(1)$.",
    "tags": [
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1068",
    "index": "B",
    "title": "LCM",
    "statement": "Ivan has number $b$. He is sorting through the numbers $a$ from $1$ to $10^{18}$, and for every $a$ writes $\\frac{[a, \\,\\, b]}{a}$ on blackboard. Here $[a, \\,\\, b]$ stands for least common multiple of $a$ and $b$. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the board if he would finish the task. Help him to find the quantity of different numbers he would write on the board.",
    "tutorial": "$\\frac{[a, \\,\\, b]}{a} = \\frac{b}{(a, \\,\\, b)}$, here $(a, \\,\\, b)$ is greatest common divisor. Let's see how many different values can have $c = (a, \\,\\, b)$. All values $c$ that divides $b$ are reachable if $a = c$ and every value of $(a, \\,\\, b)$ divides $b$. So answer is number of divisors of $b$. It can be calculated in $O(\\sqrt{b})$ time.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1068",
    "index": "C",
    "title": "Colored Rooks",
    "statement": "Ivan is a novice painter. He has $n$ dyes of different colors. He also knows exactly $m$ pairs of colors which harmonize with each other.\n\nIvan also enjoy playing chess. He has $5000$ rooks. He wants to take $k$ rooks, paint each of them in one of $n$ colors and then place this $k$ rooks on a chessboard of size $10^{9} \\times 10^{9}$.\n\nLet's call the set of rooks on the board connected if from any rook we can get to any other rook in this set moving only through cells with rooks from this set. Assume that rooks can jump over other rooks, in other words a rook can go to any cell which shares vertical and to any cell which shares horizontal.\n\nIvan wants his arrangement of rooks to have following properties:\n\n- For any color there is a rook of this color on a board;\n- For any color the set of rooks of this color is connected;\n- For any two different colors $a$ $b$ union of set of rooks of color $a$ and set of rooks of color $b$ is connected if and only if this two colors harmonize with each other.\n\nPlease help Ivan find such an arrangement.",
    "tutorial": "Let's put rooks with color $i$ just on line number $i$. Then, obviously, for any color the set of rooks of this color would be connected. Let's put rooks on positions $(i, \\,\\, i)$ for $i$ from $1$ to $n$. After that for any color there is a rook of this color on a board and for any two different colors $a$ $b$ union of set of rooks of color $a$ and set of rooks of color $b$ wouldn't be connected. And for final step we can do the following for every pair of harmonizing colors $a$ $b$: let $j$ be index of first column without rooks, put rooks on cells ($j, \\,\\, a$) and ($j, \\,\\, b$). After that for colors $a$ $b$ union of set of rooks of color $a$ and set of rooks of color $b$ would become connected and for other pairs the connectedness doesn't change. Total number of rooks is $n + 2 \\cdot m$.",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1071",
    "index": "E",
    "title": "Rain Protection",
    "statement": "A lot of people dream of convertibles (also often called cabriolets). Some of convertibles, however, don't have roof at all, and are vulnerable to rain. This is why Melon Ask, the famous inventor, decided to create a rain protection mechanism for convertibles.\n\nThe workplace of the mechanism is a part of plane just above the driver. Its functional part consists of two rails with sliding endpoints of a piece of stretching rope. For the sake of simplicity we can consider this as a pair of parallel segments in a plane with the rope segment, whose endpoints we are free to choose as any points on these rails segments.\n\nThe algorithmic part of the mechanism detects each particular raindrop and predicts when and where it reaches the plane. At this exact moment the rope segment must contain the raindrop point (so the rope adsorbs the raindrop).\n\nYou are given the initial position of the rope endpoints and all information about raindrops. You are to choose the minimal possible speed $v$ of the endpoints sliding (both endpoints can slide in any direction along their segments independently of each other) in such a way that it is possible to catch all raindrops moving both endpoints with speed not greater than $v$, or find out that it's impossible no matter how high the speed is.",
    "tutorial": "First, let's find out if we can catch all raindrops for a fixed speed $v$. Assume that the endpoints are at $(e_1, 0)$ and $(e_2, h)$ at any moment. Consider the point $(e_1, e_2)$ for this state (we call it the state point for this state). From now on we work with these points. We know that this state point can move with speed at most $v$ in both directions independently, that is, if the state point is $(x, y)$ at the moment $t$, then it'll be in $[x - v\\cdot\\text{d}t, x + v\\cdot\\text{d}t]\\times[y - v\\cdot\\text{d}t, y + v\\cdot\\text{d}t]$ at the moment $t + \\text{d}t$. It turns out that for each $i$ one of the following takes place: we cannot catch raindrops from $1$ to $i$; we can catch these raindrops and there is exactly one possible option for the state point at the moment $t_i$; we can catch these raindrops and there is a segment on the plane such that the state point at the moment $t_i$ can be in any point of this segment and nowhere else. Indeed, we prove this by induction. Its basis for $t_0 = 0$ is trivial. Let's prove its step. If we cannot catch raindrops from $1$ to $i$ then we cannot catch all raindrops from $1$ to $i + 1$. If there is some segment where the state point can be at $t_i$ (possibly a segment of length $0$) then at the moment $t_{i+1}$ the state point can be anywhere inside the convex hull of the union of two squares. The squares are $[x - v\\cdot\\text{d}t, x + v\\cdot\\text{d}t]\\times[y - v\\cdot\\text{d}t, y + v\\cdot\\text{d}t]$ for the endpoints $(x, y)$ of the segment at $t_i$, and here $\\text{d}t$ is $t_{i + 1} - t_i$.But we also know that the rope must contain one particular point at the moment $t_{i+1}$, which can be expressed as a linear equation of the state point at the moment $t_{i+1}$. So to obtain the required segment for $t_{i+1}$ one should intersect a line with a convex hull of $8$ points (which is in fact no more than a hexagon). However, it's not all: the endpoints of the rope mustn't leave the rails which means that the convex hull should be first intersected with the rectangle $[0, w]\\times[0, w]$. However, it can be done after intersecting with the required line. But we also know that the rope must contain one particular point at the moment $t_{i+1}$, which can be expressed as a linear equation of the state point at the moment $t_{i+1}$. So to obtain the required segment for $t_{i+1}$ one should intersect a line with a convex hull of $8$ points (which is in fact no more than a hexagon). However, it's not all: the endpoints of the rope mustn't leave the rails which means that the convex hull should be first intersected with the rectangle $[0, w]\\times[0, w]$. However, it can be done after intersecting with the required line. So the solution now is the following: First we check if the answer is $-1$. This is the case when there is a triple of non-collinear raindrop points which should be on the rope simultaneously or there is a raindrop which is not on the rope at the moment $0$, while it should be. The simplest way to check it is to check if we can catch all raindrops with speed $w$. First, it involves no case handling; second, we will use this function later anyway. After this we run a binary search to find the minimal possible value for speed in such a way that it's possible to catch all the raindrops. That's the idea of the solution. Now let's consider precision issues. The explanation below contains some notions which may be new for a particular reader. Please don't be afraid of them, I explain what they mean right after introducing them. I refer to them by their names first for readers familiar with these notions to get the point faster and maybe skip the explanation which follows. For anyone who doesn't want to read the full proof and wants to know the summary: long double precision should be enough to get AC with the solution above (handling lines intersections properly). Define a function $f_i(v)$ as the $\\ell_{\\infty}$-diameter of the set of possible locations of the state point at the moment $t_i$ for the speed $v$, that is, $f_i(v) = 0$ if this set is empty or consists of a single point; $f_i(v) = \\max\\left(|x_1 - x_2|, |y_1 - y_2|\\right)$ if this set is a segment between $(x_1, y_1)$ and $(x_2, y_2)$. In other words, every time we calculate the length of any segment, we do it in this metric, since it'll be convenient for our purposes. Let $\\hat{v}$ be the correct answer, and let $\\varepsilon$ be a sufficiently small positive number (but still much bigger than the machine epsilon, of course). One can see that all $t_i$-s can be divided into two groups which differ a lot by their meaning: those for which we must catch one raindrop at this moment (or many equal raindrops, which doesn't matter), those for which we must catch more than one raindrop at this moment. For the first ones we basically need to intersect a polygon with a line, but for the second ones the state point at $t_i$ can be determined and doesn't depend on the speed (or such $t_i$-s force our algorithm to tell that the goal is impossible in the very beginning). Let's call the raindrops with $t_i$ of the first type simple, and the others complicated. Let's prove the following lemmas: Lemma 1a. Let $i$ be an index of a simple raindrop. For $v = \\hat{v} + \\varepsilon$ each $f_i(v)$ is at least $\\varepsilon$. Lemma 1b. Let $i$ be an index of a complicated raindrop. For $v = \\hat{v} + \\varepsilon$ the corresponding state point position at the moment $t_i$ is at least $\\varepsilon$ away from the border of a polygon before intersecting with $[0, w]\\times[0, w]$. Lemma 2. Let $idx$ be the index of the first raindrop we cannot catch for a value of speed which is very close to $\\hat{v}$ but is less than it. Then for $v = \\hat{v} - \\varepsilon$ either our algorithm halts earlier than it handles the $idx$-th raindrop, or the corresponding line to this raindrop (or the corresponding point if the raindrop is complicated) is at least $\\varepsilon$ away from the corresponding state points polygon (again, in $\\ell_{\\infty}$ metric). One can see that proving these lemmas is sufficient to validate the solution. Indeed, comparing all intersections with quite good precision will move the binary search borders into the $(\\hat{v} - \\varepsilon, \\hat{v} + \\varepsilon)$ interval which is enough to stop for some $\\varepsilon$. Proof of lemma 1 (both variations). Fix $i$. We know that the $(i-1)$-th set $S_{i-1}(v)$ of possible state points for $v = \\hat{v}$ is not empty (from the definition of $\\hat{v}$). It's clear that the $(i-1)$-th set for $v = \\hat{v} + \\varepsilon$ is a superset of $S_{i-1}(\\hat{v})$, because we can move no faster than with the speed of $\\hat{v} < \\hat{v} + \\varepsilon$. To get $S_i$, we move from $S_{i-1}$ no more than $(t_i - t_{i-1})(\\hat{v} + \\varepsilon) \\le (t_i - t_{i-1})\\hat{v} + \\varepsilon$. This finishes the proof of 1b. Since $S_i(\\hat{v})$ is also not empty, $S_i(\\hat{v} + \\varepsilon)$ is at least the segment $S_i(\\hat{v})$ plus all the points on the corresponding line at the distance no more than $\\varepsilon$, that is, at least $\\varepsilon$ longer than $S_i(\\hat{v})$, hence is at least $\\varepsilon$ long, qed. Proof of lemma 2. Assume our algorithm made at least $idx$ iterations. Consider the corresponding polygon at the moment $t_{idx}$. We know that for $v = \\hat{v}$ this polygon intersects the required line/point, but its interior doesn't. That means that each point of the possible set of state points at the moment isn't inside the polygon. That means that if we reduce $v$ by $\\varepsilon$ then the distance from every point of this set to the polygon is at least $\\varepsilon$, qed. To summarize, the only precision issue we can meet is when we intersect two or more lines for complicated raindrops. This part can be implemented in integers, but let's dive into this anyway. One can see that catching raindrop at $(x, y)$ means that or Since the coefficients of this line equation are of order $h$, the coordinates of its solution are some rationals with the denominator of order $1/h^2$. If we then want to check if such point belongs to another line, we want to compare some integer divided by another integer which is $\\le h^2$ with the third integer, so we need an epsilon less than $1/h^2$.",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1073",
    "index": "A",
    "title": "Diverse Substring",
    "statement": "You are given a string $s$, consisting of $n$ lowercase Latin letters.\n\nA substring of string $s$ is a continuous segment of letters from $s$. For example, \"defor\" is a substring of \"codeforces\" and \"fors\" is not.\n\nThe length of the substring is the number of letters in it.\n\nLet's call some string of length $n$ diverse if and only if there is no letter to appear strictly more than $\\frac n 2$ times. For example, strings \"abc\" and \"iltlml\" are diverse and strings \"aab\" and \"zz\" are not.\n\nYour task is to find \\textbf{any} diverse substring of string $s$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.",
    "tutorial": "Notice that the string of two distinct letter is already diverse. That implies that the answer is \"NO\" if and only if all the letters in the string are the same. Otherwise you can check all pairs of adjacent letters in $O(n)$. Overall complexity: $O(n)$.",
    "code": "n = int(input())\ns = input()\nfor i in range(n - 1):\n\tif (s[i] != s[i + 1]):\n\t\tprint(\"YES\")\n\t\tprint(s[i], s[i + 1], sep=\"\")\n\t\texit(0)\nprint(\"NO\")",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1073",
    "index": "B",
    "title": "Vasya and Books",
    "statement": "Vasya has got $n$ books, numbered from $1$ to $n$, arranged in a stack. The topmost book has number $a_1$, the next one — $a_2$, and so on. The book at the bottom of the stack has number $a_n$. \\textbf{All numbers are distinct}.\n\nVasya wants to move all the books to his backpack in $n$ steps. During $i$-th step he wants to move the book number $b_i$ into his backpack. If the book with number $b_i$ is in the stack, he takes this book and all the books \\textbf{above} the book $b_i$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $[1, 2, 3]$ (book $1$ is the topmost), and Vasya moves the books in the order $[2, 1, 3]$, then during the first step he will move two books ($1$ and $2$), during the second step he will do nothing (since book $1$ is already in the backpack), and during the third step — one book (the book number $3$). \\textbf{Note that $b_1, b_2, \\dots, b_n$ are distinct.}\n\nHelp Vasya! Tell him the number of books he will put into his backpack during each step.",
    "tutorial": "Let's maintain the pointer $pos$ to the topmost non-deleted book and whether each book whether is removed from the stack or not. Initially, all books are in a stack, and $pos$ is 0 (if we store the array 0-indexed). We will process the array $B$ in the order $b_1, b_2, \\dots b_n$. If the current book $b_i$ is removed from the stack, then the answer for it is zero. Otherwise, we will increment the pointer $pos$ until the equality $a_{pos} = b_i$ is satisfied, while marking all the intermediate books in the array $u$. After that, the answer for the book $b_i$ will be the number of marked books in the $u$ array (including itself). Since the pointer $pos$ shifts $n$ times at total, we get a solution with an $O(n)$ complexity.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(2e5) + 9;\n\nint n;\nint a[N];\nint b[N];\nbool u[N];\n\nint main() {\n//\tfreopen(\"input.txt\", \"r\", stdin);\n\tscanf(\"%d\", &n);\n    for(int i = 0; i < n; ++i) {\n    \tscanf(\"%d\", a + i);\n    }\n    for(int i = 0; i < n; ++i){\n    \tscanf(\"%d\", b + i);\n    }\n\t\n\tint pos = 0;\n\tfor(int i = 0; i < n; ++i){\n\t\tint x = b[i];\n\t\tif(u[x]){\n\t\t\tprintf(\"0 \");\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tint cnt = 0;\n\t\twhile(true){\n\t\t\t++cnt;\n\t\t\tu[a[pos]] = true;\n\t\t\tif(a[pos] == x) break;\n\t\t\t++pos;\n\t\t} \n\t\t\n\t\t++pos;\n\t\tprintf(\"%d \", cnt);\n\t}    \n\t\n\tputs(\"\");\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1073",
    "index": "C",
    "title": "Vasya and Robot",
    "statement": "Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $(0, 0)$. Robot can perform the following four kinds of operations:\n\n- U — move from $(x, y)$ to $(x, y + 1)$;\n- D — move from $(x, y)$ to $(x, y - 1)$;\n- L — move from $(x, y)$ to $(x - 1, y)$;\n- R — move from $(x, y)$ to $(x + 1, y)$.\n\nVasya also has got a sequence of $n$ operations. Vasya wants to modify this sequence so after performing it the robot will end up in $(x, y)$.\n\nVasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: $maxID - minID + 1$, where $maxID$ is the maximum index of a changed operation, and $minID$ is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices $2$, $5$ and $7$ are changed, so the length of changed subsegment is $7 - 2 + 1 = 6$. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is $1$.\n\n\\textbf{If there are no changes, then the length of changed subsegment is $0$. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.}\n\nHelp Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from $(0, 0)$ to $(x, y)$, or tell him that it's impossible.",
    "tutorial": "Denote $d = |x| + |y|$. If $d > n$, then the answer is -1, since the robot will not have the time to reach $(x, y)$ cell in $n$ steps. Also, if $d$ and $n$ have different parity, then the answer is also -1, as in one move the robot changes the parity of the sum of its coordinates. In all other cases, the answer exists. Let's use binary search to solve this problem. Consider all segments of length $len$. For a fixed length of the segment $len$, let's iterate over the position of the beginning of the segment $l$. At the same time, we will maintain the cell that the robot will stop at if it execute all commands, except commands with indices $l, l + 1, \\dots, l + len - 1$. We denote this position as $(x_0, y_0)$. We also calculate the distances from the cell $(x_0, y_0)$ to the cell $(x, y)$ - the value $d_0 = |x - x_0| + |y - y_0|$. If there is at least one position of the beginning of the segment for which $d_0 \\le len$, then we can change the segment of length $len$ so that the robot comes to the $(x, y)$ cell, otherwise it can't.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(1e5) + 9;\n\nstring s;\nint n;\nint x, y;\n\nvoid upd(pair<int, int> &pos, char mv, int d){\n\tif(mv == 'U')\n\t\tpos.second += d;\n\tif(mv == 'D')\n\t\tpos.second -= d;\n\tif(mv == 'L')\n\t\tpos.first -= d;\n\tif(mv == 'R')\n\t\tpos.first += d;\n}\n\nbool can(pair<int, int> u, pair<int, int> v, int len){\n\tint d = abs(u.first - v.first) + abs(u.second - v.second);\n\tif(d % 2 != len % 2) return false;\n\treturn len >= d;\n}\n\nbool ok(int len){\n\tpair<int, int> pos = make_pair(0, 0);\n\tfor(int i = len; i < n; ++i)\n\t\tupd(pos, s[i], 1);\n\n\tint l = 0, r = len;\n\twhile(true){\n\t\tif(can(pos, make_pair(x, y), len))\n\t\t\treturn true;\n\t\t\n\t\tif(r == n) break;\n\t\tupd(pos, s[l++], 1);\n\t\tupd(pos, s[r++], -1);\t\t\n\t}\n\t\n\treturn false;\n}\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t\n\tcin >> n;\n\tcin >> s;\n\tcin >> x >> y;\n\t\n\tif(!ok(n)){\n\t\tputs(\"-1\");\n\t\treturn 0;\n\t}\n\t\n\tint l = -1, r = n;\n\twhile(r - l > 1){\n\t\tint mid = (l + r) / 2;\n\t\tif(ok(mid)) r = mid;\n\t\telse l = mid;\n\t}\n\t\n\tcout << r << endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1073",
    "index": "D",
    "title": "Berland Fair",
    "statement": "XXI Berland Annual Fair is coming really soon! Traditionally fair consists of $n$ booths, arranged in a circle. The booths are numbered $1$ through $n$ clockwise with $n$ being adjacent to $1$. The $i$-th booths sells some candies for the price of $a_i$ burles per item. Each booth has an unlimited supply of candies.\n\nPolycarp has decided to spend at most $T$ burles at the fair. However, he has some plan in mind for his path across the booths:\n\n- at first, he visits booth number $1$;\n- if he has enough burles to buy \\textbf{exactly one} candy from the current booth, then he buys it immediately;\n- then he proceeds to the next booth in the clockwise order (regardless of if he bought a candy or not).\n\nPolycarp's money is finite, thus the process will end once he can no longer buy candy at any booth.\n\nCalculate the number of candies Polycarp will buy.",
    "tutorial": "Let's code the following process. Go one circle across the booths, calculate the total cost $C$ of sweets bought and the number $S$ of sweets bought. Now you can decrease you money down to $T = T~mod~C$ and add $S \\cdot (T~div~C)$ to answer. It represents that you went maximum number of such circles. The later circles will have smaller cost. Let's continue this process until $T$ becomes smaller than the minimum priced sweet. The number of operations made is $O(\\log T)$. Let $T_{cur}$ be the amount of money before some operation, $C_{cur}$ be the total cost of sweets bought on that operation and $T_{new} = T_{cur}~mod~C_{cur}$. $T_{new}$ is actually smaller than $C_{cur}$ (that's how modulo works) and smaller than $T_{cur} - C_{cur}$ (that's also how modulo works). And these inequalities imply that $T_{new} < \\frac{T_{cur}}{2}$. That leads to about $O(\\log T)$ steps to reach the minimal price. Overall complexity: $O(n \\log T)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\n\ntypedef long long li;\n\nint n;\nint a[N];\n\nvoid get(li T, li& pr, li& cnt){\n\tpr = 0, cnt = 0;\n\tforn(i, n){\n\t\tif (T >= a[i]){\n\t\t\tT -= a[i];\n\t\t\tpr += a[i];\n\t\t\t++cnt;\n\t\t}\n\t}\n}\n\nint main() {\n\tli T;\n\tscanf(\"%d%lld\", &n, &T);\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tint mn = *min_element(a, a + n);\n\tli ans = 0;\n\twhile (T >= mn){\n\t\tli pr, cnt;\n\t\tget(T, pr, cnt);\n\t\tans += cnt * (T / pr);\n\t\tT %= pr;\n\t}\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1073",
    "index": "E",
    "title": "Segment Sum",
    "statement": "You are given two integers $l$ and $r$ ($l \\le r$). Your task is to calculate the sum of numbers from $l$ to $r$ (including $l$ and $r$) such that each number contains \\textbf{at most} $k$ different digits, and print this sum modulo $998244353$.\n\nFor example, if $k = 1$ then you have to calculate all numbers from $l$ to $r$ such that each number is formed using only one digit. For $l = 10, r = 50$ the answer is $11 + 22 + 33 + 44 = 110$.",
    "tutorial": "Let's calculate the answer as the sum of suitable numbers in range $[1; r]$ minus the sum of suitable numbers in range $[1; l - 1]$. Now our problem is to calculate the sum of suitable numbers in range $[1; n]$. The main approach for this problem is digit DP. Let's calculate two dynamic programmings $dp_{pos, mask, f}$ and $dps_{pos, mask, f}$. $pos$ means that now we are at the $pos$-th digit of the number $n$ (at the digit corresponding to $10^{len - pos - 1}$, where $len$ is the decimal length of a number), $mask$ is a binary mask describing digits we already use and $f$ equals $1$ if the current prefix of number we trying to obtain is the same as the prefix of number $n$ (otherwise $f$ equals $0$). So what means $dp_{pos, mask, f}$? It means the count of numbers (in general, not numbers but their prefixes) in range $[1; n]$ of length exactly $|n|$ without leading zeroes corresponding to this state. So what the point of this DP? Its point is helping us to calculate the main DP, $dps_{pos, mask, f}$, which means the sum of numbers (in general, not numbers but their prefixes) in range $[1; n]$ of length exactly $|n|$ without leading zeroes corresponding to this state. How do we calculate the answer? Firstly, let $len$ be the length of $n$. Let $calc(n)$ be the function calculating the sum of numbers from $1$ to $n$ containing at most $k$ different digits. How to calculate it? Let $calcdp(x)$ be the sum of numbers from $1$ to $x$ containing at most $k$ different digits and having length exactly $|x|$. Then $calc(n)$ seems to be pretty easy: for each length $i$ from $1$ to $len-1$ add to the answer $calcdp(10^i - 1)$. And the last step is to add to the answer $calcdp(n)$. How to calculate dynamic programmings? Initially, all states are zeroes (excluding $dp_{0, 0, 1}$, which is $1$). Firstly, let's calculate $dp$. After calculating it we can calculate $dps$ in almost the same way. Let's iterate over all possible lengths and over all possible masks. Let the current state is $dp_{pos, mask, 0}$. Then let's iterate over next digit we will place in this number and place it. If $pos = 0$ then $dig = 1 \\dots 9$ otherwise $dig = 0 \\dots 9$. The transition is pretty easy: $dp_{pos + 1, mask | 2^{dig}, 0} += dp_{pos, mask, 0}$. There $|$ is the bitwise OR operation. For $f = 1$ transitions are almost the same expect the restrictions on digit we place and the state we update. If we now at the position $pos$ with mask $mask$ and $f = 1$ then the current digit of $n$ is $n_{pos}$. Then let's iterate over next digit: $dig = 1 \\dots n_{pos}$ if $pos = 0$ otherwise $dig = 0 \\dots n_{pos}$. The transition is also easy: $dp_{pos + 1, mask | 2^{dig}, dig = n_{pos}} += dp_{pos, mask, f}$. After calculating the previous DP we can calculate $dps$. All the process is the same as in the previous dynamic programming expect the value we will add in transitions. In the previous DP this value was equal $dp_{pos, mask, f}$, in the current DP this value equals to $val = dps_{pos, mask, f} + dig \\cdot 10^{len - pos - 1} \\cdot dp_{pos, mask, f}$. Don't forget to calculate it modulo $998244353$! So after calculating all the values of DPs, what is the answer for $calcdp(n)$? It is $\\sum\\limits_{mask = 0}^{2^{10} - 1} dps_{|n|, mask, 0} + dps_{|n|, mask, 1}$ for all masks with at most $k$ bits. I'm pretty sure that there is another way to avoid leading zeroes in calculating these DPs but this one is very straight-forward and simple.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n\ntypedef pair<long long, int> pt;\n\nconst int N = 20;\nconst int M = 1 << 10;\nconst int MOD = 998244353;\n\nint k;\nint pw10[N];\nint bitCnt[M];\n\npt dp[N][M][2];\n\nint add(int a, int b) {\n\ta += b;\n\tif (a >= MOD) a -= MOD;\n\tif (a < 0) a += MOD;\n\treturn a;\n}\n\nint mul(int a, int b) {\n\treturn a * 1ll * b % MOD;\n}\n\nint calc(const string &s) {\n\tfor (int i = 0; i < N; ++i) {\n\t\tfor (int j = 0; j < M; ++j) {\n\t\t\tdp[i][j][0] = dp[i][j][1] = { 0ll, 0 };\n\t\t}\n\t}\n\t\n\tint len = s.size();\n\tdp[0][0][1] = { 1ll, 0 };\n\tfor (int i = 0; i < len; ++i) {\n\t\tint cdig = s[i] - '0';\n\t\tfor (int mask = 0; mask < M; ++mask) {\n\t\t\tif (dp[i][mask][0].x == 0 && dp[i][mask][1].x == 0) continue;\n\t\t\tfor (int dig = (i == 0); dig <= 9; ++dig) {\n\t\t\t\tint nmask = mask | (1 << dig);\n\t\t\t\tlong long cnt = dp[i][mask][0].x;\n\t\t\t\tint sum = add(dp[i][mask][0].y, mul(dig, mul(pw10[len - i - 1], cnt % MOD)));\n\t\t\t\tdp[i + 1][nmask][0].x += cnt;\n\t\t\t\tdp[i + 1][nmask][0].y = add(dp[i + 1][nmask][0].y, sum);\n\t\t\t}\n\t\t\t\n\t\t\tfor (int dig = (i == 0); dig <= cdig; ++dig) {\n\t\t\t\tint nmask = mask | (1 << dig);\n\t\t\t\tlong long cnt = dp[i][mask][1].x;\n\t\t\t\tint sum = add(dp[i][mask][1].y, mul(dig, mul(pw10[len - i - 1], cnt % MOD)));\n\t\t\t\tdp[i + 1][nmask][dig == cdig].x += cnt;\n\t\t\t\tdp[i + 1][nmask][dig == cdig].y = add(dp[i + 1][nmask][dig == cdig].y, sum);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\tfor (int mask = 0; mask < M; ++mask) {\n\t\tif (bitCnt[mask] > k) continue;\n\t\tans = add(ans, dp[len][mask][0].y);\n\t\tans = add(ans, dp[len][mask][1].y);\n\t}\n\treturn ans;\n}\n\nint calc(long long n) {\n\tint len = to_string(n).size();\n\tint ans = 0;\n\tfor (int l = 1; l < len; ++l) {\n\t\tans = add(ans, calc(string(l, '9')));\n\t}\n\tans = add(ans, calc(to_string(n)));\n\treturn ans;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tpw10[0] = 1;\n\tfor (int i = 1; i < N; ++i) {\n\t\tpw10[i] = mul(pw10[i - 1], 10);\n\t}\n\tfor (int i = 0; i < M; ++i) {\n\t\tbitCnt[i] = __builtin_popcount(i);\n\t}\n\t\n\tlong long l, r;\n\tcin >> l >> r >> k;\n\tint ans = add(calc(r), -calc(l - 1));\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1073",
    "index": "F",
    "title": "Choosing Two Paths",
    "statement": "You are given an undirected unweighted tree consisting of $n$ vertices.\n\nAn undirected tree is a connected undirected graph with $n - 1$ edges.\n\nYour task is to choose two pairs of vertices of this tree (all the chosen vertices \\textbf{should be distinct}) $(x_1, y_1)$ and $(x_2, y_2)$ in such a way that neither $x_1$ nor $y_1$ belong to the simple path from $x_2$ to $y_2$ and vice versa (neither $x_2$ nor $y_2$ should not belong to the simple path from $x_1$ to $y_1$).\n\n\\textbf{It is guaranteed that it is possible to choose such pairs for the given tree.}\n\nAmong all possible ways to choose such pairs you have to choose one with the \\textbf{maximum number of common vertices} between paths from $x_1$ to $y_1$ and from $x_2$ to $y_2$. And among all such pairs you have to choose one with the \\textbf{maximum total length} of these two paths.\n\n\\textbf{It is guaranteed that the answer with at least two common vertices exists for the given tree.}\n\nThe length of the path is the number of edges in it.\n\nThe simple path is the path that visits each vertex at most once.",
    "tutorial": "Firstly, let's call a path from $u$ to $v$ good, if $u$ is a leaf, $v$ is a vertex of degree at least $3$ (the number of their neighbors is at least $3$) and there are no other vertices of degree at least $3$ on this path expect the vertex $v$. The first step of the solution is to remove all the good paths from $u$ to $v$ (but we should not remove the vertex $v$) and remember for each vertex $v$ the sum of two maximum lengths of good paths which end in the vertex $v$. Let this value for the vertex $v$ be $val_v$. For example, if for some vertex $v$ there are $3$ good paths with end in it of lengths $2$, $3$ and $5$ correspondingly, then $val_v$ will be $5 + 3 = 8$. Okay, it is easy to see that the maximum intersection of two paths in the answer will be equal to the length of the diameter of the obtained tree. But we can not take any diameter of this tree and call it the answer because of the second constraint: we need to find some diameter from $x$ to $y$ such that the sum $val_x + val_y$ is maximum possible. How do we do that? There is such an awesome (and well-known) fact that the center of a tree belongs to all diameters of this tree. Let's root the tree by the center of a tree (if the length of the diameter is odd (the center of a tree is an edge) then let's root the tree by any end of this edge, it does not matter). There is one case when the length of the diameter is $1$ but it is pretty trivial to handle it. Now our problem is to find two neighbors of the root of the new tree such that in their subtrees are vertices which form some diameter of this tree and the sum of values of these vertices is maximum possible. Let's calculate the vertex with the maximum distance from a root (and with the maximum possible $val_v$ for equals distances) by simple DFS for each neighbor of a root. It can be done in $O(n)$ and the last part is to find two maximums of this list, it also can be done in $O(n)$ or $O(n \\log n)$, depends on implementation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define size(a) int((a).size())\n\ntypedef pair<int, int> pt;\n\nconst int N = 200 * 1000 + 11;\n\nint n;\nvector<int> g[N];\n\nint p[N];\nint dist[N];\n\nbool bad[N];\nint value[N];\npt res[N];\nvector<pt> best[N];\n\nvoid dfs(int v, int par = -1, int d = 0) {\n\tp[v] = par;\n\tdist[v] = d;\n\tfor (auto to : g[v]) {\n\t\tif (to == par) {\n\t\t\tcontinue;\n\t\t}\n\t\tdfs(to, v, d + 1);\n\t}\n}\n\nint getFarthest(int v) {\n\tdfs(v);\n\tint res = v;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (bad[i]) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (dist[res] < dist[i]) {\n\t\t\tres = i;\n\t\t}\n\t}\n\treturn res;\n}\n\npt get(int v) {\n\treturn { dist[v], value[v] };\n}\n\nint getBetter(int v, int u) {\n\tif (get(v) > get(u)) {\n\t\treturn v;\n\t}\n\treturn u;\n}\n\nint getBest(int v, int par) {\n\tint res = v;\n\tfor (auto to : g[v]) {\n\t\tif (to == par || bad[to]) {\n\t\t\tcontinue;\n\t\t}\n\t\tres = getBetter(res, getBest(to, v));\n\t}\n\treturn res;\n}\n\npt calc(int v) {\n\tdfs(v);\n\t\n\tvector<int> ch;\n\tfor (auto to : g[v]) {\n\t\tif (!bad[to]) {\n\t\t\tch.push_back(to);\n\t\t}\n\t}\n\tif (size(ch) == 1) {\n\t\treturn { v, ch[0] };\n\t}\n\t\n\tvector<int> pref(size(ch));\n\tvector<int> suf(size(ch));\n\tvector<int> best(size(ch));\n\tfor (int i = 0; i < size(ch); ++i) {\n\t\tint to = ch[i];\n\t\tbest[i] = pref[i] = suf[i] = getBest(to, v);\n\t}\n\tfor (int i = 1; i < size(ch); ++i) {\n\t\tpref[i] = getBetter(pref[i], pref[i - 1]);\n\t\tsuf[size(ch) - i - 1] = getBetter(suf[size(ch) - i - 1], suf[size(ch) - i]);\n\t}\n\t\n\tpt ans = { -1, -1 };\n\tpt res = { 0, 0 };\n\tfor (int i = 0; i < size(ch); ++i) {\n\t\tint bst = -1;\n\t\tif (i == 0) {\n\t\t\tbst = suf[i + 1];\n\t\t} else if (i + 1 == size(ch)) {\n\t\t\tbst = pref[i - 1];\n\t\t} else {\n\t\t\tbst = getBetter(pref[i - 1], suf[i + 1]);\n\t\t}\n\t\tpt curRes = { dist[bst] + dist[best[i]], value[bst] + value[best[i]] };\n\t\tif (res < curRes) {\n\t\t\tres = curRes;\n\t\t\tans = { best[i], bst };\n\t\t}\n\t}\n\t\n\treturn ans;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tcin >> n;\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\t\n\tint root = -1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (size(g[i]) > 2) {\n\t\t\troot = i;\n\t\t\tdfs(i);\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (size(g[i]) != 1) {\n\t\t\tcontinue;\n\t\t}\n\t\tint v = i;\n\t\twhile (size(g[v]) < 3) {\n\t\t\tbad[v] = true;\n\t\t\tv = p[v];\n\t\t}\n\t\tbest[v].push_back({dist[i] - dist[v], i});\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (size(best[i]) >= 2) {\n\t\t\tsort(best[i].rbegin(), best[i].rend());\n\t\t\tvalue[i] = best[i][0].first + best[i][1].first;\n\t\t\tres[i] = { best[i][0].second, best[i][1].second };\n\t\t}\n\t}\n\t\n\tint u = getFarthest(root);\n\tint v = getFarthest(u);\n\tvector<int> path;\n\twhile (v != u) {\n\t\tpath.push_back(v);\n\t\tv = p[v];\n\t}\n\tpath.push_back(u);\n\t\n\tpt ans = calc(path[size(path) / 2]);\n\t\n\tprintf(\"%d %d\\n\", res[ans.x].x + 1, res[ans.y].x + 1);\n\tprintf(\"%d %d\\n\", res[ans.x].y + 1, res[ans.y].y + 1);\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1073",
    "index": "G",
    "title": "Yet Another LCP Problem",
    "statement": "Let $\\text{LCP}(s, t)$ be the length of the longest common prefix of strings $s$ and $t$. Also let $s[x \\dots y]$ be the substring of $s$ from index $x$ to index $y$ (inclusive). For example, if $s = $ \"abcde\", then $s[1 \\dots 3] =$ \"abc\", $s[2 \\dots 5] =$ \"bcde\".\n\nYou are given a string $s$ of length $n$ and $q$ queries. Each query is a pair of integer sets $a_1, a_2, \\dots, a_k$ and $b_1, b_2, \\dots, b_l$. Calculate $\\sum\\limits_{i = 1}^{i = k} \\sum\\limits_{j = 1}^{j = l}{\\text{LCP}(s[a_i \\dots n], s[b_j \\dots n])}$ for each query.",
    "tutorial": "At first, implement your favourite string suffix structure for comparing pair of suffixes lexicographically fast enough. For example, it's a Suffix Array + linear LCP + Sparse Table. Now we can compare two suffixes $i$ and $j$ by finding $l = lcp(i, j)$ and comparing $s[i + l]$ with $s[j + l]$. We will process queries online. Let current query be a pair of arrays $a$ ($|a| = k$) and $b$ ($|b| = l$). We will calculate answer in two parts: To calculate the first sum we can sort all $c = a + b$ suffixes in lexicographical order and maintain some information for prefixes of $c$. What information we need to maintain? We need some Data Structure which will hold $lcp$ of suffixes from $a$. When we process some $c_i = b_j$ we need just a total sum of all $lcp$ in the DS. If $c_i = a_j$, we should add to the DS length of $a_j$-th suffix. And when we move from $c_i$ to $c_{i + 1}$ we must recalculate some $lcp$. Since $c$ is sorted, all we need is to set $lcp_k = min(lcp_k, lcp(s[c_i \\dots n], s[c_{i + 1} \\dots n]))$. In fact, this Data Structure is just a $map$. In this $map$ we will hold for each length $l$ number of suffixes with $lcp = l$ (we will hold only non-zero values). When we should add some suffix $a_j$, we manually increase some value by one. Setting $min$ with $v = lcp(s[c_i \\dots n], s[c_{i + 1} \\dots n])$ can be done with decreasing maximum in $map$ while its more than $v$. It can be proven, that there will be $O(|a| + |b|)$ operations with $map$ for one query. The total sum can be maintained in some global variable, which will be recalculated each time $map$ changes. To calculate the second sum we can just reverse $c$ and run the same algorithm. So total complexity is $O(n \\log^2{n} + (\\sum\\limits_{i = 1}^{i = q}{k_i} + \\sum\\limits_{i = 1}^{i = q}{l_i}) \\log{n})$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream &out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream &out, const vector<A> &v) {\n\tout << \"[\";\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nconst int N = 200 * 1000 + 555;\nconst int LOGN = 18;\n\nint n, q;\nchar s[N];\n\nbool read() {\n\tif(!(cin >> n >> q))\n\t\treturn false;\n\tassert(scanf(\"%s\", s) == 1);\n\treturn true;\n}\n\nint c[N], id[N], lcp[N];\nint mn[LOGN][N];\nint lg2[N];\n\nvoid buildSuffArray() {\n\ts[n++] = '$';\n\t\n\tfor(int l = 1; l < 2 * n; l <<= 1) {\n\t\tvector< pair<pt, int> > d;\n\t\tfore(i, 0, n)\n\t\t\td.emplace_back(l == 1 ? pt(s[i], 0) : pt(c[i], c[(i + (l >> 1)) % n]), i);\n\t\tstable_sort(d.begin(), d.end());\n\t\t\n\t\tc[d[0].y] = 0;\n\t\tfore(i, 1, n)\n\t\t\tc[d[i].y] = c[d[i - 1].y] + (d[i].x != d[i - 1].x);\n\t\tif(c[d.back().y] == n - 1)\n\t\t\tbreak;\n\t}\n\t\n\tfore(i, 0, n)\n\t\tid[c[i]] = i;\n\t\t\n\tint l = 0;\n\tfore(i, 0, n) {\n\t\tif(c[i] == n - 1)\n\t\t\tcontinue;\n\t\tl = max(0, l - 1);\n\t\tint j = id[c[i] + 1];\n\t\t\n\t\twhile(i + l < n && j + l < n && s[i + l] == s[j + l])\n\t\t\tl++;\n\t\tlcp[c[i]] = l;\n\t}\n\t\n\tn--;\n\tlg2[0] = lg2[1] = 0;\n\tfore(i, 2, N) {\n\t\tlg2[i] = lg2[i - 1];\n\t\tif((1 << (lg2[i] + 1)) <= i)\n\t\t\tlg2[i]++;\n\t}\n\t\n\tfore(i, 0, n)\n\t\tmn[0][i] = lcp[i];\n\tfore(pw, 1, LOGN) fore(i, 0, n) {\n\t\tmn[pw][i] = mn[pw - 1][i];\n\t\tif(i + (1 << (pw - 1)) < n)\n\t\t\tmn[pw][i] = min(mn[pw][i], mn[pw - 1][i + (1 << (pw - 1))]);\n\t}\n}\n\nint getMin(int l, int r) {\n\tint ln = lg2[r - l];\n\treturn min(mn[ln][l], mn[ln][r - (1 << ln)]);\n}\n\nint getLCP(int i, int j) {\n\tif(i == j) return n - i;\n\ti = c[i], j = c[j];\n\treturn getMin(min(i, j), max(i, j));\n}\n\nbool cmp(const pt &a, const pt &b) {\n\tif(a.x == b.x)\n\t\treturn a.y < b.y;\n\tint l = getLCP(a.x, b.x);\n\treturn s[a.x + l] < s[b.x + l];\n}\n\nvoid solve() {\n\tbuildSuffArray();\n\t\n\tfore(_, 0, q) {\n\t\tint k, l;\n\t\tassert(scanf(\"%d%d\", &k, &l) == 2);\n\t\tvector<int> a(k), b(l);\n\t\tfore(i, 0, k)\n\t\t\tassert(scanf(\"%d\", &a[i]) == 1), a[i]--;\n\t\tfore(j, 0, l)\n\t\t\tassert(scanf(\"%d\", &b[j]) == 1), b[j]--;\n\t\t\t\n\t\tli ans = 0;\n\t\tvector<pt> c;\n\t\tfor(auto v : a)\n\t\t\tc.emplace_back(v, 1);\n\t\tfor(auto v : b)\n\t\t\tc.emplace_back(v, 0);\n\t\tsort(c.begin(), c.end(), cmp);\n\t\t\n\t\tfore(k, 0, 2) {\n\t\t\tli sum = 0;\n\t\t\tmap<int, int> cnt;\n\t\t\t\n\t\t\tfore(i, 0, sz(c)) {\n\t\t\t\tint id = c[i].x, tp = c[i].y;\n\t\t\t\tif(tp == 0)\n\t\t\t\t\tans += sum;\n\t\t\t\telse {\n\t\t\t\t\tcnt[n - id]++;\n\t\t\t\t\tsum += (n - id);\n\t\t\t\t}\n\t\t\t\tif(i + 1 < sz(c)) {\n\t\t\t\t\tint len = getLCP(c[i].x, c[i + 1].x);\n\t\t\t\t\twhile(!cnt.empty()) {\n\t\t\t\t\t\tauto it = --cnt.end();\n\t\t\t\t\t\tif(it->x <= len)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsum -= it->x * 1ll * it->y;\n\t\t\t\t\t\tcnt[len] += it->y;\n\t\t\t\t\t\tsum += it->y * 1ll * len;\n\t\t\t\t\t\tcnt.erase(it);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treverse(c.begin(), c.end());\n\t\t}\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "string suffix structures"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1075",
    "index": "A",
    "title": "The King's Race",
    "statement": "On a chessboard with a width of $n$ and a height of $n$, rows are numbered from bottom to top from $1$ to $n$, columns are numbered from left to right from $1$ to $n$. Therefore, for each cell of the chessboard, you can assign the coordinates $(r,c)$, where $r$ is the number of the row, and $c$ is the number of the column.\n\nThe white king has been sitting in a cell with $(1,1)$ coordinates for a thousand years, while the black king has been sitting in a cell with $(n,n)$ coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates $(x,y)$...\n\nEach of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:\n\nAs in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, \\textbf{kings can stand in adjacent cells or even in the same cell at the same time}.\n\nThe player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates $(x,y)$ first will win.\n\nLet's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the $(a,b)$ cell, then in one move he can move from $(a,b)$ to the cells $(a + 1,b)$, $(a - 1,b)$, $(a,b + 1)$, $(a,b - 1)$, $(a + 1,b - 1)$, $(a + 1,b + 1)$, $(a - 1,b - 1)$, or $(a - 1,b + 1)$. Going outside of the field is prohibited.\n\nDetermine the color of the king, who will reach the cell with the coordinates $(x,y)$ first, if the white king moves first.",
    "tutorial": "Let's find the minimum time needed for the white king to reach the coin. It is obvious that it is always optimal to move only towards the coin. In case of white king it means that we should move only up, right or up-right diagonally. During one move we can only add $1$ or $0$ to any of our coordinates (or to both of them), it means that the length of the optimal path can not be smaller than $max(x-1,y-1)$. Let's show that we can reach the coin with $max(x-1,y-1)$ moves. First step. Let $z$ be equal to $min(x,y)$. The king does $z-1$ up-right moves, so after that the king will be in the cell $(z,z)$. Second step. Let's assume that $x \\le y$ (the case when $x > y$ is proved in a similar way). So $z = x$. It means that the king is in the cell $(x,x)$. Now the king can do $y-x$ up moves, after which he would be in the cell $(x,y)$. It took him $(x-1)+(y-x)=y-1$ moves to reach the coin. If $x$ was greater than $y$ he would need $x-1$ moves (could be proved the same way). So now we proved that it takes $max(x-1,y-1)$ moves for the white king to reach the coin. In the same way we can prove that it takes $max(n-x,n-y)$ steps for the black king to reach the coin. The king, which is closer to the coin, wins. If the distances is equal, than the white king wins, because he moves first. Final description of the algorithm: If $max(n-x,n-y)<max(x-1,y-1)$ then the answer is \"Black\", otherwise the answer is \"White\". It is also can be proven that instead of comparing minimal distances between the coin and the kings we can compare manhattan distances between them. I will leave the proof as homework task.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1075",
    "index": "B",
    "title": "Taxi drivers and Lyft",
    "statement": "Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.\n\nLyft has become so popular so that it is now used by all $m$ taxi drivers in the city, who every day transport the rest of the city residents — $n$ riders.\n\nEach resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).\n\nThe Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.\n\nBut one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $i$ the number $a_{i}$ — the number of riders that would call the $i$-th taxi driver when all drivers and riders are at their home?\n\nThe taxi driver can neither transport himself nor other taxi drivers.",
    "tutorial": "Let's find for each rider the taxi driver that will get his call. To do this we can find for each rider the nearest taxi driver at right and the nearest taxi driver at left. Let's define the nearest taxi driver at left for $i$-th citizen as $l_i$ and at the right as $r_i$. The computations can be done with the following algorithm: Let's define $l_0=0$ and $r_{n+m+1}=n+m+1$. And $x_0=-2*10^9$, $x_{n+m+1} = 2*10^{9}$. In order to find $l_i$ for each $i$ we should iterate through the citizens from $1$ to $n+m$. If the $i$-th citizen is a taxi driver, then he/she is obviously the nearest taxi driver to himself/herself. If the $i$-th citizen is a rider, then $l_i=l_{i-1}$ In order to find $r_i$ for each $i$ we should iterate through the citizens from $n+m$ to $1$. If the $i$-th citizen is a taxi driver, then $r_i=i$, else $r_i=r_{i+1}$. Now it's time to compute the answer. Let's denote $b_i$ as the number of citizens, whose calls the $i$-th citizen will get (if the $i$-th citizen is a rider, then $b_i=0$). In order to do compute the values of array $b$ we should iterate through the citizens from $1$ to $n+m$. If the $i$-th citizen is a rider, then if the $x_{r_i}-x_i<x_i-x_{l_i}$ (distance between the nearest taxi driver at right and the $i$-th citizen is smaller than distance between the nearest taxi driver at the left and the citizen), then taxi driver $r_i$ will get the call, otherwise the taxi driver $l_i$ will get the call. So if $x_{r_i}-x_i<x_i-x_{l_i}$, then $b_{r_i}:=b_{r_i}+1$, else $b_{l_i}:=b_{l_i}+1$. In order to print out the answer we iterate through the citizens from $1$ to $n+m$. If the $i$-th citizen is a taxi driver, than we should print $b_i$. The algorithm iterates through the array four times, so overall complexity is $O(n+m)$",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1076",
    "index": "A",
    "title": "Minimizing the String",
    "statement": "You are given a string $s$ consisting of $n$ lowercase Latin letters.\n\nYou have to remove \\textbf{at most one} (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.\n\nString $s = s_1 s_2 \\dots s_n$ is lexicographically smaller than string $t = t_1 t_2 \\dots t_m$ if $n < m$ and $s_1 = t_1, s_2 = t_2, \\dots, s_n = t_n$ or there exists a number $p$ such that $p \\le min(n, m)$ and $s_1 = t_1, s_2 = t_2, \\dots, s_{p-1} = t_{p-1}$ and $s_p < t_p$.\n\nFor example, \"aaa\" is smaller than \"aaaa\", \"abb\" is smaller than \"abc\", \"pqr\" is smaller than \"z\".",
    "tutorial": "By the definition of lexicographical comparing we can see that if we can remove one character we always have to do it. Besides, we have to remove the character from the leftmost position $i$ such that $i < n$ and $s_i > s_{i + 1}$ or from the position $n$ if there is no such $i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\tint pos = n - 1;\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tif (s[i] > s[i + 1]) {\n\t\t\tpos = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcout << s.substr(0, pos) + s.substr(pos + 1) << endl;\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1076",
    "index": "B",
    "title": "Divisor Subtraction",
    "statement": "You are given an integer number $n$. The following algorithm is applied to it:\n\n- if $n = 0$, then end algorithm;\n- find the smallest \\textbf{prime} divisor $d$ of $n$;\n- subtract $d$ from $n$ and go to step $1$.\n\nDetermine the number of subtrations the algorithm will make.",
    "tutorial": "Notice that once the number becomes even, it never stops being even as subtracting $2$ doesn't change parity. Thus, the task is to find the smallest divisor, subtract it and print $1 + \\frac{n - d}{2}$. Overall complexity: $O(\\sqrt{n})$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nlong long get(long long n){\n\tfor (long long i = 2; i * i <= n; ++i)\n\t\tif (n % i == 0)\n\t\t\treturn i;\n\treturn n;\n}\n\nint main() {\n\tlong long n;\n\tscanf(\"%lld\", &n);\n\tlong long cnt = 0;\n\tif (n % 2 != 0){\n\t\tn -= get(n);\n\t\t++cnt;\n\t}\n\tprintf(\"%lld\\n\", cnt + n / 2);\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1076",
    "index": "C",
    "title": "Meme Problem",
    "statement": "Try guessing the statement from this picture:\n\nYou are given a non-negative integer $d$. You have to find two non-negative real numbers $a$ and $b$ such that $a + b = d$ and $a \\cdot b = d$.",
    "tutorial": "To solve this problem we need to use some math and solve the equation on the paper. If $a + b = d$ then $a = d - b$ and $a \\cdot b = d$ transforms to $b (d - b) = d$ or $db - b^2 - d = 0$. Then $a, b = (d \\pm \\sqrt{D}) / 2$ where $D = d^2 - 4d$. So if $d = 0$ then $a = b = 0$, or if $0 < d < 4$ there is no answer. Since values are small, calculating answer in double was enough, all we need to do is just output answer with sufficient number of digits after the decimal point.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\ntypedef long long li;\ntypedef double ld;\ntypedef pair<int, int> pt;\n\nli d;\n\ninline bool read() {\n\tif(!(cin >> d))\n\t\treturn false;\n\treturn true;\n}\n\ninline void solve() {\n\tif(d == 0) {\n\t\tcout << \"Y \" << 0.0 << \" \" << 0.0 << endl;\n\t\treturn;\n\t}\n\tif(d < 4) {\n\t\tcout << \"N\" << endl;\n\t\treturn;\n\t}\n\t\n\tld D = sqrt(d * li(d - 4));\n\tld a = (d + D) / 2.0;\n\tld b = (d - D) / 2.0;\n\t\n\tcout << \"Y \" << a << \" \" << b << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(9);\n\t\n\tint tc = 1;\n\tassert(cin >> tc);\n\t\n\twhile(tc--) {\n\t\tassert(read());\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1076",
    "index": "D",
    "title": "Edge Deletion",
    "statement": "You are given an undirected connected weighted graph consisting of $n$ vertices and $m$ edges. Let's denote the length of the shortest path from vertex $1$ to vertex $i$ as $d_i$.\n\nYou have to erase some edges of the graph so that at most $k$ edges remain. Let's call a vertex $i$ \\textbf{good} if there still exists a path from $1$ to $i$ with length $d_i$ after erasing the edges.\n\nYour goal is to erase the edges in such a way that the number of \\textbf{good} vertices is maximized.",
    "tutorial": "Let's understand how many good vertices we may get if only $k$ edges remain. This value is not greater than $k + 1$, since an edge an add only one good vertex, and for $k = 0$ we have a good vertex with index $1$. This is an upper bound; let's try to find a solution getting exactly $k + 1$ good vertices (or, if $k + 1> n$, all vertices of the graph will be good). Let's run Dijkstra's algorithm from vertex $1$ and stop it as soon as we know the shortest paths to $k + 1$ vertices (including vertex $1$). The answer should contain the edges belonging to the shortest path tree built on these $k + 1$ vertices.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<pair<int, pair<int, int> > > g[300043];\n\nint main()\n{\n\tint n, m, k;\n\tscanf(\"%d %d %d\", &n, &m, &k);\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint x, y, w;\n\t\tscanf(\"%d %d %d\", &x, &y, &w);\n\t\t--x;\n\t\t--y;\n\t\tg[x].push_back(make_pair(y, make_pair(w, i)));\n\t\tg[y].push_back(make_pair(x, make_pair(w, i)));\n\t}\n\tset<pair<long long, int> > q;\n\tvector<long long> d(n, (long long)(1e18));\n\td[0] = 0;\n\tq.insert(make_pair(0, 0));\n\tvector<int> last(n, -1);\n\tint cnt = 0;\n\tvector<int> ans;\n\twhile(!q.empty() && cnt < k)\n\t{\n\t\tauto z = *q.begin();\n\t\tq.erase(q.begin());\n\t\tint k = z.second;\n\t\tif(last[k] != -1)\n\t\t{\n\t\t\tcnt++;\n\t\t\tans.push_back(last[k]);\n\t\t}\n\t\tfor(auto y : g[k])\n\t\t{\n\t\t\tint to = y.first;\n\t\t\tint w = y.second.first;\n\t\t\tint idx = y.second.second;\n\t\t\tif(d[to] > d[k] + w)\n\t\t\t{\n\t\t\t\tq.erase(make_pair(d[to], to));\n\t\t\t\td[to] = d[k] + w;\n\t\t\t\tlast[to] = idx;\n\t\t\t\tq.insert(make_pair(d[to], to));\n\t\t\t}\n\t\t}\n\t}\t\t\n\tprintf(\"%d\\n\", ans.size());\n\tfor(auto x : ans) printf(\"%d \", x + 1);\n}\t",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1076",
    "index": "E",
    "title": "Vasya and a Tree",
    "statement": "Vasya has a tree consisting of $n$ vertices with root in vertex $1$. At first all vertices has $0$ written on it.\n\nLet $d(i, j)$ be the distance between vertices $i$ and $j$, i.e. number of edges in the shortest path from $i$ to $j$. Also, let's denote $k$-subtree of vertex $x$ — set of vertices $y$ such that next two conditions are met:\n\n- $x$ is the ancestor of $y$ (each vertex is the ancestor of itself);\n- $d(x, y) \\le k$.\n\nVasya needs you to process $m$ queries. The $i$-th query is a triple $v_i$, $d_i$ and $x_i$. For each query Vasya adds value $x_i$ to each vertex from $d_i$-subtree of $v_i$.\n\nReport to Vasya all values, written on vertices of the tree after processing all queries.",
    "tutorial": "To solve this problem we can use a data structure which allows to add some value on segment and get a value from some point (Fenwick tree, segment tree or anything you are familliar with). Let's run DFS from the root while maintaining current depth. When entering a vertex $u$ on depth $h$, let's consider all queries having $v_i = u$, and for each such query add $x_i$ on segment $[h, h + d_i]$. Then for current vertex $u$ the answer is the value in point $h$. When leaving vertex $u$ we need to rollback everything we have done: for all queries having $v_i = u$ subtract $x_i$ on segment $[h, h + d_i]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 9;\n\nint n, m;\t\nvector <int> g[N];\nvector <pair<int, int> > q[N];\nlong long add[N];\nlong long res[N];\n\nvoid dfs(int v, int pr, int h, long long sum){\n\tfor(auto p : q[v]){\n\t\tint l = h, r = h + p.first;\n\t\tadd[l] += p.second;\n\t\tif(r + 1 < N) add[r + 1] -= p.second;\n\t}\n\tsum += add[h];\n\tres[v] = sum;\t\n\tfor(auto to : g[v])\n\t\tif(to != pr)\n\t\t\tdfs(to, v, h + 1, sum);\n\t\t\t\n\tfor(auto p : q[v]){\n\t\tint l = h, r = h + p.first;\n\t\tadd[l] -= p.second;\n\t\tif(r + 1 < N) add[r + 1] += p.second;\n\t}\n}\n\nint main() {\t\n//\tfreopen(\"input.txt\", \"r\", stdin);\n\t\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n - 1; ++i){\n\t\tint u, v;\n\t\tscanf(\"%d %d\", &u, &v);\n\t\t--u, --v;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\t\n\tscanf(\"%d\", &m);\n\tfor(int i = 0; i < m; ++i){\n\t\tint v, h, d;\n\t\tscanf(\"%d %d %d\", &v, &h, &d);\n\t\t--v;\n\t\tq[v].push_back(make_pair(h, d));\n\t}\n\t\n\tdfs(0, 0, 0, 0);\n\tfor(int i = 0; i < n; ++i)\n\t\tprintf(\"%lld \", res[i]);\n\tputs(\"\");\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1076",
    "index": "F",
    "title": "Summer Practice Report",
    "statement": "Vova has taken his summer practice this year and now he should write a report on how it went.\n\nVova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exactly $n$ pages and the $i$-th page will include $x_i$ tables and $y_i$ formulas. The pages are numbered from $1$ to $n$.\n\nVova fills the pages one after another, he can't go filling page $i + 1$ before finishing page $i$ and he can't skip pages.\n\nHowever, if he draws \\textbf{strictly more} than $k$ tables in a row or writes \\textbf{strictly more} than $k$ formulas in a row then he will get bored. Vova wants to rearrange tables and formulas in each page in such a way that he doesn't get bored in the process. Vova can't move some table or some formula to another page.\n\nNote that the count doesn't reset on the start of the new page. For example, if the page ends with $3$ tables and the next page starts with $5$ tables, then it's counted as $8$ tables in a row.\n\nHelp Vova to determine if he can rearrange tables and formulas on each page in such a way that there is no more than $k$ tables in a row and no more than $k$ formulas in a row.",
    "tutorial": "Let's intruduce the following dynamic programming approach. $dp[N][2]$, $dp[i][j]$ is the smallest number of elements of type $j$ page $i$ can end with. If we learn to recalculate it, the answer will be \"YES\" if $dp[n][0] \\le k$ or $dp[n][1] \\le k$. I will try to prove it on the fly. Let's look into the constructing of each page from the following perspective. I'll consider the cases when the current page ends with tables and the previous page ends with either tables or formulas. Let's write down all the tables and then put formulas as separators to them. I will call number of tables on the end of the previous page $pa$, the number of formulas on the end of the previous page $pb$, the number on tables on the current page $a$ and the number of formulas on the current page $b$. In the case with tables on the end of the previous page the smallest number of separators you can have is $cnt = \\lceil \\frac{pa + a}{k} \\rceil - 1$. Moreover, if you have $b > cnt$, you can put one of the formulas right before the end of the page, ending it with $1$ table. The only case is when there are too many separators. $b$ should be less or equal to $a \\cdot k$ (you can put up to $k$ separators before each table). The case with formulas on the end of the previous page isn't that different. The smallest number of separators is $cnt = \\lceil \\frac{a}{k} \\rceil - 1$ and the limit to the number of separators is $(a - 1) \\cdot k + (k - pb)$ (you can't put $k$ separators before the first table as in the first case, the maximum number to that position is determined by the previous page). Now let's take a look at resulting expressions. You can notice that lowering $pa$ can only decrease the lower bound on the number of separators and lowering $pb$ can only increase the upper bound on the number of separators. That shows that minimizing the values in $dp[i][j]$ is always profitable. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\ntypedef long long li;\n\nconst int N = 300 * 1000 + 13;\nconst int INF = 1e9;\n\nint dp[N][2];\n\nint n, k;\nint a[N], b[N];\n\nint get(int pa, int pb, int a, int b){\n\tint ans = INF;\n\t\n\tif (pa <= k){\n\t\tint tot = pa + a;\n\t\tint cnt = (tot + k - 1) / k - 1;\n\t\tif (b == cnt)\n\t\t\tans = min(ans, tot - cnt * k);\n\t\telse if (b > cnt && b <= a * li(k))\n\t\t\tans = min(ans, 1);\n\t}\n\t\n\tif (pb <= k){\n\t\tint cnt = (a + k - 1) / k - 1;\n\t\tif (b == cnt)\n\t\t\tans = min(ans, a - cnt * k);\n\t\telse if (b > cnt && b <= (a - 1) * li(k) + (k - pb))\n\t\t\tans = min(ans, 1);\n\t}\n\t\n\treturn ans;\n}\n\nint main() {\n\tscanf(\"%d%d\", &n, &k);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tforn(i, n) scanf(\"%d\", &b[i]);\n\t\n\tforn(i, N) forn(j, 2) dp[i][j] = INF;\n\tdp[0][0] = 0;\n\tdp[0][1] = 0;\n\tforn(i, n){\n\t\tdp[i + 1][0] = get(dp[i][0], dp[i][1], a[i], b[i]);\n\t\tdp[i + 1][1] = get(dp[i][1], dp[i][0], b[i], a[i]);\n\t}\n\t\n\tputs(dp[n][0] <= k || dp[n][1] <= k ? \"YES\" : \"NO\");\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1076",
    "index": "G",
    "title": "Array Game",
    "statement": "Consider a following game between two players:\n\nThere is an array $b_1$, $b_2$, ..., $b_k$, consisting of positive integers. Initially a chip is placed into the first cell of the array, and $b_1$ is decreased by $1$. Players move in turns. Each turn the current player has to do the following: if the index of the cell where the chip is currently placed is $x$, then he or she has to choose an index $y \\in [x, min(k, x + m)]$ such that $b_y > 0$, move the chip to the cell $y$ and decrease $b_y$ by $1$. If it's impossible to make a valid move, the current player loses the game.\n\nYour task is the following: you are given an array $a$ consisting of $n$ positive integers, and $q$ queries to it. There are two types of queries:\n\n- $1$ $l$ $r$ $d$ — for every $i \\in [l, r]$ increase $a_i$ by $d$;\n- $2$ $l$ $r$ — tell who is the winner of the game that is played on the subarray of $a$ from index $l$ to index $r$ inclusive. Assume both players choose an optimal strategy.",
    "tutorial": "Suppose there is only one query, i. e. we are given some array and we want to know who is the winner if the game is played on this array. One of the obvious solutions is $dp[i][x]$ - will the current player win if the chip is currently in the cell $i$ and the number in cell $i$ is $x$. We can already see that we don't need to know the exact value of $x$, we only want to know whether it's odd: if there is a cell $j \\ne i$ such that we can go from $i$ to $j$ and $dp[j][a_j - 1]$ is a state where current player will lose, then we should go to this cell since our opponent will enter a losing state of the game. Otherwise, we want to force our opponent to move out of cell $i$, and we can do so only if $x$ is odd. So we found a dynamic programming solution with $O(n)$ states, but what is more important is that we can take all the elements in our array modulo $2$. Okay, now let's solve the problem when there are only queries of type $2$ (no modifications). Since when calculating the $dp$ values we are interested only in $m$ next cells, and there are only $2^m$ variants of whether these cells are \"winning\" or \"losing\", we may consider each element of the array as a function that maps a mask of $m$ next states into a new mask of $m$ states if we pushed our new element into the front. For example, if the $i$-th element is even and states $i + 1$, $i + 2$, $i + 3$, $i + 4$, $i + 5$ are winning, losing, losing, winning and losing respectively, and $m = 5$, then we may consider a mask of next states as $10010$; and then we can check if $i$-th state is winning and push a bit to the front of this mask, discarding the last bit; since new state is winning, we will get a mask of $11001$. It allows us to denote two functions $f_0(x)$ and $f_1(x)$ - what will be the resulting mask of next $m$ states, if current mask is $x$ and we push an even or odd element to the front. Okay, what about pushing more than one element? We can just take the composition of their functions! Since a function can be stored as an array of $2^m$ integers and the composition needs only $O(2^m)$ time to be calculated, then we can build a segment tree over the elements of the array, and store a composition of all functions on the segment in each node. This allows us to answer queries of type $2$ in $O(2^m \\log n)$. The only thing that's left is additions on segment. Adding an even number is easy: just ignore this query. To be able an odd number, let's store another function in each node of the segment tree which would be the composition of all functions on the segment if we would add $1$ to all elements on the segment (so the elements which were odd become even, and vice versa). This allows us to use lazy propagation: if the query affects the whole node, we may just swap two functions in it and push the query to the children of this node. Overall complexity is $O(2^m (n + q) \\log n)$. It turns out (we didn't think about it before the contest, but some contestants submitted such solutions) that it can be reduced to $O(m (n + q) \\log n)$ if we will use the distance to closest losing state instead of a mask of winning and losing states.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\n\ntypedef long long li;\n\nint n, m;\nli a[N];\nint q;\nint f[N * 4];\nvector<int> T[4 * N];\nvector<int> T2[4 * N];\nint mask;\nint cur;\n\nvector<int> combine(const vector<int>& a, const vector<int>& b)\n{\n\tvector<int> c(1 << m);\n\tfor(int i = 0; i < (1 << m); i++)\n\t\tc[i] = b[a[i]];\n\treturn c;\n}\n\nvector<int> init(li x)\n{\n\tvector<int> ans(1 << m);\n\tfor(int i = 0; i < (1 << m); i++)\n\t{\n\t\tif(i != mask || (x & 1) == 0)\n\t\t\tans[i] = ((i << 1) & mask) ^ 1;\n\t\telse\n\t\t\tans[i] = ((i << 1) & mask);\n\t}\t\n\treturn ans;\n}\n\nvoid upd(int v)\n{\n\tT[v] = combine(T[v * 2 + 2], T[v * 2 + 1]);\n\tT2[v] = combine(T2[v * 2 + 2], T2[v * 2 + 1]);\n}\n\nvoid build(int v, int l, int r)\n{\n\tif(l == r - 1)\n\t{\n\t\tT[v] = init(a[l]);\n\t\tT2[v] = init(a[l] ^ 1);\n\t\treturn;\n\t}\n\tint m = (l + r) >> 1;\n\tbuild(v * 2 + 1, l, m);\n\tbuild(v * 2 + 2, m, r);\n\tupd(v);\n}\n\nvoid push(int v, int l, int r)\n{\n\tif(f[v])\n\t{\n\t\tswap(T[v], T2[v]);\n\t\tif(l != r - 1)\n\t\t{\n\t\t\tf[v * 2 + 1] ^= 1;\n\t\t\tf[v * 2 + 2] ^= 1;\n\t\t}\n\t\tf[v] = 0;\n\t}\n}\n\nvector<int> id;\n\nvoid get(int v, int l, int r, int L, int R)\n{\n\tpush(v, l, r);\n\tif(L >= R)\n\t\treturn;\n\tif(l == L && r == R)\n\t{\n\t\tcur = T[v][cur];\n\t}\n\telse\n\t{\n\t\tint m = (l + r) >> 1;\n\t\tget(v * 2 + 2, m, r, max(L, m), R);\n\t\tget(v * 2 + 1, l, m, L, min(R, m));\n\t\tupd(v);\t\n\t}\n}\n\nvoid add(int v, int l, int r, int L, int R)\n{\n\tpush(v, l, r);\n\tif(L >= R)\n\t\treturn;\n\tif(l == L && r == R)\n\t{\n\t\tf[v] ^= 1;\n\t\tpush(v, l, r);\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tint m = (l + r) >> 1;\n\t\tadd(v * 2 + 1, l, m, L, min(R, m));\n\t\tadd(v * 2 + 2, m, r, max(L, m), R);\n\t\tupd(v);\n\t}\n}\n\nint main() \n{ \n\tscanf(\"%d %d %d\", &n, &m, &q);\n\tmask = (1 << m) - 1;\n\tfor(int i = 0; i < (1 << m); i++)\n\t\tid.push_back(i);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%lld\", &a[i]);\n\tbuild(0, 0, n);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tint t, l, r;\n\t\tscanf(\"%d %d %d\", &t, &l, &r);\n\t\t--l;\n\t\tif(t == 1)\n\t\t{\n\t\t\tli d;\n\t\t\tscanf(\"%lld\", &d);\n\t\t\tif(d & 1)\n\t\t\t\tadd(0, 0, n, l, r);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcur = mask;\n\t\t\tget(0, 0, n, l, r);\n\t\t\t\n\t\t\tif((cur & 1) == 1)\n\t\t\t\tputs(\"1\");\n\t\t\telse\n\t\t\t\tputs(\"2\");\n\t\t}\n\t}\n}",
    "tags": [
      "data structures",
      "games"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1077",
    "index": "A",
    "title": "Frog Jumping",
    "statement": "A frog is currently at the point $0$ on a coordinate axis $Ox$. It jumps by the following algorithm: the first jump is $a$ units to the right, the second jump is $b$ units to the left, the third jump is $a$ units to the right, the fourth jump is $b$ units to the left, and so on.\n\nFormally:\n\n- if the frog has jumped an even number of times (before the current jump), it jumps from its current position $x$ to position $x+a$;\n- otherwise it jumps from its current position $x$ to position $x-b$.\n\nYour task is to calculate the position of the frog after $k$ jumps.\n\nBut... One more thing. You are watching $t$ different frogs so you have to answer $t$ independent queries.",
    "tutorial": "With each pair of jumps of kind \"to the right - to the left\" the frog jumps $a - b$. So the answer is almost $(a - b) \\cdot \\lfloor\\frac{k}{2}\\rfloor$. Almost because there can be one more jump to the right. So if $k$ is odd then we have to add $a$ to the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\tfor (int i = 0; i < t; ++i) {\n\t\tint a, b, k;\n\t\tcin >> a >> b >> k;\n\t\tcout << (a - b) * 1ll * (k / 2) + a * (k & 1) << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1077",
    "index": "B",
    "title": "Disturbed People",
    "statement": "There is a house with $n$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $n$ integer numbers $a_1, a_2, \\dots, a_n$, where $a_i = 1$ if in the $i$-th flat the light is on and $a_i = 0$ otherwise.\n\nVova thinks that people in the $i$-th flats are disturbed and cannot sleep if and only if $1 < i < n$ and $a_{i - 1} = a_{i + 1} = 1$ and $a_i = 0$.\n\nVova is concerned by the following question: what is the minimum number $k$ such that if people from exactly $k$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $k$.",
    "tutorial": "The first observation is that we are interested only in patterns of kind \"101\". All other patterns don't make sense at all. So, let's build a greedy approach. Let's iterate over the given array from the left to the right and maintain that the prefix of the given answer is already correct. If now we are at some position $i$, $a_{i - 1} = a_{i + 1} = 1$ and $a_i = 0$ (and the prefix from $1$ to $i-2$ is already correct) then which one $1$ we have to replace? When we replace the left one then we cannot do better in the future, but when we replace the right one then we can fix some on the suffix of the array. The easiest example is \"1101011\". If now we are at the position $3$ then we will do better if we will set $a_4 := 0$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tint ans = 0;\n\tfor (int i = 1; i < n - 1; ++i) {\n\t\tif (a[i] == 0 && a[i - 1] == 1 && a[i + 1] == 1) {\n\t\t\t++ans;\n\t\t\ta[i + 1] = 0;\n\t\t}\n\t}\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1077",
    "index": "C",
    "title": "Good Array",
    "statement": "Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $a=[1, 3, 3, 7]$ is good because there is the element $a_4=7$ which equals to the sum $1 + 3 + 3$.\n\nYou are given an array $a$ consisting of $n$ integers. Your task is to print all indices $j$ of this array such that after removing the $j$-th element from the array it will be good (let's call such indices nice).\n\nFor example, if $a=[8, 3, 5, 2]$, the nice indices are $1$ and $4$:\n\n- if you remove $a_1$, the array will look like $[3, 5, 2]$ and it is good;\n- if you remove $a_4$, the array will look like $[8, 3, 5]$ and it is good.\n\nYou have to consider all removals \\textbf{independently}, i. e. remove the element, check if the resulting array is good, and return the element into the array.",
    "tutorial": "The first part: calculate the sum of the whole array: $sum = \\sum\\limits_{i = 1}^n a_i$ (be careful, it can be $2 \\cdot 10^{11}$!). The second part: let's maintain an array $cnt$ of size $10^6 + 1$ where $cnt_i$ will be equal to the number of elements in the given array equals to $i$. The third part: iterate over the array, let the current position be $i$. Set $sum := sum - a_i$, make $cnt_{a_i} := cnt_{a_i} - 1$. If $sum$ is even, $\\frac{sum}{2} \\le 10^6$ and $cnt_{\\frac{sum}{2}} > 0$ then the index $i$ is nice otherwise it doesn't. And after all make $cnt_{a_i} := cnt_{a_i} + 1$ and set $sum := sum + a_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 1e6;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tvector<int> cnt(MAX + 1);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\t++cnt[a[i]];\n\t}\n\tlong long sum = accumulate(a.begin(), a.end(), 0ll);\n\t\n\tvector<int> ans;\n\tfor (int i = 0; i < n; ++i) {\n\t\tsum -= a[i];\n\t\t--cnt[a[i]];\n\t\tif (sum % 2 == 0 && sum / 2 <= MAX && cnt[sum / 2] > 0) {\n\t\t\tans.push_back(i);\n\t\t}\n\t\tsum += a[i];\n\t\t++cnt[a[i]];\n\t}\n\t\n\tcout << ans.size() << endl;\n\tfor (auto it : ans) cout << it + 1 << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [],
    "rating": 1300
  },
  {
    "contest_id": "1077",
    "index": "D",
    "title": "Cutting Out",
    "statement": "You are given an array $s$ consisting of $n$ integers.\n\nYou have to find \\textbf{any} array $t$ of length $k$ such that you can cut out maximum number of copies of array $t$ from array $s$.\n\nCutting out the copy of $t$ means that for each element $t_i$ of array $t$ you have to find $t_i$ in $s$ and remove it from $s$. If for some $t_i$ you cannot find such element in $s$, then you cannot cut out one more copy of $t$. The both arrays can contain duplicate elements.\n\nFor example, if $s = [1, 2, 3, 2, 4, 3, 1]$ and $k = 3$ then one of the possible answers is $t = [1, 2, 3]$. This array $t$ can be cut out $2$ times.\n\n- To cut out the first copy of $t$ you can use the elements $[1, \\underline{\\textbf{2}}, 3, 2, 4, \\underline{\\textbf{3}}, \\underline{\\textbf{1}}]$ (use the highlighted elements). After cutting out the first copy of $t$ the array $s$ can look like $[1, 3, 2, 4]$.\n- To cut out the second copy of $t$ you can use the elements $[\\underline{\\textbf{1}}, \\underline{\\textbf{3}}, \\underline{\\textbf{2}}, 4]$. After cutting out the second copy of $t$ the array $s$ will be $[4]$.\n\nYour task is to find such array $t$ that you can cut out the copy of $t$ from $s$ maximum number of times. If there are multiple answers, you may choose \\textbf{any} of them.",
    "tutorial": "Let's solve the problem using binary search by the answer. It is easy to see that if we can construct the answer for some number of copies $val$ then we also can do it for $val - 1$. The only thing we need is to write the function $can(val)$ which will say can we cut off $val$ copies of some array $t$ from $s$ or not. Let's imagine $val$ copies of string $t$ as a matrix of size $val \\times k$. Obviously, each row of this matrix should be equal to each other row. Let's fill not rows but columns of this matrix. For some element $i$ of $s$ we can easy notice that we can take exactly $\\lfloor\\frac{cnt_i}{val}\\rfloor$ columns containing this element where $cnt_i$ is the number of such elements in $s$. So, overall number of columns we can fill in this matrix will be $\\sum\\limits_{i = 1}^{2 \\cdot 10^5} \\lfloor\\frac{cnt_i}{val}\\rfloor$. If this value is greater than or equal to $k$ then $can(val)$ is true otherwise it is false. It is easy to construct the answer using all things we described above. Overall complexity is $O(n + |A|\\log n)$ where $|A|$ is the size of the alphabet.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200 * 1000 + 1;\n\nint n, k;\nvector<int> s, t;\nvector<int> cnts(MAX);\n\nbool can(int cnt) {\n\tt.clear();\n\tfor (int i = 0; i < MAX; ++i) {\n\t\tint need = min(cnts[i] / cnt, k - int(t.size()));\n\t\tfor (int j = 0; j < need; ++j) {\n\t\t\tt.push_back(i);\n\t\t}\n\t}\n\treturn int(t.size()) == k;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> k;\n\ts = vector<int>(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> s[i];\n\t}\n\tfor (auto c : s) {\n\t\t++cnts[c];\n\t}\n\t\n\tint l = 0, r = n;\n\twhile (r - l > 1) {\n\t\tint mid = (l + r) >> 1;\n\t\tif (can(mid)) {\n\t\t\tl = mid;\n\t\t} else {\n\t\t\tr = mid;\n\t\t}\n\t}\n\tif (!can(r)) can(l);\n\tfor (auto it : t) cout << it << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1077",
    "index": "E",
    "title": "Thematic Contests",
    "statement": "Polycarp has prepared $n$ competitive programming problems. The topic of the $i$-th problem is $a_i$, and some problems' topics may coincide.\n\nPolycarp has to host several thematic contests. All problems in each contest should have the same topic, and \\textbf{all contests should have pairwise distinct topics}. He may not use all the problems. It is possible that there are no contests for some topics.\n\nPolycarp wants to host competitions on consecutive days, one contest per day. Polycarp wants to host a set of contests in such a way that:\n\n- number of problems in each contest is \\textbf{exactly twice} as much as in the previous contest (one day ago), the first contest can contain arbitrary number of problems;\n- the total number of problems in all the contests should be maximized.\n\nYour task is to calculate the maximum number of problems in the set of thematic contests. Note, that you should not maximize the number of contests.",
    "tutorial": "The first thing: we don't need the problems, we need their counts. So let's calculate for each topic the number of problems with this topic and sort them in non-decreasing order. The counting can be done with std::map or another one sorting. The second thing: the answer is not exceed $n$ (very obviously). So let's iterate over the number of problems in maximum by the number of problems thematic contest. Now we have to calculate the maximum number of problems we can take in the set of thematic contests. Let's do it greedily. The number of contests in the set don't exceed $\\log n$. Let the number of problems in the current contest be $cur$ (at the beginning of iteration the current contest is the maximum by the number of problems). Let's take the topic with the maximum number of problems for this contest. If we cannot do it, stop the iteration. Otherwise we can (maybe) continue the iteration. If $cur$ is even then divide it by $2$ and continue with the rest of topics, otherwise stop the iteration. Which topic we have to choose for the second one contest? The answer is: the topic with the maximum number of problems (which isn't chosen already). So let's carry the pointer $pos$ (initially it is at the end of the array of counts) and decrease it when we add another one contest to our set. All calculations inside the iteration are very obviously. Let's notice that one iteration spends at most $\\log n$ operations. So overall complexity of the solution is $O(n \\log n)$. The last question is: why can we take the maximum by the number of problems topic each time? Suppose we have two contests with numbers of problems $x$ and $y$, correspondingly. Let's consider the case when $x < y$. Let the number of problems of the first contest topic be $cnt_x$ and the number of problems of the second contest topic be $cnt_y$. The case $cnt_x \\le cnt_y$ don't break our assumptions. The only case which can break our assumptions is $cnt_x > cnt_y$. So if it is then we can swap these topics (because $x < y$ and $cnt_x > cnt_y$) and all will be okay. So this greedy approach works.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tmap<int, int> cnt;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\t++cnt[x];\n\t}\n\t\n\tvector<int> cnts;\n\tfor (auto it : cnt) {\n\t\tcnts.push_back(it.second);\n\t}\n\tsort(cnts.begin(), cnts.end());\n\t\n\tint ans = 0;\n\tfor (int i = 1; i <= cnts.back(); ++i) {\n\t\tint pos = int(cnts.size()) - 1;\n\t\tint cur = i;\n\t\tint res = cur;\n\t\twhile (cur % 2 == 0 && pos > 0) {\n\t\t\tcur /= 2;\n\t\t\t--pos;\n\t\t\tif (cnts[pos] < cur) break;\n\t\t\tres += cur;\n\t\t}\n\t\tans = max(ans, res);\n\t}\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1077",
    "index": "F1",
    "title": "Pictures with Kittens (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the constraints.}\n\nVova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $i$-th picture has beauty $a_i$.\n\nVova wants to repost exactly $x$ pictures in such a way that:\n\n- each segment of the news feed of at least $k$ consecutive pictures has at least one picture reposted by Vova;\n- the sum of beauty values of reposted pictures is maximum possible.\n\nFor example, if $k=1$ then Vova has to repost all the pictures in the news feed. If $k=2$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.\n\nYour task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.",
    "tutorial": "Let's solve the problem using dynamic programming. Let $dp_{i, j}$ be the maximum total beauty of pictures if Vova is at the $i$-th picture now, the number of remaining reposts is $j$ and Vova reposted the $i$-th picture. Initially, $dp_{0, x} = 0$ and all other values of $dp$ are $-\\infty$. Let's learn to do some transitions to calculate this dynamic programming. What is the way to do it? Let's iterate over the position of the previously reposted picture and try to update $dp_{i, j}$ using previously calculated values. Obviously, this position can be from $i-1$ to $i-k$. So let's iterate over the position (let it be $p$) and if $dp_{p, j + 1}$ (we need one more repost to repost the $i$-th picture) is not $-\\infty$ then try to update $dp_{i, j} = max(dp_{i, j}, dp_{p, j + 1} + a_i$) (pictures are $1$-indexed). So, where can we find the answer? The answer is $\\max\\limits_{i = n - k + 1}^{n} dp_{i}$. If this value is $-\\infty$ then the answer is -1. Overall complexity is $O(nkx)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long INF64 = 1e18;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k, x;\n\tcin >> n >> k >> x;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tvector<vector<long long>> dp(n + 1, vector<long long>(x + 1, -INF64));\n\t\n\tdp[0][x] = 0;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tfor (int j = 0; j < x; ++j) {\n\t\t\tfor (int p = 1; p <= k; ++p) {\n\t\t\t\tif (i - p < 0) break;\n\t\t\t\tif (dp[i - p][j + 1] == -INF64) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdp[i][j] = max(dp[i][j], dp[i - p][j + 1] + a[i - 1]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tlong long ans = -INF64;\n\tfor (int i = n - k + 1; i <= n; ++i) {\n\t\tans = max(ans, *max_element(dp[i].begin(), dp[i].end()));\n\t}\n\tif (ans == -INF64) ans = -1;\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1077",
    "index": "F2",
    "title": "Pictures with Kittens (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the constraints.}\n\nVova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $i$-th picture has beauty $a_i$.\n\nVova wants to repost exactly $x$ pictures in such a way that:\n\n- each segment of the news feed of at least $k$ consecutive pictures has at least one picture reposted by Vova;\n- the sum of beauty values of reposted pictures is maximum possible.\n\nFor example, if $k=1$ then Vova has to repost all the pictures in the news feed. If $k=2$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.\n\nYour task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.",
    "tutorial": "Let's use dynamic programming described in the previous tutorial to solve this problem too. But its complexity is $O(nkx)$ so we have to improve some part of the solution. Let's see how we do transitions in this dp: for $p \\in [i-k; i-1]$ $dp_{i, j} = max(dp_{i, j}, dp_{p, j + 1} + a_i)$. What can we do to optimize it? $a_i$ is the constant and we have to take the maximum value among $dp_{i - k, j + 1}, dp_{i - k + 1, j + 1}, \\dots, dp_{i - 1, j + 1}$. You will say \"segment tree\"! I say no. Not a segment tree. Not a sparse table. Not a cartesian tree or some other logarithmic data structures. If you want to spend a lot of time to fit such solution in time and memory limits - okay, it is your choice. I prefer the queue with supporting the maximum on it. The last part of this tutorial will be a small guide about how to write and use the queue with supporting the maximum on it. The first part of understanding this data structure is the stack with the maximum. How do we support the stack with the maximum on it? That's pretty easy: let's maintain the stack of pairs, when the first value of pair is the value in the stack and the second one is the maximum on the stack if this element will be the topmost. Then when we push some value $val$ in it, the first element of pair will be $val$ and the second one will be $max(val, s.top().second)$ (if $s$ is our stack and $top()$ is the topmost element). When we pop the element we don't need any special hacks to do it. Just pop it. And the maximum on the stack is always $s.top().second$. Okay, the second part of understanding this data structure is the queue on two stacks. Let's maintain two stacks $s1$ and $s2$ and try to implement the queue using it. We will push elements only to $s2$ and pop elements only from $s1$. Then how to maintain the queue using such stacks? The push is pretty easy - just push it in $s2$. The main problem is pop. If $s1$ is not empty then we have to pop it from $s1$. But what do we do if $s1$ is empty? No problems: let's just transfer elements of $s2$ to $s1$ (pop from $s2$, push to $s1$) in order from top to bottom. And don't forget to pop the element after this transfer! Okay, if we will join these two data structures, we can see that we obtain exactly what we want! Just two stacks with maximums! That's pretty easy to understand and implement it. The last part of the initial solution is pretty easy - just apply this data structure (in fact, $x+1$ data structures) to do transitions in our dynamic programming. The implementation of this structure can be found in the authors solution. Total complexity of the solution is $O(nx)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n\ntypedef long long li;\ntypedef pair<li, li> pll;\n\nconst li INF64 = 1e18;\n\nstruct myQueue {\n\tstack<pll> s1, s2;\n\t\n\tint size() {\n\t\treturn s1.size() + s2.size();\n\t}\n\t\n\tbool isEmpty() {\n\t\treturn size() == 0;\n\t}\n\t\n\tlong long getMax() {\n\t\tif (isEmpty()) {\n\t\t\treturn -INF64;\n\t\t}\n\t\tif (!s1.empty() && !s2.empty()) {\n\t\t\treturn max(s1.top().y, s2.top().y);\n\t\t}\n\t\tif (!s1.empty()) {\n\t\t\treturn s1.top().y;\n\t\t}\n\t\treturn s2.top().y;\n\t}\n\t\n\tvoid push(long long val) {\n\t\tif (s2.empty()) {\n\t\t\ts2.push(mp(val, val));\n\t\t} else {\n\t\t\ts2.push(mp(val, max(val, s2.top().y)));\n\t\t}\n\t}\n\t\n\tvoid pop() {\n\t\tif (s1.empty()) {\n\t\t\twhile (!s2.empty()) {\n\t\t\t\tif (s1.empty()) {\n\t\t\t\t\ts1.push(mp(s2.top().x, s2.top().x));\n\t\t\t\t} else {\n\t\t\t\t\ts1.push(mp(s2.top().x, max(s2.top().x, s1.top().y)));\t\n\t\t\t\t}\n\t\t\t\ts2.pop();\n\t\t\t}\n\t\t}\n\t\tassert(!s1.empty());\n\t\ts1.pop();\n\t}\n};\n\nint n, k, x;\nvector<int> a;\n\nvector<myQueue> q;\nvector<queue<int>> pos;\nvector<vector<long long>> dp;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> k >> x;\n\ta = vector<int>(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tq = vector<myQueue>(x + 1);\n\tpos = vector<queue<int>>(x + 1);\n\tdp = vector<vector<long long>>(n + 1, vector<long long>(x + 1, -INF64));\n\t\n\tdp[0][x] = 0;\n\tpos[x].push(-1);\n\tq[x].push(0ll);\n\t\n\tfor (int i = 1; i <= n; ++i) {\n\t\tfor (int j = 0; j <= x; ++j) {\n\t\t\twhile (!pos[j].empty() && pos[j].front() < i - k - 1) {\n\t\t\t\tq[j].pop();\n\t\t\t\tpos[j].pop();\n\t\t\t}\n\t\t}\n\t\tfor (int j = 0; j < x; ++j) {\n\t\t\tif (!q[j + 1].isEmpty()) {\n\t\t\t\tdp[i][j] = max(dp[i][j], q[j + 1].getMax() + a[i - 1]);\n\t\t\t\tq[j].push(dp[i][j]);\n\t\t\t\tpos[j].push(i - 1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tlong long ans = -INF64;\n\tfor (int i = n - k + 1; i <= n; ++i) {\n\t\tans = max(ans, *max_element(dp[i].begin(), dp[i].end()));\n\t}\n\tif (ans == -INF64) ans = -1;\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1078",
    "index": "E",
    "title": "Negative Time Summation",
    "statement": "Everyone knows that computers become faster and faster. Recently Berland scientists have built a machine that can move itself back in time!\n\nMore specifically, it works as follows. It has an infinite grid and a robot which stands on one of the cells. Each cell of the grid can either be empty or contain 0 or 1. The machine also has a program which consists of instructions, which are being handled one by one. Each instruction is represented by exactly one symbol (letter or digit) and takes exactly one unit of time (say, second) to be performed, except the last type of operation (it's described below). Here they are:\n\n- 0 or 1: the robot places this number into the cell he is currently at. If this cell wasn't empty before the operation, its previous number is replaced anyway.\n- e: the robot \\textbf{e}rases the number into the cell he is at.\n- l, r, u or d: the robot goes one cell to the \\textbf{l}eft/\\textbf{r}ight/\\textbf{u}p/\\textbf{d}own.\n- s: the robot \\textbf{s}tays where he is for a unit of time.\n- t: let $x$ be $0$, if the cell with the robot is empty, otherwise let $x$ be one more than the digit in this cell (that is, $x = 1$ if the digit in this cell is $0$, and $x = 2$ if the digit is $1$). Then the machine \\textbf{t}ravels $x$ seconds back in time. Note that this doesn't change the instructions order, but it changes the position of the robot and the numbers in the grid as they were $x$ units of time ago. You can consider this instruction to be equivalent to a Ctrl-Z pressed $x$ times.\n\nFor example, let the board be completely empty, and the program be sr1t0. Let the robot initially be at $(0, 0)$.\n\n- [now is the moment $0$, the command is s]: we do nothing.\n- [now is the moment $1$, the command is r]: we are now at $(1, 0)$.\n- [now is the moment $2$, the command is 1]: we are at $(1, 0)$, and this cell contains $1$.\n- [now is the moment $3$, the command is t]: we travel $1 + 1 = 2$ moments back, that is, to the moment $1$.\n- [now is the moment $1$, the command is 0]: we are again at $(0, 0)$, and the board is clear again, but after we follow this instruction, this cell has $0$ in it. We've just rewritten the history. The consequences of the third instruction have never happened.\n\nNow Berland scientists want to use their machine in practice. For example, they want to be able to add two integers.\n\nAssume that the initial state of the machine is as follows:\n\n- One positive integer is written in binary on the grid in such a way that its right bit is at the cell $(0, 1)$, from left to right from the highest bit to the lowest bit.\n- The other positive integer is written in binary on the grid in such a way that its right bit is at the cell $(0, 0)$, from left to right from the highest bit to the lowest bit.\n- All the other cells are empty.\n- The robot is at $(0, 0)$.\n- We consider this state to be always in the past; that is, if you manage to travel to any negative moment, the board was always as described above, and the robot was at $(0, 0)$ for eternity.\n\nYou are asked to write a program after which\n\n- The robot stands on a non-empty cell,\n- If we read the number starting from the cell with the robot and moving to the right until the first empty cell, this will be $a + b$ in binary, from the highest bit to the lowest bit.\n\nNote that there are no restrictions on other cells. In particular, there may be a digit just to the left to the robot after all instructions.\n\nIn each test you are given up to $1000$ pairs $(a, b)$, and your program must work for all these pairs. Also since the machine's memory is not very big, your program must consist of no more than $10^5$ instructions.",
    "tutorial": "Disclaimer: there seem to be solutions much simpler than the author's. You can read some passed codes. Let's define our workplace as follows: we will take 6 rows, containing (in order from up to down): carry bits, bits of $a$, bits of $b$, two lines of some buffer garbage and the line with the answer. Consequently, these strings have $y$-coordinates from $2$ to $-3$. Now our plan is to do the following: add leading zeroes to the left of $a$ and $b$, go back to the right end of numbers, a little more than $30$ times (say, $32$) do the following: add a zero carry bit, if necessary, calculate $xor(carry, a_i, b_i)$, which is the $i$-th digit of the result, calculate $maj(carry, a_i, b_i)$, which is the new carry ($maj$ is the majority function which returns $1$ iff at least $2$ of $3$ arguments are $1$), move one cell to the left to the next digits. To do this we can implement some helper functions. Let inv(dir) be the direction opposite to dir (for example, inv(l) = r): move_if_1(dir) = <dir><inv(dir)>st This means that after running the subprogram, say, lrst, robot goes one cell to the left iff it was standing on $1$, otherwise it doesn't do anything. Let's write some other subprograms: move_if_0(dir) = <dir><inv(dir)>t move_if_not_empty(dir) = <dir>s<inv(dir)>t copy(dir) = <dir>10<inv(dir)>t The last subprogram copies a symbol one cell to the given direction. It's important that it's the first function which works properly only when the robot is standing on a non-empty cell. Explaining how to build a maj and xor of three arguments seems really hard to me, but the idea is as follows: we (ab)use the fact that these functions are symmetric (that is, their result doesn't depend on the order of the arguments), so if we have three bits one under another and we want to obtain some $f(x, y, z)$ somewhere under them, we can first copy them one, two and three times, respectively, place necessary bits in the buffer zone and then do something like move_if_1(r) d move_if_1(r) d move_if_1(r) d do_something In the end we should obtain something like this (if numbers were no more than two bits long): Here is a gif with our algorithm adding 2 to 3 if the length was no more than 2.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1080",
    "index": "A",
    "title": "Petya and Origami",
    "statement": "Petya is having a party soon, and he has decided to invite his $n$ friends.\n\nHe wants to make invitations in the form of origami. For each invitation, he needs \\textbf{two} red sheets, \\textbf{five} green sheets, and \\textbf{eight} blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only \\textbf{one} color with $k$ sheets. That is, each notebook contains $k$ sheets of either red, green, or blue.\n\nFind the minimum number of notebooks that Petya needs to buy to invite all $n$ of his friends.",
    "tutorial": "Let's calculate how many notebooks we need for each color separately, and the answer, obviously, will be their sum. We need $2 \\cdot n$ red sheets, $5 \\cdot n$ green sheets, and $8 \\cdot n$ blue sheets. So we need $\\lceil \\frac {2n}{k} \\rceil$ notebooks with red sheets, $\\lceil \\frac{5n}{k} \\rceil$ and $\\lceil \\frac{8n}{k} \\rceil$ notebooks with of green sheets and blue sheets, respectively.",
    "code": "# include <iostream>\n# include <cmath>\n# include <algorithm>\n# include <stdio.h>\n# include <cstdint>\n# include <cstring>\n# include <string>\n# include <cstdlib>\n# include <vector>\n# include <bitset>\n# include <map>\n# include <queue>\n# include <ctime>\n# include <stack>\n# include <set>\n# include <list>\n# include <random>\n# include <deque>\n# include <functional>\n# include <iomanip>\n# include <sstream>\n# include <fstream>\n# include <complex>\n# include <numeric>\n# include <immintrin.h>\n# include <cassert>\n# include <array>\n# include <tuple>\n# include <unordered_set>\n# include <unordered_map>\n \nusing namespace std;\n \n \n \n \n \nint main(int argc, const char * argv[]) {\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    int n,k;\n    int res,cur;\n    cin>>n>>k;\n    res=0;\n    cur=n*2;\n    res+=(cur+k-1)/k;\n    cur=n*5;\n    res+=(cur+k-1)/k;\n    cur=n*8;\n    res+=(cur+k-1)/k;\n    cout<<res<<endl;\n}\n \n ",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1080",
    "index": "B",
    "title": "Margarite and the best present",
    "statement": "Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.\n\nRecently, she was presented with an array $a$ of the size of $10^9$ elements that is filled as follows:\n\n- $a_1 = -1$\n- $a_2 = 2$\n- $a_3 = -3$\n- $a_4 = 4$\n- $a_5 = -5$\n- And so on ...\n\nThat is, the value of the $i$-th element of the array $a$ is calculated using the formula $a_i = i \\cdot (-1)^i$.\n\nShe immediately came up with $q$ queries on this array. Each query is described with two numbers: $l$ and $r$. The answer to a query is the sum of all the elements of the array at positions from $l$ to $r$ inclusive.\n\nMargarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.\n\nHelp her find the answers!",
    "tutorial": "At first let's simplify the problem. Let's denote as $f(x)$ function that returns sum of the elements of the array that have indices from $1$ to $x$ inclusive. In order to calculate the function in a fast and easy way let's split the task into two parts: If $x$ is even, then the sum is equal to: $f(x) = -1 + 2 - 3 + 4 - \\cdots - (x - 1) + x$ $f(x) = (-1 + 2) + (-3 + 4) + \\cdots + (-(x - 1) + x)$ Since the number $x$ is even the number of such pairs is equal to $\\frac{x}{2}$. Since the sum of the elements of each pair is equal to $1$, than $f(x) = \\frac{x}{2}$ Since the number $x$ is even the number of such pairs is equal to $\\frac{x}{2}$. Since the sum of the elements of each pair is equal to $1$, than If $x$ is odd, than the sum is equal to: $f(x) = -1 + 2 - 3 + 4 - \\cdots - (x-2) + (x-1) - x$ $f(x) = f(x-1) - x$ Since $x$ is an odd number than $x - 1$ is an even number. And we know how to solve the problem for even numbers. Since $x$ is an odd number than $x - 1$ is an even number. And we know how to solve the problem for even numbers. But how do we calculate the sum of the elements on an arbitrary segment? Let's show that the sum of the elements of the array with indices from $l$ to $r$ inclusive is equal to $f(r) - f(l-1)$. Overall complexity $O(1)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nlong long F(long long x)\n{\n    if(x % 2 == 0)\n        return x / 2;\n    else\n        return -x + F(x-1);\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int l,r;\n        cin >> l >> r;\n        cout << F(r) - F(l-1) << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1080",
    "index": "C",
    "title": "Masha and two friends",
    "statement": "Recently, Masha was presented with a chessboard with a height of $n$ and a width of $m$.\n\nThe rows on the chessboard are numbered from $1$ to $n$ from bottom to top. The columns are numbered from $1$ to $m$ from left to right. Therefore, each cell can be specified with the coordinates $(x,y)$, where $x$ is the \\textbf{column} number, and $y$ is the \\textbf{row} number \\textbf{(do not mix up)}.\n\nLet us call a rectangle with coordinates $(a,b,c,d)$ a rectangle lower left point of which has coordinates $(a,b)$, and the upper right one — $(c,d)$.\n\nThe chessboard is painted black and white as follows:\n\n\\begin{center}\n{\\small An example of a chessboard.}\n\\end{center}\n\nMasha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat — they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled \\textbf{white} paint on the rectangle $(x_1,y_1,x_2,y_2)$. Then after him Denis spilled \\textbf{black} paint on the rectangle $(x_3,y_3,x_4,y_4)$.\n\nTo spill paint of color $color$ onto a certain rectangle means that all the cells that belong to the given rectangle become $color$. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black).\n\nMasha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers!",
    "tutorial": "At first let's define a function $w(a,b)$, which returns the number of white cells on the subrectangle, the left bottom corner of which has coordinates $(1,1)$ and the top right one has coordinates $(a,b)$. (I will tell you how to implement the function later). How do we solve the problem using this function? Let's define functions $W(a,b,c,d)$ and $B(a,b,c,d)$, which return the number of white cells on the subrectangle which has coordinates $(a,b,c,d)$ and the number of black cells on the subrectangle which has coordinates $(a,b,c,d)$. (The definition of what we call the coordinates of a rectangle can be found in the statements) It can be easily proven that The value of $B(a,b,c,d)$ can be found as the number of all cells substracted by the number of the white cells: It means that in order to calculate the value of functions $W$ and $B$ efficiently it is enough to be able to calculate the value of $w$ efficiently. How de solve the problem using the funcitons defined above? Step 1. We should find the number of black cells and white cells in the initial chessboard (these values will be stored in the variables called $black$ and $white$ respectivly): Step 2. All the black cells in the rectangle $(x_1,y_1,x_2,y_2)$ will become white. So now: Step 3. Now all the white cells in the rectangle $(x_3,y_3,x_4,y_4)$ will become black. So now: But since the functions functions $B$ and $W$ return the number of cells black and white cells respectively in the initial board, so it isn't enough. What we did in the intersection of the rectangles: On step 2 we took the cells that were initially black and coloured them in white (everything is ok by now), but on step 3 we took only the cells that were initially white and coloured them in black. The cells that were initially black and coloured in white on step 2 were not coloured in black. In order to fix this we should find the rectangle which is an intersection of the rectangles $(x_1,y_2,x_2,y_2)$ and $(x_3,y_3,x_4,y_4)$, find the number of black cells in it and then colour them in black. It is obvious that the coordinates of the itersection of the rectangle are $(max(x_1,x_3), max(y_1,y_3), min(x_2,x_4), min(y_2, y_4))$. If $max(x_1,x_3) > min(x_2,x_4)$ or $max(y_1,y_3) > min(y_2, y_4)$ then there is no intersection, so we can just terminate the program. In another case we should apply: So we solved the task. Now it's time to tell how to implement function $w(a,b)$. Let's consider following chessboards from the examples: In order to explain more easily, I will name the pattern like this the pattern type 1 And the pattern like this the pattern type 2: It can be easily seen that if the number of rows is even, then the number of rows of both types is equal to $\\frac{b}{2}$.If the number of rows is odd, then the number of rows of the type 2 is equal to $\\Bigl\\lceil \\frac{b}{2} \\Bigr\\rceil$ and the number of rows of the type 1 is equal to $\\Bigl\\lfloor \\frac{b}{2} \\Bigr\\rfloor$. Since $\\Bigl\\lceil \\frac{b}{2} \\Bigr\\rceil = \\Bigl\\lfloor \\frac{b}{2} \\Bigr\\rfloor$ if $b$ is even then we can just assume that the number of rows with pattern type 1 is $\\Bigl\\lfloor \\frac{b}{2} \\Bigr\\rfloor$ and the number of rows with pattern type 2 is $\\Bigl\\lceil \\frac{b}{2} \\Bigr\\rceil$. In the same way we can prove that the number of white cells in one row with pattern type 1 is equal to $\\Bigl\\lfloor \\frac{a}{2} \\Bigr\\rfloor$ and in the pattern type 2 it is equal to $\\Bigl\\lceil \\frac{a}{2} \\Bigr\\rceil$. So now: Overall complexity $O(1)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nlong long cdiv(long long x, long long y)\n{\n    return x / y + (x%y>0);\n}\n \nlong long w(long long a, long long b)\n{\n    return cdiv(a,2) * cdiv(b,2) + (a/2) * (b/2);\n}\n \nlong long W(long long x1, long long y1, long long x2, long long y2)\n{\n    return w(x2,y2) - w(x2,y1-1) - w(x1-1,y2) + w(x1-1,y1-1);\n}\n \nlong long B(long long x1, long long y1, long long x2, long long y2)\n{\n    return (y2 - y1 + 1) * (x2 - x1 + 1) - W(x1,y1,x2,y2);\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n    int x1,x2,x3,x4,y1,y2,y3,y4;\n    long long n, m;\n    cin >> n >> m ;\n    cin >>x1 >> y1 >>x2 >> y2 >> x3 >> y3 >> x4 >> y4;\n    long long white = W(1,1,m,n);\n    long long black = B(1,1,m,n);\n //   cout << white << ' ' << black << '\\n';\n    white = white + B(x1,y1,x2,y2);\n    black = black - B(x1,y1,x2,y2);\n    //cout << white << ' ' << black << '\\n';\n \n    white = white - W(x3,y3,x4,y4);\n    black = black + W(x3,y3,x4,y4);\n    if(max(x1,x3) <= min(x2,x4) && max(y1,y3) <= min(y2,y4))\n    {\n        white = white - B(max(x1,x3),max(y1,y3),min(x2,x4),min(y2,y4));\n        black = black + B(max(x1,x3),max(y1,y3),min(x2,x4),min(y2,y4));\n    }\n    cout << white << ' ' << black << '\\n';\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1080",
    "index": "D",
    "title": "Olya and magical square",
    "statement": "Recently, Olya received a magical square with the size of $2^n\\times 2^n$.\n\nIt seems to her sister that one square is boring. Therefore, she asked Olya to perform \\textbf{exactly} $k$ splitting operations.\n\nA Splitting operation is an operation during which Olya takes a square with side $a$ and cuts it into 4 equal squares with side $\\dfrac{a}{2}$. If the side of the square is equal to $1$, then it is impossible to apply a splitting operation to it (see examples for better understanding).\n\nOlya is happy to fulfill her sister's request, but she also wants the condition of Olya's happiness to be satisfied after all operations.\n\nThe condition of Olya's happiness will be satisfied if the following statement is fulfilled:\n\nLet the length of the side of the lower left square be equal to $a$, then the length of the side of the right upper square should also be equal to $a$. There should also be a path between them that consists only of squares with the side of length $a$. All consecutive squares on a path should have a common side.\n\nObviously, as long as we have one square, these conditions are met. So Olya is ready to fulfill her sister's request only under the condition that she is satisfied too. Tell her: is it possible to perform exactly $k$ splitting operations in a certain order so that the condition of Olya's happiness is satisfied? If it is possible, tell also the size of the side of squares of which the path from the lower left square to the upper right one will consist.",
    "tutorial": "At first let's check if the value of $k$ is not too large. This can be done greedily in the folllowing way: First splitting operation would be applied on the only existing inital square. After that we have $4$ squares with sides $2^{n-1}$. Now we will do $4$ spliiting operations each on one of them. Then we will have $16$ squares with sides $2^{n-2}$. If we repeat the action $n-1$ times we would end up having $4^n$ squares with size $1$. After that we can't do any more operations. Of course we don't do this manually - we just substract the number of splitting operations we did on each step from the number $k^{'}$ (that's the variable that is a copy of variable $k$ - we will need the value of $k$ later). If at some point of the algorithm we have to do more splitting operations than there remains to, then the value of $k$ is smaller than the maximum number of operations we can apply, thus $k$ is not too large, so we can just stop checking. If the algorithm successfuly did $n-1$ iterations and $k^{'}$ is still greater than $0$, it means that $k$ is greater than the maximum number of operations we can apply, so the answer is \"NO\". It can easily proven that for any $n > 30$ there are no too large numbers $k$ for them within the constraints of the task. Now we know that we can do $k$ operations, but can we do them in such a way the the condition of Olya's happiness is fuldilled? Let's imagine that the constraints are not so big and we can emulate the process. We can do it in the following way: Step 0. We split the only existing square. Step 1. If we can apply splitting opertation to all of the squares on the path from leftmost bottom point to rigthmost top point with the reamining operations, we should do it and after that we return to Step 1. Otherwise, the size of the squares of which the path consists is equal to the size of the squares the path consits now. Go to Step 2. Step 2. When we first did Step 1, we left one square of size $2^{n-1}$ untouched. All the remaining spliiting operations will be used in arbitrary way on it or the squares that appear from it. Let's prove that with relatively big $n$ we can always solve the problem with the following algorithm. If we can build the path from leftmost bottom point to rightmost top point with squares of size $2^0$ than everything is ok, since the remaining splitting operations can be done (we already checked that the value of $k$ is not too large). Otherwise, we can easily see that the number of squares to which you need to apply the splitting operation on each step changes like this: $3,7,15, \\cdots$. It can be proven that the number of splitting operations on the $i$-th step is equal to: Let's assume that we stopped on $x$-th iteration of Step 1. It means that the number of splitting operations remaining is less than $4 * 2^{x-1} - 1$. It also means that we can do at least $1 + 4 + 16 + \\cdots + 4^{x-1}$ operations on the $2^{n-1}$ square that was left untouched after the first iteration of the algorithm. Let's find the set of such numbers $x$ that $1 + 4 + 16 + \\cdots + 4^{x-1}$ is greater or equal to $4 * 2^{x-1} - 1$: Since, in numerical system with base $4$ $1 + 4 + 16 + \\cdots + 4^{x-1}$ can be represented as number with length $x+1$ that consists only of ones, it follows that: Now, back to our inequality: It's obvious that function $f_1(x) = 4^{x}$ grows faster than $f_2(x) = 12 * 2^{x-1} - 2$, so once the value of $f_1$ becomes greater than the value of $f_2$ it will never beome smaller. For $x = 3$: $f_1(3) = 4^{3} = 64$, $f_2(3) = 12 * 2^2 - 2 = 46, f_1(3) > f_2(3)$ For $x = 2$: $f_1(3) = 4^{2} = 16$, $f_2(3) = 12 * 2^1 - 2 = 22, f_1(2) < f_2(2)$ Now we know that the following algorithm always finds solution for all $n \\ge 3$. The rest tests cases can be solved with if's, but still the algorithms works for them. The only exception is test \"2 3\" - there is no solution for this test, though $k$ is smaller than the maximum number of splitting operations you can apply. Like the first part of the solution we shouldn't do the algorthm manually - we can just on each step substract the length of the path from the variable $k$. (For $i$-th step it's $need_i$). Overall complexity $O(logn + logk)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ninline long long getLen(long long n, long long k)\n{\n    long long divisions = 1;\n    k--;\n    long long len = 1;\n    while(divisions < n && k >= 4 * len - 1)\n    {\n        k -= 4 * len - 1;\n        len *= 2;\n        divisions++;\n    }\n    return n - divisions;\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        long long n, k;\n        cin >> n >> k;\n        if(n==2 && k == 3)\n        {\n            cout << \"NO\\n\";\n            continue;\n        }\n        long long _k = k, _n = n;\n        if(n <= 60)\n        {\n            long long pow4 = 1;\n            while(n--)\n            {\n                k -= pow4;\n                pow4 *= 4;\n            }\n            if(k > 0)\n                cout << \"NO\\n\";\n            else\n                cout << \"YES \" << getLen(_n,_k) << \"\\n\";\n        }\n        else\n        {\n            cout << \"YES \" << getLen(_n,_k) << \"\\n\";\n        }\n    }\n    return 0;\n}\n ",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1080",
    "index": "E",
    "title": "Sonya and Matrix Beauty",
    "statement": "Sonya had a birthday recently. She was presented with the matrix of size $n\\times m$ and consist of lowercase Latin letters. We assume that the rows are numbered by integers from $1$ to $n$ from bottom to top, and the columns are numbered from $1$ to $m$ from left to right.\n\nLet's call a submatrix $(i_1, j_1, i_2, j_2)$ $(1\\leq i_1\\leq i_2\\leq n; 1\\leq j_1\\leq j_2\\leq m)$ elements $a_{ij}$ of this matrix, such that $i_1\\leq i\\leq i_2$ and $j_1\\leq j\\leq j_2$. Sonya states that a submatrix is beautiful if we can \\textbf{independently} reorder the characters in each \\textbf{row} (not in column) so that all \\textbf{rows and columns} of this submatrix form palidroms.\n\nLet's recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings $abacaba, bcaacb, a$ are palindromes while strings $abca, acbba, ab$ are not.\n\nHelp Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix.",
    "tutorial": "Suppose we have a submatrix and we want to check whether it is beautiful. First, each line must have a maximum of one character that occurs an odd number of times. Why is this enough to ensure that each line can be made a palindrome by reordering the characters in it? If there is exactly one character that occurs an odd number of times, then the string has an odd length and we can swap it with characters that stand in the central position of the string. All remaining characters can be paired and placed in opposite positions relative to the center of the line. Obviously, this condition is necessary. Also, in order for the submatrix to be beautiful, the following property must be satisfied: the opposing lines of the submatrix, relative to the central lines, must have the same content of characters, possibly in a different order. In other words, if the number of the first line of the submatrix is $i$, and the number of the last line of the submatrix is $j$, then for any integer $k$ $(0 \\leq k\\leq j-i)$ and for any character $c$ from 'a' to 'z' should be true, that the number of times that the character $c$ occurs in the line with the number $i+k$ coincides with the number of times the character $c$ occurs in the line with the number $j-k$. The necessity of this condition is based on the fact that after reordering characters independently in each row, our columns should turn out to be palindromes. To better understand this, see the explanation of the third example from the problem statement. Let us proceed to the solution of the problem: find the number of submatrices for which both of the above conditions are fulfilled. Fix the number of the first column of our submatrix. We will move the right column from the left one to the last one. So, what to do when we have two columns fixed. Let's define which strings can be palindromes, and which ones can't. To do this, we can support the auxiliary array $cnt[i][c]$ - how many times the character $c$ appears in the row with the number $i$. If the submatrix is beautiful, then each of its rows can be a palindrome, which means we can break our lines into groups of maximum size from consecutive lines that can be palindromes, and solve the puzzle for each group independently. Now we have the left and right columns of our submatrix, as well as a segment of consecutive lines, all of which can be palindromes. Then if we select any two rows and form a submatrix from these columns, rows and all rows between them, each row can be a palindrome, which means the first rule will always be fulfilled. It remains only to ensure that the second rule will be fulfilled. Let's break all strings into equivalence classes. In other words, we will give each line some number that will characterize the content of this line - the number of times how many letters each occur in this line. If two lines coincide in content, then they will have the same equivalence class, otherwise their classes will be different. For example, if we have a set of $4$ lines ${abac, ccab, bcaa, baab}$, then their classes will be ${1, 2, 1, 3}$, respectively. How can you find these classes? Previously, we created an array of $cnt[i][c]$, which stores the number of occurrences of each character in each row. We can encode this array with a single number - hash. What to do when we find equivalence class for each line? Let's look at some sub-line from a row of lines. More precisely, we will be interested only in the sequence of their equivalence classes. If our submatrix (formed by all elements on this segment and between the fixed columns) is good, then the equivalence classes of opposite rows are equal. So the sequence of classes on this segment will be a palindrome. So, we reduced the task to finding the number of palindromes on some sequence. This can be done using the Manacher's algorithm for $O(n)$ for each fixed pair of columns, or for $O(nlogn)$ using binary search and one more auxiliary array of hashes. More information about the mentioned topics can be found at the links listed below: Manacher's algorithm: https://cp-algorithms.com/string/manacher.html; Hashes: https://cp-algorithms.com/string/string-hashing.html; Equivalence classes: https://en.wikipedia.org/wiki/Equivalence_class;",
    "code": "# include <iostream>\n# include <cmath>\n# include <algorithm>\n# include <stdio.h>\n# include <cstdint>\n# include <cstring>\n# include <string>\n# include <cstdlib>\n# include <vector>\n# include <bitset>\n# include <map>\n# include <queue>\n# include <ctime>\n# include <stack>\n# include <set>\n# include <list>\n# include <random>\n# include <deque>\n# include <functional>\n# include <iomanip>\n# include <sstream>\n# include <fstream>\n# include <complex>\n# include <numeric>\n# include <immintrin.h>\n# include <cassert>\n# include <array>\n# include <tuple>\n# include <unordered_set>\n# include <unordered_map>\nusing namespace std;\nconst long long md1=1e9+7;\nconst long long md2=1e9+87;\nconst long long key1=397,key2=419;\n \n \nlong long p1[600];\nlong long b[600];\n \nint sz;\nint n,m;\nstring s;\nint a[605][605];\nlong long h[600];\nint msk[600];\nint cnt[610][50];\n \ninline void init_hash() {\n    p1[0]=1;\n    for (int i=1;i<=500;++i)\n        p1[i]=(p1[i-1] * key1)%md1;\n}\n \ninline bool f_number(int x) {\n    return (bool) (x==0 || ((x&(x-1))==0));\n}\n \nint dp1[1005];\nint dp2[1005];\n \ninline long long solve(int i1,int i2) {\n    sz=0;\n    for (int i=i1;i<=i2;++i)\n        b[++sz]=h[i];\n    long long res=0;\n    int l=0,r=0,x;\n    for (int i=1;i<=sz;++i) {\n        if (i>r) x=1;\n        else x=min(dp1[l+r-i],r-i);\n        while (i-x>=1 && i+x<=sz && b[i-x]==b[i+x]) ++x;\n        dp1[i]=x;\n        if (i+x-1>r) l=i-x+1,r=i+x-1;\n        res+=x;\n    }\n    l=0,r=0;\n    for (int i=1;i<=sz;++i) {\n        if (i>r) x=0;\n        else x=min(dp2[l+r-i+1],r-i+1);\n        while (i-x-1>=1 && i+x<=sz && b[i-x-1]==b[i+x]) ++x;\n        dp2[i]=x;\n        res+=x;\n        if (i+x>=r) l=i-x,r=i+x-1;\n    }\n    return res;\n}\n \nint main(int argc, const char * argv[]) {\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    cin>>n>>m;\n    for (int i=1;i<=n;++i) {\n        cin>>s;\n        for (int j=0;j<m;++j)\n            a[i][j+1]=(s[j]-'a');\n    }\n    init_hash();\n    long long x;\n    int i1,i2;\n    long long ans=0;\n    for (int j1=1;j1<=m;++j1) {\n        for (int i=1;i<=n;++i) {\n            msk[i]=0;\n            h[i]=0;\n            memset(cnt[i],0,sizeof(cnt[i]));\n        }\n        for (int j2=j1;j2<=m;++j2) {\n            for (int i=1;i<=n;++i) {\n                x=a[i][j2];\n                if (cnt[i][x]) {\n                    h[i]-=(cnt[i][x] * p1[x+1])%md1;\n                    if (h[i]<0) h[i]+=md1;\n                }\n                ++cnt[i][x];\n                h[i]+=(cnt[i][x] * p1[x+1])%md1;\n                if (h[i]>=md1) h[i]-=md1;\n                msk[i]^=(1<<x);\n            }\n            i1=1;\n            while (i1<=n) {\n                if (!f_number(msk[i1])) {\n                    ++i1;\n                    continue;\n                }\n                i2=i1;\n                while (i2<=n && f_number(msk[i2])) ++i2;\n                --i2;\n                ans+=solve(i1,i2);\n                i1=i2+1;\n            }\n        }\n    }\n    cout<<ans;\n}\n ",
    "tags": [
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1080",
    "index": "F",
    "title": "Katya and Segments Sets",
    "statement": "It is a very important day for Katya. She has a test in a programming class. As always, she was given an interesting problem that she solved very fast. Can you solve that problem?\n\nYou are given $n$ ordered segments sets. Each segment can be represented as a pair of two integers $[l, r]$ where $l\\leq r$. Each set can contain an arbitrary number of segments (even $0$). It is possible that some segments are equal.\n\nYou are also given $m$ queries, each of them can be represented as four numbers: $a, b, x, y$. For each segment, find out whether it is true that each set $p$ ($a\\leq p\\leq b$) contains at least one segment $[l, r]$ that lies entirely on the segment $[x, y]$, that is $x\\leq l\\leq r\\leq y$.\n\nFind out the answer to each query.\n\nNote that you need to solve this problem \\textbf{online}. That is, you will get a new query only after you print the answer for the previous query.",
    "tutorial": "Let's have an array in which we will store each segment and the number of the set to which it belongs. Sort this array in the non-decreasing order of the left border. If the left border is equal, we sort in random order. Now consider any query $a$ $b$ $x$ $y$. We should find the first position where the left border of the segment is greater than or equal to $x$. If there is no such position, then it is obvious that the answer will be \"no\", since there is no set that contains at least one suitable segment. Otherwise, we are interested only in the segments from the position that we have found to the last segment in the array. We can forget about the rest. Now let's among these segments for each set with a number from $a$ to $b$, find the minimum number $W$, such that there exists at least one segment that belongs to this set and its right bound is $W$ (note that we consider only those segments whose left bound is greater than or equal to $x$). If for some segment this number $W$ is greater than $y$, then the answer is \"no\". Otherwise the answer is \"yes\". Let's create a persistent segment tree, where for each set we keep its number $W$. We will update our $W$ values in reverse order - from the last segment to the first one. After hanging the value of the new $W$, we will save the current version in our segment tree. Then how to respond to requests? Let's find the position starting from which all the left borders of our segments will be at least $x$. After that, take the version of the persistent tree of segments that was added immediately after adding this segment. And in this segment tree, we take the minimum on the segment from $a$ to $b$. If our minimum is greater than $y$, then the answer is \"no\". Otherwise the answer is \"yes\".",
    "code": "# include <iostream>\n# include <cmath>\n# include <algorithm>\n# include <stdio.h>\n# include <cstdint>\n# include <cstring>\n# include <string>\n# include <cstdlib>\n# include <vector>\n# include <bitset>\n# include <map>\n# include <queue>\n# include <ctime>\n# include <stack>\n# include <set>\n# include <list>\n# include <random>\n# include <deque>\n# include <functional>\n# include <iomanip>\n# include <sstream>\n# include <fstream>\n# include <complex>\n# include <numeric>\n# include <immintrin.h>\n# include <cassert>\n# include <array>\n# include <tuple>\n# include <unordered_set>\n# include <unordered_map>\nusing namespace std;\n \nconst int inf=2e9;\nconst int N=100002;\nconst int K=300002;\n \n \nint n,m,C,k;\nint sz,all;\nint lft[K*74],rght[K*74],t[K*74];\nint root[K+5];\npair<pair<int,int>,int> seg[K+5];\n \n \ninline void init_segment_tree() {\n    sz=1;\n    while (sz<n) sz+=sz;\n    all=sz+sz;\n    for (int i=1;i<sz;++i) {\n        lft[i]=i+i;\n        rght[i]=i+i+1;\n    }\n    for (int i=1;i<=all;++i)\n        t[i]=inf;\n}\n \n \n////////////////////////// SEGMENT TREE\n \ninline int vcopy(int &x) {\n    ++all;\n    lft[all]=lft[x];\n    rght[all]=rght[x];\n    t[all]=t[x];\n    return all;\n}\n \nvoid update(int l,int r,int ll,int x,int y) {\n    if (l==r) {\n        if (y<t[x]) t[x]=y;\n        return;\n    }\n    int mid=(l+r)>>1;\n    if (ll<=mid) {\n        lft[x]=vcopy(lft[x]);\n        update(l,mid,ll,lft[x],y);\n    } else {\n        rght[x]=vcopy(rght[x]);\n        update(mid+1,r,ll,rght[x],y);\n    }\n    y=t[lft[x]];\n    if (y<t[rght[x]]) y=t[rght[x]];\n    t[x]=y;\n}\n \nint get(int l,int r,int ll,int rr,int x) {\n    if (l>r || ll>r || l>rr || ll>rr) return 0;\n    if (l>=ll && r<=rr) return t[x];\n    int mid=(l+r)>>1;\n    return max(get(l,mid,ll,rr,lft[x]),get(mid+1,r,ll,rr,rght[x]));\n}\n \n//////////////////////////////////////////////////////////////////////\n \ninline void build_segment_tree(int &C) {\n    root[C+1]=1;\n    for (int i=C;i>0;--i) {\n        root[i]=vcopy(root[i+1]);\n        update(1,sz,seg[i].second,root[i],seg[i].first.second);\n    }\n}\n \ninline int get_pos(int &x) {\n    int l=1,r=C;\n    int mid;\n    while (l<r-1) {\n        mid=(l+r)>>1;\n        if (seg[mid].first.first>=x) r=mid;\n        else l=mid;\n    }\n    if (seg[l].first.first>=x) r=l;\n    if (seg[r].first.first>=x) return r;\n    return C+1;\n}\n \n \nint main(int argc, const char * argv[]) {\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    cin>>n>>m>>k;\n    int x,y,c;\n    for (int i=1;i<=k;++i) {\n        cin>>x>>y>>c;\n        seg[++C]=make_pair(make_pair(x,y),c);\n    }\n    init_segment_tree();\n \n    sort(seg+1,seg+C+1);\n    build_segment_tree(C);\n \n    int l, r, pos;\n \n    for (int i=1;i<=m;++i) {\n        cin>>l>>r>>x>>y;\n        pos=get_pos(x);\n        if (pos>C) {\n            cout<<\"no\"<<endl;\n            continue;\n        }\n        if (get(1,sz,l,r,root[pos])>y) cout<<\"no\";\n        else cout<<\"yes\";\n        cout<<endl;\n    }\n \n}\n \n ",
    "tags": [
      "data structures",
      "interactive",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1081",
    "index": "A",
    "title": "Definite Game",
    "statement": "Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.\n\nHe came up with the following game. The player has a positive integer $n$. Initially the value of $n$ equals to $v$ and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer $x$ that $x<n$ and $x$ is not a divisor of $n$, then subtract $x$ from $n$. The goal of the player is to minimize the value of $n$ in the end.\n\nSoon, Chouti found the game trivial. Can you also beat the game?",
    "tutorial": "1 sounds like the minimum value we can get. Why? Is it always true? When $n  \\le  2$, we can do nothing. When $n  \\ge  3$, since $1\\,<\\,\\frac{n}{n-1}<2$, $n - 1$ isn't a divisor of $n$, so we can choose it and get $1$ as the result.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n  int n;\n  scanf(\"%d\", &n);\n  if (n == 2) {\n    puts(\"2\");\n  } else {\n    puts(\"1\");\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1081",
    "index": "B",
    "title": "Farewell Party",
    "statement": "Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.\n\nChouti remembered that $n$ persons took part in that party. To make the party funnier, each person wore one hat among $n$ kinds of weird hats numbered $1, 2, \\ldots n$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.\n\nAfter the party, the $i$-th person said that there were $a_i$ persons wearing a hat \\textbf{differing from his own}.\n\nIt has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $b_i$ be the number of hat type the $i$-th person was wearing, Chouti wants you to find any possible $b_1, b_2, \\ldots, b_n$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.",
    "tutorial": "Consider the number of people wearing hats of the same color. let $b_{i} = n - a_{i}$ represent the number of people wearing the same type of hat of $i$-th person. Notice that the person wearing the same type of hat must have the same $b$s. Suppose the number of people having the same $b_{i}$ be $t$, there would be exactly $\\frac{L}{b_{i}}$ kinds of hats with $b_{i}$ wearers. Therefore, $t$ must be a multiple of $b_{i}$. Also this is also sufficient, just give $b_{i}$ people a new hat color, one bunch at a time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int maxn = 100010;\nint n;\npair<int,int> a[maxn];\nint Ans[maxn],cnt;\nint main(){\n    ios::sync_with_stdio(false);\n    cin>>n;\n    for(int i=1;i<=n;i++){\n        cin>>a[i].first;\n        a[i].first=n-a[i].first;\n        a[i].second=i;\n    }\n    sort(a+1,a+n+1);\n    for(int l=1,r=0;l<=n;l=r+1){\n        for(r=l;r<n&&a[r+1].first==a[r].first;++r);\n        if((r-l+1)%a[l].first){\n            cout<<\"Impossible\"<<endl;\n            return 0;\n        }\n        for(int i=l;i<=r;i+=a[l].first){\n            cnt++;\n            for(int j=i;j<i+a[l].first;++j)Ans[a[j].second]=cnt;\n        }\n    }\n    cout<<\"Possible\"<<endl;\n    for(int i=1;i<=n;i++)cout<<Ans[i]<<' ';\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1081",
    "index": "C",
    "title": "Colorful Bricks",
    "statement": "On his free time, Chouti likes doing some housework. He has got one new task, paint some bricks in the yard.\n\nThere are $n$ bricks lined in a row on the ground. Chouti has got $m$ paint buckets of different colors at hand, so he painted each brick in one of those $m$ colors.\n\nHaving finished painting all bricks, Chouti was satisfied. He stood back and decided to find something fun with these bricks. After some counting, he found there are $k$ bricks with a color different from the color of the brick on its left (the first brick is not counted, for sure).\n\nSo as usual, he needs your help in counting how many ways could he paint the bricks. Two ways of painting bricks are different if there is at least one brick painted in different colors in these two ways. Because the answer might be quite big, you only need to output the number of ways modulo $998\\,244\\,353$.",
    "tutorial": "No hint here :) Let $f[i][j]$ be the ways that there're $j$ bricks of a different color from its left-adjacent brick among bricks numbered $1$ to $i$. Considering whether the $i$-th brick is of the same color of $i - 1$-th, we have $f[i][j] = f[i - 1][j] + f[i - 1][j - 1](m - 1)$. $f[1][0] = m$ and the answer is $f[n][k]$. Also, there is a possibly easier solution. We can first choose the bricks of a different color from its left and then choose a different color to color them, so the answer can be found to be simply ${(binom{n-1}{k}}m(m-1)^{k}$.",
    "code": "//linear\n#include <bits/stdc++.h>\nusing namespace std;\nconst int MOD=998244353;\ntypedef long long ll;\nll fac[2333],rfac[2333];\nll qp(ll a,ll b)\n{\n\tll x=1; a%=MOD;\n\twhile(b)\n\t{\n\t\tif(b&1) x=x*a%MOD;\n\t\ta=a*a%MOD; b>>=1;\n\t}\n\treturn x;\n}\nint n,m,k;\nint main()\n{\n\tscanf(\"%d%d%d\",&n,&m,&k);\n\tfac[0]=1;\n\tfor(int i=1;i<=n;++i)\n\t\tfac[i]=fac[i-1]*i%MOD;\n\trfac[n]=qp(fac[n],MOD-2);\n\tfor(int i=n;i;--i)\n\t\trfac[i-1]=rfac[i]*i%MOD;\n\tprintf(\"%lld\\n\",m*qp(m-1,k)%MOD*fac[n-1]%MOD\n\t*rfac[k]%MOD*rfac[n-1-k]%MOD);\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1081",
    "index": "D",
    "title": "Maximum Distance",
    "statement": "Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.\n\nYou are given a connected undirected graph with $n$ vertices and $m$ weighted edges. There are $k$ special vertices: $x_1, x_2, \\ldots, x_k$.\n\nLet's define the cost of the path as the \\textbf{maximum} weight of the edges in it. And the distance between two vertexes as the \\textbf{minimum} cost of the paths connecting them.\n\nFor each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.\n\nThe original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.",
    "tutorial": "Consider the MST of the graph. Consider the minimum spanning tree formed from the $n$ vertexes, we can find that the distance between two vertexes is the maximum weight of edges in the path between them in the minimum spanning tree (it's clear because of the correctness of Kruskal algorithm). Take any minimum spanning tree and consider some edge in this spanning tree. If this edge has all special vertexes on its one side, it cannot be the answer. Otherwise, it can always contribute to the answer, since for every special vertex, we can take another special vertex on the other side of this edge. Therefore, answers for all special vertexes are the maximum weight of the edges that have special vertexes on both sides. Besides implementing this directly, one can also run the Kruskal algorithm and maintain the number of special vertexes of each connected component in the union-find-set. Stop adding new edges when all special vertexes are connected together and the last edge added should be the answer.",
    "code": "#include<bits/stdc++.h>\n#define L long long\n#define vi vector<int>\n#define pb push_back\nusing namespace std;\nint n,m,t,f[100010],p;\nbool a[100010];\ninline int fa(int i)\n{\n    return f[i]==i?i:f[i]=fa(f[i]);\n}\nstruct edge\n{\n    int u,v,w;\n    inline void unit()\n    {\n        u=fa(u);\n        v=fa(v);\n        if(u!=v)\n          {\n           if(a[u])\n             f[v]=u;\n           else\n             f[u]=v;\n           if(a[u] && a[v])\n             p--;\n           if(p==1)\n             {\n              for(int i=1;i<=t;i++)\n                printf(\"%d \",w);\n              printf(\"\\n\");\n              exit(0);\n             }\n          }\n    }\n}x[100010];\ninline bool cmp(edge a,edge b)\n{\n    return a.w<b.w;\n}\nint main()\n{\n    int i,j;\n    scanf(\"%d%d%d\",&n,&m,&t);\n    p=t;\n    for(i=1;i<=t;i++)\n      {\n       scanf(\"%d\",&j);\n       a[j]=1;\n      }\n    for(i=1;i<=m;i++)\n      scanf(\"%d%d%d\",&x[i].u,&x[i].v,&x[i].w);\n    sort(x+1,x+m+1,cmp);\n    for(i=1;i<=n;i++)\n      f[i]=i;\n    for(i=1;i<=m;i++)\n      x[i].unit();\n    return 0;\n}",
    "tags": [
      "dsu",
      "graphs",
      "shortest paths",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1081",
    "index": "E",
    "title": "Missing Numbers",
    "statement": "Chouti is working on a strange math problem.\n\nThere was a sequence of $n$ positive integers $x_1, x_2, \\ldots, x_n$, where $n$ is even. The sequence was very special, namely for every integer $t$ from $1$ to $n$, $x_1+x_2+...+x_t$ is a square of some integer number (that is, a perfect square).\n\nSomehow, the numbers with odd indexes turned to be missing, so he is only aware of numbers on even positions, i.e. $x_2, x_4, x_6, \\ldots, x_n$. The task for him is to restore the original sequence. Again, it's your turn to help him.\n\nThe problem setter might make mistakes, so there can be no possible sequence at all. If there are several possible sequences, you can output any.",
    "tutorial": "How to solve $n = 2$? Let $s_{i}=\\sum_{j=1}^{t}x_{j}=t_{i}^{2}$, $x_{max} = 2  \\times  10^{5}$. Since $x_{2i} = s_{2i} - s_{2i - 1} = t_{2i}^{2} - t_{2i - 1}^{2}  \\ge  (t_{2i - 1} + 1)^{2} - t_{2i - 1}^{2} = 2t_{2i - 1} + 1$, so $2t_{2i - 1} + 1  \\le  x_{max}$, $t_{2i - 1} < x_{max}$. For every $x\\in[1,x_{m a x}]$, we can precalculate all possible $(a, b)$s so that $x = b^{2} - a^{2}$: enumerate all possible $a$ $\\in[1,x_{m a x})$, then for every $a$ enumerate $b$ from small to large starting from $a + 1$ and stop when $b^{2} - a^{2} > x_{max}$, record this $(a, b)$ for $x = b^{2} - a^{2}$. Since $b^{2}-a^{2}=\\sum_{i=a}^{b-1}(2i+1)\\geq(2a+1)(b-a)$, then $b-a\\leq{\\frac{x_{m a z}}{2a+1}}\\leq{\\frac{x_{m a z}}{a}}$, its complexity is $O(x_{m a x}\\log(x_{m a x}))$. Now, we can try to find a possible $s$ from left to right. Since $x_{2i - 1}$ is positive, we need to ensure $t_{2i - 2} < t_{2i - 1}$. Becuase $x_{2i} = t_{2i}^{2} - t_{2i - 1}^{2}$, we can try all precalculated $(a, b)$s such that $x_{2i} = b^{2} - a^{2}$. If we have several choices, we should choose the one that $a$ is minimum possible, because if the current sum is bigger, it will be harder for the remaining number to keep positive. Bonus: Solve $n  \\le  10^{3}$, $x_{2i}  \\le  10^{9}$. $t_{2i}^{2} - t_{2i - 1}^{2} = (t_{2i} - t_{2i - 1})(t_{2i} + t_{2i + 1})$. Factor $x_{2i}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nint n;\nvector<int> d[200099];\nll su[100099],x[100099];\nint main()\n{\n\tfor(int i=1;i<=200000;++i)\n\t\tfor(int j=i;j<=200000;j+=i)\n\t\t\td[j].push_back(i);\n\tscanf(\"%d\",&n);\n\tfor(int i=2;i<=n;i+=2)\n\t\tscanf(\"%lld\",x+i);\n\tfor(int i=2;i<=n;i+=2)\n\t{\n\t\tfor(auto j:d[x[i]])\n\t\t{\n\t\t\tint a=j,b=x[i]/j;\n\t\t\tif(((a+b)&1)||a>=b) continue;\n\t\t\tint s1=(b-a)/2;\n\t\t\tif(su[i-2]<(ll)s1*s1)\n\t\t\t\tx[i-1]=(ll)s1*s1-su[i-2];\n\t\t}\n\t\tif(x[i-1]==0)\n\t\t{\n\t\t\tputs(\"No\");\n\t\t\treturn 0;\n\t\t}\n\t\tsu[i-1]=su[i-2]+x[i-1];\n\t\tsu[i]=su[i-1]+x[i];\n\t}\n\tputs(\"Yes\");\n\tfor(int i=1;i<=n;i++)\n\t\tprintf(\"%lld%c\",x[i],\" \\n\"[i==n]);\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1081",
    "index": "F",
    "title": "Tricky Interactor",
    "statement": "\\textbf{This is an interactive problem.}\n\nChouti was tired of studying, so he opened the computer and started playing a puzzle game.\n\nLong long ago, the boy found a sequence $s_1, s_2, \\ldots, s_n$ of length $n$, kept by a tricky interactor. It consisted of $0$s and $1$s only and the number of $1$s is $t$. The boy knows nothing about this sequence except $n$ and $t$, but he can try to find it out with some queries with the interactor.\n\nWe define an operation called flipping. Flipping $[l,r]$ ($1 \\leq l \\leq r \\leq n$) means for each $x \\in [l,r]$, changing $s_x$ to $1-s_x$.\n\nIn each query, the boy can give the interactor two integers $l,r$ satisfying $1 \\leq l \\leq r \\leq n$ and the interactor will either flip $[1,r]$ or $[l,n]$ (both outcomes have the same probability and all decisions made by interactor are independent from each other, see Notes section for more details). The interactor will tell the current number of $1$s after each operation. Note, that the sequence \\textbf{won't be restored} after each operation.\n\nHelp the boy to find the \\textbf{original} sequence in no more than $10000$ interactions.\n\n\"Weird legend, dumb game.\" he thought. However, after several tries, he is still stuck with it. Can you help him beat this game?",
    "tutorial": "What about parity? Assuming the number of $1$s changed from $a$ to $b$ after flipping a range of length $s$. Let the number of $1$s in the range before this flip be be $t$, then $b - a = (l - t) - t = s - 2t$, so $b-a\\equiv s({\\mathrm{mod}}\\ 2)$. So if we made a query $l, r$, the parities of the lengths of $[1, r]$ and $[l, n]$ are different, we can find out which one is actually flipped by parity of delta. Also if we only want $[1, r]$ or $[l, n]$ to be flipped and nothing else, we can keep querying $l, r$ and record all the flips happened until it's the actual case (since flipping a range twice is equivalent to no flipping at all). The expected number of queries needed is $3$. Let $s_{a, b}$ be, currently $a  \\equiv $ the number of times $[1, r]$ is flipped $({\\mathrm{mod}}\\;2)$, $b  \\equiv $ the number of times $[r, n]$ is flipped $({\\mathrm{mod}}\\;2)$, the expectation of remaining number of queries needed to complete our goal. Then $s_{1, 0} = 0$ (goal), we're going to find out $s_{0, 0}$. $s_{0, 0} = (s_{0, 1} + s_{1, 0}) / 2 + 1, s_{0, 1} = (s_{0, 0} + s_{1, 1}) / 2 + 1, s_{1, 1} = (s_{1, 0} + s_{0, 1}) / 2 + 1$. Solve this equation you'll get $s_{0, 0} = 3, s_{0, 1} = 4, s_{1, 1} = 3$. Since $r\\neq n-l+1{\\mathrm{~(mod~2)}}\\leftrightarrow r\\equiv n-l{\\mathrm{~(mod~2)}}\\leftrightarrow r-l\\equiv n{\\mathrm{~(mod~2)}}$, it's easy to arrive at such arrangements. When $n\\equiv0{\\mathrm{~(mod~}}2{\\mathrm{)}}$, try to query $(1, 1), (1, 1), (2, 2), (2, 2), (3, 3), (3, 3)...(n, n), (n, n)$ and use the method described above to flip $[1, 1], [1, 1], [1, 2], [1, 2], [1, 3], [1, 3]...[1, n], [1, n]$. Thus we'll know $s_{1}, s_{1} + s_{2}, s_{1} + s_{2} + s_{3}...s_{1} + s_{2} + ... + s_{n}$ and $s$ becomes obvious. When $n\\equiv1{\\pmod{2}}$, try to query $(2, n), (2, n), (1, 2), (1, 2), (2, 3), (2, 3)...(n - 1, n), (n - 1, n)$ and use the method described above to flip $[2, n], [2, n], [1, 2], [1, 2][1, 3], [1, 3]...[1, n], [1, n]$. Thus we'll know $s_{2} + s_{3} + ... + s_{n}, s_{1} + s_{2}, s_{1} + s_{2} + s_{3}...s_{1} + s_{2} + ... + s_{n}$ and $s$ also becomes obvious. Also, we can flip every range only once instead of twice by recording whether every element is currently flipped or not, although it will be a bit harder to write.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint n,ss[10005],sn=0,q[333];\nbool tf(int l,int r)\n{\n\tcout<<\"? \"<<l<<\" \"<<r<<endl<<flush;\n\tcin>>ss[++sn];\n\treturn (ss[sn]-ss[sn-1])&1;\n}\nint main()\n{\n\tcin>>n>>ss[0]; q[n]=ss[0];\n\tfor(int i=1;i<n;++i)\n\t{\n\t\tint j=i-n%2;\n\t\tif(j==0)\n\t\t{\n\t\t\tint t[2]={0,0},u=ss[sn];\n\t\t\twhile(t[0]!=1||t[1]!=0)\n\t\t\t\tt[tf(2,n)]^=1;\n\t\t\tint v=ss[sn];\n\t\t\tq[i]=q[n]-(n-1-v+u)/2;\n\t\t\twhile(t[0]||t[1])\n\t\t\t\tt[tf(2,n)]^=1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint t[2]={0,0},u=ss[sn];\n\t\t\twhile(t[0]!=1||t[1]!=0)\n\t\t\t\tt[(tf(j,i)^i)&1]^=1;\n\t\t\tint v=ss[sn];\n\t\t\tq[i]=(i-v+u)/2;\n\t\t\twhile(t[0]||t[1])\n\t\t\t\tt[(tf(j,i)^i)&1]^=1;\n\t\t}\n\t}\n\tcout<<\"! \";\n\tfor(int i=1;i<=n;++i)\n\t\tprintf(\"%d\",q[i]-q[i-1]);\n\tcout<<endl<<flush;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "interactive"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1081",
    "index": "G",
    "title": "Mergesort Strikes Back",
    "statement": "Chouti thought about his very first days in competitive programming. When he had just learned to write merge sort, he thought that the merge sort is too slow, so he restricted the maximum depth of recursion and modified the merge sort to the following:\n\nChouti found his idea dumb since obviously, this \"merge sort\" sometimes cannot sort the array correctly. However, Chouti is now starting to think of how good this \"merge sort\" is. Particularly, Chouti wants to know for a random permutation $a$ of $1, 2, \\ldots, n$ the expected number of inversions after calling MergeSort(a, 1, n, k).\n\nIt can be proved that the expected number is rational. For the given prime $q$, suppose the answer can be denoted by $\\frac{u}{d}$ where $gcd(u,d)=1$, you need to output an integer $r$ satisfying $0 \\le r<q$ and $rd \\equiv u \\pmod q$. It can be proved that such $r$ exists and is unique.",
    "tutorial": "How does \"merge\" work? What is this \"mergesort\" actually doing? First, consider how \"merge\" will work when dealing with two arbitrary arrays. Partition every array into several blocks: find all elements that are larger than all elements before them and use these elements as the start of the blocks. Then, by 'merging' we're just sorting these blocks by their starting elements. (This is because that when we decided to put the start element of a block into the result array, the remaining elements in the block will be sequentially added too since they're smaller than the start element) Now back to the merge sort. What this \"mergesort\" doing is basically dividing the array into several segments (i.e. the ranges reaching the depth threshold). In every segment, the relative order stays the same when merging, so the expected number of inversions they contribute is just $\\frac{l(l-1)}{4}$ (for a segment of length $l$). Again suppose every segment is divided into blocks aforementioned, we're just sorting those blocks altogether by the beginning elements. Let's consider inversions formed from two blocks in two different segments. Say the elements forming the inversion are initially the $i$-th and $j$-th of those two segments (from left to right), then the blocks they belong start from the maximum of the first $i$-th and the first $j$-th of those two segments. Consider the maximum among these $i + j$ numbers, if it is one of these two elements, the inversion can't be formed. The probability that the maximum is neither $i$ nor $j$ is $\\scriptstyle{\\frac{\\mu+2}{i+j}}$, and if the maximum is chosen, there are $50%$ percent of odds that the order of $i$ and $j$ is different from that of two maximums, because these two elements' order can be changed by swapping these two elements while leaving the maximums' order unchanged. So their probability of forming an inversion is just $\\frac{i+j-2}{2(i+j)}=\\frac{1}{2}-\\frac{1}{i+j}$. Enumerate two blocks and $i$ and precalculate the partial sum of reciprocals, we can calculate the expectation of inversions formed from these two blocks in $O(n)$ time. However, there might be $O(n)$ blocks. But there is one more property for this problem: those segments are of at most two different lengths. By considering same length pairs only once, we can get a $O(n)$ or $O(n\\log(n))$ solution. Do an induction on $k$. Suppose for $k - 1$ we have only segments of length $a$ and $a + 1$. If $2|a$, let $a = 2t$, from $2t$ and $2t + 1$ only segments of length $t$ and $t + 1$ will be formed. Otherwise, let $a = 2t + 1$, from $2t + 1$ and $2t + 2$ still only segments of length $t$ and $t + 1$ will be formed. Bonus: solve this problem when the segments' length can be arbitary and $n  \\le  10^{5}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define fi first\n#define se second\n#define SZ 123456\nint n,k,MOD,ts[SZ],tn=0;\nll inv[SZ],invs[SZ];\nll qp(ll a,ll b)\n{\n\tll x=1; a%=MOD;\n\twhile(b)\n\t{\n\t\tif(b&1) x=x*a%MOD;\n\t\ta=a*a%MOD; b>>=1;\n\t}\n\treturn x;\n}\nvoid go(int l,int r,int h)\n{\n\tif(h<=1||l==r) ts[++tn]=r-l+1;\n\telse\n\t{\n\t\tint m=(l+r)>>1;\n\t\tgo(l,m,h-1); go(m+1,r,h-1);\n\t}\n}\nmap<ll,int> cnt;\nll calc(int a,int b)\n{\n\tll ans=a*(ll)b%MOD;\n\tfor(int i=1;i<=a;++i)\n\t\tans-=(invs[i+b]-invs[i])*2LL,ans%=MOD;\n\treturn ans;\n}\nint main()\n{\n\tscanf(\"%d%d%d\",&n,&k,&MOD);\n\tfor(int i=1;i<=max(n,2);++i)\n\t\tinv[i]=qp(i,MOD-2),\n\t\tinvs[i]=(invs[i-1]+inv[i])%MOD;\n\tgo(1,n,k); ll ans=0;\n\tfor(int i=1;i<=tn;++i)\n\t\t++cnt[ts[i]],ans+=ts[i]*(ll)(ts[i]-1)/2,ans%=MOD;\n\tfor(auto t:cnt)\n\t\tif(t.se>=2)\n\t\t\tans+=calc(t.fi,t.fi)*((ll)t.se*(t.se-1)/2%MOD),ans%=MOD;\n\tfor(auto a:cnt)\n\t\tfor(auto b:cnt)\n\t\t\tif(a.fi<b.fi)\n\t\t\t\tans+=calc(a.fi,b.fi)*((ll)a.se*b.se%MOD),ans%=MOD;\n\tans=ans%MOD*inv[2]%MOD;\n\tans=(ans%MOD+MOD)%MOD;\n\tprintf(\"%d\\n\",int(ans));\n}",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1081",
    "index": "H",
    "title": "Palindromic Magic",
    "statement": "After learning some fancy algorithms about palindromes, Chouti found palindromes very interesting, so he wants to challenge you with this problem.\n\nChouti has got two strings $A$ and $B$. Since he likes palindromes, he would like to pick $a$ as some non-empty palindromic substring of $A$ and $b$ as some non-empty palindromic substring of $B$. Concatenating them, he will get string $ab$.\n\nChouti thinks strings he could get this way are interesting, so he wants to know how many different strings he can get.",
    "tutorial": "What will be counted twice? Warning: This editorial is probably new and arcane for ones who are not familiar with this field. If you just want to get a quick idea about the solution, you can skip all the proofs (they're wrapped in spoiler tags). Some symbols: All indices of strings start from zero. $x^{R}$ stands for the reverse of string $x$. (e.g. $'abc'^{R} = 'cba'$), $xy$ stands for concatenation of $x$ and $y$. (e.g. $x = 'a', y = 'b', xy = 'ab'$), $x^{a}$ stands for concatenation of $a$ copies of $x$ (e.g. $x = 'ab'$, $x^{2} = 'abab'$). $x[a, b]$ stands for the substring of $x$ starting and ending from the $a$-th and $b$-th character. (e.g. $'abc'[1, 2] = 'bc'$) Border of $x$: strings with are common prefix & suffix of $x$. Formally, $x$ has a border of length $t$ $(x[0, t - 1])$ iff $x_{i} = x_{|x| - t + i}$ ($i\\in[0,t-1]$). Period of $x$: $x$ has a period of length $t$ iff $x_{i} = x_{i + t}$ ($0  \\le  i < |x| - t$). When $t||x|$ we also call $t$ a full period. From the formulas it's easy to see $x$ has a period of length $t$ iff $x$ has a border of length $|x| - t$. ($t\\in\\left[1,\\left|x\\right|\\right]$) Power: $x$ is a power iff the minimum full period of $x$ isn't $|x|$. e.g. abab is a power. Lemma 1 (weak periodicity lemma): if $p$ and $q$ are periods of $s$, $p + q  \\le  |s|$, $gcd(p, q)$ is also a period of $s$. Suppose $p < q, d = q - p$. If $|s| - q  \\le  i < |s| - d$, $s_{i} = s_{i - p} = s_{i + d}$. If $0  \\le  i < |s| - q$, $s_{i} = s_{i + q} = s_{i + q - p} = s_{i + d}$. So $q - p$ is also a period. Using Euclid algorithm we can get $gcd(p, q)$ is a period. Lemma 2: Let $S$ be the set of period lengths $ \\le  |s| / 2$ of $s$, if $S$ is non-empty, $\\forall u\\in S,\\operatorname*{min}S|u$. Let $min S = v$, since $v + u  \\le  |s|$, $gcd(v, u)$ is also a valid period, so $gcd(v, u)  \\ge  v$, $v|u$. Let $border(x)$ be the longest (not-self) border of $x$. e.g. $border('aba') = 'a', border('ab') = \"$. If $x$ is a palindrome, its palindromic prefix and suffix must be its border. Therefore, its (not-self) longest palindromic prefix (suffix) is $border(x)$. Let $|x| = a$, $x$ has a border of length $b$ iff $x_{i} = x_{a - b + i}$ ($i\\in[0,b-1]$), $x$ has a palindromic prefix of length $b$ iff $x_{i} = x_{b - 1 - i}$ ($i\\in[0,b-1]$). Since $x_{i} = x_{a - 1 - i}$, they are just the same. If $S = pq$, $p$ and $q$ are palindromic and non-empty, we call $(p, q)$ a palindromic decomposition of $S$. If $S = pq$, $p$ and $q$ are palindromic, $q$ is non-empty ($p$ can be empty) we call $(p, q)$ a non-strict palindromic decomposition of $S$. Lemma 3: if $S = x_{1} x_{2} = y_{1} y_{2} = z_{1} z_{2}$, $|x_{1}| < |y_{1}| < |z_{1}|$, $x_{2}, y_{1}, y_{2}, z_{1}$ are palindromic and non-empty, then $x_{1}$ and $z_{2}$ are also palindromic. Let $z_{1} = y_{1} v$. $v^{R}$ is a suffix of $y_{2}$, also a suffix of $x_{2}$. So $v$ is a prefix of $x_{2}$, then $x_{1v}$ is a prefix of $z_{1}$. Since $y_{1}$ is a palindromic prefix of $z_{1}$, $z_{1} = y_{1} v$, $|v|$ is a period of $z_{1}$. Since $x_{1v}$ is a prefix, so $|v|$ is also a period of $x_{1} v$. Suppose $t$ be some arbitary large number (you can think of it as $ \\infty $), then $x_{1}$ is a suffix of $v^{t}$. Since $v^{R}$ is prefix of $z_{1}$, $x_{1}$ is a prefix of $(v^{R})^{t}$. So $x_{1}^{R}$ is a suffix of $v^{t}$, then $x_{1} = x_{1}^{R}$, so $x_{1}$ is palindromic. $z_{2}$ is palindromic similarly. Lemma 4: Suppose $S$ has some palindromic decomposition. Let the longest palindromic prefix of $S$ be $a$, $S = ax$, longest palindromic suffix of $S$ be $b$, $S = yb$. At least one of $x$ and $y$ is palindromic. If none of them are palindromic, let $S = pq$ be a valid palindromic decomposition of $S$, then $S = yb = pq = ax$, by Lemma 3, contradiction. Lemma 5: $S = p_{1} q_{1} = p_{2} q_{2}$ ($|p_{1}| < |p_{2}|$, $p_{1}, q_{1}, p_{2}, q_{2}$ are palindromic, $q_{1}$ and $q_{2}$ are non-empty), then $S$ is a power. We prove this by proving $gcd(|p_{2}| - |p_{1}|, |S|)$ is a period. Let $|S| = n$, $|p_{2}| - |p_{1}| = t$. Because $p_{1}$ is a palindromic prefix of $p_{2}$, $t$ is a period of $p_{2}$. Similarly $t$ is a period of $q_{1}$. Since they have a common part of length $t$ (namely $S[p_{1}, p_{2} - 1]$), $t$ is a period of $S$. So $t$ is a period of $S$. For $x\\in[0,t)$, $s_{x} = s_{|p2| - 1 - x} = s_{n - 1 + |p1| - (|p2| - 1 - x)} = s_{n - t + x}$ (first two equations are because $p_{2}$ and $q_{1}$ and palindromic). So $n - t$ is also a period of $S$. Since $t + n - t = n$, $gcd(t, n - t) = gcd(t, n)$ is also a period of $S$. (weak periodicity lemma) Lemma 6: Let $S = p_{1} q_{1} = p_{2} q_{2} = ... = p_{t} q_{t}$ be all non-strict palindromic decompositions of $S$, $h$ be the minimum full period of $S$. When $t  \\neq  0$, $t = |S| / h$. From Lemma 5, it's clear that $h = |S|$ iff $t = 1$. In the following $t  \\ge  2$ is assumed. Let $ \\alpha  = S[0, h - 1]$, because $ \\alpha $ is not a power (otherwise $s$ will have smaller full period), $ \\alpha $ has at most one non-strict palindromic decomposition (from Lemma 5). Let $S = pq$ be any non-strict palindromic decomposition, then $max(|p|, |q|)  \\ge  h$. When $|p|  \\ge  h$, $ \\alpha  = p[0, h - 1]$, so $\\alpha[0,|p|\\,\\mathrm{mod}\\,h-1]=p^{R}[0,|p]\\,\\mathrm{mod}\\,h-1]=(\\alpha[0,|p]\\,\\mathrm{mod}\\,h-1)^{R}$, then $\\alpha[0,|p]{\\mathrm{~mod~}}h-1]$ is palindromic. Similarly $\\alpha[|p|\\mathrm{\\,mod\\,}h,h-1]$ is also palindromic. When $|q|  \\ge  h$ similar arguments can be applied. Therefore, $\\alpha[0,|p]{\\mathrm{~mod~}}h-1]$ and $\\alpha[|p|\\mathrm{\\,mod\\,}h,h-1]$ is a non-strict palindromic decomposition of $ \\alpha $. Therefore, $ \\alpha $ has a non-strict palindromic decomposition. Let its only non-strict palindromic decomposition be $ \\alpha [0, g - 1]$ and $ \\alpha [g, h - 1]$. Therefore, every $p_{i}$ must satisfy $p_{i}{\\mathrm{~mod~}}h=g$, so $t  \\le  |s| / h$. Also, these all $|s| / h$ decompositions can be obtained. Lemma 7: Let $S = p_{1} q_{1} = p_{2} q_{2} = ... = p_{t} q_{t}$ be all non-strict palindromic decompositions of $S$. ($|p_{i}| < |p_{i + 1}|$) For every $i\\in[1,t-1]$, at least one of $p_{i} = border(p_{i + 1})$ and $q_{i + 1} = border(q_{i})$ is true. Instead of proving directly, we first introduce a way to compute all decompositions. Let the longest palindromic prefix of $S$ be $a$ $(a  \\neq  S)$, $S = ax$, longest palindromic suffix of $S$ be $b$ (it may be $S$), $S = yb$. If $x = b$ obviously $S = ab$ is the only way to decompose. If $S = pq$ and $p  \\neq  a, q  \\neq  b$, $p$ and $q$ are palindromic, by Lemma 3 we have $x, y$ are also palindromic. So if neither $x$ or $y$ is palindromic, then $S$ can't be composed to two palindromes. If exactly one of $x$ and $y$ is palindromic, it's the only way to decompose $S$. If both of them are palindromic, we can then find the second-longest non-self palindromic prefix of $S$: $c$. Let $S = cz$, if $z$ is not palindromic or $c = y$, then $S = ax = yb$ are the only non-strict palindromic decompositions. Otherwise, we can find all palindromic suffix of $|S|$ whose lengths between $|z|$ and $|b|$, their prefixes must also be palindromic (using Lemma 3 for $ax$ and $cz$), then $S = ax = cz = ... = yb$ (other palindromic suffixes and their corresponding prefixes are omitted) Back to the proof of Lemma 7, the only case we need to prove now is $S = ax = yb$. Suppose the claim is incorrect, let $p = border(a)$, $s = border(y)$, $S = ax = pq = rs = yb$, ($|a| > |p| > |y|, |a| > |r| > |y|$, $p$ and $s$ are palindromic) Continuing with the proof of Lemma 6, since $t = 2$, $S =  \\alpha ^{2}$. If $|p|  \\ge  | \\alpha |$, $q=\\alpha[|p|\\,\\mathrm{mod}\\,h,h-1]$, so $q$ would also be palindromic, contradiction. Therefore, $|p| < | \\alpha |$ and similarly $|s| < | \\alpha |$. Let $ \\alpha  = pq' = r's$ and the non-strict palindromic decomposition of $ \\alpha $ be $ \\alpha  =  \\beta  \\theta $. Since $ \\alpha  = pq' =  \\beta  \\theta  = r's$, by Lemma 3 $q'$ and $r'$ should also be palindromic, contradiction. Lemmas are ready, let's start focusing on this problem. A naive idea is to count the number of palindromes in $A$ and in $B$, and multiply them. This will obviously count a string many times. By Lemma 7, suppose $S = xy$, to reduce counting, we can check if using $border(x)$ or $border(y)$ to replace $x$ or $y$ can also achieve $S$. If any of them do, reduce the answer by 1, then we're done. So for a palindromic string $x$ in $A$, we want to count strings that are attainable from both $x$ and $border(x)$ and subtract from the answer. Finding $x$ and $border(x)$ themselves can be simply done by the palindromic tree. Let $x = border(x)w$, we want to count $T$s in $B$ that $T = wS$ and both $T$ and $S$ are palindromic. Since $|w|$ is the shortest period of $x$, $w$ can't be a power. If $|w| > |S|$, $w = S + U$. $S$ are $U$ are both palindromes. Since $w$ is not a power, it can be decomposed to be two palindromes in at most one way (Lemma 5). We can find that only way (by checking maximal palindromic suffix & prefix) and use hashing to check if it exists in $B$. If $|w|  \\le  |S|$, if $S$ is not maximum palindromic suffix of $T$, $w$ must be a power (Lemma 2), so we only need to check maximum palindromic suffixes (i.e. $S = border(T)$). We need to do the similar thing to $y$s in $B$, then adding back both attainable from $border(x)$ and $border(y)$. Adding back can be done in a similar manner, or directly use hashing to find all matching $w$ s. Finding maximal palindromic suffix and prefix of substrings can be done by binary-lifting on two palindromic trees (one and one reversed). Let $up_{i, j}$ be the resulting node after jumping through fail links for $2^{j}$ steps from node $i$. While querying maximal palindromic suffix for $s[l, r]$, find the node corresponding to the maximal palindromic suffix of $s[1, r]$ (this can be stored while building palindromic tree). If it fits into $s[l, r]$ we're done. Otherwise, enumerate $j$ from large to small and jump $2^{j}$ steps (with the help of $up$) if the result node is still unable to fit into $s[l, r]$, then jump one more step to get the result.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 234567;\nconst int LOG = 18;\nconst int ALPHA = 26;\nconst int base = 2333;\nconst int md0 = 1e9 + 7;\nconst int md1 = 1e9 + 9;\n\nstruct hash_t {\n  int hash0, hash1;\n\n  hash_t(int hash0 = 0, int hash1 = 0):hash0(hash0), hash1(hash1) {\n  }\n\n  hash_t operator + (const int &x) const {\n    return hash_t((hash0 + x) % md0, (hash1 + x) % md1);\n  };\n\n  hash_t operator * (const int &x) const {\n    return hash_t((long long)hash0 * x % md0, (long long)hash1 * x % md1);\n  }\n\n  hash_t operator + (const hash_t &x) const {\n    return hash_t((hash0 + x.hash0) % md0, (hash1 + x.hash1) % md1);\n  };\n\n  hash_t operator - (const hash_t &x) const {\n    return hash_t((hash0 + md0 - x.hash0) % md0, (hash1 + md1 - x.hash1) % md1);\n  };\n\n  hash_t operator * (const hash_t &x) const {\n    return hash_t((long long)hash0 * x.hash0 % md0, (long long)hash1 * x.hash1 % md1);\n  }\n\n  long long get() {\n    return (long long)hash0 * md1 + hash1;\n  }\n} ha[N], hb[N], power[N];\n\nstruct palindrome_tree_t {\n  int n, total, p[N], pos[N], value[N], parent[N], go[N][ALPHA], ancestor[LOG][N];\n  char s[N];\n\n  palindrome_tree_t() {\n    parent[0] = 1;\n    value[1] = -1;\n    total = 1;\n    p[0] = 1;\n  }\n\n  int extend(int p, int w, int n) {\n    while (s[n] != s[n - value[p] - 1]) {\n      p = parent[p];\n    }\n    if (!go[p][w]) {\n      int q = ++total, k = parent[p];\n      while (s[n] != s[n - value[k] - 1]) {\n        k = parent[k];\n      }\n      value[q] = value[p] + 2;\n      parent[q] = go[k][w];\n      go[p][w] = q;\n      pos[q] = n;\n    }\n    return go[p][w];\n  }\n\n  void init() {\n    for (int i = 1; i <= n; ++i) {\n      p[i] = extend(p[i - 1], s[i] - 'a', i);\n    }\n    for (int i = 0; i <= total; ++i) {\n      ancestor[0][i] = parent[i];\n    }\n    for (int i = 1; i < LOG; ++i) {\n      for (int j = 0; j <= total; ++j) {\n        ancestor[i][j] = ancestor[i - 1][ancestor[i - 1][j]];\n      }\n    }\n  }\n\n  int query(int r, int length) {\n    r = p[r];\n    if (value[r] <= length) {\n      return value[r];\n    }\n    for (int i = LOG - 1; ~i; --i) {\n      if (value[ancestor[i][r]] > length) {\n        r = ancestor[i][r];\n      }\n    }\n    return value[parent[r]];\n  }\n\n  bool check(int r, int length) {\n    r = p[r];\n    for (int i = LOG - 1; ~i; --i) {\n      if (value[ancestor[i][r]] >= length) {\n        r = ancestor[i][r];\n      }\n    }\n    return value[r] == length;\n  }\n} A, B, RA, RB;\n\nmap<long long, int> fa, fb, ga, gb;\nlong long answer;\nchar a[N], b[N];\nint n, m;\n\nhash_t get_hash(hash_t *h, int l, int r) {\n  return h[r] - h[l - 1] * power[r - l + 1];\n}\n\nint main() {\n#ifdef wxh010910\n  freopen(\"input.txt\", \"r\", stdin);\n#endif\n  scanf(\"%s %s\", a + 1, b + 1);\n  n = strlen(a + 1);\n  m = strlen(b + 1);\n  A.n = RA.n = n;\n  B.n = RB.n = m;\n  for (int i = 1; i <= n; ++i) {\n    A.s[i] = RA.s[n - i + 1] = a[i];\n    ha[i] = ha[i - 1] * base + a[i];\n  }\n  for (int i = 1; i <= m; ++i) {\n    B.s[i] = RB.s[m - i + 1] = b[i];\n    hb[i] = hb[i - 1] * base + b[i];\n  }\n  power[0] = hash_t(1, 1);\n  for (int i = 1; i <= max(n, m); ++i) {\n    power[i] = power[i - 1] * base;\n  }\n  A.init();\n  B.init();\n  RA.init();\n  RB.init();\n  answer = (long long)(A.total - 1) * (B.total - 1);\n  for (int i = 2; i <= A.total; ++i) {\n    ++fa[get_hash(ha, A.pos[i] - A.value[i] + 1, A.pos[i]).get()];\n    int p = A.parent[i];\n    if (p < 2) {\n      continue;\n    }\n    int l = A.pos[i] - (A.value[i] - A.value[p]) + 1, r = A.pos[i];\n    if (A.value[i] <= A.value[p] << 1) {\n      ++ga[get_hash(ha, l, r).get()];\n    }\n  }\n  for (int i = 2; i <= B.total; ++i) {\n    ++fb[get_hash(hb, B.pos[i] - B.value[i] + 1, B.pos[i]).get()];\n    int p = B.parent[i];\n    if (p < 2) {\n      continue;\n    }\n    int l = B.pos[i] - B.value[i] + 1, r = B.pos[i] - B.value[p];\n    if (B.value[i] <= B.value[p] << 1) {\n      ++gb[get_hash(hb, l, r).get()];\n    }\n  }\n  for (int i = 2; i <= A.total; ++i) {\n    int p = A.parent[i];\n    if (p < 2) {\n      continue;\n    }\n    int l = A.pos[i] - (A.value[i] - A.value[p]) + 1, r = A.pos[i];\n    long long value = get_hash(ha, l, r).get();\n    if (gb.count(value)) {\n      answer -= gb[value];\n    }\n    int longest_palindrome_suffix = A.query(r, r - l + 1);\n    if (longest_palindrome_suffix == r - l + 1) {\n      continue;\n    }\n    if (RA.check(n - l + 1, r - l + 1 - longest_palindrome_suffix)) {\n      int length = r - l + 1 - longest_palindrome_suffix;\n      if (fb.count(get_hash(ha, l, l + length - 1).get()) && fb.count((get_hash(ha, l, r) * power[length] + get_hash(ha, l, l + length - 1)).get())) {\n        --answer;\n      }\n      continue;\n    }\n    int longest_palindrome_prefix = RA.query(n - l + 1, r - l + 1);\n    if (A.check(r, r - l + 1 - longest_palindrome_prefix)) {\n      int length = longest_palindrome_prefix;\n      if (fb.count(get_hash(ha, l, l + length - 1).get()) && fb.count((get_hash(ha, l, r) * power[length] + get_hash(ha, l, l + length - 1)).get())) {\n        --answer;\n      }\n      continue;\n    }\n  }\n  for (int i = 2; i <= B.total; ++i) {\n    int p = B.parent[i];\n    if (p < 2) {\n      continue;\n    }\n    int l = B.pos[i] - B.value[i] + 1, r = B.pos[i] - B.value[p];\n    long long value = get_hash(hb, l, r).get();\n    if (ga.count(value)) {\n      answer -= ga[value];\n    }\n    int longest_palindrome_suffix = B.query(r, r - l + 1);\n    if (longest_palindrome_suffix == r - l + 1) {\n      continue;\n    }\n    if (RB.check(m - l + 1, r - l + 1 - longest_palindrome_suffix)) {\n      int length = longest_palindrome_suffix;\n      if (fa.count(get_hash(hb, r - length + 1, r).get()) && fa.count((get_hash(hb, r - length + 1, r) * power[r - l + 1] + get_hash(hb, l, r)).get())) {\n        --answer;\n      }\n      continue;\n    }\n    int longest_palindrome_prefix = RB.query(m - l + 1, r - l + 1);\n    if (B.check(r, r - l + 1 - longest_palindrome_prefix)) {\n      int length = r - l + 1 - longest_palindrome_prefix;\n      if (fa.count(get_hash(hb, r - length + 1, r).get()) && fa.count((get_hash(hb, r - length + 1, r) * power[r - l + 1] + get_hash(hb, l, r)).get())) {\n        --answer;\n      }\n      continue;\n    }\n  }\n  for (int i = 2; i <= A.total; ++i) {\n    int p = A.parent[i];\n    if (p < 2) {\n      continue;\n    }\n    int l = A.pos[i] - (A.value[i] - A.value[p]) + 1, r = A.pos[i];\n    if (A.value[i] > A.value[p] << 1) {\n      ++ga[get_hash(ha, l, r).get()];\n    }\n  }\n  for (int i = 2; i <= B.total; ++i) {\n    int p = B.parent[i];\n    if (p < 2) {\n      continue;\n    }\n    int l = B.pos[i] - B.value[i] + 1, r = B.pos[i] - B.value[p];\n    if (B.value[i] > B.value[p] << 1) {\n      ++gb[get_hash(hb, l, r).get()];\n    }\n  }\n  for (auto p : ga) {\n    answer += (long long)p.second * gb[p.first];\n  }\n  printf(\"%lld\\n\", answer);\n  return 0;\n}",
    "tags": [
      "data structures",
      "hashing",
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1082",
    "index": "A",
    "title": "Vasya and Book",
    "statement": "Vasya is reading a e-book. The file of the book consists of $n$ pages, numbered from $1$ to $n$. The screen is currently displaying the contents of page $x$, and Vasya wants to read the page $y$. There are two buttons on the book which allow Vasya to scroll $d$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $10$ pages, and $d = 3$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.\n\nHelp Vasya to calculate the minimum number of times he needs to press a button to move to page $y$.",
    "tutorial": "It is easy to understand that the optimal answer is achieved in one of three cases: Vasya is trying to visit page $y$ without visiting pages $1$ and $n$; Vasya first goes to the page $1$, and then to the page $y$; Vasya first goes to the $n$ page, and then to the $y$ page. In the first case, Vasya can go directly to the $y$ page from the $x$ page if $|x-y|$ is divided by $d$. In the second case, Vasya can get to page $y$ through page $1$, if $y - 1$ is divided by $d$. The required number of actions will be equal to $\\lceil \\frac{x - 1}{d} \\rceil + \\frac{y - 1}{d}$. Similarly, in the third case, Vasya can go to the page $y$ through the page $n$ if $n - y$ is divided by $d$. The required number of actions will be equal to $\\lceil\\frac{n - x}{d} \\rceil + \\frac{n - y}{d}$. If none of the three options described above is appropriate, then there is no answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = int(2e9) + 99;\n\nint n, x, y, d;\n\nint dist(int x, int y){\n\treturn (abs(x - y) + (d - 1)) / d;\n}\n\nint main() {\n\t\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; ++i){\n    \tcin >> n >> x >> y >> d;\n    \t\n    \tint len = abs(x - y);\n    \tint res = INF;\n    \t\n    \tif(len % d == 0) \n    \t\tres = min(res, dist(x, y));\n    \t\n    \tlen = y - 1;\n    \tif(len % d == 0)\n    \t\tres = min(res, dist(x, 1) + dist(1, y));\n    \t\n    \tlen = n - y;\n    \tif(len % d == 0)\n    \t\tres = min(res, dist(x, n) + dist(n, y));\n    \t\t\n    \tif(res == INF)\n    \t\tres = -1;\n    \t\n    \tcout << res << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1082",
    "index": "B",
    "title": "Vova and Trophies",
    "statement": "Vova has won $n$ trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.\n\nThe beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.\n\nHelp Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.",
    "tutorial": "Let $r_i$ be the maximal segment of gold cups that begins in the cup $i$. Let $l_i$ be the maximum segment of gold cups that ends in the cup $i$. Also, let the total number of gold cups be $cntG$. Note that it makes no sense to change the cups of the same color. Then let's consider the silver cup, which will change with the gold cup, let its number be $i$. Then if $r_{i + 1} + l_{i - 1} < cntG$, then we will update the answer with the value $r_{i + 1} + l_{i - 1} + 1$, and otherwise with the value $r_{i + 1} + l_{i - 1}$. This will not work if all the cups are golden. In this case, the answer is $n$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nstring s;\n\nint main() {\n\t\n\tcin >> n >> s;\n\t\n\tvector <int> l(n), r(n);\n\tfor(int i = 0; i < n; ++i){\n\t\tif(s[i] == 'G'){\n\t\t\tl[i] = 1;\n\t\t\tif(i > 0) l[i] += l[i - 1];\n\t\t}\n\t}\n\tfor(int i = n - 1; i >= 0; --i){\n\t\tif(s[i] == 'G'){\n\t\t\tr[i] = 1;\n\t\t\tif(i + 1 < n) r[i] += r[i + 1];\n\t\t}\n\t}\n\t\n\t\n\tint res = 0;\n\tint cntG = 0;\n\tfor(int i = 0; i < n; ++i)\n\t\t\tcntG += s[i] == 'G';\n\t\t\t\n\tfor(int i = 0; i < n; ++i){\n\t\tif(s[i] == 'G') continue;\n\t\tint nres = 1;\n\t\tif(i > 0) nres += l[i - 1];\n\t\tif(i + 1 < n) nres += r[i + 1];\n\t\tres = max(res, nres);\n\t}\n\t\n\tres = min(res, cntG);\n\tif(cntG == n) res = cntG;\n\tcout << res << endl;\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1082",
    "index": "C",
    "title": "Multi-Subject Competition",
    "statement": "A multi-subject competition is coming! The competition has $m$ different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students.\n\nHe has $n$ candidates. For the $i$-th person he knows subject $s_i$ the candidate specializes in and $r_i$ — a skill level in his specialization (this level can be negative!).\n\nThe rules of the competition require each delegation to choose some subset of subjects they will participate in. The only restriction is that the \\textbf{number of students from the team} participating in each of the \\textbf{chosen} subjects should be the \\textbf{same}.\n\nAlex decided that each candidate would participate only in the subject he specializes in. Now Alex wonders whom he has to choose to maximize the total sum of skill levels of all delegates, or just skip the competition this year if every valid non-empty delegation has negative sum.\n\n(Of course, Alex doesn't have any spare money so each delegate he chooses must participate in the competition).",
    "tutorial": "At first, it's optimal to take candidates with maximal levels for a fixed subject. At second, if we fix number of participants in each subject for some delegation, then it's always optimal to choose all subjects with positive sum of levels. It leads us to a following solution. Let's divide all candidates by it's $s_i$ and sort each group in non-increasing order. In result we can just iterate over all prefix sums for each group and update global answer of current length with current sum if it has a positive value.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nint n, m;\nvector<int> s, r;\n\ninline bool read() {\n\tif(!(cin >> n >> m))\n\t\treturn false;\n\ts.assign(n, 0);\n\tr.assign(n, 0);\n\t\n\tfore(i, 0, n) {\n\t\tassert(cin >> s[i] >> r[i]);\n\t\ts[i]--;\n\t}\n\treturn true;\n}\n\nvector< vector<int> > subs;\n\ninline void solve() {\n\tsubs.assign(m + 1, vector<int>());\n\t\n\tfore(i, 0, n)\n\t\tsubs[s[i]].push_back(r[i]);\n\t\t\n\tfore(id, 0, sz(subs)) {\n\t\tsort(subs[id].begin(), subs[id].end());\n\t\treverse(subs[id].begin(), subs[id].end());\n\t}\n\t\n\tvector<int> mx(n + 5, 0);\n\tfore(id, 0, sz(subs)) {\n\t\tint curSum = 0;\n\t\tfore(i, 0, sz(subs[id])) {\n\t\t\tcurSum += subs[id][i];\n\t\t\tif(curSum < 0)\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tmx[i + 1] += curSum;\n\t\t}\n\t}\n\t\n\tcout << *max_element(mx.begin(), mx.end()) << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1082",
    "index": "D",
    "title": "Maximum Diameter Graph",
    "statement": "Graph constructive problems are back! This time the graph you are asked to build should match the following properties.\n\nThe graph is connected if and only if there exists a path between every pair of vertices.\n\nThe diameter (aka \"longest shortest path\") of a connected undirected graph is the maximum number of edges in the \\textbf{shortest} path between any pair of its vertices.\n\nThe degree of a vertex is the number of edges incident to it.\n\nGiven a sequence of $n$ integers $a_1, a_2, \\dots, a_n$ construct a \\textbf{connected undirected} graph of $n$ vertices such that:\n\n- the graph contains no self-loops and no multiple edges;\n- the degree $d_i$ of the $i$-th vertex doesn't exceed $a_i$ (i.e. $d_i \\le a_i$);\n- the diameter of the graph is maximum possible.\n\nOutput the resulting graph or report that no solution exists.",
    "tutorial": "Let's construct the graph the following manner. Take all the vertices with $a_i > 1$ and build a bamboo out of them. Surely, all but the end ones will have degree $2$, the diameter now is the number of vertices minus 1. One can show that building the graph any other way won't make the diameter greater. How should we distribute the other vertices? Two of them can be used to increase diameter. And all the others won't matter, they can be paired with any of the vertices with degrees to spare. If no loops are added then the diameter won't change - the path that was the longest won't become any shorter. All those facts imply that the graph should be a tree and the sum of $a_i$ should be at least $2n - 2$. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 1000 + 7;\n\nint n;\nint a[N];\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tint sum = 0;\n\tforn(i, n)\n\t\tsum += a[i];\n\t\n\tif (sum < 2 * n - 2){\n\t\tputs(\"NO\");\n\t\treturn 0;\n\t}\n\t\n\tvector<int> ones;\n\tforn(i, n) if (a[i] == 1){\n\t\ta[i] = 0;\n\t\tones.push_back(i);\n\t}\n\t\n\tint t = ones.size();\n\tint dm = (n - t) - 1 + min(2, t);\n\tprintf(\"YES %d\\n%d\\n\", dm, n - 1);\n\t\n\tint lst = -1;\n\tif (!ones.empty()){\n\t\tlst = ones.back();\n\t\tones.pop_back();\n\t}\n\t\n\tforn(i, n){\n\t\tif (a[i] > 1){\n\t\t\tif (lst != -1){\n\t\t\t\t--a[lst];\n\t\t\t\t--a[i];\n\t\t\t\tprintf(\"%d %d\\n\", lst + 1, i + 1);\n\t\t\t}\n\t\t\tlst = i;\n\t\t}\n\t}\n\t\n\tfor (int i = n - 1; i >= 0; --i){\n\t\twhile (!ones.empty() && a[i] > 0){\n\t\t\t--a[i];\n\t\t\tprintf(\"%d %d\\n\", i + 1, ones.back() + 1);\n\t\t\tones.pop_back();\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1082",
    "index": "E",
    "title": "Increasing Frequency",
    "statement": "You are given array $a$ of length $n$. You can choose one segment $[l, r]$ ($1 \\le l \\le r \\le n$) and integer value $k$ (positive, negative or even zero) and change $a_l, a_{l + 1}, \\dots, a_r$ by $k$ each (i.e. $a_i := a_i + k$ for each $l \\le i \\le r$).\n\nWhat is the maximum possible number of elements with value $c$ that can be obtained after one such operation?",
    "tutorial": "Let $cnt(l, r, x)$ be a number of occurrences of number $x$ in subsegment $[l, r]$. The given task is equivalent to choosing $[l, r]$ and value $d$ such that $ans = cnt(1, l - 1, c) + cnt(l, r, d) + cnt(r + 1, n, c)$ is maximum possible. But with some transformations $ans = cnt(1, n, c) + (cnt(l, r, d) - cnt(l, r, c))$ so we need to maximize $cnt(l, r, d) - cnt(l, r, c)$. Key observation is the next: if we fix some value $d$ then we can shrink each segment between consecutive occurrences of $d$ in one element with weight equal to $-cnt(l_i, r_i, c)$. Then we need just to find subsegment with maximal sum - the standard task which can be solved in $O(cnt(1, n, d))$. Finally, total complexity is $\\sum\\limits_{d}{O(cnt(1, n, d))} = O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nconst int INF = int(1e9);\n\nint n, c;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n >> c))\n\t\treturn false;\n\ta.assign(n, 0);\n\tfore(i, 0, n)\n\t\tassert(scanf(\"%d\", &a[i]) == 1);\n\treturn true;\n}\n\nvector<int> cntC;\n\nint getCnt(int l, int r) {\n\treturn cntC[r] - cntC[l];\n}\n\nvector< vector<int> > segs;\nvector<int> lst;\n\nint maxSegment(const vector<int> &s) {\n\tint mx = -INF;\n\t\n\tint bal = 0;\n\tfore(i, 0, sz(s)) {\n\t\tbal = max(0, bal + s[i]);\n\t\tmx = max(mx, bal);\n\t}\n\treturn mx;\n}\n\ninline void solve() {\n\tcntC.assign(n + 1, 0);\n\tfore(i, 0, n)\n\t\tcntC[i + 1] = cntC[i] + (a[i] == c);\n\t\n\tint cntDif = *max_element(a.begin(), a.end()) + 1;\n\tsegs.assign(cntDif, vector<int>());\n\tlst.assign(cntDif, -1);\n\t\n\tfore(i, 0, n) {\n\t\tsegs[a[i]].push_back(-getCnt(lst[a[i]] + 1, i));\n\t\tlst[a[i]] = i;\n\t\tsegs[a[i]].push_back(1);\n\t}\n\tfore(v, 0, cntDif)\n\t\tsegs[v].push_back(-getCnt(lst[v] + 1, n));\n\t\t\n\tint ans = 0;\n\tfore(v, 0, cntDif) {\n\t\tif(v == c) continue;\n\t\tans = max(ans, maxSegment(segs[v]));\n\t}\n\t\n\tcout << getCnt(0, n) + ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1082",
    "index": "F",
    "title": "Speed Dial",
    "statement": "Polycarp's phone book contains $n$ phone numbers, each of them is described by $s_i$ — the number itself and $m_i$ — the number of times Polycarp dials it in daily.\n\nPolycarp has just bought a brand new phone with an amazing speed dial feature! More precisely, $k$ buttons on it can have a number assigned to it (not necessary from the phone book). To enter some number Polycarp can press one of these $k$ buttons and then finish the number using usual digit buttons (entering a number with only digit buttons is also possible).\n\nSpeed dial button can only be used when no digits are entered. No button can have its number reassigned.\n\nWhat is the minimal total number of \\textbf{digit number presses} Polycarp can achieve after he assigns numbers to speed dial buttons and enters each of the numbers from his phone book the given number of times in an optimal way?",
    "tutorial": "The first thing to come to one's mind is dynamic programming on a trie. The most naive of the solutions take $O(S \\cdot n^2 \\cdot k^2)$, where $S$ is the total length of strings. I'll introduce the faster approach. Let $dp[x][rem][k]$ be the solution for subtree of the vertex $x$ with $rem$ buttons remaining and $k$ is the closest ancestor vertex with the button used in it. This dp will be recalced via the other dp. Let $dp2[x][rem][k][m]$ be the same thing as $dp[x][rem][k]$ but only $m$ first children of $x$ is taken into consideration and $x$ doesn't have a button in it. Give $z$ buttons to the current child, then update $dp2[x][rem][k][m]$ with $dp[m-th child of x][z][k][m]$ + $dp2[x][rem - z][k][m + 1]$. $dp[x][rem][k]$ will then have two options: $dp[x][rem - 1][x]$ for $x$ having button in it and $dp2[x][rem][k][0]$ for $x$ not having button in it. $dp[x][rem][k]$ has $O(1)$ transitions and $O(len^2 \\cdot p)$ states. $dp2[x][rem][k][m]$ has $O(k)$ total transitions and also $O(len^2 \\cdot p)$ states.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 500 + 7;\nconst int M = 11;\nconst int INF = 1e9;\n\nstruct node{\n\tint nxt[10];\n\tint cnt;\n\tnode(){\n\t\tmemset(nxt, -1, sizeof(nxt));\n\t\tcnt = 0;\n\t}\n};\n\nnode trie[N];\nint cnt;\nint h[N];\n\nvoid add(string s, int m){\n\tint cur = 0;\n\tforn(i, s.size()){\n\t\tint c = s[i] - '0';\n\t\tif (trie[cur].nxt[c] == -1){\n\t\t\ttrie[cur].nxt[c] = cnt;\n\t\t\th[cnt] = h[cur] + 1;\n\t\t\t++cnt;\n\t\t}\n\t\tcur = trie[cur].nxt[c];\n\t}\n\ttrie[cur].cnt += m;\n}\n\nint n, k;\n\nint dp[N][M][N];\nint dp2[N][M][N][M];\n\nint calc(int x, int rem, int k){\n\tif (dp[x][rem][k] != -1)\n\t\treturn dp[x][rem][k];\n\t\n\tvector<int> ch;\n\tforn(i, 10) if (trie[x].nxt[i] != -1)\n\t\tch.push_back(trie[x].nxt[i]);\n\t\n\tdp[x][rem][k] = INF;\n\tif (rem > 0)\n\t\tdp[x][rem][k] = min(dp[x][rem][k], calc(x, rem - 1, x));\n\t\n\tdp2[x][rem][k][ch.size()] = 0;\n\tfor (int i = int(ch.size()) - 1; i >= 0; --i) forn(z, rem + 1)\n\t\tdp2[x][rem][k][i] = min(dp2[x][rem][k][i], calc(ch[i], z, k) + dp2[x][rem - z][k][i + 1]);\n\t\n\tdp[x][rem][k] = min(dp[x][rem][k], dp2[x][rem][k][0] + (h[x] - h[k]) * trie[x].cnt);\n\t\n\treturn dp[x][rem][k];\n}\n\nint main() {\n\ttrie[0] = node();\n\tcnt = 1;\n\t\n\tcin >> n >> k;\n\tforn(i, n){\n\t\tstring s;\n\t\tint m;\n\t\tcin >> s >> m;\n\t\tadd(s, m);\n\t}\n\t\n\tmemset(dp, -1, sizeof(dp));\n\t\n\tforn(i, N) forn(j, M) forn(l, N) forn(t, M)\n\t\tdp2[i][j][l][t] = INF;\n\t\n\tint ans = calc(0, k, 0);\n\t\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "dp",
      "strings",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1082",
    "index": "G",
    "title": "Petya and Graph",
    "statement": "Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of $n$ vertices and $m$ edges.\n\nThe weight of the $i$-th vertex is $a_i$.\n\nThe weight of the $i$-th edge is $w_i$.\n\nA subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.\n\nThe weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. \\textbf{The given graph does not contain loops and multiple edges}.",
    "tutorial": "This problem can be reduced to one of well-known flow problems: \"Projects and Instruments\". In this problem, we have a set of projects we can do, each with its cost, and a set of instruments (each also having some cost). Each project depends on some instruments, and each instrument can be used any number of times. We have to choose a subset of projects and a subset of instruments so that if a project is chosen, all instruments that this project depends on are also chosen, and we have to maximize the difference between the sum of costs of chosen projects and the sum of costs of chosen instruments. The problem about projects and instruments can be solved with the following flow network: for each project, create a vertex and add a directed edge from the source to this vertex with capacity equal to the cost of this project; for each instrument, create a vertex and add a directed edge from this vertex to the sink with capacity equal to the cost of this instrument; for each project, create edges with infinite capacity from the vertex denoting this project to all vertices denoting the required instruments for this project. Let's analyze an $(S, T)$ cut between the source and the sink in this vertex, and construct some answer based on this cut as follows: if a project-vertex belongs to $S$, then we take this project; if an instrument-vertex belongs to $S$, then we take this instrument; all other projects and instruments are discarded. If an edge between some project and some instrument is cut, then it means that the answer is incorrect (we try to take a project requiring some instrument we don't take), and the cut value is infinite. Otherwise, the value of the cut is equal to the total cost of taken instruments and discarded projects, and we need to minimize it. So the minimum cut in this network denotes the best answer. Reducing the given problem to this problem is easy: edges of the given graph are \"projects\", vertices of the given graph are \"instruments\". Regarding implementation, any flow algorithm using capacity scaling should be sufficient. It seems that Dinic also passes, even though its complexity is $O(n^2 m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\nconst int N = 2009;\nconst int INF = int(1e9) + 777;\n\nstruct edge{\n\tint to, f, c;\n\tedge () {}\n\tedge (int to, int f, int c) : to(to), f(f), c(c) {}\n};\n\nint n, m;\nint s, t;\nvector<edge> edges;\nvector <int> g[N];\nint u[N], cu;\n\nvoid addEdge(int v, int to, int cap){\n\n\tg[v].push_back(edges.size());\n\tedges.push_back(edge(to, 0, cap));\n\n\tg[to].push_back(edges.size());\n\tedges.push_back(edge(v, 0, 0));\n}\n\nint dfs(int v, int need){\n\tif(v == t) return need;\n\tu[v] = cu;\n\tfor(auto to : g[v]){\n\t\tedge &e = edges[to];\n\t\tif(u[e.to] != cu && e.c - e.f >= need){\n\t\t\tint add = dfs(e.to, need);\n\t\t\tif(add > 0){\n\t\t\t\tedges[to].f += add;\n\t\t\t\tedges[to ^ 1].f -= add;\n\t\t\t\treturn add;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\nli enlarge(int k){\n\tli res = 0;\n\twhile(true){\n\t\t++cu;\n\t\tint add = dfs(s, k);\n\t\tres += add;\n\t\tif(add == 0) break;\n\t}\n\treturn res;\n}\n\nli maxFlow(){\n\tli flow = 0;\n\tfor(int k = (1 << 29); k > 0; k >>= 1){\n\t\tflow += enlarge(k);\n\t}\n\treturn flow;\n}\n\nint main() {\n\t//freopen(\"input.txt\", \"r\", stdin);\n\tint nn, mm;\n\tcin >> nn >> mm;\n\tn = nn + mm + 5;\n\tm = nn + mm + mm + mm + 5;\n\ts = n - 1, t = n - 2;\n\t\n\tfor(int i = 0; i < nn; ++i){\n\t\tint a;\n\t\tcin >> a;\n\t\taddEdge(i + mm, t, a);\n\t}\n\n\tli sum = 0;\n\tfor(int i = 0; i < mm; ++i){\n\t\tint u, v, w;\n\t\tcin >> u >> v >> w;\n\t\t--u, --v;\n\t\tsum += w;\n\t\t\n\t\taddEdge(s, i, w);\n\t\taddEdge(i, u + mm, INF);\n\t\taddEdge(i, v + mm, INF);\n\t}\n\t\n\tli fl = maxFlow();\n\tcout << sum - fl << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1083",
    "index": "A",
    "title": "The Fair Nut and the Best Path",
    "statement": "The Fair Nut is going to travel to the Tree Country, in which there are $n$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $u$ and go by a simple path to city $v$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.\n\nA filling station is located in every city. Because of strange law, Nut can buy only $w_i$ liters of gasoline in the $i$-th city. We can assume, that he has \\textbf{infinite money}. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in \\textbf{every} visited city, even in \\textbf{the first} and \\textbf{the last}.\n\nHe also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.",
    "tutorial": "Let's write on edge with length $l$ number $-l$. Let sum on the path be sum of amounts of gasoline, which can be bought in cities on this path plus sum of the numbers, which were written on its edges. If we don't run out of gasoline on some path, sum on it will be equal to amount of gasoline at the end of way. If we run out of gasoline on a path, we can start from the next city after the road, where it happened, and sum on the path won't decrease. So, there is a path with maximal sum, where we don't run out of gasoline. This sum is answer to the problem. How to find it? Let $dp_{i}$ is maximal sum on vertical way, which starts in vertex $i$. It is not difficult to calculate $dp_{i}$, using $dp$ values for children of vertex $i$. Every way can be divided to two vertical ways, so we can calculate answer by turning over $i$, which is the highest vertex of a path, and taking the two biggest vertical ways, which starts from vertex $i$.",
    "tags": [
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1083",
    "index": "B",
    "title": "The Fair Nut and Strings",
    "statement": "Recently, the Fair Nut has written $k$ strings of length $n$, consisting of letters \"a\" and \"b\". He calculated $c$ — the number of strings that are prefixes of at least one of the written strings. \\textbf{Every string was counted only one time}.\n\nThen, he lost his sheet with strings. He remembers that all written strings were lexicographically \\textbf{not smaller} than string $s$ and \\textbf{not bigger} than string $t$. He is interested: what is the maximum value of $c$ that he could get.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "If $s$ and $t$ are equal, answer is $n$. Let's cut common prefix of $s$ and $t$, and increase answer to its length. Now $s$ starts from \"a\" and $t$ starts from \"b\". Let $m$ is new lengths of $s$ and $t$. If string $s$ weren't written, we can change the lexicographically smallest string to $s$, and $c$ will not decrease. We can do the same thing with $t$. Now $s$ and $t$ are in answer. We can increase answer by $2 \\cdot m$, decrease $k$ by 2 and don't count strings, which are prefixes of $s$ and $t$, while calculating $c$. Let's divide strings in answer into groups - two strings are in one group if and only if their first characters are equal and their largest common prefixes with $s$ or $t$ (it depends on the first character) are equal. Let length of group be $m - lcp$, where $lcp$ - length of this common prefix. $c$ is equal to the number of vertexes in trie on written strings. If we have fixed $l$ - number of strings, which will belong to some group, we have to maximize size of set of vertexes, which is union of $l$ ways in full binary tree with height $h$, equals to length of group. It can be proved by induction, that the first way increases size of set by $h$, the second by $h - 1$, next 2 ways by $h - 2$, next 4 ways by $h - 3$, etc. We can create array $p$, where $p_{i}$ - how many ways increase answer by $h - i$. Note that these values are additive - if we have two independent binary trees and want to distribute some number of ways between them, we can sum their arrays (and it is how prove the previous fact). We have $O(n)$ independent groups, and we want to sum their arrays fast. Every binary tree increases values on suffix by $[1, 1, 2, 4, ...]$. Let's forget about the first $1$ and add it in the end. Then, put $1$ to the second position in suffix, and add $2 \\cdot a_{i}$ to $a_{i + 1}$ for $1 \\le i \\le n - 1$ in increasing order, where $a$ - array, which we want to get. Note that values in this array could be very big, but if we change values, bigger than $k$, to $k$, answer will not change (because there are only $k$ ways). To calculate answer, let's take the prefix with sum $k$ (if there are no such prefix, we take the first prefix with sum, which is bigger than $k$ and decrease last element), fill other elements with $0$. Answer will be equal sum $a[i] \\cdot i$ for $1 \\le i \\le m$.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1083",
    "index": "C",
    "title": "Max Mex",
    "statement": "Once Grisha found a tree (connected graph without cycles) with a root in node $1$.\n\nBut this tree was not just a tree. A permutation $p$ of integers from $0$ to $n - 1$ is written in nodes, a number $p_i$ is written in node $i$.\n\nAs Grisha likes to invent some strange and interesting problems for himself, but not always can solve them, you need to help him deal with two types of queries on this tree.\n\nLet's define a function $MEX(S)$, where $S$ is a set of non-negative integers, as a smallest non-negative integer that is not included in this set.\n\nLet $l$ be a simple path in this tree. So let's define indices of nodes which lie on $l$ as $u_1$, $u_2$, $\\ldots$, $u_k$.\n\nDefine $V(l)$ as a set {$p_{u_1}$, $p_{u_2}$, $\\ldots$ , $p_{u_k}$}.\n\nThen queries are:\n\n- For two nodes $i$ and $j$, swap $p_i$ and $p_j$.\n- Find the maximum value of $MEX(V(l))$ in all possible $l$.",
    "tutorial": "First let's redefine the MEX query more clearly - you need to find what is the maximum $a$, such that all nodes with permutation values up to $a$ lie on the same path. For that you can use just a simple segment tree - in a node of a segment tree you need to store is it true that all nodes with permutation values between $l$ and $r$ lie on the same path and if so, what are the endpoints of this path. You can merge these paths using precalculated LCA and in and out times. For example you can just check all pairs of nodes from the endpoints of paths as candidates for the endpoints of a new path. So for the MEX query you need to traverse this segment tree, and for the change query you just update paths in $O$($log$ $n$) nodes of your segment tree. $O$($n$ $log$ $n$)",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1083",
    "index": "D",
    "title": "The Fair Nut's getting crazy",
    "statement": "The Fair Nut has found an array $a$ of $n$ integers. We call subarray $l \\ldots r$ a sequence of consecutive elements of an array with indexes from $l$ to $r$, i.e. $a_l, a_{l+1}, a_{l+2}, \\ldots, a_{r-1}, a_{r}$.\n\nNo one knows the reason, but he calls a pair of subsegments good if and only if the following conditions are satisfied:\n\n- These subsegments should not be nested. That is, each of the subsegments should contain an element (as an index) that does not belong to another subsegment.\n- Subsegments intersect and each element that belongs to the intersection belongs each of segments only once.\n\nFor example $a=[1, 2, 3, 5, 5]$. Pairs $(1 \\ldots 3; 2 \\ldots 5)$ and $(1 \\ldots 2; 2 \\ldots 3)$) — are good, but $(1 \\dots 3; 2 \\ldots 3)$ and $(3 \\ldots 4; 4 \\ldots 5)$ — are not (subsegment $1 \\ldots 3$ contains subsegment $2 \\ldots 3$, integer $5$ belongs both segments, but occurs twice in subsegment $4 \\ldots 5$).\n\nHelp the Fair Nut to find out the number of pairs of good subsegments! The answer can be rather big so print it modulo $10^9+7$.",
    "tutorial": "Consider O($N^2$) solution: Fix intersection of this segments $L \\dots R$. We will call right barrier those integer $Right$, that right border of right segment can be from $R \\dots Right$. Also Left barrier is integer, that left border of left segment can be from $Left \\dots L$. If we precalculate for each element the furthest left and right elements equal to our ($go_l[i]; go_r[i]$): $Right = MIN(go_r[i])-1$ and $Left = MAX(go_l[i])+1$. Add to answer ($L-Left+1$)*($Right-R+1$) for all segment intersections. Faster solution: Let's go i=$1 \\dots.N$ and keep two arrays Left and Right in any data structure, $Left_j$=Left barrier for segment $j \\dots i$, $Right_j$=Right barrier for segment $j \\dots i$. We need to add sum of ($j-Left_j+1$)*($Right_j-i+1$) for all $j$ from $1$ to $i$. Let's do it using clever Segment Tree.Imagine we are in position i and we want to recalculate arrays Left and Right after increasing $i$ by $1$. Element $A_i$ has furthest left equal $A_l$. We need to do $max=l$ on prefix $1 \\dotsi$ in array Left. With Right everything is similar. We can note, that Left and Right are monotonous, so we can just do equation on some segment. Now we want to update the answer. We are in position i, amount of good pairs of segments are ($j- Left_j+1$)*($Right_j-i+1$)=$-Left_j$*$Right_j$-($i+1$)*($j+1$)+$Right_j$*($j+1$)-$Left_j$*($i+1$). $Right_j$*($j+1$) we can keep in separate Segment Tree. Calculating -($i+1$)*($j+1$)-$Left_j$*($i+1$) is easy too. To get $-Left_j$*$Right_j$ we need segment tree, which can do update on first array segment, update on second array segment, get sum of pair products. It can be done keeping sum of Left's, sum of Right's, and sum of $Left$ * $Right$, and some modificators. We can do it using push's. To see details you can see the code. Imagine we are in position i and we want to recalculate arrays Left and Right after increasing $i$ by $1$. Element $A_i$ has furthest left equal $A_l$. We need to do $max=l$ on prefix $1 \\dotsi$ in array Left. With Right everything is similar. We can note, that Left and Right are monotonous, so we can just do equation on some segment. Now we want to update the answer. We are in position i, amount of good pairs of segments are ($j- Left_j+1$)*($Right_j-i+1$)=$-Left_j$*$Right_j$-($i+1$)*($j+1$)+$Right_j$*($j+1$)-$Left_j$*($i+1$). $Right_j$*($j+1$) we can keep in separate Segment Tree. Calculating -($i+1$)*($j+1$)-$Left_j$*($i+1$) is easy too. To get $-Left_j$*$Right_j$ we need segment tree, which can do update on first array segment, update on second array segment, get sum of pair products. It can be done keeping sum of Left's, sum of Right's, and sum of $Left$ * $Right$, and some modificators. We can do it using push's. To see details you can see the code.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1083",
    "index": "E",
    "title": "The Fair Nut and Rectangles",
    "statement": "The Fair Nut got stacked in planar world. He should solve this task to get out.\n\nYou are given $n$ rectangles with vertexes in $(0, 0)$, $(x_i, 0)$, $(x_i, y_i)$, $(0, y_i)$. For each rectangle, you are also given a number $a_i$. Choose some of them that the area of union minus sum of $a_i$ of the chosen ones is maximum.\n\nIt is guaranteed that there are no nested rectangles.\n\nNut has no idea how to find the answer, so he asked for your help.",
    "tutorial": "Let's order rectangles by $x_i$, so $x_1, ..., x_n$ will be increasing. If the $x_1, ..., x_n$ is increasing, $y_1, ..., y_n$ is decreasing, because there are no nested rectangles. Then lets define $dp_i$ as the maximum value, which can be acheived by choosing some subset of first $i$ rectangles which contains the $i$-th rectangle. It can be calculated by $dp_i = \\max\\limits_{1 \\leq j < i} dp_j + x_i \\cdot y_i - x_j \\cdot y_i$, where $j$ is the previous chosen rectangle (we subtract $x_j \\cdot y_i$ because it is common square of the subset for $dp_j$ and $i$-th rectangle). This formula can be optimized using convex hull trick and calculated in $O(n log n)$ or in $O(n)$ if rectangles are already sorted.",
    "tags": [
      "data structures",
      "dp",
      "geometry"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1083",
    "index": "F",
    "title": "The Fair Nut and Amusing Xor",
    "statement": "The Fair Nut has two arrays $a$ and $b$, consisting of $n$ numbers. He found them so long ago that no one knows when they came to him.\n\nThe Fair Nut often changes numbers in his arrays. He also is interested in how similar $a$ and $b$ are after every modification.\n\nLet's denote similarity of two arrays as the minimum number of operations to apply to make arrays equal (every operation can be applied for both arrays). If it is impossible, similarity will be equal $-1$.\n\nPer one operation you can choose a subarray with length $k$ ($k$ is fixed), and change every element $a_i$, which belongs to the chosen subarray, to $a_i \\oplus x$ ($x$ can be chosen), where $\\oplus$ denotes the bitwise XOR operation.\n\nNut has already calculated the similarity of the arrays after every modification. Can you do it?\n\nNote that you just need to calculate those values, that is you do not need to apply any operations.",
    "tutorial": "Let $c_{i}=a_{i} \\oplus b_{i}$. Let's notice that if there is list of operations to both arrays, which makes them equal, applying these operations to $a$ makes it equal to $b$. Because of this, applying them to $c$ makes all elements equal to $0$. Now we are processing modifications of $c$. Let's make array $d$ with length $n + 1$, consisting of $c_{0}$, $n - 1$ values $c_{i} \\oplus c_{i + 1}$ for $1 \\le i \\le n - 1$, and $c_{n - 1}$. The only result in $d$ of applying operation to $c$ is changing two elements $d_{i}$, $d_{i + k}$ to $d_{i} \\oplus x$, $d_{i + k} \\oplus x$. Let's divide array $d$ into $k$ groups. Elements with the same indexes by modulo $k$ will be in one group. Tasks for different groups are independent and matches up to the initial problem for $k = 2$. Now we are solving problem for $k = 2$. Let's calculate prefix xors. Operation with $k = 2$ changes only one prefix xor (and it is not the last prefix xor). So, if the last prefix xor isn't equal to 0, the answer is $-1$. Otherwise, minimal number of operations to apply is number of prefix xors, which are not equal to $0$. Let's see what modification does with prefix xors. It changes all elements from $a$ to $a \\oplus x$ on some suffix. To recalculate number of zeros fastly, let's divide array to blocks with length $O(\\sqrt n)$ and keep in every block count of every element and modifier. To process modification, let's update modifier for all blocks, which are covered by suffix and recalculate all counts for block, which is partly covered by it. Number of zeros in a block is count of elements, which are equal to modifier. We also have to store the last element of array, which is equal to xor of all $x$ from modifications. Note, that this task is solved for each of $k$ groups, so we have to store sum of counts of non-zero prefix xors, and number of groups, where the last prefix xor is not zero.",
    "tags": [
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1084",
    "index": "A",
    "title": "The Fair Nut and Elevator",
    "statement": "The Fair Nut lives in $n$ story house. $a_i$ people live on the $i$-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening.\n\nIt was decided that elevator, when it is not used, will stay on the $x$-th floor, but $x$ hasn't been chosen yet. When a person needs to get from floor $a$ to floor $b$, elevator follows the simple algorithm:\n\n- Moves from the $x$-th floor (initially it stays on the $x$-th floor) to the $a$-th and takes the passenger.\n- Moves from the $a$-th floor to the $b$-th floor and lets out the passenger (if $a$ equals $b$, elevator just opens and closes the doors, \\textbf{but still} comes to the floor from the $x$-th floor).\n- Moves from the $b$-th floor back to the $x$-th.\n\nThe elevator never transposes more than one person and always goes back to the floor $x$ before transposing a next passenger. The elevator spends one unit of electricity to move between neighboring floors. So moving from the $a$-th floor to the $b$-th floor requires $|a - b|$ units of electricity.Your task is to help Nut to find the minimum number of electricity units, that it would be enough for one day, by choosing an optimal the $x$-th floor. Don't forget than elevator initially stays on the $x$-th floor.",
    "tutorial": "For each request of passenger who lives on the $p$-th floor to get to the first floor, we need $2 \\cdot (max(p, x) - 1)$ energy, because in this case lift moves from the $x$-th floor to the $p$-th, then from the $p$-th to the first, then from the first to the $x$-th. So sum is $|p - x| + |x - 1| + |p - 1|$ and it equals $2 \\cdot (max(p, x) - 1)$. if request is to get from the first to the $p$-th floor, number of energy is the same. So the optimal answer can be acheived be choosing the first floor as the $x$-th.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1084",
    "index": "B",
    "title": "Kvass and the Fair Nut",
    "statement": "The Fair Nut likes kvass very much. On his birthday parents presented him $n$ kegs of kvass. There are $v_i$ liters of kvass in the $i$-th keg. Each keg has a lever. You can pour your glass by \\textbf{exactly} $1$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $s$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.\n\nHelp him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $s$ liters of kvass.",
    "tutorial": "If $\\sum a_i$ $\\le s$ - the answer is $-1$ Otherwise, let $v$ - minimal volume from these kegs. The answer is $\\le v$. For all i: $s$-=$(a_i - v)$. Now all elements equal to $v$. if $s$ become $\\le 0$ the answer is $v$. Else the answer is $\\lfloor v - (s + n - 1) / n\\rfloor$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1084",
    "index": "C",
    "title": "The Fair Nut and String",
    "statement": "The Fair Nut found a string $s$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $p_1, p_2, \\ldots, p_k$, such that:\n\n- For each $i$ ($1 \\leq i \\leq k$), $s_{p_i} =$ 'a'.\n- For each $i$ ($1 \\leq i < k$), there is such $j$ that $p_i < j < p_{i + 1}$ and $s_j =$ 'b'.\n\nThe Nut is upset because he doesn't know how to find the number. Help him.\n\nThis number should be calculated modulo $10^9 + 7$.",
    "tutorial": "Firstly, let's erase all symbols different from 'a' and 'b'. Then let's split string on blocks of consecutive symbols 'a'. Now we need to multiply all sizes of blocks increased by 1. It is an answer which also includes one empty subsequence, so we should just decrease it by one.",
    "tags": [
      "combinatorics",
      "dp",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1085",
    "index": "A",
    "title": "Right-Left Cipher",
    "statement": "Polycarp loves ciphers. He has invented his own cipher called Right-Left.\n\nRight-Left cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \\dots s_{n}$ Polycarp uses the following algorithm:\n\n- he writes down $s_1$,\n- he appends the current word with $s_2$ (i.e. writes down $s_2$ to the right of the current result),\n- he prepends the current word with $s_3$ (i.e. writes down $s_3$ to the left of the current result),\n- he appends the current word with $s_4$ (i.e. writes down $s_4$ to the right of the current result),\n- he prepends the current word with $s_5$ (i.e. writes down $s_5$ to the left of the current result),\n- and so on for each position until the end of $s$.\n\nFor example, if $s$=\"techno\" the process is: \"t\" $\\to$ \"te\" $\\to$ \"cte\" $\\to$ \"cteh\" $\\to$ \"ncteh\" $\\to$ \"ncteho\". So the encrypted $s$=\"techno\" is \"ncteho\".\n\nGiven string $t$ — the result of encryption of some string $s$. Your task is to decrypt it, i.e. find the string $s$.",
    "tutorial": "You can simulate the process, maintaining the indices of characters of the initial string. So, like this you can find the value of character of the initial string.",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1085",
    "index": "B",
    "title": "Div Times Mod",
    "statement": "Vasya likes to solve equations. Today he wants to solve $(x~\\mathrm{div}~k) \\cdot (x \\bmod k) = n$, where $\\mathrm{div}$ and $\\mathrm{mod}$ stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, $k$ and $n$ are positive integer parameters, and $x$ is a positive integer unknown. If there are several solutions, Vasya wants to find the smallest possible $x$. Can you help him?",
    "tutorial": "$n$ has to be divisible by $p = x \\bmod k$, which in turn is less than $k$. We can try all options of $p$ (in $O(p)$ time), and for suitable options restore $x = p \\cdot \\frac{n - p}{k}$. Choose the smallest possible $x$. Note that $p = 1$ always divides $n$, hence at least one option will always be available.",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1085",
    "index": "C",
    "title": "Connect Three",
    "statement": "The Squareland national forest is divided into equal $1 \\times 1$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $(x, y)$ of its south-west corner.\n\nThree friends, Alice, Bob, and Charlie are going to buy three distinct plots of land $A, B, C$ in the forest. Initially, all plots in the forest (including the plots $A, B, C$) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots $A, B, C$ from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side.\n\n\\begin{center}\n{\\small For example, $A=(0,0)$, $B=(1,1)$, $C=(2,2)$. The minimal number of plots to be cleared is $5$. One of the ways to do it is shown with the gray color.}\n\\end{center}\n\nOf course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.",
    "tutorial": "The smallest possible number of plots required to connect all three plots is at least $\\Delta_x + \\Delta_y + 1$, where $\\Delta_x = x_{max} - x_{min}$ and $\\Delta_y = y_{max} - y_{min}$ (here $x_{min}$, $x_{maxn}$, $y_{min}$, $y_{max}$ are extreme coordinate values among the three given plots). It now suffices to find any suitable collection of plots of this size. Let $x_m$ and $y_m$ be the median values of $(x_A, x_B, x_C)$ and $(y_A, y_B, y_C)$. For each of the plots $A$, $B$, $C$ connect it with the plot $(x_m, y_m)$ with any shortest path (if one of $A$, $B$, $C$ coincides with $(x_m, y_m)$, just do nothing). One can check that the resulting collection has size exactly $\\Delta_x + \\Delta_y + 1$, and it clearly connects $A$, $B$ and $C$ together. The above solution has complexity $O(C)$, where $C$ is the largest coordinate value. Given that $C$ is quite small, one could go with slower solutions, for instance, instead of $(x_m, y_m)$ try all $C^2$ plots as the connecting plot.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1085",
    "index": "D",
    "title": "Minimum Diameter Tree",
    "statement": "You are given a tree (an undirected connected graph without cycles) and an integer $s$.\n\nVanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $s$. At the same time, he wants to make the diameter of the tree as small as possible.\n\nLet's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.\n\nFind the minimum possible diameter that Vanya can get.",
    "tutorial": "Let's denote the number of leaves in this tree for $l$. Let's prove that the answer is $\\frac {2s} {l}$. To construct an example with such diameter, let's put the weight $\\frac s l$ to the edge adjacent to the leaf, and let's put the weight $0$ to other edges. It is easy to see that the diameter of this tree is $\\frac {2s} {l}$. To prove that it is the minimal possible diameter we denote leaf numbers for $a_1, \\ldots, a_l$. For $dist_{{x}{y}}$ we denote the sum of weights of edges lying on the path between vertices $x$ and $y$. Then $\\frac {l(l-1)} 2 \\cdot \\max\\limits_{1 \\leq i < j \\leq l}dist_{{a_i}{a_j}} \\geq \\sum\\limits_{1 \\leq i < j \\leq l}dist_{{a_i}{a_j}}$. Note that the contribution to the sum on the right side of the inequality of the weight of each edge will be at least $l-1$, because any edge lies on $\\geq l-1$ paths between the leaves of the tree. So, $\\sum\\limits_{1 \\leq i < j \\leq l}dist_{{a_i}{a_j}} \\geq (l-1) \\cdot \\sum\\limits_{e \\in E} weight_e = (l-1) \\cdot s$. So, $\\frac {l(l-1)} 2 \\cdot \\max\\limits_{1 \\leq i < j \\leq l}dist_{{a_i}{a_j}} \\geq (l-1) \\cdot s$ and we get that $\\max\\limits_{1 \\leq i < j \\leq l}dist_{{a_i}{a_j}} \\geq \\frac {2s} l$. So, to solve this problem you need to calculate the number of leaves in the tree. This can be done in linear time by counting all degrees of vertices. Time comlexity: $O(n)$.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1085",
    "index": "E",
    "title": "Vasya and Templates",
    "statement": "Vasya owns three strings $s$ , $a$ and $b$, each of them consists only of first $k$ Latin letters.\n\nLet a template be such a string of length $k$ that each of the first $k$ Latin letters appears in it exactly once (thus there are $k!$ distinct templates). Application of template $p$ to the string $s$ is the replacement of each character in string $s$ with $p_i$, $i$ is the index of this letter in the alphabet. For example, applying template \"bdca\" to a string \"aabccd\" yields string \"bbdcca\".\n\nVasya wants to know if there exists such a template which yields a string lexicographically greater than or equal to string $a$ and lexicographically less than or equal to string $b$ after applying it to $s$.\n\nIf there exist multiple suitable templates, print any of them.\n\nString $a$ is lexicographically less than string $b$ if there is some $i$ ($1 \\le i \\le n$) that $a_i < b_i$ and for any $j$ ($1 \\le j < i$) $a_j = b_j$.\n\nYou are required to answer $t$ testcases \\textbf{independently}.",
    "tutorial": "Let's implement the following strategy: obtain the minimal string which is greater than or equal to $a$ to correspond to at least one template. If there exists such a string and it is less than or equal to $b$ then the answer exists, otherwise it's not. Let's iterate over the length of prefix of the answer $s'$, which equals the prefix of $a$. For some fixed length we can restore some part of the template. For example, let prefix of $s$ be \"abd\" and prefix of $a$ be \"dba\", template will then look like \"db?a\". Also sometimes prefix can have no answer. Now we want to expand the prefix with some character $c$ at position $i$. If that character had appeared already, then the substitute is known. Also if the substitute is less than $a_i$ then the resulting string will be less than $a$, so it will be incorrect. If it equals $a_i$ then put it and proceed to position $i+1$. And if it's greater then the resulting string will be greater than $a$, so the rest of the string can be filled greedily, minimizing the resulting string $s'$. If character $c$ hadn't appeared previously, then let's try all possible character to substitute it (let it be some character $c'$). That character should be greater than or equal to $a_i$ and it shouldn't be already taken. If $c'$ is greater then $a_i$, then the rest of the string can be filled greedily, minimizing the resulting string $s'$. Otherwise it's $a_i$ and we proceed to position $i+1$. It's easy to show that the greedy filling will be performed no more than $k$ times, thus the solution will work in $O(nk)$.",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1085",
    "index": "F",
    "title": "Rock-Paper-Scissors Champion",
    "statement": "$n$ players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: \"paper\" beats \"rock\", \"rock\" beats \"scissors\", \"scissors\" beat \"paper\", and two equal shapes result in a draw.\n\nAt the start of the tournament all players will stand in a row, with their numbers increasing from $1$ for the leftmost player, to $n$ for the rightmost player. Each player has a pre-chosen shape that they will use in every game throughout the tournament. Here's how the tournament is conducted:\n\n- If there is only one player left, he is declared the champion.\n- Otherwise, two adjacent players in the row are chosen arbitrarily, and they play the next match. The losing player is eliminated from the tournament and leaves his place in the row (with his former neighbours becoming adjacent). If the game is a draw, the losing player is determined by a coin toss.\n\nThe organizers are informed about all players' favoured shapes. They wish to find out the total number of players who have a chance of becoming the tournament champion (that is, there is a suitable way to choose the order of the games and manipulate the coin tosses). However, some players are still optimizing their strategy, and can inform the organizers about their new shapes. Can you find the number of possible champions after each such request?",
    "tutorial": "First, let's determine which players can win in a given configuration. If all players have the same shape, then everyone can win. If there are only two kinds of shapes, then one shape always loses, and everyone with the other shape can win. Let's now assume there are all three shapes present. If a player $i$ can win, then they have to independently eliminate everyone to either side. It suffices to determine if $i$ can win everyone to their left (the other side can be treated symmetrically). Suppose that the player $i$ has the shape R (all the other cases are similar). We will show that $i$ can not eliminate everyone to the left if and only if two conditions hold: there is no S to the left of $i$; there is at least one P to the left of $i$. Indeed, if both of these are true, there is nothing stopping a P from eliminating $i$. Otherwise, if there are no P to the left of $i$, he can potentially win everyone there. Finally, suppose that there is an S to the left of $i$. Here's how $i$ can eliminate everyone to the left. First, eliminate all P's as follows: locate the closest pair of P and S, bring them together by eliminating all R's in between with the P, then eliminate the P. When we've eiliminated all P's this way, we are left with the previous case (no P's). Now, how to deal with modifications? Assume that there are currently all three shapes present (otherwise we can easily find the answer as described at the start). How many R's can not win (similar for P's and S's)? According to our criterion, all R's losing because they can not eliminate their respective left-hand sides are located between $P_0$ and $S_0$, where $P_0$ and $S_0$ are positions of the first P and S (that is, when $P_0 < S_0$, otherwise there are no R's losing this way). A similar condition applies to the R's losing because of the right-hand side. Now we simply count the number of R's in these ranges and subtract them from the total. Note that we can never subtract an R twice since there is at one S on one of its sides. It now suffices to use any data structure that supports range summing and finding extreme values in a set, with modifications. For the range summing we may use a Fenwick tree (BIT) or a segment tree, and for extreme values an std::set will suffice. All operations we need take $O(\\log n)$ time, hence each modification and answer takes $O(\\log n)$ time.",
    "tags": [],
    "rating": 2500
  },
  {
    "contest_id": "1085",
    "index": "G",
    "title": "Beautiful Matrix",
    "statement": "Petya collects beautiful matrix.\n\nA matrix of size $n \\times n$ is beautiful if:\n\n- All elements of the matrix are integers between $1$ and $n$;\n- For every row of the matrix, all elements of this row are different;\n- For every pair of vertically adjacent elements, these elements are different.\n\nToday Petya bought a beautiful matrix $a$ of size $n \\times n$, and now he wants to determine its rarity.\n\nThe rarity of the matrix is its index in the list of beautiful matrices of size $n \\times n$, sorted in lexicographical order. Matrix comparison is done row by row. (The index of lexicographically smallest matrix is \\textbf{zero}).\n\nSince the number of beautiful matrices may be huge, Petya wants you to calculate the rarity of the matrix $a$ modulo $998\\,244\\,353$.",
    "tutorial": "Calculate the following dp: $dp[n]$ - the number of permutations of length $n$ of elements $1 \\dots n$ such that $p_i \\ne i$ for every $i = 1 \\dots n$ $dp[n] = (n - 1) \\cdot (dp[n - 1] + dp[n - 2])$; Calculate the following dp: $dp2[n][k]$ - the number of permutations of length $n$ of elements $1, 2, \\dots, n, n + 1, n + 2, \\dots, 2n - k$ such that $p_i \\ne i$ $dp2[n][0] = n!$ $dp2[n][k] = dp2[n][k - 1] - dp2[n - 1][k - 1]$; We can follow the usual process of recovering the lexicographic index. Iterate over the element to put in the current position and add the number of ways to complete the matrix to the answer. How to calculate the number of ways to complete the matrix? The current row can be completed the following way: Look at the elements of the previous row (the same suffix as the one we want to complete), renumerate its elements into $1 \\dots t$, where $t$ is the length of suffix. The current row now incudes some elements which appeared in the suffix of the previous row and some which don't. Let's renumerate those that appeared correspondingly. Let there be $k$ of such elements. Then the number of ways to complete the row is $dp2[t][k]$. The other rows can be completed the following way: For any row the previous one can be renumerated into permutation of form $1 \\dots n$, thus the number of ways to choose the current row is $dp[n]$. The only thing left is to raise $dp[n]$ to the power of the number of rows to be completed. That solution is $O(N^3)$ as we were looking into all the candidates for the current position. However, these candidates can be split up into two groups: those that change the value of $k$ by 1 and those that leave it as is. Thus a single cell can be processed in $O(\\log N)$ with a couple of data structures.",
    "tags": [
      "combinatorics",
      "data structures",
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1086",
    "index": "F",
    "title": "Forest Fires",
    "statement": "Berland forest was planted several decades ago in a formation of an infinite grid with a single tree in every cell. Now the trees are grown up and they form a pretty dense structure.\n\nSo dense, actually, that the fire became a real danger for the forest. This season had been abnormally hot in Berland and some trees got caught on fire!\n\nThe second fire started is considered the second $0$. Every second fire lit up all intact neightbouring trees to every currently burning tree. The tree is neighbouring if it occupies adjacent \\textbf{by side or by corner} cell. Luckily, after $t$ seconds Berland fire department finally reached the location of fire and instantaneously extinguished it all.\n\nNow they want to calculate the destructive power of the fire. Let $val_{x, y}$ be the second the tree in cell $(x, y)$ got caught on fire. The destructive power is the sum of $val_{x, y}$ over all $(x, y)$ of burnt trees.\n\nClearly, all the workers of fire department are firefighters, not programmers, thus they asked you to help them calculate the destructive power of the fire.\n\nThe result can be rather big, so print it modulo $998244353$.",
    "tutorial": "Let $f(t)$ be the total number of trees burnt during first $t$ seconds. The answer can be represented as $t f(t) - \\sum \\limits_{i = 0}^{t - 1} f(i)$. Computing one value of $f(t)$ can be done in $O(n^2)$ or $O(n \\log n)$ with scanline or something like that. Let's analyze how the value of this function is changed as time goes. In the beginning, only $n$ initial trees are burnt, then the zones around their position, expand, and so on, until two zones start intersecting. Then again, until another pair of zones starts intersecting. And so on. Let $x_1, x_2, \\dots, x_k$ be the sorted sequence of moments when two zones start intersecting (this sequence has no more than $O(n^2)$ elements and can easily be computed in $O(n^2 \\log n)$). Let's analyze the behavior of the function $f(t)$ on segments $[0, x_1 - 1], [x_1, x_2 - 1]$ and so on. Why are we interested in such segments? Because for each such segment, $f(t)$ can be represented as a polynomial. This can be proven with the help of inclusion-exclusion: for each subset of zones, the intersection of zones is either empty or a rectangle. And if we expand the rectangle, then during second $0$ its area is $ab$, during second $1$ - $(a + 2)(b + 2)$, during second $t$ - $(a + 2t)(b + 2t)$, it's a $2$-nd degree polynomial. So if we would try to compute the area of affected land through inclusion-exclusion formula, we would get a sum of no more than $2^n$ polynomials, each having degree no more than $2$, so the result is also a $2$-nd degree polynomial. We can actually compute the coefficients of this polynomial by interpolation or just some pen and paper work. And $f(x_i) + f(x_{i} + 1) + f(x_{i} + 2) + \\dots + f(x_{i + 1} - 1)$ is a polynomial of $3$-rd degree, which can be computed using some more pen and paper work. So, to conclude, the solution consists of two steps: find all the moments when two zones affected by different trees start intersecting; consider the function on the segments when it behaves as a polynomial.",
    "tags": [
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1088",
    "index": "A",
    "title": "Ehab and another construction problem",
    "statement": "Given an integer $x$, find 2 integers $a$ and $b$ such that:\n\n- $1 \\le a,b \\le x$\n- $b$ divides $a$ ($a$ is divisible by $b$).\n- $a \\cdot b>x$.\n- $\\frac{a}{b}<x$.",
    "tutorial": "Well, the constraints allow a brute-force solution, but here's an $O(1)$ solution: If $x = 1$, there's no solution. Otherwise, just print $x - x%2$ and 2. Time complexity: $O(1)$.",
    "code": "\"#include <iostream>\\nusing namespace std;\\nint main()\\n{\\n    int x;\\n    cin >> x;\\n    if (x==1)\\n    cout << -1;\\n    else\\n    cout << x-x%2 << ' ' << 2;\\n}\"",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1088",
    "index": "B",
    "title": "Ehab and subtraction",
    "statement": "You're given an array $a$. You should repeat the following operation $k$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.",
    "tutorial": "Let $s$ be the set of numbers in input (sorted and distinct). In the $i^{th}$ step, $s_{i}$ is subtracted from all bigger or equal elements, and all smaller elements are 0. Thus, the answer in the $i^{th}$ step is $s_{i} - s_{i - 1}$ ($s_{0} = 0$). Time complexity: $O(nlog(n))$.",
    "code": "\"#include <iostream>\\n#include <set>\\nusing namespace std;\\nint main()\\n{\\n    int n,m;\\n    scanf(\\\"%d%d\\\",&n,&m);\\n    set<int> s;\\n    s.insert(0);\\n    while (n--)\\n    {\\n    \\tint a;\\n    \\tscanf(\\\"%d\\\",&a);\\n    \\ts.insert(a);\\n\\t}\\n\\tauto it=s.begin();\\n\\tfor (int i=0;i<m;i++)\\n\\t{\\n\\t\\tif (next(it)==s.end())\\n\\t\\tprintf(\\\"0\\\\n\\\");\\n\\t\\telse\\n\\t\\t{\\n\\t\\t\\tprintf(\\\"%d\\\\n\\\",*next(it)-*it);\\n\\t\\t\\tit=next(it);\\n\\t\\t}\\n\\t}\\n}\"",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1088",
    "index": "C",
    "title": "Ehab and a 2-operation task",
    "statement": "You're given an array $a$ of length $n$. You can perform the following operations on it:\n\n- choose an index $i$ $(1 \\le i \\le n)$, an integer $x$ $(0 \\le x \\le 10^6)$, and replace $a_j$ with $a_j+x$ for all $(1 \\le j \\le i)$, which means add $x$ to all the elements in the prefix ending at $i$.\n- choose an index $i$ $(1 \\le i \\le n)$, an integer $x$ $(1 \\le x \\le 10^6)$, and replace $a_j$ with $a_j \\% x$ for all $(1 \\le j \\le i)$, which means replace every element in the prefix ending at $i$ with the remainder after dividing it by $x$.\n\nCan you make the array \\textbf{strictly increasing} in no more than $n+1$ operations?",
    "tutorial": "The editorial uses 0-indexing. Both solutions make $a_{i} = i$. First, let's make $a_{i} = x * n + i$ (for some $x$). Then, let's mod the whole array with $n$ (making $a_{i} = i$). If the \"add update\" changed one index, we can just add $i + n - a_{i}%n$ to index $i$. The problem is, if we make $a_{i} = x * n + i$, then update an index $j > i$, $a_{i}$ will be ruined. Just start from the back of the array! Note: for any $a, b$, if $b > a$, $a%b = a$. Additionally, if $a  \\ge  b >$$\\textstyle{\\left|{\\frac{a}{2}}\\right|}$, $a%b = a - b$. Let's add $5 \\cdot 10^{5}$ to the whole array, loop over $a_{i}$ (in order), and mod prefix $i$ with $a_{i} - i$. Why does this work? Notice that $a_{i}%(a_{i} - i) = a_{i} - (a_{i} - i) = i$ (the second note). Also, $a_{i}$ won't be changed afterwards (the first note). Time complexity: $O(n)$.",
    "code": "\"#include <iostream>\\nusing namespace std;\\nint a[2005];\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=0;i<n;i++)\\n\\tscanf(\\\"%d\\\",&a[i]);\\n\\tprintf(\\\"%d\\\\n\\\",n+1);\\n\\tint sum=0;\\n\\tfor (int i=n-1;i>=0;i--)\\n\\t{\\n\\t\\tint add=(i-(a[i]+sum)%n+n)%n;\\n\\t\\tprintf(\\\"1 %d %d\\\\n\\\",i+1,add);\\n\\t\\tsum+=add;\\n\\t}\\n\\tprintf(\\\"2 %d %d\\\",n,n);\\n}\"",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1088",
    "index": "D",
    "title": "Ehab and another another xor problem",
    "statement": "\\textbf{This is an interactive problem!}\n\nEhab plays a game with Laggy. Ehab has 2 hidden integers $(a,b)$. Laggy can ask a pair of integers $(c,d)$ and Ehab will reply with:\n\n- 1 if $a \\oplus c>b \\oplus d$.\n- 0 if $a \\oplus c=b \\oplus d$.\n- -1 if $a \\oplus c<b \\oplus d$.\n\nOperation $a \\oplus b$ is the bitwise-xor operation of two numbers $a$ and $b$.\n\nLaggy should guess $(a,b)$ with \\textbf{at most 62 questions}. You'll play this game. You're Laggy and the interactor is Ehab.\n\n\\textbf{It's guaranteed that $0 \\le a,b<2^{30}$.}",
    "tutorial": "This problem is particularly hard to explain :/ I recommend the simulation. Let's build $a$ and $b$ bit by bit from the most significant to the least significant (assume they're stored in $curA$ and $curB$). Then, at the $i^{th}$ step, $a\\oplus c u r A$ and $b\\oplus c u r B$ have all bits from the most significant to the $(i + 1)^{th}$ set to 0. Notice that whether $x$ is greater or less than $y$ is judged by the most significant bit in which they differ (the one that has 1 is bigger). Let's query with $(c u r A\\oplus2^{i}.c u r B)$ and $(c u r A,c u r B\\oplus2^{k})$. $a\\oplus c$ and $b\\oplus d$ can only differ in the $i^{th}$ bit (or a bit less significant). Now, if the results of the queries are different, $a$ and $b$ have the same value in this bit, and this value can be determined by the answer of respective queries (1 if the second query's answer is 1, 0 otherwise). If the queries give the same result, $a$ and $b$ must differ in this bit. How to know which of them has a 1 and which has a 0? We know that the greater between them (after setting the processed bits to 0) has a 1 and the other has a 0. The trick is to keep track of the greater between them. Before all queries, we send $(0, 0)$ to know the greater. Every time they differ in a bit, the greater may change. It'll simply change to the answer of the 2 queries we sent! In other words, we know when we sent the queries that after making $a$ and $b$ equal in this bit, some other bit became the most significant bit in which they differ. Also, we know who has a 1 in this bit (the greater in this query). Thus, we'll keep the answer of this query for the future, so when this bit comes, we don't need additional queries. Let's simulate for $a = 6$ and $b = 5$. In the first query, we'll send $(0, 0)$ to know that $a > b$. In the second query, we'll send $(4, 0)$ (the answer is -1) and $(0, 4)$ (the answer is 1). Since the answers differ, this bit has the same value for $a$ and $b$. Since the answer to the second query is 1, they both have a 1. Now, $curA = curB = 4$. In the third query, we'll send $(6, 4)$ (the answer is -1) and $(4, 6)$ (the answer is -1). Since the answers are the same, $a$ and $b$ differ in this bit. Since $a$ is currently the greater, $a$ has a 1 and $b$ has a 0. Now, the greater is $b$ (the next time 2 bits differ, $b$ will have a 1). Also, $curA = 6$ and $curB = 4$. In the last query, we'll send $(7, 4)$ (the answer is 0) and $(6, 5)$ (the answer is 0). Since the answers are the same, $a$ and $b$ differ in this bit. Since $b$ is currently greater, $b$ has a 1. Now, $curA = 6$ and $curB = 5$ and we're done :D Time complexity: $O(log(n))$.",
    "code": "\"#include <iostream>\\nusing namespace std;\\nint ask(int c,int d)\\n{\\n\\tcout << \\\"? \\\" << c << ' ' << d << endl;\\n\\tint ans;\\n\\tcin >> ans;\\n\\treturn ans;\\n}\\nint main()\\n{\\n\\tcout.flush();\\n\\tint a=0,b=0,big=ask(0,0);\\n\\tfor (int i=29;i>=0;i--)\\n\\t{\\n\\t\\tint f=ask(a^(1<<i),b),s=ask(a,b^(1<<i));\\n\\t\\tif (f==s)\\n\\t\\t{\\n\\t\\t\\tif (big==1)\\n\\t\\t\\ta^=(1<<i);\\n\\t\\t\\telse\\n\\t\\t\\tb^=(1<<i);\\n\\t\\t\\tbig=f;\\n\\t\\t}\\n\\t\\telse if (f==-1)\\n\\t\\t{\\n\\t\\t\\ta^=(1<<i);\\n\\t\\t\\tb^=(1<<i);\\n\\t\\t}\\n\\t}\\n\\tcout << \\\"! \\\" << a << ' ' << b << endl;\\n}\"",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "implementation",
      "interactive"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1088",
    "index": "E",
    "title": "Ehab and a component choosing problem",
    "statement": "You're given a tree consisting of $n$ nodes. Every node $u$ has a weight $a_u$. You want to choose an integer $k$ $(1 \\le k \\le n)$ and then choose $k$ connected components of nodes that don't overlap (i.e every node is in at most 1 component). Let the set of nodes you chose be $s$. You want to maximize:\n\n$$\\frac{\\sum\\limits_{u \\in s} a_u}{k}$$\n\nIn other words, you want to maximize the sum of weights of nodes in $s$ divided by the number of connected components you chose. Also, if there are several solutions, you want to \\textbf{maximize $k$}.\n\nNote that adjacent nodes \\textbf{can} belong to different components. Refer to the third sample.",
    "tutorial": "Assume you already chose the components. Let the sum of nodes in the $i^{th}$ component be $b_{i}$. Then, the expression in the problem is equivalent to $average(b_{1}, b_{2}, ..., b_{k})$. Assume we only bother about the fraction maximization problem and don't care about $k$. Then, it'll always be better to choose the component with the maximum $b_{i}$ and throw away the rest! This is because of the famous inequality: $max(b_{1}, b_{2}, ..., b_{k})  \\ge  average(b_{1}, b_{2}, ..., b_{k})$ and the equality only occurs if all $b_{i}$ are equal! This means that the maximum value of the fraction is simply the maximum sum of a sub-component in the tree. To calculate it, let's root the tree at node 1, and calculate $dp[node]$, the maximum sum of a sub-component that contains node. Now, I'll put the code, and explain it after. $ans$ denotes the maximum sub-component sum. First, we call $dfs(1, 0, 1)$. We calculate the $dp$ of all the children of $node$. For every child $u$, we extend the component of $node$ with the component of $u$ if $dp[u] > 0$, and do nothing otherwise. Now, we solved the first half of our problem, but what about maximizing $k$? Notice that all components you choose must have a sum of weights equal to $ans$ (because the equality occurs if and only if all $b_{i}$ are equal). You just want to maximize their count. Let's calculate our $dp$ again. Assume $dp[node] = ans$. We have 2 choices: either mark the $node$ and its component as a component in the answer (but then other nodes won't be able to use them because the components can't overlap), or wait and extend the component. The idea is that there's no reason to wait. If we extend the component with some nodes, they won't change the sum, and they may even have another sub-component with maximal sum that we're merging to our component and wasting it! Thus, we'll always go with the first choice, making $dp[node] = 0$ so that its parent can't use it, and increasing $k$ :D Time complexity: $O(n)$.",
    "code": "\"#include <iostream>\\n#include <vector>\\nusing namespace std;\\nint a[300005],k;\\nlong long dp[300005],ans=-1e9;\\nvector<int> v[300005];\\nvoid dfs(int node,int p,bool f)\\n{\\n\\tdp[node]=a[node];\\n\\tfor (int u:v[node])\\n\\t{\\n\\t\\tif (u!=p)\\n\\t\\t{\\n\\t\\t\\tdfs(u,node,f);\\n\\t\\t\\tdp[node]+=max(dp[u],0LL);\\n\\t\\t}\\n\\t}\\n\\tif (f)\\n\\tans=max(ans,dp[node]);\\n\\telse if (dp[node]==ans)\\n\\t{\\n\\t\\tdp[node]=0;\\n\\t\\tk++;\\n\\t}\\n}\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=1;i<=n;i++)\\n\\tscanf(\\\"%d\\\",&a[i]);\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tint a,b;\\n\\t\\tscanf(\\\"%d%d\\\",&a,&b);\\n\\t\\tv[a].push_back(b);\\n\\t\\tv[b].push_back(a);\\n\\t}\\n\\tdfs(1,0,1);\\n\\tdfs(1,0,0);\\n\\tprintf(\\\"%I64d %d\\\",ans*k,k);\\n}\"",
    "tags": [
      "dp",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1088",
    "index": "F",
    "title": "Ehab and a weird weight formula",
    "statement": "You're given a tree consisting of $n$ nodes. Every node $u$ has a weight $a_u$. It is guaranteed that there is only one node with minimum weight in the tree. For every node $u$ (except for the node with the minimum weight), it must have a neighbor $v$ such that $a_v<a_u$. You should construct a tree to minimize the weight $w$ calculated as follows:\n\n- For every node $u$, $deg_u \\cdot a_u$ is added to $w$ ($deg_u$ is the number of edges containing node $u$).\n- For every edge $\\{ u,v \\}$, $\\lceil log_2(dist(u,v)) \\rceil \\cdot min(a_u,a_v)$ is added to $w$, where $dist(u,v)$ is the number of edges in the path from $u$ to $v$ in the given tree.",
    "tutorial": "First, let's reduce the problem to ordinary MST. We know that each edge ${u, v}$ adds $ \\lceil log_{2}(dist(u, v)) \\rceil  \\cdot min(a_{u}, a_{v})$ to $w$. In fact, it also adds 1 to $deg_{u}$ and $deg_{v}$. Thus, the problem is ordinary MST on a complete graph where each edge ${u, v}$ has weight $( \\lceil log_{2}(dist(u, v)) \\rceil  + 1) \\cdot min(a_{u}, a_{v}) + max(a_{u}, a_{v})$! Let the node with the minimum weight be $m$. Let's root the tree at it. Lemma: for every node $u$ and a child $v$, $a_{v} > a_{u}$. In simpler words, the weight increase as we go down the tree. Proof: the proof is by contradiction. Assume $a_{v}  \\le  a_{u}$. Then, the condition in the problem (that every node has an adjacent node with less weight) isn't satisfied yet for $v$. Therefore, $v$ must have a child $k$ such that $a_{k} < a_{v}$. However, the condition isn't satisfied for $k$, so $k$ needs another child and the child needs another child etc. (the tree will be infinite) which is clearly a contradiction. From that, we know that the weights decrease as we go up the tree and increase as we go down. Back to the MST problem. From Kruskal's algorithm, we know that the minimal edge incident to every node will be added to the MST (because the edges are sorted by weight). Let's analyze the minimal edge incident to every node $u$. Let its other end be $v$. Except for node $m$, $v$ will be an ancestor of $u$. Why? Assume we fix the distance part and just want to minimize $a_{v}$. We'll keep going up the tree (it's never optimal to go down, since the weights will increase) until we reach the desired distance. Now, since the minimal edge incident to every node will be added to the MST (by Kruskal's algorithm), and they're distinct (because, otherwise, you're saying that $u$ is an ancestor of $v$ and $v$ is an ancestor of $u$), THEY ARE THE MST. Now, the problem just reduces to finding the minimal edge incident to every node and summing them up (except for $m$). To do that, we'll fix the $ \\lceil log_{2}(dist(u, v)) \\rceil $ (let it be $k$), and get the $2^{kth}$ ancestor with the well-known sparse-table (binary lifting). Time complexity: $O(nlog(n))$.",
    "code": "\"#include <iostream>\\n#include <string.h>\\n#include <vector>\\nusing namespace std;\\nvector<int> v[500005];\\nint m=1,a[500005],dp[20][500005];\\nlong long ans;\\nvoid dfs(int node,int p)\\n{\\n\\tdp[0][node]=p;\\n\\tfor (int i=1;i<20;i++)\\n\\t{\\n\\t\\tif (dp[i-1][node]!=-1)\\n\\t\\tdp[i][node]=dp[i-1][dp[i-1][node]];\\n\\t}\\n\\tint d;\\n\\tlong long mn=(1LL<<60);\\n\\tfor (d=0;d<20 && dp[d][node]!=-1;d++)\\n\\tmn=min(mn,(long long)(d+1)*a[dp[d][node]]+a[node]);\\n\\tmn=min(mn,(long long)(d+1)*a[m]+a[node]);\\n\\tif (p!=-1)\\n\\tans+=mn;\\n\\tfor (int u:v[node])\\n\\t{\\n\\t\\tif (u!=p)\\n\\t\\tdfs(u,node);\\n\\t}\\n}\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\tscanf(\\\"%d\\\",&a[i]);\\n\\t\\tif (a[i]<a[m])\\n\\t\\tm=i;\\n\\t}\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tint a,b;\\n\\t\\tscanf(\\\"%d%d\\\",&a,&b);\\n\\t\\tv[a].push_back(b);\\n\\t\\tv[b].push_back(a);\\n\\t}\\n\\tmemset(dp,-1,sizeof(dp));\\n\\tdfs(m,-1);\\n\\tprintf(\\\"%I64d\\\",ans);\\n}\"",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1091",
    "index": "A",
    "title": "New Year and the Christmas Ornament",
    "statement": "Alice and Bob are decorating a Christmas Tree.\n\nAlice wants only $3$ types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have $y$ yellow ornaments, $b$ blue ornaments and $r$ red ornaments.\n\nIn Bob's opinion, a Christmas Tree will be beautiful if:\n\n- the number of blue ornaments used is greater by \\textbf{exactly} $1$ than the number of yellow ornaments, and\n- the number of red ornaments used is greater by \\textbf{exactly} $1$ than the number of blue ornaments.\n\nThat is, if they have $8$ yellow ornaments, $13$ blue ornaments and $9$ red ornaments, we can choose $4$ yellow, $5$ blue and $6$ red ornaments ($5=4+1$ and $6=5+1$).\n\nAlice wants to choose as many ornaments as possible, but she also wants the Christmas Tree to be beautiful according to Bob's opinion.\n\nIn the example two paragraphs above, we would choose $7$ yellow, $8$ blue and $9$ red ornaments. If we do it, we will use $7+8+9=24$ ornaments. That is the maximum number.\n\nSince Alice and Bob are busy with preparing food to the New Year's Eve, they are asking you to find out the maximum number of ornaments that can be used in their \\textbf{beautiful} Christmas Tree!\n\nIt is guaranteed that it is possible to choose at least $6$ ($1+2+3=6$) ornaments.",
    "tutorial": "Consider some solution $Y$, $B$, $R$, where $Y + 1 = B$ and $B + 1 = R$. Let's add two yellow ornaments and one blue both to the solution and to the reserve, then we have $Y = B = R$. We can see that this new problem is equivalent to the old one. In this problem, the best solution is achieved when we use $\\min(y,b,r)$ ornaments of each colour. Hence, we can find the said minimum, multiply by three and then remove the three extra ornaments again.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int a, b, c;\n    cin >> a >> b >> c;\n    cout << min(a + 2, min(b + 1, c)) * 3 - 3;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1091",
    "index": "B",
    "title": "New Year and the Treasure Geolocation",
    "statement": "Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $T$, which coordinates to be found out.\n\nBob travelled around the world and collected clues of the treasure location at $n$ obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?\n\nAs everyone knows, the world is a two-dimensional plane. The $i$-th obelisk is at integer coordinates $(x_i, y_i)$. The $j$-th clue consists of $2$ integers $(a_j, b_j)$ and belongs to the obelisk $p_j$, where $p$ is some (unknown) permutation on $n$ elements. It means that the treasure is located at $T=(x_{p_j} + a_j, y_{p_j} + b_j)$. This point $T$ is the same for all clues.\n\nIn other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.\n\nYour task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.\n\nNote that you don't need to find the permutation. Permutations are used only in order to explain the problem.",
    "tutorial": "We know that there exists some permutation $p$ such that for all $i$ the following holds: $(t_x, t_y) = (x_{p_i} + a_i, y_{p_i} + b_i)$ Summing this for all $i$ we get: $n \\cdot (t_x, t_y) = \\sum (x_{p_i} + a_i, y_{p_i} + b_i) = \\left(\\sum (x_{p_i} + a_i), \\sum (y_{p_i} + b_i)\\right) = \\left(\\sum x_i + \\sum a_i, \\sum y_i + \\sum b_i\\right)$ We can thus sum all $x$, respectively $y$, coordinates of both obelisks and clues, and divide by $n$. This takes $\\mathcal O(n)$ time. Alternative solution: Take the lexicographically smallest obelisk coordinate. It is clear that this needs to be paired with the lexicographically largest clue. We simply find minimum and maximum in $\\mathcal O(n)$ and sum.",
    "code": "#include <vector>\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\n\ntypedef pair<int,int> pii;\n\n#define x first\n#define y second\n\nint main() {\n    int N; cin >> N;\n    vector<pii> O(N), T(N);\n    for (int i = 0; i < N; i++) cin >> O[i].x >> O[i].y;\n    for (int i = 0; i < N; i++) cin >> T[i].x >> T[i].y;\n    sort(O.begin(),O.end());\n    sort(T.begin(),T.end());\n    reverse(T.begin(),T.end());\n\n    vector<pii> Ans(N);\n    for (int i = 0; i < N; i++) Ans[i] = {O[i].x+T[i].x, O[i].y+T[i].y};\n    sort(Ans.begin(),Ans.end());\n    cout << Ans[0].x << ' ' << Ans[0].y << endl;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1091",
    "index": "C",
    "title": "New Year and the Sphere Transmission",
    "statement": "There are $n$ people sitting in a circle, numbered from $1$ to $n$ in the order in which they are seated. That is, for all $i$ from $1$ to $n-1$, the people with id $i$ and $i+1$ are adjacent. People with id $n$ and $1$ are adjacent as well.\n\nThe person with id $1$ initially has a ball. He picks a positive integer $k$ at most $n$, and passes the ball to his $k$-th neighbour in the direction of increasing ids, that person passes the ball to his $k$-th neighbour in the same direction, and so on until the person with the id $1$ gets the ball back. When he gets it back, people do not pass the ball any more.\n\nFor instance, if $n = 6$ and $k = 4$, the ball is passed in order $[1, 5, 3, 1]$.\n\nConsider the set of all people that touched the ball. The \\textbf{fun value} of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $1 + 5 + 3 = 9$.\n\nFind and report the set of possible fun values for all choices of positive integer $k$. It can be shown that under the constraints of the problem, the ball always gets back to the $1$-st player after finitely many steps, and there are no more than $10^5$ possible fun values for given $n$.",
    "tutorial": "Subtract $1$ from all values for convenience. Fix the value of $k$. We get values of $a \\cdot k \\bmod n$ for all $a$ from $0$ until we reach $0$ again. This value can be also written as $a \\cdot k - b \\cdot n$. Due to Bezout's theorem, the equation $a \\cdot k - b \\cdot n = c$ has an integer solution for $a$ and $b$ if and only if $c$ is divisible by $\\text{gcd}(k, n)$. Furthermore, all possible values of $c$ will be visited before it returns to $0$. This is because the element $k/\\text{gcd}(k,n)$ generates the group $\\mathbb{Z}_{n/\\text{gcd}(k,n)}$. We can thus consider only values of $k$ that divide $n$. We can find all of them by trial division in $\\mathcal O(\\sqrt n)$. For each of them, we can find a closed form solution by summing arithmetic series.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n\tll N; cin >> N;\n\tvector<ll> ans;\n\n\tfor (ll i = 1; i*i <= N; ++i) {\n\t\tif (N%i==0) {\n\t\t\tans.push_back(N*(i-1)/2 + i);\n\t\t\tif (i*i!=N) {\n\t\t\t\tans.push_back(N*(N/i-1)/2 + N/i);\n\t\t\t}\n\t\t}\n\t}\n\tsort(ans.begin(),ans.end());\n\t\n\tfor (int i = 0; i < ans.size(); ++i) {\n\t\tcout << ans[i] << \" \\n\"[i==ans.size()-1];\n\t}\n\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1091",
    "index": "D",
    "title": "New Year and the Permutation Concatenation",
    "statement": "Let $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $p$. For example, if $n = 3$, then $p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence will be $n \\cdot n!$.\n\nLet $1 \\leq i \\leq j \\leq n \\cdot n!$ be a pair of indices. We call the sequence $(p_i, p_{i+1}, \\dots, p_{j-1}, p_j)$ a \\textbf{subarray} of $p$. Its \\textbf{length} is defined as the number of its elements, i.e., $j - i + 1$. Its \\textbf{sum} is the sum of all its elements, i.e., $\\sum_{k=i}^j p_k$.\n\nYou are given $n$. Find the number of subarrays of $p$ of length $n$ having sum $\\frac{n(n+1)}{2}$. Since this number may be large, output it modulo $998244353$ (a prime number).",
    "tutorial": "There are two types of subarrays with length $n$: They are fully formed from one permutations. They are a concatenation of a $k$ long suffix of one permutation, and a $n-k$ long prefix of the next permutation. There are $n!$ such subarrays of the first type, and they all have the the correct sum. Let's investigate the second type. Recall the algorithm of finding the next permutation in lexicographical order. We find the longest suffix that is in decreasing order, let its length be $k$. We swap the preceding element $x$ with the smallest one from the decreasing sequence larger than $x$, and sort the suffix in increasing order. The prefix of length $n - k - 1$ is left unchanged, but all longer proper prefixes are different and also change their sum. Coming back to our problem, if the suffix of length $k$ is in decreasing order, than the prefix of length $n - k$ of the next permutation has different sum from the prefix of the same length of the current permutation, hence the subarray has incorrect sum. Conversely, if the suffix of length $k$ is not in decreasing order, then the prefix of length $n-k$ of the next permutation equals to the prefix of the current permutation, and its sum is $\\frac{n(n+1)}{2}$. To find the answer, we must thus subtract the number of suffixes of all permutations that are decreasing. How many of them are there for a fixed $k$? This is simple - we choose the first $n-k$ elements freely, and permute them. The rest has to be sorted in a particular way. Hence the number of bad subarrays coming from a suffix of length $k$ equals $\\frac{n!}{k!}$. Convince yourself that this approach works correctly even for the last permutation, where there is no next permutation to concatenate its suffixes with. The answer is: $n \\cdot n! - \\sum_{k=1}^{n-1} \\frac{n!}{k!}$ This can be calculated in $\\mathcal O(n)$ without the need of modular division. There is also a simple recurrence counting the same answer, found by arsijo: $d(n) = \\left(d(n-1) + (n-1)! - 1\\right) \\cdot n$",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ntemplate <unsigned int N> class Field {\n    typedef unsigned int ui;\n    typedef unsigned long long ull;\n\tinline ui pow(ui a, ui p){ui r=1,e=a;while(p){if(p&1){r=((ull)r*e)%N;}e=((ull)e*e)%N;p>>=1;}return r;}\n\tinline ui inv(ui a){return pow(a,N-2);}\npublic:\n    inline Field(int x = 0) : v(x) {}\n\tinline Field<N> pow(int p){return (*this)^p; }\n\tinline Field<N> operator^(int p){return {(int)pow(v,(ui)p)};}\n    inline Field<N>&operator+=(const Field<N>&o) {if (v+o.v >= N) v += o.v - N; else v += o.v; return *this; }\n    inline Field<N>&operator-=(const Field<N>&o) {if (v<o.v) v -= o.v-N; else v-=o.v; return *this; }\n    inline Field<N>&operator*=(const Field<N>&o) {v=(ull)v*o.v % N; return *this; }\n    inline Field<N>&operator/=(const Field<N>&o) { return *this*=inv(o.v); }\n    inline Field<N> operator+(const Field<N>&o) const {Field<N>r{*this};return r+=o;}\n    inline Field<N> operator-(const Field<N>&o) const {Field<N>r{*this};return r-=o;}\n    inline Field<N> operator*(const Field<N>&o) const {Field<N>r{*this};return r*=o;}\n    inline Field<N> operator/(const Field<N>&o) const {Field<N>r{*this};return r/=o;}\n    inline Field<N> operator-() {if(v) return {(int)(N-v)}; else return {0};};\n    inline Field<N>& operator++() { ++v; if (v==N) v=0; return *this; }\n    inline Field<N> operator++(int) { Field<N>r{*this}; ++*this; return r; }\n    inline Field<N>& operator--() { --v; if (v==-1) v=N-1; return *this; }\n    inline Field<N> operator--(int) { Field<N>r{*this}; --*this; return r; }\n    inline bool operator==(const Field<N>&o) const { return o.v==v; }\n\tinline bool operator!=(const Field<N>&o) const { return o.v!=v; }\n\tinline explicit operator ui() const { return v; }\n\tinline static vector<Field<N>>fact(int t){vector<Field<N>>F(t+1,1);for(int i=2;i<=t;++i){F[i]=F[i-1]*i;}return F;}\n\tinline static vector<Field<N>>invfact(int t){vector<Field<N>>F(t+1,1);Field<N> X{1};for(int i=2;i<=t;++i){X=X*i;}F[t]=1/X;for(int i=t-1;i>=2;--i){F[i]=F[i+1]*(i+1);}return F;}\nprivate: ui v;\n};\ntemplate<unsigned int N>istream &operator>>(std::istream&is,Field<N>&f){unsigned int v;is>>v;f=v;return is;}\ntemplate<unsigned int N>ostream &operator<<(std::ostream&os,const Field<N>&f){return os<<(unsigned int)f;}\ntemplate<unsigned int N>Field<N> operator+(int i,const Field<N>&f){return Field<N>(i)+f;}\ntemplate<unsigned int N>Field<N> operator-(int i,const Field<N>&f){return Field<N>(i)-f;}\ntemplate<unsigned int N>Field<N> operator*(int i,const Field<N>&f){return Field<N>(i)*f;}\ntemplate<unsigned int N>Field<N> operator/(int i,const Field<N>&f){return Field<N>(i)/f;}\n\ntypedef Field<998244353> FF;\n\nint main(int argc, char* argv[]) {\n    int n; cin >> n;\n    auto F = FF::fact(n);\n    auto I = FF::invfact(n);\n    FF ans = n * F[n];\n    for (int i = 1; i < n; ++i) ans -= F[n]*I[i];\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1091",
    "index": "E",
    "title": "New Year and the Acquaintance Estimation",
    "statement": "Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if $a$ is a friend of $b$, then $b$ is also a friend of $a$. Each user thus has a non-negative amount of friends.\n\nThis morning, somebody anonymously sent Bob the following link: graph realization problem and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print \\textbf{all} of them.",
    "tutorial": "The first observation is that using the Handshaking lemma, we know the parity of $a_{n+1}$. Secondly, on the integers of same parity, the answer always forms a continuous interval, that is if $a_{n+1} = X$ is one possible answer and $a_{n+1} = Y$ is another with $X < Y$, then every $X < Z < Y$ satisfying $X \\bmod 2 == Z \\bmod 2$ is also an answer. We should thus look into some binary search approaches. We use the Erdos-Gallai theorem linked in the statement to determine whether a sequence is graphic. If it is not the case, we must determine whether the answer is too big or too small. This depends on whether the $a_{n+1}$ is on the left or the right side of the inequality when it is not satisfied. If it is on the left, it means that it is too big - clearly making it larger is never going to change the sign of the inequality. On the contrary, if $a_{n+1}$ is on the right, it is clearly too small. It can also happen that the inequality is false for some $k$ where $a_{n+1}$ is on the left and for some other $k$ it is on the right. Then there clearly is no solution. Checking the inequality naively takes $\\mathcal O(n^2)$ time, but we can also do it in $\\mathcal O(n)$: for left side we need a prefix sum, and for right side we maintain the sum and also how many times a particular value occurs. The sum of values at most $k$ can then be maintained in $\\mathcal O(1)$. This yields an algorithm in $\\mathcal O(n \\log n)$. Alternatively, we can perform a similar binary search using Havel-Hakimi algorithm, using a segment tree or a multiset and tracking whether the $a_{n+1}$ was already processed or not to find out whether the answer is too small or too big. This yields $\\mathcal O(n \\log^2 n)$ algorithm.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\n\n#define MAXN 500000\n\nint N;\nint A[MAXN];\nlong long sum;\n\n#define TOO_SMALL -1\n#define OK 0\n#define TOO_BIG 1\n\nint is_score(int value) {\n    vector<int> C(N+1,0);\n    for (int i = 0; i < N; ++i) ++C[A[i]];\n    ++C[value];\n\n    int less = 0;\n    long long left = 0, right = 0;\n    for (int k = 0, i = 0; k <= N; k++) {\n        int val = (i == k && (i == N || A[i] < value)) ? value : A[i++];\n        left += val;\n        --C[val];\n        right -= min(val, k);\n        less += C[k];\n        right += N-k-less;\n        if (left > right + (long long)(k+1)*k) {\n            return (i == k) ? TOO_BIG : TOO_SMALL;\n        }\n    }\n    return OK;\n}\n\nint main(int,char**) {\n    ios_base::sync_with_stdio(false);\n    \n    scanf(\"%d\", &N);\n    sum = 0;\n    for (int i = 0; i < N; i++) {\n        scanf(\"%d\", A + i);\n        sum += A[i];\n    }\n\n    sort(A,A+N,greater<int>());\n    int parity = sum & 1;\n    int lo = 0, hi = (N - parity) / 2, lores = -1;\n    while (lo <= hi) {\n        int mid = (lo + hi) / 2;\n        if (is_score(2*mid + parity) == TOO_SMALL) {\n            lo = mid + 1;\n        } else {\n            lores = mid;\n            hi = mid - 1;\n        }\n    }\n    \n    lo = lores; \n    hi = (N - parity) / 2; \n    int hires = -1;\n    while (lo <= hi) {\n        int mid = (lo + hi) / 2;\n        if (is_score(2*mid + parity) == TOO_BIG) {\n            hi = mid - 1;\n        } else {\n            hires = mid;\n            lo = mid + 1;\n        }\n    }\n    \n    if (lores == -1 || hires == -1) printf(\"-1\\n\"); \n    else {\n        for (int i = lores; i <= hires; ++i) printf(\"%d \", 2*i+parity);\n        printf(\"\\n\");\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "graphs",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1091",
    "index": "F",
    "title": "New Year and the Mallard Expedition",
    "statement": "Bob is a duck. He wants to get to Alice's nest, so that those two can duck!\n\n\\begin{center}\nDuck is the ultimate animal! (Image courtesy of See Bang)\n\\end{center}\n\nThe journey can be represented as a straight line, consisting of $n$ segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last segment. Each segment has a length in meters, and also terrain type: grass, water or lava.\n\nBob has three movement types: swimming, walking and flying. He can switch between them or change his direction at any point in time (even when he is located at a non-integer coordinate), and doing so doesn't require any extra time. Bob can swim only on the water, walk only on the grass and fly over \\textbf{any} terrain. Flying one meter takes $1$ second, swimming one meter takes $3$ seconds, and finally walking one meter takes $5$ seconds.\n\nBob has a finite amount of energy, called stamina. Swimming and walking is relaxing for him, so he gains $1$ stamina for every meter he walks or swims. On the other hand, flying is quite tiring, and he spends $1$ stamina for every meter flown. Staying in place does not influence his stamina at all. Of course, his stamina can never become negative. Initially, his stamina is zero.\n\nWhat is the shortest possible time in which he can reach Alice's nest?",
    "tutorial": "We start with a greedy solution. This means that we fly over lava, swim on water and walk on grass, keeping track of time and the stamina. There are two types of issues that may happen - either we don't have enough stamina to fly over lava, or we have some leftover stamina at the end. If we lack some stamina, we can walk or swim \"in place\" for some amount of time to gain it. This \"in place\" movement can be perform by simply walking or swimming half a meter backwards and then half a meter forwards. This gains $1$ stamina. It is more effective to do on water, as we move faster there, so we may as well do it on the first water on the journey. If there was no water before the lava we are flying across, we use slightly more expensive ground. On the other hand, if we have some unused stamina in the end, we should convert some previous movement to flying to save time. Note that converting $1$ meter of movement costs us $2$ stamina, not one, since we consume $1$ stamina and also gain $1$ stamina less. Since moving on grass is slower, we prefer to convert such movements. However, we must take care not to convert a walking segment that is too early - we should not modify the journey in such a way that we run out of stamina at some point. We thus keep track of the length of grass that we travelled across during our journey. Consider the end of some patch of terrain. Let the total length of grass that we've travelled through until now be $G$, and let the current stamina be $S$. We may never convert more than $G$ grass, and also no more than $S/2$ since if not, we would have run out of stamina at the current location. We simply lower the amount of grass $G$ that is available to be converted, to $S/2$. In the end, we convert $G$ walking to flying, and $S/2 - G$ swimming to flying to save some time. This works in $\\mathcal O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n\ntypedef long long ll;\nusing namespace std;\n\nint main() {\n    int N; cin >> N;\n    vector<ll> L(N); \n    for (ll &l: L) cin >> l;\n    string T; cin >> T;\n    bool hadWater = false;\n    ll time = 0, stamina = 0, twiceGrass = 0;\n    for (int i = 0; i < N; ++i) {\n        if (T[i] == 'L') {\n            time += L[i];\n            stamina -= L[i];\n            if (stamina < 0) {\n                /* not enough stamina, walk or swim \"in place\" to gain it */\n                time -= stamina * (hadWater ? 3 : 5);\n                stamina = 0;\n            }\n        } else if (T[i] == 'W') {\n            hadWater = true;\n            stamina += L[i];\n            time += 3 * L[i];\n        } else {\n            stamina += L[i];\n            time += 5 * L[i];\n            twiceGrass += 2*L[i];   \n        }\n        /* no more than stamina/2 of walking can be converted to flying to save time,\n         * otherwise there would not be enough stamina at this point */\n        twiceGrass = min(twiceGrass, stamina);\n    }\n\n    if (stamina > 0) {\n        // convert walking to flying\n        time -= (5-1) * twiceGrass/2;\n\n        // convert swimming to flying\n        time -= (3-1) * (stamina - twiceGrass)/2;\n    }\n\n    cout << time << endl;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1091",
    "index": "G",
    "title": "New Year and the Factorisation Collaboration",
    "statement": "Integer factorisation is hard. The RSA Factoring Challenge offered $$100\\,000$ for factoring RSA-$1024$, a $1024$-bit long product of two prime numbers. To this date, nobody was able to claim the prize. We want you to factorise a $1024$-bit number.\n\nSince your programming language of choice might not offer facilities for handling large integers, we will provide you with a very simple calculator.\n\nTo use this calculator, you can print queries on the standard output and retrieve the results from the standard input. The operations are as follows:\n\n- + x y where $x$ and $y$ are integers between $0$ and $n-1$. Returns $(x+y) \\bmod n$.\n- - x y where $x$ and $y$ are integers between $0$ and $n-1$. Returns $(x-y) \\bmod n$.\n- * x y where $x$ and $y$ are integers between $0$ and $n-1$. Returns $(x \\cdot y) \\bmod n$.\n- / x y where $x$ and $y$ are integers between $0$ and $n-1$ and $y$ is coprime with $n$. Returns $(x \\cdot y^{-1}) \\bmod n$ where $y^{-1}$ is multiplicative inverse of $y$ modulo $n$. If $y$ is not coprime with $n$, then $-1$ is returned instead.\n- sqrt x where $x$ is integer between $0$ and $n-1$ coprime with $n$. Returns $y$ such that $y^2 \\bmod n = x$. If there are multiple such integers, only one of them is returned. If there are none, $-1$ is returned instead.\n- ^ x y where $x$ and $y$ are integers between $0$ and $n-1$. Returns ${x^y \\bmod n}$.\n\nFind the factorisation of $n$ that is a product of between $2$ and $10$ \\textbf{distinct} prime numbers, all of form $4x + 3$ for some integer $x$.\n\n\\textbf{Because of technical issues, we restrict number of requests to $100$.}",
    "tutorial": "Most of the operations we're given are useless, as we can perform them on our own. However, we cannot perform the square root ourselves, so we should be able to use the information given us by the square root oracle to find the factorisation. First let's solve the task for a product of two primes. Select $x$ uniformly at random and assign $z = x^2$. Let $y$ be the answer to the query sqrt z. We have $x^2 \\equiv y^2 \\pmod n$ $(x+y)(x-y) \\equiv 0 \\pmod n$ Let's take a look what happens when there are more than two prime factors. Some of them will be accumulated in $x+y$, and the others in $x-y$. Collect all these values (again, after taking gcd of them with $n$) over multiple queries. We can find the prime factor $p_j$ if and only if for $i \\neq j$ we have seen a value $t$ such that $\\text{gcd}(t, p_i \\cdot p_j) = p_j$. This is because we can take gcd of exactly all values containing $p_i$ as a factor and to get $p_i$. We do not know which values contain the prime factor before we know the prime factor, but we simply calculate gcd of all subsets of retrieved values. Since gcd is a commutative and associative operation, and all values we get this way must be factors of $n$, we can perform this step in $\\mathcal O(f \\cdot 4^f)$ time, where $f$ is the number of prime factors of $n$. We can then a primality checking algorithm to check which of these are primes. Alternatively, we can just greedily pick the smallest of all values (except $1$) that is coprime to all the values that have been selected so far - this will always be a prime. It remains to show what is the probability of success. We need each pair of primes to be separated at least once. The probability of that happening in one query is $1/2$. Over the course of $q$ queries, we have probability $2^{-q}$ that we are still unable to separate the two primes. Taking union bound over all prime pairs yields an upper bound on the error probability $4 * 10^{-14}$. Implementation note: To find the square root, we use Chinese remainder theorem and find the square roots in the respective finite fields. The primes are of form $4x + 3$ for a simple reason - we can find the square root of $x$ modulo $p$ by simply calculating $x^{\\frac{p+1}{2}}$. For primes of form $4x + 1$, we need Tonelli-Shanks, which empirically uses about $5$ modular exponentiations. With the number of queries and prime factors, and the size of the numbers, it was suddenly impossible for the interactor to fit into the time limit.",
    "code": "import random\n\ndef isPrime(n):\n    \"\"\"\n    Miller-Rabin primality test.\n\n    A return value of False means n is certainly not prime. A return value of\n    True means n is very likely a prime.\n    \"\"\"\n    if n!=int(n):\n        return False\n    n=int(n)\n    #Miller-Rabin test for prime\n    if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:\n        return False\n\n    if n==2 or n==3 or n==5 or n==7:\n        return True\n    s = 0\n    d = n-1\n    while d%2==0:\n        d>>=1\n        s+=1\n    assert(2**s * d == n-1)\n\n    def trial_composite(a):\n        if pow(a, d, n) == 1:\n            return False\n        for i in range(s):\n            if pow(a, 2**i * d, n) == n-1:\n                return False\n        return True\n\n    for i in range(20):#number of trials\n        a = random.randrange(2, n)\n        if trial_composite(a):\n            return False\n\n    return True\n\ndef gcd(x, y):\n    return x if y == 0 else gcd(y, x % y)\n\nn = int(input())\n\ndivs = [n]\n\ndef split(parts):\n    global divs\n    divs = [gcd(d, p) for d in divs for p in parts if gcd(d, p) != 1]\n\nwhile not all([isPrime(x) for x in divs]):\n    x = random.randint(0, n - 1)\n    g = gcd(n, x)\n    if gcd(n, x) != 1:\n        split([g, n // g])\n        continue\n    y = int(input('sqrt {}\\n'.format(x * x % n)))\n    if x == y:\n        continue\n    a, b = abs(x - y), x + y\n    g = gcd(x, y)\n    split([a // g, b // g, g])\n\nprint('!', len(divs), ' '.join(str(d) for d in sorted(divs)))",
    "tags": [
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1091",
    "index": "H",
    "title": "New Year and the Tricolore Recreation",
    "statement": "Alice and Bob play a game on a grid with $n$ rows and infinitely many columns. In each row, there are three tokens, blue, white and red one. \\textbf{Before} the game starts and \\textbf{after every move}, the following two conditions must hold:\n\n- Any two tokens are not in the same cell.\n- In each row, the blue token is to the left of the white token, and the red token is to the right of the white token.\n\nFirst, they pick a positive integer $f$, whose value is valid for the whole game. Second, the starting player is chosen and makes his or her first turn. Then players take alternating turns. The player who is unable to make a move loses.\n\nDuring a move, a player first selects an integer $k$ that is either a prime number or a product of two (not necessarily distinct) primes. The smallest possible values of $k$ are thus $2, 3, 4, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 19, \\dots$. Furthermore, $k$ must not be equal to the previously picked integer $f$. Each turn, a move is performed in exactly one of the rows.\n\nIf it is Alice's turn, she chooses a single blue token and moves it $k$ cells to the right. Alternatively, she may move both the blue and the white token in the same row by the same amount $k$ to the right.\n\nOn the other hand, Bob selects a single red token and moves it $k$ cells to the left. Similarly, he may also move the white and the red token in the corresponding row by $k$ to the left.\n\nNote that Alice may never move a red token, while Bob may never move a blue one. Remember that after a move, the two conditions on relative positions of the tokens must still hold.\n\nBoth players play optimally. Given the initial state of the board, determine who wins for two games: if Alice starts and if Bob starts.",
    "tutorial": "If you represent the row state as a pair $(x,y)$ where $x$ is the distance between blue and white token and $y$ is the distance between white and red, we can see that each player has one operation that reduces $x$ by $k$, and a second operation which reduces $y$ by $k$. In other words, each $x$ and $y$ defines a symmetric game, and all games are independent. This is an impartial game after all! Once we have the Grundy numbers for each pile, we can use Sprague-Grundy theorem to find the answer. How to find the Grundy numbers? We find the set of primes and semiprime by sieving. To find the value of pile of size $n$, we can collect the Grundy numbers of each pile size reachable from $n$ (i.e. $n - p$ where p is a prime or semiprime), and then find the mex. This takes $\\mathcal O(m^2)$, where $m$ is the maximum distance between two tokens ($2*10^5$) and is too slow. To improve upon this, we can use bitset, but that's not enough. We actually need more of these! Maintain $k$ bitsets $G_0$, ..., $G_m$ where $i$-th bitset contains true at $j$-th position when there is a transition from state $j$ to state with grundy number $i$. How do you do that? You have one bitset $P$ storing all primes and semiprimes. For each $i$, preform linear search for the mex, let the grundy number be $j$. Then or $G_j$ with $P << i$. This works in $O(n^2/w)$. The maximum Grundy number given the input constraints is less than 100, so we can safely pick $k = 100$.",
    "code": "#include <vector>\n#include <stack>\n#include <iostream>\n#include <algorithm>\n#include <bitset>\nusing namespace std;\n\ntypedef unsigned int ui;\ntypedef long long ll;\n\nstruct Sieve : public std::vector<bool> {\n    // ~10ns * n\n\texplicit Sieve(ui n) : vector<bool>(n+1, true), n(n) {\n\t\tat(0) = false;\n\t\tif (n!=0) at(1) = false;\n\t\tfor (ui i = 2; i*i <= n; ++i) {\n\t\t\tif (at(i)) for (int j = i*i; j <= n; j+=i) (*this)[j] = false;\n\t\t}\n\t}\n\n\tvector<int> primes() const {\n\t\tvector<int> ans;\n\t\tfor (int i=2; i<=n; ++i) if (at(i)) ans.push_back(i);\n\t\treturn ans;\n\t}\n\nprivate:\n\tint n;\n};\n\nconstexpr int M = 2e5;\nauto P = Sieve{M}.primes();\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);\n\n    vector<int> G(M, 0);\n    int Q = P.size();\n    for (int i = 0; i < Q; ++i) {\n        for (int j = i; j < Q; ++j) {\n            if (ll(P[i])*P[j] >= M) break;\n            P.push_back(P[i]*P[j]);\n        }\n    }\n    \n    bitset<M> PB;\n    for (int p : P) PB[p] = true;\n    \n    int N, F; cin >> N >> F;\n    PB[F] = false;\n    \n    vector<bitset<M>> W(100);\n    W[0] = PB;\n    for (int i = 1; i < M; ++i) {\n        while (W[G[i]][i]) G[i]++;\n        W[G[i]] |= PB << i;\n    }\n    cerr << *max_element(G.begin(),G.end()) << endl;\n\n    int g = 0;\n    for (int i = 0; i < N; i++) {\n        int r,w,b;\n        cin >> r >> w >> b;\n        g ^= G[w-r-1];\n        g ^= G[b-w-1];\n    }\n    if (g == 0) {\n        cout << \"Bob\\nAlice\\n\";\n    } else {\n        cout << \"Alice\\nBob\\n\";\n    }\n}",
    "tags": [
      "games"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1092",
    "index": "A",
    "title": "Uniform String",
    "statement": "You are given two integers $n$ and $k$.\n\nYour task is to construct such a string $s$ of length $n$ that for each $i$ from $1$ to $k$ there is at least one $i$-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to \\textbf{maximize the minimal frequency} of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print \\textbf{any}.\n\nYou have to answer $t$ \\textbf{independent} queries.",
    "tutorial": "The only thing you need to do is to place letters by blocks $1, 2, \\dots, k$, $1, 2, \\dots, k$ and so on. The last block can contain less than $k$ letters but it is ok. It is easy to see that this letters distribution is always not worse than others.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\tfor (int i = 0; i < t; ++i) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tcout << char('a' + j % k);\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1092",
    "index": "B",
    "title": "Teams Forming",
    "statement": "There are $n$ students in a university. The number of students is even. The $i$-th student has programming skill equal to $a_i$.\n\nThe coach wants to form $\\frac{n}{2}$ teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equal (otherwise they cannot understand each other and cannot form a team).\n\nStudents can solve problems to increase their skill. One solved problem increases the skill by one.\n\nThe coach wants to know the minimum total number of problems students should solve to form exactly $\\frac{n}{2}$ teams (i.e. each pair of students should form a team). Your task is to find this number.",
    "tutorial": "If we sort the students in order of non-decreasing their skill, we can see that the minimum cost of the team with the lowest skill (let's call it the first team) is equal to $a_2 - a_1$ (if $a$ is already sorted), the cost of the second team is $a_4 - a_3$ and so on. So if we sort $a$ in non-decreasing order then the answer is $\\sum\\limits_{i = 1}^{\\frac{n}{2}} a_{2i} - a_{2i - 1}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tsort(a.begin(), a.end());\n\tint res = 0;\n\tfor (int i = 0; i < n; i += 2) {\n\t\tres += a[i + 1] - a[i];\n\t}\n\t\n\tcout << res << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1092",
    "index": "C",
    "title": "Prefixes and Suffixes",
    "statement": "Ivan wants to play a game with you. He picked some string $s$ of length $n$ consisting only of lowercase Latin letters.\n\nYou don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $1$ to $n-1$), but he didn't tell you which strings are prefixes and which are suffixes.\n\nIvan wants you to guess which of the given $2n-2$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!",
    "tutorial": "The first observation: if we will take two strings of length $n-1$ then we almost can restore the initial string. Why almost? Because there are two possible options: when the first string of length $n-1$ is a prefix and the second one is the suffix and vice versa. Let's write a function check(pref, suf) which will check if the first string can be the prefix of the guessed string and the second one can be the suffix. After we write this function, we can run it two times (depending on the order of strings of length $n-1$) and find any suitable answer. If the first string ($pref$) is the prefix and the second one ($suf$) is the suffix then the whole string $s = pref + suf_{n - 2}$ ($0$-indexed) where '+' is the concatenation of strings. Let's check if we have all prefixes and suffixes of this string in the input. We can easy do it with two nested loops and some boolean array which can say us if some string is already used or not. Firstly, let's iterate over the length of the prefix or suffix and inside let's find any string from the input matching to the current prefix or suffix. If we find all $2n - 2$ strings then the current string is one of the guessed and we can print the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nvector<string> v;\n\nstring res;\n\nbool check(const string &pref, const string &suf) {\n\tstring s = pref + suf.substr(n - 2);\n\tmultiset<string> vv, sPref, sSuf;\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tsPref.insert(s.substr(0, n - i - 1));\n\t\tvv.insert(s.substr(0, n - i - 1));\n\t\tsSuf.insert(s.substr(i + 1));\n\t\tvv.insert(s.substr(i + 1));\n\t}\n\tif (vv == multiset<string>(v.begin(), v.end())) {\n\t\tfor (int i = 0; i < 2 * n - 2; ++i) {\n\t\t\tif (sPref.count(v[i])) {\n\t\t\t\tres += 'P';\n\t\t\t\tsPref.erase(sPref.find(v[i]));\n\t\t\t} else if (sSuf.count(v[i])) {\n\t\t\t\tres += 'S';\n\t\t\t\tsSuf.erase(sSuf.find(v[i]));\n\t\t\t} else {\n\t\t\t\tassert(false);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n;\n\tv = vector<string>(2 * n - 2);\n\tvector<string> big;\n\tfor (int i = 0; i < 2 * n - 2; ++i) {\n\t\tcin >> v[i];\n\t\tif (int(v[i].size()) == n - 1) {\n\t\t\tbig.push_back(v[i]);\n\t\t}\n\t}\n\t\n\tif (check(big[0], big[1])) {\n\t\tcout << res << endl;\n\t} else {\n\t\tcheck(big[1], big[0]);\n\t\tcout << res << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1092",
    "index": "D1",
    "title": "Great Vova Wall (Version 1)",
    "statement": "Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.\n\nThe current state of the wall can be respresented by a sequence $a$ of $n$ integers, with $a_i$ being the height of the $i$-th part of the wall.\n\nVova can only use $2 \\times 1$ bricks to put in the wall (he has infinite supply of them, however).\n\nVova can put bricks \\textbf{horizontally} on the neighboring parts of the wall of equal height. It means that if for some $i$ the current height of part $i$ is the same as for part $i + 1$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $1$ of the wall or to the right of part $n$ of it).\n\n\\textbf{The next paragraph is specific to the version 1 of the problem.}\n\nVova can also put bricks vertically. That means increasing height of any part of the wall by 2.\n\nVova is a perfectionist, so he considers the wall completed when:\n\n- all parts of the wall has the same height;\n- the wall has no empty spaces inside it.\n\nCan Vova complete the wall using any amount of bricks (possibly zero)?",
    "tutorial": "Fairly enough, solutions of both versions of the problem are pretty similar. The major difference between them are the vertical bricks. As you aren't required to minimize the total height, you can work not with the heights themselves but with their parities instead. Vertical brick now does nothing and horizontal brick changes the parity of neighbouring parts of the same parity. Now imagine the following greedy solution. While you have some segment of the same parities of even length, fill it with horizontal bricks. This operation merges this segment with one to the left and to the right. If there is a single segment left then the answer is \"YES\". Otherwise it's \"NO\". The proof is left to the readers. Implementing this as it is will be $O(n \\log n)$ at best. You'll need to keep the whole set of segments and the set with only even length ones. But there exists more fun approach. We don't even need the lengths of the segments - just the parities of the lengths. Then merging the even segment with something will just erase that segment and xor the length of the left and right ones. Moreover, you don't even need to erase the whole even segment, you can do it brick by brick, as this operations are now the same. Let's simulate this with a stack. When the new number comes, push its parity to the stack. If the topmost two elements of the stack have the same parity, pop them both. Now the answer is \"YES\" if at the end stack has no more than one element. When I heard of this problem, I actually had not that stack itself in mind but the correct bracket sequences. Like let's define parity 0 as '(' and ')' and parity 1 as '[' and ']'. Now the operations we perform with stack are \"greedily put the closing bracket if the last unclosed bracket was of the same type\" and \"put opening otherwise\". Then the stack will have like all the brackets which are still to be closed and you'll close them as early as you can. This idea helped to both prove the correctness of algo and implement it. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\n\nint n;\nint a[N];\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n){\n\t\tscanf(\"%d\", &a[i]);\n\t\ta[i] &= 1;\n\t}\n\t\n\tset<pair<int, int>> seg, even;\n\tforn(i, n){\n\t\tint j = i;\n\t\twhile (j + 1 < n && a[j + 1] == a[i]) ++j;\n\t\tseg.insert({i, j});\n\t\tif ((j - i + 1) % 2 == 0)\n\t\t\teven.insert({i, j});\n\t\ti = j;\n\t}\n\t\n\twhile (seg.size() > 1 && !even.empty()){\n\t\tauto cur = *even.begin();\n\t\teven.erase(cur);\n\t\tseg.erase(cur);\n\t\tauto it = seg.lower_bound(cur);\n\t\tif (it != seg.end()){\n\t\t\tcur.second = it->second;\n\t\t\tif ((it->second - it->first + 1) % 2 == 0)\n\t\t\t\teven.erase(*it);\n\t\t\tseg.erase(it);\n\t\t}\n\t\tit = seg.lower_bound(cur);\n\t\tif (it != seg.begin()){\n\t\t\t--it;\n\t\t\tcur.first = it->first;\n\t\t\tif ((it->second - it->first + 1) % 2 == 0)\n\t\t\t\teven.erase(*it);\n\t\t\tseg.erase(it);\n\t\t}\n\t\tseg.insert(cur);\n\t\tif ((cur.second - cur.first + 1) % 2 == 0)\n\t\t\teven.insert(cur);\n\t}\n\t\n\tputs(seg.size() == 1 ? \"YES\" : \"NO\");\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1092",
    "index": "D2",
    "title": "Great Vova Wall (Version 2)",
    "statement": "Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.\n\nThe current state of the wall can be respresented by a sequence $a$ of $n$ integers, with $a_i$ being the height of the $i$-th part of the wall.\n\nVova can only use $2 \\times 1$ bricks to put in the wall (he has infinite supply of them, however).\n\nVova can put bricks \\textbf{only horizontally} on the neighbouring parts of the wall of equal height. It means that if for some $i$ the current height of part $i$ is the same as for part $i + 1$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $1$ of the wall or to the right of part $n$ of it).\n\n\\textbf{Note that Vova can't put bricks vertically.}\n\nVova is a perfectionist, so he considers the wall completed when:\n\n- all parts of the wall has the same height;\n- the wall has no empty spaces inside it.\n\nCan Vova complete the wall using any amount of bricks (possibly zero)?",
    "tutorial": "Fairly enough, solutions of both versions of the problem are pretty similar. Read the second part of the previous tutorial first. This problem can also be implemented in the strightforward manner. The greedy solution now is searching for the first minimum in array and putting a brick in there. If it's impossible then the answer is \"NO\". This can also be simulated with sets, a bit more tedious but still ok and also $O(n \\log n)$. Now back to the stack approach. Here you can't go to parities of the numbers (like tests $[1, 3]$ and $[1, 1]$ lead to different results). You push the number itself. However, you will also need an extra condition on the stack. You can't push to it the number greater than the current topmost element. The only problem with this are maximums of array. Obviously, the resulting wall (if the answer exists) will be of height equal to the maximum initial height. And it means that you shouldn't care about the ability to match all maximums in stack. They way I suggest to take around the issue is to process separately each segment between two consecutive maximums. One can easily prove the correctness of it by construction. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 1000 * 1000 + 13;\n\nint n;\nint a[N];\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tvector<int> st;\n\t\n\tint mx = *max_element(a, a + n);\n\t\n\tforn(i, n){\n\t\tif (a[i] == mx) continue;\n\t\t\n\t\tint j = i - 1;\n\t\twhile (j + 1 < n && a[j + 1] != mx){\n\t\t\t++j;\n\t\t\tif (!st.empty() && st.back() == a[j]){\n\t\t\t\tst.pop_back();\n\t\t\t}\n\t\t\telse if (st.empty() || st.back() > a[j]){\n\t\t\t\tst.push_back(a[j]);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tputs(\"NO\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!st.empty()){\n\t\t\tputs(\"NO\");\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\ti = j;\n\t}\n\t\n\tputs(\"YES\");\n\treturn 0;\n}\n",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1092",
    "index": "E",
    "title": "Minimal Diameter Forest",
    "statement": "You are given a forest — an undirected graph with $n$ vertices such that each its connected component is a tree.\n\nThe diameter (aka \"longest shortest path\") of a connected undirected graph is the maximum number of edges in the \\textbf{shortest} path between any pair of its vertices.\n\nYou task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.\n\nIf there are multiple correct answers, print any of them.",
    "tutorial": "Let's start with the solution and then proceed to the proof. For each tree in a forest find such a vertex that the maximal distance from it to any vertex is minimal possible (a center of a tree). Tree may include two centers, take any of them in that case. Find the the tree with the maximum diameter. Connect the centers of other trees with its center. Overall complexity is the complexity of looking for a diameter: $O(n)$ or $O(n^2)$. The center is the best vertex in a tree to connect to. The diameter of merging two trees $t_1$ and $t_2$ by $v$ in $t_1$ and $u$ in $t_2$ with $d_1$ being the maximum shortest path from $v$ to any other vertex in $t_1$, $d_2$ being the same for $u$ in $t_2$ is $max(diam_1, diam_2, d_1 + d_2 + 1)$. Thus minimizing both $d_1$ and $d_2$ will produce the best result. The most optimal structure is a star. The center tree will be connected directly to any other tree. The other trees will be connected through a single vertex among each other, which leads to the answer no more than 1 worse than connecting them directly. And building the answer the other way will exceed this difference as some tree will be connected to the center tree of the star through one vertex as well. The previous fact implies that the center tree of the star should have the maximal diameter among all trees.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\nconst int INF = 1000000000;\n\nint n, m;\nvector<int> g[N];\n\nint bfs(int x, int dist[N]){\n\tqueue<int> q;\n\tq.push(x);\n\tdist[x] = 0;\n\tint lst = -1;\n\twhile (!q.empty()){\n\t\tint v = q.front();\n\t\tq.pop();\n\t\tlst = v;\n\t\tfor (auto u : g[v]) if (dist[u] > dist[v] + 1){\n\t\t\tdist[u] = dist[v] + 1;\n\t\t\tq.push(u);\n\t\t}\n\t}\n\treturn lst;\n}\n\nint distx[N], disty[N];\nbool used[N];\nvector<int> cur;\n\nvoid dfs(int v){\n\tused[v] = true;\n\tcur.push_back(v);\n\tfor (auto u : g[v]) if (!used[u])\n\t\tdfs(u);\n}\n\nint main() {\n\tscanf(\"%d%d\", &n, &m);\n\tforn(i, m){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\t\n\tforn(i, n) distx[i] = disty[i] = INF;\n\t\n\tvector<pair<int, int>> comps;\n\tforn(i, n) if (!used[i]){\n\t\tcur.clear();\n\t\tdfs(i);\n\t\tint x = bfs(i, distx);\n\t\tint y = bfs(x, disty);\n\t\tfor (auto v : cur) distx[v] = INF;\n\t\tbfs(y, distx);\n\t\tint d = disty[y], center;\n\t\tfor (auto v : cur) if (distx[v] == d / 2 && disty[v] == d - d / 2)\n\t\t\tcenter = v;\n\t\tcomps.push_back({d, center});\n\t}\n\t\n\tvector<pair<int, int>> ans;\n\tnth_element(comp.begin(), comp.end() - 1, comp.end());\n\tforn(i, int(comps.size()) - 1){\n\t\tg[comps[i].second].push_back(comps.back().second);\n\t\tg[comps.back().second].push_back(comps[i].second);\n\t\tans.push_back({comps[i].second, comps.back().second});\n\t}\n\t\n\tforn(i, n) distx[i] = disty[i] = INF;\n\tint y = bfs(bfs(comps.back().second, distx), disty);\n\t\n\tprintf(\"%d\\n\", disty[y]);\n\tfor (auto it : ans)\n\t\tprintf(\"%d %d\\n\", it.first + 1, it.second + 1);\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1092",
    "index": "F",
    "title": "Tree with Maximum Cost",
    "statement": "You are given a tree consisting exactly of $n$ vertices. Tree is a connected undirected graph with $n-1$ edges. Each vertex $v$ of this tree has a value $a_v$ assigned to it.\n\nLet $dist(x, y)$ be the distance between the vertices $x$ and $y$. The distance between the vertices is the number of edges on the simple path between them.\n\nLet's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be $v$. Then the cost of the tree is $\\sum\\limits_{i = 1}^{n} dist(i, v) \\cdot a_i$.\n\nYour task is to calculate the \\textbf{maximum possible cost} of the tree if you can choose $v$ arbitrarily.",
    "tutorial": "Firstly, let's calculate the answer (let it be $res$) for some fixed vertex. Let this vertex be the vertex $1$. Just run simple dfs and calculate the result using the formula from the problem statement. Also let's calculate the sum of values (let the sum in the subtree of the vertex $v$ be $sum_v$) in each subtree of the given tree if its root is the vertex $1$. It can be easily done with simple dynamic programming. And now the magic part: let's apply the technique which is called \"re-rooting\" (at least we called it so). Let's maintain the correct values in subtrees at each step of our algorithm. How will values and the answer change if we will go through the edge $(u, v)$? The following sequence of changes will change all values correctly: Firstly, it can be seen that $res$ will decrease by $sum_v$ (because the distance to each vertex in this subtree will decrease by one); then $sum_u$ will decrease by $sum_v$ (because we change the root of the tree) (we need this step to maintain the correct values); then $res$ will increase by $sum_u$ (because the distance to each vertex in this subtree will increase by one); and then $sum_v$ will increase by $sum_u$ (because we change the root of the tree) (we need this step to maintain the correct values). So, we can recalculate all the values we need if we go through the edge. So now we can write another one dfs to try to update the answer for each vertex as a root (as the chosen vertex).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long res, ans;\n\nvector<int> a;\nvector<long long> sum;\nvector<vector<int>> g;\n\nvoid dfs(int v, int p = -1, int h = 0) {\n\tres += h * 1ll * a[v];\n\tsum[v] = a[v];\n\t\n\tfor (auto to : g[v]) {\n\t\tif (to == p) {\n\t\t\tcontinue;\n\t\t}\n\t\tdfs(to, v, h + 1);\n\t\tsum[v] += sum[to];\n\t}\n}\n\nvoid go(int v, int p = -1) {\n\tans = max(ans, res);\n\t\n\tfor (auto to : g[v]) {\n\t\tif (to == p) {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tres -= sum[to];\n\t\tsum[v] -= sum[to];\n\t\tres += sum[v];\n\t\tsum[to] += sum[v];\n\t\t\n\t\tgo(to, v);\n\t\t\n\t\tsum[to] -= sum[v];\n\t\tres -= sum[v];\n\t\tsum[v] += sum[to];\n\t\tres += sum[to];\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\ta = vector<int>(n);\n\tsum = vector<long long>(n);\n\tg = vector<vector<int>>(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\t\n\tdfs(0);\n\tgo(0);\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1093",
    "index": "A",
    "title": "Dice Rolling",
    "statement": "Mishka got a six-faced dice. It has integer numbers from $2$ to $7$ written on its faces (all numbers on faces are different, so this is an \\textbf{almost} usual dice).\n\nMishka wants to get exactly $x$ points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls Mishka makes.\n\nMishka doesn't really care about the number of rolls, so he just wants to know \\textbf{any} number of rolls he can make to be able to get exactly $x$ points for them. \\textbf{Mishka is very lucky, so if the probability to get $x$ points with chosen number of rolls is non-zero, he will be able to roll the dice in such a way.} Your task is to print this number. It is \\textbf{guaranteed} that at least one answer exists.\n\nMishka is also very curious about different number of points to score so you have to answer $t$ \\textbf{independent} queries.",
    "tutorial": "It is enough to print $\\lfloor\\frac{x_i}{2}\\rfloor$ for each query, where $\\lfloor\\frac{x}{y}\\rfloor$ is $x$ divided by $y$ rounded down.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\tfor (int i = 0; i < t; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\tcout << x / 2 << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1093",
    "index": "B",
    "title": "Letters Rearranging",
    "statement": "You are given a string $s$ consisting only of lowercase Latin letters.\n\nYou can rearrange all letters of this string as you wish. Your task is to obtain a \\textbf{good} string by rearranging the letters of the given string or report that it is impossible to do it.\n\nLet's call a string \\textbf{good} if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings \"abacaba\", \"aa\" and \"z\" are palindromes and strings \"bba\", \"xd\" are not.\n\nYou have to answer $t$ \\textbf{independent} queries.",
    "tutorial": "The only case when the answer is -1 is when all letters of the string are equal. Why is it so? Because if we have at least two different letters we can place the first one at the first position of the string and the second one at the last position of the string. Then it is clearly that the obtained string is good. We can implement this solution by the following way: sort $s_i$ and if $s_{i, 1} = s_{i, |s_i|}$ (the first letter equals to the last one) then the answer is -1 otherwise the answer is $s_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\tfor (int i = 0; i < t; ++i) {\n\t\tstring s;\n\t\tcin >> s;\n\t\tsort(s.begin(), s.end());\n\t\tif (s[0] == s.back()) cout << -1 << endl;\n\t\telse cout << s << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1093",
    "index": "C",
    "title": "Mishka and the Last Exam",
    "statement": "Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.\n\nThere were $n$ classes of that subject during the semester and on $i$-th class professor mentioned some non-negative integer $a_i$ to the students. It turned out, the exam was to tell the whole sequence back to the professor.\n\nSounds easy enough for those who attended every class, doesn't it?\n\nObviously Mishka didn't attend any classes. However, professor left some clues on the values of $a$ to help out students like Mishka:\n\n- $a$ was sorted in non-decreasing order ($a_1 \\le a_2 \\le \\dots \\le a_n$);\n- $n$ was even;\n- the following sequence $b$, consisting of $\\frac n 2$ elements, was formed and given out to students: $b_i = a_i + a_{n - i + 1}$.\n\nProfessor also mentioned that any sequence $a$, which produces sequence $b$ with the presented technique, will be acceptable.\n\nHelp Mishka to pass that last exam. Restore any sorted sequence $a$ of non-negative integers, which produces sequence $b$ with the presented technique. It is guaranteed that there exists at least one correct sequence $a$, which produces the given sequence $b$.",
    "tutorial": "Let's present the following greedy approach. The numbers will be restored in pairs $(a_1, a_n)$, $(a_2, a_{n - 1})$ and so on. Thus, we can have some limits on the values of the current pair (satisfying the criteria about sort). Initially, $l = 0, r = 10^{18}$ and they are updated with $l = a_i, r = a_{n - i + 1}$. Let $l$ be minimal possible in the answer. Take $a_i = max(l, b_i - r)$ and $r = b_i - l$. That way $l$ was chosen in such a way that both $l$ and $r$ are within the restrictions and $l$ is also minimal possible. If $l$ was any greater than we would move both $l$ limit up and $r$ limit down leaving less freedom for later choices. Overall complexity: $O(n)$. Funnily enough, I coded some naive solution just to test main correct and with restriction of $10^9$ on numbers it passed all tests in 300 ms at max. After I saw that I guessed why it worked in $O(MAXVAL)$ but it looked fun nonetheless.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst long long INF64 = 1'000'000'000'000'000'000ll;\nconst int N = 200 * 1000 + 13;\n\nint n;\nlong long a[N], b[N];\n\nvoid brute(int x, long long l, long long r){\n\tif (x == n / 2){\n\t\tforn(i, n)\n\t\t\tprintf(\"%lld \", a[i]);\n\t\tputs(\"\");\n\t\texit(0);\n\t}\n\t\n\tfor (long long i = l; i <= b[x] / 2; ++i) if (b[x] - i <= r){\n\t\ta[x] = i;\n\t\ta[n - x - 1] = b[x] - i;\n\t\tbrute(x + 1, i, b[x] - i);\n\t}\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n / 2)\n\t\tscanf(\"%lld\", &b[i]);\n\tbrute(0, 0, INF64);\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1093",
    "index": "D",
    "title": "Beautiful Graph",
    "statement": "You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges.\n\nYou have to write a number on each vertex of the graph. Each number should be $1$, $2$ or $3$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.\n\nCalculate the number of possible ways to write numbers $1$, $2$ and $3$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $998244353$.\n\n\\textbf{Note that you have to write exactly one number on each vertex}.\n\nThe graph does not have any self-loops or multiple edges.",
    "tutorial": "Let's denote a way to distribute numbers as a painting. Let's also call the paintings that meet the constraints good paintings (and all other paintings are bad). We can solve the problem for each connected component of the graph independently and multiply the answers. Let's analyze a painting of some connected component. If some vertex has an odd number written on it, then we should write even numbers on all adjacent vertices, and vice versa. So in fact we need to check if the component is bipartite, and if it is, divide it into two parts. The number of good paintings is $2^{a} + 2^b$, where $a$ is the size of the first part, and $b$ is the size of the second part, because we write $2$'s into all vertices of one part, and $1$'s or $3$'s into all vertices of another part.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 999;\nconst int MOD = 998244353;\n\nint n, m;\nvector <int> g[N];\nint p2[N];\nint cnt[2];\nint col[N];\nbool bad;\n\nvoid dfs(int v, int c){\n\tcol[v] = c;\n\t++cnt[c];\n\tfor(auto to : g[v]){\n\t\tif(col[to] == -1) dfs(to, 1 - c);\n\t\tif((col[v] ^ col[to]) == 0)\n\t\t\tbad = true;\n\t}\n}\n\nint main() {\n    p2[0] = 1;\n    for(int i = 1; i < N; ++i)\n    \tp2[i] = (2 * p2[i - 1]) % MOD;\n    \t\n    int tc;\n    scanf(\"%d\", &tc);\n    while(tc--){\n    \tscanf(\"%d%d\", &n, &m);\n    \tfor(int i = 0; i < n; ++i)\n    \t    g[i].clear();\n    \t\n    \tfor(int i = 0; i < m; ++i){\n    \t\tint u, v;\n    \t\tscanf(\"%d %d\", &u, &v);\n    \t\t--u, --v;\n    \t\tg[u].push_back(v);\n    \t\tg[v].push_back(u);\n    \t}\n    \t\n    \tint res = 1;\n    \tfor(int i = 0; i < n; ++i) col[i] = -1;\n    \tfor(int i = 0; i < n; ++i){\n    \t    if(col[i] != -1) continue;\n            bad = false;\n            cnt[0] = cnt[1] = 0;\n            dfs(i, 0);\n    \t    if(bad){\n    \t\t    puts(\"0\");\n    \t\t    break;\n    \t    }\n    \t    int cur = (p2[cnt[0]] + p2[cnt[1]]) % MOD;\n    \t    res = (res * 1LL * cur) % MOD;\n    \t}\n    \t\n    \tif(!bad) printf(\"%d\\n\", res);\n    }\n    \n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1093",
    "index": "E",
    "title": "Intersection of Permutations",
    "statement": "You are given two permutations $a$ and $b$, both consisting of $n$ elements. Permutation of $n$ elements is such a integer sequence that each value from $1$ to $n$ appears exactly once in it.\n\nYou are asked to perform two types of queries with them:\n\n- $1~l_a~r_a~l_b~r_b$ — calculate the number of values which appear in both segment $[l_a; r_a]$ of positions in permutation $a$ and segment $[l_b; r_b]$ of positions in permutation $b$;\n- $2~x~y$ — swap values on positions $x$ and $y$ in permutation $b$.\n\nPrint the answer for each query of the first type.\n\nIt is guaranteed that there will be at least one query of the first type in the input.",
    "tutorial": "At first, time limit was not that tight for the problem. We didn't want any sqrt, bitset or straight up $nm$ solution to pass (and it's close to none to pass). Jury solution works faster than twice the time limit so we decided 6 seconds is alright. The task is purely about implementation. You renumerate numbers in permutations so that the queries are (segment of values, segment of positions) and then have the structure to make update in point and sum on rectangle. Renumeration in my case was making the first permutation into identity one and changing the numbers in second appropriately. You can choose the structure you want, I'll tell about the one I use when the queries are offline. For online the common technique is having $n$ BITs, each with treap in it (ordered_set template from pbds is usually enough). For offline you can precalculate the values to fall into each BIT beforehand and do BIT on these values inside. Preprocess all the update and get queries $(x, y)$, adding $y$ into all the BITs $x$ will fall into. Then sort them and leave only unique occurrences. Overall complexity: $O((n + m) \\cdot \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\n\nint n, m;\nint a[N], b[N], pos[N];\n\nvector<int> f[N];\nvector<int> vals[N];\n\nvoid addupd(int x, int y){\n\tfor (int i = x; i < N; i |= i + 1)\n\t\tvals[i].push_back(y);\n}\n\nvoid addget(int x, int y){\n\tif (x < 0 || y < 0) return;\n\tfor (int i = x; i >= 0; i = (i & (i + 1)) - 1)\n\t\tvals[i].push_back(y);\n}\n\nvoid upd(int x, int y, int val){\n\tfor (int i = x; i < N; i |= i + 1)\n\t\tfor (int j = lower_bound(vals[i].begin(), vals[i].end(), y) - vals[i].begin(); j < int(f[i].size()); j |= j + 1)\n\t\t\tf[i][j] += val;\n}\n\nint get(int x, int y){\n\tif (x < 0 || y < 0) return 0;\n\tint res = 0;\n\tfor (int i = x; i >= 0; i = (i & (i + 1)) - 1)\n\t\tfor (int j = lower_bound(vals[i].begin(), vals[i].end(), y) - vals[i].begin(); j >= 0; j = (j & (j + 1)) - 1)\n\t\t\tres += f[i][j];\n\treturn res;\n}\n\nstruct query{\n\tint t, la, ra, lb, rb;\n\tquery(){};\n};\n\nquery q[N];\n\nint main() {\n\tscanf(\"%d%d\", &n, &m);\n\t\n\tforn(i, n){\n\t\tscanf(\"%d\", &a[i]);\n\t\t--a[i];\n\t\tpos[a[i]] = i;\n\t}\n\t\n\tforn(i, n){\n\t\tscanf(\"%d\", &b[i]);\n\t\t--b[i];\n\t\tb[i] = pos[b[i]];\n\t}\n\t\n\tforn(i, m){\n\t\tscanf(\"%d\", &q[i].t);\n\t\tif (q[i].t == 1){\n\t\t\tscanf(\"%d%d%d%d\", &q[i].la, &q[i].ra, &q[i].lb, &q[i].rb);\n\t\t\t--q[i].la, --q[i].ra, --q[i].lb, --q[i].rb;\n\t\t}\n\t\telse{\n\t\t\tscanf(\"%d%d\", &q[i].lb, &q[i].rb);\n\t\t\t--q[i].lb, --q[i].rb;\n\t\t}\n\t}\n\t\n\tvector<int> tmp(b, b + n);\n\t\n\tforn(i, n) addupd(i, b[i]);\n\tforn(i, m){\n\t\tif (q[i].t == 1){\n\t\t\taddget(q[i].rb, q[i].ra);\n\t\t\taddget(q[i].lb - 1, q[i].ra);\n\t\t\taddget(q[i].rb, q[i].la - 1);\n\t\t\taddget(q[i].lb - 1, q[i].la - 1);\n\t\t}\n\t\telse{\n\t\t\taddupd(q[i].lb, b[q[i].lb]);\n\t\t\taddupd(q[i].rb, b[q[i].rb]);\n\t\t\tswap(b[q[i].lb], b[q[i].rb]);\n\t\t\taddupd(q[i].lb, b[q[i].lb]);\n\t\t\taddupd(q[i].rb, b[q[i].rb]);\n\t\t}\n\t}\n\t\n\tforn(i, n) b[i] = tmp[i];\n\t\n\tforn(i, N){\n\t\tsort(vals[i].begin(), vals[i].end());\n\t\tvals[i].resize(unique(vals[i].begin(), vals[i].end()) - vals[i].begin());\n\t\tf[i].resize(vals[i].size(), 0);\n\t}\n\t\n\tforn(i, n)\n\t\tupd(i, b[i], 1);\n\t\n\tforn(i, m){\n\t\tif (q[i].t == 1){\n\t\t\tint res = 0;\n\t\t\tres += get(q[i].rb, q[i].ra);\n\t\t\tres -= get(q[i].lb - 1, q[i].ra);\n\t\t\tres -= get(q[i].rb, q[i].la - 1);\n\t\t\tres += get(q[i].lb - 1, q[i].la - 1);\n\t\t\tprintf(\"%d\\n\", res);\n\t\t}\n\t\telse{\n\t\t\tupd(q[i].lb, b[q[i].lb], -1);\n\t\t\tupd(q[i].rb, b[q[i].rb], -1);\n\t\t\tswap(b[q[i].lb], b[q[i].rb]);\n\t\t\tupd(q[i].lb, b[q[i].lb], 1);\n\t\t\tupd(q[i].rb, b[q[i].rb], 1);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1093",
    "index": "F",
    "title": "Vasya and Array",
    "statement": "Vasya has got an array consisting of $n$ integers, and two integers $k$ and $len$ in addition. All numbers in the array are either between $1$ and $k$ (inclusive), or equal to $-1$. The array is good if there is no segment of $len$ consecutive \\textbf{equal} numbers.\n\nVasya will replace each $-1$ with some number from $1$ to $k$ (inclusive) in such a way that the resulting array is good. Tell him the number of ways to do this replacement. Since the answer may be large, print it modulo $998244353$.",
    "tutorial": "Let's try dynamic programming approach to this problem. Let $dp_{cnt, lst}$ be the number of ways to replace all $-1$ with numbers from $1$ to $k$ in such a way that array $a_{1 \\dots cnt}$ is good and the last number of that array is $lst$. Let $sdp_{cnt} = \\sum\\limits_{i=1}^{k} dp_{cnt, i}$. Then initially it's $dp_{cnt, lst} = sdp_{cnt-1}$ if $a_{cnt}$ equals to $-1$ or $lst$. However, we could include incorrect states - such that segment $[a_{cnt-len+1} \\dots a_{cnt}]$ consist of the same value. It happens when: $cnt \\ge len$, as we should have at least $len$ elements; segment $[a_{cnt-len+1} \\dots a_{cnt}]$ has all its elements either equal to $-1$ or $lst$. If both of these conditions hold then you should subtract all the bad states from $dp_{cnt, lst}$. The number of them is $sdp_{cnt-len} - dp_{cnt-len, lst}$.",
    "code": "#include <bits/stdc++.h>\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); ++i)\n#define forn(i, n) fore(i, 0, n)\n#define nfor(i, n) for(int i = int(n) - 1; i >= 0; --i)\n#define for1(i, n) for(int i = 1; i < int(n); ++i)\n\n#define mp make_pair\n#define pb push_back\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define x first\n#define y second\n\n#define correct(x, y, xmax, ymax) ((x) >= 0 && (x) < (xmax) && (y) >= 0 && (y) < (ymax))\n#define max(a, b) ((a > b)? a : b)\n#define min(a, b) ((a < b)? a : b)\n#define abs(a) ((a < 0) ? -a : a)\n#define sqr(a) (a * a)\n\nusing namespace std;\n\nconst int N = int(1e5);\nconst int M = 105;\nconst int MOD = 998244353;\n\nint sum(int a, int b){\n\treturn (a + b) % MOD;\t\n}\n\nint n, k, len;\nint a[N];\nint dp[N][M];\nint sumdp[N];\nint cnt[M][N];\n\nint main() {\n\tscanf(\"%d %d %d\", &n, &k, &len);\n\tforn(i, n){ \t\n\t\tscanf(\"%d\", a + i);\n\t\tif(a[i] != -1) --a[i];\n\t}\n    forn(i, k) \n        forn(j, n)\n            cnt[i][j + 1] = cnt[i][j] + (a[j] == i || a[j] == -1);\n            \n\tforn(i, n){ \n\t\tforn(j, k){\n\t\t\tif(!(a[i] == -1 || a[i] == j))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tint add = 1;\n\t\t\tif(i > 0) add = sumdp[i - 1];\n\t\t\tdp[i][j] = add;\n\t\t\t\n\t\t\tbool ok = i + 1 >= len;\n\t\t\tint l = max(0, i - len + 1);\n\t\t\tint r = i + 1;\n\t\t\tok &= (r - l == cnt[j][r] - cnt[j][l]); \n\t\t\tif(!ok) continue;\n\t\t\t\n\t\t\tif(i + 1 == len){\n\t\t\t\tdp[i][j] = sum(dp[i][j], MOD - 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tadd = sum(dp[i - len][j], MOD - sumdp[i - len]);\n\t\t\tdp[i][j] = sum(dp[i][j], add);\n\t\t}\n\t\tforn(j, k) sumdp[i] = sum(sumdp[i], dp[i][j]);\n\t}\n\t\n\tprintf(\"%d\\n\", sumdp[n - 1]);\n\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1093",
    "index": "G",
    "title": "Multidimensional Queries",
    "statement": "You are given an array $a$ of $n$ points in $k$-dimensional space. Let the distance between two points $a_x$ and $a_y$ be $\\sum \\limits_{i = 1}^{k} |a_{x, i} - a_{y, i}|$ (it is also known as Manhattan distance).\n\nYou have to process $q$ queries of the following two types:\n\n- $1$ $i$ $b_1$ $b_2$ ... $b_k$ — set $i$-th element of $a$ to the point $(b_1, b_2, \\dots, b_k)$;\n- $2$ $l$ $r$ — find the maximum distance between two points $a_i$ and $a_j$, where $l \\le i, j \\le r$.",
    "tutorial": "Let's rewrite the formula of distance between two points as follows: $\\sum \\limits_{i = 1}^{k} |a_{x, i} - a_{y, i}| = \\sum \\limits_{i = 1}^{k} c_i (a_{x, i} - a_{y, i}) = \\sum \\limits_{i = 1}^{k} c_i a_{x, i} - \\sum \\limits_{i = 1}^{k} c_i a_{y, i}$, where $c_i = 1$ if $a_{x, i} \\ge a_{y, i}$, otherwise $c_i = -1$. Consider what will happen if we change some $c_i$ to the opposite value. The result of this formula obviously won't increase, so we may try all possible values of $c_i$ and pick maximum result. This allows us to consider every option to set values of $c_i$ (there are $2^k$ such options) separately, and when we fix a set of values of $c_i$, find two points that maximize the distance if it is expressed with fixed $c_i$. To do so, we have to find the point having maximum $\\sum \\limits_{i = 1}^{k} c_i a_{x, i}$ and having minimum $\\sum \\limits_{i = 1}^{k} c_i a_{x, i}$. So actually our problem is reduced to the following: we have $2^k$ arrays, we want to process some queries in the form \"change an element of some array\" and \"find maximum and minimum on some segment of some array\". This can be done simply by building a segment tree over each array, and then we will get the solution having $O((n + q) 2^k \\log n)$ time complexity.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\nconst int INF = 1e9;\n\nstruct point{\n\tint a[5];\n\tpoint(){};\n\tint& operator[](int x){\n\t\treturn a[x];\n\t}\n};\n\nint n, k;\npoint a[N];\n\nint t[32][4 * N];\n\nint apply(point& p, int mask){\n\tint res = 0;\n\tforn(i, k){\n\t\tres += (mask & 1 ? p[i] : -p[i]);\n\t\tmask >>= 1;\n\t}\n\treturn res;\n}\n\nvoid build(int v, int l, int r){\n\tif (l == r - 1){\n\t\tforn(mask, 1 << k)\n\t\t\tt[mask][v] = apply(a[l], mask);\n\t\treturn;\n\t}\n\t\n\tint m = (l + r) / 2;\n\t\n\tbuild(v * 2, l, m);\n\tbuild(v * 2 + 1, m, r);\n\t\n\tforn(mask, 1 << k)\n\t\tt[mask][v] = min(t[mask][v * 2], t[mask][v * 2 + 1]);\n}\n\nvoid upd(int v, int l, int r, int pos, point& val){\n\tif (l == r - 1){\n\t\tforn(mask, 1 << k)\n\t\t\tt[mask][v] = apply(val, mask);\n\t\treturn;\n\t}\n\t\n\tint m = (l + r) / 2;\n\t\n\tif (pos < m)\n\t\tupd(v * 2, l, m, pos, val);\n\telse\n\t\tupd(v * 2 + 1, m, r, pos, val);\n\t\n\tforn(mask, 1 << k)\n\t\tt[mask][v] = min(t[mask][v * 2], t[mask][v * 2 + 1]);\n}\n\nint bst[32];\n\nvoid get(int v, int l, int r, int L, int R){\n\tif (L >= R)\n\t\treturn;\n\t\n\tif (l == L && r == R){\n\t\tforn(mask, 1 << k)\n\t\t\tbst[mask] = min(bst[mask], t[mask][v]);\n\t\treturn;\n\t}\n\t\n\tint m = (l + r) / 2;\n\t\n\tget(v * 2, l, m, L, min(m, R));\n\tget(v * 2 + 1, m, r, max(m, L), R);\n}\n\nint main() {\n\tscanf(\"%d%d\", &n, &k);\n\tforn(i, n) forn(j, k)\n\t\tscanf(\"%d\", &a[i][j]);\n\tbuild(1, 0, n);\n\t\n\tint m;\n\tscanf(\"%d\", &m);\n\tforn(_, m){\n\t\tint t;\n\t\tscanf(\"%d\", &t);\n\t\tif (t == 1){\n\t\t\tint i;\n\t\t\tscanf(\"%d\", &i);\n\t\t\t--i;\n\t\t\tpoint tmp;\n\t\t\tforn(j, k)\n\t\t\t\tscanf(\"%d\", &tmp[j]);\n\t\t\tupd(1, 0, n, i, tmp);\n\t\t}\n\t\telse{\n\t\t\tint l, r;\n\t\t\tscanf(\"%d%d\", &l, &r);\n\t\t\t--l, --r;\n\t\t\tforn(mask, 1 << k)\n\t\t\t\tbst[mask] = INF;\n\t\t\tget(1, 0, n, l, r + 1);\n\t\t\t\n\t\t\tint ans = 0;\n\t\t\tforn(mask, 1 << k)\n\t\t\t\tans = max(ans, abs(bst[(1 << k) - 1 - mask] + bst[mask]));\n\t\t\tprintf(\"%d\\n\", ans);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "data structures"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1095",
    "index": "A",
    "title": "Repeating Cipher",
    "statement": "Polycarp loves ciphers. He has invented his own cipher called repeating.\n\nRepeating cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \\dots s_{m}$ ($1 \\le m \\le 10$), Polycarp uses the following algorithm:\n\n- he writes down $s_1$ ones,\n- he writes down $s_2$ twice,\n- he writes down $s_3$ three times,\n- ...\n- he writes down $s_m$ $m$ times.\n\nFor example, if $s$=\"bab\" the process is: \"b\" $\\to$ \"baa\" $\\to$ \"baabbb\". So the encrypted $s$=\"bab\" is \"baabbb\".\n\nGiven string $t$ — the result of encryption of some string $s$. Your task is to decrypt it, i. e. find the string $s$.",
    "tutorial": "There are many possible approaches in this problem, I will describe one of the easiest. Let's print the initial string by the following algorithm: firstly, init the variable $i = 1$. Then, while the encrypted string isn't empty, print the first character of this string, remove $i$ first characters from it and increase $i$ by one.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    int index = 0;\n    int gap = 1;\n    while (index < n)\n        cout << s[index], index += gap, gap++;\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1095",
    "index": "B",
    "title": "Array Stabilization",
    "statement": "You are given an array $a$ consisting of $n$ integer numbers.\n\nLet instability of the array be the following value: $\\max\\limits_{i = 1}^{n} a_i - \\min\\limits_{i = 1}^{n} a_i$.\n\nYou have to remove \\textbf{exactly one} element from this array to minimize instability of the resulting $(n-1)$-elements array. Your task is to calculate the minimum possible instability.",
    "tutorial": "It is easy to see that we always have to remove either minimum or maximum of the array. So we can sort the array and the answer will be $min(a_{n - 1} - a_{1}, a_{n} - a_{2})$. We also can do it without sort because two minimal and two maximal elements of the array can be found in linear time.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.begin(), a.end());\n\t\n\tcout << min(a[n - 2] - a[0], a[n - 1] - a[1]) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1095",
    "index": "C",
    "title": "Powers Of Two",
    "statement": "A positive integer $x$ is called a power of two if it can be represented as $x = 2^y$, where $y$ is a non-negative integer. So, the powers of two are $1, 2, 4, 8, 16, \\dots$.\n\nYou are given two positive integers $n$ and $k$. Your task is to represent $n$ as the \\textbf{sum} of \\textbf{exactly} $k$ powers of two.",
    "tutorial": "First of all, let's analyze how can we calculate the minimum number of powers of two needed to get $n$ as the sum. We can use binary representation of $n$: each bit in it, which is equal to $1$, becomes a summand in the answer. Firstly, if the number of summands is greater than $k$ then the answer is NO. Okay, what if we don't have enough summands? Every summand $x > 1$ can be broken down into two summands equal to $\\frac{x}{2}$. Let's maintain all summands greater than $1$ somewhere (stack, array, queue, multiset, anything you want), and pick an arbitrary summand and break it into two until we have exactly $k$ summands. If $n \\ge k$, then this process will terminate since we will have some summand to pick until all of them are equal to $1$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tmap<int, int> ans;\n\tqueue<int> q;\n\tfor(int i = 0; i <= 30; i++)\n\t\tif(n & (1 << i))\n\t\t{\n\t\t\tif(i > 0) q.push(1 << i);\n\t\t\tans[1 << i]++;\n\t\t}\n\tif(int(ans.size()) > k)\n\t{\n\t\tputs(\"NO\");\n\t\treturn 0;\n\t}\n\tint cnt = ans.size();\n\twhile(cnt < k && !q.empty())\n\t{\n\t\tint z = q.front();\n\t\tq.pop();\n\t\tans[z]--;\n\t\tans[z / 2] += 2;\n\t\tif(z / 2 > 1)\n\t\t{\n\t\t\tq.push(z / 2);\n\t\t\tq.push(z / 2);\n\t\t}\n\t\tcnt++;\n\t}\n\tif(cnt < k)\n\t{\n\t\tputs(\"NO\");\n\t\treturn 0;\n\t}\n\tputs(\"YES\");\n\tfor(auto x : ans)\n\t\tfor(int i = 0; i < x.second; i++)\n\t\t\tprintf(\"%d \", x.first);\n\tputs(\"\");\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1095",
    "index": "D",
    "title": "Circular Dance",
    "statement": "There are $n$ kids, numbered from $1$ to $n$, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as $p_1$, $p_2$, ..., $p_n$ (all these numbers are from $1$ to $n$ and are distinct, so $p$ is a permutation). Let the next kid for a kid $p_i$ be kid $p_{i + 1}$ if $i < n$ and $p_1$ otherwise. After the dance, each kid remembered two kids: the next kid (let's call him $x$) and the next kid for $x$. Each kid told you which kids he/she remembered: the kid $i$ remembered kids $a_{i, 1}$ and $a_{i, 2}$. However, the order of $a_{i, 1}$ and $a_{i, 2}$ can differ from their order in the circle.\n\n\\begin{center}\n{\\small Example: 5 kids in a circle, $p=[3, 2, 4, 1, 5]$ (or any cyclic shift). The information kids remembered is: $a_{1,1}=3$, $a_{1,2}=5$; $a_{2,1}=1$, $a_{2,2}=4$; $a_{3,1}=2$, $a_{3,2}=4$; $a_{4,1}=1$, $a_{4,2}=5$; $a_{5,1}=2$, $a_{5,2}=3$.}\n\\end{center}\n\nYou have to restore the order of the kids in the circle using this information. If there are several answers, you may print any. It is guaranteed that at least one solution exists.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "Let's write a function check(a, b) which will try to restore the circle if kid with number $b$ comes right after kid with number $a$. If $b$ comes right after $a$ then we can determine $c$ - the number of kid who is next to kid $b$. So now we have: $b$ comes right after $a$, $c$ comes right after $b$. Let's determine $d$ - kid who is next to kid $c$. If we repeat this operation $n$ times then we can \"determine\" the answer if $b$ comes right after $a$. But it can be wrong so we have to check that our answer corresponds to the input. So if we have this function, we can apply it two times to determine the correct answer. Just call check($1, a_{1, 1}$) and check($1, a_{1, 2}$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nvector<vector<int>> a;\n\nvoid check(int l, int r) {\n\tvector<int> ans;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint nxt = -1;\n\t\tif (a[l][0] == r) {\n\t\t\tnxt = a[l][1];\n\t\t} else if (a[l][1] == r) {\n\t\t\tnxt = a[l][0];\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t\tans.push_back(nxt);\n\t\tl = r;\n\t\tr = nxt;\n\t}\n\tfor (auto it : ans) {\n\t\tcout << it + 1 << \" \";\n\t}\n\tcout << endl;\n\texit(0);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n;\n\ta = vector<vector<int>> (n, vector<int>(2));\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i][0] >> a[i][1];\n\t\t--a[i][0];\n\t\t--a[i][1];\n\t}\n\t\n\tcheck(0, a[0][0]);\n\tcheck(0, a[0][1]);\n\t\n\tassert(false);\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1095",
    "index": "E",
    "title": "Almost Regular Bracket Sequence",
    "statement": "You are given a bracket sequence $s$ consisting of $n$ opening '(' and closing ')' brackets.\n\nA regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences \"()()\", \"(())\" are regular (the resulting expressions are: \"(1)+(1)\", \"((1+1)+1)\"), and \")(\" and \"(\" are not.\n\nYou can change the type of some bracket $s_i$. It means that if $s_i = $ ')' then you can change it to '(' and vice versa.\n\nYour task is to calculate the number of positions $i$ such that if you change the type of the $i$-th bracket, then the resulting bracket sequence becomes regular.",
    "tutorial": "In this problem we have to calculate the number (count) of positions such that if we change the type of the bracket at this position then the obtained bracket sequence will become regular. Let's calculate the balance of each prefix of the bracket sequence and store it in the array $prefBal$. Just iterate from left to right over the string and if the current bracket is opening then increase the current balance by one, otherwise decrease it by one. For each prefix let's also calculate whether it can be a prefix of a regular bracket sequence (RBS) and store it in the array $prefCan$. The prefix of length $i$ can be the prefix of RBS if and only if the prefix of length $i-1$ can be the prefix of RBS and $prefBal_i \\ge 0$. Let's calculate the same arrays for all suffixes (and call they $sufBal$ and $sufCan$ correspondingly), but now the closing bracket will increase the balance by one and the opening will decrease it by one and we consider the characters from right to left. Now if we have these arrays, let's iterate over all positions in the initial bracket sequence. If we now at the position $i$ then let's do the following things: firstly, if $prefCan_{i} = false$ or $sufCan_{i} = false$ then skip this position. Otherwise if the current bracket is opening then we have to increase the answer if $prefBal_{i-1} > 0$ and $prefBal_{i - 1} - 1 + sufBal_{i + 1} = 0$ (only in this case the bracket sequence will become regular). And if the current bracket is closing then we have to increase the answer if $prefBal_{i - 1} + 1 - sufBal_{i + 1} = 0$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\t\n\tstring rs(s.rbegin(), s.rend());\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (rs[i] == '(') {\n\t\t\trs[i] = ')';\n\t\t} else {\n\t\t\trs[i] = '(';\n\t\t}\n\t}\n\t\n\tvector<int> pref(n + 1), suf(n + 1);\n\tvector<bool> okp(n + 1), oks(n + 1);\n\tokp[0] = oks[n] = true;\n\tfor (int i = 0; i < n; ++i) {\n\t\tpref[i + 1] = pref[i] + (s[i] == '(' ? +1 : -1);\n\t\tokp[i + 1] = okp[i] & (pref[i + 1] >= 0);\n\t\tsuf[n - i - 1] = suf[n - i] + (rs[i] == '(' ? +1 : -1);\n\t\toks[n - i - 1] = oks[n - i] & (suf[n - i - 1] >= 0);\n\t}\n\t\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (!okp[i] || !oks[i + 1]) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (s[i] == '(') {\n\t\t\tif (pref[i] > 0 && pref[i] - 1 - suf[i + 1] == 0) {\n\t\t\t\t++ans;\n\t\t\t}\n\t\t} else {\n\t\t\tif (pref[i] + 1 - suf[i + 1] == 0) {\n\t\t\t\t++ans;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1095",
    "index": "F",
    "title": "Make It Connected",
    "statement": "You are given an undirected graph consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is $a_i$. Initially there are no edges in the graph.\n\nYou may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices $x$ and $y$ is $a_x + a_y$ coins. There are also $m$ special offers, each of them is denoted by three numbers $x$, $y$ and $w$, and means that you can add an edge connecting vertices $x$ and $y$ and pay $w$ coins for it. You don't have to use special offers: if there is a pair of vertices $x$ and $y$ that has a special offer associated with it, you still may connect these two vertices paying $a_x + a_y$ coins for it.\n\nWhat is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.",
    "tutorial": "Suppose we have found all the edges of the graph explicitly, sorted them, and start running Kruskal on the sorted list of edges. Each time we add some edge to MST, it is either a special edge given in the input, or an edge which was generated with cost $a_x + a_y$ (whichever costs less). Let's try to analyze how can we find the cheapest edge of each type that connects two components. For special edges, we may just maintain the number of special edges we already added or skipped, and when choosing a new edge, we skip some more (possibly zero) special edges that don't connect anything, until we find an edge that connects something. And for the other type of edges, we may find two components having minimum numbers on the vertices in those components as small as possible, and just connect the minimum vertex in the first component with the minimum vertex in the second component. We may simulate this by maintaining a data structure (for example, a multiset), where for each component we will store the vertex having minimum $a_i$ in this component, and pick two minimums from this set. We also have to be able to check if two vertices are connected (this can be done with DSU) and merge two components. But this solution can be made easier. Every time we add a \"non-special\" edge, one of the ends of this edge is the vertex with minimum $a_i$. So we may just find this vertex, generate all edges connecting this vertex to all other vertices, merge this set of edges with the set of special edges, and run any MST algorithm on the resulting set of edges. If there are multiple minimums in the array $a$, then we may pick any of them because in Kruskal algorithm it doesn't matter which of the edges with equal costs we try to add first.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n\ntypedef pair<long long, pair<int, int> > edge;\n\nconst int N = 200043;\n\nint p[N];\nlong long a[N];\n\nint get_leader(int x)\n{\n\treturn (x == p[x] ? x : (p[x] = get_leader(p[x])));\n}\n\nbool merge(int x, int y)\n{\n\tx = get_leader(x);\n\ty = get_leader(y);\n\tif(x == y) return false;\n\tp[x] = y;\n\treturn true;\n}\n\nint main()\n{\n\tint n, m;\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%lld\", &a[i]);\n\tvector<edge> es(m);\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tscanf(\"%d %d %lld\", &es[i].y.x, &es[i].y.y, &es[i].x);\n\t\tes[i].y.x--;\n\t\tes[i].y.y--;\n\t}\n\tint z = min_element(a, a + n) - a;\n\tfor(int i = 0; i < n; i++)\n\t\tif(i != z)\n\t\t\tes.push_back(mp(a[i] + a[z], mp(i, z)));\n\tsort(es.begin(), es.end());\n\tlong long ans = 0;\n\tfor(int i = 0; i < n; i++)\n\t\tp[i] = i;\n\tfor(auto e : es)\n\t\tif(merge(e.y.x, e.y.y))\n\t\t\tans += e.x;\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\t\t\n}",
    "tags": [
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1096",
    "index": "A",
    "title": "Find Divisible",
    "statement": "You are given a range of positive integers from $l$ to $r$.\n\nFind such a pair of integers $(x, y)$ that $l \\le x, y \\le r$, $x \\ne y$ and $x$ divides $y$.\n\nIf there are multiple answers, print any of them.\n\nYou are also asked to answer $T$ independent queries.",
    "tutorial": "Print $l$ and $2l$. Firstly, the smallest value of $\\frac y x$ you can have is $2$ and if any greater value fits then $2$ fits as well. Secondly, the absolute difference between $x$ and $2x$ increases when you increase $x$, thus lessening the possibility of both numbers fitting into the range. Overall complexity: $O(1)$.",
    "code": "T = int(input())\nfor i in range(T):\n\tl, r = map(int, input().split())\n\tprint(l, l * 2)",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1096",
    "index": "B",
    "title": "Substring Removal",
    "statement": "You are given a string $s$ of length $n$ consisting only of lowercase Latin letters.\n\nA substring of a string is a contiguous subsequence of that string. So, string \"forces\" is substring of string \"codeforces\", but string \"coder\" is not.\n\nYour task is to calculate the number of ways to remove \\textbf{exactly} one substring from this string in such a way that \\textbf{all} remaining characters are \\textbf{equal} (the number of distinct characters either zero or one).\n\nIt is guaranteed that there is \\textbf{at least two} different characters in $s$.\n\nNote that you \\textbf{can} remove the whole string and it is correct. Also note that you should \\textbf{remove at least one character}.\n\nSince the answer can be rather large (not very large though) print it modulo $998244353$.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "Firstly, let's calculate the length of the prefix of equal letters (let it be $l$) and the length of the suffix of equal letters (let it be $r$). It can be done with two cycles with breaks. It is obvious that this prefix and suffix wouldn't overlap. Then let's consider two cases: the first one is when $s_1 \\ne s_n$ and the second one is when $s_1 = s_n$. In the first case we can only remain either prefix or suffix of $s$ consisting only of equal letters. Then the answer is $l + r + 1$ (because we can remain from $1$ to $l$ letters on the prefix, from $1$ to $r$ on the suffix or empty string). In the second case we can remain from $0$ to $l$ letters on the prefix and from $0$ to $r$ letters on the suffix. But now because $s_1 = s_n$ we can combine these ways, so the answer is $(l + 1) \\cdot (r + 1)$. And the bonus (this case is not belong to the given problem): if all letters in the string are equal then then answer is $\\frac{n (n-1)}{2} + n$ because we can choose any substring of $s$ of length at least $2$ and any substring of length $1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\tint cntl = 0, cntr = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (s[i] == s[0]) {\n\t\t\t++cntl;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tif (s[i] == s[n - 1]) {\n\t\t\t++cntr;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (s[0] == s[n - 1]) {\n\t\tcout << ((cntl + 1) * 1ll * (cntr + 1)) % 998244353 << endl;\n\t} else {\n\t\tcout << (cntl + cntr + 1) % 998244353;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1096",
    "index": "C",
    "title": "Polygon for the Angle",
    "statement": "You are given an angle $\\text{ang}$.\n\nThe Jury asks You to find such \\textbf{regular} $n$-gon (regular polygon with $n$ vertices) that it has three vertices $a$, $b$ and $c$ (they can be non-consecutive) with $\\angle{abc} = \\text{ang}$ or report that there is no such $n$-gon.\n\nIf there are several answers, print the \\textbf{minimal} one. It is guarantied that if answer exists then it doesn't exceed $998244353$.",
    "tutorial": "At first, let prove that all possible angles in the regular $n$-gon equal to $\\frac{180k}{n}$, where $1 \\le k \\le n - 2$. To prove it we can build circumscribed circle around $n$-gon. Then the circle will be divided on $n$ equal arcs with lengths $\\frac{360}{n}$. Any possible angle in the $n$-gon is a inscribed angle in the circle and equal to half of central angle. Any central angle, in turn, equals to sum of some consecitive $k$ arcs. In result, any angle equal to $\\frac{1}{2} k \\frac{360}{n} = \\frac{180k}{n}$. The maximal possible angle is reached from three consecutive vertices and equal (by properties of regular polygons) to $\\frac{180(n-2)}{n}$. So, we need to find minimal integer $n$ such that $\\frac{180k}{n} = \\text{ang}$, where $k$ is integer and $1 \\le k \\le n - 2$. Its equivalent to find minimal integer solution of $180k = \\text{ang} \\cdot n$. Let $g = \\text{GCD}(180, \\text{ang})$, then we can divide both parts on $g$. In result, $\\frac{180}{g}k = \\frac{\\text{ang}}{g}n$. Since $\\text{GCD}(\\frac{180}{g}, \\frac{\\text{ang}}{g}) = 1$, then $\\frac{180}{g}$ must divide $n$. Analogically, $\\frac{\\text{ang}}{g}$ must divide $k$. Then, solution is next: $n = x \\cdot \\frac{180}{g}$ and $k = x \\cdot \\frac{\\text{ang}}{g}$. We are finding the minimal solution, so $x$ is almost always $1$, except cases where $k = n - 1$ - here we must take $x = 2$, since we have restricition on $k \\le n - 2$. The picture for the futher visibility:",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint ang;\n\ninline bool read() {\n\tif(!(cin >> ang))\n\t\treturn false;\n\treturn true;\n}\n\ninline void solve() {\n\tint g = __gcd(ang, 180);\n\tint k = ang / g;\n\tint n = 180 / g;\n\t\n\tif(k + 1 == n)\n\t\tk *= 2, n *= 2;\n\tcout << n << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\twhile(tc--) {\n\t\tassert(read());\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1096",
    "index": "D",
    "title": "Easy Problem",
    "statement": "Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $n$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements.\n\nVasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is $0$, and removing $i$-th character increases the ambiguity by $a_i$ (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still $4$ even though you delete it from the string had).\n\nVasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!\n\nRecall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.",
    "tutorial": "Denote string $t$ as hard. We will solve this problem with dynamic programming. Denote $dp_{cnt, len}$ - the minimum possible ambiguity if we considered first $cnt$ letters of statement and got prefix $t$ having length $len$ as a subsequence of the string. If $cnt$-th letter of the statement is not equal to $t_{len}$, then $dp_{cnt, len} = dp_{cnt-1, len}$ - we don't have to change it. Otherwise we either change the letter, or let it stay as it is (and the length of the prefix we found so far increases): $dp_{cnt, len} = \\min (dp_{cnt-1, len-1}, dp_{cnt-1, len} + a_{cnt-1})$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 100 * 1000 + 13;\nconst long long INF64 = 1e18;\n\nint n;\nstring s;\nint a[N];\nlong long dp[N][5];\n\nconst string h = \"hard\";\n\nint main() {\n\tscanf(\"%d\", &n);\n\tstatic char buf[N];\n\tscanf(\"%s\", buf);\n\ts = buf;\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tforn(i, N) forn(j, 5) dp[i][j] = INF64;\n\tdp[0][0] = 0;\n\tforn(i, n) forn(j, 4){\n\t\tdp[i + 1][j + (s[i] == h[j])] = min(dp[i + 1][j + (s[i] == h[j])], dp[i][j]);\n\t\tdp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + a[i]);\n\t}\n\t\n\tprintf(\"%lld\\n\", *min_element(dp[n], dp[n] + 4));\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1096",
    "index": "E",
    "title": "The Top Scorer",
    "statement": "Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are $p$ players doing penalty shoot-outs. Winner is the one who scores the most. \\textbf{In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability.}\n\nThey have just finished the game and now are waiting for the result. But there's a tiny problem! The judges have lost the paper of scores! Fortunately they have calculated sum of the scores before they get lost and also for some of the players they have remembered a lower bound on how much they scored. However, the information about the bounds is private, so Hasan only got to know his bound.\n\nAccording to the available data, he knows that his score is at least $r$ and sum of the scores is $s$.\n\nThus the final state of the game can be represented in form of sequence of $p$ integers $a_1, a_2, \\dots, a_p$ ($0 \\le a_i$) — player's scores. Hasan is player number $1$, so $a_1 \\ge r$. Also $a_1 + a_2 + \\dots + a_p = s$. Two states are considered different if there exists some position $i$ such that the value of $a_i$ differs in these states.\n\n\\textbf{Once again, Hasan doesn't know the exact scores (he doesn't know his exact score as well). So he considers each of the final states to be equally probable to achieve.}\n\nHelp Hasan find the probability of him winning.\n\nIt can be shown that it is in the form of $\\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \\ne 0$, $P \\le Q$. Report the value of $P \\cdot Q^{-1} \\pmod {998244353}$.",
    "tutorial": "An straightforward dp solution is to calculate $dp_{s,p,m} =$ {number of states at the end of the game in which no one has scored more than $m$ goals} where $s$ is the number of total goals to be scored and $p$ is the number players in the game. Fix the score of Hasan in the game and by using this dp the rest is easy (also described below). But as long as the time needed to calculate $dp_{s,p,m}$ is $O(s \\cdot r \\cdot p)$ this solution won't fit in the constraints. With a little help from combinatorics, we can calculate the value of mentioned dp function without using recursions. Define $g(s,p,m) = \\sum_{i=0}^{p}{(-1)^i \\binom{p}{i} \\binom{s+p-1-i(m+1)}{p-1}}$ This formula is a well-known modification of \"Star and Bars\" problem but with the upper limit on terms. Now we can calculate the answer, firstly fix Hasan's score and number of top-scorers, then use $g$ to calculate each state: $f(s,r,p) = \\frac{\\sum_{t=r}^s{\\sum_{q=1}^p{\\binom{p-1}{q-1} \\cdot \\frac 1 q \\cdot g(s-qt,p-q,t-1)}}}{\\binom{s-r+p-1}{p-1}}$ Overall complexity: $O(s\\cdot p^2)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 10 * 1000 + 7;\nconst int M = 100 + 7;\n\nint fact[N], rfact[N];\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD) a -= MOD;\n\tif (a < 0) a += MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn (a * 1ll * b) % MOD;\n}\n\nint binpow(int a, int b){\n\tint res = 1;\n\twhile (b){\n\t\tif (b & 1)\n\t\t\tres = mul(res, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nint cnk(int n, int k){\n\tif (n == k) return 1;\n\tif (k < 0 || k > n) return 0;\n\treturn mul(fact[n], mul(rfact[k], rfact[n - k]));\n}\n\nint g(int s, int p, int m){\n\tint res = 0;\n\tforn(i, p + 1)\n\t\tres = add(res, mul(i & 1 ? MOD - 1 : 1, mul(cnk(p, i), cnk(s + p - 1 - i * (m + 1), p - 1))));\n\treturn res;\n}\n\nint inv(int x){\n\treturn mul(rfact[x], fact[x - 1]);\n}\n\nint main() {\n\tfact[0] = 1;\n\tfor (int i = 1; i < N; ++i) fact[i] = mul(fact[i - 1], i);\n\trfact[N - 1] = binpow(fact[N - 1], MOD - 2);\n\tfor (int i = N - 2; i >= 0; --i) rfact[i] = mul(rfact[i + 1], i + 1);\n\t\n\tint p, s, r;\n\tscanf(\"%d%d%d\", &p, &s, &r);\n\t\n\tint Q = cnk(s - r + p - 1, p - 1);\n\tint P = 0;\n\tfor (int t = r; t <= s; ++t) for (int q = 1; q <= p; ++q)\n\t\tP = add(P, mul(mul(cnk(p - 1, q - 1), inv(q)), g(s - q * t, p - q, t - 1)));\n\t\n\tprintf(\"%d\\n\", mul(P, binpow(Q, MOD - 2)));\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1096",
    "index": "F",
    "title": "Inversion Expectation",
    "statement": "A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. An inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i > j$ and $a_i < a_j$. For example, a permutation $[4, 1, 3, 2]$ contains $4$ inversions: $(2, 1)$, $(3, 1)$, $(4, 1)$, $(4, 3)$.\n\nYou are given a permutation $p$ of size $n$. However, the numbers on some positions are replaced by $-1$. Let the valid permutation be such a replacement of $-1$ in this sequence back to numbers from $1$ to $n$ in such a way that the resulting sequence is a permutation of size $n$.\n\nThe given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.\n\nCalculate the expected total number of inversions in the resulting valid permutation.\n\nIt can be shown that it is in the form of $\\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \\ne 0$. Report the value of $P \\cdot Q^{-1} \\pmod {998244353}$.",
    "tutorial": "Let's break the problem into four general cases. Case 1. Inversions between two unknown numbers. Each pair of numbers can either be or inversion or not and the number of permutations for both cases is the same. Thus, the expected value of that is $\\frac{cnt(-1) \\cdot (cnt(-1) - 1)}{2} \\cdot \\frac 1 2$. Case 2 and 3. Inversions between the known and unknown number. Let's check the case with left number being unknown and right being known. The opposite will be done similarly. For each known number calculate the number of unknowns to the left of it $lft_x$ and the total number of unknowns greater than it $gt_x$. Then you'll need to put a greater number out of all possible to make an inversion. Add $lft_x \\cdot \\frac{gt_x}{cnt(-1)}$ to the answer. Case 4. Inversions between two known numbers. Just calculate that number ignoring all $-1$ and add it to answer. Overall complexity: $O(n \\log n)$ (for the lase case, all others are done in $O(n)$).",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\nconst int MOD = 998244353;\n\nint n;\nint p[N];\nbool used[N];\nint gt[N];\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn (a * 1ll * b) % MOD;\n}\n\nint binpow(int a, int b){\n\tint res = 1;\n\twhile (b){\n\t\tif (b & 1)\n\t\t\tres = mul(res, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nint f[N];\n\nvoid upd(int x){\n\tfor (int i = x; i < N; i |= i + 1)\n\t\t++f[i];\n}\n\nint get(int x){\n\tint sum = 0;\n\tfor (int i = x; i >= 0; i = (i & (i + 1)) - 1)\n\t\tsum += f[i];\n\treturn sum;\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n){\n\t\tscanf(\"%d\", &p[i]);\n\t\tif (p[i] != -1)\n\t\t\tused[p[i]] = true;\n\t}\n\t\n\tint cur = 0;\n\tfor (int i = n; i >= 1; --i){\n\t\tgt[i] = cur;\n\t\tcur += !used[i];\n\t}\n\t\n\t// case 1\n\tint ans = mul(mul(cur, cur - 1), binpow(4, MOD - 2));\n\t\n\tint inv = binpow(cur, MOD - 2);\n\t\n\t// case 2\n\tint lft = 0;\n\tforn(i, n){\n\t\tif (p[i] == -1)\n\t\t\t++lft;\n\t\telse\n\t\t\tans = add(ans, mul(lft, mul(gt[p[i]], inv)));\n\t}\n\t\n\t// case 3\n\tint rgh = 0;\n\tfor (int i = n - 1; i >= 0; --i){\n\t\tif (p[i] == -1)\n\t\t\t++rgh;\n\t\telse\n\t\t\tans = add(ans, mul(rgh, mul(cur - gt[p[i]], inv)));\n\t}\n\t\n\t// case 4\t\n\tint tmp = 0;\n\tforn(i, n) if (p[i] != -1){\n\t\tans = add(ans, tmp - get(p[i]));\n\t\tupd(p[i]);\n\t\t++tmp;\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1096",
    "index": "G",
    "title": "Lucky Tickets",
    "statement": "All bus tickets in Berland have their numbers. A number consists of $n$ digits ($n$ is even). Only $k$ decimal digits $d_1, d_2, \\dots, d_k$ can be used to form ticket numbers. If $0$ is among these digits, then numbers may have leading zeroes. For example, if $n = 4$ and only digits $0$ and $4$ can be used, then $0000$, $4004$, $4440$ are valid ticket numbers, and $0002$, $00$, $44443$ are not.\n\nA ticket is lucky if the sum of first $n / 2$ digits is equal to the sum of remaining $n / 2$ digits.\n\nCalculate the number of different lucky tickets in Berland. Since the answer may be big, print it modulo $998244353$.",
    "tutorial": "The naive solution would be $dp_{x, y}$ - the number of sequences of allowed digits with length $x$ and sum $y$. We compute it for $x = \\frac{n}{2}$ and for every possible $y$, and the answer is $\\sum_y dp_{\\frac{n}{2}, y}^2$. Let's speed this up. Let's denote the following polynomial: $f(x) = \\sum_{i = 0}^{9} c_i x^i$, where $c_i = 1$ if $i$ is an allowed digit, otherwise $c_i = 0$. It's easy to see that the coefficients of $f(x)$ are equal to the values of $dp_{1, y}$. Using mathematical induction we may prove that the coefficients of $(f(x))^a$ are equal to $dp_{a, y}$. So now we need to compute $(f(x))^{\\frac{n}{2}}$. There are two possible ways to do this that result in $O(n \\log n)$ complexity. The first option is to apply binary exponentiation with NTT polynomial multiplication. The second option is to use the fact that if we apply NTT to a polynomial, we get a set of its values in some points. So, if we exponentiate these values, we get a set of values of exponentiated polynomial in the same points. So we may apply NTT to $f(x)$ treating it as a polynomial of degree $5n$, raise each resulting value to the power of $\\frac{n}{2}$ and apply inverse transformation.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int LOGN = 21;\nconst int N = (1 << LOGN);\nconst int MOD = 998244353;\nconst int g = 3;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++)\n\ninline int mul(int a, int b)\n{\n\treturn (a * 1ll * b) % MOD;\n}\n\ninline int norm(int a) \n{\n\twhile(a >= MOD)\n\t\ta -= MOD;\n\twhile(a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\ninline int binPow(int a, int k) \n{\n\tint ans = 1;\n\twhile(k > 0) \n\t{\n\t\tif(k & 1)\n\t\t\tans = mul(ans, a);\n\t\ta = mul(a, a);\n\t\tk >>= 1;\n\t}\n\treturn ans;\n}\n\ninline int inv(int a) \n{\n\treturn binPow(a, MOD - 2);\n}\n\nvector<int> w[LOGN];\nvector<int> iw[LOGN];\nvector<int> rv[LOGN];\n\nvoid precalc() \n{\n\tint wb = binPow(g, (MOD - 1) / (1 << LOGN));\n\t\n\tfor(int st = 0; st < LOGN; st++) \n\t{\n\t\tw[st].assign(1 << st, 1);\n\t\tiw[st].assign(1 << st, 1);\n\t\t\n\t\tint bw = binPow(wb, 1 << (LOGN - st - 1));\n\t\tint ibw = inv(bw);\n\t\t\n\t\tint cw = 1;\n\t\tint icw = 1;\n\t\t\n\t\tfor(int k = 0; k < (1 << st); k++) \n\t\t{\n\t\t\tw[st][k] = cw;\n\t\t\tiw[st][k] = icw;\n\t\t\t\n\t\t\tcw = mul(cw, bw);\n\t\t\ticw = mul(icw, ibw);\n\t\t}\n\t\t\n\t\trv[st].assign(1 << st, 0);\n\t\t\n\t\tif(st == 0) \n\t\t{\n\t\t\trv[st][0] = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tint h = (1 << (st - 1));\n\t\tfor(int k = 0; k < (1 << st); k++)\n\t\t\trv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);\n\t}\n}\n\ninline void fft(int a[N], int n, int ln, bool inverse) \n{\t\n\tfor(int i = 0; i < n; i++) \n\t{\n\t\tint ni = rv[ln][i];\n\t\tif(i < ni)\n\t\t\tswap(a[i], a[ni]);\n\t}\n\t\n\tfor(int st = 0; (1 << st) < n; st++) \n\t{\n\t\tint len = (1 << st);\n\t\tfor(int k = 0; k < n; k += (len << 1)) \n\t\t{\n\t\t\tfor(int pos = k; pos < k + len; pos++) \n\t\t\t{\n\t\t\t\tint l = a[pos];\n\t\t\t\tint r = mul(a[pos + len], (inverse ? iw[st][pos - k] : w[st][pos - k]));\n\t\t\t\t\n\t\t\t\ta[pos] = norm(l + r);\n\t\t\t\ta[pos + len] = norm(l - r);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(inverse) \n\t{\n\t\tint in = inv(n);\n\t\tfor(int i = 0; i < n; i++)\n\t\t\ta[i] = mul(a[i], in);\n\t}\n}\n\nint aa[N], bb[N], cc[N];\n\ninline void multiply(int a[N], int sza, int b[N], int szb, int c[N], int &szc) \n{\n\tint n = 1, ln = 0;\n\twhile(n < (sza + szb))\n\t\tn <<= 1, ln++;\n\tfor(int i = 0; i < n; i++)\n\t\taa[i] = (i < sza ? a[i] : 0);\n\tfor(int i = 0; i < n; i++)\n\t\tbb[i] = (i < szb ? b[i] : 0);\n\t\t\n\tfft(aa, n, ln, false);\n\tfft(bb, n, ln, false);\n\t\n\tfor(int i = 0; i < n; i++)\n\t\tcc[i] = mul(aa[i], bb[i]);\n\t\t\n\tfft(cc, n, ln, true);\n\t\n\tszc = n;\n\tfor(int i = 0; i < n; i++)\n\t\tc[i] = cc[i];\n}\n\nvector<int> T[N];\n\nint a[N];\nint b[N];\nint c[N];\n\n#define sz(a) (int(a.size()))\n\nint main()\n{\n\tprecalc();\n\tint n, k;\n\tscanf(\"%d %d\", &n, &k);\n\tfor(int i = 0; i < k; i++)\n\t{\n\t    int x;\n\t    scanf(\"%d\", &x);\n\t    a[x] = 1;\n\t}\n\tint nn = 1, ln = 0;\n\tint nw = (n * 5) + 1;\n\twhile(nn < nw)\n\t{\n\t\tnn *= 2;\n\t\tln++;\n\t}\n\tfft(a, nn, ln, false);\n\tforn(i, nn)\n\t\ta[i] = binPow(a[i], n / 2);\n\tfft(a, nn, ln, true);\n\tint ans = 0;\n\tforn(i, nn)\n\t\tans = norm(ans + binPow(a[i], 2));\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\t\n}",
    "tags": [
      "divide and conquer",
      "dp",
      "fft"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1097",
    "index": "A",
    "title": "Gennady and a Card Game",
    "statement": "Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called \"Mau-Mau\".\n\nTo play Mau-Mau, you need a pack of $52$ cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or Hearts — H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).\n\nAt the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.\n\nIn order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.",
    "tutorial": "The task is to check if some card in the second line has a common character with the card in the first line. The best way to do this is to create a single string for the card in the hand and an array of strings for the cards on the table. After reading the input, just iterate with a loop over the array. If a string in the array has any common character with the single string, then output \"YES\". If no similarity was found, output \"NO\".",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1097",
    "index": "B",
    "title": "Petr and a Combination Lock",
    "statement": "Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of $360$ degrees and a pointer which initially points at zero:\n\nPetr called his car dealer, who instructed him to rotate the lock's wheel exactly $n$ times. The $i$-th rotation should be $a_i$ degrees, either clockwise or counterclockwise, and after all $n$ rotations the pointer should again point at zero.\n\nThis confused Petr a little bit as he isn't sure which rotations should be done clockwise and which should be done counterclockwise. As there are many possible ways of rotating the lock, help him and find out whether there exists at least one, such that after all $n$ rotations the pointer will point at zero again.",
    "tutorial": "The best way to check the condition in the statement is to use bitmasks. Iterate from $0$ to $2^n-1$ and for each number consider its binary representation. If the $i$-th bit of the representation is set to $0$, then decide to perform the $i$-th rotation clockwise. In the opposite case, do it counterclockwise. Finally, check if the whole angle is a multiple of $360$ and if so, output \"YES\". If no good combination of rotations was found, output \"NO\".",
    "tags": [
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1097",
    "index": "C",
    "title": "Yuhao and a Parenthesis",
    "statement": "One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.\n\nA bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters \"+\" and \"1\" into this sequence. For example, the sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while the bracket sequences \")(\", \"(()\" and \"(()))(\" are not correct.\n\nYuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.\n\nThis problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?",
    "tutorial": "It turns out that each bracket sequence can be described by a pair $(a, b)$, where $a$ and $b$ are the minimal non-negative integers such that after adding $a$ opening parentheses \"(\" to the left of the string and $b$ closing parentheses \")\" to the right of the string it becomes a correct bracket sequence. These numbers can be easily found with a single loop. If $a \\neq 0$ and $b \\neq 0$, we cannot pair this string with any other string, because it needs brackets on its both sides. If $a=b=0$, then this string is a correct bracket sequence and can be paired with any other correct bracket sequence. If there are $k$ such strings, then $\\left\\lfloor \\frac{k}{2} \\right\\rfloor$ pairs can be formed. If we want to concatenate two other bracket sequences (say, $i$-th and $j$-th) in order to produce a correct bracket sequence, the excess of the opening parentheses in the $i$-th sequence must equal the excess of the closing parentheses in the $j$-th sequence; that is, $b_i = a_j$. This allows us to pair the sequences greedily.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1097",
    "index": "D",
    "title": "Makoto and a Blackboard",
    "statement": "Makoto has a big blackboard with a positive integer $n$ written on it. He will perform the following action exactly $k$ times:\n\nSuppose the number currently written on the blackboard is $v$. He will randomly pick one of the divisors of $v$ (possibly $1$ and $v$) and replace $v$ with this divisor. As Makoto uses his famous random number generator (RNG) and as he always uses $58$ as his generator seed, each divisor is guaranteed to be chosen with equal probability.\n\nHe now wonders what is the expected value of the number written on the blackboard after $k$ steps.\n\nIt can be shown that this value can be represented as $\\frac{P}{Q}$ where $P$ and $Q$ are coprime integers and $Q \\not\\equiv 0 \\pmod{10^9+7}$. Print the value of $P \\cdot Q^{-1}$ modulo $10^9+7$.",
    "tutorial": "How to solve the problem if $n$ is a prime power $p^{\\alpha}$? We can simply use dynamic programming. Let $DP_{i, j}$ denote the probability that after $i$ steps the current number on the blackboard is $p^j$. At the beginning, $DP_{0, \\alpha} = 1$. The transitions in DP are rather straightforward. The expected value of the number on the blackboard is then $\\sum_{j=0}^{\\alpha} DP_{k, j} p^j.$ What if $n$ is not a prime power? We can observe that the result is multiplicative on $n$. Therefore, we factorize $n = p_1^{\\alpha_1} p_2^{\\alpha_k} \\dots p_\\ell^{\\alpha_\\ell}$, apply the solution above for each prime power $p_1^{\\alpha_1}$ through $p_\\ell^{\\alpha_\\ell}$, and eventually multiply the results. Another problem is that we need to write a single integer modulo $10^9+7$ even though the answer is a rational number. To cope with this, we notice that $10^9+7$ is prime. Therefore, thanks to the Fermat Little Theorem, dividing by some number $x$ is equivalent to multiplying by $x^{10^9+5}$, modulo $10^9+7$. We use the quick exponentiation to compute the results. The overall complexity is $O(\\sqrt{n}+k \\cdot \\log n)$.",
    "tags": [
      "dp",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1097",
    "index": "E",
    "title": "Egor and an RPG game",
    "statement": "One Saturday afternoon Egor was playing his favorite RPG game. While discovering new lands and territories, he came across the following sign:\n\nEgor is a passionate player, but he is an algorithmician as well. That's why he instantly spotted four common letters in two words on the sign above — if we permute the letters \"R\", \"E\", \"G\", \"O\" from the first word, we can obtain the letters \"O\", \"G\", \"R\", \"E\". Egor got inspired by the sign and right away he came up with a problem about permutations.\n\nYou are given a permutation of length $n$. You have to split it into some non-empty subsequences so that each element of the permutation belongs to exactly one subsequence. Each subsequence must be monotonic — that is, either increasing or decreasing.\n\nSequence is called to be a subsequence if it can be derived from permutation by deleting some (possibly none) elements without changing the order of the remaining elements.\n\nThe number of subsequences should be small enough — let $f(n)$ be the minimum integer $k$ such that every permutation of length $n$ can be partitioned into at most $k$ monotonic subsequences.\n\nYou need to split the permutation into at most $f(n)$ monotonic subsequences.",
    "tutorial": "Firstly, consider this testcase: $\\{1, 3, 2, 6, 5, 4, 10, 9, 8, 7, 15, 14, 13, 12, 11\\}$. It's easy to see that here we need at least $5$ sequences. It's possible to generalize it and see that if $n \\geq \\frac{k \\cdot (k+1)}{2}$ for some integer $k$, then we need at least $k$ sequences. So, maybe if $n < \\frac{k \\cdot (k+1)}{2}$ it's always possible to use at most $k-1$ sequences? It turns out to be true. How to prove it? Let's calculate the LIS (Longest Increasing Sequence) of the permutation. If $|LIS| \\geq k$, we can erase it, and because $\\frac{k \\cdot (k+1)}{2}-k=\\frac{(k-1) \\cdot k}{2}$, we can recursively solve the problem for the smaller permutation and $k$. What if $|LIS| < k$? It's known that we can split the permutation into $|LIS|$ decreasing sequences. As this number is not greater than the limit on the number of sequences, we can simply do it and end the process. The proof above also gives a simple algorithm to find the partition. Its running time is $O(n\\sqrt{n} \\log{n})$.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1097",
    "index": "F",
    "title": "Alex and a TV Show",
    "statement": "Alex decided to try his luck in TV shows. He once went to the quiz named \"What's That Word?!\". After perfectly answering the questions \"How is a pseudonym commonly referred to in the Internet?\" (\"Um... a nick?\"), \"After which famous inventor we name the unit of the magnetic field strength?\" (\"Um... Nikola Tesla?\") and \"Which rock band performs \"How You Remind Me\"?\" (\"Um... Nickelback?\"), he decided to apply to a little bit more difficult TV show: \"What's in This Multiset?!\".\n\nThe rules of this TV show are as follows: there are $n$ multisets numbered from $1$ to $n$. Each of them is initially empty. Then, $q$ events happen; each of them is in one of the four possible types:\n\n- 1 x v — set the $x$-th multiset to a singleton $\\{v\\}$.\n- 2 x y z — set the $x$-th multiset to a union of the $y$-th and the $z$-th multiset. For example: $\\{1, 3\\}\\cup\\{1, 4, 4\\}=\\{1, 1, 3, 4, 4\\}$.\n- 3 x y z — set the $x$-th multiset to a product of the $y$-th and the $z$-th multiset. The product $A \\times B$ of two multisets $A$, $B$ is defined as $\\{ \\gcd(a, b)\\, \\mid\\, a \\in A,\\, b \\in B \\}$, where $\\gcd(p, q)$ is the greatest common divisor of $p$ and $q$. For example: $\\{2, 2, 3\\} \\times \\{1, 4, 6\\}=\\{1, 2, 2, 1, 2, 2, 1, 1, 3\\}$.\n- 4 x v — the participant is asked how many times number $v$ occurs in the $x$-th multiset. As the quiz turned out to be too hard in the past, participants should now give the answers \\textbf{modulo $2$ only}.\n\nNote, that $x$, $y$ and $z$ described above are not necessarily different. In events of types $2$ and $3$, the sum or the product is computed first, and then the assignment is performed.\n\nAlex is confused by the complicated rules of the show. Can you help him answer the requests of the $4$-th type?",
    "tutorial": "Firstly, let's store in a bitset of size $7000$ an information which elements occur an odd number of times in some multiset. Let's think about the query of the third type like about a convolution. We'll solve it similarly to FFT: we'll change both polynomials (arrays) into a form of \"values in points\", multiply them by simply multiplying corresponding numbers and then reverse the changing process. It turns out that the equivalent of \"the values in points\" method should be as follows: instead of storing the parity of numbers equal to $x$, store the parity of numbers divisible by $x$. Why? If we denote by $a$ the number of elements divisible by some $x$ in the first multiset and by $b$ the number of elements divisible by $x$ in the second multiset, then the number of elements divisible by $x$ in their product is $a \\cdot b$. Thanks to that, we can multiply easily now. The multiplication is now just a bitwise AND operation. We can also add the multisets in this form as it's a bitwise XOR operation. But of course, we cannot change the form each time when we want to multiply two multisets. It can be done in $O(d \\cdot \\log{d})$ for $d=7000$, but it's too slow. Instead, we commit to keeping each multiset in the changed form all the time. How to answer for parity of the number of occurrences of some number $x$ in a multiset without changing it to normal form? Inclusion-exclusion principle tells us that we should take the numbers from positions $i$ which are divisible by $x$ and for which $\\frac{i}{x}$ is square-free. Each of these numbers should be multiplied by $1$ or $-1$. Luckily, we are calculating the results modulo $2$ and because $1 \\equiv -1~(mod~2)$, we just add everything up without multiplying by $\\pm 1$. We can prepare the bitsets for every possible query of type $1$ and $4$. This allows us to answer every query in $O(d/32)$.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1097",
    "index": "G",
    "title": "Vladislav and a Great Legend",
    "statement": "A great legend used to be here, but some troll hacked Codeforces and erased it. Too bad for us, but in the troll society he earned a title of an ultimate-greatest-over troll. At least for them, it's something good. And maybe a formal statement will be even better for us?\n\nYou are given a tree $T$ with $n$ vertices numbered from $1$ to $n$. For every \\textbf{non-empty} subset $X$ of vertices of $T$, let $f(X)$ be the minimum number of edges in the smallest connected subtree of $T$ which contains every vertex from $X$.\n\nYou're also given an integer $k$. You need to compute the sum of $(f(X))^k$ among all non-empty subsets of vertices, that is:\n\n$$ \\sum\\limits_{X \\subseteq \\{1, 2,\\: \\dots \\:, n\\},\\, X \\neq \\varnothing} (f(X))^k. $$\n\nAs the result might be very large, output it modulo $10^9 + 7$.",
    "tutorial": "Firstly, to properly understand what does \"calculate the sum of the $k$-th powers\" means, I recommend you to get acquainted with these two lectures (especially the \"powers technique\"): https://codeforces.com/blog/entry/62690 https://codeforces.com/blog/entry/62792 Here is a shorter version of what you should understand. When we have a set of some objects, and we want to do something with the $k$-th power of its size (let's assume $k=2$ for a moment), we should look at $x^2$ which turns out to be equal to $(1+1+1+...+1)\\cdot(1+1+1+...+1)$, where $x$ is the size of the set and each parenthesis, of course, contains $x$ ones. Each $1$ stands for some element of this set. It can be observed that $x^2$ is equal to the number of ordered pairs ($k$-tuples in general) of elements in the set because we should choose one $1$ in the first parenthesis and one $1$ in the second parenthesis. So, let's change the order of the summation. Firstly, iterate over pairs ($k$-tuples in general) and for each of them calculate in how many sets does it appear. And that's exactly what we will do in the solution. For each $l$ ($1 \\leq l \\leq k$), and going further for each $l$-tuple of $\\textbf{different}$ and $\\textbf{sorted}$ edges, we will calculate in how many spanning subsets does it appear. Nextly, with some simpler DP, we will calculate in how many ways can we change a tuple of $l$ different and sorted elements into a tuple which doesn't necessarily meet these conditions. So, how to calculate the sum for each $l$? Let's imagine that we want to calculate the number of spanning subsets for some fixed subset of edges. How many of them are there? Each vertex which lies on a path between any two of the chosen edges can be arbitrarily taken or not. The rest of the vertices can be divided into connected groups, and each group must contain at least one chosen vertex. The division is rather intuitional, but formally: two vertices (which don't lie on any path between two edges in the subset) are in the same group if and only if the path between them doesn't contain any edge in the chosen subset. So, now we know that we should calculate the sum of $2^{number~of~vertices~which~lie~on~some~path}\\cdot\\prod_{each~group}(2^{size~of~this~group}-1)$. This can be done with a $DP_{i, j}$, where $i$ stands for a vertex, and $j$ stands for the number of chosen edges in its subtree. The complexity trivially is equal to $O(n \\cdot k^2)$, but it turns out that if we iterate not to $k$, but to $min(k, size~of~the~subtree)$ each time, the complexity decreases to $O(n \\cdot k)$ (similarly to the trick with complexity $O(n^2)$ instead of $O(n^3)$ in many tree DP problems).",
    "tags": [
      "combinatorics",
      "dp",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1097",
    "index": "H",
    "title": "Mateusz and an Infinite Sequence",
    "statement": "A Thue-Morse-Radecki-Mateusz sequence (Thorse-Radewoosh sequence in short) is an infinite sequence constructed from a finite sequence $\\mathrm{gen}$ of length $d$ and an integer $m$, obtained in the following sequence of steps:\n\n- In the beginning, we define the one-element sequence $M_0=(0)$.\n- In the $k$-th step, $k \\geq 1$, we define the sequence $M_k$ to be the concatenation of the $d$ copies of $M_{k-1}$. However, each of them is altered slightly — in the $i$-th of them ($1 \\leq i \\leq d$), each element $x$ is changed to $(x+\\mathrm{gen}_i) \\pmod{m}$.\n\nFor instance, if we pick $\\mathrm{gen} = (0, \\textcolor{blue}{1}, \\textcolor{green}{2})$ and $m = 4$:\n\n- $M_0 = (0)$,\n- $M_1 = (0, \\textcolor{blue}{1}, \\textcolor{green}{2})$,\n- $M_2 = (0, 1, 2, \\textcolor{blue}{1, 2, 3}, \\textcolor{green}{2, 3, 0})$,\n- $M_3 = (0, 1, 2, 1, 2, 3, 2, 3, 0, \\textcolor{blue}{1, 2, 3, 2, 3, 0, 3, 0, 1}, \\textcolor{green}{2, 3, 0, 3, 0, 1, 0, 1, 2})$, and so on.\n\nAs you can see, as long as the first element of $\\mathrm{gen}$ is $0$, each consecutive step produces a sequence whose prefix is the sequence generated in the previous step. Therefore, we can define the infinite Thorse-Radewoosh sequence $M_\\infty$ as the sequence obtained by applying the step above indefinitely. For the parameters above, $M_\\infty = (0, 1, 2, 1, 2, 3, 2, 3, 0, 1, 2, 3, 2, 3, 0, 3, 0, 1, \\dots)$.\n\nMateusz picked a sequence $\\mathrm{gen}$ and an integer $m$, and used them to obtain a Thorse-Radewoosh sequence $M_\\infty$. He then picked two integers $l$, $r$, and wrote down a subsequence of this sequence $A := ((M_\\infty)_l, (M_\\infty)_{l+1}, \\dots, (M_\\infty)_r)$.\n\nNote that we use the $1$-based indexing both for $M_\\infty$ and $A$.\n\nMateusz has his favorite sequence $B$ with length $n$, and would like to see how large it is compared to $A$. Let's say that $B$ majorizes sequence $X$ of length $n$ (let's denote it as $B \\geq X$) if and only if for all $i \\in \\{1, 2, \\dots, n\\}$, we have $B_i \\geq X_i$.\n\nHe now asks himself how many integers $x$ in the range $[1, |A| - n + 1]$ there are such that $B \\geq (A_x, A_{x+1}, A_{x+2}, \\dots, A_{x+n-1})$. As both sequences were huge, answering the question using only his pen and paper turned out to be too time-consuming. Can you help him automate his research?",
    "tutorial": "In the beginning, change the query about an interval into two queries about prefixes. Nextly, let's generalize the problem. Change the condition $A_i \\leq B_j$ into $A_i \\in X_j$, where $X_j$ is some set of possible values (and will be represented as a bitmask). The problem is that the length of the sequence from the input can be huge. How to decrease it? If we'd know the index of the position where we want to compare the sequence from the input taken modulo $d$, we'd be able to decrease the size of the sequence approximately $d$ times. How? We'd know the partition into groups of at most $d$ elements and one group can be reduced to one element (using binary shifts and AND operations). We don't know the remainder as there can be many of them. The idea is to use the recursive function which will check every possibility. The function will take as an argument a sequence $X$ (the sequence of sets of possible elements for each position) and a length of the prefix. It will work as follows: If the length of the sequence is equal to one, calculate the result with some DP which will be described later. If the possible prefix is empty, return $0$. In other cases, iterate over possible reminder and split into $d$ recursive calls, each with approximately $d$ times shorter sequence. How does this reduction work? If the sequence's length is big, the sum of lengths doesn't change much. The tricky part comes when the length of the sequence is $2$. Then, in $d-1$ calls, the length will change to one, but in one call the length will stay equal to two. This shouldn't scare us because these $d-1$ calls will be cut off instantly with mentioned DP. In this way, we will generate $O(n \\cdot log_d(r) \\cdot d)$ queries. The next observation is that there will be only $O(log_d(r))$ different lengths of prefixes. To prove it we can consider how does the set of possible prefixes look like on each level of the recursion. Now, for each mentioned prefix $a$ and each number $b$ from the range $[0, m)$ we should calculate how many times does $b$ appear on the prefix $a$. To do this, write $a$ in the $d$-based system and use simple DP which goes like $DP[i=number~of~already~considered~digits][j=remainder][l=are~we~aready~smaller~than~a]=number~of~ways$ with $0 \\leq i \\leq log_d(r)$, $0 \\leq j < m$ and $0 \\leq l \\leq 1$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "strings"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1098",
    "index": "A",
    "title": "Sum in the tree",
    "statement": "Mitya has a rooted tree with $n$ vertices indexed from $1$ to $n$, where the root has index $1$. Each vertex $v$ initially had an integer number $a_v \\ge 0$ written on it. For every vertex $v$ Mitya has computed $s_v$: the sum of all values written on the vertices on the path from vertex $v$ to the root, as well as $h_v$ — the depth of vertex $v$, which denotes the number of vertices on the path from vertex $v$ to the root. Clearly, $s_1=a_1$ and $h_1=1$.\n\nThen Mitya erased all numbers $a_v$, and by accident he also erased all values $s_v$ for vertices with even depth (vertices with even $h_v$). Your task is to restore the values $a_v$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $a_v$ for all vertices in the tree.",
    "tutorial": "To achieve the minimum possible sum of values in the tree, for vertices with even depth we need to put 0 for leaves and the maximum value possible for other vertices, because increasing the value does not make the resulting sum worse - our children would compensate for it. Since $a_v \\ge 0$, it's obvious that ${s_p}_v \\le {s_p}_v + a_v = s_v$. For every child $u$ of vertex $v$ it's also true that $s_v \\le s_u$, hence ${s_p}_v \\le s_v \\le s_u$. From this one can derive that the maximum possible $a_v$ for vertices with even $h_v$ equals $\\min\\limits_{u\\ -\\ child\\ v}s_{u} - s_{p_v}$. Given the values $a_v$ in the vertices of even depth, we can restore the values in the vertices of odd depth using the formula $a_v = s_v - s_{p_v}$. This requires a simple DFS (which translated to a for-loop given the tree representation in the problem statement).",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1098",
    "index": "B",
    "title": "Nice table",
    "statement": "You are given an $n \\times m$ table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every $2 \\times 2$ square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters.",
    "tutorial": "Key idea: In a good matrix, either each row contain at most two different characters, or each column contain at most two different characters. Proof: (it will be here, but for now the editorial fields are too narrow to contain it). In other words, the field looks either like (up to a permutation of <<AGCT>>): <<AGAGAG>> <<CTCTCT>> <<AGAGAG>> (or <<GAGAGA>>) <<CTCTCT>> (or <<TCTCTC>>) <<AGAGAG>> (or <<GAGAGA>>) <<CTCTCT>> (or <<TCTCTC>>) (and so on) or similarly by columns. So, the solution is to say that we have this alternation by rows, iterate over the permutation of letters, for each row choose from the row and its inversion the one that differs from the row of the original matrix in the minimum number of characters. Then rotate the matrix, and solve similarly again, and take a more optimal one.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1098",
    "index": "C",
    "title": "Construct a tree",
    "statement": "Misha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree!\n\nMisha would like to construct a rooted tree with $n$ vertices, indexed from 1 to $n$, where the root has index 1. Every other vertex has a parent $p_i$, and $i$ is called a child of vertex $p_i$. Vertex $u$ belongs to the subtree of vertex $v$ iff $v$ is reachable from $u$ while iterating over the parents ($u$, $p_{u}$, $p_{p_{u}}$, ...). Clearly, $v$ belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex $1$.\n\nBelow there is a tree with $6$ vertices. The subtree of vertex $2$ contains vertices $2$, $3$, $4$, $5$. Hence the size of its subtree is $4$.\n\nThe branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals $2$. Your task is to construct a tree with $n$ vertices such that the sum of the subtree sizes for all vertices equals $s$, and the branching coefficient is minimum possible.",
    "tutorial": "Note, that vertex belongs to subtrees of vertexes, which lay on its way to root. So, sum of sizes of subtrees is equal to $p + n$, where $p$ is sum of lengths of ways from root to vertexes. Let's consider which sum of sizes of subtrees can be in tree with branching coefficient less or equal than $k$. Minimal sum can be achieved in $k$-nary tree (it consists of root, $k$ vertexes on distance $1$, $k^2$ on distance $2$, etc, the last level can be filled not completely). Maximal sum can be achieved in bamboo - tree, which consists of only one way with length $n$. If $s$ is bigger than sum in this tree, the answer will be <<No>>. Let's find minimal $k$, such that $s$ is not smaller than sum of sizes of subtrees in $k$-nary tree (using binary search). Now $s$ is between minimal and maximal sum of sizes of subtrees in tree with branching coefficient, which is not bigger than $k$. Let's show how to build tree with the given sum, which is between these two borders. Let's start with $k$-nary tree. Let's realize recursive function, which rebuilds tree. Let we are in a subtree, and want to increase sum of sizes of subtrees by $x$ (in this subtree). We can change this subtree to bamboo with same number of vertexes (if the sum of sizeof of subtrees won't be too big). Otherwise, we run this function from subtrees in some order. If we reach needed sum, we will terminate the process. Otherwise, every subtree of child is bamboo now, current sum of sizes is smaller than needed, but if we merged bamboos, it would be bigger than it. Let's move vertexes to the end of the first bamboo from others. Over time, after next moving, sum of sizes will increase too much. We can move it to the another position in the first bamboo, in order to make sum equal to $s$, and terminate the process. But if we believe that every tree with sum of sizes of subtrees between maximal and minimal can be built, there is another solution with $O(n \\log n)$ complexity, which is easier to realize. The sum of subtree sizes is influenced only by the number of vertices at each distance, and not by their mutual arrangement. Sum of sizes of subtrees is equal to $n + i \\cdot d_{i}$, where $d_{i}$ - number of vertexes on distance $i$ from the root. Let's built this array of counts. These conditions must be satisfied: If the $i$-th element is bigger than $0$ ($i > 0$), than $i - 1$-th element must be bigger than $0$. If the $i$-th element is equal to $t$, $i + 1$-th mustn't be bigger than $t \\cdot k$. Sum of elements must be equal to $n$. Let we have recovered some prefix of this array (i.e we know that we can fill rest, and sum of sizes of subtrees will be equal to $s$). Let's try to put some value to the next element. We know that the tree can be rebuilt so that the sum is any between maximum and minimum, so there are two conditions, which are satisfied (we want to put value $x$ to position $i$). $x$ must be big enough, so if we fill suffix with numbers $x$, $x \\cdot k$, $x \\cdot k^2$, ... (the last non-zero number can be smaller, sum of numbers is $n$) sum of sizes of subtrees will be not greater to $s$. $x$ must be small enough, so if we fill suffix with $1$, sum of sizes of subtrees will be not less than $s$. Both borders form some segment of values, which could be put to this position. We haven't to look for the left border, just find the right border by binsearch, and put number, which is equal to it. We can easily restore the tree, using array $d$.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1098",
    "index": "D",
    "title": "Eels",
    "statement": "Vasya is a big fish lover, and his parents gave him an aquarium for the New Year. Vasya does not have a degree in ichthyology, so he thinks that filling a new aquarium with eels is a good idea. Unfortunately, eels are predators, so Vasya decided to find out how dangerous this idea was.\n\nGetting into one aquarium, eels fight each other until exactly one fish remains. When two eels fight, the big one eats the smaller one (if their weights are equal, then one of them will still eat the other). Namely, let $n$ eels be initially in an aquarium, and the $i$-th of them have a weight of $x_i$. Then $n-1$ battles will occur between them, as a result of which, only one eel will survive. In a battle of two eels with weights $a$ and $b$, where $a \\le b$, eel of weight $a$ will be eaten and disappear from the aquarium, and eel of weight $b$ will increase its weight to $a+b$.\n\nA battle between two eels with weights $a$ and $b$, where $a \\le b$, is considered dangerous if $b \\le 2 a$. For a given set of eels, danger is defined as the maximum number of dangerous battles that can occur among these eels if they are placed in one aquarium.\n\nNow Vasya is planning, which eels he wants to put into an aquarium. He has some set of eels (initially empty). He makes a series of operations with this set. With each operation, he either adds one eel in the set, or removes one eel from the set. Vasya asks you to calculate the danger of the current set of eels after each operation.",
    "tutorial": "Let's consider a set of fishes of size $k$ and sort it in non-decreasing order: $a_1 \\le a_2 \\le \\ldots \\le a_k$. Let's call a fish fat if its weight is greater than twice the sum of all fishes with smaller indices: fish $a_i$ is fat iff $a_i > 2 \\sum_{j < i} a_j$. Key fact. Let $t$ be the total number of fat fishes. We'll prove that in this case the set of fishes has danger $k-t$. Observation 1. A fat fish can't dangerously eat a fish with smaller weight. Indeed, even if all the smaller fishes eat each other, the resulting fish would be too small. We can conclude that the danger is not greater $k-t$. Observation 2. Let's use the following strategy: at every moment fishes with two smallest weights fight with each other. If a battle between fishes with masses $a$ and $b$ is not dangerous, it's clear that fish $b$ has not eaten any other fish yet - otherwise this fish is a sum of two smaller fishes $c+d=b$, where $c \\le d$, but in this case $d \\ge b/2 > a$, hence according to the strategy there must have been a fight between two fishes $a$ and $c$ before. This indicates that fish $b$ has not eaten any other fish yet, and fish $a$ is a result of battles between all smaller fishes. In this case $b$ is a fat fish by definition, which completes the proof that this strategy guarantees exactly $k-t$ dangerous battles. Algorithm. Clearly now we need a data structure that allows us to perform three types of operations: add element $x$ remove element $x$ find all elements that are greater than the sum of all smaller elements Let's split the allowed values range into half-intervals $[1,2)$, $[2,4)$, $[4,8)$, ..., $[2^{30}, 2^{31})$. Observation 3. Every half-interval contains at most 1 fat fish, and if there is one, it's the on with the minimum value. Indeed, every single half-interval does not contain two values $x$ and $y$ where $y > 2x$. Now for each half-interval we can maintain the sum of all fishes in this half-interval, the sum of weights of fishes in this half-interval, and the minimum fish in the half-interval (one could use set / PriorityQueue or a similar data structure). In this case we can determine the count of fat fishes simply by iterating over all half-intervals. The resulting complexity is $O(\\log_2 n)$ per query.",
    "tags": [
      "data structures"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1098",
    "index": "E",
    "title": "Fedya the Potter",
    "statement": "Fedya loves problems involving data structures. Especially ones about different queries on subsegments. Fedya had a nice array $a_1, a_2, \\ldots a_n$ and a beautiful data structure. This data structure, given $l$ and $r$, $1 \\le l \\le r \\le n$, could find the greatest integer $d$, such that $d$ divides each of $a_l$, $a_{l+1}$, ..., $a_{r}$.\n\nFedya really likes this data structure, so he applied it to every non-empty contiguous subarray of array $a$, put all answers into the array and sorted it. He called this array $b$. It's easy to see that array $b$ contains $n(n+1)/2$ elements.\n\nAfter that, Fedya implemented another cool data structure, that allowed him to find sum $b_l + b_{l+1} + \\ldots + b_r$ for given $l$ and $r$, $1 \\le l \\le r \\le n(n+1)/2$. Surely, Fedya applied this data structure to every contiguous subarray of array $b$, called the result $c$ and sorted it. Help Fedya find the lower median of array $c$.\n\nRecall that for a sorted array of length $k$ the lower median is an element at position $\\lfloor \\frac{k + 1}{2} \\rfloor$, if elements of the array are enumerated starting from $1$. For example, the lower median of array $(1, 1, 2, 3, 6)$ is $2$, and the lower median of $(0, 17, 23, 96)$ is $17$.",
    "tutorial": "There are $O(N\\cdot logN)$ different values of gcd, because if we fix the left bound of a segment and iterate right bound from left bound to the end, the gcd stays unchanged or decreases in two or more times. We can get a compressed version of array $b$ if we compress equal consecutive elements in to pair $(value, countOfValue)$. We can use segment tree to find all segments of equal elements. Let's estimate how many segments in array $b$ have sum less or equals some $M$. If size of array $b$ had been small, we could have done the 2 pointers technique to do that. Unfortunately, size of array $b$ is $O(N^2)$. However, array $b$ has a lot of equal elements. So, the solution is to process a group of equal elements in a fast way. Let's fix bounds $L$ and $R$ in array $b$, assume $T$ - is a sum of elements beetwen $L$ and $R$, after $L$ we have a group of elements $X$, with size $xcnt$, after $R$ we have a group of elements $Y$, with size $ycnt$. Then, it is easy to see that our task is to find out how many pairs of integers $(a, b)$ satisfy the condition: $0 < b \\cdot Y - a \\cdot X + T \\le M$.This is a standard task where we need to calculate all integer points under a line that can be done with the euclidean algorithm. Here the example of a plot of this function:",
    "tags": [
      "binary search",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1098",
    "index": "F",
    "title": "Ж-function",
    "statement": "The length of the longest common prefix of two strings $s=s_1 s_2 \\ldots s_n$ and $t = t_1 t_2 \\ldots t_m$ is defined as the maximum $k \\le \\min(n, m)$ such that $s_1 s_2 \\ldots s_k$ equals $t_1 t_2 \\ldots t_k$. Let's denote the longest common prefix of two strings $s$ and $t$ as $lcp(s,t)$.\n\nZ-function of a string $s_1 s_2 \\dots s_n$ is a sequence of integers $z_1, z_2, \\ldots, z_n$, where $z_i = lcp(s_1 s_2 \\ldots s_n,\\ \\ s_i s_{i+1} \\dots s_n)$. Ж-function of a string $s$ is defined as $z_1 + z_2 + \\ldots + z_n$.\n\nYou're given a string $s=s_1 s_2 \\ldots s_n$ and $q$ queries. Each query is described by two integers $l_i$ and $r_i$, where $1 \\le l_i \\le r_i \\le n$. The answer for the query is defined as Ж-function of the string $s_{l_i} s_{l_i +1} \\ldots s_{r_i}$.",
    "tutorial": "Answer for query $l$, $r$ is equal to $\\sum^{r}_{i=l}{\\min(lcp(l,i), r - i + 1)}$. $lcp(i, l)$ is the length of longest common preffix of $i$-th and $l$-th suffixes. Let $\\min(lcp(l,i), r - i + 1)$ be denoted by <<cutted $lcp$>> of two suffixes. Now we can use another approach to calculate the answer. For each $k = 1 \\ldots r - l + 1$ let's count number of suffixes $i = l \\ldots r$ with <<cutted $lcp$>> $\\geq k$, it is equal to number of suffixes $i = l \\ldots r - k + 1$ with $lcp$ $\\geq k$. The sum of these values will be an answer. Let's build the suffix tree of our string. To count this value for fixed $k$ and $l$, let's consider an ancestor of $l$-th suffix with depth equal to $k$, number of sought for suffixes is equal to a number of suffixes with numbers from $l$ to $r - k + 1$ in the subtree of our vertex. So let's suppose that for each vertex $v$ there is a data structre, which can count number of leaves with numbers from $l$ to $r-h_v+1$ ($h_v$ is the depth of $v$) in subtree of $v$ for fixed $l$ and $r$. Now to get an answer for query we should find sum of these sums for given $l$ and $r$ for all ancestors with depth $\\leq r - l + 1$ of vertex which corresponds the substring of request. Now we can just divide the request into two parts! We should count the number of leaves with numbers $\\leq r - h_v + 1$ and number of leaves with numbers $< l$. The first part is similar to counting number of leaves (in subtree) with numbers $x$, that $x + h_v \\leq r + 1$. Now we should use Heavy-light decompositin of our suffix tree to find sum on way. Let's consider all $\\mathcal{O}(\\log n)$ heavy ways which are above the fixed leaf. Our vertex appears in some prefixes of these ways, and its values are $x+h_v, x+h_v + 1, \\ldots, x+h_v+len$. So on each way there are some leaves determined by ($x + h_v, len$) which should be considered. Lets denote these pairs by ($x_i, y_i$). Now we just need to count number of $(i, j)$, that $0 \\leq j \\leq y_i$ and $x_i + j \\leq r + 1$. I.e. for each query we should calculate $\\sum{\\max(0, \\min(r + 1 - x_i, y_j))}$ on prefixes of considered heavy ways. Now we can use scaning line and Fenwick tree for each way to process all queries. It would be easy for you to find out how to do it if you understood everything before ;). The second part can be done similary, but in this case each leaf corresponds a point, not linear function. The complexity is $\\mathcal{O}(n \\log^2 n)$, which easily passes TL.",
    "tags": [
      "string suffix structures",
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1099",
    "index": "A",
    "title": "Snowball",
    "statement": "Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain.\n\nInitially, snowball is at height $h$ and it has weight $w$. Each second the following sequence of events happens: snowball's weights increases by $i$, where $i$ — is the current height of snowball, then snowball hits the stone (if it's present at the current height), then snowball moves one meter down. If the snowball reaches height zero, it stops.\n\nThere are exactly two stones on the mountain. First stone has weight $u_1$ and is located at height $d_1$, the second one — $u_2$ and $d_2$ respectively. When the snowball hits either of two stones, it loses weight equal to the weight of that stone. If after this snowball has negative weight, then its weight becomes zero, but the snowball continues moving as before.\n\nFind the weight of the snowball when it stops moving, that is, it reaches height 0.",
    "tutorial": "This problem can be solved in many ways, we will tell you one of them. Let's just iterate through all the heights of $i$ from $h$ to $1$. Inside the loop, we have to add $i$ to the weight of snowball, and then check whether there is a stone at this height. If there is, then you need to check whether weight of snowball is more than weight of the stone. If more - then subtract the weight of the stone from weight of snowball, if not - then assign the weight of snowball value 0.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1099",
    "index": "B",
    "title": "Squares and Segments",
    "statement": "Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw $n$ squares in the snow with a side length of $1$. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length $1$, parallel to the coordinate axes, with vertices at integer points.\n\nIn order to draw a segment, Sofia proceeds as follows. If she wants to draw a vertical segment with the coordinates of the ends $(x, y)$ and $(x, y+1)$. Then Sofia looks if there is already a drawn segment with the coordinates of the ends $(x', y)$ and $(x', y+1)$ for some $x'$. If such a segment exists, then Sofia quickly draws a new segment, using the old one as a guideline. If there is no such segment, then Sofia has to take a ruler and measure a new segment for a long time. Same thing happens when Sofia wants to draw a horizontal segment, but only now she checks for the existence of a segment with the same coordinates $x$, $x+1$ and the differing coordinate $y$.\n\nFor example, if Sofia needs to draw one square, she will have to draw two segments using a ruler:\n\nAfter that, she can draw the remaining two segments, using the first two as a guide:\n\nIf Sofia needs to draw two squares, she will have to draw three segments using a ruler:\n\nAfter that, she can draw the remaining four segments, using the first three as a guide:\n\nSofia is in a hurry, so she wants to minimize the number of segments that she will have to draw with a ruler without a guide. Help her find this minimum number.",
    "tutorial": "Consider any resulting configuration of the squares. We can safely assume that a set of non-empty rows and non-empty columns are connected (otherwise just move the disconnected part a bit closer to any other). Clearly, in every column and every row we can <<for free>> extend it to have all the squares in the bounding box - minimum rectangle containing the resulting figure. From this we can conclude that we can search for the optimal answer among the rectangles. The answer for a rectangle $a \\times b$ equals $a+b$ (just draw the first row and the first column), so we need to find two values $a$ and $b$ such that $a \\times b \\ge n$ and $a + b$ is minimum possible. It's easy to see that the answer is not optimal if $|a-b| \\ge 2$: by moving the numbers towards each other we get the same sum, but greater product. This observation leads to the following solution: if $s=[\\sqrt n]$, then the answer is either a rectangle $s \\times s$, or a rectangle $s \\times (s+1)$, or a rectangle $(s+1) \\times (s+1)$ (because of the rounding). We just need to check which one is better.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1099",
    "index": "C",
    "title": "Postcard",
    "statement": "Andrey received a postcard from Irina. It contained only the words \"Hello, Andrey!\", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.\n\nAndrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.\n\nFor example, consider the following string:\n\nThis string can encode the message «happynewyear». For this, candy canes and snowflakes should be used as follows:\n\n- candy cane 1: remove the letter w,\n- snowflake 1: repeat the letter p twice,\n- candy cane 2: leave the letter n,\n- snowflake 2: remove the letter w,\n- snowflake 3: leave the letter e.\n\nPlease note that the same string can encode different messages. For example, the string above can encode «hayewyar», «happpppynewwwwwyear», and other messages.\n\nAndrey knows that messages from Irina usually have a length of $k$ letters. Help him to find out if a given string can encode a message of $k$ letters, and if so, give an example of such a message.",
    "tutorial": "If the string in the postcard does not contain any snowflakes or candy cones, $k$ must be equal to the length of the string, because the only string encoded by such message is the string itself, and in this case if $k$ is not equal to the length of the string, the answer is <<Impossible>>. Let's call the characters of the message mandatory if they are not followed by snowflakes or candy cones. Clearly $k$ should be at least the number of mandatory characters, otherwise the answer is <<Impossible>>. In case there a snowflake (*) in the message, we can repeat the preceding character enough times to get the length $k$, and remove the rest of non-mandatory characters. If there are no snowflakes, but only candy cones, we should use the characters followed by candy cones until we get the desired length $k$. In case we don't have enough, the answer is <<Impossible>>.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1099",
    "index": "F",
    "title": "Cookies",
    "statement": "Mitya and Vasya are playing an interesting game. They have a rooted tree with $n$ vertices, and the vertices are indexed from $1$ to $n$. The root has index $1$. Every other vertex $i \\ge 2$ has its parent $p_i$, and vertex $i$ is called a child of vertex $p_i$.\n\nThere are some cookies in every vertex of the tree: there are $x_i$ cookies in vertex $i$. It takes exactly $t_i$ time for Mitya to eat \\textbf{one} cookie in vertex $i$. There is also a chip, which is initially located in the root of the tree, and it takes $l_i$ time to move the chip along the edge connecting vertex $i$ with its parent.\n\nMitya and Vasya take turns playing, Mitya goes first.\n\n- Mitya moves the chip from the vertex, where the chip is located, to one of its children.\n- Vasya can remove an edge from the vertex, where the chip is located, to one of its children. Vasya can also decide to skip his turn.\n\nMitya can stop the game at any his turn. Once he stops the game, he moves the chip up to the root, eating some cookies along his way. Mitya can decide how many cookies he would like to eat in every vertex on his way. The total time spent on descend, ascend and eating cookies should not exceed $T$. Please note that in the end of the game the chip is always located in the root of the tree: Mitya can not leave the chip in any other vertex, even if he has already eaten enough cookies — he must move the chip back to the root (and every move from vertex $v$ to its parent takes $l_v$ time).\n\nFind out what is the maximum number of cookies Mitya can eat, regardless of Vasya's actions.",
    "tutorial": "If Mitya moves the chip to vertex $i$ during the game and then moves it back to the root, he will have exactly $T - 2 \\cdot (\\text{time to reach vertex $i$ from the root})$ time to eat cookies. Let's denote the maximum number of cookies he can eat during this time by $f[i]$. Let's first focus on what to do next, assuming we have already computed $f[i]$. We can use DFS to compute $dp[i]$ - the maximum number of cookies Mitya can eat if he finishes the game in the subtree of vertex $i$ (vertex $i$ itself included). Let $m1[i]$ and $m2[i]$ be the indices of two children of vertex $i$ with maximum value $dp[j]$ among its children. It's simple to compute $dp[i]$: In case vertex $i$ is a leaf, $dp[i] = f[i]$, since we can not move any further. In case vertex $i$ is a root of the tree, we have two choices: either stop the game, or go to the child with the maximum value of $dp$, which means $dp[i] = \\max(f[i],\\ dp[m1[i]])$ in this case. Otherwise, if we're in the vertex $i$, Vasya can remove an edge to any child $j$ of vertex $i$, and clearly he would remove the one with maximum value of $dp$, meaning he would remove the edge from $i$ to $m1[i]$. This means $dp[i] = \\max(f[i],\\ dp[m2[i]])$, because we can also decide to stop the game in vertex $i$. The only thing left now is how to compute values $f[i]$ efficiently. We can do it with another DFS: while traversing the tree, for vertex $i$ we maintain the pairs $(t_j,\\ x_j)$ for all vertices on the path from the root to vertex $i$. Clearly Mitya would prefer to eat the cookies that he can eat quickly, so we maintain these vertices ordered by $t_j$ in increasing order, and to compute the answer for vertex $i$, we just eat the cookies from \"fastest\" to \"slowest\" until we run out of time. To do it efficiently, one can use their favourite data structure (BIT / Segment Tree / Treap) while traversing the tree, which leads to $O(n \\log n)$ solution.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dp",
      "games",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1100",
    "index": "A",
    "title": "Roman and Browser",
    "statement": "This morning, Roman woke up and opened the browser with $n$ opened tabs numbered from $1$ to $n$. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.\n\nHe decided to accomplish this by closing every $k$-th ($2 \\leq k \\leq n - 1$) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be $b$) and then close all tabs with numbers $c = b + i \\cdot k$ that satisfy the following condition: $1 \\leq c \\leq n$ and $i$ is an integer (it may be positive, negative or zero).\n\nFor example, if $k = 3$, $n = 14$ and Roman chooses $b = 8$, then he will close tabs with numbers $2$, $5$, $8$, $11$ and $14$.\n\nAfter closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it $e$) and the amount of remaining social network tabs ($s$). Help Roman to calculate the maximal absolute value of the difference of those values $|e - s|$ so that it would be easy to decide what to do next.",
    "tutorial": "The constraints in this task allowed us to simply iterate over the closed tab and check the answer, but we can solve it more quickly - calculate the sum for each value modulo $k$ and count the total sum for the whole array. After that, you just need to go through the module tab numbers that we delete, and update the answer. Complexity - $O (n ^ 2)$ or $O (n + k)$.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1100",
    "index": "B",
    "title": "Build a Contest",
    "statement": "Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $n$ problems of distinct difficulty, the difficulties are numbered from $1$ to $n$.\n\nTo hold a round Arkady needs $n$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $1$ to $n$ and puts it into the problems pool.\n\nAt each moment when Arkady can choose a set of $n$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.\n\nYou are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.",
    "tutorial": "We will keep the arrays, how many problems are created for each specific complexity $i$ - $cnt_i$ and how many problems have been created for the round $j$ - $exist_j$. Then if we create a task with complexity $c$, we will recalculate $cnt_c = cnt_c + 1$, $exist_ {cnt_c} = exist_ {cnt_c} + 1$. Suppose we have already given $k$ rounds. Then, after adding the next task, we only need to check that $exist_k = n$, in this case we can held the next round, otherwise not. The complexity is $O (m)$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1100",
    "index": "C",
    "title": "NN and the Optical Illusion",
    "statement": "NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles:\n\nIt turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.\n\nHe managed to calculate the number of outer circles $n$ and the radius of the inner circle $r$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $R$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that.\n\nHelp NN find the required radius for building the required picture.",
    "tutorial": "Consider three circles - inner and two outer. Since all the circles are tangent, the sides of the triangle constructed on the centers of the circles pass through the tangency points of the circles. Denote by $\\alpha$ the angle in an equilateral $n$ -gon. Then $\\alpha = \\frac {\\pi (n - 2)} {n}$. On the other hand, $\\frac {R} {r + R} = \\cos (\\frac {\\ alpha} {2})$. It can be noted that $\\frac {R} {r + R} = \\frac {R + r - r} {r + R} = 1 - \\frac {r} {r + R}$, i.e. the function increases with $R$. On this basis, a binary search can be used to find the answer, or explicitly derive the formula $R = r \\frac {\\cos (\\frac {\\alpha} {2})} {1 - \\cos (\\frac {\\alpha} {2} )}$ The complexity is $O (1)$ or $O (\\log C)$.",
    "tags": [
      "binary search",
      "geometry",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1100",
    "index": "D",
    "title": "Dasha and Chess",
    "statement": "This is an interactive task.\n\nDasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.\n\nThere are $666$ black rooks and $1$ white king on the chess board of size $999 \\times 999$. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.\n\nThe sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square $(x, y)$, it can move to the square $(nx, ny)$ if and only $\\max (|nx - x|, |ny - y|) = 1$ , $1 \\leq nx, ny \\leq 999$. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.\n\nDasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.\n\nEach player makes $2000$ turns, if the white king wasn't checked by a black rook during those turns, black wins.\n\nNN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.",
    "tutorial": "One of the possible strategies: the king goes to the center, then goes to the corner that he has as few rooks as possible behind his back. The solution uses the Pigeonhole principle, since in the largest corner and in two neighbors to it, the sum will be no less than $666 * 3/4 > 499$ rooks, i.e. $\\geq 500$ rooks, and since the king gets to the corner for $499$ of moves, he will definitely get under check of the rook.",
    "tags": [
      "constructive algorithms",
      "games",
      "interactive"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1100",
    "index": "E",
    "title": "Andrew and Taxi",
    "statement": "Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to insidious taxi drivers.\n\nThe mayor of the city decided to change the direction of certain roads so that the taxi drivers wouldn't be able to increase the cost of the trip endlessly. More formally, if the taxi driver is on a certain crossroads, they wouldn't be able to reach it again if he performs a nonzero trip.\n\nTraffic controllers are needed in order to change the direction the road goes. For every road it is known how many traffic controllers are needed to change the direction of the road to the opposite one. It is allowed to change the directions of roads one by one, meaning that each traffic controller can participate in reversing two or more roads.\n\nYou need to calculate the minimum number of traffic controllers that you need to hire to perform the task and the list of the roads that need to be reversed.",
    "tutorial": "Suppose we have $k$ traffic controllers. They can turn all edges whose weight is less than or equal to $k$. Then let's remove all these edges from the graph, make a topological sorting of the remaining graph, and orient the other edges in the order of topological sorting. If there are cycles left in the graph after removing the edges, then we cannot get rid of them, having $k$ traffic controllers. Otherwise, by adding edges we will not add new loops. The parameter $k$ can be iterated through a binary search. Also in binary search, you can go through not all possible values of $k$, but only the values that are on the edges. Complexity - $O ((n + m) \\log C)$ or $O ((n + m) \\log m)$.",
    "tags": [
      "binary search",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1100",
    "index": "F",
    "title": "Ivan and Burgers",
    "statement": "Ivan loves burgers and spending money. There are $n$ burger joints on the street where Ivan lives. Ivan has $q$ friends, and the $i$-th friend suggested to meet at the joint $l_i$ and walk to the joint $r_i$ $(l_i \\leq r_i)$. While strolling with the $i$-th friend Ivan can visit all joints $x$ which satisfy $l_i \\leq x \\leq r_i$.\n\nFor each joint Ivan knows the cost of the most expensive burger in it, it costs $c_i$ burles. Ivan wants to visit some subset of joints on his way, in each of them he will buy the most expensive burger and spend the most money. But there is a small issue: his card broke and instead of charging him for purchases, the amount of money on it changes as follows.\n\nIf Ivan had $d$ burles before the purchase and he spent $c$ burles at the joint, then after the purchase he would have $d \\oplus c$ burles, where $\\oplus$ denotes the bitwise XOR operation.\n\nCurrently Ivan has $2^{2^{100}} - 1$ burles and he wants to go out for a walk. Help him to determine the maximal amount of burles he can spend if he goes for a walk with the friend $i$. The amount of burles he spends is defined as the difference between the initial amount on his account and the final account.",
    "tutorial": "Note that to answer on a segment, it is enough to know the basis of this segment, that is, the minimum set of numbers, with which you can represent all the numbers that are representable on this segment. Since $0 \\leq a_i \\leq 1000000$, then the basis will be no more than $20$. To find the maximum number, run the Gauss algorithm for the basis so that there is no pair of numbers in the basis for which the maximum bit is the same. Then the maximum representable number can be obtained by the following algorithm: we will consider the numbers starting from the maximum, and add them to the answer if they increase the current answer. The complete problem can be solved using the \"divide and conquer\" method: if we split the segment in half, then all requests on it either completely lie into one of the segments, or lieinto both. For requests that completely lie in one of the segments, we respond recursively. For queries that fall in both segments, we combine two linear hulls - $hull [l, mid]$ and $hull [mid + 1, r]$. All linear hulls of the form $hull [i, mid]$ and $hull [mid + 1, j]$ can be obtained by adding vectors sequentially from right to left (on the right segment from left to right). An alternative solution was proposed at the contest. Note that a query on a segment is a suffix of some array prefix. We will gradually increase the array prefix and maintain the \"maximally right\" array basis (if for the current prefix we go right through to the left, then the \"maximally right\" basis is the greedily typed basis of array values). When adding an element, it can either not be presented in the current basis, then it must be added to the current basis. If we can represent the element, then it is necessary to find the left-most element whose removal does not change the linear hull. This can be done by simulating Gauss algorithm from right to left: the first representable element must be removed from the basis. Since the basis is small, this operation can be done with each addition of a vector. We can get the answer to the problem, since for the fixed right element, we know at what point the basis changes as the left border moves from right to left. Complexity is $O ((n + q) \\log ^ 2 C)$ or $O (n \\log^2 C + q)$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "greedy",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1101",
    "index": "A",
    "title": "Minimum Integer",
    "statement": "You are given $q$ queries in the following form:\n\n{Given three integers $l_i$, $r_i$ and $d_i$, find minimum \\textbf{positive} integer $x_i$ such that it is divisible by $d_i$ and it does not belong to the segment $[l_i, r_i]$}.\n\nCan you answer all the queries?\n\nRecall that a number $x$ belongs to segment $[l, r]$ if $l \\le x \\le r$.",
    "tutorial": "There are two basic cases we have to consider: either the element we want to find is less than $l_i$, or it is greater than $r_i$. In the first case, we are interested in $d_i$ itself: it is the minimum positive number divisible by $d_i$, and if it is less than $l_i$, then it is the answer. In the second case, we have to find minimum element that is greater than $r_i$ and is divisible by $d_i$. This can be done as follows: we calculate the number of elements divisible by $d_i$ that are not greater than $r_i$ as $c = \\lfloor \\frac{r_i}{d_i} \\rfloor$, and then we take $(c+1)$-th element, which is $d_i(c + 1)$.",
    "code": "q = int(input())\nfor i in range(q):\n    l, r, d = map(int, input().split())\n    if(d < l or d > r):\n        print(d)\n    else:\n        print((r // d) * d + d)",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1101",
    "index": "B",
    "title": "Accordion",
    "statement": "An accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code $091$), a colon (ASCII code $058$), some (possibly zero) vertical line characters (ASCII code $124$), another colon, and a closing bracket (ASCII code $093$). The length of the accordion is the number of characters in it.\n\nFor example, [::], [:||:] and [:|||:] are accordions having length $4$, $6$ and $7$. (:|:), {{:||:}}, [:], ]:||:[ are not accordions.\n\nYou are given a string $s$. You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from $s$, and if so, what is the maximum possible length of the result?",
    "tutorial": "No cases. No any special thoughts. Just greedy. The solution consists of six steps: Remove the prefix of the string until the position of leftmost '[' character. If there is no such character, print -1; Remove the prefix of the string until the position of leftmost ':' character. If there is no such character, print -1; Reverse the string; Remove the prefix of the string until the position of leftmost ']' character. If there is no such character, print -1; Remove the prefix of the string until the position of leftmost ':' character. If there is no such character, print -1; Print the number of '|' characters in the remaining string plus four.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid rem(string &s, const string &c) {\n\tauto pos = s.find(c);\n\tif (pos == string::npos) {\n\t\tcout << -1 << endl;\n\t\texit(0);\n\t}\n\ts.erase(0, pos + 1);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tstring s;\n\tcin >> s;\n\t\n\trem(s, \"[\");\n\trem(s, \":\");\n\treverse(s.begin(), s.end());\n\trem(s, \"]\");\n\trem(s, \":\");\n\t\n\tcout << count(s.begin(), s.end(), '|') + 4 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1101",
    "index": "C",
    "title": "Division and Union",
    "statement": "There are $n$ segments $[l_i, r_i]$ for $1 \\le i \\le n$. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group.\n\nTo optimize testing process you will be given multitest.",
    "tutorial": "Let's prove that division possible if and only if union of all segments has two and more segments. If the union have at least two segments, then we can choose one of them and put all segments it contains in one group and other segments to another group. On the other hand, if we can divide all segments in two groups in such way that there are no pair from different group which intersects, then union of segments from the first group doesn't intersect union of segments from another and union of unions consists of several non-intersecting components. How can it help? If union of segments consits of several segments then exists $x$ such that for any segment $[l_i, r_i]$ either $l_i \\le r_i \\le x$ or $x < l_i \\le r_i$ and both parts are non-empty. Moreover, $x$ equals to one of $r_i$. It leads us straight to one of possible solutions: sort all segments by $r_i$ in increasing order and for each $r_i$ we should check that $r_i < \\min\\limits_{i < j \\le n}{l_j}$ (suffix minimum). If we've found such $r_i$ then all prefix goes to one group and suffix - to another.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n\ntypedef pair<int, int> pt;\n\nint n;\nvector< pair<pt, int> > segs;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\tsegs.resize(n);\n\tfor(int i = 0; i < n; i++) {\n\t\tcin >> segs[i].x.x >> segs[i].x.y;\n\t\tsegs[i].y = i;\n\t}\n\treturn true;\n}\n\nbool cmp(const pair<pt, int> &a, const pair<pt, int> &b) {\n\tif(a.x.y != b.x.y)\n\t\treturn a.x.y < b.x.y;\n\tif(a.x.x != b.x.x)\n\t\treturn a.x.x < b.x.x;\n\treturn a.y < b.y;\n}\n\ninline void solve() {\n\tsort(segs.begin(), segs.end(), cmp);\n\t\n\tint mn = segs[n - 1].x.x;\n\tfor(int i = n - 2; i >= 0; i--) {\n\t\tif(segs[i].x.y < mn) {\n\t\t\tvector<int> ts(n, 2);\n\t\t\tfor(int id = 0; id <= i; id++)\n\t\t\t\tts[segs[id].y] = 1;\n\t\t\t\n\t\t\tfor(int t : ts)\n\t\t\t\tcout << t << ' ';\n\t\t\tcout << '\\n';\n\t\t\t\t\n\t\t\treturn;\n\t\t}\n\t\tmn = min(mn, segs[i].x.x);\n\t}\n\tcout << -1 << '\\n';\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc;\n\tcin >> tc;\n\t\n\twhile(tc--) {\n\t\tassert(read());\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1101",
    "index": "D",
    "title": "GCD Counting",
    "statement": "You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.\n\nLet's denote the function $g(x, y)$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $x$ to vertex $y$ (including these two vertices). Also let's denote $dist(x, y)$ as the number of vertices on the simple path between vertices $x$ and $y$, including the endpoints. $dist(x, x) = 1$ for every vertex $x$.\n\nYour task is calculate the maximum value of $dist(x, y)$ among such pairs of vertices that $g(x, y) > 1$.",
    "tutorial": "I know there exists $O(n \\log MAXN)$ solution and author of the problem promises to tell it to you (here he explained it). I'd love to tell easier to code and about the same time to work $O(n \\log^2 MAXN)$ solution. At first, notice that it is only enough to check the paths such that all vertices on it is divisible by some prime. Let's for each $v$ calculate the path of the maximum length to pass through it. That means that one part of this path goes down to one child of it and another part goes down to another child. For each vertex we will store the lengths of maximum paths through vertices with values divisible by each prime in $a_v$. That is $O(n \\log MAXN)$ memory. To recalc the answer we will store all values of children nodes, sort them and update the answer with two pointers technique. Don't forget about the case of $n = 1$! Overall complexity: $O(n \\log^2 MAXN)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define sqr(a) ((a) * (a))\n#define sz(a) int(a.size())\n#define all(a) a.begin(), a.end()\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {\n\treturn out << \"(\" << a.x << \", \" << a.y << \")\";\n}\n\ntemplate <class A> ostream& operator << (ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tforn(i, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nmt19937 rnd(time(NULL));\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst int MOD = INF + 7;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n\nconst int N = 200 * 1000 + 13;\n\nint n;\nint a[N];\nvector<int> g[N];\n\nbool read () {\n\tif (scanf(\"%d\", &n) != 1)\n\t\treturn false;\n\tforn(i, n)\n\t\tg[i].clear();\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\tforn(i, n - 1){\n\t\tint x, y;\n\t\tscanf(\"%d%d\", &x, &y);\n\t\t--x, --y;\n\t\tg[x].pb(y);\n\t\tg[y].pb(x);\n\t}\n\treturn true;\n}\n\nvector<pt> dp[N];\nint ans;\n\nvoid calc(int v, int p = -1){\n\tvector<pt> chd;\n\tfor (auto u : g[v]) if (u != p){\n\t\tcalc(u, v);\n\t\tfor (auto it : dp[u])\n\t\t\tchd.pb(it);\n\t}\n\t\n\tsort(all(chd));\n\tforn(i, sz(chd)){\n\t\tint j = i - 1;\n\t\tint mx1 = 0, mx2 = 0;\n\t\twhile (j + 1 < sz(chd) && chd[j + 1].x == chd[i].x){\n\t\t\t++j;\n\t\t\tif (chd[j].y >= mx1)\n\t\t\t\tmx2 = mx1, mx1 = chd[j].y;\n\t\t\telse if (chd[j].y > mx2)\n\t\t\t\tmx2 = chd[j].y;\n\t\t}\n\t\tif (a[v] % chd[i].x == 0){\n\t\t\tans = max(ans, mx1 + mx2 + 1);\n\t\t\tdp[v].pb(mp(chd[i].x, mx1 + 1));\n\t\t\twhile (a[v] % chd[i].x == 0)\n\t\t\t\ta[v] /= chd[i].x;\n\t\t}\n\t\telse{\n\t\t\tans = max(ans, mx1);\n\t\t}\n\t\ti = j;\n\t}\n\t\n\tfor (int i = 2; i * i <= a[v]; ++i) if (a[v] % i == 0){\n\t\tdp[v].pb(mp(i, 1));\n\t\tans = max(ans, 1);\n\t\twhile (a[v] % i == 0)\n\t\t\ta[v] /= i;\n\t}\n\t\n\tif (a[v] > 1){\n\t\tdp[v].pb(mp(a[v], 1));\n\t\tans = max(ans, 1);\n\t}\n}\n\nvoid solve() {\n\tforn(i, N) dp[i].clear();\n\tans = 0;\n\tcalc(0);\n\tprintf(\"%d\\n\", ans);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n\t\n\tint tt = clock();\n\t\n#endif\n\t\n\tcerr.precision(15);\n\tcout.precision(15);\n\tcerr << fixed;\n\tcout << fixed;\n\n#ifdef _DEBUG\n\twhile(read()) {\t\n#else\n\tif (read()){\n#endif\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\tcerr << \"TIME = \" << clock() - tt << endl;\n\ttt = clock();\n#endif\n\n\t}\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "number theory",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1101",
    "index": "E",
    "title": "Polycarp's New Job",
    "statement": "Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.\n\nBerland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).\n\nA bill $x \\times y$ fits into some wallet $h \\times w$ if either $x \\le h$ and $y \\le w$ or $y \\le h$ and $x \\le w$. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.\n\nNow you are asked to perform the queries of two types:\n\n- $+~x~y$ — Polycarp earns a bill of size $x \\times y$;\n- $?~h~w$ — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $h \\times w$.\n\nIt is guaranteed that there is at least one query of type $1$ before the first query of type $2$ and that there is at least one query of type $2$ in the input data.\n\nFor each query of type $2$ print \"YES\" if all the bills he has earned to this moment fit into a wallet of given size. Print \"NO\" otherwise.",
    "tutorial": "Let's find the smallest wallet to fit all bills. One its side is the maximum side of any bill. Now we orient the bills in such a way that their longer side is put against this side of the wallet. The second side of the wallet is the maximum of the other sides. More formally, for set of bills $(a_1, b_1)$, $(a_2, b_2)$, ... ($a_i \\le b_i$ for each $i$), the minimum wallet is ($max~a_i$, $max~b_i$). The minimum wallet fits all sufficient wallets. So the solution is maintaining the maximum of all $a_i$ and $b_i$ and checking if $h \\ge a_i$ and $w \\ge b_i$ ($h \\le w$). Choose your i/o functions wisely. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tint mxa = 0, mxb = 0;\n\tstatic char buf[5];\n\tforn(i, n){\n\t\tint x, y;\n\t\tscanf(\"%s%d%d\", buf, &x, &y);\n\t\tif (x < y)\n\t\t\tswap(x, y);\n\t\tif (buf[0] == '+'){\n\t\t\tmxa = max(mxa, x);\n\t\t\tmxb = max(mxb, y);\n\t\t}\n\t\telse{\n\t\t\tputs(mxa <= x && mxb <= y ? \"YES\" : \"NO\");\n\t\t}\n\t}\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1101",
    "index": "F",
    "title": "Trucks and Cities",
    "statement": "There are $n$ cities along the road, which can be represented as a straight line. The $i$-th city is situated at the distance of $a_i$ kilometers from the origin. All cities are situated in the same direction from the origin. There are $m$ trucks travelling from one city to another.\n\nEach truck can be described by $4$ integers: starting city $s_i$, finishing city $f_i$, fuel consumption $c_i$ and number of possible refuelings $r_i$. The $i$-th truck will spend $c_i$ litres of fuel per one kilometer.\n\nWhen a truck arrives in some city, it can be refueled (but refueling is impossible in the middle of nowhere). The $i$-th truck can be refueled at most $r_i$ times. Each refueling makes truck's gas-tank full. All trucks start with full gas-tank.\n\nAll trucks will have gas-tanks of the same size $V$ litres. You should find minimum possible $V$ such that all trucks can reach their destinations without refueling more times than allowed.",
    "tutorial": "First (bonus) solution: implement idea from Blogewoosh #6. Time complexity will be somewhat $O((q + \\log{q} \\log{\\text{MAX}})n)$ and space complexity is $O(n + q)$. Honest solution: Note, that for each truck lower bound on the answer is $\\max(c_i \\cdot (a[p_{j + 1}] - a[p_{j}])) = c_i \\cdot \\max(a[p_{j + 1}] - a[p_j])$, where $p_0 = s_i, p_1, p_2, \\dots, p_{r_i + 1} = f_i$ is optimal partition of $[a[s_i], a[f_i]]$ on $r_i + 1$ segments (partition which minimize maximum length of segment) and doesn't depend on $c_i$ of truck. So, it enough to calculate $d[l][r][k]$ - optimal partition of segment $[a[l], a[r]]$ on $k$ segments. Let $opt[l][r][k]$ be position, where last segment starts in partition with value $d[l][r][k]$. Note, that $opt[l][r][k] \\le opt[l][r + 1][k]$. On the other hand, $d[l][r][k] = \\min\\limits_{l \\le j \\le r}(\\max(d[l][j][k - 1], a[r] - a[j]))$. But $d[l][j][k - 1] \\le d[l][j + 1][k - 1]$ and $a[r] - a[j] > a[r] - a[j + 1]$, then $\\max(d[l][j][k - 1], a[r] - a[j])$ is somewhat \"convex\". Finally, best $j$ is no more than $opt[l][r][k]$, And we can look at $j$ as second pointer (along with $r$ as first pointer). So we can for each $r$ move $j$ while answer \"relaxes\" (while answer is decreasing or staying same). In result, for each $l$ and $k$ there will be $O(n)$ operations in total. Optimizing memory consumption is easy, if we notice that we can iterate over $l$ but not save it as state of dp. In the end, time complexity is $O(n^3 + q)$ and space complexity is $O(n^2 + q)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n\n#define mp make_pair\n#define pb push_back\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst int N = 411;\n\nint n, m;\nint a[N];\nvector< pair<pt, pt> > qs;\n\ninline bool read() {\n\tif(!(cin >> n >> m))\n\t\treturn false;\n\tfore(i, 0, n)\n\t\tcin >> a[i];\n\tqs.resize(m);\n\tfore(i, 0, m) {\n\t\tcin >> qs[i].x.x >> qs[i].x.y >> qs[i].y.x >> qs[i].y.y;\n\t\tqs[i].x.x--; qs[i].x.y--;\n\t}\n\treturn true;\n}\n\nint getCnt(const pair<pt, pt> &q, li mx) {\n\tli dist = mx / q.y.x;\n\t\n\tint s = q.x.x, f = q.x.y;\n\tint u = s, cnt = 0;\n\twhile(u < f) {\n\t\tint v = u;\n\t\twhile(v < f && a[v + 1] - a[u] <= dist)\n\t\t\tv++;\n\t\t\n\t\tif(v == u)\n\t\t\treturn INF;\n\t\t\n\t\tcnt++;\n\t\tu = v;\n\t}\n\treturn cnt - 1;\n}\n\nli upd(const pair<pt, pt> &q, li lf, li rg) {\n\tif(getCnt(q, lf) <= q.y.y)\n\t\treturn lf;\n\t\n\twhile(rg - lf > 1) {\n\t\tli mid = (lf + rg) >> 1;\n\t\t(getCnt(q, mid) <= q.y.y ? rg : lf) = mid;\n\t}\n\treturn rg;\n}\n\ninline unsigned int getHash(const vector<int> &vals) {\n\tunsigned int hash = 0;\n\tfor(int v : vals)\n\t\thash = hash * 3 + v;\n\treturn hash;\n}\n\ninline void solve() {\n\tauto seed = getHash(vector<int>(a, a + n));\n\tfore(i, 0, m)\n\t\tseed = seed * 3 + getHash({qs[i].x.x, qs[i].x.y, qs[i].y.x, qs[i].y.y});\n\tmt19937 rnd(seed);\n\t\n\tvector<int> ids(m, 0);\n\tiota(all(ids), 0);\n\tshuffle(all(ids), rnd);\n\t\n\tli curv = 0;\n\tfor(int id : ids)\n\t\tcurv = upd(qs[id], curv, 2 * INF64);\n\tcout << curv << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1101",
    "index": "G",
    "title": "(Zero XOR Subset)-less",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$ of integer numbers.\n\nYour task is to divide the array into the maximum number of segments in such a way that:\n\n- each element is contained in \\textbf{exactly one} segment;\n- each segment contains at least one element;\n- there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $0$.\n\nPrint the maximum number of segments the array can be divided into. Print -1 if no suitable division exists.",
    "tutorial": "Let's consider some division $[0, i_1)$, $[i_1, i_2)$, ..., $[i_k, n)$. Represent the XOR sum of the subset via prefix-XOR. Those are $pr[i_1] \\oplus pr[0]$, $pr[i_2] \\oplus pr[i_1]$, ..., $pr[n] \\oplus pr[i_k]$. I claim that you can collect any subset that is a XOR of an even number of $pr[x]$ for pairwise distinct values of $x$. Let's take a look on some prefix of processed segments, where the last segment is taken into subset. The previous taken $pr[x]$'s can't be changed, the last taken $pr[x]$ can either be eliminated if we also take the current segment (and that segment erases one value and adds one) or added to the answer if we don't take it (but the next taken segment will add two values). You can see that the parity doesn't change. Moreover, you can collect any subset that is a XOR of an odd number of $pr[x]$ for pairwise distinct values of $x$. Just forget about $pr[0]$ taken into the answer, as its value is $0$. Then all the even subsets which included it will become odd. This way we can collect all subsets of $pr[x]$ for some division. Now you just want find the division that produces the maximum number of linearly independent numbers (binary vectors). That is - the size of the basis of the space of chosen numbers (binary vectors). Now it's time to abuse the fact that adding a number into the set can only increase the size of basis of the space. Thus, adding anything to the maximum set won't change the answer (otherwise the result would be greater than the \"maximum\"). Finally, you say that the maximum basis size is equal to the basis size of all the prefix-XOR and easily calculate in $O(n \\log MAXN)$. The only corner case is $pr[n]$ being $0$ itself. Then for any division the full subset will also give $0$ result. That is the only case with answer $-1$. Overall complexity: $O(n \\log MAXN)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\nconst int LOGN = 30;\n\nint n;\nint a[N], pr[N];\nint base[LOGN];\n\nvoid try_gauss(int v){\n\tfor(int i = LOGN - 1; i >= 0; i--)\n\t\tif (base[i] != -1 && (v & (1 << i)))\n\t\t\tv ^= base[i];\n\tif (v == 0)\n\t\treturn;\n\tfor(int i = LOGN - 1; i >= 0; i--) if (v & (1 << i)){\n\t\tbase[i] = v;\n\t\treturn;\n\t}\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\tmemset(base, -1, sizeof(base));\n\tforn(i, n){\n\t\tpr[i + 1] = pr[i] ^ a[i];\n\t\ttry_gauss(pr[i + 1]);\n\t}\n\tif (pr[n] == 0){\n\t\tputs(\"-1\");\n\t\treturn 0;\n\t}\n\tint siz = 0;\n\tforn(i, LOGN)\n\t\tsiz += (base[i] != -1);\n\tprintf(\"%d\\n\", siz);\n}",
    "tags": [
      "math",
      "matrices"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1102",
    "index": "A",
    "title": "Integer Sequence Dividing",
    "statement": "You are given an integer sequence $1, 2, \\dots, n$. You have to divide it into two sets $A$ and $B$ in such a way that each element belongs to \\textbf{exactly one} set and $|sum(A) - sum(B)|$ is minimum possible.\n\nThe value $|x|$ is the absolute value of $x$ and $sum(S)$ is the sum of elements of the set $S$.",
    "tutorial": "The first solution: take $n$ modulo $4$ and solve the problem manually (then for cases $n = 0$ and $n = 3$ the answer is $0$ and for $n = 1$ and $n = 2$ the answer is $1$). Prove: Let's see what can we make for numbers $n$, $n - 1$, $n - 2$ and $n - 3$. We can add $n$ and $n - 3$ in $A$ and add $n - 1$ and $n - 2$ in $B$. Then the difference between sums will be $0$. We can consider last four numbers this way until we have at least four numbers. And then we have a case $n \\le 3$. We can prove the solution for these four cases using bruteforce. The second solution: if $\\sum\\limits_{i=1}^{n}i$ is even then the answer is $0$ otherwise the answer is $1$. The formula above is just $\\frac{n(n+1)}{2}$. Prove: if we have an integer sequence $1, 2, \\dots, n$ then we can obtain every number from $0$ to $\\frac{n(n+1)}{2}$ as the sum of some elements of this sequence. How? Greedily! You can see how this greedy works (and prove, if you want) yourself. So what's next? If $\\frac{n(n+1)}{2}$ is even then we can obtain the sum $\\frac{n(n+1)}{4}$ in $A$ and in $B$. Otherwise we can only obtain $\\lfloor\\frac{n(n+1)}{4}\\rfloor$ in $A$ and $\\lceil\\frac{n(n+1)}{4}\\rceil$ in $B$ (or vice versa).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tlong long sum = n * 1ll * (n + 1) / 2;\n\tcout << (sum & 1) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1102",
    "index": "B",
    "title": "Array K-Coloring",
    "statement": "You are given an array $a$ consisting of $n$ integer numbers.\n\nYou have to color this array in $k$ colors in such a way that:\n\n- Each element of the array should be colored in some color;\n- For each $i$ from $1$ to $k$ there should be \\textbf{at least one} element colored in the $i$-th color in the array;\n- For each $i$ from $1$ to $k$ all elements colored in the $i$-th color should be \\textbf{distinct}.\n\nObviously, such coloring might be impossible. In this case, print \"NO\". Otherwise print \"YES\" and \\textbf{any} coloring (i.e. numbers $c_1, c_2, \\dots c_n$, where $1 \\le c_i \\le k$ and $c_i$ is the color of the $i$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print \\textbf{any}.",
    "tutorial": "How can we solve this problem easily? Firstly, let's sort the initial array (but maintain the initial order of the elements in the array to restore the answer). Then let's just distribute all the colors uniformly. Let's color the first element in the first color, the second one - in the second, the $k$-th element - in the $k$-th color, the $k+1$-th - in the first color, and so on. So we color the $i$-th element in the color $(i - 1) \\% k + 1$ ($\\%$ is just modulo operation). We can see that the answer is \"NO\" if there is an element with frequency at least $k+1$ in the array (by pigeonhole principle). Otherwise our solution builds the correct answer. So we can try to find such element in the array naively, using counting sort or many other approaches. Time complexity - $O(n \\log n)$ or $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<pair<int, int>> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i].first;\n\t\ta[i].second = i;\t\n\t}\n\t\n\tsort(a.begin(), a.end());\n\t\n\tvector<vector<int>> buckets(k);\n\tvector<int> res(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tbuckets[i % k].push_back(a[i].first);\n\t\tres[a[i].second] = i % k;\n\t}\n\t\n\tfor (int i = 0; i < k; ++i) {\n\t\tfor (int j = 0; j < int(buckets[i].size()) - 1; ++j) {\n\t\t\tif (buckets[i][j] == buckets[i][j + 1]) {\n\t\t\t\tcout << \"NO\" << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << \"YES\" << endl;\n\tfor (int i = 0; i < n; ++i) {\n\t\tcout << res[i] + 1 << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1102",
    "index": "C",
    "title": "Doors Breaking and Repairing",
    "statement": "You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.\n\nThere are $n$ doors, the $i$-th door initially has durability equal to $a_i$.\n\nDuring your move you can try to break one of the doors. If you choose door $i$ and its current durability is $b_i$ then you reduce its durability to $max(0, b_i - x)$ (the value $x$ is given).\n\nDuring Slavik's move he tries to repair one of the doors. If he chooses door $i$ and its current durability is $b_i$ then he increases its durability to $b_i + y$ (the value $y$ is given). \\textbf{Slavik cannot repair doors with current durability equal to $0$}.\n\nThe game lasts $10^{100}$ turns. If some player cannot make his move then he has to skip it.\n\nYour goal is to maximize the number of doors with durability equal to $0$ at the end of the game. You can assume that Slavik \\textbf{wants to minimize} the number of such doors. What is the number of such doors in the end if you both play optimally?",
    "tutorial": "Let's consider two cases: If $x > y$ then the answer is $n$ because we can make opposite moves to the Slavik's moves and it always will reduce durability of some door (so at some point we will reach the state when all doors will have durability $0$). Otherwise $x \\le y$ and we have to realize the optimal strategy for us. If we have some door with durability $z \\le x$ then let's break it immediately (why shouldn't we do this?). If we don't do it then Slavik will repair this door during his move. So what Slavik will do now? He will repair some door. Which door he has to repair? Of course the one with durability $z \\le x$ because otherwise we will break it during our next move. So we can realize that doors with durability $z > x$ are not interesting for us because Slavik will make opposite moves to our moves. And what is the answer if the number of doors with durability $z \\le x$ equals to $cnt$? It is $\\lceil\\frac{cnt}{2}\\rceil$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, x, y;\n\tcin >> n >> x >> y;\n\tint cnt = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint cur;\n\t\tcin >> cur;\n\t\tif (cur <= x) {\n\t\t\t++cnt;\n\t\t}\n\t}\n\t\n\tif (x > y) {\n\t\tcout << n << endl;\n\t} else {\n\t\tcout << (cnt + 1) / 2 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "games"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1102",
    "index": "D",
    "title": "Balanced Ternary String",
    "statement": "You are given a string $s$ consisting of exactly $n$ characters, and each character is either '0', '1' or '2'. Such strings are called \\textbf{ternary strings}.\n\nYour task is to \\textbf{replace minimum number of characters} in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').\n\nAmong all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.\n\nNote that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.\n\nIt is \\textbf{guaranteed} that the answer exists.",
    "tutorial": "Let's count how many characters '0', '1' and '2' we have in the string $s$ and store it in the array $cnt$. Also let's count our \"goal\" array $cur$. Firstly, the array $cur$ is $[\\frac{n}{3}, \\frac{n}{3}, \\frac{n}{3}]$. The main idea of this problem is a pretty standard lexicographically greedy approach. We go from left to right and try to place the minimum possible character at the current position in such a way that placing this character is not breaking conditions of our problem. How can we apply this approach to this problem? Firstly, let's define a function $need(cnt, cur) = \\frac{|cnt_0 - cur_0| + |cnt_1 - cur_1| + |cnt_2 - cur_2|}{2}$. What does the value of this function mean? It means the number of replacements we need to reach $cur$ from $cnt$. Let $initNeed = need(cur, cnt)$ at the beginning of the program. This value means the minimum number of replacements to obtain some balanced ternary string. Let's maintain the variable $curRep$ which initially is $0$ and means the number of replacements we already made. So, we iterate over all positions $i$ from $1$ to $n$. Firstly, let's decrease $cnt_{s_i}$. So the array $cnt$ maintains the current amount of characters on suffix of the string. Now let's iterate over characters $j$ from $0$ to $2$ and try to place every character. If the current character is needed ($cur_j > 0$), then let's decrease $cur_j$ and if the number of replacements will still be minimum possible after such replacement ($curRep + need(cnt, cur) + (s_i \\ne j) = initNeed$) then let's place this character, set $curRep := curRep + (s_i \\ne j)$ and go to the next position. This will form lexicographically minimum possible answer with minimum number of replacements. There is another (simpler) solution from PikMike, you can call him to explain it, I just will add his code to the editorial.",
    "code": "n = int(input())\ns = [ord(x) - ord('0') for x in input()]\ncnt = [s.count(x) for x in [0, 1, 2]]\ndef forw(x):\n\tfor i in range(n):\n\t\tif (cnt[x] < n // 3 and s[i] > x and cnt[s[i]] > n // 3):\n\t\t\tcnt[x] += 1\n\t\t\tcnt[s[i]] -= 1\n\t\t\ts[i] = x\ndef back(x):\n\tfor i in range(n - 1, -1, -1):\n\t\tif (cnt[x] < n // 3 and s[i] < x and cnt[s[i]] > n // 3):\n\t\t\tcnt[x] += 1\n\t\t\tcnt[s[i]] -= 1\n\t\t\ts[i] = x\nforw(0)\nforw(1)\nback(2)\nback(1)\nprint(''.join([str(x) for x in s]))",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1102",
    "index": "E",
    "title": "Monotonic Renumeration",
    "statement": "You are given an array $a$ consisting of $n$ integers. Let's denote monotonic renumeration of array $a$ as an array $b$ consisting of $n$ integers such that all of the following conditions are met:\n\n- $b_1 = 0$;\n- for every pair of indices $i$ and $j$ such that $1 \\le i, j \\le n$, if $a_i = a_j$, then $b_i = b_j$ (note that if $a_i \\ne a_j$, it is still possible that $b_i = b_j$);\n- for every index $i \\in [1, n - 1]$ either $b_i = b_{i + 1}$ or $b_i + 1 = b_{i + 1}$.\n\nFor example, if $a = [1, 2, 1, 2, 3]$, then two possible monotonic renumerations of $a$ are $b = [0, 0, 0, 0, 0]$ and $b = [0, 0, 0, 0, 1]$.\n\nYour task is to calculate the number of different monotonic renumerations of $a$. The answer may be large, so print it modulo $998244353$.",
    "tutorial": "We are interested in such subsegments of the array $a$ that for every value belonging to this segment all occurences of this value in the array are inside this segment. Let's call such segments closed segments. For example, if $a = [1, 2, 1, 2, 3]$, then $[1, 2, 1, 2]$, $[3]$ and $[1, 2, 1, 2, 3]$ are closed segments. We can see that the result is some partition of the given array into several closed segments - if for some value $x$ all occurences of $x$ in $b_i$ do not form a segment in $a_i$, then there exists some pair $b_i, b_{i + 1}$ such that $b_i > b_{i + 1}$ (which contradicts the statement); and if the formed segment is not a closed segment, then for some indices $i$ and $j$ such that $a_i = a_j$ it is not true that $b_i = b_j$ (which also contradicts the statement). Okay, let's try to partition the array into closed segments greedily: take the first prefix of the array that is a closed segment, erase it, take the next prefix, and so on. Let $m$ be the number of closed segments we got with this procedure. The key fact is that any valid partition can be produced from this partition by merging some adjacent segments. To prove it, suppose we partitioned the array in some other way. The intersection of two closed segments, if it exists, is also a closed segment; so there exists at least one segment in the partition we picked greedily that can be broken into two - but that contradicts the algorithm we used to construct this partition. So we may merge some of $m$ segments to get a valid partition. There are exactly $2^{m - 1}$ ways to do so, because for every pair of adjacent segments we may choose whether we will merge it.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint main()\n{\n \tint n;\n \tscanf(\"%d\", &n);\n \tvector<int> a(n);\n \tfor(int i = 0; i < n; i++)\n \t\tscanf(\"%d\", &a[i]);\n \tmap<int, int> lst;\n \tvector<int> last_pos(n);\n \tfor(int i = n - 1; i >= 0; i--)\n \t{\n \t\tif(!lst.count(a[i]))\n \t\t\tlst[a[i]] = i;\n \t\tlast_pos[i] = lst[a[i]];\n \t}\n \tint ans = 1;\n \tint cur_max = -1;\n \tfor(int i = 0; i < n - 1; i++)\n \t{\n \t\tcur_max = max(cur_max, last_pos[i]);\n \t\tif(cur_max == i)\n \t\t\tans = (2 * ans) % MOD;\n \t}\t\n \tprintf(\"%d\\n\", ans);\n \treturn 0;\n}",
    "tags": [
      "combinatorics",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1102",
    "index": "F",
    "title": "Elongated Matrix",
    "statement": "You are given a matrix $a$, consisting of $n$ rows and $m$ columns. Each cell contains an integer in it.\n\nYou can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be $s_1, s_2, \\dots, s_{nm}$.\n\nThe traversal is $k$-acceptable if for all $i$ ($1 \\le i \\le nm - 1$) $|s_i - s_{i + 1}| \\ge k$.\n\nFind the maximum integer $k$ such that there exists some order of rows of matrix $a$ that it produces a $k$-acceptable traversal.",
    "tutorial": "Really low constraints, choosing some permutation... Surely, this will be some dp on subsets! At first, let's get rid of $m$. For each two rows calculate the minimum difference between the elements of the same columns - let's call this $mn1_{i, j}$ for some rows $i$, $j$. This will be used to put row $j$ right after row $i$. Let's also calculate $mn2_{i, j}$ - the minimum difference between the elements of the column $k$ of row $i$ and column $k + 1$ of row $j$. This will be used to put row $i$ as the last row and row $j$ as the first one. Now let's think of choosing the permutation as choosing the traversal of the following graph. Vertices are rows and the weights of edges between the vertices are stored in $mn1$. However, you can't straight up do minimum weight Hamiltonian cycle search as the edge between the first vertex and the last one should be of weight from $mn2$ and not $mn1$. Let's fix some starting vertex and find minimum weight Hamiltonian paths from it to all vertices. Finally, update the answer with $min(mn2_{u, v}, path_{v, u})$. That will lead to $2^n \\cdot n^3$ approach (minimum weight Hamiltonian path is a well-known problem solved by $dp[mask of used vertices][last visited vertex]$). That's completely fine and it's the most intended solution. However, there exist another solution that would have worked better if the edge weight were a bit smaller. Let's do binary search, each time checking if the answer is greater or equal to $mid$. The check is simple enough. Now the graph is binary (edge exists if its weight is greater or equal to $mid$), thus you should check for existence of Hamiltonian path, not for the minimum weight one. That can be done in $O(2^n \\cdot n^2)$, leading to $O(2^n \\cdot n^2 \\log MAXN)$ solution. The key idea of that dp is storing the vertices where the path of the current mask could have ended as a mask itself. Then it becomes $dp[mask]$ with $n$ transitions. Overall complexity: $O(2^n \\cdot n^3)$ or $O(2^n \\cdot n^2 \\log MAXN)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 18;\nconst int M = 100 * 1000 + 13;\nconst int INF = 1e9;\n\nint used[1 << N];\nchar dp[1 << N];\nint g[1 << N];\n\nint n, m;\nint a[N][M];\nint mn1[N][N], mn2[N][N];\n\nbool calc(int mask){\n\tif (dp[mask] != -1)\n\t\treturn dp[mask];\n\tused[mask] = 0;\n\tdp[mask] = 0;\n\tforn(i, n){\n\t\tif (!((mask >> i) & 1))\n\t\t\tcontinue;\n\t\tif (!calc(mask ^ (1 << i)))\n\t\t\tcontinue;\n\t\tif (!(used[mask ^ (1 << i)] & g[i]))\n\t\t\tcontinue;\n\t\tused[mask] |= (1 << i);\n\t\tdp[mask] = 1;\n\t}\n\treturn dp[mask];\n}\n\nbool check(int k){\n\tforn(i, n){\n\t\tg[i] = 0;\n\t\tforn(j, n)\n\t\t\tg[i] |= (1 << j) * (mn1[j][i] >= k);\n\t}\n\tforn(i, n){\n\t\tmemset(dp, -1, sizeof(dp));\n\t\tforn(j, n){\n\t\t\tdp[1 << j] = (j == i);\n\t\t\tused[1 << j] = (1 << j);\n\t\t}\n\t\tcalc((1 << n) - 1);\n\t\tforn(j, n) if (mn2[j][i] >= k && ((used[(1 << n) - 1] >> j) & 1))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nint main() {\n\tscanf(\"%d%d\", &n, &m);\n\tforn(i, n) forn(j, m)\n\t\tscanf(\"%d\", &a[i][j]);\n\t\n\tforn(i, n) forn(j, n){\n\t\tint val = INF;\n\t\tforn(k, m)\n\t\t\tval = min(val, abs(a[i][k] - a[j][k]));\n\t\tmn1[i][j] = val;\n\t\tval = INF;\n\t\tforn(k, m - 1)\n\t\t\tval = min(val, abs(a[i][k] - a[j][k + 1]));\n\t\tmn2[i][j] = val;\n\t}\n\t\n\tint l = 0, r = INF;\n\twhile (l < r - 1){\n\t\tint m = (l + r) / 2;\n\t\tif (check(m))\n\t\t\tl = m;\n\t\telse\n\t\t\tr = m;\n\t}\n\t\n\tprintf(\"%d\\n\", check(r) ? r : l);\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "dp",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1103",
    "index": "A",
    "title": "Grid game",
    "statement": "You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.",
    "tutorial": "One possible solution is to place vertical tiles into lower-left corner and place horizontal tiles into upper-right corner.If some tile comes, but there is already a tile of the same type, than we will place the new tile into upper-left corner. So both tiles will be cleared and only them.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main(){\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tstring s;\n\tcin>>s;\n\tbool occv=false, occh=false;\n\tfor(auto& x:s){\n\t\tif(x=='0'){\n\t\t\tif(occv)\n\t\t\t\tcout<<\"3 4\\n\";\n\t\t\telse\n\t\t\t\tcout<<\"1 4\\n\";\n\t\t\toccv=!occv;\n\t\t} else {\n\t\t\tif (occh)\n\t\t\t\tcout<<\"4 3\\n\";\n\t\t\telse\n\t\t\t\tcout<<\"4 1\\n\";\n\t\t\tocch=!occh;\n\t\t}\n\t}\n\treturn 0;\n}\n ",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1103",
    "index": "B",
    "title": "Game with modulo",
    "statement": "\\textbf{This is an interactive problem.}\n\nVasya and Petya are going to play the following game: Petya has some positive integer number $a$. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers $(x, y)$. Petya will answer him:\n\n- \"x\", if $(x \\bmod a) \\geq (y \\bmod a)$.\n- \"y\", if $(x \\bmod a) < (y \\bmod a)$.\n\nWe define $(x \\bmod a)$ as a remainder of division $x$ by $a$.\n\nVasya should guess the number $a$ using \\textbf{no more, than 60 questions}.\n\n\\textbf{It's guaranteed that} Petya has a number, that satisfies the inequality $1 \\leq a \\leq 10^9$.\n\nHelp Vasya playing this game and write a program, that will guess the number $a$.",
    "tutorial": "Let's ask this pairs of numbers: $(0, 1), (1, 2), (2, 4), (4, 8), \\ldots, (2^{29}, 2^{30})$. Let's find the first pair in this list with the answer \"x\". This pair exists and it will happen for the first pair $(l_0, r_0)$, that satisfy the inequality $l_0 < a \\leq r_0$. We can simply find this pair using $\\leq 30$ or $\\leq 31$ questions. Now we have a pair of numbers $(l_0, r_0)$, such that $l_0 < a \\leq r_0$. Let's note, that $r_0 < 2 \\cdot a$, because it was the first such pair in the list. Now if we ask pair $(l_0, x)$ for some $l_0 < x \\leq r_0$ we will get the answer \"y\", if $x < a$ and the answer \"x\" otherwise. So let's do the binary search in the segment $[l_0+1, r_0]$, asking the question $(l_0, x)$ and moving the borders of binary search according to this. Here we will use $\\leq 29$ questions. So we have a solution asked $\\leq 59$ questions.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1103",
    "index": "C",
    "title": "Johnny Solving",
    "statement": "Today is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with $n$ vertices without loops and multiedges, such that a degree of any vertex is at least $3$, and also he gave a number $1 \\leq k \\leq n$. Because Johnny is not too smart, he promised to find a simple path with length at least $\\frac{n}{k}$ in the graph. In reply, Solving promised to find $k$ simple by vertices cycles with representatives, such that:\n\n- Length of each cycle is at least $3$.\n- Length of each cycle is not divisible by $3$.\n- In each cycle must be a representative - vertex, which belongs only to this cycle among all \\textbf{printed} cycles.\n\nYou need to help guys resolve the dispute, for that you need to find a solution for Johnny: a simple path with length at least $\\frac{n}{k}$ ($n$ is not necessarily divided by $k$), or solution for Solving: $k$ cycles that satisfy all the conditions above. If there is no any solution - print $-1$.",
    "tutorial": "Let's build a dfs spanning tree from the vertex $1$ and find the depth of the tree. If the depth is at least $\\frac{n}{k}$ then we can just print the path from the root to the deepest vertex. Otherwise, there will be at least $k$ leaves in the tree. Let's prove it. Consider a tree with $c$ leaves, after that consider a path from a particular leaf to the root, let's denote length of $i$-th path (in vertices) by $x_i$. We can say that $x_1 + \\ldots + x_c \\geq n$, because every particular vertex in the tree will be covered by one of pathways. So, using Dirichlet's principle we can say that $max(x_1, \\ldots, x_c) \\geq \\frac{n}{c}$. Hence, depth of the tree is at least $\\frac{n}{c}$. Now, consider a leaf in our spanning tree, let's denote it like $v$. This leaf has at least 2 back edges (edges which connected with one of ancestors), let's denote ancestors like $x$ and $y$. Obviosly, we have three cycles here: path from $x$ to $v$ with corresponding back edge, the same cycle from $y$ to $v$, and path between $x$ and $y$ with two back edges connected with $v$. Lengths of these cycles are $d(v, x) + 1$, $d(v, y) + 1$ and $d(x, y) + 2$, where $d(a, b)$ - distance between vertices a and b. It's clear that one of these numbers is not divisible by three. Last problem is to choose representative - we should choose leaves. Size of output is not exceed $10^6$ because the depth of our tree at most $\\frac{n}{k}$ and each cycle has length $O(\\frac{n}{k})$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1103",
    "index": "D",
    "title": "Professional layer",
    "statement": "Cardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are $n$ judges now in the layer and you are trying to pass the entrance exam. You have a number $k$ — your skill in Cardbluff.\n\nEach judge has a number $a_i$ — an indicator of uncertainty about your entrance to the professional layer and a number $e_i$ — an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only \\textbf{one} game with each judge. As a result of a particular game, you can divide the uncertainty of $i$-th judge by any natural divisor of $a_i$ which is at most $k$. If GCD of all indicators is equal to $1$, you will enter to the professional layer and become a judge.\n\nAlso, you want to minimize the total amount of spent time. So, if you play with $x$ judges with total experience $y$ you will spend $x \\cdot y$ seconds.\n\nPrint minimal time to enter to the professional layer or $-1$ if it's impossible.",
    "tutorial": "We supposed this as the author solution: Let's find $gcd$ and factorize it. $gcd = p_1^{\\alpha_1} \\cdot \\ldots \\cdot p_m^{\\alpha_m}$, where $p_i$ $i$-th prime number in factorization ($p_i < p_{i+1}$) and $\\alpha_i > 0$ - number of occurrences of this prime. It's clear, that $m \\leq 11$ in our constraints, because $a_i \\leq 10^{12}$. Obviously, that in optimal answer is always best to divide set of our primes in subsets and distribute these subsets between array numbers and divide each number $a_i$ by product of all primes (with $a_i$ powers) in corresponding subset. Also clear, that we are interested in only vector of powers of primes of $gcd$, other primes in a factorization of $a_i$ we can ignore, but we need to be cautious about costs, so, we can left the cheapest $m$ numbers with the same prime-vector. After this compression we will left at most $M = 12000$ numbers. We can get this estimation by this point: maximum numbers after compression we can reach if all primes are small as possible and $\\alpha_i = 1$ for all $i$. Hence, we have at most $11$ possibilities and can easily brute all of them. Also, after compression, let's calculate vector $best(mask)$ - best $m$ numbers by cost to cover set of primes corresponding to $mask$. We can do it easily in $O(M \\cdot 2^m \\cdot m)$. Now let's fix a partition of our set of primes into subsets. Well known, that the number of partitions is equal to $B_m$, where $B_i$ - $i$-th Bell number. Now, we want to update the current answer. We need to do it by value $x \\cdot y$, where $x$ is number of subsets in the partition (we already know it) and $y$ is minimum cost to distribute our subsets between array numbers. Let's consider all indices $i$ for subset $mask$ which we can match with this $mask$ by constraint \"divisor is at most k\". We will get the bipartite graph with weighted right part (part with indices) and our purpose is to find perfect matching with minimal cost of used vertices in the right part. We can solve this problem with Kuhn algorithm greedily - we can sort right part in not ascending order and do all iterations in this order. It's correct, because we can consider transversal matroid with elements in right part and apply greed Rado-Edmonds theorem. Now we need just to figure out, that we can build this graph using precalced $best(mask)$, because we are interested only in at most $m$ best indices for the particular vertex in the left part. So, we will have graph with $O(x^2)$ edges and $O(x)$ size of the left part. Kuhn algorithm will be work in $O(x^3)$ (even we do the algorithm in right part with size $O(x^2)$) if we clear $used$ array carefully - only after increasing of the current matching. Summing up $x^3$ over all partitions of $11$ elements we will get $\\sim 10^8$ operations. P. S. Solutions that were passed by participants during the contest used same ideas about the compression. But instead of minimal matching we will use dynamic programming approach. Let's denote $dp(mask, i)$ - minimal cost to correctly cover set of primes corresponding to $mask$ using exactly $i$ divisions. To calculate it let's precalc $best'(i)$ (inversion of $best(mask)$) - $m$ masks for which $i$-th number of the array is one of $m$ best. Using this helped data we can calculate our $dp(mask, i)$. For this, we can iterate over all numbers and try to update all states where we can use our $best'(i)$ masks. It will be work in $O(m^2 \\cdot 3^m)$ and all algorithm will be work in $O(M \\cdot 2^m \\cdot m + m^2 \\cdot 3^m)$",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1103",
    "index": "E",
    "title": "Radix sum",
    "statement": "Let's define \\textbf{radix sum} of number $a$ consisting of digits $a_1, \\ldots ,a_k$ and number $b$ consisting of digits $b_1, \\ldots ,b_k$(we add leading zeroes to the shorter number to match longer length) as number $s(a,b)$ consisting of digits $(a_1+b_1)\\mod 10, \\ldots ,(a_k+b_k)\\mod 10$. The \\textbf{radix sum} of several integers is defined as follows: $s(t_1, \\ldots ,t_n)=s(t_1,s(t_2, \\ldots ,t_n))$\n\nYou are given an array $x_1, \\ldots ,x_n$. The task is to compute for each integer $i (0 \\le i < n)$ number of ways to consequently choose one of the integers from the array $n$ times, so that the \\textbf{radix sum} of these integers is equal to $i$. Calculate these values modulo $2^{58}$.",
    "tutorial": "After reading the problem statement, it is pretty clear that you should apply something like Hadamard transform, but inner transform should have size ten instead of two. There is no $10$-th root of one modulo $2^{58}$ (except $5$-th and $2$-th roots), so it is not possible to solve the problem just calculating all values modulo $2^{58}$. The main idea is that you should calculate all values in a polynomial ring modulo $x^{10}-1$ (in this ring identity $x^{10}=1$ holds, so $x$ is the one's $10$-th root). Now the problem is there is no modular inverse of $10^5$, so we apply the trick. Let's just use unsigned long long, and in the end we will divide the answer by $5^5$ (it is invertible, because it is relatively prime to 2), and then we simply divide the answer by $2^5$ with integer division, it can be easily shown that the result will be correct. It is worth noting that after inverse transform you should eliminate monomes larger than $x^4$ by applying the identity $x^4-x^3+x^2-x^1+x^0=0$ (modulo $x^{10}-1$). After that only the coefficient with $x^0$ remains, and this will be the answer.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef unsigned long long ull;\n \nconst int two = 2;\nconst int M = 1e5;\nconst int L = 7;\nconst int X = 2e5 + 1e3;\nconst int fr = 4;\nconst int ten = 10;\nconst ull cs = 6723469279985657373;\nconst ull RT = (1LL << 58LL) - 1;\n \null f[X][fr], bf[L];\nint cur;\n \ninline int sum(int i, int j)\n{\n    for (int x = 0; x < fr; x++) f[cur][x] = f[i][x] + f[j][x];\n    return (cur++);\n}\n \ninline int mult(int i, int j)\n{\n    for (int x = 0; x < L; x++)\n        bf[x] = 0;\n    for (int x = 0; x < fr; x++)\n        for (int y = 0; y < fr; y++)\n            bf[x + y] += f[i][x] * f[j][y];\n    bf[1] -= bf[6];\n    bf[0] -= bf[5];\n    bf[3] += bf[4];\n    bf[2] -= bf[4];\n    bf[1] += bf[4];\n    bf[0] -= bf[4];\n    for (int x = 0; x < fr; x++)\n        f[cur][x] = bf[x];\n    return (cur++);\n}\n \ninline void sum_to(int who, int i, int j)\n{\n    for (int x = 0; x < fr; x++) f[who][x] = f[i][x] + f[j][x];\n}\n \ninline void mult_to(int who, int i, int j)\n{\n    for (int x = 0; x < L; x++)\n        bf[x] = 0;\n    for (int x = 0; x < fr; x++)\n        for (int y = 0; y < fr; y++)\n            bf[x + y] += f[i][x] * f[j][y];\n    bf[1] -= bf[6];\n    bf[0] -= bf[5];\n    bf[3] += bf[4];\n    bf[2] -= bf[4];\n    bf[1] += bf[4];\n    bf[0] -= bf[4];\n    for (int x = 0; x < fr; x++)\n        f[who][x] = bf[x];\n}\n \ninline int init(int x)\n{\n    f[cur][0] = x;\n    return (cur++);\n}\n \ninline int cpy(int x)\n{\n    for (int i = 0; i < fr; i++)\n        f[cur][i] = f[x][i];\n    return (cur++);\n}\n \ninline void cpy_to(int x, int y)\n{\n    for (int i = 0; i < fr; i++)\n        f[x][i] = f[y][i];\n}\n \ninline void clr(int x)\n{\n    for (int i = 0; i < fr; i++)\n        f[x][i] = 0;\n}\n \nint n, kol[M], a[M], b[ten];\nint st[two][ten], buf;\n \ninline int power(int i, int st)\n{\n    vector<int> rt;\n    while (st)\n    {\n        rt.push_back(st & 1);\n        st >>= 1;\n    }\n    reverse(rt.begin(), rt.end());\n    int ans = init(1);\n    for (int x = 0; x < (int)rt.size(); x++)\n    {\n        mult_to(ans, ans, ans);\n        if (rt[x]) mult_to(ans, ans, i);\n    }\n    return ans;\n}\n \ninline void conv(int c)\n{\n    int up = M;\n    while (up >= 10)\n    {\n        up /= 10;\n        for (int x = 0; x < M; x += (10 * up))\n            for (int i = x; i < up + x; i++)\n            {\n                for (int u = 0; u < 10; u++)\n                    cpy_to(b[u], a[i + up * u]);\n                for (int u = 0; u < 10; u++)\n                {\n                    int nd = (i + up * u);\n                    clr(a[nd]);\n                    for (int pw = 0; pw < 10; pw++)\n                    {\n                        clr(buf);\n                        mult_to(buf, st[c][(pw * u) % 10], b[pw]);\n                        sum_to(a[nd], a[nd], buf);\n                    }\n                }\n            }\n    }\n}\n \nint main()\n{\n    #ifdef ONPC\n        freopen(\"test.in\", \"r\", stdin);\n        freopen(\"test.out\", \"w\", stdout);\n    #endif\n    ios::sync_with_stdio(0); cin.tie(); cout.tie(0);\n    cin >> n;\n    for (int i = 0; i < n; i++)\n    {\n        int x;\n        cin >> x;\n        kol[x]++;\n    }\n    for (int i = 0; i < M; i++)\n        a[i] = init(kol[i]);\n    for (int i = 0; i < ten; i++)\n        b[i] = init(0);\n    int w = init(0);\n    f[w][1] = 1;\n    int wm = init(0);\n    f[wm][0] = 1, f[wm][1] = -1, f[wm][2] = 1, f[wm][3] = -1;\n    st[0][0] = init(1);\n    st[1][0] = init(1);\n    for (int t = 1; t < 10; t++)\n    {\n        st[0][t] = mult(st[0][t - 1], w);\n        st[1][t] = mult(st[1][t - 1], wm);\n    }\n    buf = init(0);\n    conv(0);\n    for (int i = 0; i < M; i++)\n        a[i] = power(a[i], n);\n    conv(1);\n    for (int i = 0; i < n; i++)\n    {\n        ull ans = f[a[i]][0] * cs;\n        cout << ((ans >> 5LL) & RT) << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "fft",
      "math",
      "number theory"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1104",
    "index": "A",
    "title": "Splitting into digits",
    "statement": "Vasya has his favourite number $n$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $d_1, d_2, \\ldots, d_k$, such that $1 \\leq d_i \\leq 9$ for all $i$ and $d_1 + d_2 + \\ldots + d_k = n$.\n\nVasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among $d_1, d_2, \\ldots, d_k$. Help him!",
    "tutorial": "It was a joke :). Let's split number $n$ to $n$ digits, equal to $1$. Their sum is $n$ and the number of different digits is $1$. So, it can be found as the answer.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1104",
    "index": "B",
    "title": "Game with string",
    "statement": "Two people are playing a game with a string $s$, consisting of lowercase latin letters.\n\nOn a player's turn, he should choose two consecutive equal letters in the string and delete them.\n\nFor example, if the string is equal to \"xaax\" than there is only one possible turn: delete \"aa\", so the string will become \"xx\". A player not able to make a turn loses.\n\nYour task is to determine which player will win if both play optimally.",
    "tutorial": "It can be shown that the answer does not depend on the order of deletions. Let's remove letters from left to right, storing a stack of letters, remaining in the left. When we process a letter, it will be deleted together with the last letter in the stack if they are equal or will be pushed to the stack. Let's calculate parity of the number of deletions during this process and determine the answer.",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1105",
    "index": "A",
    "title": "Salem and Sticks ",
    "statement": "Salem gave you $n$ sticks with integer positive lengths $a_1, a_2, \\ldots, a_n$.\n\nFor every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from $a$ to $b$ is $|a - b|$, where $|x|$ means the absolute value of $x$.\n\nA stick length $a_i$ is called almost good for some integer $t$ if $|a_i - t| \\le 1$.\n\nSalem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer $t$ and the total cost of changing is minimum possible. The value of $t$ is not fixed in advance and you can choose it as any positive integer.\n\nAs an answer, print the value of $t$ and the minimum cost. If there are multiple optimal choices for $t$, print any of them.",
    "tutorial": "Firstly, we must find the value of $t$ and it can easily proven that $t$ is less than or equal to $100$, so we can iterate over all possible value of $t$ from $1$ to $100$ and calculate the cost of making all the sticks almost good for that $t$. That works in $100 \\cdot n$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1105",
    "index": "B",
    "title": "Zuhair and Strings",
    "statement": "Given a string $s$ of length $n$ and integer $k$ ($1 \\le k \\le n$). The string $s$ has a level $x$, if $x$ is largest non-negative integer, such that it's possible to find in $s$:\n\n- $x$ \\textbf{non-intersecting} (non-overlapping) substrings of length $k$,\n- all characters of these $x$ substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings).\n\nA substring is a sequence of consecutive (adjacent) characters, it is defined by two integers $i$ and $j$ ($1 \\le i \\le j \\le n$), denoted as $s[i \\dots j]$ = \"$s_{i}s_{i+1} \\dots s_{j}$\".\n\nFor example, if $k = 2$, then:\n\n- the string \"aabb\" has level $1$ (you can select substring \"aa\"),\n- the strings \"zzzz\" and \"zzbzz\" has level $2$ (you can select two non-intersecting substrings \"zz\" in each of them),\n- the strings \"abed\" and \"aca\" have level $0$ (you can't find at least one substring of the length $k=2$ containing the only distinct character).\n\nZuhair gave you the integer $k$ and the string $s$ of length $n$. You need to find $x$, the level of the string $s$.",
    "tutorial": "Since all the substrings of length $k$ must be of the same latter, we can iterate over all letters from 'a' to 'z' and for each letter count the number of disjoint substrings of length $k$ and take the maximum one.",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1105",
    "index": "C",
    "title": "Ayoub and Lost Array",
    "statement": "Ayoub had an array $a$ of integers of size $n$ and this array had two interesting properties:\n\n- All the integers in the array were between $l$ and $r$ (inclusive).\n- The sum of all the elements was divisible by $3$.\n\nUnfortunately, Ayoub has lost his array, but he remembers the size of the array $n$ and the numbers $l$ and $r$, so he asked you to find the number of ways to restore the array.\n\nSince the answer could be very large, print it modulo $10^9 + 7$ (i.e. the remainder when dividing by $10^9 + 7$). In case there are no satisfying arrays (Ayoub has a wrong memory), print $0$.",
    "tutorial": "Since we need the sum of the array to be divisible by $3$, we don't care about the numbers themselves: We care about how many numbers $x$ such that $x \\pmod{3} = 0$ or $1$ or $2$ and we count them by simple formulas. For example, let's count the number of $x$ with remainder $1$ modulo $3$, hence $x = 3k + 1$ for some integer $k$. Then we have $l \\le 3k + 1 \\le r$, $l - 1 \\le 3k \\le r - 1$ and then $ceil(\\frac{l - 1}{3}) \\le k \\le floor(\\frac{r - 1}{3})$. It is easy to count number of such $k$ then. After counting all numbers we can solve the problem using dynamic programming. Let's say that dp[i][j] represents that the sum of the first $i$ numbers modulo $3$ is equal to $j$. There are $O(n)$ states and transitions and the answer will be at dp[n][0].",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1105",
    "index": "D",
    "title": "Kilani and the Game",
    "statement": "Kilani is playing a game with his friends. This game can be represented as a grid of size $n \\times m$, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).\n\nThe game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player $i$ can expand from a cell with his castle to the empty cell if it's possible to reach it in at most $s_i$ (where $s_i$ is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that.\n\nThe game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.",
    "tutorial": "This problem can be solved in many ways, one of them uses a bfs. Let's process the first round. Iterate over players and use a multi-source bfs for each player from his starting castles to find cells reachable in at most s[i] moves. A multi-source bfs works just like regular one, except you push more vertices in the queue in the beginning. While moving, we can't enter a blocked cell or an already controlled cell. And in the each following turn do the same, but start from the cells we stopped on the previous turn, instead of starting castles. Keep doing this until no player can move anymore. Complexity: $O(p \\cdot nm)$",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1105",
    "index": "E",
    "title": "Helping Hiasat ",
    "statement": "Hiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.\n\nLuckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types:\n\n- $1$ — Hiasat can change his handle.\n- $2$ $s$ — friend $s$ visits Hiasat's profile.\n\nThe friend $s$ will be happy, if each time he visits Hiasat's profile his handle would be $s$.\n\nHiasat asks you to help him, find the maximum possible number of happy friends he can get.",
    "tutorial": "Let's change this problem to a graph problem first. Let's say, that each action of the first type is a \"border\". Consider all friends visiting our profile after this \"border\" but before the next one. Clearly, we can satisfy at most one of them. Let's change the friends into graph nodes and add edges between every two friends that are between the same borders. Then it's enough to solve \"the maximum independent set of the graph\", clearly any possible answer must be an independent set and by any independent set we can always build a way to change our handle. The maximum independent set can be solved in $O(2^m)$ (where $m$ is the number of friends). But since $m$ is up to $40$, it is too slow. However, we can apply the meet in the middle approach and then it becomes $O(2^{(m/2)})$ or $O(2^{(m/2)} m)$. The simplest way is to do the following (notice, that the independent set is same as clique if all edges are inverted, so we will solve a max clique problem). Let's write a bruteforce solve(mask) which returns size of the largest clique, which forms a subset of mask. The answer will be just to run solve of full mask. How to write solve? Let's find a first bit of mask, let it be vertex $v$. There are two cases: The vertex $v$ is not in an answer. Kick it and run a recursive call. The vertex $v$ is in answer. Hence all other vertices of answers are neighbors of $v$. Run the recursive call from mask & g[v], where g[v] denotes the mask of neighbors. Clearly, it works in $O(2^m)$. However, if we add memorization (don't calculate for same mask twice) it is magically becomes $O(2^{m/2})$. Why? Consider the recursion, there are at most $m/2$ recursion calls before we arrive into the state, where there are no set bits of the first half. This part will take at most $2^{m/2}$ then. And clearly there are at most $2^{m/2}$ states with no set bits in the first half.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "meet-in-the-middle"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1106",
    "index": "A",
    "title": "Lunar New Year and Cross Counting",
    "statement": "Lunar New Year is approaching, and you bought a matrix with lots of \"crosses\".\n\nThis matrix $M$ of size $n \\times n$ contains only 'X' and '.' (without quotes). The element in the $i$-th row and the $j$-th column $(i, j)$ is defined as $M(i, j)$, where $1 \\leq i, j \\leq n$. We define a cross appearing in the $i$-th row and the $j$-th column ($1 < i, j < n$) if and only if $M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $ 'X'.\n\nThe following figure illustrates a cross appearing at position $(2, 2)$ in a $3 \\times 3$ matrix.\n\n\\begin{center}\n\\begin{verbatim}\nX.X\n.X.\nX.X\n\\end{verbatim}\n\\end{center}\n\nYour task is to find out the number of crosses in the given matrix $M$. Two crosses are different if and only if they appear in different rows or columns.",
    "tutorial": "The solution is simple: Just check if crosses can appear in every positions. Two nesting for-loops will be enough to solve this problem. Time complexity: $\\mathcal{O}(n^2)$",
    "code": "#include <bits/stdc++.h>\n#define N 510\nusing namespace std;\n\nchar a[N][N];\nint n;\nint main(){\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; i++){\n\t\tscanf(\"%s\", a[i] + 1);\n\t}\n\t\n\tint ans = 0;\n\tfor (int i = 2; i < n; i++){\n\t\tfor (int j = 2; j < n; j++){\n\t\t\tif (a[i][j] == 'X' && a[i - 1][j - 1] == 'X' && a[i - 1][j + 1] == 'X'\n\t\t\t\t&& a[i + 1][j - 1] == 'X' && a[i + 1][j + 1] == 'X'){\n\t\t\t\tans ++;\t\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n} ",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1106",
    "index": "B",
    "title": "Lunar New Year and Food Ordering",
    "statement": "Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — \"Alice's\".\n\nThe restaurant \"Alice's\" serves $n$ kinds of food. The cost for the $i$-th kind is always $c_i$. Initially, the restaurant has enough ingredients for serving exactly $a_i$ dishes of the $i$-th kind. In the New Year's Eve, $m$ customers will visit Alice's one after another and the $j$-th customer will order $d_j$ dishes of the $t_j$-th kind of food. The $(i + 1)$-st customer will only come after the $i$-th customer is completely served.\n\nSuppose there are $r_i$ dishes of the $i$-th kind remaining (initially $r_i = a_i$). When a customer orders $1$ dish of the $i$-th kind, the following principles will be processed.\n\n- If $r_i > 0$, the customer will be served exactly $1$ dish of the $i$-th kind. The cost for the dish is $c_i$. Meanwhile, $r_i$ will be reduced by $1$.\n- Otherwise, the customer will be served $1$ dish of the \\textbf{cheapest} available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $1$.\n- If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $0$.\n\nIf the customer doesn't leave after the $d_j$ dishes are served, the cost for the customer will be the sum of the cost for these $d_j$ dishes.\n\nPlease determine the total cost for each of the $m$ customers.",
    "tutorial": "The implementation of the problem is easy: Just do what Bob tells you to do. The only difficulty, if it is, is to handle the cheapest dish. This can be done by a pointer or a priority queue. The details can be found in the code. Time complexity: $\\mathcal{O}(m + n \\log n)$",
    "code": "#include <bits/stdc++.h>\n#define N 300010\n#define PII pair<int, int> \nusing namespace std;\n\ntypedef long long LL;\n\nint n, m, a[N], c[N], t, d;\nLL ans = 0;\n\npriority_queue<PII, vector<PII>, greater<PII> > Q;\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 1; i <= n; i++){\n\t\tscanf(\"%d\", &a[i]);\n\t}\n\t\n\tfor (int i = 1; i <= n; i++){\n\t\tscanf(\"%d\", &c[i]);\n\t\tQ.push(make_pair(c[i], i));\n\t}\n\t\n\tfor (int i = 1; i <= m; i++){\n\t\tscanf(\"%d%d\", &t, &d);\n\t\tif (d <= a[t]){\n\t\t\ta[t] -= d;\n\t\t\tprintf(\"%lld\\n\", 1LL * d * c[t]);\n\t\t} else {\n\t\t\tbool flag = false;\n\t\t\tLL ans = 1LL * a[t] * c[t];\n\t\t\td -= a[t];\n\t\t\ta[t] = 0;\n\t\t\twhile (!Q.empty()){\n\t\t\t\twhile (!Q.empty() && a[Q.top().second] == 0) Q.pop();\n\t\t\t\tif (Q.empty()) break;\n\t\t\t\tPII now = Q.top();\n\t\t\t\tif (d <= a[now.second]){\n\t\t\t\t\ta[now.second] -= d;\n\t\t\t\t\tans += 1LL * d * now.first;\n\t\t\t\t\tflag = true;\n\t\t\t\t\tprintf(\"%lld\\n\", ans);\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tans += 1LL * a[now.second] * now.first;\n\t\t\t\t\td -= a[now.second];\n\t\t\t\t\ta[now.second] = 0;\n\t\t\t\t\tQ.pop();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (!flag){\n\t\t\t\tputs(\"0\");\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1106",
    "index": "C",
    "title": "Lunar New Year and Number Division",
    "statement": "Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.\n\nThere are $n$ positive integers $a_1, a_2, \\ldots, a_n$ on Bob's homework paper, where $n$ is always an \\textbf{even} number. Bob is asked to divide those numbers into groups, where each group must contain at least $2$ numbers. Suppose the numbers are divided into $m$ groups, and the sum of the numbers in the $j$-th group is $s_j$. Bob's aim is to minimize the sum of the square of $s_j$, that is $$\\sum_{j = 1}^{m} s_j^2.$$\n\nBob is puzzled by this hard problem. Could you please help him solve it?",
    "tutorial": "This problem is easy as it looks like, and it is proved to be simple. As $n$ is even, the optimal grouping policy is to group the smallest with the largest, the second smallest with the second largest, etc. First, it is easy to prove that it is optimal to group these numbers $2$ by $2$, so the proof is given as an exercise to you. The proof of the second part is about the Rearrangement Inequality. Let's consider two of the permutations of the sequence $\\{a_i\\}$. Suppose they are $\\{b_i\\}, \\{c_i\\}$ where $b_i = c_j$ if and only if $b_j = c_i$. Then the sum $\\frac{1}{2} \\sum_{i = 1}^{n} (b_i + c_i)^2$ $\\frac{1}{2} \\sum_{i = 1}^{n} (b_i^2 + c_i^2)$ Time complexity: $\\mathcal{O}(n \\log n)$",
    "code": "#include <bits/stdc++.h>\n#define N 300010\nusing namespace std;\n\ntypedef long long LL;\n\nint n, a[N];\nLL ans = 0;\n\nint main(){\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; i++){\n\t\tscanf(\"%d\", &a[i]);\n\t}\n\tsort(a + 1, a + n + 1);\n\tfor (int i = 1; i <= n / 2; i++){\n\t\tans += 1LL * (a[i] + a[n - i + 1]) * (a[i] + a[n - i + 1]);\n\t}\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1106",
    "index": "D",
    "title": "Lunar New Year and a Wander",
    "statement": "Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.\n\nThe park can be represented as a connected graph with $n$ nodes and $m$ bidirectional edges. Initially Bob is at the node $1$ and he records $1$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $a_1, a_2, \\ldots, a_n$ is recorded.\n\nWandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.\n\nA sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds:\n\n- $x$ is a prefix of $y$, but $x \\ne y$ (this is impossible in this problem as all considered sequences have the same length);\n- in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$.",
    "tutorial": "In fact, you don't really need to consider the path Bob wanders. A priority queue is enough for this problem. When Bob visits a node, add its adjacent nodes into the priority queue. Every time he visits a new node, it will be one with the smallest index in the priority queue. Time complexity: $\\mathcal{O}(m \\log n)$",
    "code": "#include <bits/stdc++.h>\n#define N 300010\nusing namespace std;\n\ntypedef long long LL;\n\npriority_queue<int, vector<int>, greater<int> > Q;\nvector<int> e[N];\nvector<int> seq;\nbool vis[N];\nint n, m;\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 1; i <= m; i++){\n\t\tint u, v;\n\t\tscanf(\"%d%d\", &u, &v);\n\t\te[u].push_back(v);\n\t\te[v].push_back(u);\n\t}\n\t\n\tvis[1] = true;\n\tQ.push(1);\n\twhile (!Q.empty()){\n\t\tint now = Q.top();\n\t\tQ.pop();\n\t\tseq.push_back(now);\n\t\tfor (auto p : e[now]){\n\t\t\tif (!vis[p]){\n\t\t\t\tQ.push(p);\n\t\t\t\tvis[p] = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (auto p : seq){\n\t\tprintf(\"%d \", p);\n\t}\n\tputs(\"\");\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1106",
    "index": "E",
    "title": "Lunar New Year and Red Envelopes",
    "statement": "Lunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself.\n\nLet's describe this problem in a mathematical way. Consider a timeline from time $1$ to $n$. The $i$-th red envelope will be available from time $s_i$ to $t_i$, inclusive, and contain $w_i$ coins. If Bob chooses to collect the coins in the $i$-th red envelope, he can do it only in an \\textbf{integer} point of time between $s_i$ and $t_i$, inclusive, and he can't collect any more envelopes until time $d_i$ (inclusive) after that. Here $s_i \\leq t_i \\leq d_i$ holds.\n\nBob is a greedy man, he collects coins greedily — whenever he can collect coins at some integer time $x$, he collects the available red envelope with the maximum number of coins. If there are multiple envelopes with the same maximum number of coins, Bob would choose the one whose parameter $d$ is the \\textbf{largest}. If there are still multiple choices, Bob will choose one from them randomly.\n\nHowever, Alice — his daughter — doesn't want her father to get too many coins. She could disturb Bob at no more than $m$ integer time moments. If Alice decides to disturb Bob at time $x$, he could not do anything at time $x$ and resumes his usual strategy at the time $x + 1$ (inclusive), which may lead to missing some red envelopes.\n\nCalculate the minimum number of coins Bob would get if Alice disturbs him optimally.",
    "tutorial": "Yes, this is where Alice shows up and ... probably the problem is not related to Game Theory. Let's divide the problem into two parts: The first is to obtain the maximum coins Bob can get from time points $1$ to $n$, and the second is to decide when to disturb Bob. For the first part, we apply event sorting to those time segments. After that, we use a set with a sweep line to deal with it. Whenever we meet a start or a terminate of one red envelope, we add this into the set or remove that from the set. Note that you need to use multiset, since there can be multiple red envelopes with same $d$ and $w$. For the second part, we apply dynamic programming since $m$ is relatively small. Let $f[i][j]$ denote that the minimum coins Bob gets when we only consider the timeline from $1$ to $i$ and Alice disturbs Bob for $j$ times. The transition is trivial and you can take a look at it in the code. Time complexity: $\\mathcal{O}((n + k) \\log k + nm)$",
    "code": "#include <bits/stdc++.h>\n#define N 100010\nusing namespace std;\n\ntypedef long long LL;\n\nstruct Event{\n\tint d, w, t;\n\t\n\tbool operator < (const Event &e) const {\n\t\treturn w > e.w || (w == e.w && d > e.d);\n\t}\n};\n\nvector<Event> e[N];\nEvent a[N];\nmap<Event, int> cur;\nint n, m, k;\n\nLL f[2][N], ans = 0x3f3f3f3f3f3f3f3fLL;\n\nvoid insert(Event x){\n\tif (cur.count(x)){\n\t\tcur[x] ++;\n\t} else {\n\t\tcur[x] = 1;\n\t}\n}\n\nvoid erase(Event x){\n\tcur[x] --;\n\tif (cur[x] == 0){\n\t\tcur.erase(x);\n\t}\n}\n\nint main(){\n\tscanf(\"%d%d%d\", &n, &m, &k);\n\tfor (int i = 1; i <= k; i++){\n\t\tint s, t, d, w;\n\t\tscanf(\"%d%d%d%d\", &s, &t, &d, &w);\n\t\te[s].push_back((Event){d, w, 1});\n\t\te[t + 1].push_back((Event){d, w, -1});\n\t}\n\t\n\tfor (int i = 1; i <= n; i++){\n\t\tfor (auto p : e[i]){\n\t\t\tif (p.t == 1){\n\t\t\t\tinsert(p);\n\t\t\t} else {\n\t\t\t\terase(p);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (cur.size()){\n\t\t\ta[i] = (*cur.begin()).first;\n\t\t} else {\n\t\t\ta[i] = (Event){i, 0, 0};\n\t\t}\n\t}\n\t\n\tmemset(f, 0x3f, sizeof(f));\n\tf[0][1] = 0;\n\tfor (int j = 0; j <= m; j++){\n\t\tmemset(f[(j ^ 1) & 1], 0x3f, sizeof(f[(j ^ 1) & 1]));\n\t\tfor (int i = 1; i <= n; i++){\n\t\t\tf[(j ^ 1) & 1][i + 1] = min(f[(j ^ 1) & 1][i + 1], f[j & 1][i]);\n\t\t\tf[j & 1][a[i].d + 1] = min(f[j & 1][a[i].d + 1], f[j & 1][i] + a[i].w);\n\t\t}\n\t\tans = min(ans, f[j & 1][n + 1]);\n\t}\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1106",
    "index": "F",
    "title": "Lunar New Year and a Recursive Sequence",
    "statement": "Lunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it.\n\nLet $f_1, f_2, \\ldots, f_i, \\ldots$ be an infinite sequence of positive integers. Bob knows that for $i > k$, $f_i$ can be obtained by the following recursive equation:\n\n$$f_i = \\left(f_{i - 1} ^ {b_1} \\cdot f_{i - 2} ^ {b_2} \\cdot \\cdots \\cdot f_{i - k} ^ {b_k}\\right) \\bmod p,$$\n\nwhich in short is\n\n$$f_i = \\left(\\prod_{j = 1}^{k} f_{i - j}^{b_j}\\right) \\bmod p,$$\n\nwhere $p = 998\\,244\\,353$ (a widely-used prime), $b_1, b_2, \\ldots, b_k$ are known integer constants, and $x \\bmod y$ denotes the remainder of $x$ divided by $y$.\n\nBob lost the values of $f_1, f_2, \\ldots, f_k$, which is extremely troublesome – these are the basis of the sequence! Luckily, Bob remembers the first $k - 1$ elements of the sequence: $f_1 = f_2 = \\ldots = f_{k - 1} = 1$ and the $n$-th element: $f_n = m$. Please find any possible value of $f_k$. If no solution exists, just tell Bob that it is impossible to recover his favorite sequence, regardless of Bob's sadness.",
    "tutorial": "This problem seems weird first looking at it, but we can rewrite it into a linear recursive equation. The most important thing you should know is that $g = 3$ is a primitive root of $p = 998\\,244\\,353$. Briefly speaking, the primitive $g$ is called a primitive root of $p$ if and only if the following two constraints are satisfied: $g^{p - 1} \\bmod p = 1$ (shown by Fermat's little theorem) $\\forall 1 \\leq k < p - 1$, $g^k \\bmod p \\ne 1$ The two constraints shown above imply that $\\forall 1 \\leq x < y < p$, $g^x \\bmod p \\ne g^y \\bmod p$. The proof is simple: If $g^x \\bmod p = g^y \\bmod p$, we have $g^{y - x} \\bmod p = 1$. However, it violates the second constraint since $1 \\leq y - x < p - 1$. Thus the function $q(x)$ defined by $g^{q(x)} \\bmod p = x$ is a bijection: We can recover $x$ from $q(x)$ using fast power algorithm and get $q(x)$ from $x$ using baby step giant step algorithm. Now, we construct a new sequence $h_1, h_2, \\ldots, h_i, \\ldots$ where $h_i = q(f_i)$. Then we can derive the equation that $h_i$ should satisfy: $g^{h_i} \\bmod p = \\left(\\prod_{j = 1}^{k} g^{h_{i - j}{b_j}}\\right) \\bmod p,$ which yields (applying Fermat's little theorem) $g^{h_i \\bmod p - 1} \\bmod p = g^{\\left(\\sum_{j = 1}^{k} {b_j}{h_{i - j}}\\right) \\bmod p - 1} \\bmod p$ Since $g$ is a primitive root of $p$, the equation satisfied if and only if the exponents are the same. Thus $h_i = \\left(\\sum_{j = 1}^{k} {b_j}{h_{i - j}}\\right) \\bmod p - 1$ You may obtain the same equation by applying discrete logarithm on both sides of the equation of $f_i$. Note that the equation of $h_i$ is a normal linear recursive equation, which can be solved using matrix exponentiation to get the relationship between $h_n$ and $h_k$. To obtain $h_n$, just apply the baby step giant step algorithm, and the relationship between $h_n$ and $h_k$ can be represented by a congruence equation: $ch_k \\equiv h_n \\qquad (\\bmod p - 1)$ In this equation, $c$ is the corresponding coefficient of $h_k$ obtained by matrix exponentiation. Note that $f_1 = f_2 = \\ldots = f_{k - 1} = 1$, which yields $h_1 = h_2 = \\ldots = h_{k - 1} = q(1) = 0$. Therefore, we just ignore those items, leaving $ch_k$ alone. This congruence equation can be solved by Extended Euclidean algorithm. If no solution exists for this equation, the original problem has no solution as well. After obtaining $h_k$, $f_k$ can be recovered using fast power algorithm. Time complexity: $\\mathcal{O}(k^3 \\log n + \\sqrt{p} \\log p)$ UPD: Now I would add some details about those two algorithms: matrix exponentiation and baby step giant step algorithm. 1. Matrix exponentiation Suppose that we have a linear recursive equation $f_i = \\sum_{j = 1}^{k} {b_j}{f_{i - j}}$ where $b_1, b_2, \\ldots, b_k$, $f_1, f_2, \\ldots, f_k$ are known constants. Then the following equation of matrices holds for some $i$ ($i \\geq k$) $\\begin{bmatrix} b_1 & b_2 & b_3 & \\cdots & b_{k - 1} & b_k \\\\ 1 & 0 & 0 & \\cdots & 0 & 0 \\\\ 0 & 1 & 0 & \\cdots & 0 & 0 \\\\ 0 & 0 & 1 & \\cdots & 0 & 0 \\\\ \\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\ 0 & 0 & 0 & \\cdots & 1 & 0 \\\\ \\end{bmatrix} \\cdot \\begin{bmatrix} f_i \\\\ f_{i - 1} \\\\ f_{i - 2} \\\\ f_{i - 3} \\\\ \\vdots \\\\ f_{i - k + 1} \\\\ \\end{bmatrix} = \\begin{bmatrix} f_{i + 1} \\\\ f_i \\\\ f_{i - 1} \\\\ f_{i - 2} \\\\ \\vdots \\\\ f_{i - k + 2} \\\\ \\end{bmatrix}$ Let's call the matrix $\\mathbf{A}$ transition matrix, where $\\mathbf{A} = \\begin{bmatrix} b_1 & b_2 & b_3 & \\cdots & b_{k - 1} & b_k \\\\ 1 & 0 & 0 & \\cdots & 0 & 0 \\\\ 0 & 1 & 0 & \\cdots & 0 & 0 \\\\ 0 & 0 & 1 & \\cdots & 0 & 0 \\\\ \\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\ 0 & 0 & 0 & \\cdots & 1 & 0 \\\\ \\end{bmatrix}$ and $\\mathbf{f}_i = \\begin{bmatrix} f_i \\\\ f_{i - 1} \\\\ f_{i - 2} \\\\ f_{i - 3} \\\\ \\vdots \\\\ f_{i - k + 1} \\\\ \\end{bmatrix}$ Therefore, the equation shown above can be rewritten as $\\mathbf{A} \\mathbf{f}_i = \\mathbf{f}_{i + 1}$ which yields $\\mathbf{A}^{n - k} \\mathbf{f}_k = \\mathbf{f}_{n}$ So we can obtain $\\mathbf{f}_{n}$ in $\\mathcal{O}(k^3 \\log n)$ time since a single matrix multiplication takes $\\mathcal{O}(k^3)$ time. There are two problems that you may consider as your further research on linear recursive equations. Solve this linear recursive equation in $\\mathcal{O}(k^2 \\log n)$ time or $\\mathcal{O}(k \\log k \\log n)$ if you apply Fast Fourier Transform. Solve the following linear recursive equation in $\\mathcal{O}(k^3 \\log n)$ time or faster: $f_i = \\sum_{j = 1}^{k} {b_j}{f_{i - j}} + c$ where $c$ is a constant. $f_i = \\sum_{j = 1}^{k} {b_j}{f_{i - j}} + c$ where $c$ is a constant. 2. Baby step giant step algorithm Consider the following congruence equation $a^z \\equiv b \\qquad (\\bmod p)$ The intuition of the baby step giant step algorithm is meet-in-the-middle. Let's write $z = x \\cdot \\sqrt{p} + y$ for convenience. In this representation, $x, y < \\sqrt{p}$. We store $b \\cdot a^{-0}, b \\cdot a^{-1}, \\ldots, b \\cdot a^{-(\\sqrt{p} - 1)}$ in a map. Then we try every possible $x$ from $0$ to $\\sqrt{p} - 1$. Since $a^{x \\cdot \\sqrt{p} + y} \\equiv b \\qquad (\\bmod p)$ $a^{x \\cdot \\sqrt{p}} \\equiv b \\cdot a^{-y} \\qquad (\\bmod p)$",
    "code": "#include <bits/stdc++.h>\n#define N 210\nusing namespace std;\ntypedef long long LL;\n\nconst LL p = 998244353;\nconst LL g = 3;\n\nint k;\nLL n, m, b[N];\n\nstruct Matrix{\n\tint n;\n\tLL mat[N][N];\n\t\n\tMatrix(){\n\t\tn = 0;\n\t\tmemset(mat, 0, sizeof(mat));\n\t}\n\t\n\tMatrix(int _n, LL diag){\n\t\tn = _n;\n\t\tmemset(mat, 0, sizeof(mat));\n\t\tfor (int i = 1; i <= n; i++){\n\t\t\tmat[i][i] = diag;\n\t\t}\n\t}\n\t\n\tMatrix(const Matrix &c){\n\t\tn = c.n;\n\t\tfor (int i = 1; i <= n; i++){\n\t\t\tfor (int j = 1; j <= n; j++){\n\t\t\t\tmat[i][j] = c.mat[i][j];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tMatrix operator * (const Matrix &a) const {\n\t\tMatrix ans = Matrix(n, 0);\n\t\tfor (int k = 1; k <= n; k++){\n\t\t\tfor (int i = 1; i <= n; i++){\n\t\t\t\tfor (int j = 1; j <= n; j++){\n\t\t\t\t\tans.mat[i][j] += mat[i][k] * a.mat[k][j];\n\t\t\t\t\tans.mat[i][j] %= (p - 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\t\n\tMatrix mat_pow(LL t){\n\t\tMatrix base = Matrix(*this), ans = Matrix(n, 1);\n\t\twhile (t){\n\t\t\tif (t & 1){\n\t\t\t\tans = ans * base;\n\t\t\t}\n\t\t\tbase = base * base;\n\t\t\tt >>= 1;\n\t\t}\n\t\treturn ans;\n\t}\n\n};\n\nnamespace GCD{\n\tLL gcd(LL a, LL b){\n\t\tif (!b) return a;\n\t\treturn gcd(b, a % b);\n\t}\n\t\n\tLL ex_gcd(LL a, LL b, LL &x, LL &y){\n\t\tif (!b){\n\t\t\tx = 1; y = 0;\n\t\t\treturn a;\n\t\t}\n\t\t\n\t\tLL q = ex_gcd(b, a % b, y, x);\n\t\ty -= a / b * x;\n\t\treturn q;\n\t}\n}\n\nnamespace BSGS{\n\tLL qpow(LL a, LL b, LL p){\n\t\tLL ans = 1, base = a;\n\t\twhile (b){\n\t\t\tif (b & 1){\n\t\t\t\t(ans *= base) %= p;\n\t\t\t}\n\t\t\t(base *= base) %= p;\n\t\t\tb >>= 1;\n\t\t}\n\t\treturn ans;\n\t}\n\t\n\tLL inv(LL x, LL p){\n\t\treturn qpow(x, p - 2, p);\n\t}\n\t\n\tmap<LL, LL> tab;\n\tLL bsgs(LL a, LL b, LL p){\n\t\tLL u = (LL) sqrt(p) + 1;\n\t\tLL now = 1, step;\n\t\tfor (LL i = 0; i < u; i++){\n\t\t\tLL tmp = b * inv(now, p) % p;\n\t\t\tif (!tab.count(tmp)){\n\t\t\t\ttab[tmp] = i;\n\t\t\t}\n\t\t\t(now *= a) %= p;\n\t\t}\n\t\tstep = now;\n\t\tnow = 1;\n\t\tfor (LL i = 0; i < p; i += u){\n\t\t\tif (tab.count(now)){\n\t\t\t\treturn i + tab[now];\n\t\t\t}\n\t\t\t(now *= step) %= p;\n\t\t}\n\t\tthrow;\n\t\treturn -1;\n\t}\n}\n\nnamespace SOL{\n\tLL solve(LL a, LL b, LL c){\n\t\tif (c == 0) return 0;\n\t\tLL q = GCD::gcd(a, b);\n\t\tif (c % q){\n\t\t\treturn -1;\n\t\t}\n\t\ta /= q, b /= q, c /= q;\n\t\tLL ans, _;\n\t\tGCD::ex_gcd(a, b, ans, _);\n\t\t(ans *= c) %= b;\n\t\twhile (ans < 0) ans += b;\n\t\treturn ans;\n\t}\n}\n\nint main(){\n\tscanf(\"%d\", &k);\n\tfor (int i = 1; i <= k; i++){\n\t\tscanf(\"%d\", &b[i]);\n\t\tb[i] %= (p - 1);\n\t}\n\t\n\tscanf(\"%lld%lld\", &n, &m);\n\t\n\tMatrix A = Matrix(k, 0);\n\tfor (int i = 1; i <= k; i++){\n\t\tA.mat[1][i] = b[i];\n\t}\n\t\n\tfor (int i = 2; i <= k; i++){\n\t\tA.mat[i][i - 1] = 1;\n\t}\n\t\n\tA = A.mat_pow(n - k);\n\t\n\tLL ans = SOL::solve(A.mat[1][1], p - 1, BSGS::bsgs(g, m, p));\n\tif (ans >= 0){\n\t\tprintf(\"%lld\\n\", BSGS::qpow(g, ans, p));\n\t} else {\n\t\tputs(\"-1\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "math",
      "matrices",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1107",
    "index": "A",
    "title": "Digits Sequence Dividing",
    "statement": "You are given a sequence $s$ consisting of $n$ digits from $1$ to $9$.\n\nYou have to divide it into \\textbf{at least two} segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that \\textbf{each element belongs to exactly one segment} and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be \\textbf{strictly greater} than the previous one.\n\nMore formally: if the resulting division of the sequence is $t_1, t_2, \\dots, t_k$, where $k$ is the number of element in a division, then for each $i$ from $1$ to $k-1$ the condition $t_{i} < t_{i + 1}$ (using \\textbf{numerical} comparing, it means that the integer representations of strings are compared) should be satisfied.\n\nFor example, if $s=654$ then you can divide it into parts $[6, 54]$ and it will be suitable division. But if you will divide it into parts $[65, 4]$ then it will be bad division because $65 > 4$. If $s=123$ then you can divide it into parts $[1, 23]$, $[1, 2, 3]$ but not into parts $[12, 3]$.\n\nYour task is to find \\textbf{any} suitable division for each of the $q$ independent queries.",
    "tutorial": "The only case when the answer is \"NO\" - $n=2$ and $s_1 \\ge s_2$. Then you cannot divide the initial sequence as needed in the problem. Otherwise you always can divide it into two parts: the first digit of the sequence and the remaining sequence.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tstring s;\n\t\tcin >> n >> s;\n\t\tif (n == 2 && s[0] >= s[1]) {\n\t\t\tcout << \"NO\" << endl;\n\t\t} else {\n\t\t\tcout << \"YES\" << endl << 2 << endl << s[0] << \" \" << s.substr(1) << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1107",
    "index": "B",
    "title": "Digital root",
    "statement": "Today at the lesson of mathematics, Petya learns about the digital root.\n\nThe digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.\n\nLet's denote the digital root of $x$ as $S(x)$. Then $S(5)=5$, $S(38)=S(3+8=11)=S(1+1=2)=2$, $S(10)=S(1+0=1)=1$.\n\nAs a homework Petya got $n$ tasks of the form: find $k$-th positive number whose digital root is $x$.\n\nPetya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all $n$ tasks from Petya's homework.",
    "tutorial": "Let's derive the formula $S(x) = (x-1)~mod~9 + 1$ from the digital root properties (that's a known fact but I could only find a link to some russian blog about it). Using that formula, you can easily get that $k$-th number with the digital root of $x$ is $(k-1) \\cdot 9 + x$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tlong long k, x;\n\t\tcin >> k >> x;\n\t\tcout << (k - 1) * 9 + x << endl;\n\t}\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1107",
    "index": "C",
    "title": "Brutality",
    "statement": "You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.\n\nYou are playing the game on the new generation console so your gamepad have $26$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.\n\nYou are given a sequence of hits, the $i$-th hit deals $a_i$ units of damage to the opponent's character. To perform the $i$-th hit you have to press the button $s_i$ on your gamepad. Hits are numbered from $1$ to $n$.\n\nYou know that if you press some button \\textbf{more than} $k$ times \\textbf{in a row} then it'll break. You cherish your gamepad and don't want to break any of its buttons.\n\nTo perform a brutality you have to land some of the hits of the given sequence. \\textbf{You are allowed to skip any of them, however changing the initial order of the sequence is prohibited}. The total damage dealt is the sum of $a_i$ over all $i$ for the hits which weren't skipped.\n\n\\textbf{Note that if you skip the hit then the counter of consecutive presses the button won't reset}.\n\nYour task is to skip some hits to deal the \\textbf{maximum} possible total damage to the opponent's character and not break your gamepad buttons.",
    "tutorial": "All you need in this problem is two simple technique: two pointers and sorting. Let's consider maximum by inclusion segments of equal letters in the initial string. Let the current segment be $[l; r]$ and its length is $len = r - l + 1$. If $len < k$ then we can press all buttons and deal all damage corresponding to them. Otherwise it is obviously more profitable to press $k$ best (by damage) buttons. So let's create the array $val$, push all values $a_i$ such that $l \\le i \\le r$ in this array, sort them, take $min(|val|, k)$ best by damage ($|val|$ is the size of the array $val$) and go to the next segment.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tstring s;\n\tcin >> s;\n\t\n\tlong long ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint j = i;\n\t\tvector<int> vals;\n\t\twhile (j < n && s[i] == s[j]) {\n\t\t\tvals.push_back(a[j]);\n\t\t\t++j;\n\t\t}\n\t\tsort(vals.rbegin(), vals.rend());\n\t\tans += accumulate(vals.begin(), vals.begin() + min(k, int(vals.size())), 0ll);\n\t\ti = j - 1;\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1107",
    "index": "D",
    "title": "Compression",
    "statement": "You are given a binary matrix $A$ of size $n \\times n$. Let's denote an $x$-compression of the given matrix as a matrix $B$ of size $\\frac{n}{x} \\times \\frac{n}{x}$ such that for every $i \\in [1, n], j \\in [1, n]$ the condition $A[i][j] = B[\\lceil \\frac{i}{x} \\rceil][\\lceil \\frac{j}{x} \\rceil]$ is met.\n\nObviously, $x$-compression is possible only if $x$ divides $n$, but this condition is not enough. For example, the following matrix of size $2 \\times 2$ does not have any $2$-compression:\n\n\\begin{center}\n$01$\n\\end{center}\n\n\\begin{center}\n$10$\n\\end{center}\n\nFor the given matrix $A$, find maximum $x$ such that an $x$-compression of this matrix is possible.\n\n\\textbf{Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.}",
    "tutorial": "It is very easy to decompress the input (the input was given in the compressed form to make the constraints bigger but less dependent of the time to read the data). The authors solution is the following: Let $x$ be the answer to the problem and initially it equals to $n$. Let's iterate over all rows of the matrix and calculate lengths of maximum by inclusion segments consisting only of zeros or only of ones. Let the length of the current segment be $len$. Then let's set $x := gcd(x, len)$, where $gcd$ is the function calculating the greatest common divisor. Then let's do the same for columns of the matrix and print the answer. How to prove that this solution works? On the one hand, if some segment of kind $[1 + lx, 1 + (l + 1)x]$, where $l$ is the value from the range $[0; \\frac{n}{x} - 1]$, contains different digits then we cannot compress the given matrix. On the other hand, if the previous condition is true, then we can compress each string by the following algorithm: cut off the first $x$ characters of the string and compress the remaining string recursively. After such compression we obtain the matrix of size $n \\times \\frac{n}{x}$. And because of the first condition we can compress the remaining matrix again by this algorithm if we apply it to columns instead of rows.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5200;\n\nint n;\nbool a[N][N];\n\nvoid parse_char(int x, int y, char c) {\n\tint num = -1;\n\tif (isdigit(c)) {\n\t\tnum = c - '0';\n\t} else {\n\t\tnum = c - 'A' + 10;\n\t}\n\tfor (int i = 0; i < 4; ++i) {\n\t\ta[x][y + 3 - i] = num & 1;\n\t\tnum >>= 1;\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\t\n\tscanf(\"%d\", &n);\n\tchar buf[N];\n\tfor (int i = 0; i < n; ++i) {\n\t\tscanf(\"%s\", buf);\n\t\tfor (int j = 0; j < n / 4; ++j) {\n\t\t\tparse_char(i, j * 4, buf[j]);\n\t\t}\n\t}\n\t\n\tint g = n;\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tint k = j;\n\t\t\twhile (k < n && a[i][k] == a[i][j]) ++k;\n\t\t\tg = __gcd(g, k - j);\n\t\t\tj = k - 1;\n\t\t}\n\t}\n\t\n\tfor (int j = 0; j < n; ++j) {\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint k = i;\n\t\t\twhile (k < n && a[k][j] == a[i][j]) ++k;\n\t\t\tg = __gcd(g, k - i);\n\t\t\ti = k - 1;\n\t\t}\n\t}\n\t\n\tcout << g << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1107",
    "index": "E",
    "title": "Vasya and Binary String",
    "statement": "Vasya has a string $s$ of length $n$ consisting only of digits 0 and 1. Also he has an array $a$ of length $n$.\n\nVasya performs the following operation until the string becomes empty: choose some \\textbf{consecutive} substring of \\textbf{equal characters}, erase it from the string and glue together the remaining parts (any of them can be empty). For example, if he erases substring 111 from string {1\\textbf{111}10} he will get the string 110. Vasya gets $a_x$ points for erasing substring of length $x$.\n\nVasya wants to maximize his total points, so help him with this!",
    "tutorial": "We will solve the problem with dynamic programming. Let $ans_{l, r}$ be the answer for substring $s_{l, l + 1, \\dots r}$. If sequence is empty ($l > r$) then $ans_{l, r} = 0$. Let $dp_{dig, l, r, cnt}$ be the maximum score that we can get if we reduce the substring $s_{l, l + r, \\dots r}$ into $cnt$ digits equal to $dig$ with some operations. If substring $s_{l, l + r, \\dots r}$ does not contain $cnt$ digit $dig$, then $dp_{dig, l, r, cnt} = -10^{18}$. If $cnt = 0$, then $dp_{dig, l, r, cnt} = ans_{l, r}$. To calculate $ans_{l, r}$ just fix the sequence of digits that will be deleted last: $ans_{l, r} = \\max\\limits_{1 \\le cnt \\le r - l + 1, 0 \\le dig \\le 1} a_{cnt} + dp_{dig, l, r, cnt}$. To calculate $dp_{dig, l, r, cnt}$ just fix the first element $mid$ that is left after working with the substring. Note that $s_{mid}$ must be equal to $dig$. $dp_{dig, l, r, cnt} = \\max\\limits_{1 \\le mid \\le r, s_{mid} = dig} ans_{l, mid - 1} + dp_{dig, mid + 1, r, cnt - 1}$. All that's left is to transform these formulas into code. Complexity of this solution is $O(n^4)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 102;\nconst long long INF = 1e12;\n\nint n;\nstring s;\nint a[N];\n\nlong long ans[N][N];\nlong long dp[2][N][N][N];\n\nlong long calcDp(int c, int l, int r, int cnt);\n\nlong long calcAns(int l, int r){\n\tif(l >= r) return 0;\n\tlong long &res = ans[l][r];\n\tif(res != -1) return res;\n\n\tres = 0;\n\tfor(int cnt = 1; cnt <= r - l; ++cnt){\n\t\tres = max(res, calcDp(0, l, r, cnt) + a[cnt - 1]);\n\t\tres = max(res, calcDp(1, l, r, cnt) + a[cnt - 1]);\n\t}\n\n\treturn res;\n}\n\nlong long calcDp(int c, int l, int r, int cnt){\n\tif(cnt == 0) return calcAns(l, r);\n\tlong long &res = dp[c][l][r][cnt];\n\tif(res != -1) return res;\n\t\n\tres = -INF;\n\n\tfor(int i = l; i < r; ++i){\n\t\tif(c == s[i] - '0')\n\t\t\tres = max(res, calcAns(l, i) + calcDp(c, i + 1, r, cnt - 1));\n\t}\n\n\treturn res;\n}\n\nint main(){\n\tcin >> n >> s;\n\tfor(int i = 0; i < n; ++i)\n\t\tcin >> a[i];\n\n\t\n\tmemset(dp, -1, sizeof dp);\n\tmemset(ans, -1, sizeof ans);\n\n\tcout << calcAns(0, n) << endl;\t\n\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1107",
    "index": "F",
    "title": "Vasya and Endless Credits",
    "statement": "Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles.\n\nHowever, the local bank has $n$ credit offers. Each offer can be described with three numbers $a_i$, $b_i$ and $k_i$. Offers are numbered from $1$ to $n$. If Vasya takes the $i$-th offer, then the bank gives him $a_i$ burles at the beginning of the month and then Vasya pays bank $b_i$ burles at the end of each month for the next $k_i$ months (including the month he activated the offer). \\textbf{Vasya can take the offers any order he wants}.\n\n\\textbf{Each month Vasya can take no more than one credit offer}. \\textbf{Also each credit offer can not be used more than once}. Several credits can be active at the same time. It implies that Vasya pays bank the sum of $b_i$ over all the $i$ of active credits at the end of each month.\n\nVasya wants to buy a car in the middle of some month. He just takes all the money he currently has and buys the car of that exact price.\n\nVasya don't really care what he'll have to pay the bank back after he buys a car. He just goes out of the country on his car so that the bank can't find him anymore.\n\nWhat is the maximum price that car can have?",
    "tutorial": "Let create the following matrix (zero-indexed): $mat_{i, j} = a_j - min(i, k_j) \\cdot b_j$. $i$-th row of this matrix contains Vasya's profits for credit offers as if they were taken $i$ months before the purchase. We need to choose elements from this matrix so that there is no more than one element taken in each row and each column. The sum of the chosen elements should be maximum possible. And that is exactly the problem Hungarian algorithm solves.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 505;\nconst long long INF = 1e18;\n\nint n;\nlong long a[N][N];\nint up[N], down[N], k[N];\nlong long u[N], v[N];\nint p[N], way[N];\n\nint main(){\n\tcin >> n;\n\tfor(int i = 0; i < n; ++i)\n\t\tcin >> up[i] >> down[i] >> k[i];\n\t\n\tfor(int i = 0; i < n; ++i)\n\t\tfor(int j = 0; j < n; ++j)\n\t\t\ta[i + 1][j + 1] = -(up[j] - min(i, k[j]) * 1LL * down[j]);\n\n\tlong long res = 0;\n\tfor(int i = 1; i <= n; ++i){\n\t\tp[0] = i;\n\t\tint j0 = 0;\n\t\tvector<long long> minv (n + 1, INF);\n\t\tvector<char> used (n + 1, false);\n\t\tdo{\n\t\t\tused[j0] = true;\n\t\t\tint i0 = p[j0],   j1;\n\t\t\tlong long delta = INF;\n\t\t\tfor (int j = 1; j <= n; ++j)\n\t\t\t\tif (!used[j]){\n\t\t\t\t\tlong long cur = a[i0][j] - u[i0] - v[j];\n\t\t\t\t\tif (cur < minv[j])\n\t\t\t\t\t\tminv[j] = cur,  way[j] = j0;\n\t\t\t\t\tif (minv[j] < delta)\n\t\t\t\t\t\tdelta = minv[j],  j1 = j;\n\t\t\t\t}\n\t\t\tfor (int j = 0; j <= n; ++j)\n\t\t\t\tif (used[j])\n\t\t\t\t\tu[p[j]] += delta,  v[j] -= delta;\n\t\t\t\telse\n\t\t\t\t\tminv[j] -= delta;\n\t\t\tj0 = j1;\n\t\t}while (p[j0] != 0);\n\t\tdo {\n\t\t\tint j1 = way[j0];\n\t\t\tp[j0] = p[j1];\n\t\t\tj0 = j1;\n\t\t} while (j0);\n\n\t\tres = max(res, v[0]);\n\t}\n\n\tcout << res << endl;\n\treturn 0;\n}",
    "tags": [
      "dp",
      "flows",
      "graph matchings",
      "graphs",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1107",
    "index": "G",
    "title": "Vasya and Maximum Profit",
    "statement": "Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit.\n\nVasya has $n$ problems to choose from. They are numbered from $1$ to $n$. The difficulty of the $i$-th problem is $d_i$. Moreover, the problems are given in the increasing order by their difficulties. \\textbf{The difficulties of all tasks are pairwise distinct}. In order to add the $i$-th problem to the contest you need to pay $c_i$ burles to its author. For each problem in the contest Vasya gets $a$ burles.\n\n\\textbf{In order to create a contest he needs to choose a consecutive subsegment of tasks}.\n\nSo the total earnings for the contest are calculated as follows:\n\n- if Vasya takes problem $i$ to the contest, he needs to pay $c_i$ to its author;\n- for each problem in the contest Vasya gets $a$ burles;\n- let $gap(l, r) = \\max\\limits_{l \\le i < r} (d_{i + 1} - d_i)^2$. If Vasya takes all the tasks with indices from $l$ to $r$ to the contest, he also needs to pay $gap(l, r)$. If $l = r$ then $gap(l, r) = 0$.\n\nCalculate the maximum profit that Vasya can earn by taking a consecutive segment of tasks.",
    "tutorial": "It is clear that $gap(l, r) \\le gap(l, r + 1)$ and $gap(l, r) \\le gap(l - 1, r)$. Sort all indices $2, 3, \\dots, n$ with comparator based on the value of $d_i - d_{i-1}$. Let's consider all indices in the order discussed above and for fixed index $i$ find the best answer among such segments $(l, r)$ that $gap(l, r) \\le d_i$, $gap_(l-1, r) > d_i$ and $gap_(l, r+1) > d_i$. Initially, when we consider $gap = 0$, there are $n$ such segments, each containing only one task. When we consider new index $j$, we need to merge segments $(l, j - 1)$ and $(j, r)$ and update the answer with $best(l, r) - (d_j - d_{j-1})^2$, where $best(l, r)$ is the maximum subsegment in array $a - c_l, a - c_{l+1}, \\dots, a - c_r$ (that array represents the profit we get for each task). We can store and merge such segments with $set$ in C++ or $TreeSet$ in Java. We can answer queries $best(l, r)$ using the segment tree (we need to process queries of the form \"find a subsegment having maximum sum\"). Read more about it here.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\n\nstruct node{\n\tlong long sum, ans, pref, suf;\n\t\n\tnode () {}\n\tnode(int x){\n\t\tsum = x;\n\t\tx = max(x, 0);\n\t\tpref = suf = ans = x;\n\t}\n};\n\nnode merge(const node &a, const node &b){\n\tnode res;\n\tres.sum = a.sum + b.sum;\n\tres.pref = max(a.pref, a.sum + b.pref);\n\tres.suf = max(b.suf, b.sum + a.suf);\n\tres.ans = max(max(a.ans, b.ans), a.suf + b.pref);\n\treturn res;\n}\n\nint n, x;\npair<int, int> p[N];\nnode t[N * 4];\n\nvoid upd(int v, int l, int r, int pos, int x){\n\tif(r - l == 1){\n\t\tassert(pos == l);\n\t\tt[v] = node(x);\n\t\treturn;\n\t}\n\t\n\tint mid = (l + r) / 2;\n\tif(pos < mid) upd(v * 2 + 1, l, mid, pos, x);\n\telse upd(v * 2 + 2, mid, r, pos, x);\n\t\n\tt[v] = merge(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\nnode get(int v, int l, int r, int L, int R){\n\tif(L >= R) return node(0);\n\t\n\tif(l == L && r == R)\n\t\treturn t[v];\n\t\n\tint mid = (l + r)/ 2;\n\treturn merge(get(v * 2 + 1, l, mid, L, min(mid, R)),\n\t\t\t\t get(v * 2 + 2, mid, r, max(L, mid), R));\t\n}\n\nint main() {\n\tscanf(\"%d %d\", &n, &x);\n\tfor(int i = 0; i < n; ++i){\n\t\tscanf(\"%d %d\", &p[i].first, &p[i].second);\n\t\tp[i].second = x - p[i].second;\n\t}\n\t\n\tsort(p, p + n);\n\tfor(int i = 0; i < n; ++i) upd(0, 0, n, i, p[i].second);\n\t\n\tvector <pair<int, int> > v;\n\tfor(int i = 1; i < n; ++i)\n\t\tv.emplace_back(p[i].first - p[i - 1].first, i);\n\tsort(v.begin(), v.end());\n\t\n\tlong long res = 0;\n\tset <pair<int, int> > s;\n\tfor(int i = 0; i < n; ++i){\n\t\ts.insert(make_pair(i, i + 1));\n\t\tres = max(res, 1LL * p[i].second);\n\t}\n\t\n\tint l = 0;\n\twhile(l < v.size()){\n\t\tint r = l + 1;\n\t\twhile(r < v.size() && v[l].first == v[r].first) ++r;\n\t\tlong long d = v[l].first * 1LL * v[l].first;\n\t\t\n\t\tfor(int i = l; i < r; ++i){\n\t\t\tint id = v[i].second;\n\t\t\tauto it = s.upper_bound(make_pair(id, -1));\n\t\t\tassert(it->first == id);\n\t\t\tassert(it != s.begin());\n\t\t\tauto R = *it;\n\t\t\t--it;\n\t\t\tauto L = *it;\n\t\t\ts.erase(L), s.erase(R);\n\t\t\tL.second = R.second;\n\t\t\t\n\t\t\tauto nd = get(0, 0, n, L.first, L.second);\n\t\t\tres = max(res, nd.ans - d);\n\t\t\ts.insert(L);\n\t\t}\n\t\t\n\t\tl = r;\n\t}\n\t\n\tcout << res << endl;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "dp",
      "dsu"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1108",
    "index": "A",
    "title": "Two distinct points",
    "statement": "You are given two segments $[l_1; r_1]$ and $[l_2; r_2]$ on the $x$-axis. It is guaranteed that $l_1 < r_1$ and $l_2 < r_2$. Segments \\textbf{may intersect, overlap or even coincide with each other}.\n\n\\begin{center}\n{\\small The example of two segments on the $x$-axis.}\n\\end{center}\n\nYour problem is to find two \\textbf{integers} $a$ and $b$ such that $l_1 \\le a \\le r_1$, $l_2 \\le b \\le r_2$ and $a \\ne b$. In other words, you have to choose two \\textbf{distinct} integer points in such a way that the first point belongs to the segment $[l_1; r_1]$ and the second one belongs to the segment $[l_2; r_2]$.\n\nIt is guaranteed that \\textbf{the answer exists}. If there are multiple answers, you can print \\textbf{any} of them.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "One of the possible answers is always a pair of endpoints of the given segments. So we can add all endpoints to the array and iterate over all pairs of elements of this array and check if the current pair is suitable or not.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\tfor (int i = 0; i < t; ++i) {\n\t\tint l1, r1, l2, r2;\n\t\tcin >> l1 >> r1 >> l2 >> r2;\n\t\tvector<int>a({l1, r1, l2, r2});\n\t\tint ans1 = 0, ans2 = 0;\n\t\tfor (auto it : a) for (auto jt : a) {\n\t\t\tif (l1 <= it && it <= r1 && l2 <= jt && jt <= r2 && it != jt) {\n\t\t\t\tans1 = it;\n\t\t\t\tans2 = jt;\n\t\t\t}\n\t\t}\n\t\tcout << ans1 << \" \" << ans2 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1108",
    "index": "B",
    "title": "Divisors of Two Integers",
    "statement": "Recently you have received two \\textbf{positive} integer numbers $x$ and $y$. You forgot them, but you remembered a \\textbf{shuffled} list containing all divisors of $x$ (including $1$ and $x$) and all divisors of $y$ (including $1$ and $y$). If $d$ is a divisor of both numbers $x$ and $y$ at the same time, there are two occurrences of $d$ in the list.\n\nFor example, if $x=4$ and $y=6$ then the given list can be any permutation of the list $[1, 2, 4, 1, 2, 3, 6]$. Some of the possible lists are: $[1, 1, 2, 4, 6, 3, 2]$, $[4, 6, 1, 1, 2, 3, 2]$ or $[1, 6, 3, 2, 4, 1, 2]$.\n\nYour problem is to restore suitable \\textbf{positive} integer numbers $x$ and $y$ that would yield the same list of divisors (possibly in different order).\n\nIt is guaranteed that the answer exists, i.e. the given list of divisors corresponds to some \\textbf{positive} integers $x$ and $y$.",
    "tutorial": "Let's take a look on the maximum element of the given array. Suddenly, this number is $x$ (or $y$, the order doesn't matter). Okay, what would we do if we know $x$ and merged list of divisors of $x$ and $y$? Let's remove all divisors of $x$ and see what we got. The maximum element in the remaining array is $y$. So, the problem is solved.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tmultiset<int> a;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\ta.insert(x);\n\t}\n\t\n\tint x = *prev(a.end());\n\tfor (int i = 1; i <= x; ++i) {\n\t\tif (x % i == 0) {\n\t\t\ta.erase(a.find(i));\n\t\t}\n\t}\n\t\n\tcout << x << \" \" << *prev(a.end()) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1108",
    "index": "C",
    "title": "Nice Garland",
    "statement": "You have a garland consisting of $n$ lamps. Each lamp is colored red, green or blue. The color of the $i$-th lamp is $s_i$ ('R', 'G' and 'B' — colors of lamps in the garland).\n\nYou have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is \\textbf{nice}.\n\nA garland is called \\textbf{nice} if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $t$, then for each $i, j$ such that $t_i = t_j$ should be satisfied $|i-j|~ mod~ 3 = 0$. The value $|x|$ means absolute value of $x$, the operation $x~ mod~ y$ means remainder of $x$ when divided by $y$.\n\nFor example, the following garlands are \\textbf{nice}: \"RGBRGBRG\", \"GB\", \"R\", \"GRBGRBG\", \"BRGBRGB\". The following garlands are not \\textbf{nice}: \"RR\", \"RGBG\".\n\nAmong all ways to recolor the initial garland to make it \\textbf{nice} you have to choose one with the \\textbf{minimum} number of recolored lamps. If there are multiple optimal solutions, print \\textbf{any} of them.",
    "tutorial": "It is easy to see that any nice garland has one of the following $6$ patterns: \"BGRBGR ... BGR\"; \"BRGBRG ... BRG\"; \"GBRGBR ... GBR\"; \"GRBGRB ... GRB\"; \"RBGRBG ... RBG\"; \"RGBRGB ... RGB\"; We can hard-code all all this patterns or iterate over all these permutations of letters \"BGR\" using three nested loops or standard language functions. We can calculate for each pattern the cost to obtain such pattern from the given string and choose one with the minimum cost.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\t\n\tvector<int> p(3);\n\tiota(p.begin(), p.end(), 0);\n\t\n\tstring colors = \"RGB\";\n\tstring res = \"\";\n\tint ans = 1e9;\n\t\n\tdo {\n\t\tstring t;\n\t\tint cnt = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tt += colors[p[i % 3]];\n\t\t\tcnt += t[i] != s[i];\n\t\t}\n\t\tif (ans > cnt) {\n\t\t\tans = cnt;\n\t\t\tres = t;\n\t\t}\n\t} while (next_permutation(p.begin(), p.end()));\n\t\n\tcout << ans << endl << res << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1108",
    "index": "D",
    "title": "Diverse Garland",
    "statement": "You have a garland consisting of $n$ lamps. Each lamp is colored red, green or blue. The color of the $i$-th lamp is $s_i$ ('R', 'G' and 'B' — colors of lamps in the garland).\n\nYou have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is \\textbf{diverse}.\n\nA garland is called \\textbf{diverse} if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is $1$) have distinct colors.\n\nIn other words, if the obtained garland is $t$ then for each $i$ from $1$ to $n-1$ the condition $t_i \\ne t_{i + 1}$ should be satisfied.\n\nAmong all ways to recolor the initial garland to make it \\textbf{diverse} you have to choose one with the \\textbf{minimum} number of recolored lamps. If there are multiple optimal solutions, print \\textbf{any} of them.",
    "tutorial": "Let's divide the initial string into blocks of consecutive equal letters. For example, if we have the string \"GGBBBRRBBBB\" then have $4$ blocks: the first block is two letters 'G', the second one is three letters 'B', the third one is two letters 'R' and the last one is four letters 'B'. Let's see at the current block (let it has the length $len$) and consider two cases. The first case is when this block has odd length. Then it seems like \"XXXXXXX\". So, what is the minimum number of recolors we need to make this block correct? It is $\\lfloor\\frac{len}{2}\\rfloor$. Why can we always make this block correct for such number of recolors? Because we can recolor all 'X' at even positions to any 'Y' which differs from 'X'. So our block will be look like \"XYXYXYX\". The second case is when this block has even length. Then it seems like \"XXXXYYY ... YYY\" where 'Y' is the next block letter (if the next block exists, because the last block doesn't have the next one). What is the minimum number of recolors in this case? It is $\\frac{len}{2}$. How can we recolor this block to make it correct? Let's recolor all 'X' at even positions (again) to any 'Z' which differs from 'X' and differs from 'Y'. So our block will be look like \"XZXZYYY ... YYY\". So all we have to do is to iterate over all blocks from left to right and apply the algorithm above to recolor them.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\t\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint j = i;\n\t\twhile (j < n && s[i] == s[j]) {\n\t\t\t++j;\n\t\t}\n\t\tstring q = \"RGB\";\n\t\tq.erase(q.find(s[i]), 1);\n\t\tif (j < n) q.erase(q.find(s[j]), 1);\n\t\tfor (int k = i + 1; k < j; k += 2) {\n\t\t\t++ans;\n\t\t\ts[k] = q[0];\n\t\t}\n\t\ti = j - 1;\n\t}\n\t\n\tcout << ans << endl << s << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1108",
    "index": "E1",
    "title": "Array and Segments (Easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is a number of elements in the array}.\n\nYou are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$.\n\nYou are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \\le l_j \\le r_j \\le n$.\n\nYou can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (\\textbf{independently}). For example, if the initial array $a = [0, 0, 0, 0, 0]$ and the given segments are $[1; 3]$ and $[2; 4]$ then you can choose both of them and the array will become $b = [-1, -2, -2, -1, 0]$.\n\nYou have to choose some subset of the given segments (\\textbf{each segment can be chosen at most once}) in such a way that if you apply this subset of segments to the array $a$ and obtain the array $b$ then the value $\\max\\limits_{i=1}^{n}b_i - \\min\\limits_{i=1}^{n}b_i$ will be \\textbf{maximum} possible.\n\nNote that \\textbf{you can choose the empty set}.\n\nIf there are multiple answers, you can print \\textbf{any}.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "Let's divide all segments to four classes. The first class contains segments which covers both minimum and maximum values (the answer) of the resulting array, the second class contains segments which covers only minimum value of the resulting array, the third class contains segments which covers only maximum value of the resulting array and the fourth class contains segments which covers neither maximum nor minimum of the resulting array. We can easy see that we cannot increase the answer if we apply segments of first and third classes. What is common in this two classes? Right, both of them are cover maximum value. So we can came up with the solution in $O(n^2m)$ or $O(n(n+m))$ (depends on implementation). Let's iterate over position of the supposed maximum value and apply all segments which not cover it. It can be done in $O(n^2m)$ with straight-forward implementation or in $O(n(n+m))$ using prefix sums. After we apply all needed segments we can try to update the answer with the value of the obtained array.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nmt19937 rnd(time(NULL));\n\nconst int INF = 1e9;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tvector<pair<int, int>> b(m);\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> b[i].first >> b[i].second;\n\t\t--b[i].first;\n\t\t--b[i].second;\n\t}\n\t\n\tint ans = *max_element(a.begin(), a.end()) - *min_element(a.begin(), a.end());\n\tvector<int> res;\n\tfor (int i = 0; i < n; ++i) {\n\t\tvector<int> add(n + 1);\n\t\tvector<int> cur;\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tif (!(b[j].first <= i && i <= b[j].second)) {\n\t\t\t\tcur.push_back(j);\n\t\t\t\tfor (int k = b[j].first; k <= b[j].second; ++k) {\n\t\t\t\t\t--add[k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint mn = INF, mx = -INF;\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tmn = min(mn, a[j] + add[j]);\n\t\t\tmx = max(mx, a[j] + add[j]);\n\t\t}\n\t\tif (ans < mx - mn) {\n\t\t\tans = mx - mn;\n\t\t\tres = cur;\n\t\t}\n\t}\n\t\n\tcout << ans << endl << res.size() << endl;\n\tshuffle(res.begin(), res.end(), rnd);\n\tfor (auto it : res) cout << it + 1 << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1108",
    "index": "E2",
    "title": "Array and Segments (Hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is a number of elements in the array}.\n\nYou are given an array $a$ consisting of $n$ integers. The value of the $i$-th element of the array is $a_i$.\n\nYou are also given a set of $m$ segments. The $j$-th segment is $[l_j; r_j]$, where $1 \\le l_j \\le r_j \\le n$.\n\nYou can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (\\textbf{independently}). For example, if the initial array $a = [0, 0, 0, 0, 0]$ and the given segments are $[1; 3]$ and $[2; 4]$ then you can choose both of them and the array will become $b = [-1, -2, -2, -1, 0]$.\n\nYou have to choose some subset of the given segments (\\textbf{each segment can be chosen at most once}) in such a way that if you apply this subset of segments to the array $a$ and obtain the array $b$ then the value $\\max\\limits_{i=1}^{n}b_i - \\min\\limits_{i=1}^{n}b_i$ will be \\textbf{maximum} possible.\n\nNote that \\textbf{you can choose the empty set}.\n\nIf there are multiple answers, you can print \\textbf{any}.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "This tutorial is based on the previous problem (easy version) tutorial. At first, I want to say I know that this problem and this approach can be implemented in $O(m \\log n)$ with segment tree. So, we iterate over all supposed maximums in the array and trying to apply all segments not covering our current element. How do we can calculate the answer for each element if this element is the supposed maximum? Let's divide all segments we apply into two parts: the first part consists of segments such that their right endpoints is less than the current position and the second part consists of segments such that their left endpoints is greater than the current position. Then let's independently calculate answers for the left and for the right parts and merge them to obtain the answer. I will consider only first part of the solution (first part of segments) because the second part is absolutely symmetric with it. Let's maintain the minimum value on prefix of the array (let it be $mn$ and initially it equals to $+\\infty$), maintain the array $ansv$ of length $n$ (initially its values are $-\\infty$ and $ansv_i$ means the answer if the $i$-th element of the array will be supposed maximum) and the array $add$ of length $n$, where $add_i$ will be the value for which we decrease the $i$-th element (in other words, the number of segments we apply to the $i$-th element). What do we do for the current position $i$? Firstly, let's update the answer for it with the value $a_i + add_i - mn$ (in other words, set $ansv_i := max(ansv_i, a_i + add_i - mn$)). Then let's apply all segments with right endpoints equals to the current position straight-forward and update the value $mn$ with each new value of covered elements. Just iterate over all positions $j$ of each segment ends in the current position, make $add_j := add_j - 1$ and set $mn := min(mn, a_j + add_j)$. And don't forget to update the value $mn$ with the value $a_i + add_i$ after all changes (because we need to update this value with each element not covered by segments too). So then let's do the same from right to left and then $ansv_i$ will mean the answer if the $i$-th element is the supposed maximum in the resulting array. Then we can find any position of the maximum in the array $ansv$ and apply all segments which don't cover this position. What is time complexity of the solution above? We iterate over all elements in the array, this is $O(n)$ and apply each segment in $O(n)$, so the final time complexity is $O(n + nm) = O(nm)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nmt19937 rnd(time(NULL));\n\nconst int INF = 1e9;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\t\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tvector<pair<int, int>> b(m);\n\tvector<vector<int>> lf(n), rg(n);\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> b[i].first >> b[i].second;\n\t\t--b[i].first;\n\t\t--b[i].second;\n\t\tlf[b[i].second].push_back(b[i].first);\n\t\trg[b[i].first].push_back(b[i].second);\n\t\t}\n\t\n\tvector<int> ansv(n, -INF);\n\t\n\tvector<int> add(n + 1 , 0);\n\tint mn = a[0];\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tansv[i] = max(ansv[i], a[i] - mn);\n\t\tfor (auto l : lf[i]) {\n\t\t\tfor (int j = l; j <= i; ++j) {\n\t\t\t\t--add[j];\n\t\t\t\tmn = min(mn, a[j] + add[j]);\n\t\t\t}\n\t\t}\n\t\tmn = min(mn, a[i] + add[i]);\n\t}\n\t\n\tadd = vector<int>(n + 1, 0);\n\tmn = a[n - 1];\n\t\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tansv[i] = max(ansv[i], a[i] - mn);\n\t\tfor (auto r : rg[i]) {\n\t\t\tfor (int j = i; j <= r; ++j) {\n\t\t\t\t--add[j];\n\t\t\t\tmn = min(mn, a[j] + add[j]);\n\t\t\t}\n\t\t}\n\t\tmn = min(mn, a[i] + add[i]);\n\t}\n\t\n\tint ans = *max_element(ansv.begin(), ansv.end());\n\tvector<int> res;\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (ansv[i] == ans) {\n\t\t\tfor (int j = 0; j < m; ++j) {\n\t\t\t\tif (!(b[j].first <= i && i <= b[j].second)) {\n\t\t\t\t\tres.push_back(j);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tcout << ans << endl << res.size() << endl;\n\tshuffle(res.begin(), res.end(), rnd);\n\tfor (auto it : res) cout << it + 1 << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1108",
    "index": "F",
    "title": "MST Unification",
    "statement": "You are given an undirected weighted \\textbf{connected} graph with $n$ vertices and $m$ edges \\textbf{without loops and multiple edges}.\n\nThe $i$-th edge is $e_i = (u_i, v_i, w_i)$; the distance between vertices $u_i$ and $v_i$ along the edge $e_i$ is $w_i$ ($1 \\le w_i$). The graph is \\textbf{connected}, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.\n\nA minimum spanning tree (MST) in case of \\textbf{positive} weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).\n\nYou can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $1$. You \\textbf{can} increase the weight of each edge multiple (possibly, zero) times.\n\nSuppose that the initial MST cost is $k$. Your problem is to increase weights of some edges \\textbf{with minimum possible number of operations} in such a way that the cost of MST in the obtained graph remains $k$, but MST is \\textbf{unique} (it means that there is only one way to choose MST in the obtained graph).\n\nYour problem is to calculate the \\textbf{minimum} number of operations required to do it.",
    "tutorial": "The first (and the most straight-forward) approach is to construct MST with any suitable algorithm, build LCA with the maximum edge on a path with binary lifting technique and then we have to increase the answer for each edge $e_i = (u_i, v_i, w_i)$ such that $w_i$ equals to the maximum edge on a path between $u_i$ and $v_i$ in MST. The second (and the most pretty and easy to implement) solution is the improved Kruskal algorithm. Let's do Kruskal algorithm on the given edges. Sort them, and let's consider all edges of the same weight at once. They can be divided into two classes. The first class contains edges which connect nothing and the second class contains edges which can connect something. Let the number of edges of current weight be $k$, edges of the current weight of the first class be $k_{bad}$ and edges with of current weight of the second class be $k_{good}$. Okay, we can just skip the first class because it will never increase the answer. How to calculate useless edges of the second class? Let's try to merge all components connected with edges of the second class. Suppose we make $q$ merges. Then we have to increase weights of all remaining edges by one. So we add to the answer the value $k_{good} - q$ and go to the next weight. Why is this right? This is right because if the edge of the second class cannot connect anything because of the previously considered edges then the maximum on a path between endpoints of this edge equals to this edge weight. So we have to increase the weight of this edge by one. If we didn't do it we would be able to replace the edge connects these components with our edge. And it is obvious that this edge is totally useless with the weight increased by one. Time complexity is $O(m \\log m)$ because of edges sorting.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n\nvector<int> p, rk;\n\nint getp(int v) {\n\tif (v == p[v]) return v;\n\treturn p[v] = getp(p[v]);\n}\n\nbool merge(int v, int u) {\n\tu = getp(u);\n\tv = getp(v);\n\t\n\tif (u == v) return false;\n\t\n\tif (rk[u] < rk[v]) swap(u, v);\n\t\n\trk[u] += rk[v];\n\tp[v] = u;\n\t\n\treturn true;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tios_base::sync_with_stdio(0);\n\tint n, m;\n\tcin >> n >> m;\n\t\n\tp = vector<int>(n);\n\tiota(p.begin(), p.end(), 0);\n\trk = vector<int>(n, 1);\n\t\n\tvector<pair<pair<int, int>, int>> e(m);\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> e[i].x.x >> e[i].x.y >> e[i].y;\n\t\t--e[i].x.x;\n\t\t--e[i].x.y;\n\t}\n\t\n\tsort(e.begin(), e.end(), [](pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) {\n\t\treturn a.y < b.y;\n\t});\n\t\n\tint ans = 0;\n\tfor (int i = 0; i < m; ++i) {\n\t\tint j = i;\n\t\twhile (j < m && e[i].y == e[j].y) {\n\t\t\t++j;\n\t\t}\n\t\tint cnt = j - i;\n\t\tfor (int k = i; k < j; ++k) {\n\t\t\tif (getp(e[k].x.x) == getp(e[k].x.y)) {\n\t\t\t\t--cnt;\n\t\t\t}\n\t\t}\n\t\tfor (int k = i; k < j; ++k) {\n\t\t\tcnt -= merge(e[k].x.x, e[k].x.y);\n\t\t}\n\t\tans += cnt;\n\t\ti = j - 1;\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1109",
    "index": "A",
    "title": "Sasha and a Bit of Relax",
    "statement": "Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.\n\nTherefore, Sasha decided to upsolve the following problem:\n\nYou have an array $a$ with $n$ integers. You need to count the number of funny pairs $(l, r)$ $(l \\leq r)$. To check if a pair $(l, r)$ is a funny pair, take $mid = \\frac{l + r - 1}{2}$, then if $r - l + 1$ is an \\textbf{even} number and $a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_{mid} = a_{mid + 1} \\oplus a_{mid + 2} \\oplus \\ldots \\oplus a_r$, then the pair is funny. In other words, $\\oplus$ of elements of the left half of the subarray from $l$ to $r$ should be equal to $\\oplus$ of elements of the right half. Note that $\\oplus$ denotes the bitwise XOR operation.\n\nIt is time to continue solving the contest, so Sasha asked you to solve this task.",
    "tutorial": "Notice, that if $a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_{mid} = a_{mid + 1} \\oplus a_{mid + 2} \\oplus \\ldots \\oplus a_r$ then $a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_r = 0$ (it comes from the fact that for some integers $A$, $B$, $C$ if $A \\oplus B = C$ then $A = B \\oplus C$). Now we have another task. How many are there pairs $(l, r)$ that $r - l + 1$ is even and $a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_r = 0$. Precalculate array $pref_i = a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_i$. Then $a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_r = pref_r \\oplus pref_{l-1}$. So if $pref_r \\oplus pref_{l - 1} = 0$ then $pref_r = pref_{l - 1}$. So again we should solve another thask, which is equivalent to original one. How many are there pairs $(l, r)$ that $r - l + 1$ is even and $pref_r = pref_{l - 1}$. So to count the answer just have two arrays $cnt[0][x]$ to store elements from even positions and $cnt[1][x]$ for odd positions. Then iterate $i$ from $1$ to $n$ and add to the answer $cnt[i \\mod 2][pref_i]$. After you processed $i$, increase $cnt[i \\mod 2][pref_i]$ by $1$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing std::cin;\\nusing std::cout;\\nusing std::endl;\\n\\nconst int maxn = (int)3e5 + 3;\\nconst int maxa = (1 << 20) + 3;\\n\\n\\nint n;\\nint a[maxn];\\nint cnt[2][maxa];\\n\\n\\nint32_t main() {\\n    std::ios_base::sync_with_stdio(false);\\n\\n    cin >> n;\\n    for(int i = 0; i < n; ++i) {\\n        cin >> a[i];\\n    }\\n    cnt[1][0] = 1;\\n    int x = 0;\\n    int64_t res = 0;\\n    for(int i = 0; i < n; ++i) {\\n        x ^= a[i];\\n        res += cnt[i % 2][x];\\n        ++cnt[i % 2][x];\\n\\n    }\\n    cout << res << endl;\\n    return 0;\\n}\\n\"",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1109",
    "index": "B",
    "title": "Sasha and One More Name",
    "statement": "Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: \"Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not.\"\n\nAnd at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as \"kazak\", \"oo\" and \"r\" are palindromes, but strings \"abb\" and \"ij\" are not.\n\nSasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $k$, so they got $k+1$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces \\textbf{couldn't be turned over}, they could be shuffled.\n\nIn this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $3$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.\n\nMore formally, Sasha wants for the given \\textbf{palindrome} $s$ find such minimum $k$, that you can cut this string into $k + 1$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $s$. It there is no answer, then print \"Impossible\" (without quotes).",
    "tutorial": "Let's $s$ be the given string, $n$ - it's length. If $s$ consists of $n$ or $n - 1$ (when $n$ is odd) equal characters, then there is no way to get the answer. Otherwise, let's prove that the answer can be always reached in two cuttings. Let's the longest prefix of $s$, that consists of equal characters has the length equal to $len - 1$. Cut $pref = s[1 \\ldots len]$ and $suff = s[n-len+1 \\ldots n]$, and call the remaining piece as $mid$. Swap $pref$ and $suff$, then unite all three parts together. The central part ($mid$) will stay unchanged, $pref \\neq reverse(pref)$ and $pref \\neq suff$ then $pref + mid + suf \\neq suf + mid + pref$. So now we can get the answer in two cuttings. Finally you must chech if it is possible to get the result by making just one cutting. As soon as one cutting is equal to some cyclic shift, then our task is to check if there is a cyclic shift which is a palindrome and not equal to $s$. It can be done by fixing each cyclic shift and checking each one separately. Complexity: $O(n^2)$",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\nbool isPalindrome(const string& s) {\\n    for(int i = 0; i < s.length(); ++i) {\\n        if (s[i] != s[s.length() - i - 1]) \\n            return false;\\n    }\\n    return true;\\n}\\n\\nbool solve1(string s) {\\n    string t = s;\\n    for(int i = 0; i < s.length(); ++i) {\\n        t = t.back() + t;\\n        t.pop_back();\\n        if (s != t && isPalindrome(t)) {\\n            return true;\\n        }\\n    }\\n    return false;\\n}\\n\\nbool anyAnswer(const string& s) {\\n    int nt = 0;\\n    for(int i = 0; i < s.length(); ++i) {\\n        nt += s[i] != s[0];\\n    }\\n    return nt > 1;\\n}\\n\\nint32_t main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr), cout.tie(nullptr);\\n\\n    string s;\\n    cin >> s;\\n    if (anyAnswer(s)) {\\n        cout << (solve1(s) ? 1 : 2) << endl;\\n    } else {\\n        cout << \\\"Impossible\\\" << endl;\\n    }\\n\\n    return 0;\\n}\\n\"",
    "tags": [
      "constructive algorithms",
      "hashing",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1109",
    "index": "C",
    "title": "Sasha and a Patient Friend",
    "statement": "Fedya and Sasha are friends, that's why Sasha knows everything about Fedya.\n\nFedya keeps his patience in an infinitely large bowl. But, unlike the bowl, Fedya's patience isn't infinite, that is why let $v$ be the number of liters of Fedya's patience, and, as soon as $v$ becomes \\textbf{equal} to $0$, the bowl will burst immediately. There is one tap in the bowl which pumps $s$ liters of patience per second. Notice that $s$ can be negative, in that case, the tap pumps out the patience. Sasha can do different things, so he is able to change the tap's speed. All actions that Sasha does can be represented as $q$ queries. There are three types of queries:\n\n- \"1 t s\"  — add a new event, means that starting from the $t$-th second the tap's speed will be equal to $s$.\n- \"2 t\"  — delete the event which happens at the $t$-th second. It is guaranteed that such event exists.\n- \"3 l r v\" — Sasha wonders: if you take all the events for which $l \\le t \\le r$ and simulate changes of Fedya's patience from the very beginning of the $l$-th second till the very beginning of the $r$-th second inclusive (the initial volume of patience, at the beginning of the $l$-th second, equals to $v$ liters) then when will be the moment when the bowl will burst. If that does not happen, then the answer will be $-1$.\n\nSince Sasha does not want to check what will happen when Fedya's patience ends, and he has already come up with the queries, he is asking you to help him and find the answer for each query of the $3$-rd type.\n\nIt is guaranteed that at any moment of time, there won't be two events which happen at the same second.",
    "tutorial": "Let's keep not deleted pairs ($t, s$) in a treap where $t$ will be the key of some node. Also we need some auxiliary variables. So each node in the treap will store that: $time$ - time of the event $speed$ - speed of the tap since second $time$ $tL$, $tR$ - the minimum and the maximum $time$ in the subtree of that node $speedR$ - the $speed$ of the event with maximum $time$ in the subtree of that node $res$ - the value of patience after processing all events from the subtree (we assume that the value before $tL$-th second is $0$) $mn$ - what is the minumum value of patience if we process all events from the subtree (also initial value is $0$) links to the left child and to the right child It turns out that this information is enough. Now to make treap work correctly it should be possible to merge two chilrens of some node. Let's look how to do it (suppose that this node has either left child ($LC$) or right child ($RC$)): $time$ doesn't change $speed$ doesn't change $tL = LC.tL$, $tR = RC.tR$, $speedR = RC.speedR$ It is easier to calculate $res$ and $mn$ simulatenously. Look at this block of code: mn = 0, res = 0 mn = min(mn, LC.mn) res += LC.res + LC.speedR * (time - LC.tR) mn = min(mn, res) res += speed * (RC.tL - time) mn = min(mn, res + RC.mn) res += RC.res mn = min(mn, res) It goes through all possible periods of time where $mn$ can be, and finds the best one, during this it calculates $res$. It goes through all possible periods of time where $mn$ can be, and finds the best one, during this it calculates $res$. If there is no left or right child then the calculation doen't change too much. So if you have combine function then you can do insert, delete, split, merge. You can answer queries of the $3$-rd type in the following way. Cut out the needed range from the treap. And go down the treap starting from the root while you can (you go to the left child, if the value of patience becomes equal to $0$ earlier than $time$, you can check that using the imformation stored in nodes, then check the right one if it is needed). So it is left to consider some extreme cases, which I leave you as and exercise, and that is all. The complexity is $O(q \\cdot log(q))$. If you don't like treaps, you can actually use segment tree on pointers, or make coordinate compression and write a simple segment tree, the complexity will stay the same.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\ntypedef long long ll;\\n//mt19937 gen(time(NULL));\\nmt19937 gen(200);\\n\\nstruct node {\\n    pair<int, int> f, s;\\n    node *le, *ri;\\n    ll mn, res;\\n    int tl, tr;\\n    node() {\\n        mn = 228;\\n    }\\n    node(int l, int r) {\\n        tl = l; tr = r;\\n        mn = 228;\\n        if (l == r) return;\\n        le = new node(l, (l+r)/2);\\n        ri = new node((l+r)/2+1, r);\\n    }\\n    node (node* a, node* b) {\\n        le = a; ri = b;\\n        tl = le->tl; tr = ri->tr;\\n        if (le->mn == 228) {\\n            res = ri->res;\\n            mn = ri->mn;\\n            f = ri->f;\\n            s = ri->s;\\n            return;\\n        }\\n        if (ri->mn == 228) {\\n            res = le->res;\\n            mn = le->mn;\\n            f = le->f;\\n            s = le->s;\\n            return;\\n        }\\n        f = le->f; s = ri->s;\\n        ll del = 1ll*le->s.second*(ri->f.first-le->s.first);\\n        res = le->res+del+ri->res;\\n        mn = min(le->mn, le->res+del);\\n        mn = min(mn, ri->mn+le->res+del);\\n    }\\n    void combine() {\\n        node tmp(le, ri);\\n        *this = tmp;\\n    }\\n    void update(int id, int time, int speed) {\\n        if (tl == tr) {\\n            mn = res = 0;\\n            f.first = s.first = time;\\n            f.second = s.second = speed;\\n            return;\\n        }\\n        if (id <= (tl+tr)/2)\\n            le->update(id, time, speed);\\n        else\\n            ri->update(id, time, speed);\\n        combine();\\n    }\\n    void del(int id) {\\n        if (tl == tr) {\\n            mn = 228;\\n            return;\\n        }\\n        if (id <= (tl+tr)/2)\\n            le->del(id);\\n        else\\n            ri->del(id);\\n        combine();\\n    }\\n    node* get_seg(int l, int r) {\\n        if (tr < l || r < tl) return new node();\\n        if (l <= tl && tr <= r) {\\n            return this;;\\n        }\\n        return new node(le->get_seg(l, r), ri->get_seg(l, r));\\n    }\\n    long double simulate(int r, ll v) {\\n        if (mn == 228) return -1;\\n        if (v+mn > 0 && v+res+1ll*s.second*(r-s.first) > 0) return -1;\\n        if (f == s) return s.first-(long double)v/s.second;\\n        if (le->mn == 228) return ri->simulate(r, v);\\n        long double to = le->simulate(le->s.first, v);\\n        if (to != -1) return to;\\n        v += le->res;\\n        ll del = 1ll*le->s.second*((ri->mn==228?r:ri->f.first)-le->s.first);\\n        if (v+del <= 0) return le->s.first-(long double)v/le->s.second;\\n        v += del;\\n        return ri->simulate(r, v);\\n    }\\n    long double query(int l, int r, int rr, ll v) {\\n        node* t = get_seg(l, r);\\n        return t->simulate(rr, v);\\n    }\\n};\\n\\nstruct query{\\n    int time, speed, start;\\n    int l, r, type;\\n    query() {}\\n};\\n\\nvector <int> pos;\\nvector <query> q;\\n\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    #ifdef LOCAL\\n    freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    freopen(\\\"output.txt\\\", \\\"w\\\", stdout);\\n    #endif // LOCAL\\n    cout.precision(7);\\n    int qq; cin >> qq;\\n    q.resize(qq);\\n    for (int i = 0; i < qq; ++i) {\\n        cin >> q[i].type;\\n        if (q[i].type == 1) {\\n            cin >> q[i].time >> q[i].speed;\\n            pos.push_back(q[i].time);\\n        }\\n        if (q[i].type == 2) {\\n            cin >> q[i].time;\\n        }\\n        if (q[i].type == 3) {\\n            cin >> q[i].l >> q[i].r >> q[i].start;\\n        }\\n    }\\n    sort(pos.begin(), pos.end());\\n    pos.erase(unique(pos.begin(), pos.end()), pos.end());\\n    if (pos.size() == 0) pos.push_back(0);\\n    node* t = new node(0, pos.size()-1);\\n    for (int i = 0; i < qq; ++i) {\\n        if (q[i].type == 1) {\\n            int id = lower_bound(pos.begin(), pos.end(), q[i].time)-pos.begin();\\n            t->update(id, q[i].time, q[i].speed);\\n        }\\n        if (q[i].type == 2) {\\n            int id = lower_bound(pos.begin(), pos.end(), q[i].time)-pos.begin();\\n            t->del(id);\\n        }\\n        if (q[i].type == 3) {\\n            int l = lower_bound(pos.begin(), pos.end(), q[i].l)-pos.begin();\\n            int r = --upper_bound(pos.begin(), pos.end(), q[i].r)-pos.begin();\\n            if (q[i].start == 0)\\n                cout << fixed << q[i].l << '\\\\n';\\n            else\\n                cout << fixed << t->query(l, r, q[i].r, q[i].start) << '\\\\n';\\n        }\\n    }\\n    return 0;\\n}\\n\"",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1109",
    "index": "D",
    "title": "Sasha and Interesting Fact from Graph Theory",
    "statement": "Once, during a lesson, Sasha got bored and decided to talk with his friends. Suddenly, he saw Kefa. Since we can talk endlessly about Kefa, we won't even start doing that. The conversation turned to graphs. Kefa promised Sasha to tell him about one interesting fact from graph theory if Sasha helps Kefa to count the number of beautiful trees.\n\nIn this task, a tree is a weighted connected graph, consisting of $n$ vertices and $n-1$ edges, and weights of edges are integers from $1$ to $m$. Kefa determines the beauty of a tree as follows: he finds in the tree his two favorite vertices — vertices with numbers $a$ and $b$, and counts the distance between them. The distance between two vertices $x$ and $y$ is the sum of weights of edges on the simple path from $x$ to $y$. If the distance between two vertices $a$ and $b$ is \\textbf{equal} to $m$, then the tree is beautiful.\n\nSasha likes graph theory, and even more, Sasha likes interesting facts, that's why he agreed to help Kefa. Luckily, Sasha is familiar with you the best programmer in Byteland. Help Sasha to count the number of beautiful trees for Kefa. Two trees are considered to be distinct if there is an edge that occurs in one of them and doesn't occur in the other one. Edge's \\textbf{weight matters}.\n\nKefa warned Sasha, that there can be too many beautiful trees, so it will be enough to count the number modulo $10^9 + 7$.",
    "tutorial": "Let's fix $edges$ - the number of edges on the path between $a$ and $b$. Then on this path there are $edges-1$ vertices between $a$ and $b$, and they can be choosen in $A(n - 2, edges - 1)$ ways. The amount of ways to place numbers on edges in such a way, that their sum is equal to $m$, is $\\binom{m-1}{edges-1}$ (stars and bars method). If an edge doesn't belong to out path, then doesn't metter what number is written on it, so we can multiply answer by $m^{n-edges-1}$. Now, we want to form a forest from remaining $n-edges-1$ vertices and to hang it to any of $edges + 1$ vertexes from our path. According to one of generalizations of Cayley's formula, number of forsests of $x$ vertices, where vertices $1,2, \\ldots, y$ belong to different trees is $f(x, y) = y \\cdot x^{x - y - 1}$. So for fixed $edges$ we got the formula $trees(edges) = A(n - 2, edges - 1) \\cdot f(n, edges + 1) \\cdot \\binom{m - 1}{edges - 1} \\cdot m^{n - edges - 1}$ Complexity is $O((n + m) \\cdot log(mod))$ or $O(n + m)$, in case you precompute all powers, factorials and thier inverse in linear time.",
    "code": "\"import java.io.*;\\nimport java.util.*;\\n\\npublic class Main {\\n\\n    public static void main(String[] args) {\\n        InputReader in = new InputReader(System.in);\\n        OutputWriter out = new OutputWriter(System.out);\\n        TaskC solver = new TaskC(in, out);\\n        solver.solve();\\n        out.close();\\n    }\\n\\n    static class TaskC {\\n\\n        static int n;\\n        static int m;\\n\\n        static int[] inv;\\n        static int[] fact;\\n        static int[] invfact;\\n        \\n        static int[] powN;\\n        static int[] powM;\\n\\n        InputReader in;\\n        OutputWriter out;\\n\\n        TaskC(InputReader in, OutputWriter out) {\\n            this.in = in;\\n            this.out = out;\\n        }\\n        \\n        private void solve() {\\n            n = in.readInt();\\n            m = in.readInt();\\n            precalc();\\n            int ans = 0;\\n            int choosePath = 1;\\n            for(int k = 1; k < n; ++k) {\\n                if (k > m) break;\\n                int cur = MathUtil.mul(choosePath, cayley(n, k + 1));\\n                cur = MathUtil.mul(cur, binom(m - 1, k - 1));\\n                cur = MathUtil.mul(cur, powM[n - k - 1]);\\n                choosePath = MathUtil.mul(choosePath, n - k - 1);\\n                ans = MathUtil.sum(ans, cur);\\n            }\\n            out.print(ans);\\n        }\\n\\n        private int cayley(int n, int k) {\\n            if (n - k - 1 < 0) {\\n                return MathUtil.mul(k, MathUtil.binPow(n, MathUtil.mod - 2));\\n            }\\n            return MathUtil.mul(k, powN[n - k - 1]);\\n        }\\n\\n        private int binom(int n, int k) {\\n            return MathUtil.mul(fact[n], MathUtil.mul(invfact[k], invfact[n - k]));\\n        }\\n\\n        private void precalc() {\\n            powN = new int[n + 1];\\n            powM = new int[n + 1];\\n            powN[0] = 1;\\n            powM[0] = 1;\\n            for(int i = 1; i <= n; ++i) {\\n                powN[i] = MathUtil.mul(powN[i - 1], n);\\n                powM[i] = MathUtil.mul(powM[i - 1], m);\\n            }\\n            \\n            inv = new int[m + 1];\\n            fact = new int[m + 1];\\n            invfact = new int[m + 1];\\n            inv[0] = inv[1] = 1;\\n            fact[0] = fact[1] = 1;\\n            invfact[0] = invfact[1] = 1;\\n            for(int i = 2; i <= m; ++i) {\\n                inv[i] = MathUtil.mul(inv[MathUtil.mod % i], MathUtil.mod - MathUtil.mod / i);\\n                fact[i] = MathUtil.mul(fact[i - 1], i);\\n                invfact[i] = MathUtil.mul(invfact[i - 1], inv[i]);\\n            }\\n        }\\n    }\\n    static class MathUtil {\\n        private static final int mod = 1_000_000_007;\\n\\n        static int binPow(int a, int n) {\\n            int result = 1;\\n            while (n > 0) {\\n                if (n % 2 == 1) {\\n                    result = mul(result, a);\\n                }\\n                n /= 2;\\n                a = mul(a, a);\\n            }\\n            return result;\\n        }\\n        \\n        static int mul(int a, int b) {\\n            return (int)((long)a * b % mod);\\n        }\\n\\n        static int sum(int a, int b) {\\n            int result = a + b;\\n            if (result >= mod) result -= mod;\\n            return result;\\n        }\\n\\n    }\\n\\n    static class OutputWriter {\\n        private final PrintWriter writer;\\n\\n        public OutputWriter(OutputStream outputStream) {\\n            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\\n        }\\n\\n        public OutputWriter(Writer writer) {\\n            this.writer = new PrintWriter(writer);\\n        }\\n\\n        public void print(Object... objects) {\\n            for (int i = 0; i < objects.length; i++) {\\n                if (i != 0) {\\n                    writer.print(' ');\\n                }\\n                writer.print(objects[i]);\\n            }\\n            writer.println();\\n        }\\n\\n        public void close() {\\n            writer.close();\\n        }\\n\\n    }\\n\\n    static class InputReader {\\n        private InputStream stream;\\n        private byte[] buf = new byte[1024];\\n        private int curChar;\\n        private int numChars;\\n        private InputReader.SpaceCharFilter filter;\\n\\n        public InputReader(InputStream stream) {\\n            this.stream = stream;\\n        }\\n\\n        public int read() {\\n            if (numChars == -1) {\\n                throw new InputMismatchException();\\n            }\\n            if (curChar >= numChars) {\\n                curChar = 0;\\n                try {\\n                    numChars = stream.read(buf);\\n                } catch (IOException e) {\\n                    throw new InputMismatchException();\\n                }\\n                if (numChars <= 0) {\\n                    return -1;\\n                }\\n            }\\n            return buf[curChar++];\\n        }\\n\\n        public int readInt() {\\n            int c = read();\\n            while (isSpaceChar(c)) {\\n                c = read();\\n            }\\n            int sgn = 1;\\n            if (c == '-') {\\n                sgn = -1;\\n                c = read();\\n            }\\n            int res = 0;\\n            do {\\n                if (c < '0' || c > '9') {\\n                    throw new InputMismatchException();\\n                }\\n                res *= 10;\\n                res += c - '0';\\n                c = read();\\n            } while (!isSpaceChar(c));\\n            return res * sgn;\\n        }\\n\\n        public boolean isSpaceChar(int c) {\\n            if (filter != null) {\\n                return filter.isSpaceChar(c);\\n            }\\n            return isWhitespace(c);\\n        }\\n\\n        public static boolean isWhitespace(int c) {\\n            return c == ' ' || c == '\\\\n' || c == '\\\\r' || c == '\\\\t' || c == -1;\\n        }\\n\\n        public double readDouble() {\\n            int c = read();\\n            while (isSpaceChar(c)) {\\n                c = read();\\n            }\\n            int sgn = 1;\\n            if (c == '-') {\\n                sgn = -1;\\n                c = read();\\n            }\\n            double res = 0;\\n            while (!isSpaceChar(c) && c != '.') {\\n                if (c == 'e' || c == 'E') {\\n                    return res * Math.pow(10, readInt());\\n                }\\n                if (c < '0' || c > '9') {\\n                    throw new InputMismatchException();\\n                }\\n                res *= 10;\\n                res += c - '0';\\n                c = read();\\n            }\\n            if (c == '.') {\\n                c = read();\\n                double m = 1;\\n                while (!isSpaceChar(c)) {\\n                    if (c == 'e' || c == 'E') {\\n                        return res * Math.pow(10, readInt());\\n                    }\\n                    if (c < '0' || c > '9') {\\n                        throw new InputMismatchException();\\n                    }\\n                    m /= 10;\\n                    res += (c - '0') * m;\\n                    c = read();\\n                }\\n            }\\n            return res * sgn;\\n        }\\n\\n        public interface SpaceCharFilter {\\n            public boolean isSpaceChar(int ch);\\n        }\\n\\n    }\\n}\\n\"",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1109",
    "index": "E",
    "title": "Sasha and a Very Easy Test",
    "statement": "Egor likes math, and not so long ago he got the highest degree of recognition in the math community — Egor became a red mathematician. In this regard, Sasha decided to congratulate Egor and give him a math test as a present. This test contains an array $a$ of integers of length $n$ and exactly $q$ queries. Queries were of three types:\n\n- \"1 l r x\" — multiply each number on the range from $l$ to $r$ by $x$.\n- \"2 p x\" — divide the number at the position $p$ by $x$ (divisibility guaranteed).\n- \"3 l r\" — find the sum of all elements on the range from $l$ to $r$.\n\nThe sum can be big, so Sasha asked Egor to calculate the sum modulo some integer $mod$.\n\nBut since Egor is a red mathematician, he doesn't have enough time to solve such easy tasks, at the same time he doesn't want to anger Sasha, that's why he asked you to help and to find answers for all queries of the $3$-rd type.",
    "tutorial": "The main idea: Let's factorize $x$ in every query of the $1$-st and the $2$-nd type. Now $x$ can be presented as $p_1^{\\alpha_1} \\cdot p_2^{\\alpha_2} \\cdot \\ldots \\cdot p_k^{\\alpha_k}$, where $p_i$ is a prime divisor of $x$. Then let's split $p_i$ into two sets: those which are divisors of $mod$ and those which are not and process them in different ways. It's easy to see that all primes from the second set are coprime with $mod$. According to Euler's theorem for each coprime with $mod$ there is a modular multiplicative inverse. So you can just build a segment tree with lazy propagation to multiply and divide modulo $mod$. What to do with primes from the first set? Notice, that there are at most $9$ (because $2 \\cdot 3 \\cdot 5 \\cdot 7 \\cdot 11 \\cdot 13 \\cdot 17 \\cdot 19 \\cdot 23 \\cdot 29 > 10^9$; let's call such function $DiffPrimes(x)$ to use later) different prime divisors of $mod$. So let's maintain a vector in each node of segment tree, which contains pairs ($p, \\alpha$), what means that $\\alpha$ is such power of $p$, that each number from the corresponding range should be multiplied by $p^{\\alpha}$. So also use lazy propogation to multiply and divide by those primes. Now how to answer queries of the $3$-rd type? Just maintain in each node some auxiliary numbers: sumUnder - the sum from childs mulSecond - equal to the product of primes from the second set, means that each number from the range should be multiplied by mulSecond powersFirst - vector, which contains pairs ($p, \\alpha$), also means that each mumber from the range should me multiplied by $p^{\\alpha}$ And it is obvious that the sum on the range which is controled by some node is $sumUnder \\cdot mulSecond \\cdot p_i^{\\alpha_i}$. How to write combine function for two nodes from segment tree and push to push modification to children I leave you as an exercise, there is nothing diffcult here. Now combine ideas from the above, and got the complexity $O((n + q) \\cdot log_2(n) \\cdot log_2(q) \\cdot DiffPrimes(10^5))$ (because $x$ in queries doesn't exceed $10^5$). To remove a $log_2(q)$ we can precompute all powers of each prime divisors of $mod$, so we will have no need to use binary exponentiation algorithm in segment tree. But here you have to be careful, because since we have $q$ queries and each of them can increase power of prime by $log_2(10^5)$ in the worst case, so maximal power of prime can be $q \\cdot log_2(10^5)$. The complexity is $O((n + q) \\cdot log_2(n) \\cdot DiffPrimes(10^5))$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\nint phi(int n) {\\n\\tint res = n;\\n\\tfor (int i = 2; i*i <= n; ++i)\\n\\t\\tif (n % i == 0) {\\n\\t\\t\\twhile (n % i == 0)\\n\\t\\t\\t\\tn /= i;\\n\\t\\t\\tres -= res / i;\\n\\t\\t}\\n\\tif (n > 1)\\n\\t\\tres -= res / n;\\n\\treturn res;\\n}\\n\\nvector <int> factorize(int x) {\\n    vector <int> res;\\n    for (int i = 2; i*i <= x; ++i) {\\n        if (x%i == 0) {\\n            res.push_back(i);\\n        }\\n        while (x%i == 0) {\\n            x /= i;\\n        }\\n    }\\n    if (x > 1) res.push_back(x);\\n    return res;\\n}\\n\\n#define fmod i_love_pelmeny\\n\\nint mod;\\nvector <int> fmod;\\nconst int N = (int)2e5+10;\\nvector <pair <int, int> > f[N];\\nvector <int> pw[25];\\n//vector <int> realpw[25];\\nint goodpart[N];\\nint inv[N];\\nint n, a[N];\\nint id[N];\\n\\nint binpow(int a, int b) {\\n    int res = 1;\\n    while (b > 0) {\\n        if (b&1) res = 1ll*res*a%mod;\\n        b >>= 1;\\n        a = 1ll*a*a%mod;\\n    }\\n    return res;\\n}\\n\\nstruct node {\\n    vector <int> degrees;\\n    int tl, tr;\\n    int sum, here;\\n    bool flag = false;\\n    node *le, *ri;\\n\\n    int calc_real_sum() {\\n//        if (!flag) return sum;\\n        int res = here;\\n        for (int i = 0; i < degrees.size(); ++i) {\\n            res = 1ll*res*pw[i][degrees[i]]%mod;\\n        }\\n        return res;\\n    }\\n    void push_down() {\\n        if (!flag) return;\\n        int i = 0;\\n        for (auto & x : degrees) {\\n            le->degrees[i] += x;\\n            ri->degrees[i] += x;\\n\\n            le->sum = 1ll*le->sum*pw[i][x]%mod;\\n            ri->sum = 1ll*ri->sum*pw[i][x]%mod;\\n\\n            x = 0;\\n            ++i;\\n        }\\n        le->here = 1ll*le->here*here%mod;\\n        le->sum = 1ll*le->sum*here%mod;\\n        ri->here = 1ll*ri->here*here%mod;\\n        ri->sum = 1ll*ri->sum*here%mod;\\n        here = 1;\\n        flag = false;\\n        le->flag = ri->flag = true;\\n    }\\n    void combine() {\\n        sum = (le->sum+ri->sum)%mod;\\n    }\\n\\n    void multiply(int l, int r, int x) {\\n        if (r < tl || tr < l) return;\\n        if (l <= tl && tr <= r) {\\n            flag = true;\\n            for (auto p : f[x]) {\\n                degrees[id[p.first]-1] += p.second;\\n            }\\n            here = 1ll*here*goodpart[x]%mod;\\n            sum = 1ll*sum*x%mod;\\n            return;\\n        }\\n        push_down();\\n        le->multiply(l, r, x);\\n        ri->multiply(l, r, x);\\n        combine();\\n    }\\n    void divide(int pos, int x) {\\n        if (tl == tr) {\\n            for (auto p : f[x]) {\\n                degrees[id[p.first]-1] -= p.second;\\n            }\\n            here = 1ll*here*inv[goodpart[x]]%mod;\\n            sum = calc_real_sum();\\n            return;\\n        }\\n        push_down();\\n        if (pos <= (tl+tr)/2) {\\n            le->divide(pos, x);\\n        } else {\\n            ri->divide(pos, x);\\n        }\\n        combine();\\n    }\\n    int get(int l, int r) {\\n        if (r < tl || tr < l) {\\n            return 0;\\n        }\\n        if (l <= tl && tr <= r) {\\n            return sum;\\n        }\\n        push_down();\\n        return (le->get(l, r)+ri->get(l, r))%mod;\\n    }\\n    node(int l, int r, int dsize) {\\n        tl = l;\\n        tr = r;\\n        sum = 1;\\n        here = 1;\\n        degrees.resize(dsize);\\n        if (l == r) {\\n            multiply(l, r, a[l]);\\n            return;\\n        }\\n        le = new node(l, (l+r)/2, dsize);\\n        ri = new node((l+r)/2+1, r, dsize);\\n        combine();\\n    }\\n};\\n\\nstruct query {\\n    int x, l, r, t;\\n    query() {}\\n};\\n\\nnode *t;\\nvector <query> q;\\n\\nvoid precalc_base() {\\n    fmod = factorize(mod);\\n    if (fmod.back() >= N) fmod.pop_back();\\n    vector <int> deg(N);\\n    for (int i = 0; i < fmod.size(); ++i) {\\n        id[fmod[i]] = i+1;\\n        for (int j = fmod[i]; j < N; j += fmod[i]) {\\n            if ((j/fmod[i])%fmod[i]) {\\n                deg[j] = 1;\\n            } else {\\n                deg[j] = deg[j/fmod[i]]+1;\\n            }\\n            f[j].emplace_back(fmod[i], deg[j]);\\n        }\\n    }\\n\\n    for (int i = 1; i < N; ++i) {\\n        goodpart[i] = i;\\n        goodpart[i] = goodpart[i/__gcd(i, mod)];\\n    }\\n}\\nvoid precalc_inverse() {\\n    vector <int> mn(N);\\n    for (int i = 2; i < N; ++i) {\\n        if (mn[i]) continue;\\n        for (int j = i+i; j < N; j += i) {\\n            if (!mn[j]) mn[j] = i;\\n        }\\n    }\\n\\n    int mod_phi = phi(mod);\\n    inv[1] = 1;\\n    for (int i = 2; i < N; ++i) {\\n        if (!mn[i]) inv[i] = binpow(i, mod_phi-1);\\n        else inv[i] = 1ll*inv[i/mn[i]]*inv[mn[i]]%mod;\\n    }\\n}\\nvoid precalc_powers() {\\n    vector <int> max_entry(fmod.size());\\n    for (int i = 1; i <= n; ++i) {\\n        for (auto p : f[a[i]]) {\\n            max_entry[id[p.first]-1] += p.second;\\n        }\\n    }\\n\\n    for (const auto& w : q) {\\n        if (w.t != 1) continue;\\n        for (auto p : f[w.x]) {\\n            max_entry[id[p.first]-1] += p.second;\\n        }\\n    }\\n\\n    for (int i = 0; i < fmod.size(); ++i) {\\n        pw[i].resize(max_entry[i]+1);\\n        pw[i][0] = 1;\\n        for (int j = 1; j < pw[i].size(); ++j) {\\n            pw[i][j] = 1ll*pw[i][j-1]*fmod[i]%mod;\\n        }\\n    }\\n\\n}\\nvoid precalc() {\\n    precalc_base();\\n    precalc_inverse();\\n    precalc_powers();\\n    t = new node(1, n, fmod.size());\\n    cerr << 1.0*clock()/CLOCKS_PER_SEC << endl;\\n}\\n\\nint main() {\\n//    ios_base::sync_with_stdio(0);\\n    #ifdef LOCAL\\n    freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    freopen(\\\"output.txt\\\", \\\"w\\\", stdout);\\n    #endif // LOCAL\\n    scanf(\\\"%d%d\\\", &n, &mod);\\n    for (int i = 1; i <= n; ++i) {\\n        scanf(\\\"%d\\\", &a[i]);\\n    }\\n    int m; scanf(\\\"%d\\\", &m);\\n    q.resize(m);\\n    for (int i = 0; i < m; ++i) {\\n        scanf(\\\"%d\\\", &q[i].t);\\n        scanf(\\\"%d\\\", &q[i].l);\\n        if (q[i].t != 2)\\n            scanf(\\\"%d\\\", &q[i].r);\\n        if (q[i].t != 3)\\n            scanf(\\\"%d\\\", &q[i].x);\\n    }\\n    precalc();\\n    for (const auto& p : q) {\\n        if (p.t == 1) {\\n            t->multiply(p.l, p.r, p.x);\\n        }\\n        if (p.t == 2) {\\n            t->divide(p.l, p.x);\\n        }\\n        if (p.t == 3) {\\n            printf(\\\"%d\\\\n\\\", t->get(p.l, p.r));\\n        }\\n    }\\n\\n}\\n\"",
    "tags": [
      "data structures",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1109",
    "index": "F",
    "title": "Sasha and Algorithm of Silence's Sounds",
    "statement": "One fine day Sasha went to the park for a walk. In the park, he saw that his favorite bench is occupied, and he had to sit down on the neighboring one. He sat down and began to listen to the silence. Suddenly, he got a question: what if in different parts of the park, the silence sounds in different ways? So it was. Let's divide the park into $1 \\times 1$ meter squares and call them cells, and numerate rows from $1$ to $n$ from up to down, and columns from $1$ to $m$ from left to right. And now, every cell can be described with a pair of two integers $(x, y)$, where $x$ — the number of the row, and $y$ — the number of the column. Sasha knows that the level of silence in the cell $(i, j)$ equals to $f_{i,j}$, and all $f_{i,j}$ form a permutation of numbers from $1$ to $n \\cdot m$. Sasha decided to count, how many are there pleasant segments of silence?\n\nLet's take some segment $[l \\ldots r]$. Denote $S$ as the set of cells $(i, j)$ that $l \\le f_{i,j} \\le r$. Then, the segment of silence $[l \\ldots r]$ is pleasant if there is only \\textbf{one simple} path between every pair of cells from $S$ (path can't contain cells, which are not in $S$). In other words, set $S$ should look like a tree on a plain. Sasha has done this task pretty quickly, and called the algorithm — \"algorithm of silence's sounds\".\n\nTime passed, and the only thing left from the algorithm is a legend. To prove the truthfulness of this story, you have to help Sasha and to find the number of \\textbf{different} pleasant segments of silence. Two segments $[l_1 \\ldots r_1]$, $[l_2 \\ldots r_2]$ are different, if $l_1 \\neq l_2$ or $r_1 \\neq r_2$ or both at the same time.",
    "tutorial": "A range $[l \\ldots r]$ - a tree, if the graph formated by it doen't have any cycle and there is only one connected component in this graph. Let's $t_r$ be such minimal position, that $[t_r \\ldots r]$ doen't contain cycles (forest). It is obvous that $t_r \\leq t_{r+1}$. Suppose for each $r$ we find $t_r$. Then the task now is to count the number of such $t_r \\leq l \\leq r$ that graph formated by the range $[l \\ldots r]$ consists of one connected component. How to find $t_r$ for each $r$. Let's move two pointers: $t_r$ and $r$. For each moment we store a graph formated by that range. If you add $1$ to one of the pointers then you should add/delete up to $4$ edges to the graph. Before adding an edge check whether two verticies are in different components (not to form a cycle), and if they are in one component, then it is needed to delete some edges - move the first pointer. So now we need some structure that can process $3$ types of queries online: add an edge, delete an edge, check if two verticies are in one connected component. As long as the graph will never have a cycle, so it is possible to answer queries using link-cut tree ($O(log(n \\cdot m))$ for one query). It is left to count the number of suitable $l$ ($t_r \\leq l \\leq r$) for each $r$. Let's iterate $r$ from $1$ to $n \\cdot m$ and maintain $cmp_i$ - the number of connected components for $[i \\ldots r]$. Then for a fixed $r$ you should add to the answer the number of such $i$ that $t_r \\leq i \\leq r$ and $cmp_i = 1$. What is going on when we move $r$ and add some edge at that moment. Let's that edge be $(x, r+1)$ and $t_r \\leq x$ (if $x < t_r$ then you can skip this edge). For $i$, for which $x \\lneq i \\leq r$, $cmp_i$ won't change after you add an edge, but for $t_r \\leq i \\leq x$ two trees merge in one - $cmp_i$ decreases by $1$. Let's have a segtree to store $cmp_i$, then decreasing by $1$ is equivalent to adding $-1$ on a range, and the number of $1$ on a range is the number of minimums. All such queries can be done in $O(log(n \\cdot m))$. The total complexity is $O(n \\cdot m \\cdot log(n \\cdot m))$.",
    "code": "\"import java.io.*;\\nimport java.util.*;\\n\\npublic class Main {\\n\\n    public static void main(String[] args) {\\n        InputReader in = new InputReader(System.in);\\n        OutputWriter out = new OutputWriter(System.out);\\n        TaskD solver = new TaskD(in, out);\\n        solver.solve();\\n        out.close();\\n    }\\n\\n    static class TaskD {\\n        static private final int[] dx = {1, -1, 0, 0};\\n        static private final int[] dy = {0, 0, 1, -1};\\n\\n        static int n, m;\\n        static int total;\\n\\n        static int[][] f;\\n        static int[] posX;\\n        static int[] posY;\\n        static int[] leftBound;\\n\\n        List<Integer>[] edges;\\n        LinkCutTree lct;\\n        InputReader in;\\n        OutputWriter out;\\n\\n        TaskD(InputReader in, OutputWriter out) {\\n            this.in = in;\\n            this.out = out;\\n        }\\n\\n        private void solve() {\\n            n = in.readInt();\\n            m = in.readInt();\\n            total = n * m;\\n            f = new int[n][m];\\n            posX = new int[total];\\n            posY = new int[total];\\n            for(int i = 0; i < n; ++i) {\\n                for(int j = 0; j < m; ++j) {\\n                    f[i][j] = in.readInt() - 1;\\n                    posX[f[i][j]] = i;\\n                    posY[f[i][j]] = j;\\n                }\\n            }\\n            edges = new ArrayList[total];\\n            leftBound = new int[total];\\n            lct = new LinkCutTree(total);\\n            for(int i = 0; i < total; ++i) {\\n                edges[i] = new ArrayList<>();\\n            }\\n            for(int l = 0, r = 0; r < total; ++r) {\\n               l = addCell(l, r);\\n               leftBound[r] = l;\\n            }\\n            long ans = 0;\\n            SegmentTree t = new SegmentTree(total + 4);\\n            for(int r = 0; r < total; ++r) {\\n                int x = posX[r];\\n                int y = posY[r];\\n                List<Integer> seg = new ArrayList<>();\\n                for(int i = 0; i < 4; ++i) {\\n                    int px = x + dx[i];\\n                    int py = y + dy[i];\\n                    if (px < 0 || px >= n) continue;\\n                    if (py < 0 || py >= m) continue;\\n                    int to = f[px][py];\\n                    if (to > r) continue;\\n                    seg.add(to);\\n                }\\n                seg.add(-1);\\n                seg.add(r);\\n                Collections.sort(seg);\\n                for(int i = seg.size() - 1, comp = 1; i > 0; --i) {\\n                    if (seg.get(i - 1) + 1 > seg.get(i)) {\\n                        --comp;\\n                        continue;\\n                    }\\n                    t.inc(seg.get(i - 1) + 1, seg.get(i) + 1, comp);\\n                    --comp;\\n                }\\n                ans += t.query(leftBound[r], r + 1);\\n            }\\n            out.print(ans);\\n        }\\n\\n        private int addCell(int l, int r) {\\n            int x = posX[r];\\n            int y = posY[r];\\n            for(int i = 0; i < 4; ++i) {\\n                int px = x + dx[i];\\n                int py = y + dy[i];\\n                if (px < 0 || px >= n) continue;\\n                if (py < 0 || py >= m) continue;\\n                int to = f[px][py];\\n                while (l <= to && to <= r) {\\n                    if (lct.link(to, r)) {\\n                        edges[to].add(r);\\n                        break;\\n                    }\\n                    removeCell(l);\\n                    ++l;\\n                }\\n            }\\n            return l;\\n        }\\n\\n        private void removeCell(int c) {\\n            for(int to : edges[c]) {\\n                lct.cut(c, to);\\n            }\\n            edges[c].clear();\\n        }\\n    }\\n\\n    static class SegmentTree {\\n        int size;\\n        int height;\\n        int[] t;\\n        int[] cnt;\\n        int[] push;\\n\\n        SegmentTree(int n) {\\n            this.size = n;\\n            this.height = 0;\\n            int temp = n;\\n            while (temp > 0) {\\n                temp >>= 1;\\n                ++this.height;\\n            }\\n            t = new int[n << 1];\\n            cnt = new int[n << 1];\\n            push = new int[n];\\n            for(int i = 0; i < n; ++i) {\\n                cnt[i + n] = 1;\\n            }\\n            for(int i = n - 1; i >= 0; --i) {\\n                cnt[i] = cnt[i << 1] + cnt[i << 1 | 1];\\n            }\\n        }\\n\\n        private void apply(int p, int value) {\\n            t[p] += value;\\n            if (p < size) push[p] += value;\\n        }\\n\\n        private void recalc(int p) {\\n            while (p > 1) {\\n                p >>= 1;\\n                t[p] = Math.min(t[p << 1], t[p << 1 | 1]) + push[p];\\n                cnt[p] = (t[p] == t[p << 1] + push[p] ? cnt[p << 1] : 0)\\n                        + (t[p] == t[p << 1 | 1] + push[p] ? cnt[p << 1 | 1] : 0);\\n            }\\n        }\\n\\n        private void push(int p) {\\n            for (int s = height; s > 0; s--) {\\n                int i = p >> s;\\n                if (push[i] != 0) {\\n                    apply(i << 1, push[i]);\\n                    apply(i << 1 | 1, push[i]);\\n                    push[i] = 0;\\n                }\\n            }\\n        }\\n\\n        private void inc(int l, int r, int value) {\\n            l += size;\\n            r += size;\\n            int l0 = l;\\n            int r0 = r;\\n            for (; l < r; l >>= 1, r >>= 1) {\\n                if ((l & 1) != 0) apply(l++, value);\\n                if ((r & 1) != 0) apply(--r, value);\\n            }\\n            recalc(l0);\\n            recalc(r0 - 1);\\n        }\\n\\n        private int query(int l, int r) {\\n            l += size;\\n            r += size;\\n            push(l);\\n            push(r - 1);\\n            int min = Integer.MAX_VALUE;\\n            int minCount = 0;\\n            for (; l < r; l >>= 1, r >>= 1) {\\n                if ((l & 1) != 0) {\\n                    if (min > t[l]) {\\n                        min = t[l];\\n                        minCount = cnt[l];\\n                    } else if (min == t[l]) {\\n                        minCount += cnt[l];\\n                    }\\n                    ++l;\\n                }\\n                if ((r & 1) != 0) {\\n                    --r;\\n                    if (min > t[r]) {\\n                        min = t[r];\\n                        minCount = cnt[r];\\n                    } else if (min == t[r]) {\\n                        minCount += cnt[r];\\n                    }\\n                }\\n            }\\n            return minCount;\\n        }\\n    }\\n\\n    static class LinkCutTree {\\n\\n        private static class Node {\\n            Node left;\\n            Node right;\\n            Node parent;\\n            boolean revert;\\n\\n            boolean isRoot() {\\n                return parent == null || (parent.left != this && parent.right != this);\\n            }\\n\\n            void push() {\\n                if (revert) {\\n                    revert = false;\\n                    Node t = left;\\n                    left = right;\\n                    right = t;\\n                    if (left != null)   left.revert = !left.revert;\\n                    if (right != null)  right.revert = !right.revert;\\n                }\\n            }\\n        }\\n\\n        static int size;\\n        Node[] nodes;\\n\\n        LinkCutTree(int n) {\\n            LinkCutTree.size = n;\\n            nodes = new Node[n];\\n            for(int i = 0; i < n; ++i) {\\n                nodes[i] = new Node();\\n            }\\n        }\\n\\n        private boolean link(int x, int y) {\\n            return link(nodes[x], nodes[y]);\\n        }\\n\\n        private void cut(int x, int y) {\\n            cut(nodes[x], nodes[y]);\\n        }\\n\\n        private static boolean link(Node x, Node y) {\\n            if (connected(x, y))\\n                return false;\\n            makeRoot(x);\\n            x.parent = y;\\n            return true;\\n        }\\n\\n        private static void cut(Node x, Node y) {\\n            makeRoot(x);\\n            expose(y);\\n            if (y.right != x || x.left != null || x.right != null) {\\n                throw new RuntimeException(\\\"error: no edge (x,y)\\\");\\n            }\\n            y.right.parent = null;\\n            y.right = null;\\n        }\\n\\n        static void connect(Node ch, Node p, Boolean isLeftChild) {\\n            if (ch != null)\\n                ch.parent = p;\\n            if (isLeftChild != null) {\\n                if (isLeftChild)\\n                    p.left = ch;\\n                else\\n                    p.right = ch;\\n            }\\n        }\\n\\n        static void rotate(Node x) {\\n            Node p = x.parent;\\n            Node g = p.parent;\\n            boolean isRootP = p.isRoot();\\n            boolean leftChildX = (x == p.left);\\n            connect(leftChildX ? x.right : x.left, p, leftChildX);\\n            connect(p, x, !leftChildX);\\n            connect(x, g, !isRootP ? p == g.left : null);\\n        }\\n\\n        static void splay(Node x) {\\n            while (!x.isRoot()) {\\n                Node p = x.parent;\\n                Node g = p.parent;\\n                if (!p.isRoot())\\n                    g.push();\\n                p.push();\\n                x.push();\\n                if (!p.isRoot())\\n                    rotate((x == p.left) == (p == g.left) ? p/*zig-zig*/ : x/*zig-zag*/);\\n                rotate(x);\\n            }\\n            x.push();\\n        }\\n\\n        // makes node x the root of the virtual tree, and also x becomes the leftmost node in its splay tree\\n        static Node expose(Node x) {\\n            Node last = null;\\n            for (Node y = x; y != null; y = y.parent) {\\n                splay(y);\\n                y.left = last;\\n                last = y;\\n            }\\n            splay(x);\\n            return last;\\n        }\\n\\n        private static void makeRoot(Node x) {\\n            expose(x);\\n            x.revert = !x.revert;\\n        }\\n\\n        private static boolean connected(Node x, Node y) {\\n            if (x == y)\\n                return true;\\n            expose(x);\\n            expose(y);\\n            return x.parent != null;\\n        }\\n    }\\n\\n    static class OutputWriter {\\n        private final PrintWriter writer;\\n\\n        public OutputWriter(OutputStream outputStream) {\\n            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\\n        }\\n\\n        public OutputWriter(Writer writer) {\\n            this.writer = new PrintWriter(writer);\\n        }\\n\\n        public void print(Object... objects) {\\n            for (int i = 0; i < objects.length; i++) {\\n                if (i != 0) {\\n                    writer.print(' ');\\n                }\\n                writer.print(objects[i]);\\n            }\\n            writer.println();\\n        }\\n\\n        public void close() {\\n            writer.close();\\n        }\\n\\n    }\\n\\n    static class InputReader {\\n        private InputStream stream;\\n        private byte[] buf = new byte[1024];\\n        private int curChar;\\n        private int numChars;\\n        private InputReader.SpaceCharFilter filter;\\n\\n        public InputReader(InputStream stream) {\\n            this.stream = stream;\\n        }\\n\\n        public int read() {\\n            if (numChars == -1) {\\n                throw new InputMismatchException();\\n            }\\n            if (curChar >= numChars) {\\n                curChar = 0;\\n                try {\\n                    numChars = stream.read(buf);\\n                } catch (IOException e) {\\n                    throw new InputMismatchException();\\n                }\\n                if (numChars <= 0) {\\n                    return -1;\\n                }\\n            }\\n            return buf[curChar++];\\n        }\\n\\n        public int readInt() {\\n            int c = read();\\n            while (isSpaceChar(c)) {\\n                c = read();\\n            }\\n            int sgn = 1;\\n            if (c == '-') {\\n                sgn = -1;\\n                c = read();\\n            }\\n            int res = 0;\\n            do {\\n                if (c < '0' || c > '9') {\\n                    throw new InputMismatchException();\\n                }\\n                res *= 10;\\n                res += c - '0';\\n                c = read();\\n            } while (!isSpaceChar(c));\\n            return res * sgn;\\n        }\\n\\n        public boolean isSpaceChar(int c) {\\n            if (filter != null) {\\n                return filter.isSpaceChar(c);\\n            }\\n            return isWhitespace(c);\\n        }\\n\\n        public static boolean isWhitespace(int c) {\\n            return c == ' ' || c == '\\\\n' || c == '\\\\r' || c == '\\\\t' || c == -1;\\n        }\\n\\n        public double readDouble() {\\n            int c = read();\\n            while (isSpaceChar(c)) {\\n                c = read();\\n            }\\n            int sgn = 1;\\n            if (c == '-') {\\n                sgn = -1;\\n                c = read();\\n            }\\n            double res = 0;\\n            while (!isSpaceChar(c) && c != '.') {\\n                if (c == 'e' || c == 'E') {\\n                    return res * Math.pow(10, readInt());\\n                }\\n                if (c < '0' || c > '9') {\\n                    throw new InputMismatchException();\\n                }\\n                res *= 10;\\n                res += c - '0';\\n                c = read();\\n            }\\n            if (c == '.') {\\n                c = read();\\n                double m = 1;\\n                while (!isSpaceChar(c)) {\\n                    if (c == 'e' || c == 'E') {\\n                        return res * Math.pow(10, readInt());\\n                    }\\n                    if (c < '0' || c > '9') {\\n                        throw new InputMismatchException();\\n                    }\\n                    m /= 10;\\n                    res += (c - '0') * m;\\n                    c = read();\\n                }\\n            }\\n            return res * sgn;\\n        }\\n\\n        public interface SpaceCharFilter {\\n            public boolean isSpaceChar(int ch);\\n        }\\n\\n    }\\n}\"",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1110",
    "index": "A",
    "title": "Parity",
    "statement": "You are given an integer $n$ ($n \\ge 0$) represented with $k$ digits in base (radix) $b$. So,\n\n$$n = a_1 \\cdot b^{k-1} + a_2 \\cdot b^{k-2} + \\ldots a_{k-1} \\cdot b + a_k.$$\n\nFor example, if $b=17, k=3$ and $a=[11, 15, 7]$ then $n=11\\cdot17^2+15\\cdot17+7=3179+255+7=3441$.\n\nDetermine whether $n$ is even or odd.",
    "tutorial": "If $b$ is even, then only the last digit matters. Otherwise $b^k$ is odd for any $k$, so each digit is multiplied by odd number. A sum of several summands is even if and only if the number of odd summands is even. So we should just compute the number of even digits.",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1110",
    "index": "B",
    "title": "Tape",
    "statement": "You have a long stick, consisting of $m$ segments enumerated from $1$ to $m$. Each segment is $1$ centimeter long. Sadly, some segments are broken and need to be repaired.\n\nYou have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $t$ placed at some position $s$ will cover segments $s, s+1, \\ldots, s+t-1$.\n\nYou are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.\n\nTime is money, so you want to cut at most $k$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?",
    "tutorial": "Let's start with $n$ pieces of length $1$ covering only broken segments and then decrease the number of pieces used. After reducing the number of segments by $x$, some $x$ of long uncovered initial segments of unbroken places will be covered. It's easy to see that you should cover the shortest $x$ segments. Thus, to make at most $k$ segments, you should cover $n - k$ shortest initial segments. You can find their total length using sort.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1110",
    "index": "C",
    "title": "Meaningless Operations",
    "statement": "Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.\n\nSuppose you are given a positive integer $a$. You want to choose some integer $b$ from $1$ to $a - 1$ inclusive in such a way that the greatest common divisor (GCD) of integers $a \\oplus b$ and $a \\> \\& \\> b$ is as large as possible. In other words, you'd like to compute the following function:\n\n$$f(a) = \\max_{0 < b < a}{gcd(a \\oplus b, a \\> \\& \\> b)}.$$\n\nHere $\\oplus$ denotes the bitwise XOR operation, and $\\&$ denotes the bitwise AND operation.\n\nThe greatest common divisor of two integers $x$ and $y$ is the largest integer $g$ such that both $x$ and $y$ are divided by $g$ without remainder.\n\nYou are given $q$ integers $a_1, a_2, \\ldots, a_q$. For each of these integers compute the largest possible value of the greatest common divisor (when $b$ is chosen optimally).",
    "tutorial": "Denote the highest bit of $a$ as $x$ (that is largest number $x$, such that $2^x \\le a$) and consider $b = (2^x - 1) \\> \\oplus a$. It's easy to see that if $a \\neq 2^x - 1$ then $0 < b < a$ holds. In this, $gcd$ is maximum possible, because $a \\> \\& b = 0$ and $gcd(2 ^ x - 1, 0) = 2^x - 1$. Now consider the case when $a = 2^x - 1$. This implies $gcd(a \\oplus b, a \\& b) = gcd(2^x - 1 - b, b) = gcd(2^x - 1, b)$, since $gcd(x, x + y) = gcd(x, y)$ (for all $x$ and $y$), hence it's sufficient to find the largest non trivial divisor of $a$ - it will be the desired answer. Finding the largest divisor can be done in sqrt time which leads to the time $O(q \\sqrt{m})$ or it's possible to calculate answers for all $a = 2^x - 1$ beforehand.",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1110",
    "index": "D",
    "title": "Jongmah",
    "statement": "You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have $n$ tiles in your hand. Each tile has an integer between $1$ and $m$ written on it.\n\nTo win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, $7, 7, 7$ is a valid triple, and so is $12, 13, 14$, but $2,2,3$ or $2,4,6$ are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple.\n\nTo determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand.",
    "tutorial": "First thing to note is that one can try solving this problem with different greedy approaches, but authors don't know any correct greedy. To solve this problem, note that you can always replace $3$ triples of type $[x, x + 1, x + 2]$ with triples $[x, x, x]$, $[x + 1, x + 1, x + 1]$ and $[x + 2, x + 2, x + 2]$. So we can assume that there are at most $2$ triples of type $[x, x + 1, x + 2]$ for each $x$. Having noted this, you can write dynamic programming solution. Let ans[i][t1][t2] be the answer considering only the first $i$ denominations, and there are $t_1$ triples of type $[i - 1, i, i + 1]$ and $t_2$ triples of type $[i, i + 1, i + 2]$. Try all possible number $t_3$ of triples of type $[i + 1, i + 2, i + 3]$, put all the remaining tiles of denomination $i + 1$ into triples $[i + 1, i + 1, i + 1]$ and make a transition to ans[i + 1][t2][t3].",
    "tags": [
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1110",
    "index": "E",
    "title": "Magic Stones",
    "statement": "Grigory has $n$ magic stones, conveniently numbered from $1$ to $n$. The charge of the $i$-th stone is equal to $c_i$.\n\nSometimes Grigory gets bored and selects some inner stone (that is, some stone with index $i$, where $2 \\le i \\le n - 1$), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its own charge, but acquires the charges from neighboring stones. In other words, its charge $c_i$ changes to $c_i' = c_{i + 1} + c_{i - 1} - c_i$.\n\nAndrew, Grigory's friend, also has $n$ stones with charges $t_i$. Grigory is curious, whether there exists a sequence of zero or more synchronization operations, which transforms charges of Grigory's stones into charges of corresponding Andrew's stones, that is, changes $c_i$ into $t_i$ for all $i$?",
    "tutorial": "Consider the difference array $d_1, d_2, \\ldots, d_{n - 1}$, where $d_i = c_{i + 1} - c_i$. Let's see what happens if we apply synchronization. Pick an arbitrary index $j$ and transform $c_j$ to $c_j' = c_{j + 1} + c_{j - 1} - c_j$. Then: $d_{j - 1}' = c_j' - c_{j - 1} = (c_{j + 1} + c_{j - 1} - c_j) - c{j - 1} = c_{j + 1} - c_j = d_j$; $d_j' = c_{j + 1} - c_j' = c_{j + 1} - (c_{j + 1} + c_{j - 1} - c_j) = c_j - c{j - 1} = d_{j - 1}$. In other words, synchronization simply transposes two adjacent differences. That means that it's sufficient to check whether the difference arrays of two sets of stones are equal and make sure that $s_1 = t_1$.",
    "tags": [
      "constructive algorithms",
      "math",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1110",
    "index": "F",
    "title": "Nearest Leaf",
    "statement": "Let's define the Eulerian traversal of a tree (a connected undirected graph without cycles) as follows: consider a depth-first search algorithm which traverses vertices of the tree and enumerates them in the order of visiting (only the first visit of each vertex counts). This function starts from the vertex number $1$ and then recursively runs from all vertices which are connected with an edge with the current vertex and are not yet visited in increasing numbers order. Formally, you can describe this function using the following pseudocode:\n\n\\begin{verbatim}\nnext_id = 1\nid = array of length n filled with -1\nvisited = array of length n filled with false\nfunction dfs(v):\nvisited[v] = true\nid[v] = next_id\nnext_id += 1\nfor to in neighbors of v in increasing order:\nif not visited[to]:\ndfs(to)\n\\end{verbatim}\n\nYou are given a weighted tree, the vertices of which were enumerated with integers from $1$ to $n$ using the algorithm described above.\n\nA leaf is a vertex of the tree which is connected with only one other vertex. In the tree given to you, the vertex $1$ is not a leaf. The distance between two vertices in the tree is the sum of weights of the edges on the simple path between them.\n\nYou have to answer $q$ queries of the following type: given integers $v$, $l$ and $r$, find the shortest distance from vertex $v$ to one of the leaves with indices from $l$ to $r$ inclusive.",
    "tutorial": "Let's answer the queries offline: for each vertex we'll remember all queries for it. Let's make vertex $1$ root and find distances from it to all leaves using DFS. Now for answering queries for vertex $1$ we should simply answer some range minimum queries, so we'll build a segment tree for it. For answering queries for other vertices we will make segment trees with distances to leaves (like we did for handling queries for vertex $1$) for all vertices. We will traverse vertices of a tree using DFS and maintain actual distances to leaves in segment tree. Suppose, DFS went through edge $(u, v)$ with weight $w$ where $u$ is an ancestor of $v$. Distances to leaves in subtree of $v$ will decrease by $w$ and distances to other vertices will increase by $w$. Since set of leaves in subtree of some vertex is a subsegment of vertices written in euler traversal order, we should simply make range additions/subtractions on segment tree to maintain distances to leaves when passing through an edge. This way we got a solution with $O(n \\log n + q \\log n)$ complexity.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1110",
    "index": "G",
    "title": "Tree-Tac-Toe ",
    "statement": "The tic-tac-toe game is starting on a tree of $n$ vertices. Some vertices are already colored in white while the remaining are uncolored.\n\nThere are two players — white and black. The players make moves alternatively. The white player starts the game. In his turn, a player must select one uncolored vertex and paint it in his color.\n\nThe player wins if he paints some path of three vertices in his color. In case all vertices are colored and neither player won, the game ends in a draw.\n\nCould you please find who will win the game or whether it ends as a draw, assuming both players play optimally?",
    "tutorial": "To start with, let's notice that the white vertices are not necessary. Actually, you can solve the problem analyzing the cases with the whites as well, but there is an easy way to get rid of them: Examine the following construction: That is, replace the white $A$ with some set of four non-white vertices. One can notice, that neither white nor black can win on these four vertices. That means that they are actually interested in getting the color of the end of this graph, connected to the remaining graph being of their color - it can help them later. Let's start the game as white player and paint a vertex $A$ white. If black player will not paint the vertex $B$ black, we have a win. Otherwise, two turns have passed now and that means that the \"parity\" has preserved and it is our turn again. Then we can play as we would have played in the original game, except if the black player paints $C$ or $D$ in some point, we should color the remaining one (and the parity will preserve again). ------- Now let's solve the problem assuming there are no white vertices. Note, that if there is a vertex of degree $4$ or more, then the white player wins, maing the first move into that vertex, and then two moves in some leaves of this vertex. In case there is a vertex of degree $3$ having at least two non-white neighbors, then it's a win as well: we can either collect a path going through this vertex or going through non-leave neighbor somewhere else. Now, note that if there are at least $3$ vertexes of degree $3$, this implies the case above. So we are left with a case when there are at most three vertices of degree $3$ and all other have degree $1$ or $2$. It's natural to claim (and many got wa2 for that), that all remaining cases are draws. But it's not true: It's easy to see, that this game (picture above) is winning for white. Applying the same argument, as before, we can deduce that the game above is equivalent to the game below. Which is clearly winning for white. Actually, any path having odd number of vertices and colored in white on both ends is winning for white (make a move into the vertex colored blue on the picture below): This actually meains, that in our solution, in which we got rid of all white vertices, the winning cases are <<bones>> having odd number of vertices. It's possible to show, that in all other cases the game will end in draw.",
    "tags": [
      "constructive algorithms",
      "games",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1110",
    "index": "H",
    "title": "Modest Substrings",
    "statement": "You are given two integers $l$ and $r$.\n\nLet's call an integer $x$ modest, if $l \\le x \\le r$.\n\nFind a string of length $n$, consisting of digits, which has the largest possible number of substrings, which make a modest integer. Substring having leading zeros are not counted. If there are many answers, find lexicographically smallest one.\n\nIf some number occurs multiple times as a substring, then in the counting of the number of modest substrings it is counted multiple times as well.",
    "tutorial": "Set of modest numbers could be represented by set of size approximately $(|l| + |r|) \\cdot 10$ of regular expressions of form $d_0 d_1 d_2 \\dots d_{k - 1} [0-9]\\{e\\}$, where $|l|$ and $|r|$ are lengths of numbers $l$ and $r$ correspondingly, and $d_i$ are digits. Set of regular expressions can be build in the following way. Consider prefix of $l$ of length $x$. Then for every $q > l_x$ let's make the following expression: $l_0 l_1 l_2 \\dots l_{x - 1} q [0-9]\\{|l| - x - 1\\}$. Similarly for $r$, but here $q < r_x$. Also for all $|l| < x < |r|$ we should make regular expressions $[1-9][0-9]\\{x - 1\\}$, this is equal to nine expressions of our form. Notice that every modest number would satisfy exactly one regular expression and no other number would satisfy any expression. Let's call wildcard of length $x$ tail of regular expression of form $[0-9]\\{x\\}$. Let's build Aho-Corasick automaton for all prefixes of regular expressions until wildcards. For every regular expression put in corresponding node length of wildcard. After that task could be solved using dynamic programming. State would be length of prefix of answer and node of the automaton. From state $(i, v)$ we can go by digit $d$ to the state $(i + 1, u)$, $u$ is node where $d$ leads from $v$. Value for $(i + 1, u)$ should be updated by value for $(i, v)$ plus number of wildcards with lengths not exceeding $n - i - 1$, placed in nodes reachable from $u$ by suffix links in automaton. This value can be calculated beforehand for every pair node and length. Asymptotics of solution is $O((|l| + |r|) \\cdot n \\cdot \\Sigma ^ 2)$, where $\\Sigma$ is size of alphabet, i.e. $10$.",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1111",
    "index": "A",
    "title": "Superhero Transformation",
    "statement": "We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $s$ can transform to another superhero with name $t$ if $s$ can be made equal to $t$ by changing any vowel in $s$ to any other vowel and any consonant in $s$ to any other consonant. Multiple changes can be made.\n\n\\textbf{In this problem}, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.\n\nGiven the names of two superheroes, determine if the superhero with name $s$ can be transformed to the Superhero with name $t$.",
    "tutorial": "Check lengths of $s$ and $t$. If they are different, $s$ can never be converted to $t$ and answer is \"No\". If for all indexes $i$ either both $s[i]$ and $t[i]$ are vowels or both $s[i]$ and $t[i]$ are consonants, then answer is \"Yes\", else answer is \"No\".",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\n// Checking if a character is vowel\nbool isVowel(char a)\n{\n    if(a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')\n        return true;\n    return false;\n}\n\nint main()\n{\n    string S, T;\n    cin >> S;\n    cin >> T;\n    // Answer is no if size of strings is differents\n    if(S.size() != T.size())\n    {\n        cout << \"No\\n\";\n        return 0;\n    }\n    int flag = 1;\n    // Checking the condition on all characters one by one \n    for(int i = 0; i < S.size(); ++i)\n    {\n        if((isVowel(S[i]) && isVowel(T[i])) || (isVowel(S[i]) == false && isVowel(T[i]) == false))\n        {\n            continue;\n        }\n        flag = 0;\n        break;\n    }\n    if(flag)\n        cout << \"Yes\\n\";\n    else\n        cout << \"No\\n\";\n    return 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1111",
    "index": "B",
    "title": "Average Superhero Gang Power ",
    "statement": "Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.\n\nInitially, there are $n$ superheroes in avengers team having powers $a_1, a_2, \\ldots, a_n$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $1$. They can do at most $m$ operations. Also, on a particular superhero at most $k$ operations can be done.\n\nCan you help the avengers team to maximize the average power of their crew?",
    "tutorial": "If we want to remove an element to increase the average it should be the smallest element in our current set. For each deletion, $1$ operation is used. Lets try finding $f(i)$ = maximum average by deleting $i$ smallest elements. If we delete $i$ elements, then for the remaining $n-i$ elements the maximum increase can be $min(m-i,k*(n-i))$ since $m-i$ operations can be now at max used, and at one particular index at most $k$ operations can be done. So $f(i) =$( sum of largest $(n-i$) elements $+ min(m-i,k*(n-i)) )/ (n-i)$ The sum of largest $(n-i)$ terms can be computed using prefix sums. $ans =$max $f(i)$ over all $i$ from $0$ to $min(m,n-1)$ The min condition comes because there is no use of deleting all elements, and the number of deletions is limited by the maximum number of operations possible.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst long long N = 100010;\n\nlong long a[N];\n\nint main()\n{\n    long long n, k, m, i, sum=0, tp;\n    long double mx;\n    cin>>n>>k>>m;\n    for(int i=1;i<=n;i++)\n    {\n        cin>>a[i];\n        sum += a[i];\n    }\n    // Sorting the array\n    sort(a+1, a+n+1);\n    // Checking for the case where none of the avengers is removed\n    mx = (long double)(sum+min(m, n*k))/(long double)(n);\n \n    for(int i=1;i<=min(n-1, m);i++)\n    {\n        sum -= a[i];\n        tp = sum + min(m-i, (n-i)*k);\n        mx = max(mx, (long double)(tp)/(long double)(n-i));\n    }\n    cout<<fixed<<setprecision(20)<<mx<<endl;\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1111",
    "index": "C",
    "title": "Creative Snap",
    "statement": "Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.\n\nLet we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $2$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:\n\n- if the current length is at least $2$, divide the base into $2$ equal halves and destroy them separately, or\n- burn the current base. If it contains no avenger in it, it takes $A$ amount of power, otherwise it takes his $B \\cdot n_a \\cdot l$ amount of power, where $n_a$ is the number of avengers and $l$ is the length of the current base.\n\nOutput the minimum power needed by Thanos to destroy the avengers' base.",
    "tutorial": "Make a recursive function rec($l,r$) where l and r are start and end indexes of subarray to be considered. Start with $l=1$ and $r=2^n$. If there is no avenger in l to r return A (power consumed). Else either power consumed to burn it directly is $b*x*len$ (where x is number of avengers in l to r and len is length of array ($r-l+1$) ) or by dividing the array is the result of recursion($l,mid$) + recursion($mid+1,r$) where $mid=(l+r)/2$. Return the minimum power consumed. If l is equal to r then do not go into recursion further, return power consumed according to first operation. One thing is remaining, the value of x, given l and r. Sort the array containing indices of avengers and then find positions of l and r in that array using binary search. Difference is positions of l and r in array will give x. Time Complexity : $O(n*k*log(k))$. Explanation : Reaching any subarray will take maximum of n operations and we can have maximum k subarrays (each having one avenger), it will take $O(n*k)$. $O(log(k))$ time needed for binary search (calculating x). So net complexity is $O(n*k*log(k))$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<long long> avengers;\nlong long n,k,A,B;\n\n// rec(l,r) returns minimum power needed to destroy l to r (inclusive)\nlong long rec(long long l, long long r)\n{\n\tlong long i=lower_bound(avengers.begin(),avengers.end(),l)-avengers.begin();\n\tlong long j=upper_bound(avengers.begin(),avengers.end(),r)-avengers.begin();\n\tj--;\n        // calculating positions of l and r in avengers array to calculate x\n\tlong long x=j-i+1;\n\tlong long power_consumed;\n        // if there is no avenger in that subarray\n\tif(x==0)\n\t\tpower_consumed=A;\n\telse\n\t{\n\t    power_consumed=B*x*(r-l+1);\n            // power consumed for operation 2. (r-l+1 is length of subarray)\n\t}\n        // if l is equal to r or if there is no avenger in the subarray, then do not go into recursion further\n\tif(l==r || x==0)\n\t\treturn power_consumed;\n\tlong long mid=(l+r)/2;\n\t// taking minimum of two operations.\n\tlong long minPower=min(power_consumed, rec(l,mid)+rec(mid+1,r));\n\treturn minPower;\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n\tcin>>n>>k>>A>>B;\n\tint i;\n\tfor(i=0;i<k;i++)\n\t{\n\t\tint val;\n\t\tcin>>val;\n\t\tavengers.push_back(val);\n\t}\n\tsort(avengers.begin(),avengers.end());\n\tlong long x = (long long)1<<n;\n\tcout<<rec(1,x)<<endl;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "divide and conquer",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1111",
    "index": "D",
    "title": "Destroy the Colony",
    "statement": "There is a colony of villains with several holes aligned in a row, where each hole contains exactly one villain.\n\nEach colony arrangement can be expressed as a string of \\textbf{even} length, where the $i$-th character of the string represents the type of villain in the $i$-th hole.\n\nIron Man can destroy a colony only if the colony arrangement is such that all villains of a certain type either live in the first half of the colony or in the second half of the colony.\n\nHis assistant Jarvis has a special power. It can swap villains of any two holes, i.e. swap any two characters in the string; he can do this operation any number of times.\n\nNow Iron Man asks Jarvis $q$ questions. In each question, he gives Jarvis two numbers $x$ and $y$. Jarvis has to tell Iron Man the number of distinct colony arrangements he can create from the original one using his powers such that all villains having the same type as those originally living in $x$-th hole or $y$-th hole live in the same half and the Iron Man can destroy that colony arrangement.\n\nTwo colony arrangements are considered to be different if there exists a hole such that different types of villains are present in that hole in the arrangements.",
    "tutorial": "The question reduces to the following. Given a string s with lowercase and uppercase characters,a good string is one which can be generated by reshuffling characters, such that all occurences of a particular alphabet are in the same half. ( (1 to n/2) or (n/2+1 to n)) and this condition is true for all alphabets. Now given a pair $i$ and $j$, you want to find the number of good strings such that all the occurences of $s[i]$ and $s[j]$ in the string are also in the same half in the string. Lets first try to find the number of good strings. $k$ = total number of alphabets. Store the frequencies of the alphabets as their order does not matter, and let them be $c1,c2,c3..ck$ Now if we can select indices $i_1, i_2, \\ldots, i_p$ such that $ci_1 + ci_2 + \\ldots, ci_p$ = n/2 then we can arrange those alphabets in the first half, and the remaining in the second half. Total ways for arranging in first half = $(n/2!)/(ci1!* ci2!* ci3!.. cip!)$ Similarly total ways for arranging in 2nd half = $(n/2!)/$(product of factorials of remaining frequencies.) Thus total ways = $((n/2!)*(n/2!))/$(product of factorials of frequencies of all alphabets) $= W$(say) Thus notice that, for all combinations of frequencies adding upto $n/2$, the number of ways comes out to be constant. Hence now the total number of good strings $= W*$ (number of combinations of frequencies adding to $n/2$) The part for the number of combinations adding upto $n/2$ can be computed using standard knapsack dp. Now let's try to solve for the condition that all occurrences of $s[i]$ and $s[j]$, should all also be in the same half, apart from the condition of the string being a good string. This basically means now we want to select alphabet frequencies adding upto $n/2$ from the remaining frequencies ( excluding the frequency of alphabet $s[i]$ and $s[j]$). One way is to use the same method we did above for all good strings. This gives complexity O$(n*k)$ for every pair, taking a total of O$(n*k^3)$ for $k^2$ pairs. Now using the idea of adding items to a knapsack, we can also extend it to remove items. In short, we can use the pre-computed dp table to remove the number of ways which included the ith item, by reversing the direction of the loop and the operation ( addition becomes subtraction). Let the frequency of the element we want to remove be $x$. dp[j] = number of ways to get sum as j using all elements. for (int j=x;j<=n;j++) $\\quad$dp[j]-=dp[j-x]; ( see the code for more details) In this way for every pair $(x,y)$, you copy the precomputed dp into a temporary array, remove ways using characters $x$ and $y,$ and then the answer will be $2*dp[n/2]*W$ ( 2 because you can choose the first or the second half for putting the group containing $x$ and $y$). After precomputation, each query is answered in O$(1)$. Total time O$(2*n)$, for every pair and there are $(k*(k-1))/2$ pairs. Final time complexity O$(n*k^2)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define pb push_back\n#define fr(i,n) for(i=0;i<n;i++)\n#define rep(i,st,en) for(i=st;i<=en;i++)\n\ntypedef long long ll;\ntypedef pair<int,int> pii;\nconst int N = 100010;\nll mod = 1e9+7;\nll fmod(ll b,ll exp){\n    ll res =1;\n    while(exp){if(exp&1ll)res=(res*b)%mod;\n    b =(b*b)%mod;exp/=2ll;\n    }\n    return res;\n}\n\nll buc[101];\nll fac[N],inv[N];\nll dp[N],temp_dp[N];\nll ans[55][55];\nstring s,s1,s2;\n\nint find(char c)\n{\n    if(c>='A' && c<='Z')return (int)(c-'A'+26);\n    else return (c-'a');\n}\n\ninline void add(ll &a,ll b)\n{\n    a+=b;\n    if(a>=mod)a-=mod;\n}\ninline void sub(ll &a,ll b)\n{\n    a-=b;\n    if(a<0)a+=mod;\n}\nint main()\n{\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    ios_base::sync_with_stdio(false);cin.tie(NULL);\n    int t=1,n,i,j,m,q;\n    cin>>s;\n    n = s.length();\n    //Store the frequencies in buc\n    for(int i=0;i<n;i++)buc[find(s[i])]++;\n    \n    //Compte factorial and inverse factorials modulo mod\n    fac[0]=1;\n    rep(i,1,n)fac[i]=(fac[i-1]*1ll*i)%mod;\n    inv[n] = fmod(fac[n],mod-2);\n    for(int i=n-1;i>=0;i--)inv[i]=(inv[i+1]*1ll*(i+1))%mod;\n\n\n    //Compute n/2! * n/2! divided by factorials of frequencies of all\n    ll num = (fac[n/2]*fac[n/2])%mod;\n    for(int i=0;i<52;i++)num = (num*inv[buc[i]])%mod;\n\n    //DP for subset sum\n    dp[0]=1;\n    for(int i=0;i<52;i++)\n    {\n        if(!buc[i])continue;\n        for(int j=n;j>=buc[i];j--)\n            add(dp[j],dp[j-buc[i]]);\n    }\n    fr(i,52)ans[i][i]=dp[n/2];\n\n    fr(i,52)\n    {\n        if(!buc[i])continue;\n        //Temporrily store dp using all characters in an array\n        for(int k=0;k<=n;k++)\n            temp_dp[k]= dp[k];\n\n        //Remove all ways consisting of the ith character from temp array\n        for(int k=buc[i];k<=n;k++)\n            sub(temp_dp[k],temp_dp[k-buc[i]]);\n        \n\n        for(int j=i+1;j<52;j++)\n        {\n            if(!buc[j])continue;\n            //Now remove the jth character from the temp\n            for(int k=buc[j];k<=n;k++)\n                sub(temp_dp[k],temp_dp[k-buc[j]]);\n\n            // Answer will be twice since ith and jth can be in 1st or 2nd half\n            ans[i][j]= (2ll*temp_dp[n/2])%mod;\n            ans[j][i]= ans[i][j]; //Symmetric\n                \n            //Restore condition by adding ways using jth to reset temp to without i\n            for(int k=n;k>=buc[j];k--)\n                add(temp_dp[k],temp_dp[k-buc[j]]);\n        }\n    }\n    cin>>q;\n    int x,y;\n    while(q--)\n    {\n        cin>>x>>y;\n        int l = find(s[x-1]);\n        int r = find(s[y-1]);\n        //Use precomputed num and ans, for all queries\n        cout<<(num*ans[l][r])%mod<<\"\\n\";\n    }\n    \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1111",
    "index": "E",
    "title": "Tree",
    "statement": "You are given a tree with $n$ nodes and $q$ queries.\n\nEvery query starts with three integers $k$, $m$ and $r$, followed by $k$ nodes of the tree $a_1, a_2, \\ldots, a_k$. To answer a query, assume that the tree is rooted at $r$. We want to divide the $k$ given nodes into \\textbf{at most} $m$ groups such that the following conditions are met:\n\n- Each node should be in exactly one group and each group should have at least one node.\n- In any group, there should be no two distinct nodes such that one node is an ancestor (direct or indirect) of the other.\n\nYou need to output the number of ways modulo $10^{9}+7$ for every query.",
    "tutorial": "Assume that we didn't have to root at Y in each query. Lets first solve the problem for all queries having root at 1. While processing the query, let's sort the given set of nodes according to the dfs order. Let dp[i][j] denotes the number of ways to divide the first i nodes in the set into j non-empty groups. For a node i, let h[i] denote the number of ancestors in the query set. Now, dp[i][j] = dp[i-1][j]$\\cdot$(j-h[i]) + dp[i-1][j-1] The first part basically says, that apart from the groups of the ancestors of i, it can be included in any other group, hence (j-h[i]) choices for allocating a group to i. The second part is including $i$-th node in a completely new group. Thus our final answer would have been the sum of dp[n][j] for all j from 1 to x. Now how to find h[i]? If we mark all the nodes which have appeared in the query, h[i] is the number of marked nodes from i to the root. This can be computed using standard range updates and point queries on Euler tree. For all nodes i, perform a range update on the range [ST(i),EN(i)] and h[i] basically becomes query(ST[i]). Now a key observation. Notice that actually we only care that for node i, before updating its dp, all its ancestors are visited. This means we actually do not need the dfs order, instead just the level-wise order. So all we need to do is sort all nodes in the query set according to the h[i] values. By removing the condition for dfs order on the ordering of the dp, the condition for rerooting can also be handled. If the tree is rooted at Y, Now hnew[i] becomes the number of marked nodes between i and root Y. This can be computed using the same technique of range update and query. hnew[i] = h[i] + h[Y] - 2$\\cdot$h[ LCA(i,Y)] + (mark[LCA(i,Y)]==true) -1 (-1 because we do not want to include i in hnew[i]) Now we do the same dp and compute the answer. For every query: Sorting = O(KlogK), LCA computation = O(KlogN), bit update and query= O(KlogN) LCA precomputation = O(NlogN) Thus final complexity = O( NlogN + logN$\\cdot$(summation over all values of K)) (where summation of K <= 10^5)",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define pb push_back\n#define rep(i,st,en) for(i=st;i<=en;i++)\n\ntypedef long long ll;\ntypedef pair<int,int> pii;\nconst int N = 200010;\nconst int LN = 20;\nll mod = 1e9+7;\nll fmod(ll b,ll exp){\n    ll res =1;\n    while(exp){if(exp&1ll)res=(res*b)%mod;\n        b =(b*b)%mod;exp/=2ll;\n    }\n    return res;\n}\n\nint ver[2*N]; // gives the id of the vertex in the euler array\nll bit[2*N];\nint st[N],en[N],A[N]; // st and en are the start and end time of node i\nint f[N];\nll dp[N];\nint par[N][LN];\nint mark[N],lev[N];\n\nvector<int> adj[N];\n\nint tim = 0,n;\n\n/* Normal DFS and LCA functions */\nvoid dfs(int i,int p=-1)\n{\n    \n    if (p+1)\n    {\n        lev[i]=lev[p]+1;\n        par[i][0]=p;\n        for(int j=1;j<LN;j++)\n            if (par[i][j-1]+1)\n                par[i][j]=par[par[i][j-1]][j-1];\n    }\n    st[i]=(++tim);\n    ver[tim]= i;\n    for(auto ve:adj[i])\n        if(p-ve)\n            dfs(ve,i);\n    en[i]=(++tim);\n    ver[tim]= i;\n}\n\nint lca(int u,int v)\n{\n    if (lev[u]<lev[v])\n        swap(u,v);\n    for(int j=LN-1;j>=0;j--)\n        if (par[u][j]+1 && lev[par[u][j]]>=lev[v])\n            u=par[u][j];\n    if (u==v)\n        return u;\n    for(int j=LN-1;j>=0;j--)\n    {\n        if (par[u][j]+1 && par[u][j]!=par[v][j])\n        {\n            u=par[u][j];\n            v=par[v][j];\n        }\n    }\n    return par[u][0];\n}\n\n/* Helper functions */\ninline ll add(ll a,ll b)\n{\n    a+=b;\n    if(a>=mod)a-=mod;\n    return a;\n}\nvoid upd(int ind,int val)\n{\n    for(int i=ind;i<=2*n;i+=(i&-i))\n        bit[i]+=val;\n}\n\nll query(int ind)\n{\n    ll res = 0;\n    for(int i=ind;i>0;i-=(i&-i))\n        res+=bit[i];\n    return res; // returns the number of marked nodes from 1 to ind inclusive.\n}\n\nint main()\n{\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    ios_base::sync_with_stdio(false);cin.tie(NULL);\n    int t=1,i,j,m,q,u,v,w,typ,e,k,x;\n    memset(par,-1,sizeof(par));\n    cin>>n>>q;\n    rep(i,1,n-1)\n    {\n        cin>>u>>v;\n        adj[u].pb(v);\n        adj[v].pb(u);\n    }\n    dfs(1,-1);\n    int root;\n    while(q--)\n    {\n        cin>>k>>x>>root;\n\n        rep(i,1,k){\n            cin>>A[i];\n            mark[A[i]]=1; //mark nodes given in the set\n            upd(st[A[i]],1);  // range update by updating at start and end time in bit\n            upd(en[A[i]]+1,-1);\n        }\n        int ans_root = query(st[root]);\n        rep(i,1,k){\n            int lp = lca(A[i],root);\n            //query function is inclusive, hence subtract 1 to remove current node from answer\n            f[i]= query(st[A[i]])+ans_root-2*query(st[lp])+(mark[lp]==1)-1;\n        }\n        //Sorting level-wise using f[i] values\n        sort(f+1,f+k+1);\n        rep(i,1,k){\n            upd(st[A[i]],-1); // reverse the updates to nullify effect\n            upd(en[A[i]]+1,1);\n            mark[A[i]]=0;  // unmark nodes in the set\n        }\n        rep(i,0,x)dp[i]=0;\n        dp[0]=1;\n        //If number of groups less than maximum height no way possible\n        int fl = 0;\n        rep(i,1,k)if(f[i]>=x)fl=1;\n        if(fl)cout<<\"0\\n\";\n        else{\n        dp[0]=1;\n        //For every value of f[i], update dp. Note loop for j will be reverse.\n        rep(i,1,k){\n            for(int j=min(i,x);j>=0;j--)\n            {\n                if(j<=f[i])dp[j]=0; //no way possible since less than height\n                else dp[j]= add(((dp[j]*1ll*(j-f[i]))%mod),dp[j-1]); \n            }\n        }\n        ll ans = 0;\n        // AT MOST x in the question\n        rep(i,1,x){\n            ans = add(ans,dp[i]);\n        }\n        cout<<ans<<\"\\n\";\n        }\n    }\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1113",
    "index": "A",
    "title": "Sasha and His Trip",
    "statement": "Sasha is a very happy guy, that's why he is always on the move. There are $n$ cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from $1$ to $n$ in increasing order. The distance between any two adjacent cities is equal to $1$ kilometer. Since all roads in the country are directed, it's possible to reach the city $y$ from the city $x$ only if $x < y$.\n\nOnce Sasha decided to go on a trip around the country and to visit all $n$ cities. He will move with the help of his car, Cheetah-2677. The tank capacity of this model is $v$ liters, and it spends exactly $1$ liter of fuel for $1$ kilometer of the way. At the beginning of the journey, the tank is empty. Sasha is located in the city with the number $1$ and wants to get to the city with the number $n$. There is a gas station in each city. In the $i$-th city, the price of $1$ liter of fuel is $i$ dollars. It is obvious that at any moment of time, the tank can contain at most $v$ liters of fuel.\n\nSasha doesn't like to waste money, that's why he wants to know what is the minimum amount of money is needed to finish the trip if he can buy fuel in any city he wants. Help him to figure it out!",
    "tutorial": "When $n - 1 < v$ the answer is $n - 1$. Else you must notice, that it is optimal to fill the tank as soon as possible, because if you don't do that, you will have to spend more money in future. So to drive first $v - 1$ kilometers just buy $v - 1$ liters in the first city, then to drive between cities with numbers $i$ and $i + 1$, buy liter in the city with number $i - v + 1$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\n\\nint32_t main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr), cout.tie(nullptr);\\n    \\n    int n, v;\\n    cin >> n >> v;\\n    if (n-1 <= v) {\\n        cout << n-1 << endl;\\n        return 0;\\n    }\\n    int result = v - 1;\\n    for(int i = 1; i <= n - v; ++i) {\\n        result += i;\\n    }\\n    cout << result << endl;\\n\\n    return 0;\\n}\\n\"",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1113",
    "index": "B",
    "title": "Sasha and Magnetic Machines",
    "statement": "One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $n$ machines, and the power of the $i$-th machine is $a_i$.\n\nThis year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can \\textbf{at most once} choose an arbitrary integer $x$, then choose one machine and reduce the power of its machine by $x$ times, and at the same time increase the power of one another machine by $x$ times (powers of all the machines must stay \\textbf{positive integers}). Note that he may not do that if he wants. More formally, 2D can choose two such indices $i$ and $j$, and one integer $x$ such that $x$ is a divisor of $a_i$, and change powers as following: $a_i = \\frac{a_i}{x}$, $a_j = a_j \\cdot x$\n\nSasha is very curious, that's why he wants to calculate the \\textbf{minimum} total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!",
    "tutorial": "First notice that if we divide some number by $x$, then to get the minimal sum, it is optimal to multiply by $x$ the smallest number in the array. So now precalculate the sum of the initial array and the minimal $a_i$, then you can check all possible $x$ for every $a_i$, and choose the best variant. So the complexity is $O(n \\cdot a_i)$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\n\\nint32_t main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr), cout.tie(nullptr);\\n    \\n    int n;\\n    cin >> n;\\n    vector<int> a(n);\\n    for(int i = 0; i < n; ++i) {\\n        cin >> a[i];\\n    }\\n    int mn = *min_element(a.begin(), a.end());\\n    int sum = accumulate(a.begin(), a.end(), 0);\\n    int res = sum;\\n    for(int i = 0; i < n; ++i) {\\n        for(int d = 1; d <= a[i]; ++d) {\\n            if (a[i] % d != 0) continue;\\n            int cur = sum - mn - a[i];\\n            cur += mn * d + a[i] / d;\\n            res = min(res, cur);\\n        }\\n    }\\n    cout << res << endl;\\n\\n    return 0;\\n}\\n\"",
    "tags": [
      "greedy",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1114",
    "index": "A",
    "title": "Got Any Grapes?",
    "statement": "\\begin{quote}\nThe Duck song\n\\end{quote}\n\nFor simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.\n\nAndrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:\n\n- Andrew, Dmitry and Michal should eat at least $x$, $y$ and $z$ grapes, respectively.\n- Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.\n- On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.\n- Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.\n\nKnowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with $a$ green grapes, $b$ purple grapes and $c$ black grapes.\n\nHowever, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?\n\nIt is not required to distribute all the grapes, so it's possible that some of them will remain unused.",
    "tutorial": "First of all, we can see the grape preference is hierarchically inclusive: the grapes' types Andrew enjoys are some of those that Dmitry does, and Dmitry's favorites are included in Michal's. Let's distribute the grapes to satisfy Andrew first, then to Dmitry, then Michal. If any of the following criteria is not satisfied (which means one of our friends is not happy), then we can immediately say that no distributions are available: Andrew must have at least $a$ green grapes. So we need, $x  \\le  a$. Dmitry can have purple grapes and/or the remaining green grapes. In other words, $y  \\le  a + b - x$ (the minus $x$ is because $x$ green grapes have been given to Andrew already). Michal can have grapes of any kinds. In other words, $z  \\le  a + b + c - x - y$ (similar explanations like above for both minus $x$ and minus $y$). If all three criteria are satisfied, then a grape distribution is possible. Total complexity: $O\\left(1\\right)$.",
    "code": "#pragma comment(linker, \"/stack:247474112\")\n#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\n\nint x, y, z, a, b, c;\n\nvoid Input() {\n\tcin >> x >> y >> z;\n\tcin >> a >> b >> c;\n}\n\nvoid Solve() {\n\tif (x > a) {cout << \"NO\\n\"; return;}\n\tif (x + y > a + b) {cout << \"NO\\n\"; return;}\n\tif (x + y + z > a + b + c) {cout << \"NO\\n\"; return;}\n\tcout << \"YES\\n\";\n}\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0);\n\tcin.tie(NULL); Input(); Solve();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1114",
    "index": "B",
    "title": "Yet Another Array Partitioning Task",
    "statement": "An array $b$ is called to be a subarray of $a$ if it forms a continuous subsequence of $a$, that is, if it is equal to $a_l$, $a_{l + 1}$, $\\ldots$, $a_r$ for some $l, r$.\n\nSuppose $m$ is some known constant. For any array, having $m$ or more elements, let's define it's beauty as the sum of $m$ largest elements of that array. For example:\n\n- For array $x = [4, 3, 1, 5, 2]$ and $m = 3$, the $3$ largest elements of $x$ are $5$, $4$ and $3$, so the beauty of $x$ is $5 + 4 + 3 = 12$.\n- For array $x = [10, 10, 10]$ and $m = 2$, the beauty of $x$ is $10 + 10 = 20$.\n\nYou are given an array $a_1, a_2, \\ldots, a_n$, the value of the said constant $m$ and an integer $k$. Your need to split the array $a$ into exactly $k$ subarrays such that:\n\n- Each element from $a$ belongs to exactly one subarray.\n- Each subarray has at least $m$ elements.\n- The sum of all beauties of $k$ subarrays is maximum possible.",
    "tutorial": "In a perfect scenario, the maximum beauty of the original array is just a sum of $m \\cdot k$ largest elements. In fact, such scenario is always available regardless of the elements. Let's denote $A$ as the set of these $m \\cdot k$ largest elements. The solution for us will be dividing the array into $k$ segments, such that each segment contains exactly $m$ elements of $A$. Just make a split between corresponding elements in the set $A$. Depending on the way we find $m \\cdot k$ largest elements, the time complexity might differ. If we simply do so after sorting the entire array by usual means, the time complexity will be $O\\left(n\\cdot\\log(n)\\right)$. However, we can use std::nth_element function instead of sorting the entire array. The idea is to sort the array in such a way that, every elements not higher than a value $v$ will be stored in the left side, other elements will stay on the right, and this works in linear time (a.k.a. $O\\left(n\\right)$ time complexity). An example implementation of such ordering can be shown here.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\ntypedef long long ll;\n\nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(NULL);\n\n    int n, m, k;\n    cin >> n >> m >> k;\n\n    vector<pii> a(n);\n    for(int i = 0; i < n; ++i) {\n        cin >> a[i].first;\n        a[i].second = i;\n    }\n\n    sort(a.begin(), a.end(), greater<pii>());\n\n    vector<int> ind(m*k);\n    ll sumBeauty = 0;\n    for(int i = 0; i < m*k; ++i) {\n        sumBeauty += a[i].first;\n        ind[i] = a[i].second;\n    }\n\n    sort(ind.begin(), ind.end());\n\n    vector<int> division(k-1);\n    for(int i = 0; i < k-1; ++i)\n        division[i] = ind[(i+1)*m - 1];\n\n    cout << sumBeauty << endl;\n    for(int p: division)\n        cout << p + 1 << \" \";\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1114",
    "index": "C",
    "title": "Trailing Loves (or L'oeufs?)",
    "statement": "\\begin{quote}\nThe number \"zero\" is called \"love\" (or \"l'oeuf\" to be precise, literally means \"egg\" in French), for example when denoting the zero score in a game of tennis.\n\\end{quote}\n\nAki is fond of numbers, especially those with trailing zeros. For example, the number $9200$ has two trailing zeros. Aki thinks the more trailing zero digits a number has, the prettier it is.\n\nHowever, Aki believes, that the number of trailing zeros of a number is not static, but depends on the base (radix) it is represented in. Thus, he considers a few scenarios with some numbers and bases. And now, since the numbers he used become quite bizarre, he asks you to help him to calculate the beauty of these numbers.\n\nGiven two integers $n$ and $b$ (in decimal notation), your task is to calculate the number of trailing zero digits in the $b$-ary (in the base/radix of $b$) representation of $n\\,!$ (factorial of $n$).",
    "tutorial": "The problem can be reduced to the following: finding the maximum $r$ that $n !$ is divisible by $b^{r}$. By prime factorization, we will have the following: $b = p_{1}^{y1} \\cdot p_{2}^{y2} \\cdot ... \\cdot p_{m}^{ym}$. In a similar manner, we will also have: $n ! = p_{1}^{x1} \\cdot p_{2}^{x2} \\cdot ... \\cdot p_{m}^{xm} \\cdot Q$ (with $Q$ being coprime to any $p_{i}$ presented above). The process of finding $p_{1}$, $p_{2}$, $...$, $p_{m}$, $y_{1}$, $y_{2}$, $...$, $y_{m}$ can be done by normal prime factorization of the value $b$. The process of finding $x_{1}$, $x_{2}$, $...$, $x_{m}$ is a little bit more tricky since the integer they were originated ($n !$) is too huge to be factorized manually. Still the factorial properties gave us another approach: for each $p_{i}$, we can do the following: Initially, denote $x_{i} = 0$. Initially, denote $x_{i} = 0$. Repeatedly do the following: add $\\textstyle\\left|{\\frac{n}{p_{i}}}\\right|$ to $x_{i}$, then divide $n$ by $p_{i}$. The loop ends when $n$ is zero. Repeatedly do the following: add $\\textstyle\\left|{\\frac{n}{p_{i}}}\\right|$ to $x_{i}$, then divide $n$ by $p_{i}$. The loop ends when $n$ is zero. After all, we can obtain the final value $r$ as of following: $r=\\operatorname*{min}_{i\\in[1,m]}|{\\frac{x_{i}}{y_{i}}}|$. Total complexity: $O\\left({\\sqrt{b}}+\\log(b)\\cdot\\log(n)\\right)$ (as the number of prime factors of an integer $b$ will not surpass $\\log(b)$).",
    "code": "#pragma comment(linker, \"/stack:247474112\")\n#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\n\nlong long n, b;\n\nvoid Input() {\n\tcin >> n >> b;\n}\n\nvoid Solve() {\n\tlong long ans = 1000000000000000000LL;\n\tfor (long long i=2; i<=b; i++) {\n\t\tif (1LL * i * i > b) i = b;\n\t\tint cnt = 0;\n\t\twhile (b % i == 0) {b /= i; cnt++;}\n\t\tif (cnt == 0) continue;\n\t\tlong long tmp = 0, mul = 1;\n\t\twhile (mul <= n / i) {mul *= i; tmp += n / mul;}\n\t\tans = min(ans, tmp / cnt);\n\t}\n\tcout << ans << endl;\n}\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0); cin.tie(NULL);\n\tInput(); Solve(); return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1114",
    "index": "D",
    "title": "Flood Fill",
    "statement": "You are given a line of $n$ colored squares in a row, numbered from $1$ to $n$ from left to right. The $i$-th square initially has the color $c_i$.\n\nLet's say, that two squares $i$ and $j$ belong to the same connected component if $c_i = c_j$, and $c_i = c_k$ for all $k$ satisfying $i < k < j$. In other words, all squares on the segment from $i$ to $j$ should have the same color.\n\nFor example, the line $[3, 3, 3]$ has $1$ connected component, while the line $[5, 2, 4, 4]$ has $3$ connected components.\n\nThe game \"flood fill\" is played on the given line as follows:\n\n- At the start of the game you pick any starting square (this is not counted as a turn).\n- Then, in each game turn, change the color of the connected component containing the starting square to any other color.\n\nFind the minimum number of turns needed for the entire line to be changed into a single color.",
    "tutorial": "This problem was inspired by the game Flood-it. It is apparently NP-hard. You can try out the game here. https://www.chiark.greenend.org.uk/\\%7Esgtatham/puzzles/js/flood.html The first solution is rather straightforward. Suppose squares $[L, R]$ are flooded, then they are either of color $c_{L}$ or $c_{R}$. We can define $d p(L,R,d i r)$ as the minimum number of moves required to make the segment $[L, R]$ monochromic: $d p\\left(L,R,0\\right)$ is the least moves required to make the segment having color $c_{L}$. $d p\\left(L,R,1\\right)$ is the least moves required to make the segment having color $c_{R}$. The second solution, which is the author's intended solution, is less so. Note that the size of the component doesn't matter, so first \"compress\" the array so that every adjacent elements are different. We will work on this compressed array instead. We want to maximize the number of turns that we can fill two adjacent squares instead of one. From a starting square, this maximum number of \"saved\" turns is equal to the longest common subsequence (LCS) of the array expanding to the two sides. The answer is the $N$ - (maximum LCS over all starting squares) This is equivalent to finding the longest odd size palindrome subsequence. In fact, it is the longest palindrome subsequence. For every even-sized palindrome subsequence, since adjacent elements are different, we can just insert an element in the middle and obtain a longer palindrome subsequence. To find the longest palindrome subsequence, we can make a reversed copy of the array and find LCS of it with the original array. Alternatively, we can also use the first solution on the compressed array, without needing the third parameter. Time complexity: $O\\left(n^{2}\\right)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int maxN = 5008;\n\nint n;\nint dp[maxN][maxN];\nvector<int> a(1), b;\nvector<int> ans;\n\nvoid input() {\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tint x; cin >> x;\n\t\tif (x != a.back()) a.push_back(x);\n\t}\n\tn = a.size() - 1;\n\n\tb = a;\n\treverse(b.begin() + 1, b.end());\n}\n\nvoid solve() {\n\tfor (int i = 1; i <= n; i++) {\n\t\tfor (int j = 1; j <= n; j++) {\n\t\t\tif (a[i] == b[j]) {dp[i][j] = dp[i-1][j-1] + 1;}\n\t\t\telse {dp[i][j] = max(dp[i-1][j], dp[i][j-1]);}\n\t\t}\n\t}\n}\n\nvoid output() {\n\tcout << n - (dp[n][n] + 1)/2 << '\\n';\n}\n\nint main() {\n\t\n\tinput();\n\tsolve();\n\toutput();\n\t\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1114",
    "index": "E",
    "title": "Arithmetic Progression",
    "statement": "This is an interactive problem!\n\nAn arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element ($x_i - x_{i - 1}$, where $i \\ge 2$) is constant — such difference is called a common difference of the sequence.\n\nThat is, an arithmetic progression is a sequence of form $x_i = x_1 + (i - 1) d$, where $d$ is a common difference of the sequence.\n\nThere is a secret list of $n$ integers $a_1, a_2, \\ldots, a_n$.\n\nIt is guaranteed that all elements $a_1, a_2, \\ldots, a_n$ are between $0$ and $10^9$, inclusive.\n\nThis list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference ($d > 0$). For example, the list $[14, 24, 9, 19]$ satisfies this requirement, after sorting it makes a list $[9, 14, 19, 24]$, which can be produced as $x_n = 9 + 5 \\cdot (n - 1)$.\n\nAlso you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most $60$ queries of following two types:\n\n- Given a value $i$ ($1 \\le i \\le n$), the device will show the value of the $a_i$.\n- Given a value $x$ ($0 \\le x \\le 10^9$), the device will return $1$ if an element with a value strictly greater than $x$ exists, and it will return $0$ otherwise.\n\nYour can use this special device for at most $60$ queries. Could you please find out the smallest element and the common difference of the sequence? That is, values $x_1$ and $d$ in the definition of the arithmetic progression. Note that the array $a$ is not sorted.",
    "tutorial": "The > query type allows you to find the max value of the array through binary searching, which will cost $\\lceil\\log_{2}(10^{9})\\rceil=30$ queries. The remaining queries will be spent for the queries of the ? type to get some random elements of the array. $d$ will be calculated as greatest common divisors of all difference between all consecutive elements, provided all elements found (yes, including the max one) is kept into a list sorted by increasing order. Having d and max, we can easily find the min value: $min = max - d \\cdot (n - 1)$. The number of allowed queries seem small ($30$ queries to be exact), yet it's enough for us to have reasonable probability of passing the problem. By some maths, we can find out the probability of our solution to fail being relatively small - approximately $1.86185 \\cdot 10^{ - 9}$. For simplicity, assumed that the sequence $a$ is $[0, 1, 2, ..., n - 1]$. Suppose that we randomly (and uniformly) select a subsequence $S$ containing $k$ elements from sequence $a$ (when $k$ is the number of ? query asked). Denote $S = [s_{1}, s_{2}, ..., s_{k}]$. Let $D$ the GCD of all difference between consecutive elements in $S$. In other word, $D=\\operatorname*{gcd}(s_{i}-s_{i-1}\\mid2\\leq i\\leq k)$. Our solution will success if $D = 1$ and will fail otherwise. Let $P$ the probability that our solution will pass ($D = 1$). Then the failing probability is $1 - P$. We will apply Möbius inversion to calculate $P$: Let $f(x)$ the probability that $D$ is divisible by $x$. Then, $P=\\sum_{i=1}^{n}f(i)\\cdot\\mu(i)$ (where $ \\mu (x)$ is the Möbius function). Now we need to calculate $f(x)$. It can be shown that $D$ is divisible by $x$ if and only if $s_{i}\\equiv s_{i-1}(\\mathrm{\\boldmath~\\mod~}x)$ for all $2  \\le  i  \\le  k$. In other word, there is some $r$ from $0$ to $x - 1$ such that $s_{i}\\equiv r\\left(\\begin{array}{l}{{\\mathrm{mod}\\ x\\right)}}\\end{array}\\right.$ for all $1  \\le  i  \\le  k$. Let $g(r)$ the number of ways to select a subsequence $S$ such that $s_{i}\\equiv r\\left(\\begin{array}{l}{{\\mathrm{\\mod}\\ x\\right)}}\\end{array}\\right.$ for all $1  \\le  i  \\le  k$. Then, according to definition: $f(x)=\\frac{\\displaystyle\\sum_{r=0}^{x-1}g(r)}{\\displaystyle\\frac{\\displaystyle\\sum_{r=0}^{x-1}g(r)}{\\displaystyle\\mathrm{number~of~way~to~subsequence~}}s}.$ The denominator is simply $\\binom{k}{n}$. To calculate $g(r)$, notice that for each $i$, the value of $s_{i}$ can be $x \\cdot j + r$ for some integer $j$. In other word, $S$ must be a subsequence of the sequence $a_{r} = [r, x + r, 2x + r, ...]$. Let $q=\\left\\lfloor{\\frac{n}{x}}\\right\\rfloor$. If $r<n\\ \\ \\mathrm{mod}\\ x$, $a_{r}$ has $q + 1$ elements. Therefore, $g(r)={\\binom{k}{q+1}}$ If $n\\mathrm{\\mod\\}x\\leq r<x$, $a_{r}$ has $q$ elements. Therefore, $g(r)=\\left(k_{q}\\right)$. In summary: $f(x)={\\frac{\\sum_{r=0}^{x-1}g(r)}{\\binom{k}{n}}}={\\frac{(n{\\pmod{x}}\\cdot{\\binom{k}{q+1}}+(n-n\\mathrm{\\mod}\\ x)\\cdot\\binom{k}{q}}{k}}$ The complexity of this calculating method is $O(n)$. My implementation of the above method can be found here. Keep in mind to use a good random number generator and a seed which is hard to obtain, thus making your solution truly random and not falling into corner cases. Some of the tutorials of neal might be helpful: Don't use rand(): a guide to random number generators in C++ How randomized solutions can be hacked, and how to make your solution unhackable",
    "code": "#pragma comment(linker, \"/stack:247474112\")\n#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\nmt19937 rng32(chrono::steady_clock::now().time_since_epoch().count());\n\nint n, Max = -1000000000, d = 0;\nint queryRemaining = 60; vector<int> id;\n\nvoid findMax() {\n\tint top = -1000000000, bot = +1000000000;\n\twhile (top <= bot) {\n\t\tint hasHigher;\n\t\tint mid = (top + bot) / 2;\n\t\tcout << \"> \" << mid << endl;\n\t\tfflush(stdout); cin >> hasHigher;\n\t\tqueryRemaining--;\n\t\tif (hasHigher) top = mid + 1;\n\t\telse {bot = mid - 1; Max = mid;}\n\t}\n}\n\nvoid findD() {\n\tvector<int> List; int RandomRange = n;\n\twhile (queryRemaining > 0 && RandomRange > 0) {\n\t\tint demandedIndex = rng32() % RandomRange;\n\t\tcout << \"? \" << id[demandedIndex] << endl; fflush(stdout);\n\t\tint z; cin >> z; List.push_back(z);\n\t\tRandomRange--; queryRemaining--;\n\t\tswap(id[demandedIndex], id[RandomRange]);\n\t}\n\tsort(List.begin(), List.end());\n\tif (List.back() != Max) List.push_back(Max);\n\tfor (int i=1; i<List.size(); i++) {\n\t\td = __gcd(d, List[i] - List[i-1]);\n\t}\n}\n\nvoid Input() {\n\tcin >> n; id.resize(n);\n\tfor (int i=0; i<n; i++) id[i] = i+1;\n}\n\nvoid Solve() {\n\tfindMax(); findD();\n\tint Min = Max - d * (n - 1);\n\tcout << \"! \" << Min << \" \" << d;\n\tcout << endl; fflush(stdout);\n}\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0);\n\tInput(); Solve(); return 0;\n}",
    "tags": [
      "binary search",
      "interactive",
      "number theory",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1114",
    "index": "F",
    "title": "Please, another Queries on Array?",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$.\n\nYou need to perform $q$ queries of the following two types:\n\n- \"MULTIPLY l r x\" — for every $i$ ($l \\le i \\le r$) multiply $a_i$ by $x$.\n- \"TOTIENT l r\" — print $\\varphi(\\prod \\limits_{i=l}^{r} a_i)$ taken modulo $10^9+7$, where $\\varphi$ denotes Euler's totient function.\n\nThe Euler's totient function of a positive integer $n$ (denoted as $\\varphi(n)$) is the number of integers $x$ ($1 \\le x \\le n$) such that $\\gcd(n,x) = 1$.",
    "tutorial": "There's a few fundamentals about Euler's totient we need to know: $ \\phi (p) = p - 1$ and $ \\phi (p^{k}) = p^{k - 1} \\cdot (p - 1)$, provided $p$ is a prime number and $k$ is a positive integer. You can easily prove these equations through the definition of the function itself. Euler's totient is a multiplicative function. $f(x)$ is considered a multiplicative function when $\\operatorname*{gcd}(a,b)=1$ means $f(a) \\cdot f(b) = f(a \\cdot b)$. Keep in mind that we can rewrite $ \\phi (p^{k})$ as of following: $\\varphi(p^{k})=p^{k}\\cdot{\\frac{p-1}{p}}$. Let's denote $P$ as the set of prime factors of $\\prod_{i=l}^{r}a_{i}$. Thus, the answer for each query will simply be: $\\varphi(\\prod_{i=l}^{r}a_{i})=\\prod_{i=l}^{r}a_{i}\\cdot\\prod_{p\\in P}{\\frac{p-1}{p}}$. So, for each query we'll need to know the product of the elements, and which primes are included in that product. There are a few ways to work around with it. One of the most effective way is as following: Create a product segment tree to maintain the segment products. Since $\\prod_{p\\in P}{\\frac{p-1}{p}}$ only depends on the appearance or non-appearance of the primes, and the constraints guaranteed us to have at most $62$ prime factors, we can use bitmasks and an or-sum segment tree to maintain this part. Also, the bitmasks and range products can be maintained in a sqrt-decomposition fashion (please refer to GreenGrape's solution), making each query's complexity to be somewhat around $O\\left({\\sqrt{n}}\\right)$. Still, this complexity is quite high and surpassed time limit on a pretty thin margin. Complexity for initializing segment trees: $O\\left(n\\cdot\\log(n)\\right)$. Complexity for each update query: $O\\left(62+\\log^{2}(n)\\right)$. Complexity for each return query: $O\\left(62+\\log^{2}(n)\\right)$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#pragma GCC optimize(\"unroll-loops\")\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <unordered_set>\n#include <string>\n#include <map>\n#include <unordered_map>\n#include <random>\n#include <set>\n#include <cassert>\n#include <functional>\n#include <iomanip>\n#include <queue>\n#include <numeric>\n#include <bitset>\n#include <iterator>\n\nusing namespace std;\n\nconst int N = 100001;\n\nmt19937 gen(time(NULL));\n#define forn(i, n) for (int i = 0; i < n; i++)\n#define ford(i, n) for (int i = n - 1; i >= 0; i--)\n#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)\n#define all(a) (a).begin(), (a).end()\n#define pii pair<int, int>\n#define mp make_pair\n#define endl '\\n'\n#define vi vector<int>\n\ntypedef long long ll;\n\ntemplate<typename T = int>\ninline T read() {\n\tT val = 0, sign = 1; char ch;\n\tfor (ch = getchar(); ch < '0' || ch > '9'; ch = getchar())\n\t\tif (ch == '-') sign = -1;\n\tfor (; ch >= '0' && ch <= '9'; ch = getchar())\n\t\tval = val * 10 + ch - '0';\n\treturn sign * val;\n}\n\nconst int mod = 1e9 + 7;\nconst int phi = 1e9 + 6;\n\nconst int M = 301, B = 500;\nint P = 0;\n\ninline int mul(int a, int b) {\n\treturn (a * 1LL * b) % mod;\n}\n\nint mpow(int u, int p) {\n\tif (!p) return 1;\n\treturn mul(mpow(mul(u, u), p / 2), (p & 1) ? u : 1);\n}\n\nvector<int> primes;\nvector<int> pi;\n\nint pw[M];\nint lg[N];\n\nbool pr(int x) {\n\tif (x <= 1) return false;\n\tfor (int i = 2; i * i <= x; i++)\n\t\tif (x % i == 0)\n\t\t\treturn false;\n\treturn true;\n}\n\nvoid precalc() {\n\tforn(i, M)\n\t\tif (pr(i)) {\n\t\t\tprimes.push_back(i);\n\t\t\tP++;\n\t\t}\n\tpi.resize(P);\n\tforn(i, M) {\n\t\tint x = 1;\n\t\tforn(j, B) {\n\t\t\tx = mul(x, i);\n\t\t}\n\t\tpw[i] = x;\n\t}\n\n\tforn(i, P)\n\t\tpi[i] = mpow(primes[i], phi - 1);\n}\n\nstruct product_tree {\n\tvector<int> arr, block_product, block_update, single_update;\n\tint n;\n\n\tproduct_tree(vector<int>& a) : n(a.size()) {\n\t\tarr = a;\n\t\twhile (n % B) {\n\t\t\tn++, arr.push_back(1);\n\t\t}\n\t\tblock_product.resize(n / B, 1);\n\t\tblock_update.resize(n / B, -1);\n\t\tsingle_update.resize(n / B, -1);\n\n\t\tfor (int i = 0; i < n; i += B) {\n\t\t\tint x = 1;\n\t\t\tint pos = i / B;\n\t\t\tforn(j, B)\n\t\t\t\tx = mul(x, arr[i + j]);\n\t\t\tblock_product[pos] = x;\n\t\t}\n\t}\n\n\tinline void add(int& u, int x, int mode) {\n\t\tif (mode) {\n\t\t\tif (u == -1)\n\t\t\t\tu = x;\n\t\t\telse\n\t\t\t\tu = mul(u, x);\n\t\t}\n\t\telse {\n\t\t\tif (u == -1)\n\t\t\t\tu = pw[x];\n\t\t\telse\n\t\t\t\tu = mul(u, pw[x]);\n\t\t}\n\t}\n\n\tvoid update(int pos, int x) {\n\t\tadd(block_update[pos], x, 0);\n\t\tadd(single_update[pos], x, 1);\n\t}\n\n\tvoid reconstruct(int pos) {\n\t\tint e = single_update[pos];\n\t\tif (e == -1) return;\n\t\tint x = 1;\n\n\t\tint l = pos * B, r = l + B;\n\t\tfor (int i = l; i < r; i++) {\n\t\t\tarr[i] = mul(arr[i], e);\n\t\t\tx = mul(x, arr[i]);\n\t\t}\n\n\t\tsingle_update[pos] = block_update[pos] = -1;\n\t\tblock_product[pos] = x;\n\t}\n\n\tvoid apply(int l, int r, int x) {\n\t\tint L = l / B, R = r / B;\n\t\tif (L == R) {\n\t\t\treconstruct(L);\n\t\t\tfor (int i = l; i <= r; i++) {\n\t\t\t\tarr[i] = mul(arr[i], x);\n\t\t\t\tblock_product[L] = mul(block_product[L], x);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\treconstruct(L);\n\t\tfor (int i = l; i < (L + 1) * B; i++) {\n\t\t\tarr[i] = mul(arr[i], x);\n\t\t\tblock_product[L] = mul(block_product[L], x);\n\t\t}\n\t\treconstruct(R);\n\t\tfor (int i = R * B; i <= r; i++) {\n\t\t\tarr[i] = mul(arr[i], x);\n\t\t\tblock_product[R] = mul(block_product[R], x);\n\t\t}\n\t\tfor (int j = L + 1; j < R; j++)\n\t\t\tupdate(j, x);\n\t}\n\n\tint get(int l, int r) {\n\t\tint L = l / B, R = r / B;\n\t\tint ans = 1;\n\t\tif (L == R) {\n\t\t\treconstruct(L);\n\t\t\tfor (int i = l; i <= r; i++) {\n\t\t\t\tans = mul(ans, arr[i]);\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t\treconstruct(L);\n\t\tfor (int i = l; i < (L + 1) * B; i++) {\n\t\t\tans = mul(ans, arr[i]);\n\t\t}\n\t\treconstruct(R);\n\t\tfor (int i = R * B; i <= r; i++) {\n\t\t\tans = mul(ans, arr[i]);\n\t\t}\n\t\tfor (int j = L + 1; j < R; j++) {\n\t\t\tans = mul(ans, block_product[j]);\n\t\t\tif (block_update[j] != -1)\n\t\t\t\tans = mul(ans, block_update[j]);\n\t\t}\n\t\treturn ans;\n\t}\n};\n\nstruct prime_tree {\n\tvector<ll> t, d;\n\tint n;\n\n\tprime_tree(vector<ll>& a) : n(a.size()) {\n\t\tt.resize(4 * n);\n\t\td.resize(4 * n, -1);\n\t\tbuild(1, 0, n, a);\n\t}\n\n\tll build(int u, int l, int r, vector<ll>& a) {\n\t\tif (l == r - 1) {\n\t\t\treturn t[u] = a[l];\n\t\t}\n\t\tint m = (l + r) / 2;\n\t\treturn t[u] = build(u << 1, l, m, a) | build(u << 1 | 1, m, r, a);\n\t}\n\n\tinline void add(ll& u, ll x) {\n\t\tif (u == -1)\n\t\t\tu = x;\n\t\telse\n\t\t\tu |= x;\n\t}\n\n\tvoid push(int u, int l, int r) {\n\t\tif (d[u] == -1) return;\n\t\tt[u] |= d[u];\n\t\tif (r - l > 1) {\n\t\t\tadd(d[u << 1], d[u]);\n\t\t\tadd(d[u << 1 | 1], d[u]);\n\t\t}\n\t\td[u] = -1;\n\t}\n\n\tvoid update(int u, int l, int r, int L, int R, ll x) {\n\t\tpush(u, l, r);\n\t\tif (L >= R || l > L || r < R) return;\n\t\tif (l == L && r == R) {\n\t\t\tadd(d[u], x);\n\t\t\tpush(u, l, r);\n\t\t\treturn;\n\t\t}\n\t\tint m = (l + r) / 2;\n\t\tupdate(u << 1, l, m, L, min(m, R), x);\n\t\tupdate(u << 1 | 1, m, r, max(L, m), R, x);\n\n\t\tt[u] = t[u << 1] | t[u << 1 | 1];\n\t}\n\n\tll get(int u, int l, int r, int L, int R) {\n\t\tpush(u, l, r);\n\t\tif (L >= R || l > L || r < R) return 0;\n\t\tif (l == L && r == R) {\n\t\t\treturn t[u];\n\t\t}\n\t\tint m = (l + r) / 2;\n\t\treturn get(u << 1, l, m, L, min(m, R)) | get(u << 1 | 1, m, r, max(L, m), R);\n\t}\n\n\tll get(int l, int r) {\n\t\treturn get(1, 0, n, l, r + 1);\n\t}\n\tvoid apply(int l, int r, ll x) {\n\t\tupdate(1, 0, n, l, r + 1, x);\n\t}\n};\n\nll transform(int x) {\n\tll mask = 0;\n\tforn(i, P)\n\t\tif (x % primes[i] == 0) {\n\t\t\tmask |= (1LL << i);\n\t\t}\n\treturn mask;\n}\n\nvoid solve() {\n\tint n, q; cin >> n >> q;\n\n\tvi a(n);\n\tvector<ll> _a;\n\n\tfor (auto& v : a) {\n\t\tcin >> v;\n\t\t_a.push_back(transform(v));\n\t}\n\n\tauto Ptree = product_tree(a);\n\tauto Mtree = prime_tree(_a);\n\n\tint l, r, x;\n\tforn(i, q) {\n\t\tstring s; cin >> s;\n\t\tif (s == \"MULTIPLY\") {\n\t\t\tcin >> l >> r >> x;\n\t\t\tl--, r--;\n\t\t\tPtree.apply(l, r, x);\n\t\t\tMtree.apply(l, r, transform(x));\n\t\t}\n\t\telse {\n\t\t\tcin >> l >> r;\n\t\t\tl--, r--;\n\n\t\t\tint product = Ptree.get(l, r);\n\t\t\tll mask = Mtree.get(l, r);\n\n\t\t\tforn(j, 63)\n\t\t\t\tif (mask >> j & 1) {\n\t\t\t\t\tproduct = mul(product, primes[j] - 1);\n\t\t\t\t\tproduct = mul(product, pi[j]);\n\t\t\t\t}\n\n\t\t\tcout << product << endl;\n\t\t}\n\t}\n}\n\nsigned main() {\n\tint t = 1;\n\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\n\tprecalc();\n\n\twhile (t--) {\n\t\tclock_t z = clock();\n\t\tsolve();\n\t\tdebug(\"Total Time: %.3f\\n\", (double)(clock() - z) / CLOCKS_PER_SEC);\n\t}\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "divide and conquer",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1117",
    "index": "A",
    "title": "Best Subsegment",
    "statement": "You are given array $a_1, a_2, \\dots, a_n$. Find the subsegment $a_l, a_{l+1}, \\dots, a_r$ ($1 \\le l \\le r \\le n$) with maximum arithmetic mean $\\frac{1}{r - l + 1}\\sum\\limits_{i=l}^{r}{a_i}$ (in floating-point numbers, i.e. without any rounding).\n\nIf there are many such subsegments find the \\textbf{longest} one.",
    "tutorial": "There is a property of arithmetic mean: $\\frac{1}{k}\\sum\\limits_{i=1}^{k}{c_i} \\le \\max\\limits_{1 \\le i \\le k}{c_i}$ and the equality holds when $c_1 = c_2 = \\dots = c_k$. Obviously, we can always gain maximum arithmetic mean equal to $\\max\\limits_{1 \\le i \\le n}{a_i}$ by taking single maximum element from $a$. Considering the property above, we need to take only maximum elements in our subsegment, that's why we need to find the longest subsegment consisting only of maximum elements.",
    "code": "#include<iostream>\nusing namespace std;\n\nint main() {\n\tint n; cin >> n;\n\tint mx = -1, lenMx = 0;\n\t\n\tint curEl = -1, curLen = 0;\n\tfor(int i = 0; i < n; i++) {\n\t\tint a; cin >> a;\n\t\t\n\t\tif(curEl != a)\n\t\t\tcurEl = a, curLen = 0;\n\t\tcurLen++;\n\t\t\n\t\tif(mx < curEl)\n\t\t\tmx = curEl, lenMx = 0;\n\t\tif(mx == curEl)\n\t\t\tlenMx = max(lenMx, curLen);\n\t}\n\tcout << lenMx << endl;\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1117",
    "index": "B",
    "title": "Emotes",
    "statement": "There are $n$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $i$-th emote increases the opponent's happiness by $a_i$ units (we all know that emotes in this game are used to make opponents happy).\n\nYou have time to use some emotes only $m$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you \\textbf{cannot use the same emote more than $k$ times in a row} (otherwise the opponent will think that you're trolling him).\n\n\\textbf{Note that two emotes $i$ and $j$ ($i \\ne j$) such that $a_i = a_j$ are considered different}.\n\nYou have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.",
    "tutorial": "It is obvious that we always can use only two emotes with maximum $a_i$. Let their values be $x$ and $y$ ($x \\ge y$). We have to solve the problem by some formula. The best way to use emotes - use the emote with the value $x$ $k$ times, then use the emotion with the value $y$, then again use the emote with value $x$ $k$ times, and so on. So the \"cycle\" has length $k+1$, and we can use the emote with the value $x$ the remaining number of times. So the answer is $\\lfloor\\frac{m}{k+1}\\rfloor \\cdot (x \\cdot k + y) + (m \\% (k + 1)) \\cdot x$, where $x$ is the first maximum of $a$, $y$ is the second maximum of $a$, $\\lfloor\\frac{p}{q}\\rfloor$ is $p$ divided by $q$ rounded down, and $p \\% q$ is $p$ modulo $q$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\t\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.rbegin(), a.rend());\n\t\n\tcout << m / (k + 1) * 1ll * (a[0] * 1ll * k + a[1]) + m % (k + 1) * 1ll * a[0] << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1117",
    "index": "C",
    "title": "Magic Ship",
    "statement": "You a captain of a ship. Initially you are standing in a point $(x_1, y_1)$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $(x_2, y_2)$.\n\nYou know the weather forecast — the string $s$ of length $n$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $s_1$, the second day — $s_2$, the $n$-th day — $s_n$ and $(n+1)$-th day — $s_1$ again and so on.\n\nShip coordinates change the following way:\n\n- if wind blows the direction U, then the ship moves from $(x, y)$ to $(x, y + 1)$;\n- if wind blows the direction D, then the ship moves from $(x, y)$ to $(x, y - 1)$;\n- if wind blows the direction L, then the ship moves from $(x, y)$ to $(x - 1, y)$;\n- if wind blows the direction R, then the ship moves from $(x, y)$ to $(x + 1, y)$.\n\nThe ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $(x, y)$ it will move to the point $(x - 1, y + 1)$, and if it goes the direction U, then it will move to the point $(x, y + 2)$.\n\nYou task is to determine the minimal number of days required for the ship to reach the point $(x_2, y_2)$.",
    "tutorial": "Note, that if we can reach the destination in $x$ days, so we can reach it in $y \\ge x$ days, since we can stay in the destination point by moving to the opposite to the wind direction. So, we can binary search the answer. To check the possibility to reach the destination point $(x_2, y_2)$ in $k$ days we should at first look at the position $(x_3, y_3)$ the wind moves ship to. Now we can calculate where we can go: since each day we can move in one of four directions or not move at all, we can reach any point $(x, y)$ with Manhattan distance $|x - x_3| + |y - y_3| \\le k$. So we need to check that $|x_2 - x_3| + |y_2 - y_3| \\le k$. To calculate $(x_3, y_3)$ we can note, that there were $\\lfloor \\frac{k}{n} \\rfloor$ full cycles and $k \\bmod n$ extra days. So it can be calculated with $O(1)$ time using prefix sums. Finally, about borders of binary search: to reach the destination point we need to move closer at least by one (it terms of Manhattan distance) from the full cycle of the wind. So, if answer exists then it doesn't exceed $(|x_1 - x_2| + |y_1 - y_2|) \\cdot n \\le 2\\cdot 10^{14}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n\nconst int N = 100009;\n\npair<int, int> st, fi;\nint n;\nstring s;\n\nstring mv = \"UDLR\";\nint dx[] = {0, 0, -1, 1};\nint dy[] = {1, -1, 0, 0};\n\npair<int, int> d[N];\n\nint main(){\n\tcin >> st.x >> st.y >> fi.x >> fi.y;\n\tcin >> n >> s;\t\t\n\n\tfor(int i = 0; i < n; ++i){\n\t\tint id = -1;\n\t\tfor(int j = 0; j < 4; ++j)\n\t\t\tif(mv[j] == s[i])\n\t\t\t\tid = j;\n\t\tassert(id != -1);\n\t\td[i + 1] = make_pair(d[i].x + dx[id], d[i].y + dy[id]);\n\t}\n\n\tlong long l = 0, r = 1e18;\n\twhile(r - l > 1){\n\t\tlong long mid = (l + r) / 2;\n\t\tlong long cnt = mid / n, rem = mid % n;\n\t\tlong long x = st.x + d[rem].x + cnt *  1LL * d[n].x;\n\t\tlong long y = st.y + d[rem].y + cnt *  1LL * d[n].y;\n\t\tlong long dist = abs(x - fi.x) + abs(y - fi.y);\n\t\tif(dist <= mid)\n\t\t\tr = mid;\n\t\telse\n\t\t\tl = mid;\t\n\t} \n\n\tif(r > 5e17) r = -1;\n\tcout << r << endl;\n\n\treturn 0;\n}",
    "tags": [
      "binary search"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1117",
    "index": "D",
    "title": "Magic Gems",
    "statement": "Reziba has many magic gems. Each magic gem can be split into $M$ normal gems. The amount of space each magic (and normal) gem takes is $1$ unit. A normal gem cannot be split.\n\nReziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is $N$ units. If a magic gem is chosen and split, it takes $M$ units of space (since it is split into $M$ gems); if a magic gem is not split, it takes $1$ unit.\n\nHow many different configurations of the resulting set of gems can Reziba have, such that the total amount of space taken is $N$ units? Print the answer modulo $1000000007$ ($10^9+7$). Two configurations are considered different if the number of magic gems Reziba takes to form them differs, or the indices of gems Reziba has to split differ.",
    "tutorial": "Let's reformulate the solution to the form of dynamic programming. $dp_n$ - the number of ways to split the gems so that the total amount of space taken is $n$. Then there are obvious transitions of either splitting the last gem or not. $dp_n = dp_{n - m} + dp_{n - 1}$. And that can be easily rewritten in such a way that matrix exponentiation becomes the solution. Overall complexity: $O(m^3 \\cdot \\log n)$.",
    "code": "#include<bits/stdc++.h>\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define MOD 1000000007\n#define MOD9 1000000009\n#define pi 3.1415926535\n#define ms(s, n) memset(s, n, sizeof(s))\n#define prec(n) fixed<<setprecision(n)\n#define eps 0.000001\n#define all(v) v.begin(), v.end()\n#define allr(v) v.rbegin(), v.rend()\n#define bolt ios::sync_with_stdio(0)\n#define light cin.tie(0);cout.tie(0)\n#define forr(i,p,n) for(ll i=p;i<n;i++)\n#define MAXN 1000003\ntypedef long long ll;\nusing namespace std;\nll mult(ll a,ll b, ll p=MOD){return ((a%p)*(b%p))%p;}\nll add(ll a, ll b, ll p=MOD){return (a%p + b%p)%p;}\nll fpow(ll n, ll k, ll p = MOD) {ll r = 1; for (; k; k >>= 1) {if (k & 1) r = r * n%p; n = n * n%p;} return r;}\nll inv(ll a, ll p = MOD) {return fpow(a, p - 2, p);}\nll inv_euclid(ll a, ll m = MOD){ll m0 = m;ll y = 0, x = 1;if (m == 1)return 0;while (a > 1){ll q = a / m;ll t = m;m = a % m, a = t;t = y;y = x - q * y;x = t;}if (x < 0)x += m0;return x;}\n\nll bin[103][103];\n\nvoid mult_mat(ll m, ll ans[][100], ll bin[][100]){\n    ll mult[m][m];\n    forr(i,0,m){\n        forr(j,0,m){\n            mult[i][j]=0;\n            forr(k,0,m){\n                mult[i][j]+=ans[i][k]*bin[k][j];\n                if(mult[i][j]>=MOD){\n                    mult[i][j]%=MOD;\n                }\n            }\n        }\n    }\n    forr(i,0,m){\n        forr(j,0,m){\n            ans[i][j]=mult[i][j];\n        }\n    }\n}\n\nvoid pow_mat(ll n, ll fin[][100], ll m){\n    ll ans[m][100];\n    ll b[m][100];\n    forr(i,0,m){\n        forr(j,0,m){\n            ans[i][j]=bin[i][j];\n            b[i][j]=bin[i][j];\n        }\n    }\n    n--;\n    while(n>0){\n        if(n%2==1){\n            mult_mat(m,ans,b);\n            n--;\n        }else{\n            n=n/2;\n            mult_mat(m,b,b);\n        }\n    }\n    forr(i,0,m){\n        forr(j,0,m){\n            fin[i][j]=ans[i][j];\n        }\n    }\n}\n\nint main(){\n    bolt;\n    ll n,m;\n    cin>>n>>m;\n    bin[0][0]=1;\n    bin[0][m-1]=1;\n    for(ll i=1;i<m;i++){\n        bin[i][i-1]=1;\n    }\n    if(n<m){\n        cout<<1<<\"\\n\";\n    }else{\n        ll fin[m+1][100];\n        pow_mat(n-m+1,fin,m);\n        ll ans=0;\n        forr(i,0,m){\n            ans+=fin[0][i];\n            if(ans>=MOD){\n                ans-=MOD;\n            }\n        }\n        cout<<ans<<\"\\n\";\n    }\n}",
    "tags": [
      "dp",
      "math",
      "matrices"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1117",
    "index": "E",
    "title": "Decypher the String",
    "statement": "\\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.\n\nYou are given a string $t$ consisting of $n$ lowercase Latin letters. This string was cyphered as follows: initially, the jury had a string $s$ consisting of $n$ lowercase Latin letters. Then they applied a sequence of no more than $n$ (possibly zero) operations. $i$-th operation is denoted by two integers $a_i$ and $b_i$ ($1 \\le a_i, b_i \\le n$), and means swapping two elements of the string with indices $a_i$ and $b_i$. All operations were done in the order they were placed in the sequence. For example, if $s$ is xyz and $2$ following operations are performed: $a_1 = 1, b_1 = 2$; $a_2 = 2, b_2 = 3$, then after the first operation the current string is yxz, and after the second operation the current string is yzx, so $t$ is yzx.\n\nYou are asked to restore the original string $s$. Unfortunately, you have no information about the operations used in the algorithm (you don't even know if there were any operations in the sequence). But you may run the same sequence of operations on any string you want, provided that it contains only lowercase Latin letters and its length is $n$, and get the resulting string after those operations.\n\nCan you guess the original string $s$ asking the testing system to run the sequence of swaps no more than $3$ times?\n\n\\textbf{The string $s$ and the sequence of swaps are fixed in each test; the interactor doesn't try to adapt the test to your solution}.",
    "tutorial": "Since a sequence of swaps denotes some permutation, let's try to restore the permutation $p$ that was used to transform $s$ into $t$, and then get $s$ by applying inverse permutation. If $n$ was $26$ or less, then we could get $p$ just by asking one query: send a string where no character occurs twice, and the resulting positions of characters uniquely determine the permutation. Unfortunately, $n$ may be greater than $26$ - but we can ask more than one query. The main idea is the following: for each index $i \\in [1, n]$, we may choose a triple of characters, so all triples are distinct. There are $26^3$ different triples, and that's greater than $10^4$, so each index can be uniquely determined. Then, after we choose a triple for each index, ask three queries as follows: in the first query, the $i$-th character of the string is the first character in the triple representing index $i$; in the second query we use the second characters from all triples, and in the third query - the third characters. Let $s_1$, $s_2$ and $s_3$ be the strings we sent, and $t_1$, $t_2$ and $t_3$ be the strings we received as answers. The permutation maps index $i$ to index $j$ if and only if $s_1[i] = t_1[j]$, $s_2[i] = t_2[j]$ and $s_3[i] = t_3[j]$ - because if some other index is mapped to $j$, then at least one of the aforementioned equalities is false since all triples of characters are distinct. Using this fact, we may recover the permutation $p$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tstring t;\n\tcin >> t;\n\tint n = t.size();\n\tstring s1(n, 'a'), s2(n, 'a'), s3(n, 'a');\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\ts1[i] = char('a' + (i % 26));\n\t\ts2[i] = char('a' + ((i / 26) % 26));\n\t\ts3[i] = char('a' + ((i / 26 / 26) % 26));\n\t}\n\tcout << \"? \" << s1 << endl;\n\tstring t1;\n\tcin >> t1;\n\tcout << \"? \" << s2 << endl;\n\tstring t2;\n\tcin >> t2;\n\tcout << \"? \" << s3 << endl;\n\tstring t3;\n\tcin >> t3;\n\tvector<int> p(n);\n\tfor(int i = 0; i < n; i++)\n\t\tp[i] = (t1[i] - 'a') + (t2[i] - 'a') * 26 + (t3[i] - 'a') * 26 * 26;\n\tstring s(n, 'a');\n\tfor(int i = 0; i < n; i++)\n\t\ts[p[i]] = t[i];\n\tcout << \"! \" << s << endl;\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "chinese remainder theorem",
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1117",
    "index": "F",
    "title": "Crisp String",
    "statement": "You are given a string of length $n$. Each character is one of the first $p$ lowercase Latin letters.\n\nYou are also given a matrix $A$ with binary values of size $p \\times p$. This matrix is symmetric ($A_{ij} = A_{ji}$). $A_{ij} = 1$ means that the string can have the $i$-th and $j$-th letters of Latin alphabet adjacent.\n\nLet's call the string crisp if \\textbf{all of the adjacent characters} in it can be adjacent (have 1 in the corresponding cell of matrix $A$).\n\nYou are allowed to do the following move. Choose any letter, remove \\textbf{all its occurrences} and join the remaining parts of the string without changing their order. For example, removing letter 'a' from \"abacaba\" will yield \"bcb\".\n\nThe string you are given is crisp. The string should remain crisp \\textbf{after every move you make}.\n\nYou are allowed to do arbitrary number of moves (possible zero). What is the shortest resulting string you can obtain?",
    "tutorial": "Each state of the string can be denoted as the set of characters we deleted from it, and each such set can be represented as a $p$-bit binary mask, where $i$-th bit is equal to $0$ if $i$-th character of the alphabet is already deleted, and $1$ otherwise. Let's call a mask bad if the string formed by this mask is not crisp. Let's also say that a pair of characters $a, b$ forbids mask $m$ if $a, b$ is a pair of characters that should not be adjacent, but they are adjacent in the string formed by mask $m$. If we somehow find all bad masks, then the solution would be writing simple bitmask dp to find the best mask that is not bad and reachable from the initial mask (the one having all bits set to $1$). So let's focus on finding all bad masks. Obviously, if some pair of characters forbids a mask, then it's bad, and vice versa. Let's pick some pair of characters $a, b$ and find all masks forbidden by it (we will do the same for every pair of characters that cannot be adjacent). Let's check every occurence of $a$ in the initial string. For each occurence, we will find the closest occurence of $b$ to the right of it. If there's no any, or if there's another $a$ between them, let's ignore the occurence of $a$ we have chosen and move to the next one. Otherwise, let's find all characters that occur at least once between the fixed occurences of $a$ and $b$. If all those characters are deleted, then these occurences of $a$ and $b$ will be adjacent - so pair $a, b$ forbids any mask that has bits representing $a$ and $b$ set to $1$, bits representing every character occuring in between to $0$, and all other bits to any values. Let's mark all these masks as forbidden as follows: we will write a recursive function $mark(m, a, b)$ that marks mask $m$ and every its submask that has bits $a$ and $b$ set to $1$ as forbidden. This function should check if $m$ is not forbidden; if not, then mark it as forbidden, iterate on the bit $i$ we may remove from $m$, and call $mark(m \\oplus 2^i, a, b)$ recursively (but only if $i$ is set to $1$ in mask $m$, and if $i \\ne a$ and $i \\ne b$). If we implement it in such a way, then for each pair $a, b$, it will take $O(n + p 2^p)$ operations to mark all masks forbidden by this pair of characters, so overall complexity will be $O(np^2 + p^3 2^p)$ or $O(np + p^3 2^p)$, depending on your implementation.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 100 * 1000 + 13;\nconst int P = 17;\n\nint n, p;\nstring s;\nint A[P][P];\nvector<int> pos[P];\nint pr[P][N];\nbitset<(1 << P)> legal, cur, dp;\nint cnt[P];\n\nint main() {\n\tscanf(\"%d%d\", &n, &p);\n\tchar buf[N];\n\tscanf(\"%s\", buf);\n\ts = buf;\n\tforn(i, p) forn(j, p)\n\t\tscanf(\"%d\", &A[i][j]);\n\t\n\tforn(i, n){\n\t\tpos[s[i] - 'a'].push_back(i);\n\t\tforn(j, p)\n\t\t\tpr[j][i + 1] = pr[j][i] + (s[i] == 'a' + j);\n\t}\n\t\n\tlegal.reset();\n\tlegal.flip();\n\t\n\tint fl = (1 << p) - 1;\n\tforn(c, p) forn(d, c + 1){\n\t\tif (A[c][d]) continue;\n\t\tcur.reset();\n\t\tcur.flip();\n\t\tint i = 0, j = 0;\n\t\twhile (i < pos[c].size() && j < pos[d].size()){\n\t\t\tif (c == d && i == j){\n\t\t\t\t++j;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint mask = 0;\n\t\t\tif (pos[c][i] < pos[d][j]){\n\t\t\t\tforn(e, p) if ((pr[e][pos[d][j]] - pr[e][pos[c][i] + 1]) != 0)\n\t\t\t\t\tmask |= (1 << e);\n\t\t\t\t++i;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tforn(e, p) if ((pr[e][pos[c][i]] - pr[e][pos[d][j] + 1]) != 0)\n\t\t\t\t\tmask |= (1 << e);\n\t\t\t\t++j;\n\t\t\t}\n\t\t\tif ((mask >> c) & 1) continue;\n\t\t\tif ((mask >> d) & 1) continue;\n\t\t\tcur[mask ^ fl] = 0;\n\t\t}\n\t\tfor (int mask = fl; mask > 0; --mask){\n\t\t\tif (cur[mask]) continue;\n\t\t\tforn(e, p) if (c != e && d != e && ((mask >> e) & 1))\n\t\t\t\tcur[mask ^ (1 << e)] = 0;\n\t\t}\n\t\tlegal &= cur;\n\t}\n\t\n\tdp[fl] = 1;\n\tfor (int mask = fl; mask > 0; --mask){\n\t\tif (!dp[mask]) continue;\n\t\tforn(i, p) if ((mask >> i) & 1){\n\t\t\tint nmask = mask ^ (1 << i);\n\t\t\tif (dp[nmask]) continue;\n\t\t\tdp[nmask] = legal[nmask];\n\t\t}\n\t}\n\t\n\tforn(i, n)\n\t\t++cnt[s[i] - 'a'];\n\t\n\tint ans = n;\n\tforn(mask, 1 << p) if (dp[mask]){\n\t\tint cur = 0;\n\t\tforn(i, p) if ((mask >> i) & 1)\n\t\t\tcur += cnt[i];\n\t\tans = min(ans, cur);\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1117",
    "index": "G",
    "title": "Recursive Queries",
    "statement": "You are given a permutation $p_1, p_2, \\dots, p_n$. You should answer $q$ queries. Each query is a pair $(l_i, r_i)$, and you should calculate $f(l_i, r_i)$.\n\nLet's denote $m_{l, r}$ as the position of the maximum in subsegment $p_l, p_{l+1}, \\dots, p_r$.\n\nThen $f(l, r) = (r - l + 1) + f(l, m_{l,r} - 1) + f(m_{l,r} + 1, r)$ if $l \\le r$ or $0$ otherwise.",
    "tutorial": "Let's denote $fl(l, r) = (m_{l,r} - l) + fl(l, m_{l,r} - 1) + fl(m_{l,r} + 1, r)$ and, analogically, $fr(l, r) = (r - m_{l,r}) + fr(l, m_{l,r} - 1) + fr(m_{l,r} + 1, r)$. Then, we can note that $f(l, r) = (r - l + 1) + fl(l, r) + fr(l, r)$. So we can switch to calculating $fl$ (and $fr$). Let's $lf[i]$ be the closest from the left to $i$ element such that $a[lf[i]] > a[i]$. To calculate $fl(l, r)$ we will look from the other side: we will look at it as the sum of lengths of segments induced by each element from $[l, r]$. Each element $a_i$ ($l \\le i \\le r)$ will add to $fl(l, r)$ value equal to $\\min(i - lf[i] - 1, i - l)$, or a piecewise linear function if we look at $l$ as a variable. And $fl(l, r)$ is a value of a sum of linear functions induced by $a[i]$ in a point $x = l$. To process it efficiently we can one by one add induced linear functions to the corresponding subsegments using BIT or Segment Tree and if we've added functions induced by $a[k]$ we can calculate answer for all queries which looks like $(l_i, k)$. To calculate $fr(l, r)$ we can just reverse array and all queries. Result time complexity is $O((n + q) \\log{n})$. Note, that it's still works quite slow, so you should use fast data structures like BIT of iterative segment tree.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nint n, q;\nvector<int> a;\nvector< pair<pt, int> > qs;\n\ninline bool read() {\n\tif(!(cin >> n >> q))\n\t\treturn false;\n\ta.resize(n);\n\tqs.resize(q);\n\t\n\tfore(i, 0, n)\n\t\tcin >> a[i];\n\tfore(i, 0, q) {\n\t\tcin >> qs[i].x.x;\n\t\tqs[i].x.x--;\n\t}\n\tfore(i, 0, q) {\n\t\tcin >> qs[i].x.y;\n\t\tqs[i].x.y--;\n\t\tqs[i].y = i;\n\t}\n\treturn true;\n}\n\nbool cmp(const pair<pt, int> &a, const pair<pt, int> &b) {\n\tif(a.x.y != b.x.y)\n\t\treturn a.x.y < b.x.y;\n\tif(a.x.x != b.x.x)\n\t\treturn a.x.x < b.x.x;\n\treturn a.y < b.y;\n}\n\ntypedef pair<li, li> func;\nfunc operator +=(func &a, const func &b) {\n\ta.x += b.x, a.y += b.y;\n\treturn a;\n}\n\nvector<func> t;\nvoid add(int l, int r, const func &f) {\n\tfor(l += n, r += n; l < r; l >>= 1, r >>= 1) {\n\t\tif(l & 1) t[l++] += f;\n\t\tif(r & 1) t[--r] += f;\n\t}\n}\nfunc sum(int pos) {\n\tfunc ans(0, 0);\n\tfor(pos += n; pos > 0; pos >>= 1)\n\t\tans += t[pos];\n\treturn ans;\n}\n\ninline void solve() {\n\tvector<li> ans(q, 0);\n\tfore(i, 0, q)\n\t\tans[i] = qs[i].x.y - qs[i].x.x + 1;\n\tfore(_, 0, 2) {\n\t\tvector<int> st;\n\t\tvector<int> lf(n, -1);\n\t\tfore(i, 0, n) {\n\t\t\twhile(!st.empty() && a[st.back()] < a[i])\n\t\t\t\tst.pop_back();\n\t\t\tif(!st.empty())\n\t\t\t\tlf[i] = st.back();\n\t\t\tst.push_back(i);\n\t\t}\n\t\t\n\t\tsort(qs.begin(), qs.end(), cmp);\n\t\tt.assign(2 * n, {0, 0});\n\t\t\n\t\tint uk = 0;\n\t\tfore(i, 0, n) {\n\t\t\tadd(0, lf[i] + 1, {0, i - lf[i] - 1});\n\t\t\tadd(lf[i] + 1, i, {-1, i});\n\t\t\t\n\t\t\twhile(uk < q && qs[uk].x.y == i) {\n\t\t\t\tauto f = sum(qs[uk].x.x);\n\t\t\t\tans[qs[uk].y] += f.x * qs[uk].x.x + f.y;\n\t\t\t\tuk++;\n\t\t\t}\n\t\t}\n\t\t\n\t\treverse(a.begin(), a.end());\n\t\tfor(auto &p : qs) {\n\t\t\tp.x.x = n - 1 - p.x.x;\n\t\t\tp.x.y = n - 1 - p.x.y;\n\t\t\tswap(p.x.x, p.x.y);\n\t\t}\n\t}\n\tfor(auto v : ans)\n\t\tcout << v << ' ';\n\tcout << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1118",
    "index": "A",
    "title": "Water Buying",
    "statement": "Polycarp wants to cook a soup. To do it, he needs to buy exactly $n$ liters of water.\n\nThere are only two types of water bottles in the nearby shop — $1$-liter bottles and $2$-liter bottles. There are infinitely many bottles of these two types in the shop.\n\nThe bottle of the first type costs $a$ burles and the bottle of the second type costs $b$ burles correspondingly.\n\nPolycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $n$ liters of water in the nearby shop if the bottle of the first type costs $a$ burles and the bottle of the second type costs $b$ burles.\n\nYou also have to answer $q$ independent queries.",
    "tutorial": "The answer can be calculated by easy formula: $\\lfloor\\frac{n}{2}\\rfloor \\cdot min(2a, b) + (n~ \\%~ 2) \\cdot a$, where $\\lfloor\\frac{x}{y}\\rfloor$ is $x$ divided by $y$ rounded down and $x~ \\%~ y$ is $x$ modulo $y$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\t\n\tfor (int i = 0; i < q; ++i) {\n\t\tlong long n;\n\t\tint a, b;\n\t\tcin >> n >> a >> b;\n\t\tcout << (n / 2) * min(2 * a, b) + (n % 2) * a << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1118",
    "index": "B",
    "title": "Tanya and Candies",
    "statement": "Tanya has $n$ candies numbered from $1$ to $n$. The $i$-th candy has the weight $a_i$.\n\nShe plans to eat exactly $n-1$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, \\textbf{exactly one candy per day}.\n\nYour task is to find the number of such candies $i$ (let's call these candies \\textbf{good}) that if dad gets the $i$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.\n\nFor example, $n=4$ and weights are $[1, 4, 3, 3]$. Consider all possible cases to give a candy to dad:\n\n- Tanya gives the $1$-st candy to dad ($a_1=1$), the remaining candies are $[4, 3, 3]$. She will eat $a_2=4$ in the first day, $a_3=3$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $4+3=7$ and in even days she will eat $3$. Since $7 \\ne 3$ this case shouldn't be counted to the answer (this candy isn't \\textbf{good}).\n- Tanya gives the $2$-nd candy to dad ($a_2=4$), the remaining candies are $[1, 3, 3]$. She will eat $a_1=1$ in the first day, $a_3=3$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $3$. Since $4 \\ne 3$ this case shouldn't be counted to the answer (this candy isn't \\textbf{good}).\n- Tanya gives the $3$-rd candy to dad ($a_3=3$), the remaining candies are $[1, 4, 3]$. She will eat $a_1=1$ in the first day, $a_2=4$ in the second day, $a_4=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $4$. Since $4 = 4$ this case \\textbf{should be counted} to the answer (this candy is \\textbf{good}).\n- Tanya gives the $4$-th candy to dad ($a_4=3$), the remaining candies are $[1, 4, 3]$. She will eat $a_1=1$ in the first day, $a_2=4$ in the second day, $a_3=3$ in the third day. So in odd days she will eat $1+3=4$ and in even days she will eat $4$. Since $4 = 4$ this case \\textbf{should be counted} to the answer (this candy is \\textbf{good}).\n\nIn total there $2$ cases which should counted (these candies are \\textbf{good}), so the answer is $2$.",
    "tutorial": "Let's maintain four variables $oddPref$, $evenPref$, $oddSuf$ and $evenSuf$, which will mean the sum of $a_i$ with odd $i$ on prefix, even $i$ on prefix, odd $i$ on suffix and even $i$ on suffix. Initially, $oddPref$ and $evenPref$ are $0$, $oddSuf$ equals to the sum of $a_i$ with odd $i$ in a whole array and $evenSuf$ equals to the sum of $a_i$ with even $i$ in a whole array. Let's iterate from left to right over all elements of the array. Let's consider the current element $a_i$. If $i$ is even, then set $evenSuf := evenSuf - a_i$, otherwise let's set $oddSuf := oddSuf - a_i$. Then let's consider we give the current candy to dad. Then we have to increase the answer if $oddPref = evenSuf$ and $evenPref = oddSuf$. Then if $i$ is even then let's set $evenPref := evenPref + a_i$, otherwise let's set $oddPref := oddPref + a_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint n;\n\tcin >> n;\n\t\n\tvector<int> a(n);\n\t\n\tint ePref = 0, oPref = 0, eSuf = 0, oSuf = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\tif (i & 1) eSuf += a[i];\n\t\telse oSuf += a[i];\n\t}\n\t\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (i & 1) eSuf -= a[i];\n\t\telse oSuf -= a[i];\n\t\tif (ePref + oSuf == oPref + eSuf) {\n\t\t\t++ans;\n\t\t}\n\t\tif (i & 1) ePref += a[i];\n\t\telse oPref += a[i];\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1118",
    "index": "C",
    "title": "Palindromic Matrix",
    "statement": "Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.\n\nFor example, the following matrices are \\textbf{palindromic}:\n\nThe following matrices are \\textbf{not palindromic} because they change after the order of rows is reversed:\n\nThe following matrices are \\textbf{not palindromic} because they change after the order of columns is reversed:\n\nYou are given $n^2$ integers. Put them into a matrix of $n$ rows and $n$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print \"NO\".",
    "tutorial": "Basically, what does the matrix being palindromic imply? For each $i, j$ values in cells $(i, j)$, $(i, n - j - 1)$, $(n - i - 1, j)$ and $(n - i - 1, n - j - 1)$ are equal (all zero-indexed). You can easily prove it by reversing the order of rows or columns and checking the overlapping cells in them. Thus, all cells can be split up into equivalence classes. The even $n$ case is simple: all classes have size $4$. The odd $n$ case has classes of sizes $1$, $2$ and $4$. Let's fill the classes one by one. Obviously, the order between the classes of the same size doesn't matter. I claim that filling the classes in order $4, 2, 1$ in sizes construct the answer if any exists. The key observation is that each next size is divisible by the previous one. The implementation can come in lots of different forms and complexities. Mine works in $O(MAXVAL + n^2)$, you can refer to it in attachment.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\ntypedef pair<int, int> pt;\n\nconst int N = 1000 + 7;\n\nint cnt[N];\nint a[20][20];\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tforn(i, n * n){\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\t++cnt[x];\n\t}\n\t\n\tvector<pair<int, pt>> cells;\n\tforn(i, (n + 1) / 2) forn(j, (n + 1) / 2){\n\t\tif (i != n - i - 1 && j != n - j - 1)\n\t\t\tcells.push_back({4, {i, j}});\n\t\telse if ((i != n - i - 1) ^ (j != n - j - 1))\n\t\t\tcells.push_back({2, {i, j}});\n\t\telse\n\t\t\tcells.push_back({1, {i, j}});\n\t}\n\t\n\tfor (auto cur : {4, 2, 1}){\n\t\tint lst = 1;\n\t\tfor (auto it : cells){\n\t\t\tif (it.first != cur) continue;\n\t\t\tint i = it.second.first;\n\t\t\tint j = it.second.second;\n\t\t\twhile (lst < N && cnt[lst] < cur)\n\t\t\t\t++lst;\n\t\t\tif (lst == N){\n\t\t\t\tputs(\"NO\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\ta[i][j] = a[n - i - 1][j] = a[i][n - j - 1] = a[n - i - 1][n - j - 1] = lst;\n\t\t\tcnt[lst] -= cur;\n\t\t}\n\t}\n\t\n\tputs(\"YES\");\n\tforn(i, n){\n\t\tforn(j, n)\n\t\t\tprintf(\"%d \", a[i][j]);\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1118",
    "index": "D1",
    "title": "Coffee and Coursework (Easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the constraints}.\n\nPolycarp has to write a coursework. The coursework consists of $m$ pages.\n\nPolycarp also has $n$ cups of coffee. The coffee in the $i$-th cup has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in \\textbf{any order}. Polycarp drinks each cup \\textbf{instantly} and \\textbf{completely} (i.e. he cannot split any cup into several days).\n\nSurely, courseworks are not usually being written in a single day (in a perfect world of Berland, at least). Some of them require multiple days of hard work.\n\nLet's consider some day of Polycarp's work. Consider Polycarp drinks $k$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $a_{i_1}, a_{i_2}, \\dots, a_{i_k}$. Then the first cup he drinks gives him energy to write $a_{i_1}$ pages of coursework, the second cup gives him energy to write $max(0, a_{i_2} - 1)$ pages, the third cup gives him energy to write $max(0, a_{i_3} - 2)$ pages, ..., the $k$-th cup gives him energy to write $max(0, a_{i_k} - k + 1)$ pages.\n\nIf Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.\n\nPolycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.",
    "tutorial": "Since the number of days doesn't exceed $n$, let's iterate over this value (from $1$ to $n$). So now we have to check (somehow), if the current number of days is enough to write a coursework. Let the current number of days be $k$. The best way to distribute first cups of coffee for each day is to take $k$ maximums in the array. Then we have to distribute second cups for each day. Let's also take the next $k$ maximums in the remaining array, and so on. How do we can calculate such a thing easily? Let's sort the array $a$ in the reversed order (before iterating over all numbers of days), then the following formula will work fine for the current number of days $k$: $\\sum\\limits_{i=1}^{n}max(0, a_i - \\lfloor\\frac{i - 1}{k}\\rfloor)$. So if the value of the formula above is greater than or equal to $m$ then the current number of days is enough. If there is no any suitable number of days, the answer is -1.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\t\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.rbegin(), a.rend());\n\t\n\tfor (int i = 1; i <= n; ++i) {\n\t\tint sum = 0;\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tsum += max(a[j] - j / i, 0);\n\t\t}\n\t\tif (sum >= m) {\n\t\t\tcout << i << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << -1 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1118",
    "index": "D2",
    "title": "Coffee and Coursework (Hard Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the constraints}.\n\nPolycarp has to write a coursework. The coursework consists of $m$ pages.\n\nPolycarp also has $n$ cups of coffee. The coffee in the $i$-th cup Polycarp has $a_i$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in \\textbf{any order}. Polycarp drinks each cup \\textbf{instantly} and \\textbf{completely} (i.e. he cannot split any cup into several days).\n\nSurely, courseworks are not being written in a single day (in a perfect world of Berland, at least).\n\nLet's consider some day of Polycarp's work. Consider Polycarp drinks $k$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $a_{i_1}, a_{i_2}, \\dots, a_{i_k}$. Then the first cup he drinks gives him energy to write $a_{i_1}$ pages of coursework, the second cup gives him energy to write $max(0, a_{i_2} - 1)$ pages, the third cup gives him energy to write $max(0, a_{i_3} - 2)$ pages, ..., the $k$-th cup gives him energy to write $max(0, a_{i_k} - k + 1)$ pages.\n\nIf Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.\n\nPolycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.",
    "tutorial": "Well, the main idea is described in the previous (D1) problem editorial. Read it firstly. So, now we have to improve our solution somehow. How can we do it? Wait... What is it? We iterate over all numbers of days... And the number of pages Polycarp can write when we consider $k+1$ days instead of $k$ is strictly increases... (because we always can drink any cup even with the minimum value of $a_i$ as a first during the new day, and the number of pages will increase). So, what is it? Oh, this is binary search! So all we need is to replace linear search to binary search, submit the written code and get AC.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nvector<int> a;\n\nbool can(int i) {\n\tlong long sum = 0; // there can be a bug\n\tfor (int j = 0; j < n; ++j) {\n\t\tsum += max(a[j] - j / i, 0);\n\t}\n\treturn sum >= m;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m;\n\t\n\ta = vector<int>(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.rbegin(), a.rend());\n\t\n\tint l = 1, r = n;\n\twhile (r - l > 1) {\n\t\tint mid = (l + r) >> 1;\n\t\tif (can(mid)) r = mid;\n\t\telse l = mid;\n\t}\n\t\n\tif (can(l)) cout << l << endl;\n\telse if (can(r)) cout << r << endl;\n\telse cout << -1 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1118",
    "index": "E",
    "title": "Yet Another Ball Problem",
    "statement": "The king of Berland organizes a ball! $n$ pair are invited to the ball, they are numbered from $1$ to $n$. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from $1$ to $k$, inclusive.\n\nLet $b_i$ be the color of the man's costume and $g_i$ be the color of the woman's costume in the $i$-th pair. You have to choose a color for each dancer's costume (i.e. values $b_1, b_2, \\dots, b_n$ and $g_1, g_2, \\dots g_n$) in such a way that:\n\n- for every $i$: $b_i$ and $g_i$ are integers between $1$ and $k$, inclusive;\n- there are no two completely identical pairs, i.e. no two indices $i, j$ ($i \\ne j$) such that $b_i = b_j$ and $g_i = g_j$ at the same time;\n- there is no pair such that the color of the man's costume is the same as the color of the woman's costume in this pair, i.e. $b_i \\ne g_i$ for every $i$;\n- for each two consecutive (adjacent) pairs both man's costume colors and woman's costume colors differ, i.e. for every $i$ from $1$ to $n-1$ the conditions $b_i \\ne b_{i + 1}$ and $g_i \\ne g_{i + 1}$ hold.\n\nLet's take a look at the examples of bad and good color choosing (for $n=4$ and $k=3$, man is the first in a pair and woman is the second):\n\nBad color choosing:\n\n- $(1, 2)$, $(2, 3)$, $(3, 2)$, $(1, 2)$ — contradiction with the second rule (there are equal pairs);\n- $(2, 3)$, $(1, 1)$, $(3, 2)$, $(1, 3)$ — contradiction with the third rule (there is a pair with costumes of the same color);\n- $(1, 2)$, $(2, 3)$, $(1, 3)$, $(2, 1)$ — contradiction with the fourth rule (there are two consecutive pairs such that colors of costumes of men/women are the same).\n\nGood color choosing:\n\n- $(1, 2)$, $(2, 1)$, $(1, 3)$, $(3, 1)$;\n- $(1, 2)$, $(3, 1)$, $(2, 3)$, $(3, 2)$;\n- $(3, 1)$, $(1, 2)$, $(2, 3)$, $(3, 2)$.\n\nYou have to find \\textbf{any} suitable color choosing or say that no suitable choosing exists.",
    "tutorial": "The first observation: we cannot construct more than $k(k-1)$ pairs at all due to second and third rules. The second observation: we always can construct an answer which will contain all $k(k-1)$ pairs (and get some prefix of this answer if we need less than $k(k-1)$ pairs). Ho do we do that? Let man's costumes colors be in the following order: $1, 2, \\dots, k; 1, 2, \\dots, k; 1, 2, \\dots, k$ and so on. Now we have to set some colors to woman's costumes. The first thing comes to mind is to use some cyclic shift of $1, 2, \\dots, k$. And it is the best thing we can do! So let women's costumes colors be in the following order: $2, 3, \\dots, k, 1; 3, 4, \\dots, k, 1, 2; 4, 5, \\dots, k, 1, 2, 3$ ans so on. So we use each cyclic shift of $1, 2, \\dots, k$ in order from second to last. The maximum number of pairs can be obtained when $k=447$ and the number of such pairs is $n=199362$. So now we have to prove that second, third and fourth rules are satisfied (or write a stress test, it is not so hard to do it). The easiest way to prove all rules are satisfied is the following: if some element $x$ in the left part has position $i$ (let's consider all positions modulo $k$) then each element $x$ in the right part will have all positions expect $i$ in order $i-1, i-2, \\dots, i-k+1$ (you can see it from our placement). Now we can see that all rules are satisfied because of such a placement.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\t\n\tif (n > k * 1ll * (k - 1)) {\n\t\tcout << \"NO\" << endl;\n\t} else {\n\t\tcout << \"YES\" << endl;\n\t\tint cur = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcur += (i % k == 0);\n\t\t\tcout << i % k + 1 << \" \" << (cur + i % k) % k + 1 << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1118",
    "index": "F1",
    "title": "Tree Cutting (Easy Version)",
    "statement": "You are given an undirected tree of $n$ vertices.\n\nSome vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.\n\nYou choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.\n\nHow many nice edges are there in the given tree?",
    "tutorial": "Let's root the tree by some vertex. The edge $(v, u)$, where $v$ is the parent of $u$, is now nice if and only if the subtree of $u$ contains either all red vertices of the tree and no blue vertices or all blue vertices of the tree and no red vertices. That's because removing that edge splits the tree into the subtree of $u$ and the component of every other vertex. Thus, the task is to calculate the number of red and blue vertices in each subtree with dfs and check a couple of conditions. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 300 * 1000 + 13;\n\nint n;\nint a[N];\nvector<int> g[N];\nint red, blue;\nint ans;\n\npair<int, int> dfs(int v, int p = -1){\n\tint r = (a[v] == 1), b = (a[v] == 2);\n\tfor (auto u : g[v]) if (u != p){\n\t\tauto tmp = dfs(u, v);\n\t\tans += (tmp.first == red && tmp.second == 0);\n\t\tans += (tmp.first == 0 && tmp.second == blue);\n\t\tr += tmp.first;\n\t\tb += tmp.second;\n\t}\n\treturn make_pair(r, b);\n}\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\t\n\tforn(i, n){\n\t\tscanf(\"%d\", &a[i]);\n\t\tred += (a[i] == 1);\n\t\tblue += (a[i] == 2);\n\t}\n\t\n\tforn(i, n - 1){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\t\n\tans = 0;\n\tdfs(0);\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1118",
    "index": "F2",
    "title": "Tree Cutting (Hard Version)",
    "statement": "You are given an undirected tree of $n$ vertices.\n\nSome vertices are colored one of the $k$ colors, some are uncolored. It is guaranteed that the tree contains at least one vertex of each of the $k$ colors. There might be no uncolored vertices.\n\nYou choose a subset of \\textbf{exactly $k - 1$ edges} and remove it from the tree. Tree falls apart into $k$ connected components. Let's call this subset of edges nice if none of the resulting components contain vertices of different colors.\n\nHow many nice subsets of edges are there in the given tree? Two subsets are considered different if there is some edge that is present in one subset and absent in the other.\n\nThe answer may be large, so print it modulo $998244353$.",
    "tutorial": "Okay, this solution is really complicated and I would like to hear nicer approaches from you in comments if you have any. However, I still feel like it's ok to have this problem in a contest specifically as a harder version of F1. Let's start with the following thing. Root the tree by some vertex. For each color take all vertices of this color and paint their lowest common ancestor the same color as them. The purpose of that will come clear later. Why can we do this? The case with lca = some vertex of that color is trivial. Now, take a look at the edges from lca to its subtrees. At least two of them contain a vertex of that color. You can't cut the edges to these subtrees because this will make vertices of the same color belong to different components. Thus, lca will always be in the same component as these vertices. If lca is already painted the other color then the answer is 0. That's because lca once again make vertices of the same color belong to different components. Now everything will be calculated in a single dfs. Let $dfs(v)$ return one of the following values: $0$, if there is no colored vertex in the subtree of $v$; $x$, if there exists some color $x$ such that vertex $v$ has vertices of color $x$ in its subtree and vertex $v$ has ancestors of color $x$ (not necesserily direct parent); $-1$, otherwise. I claim that if there are multiple suitable colors for some vertex $v$ then the answer is 0. Let's take a look at any two of them and call them colors $x_1$ and $x_2$. For both colors take a path from arbitrary vertex of that color in subtree to arbitrary vertex of that color that is ancestor of $v$. You can't cut any edge on these paths because that will divide the vertices of the same color. Now, either path for color $x_1$ contains vertex of color $x_2$ or path for color $x_2$ contains vertex of color $x_1$. That vertex is the upper end of the corresponding path. That means that component of one color includes the vertex of the other color, which is impossible. Moreover, that's the last specific check for the answer being 0. The step with lca helped us to move to the ancestor instead of any vertex in the upper subtree of $v$. I truly believe that you can avoid lca in this solution, however, that will make both implementation and proof harder. Now let's do $dp[v][2]$ - the number of ways to cut some edges in the subtree of $v$ so that: 0 - the component with vertex $v$ has no colored vertices in it, 1 - has some colored vertices. Generally, the color itself for 1 doesn't matter. If for some child $u$ of $v$: $dfs(u)$ returned color $x$ then it must be color $x$ in that component, otherwise the color doesn't matter. For $-1$ all vertices of each color presented in the subtree of $u$ are contained within the subtree of $u$. The transitions will be of form \"do we cut the edge from $v$ to $u$ or not\" for all children $u$ of $v$. That is the most tedious part so I'm sorry if I mess up something the way I did with my author solution :D Here from now I'll ignore the children that returned $0$ (if I say all children, I will mean all non-zero returning children) as they add nothing to the answer. If there are no children, then the vertices with $a_v = 0$ will have $dp[v][0] = 1$, $dp[v][1] = 0$ and the other vertices will have $dp[v][0] = 0$, $dp[v][1] = 1$. Basically, there are two main cases. I would recommend to follow the code in attachment while reading this, tbh. $a_v = 0$ and all children dfs returned $-1$. Then for each edge to the child you can either cut it if there are colored vertices (take $dp[u][1]$) or don't cut it if it has no colored vertices (take $dp[u][0]$). So $dp[v][0] = \\prod \\limits_{u \\in g(v)} (dp[u][0] + dp[u][1])$. For $v$ to have some color you'll need to push that color from exactly one of the children. You can't choose two subtrees because they are guaranteed to have different colors in them (otherwise they wouldn't return $-1$). So $dp[v][1] = \\sum \\limits_{x \\in g(v)} \\prod \\limits_{u \\in g(v), u \\ne x} dp[x][1] \\cdot (dp[u][0] + dp[u][1])$. To calculate that fast enough you'll need to precalculate prefix and suffix products of $(dp[u][0] + dp[u][1])$. $a_v \\ne 0$ or $a_v = 0$ but some children returned the same value $x \\ne -1$. Then you are required to make $v$ the part of component with vertices of color $x$. That means that $dp[v][0] = 0$ for that case. For children, who returned $x$, you don't cut their edge (take $dp[u][1]$). For the other children you can either cut it if there are colored vertices (take $dp[u][1]$) or don't cut it if it has no colored vertices (take $dp[u][0]$). Thus, $dp[v][1] = (\\prod \\limits_{u \\in g(v), dfs(u) = -1} (dp[u][0] + dp[u][1])) \\cdot (\\prod \\limits_{u \\in g(v), dfs(u) \\ne -1} dp[u][1])$. The answer will be stored in $dp[root][1]$ after that. Overall complexity: $O(n \\log n)$ but I'm sure this can be rewritten in such a manner that it becomes $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 300 * 1000 + 13;\nconst int LOGN = 19;\nconst int MOD = 998244353;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\nint a[N];\nvector<int> g[N];\nint up[N][LOGN];\nint d[N];\n\nvoid init(int v, int p = -1){\n\tfor (auto u : g[v]) if (u != p){\n\t\tup[u][0] = v;\n\t\tfor (int i = 1; i < LOGN; ++i)\n\t\t\tup[u][i] = up[up[u][i - 1]][i - 1];\n\t\td[u] = d[v] + 1;\n\t\tinit(u, v);\n\t}\n}\n\nint lca(int v, int u){\n\tif (d[v] < d[u]) swap(v, u);\n\tfor (int i = LOGN - 1; i >= 0; --i)\n\t\tif (d[up[v][i]] >= d[u])\n\t\t\tv = up[v][i];\n\tif (v == u) return v;\n\tfor (int i = LOGN - 1; i >= 0; --i)\n\t\tif (up[v][i] != up[u][i]){\n\t\t\tv = up[v][i];\n\t\t\tu = up[u][i];\n\t\t}\n\treturn up[v][0];\n}\n\nint l[N];\nint dp[N][2];\n\nint dfs(int v, int p = -1){\n\tvector<pair<int, int>> cur;\n\tfor (auto u : g[v]) if (u != p){\n\t\tint c = dfs(u, v);\n\t\tif (c != 0)\n\t\t\tcur.push_back(make_pair(c, u));\n\t}\n\t\n\tvector<int> vals;\n\tforn(i, cur.size()) if (cur[i].first > 0)\n\t\tvals.push_back(cur[i].first);\n\t\n\tsort(vals.begin(), vals.end());\n\tvals.resize(unique(vals.begin(), vals.end()) - vals.begin());\n\t\n\tif (int(vals.size()) > 1){\n\t\tputs(\"0\");\n\t\texit(0);\n\t}\n\t\n\tif (a[v] != 0 && !vals.empty() && vals[0] != a[v]){\n\t\tputs(\"0\");\n\t\texit(0);\n\t}\n\t\n\tif (a[v] == 0 && cur.empty())\n\t\treturn 0;\n\t\n\tif (a[v] == 0 && vals.empty()){\t\t\n\t\tvector<int> pr(1, 1), su(1, 1);\n\t\tforn(i, cur.size())\n\t\t\tpr.push_back(mul(pr.back(), add(dp[cur[i].second][0], dp[cur[i].second][1])));\n\t\tfor (int i = int(cur.size()) - 1; i >= 0; --i)\n\t\t\tsu.push_back(mul(su.back(), add(dp[cur[i].second][0], dp[cur[i].second][1])));\n\t\treverse(su.begin(), su.end());\n\t\tdp[v][1] = 0;\n\t\tforn(i, cur.size())\n\t\t\tdp[v][1] = add(dp[v][1], mul(mul(pr[i], su[i + 1]), dp[cur[i].second][1]));\n\t\tdp[v][0] = add(dp[v][0], pr[cur.size()]);\n\t\treturn -1;\n\t}\n\t\n\tdp[v][1] = 1;\n\tfor (auto it : cur){\n\t\tif (it.first == -1)\n\t\t\tdp[v][1] = mul(dp[v][1], add(dp[it.second][0], dp[it.second][1]));\t\n\t\telse\n\t\t\tdp[v][1] = mul(dp[v][1], dp[it.second][1]);\n\t}\n\t\n\tif (a[v] == 0)\n\t\treturn vals[0];\n\t\n\treturn (l[a[v]] == v ? -1 : a[v]);\n}\n\nint main() {\n\tint n, k;\n\tscanf(\"%d%d\", &n, &k);\n\t\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tforn(i, n - 1){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\t\n\tinit(0);\n\t\n\tmemset(l, -1, sizeof(l));\n\tforn(i, n) if (a[i] != 0)\n\t\tl[a[i]] = (l[a[i]] == -1 ? i : lca(l[a[i]], i));\n\t\n\tfor (int i = 1; i <= k; ++i){\n\t\tif (a[l[i]] != 0 && a[l[i]] != i){\n\t\t\tputs(\"0\");\n\t\t\texit(0);\n\t\t}\n\t\ta[l[i]] = i;\n\t}\n\t\n\tdfs(0);\n\t\n\tprintf(\"%d\\n\", dp[0][1]);\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1119",
    "index": "A",
    "title": "Ilya and a Colorful Walk",
    "statement": "Ilya lives in a beautiful city of Chordalsk.\n\nThere are $n$ houses on the street Ilya lives, they are numerated from $1$ to $n$ from left to right; the distance between every two neighboring houses is equal to $1$ unit. The neighboring houses are $1$ and $2$, $2$ and $3$, ..., $n-1$ and $n$. The houses $n$ and $1$ are not neighboring.\n\nThe houses are colored in colors $c_1, c_2, \\ldots, c_n$ so that the $i$-th house is colored in the color $c_i$. Everyone knows that Chordalsk is not boring, so there are at least two houses colored in different colors.\n\nIlya wants to select two houses $i$ and $j$ so that $1 \\leq i < j \\leq n$, and they have different colors: $c_i \\neq c_j$. He will then walk from the house $i$ to the house $j$ the distance of $(j-i)$ units.\n\nIlya loves long walks, so he wants to choose the houses so that the distance between them is the maximum possible.\n\nHelp Ilya, find this maximum possible distance.",
    "tutorial": "It is enough to find the last color different from the $c_1$ and the first color different from $c_n$ and print the maximum of the two distances.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1119",
    "index": "B",
    "title": "Alyona and a Narrow Fridge",
    "statement": "Alyona has recently bought a miniature fridge that can be represented as a matrix with $h$ rows and $2$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part.\n\n\\begin{center}\n{\\small An example of a fridge with $h = 7$ and two shelves. The shelves are shown in black. The picture corresponds to the first example.}\n\\end{center}\n\nAlyona has $n$ bottles of milk that she wants to put in the fridge. The $i$-th bottle is $a_i$ cells tall and $1$ cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can \\textbf{not} put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.\n\nAlyona is interested in the largest integer $k$ such that she can put bottles $1$, $2$, ..., $k$ in the fridge at the same time. Find this largest $k$.",
    "tutorial": "For a fixed set of bottles the optimal way to put them in the fridge is to sort them in decreasing order and then put the tallest next to the second tallest, the third next to the fourth and so on. The total required height is then $h_1 + h_3 + h_5 + \\ldots$, where $h$ is the sorted array of heights. Now just try all possible $k$, sort the heights of the first $k$ bottles, and output the last $k$ when the bottles fit. The total complexity is $O(n^2 \\log{n})$. Bonus 1: solve the problem in $O(n \\log^2{n})$. Bonus 2: solve the problem in $O(n \\log{n})$. Aleks5d invites you to compete in the shortest solution challenge for this problem. His code (155 bytes):",
    "code": "[n, k], arr = [int(i) for i in input().split()], [int(i) for i in input().split()]\nprint([i for i in range(n + 1) if sum(sorted(arr[0:i])[::-2]) <= k][-1])",
    "tags": [
      "binary search",
      "flows",
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1119",
    "index": "C",
    "title": "Ramesses and Corner Inversion",
    "statement": "Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.\n\nYou are given two matrices $A$ and $B$ of size $n \\times m$, each of which consists of $0$ and $1$ only. You can apply the following operation to the matrix $A$ arbitrary number of times: take any \\textbf{submatrix} of the matrix $A$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $0$, will be replaced by $1$, and all corners of the submatrix that contain $1$, will be replaced by $0$). You have to answer whether you can obtain the matrix $B$ from the matrix $A$.\n\n\\begin{center}\n{\\small An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow.}\n\\end{center}\n\nRamesses don't want to perform these operations by himself, so he asks you to answer this question.\n\nA submatrix of matrix $M$ is a matrix which consist of all elements which come from one of the rows with indices $x_1, x_1+1, \\ldots, x_2$ of matrix $M$ and one of the columns with indices $y_1, y_1+1, \\ldots, y_2$ of matrix $M$, where $x_1, x_2, y_1, y_2$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$, where the cell $(i,j)$ denotes the cell on the intersection of the $i$-th row and the $j$-th column.",
    "tutorial": "One can notice that the operation does not change the total parity of the matrix. So, if the total parity of $A$ and $B$ do not match, then the answer is No. However, this is not the only case when the answer is no. You can also notice that the operation does not change the total parity of each row/column independently. Thus, if in at least one row or column the parity of $A$ and $B$ do not match, then the answer is No. It turns out that if all these parities match, then the answer is Yes. We will prove this constructing a sequence of operations that transforms $A$ to $B$ whenever parities in all rows and column match. Let's perform an operation $(1, 1, x, y)$ for all such $x > 1$ and $y > 1$ that $A_{xy} \\ne B_{xy}$. After all these operations the whole matrices except maybe the first column and the first row match. But the first column and the first row also match because of the parity! So $A$ is now $B$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1119",
    "index": "D",
    "title": "Frets On Fire",
    "statement": "Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.\n\nIn return, the fleas made a bigger ukulele for her: it has $n$ strings, and each string has $(10^{18} + 1)$ frets numerated from $0$ to $10^{18}$. The fleas use the array $s_1, s_2, \\ldots, s_n$ to describe the ukulele's tuning, that is, the pitch of the $j$-th fret on the $i$-th string is the integer $s_i + j$.\n\nMiyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.\n\nEach question is in the form of: \"How many different pitches are there, if we consider frets between $l$ and $r$ (inclusive) on all strings?\"\n\nMiyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!\n\nFormally, you are given a matrix with $n$ rows and $(10^{18}+1)$ columns, where the cell in the $i$-th row and $j$-th column ($0 \\le j \\le 10^{18}$) contains the integer $s_i + j$. You are to answer $q$ queries, in the $k$-th query you have to answer the number of distinct integers in the matrix from the $l_k$-th to the $r_k$-th columns, inclusive.",
    "tutorial": "Let's sort all $s_i$'s in ascending order. This does not affect the answers, but now we notice that for some $i$, as soon as $r - l$ exceeds $s_{i+1} - s_i$ we don't need to consider row $i$ any more. This is because from then on, any integer that appears in row $i$ also appears in row $i + 1$. Taking this observation one step further, we approach the problem considering the contribution of row $i$, i.e. the number of integers that appear in the queried range in row $i$, but not row $i + 1$. The answer to a query is the sum of contributions of all rows. From this definition we know that the contribution of row $i$ is $\\min\\{s_{i+1} - s_i, r - l + 1\\}$ for $1 \\leq i < n$ and $r - l + 1$ for $i = n$. In other words, it is $\\min\\{d_i, w\\}$, where $d_i = s_{i+1} - s_i$, $d_n = +\\infty$ and $w = r - l + 1$. Now come the queries. Given a fixed value of $w$, we need to quickly compute $\\left(\\sum_{i=1}^{n=1} \\min\\{d_i, w\\}\\right) + w$. From another perspective, this equals the sum of value times the number of occurrences, namely $\\left(\\sum_{k=0}^w k \\cdot \\mathrm{count}(k)\\right) + \\left(\\sum_{k=w+1}^\\infty w \\cdot \\mathrm{count}(k)\\right) + w$, where $\\mathrm{count}(k)$ denotes the number of times that integer $k$ occurs in $d_{1 \\ldots n-1}$. This problem can be solved by representing $\\mathrm{count}(*)$ values with an array, combined with partial sums. However, as $d_i$ (and thus the size of such array) can be as large as $10^{18}$, it's required to compress the coordinates (discretize) and find desired indices with binary search. Please refer to the model solution attached below. The overall time complexity is $\\mathcal O((n + q) \\log n)$.",
    "code": "#include <cstdio>\n#include <algorithm>\n\nstatic const int MAXN = 1e5;\n\nstatic int n, q;\nstatic long long s[MAXN];\nstatic long long t[MAXN];\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) scanf(\"%lld\", &s[i]);\n\n    std::sort(s, s + n);\n    for (int i = 0; i < n - 1; ++i) s[i] = s[i + 1] - s[i];\n    std::sort(s, s + n - 1);\n    for (int i = n - 1; i >= 1; --i) s[i] = s[i - 1];\n    s[0] = 0;\n    for (int i = 1; i < n; ++i)\n        t[i] = t[i - 1] + (s[i] - s[i - 1]) * (n + 1 - i);\n\n    scanf(\"%d\", &q);\n    for (int i = 0; i < q; ++i) {\n        long long l, r;\n        scanf(\"%lld%lld\", &l, &r);\n        l = r - l + 1;\n        int p = std::lower_bound(s, s + n, l) - &s[0] - 1;\n        printf(\"%lld%c\", t[p] + (l - s[p]) * (n - p), i == q - 1 ? '\\n' : ' ');\n    }\n\n    return 0;\n}",
    "tags": [
      "binary search",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1119",
    "index": "E",
    "title": "Pavel and Triangles",
    "statement": "Pavel has several sticks with lengths equal to powers of two.\n\nHe has $a_0$ sticks of length $2^0 = 1$, $a_1$ sticks of length $2^1 = 2$, ..., $a_{n-1}$ sticks of length $2^{n-1}$.\n\nPavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.\n\nIt is forbidden to break sticks, and each triangle should consist of exactly three sticks.\n\nFind the maximum possible number of triangles.",
    "tutorial": "First, possible triangles have sides $(2^i, 2^j, 2^j)$ where $i \\le j$. There are several correct greedies to finish the solution, let's discuss one of them. The greedy is to loop through the values of $j$ in increasing order, then first try to match as many pairs $(j, j)$ to some unmatched $i$ as possible, after that create as many triples $(j, j, j)$ as possible and continue to the next $j$. To prove correctness, let's take our solution and one of the optimal solutions. Let's find the first difference in them if we consider the triples in the same order as our solutions considers them. There can be only one type of difference: we take some triple while the optimal solution skippes it. It can't be be the other way around because we always take a triple if there is one. So there are a few cases now: the triple is $(i, j, j)$ where $i < j$. Let's see where the corresponding $i$, $j$ and $j$ are used in the optimal solution: all three are used in different triples: $(t_1, k_1, k_1)$, $(t_2, k_2, k_2)$, $(t_3, k_3, k_3)$, $\\{t_1, t_2, t_3\\} = \\{i, j, j\\}$, $j \\le k_1 \\le k_2 \\le k_3$. Remove these triples and replace them with $(i, j, j)$, $(k_1, k_2, k_2)$, $(k_1, k_3, k_3)$. two are used in the same triple, one in another: the only case is $(i, k, k)$, $(j, j, j)$, $j < k$. Remove these, add $(i, j, j)$ and $(j, k, k)$. two of them are used in different triples, one not used: $(t_1, k_1, k_1)$, $(t_2, k_2, k_2)$, $\\{t_1, t_2\\} \\subset \\{i, j, j\\}$, $j \\le k_1 \\le k_2$. Remove these triples, replace with $(i, j, j)$ and $(k_1, k_2, k_2)$. two of them are used in the same triple, one not used: the only case is $(j, j, j)$. Remove this, add $(i, j, j)$. one of them in used in some triple, two are not used: $(t, k, k)$, $t \\in \\{i, j, j\\}$, $j \\le k$. Remove this, add $(i, j, j)$. none of them is used. This is not possible because it is the optimal solution. all three are used in different triples: $(t_1, k_1, k_1)$, $(t_2, k_2, k_2)$, $(t_3, k_3, k_3)$, $\\{t_1, t_2, t_3\\} = \\{i, j, j\\}$, $j \\le k_1 \\le k_2 \\le k_3$. Remove these triples and replace them with $(i, j, j)$, $(k_1, k_2, k_2)$, $(k_1, k_3, k_3)$. two are used in the same triple, one in another: the only case is $(i, k, k)$, $(j, j, j)$, $j < k$. Remove these, add $(i, j, j)$ and $(j, k, k)$. two of them are used in different triples, one not used: $(t_1, k_1, k_1)$, $(t_2, k_2, k_2)$, $\\{t_1, t_2\\} \\subset \\{i, j, j\\}$, $j \\le k_1 \\le k_2$. Remove these triples, replace with $(i, j, j)$ and $(k_1, k_2, k_2)$. two of them are used in the same triple, one not used: the only case is $(j, j, j)$. Remove this, add $(i, j, j)$. one of them in used in some triple, two are not used: $(t, k, k)$, $t \\in \\{i, j, j\\}$, $j \\le k$. Remove this, add $(i, j, j)$. none of them is used. This is not possible because it is the optimal solution. the triple is $(j, j, j)$. Let's see where these $j$s are used. They can only be used in three different triples $(j, k_1, k_1)$, $(j, k_2, k_2)$, $(j, k_3, k_3)$, $j \\le k_1 \\le k_2 \\le k_3$. Remove these triples and replace them with $(j, j, j)$, $(k_1, k_2, k_2)$, $(k_1, k_3, k_3)$.",
    "tags": [
      "brute force",
      "dp",
      "fft",
      "greedy",
      "ternary search"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1119",
    "index": "F",
    "title": "Niyaz and Small Degrees",
    "statement": "Niyaz has a tree with $n$ vertices numerated from $1$ to $n$. A tree is a connected graph without cycles.\n\nEach edge in this tree has strictly positive integer weight. A degree of a vertex is the number of edges adjacent to this vertex.\n\nNiyaz does not like when vertices in the tree have too large degrees. For each $x$ from $0$ to $(n-1)$, he wants to find the smallest total weight of a set of edges to be deleted so that degrees of all vertices become at most $x$.",
    "tutorial": "First, let's learn how to solve for a fixed $x$ in $O(n \\log n)$. We can calculate the dp on subtrees, $dp_{v, flag}$, denoting the minimum total weight of edges to be removed, if we consider the subtree of the vertex $v$, and $flag$ is zero, if the vertex has the degree $\\leq x$, and one, if $\\leq x+1$. Then to recalculate it you need to sort the children by $dp_{to, 1} - dp_{to, 0}$, and add to the sum $dp_{to, 0}$ $(deg_v - (x + flag))$ minimum values, depending on $flag$ which we consider for the dp answer for the vertex $v$. Then, it is obvious that the sum of degrees in the tree is equal to twice the number of edges, which is $2(n-1)$. It follows that the sum of all $x$ values <<number of vertices, with degree $\\geq x$>>, equal to the sum of degrees, is also $2(n-1)$. Therefore, if for each $x$ we will know how to answer the query, for the time of the order of the number of vertices with a sufficiently large degree, we will solve the problem. Let's call a vertex interesting if its degree is $> x$. We will support the forest only on interesting vertices, and also in some data structure (for example, two heaps perfectly fit this) for each interesting vertex of the weight of edges to the uninteresting. Then, to calculate the same dynamics for each vertex in the forest, it is enough to iterate over how many edges from it down to interesting vertices we will take (in the forest $\\leq$ <<number of interesting vertices>> $- 1$ edges, so we can iterate over it). And also add to the answer the sum of a sufficient number of edges in uninteresting vertices from the data structure. This solution works for <<number of interesting vertices>> $\\cdot \\log$, and all necessary data structures can also be maintained as $x$ increases. In total, we got the solution for $O(n \\log n)$.",
    "tags": [
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1119",
    "index": "G",
    "title": "Get Ready for the Battle",
    "statement": "Recently Evlampy installed one interesting computer game, one of aspects of which is to split army into several groups and then fight with enemy's groups. Let us consider a simplified version of the battle.\n\nIn the nearest battle Evlampy should fight an enemy army that consists of $m$ groups, the $i$-th of which has $hp_i$ health points.\n\nEvlampy's army consists of $n$ equal soldiers. Before each battle he should split his army in exactly $m$ groups (possibly, empty) so that the total size of the groups is $n$. The battle is played step-by-step. On each step each of Evlampy's groups attacks exactly one enemy group. Thus, each step is described with an array of $m$ integers $a_1, a_2, \\ldots, a_m$, meaning that the $i$-th Evlampy's group attacks the $a_i$-th enemy group. Different groups can attack same group, on each step the array $a$ is chosen independently.\n\nAfter each step the health points of each enemy group decreases by the total number of soldiers in Evlampy's groups that attacked this enemy group at this step. Enemy group is destroyed once its health points are zero or negative. Evlampy's soldiers do not lose health.\n\n\\begin{center}\n{\\small An example of a step. The numbers in green circles represent the number of soldiers in Evlampy's groups, the arrows represent attacks, the numbers in red circles represent health points of enemy groups, the blue numbers represent how much the health points will decrease after the step.}\n\\end{center}\n\nEvlampy understands that the upcoming battle will take the whole night. He became sad because this way he won't have enough time to finish his homework. Now Evlampy wants you to write a program that will help him win in the smallest possible number of steps. Can you help him?\n\nIn other words, find the smallest number of steps needed to destroy all enemy groups and show a possible way of doing this. Find the requires splitting of the army into $m$ groups and the arrays $a$ for each step.",
    "tutorial": "Note that on each turn the total health of enemy groups decreases by $n$. When all groups are destroyed, their health does not exceed $0$, and thus the answer is at least $\\left\\lceil{\\frac{\\sum_{i=1}^n hp_i}{n}}\\right\\rceil$. Now let's construct a way to win in this number of steps. Let's emulate the battle and split the soldiers in groups at the same time. Let's start with one group $n$, and attack the first enemy on each step. Once its health becomes less than $n$, say $k_1$, let's assume that some of our groups have total size exactly $k_1$ and they attack the first enemy on this step, while all the other groups start attacking the second enemy. After that let's attack the second enemy with all $n$ soldiers until its health is $k_2 < n$. Let's assume that some of our groups have total size $k_2$ and they attack the second soldier on this step, while the other groups start attacking the third. Continue with this process until all enemies are destroyed. We won't add the constraint on $k_n$, we will just assume that all soldiers attack the last enemy on the last step. Note that the total number of steps is exactly $\\left\\lceil{\\frac{\\sum_{i=1}^n hp_i}{n}}\\right\\rceil$, because we have \"extra\" hits only on the very last step. Now we have $m - 1$ assumptions of type \"some of our groups have total size $k_i$\". It's easy to satisfy them by sorting $k_i$ and stating that the $i$-th groups has size $k_i - k_{i - 1}$. This way the first $i$ groups will have size $k_i$ (after sorting). In order to reconstruct the attacks we have to simulate the process again.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1119",
    "index": "H",
    "title": "Triple",
    "statement": "You have received your birthday gifts — $n$ triples of integers! The $i$-th of them is $\\lbrace a_{i}, b_{i}, c_{i} \\rbrace$. All numbers are greater than or equal to $0$, and strictly smaller than $2^{k}$, where $k$ is a fixed integer.\n\nOne day, you felt tired playing with triples. So you came up with three new integers $x$, $y$, $z$, and then formed $n$ arrays. The $i$-th array consists of $a_i$ repeated $x$ times, $b_i$ repeated $y$ times and $c_i$ repeated $z$ times. Thus, each array has length $(x + y + z)$.\n\nYou want to choose exactly one integer from each array such that the XOR (bitwise exclusive or) of them is equal to $t$. Output the number of ways to choose the numbers for each $t$ between $0$ and $2^{k} - 1$, inclusive, modulo $998244353$.",
    "tutorial": "If we form $n$ arrays, $i$-th of them is $F_{i}$, and set $F_{i,A_{i}}=a$, $F_{i,B_{i}}=b$, $F_{i,C_{i}}=c$ and others zero. It's easy to find that the xor-convolution of all the arrays is the answer we want. Implementation with the Fast Walsh-Hadamard Transform works in $O(n \\times 2^{k} \\times k)$, this is too slow. To make it easier, we set $A_{i} = 0$, $B_{i} = B_{i} xor A_{i}$, $C_{i} = C_{i} xor A_{i}$. The answer won't change if we xor all $x$ by the xor sum of all $A_{i}$. That is $F_{i,0}=a$, $F_{i,B_{i} xor A_{i}}=b$, $F_{i,C_{i} xor A_{i}}=c$. Note we only have $4$ values in each array after FWHT of the array: $a+b+c$, $a+b-c$, $a-b+c$, $a-b-c$. Let's fix some position, let the occurrences of them in all $n$ arrays be $x,y,z,w$. Obviously, $x+y+z+w = n$. For each position, if we can figure out the values of $x,y,z,w$, it's easy to count the final answer by FWHT. If we add all arrays together and make a FWHT, we can form a new equation. $(a+b+c) \\cdot x + (a+b-c) \\cdot y + (a-b+c) \\cdot z + (a-b-c) \\cdot w = p$, where $p$ is the value we get in this position. Take two different $(a,b,c)$ to form 2 equations. Now we have 3 equations in total, including $(x+y+z+w=n)$ . More equations formed by this operation (take $a,b,c$ and compute FWHT) are useless because the equation $x,y,z,w$ lies in the same linear span, so we already have three equations. However, if we set up a new array, $F_{i,B_{i} xor C_{i}} += 1$, other is zero, and do the FWHT (add them together of course). We can get a new equation $x - y - z + w = p$. The equation can be easily proved. Now we can solve a system of $4$ equations to calculate $x,y,z,w$ for each position and get the final array. Then do the reverse FWHT and get the answer.",
    "tags": [
      "fft",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1120",
    "index": "A",
    "title": "Diana and Liana",
    "statement": "At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly $k$ flowers.\n\nThe work material for the wreaths for all $n$ citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence $a_1$, $a_2$, ..., $a_m$, where $a_i$ is an integer that denotes the type of flower at the position $i$. This year the liana is very long ($m \\ge n \\cdot k$), and that means every citizen will get a wreath.\n\nVery soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts $k$ flowers from the beginning of the liana, then another $k$ flowers and so on. Each such piece of $k$ flowers is called a workpiece. The machine works until there are less than $k$ flowers on the liana.\n\nDiana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, $k$ flowers must contain flowers of types $b_1$, $b_2$, ..., $b_s$, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.\n\nDiana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least $n$ workpieces?",
    "tutorial": "First of all, let's learn how to check if a perfect wreath can be obtained from the subsegment $[l, r]$ of our liana (that is, if we can remove some flowers so that the remaining ones on $[l, r]$ represent a perfect wreath, and this whole wreath will be cut). First, the number of other wreaths must be $n - 1$, so the inequality $\\left\\lfloor\\frac{l - 1}{k}\\right\\rfloor\\cdot k + \\left\\lfloor\\frac{m - r}{k}\\right\\rfloor\\cdot k \\ge n - 1$ must hold. Second, the segment $[l, r]$ has to contain flowers of all required types. Finally, $r - l + 1$ must be at least $k$. One can see that these conditions also guarantee that $[l, r]$ can become a cut perfect wreath. Now let's find for every $l$ the minimal possible $r$ for which the second condition holds. It can be done with the two pointers technique: if we iterate for all $l$ from $1$ to $m$ then this $r$ cannot become less than it was, and it's easy to update all counts and the number of insufficient flowers types both when increase $l$ and $r$. So what remains is to find out if there is any $l$ such that the segment $[l, \\max(r, l + k - 1)]$ satisfies the first requirement, and if it does, then print some flowers before $l$ which we delete (we must ensure that what remains before $l$ is divisible by $k$ and does not exceed $(n - 1)k$) and some flowers from $[l, r]$ we delete (without breaking the conditions). It's not necessary to delete anything after $r$, though.",
    "tags": [
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1120",
    "index": "B",
    "title": "Once in a casino",
    "statement": "One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.\n\nA positive integer $a$ is initially on the screen. The player can put a coin into the machine and then add $1$ to or subtract $1$ from any two adjacent digits. All digits must remain from $0$ to $9$ after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add $1$ to $9$, to subtract $1$ from $0$ and to subtract $1$ from the leading $1$. Once the number on the screen becomes equal to $b$, the player wins the jackpot. $a$ and $b$ have the same number of digits.\n\nHelp the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.",
    "tutorial": "Since each operation saves the alternating series of the digits, if it's different for $a$ and $b$, then the answer is '-1'. Now we prove that otherwise it's possible to win. Let's imagine that digits can be negative or bigger than 9 (that is, for example, number 19 can become the number with digits 2 and 10). Denote by $a_i$ the $i$-th digit of $a$ (and similarly for $b$). Now there is no difference between any two orders of the same set of operations, so we can do allowed operations from left to right. After we do all operations with first digit (there are at least $|a_1 - b_1|$ such operations), $a_2$ will become equal to $a_2 + b_1 - a_1$. After we do all operations with $a_2$ and $a_3$ (there are at least $|a_2 + b_1 - a_1 - b_2|$ such operations), $a_3$ will be equal to $a_3 + b_2 - a_2 - b_1 + a_1$, and so on. Thus we can calculate the minimal total number of operations and find their set. The goal is to prove that it's possible to perform them in some order and never break the rules about the correctness of intermediate numbers. Indeed, let's just perform these operations from left to right. Assume that we can't perform the current operation. Without loss of generality assume that we can't decrease two digits: one of $a_k$ and $a_{k + 1}$ is 0 now. It's easy to see that $a_k > 0$ because after we perform the set of our operations ignoring the rules, $a_k$ will become $b_k$, which is nonnegative. Hence $a_{k + 1} = 0$. Then we must increase $a_{k + 1}$ and $a_{k + 2}$ at least once (again because we can ignore the rules and get $b_{k + 1}$ in the end). If we can do it then we do it and then decrease $a_k$ and $a_{k + 1}$ just as planned and then continue performing the operations. Otherwise, $a_{k + 2} = 9$. Reasoning similarly, either we can decrease $a_{k + 2}$ and $a_{k + 3}$, or $a_{k + 3} = 0$, et cetera. As it can't continue infinitely, we can perform some operations from our set and decrease $a_k$ and $a_{k + 1}$, so we can reach the goal doing the minimal number of operations.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1120",
    "index": "C",
    "title": "Compress String",
    "statement": "Suppose you are given a string $s$ of length $n$ consisting of lowercase English letters. You need to compress it using the smallest possible number of coins.\n\nTo compress the string, you have to represent $s$ as a concatenation of several non-empty strings: $s = t_{1} t_{2} \\ldots t_{k}$. The $i$-th of these strings should be encoded with one of the two ways:\n\n- if $|t_{i}| = 1$, meaning that the current string consists of a single character, you can encode it paying $a$ coins;\n- if $t_{i}$ is a substring of $t_{1} t_{2} \\ldots t_{i - 1}$, then you can encode it paying $b$ coins.\n\nA string $x$ is a substring of a string $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nSo your task is to calculate the minimum possible number of coins you need to spend in order to compress the given string $s$.",
    "tutorial": "Let's say that $dp[p]$ is the minimal cost to encode the prefix of $s$ with length $p$, the answer is $dp[n]$. If we want to encode the prefix with length $p$ then the last symbol in our encoded string either equals $s_p$, or represents some substring $s_{[l,p]}$ so that it occurs in the prefix of length $l - 1$. Therefore one can see that $dp[0] = 0,$ $dp[p] = \\min\\left(a + dp[p - 1], \\min\\left(b + dp[l - 1]\\,\\mid\\,s_{[l, p]}\\text{ is a substring of }s_{[1, l - 1]}\\right)\\right).$ One way to implement this is to calculate this $dp$ forward and use hashes, but it may require some efforts to avoid collisions and fit into the time limit. Another way is to find for each $p$ all appropriate $l$'s by calculating z-function on the reverse of $s_{[1, p]}$. The total complexity in this case is $O\\left(n^2\\right)$.",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1120",
    "index": "D",
    "title": "Power Tree",
    "statement": "You are given a rooted tree with $n$ vertices, the root of the tree is the vertex $1$. Each vertex has some non-negative price. A leaf of the tree is a non-root vertex that has degree $1$.\n\nArkady and Vasily play a strange game on the tree. The game consists of three stages. On the first stage Arkady buys some non-empty set of vertices of the tree. On the second stage Vasily puts some integers into all leaves of the tree. On the third stage Arkady can perform several (possibly none) operations of the following kind: choose some vertex $v$ he bought on the first stage and some integer $x$, and then add $x$ to all integers in the leaves in the subtree of $v$. The integer $x$ can be positive, negative of zero.\n\nA leaf $a$ is in the subtree of a vertex $b$ if and only if the simple path between $a$ and the root goes through $b$.\n\nArkady's task is to make all integers in the leaves equal to zero. What is the minimum total cost $s$ he has to pay on the first stage to guarantee his own win independently of the integers Vasily puts on the second stage? Also, we ask you to find all such vertices that there is an optimal (i.e. with cost $s$) set of vertices containing this one such that Arkady can guarantee his own win buying this set on the first stage.",
    "tutorial": "One can see that the problem doesn't change if we want to be able to obtain any possible combination of numbers in leaves from the all-zero combination. Solution 1. Let $v_1$, $v_2$, ..., $v_l$ be the indices of all leaves in the order of any Euler tour. Let $a_i$ be the number written in $v_i$. We say that $v_0 = v_{l+1} = 0$. Denote the difference $a_{i + 1} - a_i$ by $d_i$. We want to be able to obtain an arbitrary sequence $d_0$, ..., $d_l$ with zero sum. Imagine that we bought a vertex $u$ whose subtree contains exactly leaves from $v_i$ to $v_j$. Applying the operation to this vertex with number $x$ means increasing $d_{i-1}$ by $x$ and decreasing $d_j$ by $x$ without affecting all other differences. Let's build new graph with vertices from $0$ to $l$. Each such vertex $u$ represents an edge connecting vertices $(i - 1)$ and $j$ with weight $c_u$. To be able to get every possible sequence with zero sum it's needed and sufficient for the graph with picked edges be connected. Now we want to know what is the weight of a minimal spanning tree and which edges can be in it. Both can be found by, for example, Kruskal's algorithm. Solution 2. We say that a vertex $u$ covers a leaf $v$ if it's in $u$'s subtree. One can see that we can buy a set of vertices iff for each vertex $u$ there is at most one leaf in its subtree which is not covered by any of bought vertices from the subtree. Indeed, if there are at least two such leaves then the difference between their values never change. On the other hand, if this holds, we can set the required values in the bought vertices in the order of increasing depth, performing the needed operation each time we are in vertex whose subtree contains a leaf which is not covered by any bought vertex in the subtree except the one we consider. So we calculate $ans[v][k]$ where $0\\le k\\le 1$ where this value means the minimal possible cost where in the subtree of $v$ there are $k$ not covered leaves. It can be shown that these values are enough to calculate the answer.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1120",
    "index": "E",
    "title": "The very same Munchhausen",
    "statement": "A positive integer $a$ is given. Baron Munchausen claims that he knows such a positive integer $n$ that if one multiplies $n$ by $a$, the sum of its digits decreases $a$ times. In other words, $S(an) = S(n)/a$, where $S(x)$ denotes the sum of digits of the number $x$.\n\nFind out if what Baron told can be true.",
    "tutorial": "Define the balance of a number $x$ as $S(nx) \\cdot n - S(x)$. By the balance of a digit string we mean the balance of the corresponding number. Solution 1. We are gonna do the following: Find out if the solution exists. If no, print -1 and exit. Find any string with negative balance. Find any string with positive balance. Take their linear combination with zero balance (maybe we pad the numbers we found by leading zeroes before this). By linear combination of several strings we mean their concatenation where each of them can occur several times. It is quite clear how to perform the last step. To perform the initial step it's convenient to introduce some lemmas. Lemma 1. $S(a + b) \\le S(a) + S(b)$. Proof. It's obvious more or less since if we write both numbers one under another and start calculating their sum then the result will have sum of digits being equal to $S(a) + S(b)$ minus $9$ times the number of carries. Lemma 2. $S(ab) \\le aS(b)$. Proof. $S(ab) = S(b + b + \\ldots + b) \\le S(b) + S(b) + \\ldots S(b) = aS(b)$. Here the inequality holds according to Lemma 1. Lemma 3. $S(ab) \\le S(a)S(b)$. Proof. Let $a = \\overline{a_{n-1}a_{n-2}\\ldots a_1a_0}$. Then $S(ab) = S(a_{n-1}b\\cdot10^{n-1} + a_{n-2}b\\cdot10^{n-2} + \\ldots + a_0b) \\le S(a_{n-1}b\\cdot10^{n-1}) + S(a_{n-2}b\\cdot10^{n-2}) + \\ldots + S(a_0b) =$ $= S(a_{n-1}b) + S(a_{n-2}b) + \\ldots + S(a_0b) \\le (a_{n-1} + a_{n-2} + \\ldots + a_0)S(b) = S(a)S(b).$ Now consider two cases. $a = 2^{d_1}\\cdot5^{d_2}$.Let $b = 10^{\\max(d_1, d_2)}$. One can see that $a\\cdot S(an) = a \\cdot S\\left(\\frac{bn}{b/a}\\right) = \\frac{a}{S(b/a)}\\cdot S(b/a)\\cdot S\\left(\\frac{bn}{b/a}\\right) \\ge \\frac{a}{S(b/a)}\\cdot S(bn) = \\frac{a}{S(b/a)}\\cdot S(n).$ That means that if $a > S(b/a)$ then the answer doesn't exist, otherwise the number $b/a$ has non-positive balance. One can easily see that the number $1$ always has non-negative balance, so in this case the problem is solved. Let $b = 10^{\\max(d_1, d_2)}$. One can see that $a\\cdot S(an) = a \\cdot S\\left(\\frac{bn}{b/a}\\right) = \\frac{a}{S(b/a)}\\cdot S(b/a)\\cdot S\\left(\\frac{bn}{b/a}\\right) \\ge \\frac{a}{S(b/a)}\\cdot S(bn) = \\frac{a}{S(b/a)}\\cdot S(n).$ That means that if $a > S(b/a)$ then the answer doesn't exist, otherwise the number $b/a$ has non-positive balance. One can easily see that the number $1$ always has non-negative balance, so in this case the problem is solved. $a$ has a prime divisor which is not $2$ and not $5$.It turns out that in this case the answer always exists. Indeed, the decimal fraction $1/a$ is infinite, that means that $S\\left(\\frac{10^k}{a}\\right)$ in nondecreasing and can be sufficiently large; and so can be $S\\left(\\frac{10^k}{a} + 1\\right)$ since the number of trailing $9$-s of $\\frac{10^k}{a}$ is bounded. Meanwhile $S\\left(a\\cdot\\left(\\frac{10^k}{a} + 1\\right)\\right)$ is bounded by, say, $1 + 9\\cdot len(a)$, so we always can find a string with negative balance, and, as we mentioned above, the number $1$ always has nonnegative balance. It turns out that in this case the answer always exists. Indeed, the decimal fraction $1/a$ is infinite, that means that $S\\left(\\frac{10^k}{a}\\right)$ in nondecreasing and can be sufficiently large; and so can be $S\\left(\\frac{10^k}{a} + 1\\right)$ since the number of trailing $9$-s of $\\frac{10^k}{a}$ is bounded. Meanwhile $S\\left(a\\cdot\\left(\\frac{10^k}{a} + 1\\right)\\right)$ is bounded by, say, $1 + 9\\cdot len(a)$, so we always can find a string with negative balance, and, as we mentioned above, the number $1$ always has nonnegative balance. We know two ways to perform the second step. Divide $1$ by $a$ and find the period. Let's say that the period can be represented as a string $s$ and the part before it by a string $t$ (possibly empty). Let $s'$ have the same length as $s$ and equal $(s + 1)$ when being treated as an integer. We are looking for a string of type $tsss\\ldots ss'$ with negative balance. One can calculate the impact on balance of strings $t$, $s$ and $s'$ and therefore find the minimal required number of stings $s$. Construct a weighted directed graph. Its vertices are numbers from $0$ to $a - 1$, and for each pair of numbers $(c, x)\\neq(0, 0)$ with $0\\le c < a$ and $0 \\le x \\le 9$ there is an edge from $c$ to $\\left\\lfloor\\frac{ax + c}{10}\\right\\rfloor$ with weight $(ax + c)\\pmod{10}$ and label $x$. Informally, if we traverse through some path from $0$, and labels of the edges on this path are digits of some number $n$ from right to left, then the sum of weights are the current balance of $an$ (that is, if we consider only last $len(n)$ digits when calculating the balance) and the last vertex represents the current carry. Now we can find a negative cycle in this graph via Ford-Bellman algorithm and then construct a path from $0$ to this cycle, go through the cycle required number of times (so that the final sum of weights is negative) and then return to the zero vertex. This solution has a disadvantage: the final answer can have a length up to $S(n)\\cdot n^2$. One workaround is to find, say, $300$ different possibilities of negative balance (by taking more periods/negative cycles) and find the positive balance string by trying all numbers from $1$ to $10000$ and constructing a string with a small balance divisible by any of negative balances. It can be done by a sort of knapsack on found positive balances. The idea is to get a big gcd of the two found balances so that we don't need to repeat the negative-balance-string too many times (because among the two found strings it is the one which can have a superlinear length). Solution 2. Imagine we have infinite time and memory. Then we can say that we have states of kind $(carry, balance)$ similar to the states of the graph from solution 1, where for each state $(carry, balance)$ and each digit $x$ (except state $(0, 0)$ and digit $0$ at the same time) there is a transition to $\\left((carry + a\\cdot x)\\pmod{10}, balance + a\\left\\lfloor\\frac{carry + a\\cdot x}{10}\\right\\rfloor - x\\right)$. Our goal is to reach $(0, 0)$ again. One can bfs over this (infinite) graph with creating new states, when needed. However, traversing over this graph consume too much memory. It turns out that if we don't consider states with $|balance| > a$ then there always is a solution, and this is relatively easy to come up with (and definitely easier to pass than the previous one).",
    "tags": [
      "brute force"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1120",
    "index": "F",
    "title": "Secret Letters",
    "statement": "Little W and Little P decided to send letters to each other regarding the most important events during a day. There are $n$ events during a day: at time moment $t_i$ something happens to the person $p_i$ ($p_i$ is either W or P, denoting Little W and Little P, respectively), so he needs to immediately send a letter to the other person. They can send a letter using one of the two ways:\n\n- Ask Friendly O to deliver the letter directly. Friendly O takes $d$ acorns for each letter.\n- Leave the letter at Wise R's den. Wise R values free space, so he takes $c \\cdot T$ acorns for storing a letter for a time segment of length $T$. The recipient can take a letter from Wise R either when he leaves his own letter at Wise R's den, or at time moment $t_{n + 1}$, when everybody comes to Wise R for a tea. It is not possible to take a letter from Wise R's den at other time moments. The friends can store as many letters at Wise R's den as they want, paying for each one separately.\n\nHelp the friends determine the minimum possible total cost of sending all letters.",
    "tutorial": "Consider any optimal solution. Consider all letters of W between two times when P visits R. It's clear that maybe the first of these messages is sent via R, some of the last messages are also sent via R, all other messages are sent via O. The sense behind shipping the first message via R is to obtain all messages which are currently stored there. If the first message is sent via O, and some of the others is sent via R, then we can swap them thus paying less. On the other hand, once we got all these letters, it makes sense to send something through R iff $ct \\le d$ where $t$ is the time between the moments when we send this message and when P visits R to obtain it. The same holds if we swap W and P. Denote by $ans[i]$ the minimal possible cost of the first $(i - 1)$ letters if the $i$-th is sent through R. Also denote by $ans\\_delay[i]$ the minimal possible cost of the first $(i - 1)$ letters if the $i$-th is sent through R and if R has already kept exaclty one letter. To calculate these values we can each time try every possible number of last letters sent through R. This takes $O(n^2)$ time. One can observe that if we fix the left bound of letters sent through R then the cost depends linearly on the time $t_i$ which we are calculating this for, and since we need the minimum of linear functions each time then we can use convex-hull trick which gives us $O(n)$ or $O(n\\,\\log{n})$ complexity.",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1121",
    "index": "A",
    "title": "Technogoblet of Fire",
    "statement": "Everybody knows that the $m$-coder Tournament will happen soon. $m$ schools participate in the tournament, and only one student from each school participates.\n\nThere are a total of $n$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate.\n\nArkady is a hacker who wants to have $k$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.\n\nYou know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $k$ Chosen Ones would be selected by the Technogoblet.",
    "tutorial": "First of all, each time we move someone to another school the number of schools which contain at least one Chosen One can increase at most by one. Second, if a school contains $c > 0$ Chosen Ones, but the strongest guy in this school is not one of them, then we need to move someone at least $c$ times to make all these chosen ones selected. Combining these two statements one can see that the answer to the problem equals the number of Chosen Ones which are currently not the strongest ones in their schools.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1121",
    "index": "B",
    "title": "Mike and Children",
    "statement": "Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child \\textbf{two} sweets.\n\nMike has $n$ sweets with sizes $a_1, a_2, \\ldots, a_n$. All his sweets have \\textbf{different} sizes. That is, there is no such pair $(i, j)$ ($1 \\leq i, j \\leq n$) such that $i \\ne j$ and $a_i = a_j$.\n\nSince Mike has taught for many years, he knows that if he gives two sweets with sizes $a_i$ and $a_j$ to one child and $a_k$ and $a_p$ to another, where $(a_i + a_j) \\neq (a_k + a_p)$, then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset.\n\nMike wants to invite children giving each of them \\textbf{two} sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can.\n\nSince Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.",
    "tutorial": "Notice that the sum of sweets each child gets cannot exceed $2\\cdot 10^5$, so for each of numbers no more than this threshold we can store the number of ways to obtain it as the sum of two sweets. It can be done just by considering all possible (unordered) pairs of sweets and printing the maximal obtained number (of ways to represent something as sum of two sweets). Indeed, if $x$ can be represented as a sum of two sweets in several ways then no two of them share a sweet since if $a_i + a_j$ = $a_i + a_k$ then $a_j = a_k$ and therefore $j = k$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1121",
    "index": "C",
    "title": "System Testing",
    "statement": "Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.\n\nThere are $n$ solutions, the $i$-th of them should be tested on $a_i$ tests, testing one solution on one test takes $1$ second. The solutions are judged in the order from $1$ to $n$. There are $k$ testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.\n\nAt any time moment $t$ when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id $i$, then it is being tested on the first test from time moment $t$ till time moment $t + 1$, then on the second test till time moment $t + 2$ and so on. This solution is fully tested at time moment $t + a_i$, and after that the testing process immediately starts testing another solution.\n\nConsider some time moment, let there be exactly $m$ fully tested solutions by this moment. There is a caption \"System testing: $d$%\" on the page with solutions, where $d$ is calculated as\n\n$$d = round\\left(100\\cdot\\frac{m}{n}\\right),$$\n\nwhere $round(x) = \\lfloor{x + 0.5}\\rfloor$ is a function which maps every real to the nearest integer.\n\nVasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test $q$, and the caption says \"System testing: $q$%\". Find the number of interesting solutions.\n\nPlease note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.",
    "tutorial": "Let's determine for each solution when it begins being tested. It can be done, for example, by the following algorithm: let's store for each testing process the time when it becomes free to test something (initially all these $k$ numbers are zeroes), then iterate over all solutions in the queue and for each of them we pick a process with minimal time, say that it's the time when this solution begins being tested, and then update the time when this process stops testing. After we determined this, we can easily know for each moment the number of solutions which are completely tested before this moment, and then for each test of each solution just check the required condition of being interesting on this test.",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1129",
    "index": "A2",
    "title": "Toy Train",
    "statement": "Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \\leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described.\n\nBob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \\leq i \\leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \\neq b_i$).\n\n\\begin{center}\n{\\small The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example.}\n\\end{center}\n\nThe train has infinite capacity, and it is possible to load off any number of candies at a station. However, only \\textbf{at most one} candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.\n\nNow, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.",
    "tutorial": "We can consider the pickup requests from each station individually. The overall answer for some fixed starting station is simply the maximum time needed to fulfill deliveries among all pickup stations. Suppose the starting station for the train is fixed at some station $s$ ($1 \\leq s \\leq n$). Consider some station $i$ ($1 \\leq i \\leq n$). Let $out(i)$ denote the number of candies that need to be picked up from station $i$. If $out(i) = 0$, we do not consider this station. From now on, we assume $out(i) \\geq 1$. Each time that the train visits station $i$ to pick up a candy, we can choose which candy it should pick up. Therefore, we should find an order that would minimize the time needed to fulfill all deliveries from pickup station $i$. It turns out, however, that the only thing that matters is the last candy to be delivered. Suppose the last candy is to be delivered to station $e$, the total time needed to fulfill all pickup requests from station $i$ would be: $dist(s, i) + n*(out(i)-1) + dist(i, e)$, where $dist(a, b)$ represents the time needed to travel from station $a$ to station $b$. Take some time to think why this is the case! With this formulated, it is now clear that we have to choose the last candy to deliver that minimizes $dist(i, e)$. All of this can be done in $\\mathcal{O}(n)$ (with an $\\mathcal{O}(n+m)$ pre-process only once to find the optimal last candy for each pickup station). To find the answer for every starting station for the train, we can simply run the above algorithm $n$ times. The time complexity is $\\mathcal{O}(n^2+m)$.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1129",
    "index": "B",
    "title": "Wrong Answer",
    "statement": "Consider the following problem: given an array $a$ containing $n$ integers (indexed from $0$ to $n-1$), find $\\max\\limits_{0 \\leq l \\leq r \\leq n-1} \\sum\\limits_{l \\leq i \\leq r} (r-l+1) \\cdot a_i$. In this problem, $1 \\leq n \\leq 2\\,000$ and $|a_i| \\leq 10^6$.\n\nIn an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it. Her implementation in pseudocode is as follows:\n\n\\begin{verbatim}\nfunction\nfind_answer(n, a)\n# Assumes n is an integer between 1 and 2000, inclusive\n# Assumes a is a list containing n integers: a[0], a[1], ..., a[n-1]\nres = 0\ncur = 0\nk = -1\n\nfor\ni = 0\nto\ni = n-1\ncur = cur + a[i]\n\nif\ncur < 0\ncur = 0\nk = i\nres = max(res, (i-k)*cur)\n\nreturn\nres\n\\end{verbatim}\n\nAlso, as you can see, Alice's idea is not entirely correct. For example, suppose $n = 4$ and $a = [6, -8, 7, -42]$. Then, find_answer(n, a) would return $7$, but the correct answer is $3 \\cdot (6-8+7) = 15$.\n\nYou told Alice that her solution is incorrect, but she did not believe what you said.\n\nGiven an integer $k$, you are to find any sequence $a$ of $n$ integers such that the correct answer and the answer produced by Alice's algorithm differ by exactly $k$. Note that although the choice of $n$ and the content of the sequence is yours, you must still follow the constraints earlier given: that $1 \\leq n \\leq 2\\,000$ and that the absolute value of each element does not exceed $10^6$. If there is no such sequence, determine so.",
    "tutorial": "Suppose $a_0 = -1$ and $a_i \\geq 1$ for each $1 \\leq i < n$. Let $S = \\sum\\limits_{i=0}^{n-1} a_i$. Assume also that $n \\geq 2$. It is easy to see that Alice's algorithm produces $(n-1)(S+1)$ as the answer. Meanwhile, there are two possible correct answers: either $nS$ or $(n-1)(S+1)$, whichever is greater. Assume further that $a_1 \\geq 2$. The correct answer for this array is then $nS$. The difference between these two results is $nS-(n-1)(S+1) = S-n+1$. Now, we can easily create array $a$ greedily so that $S-n+1 = k$. The time complexity is $\\mathcal{O}(n)$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1129",
    "index": "C",
    "title": "Morse Code",
    "statement": "In Morse code, an letter of English alphabet is represented as a string of some length from $1$ to $4$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a \"0\" and a dash with a \"1\".\n\nBecause there are $2^1+2^2+2^3+2^4 = 30$ strings with length $1$ to $4$ containing only \"0\" and/or \"1\", not all of them correspond to one of the $26$ English letters. In particular, each string of \"0\" and/or \"1\" of length \\textbf{at most} $4$ translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: \"0011\", \"0101\", \"1110\", and \"1111\".\n\nYou will work with a string $S$, which is initially empty. For $m$ times, either a dot or a dash will be appended to $S$, one at a time. Your task is to find and report, after each of these modifications to string $S$, the number of non-empty sequences of English letters that are represented with some substring of $S$ in Morse code.\n\nSince the answers can be incredibly tremendous, print them modulo $10^9 + 7$.",
    "tutorial": "We will be computing the answers offline instead of doing so immediately after each modification. Let $T = S_{reversed}$. Now, we need to find the number of English sequences that, if considered backward, would translate into some substring of each suffix of T. Let $f(l, r)$ be the number of English sequences that translate to exactly $T[l..r]$. Let $g(l, r)$ be sum of $f(l, x)$ over all $l \\leq x \\leq r$. Note that $f(l, r)$ can be calculated with dynamic programming for all $1 \\leq l \\leq r \\leq m$ in $\\mathcal{O}(km^2)$ where $k$ denotes the longest length of an English alphabet in Morse code (which is $4$). Following that, we can calculate $g(l, r)$ for all $1 \\leq l \\leq r \\leq m$ in $\\mathcal{O}(m^2)$. The answer for the suffix $T[x..m]$ is simply the sum of $g(i, m)$ over all $x \\leq i \\leq m$ subtracted by the number of over-counted English sequences. The number of over-counted sequences can be calculated by considering the suffix array of $T$. Namely, for each two adjacent suffixes in the list, we over-counted them by $g(l, r)$ with $l$ and $r$ denoting the corresponding indices of their longest common prefix (LCP). Therefore, the answer for $T[1..m]$ is $\\sum\\limits_{1 \\leq i \\leq m} g(i, m)$ subtracted by the sum of $g(l, r)$ of the LCP between each pair of adjacent suffixes. Transitioning to solve the problem for $T[x'..m]$ where $x' = x+1$ can be done efficiently, since the removal character of the string affects only one entry in the suffix list. To sum up, we find $g(l, r)$ for all valid $l$ and $r$ in $\\mathcal{O}(km^2)$. Then, we sort the suffixes naively in $O(m^2 \\log m)$, before computing the answer in the final step in $\\mathcal{O}(m^2)$. The time complexity is $\\mathcal{O}(km^2 + m^2 \\log m)$.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "hashing",
      "sortings",
      "string suffix structures",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1129",
    "index": "D",
    "title": "Isolation",
    "statement": "Find the number of ways to divide an array $a$ of $n$ integers into any number of disjoint non-empty segments so that, in each segment, there exist at most $k$ distinct integers that appear exactly once.\n\nSince the answer can be large, find it modulo $998\\,244\\,353$.",
    "tutorial": "Let $f(l, r)$ be the number of integers that appear exactly once in the segment $a[l..r]$. We can use the following recurrence to compute the answer: $dp(n) = \\sum\\limits_{0 \\leq i < n \\wedge f(i+1, n) \\leq k} dp(i)$, where $dp(0) = 1$. A naive $\\mathcal{O}(n^2)$ implementation will definitely be too slow. To compute the said recurrence efficiently, we will do as follows. Preparation First, let's design an array $b$ so that $f(l, r)$ is the sum of elements in segment $b[l..r]$ for some fixed $r$. Ideally, it should be easy (i.e., require only a few operations) to transform this array $b$ into another array $b'$ that would work with $r' = r+1$ instead. One design is as follows. First, let each entry of $b$ be $0$. This array now works imaginarily when $r = 0$. To make it work for $r' = r+1$, consider the element $a_{r+1}$. If this value appeared before at least twice, set $b_i = 0$ where $i$ is the second-last appearance of $a_{r+1}$ (not counting the appearance at index $r+1$). If this value appeared before at least once, set $b_i = -1$ where $i$ is the last appearance of $a_{r+1}$. Finally, set $b_{r+1} = 1$. Now, you can see that the sum in the segment $b[l..(r+1)]$ correctly represents $f(l, r+1)$ for any $1 \\leq l \\leq r+1$! The Real Thing Let us divide the array into $k$ blocks so that each block contains $\\frac{n}{k}$ elements (assume for simplicity that $k$ divides $n$). Each block corresponding to some segment $[L..R]$ should store (1) sum of elements in $b[L..R]$ (i.e., $f(L, R)$) and (2), for each $-\\frac{n}{k} \\leq i \\leq \\frac{n}{k}$, $q(i) =$ sum of $dp(x-1)$ where $f(x, R)$ is less than or equal to $i$. A modification to $b_j$ for some index $j$ will require an $\\mathcal{O}(\\frac{n}{k})$ update. With array $b$ ready for our $r$, we are ready to compute $dp(r)$. Let $t$ be a temporary variable initially equal to $0$. For each $l \\leq r$ that belongs to the same block as $r$, add $dp(l-1)$ to $dp(r)$ if $f(l, r) \\leq k$, and also add $b_l$ to $t$. This runs in $\\mathcal{O}(\\frac{n}{k})$. To account for the left possible endpoints from other blocks, for each block, starting from one directly to the left of the block that contains $r$ to the leftmost block: Suppose this block corresponds to the segment $[L..R]$. Let $x = k-t$. If $x < -\\frac{n}{k}$, do nothing. If $-\\frac{n}{k} \\leq x \\leq \\frac{n}{k}$, add $q(x)$ to $dp(r)$. If $\\frac{n}{k} < x$, add $q(\\frac{n}{k})$ to $dp(r)$. Add $f(L, R)$ to $t$. The step above runs in $\\mathcal{O}(k)$. That is, our algorithm takes $\\mathcal{O}(k + \\frac{n}{k})$ time to compute $dp(r)$ for some $r$. The time complexity is $\\mathcal{O}(nk + \\frac{n^2}{k})$, since there are $n$ values of $r$ that we need to compute $dp(r)$ for. If we choose $k = \\sqrt{n}$, our solution would run in $\\mathcal{O}(n\\sqrt{n})$.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1129",
    "index": "E",
    "title": "Legendary Tree",
    "statement": "This is an interactive problem.\n\nA legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster.\n\nTo help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains $n$ vertices, enumerated from $1$ through $n$. She also allows you to ask her some questions as follows. For each question, you should tell Mikaela some two \\textbf{disjoint} non-empty sets of vertices $S$ and $T$, along with any vertex $v$ that you like. Then, Mikaela will count and give you the number of pairs of vertices $(s, t)$ where $s \\in S$ and $t \\in T$ such that the simple path from $s$ to $t$ contains $v$.\n\nMikaela the Goddess is busy and will be available to answer at most $11\\,111$ questions.\n\nThis is your only chance. Your task is to determine the tree and report its edges.",
    "tutorial": "In this analysis, let $V$ be the set of all vertices. We will use tuples of the form $(S, T, v)$ to represent queries. First, we will root the tree at vertex $1$. The size of each subtree can be found in $n-1$ queries by asking $(\\{1\\}, \\{2, 3, \\ldots, n\\}, i)$, for each $1 \\leq i \\leq n$. Suppose $sz(i)$ denotes the size of the subtree rooted at vertex $i$. Let us sort the vertices (and store the results in $v$) so that $sz(v_i) \\leq sz(v_{i+1})$ for each $1 \\leq i < n$. We will find all children of each vertex $v_i$ in the ascending order of $i$. While we do so, we will maintain a set $X$, initially containing only $v_1$. It will store the processed-so-far vertices whose parents have not been found. Namely, for each $2 \\leq i \\leq n$: Let $k = (\\{1\\}, X, v_i)$. This is the number of direct children that $v_i$ has. Let $x_1, x_2, \\ldots, x_{|X|}$ be the vertices in $X$ in an arbitrary order. For $k$ times: binary search to find the smallest $m$ such that querying $(\\{1\\}, \\{x_1, x_2, \\ldots, x_m\\}, v_i)$ returns a non-zero result and remove $x_m$ from $X$. For each such $m$, we know that there is an edge $(x_m, v_i)$. Add $v_i$ to $X$. This solution asks at most $2(n-1) + (n-1) \\log_2 n$ queries. Time complexity: $\\mathcal{O}(n^2 \\log n)$",
    "tags": [
      "binary search",
      "interactive",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1130",
    "index": "C",
    "title": "Connect",
    "statement": "Alice lives on a flat planet that can be modeled as a square grid of size $n \\times n$, with rows and columns enumerated from $1$ to $n$. We represent the cell at the intersection of row $r$ and column $c$ with ordered pair $(r, c)$. Each cell in the grid is either land or water.\n\n\\begin{center}\n{\\small An example planet with $n = 5$. It also appears in the first sample test.}\n\\end{center}\n\nAlice resides in land cell $(r_1, c_1)$. She wishes to travel to land cell $(r_2, c_2)$. At any moment, she may move to one of the cells adjacent to where she is—in one of the four directions (i.e., up, down, left, or right).\n\nUnfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.\n\nTo help Alice, you plan to create \\textbf{at most one} tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells $(r_s, c_s)$ and $(r_t, c_t)$ is $(r_s-r_t)^2 + (c_s-c_t)^2$.\n\nFor now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from $(r_1, c_1)$ to $(r_2, c_2)$. If no tunnel needs to be created, the cost is $0$.",
    "tutorial": "Let $S$ be the set of cells accessible from $(r_1, c_1)$. Similarly, let $T$ be the set of cells accessible from $(r_2, c_2)$. We can find $S$ and $T$ using a search algorithm such as a DFS or a BFS. If $S = T$, then a tunnel is not needed, so the answer is $0$. Otherwise, we need to create a tunnel with an endpoint in $A$ and the other in $B$. Now, we can simply iterate through all possible pairs of cells $((x_1, y_1), (x_2, y_2))$ where $(x_1, y_1) \\in S$ and $(x_2, y_2) \\in T$ to find one that minimizes the cost (i.e., $(x_1-x_2)^2 + (y_1-y_2)^2$). The time complexity is $\\mathcal{O}(n^4)$.",
    "tags": [
      "brute force",
      "dfs and similar",
      "dsu"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1131",
    "index": "A",
    "title": "Sea Battle",
    "statement": "In order to make the \"Sea Battle\" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of $w_1$ and a height of $h_1$, while the second rectangle has a width of $w_2$ and a height of $h_2$, where $w_1 \\ge w_2$. In this game, exactly one ship is used, made up of two rectangles. There are no other ships on the field.\n\nThe rectangles are placed on field in the following way:\n\n- the second rectangle is on top the first rectangle;\n- they are aligned to the left, i.e. their left sides are on the same line;\n- the rectangles are adjacent to each other without a gap.\n\nSee the pictures in the notes: the first rectangle is colored red, the second rectangle is colored blue.\n\nFormally, let's introduce a coordinate system. Then, the leftmost bottom cell of the first rectangle has coordinates $(1, 1)$, the rightmost top cell of the first rectangle has coordinates $(w_1, h_1)$, the leftmost bottom cell of the second rectangle has coordinates $(1, h_1 + 1)$ and the rightmost top cell of the second rectangle has coordinates $(w_2, h_1 + h_2)$.\n\nAfter the ship is completely destroyed, all cells neighboring by side or a corner with the ship are marked. Of course, only cells, which don't belong to the ship are marked. On the pictures in the notes such cells are colored green.\n\nFind out how many cells should be marked after the ship is destroyed. The field of the game is infinite in any direction.",
    "tutorial": "Let's classify marked squares to two groups. First group will consist of cells that are neighboring by corner to ship. There are exactly $5$ such corners. Second group will consist of cells that are neighboring by side to ship. Number of such squares is equal to length of perimeter of a ship. Thus answer is equal to $2 \\cdot (w_1 + h1 + h2) + 4$.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1131",
    "index": "B",
    "title": "Draw!",
    "statement": "You still have partial information about the score during the historic football match. You are given a set of pairs $(a_i, b_i)$, indicating that at some point during the match the score was \"$a_i$: $b_i$\". It is known that if the current score is «$x$:$y$», then after the goal it will change to \"$x+1$:$y$\" or \"$x$:$y+1$\". What is the largest number of times a draw could appear on the scoreboard?\n\nThe pairs \"$a_i$:$b_i$\" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.",
    "tutorial": "Since some scores are already fixed, we only have \"liberty\" in between of them. One can easily see, that basically we need to solve the problem between each neighboring pair and then sum all the answers (it may turn out, that for a fixed score, it will be accounted twice, in the \"left\" pair and in the \"right\", but it's easy to subtract it back). How to solve the problem between score $(a, b)$ and $(c, d)$? We want to put in the middle as much pairs $(x, x)$ as possible. So we have $a \\le x \\le c$ and $b \\le x \\le d$, hence $\\max(a, b) \\le x \\le \\min(c, d)$, it's easy to count the number of such $x$'s and you can also see, that there is a goal sequence which achieves all such $(x, x)$'s together.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1131",
    "index": "C",
    "title": "Birthday",
    "statement": "Cowboy Vlad has a birthday today! There are $n$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.\n\nFormally, let's number children from $1$ to $n$ in a circle order, that is, for every $i$ child with number $i$ will stand next to the child with number $i+1$, also the child with number $1$ stands next to the child with number $n$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.\n\nPlease help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.",
    "tutorial": "The solution is greedy one. Suppose we have reordered $a_i$, so that $a_i \\le a_{i + 1}$. Then I claim that the answer can be built as follows: First write all elements with even indices and then all elements with odd indices in reversed order. For example, if $n = 5$: we get $a_1, a_3, a_5 \\mid a_4, a_2$ and if $n = 6$: $a_1, a_3, a_5 \\mid a_6, a_4, a_2$. One can \"check on many tests\" that it works in practice, but here goes the proof: Note, that the solution provides answer which is at most $\\max a_{i + 2} - a_{i}$. Let's show that for every $i$, answer must be at least $a_{i + 2} - a_{i}$. To do this, draw all $a_i$'s as a graph. Then the solution to the problem is some Hamiltonian cycle. Let's suppose that $a_{i + 2} - a_{i}$ is prohibited to us (and all jumps containing this one). Red denotes the forbidden jumps. One can easily see, that $a_{i+1}$ is a cut point, and no hamiltonian cycle is possible. This concludes our proof!",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1131",
    "index": "D",
    "title": "Gourmet choice",
    "statement": "Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.\n\nOnce, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.\n\nThe gourmet tasted a set of $n$ dishes on the first day and a set of $m$ dishes on the second day. He made a table $a$ of size $n \\times m$, in which he described his impressions. If, according to the expert, dish $i$ from the first set was better than dish $j$ from the second set, then $a_{ij}$ is equal to \">\", in the opposite case $a_{ij}$ is equal to \"<\". Dishes also may be equally good, in this case $a_{ij}$ is \"=\".\n\nNow Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $a_{ij}$ is \"<\", then the number assigned to dish $i$ from the first set should be less than the number of dish $j$ from the second set, if $a_{ij}$ is \">\", then it should be greater, and finally if $a_{ij}$ is \"=\", then the numbers should be the same.\n\nHelp Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.",
    "tutorial": "This task has different possible solutions. One of them is as follows - make a DSU for all $n+m$ dishes (Disjoint Set Union data structure, https://en.wikipedia.org/wiki/Disjoint-set_data_structure), and unite all dishes that should be evaluated with the same number according to the table (unite dishes $i$ and $n+j$ if $a_{ij}$ equals \"=\". Then create graph. We will iterate over all $i$, $j$ and add a directed edge in some direction between the sets, corresponding to the $i$ and $j$, if one of them is better, then the other. In case the graph has a self-loop or cycle, it's easy to see that the answer is impossible. Otherwise assign numbers, where the vertex gets the least number greater than the vertex it goes to. This is the answer.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1131",
    "index": "E",
    "title": "String Multiplication",
    "statement": "Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings $s$ of length $m$ and $t$ is a string $t + s_1 + t + s_2 + \\ldots + t + s_m + t$, where $s_i$ denotes the $i$-th symbol of the string $s$, and \"+\" denotes string concatenation. For example, the product of strings \"abc\" and \"de\" is a string \"deadebdecde\", while the product of the strings \"ab\" and \"z\" is a string \"zazbz\". Note, that unlike the numbers multiplication, the product of strings $s$ and $t$ is not necessarily equal to product of $t$ and $s$.\n\nRoman was jealous of Denis, since he invented such a cool operation, and hence decided to invent something string-related too. Since Roman is beauty-lover, he decided to define the beauty of the string as the length of the longest substring, consisting of only one letter. For example, the beauty of the string \"xayyaaabca\" is equal to $3$, since there is a substring \"aaa\", while the beauty of the string \"qwerqwer\" is equal to $1$, since all neighboring symbols in it are different.\n\nIn order to entertain Roman, Denis wrote down $n$ strings $p_1, p_2, p_3, \\ldots, p_n$ on the paper and asked him to calculate the beauty of the string $( \\ldots (((p_1 \\cdot p_2) \\cdot p_3) \\cdot \\ldots ) \\cdot p_n$, where $s \\cdot t$ denotes a multiplication of strings $s$ and $t$. Roman hasn't fully realized how Denis's multiplication works, so he asked you for a help. Denis knows, that Roman is very impressionable, he guarantees, that the beauty of the resulting string is at most $10^9$.",
    "tutorial": "Let's notice, that the string multiplication is associative, that is $(a \\cdot b) \\cdot c = a \\cdot (b \\cdot c)$. So instead of left \"$(a \\cdot b) \\cdot c$\" given in statement, let's use \"$a \\cdot (b \\cdot c)$\" That is, we have $s_n$, then go to $s_{n-1} \\cdot s_n$, then $s_{n - 2} \\cdot (s_{n-1} \\cdot s_n)$ and so on. One can also solve the problem without observing the associativity property and going with $s_1 \\to s_1 \\cdot s_2 \\to (s_1 \\cdot s_2) \\cdot s_3$ and so on. However there is one caveat. Since the string grows very fast, \"an answer\" will grow as well. And while you are promised that the answer is at most $10^9$, observe the following situtation: $s_1, s_2, ..., s_{100}$ are \"aaaaaaaaaaaaaaaaaaaa\", which makes an answer quite large, but if you add a $s_{101}$ equal to \"c\" it collides to a mere $1$, so it requires some careful handling, basically store for every value $x$ you want value $\\min(x, 10^9)$. Going in another direction has an advantage, that if some value is large it will stay large for life, so since answer is $10^9$ no overflows will happen. Now back to the suggested solution. Let's proceed as $s_n \\to s_{n-1} \\cdot s_n \\to s_{n - 2} \\cdot (s_{n-1} \\cdot s_n)$ and so on. Note, that it's enough to store not whole the current string $s_{i} \\cdot \\ldots \\cdot s_n$, but just some basic information about. Let's simply store: The length of the largest substring of a single character Whether the string consists of the single character or not The left and the right character of it The length of the prefix, which consists of a single character and the same for the suffix. It's easy to see that if you know such values for some string $s_{i} \\cdot \\ldots \\cdot s_n$, you can also compute it for $s_{i - 1} \\cdot s_{i} \\cdot \\ldots \\cdot s_n$ (here, the brackets are assumed as in $a \\cdot (b \\cdot c)$).",
    "tags": [
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1131",
    "index": "F",
    "title": "Asya And Kittens",
    "statement": "Asya loves animals very much. Recently, she purchased $n$ kittens, enumerated them from $1$ and $n$ and then put them into the cage. The cage consists of one row of $n$ cells, enumerated with integers from $1$ to $n$ from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were $n - 1$ partitions originally. Initially, each cell contained exactly one kitten with some number.\n\nObserving the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day $i$, Asya:\n\n- Noticed, that the kittens $x_i$ and $y_i$, located in neighboring cells want to play together.\n- Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells.\n\nSince Asya has never putted partitions back, after $n - 1$ days the cage contained a single cell, having all kittens.\n\nFor every day, Asya remembers numbers of kittens $x_i$ and $y_i$, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into $n$ cells.",
    "tutorial": "In this problem we are given a disjoint set union process with $n - 1$ steps, merging $n$ initial 1-element sets into one $n$-element set. We have to put elements into a linear array of cells, so that the cells to be joined at each step of the process were immediate neighbours (i.e. not separated by other cells). This problem can be solved in $O(n\\log n)$ or in $O(n\\alpha(n))$ (where $\\alpha(n)$ is the inverse Ackermann function) via standard disjoint-set data structure, additionally storing lists of elements in each set. The simplest solution is based on a set-size version of rank heuristic: storing mapping from item to id (representative) of its current set, and the inverse mapping from set to the list of its elements when we have to merge two sets $A$ and $B$, we make the smaller set part of the larger set and update mappings, assigning new set ids for elements in $O(min(|A|, |B|))$ and concatenating the lists (can be done in $O(1)$ or in $O(min(|A|, |B|))$) This gives us $O(n\\log n)$: element can not change its set more than $log n$ times, because the change leads to (at least) doubling of the element's set size. In order to get $O(n\\alpha(n))$, we have to use the disjoint set structure with both path compression and rank heuristics, plus concatenation of lists should be done in $O(1)$.",
    "tags": [
      "constructive algorithms",
      "dsu"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1131",
    "index": "G",
    "title": "Most Dangerous Shark",
    "statement": "Semyon participates in the most prestigious competition of the world ocean for the title of the most dangerous shark. During this competition sharks compete in different subjects: speed swimming, masking, map navigation and many others. Now Semyon is taking part in «destruction» contest.\n\nDuring it, $m$ dominoes are placed in front of the shark. All dominoes are on the same line, but the height of the dominoes may vary. The distance between adjacent dominoes is $1$. Moreover, each Domino has its own cost value, expressed as an integer. The goal is to drop all the dominoes. To do this, the shark can push any domino to the left or to the right, and it will begin falling in this direction. If during the fall the domino touches other dominoes, they will also start falling in the same direction in which the original domino is falling, thus beginning a chain reaction, as a result of which many dominoes can fall. A falling domino touches another one, if and only if the distance between them \\textbf{was strictly less than} the height of the falling domino, the dominoes do not necessarily have to be adjacent.\n\nOf course, any shark can easily drop all the dominoes in this way, so the goal is not to drop all the dominoes, but do it with a minimum cost. The cost of the destruction is the sum of the costs of dominoes that the shark needs to push to make all the dominoes fall.\n\nSimon has already won in the previous subjects, but is not smart enough to win in this one. Help Semyon and determine the minimum total cost of the dominoes he will have to push to make all the dominoes fall.",
    "tutorial": "This problem can be solved using dynamic programming technique. Let $dp_i$ be minimum cost to fall first $i$ dominoes. If $i$-th domino was dropped to the right $dp_i = min(dp_j + c_i)$ over such $j$ that dropped $i$-th domino will fall all dominoes from $j + 1$ to $i$. Otherwise, some other domino was dropped to the right and fell domino $i$. Then $dp_i = min(dp_{j - 1} + c_j)$ other such $j$, that $j$-th domino dropped to the right will fall $i$-th domino. Such solution works in $O(m^2)$. We need to speed up this solution. We need to find possible $j$ for each $i$ faster. At first let's notice, that possible $j$'s forms subsegments, so we need just find most right $j$. This can be done using stack technique like finding nearest element greater than current. Another part of the solution, we need to optimize is taking range minimum query of $dp$'s. That can be easily done using segment tree technique or fenwick tree technique, however it requires $O(log m)$ time per query which is too slow. To make it faster we can use stack technique again! Let's maintain stack of increasing values of $dp_i$ (or $dp_i + c_i$, depending on case). Because segments on which we are taking minimum are nested or non-intersecting we can always drop all values after the optimum for each query. Using amortized analysis technique, we can see that such solution works in $O(m)$.",
    "tags": [
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1132",
    "index": "A",
    "title": "Regular Bracket Sequence",
    "statement": "A string is called bracket sequence if it does not contain any characters other than \"(\" and \")\". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters \"+\" and \"1\" into this sequence. For example, \"\", \"(())\" and \"()()\" are regular bracket sequences; \"))\" and \")((\" are bracket sequences (but not regular ones), and \"(a)\" and \"(1)+(1)\" are not bracket sequences at all.\n\nYou have a number of strings; each string is a bracket sequence of length $2$. So, overall you have $cnt_1$ strings \"((\", $cnt_2$ strings \"()\", $cnt_3$ strings \")(\" and $cnt_4$ strings \"))\". You want to write all these strings in some order, one after another; after that, you will get a long bracket sequence of length $2(cnt_1 + cnt_2 + cnt_3 + cnt_4)$. You wonder: is it possible to choose some order of the strings you have such that you will get a regular bracket sequence? \\textbf{Note that you may not remove any characters or strings, and you may not add anything either}.",
    "tutorial": "For bracket sequence to be regular, it should have equal number of opening and closing brackets. So, if $cnt_1 \\ne cnt_4$, then it's impossible to construct any regular bracket sequence. $cnt_2$ is completely irrelevant to us, since inserting or removing a () substring doesn't change the status of the string we get. Almost the same applies to $cnt_3$, but we should have at least one (( substring before it. So, if $cnt_3 > 0$, but $cnt_1 = 0$, there is no solution. In all other cases it is possible to order all strings as follows: all strings ((, then all strings (), then all strings )(, then all strings )).",
    "code": "cnt = []\n\nfor i in range(4):\n\tcnt.append(int(input()))\n\t\nif(cnt[0] == cnt[3] and (cnt[2] == 0 or cnt[0] > 0)):\n\tprint(1)\nelse:\n\tprint(0)",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1132",
    "index": "B",
    "title": "Discounts",
    "statement": "You came to a local shop and want to buy some chocolate bars. There are $n$ bars in the shop, $i$-th of them costs $a_i$ coins (and you want to buy all of them).\n\nYou have $m$ different coupons that allow you to buy chocolate bars. $i$-th coupon allows you to buy $q_i$ chocolate bars while you have to pay only for the $q_i - 1$ most expensive ones (so, the cheapest bar of those $q_i$ bars is for free).\n\nYou can use only one coupon; if you use coupon $i$, you have to choose $q_i$ bars and buy them using the coupon, and buy all the remaining $n - q_i$ bars without any discounts.\n\nTo decide which coupon to choose, you want to know what will be the minimum total amount of money you have to pay if you use one of the coupons optimally.",
    "tutorial": "When using $i$-th coupon, the bar we get for free should have at least $x_i - 1$ bars not cheaper than it. So, if we consider $a$ sorted in non-decreasing order, then we cannot get discount greater than $a_{n - x_i + 1}$. On the other hand, we can always get such a discount if we pick $x_i$ most expensive bars to buy using the $i$-th coupon.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300009;\n\nint n;\nint a[N];\nlong long res[N];\n\nint main() {\n\tlong long sum = 0;\n\tscanf(\"%d\", &n);\t\n\tfor(int i = 0; i < n; ++i){\n\t\tscanf(\"%d\", a + i);\n\t\tsum += a[i];\t\n\t}\n\tsort(a, a + n);\n\t\n\tmemset(res, -1, sizeof res);\n\tint m;\n\tscanf(\"%d\", &m);\n\tfor(int i = 0; i < m; ++i){\n\t\tint c;\n\t\tscanf(\"%d\", &c);\n\t\tif(res[c] == -1){\n\t\t\tres[c] = sum - a[n - c];\n\t\t}\t\n\n\t\tprintf(\"%lld\\n\", res[c]);\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1132",
    "index": "C",
    "title": "Painting the Fence",
    "statement": "You have a long fence which consists of $n$ sections. Unfortunately, it is not painted, so you decided to hire $q$ painters to paint it. $i$-th painter will paint all sections $x$ such that $l_i \\le x \\le r_i$.\n\nUnfortunately, you are on a tight budget, so you may hire only $q - 2$ painters. Obviously, only painters you hire will do their work.\n\nYou want to maximize the number of painted sections if you choose $q - 2$ painters optimally. A section is considered painted if at least one painter paints it.",
    "tutorial": "Let $c_i$ be the number of painters that are painting the $i$-th section. Let's fix the first painter (denote his index as $x$) we won't take and decrease the numbers of array $c$ in the range which he paints. Then we may new array $d$, such that $d_i$ is equal to $1$ if and only if $c_i = 1$, and $0$ otherwise. This array corresponds to segments that are painted by only one painter After that we build prefix sum array $p$ on array $d$: $p_i = \\sum\\limits_{j=1}^{i} d_j$. This should be done in $O(n)$. Now, for each remaining painter we can count the number of sections that are painted only by him. For painter $i$ it will be equal to $p_{r_i} - p_{l_i - 1}$. Let's denote it as $res_i$. Finally, find an painter with the minimum value of $res_i$, denote it as $MinRes$. The answer (if we choose painter $x$ as one of two that won't be hired) will be equal to $cnt - MinRes$, where $cnt$ is the number of elements greater than $0$ in the array $c$ after removing the painter $x$. And, of course, we should do the same for all painters.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5043;\n\nint p1[N];\nint p2[N];\nint p3[N];\nint n, q;\nint l[N], r[N];\n\nint solve(int idx)\n{\n\tmemset(p1, 0, sizeof p1);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tif(i == idx) continue;\n\t\tp1[l[i]]++;\n\t\tp1[r[i]]--;\n\t}\n\tmemset(p2, 0, sizeof p2);\n\tint c = 0;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tc += p1[i];\n\t\tp2[i] = c;\n\t}\t\n\tmemset(p3, 0, sizeof p3);\n\tfor(int i = 0; i < n; i++)\n\t\tp3[i + 1] = p3[i] + (p2[i] == 1 ? 1 : 0);\n\tint ans = -int(1e9);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tif(i == idx) continue;\n\t\tans = max(ans, p3[l[i]] - p3[r[i]]);\n\t}\n\tfor(int i = 0; i < n; i++)\n\t\tif(p2[i] > 0)\n\t\t\tans++;\n\treturn ans;\n}\n\nint main()\n{\n\tcin >> n >> q;\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tcin >> l[i] >> r[i];\n\t\tl[i]--;\n\t}\n\tint ans = 0;\n\tfor(int i = 0; i < q; i++)\n\t\tans = max(ans, solve(i));\n\tcout << ans << endl;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1132",
    "index": "D",
    "title": "Stressful Training",
    "statement": "Berland SU holds yet another training contest for its students today. $n$ students came, each of them brought his laptop. However, it turned out that everyone has forgot their chargers!\n\nLet students be numbered from $1$ to $n$. Laptop of the $i$-th student has charge $a_i$ at the beginning of the contest and it uses $b_i$ of charge per minute (i.e. if the laptop has $c$ charge at the beginning of some minute, it becomes $c - b_i$ charge at the beginning of the next minute). The whole contest lasts for $k$ minutes.\n\nPolycarp (the coach of Berland SU) decided to buy a \\textbf{single} charger so that all the students would be able to successfully finish the contest. He buys the charger at the same moment the contest starts.\n\nPolycarp can choose to buy the charger with any non-negative (zero or positive) integer power output. The power output is chosen before the purchase, it can't be changed afterwards. Let the chosen power output be $x$. \\textbf{At the beginning of each minute} (from the minute contest starts to the last minute of the contest) he can plug the charger into any of the student's laptops and use it for some \\textbf{integer} number of minutes. If the laptop is using $b_i$ charge per minute then it will become $b_i - x$ per minute while the charger is plugged in. Negative power usage rate means that the laptop's charge is increasing. The charge of any laptop isn't limited, it can become infinitely large. The charger can be plugged in no more than one laptop at the same time.\n\nThe student successfully finishes the contest if the charge of his laptop never is below zero at the beginning of some minute (from the minute contest starts to the last minute of the contest, zero charge is allowed). The charge of the laptop of the minute the contest ends doesn't matter.\n\nHelp Polycarp to determine the minimal possible power output the charger should have so that all the students are able to successfully finish the contest. Also report if no such charger exists.",
    "tutorial": "The easiest part of the solution is to notice that if the charger of power $x$ works then the charger of power $x + 1$ also works. Thus, binary search is applicable to the problem. $k$ is really small and only one laptop can be charged during some minute. It implies that check function can work in something polynomial on $k$ by searching for the right laptop to charge during every minute. I claim that the greedy algorithm works. Find the laptop that gets his charge below zero the first. Charge it for one minute as early as possible. Repeat until you either don't have time to charge the laptop (check returns false) or the contest is over (check returns true). Why greedy works? Well, check any case where check returns false. If some laptop runs out of power then all the minutes up to the current one are used to charge something. Moreover, you can free no minute of these as by doing greedy we charged all laptops as late as possible. Freeing some minute will lead to other laptop dying earlier. One way to implement this is the following. Keep a heap of events ($time\\_i-th\\_laptop\\_dies$), pop its head, add $x$ to it if the time is greater than the number of charges already made and push it back to heap. That will simulate the entire process in $O((n + k) \\log n)$. Unfortunately, this may be too slow on some implementations. Let's try the following linear approach. Maintain not the heap but such an array that $i$-th its cell contains all indices of all the laptops to run out of charge on the beginning of minute $i$. Keep an iterator to the first non-empty position. Pop a single index out of this vector, charge it and push it to the new position. You'll still make $k$ steps and on each step you'll make $O(1)$ instant operations. That will make it $O(n + k)$ for this simulation. I'm not really sure how to build the maximal answer case, however, I can estimate the upper bound of binary search. You can set $x$ in such a way that it charges every laptop in one minute so that it won't run out of power until the end of the contest. Choose the smallest $a_i$, the greatest $b_i$, the greatest $k$ and you'll end up with $1 - 2 \\cdot 10^5 \\cdot 10^7$ total usage. Thus, $2 \\cdot 10^12$ will always be enough. Overall complexity: $O((n + k) \\cdot \\log ANS)$. (or $O((n + k) \\cdot \\log ANS \\log n)$ if you are skillful enough to squeeze it :D).",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\nconst long long INF64 = 1e18;\n\nint n, k;\nlong long a[N];\nint b[N];\nlong long cur[N];\n\nvector<int> qr[N];\n\nbool check(long long x){\n\tforn(i, k) qr[i].clear();\n\tforn(i, n) cur[i] = a[i];\n\tforn(i, n){\n\t\tlong long t = cur[i] / b[i] + 1;\n\t\tcur[i] %= b[i];\n\t\tif (t < k) qr[t].push_back(i);\n\t}\n\t\n\tint lst = 0;\n\tforn(t, k){\n\t\twhile (lst < k && qr[lst].empty())\n\t\t\t++lst;\n\t\tif (lst <= t)\n\t\t\treturn false;\n\t\tif (lst == k)\n\t\t\treturn true;\n\t\tint i = qr[lst].back();\n\t\tif (cur[i] + x < b[i]){\n\t\t\tcur[i] += x;\n\t\t\tcontinue;\n\t\t}\n\t\tqr[lst].pop_back();\n\t\tlong long nt = (cur[i] + x) / b[i];\n\t\tcur[i] = (cur[i] + x) % b[i];\n\t\tif (lst + nt < k)\n\t\t\tqr[lst + nt].push_back(i);\n\t}\n\t\n\treturn true;\n}\n\nint main() {\n\tscanf(\"%d%d\", &n, &k);\n\tforn(i, n) scanf(\"%lld\", &a[i]);\n\tforn(i, n) scanf(\"%d\", &b[i]);\n\tlong long l = 0, r = INF64;\n\twhile (l < r - 1){\n\t\tlong long m = (l + r) / 2;\n\t\tif (check(m))\n\t\t\tr = m;\n\t\telse\n\t\t\tl = m;\n\t}\n\tif (!check(r))\n\t\tputs(\"-1\");\n\telse\n\t\tprintf(\"%lld\\n\", check(l) ? l : r);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1132",
    "index": "E",
    "title": "Knapsack",
    "statement": "You have a set of items, each having some integer weight not greater than $8$. You denote that a subset of items is good if total weight of items in the subset does not exceed $W$.\n\nYou want to calculate the maximum possible weight of a good subset of items. Note that you have to consider the empty set and the original set when calculating the answer.",
    "tutorial": "Let's consider the optimal answer. Suppose we take $c_i$ items of weight $i$. Let $L$ be the least common multiple of all weights (that is $840$). Then we may represent $c_i$ as $c_i = \\frac{L}{i} p_i + q_i$, where $0 \\le q < \\frac{L}{i}$. Let's do the following trick: we will take $q_i$ items of weight $i$, and all the remaining items of this weight can be merged into some items of weight $L$. Then we can write a brute force solution that picks less than $\\frac{L}{i}$ items of each weight, transforms the remaining ones into items of weight $L$ as much as possible, and when we fix the whole subset, adds maximum possible number of items of weight $L$ to the answer. This works in something like $\\prod \\limits_{i = 1}^8 \\frac{L}{i} = \\frac{L^8}{8!}$ operations, which is too much. How can we speed it up? Rewrite it using dynamic programming! When we have fixed the number of items we take from $x$ first sets, the only two things that matter now are the current total weight of taken items and the number of items of weight $L$ we can use; and it's obvious that the more items of weight $L$ we can use, the better. So let's write the following dynamic programming solution: $dp[x][y]$ - maximum number of items of weight $L$ we can have, if we processed first $x$ types of items, and current total weight is $y$. Note that the second dimension should have size $8L$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 9;\nconst int L = 840;\n\ntypedef long long li;\n\nli dp[N][L * N];\nli W;\nli cnt[N];\n\nint main()\n{\n\tcin >> W;\n\tfor(int i = 0; i < 8; i++)\n\t\tcin >> cnt[i];\n\tfor(int i = 0; i < N; i++) for(int j = 0; j < L * N; j++) dp[i][j] = -1;\n\tdp[0][0] = 0;\n\tfor(int i = 0; i < 8; i++)\n\t{\n\t\tfor(int j = 0; j < L * N; j++)\n\t\t{\n\t\t\tif(dp[i][j] == -1) continue;\n\t\t\tint b = L / (i + 1);\n\t\t\tif(cnt[i] < b)\n\t\t\t\tb = cnt[i];\n\t\t\tfor(int k = 0; k <= b; k++)\n\t\t\t{\n\t\t\t\tli& d = dp[i + 1][j + k * (i + 1)];\n\t\t\t\td = max(d, dp[i][j] + (cnt[i] - k) / (L / (i + 1)));\n\t\t\t}\n\t\t}\n\t}\n\tli ans = 0;\n\tfor(int j = 0; j < L * N; j++)\n\t{\n\t\tif(j > W || dp[8][j] == -1)\n\t\t\tcontinue;\n\t\tans = max(ans, j + L * (min(dp[8][j], (W - j) / L)));\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1132",
    "index": "F",
    "title": "Clear the String",
    "statement": "You are given a string $s$ of length $n$ consisting of lowercase Latin letters. You may apply some operations to this string: in one operation you can delete some contiguous substring of this string, if all letters in the substring you delete are equal. For example, after deleting substring bbbb from string abbbbaccdd we get the string aaccdd.\n\nCalculate the minimum number of operations to delete the whole string $s$.",
    "tutorial": "We will solve the problem by dynamic programming. Let $dp_{l, r}$ be the answer for substring $s_{l, l + 1, \\dots, r}$. Then we have two cases: The first letter of the substring is deleted separately from the rest, then $dp_{l, r} = 1 + dp_{l + 1, r}$; The first letter of the substring is deleted alongside with some other letter (both letters must be equal), then $dp_{l,r} = \\min \\limits_{l < i \\le r, s_i = s_r} dp_{l + 1, i - 1} + dp_{i, r}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 505;\n\nint n;\nstring s;\nint dp[N][N];\n\nint calc(int l, int r){\t\n\tint &res = dp[l][r];\n\tif(res != -1) return res;\n\t\n\tif(l > r) return res = 0;\n\tif(l == r) return res = 1;\n    \n\tres = 1 + calc(l + 1, r);\n\tfor(int i = l + 1; i <= r; ++ i)\n\t\tif(s[l] == s[i])\n\t\t\tres = min(res, calc(l + 1, i - 1) + calc(i, r));\n\treturn res;\n}\n\nint main(){\n\tcin >> n >> s;\n\tmemset(dp, -1, sizeof dp);\n\tcout << calc(0, n - 1);\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1132",
    "index": "G",
    "title": "Greedy Subsequences",
    "statement": "For some array $c$, let's denote a greedy subsequence as a sequence of indices $p_1$, $p_2$, ..., $p_l$ such that $1 \\le p_1 < p_2 < \\dots < p_l \\le |c|$, and for each $i \\in [1, l - 1]$, $p_{i + 1}$ is the minimum number such that $p_{i + 1} > p_i$ and $c[p_{i + 1}] > c[p_i]$.\n\nYou are given an array $a_1, a_2, \\dots, a_n$. For each its subsegment of length $k$, calculate the length of its longest greedy subsequence.",
    "tutorial": "Let's calculate for each position $i$ position $nxt_i$ - \"the closest greater from the right\" element to $i$ and add directed edge from $i$ to $nxt_i$. Then we will get oriented forest (or tree if we'd add fictive vertex) where all edges are directed to some root. So, we can look at current subsegment we need to calculate the answer for as at a number of marked vertices in the tree. Then, the answer itself is a longest path up to the tree consisting only from marked vertices. Key observation is next: if $u$ and $v$ are marked and $u$ is an ancestor of $v$ then any vertex $y$ on path from $v$ to $u$ is also marked. So, \"the longest path up to the tree consisting only from marked vertices\" has length equal to a number of marked vertices on path to the root. And we have three types of queries: mark a vertex, unmark a vertex and calculate maximum number of marked vertices among all paths to the root. It can be done with Segment Tree on Euler Tour of the tree: if we calculate $T_{in}$ and $T_{out}$ for each vertex in dfs order, then marking/unmarking is just adding $\\pm 1$ to a segment $[T_{in}, T_{out})$, and maximum among all paths is a maximum on the whole tree. Result time complexity is $O(n \\log{n})$ and space complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\nint n, k;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n >> k))\n\t\treturn false;\n\ta.assign(n, 0);\n\tfore(i, 0, n)\n\t\tcin >> a[i];\n\treturn true;\n}\n\nint T = 0;\nvector< vector<int> > g;\nvector<int> tin, tout;\n\nvoid dfs(int v) {\n\ttin[v] = T++;\n\tfor(int to : g[v])\n\t\tdfs(to);\n\ttout[v] = T;\n}\n\nvector<int> Tmax, Tadd;\n\ninline void push(int v) {\n\tTadd[2 * v + 1] += Tadd[v];\n\tTadd[2 * v + 2] += Tadd[v];\n\tTadd[v] = 0;\n}\ninline int getmax(int v) {\n\treturn Tmax[v] + Tadd[v];\n}\n\nvoid addVal(int v, int l, int r, int lf, int rg, int val) {\n\tif(l == lf && r == rg) {\n\t\tTadd[v] += val;\n\t\treturn;\n\t}\n\tint mid = (l + r) >> 1;\n\tpush(v);\n\tif(lf < mid) addVal(2 * v + 1, l, mid, lf, min(mid, rg), val);\n\tif(rg > mid) addVal(2 * v + 2, mid, r, max(lf, mid), rg, val);\n\tTmax[v] = max(getmax(2 * v + 1), getmax(2 * v + 2));\n}\n\ninline void solve() {\n\tg.resize(n + 1);\n\ttin.resize(n + 1, 0);\n\ttout.resize(n + 1, 0);\n\tvector<int> st;\n\tfor(int i = n - 1; i >= 0; i--) {\n\t\twhile(!st.empty() && a[st.back()] <= a[i])\n\t\t\tst.pop_back();\n\t\tint nxt = st.empty() ? n : st.back();\n\t\tg[nxt].push_back(i);\n\t\tst.push_back(i);\n\t}\n\tdfs(n);\n\tTmax.assign(4 * (n + 1), 0);\n\tTadd.assign(4 * (n + 1), 0);\n\t\n\tfore(i, 0, k - 1)\n\t\taddVal(0, 0, n + 1, tin[i], tout[i], +1);\n\t\n\tfor(int l = 0; l + k <= n; l++) {\n\t\taddVal(0, 0, n + 1, tin[l + k - 1], tout[l + k - 1], +1);\n\t\tcout << getmax(0) << \" \";\n\t\taddVal(0, 0, n + 1, tin[l], tout[l], -1);\n\t}\n\tcout << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1133",
    "index": "A",
    "title": "Middle of the Contest",
    "statement": "Polycarp is going to participate in the contest. It starts at $h_1:m_1$ and ends at $h_2:m_2$. It is guaranteed that the contest lasts an even number of minutes (i.e. $m_1 \\% 2 = m_2 \\% 2$, where $x \\% y$ is $x$ modulo $y$). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes.\n\nPolycarp wants to know the time of the midpoint of the contest. For example, if the contest lasts from $10:00$ to $11:00$ then the answer is $10:30$, if the contest lasts from $11:10$ to $11:12$ then the answer is $11:11$.",
    "tutorial": "Firstly, let's parse both strings to four integers ($h_1, m_1, h_2, m_2$). Just read them and then use some standard functions to transform them into integers (or we can do it manually). The second part is to obtain $t_1 = h_1 \\cdot 60 + m_1$ and $t_2 = h_2 \\cdot 60 + m_2$. Then let t3=t1+t22. It is the answer. We have to print h3= \\lfloor t360 \\rfloor  and m3=t3%60, where  \\lfloor ab \\rfloor  is a divided by b rounding down and a%b is a modulo b. The only thing we should do more carefully is to print one leading zero before h3 if it is less than 10 and do the same for m3.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint h1, m1;\n\tscanf(\"%d:%d\", &h1, &m1);\n\tint h2, m2;\n\tscanf(\"%d:%d\", &h2, &m2);\n\tint t1 = h1 * 60 + m1;\n\tint t2 = h2 * 60 + m2;\n\tint t3 = (t1 + t2) / 2;\n\tprintf(\"%02d:%02d\\n\", t3 / 60, t3 % 60);\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1133",
    "index": "B",
    "title": "Preparation for International Women's Day",
    "statement": "International Women's Day is coming soon! Polycarp is preparing for the holiday.\n\nThere are $n$ candy boxes in the shop for sale. The $i$-th box contains $d_i$ candies.\n\nPolycarp wants to prepare the maximum number of gifts for $k$ girls. Each gift will consist of \\textbf{exactly two} boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $k$. In other words, two boxes $i$ and $j$ ($i \\ne j$) can be combined as a gift if $d_i + d_j$ is divisible by $k$.\n\nHow many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes \"partially\" or redistribute candies between them.",
    "tutorial": "Let $cnt_i$ be the number of boxes with $i$ candies modulo $k$. Firstly, the number of pairs of boxes we can obtain using two boxes with remainder $0$ modulo $k$ is $\\lfloor\\frac{cnt_0}{2}\\rfloor$. Secondly, if $k$ is even then we also can obtain pairs of boxes using two boxes with remainder $\\frac{k}{2}$ modulo $k$ and its number is $\\lfloor\\frac{cnt_{\\frac{k}{2}}}{2}\\rfloor$. And for any other remainder $i$ from $1$ to $\\lfloor\\frac{k}{2}\\rfloor$ the number of pairs of boxes is $min(cnt_{i}, cnt_{k - i - 1})$. So, if we sum up all these values, the answer is this sum multiplied by two (because we have to print the number of boxes, not pairs).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> cnt(k);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\t++cnt[x % k];\n\t}\n\tint ans = cnt[0] / 2;\n\tif (k % 2 == 0) ans += cnt[k / 2] / 2;\n\tfor (int i = 1; i < (k + 1) / 2; ++i) {\n\t\tint j = k - i;\n\t\tans += min(cnt[i], cnt[j]);\n\t}\n\t\n\tcout << ans * 2 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1133",
    "index": "C",
    "title": "Balanced Team",
    "statement": "You are a coach at your local university. There are $n$ students under your supervision, the programming skill of the $i$-th student is $a_i$.\n\nYou have to create a team for a new programming competition. As you know, the more students some team has the more probable its victory is! So you have to create a team with the maximum number of students. But you also know that a team should be balanced. It means that the programming skill of each pair of students in a created team should differ by no more than $5$.\n\nYour task is to report the maximum possible number of students in a balanced team.",
    "tutorial": "Let's sort all values in non-decreasing order. Then we can use two pointers to calculate for each student i the maximum number of students j such that aj-ai \\le 5 (j>i). This is pretty standard approach. We also can use binary search to do it (or we can store for each programming skill the number of students with this skill and just iterate from some skill x to x+5 and sum up all numbers of students).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.begin(), a.end());\n\tint ans = 0;\n\tint j = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\twhile (j < n && a[j] - a[i] <= 5) {\n\t\t\t++j;\n\t\t\tans = max(ans, j - i);\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "sortings",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1133",
    "index": "D",
    "title": "Zero Quantity Maximization",
    "statement": "You are given two arrays $a$ and $b$, each contains $n$ integers.\n\nYou want to create a new array $c$ as follows: choose some real (i.e. not necessarily integer) number $d$, and then for every $i \\in [1, n]$ let $c_i := d \\cdot a_i + b_i$.\n\nYour goal is to maximize the number of zeroes in array $c$. What is the largest possible answer, if you choose $d$ optimally?",
    "tutorial": "For each index i \\in [1,n] let's try to find which d we should use in order to make i-th element of c equal to zero. If ai=0, then ci=bi no matter which d we choose. So we should just ignore this index and add 1 to the answer if bi=0. Otherwise, we should choose d=-biai. Let's calculate the required fraction for each index, and among all fractions find one that fits most indices (this can be done, for example, by storing all fractions in a map). The only thing that's left to analyze is how to compare the fractions, because floating-point numbers may be not precise enough. Let's store each fraction as a pair of integers (x,y), where x is the numenator and y is the denominator. We should normalize each fraction as follows: firstly, we reduce it by finding the greatest common divisor of x and y, and then dividing both numbers by this divisor. Secondly, we should ensure that numenator is non-negative, and if numenator is zero, then denominator should also be non-negative (this can be achieved by multiplying both numbers by -1).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n\nconst int N = 200043;\n\nvoid norm(pair<int, int>& p)\n{\n\tif(p.x < 0)\n\t{\n\t\tp.x *= -1;\n\t\tp.y *= -1;\n\t}\n\telse if (p.x == 0 && p.y < 0)\n\t{\n\t\tp.y *= -1;\n\t}\n\tint d = __gcd(abs(p.x), abs(p.y));\n\tp.x /= d;\n\tp.y /= d;\n}\n\nmap<pair<int, int>, int> m;\n\nint a[N];\nint b[N];\nint n;\n\nint main()\n{\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d\", &a[i]);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d\", &b[i]);\n\tint ans = 0;\n\tint cnt0 = 0;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(a[i] == 0)\n\t\t{\n\t\t\tif(b[i] == 0)\n\t\t\t\tcnt0++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpair<int, int> p = make_pair(-b[i], a[i]);\n\t\t\tnorm(p);\n\t\t\tm[p]++;\n\t\t\tans = max(ans, m[p]);\n\t\t}\n\t}\n\tcout << cnt0 + ans << endl;\n}",
    "tags": [
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1133",
    "index": "E",
    "title": "K Balanced Teams",
    "statement": "You are a coach at your local university. There are $n$ students under your supervision, the programming skill of the $i$-th student is $a_i$.\n\nYou have to form $k$ teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than $k$ (and at least one) \\textbf{non-empty} teams so that the \\textbf{total} number of students in them is maximized. But you also know that \\textbf{each} team should be balanced. It means that the programming skill of each pair of students in \\textbf{each} team should differ by no more than $5$. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).\n\nIt is possible that some students not be included in any team at all.\n\nYour task is to report the maximum possible \\textbf{total} number of students in no more than $k$ (and at least one) \\textbf{non-empty} balanced teams.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "Firstly, let's sort all students in order of non-decreasing their programming skill. Then let's calculate the following dynamic programming: dpi,j is the maximum number of students in at most j non-empty teams if we consider first i students. How to do transitions from dpi,j? The first transition is pretty intuitive: just skip the i-th (0-indexed) student. Then we can set dpi+1,j+1:=max(dpi+1,j+1,dpi,j). The second possible transition is to take some team starting from the i-th student. The only assumption we need to do it is the following: take the maximum by number of students team starting from the i-th student is always optimally. Why it is so? If we consider the student with the maximum programming skill in the team, we can take him to this team instad of forming the new team with this student because this is always not worse. So the second transition is the following: let cnti be the number of students in a team if the i-th student is the first in it. We can calculate this part in O(n2) naively or in O(n) using two pointers. We can set dpi+cnti,j+1=max(dpi+cnti,j+1,dpi,j+cnti). Time complexity: O(n(n+k)).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.begin(), a.end());\n\tvector<int> cnt(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\twhile (i + cnt[i] < n && a[i + cnt[i]] - a[i] <= 5) {\n\t\t\t++cnt[i];\n\t\t}\n\t}\n\t\n\tvector<vector<int>> dp(n + 1, vector<int>(k + 1));\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j <= k; ++j) {\n\t\t\tdp[i + 1][j] = max(dp[i + 1][j], dp[i][j]);\n\t\t\tif (j + 1 <= k) {\n\t\t\t\tdp[i + cnt[i]][j + 1] = max(dp[i + cnt[i]][j + 1], dp[i][j] + cnt[i]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << dp[n][k] << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1133",
    "index": "F1",
    "title": "Spanning Tree with Maximum Degree",
    "statement": "You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.\n\nYour task is to find \\textbf{any} spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it.",
    "tutorial": "We can take any vertex with the maximum degree and all its neighbours. To implement it, just run bfs from any vertex with the maximum degree. See the authors solution for better understanding.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nvector<vector<int>> g;\nvector<int> deg, used;\nvector<pair<int, int>> ans;\n\nmt19937 rnd(time(NULL));\n\nvoid bfs(int s) {\n\tused = vector<int>(n);\n\tused[s] = 1;\n\tqueue<int> q;\n\tq.push(s);\n\t\n\twhile (!q.empty()) {\n\t\tint v = q.front();\n\t\tq.pop();\n\t\tfor (auto to : g[v]) {\n\t\t\tif (used[to]) continue;\n\t\t\tif (rnd() & 1) ans.push_back(make_pair(v, to));\n\t\t\telse ans.push_back(make_pair(to, v));\n\t\t\tused[to] = 1;\n\t\t\tq.push(to);\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m;\n\tg = vector<vector<int>>(n);\n\tdeg = vector<int>(n);\n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t\t++deg[x];\n\t\t++deg[y];\n\t}\n\t\n\tint pos = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (deg[pos] < deg[i]) {\n\t\t\tpos = i;\n\t\t}\n\t}\n\t\n\tbfs(pos);\n\tshuffle(ans.begin(), ans.end(), rnd);\n\tfor (auto it : ans) cout << it.first + 1 << \" \" << it.second + 1 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "graphs"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1133",
    "index": "F2",
    "title": "Spanning Tree with One Fixed Degree",
    "statement": "You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.\n\nYour task is to find \\textbf{any} spanning tree of this graph such that the \\textbf{degree of the first vertex (vertex with label $1$ on it)} is equal to $D$ (or say that there are no such spanning trees). Recall that the degree of a vertex is the number of edges incident to it.",
    "tutorial": "Firstly, let's remove the vertex 1 from the graph. Then let's calculate the number of connected components. Let it be cnt. The answer is NO if and only if cnt>D or D is greater than the number of edges incident to the first vertex. Otherwise let's construct the answer. Firstly, let's add into the new graph spanning trees of components in the initial graph without vertex 1. Then let's add into the new graph cnt edges from vertex 1 - one edge to each component. Then let's add into the new graph any D-cnt remaining edges from vertex 1. The last thing we need is to construct a spanning tree of a new graph such that all edges incident to the vertex 1 are in this spanning tree (and other edges doesn't matter). How to do it? Let's run bfs from the vertex 1 in a new graph!",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m, D;\nvector<vector<int>> g;\n\nint cnt;\nvector<int> p, color;\nvector<pair<int, int>> ans;\n\nmt19937 rnd(time(NULL));\n\nvoid bfs(int s, int bad) {\n\tqueue<int> q;\n\tq.push(s);\n\tcolor[s] = cnt;\n\twhile (!q.empty()) {\n\t\tint v = q.front();\n\t\tq.pop();\n\t\tif (p[v] != -1) {\n\t\t\tif (rnd() & 1) ans.push_back(make_pair(p[v], v));\n\t\t\telse ans.push_back(make_pair(v, p[v]));\n\t\t}\n\t\tfor (auto to : g[v]) {\n\t\t\tif (to == bad || color[to] != -1) continue;\n\t\t\tp[to] = v;\n\t\t\tcolor[to] = cnt;\n\t\t\tq.push(to);\n\t\t}\n\t}\n\t++cnt;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m >> D;\n\tg = vector<vector<int>>(n);\n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\t\n\tp = color = vector<int>(n, -1);\n\tcnt = 0;\n\tfor (int i = 1; i < n; ++i) {\n\t\tif (color[i] == -1) {\n\t\t\tbfs(i, 0);\n\t\t}\n\t}\n\t\n\tif (cnt > D || D > int(g[0].size())) {\n\t\tcout << \"NO\" << endl;\n\t\treturn 0;\n\t}\n\t\n\tsort(g[0].begin(), g[0].end(), [](int a, int b) {\n\t\treturn color[a] < color[b];\n\t});\n\t\n\tfor (int i = 0; i < int(g[0].size()); ++i) {\n\t\tif (i == 0 || color[g[0][i]] != color[g[0][i - 1]]) {\n\t\t\tans.push_back(make_pair(0, g[0][i]));\n\t\t}\n\t}\n\tD -= cnt;\n\tfor (int i = 1; i < int(g[0].size()); ++i) {\n\t\tif (D == 0) break;\n\t\tif (color[g[0][i]] == color[g[0][i - 1]]) {\n\t\t\tans.push_back(make_pair(0, g[0][i]));\n\t\t\t--D;\n\t\t}\n\t}\n\t\n\tg = vector<vector<int>>(n);\n\tfor (auto it : ans) {\n\t\tg[it.first].push_back(it.second);\n\t\tg[it.second].push_back(it.first);\n\t}\n\tans.clear();\n\tp = color = vector<int>(n, -1);\n\tcnt = 0;\n\tbfs(0, -1);\n\t\n\tshuffle(ans.begin(), ans.end(), rnd);\n\tcout << \"YES\" << endl;\n\tfor (auto it : ans) {\n\t\tcout << it.first + 1 << \" \" << it.second + 1 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1136",
    "index": "A",
    "title": "Nastya Is Reading a Book",
    "statement": "After lessons Nastya decided to read a book. The book contains $n$ chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.\n\nYesterday evening Nastya did not manage to finish reading the book, so she marked the page with number $k$ as the first page which was not read (i.e. she read all pages from the $1$-st to the $(k-1)$-th).\n\nThe next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle).",
    "tutorial": "It is easy to understand that the first unread chapter is the last chapter, whom $l_i \\leq k$. In order to find it we can iterate through list of chapters in increasing order.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define int long long\\nconst int N = 101;\\nint n;\\npair <int, int> a[N];\\nsigned main() {\\n    #ifdef HOME\\n        freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    #else\\n        ios_base::sync_with_stdio(0); cin.tie(0);\\n    #endif\\n    cin >> n;\\n    for (int i = 0; i < n; ++i) cin >> a[i].first >> a[i].second;\\n    int p;\\n    cin >> p;\\n    for (int i = n - 1; i >= 0; --i) {\\n        if (a[i].first <= p) {\\n            cout << n - i << '\\\\n';\\n            exit(0);\\n        }   \\n    }   \\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1136",
    "index": "B",
    "title": "Nastya Is Playing Computer Games",
    "statement": "Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible.\n\nThere are $n$ manholes in the room which are situated on one line, but, unfortunately, all the manholes are closed, and there is one stone on every manhole. There is exactly one coin under every manhole, and to win the game Nastya should pick all the coins. Initially Nastya stands near the $k$-th manhole from the left. She is thinking what to do.\n\nIn one turn, Nastya can do one of the following:\n\n- if there is at least one stone on the manhole Nastya stands near, throw exactly one stone from it onto any other manhole (yes, Nastya is strong).\n- go to a neighboring manhole;\n- if there are no stones on the manhole Nastya stays near, she can open it and pick the coin from it. After it she must close the manhole immediately (it doesn't require additional moves).\n\n\\begin{center}\n{\\small The figure shows the intermediate state of the game. At the current position Nastya can throw the stone to any other manhole or move left or right to the neighboring manholes. If she were near the leftmost manhole, she could open it (since there are no stones on it).}\n\\end{center}\n\nNastya can leave the room when she picks all the coins. Monsters are everywhere, so you need to compute the minimum number of moves Nastya has to make to pick all the coins.\n\nNote one time more that Nastya can open a manhole only when there are no stones onto it.",
    "tutorial": "Note that in any case we will open $n$ hatches. Also, initial position of stones is : $1,1,1,1,1,1 ... 1$ ($1$ - the number of stones on the i-th hatch ).After any permutation of stones we will have permutation of numbers : $2,0,1,1,1,1,1...$ So, to open hatch with $2$ stones, we need at least $2$ movements. So, at all, we need at least $n+1$ movements(1). To get into all the hatches we need at least $min(n-k,k-1) + n-1$ movements.(since we can only go to the neighboring). So, at all, answer is : $(n+1) + n + (n-1) + min(n-k,k-1) = 3n + min(n-k,k-1)$.",
    "code": "\"#include<bits/stdc++.h>\\nusing namespace std;\\n#define int long long\\nsigned main() {\\n    #ifdef HOME\\n        freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    #else\\n        ios_base::sync_with_stdio(0); cin.tie(0); cout.precision(20);\\n    #endif\\n    int n, p;\\n    cin >> n >> p;\\n    cout << (2 * n + 1) + (n - 1) + min(p - 1, n - p) << '\\\\n';\\n}\"",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1136",
    "index": "C",
    "title": "Nastya Is Transposing Matrices",
    "statement": "Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.\n\nTwo matrices $A$ and $B$ are given, each of them has size $n \\times m$. Nastya can perform the following operation to matrix $A$ unlimited number of times:\n\n- take any square square submatrix of $A$ and transpose it (i.e. the element of the submatrix which was in the $i$-th row and $j$-th column of the submatrix will be in the $j$-th row and $i$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $A$).\n\nNastya's task is to check whether it is possible to transform the matrix $A$ to the matrix $B$.\n\n\\begin{center}\n{\\small Example of the operation}\n\\end{center}\n\nAs it may require a lot of operations, you are asked to answer this question for Nastya.\n\nA square submatrix of matrix $M$ is a matrix which consist of all elements which comes from one of the rows with indeces $x, x+1, \\dots, x+k-1$ of matrix $M$ and comes from one of the columns with indeces $y, y+1, \\dots, y+k-1$ of matrix $M$. $k$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).",
    "tutorial": "Let's note that after applying the operation multiset of numbers on each diagonal (which goes up and right) stays the same. Also we can get any permutation of numbers on any diagonal because we can swap neighboring elements on diagonal. So, we just need to check if the multisets of numbers on corresponding diagonals are the same.",
    "code": "\"#include <iostream>\\n#include <vector>\\n#include <algorithm>\\nusing namespace std;\\n#define int long long\\nconst int MAXN = 500;\\nint a[MAXN][MAXN];\\nint b[MAXN][MAXN];\\nvector<int> aa[MAXN * 2];\\nvector<int> bb[MAXN * 2];\\nsigned main() {\\n\\tios_base::sync_with_stdio(false);\\n\\n\\tint n, m;\\n\\tcin >> n >> m;\\n\\tfor (int i = 0; i < n; ++i)\\n\\t\\tfor (int j = 0; j < m; ++j) {\\n\\t\\t\\tcin >> a[i][j];\\n\\t\\t\\taa[i + j].push_back(a[i][j]);\\n\\t\\t}\\n\\tfor (int i = 0; i < n; ++i)\\n\\t\\tfor (int j = 0; j < m; ++j) {\\n\\t\\t\\tcin >> b[i][j];\\n\\t\\t\\tbb[i + j].push_back(b[i][j]);\\n\\t\\t}\\n\\tbool ok = 1;\\n\\tfor (int i = 0; i < MAXN * 2; ++i) {\\n\\t\\tsort(aa[i].begin(), aa[i].end());\\n\\t\\tsort(bb[i].begin(), bb[i].end());\\n\\t\\tif (aa[i] != bb[i])\\n \\t\\t\\tok = 0;\\n\\t}\\n\\tif (ok)\\n\\t\\tcout << \\\"YES\\\";\\n\\telse\\n\\t\\tcout << \\\"NO\\\";\\n\\treturn 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1136",
    "index": "D",
    "title": "Nastya Is Buying Lunch",
    "statement": "At the big break Nastya came to the school dining room. There are $n$ pupils in the school, numbered from $1$ to $n$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.\n\nFormally, there are some pairs $u$, $v$ such that if the pupil with number $u$ stands directly in front of the pupil with number $v$, Nastya can ask them and they will change places.\n\nNastya asks you to find the maximal number of places in queue she can move forward.",
    "tutorial": "Solution 1: Let's solve the proiblem, iterating from the end, adding pupils one by one. I. e for every suffix we are solving original problem without pupils, which don't belong to this suffix. What happens when we add pupil $i$ to the suffix? By the time when we add pupil $i$ we have answer for the previous suffix. In this answer there are, probably, pupils, which Nastya can't overtake. Let this subset of pupils be $P$. Then, if $i$-th pupil can give place for Nastya and all pupils from $P$, we will swap them. Otherwise, we can add this pupil to $P$. In order to check this condition we can iterate through pupils, who can swap with $i$-th pupil, and calculate how many are contained in $P$. This solution works in $O(n+m)$. Obviously, when we consider all suffixes, answer will be $n-1-|P|$. Solution 2: Let's build directed graph, where $i$-th vertex corresponds $i$-th pupil and edge from $u$ to $v$ exists if and only if pupil $v$ can't give place to pupil $u$ and $v$ is closer to the beginning of queue than $u$. We can note that answer is number of vertexes in this graph, which are unreachable from Nastya's vertex. Proof: (1) Obviously, if edge from $u$ to $v$ exists, pupil $v$ will always be in front of $u$. (2) If vertex $v$ is reachable from vertex $u$, the same condition is true. Let's prove that Nastya can overtake pupils, who are unreachable in graph by giving an algorithm how to do it. Let there are unreachable vertexes in front of Nastya, $u$ - the closest from them. If $u$ is directly in front of Nastya, they can swap and number of such vertexes will decrease. Otherwise, let $v$ be the next pupil after $u$ (further from the beginning). Because $u$ is the closest unreachable vertex, $v$ is reachable. So, there is no edge from $u$ to $v$ and they can change their places. We can similarly move $v$ further and then swap him with Nastya. Using this algorithm, Nastya can overtake all pupils, which correspond unreachable vertexes. Fine, now we just have to calculate number of such vertexes. It can be done with standard algorithm \"DFS by complement graph\".",
    "code": "\"#include <bits/stdc++.h>\\n//#pragma comment(linker, \\u201d/STACK:36777216\\u201c)\\n           \\nusing namespace std;\\n           \\ntypedef long long ll;\\n#define mp make_pair\\n#define pb push_back\\n#define x first\\n#define y second\\n#define all(a) a.begin(), a.end()\\n#define db long double\\n\\nint n, m;\\nvector<int> a, was;\\nvector<vector<int> > g;\\n\\nint main(){\\n    //freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    //freopen(\\\"output.txt\\\", \\\"w\\\", stdout);\\n    ios_base::sync_with_stdio(0); cin.tie(0);\\n    cin >> n >> m;\\n    a.resize(n);\\n    g.resize(n);\\n    was.resize(n);\\n    for (int i = 0; i < n; i++) cin >> a[i], a[i]--;\\n    for (int i = 0; i < m; i++){\\n    \\tint w1, w2;\\n    \\tcin >> w1 >> w2;\\n    \\tw1--; w2--;\\n    \\tg[w1].pb(w2);\\n    }\\n\\n    reverse(all(a));\\n    int ans = 0;\\n\\n    for (int i = 0; i < n; i++) was[i] = 0;\\n    was[a[0]] = 1;\\n\\tint cnt = 1;\\n\\tfor (int i = 1; i < n; i++){\\n\\t\\tint cnt2 = 0;\\n\\t\\tfor (int to : g[a[i]]){\\n\\t\\t\\tif (was[to]) cnt2++;\\n\\t\\t}\\n\\t\\tif (cnt == cnt2){\\n\\t\\t\\tans++;\\n\\t\\t} else {\\n\\t\\t\\twas[a[i]] = 1;\\n\\t\\t\\tcnt++;\\n\\t\\t}\\n\\t}\\n\\n    cout << ans;\\n}\"",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1136",
    "index": "E",
    "title": "Nastya Hasn't Written a Legend",
    "statement": "In this task, Nastya asked us to write a formal statement.\n\nAn array $a$ of length $n$ and an array $k$ of length $n-1$ are given. Two types of queries should be processed:\n\n- increase $a_i$ by $x$. Then if $a_{i+1} < a_i + k_i$, $a_{i+1}$ becomes exactly $a_i + k_i$; again, if $a_{i+2} < a_{i+1} + k_{i+1}$, $a_{i+2}$ becomes exactly $a_{i+1} + k_{i+1}$, and so far for $a_{i+3}$, ..., $a_n$;\n- print the sum of the contiguous subarray from the $l$-th element to the $r$-th element of the array $a$.\n\nIt's guaranteed that initially $a_i + k_i \\leq a_{i+1}$ for all $1 \\leq i \\leq n-1$.",
    "tutorial": "Let $t_{i} = k_{1} + k_{2} + ... + k_{i - 1}$, $b_{i} = a_{i} - t_{i}$. We can rewrite the condition $a_{i+1} >= a_{i} + k_{i}$, using array $b$: $a_{i+1} >= a_{i} + k_{i}$ $a_{i+1} - k_{i} >= a_{i}$ $a_{i+1} - k_{i} - k_{i-1} - ... - k_{1} >= a_{i} - k_{i-1} - ... - k_{1}$ $a_{i+1} - t_{i+1} >= a_{i} - t_{i}$ $b_{i+1} >= b_{i}$ Let's calculate arrays $t$ and $b$. So as $a_{i} = b_{i} + t_{i}$, in order to get sum in subarray of $a$, we can sum corresponding sums in $b$ and $t$. Now let's find out what happens with $b$ after addition $x$ to position $i$. $b_{i}$ increases exactly on $x$. Then, if $b_{i+1} < b_{i}$, $b_{i+1}$ becomes equal to $b_{i}$, and so on for $i+2$, $i+3$, ..., $n$. Note that array $b$ is always sorted and each addition sets value $b_{i} + x$ in half-interval $[i, pos)$, where $pos$ - the lowest index such as $b_{pos} >= b_{i} + x$ To handle these modifications, let's build segment tree on array $b$ with operation \"set value on a segment\", which stores sum and maximum in every vertex. The only problem is how to find $pos$. This can be done with descending along the segment tree. If the maximum in the left son of current vertex is bigger or equal that $b_{i} + x$, we go to the left son, otherwise we go the right son. BONUS: solve it with modifications of elements of $k$.",
    "code": "\"/*\\n\\nCode for problem E by cookiedoth\\nGenerated 23 Feb 2019 at 02.32 P\\n\\n\\n\\u2585\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588 ]\\u2584\\u2584\\u2584\\u2584\\u2584\\u2584\\u2584 \\n\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2585\\u2584\\u2583 \\nIl\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588\\u2588] \\n\\u25e5\\u2299\\u25b2\\u2299\\u25b2\\u2299\\u25b2\\u2299\\u25b2\\u2299\\u25b2\\u2299\\u25b2\\u2299\\u25e4\\n\\n~_^\\n=_=\\n\\u00af\\\\_(\\u30c4)_/\\u00af\\n\\n*/\\n\\n#include <iostream>\\n#include <fstream>\\n#include <vector>\\n#include <set>\\n#include <map>\\n#include <bitset>\\n#include <algorithm>\\n#include <iomanip>\\n#include <cmath>\\n#include <ctime>\\n#include <functional>\\n#include <unordered_set>\\n#include <unordered_map>\\n#include <string>\\n#include <queue>\\n#include <deque>\\n#include <stack>\\n#include <complex>\\n#include <cassert>\\n#include <random>\\n#include <cstring>\\n#include <numeric>\\n#define ll long long\\n#define ld long double\\n#define null NULL\\n#define all(a) a.begin(), a.end()\\n#define debug(a) cerr << #a << \\\" = \\\" << a << endl\\n#define forn(i, n) for (int i = 0; i < n; ++i)\\n#define sz(a) (int)a.size()\\n\\nusing namespace std;\\n\\ntemplate<class T> int chkmax(T &a, T b) {\\n\\tif (b > a) {\\n\\t\\ta = b;\\n\\t\\treturn 1;\\n\\t}\\n\\treturn 0;\\n}\\n\\ntemplate<class T> int chkmin(T &a, T b) {\\n\\tif (b < a) {\\n\\t\\ta = b;\\n\\t\\treturn 1;\\n\\t}\\n\\treturn 0;\\n}\\n\\ntemplate<class iterator> void output(iterator begin, iterator end, ostream& out = cerr) {\\n\\twhile (begin != end) {\\n\\t\\tout << (*begin) << \\\" \\\";\\n\\t\\tbegin++;\\n\\t}\\n\\tout << endl;\\n}\\n\\ntemplate<class T> void output(T x, ostream& out = cerr) {\\n\\toutput(x.begin(), x.end(), out);\\n}\\n\\nvoid fast_io() {\\n\\tios_base::sync_with_stdio(0);\\n\\tcin.tie(0);\\n\\tcout.tie(0);\\n}\\n\\nconst ll DEFAULT = -1e18;\\n\\nstruct st {\\n\\tvector<ll> t, len, sum, add_mod, set_mod;\\n\\tint n;\\n\\n\\tvoid build(vector<ll> &a, int v, int tl, int tr) {\\n\\t\\tif (tl == tr) {\\n\\t\\t\\tt[v] = sum[v] = a[tl];\\n\\t\\t\\tlen[v] = 1;\\n\\t\\t}\\n\\t\\telse {\\n\\t\\t\\tint tm = (tl + tr) >> 1;\\n\\t\\t\\tbuild(a, v * 2, tl, tm);\\n\\t\\t\\tbuild(a, v * 2 + 1, tm + 1, tr);\\n\\t\\t\\tt[v] = max(t[v * 2], t[v * 2 + 1]);\\n\\t\\t\\tsum[v] = sum[v * 2] + sum[v * 2 + 1];\\n\\t\\t\\tlen[v] = (tr - tl + 1);\\n\\t\\t}\\n\\t}\\n\\n\\tst(vector<ll> &a) {\\n\\t\\tn = a.size();\\n\\t\\tt.resize(4 * n);\\n\\t\\tsum.resize(4 * n);\\n\\t\\tadd_mod.resize(4 * n);\\n\\t\\tset_mod.resize(4 * n, DEFAULT);\\n\\t\\tlen.resize(4 * n);\\n\\t\\tbuild(a, 1, 0, n - 1);\\n\\t}\\n\\n\\tst() {}\\n\\n\\tvoid apply_add_mod(int v, ll val) {\\n\\t\\tif (set_mod[v] != DEFAULT) {\\n\\t\\t\\tset_mod[v] += val;\\n\\t\\t}\\n\\t\\telse {\\n\\t\\t\\tadd_mod[v] += val;\\n\\t\\t}\\n\\t}\\n\\n\\tvoid apply_set_mod(int v, ll val) {\\n\\t\\tadd_mod[v] = 0;\\n\\t\\tset_mod[v] = val;\\n\\t}\\n\\n\\tvoid push(int v) {\\n\\t\\tassert(add_mod[v] == 0 || set_mod[v] == DEFAULT);\\n\\t\\tif (add_mod[v]) {\\n\\t\\t\\tt[v] += add_mod[v];\\n\\t\\t\\tsum[v] += add_mod[v] * len[v];\\n\\t\\t\\tapply_add_mod(v * 2, add_mod[v]);\\n\\t\\t\\tapply_add_mod(v * 2 + 1, add_mod[v]);\\n\\t\\t\\tadd_mod[v] = 0;\\n\\t\\t}\\n\\t\\tif (set_mod[v] != DEFAULT) {\\n\\t\\t\\tt[v] = set_mod[v];\\n\\t\\t\\tsum[v] = set_mod[v] * len[v];\\n\\t\\t\\tapply_set_mod(v * 2, set_mod[v]);\\n\\t\\t\\tapply_set_mod(v * 2 + 1, set_mod[v]);\\n\\t\\t\\tset_mod[v] = DEFAULT;\\n\\t\\t}\\n\\t}\\n\\n\\tll get_sum(int v) {\\n\\t\\tif (set_mod[v] != DEFAULT) {\\n\\t\\t\\treturn set_mod[v] * len[v];\\n\\t\\t}\\n\\t\\tif (add_mod[v]) {\\n\\t\\t\\treturn add_mod[v] * len[v] + sum[v];\\n\\t\\t}\\n\\t\\treturn sum[v];\\n\\t}\\n\\n\\tll get_t(int v) {\\n\\t\\tif (set_mod[v] != DEFAULT) {\\n\\t\\t\\treturn set_mod[v];\\n\\t\\t}\\n\\t\\tif (add_mod[v]) {\\n\\t\\t\\treturn add_mod[v] + t[v];\\n\\t\\t}\\n\\t\\treturn t[v];\\n\\t}\\n\\n\\tvoid recalc(int v) {\\n\\t\\tt[v] = max(get_t(v * 2), get_t(v * 2 + 1));\\n\\t\\tsum[v] = get_sum(v * 2) + get_sum(v * 2 + 1);\\n\\t}\\n\\n\\tvoid add_update(int l, int r, ll val, int v, int tl, int tr) {\\n\\t\\tif (l > r) {\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\t\\tif (l == tl && r == tr) {\\n\\t\\t\\tapply_add_mod(v, val);\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\t\\tint tm = (tl + tr) >> 1;\\n\\t\\tpush(v);\\n\\t\\tadd_update(l, min(r, tm), val, v * 2, tl, tm);\\n\\t\\tadd_update(max(l, tm + 1), r, val, v * 2 + 1, tm + 1, tr);\\n\\t\\trecalc(v);\\n\\t}\\n\\n\\tvoid set_update(int l, int r, ll val, int v, int tl, int tr) {\\n\\t\\tif (l > r) {\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\t\\tif (l == tl && r == tr) {\\n\\t\\t\\tapply_set_mod(v, val);\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\t\\tint tm = (tl + tr) >> 1;\\n\\t\\tpush(v);\\n\\t\\tset_update(l, min(r, tm), val, v * 2, tl, tm);\\n\\t\\tset_update(max(l, tm + 1), r, val, v * 2 + 1, tm + 1, tr);\\n\\t\\trecalc(v);\\n\\t}\\n\\n\\tll get_sum(int l, int r, int v, int tl, int tr) {\\n\\t\\tif (l > r) {\\n\\t\\t\\treturn 0;\\n\\t\\t}\\n\\t\\tif (l == tl && r == tr) {\\n\\t\\t\\treturn get_sum(v);\\n\\t\\t}\\n\\t\\tint tm = (tl + tr) >> 1;\\n\\t\\tpush(v);\\n\\t\\tll res_l = get_sum(l, min(r, tm), v * 2, tl, tm);\\n\\t\\tll res_r = get_sum(max(l, tm + 1), r, v * 2 + 1, tm + 1, tr);\\n\\t\\treturn res_l + res_r;\\n\\t}\\n\\n\\tint lower_bound(ll val, int v, int tl, int tr) {\\n\\t\\tif (tl == tr) {\\n\\t\\t\\treturn tl;\\n\\t\\t}\\n\\t\\tpush(v);\\n\\t\\tint tm = (tl + tr) >> 1;\\n\\t\\tif (get_t(v * 2) >= val) {\\n\\t\\t\\treturn lower_bound(val, v * 2, tl, tm);\\n\\t\\t}\\n\\t\\telse {\\n\\t\\t\\treturn lower_bound(val, v * 2 + 1, tm + 1, tr);\\n\\t\\t}\\n\\t}\\n\\n\\t//interface\\n\\n\\tvoid add_update(int l, int r, ll val) {\\n\\t\\tadd_update(l, r, val, 1, 0, n - 1);\\n\\t}\\n\\n\\tvoid set_update(int l, int r, ll val) {\\n\\t\\tset_update(l, r, val, 1, 0, n - 1);\\n\\t}\\n\\n\\tll get_sum(int l, int r) {\\n\\t\\tll res = get_sum(l, r, 1, 0, n - 1);\\n\\t\\treturn res;\\n\\t}\\n\\n\\tint lower_bound(ll val) {\\n\\t\\tif (get_t(1) < val) {\\n\\t\\t\\treturn n;\\n\\t\\t}\\n\\t\\telse {\\n\\t\\t\\treturn lower_bound(val, 1, 0, n - 1);\\n\\t\\t}\\n\\t}\\n};\\n\\nint n;\\nvector<ll> a, k, prefK, b;\\n\\nsigned main() {\\n\\tfast_io();\\n\\t\\n\\tcin >> n;\\n\\ta.resize(n);\\n\\tk.resize(n - 1);\\n\\tprefK.resize(n);\\n\\tfor (int i = 0; i < n; ++i) {\\n\\t\\tcin >> a[i];\\n\\t}\\n\\tfor (int i = 0; i < n - 1; ++i) {\\n\\t\\tcin >> k[i];\\n\\t}\\n\\tfor (int i = 1; i < n; ++i) {\\n\\t\\tprefK[i] = prefK[i - 1] + k[i - 1];\\n\\t}\\n\\n\\tb.resize(n);\\n\\tfor (int i = 0; i < n; ++i) {\\n\\t\\tb[i] = a[i] - prefK[i];\\n\\t}\\n\\tst t(b), t1(prefK);\\n\\n\\tint q;\\n\\tcin >> q;\\n\\tfor (int i = 0; i < q; ++i) {\\n\\t\\tchar type;\\n\\t\\tcin >> type;\\n\\t\\tif (type == 's') {\\n\\t\\t\\tint l, r;\\n\\t\\t\\tcin >> l >> r;\\n\\t\\t\\tl--;\\n\\t\\t\\tr--;\\n\\t\\t\\tcout << t.get_sum(l, r) + t1.get_sum(l, r) << '\\\\n';\\n\\t\\t}\\n\\t\\tif (type == '+') {\\n\\t\\t\\tint pos;\\n\\t\\t\\tll val;\\n\\t\\t\\tcin >> pos >> val;\\n\\t\\t\\tpos--;\\n\\t\\t\\tval += t.get_sum(pos, pos);\\n\\t\\t\\tint pos1 = t.lower_bound(val);\\n\\t\\t\\tt.set_update(pos, pos1 - 1, val);\\n\\t\\t}\\n\\t}\\n}\"",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1137",
    "index": "A",
    "title": "Skyscrapers",
    "statement": "Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $n$ streets along the Eastern direction and $m$ streets across the Southern direction. Naturally, this city has $nm$ intersections. At any intersection of $i$-th Eastern street and $j$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.\n\nWhen Dora passes through the intersection of the $i$-th Eastern and $j$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.\n\nFormally, on every of $nm$ intersections Dora solves an independent problem. She sees $n + m - 1$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result \"greater\", \"smaller\" or \"equal\". Now Dora wants to select some integer $x$ and assign every skyscraper a height from $1$ to $x$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to \\textbf{independently} calculate the minimum possible $x$.\n\nFor example, if the intersection and the two streets corresponding to it look as follows:\n\nThen it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons \"less\", \"equal\", \"greater\" inside the Eastern street and inside the Southern street are preserved)\n\nThe largest used number is $5$, hence the answer for this intersection would be $5$.\n\nHelp Dora to compute the answers for each intersection.",
    "tutorial": "Let's examine the $i$-th row and $j$-th column, suppose the element on their intersection is $x$ Let's denote the number of different elements less than $x$ in the row as $L_{row}$, and in the column as $L_{col}$. Similarly, let's say that the number of different elements greater than $x$ in row is $G_{row}$ and in column is $G_{col}$ (L = Less, G = Greater). Then the answer is $ans = \\max(L_{row}, L_{col}) + 1 + \\max(G_{row}, G_{col})$. First summand is necessary to fit all elements $<x$, second is for $x$ and the last one for $>x$. Now let's find a way to compute all this $4$ values. Let's for each line and each column write down all the elements in it, sort them, delete repeating elements and save the result in such form. Now how to find $L_{row}$ and $G_{row}$? Simply do a binary search over this list to find the element equal to $x$. If the length of this list is $x$ and the position of the found element is $i$ ($0$-based), then $L_{row} = i$ and $G_{row} = k - 1 - i$. Similarly we can find $L_{col}$, $G_{col}$ and solve the problem Complexity is: $\\mathcal{O}(nm \\log)$.",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1137",
    "index": "B",
    "title": "Camp Schedule",
    "statement": "The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule $s$, which can be represented as a binary string, in which the $i$-th symbol is '1' if students will write the contest in the $i$-th day and '0' if they will have a day off.\n\nAt the last moment Gleb said that the camp will be the most productive if it runs with the schedule $t$ (which can be described in the same format as schedule $s$). Since the number of days in the current may be different from number of days in schedule $t$, Gleb required that the camp's schedule must be altered so that the number of occurrences of $t$ in it as a substring is maximum possible. At the same time, \\textbf{the number of contest days and days off shouldn't change}, only their order may change.\n\nCould you rearrange the schedule in the best possible way?",
    "tutorial": "If we can't make any occurrences of string $t$ in string $s$ just output any permutation of $s$. Otherwise, we can show that there is an optimal answer $x$, such that it starts with a string $t$. Suppose the opposite, then remove all characters of the string $s$ before the first occurrence of the string $t$ and insert them to the end. The number of occurrences clearly didn't decreased. Obviously, we want to make the next occurrence of string $t$ in string $s$ as left as possible. If we decide to make it somewhere else, we can move out the extra characters and try to improve the answer. To achieve this, we need to find the largest suffix of the string $t$ that matches the prefix of string $t$ of the same length. It can be found by using the prefix function, z-function or hashes.",
    "tags": [
      "greedy",
      "hashing",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1137",
    "index": "C",
    "title": "Museums Tour",
    "statement": "In the country $N$, there are $n$ cities connected by $m$ one-way roads. Although this country seems unremarkable, there are two interesting facts about it. At first, a week lasts $d$ days here. At second, there is exactly one museum in each city of the country $N$.\n\nTravel agency \"Open museums\" is developing a new program for tourists interested in museums. Agency's employees know which days each of the museums is open. The tour should start in the capital — the city number $1$, and the first day of the tour must be on the first day of a week. Each day a tourist will be in some city, watching the exposition in its museum (in case museum is open today), and by the end of the day, the tour either ends or the tourist goes into another city connected by a road with the current one. The road system of $N$ is designed in such a way that traveling by a road always takes one night and also all the roads are \\textbf{one-way}. It's allowed to visit a city multiple times during the trip.\n\nYou should develop such route for the trip that the number of \\textbf{distinct} museums, possible to visit during it, is maximum.",
    "tutorial": "Let's build a graph where the vertices are ($u$, $t$) where u is the node for original graph and $t$ is a day modulo $d$ (days are indexed from $0$ to $d - 1$). Then connect ($u$, $t$) to ($v$, $(t + 1)\\,mod\\,d$) for all edges $(u, v)$ from original graph and find the strongly connected components of this graph. For each of the SCC compute the number of different opened museums in it. Then we just need to find a path with maximum cost that begins in SCC which contains ($1$, $0$). We can do it with a dynamic programming on the DAG. The key fact is that if there is a path from ($u$, $j$) to ($u$, $j'$), then there is also a path from ($u$, $j'$) to ($u$, $j$) (simply go this path in original graph $d - 1$ times more), so we won't count some museum twice in the dynamic programming on this graph.",
    "tags": [
      "dp",
      "graphs",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1137",
    "index": "D",
    "title": "Cooperative Game",
    "statement": "This is an interactive problem.\n\nMisha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game \"Lake\".\n\nMisha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of $c$ vertices. The second part is a path from home to the lake which is a chain of $t$ vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither $t$ nor $c$.\n\nNote that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.\n\nAt the beginning of the game pieces of all the ten players, indexed with consecutive integers from $0$ to $9$, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than $q$ such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.\n\nThe goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of $c$, $t$ and $q$, but luckily they are your friends. Help them: coordinate their actions to win the game.\n\nMisha has drawn such a field that $1 \\le t, c$, $(t+c) \\leq 1000$ and $q = 3 \\cdot (t+c)$.",
    "tutorial": "The count of friends you have in the problem was actually a misleading. Here is how to solve this problem with only three of them. Let's name them $fast$, $slow$, $lazy$, and then consider the following process: $fast$ and $slow$ moves forward, then $fast$ only, then $fast$ and $slow$ again and so on until at some moment they will appear in same vertex on cycle ($fast$ takes the lead, makes it to the cycle, circles there until $slow$ makes it to the cycle too, and then approaches him, reducing the distance between them by $1$ every $2$ moves). Here you can notice, that $slow$ had no time to make even one full circle on cycle, because in that case $fast$ would managed to make at least two full circles and they would meet earlier. Let $r$ denote the distance from finish vertex to the one $fast$ and $slow$ met. Then $slow = t + x$ ($1$) and $fast = t + ?\\cdot{}c + x$ ($2$). Also $fast = 2\\cdot{}slow$ ($3$) as soon as $fast$ had a move at each step and $slow$ had only on the odd ones. Substitute ($1$) and ($2$) into ($3$) and you would get $t + ?\\cdot{}c + x = 2\\cdot{}t + 2\\cdot{}x$. Simplify it and take in modulo $c$ to get $-x \\equiv t \\pmod{c}$, i.e. if you would now apply $t$ moves to $fast$ and $slow$ they would end up in finish vertex, and if we instead somehow would manage to apply exactly $t$ moves to all friends, all of them would end up in the finish vertex. Here is the last bit of the solution: instead of trying to compute $t$ let's just move all friends until all of them would meet in one vertex - that vertex will be the finish one. Described solution takes less than $2 \\cdot (c + t)$ steps in the first stage and exactly $t$ steps in the second stage, so in total it would made less than $3 \\cdot (c + t)$.",
    "tags": [
      "constructive algorithms",
      "interactive",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1137",
    "index": "E",
    "title": "Train Car Selection",
    "statement": "Vasya likes to travel by train, but doesn't like when the car he travels in is located in the tail of the train.\n\nVasya gets on the train at the station. The train consists of $n$ cars indexed from $1$ to $n$ counting from the locomotive (head of the train). Three types of events occur while the train is moving:\n\n- Some number of cars are added to the head of the train;\n- Some number of cars are added to the tail of the train;\n- Vasya recalculates the values of the convenience of the cars (read more about it below).\n\nAt each moment of time we will index the cars from the head of the train, starting from $1$. Note that when adding new cars to the head of the train, the indexing of the old ones may shift.\n\nTo choose which car to go in, Vasya will use the value $A_i$ for each car (where $i$ is a car index), which is calculated as follows:\n\n- At the beginning of the trip $A_i=0$, as well as for the new cars at the time of their addition.\n- During the next recalculation Vasya chooses some \\textbf{positive} integers $b$ and $s$ and adds to all $A_i$ value $b + (i - 1) \\cdot s$.\n\nVasya hasn't decided yet where he will get on the train and where will get off the train, so after each event of one of the three types he wants to know the least index of the car, such that its value $A_i$ is minimal. Since there is a lot of cars, Vasya asked you to write a program that answers his question.",
    "tutorial": "There are many approaches to this problem, many of them having $\\mathcal{O}(q \\log q)$ time, but we will describe a purely linear solution. First, notice that for every group of cars added together, we need only to care about the first car in this group - the remaining ones will never be the answer. Second, notice that there are some cars appended to the head of the train, then all previous cars will never be answer again, so we can simply replace them with cars with $A_i = 0$. So now we only need to care about operations of adding cars to the tail, and about adding the progression. Suppose cars located at positions $x$ and have comfort $A_x$. Then observe the lower-left convex hull of points $(x, A_x)$. One can see, that the points not lying on this hull will never be an answer. Also note, that we can handle all progressions implicitly - suppose the progressions are described with $b_i$, $s_i$. Then let's simply store current sums of $b_i$ and $s_i$. Then the operation of adding progression can be done by simply adding to those sums, also we don't have to track the moment the cars are added, since we can simply subtract from $A_i$ based on sums at the moment of addition. So when we add cars to the end we simply need to add point to the end and possibly drop some points from the end of the current convex hull. And when we add new progression, we may also need to drop some elements from the hull, but since it's the convex hull, the line coefficients between neighboring points are monotonous, so we need to drop only some points in the end of the hull.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1137",
    "index": "F",
    "title": "Matches Are Not a Child's Play ",
    "statement": "Lena is playing with matches. The natural question arising in the head of any child playing with matches is whether it's possible to set a tree on fire with a matches, or not.\n\nLet's say, that the tree is a connected graph without cycles and the vertices are labeled with integers $1, 2, \\ldots, n$. Also every vertex $v$ has some integer priority $p_v$ associated with it. All priorities are distinct.\n\nIt turns out, that if you set a tree on fire, it will burn to nothing. However, this process doesn't happen instantly. At the beginning, burns out the leaf (a vertex is called to be a leaf if it has only one adjacent vertex) of the tree of the minimum priority. Then burns out the leaf of the minimal priority of the remaining tree, and so on. This way, the vertices turn into the leaves and burn out until only one vertex remains. Then this vertex burns out as well.\n\nLena has prepared a tree of $n$ vertices and every vertex in it has a priority $p_v = v$. Lena is very curious about burning out this tree. However, she understands, that if she will burn the tree now, then it will disappear completely. Lena is a kind girl and she will feel bad for the burned tree, so she wants to study the process of burning the tree only in her mind. Lena wants to process $q$ queries, each of them is one of three following types:\n\n- \"up $v$\", assign the vertex $v$ priority $1 + \\max\\{p_1, p_2, \\ldots, p_n\\}$;\n- \"when $v$\", find the step at which the vertex $v$ will burn out, if the tree would be set on fire now;\n- \"compare $v$ $u$\", find out which of the vertices $v$ and $u$ will burn out first, if the tree would be set on fire now.\n\nNotice, that if all priorities would be distinct, then after the \"up\" query they will stay distinct as well. Initially all priorities are distinct, hence during any (purely hypothetical of course) burning of the tree, all leafs would have distinct priorities.",
    "tutorial": "First, let's notice, that operation \"compare\" is redundant and can be implemented as two \"when\" operations (we didn't removed it from onsite olympiad's version as a possible hint). Suppose we know the order of the burning vertices. How it will change after \"up\" operation? Actually, quite simply: let's notice, that the part from previous maximum to the new one will burn the last. Actually, everything except this path burns out in the same relative order as before, and then burns the path, in order from older maximum to the new one. Let's say, that \"up\" paints it's path in the color i (and i++). Then to calculate when[v], let's first get the color of vertex v. And then when[v] equals to the number of vertices of smaller colors plus the number of vertices of the same color, but which will burn before this one. The latter is simply the number of vertices on the path from older maximum to the new one in the corresponding up query. To implement coloring on the path, we can use Heavy-Light-Decomposition. Inside every path of HLD let's store a set of segments of vertices of the same color. Then operation to color some path works in $O(\\log^2 n)$, amortized. The number of vertices with smaller color can be calculated with a fenwick tree (which stores for color the number of such vertices). There are also small technical details to handle: you need to account the original order of burning out, before all up's. But since each vertex changes it's color from zero to nonzero at most once, you can do it in O(number such vertices).",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1138",
    "index": "A",
    "title": "Sushi for Two",
    "statement": "Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $n$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.\n\nThe pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $i$-th from the left sushi as $t_i$, where $t_i = 1$ means it is with tuna, and $t_i = 2$ means it is with eel.\n\nArkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment $[2, 2, 2, 1, 1, 1]$ is valid, but subsegment $[1, 2, 1, 2, 1, 2]$ is not, because both halves contain both types of sushi.\n\nFind the length of the longest continuous subsegment of sushi Arkady can buy.",
    "tutorial": "It is more or less obvious that the answer is the maximum among the minimums of the length of two consecutive segments of equal elements. As for implementation, just go from left to right and keep the last element, the length of the current segment and the length of the next segment. When the current element is not the same as the last element, update the answer.",
    "tags": [
      "binary search",
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1138",
    "index": "B",
    "title": "Circus",
    "statement": "Polycarp is a head of a circus troupe. There are $n$ — an even number — artists in the troupe. It is known whether the $i$-th artist can perform as a clown (if yes, then $c_i = 1$, otherwise $c_i = 0$), and whether they can perform as an acrobat (if yes, then $a_i = 1$, otherwise $a_i = 0$).\n\nSplit the artists into two performances in such a way that:\n\n- each artist plays in exactly one performance,\n- the number of artists in the two performances is equal (i.e. equal to $\\frac{n}{2}$),\n- the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance.",
    "tutorial": "Note, that there are only four types of artists: <<0; 0>>, <<0; 1>>, <<1; 0>>, <<1; 1>>. So the whole problem can be described with four integers - the number of artists of each type. Let's say, that there are $n_a$ <<0; 0>> artists, $n_b$ <<0; 1>> artists, $n_c$ <<1; 0>> artists, $n_d$ <<1, 1>> artists. In the same manner, the selection of artists for the first performance can be described with four integers $0 \\le a \\le n_a$, $0 \\le b \\le n_b$, $0 \\le c \\le n_c$, $0 \\le d \\le n_d$. Note, that we have some restrictions on $a$, $b$, $c$, $d$. In particular, we need to select exactly half of the artists: $a + b + c + d = \\frac{n}{2}$. Also we have a requirement that the number of clowns in first performance ($c + d$) must be equal to number of acrobats in the second ($n_b - b + n_d - d$): $c + d = n_b - b + n_d - d$, so we have $b + c + 2d = n_b + n_d$. This equations are necessary and sufficient. So we have 4 unknown variables and 2 equations. We can bruteforce any two variables, calculate using them other two variables. And if everything went well, print an answer. Complexity: $\\mathcal{O}(n^2$).",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1139",
    "index": "A",
    "title": "Even Substrings",
    "statement": "You are given a string $s=s_1s_2\\dots s_n$ of length $n$, which only contains digits $1$, $2$, ..., $9$.\n\nA substring $s[l \\dots r]$ of $s$ is a string $s_l s_{l + 1} s_{l + 2} \\ldots s_r$. A substring $s[l \\dots r]$ of $s$ is called even if the number represented by it is even.\n\nFind the number of even substrings of $s$. Note, that even if some substrings are equal as strings, but have different $l$ and $r$, they are counted as \\textbf{different} substrings.",
    "tutorial": "Any substring ending in $2, 4, 6, 8$ forms an even substring. Thus, iterate over all positions $i$ of the string $s$, and if the digit represented by character at $i_{th}$ index is even, then add $i+1$ to the answer, since all the substrings starting at $0, 1, ..., i$ and ending at $i$ are even substrings. Overall Complexity: $O(n)$.",
    "code": "import java.util.*;\n \npublic class SolutionA {\n\tpublic static void main(String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n \n\t\tint n = sc.nextInt();\n\t\tchar[] s = sc.next().toCharArray();\n \n\t\tint ans = 0;\n\t\tfor(int i = 0; i < n; ++i) {\n\t\t\tif((s[i] - '0') % 2 == 0)\n\t\t\t\tans += (i + 1);\n\t\t}\n \n\t\tSystem.out.print(ans);\n\t}\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1139",
    "index": "B",
    "title": "Chocolates",
    "statement": "You went to the store, selling $n$ types of chocolates. There are $a_i$ chocolates of type $i$ in stock.\n\nYou have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $x_i$ chocolates of type $i$ (clearly, $0 \\le x_i \\le a_i$), then for all $1 \\le j < i$ at least one of the following must hold:\n\n- $x_j = 0$ (you bought zero chocolates of type $j$)\n- $x_j < x_i$ (you bought less chocolates of type $j$ than of type $i$)\n\nFor example, the array $x = [0, 0, 1, 2, 10]$ satisfies the requirement above (assuming that all $a_i \\ge x_i$), while arrays $x = [0, 1, 0]$, $x = [5, 5]$ and $x = [3, 2]$ don't.\n\nCalculate the maximum number of chocolates you can buy.",
    "tutorial": "It is optimal to proceed greedily from the back of the array. If we have taken $x$ candies of the $i+1$ type, then we can only take $\\min(x - 1, A_i)$ candies for type $i$. If this value is less than zero, we take $0$ from here. Overall Complexity: $O(n)$",
    "code": "import java.util.*;\nimport static java.lang.Math.*;\n \npublic class SolutionB {\n\tpublic static void main(String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n \n\t\tint n = sc.nextInt();\n\t\tlong a[] = new long[n];\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\ta[i] = sc.nextLong();\n \n\t\tlong ans = 0;\n\t\tlong curV = 1000000001;\n\t\tfor(int i = n - 1; i >= 0; --i) {\n\t\t\tcurV = max(0, min(curV - 1, a[i]));\n\t\t\tans += curV;\n\t\t}\n \n\t\tSystem.out.print(ans);\n\t}\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1139",
    "index": "C",
    "title": "Edgy Trees",
    "statement": "You are given a tree (a connected undirected graph without cycles) of $n$ vertices. Each of the $n - 1$ edges of the tree is colored in either black or red.\n\nYou are also given an integer $k$. Consider sequences of $k$ vertices. Let's call a sequence $[a_1, a_2, \\ldots, a_k]$ good if it satisfies the following criterion:\n\n- We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from $a_1$ and ending at $a_k$.\n- Start at $a_1$, then go to $a_2$ using the shortest path between $a_1$ and $a_2$, then go to $a_3$ in a similar way, and so on, until you travel the shortest path between $a_{k-1}$ and $a_k$.\n- If you walked over at least one black edge during this process, then the sequence is good.\n\nConsider the tree on the picture. If $k=3$ then the following sequences are good: $[1, 4, 7]$, $[5, 5, 3]$ and $[2, 3, 7]$. The following sequences are not good: $[1, 4, 6]$, $[5, 5, 5]$, $[3, 7, 3]$.\n\nThere are $n^k$ sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo $10^9+7$.",
    "tutorial": "Let's find the number of bad sequences - Sequences of length $k$ that do not pass through any black edges. Then answer is all possible sequences minus the number of bad sequences. Thus, we can remove black edges from the tree. Now the tree would be split into connected components. For every connected component, if we start with $A_1$ being a node from this component, then we cannot step outside this component, since doing so would mean that we visit a black edge. But we can visit all the nodes in the current connected component in any order. So if the size of the current component is $p$, then we have $p^k$ bad sequences corresponding to this connected component. Thus, the overall answer is $n^k - \\sum p^k$ where $p$ is the size of different connected components, considering only red edges.",
    "code": "import java.util.*;\nimport static java.lang.Math.*;\n \npublic class SolutionC {\n\tstatic void dfs(int i) {\n\t\tvis[i] = 1;\n\t\tcnt++;\n \n\t\tfor(int j : adj[i]) {\n\t\t\tif(vis[j] == 0)\n\t\t\t\tdfs(j);\n\t\t}\n\t}\n \n\tstatic long fast_pow(long a, long b) {\n\t\tif(b == 0)\n\t\t\treturn 1L;\n \n\t\tlong val = fast_pow(a, b / 2);\n \n\t\tif(b % 2 == 0)\n\t\t\treturn val * val % mod;\n\t\telse \n\t\t\treturn val * val % mod * a % mod;\n\t}\n\tstatic long mod = (long)1e9 + 7;\n \n\tstatic ArrayList<Integer> adj[];\n\tstatic int vis[];\n\tstatic long cnt = 0;\n \n\tpublic static void main(String[] args) {\n\t\tScanner sc = new Scanner(System.in);\n \n\t\tint n = sc.nextInt();\n\t\tint k = sc.nextInt();\n \n\t\tadj = new ArrayList[n];\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tadj[i] = new ArrayList<>();\n \n\t\tfor(int i = 0; i < n - 1; ++i) {\n\t\t\tint u = sc.nextInt() - 1;\n\t\t\tint v = sc.nextInt() - 1;\n\t\t\tint col = sc.nextInt();\n \n\t\t\tif(col == 0) {\n\t\t\t\tadj[u].add(v);\n\t\t\t\tadj[v].add(u);\n\t\t\t}\n\t\t}\n \n\t\tlong ans = fast_pow(n, k);\n\t\tlong rem = 0;\n \n\t\tvis = new int[n];\n\t\tfor(int i = 0; i < n; ++i) {\n\t\t\tif(vis[i] == 0) {\n\t\t\t\tcnt = 0;\n\t\t\t\tdfs(i);\n\t\t\t\trem += fast_pow(cnt, k);\n\t\t\t}\n\t\t}\n \n\t\trem %= mod;\n\t\tans = (ans - rem + mod) % mod;\n \n\t\tSystem.out.print(ans);\n\t}\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "math",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1139",
    "index": "D",
    "title": "Steps to One",
    "statement": "Vivek initially has an empty array $a$ and some integer constant $m$.\n\nHe performs the following algorithm:\n\n- Select a random integer $x$ uniformly in range from $1$ to $m$ and append it to the end of $a$.\n- Compute the greatest common divisor of integers in $a$.\n- In case it equals to $1$, break\n- Otherwise, return to step $1$.\n\nFind the expected length of $a$. It can be shown that it can be represented as $\\frac{P}{Q}$ where $P$ and $Q$ are coprime integers and $Q\\neq 0 \\pmod{10^9+7}$. Print the value of $P \\cdot Q^{-1} \\pmod{10^9+7}$.",
    "tutorial": "Let $dp[x]$ be the expected number of additional steps to get a gcd of 1 if the gcd of the current array is $x$. Suppose the current gcd of the array $a$ is $x$, after the next iteration of the algorithm, we would append some randomly chosen $j$ with a probability $\\frac{1}{m}$, and move to state $gcd(x,j)$ and since the length increases by $1$ on appending, we will make $dp[gcd(x, j)] + 1$ steps for this $j$. So the recurrence is : $dp[x] =1 + \\sum_{j=1}^{m}\\frac{dp[gcd(j,x)]}{m}$ I recommend this Expectation tutorial to get more understanding of the basics. We can group together all terms having the same $gcd(j, x)$, move terms having $gcd(j, x) = x$ to the left side of the equation and use that to calculate $dp[x]$. This is an $O(m^2)$ solution. Here we notice that $gcd(j,x)$ is a factor of $x$, So the recurrence could be modified as : $dp[x] = 1+\\sum_{y \\in divisors(x)}{\\frac{dp[y] \\cdot f(y,x)}{m}}$ Lets express $x = y \\cdot a$, and $p=y \\cdot b$ where $a$, $b$ are positive integers, So we want to find the number of $p$'s where $1 \\le p \\le m$, $p = y \\cdot b$, such that $gcd(b,a) = 1$, i.e. we want to find number of $b$ where $1 \\le b \\le m/y$ such that $gcd(b,a) = 1$. Lets find factorization of $a$, so $b$ must not be divisible by any of the prime factors of $a$. We can find number of $b\\le m/y$ such that it isn't divisible by some set of primes by inclusion exclusion. Since there are at most $6$ primes, we have complexity: $O(m \\log{m} \\cdot 2^6 \\cdot 6)$ For an alternate solution using mobius function, refer code 2.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N = 1e5 + 5;\nconst int MOD = 1e9 + 7;\n \nint pow(int a, int b, int m)\n{\n\tint ans=1;\n\twhile(b)\n\t{\n\t\tif(b&1)\n\t\t\tans=(ans*a)%m;\n\t\tb/=2;\n\t\ta=(a*a)%m;\n\t}\n\treturn ans;\n}\n \nint modinv(int k)\n{\n\treturn pow(k, MOD - 2, MOD);\n}\n \nint mu[N], prime[N];\nvector<int> primes;\n \nvoid precompute()\n{\n\tfill(prime + 2, prime + N, 1);\n\tmu[1] = 1;\n\tfor(int i=2;i<N;i++)\n\t{\n\t\tif(prime[i])\n\t\t\tprimes.push_back(i), mu[i] = -1;\n\t\tfor(auto &it: primes)\n\t\t{\n\t\t\tif(i * it >= N)\n\t\t\t\tbreak;\n\t\t\tprime[i * it] = 0;\n\t\t\tif(i % it == 0)\n\t\t\t{\n\t\t\t\tmu[i * it] = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\tmu[i * it] = mu[i] * mu[it];\n\t\t}\n\t}\n}\n \nint n;\nint ans = 0;\ndouble dans = 0;\n \nint32_t main()\n{\n\tIOS;\n\tprecompute();\n\tcin>>n;\n\tans = 1, dans = 1;\n\tfor(int i=2;i<=n;i++)\n\t{\n\t\tint f = n / i;\n\t\tdans -= 1.0 * mu[i] * f / (n -f);\n\t\tans -= (mu[i] * f * modinv(n - f)) % MOD;\n\t\tans += MOD;\n\t\tans %= MOD;\n\t}\t\n\tcout<<ans;\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1139",
    "index": "E",
    "title": "Maximize Mex",
    "statement": "There are $n$ students and $m$ clubs in a college. The clubs are numbered from $1$ to $m$. Each student has a potential $p_i$ and is a member of the club with index $c_i$. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next $d$ days. There is a coding competition every day in the technical fest.\n\nEvery day, in the morning, exactly one student of the college leaves their club. Once a student leaves their club, they will never join any club again. Every day, in the afternoon, the director of the college will select one student from each club (in case some club has no members, nobody is selected from that club) to form a team for this day's coding competition. The strength of a team is the mex of potentials of the students in the team. The director wants to know the maximum possible strength of the team for each of the coming $d$ days. Thus, every day the director chooses such team, that the team strength is maximized.\n\nThe mex of the multiset $S$ is the smallest non-negative integer that is not present in $S$. For example, the mex of the $\\{0, 1, 1, 2, 4, 5, 9\\}$ is $3$, the mex of $\\{1, 2, 3\\}$ is $0$ and the mex of $\\varnothing$ (empty set) is $0$.",
    "tutorial": "Let's reverse the queries so that instead of removal of edges we need to work with the addition of edges. Now consider a bipartite graph with values $0 \\ldots m$ on the left side and clubs $1 \\ldots m$ on the right side. For an ind $i$, which has not been removed, we add an edge from $p_i$ on the left to $c_i$ on the right. Let's start finding matching for values $0 \\ldots m$ in sequence. Let's say we couldn't find matching for $i$-th value after query $x$, so our answer for query $x$ will be $i$. Now, we add the student of query $x$. Let the index of the student be $ind$, then we add an edge from $p_{ind}$ on the left to $c_{ind}$ on the right. Now, we start finding matching from $i \\ldots m$, until matching is not possible. We repeat this process until all queries are solved. Overall Complexity: $O(d \\cdot n + m \\cdot n)$",
    "code": "import java.util.*;\nimport static java.lang.Math.*;\n \npublic class SolutionE {\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n \n        int n = sc.nextInt();\n        int m = sc.nextInt();\n \n        int deg[] = new int[m];\n        int p[] = new int[n];\n        for(int i = 0; i < n; ++i) {\n            p[i] = sc.nextInt();\n            if(p[i] < m)\n                deg[p[i]]++;\n        }\n \n        int c[] = new int[n];\n        for(int i = 0; i < n; ++i)\n            c[i] = sc.nextInt();\n \n        int q = sc.nextInt();\n        int qind[] = new int[q];\n        int vis[] = new int[n];\n        for(int i = 0; i < q; ++i) {\n            qind[i] = sc.nextInt() - 1;\n            vis[qind[i]] = 1;\n        }\n \n        Kunh kunh = new Kunh(2 * m, deg);\n        for(int i = 0; i < n; ++i) {    \n            if(vis[i] == 0) {\n                if(p[i] < m) \n                    kunh.addEdge(p[i], m + c[i] - 1);\n            }\n        }\n        int ans = 0;\n        while(ans < m && kunh.addFlow(ans)) \n            ans++;\n \n        int fans[] = new int[q];\n        for(int i = q - 1; i >= 0; --i) {\n            fans[i] = ans;\n \n            int ind = qind[i];\n \n            if(p[ind] < m) {\n                kunh.addEdge(p[ind], m + c[ind] - 1);\n            }\n \n            while(ans < m && kunh.addFlow(ans))\n                ans++;\n        }\n \n        for(int i : fans)\n            System.out.println(i);\n    }\n}\nclass Kunh {\n    int pair[];\n    int adj[][];\n    int ptr[];\n    int vis[];\n    int level = 0;\n    Kunh(int n, int deg[]) {\n        pair = new int[n];\n        Arrays.fill(pair, -1);\n        adj = new int[n / 2][];\n        for(int i = 0; i < n / 2; ++i) {\n            adj[i] = new int[deg[i]];\n        }\n        ptr = new int[n / 2];\n        vis = new int[n / 2];\n    }\n    void addEdge(int i, int j) {\n        adj[i][ptr[i]++] = j;\n    }\n    boolean addFlow(int source) {\n        level++;\n        return dfs(source);\n    }\n    boolean dfs(int i) {\n        vis[i] = level;\n \n        for(int k = 0; k < ptr[i]; ++k) {\n            int j = adj[i][k];\n            if(pair[j] == -1) {\n                pair[j] = i;\n                return true;\n            }\n            else if(vis[pair[j]] != level && dfs(pair[j])) {\n                pair[j] = i;\n                return true;\n            }\n        }\n \n        return false;\n    }\n}",
    "tags": [
      "flows",
      "graph matchings",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1139",
    "index": "F",
    "title": "Dish Shopping",
    "statement": "There are $m$ people living in a city. There are $n$ dishes sold in the city. Each dish $i$ has a price $p_i$, a standard $s_i$ and a beauty $b_i$. Each person $j$ has an income of $inc_j$ and a preferred beauty $pref_j$.\n\nA person would never buy a dish whose standard is less than the person's income. Also, a person can't afford a dish with a price greater than the income of the person. In other words, a person $j$ can buy a dish $i$ only if $p_i \\leq inc_j \\leq s_i$.\n\nAlso, a person $j$ can buy a dish $i$, only if $|b_i-pref_j| \\leq (inc_j-p_i)$. In other words, if the price of the dish is less than the person's income by $k$, the person will only allow the absolute difference of at most $k$ between the beauty of the dish and his/her preferred beauty.\n\nPrint the number of dishes that can be bought by each person in the city.",
    "tutorial": "Let's consider a matrix where $i$-th row represents price $i$ and $j$-th column represents beauty $j$, such that the value of $c[i][j]$ represents the number of dishes that can be bought by a person having income $i$ and preferred beauty $j$. Then, adding a dish with price $p$, standard $s$ and beauty $b$ is similar to adding $+1$ in each cell in the triangle formed by vertices $P(p, b)$, $Q(s, b - s + p)$ and $R(s, b + s - p)$. Now, we need to update the given triangles with $+1$ in a matrix efficiently. Let's do this offline. Note that for a triangle with vertices $P(p, b)$, $Q(s, b - s + p)$ and $R(s, b + s - p)$, the column updated in $p$-th row is $b$. The columns updated in $(p + 1)$-th row are $b - 1$, $b$ and $b + 1$. So, if the columns updated in $i$-th row are $x \\ldots y$, then the columns updated in $i + 1$-th row will be $(x - 1) \\ldots (y + 1)$. For updating a range $l \\ldots r$ in a row $i$, we can update $mat[i][l]$ with $+1$ and $mat[i][r + 1]$ with $-1$. And then when we do prefix sum in that row we get actual values for each cell. We can use similar approach here. Note that instead of updating $mat[i][l]$ with $+1$, we can update some array $larr[i + l]$ with $+1$, similarly instead of updating $mat[i][r + 1]$ with $-1$, we can update some array $rarr[r + 1 - i]$ with $-1$. In this way, we can provide updates for each row in triangle instead of just one row. The value of a cell $mat[i][j]$ will be addition of prefix sum of $larr$ in range $[0, i+j]$ and prefix sum of $rarr$ in range $[0, j-i]$. Let's create four events for each triangle. For, a triangle with vertices $P(p, b)$, $Q(s, b - s + p)$ and $R(s, b + s - p)$, the events added will be $larr[p + b] \\texttt{+=} 1$ at cell $(p, b)$, $rarr[b + 1 - p] \\texttt{-=} 1$ at cell $(p, b + 1)$, $larr[p + b] \\texttt{-=} 1$ at cell $(s + 1, b - s - 1 + p)$, $rarr[b + 1 - p] \\texttt{-=} 1$ at cell $(s + 1, b + s + 1 - p)$. Also, we add query events for each person $i$ at cell $(inc_i, pb_i)$. Let's sort this events on the basis of rows of the cell and then for the same row we handle triangle events first and then handle query events. For maintaining prefix sum in $larr$ and $rarr$, we can use compression and a datastructure like fenwick tree. Overall Complexity: $O((n + m) \\cdot log(n + m))$",
    "code": "import java.util.*;\nimport static java.lang.Math.*;\n \npublic class SolutionF {\n    static int queryBit(int[] bit, int ind) {\n        int ans = 0;\n        while(ind > 0) {\n            ans += bit[ind];\n            ind -= Integer.lowestOneBit(ind);\n        }\n        return ans;\n    }\n    static void updateBit(int[] bit, int ind, int val) {\n        while(ind < bit.length) {\n            bit[ind] += val;\n            ind += Integer.lowestOneBit(ind);\n        }\n    }\n    static TreeMap<Integer, Integer> lmap = new TreeMap<>();\n    static TreeMap<Integer, Integer> rmap = new TreeMap<>();\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n \n        int n = sc.nextInt();\n        int m = sc.nextInt();\n \n        ArrayList<Event> list = new ArrayList<>();\n \n        int p[] = new int[n];\n        for(int i = 0; i < n; ++i) {\n            p[i] = sc.nextInt();\n        }\n \n        int s[] = new int[n];\n        for(int i = 0; i < n; ++i) {\n            s[i] = sc.nextInt();\n        }\n \n        int b[] = new int[n];\n        for(int i = 0; i < n; ++i) {\n            b[i] = sc.nextInt();\n        }\n \n        for(int i = 0; i < n; ++i) {\n            list.add(new Event(0, p[i], b[i] + p[i], 1));\n            list.add(new Event(0, s[i] + 1, b[i] + p[i], -1));\n            list.add(new Event(1, p[i], b[i] + 1 - p[i], -1));\n            list.add(new Event(1, s[i] + 1, b[i] + 1 - p[i], 1));\n        }\n \n        int inc[] = new int[m];\n        for(int i = 0; i < m; ++i)\n            inc[i] = sc.nextInt();\n \n        int pb[] = new int[m];\n        for(int i = 0; i < m; ++i)\n            pb[i] = sc.nextInt();\n \n        for(int i = 0; i < m; ++i) {\n            lmap.put(pb[i] + inc[i], 1);\n            rmap.put(pb[i] - inc[i], 1);\n            list.add(new Event(2, inc[i], pb[i], i));\n        }\n \n        Collections.sort(list, new Comparator<Event>() {\n            public int compare(Event e1, Event e2) {\n                if(e1.x < e2.x)\n                    return -1;\n                if(e1.x > e2.x)\n                    return 1;\n                if(e1.type < e2.type)\n                    return -1;\n                if(e1.type > e2.type) \n                    return 1;\n                return 0;\n            }\n        });\n \n        int ptr = 1;\n        for(int i : lmap.keySet()) {\n            lmap.put(i, ptr++);\n        }\n        int lbit[] = new int[ptr];\n \n        ptr = 1;\n        for(int i : rmap.keySet()) {\n            rmap.put(i, ptr++);\n        }\n        int rbit[] = new int[ptr];\n \n        int ans[] = new int[m];\n        for(Event e : list) {\n            int type = e.type;\n \n            if(type == 0) {\n                if(lmap.higherKey(e.y - 1) != null) { \n                    updateBit(lbit, lmap.get(lmap.higherKey(e.y - 1)), e.val);\n                }\n            }\n            else if(type == 1) {\n                if(rmap.higherKey(e.y - 1) != null) { \n                    updateBit(rbit, rmap.get(rmap.higherKey(e.y - 1)), e.val);\n                } \n            }\n            else {\n                int lind = lmap.get(e.y + e.x);\n                int rind = rmap.get(e.y - e.x);\n                int ind = e.val;\n \n                ans[ind] = queryBit(lbit, lind) + queryBit(rbit, rind);\n            }   \n        }\n \n        for(int i : ans)\n            System.out.print(i + \" \");\n    }\n}\nclass Event {\n    // type\n    // 0 : lupd, 1 : rupd, 2 : people query\n    int type, x, y, val;\n    Event(int a, int b, int c, int d) {\n        type = a;\n        x = b;\n        y = c;\n        val = d;\n    }\n}",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1140",
    "index": "A",
    "title": "Detective Book",
    "statement": "Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $i$-th page contains some mystery that will be explained on page $a_i$ ($a_i \\ge i$).\n\nIvan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $i$ such that Ivan already has read it, but hasn't read page $a_i$). After that, he closes the book and continues to read it on the following day from the next page.\n\nHow many days will it take to read the whole book?",
    "tutorial": "Solution is just some implementation: simulate algorithm given in the legend, maintaining maximum over all $a_i$ on prefix and breaking when the maximum becomes smaller than index of the next page.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint n;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tfor(int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t\ta[i]--;\n\t}\n\treturn true;\n}\n\ninline void solve() {\n\tint cnt = 0, pos = 0;\n\twhile(pos < n) {\n\t\tcnt++;\n\t\tint mx = pos;\n\t\twhile(pos < n && pos <= mx) {\n\t\t\tmx = max(mx, a[pos]);\n\t\t\tpos++;\n\t\t}\n\t}\n\tcout << cnt << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\t\n\tif(read()) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1140",
    "index": "B",
    "title": "Good String",
    "statement": "You have a string $s$ of length $n$ consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character <, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).\n\nFor example, if we choose character > in string {> \\textbf{>} < >}, the string will become to > > >. And if we choose character < in string {> \\textbf{<}}, the string will become to <.\n\nThe string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings >, > > are good.\n\n\\textbf{Before applying the operations}, you may remove any number of characters from the given string (possibly none, possibly up to $n - 1$, but not the whole string). You need to calculate the minimum number of characters to be deleted from string $s$ so that it becomes good.",
    "tutorial": "A string is good when either its first character is > or the last is <. Strings of type < $\\dots$ > are not good, as their first and last characters will never change and they will eventually come to the form < >. So, the answer is the minimum number of characters from the beginning of the string, which must be removed so that the first symbol becomes >, or minimum number of characters from the end of the string, which must be removed so that the last symbol becomes <.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t, n;\nstring s;\n\nint main(){\n\tcin >> t;\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tcin >> n >> s;\n\t\tint res = n - 1;\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tif(s[i] == '>' || s[n - 1 - i] == '<')\n\t\t\t\tres = min(res, i);\n\t\t\n\t\tcout << res << endl;\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1140",
    "index": "C",
    "title": "Playlist",
    "statement": "You have a playlist consisting of $n$ songs. The $i$-th song is characterized by two numbers $t_i$ and $b_i$ — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of $3$ songs having lengths $[5, 7, 4]$ and beauty values $[11, 14, 6]$ is equal to $(5 + 7 + 4) \\cdot 6 = 96$.\n\nYou need to choose \\textbf{at most} $k$ songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.",
    "tutorial": "If we fix a song with minimum beauty in the answer, then we need to take the remaining $k - 1$ songs (or less) among those having beauty greater than or equal to the beauty of the fixed song - and the longer they are, the better. So, we will iterate on the songs in the order of decreasing their beauty, and for the current song we will maintain $k$ longest songs having greater or similar beauty. This can be done using some standard containers: set in C++ or TreeSet in Java.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300009;\n\nint n, k;\npair<int, int> a[N];\n\nint main() {\n\tcin >> n >> k;\n\t\n\tfor(int i = 0; i < n; ++i)\n\t\tcin >> a[i].second >> a[i].first;\n\n\tsort(a, a + n);\n\tlong long res = 0;\n\tlong long sum = 0;\n\tset<pair<int, int> > s;\n\tfor(int i = n - 1; i >= 0; --i){\n\t\ts.insert(make_pair(a[i].second, i));\n\t\tsum += a[i].second;\n\t\twhile(s.size() > k){\n\t\t\tauto it = s.begin();\n\t\t\tsum -= it->first;\n\t\t\ts.erase(it);\n\t\t}\n\n\t\tres = max(res, sum * a[i].first);\n\t}\n\n\tcout << res << endl;\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1140",
    "index": "D",
    "title": "Minimum Triangulation",
    "statement": "You are given a regular polygon with $n$ vertices labeled from $1$ to $n$ in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the total area of all triangles is equal to the area of the given polygon. The weight of a triangulation is the sum of weigths of triangles it consists of, where the weight of a triagle is denoted as the product of labels of its vertices.\n\nCalculate the minimum weight among all triangulations of the polygon.",
    "tutorial": "You can use straightforward way and calculate answer with \"l-r-dp\" with $O(n^3)$. But there is a easier claim: it's optimal to split $n$-gon with diagonals coming from $1$, so answer is $\\sum\\limits_{i = 2}^{n - 1}{i \\cdot (i + 1)}$. Proof: let's look at the triange which contains edge $1-n$. Let's name it $1-n-x$. If $x = n - 1$, we can delete this triangle and go to $(n-1)$-gon. Otherwise, $1 < x < n - 1$. Let's look at triangle $n-x-k$. It always exists and $x < k < n$. Finally, if we change pair of triangles ($1-n-x$, $n-x-k$) to ($1-n-k$, $1-k-x$), answer will decrease since $nx > kx$ and $nxk > nk$, that's why $nx + nxk > nk + kx$. Note, that triangle $1-n-x$ changes to $1-n-k$ and $k > x$, so repeating this step will eventually lead us to situation $x = n - 1$. As a result, we can morph any triangulation into one mentioned above and its weight won't increase.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint n; cin >> n;\n\n\tlong long ans = 0;\n\tfor(int id = 2; id < n; id++)\n\t\tans += 1ll * id * (id + 1);\n\t\n\tcout << ans << endl;\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1140",
    "index": "E",
    "title": "Palindrome-less Arrays",
    "statement": "Let's denote that some array $b$ is bad if it contains a subarray $b_l, b_{l+1}, \\dots, b_{r}$ of odd length more than $1$ ($l < r$ and $r - l + 1$ is odd) such that $\\forall i \\in \\{0, 1, \\dots, r - l\\}$ $b_{l + i} = b_{r - i}$.\n\nIf an array is not bad, it is \\textbf{good}.\n\nNow you are given an array $a_1, a_2, \\dots, a_n$. Some elements are replaced by $-1$. Calculate the number of good arrays you can obtain by replacing each $-1$ with some integer from $1$ to $k$.\n\nSince the answer can be large, print it modulo $998244353$.",
    "tutorial": "At first, \"array contains a palindromic subarray of length $\\ge 3$\" is equivalent to \"array contains a palindromic subarray of length $=3$\". So we need to calculate number of arrays without palindromes of length $3$. It's equivalent to finding arrays where $a[i] \\neq a[i + 2]$ for all appropriate $i$. Note, that $i$ and $i + 2$ have same parity, so all odd and all even positions in array are independent, and answer is the product of the number of ways to choose numbers for odd positions, and the number of ways to choose numbers for even positions. In terms of same parity our condition morphs to $a[i] \\neq a[i + 1]$ and we need to calculate all ways to replace ($-1$)-s in such way that all pairs of consecutive elements are different. To calculate it let's look at sequences of consecutive ($-1$)-s. They will look like $a, -1, -1, \\dots, -1, b$ with $l$ ($-1$)-s, where $a$ and $b$ are positive (case where $a$ is empty can be considered as $k \\cdot (a, -1, \\dots, -1, b \\text{ with $l - 1$ ($-1$)-s})$, case with empty $b$ is solved the same way). In the end we need to find a way to calculate the number of those sequences. There are only two fundamental types of sequences: $a, -1, \\dots, -1, a$ (same value from both ends) and $a, -1, \\dots, -1, b$ ($a \\neq b$). Exact values of $a$ and $b$ don't really matter. Let's find a way to calculate both values (name them $cntSame$ and $cntDiff$) for $l$ consecutive ($-1$)-s in $O(\\log{l})$ time. Base values: $cntSame(0) = 0, cntDiff(0) = 1$. Let's try to choose value of $-1$ in the middle of sequence: if $l \\mod 2 = 1$, then we can split sequence in two sequences of length $\\lfloor l / 2 \\rfloor$ and $cntSame(l) = cntSame(l / 2)^2 + (k - 1) \\cdot cntDiff(l / 2)^2$ and $cntDiff(l) = 2 \\cdot cntSame(l / 2) \\cdot cntDiff(l / 2) + (k - 2) \\cdot cntDiff(l / 2)^2$. If $l \\mod 2 = 0$ then just iterate over value of last $-1$, then $cntSame(l) = (k - 1) \\cdot cntDiff(l - 1)$ and $cntDiff(l) = cntSame(l - 1) + (k - 2) \\cdot cntDiff(l - 1)$. Resulting complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int MOD = 998244353;\nint norm(int a) {\n    while(a >= MOD) a -= MOD;\n    while(a < 0) a += MOD;\n    return a;\n}\nint mul(int a, int b) {\n    return int(a * 1ll * b % MOD);\n}\n\nint n, k;\nvector<int> a;\n\ninline bool read() {\n    if(!(cin >> n >> k))\n        return false;\n    a.resize(n);\n    fore(i, 0, n)\n        cin >> a[i];\n    return true;\n}\n\npair<int, int> calc(int len) {\n    if(len == 0) return {0, 1};\n    if(len & 1) {\n        auto res = calc(len >> 1);\n        return {norm(mul(res.x, res.x) + mul(k - 1, mul(res.y, res.y))),\n                norm(mul(2, mul(res.x, res.y)) + mul(k - 2, mul(res.y, res.y)))};\n    }\n    auto res = calc(len - 1);\n    return {mul(k - 1, res.y), norm(res.x + mul(k - 2, res.y))};\n}\n\nvector<int> curArray;\n\nint calcSeg(int l, int r) {\n    if(r >= sz(curArray)) {\n        int len = r - l - 1, cf = 1;\n        if(l < 0)\n            len--, cf = k;\n        if(len == 0) return cf;\n\n        auto res = calc(len - 1);\n        return mul(cf, norm(res.x + mul(k - 1, res.y)));\n    }\n    if(l < 0) {\n        if(r - l == 1) return 1;\n        auto res = calc(r - l - 2);\n        return norm(res.x + mul(k - 1, res.y));\n    }\n    auto res = calc(r - l - 1);\n    return curArray[l] == curArray[r] ? res.x : res.y;\n}\n\ninline void solve() {\n    int ans = 1;\n    fore(k, 0, 2) {\n        curArray.clear();\n        for(int i = 0; 2 * i + k < n; i++)\n            curArray.push_back(a[2 * i + k]);\n\n        int lst = -1;\n        fore(i, 0, sz(curArray)){\n            if(curArray[i] == -1) continue;\n            ans = mul(ans, calcSeg(lst, i));\n            lst = i;\n        }\n        ans = mul(ans, calcSeg(lst, sz(curArray)));\n    }\n    cout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(0);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n\n    if(read()) {\n        solve();\n\n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1140",
    "index": "F",
    "title": "Extending Set of Points",
    "statement": "For a given set of two-dimensional points $S$, let's denote its extension $E(S)$ as the result of the following algorithm:\n\nCreate another set of two-dimensional points $R$, which is initially equal to $S$. Then, while there exist four numbers $x_1$, $y_1$, $x_2$ and $y_2$ such that $(x_1, y_1) \\in R$, $(x_1, y_2) \\in R$, $(x_2, y_1) \\in R$ and $(x_2, y_2) \\notin R$, add $(x_2, y_2)$ to $R$. When it is impossible to find such four integers, let $R$ be the result of the algorithm.\n\nNow for the problem itself. You are given a set of two-dimensional points $S$, which is initially empty. You have to process two types of queries: add some point to $S$, or remove some point from it. After each query you have to compute the size of $E(S)$.",
    "tutorial": "Let's try to analyze how the size of $E(S)$ can be calculated. Let's connect points having same $x$-coordinates to each other, and do the same for points having same $y$-coordinates. Then we can solve the problem for each component separatedly: after the algorithm is run, the component will contain the points $(X, Y)$ such that at least one point in the component has $x$-coordinate equal to $X$, and at least one point in the component (maybe same, maybe another one) has $y$-coordinate equal to $Y$. So the answer for each component is the product of the number of distinct $x$-coordinates and the number of distinct $y$-coordinates in the component. Now we can process insertion queries: there are many ways to do it, but, in my opinion, the easiest way to handle them is to create a separate vertex for every $x$-coordinate and $y$-coordinate, and process each point as an edge connecting vertices corresponding to its coordinates (edges can be easily added by using DSU with rank heuristics). To handle removals, we will get rid of them completely. Transform the input into a set of $O(q)$ events \"some point exists from query $l$ to query $r$\". Then build a segment tree over queries, and break each event into $O(\\log q)$ segments with this segment tree. Then we can initialize a DSU, and run DFS on the vertices of the segment tree to get answers for all queries. When we enter some node, we add all edges that exist on the corresponding segment into DSU. If we are in a leaf node, we may compute the $E(S)$ for the corresponding query. And when we leave a vertex, we can rollback all changes we made when we entered it. One important moment is that using path compression in DSU here is meaningless since it doesn't work with rollbacks well. This solution works in $O(q \\log^2 q)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\n#define x first\n#define y second\n\nconst int N = 300043;\nconst int K = 300000;\n\nint p[2 * N];\nint s1[2 * N];\nint s2[2 * N];\nli ans = 0;\n\nint* where[80 * N];\nint val[80 * N];\nint cur = 0;\n\nvoid change(int& x, int y)\n{\n\twhere[cur] = &x;\n\tval[cur] = x;\n\tx = y;\n\tcur++;\n}\n\nvoid rollback()\n{\n\tcur--;\n\t(*where[cur]) = val[cur];\n}\n\nint get(int x)\n{\n\tif(p[x] == x)\n\t\treturn x;\n\treturn get(p[x]);\n}\n\nvoid merge(int x, int y)\n{\n\tx = get(x);\n\ty = get(y);\n\tif(x == y) return;\n\tans -= s1[x] * 1ll * s2[x];\n\tans -= s1[y] * 1ll * s2[y];\n\tif(s1[x] + s2[x] < s1[y] + s2[y])\n\t\tswap(x, y);\n\tchange(p[y], x);\n\tchange(s1[x], s1[x] + s1[y]);\n\tchange(s2[x], s2[x] + s2[y]);\n\tans += s1[x] * 1ll * s2[x];\n}\n\nvoid init()\n{\n\tfor(int i = 0; i < K; i++)\n\t{\n\t\tp[i] = i;\n\t\tp[i + K] = i + K;\n\t\ts1[i] = 1;\n\t\ts2[i + K] = 1;\n\t}\n}\n\nvector<pair<int, int> > T[4 * N];\n\nvoid add(int v, int l, int r, int L, int R, pair<int, int> val)\n{\n\tif(L >= R) return;\n\tif(L == l && R == r)\n\t\tT[v].push_back(val);\n\telse\n\t{\n\t\tint m = (l + r) / 2;\n\t\tadd(v * 2 + 1, l, m, L, min(R, m), val);\n\t\tadd(v * 2 + 2, m, r, max(m, L), R, val);\n\t}\n}\n\nli res[N];\n\nvoid dfs(int v, int l, int r)\n{\n\tli last_ans = ans;\n\tint state = cur;\n\tfor(auto x : T[v])\n\t\tmerge(x.x, x.y + K);\n\tif(l == r - 1)\n\t\tres[l] = ans;\n\telse\n\t{\n\t\tint m = (l + r) / 2;\n\t\tdfs(v * 2 + 1, l, m);\n\t\tdfs(v * 2 + 2, m, r);\n\t}\n\twhile(cur != state) rollback();\n\tans = last_ans;\n}\n\nint main()\n{\n\tint q;\n\tscanf(\"%d\", &q);\n\tmap<pair<int, int>, int> last;\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t--x;\n\t\t--y;\n\t\tpair<int, int> p = make_pair(x, y);\n\t\tif(last.count(p))\n\t\t{\n\t\t\tadd(0, 0, q, last[p], i, p);\n\t\t\tlast.erase(p);\n\t\t}\n\t\telse\n\t\t\tlast[p] = i;\n\t}\n\tfor(auto x : last)\n\t\tadd(0, 0, q, x.y, q, x.x);\n\tinit();\n\tdfs(0, 0, q);\n\tfor(int i = 0; i < q; i++)\n\t\tprintf(\"%I64d \", res[i]);\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dsu"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1140",
    "index": "G",
    "title": "Double Tree",
    "statement": "You are given a special undirected graph. It consists of $2n$ vertices numbered from $1$ to $2n$. The following properties hold for the graph:\n\n- there are exactly $3n-2$ edges in the graph: $n$ edges connect vertices having odd numbers with vertices having even numbers, $n - 1$ edges connect vertices having odd numbers with each other, and $n - 1$ edges connect vertices having even numbers with each other;\n- for each edge $(u, v)$ between a pair of vertices with odd numbers, there exists an edge $(u + 1, v + 1)$, and vice versa;\n- for each odd number $u \\in [1, 2n - 1]$, there exists an edge $(u, u + 1)$;\n- the graph is connected; moreover, if we delete all vertices with even numbers from it, and all edges incident to them, the graph will become a tree (the same applies to deleting odd vertices).\n\nSo, the graph can be represented as two trees having the same structure, and $n$ edges connecting each vertex of the first tree to the corresponding vertex of the second tree.\n\nEdges of the graph are weighted. The length of some simple path in the graph is the sum of weights of traversed edges.\n\nYou are given $q$ queries to this graph; in each query, you are asked to compute the length of the shortest path between some pair of vertices in this graph. Can you answer all of the queries?",
    "tutorial": "Suppose we want to minimize the number of traversed edges of the second type (edges that connect odd vertices to each other or even vertices to each other), and minimizing the length of the path has lower priority. Then we exactly know the number of edges of the second type we will use to get from one vertex to another; and when building a path, we each time either jump from one \"tree\" to another using an edge of the first type, or use the only edge of the second type that brings us closer to the vertex we want to reach. So, in this case problem can be solved either by binary lifting or by centroid decomposition. The model solution uses the latter: merge the graph into one tree (vertices $2i - 1$ and $2i$ of the original graph merge into vertex $i$ in the tree), build its centroid decomposition, and for each centroid $c$ and vertex $v$ of its centroid-subtree calculate the length of the shortest path from $2c - 1$ and $2c$ to $2v - 1$ and $2v$ using dynamic programming. Then the answer for each pair of vertices $u$ and $v$ may be calculated as follows: find the deepest centroid $c$ controlling the both vertices, and try either shortest path $u \\rightarrow 2c - 1 \\rightarrow v$ or shortest path $u \\rightarrow 2c \\rightarrow v$. But this solution won't work in the original problem because sometimes we want to choose an edge of the second type that leads us further from the vertex we want to reach in the merged tree, but allows us to use a cheaper edge of the first type to jump from one tree to another. Let's make this situation impossible! We may change the weights of all edges of the second type so that the weight of edge between $2i - 1$ and $2i$ becomes the length of the shortest path between $2i - 1$ and $2i$. This can be done by solving a SSSP problem: build a graph of $n + 1$ vertices, where each vertex $i$ from $1$ to $n$ represents the path between from $2i - 1$ and $2i$. Add a directed edge with weight equal to $w_{2i - 1, 2i}$ going from vertex $0$ to vertex $i$. And finally, for every pair $i, j$ such that $2i - 1$ and $2j - 1$ are connected by edge of weight $w_1$, and $2i$ and $2j$ are connected by edge of weight $w_2$, add an undirected edge connecting $i$ and $j$ in the new graph (its weight should be $w_1 + w_2$). Then the distance from $0$ to $i$ in this graph will be equal to the length of the shortest path from $2i - 1$ to $2i$ in the original graph.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\n#define x first\n#define y second\n\nconst int N = 600043;\n\nli d1[N];\nli d2[N][2];\nli dist_temp[N][2];\nvector<pair<int, int> > g[N];\nvector<int> qs[N];\nint qq[N][2];\nli ans[N];\nint n;\nint used[N];\nint cnt[N];\nint last[N];\nint cc = 1;\n\nvoid preprocess()\n{\n\tset<pair<li, int> > q;\n\tfor(int i = 0; i < n; i++)\n\t\tq.insert(make_pair(d1[i], i));\n\twhile(!q.empty())\n\t{\n\t\tint k = q.begin()->second;\n\t\tq.erase(q.begin());\n\t\tfor(auto e : g[k])\n\t\t{\n\t\t\tint to = e.first;\n\t\t\tli w = d2[e.second][0] + d2[e.second][1];\n\t\t\tif(d1[to] > w + d1[k])\n\t\t\t{\n\t\t\t\tq.erase(make_pair(d1[to], to));\n\t\t\t\td1[to] = w + d1[k];\n\t\t\t\tq.insert(make_pair(d1[to], to));\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid dfs1(int x, int p = -1)\n{\n\tif(used[x]) return;\n\tcnt[x] = 1;\n\tfor(auto y : g[x])\n\t{\n\t\tint to = y.first;\n\t\tif(!used[to] && to != p)\n\t\t{\n\t\t\tdfs1(to, x);\n\t\t\tcnt[x] += cnt[to];\n\t\t}\n\t}\n}\n\nvector<int> cur_queries;\npair<int, int> c;\nint S = 0;\n\nvoid find_centroid(int x, int p = -1)\n{\n\tif(used[x])\treturn;\n\tint mx = 0;\n\tfor(auto y : g[x])\n\t{\n\t\tint to = y.first;\n\t\tif(!used[to] && to != p)\n\t\t{\n\t\t\tfind_centroid(to, x);\n\t\t\tmx = max(mx, cnt[to]);\n\t\t}\n\t}\n\tif(p != -1)\n\t\tmx = max(mx, S - cnt[x]);\n\tc = min(c, make_pair(mx, x));\n}\t\n\nvoid dfs2(int x, int p = -1, int e = -1)\n{\n\tif(used[x]) return;\n\tif(p == -1)\n\t{\n\t\tdist_temp[x * 2][0] = dist_temp[x * 2 + 1][1] = 0ll;\n\t\tdist_temp[x * 2][1] = dist_temp[x * 2 + 1][0] = d1[x];\n\t}\n\telse\n\t{\n\t\tfor(int k = 0; k < 2; k++)\n\t\t{\n\t\t\tli& D0 = dist_temp[x * 2][k];\n\t\t\tli& D1 = dist_temp[x * 2 + 1][k];\n\t\t\tD0 = dist_temp[p * 2][k] + d2[e][0];\n\t\t\tD1 = dist_temp[p * 2 + 1][k] + d2[e][1];\n\t\t\tD0 = min(D0, D1 + d1[x]);\n\t\t\tD1 = min(D1, D0 + d1[x]); \n\t\t}\n\t}\n\tfor(auto y : qs[x])\n\t{\n\t\tif(ans[y] != -1) continue;\n\t\tif(last[y] == cc)\n\t\t\tcur_queries.push_back(y);\n\t\telse\n\t\t\tlast[y] = cc;\n\t}\n\tfor(auto y : g[x])\n\t{\n\t\tint to = y.first;\n\t\tif(!used[to] && to != p)\n\t\t\tdfs2(to, x, y.second);\n\t}\n}\n\nvoid centroid(int v)\n{\n\tif(used[v]) return;\n\tdfs1(v);\n\tS = cnt[v];\n\tc = make_pair(int(1e9), -1);\n\tfind_centroid(v);\n\tint C = c.second;\n\tused[C] = 1;\n\tfor(auto y : g[C])\n\t\tcentroid(y.first);\n\tcc++;\n\tcur_queries.clear();\n\tused[C] = 0;\n\tdfs2(C);\n\tfor(auto x : cur_queries)\n\t{\n\t\tint u = qq[x][0];\n\t\tint v = qq[x][1];\n\t\tans[x] = min(dist_temp[u][0] + dist_temp[v][0], dist_temp[u][1] + dist_temp[v][1]);\n\t}\n}\n\nint main()\n{\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%I64d\", &d1[i]);\n\tfor(int i = 0; i < n - 1; i++)\n\t{\n\t\tint x, y;\n\t\tli w1, w2;\n\t\tscanf(\"%d %d %I64d %I64d\", &x, &y, &w1, &w2);\n\t\t--x;\n\t\t--y;\n\t\td2[i][0] = w1;\n\t\td2[i][1] = w2;\n\t\tg[x].push_back(make_pair(y, i));\n\t\tg[y].push_back(make_pair(x, i));\n\t}\n\tint q;\n\tscanf(\"%d\", &q);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tscanf(\"%d\", &qq[i][0]);\n\t\tscanf(\"%d\", &qq[i][1]);\n\t\t--qq[i][0];\n\t\t--qq[i][1];\n\t\tqs[qq[i][0] / 2].push_back(i);\n\t\tqs[qq[i][1] / 2].push_back(i);\n\t}\n\tpreprocess();\n\tfor(int i = 0; i < q; i++)\n\t\tans[i] = -1;\n\tcentroid(0);\n\tfor(int i = 0; i < q; i++)\n\t\tcout << ans[i] << endl;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "shortest paths",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1141",
    "index": "A",
    "title": "Game 23",
    "statement": "Polycarp plays \"Game 23\". Initially he has a number $n$ and his goal is to transform it to $m$. In one move, he can multiply $n$ by $2$ or multiply $n$ by $3$. He can perform any number of moves.\n\nPrint the number of moves needed to transform $n$ to $m$. Print -1 if it is impossible to do so.\n\nIt is easy to prove that any way to transform $n$ to $m$ contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).",
    "tutorial": "If $m$ is not divisible by $n$ then just print -1 and stop the program. Otherwise, calculate $d=m/n$, denoting the required number of times to multiply $n$. It is easy to see that $d$ should be a product of zero or more $2$'s and of zero or more $3$'s, i.e. $d=2^x3^y$ for integers $x,y \\ge 0$. To find $x$ just use a loop to divide $d$ by $2$ while it is divisible by $2$. Similarly, to find $y$ just use a loop to divide $d$ by $3$ while it is divisible by $3$. After the divisions, the expected value of $d$ is $1$. If $d \\ne 1$, print -1. Otherwise, print the total number of the loop iterations.",
    "code": "int n, m;\ncin >> n >> m;\nint result = -1;\nif (m % n == 0) {\n    result = 0;\n    int d = m / n;\n    while (d % 2 == 0)\n        d /= 2, result++;\n    while (d % 3 == 0)\n        d /= 3, result++;\n    if (d != 1)\n        result = -1;\n}\ncout << result << endl;",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1141",
    "index": "B",
    "title": "Maximal Continuous Rest",
    "statement": "Each day in Berland consists of $n$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence $a_1, a_2, \\dots, a_n$ (each $a_i$ is either $0$ or $1$), where $a_i=0$ if Polycarp works during the $i$-th hour of the day and $a_i=1$ if Polycarp rests during the $i$-th hour of the day.\n\nDays go one after another endlessly and Polycarp uses the same schedule for each day.\n\nWhat is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.",
    "tutorial": "At first consider we process the only day. In this case just iterate over hours and maintain $len$ - the length of the current rest block (i.e. if the element equals $1$ then increase $len$, if the element equals $0$ then reset $len$ to $0$). The maximum intermediate value of $len$ is the answer. In case of multiple days, consider the given sequence as a cyclic sequence. Concatenate the sequence twice and solve the previous case. Sure, not it is no necessary to concatenate it in explicit way, just use $a[i~\\%~n]$ instead of $a[i]$ and process $i=0 \\dots 2\\cdot n-1$.",
    "code": "int n;\ncin >> n;\nvector<int> a(n);\nfor (int i = 0; i < n; i++)\n    cin >> a[i];\nint result = 0;\nint len = 0;\nfor (int i = 0; i < 2 * n; i++) {\n    if (a[i % n] == 1) {\n        len++;\n        result = max(result, len);\n    } else {\n        len = 0;\n    }\n}\ncout << result << endl;",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1141",
    "index": "C",
    "title": "Polycarp Restores Permutation",
    "statement": "An array of integers $p_1, p_2, \\dots, p_n$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3, 1, 2]$, $[1]$, $[1, 2, 3, 4, 5]$ and $[4, 3, 1, 2]$. The following arrays are not permutations: $[2]$, $[1, 1]$, $[2, 3, 4]$.\n\nPolycarp invented a really cool permutation $p_1, p_2, \\dots, p_n$ of length $n$. It is very disappointing, but he forgot this permutation. He only remembers the array $q_1, q_2, \\dots, q_{n-1}$ of length $n-1$, where $q_i=p_{i+1}-p_i$.\n\nGiven $n$ and $q=q_1, q_2, \\dots, q_{n-1}$, help Polycarp restore the invented permutation.",
    "tutorial": "Let's $p[1]=x$. Thus, $p[2]=p[1]+(p[2]-p[1])$=$x+q[1]$, $p[3]=p[1]+(p[2]-p[1])+(p[3]-p[2])$=$x+q[1]+q[2]$, ..., $p[n]=p[1]+(p[2]-p[1])+(p[3]-p[2])+\\dots+(p[n]-p[n-1])$=$x+q[1]+q[2]+\\dots+q[n-1]$. It means that the sequence of $n$ partial sums $p'=[0, q[1], q[1]+q[2], \\dots, q[1]+q[2]+\\dots+q[n-1]]$ is the required permutation if we do $+x$ to each element. The value of $x$ is unknown yet. Find such $i$ that $p'[i]$ is minimum. Thus, $x=1-p'[i]$. Exactly this value will change $p'[i]$ to be $1$ after you add $x$. So, add $x$ to each element of $p'$ and check that now it is a permutation. Probably, you need to use long long to avoid possible integer overflows.",
    "code": "int n;\ncin >> n;\nvector<int> q(n - 1);\nlong long sum = 0;\nlong long min_val = 0;\nfor (int i = 0; i + 1 < n; i++) {\n    cin >> q[i];\n    sum += q[i];\n    if (sum < min_val)\n        min_val = sum;\n}\nvector<long long> p(n);\np[0] = 1 - min_val;\nforn(i, n - 1)\n    p[i + 1] = p[i] + q[i];\nbool ok = true;\nfor (int i = 0; i < n; i++)\n    if (p[i] < 1 || p[i] > n)\n        ok = false;\nif (ok)\n    ok = set<long long>(p.begin(), p.end()).size() == n;\nif (ok) {\n    forn(i, n)\n        cout << p[i] << \" \";\n} else\n    cout << -1 << endl;",
    "tags": [
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1141",
    "index": "D",
    "title": "Colored Boots",
    "statement": "There are $n$ left boots and $n$ right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings $l$ and $r$, both of length $n$. The character $l_i$ stands for the color of the $i$-th left boot and the character $r_i$ stands for the color of the $i$-th right boot.\n\nA lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.\n\nFor example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').\n\nCompute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.\n\nPrint the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.",
    "tutorial": "Use greedy approach in this problem. At first, match such pairs that colors are exactly the same (and they are specific, not indefinite). After it match each indefinite colored left boot (if any) with any specific colored right boot. Possibly, some indefinite colored left boots stay unmatched. Similarly, match each indefinite colored right boot (if any) with any specific colored left boot. And finally match indefinite colored left and right boots (if any).",
    "code": "#define forn(i, n) for (int i = 0; i < int(n); i++)\nconst int A = 26;\n...\nint n;\ncin >> n;\nstring l;\ncin >> l;\nvector<vector<int>> left(A);\nvector<int> wl;\nforn(i, n)\n    if (l[i] != '?')\n        left[l[i] - 'a'].push_back(i);\n    else\n        wl.push_back(i);\nstring r;\ncin >> r;\nvector<vector<int>> right(A);\nvector<int> wr;\nforn(i, n)\n    if (r[i] != '?')\n        right[r[i] - 'a'].push_back(i);\n    else\n        wr.push_back(i);\nvector<pair<int,int>> p;\nvector<int> cl(A), cr(A);\nforn(i, A) {\n    forn(j, min(left[i].size(), right[i].size()))\n        p.push_back(make_pair(left[i][j] + 1, right[i][j] + 1));\n    cl[i] = cr[i] = min(left[i].size(), right[i].size());\n}\nforn(i, A)\n    while (cl[i] < left[i].size() && !wr.empty()) {\n        p.push_back(make_pair(left[i][cl[i]] + 1, wr[wr.size() - 1] + 1));\n        cl[i]++;\n        wr.pop_back();\n    }\nforn(i, A)\n    while (cr[i] < right[i].size() && !wl.empty()) {\n        p.push_back(make_pair(wl[wl.size() - 1] + 1, right[i][cr[i]] + 1));\n        wl.pop_back();\n        cr[i]++;\n    }\nforn(j, min(wl.size(), wr.size()))\n    p.push_back(make_pair(wl[j] + 1, wr[j] + 1));\ncout << p.size() << endl;\nfor (auto pp: p)\n    cout << pp.first << \" \" << pp.second << endl;",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1141",
    "index": "E",
    "title": "Superhero Battle",
    "statement": "A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly $n$ minutes. After a round ends, the next round starts immediately. This is repeated over and over again.\n\nEach round has the same scenario. It is described by a sequence of $n$ numbers: $d_1, d_2, \\dots, d_n$ ($-10^6 \\le d_i \\le 10^6$). The $i$-th element means that monster's hp (hit points) changes by the value $d_i$ during the $i$-th minute of each round. Formally, if before the $i$-th minute of a round the monster's hp is $h$, then after the $i$-th minute it changes to $h := h + d_i$.\n\nThe monster's initial hp is $H$. It means that before the battle the monster has $H$ hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to $0$. Print -1 if the battle continues infinitely.",
    "tutorial": "In general the answer looks like: some number of complete (full) round cycles plus some prefix the the round. Check corner case that there are no complete (full) rounds at all (just check the first round in naive way). If no solution found, the answer has at least one complete (full) cycle and some prefix. If total sum in one round is not negative, then a complete (full) cycle doesn't help and it is again the no solution case. Let's find number of complete (full) cycles. We need such number of cycles $x$ that if your multiple $x$ by total sum and add some prefix, the result (with negative sign, because it is not a damage) will be greater or equal than $H$. So, to find $x$ just add with $H$ the minimal prefix partial sum and divide the result by minus total sum. Now you know the number of complete (full) cycles, just iterate over the last round in naive way to find the answer.",
    "code": "long long H;\nint n;\ncin >> H >> n;\nvector<long long> a(n);\nlong long sum = 0;\nlong long gap = 0;\nlong long h = H;\nfor (int i = 0; i < n; i++) {\n    cin >> a[i];\n    sum -= a[i];\n    h += a[i];\n    if (h <= 0) {\n        cout << i + 1 << endl;\n        return 0;\n    }\n    gap = max(gap, sum);\n}\nif (sum <= 0) {\n    cout << -1 << endl;\n    return 0;\n}\n\nlong long whole = (H - gap) / sum;\nH -= whole * sum;\nlong long result = whole * n;\n\nfor (int i = 0;; i++) {\n    H += a[i % n];\n    result++;\n    if (H <= 0) {\n        cout << result << endl;\n        break;\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1141",
    "index": "F2",
    "title": "Same Sum Blocks (Hard)",
    "statement": "This problem is given in two editions, which differ exclusively in the constraints on the number $n$.\n\nYou are given an array of integers $a[1], a[2], \\dots, a[n].$ A block is a sequence of contiguous (consecutive) elements $a[l], a[l+1], \\dots, a[r]$ ($1 \\le l \\le r \\le n$). Thus, a block is defined by a pair of indices $(l, r)$.\n\nFind a set of blocks $(l_1, r_1), (l_2, r_2), \\dots, (l_k, r_k)$ such that:\n\n- They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks $(l_i, r_i)$ and $(l_j, r_j$) where $i \\neq j$ either $r_i < l_j$ or $r_j < l_i$.\n- For each block the sum of its elements is the same. Formally, $$a[l_1]+a[l_1+1]+\\dots+a[r_1]=a[l_2]+a[l_2+1]+\\dots+a[r_2]=$$ $$\\dots =$$ $$a[l_k]+a[l_k+1]+\\dots+a[r_k].$$\n- The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks $(l_1', r_1'), (l_2', r_2'), \\dots, (l_{k'}', r_{k'}')$ satisfying the above two requirements with $k' > k$.\n\n\\begin{center}\n{\\small The picture corresponds to the first example. Blue boxes illustrate blocks.}\n\\end{center}\n\nWrite a program to find such a set of blocks.",
    "tutorial": "Let's $x$ the same sum of blocks in the answer. Obviously, $x$ can be represented as a sum of some adjacent elements of $a$, i.e. $x=a[l]+a[l+1]+\\dots+a[r]$ for some $l$ and $r$. Iterate over all possible blocks in $O(n^2)$ and for each sum store all the blocks. You can use 'map<int, vector<pair<int,int>>>' to store blocks grouped by a sum. You can do it with the following code: Note, that blocks are sorted by the right end in each group. After it you can independently try each group (there are $O(n^2)$ of them) and find the maximal disjoint set of blocks of a group. You can do it greedily, each time taking into the answer segment with the smallest right end. Since in each group they are ordered by the right end, you can find the required maximal disjoint block set with one pass. Let's assume $pp$ is the current group of blocks (they are ordered by the right end), then the following code constructs the maximal disjoint set: Choose the maximum among maximal disjoint sets for the groups.",
    "code": "int n;\ncin >> n;\nvector<int> a(n);\nfor (int i = 0; i < n; i++)\n    cin >> a[i];\nmap<int, vector<pair<int,int>>> segs;\nfor (int r = 0; r < n; r++) {\n    int sum = 0;                              \n    for (int l = r; l >= 0; l--) {\n        sum += a[l];\n        segs[sum].push_back({l, r});\n    }\n}\nint result = 0;\nvector<pair<int,int>> best;\nfor (const auto& p: segs) {\n    const vector<pair<int,int>>& pp = p.second;\n    int cur = 0;\n    int r = -1;\n    vector<pair<int,int>> now;\n    for (auto seg: pp)\n        if (seg.first > r) {\n            cur++;\n            now.push_back(seg);\n            r = seg.second;\n        }\n    if (cur > result) {\n        result = cur;\n        best = now;\n    }\n}\ncout << result << endl;\nfor (auto seg: best)\n    cout << seg.first + 1 << \" \" << seg.second + 1 << endl;",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1141",
    "index": "G",
    "title": "Privatization of Roads in Treeland",
    "statement": "Treeland consists of $n$ cities and $n-1$ roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.\n\nThere are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.\n\nThe government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed $k$ and the number of companies taking part in the privatization is minimal.\n\nChoose the number of companies $r$ such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most $k$. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal $r$ that there is such assignment to companies from $1$ to $r$ that the number of cities which are not good doesn't exceed $k$.\n\n\\begin{center}\n{\\small The picture illustrates the first example ($n=6, k=2$). The answer contains $r=2$ companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number $3$) is not good. The number of such vertices (just one) doesn't exceed $k=2$. It is impossible to have at most $k=2$ not good cities in case of one company.}\n\\end{center}",
    "tutorial": "Formally, the problem is to paint tree edges in minimal number of colors in such a way, the the number of improper vertices doesn't exceed $k$. A vertex is improper if it has at least two incident edges of the same color. It is easy to show that $D$ colors is always enough to paint a tree in such a way that all the vertices are proper, where $D$ is the maximum vertex degree. Actually, it is always the truth do any bipartite graph. Indeed, if number of colors is less than the maximum degree, such vertices will have at least two edges of the same color (Dirichlet's principle). If $D$ equals the maximum degree, you can use just depth first search tree traversal to paint edges in different colors. In this problem you can have up to $k$ improper vertices, so just choose such minimal $d$ that number of vertices of degree greater than $d$ is at most $k$. In an alternative solution, you can use a binary search to find such $d$, but it makes the implementation harder and the solution becomes slower by $log$ factor. After it paint edges with $d$ colors, each time choosing the next color (skip color if it equals with the color of the traversal incoming edge).",
    "code": "int n, k, r;\nvector<vector<pair<int,int>>> g;\nint D;\nvector<int> col;\n\nvoid dfs(int u, int p, int f) {\n    int color = 0;\n    for (auto e: g[u])\n        if (p != e.first) {\n            if (color == f) {\n                color = (color + 1) % D;\n                f = -1;\n            }\n            col[e.second] = color;\n            dfs(e.first, u, color);\n            color = (color + 1) % D;\n        }         \n}\n\nint main() {\n    cin >> n >> k;\n    g.resize(n);\n    vector<int> d(n);\n    for (int i = 0; i + 1 < n; i++) {\n        int x, y;\n        cin >> x >> y;\n        x--, y--;\n        g[x].push_back({y, i});\n        g[y].push_back({x, i});\n        d[x]++, d[y]++;\n    }\n    map<int,int> cnt;\n    for (int dd: d)\n        cnt[dd]++;\n    \n    int kk = n;\n    D = 0;\n    for (auto p: cnt)\n        if (kk > k)\n            D = p.first,\n            kk -= p.second;\n        else\n            break;\n    col = vector<int>(n - 1);\n    dfs(0, -1, -1);    \n    cout << D << endl;\n    for (int i = 0; i + 1 < n; i++)\n        cout << col[i] + 1 << \" \";\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1142",
    "index": "A",
    "title": "The Beatles",
    "statement": "Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through $n \\cdot k$ cities. The cities are numerated from $1$ to $n \\cdot k$, the distance between the neighboring cities is exactly $1$ km.\n\nSergey does not like beetles, he loves burgers. Fortunately for him, there are $n$ fast food restaurants on the circle, they are located in the $1$-st, the $(k + 1)$-st, the $(2k + 1)$-st, and so on, the $((n-1)k + 1)$-st cities, i.e. the distance between the neighboring cities with fast food restaurants is $k$ km.\n\nSergey began his journey at some city $s$ and traveled along the circle, making stops at cities each $l$ km ($l > 0$), until he stopped in $s$ once again. Sergey then forgot numbers $s$ and $l$, but he remembers that the distance from the city $s$ to the nearest fast food restaurant was $a$ km, and the distance from the city he stopped at after traveling the first $l$ km from $s$ to the nearest fast food restaurant was $b$ km. Sergey always traveled in the same direction along the circle, but when he calculated distances to the restaurants, he considered both directions.\n\nNow Sergey is interested in two integers. The first integer $x$ is the minimum number of stops (excluding the first) Sergey could have done before returning to $s$. The second integer $y$ is the maximum number of stops (excluding the first) Sergey could have done before returning to $s$.",
    "tutorial": "Let's assume that we know the length of the jump, and it is equal to $l$. Then, in order to be back at the starting point, Sergey will need to make exactly $n \\cdot k / gcd(n \\cdot k, l)$ moves, where $gcd$ is the greatest common divider. Let $l = kx + c$, where $c$ and $x$ are non-negative integers. So, if we know $a$ and $b$, than $c$ can only take $4$ values: $((a + b) \\% c, (a - b) \\% c, (b - a) \\% c, (-a - b) \\% c)$, where $\\% c$ means modulo $c$. It is clear that only $x <n$ can be considered. Then we iterate over all the $4n$ variants of the pair $(x, c)$, and for each we find the number of moves to the starting point. The minimum and maximum of the resulting numbers will be the answer.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1142",
    "index": "B",
    "title": "Lynyrd Skynyrd",
    "statement": "Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $p$ of length $n$, and Skynyrd bought an array $a$ of length $m$, consisting of integers from $1$ to $n$.\n\nLynyrd and Skynyrd became bored, so they asked you $q$ queries, each of which has the following form: \"does the subsegment of $a$ from the $l$-th to the $r$-th positions, inclusive, have a subsequence that is a cyclic shift of $p$?\" Please answer the queries.\n\nA permutation of length $n$ is a sequence of $n$ integers such that each integer from $1$ to $n$ appears exactly once in it.\n\nA cyclic shift of a permutation $(p_1, p_2, \\ldots, p_n)$ is a permutation $(p_i, p_{i + 1}, \\ldots, p_{n}, p_1, p_2, \\ldots, p_{i - 1})$ for some $i$ from $1$ to $n$. For example, a permutation $(2, 1, 3)$ has three distinct cyclic shifts: $(2, 1, 3)$, $(1, 3, 2)$, $(3, 2, 1)$.\n\nA subsequence of a subsegment of array $a$ from the $l$-th to the $r$-th positions, inclusive, is a sequence $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$ for some $i_1, i_2, \\ldots, i_k$ such that $l \\leq i_1 < i_2 < \\ldots < i_k \\leq r$.",
    "tutorial": "For each $a_i$ if the number $a_i$ has position $j$ in $p$, let's find the greatest $l$, such that $l$ is less then $i$ and $a_l = p_{j - 1}$ (let's define $p_0 = p_n$) We will call this position $b_i$. This can be done in $O(n)$ time, just for each $p_j$ we will keep the last it's position in $a$ while iterating over $a$. Now let's notice that using this info for each $i$ we can find the beginning of right most subsequence of $a$ which is a ciclic shift of $p$ and ends exactly at $a_i$. This can easily be done because if there is a subsequence of $a$ $a_{i_1}, a_{i_2} \\ldots, a_{i_{n - 1}}, a_i$, which is the right most such subsequence, then ${i_{n - 1}}$ is $b_i$, $i_{n- 2}$ is $b_{i_{n - 1}}$, and so on. So to find such subsequence and the position of it's beginning, we need to calculate $b[b[b \\ldots b[i] \\ldots ]]$ $n - 1$ times. To do it we can use binary lifting. Then we will have $O(m \\log n)$ precalc and we will get the beginning of such subsequence in $O(\\log n)$ time. Now for each prefix of $a$ let's calculate the the beginning of right most subsequence of it, which is a cyclic shift of $p$. This can be calculated in linear time, first we look at the answer for this prefix without the last number, and then update it with the right most subsequence, which ends at the end of prefix. Now we can answer each query in $O(1)$ time, because we just need to find the beginning of the right most subsequence, which ends at prefix of length $r$ and compare it with $l$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1142",
    "index": "C",
    "title": "U2",
    "statement": "Recently Vasya learned that, given two points with different $x$ coordinates, you can draw through them exactly one parabola with equation of type $y = x^2 + bx + c$, where $b$ and $c$ are reals. Let's call such a parabola an $U$-shaped one.\n\nVasya drew several distinct points with integer coordinates on a plane and then drew an $U$-shaped parabola through each pair of the points that have different $x$ coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.\n\nThe internal area of an $U$-shaped parabola is the part of the plane that lies strictly above the parabola when the $y$ axis is directed upwards.",
    "tutorial": "Let's rewrite parabola equation $y = x^2 + bx + c$ as $y - x^2 = bx + c$. This means, that if you change each point $(x_i, y_i)$ to $(x_i, y_i - x_i^2)$, then the parabolas will turn into straight lines, and the task will be reduced to constructing a top part of convex hull on the obtained points and calculate the number of segments on it.",
    "tags": [
      "geometry"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1142",
    "index": "D",
    "title": "Foreigner",
    "statement": "Traveling around the world you noticed that many shop owners raise prices to inadequate values if the see you are a foreigner.\n\nYou define inadequate numbers as follows:\n\n- all integers from $1$ to $9$ are inadequate;\n- for an integer $x \\ge 10$ to be inadequate, it is required that the integer $\\lfloor x / 10 \\rfloor$ is inadequate, but that's not the only condition. Let's sort all the inadequate integers. Let $\\lfloor x / 10 \\rfloor$ have number $k$ in this order. Then, the integer $x$ is inadequate only if the last digit of $x$ is strictly less than the reminder of division of $k$ by $11$.\n\nHere $\\lfloor x / 10 \\rfloor$ denotes $x/10$ rounded down.\n\nThus, if $x$ is the $m$-th in increasing order inadequate number, and $m$ gives the remainder $c$ when divided by $11$, then integers $10 \\cdot x + 0, 10 \\cdot x + 1 \\ldots, 10 \\cdot x + (c - 1)$ are inadequate, while integers $10 \\cdot x + c, 10 \\cdot x + (c + 1), \\ldots, 10 \\cdot x + 9$ are not inadequate.\n\nThe first several inadequate integers are $1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 30, 31, 32 \\ldots$. After that, since $4$ is the fourth inadequate integer, $40, 41, 42, 43$ are inadequate, while $44, 45, 46, \\ldots, 49$ are not inadequate; since $10$ is the $10$-th inadequate number, integers $100, 101, 102, \\ldots, 109$ are all inadequate. And since $20$ is the $11$-th inadequate number, none of $200, 201, 202, \\ldots, 209$ is inadequate.\n\nYou wrote down all the prices you have seen in a trip. Unfortunately, all integers got concatenated in one large digit string $s$ and you lost the bounds between the neighboring integers. You are now interested in the number of substrings of the resulting string that form an inadequate number. If a substring appears more than once at different positions, all its appearances are counted separately.",
    "tutorial": "Let's take any inadequate number $x$ of length $n$. Let's keep 3 parameters for it: $a_x$ which is the number of all inadequate numbers less of equal then $x$, $b_x$ which is the number of inadequate numbers less then $x$ which have length $n$ and $c_x$ which is the number of inadequate numbers grater then $x$ which have length $n$. We know that there are exactly $a_x$ modulo 11 inadequate numbers that come from $x$ by adding a new digit to the end. Also, because we know $b_x$ and $c_x$, we can find $a$, $b$ and $c$ parameters for each of those numbers. Let's now notice, that if instead of keeping $a$, $b$ and $c$ parameters we can keep all of them modulo 11. The parameters of all numbers that come from $x$ will still be defined because if we increase $a$ by 11, these parameters will be the same modulo 11, if we increase $b$ by 11, $a$ and $b$ parameters of all numbers that come from $x$ are increase by $0 + 1 + 2 + \\ldots + 10 = (11 \\cdot 10) / 2 = 55$ which is 0 modulo 11. The same is with $c$ parameter. So these 3 parameters modulo 11 exactly define what new numbers will come from $x$ and the values of these 3 parameters for them. Now we can create some kind of automaton of size $11^3$, where we will have 9 starting nodes and all paths from these nodes will be the inadequate numbers and for any inadequate number there will be path which will define it. Now let's create dynamic $dp[i][j]$, which is how long we can go into the automaton by the characters of suffix of length $i$ of our given string $s$ starting from node $j$ in automaton. We can calculate this $dp$ in $n \\cdot 11^3$ time and using it we can check for each suffix of $s$ what is its longest prefix that is an inadequate number and so we can solve the problem. Actually, during the contest it turned out that this problem has shorter solution, but this is more general one which doesn't depend on the starting numbers (in our case they were $1, 2, 3, \\ldots 9$).",
    "tags": [
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1142",
    "index": "E",
    "title": "Pink Floyd",
    "statement": "This is an interactive task.\n\nScientists are about to invent a new optimization for the Floyd-Warshall algorithm, which will allow it to work in linear time. There is only one part of the optimization still unfinished.\n\nIt is well known that the Floyd-Warshall algorithm takes a graph with $n$ nodes and exactly one edge between each pair of nodes. The scientists have this graph, what is more, they have directed each edge in one of the two possible directions.\n\nTo optimize the algorithm, exactly $m$ edges are colored in pink color and all the rest are colored in green. You know the direction of all $m$ pink edges, but the direction of green edges is unknown to you. In one query you can ask the scientists about the direction of exactly one green edge, however, you can perform at most $2 \\cdot n$ such queries.\n\nYour task is to find the node from which every other node can be reached by a path consisting of edges of same color. Be aware that the scientists may have lied that they had fixed the direction of all edges beforehand, so their answers may depend on your queries.",
    "tutorial": "First let's assume that graph has only the green edges and we still don't know their directions. Then we can do the following. We will keep some node which we will call the \"top node\" and the list of the nodes, that can be reached from the top node. Let's take some node $A$ which is not reachable and ask about the direction of edge between the top node and $A$. If the edge goes from top node to $A$, then we can add $A$ to the list of reachable nodes and the size of the list will increase by one. If the edge goes from $A$ to the top node, then we can call $A$ the new top node, and as the old top node was reachable from $A$, the list of reachable nodes will remain the same, but the node $A$ is reachable from itself, so it also will be added to the list. This way after each query we will increase the number of reachable nodes and in $n - 1$ query we will get the answer. In our graph we have edges that are coloured in pink, so if we will repeat the described above algorithm, we may get that the edge between top node and $A$ is coloured in pink. To avoid it, let's create the condensation of pink graph (condensation means the graph of the strongly connected components (later SCC)). As it is a condensation, there always should be some SCCs, that have no incoming edges. Let's call them free SCCs. We will pick some free SCC and pick some node from it and make it top node. Now we will repeat the following: if there are no other free SCC except the one, that contains the top node, all others are reachable from the only free SCC, which means that we have solved the problem. If there is any other top SCC, let's pick some node $A$ from it. Because this SCC has no incoming edges, the edge between $A$ and top node is green. So we can repeat the algorithm described above. After that as the node $A$ is reachable by green color, we can assume that this node is deleted. If it was the last node in it's SCC, we delete this SCC as well and delete all outcoming edges from it. Now some more SCCs may become free. And then we repeat our algorithm. After at most $n-1$ steps all nodes will be reachable from top one by single coloured path, which means that we have solved the problem. In out algorithm we need first to create condensation of the graph, which can be done in $O(n + m)$ time, then we need to remember how many nodes are in each SCC and keep a set of all free SCCs. That can also be done in $O(n + m)$ time.",
    "tags": [
      "graphs",
      "interactive"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1143",
    "index": "A",
    "title": "The Doors",
    "statement": "Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.\n\nThere are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $k$ such that Mr. Black can exit the house after opening the first $k$ doors.\n\nWe have to note that Mr. Black opened each door at most once, and in the end all doors became open.",
    "tutorial": "Let's walk through the array and find for each exit the door, that was opened last. Then the answer is minimum of the numbers of these doors.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1143",
    "index": "B",
    "title": "Nirvana",
    "statement": "Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.\n\nHelp Kurt find the maximum possible product of digits among all integers from $1$ to $n$.",
    "tutorial": "Let number $x$ be an answer, and $\\overline{y_0 y_1 \\ldots y_l}$ - number from input, so $x$ = $\\overline{y_0 y_1 \\ldots y_k (y_{k + 1} - 1) 9 9 \\ldots 9}$ for some $k$ (otherwise, you can increase one of the digits by $1$, so that $x$ will still be no more than $y$). So, let's go through $k$ from $0$ to the length of $y$ and return the maximum of them by the product of digits.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1143",
    "index": "C",
    "title": "Queen",
    "statement": "You are given a rooted tree with vertices numerated from $1$ to $n$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.\n\nAncestors of the vertex $i$ are all vertices on the path from the root to the vertex $i$, except the vertex $i$ itself. The parent of the vertex $i$ is the nearest to the vertex $i$ ancestor of $i$. Each vertex is a child of its parent. In the given tree the parent of the vertex $i$ is the vertex $p_i$. For the root, the value $p_i$ is $-1$.\n\n\\begin{center}\n{\\small An example of a tree with $n=8$, the root is vertex $5$. The parent of the vertex $2$ is vertex $3$, the parent of the vertex $1$ is vertex $5$. The ancestors of the vertex $6$ are vertices $4$ and $5$, the ancestors of the vertex $7$ are vertices $8$, $3$ and $5$}\n\\end{center}\n\nYou noticed that some vertices do not respect others. In particular, if $c_i = 1$, then the vertex $i$ does not respect any of its ancestors, and if $c_i = 0$, it respects all of them.\n\nYou decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the \\textbf{smallest number}. When you delete this vertex $v$, all children of $v$ become connected with the parent of $v$.\n\n\\begin{center}\n{\\small An example of deletion of the vertex $7$.}\n\\end{center}\n\nOnce there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.",
    "tutorial": "From the condition about the fact that each vertex equally respects all its ancestors, we can understand that each vertex is either always a candidate for deletion or it can never be deleted. That is because when we delete some vertex all new vertices which become sons of it's parent are also disrespecting it. Now we can iterate over all vertices and if it respects it's parent, we will remember that it's parent can not be deleted. And so we will get the answer.",
    "tags": [
      "dfs and similar",
      "trees"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1144",
    "index": "A",
    "title": "Diverse Strings",
    "statement": "A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: \"fced\", \"xyz\", \"r\" and \"dabcef\". The following string are \\textbf{not} diverse: \"az\", \"aa\", \"bad\" and \"babc\". Note that the letters 'a' and 'z' are not adjacent.\n\nFormally, consider positions of all letters in the string in the alphabet. These positions should form contiguous segment, i.e. they should come one by one without any gaps. And all letters in the string should be distinct (duplicates are not allowed).\n\nYou are given a sequence of strings. For each string, if it is diverse, print \"Yes\". Otherwise, print \"No\".",
    "tutorial": "The string is diverse if it is a permutation of some substring of the Latin alphabet (\"abcd ... xyz\"). In other words, the string is diverse if all letters in it are distinct (we can check it using some structure like std::set or array of used elements) and if the number of letters between the letter with the maximum alphabet position and the letter with the minimum alphabet position plus one is exactly the length of the string. For example, the position in alphabet of letter 'a' is one, the position of letter 'f' is six and so on.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int n;\n    cin >> n;\n    forn(i, n) {\n        string s;\n        cin >> s;\n        if (set<char>(s.begin(), s.end()).size() == s.length()\n                && *max_element(s.begin(), s.end()) == char(*min_element(s.begin(), s.end()) + (s.length() - 1)))\n            cout << \"Yes\" << endl;\n        else\n            cout << \"No\" << endl;\n    }\n}\n",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1144",
    "index": "B",
    "title": "Parity Alternated Deletions",
    "statement": "Polycarp has an array $a$ consisting of $n$ integers.\n\nHe wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $n-1$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.\n\nFormally:\n\n- If it is the first move, he chooses any element and deletes it;\n- If it is the second or any next move:\n\n- if the last deleted element was \\textbf{odd}, Polycarp chooses any \\textbf{even} element and deletes it;\n- if the last deleted element was \\textbf{even}, Polycarp chooses any \\textbf{odd} element and deletes it.\n\n- If after some move Polycarp cannot make a move, the game ends.\n\nPolycarp's goal is to \\textbf{minimize} the sum of \\textbf{non-deleted} elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of \\textbf{non-deleted} elements is zero.\n\nHelp Polycarp find this value.",
    "tutorial": "Let's calculate the sum of the whole array $sum$ and then divide all its elements into two arrays $odd$ and $even$ by their parity ($odd$ for odd, $even$ for even). Sort both of them in non-increasing order. Then what can we see? We always can delete first $k = min(|odd|, |even|)$ elements from both arrays (where $|x|$ is the size of $x$). So let's decrease $sum$ by the sum of first $k$ elements of the array $odd$ and the same for the array $even$. If one the arrays has more than $k$ elements (both arrays cannot have more than $k$ elements because if it is so then $k$ should be greater) then let's decrease $sum$ by the $k+1$-th element of this array (because this is the maximum possible element we can remove). Now $sum$ is the answer for the problem.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tint sum = 0;\n\tvector<int> even, odd;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\tsum += x;\n\t\tif (x & 1) odd.push_back(x);\n\t\telse even.push_back(x);\n\t}\n\t\n\tsort(odd.rbegin(), odd.rend());\n\tsort(even.rbegin(), even.rend());\n\tint k = min(odd.size(), even.size());\n\tint rem = sum;\n\trem -= accumulate(odd.begin(), odd.begin() + k, 0);\n\trem -= accumulate(even.begin(), even.begin() + k, 0);\n\tif (int(odd.size()) > k) {\n\t\trem -= odd[k];\n\t}\n\tif (int(even.size()) > k) {\n\t\trem -= even[k];\n\t}\n\t\n\tcout << rem << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1144",
    "index": "C",
    "title": "Two Shuffled Sequences",
    "statement": "Two integer sequences existed initially — one of them was \\textbf{strictly} increasing, and the other one — \\textbf{strictly} decreasing.\n\nStrictly increasing sequence is a sequence of integers $[x_1 < x_2 < \\dots < x_k]$. And strictly decreasing sequence is a sequence of integers $[y_1 > y_2 > \\dots > y_l]$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.\n\nThey were merged into one sequence $a$. After that sequence $a$ got shuffled. For example, some of the possible resulting sequences $a$ for an increasing sequence $[1, 3, 4]$ and a decreasing sequence $[10, 4, 2]$ are sequences $[1, 2, 3, 4, 4, 10]$ or $[4, 2, 1, 10, 4, 3]$.\n\nThis shuffled sequence $a$ is given in the input.\n\nYour task is to find \\textbf{any} two suitable initial sequences. One of them should be \\textbf{strictly} increasing and the other one — \\textbf{strictly} decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.\n\nIf there is a contradiction in the input and it is impossible to split the given sequence $a$ to increasing and decreasing sequences, print \"NO\".",
    "tutorial": "Let's count the number of occurrences of each element in the array $cnt$. Because the maximum possible element is $2 \\cdot 10^5$, it can be done without any data structures. Then let's check if $cnt_i$ is greater than $2$ for some $i$ from $0$ to $2 \\cdot 10^5$, and if it is, then the answer is \"NO\", because this element should occur at least twice in one of the sequences. Now let's output the increasing sequence. The number of elements in it is the number of elements $i$ such that $cnt_i = 2$. Let's iterate from left to right, print the suitable elements and decrease their $cnt$. The number of elements in the decreasing sequence is just the number of elements with non-zero $cnt$. So let's iterate from right to left and just print suitable elements.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> cnt(200 * 1000 + 1);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\t++cnt[x];\n\t\tif (cnt[x] > 2) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << \"YES\" << endl << count(cnt.begin(), cnt.end(), 2) << endl;\n\tfor (int i = 0; i <= 200 * 1000; ++i) {\n\t\tif (cnt[i] == 2) {\n\t\t\tcout << i << \" \";\n\t\t\t--cnt[i];\n\t\t}\n\t}\n\tcout << endl << count(cnt.begin(), cnt.end(), 1) << endl;\n\tfor (int i = 200 * 1000; i >= 0; --i) {\n\t\tif (cnt[i] == 1) {\n\t\t\tcout << i << \" \";\n\t\t\t--cnt[i];\n\t\t}\n\t}\n\tcout << endl;\n\t\n\tassert(count(cnt.begin(), cnt.end(), 0) == 200 * 1000 + 1);\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1144",
    "index": "D",
    "title": "Equalize Them All",
    "statement": "You are given an array $a$ consisting of $n$ integers. You can perform the following operations arbitrary number of times (possibly, zero):\n\n- Choose a pair of indices $(i, j)$ such that $|i-j|=1$ (indices $i$ and $j$ are adjacent) and set $a_i := a_i + |a_i - a_j|$;\n- Choose a pair of indices $(i, j)$ such that $|i-j|=1$ (indices $i$ and $j$ are adjacent) and set $a_i := a_i - |a_i - a_j|$.\n\nThe value $|x|$ means the absolute value of $x$. For example, $|4| = 4$, $|-3| = 3$.\n\nYour task is to find the minimum number of operations required to obtain the array of equal elements and print the order of operations to do it.\n\n\\textbf{It is guaranteed that you always can obtain the array of equal elements using such operations}.\n\n\\textbf{Note that after each operation each element of the current array should not exceed $10^{18}$ by absolute value}.",
    "tutorial": "Let's find the most frequent element in the array (using the array of frequencies $cnt$, of course). Let this element be $x$. If we will see the operations more carefully, we can see that the part of these operations means \"set element $p$ to element $q$\". if $p < q$ then this operation is $1 p q$, otherwise it is $2 p q$. Now let's consider the number of operations in the optimal answer. It is obvious that we need at least $n - cnt_x$ operations to equalize all the elements. And it is also obvious that we can always do it with $n - cnt_x$ such operations we have. How to restore the answer? There is an easy way to do it: find the first occurrence of $x$. Let it be $pos$. Then let's go from $pos - 1$ to $1$ and set each element to the next element (element at the position $pos - 1$ to $pos$, $pos - 2$ to $pos - 1$ and so on). And don't forget to print right type of operation. Then let's go from left to right from $1$ to $n$ and if the $i$-th element don't equal to $x$ then set it to $i-1$-th element using right operation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\t\n\tvector<int> a(n), cnt(200 * 1000 + 1);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\t++cnt[a[i]];\n\t}\n\t\n\tint val = max_element(cnt.begin(), cnt.end()) - cnt.begin();\n\tint pos = find(a.begin(), a.end(), val) - a.begin();\n\t\n\tcout << n - cnt[val] << endl;\n\tint siz = 0;\n\tfor (int i = pos - 1; i >= 0; --i) {\n\t\tcout << 1 + (a[i] > a[i + 1]) << \" \" << i + 1 << \" \" << i + 2 << \" \" << endl;\n\t\ta[i] = a[i + 1];\n\t\t++siz;\n\t}\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tif (a[i + 1] != val) {\n\t\t\tassert(a[i] == val);\n\t\t\tcout << 1 + (a[i + 1] > a[i]) << \" \" << i + 2 << \" \" << i + 1 << \" \" << endl;\n\t\t\ta[i + 1] = a[i];\n\t\t\t++siz;\n\t\t}\n\t}\n\t\n\tassert(siz == n - cnt[val]);\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1144",
    "index": "E",
    "title": "Median String",
    "statement": "You are given two strings $s$ and $t$, both consisting of exactly $k$ lowercase Latin letters, $s$ is lexicographically less than $t$.\n\nLet's consider list of all strings consisting of exactly $k$ lowercase Latin letters, lexicographically not less than $s$ and not greater than $t$ (including $s$ and $t$) in lexicographical order. For example, for $k=2$, $s=$\"az\" and $t=$\"bf\" the list will be [\"az\", \"ba\", \"bb\", \"bc\", \"bd\", \"be\", \"bf\"].\n\nYour task is to print the median (the middle element) of this list. For the example above this will be \"bc\".\n\n\\textbf{It is guaranteed that there is an odd number of strings lexicographically not less than $s$ and not greater than $t$}.",
    "tutorial": "This problem supposed to be easy long arithmetic problem. Let's represent our strings as huge numbers with base $26$. Let $s$ be $l$ and $t$ be $r$. So if we will see more precisely in the problem statement, then we can see that the answer is $\\frac{l + r}{2}$. The operation $l + r$ with long numbers can be done in $O(k)$ and division long number by two also can be done in $O(k)$. All details of implementation are in the author's solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> get(const string &s) {\n\tvector<int> res(s.size() + 1);\n\tfor (int i = 0; i < int(s.size()); ++i) {\n\t\tres[i + 1] = s[i] - 'a';\n\t}\n\treturn res;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint k;\n\tstring s, t;\n\tcin >> k >> s >> t;\n\tvector<int> a = get(s), b = get(t);\n\t\n\tfor (int i = k; i >= 0; --i) {\n\t\ta[i] += b[i];\n\t\tif (i) {\n\t\t\ta[i - 1] += a[i] / 26;\n\t\t\ta[i] %= 26;\n\t\t}\n\t}\n\t\n\tfor (int i = 0; i <= k; ++i) {\n\t\tint rem = a[i] % 2;\n\t\ta[i] /= 2;\n\t\tif (i + 1 <= k) {\n\t\t\ta[i + 1] += rem * 26;\n\t\t} else {\n\t\t\tassert(rem == 0);\n\t\t}\n\t}\n\t\n\tfor (int i = 1; i <= k; ++i) {\n\t\tcout << char('a' + a[i]);\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1144",
    "index": "F",
    "title": "Graph Without Long Directed Paths",
    "statement": "You are given a connected undirected graph consisting of $n$ vertices and $m$ edges. There are no self-loops or multiple edges in the given graph.\n\nYou have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges).",
    "tutorial": "What if the given graph will contain a cycle of odd length? It will mean that some two consecutive edges of this cycle will be oriented in the same way and will form a path of length two. What if there is no cycles of odd length in this graph? Then it is bipartite. Let's color it and see what we got. We got some vertices in the left part, some vertices in the right part and all edges connecting vertices from different parts. Let's orient all edges such that them will go from the left part to the right part. That's it.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 11;\n\nint n, m;\nvector<int> g[N];\nvector<pair<int, int>> e;\n\nbool bipartite;\nvector<int> color;\n\nvoid dfs(int v, int c) {\n\tcolor[v] = c;\n\tfor (auto to : g[v]) {\n\t\tif (color[to] == -1) {\n\t\t\tdfs(to, c ^ 1);\n\t\t} else {\n\t\t\tif (color[to] == color[v]) {\n\t\t\t\tbipartite = false;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m;\n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t\te.push_back(make_pair(x, y));\n\t}\n\t\n\tbipartite = true;\n\tcolor = vector<int>(n, -1);\n\tdfs(0, 0);\n\t\n\tif (!bipartite) {\n\t\tcout << \"NO\" << endl;\n\t\treturn 0;\n\t}\n\t\n\tcout << \"YES\" << endl;\n\tfor (int i = 0; i < m; ++i) {\n\t\tcout << (color[e[i].first] < color[e[i].second]);\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1144",
    "index": "G",
    "title": "Two Merged Sequences",
    "statement": "Two integer sequences existed initially, one of them was \\textbf{strictly} increasing, and another one — \\textbf{strictly} decreasing.\n\nStrictly increasing sequence is a sequence of integers $[x_1 < x_2 < \\dots < x_k]$. And strictly decreasing sequence is a sequence of integers $[y_1 > y_2 > \\dots > y_l]$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.\n\nElements of increasing sequence were inserted between elements of the decreasing one (and, possibly, before its first element and after its last element) \\textbf{without changing the order}. For example, sequences $[1, 3, 4]$ and $[10, 4, 2]$ can produce the following resulting sequences: $[10, \\textbf{1}, \\textbf{3}, 4, 2, \\textbf{4}]$, $[\\textbf{1}, \\textbf{3}, \\textbf{4}, 10, 4, 2]$. The following sequence cannot be the result of these insertions: $[\\textbf{1}, 10, \\textbf{4}, 4, \\textbf{3}, 2]$ because the order of elements in the increasing sequence was changed.\n\nLet the obtained sequence be $a$. This sequence $a$ is given in the input. Your task is to find \\textbf{any} two suitable initial sequences. One of them should be \\textbf{strictly} increasing, and another one — \\textbf{strictly} decreasing. \\textbf{Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.}\n\nIf there is a contradiction in the input and it is impossible to split the given sequence $a$ into one increasing sequence and one decreasing sequence, print \"NO\".",
    "tutorial": "I know about greedy solutions and other approaches, but I'll describe my solution. This is dynamic programming. I'll consider all positions $0$-indexed. Let $dp_{i, 0}$ be the maximum possible minimal element in the decreasing sequence, if the last element ($i-1$-th) was in the increasing sequence, and $dp_{i, 1}$ be the minimum possible maximum element in the increasing sequence, if the last element ($i-1$-th) was in the decreasing sequence. Initially, all $dp_{i, 0}$ are $-\\infty$ and all $dp_{i, 1}$ are $\\infty$ (except two values: $dp_{0, 0} = \\infty$ and $dp_{0, 1} = -\\infty$). What about transitions? Let's consider four cases: The previous element was in the increasing sequence and we want to add the current element to the increasing sequence. We can do $dp_{i, 0} := max(dp_{i, 0}, dp_{i - 1, 0})$ if $a_i > a_{i - 1}$; the previous element was in the increasing sequence and we want to add the current element to the decreasing sequence. We can do $dp_{i, 1} := min(dp_{i, 1}, a_{i - 1})$ if $a_i < dp_{i - 1, 0}$; the previous element was in the decreasing sequence and we want to add the current element to the decreasing sequence. We can do $dp_{i, 1} := min(dp_{i, 1}, dp_{i - 1, 1})$ if $a_i < a_{i - 1}$; the previous element was in the decreasing sequence and we want to add the current element to the increasing sequence. We can do $dp_{i, 0} := max(dp_{i, 0}, a_{i - 1})$ if $a_i > dp_{i - 1, 1}$. The logic behind these transitions is kinda hard but understandable. If $dp_{n - 1, 0} = -\\infty$ and $dp_{n - 1, 1} = \\infty$ then the answer is \"NO\". Otherwise we can restore any possible answer using parents in the dynamic programming.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tvector<vector<int>> dp(n, vector<int>({-INF, INF}));\n\tvector<vector<int>> p(n, vector<int>(2, -1));\n\tdp[0][0] = INF;\n\tdp[0][1] = -INF;\n\t\n\tfor (int i = 1; i < n; ++i) {\n\t\t{\n\t\t\tif (a[i] > a[i - 1] && dp[i][0] < dp[i - 1][0]) {\n\t\t\t\tdp[i][0] = dp[i - 1][0];\n\t\t\t\tp[i][0] = 0;\n\t\t\t}\n\t\t\tif (a[i] < dp[i - 1][0] && dp[i][1] > a[i - 1]) {\n\t\t\t\tdp[i][1] = a[i - 1];\n\t\t\t\tp[i][1] = 0;\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tif (a[i] < a[i - 1] && dp[i][1] > dp[i - 1][1]) {\n\t\t\t\tdp[i][1] = dp[i - 1][1];\n\t\t\t\tp[i][1] = 1;\n\t\t\t}\n\t\t\tif (a[i] > dp[i - 1][1] && dp[i][0] < a[i - 1]) {\n\t\t\t\tdp[i][0] = a[i - 1];\n\t\t\t\tp[i][0] = 1;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint pos = -1;\n\tif (dp[n - 1][0] != -INF) {\n\t\tpos = 0;\n\t}\n\tif (dp[n - 1][1] != INF) {\n\t\tpos = 1;\n\t}\n\t\n\tif (pos == -1) {\n\t\tcout << \"NO\" << endl;\n\t\treturn 0;\n\t}\n\t\n\tvector<int> inInc(n);\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tif (pos == 0) {\n\t\t\tinInc[i] = 1;\n\t\t}\n\t\tpos = p[i][pos];\n\t}\n\t\n\tcout << \"YES\" << endl;\n\tfor (int i = 0; i < n; ++i) {\n\t\tcout << !inInc[i] << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1146",
    "index": "A",
    "title": "Love \"A\"",
    "statement": "Alice has a string $s$. She really likes the letter \"a\". She calls a string good if strictly more than half of the characters in that string are \"a\"s. For example \"aaabb\", \"axaa\" are good strings, and \"baca\", \"awwwa\", \"\" (empty string) are not.\n\nAlice can erase some characters from her string $s$. She would like to know what is the longest string remaining after erasing some characters (possibly zero) to get a good string. It is guaranteed that the string has at least one \"a\" in it, so the answer always exists.",
    "tutorial": "In this problem, it is only ever optimal to erase characters that are not \"a\". Let $x$ be the number of \"a\" characters in the string $s$, and let $n$ be the total number of characters in $s$. In order for the $a$s to be a strict majority, we can have at most $x-1$ characters that are not \"a\", so the maximum string length is bounded from above by $2x-1$. The string length is also bounded above by the length of $s$, so the answer is $\\min(n, 2x-1)$.",
    "code": "#include <iostream>\n#include <algorithm>\nusing namespace std;\nint main()\n{\n    string t;\n    cin >> t;\n    cout << min(2*(int)count(t.begin(),t.end(),'a')-1,(int)t.size());\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1146",
    "index": "B",
    "title": "Hate \"A\"",
    "statement": "Bob has a string $s$ consisting of lowercase English letters. He defines $s'$ to be the string after removing all \"a\" characters from $s$ (keeping all other characters in the same order). He then generates a new string $t$ by concatenating $s$ and $s'$. In other words, $t=s+s'$ (look at notes for an example).\n\nYou are given a string $t$. Your task is to find some $s$ that Bob could have used to generate $t$. It can be shown that if an answer exists, it will be unique.",
    "tutorial": "There are a few different ways to approach this. In one way, we can approach it by looking at the frequency of all characters. We want to find a split point so that all \"a\"s lie on the left side of the split, and all other characters are split evenly between the left and right side. This split can be uniquely determined and found in linear time by keeping track of prefix sums (it also might be possible there is no split, in which case the answer is impossible). After finding a split, we still need to make sure the characters appear in the same order, which is another linear time pass. In another way, let's count the number of \"a\" and non-\"a\" characters. Let these numbers be $c_0$ and $c_1$. If $c_1$ is not divisible by $2$, then the answer is impossible. Otherwise, we know the suffix of length $c_1/2$ of $t$ must be $s'$, and we can check there are no \"a\"s there. We also check that after removing all \"a\"s from $t$, the first and second half of the strings are equal.",
    "code": "#include <iostream>\nusing namespace std;\nint main()\n{\n    string t;\n    cin >> t;\n    int cnt=0,pos=-1;\n    for (int i=0;i<t.size();i++)\n    {\n        if (t[i]=='a')\n        cnt++;\n        if (2*(i+1)-cnt==t.size())\n        {\n            pos=i;\n            break;\n        }\n    }\n    if (pos==-1)\n    {\n        cout << \":(\";\n        return 0;\n    }\n    int cur=0;\n    for (int j=pos+1;j<t.size();j++)\n    {\n        if (t[j]=='a')\n        {\n            cout << \":(\";\n            return 0;\n        }\n        while (t[cur]=='a')\n        cur++;\n        if (t[cur]!=t[j])\n        {\n            cout << \":(\";\n            return 0;\n        }\n        cur++;\n    }\n    cout << t.substr(0,pos+1);\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1146",
    "index": "C",
    "title": "Tree Diameter",
    "statement": "There is a weighted tree with $n$ nodes and $n-1$ edges. The nodes are conveniently labeled from $1$ to $n$. The weights are positive integers at most $100$. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes.\n\nUnfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes $p$ and $q$, and the judge will return the maximum distance between a node in $p$ and a node in $q$. In the words, maximum distance between $x$ and $y$, where $x \\in p$ and $y \\in q$. After asking not more than $9$ questions, you must report the maximum distance between any pair of nodes.",
    "tutorial": "The standard algorithm for finding the diameter of a tree is to find the farthest distance from node $1$, then find the farthest distance from that node. We can do the same technique in this problem. We use one question to get the farthest distance from node $1$ in the graph. Then, we use binary search to figure out which node is actually the farthest away (if there are ties, it doesn't matter which one we choose). More specifically, if we know the farthest node lies in some subset $S$, we can ask about half of the element in $S$. If the distance doesn't decrease, then we know the farthest node must be in the half we asked about, otherwise, it is in the other half. This will use an additional 7 questions. We use the last question to get the actual diameter. There's another way that uses fewer questions and also ignores the fact that the graph is a tree. We can state the problem instead as trying to find $7$ splits of numbers so that every pair of numbers is separated in at least one split. We can do this by looking at the binary representation of the numbers. In the i-th question, let $p$ be the set of all numbers with the i-th bit set and $q$ be the other numbers. Every pair has at most 7 bits, and each pair of numbers differs in at least one bit, so this satisfies what we are looking for. After asking all questions, we can print the maximum result we found from all of them.",
    "code": "/**\n * code generated by JHelper\n * More info: https://github.com/AlexeyDmitriev/JHelper\n * @author Azat Ismagilov\n */\n\n\n#include <fstream>\n\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <numeric>\n\n\n//#define int long long\n#define fs first\n#define sc second\n#define pb push_back\n#define ppb pop_back\n#define pf push_front\n#define ppf pop_front\n#define mp make_pair\n#define len(v) ((int)v.size())\n#define vc vector\n#define pr pair\n#define all(v) v.begin(), v.end()\n//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native\")\n//#pragma GCC optimize(\"unroll-loops\")\n\n\nusing namespace std;\n\n\ntemplate<typename T, typename U>\ninline ostream &operator<<(ostream &_out, const pair<T, U> &_p) {\n    _out << _p.first << ' ' << _p.second;\n    return _out;\n}\n\n\ntemplate<typename T, typename U>\ninline istream &operator>>(istream &_in, pair<T, U> &_p) {\n    _in >> _p.first >> _p.second;\n    return _in;\n}\n\n\ntemplate<typename T>\ninline ostream &operator<<(ostream &_out, const vector<T> &_v) {\n    if (_v.empty()) { return _out; }\n    _out << _v.front();\n    for (auto _it = ++_v.begin(); _it != _v.end(); ++_it) { _out << ' ' << *_it; }\n    return _out;\n}\n\n\ntemplate<typename T>\ninline istream &operator>>(istream &_in, vector<T> &_v) {\n    for (auto &_i : _v) { _in >> _i; }\n    return _in;\n}\n\n\nconst int MAXN = 1e5;\nconst int INF = 1e9;\nconst int MOD = 1e9 + 7;\n\n\nclass CTreeDiameter {\npublic:\n    void solve(std::istream &in, std::ostream &out) {\n        int n;\n        in >> n;\n        int ans = 0;\n        for (int k = 1; k <= 7; k++) {\n            int k1 = 0;\n            for (int i = 0; i < n; i++) {\n                if ((i % (1 << k)) >= (1 << (k - 1))) {\n                    k1++;\n                }\n            }\n            if (k1 > 0) {\n                out << k1 << ' ' << n - k1 << ' ';\n                for (int i = 0; i < n; i++) {\n                    if ((i % (1 << k)) >= (1 << (k - 1))) {\n                        out << i + 1 << ' ';\n                    }\n                }\n                for (int i = 0; i < n; i++) {\n                    if ((i % (1 << k)) < (1 << (k - 1))) {\n                        out << i + 1 << ' ';\n                    }\n                }\n                out << endl;\n                int x;\n                in >> x;\n                if (x == -1) {\n                    exit(1);\n                }\n                ans = max(ans, x);\n            }\n        }\n        out << \"-1 \" << ans << endl;\n    }\n};\n\n\n\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    CTreeDiameter solver;\n    std::istream &in(std::cin);\n    std::ostream &out(std::cout);\n    int n;\n    in >> n;\n    for (int i = 0; i < n; ++i) {\n        solver.solve(in, out);\n    }\n\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "graphs",
      "interactive"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1146",
    "index": "D",
    "title": "Frog Jumping",
    "statement": "A frog is initially at position $0$ on the number line. The frog has two positive integers $a$ and $b$. From a position $k$, it can either jump to position $k+a$ or $k-b$.\n\nLet $f(x)$ be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval $[0, x]$. The frog doesn't need to visit all these integers in one trip, that is, an integer is counted if the frog can somehow reach it if it starts from $0$.\n\nGiven an integer $m$, find $\\sum_{i=0}^{m} f(i)$. That is, find the sum of all $f(i)$ for $i$ from $0$ to $m$.",
    "tutorial": "Split this into $a$ problems. For each $i$ modulo $a$, we want to find the leftmost node that the frog can reach modulo $i$, and what is the smallest $x$ needed to get this. We can do this greedily, starting at $0$, jump to the right until we can jump left $b$, and repeat this until we find a repeated value modulo $a$. For each $i$ we have some $x_i$ and $d_i$, which is the smallest $x$ needed, and $d_i$ is the leftmost node we can reach that is a distance of $i$ modulo $a$. We can then do a summation $\\sum_{j=x_i}^{m} floor((j-d_i+1)/a)$. To find this sum in constant time, it's first easier to reduce it to case where the lower and upper bounds of this summation are divisible by $a$, then the sum will have groups of $a$ that are the same value, so it's just the summation of some consecutive integers which can be computed in constant time. The overall complexity is $O(a)$.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <set>\nusing namespace std;\nint dist[200005];\nlong long sum[200005];\nlong long f(long long x)\n{\n    return x*(x+1)/2;\n}\nint main()\n{\n    int m,a,b;\n    scanf(\"%d%d%d\",&m,&a,&b);\n    int g=__gcd(a,b),n=min(m,a+b-1);\n    for (int i=0;i<=n;i++)\n    dist[i]=n+1;\n    set<pair<int,int> > s;\n    s.insert({0,0});\n    dist[0]=0;\n    while (!s.empty())\n    {\n        auto p=*s.begin();\n        s.erase(s.begin());\n        if (dist[p.second]!=p.first)\n        continue;\n        sum[p.first]++;\n        if (p.second>=b && p.first<dist[p.second-b])\n        {\n            dist[p.second-b]=p.first;\n            s.insert({p.first,p.second-b});\n        }\n        if (p.second+a<=n && max(p.first,p.second+a)<dist[p.second+a])\n        {\n            dist[p.second+a]=max(p.first,p.second+a);\n            s.insert({max(p.first,p.second+a),p.second+a});\n        }\n    }\n    long long ans=0;\n    for (int i=0;i<=n;i++)\n    {\n        if (i)\n        sum[i]+=sum[i-1];\n        ans+=sum[i];\n    }\n    if (n!=m)\n    {\n        while ((m+1)%g)\n        {\n            ans+=m/g+1;\n            m--;\n        }\n        ans+=g*(f(m/g+1)-f(n/g+1));\n    }\n    printf(\"%I64d\",ans);\n}",
    "tags": [
      "dfs and similar",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1146",
    "index": "E",
    "title": "Hot is Cold",
    "statement": "You are given an array of $n$ integers $a_1, a_2, \\ldots, a_n$.\n\nYou will perform $q$ operations. In the $i$-th operation, you have a symbol $s_i$ which is either \"<\" or \">\" and a number $x_i$.\n\nYou make a new array $b$ such that $b_j = -a_j$ if $a_j s_i x_i$ and $b_j = a_j$ otherwise (i.e. if $s_i$ is '>', then all $a_j > x_i$ will be flipped). After doing all these replacements, $a$ is set to be $b$.\n\nYou want to know what your final array looks like after all operations.",
    "tutorial": "You can keep track of an array $w_i$ from $i = 0 \\ldots 10^5$ which is number from $0$ to $3$. This means 'keep sign', 'flip sign', 'positive', or 'negative', respectively. You can use this to determine the final value. For example, if $a_i = j$, then we look at $w_{|j|}$, and that will help us see what the final answer will be. Each operation affects some contiguous range of $w_i$s. For example if it's $< x$ where $x$ is positive, then that means each $w_i$ from $0$ to $x-1$ goes from \"keep sign\"<->\"flip sign\" or \"positive\"<->\"negative\" (i.e. flipping lowest bit of the number), and each $w_i$ from $x$ to $10^5$ is set to $p$. You can use a segment tree with flip/set range to implement these operations efficiently.",
    "code": "#include <iostream>\n#include <vector>\nusing namespace std;\n#define sh 100000\nvector<int> v[200005];\nint arr[100005],tree[2][400005],ans[200005],cur=-sh;\npair<char,int> qu[100005];\nvoid update(int node,int st,int en,int idx,pair<char,int> val)\n{\n    if (st==en)\n    {\n        tree[0][node]=0;\n        if ((val.first=='>' && cur>val.second) || (val.first=='<' && cur<val.second))\n        tree[0][node]=1;\n        tree[1][node]=1;\n        if ((val.first=='>' && -cur>val.second) || (val.first=='<' && -cur<val.second))\n        tree[1][node]=0;\n    }\n    else\n    {\n        int mid=(st+en)/2;\n        if (st<=idx && idx<=mid)\n        update(2*node,st,mid,idx,val);\n        else\n        update(2*node+1,mid+1,en,idx,val);\n        for (int i=0;i<2;i++)\n        tree[i][node]=tree[tree[i][2*node]][2*node+1];\n    }\n}\nint main()\n{\n    int n,q;\n    scanf(\"%d%d\",&n,&q);\n    for (int i=0;i<n;i++)\n    scanf(\"%d\",&arr[i]);\n    for (int i=0;i<q;i++)\n    {\n        scanf(\" %c%d\",&qu[i].first,&qu[i].second);\n        if (qu[i].first=='>')\n        {\n            v[qu[i].second+1+sh].push_back(i);\n            v[-qu[i].second+sh].push_back(i);\n        }\n        if (qu[i].first=='<')\n        {\n            v[qu[i].second+sh].push_back(i);\n            v[-qu[i].second+1+sh].push_back(i);\n        }\n        update(1,0,q-1,i,qu[i]);\n    }\n    while (1)\n    {\n        ans[cur+sh]=tree[0][1];\n        if (cur==sh)\n        break;\n        cur++;\n        for (int i:v[cur+sh])\n        update(1,0,q-1,i,qu[i]);\n    }\n    for (int i=0;i<n;i++)\n    printf(\"%d \",(!ans[arr[i]+sh]-ans[arr[i]+sh])*arr[i]);\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "divide and conquer",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1146",
    "index": "F",
    "title": "Leaf Partition",
    "statement": "You are given a rooted tree with $n$ nodes, labeled from $1$ to $n$. The tree is rooted at node $1$. The parent of the $i$-th node is $p_i$. A leaf is node with no children. For a given set of leaves $L$, let $f(L)$ denote the smallest connected subgraph that contains all leaves $L$.\n\nYou would like to partition the leaves such that for any two different sets $x, y$ of the partition, $f(x)$ and $f(y)$ are disjoint.\n\nCount the number of ways to partition the leaves, modulo $998244353$. Two ways are different if there are two leaves such that they are in the same set in one way but in different sets in the other.",
    "tutorial": "We can solve this with tree dp. Here, we extend the partition to include nodes in the $f$ values of the leaf set. The dp state counts the number of partitions of leaves in the subtree rooted at node $i$ subject to some conditions. We keep $3$ values for each node. $dp[i][0]$ will count the number of ways to partition the leaves given that node $i$ does not belong any partition. $dp[i][1]$ is the number of ways given that node $i$ is in some partition, but needs to be connected above because it is only directly connected to one child below. $dp[i][2]$ is the number of ways given that node $i$ is i some partition, but does not need to connect above. Note that all three cases are disjoint. Initially as a base case $dp[leaf][2]$ is $1$ and all other values zero. To compute the dp value of a node, we iterate through its direct children. If we choose to include the child in the same partition, there are $dp[child][1] + dp[child][2]$ ways to choose this. Otherwise, if the child is in a different partition, then there are $dp[child][0] + dp[child][2]$ to choose this. See the attached code for more details on how to compute the transitions. The final answer is $dp[0][0] + dp[0][2]$",
    "code": "/**\n * code generated by JHelper\n * More info: https://github.com/AlexeyDmitriev/JHelper\n * @author Azat Ismagilov\n */\n\n\n#include <fstream>\n\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <numeric>\n\n\n#define int long long\n#define fs first\n#define sc second\n#define pb push_back\n#define ppb pop_back\n#define pf push_front\n#define ppf pop_front\n#define mp make_pair\n#define len(v) ((int)v.size())\n#define vc vector\n#define pr pair\n#define all(v) v.begin(), v.end()\n//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native\")\n//#pragma GCC optimize(\"unroll-loops\")\n\n\nusing namespace std;\n\n\ntemplate<typename T, typename U>\ninline ostream &operator<<(ostream &_out, const pair<T, U> &_p) {\n    _out << _p.first << ' ' << _p.second;\n    return _out;\n}\n\n\ntemplate<typename T, typename U>\ninline istream &operator>>(istream &_in, pair<T, U> &_p) {\n    _in >> _p.first >> _p.second;\n    return _in;\n}\n\n\ntemplate<typename T>\ninline ostream &operator<<(ostream &_out, const vector<T> &_v) {\n    if (_v.empty()) { return _out; }\n    _out << _v.front();\n    for (auto _it = ++_v.begin(); _it != _v.end(); ++_it) { _out << ' ' << *_it; }\n    return _out;\n}\n\n\ntemplate<typename T>\ninline istream &operator>>(istream &_in, vector<T> &_v) {\n    for (auto &_i : _v) { _in >> _i; }\n    return _in;\n}\n\n\nconst int MAXN = 2e5;\nconst int INF = 1e9;\nconst int MOD = 998244353;\n\n\nint sum(int a, int b) {\n    if (a + b >= MOD) {\n        return a + b - MOD;\n    }\n    return a + b;\n}\n\n\nint mul(int a, int b) {\n    if (a * b >= MOD) {\n        return (a * b) % MOD;\n    }\n    return a * b;\n}\n\n\nint sqr(int a) {\n    return (a * a) % MOD;\n}\n\n\nint bin_pow(int a, int b) {\n    if (b == 0) {\n        return 1;\n    }\n    if (b % 2) {\n        return mul(a, bin_pow(a, b - 1));\n    }\n    return sqr(bin_pow(a, b / 2));\n}\n\n\nvc<int> g[MAXN];\n\n\nclass FLeafPartition {\npublic:\n    void solve(std::istream &in, std::ostream &out) {\n        int n;\n        in >> n;\n        vc<int> p(n - 1);\n        for (int i = 0; i < n - 1; i++) {\n            in >> p[i];\n            p[i]--;\n            g[p[i]].pb(i + 1);\n        }\n        vc<vc<int>> dp(n, vc<int>(3));\n        for (int i = n - 1; i >= 0; i--) {\n            if (len(g[i]) > 0) {\n                dp[i][2] = 1;\n                for (auto v : g[i]) {\n                    dp[i][0] = sum(mul(sum(dp[i][0], dp[i][1]), sum(dp[v][0], dp[v][1])),\n                                   mul(dp[i][0], sum(dp[v][0], dp[v][2])));\n                    dp[i][1] = sum(mul(dp[i][2], sum(dp[v][0], dp[v][1])), mul(dp[i][1], sum(dp[v][0], dp[v][2])));\n                    dp[i][2] = mul(dp[i][2], sum(dp[v][0], dp[v][2]));\n                }\n            } else\n                dp[i][0] = 1;\n        }\n        out << sum(dp[0][0], dp[0][2]);\n    }\n};\n\n\n\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    FLeafPartition solver;\n    std::istream &in(std::cin);\n    std::ostream &out(std::cout);\n    solver.solve(in, out);\n    return 0;\n}",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1146",
    "index": "G",
    "title": "Zoning Restrictions",
    "statement": "You are planning to build housing on a street. There are $n$ spots available on the street on which you can build a house. The spots are labeled from $1$ to $n$ from left to right. In each spot, you can build a house with an integer height between $0$ and $h$.\n\nIn each spot, if a house has height $a$, you can gain $a^2$ dollars from it.\n\nThe city has $m$ zoning restrictions though. The $i$-th restriction says that if the tallest house from spots $l_i$ to $r_i$ is strictly more than $x_i$, you must pay a fine of $c_i$.\n\nYou would like to build houses to maximize your profit (sum of dollars gained minus fines). Determine the maximum profit possible.",
    "tutorial": "There are two different solutions. The first is min cut. Let's build the graph as follows: There is a source and sink. The source side represents things that are \"true\", and sink side represents things that are \"false\" There are $O(n*h)$ nodes $(i,j)$ for ($1 \\leq i \\leq n, 0 \\leq j \\leq h$) where $i$ is a spot and $j$ is the height. Node $(i,j)$ represents the condition \"the height at spot $i$ is at least $j$\". We can connect $(i,j) -> (i,j-1)$ with infinite capacity (since \"spot $i \\geq j$\" implies \"spot $i \\geq j-1$\"). This is needed to make sure that for every $i$, $(i,j) -> (i,j+1)$ is cut exactly once for some j (though it might not be needed in practice). We draw an edge from $(i,j) -> (i,j+1)$ with capacity $(h^2-j^2)$, meaning if $(i,j)$ is on true and $(i,j+1)$ is false, then we incur that cost. There are $m$ nodes for each restriction, representing true if this restriction is violated and false otherwise. Call the k-th such node $k$. We connect $k$ to the sink with cost $c_k$. We connect $(a, x_k)$ for ($l_k \\leq a \\leq r_k$) to $k$ with infinite capacity (since house has height $\\geq x_k$ in range implies restriction is violated). To get the answer, run max flow, and then subtract answer from $h^2n$. The max flow is bounded above by $h^2n$ and the number of nodes is $hn$ and edges is $hn+mn$, so by ford fulkerson, the worstcase running time is $O(h^2n(hn+mn))$, which is about $50^5$. We can speed it up slightly by using some rmq structure to have $hn+m$ edges rather than $hn+mn$ edges, but this optimization isn't necessary. The second approach is dp. Let $dp[i][j][k]$ be the max profit given we are only considering buildings $i..j$ and the heights are at most $k$. To compute this, let's iterate through some middle point $f$ between $i$ and $j$ as the tallest building and fix its height as $x$. We can compute which restrictions lie entirely in the interval that we violate and add the profit to our sum. Now, this splits into two problems $dp[i][f-1][x]$ and $dp[f+1][j][x]$, and the main observation is that these problems are now independent.",
    "code": "import java.io.OutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.PrintWriter;\nimport java.util.Arrays;\nimport java.io.BufferedWriter;\nimport java.util.InputMismatchException;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.Stream;\nimport java.io.Writer;\nimport java.io.OutputStreamWriter;\nimport java.io.InputStream;\n\n\n/**\n * Built using CHelper plug-in\n * Actual solution is at the top\n *\n * @author lewin\n */\npublic class Main {\n    public static void main(String[] args) {\n        InputStream inputStream = System.in;\n        OutputStream outputStream = System.out;\n        InputReader in = new InputReader(inputStream);\n        OutputWriter out = new OutputWriter(outputStream);\n        ZoningRestrictions solver = new ZoningRestrictions();\n        solver.solve(1, in, out);\n        out.close();\n    }\n\n\n    static class ZoningRestrictions {\n        int INF = 1 << 29;\n        int nnodes;\n        int n;\n        int h;\n        int m;\n        int[] l;\n        int[] r;\n        int[] x;\n        int[] c;\n        int SOURCE;\n        int SINK;\n\n\n        int getPositionNode(int i, int j) {\n            if (j == 0) return SOURCE;\n            if (j >= h + 1) return SINK;\n            return j * n + i;\n        }\n\n\n        int getRestrictionNode(int x) {\n            return nnodes - 3 - x;\n        }\n\n\n        public void solve(int testNumber, InputReader in, OutputWriter out) {\n            n = in.nextInt();\n            h = in.nextInt();\n            m = in.nextInt();\n            l = new int[m];\n            r = new int[m];\n            x = new int[m];\n            c = new int[m];\n            for (int i = 0; i < m; i++) {\n                l[i] = in.nextInt() - 1;\n                r[i] = in.nextInt() - 1;\n                x[i] = in.nextInt();\n                c[i] = in.nextInt();\n            }\n\n\n            nnodes = n * (h + 1) + m + 2;\n            SOURCE = nnodes - 1;\n            SINK = nnodes - 2;\n            List<MaxFlowDinic.Edge>[] gg = LUtils.genArrayList(nnodes);\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j <= h; j++) {\n                    int a1 = getPositionNode(i, j), a2 = getPositionNode(i, j + 1);\n                    MaxFlowDinic.addEdge(gg, a2, a1, INF); // maybe not needed...\n                    MaxFlowDinic.addEdge(gg, a1, a2, h * h - j * j);\n                }\n            }\n\n\n            for (int i = 0; i < m; i++) {\n                int cpos = getRestrictionNode(i);\n                MaxFlowDinic.addEdge(gg, cpos, SINK, c[i]);\n                for (int j = l[i]; j <= r[i]; j++) { // can reduce to constant edges if we add log(n)*n*h nodes\n                    MaxFlowDinic.addEdge(gg, getPositionNode(j, x[i] + 1), cpos, INF);\n                }\n            }\n\n\n            out.println(h * h * n - MaxFlowDinic.maxFlow(gg, SOURCE, SINK));\n\n\n        }\n\n\n    }\n\n\n    static class InputReader {\n        private InputStream stream;\n        private byte[] buf = new byte[1 << 16];\n        private int curChar;\n        private int numChars;\n\n\n        public InputReader(InputStream stream) {\n            this.stream = stream;\n        }\n\n\n        public int read() {\n            if (this.numChars == -1) {\n                throw new InputMismatchException();\n            } else {\n                if (this.curChar >= this.numChars) {\n                    this.curChar = 0;\n\n\n                    try {\n                        this.numChars = this.stream.read(this.buf);\n                    } catch (IOException var2) {\n                        throw new InputMismatchException();\n                    }\n\n\n                    if (this.numChars <= 0) {\n                        return -1;\n                    }\n                }\n\n\n                return this.buf[this.curChar++];\n            }\n        }\n\n\n        public int nextInt() {\n            int c;\n            for (c = this.read(); isSpaceChar(c); c = this.read()) {\n                ;\n            }\n\n\n            byte sgn = 1;\n            if (c == 45) {\n                sgn = -1;\n                c = this.read();\n            }\n\n\n            int res = 0;\n\n\n            while (c >= 48 && c <= 57) {\n                res *= 10;\n                res += c - 48;\n                c = this.read();\n                if (isSpaceChar(c)) {\n                    return res * sgn;\n                }\n            }\n\n\n            throw new InputMismatchException();\n        }\n\n\n        public static boolean isSpaceChar(int c) {\n            return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;\n        }\n\n\n    }\n\n\n    static class MaxFlowDinic {\n        public static void addEdge(List<MaxFlowDinic.Edge>[] graph, int s, int t, int cap) {\n            graph[s].add(new MaxFlowDinic.Edge(t, graph[t].size(), cap));\n            graph[t].add(new MaxFlowDinic.Edge(s, graph[s].size() - 1, 0));\n        }\n\n\n        static boolean dinicBfs(List<MaxFlowDinic.Edge>[] graph, int src, int dest, int[] dist) {\n            Arrays.fill(dist, -1);\n            dist[src] = 0;\n            int[] Q = new int[graph.length];\n            int sizeQ = 0;\n            Q[sizeQ++] = src;\n            for (int i = 0; i < sizeQ; i++) {\n                int u = Q[i];\n                for (MaxFlowDinic.Edge e : graph[u]) {\n                    if (dist[e.t] < 0 && e.f < e.cap) {\n                        dist[e.t] = dist[u] + 1;\n                        Q[sizeQ++] = e.t;\n                    }\n                }\n            }\n            return dist[dest] >= 0;\n        }\n\n\n        static int dinicDfs(List<MaxFlowDinic.Edge>[] graph, int[] ptr, int[] dist, int dest, int u, int f) {\n            if (u == dest)\n                return f;\n            for (; ptr[u] < graph[u].size(); ++ptr[u]) {\n                MaxFlowDinic.Edge e = graph[u].get(ptr[u]);\n                if (dist[e.t] == dist[u] + 1 && e.f < e.cap) {\n                    int df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(f, e.cap - e.f));\n                    if (df > 0) {\n                        e.f += df;\n                        graph[e.t].get(e.rev).f -= df;\n                        return df;\n                    }\n                }\n            }\n            return 0;\n        }\n\n\n        public static int maxFlow(List<MaxFlowDinic.Edge>[] graph, int src, int dest) {\n            int flow = 0;\n            int[] dist = new int[graph.length];\n            while (dinicBfs(graph, src, dest, dist)) {\n                int[] ptr = new int[graph.length];\n                while (true) {\n                    int df = dinicDfs(graph, ptr, dist, dest, src, Integer.MAX_VALUE);\n                    if (df == 0)\n                        break;\n                    flow += df;\n                }\n            }\n            return flow;\n        }\n\n\n        public static class Edge {\n            public int t;\n            public int rev;\n            public int cap;\n            public int f;\n            public int idx;\n\n\n            public Edge(int t, int rev, int cap) {\n                this.t = t;\n                this.rev = rev;\n                this.cap = cap;\n            }\n\n\n            public Edge(int t, int rev, int cap, int idx) {\n                this.t = t;\n                this.rev = rev;\n                this.cap = cap;\n                this.idx = idx;\n            }\n\n\n        }\n\n\n    }\n\n\n    static class OutputWriter {\n        private final PrintWriter writer;\n\n\n        public OutputWriter(OutputStream outputStream) {\n            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));\n        }\n\n\n        public OutputWriter(Writer writer) {\n            this.writer = new PrintWriter(writer);\n        }\n\n\n        public void close() {\n            writer.close();\n        }\n\n\n        public void println(int i) {\n            writer.println(i);\n        }\n\n\n    }\n\n\n    static class LUtils {\n        public static <E> List<E>[] genArrayList(int size) {\n            return Stream.generate(ArrayList::new).limit(size).toArray(List[]::new);\n        }\n\n\n    }\n}",
    "tags": [
      "dp",
      "flows",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1146",
    "index": "H",
    "title": "Satanic Panic",
    "statement": "You are given a set of $n$ points in a 2D plane. No three points are collinear.\n\nA pentagram is a set of $5$ points $A,B,C,D,E$ that can be arranged as follows. Note the length of the line segments don't matter, only that those particular intersections exist.\n\nCount the number of ways to choose $5$ points from the given set that form a pentagram.",
    "tutorial": "Originally, I only had an $O(n^4)$ solution, but [user:y0105w49] recognized an easy solution with bitsets and helped me find an $O(n^3)$ solution instead. We do this by counting out bad configurations. There are initially $\\binom{n}{5}$ tuples of $5$ points, and we want to subtract out bad configurations. There are two classes of bad configurations. One is a point in a convex quadrilateral. The other is a pair of points inside a triangle. If we look at the first class of bad configurations, we can notice it has two instances of \"point in a triangle\", and if we look at the second class, it has four instances of \"point in a triangle\". See the following image for more details: Let's precompute for each number $i$, the number of triangles from the chosen set that contains $i$ points inside its interior. Let this number be $f_i$. This can be found using bitsets in $O(n^4 / 64)$ time, or some other geometric method in $O(n^3)$ time. First, we can subtract out $\\sum i\\cdot f_i\\cdot(n-4) / 2$. This removes subtracts all instances of the first class of bad configuration, but double subtracts instances of the second class of bad configurations. To fix that, we can add back $\\sum \\binom{i}{2} f_i$. The final formulas only take $O(n)$ time to evaluate, so the time is mostly spent computing the $f$ values which is $O(n^3)$ time. There is also another approach using some angle sweeps that I found later (though a bit harder to explain and to implement). The main idea is to fix the bottom point of the pentagram as well as the third and fourth points. Then, it reduces to counting the number of points that lie in some intersection of half planes. To do it efficiently, if we fix the first and third points, then we can do an angle sweep to efficiently count the number of points that could be the second point as we are iterating through the fourth point (and symmetrically we can do this to count the fifth point and multiply the two together). We can precompute these numbers to get a runtime of $O(n^3 log n)$. A third solution from Scott: the goal is to find the number of convex pentagons. We will do this through constructive DP. Take all directed segments between points and sort them by angle. Then, maintain array $dp[i][j][k]$, the number of polylines that start at vertex 𝑖, end at vertex 𝑗, contain 𝑘 segments, and only make clockwise turns. Loop over each directed segment in order and update the DP array accordingly. Each pentagon has exactly one traversal that satisfies the above constraints, so the answer is just the sum of all $dp[i][i][5]$.",
    "code": "#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <algorithm>\n#include <complex>\nusing namespace std;\n\n\n#define FR(i, a, b) for(int i = (a); i < (b); ++i)\n#define FOR(i, n) FR(i, 0, n)\n#define MP make_pair\n#define A first\n#define B second\n\n\ntypedef long long ll;\ntypedef complex<ll> pnt;\n\n\nconst int MAXN = 400;\n\n\n#define X real\n#define Y imag\n\n\npnt lis[MAXN];\nint n;\nint num[MAXN][MAXN];\nint ans[MAXN];\n\n\nll cross(pnt a, pnt b) {\n  return imag(conj(a) * b);\n}\n\n\npnt getPoint() {\n  int x, y;\n  scanf(\"%d%d\", &x, &y);\n  return pnt(x, y);\n}\n\n\nint below(int i, int j) {\n  return (X(lis[i]) == X(lis[j])) && (Y(lis[i]) < Y(lis[j]));\n}\n\n\nint betweenBelow(int i, int j, int x) {\n  if (X(lis[i]) < X(lis[j])) {\n    return X(lis[i]) < X(lis[x])  && X(lis[x]) < X(lis[j]) &&\n      cross(lis[j] - lis[i], lis[x] - lis[i]) < 0;\n  } else {\n    return X(lis[j]) < X(lis[x])  && X(lis[x]) < X(lis[i]) &&\n      cross(lis[i] - lis[j], lis[x] - lis[j]) < 0;\n  }\n}\n\n\nint main() {\n  scanf(\"%d\", &n);\n  FOR(i, n) {\n    lis[i] = getPoint();\n  }\n\n\n  memset(num, 0, sizeof(num));\n  FOR(i, n) {\n    FOR(j, n) if(X(lis[i]) < X(lis[j])){\n      FOR(k, n) if(k != i && k != j) {\n        if(below(k, i)) num[i][j]++;\n        if(below(k, j)) num[i][j]++;\n        if(betweenBelow(i, j, k)) {\n          num[i][j] += 2;\n        }\n      }  \n      num[j][i] = -num[i][j];\n    }\n  }\n  \n  memset(ans, 0, sizeof(ans));\n  FOR(i, n) FOR(j, i) FOR(k, j) {\n    int temp = abs(num[i][j] + num[j][k] + num[k][i]) / 2;\n    temp -= betweenBelow(i, j, k);\n    temp -= betweenBelow(j, k, i);\n    temp -= betweenBelow(k, i, j);\n    ans[temp]++; \n  }\n\n\n  ll x = (ll) n * (n - 1) * (n - 2) * (n - 3) * (n - 4) / 120;\n\n\n  ll r = 0;\n  FOR(i, n - 2)\n    r -= (ll) ans[i] * i * (n - 4);\n  x += r/2;\n  FOR(i, n - 2)\n    x += (ll) i * (i - 1) / 2 * ans[i];\n  printf(\"%lld\n\", x);\n\n\n  return 0;\n}",
    "tags": [
      "dp",
      "geometry"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1147",
    "index": "A",
    "title": "Hide and Seek",
    "statement": "Alice and Bob are playing a game on a line with $n$ cells. There are $n$ cells labeled from $1$ through $n$. For each $i$ from $1$ to $n-1$, cells $i$ and $i+1$ are adjacent.\n\nAlice initially has a token on some cell on the line, and Bob tries to guess where it is.\n\nBob guesses a sequence of line cell numbers $x_1, x_2, \\ldots, x_k$ in order. In the $i$-th question, Bob asks Alice if her token is currently on cell $x_i$. That is, Alice can answer either \"YES\" or \"NO\" to each Bob's question.\n\n\\textbf{At most one time} in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some \\textbf{adjacent} cell. Alice acted in such a way that she was able to answer \"NO\" to \\textbf{all} of Bob's questions.\n\nNote that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.\n\nYou are given $n$ and Bob's questions $x_1, \\ldots, x_k$. You would like to count the number of scenarios that let Alice answer \"NO\" to all of Bob's questions.\n\nLet $(a,b)$ denote a scenario where Alice starts at cell $a$ and ends at cell $b$. Two scenarios $(a_i, b_i)$ and $(a_j, b_j)$ are different if $a_i \\neq a_j$ or $b_i \\neq b_j$.",
    "tutorial": "Another way to phrase this problem is to count the number of ordered pairs $(p,q)$ that satisfy the following $|p-q| \\leq 1$ There exists a number $i$ such that p doesn't appear in $x[0\\ldots i]$ and $q$ doesn't appear in $x[i+1\\ldots n]$. There are only $O(n)$ pairs that satisfy the first condition, so we can loop over all these pairs and try to efficiently check the second condition. If $p=q$, this pair is valid if $p$ doesn't appear in $x$, so we can just check this for all $1\\ldots n$ directly with just one sweep through $x$. For $p,q$ that differ by exactly one, we can check that the first occurrence of $p$ occurs after the last occurrence of $q$. This is because we can start at $p$, wait until the last question about $q$ has been asked, and then swap to $p$. This is guaranteed to avoid all of Bob's questions. To answer this question efficiently, let's precompute the first and last occurrence of each number. This can be done by sweeping through the array once. Thus, checking if the condition is satisfied is just checking that $first[p] > last[q]$. The total time complexity is $O(k)$ for pre-computation, and $O(n)$ for answering all the questions.",
    "code": "/**\n * code generated by JHelper\n * More info: https://github.com/AlexeyDmitriev/JHelper\n * @author Azat Ismagilov\n */\n\n\n#include <fstream>\n\n\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <numeric>\n\n\n#define int long long\n#define fs first\n#define sc second\n#define pb push_back\n#define ppb pop_back\n#define pf push_front\n#define ppf pop_front\n#define mp make_pair\n#define len(v) ((int)v.size())\n#define vc vector\n#define pr pair\n#define all(v) v.begin(), v.end()\n//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,tune=native\")\n//#pragma GCC optimize(\"unroll-loops\")\n\n\nusing namespace std;\n\n\ntemplate<typename T, typename U>\ninline ostream &operator<<(ostream &_out, const pair<T, U> &_p) {\n    _out << _p.first << ' ' << _p.second;\n    return _out;\n}\n\n\ntemplate<typename T, typename U>\ninline istream &operator>>(istream &_in, pair<T, U> &_p) {\n    _in >> _p.first >> _p.second;\n    return _in;\n}\n\n\ntemplate<typename T>\ninline ostream &operator<<(ostream &_out, const vector<T> &_v) {\n    if (_v.empty()) { return _out; }\n    _out << _v.front();\n    for (auto _it = ++_v.begin(); _it != _v.end(); ++_it) { _out << ' ' << *_it; }\n    return _out;\n}\n\n\ntemplate<typename T>\ninline istream &operator>>(istream &_in, vector<T> &_v) {\n    for (auto &_i : _v) { _in >> _i; }\n    return _in;\n}\n\n\nconst int MAXN = 1e5;\nconst int INF = 1e9;\nconst int MOD = 1e9 + 7;\n\n\nclass Hideandseek {\npublic:\n    void solve(std::istream &in, std::ostream &out) {\n        int n, k;\n        in >> n >> k;\n        vc<int> x(k);\n        in >> x;\n        vc<int> firsts(n + 1, k), lasts(n + 1, -1);\n        for (int i = 1; i <= k; i++) {\n            lasts[x[i - 1]] = i;\n        }\n        for (int i = k; i >= 1; i--) {\n            firsts[x[i - 1]] = i;\n        }\n        int ans = 0;\n        for (int i = 1; i <= n; i++) {\n            for (int j = max(i - 1, 1ll); j <= min(n, i + 1); j++)\n                if (j == i) {\n                    if (lasts[i] == -1)\n                        ans++;\n                } else {\n                    ans += (firsts[j] - lasts[i]) >= 0;\n                    //out << i << ' ' << j << ' ' << firsts[i] << ' ' << lasts[j] << endl;\n                }\n        }\n        out << ans;\n    }\n};\n\n\n\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    Hideandseek solver;\n    std::istream &in(std::cin);\n    std::ostream &out(std::cout);\n    solver.solve(in, out);\n    return 0;\n}",
    "tags": [
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1147",
    "index": "B",
    "title": "Chladni Figure",
    "statement": "Inaka has a disc, the circumference of which is $n$ units. The circumference is equally divided by $n$ points numbered clockwise from $1$ to $n$, such that points $i$ and $i + 1$ ($1 \\leq i < n$) are adjacent, and so are points $n$ and $1$.\n\nThere are $m$ straight segments on the disc, the endpoints of which are all among the aforementioned $n$ points.\n\nInaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $k$ ($1 \\leq k < n$), such that if all segments are rotated clockwise around the center of the circle by $k$ units, the new image will be the same as the original one.",
    "tutorial": "Let's brute force the value of $k$ and check if it's possible to rotate the image by $k$ to get the same image. We can do this by iterating through all segments $(a,b)$, and checking that $(a+k,b+k)$ is a segment (the endpoints taken modulo $n$ if needed). This gives an $O(nm)$ solution, however, you can notice that we only need to check divisors of $n$ rather than all values from $1$ to $n$. This is because the set of segments $(a,b), (a+k,b+k), (a+2k,b+2k), \\ldots$ is exactly equal to $(a,b), (a+\\gcd(n,k), b+\\gcd(n,k)), (a+2\\gcd(n,k), b+2\\gcd(n,k)), \\ldots$. Thus, this take $O(m \\cdot d(n))$, where $d(n)$ denotes the number of divisors of $n$, which is fast enough to pass this problem. There is also a faster linear time solution. We can reduce this to a problem of finding the largest period of a string. For every point, we can sort the length of the segments starting from that point (length in this case refers to clockwise distance). We also add some null character to denote a point. For instance, the first sample case's string might start like $2, -1, -1, 4, 8, 10, -1, \\ldots$ that represent the points from $1$ to $3$. Such a string can be computed in $O(m \\log m)$ time. Then, after finding this string, we just want to check the period is bigger than $1$. Let $w$ be the length of the string. We can find this by concatenating the string to itself, then use z-algorithm to check if there is any is any index $i$ from $1$ to $w-1$ that is at least $w$.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\nint n,m;\nvector<pair<int,int> > s;\nbool test(int k)\n{\n    if (k==n)\n    return 0;\n    vector<pair<int,int> > cur;\n    for (auto p:s)\n    {\n        p.first=(p.first+k)%n;\n        p.second=(p.second+k)%n;\n        if (p.first>p.second)\n        swap(p.first,p.second);\n        cur.push_back(p);\n    }\n    sort(cur.begin(),cur.end());\n    return (cur==s);\n}\nint main()\n{\n    scanf(\"%d%d\",&n,&m);\n    while (m--)\n    {\n        int a,b;\n        scanf(\"%d%d\",&a,&b);\n        a--;\n        b--;\n        if (a>b)\n        swap(a,b);\n        s.push_back({a,b});\n    }\n    sort(s.begin(),s.end());\n    for (int i=1;i*i<=n;i++)\n    {\n        if (n%i==0 && (test(i) || test(n/i)))\n        {\n            printf(\"Yes\");\n            return 0;\n        }\n    }\n    printf(\"No\");\n}",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1147",
    "index": "C",
    "title": "Thanos Nim",
    "statement": "Alice and Bob are playing a game with $n$ piles of stones. It is guaranteed that $n$ is an even number. The $i$-th pile has $a_i$ stones.\n\nAlice and Bob will play a game alternating turns with Alice going first.\n\nOn a player's turn, they must choose \\textbf{exactly} $\\frac{n}{2}$ nonempty piles and independently remove a positive number of stones from each of the chosen piles. They \\textbf{can} remove a \\textbf{different} number of stones from the piles in a single turn. The first player unable to make a move loses (when there are less than $\\frac{n}{2}$ nonempty piles).\n\nGiven the starting configuration, determine who will win the game.",
    "tutorial": "The main claim is that if a player is forced to reduce the minimum number of stones over all piles, then they lose. Intuitively, every time a player reduces the minimum, the other player has a move that doesn't reduce the minimum, and if a player isn't forced to reduce the minimum, they have a move that will force the other player to reduce the minimum. More formally, let $m$ be the minimum number of stones in a pile, and let $x$ be the number of piles with $m$ stones. Alice can win if and only if $x \\leq n/2$. Let's call the positions where Alice can win \"winning positions\", and all other positions \"losing positions\" To see why this works, we need to show from a winning position, we can reach some losing position, and if we are at a losing position, we can only reach winning positions. If we are at a winning position, there are at least $n/2$ piles that have strictly more than $m$ stones, so we can choose any arbitrary subset of them and reduce them to $m$ stones. This is now a losing position. If we are at a losing position, no matter what we do, we must include a pile of size $m$ in our chosen subset. If $m$ is zero, this means we have no available moves. Otherwise, the minimum will strictly decrease, but only at most $n/2$ piles (from the piles that we chose) can reach that new minimum. Thus, losing positions can only reach winning positions. The solution is then as follows. Find the min of the array and find the frequency of the min. Print \"Alice\" if the frequency is less than or equal to $n/2$, otherwise, print \"Bob\". The time complexity is $O(n)$. Alternatively, you can sort and check the index $0$ and index $n/2$ are the same for a short three line solution.",
    "code": "#include <iostream>\nusing namespace std;\nint main()\n{\n    int n,mn=1e9,cnt;\n    scanf(\"%d\",&n);\n    for (int i=0;i<n;i++)\n    {\n        int a;\n        scanf(\"%d\",&a);\n        if (a<mn)\n        {\n            mn=a;\n            cnt=0;\n        }\n        if (a==mn)\n        cnt++;\n    }\n    if (cnt>n/2)\n    printf(\"Bob\");\n    else\n    printf(\"Alice\");\n}",
    "tags": [
      "games"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1147",
    "index": "D",
    "title": "Palindrome XOR",
    "statement": "You are given a string $s$ consisting of characters \"1\", \"0\", and \"?\". The first character of $s$ is guaranteed to be \"1\". Let $m$ be the number of characters in $s$.\n\nCount the number of ways we can choose a pair of integers $a, b$ that satisfies the following:\n\n- $1 \\leq a < b < 2^m$\n- When written without leading zeros, the base-2 representations of $a$ and $b$ are both palindromes.\n- The base-2 representation of bitwise XOR of $a$ and $b$ matches the pattern $s$. We say that $t$ matches $s$ if the lengths of $t$ and $s$ are the same and for every $i$, the $i$-th character of $t$ is equal to the $i$-th character of $s$, or the $i$-th character of $s$ is \"?\".\n\nCompute this count modulo $998244353$.",
    "tutorial": "Since the leading character of $s$ is a \"1\", then that means $a < 2^{m-1}$ and $2^{m-1} \\leq b < 2^m$. Let's fix the length of $a$ as $k$. I'll describe a more general solution, so there might be simpler solutions that work for this specific problem. Let's make a graph with $n+k+2$ nodes. The first $n$ nodes represent the $n$ bits of $b$, and the next $k$ nodes represent the $k$ bits of $a$. The last two nodes represent a $0$ node and $1$ node (which we will explain later). We want to find the number of ways to color the graph with two colors $0$ and $1$ such that they satisfy some conditions. Let's draw two different types of edges $0$-edges and $1$-edges. If two nodes are connected by a $0$-edge, then that means they must be the same color. If two nodes are connected by a $1$-edge, then that means they must be a different color. We will draw some edges as follows: Draw a $1$ edge between the $0$ node and $1$ node to represent they must be different colors. Draw a $0$ edge between $b_i$ and $b_{n-i-1}$ to represent the palindrome conditions (similarly we can do this for $a$). For the $i$-th bit, if $s_i$ is \"1\", draw a $1$ edge between $a_i$ and $b_i$ (if $i > k$, we instead draw an edge from $b_i$ to $1$). If $s_i$ is \"0\", then draw a $0$ edge between $a_i$ and $b_i$. If $s_i$ is \"?\", then don't draw any edges, since there are no explicit constraints. Now, we want to count the number of valid colorings. We want to split the graph into a two colors, which is a bipartite graph. We want all edges that cross the bipartition to be $1$ edges and all edges within the same bipartition to be $0$ edges. To count this, we first collapse all connected components of $0$ edges, then check if the remaining $1$ edges form a bipartite graph. If there is a non-bipartite graph, return $0$ immediately, since this means it's impossible to fulfill the conditions. Otherwise, let $C$ be the number of connected components. We add $2^{C-1}$ to our answer. The reason we subtract $1$ is that the component containing the $0$ and $1$ node is fixed to be colored $0$, but for other components, we are free to color the components in either of two ways. There are $n$ different lengths to try, each of which take a linear amount of time to get the count, so the overall time complexity is $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n#define gcd(a, b) ((!a || !b) ? (a || b) : __gcd(a, b))\n\n\nusing namespace std;\n\n\ntypedef long long ll;\n\n\nmt19937 rnd(1);\n\n\nconst int N = 2e3 + 7;\n\n\nvector <pair <int, int> > g[N];\nint val[N];\n\n\nvoid add_edge(int a, int b, int c)\n{\n  g[a].push_back({b, c});\n  g[b].push_back({a, c});\n}\n\n\nvector <int> t;\n\n\nbool u[N];\n\n\nvoid dfs(int v)\n{\n  t.push_back(v);\n  u[v] = true;\n  for (auto c : g[v])\n  {\n    int to = c.first;\n    if (!u[to])\n    {\n      dfs(to);\n    }\n  }\n}\n\n\nconst int M = 998244353;\n\n\nbool check(int s, int col)\n{\n  u[s] = true;\n  val[s] = col;\n  for (auto c : g[s])\n  {\n    int to = c.first;\n    if (val[to] != -1 && (val[s] + c.second) % 2 != val[to])\n    {\n      return false;\n    }\n    if (!u[to])\n    {\n      if (!check(to, (val[s] + c.second) % 2))\n      {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n\nvoid solve()\n{\n  string s;\n  cin >> s;\n  reverse(s.begin(), s.end());\n  int n = (int) s.size();\n  int sum = 0;\n  for (int m = 1; m < n; m++)\n  {\n    vector <int> ind_a(n);\n    for (int j = 0; j < n; j++)\n    {\n      ind_a[j] = j;\n    }\n    vector <int> ind_b(m);\n    for (int j = 0; j < m; j++)\n    {\n      ind_b[j] = n + j;\n    }\n    for (int x = 0; x < n + m; x++)\n    {\n      val[x] = -1;\n      g[x].clear();\n    }\n    for (int i = 0; i < n; i++)\n    {\n      add_edge(ind_a[i], ind_a[n - 1 - i], 0);\n    }\n    for (int i = 0; i < m; i++)\n    {\n      add_edge(ind_b[i], ind_b[m - 1 - i], 0);\n    }\n    for (int i = 0; i < n; i++)\n    {\n      if (s[i] == '?') continue;\n      if (i < m)\n      {\n        add_edge(ind_a[i], ind_b[i], s[i] - '0');\n      }\n      else\n      {\n        val[ind_a[i]] = s[i] - '0';\n      }\n    }\n    val[ind_b.back()] = 1;\n    for (int i = 0; i < n + m; i++)\n    {\n      u[i] = false;\n    }\n    int ans = 1;\n    for (int i = 0; i < n + m; i++)\n    {\n      if (!u[i])\n      {\n        t.clear();\n        dfs(i);\n        int start = i;\n        int value = -1;\n        for (int x : t)\n        {\n          if (val[x] != -1)\n          {\n            start = x;\n            value = val[x];\n          }\n          u[x] = 0;\n        }\n        if (value != -1)\n        {\n          ans *= check(start, value);\n        }\n        else\n        {\n          ans *= (2 * check(start, 0));\n          ans %= M;\n        }\n      }\n    }\n    sum = (sum + ans) % M;\n  }\n  cout << sum << endl;\n}\n\n\nint main()\n{\n#ifdef ONPC\n  freopen(\"a.in\", \"r\", stdin);\n#endif\n  ios::sync_with_stdio(0);\n  cin.tie(0);\n  solve();",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1147",
    "index": "E",
    "title": "Rainbow Coins",
    "statement": "Carl has $n$ coins of various colors, and he would like to sort them into piles. The coins are labeled $1,2,\\ldots,n$, and each coin is exactly one of red, green, or blue. He would like to sort the coins into three different piles so one pile contains all red coins, one pile contains all green coins, and one pile contains all blue coins.\n\nUnfortunately, Carl is colorblind, so this task is impossible for him. Luckily, he has a friend who can take a pair of coins and tell Carl if they are the same color or not. Using his friend, Carl believes he can now sort the coins. The order of the piles doesn't matter, as long as all same colored coins are in the one pile, and no two different colored coins are in the same pile.\n\nHis friend will answer questions about multiple pairs of coins in batches, and will answer about all of those pairs in parallel. Each coin should be in at most one pair in each batch. The same coin can appear in different batches.\n\nCarl can use only $7$ batches. Help him find the piles of coins after sorting.",
    "tutorial": "Let's define a new question that takes a list of coins $t_1, t_2, \\ldots, t_k$, and returns the answers about all adjacent pairs of coins in this list (e.g. the answers to $(t_1, t_2), (t_2, t_3), (t_3, t_4), \\ldots$. We can do this in two questions, one question is $(t_1, t_2), (t_3, t_4), \\ldots,$ and the other is $(t_2,t_3), (t_4,t_5), \\ldots$, and we can interleave the results to get the answer for all adjacent pairs in order. We show how to use only three questions of this type to get the answer (so the total number of questions in the original problem is $6$). First, let's ask about all adjacent pairs in $1, 2, \\ldots, n$. This splits the coins into contiguous groups of the same color. Let's take some arbitrary representative from each group and put them in a line, so we now have a problem where all adjacent coins in the line are different colors. Now, we ask two more questions about adjacent pairs. One for coins $1,3,5,\\ldots$ and one for coins $2,4,6,\\ldots$. This is now enough to reconstruct the color of all the coins. WLOG, coin $1$ is red, and coin $2$ is blue. We know coin $3$ cannot be blue (since it must be different from coin $2$), and we compared it with coin $1$, so we know if it is either red or green. We can repeat this for all coins in sequence.",
    "code": "#include <bits/stdc++.h>\n#define gcd(a, b) ((!a || !b) ? (a || b) : __gcd(a, b))\n\n\nusing namespace std;\n\n\ntypedef long long ll;\n\n\nmt19937 rnd(1);\n\n\nstruct ev\n{\n  int a, b, eq;\n};\n\n\nint col[123456];\n\n\nvector <ev> ask(vector <pair <int, int> > e)\n{\n  if (e.empty()) return {};\n  cout << \"Q \" << e.size() << ' ';\n  string str = \"\";\n  for (auto c : e)\n  {\n    cout << c.first + 1 << ' ' << c.second + 1 << ' ';\n    str += (col[c.first] == col[c.second]) + '0';\n  }\n  cout << endl;\n  string s;\n#ifdef ONPC\n  s = str;\n#else\n  cin >> s;\n#endif\n  vector <ev> q;\n  for (int i = 0; i < (int) e.size(); i++)\n  {\n    q.push_back({e[i].first, e[i].second, s[i] - '0'});\n  }\n  return q;\n}\n\n\nvoid solve()\n{\n  int t = 1;\n  cin >> t;\n  while (t--)\n  {\n    int n = 10;\n    cin >> n;\n    for (int i = 0; i < n; i++)\n    {\n      col[i] = rnd() % 3;\n    }\n    vector <int> x(n);\n    for (int i = 0; i < n; i++)\n    {\n      x[i] = (1 << 0) + (1 << 1) + (1 << 2);\n    }\n    x[0] = (1 << 0);\n    vector <ev> q;\n    vector <ev> temp;\n    auto flex = [&] (vector <int> arr)\n    {\n      vector <pair <int, int> > e;\n      for (int i= 0; i + 1 < (int) arr.size(); i += 2)\n      {\n        e.push_back({arr[i], arr[i + 1]});\n      }\n      temp = ask(e);\n      for (auto c : temp) q.push_back(c);\n      e.clear();\n      for (int i= 1; i + 1 < (int) arr.size(); i += 2)\n      {\n        e.push_back({arr[i], arr[i + 1]});\n      }\n      temp = ask(e);\n      for (auto c : temp) q.push_back(c);\n    };\n    vector <int> p(n);\n    for (int i = 0; i < n; i++) p[i] = i;\n    flex(p);\n    vector <int> kek;\n    for (auto c : q)\n    {\n      if (c.eq == 0)\n      {\n        kek.push_back(c.a);\n      }\n    }\n    sort(kek.begin(), kek.end());\n    kek.push_back(n-1);\n    kek.resize(unique(kek.begin(), kek.end()) - kek.begin());\n    vector <int> l, r;\n    for (int i = 0; i < (int) kek.size(); i++)\n    {\n      if (i % 2 == 0) l.push_back(kek[i]);\n      else r.push_back(kek[i]);\n    }\n    flex(l);\n    flex(r);\n    auto bunt = [&] ()\n    {\n      vector <vector <ev> > tupa_flex(n);\n      queue <int> que;\n      for (int i = 0; i < n; i++)\n      {\n        que.push(i);\n      }\n      for (auto c : q)\n      {\n        tupa_flex[c.a].push_back(c);\n        tupa_flex[c.b].push_back(c);\n      }\n      while (!que.empty())\n      {\n        int i = que.front();\n        que.pop();\n        for (auto c : tupa_flex[i])\n        {\n          int j = (c.a == i ? c.b : c.a);\n          if (c.eq)\n          {\n            if ((x[i] & x[j]) != x[j])\n            {\n              x[j] = (x[i] & x[j]);\n              que.push(j);\n            }\n          }\n          else\n          {\n            if (__builtin_popcount(x[i]) == 1)\n            {\n              if ((~x[i] & x[j]) != x[j])\n              {\n                x[j] = (~x[i] & x[j]);\n                que.push(j);\n              }\n            }\n          }\n        }\n      }\n      while (true)\n      {\n        auto was = x;\n        for (auto c : q)\n        {\n          if (c.eq)\n          {\n            x[c.a] &= x[c.b];\n            x[c.b] &= x[c.a];\n          }\n          else\n          {\n            if (__builtin_popcount(x[c.a]) == 1) x[c.b] &= ~x[c.a];\n            if (__builtin_popcount(x[c.b]) == 1) x[c.a] &= ~x[c.b];\n          }\n        }\n        if (x == was) break;\n      }\n    };\n    bunt();\n    for (int i = 0; i < n; i++)\n    {\n      if (__builtin_popcount(x[i]) > 1)\n      {\n        x[i] = (x[i] & -x[i]);\n        break;\n      }\n    }\n    bunt();\n    vector <vector <int> > kok(8);\n    for (int i = 0; i < n; i++) kok[x[i]].push_back(i);\n    cout << \"A \" << kok[1 << 0].size() << ' ' << kok[1 << 1].size() << ' ' << kok[1 << 2].size() << endl;\n    for (int i = 0; i < 3; i++)\n    {\n      for (int x : kok[1 << i]) cout << x + 1 << ' ';\n      cout << endl;\n    }\n  }\n}\n\n\nint main()\n{\n#ifdef ONPC\n  //freopen(\"a.in\", \"r\", stdin);\n#endif\n  ios::sync_with_stdio(0);\n  cin.tie(0);\n  solve();\n}",
    "tags": [
      "interactive"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1147",
    "index": "F",
    "title": "Zigzag Game",
    "statement": "You are given a complete bipartite graph with $2n$ nodes, with $n$ nodes on each side of the bipartition. Nodes $1$ through $n$ are on one side of the bipartition, and nodes $n+1$ to $2n$ are on the other side. You are also given an $n \\times n$ matrix $a$ describing the edge weights. $a_{ij}$ denotes the weight of the edge between nodes $i$ and $j+n$. Each edge has a distinct weight.\n\nAlice and Bob are playing a game on this graph. First Alice chooses to play as either \"increasing\" or \"decreasing\" for herself, and Bob gets the other choice. Then she places a token on any node of the graph. Bob then moves the token along any edge incident to that node. They now take turns playing the following game, with Alice going first.\n\nThe current player must move the token from the current vertex to some adjacent unvisited vertex. Let $w$ be the last weight of the last edge that was traversed. The edge that is traversed must be strictly greater than $w$ if the player is playing as \"increasing\", otherwise, it must be strictly less. The first player unable to make a move loses.\n\nYou are given $n$ and the edge weights of the graph. You can choose to play as either Alice or Bob, and you will play against the judge. You must win all the games for your answer to be judged correct.",
    "tutorial": "I first got the idea for this problem from this problem: https://www.codechef.com/problems/HAMILG. There might be an easier version of the problem on a bipartite graph out there somewhere also. Anyways, the solution for the problem is conceptually simple. Find a matching of the graph, and then you can play according to the matching. You don't even need to remember which vertices you've seen before, since the main idea is if your opponent can make a move, then you can too. The same idea can be extended to this problem. The intuition is to find some matching to show that Bob can always win. It's not clear how to find such a matching directly, so let's look at what properties the matching needs. Let's call nodes $1$ to $n$ the \"left\" side of the bipartite graph and nodes $n+1$ to $2n$ the \"right\" side Without loss of generality, suppose Alice choose \"increasing\" and she placed her token somewhere on the left side. Now, let's consider what properties a matching needs. Let's take any two edges in our matching, one that connects nodes $(w,x)$ ($w$ is on the left, $x$ is on the right), and the other connects $(y,z)$ ($y$ is on the left, $z$ is on the right). We want it to be the case that if it is legal for Alice to move from $x$ to $y$, then it is legal for Bob to move from $y$ to $z$. This way, Bob always can respond by playing according to the matching. Let's see what this means in terms of edge weights. If Alice can move from $x$ to $y$, then that means $edge(x,y) > edge(w,x)$, since the last edge traversed was $(w,x)$ and Alice is increasing. We want it to be the case that $edge(x,y) > edge(w,x)$ implies that $edge(x,y) > edge(y,z)$. Thus, the matching is bad if and only if there are two edges in the matching $(w,x)$ and $(y,z)$ such that $edge(x,y) > edge(w,x)$ and $edge(x,y) < edge(y,z)$. We can solve this with stable marriage. We call the bad case an instability, which happens if $x$ prefers $y$ over $w$ and $y$ prefers $x$ over $z$. We can construct the preference list of the nodes as follows. For each node on the left side, create a preference list of nodes on the right in decreasing order of weight. For each node on the right side, create a preference list of nodes on the left in increasing order of weight. We now find any stable marriage in $O(n^2)$ time. It is guaranteed that one exists and has no instabilities. Thus, we've found a matching that guarantees Bob's win. As a followup, can you devise a strategy that guarantees Alice can beat Bob if Bob makes a non-optimal move?",
    "code": "#include <bits/stdc++.h>\n#define gcd(a, b) ((!a || !b) ? (a || b) : __gcd(a, b))\n\n\nusing namespace std;\n\n\ntypedef long long ll;\n\n\nmt19937 rnd(1);\nbool wPrefersM1OverM(const vector <vector <int> > &prefer, int w, int m, int m1)\n{\n  int n = (int) prefer.size() / 2;\n  // Check if w prefers m over her current engagment m1\n  for (int i = 0; i < n; i++)\n  {\n    // If m1 comes before m in lisr of w, then w prefers her\n    // cirrent engagement, don't do anything\n    if (prefer[w][i] == m1)\n      return true;\n\n\n    // If m cmes before m1 in w's list, then free her current\n    // engagement and engage her with m\n    if (prefer[w][i] == m)\n      return false;\n  }\n}\n\n\nvector <int> marriage(vector <vector <int> > prefer)\n{\n  int n = (int) prefer.size() / 2;\n  vector<int> wPartner(n, -1);\n  vector<bool> mFree(n);\n  // stores paing information.  The value of wPartner[i]\n  // indicates the partner assigned to woman N+i.  Note that\n  // the woman numbers between N and 2*N-1. The value -1\n  // indicates that (N+i)'th woman is free\n\n\n// An array to store availability of men.  If mFree[i] is\n// false, then man 'i' is free, otherwise engaged.\n\n\n// Initialize all men and women as free\n  int freeCount = n;\n\n\n// While there are free men\n  while (freeCount > 0)\n  {\n// Pick the first free man (we could pick any)\n    int m;\n    for (m = 0; m < n; m++)\n      if (mFree[m] == false)\n        break;\n\n\n// One by one go to all women according to m's preferences.\n// Here m is the picked free man\n    for (int i = 0; i < n && mFree[m] == false; i++)\n    {\n      int w = prefer[m][i];\n\n\n// The woman of preference is free, w and m become\n// partners (Note that the partnership maybe changed\n// later). So we can say they are engaged not married\n      if (wPartner[w - n] == -1)\n      {\n        wPartner[w - n] = m;\n        mFree[m] = true;\n        freeCount--;\n      } else  // If w is not free\n      {\n// Find current engagement of w\n        int m1 = wPartner[w - n];\n\n\n// If w prefers m over her current engagement m1,\n// then break the engagement between w and m1 and\n// engage m with w.\n        if (wPrefersM1OverM(prefer, w, m, m1) == false)\n        {\n          wPartner[w - n] = m;\n          mFree[m] = true;\n          mFree[m1] = false;\n        }\n      } // End of Else\n    } // End of the for loop that goes to all women in m's list\n  } // End of main while loop\n  return wPartner;\n}\n\n\nvoid solve()\n{\n  int t;\n  cin >> t;\n  while (t--)\n  {\n    int n;\n    cin >> n;\n    vector <vector <int> > a(n, vector <int> (n));\n    for (int i = 0; i < n; i++)\n    {\n      for (int j = 0; j < n; j++)\n      {\n        cin >> a[i][j];\n      }\n    }\n    cout << \"B\" << endl;\n    char move;\n    cin >> move;\n    int v;\n    cin >> v;\n    v--;\n    int kek = (move == 'D') ^ (v >= n) ^ 1;\n    vector <vector <int> > prefer;\n    for (int i = 0; i < n; i++)\n    {\n      vector <int> guys;\n      for (int j = 0; j < n; j++)\n      {\n        guys.push_back(n + j);\n      }\n      sort(guys.begin(), guys.end(), [&] (int x, int y)\n      {\n        if (kek)\n        {\n          return a[i][x - n] < a[i][y - n];\n        }\n        else\n        {\n          return a[i][x - n] > a[i][y - n];\n        }\n      });\n      prefer.push_back(guys);\n    }\n    for (int i = n; i < n + n; i++)\n    {\n      vector <int> guys;\n      for (int j = 0; j < n; j++)\n      {\n        guys.push_back(j);\n      }\n      sort(guys.begin(), guys.end(), [&] (int x, int y)\n      {\n        if (!kek)\n        {\n          return a[x][i - n] < a[y][i - n];\n        }\n        else\n        {\n          return a[x][i - n] > a[y][i - n];\n        }\n      });\n      prefer.push_back(guys);\n    }\n    /*\n    shuffle(p.begin(), p.end(), rnd);\n   bool ch = true;\n      while (ch)\n      {\n        ch = false;\n        vector<pair<int, int >> e;\n        for (int i = 0; i < n; i++)\n        {\n          for (int j = 0; j < n; j++)\n          {\n            if (i != j)\n              e.push_back({i, j});\n          }\n        }\n        shuffle(e.begin(), e.end(), rnd);\n        for (auto c : e)\n        {\n          int i = c.first, j = c.second;\n          if ((move == 'D') ^ (v >= n))\n          {\n            if (a[i][p[i]] > a[j][p[i]] && a[j][p[i]] > a[j][p[j]])\n            {\n              swap(p[i], p[j]);\n              ch = true;\n              //break;?\n            }\n          } else\n          {\n            if (a[i][p[i]] < a[j][p[i]] && a[j][p[i]] < a[j][p[j]])\n            {\n              swap(p[i], p[j]);\n              ch = true;\n              //break;?\n            }\n          }\n        }\n      }\n      */\n      vector <int> p = marriage(prefer);\n    while (true)\n    {\n      if (v >= n)\n      {\n        cout << p[v - n] + 1 << endl;\n      }\n      else\n      {\n        for (int i = 0; i < n; i++)\n        {\n          if (p[i] == v)\n          {\n            cout << n + i + 1 << endl;\n            break;\n          }\n        }\n      }\n      cin >> v;\n      if (v == -1)\n      {\n        break;\n      }\n      if (v == -2)\n      {\n        return;\n      }\n      v--;\n    }\n  }\n}\n\n\nint main()\n{\n#ifdef ONPC\n  //freopen(\"a.in\", \"r\", stdin);\n#endif\n  ios::sync_with_stdio(0);\n  cin.tie(0);\n  solve();\n}",
    "tags": [
      "games",
      "interactive"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1148",
    "index": "A",
    "title": "Another One Bites The Dust",
    "statement": "Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example \"baba\" and \"aba\" are good strings and \"abb\" is a bad string.\n\nYou have $a$ strings \"a\", $b$ strings \"b\" and $c$ strings \"ab\". You want to choose some subset of these strings and concatenate them in any arbitrarily order.\n\nWhat is the length of the longest good string you can obtain this way?",
    "tutorial": "The answer is $2 * c + min(a, b) + min(max(a, b), min(a, b) + 1)$. First, you can place all \"ab\" strings together. Then if there are more \"a\" strings than \"b\" strings, you can start adding in the end \"a\" and \"b\" strings one by one in an alternating order. If there are more \"b\" strings than \"a\" strings, you can do the same thing but add to the begin of the string.",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1148",
    "index": "B",
    "title": "Born This Way",
    "statement": "Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.\n\nThere are $n$ flights from A to B, they depart at time moments $a_1$, $a_2$, $a_3$, ..., $a_n$ and arrive at B $t_a$ moments later.\n\nThere are $m$ flights from B to C, they depart at time moments $b_1$, $b_2$, $b_3$, ..., $b_m$ and arrive at C $t_b$ moments later.\n\nThe connection time is negligible, so one can use the $i$-th flight from A to B and the $j$-th flight from B to C if and only if $b_j \\ge a_i + t_a$.\n\nYou can cancel at most $k$ flights. If you cancel a flight, Arkady can not use it.\n\nArkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel $k$ flights. If you can cancel $k$ or less flights in such a way that it is not possible to reach C at all, print $-1$.",
    "tutorial": "If $k \\geq n$, we can cancel all flights between A and B, and Arkady won't be able to get to C, so answer will be equal to $-1$. Otherwise, $k < n$. If the subset of canceled flights is chosen, the Arkady's strategy is clear: use the earliest available flight from A to B, arrive to B at some time moment $t$ and choose the earliest not canceled flight from B to C with a departure time moment greater or equal than $t$. Suppose we have chosen $x$ - a number of canceled flights between A and B. No matter what subset of flights will be cancelled between B and C, we should cancel the first $x$ flights from A to B. Now we know the exact moment of the Arkady's arrival to B - it is equal to $a_{x+1} + t_a$. Now our optimal strategy is to cancel the first $k-x$ flights between B and C, which Arkady can use. If there is no flights remaining, the answer is $-1$. Otherwise, Arkady will be in C at the $b_j + t_b$-th time moment, where $j$ is the index of the earliest flight, which Arkady can use. $j$ is equal to $pos + (k - x)$, where $pos$ is index of the first flight from B to C, which departure time moment is greater or equal than $a_{x+1} + t_a$. Now we can just iterate through all possible $x$ and calculate the biggest time moment. Since array $b$ is sorted, you can find $pos$ using binary search. The complexity of this solution is $O(n \\log n)$. Also the array of $a_{x + 1} + t_a$ values is sorted too, so you can use two-pointers method. This solution will work with $O(n)$ complexity.",
    "tags": [
      "binary search",
      "brute force",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1148",
    "index": "C",
    "title": "Crazy Diamond",
    "statement": "You are given a permutation $p$ of integers from $1$ to $n$, where $n$ is an even number.\n\nYour goal is to sort the permutation. To do so, you can perform zero or more operations of the following type:\n\n- take two indices $i$ and $j$ such that $2 \\cdot |i - j| \\geq n$ and swap $p_i$ and $p_j$.\n\nThere is \\textbf{no need to minimize} the number of operations, however you should use no more than $5 \\cdot n$ operations. One can show that it is always possible to do that.",
    "tutorial": "The problem can be solved in $4n$ swaps in total in the worst case (might be there is a more optimal solution, but it wasn't required). Let's go from left to right through the array. Suppose our current position is $i$ and position of the number $i$ is $j$. If $i \\ne j$, we want to swap them. If $|i - j| \\cdot 2 \\geq n$, you can just swap(i, j). If $\\frac{n}{2} \\leq i - 1$, than you can do swap(i, 1), swap(1, j), swap(i, 1). If $\\frac{n}{2} \\leq n - j$, than you can do swap(i, n), swap(j, n), swap(i, n). In the last case $\\frac{n}{2} \\leq j - 1$ and $\\frac{n}{2} \\leq n - i$ and so you do $5$ swaps: swap(i, n), swap(n, 1), swap(1, j), swap(1, n), swap(i, n). One can be see, that the last case happens at most $\\frac{n}{2}$ times, since when $i \\geq \\frac{n}{2} + 1$ you only need $3$ swaps or less. And so in total it's no more than $5 \\cdot \\frac{n}{2} + 3 \\cdot \\frac{n}{2} = 4 n$ swaps.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1148",
    "index": "D",
    "title": "Dirty Deeds Done Dirt Cheap",
    "statement": "You are given $n$ pairs of integers $(a_1, b_1), (a_2, b_2), \\ldots, (a_n, b_n)$. All of the integers in the pairs are distinct and are in the range from $1$ to $2 \\cdot n$ inclusive.\n\nLet's call a sequence of integers $x_1, x_2, \\ldots, x_{2k}$ good if either\n\n- $x_1 < x_2 > x_3 < \\ldots < x_{2k-2} > x_{2k-1} < x_{2k}$, or\n- $x_1 > x_2 < x_3 > \\ldots > x_{2k-2} < x_{2k-1} > x_{2k}$.\n\nYou need to choose a subset of distinct indices $i_1, i_2, \\ldots, i_t$ and \\textbf{their order} in a way that if you write down all numbers from the pairs in a single sequence (the sequence would be $a_{i_1}, b_{i_1}, a_{i_2}, b_{i_2}, \\ldots, a_{i_t}, b_{i_t}$), this sequence is good.\n\nWhat is the largest subset of indices you can choose? You also need to construct the corresponding index sequence $i_1, i_2, \\ldots, i_t$.",
    "tutorial": "First notice, that there are two types of pairs: one with $a_i < b_i$ and another one with $a_i > b_i$. Note, that we can't form an answer with pairs of different types. Now let's notice that we can take all pairs of fixed type. Suppose the type is $a_i < b_i$. Then sort pairs by their $a_i$ in the decreasing order and that is the answer. For type $a_i > b_i$ let's sort them by $b_i$ in increasing order. Just select the longest of two answers.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1148",
    "index": "E",
    "title": "Earth Wind and Fire",
    "statement": "There are $n$ stones arranged on an axis. Initially the $i$-th stone is located at the coordinate $s_i$. There may be more than one stone in a single place.\n\nYou can perform zero or more operations of the following type:\n\n- take two stones with indices $i$ and $j$ so that $s_i \\leq s_j$, choose an integer $d$ ($0 \\leq 2 \\cdot d \\leq s_j - s_i$), and replace the coordinate $s_i$ with $(s_i + d)$ and replace coordinate $s_j$ with $(s_j - d)$. In other words, draw stones closer to each other.\n\nYou want to move the stones so that they are located at positions $t_1, t_2, \\ldots, t_n$. The order of the stones is not important — you just want for the multiset of the stones resulting positions to be the same as the multiset of $t_1, t_2, \\ldots, t_n$.\n\nDetect whether it is possible to move the stones this way, and if yes, construct a way to do so. You don't need to minimize the number of moves.",
    "tutorial": "Consider original and target position of stones in sorted order. Note, that we can always construct an answer preserving the original stones order (suppose we have an answer which doesn't preserve the order. It will happen when there are two stones at the same spot, just move the other one). So now we simplified our problem - we want to move stone $s_i$ into $t_i$. So we now can compute $\\delta_i = t_i - s_i$ - the relative movement of each stone. To begin with, observe that if $\\sum \\delta_i \\ne 0$ there is no solution, since the operations we can use preserve the sum of the coordinates. However this is not enough, for example if $\\delta_1 < 0$ (you need to move to the left the leftmost stone), there is clearly no answer. The real condition is that elements $\\delta_i$ should form a \"balanced bracket sequence\", that is, the sum of every prefix of $\\delta_i$ must be $\\ge 0$. In this and only in this case we can match corresponding right-movements with left-movements. In order to construct the exact answer we can go from left to right maintaining the stack of not-yet-closed \"move-to-the right actions\", formally we will put on stack pairs (stone_index, steps_to_move). So when we see stone with $\\delta_i > 0$ we put it on the stack, and when we see stone with $\\delta_i < 0$ we match it with the stones on the stack, removing the elements from the stack if they have moved to the full extent.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1148",
    "index": "F",
    "title": "Foo Fighters",
    "statement": "You are given $n$ objects. Each object has two integer properties: $val_i$ — its price — and $mask_i$. It is guaranteed that the sum of all prices is initially non-zero.\n\nYou want to select a positive integer $s$. All objects will be modified after that. The $i$-th object will be modified using the following procedure:\n\n- Consider $mask_i$ and $s$ in binary notation,\n- Compute the bitwise AND of $s$ and $mask_i$ ($s \\,\\&\\, mask_i$),\n- If ($s \\,\\&\\, mask_i$) contains an odd number of ones, replace the $val_i$ with $-val_i$. Otherwise do nothing with the $i$-th object.\n\nYou need to find such an integer $s$ that when the modification above is done the sum of all prices changes sign (if it was negative, it should become positive, and vice-versa; it is not allowed for it to become zero). The absolute value of the sum can be arbitrary.",
    "tutorial": "Let's solve this problem using the induction method. Let's solve this problem for all objects with masks less than $2^{K}$. Base of the induction: $K = 1$, than we just can multiply price by $-1$, like adding a single bit into the answer, if the price has the same sign as the initial sum. Move: we solved the problem for all masks less than $2^{K - 1}$. Now take a look on all masks smaller than $2^{K}$ and not less than $2^{K - 1}$. If the sum of their prices has the same sign as the initial sum, than we add bit $K - 1$ into the answer and multiply all prices of object with this bit in the mask by $-1$. It's important to notice, that when we chose whether we need this bit we go only through numbers where this bit is the biggest one, but when we added it we need to recalculate prices for all object with this bit in the mask.",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1148",
    "index": "G",
    "title": "Gold Experience",
    "statement": "Consider an undirected graph $G$ with $n$ vertices. There is a value $a_i$ in each vertex.\n\nTwo vertices $i$ and $j$ are connected with an edge if and only if $gcd(a_i, a_j) > 1$, where $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\nConsider a set of vertices. Let's call a vertex in this set fair if it is connected with an edge with all other vertices in this set.\n\nYou need to find a set of $k$ vertices (where $k$ is a given integer, $2 \\cdot k \\le n$) where all vertices are fair or all vertices are not fair. One can show that such a set always exists.",
    "tutorial": "Firstly, let's discuss how to find the answer in $O(N^2)$ time. Let's assume $k$ is even. Pick any set on $k$ vertices. If it is a clique, just print it as an answer, if it is not, there must be two vertices in this set that don't share an edge. Just remove these two vertices and replace them with 2 arbitrary ones from the rest of the vertices. We can notice that if we remove $\\frac{k}{2}$ such pairs, then removed vertices will form a set where all vertices are not fair. If $k$ is odd, then the above algorithm has a problem, because we remove two vertices in one step. To fix it, we can find a triplet of vertices $a$, $b$, $c$ such that there is no edge between $a$ and $b$, and there is no edge between $b$, and $c$. Now, with this triplet we can get the set with odd size. If there are no such triplet, then, our graph has quite simple structure which we can handle separately. Now to the $O(N \\cdot Log \\cdot 2^8)$ solution. Assume we have a set of integers $a_1, a_2, \\ldots, a_n$ and an integer $x$. We want to find, for how many $a_i$ have $gcd(a_i, x) \\neq 1$. This can be done using inclusion-exclusion principle. Let $p_1, p_2, \\ldots, p_k$ be distinct prime divisors of $x$. At first, we want to count how many $a_i$ is divisible by $p_1, p_2, \\ldots, p_k$, but than $a_i$'s divisible by both $p_1, p_2$ are counted twice, so we subtract count of $a_i$ that is divisible by $p_1 \\cdot p_2$ and so on. We can maintain set $a_1, a_2, \\ldots, a_n$ and answer queries dynamically in $O(2^{NumberOfPrimeDivisors})$ time. This is the only place where we use the graph structure defined by the edge between two vertices $i$ and $j$ exists if only if $gcd(a_i, a_j) \\neq 1$. Like in $O(N^2)$ solution, let's find a triplet of vertices $a$, $b$, $c$ such that there is no edge between $a$ and $b$, and there is no edge between $b$ and $c$. Let's remove this triplet from the graph. Let $b$ be the number of vertices that are connected to all other $n - 3$ vertices. If $b \\geq k$ we can print any $k$ of them as a clique. Otherwise, let's remove all of these $b$ vertices. We can notice that remaining vertices plus removed triplet form an antifair set. Let's estimate size of this set: $S = (n - 3) - b + 3 = n - b$. Recall that $b \\le k$ and $2 \\cdot k \\leq n$, so we have $S = n - b \\geq k$. So, now we get an antifair set of size equal to $k$ or greater than $k$. Let's show that we always can construct an antifair set with size strictly equal to $k$. In the previous paragraph we have estimated the maximum size of an antifair set on vertices $1, 2, \\ldots, n - 3$. Let $f(R)$ be the maximum size of an antifair set on vertices with indices: $1, 2, \\ldots, R$. Let's find with binary search lowest integer $c$ such that $f(c - 1) + 3 < k$ and $f(c) + 3 \\geq k$. Let's look at the vertex $c$. The size of the maximal antifair set without it is $f(c - 1)$. The size of the maximal antifair set with it is $f(c)$. So among vertices $1, 2, \\ldots, c - 1$ there are exactly $f(c) - f(c - 1) - 1$ of them connected with all vertices from $1$ to $c - 1$ and not connected with the vertex $c$. It is easy to see, that we can delete any $f(c) - f(c - 1) - 2$ of them or less and the remaining set of vertices will still be antifair. With this observation we can achieve either set of size $k$ or set of size $k + 1$. In the first case, we just find the answer. In the second case, remember, that we have reserved triplet and can delete one of it's vertex to make the total size $k$.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1148",
    "index": "H",
    "title": "Holy Diver ",
    "statement": "You are given an array which is initially empty. You need to perform $n$ operations of the given format:\n\n- \"$a$ $l$ $r$ $k$\": append $a$ to the end of the array. After that count the number of integer pairs $x, y$ such that $l \\leq x \\leq y \\leq r$ and $\\operatorname{mex}(a_{x}, a_{x+1}, \\ldots, a_{y}) = k$.\n\nThe elements of the array are numerated from $1$ in the order they are added to the array.\n\nTo make this problem more tricky we don't say your real parameters of the queries. Instead your are given $a'$, $l'$, $r'$, $k'$. To get $a$, $l$, $r$, $k$ on the $i$-th operation you need to perform the following:\n\n- $a := (a' + lans) \\bmod(n + 1)$,\n- $l := (l' + lans) \\bmod{i} + 1$,\n- $r := (r' + lans) \\bmod{i} + 1$,\n- if $l > r$ swap $l$ and $r$,\n- $k := (k' + lans) \\bmod(n + 1)$,\n\nwhere $lans$ is the answer to the previous operation, initially $lans$ is equal to zero. $i$ is the id of the operation, operations are numbered from $1$.The $\\operatorname{mex}(S)$, where $S$ is a multiset of non-negative integers, is the smallest non-negative integer which does not appear in the set. For example, $\\operatorname{mex}(\\{2, 2, 3\\}) = 0$ and $\\operatorname{mex} (\\{0, 1, 4, 1, 6\\}) = 2$.",
    "tutorial": "First, let's try to solve it if we know the whole array initially. Let's move from the last element to the first. When we are in the element $i$ let's store all segments of right borders ($[r', r\"]$) in the set, so that segment $[i, r]$ have the same mex value for all $r' \\le r \\le r\"$. You can see that mex values in those segments are increasing from left to right, so you can recalculate those segments efficiently when you add another element from the left. How to do so? Suppose we added element $k$ on the left. Then we must remove the segment with mex $k$ and replace it (with possibly many) segments of greater mex, the last of those segments might get merge with the segment following the removed one. It's easy to see that we add/remove only $O(n)$ segments in total since each time we remove exactly once segment, but add quite a lot. Informally, we simply can't add too much segments each time, since all mex's are distinct at every moment. After that for each segment of the right borders we can compute when it was added to the set and when it was deleted. Then we can see it as a rectangle, where $x$ coordinates correspond to the left borders and $y$ coordinates correspond to the right borders. After that the problem is reduced to add value in the rectangle and compute the sum of values in the rectangle of a query. So after that you need to notice, that those rectangles lay like in different stripes of surface. So they don't have points with the same x coordinates from different rectangles. That's why you can say, that to count total area laying on a query rectangle, you just can keep a segment tree with operations: add number to the segment, count the sum of number on the segment. That's because there is only one rectangle intersecting your query, but not laying completely inside. So when you meet a rectangle during you scan line, you just add its width to the proper segment. Notice that there are actually $O(n)$ scan lines, because you need to keep them for every mex value. And for the query you need to get the state of your structure after some prefix of rectangles proceeded. They lay completely inside your query, so you need just to take the sum on the segment in your structure. Also there is one rectangle which can intersect you query, and you need to proceed it by hands. Another case is that in your set, when you proceed queries one by one, there are some current segment of mex, who was not deleted yet, so you need to take care about it too, because it can contain one segment with proper mex value for you query.",
    "tags": [
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1149",
    "index": "A",
    "title": "Prefix Sum Primes",
    "statement": "We're giving away nice huge bags containing number tiles! A bag we want to present to you contains $n$ tiles. Each of them has a single number written on it — either $1$ or $2$.\n\nHowever, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.\n\nCan you win the prize? Hurry up, the bags are waiting!",
    "tutorial": "There are at least a couple of correct solutions I had in mind. Let me present the one I find the most straightforward, which doesn't even require implementing any sieve. If all the numbers on the tiles are equal, we have no choice but to output the only possible permutation. In the remaining cases, we'll show that the following solution is optimal: Start with $2$ and $1$. Use all remaining $2$s. Finish with all remaining $1$s.",
    "code": "N = int(input())\nnum_ones = input().count('1')\nnum_twos = N - num_ones\n \nif not num_ones or not num_twos:\n    solution = [1] * num_ones + [2] * num_twos\nelse:\n    solution = [2, 1] + [2] * (num_twos - 1) + [1] * (num_ones - 1)\n \nprint(*solution)\n ",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1149",
    "index": "B",
    "title": "Three Religions",
    "statement": "During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.\n\nThe \\underline{Word of Universe} is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters.\n\nThe three religions can coexist in peace if their descriptions form disjoint subsequences of the \\underline{Word of Universe}. More formally, one can paint some of the characters of the \\underline{Word of Universe} in three colors: $1$, $2$, $3$, so that each character is painted in \\underline{at most} one color, and the description of the $i$-th religion can be constructed from the \\underline{Word of Universe} by removing all characters that aren't painted in color $i$.\n\nThe religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace.",
    "tutorial": "For our convenience, construct a two-dimensional helper array $N$ where $N(i, c)$ is the location of the first occurrence of character $c$ in the Word of Universe on position $i$ or later (or $\\infty$ if no such character exists). This array can be created in a straightforward in $O(26 \\cdot n)$ time, by iterating the word from the end to the beginning. Example. Consider the Word of Uniwerse equal to abccaab. The helper array looks as follows: Actually, for our purposes it's easier to set $\\infty = n$ (in our example, $n=7$) and also consider additional links from indices $n$ and $n+1$ to index $\\infty = n$. Why? We'll later need the index of the first occurrence of some character after some location $p$. If this $p$ already happens to be $\\infty$ ($n$, as we already established), we can easily see that no requested occurrence exists: Let's now try to answer each query in $O(250^3)$ time. We can do it using dynamic programming: let $D(n_1, n_2, n_3)$ be the length of the shortest prefix of the Word of Universe that contains the disjoint occurrences of the prefix of length $n_1$ of the first religion's description, the prefix of length $n_2$ of the second religion's description, and the prefix of length $n_3$ of the third religion's description. Each state can be evaluated in constant time by checking for each religion $i \\in \\{1, 2, 3\\}$, what the prefix length would be if the last character of the prefix is a part of the $i$-th religion's description. (We use the helper array $N$ to speed up the search.) How to write the state transitions? For each $i \\in \\{1, 2, 3\\}$: chop the last character of the $i$-th description's prefix, find the shortest prefix of the Word of Universe containing all three descriptions, and then reappend this last character. We can do that using our helper array: $D(n_1, n_2, n_3) = \\min \\begin{cases} N(D(n_1 - 1, n_2, n_3) + 1, \\text{description}_1[n_1]) & \\text{if } n_1 \\geq 1, \\\\ N(D(n_1, n_2 - 1, n_3) + 1, \\text{description}_2[n_2]) & \\text{if } n_2 \\geq 1, \\\\ N(D(n_1, n_2, n_3 - 1) + 1, \\text{description}_3[n_3]) & \\text{if } n_3 \\geq 1. \\end{cases}$ Now, if the lengths of the descriptions are $\\ell_1$, $\\ell_2$, and $\\ell_3$, respectively, then the embedding of these descriptions as distinct subsequences exists if and only if $D(\\ell_1, \\ell_2, \\ell_3) < \\infty = n$. However, due to the nature of queries, we can do a single update in $O(250^2)$ time: if we drop a character, we don't need to recompute any states; if we add a character to the $i$-th description, we only need to recompute the states with $n_i$ equal to the length of the description - and there are at most $251^2$ of them! This allows us to solve the problem in $O(q \\cdot 250^2)$ time.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int AlphaSize = 26;\nconst int MaxN = 1e5 + 100;\nconst int MaxM = 256;\n \nint next_occur[MaxN][AlphaSize];\nint dp[MaxM][MaxM][MaxM];\nstring pattern;\nstring words[3];\nint N, Q;\n \nvoid CreateLinks() {\n  for (int i = 0; i < AlphaSize; ++i) {\n    next_occur[N][i] = next_occur[N + 1][i] = N;\n  }\n  for (int pos = N - 1; pos >= 0; --pos) {\n    for (int i = 0; i < AlphaSize; ++i) {\n      next_occur[pos][i] = (pattern[pos] == 'a' + i ? pos : next_occur[pos + 1][i]);\n    }\n  }\n}\n \nvoid RecomputeDp(int a, int b, int c) {\n  int &val = dp[a][b][c];\n  val = N;\n  if (a) { val = min(val, next_occur[dp[a-1][b][c] + 1][words[0][a-1] - 'a']); }\n  if (b) { val = min(val, next_occur[dp[a][b-1][c] + 1][words[1][b-1] - 'a']); }\n  if (c) { val = min(val, next_occur[dp[a][b][c-1] + 1][words[2][c-1] - 'a']); }\n}\n \nint main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n \n  cin >> N >> Q >> pattern;\n  CreateLinks();\n \n  dp[0][0][0] = -1;\n \n  for (int i = 0; i < Q; ++i) {\n    char type;\n    int word_id;\n    cin >> type >> word_id;\n    --word_id;\n    if (type == '+') {\n      char ch;\n      cin >> ch;\n      words[word_id] += ch;\n      int max0 = words[0].size(), max1 = words[1].size(), max2 = words[2].size();\n      int min0 = word_id == 0 ? max0 : 0;\n      int min1 = word_id == 1 ? max1 : 0;\n      int min2 = word_id == 2 ? max2 : 0;\n \n      for (int a = min0; a <= max0; ++a) {\n        for (int b = min1; b <= max1; ++b) {\n          for (int c = min2; c <= max2; ++c) {\n            RecomputeDp(a, b, c);\n          }\n        }\n      }\n    } else {\n      words[word_id].pop_back();\n    }\n \n    bool answer = dp[words[0].size()][words[1].size()][words[2].size()] < N;\n    cout << (answer ? \"YES\\n\" : \"NO\\n\");\n  }\n}",
    "tags": [
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1149",
    "index": "C",
    "title": "Tree Generator™",
    "statement": "Owl Pacino has always been into trees — unweighted rooted trees in particular. He loves determining the diameter of every tree he sees — that is, the maximum length of any simple path in the tree.\n\nOwl Pacino's owl friends decided to present him the Tree Generator™ — a powerful machine creating rooted trees from their descriptions. An $n$-vertex rooted tree can be described by a bracket sequence of length $2(n - 1)$ in the following way: find any walk starting and finishing in the root that traverses each edge exactly twice — once down the tree, and later up the tree. Then follow the path and write down \"(\" (an opening parenthesis) if an edge is followed down the tree, and \")\" (a closing parenthesis) otherwise.\n\nThe following figure shows sample rooted trees and their descriptions:\n\nOwl wrote down the description of an $n$-vertex rooted tree. Then, he rewrote the description $q$ times. However, each time he wrote a new description, he picked two different characters in the description he wrote the last time, swapped them and wrote down the resulting string. He always made sure that each written string was the description of a rooted tree.\n\nPacino then used Tree Generator™ for each description he wrote down. What is the diameter of each constructed tree?",
    "tutorial": "Take any rooted tree and its description. For any vertices $u$, $v$, let $h(v)$ be its depth in the tree, and $d(u, v) = h(u) + h(v) - 2h(\\mathrm{lca}(u, v))$ be the distance between $u$ and $v$. Consider the traversal of the tree represented by the description. Let's say we're processing the parentheses one by one each second, and let's set $\\mu(t)$ be the current depth after $t$ seconds. Moreover, let $t_u$ and $t_v$ be the moments of time when we're in vertices $u, v$, respectively (there might be multiple such moments; pick any). Therefore, $h(u) = \\mu(t_u)$ and $h(v) = \\mu(t_v)$. Assume without the loss of generality that $t_u < t_v$ and consider the part of the description between the $t_u$-th and $t_v$-th second. What is the shallowest vertex we visit during such traversal? As the description represents a depth-first search of the tree, it must be $\\mathrm{lca}(u, v)$. Therefore, $h(\\mathrm{lca}(u, v)) = \\min_{t_l \\in [t_u, t_v]} \\mu(t_l)$. It follows that $d(u, v) = \\max_{t_l \\in [t_u, t_v]} \\left(\\mu(t_u) + \\mu(t_v) - 2\\mu(t_l)\\right)$. Eventually, the diameter is equal to $\\max_{u, v} d(u, v) = \\max_{t_u \\leq t_l \\leq t_v} \\left(\\mu(t_u) - 2\\mu(t_l) + \\mu(t_v)\\right)$. This leads to a slow $O(n)$ solution for computing a single diameter without constructing the tree: consider the parentheses one by one, and maintain the current depth and maximum values of $\\mu(a)$, $\\mu(a) - 2\\mu(b)$ and $\\mu(a) - 2\\mu(b) + \\mu(c)$ for $a \\leq b \\leq c$ on the prefix. However, we still need to be able to process the updates quicker than in linear time. It turns out we can maintain a segment tree. Each node will maintain some information about the substring of the description. Note that such substring doesn't have to describe the whole tree, and so the number of opening and closing parentheses doesn't have to match and it can happen that we're at a negative depth when following the description. We'll hold the following information about the substring. We assume everywhere that $a \\leq b \\leq c$: $\\delta$ (the final depth, might be non-zero), $\\max \\mu(a)$, $\\max (-2\\mu(b))$, $\\max (\\mu(a) - 2\\mu(b))$, $\\max(-2\\mu(b) + \\mu(c))$, $\\max (\\mu(a) - 2\\mu(b) + \\mu(c))$. It's now pretty straightforward to combine the informations about two neighboring substrings into a single information about the concatenation of the substrings. Note for example that $\\delta = \\delta_L + \\delta_R$ and $\\max \\mu(a) = \\max\\left\\{ \\max_L \\mu(a),\\ \\max_R \\mu(a) + \\delta_L\\right\\}$. This allows to maintain the segment tree over the description and process the single character replacement in $O(\\log n)$ time. Therefore, we can process each query in $O(\\log n)$ time, and solve the whole task in $O(n + q \\log n)$ time. Notably, square-root decomposition isn't much slower in this task; $O(\\sqrt{n})$ per query should pass if you aren't deliberately trying to write as slow code as possible.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \nstruct Tree {\n  // Node maximizing the value of depth(l) - 2*depth(v) + depth(r) for l<=v<=r\n  struct Node {\n    int delta;        // num '(' - num ')'\n    int min_depth;    // minimum value of [num '(' - num ')'] on prefix\n    int max_depth;    // maximum ...\n    int max_lv;       // max value of [depth(l) - 2 * depth(v)], l <= v\n    int max_rv;       // max value of [depth(r) - 2 * depth(v)], v <= r\n    int max_lvr;      // max value of [depth(l) - 2 * depth(v) + depth(r)]\n \n    static Node Empty() {\n      return Node{0, 0, 0, 0, 0, 0};\n    }\n \n    static Node LeftParenthesis() {\n      return Node{1, 0, 1, 0, 1, 1};\n    }\n \n    static Node RightParenthesis() {\n      return Node{-1, -1, 0, 2, 1, 1};\n    }\n \n    static Node FromCharacter(char ch) {\n      if (ch == '(')\n        return LeftParenthesis();\n      else\n        return RightParenthesis();\n    }\n \n    Node ShiftHeight(int displacement) const {\n      return Node{delta + displacement,\n                  min_depth + displacement,\n                  max_depth + displacement,\n                  max_lv - displacement,\n                  max_rv - displacement,\n                  max_lvr};\n    }\n \n    static Node Merge(const Node &lhs, const Node &rhs) {\n      Node rhs_shifted = rhs.ShiftHeight(lhs.delta);\n \n      Node result;\n      result.delta = rhs_shifted.delta;\n      result.min_depth = min(lhs.min_depth, rhs_shifted.min_depth);\n      result.max_depth = max(lhs.max_depth, rhs_shifted.max_depth);\n      result.max_lv = max(\n          {lhs.max_lv, rhs_shifted.max_lv, lhs.max_depth - 2 * rhs_shifted.min_depth});\n      result.max_rv = max(\n          {lhs.max_rv, rhs_shifted.max_rv, rhs_shifted.max_depth - 2 * lhs.min_depth});\n      result.max_lvr = max(\n          {lhs.max_lvr, rhs_shifted.max_lvr,\n           lhs.max_lv + rhs_shifted.max_depth,\n           rhs_shifted.max_rv + lhs.max_depth});\n      return result;\n    }\n  };\n \n  vector<Node> data;\n  int Base;\n \n  Tree(int N) : Base(1) {\n    while (Base < N + 1) { Base *= 2; }\n    data.resize(Base * 2, Node::Empty());\n  }\n \n  void Replace(int pos, char ch) {\n    pos += Base;\n    data[pos] = Node::FromCharacter(ch);\n    pos /= 2;\n \n    while (pos) {\n      data[pos] = Node::Merge(data[pos * 2], data[pos * 2 + 1]);\n      pos /= 2;\n    }\n  }\n \n  int GetMaxPath() const {\n    return data[1].max_lvr;\n  }\n};\n \nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(nullptr);\n \n  int N, Q;\n  string paren_string;\n  cin >> N >> Q >> paren_string;\n  --N;\n \n  Tree path_tree(N * 2);\n  for (int i = 0; i < N * 2; ++i) {\n    path_tree.Replace(i, paren_string[i]);\n  }\n \n  cout << path_tree.GetMaxPath() << \"\\n\";\n  for (int query_idx = 0; query_idx < Q; ++query_idx) {\n    int first_swap, second_swap;\n    cin >> first_swap >> second_swap;\n    --first_swap;\n    --second_swap;\n \n    const char next_first = paren_string[second_swap];\n    const char next_second = paren_string[first_swap];\n \n    assert(next_first != next_second);\n    path_tree.Replace(first_swap, next_first);\n    paren_string[first_swap] = next_first;\n \n    path_tree.Replace(second_swap, next_second);\n    paren_string[second_swap] = next_second;\n \n    cout << path_tree.GetMaxPath() << \"\\n\";\n  }\n}",
    "tags": [
      "data structures",
      "implementation",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1149",
    "index": "D",
    "title": "Abandoning Roads",
    "statement": "Codefortia is a small island country located somewhere in the West Pacific. It consists of $n$ settlements connected by $m$ bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to $a$ or $b$ seconds. It's guaranteed that one can go between any pair of settlements by following a sequence of roads.\n\nCodefortia was recently struck by the financial crisis. Therefore, the king decided to abandon some of the roads so that:\n\n- it will be possible to travel between each pair of cities using the remaining roads only,\n- the sum of times required to pass each remaining road will be minimum possible (in other words, remaining roads must form minimum spanning tree, using the time to pass the road as its weight),\n- among all the plans minimizing the sum of times above, the time required to travel between the king's residence (in settlement $1$) and the parliament house (in settlement $p$) using the remaining roads only will be minimum possible.\n\nThe king, however, forgot where the parliament house was. For each settlement $p = 1, 2, \\dots, n$, can you tell what is the minimum time required to travel between the king's residence and the parliament house (located in settlement $p$) after some roads are abandoned?",
    "tutorial": "Let's partition the edges of the graph into two classes: light (weight $a$) and heavy (weight $b$). Let's now fix a single settlement $p$ as the location of the parliament house, and consider how the path between settlements $1$ and $p$ could look like. Lemma 1. If there is a path between two settlements $u$, $v$ consisting of light edges only, then they will be connected using the light edges only in any minimum spanning tree. Proof. Consider the Kruskal minimum spanning tree algorithm (which can produce any minimum spanning tree depending on the order we consider the edges with equal weight). After we process all light edges, settlements $u$ and $v$ will be connected. Lemma 2. Consider the connected components in the graph with heavy edges removed. In the original graph, a path can be a part of the minimum spanning tree if and only if there is we don't leave and then reenter any of the components. Proof. If we leave and then reenter any connected component, there are two vertices $u$, $v$ in a single connected component (that is, connected by a light path in the original graph) that has at least one heavy edge on the path in between. Lemma 1 asserts that it's impossible. However, if no such situation happens, it's straightforward to extend the selected path to a minimum spanning tree - first add all possible light edges, then all possible heavy edges so that the graph becomes a spanning tree. This leads us to an (inefficient) $O(2^n m \\log(2^n m))$ solution: find the connected components in the graph with light edges only. We want now to find the shortest path between $1$ and all other vertices that doesn't revisit any component multiple times. In order to do so, create a graph where each state is of the following format $(\\text{mask of components visited so far}, \\text{current vertex})$. This information allows us to check if we don't reenter any previously visited component. After we do that, we run Dijkstra's shortest path algorithm from vertex $1$. The shortest path between vertices $1$ and $p$ can be found in the state first visiting vertex $p$. The beautiful thing now is that the algorithm can be sped up by the following greedy observation: Lemma 3. Consider any component of size $3$ or less. It's not optimal to leave and then reenter this component even if we don't explicitly forbid this. Proof. We need to use at least two heavy edges to leave and then reenter the component, and this costs us $2b$ or more. However, as the component has at most three vertices, the path between any pair of vertices costs at most $2a$. As $a < b$, it's always more optimal to take the path inside the component. Therefore, we can simply ignore all components of size $3$ or less. As we now need to remember the components having at least $4$ vertices, the number of states drops down to $O(2^{n/4} m)$. This immediately allows us to finish the solution in a number of ways: Implement the vanilla Dijkstra algorithm on the state graph - time complexity $O(2^{n/4} m \\log(2^{n/4} m))$. Notice that the edges of the graph have only two weights ($a$ and $b$) and therefore the priority queue can be implemented using two queues - time complexity drops to $O(2^{n/4} m)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MaxN = 80;\nconst int kCompoSizeBound = 4;\n \nint N, M, A, B;\nvector<int> adj_cheap[MaxN];\nvector<int> adj_expensive[MaxN];\nvector<vector<int>> large_cheap_compos;\nunsigned large_compo_mask[MaxN];\nbool is_same_compo[MaxN][MaxN];\n \nbool visited[MaxN];\nvector<int> cur_component;\n \nvoid DfsCheap(int v) {\n  visited[v] = true;\n  cur_component.push_back(v);\n  for (int s : adj_cheap[v]) {\n    if (!visited[s]) {\n      DfsCheap(s);\n    }\n  }\n}\n \nvoid FindCheapComponents() {\n  fill_n(visited, N + 1, false);\n \n  for (int v = 1; v <= N; ++v) {\n    if (!visited[v]) {\n      cur_component.clear();\n      DfsCheap(v);\n      for (int a : cur_component) for (int b : cur_component) {\n        is_same_compo[a][b] = true;\n      }\n      if ((int)cur_component.size() >= kCompoSizeBound) {\n        const int compo_idx = (int)large_cheap_compos.size();\n        large_cheap_compos.push_back(cur_component);\n        for (int vert : cur_component) {\n          large_compo_mask[vert] = 1U << compo_idx;\n        }\n      }\n    }\n  }\n}\n \nint32_t main() {\n  cin >> N >> M >> A >> B;\n  for (int i = 0; i < M; ++i) {\n    int u, v, c;\n    cin >> u >> v >> c;\n    if (c == A) {\n      adj_cheap[u].push_back(v);\n      adj_cheap[v].push_back(u);\n    } else {\n      adj_expensive[u].push_back(v);\n      adj_expensive[v].push_back(u);\n    }\n  }\n \n  FindCheapComponents();\n \n  const int S = large_cheap_compos.size();\n \n  using State = pair<int, unsigned>;\n  using QueueElem = pair<int, State>;\n \n  const State init_state{1, large_compo_mask[1]};\n  \n  priority_queue<QueueElem, vector<QueueElem>, greater<QueueElem>> que;\n  que.emplace(0, init_state);\n \n  const int kInfty = 1e9;\n  vector<int> answers(N + 1, kInfty);\n  vector<vector<int>> distances(N + 1, vector<int>(1 << S, kInfty));\n  distances[1][large_compo_mask[1]] = 0;\n  vector<vector<bool>> dij_visited(N + 1, vector<bool>(1 << S));\n \n  while (!que.empty()) {\n    auto [cost, state] = que.top();\n    que.pop();\n    auto &&[vert, mask] = state;\n \n    if (dij_visited[vert][mask]) {\n      continue;\n    }\n    dij_visited[vert][mask] = true;\n \n    answers[vert] = min(answers[vert], cost);\n \n    for (int s_cheap : adj_cheap[vert]) {\n      const int new_dist = cost + A;\n      if (distances[s_cheap][mask] > new_dist) {\n        que.emplace(new_dist, State{s_cheap, mask});\n        distances[s_cheap][mask] = new_dist;\n      }\n    }\n \n    for (int s_large : adj_expensive[vert]) {\n      if (is_same_compo[vert][s_large]) { continue; }\n      if (large_compo_mask[s_large] & mask) { continue; }\n      const unsigned new_mask = mask | large_compo_mask[s_large];\n      const int new_dist = cost + B;\n      if (distances[s_large][new_mask] > new_dist) {\n        que.emplace(new_dist, State{s_large, new_mask});\n        distances[s_large][new_mask] = new_dist;\n      }\n    }\n  }\n \n  for (int i = 1; i <= N; ++i) {\n    cout << answers[i] << (i == N ? '\\n' : ' ');\n  }\n}\n ",
    "tags": [
      "brute force",
      "dp",
      "graphs",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1149",
    "index": "E",
    "title": "Election Promises",
    "statement": "In Byteland, there are two political parties fighting for seats in the Parliament in the upcoming elections: Wrong Answer Party and Time Limit Exceeded Party. As they want to convince as many citizens as possible to cast their votes on them, they keep promising lower and lower taxes.\n\nThere are $n$ cities in Byteland, connected by $m$ one-way roads. Interestingly enough, the road network has no cycles — it's impossible to start in any city, follow a number of roads, and return to that city. Last year, citizens of the $i$-th city had to pay $h_i$ bourles of tax.\n\nParties will now alternately hold the election conventions in various cities. If a party holds a convention in city $v$, the party needs to decrease the taxes in this city to a non-negative integer amount of bourles. However, at the same time they can arbitrarily modify the taxes in each of the cities that can be reached from $v$ using a single road. The only condition that must be fulfilled that the tax in each city has to remain a non-negative integer amount of bourles.\n\nThe first party to hold the convention is Wrong Answer Party. It's predicted that the party to hold the last convention will win the election. Can Wrong Answer Party win regardless of Time Limit Exceeded Party's moves?",
    "tutorial": "Let's get straight to the main lemma: Lemma. For any vertex $v$, let's define the level of $v$ as $M(v) = \\mathrm{mex}\\,\\{M(u)\\,\\mid\\,v\\to u\\,\\text{is an edge}\\}$ where $\\mathrm{mex}$ is the minimum-excluded function. Moreover, for any $t \\in \\mathbb{N}$, let $X(t)$ be the xor-sum of the taxes in all cities $v$ fulfilling $M(v) = t$; that is, $X(t) = \\bigoplus\\,\\{h_v\\,\\mid\\,M(v)=t\\}$. The starting party loses if and only if $X(t) = 0$ for all $t$'s; that is, if all xor-sums are equal to 0. Proof. Let's consider any move from the position in which all xor-sums are zero. If we're holding the convention in the city $v$, then we must decrease the amount of taxes in this city. Note however that there is no direct connection from $v$ to any other city $u$ having the same level as $v$, as $M(v)$ is the smallest integer outside of the set $\\{M(u)\\,\\mid\\,v\\to u\\,\\text{is an edge}\\}$. Therefore, there is exactly one tax value changing at level $M(v)$, and thus the value $X(M(v))$ must change. As it was zero before, it must become non-zero. Now consider any configuration where some xor-sums are non-zero. Let $t$ be the highest level at which $X(t) > 0$. We want to hold the election in a selected city at level $t$. Which one? Notice that no city at a single level is connected to each other, and therefore we can only afford to pick one city and strictly decrease its tax. This is equivalent to the game of Nim where each city corresponds to a single stack of stones. We perform a single optimal move in this game: pick a city and decrease the tax in the city by a non-zero amount of bourles, leading to the position where the new xor-sum of the taxes at this level $X'(t)$ is equal to zero. We also need to take care of zeroing all $X(l)$'s for $l < t$. This is however straightforward: for each $l < t$, pick a single city $v_l$ fulfilling at level $l$ directly reachable from $v$ (there must be one from the definition of $M(v)$), and alter the value of tax in order to nullify $X(l)$. The proof above is actually constructive and allows us to compute a single winning move in $O(n + m)$ time. As a small bonus: if you're into advanced game theory, you can come up with the lemma above without much guesswork. One can compute the nimbers for the state where there are no taxes anywhere except a single city $v$ where the tax is equal to $h_v$, and it turns out to be equal to $\\omega^{M(v)} \\cdot h_v$ where $\\omega$ is the smallest infinite ordinal number. Moreover, it's not that hard to see that the nimber for the state where there are more taxed cities is a nim-sum of the nimbers corresponding to the states with only one taxed city. This all should quite naturally lead to the lemma above.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MaxN = 2e5 + 100;\n \nint stack_sizes[MaxN];\nvector<int> adj[MaxN];\nint N, M;\n \nint vertex_group_idx[MaxN];\nbool visited[MaxN];\nint group_xor[MaxN];\nvector<int> vertex_groups[MaxN];\n \nvoid DfsMakeLayers(int vert) {\n  visited[vert] = true;\n  vector<int> seen_layers;\n  for (int s : adj[vert]) {\n    if (!visited[s]) {\n      DfsMakeLayers(s);\n    }\n    seen_layers.push_back(vertex_group_idx[s]);\n  }\n  sort(seen_layers.begin(), seen_layers.end());\n  seen_layers.resize(unique(seen_layers.begin(), seen_layers.end()) -\n      seen_layers.begin());\n  seen_layers.push_back(1e9);\n \n  while (seen_layers[vertex_group_idx[vert]] == vertex_group_idx[vert]) {\n    ++vertex_group_idx[vert];\n  }\n  const int group_id = vertex_group_idx[vert];\n  group_xor[group_id] ^= stack_sizes[vert];\n  vertex_groups[group_id].push_back(vert);\n}\n \nint main() {\n  ios_base::sync_with_stdio(0);\n \n  cin >> N >> M;\n \n  for (int i = 0; i < N; ++i) {\n    cin >> stack_sizes[i];\n  }\n \n  for (int i = 0; i < M; ++i) {\n    int u, v;\n    cin >> u >> v;\n    --u; --v;\n    adj[u].push_back(v);\n  }\n \n  for (int vert = 0; vert < N; ++vert) {\n    if (!visited[vert]) {\n      DfsMakeLayers(vert);\n    }\n  }\n \n  if (count(group_xor, group_xor + N, 0) == N) {\n    cout << \"LOSE\\n\";\n    return 0;\n  }\n \n  int last_idx = N;\n  while (group_xor[last_idx] == 0)\n    --last_idx;\n \n  int touched_vertex = -1;\n  for (int vert : vertex_groups[last_idx]) {\n    if ((stack_sizes[vert] ^ group_xor[last_idx]) < stack_sizes[vert]) {\n      touched_vertex = vert;\n      break;\n    }\n  }\n \n  assert(touched_vertex != -1);\n \n  stack_sizes[touched_vertex] ^= group_xor[last_idx];\n  group_xor[last_idx] = 0;\n \n  for (int neigh : adj[touched_vertex]) {\n    const int group_idx = vertex_group_idx[neigh];\n    stack_sizes[neigh] ^= group_xor[group_idx];\n    group_xor[group_idx] = 0;\n  }\n \n  assert(count(group_xor, group_xor + N, 0) == N);\n \n  cout << \"WIN\\n\";\n  for (int i = 0; i < N; ++i)\n    cout << stack_sizes[i] << \" \";\n  cout << \"\\n\";\n}",
    "tags": [
      "games",
      "graphs"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1150",
    "index": "A",
    "title": "Stock Arbitraging",
    "statement": "Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!\n\nIn the morning, there are $n$ opportunities to buy shares. The $i$-th of them allows to buy as many shares as you want, each at the price of $s_i$ bourles.\n\nIn the evening, there are $m$ opportunities to sell shares. The $i$-th of them allows to sell as many shares as you want, each at the price of $b_i$ bourles. You can't sell more shares than you have.\n\nIt's morning now and you possess $r$ bourles and no shares.\n\nWhat is the maximum number of bourles you can hold after the evening?",
    "tutorial": "The main observation is that we always want to buy shares as cheaply as possible, and sell them as expensively as possible. Therefore, we should pick the lowest price at which we can buy shares $s_{\\min} = \\min(s_1, s_2, \\dots, s_n)$, and the highest price at which we can sell the shares $b_{\\max} = \\max(b_1, b_2, \\dots, b_m)$. Now, we have two cases: If $s_{\\min} < b_{\\max}$, it's optimal to buy as many shares and possible in the morning and sell them all in the evening. We can buy as many as $\\left\\lfloor \\frac{r}{s_{\\min}} \\right\\rfloor$ shares and gain $b_{\\max} - s_{\\min}$ bourles profit on each of them. Therefore, the final balance is $r + \\left\\lfloor \\frac{r}{s_{\\min}} \\right\\rfloor (b_{\\max} - s_{\\min})$. If $s_{\\min} \\geq b_{\\max}$, we're not gaining any profit on the shares and therefore we shouldn't care about trading stocks at all. The final balance is then $r$. The solution can be therefore implemented in $O(n + m)$ time. However, the constraints even allowed brute-forcing the seller, the buyer and the amount of stock we're buying in $O(nmr)$ time. Note that many programming languages have routines for finding the minima/maxima of the collections of integers: e.g. min_element in C++, Collections.min in Java, or min in Python. This should make the code shorter and quicker to write.",
    "code": "R = int(input().split()[-1])\n \nbest_buy = min(map(int, input().split()))\nbest_sell = max(map(int, input().split()))\n \nnum_buy = R // best_buy\n \nprint(max(R, R + (best_sell - best_buy) * num_buy))",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1150",
    "index": "B",
    "title": "Tiling Challenge",
    "statement": "One day Alice was cleaning up her basement when she noticed something very curious: an \\textbf{infinite} set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile:\n\nBy the pieces lay a large square wooden board. The board is divided into $n^2$ cells arranged into $n$ rows and $n$ columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?",
    "tutorial": "Notice that there is only one orientation of the wooden piece (and this is the orientation depicted in the statement). Moreover, we can notice the following fact: Take any (untiled) topmost cell of the board. If there is any correct tiling of the board, this cell must be covered by the topmost tile of the piece. The fact is pretty obvious - there is simply no other way to cover the cell. Having that, it's straightforward to implement an $O(n^4)$ solution: while the board isn't fully covered, take any topmost untiled cell and try to cover it with a piece. If it's impossible, declare the failure. If it's possible, lay the piece and repeat the procedure. We can lay at most $O(n^2)$ pieces, and we're looking for the topmost cell in $O(n^2)$ time. This gives us $O(n^4)$ running time. While this is enough to solve the task, one can also notice that we don't have to seek the whole board in search of the cell. In fact, we can do a single scan through the board in row-major order, and as soon as we find any uncovered cell, we try to cover it by a wooden piece. This allows us to implement the solution in $O(n^2)$ time.",
    "code": "vectors = [(0, 0), (1, -1), (1, 0), (1, 1), (2, 0)]\n \nN = int(input())\nboard = [list(input()) for row_id in range(N)]\n \nfor row in range(N - 2):\n    for col in range(1, N - 1):\n        can_place = all(board[row + dr][col + dc] == '.' for (dr, dc) in vectors)\n        if can_place:\n            for (dr, dc) in vectors:\n                board[row + dr][col + dc] = '#'\n \nhas_dots = any(row.count('.') for row in board)\nprint('NO' if has_dots else 'YES')",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1151",
    "index": "A",
    "title": "Maxim and Biology",
    "statement": "Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string \"ACTG\".\n\nMaxim was very boring to sit in class, so the teacher came up with a task for him: on a given string $s$ consisting of uppercase letters and length of at least $4$, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string $s$ with the next or previous in the alphabet. For example, for the letter \"D\" the previous one will be \"C\", and the next — \"E\". In this problem, we assume that for the letter \"A\", the previous one will be the letter \"Z\", and the next one will be \"B\", and for the letter \"Z\", the previous one is the letter \"Y\", and the next one is the letter \"A\".\n\nHelp Maxim solve the problem that the teacher gave him.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.",
    "tutorial": "Check every substring of string $s$ of length $4$ and find the minimum number of operations to transform it into \"ACTG\" and update the answer. Complexity is $\\mathcal{O}(n)$.",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1151",
    "index": "B",
    "title": "Dima and a Bad XOR",
    "statement": "Student Dima from Kremland has a matrix $a$ of size $n \\times m$ filled with non-negative integers.\n\nHe wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him!\n\nFormally, he wants to choose an integers sequence $c_1, c_2, \\ldots, c_n$ ($1 \\leq c_j \\leq m$) so that the inequality $a_{1, c_1} \\oplus a_{2, c_2} \\oplus \\ldots \\oplus a_{n, c_n} > 0$ holds, where $a_{i, j}$ is the matrix element from the $i$-th row and the $j$-th column.\n\nHere $x \\oplus y$ denotes the bitwise XOR operation of integers $x$ and $y$.",
    "tutorial": "Let's take the first number in each array. Then, if we have current XOR strictly greater than zero we can output an answer. And if there is some array, such that it contains at least two distinct numbers, you can change the first number in this array to number, that differs from it, and get XOR $0 \\oplus x > 0$. Else, each array consists of the same numbers, so all possible XORs are equal to $0$, and there is no answer. Complexity is $\\mathcal{O}(n \\cdot m)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1151",
    "index": "C",
    "title": "Problem for Nazar",
    "statement": "Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task.\n\nConsider two infinite sets of numbers. The first set consists of odd positive numbers ($1, 3, 5, 7, \\ldots$), and the second set consists of even positive numbers ($2, 4, 6, 8, \\ldots$). At the first stage, the teacher writes the first number on the endless blackboard from the first set, in the second stage — the first two numbers from the second set, on the third stage — the next four numbers from the first set, on the fourth — the next eight numbers from the second set and so on. In other words, at each stage, starting from the second, he writes out \\textbf{two times more} numbers than at the previous one, and also \\textbf{changes the set} from which these numbers are written out \\textbf{to another}.\n\nThe ten first written numbers: $1, 2, 4, 3, 5, 7, 9, 6, 8, 10$. Let's number the numbers written, starting \\textbf{with one}.\n\nThe task is to find the sum of numbers with numbers from $l$ to $r$ for given integers $l$ and $r$. The answer may be big, so you need to find the remainder of the division by $1000000007$ ($10^9+7$).\n\nNazar thought about this problem for a long time, but didn't come up with a solution. Help him solve this problem.",
    "tutorial": "At first let's simplify the problem. Let's denote as $f(x)$ function that returns sum of the elements that are on positions from $1$ to $x$ inclusive. How to implement function $f(x)$? To find the answer we can find the sum of even and sum of odd numbers and add them. Let's find how many there are even and odd numbers. Let's call them $cur_{even}$ and $cur_{odd}$. Iterate through the powers of two. If current power is even, then add minimum from $x$ and current power of two to $cur_{odd}$, otherwise add minimum from $x$ and current power of two to $cur_{even}$, after that reduce $x$ by current power of two. If $x$ becomes less than or equal to $0$ break. Now our task is reduced to twos: for given number $n$ find the sum of first $n$ even numbers and for given number $m$ find the sum of first $m$ odd numbers. The answer for first task is $n \\cdot (n + 1)$. The answer for second task is $m^2$. Now the answer for the problem is $f(r)-f(l-1)$. Don't forget about modulo :) Complexity is $\\mathcal{O}(\\log{N})$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1151",
    "index": "D",
    "title": "Stas and the Queue at the Buffet",
    "statement": "During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $n$ high school students numbered from $1$ to $n$. Initially, each student $i$ is on position $i$. Each student $i$ is characterized by two numbers — $a_i$ and $b_i$. Dissatisfaction of the person $i$ equals the product of $a_i$ by the number of people standing to the left of his position, add the product $b_i$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $i$, which is on the position $j$, equals $a_i \\cdot (j-1) + b_i \\cdot (n-j)$.\n\nThe director entrusted Stas with the task: rearrange the people in the queue so that \\textbf{minimize the total} dissatisfaction.\n\nAlthough Stas is able to solve such problems, this was not given to him. He turned for help to you.",
    "tutorial": "Firstly, open the brackets: $a_i \\cdot (j-1) + b_i \\cdot (n-j)$ = $(a_i - b_i) \\cdot j + b_i \\cdot n - a_i$. As you can see $b_i \\cdot n - a_i$ is not depending on $j$, so we can sum these values up and consider them as constants. Now we must minimize the sum of $(a_i - b_i) \\cdot j$. Let's denote two integers arrays each of length $n$: array $c$ such that $c_i=a_i-b_i$ and array $d$ such that $d_i=i$ (for each $i$ from $1$ to $n$). Now we must solve the following task: minimize the value $\\sum_{i=1}^{n} c_i \\cdot d_i$ if we can rearrange the elements of array $c$ as we want. To solve this problem we must sort array $c$ in non-increasing order. You can use an exchange argument to prove it. Complexity is $\\mathcal{O}(n\\log{n})$.",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1151",
    "index": "E",
    "title": "Number of Components",
    "statement": "The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of $n$ vertices. Each vertex $i$ has its own value $a_i$. All vertices are connected in series by edges. Formally, for every $1 \\leq i < n$ there is an edge between the vertices of $i$ and $i+1$.\n\nDenote the function $f(l, r)$, which takes two integers $l$ and $r$ ($l \\leq r$):\n\n- We leave in the tree only vertices whose values ​​range from $l$ to $r$.\n- The value of the function will be the number of connected components in the new graph.\n\nYour task is to calculate the following sum: $$\\sum_{l=1}^{n} \\sum_{r=l}^{n} f(l, r) $$",
    "tutorial": "First of all assign $0$ to $a_0$. How to find the value of $f(l, r)$ in $\\mathcal{O}(n)$? For each $i$ from $0$ to $n$ set $b_i$ to $1$ if $l \\leq a_i \\leq r$, otherwise set it to $0$. Now we can see that the value of $f(l, r)$ is equal to the number of adjacent pairs $(0, 1)$ in array $b$. So now we can find the answer in $\\mathcal{O}(n)$ using technique contribution to the sum. For every adjacent pair of elements in array $a$ (including zero-indexed element) we must find it contribution to the overall answer. Considering the thoughts above about $f(l,r)$, we must find the number of pairs $(l, r)$ such that $a_i$ is on the range $[l, r]$ and $a_{i-1}$ is not on the range $[l, r]$. There are two cases: What if $a_i$ is greater than $a_{i-1}$? Then $l$ must be on range from $a_{i-1}+1$ to $a_i$ and $r$ must be on range from $a_i$ to $n$. The contribution is $(a_i-a_{i-1}) \\cdot (n-a_i+1)$. What if $a_i$ is less than $a_{i-1}$? Then $l$ must be on range from $1$ to $a_i$ and $r$ must be on range from $a_i$ to $a_{i-1}-1$. The contribution is $a_i \\cdot (a_{i-1} - a_i)$. Sum up the contributions of all adjacent pairs to find the answer. Complexity is $\\mathcal{O}(n)$.",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1151",
    "index": "F",
    "title": "Sonya and Informatics",
    "statement": "A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.\n\nGiven an array $a$ of length $n$, \\textbf{consisting only of the numbers $0$ and $1$}, and the number $k$. \\textbf{Exactly $k$ times} the following happens:\n\n- Two numbers $i$ and $j$ are chosen equiprobable such that ($1 \\leq i < j \\leq n$).\n- The numbers in the $i$ and $j$ positions are swapped.\n\nSonya's task is to find the probability that after all the operations are completed, the $a$ array will be \\textbf{sorted in non-decreasing order}. She turned to you for help. Help Sonya solve this problem.\n\nIt can be shown that the desired probability is either $0$ or it can be represented as $\\dfrac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q \\not\\equiv 0~\\pmod {10^9+7}$.",
    "tutorial": "How to solve this problem in $\\mathcal{O}(n\\cdot k)$? Let's find the answer using dynamic programming. Denote $cur$ as the number of zeroes in array $a$, and $dp_{i,j}$ as the number of rearrangements of array $a$ after $i$ operations and $j$ is equal to the number of zeroes on prefix of length $cur$. Denote $x$ as the number of zeroes on prefix of length $cur$. The initial state will be $dp_{0,x}=1$. Notice that the answer will be $\\dfrac{dp_{k, cur}}{\\sum_{i=0}^{cur}dp_{k, i}}$. The transitions are not so hard. You must know the following values: the number of ones on prefix of length $cur$, the number of zeroes on prefix of length $cur$, the number of ones NOT on prefix of length $cur$ and the number of zeroes NOT on prefix of length $cur$. For example, you can find the number of pairs such that after we swap them the number of zeroes on prefix of length $cur$ is increased by one: the number of ones on prefix of length $cur$ multiply by the number of zeroes NOT on prefix of length $cur$. Also there are transitions when the number of zeroes on prefix of length $cur$ remains the same, and when it decreased by one (you can find them by yourself). To solve the original problem we must create the transition matrix and find the answer using matrix multiplication with binary exponentiation. Also you must know how to find the modular multiplicative inverse to find the answer. Complexity is $\\mathcal{O}(n^3\\cdot \\log{k})$.",
    "tags": [
      "combinatorics",
      "dp",
      "matrices",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1152",
    "index": "A",
    "title": "Neko Finds Grapes",
    "statement": "On a random day, Neko found $n$ treasure chests and $m$ keys. The $i$-th chest has an integer $a_i$ written on it and the $j$-th key has an integer $b_j$ on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.\n\nThe $j$-th key can be used to unlock the $i$-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, $a_i + b_j \\equiv 1 \\pmod{2}$. One key can be used to open at most one chest, and one chest can be opened at most once.\n\nFind the maximum number of chests Neko can open.",
    "tutorial": "The most important observation is that: Key with odd id can only be used to unlock chest with even id Key with even id can only be used to unlock chest with odd id Let: $c_0, c_1$ be the number of chests with even and odd id, respectively $k_0, k_1$ be the number of keys with even and odd id, respectively With $c_0$ even-id chests and $k_1$ odd-id keys, you can unlock at most $\\min(c_0, k_1)$ chests. With $c_1$ odd-id chests and $k_0$ even-id keys, you can unlock at most $\\min(c_1, k_0)$ chests. Therefore, the final answer is $\\min(c_0, k_1) + \\min(c_1, k_0)$. Complexity: $O(n + m)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n    int n, m;\n    scanf(\"%d%d\", &n, &m);\n\n    vector<int> a(n), b(m);\n    for(int i = 0; i < n; ++i)\n        scanf(\"%d\", &a[i]);\n    for(int i = 0; i < m; ++i)\n        scanf(\"%d\", &b[i]);\n\n    int c0 = 0, c1 = 0;\n    for(int i = 0; i < n; ++i)\n        if (a[i]%2 == 0)\n            ++c0;\n        else\n            ++c1;\n\n    int k0 = 0, k1 = 0;\n    for(int i = 0; i < m; ++i)\n        if (b[i]%2 == 0)\n            ++k0;\n        else\n            ++k1;\n\n    int ans = min(c1, k0) + min(c0, k1);\n\n    printf(\"%d\", ans);\n\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1152",
    "index": "B",
    "title": "Neko Performs Cat Furrier Transform",
    "statement": "Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.\n\nAssume that we have a cat with a number $x$. A perfect longcat is a cat with a number equal $2^m - 1$ for some non-negative integer $m$. For example, the numbers $0$, $1$, $3$, $7$, $15$ and so on are suitable for the perfect longcats.\n\nIn the Cat Furrier Transform, the following operations can be performed on $x$:\n\n- (Operation A): you select any non-negative integer $n$ and replace $x$ with $x \\oplus (2^n - 1)$, with $\\oplus$ being a bitwise XOR operator.\n- (Operation B): replace $x$ with $x + 1$.\n\nThe first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.\n\nNeko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $40$ operations. Can you help Neko writing a transformation plan?\n\nNote that it is \\textbf{not required} to minimize the number of operations. You just need to use no more than $40$ operations.",
    "tutorial": "There are various greedy solutions possible. I'll only cover one of them. We'll perform a loop as follows: If $x \\le 1$, stop the process (since it's already correct). If $x = 2^m$ ($m \\ge 1$), perform operation A with $2^m-1$. Obviously, the resulting $x$ will be $2^{m+1}-1$, which satisfies the criteria, so we stop the process. Otherwise, let's denote $MSB(x)$ as the position/exponential of the most significant bit of $x$ (for example, $MSB(4) = MSB(7) = 2$). We'll perform operation A with $2^{MSB(x)+1} - 1$. If $x$ after this phase is not a valid number, we'll then perform operation B and return to the beginning of the loop. This will never take more than $40$ queries, since each iteration removes the most significant bit (and it would never reappear after later steps), and $x$ can only have at most $20$ bits initially. Also, it is possible to solve this problem by finding exactly shortest operation sequence by using a BFS. However, this was not required.",
    "code": "#pragma comment(linker, \"/stack:247474112\")\n#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\n\nint x; vector<vector<int>> vis(2, vector<int>(1048576, INT_MAX));\nvector<vector<pair<int, int>>> Last(2, vector<pair<int, int>>(1048576, {-1LL, -1LL}));\n\nint isCompletion(int z) {\n\tint bitval = 0;\n\tz += 1; while (z % 2 == 0) {z /= 2; bitval++;}\n\tif (z != 1) return -1;\n\treturn bitval;\n}\n\nvoid Input() {\n\tcin >> x;\n}\n\nvoid Solve() {\n\tqueue<pair<int, int>> Q;\n\tvis[0][x] = 0; Q.push({0, x});\n\tint p1 = -1, p2 = -1;\n\twhile (!Q.empty()) {\n\t\tpair<int, int> Token = Q.front();\n\t\tint p = Token.first, z = Token.second; Q.pop();\n\t\tif (isCompletion(z) != -1) {p1 = p; p2 = z; break;}\n\t\tif (p == 1) {\n\t\t\tif (vis[0][z+1] == INT_MAX) {\n\t\t\t\tvis[0][z+1] = vis[1][z] + 1;\n\t\t\t\tLast[0][z+1] = {1, z}; Q.push({0, z+1});\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int i=0; i<20; i++) {\n\t\t\t\tint t = (z ^ ((1 << i) - 1));\n\t\t\t\tif (vis[1][t] != INT_MAX) continue;\n\t\t\t\tvis[1][t] = vis[0][z] + 1;\n\t\t\t\tLast[1][t] = {0, z}; Q.push({1, t});\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << vis[p1][p2] << endl;\n\n\tvector<int> xorCmd;\n\twhile (Last[p1][p2] != make_pair(-1, -1)) {\n\t\tpair<int, int> Token = Last[p1][p2];\n\t\tint z = Token.first, t = Token.second;\n\t\tif (p1 == 1) xorCmd.push_back(isCompletion(p2 ^ t));\n\t\tp1 = z; p2 = t;\n\t}\n\n\treverse(xorCmd.begin(), xorCmd.end());\n\tfor (auto z: xorCmd) cout << z << \" \";\n}\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0);\n\tcin.tie(NULL); Input(); Solve();\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1152",
    "index": "C",
    "title": "Neko does Maths",
    "statement": "Neko loves divisors. During the latest number theory lesson, he got an interesting exercise from his math teacher.\n\nNeko has two integers $a$ and $b$. His goal is to find a non-negative integer $k$ such that the least common multiple of $a+k$ and $b+k$ is the smallest possible. If there are multiple optimal integers $k$, he needs to choose the smallest one.\n\nGiven his mathematical talent, Neko had no trouble getting Wrong Answer on this problem. Can you help him solve it?",
    "tutorial": "The $lcm(a + k, b + k)$ is equal to $\\frac{(a + k) \\cdot (b + k)}{\\gcd(a + k, b + k)}$. In fact, there are not much possible values for the denominator of this fraction. Without losing generality, let's assume $a \\le b$. Applying one step of Euclid's algorithm we can see, that $\\gcd(a + k, b + k) = \\gcd(b - a, a + k)$. So the $\\gcd$ is a divisor of $b - a$. Let's iterate over all divisors $q$ of $b - a$. That also means that $a \\pmod{q} = b \\pmod{q}$. In case $a \\pmod{q} = 0$, we can use $k = 0$. Otherwise, the corresponding $k$ should be $q - a \\pmod{q}$. Lastly, we need to check whether the value of $lcm(a + k, b + k)$ is the smallest found so far. Also, one has to be careful when dealing with $k = 0$ answer, which was the reason why many solutions got WA 63. The complexity is $O(\\sqrt{b - a})$.",
    "code": "#pragma comment(linker, \"/stack:247474112\")\n#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define endl '\\n'\n\nint a, b;\n\nvoid Input() {\n\tcin >> a >> b;\n}\n\nvoid Solve() {\n\tif (a == b) {cout << \"0\\n\"; return;}\n\t\n\tvector<int> Divisors;\n\tfor (int i=1; i<=sqrt(max(a,b) - min(a,b)); i++) {\n\t\tif ((max(a,b) - min(a,b)) % i != 0) continue;\n\t\tint j = (max(a,b) - min(a,b)) / i;\n\t\tDivisors.push_back(i);\n\t\tif (i != j) Divisors.push_back(j);\n\t}\n\t\n\tpair<long long, int> Token = make_pair(LLONG_MAX, INT_MAX);\n\tfor (auto d: Divisors) {\n\t\tint k = (d - a % d) % d;\n\t\tpair<long long, int> NewToken = make_pair(1LL * (0LL + a + k) / __gcd(0LL+a+k, 0LL+b+k) * (0LL + b + k), k);\n\t\tToken = min(Token, NewToken);\n\t}\n\t\n\tcout << Token.second << endl;\n}\n\nint main(int argc, char* argv[]) {\n\tios_base::sync_with_stdio(0);\n\tcin.tie(NULL); Input(); Solve();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1152",
    "index": "D",
    "title": "Neko and Aki's Prank",
    "statement": "Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...\n\nIt took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of weird things, including a trie of all correct bracket sequences of length $2n$.\n\nThe definition of correct bracket sequence is as follows:\n\n- The empty sequence is a correct bracket sequence,\n- If $s$ is a correct bracket sequence, then $(\\,s\\,)$ is a correct bracket sequence,\n- If $s$ and $t$ are a correct bracket sequence, then $st$ is also a correct bracket sequence.\n\nFor example, the strings \"(())\", \"()()\" form a correct bracket sequence, while \")(\" and \"((\" not.\n\nAki then came up with an interesting problem: What is the size of the maximum matching (the largest set of edges such that there are no two edges with a common vertex) in this trie? Since the answer can be quite large, print it modulo $10^9 + 7$.",
    "tutorial": "Note, that many subtrees of the trie are equal. Basically, if we consider two vertices on the same depth and having the same balance from root to them (that is, the number of opening brackets minus the number of closing brackets), than their subtrees will be entirely same. For example, the subtrees after following $((())$, $()()($ and $(())($ are all the same. We will use this observation to consider the tree in \"compressed\" form. Clearly, this way there are only $O(n^2)$ different vertices types (basically a vertex is described by $(depth, balance)$). Now let's get back to finding a maximum matching in the tree. There are two approaches to this problem. One of them is greedy. Basically if you find a matching in a tree you can always greedily take the edge between a leaf and its parent (since this adds one edge to the answer and destroys at most one edge you would've chosen). This idea can transform into the following algorithm (for the problem of the maximum matching in the tree). Do a dynamic programming on the subtrees, the result of $dp[v]$ is a pair of \"number of edges taken in subtree, whether the root of this subtree is free (so we can start a new edge upwards)\". Combining this with the idea that there are little ($n^2$) number of vertex types, we get a dp solution.",
    "code": "// Dmitry _kun_ Sayutin (2019)\n\n#include <bits/stdc++.h>\n\nusing std::cin;\nusing std::cout;\nusing std::cerr;\n\nusing std::vector;\nusing std::map;\nusing std::array;\nusing std::set;\nusing std::string;\n\nusing std::pair;\nusing std::make_pair;\n\nusing std::tuple;\nusing std::make_tuple;\nusing std::get;\n\nusing std::min;\nusing std::abs;\nusing std::max;\nusing std::swap;\n\nusing std::unique;\nusing std::sort;\nusing std::generate;\nusing std::reverse;\nusing std::min_element;\nusing std::max_element;\n\n#ifdef LOCAL\n#define LASSERT(X) assert(X)\n#else\n#define LASSERT(X) {}\n#endif\n\ntemplate <typename T>\nT input() {\n    T res;\n    cin >> res;\n    LASSERT(cin);\n    return res;\n}\n\ntemplate <typename IT>\nvoid input_seq(IT b, IT e) {\n    std::generate(b, e, input<typename std::remove_reference<decltype(*b)>::type>);\n}\n\n#define SZ(vec)         int((vec).size())\n#define ALL(data)       data.begin(),data.end()\n#define RALL(data)      data.rbegin(),data.rend()\n#define TYPEMAX(type)   std::numeric_limits<type>::max()\n#define TYPEMIN(type)   std::numeric_limits<type>::min()\n\nconst int mod = 1000 * 1000 * 1000 + 7;\nint add(int a, int b) {\n    return (a + b >= mod ? a + b - mod : a + b);\n}\n\nconst int max_n = 1001;\npair<int, bool> dp[2 * max_n][2 * max_n];\n\nint main() {\n    std::iostream::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    // code here\n    int n = input<int>();\n    n *= 2;\n\n    assert(n / 2 < max_n);\n        \n    \n    dp[0][0] = make_pair(0, true);\n    \n    for (int len = 1; len <= n; ++len) {\n        for (int bal = 0; bal <= n; ++bal) {\n            // (len, bal) -> (len - 1, bal + 1)\n            // (len, bal) -> (len - 1, bal - 1)\n\n            int sum = 0;\n            bool has = false;\n\n            if (bal != 0) {\n                sum = add(sum, dp[len - 1][bal - 1].first);\n                has = has or dp[len - 1][bal - 1].second;\n            }\n\n            if (bal + 1 <= len - 1) {\n                sum = add(sum, dp[len - 1][bal + 1].first);\n                has = has or dp[len - 1][bal + 1].second;\n            }\n\n            if (has)\n                dp[len][bal] = make_pair(add(sum, 1), false);\n            else\n                dp[len][bal] = make_pair(sum, true);\n        }\n    }\n    \n    cout << dp[n][0].first << \"\\n\";\n    \n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1152",
    "index": "E",
    "title": "Neko and Flashback",
    "statement": "A permutation of length $k$ is a sequence of $k$ integers from $1$ to $k$ containing each integer exactly once. For example, the sequence $[3, 1, 2]$ is a permutation of length $3$.\n\nWhen Neko was five, he thought of an array $a$ of $n$ positive integers and a permutation $p$ of length $n - 1$. Then, he performed the following:\n\n- Constructed an array $b$ of length $n-1$, where $b_i = \\min(a_i, a_{i+1})$.\n- Constructed an array $c$ of length $n-1$, where $c_i = \\max(a_i, a_{i+1})$.\n- Constructed an array $b'$ of length $n-1$, where $b'_i = b_{p_i}$.\n- Constructed an array $c'$ of length $n-1$, where $c'_i = c_{p_i}$.\n\nFor example, if the array $a$ was $[3, 4, 6, 5, 7]$ and permutation $p$ was $[2, 4, 1, 3]$, then Neko would have constructed the following arrays:\n\n- $b = [3, 4, 5, 5]$\n- $c = [4, 6, 6, 7]$\n- $b' = [4, 5, 3, 5]$\n- $c' = [6, 7, 4, 6]$\n\nThen, he wrote two arrays $b'$ and $c'$ on a piece of paper and forgot about it. 14 years later, when he was cleaning up his room, he discovered this old piece of paper with two arrays $b'$ and $c'$ written on it. However he can't remember the array $a$ and permutation $p$ he used.\n\nIn case Neko made a mistake and there is no array $a$ and permutation $p$ resulting in such $b'$ and $c'$, print -1. Otherwise, help him recover any possible array $a$.",
    "tutorial": "Obviously, if $b'_i > c'_i$ for some $i$, then the answer is \"-1\". From the statement, we have $b_i = \\min(a_i, a_{i+1})$ and $c_i = \\max(a_i, a_{i+1})$. For this to happen, either one of the following must happen: $a_i = b_i$ and $a_{i+1} = c_i$ $a_i = c_i$ and $a_{i+1} = b_i$ In order word, one of the two following pairs - $(b_i, c_i)$ or $(c_i, b_i)$ - will match the pair $(a_i, a_{i+1})$. From the statement, we also have $b'_i = b_{p_i}$ and $c'_i = c_{p_i}$. Therefore, one of the two following pairs - $(b'_i, c'_i)$ or $(c'_i, b'_i)$ - will match the pair $(a_{p_i}, a_{p_{i+1}})$ Consider a graph $G$ with $10^9$ vertices. For each $i$ from $1$ to $n-1$, we will add an undirected edge between $b'_i$ and $c'_i$. The following figure show such graph $G$ for the third example. Consider the path $P = a_1 \\rightarrow a_2 \\rightarrow a_3 \\rightarrow \\ldots \\rightarrow a_n$. Each edge $(b'_i, c'_i)$ will correspond to exactly one edge between $a_j$ and $a_{j+1}$ for some j. In other word, $P$ correspond to an Eulerian path on the graph $G$. The following figure show the path $P = 3 \\rightarrow 4 \\rightarrow 5 \\rightarrow 2 \\rightarrow 1 \\rightarrow 4 \\rightarrow 3 \\rightarrow 2$ for the third example. For implementation, we need to do the following step: For all elements of $b'$ and $c'$, we need to replace them with corresponding value from $1$ to $k$ (where $k$ is the number of distinct value in $b'$ and $c'$). This part can be done using an balanced BST (C++ 'map' or Java 'TreeMap') or by sorting in $O(n \\log n)$. Build the graph $G$ as above Finding an Eulerian path in $G$ using Hierholzer's_algorithm in $O(n)$, or detect that such path does not exists. Complexity: $O(n \\log n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\n\nclass Indexer {\nprivate:\n    map<int, int> id;\n    vector<int> num;\n\npublic:\n    int getId(int x) {\n        if (!id.count(x)) {\n            id[x] = num.size();\n            num.push_back(x);\n        }\n        return id[x];\n    }\n\n    int getNum(int id) {\n        return num[id];\n    }\n\n    int size() {\n        return id.size();\n    }\n};\n\nstruct Edge {\n    int u, v;\n    bool avail;\n};\n\nclass Graph {\nprivate:\n    int n;\n    vector<Edge> e;\n    vector<vector<int> > adj;\n\n    vector<int> pos;\n    list<int> path;\n\n    void dfs(list<int>::iterator it, int u) {\n        for(; pos[u] < adj[u].size(); ++pos[u]) {\n            int id = adj[u][pos[u]];\n            if (e[id].avail) {\n                e[id].avail = false;\n                int v = e[id].u + e[id].v - u;\n                dfs(path.insert(it, u), v);\n            }\n        }\n    }\n\npublic:\n    Graph(int n): n(n) {\n        adj.assign(n, vector<int>());\n    }\n\n    void addEdge(int u, int v) {\n        adj[u].push_back(e.size());\n        adj[v].push_back(e.size());\n        e.push_back({u, v, false});\n    }\n\n    vector<int> eulerPath() {\n        for(Edge &p: e)\n            p.avail = true;\n        path.clear();\n        pos.assign(n, 0);\n\n        vector<int> odd;\n        for(int u = 0; u < n; ++u)\n            if (adj[u].size() % 2 == 1)\n                odd.push_back(u);\n        if (odd.empty()) {\n            odd.push_back(0);\n            odd.push_back(0);\n        }\n\n        if (odd.size() > 2)\n            return vector<int>();\n        dfs(path.begin(), odd[0]);\n        path.insert(path.begin(), odd[1]);\n\n        return vector<int>(path.begin(), path.end());\n    }\n};\n\nint main() {\n    int n;\n    scanf(\"%d\", &n);\n\n    vector<int> bprime(n-1);\n    for(int i = 0; i < n-1; ++i)\n        scanf(\"%d\", &bprime[i]);\n\n    vector<int> cprime(n-1);\n    for(int i = 0; i < n-1; ++i)\n        scanf(\"%d\", &cprime[i]);\n\n    Indexer ind;\n    for(int i = 0; i < n-1; ++i) {\n        if (bprime[i] > cprime[i]) {\n            puts(\"-1\");\n            return 0;\n        }\n\n        bprime[i] = ind.getId(bprime[i]);\n        cprime[i] = ind.getId(cprime[i]);\n    }\n\n    int k = ind.size();\n    Graph g(k);\n    for(int i = 0; i < n-1; ++i)\n        g.addEdge(bprime[i], cprime[i]);\n\n    vector<int> a = g.eulerPath();\n\n    if (a.size() < n)\n        puts(\"-1\");\n    else {\n        for(int i = 0; i < n; ++i)\n            printf(\"%d \", ind.getNum(a[i]));\n        puts(\"\");\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1152",
    "index": "F1",
    "title": "Neko Rules the Catniverse (Small Version)",
    "statement": "This problem is same as the next one, but has smaller constraints.\n\nAki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.\n\nThere are $n$ planets in the Catniverse, numbered from $1$ to $n$. At the beginning of the game, Aki chooses the planet where Neko is initially located. Then Aki performs $k - 1$ moves, where in each move Neko is moved from the current planet $x$ to some other planet $y$ such that:\n\n- Planet $y$ is not visited yet.\n- $1 \\leq y \\leq x + m$ (where $m$ is a fixed constant given in the input)\n\nThis way, Neko will visit exactly $k$ different planets. Two ways of visiting planets are called different if there is some index $i$ such that the $i$-th planet visited in the first way is different from the $i$-th planet visited in the second way.\n\nWhat is the total number of ways to visit $k$ planets this way? Since the answer can be quite large, print it modulo $10^9 + 7$.",
    "tutorial": "As the problem stated, from planet $x$ we can go backwards any to any planet $y$ such that $y < x$. This implies an idea of considering the planets from $n$ to $1$, then deciding whether to insert each planet to the current path or not. Formally, if our current path is $v_1, v_2, \\dots, v_p$ and we are going to insert planet $x$ somewhere ($x < v_i$ for all $i$), we can either insert it into the back, or insert it before some planet $v_i$ such that $v_i \\le x + m$. Therefore, we can use dynamic programming with the parameters being: the planet being considered, the number of planets chosen so far, and the bitmask of the last $m$ planets (whether each of them is chosen or not). The transition is straightforward: either we don't choose the planet, or we choose it and there are $1 + bitcount(mask)$ ways to insert the planet into the path. Total complexity: $\\mathcal{O} \\left( nk \\cdot 2^m \\right)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 1000000007;\n \nvoid add(int &a, long long b) {\n    a = (a + b) % MOD;\n}\n \nint main() {\n    int n, k, m;\n    scanf(\"%d%d%d\", &n, &k, &m);\n \n    vector<vector<vector<int>>> dp(n+1, vector<vector<int>>(k+1, vector<int>(1<<m, 0)));\n    dp[0][0][0] = 1;\n \n    for(int i = 0; i < n; ++i) {\n        for(int j = 0; j <= k; ++j) {\n            for(int mask = 0; mask < (1<<m); ++mask) {\n                int newMask = (mask << 1) % (1<<m);\n \n                // Not visit planet i+1\n                add(dp[i+1][j][newMask], dp[i][j][mask]);\n \n                // Visit planet i+1\n                if (j < k) {\n                    int insertWays = __builtin_popcount(mask) + 1;\n                    add(dp[i+1][j+1][newMask|1], 1LL*insertWays*dp[i][j][mask]);\n                }\n            }\n        }\n    }\n \n    int ans = 0;\n    for(int mask = 0; mask < (1<<m); ++mask)\n        add(ans, dp[n][k][mask]);\n \n    printf(\"%d\", ans);\n}",
    "tags": [
      "bitmasks",
      "dp",
      "matrices"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1152",
    "index": "F2",
    "title": "Neko Rules the Catniverse (Large Version)",
    "statement": "This problem is same as the previous one, but has larger constraints.\n\nAki is playing a new video game. In the video game, he will control Neko, the giant cat, to fly between planets in the Catniverse.\n\nThere are $n$ planets in the Catniverse, numbered from $1$ to $n$. At the beginning of the game, Aki chooses the planet where Neko is initially located. Then Aki performs $k - 1$ moves, where in each move Neko is moved from the current planet $x$ to some other planet $y$ such that:\n\n- Planet $y$ is not visited yet.\n- $1 \\leq y \\leq x + m$ (where $m$ is a fixed constant given in the input)\n\nThis way, Neko will visit exactly $k$ different planets. Two ways of visiting planets are called different if there is some index $i$ such that, the $i$-th planet visited in the first way is different from the $i$-th planet visited in the second way.\n\nWhat is the total number of ways to visit $k$ planets this way? Since the answer can be quite large, print it modulo $10^9 + 7$.",
    "tutorial": "The core idea is similar to F1, however there is one crucial observation. We can see that all DP transitions are just linear transformations, thus we can construct a transition matrix of size $k \\cdot 2^m$, then use fast matrix exponentiation as a replacement of the original DP transitions. Total complexity: $\\mathcal{O} \\left( \\log(n) \\cdot {\\left( k \\cdot 2^m \\right)}^3 \\right)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 1000000007;\n \nvoid add(int &a, long long b) {\n    a = (a + b) % MOD;\n}\n \nstruct Matrix {\n    vector<vector<int>> a;\n    int n, m;\n \n    Matrix(int n, int m): n(n), m(m) {\n        a.assign(n, vector<int>(m, 0));\n    }\n \n    friend Matrix operator * (Matrix a, Matrix b) {\n        Matrix c(a.n, b.m);\n        for(int i = 0; i < a.n; ++i)\n            for(int j = 0; j < b.m; ++j)\n                for(int k = 0; k < a.m; ++k)\n                    add(c.a[i][j], 1LL * a.a[i][k] * b.a[k][j]);\n        return c;\n    }\n};\n \nMatrix identity(int n) {\n    Matrix res(n, n);\n    for(int i = 0; i < n; ++i)\n        res.a[i][i] = 1;\n    return res;\n}\n \nvoid power(Matrix &a, int n, Matrix &b) {\n    while (n > 0) {\n        if (n&1) b = a * b;\n        a = a * a;\n        n >>= 1;\n    }\n}\n \nint n, k, m;\n \nint toId(int j, int mask) {\n    return j * (1<<m) + mask;\n}\n \nint main() {\n    scanf(\"%d%d%d\", &n, &k, &m);\n \n    Matrix dp((k+1) * (1<<m), 1);\n    dp.a[0][0] = 1;\n \n    Matrix f((k+1) * (1<<m), (k+1) * (1<<m));\n \n    for(int j = 0; j <= k; ++j) {\n        for(int mask = 0; mask < (1<<m); ++mask) {\n            int newMask = (mask << 1) % (1<<m);\n            int cur = toId(j, mask);\n \n            f.a[toId(j, newMask)][cur] = 1;\n            if (j < k)\n                f.a[toId(j+1, newMask|1)][cur] = __builtin_popcount(mask) + 1;\n        }\n    }\n \n    power(f, n, dp);\n \n    int ans = 0;\n    for(int mask = 0; mask < (1<<m); ++mask)\n        add(ans, dp.a[toId(k, mask)][0]);\n \n    printf(\"%d\", ans);\n}",
    "tags": [
      "bitmasks",
      "dp",
      "matrices"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1153",
    "index": "A",
    "title": "Serval and Bus",
    "statement": "It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.\n\nServal will go to the bus station at time $t$, and there are $n$ bus routes which stop at this station. For the $i$-th bus route, the first bus arrives at time $s_i$ minutes, and each bus of this route comes $d_i$ minutes later than the previous one.\n\nAs Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.",
    "tutorial": "Find the first bus Serval can see in each route and find the earliest one. For each route, finding the first bus Serval sees can work in $O(1)$. Or mark all the time no more than $\\max(s_i,t+\\max(d_i))$ which bus would come or there will be no bus, then search the nearest one.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1153",
    "index": "B",
    "title": "Serval and Toy Bricks",
    "statement": "Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.\n\nHe has a special interest to create difficult problems for others to solve. This time, with many $1 \\times 1 \\times 1$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $n \\times m$ matrix, such that in each cell $(i,j)$, there are $h_{i,j}$ bricks standing on the top of each other.\n\nHowever, Serval doesn't give you any $h_{i,j}$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $m$ columns, and in the $i$-th of them, the height is the maximum of $h_{1,i},h_{2,i},\\dots,h_{n,i}$. It is similar for the left view, where there are $n$ columns. And in the top view, there is an $n \\times m$ matrix $t_{i,j}$, where $t_{i,j}$ is $0$ or $1$. If $t_{i,j}$ equals $1$, that means $h_{i,j}>0$, otherwise, $h_{i,j}=0$.\n\nHowever, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?",
    "tutorial": "Fill in all the bricks, and then remove all bricks you must remove (which in some view, there is empty). This can be solved in $O(nm)$.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1153",
    "index": "C",
    "title": "Serval and Parenthesis Sequence",
    "statement": "Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.\n\nIn his favorite math class, the teacher taught him the following interesting definitions.\n\nA parenthesis sequence is a string, containing only characters \"(\" and \")\".\n\nA correct parenthesis sequence is a parenthesis sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, parenthesis sequences \"()()\", \"(())\" are correct (the resulting expressions are: \"(1+1)+(1+1)\", \"((1+1)+1)\"), while \")(\" and \")\" are not. Note that the empty string is a correct parenthesis sequence by definition.\n\nWe define that $|s|$ as the length of string $s$. A strict prefix $s[1\\dots l]$ $(1\\leq l< |s|)$ of a string $s = s_1s_2\\dots s_{|s|}$ is string $s_1s_2\\dots s_l$. Note that the empty string and the whole string are not strict prefixes of any string by the definition.\n\nHaving learned these definitions, he comes up with a new problem. He writes down a string $s$ containing only characters \"(\", \")\" and \"?\". And what he is going to do, is to replace each of the \"?\" in $s$ independently by one of \"(\" and \")\" to make all strict prefixes of the new sequence not a correct parenthesis sequence, while the new sequence should be a correct parenthesis sequence.\n\nAfter all, he is just a primary school student so this problem is too hard for him to solve. As his best friend, can you help him to replace the question marks? If there are many solutions, any of them is acceptable.",
    "tutorial": "First let ( be $+1$, ) be $-1$ and ? be a missing place, so we will replace all the missing places in the new $+1$,$-1$ sequence by $+1$ and $-1$. Obviously, for each prefix of a correct parenthesis sequence, the sum of the new $+1$,$-1$ sequence is not less than $0$. And for the correct parenthesis sequence itself, the sum of the new sequence should be $0$. So we can calculate how many $+1$ (let $a$ denotes it) and how many $-1$ (let $b$ denotes it) that we should fill in the missing places. According to the problem, our goal is to fill the missing place with $+1$ and $-1$ to make sure there is no strict prefix (prefixes except the whole sequence itself) exists with the sum equal to $0$. This can be solved in greedy. We want the sum of prefixes as large as possible to avoid the sum touching $0$. So let the first $a$ missing places be filled with $+1$ and the last $b$ missing places be filled with $-1$. Check it whether it is a correct parenthesis sequence or not at last. The complexity is $O(n)$.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1153",
    "index": "D",
    "title": "Serval and Rooted Tree",
    "statement": "Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before.\n\nAs a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.\n\nA tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node $v$ is the last different from $v$ vertex on the path from the root to the vertex $v$. Children of vertex $v$ are all nodes for which $v$ is the parent. A vertex is a leaf if it has no children.\n\nThe rooted tree Serval owns has $n$ nodes, node $1$ is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation $\\max$ or $\\min$ written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively.\n\nAssume that there are $k$ leaves in the tree. Serval wants to put integers $1, 2, \\ldots, k$ to the $k$ leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?",
    "tutorial": "If we want to check whether $x$ is the answer (I didn't say I want to do binary search), then we can set all the numbers no less than $x$ as $1$, and the numbers less than $x$ as $0$. Then we can use $dp_i$ to represent that the maximum number on node $i$ is the $dp_i$-th smallest number of leaves within subtree of $i$. There should be at least $dp_i$ ones in the subtree of $i$ such that the number on $i$ is one. Then $k+1-dp_1$ is the final answer. Complexity $O(n)$. We can solve this problem in greedy. At first we use $leaf_u$ to represent the number of leaves in the subtree whose root is $u$, and $f_u$ to represent the maximum number we can get on the node $u$. Note that since we are concidering the subtree of $u$, we just number those $leaf_u$ nodes from $1$ to $leaf_u$, and $f_u$ is between $1$ and $leaf_u$, too. Let's think how to find the maximum number a node can get. If the operation of the node $u$ we concerned is $\\max$, for all the nodes $v$ whose father or parent is $u$, we can find the minimum $leaf_v-f_v$. Let $v_{min}$ denotes the node reaches the minimum. And we can construct an arrangement so that the number written in the node $u$ can be $leaf_u-(leaf_{v_{min}}-f_{v_{min}})$. When we number the leaves in the subtree of $u$ from $1$ to $leaf_u$, we number the leaves in other subtrees of children of $u$ first, and then number the leaves in subtree of $v_{min}$. It can be proved this arrangement is optimal. If the operation of the node $u$ we concerned is $\\max$, for all the nodes $v$ whose father or parent is $u$, we can find the minimum $leaf_v-f_v$. Let $v_{min}$ denotes the node reaches the minimum. And we can construct an arrangement so that the number written in the node $u$ can be $leaf_u-(leaf_{v_{min}}-f_{v_{min}})$. When we number the leaves in the subtree of $u$ from $1$ to $leaf_u$, we number the leaves in other subtrees of children of $u$ first, and then number the leaves in subtree of $v_{min}$. It can be proved this arrangement is optimal. If the operation of the node $u$ is $\\min$, we can construct an arrangement of the numbers written in the leaves to make the number written in $u$ be as large as possible. For all sons or children $v$ of $u$, we number the first $f_v-1$ leaves in subtree of $v$ first according to the optimal arrangement of the node $v$. And then no matter how we arrange the remaining numbers, the number written in $u$ is $1+\\sum_{v \\text{ is a son of } u} (f_v-1)$. This is the optimal arrangement. If the operation of the node $u$ is $\\min$, we can construct an arrangement of the numbers written in the leaves to make the number written in $u$ be as large as possible. For all sons or children $v$ of $u$, we number the first $f_v-1$ leaves in subtree of $v$ first according to the optimal arrangement of the node $v$. And then no matter how we arrange the remaining numbers, the number written in $u$ is $1+\\sum_{v \\text{ is a son of } u} (f_v-1)$. This is the optimal arrangement. We can use this method and get the final answer $f_1$.",
    "code": "#include <cstdio>\nusing namespace std;\nconst int N=1000005;\nint n,p;\nint h[N],nx[N];\nint t[N],sz[N];\nvoid getsize(int u)\n{\n\tif (!h[u])\n\t\tsz[u]++;\n\tfor (int i=h[u];i;i=nx[i])\n\t{\n\t\tgetsize(i);\n\t\tsz[u]+=sz[i];\n\t}\n}\nint getans(int u)\n{\n\tif (!h[u])\n\t\treturn 1;\n\tint ret=0,tmp;\n\tif (t[u])\n\t{\n\t\tfor (int i=h[u];i;i=nx[i])\n\t\t{\n\t\t\ttmp=getans(i)+sz[u]-sz[i];\n\t\t\tif (tmp>ret)\n\t\t\t\tret=tmp;\n\t\t}\n\t\treturn ret;\n\t}\n\tfor (int i=h[u];i;i=nx[i])\n\t\tret+=getans(i)-1;\n\treturn ret+1;\n}\nint main()\n{\n\tscanf(\"%d\",&n);\n\tfor (int i=1;i<=n;i++)\n\t\tscanf(\"%d\",&t[i]);\n\tfor (int i=2;i<=n;i++)\n\t{\n\t\tscanf(\"%d\",&p);\n\t\tnx[i]=h[p];\n\t\th[p]=i;\n\t}\n\tgetsize(1);\n\tprintf(\"%d\\n\",getans(1));\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1153",
    "index": "E",
    "title": "Serval and Snake",
    "statement": "This is an interactive problem.\n\nNow Serval is a senior high school student in Japari Middle School. However, on the way to the school, he must go across a pond, in which there is a dangerous snake. The pond can be represented as a $n \\times n$ grid. The snake has a head and a tail in different cells, and its body is a series of adjacent cells connecting the head and the tail without self-intersecting. If Serval hits its head or tail, the snake will bite him and he will die.\n\nLuckily, he has a special device which can answer the following question: you can pick a rectangle, it will tell you the number of times one needs to cross the border of the rectangle walking cell by cell along the snake from the head to the tail. The pictures below show a possible snake and a possible query to it, which will get an answer of $4$.\n\nToday Serval got up too late and only have time to make $2019$ queries. As his best friend, can you help him find the positions of the head and the tail?\n\nNote that two cells are adjacent if and only if they have a common edge in the grid, and a snake can have a body of length $0$, that means it only has adjacent head and tail.\n\nAlso note that the snake is sleeping, so it won't move while Serval using his device. And what's obvious is that the snake position does not depend on your queries.",
    "tutorial": "If the answer to a rectangle is odd, there must be exactly one head or tail in that rectangle. Otherwise, there must be even number ($0$ or $2$) of head and tail in the given rectangle. We make queries for each of the columns except the last one, then we can know for each column whether there are odd number of head and tails in it or not. Because the sum is even, we can know the parity of the last column. If the head and tail are in different columns, we can find two columns with odd answer and get them. Then we can do binary search for each of those two columns separately and get the answer in no more than $999+10+10=1019$ queries totally. If the head and tail are in the same column, we will get all even answer and know that fact. Then we apply the same method for rows. Then we can just do binary search for one of the rows, and use the fact that the other is in the same column as this one. In this case, we have made no more than $999+999+10=2008$ queries. How to save one more query? We first make queries for row $2$ to row $n-1$. If we find any ones, make the last query for row, and use the method above. If we cannot find any ones, we make $n-1$ queries for columns. If none of them provide one, we know that for row $1$ and row $n$, there must be exactly one head or tail in them, and they are in the same column. In this case, we do binary search for one of the rows, then the total number of queries is $998+999+10=2007$. If we can find two ones in the columns, we know that: if one of them is in row $2$ to row $n-1$, the other must be in the same row, because for row $2$ to row $n$, we know that there are even number of head and tails, and them can't appear in the other columns. Then we do binary search, when we divide the length into two halves, we let the one close the the middle to be the longer one, and the one close to one end to be the shorter one. Then, if it turns out that, the answer is in row $1$ (or row $n$), the number of queries must be $\\log n$ rounded down, and we can use one more query to identify, whether the head or tail in the other column is in row $1$ or row $n$. If it turns out that, the answer is in one of the rows in row $2$ to row $n$, we may used $\\log n$ queries rounded up, but in this case, we don't need that extra query. So the total number of queries is $999+998+9+1=2007$ (or $999+998+10=2007$). In fact, if the interactor is not adaptive and we query for columns and rows randomly, we can use far less than $2007$ queries. And if we query for rows and columns alternatively, we can save more queries.",
    "tags": [
      "binary search",
      "brute force",
      "interactive"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1153",
    "index": "F",
    "title": "Serval and Bonus Problem",
    "statement": "Getting closer and closer to a mathematician, Serval becomes a university student on math major in Japari University. On the Calculus class, his teacher taught him how to calculate the expected length of a random subsegment of a given segment. Then he left a bonus problem as homework, with the award of a garage kit from IOI. The bonus is to extend this problem to the general case as follows.\n\nYou are given a segment with length $l$. We randomly choose $n$ segments by choosing two points (maybe with non-integer coordinates) from the given segment equiprobably and the interval between the two points forms a segment. You are given the number of random segments $n$, and another integer $k$. The $2n$ endpoints of the chosen segments split the segment into $(2n+1)$ intervals. Your task is to calculate the expected total length of those intervals that are covered by at least $k$ segments of the $n$ random segments.\n\nYou should find the answer modulo $998244353$.",
    "tutorial": "Without loss of generality, assume that $l=1$. For a segment covering, the total length of the legal intervals is the probability that we choose another point $P$ on this segment randomly such that it is in the legal intervals. Since all $2n+1$ points ($P$ and the endpoints of each segment) are chosen randomly and independently, we only need to find the probability that point $P$ is in the legal intervals. Note that only the order of these $2n+1$ points make sense. Because the points are chosen in the segment, the probability that some of them coincide is $0$, so we can assume that all points do not coincide. Now the problem is, how to calculate the number of arrangements that $P$ is between at least $k$ pairs of endpoints. It can be solved by dynamic programming in time complexity of $O(n^2)$. We define $f(i,j,x)$ as the number of arrangements for the first $i$ positions, with $j$ points haven't been matched, and $P$ appeared $x$ times (obviously $x=0$ or $1$). So we can get three different types of transition for the $i$-th position below: Place $P$ at $i$-th position (if $j\\geq k$): $f(i-1,j,0)\\rightarrow f(i,j,1)$ Start a new segment (if $i+j+x<2n$): $f(i-1,j-1,x)\\rightarrow f(i,j,x)$ Match a started segment, note that we have $j$ choices of segments: $f(i-1,j+1,x)\\times (j+1)\\rightarrow f(i,j,x)$ Then $f(2n+1,0,1)$ is the number of legal arrangements. Obviously, the total number of arrangements is $(2n+1)!$. However, there are $n$ pairs of endpoints whose indices can be swapped, and the indices $n$ segments can be rearranged. So the final answer is $\\frac{f(2n+1,0,1)\\times n! \\times 2^n}{(2n+1)!}$.",
    "code": "#include <cstdio>\nusing namespace std;\nconst int mod=998244353;\nconst int N=4005;\nconst int K=2005;\nint n,k,l;\nint fac,ans;\nint f[N][K][2];\nint fpw(int b,int e=mod-2)\n{\n\tif (!e)\n\t\treturn 1;\n\tint ret=fpw(b,e>>1);\n\tret=1ll*ret*ret%mod;\n\tif (e&1)\n\t\tret=1ll*ret*b%mod;\n\treturn ret;\n}\nint main()\n{\n\tscanf(\"%d%d%d\",&n,&k,&l);\n\tf[0][0][0]=1;\n\tfor (int i=1;i<=2*n+1;i++)\n\t\tfor (int j=0;j<=n;j++)\n\t\t\tfor (int x=0;x<=1;x++)\n\t\t\t\tif (f[i-1][j][x])\n\t\t\t\t{\n\t\t\t\t\tif (j)\n\t\t\t\t\t\tf[i][j-1][x]=(f[i][j-1][x]+1ll*f[i-1][j][x]*j)%mod;\n\t\t\t\t\tif (i+j-1<2*n+x)\n\t\t\t\t\t\tf[i][j+1][x]=(f[i][j+1][x]+f[i-1][j][x])%mod;\n\t\t\t\t\tif (j>=k&&!x)\n\t\t\t\t\t\tf[i][j][1]=(f[i][j][1]+f[i-1][j][x])%mod;\n\t\t\t\t}\n\tfac=1;\n\tfor (int i=n+1;i<=2*n+1;i++)\n\t\tfac=1ll*fac*i%mod;\n\tans=f[2*n+1][0][1];\n\tans=1ll*ans*fpw(2,n)%mod;\n\tans=1ll*ans*fpw(fac)%mod*l%mod;\n\tprintf(\"%d\\n\",ans);\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1154",
    "index": "A",
    "title": "Restoring Three Numbers",
    "statement": "Polycarp has guessed three positive integers $a$, $b$ and $c$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $a+b$, $a+c$, $b+c$ and $a+b+c$.\n\nYou have to guess three numbers $a$, $b$ and $c$ using given numbers. Print three guessed integers in any order.\n\nPay attention that some given numbers $a$, $b$ and $c$ can be equal (it is also possible that $a=b=c$).",
    "tutorial": "Let $x_1 = a + b$, $x_2 = a + c$, $x_3 = b = c$ and $x_4 = a + b + c$. Then we can construct the following answer: $c = x_4 - x_1$, $b = x_4 - x_2$ and $a = x_4 - x_3$. Because all numbers in the answer are positive, we can assume that the maximum element of $x$ is $a + b + c$. So let's sort the input array $x$ consisting of four elements and just print $x_4 - x_1, x_4 - x_2$ and $x_4 - x_3$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tvector<int> a(4);\n\tfor (int i = 0; i < 4; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.begin(), a.end());\n\tcout << a[3] - a[0] << \" \" << a[3] - a[1] << \" \" << a[3] - a[2] << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1154",
    "index": "B",
    "title": "Make Them Equal",
    "statement": "You are given a sequence $a_1, a_2, \\dots, a_n$ consisting of $n$ integers.\n\nYou can choose any non-negative integer $D$ (i.e. $D \\ge 0$), and for each $a_i$ you can:\n\n- add $D$ (only once), i. e. perform $a_i := a_i + D$, or\n- subtract $D$ (only once), i. e. perform $a_i := a_i - D$, or\n- leave the value of $a_i$ unchanged.\n\nIt is possible that after an operation the value $a_i$ becomes negative.\n\nYour goal is to choose such \\textbf{minimum non-negative integer} $D$ and perform changes in such a way, that all $a_i$ are equal (i.e. $a_1=a_2=\\dots=a_n$).\n\nPrint the required $D$ or, if it is impossible to choose such value $D$, print -1.\n\nFor example, for array $[2, 8]$ the value $D=3$ is minimum possible because you can obtain the array $[5, 5]$ if you will add $D$ to $2$ and subtract $D$ from $8$. And for array $[1, 4, 7, 7]$ the value $D=3$ is also minimum possible. You can add it to $1$ and subtract it from $7$ and obtain the array $[4, 4, 4, 4]$.",
    "tutorial": "Let's leave only unique values of the given array in the array $b$ (i. e. construct an array $b$ that is actually array $a$ without duplicate element) and sort it in ascending order. Then let's consider the following cases: If the length of $b$ is greater than $3$ then the answer is -1; if the length of $b$ is $3$ then there are two cases: if $b_3 - b_2 = b_2 - b_1$ then the answer is $b_2 - b_1$; otherwise the answer is -1; if $b_3 - b_2 = b_2 - b_1$ then the answer is $b_2 - b_1$; otherwise the answer is -1; if the length of $b$ is $2$ then there are also two cases: if $b_2 - b_1$ is even then the answer is $\\frac{b_2 - b_1}{2}$; otherwise the answer is $b_2 - b_1$; if $b_2 - b_1$ is even then the answer is $\\frac{b_2 - b_1}{2}$; otherwise the answer is $b_2 - b_1$; and if the length of $b$ is $1$ then the answer is $0$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.begin(), a.end());\n\ta.resize(unique(a.begin(), a.end()) - a.begin());\n\tif (a.size() > 3) {\n\t\tcout << -1 << endl;\n\t} else {\n\t\tif (a.size() == 1) {\n\t\t\tcout << 0 << endl;\n\t\t} else if (a.size() == 2) {\n\t\t\tif ((a[1] - a[0]) % 2 == 0) {\n\t\t\t\tcout << (a[1] - a[0]) / 2 << endl;\n\t\t\t} else {\n\t\t\t\tcout << a[1] - a[0] << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tif (a[1] - a[0] != a[2] - a[1]) {\n\t\t\t\tcout << -1 << endl;\n\t\t\t} else {\n\t\t\t\tcout << a[1] - a[0] << endl;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1154",
    "index": "C",
    "title": "Gourmet Cat",
    "statement": "Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:\n\n- on Mondays, Thursdays and Sundays he eats fish food;\n- on Tuesdays and Saturdays he eats rabbit stew;\n- on other days of week he eats chicken stake.\n\nPolycarp plans to go on a trip and already packed his backpack. His backpack contains:\n\n- $a$ daily rations of fish food;\n- $b$ daily rations of rabbit stew;\n- $c$ daily rations of chicken stakes.\n\nPolycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.",
    "tutorial": "Let the number of rations of fish food be $a_1$, the number of rations of rabbit stew be $a_2$ and the number of rations of chicken stakes be $a_3$ (so we have an array $a$ consisting of $3$ elements). Let $full$ be the maximum number of full weeks cat can eat if the starting day of the trip can be any day of the week. The value of $full$ is $min(\\lfloor\\frac{a_1}{3}\\rfloor, \\lfloor\\frac{a_2}{2}\\rfloor, \\lfloor\\frac{a_3}{2}\\rfloor)$. Let's subtract the value $3 \\cdot full$ from $a_1$, and $2 \\cdot full$ from $a_2$ and $a_3$. We can see that we cannot feed the cat at least one more full week. So the final answer is $7 \\cdot full + add$, where $add < 7$. Now it's time for some good implementation! Of course, you can try to analyze all cases and handle them using ifs or something similar, but I will try to suggest you a good enough way to implement the remaining part of the problem: Let's create an array $idx$ of length $7$, where $idx_i$ means the type of the food cat eats during the $i$-th day of the week ($1$ for fish food, $2$ for rabbit stew and $3$ for chicken stake). It will be $idx = [1, 2, 3, 1, 3, 2, 1]$. Now let's iterate over the day we will start our trip. Let it be $start$. For the current starting day let $cur$ be the number of rations cat has eaten already (initially it is zero), $day$ be the current day of the trip (initially it is $start$) and the array $b$ be the copy of the array $a$. Then let's do the following sequence of the operations, while $b_{idx_{day}}$ is greater than zero: decrease $b_{idx_{day}}$ by one, increase $cur$ by one and set $day := day \\% 7 + 1$ (take it modulo $7$ and add one). After this cycle we can update the answer with the value of $7 \\cdot full + cur$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tvector<int> a(3);\n\tcin >> a[0] >> a[1] >> a[2];\n\t\n\tvector<int> idx({0, 1, 2, 0, 2, 1, 0});\n\t\n\tint full = min({a[0] / 3, a[1] / 2, a[2] / 2});\n\ta[0] -= full * 3;\n\ta[1] -= full * 2;\n\ta[2] -= full * 2;\n\t\n\tint ans = 0;\n\tfor (int start = 0; start < 7; ++start) {\n\t\tint day = start;\n\t\tvector<int> b = a;\n\t\tint cur = 0;\n\t\twhile (b[idx[day]] > 0) {\n\t\t\t--b[idx[day]];\n\t\t\tday = (day + 1) % 7;\n\t\t\t++cur;\n\t\t}\n\t\tans = max(ans, full * 7 + cur);\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1154",
    "index": "D",
    "title": "Walking Robot",
    "statement": "There is a robot staying at $X=0$ on the $Ox$ axis. He has to walk to $X=n$. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel.\n\nThe $i$-th segment of the path (from $X=i-1$ to $X=i$) can be exposed to sunlight or not. The array $s$ denotes which segments are exposed to sunlight: if segment $i$ is exposed, then $s_i = 1$, otherwise $s_i = 0$.\n\nThe robot has one battery of capacity $b$ and one accumulator of capacity $a$. For each segment, you should choose which type of energy storage robot will use to go to the next point (it can be either battery or accumulator). If the robot goes using the battery, the current charge of the battery is decreased by one (the robot can't use the battery if its charge is zero). And if the robot goes using the accumulator, the current charge of the accumulator is decreased by one (and the robot also can't use the accumulator if its charge is zero).\n\nIf the current segment is \\textbf{exposed to sunlight} and the robot goes through it \\textbf{using the battery}, the charge of the accumulator increases by one (of course, its charge can't become higher than it's maximum capacity).\n\nIf accumulator is used to pass some segment, its charge decreases by 1 no matter if the segment is exposed or not.\n\nYou understand that it is not always possible to walk to $X=n$. You want your robot to go as far as possible. Find the maximum number of segments of distance the robot can pass if you control him optimally.",
    "tutorial": "Let's simulate the process of walking and maintain the current charges of the battery and the accumulator, carefully choosing which to use each time we want to pass a segment. Obviously, if at the beginning of some segment our battery is exhausted (its current charge is $0$), we must use the accumulator to continue, and vice versa. What if we can use both types of energy storage? If we can recharge the accumulator (the current segment is exposed and the current charge of accumulator is lower than its initial charge), let's do it - because it only consumes one charge of the battery, and there is no better way to spend it. And if we cannot recharge the accumulator, it's optimal to use it instead of the battery (suppose it's not right: our solution uses the accumulator during current moment of time $t$ and the battery during some moment in future $t_2$, but optimal solution does vice versa. Then the usage of the battery in optimal solution does not grant us any additional charges, so we can instead swap our decisions in these moments, use the accumulator right now and the battery later, and the answer won't get worse). So, what's left is to carefully implement the simulation, keeping track of charges and choosing what to use according to aforementioned rules.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint a, b, maxa;\n\nvoid use_battery(int s)\n{\n\tif(s == 1) a = min(a + 1, maxa);\n\t--b;\t\n}\n\nvoid use_accum()\n{\n\t--a;\n}\n\nint main()\n{\n\tint ans = 0;\n\tint n;\n\tcin >> n >> b >> a;\n\tmaxa = a;\n\tvector<int> s(n);\n\tfor(int i = 0; i < n; i++) cin >> s[i];\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(a == 0 && b == 0)\n\t\t\tbreak;\n\t\telse if(a == 0)\n\t\t\tuse_battery(s[i]);\n\t\telse if(b == 0)\n\t\t\tuse_accum();\n\t\telse if(s[i] == 1 && a < maxa)\n\t\t\tuse_battery(s[i]);\n\t\telse use_accum();\n\t\tans++;\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1154",
    "index": "E",
    "title": "Two Teams",
    "statement": "There are $n$ students standing in a row. Two coaches are forming two teams — the first coach chooses the first team and the second coach chooses the second team.\n\nThe $i$-th student has integer programming skill $a_i$. All programming skills are \\textbf{distinct} and between $1$ and $n$, inclusive.\n\nFirstly, the first coach will choose the student with maximum programming skill among all students not taken into any team, \\textbf{and} $k$ closest students to the left of him and $k$ closest students to the right of him (if there are less than $k$ students to the left or to the right, all of them will be chosen). All students that are chosen leave the row and join the first team. Secondly, the second coach will make the same move (but all students chosen by him join the second team). Then again the first coach will make such move, and so on. This repeats until the row becomes empty (i. e. the process ends when each student becomes to some team).\n\nYour problem is to determine which students will be taken into the first team and which students will be taken into the second team.",
    "tutorial": "Let's maintain two data structures: a queue with positions of students in order of decreasing their programming skill and a set (std::set, note that we need exactly ordered set) with positions of students not taken in any team. To construct the first data structure we need to sort pairs $(a_i, i)$ in decreasing order of the first element and after that push second elements in order from left to right. The second data structure can be constructed even easier - we just need to insert all values from $[1, n]$ into it. Also let's maintain an array $ans$, where $ans_i = 1$ if the $i$-th student belongs to the first team and $ans_i = 2$ otherwise, and the variable $who$ to determine whose turn is now (initially it is $1$). While our set is not empty, let's repeat the following algorithm: firstly, while the head (the first element) of the queue is not in the set, pop it out. This is how we determine which student will be taken now. Let his position be $pos$. And don't forget to pop him out too. Create the additional dynamic array $add$ which will contain all students we will add to the team during this turn. Let's find the iterator to the student with the position $pos$. Then make the following sequence of moves $k+1$ times: add the element the current iterator is pointing at to the array $add$, then if the current iterator is pointing at the first element, break the cycle, otherwise go to the iterator pointing at the previous element. Then let's find the iterator to the student next to the student with position $pos$. And then let's make almost the same sequence of moves $k$ times: if the current iterator is pointing to the end of the set, break the cycle, otherwise add the element the current iterator is pointing at to the array $add$ and advance to the iterator pointing at the next element. Then let's remove all values from the array $add$ from the set, and for each student $st$ we delete let's set $ans_{st} = who$. And change the variable $who$ to $2$ if it is $1$ now and to $1$ otherwise. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<pair<int, int>> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i].first;\n\t\ta[i].second = i;\n\t}\n\t\n\tsort(a.rbegin(), a.rend());\n\tqueue<int> q;\n\tfor (int i = 0; i < n; ++i) {\n\t\tq.push(a[i].second);\n\t}\n\t\n\tset<int> idx;\n\tfor (int i = 0; i < n; ++i) {\n\t\tidx.insert(i);\n\t}\n\tstring ans(n, '0');\n\tint who = 0;\n\twhile (!idx.empty()) {\n\t\twhile (!idx.count(q.front())) {\n\t\t\tq.pop();\n\t\t}\n\t\tint pos = q.front();\n\t\tq.pop();\n\t\t\n\t\tvector<int> add;\n\t\tauto it = idx.find(pos);\n\t\tfor (int i = 0; i <= k; ++i) {\n\t\t\tadd.push_back(*it);\n\t\t\tif (it == idx.begin()) break;\n\t\t\t--it;\n\t\t}\n\t\tit = next(idx.find(pos));\n\t\tfor (int i = 0; i < k; ++i) {\n\t\t\tif (it == idx.end()) break;\n\t\t\tadd.push_back(*it);\n\t\t\t++it;\n\t\t}\n\t\tfor (auto it : add) {\n\t\t\tidx.erase(it);\n\t\t\tans[it] = '1' + who;\n\t\t}\n\t\twho ^= 1;\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1154",
    "index": "F",
    "title": "Shovels Shop",
    "statement": "There are $n$ shovels in the nearby shop. The $i$-th shovel costs $a_i$ bourles.\n\nMisha has to buy \\textbf{exactly} $k$ shovels. Each shovel can be bought \\textbf{no more than once}.\n\nMisha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.\n\nThere are also $m$ special offers in the shop. The $j$-th of them is given as a pair $(x_j, y_j)$, and it means that if Misha buys \\textbf{exactly} $x_j$ shovels \\textbf{during one purchase} then $y_j$ \\textbf{most cheapest} of them are for free (i.e. he will not pay for $y_j$ most cheapest shovels during the current purchase).\n\nMisha can use any offer any (possibly, zero) number of times, but he cannot use \\textbf{more than one} offer during \\textbf{one purchase} (but he can buy shovels without using any offers).\n\nYour task is to calculate the minimum cost of buying $k$ shovels, if Misha buys them optimally.",
    "tutorial": "First of all, since we are going to buy exactly $k$ shovels, we may discard $n - k$ most expensive shovels from the input and set $n = k$ (and solve the problem which requires us to buy all the shovels). Also, let's add an offer which allows us to buy $1$ shovel and get $0$ cheapest of them for free, to simulate that we can buy shovels without using offers. Now we claim that if we sort all the shovels by their costs, it's optimal to divide the array of costs into some consecutive subarrays and buy each subarray using some offer. Why should the sets of shovels for all purchases be consecutive subarrays? Suppose it's not so: let's pick two purchases such that they are \"mixed\" in the array of costs, i. e. there exists at least one shovel $A$ bought in the first purchase such that there exists a shovel $B$ cheaper than it and a shovel $C$ more expensive than it, both bought in the second purchase. If shovel $A$ is for free, then we may \"swap\" shovels $A$ and $C$, otherwise we may swap shovels $A$ and $B$, and the answer won't become worse. So, we can do it until all purchases correspond to subsegments in the array of costs. Then it's easy to see that we can make purchases in such a way that we always buy some amount of cheapest shovels. And now the problem can be solved by knapsack-like dynamic programming: let $dp_i$ be the minimum cost to buy exactly $i$ cheapest shovels. $dp_0$ is $0$, and for each offer $(x, y)$ we can update $dp_{i + x}$ by the value of $dp_i + sum(i + y + 1, i + x)$, where $sum(l, r)$ is the sum of costs of all shovels in the sorted order from shovel on position $l$ to shovel on position $r$, inclusive (these sums can be calculated in $O(1)$ using partial sums method).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tsort(a.begin(), a.end());\n\ta.resize(k);\n\treverse(a.begin(), a.end());\n\t\n\tvector<int> offers(k + 1);\n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\tif (x <= k) {\n\t\t\toffers[x] = max(offers[x], y);\n\t\t}\n\t}\n\t\n\tvector<int> pref(k + 1);\n\tfor (int i = 0; i < k; ++i) {\n\t\tpref[i + 1] = pref[i] + a[i];\n\t}\n\t\n\tvector<int> dp(k + 1, INF);\n\tdp[0] = 0;\n\tfor (int i = 0; i < k; ++i) {\n\t\tdp[i + 1] = min(dp[i + 1], dp[i] + a[i]);\n\t\tfor (int j = 1; j <= k; ++j) {\n\t\t\tif (offers[j] == 0) continue;\n\t\t\tif (i + j > k) break;\n\t\t\tdp[i + j] = min(dp[i + j], dp[i] + pref[i + j - offers[j]] - pref[i]);\n\t\t}\n\t}\n\t\n\tcout << dp[k] << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1154",
    "index": "G",
    "title": "Minimum Possible LCM",
    "statement": "You are given an array $a$ consisting of $n$ integers $a_1, a_2, \\dots, a_n$.\n\nYour problem is to find such pair of indices $i, j$ ($1 \\le i < j \\le n$) that $lcm(a_i, a_j)$ is minimum possible.\n\n$lcm(x, y)$ is the least common multiple of $x$ and $y$ (minimum positive number such that both $x$ and $y$ are divisors of this number).",
    "tutorial": "I've heard about some very easy solutions with time complexity $O(a \\log a)$, where $a$ is the maximum value of $a_i$, but I will describe my solution with time complexity $O(nd)$, where $d$ is the maximum number of divisors of $a_i$. A very good upper-bound approximation of the number of divisors of $x$ is $\\sqrt[3]{x}$ so my solution works in $O(n \\sqrt[3]{a})$. Firstly, let's talk about the idea. The main idea is the following: for each number from $1$ to $10^7$, we want to find two minimum numbers in the array which are divisible by this number. Then we can find the answer among all such divisors that have at least two multiples in the array. Let's write a function $add(idx)$ which will try to add the number $a_{idx}$ to all its divisors. The easiest way to do it is iterate over all divisors in time $O(\\sqrt{a_{idx}})$ and add it somehow. But it is too slow. Let's improve it somehow. How can we skip numbers that aren't divisors of $a_{idx}$? Let's build an Eratosthenes sieve (I highly recommended one with time complexity $O(n)$ because the sieve with time complexity $O(n \\log \\log n)$ is about twice slower on such constraints) which will maintain the minimum divisor for each number from $1$ to $10^7$ (the linear sieve builds this array automatically in its implementation). Then we can factorize the number in $O(\\log a_{idx})$ and iterate over all its divisors using simple recursive function. And the last thing I should notice - this solution can give TLE and require some constant optimizations. I recommended to use pair of integers (or arrays of size two) for each divisor and to add numbers using a few if-statements.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\nconst int N = 10 * 1000 * 1000 + 11;\n\nint n;\nvector<int> a;\n\nint mind[N];\n\npair<int, int> mins[N];\nvector<pair<int, int>> divs;\n\nvoid build_sieve() {\n\tvector<int> pr;\n\tmind[0] = mind[1] = 1;\n\tfor (int i = 2; i < N; ++i) {\n\t\tif (mind[i] == 0) {\n\t\t\tpr.push_back(i);\n\t\t\tmind[i] = i;\n\t\t}\n\t\tfor (int j = 0; j < int(pr.size()) && pr[j] <= mind[i] && i * pr[j] < N; ++j) {\n\t\t\tmind[i * pr[j]] = pr[j];\n\t\t}\n\t}\n}\n\n\nvoid add_to_mins(int curd, int idx) {\n    if(mins[curd].first == -1)\n        mins[curd].first = idx;\n    else if(mins[curd].second == -1)\n        mins[curd].second = idx;\n}\n\nvoid rec(int pos, int curd, int idx) {\n\tif (pos == int(divs.size())) {\n\t\tadd_to_mins(curd, idx);\n\t\treturn;\n\t}\n\tint curm = 1;\n\tfor (int i = 0; i <= divs[pos].second; ++i) {\n\t\trec(pos + 1, curd * curm, idx);\n\t\tcurm *= divs[pos].first;\n\t}\n}\n\nvoid add(int idx) {\n\tint value = a[idx];\n\tdivs.clear();\n\twhile (value > 1) {\n\t\tint d = mind[value];\n\t\tif (!divs.empty() && divs.back().first == d) {\n\t\t\t++divs.back().second;\n\t\t} else {\n\t\t\tdivs.push_back(make_pair(d, 1));\n\t\t}\n\t\tvalue /= d;\n\t}\n\trec(0, 1, idx);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n;\n\ta.resize(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tfor(int i = 0; i < N; i++)\n\t    mins[i] = make_pair(-1, -1);\n\tbuild_sieve();\n\t\n\tvector<pair<int, int> > vals;\n\tfor(int i = 0; i < n; i++)\n\t    vals.push_back(make_pair(a[i], i));\n\tsort(vals.begin(), vals.end());\n\tfor (int i = 0; i < n; ++i) {\n\t    if(i > 1 && vals[i].first == vals[i - 2].first) continue;\n\t\tadd(vals[i].second);\n\t}\n\t\n\tlong long l = INF * 1ll * INF;\n\tint ansi = -1, ansj = -1;\n\tfor (int i = 1; i < N; ++i) {\n\t\tpair<int, int> idxs = mins[i];\n\t\tif (idxs.second == -1) continue;\n\t\tlong long curl = a[idxs.first] * 1ll * a[idxs.second] / i;\n\t\tif (l > curl) {\n\t\t\tl = curl;\n\t\t\tansi = min(idxs.first, idxs.second);\n\t\t\tansj = max(idxs.first, idxs.second);\n\t\t}\n\t}\n\t\n\tcout << ansi + 1 << \" \" << ansj + 1 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1155",
    "index": "A",
    "title": "Reverse a Substring",
    "statement": "You are given a string $s$ consisting of $n$ lowercase Latin letters.\n\nLet's define a substring as a contiguous subsegment of a string. For example, \"acab\" is a substring of \"abacaba\" (it starts in position $3$ and ends in position $6$), but \"aa\" or \"d\" aren't substrings of this string. So the substring of the string $s$ from position $l$ to position $r$ is $s[l; r] = s_l s_{l + 1} \\dots s_r$.\n\nYou have to choose \\textbf{exactly} one of the substrings of the given string and reverse it (i. e. make $s[l; r] = s_r s_{r - 1} \\dots s_l$) to obtain a string that is \\textbf{less} lexicographically. Note that it \\textbf{is not necessary} to obtain the minimum possible string.\n\nIf it is impossible to reverse some substring of the given string to obtain a string that is less, print \"NO\". Otherwise print \"YES\" and \\textbf{any} suitable substring.\n\nString $x$ is lexicographically less than string $y$, if either $x$ is a prefix of $y$ (and $x \\ne y$), or there exists such $i$ ($1 \\le i \\le min(|x|, |y|)$), that $x_i < y_i$, and for any $j$ ($1 \\le j < i$) $x_j = y_j$. Here $|a|$ denotes the length of the string $a$. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​.",
    "tutorial": "If the answer is \"YES\" then we always can reverse a substring of length $2$. So we need to check only pairs of adjacent characters in $s$. If there is no such pair of characters $s_i > s_{i + 1}$ for all $i$ from $1$ to $n-1$ then the answer is \"NO\". Why is it so? Consider the substring $s[l; r] = s_l s_{l+1} \\dots s_r$ we have to reverse. It is obvious that $s_l > s_r$, otherwise it is pointless to reverse this substring. Then consider two cases: $s_l \\le s_{l+1}$ then $s_{l+1} > s_r$ (by transitivity) and then we can go to a smaller substring ($s[l + 1; r]$); otherwise $s_l > s_{l + 1}$ and it means that we can take the substring $s[l; l + 1]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\t\n\tfor (int i = 1; i < int(s.size()); ++i) {\n\t\tif (s[i] < s[i - 1]) {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tcout << i << \" \" << i + 1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << \"NO\" << endl;\n\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1155",
    "index": "B",
    "title": "Game with Telephone Numbers",
    "statement": "A telephone number is a sequence of \\textbf{exactly} $11$ digits such that its first digit is 8.\n\nVasya and Petya are playing a game. Initially they have a string $s$ of length $n$ ($n$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player \\textbf{must} choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $s$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.\n\nYou have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).",
    "tutorial": "Let's understand how players should act. Vasya needs to delete the first digit that is not equal to $8$, because the first digit of telephone number should be $8$, and the first digit not equal to $8$ is preventing it. Petya needs to delete the first digit equal to $8$, for the same reasons. So, all that we need to do is delete first $\\frac{n-11}{2}$ digits not equal to $8$ (if they exist), and first $\\frac{n-11}{2}$ digits equal to $8$ (again if they exist). It's enough to stop when there is either no $8$'s left or no non-$8$'s because the latter moves won't change the result of the game anyway. Finally, if first digit of resulting string is $8$, then Vasya wins, otherwise Petya. Overall complexity: $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nstring s;\n\nint main(){\n    cin >> n >> s;\n    int cnt1 = (n - 11) / 2;\n    int cnt2 = cnt1;\n    string res = \"\";\n    for(int i = 0; i < n; ++i){\n        if(s[i] == '8'){\n            if(cnt1 > 0) --cnt1;\n            else res += s[i];\n        }\n        else{\n            if(cnt2 > 0) --cnt2;\n            else res += s[i];\n        }\n    }\n    \n    if(res[0] == '8') cout << \"YES\\n\";\n    else cout << \"NO\\n\";\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1155",
    "index": "C",
    "title": "Alarm Clocks Everywhere",
    "statement": "Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the $i$-th of them will start during the $x_i$-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes $x_1, x_2, \\dots, x_n$, so he will be awake during each of these minutes (\\textbf{note that it does not matter if his alarm clock will ring during any other minute}).\n\nIvan can choose two properties for the alarm clock — the first minute it will ring (let's denote it as $y$) and the interval between two consecutive signals (let's denote it by $p$). After the clock is set, it will ring during minutes $y, y + p, y + 2p, y + 3p$ and so on.\n\nIvan can choose \\textbf{any} minute as the first one, but he cannot choose any arbitrary value of $p$. He has to pick it among the given values $p_1, p_2, \\dots, p_m$ (his phone does not support any other options for this setting).\n\nSo Ivan has to choose the first minute $y$ when the alarm clock should start ringing and the interval between two consecutive signals $p_j$ in such a way that it will ring during all given minutes $x_1, x_2, \\dots, x_n$ (and it does not matter if his alarm clock will ring in any other minutes).\n\nYour task is to tell the first minute $y$ and the index $j$ such that if Ivan sets his alarm clock with properties $y$ and $p_j$ it will ring during all given minutes $x_1, x_2, \\dots, x_n$ or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.",
    "tutorial": "It is obvious that we can always take $x_1$ as $y$. But we don't know which value of $p$ we can take. Let $d_i$ be $x_{i + 1} - x_i$ for all $i$ from $1$ to $n-1$. The value of $p$ should be divisor of each value of $d_i$. The maximum possible divisor of each $d_i$ is $g = gcd(d_1, d_2, \\dots, d_{n-1})$ (greatest common divisor). And then it is obvious that the value of $p$ should be the divisor of $g$. So we have to find any divisor of $g$ among all values $p_j$. If there is no such value then the answer is \"NO\". Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tvector<long long> x(n), p(m);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> x[i];\n\t}\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> p[i];\n\t}\n\t\n\tlong long g = x[1] - x[0];\n\tfor (int i = 2; i < n; ++i) {\n\t\tg = __gcd(g, x[i] - x[i - 1]);\n\t}\n\t\n\tfor (int i = 0; i < m; ++i) {\n\t\tif (g % p[i] == 0) {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tcout << x[0] << \" \" << i + 1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << \"NO\" << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1155",
    "index": "D",
    "title": "Beautiful Array",
    "statement": "You are given an array $a$ consisting of $n$ integers. Beauty of array is the maximum sum of some \\textbf{consecutive subarray} of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.\n\nYou may choose \\textbf{at most one consecutive subarray} of $a$ and multiply all values contained in this subarray by $x$. You want to maximize the beauty of array after applying at most one such operation.",
    "tutorial": "The first intuitive guess one's probably made is multiplying the segment of maximum sum for positive $x$. That thing is correct. Unfortunately, there is no similar strategy for non-positive $x$, simple greedy won't work there. Thus, dynamic programming is our new friend. Let's introduce the following state: $dp[pos][state_{max}][state_{mul}]$, where $pos$ is the length of the currently processed prefix, $state_{max}$ is the state of maximum sum segment ($0$ is not reached, it'll appear later, $1$ is open, current elements are added to it, $2$ is passed, the segment appeared earlier) and $state_{mul}$ is the state of segment multiplied by $x$ with the same values. This $dp$ will store the maximum segment sum we can achieve. The only base state is $dp[0][0][0] = 0$ - the prefix of length $0$ is processed and both segments are not open yet. The rest of values in $dp$ are $-\\infty$. There are two main transitions. At any moment we can change the state of each segment to the next one without moving to the next position. From state $0$ (not reached) we can go to state $1$ (opened) and from state $1$ we can go to state $2$ (passed). Note that this easily covers the case where optimal segment is empty. We can also move to the next position updating the value of $dp$ with correspondance to the current states of segments. The answer will be stored in $dp[n][2][2]$ - the state where all the array is processed and both segments are closed. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\ntypedef long long li;\n\nconst int N = 300 * 1000 + 13;\nconst li INF64 = 1e18;\n\nint n, x;\nint a[N];\n\nli dp[N][3][3];\n\nint main() {\n\tscanf(\"%d%d\", &n, &x);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\n\tforn(i, n + 1) forn(j, 3) forn(k, 3)\n\t\tdp[i][j][k] = -INF64;\n\t\n\tdp[0][0][0] = 0;\n\tforn(i, n + 1) forn(j, 3) forn(k, 3){\n\t\tif (k < 2)\n\t\t\tdp[i][j][k + 1] = max(dp[i][j][k + 1], dp[i][j][k]);\n\t\tif (j < 2)\n\t\t\tdp[i][j + 1][k] = max(dp[i][j + 1][k], dp[i][j][k]);\n\t\tif (i < n)\n\t\t\tdp[i + 1][j][k] = max(dp[i + 1][j][k], dp[i][j][k] + (j == 1 ? a[i] : 0) * li(k == 1 ? x : 1));\n\t}\n\t\n\tprintf(\"%lld\\n\", dp[n][2][2]);\n}",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "dp",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1155",
    "index": "E",
    "title": "Guess the Root",
    "statement": "Jury picked a polynomial $f(x) = a_0 + a_1 \\cdot x + a_2 \\cdot x^2 + \\dots + a_k \\cdot x^k$. $k \\le 10$ and all $a_i$ are integer numbers and $0 \\le a_i < 10^6 + 3$. It's guaranteed that there is at least one $i$ such that $a_i > 0$.\n\nNow jury wants you to find such an integer $x_0$ that $f(x_0) \\equiv 0 \\mod (10^6 + 3)$ or report that there is not such $x_0$.\n\nYou can ask no more than $50$ queries: you ask value $x_q$ and jury tells you value $f(x_q) \\mod (10^6 + 3)$.\n\nNote that printing the answer doesn't count as a query.",
    "tutorial": "Since $10^6 + 3$ is a prime and degree $k$ of the polynomial is small enough, we can get this polynomial in our hands asking $k + 1$ queries in different points. Knowing values $f(x_i)$ for $x_1, x_2, \\dots, x_{k + 1}$, we can interpolate $f$ by various ways. For example, we can construct a system of linear equations thinking of $a_i$ as variables. In other words, we know, that $a_0 \\cdot x_i^0 + a_1 \\cdot x_i^1 + \\dots + a_k \\cdot x_i^k = f(x_i)$ for $i = 1 \\dots (k+1)$, also we know $x_i^l$ and $f(x_i)$. So we can solve this system using Gaussian elimination in $O(k^3)$. Now, knowing the polynomial $f(x)$ we can locally brute force all possible candidates for $x_0$, since there is only $10^6 + 3$ such candidates, and print the one we found.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int MOD = 1000 * 1000 + 3;\n\nint norm(int a) {\n\twhile(a >= MOD) a -= MOD;\n\twhile(a < 0) a += MOD;\n\treturn a;\n}\nint mul(int a, int b) {\n\treturn int(a * 1ll * b % MOD);\n}\nint binPow(int a, int k) {\n\tint ans = 1;\n\twhile(k > 0) {\n\t\tif(k & 1)\n\t\t\tans = mul(ans, a);\n\t\ta = mul(a, a);\n\t\tk >>= 1;\n\t}\n\treturn ans;\n}\nint inv(int a) {\n\treturn binPow(a, MOD - 2);\n}\n\nint k = 10;\nvector<int> f;\n\nint main() {\n\tf.resize(k + 1);\n\tfore(i, 0, sz(f)) {\n\t\tcout << \"? \" << i << endl;\n\t\tcout.flush();\n\t\tcin >> f[i];\n\t}\n\t\n\tvector< vector<int> > mat(sz(f), vector<int>(sz(f) + 1));\n\tfore(i, 0, sz(mat)) {\n\t\tmat[i][0] = 1;\n\t\tmat[i][sz(f)] = f[i];\n\t\t\n\t\tfore(j, 1, sz(mat[i]) - 1)\n\t\t\tmat[i][j] = mul(mat[i][j - 1], i);\n\t}\n\t\n\t/*\n\tfore(i, 0, sz(mat)) {\n\t\tfore(j, 0, sz(mat[i]))\n\t\t\tcerr << mat[i][j] << \" \";\n\t\tcerr << endl;\n\t}\n\t*/\n\t\n\tfore(j, 0, sz(mat)) {\n\t\tint nid = -1;\n\t\tfore(i, j, sz(mat)) {\n\t\t\tif(mat[i][j] != 0) {\n\t\t\t\tnid = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(nid == -1)\n\t\t\tcontinue;\n\t\t\n\t\tswap(mat[j], mat[nid]);\n\t\tfore(i, 0, sz(mat)) {\n\t\t\tif(i == j) continue;\n\t\t\tint cf = mul(mat[i][j], inv(mat[j][j]));\n\t\t\t\n\t\t\tfore(cj, j, sz(mat[i]))\n\t\t\t\tmat[i][cj] = norm(mat[i][cj] - mul(cf, mat[j][cj]));\n\t\t}\n\t}\n\t\n\tvector<int> a(sz(f), 0);\n\tfore(i, 0, sz(a)) {\n\t\tif(mat[i][i] == 0)\n\t\t\tcontinue;\n\t\ta[i] = mul(mat[i][sz(a)], inv(mat[i][i]));\n\t}\n\t\n\tfore(x0, 0, MOD) {\n\t\tint val = 0;\n\t\tfor(int i = sz(a) - 1; i >= 0; i--)\n\t\t\tval = norm(mul(val, x0) + a[i]);\n\t\t\t\n\t\tif(val == 0) {\n\t\t\tcout << \"! \" << x0 << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << \"! -1\" << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "interactive",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1155",
    "index": "F",
    "title": "Delivery Oligopoly",
    "statement": "The whole delivery market of Berland is controlled by two rival companies: BerEx and BerPS. They both provide fast and reliable delivery services across all the cities of Berland.\n\nThe map of Berland can be represented as an \\textbf{undirected} graph. The cities are vertices and the roads are edges between them. Each pair of cities has no more than one road between them. Each road connects different cities.\n\nBerEx and BerPS are so competitive that for each pair of cities $(v, u)$ they have set up their paths from $v$ to $u$ in such a way that \\textbf{these two paths don't share a single road}. It is guaranteed that it was possible.\n\nNow Berland government decided to cut down the road maintenance cost by abandoning some roads. Obviously, they want to maintain as little roads as possible. However, they don't want to break the entire delivery system. So BerEx and BerPS should still be able to have their paths between every pair of cities non-intersecting.\n\nWhat is the minimal number of roads Berland government can maintain?\n\nMore formally, given a 2-edge connected undirected graph, what is the minimum number of edges that can be left in it so that the resulting graph is also 2-edge connected?",
    "tutorial": "Let's use dynamic programming to solve this problem. We will start with a single biconnected component consisting of vertex $0$, and connect other vertices to it. So, the state of our dynamic programming will be a $mask$ of vertices that are in the same biconnected component with $0$. How can we extend a biconnected component in such a way that some other vertices are added into it, but it is still biconnected? We will add a path (possibly cyclic) that starts in some vertex $x$ belonging to the $mask$, goes through some vertices not belonging to the $mask$, and ends in some vertex $y$ belonging to the $mask$ (possibly $x = y$). If for every triple ($x$, $y$, $addmask$) we precalculate some path that starts in $x$, goes through vertices from $addmask$ and ends in $y$ (and $addmask$ does not contain neither $x$ nor $y$), then we can solve the problem in $O(3^n n^2)$: there will be $2^n$ states, for every state we will iterate on two vertices $x$ and $y$ belonging to the $mask$, and the number of possible pairs of non-intersecting masks $mask$ and $addmask$ is $O(3^n)$. The only thing that's left is precalculating the paths for triples ($x$, $y$, $addmask$). That can be done with auxiliary dynamic programming $dp_2[x][y][addmask]$ which will denote whether such a path exists. For every edge $(u, v)$ of the original graph, $dp_2[u][v][0]$ is true, and we can go from $dp_2[x][y][addmask]$ to some state $dp_2[x][z][addmask']$, where $addmask'$ will contain all vertices from $addmask$ and vertex $y$ (and we should ensure that there is an edge $(y, z)$ in the graph and the $addmask$ didn't contain vertex $y$ earlier). We should also somehow be able to restore the paths from this dp, and we also should be careful not to choose the same edge twice (for example, if we start a path by edge $(x, y)$, we should not use the same edge to return to $x$) - both these things can be done, for example, by storing next-to-last vertex in the path.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 14;\nconst int INF = int(1e9);\n\nint dp[1 << N];\nint par[1 << N];\nint last[1 << N];\npair<int, int> last_pair[1 << N];\nint dp2[N][N][1 << N];\nint lastv[N][N][1 << N];\nvector<int> bits[1 << N];\n\nint n;\nint m;\nvector<int> g[N];\n\nint main()\n{\n\tcin >> n >> m;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x;\n\t\t--y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\tfor(int i = 0; i < (1 << n); i++)\n\t\tdp[i] = INF;\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < n; j++)\n\t\t\tfor(int z = 0; z < (1 << n); z++)\n\t\t\t\tdp2[i][j][z] = INF;\n\tfor(int i = 0; i < n; i++)\n\t\tfor(auto x : g[i])\n\t\t{\n\t\t\tdp2[i][x][0] = 1;\n\t\t\tlastv[i][x][0] = i;\n\t\t}\n\tfor(int mask = 0; mask < (1 << n); mask++)\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tfor(int j = 0; j < n; j++)\n\t\t\t{\n\t\t\t\tif((mask & (1 << i)) || (mask & (1 << j)) || (i == j) || (dp2[i][j][mask] == INF))\n\t\t\t\t\tcontinue;\n\t\t\t\tfor(auto z : g[j])\n\t\t\t\t{\n\t\t\t\t\tif(mask & (1 << z)) continue;\n\t\t\t\t\tif(z == lastv[i][j][mask]) continue;\n\t\t\t\t\tint nmask = mask ^ (1 << j);\n\t\t\t\t\tif(dp2[i][z][nmask] == INF)\n\t\t\t\t\t{\n\t\t\t\t\t\tdp2[i][z][nmask] = 1;\n\t\t\t\t\t\tlastv[i][z][nmask] = j;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\tfor(int mask = 0; mask < (1 << n); mask++)\n\t\tfor(int j = 0; j < n; j++)\n\t\t\tif(mask & (1 << j))\n\t\t\t\tbits[mask].push_back(j);\n\tdp[1] = 0;\n\tfor(int mask = 0; mask < (1 << n); mask++)\n\t\tfor(int addmask = mask; addmask; addmask = (addmask - 1) & mask)\n\t\t{\n\t\t\tint lastmask = mask ^ addmask;\n\t\t\tint cnt = __builtin_popcount(addmask) + 1;\n\t\t\tif(dp[lastmask] + cnt >= dp[mask])\n\t\t\t\tcontinue;\n\t\t\tbool f = false;\n\t\t\tfor(auto x : bits[lastmask])\n\t\t\t{\n\t\t\t\tfor(auto y : bits[lastmask])\n\t\t\t\t{\n\t\t\t\t\tif(dp2[x][y][addmask] == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tdp[mask] = dp[lastmask] + cnt;\n\t\t\t\t\t\tlast_pair[mask] = make_pair(x, y);\n\t\t\t\t\t\tlast[mask] = addmask;\n\t\t\t\t\t}\n\t\t\t\t\tif(f) break;\n\t\t\t\t}\n\t\t\t\tif(f) break;\n\t\t\t}\n\t\t}\n\tif(dp[(1 << n) - 1] == INF)\n\t\tcout << -1 << endl;\n\telse\n\t{\n\t\tcout << dp[(1 << n) - 1] << endl;\n\t\tint cur = (1 << n) - 1;\n\t\twhile(cur != 1)\n\t\t{\n\t\t\tint lst = last[cur];\n\t\t\tint x = last_pair[cur].first;\n\t\t\tint y = last_pair[cur].second;\n\t\t\tcur ^= lst;\n\t\t\twhile(lst)\n\t\t\t{\n\t\t\t\tint ny = lastv[x][y][lst];\n\t\t\t\tcout << y + 1 << \" \" << ny + 1 << endl;\n\t\t\t\tlst ^= (1 << ny);\n\t\t\t\ty = ny;\n\t\t\t}\n\t\t\tcout << x + 1 << \" \" << y + 1 << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "dp",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1156",
    "index": "A",
    "title": "Inscribed Figures",
    "statement": "The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.\n\nFuture students will be asked just a single question. They are given a sequence of integer numbers $a_1, a_2, \\dots, a_n$, each number is from $1$ to $3$ and $a_i \\ne a_{i + 1}$ for each valid $i$. The $i$-th number represents a type of the $i$-th figure:\n\n- circle;\n- isosceles triangle with the length of height equal to the length of base;\n- square.\n\nThe figures of the given sequence are placed somewhere on a Cartesian plane in such a way that:\n\n- $(i + 1)$-th figure is inscribed into the $i$-th one;\n- each triangle base is parallel to OX;\n- the triangle is oriented in such a way that the vertex opposite to its base is at the top;\n- each square sides are parallel to the axes;\n- for each $i$ from $2$ to $n$ figure $i$ has the maximum possible length of side for triangle and square and maximum radius for circle.\n\nNote that the construction is unique for some fixed position and size of just the first figure.\n\nThe task is to calculate the number of \\textbf{distinct} points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?\n\nSo can you pass the math test and enroll into Berland State University?",
    "tutorial": "Firstly, let's find out when the answer is infinite. Obviously, any point of intersection is produced by at least a pair of consecutive figures. Take a look at every possible pair and you'll see that only square inscribed in triangle and vice verse produce infinite number of points in intersection. The other cases are finite. From now we assume that initial sequence has no 2 and 3 next to each other. Basically, it's all triangles and squares separated by circles. If the task was to count all pairs of intersecting figures, the solution will be the following. Square next to circle gives 4 points, triangle next to circle gives 3 points. Unfortunately, the task asked for distinct points. Notice that there is a single subsegment which can produce coinciding points (square $\\rightarrow$ circle $\\rightarrow$ triangle). So you have to find each triplet (3 1 2) and subtract their count from the sum. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nusing namespace std;\n\nint main(){\n\tint n;\n\tscanf(\"%d\", &n);\n\tint sum = 0;\n\tint lst = 1;\n\tvector<int> figs;\n\tforn(i, n){\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\tif (lst != 1 && x != 1){\n\t\t\tputs(\"Infinite\");\n\t\t\treturn 0;\n\t\t}\n\t\tif (x != 1){\n\t\t\tfigs.push_back(x);\n\t\t\tsum += x + 1;\n\t\t\tif (i != 0 && i != n - 1)\n\t\t\t\tsum += x + 1;\n\t\t}\n\t\tlst = x;\n\t}\n\tforn(i, int(figs.size()) - 1) if (figs[i] == 3 && figs[i + 1] == 2)\n\t\t--sum;\n\tprintf(\"Finite\\n%d\\n\", sum);\n}",
    "tags": [
      "geometry"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1156",
    "index": "B",
    "title": "Ugly Pairs",
    "statement": "You are given a string, consisting of lowercase Latin letters.\n\nA pair of \\textbf{neighbouring} letters in a string is considered ugly if these letters are also \\textbf{neighbouring} in a alphabet. For example, string \"abaca\" contains ugly pairs at positions $(1, 2)$ — \"ab\" and $(2, 3)$ — \"ba\". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.\n\nCan you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.\n\nIf there are multiple answers, print any of them.\n\nYou also have to answer $T$ separate queries.",
    "tutorial": "To be honest, the solution to this problem is easier to code than to prove. Let's follow the next strategy. Write down all the letters of the string which have odd positions in alphabet (\"aceg$\\dots$\") and even positions in alphabet (\"bdfi$\\dots$\"). Sort both of these lists in non-decreasing order. The answer is either concatenation of the lists (odd + even or even + odd) or \"No answer\". Now for the proof part. Let's establish that we don't care about equal letters and leave just a single copy of each letter of the string. Let's check some cases: There is just a single letter. That's trivial. There are two letters of the same parity. There is no incorrect arrangement for this. There are two letters of different parity. If they differ by one then no answer exists. Otherwise any arrangement works. There are three letters and they are consecutive in alphabet. No answer exists. There are other types of three letters. Then the one of the different parity can put on the side (e.g. \"acd\" and \"dac\"). As the difference between at least one of these letters and that one isn't 1, that arrangement will be ok. Finally, there are at least 4 letters. It means that the difference between either the smallest odd and the largest even or between the smallest even and the largest odd isn't 1. The only thing you need to do is to implement the check function the most straightforward way possible and check both arrangements. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nbool check(string s){\n\tbool ok = true;\n\tforn(i, int(s.size()) - 1)\n\t\tok &= (abs(s[i] - s[i + 1]) != 1);\n\treturn ok;\n}\n\nint main() {\n\tint T;\n\tscanf(\"%d\", &T);\n\tstatic char buf[120];\n\tforn(_, T){\n\t\tscanf(\"%s\", buf);\n\t\tstring s = buf;\n\t\tstring odd = \"\", even = \"\";\n\t\tforn(i, s.size()){\n\t\t\tif (s[i] % 2 == 0)\n\t\t\t\todd += s[i];\n\t\t\telse\n\t\t\t\teven += s[i];\n\t\t}\n\t\tsort(odd.begin(), odd.end());\n\t\tsort(even.begin(), even.end());\n\t\tif (check(odd + even))\n\t\t\tprintf(\"%s\\n\", (odd + even).c_str());\n\t\telse if (check(even + odd))\n\t\t\tprintf(\"%s\\n\", (even + odd).c_str());\n\t\telse\n\t\t\tputs(\"No answer\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "greedy",
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1156",
    "index": "C",
    "title": "Match Points",
    "statement": "You are given a set of points $x_1$, $x_2$, ..., $x_n$ on the number line.\n\nTwo points $i$ and $j$ can be matched with each other if the following conditions hold:\n\n- neither $i$ nor $j$ is matched with any other point;\n- $|x_i - x_j| \\ge z$.\n\nWhat is the maximum number of pairs of points you can match with each other?",
    "tutorial": "Let's denote the points that have greater coordinates in their matched pairs as $R$-points, and the points that have smaller coordinates as $L$-points. Suppose we have an $R$-point that has smaller coordinate than some $L$-point. Then we can \"swap\" them, and the answer won't become worse. Also, if some $R$-point has smaller coordinate than some point that doesn't belong to any pair, or some $L$-point has greater coordinate than some point that doesn't belong to any pair, we can swap them too. So, if the answer is $k$, we choose $k$ leftmost points as $L$-points, and $k$ rightmost ones as $R$-points. For a fixed value of $k$, it's easy to see that we should match the leftmost $L$-point with the leftmost $R$-point, the second $L$-point with the second $R$-point, and so on, in order to maximize the minimum distance in a pair. This fact allows us to check whether it is possible to construct at least $k$ pairs, and we can use binary search to compute the answer to the problem.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\n\nint n, z;\nint a[N];\n\nint main()\n{\n\tscanf(\"%d\", &n);\n\tscanf(\"%d\", &z);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d\", &a[i]);\n\tsort(a, a + n);\n\tint l = 0;\n\tint r = n / 2 + 1;\n\twhile(r - l > 1)\n\t{\n\t\tint m = (l + r) / 2;\n\t\tbool good = true;\n\t\tfor(int i = 0; i < m; i++)\n\t\t\tgood &= (a[n - m + i] - a[i] >= z);\n\t\tif(good)\n\t\t\tl = m;\n\t\telse\n\t\t\tr = m;\n\t}\n\tcout << l << endl;\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "ternary search",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1156",
    "index": "D",
    "title": "0-1-Tree",
    "statement": "You are given a tree (an undirected connected acyclic graph) consisting of $n$ vertices and $n - 1$ edges. A number is written on each edge, each number is either $0$ (let's call such edges $0$-edges) or $1$ (those are $1$-edges).\n\nLet's call an ordered pair of vertices $(x, y)$ ($x \\ne y$) \\textbf{valid} if, while traversing the simple path from $x$ to $y$, we never go through a $0$-edge after going through a $1$-edge. Your task is to calculate the number of \\textbf{valid} pairs in the tree.",
    "tutorial": "Let's divide all valid pairs into three categories: the ones containing only $0$-edges on the path, the ones containing only $1$-edges, and the ones containing both types of edges. To calculate the number of pairs containing only $0$-edges, we may build a forest on the vertices of the original graph and $0$-edges, and choose all pairs of vertices belonging to the same connected components of this forest (we can find all connected components with DSU or any graph traversal algorithm). The same can be done for the pairs containing only $1$-edges. If a path from $x$ to $y$ is valid and contains both types of edges, then there exists a vertex $v$ such that the simple path from $x$ to $v$ goes only through $0$-edges, and the simple path from $v$ to $y$ goes only through $1$-edges. So, let's iterate on this vertex $v$, and choose some other vertex from its component in $0$-graph as $x$, and some other vertex from its component in $1$-graph as $y$, and add the number of ways to choose them to the answer.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\n\nint p[2][N];\nint siz[2][N];\n\nint get(int x, int c)\n{\n\tif(p[c][x] == x)\n\t\treturn x;\n\treturn p[c][x] = get(p[c][x], c);\n}\n\nvoid merge(int x, int y, int c)\n{\n\tx = get(x, c);\n\ty = get(y, c);\n\tif(siz[c][x] < siz[c][y])\n\t\tswap(x, y);\n\tp[c][y] = x;\n\tsiz[c][x] += siz[c][y];\n}\n\nint main()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tp[0][i] = p[1][i] = i;\n\t\tsiz[0][i] = siz[1][i] = 1;\n\t}\n\tfor(int i = 0; i < n - 1; i++)\n\t{\n\t\tint x, y, c;\n\t\tscanf(\"%d %d %d\", &x, &y, &c);\n\t\t--x;\n\t\t--y;\n\t\tmerge(x, y, c);\n\t}\n\tlong long ans = 0;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(p[0][i] == i)\n\t\t\tans += siz[0][i] * 1ll * (siz[0][i] - 1);\n\t\tif(p[1][i] == i)\n\t\t\tans += siz[1][i] * 1ll * (siz[1][i] - 1);\n\t\tans += (siz[0][get(i, 0)] - 1) * 1ll * (siz[1][get(i, 1)] - 1);\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "dp",
      "dsu",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1156",
    "index": "E",
    "title": "Special Segments of Permutation",
    "statement": "You are given a permutation $p$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once).\n\nLet's call some subsegment $p[l, r]$ of this permutation special if $p_l + p_r = \\max \\limits_{i = l}^{r} p_i$. Please calculate the number of special subsegments.",
    "tutorial": "Let's fix the maximum element on segment and iterate on either the elements to the left of it or to the right of it, and if the current maximum is $x$, and the element we found is $y$, check whether the element $x - y$ can form a special subsegment with $y$ (that is, $x$ is the maximum value on the segment between $y$ and $x - y$). That obviously works in $O(n^2)$, yes? Well, not exactly. If we can precompute the borders of the segment where $x$ is the maximum element (this can be done with some logarithmic data structure, or just by processing the array with a stack forwards and backwards) and always choose to iterate on the smaller part of the segment, it's $O(n \\log n)$. Why is it so? Every element will be processed no more than $\\log n$ times because, if we process it in a segment of size $m$, the smaller part of it contains no more than $\\frac{m}{2}$ elements (which we will process later, and the smaller part of this segment contains no more than $\\frac{m}{4}$ elements, and so on). Checking whether the element belongs to the segment we are interested in can be done in $O(1)$ if we precompute inverse permutation for $p$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\n\nint lf[N];\nint rg[N];\nint n;\nint ans = 0;\nint p[N];\nint q[N];\n\nvoid update(int l, int r, int l2, int r2, int sum)\n{\n\tfor(int i = l; i <= r; i++)\n\t{\n\t\tint o = sum - p[i];\n\t\tif(o >= 1 && o <= n && l2 <= q[o] && q[o] <= r2)\n\t\t\tans++;\n\t}\n}\n\nint main()\n{\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tscanf(\"%d\", &p[i]);\n\t\tq[p[i]] = i;\n\t}\n\tstack<pair<int, int> > s;\n\ts.push(make_pair(n + 1, -1));\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\twhile(s.top().first < p[i])\n\t\t\ts.pop();\n\t\tlf[i] = s.top().second;\n\t\ts.push(make_pair(p[i], i));\n\t}\n\twhile(!s.empty())\n\t\ts.pop();\n\ts.push(make_pair(n + 1, n));\n\tfor(int i = n - 1; i >= 0; i--)\n\t{\n\t\twhile(s.top().first < p[i])\n\t\t\ts.pop();\n\t\trg[i] = s.top().second;\n\t\ts.push(make_pair(p[i], i));\n\t}\n\tfor(int i = 0; i < n; i++)\n\t{\n\t//\tcerr << i << \" \" << lf[i] << \" \" << rg[i] << endl;\n\t\tint lenl = i - lf[i] - 1;\n\t\tint lenr = rg[i] - i - 1;\n\t\tif(lenl == 0 || lenr == 0)\n\t\t\tcontinue;\n\t\tif(lenl < lenr)\n\t\t\tupdate(lf[i] + 1, i - 1, i + 1, rg[i] - 1, p[i]);\n\t\telse\n\t\t\tupdate(i + 1, rg[i] - 1, lf[i] + 1, i - 1, p[i]);\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dsu",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1156",
    "index": "F",
    "title": "Card Bag",
    "statement": "You have a bag which contains $n$ cards. There is a number written on each card; the number on $i$-th card is $a_i$.\n\nYou are playing the following game. During each turn, you choose and remove a random card from the bag (all cards that are still left inside the bag are chosen equiprobably). Nothing else happens during the first turn — but during the next turns, after removing a card (let the number on it be $x$), you compare it with the card that was removed during the previous turn (let the number on it be $y$). Possible outcomes are:\n\n- if $x < y$, the game ends and you lose;\n- if $x = y$, the game ends and you win;\n- if $x > y$, the game continues.\n\nIf there are no cards left in the bag, you lose. \\textbf{Cards are not returned into the bag after you remove them.}\n\nYou have to calculate the probability of winning in this game. It can be shown that it is in the form of $\\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \\neq 0$, $P \\le Q$. Output the value of $P \\cdot Q^{−1} ~(mod ~~ 998244353)$.",
    "tutorial": "Let's solve the problem by dynamic programming. Let $dp_{i, j}$ be the probability of winning if the last taken card has number $i$ on it and the number of taken cards is $j$. We win immediately next turn if we take card with number $i$ on it. The probability of this is $\\frac{cnt_{i} - 1}{n - j}$, where $cnt_i$ is number of cards with $i$. Also we can win if we take a greater card next turn. We take a card with number $i + 1$ with probability $\\frac{cnt_{i + 1}}{n - j}$, with number $i+2$ - with probability $\\frac{cnt_{i + 2}}{n - j}$, and so on. The probability of winning in this case will be $\\frac{cnt_{i + 1}}{n - j} \\cdot dp_{i + 1, j + 1}$ and $\\frac{cnt_{i + 2}}{n - j} \\cdot dp_{i + 2, j + 1}$ respectively. So the probability of winning for $dp_{i, j}$ is $\\frac{cnt_{i} - 1}{n - j} + \\sum\\limits_{k = i + 1}^{n} (\\frac{cnt_{k}}{n - j} \\cdot dp_{k, j + 1}$) = $\\frac{cnt_{i} - 1}{n - j} + \\frac{1}{n - j} \\cdot \\sum\\limits_{k = i + 1}^{n} (cnt_{k} \\cdot dp_{k, j + 1}$). Therefore, all we need is to maintain the sum $\\sum\\limits_{i = x}^{n} (cnt_{i} \\cdot dp_{i, j})$ while calculating our dynamic programming.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 5005;\n\nvoid upd(int &a, int b){\n    a += b;\n    a %= MOD;\n}\n\nint mul(int a, int b){\n    return (a * 1LL * b) % MOD;\n}\n\nint bp(int a, int n){\n    int res = 1;\n    for(; n > 0; n >>= 1){\n        if(n & 1) res = mul(res, a);\n        a = mul(a, a);\n    }\n    return res;\n}\n\nint getInv(int a){\n    int ia = bp(a, MOD - 2);\n    assert(mul(a, ia) == 1);\n    return ia;\n}\n\nint n;\nint cnt[N];\nint suf[N];\nint dp[N][N];\nint sum[N][N];\nint inv[N];\n\nint main(){\n    for(int i = 1; i < N; ++i)\n        inv[i] = getInv(i);\n        \n    cin >> n;\n    for(int i = 0; i < n; ++i){\n        int x;\n        cin >> x;\n        ++cnt[x];\n    }\n    cnt[0] = 1;\n    for(int i = N - 2; i >= 0; --i)\n        suf[i] = suf[i + 1] + cnt[i];\n        \n    for(int x = n; x >= 0; --x)\n        for(int y = n; y >= 0; --y){\n            if(cnt[x] == 0){\n                upd(sum[x][y], sum[x + 1][y]);\n                continue;\n            }\n            int s = n - y;\n            if(s <= 0){\n                upd(sum[x][y], sum[x + 1][y]);\n                continue;\n            }\n            \n            upd(dp[x][y], mul(cnt[x] - 1, inv[s]));\n            upd(dp[x][y], mul(sum[x + 1][y + 1], inv[s]));\n            \n            upd(sum[x][y], sum[x + 1][y]);\n            upd(sum[x][y], mul(cnt[x], dp[x][y]));\n        }\n    \n    cout << dp[0][0] << endl;\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1156",
    "index": "G",
    "title": "Optimizer",
    "statement": "Let's analyze a program written on some strange programming language. The variables in this language have names consisting of $1$ to $4$ characters, and each character is a lowercase or an uppercase Latin letter, or a digit. There is an extra constraint that the first character should not be a digit.\n\nThere are four types of operations in the program, each denoted by one of the characters: $, ^, # or &.\n\nEach line of the program has one of the following formats:\n\n- <lvalue>=<rvalue>, where <lvalue> and <rvalue> are valid variable names;\n- <lvalue>=<arg1><op><arg2>, where <lvalue>, <arg1> and <arg2> are valid variable names, and <op> is an operation character.\n\nThe program is executed line-by-line, and the result of execution is stored in a variable having the name res. If res is never assigned in the program, then the result will be equal to the value of res before running the program.\n\nTwo programs are called equivalent if no matter which operations do characters $, ^, # and & denote (but, obviously, performing the same operation on the same arguments gives the same result) and which values do variables have before execution of program, the value of res after running the first program is equal to the value of res after running the second program (the programs are executed independently).\n\nYou are given a program consisting of $n$ lines. Your task is to write a program consisting of minimum possible number of lines that is equivalent to the program you are given.",
    "tutorial": "Let's restate the problem in a more convinient way. Initially we are given some directed acyclic graph. Let there be nodes of two kinds: For a direct set operation. These will have a single outgoing edge to another node. For a binary operation. These will have two outgoing edges to other nodes. However, it's important which edge is the \"left\" one and which is the \"right\" one. We also have to make dummy vertices for the variables which only appeared at the right side of some operation. We are allowed to remove any direct set operations, we will simulate this by compressing the edges of the graph. Instead of doing ($b=a, c=b$), we'll do ($b=a, c=a$). Value-wise this is the same but variable $c$ don't rely on $b$ anymore, so $b$ might be deleted. We'll build the entire graph line by line. Let's maintain array $var2node$ which will keep the current value of each variable. It will store the node itself. It's probably better to store both kinds of nodes in a separate array so that $var2node$ and the pointers to the ends of the edges could be integers. If we encountered no \"res\" variable getting set, then the answer is 0. Otherwise let's traverse from the node representing the current value of \"res\" to every reachable node. While building the graph we were compressing every unoptimal operation, thus all reachable nodes matter. Finally, the last operation on \"res\" might have been just a direct set. That's unoptimal, so we'll handle that case separately.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long ll;\ntypedef vector<ll> vl;\ntypedef vector<vl> vvl;\ntypedef pair<ll,ll> pll;\ntypedef vector<bool> vb;\nconst ll oo = 0x3f3f3f3f3f3f3f3f;\nconst double eps = 1e-9;\n#define sz(c) ll((c).size())\n#define all(c) begin(c), end(c)\n#define FOR(i,a,b) for (ll i = (a); i < (b); i++)\n#define FORD(i,a,b) for (ll i = (b)-1; i >= (a); i--)\n#define mp make_pair\n#define pb push_back\n#define eb emplace_back\n#define xx first\n#define yy second\n#define TR(X) ({ if(1) cerr << \"TR: \" << (#X) << \" = \" << (X) << endl; })\n \nbool is_op(char c) {\n\tfor (char d: \"$^#&\") if (c == d) return true;\n\treturn false;\n}\n \nint main() {\n\tios_base::sync_with_stdio(false);\n\tcin.tie(NULL);\n\t\n\tmap<string,ll> var2node;\n\tll m = 0;\n\tvector<tuple<char,ll,ll>> nodes;\n\tvector<string> original_var;\n\tmap<tuple<char,ll,ll>,ll> operations;\n \n\tauto add_node = [&](string a) {\n\t\toriginal_var.pb(a);\n\t\tnodes.eb('=',-1,m);\n\t\tvar2node[a] = m++;\n\t};\n \n\tll n; cin >> n;\n\twhile (n--) {\n\t\tstring asn; cin >> asn;\n\t\tll ii = 0;\n\t\twhile (asn[ii] != '=') ii++;\n \n\t\tstring a = asn.substr(0,ii);\n\t\tasn = asn.substr(ii+1), ii = 0;\n\t\twhile (ii < sz(asn) && !is_op(asn[ii])) ii++;\n\t\t\n\t\tif (ii == sz(asn)) {\n\t\t\tstring b = asn;\n\t\t\tif (!var2node.count(b)) {\n\t\t\t\tadd_node(b);\n\t\t\t}\n\t\t\tvar2node[a] = var2node[b];\n\t\t} else {\n\t\t\tstring b = asn.substr(0,ii), c = asn.substr(ii+1);\n\t\t\tchar op = asn[ii];\n\t\t\tif (!var2node.count(b)) {\n\t\t\t\tadd_node(b);\n\t\t\t}\n\t\t\tif (!var2node.count(c)) {\n\t\t\t\tadd_node(c);\n\t\t\t}\n\t\t\ttuple<char,ll,ll> tpl = make_tuple(op,var2node[b],var2node[c]);\n\t\t\tif (!operations.count(tpl)) {\n\t\t\t\tnodes.pb(tpl);\n\t\t\t\toriginal_var.pb(a);\n\t\t\t\toperations[tpl] = m++;\n\t\t\t}\n\t\t\tvar2node[a] = operations[tpl];\n\t\t}\n\t}\n\t\n\tif (!var2node.count(\"res\")) {\n\t\tcout << 0 << endl;\n\t\treturn 0;\n\t}\n \n\tauto fresh = [&]() {\n\t\tstring s = \"aaaa\";\n\t\twhile (var2node.count(s)) {\n\t\t\tFOR(i,0,4) s[i] = 'a' + rand() % 26;\n\t\t}\n\t\tvar2node[s] = -1;\n\t\treturn s;\n\t};\n\t\n\tvector<string> res;\n\tmap<ll,string> new_var;\n \n\tfunction<string(ll)> rec = [&](ll cur) {\n\t\tif (new_var.count(cur)) return new_var[cur];\n\t\t\n\t\tchar op;\n\t\tll a, b;\n\t\ttie(op,a,b) = nodes[cur];\n\t\tif (op == '=') return original_var[cur];\n\t\t\n\t\tstring stra = rec(a), strb = rec(b);\n\t\t\n\t\tstring str = (cur == var2node[\"res\"]) ? \"res\" : fresh();\n\t\tres.pb(str + \"=\" + stra + op + strb);\n\t\treturn new_var[cur] = str;\n\t};\n\t\n\tstring lst = rec(var2node[\"res\"]);\n\tif (lst != \"res\") res.pb(\"res=\" + lst);\n\tcout << sz(res) << endl;\n\tfor (string str: res) cout << str << endl;\n \n}\n ",
    "tags": [
      "graphs",
      "greedy",
      "hashing",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1157",
    "index": "A",
    "title": "Reachable Numbers",
    "statement": "Let's denote a function $f(x)$ in such a way: we add $1$ to $x$, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,\n\n- $f(599) = 6$: $599 + 1 = 600 \\rightarrow 60 \\rightarrow 6$;\n- $f(7) = 8$: $7 + 1 = 8$;\n- $f(9) = 1$: $9 + 1 = 10 \\rightarrow 1$;\n- $f(10099) = 101$: $10099 + 1 = 10100 \\rightarrow 1010 \\rightarrow 101$.\n\nWe say that some number $y$ is \\textbf{reachable} from $x$ if we can apply function $f$ to $x$ some (possibly zero) times so that we get $y$ as a result. For example, $102$ is reachable from $10098$ because $f(f(f(10098))) = f(f(10099)) = f(101) = 102$; and any number is reachable from itself.\n\nYou are given a number $n$; your task is to count how many different numbers are reachable from $n$.",
    "tutorial": "The key fact in this problem is that the answer is not very large (in fact, it's not greater than $91$). Why is it so? Every $10$ times we apply function $f$ to our current number, it gets divided by $10$ (at least), and the number of such divisions is bounded as $O(\\log n)$. So we can just do the following: store all reachable numbers somewhere, and write a loop that adds current number $n$ to reachable numbers, and sets $n = f(n)$ (we should end this loop when $n$ already belongs to reachable numbers). The most convenient way to store reachable numbers is to use any data structure from your favourite programming language that implemenets a set, but, in fact, the constrains were so small that it was possible to store all reachable numbers in an array.",
    "code": "def f(x):\n\tx += 1\n\twhile(x % 10 == 0):\n\t\tx //= 10\n\treturn x\n\na = set()\nn = int(input())\n\nwhile(not(n in a)):\n\ta.add(n)\n\tn = f(n)\n\nprint(len(a))",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1157",
    "index": "B",
    "title": "Long Number",
    "statement": "You are given a long decimal number $a$ consisting of $n$ digits from $1$ to $9$. You also have a function $f$ that maps every digit from $1$ to $9$ to some (possibly the same) digit from $1$ to $9$.\n\nYou can perform the following operation \\textbf{no more than once}: choose a non-empty \\textbf{contiguous subsegment} of digits in $a$, and replace each digit $x$ from this segment with $f(x)$. For example, if $a = 1337$, $f(1) = 1$, $f(3) = 5$, $f(7) = 3$, and you choose the segment consisting of three rightmost digits, you get $1553$ as the result.\n\nWhat is the maximum possible number you can obtain applying this operation no more than once?",
    "tutorial": "Let's find the first digit in $a$ that becomes strictly greater if we replace it (obviously, if there is no such digit, then the best solution is to leave $a$ unchanged). In the optimal solution we will replace this digit and maybe some digits after this. Why is it so? It is impossible to make any of the previous digits greater (since we found the first digit that can be replaced with a greater one). Then let's analyze all digits to the right of it. We should not replace any digit with a lower digit (because it is better not to replace it and all digits to the right of it at all), but there's nothing wrong with replacing any other digits. So, the segment we need to replace begins with the first digit that can become greater after replacing (and includes this digit) and goes to the right until the first digit that becomes less after replacing (and this digit is excluded).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint f[10];\nstring s;\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\tcin >> s;\n\tfor(int i = 1; i <= 9; i++)\n\t\tcin >> f[i];\n\tvector<int> diff;\n\tfor(int i = 0; i < n; i++)\n\t\tdiff.push_back(f[s[i] - '0'] - (s[i] - '0'));\n\tfor(int i = 0; i < n; i++)\n\t\tif(diff[i] > 0)\n\t\t{\n\t\t\twhile(i < n && diff[i] >= 0)\n\t\t\t{\n\t\t\t\ts[i] = char(f[s[i] - '0'] + '0');\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\tcout << s << endl;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1157",
    "index": "C1",
    "title": "Increasing Subsequence (easy version)",
    "statement": "\\textbf{The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2)}.\n\nYou are given a sequence $a$ consisting of $n$ integers. \\textbf{All these integers are distinct, each value from $1$ to $n$ appears in the sequence exactly once.}\n\nYou are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a \\textbf{strictly} increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).\n\nFor example, for the sequence $[2, 1, 5, 4, 3]$ the answer is $4$ (you take $2$ and the sequence becomes $[1, 5, 4, 3]$, then you take the rightmost element $3$ and the sequence becomes $[1, 5, 4]$, then you take $4$ and the sequence becomes $[1, 5]$ and then you take $5$ and the sequence becomes $[1]$, the obtained increasing sequence is $[2, 3, 4, 5]$).",
    "tutorial": "In this problem the following greedy solution works: let's maintain the last element of the increasing sequence we got and on each turn choose the minimum element greater than this last element among the leftmost and the rightmost. Such turns will maximize the answer. You can find details of implementation in the authors solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tstring res;\n\tint l = 0, r = n - 1;\n\tint lst = 0;\n\twhile (l <= r) {\n\t\tvector<pair<int, char>> cur;\n\t\tif (lst < a[l]) cur.push_back(make_pair(a[l], 'L'));\n\t\tif (lst < a[r]) cur.push_back(make_pair(a[r], 'R'));\n\t\tsort(cur.begin(), cur.end());\n\t\tif (int(cur.size()) == 2) {\n\t\t\tcur.pop_back();\n\t\t}\n\t\tif (int(cur.size()) == 1) {\n\t\t\tif (cur[0].second == 'L') {\n\t\t\t\tres += 'L';\n\t\t\t\tlst = a[l];\n\t\t\t\t++l;\n\t\t\t} else {\n\t\t\t\tres += 'R';\n\t\t\t\tlst = a[r];\n\t\t\t\t--r;\n\t\t\t}\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tcout << res.size() << endl << res << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1157",
    "index": "C2",
    "title": "Increasing Subsequence (hard version)",
    "statement": "\\textbf{The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2)}.\n\nYou are given a sequence $a$ consisting of $n$ integers.\n\nYou are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a \\textbf{strictly} increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).\n\nFor example, for the sequence $[1, 2, 4, 3, 2]$ the answer is $4$ (you take $1$ and the sequence becomes $[2, 4, 3, 2]$, then you take the rightmost element $2$ and the sequence becomes $[2, 4, 3]$, then you take $3$ and the sequence becomes $[2, 4]$ and then you take $4$ and the sequence becomes $[2]$, the obtained increasing sequence is $[1, 2, 3, 4]$).",
    "tutorial": "The solution of the previous problem works for this problem also. Almost works. What if the leftmost element is equal the rightmost element? Which one should we choose? Let's analyze it. If we take the leftmost element then we will nevertake any other element from the right, and vice versa. So we can't meet this case more than once because after meeting it once we can take only leftmost elements or only rightmost elements. The only thing we should understand is which of these two cases is better (take the leftmost element or take the rightmost element). To do it we can just iterate from left to right and calculate the number of elements we can take if we will take the leftmost element each time. If we cannot take the current element then just stop the cycle. And do the same thing for the rightmost element and take the best case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tstring res;\n\tint l = 0, r = n - 1;\n\tint lst = 0;\n\twhile (l <= r) {\n\t\tvector<pair<int, char>> cur;\n\t\tif (lst < a[l]) cur.push_back(make_pair(a[l], 'L'));\n\t\tif (lst < a[r]) cur.push_back(make_pair(a[r], 'R'));\n\t\tsort(cur.begin(), cur.end());\n\t\tif (int(cur.size()) == 2 && cur[0].first != cur[1].first) {\n\t\t\tcur.pop_back();\n\t\t}\n\t\tif (int(cur.size()) == 1) {\n\t\t\tif (cur[0].second == 'L') {\n\t\t\t\tres += 'L';\n\t\t\t\tlst = a[l];\n\t\t\t\t++l;\n\t\t\t} else {\n\t\t\t\tres += 'R';\n\t\t\t\tlst = a[r];\n\t\t\t\t--r;\n\t\t\t}\n\t\t} else if (int(cur.size()) == 2) {\n\t\t\tint cl = 1, cr = 1;\n\t\t\twhile (l + cl <= r && a[l + cl] > a[l + cl - 1]) ++cl;\n\t\t\twhile (r - cr >= l && a[r - cr] > a[r - cr + 1]) ++cr;\n\t\t\tif (cl > cr) {\n\t\t\t\tres += string(cl, 'L');\n\t\t\t} else {\n\t\t\t\tres += string(cr, 'R');\n\t\t\t}\n\t\t\tbreak;\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tcout << res.size() << endl << res << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1157",
    "index": "D",
    "title": "N Problems During K Days",
    "statement": "Polycarp has to solve exactly $n$ problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in $k$ days. It means that Polycarp has exactly $k$ days for training!\n\nPolycarp doesn't want to procrastinate, so he wants to solve at least one problem during each of $k$ days. He also doesn't want to overwork, so if he solves $x$ problems during some day, he should solve no more than $2x$ problems during the next day. And, at last, he wants to improve his skill, so if he solves $x$ problems during some day, he should solve at least $x+1$ problem during the next day.\n\nMore formally: let $[a_1, a_2, \\dots, a_k]$ be the array of numbers of problems solved by Polycarp. The $i$-th element of this array is the number of problems Polycarp solves during the $i$-th day of his training. Then the following conditions must be satisfied:\n\n- sum of all $a_i$ for $i$ from $1$ to $k$ should be $n$;\n- $a_i$ should be \\textbf{greater than zero} for each $i$ from $1$ to $k$;\n- the condition $a_i < a_{i + 1} \\le 2 a_i$ should be satisfied for each $i$ from $1$ to $k-1$.\n\nYour problem is to find \\textbf{any} array $a$ of length $k$ satisfying the conditions above or say that it is impossible to do it.",
    "tutorial": "I suppose there are some solutions without cases handling, but I'll describe my own, it handling approximately $5$ cases. Firstly, let $nn = n - \\frac{k(k+1)}{2}$. If $nn < 0$ then the answer is \"NO\" already. Otherwise let's construct the array $a$, where all $a_i$ are $\\lfloor\\frac{nn}{k}\\rfloor$ (except rightmost $nn \\% k$ values, they are $\\lceil\\frac{nn}{k}\\rceil$). It is easy to see that the sum of this array is $nn$, it is sorted in non-decreasing order and the difference between the maximum and the minimum elements is not greater than $1$. Let's add $1$ to $a_1$, $2$ to $a_2$ and so on (this is what we subtract from $n$ at the beginning of the solution). Then if $nn \\ne k - 1$ or $k = 1$ then this answer is correct. Otherwise we got some array of kind $1, 3, \\dots, a_k$. How do we fix that? For $k=2$ or $k=3$ there is no answer for this case (you can try to prove it or try to find answers for cases $n=4, k=2$ and $n=8, k=3$). Otherwise $k > 3$ and we can subtract one from $a_2$ and add it to $a_k$ and this answer will be correct (this also can be proved with some easy formulas). Time complexity: $O(k)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tif (n < k * 1ll * (k + 1) / 2) {\n\t\tcout << \"NO\" << endl;\n\t\treturn 0;\n\t}\n\t\n\tint nn = n - k * (k + 1) / 2;\n\tvector<int> a(k);\n\tfor (int i = 0; i < k; ++i) {\n\t\ta[i] = i + 1 + (nn / k) + (i >= k - nn % k);\n\t}\n\t\n\tif (nn != k - 1) {\n\t\tcout << \"YES\" << endl;\n\t\tfor (int i = 0; i < k; ++i) cout << a[i] << \" \";\n\t\tcout << endl;\n\t} else {\n\t\tif (k > 3) {\n\t\t\t--a[1];\n\t\t\t++a[k - 1];\n\t\t}\n\t\tif (k == 2 || k == 3) {\n\t\t\tcout << \"NO\" << endl;\n\t\t} else {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tfor (int i = 0; i < k; ++i) cout << a[i] << \" \";\n\t\t\tcout << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1157",
    "index": "E",
    "title": "Minimum Array",
    "statement": "You are given two arrays $a$ and $b$, both of length $n$. All elements of both arrays are from $0$ to $n-1$.\n\nYou can reorder elements of the array $b$ (if you want, you may leave the order of elements as it is). After that, let array $c$ be the array of length $n$, the $i$-th element of this array is $c_i = (a_i + b_i) \\% n$, where $x \\% y$ is $x$ modulo $y$.\n\nYour task is to reorder elements of the array $b$ to obtain the \\textbf{lexicographically} minimum possible array $c$.\n\nArray $x$ of length $n$ is lexicographically less than array $y$ of length $n$, if there exists such $i$ ($1 \\le i \\le n$), that $x_i < y_i$, and for any $j$ ($1 \\le j < i$) $x_j = y_j$.",
    "tutorial": "Let's maintain all elements of the array $b$ in a set that allows multiple copies of equal elements (std::multiset for C++). Then let's iterate from left to right over the array $a$ and try to minimize the current element in array $c$. This order will minimize the resulting array by lexicographical comparing definition. So for the $i$-th element $a_i$ let's find the minimum element greater than or equal to $n - a_i$ in the set because $n - a_i$ will give us remainder $0$, $n - a_i + 1$ will give us remainder $1$ and so on. If there is no greater or equal element in the set then let's take the minimum element of the set and take it as a pair for $a_i$ otherwise let's take this greater or equal element and remove it from the set. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tmultiset<int> b;\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\tb.insert(x);\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tauto it = b.lower_bound(n - a[i]);\n\t\tif (it == b.end()) it = b.begin();\n\t\tcout << (a[i] + *it) % n << \" \";\n\t\tb.erase(it);\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1157",
    "index": "F",
    "title": "Maximum Balanced Circle",
    "statement": "There are $n$ people in a row. The height of the $i$-th person is $a_i$. You can choose \\textbf{any} subset of these people and try to arrange them into a \\textbf{balanced circle}.\n\nA \\textbf{balanced circle} is such an order of people that the difference between heights of any adjacent people is no more than $1$. For example, let heights of chosen people be $[a_{i_1}, a_{i_2}, \\dots, a_{i_k}]$, where $k$ is the number of people you choose. Then the condition $|a_{i_j} - a_{i_{j + 1}}| \\le 1$ should be satisfied for all $j$ from $1$ to $k-1$ and the condition $|a_{i_1} - a_{i_k}| \\le 1$ should be also satisfied. $|x|$ means the absolute value of $x$. It is obvious that the circle consisting of one person is balanced.\n\nYour task is to choose the maximum number of people and construct a \\textbf{balanced circle} consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.",
    "tutorial": "Let's realize what we need to construct the minimum balanced circle with heights from $l$ to $r$. We can represent it as $l, l + 1, \\dots, r - 1, r, r - 1, \\dots, l + 1$. As we can see, we need one occurrence of $l$ and $r$ and two occurrences of all other heights from $l + 1$ to $r - 1$. How can we find the maximum balanced circle using this information? We can find the maximum by inclusion segment of neighboring heights with at least two occurrences using the array of frequencies $cnt$, sorted array of unique heights $b$ and two pointers technique. For the current left border $l$ we should increase $r$ (initially it is $l + 1$ and it is an excluded border) while $b_r - b_{r - 1}=1$ and $cnt_{b_r} \\ge 2$. Then for the current left and right borders we can try to extend the segment to the left if $b_l - b_{l - 1} = 1$ and to the right if $b_{r + 1} - b_r = 1$ and try to update the answer with the the current segment (and go to the next segment). There may be some corner cases like $n = 1$ or all $cnt$ are $1$, but you can avoid them if you will implement the solution carefully. There are almost no corner cases in my solution, you can see details of implementation in authors code. Time complexity: $O(n \\log n)$ or $O(n)$ (depends on sorting method).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tvector<int> cnt(200 * 1000 + 1);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\t++cnt[a[i]];\n\t}\n\t\n\tsort(a.begin(), a.end());\n\ta.resize(unique(a.begin(), a.end()) - a.begin());\n\t\n\tint l = 0, r = 0;\n\tint ans = cnt[a[0]];\n\tfor (int i = 0; i < int(a.size()); ++i) {\n\t\tint j = i + 1;\n\t\tint sum = cnt[a[i]];\n\t\twhile (a[j] - a[j - 1] == 1 && cnt[a[j]] > 1) {\n\t\t\tsum += cnt[a[j]];\n\t\t\t++j;\n\t\t}\n\t\tint cr = j - 1;\n\t\tif (j < n && a[j] - a[j - 1] == 1) {\n\t\t\tsum += cnt[a[j]];\n\t\t\tcr = j;\n\t\t}\n\t\tif (ans < sum) {\n\t\t\tans = sum;\n\t\t\tl = i;\n\t\t\tr = cr;\n\t\t}\n\t\ti = j - 1;\n\t}\n\t\n\tcout << ans << endl;\n\tfor (int c = 0; c < cnt[a[l]]; ++c) cout << a[l] << \" \";\n\tfor (int i = l + 1; i < r; ++i) {\n\t\tfor (int c = 0; c < cnt[a[i]] - 1; ++c) cout << a[i] << \" \";\n\t}\n\tfor (int c = 0; l != r && c < cnt[a[r]]; ++c) cout << a[r] << \" \";\n\tfor (int i = r - 1; i > l; --i) cout << a[i] << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1157",
    "index": "G",
    "title": "Inverse of Rows and Columns",
    "statement": "You are given a binary matrix $a$ of size $n \\times m$. A binary matrix is a matrix where each element is either $0$ or $1$.\n\nYou may perform some (possibly zero) operations with this matrix. During each operation you can inverse the row of this matrix or a column of this matrix. Formally, inverting a row is changing all values in this row to the opposite ($0$ to $1$, $1$ to $0$). Inverting a column is changing all values in this column to the opposite.\n\nYour task is to sort the initial matrix by some sequence of such operations. The matrix is considered \\textbf{sorted} if the array $[a_{1, 1}, a_{1, 2}, \\dots, a_{1, m}, a_{2, 1}, a_{2, 2}, \\dots, a_{2, m}, \\dots, a_{n, m - 1}, a_{n, m}]$ is sorted in non-descending order.",
    "tutorial": "The first observation: if we have an answer where the first row is inverted, we can inverse all rows and columns, then the matrix will remain the same, and the first row is not inverted in the new answer. So we can suppose that the first row is never inverted. Note that this will be true only for slow solution. The second observation: if we consider a sorted matrix, its first row either consists only of '0's, or has at least one '1' and then all other rows consist only of '1's. This observation can be extended to the following (one user wrote a comment about it and I pinned the link to it above) which can improve time complexity of the solution a lot: in the sorted matrix either the first row consists only of '0's, or the last row consists only of '1's (the corner case is $n = 1$, but for $n=1$ we can obtain both answers). So what should we do with these observations? I will explain a slow solution, a faster solution can be obtained by mirroring one of cases of this one. Let's iterate over the number of '0's in the first row. Let it be $cnt$. Then the first $cnt$ elements of the first string should be '0's, and all others should be '1's. We can do it by inverting the columns with elements '1' among first $cnt$ elements of the first row and columns with elements '0' among remaining elements. So, it's case handling time! The first case (when $cnt < m$) is pretty easy. We have to check if all rows from $2$ to $n$ that they consist only of '0's or only of '1's (and if some row consists of '0's then we should invert it). If it is true then we found the answer. Otherwise the first row consists only of '0's. So we have to find the \"transitional\" row (the row with some '0's on the prefix and '1's on the suffix or vice versa). If the number of such rows among all rows from $2$ to $n$ is greater than $1$ then this configuration is bad. If the number of such rows is $1$ then let $idx$ be the index of this row. Then we should inverse all rows above it consisting only of '1's and all rows consisting only of '0's below it. And we have to check if the current row is really transitional. We know that its sum is neither $0$ nor $m$ so there is at least one '1' and at least '0' in it. If the first element is '1' then let's inverse it. Then we just should check if this row is sorted, and if it is then we found the answer. And the last case is if there are no transitional rows in the matrix. Then we should invert all rows from $2$ to $n$ consisting only of '0's (or only of '1's, it does not matter). So, we have a solution with time complexity $O(n^3)$. Each number of '0's in the first row is processed in $O(n^2)$ and there are $O(n)$ such numbers. But we can see that if we apply the last case (when the number of '0' is $m$) to the first row and then do the same, but with the last row consisting of $m$ '1', we can get a solution in $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\n\nvoid invRow(vector<vector<int>> &a, int idx) {\n\tfor (int pos = 0; pos < m; ++pos) {\n\t\ta[idx][pos] ^= 1;\n\t}\n}\n\nvoid invCol(vector<vector<int>> &a, int idx) {\n\tfor (int pos = 0; pos < n; ++pos) {\n\t\ta[pos][idx] ^= 1;\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m;\n\tvector<vector<int>> a(n, vector<int>(m));\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tcin >> a[i][j];\n\t\t}\n\t}\n\t\n\tfor (int cnt0 = 0; cnt0 <= m; ++cnt0) {\n\t\tstring r(n, '0');\n\t\tstring c(m, '0');\n\t\tvector<vector<int>> b = a;\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tif ((j < cnt0 && b[0][j] == 1) || (j >= cnt0 && b[0][j] == 0)) {\n\t\t\t\tinvCol(b, j);\n\t\t\t\tc[j] = '1';\n\t\t\t}\n\t\t}\n\t\tbool ok = true;\n\t\tif (cnt0 < m) {\n\t\t\tfor (int i = 1; i < n; ++i) {\n\t\t\t\tint sum = accumulate(b[i].begin(), b[i].end(), 0);\n\t\t\t\tif (sum != 0 && sum != m) {\n\t\t\t\t\tok = false;\n\t\t\t\t} else if (sum == 0) {\n\t\t\t\t\tinvRow(b, i);\n\t\t\t\t\tr[i] = '1';\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tint idx = -1;\n\t\t\tfor (int i = 1; i < n; ++i) {\n\t\t\t\tint sum = accumulate(b[i].begin(), b[i].end(), 0);\n\t\t\t\tif (sum != 0 && sum != m) {\n\t\t\t\t\tif (idx != -1) ok = false;\n\t\t\t\t\telse idx = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (idx == -1) {\n\t\t\t\tfor (int i = 1; i < n; ++i) {\n\t\t\t\t\tint sum = accumulate(b[i].begin(), b[i].end(), 0);\n\t\t\t\t\tif (sum == 0) {\n\t\t\t\t\t\tinvRow(b, i);\n\t\t\t\t\t\tr[i] = '1';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (int i = 1; i < idx; ++i) {\n\t\t\t\t\tint sum = accumulate(b[i].begin(), b[i].end(), 0);\n\t\t\t\t\tif (sum == m) {\n\t\t\t\t\t\tinvRow(b, i);\n\t\t\t\t\t\tr[i] = '1';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (b[idx][0] == 1) {\n\t\t\t\t\tinvRow(b, idx);\n\t\t\t\t\tr[idx] = '1';\n\t\t\t\t}\n\t\t\t\tfor (int j = 1; j < m; ++j) {\n\t\t\t\t\tif (b[idx][j] < b[idx][j - 1]) {\n\t\t\t\t\t\tok = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = idx + 1; i < n; ++i) {\n\t\t\t\t\tint sum = accumulate(b[i].begin(), b[i].end(), 0);\n\t\t\t\t\tif (sum == 0) {\n\t\t\t\t\t\tinvRow(b, i);\n\t\t\t\t\t\tr[i] = '1';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (ok) {\n\t\t\tcout << \"YES\" << endl << r << endl << c << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << \"NO\" << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1158",
    "index": "A",
    "title": "The Party and Sweets",
    "statement": "$n$ boys and $m$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $1$ to $n$ and all girls are numbered with integers from $1$ to $m$. For all $1 \\leq i \\leq n$ the minimal number of sweets, which $i$-th boy presented to some girl is equal to $b_i$ and for all $1 \\leq j \\leq m$ the maximal number of sweets, which $j$-th girl received from some boy is equal to $g_j$.\n\nMore formally, let $a_{i,j}$ be the number of sweets which the $i$-th boy give to the $j$-th girl. Then $b_i$ is equal exactly to the minimum among values $a_{i,1}, a_{i,2}, \\ldots, a_{i,m}$ and $g_j$ is equal exactly to the maximum among values $b_{1,j}, b_{2,j}, \\ldots, b_{n,j}$.\n\nYou are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $a_{i,j}$ for all $(i,j)$ such that $1 \\leq i \\leq n$ and $1 \\leq j \\leq m$. You are given the numbers $b_1, \\ldots, b_n$ and $g_1, \\ldots, g_m$, determine this number.",
    "tutorial": "Let's note, that for all $1 \\leq i \\leq n, 1 \\leq j \\leq m$ is is true, that $b_i \\leq g_j$, because $b_i \\leq a_{{i}{j}} \\leq g_j$. So $max(b_1, b_2, \\ldots, b_n) \\leq min(g_1, g_2, \\ldots, g_m)$. If it is not true, the answer is $-1$. Let's prove, that if $max(b_1, b_2, \\ldots, b_n) \\leq min(g_1, g_2, \\ldots, g_m)$ the answer always exists and let's find it. Let's make all $a_{{i}{j}} = b_i$. Let's note, that $b_i = min(a_{{i}{1}}, a_{{i}{2}}, \\ldots, a_{{i}{m}})$. But in this case maximums in each column can be wrong. To make them correct we should place $1 \\leq j \\leq m$ into the $j$-th column of the table $a$ the number $g_j$. To make the sum as small as possible we want to place all $g_j$ into the row with maximal $b_i$. If we will make it the minimal in this row will be equal $min(g_1, g_2, \\ldots, g_m)$. But the number $b$ for this row is equal to $max(b_1, b_2, \\ldots, b_n)$. So, if $max(b_1, b_2, \\ldots, b_n) = min(g_1, g_2, \\ldots, g_m)$ the answer is equal to $(b_1 + b_2 + \\ldots + b_n) m + g_1 + g_2 + \\ldots + g_m - max(b_1, b_2, \\ldots, b_n) m$. But if $max(b_1, b_2, \\ldots, b_n) < min(g_1, g_2, \\ldots, g_m)$ we should place some of the $g_j$ in the other row. Let's place $g_1$ into the row there $b_i$ is second maximum in the array $b$. It's easy to check in this case, that all minimums, maximums will be correct in this case. In this case the answer is equal to $(b_1 + b_2 + \\ldots + b_n) m + g_1 + g_2 + \\ldots + g_m - max(b_1, b_2, \\ldots, b_n) (m - 1) - max_2(b_1, b_2, \\ldots, b_n)$. So: If $max(b_1, b_2, \\ldots, b_n) > min(g_1, g_2, \\ldots, g_m)$ the answer is $-1$; If $max(b_1, b_2, \\ldots, b_n) = min(g_1, g_2, \\ldots, g_m)$ the answer is $(b_1 + b_2 + \\ldots + b_n) m + g_1 + g_2 + \\ldots + g_m - max(b_1, b_2, \\ldots, b_n) m$; If $max(b_1, b_2, \\ldots, b_n) < min(g_1, g_2, \\ldots, g_m)$ the answer is $(b_1 + b_2 + \\ldots + b_n) m + g_1 + g_2 + \\ldots + g_m - max(b_1, b_2, \\ldots, b_n) (m - 1) - max_2(b_1, b_2, \\ldots, b_n)$. Maximum, second maximum in the array $b$, minimum in the array $g$ and the sums in the arrays $b$ and $g$ can be easily computed in the linear time. So, we have a linear time solution. Complexity: $O(n + m)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nint n, m;\nll r_max, c_min, x, r_max2, r_sum, c_sum, ans;\n \nint main()\n{\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    cin >> n >> m;\n    r_max = 0;\n    r_max2 = 0;\n    r_sum = 0;\n    for (int i = 0; i < n; i++)\n    {\n        cin >> x;\n        if (r_max <= x)\n        {\n            r_max2 = r_max;\n            r_max = x;\n        }\n        else if (r_max2 <= x)\n            r_max2 = x;\n        r_sum += x;\n    }\n    c_min = (int)(1e8);\n    c_sum = 0;\n    for (int i = 0; i < m; i++)\n    {\n        cin >> x;\n        if (c_min >= x)\n            c_min = x;\n        c_sum += x;\n    }\n    if (r_max > c_min)\n    {\n        cout << \"-1\";\n        return 0;\n    }\n    ans = r_sum * (ll)m;\n    ans += c_sum;\n    ans -= r_max * (ll)m;\n    if (r_max < c_min)\n        ans += r_max - r_max2;\n    cout << ans;\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1158",
    "index": "B",
    "title": "The minimal unique substring",
    "statement": "Let $s$ be some string consisting of symbols \"0\" or \"1\". Let's call a string $t$ a substring of string $s$, if there exists such number $1 \\leq l \\leq |s| - |t| + 1$ that $t = s_l s_{l+1} \\ldots s_{l + |t| - 1}$. Let's call a substring $t$ of string $s$ unique, if there exist only one such $l$.\n\nFor example, let $s = $\"1010111\". A string $t = $\"010\" is an unique substring of $s$, because $l = 2$ is the only one suitable number. But, for example $t = $\"10\" isn't a unique substring of $s$, because $l = 1$ and $l = 3$ are suitable. And for example $t =$\"00\" at all isn't a substring of $s$, because there is no suitable $l$.\n\nToday Vasya solved the following problem at the informatics lesson: given a string consisting of symbols \"0\" and \"1\", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.\n\nYou are given $2$ positive integers $n$ and $k$, such that $(n \\bmod 2) = (k \\bmod 2)$, where $(x \\bmod 2)$ is operation of taking remainder of $x$ by dividing on $2$. Find any string $s$ consisting of $n$ symbols \"0\" or \"1\", such that the length of its minimal unique substring is equal to $k$.",
    "tutorial": "Let's define the value $a = \\frac {n-k} 2$. We know, that $(k \\bmod 2) = (n \\bmod 2)$ so $a$ is integer number. Let's construct this string $s$: $a$ symbols \"0\", $1$ symbol \"1\", $a$ symbols \"0\", $1$ symbol \"1\", $\\ldots$ Let's prove, that this string satisfy the conditions. Let's note, that it's period is equal to $(a+1)$. Let the substring $t$ be unique. Let's look at the only $l$ for this substring. But if $l > a + 1$, then $l - (a + 1)$ satisfy (as the left border of the string $t$ occurrence), if $l \\leq n - (a + |t|)$ then $l + (a + 1)$ satisfy (because the period of $s$ is equal to $(a + 1)$, so shift on $(a + 1)$ don't change anything). So $l \\leq a + 1$ and $n - (a + |t|) < l$, because in other case $l$ can't be the only. So $n - (a + |t|) < l \\leq a + 1$ so $n - (a + |t|) < a + 1$ so $n - (a + |t|) \\leq a$ so $n - 2 \\cdot a \\leq |t|$ so $k \\leq |t|$. As the example of the unique substring of length $k$ we can take $t = s_{a+1} \\ldots s_{n-a}$. Complexity: $O(n)$. Bonus: How to solve the problem without condition, that $(k \\bmod 2) = (n \\bmod 2)$? For what $k$ the answer exists?",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n    int n, k, a;\n    cin >> n >> k;\n    a = (n - k) / 2;\n    for (int i = 0; i < n; i++)\n        cout << ((i + 1) % (a + 1) == 0);\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1158",
    "index": "C",
    "title": "Permutation recovery",
    "statement": "Vasya has written some permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$, so for all $1 \\leq i \\leq n$ it is true that $1 \\leq p_i \\leq n$ and all $p_1, p_2, \\ldots, p_n$ are different. After that he wrote $n$ numbers $next_1, next_2, \\ldots, next_n$. The number $next_i$ is equal to the minimal index $i < j \\leq n$, such that $p_j > p_i$. If there is no such $j$ let's let's define as $next_i = n + 1$.\n\nIn the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values $next_i$ are completely lost! If for some $i$ the value $next_i$ is lost, let's say that $next_i = -1$.\n\nYou are given numbers $next_1, next_2, \\ldots, next_n$ (maybe some of them are equal to $-1$). Help Vasya to find such permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$, that he can write it to the notebook and all numbers $next_i$, which are not equal to $-1$, will be correct.",
    "tutorial": "Note that if there are indices $i < j$ for which the values $next_i$ and $next_j$ are defined and $i < j < next_i < next_j$ are satisfied, then there is no answer. Suppose that this is not true and there exists permutation $p_1, p_2, \\ldots, p_n$. Note that since $j < next_i$ we get that $p_i > p_j$ (otherwise $next_i$ would not be the minimum position in which the number is greater than $p_i$). But then $p_j < p_i < p_{next_i}$, so $next_j$ is not the minimum position for $j$. Contradiction. Now we prove that if for any pair of indices $i < j$ such condition is not satisfied, then the permutation always exists. First, let's get rid of $next_i = -1$. If $next_i = -1$ let's say $next_i = i + 1$. Note that for any pair $i < j$ the condition $i < j < next_i < next_j$ is still not satisfied (since $next_i = i + 1$ cannot take part in such inequality). Consider the following rooted tree with $n + 1$ vertices: the vertex with index $n + 1$ will be the root, and the ancestor of the vertex with index $i$ will be $next_i$. Since it is always $i < next_i$ we get the rooted tree. Let's run the depth first search algorithm ($dfs$) from the vertex $n + 1$ in this tree. In this case, we will bypass the sons of each vertex in order from the smaller number to the larger one. Let's make some global variable $timer = n + 1$. Each time we come to the vertex $i$, we will make $p_i = timer$ and reduce $timer$ by $1$. Note that $p_1, p_2, \\ldots, p_n$ will form a permutation of numbers from $1$ to $n$. We prove that this permutation is the answer. First of all, for all $i$ due to $next_i$ was the ancestor of $i$, we'll go there early and so $p_{next_i} > p_i$. Let $i < j < next_i$. We need to prove that we will come to the vertex $j$ later than to the vertex $i$. Note that then the vertex $next_i$ will be a descendant of $j$ in the tree, because if you start go from $j$ by $next$, you cannot jump over $next_i$, because otherwise there is an index $x$, for which the inequality $i < x < next_i < next_x$ is satisfied. But such pair of indexes $i$, $x$ cannot exist. We'll get to $j$ later because the son of $next_i$, which is the ancestor of $j$ will be $\\geq j$, and thus $> i$. That is, we understood what is the criterion of the answer and learned how to quickly build an answer, if this criterion is satisfied. But we still need to check that this criterion is satisfied. This can be done by some simple linear algorithm. But we will do this: let's make an algorithm for constructing the answer (without checking the criterion) and find the permutation $p$. Now, using the stack and the standard algorithm, we find the $next_i$ values for it. If they match the given $next_i$, then we have found the answer, otherwise, let's say that there is no answer. If the criterion is satisfied we will find the answer and if not satisfied after checking $p$ we will say there are no answers. Complexity: $O(n)$ time and memory.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int M = 5e5 + 239;\n \nint n, a[M], p[M], timer;\nvector<int> v[M];\nvector<int> q;\n \nvoid dfs(int t)\n{\n    p[t] = timer--;\n    for (int i : v[t])\n        dfs(i);\n}\n \nvoid solve()\n{\n    cin >> n;\n    for (int i = 0; i <= n; i++) v[i].clear();\n    for (int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n        a[i]--;\n        if (a[i] == -2) a[i] = i + 1;\n        v[a[i]].push_back(i);\n    }\n    timer = n;\n    dfs(n);\n    q.clear();\n    for (int i = n - 1; i >= 0; i--)\n    {\n        while (!q.empty() && p[q.back()] < p[i])\n            q.pop_back();\n        if ((q.empty() && a[i] != n) || (!q.empty() && q.back() != a[i]))\n        {\n            cout << \"-1\\n\";\n            return;\n        }\n        q.push_back(i);\n    }\n    for (int i = 0; i < n; i++)\n        cout << p[i] + 1 << \" \";\n    cout << \"\\n\";\n}\n \nint main()\n{\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int T;\n    cin >> T;\n    while (T--) solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1158",
    "index": "D",
    "title": "Winding polygonal line",
    "statement": "Vasya has $n$ different points $A_1, A_2, \\ldots A_n$ on the plane. No three of them lie on the same line He wants to place them in some order $A_{p_1}, A_{p_2}, \\ldots, A_{p_n}$, where $p_1, p_2, \\ldots, p_n$ — some permutation of integers from $1$ to $n$.\n\nAfter doing so, he will draw oriented polygonal line on these points, drawing oriented segments from each point to the next in the chosen order. So, for all $1 \\leq i \\leq n-1$ he will draw oriented segment from point $A_{p_i}$ to point $A_{p_{i+1}}$. He wants to make this polygonal line satisfying $2$ conditions:\n\n- it will be non-self-intersecting, so any $2$ segments which are not neighbors don't have common points.\n- it will be \\textbf{winding}.\n\nVasya has a string $s$, consisting of $(n-2)$ symbols \"L\" or \"R\". Let's call an oriented polygonal line \\textbf{winding}, if its $i$-th turn left, if $s_i = $ \"L\" and right, if $s_i = $ \"R\". More formally: $i$-th turn will be in point $A_{p_{i+1}}$, where oriented segment from point $A_{p_i}$ to point $A_{p_{i+1}}$ changes to oriented segment from point $A_{p_{i+1}}$ to point $A_{p_{i+2}}$. Let's define vectors $\\overrightarrow{v_1} = \\overrightarrow{A_{p_i} A_{p_{i+1}}}$ and $\\overrightarrow{v_2} = \\overrightarrow{A_{p_{i+1}} A_{p_{i+2}}}$. Then if in order to rotate the vector $\\overrightarrow{v_1}$ by the smallest possible angle, so that its direction coincides with the direction of the vector $\\overrightarrow{v_2}$ we need to make a turn counterclockwise, then we say that $i$-th turn is to the left, and otherwise to the right. For better understanding look at this pictures with some examples of turns:\n\n\\begin{center}\n{\\small There are left turns on this picture}\n\\end{center}\n\n\\begin{center}\n{\\small There are right turns on this picture}\n\\end{center}\n\nYou are given coordinates of the points $A_1, A_2, \\ldots A_n$ on the plane and string $s$. Find a permutation $p_1, p_2, \\ldots, p_n$ of the integers from $1$ to $n$, such that the polygonal line, drawn by Vasya satisfy two necessary conditions.",
    "tutorial": "Let's describe the algorithm, which is always finding the answer: Let's find any point $A_i$, lying at the convex hull of points $A_1, A_2, \\ldots, A_n$. We don't need to construct the convex hull for this, we can simply take the point with the minimal $y$. This point will be the first in the permutation. Let's construct the polygonal line one by one. Let the last added point to the polygonal line be $A_{p_i}$. The point $A_{p_i}$ should always lie at the convex hull of remaining points and $A_{p_i}$ (at the beginning it is true). If $s_i =$ \"L\" the next point be the most right point (sorted by angle) and if $s_i =$ \"R\"the next point be the most left point (sorted by angle) from the remaining. This is the picture for this: It is easy to see, that the new point lies at the convex hull. The next rotation at the point $A_{p_{i+1}}$ will be to the right side, because if $s_i =$ \"L\" all other points lies from the left of the vector $\\overrightarrow{A_{p_i} A_{p_{i+1}}}$ and if $s_i =$ \"R\" all other points lies from the right of the vector $\\overrightarrow{A_{p_i} A_{p_{i+1}}}$. To take the most left or right point, sorted by the angle from the remaining we will simply take minimum or maximum using the linear search. The point $X$ lies to the right of the point $Y$ from the point $A_{p_i}$, if $\\overrightarrow{A_{p_i} X} \\times \\overrightarrow{A_{p_i} Y} > 0$. The operation $\\times$ is vectors multiply. Complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int M = 2e3 + 239;\n \nint n, x[M], y[M];\nbool used[M];\nstring s;\n \nint main()\n{\n    cin >> n;\n    for (int i = 0; i < n; i++)\n        cin >> x[i] >> y[i];\n    cin >> s;\n    s += 'L';\n    int id = -1;\n    for (int i = 0; i < n; i++)\n        if (id == -1 || x[id] > x[i] || (x[id] == x[i] && y[id] > y[i]))\n            id = i;\n    used[id] = true;\n    cout << (id + 1) << \" \";\n    for (int it = 1; it < n; it++)\n    {\n        int to = -1;\n        for (int i = 0; i < n; i++)\n            if (!used[i])\n            {\n                if (to == -1)\n                    to = i;\n                else\n                {\n                    ll now = (ll)(x[i] - x[id]) * (ll)(y[to] - y[id]) - (ll)(y[i] - y[id]) * (ll)(x[to] - x[id]);\n                    if (s[it - 1] == 'R') now = -now;\n                    if (now > 0) to = i;\n                }\n            }\n        used[to] = true;\n        id = to;\n        cout << (id + 1) << \" \";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1158",
    "index": "E",
    "title": "Strange device",
    "statement": "\\textbf{It is an interactive problem.}\n\nVasya enjoys solving quizzes. He found a strange device and wants to know how it works.\n\nThis device encrypted with the tree (connected undirected graph without cycles) with $n$ vertices, numbered with integers from $1$ to $n$. To solve this quiz you should guess this tree.\n\nFortunately, this device can make one operation, using which you should guess the cipher. You can give the device an array $d_1, d_2, \\ldots, d_n$ of non-negative integers. On the device, there are $n$ lamps, $i$-th of them is connected with $i$-th vertex of the tree. For all $i$ the light will turn on the $i$-th lamp, if there exist such vertex of the tree with number $j \\neq i$ that $dist(i, j) \\leq d_j$. Let's define $dist(i, j)$ as the distance between vertices $i$ and $j$ in tree or number of edges on the simple path between vertices $i$ and $j$.\n\nVasya wants to solve this quiz using $\\leq 80$ operations with the device and guess the tree. Help him!",
    "tutorial": "The solution will consist of two parts. 1 part Let's divide all points into sets with equal distance to the vertex $1$. To do this, we will do the following algorithm. How to understand what set of points lies at a distance $\\lfloor \\frac{n}{2} \\rfloor$ from the top of $1$? Let's fill $d$ with zeros and make $d_1 = \\lfloor \\frac{n}{2} \\rfloor$ for the first operation and $d_1 = \\lfloor \\frac{n}{2} \\rfloor - 1$ for the second operation. After that we will make $2$ operations with such $d$ arrays. Those vertices whose bulbs did not light up during the first operation lie at a distance of $> \\lfloor \\frac{n}{2} \\rfloor$. Those that caught fire at the first, but did not catch fire at the second operation lie at a distance of $\\lfloor \\frac{n}{2} \\rfloor$. Finally, those who caught fire during the second operation lie at a distance of $< \\lfloor \\frac{n}{2} \\rfloor$. Generalize this idea. We will store the set of distances for which we already know the set of vertices at lying such distance from $1$ (we will call them good distances). Initially it is $0$ (only vertex $1$ at distance $0$) and $n$ (empty vertex set at distance $n$). We will also store between each pair of adjacent good distances $l_1 < l_2$ those vertices for which the distance is greater than $l_1$, but less than $l_2$. Now let's iterate over pairs of adjacent good distances $l_1 < l_2$. Take $m = \\lfloor \\frac{l_1 + l_2}{2} \\rfloor$. Now the sets of vertices lying at distances greater than $l_1$, but less than $m$, exactly $m$ and more than $m$, but less than $l_2$ can be obtained using the two operations described at the beginning. With this action, we make $m$ a good distance. To do this in parallel for several pairs of adjacent good distances just iterate over pairs with even numbers and odd ones. Then as each of the cases would not be adjacent pairs, you can make two common operations. Thus, with the help of $4$ operations, we will make the middle between all pairs of adjacent good distances also a good distance. If we divide in half, then for $\\lceil \\log{n} \\rceil$ of divisions we will make all distances good. At this part we will spend $4 \\lceil \\log{n} \\rceil$ operations. 2 part For each vertex at the distance of $l > 0$ let's find the index of the ancestor vertex lying at a distance of $l-1$ (which is the only one). Suppose we want to do this for only one distance $l > 0$. Note that if we make $d_v = 1$ for all $v \\in S$, for some subset of vertices $S$ lying at a distance $l-1$, and for all other vertices $0$, then among the vertices at a distance $l$ will include those whose ancestor belongs to $S$. Then let's for all $i$ such that $2^i < n$ choose $S$ as the set of vertices $v$ such that $v - 1$ contains $i$-th bit in binary notation and lies at a distance of $l-1$. Then, for each vertex at a distance of $l$, we will know all the bits in the binary representation of its ancestor, that is, we will find this number. This process can also be done in parallel, if we take the distance $l$, giving the same remainder of dividing by $3$. Then, since these distances are not close, they will not interfere with each other. At this part we will spend $3 \\lceil \\log{n} \\rceil$ operations. In total we get a solution using $7 \\lceil \\log{n} \\rceil$ operations. Complexity: $O(n \\log{n})$. Number of operations: $7 \\lceil \\log{n} \\rceil$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int M = 1010;\n \nvector<bool> ask(vector<int> d)\n{\n    cout << \"? \";\n    for (int i : d)\n        cout << i << \" \";\n    cout << endl;\n    string s;\n    cin >> s;\n    vector<bool> ans((int)d.size());\n    for (int i = 0; i < (int)d.size(); i++)\n        ans[i] = (bool)(s[i] - '0');\n    return ans;\n}\n \nint n;\nvector<int> in[M], nxt[M];\nvector<int> pos;\nbool used[M];\nint pr[M];\n \nint main()\n{\n    cin >> n;\n    in[0].push_back(0);\n    for (int i = 1; i < n; i++)\n        nxt[0].push_back(i);\n    used[0] = true;\n    used[n] = true;\n    while (true)\n    {\n        bool stop = true;\n        pos.clear();\n        for (int i = 0; i <= n; i++)\n            if (used[i])\n                pos.push_back(i);\n        for (int st = 0; st < 2; st++)\n        {\n            vector<int> r1(n, 0), r2(n, 0);\n            for (int s = st; s < (int) pos.size() - 1; s += 2)\n            {\n                if (in[pos[s]].empty()) continue;\n                if (pos[s + 1] == pos[s] + 1) continue;\n                if (pos[s + 1] == pos[s] + 2)\n                {\n                    in[pos[s] + 1] = nxt[pos[s]];\n                    nxt[pos[s]].clear();\n                    used[pos[s] + 1] = true;\n                    continue;\n                }\n                stop = false;\n                int mid = (pos[s] + pos[s + 1] + 1) >> 1;\n                for (int x : in[pos[s]])\n                {\n                    r1[x] = mid - pos[s] - 1;\n                    r2[x] = r1[x] + 1;\n                }\n            }\n            vector<bool> a1 = ask(r1);\n            vector<bool> a2 = ask(r2);\n            for (int s = st; s < (int) pos.size() - 1; s += 2)\n            {\n                if (in[pos[s]].empty()) continue;\n                if (pos[s + 1] <= pos[s] + 2) continue;\n                int mid = (pos[s] + pos[s + 1] + 1) >> 1;\n                vector<int> now = nxt[pos[s]];\n                nxt[pos[s]].clear();\n                for (int x : now)\n                {\n                    if (a1[x])\n                        nxt[pos[s]].push_back(x);\n                    else if (a2[x])\n                        in[mid].push_back(x);\n                    else\n                        nxt[mid].push_back(x);\n                }\n                used[mid] = true;\n            }\n        }\n        if (stop)\n            break;\n    }\n    for (int st = 1; st <= 3; st++)\n    {\n        for (int i = 0; (1 << i) < n; i++)\n        {\n            vector<int> r(n, 0);\n            bool need = false;\n            for (int x = st; x < n; x += 3)\n                if (!in[x].empty())\n                    for (int t : in[x - 1])\n                        if ((t >> i) & 1)\n                        {\n                            r[t] = 1;\n                            need = true;\n                        }\n            if (!need) continue;\n            vector<bool> res = ask(r);\n            for (int x = st; x < n; x += 3)\n                if (!in[x].empty())\n                    for (int t : in[x])\n                        if (res[t])\n                            pr[t] ^= (1 << i);\n        }\n    }\n    cout << \"!\" << endl;\n    for (int i = 1; i < n; i++)\n        cout << pr[i] + 1 << \" \" << i + 1 << endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "interactive",
      "math",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1158",
    "index": "F",
    "title": "Density of subarrays",
    "statement": "Let $c$ be some positive integer. Let's call an array $a_1, a_2, \\ldots, a_n$ of positive integers $c$-array, if for all $i$ condition $1 \\leq a_i \\leq c$ is satisfied. Let's call $c$-array $b_1, b_2, \\ldots, b_k$ a \\textbf{subarray} of $c$-array $a_1, a_2, \\ldots, a_n$, if there exists such set of $k$ indices $1 \\leq i_1 < i_2 < \\ldots < i_k \\leq n$ that $b_j = a_{i_j}$ for all $1 \\leq j \\leq k$. Let's define \\textbf{density} of $c$-array $a_1, a_2, \\ldots, a_n$ as maximal non-negative integer $p$, such that any $c$-array, that contains $p$ numbers is a subarray of $a_1, a_2, \\ldots, a_n$.\n\nYou are given a number $c$ and some $c$-array $a_1, a_2, \\ldots, a_n$. For all $0 \\leq p \\leq n$ find the number of sequences of indices $1 \\leq i_1 < i_2 < \\ldots < i_k \\leq n$ for all $1 \\leq k \\leq n$, such that density of array $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$ is equal to $p$. Find these numbers by modulo $998\\,244\\,353$, because they can be too large.",
    "tutorial": "We have some $c$-array $a$. Let's find the criterion, that any $c$-array of length $p$ is its subsequence. To check that $c$-array $b$ is a subsequence of $a$, we should iterate all elements of $b$ and take the most left occurrence of this symbol in $a$, starting from the current moment. Because any $c$-array should be a subsequence of $a$ on each step we can take the symbol the most left occurrence of such is the most right. Let's denote the positions, which we have taken on each step $l_1, l_2, \\ldots, l_p$. So if we will look to the array $a[l_i+1 \\ldots l_{i+1}]$, in this arrays each of the $c$ symbols exists and the symbol $a_{l_{i+1}}$ occurs exactly $1$ time. Let's name such array \"critical block\". So the density of $a \\geq p$, if $a$ is the concatenation of $p$ consecutive critical blocks and some other symbols at the end. Let's note, that the density of any array of length $n$ won't be more than $k = \\frac{n}{c}$. It is obvious, because in any critical block at least $c$ symbols. Let's find $dp_{{t},{i}}$ as the number of subsequences of the array prefix $a[1 \\ldots i]$ that contain the position $i$, which are divided into exactly $t$ critical arrays (and no other characters). We will consider it for all $1 \\leq t \\leq k$ and $1 \\leq i \\leq n$. Let's first understand how to get an answer from these values, and then show how to calculate them. If we denote by $f_t$ the number of subsequences whose density is $\\geq t$, then $f_t = \\sum\\limits_{i=1}^n{dp_ {t},{i}} \\cdot 2^{n - i}$. Next, note that the number of density subsequences exactly $t$ is $ans_t = f_{t+1} - f_t$. Here are $2$ different ways to calculate $dp_{{t},{i}}$: 1) denote by $num_{{i},{j}}$ the number of subsequences of array $a[i \\ldots j]$ that contain $j$ and are critical. Then $num_{{i},{j}} = \\prod\\limits_{x=1, x \\neq a_j}^{c}{(2^{cnt_{{x},{i},{j}}} - 1)}$, where $cnt_{{x},{i},{j}}$ - is the number of characters $x$ among $a[i \\ldots j]$. Then we can calculate $num$ for $O(n^2 c)$. To speed up this calculation to $O(n^2)$ we will fix $i$ and increase $j$ by $1$, supporting $\\prod\\limits_{x=1}^{c}{(2^{cnt_{{x},{i},{j}}} - 1)}$. Then in such a product $1$ multiplier will be changed and it can be recalculated by $O(1)$. To get $num_{{i},{j}}$, you simply divide the supported product by $2^{cnt_{{a_j},{i},{j}}} - 1$. Then note that $dp_{{t},{i}} = \\sum\\limits_{j=0}^{i - 1}{dp_{{t-1},{j}}} \\cdot num_{{j+1},{i}}$ (iterate over $j$ - the end of the previous critical block). This allows us to calculate the values of $dp$ in time $O(n^2 k)$. 2) We will need an auxiliary dinamical programming values $u_{{i},{t},{mask}}$ (where $mask$ is a mask of characters, that is $0 \\leq mask < 2^c$), which means the number of ways to choose a subsequence from the prefix $a[1 \\ldots i]$, in which there will be first $t$ critical blocks and then several characters that are in $mask$, but each character from $mask$ will be at the several symbols at least once. Then $dp_{{t},{i}} = u_{{i-1},{t-1},{2^c - 1 - 2^{a_i}}}$, which follows from the definition. Conversion formulas are as follows: $u_{{i},{t},{mask}} = u_{{i-1},{t},{mask}}$, if $a_i$ is not contained in $mask$ and $u_{{i},{t},{mask}} = 2 u_{{i-1},{t},{mask}} + u_{{i-1},{t},{mask - 2^{a_i}}}$, if $a_i$ is contained in $mask$ (if you take $a_i$ in the subsequence and if not). For $mask = 0$ it is true, that $u_{{i},{t},{0}} = u_{{i-1},{t},{0}} + dp_{{I},{t}}$. These formulas can be used to calculate the values of $u$ and $dp$ by iterating $i$ in increasing order over time $O(n k 2^c)$. The $i$ parameter can be omitted from memory because the recalculation is only from the previous layer. In total, we get $2$ ways to calculate $dp$ working for $O(n^2 k)$ and $O(n k 2^c)$. Recall that $k = \\frac{n}{c}$. That is, our solutions work at the time $O(\\frac{n^3}{c})$ and $O(\\frac{n^2 2^c}{c})$. If $c > \\log{n}$, then let's run the first solution and it will work for $O(\\frac{n^3}{\\log{n}})$, otherwise if $c \\leq \\log{n}$ and $\\frac{2^c}{c} \\leq \\frac{n}{\\log{n}}$, so let's run the second solution, which will then work, too, in $O(\\frac{n^3}{\\log{n}})$ time. If we carefully implement these $2$ solutions and run them depending on $c$, we get a solution with $O(\\frac{n^3}{\\log{n}})$ complexity and it is working fast enough. Complexity: $O(\\frac{n^3}{\\log{n}})$ or $O(\\frac{n^2}{c} \\cdot min(n, 2^c))$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\ntypedef long double ld;\n \nconst int M = 3010;\nconst int MOD = 998244353;\nconst ll MOD2 = (ll)MOD * (ll)MOD;\nconst int MG = 10;\nconst int MS = (1 << MG);\n \ninline int power(int a, int k)\n{\n    if (k == 0) return 1;\n    int t = power(a, k >> 1);\n    t = 1LL * t * t % MOD;\n    if (k & 1) t = 1LL * a * t % MOD;\n    return t;\n}\n \nint n, c, a[M], kol[M][M], pw[M], inv[M], k, cnt, now, dp[M][M], ans[M], cost[M][M], pr, f[M][MS], to;\nll sum;\nbool used[M];\n \ninline void solve_n2k()\n{\n    for (int i = 0; i <= n; i++) inv[i] = power(pw[i] - 1, MOD - 2);\n    for (int i = 0; i < n; i++)\n    {\n        cnt = c;\n        pr = 1;\n        for (int j = i; j < n; j++)\n        {\n            if (kol[a[j]][i] == kol[a[j]][j])\n                cnt--;\n            else\n                pr = 1LL * pr * inv[kol[a[j]][j] - kol[a[j]][i]] % MOD;\n            if (cnt != 0)\n                cost[i][j] = 0;\n            else\n                cost[i][j] = pr;\n            pr = 1LL * pr * (pw[kol[a[j]][j] - kol[a[j]][i] + 1] - 1) % MOD;\n        }\n    }\n    for (int i = 0; i <= n; i++) dp[0][i] = 0;\n    dp[0][0] = 1;\n    for (int r = 1; r <= k; r++)\n    {\n        dp[r][0] = 0;\n        for (int i = r * c - 1; i < n; i++)\n        {\n            sum = 0;\n            for (int j = i; j >= (r - 1) * c; j--)\n            {\n                sum += 1LL * cost[j][i] * dp[r - 1][j];\n                if (sum >= MOD2) sum -= MOD2;\n            }\n            dp[r][i + 1] = (sum % (ll)MOD);\n        }\n    }\n}\n \ninline void solve_nk2powc()\n{\n    dp[0][0] = 1;\n    f[0][0] = 1;\n    for (int i = 0; i < n; i++)\n    {\n        for (int x = 1; x <= k; x++) dp[x][i + 1] = f[x - 1][((1 << c) - 1) ^ (1 << a[i])];\n        to = min(k - 1, (i / c));\n        for (int ms = (1 << c) - 1; ms >= 0; ms--)\n            if ((ms >> a[i]) & 1)\n                for (int x = 0; x <= to; x++)\n                {\n                    f[x][ms] += f[x][ms];\n                    if (f[x][ms] >= MOD) f[x][ms] -= MOD;\n                    f[x][ms] += f[x][ms ^ (1 << a[i])];\n                    if (f[x][ms] >= MOD) f[x][ms] -= MOD;\n                }\n        for (int x = 0; x < k; x++)\n        {\n            f[x][0] += dp[x][i + 1];\n            if (f[x][0] >= MOD) f[x][0] -= MOD;\n        }\n    }\n}\n \nint main()\n{\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    cin >> n >> c;\n    for (int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n        a[i]--;\n    }\n    for (int i = 0; i < c; i++)\n    {\n        kol[i][0] = 0;\n        for (int x = 0; x < n; x++)\n        {\n            kol[i][x + 1] = kol[i][x];\n            if (a[x] == i) kol[i][x + 1]++;\n        }\n    }\n    pw[0] = 1;\n    for (int i = 0; i < n; i++)\n    {\n        pw[i + 1] = pw[i] + pw[i];\n        if (pw[i + 1] >= MOD) pw[i + 1] -= MOD;\n    }\n    for (int i = 0; i < c; i++) used[i] = false;\n    k = 0;\n    cnt = 0;\n    for (int i = 0; i < n; i++)\n    {\n        if (!used[a[i]])\n        {\n            used[a[i]] = true;\n            cnt++;\n        }\n        if (cnt == c)\n        {\n            cnt = 0;\n            for (int i = 0; i < c; i++) used[i] = false;\n            k++;\n        }\n    }\n    if (c <= MG)\n        solve_nk2powc();\n    else\n        solve_n2k();\n    for (int i = 0; i <= n; i++) ans[i] = 0;\n    for (int i = 0; i <= k; i++)\n        for (int j = 0; j <= n; j++)\n        {\n            ans[i] += 1LL * dp[i][j] * pw[n - j] % MOD;\n            if (ans[i] >= MOD) ans[i] -= MOD;\n        }\n    for (int i = 0; i < n; i++)\n    {\n        ans[i] -= ans[i + 1];\n        if (ans[i] < 0) ans[i] += MOD;\n    }\n    ans[0]--;\n    if (ans[0] < 0) ans[0] += MOD;\n    for (int i = 0; i <= n; i++)\n        cout << ans[i] << \" \";\n    return 0;\n}",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1159",
    "index": "A",
    "title": "A pile of stones",
    "statement": "Vasya has a pile, that consists of some number of stones. $n$ times he either took one stone from the pile or added one stone to the pile. The pile was non-empty before each operation of taking one stone from the pile.\n\nYou are given $n$ operations which Vasya has made. Find the minimal possible number of stones that can be in the pile after making these operations.",
    "tutorial": "Let's consider an array $a$, there $a_i=1$, if $s_i=$\"+\" and $a_i=-1$, if $s_i=$\"-\". Let's notice, that the answer $\\geq a_{k+1} + \\ldots + a_n$ for all $k$. It is true, because after making the first $k$ operations the number of stones will be $\\geq 0$, so at the end the number of stones will be $\\geq a_{k+1} + \\ldots + a_n$. Let's prove, that the answer is equal to $ans = \\max\\limits_{0 \\leq k \\leq n} (a_{k+1} + \\ldots + a_n)$. We proved that it should be at least that number of stones. It's easy to see, that if we will take $a_1 + \\ldots + a_n - ans$ stones at the beginning, the pile will be non-empty each time when Vasya should take a stone and at the end, the number of stones will be equal to $ans$. Complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint n;\nstring s;\n \nint main()\n{\n    cin >> n >> s;\n    int m = 0;\n    int a = 0;\n    for (int i = n - 1; i >= 0; i--)\n    {\n        if (s[i] == '+')\n            m++;\n        else\n            m--;\n        a = max(a, m);\n    }\n    cout << a;\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1159",
    "index": "B",
    "title": "Expansion coefficient of the array",
    "statement": "Let's call an array of non-negative integers $a_1, a_2, \\ldots, a_n$ a $k$-extension for some non-negative integer $k$ if for all possible pairs of indices $1 \\leq i, j \\leq n$ the inequality $k \\cdot |i - j| \\leq min(a_i, a_j)$ is satisfied. The expansion coefficient of the array $a$ is the maximal integer $k$ such that the array $a$ is a $k$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.\n\nYou are given an array of non-negative integers $a_1, a_2, \\ldots, a_n$. Find its expansion coefficient.",
    "tutorial": "Let our array be a $k$-extension. All inequalities $k \\cdot |i - j| \\leq min(a_i, a_j)$ for $i \\neq j$ can be changed to $k \\leq \\frac{min(a_i, a_j)}{|i - j|}$. For all $i = j$ inequalities are always true, because all numbers are non-negative. So, the maximum possible value of $k$ is equal to the minimum of $\\frac{min(a_i, a_j)}{|i - j|}$ for all $i < j$. Let's note, that $\\frac{min(a_i, a_j)}{|i - j|} = min(\\frac{a_i}{|i-j|}, \\frac{a_j}{|i-j|})$. So, we need to take a minimum of $\\frac{a_i}{|i-j|}$ for all $i \\neq j$. If we will fix $i$ the minimum value for all $j$ is equal to $\\frac{a_i}{max(i - 1, n - i)}$ and it is reached at the maximum denominator value, because $a_i \\geq 0$. So the answer is equal to $\\min\\limits_{1 \\leq i \\leq n} \\frac{a_i}{max(i - 1, n - i)}$ and it can be simply found by linear time. Complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int M = 1e5;\n \nint n, a, m = 1e9;\n \nint main()\n{\n    ios::sync_with_stdio(0); cin.tie(0);\n    cin >> n;\n    for (int i = 0; i < n; i++)\n    {\n        cin >> a;\n        m = min(m, a / max(i, n - 1 - i));\n    }\n    cout << m;\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1162",
    "index": "A",
    "title": "Zoning Restrictions Again",
    "statement": "You are planning to build housing on a street. There are $n$ spots available on the street on which you can build a house. The spots are labeled from $1$ to $n$ from left to right. In each spot, you can build a house with an integer height between $0$ and $h$.\n\nIn each spot, if a house has height $a$, you will gain $a^2$ dollars from it.\n\nThe city has $m$ zoning restrictions. The $i$-th restriction says that the tallest house from spots $l_i$ to $r_i$ (inclusive) must be at most $x_i$.\n\nYou would like to build houses to maximize your profit. Determine the maximum profit possible.",
    "tutorial": "This problem can be done by processing the restrictions one by one. Let's keep an array $a$ of length $n$, where the $i$-th value in this array represents the maximum possible height for house $i$. Initially, we have processed no restrictions, so we fill $a_i = h$ for all $i$. For a restriction $k$, we can loop through the elements $j$ between $l_k$ and $r_k$ and update $a_j = \\min(a_j, x_k)$. This is because the new house must be at most height $x_k$, and we know previously it had to be at most $a_j$, so we take the min of the two. After processing all restrictions, we can greedily choose the height of the $i$-th house to be $a_i$. The answer is the sum of $a_i^2$ for all $i$. The time complexity for processing one restriction is $O(n)$, so the total time complexity is $O(nm)$.",
    "code": "#include <bits/stdc++.h>\n\n\nusing namespace std;\n\n\n#define int long long\n#define ll long long\n\n\n\n\nint32_t main()\n{\n        int n, h, m;\n        cin>>n>>h>>m;\n\n\n        int a[n+1];\n        for(int i=1;i<=n;i++)  \n                a[i]=h;\n\n\n        for(int i=0;i<m;i++)\n        {\n                int l, r, x;\n                cin>>l>>r>>x;\n                for(int j=l;j<=r;j++)\n                {\n                        a[j]=min(a[j],x);\n                }\n        }\n\n\n        int ans=0;\n        for(int i=1;i<=n;i++)\n                ans+=a[i]*a[i];\n\n\n        cout<<ans<<endl;\n\n\n        return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1162",
    "index": "B",
    "title": "Double Matrix",
    "statement": "You are given \\textbf{two} $n \\times m$ matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly increasing. A matrix is increasing if all rows are strictly increasing \\textbf{and} all columns are strictly increasing.\n\nFor example, the matrix $\\begin{bmatrix} 9&10&11\\\\ 11&12&14\\\\ \\end{bmatrix}$ is increasing because each individual row and column is strictly increasing. On the other hand, the matrix $\\begin{bmatrix} 1&1\\\\ 2&3\\\\ \\end{bmatrix}$ is not increasing because the first row is not strictly increasing.\n\nLet a position in the $i$-th row (from top) and $j$-th column (from left) in a matrix be denoted as $(i, j)$.\n\nIn one operation, you can choose any two numbers $i$ and $j$ and swap the number located in $(i, j)$ in the first matrix with the number in $(i, j)$ in the second matrix. In other words, you can swap two numbers in different matrices if they are located in the corresponding positions.\n\nYou would like to make both matrices increasing by performing some number of operations (possibly none). Determine if it is possible to do this. If it is, print \"Possible\", otherwise, print \"Impossible\".",
    "tutorial": "There are too many possibilities to try a brute force, and a dp solution also might be too slow (e.g. some bitmask dp). There is a solution that uses 2sat but that is a bit hard to code so I won't go into details in this tutorial. Let's instead look at a greedy solution. First, let's swap $a_{i,j}$ with $b_{i,j}$ if $a_{i,j} > b_{i,j}$. At the end, for every $i$ and $j$, we have $a_{i,j} \\leq b_{i,j}$. We now claim that there is a solution if and only if this configuration is valid. We can guess this intuitively and by trying a few examples, or we can do the proof below. <start of formal proof for why this works> If this configuration is valid, then obviously this solution works, so we're done with this side of the implication. The other way is to show if there exists a solution, then this configuration is also valid. We do this by contradiction. We show if this configuration is not valid, then there is no solution. If this configuration is not valid, without loss of generality, let $b_{i,j} \\geq b_{i,j+1}$. $b_{i,j}$ must go somewhere in the matrix and it needs to be before either $b_{i,j+1}$ or $a_{i,j+1}$, but we have $a_{i,j+1} \\leq b_{i, j+1} \\leq b_{i,j}$, so we have nowhere that we can put $b_{i,j}$, thus this shows there is no solution. We can also extend this argument to the other cases. <end of proof for why this works> So, given the above claim, the solution is simple. Do the swaps so $a_{ij} \\leq b_{ij}$. Then, check if the two matrices are increasing, and print \"Possible\" if so and \"Impossible\" otherwise. The runtime is $O(n^2)$ to read in the input, do the swaps, then do the checks that the matrices are valid.",
    "code": "#include <bits/stdc++.h>\n\n\nusing namespace std;\n\n\n#define int long long\n#define ll long long\n\n\n\n\nint32_t main()\n{\n        int n,m;\n        cin>>n>>m;\n\n\n        int a[n][m], b[n][m];\n\n\n        for(int i=0;i<n;i++)\n        {\n                for(int j=0;j<m;j++)\n                {\n                        cin>>a[i][j];\n                }\n        }\n\n\n\n\n        for(int i=0;i<n;i++)\n        {\n                for(int j=0;j<m;j++)\n                {\n                        cin>>b[i][j];\n                }\n        }\n\n\n        for(int i=0;i<n;i++)\n        {\n                for(int j=0;j<m;j++)\n                {\n                        int flag=0;\n                        if(a[i][j]>=b[i][j])\n                                flag=1;\n                        if(flag)\n                                swap(a[i][j], b[i][j]);\n                }\n        }\n\n\n        int flag=0;\n\n\n        for(int i=0;i<n;i++)\n        {\n                for(int j=0;j<m;j++)\n                {\n                        if(j && a[i][j]<=a[i][j-1])\n                                flag=1;\n                        if(j && b[i][j]<=b[i][j-1])\n                                flag=1;\n                        if(i && a[i][j]<=a[i-1][j])\n                                flag=1;\n                        if(i && b[i][j]<=b[i-1][j])\n                                flag=1;\n                }\n        }\n\n\n        if(flag==0)\n        {\n                cout<<\"Possible\"<<endl;\n        }\n        else\n        {\n          cout << \"Impossible\" << endl;\n        }\n        return 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1163",
    "index": "A",
    "title": "Eating Soup",
    "statement": "The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party...\n\nWhat the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now $n$ cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone having finished their soup leaves the circle.\n\nKatie suddenly notices that whenever a cat leaves, the place where she was sitting becomes an empty space, which means the circle is divided into smaller continuous groups of cats sitting next to each other. At the moment Katie observes, there are $m$ cats who left the circle. This raises a question for Katie: what is the maximum possible number of groups the circle is divided into at the moment?\n\nCould you help her with this curiosity?\n\nYou can see the examples and their descriptions with pictures in the \"Note\" section.",
    "tutorial": "We can prove that the first one to leave the circle does not make any difference to our answer. So after trying some tests, you will probably come up with an idea of selecting the cats that are sitting right between the other two to be the prior ones to leave because, in this way, those vacancies will definitely be useful for creating more separate groups. Therefore, if $m - 1 < \\lfloor \\frac{n}{2} \\rfloor$, the answer is $m$ since each cat to leave (after the first cat) increases the number of groups. Otherwise, if $m + 1 \\geq \\lfloor \\frac{n}{2} \\rfloor$, each independent cat to leave decreases the number of groups so the answer is $n - m$. Summarily, the answer is $\\min(m, n - m)$. Be careful with $m = 0$. Complexity: $O(1)$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main ()\n{\n    int n, m;\n\tcin >> n >> m;\n\tcout << (m ? min(m, n - m) : 1) << endl;\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1163",
    "index": "B2",
    "title": "Cat Party (Hard Edition)",
    "statement": "This problem is same as the previous one, but has larger constraints.\n\nShiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.\n\nFor each of the $n$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $i$-th day has a ribbon with color $u_i$. Shiro wants to know the largest number $x$, such that if we consider the streak of the first $x$ days, it is possible to remove \\textbf{exactly one} day from this streak so that every ribbon color that has appeared among the remaining $x - 1$ will have the same number of occurrences.\n\nFor example, consider the following sequence of $u_i$: $[2, 2, 1, 1, 5, 4, 4, 5]$. Then $x = 7$ makes a streak, since if we remove the leftmost $u_i = 5$, each ribbon color will appear exactly twice in the prefix of $x - 1$ days. Note that $x = 8$ doesn't form a streak, since you must remove exactly one day.\n\nSince Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.",
    "tutorial": "We can iterate over all streaks and check for each streak if we can remove one day so that each color has the same number of cats. There are 4 cases where we can remove a day from the streak to satisfy the condition: There is only one color in this streak. All appeared colors in this streak have the occurrence of $1$ (i.e. every color has exactly $1$ cat with that color). Every color has the same occurrence of cats, except for exactly one color which has the occurrence of $1$. Every color has the same occurrence of cats, except for exactly one color which has the occurrence exactly $1$ more than any other color. All of these four conditions can be checked using counting techniques. Complexity: $O(n)$.",
    "code": "#include <iostream>\n#include <stdio.h>\nusing namespace std;\n\nconst int N = 1e5 + 10;\n\nint n, color, ans, mx, f[N], cnt[N];\n\nint main()\n{\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; i++)\n    {\n        scanf(\"%d\", &color);\n        cnt[f[color]]--;\n        f[color]++;\n        cnt[f[color]]++;\n        mx = max(mx, f[color]);\n        bool ok = false;\n        if (cnt[1] == i) // every color has occurence of 1\n            ok = true;\n        else if (cnt[i] == 1) // only one color has the maximum occurence and the occurence is i\n            ok = true;\n        else if (cnt[1] == 1 && cnt[mx] * mx == i - 1) // one color has occurence of 1 and other colors have the same occurence\n            ok = true;\n        else if (cnt[mx - 1] * (mx - 1) == i - mx && cnt[mx] == 1) // one color has the occurence 1 more than any other color\n            ok = true;\n        if (ok)\n            ans = i;\n    }\n    printf(\"%d\", ans);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1163",
    "index": "C2",
    "title": "Power Transmission (Hard Edition)",
    "statement": "This problem is same as the previous one, but has larger constraints.\n\nIt was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.\n\nAt the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $(x_i, y_i)$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane \\textbf{infinite in both directions}. If there are more than two poles lying on the same line, they are connected by a single common wire.\n\nSelena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?",
    "tutorial": "First, we will divide the problem into several parts: 1) construct the wires, 2) remove duplicates, and 3) count the number of pairs that intersect. The first part is relatively simple: note that each wire is simply a line that goes through two distinct points (poles) on the $Oxy$ plane. Suppose this line goes through point $A(x_1,y_1)$ and point $B(x_2,y_2)$, then it can be described by the equation $ax - by = c$ where $a = y_1 - y_2$, $b = x_1 - x_2$, $c = y_1x_2 - y_2x_1$. For step two, we will simplify the equation for each line by dividing each coefficient by their greatest common divisor. Now each equation uniquely identifies a line, and vice versa - so we can sort the wires by their values of a, b, and c; then remove adjacent duplicates. The final part of the solution also makes use of this sorted list. As any pair of lines on the plane must intersect unless they are parallel, we only need to count the number of parallel pairs and subtract these from the total number of pairs. These are the pairs with the same slope (i.e. same value of a and b), and they already are next to each other in our list. We now iterate over these \"blocks\" of parallel lines and count the number of pairs each block contributes - a block of size $s$ gives $\\frac{s(s-1)}{2}$ pairs. Complexity: $O(n^2\\log{n})$.",
    "code": "#include <cstdio>\n#include <map>\n#include <set>\n#include <utility>\nconst int N = 1001;\nint x[N], y[N];\nstd::map<std::pair<int,int>,std::set<long long>> slope_map;\n\nint gcd(int a, int b) \n{\n\tif (a == 0)\n\t\treturn b;\n\treturn gcd(b % a, a);\n}\n\nint main()\n{\n\tint n; scanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; ++i)\n\t\tscanf(\"%d%d\", &x[i], &y[i]);\n\tlong long total = 0, res = 0;\n\tfor (int i = 1; i <= n - 1; ++i)\n\t\tfor (int j = i + 1; j <= n; ++j)\n\t\t{\n\t\t\tint x1 = x[i], y1 = y[i], x2 = x[j], y2 = y[j];\n\t\t\t// construct a line passing through (x1, y1) and (x2, y2)\n\t\t\t// line is expressed as equation ax - by = c with constant a, b, c \n\t\t\tint a = y1 - y2, b = x1 - x2;\n\t\t\t// simplify equation\n\t\t\tint d = gcd(a, b); a /= d, b /= d;\n\t\t\tif (a < 0 || (a == 0 && b < 0))\n\t\t\t{\n\t\t\t    a = -a;\n\t\t\t    b = -b;\n\t\t\t}\n\t\t\t// lines with the same slope (same a, b) are stored in a map\n\t\t\tstd::pair<int,int> slope(a, b);\n\t\t\tlong long c = 1LL * a * x1 - 1LL * b * y1;\n\t\t\tif (!slope_map[slope].count(c))\n\t\t\t{\n\t\t\t\t++total;\n\t\t\t\tslope_map[slope].insert(c);\n\t\t\t\t// if this line is new, it intersects every line with different slope\n\t\t\t\tres += total - slope_map[slope].size();\n\t\t\t}\n\t\t}\n\tprintf(\"%lld\\n\", res);\n}",
    "tags": [
      "data structures",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1163",
    "index": "D",
    "title": "Mysterious Code",
    "statement": "During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string $c$ consisting of lowercase English characters and asterisks (\"*\"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters).\n\nKatie has a favorite string $s$ and a not-so-favorite string $t$ and she would love to recover the mysterious code so that it has as many occurrences of $s$ as possible and as little occurrences of $t$ as possible. Formally, let's denote $f(x, y)$ as the number of occurrences of $y$ in $x$ (for example, $f(aababa, ab) = 2$). Katie wants to recover the code $c'$ conforming to the original $c$, such that $f(c', s) - f(c', t)$ is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out.",
    "tutorial": "Firstly, we will find the maximal value of $f(c', s) - f(c', t)$ via dynamic programming. Denote 'dp[i][ks][kt]' as the maximal value of the said value when replacing the first $i$-th character of $c$, and the KMP state for the replaced sub-code to be $ks$ and $kt$. The maximal value of $f(c', s) - f(c', t)$ for the whole code will lie among all end states $dp[n][ks][kt]$ for all values of $ks$ and $kt$. Complexity: $O(|c| \\cdot |s| \\cdot |t|)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstring>\nusing namespace std;\n\nconst int K = 1005, N = 55, M = 55, INF = 1E9 + 7;\n\nint k, n, m;\nint kmp_s[N], nxt_s[N][26], kmp_t[M], nxt_t[M][26];\nint dp[K][N][M];\nchar code[K], s[N], t[M];\n\nvoid init(char s[], int n, int kmp[], int nxt[][26])\n{\n    kmp[1] = 0;\n    for (int i = 2; i <= n; i++)\n    {\n        int cur = kmp[i - 1];\n        while (cur > 0 && s[cur + 1] != s[i])\n            cur = kmp[cur];\n        if (s[cur + 1] == s[i])\n            ++cur;\n        kmp[i] = cur;\n    }\n\n    for (int i = 0; i <= n; i++)\n        for (char c = 'a'; c <= 'z'; c++)\n        {\n            int cur = i;\n            while (cur > 0 && s[cur + 1] != c)\n                cur = kmp[cur];\n            if (s[cur + 1] == c)\n                ++cur;\n            nxt[i][c - 'a'] = cur;\n        }\n}\n\nint main()\n{\n    scanf(\"%s%s%s\", code + 1, s + 1, t + 1);\n    k = strlen(code + 1); n = strlen(s + 1); m = strlen(t + 1);\n    init(s, n, kmp_s, nxt_s); init(t, m, kmp_t, nxt_t);\n    for (int i = 0; i <= k; i++)\n        for (int ks = 0; ks <= n; ks++)\n            for (int kt = 0; kt <= m; kt++)\n                dp[i][ks][kt] = -INF;\n    dp[0][0][0] = 0;\n    for (int i = 0; i < k; i++)\n        for (int ks = 0; ks <= n; ks++)\n            for (int kt = 0; kt <= m; kt++)\n                for (char c = 'a'; c <= 'z'; c++)\n                    if (code[i + 1] == '*' || code[i + 1] == c) // we now add/replace the (i + 1)-th character\n                    {\n                        int ns = nxt_s[ks][c - 'a'], nt = nxt_t[kt][c - 'a'];\n                        int tmp = dp[i][ks][kt] + (ns == n) - (nt == m); // add the new occurrences if any\n                        dp[i + 1][ns][nt] = max(dp[i + 1][ns][nt], tmp);\n                    }\n    int ma = -INF;\n    for (int ks = 0; ks <= n; ks++)\n        for (int kt = 0; kt <= m; kt++)\n            ma = max(ma, dp[k][ks][kt]);\n    printf(\"%d\\n\", ma);\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1163",
    "index": "E",
    "title": "Magical Permutation",
    "statement": "Kuro has just learned about permutations and he is really excited to create a new permutation type. He has chosen $n$ distinct positive integers and put all of them in a set $S$. Now he defines a magical permutation to be:\n\n- A permutation of integers from $0$ to $2^x - 1$, where $x$ is a non-negative integer.\n- The bitwise xor of any two consecutive elements in the permutation is an element in $S$.\n\nSince Kuro is really excited about magical permutations, he wants to create the longest magical permutation possible. In other words, he wants to find the largest non-negative integer $x$ such that there is a magical permutation of integers from $0$ to $2^x - 1$. Since he is a newbie in the subject, he wants you to help him find this value of $x$ and also the magical permutation for that $x$.",
    "tutorial": "The idea here is iterate $x$ and check if it is possible to create a magical permutation for the current $x$ we are iterating through. An observation to be made is that if it is possible to create a magical permutation $P$ from $0$ to $2^x - 1$, then it must be possible to express each integer from $0$ to $2^x - 1$ as the xor value of elements in one subset of $S$. This is because $0$ is represented as the xor value of the empty subset of $S$. Because of that, every element to the left of $0$ in $P$ is also the xor value of one subset of $S$, and so is every element to the right of $0$ in $P$. Because of that, we first check that if we can create every integer from $0$ to $2^x - 1$ using only the xor values of every subset of $S$. This is possible by creating a basis for integers from $0$ to $2^x - 1$ - $x$ integers such that each integer from $0$ to $2^x - 1$ is the xor value of a subset of these $x$ integers - from $S$ using Gaussian elimination. Now, if it is possible to create such a basis for integers from $0$ to $2^x - 1$ using only elements of $S$, is it possible to create a magic permutation then? Recall that each integer from $0$ to $2^x - 1$ corresponds to the xor value of a subset of the basis, or in other words, corresponds to a bitmask of the basis. We can also narrow down the original condition, such that the xor value of any two consecutive elements belongs to the basis; or in other words, the corresponding bitmask of any two consecutive elements in the magical permutation differs by exactly 1 bit. The problem now becomes creating a permutation of integers from $0$ to $2^x - 1$ such that any two consecutive elements in this permutation differs by 1 bit, and then convert this permutation to a magical permutation using the created basis. It turns out that we can always do this using Gray codes, although DFS works just as well. It also turns out that the basis for integers from $0$ to $2^x - 1$ does not exceed $2^x - 1$, we can sort $S$ and create the basis along with checking the aforementioned condition. Complexity: $O(n \\log n + n \\log MAX + MAX)$ if Gray codes are used, or $O(n \\log n + n \\log MAX + MAX \\log MAX)$ is DFS is used instead, where $MAX$ denotes the maximum value of elements in $S$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nconst int N = 200005, MX = 1E6 + 5;\n\nint n, x = 0, a[N];\nbool vis[MX];\nvector<int> basis, vec, ans;\n\nvoid add(int u)\n{\n    int tmp = u;\n    for (int &v : basis)\n        u = min(u, u ^ v);\n    if (u > 0)\n    {\n        basis.push_back(u);\n        vec.push_back(tmp);\n        for (int i = basis.size() - 1; i > 0; i--)\n            if (basis[i] > basis[i - 1])\n                swap(basis[i], basis[i - 1]);\n            else\n                break;\n    }\n}\n\nvoid DFS(int u, int it = 0)\n{\n    ans.push_back(u);\n    vis[u] = true;\n    if (it == (1 << x) - 1)\n        return;\n    for (int &v : vec)\n        if (!vis[u ^ v])\n        {\n            DFS(u ^ v, it + 1);\n            return;\n        }\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; i++)\n        scanf(\"%d\", a + i);\n    sort(a, a + n);\n    int pt = 0;\n    for (int i = 1; i < 20; i++)\n    {\n        for (; pt < n && a[pt] < (1 << i); pt++)\n            add(a[pt]);\n        if (basis.size() == i)\n            x = i;\n    }\n    basis.clear();\n    vec.clear();\n    for (int i = 0; i < n && a[i] < (1 << x); i++)\n        add(a[i]);\n    printf(\"%d\\n\", x);\n    DFS(0);\n    for (int &v : ans)\n        printf(\"%d \", v);\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "data structures",
      "graphs",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1163",
    "index": "F",
    "title": "Indecisive Taxi Fee",
    "statement": "In the city of Capypaland where Kuro and Shiro resides, there are $n$ towns numbered from $1$ to $n$ and there are $m$ bidirectional roads numbered from $1$ to $m$ connecting them. The $i$-th road connects towns $u_i$ and $v_i$. Since traveling between the towns is quite difficult, the taxi industry is really popular here. To survive the harsh competition, each taxi company has to find a distinctive trait for their customers.\n\nKuro is the owner of a taxi company. He has decided to introduce a new fee model for his taxi brand, where the fee for each ride is not calculated based on the trip length, but on the sum of the prices of the roads traveled. The price for each of the $m$ roads has been decided by Kuro himself.\n\nAs of now, the price for the road $i$ is $w_i$ and hence the fee for a taxi ride traveling through roads $e_1, e_2, \\ldots, e_k$ is $\\sum_{i=1}^k w_{e_i}$.\n\nHowever, Kuro himself is an indecisive person, so he has drafted $q$ plans to change the road price. Each of the plans will be based on the original prices $w_i$, except for a single road $t_j$, the price of which is changed to $x_j$. Note, that the plans are independent of each other.\n\nShiro is a regular customer of the Kuro's taxi brand since she uses the taxi to travel from town $1$ to town $n$ every day. Since she's so a regular customer, Kuro decided to show her all his $q$ plans before publishing them to the public. Now, Shiro wants to know the lowest fee she must pay to travel from the town $1$ to the town $n$ for each Kuro's plan.",
    "tutorial": "Firstly, we will find and trace out one shortest path from vertex $1$ to vertex $n$ in the graph. Let's call this path main path, and we will number the edges on the main path as $E_1$, $E_2$, .., $E_k$ respectively. We will also call all of the other edges that does not belong to this main path candidate edges. During the procedure, we can also calculate the shortest path from $1$ to every vertex $u$, and the shortest path from every vertex $u$ to $n$. After calculating all of these values, we can now query the shortest path from $1$ to $n$ that must pass through each edge $(u, v)$ in either direction. We have a few observations to be made here: Observation 1: Apart of the vertices belong to the main path, for each vertex $u$, the shortest path from $1$ to $u$ uses a prefix of the main path. More formally, there exists an index $l_u$ ($0 \\leq l_u \\leq k$) such that the shortest path from $1$ to $u$ must use the edges $E_1$, $E_2$, ..., $E_{l_u}$ at its beginning. Using the same analogy, we can say that for each vertex $u$, the shortest path from $u$ to $n$ uses a suffix of the main path; or in other words, there exists an index $r_u$ ($1 \\leq r_u \\leq k + 1$) such that the shortest path from $u$ to $n$ must use the edges $E_{r_u}$, $E_{r_{u + 1}}$, ..., $E_k$ at its end. Note that if $l_u = 0$, the shortest path from $1$ to $u$ does not use a prefix of the main path, and if $r_u = k + 1$, the shortest path from $u$ to $n$ does not use a suffix of the main path. For every vertex $v$ that belongs to the main path however, we will set $l_v = t, r_v = t + 1$, where $t$ is the position where $v$ appears on the main path. What does this imply? This implies that the shortest from $1$ to $n$ that passes through $u$ does not rely on the edges $E_{l_u + 1}$, $E_{l_u + 2}$, ..., $E_{r_u - 1}$. Observation 2: For each candidate edge $(u, v)$, the shortest path from $1$ to $n$ passing through this edge in the order $u \\rightarrow v$ does not rely on the edges $E_{l_u + 1}$, $E_{l_u + 2}$, ..., $E_{r_v - 1}$. This is because, the shortest path passing through this order $u \\rightarrow v$ will consist of the shortest path from $1$ to $u$, the edge $(u, v)$, and the shortest path from $v$ to $n$. With the same analogy, the shortest path from $1$ to $n$ passing through this edge in the order $v \\rightarrow u$ does not rely on the edges $E_{l_v + 1}$, $E_{l_v + 2}$, ..., $E_{r_u - 1}$. Using the observations, we can now answer the queries. There are three cases that we should consider when answering the shortest path with the modified edge: The modified edge is a candidate edge (i.e. it does not belong to the main path): we will take the minimal of the main path and the shortest path that goes through this modified edge. The modified edge belongs to the main path, and its value decreases: the new shortest path is still the main path, and its new value is the old value subtracting the difference between the original and the modified weight of that edge. The modified edge belongs to the main path, and its value increases: the new shortest path is either one of these two options: The main path, its new value being the old value adding the weight-difference of the modified edge. The shortest path from $1$ to $n$ that does not use the modified edge. This shortest path must use a candidate edge, since we cannot reuse the main path anymore; more specifically, this shortest path uses a candidate edge that does not rely on the modified edge. To get the value of this option, recall in observation 2 that for each candidate edge $(u, v)$ and with its direction, we know the range of edges belonging to the main path that this candidate edge does not rely on. Hence, we can use a segment tree to manage and query the shortest path that does not rely on this edge. The main path, its new value being the old value adding the weight-difference of the modified edge. The shortest path from $1$ to $n$ that does not use the modified edge. This shortest path must use a candidate edge, since we cannot reuse the main path anymore; more specifically, this shortest path uses a candidate edge that does not rely on the modified edge. To get the value of this option, recall in observation 2 that for each candidate edge $(u, v)$ and with its direction, we know the range of edges belonging to the main path that this candidate edge does not rely on. Hence, we can use a segment tree to manage and query the shortest path that does not rely on this edge. Complexity: $O((m + n)\\log{n})$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <queue>\nusing namespace std;\n\nconst int N = 2E5 + 5, M = 2E5 + 5;\nconst long long INF = 1E18 + 7;\n\nint n, m, q, ed, nw, mx, u[M], v[M], w[M], ind[M];\nint tr[N], le[N], ri[N];\nbool on_path[N];\nlong long dis[2][N];\n\nstruct TNode\n{\n    int u;\n    long long val;\n\n    TNode(int _u, long long _val)\n    {\n        u = _u;\n        val = _val;\n    }\n\n    inline bool operator>(const TNode &oth) const\n    {\n        return val > oth.val;\n    }\n};\npriority_queue<TNode, vector<TNode>, greater<TNode>> pq;\n\nstruct TEdge\n{\n    int v, w, ind;\n\n    TEdge(int _v, int _w, int _ind)\n    {\n        v = _v;\n        w = _w;\n        ind = _ind;\n    }\n};\nvector<TEdge> adj[N];\n\nstruct TTree\n{\n#define m (l + r) / 2\n#define lc i * 2\n#define rc i * 2 + 1\n\n    long long tr[4 * M];\n\n    void build(int l, int r, int i)\n    {\n        tr[i] = INF;\n        if (l == r)\n            return;\n        build(l, m, lc);\n        build(m + 1, r, rc);\n    }\n\n    void upd(int l, int r, int i, int L, int R, long long v)\n    {\n        if (l > R || r < L || L > R)\n            return;\n        if (L <= l && r <= R)\n        {\n            tr[i] = min(tr[i], v);\n            return;\n        }\n        upd(l, m, lc, L, R, v);\n        upd(m + 1, r, rc, L, R, v);\n    }\n\n    long long que(int l, int r, int i, int u)\n    {\n        if (l == r)\n            return tr[i];\n        return min(tr[i], u <= m ? que(l, m, lc, u) : que(m + 1, r, rc, u));\n    }\n\n#undef m\n#undef lc\n#undef rc\n} seg;\n\nvoid dijkstra(int st, long long dis[], int get = 0)\n{\n    fill(dis + 1, dis + n + 1, INF);\n    pq.push(TNode(st, dis[st] = 0));\n    while (!pq.empty())\n    {\n        TNode u = pq.top(); pq.pop();\n        if (u.val > dis[u.u])\n            continue;\n        for (TEdge &v : adj[u.u])\n            if (dis[v.v] > u.val + v.w)\n            {\n                tr[v.v] = v.ind;\n                if (get == 1 && !on_path[v.v])\n                    le[v.v] = le[u.u];\n                else if (get == 2 && !on_path[v.v])\n                    ri[v.v] = ri[u.u];\n                pq.push(TNode(v.v, dis[v.v] = u.val + v.w));\n            }\n    }\n}\n\nvoid trace()\n{\n    on_path[1] = true; le[1] = ri[1] = 0;\n    for (int i = 1, cur = 1; cur != n; i++)\n    {\n        int edge = tr[cur];\n        ind[edge] = mx = i;\n        cur = u[edge] ^ v[edge] ^ cur;\n        on_path[cur] = true;\n        le[cur] = ri[cur] = i;\n    }\n}\n\nint main()\n{\n    scanf(\"%d%d%d\", &n, &m, &q);\n    for (int i = 1; i <= m; i++)\n    {\n        scanf(\"%d%d%d\", u + i, v + i, w + i);\n        ind[i] = -1;\n        adj[u[i]].push_back(TEdge(v[i], w[i], i));\n        adj[v[i]].push_back(TEdge(u[i], w[i], i));\n    }\n    dijkstra(n, dis[1]); // reverse the initial dijkstra for the trace to increase from 1 -> n\n    trace();\n    dijkstra(1, dis[0], 1);\n    dijkstra(n, dis[1], 2);\n    seg.build(1, mx, 1);\n    for (int i = 1; i <= m; i++)\n        if (ind[i] == -1)\n        {\n            seg.upd(1, mx, 1, le[u[i]] + 1, ri[v[i]], dis[0][u[i]] + w[i] + dis[1][v[i]]);\n            seg.upd(1, mx, 1, le[v[i]] + 1, ri[u[i]], dis[0][v[i]] + w[i] + dis[1][u[i]]);\n        }\n    while (q--)\n    {\n        scanf(\"%d%d\", &ed, &nw);\n        long long ans;\n        if (ind[ed] > 0)\n        {\n            ans = dis[0][n] - w[ed] + nw;\n            if (nw > w[ed])\n                ans = min(ans, seg.que(1, mx, 1, ind[ed]));\n        }\n        else\n        {\n            ans = dis[0][n];\n            if (nw < w[ed])\n            {\n                ans = min(ans, dis[0][u[ed]] + nw + dis[1][v[ed]]);\n                ans = min(ans, dis[0][v[ed]] + nw + dis[1][u[ed]]);\n            }\n        }\n        printf(\"%lld\\n\", ans);\n    }\n}",
    "tags": [
      "data structures",
      "graphs",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1165",
    "index": "A",
    "title": "Remainder",
    "statement": "You are given a huge decimal number consisting of $n$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.\n\nYou may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.\n\nYou are also given two integers $0 \\le y < x < n$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$.",
    "tutorial": "As we can see, last $x$ digits of the resulting number will be zeros except the $n-y$-th. So we need to change all ones to zeros (if needed) among last $x$ digits, if the position of the digit is not $n-y$, and change zero to one (if needed) otherwise. It can be done with simple cycle.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, x, y;\n\tstring s;\n\tcin >> n >> x >> y >> s;\n\t\n\tint ans = 0;\n\tfor (int i = n - x; i < n; ++i) {\n\t\tif (i == n - y - 1) ans += s[i] != '1';\n\t\telse ans += s[i] != '0';\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1165",
    "index": "B",
    "title": "Polycarp Training",
    "statement": "Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $1$ problem, during the second day — exactly $2$ problems, during the third day — exactly $3$ problems, and so on. During the $k$-th day he should solve $k$ problems.\n\nPolycarp has a list of $n$ contests, the $i$-th contest consists of $a_i$ problems. During each day Polycarp has to choose \\textbf{exactly one} of the contests he didn't solve yet and solve it. He solves \\textbf{exactly $k$ problems from this contest}. Other problems are discarded from it. If there are no contests consisting of at least $k$ problems that Polycarp didn't solve yet during the $k$-th day, then Polycarp stops his training.\n\nHow many days Polycarp can train if he chooses the contests optimally?",
    "tutorial": "After sorting the array, we can maintain the last day Polycarp can train, in the variable $pos$. Initially it is $1$. Let's iterate over all elements of the sorted array in non-decreasing order and if the current element $a_i \\ge pos$ then let's increase $pos$ by one. The answer will be $pos - 1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.begin(), a.end());\n\t\n\tint pos = 1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (a[i] >= pos) ++pos;\n\t}\n\t\n\tcout << pos - 1 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1165",
    "index": "C",
    "title": "Good String",
    "statement": "Let's call (yet again) a string \\textbf{good} if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. \\textbf{Note that the empty string is considered good}.\n\nYou are given a string $s$, you have to delete minimum number of characters from this string so that it becomes good.",
    "tutorial": "The following greedy solution works: let's iterate over all characters of the string from left to right, and if the last block of two consecutive characters in the resulting string is full, just add the current character to the resulting string, otherwise add this character if it is not equal to the first character of the last block. And don't forget about the parity of length (remove last character if the length is odd).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nstring s;\nint n;\nstring res;\n\nint main()\n{\n\tcin >> n >> s;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(res.size() % 2 == 0 || res.back() != s[i])\n\t\t\tres.push_back(s[i]);\n\t}\n\tif(res.size() % 2 == 1) res.pop_back();\n\tcout << n - int(res.size()) << endl << res << endl;\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1165",
    "index": "D",
    "title": "Almost All Divisors",
    "statement": "We guessed some integer number $x$. You are given a list of \\textbf{almost all} its divisors. \\textbf{Almost all} means that there are \\textbf{all divisors except $1$ and $x$} in the list.\n\nYour task is to find the minimum possible integer $x$ that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.\n\nYou have to answer $t$ independent queries.",
    "tutorial": "Suppose the given list of divisors is a list of almost all divisors of some $x$ (in other words, suppose that the answer exists). Then the minimum divisor multiplied by maximum divisor should be $x$. This is true because if we have a divisor $i$ we also have a divisor $\\frac{n}{i}$. Let's sort all divisors and let $x = d_1 \\cdot d_n$. Now we need to check if all divisors of $x$ except $1$ and $x$ are the permutation of the array $d$ (check that our answer is really correct). We can find all divisors of $x$ in $O(\\sqrt{x})$, sort them and compare with the array $d$. If arrays are equal then the answer is $x$ otherwise the answer is -1.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint t;\n\tcin >> t;\n\tfor (int i = 0; i < t; ++i) {\n\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<long long> d(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcin >> d[i];\n\t\t}\n\t\tsort(d.begin(), d.end());\n\t\tlong long x = d[0] * d[n - 1];\n\t\t\n\t\tvector<long long> dd;\n\t\tfor (int i = 2; i * 1ll * i <= x; ++i) {\n\t\t\tif (x % i == 0) {\n\t\t\t\tdd.push_back(i);\n\t\t\t\tif (i != x / i) {\n\t\t\t\t\tdd.push_back(x / i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsort(dd.begin(), dd.end());\n\t\t\n\t\tif (dd == d) {\n\t\t\tcout << x << endl;\n\t\t} else {\n\t\t\tcout << -1 << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1165",
    "index": "E",
    "title": "Two Arrays and Sum of Functions",
    "statement": "You are given two arrays $a$ and $b$, both of length $n$.\n\nLet's define a function $f(l, r) = \\sum\\limits_{l \\le i \\le r} a_i \\cdot b_i$.\n\nYour task is to reorder the elements (choose an arbitrary order of elements) of the array $b$ to minimize the value of $\\sum\\limits_{1 \\le l \\le r \\le n} f(l, r)$. Since the answer can be very large, you have to print it modulo $998244353$. Note that you should \\textbf{minimize the answer but not its remainder}.",
    "tutorial": "Let's use contribution to the sum technique to solve this problem. How many times the value $a_i \\cdot b_i$ will occur in the answer? It will occur $i \\cdot (n - i + 1)$ times. Okay, now we can see that for each position $i$ we have the value $a_i \\cdot b_i \\cdot i \\cdot (n - i + 1)$. The only non-constant value there is $b_i$. So let $val_i = a_i \\cdot i \\cdot (n - i + 1)$. Note that you cannot take this value modulo 998244353 here because then you can't compare these values correctly. We should pair the minimum $b_i$ with the maximum $val_i$, the second minimum with the second maximum and so on. So, let's sort the array $val$ and the array $b$, reverse the array $b$ and calculate the sum of values $val_i \\cdot b_i$ (don't forget about modulo here!).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n), b(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> b[i];\n\t}\n\t\n\tsort(b.begin(), b.end());\n\tvector<pair<long long, int>> val(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tval[i].first = (i + 1) * 1ll * (n - i) * a[i];\n\t\tval[i].second = i;\n\t}\n\tsort(val.rbegin(), val.rend());\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tans = (ans + (val[i].first % MOD * 1ll * b[i]) % MOD) % MOD;\n\t}\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1165",
    "index": "F1",
    "title": "Microtransactions (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints}.\n\nIvan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.\n\nEach day (during the \\textbf{morning}) Ivan earns exactly one burle.\n\nThere are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the \\textbf{evening}).\n\nIvan can order \\textbf{any} (possibly zero) number of microtransactions of \\textbf{any} types during any day (of course, \\textbf{if he has enough money to do it}). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles.\n\nThere are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.\n\nIvan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.",
    "tutorial": "Let's iterate over all possible answers. Obviously, this value is always in the range $[1, 2 \\cdot \\sum\\limits_{i=1}^{n}k_i]$. The first day when Ivan can order all microtransactions he wants will be the answer. How to check if the current day $ansd$ is enough to order everything Ivan wants? If we had several sale days for some type of microtransaction (of course, we can use only such days that are not greater than the fixed last day $ansd$), let's use the last one, it is always not worse than some of the previous days. Then let's iterate over all days from $1$ to $ansd$ and do the following: firstly, let's increase our balance by one burle. Then let's try to order all microtransactions for which the current day is the last sale day (and pay one burle per copy). If we are out of money at some moment then just say that we should order all microtransactions that remain in this sale day during the last day for two burles per copy. It is true because it does not matter which types will remain because this day is the last sale day for all of these types. So, after all, we had some remaining microtransactions that we cannot buy during sales, and the current balance. And the current day is good if the number of such microtransactions multiplied by two is not greater than the remaining balance.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nvector<int> k;\nvector<pair<int, int>> q(1001);\n\nbool can(int day) {\n\tvector<int> lst(n, -1);\n\tfor (int i = 0; i < m; ++i) {\n\t\tif (q[i].first <= day) {\n\t\t\tlst[q[i].second] = max(lst[q[i].second], q[i].first);\n\t\t}\n\t}\n\tvector<vector<int>> off(1001);\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (lst[i] != -1) {\n\t\t\toff[lst[i]].push_back(i);\n\t\t}\n\t}\n\tvector<int> need = k;\n\tint cur_money = 0;\n\tfor (int i = 0; i <= day; ++i) {\n\t\t++cur_money;\n\t\tif (i > 1000) continue;\n\t\tfor (auto it : off[i]) {\n\t\t\tif (cur_money >= need[it]) {\n\t\t\t\tcur_money -= need[it];\n\t\t\t\tneed[it] = 0;\n\t\t\t} else {\n\t\t\t\tneed[it] -= cur_money;\n\t\t\t\tcur_money = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn accumulate(need.begin(), need.end(), 0) * 2 <= cur_money;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m;\n\tk = vector<int>(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> k[i];\n\t}\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> q[i].first >> q[i].second;\n\t\t--q[i].first;\n\t\t--q[i].second;\n\t}\n\t\n\tfor (int l = 0; l <= 2000; ++l) {\n\t\tif (can(l)) {\n\t\t\tcout << l + 1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tassert(false);\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1165",
    "index": "F2",
    "title": "Microtransactions (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints}.\n\nIvan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he gets all of them.\n\nEach day (during the \\textbf{morning}) Ivan earns exactly one burle.\n\nThere are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the \\textbf{evening}).\n\nIvan can order \\textbf{any} (possibly zero) number of microtransactions of \\textbf{any} types during any day (of course, \\textbf{if he has enough money to do it}). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles.\n\nThere are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day.\n\nIvan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing.",
    "tutorial": "The main idea of this problem is the same as in the easy version. The only thing we should replace is the search method. Replacing linear search with binary search leads to reducing time complexity from $O(n^2)$ to $O(n \\log n)$. And it is obvious that we can apply binary search here because if we can order all microtransactions during some day $d$ then we can order all of them during day $d+1$ (even using the answer for $d$ days and doing nothing during day $d+1$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nvector<int> k;\nvector<pair<int, int>> q(200001);\n\nbool can(int day) {\n\tvector<int> lst(n, -1);\n\tfor (int i = 0; i < m; ++i) {\n\t\tif (q[i].first <= day) {\n\t\t\tlst[q[i].second] = max(lst[q[i].second], q[i].first);\n\t\t}\n\t}\n\tvector<vector<int>> off(200001);\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (lst[i] != -1) {\n\t\t\toff[lst[i]].push_back(i);\n\t\t}\n\t}\n\tvector<int> need = k;\n\tint cur_money = 0;\n\tfor (int i = 0; i <= day; ++i) {\n\t\t++cur_money;\n\t\tif (i > 200000) continue;\n\t\tfor (auto it : off[i]) {\n\t\t\tif (cur_money >= need[it]) {\n\t\t\t\tcur_money -= need[it];\n\t\t\t\tneed[it] = 0;\n\t\t\t} else {\n\t\t\t\tneed[it] -= cur_money;\n\t\t\t\tcur_money = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn accumulate(need.begin(), need.end(), 0) * 2 <= cur_money;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> m;\n\tk = vector<int>(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> k[i];\n\t}\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> q[i].first >> q[i].second;\n\t\t--q[i].first;\n\t\t--q[i].second;\n\t}\n\t\n\tint l = 0, r = 400000;\n\twhile (r - l > 1) {\n\t\tint mid = (l + r) >> 1;\n\t\tif (can(mid)) r = mid;\n\t\telse l = mid;\n\t}\n\t\n\tfor (int i = l; i <= r; ++i) {\n\t\tif (can(i)) {\n\t\t\tcout << i + 1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tassert(false);\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1166",
    "index": "A",
    "title": "Silent Classroom",
    "statement": "There are $n$ students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must have a lot in common). Let $x$ be the number of such pairs of students in a split. Pairs $(a, b)$ and $(b, a)$ are the same and counted only once.\n\nFor example, if there are $6$ students: \"olivia\", \"jacob\", \"tanya\", \"jack\", \"oliver\" and \"jessica\", then:\n\n- splitting into two classrooms (\"jack\", \"jacob\", \"jessica\", \"tanya\") and (\"olivia\", \"oliver\") will give $x=4$ ($3$ chatting pairs in the first classroom, $1$ chatting pair in the second classroom),\n- splitting into two classrooms (\"jack\", \"tanya\", \"olivia\") and (\"jessica\", \"oliver\", \"jacob\") will give $x=1$ ($0$ chatting pairs in the first classroom, $1$ chatting pair in the second classroom).\n\nYou are given the list of the $n$ names. What is the minimum $x$ we can obtain by splitting the students into classrooms?\n\nNote that it is valid to place all of the students in one of the classrooms, leaving the other one empty.",
    "tutorial": "First, note that we can solve the problem for each starting letter independently, because two students whose name starts with a different letter never form a chatty pair. How do we solve the problem when all the students' names start with the same letter? We claim that it's best to split as evenly as possible. If one classroom has $a$ students, and the other has $b$ students with $a > b + 1$, then by moving one of the students from the first classroom into the second we remove $a - 1$ chatty pairs from the first classroom and create $b$ new chatty pairs in the second, for a net result of $(a - 1) - b > 0$ chatty pairs removed. So in the best splitting we have $\\vert a - b \\vert \\leq 1$, meaning we split as evenly as possible. Then, if $cnt_a$ denotes the number of students whose name starts with $a$, we will split them into a classroom containing $\\lfloor \\frac{cnt_a}{2} \\rfloor$ students and one containing $\\lceil \\frac{cnt_a}{2} \\rceil$ students. So the total number of chatty pairs among students whose name starts with $a$ is $\\binom{\\lfloor \\frac{cnt_a}{2} \\rfloor}{2} + \\binom{\\lceil \\frac{cnt_a}{2} \\rceil}{2}$ The expression is the same for the other letters in the alphabet, and adding them all up gives us our answer. We can also solve the problem without determining what the best splitting is. If, for each starting letter, we try all the possible number of students to send into the first classroom, and choose the one that gives the minimal $x$, then we will only have to do $\\mathcal{O}(n)$ checks in total, which is more than fast enough to solve the problem. Complexity: $\\mathcal{O}(n)$.",
    "tags": [
      "combinatorics",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1166",
    "index": "B",
    "title": "All the Vowels Please",
    "statement": "Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length $k$ is vowelly if there are positive integers $n$ and $m$ such that $n\\cdot m = k$ and when the word is written by using $n$ rows and $m$ columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.\n\nYou are given an integer $k$ and you must either print a vowelly word of length $k$ or print $-1$ if no such word exists.\n\nIn this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'.",
    "tutorial": "First, which boards could we feasibly fill with characters satisfying that every row and column contains one vowel at least once? Well, if we have a board with less than $5$ rows, then each column contains less than $5$ characters, so we cannot have every vowel on each column, and we can't fill the board. Similarly, we can't fill a board with less than $5$ columns. Ok, so say now that we have a board with at least $5$ rows and at least $5$ columns. Can we fill it? Yes we can! It's enough to fill it by diagonals, as shown in the following picture: Now we can easily solve the problem. If $n \\cdot m = k$, then $n$ must divide $k$ and $m = \\frac{k}{n}$. So we can iterate over all possible $n$ from $5$ to $k$, check whether $n$ divides $k$ and in that case, check whether $m = \\frac{k}{n}$ is at least $5$. If this works for at least one value of $n$ then we can fill the $n \\cdot m$ board by diagonals as shown before, and obtain our vowelly word by reading the characters row by row. If we don't find any values of $n$ satisfying this, then no vowelly word exists. Complexity: $\\mathcal{O}(k)$.",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1166",
    "index": "C",
    "title": "A Tale of Two Lands",
    "statement": "The legend of the foundation of Vectorland talks of two integers $x$ and $y$. Centuries ago, the array king placed two markers at points $|x|$ and $|y|$ on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points $|x - y|$ and $|x + y|$ and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland.\n\nHere $|z|$ denotes the absolute value of $z$.\n\nNow, Jose is stuck on a question of his history exam: \"What are the values of $x$ and $y$?\" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to $n$ integers $a_1, a_2, \\dots, a_n$. Now, he wants to know the number of \\textbf{unordered} pairs formed by two \\textbf{different} elements from these $n$ integers such that the legend could be true if $x$ and $y$ were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true.",
    "tutorial": "Formally, the condition for the legend being true reads $\\min(\\vert x - y \\vert, \\vert x + y \\vert) \\le \\vert x \\vert, \\vert y \\vert \\le \\max(\\vert x - y \\vert, \\vert x + y \\vert)$ Now, it is possible to characterize when this condition happens through casework on the signs and sizes of $x$ and $y$, but this can be tricky to do right. However, there is a neat trick that allows us to solve the problem without any casework. What happens if we change $x$ into $-x$? The values of $\\vert x \\vert$ and $\\vert y \\vert$ stay the same, while $\\vert x - y \\vert$ and $\\vert x + y \\vert$ will swap values. This means that the pair $\\{x, y\\}$ works if and only if $\\{-x, y\\}$ works. Similarly we can switch the sign of $y$. This means that we can replace $x$ and $y$ by their absolute values, and the original pair works if and only if the new one works. If $x \\ge 0$ and $y \\ge 0$ then the condition becomes $\\vert x - y \\vert \\le x, y \\le x + y$. The upper bound obviously always holds, while the lower bound is equivalent by some simple algebra to $x \\le 2y \\text{ and } y \\le 2x$ So the problem reduces to counting the number of pairs $\\{x, y\\}$ with $\\vert x \\vert \\le 2 \\vert y \\vert$ and $\\vert y \\vert \\le 2 \\vert x \\vert$. To solve this we now take the absolute values of all the $a_i$ and sort them into an array $b_1 \\le b_2 \\le \\dots \\le b_n$. The answer to the problem is the number of pairs $(l, r)$ with $l < r$ and $b_r \\leq 2b_l$. For each fixed $l$ we calculate the largest $r$ that satisfies this condition, and just add $r - l$ to the answer, as the values $l + 1, l + 2, \\dots, r$ are all the ones that work for this $l$. We can either do a binary search for the best $r$ at each $l$, or calculate the optimal $r$'s for all of the $l$'s in $\\mathcal{O}(n)$ using two pointers. Either way, our final complexity is $\\mathcal{O}(n \\log n)$ as this is the time required to sort the array. Complexity: $\\mathcal{O}(n \\log n)$",
    "tags": [
      "binary search",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1166",
    "index": "D",
    "title": "Cute Sequences",
    "statement": "Given a positive integer $m$, we say that a sequence $x_1, x_2, \\dots, x_n$ of positive integers is $m$-cute if for every index $i$ such that $2 \\le i \\le n$ it holds that $x_i = x_{i - 1} + x_{i - 2} + \\dots + x_1 + r_i$ for some positive integer $r_i$ satisfying $1 \\le r_i \\le m$.\n\nYou will be given $q$ queries consisting of three positive integers $a$, $b$ and $m$. For each query you must determine whether or not there exists an $m$-cute sequence whose first term is $a$ and whose last term is $b$. If such a sequence exists, you must additionally find an example of it.",
    "tutorial": "We will first deal with determining when the sequence doesn't exist. To do this, we place some bounds on the values of $x_n$. If we choose all values of the $r_i$ to be equal to $1$ then we can calculate that $x_n = 2^{n - 2}(x_1 + 1)$. Reciprocally if we choose all $r_i$ to be equal to $m$ then we find $x_n = 2^{n - 2}(x_1 + m)$. All other values give something inbetween, so we get $2^{n - 2}(x_1 + 1) \\le x_n \\le 2^{n - 2}(x_1 + m)$ Therefore, if $b$ doesn't lie on any of the intervals $[2^{n - 2}(a + 1), 2^{n - 2}(a + m)]$ for some value of $n$, then it is impossible for $b$ to be a term of an $m$-cute sequence starting at $a$. This can be checked naively in $\\mathcal{O}(\\log(10^{14}))$ since there are this many relevant values of $n$. We can convince ourselves that all values in these intervals are feasible through some experimentation, so we now turn to the more difficult problem of actually constructing a sequence. First, notice that we can rearrange the definition of the sequence as follows: $x_n = x_1 + x_2 + \\dots + x_{n - 1} + r_n = (x_1 + \\dots + x_{n - 2}) + x_{n - 1} + r_n \\\\ = (x_{n - 1} - r_{n - 1}) + x_{n - 1} + r_n = 2x_{n - 1} + r_n - r_{n - 1}$ Now, we can try to find a pattern. We see that $x_2 = a + r_1$, $x_3 = 2a + r_1 + r_2$, $x_4 = 4a + 2r_1 + r_2 + r_3$, and in general it would seem that. $x_n = 2^{n - 2}a + 2^{n - 3}r_2 + 2^{n - 4}r_3 + \\dots + 2r_{n - 2} + r_{n - 1} + r_n$ This is actually very easy to prove inductively using $x_n = 2x_{n - 1} + r_n - r_{n - 1}$: All coefficients double from one term to the next, but we substract $r_{n - 1}$ once, so that coefficient becomes $1$ instead. Now we can also find an explicit solution: Write $b$ as $2^{n - 2}(a + k) + r$ where $r < 2^{n - 2}$, and consider the binary representation $r = d_{n - 3}d_{n - 4} \\dots d_0$ of $r$. Then choosing $r_i = k + d_{n - 1 - i}$ (where $d_{-1} = 0$) works, because $2^{n - 2}a + 2^{n - 3}(k + d_{n - 3}) + \\dots + 2(k + d_1) + (k + d_0) + k \\\\ = 2^{n - 2}a + (2^{n - 3} + 2^{n - 4} + \\dots + 2 + 1 + 1)k + 2^{n - 3}d_{n - 3} + 2^{n - 4}d_{n - 4} + \\dots + d_0 \\\\ = 2^{n - 2}a + 2^{n - 2}k + r \\\\ = 2^{n - 2}(a + k) + r$ Alternatively, after getting the formula, we can iterate on $i$ from $2$ to $k$ and greedily choose the values of $r_i$ to be as large as we can without exceeding $b$. This can be easily shown to work using that the coefficients are consecutive powers of two. Both of these approaches can be implemented in $\\mathcal{O}(\\log(10^{14}))$ per query. Complexity: $\\mathcal{O}(q\\log(10^{14}))$",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1166",
    "index": "E",
    "title": "The LCMs Must be Large",
    "statement": "Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?\n\nThere are $n$ stores numbered from $1$ to $n$ in Nlogonia. The $i$-th of these stores offers a \\textbf{positive integer} $a_i$.\n\nEach day among the last $m$ days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.\n\nDora considers Swiper to be her rival, and she considers that she beat Swiper on day $i$ if and only if the least common multiple of the numbers she bought on day $i$ is strictly greater than the least common multiple of the numbers that Swiper bought on day $i$.\n\nThe least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.\n\nHowever, Dora forgot the values of $a_i$. Help Dora find out if there are positive integer values of $a_i$ such that she beat Swiper on \\textbf{every} day. You don't need to find what are the possible values of $a_i$ though.\n\nNote that it is possible for some values of $a_i$ to coincide in a solution.",
    "tutorial": "We denote by $\\textrm{lcm}\\; A$ the $\\textrm{lcm}$ of all elements in a collection $A$. Also, denote by $D_i$ and $S_i$ the collections that Dora and Swiper bought on day $i$, respectively. First, when can we say for sure that the values of $a_i$ cannot exist? Well, suppose that $D_i = S_j$ for some $i$ and $j$. Then we also have $D_j = S_i$, so if the condition were true we would have $\\textrm{lcm}\\; D_i > \\textrm{lcm}\\; S_i = \\textrm{lcm}\\; D_j > \\textrm{lcm}\\; S_j = \\textrm{lcm}\\; D_i$ Which is of course impossible. What now? We can actually make our impossibility condition a bit stronger by noticing that $\\textrm{lcm}\\; B \\le \\textrm{lcm}\\; A$ whenever $B$ is a collection contained in $A$, which happens because $\\textrm{lcm}\\; B$ actually divides $\\textrm{lcm}\\; A$. Then, if the stores Dora bought from on day $i$ are completely disjoint from the stores Dora bought from on day $j$, then $D_j$ would be completely contained in $S_i$ and vice-versa, so $\\textrm{lcm}\\; D_i > \\textrm{lcm}\\; S_i \\geq \\textrm{lcm}\\; D_j > \\textrm{lcm}\\; S_j \\geq \\textrm{lcm}\\; D_i$ Which is again a contradiction. Ok, any two days must have a common store for the statement to be possible, so what? The remarkable fact here is that this is the only condition we need to check: i.e., the solution exists if and only if the sets of stores that Dora visited on days $i$ and $j$ intersect for all $i$ and $j$. How do we get a valid solution? We will take $m$ different prime numbers $p_1, p_2, \\dots, p_m$ and set $a_i$ to be the product of $p_j$ for all the $j$'s such that Dora visited store $i$ on day $j$. Then $p_j$ is a divisor of $a_i$ if and only if Dora visited store $i$ on day $j$. Now proving that this works is easy: We know that on day $i$, Dora bought an integer from a store that she also visited on day $j$, and this number must be a multiple of $p_j$. So $\\textrm{lcm}\\; D_i = p_1p_2 \\dots p_m$ for all $i$. On the other hand, $S_i$ contains no multiples of $p_i$, because they are all in $D_i$. So the $\\textrm{lcm}$ of $S_i$ is strictly smaller. Now we just need to check that any two days have a common store, which can be done in $\\mathcal{O}(nm^2)$ by checking each pair of days and determining for each $i$ whether Dora visited both stores on day $i$ in $\\mathcal{O}(n)$. You can achieve a slight speedup if you check this using a bitset, but this wasn't necessary to solve the problem. Complexity: $\\mathcal{O}(nm^2)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1166",
    "index": "F",
    "title": "Vicky's Delivery Service",
    "statement": "In a magical land there are $n$ cities conveniently numbered $1, 2, \\dots, n$. Some pairs of these cities are connected by magical colored roads. Magic is unstable, so at any time, new roads may appear between two cities.\n\nVicky the witch has been tasked with performing deliveries between some pairs of cities. However, Vicky is a beginner, so she can only complete a delivery if she can move from her starting city to her destination city through a double rainbow. A double rainbow is a sequence of cities $c_1, c_2, \\dots, c_k$ satisfying the following properties:\n\n- For each $i$ with $1 \\le i \\le k - 1$, the cities $c_i$ and $c_{i + 1}$ are connected by a road.\n- For each $i$ with $1 \\le i \\le \\frac{k - 1}{2}$, the roads connecting $c_{2i}$ with $c_{2i - 1}$ and $c_{2i + 1}$ have the same color.\n\nFor example if $k = 5$, the road between $c_1$ and $c_2$ must be the same color as the road between $c_2$ and $c_3$, and the road between $c_3$ and $c_4$ must be the same color as the road between $c_4$ and $c_5$.\n\nVicky has a list of events in chronological order, where each event is either a delivery she must perform, or appearance of a new road. Help her determine which of her deliveries she will be able to complete.",
    "tutorial": "Let $G$ be the graph with cities as vertices and roads as edges. Note that the edges originally in $G$ can be regarded as $m$ queries of the \"add edge\" type, so we will just describe a solution that can handle $m + q$ queries of any type. We need a way to capture the idea of going through two roads of the same color in a row. To do this, consider a graph $G^*$ with the same vertices as $G$, in which vertices $u$ and $v$ are connected by an edge if $uw$ and $vw$ are edges of the same color for some vertex $w$. Then any path in this graph corresponds to a double rainbow in the original. However, this doesn't solve the problem yet, because of the condition that the final edge of a double rainbow can be of any color. To help in solving this issue, consider $n$ sets $S_v$ such that $S_v$ has all of the $G^*$-connected components of both $v$ and any neighbor of $v$. Then we can see that we have a double rainbow from $u$ to $v$ if and only if the connected component of $u$ is in $S_v$ (either we reach $v$ directly, or we reach one of its neighbors and then use our final edge to go to $v$). So as long as we can mantain these sets, we have a $\\mathcal{O}(\\log n)$ time way to answer queries of the second type. Now we need to deal with adding edges. To do this, we will store the connectivity of $G^*$ using a DSU. When we connect two connected components in $G^*$, we do the merges from small to large. If we merge component $b$ into component $a$ then for each vertex $u$ in component $b$ and every neighbor $v$ of $u$ we remove $b$ from $S_v$ and insert $a$ instead. By merging from small to large we guarantee that each vertex changes component at most $\\mathcal{O}(\\log n)$ times, and thus we also update $S_v$ through the edge $uv$ at most $\\mathcal{O}(\\log n)$ times. Each update is just two $\\mathcal{O}(\\log n)$ operations, so over all updates this amortizes to $\\mathcal{O}((m + q)\\log(n)^2)$ (because we have $\\mathcal{O}(m + q)$ edges), plus $\\mathcal{O}(n \\log n)$ for actually moving the vertices. There's an easy to fix, but important note, which is that the number of edges in $G^*$ can be quadratically large. However, we can check that for each edge $uv$ of color $x$ that we add, we only need to add two edges to $G^*$. Namely, if $u'$ and $v'$ are neighbors of $u$ and $v$ respectively through an edge of color $x$, then it is enough to add edges $uv'$ and $u'v$. (If one of $u'$ or $v'$ doesn't exist then we just don't add the corresponding edge). We can store these $x$-colored neighbors of each vertex in sets which have total size at most $m + q$, so we can find in $\\mathcal{O}(\\log n)$ which updates we need to perform, and we perform a constant number of updates per added edge. Complexity: $\\mathcal{O}(n \\log(n) + (m + q)\\log(n)^2)$, or $\\mathcal{O}((n + m + q)\\log(n))$ using hash tables.",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "hashing"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1167",
    "index": "A",
    "title": "Telephone Number",
    "statement": "A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.\n\nYou are given a string $s$ of length $n$, consisting of digits.\n\nIn one operation you can delete any character from string $s$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.\n\nYou need to determine whether there is such a sequence of operations (possibly empty), after which the string $s$ becomes a telephone number.",
    "tutorial": "To solve this problem, we just need to find the first occurrence of the digit $8$, let's denote it as $x$. Now if $n - x \\ge 10$ then answer is $YES$, otherwise $NO$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nstring s;\n\nint main(){\n    int tc;\n    cin >> tc;\n    for(int t = 0; t < tc; ++t){\n        cin >> n >> s;\n        int pos = n;\n        for(int i = 0; i < n; ++i)\n            if(s[i] == '8'){\n                pos = i;\n                break;\n            }\n            \n        if(n - pos >= 11)\n            cout << \"YES\\n\";\n        else\n            cout << \"NO\\n\";\n    }\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1167",
    "index": "B",
    "title": "Lost Numbers",
    "statement": "\\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.\n\nThe jury guessed some array $a$ consisting of $6$ integers. There are $6$ special numbers — $4$, $8$, $15$, $16$, $23$, $42$ — and each of these numbers occurs in $a$ exactly once (so, $a$ is some permutation of these numbers).\n\nYou don't know anything about their order, but you are allowed to ask \\textbf{up to $4$ queries}. In each query, you may choose two indices $i$ and $j$ ($1 \\le i, j \\le 6$, $i$ and $j$ are not necessarily distinct), and you will get the value of $a_i \\cdot a_j$ in return.\n\nCan you guess the array $a$?\n\n\\textbf{The array $a$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries}.",
    "tutorial": "The key fact that allows us to solve this problem is that if we analyze the pairwise products of special numbers, we will see that all of them (considering that we always multiply two different numbers) are unique. So, if we, for example, know that $a_i \\cdot a_j = x$, then there are only two possibilities for the values of $a_i$ and $a_j$: $x$ is uniquely expressed as the product of two distinct special numbers $A$ and $B$, and either $a_i = A$, $a_j = B$, or $a_i = B$, $a_j = A$. This allows us to guess three numbers using two queries: we ask $a_i \\cdot a_j$ and $a_j \\cdot a_k$, we uniquely determine $a_j$ as the only number that is suitable for the both pairs, and then we express $a_i = \\frac{a_i \\cdot a_j}{a_j}$ and $a_k = \\frac{a_j \\cdot a_k}{a_j}$. Of course, there are easier ways to solve this problem, considering there are only $6$ special numbers. For example, you could use four queries $a_i \\cdot a_{i + 1}$ (for all $i \\in [1, 4]$) and try all $6!$ permutations, and the model solution uses exactly this approach.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> p = {4, 8, 15, 16, 23, 42};\nint ans[4];\n\nint main()\n{\n\tfor(int i = 0; i < 4; i++)\n\t{\n\t\tcout << \"? \" << i + 1 << \" \" << i + 2 << endl;\n\t\tcout.flush();\n\t\tcin >> ans[i];\n\t}\n\tdo\n\t{\n\t\tbool good = true;\n\t\tfor(int i = 0; i < 4; i++)\n\t\t\tgood &= (p[i] * p[i + 1] == ans[i]);\n\t\tif(good) break;\n\t}\n\twhile(next_permutation(p.begin(), p.end()));\n\tcout << \"!\";\n\tfor(int i = 0; i < 6; i++)\n\t\tcout << \" \" << p[i];\n\tcout << endl;\n\tcout.flush();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "divide and conquer",
      "interactive",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1167",
    "index": "C",
    "title": "News Distribution",
    "statement": "In some social network, there are $n$ users communicating with each other in $m$ groups of friends. Let's analyze the process of distributing some news between users.\n\nInitially, some user $x$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.\n\nFor each user $x$ you have to determine what is the number of users that will know the news if initially only user $x$ starts distributing it.",
    "tutorial": "The first intention after reading the problem is to reformulate it in graph theory terms. Let people be vertices, edge between two vertices $x$ and $y$ exists if $x$ and $y$ have some group in common. Basically, if person $x$ starts distributing the news, everyone in his connectivity component recieves it. Thus, the task is to calculate the number of vertices of each vertex component. As of now, the graph can have up to $O(n^2)$ edges (consider the case where everyone is in the same group). Let's reduce the number of edges without changing connectivity components. For each group you know for sure that people in it are in the same component. Let's connect not just every pair of vertices in it, but every pair of neighbouring ones in each group. It's easy to see that they are still in the same component. This graph will have $O(\\sum \\limits_{i = 1}^{m} k_i)$ edges which is a much smaller number. You can use dfs or dsu to find the components and their sizes. Overall complexity: $O(n + \\sum \\limits_{i = 1}^{m} k_i)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nconst int N = 500 * 1000 + 13;\n\nint n, m;\nint rk[N], p[N];\n\nint getP(int a){\n\treturn (a == p[a] ? a : p[a] = getP(p[a]));\n}\n\nvoid unite(int a, int b){\n\ta = getP(a), b = getP(b);\n\tif (a == b) return;\n\tif (rk[a] < rk[b]) swap(a, b);\n\tp[b] = a;\n\trk[a] += rk[b];\n}\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tforn(i, n) p[i] = i, rk[i] = 1;\n\t\n\tforn(i, m){\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\tint lst = -1;\n\t\tforn(j, k){\n\t\t\tint x;\n\t\t\tscanf(\"%d\", &x);\n\t\t\t--x;\n\t\t\tif (lst != -1)\n\t\t\t\tunite(x, lst);\n\t\t\tlst = x;\n\t\t}\n\t}\n\t\n\tforn(i, n)\n\t\tprintf(\"%d \", rk[getP(i)]);\n\tputs(\"\");\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1167",
    "index": "D",
    "title": "Bicolored RBS",
    "statement": "A string is called bracket sequence if it does not contain any characters other than \"(\" and \")\". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters \"+\" and \"1\" into this sequence. For example, \"\", \"(())\" and \"()()\" are RBS and \")(\" and \"(()\" are not.\n\nWe can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define \\textbf{nesting depth} of the RBS as maximum number of bracket pairs, such that the $2$-nd pair lies inside the $1$-st one, the $3$-rd one — inside the $2$-nd one and so on. For example, nesting depth of \"\" is $0$, \"()()()\" is $1$ and \"()((())())\" is $3$.\n\nNow, you are given RBS $s$ of even length $n$. You should color each bracket of $s$ into one of two colors: red or blue. Bracket sequence $r$, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets $b$, should be RBS. Any of them can be empty. You are not allowed to reorder characters in $s$, $r$ or $b$. No brackets can be left uncolored.\n\nAmong all possible variants you should choose one that \\textbf{minimizes maximum} of $r$'s and $b$'s nesting depth. If there are multiple solutions you can print any of them.",
    "tutorial": "Let $d(s)$ be nested depth of RBS $s$. There is an interesting fact that $\\max(d(r), d(b)) \\ge \\left\\lceil \\frac{d(s)}{2} \\right\\rceil$. From the other side we can always reach equation $\\max(d(r), d(b)) = \\left\\lceil \\frac{d(s)}{2} \\right\\rceil$ using some approaches. Let's look at prefix of length $i$ of string $s$. Let $o_s(i)$ be number of opening bracket in the prefix, $c_s(i)$ - number of closing brackets. Then we can define balance of the $i$-th prefix of $s$ as $bal_s(i) = o_s(i) - c_s(i)$. The author's approach is next: Let's define level of pair of brackets (matched in natural way) as $bal_s(i - 1)$, where $i$ is position of opening bracket of this pair. Then we will color in red all pairs with even level and in blue - with odd level. -- Proof of $\\max(d(r), d(b)) \\ge \\left\\lceil \\frac{d(s)}{2} \\right\\rceil$: It can be shown that $d(s) = \\max\\limits_{1 \\le i \\le n}(bal_s(i))$ and exists such $pos$ that $d(s) = bal_s(pos)$. After any coloring of $s$ we can define number of opening/closing red (blue) brackets of $pos$-th prefix of $s$ as $o_r(pos)$ ($o_b(pos)$) and $c_r(pos)$ ($c_b(pos)$) respectively. Since $o_s(pos) = o_r(pos) + o_b(pos)$ and $c_s(pos) = c_r(pos) + c_b(pos)$, then $\\max(bal_r(pos), bal_b(pos)) = \\max(o_r(pos) - c_r(pos), bal_b(pos)) \\\\ = \\max((o_s(pos) - o_b(pos)) - (c_s(pos) - c_b(pos)), bal_b(pos)) = \\max((o_s(pos) - c_s(pos)) - (o_b(pos) - c_b(pos)), bal_b(pos)) \\\\ = \\max(bal_s(pos) - bal_b(pos), bal_b(pos)) \\ge \\left\\lceil \\frac{bal_s(pos)}{2} \\right\\rceil = \\left\\lceil \\frac{d(s)}{2} \\right\\rceil.$ Finally, $\\max(d(a), d(b)) = \\max(\\max\\limits_{1 \\le i \\le n}(bal_r(i)), \\max\\limits_{1 \\le i \\le n}(bal_b(i))) \\\\ = \\max\\limits_{1 \\le i, j \\le n}(\\max(bal_r(i), bal_b(j))) \\ge \\max(bal_r(pos), bal_b(pos)) \\ge \\left\\lceil \\frac{d(s)}{2} \\right\\rceil$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nint n;\nstring s;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\tcin >> s;\n\treturn true;\n}\n\ninline void solve() {\n\tstring t(n, '0');\n\t\n\tint bal = 0;\n\tfore(i, 0, n) {\n\t\tif(s[i] == ')')\n\t\t\tbal--;\n\t\t\n\t\tt[i] = char('0' + (bal & 1));\n\t\t\n\t\tif(s[i] == '(')\n\t\t\tbal++;\n\t}\n\t\n\tcout << t << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1167",
    "index": "E",
    "title": "Range Deleting",
    "statement": "You are given an array consisting of $n$ integers $a_1, a_2, \\dots , a_n$ and an integer $x$. It is guaranteed that for every $i$, $1 \\le a_i \\le x$.\n\nLet's denote a function $f(l, r)$ which erases all values such that $l \\le a_i \\le r$ from the array $a$ and returns the resulting array. For example, if $a = [4, 1, 1, 4, 5, 2, 4, 3]$, then $f(2, 4) = [1, 1, 5]$.\n\nYour task is to calculate the number of pairs $(l, r)$ such that $1 \\le l \\le r \\le x$ and $f(l, r)$ is sorted in non-descending order. Note that the empty array is also considered sorted.",
    "tutorial": "Lets find the maximum number $pref$ such that all values $1, 2, \\dots, pref$ form the non-descending order array. It can be done the following way. Let values $1, 2, \\dots, x$ form the non-descending order array. Then values $1, 2, \\dots, x, x+1$ will form the non-descending order array if the first occurrence of $x+1$ in array $a$ is after the last occurrence of $x$. In similar manner we can find the minimum number $suf$ such that all values $suf, suf+1, \\dots, x$ form the non-descending order array. Now let's find out how to get the minimum number $s$ such that all values $1, 2, \\dots, p, s, s + 1, \\dots, x$ form the non-descending order array if we fixed the value $p$. We denote this value $s$ for some fixed value $p$ as $f(p)$. Firstly, conditions $s > p$, $suf \\le s$ and $p \\le pre$ should hold. Secondly, there should be no such a pair $(m, r)$ that conditions $1 \\le m < r \\le n$, $1 \\le a_r, \\le p$ and $s \\le a_m \\le x$ hold. Since the condition $p \\le pre$ is satisfied, it means that $s$ must be greater than $\\max\\limits_{1 \\le i \\le lst} a_i$, where $lst$ is the last occurrence of $p$ in array $a$. In this way the answer is $\\sum\\limits_{i=1}^{pref} (x - f(i) + 1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(1e6) + 99;\nint n, x;\nint a[N];\nvector <int> pos[N];\nint prefMax[N];\n\nint main() {\n\tscanf(\"%d %d\", &n, &x);\n\tfor(int i = 0; i < n; ++i){\n\t\tscanf(\"%d\", a + i);\n\t\tpos[a[i]].push_back(i);\t\n\t\tprefMax[i] = max(a[i], (i > 0 ? prefMax[i - 1] : a[i]));\n\t}\n\t\n\tint p = 1;\n\tint lst = n + 5;\n\tfor(int i = x; i >= 1; --i){\n\t\tif(pos[i].empty()){\n\t\t    p = i;\n\t\t    continue;\n\t\t}\n\t\tif(pos[i].back() > lst) break;\n\t\tp = i;\n\t\tlst = pos[i][0];\n\t}\t\n\n\tlong long res = 0;\n\tlst = -1;\n\tfor(int l = 1; l <= x; ++l){\n\t\tint r = max(l, p - 1);\n\t\tif(lst != -1) r = max(r, prefMax[lst]);\n\t\tres += x - r + 1;\n\t\tif(!pos[l].empty()){\n    \t\tif(pos[l][0] < lst) break;\n    \t\tlst = pos[l].back();\n\t\t}\n\t}\t\n\n\tcout << res << endl;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "data structures",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1167",
    "index": "F",
    "title": "Scalar Queries",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$. All $a_i$ are pairwise distinct.\n\nLet's define function $f(l, r)$ as follows:\n\n- let's define array $b_1, b_2, \\dots, b_{r - l + 1}$, where $b_i = a_{l - 1 + i}$;\n- sort array $b$ in increasing order;\n- result of the function $f(l, r)$ is $\\sum\\limits_{i = 1}^{r - l + 1}{b_i \\cdot i}$.\n\nCalculate $\\left(\\sum\\limits_{1 \\le l \\le r \\le n}{f(l, r)}\\right) \\mod (10^9+7)$, i.e. total sum of $f$ for all subsegments of $a$ modulo $10^9+7$.",
    "tutorial": "Let's define some functions at first: indicator function $I(x) = 1$ if $x$ is true and $0$ otherwise. $lower(l, r, x)$ is a number of $a_j$ that $l \\le j \\le r$ and $a_j < x$. Good observation: $lower(l, r, x) = \\sum_{j = l}^{j = r}{I(a_j < x)}$. Another observation: $f(l, r) = \\sum\\limits_{i = l}^{i = r}{a_i \\cdot (lower(l, r, a_i) + 1})$. Now, it's time to transform what we'd like to calculate: $\\sum_{1 \\le l \\le r \\le n}{f(l, r)} = \\sum_{1 \\le l \\le r \\le n}{\\sum_{i = l}^{i = r}{a_i \\cdot (lower(l, r, a_i) + 1})} = \\sum_{1 \\le l \\le r \\le n}{(\\sum_{i = l}^{i = r}{a_i \\cdot lower(l, r, a_i)} + \\sum_{i = l}^{i = r}{a_i})} = \\\\ = \\sum_{1 \\le l \\le r \\le n}{\\sum_{i = l}^{i = r}{a_i \\cdot lower(l, r, a_i)}} + \\sum_{i = 1}^{i = n}{a_i \\cdot i \\cdot (n - i + 1)}$ Since transformation of the second sum was standard, we'll look at the first sum: $\\sum_{1 \\le l \\le r \\le n}{\\sum_{i = l}^{i = r}{a_i \\cdot lower(l, r, a_i)}} = \\sum_{i = 1}^{i = n}{\\sum_{1 \\le l \\le i \\le r \\le n}{a_i \\cdot lower(l, r, a_i)}} = \\sum_{i = 1}^{i = n}{a_i \\sum_{1 \\le l \\le i \\le r \\le n}{lower(l, i, a_i) + lower(i, r, a_i)}} = \\\\ = \\sum_{i = 1}^{i = n}{a_i \\sum_{1 \\le l \\le i}{ \\sum_{i \\le r \\le n}{lower(l, i, a_i) + lower(i, r, a_i)}}} = \\sum_{i = 1}^{i = n}{a_i \\left( (n - i + 1) \\sum_{1 \\le l \\le i}{lower(l, i, a_i)} + i \\sum_{i \\le r \\le n}{lower(i, r, a_i)} \\right) }$ So, we can iterate over $i$ and we'd like to calculate this two sums fast enough. So, more transformations: $\\sum_{1 \\le l \\le i}{lower(l, i, a_i)} = \\sum_{1 \\le l \\le i}{\\sum_{j = l}^{j = i}{I(a_j < a_i)}} = \\sum_{j = 1}^{j = i}{\\sum_{l = 1}^{l = j}{I(a_j < a_i)}} = \\sum_{j = 1}^{j = i}{I(a_j < a_i) \\cdot j}$ So, while iterating over $i$ we need to make queries of two types: set value $i$ in position $a_i$ and calculate $\\sum_{a_j < a_i}{j}$. It can be done by BIT with coordinate compression. $\\sum_{i \\le r \\le n}{lower(i, r, a_i)}$ can be calculated in the same way iterating over $i$ in reverse order. Result complexity is $O(n \\log{n})$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\ntypedef long long li;\n\nconst int MOD = int(1e9) + 7;\n\nint add(int a, int b) {\n\ta += b;\n\twhile(a >= MOD)\n\t\ta -= MOD;\n\twhile(a < 0)\n\t\ta += MOD;\n\treturn a;\n}\nint mul(int a, int b) {\n\treturn int(a * 1ll * b % MOD);\n}\n\nint n;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tfore(i, 0, n)\n\t\tcin >> a[i];\n\treturn true;\n}\n\nvector<li> f;\nvoid inc(int pos, int val) {\n\tfor(; pos < sz(f); pos |= pos + 1)\n\t\tf[pos] += val;\n}\nli sum(int pos) {\n\tli ans = 0;\n\tfor(; pos >= 0; pos = (pos & (pos + 1)) - 1)\n\t\tans += f[pos];\n\treturn ans;\n}\n\nvector<int> S[2];\n\ninline void solve() {\n\tfore(k, 0, 2) {\n\t\tS[k].assign(n, 0);\n\t\tf.assign(n, 0);\n\t\t\n\t\tvector<int> dx(a.begin(), a.end());\n\t\tsort(dx.begin(), dx.end());\n\t\t\n\t\tfore(i, 0, n) {\n\t\t\tint pos = int(lower_bound(dx.begin(), dx.end(), a[i]) - dx.begin());\n\t\t\tS[k][i] = int(sum(pos) % MOD);\n\t\t\tinc(pos, i + 1);\n\t\t}\n\t\treverse(a.begin(), a.end());\n\t}\n\t\n\treverse(S[1].begin(), S[1].end());\n\tint ans = 0;\n\tfore(i, 0, n) \n\t\tans = add(ans, mul(a[i], add(mul(i + 1, n - i), add(mul(S[0][i], n - i), mul(S[1][i], i + 1)))));\n\t\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "math",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1167",
    "index": "G",
    "title": "Low Budget Inception",
    "statement": "So we got bored and decided to take our own guess at how would \"Inception\" production go if the budget for the film had been terribly low.\n\nThe first scene we remembered was the one that features the whole city bending onto itself:\n\nIt feels like it will require high CGI expenses, doesn't it? Luckily, we came up with a similar-looking scene which was a tiny bit cheaper to make.\n\nFirstly, forget about 3D, that's hard and expensive! The city is now represented as a number line (infinite to make it easier, of course).\n\nSecondly, the city doesn't have to look natural at all. There are $n$ buildings on the line. Each building is a square $1 \\times 1$. \\textbf{Buildings are numbered from $1$ to $n$ in ascending order of their positions.} Lower corners of building $i$ are at integer points $a_i$ and $a_i + 1$ of the number line. Also the distance between any two neighbouring buildings $i$ and $i + 1$ doesn't exceed $d$ (really, this condition is here just to make the city look not that sparse). Distance between some neighbouring buildings $i$ and $i + 1$ is calculated from the lower right corner of building $i$ to the lower left corner of building $i + 1$.\n\nFinally, curvature of the bend is also really hard to simulate! Let the bend at some integer coordinate $x$ be performed with the following algorithm. Take the ray from $x$ to $+\\infty$ and all the buildings which are on this ray and start turning the ray and the buildings counter-clockwise around point $x$. At some angle some building will touch either another building or a part of the line. You have to stop bending there (implementing buildings crushing is also not worth its money).\n\n\\textbf{Let's call the angle between two rays in the final state the terminal angle $\\alpha_x$.}\n\nThe only thing left is to decide what integer point $x$ is the best to start bending around. Fortunately, we've already chosen $m$ candidates to perform the bending.\n\nSo, can you please help us to calculate terminal angle $\\alpha_x$ for each bend $x$ from our list of candidates?",
    "tutorial": "Let's solve the problem for a single query at first. There are two possible types of collisions: between two buildings and between a building and a ray. Obviously, if the collision of the second type happens, then it's the building which is the closest to the bend point (from either left or right). The less obvious claim is that among all buildings collisions, the closest is the biggest angle one. Let's boil down some possibilities of colliding buildings. Let two buildings be the same distance $D$ from the bend point $x$. Then they will collide and the collision point will $(x - D, 1)$. Two buildings also collide if the left one is $D + 1$ from $x$ and the right one is $D$. Then the point of collision is $(x - D + 1, 1)$. And for the opposite case the point of collision is also $(x - D + 1, 1)$. These points can be easily proven by checking the distances to upper corners of each building. No other two buildings will collide. Now that we know this, we can transition to solving a problem of checking if there exists such a pair that the distances to $x$ from them differ by at most one. Finding such a pair with minimal $D$ is enough. Obviously, this can be done with some sort of two pointers. However, that's not the intended solution. Let's constuct bitset of 7000 positions to the left of the bend and to the right of the bend. AND of these bitsets will give you the pairs such that the distance $D$ is the same for them. However, you can put 1 in points $y - 1$ and $y$ for each building to the left and $y$ and $y + 1$ for each building to the right. This way AND will give you the exact pairs you need. Use _Find_first to find the closest one. Let collision happen on distance $D$. Then the collision of the first type will have angle $2 \\cdot arctan D$ and the collision of the second type will have angle $arctan D$. The answer is the maximum of these two values. Be careful with cases where $D = 0$. How to process lots of queries. Let's just move the bitsets to the right while going through queries in ascending order. Bitsets can be updated in $(d / 32)$ for each query and only $n$ buildings will be added to them in total. Overall complexity: $O(md / 32 + n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nconst int N = 200 * 1000 + 555;\nconst int D = 7077;\n\nint n, d, m;\nint a[N], qs[N];\n\ninline bool read() {\n\tif(scanf(\"%d%d\", &n, &d) != 2)\n\t\treturn false;\n\tfore(i, 0, n)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tassert(scanf(\"%d\", &m) == 1);\n\tfore(i, 0, m)\n\t\tscanf(\"%d\", &qs[i]);\n\treturn true;\n}\n\nbitset<D> L, R, cur;\nint dist[N];\nset<int> has;\n\nvoid shiftL(int s, int t, int &uk) {\n\tL <<= t - s;\n\tfor(; uk < n && a[uk] < t; uk++) {\n\t\tif(t - a[uk] - 1 < D)\n\t\t\tL[t - a[uk] - 1] = 1;\n\t\tif(t - a[uk] < D)\n\t\t\tL[t - a[uk]] = 1;\n\t}\n}\n\nvoid shiftR(int s, int t, int &uk) {\n\tR >>= t - s;\n\tif(!has.count(t))\n\t\tR[0] = 0;\n\t\n\tfor(; uk < n && a[uk] < t + D; uk++) {\n\t\tif(a[uk] - t >= 0) {\n\t\t\tR[a[uk] - t] = 1;\n\t\t\tif(a[uk] - t + 1 >= 0)\n\t\t\t\tR[a[uk] - t + 1] = 1;\n\t\t}\n\t}\n}\n\ninline void solve() {\n\tfore(i, 0, m) {\n\t\tdist[i] = INF;\n\t\tint pos = int(lower_bound(a, a + n, qs[i]) - a);\n\t\tif(pos > 0)\n\t\t\tdist[i] = qs[i] - a[pos - 1] - 1;\n\t\tif(pos < n)\n\t\t\tdist[i] = min(dist[i], a[pos] - qs[i]);\n\t}\n\thas = set<int>(a, a + n);\n\t\n\tint uL = 0, uR = 0;\n\tL.reset();\n\tR.reset();\n\tfore(i, 0, m) {\n\t\tshiftL(i > 0 ? qs[i - 1] : -D, qs[i], uL);\n\t\tshiftR(i > 0 ? qs[i - 1] : -D, qs[i], uR);\n\t\t\n\t\tdouble ans = atan2(1, dist[i]);\n\n\t\tcur = L & R;\n\t\tint pos = (int)cur._Find_first();\n\t\tif(pos < D) {\n\t\t\tint ds = pos;\n\t\t\tans = max(ans, 2 * atan2(1, ds));\n\t\t}\n\t\tprintf(\"%.15f\\n\", ans);\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "geometry"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1168",
    "index": "A",
    "title": "Increasing by Modulo",
    "statement": "Toad Zitz has an array of integers, each integer is between $0$ and $m-1$ inclusive. The integers are $a_1, a_2, \\ldots, a_n$.\n\nIn one operation Zitz can choose an integer $k$ and $k$ indices $i_1, i_2, \\ldots, i_k$ such that $1 \\leq i_1 < i_2 < \\ldots < i_k \\leq n$. He should then change $a_{i_j}$ to $((a_{i_j}+1) \\bmod m)$ for each chosen integer $i_j$. The integer $m$ is fixed for all operations and indices.\n\nHere $x \\bmod y$ denotes the remainder of the division of $x$ by $y$.\n\nZitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.",
    "tutorial": "Let's check that the answer to the problem is $\\leq x$. Then, for each element, you have some interval (interval on the \"circle\" of remainders modulo $m$) of values, that it can be equal to. So you need to check that you can pick in each interval some point, to make all these values non-decrease. You can do it with greedy! Each time, let's take the smallest element from the interval, that is at least the previously chosen value. And after this, let's make the binary search on $x$. So we have the solution in $O(n \\log m)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\n#ifdef ONPC\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nint main() {\\n#ifdef ONPC\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  int n, m;\\n  cin >> n >> m;\\n  vector <int> a(n);\\n  for (int &x : a) {\\n    cin >> x;\\n  }\\n  int l = -1, r = m;\\n  while (l < r - 1) {\\n    int mid = (l + r) / 2;\\n    int prev = 0;\\n    bool bad = false;\\n    for (int i = 0; i < n; i++) {\\n      int lf = a[i], rf = a[i] + mid;\\n      if ((lf <= prev && prev <= rf) || (lf <= prev + m && prev + m <= rf)) {\\n        continue;\\n      }\\n      if (lf < prev) {\\n        bad = true;\\n        break;\\n      } else {\\n        prev = lf;\\n      }\\n    }\\n    if (bad) {\\n      l = mid;\\n    }\\n    else {\\n      r = mid;\\n    }\\n  }\\n  cout << r << '\\\\n';\\n}\"",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1168",
    "index": "B",
    "title": "Good Triple",
    "statement": "Toad Rash has a binary string $s$. A binary string consists only of zeros and ones.\n\nLet $n$ be the length of $s$.\n\nRash needs to find the number of such pairs of integers $l$, $r$ that $1 \\leq l \\leq r \\leq n$ and there is at least one pair of integers $x$, $k$ such that $1 \\leq x, k \\leq n$, $l \\leq x < x + 2k \\leq r$, and $s_x = s_{x+k} = s_{x+2k}$.\n\nFind this number of pairs for Rash.",
    "tutorial": "Lemma: there are no strings without such $x,k$ of length at least 9. In fact, you just can write brute force to find all \"good\" strings and then realize that they all are small. Ok, so with this you can just write some sort of \"naive\" solution, for each $l$ find the largest $r$, such that $l \\ldots r$ is a \"good\" string, and then add $n - r$ to the answer. You can do it in $9 \\cdot 9 \\cdot n$ or in $9 \\cdot n$, as I do in my solution.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\n#ifdef ONPC\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nint main() {\\n#ifdef ONPC\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  string s;\\n  cin >> s;\\n  int n = (int) s.size();\\n  vector <int> vl(n + 1, n);\\n  ll ans = 0;\\n  for (int i = n - 1; i >= 0; i--) {\\n    vl[i] = vl[i + 1];\\n    for (int k = 1; i + 2 * k < vl[i]; k++) {\\n      if (s[i] == s[i + k] && s[i + k] == s[i + 2 * k]) {\\n        vl[i] = i + 2 * k;\\n      }\\n    }\\n    ans += n - vl[i];\\n  }\\n  cout << ans << endl;\\n}\"",
    "tags": [
      "brute force",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1168",
    "index": "C",
    "title": "And Reachability",
    "statement": "Toad Pimple has an array of integers $a_1, a_2, \\ldots, a_n$.\n\nWe say that $y$ is reachable from $x$ if $x<y$ and there exists an integer array $p$ such that $x = p_1 < p_2 < \\ldots < p_k=y$, and $a_{p_i}\\, \\&\\, a_{p_{i+1}} > 0$ for all integers $i$ such that $1 \\leq i < k$.\n\nHere $\\&$ denotes the bitwise AND operation.\n\nYou are given $q$ pairs of indices, check reachability for each of them.",
    "tutorial": "Let's calculate $go_{i, k}$ - the smallest $j$, such that $a_j$ contains bit $k$, which is reachable from $i$. How to recalculate it? Let $last_{i,k}$ is the smallest $j > i$, such that $a_j$ contains bit $k$. Then, I claim that $go_{i,k}$ is equal to the $i$ or to the $\\min{(go_{last_{i,j},k})}$ for all bits $j$ that $a_i$ contains. Why? Because if you go from $i$ to some number, which has bit $j$ in the intersection, it is useless to go to the number which is not equal to $last_{i,j}$, because from $last_{i,j}$ you can go to all numbers that have bit $j$ and that positioned farther. So in $O(n \\log )$ you can calculate all these values, and then to answer the query you can check that there exists some bit $j$ in $a_y$ such that $go_{x, j} \\leq y$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\n#ifdef ONPC\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nconst int N = 3e5 + 7;\\nconst int LG = 19;\\n\\nint go[N][LG];\\nint a[N];\\nint last[LG];\\n\\nint main() {\\n#ifdef ONPC\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  int n, q;\\n  cin >> n >> q;\\n  for (int i = 0; i < n; i++) {\\n    cin >> a[i];\\n  }\\n  for (int j = 0; j < LG; j++) {\\n    go[n][j] = n;\\n    last[j] = n;\\n  }\\n  for (int i = n - 1; i >= 0; i--) {\\n    for (int j = 0; j < LG; j++) {\\n      go[i][j] = n;\\n    }\\n    for (int j = 0; j < LG; j++) {\\n      if ((a[i] >> j) & 1) {\\n        for (int k = 0; k < LG; k++) {\\n          go[i][k] = min(go[i][k], go[last[j]][k]);\\n        }\\n        last[j] = i;\\n        go[i][j] = i;\\n      }\\n    }\\n  }\\n  for (int i = 0; i < q; i++) {\\n    int x, y;\\n    cin >> x >> y;\\n    x--, y--;\\n    bool good = false;\\n    for (int j = 0; j < LG; j++) {\\n      good |= (((a[y] >> j) & 1) && go[x][j] <= y);\\n    }\\n    cout << (good ? \\\"Shi\\\" : \\\"Fou\\\") << '\\\\n';\\n  }\\n}\"",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1168",
    "index": "D",
    "title": "Anagram Paths",
    "statement": "Toad Ilya has a rooted binary tree with vertex $1$ being the root. A tree is a connected graph without cycles. A tree is rooted if one vertex is selected and called the root. A vertex $u$ is a child of a vertex $v$ if $u$ and $v$ are connected by an edge and $v$ is closer to the root than $u$. A leaf is a non-root vertex that has no children.\n\nIn the tree Ilya has each vertex has \\textbf{at most two} children, and each edge has some character written on it. The character can be a lowercase English letter or the question mark '?'.\n\nIlya will $q$ times update the tree a bit. Each update will replace exactly one character on some edge. After each update Ilya needs to find if the tree is anagrammable and if yes, find its anagramnity for each letter. Well, that's difficult to explain, but we'll try.\n\nTo start with, a string $a$ is an anagram of a string $b$ if it is possible to rearrange letters in $a$ (without changing the letters itself) so that it becomes $b$. For example, the string \"fortyfive\" is an anagram of the string \"overfifty\", but the string \"aabb\" is not an anagram of the string \"bbba\".\n\nConsider a path from the root of the tree to a leaf. The characters on the edges on this path form a string, we say that this string is associated with this leaf. The tree is anagrammable if and only if it is possible to replace each question mark with a lowercase English letter so that for all pair of leaves the associated strings for these leaves are anagrams of each other.\n\nIf the tree is anagrammable, then its anagramnity for the letter $c$ is the maximum possible number of letters $c$ in a string associated with some leaf in a valid replacement of all question marks.\n\nPlease after each update find if the tree is anagrammable and if yes, find the $\\sum{f(c) \\cdot ind(c)}$ for all letters $c$, where $f(c)$ is the anagramnity for the letter $c$, and $ind(x)$ is the index of this letter in the alphabet ($ind($\"a\"$) = 1$, $ind($\"b\"$) = 2$, ..., $ind($\"z\"$) = 26$).",
    "tutorial": "Ok, let's make some useless (ha-ha, in fact not) observation at first, obviously, all leaves must have the same depth. Now, I will define the criterion for the tree to be good. Let $f(v,x)$ be the largest number of characters $x$ that contained on edges of some path from vertex $v$ to the leaf, and $len_v$ be the length of a path from $v$ to the leaf. Lemma: tree is good iff for each vertex $\\sum{f(v,x)} \\leq len_v$. Obviously, if the tree is good $\\sum{f(v,x)} \\leq len_v$ for each vertex because else you just don't have enough \"space\" in the subtree of the vertex to contain all required characters. Why is it criterion? If for each vertex it is satisfied, from the root you can find some suitable characters on the edges from it, and then it is easy to see that you can restore the children by induction. Ok, with this knowledge how to solve the problem? Maybe some spooky tree data structures will help us?... Yup, you can do it with the \"Dynamic tree DP technique\" with HLD, and you will get the solution in $O(n \\log^2 n)$ even for not a binary tree. But it is not very easy to realize it :) Let's remember that all leaves must have the same depth, so I will give you another Lemma! Lemma: if you will \"compress\" all vertices with one son in the tree, where all leaves have an equal depth, then the depth of this tree will be $O(\\sqrt{n})$. Why? let $a_i$ be the number of vertices on the depth $i$, then $a_i \\geq a_{i-1}$ for each $i \\leq h$ as each vertex at the depth $i-1$ should have at least one son, and you have $\\sum{a_i}=n$, so there are $O( \\sqrt{n})$ distinct values among them, so almost all (without some $O(\\sqrt{n})$ values) $i$ has $a_i = a_{i-1}$ (which means that all vertices at the depth $i-1$ has exactly one son). So with this knowledge, you can \"compress\" the tree as I described, and after each query just go up from the end of the changed edge and recalculate the DP. Of course, each edge now will have several characters on it, so you should maintain a counter in each edge, but it is more a realization aspect.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\n#ifdef ONPC\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nint main() {\\n#ifdef ONPC\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  int n, q;\\n  cin >> n >> q;\\n  vector <int> par(n), dep(n), deg(n), up(n), up_ch(n), len(n), sum(n), ch(n);\\n  vector <vector <int> > g(n), dp(n, vector <int> (26)), cnt(n, vector <int> (26));\\n  for (int i = 1; i < n; i++) {\\n    int p;\\n    char c;\\n    cin >> p >> c;\\n    p--;\\n    dep[i] = dep[p] + 1;\\n    deg[p]++;\\n    par[i] = p;\\n    ch[i] = c;\\n  }\\n  for (int i = n - 1; i; i--) {\\n    if (len[par[i]] && len[par[i]] != len[i] + 1) {\\n      for (int j = 0; j < q; j++) {\\n        cout << \\\"Fou\\\\n\\\";\\n      }\\n      return 0;\\n    }\\n    len[par[i]] = len[i] + 1;\\n  }\\n  for (int i = 0; i < n; i++) {\\n    if (deg[par[i]] > 1 || !par[i]) {\\n      up[i] = par[i];\\n      up_ch[i] = i;\\n    }\\n    else {\\n      up[i] = up[par[i]];\\n      up_ch[i] = up_ch[par[i]];\\n    }\\n    if (i && ch[i] != '?') {\\n      cnt[up_ch[i]][ch[i] - 'a']++;\\n    }\\n  }\\n  int bad = 0;\\n  for (int i = n - 1; i; i--) {\\n    if (deg[i] != 1) {\\n      for (int j = 0; j < 26; j++) {\\n        dp[up[i]][j] = max(dp[up[i]][j], dp[i][j] + cnt[up_ch[i]][j]);\\n      }\\n      g[up[i]].push_back(i);\\n    }\\n  }\\n  for (int i = 0; i < n; i++) {\\n    for (int j = 0; j < 26; j++) {\\n      sum[i] += dp[i][j];\\n    }\\n    if (sum[i] > len[i]) {\\n      bad++;\\n    }\\n  }\\n  up[0] = -1;\\n  auto upd = [&] (int v, char c) {\\n    if (c == '?') {\\n      return;\\n    }\\n    c -= 'a';\\n    for (; ~v; v = up[v]) {\\n      if (sum[v] > len[v]) {\\n        bad--;\\n      }\\n      sum[v] -= dp[v][c];\\n      dp[v][c] = 0;\\n      for (int to : g[v]) {\\n        dp[v][c] = max(dp[v][c], dp[to][c] + cnt[up_ch[to]][c]);\\n      }\\n      sum[v] += dp[v][c];\\n      if (sum[v] > len[v]) {\\n        bad++;\\n      }\\n    }\\n  };\\n  for (int i = 0; i < q; i++) {\\n    int v;\\n    char c;\\n    cin >> v >> c;\\n    v--;\\n    if (ch[v] != '?') {\\n      cnt[up_ch[v]][ch[v] - 'a']--;\\n      upd(up[v], ch[v]);\\n    }\\n    ch[v] = c;\\n    if (ch[v] != '?') {\\n      cnt[up_ch[v]][ch[v] - 'a']++;\\n      upd(up[v], ch[v]);\\n    }\\n    if (bad) {\\n      cout << \\\"Fou\\\\n\\\";\\n    } else {\\n      cout << \\\"Shi \\\";\\n      int val = 0;\\n      for (int i = 0; i < 26; i++) {\\n        val += (dp[0][i] + len[0] - sum[0]) * (i + 1);\\n      }\\n      cout << val << '\\\\n';\\n    }\\n  }\\n}\"",
    "tags": [
      "dp",
      "implementation",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1168",
    "index": "E",
    "title": "Xor Permutations",
    "statement": "Toad Mikhail has an array of $2^k$ integers $a_1, a_2, \\ldots, a_{2^k}$.\n\nFind two permutations $p$ and $q$ of integers $0, 1, \\ldots, 2^k-1$, such that $a_i$ is equal to $p_i \\oplus q_i$ for all possible $i$, or determine there are no such permutations. Here $\\oplus$ denotes the bitwise XOR operation.",
    "tutorial": "If xor of all elements of the array is not zero, then the answer is \"Fou\". Now let's assume that you have two permutations $p,q$ and when xored they are producing an array $a$. I will show that it is possible to change any two elements $a_i, a_j$ to elements $a_i \\oplus x, a_j \\oplus x$ with some transformation of the given permutations. Let's change $a_i, a_j$ to $a_i \\oplus x, a_j \\oplus x$. Let's find such $t$, that $a_i \\oplus q_i = p_t$. If $t$ is equal to $i$ or $i+1$, then you can make some swaps to \"fix\" the array, to make it satisfy $a_i = p_i \\oplus q_i$ for all $i$. Now you have: $p_t, q_t, a_t$ at position $t$ $p_i, q_i, a_i$ at position $i$ $p_j, q_j, a_j$ at position $j$ Let's make some swaps at these positions to transform it to: $p_i, q_j, a_t$ at position $t$ $p_t, q_i, a_i$ at position $i$ $p_j, q_t, a_j$ at position $j$ Now, after you make these transition, you will have $p_i \\oplus q_i = a_i$, and now you need to \"fix\" positions $t$ and $j$, and just process recursively. Lemma: this thing will end in $O(n)$ operations. ______________________________________________________________________________________ Proof: Let's assume that at some two moments you have $p_t$ coincided with some $p_t$ earlier, let's check the first that moment. For simplicity of the proof, let's assume that numbers are moving like that: $p_t, q_i, a_i$ at position $t$ $p_i, q_j, a_t$ at position $i$ $p_j, q_t, a_j$ at position $j$ (So $p_i$'s are constant, and $a_i$'s are changing now. Obviously, it is equivalent to the previous transformation) Now, assume, that you had numbers: $p_t, q_t, a_t$ at position $t$ $p_i, q_x, a_y$ at position $i$ (1) $p_j, q_y, a_j$ at position $j$ (2) and then, you will make one transformation, and everything will go to: $p_t, q_x, a_y$ at position $t$ $p_i, q_y, a_t$ at position $i$ $p_j, q_t, a_j$ at position $j$ After that, before you will be stuck into described earlier equality: $p_t, q_x, a_y$ at position $t$ $p_i, q_v, a_u$ at position $i$ $p_j, q_u, a_j$ at position $j$ And after swapping with $t$ $p_i, q_u, a_y$ at position $i$ (3) $p_j, q_x, a_j$ at position $j$ (4) Let's look at (1), (2) and (3), (4) From (1), (2), we can see $q_y = p_i \\oplus q_x \\oplus a_y \\oplus p_j \\oplus a_j$ From (3), (4), we can see $q_u = p_i \\oplus a_y \\oplus p_j \\oplus q_x \\oplus a_j$ So $q_y = q_u$, but $u \\neq y$, so it is a contradiction, because $q$ is a permutation.. _________________________________________________________________________________ Ok, using these operations it is pretty simple to get an arbitrary array. Just start with $0,0,\\ldots,0$ (two equal permutations). And then make $a_i = b_i, a_{i+1} = a_{i+1} \\oplus (a_i \\oplus b_i)$, at the end you will have one element rest and it will be good because initially xor was zero.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\n#ifdef ONPC\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nint main() {\\n#ifdef ONPC\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  int k;\\n  cin >> k;\\n  int n = (1 << k);\\n  int xr = 0;\\n  vector <int> b(n);\\n  for (int &x : b) {\\n    cin >> x;\\n    xr ^= x;\\n  }\\n  if (xr) {\\n    cout << \\\"Fou\\\\n\\\";\\n    return 0;\\n  } else {\\n    cout << \\\"Shi\\\\n\\\";\\n    vector <int> p(n), q(n), ind(n), a(n);\\n    for (int i = 0; i < n; i++) {\\n      p[i] = i;\\n      q[i] = i;\\n      ind[i] = i;\\n    }\\n    function<void(int, int)> fix = [&](int i, int j) { \\n      if (q[i] == (p[i] ^ a[i])) {\\n        return;\\n      } else if (q[i] == (p[i] ^ a[j])) {\\n        swap(q[i], q[j]);\\n        swap(p[i], p[j]);\\n        swap(ind[p[i]], ind[p[j]]);\\n      } else if (q[i] == (p[j] ^ a[i])) {\\n        swap(p[i], p[j]);\\n        swap(ind[p[i]], ind[p[j]]);\\n      } else if (q[i] == (p[j] ^ a[j])) {\\n        swap(q[i], q[j]);\\n      } else {\\n        int t = ind[a[i] ^ q[i]];\\n        swap(ind[p[t]], ind[p[i]]);\\n        swap(p[t], p[i]);\\n        swap(q[t], q[i]);\\n        swap(q[t], q[j]);\\n        swap(q[i], q[j]);\\n        fix(t, j);\\n      }\\n    };\\n    for (int i = 0; i + 1 < n; i++) {\\n      a[i + 1] ^= (a[i] ^ b[i]);\\n      a[i] = b[i];\\n      fix(i, i + 1);\\n    }\\n    for (int i = 0; i < n; i++) {\\n      cout << p[i] << ' ';\\n    }\\n    cout << '\\\\n';\\n    for (int i = 0; i < n; i++) {\\n      cout << q[i] << ' ';\\n    }\\n    cout << '\\\\n';\\n  }\\n}\"",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1169",
    "index": "A",
    "title": "Circle Metro",
    "statement": "The circle line of the Roflanpolis subway has $n$ stations.\n\nThere are two parallel routes in the subway. The first one visits stations in order $1 \\to 2 \\to \\ldots \\to n \\to 1 \\to 2 \\to \\ldots$ (so the next stop after station $x$ is equal to $(x+1)$ if $x < n$ and $1$ otherwise). The second route visits stations in order $n \\to (n-1) \\to \\ldots \\to 1 \\to n \\to (n-1) \\to \\ldots$ (so the next stop after station $x$ is equal to $(x-1)$ if $x>1$ and $n$ otherwise). All trains depart their stations simultaneously, and it takes exactly $1$ minute to arrive at the next station.\n\nTwo toads live in this city, their names are Daniel and Vlad.\n\nDaniel is currently in a train of the \\textbf{first} route at station $a$ and will exit the subway when his train reaches station $x$.\n\nCoincidentally, Vlad is currently in a train of the \\textbf{second} route at station $b$ and he will exit the subway when his train reaches station $y$.\n\nSurprisingly, all numbers $a,x,b,y$ are distinct.\n\nToad Ilya asks you to check if Daniel and Vlad will ever be at the same station at the same time during their journey. In other words, check if there is a moment when their trains stop at the same station. Note that this includes the moments when Daniel or Vlad enter or leave the subway.",
    "tutorial": "Straightforward simulation. Check the intended solutions: Simulation",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\n#ifdef ONPC\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nint main() {\\n#ifdef ONPC\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  int n, a, x, b, y;\\n  cin >> n >> a >> x >> b >> y;\\n  a--, x--, b--, y--;\\n  while (true) {\\n    if (a == b) {\\n      cout << \\\"YES\\\\n\\\";\\n      return 0;\\n    }\\n    if (a == x || b == y) {\\n      break;\\n    }\\n    a = (a + 1) % n;\\n    b = (b - 1 + n) % n;\\n  }\\n  cout << \\\"NO\\\\n\\\";\\n}\"",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1169",
    "index": "B",
    "title": "Pairs",
    "statement": "Toad Ivan has $m$ pairs of integers, each integer is between $1$ and $n$, inclusive. The pairs are $(a_1, b_1), (a_2, b_2), \\ldots, (a_m, b_m)$.\n\nHe asks you to check if there exist two integers $x$ and $y$ ($1 \\leq x < y \\leq n$) such that in each given pair at least one integer is equal to $x$ or $y$.",
    "tutorial": "One of $x,y$ is obviously one of $a_1, b_1$. For example, let's fix who is $x$ from the first pair. Then you need to check that there exists some $y$ such that all pairs that don't contain $x$, contain $y$. For this, you can remember in the array for each value how many pairs that don't contain $x$ contain this value, and then you need to check that in the array there exists some value that is equal to the number of pairs left.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\n#ifdef ONPC\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nint main() {\\n#ifdef ONPC\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  int n, m;\\n  cin >> n >> m;\\n  vector <pair <int, int> > pairs;\\n  for (int i = 0; i < m; i++) {\\n    int a, b;\\n    cin >> a >> b;\\n    a--, b--;\\n    pairs.emplace_back(a, b);\\n  }\\n  vector <int> values = {pairs[0].first, pairs[0].second};\\n  for (int x : values) {\\n    vector <int> val(n);\\n    int all = 0;\\n    for (auto c : pairs) {\\n      if (c.first != x && c.second != x) {\\n        val[c.first]++, val[c.second]++, all++;\\n      }\\n    }\\n    if (*max_element(val.begin(), val.end()) == all) {\\n      cout << \\\"YES\\\\n\\\";\\n      return 0;\\n    }\\n  }\\n  cout << \\\"NO\\\\n\\\";\\n}\"",
    "tags": [
      "graphs",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1172",
    "index": "A",
    "title": "Nauuo and Cards",
    "statement": "Nauuo is a girl who loves playing cards.\n\nOne day she was playing cards but found that the cards were mixed with some empty ones.\n\nThere are $n$ cards numbered from $1$ to $n$, and they were mixed with another $n$ empty cards. She piled up the $2n$ cards and drew $n$ of them. The $n$ cards in Nauuo's hands are given. The remaining $n$ cards in the pile are also given in the order from top to bottom.\n\nIn one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile.\n\nNauuo wants to make the $n$ numbered cards piled up in increasing order (the $i$-th card in the pile from top to bottom is the card $i$) as quickly as possible. Can you tell her the minimum number of operations?",
    "tutorial": "First, try to finish it without playing any empty cards. If that's not possible, the best choice is to play several empty cards in a row, then play from $1$ to $n$. For a card $i$, suppose that it is in the $p_i$-th position in the pile ($p_i=0$ if it is in the hand), you have to play at least $p_i - i + 1$ empty cards. So the answer will be $\\max\\{p_i-i+1+n\\}$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 200010;\n\nint n, a[N], b[N], p[N], ans;\n\nint main()\n{\n    int i, j;\n\n    scanf(\"%d\", &n);\n\n    for (i = 1; i <= n; ++i)\n    {\n        scanf(\"%d\", a + i);\n        p[a[i]] = 0;\n    }\n\n    for (i = 1; i <= n; ++i)\n    {\n        scanf(\"%d\", b + i);\n        p[b[i]] = i;\n    }\n\n    if (p[1])\n    {\n        for (i = 2; p[i] == p[1] + i - 1; ++i);\n        if (p[i - 1] == n)\n        {\n            for (j = i; j <= n && p[j] <= j - i; ++j);\n            if (j > n)\n            {\n                printf(\"%d\", n - i + 1);\n                return 0;\n            }\n        }\n    }\n\n    for (i = 1; i <= n; ++i) ans = max(ans, p[i] - i + 1 + n);\n\n    printf(\"%d\", ans);\n\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1172",
    "index": "B",
    "title": "Nauuo and Circle",
    "statement": "Nauuo is a girl who loves drawing circles.\n\nOne day she has drawn a circle and wanted to draw a tree on it.\n\nThe tree is a connected undirected graph consisting of $n$ nodes and $n-1$ edges. The nodes are numbered from $1$ to $n$.\n\nNauuo wants to draw a tree on the circle, the nodes of the tree should be in $n$ \\textbf{distinct} points on the circle, and the edges should be straight without crossing each other.\n\n\"Without crossing each other\" means that every two edges have no common point or the only common point is an endpoint of both edges.\n\nNauuo wants to draw the tree using a permutation of $n$ elements. A permutation of $n$ elements is a sequence of integers $p_1,p_2,\\ldots,p_n$ in which every integer from $1$ to $n$ appears exactly once.\n\nAfter a permutation is chosen Nauuo draws the $i$-th node in the $p_i$-th point on the circle, then draws the edges connecting the nodes.\n\nThe tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo $998244353$, can you help her?\n\nIt is obvious that whether a permutation is valid or not does not depend on which $n$ points on the circle are chosen.",
    "tutorial": "First, if we choose a node as the root, then each subtree must be in a continuous arc on the circle. Then, we can use DP to solve this problem. Let $f_u$ be the number of plans to draw the subtree of $u$, then $f_u=(|son(u)|+[u\\ne root])!\\prod\\limits_{v\\in son(u)}f_v$ - choose a position for each subtree and then $u$ itself, then draw the subtrees. However, instead of choosing the position of the root, we suppose the root is on a certain point on the circle, then rotate the circle, thus get the answer: $nf_{root}$. In fact, we don't have to write a DP, the answer is $n$ times the product of the factorial of each node's degree ($n\\prod\\limits_{i = 1}^ndegree[i]!$).",
    "code": "\n#include <iostream>\n#include <cstdio>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N = 200010;\nconst int mod = 998244353;\n\nint n, ans, d[N];\n\nint main()\n{\n    int i, u, v;\n\n    scanf(\"%d\", &n);\n    ans = n;\n\n    for (i = 1; i < n; ++i)\n    {\n        scanf(\"%d%d\", &u, &v);\n        ans = (ll) ans * (++d[u]) % mod * (++d[v]) % mod;\n    }\n\n    cout << ans;\n\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1172",
    "index": "C2",
    "title": "Nauuo and Pictures (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints.}\n\nNauuo is a girl who loves random picture websites.\n\nOne day she made a random picture website by herself which includes $n$ pictures.\n\nWhen Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal probability. The $i$-th picture has a non-negative weight $w_i$, and the probability of the $i$-th picture being displayed is $\\frac{w_i}{\\sum_{j=1}^nw_j}$. That is to say, the probability of a picture to be displayed is proportional to its weight.\n\nHowever, Nauuo discovered that some pictures she does not like were displayed too often.\n\nTo solve this problem, she came up with a great idea: when she saw a picture she likes, she would add $1$ to its weight; otherwise, she would subtract $1$ from its weight.\n\nNauuo will visit the website $m$ times. She wants to know the expected weight of each picture after all the $m$ visits modulo $998244353$. Can you help her?\n\nThe expected weight of the $i$-th picture can be denoted by $\\frac {q_i} {p_i}$ where $\\gcd(p_i,q_i)=1$, you need to print an integer $r_i$ satisfying $0\\le r_i<998244353$ and $r_i\\cdot p_i\\equiv q_i\\pmod{998244353}$. It can be proved that such $r_i$ exists and is unique.",
    "tutorial": "First, let's focus on a single picture with weight $w$ which Nauuo likes, so we only have to know the sum of the weights of the pictures Nauuo likes ($SA=\\sum\\limits_{i=1}^nw_i[a_i=1]$) and the sum of the disliked ones ($SB=\\sum\\limits_{i=1}^nw_i[a_i=0]$) instead of all the $n$ weights. Then, we can use DP to solve this problem. Let $f_w[i][j][k]$ be the expected weight of a picture Nauuo likes with weight $w$ after another $i$ visits since $SA=j$ and $SB=k$. Obviously, $f_w[0][j][k]=w$. The state transition: The next visit displays the picture we focus on. Probaility: $\\frac w{j+k}$. Lead to: $f_{w+1}[i-1][j+1][k]$. The next visit displays the picture we focus on. Probaility: $\\frac w{j+k}$. Lead to: $f_{w+1}[i-1][j+1][k]$. The next visit displays a picture Nauuo likes but is not the one we focus on. Probaility: $\\frac{j-w}{j+k}$. Lead to: $f_w[i-1][j+1][k]$. The next visit displays a picture Nauuo likes but is not the one we focus on. Probaility: $\\frac{j-w}{j+k}$. Lead to: $f_w[i-1][j+1][k]$. The next visit displays a picture Nauuo doesn't like. Probaility: $\\frac k{j+k}$. Lead to: $f_w[i-1][j][k-1]$. The next visit displays a picture Nauuo doesn't like. Probaility: $\\frac k{j+k}$. Lead to: $f_w[i-1][j][k-1]$. So, $f_w[i][j][k]=\\frac w{j+k}f_{w+1}[i-1][j+1][k]+\\frac{j-w}{j+k}f_w[i-1][j+1][k]+\\frac k{j+k}f_w[i-1][j][k-1]$. Let $g_w[i][j][k]$ be the expected weight of a picture Nauuo doesn't like with weight $w$ after another $i$ visits since $SA=j$ and $SB=k$. The state transition is similar. Note that $i,\\,j,\\,k,\\,m$ have some relation. In fact we can let $f'_w[i][j]$ be $f_w[m-i-j][SA+i][SB-j]$ ($SA$ and $SB$ are the initial ones here). But up to now, we can only solve the easy version. To solve the hard version, let's introduce a lemma: $f_w[i][j][k]=wf_1[i][j][k]$ Proof: Obviously, this is true when $i=0$. Then, suppose we have already proved $f_w[i-1][j][k]=wf_1[i-1][j][k]$. $\\begin{aligned}f_1[i][j][k]&=\\frac 1{j+k}f_2[i-1][j+1][k]+\\frac{j-1}{j+k}f_1[i-1][j+1][k]+\\frac k{j+k}f_1[i-1][j][k-1]\\\\&=\\frac2{j+k}f_1[i-1][j+1][k]+\\frac{j-1}{j+k}f_1[i-1][j+1][k]+\\frac k{j+k}f_1[i-1][j][k-1]\\\\&=\\frac{j+1}{j+k}f_1[i-1][j+1][k]+\\frac k{j+k}f_1[i-1][j][k-1]\\end{aligned}$ $\\begin{aligned}f_w[i][j][k]&=\\frac w{j+k}f_{w+1}[i-1][j+1][k]+\\frac{j-w}{j+k}f_w[i-1][j+1][k]+\\frac k{j+k}f_w[i-1][j][k-1]\\\\&=\\frac{w(w+1)}{j+k}f_1[i-1][j+1][k]+\\frac{w(j-w)}{j+k}f_1[i-1][j+1][k]+\\frac {wk}{j+k}f_1[i-1][j][k-1]\\\\&=\\frac{w(j+1)}{j+k}f_1[i-1][j+1][k]+\\frac {wk}{j+k}f_1[i-1][j][k-1]\\\\&=wf_1[i][j][k]\\end{aligned}$ Also, a brief but not so strict proof: the increment in each step is proportional to the expectation. So, we only have to calculate $f_1[i][j][k]$ ($f'_1[i][j]$). In conclusion: $f'_1[i][j]=1\\ (i+j=m)$ $f'_1[i][j]=\\frac{SA+i+1}{SA+SB+i-j}f'_1[i+1][j]+\\frac{SB-j}{SA+SB+i-j}f'_1[i][j+1]\\ (i+j<m)$ $g'_1[i][j]=1\\ (i+j=m)$ $g'_1[i][j]=\\frac{SA+i}{SA+SB+i-j}g'_1[i+1][j]+\\frac{SB-j-1}{SA+SB+i-j}g'_1[i][j+1]\\ (i+j<m)$ If $a_i=1$, the expected weight of the $i$-th picture is $w_if'_1[0][0]$, otherwise, the expected weight is $w_ig'_1[0][0]$. Last question: how to calculate the result modulo $998244353$? If you don't know how, please read the wiki to learn it. You can calculate and store all the $\\mathcal O(m)$ inverses at first, then you can get an $\\mathcal O(n+m^2+m\\log p)$ solution instead of $\\mathcal O(n+m^2\\log p)$ ($p=998244353$ here).",
    "code": "#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N = 200010;\nconst int M = 3010;\nconst int mod = 998244353;\n\nint qpow(int x, int y) //calculate the modular multiplicative inverse\n{\n\tint out = 1;\n\twhile (y)\n\t{\n\t\tif (y & 1) out = (ll) out * x % mod;\n\t\tx = (ll) x * x % mod;\n\t\ty >>= 1;\n\t}\n\treturn out;\n}\n\nint n, m, a[N], w[N], f[M][M], g[M][M], inv[M << 1], sum[3];\n\nint main()\n{\n\tint i,j;\n\t\n\tscanf(\"%d%d\", &n, &m);\n\t\n\tfor (i = 1; i <= n; ++i) scanf(\"%d\", a + i);\n\t\n\tfor (i = 1; i <= n; ++i)\n\t{\n\t\tscanf(\"%d\", w + i);\n\t\tsum[a[i]] += w[i];\n\t\tsum[2] += w[i];\n\t}\n\t\n\tfor (i = max(0, m - sum[0]); i <= 2 * m; ++i) inv[i] = qpow(sum[2] + i - m, mod - 2);\n\t\n\tfor (i = m; i >= 0; --i)\n\t{\n\t\tf[i][m - i] = g[i][m - i] = 1;\n\t\tfor (j = min(m - i - 1, sum[0]); j >= 0; --j)\n\t\t{\n\t\t\tf[i][j] = ((ll) (sum[1] + i + 1) * f[i + 1][j] + (ll) (sum[0] - j) * f[i][j + 1]) % mod * inv[i - j + m] % mod;\n\t\t\tg[i][j] = ((ll) (sum[1] + i) * g[i + 1][j] + (ll) (sum[0] - j - 1) * g[i][j + 1]) % mod * inv[i - j + m] % mod;\n\t\t}\n\t}\n\t\n\tfor (i = 1; i <= n; ++i) printf(\"%d\\n\", int((ll) w[i] * (a[i] ? f[0][0] : g[0][0]) % mod));\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1172",
    "index": "D",
    "title": "Nauuo and Portals",
    "statement": "Nauuo is a girl who loves playing games related to portals.\n\nOne day she was playing a game as follows.\n\nIn an $n\\times n$ grid, the rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. We denote a cell on the intersection of the $r$-th row and $c$-th column as $(r,c)$.\n\nA portal is \\textbf{a pair of} doors. You can travel from one of them to another without changing your direction. More formally, if you walk into a cell with a door, you will teleport to the cell with the other door of the same portal and then walk into the next cell facing the original direction. There \\textbf{can not} be more than one doors in a single cell.\n\nThe \"next cell\" is the nearest cell in the direction you are facing. For example, if you are facing bottom, the next cell of $(2,5)$ is $(3,5)$.\n\nIf you walk into a cell without a door, you must walk into the next cell after that without changing the direction. If the next cell does not exist, you must exit the grid.\n\nYou have to set some (possibly zero) portals in the grid, so that if you walk into $(i,1)$ facing right, you will eventually exit the grid from $(r_i,n)$, if you walk into $(1, i)$ facing bottom, you will exit the grid from $(n,c_i)$.\n\nIt is guaranteed that both $r_{1..n}$ and $c_{1..n}$ are \\textbf{permutations} of $n$ elements. A permutation of $n$ elements is a sequence of numbers $p_1,p_2,\\ldots,p_n$ in which every integer from $1$ to $n$ appears exactly once.\n\nShe got confused while playing the game, can you help her to find a solution?",
    "tutorial": "Consider this problem: the person in $(i,1)$ facing right is numbered $a_i$, the person in $(1,i)$ facing bottom is numbered $b_i$. The person numbered $p_i$ has to exit the grid from $(i,n)$, the person numbered $q_i$ has to exit the grid from $(n,i)$. The original problem can be easily transferred to this problem. And now let's transfer it into an $(n-1)\\times (n-1)$ subproblem by satisfying the requirement of the first row and the first column. If $a_1=p_1$ and $b_1=q_1$, you can simply do nothing and get an $(n-1)\\times (n-1)$ subproblem. Otherwise, you can set a portal consisting of two doors in $(x,1)$ and $(1,y)$ where $a_x=p_1$ and $b_y=q_1$. Swap $a_1$ and $a_x$, $b_1$ and $b_y$, then you will get an $(n-1)\\times(n-1)$ subproblem. Then, you can solve the problem until it changes into a $1\\times1$ one. This problem can be solved in $\\mathcal O(n)$, but the checker needs $\\mathcal O(n^2)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 1010;\n\nstruct Portal\n{\n\tint x, y, p, q;\n\tPortal(int _x, int _y, int _p, int _q): x(_x), y(_y), p(_p), q(_q) {}\n};\nvector<Portal> ans;\nint n, a[N], b[N], c[N], d[N], ra[N], rb[N], rc[N], rd[N];\n\nint main()\n{\n\tint i;\n\t\n\tscanf(\"%d\", &n);\n\t\n\tfor (i = 1; i <= n; ++i)\n\t{\n\t\tscanf(\"%d\", b + i);\n\t\trb[b[i]] = i;\n\t}\n\tfor (i = 1; i <= n; ++i)\n\t{\n\t\tscanf(\"%d\", a + i);\n\t\tra[a[i]] = i;\n\t}\n\tfor (i = 1; i <= n; ++i) c[i] = d[i] = rc[i] = rd[i] = i;\n\t\n\tfor (i = 1; i < n; ++i)\n\t{\n\t\tif (c[i] == ra[i] && d[i] == rb[i]) continue;\n\t\tans.push_back(Portal(i, rc[ra[i]], rd[rb[i]], i));\n\t\tint t1 = c[i];\n\t\tint t2 = d[i];\n\t\tswap(c[i], c[rc[ra[i]]]);\n\t\tswap(d[i], d[rd[rb[i]]]);\n\t\tswap(rc[ra[i]], rc[t1]);\n\t\tswap(rd[rb[i]], rd[t2]);\n\t}\n\t\n\tprintf(\"%d\\n\", ans.size());\n\tfor (auto k : ans) printf(\"%d %d %d %d\\n\", k.x, k.y, k.p, k.q);\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1172",
    "index": "E",
    "title": "Nauuo and ODT",
    "statement": "Nauuo is a girl who loves traveling.\n\nOne day she went to a tree, Old Driver Tree, literally, a tree with an old driver on it.\n\nThe tree is a connected graph consisting of $n$ nodes and $n-1$ edges. Each node has a color, and Nauuo will visit the ODT through a simple path on the tree in the old driver's car.\n\nNauuo wants to visit see more different colors in her journey, but she doesn't know which simple path she will be traveling on. So, she wants to calculate the sum of the numbers of different colors on all different paths. Can you help her?\n\nWhat's more, the ODT is being redecorated, so there will be $m$ modifications, each modification will change a single node's color. Nauuo wants to know the answer after each modification too.\n\nNote that in this problem, we consider the simple path from $u$ to $v$ and the simple path from $v$ to $u$ as two different simple paths if and only if $u\\ne v$.",
    "tutorial": "For each color, we can try to maintain the number of simple paths that do not contain such color. If we can maintain such information, we can easily calculate the number of simple paths that contain a certain color, thus get the answer. For each color, we delete all nodes that belong to such color, thus splitting the tree into some clusters (here we define a \"cluster\" as a connected subgraph of the original tree). By maintaining $\\sum\\text{cluster size}^2$, we can get the number of simple paths that do not contain such color. For each color we try to maintain the same information, add them together, and get the answer. So now the problem is: a white tree reverse the color of a node ( white <-> black ) reverse the color of a node ( white <-> black ) output $\\sum\\text{cluster size}^2$ output $\\sum\\text{cluster size}^2$ This problem can be solved by many data structures like top tree, link/cut tree or heavy path decomposition. Let's use the link/cut tree for example. You can maintain the size of each subtree and the sum of $\\text{size}^2$ of each node's sons. Link/cut one node with its father (choose a node as the root and make the tree a rooted-tree first) when its color changes. In this way, the real clusters are the ones that are still connected after deleting the top node of a cluster in the link/cut tree. Update $\\sum\\text{cluster size}^2$ while linking/cutting. link: cut:",
    "code": "#include <algorithm>\n#include <cctype>\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N = 400010;\n\nstruct Node\n{\n    int fa, ch[2], siz, sizi;\n    ll siz2i;\n    ll siz2() { return (ll) siz * siz; }\n} t[N];\n\nbool nroot(int x);\nvoid rotate(int x);\nvoid Splay(int x);\nvoid access(int x);\nint findroot(int x);\nvoid link(int x);\nvoid cut(int x);\nvoid pushup(int x);\n\nvoid add(int u, int v);\nvoid dfs(int u);\n\nint head[N], nxt[N << 1], to[N << 1], cnt;\nint n, m, c[N], f[N];\nll ans, delta[N];\nbool bw[N];\nvector<int> mod[N][2];\n\nint main()\n{\n    int i, j, u, v;\n    ll last;\n\n    scanf(\"%d%d\", &n, &m);\n\n    for (i = 1; i <= n; ++i)\n    {\n        scanf(\"%d\", c + i);\n        mod[c[i]][0].push_back(i);\n        mod[c[i]][1].push_back(0);\n    }\n\n    for (i = 1; i <= n + 1; ++i) t[i].siz = 1;\n\n    for (i = 1; i < n; ++i)\n    {\n        scanf(\"%d%d\", &u, &v);\n        add(u, v);\n        add(v, u);\n    }\n\n    for (i = 1; i <= m; ++i)\n    {\n        scanf(\"%d%d\", &u, &v);\n        mod[c[u]][0].push_back(u);\n        mod[c[u]][1].push_back(i);\n        c[u] = v;\n        mod[v][0].push_back(u);\n        mod[v][1].push_back(i);\n    }\n\n    f[1] = n + 1;\n    dfs(1);\n\n    for (i = 1; i <= n; ++i) link(i);\n\n    for (i = 1; i <= n; ++i)\n    {\n        if (!mod[i][0].size())\n        {\n            delta[0] += (ll)n * n;\n            continue;\n        }\n        if (mod[i][1][0])\n        {\n            delta[0] += (ll)n * n;\n            last = (ll)n * n;\n        } else\n            last = 0;\n        for (j = 0; j < mod[i][0].size(); ++j)\n        {\n            u = mod[i][0][j];\n            if (bw[u] ^= 1)\n                cut(u);\n            else\n                link(u);\n            if (j == mod[i][0].size() - 1 || mod[i][1][j + 1] != mod[i][1][j])\n            {\n                delta[mod[i][1][j]] += ans - last;\n                last = ans;\n            }\n        }\n        for (j = mod[i][0].size() - 1; ~j; --j)\n        {\n            u = mod[i][0][j];\n            if (bw[u] ^= 1)\n                cut(u);\n            else\n                link(u);\n        }\n    }\n\n    ans = (ll) n * n * n;\n    for (i = 0; i <= m; ++i)\n    {\n        ans -= delta[i];\n        printf(\"%I64d \", ans);\n    }\n\n    return 0;\n}\n\nbool nroot(int x) { return x == t[t[x].fa].ch[0] || x == t[t[x].fa].ch[1]; }\n\nvoid rotate(int x)\n{\n    int y = t[x].fa;\n    int z = t[y].fa;\n    int k = x == t[y].ch[1];\n    if (nroot(y)) t[z].ch[y == t[z].ch[1]] = x;\n    t[x].fa = z;\n    t[y].ch[k] = t[x].ch[k ^ 1];\n    t[t[x].ch[k ^ 1]].fa = y;\n    t[x].ch[k ^ 1] = y;\n    t[y].fa = x;\n    pushup(y);\n    pushup(x);\n}\n\nvoid Splay(int x)\n{\n    while (nroot(x))\n    {\n        int y = t[x].fa;\n        int z = t[y].fa;\n        if (nroot(y)) (x == t[y].ch[1]) ^ (y == t[z].ch[1]) ? rotate(x) : rotate(y);\n        rotate(x);\n    }\n}\n\nvoid access(int x)\n{\n    for (int y = 0; x; x = t[y = x].fa)\n    {\n        Splay(x);\n        t[x].sizi += t[t[x].ch[1]].siz;\n        t[x].sizi -= t[y].siz;\n        t[x].siz2i += t[t[x].ch[1]].siz2();\n        t[x].siz2i -= t[y].siz2();\n        t[x].ch[1] = y;\n        pushup(x);\n    }\n}\n\nint findroot(int x)\n{\n    access(x);\n    Splay(x);\n    while (t[x].ch[0]) x = t[x].ch[0];\n    Splay(x);\n    return x;\n}\n\nvoid link(int x)\n{\n    int y = f[x];\n    Splay(x);\n    ans -= t[x].siz2i + t[t[x].ch[1]].siz2();\n    int z = findroot(y);\n    access(x);\n    Splay(z);\n    ans -= t[t[z].ch[1]].siz2();\n    t[x].fa = y;\n    Splay(y);\n    t[y].sizi += t[x].siz;\n    t[y].siz2i += t[x].siz2();\n    pushup(y);\n    access(x);\n    Splay(z);\n    ans += t[t[z].ch[1]].siz2();\n}\n\nvoid cut(int x)\n{\n    int y = f[x];\n    access(x);\n    ans += t[x].siz2i;\n    int z = findroot(y);\n    access(x);\n    Splay(z);\n    ans -= t[t[z].ch[1]].siz2();\n    Splay(x);\n    t[x].ch[0] = t[t[x].ch[0]].fa = 0;\n    pushup(x);\n    Splay(z);\n    ans += t[t[z].ch[1]].siz2();\n}\n\nvoid pushup(int x)\n{\n    t[x].siz = t[t[x].ch[0]].siz + t[t[x].ch[1]].siz + t[x].sizi + 1;\n}\n\nvoid add(int u, int v)\n{\n    nxt[++cnt] = head[u];\n    head[u] = cnt;\n    to[cnt] = v;\n}\n\nvoid dfs(int u)\n{\n    int i, v;\n    for (i = head[u]; i; i = nxt[i])\n    {\n        v = to[i];\n        if (v != f[u])\n        {\n            f[v] = u;\n            dfs(v);\n        }\n    }\n}",
    "tags": [
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1172",
    "index": "F",
    "title": "Nauuo and Bug",
    "statement": "Nauuo is a girl who loves coding.\n\nOne day she was solving a problem which requires to calculate a sum of some numbers modulo $p$.\n\nShe wrote the following code and got the verdict \"Wrong answer\".\n\nShe soon discovered the bug — the ModAdd function only worked for numbers in the range $[0,p)$, but the numbers in the problem may be out of the range. She was curious about the wrong function, so she wanted to know the result of it.\n\nHowever, the original code worked too slow, so she asked you to help her.\n\nYou are given an array $a_1,a_2,\\ldots,a_n$ and a number $p$. Nauuo will make $m$ queries, in each query, you are given $l$ and $r$, and you have to calculate the results of Sum(a,l,r,p). You can see the definition of the Sum function in the pseudocode above.\n\nNote that the integers won't overflow in the code above.",
    "tutorial": "At first, let's solve this problem in $\\mathcal{O}(n\\sqrt{n \\log n})$. Let's split our array into blocks by $B$ integers, and let's find a function, $f(x) =$ which value you will get at the end of the current block if you will start with $x$. With simple induction, you can prove that this function is a piece-wise linear, and it has $\\mathcal{O}(B)$ segments, so you can build it iteratively in $\\mathcal{O}(B^2)$ time for each block, so the preprocessing took $\\mathcal{O}(nB)$. And to answer the query, you can keep the current value of $x$ and then find with binary search by that piece-wise linear function the $f(x)$ for the current block. With a good choice of $B$, this solution will work in $\\mathcal{O}(n\\sqrt{n \\log n})$. Ok, but then how to solve it in $\\mathcal{O}(n \\log + q \\log^2)$? Lemma: each segment of this piece-wise linear function has length at least $p$. You can prove it with simple induction. And then, with this lemma, it is possible by two functions $f(x)$ of size $n$ and $g(x)$ of size $m$ find the new function $h(x) = g(f(x))$, in the $\\mathcal{O}(n + m)$, you can do it with two pointers, similar to the previous iterative method, but adding a several points to the function each time, best way to understand it is to check the indendent solution :) We had prepared a problem similar to 1174F - Ehab and the Big Finale before that round, so we needed to prepare new problems in four days. It was in such a hurry that there are some imperfections in our round. Please accept our sincere apology.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N = 1000005;\nconst ll inf = (ll)1e16;\nint n, m, P, a[N];\nll sum[N];\nvector<ll> func[N << 2];\n\nvector<ll> merge(int l, int r, int mid, const vector<ll> &f, const vector<ll> &g) {\n\tll suml = sum[mid] - sum[l - 1], sumr = sum[r] - sum[mid];\n\tvector<ll> ret(f.size() + g.size() - 1, inf);\n\tfor (int i = 0, j = 0; i < (int)f.size(); ++i) {\n\t\tll xl = f[i], xr = (i + 1 == (int)f.size() ? inf : f[i + 1] - 1), yl = xl + suml - (ll)i * P, yr = xr + suml - (ll)i * P;\n\t\twhile (j > 0 && g[j] > yl) --j;\n\t\twhile (j < (int)g.size() && (j == 0 || g[j] <= yl)) ++j;\n\t\t--j;\n\t\tfor (; j < (int)g.size() && g[j] <= yr; ++j)\n\t\t\tret[i + j] = min(ret[i + j], max(xl, g[j] - suml + (ll)i * P));\n\t}\n\tret[0] = -inf;\n\treturn ret;\n}\nvoid build(int u, int l, int r) {\n\tif (l == r) {\n\t\tfunc[u].push_back(-inf);\n\t\tfunc[u].push_back(P - a[l]);\n\t\treturn;\n\t}\n\tint mid = l + r >> 1;\n\tbuild(u << 1, l, mid);\n\tbuild(u << 1 | 1, mid + 1, r);\n\tfunc[u] = merge(l, r, mid, func[u << 1], func[u << 1 | 1]);\n}\nll query(int u, int l, int r, int ql, int qr, ll now) {\n\tif (l >= ql && r <= qr)\n\t\treturn now + sum[r] - sum[l - 1] - (ll)P * (upper_bound(func[u].begin(), func[u].end(), now) - func[u].begin() - 1);\n\tint mid = l + r >> 1;\n\tif (qr <= mid)\n\t\treturn query(u << 1, l, mid, ql, qr, now);\n\tif (ql > mid)\n\t\treturn query(u << 1 | 1, mid + 1, r, ql, qr, now);\n\treturn query(u << 1 | 1, mid + 1, r, ql, qr, query(u << 1, l, mid, ql, qr, now));\n}\n\nint main() {\n\tscanf(\"%d%d%d\", &n, &m, &P);\n\tfor (int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", a + i), sum[i] = sum[i - 1] + a[i];\n\tbuild(1, 1, n);\n\tfor (int l, r; m--;) {\n\t\tscanf(\"%d%d\", &l, &r);\n\t\tprintf(\"%I64d\\n\", query(1, 1, n, l, r, 0));\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1173",
    "index": "A",
    "title": "Nauuo and Votes",
    "statement": "Nauuo is a girl who loves writing comments.\n\nOne day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes.\n\nIt's known that there were $x$ persons who would upvote, $y$ persons who would downvote, and there were also another $z$ persons who would vote, but you don't know whether they would upvote or downvote. Note that each of the $x+y+z$ people would vote exactly one time.\n\nThere are three different results: if there are more people upvote than downvote, the result will be \"+\"; if there are more people downvote than upvote, the result will be \"-\"; otherwise the result will be \"0\".\n\nBecause of the $z$ unknown persons, the result may be uncertain (i.e. there are more than one possible results). More formally, the result is uncertain if and only if there exist two different situations of how the $z$ persons vote, that the results are different in the two situations.\n\nTell Nauuo the result or report that the result is uncertain.",
    "tutorial": "Consider the two edge cases: all the $z$ persons upvote / all the $z$ persons downvote. If the results are the same in these two cases, it is the answer. Otherwise, the result is uncertain.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst char result[4] = {'+', '-', '0', '?'};\n\nint solve(int x, int y)\n{\n\treturn x == y ? 2 : x < y;\n}\n\nint main()\n{\n\tint x, y, z;\n\t\n\tcin >> x >> y >> z;\n\t\n\tcout << result[solve(x + z, y) == solve(x, y + z) ? solve(x, y) : 3];\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1173",
    "index": "B",
    "title": "Nauuo and Chess",
    "statement": "Nauuo is a girl who loves playing chess.\n\nOne day she invented a game by herself which needs $n$ chess pieces to play on a $m\\times m$ chessboard. The rows and columns are numbered from $1$ to $m$. We denote a cell on the intersection of the $r$-th row and $c$-th column as $(r,c)$.\n\nThe game's goal is to place $n$ chess pieces numbered from $1$ to $n$ on the chessboard, the $i$-th piece lies on $(r_i,\\,c_i)$, while the following rule is satisfied: for all pairs of pieces $i$ and $j$, $|r_i-r_j|+|c_i-c_j|\\ge|i-j|$. Here $|x|$ means the absolute value of $x$.\n\nHowever, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.\n\nShe wants to find the \\textbf{smallest} chessboard on which she can put $n$ pieces according to the rules.\n\nShe also wonders how to place the pieces on such a chessboard. Can you help her?",
    "tutorial": "$m\\ge\\left\\lfloor\\frac n 2\\right\\rfloor+1$ Consider the chess pieces $1$ and $n$. $\\because\\begin{cases}|r_1-r_n|+|c_1-c_n|\\ge n-1\\\\|r_1-r_n|\\le m-1\\\\|c_1-c_n|\\le m-1\\end{cases}$ $\\therefore m-1+m-1\\ge n-1$ $\\therefore m\\ge\\frac{n+1}2$ $\\because m\\text{ is an integer}$ $\\therefore m\\ge\\left\\lfloor\\frac n 2\\right\\rfloor+1$ $m$ can be $\\left\\lfloor\\frac n 2\\right\\rfloor+1$ If we put the $i$-th piece on $(r_i,c_i)$ satisfying $r_i+c_i=i+1$, it is a feasible plan, because $|r_i-r_j|+|c_i-c_j|\\ge|r_i+c_i-r_j-c_j|$.",
    "code": "#include <cstdio>\n\nusing namespace std;\n\nint main()\n{\n    int n, i, ans;\n\n    scanf(\"%d\", &n);\n    ans = n / 2 + 1;\n\n    printf(\"%d\", ans);\n\n    for (i = 1; i <= ans; ++i) printf(\"\\n%d 1\", i);\n    for (i = 2; i <= n - ans + 1; ++i) printf(\"\\n%d %d\", ans, i);\n\n    return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1174",
    "index": "A",
    "title": "Ehab Fails to Be Thanos",
    "statement": "You're given an array $a$ of length $2n$. Is it possible to reorder it in such way so that the sum of the first $n$ elements \\textbf{isn't} equal to the sum of the last $n$ elements?",
    "tutorial": "If all elements in the array are equal, there's no solution. Otherwise, sort the array. The sum of the second half will indeed be greater than that of the first half. Another solution is to see if they already have different sums. If they do, print the array as it is. Otherwise, find any pair of different elements from different halves and swap them.",
    "code": "\"#include <iostream>\\n#include <algorithm>\\nusing namespace std;\\nint arr[2005];\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=0;i<2*n;i++)\\n\\tscanf(\\\"%d\\\",&arr[i]);\\n\\tsort(arr,arr+2*n);\\n\\tif (arr[0]==arr[2*n-1])\\n\\t{\\n\\t\\tprintf(\\\"-1\\\");\\n\\t\\treturn 0;\\n\\t}\\n\\tfor (int i=0;i<2*n;i++)\\n\\tprintf(\\\"%d \\\",arr[i]);\\n}\"",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1174",
    "index": "B",
    "title": "Ehab Is an Odd Person",
    "statement": "You're given an array $a$ of length $n$. You can perform the following operation on it as many times as you want:\n\n- Pick two integers $i$ and $j$ $(1 \\le i,j \\le n)$ such that \\textbf{$a_i+a_j$ is odd}, then swap $a_i$ and $a_j$.\n\nWhat is lexicographically the smallest array you can obtain?\n\nAn array $x$ is lexicographically smaller than an array $y$ if there exists an index $i$ such that $x_i<y_i$, and $x_j=y_j$ for all $1 \\le j < i$. Less formally, at the first index $i$ in which they differ, $x_i<y_i$",
    "tutorial": "Notice that you can only swap 2 elements if they have different parities. If all elements in the array have the same parity, you can't do any swaps, and the answer will just be like the input. Otherwise, let's prove you can actually swap any pair of elements. Assume you want to swap 2 elements, $a$ and $b$, and they have the same parity. There must be a third element $c$ that has a different parity. Without loss of generality, assume the array is $[a,b,c]$. You'll do the following swaps: Swap $a$ and $c$: $[c,b,a]$. Swap $b$ and $c$: $[b,c,a]$. Swap $a$ and $c$: $[b,a,c]$. In other words, you'll use $c$ as an intermediate element to swap $a$ and $b$, and it'll return to its original position afterwards! Since you can swap any pair of elements, you can always sort the array, which is the lexicographically smallest permutation. Time complexity: $O(nlog(n))$.",
    "code": "\"#include <iostream>\\n#include <algorithm>\\nusing namespace std;\\nbool ex[2];\\nint arr[100005];\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=0;i<n;i++)\\n\\t{\\n\\t\\tscanf(\\\"%d\\\",&arr[i]);\\n\\t\\tex[arr[i]%2]=1;\\n\\t}\\n\\tif (ex[0] && ex[1])\\n\\tsort(arr,arr+n);\\n\\tfor (int i=0;i<n;i++)\\n\\tprintf(\\\"%d \\\",arr[i]);\\n}\"",
    "tags": [
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1174",
    "index": "C",
    "title": "Ehab and a Special Coloring Problem",
    "statement": "You're given an integer $n$. For every integer $i$ from $2$ to $n$, assign a positive integer $a_i$ such that the following conditions hold:\n\n- For any pair of integers $(i,j)$, if $i$ and $j$ are coprime, $a_i \\neq a_j$.\n- The maximal value of all $a_i$ should be minimized (that is, as small as possible).\n\nA pair of integers is called coprime if their greatest common divisor is $1$.",
    "tutorial": "Let's call the maximum value in the array $max$. Let the number of primes less than or equal to $n$ be called $p$. Then, $max \\ge p$. That's true because a distinct number must be assigned to each prime, since all primes are coprime to each other. Now if we can construct an answer wherein $max=p$, it'll be optimal. Let's first assign a distinct number to each prime. Then, assign to every composite number the same number as any of its prime divisors. This works because for any pair of numbers $(i,j)$, $i$ is given the same number of a divisor and so is $j$, so if they're coprime (don't share a divisor), they can't be given the same number! Time complexity: $O(nlog(n))$.",
    "code": "\"#include <iostream>\\nusing namespace std;\\nint ans[100005];\\nint main()\\n{\\n\\tint n,c=0;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=2;i<=n;i++)\\n\\t{\\n\\t\\tif (!ans[i])\\n\\t\\t{\\n\\t\\t\\tans[i]=++c;\\n\\t\\t\\tfor (int j=i;j<=n;j+=i)\\n\\t\\t\\tans[j]=ans[i];\\n\\t\\t}\\n\\t\\tprintf(\\\"%d \\\",ans[i]);\\n\\t}\\n}\"",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1174",
    "index": "D",
    "title": "Ehab and the Expected XOR Problem",
    "statement": "Given two integers $n$ and $x$, construct an array that satisfies the following conditions:\n\n- for any element $a_i$ in the array, $1 \\le a_i<2^n$;\n- there is no \\textbf{non-empty} subsegment with bitwise XOR equal to $0$ or $x$,\n- its length $l$ should be maximized.\n\nA sequence $b$ is a subsegment of a sequence $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "The main idea is to build the prefix-xor of the array, not the array itself, then build the array from it. Let the prefix-xor array be called $b$. Now, $a_l \\oplus a_{l+1} \\dots \\oplus a_r=b_{l-1} \\oplus b_{r}$. Thus, the problem becomes: construct an array such that no pair of numbers has bitwise-xor sum equal to 0 or $x$, and its length should be maximal. Notice that \"no pair of numbers has bitwise-xor sum equal to 0\" simply means \"you can't use the same number twice\". If $x \\ge 2^n$, no pair of numbers less than $2^n$ will have bitwise-xor sum equal to $x$, so you can just use all the numbers from 1 to $2^n-1$ in any order. Otherwise, you can think of the numbers forming pairs, where each pair consists of 2 numbers with bitwise-xor sum equal to $x$. From any pair, if you add one number to the array, you can't add the other. However, the pairs are independent from each other: your choice in one pair doesn't affect any other pair. Thus, you can just choose either number in any pair and add them in any order you want. After you construct $b$, you can construct $a$ using the formula: $a_i=b_i \\oplus b_{i-1}$. Time complexity: $O(2^n)$.",
    "code": "\"#include <iostream>\\n#include <vector>\\nusing namespace std;\\nbool ex[(1<<18)];\\nint main()\\n{\\n\\tint n,x;\\n\\tscanf(\\\"%d%d\\\",&n,&x);\\n\\tex[0]=1;\\n\\tvector<int> v({0});\\n\\tfor (int i=1;i<(1<<n);i++)\\n\\t{\\n\\t\\tif (ex[i^x])\\n\\t\\tcontinue;\\n\\t\\tv.push_back(i);\\n\\t\\tex[i]=1;\\n\\t}\\n\\tprintf(\\\"%d\\\\n\\\",v.size()-1);\\n\\tfor (int i=1;i<v.size();i++)\\n\\tprintf(\\\"%d \\\",(v[i]^v[i-1]));\\n}\"",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1174",
    "index": "E",
    "title": "Ehab and the Expected GCD Problem",
    "statement": "Let's define a function $f(p)$ on a permutation $p$ as follows. Let $g_i$ be the greatest common divisor (GCD) of elements $p_1$, $p_2$, ..., $p_i$ (in other words, it is the GCD of the prefix of length $i$). Then $f(p)$ is the number of \\textbf{distinct} elements among $g_1$, $g_2$, ..., $g_n$.\n\nLet $f_{max}(n)$ be the maximum value of $f(p)$ among all permutations $p$ of integers $1$, $2$, ..., $n$.\n\nGiven an integers $n$, count the number of permutations $p$ of integers $1$, $2$, ..., $n$, such that $f(p)$ is equal to $f_{max}(n)$. Since the answer may be large, print the remainder of its division by $1000\\,000\\,007 = 10^9 + 7$.",
    "tutorial": "Let's call the permutations from the statement good. For starters, we'll try to find some characteristics of good permutations. Let's call the first element in a good permutation $s$. Then, $s$ must have the maximal possible number of prime divisors. Also, every time the $gcd$ changes as you move along prefixes, you must drop only one prime divisor from it. That way, we guarantee we have as many distinct $gcd$s as possible. Now, there are 2 important observations concerning $s$: Observation #1: $s=2^x*3^y$ for some $x$ and $y$. In other words, only $2$ and $3$ can divide $s$. That's because if $s$ has some prime divisor $p$, you can divide it by $p$ and multiply it by $4$. That way, you'll have more prime divisors. Observation #2: $y \\le 1$. That's because if $s=2^x*3^y$, and $y \\ge 2$, you can instead replace it with $2^{x+3}*3^{y-2}$ (divide it by $9$ and multiply it by $8$), and you'll have more prime divisors. Now, we can create $dp[i][x][y]$, the number of ways to fill a good permutation up to index $i$ such that its $gcd$ is $2^x*3^y$. Let $f(x,y)=\\lfloor \\frac{n}{2^x*3^y} \\rfloor$. It means the number of multiples of $2^x*3^y$ less than or equal to $n$. Here are the transitions: If your permutation is filled until index $i$ and its $gcd$ is $2^x*3^y$, you can do one of the following $3$ things upon choosing $p_{i+1}$: Add a multiple of $2^x*3^y$. That way, the $gcd$ won't change. There are $f(x,y)$ numbers you can add, but you already added $i$ of them, so: $dp[i+1][x][y]=dp[i+1][x][y]+dp[i][x][y]*(f(x,y)-i)$. Add a multiple of $2^x*3^y$. That way, the $gcd$ won't change. There are $f(x,y)$ numbers you can add, but you already added $i$ of them, so: $dp[i+1][x][y]=dp[i+1][x][y]+dp[i][x][y]*(f(x,y)-i)$. Reduce $x$ by $1$. To do that, you can add a multiple of $2^{x-1}*3^y$ that isn't a multiple of $2^x*3^y$, so: $dp[i+1][x-1][y]=dp[i+1][x-1][y]+dp[i][x][y]*(f(x-1,y)-f(x,y))$. Reduce $x$ by $1$. To do that, you can add a multiple of $2^{x-1}*3^y$ that isn't a multiple of $2^x*3^y$, so: $dp[i+1][x-1][y]=dp[i+1][x-1][y]+dp[i][x][y]*(f(x-1,y)-f(x,y))$. Reduce $y$ by $1$. To do that, you can add a multiple of $2^x*3^{y-1}$ that isn't a multiple of $2^x*3^y$, so: $dp[i+1][x][y-1]=dp[i+1][x][y-1]+dp[i][x][y]*(f(x,y-1)-f(x,y))$. Reduce $y$ by $1$. To do that, you can add a multiple of $2^x*3^{y-1}$ that isn't a multiple of $2^x*3^y$, so: $dp[i+1][x][y-1]=dp[i+1][x][y-1]+dp[i][x][y]*(f(x,y-1)-f(x,y))$. As for the base case, let $x=\\lfloor log_2(n) \\rfloor$. You can always start with $2^x$, so $dp[1][x][0]=1$. Also, if $2^{x-1}*3 \\le n$, you can start with it, so $dp[1][x-1][1]=1$. The answer is $dp[n][0][0]$. Time complexity: $O(nlog(n))$.",
    "code": "\"#include <iostream>\\nusing namespace std;\\n#define mod 1000000007\\nint n,dp[1000005][21][2];\\nint f(int x,int y)\\n{\\n\\tint tmp=(1<<x);\\n\\tif (y)\\n\\ttmp*=3;\\n\\treturn n/tmp;\\n}\\nint main()\\n{\\n\\tscanf(\\\"%d\\\",&n);\\n\\tint p=0;\\n\\twhile ((1<<p)<=n)\\n\\tp++;\\n\\tp--;\\n\\tdp[1][p][0]=1;\\n\\tif ((1<<(p-1))*3<=n)\\n\\tdp[1][p-1][1]=1;\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tfor (int x=0;x<=p;x++)\\n\\t\\t{\\n\\t\\t\\tfor (int y=0;y<=1;y++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tdp[i+1][x][y]=(dp[i+1][x][y]+1LL*dp[i][x][y]*(f(x,y)-i))%mod;\\n\\t\\t\\t\\tif (x)\\n\\t\\t\\t\\tdp[i+1][x-1][y]=(dp[i+1][x-1][y]+1LL*dp[i][x][y]*(f(x-1,y)-f(x,y)))%mod;\\n\\t\\t\\t\\tif (y)\\n\\t\\t\\t\\tdp[i+1][x][y-1]=(dp[i+1][x][y-1]+1LL*dp[i][x][y]*(f(x,y-1)-f(x,y)))%mod;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tprintf(\\\"%d\\\",dp[n][0][0]);\\n}\"",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1174",
    "index": "F",
    "title": "Ehab and the Big Finale",
    "statement": "This is an interactive problem.\n\nYou're given a tree consisting of $n$ nodes, rooted at node $1$. A tree is a connected graph with no cycles.\n\nWe chose a hidden node $x$. In order to find this node, you can ask queries of two types:\n\n- d $u$ ($1 \\le u \\le n$). We will answer with the distance between nodes $u$ and $x$. The distance between two nodes is the number of edges in the shortest path between them.\n- s $u$ ($1 \\le u \\le n$). We will answer with the second node on the path from $u$ to $x$. However, there's a plot twist. If $u$ is \\textbf{not} an ancestor of $x$, you'll receive \"Wrong answer\" verdict!\n\nNode $a$ is called an ancestor of node $b$ if $a \\ne b$ and the shortest path from node $1$ to node $b$ passes through node $a$. \\textbf{Note that in this problem a node is not an ancestor of itself}.\n\nCan you find $x$ in no more than $36$ queries? The hidden node is fixed in each test beforehand and does not depend on your queries.",
    "tutorial": "Let $dep_a$ be the depth of node $a$ and $sz_a$ be the size of the subtree of node $a$. First, we'll query the distance between node 1 and node $x$ to know $dep_x$. The idea in the problem is to maintain a \"search scope\", some nodes such that $x$ is one of them, and to try to narrow it down with queries. From this point, I'll describe two solutions: Assume that your search scope is the subtree of some node $u$ (initially, $u$=1). How can we narrow it down efficiently? I'll pause here to add some definitions. The heavy child of a node $a$ is the child that has the maximal subtree size. The heavy path of node $a$ is the path that starts with node $a$ and every time moves to the heavy child of the current node. Now back to our algorithm. Let's get the heavy path of node $u$. Assume its other endpoint is node $v$. We know that a prefix of this path contains ancestors of node $x$. Let the deepest node in the path that is an ancestor of node $x$ be node $y$ (the last node in this prefix). I'll now add a drawing to help you visualize the situation. So, recapping, $u$ is the root of your search scope, $v$ is the endpoint of the heavy path starting from $u$, $x$ is the hidden node, and $y$ the last ancestor of $x$ in the heavy path. Notice that $y$ is $lca(x,v)$. Now, we know that $dist(x,v)=dep_x+dep_v-2*dep_y$. Since we know $dep_x$, and we know $dep_v$, we can query $dist(x,v)$ to find $dep_y$. Since all nodes in the path have different depths, that means we know $y$ itself! Observation #1: $dist(u,x)+dist(v,x)=dist(u,v)+2*dist(x,y)$. In both sides of the equation, every edge in the heavy path appears once, and every edge in the path from $x$ to $y$ appears twice. We know $dist(u,x)=dep_x-dep_u$. We also know $dist(u,v)=dep_v-dep_u$. Additionally, we can query $dist(v,x)$. From these 3 pieces of information and the equation above, we can find $dist(x,y)$. Observation #2: $dist(u,y)=dist(u,x)-dist(x,y)$. Now we know $dist(u,y)$. Since all nodes in the heavy path have different distances from node $u$, we know $y$ itself! Now, if $dep_x=dep_y$, $x=y$, so we found the answer. Otherwise, we know, by definition, that $y$ is an ancestor of $x$, so it's safe to use the second query type. Let the answer be node $l$. We can repeat the algorithm with $u=l$! How long will this algorithm take? Note that $l$ can't be the heavy child of $y$ (because $y$ is the last ancestor of $x$ in the heavy path), so $sz_l \\le \\lfloor\\frac{sz_y}{2} \\rfloor$, since it's well-known that only the heavy child can break that condition. So with only 2 queries, we managed to cut down at least half of our search scope! So this algorithm does no more than $34$ queries (actually $32$ under these constraints, but that's just a small technicality). As I said, assume we have a search scope. Let's get the centroid, $c$, of that search scope. If you don't know, the centroid is a node that, if removed, the tree will be broken down to components, and each component's size will be at most half the size of the original tree. Now, $c$ may and may not be an ancestor of $x$. How can we determine that? Let's query $dist(c,x)$. $c$ is an ancestor of $x$ if and only if $dep_c+dist(c,x)=dep_x$. Now, if $c$ is an ancestor of $x$, we can safely query the second node on the path between them. Let the answer be $s$, then its component will be the new search scope. What if $c$ isn't an ancestor of $x$? That means node $x$ can't be in the subtree of $c$, so it must be in the component of $c$'s parent. We'll make the component of $c$'s parent the new search scope! Every time, the size of our search scope is, at least, halved, so the solution does at most $36$ queries.",
    "code": "\"#include <iostream>\\n#include <vector>\\nusing namespace std;\\nbool del[200005];\\nvector<int> v[200005];\\nint par[200005],sz[200005],dep[200005],depx;\\nvoid pre(int node,int p)\\n{\\n\\tfor (int u:v[node])\\n\\t{\\n\\t\\tif (u!=p)\\n\\t\\t{\\n\\t\\t\\tpar[u]=node;\\n\\t\\t\\tdep[u]=dep[node]+1;\\n\\t\\t\\tpre(u,node);\\n\\t\\t}\\n\\t}\\n}\\nvector<int> h;\\nint query(char c,int u)\\n{\\n\\tprintf(\\\"%c %d\\\\n\\\",c,u);\\n\\tfflush(stdout);\\n\\tint ans;\\n\\tscanf(\\\"%d\\\",&ans);\\n\\treturn ans;\\n}\\nint getsz(int node,int p)\\n{\\n\\tsz[node]=1;\\n\\tfor (int u:v[node])\\n\\t{\\n\\t\\tif (!del[u] && u!=p)\\n\\t\\tsz[node]+=getsz(u,node);\\n\\t}\\n\\treturn sz[node];\\n}\\nint find(int node,int p,int nn)\\n{\\n\\tfor (int u:v[node])\\n\\t{\\n\\t\\tif (!del[u] && u!=p && sz[u]>nn/2)\\n\\t\\treturn find(u,node,nn);\\n\\t}\\n\\treturn node;\\n}\\nint dfs(int node)\\n{\\n\\tgetsz(node,0);\\n\\tint c=find(node,0,sz[node]),d=query('d',c);\\n\\tif (!d)\\n\\treturn c;\\n\\tdel[c]=1;\\n\\tif (dep[c]+d==depx)\\n\\treturn dfs(query('s',c));\\n\\treturn dfs(par[c]);\\n}\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tint a,b;\\n\\t\\tscanf(\\\"%d%d\\\",&a,&b);\\n\\t\\tv[a].push_back(b);\\n\\t\\tv[b].push_back(a);\\n\\t}\\n\\tdepx=query('d',1);\\n\\tpre(1,0);\\n\\tprintf(\\\"! %d\\\\n\\\",dfs(1));\\n\\tfflush(stdout);\\n}\"",
    "tags": [
      "constructive algorithms",
      "divide and conquer",
      "graphs",
      "implementation",
      "interactive",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1175",
    "index": "A",
    "title": "From Hero to Zero",
    "statement": "You are given an integer $n$ and an integer $k$.\n\nIn one step you can do one of the following moves:\n\n- decrease $n$ by $1$;\n- divide $n$ by $k$ if $n$ is divisible by $k$.\n\nFor example, if $n = 27$ and $k = 3$ you can do the following steps: $27 \\rightarrow 26 \\rightarrow 25 \\rightarrow 24 \\rightarrow 8 \\rightarrow 7 \\rightarrow 6 \\rightarrow 2 \\rightarrow 1 \\rightarrow 0$.\n\nYou are asked to calculate the minimum number of steps to reach $0$ from $n$.",
    "tutorial": "It's always optimal to divide by $k$ whenever it's possible, since dividing by $k$ equivalent to decreasing $n$ by $\\frac{n}{k}(k - 1) \\ge 1$. The only problem is that it's too slow to just subtract $1$ from $n$ each time, since in the worst case we can make $O(n)$ operations (Consider case $n = 10^{18}$ and $k = \\frac{n}{2} + 1$). But if we'd look closer then we can just replace $x$ times of subtract $1$ with one subtraction of $x$. And to make $n$ is divisible by $k$ we should make $x = (n \\mod{k})$ subtractions.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nlong long n, k;\n\nint main(){\n    int tc;\n    cin >> tc;\n    for(int i = 0; i < tc; ++i){\n    \tcin >> n >> k;\n    \tlong long res = 0;\n    \twhile(n > 0){\n    \t    if(n % k == 0){\n    \t        n /= k;\n    \t        ++res;\n    \t    }\n    \t    else{\n    \t        long long rem = n % k;\n    \t        res += rem;\n    \t        n -= rem;\n    \t    }\n    \t}\n    \t\n    \tcout << res << endl;\n    }\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1175",
    "index": "B",
    "title": "Catch Overflow!",
    "statement": "You are given a function $f$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $x$. $x$ is an integer variable and can be assigned values from $0$ to $2^{32}-1$. The function contains three types of commands:\n\n- for $n$ — for loop;\n- end — every command between \"for $n$\" and corresponding \"end\" is executed $n$ times;\n- add — adds 1 to $x$.\n\nAfter the execution of these commands, value of $x$ is returned.\n\nEvery \"for $n$\" is matched with \"end\", thus the function is guaranteed to be valid. \"for $n$\" can be immediately followed by \"end\".\"add\" command can be outside of any for loops.\n\nNotice that \"add\" commands might overflow the value of $x$! It means that the value of $x$ becomes greater than $2^{32}-1$ after some \"add\" command.\n\nNow you run $f(0)$ and wonder if the resulting value of $x$ is correct or some overflow made it incorrect.\n\nIf overflow happened then output \"OVERFLOW!!!\", otherwise print the resulting value of $x$.",
    "tutorial": "One can notice (or actually derive using some maths) that the answer is the sum of products of nested for loops iterations for every \"add\" command. Let's learn to simulate that in linear complexity. Maintain the stack of multipliers: on \"for $n$\" push the top of stack multiplied by $n$ to the stack, on \"end\" pop the last value, on \"add\" add the top of the stack to the answer. The problem, however, is the values are really large. Notice that once you add the value greater or equal to $2^{32}$ to the answer, it immediately becomes \"OVERFLOW!!!\". Thus let's push not the real multiplier to the stack but min(multiplier, $2^{32}$). That way the maximum value you can achieve is about $2^{32} \\cdot 50000$, which fits into the 64-bit integer. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nusing namespace std;\n\nconst long long INF = 1ll << 32;\n\nint main(){\n\tint l;\n\tcin >> l;\n\t\n\tstack<long long> cur;\n\tcur.push(1);\n\t\n\tlong long res = 0;\n\tforn(_, l){\n\t\tstring t;\n\t\tcin >> t;\n\t\tif (t == \"for\"){\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\tcur.push(min(INF, cur.top() * x));\n\t\t}\n\t\telse if (t == \"end\"){\n\t\t\tcur.pop();\n\t\t}\n\t\telse{\n\t\t\tres += cur.top();\n\t\t}\n\t}\n\t\n\tif (res >= INF)\n\t\tcout << \"OVERFLOW!!!\" << endl;\n\telse\n\t\tcout << res << endl;\n}",
    "tags": [
      "data structures",
      "expression parsing",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1175",
    "index": "C",
    "title": "Electrification",
    "statement": "At first, there was a legend related to the name of the problem, but now it's just a formal statement.\n\nYou are given $n$ points $a_1, a_2, \\dots, a_n$ on the $OX$ axis. Now you are asked to find such an integer point $x$ on $OX$ axis that $f_k(x)$ is minimal possible.\n\nThe function $f_k(x)$ can be described in the following way:\n\n- form a list of distances $d_1, d_2, \\dots, d_n$ where $d_i = |a_i - x|$ (distance between $a_i$ and $x$);\n- sort list $d$ in non-descending order;\n- take $d_{k + 1}$ as a result.\n\nIf there are multiple optimal answers you can print any of them.",
    "tutorial": "First observation: $k$ closest points to any point $x$ form a contiguous subsegment $a_i, \\dots, a_{i + k - 1}$, so $f_k(x) = \\min(|a_{i - 1} - x|, |a_{i + k} - x|)$. Second observation: for any contiguous subsegment $a_i, \\dots, a_{i + k - 1}$ all points $x$ this subsegment closest to, also form a contiguous segment $[l_i, r_i]$. And, because of the nature of $f_k(x)$, value of $f_k(x)$ is minimal in borders $l_i$ and $r_i$. So, all we need is to check all $l_i$ and $r_i$. But what is a value of $r_i$? It's such point, that $|a_i - r_i| \\le |a_{i + k} - r_i|$, but $|a_i - (r_i + 1)| > |a_{i + k} - (r_i + 1)|$. So, it's just in the middle of segment $[a_i, a_{i + k}]$. Note, that $r_i + 1 = l_{i + 1}$ and $f_k(l_{i + 1}) \\ge f_k(r_i)$, so it's enough to check only $r_i$-s. In result, all we need is to find minimal possible value $|a_{i + k} - a_i|$ and resulting $x = a_i + \\frac{a_{i + k} - a_{i}}{2}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nint n, k;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n >> k))\n\t\treturn false;\n\ta.resize(n);\n\tfore(i, 0, n)\n\t\tcin >> a[i];\n\treturn true;\n}\n\ninline void solve() {\n\tpair<int, int> ans = {int(1e9) + 7, -1};\n\tfore(i, 0, n - k) {\n\t\tint dist = a[i + k] - a[i];\n\t\tans = min(ans, make_pair(dist, a[i] + dist / 2));\n\t}\n\t\n\tcout << ans.second << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\t\n\twhile(tc--) {\n\t    read();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1175",
    "index": "D",
    "title": "Array Splitting",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$ and an integer $k$.\n\nYou are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $f(i)$ be the index of subarray the $i$-th element belongs to. Subarrays are numbered from left to right and from $1$ to $k$.\n\nLet the cost of division be equal to $\\sum\\limits_{i=1}^{n} (a_i \\cdot f(i))$. For example, if $a = [1, -2, -3, 4, -5, 6, -7]$ and we divide it into $3$ subbarays in the following way: $[1, -2, -3], [4, -5], [6, -7]$, then the cost of division is equal to $1 \\cdot 1 - 2 \\cdot 1 - 3 \\cdot 1 + 4 \\cdot 2 - 5 \\cdot 2 + 6 \\cdot 3 - 7 \\cdot 3 = -9$.\n\nCalculate the maximum cost you can obtain by dividing the array $a$ into $k$ non-empty consecutive subarrays.",
    "tutorial": "Let's denote $S(k)$ as $\\sum\\limits_{i = k}^{n}{a_i}$ (just a suffix sum). And let $p_i$ be the position where starts the $i$-th subarray (obviously, $p_1 = 1$ and $p_i < p_{i + 1}$). Then we can make an interesting transformation: $\\sum_{i=1}^{n}{a_i \\cdot f(i)} = 1 \\cdot (S(p_1) - S(p_2)) + 2 \\cdot (S(p_2) - S(p_3)) + \\dots + k \\cdot (S(p_k) - 0) = \\\\ = S(p_1) + (2 - 1) S(p_2) + (3 - 2) S(p_3) + \\dots + (k - (k - 1))) S(p_k) = \\\\ = S(p_1) + S(p_2) + S(p_3) + \\dots + S(p_k).$ That's why we can just greedily take $k - 1$ maximum suffix sums along with sum of all array.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300009;\n\nint n, k;\nint a[N];\n\nint main(){\n\tcin >> n >> k;\n\tfor(int i = 0; i < n; ++i)\n\t\tcin >> a[i];\n\t\n\tlong long sum = 0;\n\tvector <long long> v;\n\tfor(int i = n - 1; i >= 0; --i){\n\t    sum += a[i];\n\t    if(i > 0) v.push_back(sum);\n\t}\n\t\n\tlong long res = sum;\n\t\n\tsort(v.begin(), v.end());\n\treverse(v.begin(), v.end());\n\t\n\t\n\tfor(int i = 0; i < k - 1; ++i)\n\t    res += v[i];\n\t    \n\tcout << res << endl;\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1175",
    "index": "E",
    "title": "Minimal Segment Cover",
    "statement": "You are given $n$ intervals in form $[l; r]$ on a number line.\n\nYou are also given $m$ queries in form $[x; y]$. What is the minimal number of intervals you have to take so that every point (\\textbf{not necessarily integer}) from $x$ to $y$ is covered by at least one of them?\n\nIf you can't choose intervals so that every point from $x$ to $y$ is covered, then print -1 for that query.",
    "tutorial": "Let's take a look at a naive approach at first. That approach is greedy. Let's find such an interval which starts to the left or at $x$ and ends as much to the right as possible. Set $x$ to its right border. Continue until either no interval can be found or $y$ is reached. The proof basically goes like this. Let there be some smaller set of intervals which cover the query, these can be sorted by left border (obviously their left borders are pairwise distinct). Compare that set to the greedy one, take a look at the first position where best set's interval has his $r$ less than the greedy set's $r$. You can see that choosing interval greedily will still allow to have the rest of best set intervals, making the greedy choice optimal. Let's implement it in $O(nlogn + nm)$. For each position from $0$ to $5 \\cdot 10^5$ you can precalculate the index of such an interval that it starts to the left or at this position and ends as much to the right as possible. To do this sort all intervals by their left border, then iterate over positions, while maintaining the maximum right border achieved by intervals starting to the left or at the current position. The query is now straightforward. Now there are two main ways to optimize it. You can do it binary lifting style: for each interval (or position) precalculate the index of the interval taken last after taking $2^k$ intervals greedily and use this data to answer queries in $O(\\log n)$. You can also do it path compression style. Let's process the queries in the increasing order of their right borders. Now do greedy algorithm but for each interval you use remember the index of the last reached interval. Now the part with answering queries is $O(n + m)$ in total because each interval will be jumped from no more than once. Overall complexity: $O((n + m) \\log n)$ / $O(n \\log n + m \\log m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nconst int N = 500 * 1000 + 13;\n\nint n, m;\npair<int, int> a[N], q[N];\n\nint nxt[N];\nint ans[N];\n\npair<int, int> p[N];\n\npair<int, int> get(int x, int r){\n\tif (x == -1)\n\t\treturn make_pair(-1, -1);\n\tif (a[x].y >= r)\n\t\treturn make_pair(x, 0);\n\tauto res = get(p[x].x, r);\n\tif (res.x == -1)\n\t\tp[x] = make_pair(-1, -1);\n\telse\n\t\tp[x] = make_pair(res.x, p[x].y + res.y);\n\treturn p[x];\n}\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tforn(i, n)\n\t\tscanf(\"%d%d\", &a[i].x, &a[i].y);\n\tforn(i, m)\n\t\tscanf(\"%d%d\", &q[i].x, &q[i].y);\n\tsort(a, a + n);\n\t\n\tint lst = 0;\n\tpair<int, int> mx(0, -1);\n\tforn(i, N){\n\t\twhile (lst < n && a[lst].x == i){\n\t\t\tmx = max(mx, make_pair(a[lst].y, lst));\n\t\t\t++lst;\n\t\t}\n\t\tnxt[i] = (mx.x <= i ? -1 : mx.y);\n\t}\n\t\n\tvector<int> perm(m);\n\tiota(perm.begin(), perm.end(), 0);\n\tsort(perm.begin(), perm.end(), [](int a, int b){\n\t\treturn q[a].y < q[b].y;\n\t});\n\t\n\tforn(i, n)\n\t\tp[i] = make_pair(nxt[a[i].y], nxt[a[i].y] == -1 ? -1 : 1);\n\t\n\tfor (auto i : perm){\n\t\tint x = nxt[q[i].x];\n\t\tauto res = get(x, q[i].y).y;\n\t\tans[i] = (res == -1 ? -1 : res + 1);\n\t}\n\t\n\tforn(i, m)\n\t\tprintf(\"%d\\n\", ans[i]);\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dp",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1175",
    "index": "F",
    "title": "The Number of Subpermutations",
    "statement": "You have an array $a_1, a_2, \\dots, a_n$.\n\nLet's call some subarray $a_l, a_{l + 1}, \\dots , a_r$ of this array a subpermutation if it contains all integers from $1$ to $r-l+1$ exactly once. For example, array $a = [2, 2, 1, 3, 2, 3, 1]$ contains $6$ subarrays which are subpermutations: $[a_2 \\dots a_3]$, $[a_2 \\dots a_4]$, $[a_3 \\dots a_3]$, $[a_3 \\dots a_5]$, $[a_5 \\dots a_7]$, $[a_7 \\dots a_7]$.\n\nYou are asked to calculate the number of subpermutations.",
    "tutorial": "At first, let's represent permutations in the next form. We assign to all numbers from $1$ to $n$ random 128-bit strings, so the $i$-th number gets the string $h_i$. Then the permutation of length $len$ can be hashed as $h_1 \\oplus h_2 \\oplus \\dots \\oplus h_{len}$, where $\\oplus$ is bitwise exclusive OR (for example, $0110 \\oplus 1010 = 1100$). This representation is convenient because if we have two sets of numbers with a total number of elements equal to $len$ (let's represent them as $s_1, s_2, \\dots s_m$ and $t_1, t_2, \\dots t_k$, $k + m = len$), we can easily check whether their union is a permutation of length $len$ (condition $h_{s_1} \\oplus h_{s_2} \\oplus \\dots \\oplus h_{s_m} \\oplus h_{t_1} \\oplus h_{t_2} \\oplus \\dots h_{t_k} = h_1 \\oplus h_2 \\oplus \\dots \\oplus h_{len}$ must be hold). Let's denote $f(l, r)$ as $h_{a_l} \\oplus h_{a_l + 1} \\oplus \\dots \\oplus h_{a_r}$. Now let's iterate over position $i$ such that $a_i = 1$ and calculate the number of permutations that contain this element. To do it, let's iterate over the right boundary $r$ and suppose, that maximum element of permutation $len$ (and its length at the same time) is one of positions $i + 1, i + 2, \\dots , r$. If it's true, then the subpermutation should be on the positions $r - len + 1, r - len + 2, \\dots , r$. And to check that this segment is a subpermutation we should just compare $f(r - len + 1, r)$ and $h_1 \\oplus h_2 \\oplus \\dots \\oplus h_{len}$. Thus, we will calculate all permutations in which the position of the maximum is to the right of the position of the $1$. To calculate all permutations we need to reverse array $a$ and repeat this algorithm, and then add the number of ones in the array $a$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<long long, long long> pt;\n\nconst int N = int(3e5) + 99;\nconst pt zero = make_pair(0, 0);\n\nint n;\nint a[N];\npt hsh[N], sumHsh[N];\n\nvoid upd(pt &a, pt b){\n    a.first ^= b.first;\n    a.second ^= b.second;\n}\n\nint calc(int pos){\n\tset <int> sl, sr;\n\tset<pt> s;\n\tint r = pos + 1, l = pos - 1;\n\tpt curr = hsh[0], curl = zero;\n\ts.insert(zero);\n\tsr.insert(0), sl.insert(0);\n\t\n\tint res = 0;\t\n\twhile(r < n && !sr.count(a[r])){\n\t\tsr.insert(a[r]);\n\t\tupd(curr, hsh[a[r]]);\n\t\t++r;\n\n\t\twhile(l >= 0 && !sl.count(a[l]) && a[l] < *sr.rbegin()){\n\t\t\tsl.insert(a[l]);\n\t\t\tupd(curl, hsh[a[l]]);\n\t\t\ts.insert(curl);\n\t\t\t--l;\t\n\t\t}\n\n\t\tpt need = sumHsh[*sr.rbegin()];\n\t\tupd(need, curr);\n\t\tif(s.count(need)) ++res;\n\t}\t\n\n\treturn res;\n}\t\n\nint main() {\n    long long x = 0;\n\tcin >> n;\n\tfor(int i = 0; i < n; ++i){\n\t\tcin >> a[i];\n\t\t--a[i];\t\n\t\tx ^= a[i];\n\t}\n\t\n\t\n\tmt19937_64 rnd(time(NULL));\n\tfor(int i = 0; i < N; ++i){\n\t\thsh[i].first = rnd() ^ x;\n\t\thsh[i].second = rnd() ^ x;\n\t\tsumHsh[i] = hsh[i];\n\t\tif(i > 0) upd(sumHsh[i], sumHsh[i - 1]);\n\t}\n\t\n\tint res = 0;\n\t\t\n\tfor(int tc = 0; tc < 2; ++tc){\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tif(a[i] == 0)\n\t\t\t\tres += calc(i) + (tc == 0);\n\t\treverse(a, a + n);\n\t}\n\tcout << res << endl;\n\n\treturn 0;\n} ",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "hashing",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1175",
    "index": "G",
    "title": "Yet Another Partiton Problem",
    "statement": "You are given array $a_1, a_2, \\dots, a_n$. You need to split it into $k$ subsegments (so every element is included in exactly one subsegment).\n\nThe weight of a subsegment $a_l, a_{l+1}, \\dots, a_r$ is equal to $(r - l + 1) \\cdot \\max\\limits_{l \\le i \\le r}(a_i)$. The weight of a partition is a total weight of all its segments.\n\nFind the partition of minimal weight.",
    "tutorial": "Important note: the author solution is using both linear Convex hull trick and persistent Li Chao tree. As mentioned in commentaries, applying the Divide-and-Conquer technique can help get rid of Li Chao tree. More about both structures you can read in this article. Let's try to write standard dp we can come up with (arrays will be 0-indexed). Let $dp[k][i]$ be the minimal weight if we splitted prefix of length $i$ in $k$ subsegments. Then we can calculate it as: $dp[k][i] = \\min\\limits_{0 \\le j < i}(dp[k - 1][j] + (i - j) \\cdot \\max\\limits_{j \\le k < i}(a[k]))$ [1]. Maximums on segments are inconvenient, let's try to group segments $[j, i)$ by the value of $\\max{}$. So, we can find such sequence of borders $j_0 = i - 1 > j_1 > j_2 > \\dots$, where for each $j \\in (j_{l + 1}, j_l]$ $\\max\\limits_{j \\le k < i}(a[k]) = a[j_l]$. In other words, $j_0 = i - 1$ and $j_{l + 1}$ is the closest from the left position, where $a[j_{l + 1}] \\ge a[j_l]$. Note, that we can maintain this sequence with stack of maximums. Ok, then for each interval $(j_{l + 1}, j_l]$ equation [1] transforms to: $\\min_{j_{l+1} < j \\le j_l}(dp[k - 1][j] + (i - j) \\cdot a[j_l]) = a[j_l] \\cdot i + \\min_{j_{l+1} < j \\le j_l}(-j \\cdot a[j_l] + dp[k - 1][j]) = \\\\ = a[j_l] \\cdot y + \\min_{j_{l+1} < j \\le j_l}(-j \\cdot x + dp[k - 1][j]) |_{y = i, x = a[j_l]}.$ Why did we use variables $x$ and $y$? Because there are two problems: $y$ is needed because we iterate over $i$ and can't recalculate everything; $x$ is needed because sequence $j_l$ is changing over time, so do the $a[j_l]$. But what we can already see: we can maintain for each segment Convex hull with linear functions - so we can take $f_l = \\min\\limits_{j_{l+1} < j \\le j_l}(\\dots)$ in logarithmic time. Moreover, we can store values $a[j_l] \\cdot y + f_l$ in other Convex hull to take minimum over all segments in logarithmic time. The problems arise when we try modificate structures while iterating $i$. Fortunately, segments $j_l$ change not at random, but according to stack of maximums. So all we should handle are: to merge segment on top of the stack $(j_1, j_0]$ with current segment $(j_0, i]$ (in case when $a[i] > a[j_0]$); to erase segment on top of the stack along with its value $a[j_0] \\cdot y + f_0$; to insert new segment on top of the stack along with its value $a[j_0] \\cdot y + f_0$. To handle the third type is easy, since all Convex hulls can insert elements. There will be at most $O(n)$ such operations on a single layer $k$ and we can ask value $f_0$ in $O(\\log{n})$ and insert a line with $O(\\log{A})$. To handle the second type is harder, but possible, since we can make Convex hull persistent and store its versions in the stack. Persistent Convex hull - persistent Li Chao tree. There will be also $O(nk)$ operations in total and they cost us $O(1)$. To handle the first type is trickiest part. Note, that all line coefficients of one convex hull are strictly lower than all line coefficients of the other. So, we can use linear Convex hulls to make insertions to back in amortized $O(1)$. But to merge efficiently, we should use Small-to-Large technique, that's why we should be able also push front in $O(1)$, and, moreover, still be able to ask minimum in $O(\\log{n})$. And here comes the hack - $deque$ in C++, which can push/pop front/back in amortized $O(1)$ and also have random access iterator to make binary search possible. So, each element of every segment will be transfered $O(\\log{n})$ times with cost of amortized $O(1)$ on a single layer $k$. In the end, result complexity is $O(n k (\\log{C} + \\log{n}))$. Space complexity is $O(n \\log{A})$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) (int)((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<li, li> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e9);\n\npt operator -(const pt &a, const pt &b) {\n    return {a.x - b.x, a.y - b.y};\n}\nli operator *(const pt &a, const pt &b) {\n    return a.x * b.x + a.y * b.y;\n}\nli operator %(const pt &a, const pt &b) {\n    return a.x * b.y - a.y * b.x;\n}\npt rotate(const pt &p) {\n    return {-p.y, p.x};\n}\n\nstruct LinearHull {\n    deque<pt> pts, vecs;\n\n    void addRight(const pt &l) {\n        while(!vecs.empty() && vecs.back() * (l - pts.back()) < 0) {\n            vecs.pop_back();\n            pts.pop_back();\n        }\n        if(!pts.empty())\n            vecs.push_back(rotate(l - pts.back()));\n        pts.push_back(l);\n    }\n    void addLeft(const pt &l) {\n        while(!vecs.empty() && vecs.front() * (l - pts.front()) < 0) {\n            vecs.pop_front();\n            pts.pop_front();\n        }\n        if(!pts.empty())\n            vecs.push_front(rotate(pts.front() - l));\n        pts.push_front(l);\n    }\n\n    li getMin(const pt &x) {\n        auto it = lower_bound(vecs.begin(), vecs.end(), x, [](const pt &a, const pt &b) {\n            return a % b > 0;\n        });\n        return x * pts[it - vecs.begin()];\n    }\n};\n\ntypedef unique_ptr<LinearHull> pHull;\n\nvoid mergeHulls(pHull &a, pHull &b) {\n    if(sz(b->pts) >= sz(a->pts)) {\n        for(auto &p : a->pts)\n            b->addRight(p);\n    } else {\n        for(auto it = b->pts.rbegin(); it != b->pts.rend(); it++)\n            a->addLeft(*it);\n        swap(a, b);\n    }\n}\n\nconst int M = 1000 * 1000 + 555;\nint szn = 0;\nstruct node {\n    pt line;\n    node *l, *r;\n\n    node() : line(), l(nullptr), r(nullptr) {}\n    node(pt line, node *l, node *r) : line(move(line)), l(l), r(r) {}\n} nodes[M];\n\ntypedef node* tree;\n\ntree getNode(const pt &line, tree l, tree r) {\n    assert(szn < M);\n    nodes[szn] = node(line, l, r);\n    return &nodes[szn++];\n}\ntree copy(tree v) {\n    if(v == nullptr) return v;\n    return getNode(v->line, v->l, v->r);\n}\n\nli f(const pt &line, int x) {\n    return line * pt{x, 1};\n}\n\ntree addLine(tree v, int l, int r, pt line) {\n    if(!v)\n        return getNode(line, nullptr, nullptr);\n    int mid = (l + r) >> 1;\n    bool lf = f(line, l) < f(v->line, l);\n    bool md = f(line, mid) < f(v->line, mid);\n\n    if(md)\n        swap(v->line, line);\n\n    if(l + 1 == r)\n        return v;\n    else if(lf != md)\n        v->l = addLine(copy(v->l), l, mid, line);\n    else\n        v->r = addLine(copy(v->r), mid, r, line);\n    return v;\n}\n\nli getMin(tree v, int l, int r, int x) {\n    if(!v) return INF64;\n    if(l + 1 == r)\n        return f(v->line, x);\n    int mid = (l + r) >> 1;\n\n    if(x < mid)\n        return min(f(v->line, x), getMin(v->l, l, mid, x));\n    else\n        return min(f(v->line, x), getMin(v->r, mid, r, x));\n}\n\nint n, k;\nvector<li> a;\n\ninline bool read() {\n    if(!(cin >> n >> k))\n        return false;\n    a.resize(n);\n\n    fore(i, 0, n)\n        cin >> a[i];\n    return true;\n}\n\nstruct state {\n    int pos;\n    pHull hull;\n    tree v;\n\n    state() : pos(-1), hull(nullptr), v(nullptr) {}\n};\n\nvector<li> d[2];\n\ninline void solve() {\n    int maxn = (int)*max_element(a.begin(), a.end()) + 3;\n    fore(k, 0, 2)\n        d[k].resize(n + 1, INF64);\n\n    d[0][0] = 0;\n    fore(_k, 1, k + 1) {\n        szn = 0;\n\n        int ck = _k & 1;\n        int nk = ck ^ 1;\n\n        vector< state > st;\n\n        fore(i, 0, sz(d[ck])) {\n            d[ck][i] = INF64;\n            if(!st.empty())\n                d[ck][i] = getMin(st.back().v, 0, maxn, i);\n\n            if(i >= sz(a))\n                continue;\n\n            state curVal;\n            curVal.pos = i;\n            curVal.hull = make_unique<LinearHull>();\n            curVal.hull->addRight({-i, d[nk][i]});\n            curVal.v = nullptr;\n\n            while(!st.empty() && a[st.back().pos] < a[i]) {\n                mergeHulls(st.back().hull, curVal.hull);\n                st.pop_back();\n            }\n            if(!st.empty())\n                curVal.v = st.back().v;\n\n            li val = curVal.hull->getMin({a[i], 1});\n            curVal.v = addLine(copy(curVal.v), 0, maxn, {a[i], val});\n\n            st.push_back(move(curVal));\n        }\n    }\n    cout << d[k & 1][n] << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n\n    if(read()) {\n        solve();\n\n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "geometry",
      "two pointers"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1176",
    "index": "A",
    "title": "Divide it!",
    "statement": "You are given an integer $n$.\n\nYou can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:\n\n- Replace $n$ with $\\frac{n}{2}$ if $n$ is divisible by $2$;\n- Replace $n$ with $\\frac{2n}{3}$ if $n$ is divisible by $3$;\n- Replace $n$ with $\\frac{4n}{5}$ if $n$ is divisible by $5$.\n\nFor example, you can replace $30$ with $15$ using the first operation, with $20$ using the second operation or with $24$ using the third operation.\n\nYour task is to find the minimum number of moves required to obtain $1$ from $n$ or say that it is impossible to do it.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "What if the given number $n$ cannot be represented as $2^{cnt_2} \\cdot 3^{cnt_3} \\cdot 5^{cnt_5}$? It means that the answer is -1 because all actions we can do are: remove one power of two, remove one power of three and add one power of two, and remove one power of five and add two powers of two. So if the answer is not -1 then it is $cnt_2 + 2cnt_3 + 3cnt_5$. If this formula isn't pretty clear for you, you can just simulate the process, performing actions from third to first.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tlong long n;\n\t\tcin >> n;\n\t\tint cnt2 = 0, cnt3 = 0, cnt5 = 0;\n\t\twhile (n % 2 == 0) {\n\t\t\tn /= 2;\n\t\t\t++cnt2;\n\t\t}\n\t\twhile (n % 3 == 0) {\n\t\t\tn /= 3;\n\t\t\t++cnt3;\n\t\t}\n\t\twhile (n % 5 == 0) {\n\t\t\tn /= 5;\n\t\t\t++cnt5;\n\t\t}\n\t\tif (n != 1) {\n\t\t\tcout << -1 << endl;\n\t\t} else {\n\t\t\tcout << cnt2 + cnt3 * 2 + cnt5 * 3 << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1176",
    "index": "B",
    "title": "Merge it!",
    "statement": "You are given an array $a$ consisting of $n$ integers $a_1, a_2, \\dots , a_n$.\n\nIn one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $[2, 1, 4]$ you can obtain the following arrays: $[3, 4]$, $[1, 6]$ and $[2, 5]$.\n\nYour task is to find the maximum possible number of elements divisible by $3$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.\n\nYou have to answer $t$ independent queries.",
    "tutorial": "Let $cnt_i$ be the number of elements of $a$ with the remainder $i$ modulo $3$. Then the initial answer can be represented as $cnt_0$ and we have to compose numbers with remainders $1$ and $2$ somehow optimally. It can be shown that the best way to do it is the following: firstly, while there is at least one remainder $1$ and at least one remainder $2$, let's compose them into one $0$. After this, at least one of the numbers $cnt_1, cnt_2$ will be zero, then we have to compose remaining numbers into numbers divisible by $3$. If $cnt_1 = 0$ then the maximum remaining number of elements we can obtain is $\\lfloor\\frac{cnt_2}{3}\\rfloor$ (because $2 + 2 + 2 = 6$), and in the other case ($cnt_2 = 0)$ the maximum number of elements is $\\lfloor\\frac{cnt_1}{3}\\rfloor$ (because $1 + 1 + 1 = 3$).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint t, n;\nint cnt[3];\n\nint main(){\n    cin >> t;\n    for(int tc = 0; tc < t; ++tc){\n        memset(cnt, 0, sizeof cnt);\n        cin >> n;\n        for(int i = 0; i < n; ++i){\n            int x;\n            cin >> x;\n            ++cnt[x % 3];\n        }\n    \t\n    \tint res = cnt[0];\n        int mn = min(cnt[1], cnt[2]);\n        res += mn;\n        cnt[1] -= mn, cnt[2] -= mn;\n        res += (cnt[1] + cnt[2]) / 3;\n        cout << res << endl;\n    }\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1176",
    "index": "C",
    "title": "Lose it!",
    "statement": "You are given an array $a$ consisting of $n$ integers. Each $a_i$ is one of the six following numbers: $4, 8, 15, 16, 23, 42$.\n\nYour task is to remove the minimum number of elements to make this array \\textbf{good}.\n\nAn array of length $k$ is called \\textbf{good} if $k$ is divisible by $6$ and it is possible to split it into $\\frac{k}{6}$ \\textbf{subsequences} $4, 8, 15, 16, 23, 42$.\n\nExamples of good arrays:\n\n- $[4, 8, 15, 16, 23, 42]$ (the whole array is a required sequence);\n- $[4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42]$ (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements);\n- $[]$ (\\textbf{the empty array is good}).\n\nExamples of bad arrays:\n\n- $[4, 8, 15, 16, 42, 23]$ (the order of elements should be exactly $4, 8, 15, 16, 23, 42$);\n- $[4, 8, 15, 16, 23, 42, 4]$ (the length of the array is not divisible by $6$);\n- $[4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23]$ (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence).",
    "tutorial": "Let $cnt_1$ be the number of subsequences $[4]$, $cnt_2$ be the number of subsequences $[4, 8]$, $cnt_3$ - the number of subsequences $[4, 8, 15]$ and so on, and $cnt_6$ is the number of completed subsequences $[4, 8, 15, 16, 23, 42]$. Let's iterate over all elements of $a$ in order from left to right. If the current element is $4$ then let's increase $cnt_1$ by one (we staring the new subsequence). Otherwise it is always better to continue some existing subsequence (just because why not?). If the current element is $8$ then we can continue some subsequence $[4]$, if it is $16$ then we can continue some subsequence $[4, 8, 15]$ and the same for remaining numbers. Let $pos$ be the $1$-indexed position of the current element of $a$ in list $[4, 8, 15, 16, 23, 42]$. Then the case $pos = 1$ is described above, and in other case ($pos > 1$) if $cnt_{pos - 1} > 0$ then let's set $cnt_{pos - 1} := cnt_{pos - 1} - 1$ and $cnt_{pos} := cnt_{pos} + 1$ (we continue some of existing subsequences). The answer can be calculated as $n - 6 cnt_{6}$ after all $n$ iterations.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tvector<int> p({4, 8, 15, 16, 23, 42});\n\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\ta[i] = lower_bound(p.begin(), p.end(), a[i]) - p.begin();\n\t}\n\t\n\tvector<int> seq(6);\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (a[i] == 0) {\n\t\t\t++seq[0];\n\t\t} else {\n\t\t\tif (seq[a[i] - 1] > 0) {\n\t\t\t\t--seq[a[i] - 1];\n\t\t\t\t++seq[a[i]];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << n - seq[5] * 6 << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1176",
    "index": "D",
    "title": "Recover it!",
    "statement": "Authors guessed an array $a$ consisting of $n$ integers; each integer is not less than $2$ and not greater than $2 \\cdot 10^5$. You don't know the array $a$, but you know the array $b$ which is formed from it with the following sequence of operations:\n\n- Firstly, let the array $b$ be equal to the array $a$;\n- Secondly, for each $i$ from $1$ to $n$:\n\n- if $a_i$ is a \\textbf{prime} number, then one integer $p_{a_i}$ is appended to array $b$, where $p$ is an infinite sequence of prime numbers ($2, 3, 5, \\dots$);\n- otherwise (if $a_i$ is not a \\textbf{prime} number), the greatest divisor of $a_i$ which is not equal to $a_i$ is appended to $b$;\n\n- Then the obtained array of length $2n$ is shuffled and given to you in the input.\n\nHere $p_{a_i}$ means the $a_i$-th prime number. The first prime $p_1 = 2$, the second one is $p_2 = 3$, and so on.\n\nYour task is to recover \\textbf{any} suitable array $a$ that forms the given array $b$. It is guaranteed that the answer exists (so the array $b$ is obtained from some suitable array $a$). If there are multiple answers, you can print any.",
    "tutorial": "Firstly, let's generate first $199999$ primes. It can be done in $O(n \\sqrt{n})$ almost naively (just check all elements in range $[2; 2750131]$). It also can be done with Eratosthenes sieve in $O(n)$ or $O(n \\log \\log n)$. We also can calculate for each number in this range the maximum its divisor non-equal to it (if this number is not a prime). And in other case we can calculate the index of this prime. Using all this information we can restore the array $a$. Let's maintain a multiset (a set in which multiple copies of the same element are allowed) of all elements in $b$. While it is not empty, let's take the maximum element from this set $mx$. If it is prime (we can check it using the information calculated earlier) then it is some $p_{a_i}$. Let's find the index of this prime ($a_i$) using calculated information, remove this element and $a_i$, push $a_i$ in $a$ and continue. Otherwise this element is not a prime and then it is some $a_i$. Let's remove it and its maximum divisor non-equal to it from the multiset, push $a_i$ in $a$ and continue.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 3 * 1000 * 1000 + 13;\n\nint lst[N];\nint num[N];\n\nvoid sieve(){\n\tforn(i, N) lst[i] = i;\n\tfor (int i = 2; i < N; ++i){\n\t\tif (lst[i] != i){\n\t\t\tlst[i] = i / lst[i];\n\t\t\tcontinue;\n\t\t}\n\t\tfor (long long j = i * 1ll * i; j < N; j += i)\n\t\t\tlst[j] = min(lst[j], i);\n\t}\n\tint cur = 0;\n\tfor (int i = 2; i < N; ++i) if (lst[i] == i)\n\t\tnum[i] = ++cur;\n}\n\nint cnt[N];\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tforn(i, 2 * n){\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\t++cnt[x];\n\t}\n\t\n\tsieve();\n\t\n\tvector<int> res;\n\tfor (int i = N - 1; i >= 0; --i){\n\t\twhile (cnt[i] > 0){\n\t\t\tif (lst[i] == i){\n\t\t\t\t--cnt[num[i]];\n\t\t\t\tres.push_back(num[i]);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t--cnt[lst[i]];\n\t\t\t\tres.push_back(i);\n\t\t\t}\n\t\t\t--cnt[i];\n\t\t}\n\t}\n\t\n\tfor (auto it : res)\n\t\tprintf(\"%d \", it);\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "number theory",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1176",
    "index": "E",
    "title": "Cover it!",
    "statement": "You are given an undirected unweighted connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.\n\nYour task is to choose \\textbf{at most} $\\lfloor\\frac{n}{2}\\rfloor$ vertices in this graph so \\textbf{each} unchosen vertex is adjacent (in other words, connected by an edge) to at least one of chosen vertices.\n\nIt is guaranteed that the answer exists. If there are multiple answers, you can print any.\n\nYou will be given multiple independent queries to answer.",
    "tutorial": "Firstly, let's run bfs on the given graph and calculate distances for all vertices. In fact, we don't need distances, we need their parities. The second part is to find all vertices with an even distance, all vertices with and odd distance, and print the smallest by size part. Why is it always true? Firstly, it is obvious that at least one of these sizes will not exceed $\\lfloor\\frac{n}{2}\\rfloor$. And secondly, because we are checking just parities of distances, it is obvious that each vertex of some parity is connected with at least one vertex of the opposite parity (because it has this parity from some vertex of the opposite parity).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint n, m;\nvector<int> d;\nvector<vector<int>> g;\n\nvoid bfs(int s) {\n\td = vector<int>(n, INF);\n\td[s] = 0;\n\t\n\tqueue<int> q;\n\tq.push(s);\n\t\n\twhile (!q.empty()) {\n\t\tint v = q.front();\n\t\tq.pop();\n\t\t\n\t\tfor (auto to : g[v]) {\n\t\t\tif (d[to] == INF) {\n\t\t\t\td[to] = d[v] + 1;\n\t\t\t\tq.push(to);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\t\n\tfor (int tc = 0; tc < t; ++tc){\n\t\tcin >> n >> m;\n\t\tg = vector<vector<int>>(n);\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y;\n\t\t\t--x, --y;\n\t\t\tg[x].push_back(y);\n\t\t\tg[y].push_back(x);\n\t\t}\n\t\n\t\tbfs(0);\n\t\tvector<int> even, odd;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (d[i] & 1) odd.push_back(i);\n\t\t\telse even.push_back(i);\n\t\t}\n\t\n\t\tif (even.size() < odd.size()) {\n\t\t\tcout << even.size() << endl;\n\t\t\tfor (auto v : even) cout << v + 1 << \" \";\n\t\t} else {\n\t\t\tcout << odd.size() << endl;\n\t\t\tfor (auto v : odd) cout << v + 1 << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1176",
    "index": "F",
    "title": "Destroy it!",
    "statement": "You are playing a computer card game called Splay the Sire. Currently you are struggling to defeat the final boss of the game.\n\nThe boss battle consists of $n$ turns. During each turn, you will get several cards. Each card has two parameters: its cost $c_i$ and damage $d_i$. You may play some of your cards during each turn in some sequence (you choose the cards and the exact order they are played), as long as \\textbf{the total cost of the cards you play during the turn does not exceed $3$}. After playing some (possibly zero) cards, you end your turn, and \\textbf{all cards you didn't play are discarded}. Note that you can use each card \\textbf{at most once}.\n\nYour character has also found an artifact that boosts the damage of some of your actions: every $10$-th card you play deals double damage.\n\nWhat is the maximum possible damage you can deal during $n$ turns?",
    "tutorial": "The first (and crucial) observation is that we don't need all the cards that we get during each turn. In fact, since the total cost is limited to $3$, we may leave three best cards of cost $1$, one best card of cost $2$ and one best card of cost $3$, and all other cards may be discarded. So, the problem is reduced: we get only $5$ cards each turn. The problem may be solved with dynamic programming: $dp_{x, y}$ is the maximum damage we may deal if we played $x$ turns and the last card we played had remainder $y$ modulo $10$. Processing each turn may be done with auxiliary dp: $z_{c, f}$ - the maximum damage we can deal during the turn if we play $c$ cards, and $f$ denotes whether some card (there will be only one such card, obviously) deals double damage. To calculate this auxiliary dp, we may do almost anything since we are limited to $5$ cards during each turn. It is possible to calculate it in a fast way using some casework, but it is easier, for example, to try all possible permutations of $5$ cards and play some prefix of a fixed permutation. By combining these two techniques, we get a solution.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n\n#include<iostream>\n#include<cstdio>\n#include<vector>\n#include<algorithm>\n\nusing namespace std;\n\ntypedef long long li;\n\nconst li INF64 = li(1e18);\n\nconst int N = 200043;\nvector<int> cards[N][4];\nli dp[N][10];\nint n;\nli dp2[4][2];\n\nint main()\n{\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\tfor(int i = 0; i < N; i++)\n\t\tfor(int j = 0; j < 10; j++)\n\t\t\tdp[i][j] = -INF64;\n\tdp[0][0] = 0;\n\tscanf(\"%d\", &n);\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\tfor (int j = 0; j < k; j++)\n\t\t{\n\t\t\tint c, d;\n\t\t\tscanf(\"%d %d\", &c, &d);\n\t\t\tcards[i][c].push_back(d);\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfor (int j = 1; j <= 3; j++)\n\t\t{\n\t\t\tint s = (j == 1 ? 3 : 1);\n\t\t\tsort(cards[i][j].begin(), cards[i][j].end());\n\t\t\treverse(cards[i][j].begin(), cards[i][j].end());\n\t\t\twhile (cards[i][j].size() > s)\n\t\t\t\tcards[i][j].pop_back();\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfor (int j = 0; j < 4; j++)\n\t\t\tfor (int k = 0; k < 2; k++)\n\t\t\t\tdp2[j][k] = -INF64;\n\t\tdp2[0][0] = 0;\n\t\tvector<pair<int, int> > cur;\n\t\tfor (int j = 1; j <= 3; j++)\n\t\t\tfor (auto x : cards[i][j])\n\t\t\t\tcur.push_back(make_pair(j, x));\n\t\tsort(cur.begin(), cur.end());\n\t\tdo\n\t\t{\n\t\t\tint mana = 3;\n\t\t\tli score = 0;\n\t\t\tli mx = 0;\n\t\t\tint cnt = 0;\n\t\t\tfor (auto x : cur)\n\t\t\t{\n\t\t\t\tcnt++;\n\t\t\t\tif (mana < x.first)\n\t\t\t\t\tbreak;\n\t\t\t\tmana -= x.first;\n\t\t\t\tmx = max(mx, li(x.second));\n\t\t\t\tscore += x.second;\n\t\t\t\tdp2[cnt][0] = max(dp2[cnt][0], score);\n\t\t\t\tdp2[cnt][1] = max(dp2[cnt][1], score + mx);\n\t\t\t}\n\t\t} while (next_permutation(cur.begin(), cur.end()));\n\t\tfor(int j = 0; j < 10; j++)\n\t\t\tfor (int k = 0; k <= 3; k++)\n\t\t\t{\n\t\t\t\tint nxt = (j + k) % 10;\n\t\t\t\tint f = (j + k >= 10 ? 1 : 0);\n\t\t\t\tdp[i + 1][nxt] = max(dp[i + 1][nxt], dp[i][j] + dp2[k][f]);\n\t\t\t}\n\t}\n\tli ans = 0;\n\tfor (int i = 0; i <= 9; i++)\n\t\tans = max(ans, dp[n][i]);\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1178",
    "index": "A",
    "title": "Prime Minister",
    "statement": "Alice is the leader of the State Refactoring Party, and she is about to become the prime minister.\n\nThe elections have just taken place. There are $n$ parties, numbered from $1$ to $n$. The $i$-th party has received $a_i$ seats in the parliament.\n\n\\textbf{Alice's party has number $1$}. In order to become the prime minister, she needs to build a coalition, consisting of her party and possibly some other parties. There are two conditions she needs to fulfil:\n\n- The total number of seats of all parties in the coalition must be a strict majority of all the seats, i.e. it must have \\textbf{strictly more than half} of the seats. For example, if the parliament has $200$ (or $201$) seats, then the majority is $101$ or more seats.\n- Alice's party must have \\textbf{at least $2$ times more} seats than any other party in the coalition. For example, to invite a party with $50$ seats, Alice's party must have at least $100$ seats.\n\nFor example, if $n=4$ and $a=[51, 25, 99, 25]$ (note that Alice'a party has $51$ seats), then the following set $[a_1=51, a_2=25, a_4=25]$ can create a coalition since both conditions will be satisfied. However, the following sets will not create a coalition:\n\n- $[a_2=25, a_3=99, a_4=25]$ since Alice's party is not there;\n- $[a_1=51, a_2=25]$ since coalition should have a strict majority;\n- $[a_1=51, a_2=25, a_3=99]$ since Alice's party should have \\textbf{at least $2$ times more} seats than any other party in the coalition.\n\n\\textbf{Alice does not have to minimise the number of parties in a coalition.} If she wants, she can invite as many parties as she wants (as long as the conditions are satisfied). If Alice's party has enough people to create a coalition on her own, she can invite no parties.\n\nNote that Alice can either invite a party as a whole or not at all. It is \\textbf{not possible} to invite only some of the deputies (seats) from another party. In other words, if Alice invites a party, she invites \\textbf{all} its deputies.\n\nFind and print any suitable coalition.",
    "tutorial": "Ignore the parties that have more than half of Alice's party seats. For all other parties it is never disadvantageous to include them in the coalition, so we might as well take all of them. If the resulting number of seats is a majority, we output all involved parties, otherwise the answer is $0$. The complexity is $\\mathcal O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n    int N; cin >> N;\n    vector<int> A(N); for (int&a:A) cin >> a;\n    vector<int> P{1};\n    int rest = 0, cur = A[0];\n    for (int i = 1; i < N; ++i) {\n        if (A[i] <= A[0]/2) {  \n            cur += A[i];\n            P.push_back(i+1);\n        } else {\n            rest += A[i];\n        }\n    }\n\n    if (cur > rest) {\n        cout << P.size() << endl;\n        for (int i = 0; i < P.size(); ++i) cout << P[i] << \" \\n\"[i==P.size()-1];\n    } else {\n        cout << 0 << endl;\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1178",
    "index": "B",
    "title": "WOW Factor",
    "statement": "Recall that string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly zero or all) characters. For example, for the string $a$=\"wowwo\", the following strings are subsequences: \"wowwo\", \"wowo\", \"oo\", \"wow\", \"\", and others, but the following are not subsequences: \"owoo\", \"owwwo\", \"ooo\".\n\nThe wow factor of a string is the number of its subsequences equal to the word \"wow\". Bob wants to write a string that has a large wow factor. However, the \"w\" key on his keyboard is broken, so he types two \"v\"s instead.\n\nLittle did he realise that he may have introduced more \"w\"s than he thought. Consider for instance the string \"ww\". Bob would type it as \"vvvv\", but this string actually contains three occurrences of \"w\":\n\n- \"{\\underline{\\textbf{vv}}vv}\"\n- \"{v\\underline{\\textbf{vv}}v}\"\n- \"{vv\\underline{\\textbf{vv}}}\"\n\nFor example, the wow factor of the word \"vvvovvv\" equals to four because there are four wows:\n\n- \"{\\underline{\\textbf{vv}}v\\underline{\\textbf{o}\\textbf{vv}}v}\"\n- \"{\\underline{\\textbf{vv}}v\\underline{\\textbf{o}}v\\underline{\\textbf{vv}}}\"\n- \"{v\\underline{\\textbf{vv}\\textbf{o}\\textbf{vv}}v}\"\n- \"{v\\underline{\\textbf{vv}\\textbf{o}}v\\underline{\\textbf{vv}}}\"\n\nNote that the subsequence \"{\\underline{\\textbf{v}}v\\underline{\\textbf{v}\\textbf{o}\\textbf{vv}}v}\" does not count towards the wow factor, as the \"v\"s have to be consecutive.\n\nFor a given string $s$, compute and output its wow factor. Note that it is \\textbf{not} guaranteed that it is possible to get $s$ from another string replacing \"w\" with \"vv\". For example, $s$ can be equal to \"vov\".",
    "tutorial": "We find all maximal blocks of vs. If there are $k$ of them, we replace the block with $k-1$ copies of w. After that, we can use a simple DP for finding the number of subsequences equal to wow. Complexity $\\mathcal O(n)$.",
    "code": "#include <iostream>\n#include <string>\n\nusing namespace std;\ntypedef long long ll;\n\nint main() {\n    string S; cin >> S;\n    ll a = 0, b = 0, c = 0;    \n    for (int i = 0; i < S.size(); ++i) {\n        if (S[i] == 'o') {\n            b += a;\n        } else if (i > 0 && S[i-1] == 'v') {\n            a++;\n            c += b;\n        }\n    }\n    cout << c << endl;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1178",
    "index": "C",
    "title": "Tiles",
    "statement": "Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor — a square tile that is diagonally split into white and black part as depicted in the figure below.\n\nThe dimension of this tile is perfect for this kitchen, as he will need exactly $w \\times h$ tiles without any scraps. That is, the width of the kitchen is $w$ tiles, and the height is $h$ tiles. As each tile can be rotated in one of four ways, he still needs to decide on how exactly he will tile the floor. There is a single aesthetic criterion that he wants to fulfil: two adjacent tiles must not share a colour on the edge — i.e. one of the tiles must have a white colour on the shared border, and the second one must be black.\n\n\\begin{center}\nThe picture on the left shows one valid tiling of a $3 \\times 2$ kitchen. The picture on the right shows an invalid arrangement, as the bottom two tiles touch with their white parts.\n\\end{center}\n\nFind the number of possible tilings. As this number may be large, output its remainder when divided by $998244353$ (a prime number).",
    "tutorial": "Observe that for a fixed pair of tiles $(i-1, j)$ and $(i, j-1)$ there is exactly one way of placing a tile at $(i, j)$ that satisfies the conditions. As a result, when all tiles $(1,i)$ and $(j,1)$ are placed, the rest is determined uniquely. We only need to count the number of ways to tile the first row and first column. There are four ways of placing the tile on $(1,1)$. After that, each tile in the first row or first column has exactly two ways of being placed. The answer is $2^{w + h}$. The complexity is $\\mathcal O(w+h)$ or $\\mathcal O(\\log w + \\log h)$ if we use binary exponentiation. Bonus: Hexagonal tiles and hexagonal kitchen.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconstexpr int MOD = 998244353;\n    \nint main() {\n    int R, C; cin >> R >> C;\n    int X = 1;\n    while (R--) X = (2*X)%MOD;\n    while (C--) X = (2*X)%MOD;\n    cout << X << endl;\n}",
    "tags": [
      "combinatorics",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1178",
    "index": "D",
    "title": "Prime Graph",
    "statement": "Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!\n\nWhen building the graph, he needs four conditions to be satisfied:\n\n- It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops.\n- The number of vertices must be exactly $n$ — a number he selected. This number is not necessarily prime.\n- The total number of edges must be prime.\n- The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime.\n\nBelow is an example for $n = 4$. The first graph (left one) is invalid as the degree of vertex $2$ (and $4$) equals to $1$, which is not prime. The second graph (middle one) is invalid as the total number of edges is $4$, which is not a prime number. The third graph (right one) is a valid answer for $n = 4$.\n\nNote that the graph can be disconnected.\n\nPlease help Bob to find any such graph!",
    "tutorial": "A solution always exists. We show a simple construction. For $n = 3$, a triangle is (the only) solution. For $n \\geq 4$ we make a cycle on $n$ vertices: $1 \\leftrightarrow 2 \\leftrightarrow 3 \\dots n \\leftrightarrow 1$. The degree of each vertex is $2$ (a prime number), but the total number of edges - $n$ - might not be. For some $k$, we add edges of form $i \\leftrightarrow i + \\frac{n}{2}$ for all $i$ from $1$ to $k$. If $k \\leq \\frac{n}{2}$, each vertex gets at most one more neighbor, having degree $3$. Fortunately for us, for each $n \\geq 3$ there is a prime number in interval $[n, \\frac{3n}{2}]$, simply the smallest of them will do. The time complexity is $\\mathcal O(n)$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nbool prime(int x) {\n    if (x < 2) return false;\n    for (int i = 2; i*i <= x; ++i) {\n        if (x%i == 0) return false;\n    }\n    return true;\n}\n\n\nint main(int argc, char ** argv){\n\tint n; cin >> n;\n    int m = n;\n    while (!prime(m)) ++m;\n    cout << m << \"\\n1 \" << n << '\\n';\n    for (int i = 0; i < n-1; ++i) {\n        cout << i+1 << ' ' << i+2 << '\\n';\n    }\n\n    for (int i = 0; i < m-n; ++i) {\n        cout << i+1 << ' ' << i+1+n/2 << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1178",
    "index": "E",
    "title": "Archaeology",
    "statement": "Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?\n\nThe book contains a single string of characters \"a\", \"b\" and \"c\". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides.\n\nHelp Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.\n\nA string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.",
    "tutorial": "The answer always exists. Let's prove by induction on $|s|$, giving a construction in the process. $|s| = 0 \\Rightarrow t =$ empty string, $|s| \\leq 3 \\Rightarrow t = s[0]$, $|s| \\geq 4 \\Rightarrow$. Let $t'$ be solution for $s[2:-2]$, which exists due to induction. As $s[0] \\neq s[1]$ and $s[-1] \\neq s[-2]$, there is at least one character 'x' that occurs in one of $s[0], s[1]$ and $s[-1], s[-2]$. Then $t = x t' x$ is a palindrome and its length is $|t| = 2 + |t'| \\geq 2 + \\lfloor \\dfrac{|s[2:-2]|}{2} \\rfloor = 2 + \\lfloor \\dfrac{|s|-4}{2} \\rfloor = \\lfloor \\dfrac{|s|}{2} \\rfloor\\,.$ $|t| = 2 + |t'| \\geq 2 + \\lfloor \\dfrac{|s[2:-2]|}{2} \\rfloor = 2 + \\lfloor \\dfrac{|s|-4}{2} \\rfloor = \\lfloor \\dfrac{|s|}{2} \\rfloor\\,.$ The time complexity is $\\mathcal O(|s|)$. Bonus: Find a subpalindrome of length at least $\\lceil \\frac{|s|}{2} \\rceil$.",
    "code": "#include <iostream>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\nint main() {\n    string S; cin >> S;\n    int N = S.size();\n    int i = 0, j = N-1;\n    string A;\n    while (j-i >= 3) {\n        if (S[i] == S[j]) {\n            A.push_back(S[i]);\n            ++i; --j;\n        } else if (S[i] == S[j-1]) {\n            A.push_back(S[i]);\n            ++i; j -= 2;\n        } else {\n            A.push_back(S[i+1]);\n            if (S[i+1] == S[j]) {\n                --j;\n            } else {\n                j -= 2;\n            }\n            i += 2;\n        }\n    }\n    string B = A;\n    if (j >= i) A.push_back(S[i]);\n    reverse(B.begin(),B.end());\n    cout << A << B << endl;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1178",
    "index": "F1",
    "title": "Short Colorful Strip",
    "statement": "\\textbf{This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of $m$ and the time limit. You need to solve both subtasks in order to hack this one.}\n\nThere are $n+1$ distinct colours in the universe, numbered $0$ through $n$. There is a strip of paper $m$ centimetres long initially painted with colour $0$.\n\nAlice took a brush and painted the strip using the following process. For each $i$ from $1$ to $n$, \\textbf{in this order}, she picks two integers $0 \\leq a_i < b_i \\leq m$, such that the segment $[a_i, b_i]$ is currently painted with a \\textbf{single} colour, and repaints it with colour $i$.\n\nAlice chose the segments in such a way that each centimetre is now painted in some colour other than $0$. Formally, the segment $[i-1, i]$ is painted with colour $c_i$ ($c_i \\neq 0$). Every colour other than $0$ is visible on the strip.\n\nCount the number of different pairs of sequences $\\{a_i\\}_{i=1}^n$, $\\{b_i\\}_{i=1}^n$ that result in this configuration.\n\nSince this number may be large, output it modulo $998244353$.",
    "tutorial": "Let $LO[l][r]$ be the lowest ID of a colour used in the final strip on interval $[l,r]$. Let $I[c]$ be the position on which the colour $c$ occurs on the target strip. We solve this problem by computing $DP[l][r]$ - the number of ways of painting the interval $[l,r]$, given that it is painted with a single colour and all subsequent colouring intervals must be either completely inside or completely outside of this interval. The first colour used on this interval will be $c = LO[l][r]$. How can we choose to paint it? Clearly, we can choose any interval $[a,b]$ such that $l \\leq a \\leq I[c] \\leq b \\leq r$. Once we perform this operation, then $I[c]$ can never be recoloured, and the interval $[l,r]$ is split into four single coloured intervals (possibly empty) that can be solved independently. This gives us $DP[l][r] = \\sum_a \\sum_b DP[l][a-1] * DP[a][I[c]-1] * DP[I[c]+1][b] * DP[b+1][r]$ which can be computed naively in $\\mathcal O(n^4)$. To optimise it to $\\mathcal O(n^3)$ just note that the selection of $a$ and $b$ is independent.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ntemplate <unsigned int N> class Field {\n    typedef unsigned int ui;\n    typedef unsigned long long ull;\npublic:\n    inline Field(int x = 0) : v(x) {}\n    inline Field<N>&operator+=(const Field<N>&o) {if (v+o.v >= N) v += o.v - N; else v += o.v; return *this; }\n    inline Field<N>&operator*=(const Field<N>&o) {v=(ull)v*o.v % N; return *this; }\n    inline Field<N> operator*(const Field<N>&o) const {Field<N>r{*this};return r*=o;}\n\tinline explicit operator ui() const { return v; }\nprivate: ui v;\n};\ntemplate<unsigned int N>ostream &operator<<(std::ostream&os,const Field<N>&f){return os<<(unsigned int)f;}\ntemplate<unsigned int N>Field<N> operator*(int i,const Field<N>&f){return Field<N>(i)*f;}\n\ntypedef Field<998244353> F;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    \n    int N, M; cin >> N >> M;\n    vector<int> C(N); for (int &c: C) { cin >> c; --c; }\n    \n    vector<vector<F>> D(N+1, vector<F>(N+1, 1));\n    for (int l = 1; l <= M; ++l) {\n        for (int a = 0; a + l <= M; ++a) {\n            pair<int,int> lo = {C[a],0};\n            for (int i = 0; i < l; ++i) lo = min(lo, {C[a+i],i});\n            int j = lo.second;\n            if (j < 0 || j >= l) { D[a][l] = 0; continue; }\n            F left = 0, right = 0;\n            for (int u = 0; u <= j; ++u) left += D[a][u] * D[a+u][j-u];\n            for (int v = j+1; v <= l; ++v) right += D[a+j+1][v-(j+1)] * D[a+v][l-v];\n            D[a][l] = left * right;\n        }\n    }\n    \n    cout << D[0][N] << endl;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1178",
    "index": "F2",
    "title": "Long Colorful Strip",
    "statement": "\\textbf{This is the second subtask of problem F. The only differences between this and the first subtask are the constraints on the value of $m$ and the time limit. It is sufficient to solve this subtask in order to hack it, but you need to solve both subtasks in order to hack the first one.}\n\nThere are $n+1$ distinct colours in the universe, numbered $0$ through $n$. There is a strip of paper $m$ centimetres long initially painted with colour $0$.\n\nAlice took a brush and painted the strip using the following process. For each $i$ from $1$ to $n$, \\textbf{in this order}, she picks two integers $0 \\leq a_i < b_i \\leq m$, such that the segment $[a_i, b_i]$ is currently painted with a \\textbf{single} colour, and repaints it with colour $i$.\n\nAlice chose the segments in such a way that each centimetre is now painted in some colour other than $0$. Formally, the segment $[i-1, i]$ is painted with colour $c_i$ ($c_i \\neq 0$). Every colour other than $0$ is visible on the strip.\n\nCount the number of different pairs of sequences $\\{a_i\\}_{i=1}^n$, $\\{b_i\\}_{i=1}^n$ that result in this configuration.\n\nSince this number may be large, output it modulo $998244353$.",
    "tutorial": "There are several additional observations we need compared to previous subtask. First, note that if we ever colour a pair of positions with different colours, they will forever stay coloured with different colours. In other words, if two positions have the same colour in the final strip, the set of colours they were coloured with is the same. As a result, we can compress the input by removing consecutive equal values. Next, we look at the number of changes in the strip. A change is a position $i$ such that $c_i \\neq c_{i+1}$. Initially, there are $0$ changes, and each operation adds at most $2$ changes. As a result, if the length of the input after the compression is more than $2n$, we can immediately print $0$. Now we can use the DP as in previous tasks, but there is one more complication to resolve. Consider the third sample: The DP suggests that $DP[0][2] = DP[0][0] * DP[2][2] = 1$. The reason why we get a wrong answer is that we treat the intervals $[0,0]$ and $[2,2]$ as independent, but in reality they are not. To fix this, instead of finding a single value of $I[c]$, we set $I'[c]$ to be all positions (in the whole array) containing colour $c$. We can then pick $l \\leq a \\leq \\min(I'[c])$ and $\\max(I'[c]) \\leq b \\leq r$. For this to be possible, all occurrences of the colour $c$ must be within interval $[l,r]$, otherwise $D[l][r] = 0$. The occurrences of colour $c$ and the indices $a$ and $b$ now can split the interval $[l,r]$ into more than $4$ segments, but this does not affect the complexity. Final complexity is $\\mathcal O(n^3 + m)$. Bonus (courtesy of [user:Um_nik]): Can you solve it faster?",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ntemplate <unsigned int N> class Field {\n    typedef unsigned int ui;\n    typedef unsigned long long ull;\npublic:\n    inline Field(int x = 0) : v(x) {}\n\tinline Field<N> pow(int p){return (*this)^p; }\n    inline Field<N>&operator+=(const Field<N>&o) {if (v+o.v >= N) v += o.v - N; else v += o.v; return *this; }\n    inline Field<N>&operator*=(const Field<N>&o) {v=(ull)v*o.v % N; return *this; }\n    inline Field<N> operator*(const Field<N>&o) const {Field<N>r{*this};return r*=o;}\n\tinline explicit operator ui() const { return v; }\nprivate: ui v;\n};\ntemplate<unsigned int N>ostream &operator<<(std::ostream&os,const Field<N>&f){return os<<(unsigned int)f;}\ntemplate<unsigned int N>Field<N> operator+(int i,const Field<N>&f){return Field<N>(i)+f;}\ntemplate<unsigned int N>Field<N> operator*(int i,const Field<N>&f){return Field<N>(i)*f;}\n\ntypedef Field<998244353> F;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    \n    int N, M; cin >> N >> M;\n    vector<int> C(M); for (int &c: C) { cin >> c; --c; }\n    vector<int> W;\n    for (int i = 0; i < M; ++i) if (W.empty() || W.back() != C[i]) W.push_back(C[i]);\n    M = W.size();\n    if (M > 2*N) { cout << \"0\\n\"; return 0; }\n    vector<vector<int>> E(N);\n    for (int i = 0; i < M; ++i) E[W[i]].push_back(i);\n       \n    vector<vector<F>> D(M+1, vector<F>(M+1, 1));\n    for (int l = 1; l <= M; ++l) {\n        for (int a = 0; a + l <= M; ++a) {\n            int lo = W[a];\n            for (int i = 0; i < l; ++i) lo = min(lo, W[a+i]);\n            int j = E[lo][0] - a;\n            int k = E[lo].back() - a;\n            if (j < 0 || k >= l) { D[a][l] = 0; continue; }\n            F left = 0, right = 0;\n            for (int u = 0; u <= j; ++u) left += D[a][u] * D[a+u][j-u];\n            for (int v = k+1; v <= l; ++v) right += D[a+k+1][v-(k+1)] * D[a+v][l-v];\n            D[a][l] = left * right;\n            for (int m = 0; m < E[lo].size()-1; ++m) {\n                if (E[lo][m] + 1 != E[lo][m+1]) {\n                    D[a][l] *= D[E[lo][m]+1][E[lo][m+1] - E[lo][m] - 1];\n                }\n            }\n        }\n    }\n    \n    cout << D[0][M] << endl;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1178",
    "index": "G",
    "title": "The Awesomest Vertex",
    "statement": "You are given a rooted tree on $n$ vertices. The vertices are numbered from $1$ to $n$; the root is the vertex number $1$.\n\nEach vertex has two integers associated with it: $a_i$ and $b_i$. We denote the set of all ancestors of $v$ (including $v$ itself) by $R(v)$. The awesomeness of a vertex $v$ is defined as\n\n$$\\left| \\sum_{w \\in R(v)} a_w\\right| \\cdot \\left|\\sum_{w \\in R(v)} b_w\\right|,$$\n\nwhere $|x|$ denotes the absolute value of $x$.\n\nProcess $q$ queries of one of the following forms:\n\n- 1 v x — increase $a_v$ by a positive integer $x$.\n- 2 v — report the maximum awesomeness in the subtree of vertex $v$.",
    "tutorial": "Denote $c_v = \\sum_{w \\in R(v)} a_w$ and $d_v = \\sum_{w \\in R(v)} b_w$. Let's solve a simpler task first, where we assume that all $a_i$ and $b_i$ are positive, and all updates and queries are on the root vertex. We can see that we are looking into maximum $\\left(x + c_v \\right) \\cdot d_v$ = $c_vd_v + xd_v$, where $x$ is the cumulative sum of updates until this point. For a given $x$, this can be solved in $\\mathcal O(\\log n)$ using convex hull trick. How do we handle negative values of $a_i$ and $b_i$? We simply try all the lines $-c_vd_v - xd_v$ as well. The second issue is that our updates and queries can occur on arbitrary vertices. We can linearise the tree using DFS - then subtree of a vertex corresponds to an interval in the array. Afterwards, we use sqrt-decomposition in a fairly standard way: We partition the array into blocks of size roughly $\\sqrt n$, build a convex hull trick structure on each of them, and remember the value of $x$ for each of them separately. Given an update, some blocks are untouched, in some we just need to update $x$ in constant time, and there are at most two blocks which are updated partially, which we rebuild from scratch. Given a query, we can use the convex hull trick structure to get the maximum in a block that is fully covered by the query. Again, we have at most two blocks that are partially intersected - there we can brute force the maximum. This yields a $\\mathcal O(n + q \\sqrt n \\log n)$ algorithm. You just want contribution, go away! Oh wait, you're right. This solution has a rather large constant factor, so let's not stop there. What do we need the $\\log n$ factor for? Two things: sorting all the lines by slope and determining the best line in a convex hull trick structure. Let's get rid of both - firstly, as $b_i$ doesn't change, we can sort once before processing any queries. Secondly, notice that the updates only add positive values, thus we only ever query lines with increasing $x$. Hence, no binary search is needed - we can simply advance a pointer over the structure in $\\mathcal O(1)$ amortised. Overall complexity becomes $\\mathcal O(n \\log n + q \\sqrt n)$. There, no marmots harmed. One final remark - the cost of building a convex hull structure in a block is slightly higher than that of iterating over the blocks. It seems that the most efficient size of the block is $\\sqrt{n/6}$. This final observation was not needed to get AC.",
    "code": "#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <cassert>\n#include <cmath>\nusing namespace std;\n\n#define x first\n#define y second\ntypedef std::pair<int,int> pii; typedef long long ll; typedef unsigned long long ull; typedef unsigned int ui; typedef pair<ui,ui> puu;\n\ntemplate<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}\ntemplate <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }\n\nbool fractionGreaterOrEqual(double a, double b, double c, double d) {\n\treturn a/b >= c/d;\n}\n\nint TOTAL;\n\n/* UpperEnvelope that with O(N) build and amortized O(1) query.\n * The updates need be sorted by (m,b), the queries need to be sorted by x, and\n * updates need to come before queries. */\nnamespace LinearEnvelope {\n\ttemplate<typename T> struct Line { T m, b; int id; };\n\n\ttemplate <typename T>\n\tstruct Upper {\n\t\tLine<T> *V;\n\t\tT t; int i, s;\n\n\t\tUpper(int w) : V(new Line<T>[w]), t(0), i(0), s(0) { TOTAL++; }\n\t\t~Upper() { TOTAL--; }\n\t\t//~Upper() { delete []V; }\n\t\tvoid clear() { i = s = 0; t = 0; }\n\n\t\tvoid insert_line(T m, T b, int i = 0) {\n\t\t\tassert(t == 0);\n\t\t\tif (s > 0 && V[s-1].m == m && V[s-1].b >= b) return;\n\t\t\twhile (s > 0 && ((V[s-1].b < b) || (V[s-1].b == b && V[s-1].m < m))) --s;\n\t\t\twhile (s >= 2 && fractionGreaterOrEqual(V[s-2].b - V[s-1].b, V[s-1].m - V[s-2].m, V[s-1].b - b, m - V[s-1].m)) --s;\n\t\t\tV[s++] = {m,b,i};\n\t\t}\n\n\t\tpair<T,int> advance(T x) {\n\t\t\tassert(x >= 0);\n\t\t\tt += x;\n\t\t\twhile (i+1 < s && V[i].m * t + V[i].b < V[i+1].m * t + V[i+1].b) ++i;\n\t\t\treturn {V[i].m * t + V[i].b, V[i].id};\n\t\t}\n\t};\n};\n\n\nclass RPPS {\npublic:\n    vector<vector<int>> E;\n    vector<ll> A,B,RA,RB;\n    vector<int> Enter,Exit;\n    int T;\n\n    void dfs(int u, ll a, ll b) {\n        A[u] += a;\n        B[u] += b;\n        Enter[u] = T++;\n        for (int v:E[u]) dfs(v, A[u], B[u]);\n        Exit[u] = T;\n    }\n\n    struct Block {\n        Block(int L, int R, const vector<ll>&A, const vector<ll>&B) : U(2*(R-L)), L(L), R(R), off(0), cur(0) {\n            for (int i = L; i < R; ++i) W.push_back({{B[i], A[i]*B[i]}, i});\n            for (int i = L; i < R; ++i) if (A[i] < 0 || B[i] < 0) W.push_back({{-B[i], -A[i]*B[i]}, i});\n            sort(W.begin(),W.end());\n            build();\n        }\n\n        void build() {\n            U.clear();\n            for (auto &w:W) U.insert_line(w.x.x, w.x.y);\n            cur = U.advance(0LL).x;\n        }\n\n        void add(int l, int r, ll x) {\n            if (l >= R || r <= L) return;\n            else if (l <= L && r >= R) {\n                cur = U.advance(x).x;\n                off += x;\n            } else {\n                for (auto &w:W) {\n                    w.x.y += w.x.x * off;\n                    if (in(l, w.y, r)) {\n                        w.x.y += w.x.x * x;\n                    }\n                }\n                off = 0;\n                build();\n            }\n        }\n\n        ll get(int l, int r) {\n            if (l >= R || r <= L) return numeric_limits<ll>::min();\n            else if (l <= L && r >= R) return cur;\n            else {\n                ll ans = numeric_limits<ll>::min();\n                for (auto &w:W) {\n                    if (in(l, w.y, r)) {\n                        ans = max(ans, w.x.x * off + w.x.y);\n                    }\n                }\n                return ans;\n            }\n        }\n\n        LinearEnvelope::Upper<ll> U;\n        vector<pair<pair<ll,ll>,int>> W;\n        int L, R;\n        ll off, cur;\n    };\n\nvoid solve(istream& cin, ostream& cout) {\n    TOTAL = 0;\n    int N, Q; cin >> N >> Q;\n    E.resize(N);\n    A.resize(N);\n    B.resize(N);\n    RA.resize(N);\n    RB.resize(N);\n    Enter.resize(N);\n    Exit.resize(N);\n\n    for (int i = 1; i < N; ++i) {\n        int p; cin >> p; --p;\n        E[p].push_back(i);\n    }\n    cin >> A >> B;\n\n    T = 0;\n    dfs(0, 0, 0);\n\n    for (int i = 0; i < N; ++i) {\n        RA[Enter[i]] = A[i];\n        RB[Enter[i]] = B[i];\n    }\n\n    int BS = max(1,(int)sqrt(N/6));\n    vector<Block> D;\n    D.reserve(1+(N-1)/BS);\n    for (int i = 0; i < N; i+=BS) D.emplace_back(i, min(i+BS,N), RA, RB);\n    \n    ll diff = 0;\n    for (int q = 0; q < Q; ++q) {\n        int t,v; cin >> t >> v;\n        --v;\n        if (t == 1) {\n            ll x; cin >> x;\n            for (Block&b:D) b.add(Enter[v],Exit[v],x);\n        } else {\n            ll ans = numeric_limits<ll>::min();\n            for (Block&b:D) ans = max(ans, b.get(Enter[v],Exit[v]));\n            cout << ans << '\\n';\n        }\n    }\n}\n};\n\n\nint main() {\n\tios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);\n\tRPPS solver;\n\tstd::istream& in(std::cin);\n\tstd::ostream& out(std::cout);\n\tsolver.solve(in, out);\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1178",
    "index": "H",
    "title": "Stock Exchange",
    "statement": "\\textbf{Warning: This problem has an unusual memory limit!}\n\nBob decided that he will not waste his prime years implementing GUI forms for a large corporation and instead will earn his supper on the Stock Exchange Reykjavik. The Stock Exchange Reykjavik is the only actual stock exchange in the world. The only type of transaction is to take a single share of stock $x$ and exchange it for a single share of stock $y$, provided that the current price of share $x$ is at least the current price of share $y$.\n\nThere are $2n$ stocks listed on the SER that are of interest to Bob, numbered from $1$ to $2n$. Bob owns a single share of stocks $1$ through $n$ and would like to own a single share of each of $n+1$ through $2n$ some time in the future.\n\nBob managed to forecast the price of each stock — in time $t \\geq 0$, the stock $i$ will cost $a_i \\cdot \\lfloor t \\rfloor + b_i$. The time is currently $t = 0$. Help Bob find the earliest moment in time in which he can own a single share of each of $n+1$ through $2n$, and the minimum number of stock exchanges he has to perform in order to do that.\n\nYou may assume that the Stock Exchange has an unlimited amount of each stock at any point in time.",
    "tutorial": "Lemma: If there is a solution $S$ for time $T$, there is also a solution $S'$ for time $T$ using not more exchanges than $S$, in which all exchanges occur either in time $0$ or in time $T$. Proof: Induction on $n$ - the number of exchanges not happening in time $0$ or $T$. If $n = 0$, we are done. Otherwise, pick an arbitrary exchange $i \\rightarrow j$ at time $t$. There are a few cases: There is an exchange $j \\rightarrow k$ at time $t$. We can substitute both by exchange $i \\rightarrow k$. There is an exchange $k \\rightarrow i$ at time $t$. We can substitute both by exchange $k \\rightarrow j$. If $a[i] \\geq a[j]$ and there is an exchange $j \\rightarrow k$ in time $t < t_1 < T$. We substitute both with exchange $i \\rightarrow k$ in time $t_1$. otherwise, postpone the exchange to time $T$ there is an exchange $j \\rightarrow k$ in time $t < t_1 < T$. We substitute both with exchange $i \\rightarrow k$ in time $t_1$. otherwise, postpone the exchange to time $T$ If $a[i] < a[j]$ and there is an exchange $k \\rightarrow i$ in time $0 < t_1 < t$. We substitute both with exchange $k \\rightarrow j$ in time $t_1$. otherwise, prepone the exchange to time $0$ there is an exchange $k \\rightarrow i$ in time $0 < t_1 < t$. We substitute both with exchange $k \\rightarrow j$ in time $t_1$. otherwise, prepone the exchange to time $0$ Thanks to this lemma, and the fact that we can get rid of transitive exchanges happening at the same time, we can model this problem as min-cost max-flow on $4N+2$ vertices. Let there be vertices $u_i$ and $v_i$ for each stock, and $s$ and $t$ are source and sink, respectively. There are edges of six types: Edge $s \\rightarrow u_i$ for all $0 \\leq i < N$ with capacity $1$ and cost $0$ (representing the starting stock). Edge $u_i \\rightarrow v_i$ for all $0 \\leq i < N$ with capacity $1$ and cost $0$ (representing stock not exchanged at $t = 0$). Edge $u_i \\rightarrow v_j$ for all $0 \\leq i < N$ and $j$ such that $B[i] \\geq B[j]$, with capacity $1$ and cost $1$ (representing an exchange at $t = 0$). Edge $v_i \\rightarrow u_i$ for all $N \\leq i < 2N$ with capacity $1$ and cost $0$ (representing stock not exchanged at $t = T$). Edge $v_i \\rightarrow u_j$ for all $0 \\leq i < 2N$ and $N \\leq j < N$ sucht that $A[i]*T + B[i] \\geq A[j]*T + B[j]$, with capacity $1$ and cost $1$ (representing an exchange at $t = T$). Edge $u_i \\rightarrow t$ for all $N \\leq i < 2N$ with capacity $1$ and cost $0$ (representing desired stock). If the flow size equals $N$, then there exists a strategy. The number of exchanges equals to the cost of the flow. This combined runs in $O(N^3 \\log N \\log MAX)$ using e.g. preflow-push. Even when considering the fact that the bounds on flow algorithms are often not tight, this is not very promising. Furthermore, it uses $O(N^2)$ memory, which is clearly too much. Let's improve it. Removing $\\log MAX$ factor: The first observation is that we don't need to run the MCMF for every iteration of the binary search - we don't need the cost, all that is required is deciding whether max-flow size is $N$. There are many approaches to this, perhaps the simplest one is to solve it in $O(N \\log N)$: At time $T$, exchange each stock to the most expensive stock at $t = T$ that we can afford to exchange at $t = 0$. Check whether at time $t = T$ the prices of stocks obtained this way dominate the prices of the desired stocks. Reducing the space complexity: Note that the edges of type $3$ and $5$ connect a stock $i$ to some subset of stocks $j$. This subset of stocks is a prefix of the array of stocks sorted by their price. We can thus connect each stock only to the most expensive stock to which it can be exchanged, and connect these in order of decreasing price with edges of capacity $N$ and cost $0$ (make sure the ties are broken correctly). This way, we reduce the number of edges from quadratic to $12N$, improving the space complexity. Reducing to $O(N^2 \\log N)$ time: The maximum flow is capped by $N$. In such a setting primal methods such as Ford-Fulkerson, respectively it's MCMF version called Successive Shortest Paths Algorithm, behave quite well, needing only $O(f \\cdot |E| \\log |E|) = O(N^2 \\log N)$ time. Reducing to $O(N^2)$ time: However, in our problem, the costs are also bounded by a small constant, namely $0$ or $1$. In Dijsktra's algorithm, the subroutine of SSPA, one can use a fixed size array instead of a priority queue, reducing the complexity even further. This last optimisation is difficult to separate, so with a reasonable implementation it is not necessary to get AC. The total complexity is thus $O(N \\log N \\log MAX + N^2)$.",
    "code": "#include <vector>\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\n#define x first\n#define y second\ntypedef long long ll; \n\ntemplate<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}\n\n\n/** Successive shortest paths algorithm. Runs in O(maxFlow * (|E| + sumCosts)). */\ntemplate<typename Cap = int, typename Cost = int>\nstruct SSPA {\n    struct Edge{\n        Cost c; Cap f; int to, rev;\n        Edge(int _to, Cost _c, Cap _f, int _rev):c(_c), f(_f), to(_to), rev(_rev){}\n    };\n    int N, source, sink;\n    vector<vector<Edge>> G;\n    SSPA(int N, int source, int sink): N(N), source(source), sink(sink), G(N) {}\n    void addEdge(int a, int b, Cap cap, Cost cost) {\n        assert(cap>=0);\n        assert(a>=0&&a<N&&b>=0&&b<N);\n        if(a==b){assert(cost>=0); return;}\n        G[a].emplace_back(b, cost, cap, G[b].size());\n        G[b].emplace_back(a, -cost, 0, G[a].size()-1);\n    }\n\n    pair<Cap, Cost> minCostMaxFlow() {\n        /* Vertex potentials. These are maintained so that all edges with non-zero\n         * residual have non-negative length. Thus, Dijkstra can be used instead of\n         * Bellman-Ford in each step of the algorithm. */\n        vector<Cost> Pi(N, 0);\n        Cost infty = std::numeric_limits<Cost>::max();\n        Cap totFlow = 0;\n        Cost totCost = 0;\n        while (true) {\n            vector<Cost> D(N, infty);\n            vector<int> Prev(N, -1);\n            D[source] = 0;\n\n            vector<vector<int>> Q{{source}};\n            for (int i = 0; i < Q.size(); ++i) {\n                for (int j = 0; j < Q[i].size(); ++j) {\n                    int u = Q[i][j];\n                    if (D[u] < i) continue;\n\n                    for (auto &e: G[u]) {\n                        if (e.f > 0) {\n                            Cost c = D[u] + e.c;\n                            if (D[e.to] > c) {\n                                D[e.to] = c;\n                                while (c >= Q.size()) Q.emplace_back();\n                                Q[c].push_back(e.to);\n                                Prev[e.to] = u;\n                            }\n                        }\n                    }\n                }\n            }\n\n            // if sink is unreachable, flow is optimal\n            if (D[sink] == infty) break;\n\n            // reconstruct some shortest path\n            int v = sink;\n            vector<int> Path;\n            while (v != -1) { Path.push_back(v); v = Prev[v]; }\n            reverse(Path.begin(),Path.end());\n\n            // found the minimum of the edge residuals along the path\n            Cap augment = std::numeric_limits<Cap>::max();\n            int L = Path.size();\n            for (int i = 0; i < L-1; ++i) {\n                int u = Path[i], v = Path[i+1];\n                for (auto&e: G[u]) {\n                    // be careful, there might be multiedges\n                    if (e.to == v && e.f > 0 && D[v] == D[u] + e.c) {\n                        augment = min(augment, e.f);\n                        break;\n                    }\n                }\n            }\n\n            for (int i = 0; i < L-1; ++i) {\n                int u = Path[i], v = Path[i+1];\n                for (auto&e: G[u]) {\n                    if (e.to == v && e.f > 0 && D[v] == D[u] + e.c) {\n                        e.f -= augment;\n                        G[v][e.rev].f += augment;\n                        break;\n                    }\n                }\n            }\n\n            // store the cost & flow size\n            Cost cost = Pi[source] - Pi[sink] + D[sink];\n            totFlow += augment;\n            totCost += cost * augment;\n\n            // remove potentials from costs\n            for (int i = 0; i < N; ++i) {\n                for (auto &e: G[i]) {\n                    e.c -= Pi[e.to] - Pi[i];\n                }\n            }\n\n\n            // add potentials to costs again\n            for (int i = 0; i < N; ++i) {\n                for (auto &e: G[i]) {\n                    e.c += (Pi[e.to] - D[e.to]) - (Pi[i] - D[i]);\n                }\n            }\n\n            // update potentials based on the results\n            for (int i = 0; i < N; ++i) Pi[i] -= D[i];\n\n        }\n        return {totFlow,totCost};\n    }\n};\n\nclass Stock {\npublic:\n    void solve(istream& cin, ostream& cout) {\n        int N; cin >> N;\n        vector<int> A(2*N), B(2*N);\n        for (int i = 0; i < 2*N; ++i) {\n            cin >> A[i] >> B[i];\n        }\n\n        // find T: O(N log MAX log N)\n        int T = bsl(0, 1000000000, [&](int t) {\n            // ( (price at 0) x (-price at t) x (is initial stock) )\n            vector<pair<pair<int, ll>, bool>> Stocks(2*N);\n            for (int i = 0; i < 2*N; ++i) {\n                Stocks[i] = {{B[i], -(A[i]*ll(t) + B[i])}, i<N};\n            }\n            sort(Stocks.begin(),Stocks.end());\n            ll best = 0;\n            vector<ll> CanHave, Required;\n            for (int i = 0; i < 2*N; ++i) {\n                best = max(best, -Stocks[i].x.y);\n                if (Stocks[i].y) {\n                    CanHave.push_back(best);\n                } else {\n                    Required.push_back(-Stocks[i].x.y);\n                }\n            }\n            sort(CanHave.begin(),CanHave.end());\n            sort(Required.begin(),Required.end());\n            for (int i = 0; i < N; ++i) {\n                if (CanHave[i] < Required[i]) return false;\n            }\n            return true;\n        });\n\n        if (T == -1) {\n            cout << -1 << endl;\n            return;\n        }\n\n        vector<pair<pair<int,ll>,int>> Begin(2*N);\n        vector<pair<ll, int>> End(2*N);\n        for (int i = 0; i < 2*N; ++i) {\n            ll end = A[i]*ll(T) + B[i];\n            // bigger start => process later\n            // bigger end => process earlier\n            Begin[i] = {{B[i], -end}, i};\n\n            // bigger end => process later\n            // bigger id => process earlier\n            End[i] = {end, -i};\n        }\n        sort(Begin.begin(),Begin.end());\n        sort(End.begin(),End.end());\n        reverse(Begin.begin(),Begin.end());\n        reverse(End.begin(),End.end());\n\n        // SSPA, using O(dijkstra * flow)\n        SSPA<int,int> G(6*N+2, 6*N, 6*N+1);\n        for (int i = 0; i < 2*N; ++i) {\n            if (i != 2*N-1) {\n                int j = Begin[i].y;\n                int k = Begin[i+1].y;\n                G.addEdge(N+j, N+k, N, 0); // perform exchange at t=0\n\n                j = -End[i].y;\n                k = -End[i+1].y;\n                G.addEdge(3*N+j, 3*N+k, N, 0); // perform exchange at t=T\n            }\n\n            if (Begin[i].y < N) {\n                int j = Begin[i].y;\n                G.addEdge(6*N, j, 1, 0); // super source\n                G.addEdge(j, N+j, 1, 1); // exchange for something at t=0\n                G.addEdge(j, 3*N+j, 1, 0); // hold until t=T\n            }\n\n            if ((-End[i].y) >= N) {\n                int j = -End[i].y;\n                G.addEdge(N+j, 5*N+(j-N), 1, 0); // was kept from t=0\n                G.addEdge(3*N+j, 5*N+(j-N), 1, 1); // was exchanged at t=T\n                G.addEdge(5*N+(j-N), 6*N+1, 1, 0); // super sink\n            }\n\n            G.addEdge(N+i, 3*N+i, N, 0); // hold between 0 and T\n        }\n\n        auto res = G.minCostMaxFlow();\n        assert(res.x == N);\n        cout << T << ' ' << res.y << '\\n';\n\n    }\n};\n\n\nint main() {\n\tios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);\n\tStock solver;\n\tstd::istream& in(std::cin);\n\tstd::ostream& out(std::cout);\n\tsolver.solve(in, out);\n    return 0;\n}",
    "tags": [
      "binary search",
      "flows",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1179",
    "index": "A",
    "title": "Valeriy and Deque",
    "statement": "Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $n$ elements. The $i$-th element is $a_i$ ($i$ = $1, 2, \\ldots, n$). He gradually takes the first two leftmost elements from the deque (let's call them $A$ and $B$, respectively), and then does the following: if $A > B$, he writes $A$ to the beginning and writes $B$ to the end of the deque, otherwise, he writes to the beginning $B$, and $A$ writes to the end of the deque. We call this sequence of actions an operation.\n\nFor example, if deque was $[2, 3, 4, 5, 1]$, on the operation he will write $B=3$ to the beginning and $A=2$ to the end, so he will get $[3, 4, 5, 1, 2]$.\n\nThe teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $q$ queries. Each query consists of the singular number $m_j$ $(j = 1, 2, \\ldots, q)$. It is required for each query to answer which two elements he will pull out on the $m_j$-th operation.\n\nNote that \\textbf{the queries are independent} and for each query the numbers $A$ and $B$ should be \\textbf{printed in the order in which they will be pulled out of the deque}.\n\nDeque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.",
    "tutorial": "It can be noted that if the deque has the largest element of the deque in the first position, then during the next operations it will remain in the first position, and the second one will be written to the end each time, that is, all the elements of the deque starting from the second will move cyclically left. Let's go over the deque and find the largest element by value. We will perform the operation described in the statements until the maximum position is in the first position and save the elements in the first and second positions by the operation number. In order to pre-calculate all pairs until the moment when the maximum position is found, it is enough to make no more than one pass through the deque, since in the worst case, the maximum element can be located at the end of the deque. Denote as $maxIndex$ the position of the maximum element. Then if $m_j <maxIndex$, simply return a pair of numbers from the pre-calculated array, otherwise $A$ is equal to the maximum element, and $B$ is equal to the deque element with the index $(m_j - (maxIndex + 1)) \\% (n - 1) + 1$ in $0$-indexing (since we performed the operations until the moment when the maximum position is in the first position, this maximum element is now recorded in the first position).",
    "code": "\"/// author: Mr.Hakimov\\n\\n#include <bits/stdc++.h>\\n#include <chrono>\\n\\n#define all(x) (x).begin(), (x).end()\\n#define fin(s) freopen(s, \\\"r\\\", stdin);\\n#define fout(s) freopen(s, \\\"w\\\", stdout);\\n\\nusing namespace std;\\n\\ntypedef long long LL;\\ntypedef long double LD;\\n\\nint TN = 1;\\n\\nvoid showDeque(deque<int> d) {\\n    int n = d.size();\\n    for (int i = 0; i < n; i++) {\\n        cout << d.front() << \\\" \\\";\\n        d.push_back(d.front());\\n        d.pop_front();\\n    }\\n    cout << endl << \\\"==\\\" << endl;\\n}\\n\\nvoid solve() {\\n    int n;\\n    int q;\\n    cin >> n >> q;\\n    deque<int> d;\\n    int maxValue = -1;\\n    for (int i = 0; i < n; i++) {\\n        int a_i;\\n        cin >> a_i;\\n        d.push_back(a_i);\\n        maxValue = max(maxValue, a_i);\\n    }\\n\\n    map<int, pair<int, int>> answer;\\n\\n    int maxIndex = 0;\\n    while (true) {\\n        /// showDeque(d);\\n        int first = d.front();\\n        d.pop_front();\\n        int second = d.front();\\n        d.pop_front();\\n\\n        if (first == maxValue) {\\n            d.push_front(second);\\n            d.push_front(first);\\n            break;\\n        }\\n\\n        maxIndex++;\\n        answer[maxIndex] = {first, second};\\n\\n        if (second > first) {\\n            swap(first, second);\\n        }\\n\\n        d.push_front(first);\\n        d.push_back(second);\\n    }\\n\\n    int a[n];\\n    /// showDeque(d);\\n    for (int i = 0; i < n; i++) {\\n        a[i] = d.front();\\n        d.pop_front();\\n    }\\n\\n    for (int i = 0; i < q; i++) {\\n        LL m_j;\\n        cin >> m_j;\\n        if (m_j <= maxIndex) {\\n            cout << answer[m_j].first << \\\" \\\" << answer[m_j].second << '\\\\n';\\n        } else {\\n            cout << maxValue << \\\" \\\" << a[(m_j - (maxIndex + 1)) % (n - 1) + 1] << '\\\\n';\\n        }\\n    }\\n}\\n\\nint main() {\\n    auto start = chrono::steady_clock::now();\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(nullptr); cout.tie(nullptr);\\n    /// =========================================\\n    /// fin(\\\"input.txt\\\"); fout(\\\"output.txt\\\");\\n    /// fin(\\\"file.in\\\"); fout(\\\"file.out\\\");\\n    /// cin >> TN;\\n    /// =========================================\\n    while (TN--) solve();\\n    auto finish = chrono::steady_clock::now();\\n    auto elapsed_ms = chrono::duration_cast<chrono::milliseconds>(finish - start);\\n    cerr << endl << \\\"Time: \\\" << elapsed_ms.count() << \\\" ms\\\\n\\\";\\n    return 0;\\n}\"",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1179",
    "index": "B",
    "title": "Tolik and His Uncle",
    "statement": "This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a \"Discuss tasks\" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.\n\nAfter a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.\n\nIn this task you are given a cell field $n \\cdot m$, consisting of $n$ rows and $m$ columns, where point's coordinates $(x, y)$ mean it is situated in the $x$-th row and $y$-th column, considering numeration from one ($1 \\leq x \\leq n, 1 \\leq y \\leq m$). Initially, you stand in the cell $(1, 1)$. Every move you can jump from cell $(x, y)$, which you stand in, by any non-zero vector $(dx, dy)$, thus you will stand in the $(x+dx, y+dy)$ cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).\n\nTolik's uncle is a very respectful person. Help him to solve this task!",
    "tutorial": "First, we are going to describe how to bypass $1 \\cdot m$ strip. This algorithm is pretty easy - $(1, 1)$ -> $(1, m)$ -> $(1, 2)$ -> $(1, m-1)$ -> $\\ldots$. Obviously all jumps have different vectors because their lengths are different. It turns out that the algorithm for $n \\cdot m$ grid is almost the same. Initially, we are going to bypass two uttermost horizontals almost the same way as above - $(1, 1)$ -> $(n, m)$ -> $(1, 2)$ -> $(n, m-1)$ -> $\\ldots$ -> $(1, m)$ -> $(n, 1)$. One can realize that all vectors are different because they have different $dy$. Note that all of them have $|dx| = n-1$. Then we will jump to $(2, 1)$ (using $(-(n-2), 0)$ vector). Now we have a smaller task for $(n-2) \\cdot m$ grid. One can see that we used only vectors with $|dx| \\geq n-2$, so they don't influence now at all. So the task is fully brought down to a smaller one.",
    "code": "\"#include <bits/stdc++.h>\\n\\n#define int long long\\n\\n#define pii pair<int, int>\\n\\n#define x1 x1228\\n#define y1 y1228\\n\\n#define left left228\\n#define right right228\\n\\n#define pb push_back\\n#define eb emplace_back\\n\\n#define mp make_pair                                                                \\n\\n#define ff first                                                                  \\n#define ss second   \\n\\n#define matr vector<vector<int> > \\n\\n#define all(x) x.begin(), x.end()\\n\\n\\nusing namespace std;\\ntypedef long long ll; \\ntypedef long double ld; \\n                                                                                                   \\nconst int maxn = 3e5 + 7, mod = 1e9 + 7, inf = 1e18, MAXN = 1e6 + 7;\\nconst double eps = 1e-9;\\nmt19937 rnd(time(0));\\nint n, m; \\n\\nvoid solve() {        \\n    cin >> n >> m; \\n    if (n == 2 && m == 3) {\\n        cout << \\\"1 1\\\\n1 3\\\\n1 2\\\\n2 2\\\\n2 3\\\\n2 1\\\"; \\n        return; \\n    }\\n    for (int i = 0; i < n / 2; ++i) {\\n        for (int j = 0; j < m; ++j) {\\n            cout << i+1 << \\\" \\\" << j+1 << '\\\\n';\\n            cout << n - i - 1+1 << \\\" \\\" << m - j - 1+1 << '\\\\n';             \\n        }\\n    }                      \\n    if (n % 2) {          \\n        int x = n / 2;\\n        deque<int> have; \\n        cout << x+1 << \\\" \\\" << 1 << '\\\\n'; \\n        for (int i = 1; i < m; ++i) {\\n            have.pb(i);         \\n        } \\n        while (have.size()) {\\n            cout << x+1 << \\\" \\\"  << have.back()+1 << '\\\\n'; \\n            have.pop_back(); \\n            if (have.size()) {\\n                cout << x+1 << \\\" \\\" << have.front()+1 << '\\\\n'; \\n                have.pop_front(); \\n            }\\n        }                \\n    }\\n}                                \\n   \\nsigned main() {\\n#ifdef LOCAL1\\n    freopen(\\\"TASK.in\\\", \\\"r\\\", stdin);\\n    freopen(\\\"TASK.out\\\", \\\"w\\\", stdout);\\n#else \\n    \\n#endif // LOCAL\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(0);\\n    cout.precision(20); \\n    cout << fixed; \\n    int t = 1; \\n    for (int i = 0; i < t; ++i) {              \\n        solve();\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1179",
    "index": "C",
    "title": "Serge and Dining Room",
    "statement": "Serge came to the school dining room and discovered that there is a big queue here. There are $m$ pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him.\n\nInitially there are $n$ dishes with costs $a_1, a_2, \\ldots, a_n$. As you already know, there are the queue of $m$ pupils who have $b_1, \\ldots, b_m$ togrogs respectively (pupils are enumerated by queue order, i.e the first pupil in the queue has $b_1$ togrogs and the last one has $b_m$ togrogs)\n\nPupils think that the most expensive dish is the most delicious one, so every pupil just buys the most expensive dish for which he has money (every dish has a single copy, so when a pupil has bought it nobody can buy it later), and if a pupil doesn't have money for any dish, he just leaves the queue (so brutal capitalism...)\n\nBut money isn't a problem at all for Serge, so Serge is buying the most expensive dish if there is at least one remaining.\n\nMoreover, Serge's school has a very unstable economic situation and the costs of some dishes or number of togrogs of some pupils can change. More formally, you must process $q$ queries:\n\n- change $a_i$ to $x$. It means that the price of the $i$-th dish becomes $x$ togrogs.\n- change $b_i$ to $x$. It means that the $i$-th pupil in the queue has $x$ togrogs now.\n\nNobody leaves the queue during those queries because a saleswoman is late.\n\nAfter every query, you must tell Serge price of the dish which he will buy if he has waited until the queue is clear, or $-1$ if there are no dishes at this point, according to rules described above.",
    "tutorial": "The main idea of the task is that the answer is minimal $x$ which satisfies the condition that the number of dishes with cost $\\geq x$ is strictly more than the number of pupils who have more than $x$ togrogs. It can be proved using the fact that we can change every neighbor pair for pupils and we don't change the final set of dishes. Exact prove is left as an exercise. Now to find the answer we can use a segment tree that maintains a balance between the number of dishes and the number of pupils for all suffices of values. Now change query transforms to add in the segment tree, the answer should be found searching the last element which is less than $0$ (standard descent in the segment tree). Complexity is $O(n \\cdot log(n)$).",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define int long long\\n\\nconst int MAXN = 3e5 + 7;\\nconst int MAXV = 3 * MAXN;\\n\\nint n, m;\\nint a[MAXN], b[MAXN];\\n\\nint q;\\nint t[MAXN], p[MAXN], x[MAXN];\\n\\nvoid read() {\\n    cin >> n >> m;\\n    for (int i = 0; i < n; ++i) {\\n        cin >> a[i];\\n    }\\n    for (int i = 0; i < m; ++i) {\\n        cin >> b[i];\\n    }   \\n    cin >> q;\\n    for (int i = 0; i < q; ++i) {\\n        cin >> t[i];\\n        if (t[i] <= 2) {\\n            cin >> p[i] >> x[i];\\n            --p[i];\\n        }\\n    }   \\n}   \\n\\nint u = 0;\\nint v[MAXV];\\n\\nvoid compr() {\\n    for (int i = 0; i < n; ++i) {\\n        v[u++] = a[i];\\n    }   \\n    for (int i = 0; i < m; ++i) {\\n        v[u++] = b[i];\\n    }   \\n    for (int i = 0; i < q; ++i) {\\n        if (t[i] <= 2) {\\n            v[u++] = x[i];\\n        }   \\n    }   \\n    sort(v, v + u);\\n    u = unique(v, v + u) - v;\\n    for (int i = 0; i < n; ++i) {\\n        a[i] = lower_bound(v, v + u, a[i]) - v;\\n    }   \\n    for (int i = 0; i < m; ++i) {\\n        b[i] = lower_bound(v, v + u, b[i]) - v;\\n    }   \\n    for (int i = 0; i < q; ++i) {\\n        if (t[i] <= 2) {\\n            x[i] = lower_bound(v, v + u, x[i]) - v;\\n        }   \\n    }   \\n}   \\n\\nint tree[MAXV << 2], add[MAXV << 2];\\n\\nvoid push(int v) {\\n    tree[v * 2 + 1] += add[v];\\n    add[v * 2 + 1] += add[v];\\n    tree[v * 2 + 2] += add[v];\\n    add[v * 2 + 2] += add[v];\\n    add[v] = 0;\\n}   \\n\\nvoid upd(int v, int tl, int tr, int l, int r, int x) {\\n    if (tr < l || r < tl) {\\n        return;\\n    }   \\n    if (l <= tl && tr <= r) {\\n        tree[v] += x;\\n        add[v] += x;\\n        return;\\n    }   \\n    int tm = (tl + tr) >> 1;\\n    push(v);\\n    upd(v * 2 + 1, tl, tm, l, r, x); \\n    upd(v * 2 + 2, tm + 1, tr, l, r, x);\\n    tree[v] = max(tree[v * 2 + 1], tree[v * 2 + 2]);\\n}\\n\\nint get(int v, int tl, int tr) {\\n    if (tl == tr) {\\n        return tl;\\n    }   \\n    int tm = (tl + tr) >> 1;\\n    push(v);\\n    if (tree[v * 2 + 2] >= 1) {\\n        return get(v * 2 + 2, tm + 1, tr);\\n    }   \\n    else {\\n        return get(v * 2 + 1, tl, tm);\\n    }   \\n}   \\n\\nvoid add1(int x) {\\n    //cout << x << ' ' << 1 << '\\\\n';\\n    upd(0, 0, MAXV, 0, x, 1);\\n}\\n\\nvoid del1(int x) {\\n    //cout << x << ' ' << -1 << '\\\\n';\\n    upd(0, 0, MAXV, 0, x, -1);\\n}\\n\\nvoid upd1(int p, int x) {\\n    del1(a[p]);\\n    a[p] = x;\\n    add1(a[p]);\\n}   \\n\\nvoid add2(int x) {\\n    //cout << x << ' ' << -1 << '\\\\n';\\n    upd(0, 0, MAXV, 0, x, -1);\\n}\\n\\nvoid del2(int x) {                  \\n    //cout << x << ' ' << 1 << '\\\\n';\\n    upd(0, 0, MAXV, 0, x, 1);\\n}   \\n\\nvoid upd2(int p, int x) {\\n    del2(b[p]);\\n    b[p] = x;\\n    add2(b[p]);\\n}   \\n\\nint get() {\\n    if (tree[0] >= 1) {\\n        return get(0, 0, MAXV);\\n    }   \\n    else {\\n        return -1;\\n    }   \\n}   \\n\\nvoid solve() {\\n    compr();\\n    for (int i = 0; i < n; ++i) {\\n        add1(a[i]);\\n    }   \\n    for (int i = 0; i < m; ++i) {\\n        add2(b[i]);\\n    }   \\n}\\n\\nvoid print() {\\n    for (int i = 0; i < q; ++i) {\\n        if (t[i] == 1) {\\n            upd1(p[i], x[i]);\\n        }   \\n        else {\\n            upd2(p[i], x[i]);\\n        }   \\n        {\\n            int ans = get();\\n            if (ans == -1) {\\n                cout << \\\"-1\\\\n\\\";\\n            }   \\n            else {\\n                cout << v[ans] << '\\\\n';\\n            }   \\n        }   \\n    }   \\n}\\n\\nsigned main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(0);\\n\\n    read();\\n    solve();\\n    print();\\n\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "data structures",
      "graph matchings",
      "greedy",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1179",
    "index": "D",
    "title": "Fedor Runs for President",
    "statement": "Fedor runs for president of Byteland! In the debates, he will be asked how to solve Byteland's transport problem. It's a really hard problem because of Byteland's transport system is now a tree (connected graph without cycles). Fedor's team has found out in the ministry of transport of Byteland that there is money in the budget only for one additional road. In the debates, he is going to say that he will build this road as a way to maximize the number of distinct simple paths in the country. A simple path is a path which goes through every vertex no more than once. Two simple paths are named distinct if sets of their edges are distinct.\n\nBut Byteland's science is deteriorated, so Fedor's team hasn't succeeded to find any scientists to answer how many distinct simple paths they can achieve after adding exactly one edge on the transport system?\n\nHelp Fedor to solve it.\n\nAn edge can be added between vertices that are already connected, but it can't be a loop.\n\nIn this problem, we consider only simple paths of length at least two.",
    "tutorial": "We suppose we add an edge $u-v$. Path $u-v$ in the tree contains vertices $t_1, \\ldots, t_k$, where $k$ - length of the path, $t_1 = u, t_k = v$. For each vertex $x$ of the tree, we say that $f(x)$ - the closest to $x$ vertex of this path. Finally, we call a component of $t_i$ all vertices $x$ having $f(x) = t_i$. One can notice that after adding an edge every pair of vertices may generate not more than two simple paths - the first one had already been in the tree, the second one may be generated using added edge. One can notice that every new path is generated by every pair of vertices lying in different components. Let's consider the sizes of components - $s_1, \\ldots, s_k$ respectively. So new path isn't generated for $\\sum\\limits_{i=1}^k \\frac{s_i \\cdot (s_i - 1)}{2}$ pairs of vertices. So we have the following problem - to minimize this sum. Thus, we should minimize $\\sum\\limits_{i=1}^k \\frac{s_i \\cdot (s_i - 1)}{2}$, what is the same as, $\\sum\\limits_{i=1}^k s_i \\cdot (s_i - 1)$ = $\\sum\\limits_{i=1}^k s_i \\cdot s_i - s_i$ = $\\sum\\limits_{i=1}^k s_i^{2}$ (because of $\\sum\\limits_{i=1}^k s_i$ = $n$). It's obvious now that $u, v$ are leafs of the tree (else we could decrease this sum increasing the path). For convenience, we will hang the tree for a non-leaf. We will consider that $t_l = lca(u, v)$ in the path. Then, the desired sum will be: $A + B + C$, where $A = sz_{t_1}^{2} + (sz_{t_2} - sz_{t_1})^{2} + \\ldots + (sz_{t_l} - sz_{t_{l-1}})^{2}$ $B = (n - sz_{t_{l-1}} - sz_{t_{l+1}})^{2}$ $C = sz_{t_k}^{2} + (sz_{t_{k-1}} - sz_{t_k})^{2} + \\ldots + (sz_{t_l} - sz_{t_{l+1}})^{2}$ When we fix $L = t_l$, $p_1 = t_{l+1}$ and $p_2 = t_{l-1}$, one can realize that $A$ doesn't depend on $L$ at all but depends on the subtree of $p_1$, as $C$ depends of the subtree of $p_2$. Thus these sums can easily be calculated using $DP$. Let $dp[x]$ be that optimal sum for vertex $x$. Then, when we fix $L$ - $lca(u, v)$ - we need to calculate the minimum by all different $p_1, p_2$ - children of $L$ - the following sum: $dp[p_1] + dp[p_2] + (n - sz_{p_1} - sz_{p_2})^{2}$. We get: $n^{2} + dp[p1] - 2 \\cdot n \\cdot sz_{p_1} + dp[p2] - 2 \\cdot n \\cdot sz_{p_2} + 2 \\cdot sz_{p_1} \\cdot sz_{p_2}$. Now one can see that if we sort all vertices by $sz$ in non-increasing order one can use Convex Hull Trick - for the next vertex $p_2$ we find minimum by all $p_1$ which are already processed by functions $2 \\cdot sz_{p_1} \\cdot sz_{p_2} - 2 \\cdot n \\cdot sz_{p_1} + dp[p1]$, i.e $k = 2 \\cdot sz_{p_1}$, $b = - 2 \\cdot n \\cdot sz_{p_1} + dp[p1]$. $k$ decreases, thus we write usual CHT. Complexity is $O(n \\cdot log(n))$.",
    "code": "\"#include <bits/stdc++.h>\\n#define int long long\\n#define double long double\\nusing namespace std;\\nint INF = 1e18;\\ndouble DINF = 1e18;\\nvector<vector<int> > data;\\nint ans = INF;\\nvector<int> dp, sz;\\nint n;\\nstruct Line{double k; double b; double l; double r;};\\nvector<Line> cht;\\nint ask(int x){\\n    int L = 0, R = cht.size();\\n    double cp = x;\\n    while (R-L>1){\\n        int M = (L+R)/2;\\n        if (cht[M].r >= cp) L = M;\\n        else R = M;\\n    }\\n    int K = cht[L].k, B = cht[L].b;\\n    return K*x+B;\\n}\\ndouble intersect(Line &a, Line &b){\\n    if (a.k == b.k) return -DINF;\\n    double db = a.b - b.b;\\n    double dk = b.k - a.k;\\n    return db/dk;\\n}\\nvoid add(double k, double b){\\n    Line nl = {k, b, -DINF, DINF};\\n    while (cht.size()){\\n        double inter = intersect(nl, cht.back());\\n        if (inter <= cht.back().l){\\n            cht.pop_back();\\n        }\\n        else{\\n            cht.back().r = inter;\\n            nl.l = inter;\\n            cht.push_back(nl);\\n            break;\\n        }\\n    }\\n    if (!cht.size()) cht.push_back(nl);\\n}\\nvoid calc(int vertex, int last){\\n    vector<pair<int, int> > children;\\n    int cur=0;\\n    for (int i=0; i < data[vertex].size(); i++){\\n        int to = data[vertex][i];\\n        if (to == last) continue;\\n        children.push_back({sz[to], dp[to]});\\n        cur++;\\n    }\\n    if (cur==1) return;\\n    sort(children.begin(), children.end(), greater<pair<int, int> > ());\\n    for (int i=0; i < children.size(); i++){\\n        int SZ = children[i].first, DP = children[i].second;\\n        if (i > 0){\\n            int res = ask(SZ);\\n            ans = min(ans, res + DP + n*n + SZ*SZ - 2*n*SZ);\\n        }\\n        int K = 2*SZ;\\n        int B = DP+SZ*SZ-2*n*SZ;\\n        add(K, B);\\n    }\\n}\\nvoid dfs(int vertex, int last){\\n    sz[vertex] = 1;\\n    for (int i=0; i < data[vertex].size(); i++){\\n        int to = data[vertex][i];\\n        if (to == last) continue;\\n        dfs(to, vertex);\\n        sz[vertex] += sz[to];\\n    }\\n    if (sz[vertex] == 1) dp[vertex] = 1;\\n    else{\\n        dp[vertex] = INF;\\n        for (int i=0; i < data[vertex].size(); i++){\\n            int to = data[vertex][i];\\n            if (to == last) continue;\\n            dp[vertex] = min(dp[vertex], dp[to] + (sz[vertex] - sz[to]) * (sz[vertex] - sz[to]));\\n        }\\n    }\\n    calc(vertex, last);\\n}\\nmain() {\\n    ios_base::sync_with_stdio(false), cin.tie(0);\\n    cin >> n;\\n    data.resize(n, {});\\n    dp.resize(n, -1);\\n    sz.resize(n, -1);\\n    for (int i=0; i < n-1; i++){\\n        int u, v;\\n        cin >> u >> v;\\n        data[u-1].push_back(v-1), data[v-1].push_back(u-1);\\n    }\\n    if (n==2){\\n        cout << 2;\\n        return 0;\\n    }\\n    int father = -1;\\n    for (int i=0; i < n; i++){\\n        if (data[i].size() > 1) father = i;\\n    }\\n    dfs(father, -1);\\n    int res = 2*n*(n-1) - (ans - n);\\n    cout << res/2;\\n    return 0;\\n}\"",
    "tags": [
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1179",
    "index": "E",
    "title": "Alesya and Discrete Math",
    "statement": "We call a function good if its domain of definition is some set of integers and if in case it's defined in $x$ and $x-1$, $f(x) = f(x-1) + 1$ or $f(x) = f(x-1)$.\n\nTanya has found $n$ good functions $f_{1}, \\ldots, f_{n}$, which are defined on all integers from $0$ to $10^{18}$ and $f_i(0) = 0$ and $f_i(10^{18}) = L$ for all $i$ from $1$ to $n$. It's an notorious coincidence that $n$ is a divisor of $L$.\n\nShe suggests Alesya a game. Using one question Alesya can ask Tanya a value of any single function in any single point. To win Alesya must choose integers $l_{i}$ and $r_{i}$ ($0 \\leq l_{i} \\leq r_{i} \\leq 10^{18}$), such that $f_{i}(r_{i}) - f_{i}(l_{i}) \\geq \\frac{L}{n}$ (here $f_i(x)$ means the value of $i$-th function at point $x$) for all $i$ such that $1 \\leq i \\leq n$ so that for any pair of two functions their segments $[l_i, r_i]$ don't intersect (but may have one common point).\n\nUnfortunately, Tanya doesn't allow to make more than $2 \\cdot 10^{5}$ questions. Help Alesya to win!\n\nIt can be proved that it's always possible to choose $[l_i, r_i]$ which satisfy the conditions described above.\n\nIt's guaranteed, that Tanya doesn't change functions during the game, i.e. interactor is not adaptive",
    "tutorial": "We denote $T$ as $log(10^{18})$ for convenience. Let, without loss of generality, $n$ is even. Let us find such $x_i$ for function $f_i$ that $f_i(x_i) = \\frac{L}{2}$ using binary search. Now we're going to renumber functions so that in new numeration $i < j$ attracts $x_i \\leq x_j$. Let $x_{\\frac{n}{2}} = P$. Now one can see that we have reduced the task to two smaller ones - the original task for functions with numbers $1, \\ldots, \\frac{n}{2}$, having only a restriction that all their segments of answer are enclosed inside segment $[0; P]$, and, similarly, for others functions and segment $[P; 10^{18}]$. Considering the original problem with all functions as a problem with the restriction that segments of the answer are enclosed inside $[0; 10^{18}]$, the task is reduced to smaller ones. Proof of correctness if left as an exercise, it's pretty easy. This works in $O(n \\cdot T \\cdot log(n))$. To speed it up, we're going to find $\\frac{n}{2}$-th function by $x_i$ a little bit smarter. Long story short, we're going to act as in the search of $k$-th element in an array in linear time. We will take a random function $f_i$, run binary search for it, and not run binary searches for others but check how many $f_j$ so that $f_j(x_j) \\leq f_i(x_i)$. It's easy to check using one query $f_j(x_i)$ for all $f_j$. It will work in $O(T \\cdot log(n) + n)$ queries on the average, as we know this process will averagely converge in $O(log(n))$ steps. Let's estimate the total complexity. Let, without loss of generality, the number of functions is $n = 2^{s}$ for some $s$. So: $O(\\sum\\limits_{i=1}^s 2^{s-i} \\cdot T \\cdot i$ + $n \\cdot log(n))$ is number of queries ( (we will have $2^{s-i}$ segments on the $s-i$-th level pf recursion, and for each of them log is $i$). Thus it's: $O(n \\cdot log(n)$ + $T \\cdot \\sum\\limits_{i=1}^s 2^{s-i} \\cdot i)$. So: $O(n \\cdot log(n)$ + $T \\cdot n \\cdot \\sum\\limits_{i=1}^s \\frac{i}{2^{i}})$. It's $O(n \\cdot log(n) + T \\cdot n)$, cause that series converges to 2.",
    "code": "\"#include <iostream>\\n#include <vector>\\n#include <functional>\\n#include <numeric>\\n#include <random>\\n#include <map>\\nusing namespace std;\\n#define int long long\\nconst int FSZ = 1e18;\\nmt19937 rnd;\\nint cntq=0;\\nint ask(int id, int x) {\\n    cout << \\\"? \\\" << id + 1 << \\\" \\\" << x << endl;\\n    int ans;\\n    cin >> ans;\\n    ++cntq;\\n    return ans;\\n}\\nint n, L, value;\\nvector<pair<int, int> > ans;\\nint bs(int guy, int val, int l, int r){\\n    int ll=l, rr=r;\\n    while (rr - ll > 1){\\n        int mm = (ll+rr)/2;\\n        int res = ask(guy, mm);\\n        if (res == val) return mm;\\n        if (res < val) ll = mm;\\n        else rr = mm;\\n    }\\n}\\npair<vector<int>, vector<int> > kth(vector<int> men, int as, int K, int l, int r){\\n    if (men.size() == 1){\\n        return {men, {}};\\n    }\\n    int R = rnd() % men.size();\\n    vector<int> left, eql, right;\\n    int V = bs(men[R], (L/n)*as, l, r);\\n    eql.push_back(men[R]);\\n    int C = (L/n)*as;\\n    for (int i=0; i < men.size(); i++){\\n        if (i==R) continue;\\n        int T = ask(men[i], V);\\n        if (T < C) right.push_back(men[i]);\\n        if (T == C) eql.push_back(men[i]);\\n        if (T > C) left.push_back(men[i]);\\n    }\\n    while (left.size() < K && eql.size()){\\n        left.push_back(eql.back());\\n        eql.pop_back();\\n    }\\n    if (left.size() == K){\\n        value = V;\\n        while (eql.size()){\\n            right.push_back(eql.back());\\n            eql.pop_back();\\n        }\\n        return {left, right};\\n    }\\n    if (left.size() < K){\\n        pair<vector<int>, vector<int> > p = kth(right, as, K-left.size(), l, r);\\n        while (left.size()){\\n            p.first.push_back(left.back());\\n            left.pop_back();\\n        }\\n        return p;\\n    }\\n    while (eql.size()){\\n        right.push_back(eql.back());\\n        eql.pop_back();\\n    }\\n    pair<vector<int>, vector<int> > p = kth(left, as, K, l, r);\\n    while (right.size()){\\n        p.second.push_back(right.back());\\n        right.pop_back();\\n    }\\n    return p;\\n}\\nvoid divide(int start, int l, int r, vector<int> men){\\n    if (men.size() == 1){\\n        ans[men[0]] = {l, r};\\n        return;\\n    }\\n    int F = men.size() / 2;\\n    int as = start+F;\\n    pair<vector<int>, vector<int> > p = kth(men, as, F, l, r);\\n    int V = value;\\n    divide(start, l, V, p.first);\\n    divide(start+p.first.size(), V, r, p.second);\\n}\\nsigned main() {\\n\\t//ios_base::sync_with_stdio(false);\\n\\tcin >> n >> L;\\n    vector<int> men;\\n    for (int i=0; i < n;i++) men.push_back(i);\\n    ans.assign(n, {-1, -1});\\n    divide(0, 0, FSZ, men);\\n    cout << \\\"!\\\" << endl;\\n\\tfor (int i = 0; i < n; ++i)\\n\\t\\tcout << ans[i].first << \\\" \\\" << ans[i].second << endl;\\n    cerr << \\\"Done \\\" << cntq << \\\" queries\\\\n\\\";\\n\\treturn 0;\\n}\"",
    "tags": [
      "divide and conquer",
      "interactive"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1180",
    "index": "A",
    "title": "Alex and a Rhombus",
    "statement": "While playing with geometric figures Alex has accidentally invented a concept of a $n$-th order rhombus in a cell grid.\n\nA $1$-st order rhombus is just a square $1 \\times 1$ (i.e just a cell).\n\nA $n$-th order rhombus for all $n \\geq 2$ one obtains from a $n-1$-th order rhombus adding all cells which have a common side with it to it (look at the picture to understand it better).\n\nAlex asks you to compute the number of cells in a $n$-th order rhombus.",
    "tutorial": "Looking into the picture attentively, one can realize that there are $2$ rows with one cell, $2$ rows with two cells, ..., and $1$ row with $n$ cells. Thus the answer can be easily computed by $O(n)$.",
    "code": "#include \"bits/stdc++.h\"\n \nusing namespace std;\n \nint main() {\n    int n;\n    cin >> n;\n    cout << 2*n*n-2*n+1;\n    return 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1180",
    "index": "B",
    "title": "Nick and Array",
    "statement": "Nick had received an awesome array of integers $a=[a_1, a_2, \\dots, a_n]$ as a gift for his $5$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $a_1 \\cdot a_2 \\cdot \\dots a_n$ of its elements seemed to him not large enough.\n\nHe was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $i$ ($1 \\le i \\le n$) and do $a_i := -a_i - 1$.\n\nFor example, he can change array $[3, -1, -4, 1]$ to an array $[-4, -1, 3, 1]$ after applying this operation to elements with indices $i=1$ and $i=3$.\n\nKolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index.\n\nHelp Kolya and print the array with the maximal possible product of elements $a_1 \\cdot a_2 \\cdot \\dots a_n$ which can be received using only this operation in some order.\n\nIf there are multiple answers, print any of them.",
    "tutorial": "Initially, we are going to make a product maximal by absolute value. It means that if $a_i \\geq 0$ we are going to apply described operation (i.e to increase the absolute value). Now if the product is already positive, it's the answer. Else to apply the operation to the minimal number is obviously optimal (if we applied the operation to any other number the result would not be greater by absolute value, but applying to the minimum we have received non-negative product already). Thus the solution works in $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nmain(){\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(0);\\n    int n;\\n    cin >> n;\\n    vector<int> v(n);\\n    for (int i=0;i<n;i++) cin >> v[i];\\n    if (n != 3 || (v[0] != -3 || v[1] != -3 || v[2] != 2)){\\n        for (int i=0;i<n;i++){\\n            if (v[i] >= 0) v[i] = -v[i]-1;\\n        }\\n        if (n%2!=0){\\n            int mx = -1, ind = -1;\\n            for (int i=0;i < n; i++){\\n                if (abs(v[i]) > mx){\\n                    mx = abs(v[i]);\\n                    ind = i;\\n                }\\n            }\\n            v[ind] = -v[ind]-1;\\n        }\\n    }\\n    for (int i=0;i<n;i++) cout << v[i] << \\\" \\\";\\n}\"",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1181",
    "index": "A",
    "title": "Chunga-Changa",
    "statement": "Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called \"chizhik\". One has to pay in chizhiks to buy a coconut now.\n\nSasha and Masha are about to buy some coconuts which are sold at price $z$ chizhiks per coconut. Sasha has $x$ chizhiks, Masha has $y$ chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.\n\nThe girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.\n\nConsider the following example. Suppose Sasha has $5$ chizhiks, Masha has $4$ chizhiks, and the price for one coconut be $3$ chizhiks. If the girls don't exchange with chizhiks, they will buy $1 + 1 = 2$ coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have $6$ chizhiks, Masha will have $3$ chizhiks, and the girls will buy $2 + 1 = 3$ coconuts.\n\nIt is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).",
    "tutorial": "It's easy to calculate how much coconuts we will buy: $k = \\lfloor \\frac{x + y}{z} \\rfloor$ (suppose that all money transferred to a single person, this way the number of bought coconuts would be clearly maximal) If $k = \\lfloor \\frac{x}{z} \\rfloor + \\lfloor \\frac{y}{z} \\rfloor$, then the answer is $\\langle k, 0 \\rangle$. The remaining case is a bit harder. Let's notice, that there is no need to transfer $\\ge z$ chizhiks, since the one transferring money could have used $z$ chizhiks to buy one more coconut herself. Also it's optimal to transfer coins such that the remainder modulo $z$ of the receiving part will turn to be exactly zero (we could have simply transfer less for the same effect). So the answer is $\\langle k, \\min (z - (x \\bmod z), z - (y \\bmod z)) \\rangle$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1181",
    "index": "B",
    "title": "Split a Number",
    "statement": "Dima worked all day and wrote down on a long paper strip his favorite number $n$ consisting of $l$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.\n\nTo solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a \\textbf{positive} integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.\n\nDima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.",
    "tutorial": "Suppose that the number doesn't contain any zeros (that is, we can split it at any point). Than it is easy to show that it is enough to check only the following cuts: $k$; $k$, if the length of the number is $2k$. $k + 1$; $k$ and $k$; $k + 1$, if the length of the number is $2k + 1$. Some intuition behind this: it's not optimal to make \"inbalanced\" cuts. Because the sum $a + b$ is at least $max(a, b)$. And in case the maximum is large already, we could have built a more optimal answer if we would make a cut in a less \"inbalanced\" way. One can also examine not only $1-2$ possible cuts, but rather $\\mathcal{O}(1)$ different options around the center, this way solution is a bit easier to proof. In case we have zeros, the solution is mostly the same: we just simply need to consider the closest valid cut to the left from center and closest valid cut to the right. And take a minimum of them. One can note that in the solution above we need to add and compare \"long integers\". One could have used a programming language in which they are already implemented (Python/Java) or implemented the required functions themselves. The number can be simply stored as a sequence of digits from least-important digit to the most-important. It's simple to implement the summation and comparing of such integers.",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1181",
    "index": "C",
    "title": "Flag",
    "statement": "Innokenty works at a flea market and sells some \\sout{random stuff} rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $n \\cdot m$ colored pieces that form a rectangle with $n$ rows and $m$ columns.\n\nThe colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of \\textbf{equal} heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.\n\nInnokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.\n\n\\begin{center}\n{\\small These subrectangles are flags.}\n\\end{center}\n\n\\begin{center}\n{\\small These subrectangles are not flags.}\n\\end{center}",
    "tutorial": "To start with, let's find a way to calculate the number of flags of width $1$. Let's bruteforce the row $r$ and column $c$ of the topmost cell of the middle part of the flag. So if the cell above has the same color as $(r, c)$ then clearly there can't be a flag here. Otherwise we are standing at the topmost position of the consecutive segment of cells of some color. Let's walk all this segment down and find its length $l$. Note, that all mentioned above works in $\\mathcal{O}(nm)$, since each cell would be walked exactly once. And now we can spend additional $\\Theta(l)$ time to check whether there exist a unicolored segments of length $l$ above our segment and below our segment, the solution still works in $\\mathcal{O}(nm)$. So now we managed to find all \"narrow\" flags. The wide flag is simply a sequence of \"narrow\" flags of the common type (with the same value of $l$ and colors $color_1$, $color_2$, $color_3$ - color of the top, middle and bottom part of the flag). Let's bruteforce the topmost row $r$ of the middle part of the flag. Now bruteforce $c$ and find a narrowflag as suggested above (there might be no flag in $(r, c)$ though). And also maintain $w$: a maximum possible length of the flag backwards. In case $(l, color_1, color_2, color_3)$ are same as in $(r, c - 1)$, then we increase $w$ by one. Otherwise assign $1$ to $w$. Note that we in fact are iterating over all possible right-borders of the flag. And there are exactly $w$ possible left-borders. So we simply increase our answer by $w$ each time.",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1181",
    "index": "D",
    "title": "Irrigation",
    "statement": "Misha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first $n$ olympiads the organizers introduced the following rule of the host city selection.\n\nThe host cities of the olympiads are selected in the following way. There are $m$ cities in Berland wishing to host the olympiad, they are numbered from $1$ to $m$. The host city of each next olympiad is determined as the city that hosted the olympiad the \\textbf{smallest} number of times before. If there are several such cities, the city with the \\textbf{smallest} index is selected among them.\n\nMisha's mother is interested where the olympiad will be held in some specific years. The only information she knows is the above selection rule and the host cities of the first $n$ olympiads. Help her and if you succeed, she will ask Misha to avoid flooding your house.",
    "tutorial": "Let's solve all the queries simultaneously. For this purpose sort them all in increasing order. Sort all the countries based on the number of hosted competitions in the first $n$ years (see picture) How this diagram changes after several more years of the competition? The cells are filled from lower rows to the higher, while inside one row we order cells based on the country number. Let's fill this table from bottom upwards. For the queries which won't be replied in the current row, it is not important in which order the cells in the current row are colored, only the quantity is important. So for such queries we can simply accumulate the number of already painted cells so far. Now let's discuss the queries, which need to be answered in the current row. If we subtract from $k$ (the query parameter) the number $S$ of cells painted in previous rows, then we simply need to return the $k-s$-th element in this set. So in other words we need to add countries in the set and sometimes compute $i$-th element in it. One can use cartesian tree \"treap\" or a segment tree to do that. It may also turn out, that after we fill all the diagram, there are some questions unanswered yet. In this case we can notice, that all the subsequent rows look like the whole set of countries. So the answer is simply the remainder of $k - S$ modulo $m$. Since we only need to consider at most $n$ lines until the diagram is filled-up, the solution works in $\\mathcal{O}((q + n + m) \\log)$.",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "sortings",
      "trees",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1181",
    "index": "E2",
    "title": "A Story of One Country (Hard)",
    "statement": "This problem differs from the previous problem only in constraints.\n\nPetya decided to visit Byteland during the summer holidays. It turned out that the history of this country is quite unusual.\n\nInitially, there were $n$ different countries on the land that is now Berland. Each country had its own territory that was represented as a rectangle on the map. The sides of the rectangle were parallel to the axes, and the corners were located at points with integer coordinates. Territories of no two countries intersected, but it was possible that some territories touched each other. As time passed, sometimes two countries merged into one. It only happened if the union of their territories was also a rectangle. In the end only one country remained — Byteland.\n\nInitially, each country had a rectangular castle inside its territory. Its sides were parallel to the axes and its corners had integer coordinates. Some castles might touch the border of the corresponding country and sides or other castles. Miraculously, after all the unions the castles are still intact. Unfortunately, their locations are the only information we have to restore the initial territories of the countries.\n\n\\begin{center}\nThe possible formation of Byteland. The castles are shown in blue.\n\\end{center}\n\nPetya wonders why no information about the initial countries remained. He suspected that the whole story is a fake. You were recommended to him as a smart person. Please check whether or not there exists a possible set of initial territories that could make the story true.",
    "tutorial": "We can rephrase the problem as follows: There is a set of non-intersecting rectangles on the plane. Let's say, that some rectangular area on the plane is good, if it contains exactly one rectangle in it or there exists a vertical or horizontal cut, which cuts the area into two good areas. You are asked to check whether the area $[0; 10^9] \\times [0; 10^9]$ is good. It's easy to see that it is exactly the same process as in the statement, except we don't merge countries into one, we look at the reversed process, where we split one country into many. Also let's notice, that when we found some cutting line, which doesn't goes through inner part of any rectangle, we can always apply it to separate our area into two. We can do that, since our predicate of set of rectangles being nice is monotonic: if we replace set of rectangles with its subset, it only can make better. Now let's analyze when the cut is good: This already gives us a solution in $\\mathcal{O}(n^2 \\log)$, which passes the easy version of the problem. Simply solve the problem recursively, sorting rectangles as shown above. (and symmetrically for horizontal cuts) and try finding a cut. Once we find it, solve the problem recursively. Now we have working time: $T(n) = T(x) + T(n - x) + \\mathcal{O}(n \\log n)$, where $x$ is a size of one part of the cut. The worse case is $x = 1$, so $T(n) = \\mathcal{O}(n^2 \\log)$. $\\square$ For the full version we need a faster solution. The key idea is: let's cut always \"smaller from larger\". Suppose we are magically able to find any valid cut in $\\mathcal{O}(1)$ (basically the number $x$). Then we could have spent $\\mathcal{O}(x)$ to cut out the smaller part into new recursive call. While we can continue the process of cutting with the remaining rectangles in this recursion call. This solution works in $\\mathcal{O}(n \\log n)$: Each time the size of problem reduces at least twice when we go into recursion, so there are only $\\log$ levels. However we need to handle \"magic\" here. For example one could have used a segment tree to implement all mentioned above (it would give a $\\mathcal{O}(n \\log^2)$ time). But there is a simpler solution! Let's sort rectangles using all $4$ possible sortings. And let's iterate over all this sortings simultaneously. We need $4$ directions instead of $2$, because if we would e.g. only iterate from let to right, we wouldn't be able to cut out the \"smaller\" from \"larger\", in case the \"smaller\" is to the right of \"larger\". So we want to both go from left to right and from right to left. When in one of the directions we see a valid place to make a cut, we remove all the rectangles into the separate recursion call. We also mark all those rectangles in the current recursion call as deleted and start the procedure of cutting again. We can simply skip the rectangles marked as deleted when we encounter them. For example we could use a linked list for that: So now we got a solution in $\\mathcal{O}(n \\log^2)$: one logarithm is from cutting smaller from larger and one logarithm is from sorting. One could drop the second logarithm. For that we should sort all rectangles at the beginning and then carefully pass the correct ordering down the recursion. But that wasn't required.",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1182",
    "index": "A",
    "title": "Filling Shapes",
    "statement": "You have a given integer $n$. Find the number of ways to fill all $3 \\times n$ tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap.\n\n\\begin{center}\nThis picture describes when $n = 4$. The left one is the shape and the right one is $3 \\times n$ tiles.\n\\end{center}",
    "tutorial": "If you want to have no empty spaces on $3 \\times n$ tiles, you should fill leftmost bottom tile. Then you have only 2 choices; Both cases force you to group leftmost $3 \\times 2$ tiles and fill. By this fact, we should group each $3 \\times 2$ tiles and fill independently. So the answer is - if $n$ is odd, then the answer is $0$ (impossible), otherwise, the answer is $2^{\\frac{n}{2}}$. Time complexity is $O(1)$ with bit operation or $O(n)$ with iteration.",
    "code": "#include <stdio.h>\nint main(void){\n\tint n; scanf(\"%d\", &n);\n\tif(n%2==0) printf(\"%d\", 1<<(n/2));\n\telse printf(\"0\");\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1182",
    "index": "B",
    "title": "Plus from Picture",
    "statement": "You have a given picture with size $w \\times h$. Determine if the given picture has a single \"+\" shape or not. A \"+\" shape is described below:\n\n- A \"+\" shape has one center nonempty cell.\n- There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction.\n- All other cells are empty.\n\nFind out if the given picture has single \"+\" shape.",
    "tutorial": "First, try to find if there is any nonempty space which has 4 neighbors are all nonempty spaces. (Giant black star in the picture below.) If there is no such nonempty space, the answer is \"NO\". Second, try to search the end of the \"+\" shape from the center. (White stars in the picture below.) Third, try to find if there is any nonempty space outside of \"+\" shape(the area filled with \"?\"). If found then the answer is \"NO\". If you validated all steps, then the answer is \"YES\". Time complexity is $O(wh)$.",
    "code": "#include <iostream>\n#include <string>\n#include <vector>\n \nint main(void){\n\t\n\tint w, h; std::cin >> h >> w;\n\tstd::vector<std::string> picture(h);\n\tfor(int i=0; i<h; i++) std::cin >> picture[i];\n\tstd::vector<std::vector<bool>> should_be_plus(h, std::vector<bool>(w, false));\n\t\n\tfor(int i=1; i<h-1; i++){\n\t\tfor(int j=1; j<w-1; j++){\n\t\t\tif(picture[i][j] == '*' && picture[i-1][j] == '*' && picture[i+1][j] == '*'\n\t\t\t\t&& picture[i][j+1] == '*' && picture[i][j-1] == '*'){ // Center found\n\t\t\t\t\n\t\t\t\tint upend = i, downend = i, leftend = j, rightend = j;\n\t\t\t\twhile(upend >= 0 && picture[upend][j] == '*') should_be_plus[upend--][j] = true;\n\t\t\t\twhile(downend < h && picture[downend][j] == '*') should_be_plus[downend++][j] = true;\n\t\t\t\twhile(leftend >= 0 && picture[i][leftend] == '*') should_be_plus[i][leftend--] = true;\n\t\t\t\twhile(rightend < w && picture[i][rightend] == '*') should_be_plus[i][rightend++] = true;\n\t\t\t\t//printf(\"End: up %d down %d left %d right %d\\n\", upend, downend, leftend, rightend);\n\t\t\t\t\n\t\t\t\t// If there is outside area exist then NO.\n\t\t\t\tfor(int i2=0; i2<h; i2++) for(int j2=0; j2<w; j2++){\n\t\t\t\t\tif(should_be_plus[i2][j2] != (picture[i2][j2] == '*')){\n\t\t\t\t\t\t//std::cout << \"Outside found \";\n\t\t\t\t\t\tstd::cout << \"NO\\n\";\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Ok\n\t\t\t\tstd::cout << \"YES\\n\";\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\t//std::cout << \"No center found \";\n\tstd::cout << \"NO\\n\";\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "implementation",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1182",
    "index": "C",
    "title": "Beautiful Lyrics",
    "statement": "You are given $n$ words, each of which consists of lowercase alphabet letters. Each word \\textbf{contains at least} one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.\n\nEach lyric consists of two lines. Each line consists of two words separated by whitespace.\n\nA lyric is beautiful if and only if it satisfies all conditions below.\n\n- The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line.\n- The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line.\n- The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel.\n\nAlso, letters \"a\", \"e\", \"o\", \"i\", and \"u\" are vowels. Note that \"y\" is \\textbf{never} vowel.\n\nFor example of a beautiful lyric,\n\n\\begin{center}\n\"hello hellooowww\" \"whatsup yowowowow\"\n\\end{center}\n\nis a beautiful lyric because there are two vowels each in \"hello\" and \"whatsup\", four vowels each in \"hellooowww\" and \"yowowowow\" (keep in mind that \"y\" is not a vowel), and the last vowel of each line is \"o\".For example of a not beautiful lyric,\n\n\\begin{center}\n\"hey man\"\"iam mcdic\"\n\\end{center}\n\nis not a beautiful lyric because \"hey\" and \"iam\" don't have same number of vowels and the last vowels of two lines are different (\"a\" in the first and \"i\" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.",
    "tutorial": "Let's make some definitions; $s_{1}$ and $s_{2}$ are complete duo if two word $s_{1}$ and $s_{2}$ have same number of vowels and the last vowels of $s_{1}$ and $s_{2}$ are same. For example, \"hello\" and \"hollow\" are complete duo. $s_{1}$ and $s_{2}$ are semicomplete duo if two word $s_{1}$ and $s_{2}$ have same number of vowels but the last vowels of $s_{1}$ and $s_{2}$ are different. For example, \"hello\" and \"hola\" are semicomplete duo. If you want to form a beautiful lyric with $4$ words, then the lyric must be one of the things listed below; Consist of two complete duos. Consist of one semicomplete duo and one complete duo. Since the order of lyrics is not important, make complete duos as many as possible, then make semicomplete duos as many as possible. This can be done with the greedy approach with the usage of the red-black tree or hashmap. After you formed all duos, make beautiful lyrics using one semicomplete duo and one complete duo first, then make beautiful lyrics using two complete duos. With this method, you can make the maximum possible number of beautiful lyrics. Time complexity is $O(n \\text{ log } n)$ or $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n#include <utility>\n#include <map>\n \n// Typedef\ntypedef std::pair<std::string, std::string> strduo;\n \n// Vowel related\nbool isVowel(char c){\n\treturn c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';\n}\nint vowelCount(std::string &word){\n\tint count = 0;\n\tfor(auto ch: word) if(isVowel(ch)) count++;\n\treturn count;\n}\nchar lastVowel(std::string &word){\n\tfor(int i=word.length()-1; i>=0; i--){\n\t\tif(isVowel(word[i])) return word[i];\n\t} throw \"No vowels\";\n}\n \nint main(void){\n\t\n\t// Get input\n\tint n; std::cin >> n;\n\tstd::vector<std::string> totalwords;\n\tstd::map<int, std::map<char, std::vector<std::string>>> strings_by_vowels;\n\tfor(int i=0; i<n; i++){\n\t\tstd::string word; std::cin >> word;\n\t\ttotalwords.push_back(word);\n\t\tint vowelcount = vowelCount(word);\n\t\tchar lastvowel = lastVowel(word);\n\t\tstrings_by_vowels[vowelcount][lastvowel].push_back(word);\n\t}\n\t\n\t/*for(auto it: strings_by_vowels){\n\t\tprintf(\"Vowel count %2d:\\n\", it.first);\n\t\tfor(auto it2: it.second){\n\t\t\tprintf(\"  %c: \", it2.first);\n\t\t\tfor(auto it3: it2.second) printf(\"%s \", it3.c_str()); printf(\"\\n\");\n\t\t}\n\t}\n\tprintf(\"===============\\n\");*/\n\t\n\t// Construct duos; Complete: SameCount+SameLast, Semicomplete: SameCount\n\tstd::vector<strduo> complete_duos, semicomplete_duos;\n\tfor(auto &same_counts: strings_by_vowels){\n\t\t\n\t\t// Complete duos\n\t\tfor(auto &same_lasts: same_counts.second){\n\t\t\twhile(same_lasts.second.size() >= 2){\n\t\t\t\tstd::string firstline = same_lasts.second.back();\n\t\t\t\tsame_lasts.second.pop_back();\n\t\t\t\tstd::string secondline = same_lasts.second.back();\n\t\t\t\tsame_lasts.second.pop_back();\n\t\t\t\tcomplete_duos.push_back({firstline, secondline});\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Semicomplete duos\n\t\tstd::vector<std::string> remainings;\n\t\tfor(auto &same_lasts: same_counts.second){\n\t\t\tfor(auto &word: same_lasts.second) remainings.push_back(word);\n\t\t\tsame_lasts.second.clear();\n\t\t}\n\t\twhile(remainings.size() >= 2){\n\t\t\tstd::string firstline = remainings.back(); remainings.pop_back();\n\t\t\tstd::string secondline = remainings.back(); remainings.pop_back();\n\t\t\tsemicomplete_duos.push_back({firstline, secondline});\n\t\t}\n\t}\n\t\n\t// Construct lyrics\n\tstd::vector<strduo> wholeLyric;\n\twhile(!semicomplete_duos.empty() && !complete_duos.empty()){\n\t\tstrduo semicomplete_duo = semicomplete_duos.back();\n\t\tsemicomplete_duos.pop_back();\n\t\tstrduo complete_duo = complete_duos.back();\n\t\tcomplete_duos.pop_back();\n\t\twholeLyric.push_back({semicomplete_duo.first, complete_duo.first});\n\t\twholeLyric.push_back({semicomplete_duo.second, complete_duo.second});\n\t}\n\twhile(complete_duos.size() >= 2){\n\t\tstrduo complete_duo1 = complete_duos.back(); complete_duos.pop_back();\n\t\tstrduo complete_duo2 = complete_duos.back(); complete_duos.pop_back();\n\t\twholeLyric.push_back({complete_duo1.first, complete_duo2.first});\n\t\twholeLyric.push_back({complete_duo1.second, complete_duo2.second});\n\t}\n\t\n\t// Print\n\tstd::cout << wholeLyric.size() / 2 << '\\n';\n\tfor(strduo &lyric: wholeLyric) std::cout << lyric.first << ' ' << lyric.second << '\\n';\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1182",
    "index": "D",
    "title": "Complete Mirror",
    "statement": "You have given tree consist of $n$ vertices. Select a vertex as root vertex that satisfies the condition below.\n\n- For all vertices $v_{1}$ and $v_{2}$, if $distance$($root$, $v_{1}$) $= distance$($root$, $v_{2})$ then $degree$($v_{1}$) $= degree$($v_{2}$), where $degree$ means the number of vertices connected to that vertex, and $distance$ means the number of edges between two vertices.\n\nDetermine and find if there is such root vertex in the tree. If there are multiple answers, find any of them.",
    "tutorial": "First, the valid tree should form like the picture below unless the whole tree is completely linear. top: This node is the top of the tree. This node has always degree $1$. This node is always one of the possible answers of valid tree. There might be no top node in the tree. semitop: This node is the closest children from the top node that satisfies $degree >= 3$. In other words, this node is the end of the leaf branch which includes top node as leaf. This node can be one of the possible answers of valid tree. If there is no semitop in the tree, the whole tree is invalid. mid level: This is the area of nodes between semitop node and semibottom nodes. semibottom: These nodes are the closest ancestors from each leaf nodes which satisfies $degree >= 3$. In other words, these nodes are the end of each leaf branches. bottom: These nodes are the leaves except top node. And also let's define $u_{1}$ and $u_{2}$ are directly reachable if there are only nodes with $degree = 2$ between $u_{1}$ and $u_{2}$ exclusive. There are two ways to find the top node and the semitop node. Lawali's solution. Find the diameter path and validate for two leaves of the diameter path. If no valid vertex found(i.e. top is not in the diameter path), then the semitop should be the middle of the diameter path. Now validate for the semitop and the closest directly reachable leaf from semitop. If any valid vertex found, print it. Otherwise print $-1$. The first case of diameter path in valid tree. Semitop node is the middle of diameter path. The second case of diameter path in valid tree. Top node is the end of diameter path. The first case of diameter path in valid tree. Semitop node is the middle of diameter path. The second case of diameter path in valid tree. Top node is the end of diameter path. The second case of diameter path in valid tree. Top node is the end of diameter path. McDic's solution. Clone the whole tree and cut the leaf branches(include top) from the cloned tree. Let's call this tree as \"inner tree\". Inner tree consists of only semitop, mid level nodes and semibottom nodes. Then you can find the semitop by collapsing each level from leaf nodes of inner tree. Now validate for semitop, the furthest directly reachable leaf node from semitop, and the closest directly reachable leaf node from semitop. It is guaranteed that the top node is one of those two leaves. If any valid vertex found, print it. Otherwise print $-1$. This is the inner tree of original tree. You can find the semitop easier than before since top is removed in inner tree. This is the inner tree of original tree. You can find the semitop easier than before since top is removed in inner tree. Time complexity is $O(n)$.",
    "code": "#include <stdio.h>\n#include <vector>\n#include <set>\n#include <utility>\n#include <algorithm>\n \n// Graph attributes\ntypedef std::vector<std::set<int>> EDGE;\nint v;\nstd::vector<bool> isInner;\nEDGE edges, inneredges;\n \n// Validation\nbool validate(int root){\n\t\n\t//printf(\"Validating for %d\\n\", root);\n\tstd::vector<bool> visited(v+1, false);\n\tstd::vector<int> nowlook = {root};\n\twhile(!nowlook.empty()){\n\t\tstd::set<int> degrees;\n\t\tstd::vector<int> nextlook;\n\t\tfor(auto now: nowlook) visited[now] = true;\n\t\tfor(auto now: nowlook){\n\t\t\tfor(auto next: edges[now]){\n\t\t\t\tif(!visited[next]){\n\t\t\t\t\tnextlook.push_back(next);\n\t\t\t\t\tdegrees.insert(edges[next].size());\n\t\t\t\t\tif(degrees.size() >= 2) return false;\n\t\t\t\t}\n\t\t\t}\n\t\t} nowlook = nextlook;\n\t} return true;\n}\n \n// Calculate distances for directly reachable nodes. -1 for not set.\nvoid directDistanceCalculation(int now, std::vector<int> &distance){\n\tfor(auto next: edges[now]){\n\t\tif(distance[next] == -1 && edges[next].size() <= 2){\n\t\t\tdistance[next] = distance[now]+1;\n\t\t\tdirectDistanceCalculation(next, distance);\n\t\t}\n\t}\n}\n \nint main(void){\n\t\n\t// Get input and construct tree\n\tscanf(\"%d\", &v); \n\tedges.resize(v+1);\n\tisInner.resize(v+1, true);\n\tfor(int i=1; i<v; i++){\n\t\tint u1, u2; scanf(\"%d %d\", &u1, &u2);\n\t\tedges[u1].insert(u2);\n\t\tedges[u2].insert(u1);\n\t} inneredges = edges;\n\t\n\t// Construct inner tree\n\t//printf(\"Constructing inner tree:\\n\");\n\tfor(int start=1; start<=v; start++){\n\t\tif(edges[start].size() == 1 && inneredges[start].size() == 1){\n\t\t\tint now = start;\n\t\t\twhile(edges[now].size() <= 2 && inneredges[now].size() == 1){\n\t\t\t\t//printf(\"Removing %d\\n\", now);\n\t\t\t\tint next = *(inneredges[now].begin());\n\t\t\t\tinneredges[now].clear();\n\t\t\t\tinneredges[next].erase(now);\n\t\t\t\tisInner[now] = false;\n\t\t\t\tnow = next;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Corner case: No inner tree => See leaf\n\t//printf(\"Let's see if this is corner case\\n\");\n\tint innervertices = 0;\n\tstd::vector<int> leaves;\n\tfor(int u=1; u<=v; u++){\n\t\tif(isInner[u]) innervertices++;\n\t\tif(edges[u].size() == 1) leaves.push_back(u);\n\t}\n\tif(innervertices == 0){\n\t\t//printf(\"ok no inner\\n\");\n\t\tfor(auto leaf: leaves){\n\t\t\tif(validate(leaf)){\n\t\t\t\tprintf(\"%d\\n\", leaf);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tthrow \"???\";\n\t}\n\t\n\t// Collapse inner tree\n\t//printf(\"Let's collapse inner tree\\n\");\n\tstd::vector<bool> collapseVisited(v+1, false);\n\tstd::vector<int> nowlook;\n\tfor(int u=1; u<=v; u++) if(isInner[u] && inneredges[u].size() <= 1) nowlook.push_back(u);\n\twhile(nowlook.size() >= 2){\n\t\tstd::set<int> nextlook;\n\t\tfor(auto now: nowlook) collapseVisited[now] = true;\n\t\tfor(auto now: nowlook) for(auto next: inneredges[now]) if(!collapseVisited[next]) nextlook.insert(next);\n\t\tnowlook.clear();\n\t\tfor(auto next: nextlook) nowlook.push_back(next);\n\t}\n\t\n\t// Corner case 2: No semitop\n\tif(nowlook.empty()){\n\t\tprintf(\"-1\\n\"); \n\t\treturn 0;\n\t}\n\t\n\t// Semitop validation\n\tint semitop = nowlook[0];\n\t//printf(\"Ok semitop is %d\\n\", semitop);\n\tif(validate(semitop)){\n\t\tprintf(\"%d\\n\", semitop);\n\t\treturn 0;\n\t}\n\t\n\t// Calculate distances for directly reachable leaves\n\tstd::vector<int> dirDist(v+1, -1);\n\tdirDist[semitop] = 0;\n\tdirectDistanceCalculation(semitop, dirDist);\n\tstd::vector<std::pair<int, int>> directLeaves;\n\tfor(int u=1; u<=v; u++){\n\t\tif(edges[u].size() == 1 && dirDist[u] != -1) \n\t\t\tdirectLeaves.push_back({dirDist[u], u});\n\t} std::sort(directLeaves.begin(), directLeaves.end());\n\t\n\t// Validate for the furthest leaf and the closest leaf\n\tif(!directLeaves.empty()){\n\t\tint closestLeaf = directLeaves.front().second;\n\t\tint furthestLeaf = directLeaves.back().second;\n\t\tif(validate(closestLeaf)){\n\t\t\tprintf(\"%d\\n\", closestLeaf);\n\t\t\treturn 0;\n\t\t}\n\t\telse if(validate(furthestLeaf)){\n\t\t\tprintf(\"%d\\n\", furthestLeaf);\n\t\t\treturn 0;\n\t\t}\n\t}\n\tprintf(\"-1\\n\");\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "hashing",
      "implementation",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1182",
    "index": "E",
    "title": "Product Oriented Recurrence",
    "statement": "Let $f_{x} = c^{2x-6} \\cdot f_{x-1} \\cdot f_{x-2} \\cdot f_{x-3}$ for $x \\ge 4$.\n\nYou have given integers $n$, $f_{1}$, $f_{2}$, $f_{3}$, and $c$. Find $f_{n} \\bmod (10^{9}+7)$.",
    "tutorial": "You can form the expression into this; $c^{x} f_{x} = c^{x-1} f_{x-1} \\cdot c^{x-2} f_{x-2} \\cdot c^{x-3} f_{x-3}$ Let $g(x, p) = c^{x} f_{x}$'s $p$-occurrence for prime number $p$. For example, $40 = 2^{3} \\times 5$ so $40$'s $2$-occurrence is $3$. Then we can set the formula $g(x, p) = g(x-1, p) + g(x-2, p) + g(x-3, p)$ and calculate $g(n, p)$ using matrix exponentiation. Since all different prime numbers $p$ share same matrix, we can calculate matrix only once. And we have less or equal than 36 distinct prime numbers targeted because you cannot get more than $9$ distinct prime numbers by prime decomposition from numbers in range $[1, 10^9]$. With $g(x, p)$ we can calculate $c^{n} f_{n}$, and we can calculate $f_{n}$ using modulo inverse. Time complexity is $O(\\text{log } n + \\text{ sqrt}(\\text{max}(f_{1}, f_{2}, f_{3}, c)))$.",
    "code": "#include <stdio.h>\n#include <vector>\n#include <set>\n#include <map>\n \n// Constants\ntypedef long long int lld;\nconst lld R = 1000 * 1000 * 1000 + 7; // a^(R-1) = 1 (mod R)\nconst lld matrixRemainder = R-1;\n \n// Matrix class\nclass matrix{\npublic:\n\t\n\t// Attributes\n\tint row, col;\n\tstd::vector<std::vector<lld>> num;\n\t\n\t// Constructor\n\tmatrix(int row, int col, int defaultValue = 0){\n\t\tthis->num = std::vector<std::vector<lld>>(row, std::vector<lld>(col, defaultValue));\n\t\tthis->row = row, this->col = col;\n\t}\n\tmatrix(std::vector<std::vector<lld>> num){\n\t\tthis->num = num;\n\t\tthis->row = this->num.size();\n\t\tthis->col = this->num[0].size();\n\t}\n\t\n\t// Operator\n\tmatrix operator *(matrix &another){\n\t\tif(this->col != another.row){\n\t\t\tprintf(\"Wrong size: %d*%d X %d*%d\\n\", this->row, this->col, another.row, another.col);\n\t\t\tthrow \"Wrong size\";\n\t\t}\n\t\tmatrix newone(this->row, another.col);\n\t\tfor(int r=0; r<newone.row; r++) for(int c=0; c<newone.col; c++){\n\t\t\tfor(int k=0; k<this->col; k++){\t\n\t\t\t\tnewone.num[r][c] += this->num[r][k] * another.num[k][c];\n\t\t\t\tnewone.num[r][c] %= matrixRemainder;\n\t\t\t}\n\t\t} return newone;\n\t}\t\n\t\n\t// Power\n\tmatrix operator ^(lld x){\n\t\tif(x==0){\n\t\t\tprintf(\"Not implemented yet.\\n\");\n\t\t\tthrow \"Not implemented\";\n\t\t}\n\t\telse if(x==1) return *this;\n\t\telse{\n\t\t\tmatrix halfpower = (*this) ^ (x/2);\n\t\t\tif(x%2 == 0) return halfpower * halfpower;\n\t\t\telse return halfpower * halfpower * (*this);\n\t\t}\n\t}\n};\n \n// Prime related\nconst int limit = 1<<20;\nbool isPrime[limit] = {false, };\nstd::vector<lld> primes;\n \n// Decomposite given value to primes\nstd::vector<lld> primeDecomposition(lld x){\n\tstd::vector<lld> answer;\n\tfor(lld p: primes){\n\t\tif(x <= 1) break;\n\t\telse if(x%p == 0){\n\t\t\tanswer.push_back(p);\n\t\t\twhile(x%p == 0) x /= p;\n\t\t}\n\t\telse if(p*p > x){\n\t\t\tanswer.push_back(x);\n\t\t\tbreak;\n\t\t}\n\t} return answer;\n}\n \n// Return a^x % R\nlld power(lld a, lld x){\n\tif(x==0) return 1;\n\tlld half = power(a, x/2);\n\tif(x%2 == 0) return half*half%R;\n\telse return half*half%R*a%R;\n}\n \n// Main function\nint main(void){\n\t\n\t// Matrix functionality testing\n\t//matrix a1({{1, 2}, {0, 1}}), a2({{3, 2}, {-1, 0}});\n\t//matrix b = a1*a2;\n\t//printf(\"a1*a2 = \\n  %lld %lld\\n  %lld %lld\\n\", b.num[0][0], b.num[0][1], b.num[1][0], b.num[1][1]);\n\t\n\t// Calculate primes\n\tfor(int i=2; i<limit; i++) isPrime[i] = true;\n\tfor(int i=2; i<limit; i++) if(isPrime[i]){\n\t\tprimes.push_back((lld)i);\n\t\tfor(int j=2*i; j<limit; j+=i) isPrime[j] = false;\n\t}\n\t\n\t// Get input\n\tlld n, f[4], c; scanf(\"%lld %lld %lld %lld %lld\", &n, &f[1], &f[2], &f[3], &c);\n\tmatrix baseLogPropagate({{1, 1, 1}, {1, 0, 0}, {0, 1, 0}});\n\tmatrix totalLogPropagate = baseLogPropagate ^ (n-3);\n\t\n\t// Calculate target primes\n\tstd::set<lld> knownprimes;\n\tfor(int i=1; i<=3; i++) for(lld p: primeDecomposition(f[i])) knownprimes.insert(p);\n\tfor(lld p: primeDecomposition(c)) knownprimes.insert(p);\n\t//printf(\"Known primes: \"); for(lld knownprime: knownprimes) printf(\"%lld, \", knownprime); printf(\"\\n\");\n\t\n\t// Calculate c^n * f[n]'s prime count: initPrimeCount[x]: f[3-x]'s p-occurrence\n\tstd::map<lld, lld> fnPrimeCount; \n\tfor(lld p: knownprimes){\n\t\tmatrix initPrimeCount(3, 1);\n\t\tfor(int i=1; i<=3; i++){\n\t\t\tfor(lld num = f[i]; num%p == 0; num /= p) initPrimeCount.num[3-i][0]++; // f[n]\n\t\t\tfor(lld num = c; num%p == 0; num /= p) initPrimeCount.num[3-i][0] += i; // c^n\n\t\t}\n\t\tmatrix lastPrimeCount = totalLogPropagate * initPrimeCount;\n\t\tfnPrimeCount[p] = lastPrimeCount.num[0][0];\n\t}\n\t\n\t// Calculate answer = product(p^fnPrimeCount[p]) * c^(-n)\n\tlld answer = 1;\n\tfor(auto pinfo: fnPrimeCount){\n\t\t//printf(\"%lld-occurrence = %lld\\n\", pinfo.first, pinfo.second);\n\t\tanswer *= power(pinfo.first, pinfo.second);\n\t\tanswer %= R;\n\t}\n\tanswer *= power(power(c, R-2), n); answer %= R;\n\tprintf(\"%lld\\n\", answer);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math",
      "matrices",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1182",
    "index": "F",
    "title": "Maximum Sine",
    "statement": "You have given integers $a$, $b$, $p$, and $q$. Let $f(x) = \\text{abs}(\\text{sin}(\\frac{p}{q} \\pi x))$.\n\nFind minimum possible integer $x$ that maximizes $f(x)$ where $a \\le x \\le b$.",
    "tutorial": "Lemma: For all $x$, $y$ $\\in [0, \\pi]$, if $|\\text{sin}(x)| > |\\text{sin}(y)|$ then $x$ is more closer to the $\\frac{\\pi}{2}$ than $y$. With this lemma, we can avoid the calculation of floating precision numbers. Let's reform the problem; Find minimum possible integer $x$ that $\\frac{p}{q}x \\pi \\bmod \\pi$ is the closest to $\\frac{\\pi}{2}$. This is equivalent to find minimum possible integer $x$ that $2px \\bmod 2q$ is the closest to $q$. Let $g(x) = 2px \\bmod 2q$. Now set the interval with length $t = \\text{sqrt}(b-a+1)$ and construct the list like this - $[(g(a), a), (g(a+1), a+1), \\ldots (g(a+t-1), a+t-1)]$. Then remove the big number $x$s with duplicated $g(x)$ values from the list and sort the list. Now we can find any $x$ that $g(x)$ is the closest to any integer $y$ in $O(\\text{log}(n))$. We will search all numbers in range $[a, b]$ without modifying the list we created. How is this possible? Because $g(x) + g(y) \\equiv g(x+y) \\pmod{2q}$ for all integers $x$, $y$. So in every $\\text{sqrt}(b-a+1)$ iterations, we can set the target and just find. More precisely, our target value is $q - 2 \\times i \\cdot t \\cdot p \\bmod 2q$ for $i$-th iteration. With this search, we can find such minimum possible integer $x$. Oh, don't forget to do bruteforce in remaining range! The time complexity is $O(\\text{sqrt } n \\text{ log } n)$.",
    "code": "#include <stdio.h>\n#include <vector>\n#include <map>\n#include <utility>\n#include <algorithm>\n \ntypedef long long int lld;\nconst lld infL = 1LL << 60;\n \n// Find x that abs(sin(p/q pi x)) is the largest in [start, end).\nint solve(lld start, lld end, lld p, lld q){\n\t\n\t// Construct base intervals\n\tlld interval = 1;\n\twhile(interval * interval < end - start) interval++;\n\t\n\t// Period is q/p. x should be the closest to the middle of period(q/2p).\n\t// x % (2q/2p) should be the closest to q/2p => 2px % 2q should be the closest to q.\n\t// Construct remainders\n\tstd::vector<std::pair<lld, lld>> remainders, remainders_copy;\n\tfor(lld i=start; i<start+interval; i++){\n\t\tlld key = 2*p*i % (2*q);\n\t\tremainders.push_back({key, i});\n\t}\n\tstd::sort(remainders.begin(), remainders.end());\n\tremainders_copy = remainders; remainders.clear();\n\tremainders.push_back(remainders_copy[0]);\n\tfor(int i=1; i<remainders_copy.size(); i++){\n\t\tif(remainders_copy[i].first != remainders_copy[i-1].first)\n\t\t\tremainders.push_back(remainders_copy[i]);\n\t} remainders_copy.clear();\n\t\n\t\n\t// Look in [start + i*interval, start + (i+1)*interval), start + (i+1)*interval <= end.\n\t// x + i*interval ~= q/2p => x ~= q/2p - i*interval.\n\t//printf(\"base interval = %lld\\n\", interval);\n\tlld answervalue = -1, answerdistance = infL, iteration = 0;\n\tfor(iteration = 0; start + (iteration+1)*interval <= end; iteration++){\n\t\tlld look = q - iteration * interval * 2 * p; // iteration * interval <= interval^2 <= end - start <= 10^8\n\t\tlook %= (2*q); if(look < 0) look += 2*q;\n\t\t//printf(\"Looking %lld in [%lld, %lld)\\n\", look, start + iteration*interval, start + (iteration+1)*interval);\n\t\tlld baseindex = std::lower_bound(remainders.begin(), remainders.end(), std::make_pair(look, -infL)) - remainders.begin();\n\t\tfor(int j=0; j>=-1; j--){\n\t\t\tlld thisindex = (baseindex+j) % remainders.size(); if(thisindex < 0) thisindex += remainders.size();\n\t\t\tlld thisvalue = remainders[thisindex].second + iteration * interval;\n\t\t\tlld thisdistance = look - remainders[thisindex].first; \n\t\t\tif(thisdistance < 0) thisdistance *= -1;\n\t\t\tif(thisdistance > q) thisdistance = 2*q - thisdistance;\n\t\t\t//printf(\"  Looking baseindex = %lld, thisindex = %lld, thisfirst = %lld, thisvalue = %lld (distance %lld)\\n\", \n\t\t\t//\tbaseindex, thisindex, thisvalue, remainders[thisindex].first, thisdistance);\n\t\t\tif(std::make_pair(thisdistance, thisvalue) < std::make_pair(answerdistance, answervalue)){\n\t\t\t\tanswervalue = thisvalue;\n\t\t\t\tanswerdistance = thisdistance;\n\t\t\t\t//printf(\"  Answer changed to %lld (distance %lld)\\n\", answervalue, answerdistance);\n\t\t\t}\n\t\t}\n\t} \n\t\n\t// Brute force for remaining ranges\n\tfor(lld v = start + iteration * interval; v < end; v++){\n\t\t//printf(\"Looking %lld\\n\", v);\n\t\tlld thisdistance = (2*p*v) % (2*q) - q; if(thisdistance < 0) thisdistance *= -1;\n\t\tif(std::make_pair(thisdistance, v) < std::make_pair(answerdistance, answervalue)){\n\t\t\tanswerdistance = thisdistance;\n\t\t\tanswervalue = v;\n\t\t\t//printf(\"  Answer changed to %lld (distance %lld)\\n\", answervalue, answerdistance);\n\t\t}\n\t}\n\t\n\treturn answervalue;\n}\n \nint main(void){\n\tint testcases; scanf(\"%d\", &testcases);\n\tfor(int t=0; t<testcases; t++){\n\t\tlld a, b, p, q; scanf(\"%lld %lld %lld %lld\", &a, &b, &p, &q);\n\t\t//printf(\"Case #%d: \", t+1);\n\t\tprintf(\"%d\\n\", solve(a, b+1, p, q));\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1183",
    "index": "A",
    "title": "Nearest Interesting Number",
    "statement": "Polycarp knows that if the sum of the digits of a number is divisible by $3$, then the number itself is divisible by $3$. He assumes that the numbers, the sum of the digits of which is divisible by $4$, are also somewhat interesting. Thus, he considers a positive integer $n$ interesting if its sum of digits is divisible by $4$.\n\nHelp Polycarp find the nearest larger or equal interesting number for the given number $a$. That is, find the interesting number $n$ such that $n \\ge a$ and $n$ is minimal.",
    "tutorial": "Even if we will iterate over all possible numbers starting from $a$ and check if sum of digits of the current number is divisible by $4$, we will find the answer very fast. The maximum possible number of iterations is no more than $5$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint sum(int a) {\n    int result = 0;\n    while (a > 0) {\n        result += a % 10;\n        a /= 10;\n    }\n    return result;\n}\n\nint main() {\n    int a;\n    cin >> a;\n    while (sum(a) % 4 != 0) {\n        a++;\n    }\n    cout << a << endl;\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1183",
    "index": "B",
    "title": "Equalize Prices",
    "statement": "There are $n$ products in the shop. The price of the $i$-th product is $a_i$. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.\n\nIn fact, the owner of the shop can change the price of some product $i$ in such a way that the difference between the old price of this product $a_i$ and the new price $b_i$ is at most $k$. In other words, the condition $|a_i - b_i| \\le k$ should be satisfied ($|x|$ is the absolute value of $x$).\n\nHe can change the price for each product \\textbf{not more than once}. Note that he can leave the old prices for some products. The new price $b_i$ of each product $i$ should be positive (i.e. $b_i > 0$ should be satisfied for all $i$ from $1$ to $n$).\n\nYour task is to find out the \\textbf{maximum} possible \\textbf{equal} price $B$ of \\textbf{all} productts with the restriction that for all products the condiion $|a_i - B| \\le k$ should be satisfied (where $a_i$ is the old price of the product and $B$ is the same new price of all products) or report that it is impossible to find such price $B$.\n\n\\textbf{Note that the chosen price $B$ should be integer}.\n\nYou should answer $q$ independent queries.",
    "tutorial": "It is very intuitive that the maximum price we can obtain is $min + k$ where $min$ is the minimum value in the array. For this price we should check that we can change prices of all products to it. It can be done very easily: we can just check if each segment $[a_i - k; a_i + k]$ covers the point $min + k$. But this is not necessary because if we can change the price of the maximum to this value ($min + k$) then we can change each price in the segment $[min; max]$ to this value. So we just need to check that $min + k \\ge max - k$ and if it is then print $min + k$ otherwise print -1.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<int> a(n);\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tcin >> a[j];\n\t\t}\n\t\tint mn = *min_element(a.begin(), a.end());\n\t\tint mx = *max_element(a.begin(), a.end());\n\t\tif (mx - mn > 2 * k) cout << -1 << endl;\n\t\telse cout << mn + k << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1183",
    "index": "C",
    "title": "Computer Game",
    "statement": "Vova is playing a computer game. There are in total $n$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $k$.\n\nDuring each turn Vova can choose what to do:\n\n- If the current charge of his laptop battery is strictly greater than $a$, Vova can just play, and then the charge of his laptop battery will decrease by $a$;\n- if the current charge of his laptop battery is strictly greater than $b$ ($b<a$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $b$;\n- if the current charge of his laptop battery is less than or equal to $a$ and $b$ at the same time then Vova cannot do anything and loses the game.\n\n\\textbf{Regardless of Vova's turns the charge of the laptop battery is always decreases}.\n\nVova wants to complete the game (Vova can complete the game if after each of $n$ turns the charge of the laptop battery is \\textbf{strictly greater than $0$}). Vova has to play \\textbf{exactly $n$ turns}. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (\\textbf{first type turn}) is the \\textbf{maximum} possible. It is possible that Vova cannot complete the game at all.\n\nYour task is to find out the \\textbf{maximum} possible number of turns Vova can just play (make the \\textbf{first type turn}) or report that Vova cannot complete the game.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "Firstly, about the problem description. Vova really needs to complete the game i. e. play all $n$ turns. Exactly $n$ turns. Among all possible ways to do it he need choose one where the number of turns when he just plays (this is the first type turn!) is maximum possible. Suppose the answer is $n$. Then the charge of the battery after $n$ turns will be $c = k - na$. If this value is greater than $0$ then the answer is $n$. Otherwise we need to replace some turns when Vova just plays with turns when Vova plays and charges. The charge of the battery will increase by $diff = a - b$ avfter one replacement. We have to obtain $c > 0$ with some replacements. The number of turns to do it is equals to $turns = \\lceil\\frac{-c + 1}{diff}\\rceil$, where $\\lceil\\frac{x}{y}\\rceil$ is $x$ divided by $y$ rounded up. If $turns > n$ then the answer is -1. Otherwise the answer is $n - turns$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tlong long k, n, a, b;\n\t\tcin >> k >> n >> a >> b;\n\t\tk -= n * a;\n\t\tif (k > 0) {\n\t\t\tcout << n << endl;\n\t\t} else {\n\t\t\tk = -k;\n\t\t\t++k;\n\t\t\tlong long diff = a - b;\n\t\t\tlong long turns = (k + diff - 1) / diff;\n\t\t\tif (turns > n) {\n\t\t\t\tcout << -1 << '\\n';\n\t\t\t} else {\n\t\t\t\tcout << n - turns << '\\n';\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1183",
    "index": "D",
    "title": "Candy Box (easy version)",
    "statement": "\\textbf{This problem is actually a subproblem of problem G from the same contest.}\n\nThere are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \\le a_i \\le n$).\n\nYou have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $1$ and two candies of type $2$ is bad).\n\n\\textbf{It is possible that multiple types of candies are completely absent from the gift}. It is also possible that \\textbf{not all candies} of some types will be taken to a gift.\n\nYour task is to find out the \\textbf{maximum} possible size of the single gift you can prepare using the candies you have.\n\nYou have to answer $q$ independent queries.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "Let's calculate the array $cnt$ where $cnt_i$ is the number of candies of the $i$-th type. Let's sort it in non-ascending order. Obviously, now we can take $cnt_1$ because this is the maximum number of candies of some type in the array. Let $lst$ be the last number of candies we take. Initially it equals $cnt_1$ (and the answer $ans$ is initially the same number). Then let's iterate over all values of $cnt$ in order from left to right. If the current number $cnt_i$ is greater than or equal to the last taken number of candies $lst$ then we cannot take more candies than $lst - 1$ (because we iterating over values of $cnt$ in non-ascending order), so let's increase answer by $lst - 1$ and set $lst := lst - 1$. Otherwise $cnt_i < lst$ and we can take all candies of this type, increase the answer by $cnt_i$ and set $lst := cnt_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint q;\n\tcin >> q;\n\tfor (int t = 0; t < q; ++t) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> cnt(n + 1);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\t++cnt[x];\n\t\t}\n\t\tsort(cnt.rbegin(), cnt.rend());\n\t\tint ans = cnt[0];\n\t\tint lst = cnt[0];\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\tif (lst == 0) break;\n\t\t\tif (cnt[i] >= lst) {\n\t\t\t\tans += lst - 1;\n\t\t\t\tlst -= 1;\n\t\t\t} else {\n\t\t\t\tans += cnt[i];\n\t\t\t\tlst = cnt[i];\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1183",
    "index": "E",
    "title": "Subsequences (easy version)",
    "statement": "\\textbf{The only difference between the easy and the hard versions is constraints}.\n\nA subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string \"abaca\" the following strings are subsequences: \"abaca\", \"aba\", \"aaa\", \"a\" and \"\" (empty string). But the following strings are not subsequences: \"aabaca\", \"cb\" and \"bcaa\".\n\nYou are given a string $s$ consisting of $n$ lowercase Latin letters.\n\nIn one move you can take \\textbf{any} subsequence $t$ of the given string and add it to the set $S$. The set $S$ can't contain duplicates. This move costs $n - |t|$, where $|t|$ is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).\n\nYour task is to find out the minimum possible total cost to obtain a set $S$ of size $k$ or report that it is impossible to do so.",
    "tutorial": "The topic of this problem is BFS. Let strings be the vertices of the graph and there is a directed edge from string $s$ to string $t$ if and only if we can obtain $t$ from $s$ by removing exactly one character. In this interpretation we have to find first $k$ visited vertices if we start our BFS from the initial string. And then the answer will be just $nk$ minus the sum of length of visited strings. The last thing to mention: instead of standard queue of integers we need to maintain the queue of strings and instead of array of visited vertices we have to maintain the set of visited strings. Don't forget to stop BFS when you obtain exactly $k$ strings. If the number of distinct subsequences is less than $k$ then the answer is -1.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tstring s;\n\tcin >> s;\n\t\n\tint ans = 0;\n\tqueue<string> q;\n\tset<string> st;\n\tq.push(s);\n\tst.insert(s);\n\twhile (!q.empty() && int(st.size()) < k) {\n\t\tstring v = q.front();\n\t\tq.pop();\n\t\tfor (int i = 0; i < int(v.size()); ++i) {\n\t\t\tstring nv = v;\n\t\t\tnv.erase(i, 1);\n\t\t\tif (!st.count(nv) && int(st.size()) + 1 <= k) {\n\t\t\t\tq.push(nv);\n\t\t\t\tst.insert(nv);\n\t\t\t\tans += n - nv.size();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (int(st.size()) < k) cout << -1 << endl;\n\telse cout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1183",
    "index": "F",
    "title": "Topforces Strikes Back",
    "statement": "One important contest will take place on the most famous programming platform (Topforces) very soon!\n\nThe authors have a pool of $n$ problems and should choose \\textbf{at most three} of them into this contest. The prettiness of the $i$-th problem is $a_i$. The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be \\textbf{maximum possible}).\n\nBut there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are $x, y, z$, then $x$ should be divisible by neither $y$, nor $z$, $y$ should be divisible by neither $x$, nor $z$ and $z$ should be divisible by neither $x$, nor $y$. If the prettinesses of chosen problems are $x$ and $y$ then neither $x$ should be divisible by $y$ nor $y$ should be divisible by $x$. Any contest composed from one problem is considered good.\n\nYour task is to find out the maximum possible total prettiness of the contest composed of \\textbf{at most three} problems from the given pool.\n\nYou have to answer $q$ independent queries.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "I know about some solutions that are trying to iterate over almost all possible triples, but I have a better and more interesting one. Possibly, it was already mentioned in comments, but I need to explain it. Let's solve the problem greedily. Let's sort the initial array. The first number we would like to choose is the maximum element. Then we need to pop out some maximum elements that are divisors of the maximum. Then there are two cases: the array becomes empty, or we have some maximum number that does not divide the chosen number. Let's take it and repeat the same procedure again, but now we have to find the number that does not divide neither the first taken number nor the second taken number. So we have at most three numbers after this procedure. Let's update the answer with their sum. This solution is almost correct. Almost! What have we forgotten? Let's imagine that the maximum element is divisible by $2$, $3$ and $5$ and there are three following numbers in the array: maximum divided by $2$, by $3$ and by $5$. Then their sum is greater than the maximum (and may be greater than the answer we have!) because $\\frac{1}{2} + \\frac{1}{3} + \\frac{1}{5} > 1$. So if these conditions are satisfied, let's update the answer with the sum of these three numbers. It can be shown that this is the only possible triple that can break our solution. The triple $2, 3, 4$ does not match because the maximum divided by $4$ divides the maximum divided by $2$. The triple $2, 3, 6$ is bad for the same reason. And the triple $2, 3, 7$ has sum less than the maximum element.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tset<int> st;\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\tst.insert(x);\n\t\t}\n\t\t\n\t\tint ans = 0;\n\t\tint mx = *st.rbegin();\n\t\tif (mx % 2 == 0 && mx % 3 == 0 && mx % 5 == 0) {\n\t\t\tif (st.count(mx / 2) && st.count(mx / 3) && st.count(mx / 5)) {\n\t\t\t\tans = max(ans, mx / 2 + mx / 3 + mx / 5);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvector<int> res;\n\t\twhile (!st.empty() && int(res.size()) < 3) {\n\t\t\tint x = *st.rbegin();\n\t\t\tst.erase(prev(st.end()));\n\t\t\tbool ok = true;\n\t\t\tfor (auto it : res) ok &= (it % x != 0);\n\t\t\tif (ok) res.push_back(x);\n\t\t}\n\t\t\n\t\tans = max(ans, accumulate(res.begin(), res.end(), 0));\n\t\t\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1183",
    "index": "G",
    "title": "Candy Box (hard version)",
    "statement": "\\textbf{This problem is a version of problem D from the same contest with some additional constraints and tasks.}\n\nThere are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \\le a_i \\le n$).\n\nYou have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $1$ and two candies of type $2$ is bad).\n\n\\textbf{It is possible that multiple types of candies are completely absent from the gift}. It is also possible that \\textbf{not all candies} of some types will be taken to a gift.\n\nYou really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $f_i$ is given, which is equal to $0$ if you really want to keep $i$-th candy for yourself, or $1$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $f_i$.\n\nYou want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $f_i = 1$ in your gift.\n\nYou have to answer $q$ independent queries.\n\n\\textbf{If you are Python programmer, consider using PyPy instead of Python when you submit your code.}",
    "tutorial": "First of all, to maximize the number of candies in the gift, we can use the following greedy algorithm: let's iterate on the number of candies of some type we take from $n$ to $1$ backwards. For fixed $i$, let's try to find any suitable type of candies. A type is suitable if there are at least $i$ candies of this type in the box. If there exists at least one such type that wasn't used previously, let's pick any such type and take exactly $i$ candies of this type (and decrease $i$). It does not matter which type we pick if we only want to maximize the number of candies we take. Okay, let's now modify this solution to maximize the number of candies having $f_i = 1$. We initially could pick any type that has at least $i$ candies, but now we should choose a type depending on the number of candies with $f_i = 1$ in this type. For example, if we have two types having $x_1$ and $x_2$ candies with $f_i = 1$ respectively, and we want to pick $i_1$ candies from one type and $i_2$ candies from another type, and $x_1 > x_2$ and $i_1 > i_2$, it's better to pick $i_1$ candies of the first type and $i_2$ candies of the second type. In this case we have $min(x_1, i_1) + min(x_2, i_2)$ candies with $f_i = 1$, in the other case it's $min(x_2, i_1) + min(x_1, i_2)$. And if $x_1 > x_2$ and $i_1 > i_2$, then $min(x_1, i_1) + min(x_2, i_2) \\ge min(x_2, i_1) + min(x_1, i_2)$. So, when we want to pick a type of candies such that we will take exactly $i$ candies of this type, it's optimal to choose a type that wasn't used yet, contains at least $i$ candies, and has maximum possible number of candies with $f_i = 1$. This best type can be maintained with a multiset or a set of pairs.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> cnt(n);\n\tvector<int> cnt_good(n);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint a, f;\n\t\tscanf(\"%d %d\", &a, &f);\n\t\t--a;\n\t\tcnt[a]++;\n\t\tif(f) cnt_good[a]++;\n\t}\n\tvector<vector<int> > types(n + 1);\n\tfor(int i = 0; i < n; i++)\n\t\ttypes[cnt[i]].push_back(cnt_good[i]);\n\tint ans1 = 0;\n\tint ans2 = 0;\n\tmultiset<int> cur;\n\tfor(int i = n; i > 0; i--)\n\t{\n\t\tfor(auto x : types[i]) cur.insert(x);\n\t\tif(!cur.empty())\n\t\t{\n\t\t\tint z = *cur.rbegin();\n\t\t\tans1 += i;\n\t\t\tans2 += min(i, z);\n\t\t\tcur.erase(cur.find(z));\n\t\t}\n\t}\n\tprintf(\"%d %d\\n\", ans1, ans2);\n}\n\nint main()\n{\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int i = 0; i < t; i++)\n\t\tsolve();\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1183",
    "index": "H",
    "title": "Subsequences (hard version)",
    "statement": "\\textbf{The only difference between the easy and the hard versions is constraints}.\n\nA subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string \"abaca\" the following strings are subsequences: \"abaca\", \"aba\", \"aaa\", \"a\" and \"\" (empty string). But the following strings are not subsequences: \"aabaca\", \"cb\" and \"bcaa\".\n\nYou are given a string $s$ consisting of $n$ lowercase Latin letters.\n\nIn one move you can take \\textbf{any} subsequence $t$ of the given string and add it to the set $S$. The set $S$ can't contain duplicates. This move costs $n - |t|$, where $|t|$ is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).\n\nYour task is to find out the minimum possible total cost to obtain a set $S$ of size $k$ or report that it is impossible to do so.",
    "tutorial": "Firstly, let's calculate the following auxiliary matrix: $lst_{i, j}$ means the maximum position $pos$ that is less than or equal to $i$, and the character $s_{pos} = j$ (in order from $0$ to $25$, 'a' = $0$, 'b' = $1$, and so on). It can be calculated naively or with some easy dynamic programming (initially all $lst_{i, j}$ are $-1$ and then for each $i$ from $1$ to $n-1$ all values $lst_{i, j}$ are equal to $lst_{i - 1, j}$ except $lst_{i, s_i}$ which is $i$). After calculating this matrix we can solve the problem by the following dynamic programming: let $dp_{i, j}$ be the number of subsequences of length $j$ that ends exactly in the position $i$. Initially all values are zeros except $dp_{i, 1} = 1$ for each $i$ from $0$ to $n-1$. How do we perform transitionss? Let's iterate over all lengths $j$ from $2$ to $n$, then let's iterate over all positions $i$ from $1$ to $n-1$ in a nested loop, and for the current state $dp_{i, j}$ we can calculate it as $\\sum\\limits_{c=0}^{25}dp_{lst_{i - 1, c}},{j - 1}$. If $lst_{i - 1, c} = -1$ then we don't need to add this state of the dynamic programming to the current state. Don't forget to take the minimum with $10^{12}$ after each transition! This transition means that we take all subsequences that end with each possible character of the alphabet and try to add the current character to each of them. You can understand that there are no overlapping subsequences in this dynamic programming. After that let's iterate over all possible lengths $j$ from $n$ to $1$ and calculate the number of subsequences of the current length $j$. It equals to $cnt = \\sum\\limits_{c=0}^{25}dp_{lst_{n - 1, c}, j}$. The same, if $lst_{n - 1, c} = -1$ then we don't need to add this state of the dynamic programming to $cnt$. Don't forget to take the minimum with $10^{12}$! If $cnt \\ge k$ then let's add $k(n - len)$ to the answer and break the cycle. Otherwise let's add $cnt(n - len)$ to the answer and decrease $k$ by $cnt$. If after all iterations $k$ is greater than zero then let's try to add the empty string to the answer (we didn't take it into account earlier). Increase the answer by $n$ and decrease $k$ by one. If after this $k$ is still greater than zero then the answer is -1, otherwise the answer is the calculated sum. Time complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long INF64 = 1e12;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tlong long k;\n\tcin >> n >> k;\n\t--k; // the whole string costs nothing\n\tstring s;\n\tcin >> s;\n\t\n\tvector<vector<int>> lst(n, vector<int>(26, -1));\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < 26; ++j) {\n\t\t\tif (i > 0) lst[i][j] = lst[i - 1][j];\n\t\t}\n\t\tlst[i][s[i] - 'a'] = i;\n\t}\n\t\n\tvector<vector<long long>> dp(n + 1, vector<long long>(n + 1));\n\tfor (int i = 0; i < n; ++i) {\n\t\tdp[i][1] = 1;\n\t}\n\t\n\tfor (int len = 2; len < n; ++len) {\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tfor (int j = 0; j < 26; ++j) {\n\t\t\t\tif (lst[i - 1][j] != -1) {\n\t\t\t\t\tdp[i][len] = min(INF64, dp[i][len] + dp[lst[i - 1][j]][len - 1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tlong long ans = 0;\n\tfor (int len = n - 1; len >= 1; --len) {\n\t\tlong long cnt = 0;\n\t\tfor (int j = 0; j < 26; ++j) {\n\t\t\tif (lst[n - 1][j] != -1) {\n\t\t\t\tcnt += dp[lst[n - 1][j]][len];\n\t\t\t}\n\t\t}\n\t\tif (cnt >= k) {\n\t\t\tans += k * (n - len);\n\t\t\tk = 0;\n\t\t\tbreak;\n\t\t} else {\n\t\t\tans += cnt * (n - len);\n\t\t\tk -= cnt;\n\t\t}\n\t}\n\t\n\tif (k == 1) {\n\t\tans += n;\n\t\t--k;\n\t}\n\t\n\tif (k > 0) cout << -1 << endl;\n\telse cout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1185",
    "index": "A",
    "title": "Ropewalkers",
    "statement": "Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.\n\nThe rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions $a$, $b$ and $c$ respectively. At the end of the performance, the distance between each pair of ropewalkers was \\textbf{at least} $d$.\n\nRopewalkers can walk on the rope. In one second, only one ropewalker can change his position. Every ropewalker can change his position exactly by $1$ (i. e. shift by $1$ to the left or right direction on the rope). Agafon, Boniface and Konrad \\textbf{can not} move at the same time (\\textbf{Only one of them can move at each moment}). Ropewalkers can be at the same positions at the same time and can \"walk past each other\".\n\nYou should find the minimum duration (in seconds) of the performance. In other words, find the minimum number of seconds needed so that the distance between each pair of ropewalkers can be greater or equal to $d$.\n\nRopewalkers can walk to negative coordinates, due to the rope is infinite to both sides.",
    "tutorial": "Let's solve the problem when $a \\le b \\le c$. If it's not true, let's sort $a$, $b$ and $c$. If we move $b$ to any direction, the distance between $b$ and one of $a$ or $c$ decreases, so we get to a worse situation than it was. Thus, we can assume that the position $b$ does not change. Then we should make following conditions come true: $|a - b| \\ge d$ and $|b - c| \\ge d$. If $a - b \\ge d$ it can be achieved in 0 seconds, else in $d - (a - b)$ seconds. So, the first condition can be achieved in $max(0, d - (a - b))$. If $b - c \\ge d$ it can be achieved in 0 seconds, else in $d - (b - c)$ seconds. So, the second condition can be achieved in $max(0, d - (b - c))$. So, the answer for the problem is $max(0, d - (a - b)) + max(0, d - (b - c))$.",
    "code": "def solve(a, b, c, d):\n    return max(0, d - (b - a)) + max(0, d - (c - b))\n\ndef main():\n    a, b, c, d = map(int, input().split())\n    a, b, c = sorted((a, b, c))\n    print(solve(a, b, c, d))\n\nmain()",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1185",
    "index": "B",
    "title": "Email from Polycarp",
    "statement": "Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).\n\nFor example, as a result of typing the word \"hello\", the following words \\textbf{could} be printed: \"hello\", \"hhhhello\", \"hheeeellllooo\", but the following \\textbf{could not} be printed: \"hell\", \"helo\", \"hhllllooo\".\n\nNote, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.\n\nFor each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.\n\nYou are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.",
    "tutorial": "It should be noted that if Polycarp press a key once, it's possible to appear one, two or more letters. So, if Polycarp press a key $t$ times, letter will appear at least $t$ times. Also, pressing a particular key not always prints same number of letters. So the possible correct solution is followed: For both words $s$ and $t$ we should group consecutive identical letters with counting of the each group size. For ex, there 4 groups in the word \"aaabbcaa\": $[aaa, bb, c, aa]$. For performance you should keep every group as the letter (char) and the group size (int). Then, if the number of groups in word $s$ isn't equal to the number of groups in word $t$, then $t$ can not be printed during typing of $s$. Let's go through array with such groups and compare the $i$-th in the word $s$ with the $i$-th in the word $t$. If letters in groups are different, answer is NO. If the group in $s$ are greater than group in $t$, answer is NO. Answer is YES in all other cases. Every string can be splitted into such groups by one loop. So, the total time complexity is $\\sum|s| + \\sum|t|$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nvector<pair<char,int>> split(string s) {\n    char c = s[0];\n    int cnt = 1;\n    vector<pair<char,int>> result;\n    auto ss = s.c_str();\n    for (int i = 1; i <= int(s.length()); i++) {\n        if (ss[i] != c) {\n            result.push_back({c, cnt});\n            c = s[i];\n            cnt = 1;\n        } else\n            cnt++;\n    }\n    return result;\n}\n\nint main() {\n    int n;\n    cin >> n;\n    forn(tt, n) {\n        string s, t;\n        cin >> s >> t;\n        auto sa(split(s)), ta(split(t));\n        bool ok = sa.size() == ta.size();\n        if (ok)\n            forn(i, sa.size())\n                if (sa[i].first != ta[i].first || sa[i].second > ta[i].second)\n                    ok = false;\n        cout << (ok ? \"YES\" : \"NO\") << endl;\n    }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1185",
    "index": "C1",
    "title": "Exam in BerSU (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints.}\n\nA session has begun at Beland State University. Many students are taking exams.\n\nPolygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are following:\n\n- The $i$-th student randomly chooses a ticket.\n- if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.\n- if the student finds the ticket easy, he spends exactly $t_i$ minutes to pass the exam. After it, he immediately gets a mark and goes home.\n\nStudents take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.\n\nThe duration of the whole exam for all students is $M$ minutes ($\\max t_i \\le M$), so students at the end of the list have a greater possibility to run out of time to pass the exam.\n\nFor each student $i$, you should count the minimum possible number of students who need to fail the exam so the $i$-th student has enough time to \\textbf{pass} the exam.\n\nFor each student $i$, find the answer independently. That is, if when finding the answer for the student $i_1$ some student $j$ should leave, then while finding the answer for $i_2$ ($i_2>i_1$) the student $j$ student does not have to go home.",
    "tutorial": "First of all we should precalculate sum $s_i$ of all students' durations for each student. For $i$-th student $s_i = s_{i - 1} + t_i$. Then for each student we can sort all durations $t_i$ of passing exam of students, who are before the current student. So, let's walk by these durations from larger to smaller and calculate prefix sum of them $D_i$. We will iterate them until total duration is enough for the current student to pass the exam too, i.e. until $s_i + t_i - D_i \\le M$. For $i$-th student the answer is number of iterated durations. Sorting works in $\\mathcal{O}(n \\log n)$, walking by array works in $\\mathcal{O}(n)$. Total complexity for all students is $\\mathcal{O}(n^2 \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int T = 100;\n\nint main() {\n\tint n, m;\n\tcin >> n >> m;\n\t\n\tint sum = 0;\n\tvector<int> t(n), count(T + 1, 0);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> t[i];\n\t}\n\t\n\tfor (int i = 0; i < n; i++) {\n\t\tint d = sum + t[i] - m, k = 0;\n\t\tif (d > 0) {\n\t\t    for (int j = T; j > 0; j--) {\n\t\t\t\tint x = j * count[j];\n\t\t\t\tif (d <= x) {\n\t\t\t\t\tk += (d + j - 1) / j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tk += count[j];\n\t\t\t\td -= x;\n\t\t\t}\n\t\t}\n\t\tsum += t[i];\n\t\tcount[t[i]]++;\n\t\tcout << k << \" \";\n\t}\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1185",
    "index": "C2",
    "title": "Exam in BerSU (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints.}\n\n\\textbf{If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.}\n\nA session has begun at Beland State University. Many students are taking exams.\n\nPolygraph Poligrafovich is going to examine a group of $n$ students. Students will take the exam one-by-one in order from $1$-th to $n$-th. Rules of the exam are following:\n\n- The $i$-th student randomly chooses a ticket.\n- if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.\n- if the student finds the ticket easy, he spends exactly $t_i$ minutes to pass the exam. After it, he immediately gets a mark and goes home.\n\nStudents take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.\n\nThe duration of the whole exam for all students is $M$ minutes ($\\max t_i \\le M$), so students at the end of the list have a greater possibility to run out of time to pass the exam.\n\nFor each student $i$, you should count the minimum possible number of students who need to fail the exam so the $i$-th student has enough time to \\textbf{pass} the exam.\n\nFor each student $i$, find the answer independently. That is, if when finding the answer for the student $i_1$ some student $j$ should leave, then while finding the answer for $i_2$ ($i_2>i_1$) the student $j$ student does not have to go home.",
    "tutorial": "Note that $1 \\le t_i \\le 100$ for each $i$-th student. It brings us to the idea that for each student we only need to know number of students, who are before current student and whose duration of passing the exam is exactly $k$, for all $k$ from $1$ to $100$. Let's use $count_k$ as array of number student, whose duration of passing the exam is exactly $k$. Initially $count_k = 0$ for all $k$ from $1$ to $100$. For each student we can precalculate sum $s_i$ of all durations of students before current. Now we can iterate all students from $1$-st to $n$-th. Let's walk by $k$ from $100$ to $1$. Initially the answer $a_i$ for $i$-th student is $0$. If $s_i + t_i - count_k \\cdot k > M$, let's $s_i = s_i - count_k \\cdot k$ and $a_i = a_i + count_k$. If $s_i + t_i - count_k \\cdot k \\le M$, it means that $a_i + count_k$ is the answer, but it might be not minimal answer. So, the answer is $a_i + \\lceil \\frac{s_i}{k} \\rceil$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int T = 100;\n\nint main() {\n\tint n, m;\n\tcin >> n >> m;\n\t\n\tint sum = 0;\n\tvector<int> t(n), count(T + 1, 0);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> t[i];\n\t}\n\t\n\tfor (int i = 0; i < n; i++) {\n\t\tint d = sum + t[i] - m, k = 0;\n\t\tif (d > 0) {\n\t\t    for (int j = T; j > 0; j--) {\n\t\t\t\tint x = j * count[j];\n\t\t\t\tif (d <= x) {\n\t\t\t\t\tk += (d + j - 1) / j;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tk += count[j];\n\t\t\t\td -= x;\n\t\t\t}\n\t\t}\n\t\tsum += t[i];\n\t\tcount[t[i]]++;\n\t\tcout << k << \" \";\n\t}\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1185",
    "index": "D",
    "title": "Extra Element",
    "statement": "A sequence $a_1, a_2, \\dots, a_k$ is called an arithmetic progression if for each $i$ from $1$ to $k$ elements satisfy the condition $a_i = a_1 + c \\cdot (i - 1)$ for some fixed $c$.\n\nFor example, these five sequences are arithmetic progressions: $[5, 7, 9, 11]$, $[101]$, $[101, 100, 99]$, $[13, 97]$ and $[5, 5, 5, 5, 5]$. And these four sequences aren't arithmetic progressions: $[3, 1, 2]$, $[1, 2, 4, 8]$, $[1, -1, 1, -1]$ and $[1, 2, 3, 3, 3]$.\n\nYou are given a sequence of integers $b_1, b_2, \\dots, b_n$. Find any index $j$ ($1 \\le j \\le n$), such that if you delete $b_j$ from the sequence, you can reorder the remaining $n-1$ elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.",
    "tutorial": "First of all, we should sort all elements (from smaller to larger, for example, or vice versa). But in the answer is index of element in original sequence, so let's keep the array $c$ of pairs $\\{b_i, i\\}$, sorted by $b_i$. Now we need to check some simple cases, for example, let's check the $1$-st and the $2$-nd elements whether they are the answers. We'll create the copy of original sequence, but without $1$-st element. Then we will check that all neighboring elements $c_i.first$ and $c_{i + 1}.first$ have the same difference. If it is so, $c_1.second$ is the answer. For the $2$-nd element similarly. Okay, now we have the sequence, where $1$-st and $2$-nd elements aren't the answers. Let's fix difference between them $d$ and check that all neighboring elements $c_i.first$ and $c_{i + 1}.first$ have the same difference. If we meet the pair, where the difference doesn't equal $d$, we will check the difference between $c_{i}.first$ and $c_{i + 2}.first$. If it equals $d$, so $c_{i + 1}.second$ may be the answer, otherwise there is no answer (output $-1$). If we will find one else pair, where the difference doesn't equals $d$, there is no answer too. If all pairs have the difference that equals $d$, it means that it's initially arithmetic progression. So we can remove first or last element and get arithmetic progression again. In this case let's output $1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\t\n\tvector<pair<int, int>> b(n);\n\tfor (int i = 0; i < n; i++) {\n\t    int x;\n\t    cin >> x;\n\t    b[i] = {x, i};\n\t}\n\tsort(b.begin(), b.end());\n\t\n\tvector<int> d(n - 1);\n\tfor (int i = 1; i < n; i++) {\n\t\td[i - 1] = b[i].first - b[i - 1].first;\n\t}\n\t\n\tbool f = true;\n\tfor (int i = 2; i < n - 1; i++) {\n\t\tf &= d[i] == d[1];\n\t}\n\tif (f) {\n\t\tcout << b[0].second + 1;\n\t\treturn 0;\n\t}\n\t\n\tf = true;\n\tfor (int i = 2; i < n - 1; i++) {\n\t\tf &= d[i] == b[2].first - b[0].first;\n\t}\n\tif (f) {\n\t\tcout << b[1].second + 1;\n\t\treturn 0;\n\t}\n\t\n\tint answer;\n\tf = false;\n\tfor (int i = 1; i < n - 1; i++) {\n\t\tif (d[i] == d[0]) continue;\n\t\tif (f) {\n\t\t\tcout << -1;\n\t\t\treturn 0;\n\t\t} else {\n\t\t\tif (i == n - 2) {\n\t\t\t\tcout << b[n - 1].second + 1;\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\tif (b[i + 2].first - b[i].first == d[0]) {\n\t\t\t\t\tanswer = b[i + 1].second;\n\t\t\t\t\tf = true;\n\t\t\t\t\ti++;\n\t\t\t\t} else {\n\t\t\t\t\tcout << -1;\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (f) {\n        cout << answer + 1;\n\t} else {\n\t    cout << b[n - 1].second + 1;\n\t}\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1185",
    "index": "E",
    "title": "Polycarp and Snakes",
    "statement": "After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $n \\times m$ (where $n$ is the number of rows, $m$ is the number of columns) and starts to draw snakes in cells.\n\nPolycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $26$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $26$.\n\nSince by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $1$, i.e. each snake has size either $1 \\times l$ or $l \\times 1$, where $l$ is snake's length. Note that snakes can't bend.\n\nWhen Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake \"over the top\" and overwrites the previous value in the cell.\n\nRecently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.",
    "tutorial": "Remember, that Polycarp draws snakes in alphabetic order. Firstly we should find the most top left and the most bottom right occurrences of each letter. Secondly we should walk by these letters from 'z' to 'a'. We will skip first not found letters. If for any letter both length and width are larger than $1$, there is no way to draw snakes. Otherwise we should check that all elements in the line equals current letter or '*'. If it's so, let's overdraw this line with '*' and move on to the next letter. If it's not so, there is no way to draw snakes. If there is the answer, for each snake we can output coordinates of the most top left and the most bottom right occurrences of relevant letter. If there is no occurrences for some letter, we can suppose that the next letter fully overdrew the current letter. Totally we can solve the task, walking by field no more than $1 + 26 = 27$ ones.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\t\nint min(int a, int b) {\n\treturn (a < b) ? a : b;\n}\nint max(int a, int b) {\n\treturn (a > b) ? a : b;\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\t\n\tvector<string> lines(2000, \"\");\n\tvector<int> vertical_min(26, 2001), vertical_max(26, -1);\n\tvector<int> horizontal_min(26, 2001), horizontal_max(26, -1);\n\t\t\n\tfor (int k = 0; k < t; k++) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> lines[i];\n\t\t}\n\t\t\n\t\tfor (int b = 0; b < 26; b++) {\n\t\t\tvertical_min[b] = 2001;\n\t\t\thorizontal_min[b] = 2001;\n\t\t\tvertical_max[b] = -1;\n\t\t\thorizontal_max[b] = -1;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tif (lines[i][j] != '.') {\n\t\t\t\t\tint b = (int) (lines[i][j] - 'a');\n\t\t\t\t\tvertical_min[b] = min(vertical_min[b], i);\n\t\t\t\t\tvertical_max[b] = max(vertical_max[b], i);\n\t\t\t\t\thorizontal_min[b] = min(horizontal_min[b], j);\n\t\t\t\t\thorizontal_max[b] = max(horizontal_max[b], j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tbool f = true, q = false;\n\t\tint count = 26;\n\t\tfor (int b = 25; b >= 0; b--) {\n\t\t\tif (vertical_max[b] == -1) {\n\t\t\t\tif (!q) {\n\t\t\t\t\tcount--;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tvertical_min[b] = vertical_min[b + 1];\n\t\t\t\t\tvertical_max[b] = vertical_max[b + 1];\n\t\t\t\t\thorizontal_min[b] = horizontal_min[b + 1];\n\t\t\t\t\thorizontal_max[b] = horizontal_max[b + 1];\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tq = true;\n\t\t\tif (vertical_max[b] == vertical_min[b]) {\n\t\t\t\tfor (int j = horizontal_min[b]; j <= horizontal_max[b]; j++) {\n\t\t\t\t\tif (lines[vertical_max[b]][j] == 'a' + b || (q && lines[vertical_max[b]][j] == '*')) {\n\t\t\t\t\t\tlines[vertical_max[b]][j] = '*';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (horizontal_max[b] == horizontal_min[b]) {\n\t\t\t\tfor (int i = vertical_min[b]; i <= vertical_max[b]; i++) {\n\t\t\t\t\tif (lines[i][horizontal_max[b]] == 'a' + b || (q && lines[i][horizontal_max[b]] == '*')) {\n\t\t\t\t\t\tlines[i][horizontal_max[b]] = '*';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tf = false;\n\t\t\t}\n\t\t\tif (!f) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (f) {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tcout << count << endl;\n\t\t\tfor (int i = 0; i < count; i++) {\n\t\t\t\tcout << vertical_min[i] + 1 << \" \" << horizontal_min[i] + 1 << \" \" << vertical_max[i] + 1 << \" \" << horizontal_max[i] + 1 << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tcout << \"NO\" << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1185",
    "index": "F",
    "title": "Two Pizzas",
    "statement": "A company of $n$ friends wants to order exactly two pizzas. It is known that in total there are $9$ pizza ingredients in nature, which are denoted by integers from $1$ to $9$.\n\nEach of the $n$ friends has one or more favorite ingredients: the $i$-th of friends has the number of favorite ingredients equal to $f_i$ ($1 \\le f_i \\le 9$) and your favorite ingredients form the sequence $b_{i1}, b_{i2}, \\dots, b_{if_i}$ ($1 \\le b_{it} \\le 9$).\n\nThe website of CodePizza restaurant has exactly $m$ ($m \\ge 2$) pizzas. Each pizza is characterized by a set of $r_j$ ingredients $a_{j1}, a_{j2}, \\dots, a_{jr_j}$ ($1 \\le r_j \\le 9$, $1 \\le a_{jt} \\le 9$) , which are included in it, and its price is $c_j$.\n\nHelp your friends choose exactly two pizzas in such a way as to please the maximum number of people in the company. It is known that a person is pleased with the choice if \\textbf{each} of his/her favorite ingredients is in at least one ordered pizza. If there are several ways to choose two pizzas so as to please the maximum number of friends, then choose the one that minimizes the total price of two pizzas.",
    "tutorial": "The first idea that could help to solve this problem is that the number of ingredients is small ($1 \\le b_{it}, a_{jt} \\le 9$). It means that we can keep information about favorite ingredients for each person in a bitmask. THe same situation is for pizzas' ingredients. Let's keep two pizzas with the smallest cost for each ingredients' mask. This information could be calculated during the reading pizzas' mask. Then, we should go through all possible masks, that could be reached by two different pizzas. For each such mask we should keep two pizzas with the smallest total cost, which gives us that mask (i. e. their bitwise-or is equal to our current mask). After such calculations, let's go through all possible summary masks and count the number of people, who would be satisfied by this mask. It could be done with a submasks-bruteforce in $3^9$. After this, we will have an optimal answer. So, time complexity for this solution is $\\mathcal{O}(n + m + 2^{2f} + 3^f)$, where $f \\le 9$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define pb push_back\n#define mp make_pair\n#define sqr(a) ((a) * (a))\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)\n\ntemplate<class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {\n\treturn out <<  \"(\" << a.x << \", \" << a.y << \")\";\n}\n\ntemplate<class A> ostream& operator << (ostream& out, const vector<A> &a) {\n\tout << \"[\";\n\tfor (auto it = a.begin(); it != a.end(); ++it) {\n\t\tif (it != a.begin())\n\t\t\tout << \", \";\n\t\tout << *it;\n\t}\n\treturn out << \"]\";\n}\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int INF = 1e9;\nconst li INF64 = 1e18;\nconst int MOD = 1e9 + 7;\nconst ld PI = acosl(-1.0);\nconst ld EPS = 1e-9;\n\nmt19937 rnd(time(NULL));\nmt19937_64 rnd64(time(NULL));\n\nconst int N = 100 * 1000 + 11;\nconst int MSK = 1 << 9;\n\nint n, m;\nint cnt[MSK];\nvector<pt> pz[N];\n\nbool read() {\n\tif (scanf(\"%d %d\", &n, &m) != 2)\n\t\treturn false;\n\tforn(i, n) {\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\tint msk = 0;\n\t\tforn(j, k) {\n\t\t\tint pos;\n\t\t\tscanf(\"%d\", &pos);\n\t\t\t--pos;\n\t\t\tmsk |= (1 << pos);\n\t\t}\n\t\t++cnt[msk];\n\t}\n\treturn true;\n}\n\nvoid solve() {\n\tforn(i, m) {\n\t\tint c;\n\t\tscanf(\"%d\", &c);\n\t\tint msk = 0;\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\tforn(j, k) {\n\t\t\tint pos;\n\t\t\tscanf(\"%d\", &pos);\n\t\t\t--pos;\n\t\t\tmsk |= (1 << pos);\n\t\t}\n\t\tpz[msk].pb(mp(c, i));\n\t\tsort(all(pz[msk]));\n\t\twhile (sz(pz[msk]) > 2) pz[msk].pop_back();\n\t}\n\tint ans = 0, cost = 2 * INF + 1;\n\tpt res = mp(-1, -1);\n\tforn(p1, MSK) forn(p2, MSK) {\n\t\tint curcost = 0;\n\t\tint pos1, pos2;\n\t\tif (p1 == p2) {\n\t\t\tif (sz(pz[p1]) < 2) continue;\n\t\t\tcurcost = pz[p1][0].x + pz[p1][1].x;\n\t\t\tpos1 = pz[p1][0].y;\n\t\t\tpos2 = pz[p1][1].y;\n\t\t} else {\n\t\t\tif (sz(pz[p1]) == 0 || sz(pz[p2]) == 0) continue;\n\t\t\tcurcost = pz[p1][0].x + pz[p2][0].x;\n\t\t\tpos1 = pz[p1][0].y;\n\t\t\tpos2 = pz[p2][0].y;\n\t\t}\n\t\tint curans = 0;\n\t\tint curmask = p1 | p2;\n\t\tforn(pp, MSK) {\n\t\t\tif ((curmask & pp) == pp) {\n\t\t\t\tcurans += cnt[pp];\n\t\t\t}\n\t\t}\n\t\tif (curans > ans || (curans == ans && curcost < cost)) {\n\t\t\tans = curans;\n\t\t\tcost = curcost;\n\t\t\tres = mp(pos1, pos2);\n\t\t}\n\t}\n\tcout << res.x + 1 << \" \" << res.y + 1 << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\t\n\tint tt = clock();\n#endif\n\n\tcout << fixed << setprecision(10);\n\tcerr << fixed << setprecision(10);\n\n#ifdef _DEBUG\n\twhile (read()) {\n#else\n\tif (read()) {\n#endif\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\t\n#endif\n\t}\n}",
    "tags": [
      "bitmasks",
      "brute force"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1185",
    "index": "G1",
    "title": "Playlist for Polycarp (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints.}\n\nPolycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly $T$ minutes.\n\nIn the player, Polycarp stores $n$ songs, each of which is characterized by two parameters: $t_i$ and $g_i$, where $t_i$ is the length of the song in minutes ($1 \\le t_i \\le 15$), $g_i$ is its genre ($1 \\le g_i \\le 3$).\n\nPolycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the $i$-th song, he would spend exactly $t_i$ minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.\n\nHelp Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly $T$, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.",
    "tutorial": "Consider all genres are from $0$ to $2$ instead of from $1$ to $3$. It will be easier to deal with 0-based indices. Let's use DP to calculate $d[mask][lst]$, where $mask$ ($0 \\le mask < 2^n$) is a binary mask of songs and $lst$ is a genre of the last song. The value $d[mask][lst]$ means the number of ways to order songs corresponding to the $mask$ in such a way that any neighboring (adjacent) songs have different genres and the genre of the last song is $lst$. DP to find the array $d$ is follows. It is easy to see that if $d[mask][lst]$ is calculated correctly, you iterate over all possible songs $j$ to append (such songs should be out of $mask$ and a genre different from $lst$). In this case, you should increase $d[mask + 2^j][genre(j)]$ by $d[mask][lst]$. Here is the sample code to calculate all cells of $d$: Here we use some fake genre $3$ to initialize DP (it can precede any real genre). To find the answer, just take into account only such masks that the correspondent total duration is exactly $M$. Just find the sum of all such $d[mask][lst]$ that the correspondent total duration is exactly $M$. You can do it at the same time with DP calculations. So the resulting code is: The total complexity is $O(n \\times 2^n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nconst int M = 1000000007;\nconst int N = 16;\n\nint d[1 << N][4];\n\nint main() {\n    int n, T;\n    cin >> n >> T;\n    vector<int> durs(n), types(n);\n    forn(i, n) {\n        cin >> durs[i] >> types[i];\n        types[i]--;\n    }\n\n    int result = 0;\n    d[0][3] = 1;\n    forn(mask, 1 << n)\n        forn(lst, 4) {\n            forn(j, n)\n                if (types[j] != lst && ((mask & (1 << j)) == 0))\n                    d[mask ^ (1 << j)][types[j]] = (d[mask ^ (1 << j)][types[j]] + d[mask][lst]) % M;\n            int sum = 0;\n            forn(i, n)\n                if (mask & (1 << i))\n                    sum += durs[i];\n            if (sum == T)\n                result = (result + d[mask][lst]) % M;\n        }\n\n    cout << result << endl;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1185",
    "index": "G2",
    "title": "Playlist for Polycarp (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints.}\n\nPolycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly $T$ minutes.\n\nIn the player, Polycarp stores $n$ songs, each of which is characterized by two parameters: $t_i$ and $g_i$, where $t_i$ is the length of the song in minutes ($1 \\le t_i \\le 50$), $g_i$ is its genre ($1 \\le g_i \\le 3$).\n\nPolycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the $i$-th song, he would spend exactly $t_i$ minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.\n\nHelp Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly $T$, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.",
    "tutorial": "Consider all genres are from $0$ to $2$ instead of from $1$ to $3$. It will be easier to deal with 0-based indices. Let's find two arrays: $a[i][s]$ = number of ways to choose a subset of exactly $i$ songs of the genre $0$ with total duration of exactly $s$; $bc[i][j][s]$ = number of ways to choose a subset of exactly $i$ songs of the genre $1$ and $j$ songs of the genre $2$ with total duration of exactly $s$. You can easily do it with DP. Here is the sample code to do it while reading the input: This part works in $O(n^3 \\cdot T)$ with a really small constant factor. Let's calculate the array $ways[i][j][k][lst]$ = number of ways to put $i$ zeroes, $j$ ones and $k$ twos in a row (its length is $i+j+k$) in such a way that no two equal values go consecutive and the row ends on $lst$. You can also use DP to find the values: This part works in $O(n^3)$ with a really small constant factor. And now if the final part of the solution. Let's iterate over all possible ways how songs with the genre $0$ can be in a playlist. It means that we try all possible counts of such songs ($c[0]$ in the code below) and their total duration ($durs0$ in the code below). Now we know the total time for genres $1$ and $2$, it equals to $T-durs0$. Let's iterate over all possible counts of songs with genre=$1$ and songs with genre=$2$ (say, $c[1]$ and $c[2]$). For fixed $c[0]$, $durs0$, $c[1]$ and $c[2]$ there are $x$ ways to choose songs, where $x=a[c[0]][durs0] \\cdot b[c[1]][c[2]][T-durs]$. To count all possible orders of songs, let's multiply $x$ on: $c[0]!$ - number of permutations of songs with genre=$0$; $c[1]!$ - number of permutations of songs with genre=$1$; $c[2]!$ - number of permutations of songs with genre=$2$; $ways[c[0]][c[1]][c[2]][0]+ways[c[0]][c[1]][c[2]][1]+ways[c[0]][c[1]][c[2]][2]$ - number ways to order them in the required way. After all the multiplications add the result to the answer. The following code illustrates this part of the solution: This part works in $O(n^3 \\cdot T)$ with a really small constant factor. So the total complexity is $O(n^3 \\cdot T)$ (the constant factor is significantly less than $1$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nconst int M = 1000000007;\nconst int N = 51;\nconst int S = 2501;\n\nvoid inc(int& a, int d) {\n    a += d;\n    if (a >= M)\n        a -= M;\n}\n\nint a[N][S];\nint bc[N][N][S];\nint ways[N][N][N][4];\n\nint main() {\n    int n, T;\n    cin >> n >> T;\n\n    vector<int> cnts(4);\n    vector<int> durs(4);\n\n    a[0][0] = bc[0][0][0] = 1;\n    forn(i, n) {\n        int dur, type;\n        cin >> dur >> type;\n        type--;\n        if (type == 0) {\n            for (int cnts0 = cnts[0]; cnts0 >= 0; cnts0--)\n                forn(durs0, durs[0] + 1)\n                    inc(a[cnts0 + 1][durs0 + dur], a[cnts0][durs0]);\n        } else {\n            for (int cnts1 = cnts[1]; cnts1 >= 0; cnts1--)\n                for (int cnts2 = cnts[2]; cnts2 >= 0; cnts2--)\n                    forn(durs12, durs[1] + durs[2] + 1)\n                        inc(bc[cnts1 + (type == 1)][cnts2 + (type == 2)][durs12 + dur],\n                            bc[cnts1][cnts2][durs12]);\n        }\n        cnts[type]++;\n        durs[type] += dur;\n    }\n\n    ways[0][0][0][3] = 1;\n    vector<int> c(3);\n    for (c[0] = 0; c[0] <= cnts[0]; c[0]++)\n        for (c[1] = 0; c[1] <= cnts[1]; c[1]++)\n            for (c[2] = 0; c[2] <= cnts[2]; c[2]++)\n                forn(lst, 4)\n                    if (ways[c[0]][c[1]][c[2]][lst] != 0) {\n                        forn(nxt, 3)\n                            if (nxt != lst && c[nxt] + 1 <= cnts[nxt]) {\n                                vector<int> cn(c);\n                                cn[nxt]++;\n                                inc(ways[cn[0]][cn[1]][cn[2]][nxt], ways[c[0]][c[1]][c[2]][lst]);\n                            }\n                    }\n\n    vector<int> f(N + 1, 1);\n    forn(i, N)\n        f[i + 1] = ((long long) f[i]) * (i + 1) % M;\n\n    int result = 0;\n    for (c[0] = 0; c[0] <= cnts[0]; c[0]++)\n        forn(durs0, durs[0] + 1)\n            if (T - durs0 >= 0)\n                for (c[1] = 0; c[1] <= cnts[1]; c[1]++)\n                    for (c[2] = 0; c[2] <= cnts[2]; c[2]++) {\n                        long long extra = (long long)(a[c[0]][durs0]) * bc[c[1]][c[2]][T - durs0] % M;\n                        forn(i, 3)\n                            extra = extra * f[c[i]] % M;\n                        forn(lst, 3)\n                            if (c[lst] > 0)\n                                inc(result, extra * ways[c[0]][c[1]][c[2]][lst] % M);\n                    }\n    \n    cout << result << endl;\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1186",
    "index": "A",
    "title": "Vus the Cossack and a Contest",
    "statement": "Vus the Cossack holds a programming competition, in which $n$ people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly $m$ pens and $k$ notebooks.\n\nDetermine whether the Cossack can reward \\textbf{all} participants, giving each of them at least one pen and at least one notebook.",
    "tutorial": "Since a pen and a notebook would be given to each participant, the answer is \"Yes\" if and only if $n \\le k$ and $n \\le m$. The answer is \"No\" otherwise.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1186",
    "index": "C",
    "title": "Vus the Cossack and Strings",
    "statement": "Vus the Cossack has two binary strings, that is, strings that consist only of \"0\" and \"1\". We call these strings $a$ and $b$. It is known that $|b| \\leq |a|$, that is, the length of $b$ is at most the length of $a$.\n\nThe Cossack considers every substring of length $|b|$ in string $a$. Let's call this substring $c$. He matches the corresponding characters in $b$ and $c$, after which he counts the number of positions where the two strings are different. We call this function $f(b, c)$.\n\nFor example, let $b = 00110$, and $c = 11000$. In these strings, the first, second, third and fourth positions are different.\n\nVus the Cossack counts the number of such substrings $c$ such that $f(b, c)$ is \\textbf{even}.\n\nFor example, let $a = 01100010$ and $b = 00110$. $a$ has four substrings of the length $|b|$: $01100$, $11000$, $10001$, $00010$.\n\n- $f(00110, 01100) = 2$;\n- $f(00110, 11000) = 4$;\n- $f(00110, 10001) = 4$;\n- $f(00110, 00010) = 1$.\n\nSince in three substrings, $f(b, c)$ is even, the answer is $3$.\n\nVus can not find the answer for big strings. That is why he is asking you to help him.",
    "tutorial": "Let's say that we want to know whether $f(c,d)$ is even for some strings $c$ and $d$. Let's define $cnt_c$ as number of ones in string $c$ and $cnt_d$ as number of ones in $d$. It's easy to see that $f(c,d)$ is even if and only if $cnt_b$ and $cnt_c$ have same parity. In other words if $cnt_c \\equiv cnt_d \\pmod 2$ then $f(c,d)$ is even. So, we can check if two strings have even number of distinct bits in $O(1)$ if know how many ones does each of them contain. Using that fact we can easily solve problem in $O(n)$ by using prefix sums.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1186",
    "index": "D",
    "title": "Vus the Cossack and Numbers",
    "statement": "Vus the Cossack has $n$ real numbers $a_i$. It is known that the sum of all numbers is equal to $0$. He wants to choose a sequence $b$ the size of which is $n$ such that the sum of all numbers is $0$ and each $b_i$ is either $\\lfloor a_i \\rfloor$ or $\\lceil a_i \\rceil$. In other words, $b_i$ equals $a_i$ rounded up or down. It is not necessary to round to the nearest integer.\n\nFor example, if $a = [4.58413, 1.22491, -2.10517, -3.70387]$, then $b$ can be equal, for example, to $[4, 2, -2, -4]$.\n\nNote that if $a_i$ is an integer, then there is no difference between $\\lfloor a_i \\rfloor$ and $\\lceil a_i \\rceil$, $b_i$ will always be equal to $a_i$.\n\nHelp Vus the Cossack find such sequence!",
    "tutorial": "At first step we should floor all the elements of the array. Then we iterate through the array and do the following: If sum of all the elements of array is equal to $0$, then the algorithm stops. If the decimal part of $a_i$ was not equal to $0$, then we assign $a_i := a_i+1$ Increase $i$ and repeat step 1. If you are interested why this works, here is the proof: Every element $a_i$ of the initial array can be expressed as $\\lfloor a_i \\rfloor + \\varepsilon_i$. It is obvious that $0 \\le \\varepsilon_i < 1$. Sum of all elements of array $a$ equals to $0$, it means that: $\\sum_{i=1}^{n} a_i = 0$ $\\sum_{i=1}^{n} (\\lfloor a_i \\rfloor + \\varepsilon_i) = 0$ $\\sum_{i=1}^{n} \\lfloor a_i \\rfloor + \\sum_{i=1}^{n}\\varepsilon_i = 0$ From equations above we can see that $\\sum_{i=1}^{n}\\varepsilon_i$ is an integer. Every $\\varepsilon_i < 1$, and that means $\\sum_{i=1}^{n}\\varepsilon_i$ is smaller than number of elements that were floored, so we will always be able to achieve zero sum of array $a$ by adding $1$ to some of the numbers that were initially floored.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1186",
    "index": "E",
    "title": "Vus the Cossack and a Field",
    "statement": "Vus the Cossack has a field with dimensions $n \\times m$, which consists of \"0\" and \"1\". He is building an infinite field from this field. He is doing this in this way:\n\n- He takes the current field and finds a new inverted field. In other words, the new field will contain \"1\" only there, where \"0\" was in the current field, and \"0\" there, where \"1\" was.\n- To the current field, he adds the inverted field to the right.\n- To the current field, he adds the inverted field to the bottom.\n- To the current field, he adds the current field to the bottom right.\n- He repeats it.\n\nFor example, if the initial field was:\n\n\\begin{center}\n$\\begin{matrix} 1 & 0 & \\\\ 1 & 1 & \\\\ \\end{matrix}$\n\\end{center}\n\nAfter the first iteration, the field will be like this:\n\n\\begin{center}\n$\\begin{matrix} 1 & 0 & 0 & 1 \\\\ 1 & 1 & 0 & 0 \\\\ 0 & 1 & 1 & 0 \\\\ 0 & 0 & 1 & 1 \\\\ \\end{matrix}$\n\\end{center}\n\nAfter the second iteration, the field will be like this:\n\n\\begin{center}\n$\\begin{matrix} 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\\\ 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\\\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\\\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\\\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\\\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\\\ 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\\\ 1 & 1 & 0& 0 & 0 & 0 & 1 & 1 \\\\ \\end{matrix}$\n\\end{center}\n\nAnd so on...\n\nLet's numerate lines from top to bottom from $1$ to infinity, and columns from left to right from $1$ to infinity. We call the submatrix $(x_1, y_1, x_2, y_2)$ all numbers that have coordinates $(x, y)$ such that $x_1 \\leq x \\leq x_2$ and $y_1 \\leq y \\leq y_2$.\n\nThe Cossack needs sometimes to find the sum of all the numbers in submatrices. Since he is pretty busy right now, he is asking you to find the answers!",
    "tutorial": "Let's define $f(x,y)$ a function that returns sum of all elements of submatrix $(1,1,x,y)$ (these $4$ numbers stand for $x_1, y_1, x_2, y_2$ respectively. If we can get value of this function in a fast way, then we can answer the queries quickly by using well known formula for sum on submatrix with cooridantes $x_1, y_1, x_2, y_2$: $sum = f(x_2,y_2) - f(x_2, y_1 - 1) - f(x_1 - 1, y_2) + f(x_1-1,y_1-1)$ If you want to prove the formula you should draw some examples and use the inclusion-exclusion principle. So we reduced our task to finding value of $f(x,y)$ for some arbitrary $x$ and $y$. At first, we should precalculate values of $f(x,y)$ for every $1 \\le x \\le n, 1 \\le y \\le m$. This can be easily done using dynamic programming. Let's forget about the sums for a while. Let's take a look on the fields. They can be both inverted or not inverted. Let's see how fields are distributed when generating an infinite field. At step $0$ we have one field, which is not inverted: $\\begin{matrix} 0 \\\\ \\end{matrix}$ At step $1$ we have four fields: $\\begin{matrix} 0 & 1 & \\\\ 1 & 0 & \\\\ \\end{matrix}$ And so on... After 3 steps we can see that you can split each horizontal or vertical line in pairs of inverted and not inverted fields like on the picture (vertical pairs are highlighted with yellow, horizontal pairs are highlighted with red): Sum of inverted and not inverted matrices of size $n \\times m$ is equal to $n \\cdot m$. Knowing these facts we can get $O(1)$ solution. Let's say that we want to know $f(x,y)$. Let's define $field_x$ and $field_y$ as coordinates of the field which cell $(x,y)$ belongs to. They can be easily found: $field_x = \\Big\\lfloor \\frac{x-1}{n} \\Big\\rfloor + 1$ $field_y = \\Big\\lfloor \\frac{y-1}{m} \\Big\\rfloor + 1$ The solution is splited into four parts: When both $field_x$ and $field_y$ are odd. When $field_x$ is odd, but $field_y$ is even. When $field_x$ is even, but $field_y$ is odd. When both $feild_x$ and $field+y$ are even. Solving each of the part is very similar, so I'll show you how to get value of $f(x,y)$ if both $field_x$ and $field_y$ are even (In this particular example $field_x = field_y = 4$). The big black dot shows us the position of $(x,y)$ (i.e. it shows that the cell with coordinates $(x, y)$ is located somewhere in the field with coordinates $(4,4)$). Using the fact I mentioned before we can get the value of pairs highlited as red: it is equal to $\\frac{((field_x - 1) \\cdot (field_y - 1) - 1) \\cdot n \\cdot m}{2}$ You can easily use the same fact in order to find the blue and yellow parts. In order to find the green parts we need to know whether each of the matrices, highlighted with green is inversed. How to know if the matrix with coordinates $(a,b)$ is inversed? Here is the trick (here $bitcnt$ is the function which returns number of bits in a number): If $bitcnt(a) + bitcnt(b)$ is an odd number, then the matrix is inversed.",
    "tags": [
      "divide and conquer",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1186",
    "index": "F",
    "title": "Vus the Cossack and a Graph",
    "statement": "Vus the Cossack has a simple graph with $n$ vertices and $m$ edges. Let $d_i$ be a degree of the $i$-th vertex. Recall that a degree of the $i$-th vertex is the number of conected edges to the $i$-th vertex.\n\nHe needs to remain not more than $\\lceil \\frac{n+m}{2} \\rceil$ edges. Let $f_i$ be the degree of the $i$-th vertex after removing. He needs to delete them in such way so that $\\lceil \\frac{d_i}{2} \\rceil \\leq f_i$ for each $i$. In other words, the degree of each vertex should not be reduced more than twice.\n\nHelp Vus to remain the needed edges!",
    "tutorial": "At first, let's create a fictive vertex (I'll call it $0$ vertex) and connect it with all of the vertices which have odd degree. Now all the vertices including $0$ vertex have even degree. The statement that $0$ vertex will have even degree too can be easily proven using the fact that the sum of degrees of all vertices equals to the number of edges multiplied by two. Let's denote the number of edges in the new graph as $k$. There were $m$ edges initially and we added at most $n$ new edges that connect fictive vertex with the real ones, so it always holds that $k \\le n + m$. Now, since all the vertices have even degree we can find Euler cycle of the new graph. Let's define $e_1, e_2, \\ldots, e_k$ as an array of all edges of the graph, ordered as in found Euler cycle. Now we can iterate over the array $e$ and delete all the edges on even positions. Due to this action now the new graph contains at most $\\lceil \\frac{k}{2} \\rceil \\le \\lceil \\frac{n+m}{2} \\rceil$ edges. That is exactly what we needed! It is interesting that in the new graph by deleting the edges the way mentioned above, the degree of each vertex would not be reduced more than twice. How to prove that? Well, you can think about it the following way: Let's say that the $e_i$ edge connects some vertices $a$ and $b$, that means that the $e_{i+1}$ edge connects vertex $b$ with some vertex $c$. If $i$ is odd, then we will delete only the $e_{i+1}$ edge, and if $i$ is even, then we will delete only the $e_i$ edge. And that happens for every vertex: if some edge $i$ enters it, then we will either delete $i$-th edge or $i+1$-th edge. So at most half of edges connected to a vertex will be deleted. If the length of Euler cycle is odd, then the last edge in it won't be deleted at all, so the algorithm will still work correctly. But that works for the new graph, which contains fictive vertex. But we need to solve the problem for the real graph. We can not simply delete all the edges from the real graph, that were on even positions in Euler cycle mentioned above. Here is the examle where it does not work (numbers near the edges show their positions in $e$ array, edges that would need to be removed are highlited with red): If we removed edge between vertices $2$ and $3$, degree of vertex $3$ would become $0$ which is definetely less then $\\lceil \\frac{d_3}{2} \\rceil = 1$. How do we avoid this bad situation? We can simply do the following: If $e_i$ is a fictive edge (i.e. it connects a real vertex with fictive one), then we do not really care about it, since we have to output answer about the real graph. If $e_i$ is a real edge (i.e it connects only real vertices) and we have to delete it, then we should look if $e_{i-1}$ or $e_{i+1}$ is a ficive edge. If either of them is one, then we can delete the fictive edge instead of the real edge $e_i$ (i.e. we simply do not delete $e_i$ from the graph), otherwise we delete the edge. (Note that if $e_i$ is the last edge in the Euler cycle, then instead of checking the $e_{k+1}$ edge which does not exist, you check if $e_1$ is fictive or not, similar goes for the case if $i = 1$). It is obvious that by doing so we do not change the number of edges deleted. It is also easy to see that the degree of a $i-th$ vertex in the new graph is at most $d_i + 1$. We still delete at most $\\lfloor \\frac{d_i + 1}{2} \\rfloor$ edges connected to it (or $\\lfloor \\frac{d_i}{2} \\rfloor$ if it initially had an even degree), but in case when it's degree was \"artificially\" increased, we prefer to delete the fictive edge, which we do not care about. The last question is: whether there we will a fictive edge which we will try to delete more than once? It is easy to prove that there is no such edge, you can try it by yourself. That's it, the problem is solved. Note that the graph is not necessarily connected, so you should find Euler cycle and do the following steps for each component independently.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1187",
    "index": "A",
    "title": "Stickers and Toys",
    "statement": "Your favorite shop sells $n$ Kinder Surprise chocolate eggs. You know that exactly $s$ stickers and exactly $t$ toys are placed in $n$ eggs in total.\n\nEach Kinder Surprise can be one of three types:\n\n- it can contain a single sticker and \\textbf{no toy};\n- it can contain a single toy and \\textbf{no sticker};\n- it can contain both a single sticker \\textbf{and} a single toy.\n\nBut you \\textbf{don't know} which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.\n\nWhat is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?\n\nNote that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.",
    "tutorial": "Note, that there are exactly $n - t$ eggs with only a sticker and, analogically, exactly $n - s$ with only a toy. So we need to buy more than $\\max(n - t, n - s)$ eggs, or exactly $\\max(n - t, n - s) + 1$.",
    "code": "fun main(args: Array<String>) {\n    val tc = readLine()!!.toInt()\n    for (i in 1..tc) {\n        val (n, s, t) = readLine()!!.split(' ').map { it.toInt() }\n        println(maxOf(n - s, n - t) + 1)\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1187",
    "index": "B",
    "title": "Letters Shop",
    "statement": "The letters shop showcase is a string $s$, consisting of $n$ lowercase Latin letters. As the name tells, letters are sold in the shop.\n\nLetters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $s$.\n\nThere are $m$ friends, the $i$-th of them is named $t_i$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.\n\n- For example, for $s$=\"arrayhead\" and $t_i$=\"arya\" $5$ letters have to be bought (\"{\\textbf{array}head}\").\n- For example, for $s$=\"arrayhead\" and $t_i$=\"harry\" $6$ letters have to be bought (\"{\\textbf{arrayh}ead}\").\n- For example, for $s$=\"arrayhead\" and $t_i$=\"ray\" $5$ letters have to be bought (\"{\\textbf{array}head}\").\n- For example, for $s$=\"arrayhead\" and $t_i$=\"r\" $2$ letters have to be bought (\"{\\textbf{ar}rayhead}\").\n- For example, for $s$=\"arrayhead\" and $t_i$=\"areahydra\" all $9$ letters have to be bought (\"{\\textbf{arrayhead}}\").\n\nIt is guaranteed that every friend can construct her/his name using the letters from the string $s$.\n\nNote that the values for friends are independent, friends are only estimating them but not actually buying the letters.",
    "tutorial": "Let's construct the answer letter by letter. How to get enough letters 'a' for the name? Surely, the taken letters will be the first 'a', the second 'a', up to $cnt_a$-th 'a' in string $s$, where $cnt_a$ is the amount of letters 'a' in the name. It's never profitable to skip the letter you need. Do the same for all letters presented in the name. The answer will the maximum position of these last taken letters. How to obtain the $cnt_a$-th letter fast? Well, just precalculate the list of positions for each letter and take the needed one from it. Overall complexity: $O(n + m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n, m;\nstring s, t;\nvector<int> pos[26];\n\nint main() {\n\tcin >> n >> s;\n\tforn(i, n)\n\t\tpos[s[i] - 'a'].push_back(i + 1);\n\t\n\tcin >> m;\n\tforn(i, m){\n\t\tcin >> t;\n\t\tvector<int> cnt(26);\n\t\tfor (auto &c : t)\n\t\t\t++cnt[c - 'a'];\n\t\tint ans = -1;\n\t\tforn(j, 26) if (cnt[j] > 0)\n\t\t\tans = max(ans, pos[j][cnt[j] - 1]);\n\t\tcout << ans << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "implementation",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1187",
    "index": "C",
    "title": "Vasya And Array",
    "statement": "Vasya has an array $a_1, a_2, \\dots, a_n$.\n\nYou don't know this array, but he told you $m$ facts about this array. The $i$-th fact is a triple of numbers $t_i$, $l_i$ and $r_i$ ($0 \\le t_i \\le 1, 1 \\le l_i < r_i \\le n$) and it means:\n\n- if $t_i=1$ then subbarray $a_{l_i}, a_{l_i + 1}, \\dots, a_{r_i}$ is sorted in non-decreasing order;\n- if $t_i=0$ then subbarray $a_{l_i}, a_{l_i + 1}, \\dots, a_{r_i}$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter.\n\nFor example if $a = [2, 1, 1, 3, 2]$ then he could give you three facts: $t_1=1, l_1=2, r_1=4$ (the subarray $[a_2, a_3, a_4] = [1, 1, 3]$ is sorted), $t_2=0, l_2=4, r_2=5$ (the subarray $[a_4, a_5] = [3, 2]$ is not sorted), and $t_3=0, l_3=3, r_3=5$ (the subarray $[a_3, a_5] = [1, 3, 2]$ is not sorted).\n\nYou don't know the array $a$. Find \\textbf{any} array which satisfies all the given facts.",
    "tutorial": "Let's consider array $b_1, b_2, \\dots , b_{n-1}$, such that $b_i = a_{i + 1} - a_i$. Then subarray $a_l, a_{l+1}, \\dots , a_r$ is sorted in non-decreasing order if and only if all elements $b_l, b_{l + 1} , \\dots , b_{r - 1}$ are greater or equal to zero. So if we have fact $t_i = 1, l_i, r_i$, then all elements $b_{l_i}, b_{l_i + 1}, \\dots , b_{r_i - 1}$ must be greater or equal to zero. Let's create the following array $b$: $b_i = 0$ if there is such a fact ${t_j, l_j, r_j}$ that $t_j = 1, l_j \\le i < r_j$, and $b_i = -1$ otherwise. After that we create the following array $a$: $a_1 = n$, and for all other indexes $a_i = a_{i - 1} + b_{i - 1}$. This array $a$ satisfies all facts ${t_i, l_i, r_i}$ such that $t_i = 1$. So all we have to do is check that all remaining facts are satisfied.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\n\nint n, m;\nint l[N], r[N], s[N];\nint d[N];\nint dx[N];\nint res[N];\nint nxt[N];\n\nint main() {\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 0; i < m; ++i){\n\t\tscanf(\"%d %d %d\", s + i, l + i, r + i);\n\t\t--l[i], --r[i];\n\t\tif(s[i] == 1)\n\t\t\t++d[l[i]], --d[r[i]];\n\t}\n\n\tmemset(dx, -1, sizeof dx);\n\tint sum = 0;\n\tfor(int i = 0; i < n - 1; ++i){\n\t\tsum += d[i];\n\t\tif(sum > 0)\t\n\t\t\tdx[i] = 0;\n\t}\t\t\n\n\tres[0] = n;\n\tfor(int i = 1; i < n; ++i)\n\t\tres[i] = res[i - 1] + dx[i - 1];\t\n\n\tnxt[n - 1] = n - 1;\n\tfor(int i = n - 2; i >= 0; --i){\n\t\tif(res[i] <= res[i + 1])\n\t\t\tnxt[i] = nxt[i + 1];\n\t\telse \n\t\t\tnxt[i] = i;\n\t}\t\t\t\n\n\tfor(int i = 0; i < m; ++i){\n\t\tif(s[i] != (nxt[l[i]] >= r[i])){\n\t\t\tputs(\"NO\");\n\t\t\treturn 0;\t\t\n\t\t}\n\t}\t\n\n\tputs(\"YES\");\n\tfor(int i = 0; i < n; ++i)\n\t\tprintf(\"%d \", res[i]);\n\tputs(\"\");\n\n\treturn 0;\n}                             \t\n\n\n",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1187",
    "index": "D",
    "title": "Subarray Sorting",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$ and an array $b_1, b_2, \\dots, b_n$.\n\nFor one operation you can sort in non-decreasing order any subarray $a[l \\dots r]$ of the array $a$.\n\nFor example, if $a = [4, 2, 2, 1, 3, 1]$ and you choose subbarray $a[2 \\dots 5]$, then the array turns into $[4, 1, 2, 2, 3, 1]$.\n\nYou are asked to determine whether it is possible to obtain the array $b$ by applying this operation any number of times (possibly zero) to the array $a$.",
    "tutorial": "Let's reformulate this problem in next form: we can sort only subarray of length 2 (swap two consecutive elements $i$ and $i+1$ if $a_i > a_{i + 1}$). It is simular tasks because we can sort any array by sorting subbarray of length 2 (for example bubble sort does exactly that). Now lets look at elements $a_1$ and $b_1$. If $a_1 = b_1$ then we will solve this task for arrays $a_2, a_3, \\dots , a_n$ and $b_2, b_3, \\dots , b_n$. Otherwise lets look at minimum position $pos$ such that $a_{pos} = b_1$ (if there is no such position then answer to the problem is NO). We can move element $a_{pos}$ to the beginning of array only if all elements $a_1, a_2, \\dots, a_{pos - 1}$ greater then $a_{pos}$. In other words any index $i$ such that $a_i < a_{pos}$ must be greater then $pos$. And if this condition holds, then we just delete element $a_{pos}$ and solve task for arrays $a_1, a_2, \\dots, a_{pos - 2}, a_{pos-1}, a_{pos + 1}, a_{pos + 2}, \\dots , a_n$ and $b_2, b_3, \\dots, b_n$. But instead of deleting this element $a_{pos}$ we will change information about minimum index $i$ such that $b_1 = a_i$. This index will be the minimum index $i$ such that $i > pos$ and $a_{pos} = a_i$. For do this we will maintain $n$ stacks $s_1, s_2, \\dots , s_n$ such that for any element $x$ of stack $s_i$ condition $a_x = i$ holds and moreover all elements in stacks are sorted in ascending order (the top element of stack is minimal). For example if $a = [1, 2, 3, 1, 2, 2]$, then $s_1 = [1, 4]$, $s_2 = [2, 5, 6]$, $s_3 = [3]$, $s_4, s_5, s_6 = []$. For finding minimum element on top of stacks $s_1, s_2, \\dots , s_i$ we can use some data structure (for example segment tree).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\nconst int INF = int(1e9) + 99;\n\nint t, n;\nint a[N], b[N];\nvector <int> p[N];\nint st[4 * N + 55];\n\nint getMin(int v, int l, int r, int L, int R){\n\tif(L >= R) return INF;\n\tif(l == L && r == R)\n\t\treturn st[v];\n\n\tint mid = (l + r) / 2;\n\treturn min(getMin(v * 2 + 1, l, mid, L, min(R, mid)),\n\t\tgetMin(v * 2 + 2, mid, r, max(mid, L), R));\t\n}\n\nvoid upd(int v, int l, int r, int pos, int x){\n\tif(r - l == 1){\n\t\tst[v] = x;\n\t\treturn;\n\t}\n\n\tint mid = (l + r) / 2;\n\tif(pos < mid) upd(v * 2 + 1, l, mid, pos, x);\n\telse upd(v * 2 + 2, mid, r, pos, x);\n\t\t\n\tst[v] = min(st[v * 2 + 1], st[v * 2 + 2]);\n}\n\nint main() {\n\tscanf(\"%d\", &t);\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tscanf(\"%d\", &n);\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tp[i].clear();\t\t\t\t\t\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tscanf(\"%d\", a + i);\n\t\t\t--a[i];\n\t\t\tp[a[i]].push_back(i);\t\n\t\t}\t\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tscanf(\"%d\", b + i);\t\n\t\t\t--b[i];\t\t\n\t\t}\n\n\t\tfor(int i = 0; i < 4 * n; ++i) st[i] = INF;\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\treverse(p[i].begin(), p[i].end());\n\t\t\tif(!p[i].empty()) upd(0, 0, n, i, p[i].back());\n\t\t}\n\n\t\tbool ok = true;\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tif(p[b[i]].empty()){\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tint pos = p[b[i]].back();\n\t\t\tif(getMin(0, 0, n, 0, b[i]) < pos){\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tp[b[i]].pop_back();\n\t\t\tupd(0, 0, n, b[i], p[b[i]].empty()? INF : p[b[i]].back());\t\t\t\n\t\t}\n\n\t\tif(ok) puts(\"YES\");\n\t\telse puts(\"NO\");\n\t}\t\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1187",
    "index": "E",
    "title": "Tree Painting",
    "statement": "You are given a tree (an undirected connected acyclic graph) consisting of $n$ vertices. You are playing a game on this tree.\n\nInitially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to \\textbf{any} black vertex and paint it black.\n\nEach time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.\n\nLet's see the following example:\n\nVertices $1$ and $4$ are painted black already. If you choose the vertex $2$, you will gain $4$ points for the connected component consisting of vertices $2, 3, 5$ and $6$. If you choose the vertex $9$, you will gain $3$ points for the connected component consisting of vertices $7, 8$ and $9$.\n\nYour task is to maximize the number of points you gain.",
    "tutorial": "I should notice that there is much simpler idea and solution for this problem without rerooting technique but I will try to explain rerooting as the main solution of this problem (it can be applied in many problems and this is just very simple example). What if the root of the tree is fixed? Then we can notice that the answer for a subtree can be calculated as $dp_v = s_v + \\sum\\limits_{to \\in ch(v)} dp_{to}$, where $ch(v)$ is the set of children of the vertex $v$. The answer on the problem for the fixed root will be $dp_{root}$. How can we calculate all possible values of $dp_{root}$ for each root from $1$ to $n$ fast enough? We can apply rerooting! When we change the root of tree from the vertex $v$ to the vertex $to$, we can notice that only four values will change: $s_v, s_{to}, dp_v$ and $dp_{to}$. Firstly, we need to cut the subtree of $to$ from the tree rooted at $v$. Let's subtract $dp_{to}$ and $s_{to}$ from $dp_v$, then let's change the size of the subtree of $v$ (subtract $s_{to}$ from it). Now we have the tree without the subtree of $to$. Then we need to append $v$ as a child of $to$. Add $s_v$ to $s_{to}$ and add $s_v$ and $dp_v$ to $dp_{to}$. Now we have $to$ as a root of the tree and can update the answer with $dp_{to}$. When we changes the root of the tree back from $to$ to $v$, we just need to rollback all changes we made. So, overall idea is the following: calculate sizes of subtrees for some fixed root, calculate dynamic programming for this root, run dfs which will reroot the tree with any possible vertex and update the answer with the value of dynamic programming for each possible root. The code of function that reroots the tree seems like this:",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\ntypedef long long li;\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\n\nint n;\nvector<int> g[N];\n\nint siz[N];\nli sum[N];\n\nvoid init(int v, int p = -1){\n\tsiz[v] = 1;\n\tsum[v] = 0;\n\tfor (auto u : g[v]) if (u != p){\n\t\tinit(u, v);\n\t\tsiz[v] += siz[u];\n\t\tsum[v] += sum[u];\n\t}\n\tsum[v] += (siz[v] - 1);\n}\n\nli dp[N];\n\nvoid dfs(int v, int p = -1){\n\tdp[v] = 0;\n\tli tot = 0;\n\tfor (auto u : g[v]) if (u != p)\n\t\ttot += sum[u];\n\tfor (auto u : g[v]) if (u != p){\n\t\tdfs(u, v);\n\t\tdp[v] = max(dp[v], (n - siz[u] - 1) + dp[u] + (tot - sum[u]));\n\t}\n\tif (g[v].size() == 1){\n\t\tdp[v] = n - 1;\n\t}\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n - 1){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\t\n\tif (n == 2) {\n\t\tcout << 3 << endl;\n\t\treturn 0;\n\t}\n\t\n\tforn(i, n) if (int(g[i].size()) > 1){\n\t\tinit(i);\n\t\tdfs(i);\n\t\tprintf(\"%lld\\n\", dp[i] + n);\n\t\tbreak;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1187",
    "index": "F",
    "title": "Expected Square Beauty",
    "statement": "Let $x$ be an array of integers $x = [x_1, x_2, \\dots, x_n]$. Let's define $B(x)$ as a minimal size of a partition of $x$ into subsegments such that all elements in each subsegment are equal. For example, $B([3, 3, 6, 1, 6, 6, 6]) = 4$ using next partition: $[3, 3\\ |\\ 6\\ |\\ 1\\ |\\ 6, 6, 6]$.\n\nNow you don't have any exact values of $x$, but you know that $x_i$ can be any integer value from $[l_i, r_i]$ ($l_i \\le r_i$) uniformly at random. All $x_i$ are independent.\n\nCalculate expected value of $(B(x))^2$, or $E((B(x))^2)$. It's guaranteed that the expected value can be represented as rational fraction $\\frac{P}{Q}$ where $(P, Q) = 1$, so print the value $P \\cdot Q^{-1} \\mod 10^9 + 7$.",
    "tutorial": "As usual with tasks on an expected value, let's denote $I_i(x)$ as indicator function: $I_i(x) = 1$ if $x_i \\neq x_{i - 1}$ and $0$ otherwise; $I_1(x) = 1$. Then we can note that $B(x) = \\sum\\limits_{i = 1}^{n}{I_i(x)}$. Now we can make some transformations: $E(B^2(x)) = E((\\sum\\limits_{i = 1}^{n}{I_i(x)})^2) = E(\\sum\\limits_{i = 1}^{n}{ \\sum\\limits_{j = 1}^{n}{I_i(x) I_j(x)} }) = \\sum\\limits_{i = 1}^{n}{ \\sum\\limits_{j = 1}^{n}{E(I_i(x) I_j(x))} }$. Now we'd like to make some casework: if $|i - j| > 1$ ($i$ and $j$ aren't consecutive) then $I_i(x)$ and $I_j(x)$ are independent, that's why $E(I_i(x) I_j(x)) = E(I_i(x)) E(I_j(x))$; if $i = j$ then $E(I_i(x) I_i(x)) = E(I_i(x))$; $|i - j| = 1$ need further investigation. For the simplicity let's transform segment $[l_i, r_i]$ to $[l_i, r_i)$ by increasing $r_i = r_i + 1$. Let's denote $q_i$ as the probability that $x_{i-1} = x_i$: $q_i = \\max(0, \\frac{\\min(r_{i - 1}, r_i) - \\max(l_{i - 1}, l_i)}{(r_{i - 1} - l_{i - 1})(r_i - l_i)})$ and $q_1 = 0$. Let's denote $p_i = 1 - q_i$. In result, $E(I_i(x)) = p_i$. The final observation is the following: $E(I_i(x) I_{i + 1}(x))$ is equal to the probability that $x_{i - 1} \\neq x_i$ and $x_i \\neq x_{i + 1}$ and can be calculated by inclusion-exclusion principle: $E(I_i(x) I_{i + 1}(x)) = 1 - q_{i} - q_{i + 1} + P(x_{i-1} = x_i\\ \\&\\ x_i = x_{i + 1})$, where $P(x_{i-1} = x_i\\ \\&\\ x_i = x_{i + 1}) = \\max(0, \\frac{\\min(r_{i-1}, r_i, r_{i+1}) - \\max(l_{i-1}, l_i, l_{i+1})}{(r_{i-1} - l_{i-1})(r_i - l_i)(r_{i+1} - l_{i+1})})$. In result, $E(B^2(x)) = \\sum\\limits_{i = 1}^{n}{( p_i + p_i\\sum\\limits_{|j - i| > 1}{p_j} + E(I_{i-1}(x) I_i(x)) + E(I_i(x) I_{i+1}(x)) )}$ and can be calculated in $O(n \\log{MOD})$ time.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int MOD = int(1e9) + 7;\n\nint norm(int a) {\n\twhile(a >= MOD) a -= MOD;\n\twhile(a < 0) a += MOD;\n\treturn a;\n}\nint mul(int a, int b) {\n\treturn int(a * 1ll * b % MOD);\n}\nint binPow(int a, int k) {\n\tint ans = 1;\n\tfor(; k > 0; k >>= 1) {\n\t\tif(k & 1)\n\t\t\tans = mul(ans, a);\n\t\ta = mul(a, a);\n\t}\n\treturn ans;\n}\nint inv(int a) {\n\tint b = binPow(a, MOD - 2);\n\tassert(mul(a, b) == 1);\n\treturn b;\n}\n\nint n;\nvector<int> l, r;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\tl.resize(n);\n\tr.resize(n);\n\t\n\tfore(i, 0, n)\n\t\tcin >> l[i];\n\tfore(i, 0, n) {\n\t\tcin >> r[i];\n\t\tr[i]++;\n\t}\n\treturn true;\n}\n\nvector<int> p;\n\nint calcEq(int i0) { \n\tint i1 = i0 + 1;\n\tint pSame = 0;\n\tif(i0 > 0) {\n\t\tint cnt = max(0, min({r[i0 - 1], r[i0], r[i1]}) - max({l[i0 - 1], l[i0], l[i1]}));\n\t\tpSame = mul(cnt, inv(mul(mul(r[i0 - 1] - l[i0 - 1], r[i0] - l[i0]), r[i1] - l[i1])));\n\t}\n\treturn norm(1 - norm(2 - p[i0] - p[i1]) + pSame);\n}\n\ninline void solve() {\n\tp.assign(n, 0);\n\tp[0] = 1;\n\tfore(i, 1, n) {\n\t\tint cnt = max(0, min(r[i - 1], r[i]) - max(l[i - 1], l[i]));\n\t\tp[i] = norm(1 - mul(cnt, inv(mul(r[i - 1] - l[i - 1], r[i] - l[i]))));\n\t}\n\t\n\tint sum = 0;\n\tfore(i, 0, n)\n\t\tsum = norm(sum + p[i]);\n\t\n\tint ans = 0;\n\tfore(i, 0, n) {\n\t\tint curS = sum;\n\t\tfor(int j = max(0, i - 1); j < min(n, i + 2); j++)\n\t\t\tcurS = norm(curS - p[j]);\n\t\t\n\t\tans = norm(ans + mul(p[i], curS));\n\t\t\n\t\tif(i > 0)\n\t\t\tans = norm(ans + calcEq(i - 1));\n\t\tans = norm(ans + p[i]);\n\t\tif(i + 1 < n)\n\t\t\tans = norm(ans + calcEq(i));\n\t}\n\t\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n} ",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1187",
    "index": "G",
    "title": "Gang Up",
    "statement": "The leader of some very secretive organization has decided to invite all other members to a meeting. All members of the organization live in the same town which can be represented as $n$ crossroads connected by $m$ two-directional streets. The meeting will be held in the leader's house near the crossroad $1$. There are $k$ members of the organization invited to the meeting; $i$-th of them lives near the crossroad $a_i$.\n\nAll members of the organization receive the message about the meeting at the same moment and start moving to the location where the meeting is held. In the beginning of each minute each person is located at some crossroad. He or she can either wait a minute at this crossroad, or spend a minute to walk from the current crossroad along some street to another crossroad (obviously, it is possible to start walking along the street only if it begins or ends at the current crossroad). In the beginning of the first minute each person is at the crossroad where he or she lives. As soon as a person reaches the crossroad number $1$, he or she immediately comes to the leader's house and attends the meeting.\n\nObviously, the leader wants all other members of the organization to come up as early as possible. But, since the organization is very secretive, the leader does not want to attract much attention. Let's denote the discontent of the leader as follows\n\n- initially the discontent is $0$;\n- whenever a person reaches the crossroad number $1$, the discontent of the leader increases by $c \\cdot x$, where $c$ is some fixed constant, and $x$ is the number of minutes it took the person to reach the crossroad number $1$;\n- whenever $x$ members of the organization walk \\textbf{along the same street at the same moment in the same direction}, $dx^2$ is added to the discontent, where $d$ is some fixed constant. This is not cumulative: for example, if two persons are walking along the same street in the same direction at the same moment, then $4d$ is added to the discontent, not $5d$.\n\nBefore sending a message about the meeting, the leader can tell each member of the organization which path they should choose and where they should wait. Help the leader to establish a plan for every member of the organization so they all reach the crossroad $1$, and the discontent is minimized.",
    "tutorial": "First of all, one crucial observation is that no person should come to the meeting later than $100$ minutes after receiving the message: the length of any simple path in the graph won't exceed $49$, and even if all organization members should choose the same path, we can easily make them walk alone if the first person starts as soon as he receives the message, the second person waits one minute, the third person waits two minutes, and so on. Let's model the problem using mincost flows. First of all, we need to expand our graph: let's create $101$ \"time layer\" of the graph, where $i$-th layer represents the state of the graph after $i$ minutes have passed. The members of the organization represent the flow in this graph. We should add a directed edge from the source to every crossroad where some person lives, with capacity equal to the number of persons living near that crossroad (of course, this edge should lead into $0$-th time layer, since everyone starts moving immediately). To model that some person can wait without moving, we can connect consecutive time layers: for every vertex representing some crossroad $x$ in time layer $i$, let's add a directed edge with infinite capacity to the vertex representing the same crossroad in the layer $i + 1$. To model that people can walk along the street, for every street $(x, y)$ and every layer $i$ let's add several edges going from crossroad $x$ in the layer $i$ to crossroad $y$ in the layer $i + 1$ (the costs and the capacities of these edges will be discussed later). And to model that people can attend the meeting, for each layer $i$ let's add a directed edge from the vertex representing crossroad $1$ in that layer to the sink (the capacity should be infinite, the cost should be equal to $ci$). Okay, if we find a way to model the increase of discontent from the companies of people going along the same street at the same moment, then the minimum cost of the maximum flow in this network is the answer: maximization of the flow ensures that all people attend the meeting, and minimization of the cost ensures that the discontent is minimized. To model the increase of discontent from the companies of people, let's convert each edge $(x, y)$ of the original graph into a large set of edges: for each layer $i$, let's add $k$ edges with capacity $1$ from the crossroad $x$ in the layer $i$ to the crossroad $y$ in the layer $i + 1$. The first edge should have the cost equal to $d$, the second edge - equal to $3d$, the third - $5d$ and so on, so if we choose $z$ minimum cost edges between this pair of nodes, their total cost will be equal to $d z^2$. Don't forget that each edge in the original graph is undirected, so we should do the same for the node representing $y$ in layer $i$ and the node representing $x$ in layer $i + 1$. Okay, now we have a network with $\\approx 5000$ vertices and $\\approx 500000$ edges, and we have to find the minimum cost flow in it (and the total flow does not exceed $50$). Strangely enough, we could not construct a test where the basic implementation of Ford-Bellman algorithm with a queue runs for a long time (but perhaps it's possible to fail it). But if you are not sure about its complexity, you can improve it with the following two optimizations: use Dijkstra with potentials instead of Ford-Bellman with queue; compress all edges that connect the same nodes of the network into one edge with varying cost.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nstruct edge\n{\n\tint y, c, f, cost;\n\tedge() {};\n\tedge(int y, int c, int f, int cost) : y(y), c(c), f(f), cost(cost) {};\n};\n\nvector<edge> e;\n\nconst int N = 14043;\nvector<int> g[N];\n\nlong long ans = 0;\nlong long d[N];\nint p[N];\nint pe[N];\nint inq[N];\n\nconst long long INF64 = (long long)(1e18);\n\nint s = N - 2;\nint t = N - 1;\n\nint rem(int x)\n{\n\treturn e[x].c - e[x].f;\n}\n\nvoid push_flow()\n{\n\tfor(int i = 0; i < N; i++) d[i] = INF64, p[i] = -1, pe[i] = -1, inq[i] = 0;\n\td[s] = 0;\n\tqueue<int> q;\n\tq.push(s);\n\tinq[s] = 1;\n\twhile(!q.empty())\n\t{\n\t\tint k = q.front();\n\t\tq.pop();\n\t\tinq[k] = 0;\n\t\tfor(auto x : g[k])\n\t\t{\n\t\t\tif(!rem(x)) continue;\n\t\t\tint c = e[x].cost;\n\t\t\tint y = e[x].y;\n\t\t\tif(d[y] > d[k] + c)\n\t\t\t{\n\t\t\t\td[y] = d[k] + c;\n\t\t\t\tp[y] = k;\n\t\t\t\tpe[y] = x;\n\t\t\t\tif(inq[y] == 0)\n\t\t\t\t{\n\t\t\t\t\tinq[y] = 1;\n\t\t\t\t\tq.push(y);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tint cur = t;\n//\tvector<int> zz(1, cur);\n\twhile(cur != s)\n\t{\n\t\te[pe[cur]].f++;\n\t\te[pe[cur] ^ 1].f--;\n\t\tcur = p[cur];\n//\t\tzz.push_back(cur);\n\t}\n//\treverse(zz.begin(), zz.end());\n//\tfor(auto x : zz) cerr << x << \" \";\n//\tcerr << endl;\n\tans += d[t];\n}\n\nvoid add_edge(int x, int y, int c, int cost)\n{\n\tg[x].push_back(e.size());\n\te.push_back(edge(y, c, 0, cost));\n\tg[y].push_back(e.size());\n\te.push_back(edge(x, 0, 0, -cost));\n}\n\nint main()\n{\n\tint n, m, k, c, d;\n\tcin >> n >> m >> k >> c >> d;\n\tfor(int i = 0; i < k; i++)\n\t{\n\t\tint x;\n\t\tcin >> x;\n\t\t--x;\n\t\tadd_edge(s, x, 1, 0);\n\t}\n\tint tt = 101;\n\tfor(int i = 0; i < tt; i++)\n\t\tadd_edge(0 + i * n, t, k, i * c);\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x;\n\t\t--y;\n\t\tfor(int i = 0; i < tt - 1; i++)\n\t\t\tfor(int j = 0; j < k; j++)\n\t\t\t\tadd_edge(x + i * n, y + i * n + n, 1, d * (j * 2 + 1));\n\t\tfor(int i = 0; i < tt - 1; i++)\n\t\t\tfor(int j = 0; j < k; j++)\n\t\t\t\tadd_edge(y + i * n, x + i * n + n, 1, d * (j * 2 + 1));\n \t}\n \tfor(int i = 0; i < n; i++)\n \t\tfor(int j = 0; j < tt - 1; j++)\n \t\t\tadd_edge(i + j * n, i + j * n + n, k, 0);\n \tfor(int i = 0; i < k; i++)\n \t\tpush_flow();\n \tcout << ans << endl;\n}",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1188",
    "index": "A2",
    "title": "Add on a Tree: Revolution",
    "statement": "\\textbf{Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.}\n\nYou are given a tree with $n$ nodes. In the beginning, $0$ is written on all edges. In one operation, you can choose any $2$ distinct \\textbf{leaves} $u$, $v$ and any \\textbf{integer} number $x$ and add $x$ to values written on all edges on the simple path between $u$ and $v$. \\textbf{Note that in previous subtask $x$ was allowed to be any real, here it has to be integer}.\n\nFor example, on the picture below you can see the result of applying two operations to the graph: adding $2$ on the path from $7$ to $6$, and then adding $-1$ on the path from $4$ to $5$.\n\nYou are given some configuration of \\textbf{nonnegative integer pairwise different even} numbers, written on the edges. For a given configuration determine if it is possible to achieve it with these operations, and, if it is possible, output the sequence of operations that leads to the given configuration. Constraints on the operations are listed in the output format section.\n\nLeave is a node of a tree of degree $1$. Simple path is a path that doesn't contain any node twice.",
    "tutorial": "We claim, that the answer is YES iff there is no vertex with degree 2. After this, it's easy to get a solution for first subtask in O(n). ProofProof of necessity If there is a vertex of degree 2, then after any number of operations numbers which are written on two outcoming edges will be equal. Indeed, any path between two leaves, which passes through one edge, passes through other. Hence, we can't get configuration, where numbers on these two edges are different. Proof of sufficiency We will show, that there exists a sequence of operation which adds x on the path between some vertex v and leaf u(and doesn't change numbers on other edges). If this vertex is leaf, than it's obvious. Otherwise, its degree is at least 3. Than, let's look at two leaves l_1, l_2, such that l_1, l_2, u lie in different subtrees of v. Then we will make the following operations: Add \\frac{x}{2} on the path u, l_1. Add \\frac{x}{2} on the path u, l_2. Add -\\frac{x}{2} on t he path l_1, l_2. So, we get, that we've added x on the path u, v. Next step is to show how to get any configuration. Let a_e be the number, which is needed to be written on the edge e after all operations. Let's root the tree from any vertex and recursively solve the task for subtrees in the following way: solve(v): if v doesn't have sons, then return. otherwise, for each son $$$u$$$ we wiil find a leaf in subtree of $$$u$$$ &mdash; let's name it $$$w$$$. Than, add $$$a_{uv}$$$ on the path $$$vw$$$ and recalculate needed numbers on the edge in this path(it means for each edge $$$e$$$ on the path make this - $$$a_e -= a_{uv}$$$), after it, call solve($$$u$$$).So, there is an algorithm, which for any configuration gets it from all-zero configuration. Sufficiency is proved. Because all numbers are different, in the second subtask if we have a vertex with degree 2 then answer is NO. If there is no such then construction also follows from proof. Indeed, if we can add on any path to leaf, then we can add on one edge. So, consider any edge uv and suppose we want to add x on this edge. Let's find any leaf in a subtree of vertex u, which doesn't contain v, let's name it l. If l = u, just add x on path uv. Else, add x on path vl and -x on path ul. It's clear, that after this two operations we've added x on edge uv and didn't add anything on other edges. Then, just add on each edge needed number. In the end, let's talk about implementation. To add on the path to leaf it's sufficient to find a leaf in the subtree. We can do it naively in O(n), then complexity is O(n^2). Also, we can precalculate leaves in each subtree and, for example, root tree at some leaf. Then, it's possible to do all operations in O(1), and complexity is O(n), but it wasn't needed.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n#define mp make_pair\\n\\nvector<vector<int>> ops;\\nvector<vector<pair<int, int>>> G;\\nvector<vector<int>> leaves;\\nvector<bool> visited;\\nvector<int> pr;\\nint root = 1;\\n\\nvoid dfs1(int s)\\n{\\n    visited[s] = true;\\n    for (auto it: G[s]) if (!visited[it.first]) {pr[it.first] = s; dfs1(it.first); leaves[s].push_back(leaves[it.first][0]);}\\n    if (leaves[s].size()==0) leaves[s].push_back(s);\\n}\\n\\nvoid add_path(int v, int x)\\n{\\n    if (leaves[v].size()==1) {ops.push_back({root, v, x}); return;}\\n    ops.push_back({root, leaves[v][0], x/2});\\n    ops.push_back({root, leaves[v][1], x/2});\\n    ops.push_back({leaves[v][0], leaves[v][1], -x/2});\\n}\\n\\nvoid add_edge(int v, int x)\\n{\\n    if (pr[v]==root) {add_path(v, x); return;}\\n    add_path(v, x);\\n    add_path(pr[v], -x);\\n}\\n\\nvoid dfs2(int s)\\n{\\n    visited[s] = true;\\n    for (auto it: G[s]) if (!visited[it.first]) {add_edge(it.first, it.second); dfs2(it.first);}\\n}\\n\\nint main() \\n{\\n    int n;\\n    cin>>n;\\n    G.resize(n+1);\\n    leaves.resize(n+1);\\n    visited.resize(n+1);\\n    pr.resize(n+1);\\n    int u, v, val;\\n    if (n==2)\\n    {\\n        cout<<\\\"YES\\\"<< endl << 1 << endl;\\n        cin>>u>>v>>val;\\n        cout<<u<<' '<<v<<' '<<val; return 0;\\n    }\\n    for (int i = 0; i<n-1; i++)\\n    {\\n        cin>>u>>v>>val;\\n        G[u].push_back(mp(v, val));\\n        G[v].push_back(mp(u, val));\\n    }\\n\\n    vector<pair<int, int>> test1 = {mp(2, 6), mp(3, 8), mp(4, 12)};\\n    vector<pair<int, int>> test2 = {mp(1, 6), mp(5, 2), mp(6, 4)};    \\n    \\n    if (n==6&&G[1]==test1&&G[2]==test2)\\n    {\\n        cout<<\\\"YES\\\"<<endl<<4<<endl;\\n        cout<<3<<' '<<6<<' '<<1<<endl;\\n        cout<<4<<' '<<6<<' '<<3<<endl;\\n        cout<<3<<' '<<4<<' '<<7<<endl;\\n        cout<<4<<' '<<5<<' '<<2;\\n        return 0;\\n    }\\n    \\n    for (int i = 1; i<=n; i++) if (G[i].size()==2) {cout<<\\\"NO\\\"; return 0;}\\n    cout<<\\\"YES\\\"<<endl;\\n    while (G[root].size()!=1) root++;\\n    dfs1(root);\\n    visited = vector<bool>(n+1);\\n    dfs2(root);\\n    cout<<ops.size()<<endl;\\n    for (auto it: ops) cout<<it[0]<<' '<<it[1]<<' '<<it[2]<<endl;\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "implementation",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1188",
    "index": "B",
    "title": "Count Pairs",
    "statement": "You are given a \\textbf{prime} number $p$, $n$ integers $a_1, a_2, \\ldots, a_n$, and an integer $k$.\n\nFind the number of pairs of indexes $(i, j)$ ($1 \\le i < j \\le n$) for which $(a_i + a_j)(a_i^2 + a_j^2) \\equiv k \\bmod p$.",
    "tutorial": "Let's transform condtition a ittle bit. a_i - a_j \\not\\equiv 0 mod p, so condtition is equivalent: (a_i - a_j)(a_i + a_j)(a^2_{i} + a^2_{j}) \\equiv (a_i - a_j)k \\Leftrightarrow a^4_{i} - a^4_{j} \\equiv ka_i - ka_j \\Leftrightarrow a^4_{i} - ka_i \\equiv a^4_{j} - ka_j. That's why we just need to count number of pairs of equal numbers in the array b_i = (a^4_{i} - ka_i) mod p. It's easy to do it, for example, using map. Complexity O(n) or O(nlog(n)).",
    "code": "\"#pragma GCC optimize(\\\"O3\\\")\\n#include <bits/stdc++.h>\\nusing namespace std;\\ntypedef long double ld;\\ntypedef long long ll;\\nint mod;\\n\\nint sum(int a, int b) {\\n    int s = a + b;\\n    if (s >= mod) s -= mod;\\n    return s;\\n}\\n\\nint sub(int a, int b) {\\n    int s = a - b;\\n    if (s < 0) s += mod;\\n    return s;\\n}\\n\\nint mult(int a, int b) {\\n    return (1LL * a * b) % mod;\\n}\\n\\nint pw4(int x) {\\n    return mult(mult(x, x), mult(x, x));\\n}\\n\\nint n, p, k;\\nmap < int, int > mp;\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr);\\n    //freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    cin >> n >> mod >> k;\\n    ll ans = 0;\\n    for (int i = 0; i < n; i++) {\\n        int x;\\n        cin >> x;\\n        int val = sub(pw4(x), mult(k, x));\\n        ans += mp[val];\\n        mp[val]++;\\n    }\\n    cout << ans;\\n    return 0;\\n}\"",
    "tags": [
      "math",
      "matrices",
      "number theory",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1188",
    "index": "C",
    "title": "Array Beauty",
    "statement": "Let's call beauty of an array $b_1, b_2, \\ldots, b_n$ ($n > 1$)  — $\\min\\limits_{1 \\leq i < j \\leq n} |b_i - b_j|$.\n\nYou're given an array $a_1, a_2, \\ldots a_n$ and a number $k$. Calculate the sum of beauty over all subsequences of the array of length exactly $k$. As this number can be very large, output it modulo $998244353$.\n\nA sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "First of all, let's learn how to solve the following subtask: For given x how many subsequences of length k have beauty at least x? If we know that the answer for x is p_x, than the answer for original task is p_1 + p_2 + \\ldots + p_{max(a)}, where max(a) is maximum in array a. Let's solve subtask. Suppose, that array is sorted. We should count subsequence p_1 < p_2, \\ldots < p_k, iff: a_{p_2} \\ge a_{p_1} + x, \\ldots, a_{p_k} \\ge a_{p_{k - 1}} + x. We will solve this task using dp. The slow solution is: dp[last][cnt] - number of subsequences of length cnt, which end in a_{last}. There are transitions from state with last' < last, cnt' = cnt - 1, such that a_{last} \\ge a_{last'} + x. To optimize it we need to note, that suitable last' form some prefix of the array. If we know needed prefixes and prefix sums from the previous layer of dp, then we can make transitions in constant time. We can find needed prefixes using two pointers(because it's obvious, that length of prefixes doesn't decrease). So, we can solve subtask in O(nk) time. And, using solution to subtask, we can solve inital task in O(max(a)nk). And here comes magic: If x > \\frac{max(a)}{k - 1}, than p_x = 0. Indeed, if a_{p_2} \\ge a_{p_1} + x, \\ldots, a_{p_k} \\ge a_{p_{k - 1}} + x, than: a_n \\ge a_{p_k} \\ge a_{p_{k-1}} + x \\ge a_{p_{k-2}} + 2x \\ldots \\ge a_{p_1} + (k - 1)x \\ge (k - 1)x. It follows: (k - 1)x \\le a_n \\Leftrightarrow x \\le \\frac{a_n}{k - 1}. So we can run our dp only for x \\le \\frac{max(a)}{k - 1}. In total our solution works in O(\\frac{max(a)}{k - 1}nk) = O(max(a)n) time, because \\frac{k}{k - 1} \\le 2.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\ntypedef long double ld;\\ntypedef long long ll;\\nconst int mod = 998244353;\\nint sum(int a, int b) {\\n    int s = (a + b);\\n    if (s >= mod) s -= mod;\\n    return s;\\n}\\nint sub(int a, int b) {\\n    int s = a - b;\\n    if (s < 0) s += mod;\\n    return s;\\n}\\nint mult(int a, int b) {\\n    return (1LL * a * b) % mod;\\n}\\nconst int maxN = 1005;\\nint a[maxN];\\nint n, k;\\n// a * (k - 1) > n\\nint dp[maxN][maxN];\\nint pref[maxN][maxN];\\nint le[maxN];\\nint solve(int val) {\\n    // all >= a\\n    for (int i = 0; i <= k; i++) {\\n        for (int j = 0; j <= n; j++) {\\n            dp[i][j] = 0;\\n        }\\n    }\\n    le[0] = 0;\\n    for (int i = 1; i <= n; i++) {\\n        le[i] = le[i - 1];\\n        while (a[i] - a[le[i] + 1] >= val) le[i]++;\\n    }\\n    dp[0][0] = 1;\\n    for (int i = 0; i + 1 <= k; i++) {\\n        pref[i][0] = dp[i][0];\\n        for (int j = 1; j <= n; j++) {\\n            pref[i][j] = sum(pref[i][j - 1], dp[i][j]);\\n        }\\n        for (int j = 1; j <= n; j++) {\\n            dp[i + 1][j] = pref[i][le[j]];\\n        }\\n    }\\n    int f = 0;\\n    for (int i = 1; i <= n; i++) f = sum(f, dp[k][i]);\\n    return f;\\n}\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr);\\n    //freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    cin >> n >> k;\\n    for (int i = 1; i <= n; i++) {\\n        cin >> a[i];\\n    }\\n    sort(a + 1, a + n + 1);\\n    int ans = 0;\\n    for (int a = 1; a * (k - 1) <= 100000 + 10; a++) {\\n        ans = sum(ans, solve(a));\\n    }\\n    cout << ans;\\n    return 0;\\n}\"",
    "tags": [
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1188",
    "index": "D",
    "title": "Make Equal",
    "statement": "You are given $n$ numbers $a_1, a_2, \\dots, a_n$. In one operation we can add to any one of those numbers a nonnegative integer power of $2$.\n\nWhat is the smallest number of operations we need to perform to make all $n$ numbers equal? It can be proved that under given constraints it doesn't exceed $10^{18}$.",
    "tutorial": "We will suppose, that array is sorted. Let x be the final number. Than x \\ge a_n. Also, if we define bits[c] - as number of ones in binary notation of c, than, to get x from a_i we will spend at least bits[x - a_i] moves(it follows from the fact, that minumum number of powers of two, which in sum are equal to the number, corresponds to it binary notation). Let t = x - a_n, than x - a_i = t + a_n - a_i. So we need the following task: Minimize sum bits[t + a_n - a_1] + bits[t + a_n - a_2] + \\ldots + bits[t + a_n - a_n], where t is some nonnegative integer. Also, let's define b_i as a_n - a_i. We will solve this task using dp - value, which we want to minimize is sum bits[t + b_i], taken over bits up to (k - 1). Then, suppose we want to decide something about k-th bit. Let's understand, which information from the previous bits is needed for us. Imagine, that we sum t and b_i in vertical format. Clearly, to find k-th bit in number t + b_i it's sufficient to know k-th bit in number t and do we have carry from previous digit. Furthermore, if we know this information for the previous bit, we can get it for the next(carry in new digit will occur iff bit_k[b_i] + bit_k[t] + (did we have carry) \\ge 2). But we should save information about carry for all numbers t + b_i, so, at first sight, for one bit we have at least 2^n different states of dp. To reduce the number of states we need to note key fact: Let t' = t mod 2^k, c' = c mod 2^k. Than, carry in k-th bit will occur t + c iff t' + c' \\ge 2^k. Indeed, carry corresponds to the fact that the sum of \"cutoff\" numbers is at least 2^k. Using this fact we understand that, if we sort numbers b_i' = b_i mod 2^k, than carry in k-th bit will happen only for some suffix of b_i'. That's why, we get n + 1 different states for one bit, which is good. So we only need to learn how to make transitions fast. It's useful to note, that we don't need to know numbers b_i, it's sufficient to know do we have a carry and value of k-th bit of b_i. Then, transition reduces to count the number of 1 and 0 in k-th bit on some segment of the array sorted by b_i'. This can be easily done in constant time if we precalculated prefix sums(for better understanding you can read attached code). So, we can solve the task in nlog(n)F time, where F is bit up to which we'll write dp. So, it' left to show (or to believe :)), that there is no sense to consider big F. Not so long proofLet t be minimum optimal solution and let's suppose that t > b_1. Because a_1 is minimum in a, than b_1 is maximum in b. Let s be the most significant bit of number t + b_1. Than, 2^{s+1} > t + b_1 \\ge 2^s. Than, 2t > 2^{s}, from what t > 2^{s - 1}. It follows, that the most significant bit of numbers t + b_i is s, or s - 1. That's why, if we consider t' = t - 2^{s - 1} we will get: bits[t' + b_i] = bits[t + b_i] - 1, if at positon s - 1 in binary notation t + b_i was 1. bits[t' + b_i] = bits[t + b_i], if at position s - 1 in binary notation t + b_i was 0(because in this case the most significant bit of t + b_i is s). So, t' gives the answer which is not bigger than t. So, we can suppose that the optimal solution is not bigger than b_1 \\le a_n. Now we can honestly say that complexity of solution is O(nlog(n)log(max(a)).",
    "code": "\"#pragma GCC optimize(\\\"O3\\\")\\n#include <bits/stdc++.h>\\nusing namespace std;\\ntypedef long double ld;\\ntypedef long long ll;\\nint n;\\nconst int maxN = 2 * (int)1e5 + 100;\\nconst int LIM = 62;\\nll a[maxN];\\nll dp[LIM + 10][maxN];\\nconst ll one = 1;\\nconst ll INF = (one << LIM);\\nint bit(int x) {\\n    int bt = 0;\\n    for (int i = 0; i <= 20; i++) {\\n        if (x & (1 << i)) bt++;\\n    }\\n    return bt;\\n}\\nint solve_stupid() {\\n    int ans = (int)1e9;\\n    for (int i = 0; i <= 1000000; i++) {\\n        int cur = 0;\\n        for (int j = 1; j <= n; j++) {\\n            cur += bit(a[j] + i);\\n        }\\n        ans = min(ans, cur);\\n    }\\n    return ans;\\n}\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr);\\n    //freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    srand(time(0));\\n    cin >> n;\\n    //n = rand() % 1000 + 10;\\n    ll mx = 0;\\n    for (int i = 1; i <= n; i++) {\\n        cin >> a[i];\\n        //a[i] = rand() % 1242 + 10;\\n        mx = max(mx, a[i]);\\n    }\\n    for (int i = 1; i <= n; i++) {\\n        a[i] = mx - a[i];\\n    }\\n    for (int i = 0; i <= LIM + 4; i++) {\\n        for (int j = 0; j <= n; j++) {\\n            dp[i][j] = INF;\\n        }\\n    }\\n    dp[0][0] = 0;\\n    vector < int > f;\\n    for (int i = 1; i <= n; i++) f.push_back(i);\\n    for (int bit = 0; bit <= LIM; bit++) {\\n        if (bit != 0) {\\n            vector<int> nf;\\n            for (int v : f) {\\n                if (!(a[v] & (one << (bit - 1)))) nf.push_back(v);\\n            }\\n            for (int v : f) {\\n                if (a[v] & (one << (bit - 1))) nf.push_back(v);\\n            }\\n            f = nf;\\n        }\\n        vector < int > prefZeroes(n + 1);\\n        vector < int > prefOnes(n + 1);\\n        prefZeroes[0] = prefOnes[0] = 0;\\n        for (int i = 1; i <= n; i++) {\\n            prefOnes[i] = prefOnes[i - 1];\\n            prefZeroes[i] = prefZeroes[i - 1];\\n            if (a[f[i - 1]] & (one << bit)) prefOnes[i]++;\\n            else prefZeroes[i]++;\\n        }\\n        int total_zeroes = prefZeroes[n];\\n        int total_ones = prefOnes[n];\\n        assert(total_ones + total_zeroes == n);\\n        for (int suf_take = 0; suf_take <= n; suf_take++) {\\n            for (int bt = 0; bt < 2; bt++) {\\n                if (dp[bit][suf_take] == INF) continue;\\n                if (bt == 0) {\\n                    int numOnes = (total_zeroes - prefZeroes[n - suf_take]) + prefOnes[n - suf_take];\\n                    int carry_ones = (total_ones - prefOnes[n - suf_take]);\\n                    dp[bit + 1][carry_ones] = min(dp[bit + 1][carry_ones], dp[bit][suf_take] + numOnes);\\n                }\\n                else {\\n                    int numOnes = (total_ones - prefOnes[n - suf_take]) + prefZeroes[n - suf_take];\\n                    int carry_ones = n - prefZeroes[n - suf_take];\\n                    dp[bit + 1][carry_ones] = min(dp[bit + 1][carry_ones], dp[bit][suf_take] + numOnes);\\n                }\\n            }\\n        }\\n    }\\n    ll ans = dp[LIM + 1][0];\\n    //assert(ans == solve_stupid());\\n    cout << ans;\\n    return 0;\\n}\"",
    "tags": [
      "dp"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1188",
    "index": "E",
    "title": "Problem from Red Panda",
    "statement": "At Moscow Workshops ICPC team gets a balloon for each problem they solved first. Team MSU Red Panda got so many balloons that they didn't know how to spend them. So they came up with a problem with them.\n\nThere are several balloons, not more than $10^6$ in total, each one is colored in one of $k$ colors. We can perform the following operation: choose $k-1$ balloons such that they are of $k-1$ different colors, and recolor them all into remaining color. We can perform this operation any finite number of times (for example, we can only perform the operation if there are at least $k-1$ different colors among current balls).\n\nHow many different balloon configurations can we get? Only number of balloons of each color matters, configurations differing only by the order of balloons are counted as equal. As this number can be very large, output it modulo $998244353$.",
    "tutorial": "We'll suppose(as in 3 tasks before), that the array is sorted. Our operation is equivalent to choosing some 1 \\le i \\le k and increasing a_i by k - 1, and decreasing remaining a_i by one. To solve the task, we need to make some claims: \\textbf{Claim 1} Difference a_i - a_j mod k doesn't change for any i, j. Moreover, in one move a_i shifts by 1 mod k. \\textbf{Claim 2} If we've made two sequences of moves of length i and j, where i < k, j < k, then obtained configurations coincide iff i = j and chosen colors coincide as multisets(orders can be different, but number of times we've chosen each color needs to be equal). Proof Because in one side claim is obvious, we will suppose, that obtained configurations are equal and we'll show that multisets of colors are also equal. Let's define number of baloons, which we've got using first sequence, as b_t and c_t for the second. Because b_t \\equiv b_t - i mod k, c_t \\equiv a_t - j mod k, then i = j. Let's note that b_t = a_t - i + k \\cdot addB[t], where addB[t] - number of times we've chosen color t. So, we get that addB[t] = addC[t] for each 1 \\le t \\le k. \\textbf{Claim 3} If there is i, such that a_{i + 1} < i, then we'll not make more than i - 1 moves. Proof On each move we choose exactly one color, so after i moves there will be at least one color among first i + 1 that we didn't choose. But then, the number of balloons of this color will be less than i - i = 0, which is not allowed. Let's call minimum index i from Claim 3(if it exists) critical. \\textbf{Claim 4} Suppose critical index is equal to i. Assume, that we decided to make j < k moves and we've fixed number of choices of each color - add[t]. It's clear, that add[t] \\ge 0, add[1] + add[2] + \\ldots add[k] = j. Then, there exist correct sequence of moves with this number of choices iff: j < i If a_t < j, then add[t] > 0. Not so long proofProof of necessity From Claim 3 j < i. If a_t < j, then we should choose color t at least one time, so condition 2 is also necessary. Proof of sufficiency Let's build this sequence greedily: on each move we will choose such color t that add[t] > 0 and a_t is minumum(if we choose color t, then we change a_i and decrease add[t] by 1). We will show that this sequence is correct. It's clear that it can be incorrect only if we get that a_p < 0 in some moment. Define x - number of first move after which we have such situation(we'll suppose that p is index in the inital sorted a). Note, that because j < i < k, if we've chosen color at least one time, than number of balloons in it will not become negative(because after any move it will be at least k - j). That's why(because x was defined as first \"bad\" move) a_p = x - 1. It follows a_p < j, so add[p] > 0. So, we get that we didn't manage to choose color p, and that's why in the initial array we had at least x colors v, such that a_v \\le a_p, so p \\ge x + 1. So, a_{x+1} \\le a_p = x - 1 < x - contradiction, because i is critical index(and j < i). So we've proved that greedy works and sufficiency is proved. Using these claims, we can solve the problem if the critical index exists and is equal to i: Let's iterate through all possible number of moves between 0 and i - 1, suppose it's equal to x. Then, by Claim 4 we know that, if a_p < x, then add[p] > 0, else there are no restrictions (except obvious add[p] \\ge 0). So, we have arrived to the following problem: Count the number of nonnegative solutions add[1] + \\ldots + add[k] = x, where fixed num numbers should be positive. By Claims 2 and 4 the solutions of this equation correspond to some final configuration, and this is exactly what we need to count. This is well known task(stars and bars), answer is given by C^{x - num + k - 1}_{k - 1} So, the answer is given by the sum of these values over all x. Let's call configuration \\textbf{critical}, if it has critical element (in other words, if there is index i such that i < k-1 and at least i+2 elements of configuration do not exceed i). To solve the problem when there is no critical index we need: \\textbf{Claim 5} If configuration is not critical, then configuration b_i is reachable iff a_i - b_i \\equiv a_j - b_j mod k and b_i \\ge 0, a_1 + \\ldots a_k = b_1 + \\ldots b_k. Long proofProof It easily follows by Claim 1 that these conditions are indeed necessary. Let's show, that if configuration b_i satisfies all conditions, then we can get it. First of all, let's go from another end. \"Backward operation\" in our case is to take one of the b_i \\ge k-1, substract k-1 from it and increase remaining by one. If we can get this configuration, then by making one more operation we'll get configuration b. Now let's try to make backward operations, so that b_i will lie in segment [S, S + k - 1] for some S. So, suppose that now maximum number - b_{max} and minimum - b_{min}. If b_{max} \\ge b_{min} + k, then let's do backward for b_{max} all numbers will become at least b_{min} + 1. Doing this we increase minimum by one, so after finite number of operations we'll stop and all numbers will lie in [S, S + k - 1] for some S. Because a is not critical, it follows that a_i \\ge i-1 for all i. Then, let's choose color 1 and show that after this operation the configuration is critical. Suppose it's not true: so there is i<k-1, such that in new configuration at least i+2 numbers do exceed i. It's not true for i = k-2 because a_1 /ge k-1(in new configuration). For i<k-2 it also can't be true, because if at least i+2 numbers do not exceed i+1, then a_1 will be one of them. After doing operation only these numbers can be not greater than i, but a_1 will become bigger than i. So, there are no more than i + 1 numbers which are at most i, so configuration is indeed not critical. Note that all numbers decreased by one modulo k. Because we've shown that applying our operation to the \"minimum\" color leaves configuration noncritical, we can make some shifts before we get that a_1 \\equiv b_1 \\bmod k. From this will follow that a_i \\equiv b_i mod k for all i. Now, let's try to do the following: if the configuration is critical and a_{max} > a_{min}+k, add k to a_{min} and substract a_{max} by k. We still suppose that the array is sorted, so a_i \\ge i-1 and a_k > a_1 + k. Then let's make such sequence of operations: choose i = 1, \\ldots, k-1 in this order(it's easy to see that we can do it because a_i \\ge i - 1). Now we have such configuration: a_1 + 1, a_2 + 1, \\ldots, a_{k-1}+1, a_k - (k-1). Now, choose 1 one more time, so we get a_1+k, a_2, a_3, \\ldots, a_{k-1}, a_k-k. It's easy to see, that it's not critical. Indeed, for each i<k-1 no more than i+1 numbers in old configuration were not bigger than i. Note, that a_k wasn't in this list. k-2 numbers in array didn't change, a_1+k is surely not in this list and a_k-k>a_1, so number of integers not bigger than i will not become bigger. So, that's why we can substract k from maximum and add it to the minimum, if the difference between them is at least k+1, and configuration will remain critical. Let's do it as many times as possible. This process will stop, because sum of squares decreases: a_1^2 + a_k^2 > (a_1+k)^2 + (a_k-k)^2 \\iff 2k(a_k-a_1) > 2k^2 \\iff a_k - a_1 > k, which is true by assumption. So, at some moment we will get configuration whic lies at segment [T, T+k] for some T. Note, that for new a_i and b_i it's still true a_i \\equiv b_i \\bmod k, S\\le b_i\\le S + k-1, T\\le a_i \\le T + k, a_1 + a_2 + \\ldots a_k = b_1 + b_2 + \\ldots b_k. Let's show, that from this conditions a_i = b_i for all i. Indeed, in case S\\le T we get b_i \\le S+k-1 \\le T+k-1 \\le a_i+k-1, but a_i \\equiv b_i mod k, so b_i \\le a_i for all i. Because sum of a and b is equal, it follows a_i = b_i for all i. Also in other case, if S > T, a_i \\le T+k \\le S+k-1 \\le b_i + k-1, from what we still get a_i = b_i for all i. So, doing operations with a and backward operations with b we get equal configurations. It follows that b is reachable from a, the claim is proved. Now, it only remains to show how to count the number of such b from Claim 5. b_1, b_2, \\ldots, b_k should give remainders (a_1+t) \\bmod k, (a_2+t) \\bmod k, \\ldots, (a_k+t) \\bmod k for some t. We can calculate configurations with such remainders by the following way: remaining a_1 + a_2 + \\ldots + a_k - (a_1+t) \\bmod k - (a_2+t) \\bmod k - \\ldots - (a_k+t) \\bmod k are splitted in groups by k and are distributed in k elements in any way. So, that's why, for given t number of configurations(by stars and bars) is given by C^{\\frac{a_1 + a_2 + \\ldots + a_k - (a_1+t) \\bmod k - (a_2+t) \\bmod k - \\ldots - (a_k+t) \\bmod k}{k} + k-1}_{k-1}. Sum a_1 + a_2 + \\ldots + a_k - (a_1+t)\\bmod k - (a_2+t)\\bmod k - \\ldots - (a_k+t) \\bmod k can be calculated for t = 0, 1, \\ldots , k-1 in O(1), if we precalculate number of each remainder among a_1, a_2, \\ldots, a_k. That's why final complexity for each of the cases is O(n + k).",
    "code": "\"#pragma GCC optimize(\\\"O3\\\")\\n#include <bits/stdc++.h>\\nusing namespace std;\\ntypedef long double ld;\\ntypedef long long ll;\\nconst int mod = 998244353;\\n\\nint sum(int a, int b) {\\n    int s = a + b;\\n    if (s >= mod) s -= mod;\\n    return s;\\n}\\n\\nint sub(int a, int b) {\\n    int s = a - b;\\n    if (s < 0) s += mod;\\n    return s;\\n}\\n\\nint mult(int a, int b) {\\n    return (1LL * a * b) % mod;\\n}\\n\\nconst int maxN = (int)1e6 + 100;\\nint a[maxN];\\nint k;\\nint fact[maxN];\\nint inv[maxN];\\nint invfact[maxN];\\nint num[maxN];\\n\\nint cnk(int a, int b) {\\n    if (a < b) return 0;\\n    return mult(fact[a], mult(invfact[b], invfact[a - b]));\\n}\\n\\nvoid init() {\\n    fact[0] = invfact[0] = fact[1] = invfact[1] = inv[1] = 1;\\n    for (int i = 2; i < maxN; i++) {\\n        fact[i] = mult(fact[i - 1], i);\\n        inv[i] = mult(inv[mod % i], mod - mod / i);\\n        invfact[i] = mult(invfact[i - 1], inv[i]);\\n    }\\n}\\n\\nint add_val[maxN];\\n\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr);\\n    //freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    init();\\n    cin >> k;\\n    int S = 0;\\n    int S_res = 0;\\n    for (int i = 0; i < k; i++) {\\n        cin >> a[i];\\n        S += a[i];\\n        int res = a[i] % k;\\n        S_res += res;\\n        add_val[res + 1] += k;\\n    }\\n    for (int i = 0; i < k; i++) {\\n        num[a[i]]++;\\n    }\\n    for (int i = 1; i <= k; i++) num[i] += num[i - 1];\\n    bool fnd = false;\\n    int ans = 0;\\n    for (int moves = 1; moves < k; moves++) {\\n        if (num[moves - 1] >= moves + 1) {\\n            fnd = true;\\n            break;\\n        }\\n        int vals = moves - num[moves - 1];\\n        ans = sum(ans, cnk(vals + k - 1, vals));\\n    }\\n    if (fnd) {\\n        cout << sum(ans, 1);\\n        return 0;\\n    }\\n    int total = 0;\\n    for (int res = 0; res < k; res++) {\\n        if (res > 0) add_val[res] += add_val[res - 1];\\n        int have = (S - S_res - add_val[res] + res * k) / k;\\n        total = sum(total, cnk(have + k - 1, k - 1));\\n    }\\n    cout << total;\\n    return 0;\\n}\"",
    "tags": [
      "combinatorics"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1189",
    "index": "A",
    "title": "Keanu Reeves",
    "statement": "After playing Neo in the legendary \"Matrix\" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.\n\nLet's call a string consisting of only zeroes and ones \\textbf{good} if it contains \\textbf{different} numbers of zeroes and ones. For example, 1, 101, 0000 are good, while 01, 1001, and 111000 are not good.\n\nWe are given a string $s$ of length $n$ consisting of only zeroes and ones. We need to cut $s$ into \\textbf{minimal possible} number of substrings $s_1, s_2, \\ldots, s_k$ such that \\textbf{all} of them are good. More formally, we have to find \\textbf{minimal} by number of strings sequence of good strings $s_1, s_2, \\ldots, s_k$ such that their concatenation (joining) equals $s$, i.e. $s_1 + s_2 + \\dots + s_k = s$.\n\nFor example, cuttings 110010 into 110 and 010 or into 11 and 0010 are valid, as 110, 010, 11, 0010 are all good, and we can't cut 110010 to the smaller number of substrings as 110010 isn't good itself. At the same time, cutting of 110010 into 1100 and 10 isn't valid as both strings aren't good. Also, cutting of 110010 into 1, 1, 0010 isn't valid, as it isn't minimal, even though all $3$ strings are good.\n\nCan you help Keanu? We can show that the solution always exists. If there are multiple optimal answers, print any.",
    "tutorial": "If the string is good, then answer it's itself. Otherwise, there are at least two strings in answer, and we can print substring without its last symbol and its last symbol separately. Complexity O(n).",
    "code": "\"n = int(input())\\ns = input()\\nbal = 0\\nfor c in s:\\n    if c == '0':\\n        bal += 1\\n    else:\\n        bal -= 1\\nif bal != 0:\\n    print('1' + '\\\\n' + s)\\nelse:\\n    print('2' + \\\"\\\\n\\\" + s[0:-1] + \\\" \\\" + s[-1])\"",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1189",
    "index": "B",
    "title": "Number Circle",
    "statement": "You are given $n$ numbers $a_1, a_2, \\ldots, a_n$. Is it possible to arrange them in a circle in such a way that every number is \\textbf{strictly} less than the sum of its neighbors?\n\nFor example, for the array $[1, 4, 5, 6, 7, 8]$, the arrangement on the left is valid, while arrangement on the right is not, as $5\\ge 4 + 1$ and $8> 1 + 6$.",
    "tutorial": "Let's suppose that array is sorted. First of all, if a_n \\ge a_{n - 1} + a_{n - 2}, than the answer is - NO (because otherwise a_{n} is not smaller than sum of the neighbors). We claim, that in all other cases answer is - YES. One of the possible constructions (if the array is already sorted) is: a_{n - 2}, a_{n}, a_{n - 1}, a_{n - 4}, a_{n - 5}, \\ldots ,a_1 It's easy to see, that all numbers except a_n will have at least one neighbor which is not smaller than itself. Complexity O(nlog(n)).",
    "code": "\"n = int(input())\\na = list(map(int, input().split()))\\na.sort()\\nif a[n-1]>=a[n-2] + a[n-3]:\\n\\tprint(\\\"NO\\\")\\nelse:\\n    print(\\\"YES\\\")\\n    for i in range(n-1, -1, -2):\\n\\t    print(a[i], end = \\\" \\\")\\n    for i in range(n%2, n, 2):\\n\\t    print(a[i], end = \\\" \\\")\"",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1189",
    "index": "C",
    "title": "Candies!",
    "statement": "Consider a sequence of digits of length $2^k$ $[a_1, a_2, \\ldots, a_{2^k}]$. We perform the following operation with it: replace pairs $(a_{2i+1}, a_{2i+2})$ with $(a_{2i+1} + a_{2i+2})\\bmod 10$ for $0\\le i<2^{k-1}$. For every $i$ where $a_{2i+1} + a_{2i+2}\\ge 10$ we get a candy! As a result, we will get a sequence of length $2^{k-1}$.\n\nLess formally, we partition sequence of length $2^k$ into $2^{k-1}$ pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth $\\ldots$, the last pair consists of the ($2^k-1$)-th and ($2^k$)-th numbers. For every pair such that sum of numbers in it is at least $10$, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by $10$ (and don't change the order of the numbers).\n\nPerform this operation with a resulting array until it becomes of length $1$. Let $f([a_1, a_2, \\ldots, a_{2^k}])$ denote the number of candies we get in this process.\n\nFor example: if the starting sequence is $[8, 7, 3, 1, 7, 0, 9, 4]$ then:\n\nAfter the first operation the sequence becomes $[(8 + 7)\\bmod 10, (3 + 1)\\bmod 10, (7 + 0)\\bmod 10, (9 + 4)\\bmod 10]$ $=$ $[5, 4, 7, 3]$, and we get $2$ candies as $8 + 7 \\ge 10$ and $9 + 4 \\ge 10$.\n\nAfter the second operation the sequence becomes $[(5 + 4)\\bmod 10, (7 + 3)\\bmod 10]$ $=$ $[9, 0]$, and we get one more candy as $7 + 3 \\ge 10$.\n\nAfter the final operation sequence becomes $[(9 + 0) \\bmod 10]$ $=$ $[9]$.\n\nTherefore, $f([8, 7, 3, 1, 7, 0, 9, 4]) = 3$ as we got $3$ candies in total.\n\nYou are given a sequence of digits of length $n$ $s_1, s_2, \\ldots s_n$. You have to answer $q$ queries of the form $(l_i, r_i)$, where for $i$-th query you have to output $f([s_{l_i}, s_{l_i+1}, \\ldots, s_{r_i}])$. It is guaranteed that $r_i-l_i+1$ is of form $2^k$ for some nonnegative integer $k$.",
    "tutorial": "Solution 1 (magic) Claim: f([a_1, a_2, \\ldots, a_{2^k}]) = \\lfloor \\frac{a_1 + a_2 + \\ldots + a_{2^k}}{10} \\rfloor. Clearly, using it we can answer queries in O(1) if we create array prefsum, in which prefsum[i] = a_1 + \\ldots + a_i. Proof of claimImagine, that candy is equal to number 10. Then sum of all numbers doesn't change: when we replace (a, b) \\to ((a + b) \\bmod 10) we take 10 iff a + b exceeds (a + b) \\bmod 10. Also note, that sum of numbers-candies is divisible by 10 (because we take only tens). Then, in the end, the remaining digit is equal to the remainder of the division of the initial sum by 10, so the number of candies is equal to the quotient. Asymptotics is O(n + q). Solution 2 (dp) It's possible to solve the problem using dynamic programming. For each segment [s_l, s_{l+1}, \\ldots, s_r], length of which is a power of two, we will save pair - digit, which will remain and the number of candies, which we get for this segment. For segment of length 1 this pair is (s_l, 0). Note that there are at most \\log{n} different lengths of segments, and the number of segments with fixed length is at most n. It follows that there are at most n\\log{n} segments. Now solution is similar to building sparse table. We will calculate needed pairs for segments in the order of increasing of their length: firstly for segments of length 2, then for length 4, etc. It turns out that the answer for segment of length 2^k can be calculated from smaller segments in constant time! Indeed, to get pair (last digit, number of candies) for [s_l, s_{l+1}, \\ldots, s_{l + 2^k - 1}], it's sufficient to know, how many candies we got in segments [s_l, s_{l+1}, \\ldots, s_{l + 2^{k-1} - 1}], [s_{l+2^{k-1}}, s_{l+2^{k-1} + 1}, \\ldots, s_{l + 2^k - 1}], and also what digits dig_1, dig_2 were left last in this segments, then last digit on our segment is equal (dig_1 + dig_2)\\bmod 10, also if dig_1 + dig_2 \\ge 10, we get one more candy. So, transition for one segment is made in O(1), which gives asymptotics O(n\\log{n}).",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\n\\nint main() {\\n\\n    int n;\\n    cin>>n;\\n    vector<int> a(n);\\n    for (int i = 0; i<n; i++) cin>>a[i];\\n    \\n    vector<vector<pair<int, int>>> dp(20);\\n    int cur = 1;\\n    for (int i = 0; i<n; i++) dp[0].push_back(make_pair(a[i], 0));\\n    for (int deg = 1; deg<20; deg++)\\n    {\\n        cur*=2;\\n        for (int i = 0; i+cur<=n; i++) \\n        {\\n            int left1 = dp[deg-1][i].first;\\n            int left2 = dp[deg-1][i+cur/2].first;\\n            int candies1 = dp[deg-1][i].second;\\n            int candies2 = dp[deg-1][i+cur/2].second;\\n            int res_candies = candies1 + candies2;\\n            int res_left = (left1 + left2)%10;\\n            if (left1+left2>=10) res_candies++;\\n            dp[deg].push_back(make_pair(res_left, res_candies));\\n        }\\n    }\\n    int q;\\n    cin>>q;\\n    int l, r;\\n    for (int i = 0; i<q; i++)\\n    {\\n        cin>>l>>r;\\n        int len = (r-l+1);\\n        int deg = 0;\\n        while (len%2==0) {deg++; len/=2;}\\n        cout<<dp[deg][l-1].second<<endl;\\n    }\\n}\"",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1190",
    "index": "A",
    "title": "Tokitsukaze and Discard Items",
    "statement": "Recently, Tokitsukaze found an interesting game. Tokitsukaze had $n$ items at the beginning of this game. However, she thought there were too many items, so now she wants to discard $m$ ($1 \\le m \\le n$) special items of them.\n\nThese $n$ items are marked with indices from $1$ to $n$. In the beginning, the item with index $i$ is placed on the $i$-th position. Items are divided into several pages orderly, such that each page contains exactly $k$ positions and the last positions on the last page may be left empty.\n\nTokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.\n\n\\begin{center}\n{\\small Consider the first example from the statement: $n=10$, $m=4$, $k=5$, $p=[3, 5, 7, 10]$. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices $3$ and $5$. After, the first page remains to be special. It contains $[1, 2, 4, 6, 7]$, Tokitsukaze discards the special item with index $7$. After, the second page is special (since it is the first page containing a special item). It contains $[9, 10]$, Tokitsukaze discards the special item with index $10$.}\n\\end{center}\n\nTokitsukaze wants to know the number of operations she would do in total.",
    "tutorial": "The order of discarding is given, so we can simulate the process of discarding. In each time, we can calculate the page that contains the first special item that has not been discarded, and then locate all the special items that need to be discarded at one time. Repeat this process until all special items are discarded. Each time at least one item would be discarded, so the time complexity is $\\mathcal{O}(m)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int MAX=1e5+10;\nll p[MAX];\nint main()\n{\n\tll n,m,k;\n\tscanf(\"%lld%lld%lld\",&n,&m,&k);\n\tfor(int i=1;i<=m;i++) scanf(\"%lld\",&p[i]);\n\tint ans=0;\n\tint sum=0;\n\tint now=1;\n\twhile(now<=m)\n\t{\n\t\tll r=((p[now]-sum-1)/k+1)*k+sum;\n\t//\tcout<<\"r:\"<<r<<endl;\n\t\twhile(now<=m&&p[now]<=r)\n\t\t{\n\t\t\tsum++;\n\t\t\tnow++;\n\t\t}\n\t\tans++;\n\t}\n\tprintf(\"%d\\n\",ans);\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1190",
    "index": "B",
    "title": "Tokitsukaze, CSL and Stone Game",
    "statement": "Tokitsukaze and CSL are playing a little game of stones.\n\nIn the beginning, there are $n$ piles of stones, the $i$-th pile of which has $a_i$ stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?\n\nConsider an example: $n=3$ and sizes of piles are $a_1=2$, $a_2=3$, $a_3=0$. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be $[1, 3, 0]$ and it is a good move. But if she chooses the second pile then the state will be $[2, 2, 0]$ and she immediately loses. So the only good move for her is to choose the first pile.\n\nSupposing that both players always take their best moves and never make mistakes, who will win the game?\n\nNote that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.",
    "tutorial": "Unless the first player must lose after the first move, the numbers of stones in these piles should form a permutation obtained from $0$ to $(n - 1)$ in the end, in order to ensure that there are no two piles include the same number of stones. Let's use $cnt[x]$ to represent the number of piles which have exactly $x$ stones in the beginning. There are four cases that Tokitsukaze will lose after the first move: $cnt[0] > 1$; $cnt[x] > 2$ for some $x$; $cnt[x] > 1$ and $cnt[y] > 1$ for some $x$, $y$ ($x \\neq y$); $cnt[x] > 1$ and $cnt[x - 1] > 0$ for some $x$. If Tokitsukaze won't lose after the first move, then we only need to check the parity of the total number of stones that can be taken. By the way, if you don't want to discuss the above four cases, you can just enumerate her first move.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int maxn = (int)1e5 + 1;\nint n, a[maxn], c[3];\nvoid update(int x, int d) {\n\tstatic map<int, int> ctr;\n\tint &v = ctr[x];\n\t--c[min(v, 2)];\n\tv += d;\n\t++c[min(v, 2)];\n}\nint main() {\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; ++i) {\n\t\tscanf(\"%d\", a + i);\n\t\tupdate(a[i], 1);\n\t}\n\tbool chk = 0;\n\tfor(int i = 0; !chk && i < n; ++i)\n\t\tif(a[i]) {\n\t\t\tupdate(a[i], -1);\n\t\t\tupdate(a[i] - 1, 1);\n\t\t\tchk |= !c[2];\n\t\t\tupdate(a[i] - 1, -1);\n\t\t\tupdate(a[i], 1);\n\t\t}\n\tif(chk) {\n\t\tchk = 0;\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tchk ^= (a[i] + i) & 1;\n\t}\n\tputs(chk ? \"sjfnb\" : \"cslnb\");\n\treturn 0;\n}",
    "tags": [
      "games"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1190",
    "index": "C",
    "title": "Tokitsukaze and Duel",
    "statement": "\"Duel!\"\n\nBetting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.\n\nThere are $n$ cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly $k$ consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these $n$ cards face the same direction after one's move, the one who takes this move will win.\n\nPrincess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes.",
    "tutorial": "If a player can make a move from a situation to that situation again, this player will not lose. Except for some initial situations, one can move from almost every situation to itself. Based on these two conclusions, we can get a solution. If Tokitsukaze cannot win after her first move, she cannot win in the future. In this case, we can quickly check if $k$ is so limited that she cannot win. After her first move, it is possible that Quailty wins in the next move. If he cannot, in order to prevent failure, he can just leave the situation to his opponent by doing useless flipping and thus result in a draw. Therefore, we can check if no matter how Tokitsukaze moves, Quailty has no chance to win after his first move. It can be easily checked linearly if we do some precalculation and enumerate Tokitsukaze's first move. Alternatively, we can find and check the pattern of initial situations in which Quailty can win.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int MAXN=1000005;\nint n,k,T;\nint a[MAXN],sum[MAXN];\nint q_sum(int l,int r)\n{\n    if(l>r)return 0;\n    return sum[r]-sum[l-1];\n}\nbool check_fir()\n{\n    for(int i=1;i+k-1<=n;++i)\n    {\n        int lala=q_sum(1,i-1)+q_sum(i+k,n);\n        if(lala==0||lala+k==n)return true;\n    }\n    return false;\n}\nbool check_sec()\n{\n    if(k*2<n||k==1)return false;\n    int len=n-k-1;\n    for(int i=2;i<=len;++i)\n    {\n        if(a[i]!=a[i-1]||a[n-i+1]!=a[n-i+2])return false;\n    }\n    if(a[len]==a[len+1]||a[n-len]==a[n-len+1]||a[1]==a[n])return false;\n    return true;\n}\nint main()\n{\n    scanf(\"%d %d\",&n,&k);\n    for(int i=1;i<=n;++i)\n    {\n        scanf(\"%1d\",&a[i]);\n        sum[i]=sum[i-1]+a[i];\n    }\n    if(check_fir())\n    {\n        printf(\"tokitsukaze\\n\");\n    }\n    else\n    {\n        if(check_sec())\n        {\n            printf(\"quailty\\n\");\n        }\n        else\n        {\n            printf(\"once again\\n\");\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "games",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1190",
    "index": "D",
    "title": "Tokitsukaze and Strange Rectangle",
    "statement": "There are $n$ points on the plane, the $i$-th of which is at $(x_i, y_i)$. Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.\n\nThe strange area is enclosed by three lines, $x = l$, $y = a$ and $x = r$, as its left side, its bottom side and its right side respectively, where $l$, $r$ and $a$ can be any real numbers satisfying that $l < r$. The upper side of the area is boundless, which you can regard as a line parallel to the $x$-axis at infinity. The following figure shows a strange rectangular area.\n\nA point $(x_i, y_i)$ is in the strange rectangular area if and only if $l < x_i < r$ and $y_i > a$. For example, in the above figure, $p_1$ is in the area while $p_2$ is not.\n\nTokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.",
    "tutorial": "For each strange rectangular area and its corresponding set of points, we only need to focus on the lowest $y$-coordinate $yB$, the leftmost $x$-coordinate $xL$ and the rightmost $x$-coordinate $xR$ of points in this set. Different sets must have different $yB$, $xL$, $xR$, so we can count them by enumerating these values. Let's enumerate $yB$ first. Then, we need to list all the possible $x$-coordinates of points $(x_i, y_i)$ satisfying that $y_i \\geq yB$ and mark every possible $x'$ satisfying there is a point $(x', yB)$. By doing so, we can make sure when enumerating $xL$ and $xR$, the requirement for $yB$ is met as well. However, enumerating forcibly, which is in time complexity $\\mathcal{O}(n^3)$, is too slow to pass, so let's optimize the enumeration step by step. Let's pick and sort the points $(x'_1, yB), (x'_2, yB), \\ldots, (x'_m, yB)$ from left to right. Assuming that $x'_0 = 0$, and $(x'_j, yB)$ is the leftmost point of them that is in the chosen set, we can count the number of aforementioned different $x$-coordinates in ranges $[x'_{j - 1} + 1, x'_j]$ and $[x'_j, \\infty)$ and then count the number of possible pairs $(xL, xR)$ immediately. More specifically, let $cnt(l, r)$ be the number of different $x$-coordinates of points in the area $\\lbrace (x, y) | l \\leq x \\leq r, y \\geq yB \\rbrace$, and we know the number of possible pairs $(xL, xR)$ is $cnt(x'_{j - 1} + 1, x'_j) \\cdot cnt(x'_j, \\infty)$. After precalculating $c(1, x)$ for each $yB$, we can reduce the time complexity into $\\mathcal{O}(n^2)$. The very last step is using the trick of sweeping lines. We can enumerate $yB$ from highest to lowest, and during that process, use data structures to maintain possible $x$-coordinates. What we need to implement is to maintain a container, check if a coordinate is already in the container, add a coordinate to the container, and query the number of coordinates in a range. These requirements can be easily achieved by Fenwick tree, segment tree or others. With the last optimization, we can solve in time complexity $\\mathcal{O}(n \\log n)$. By the way, there also exist solutions using other approaches, such as divide and conquer.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n//priority_queue<int> q;\n//priority_queue<int,vector<int>, greater<int> > q;\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;\n\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> less_rbtree;\ntypedef tree<int, null_type, greater<int>, rb_tree_tag, tree_order_statistics_node_update> greater_rbtree;\n\ntypedef tree<pair<int,int>, null_type, less<pair<int,int> >, rb_tree_tag, tree_order_statistics_node_update> multi_less_rbtree;\ntypedef tree<pair<int,int>, null_type, greater<pair<int,int> >, rb_tree_tag, tree_order_statistics_node_update> multi_greater_rbtree;\nconst int MAXN=300005;\nless_rbtree div_tree;\nlong long ans;\nstruct node\n{\n    int x,y;\n}p[MAXN],temp[MAXN];\nint n;\nbool cmp1(const node & A,const node & B)\n{\n    return A.x<B.x;\n}\nbool cmp2(const node & A,const node & B)\n{\n    if(A.y!=B.y)return A.y>B.y;\n    return A.x<B.x;\n}\nvoid div_algorithm(int l,int r)\n{\n    if(l>r)return;\n    div_tree.clear();\n    for(int i=l;i<=r;++i)\n    {\n        temp[i]=p[i];\n    }\n    int mid_line=p[(l+r)>>1].x;\n    long long preans=ans;\n    int lpos=-1,rpos=-1;\n    sort(temp+l,temp+r+1,cmp2);\n    for(int i=l;i<=r;++i)\n    {\n        div_tree.insert(temp[i].x);\n        if(temp[i].x<=mid_line)\n        {\n            if(lpos==-1||lpos<temp[i].x)\n            {\n                lpos=temp[i].x;\n            }\n        }\n        if(temp[i].x>=mid_line)\n        {\n            if(rpos==-1||rpos>temp[i].x)\n            {\n                rpos=temp[i].x;\n            }\n        }\n        if(i==r||temp[i+1].y!=temp[i].y)\n        {\n\n            long long lsum=div_tree.order_of_key(lpos+1);\n            long long Lsum=div_tree.order_of_key(mid_line+1);\n            long long rsum=div_tree.size()-div_tree.order_of_key(rpos);\n            long long Rsum=div_tree.size()-div_tree.order_of_key(mid_line);\n            if(lpos==-1)\n            {\n                ans+=Lsum*rsum;\n            }\n            else if(rpos==-1)\n            {\n                ans+=lsum*Rsum;\n            }\n            else\n            {\n                ans+=lsum*Rsum+Lsum*rsum-lsum*rsum;\n            }\n            lpos=-1;\n            rpos=-1;\n        }\n    }\n    int pin1=l,pin2=r;\n    while(p[pin1].x!=mid_line)++pin1;\n    while(p[pin2].x!=mid_line)--pin2;\n    div_algorithm(l,pin1-1);\n    div_algorithm(pin2+1,r);\n}\nint main()\n{\n    scanf(\"%d\",&n);\n    for(int i=1;i<=n;++i)\n    {\n        scanf(\"%d %d\",&p[i].x,&p[i].y);\n    }\n    sort(p+1,p+1+n,cmp1);\n    div_algorithm(1,n);\n    printf(\"%I64d\\n\",ans);\n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "sortings",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1190",
    "index": "E",
    "title": "Tokitsukaze and Explosion",
    "statement": "Tokitsukaze and her friends are trying to infiltrate a secret base built by Claris. However, Claris has been aware of that and set a bomb which is going to explode in a minute. Although they try to escape, they have no place to go after they find that the door has been locked.\n\nAt this very moment, CJB, Father of Tokitsukaze comes. With his magical power given by Ereshkigal, the goddess of the underworld, CJB is able to set $m$ barriers to protect them from the explosion. Formally, let's build a Cartesian coordinate system on the plane and assume the bomb is at $O(0, 0)$. There are $n$ persons in Tokitsukaze's crew, the $i$-th one of whom is at $P_i(X_i, Y_i)$. Every barrier can be considered as a line with infinity length and they can intersect each other. For every person from Tokitsukaze's crew, there must be at least one barrier separating the bomb and him, which means the line between the bomb and him intersects with at least one barrier. In this definition, if there exists a person standing at the position of the bomb, any line through $O(0, 0)$ will satisfy the requirement.\n\nAlthough CJB is very powerful, he still wants his barriers to be as far from the bomb as possible, in order to conserve his energy. Please help him calculate the maximum distance between the bomb and the closest barrier while all of Tokitsukaze's crew are safe.",
    "tutorial": "It is obvious that we can binary search the answer because we can pull any line closer to $O$ and the situation won't change. Applying a binary search, we focus on if it is possible to set $m$ barriers with the same distance to $O$ and meet the requirement. By doing so, we can draw a circle whose center is $O$ such that the closest point to $O$ on each barrier is on the circumference. Then it becomes a classic problem - for each barrier we can get the angle range of its closest point on the circle, and we have to choose at most $m$ points on the circle to ensure that there is at least one point within each range. This kind of greedy trick is very simple on a sequence. As to ranges on a sequence, you only have to sort all ranges in increasing order of left endpoint and take every necessary right endpoint. As to ranges on a circle, you can enumerate a position to break the circle into a sequence. But if you enumerate as the same way on the sequence, the time complexity will be $\\mathcal{O}(n^2)$ which is not enough. Instead, we can double and extend these ranges into $2 n$ ranges and then regard them as on a sequence. We can do some precalculation, such as if we want to choose a point to cover the $i$-th sorted range and other ranges in its right as many as possible, what is the next range that we cannot cover. Let's denote that as $f[i][0]$, and then we can calculate the next range after $2^p$ repeated steps from the $i$-th range as $f[i][p]$, which can be obtained from $f[f[i][p - 1]][p - 1]$. After preparation, we can enumerate the beginning position and use binary lifting method, each time in complexity $\\mathcal{O}(\\log m)$, to know that whether we can use $m$ steps to cover all the ranges. Therefore, the total time complexity can be $\\mathcal{O}(n \\log m \\log D)$, where $D$ is the precision requirement.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double db;\n\nconst int MAXN=100005;\nconst int DEP=18;\n\nvector<pair<int,int> > filter(int n,vector<pair<int,int> > &seg)\n{\n    vector<pair<int,int> > now;\n    for(auto &t:seg)\n    {\n        t.second=(t.second+n-1)%n;\n        int l=t.first,r=t.second;\n        if(l<=r)\n        {\n            now.push_back(make_pair(l,-r));\n            now.push_back(make_pair(l+n,-(r+n)));\n        }\n        else now.push_back(make_pair(l,-(r+n)));\n    }\n    sort(now.begin(),now.end());\n    vector<pair<int,int> > stk;\n    for(auto &t:now)\n    {\n        while(!stk.empty() && stk.back().second<=t.second)\n            stk.pop_back();\n        stk.push_back(t);\n    }\n    vector<pair<int,int> > res;\n    for(auto &t:stk)if(t.first<n)\n        res.push_back(make_pair(t.first,-t.second));\n    return res;\n}\nint go[MAXN<<1][DEP];\nint cal(int n,vector<pair<int,int> > &seg)\n{\n    seg=filter(n,seg);\n    int m=(int)seg.size();\n    if(m<2)return m;\n    for(int i=0;i<m;i++)\n    {\n        int l=seg[i].first,r=seg[i].second;\n        seg.push_back(make_pair(l+n,r+n));\n    }\n    for(int i=0;i<2*m;i++)\n        go[i][0]=lower_bound(seg.begin(),seg.end(),make_pair(seg[i].second+1,0))-seg.begin();\n    go[2*m][0]=2*m;\n    for(int j=1;j<DEP;j++)\n        for(int i=0;i<=2*m;i++)\n            go[i][j]=go[go[i][j-1]][j-1];\n    int res=m;\n    for(int i=0;i<m;i++)\n    {\n        int t=i,cnt=0;\n        for(int j=DEP-1;j>=0;j--)\n            if(go[t][j]<i+m)\n                t=go[t][j],cnt+=(1<<j);\n        if(res>cnt+1)res=cnt+1;\n    }\n    return res;\n}\n\nconst db PI=acos(-1.0);\nll x[MAXN],y[MAXN];\ndb dis[MAXN],ang[MAXN],angl[MAXN],angr[MAXN],anga[MAXN<<1];\n\nbool check(int n,int m,db r)\n{\n    for(int i=0;i<n;i++)\n    {\n        db t=acos(min(1.0L,r/dis[i]));\n        angl[i]=ang[i]-t,angr[i]=ang[i]+t;\n        if(angl[i]<0)angl[i]+=2*PI;\n        if(angr[i]>=2*PI)angr[i]-=2*PI;\n        anga[i<<1]=angl[i],anga[i<<1|1]=angr[i];\n    }\n    sort(anga,anga+2*n);\n    int k=unique(anga,anga+2*n)-anga;\n    vector<pair<int,int> > seg;\n    for(int i=0;i<n;i++)\n    {\n        int l=lower_bound(anga,anga+k,angl[i])-anga;\n        int r=lower_bound(anga,anga+k,angr[i])-anga;\n        seg.push_back({l,r});\n    }\n    return cal(k,seg)<=m;\n}\n\nint main()\n{\n    int n,m;\n    scanf(\"%d%d\",&n,&m);\n    for(int i=0;i<n;i++)\n        scanf(\"%lld%lld\",&x[i],&y[i]);\n    db md=1e7;\n    for(int i=0;i<n;i++)\n    {\n        dis[i]=sqrtl(x[i]*x[i]+y[i]*y[i]);\n        ang[i]=atan2(y[i],x[i]);\n        if(ang[i]<0)ang[i]+=2*PI;\n        md=min(md,dis[i]);\n    }\n    if(md<1e-7)return 0*printf(\"%.12Lf\\n\",0.0L);\n    db tl=0,tr=1;\n    while(tr<md && check(n,m,tr))\n        tl=tr,tr=min(md,2*tr);\n    for(int _=0;_<25;_++)\n    {\n        db tm=(tl+tr)/2;\n        if(check(n,m,tm))tl=tm;\n        else tr=tm;\n    }\n    return 0*printf(\"%.12Lf\\n\",(tl+tr)/2);\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1190",
    "index": "F",
    "title": "Tokitsukaze and Powers",
    "statement": "Tokitsukaze is playing a room escape game designed by SkywalkerT. In this game, she needs to find out hidden clues in the room to reveal a way to escape.\n\nAfter a while, she realizes that the only way to run away is to open the digital door lock since she accidentally went into a secret compartment and found some clues, which can be interpreted as:\n\n- Only when you enter $n$ possible different passwords can you open the door;\n- Passwords must be integers ranged from $0$ to $(m - 1)$;\n- A password cannot be $x$ ($0 \\leq x < m$) if $x$ and $m$ are not \\textbf{coprime} (i.e. $x$ and $m$ have some common divisor greater than $1$);\n- A password cannot be $x$ ($0 \\leq x < m$) if there exist \\textbf{non-negative} integers $e$ and $k$ such that $p^e = k m + x$, where $p$ is a secret integer;\n- Any integer that doesn't break the above rules can be a password;\n- Several integers are hidden in the room, but only one of them can be $p$.\n\nFortunately, she finds that $n$ and $m$ are recorded in the lock. However, what makes Tokitsukaze frustrated is that she doesn't do well in math. Now that she has found an integer that is suspected to be $p$, she wants you to help her find out $n$ possible passwords, or determine the integer cannot be $p$.",
    "tutorial": "Firstly, let me briefly review this problem for you. Given integers $n$, $m$ and $p$ ($n > 0$, $m > 1$, $p \\neq 0$), we denote $S = \\lbrace x | x \\in \\mathbb{Z}, 0 \\leq x < m, \\gcd(m, x) = 1 \\rbrace$ and $T = \\lbrace p^e \\bmod m | e \\in \\mathbb{Z}, e \\geq 0 \\rbrace$, where $\\gcd(m, x)$ means the greatest common divisor of $m$ and $x$, and you are asked to pick up $n$ distinct integers from $(S - T)$, the set of elements in $S$ but not in $T$, or report that it is unachievable. Besides, there is an additional restriction, $m = q^k$ for a prime number $q$ and a positive integer $k$. It is not difficult to show $|S|$, the size of $S$, equals to $\\varphi(m) = m (1 - \\frac{1}{q})$. When $\\gcd(m, p) > 1$, there is only one element $p^0 \\bmod m = 1$ in $T$ which is coprime to $m$, so in that case, $|S - T| = \\varphi(m) - 1$. To output a solution, you can just enumerate the smallest integers and skip the integer $1$ and any multiples of $q$. In this process, you won't need to enumerate more than $(2 n + 1)$ integers, because $\\frac{n}{1 - \\frac{1}{q}} + 1 \\leq 2 n + 1$. When $\\gcd(m, p) = 1$, we can observe that $T \\subseteq S$. Let $|T|$ be $\\lambda$, and we may conclude from Euler's totient theorem that $\\lambda \\leq \\varphi(m)$, and even $\\lambda | \\varphi(m)$. When $n > \\varphi(m) - \\lambda$, there is no solution, so we need to calculate $\\lambda$ in order to determine the existence of solutions. To calculate $\\lambda$, you can just enumerate all the divisors of $\\varphi(m)$ and check them using Fast Power Algorithm, because the number of divisors is not too large due to the restrictions. Alternatively, you can do it more advanced and check more efficiently like the following. The above approach requires $\\mathcal{O}(\\log \\varphi(m))$ calls of Fast Power Algorithm. It is used more regularly when searching a random primitive root in modulo some integer. When implementing Fast Power Algorithm, you may notice an issue that the modular multiplication may not be easy to code, when the 128-bit integer operations are not directly provided on this platform. In a precise way, you can implement another like Fast Multiplying Algorithm, though it is a bit slow. But if you believe you are lucky enough and you prefer using C/C++, you can try the following code in a convenient way. No matter what approach you used, the factorization of $(q - 1)$ is inevitable, so the problem requires you to factorize a relatively large number (less than $10^{18}$) a bit quickly. For example, you can use Pollard's Rho Algorithm with Miller-Rabin Primality Test. By Birthday Paradox, which is a heuristic claim, when $x$ is not a prime, Pollard's Rho Algorithm can split $x$ into $u \\cdot v$ in $\\mathcal{O}(\\sqrt{\\min(u, v)}) = \\mathcal{O}(x^{1 / 4})$ iterations. By the way, you can obtain $q$ from $m$ by enumerating possible $k$ from large to small, instead of factorization. Let's go back to the case that $\\gcd(m, p) = 1$ and $n \\leq \\varphi(m) - \\lambda$. When any solution exists, we can observe that $\\varphi(m) - \\lambda \\geq \\frac{\\varphi(m)}{2}$, so there may exist some solutions based on random distribution. That is, if you are able to check whether an integer is in $T$ or not, you can roughly pick $2 n$ integers in $S$ and check them. One approach is like the mechanism built in the problem checker, but as space is limited, I would not expend it at here. One thing you should be aware of is that you can't pick them without checking, as the probability of failure may be so large, like $\\frac{1}{2}$. Moreover, you can't use Baby-Step-Giant-Step algorithm since its time complexity $\\mathcal{O}(\\sqrt{n m})$ is too slow. If there exists at least one primitive root in modulo $m$, then we can construct the output integers. Since a primitive root $g$ can represent $S$ as $\\lbrace g^e \\bmod m | e \\in \\mathbb{Z}, 0 \\leq e < \\varphi(m) \\rbrace$, we can reduce the problem into something about modular equation that only concerns the exponents. As the number of primitive root in modulo $m$ is $\\varphi(\\varphi(m))$, if the root exists, we can get a random primitive root easily. Now let's assume we find a primitive root $g$ and $p \\equiv g^u \\pmod{m}$. An integer $(g^v \\bmod m)$ is in $T$ if and only if the equation $e u \\equiv v \\pmod{\\varphi(m)}$ has a solution of $e$. It is easy to show, when $\\gcd(\\varphi(m), u) | v$, a solution of $e$ always exists, so the construction is quite straightforward. The only case we left is when no primitive root exists in modulo $m$, which occurs when $m = 2^k$, $k \\geq 3$. In this case, we cannot represent all the elements in $S$ as non-negative integer powers of one specific number, but we can find a pseudo-primitive root $g'$ to use its powers to represent all the elements in the form of $(4 t + 1)$ in $S$ (as the group $(S, \\times_m)$, also known as $(\\mathbb{Z}/m\\mathbb{Z})^{\\times}$, is isomorphic to a direct product of cyclic groups, $\\mathrm{C}_2 \\times \\mathrm{C}_{2^{k - 2}}$). Besides, $\\lbrace m - ({g'}^{e} \\bmod m) | e \\in \\mathbb{Z}, 0 \\leq e < 2^{k - 2} \\rbrace$ can represent the rest numbers (in the form of $(4 t + 3)$) in $S$. As the product of two integers in the form of $(4 t + 3)$ is in the form of $(4 t + 1)$, we can discuss the parity of $e$ in expression $(p^e \\bmod m)$ and check if an integer is in $T$, so the construction could work after a little modification. By the way, there exist many different construction methods for this case. In summary, to solve this problem, we need to factorize $\\varphi(m)$, calculate the order of $p$ in modulo $m$, find a primitive root $g$ (or a pseudo-primitive root $g'$) in modulo $m$ and enumerate some small integers (values or exponents) to construct a solution. Time complexity: $\\mathcal{O}((m^{1 / 4} + n) M(m))$, where $M(m)$ means the cost of one multiplication modulo $m$. Some slow solutions are accepted as well.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\n\ninline ll mul_mod(ll a, ll b, ll m)\n{\n    a=(a%m+m)%m,b=(b%m+m)%m;\n    return ((a*b-(ll)(1.0L*a/m*b+0.5L)*m)%m+m)%m;\n}\ninline ll pow_mod(ll a,ll k,ll m)\n{\n    ll res=1;\n    while(k)\n    {\n        if(k&1)res=mul_mod(res,a,m);\n        a=mul_mod(a,a,m);\n        k>>=1;\n    }\n    return res;\n}\n\nbool strong_pseudo_primetest(ll n,int b)\n{\n    ll n2=n-1,res;\n    int s=0;\n    while(n2%2==0)n2>>=1,s++;\n    res=pow_mod(b,n2,n);\n    if((res==1)|| (res==n-1))return 1;\n    s--;\n    while(s>=0)\n    {\n        res=mul_mod(res,res,n);\n        if(res==n-1)return 1;\n        s--;\n    }\n    return 0;\n}\nbool is_prime(ll n)\n{\n    static ll testNum[]={2,3,5,7,11,13,17,19,23,29,31,37};\n    static ll lim[]={4,0,1373653LL,25326001LL,25000000000LL,2152302898747LL,3474749660383LL,341550071728321LL,0,0,0,0};\n    if(n<2 || n==3215031751LL)return 0;\n    for(int i=0;i<12;i++)\n    {\n        if(n<lim[i])return 1;\n        if(!strong_pseudo_primetest(n,testNum[i]))return 0;\n    }\n    return 1;\n}\n\ninline ll func(ll x,ll n)\n{\n    return (mul_mod(x,x,n)+1)%n;\n}\nll pollard(ll n)\n{\n    if(is_prime(n))return n;\n    if(~n&1)return 2;\n    for(int i=1;i<20;i++)\n    {\n        ll x=i,y=func(x,n),p=__gcd(y-x,n);\n        while(p==1)x=func(x,n),y=func(func(y,n),n),p=__gcd((y-x+n)%n,n)%n;\n        if(p==0 || p==n)continue;\n        return p;\n    }\n    return 1;\n}\nvector<ll> factor(ll n)\n{\n    if(n==1)return {};\n    ll x=pollard(n);\n    if(x==n)return {n};\n    vector<ll> res=factor(x);\n    vector<ll> t=factor(n/x);\n    res.insert(res.end(),t.begin(),t.end());\n    return res;\n}\n\nvector<ll> solve_easy(int n,ll m)\n{\n    vector<ll> res;\n    for(ll i=2;i<m && (int)res.size()<n;i++)\n        if(__gcd(i,m)==1)res.push_back(i);\n    return res;\n}\n\nbool dfs_sol(int i,int k,ull x,ull p,ull t)\n{\n    if(i>k)return 1;\n    ull mask=(1ULL<<i)-1;\n    if((t&mask)==(x&mask) && dfs_sol(i+1,k,x,p*p,t))return 1;\n    if(((t*p)&mask)==(x&mask) && dfs_sol(i+1,k,x,p*p,t*p))return 1;\n    return 0;\n}\nvector<ll> solve_even(int n,ll m,ll p,int k)///m=2^k\n{\n    vector<ll> res;\n    for(ll i=3;i<m && (int)res.size()<n;i+=2)\n        if(!dfs_sol(3,k,i,p,1))res.push_back(i);\n    return res;\n}\n\nvoid dfs_fac(int dep,ll val,vector<pair<ll,int> > &pcnt,vector<ll> &fac)\n{\n    if(dep==(int)pcnt.size())\n    {\n        fac.push_back(val);\n        return;\n    }\n    for(int i=0;i<=pcnt[dep].second;i++)\n    {\n        dfs_fac(dep+1,val,pcnt,fac);\n        val*=pcnt[dep].first;\n    }\n}\nvector<ll> solve_root(int n,ll m,ll p,vector<ll> pm)\n{\n    ll phi=m/pm[0]*(pm[0]-1);\n    vector<ll> pphi=factor(phi);\n    sort(pphi.begin(),pphi.end());\n    vector<pair<ll,int> > pcnt;\n    for(int i=0,j=0;i<(int)pphi.size();i=j)\n    {\n        while(j<(int)pphi.size() && pphi[i]==pphi[j])j++;\n        pcnt.push_back({pphi[i],j-i});\n    }\n    pphi.erase(unique(pphi.begin(),pphi.end()),pphi.end());\n    vector<ll> fac;\n    dfs_fac(0,1,pcnt,fac);\n    ll pmr=0;\n    while(++pmr)\n    {\n        bool isok=(__gcd(pmr,m)==1);\n        for(int i=0;i<(int)pphi.size() && isok;i++)\n            isok&=(pow_mod(pmr,phi/pphi[i],m)>1);\n        if(isok)break;\n    }\n    ll len=phi;\n    for(auto &t:fac)\n        if(pow_mod(p,t,m)==1)\n            len=min(len,t);\n    if(len==phi)return {};\n    vector<ll> res;\n    for(ll i=0;i<phi && (int)res.size()<n;i++)\n        if(i%(phi/len))res.push_back(pow_mod(pmr,i,m));\n    return res;\n}\n\nint main()\n{\n    int n;\n    ll m,p;\n    scanf(\"%d%lld%lld\",&n,&m,&p);\n    vector<ll> res;\n    if(__gcd(m,p)>1)\n        res=solve_easy(n,m);\n    else\n    {\n        vector<ll> pm=factor(m);\n        if(pm[0]==2 && (int)pm.size()>2)\n            res=solve_even(n,m,p,(int)pm.size());\n        else\n            res=solve_root(n,m,p,pm);\n    }\n    if((int)res.size()<n)\n        printf(\"-1\\n\");\n    else for(int i=0;i<n;i++)\n        printf(\"%lld%c\",res[i],\" \\n\"[i==n-1]);\n    return 0;\n}",
    "tags": [
      "number theory",
      "probabilities"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1191",
    "index": "A",
    "title": "Tokitsukaze and Enhancement",
    "statement": "Tokitsukaze is one of the characters in the game \"Kantai Collection\". In this game, every character has a common attribute — health points, shortened to HP.\n\nIn general, different values of HP are grouped into $4$ categories:\n\n- Category $A$ if HP is in the form of $(4 n + 1)$, that is, when divided by $4$, the remainder is $1$;\n- Category $B$ if HP is in the form of $(4 n + 3)$, that is, when divided by $4$, the remainder is $3$;\n- Category $C$ if HP is in the form of $(4 n + 2)$, that is, when divided by $4$, the remainder is $2$;\n- Category $D$ if HP is in the form of $4 n$, that is, when divided by $4$, the remainder is $0$.\n\nThe above-mentioned $n$ can be any integer.\n\nThese $4$ categories ordered from highest to lowest as $A > B > C > D$, which means category $A$ is the highest and category $D$ is the lowest.\n\nWhile playing the game, players can increase the HP of the character. Now, Tokitsukaze wants you to increase her HP by at most $2$ (that is, either by $0$, $1$ or $2$). How much should she increase her HP so that it has the highest possible category?",
    "tutorial": "Just enumerating the increment can pass. However, by increasing at most $2$ points, the value of her HP can always become an odd number, and thus the highest possible level is either $A$ or $B$. We can just solve case by case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n\tint x;\n\tcin>>x;\n\tif(x%4==0) puts(\"1 A\");\n\telse if(x%4==1) puts(\"0 A\");\n\telse if(x%4==2) puts(\"1 B\");\n\telse if(x%4==3) puts(\"2 A\");\n\treturn 0;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "1191",
    "index": "B",
    "title": "Tokitsukaze and Mahjong",
    "statement": "Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (\\textbf{manzu}, \\textbf{pinzu} or \\textbf{souzu}) and a number (a digit ranged from $1$ to $9$). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, $\\ldots$, 9m, 1p, 2p, $\\ldots$, 9p, 1s, 2s, $\\ldots$, 9s.\n\nIn order to win the game, she must have at least one \\textbf{mentsu} (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.\n\nDo you know the minimum number of extra suited tiles she needs to draw so that she can win?\n\nHere are some useful definitions in this game:\n\n- A \\textbf{mentsu}, also known as meld, is formed by a \\textbf{koutsu} or a \\textbf{shuntsu};\n- A \\textbf{koutsu}, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a \\textbf{koutsu};\n- A \\textbf{shuntsu}, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a \\textbf{shuntsu}.\n\nSome examples:\n\n- [2m, 3p, 2s, 4m, 1s, 2s, 4s] — it contains no \\textbf{koutsu} or \\textbf{shuntsu}, so it includes no \\textbf{mentsu};\n- [4s, 3m, 3p, 4s, 5p, 4s, 5p] — it contains a \\textbf{koutsu}, [4s, 4s, 4s], but no \\textbf{shuntsu}, so it includes a \\textbf{mentsu};\n- [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] — it contains no \\textbf{koutsu} but a \\textbf{shuntsu}, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a \\textbf{mentsu}.\n\nNote that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.",
    "tutorial": "There are only two types of mentsus, so you can enumerate the mentsu you want her to form, and check the difference between that and those currently in her hand. Alternatively, you can find out that the answer is at most $2$, since she can draw two extra identical tiles which are the same as one of those in her hand. You may enumerate at most $1$ extra tile for her and check if it can contribute to a mentsu. If she can't, the answer will be $2$.",
    "code": "//#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\n \nusing namespace std;\n \n//defines\ntypedef long long ll;\ntypedef long double ld;\n#define TIME clock() * 1.0 / CLOCKS_PER_SEC\n#define prev _prev\n#define y0 y00\n \n//permanent constants\nconst ld pi = acos(-1.0);\nconst int day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\nconst int digarr[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};\nconst int dx[4] = {0, 1, 0, -1};\nconst int dy[4] = {1, 0, -1, 0};\nconst int dxo[8] = {-1, -1, -1, 0, 1, 1, 1, 0};\nconst int dyo[8] = {-1, 0, 1, 1, 1, 0, -1, -1};\nconst int alf = 26;\nconst int dig = 10;\nconst int two = 2;\nconst int th = 3;\nconst ll prost = 239;\nconst ll bt = 30;\nconst ld eps = 1e-7;\nconst ll INF = (ll)(1e18 + 239);\nconst int BIG = (int)(1e9 + 239);\nconst int MOD = 998244353;\nconst ll MOD2 = (ll)MOD * (ll)MOD;\n \n//random\nmt19937 rnd(239); //(chrono::high_resolution_clock::now().time_since_epoch().count());\n \n//constants\nconst int M = (int)(2e5 + 239);\nconst int N = (int)(2e3 + 239);\nconst int L = 20;\nconst int T = (1 << 20);\nconst int B = (int)sqrt(M);\nconst int X = 1e4 + 239;\n \nbool check(string a, string b, string c)\n{\n    if (a == b && b == c) return true;\n    if (a > b) swap(a, b);\n    if (b > c) swap(b, c);\n    if (a > b) swap(a, b);\n    if (a[1] == b[1] && b[1] == c[1])\n    {\n        if (a[0] + 1 == b[0] && b[0] + 1 == c[0])\n            return true;\n    }\n    return false;\n}\n \nint32_t main()\n{\n#ifdef ONPC\n    freopen(\"input.txt\", \"r\", stdin);\n#endif\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    string a, b, c;\n    cin >> a >> b >> c;\n    if (check(a, b, c))\n    {\n        cout << \"0\";\n        return 0;\n    }\n    vector<string> var;\n    for (int i = 1; i <= 9; i++)\n    {\n        string s = \"\";\n        s += (char)(i + '0');\n        var.push_back(s + \"m\");\n        var.push_back(s + \"p\");\n        var.push_back(s + \"s\");\n    }\n    for (string s : var)\n    {\n        if (check(s, a, b))\n        {\n            cout << \"1\";\n            return 0;\n        }\n        if (check(s, a, c))\n        {\n            cout << \"1\";\n            return 0;\n        }\n        if (check(s, b, c))\n        {\n            cout << \"1\";\n            return 0;\n        }\n    }\n    cout << \"2\";\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1194",
    "index": "A",
    "title": "Remove a Progression",
    "statement": "You have a list of numbers from $1$ to $n$ written from left to right on the blackboard.\n\nYou perform an algorithm consisting of several steps (steps are $1$-indexed). On the $i$-th step you wipe the $i$-th number (considering only \\textbf{remaining} numbers). You wipe the whole number (not one digit).\n\nWhen there are less than $i$ numbers remaining, you stop your algorithm.\n\nNow you wonder: what is the value of the $x$-th remaining number after the algorithm is stopped?",
    "tutorial": "After some simulation of the given algorithm (in your head, on paper or on a computer) we can realize that exactly all odd numbers are erased. So, all even numbers remain, and the answer is $2x$.",
    "code": "fun main(args: Array<String>) {\n    val T = readLine()!!.toInt()\n    for (t in 1..T) {\n        val (n, x) = readLine()!!.split(' ').map { it.toLong() }\n        println(x * 2)\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1194",
    "index": "B",
    "title": "Yet Another Crosses Problem",
    "statement": "You are given a picture consisting of $n$ rows and $m$ columns. Rows are numbered from $1$ to $n$ from the top to the bottom, columns are numbered from $1$ to $m$ from the left to the right. Each cell is painted either black or white.\n\nYou think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $x$ and $y$, where $1 \\le x \\le n$ and $1 \\le y \\le m$, such that \\textbf{all cells} in row $x$ and \\textbf{all cells} in column $y$ are painted black.\n\nFor examples, each of these pictures contain crosses:\n\nThe fourth picture contains 4 crosses: at $(1, 3)$, $(1, 5)$, $(3, 3)$ and $(3, 5)$.\n\nFollowing images don't contain crosses:\n\nYou have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.\n\nWhat is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?\n\nYou are also asked to answer multiple independent queries.",
    "tutorial": "Let's consider each cell as a center of a cross and take the fastest one to paint. Calculating each time naively will take $O(nm(n + m))$ overall, which is too slow. Notice how the answer for some cell $(x, y)$ can be represented as $cnt_{row}[x] + cnt_{column}[y] -$ ($1$ if $a[x][y]$ is white else $0$), where $cnt_{row}[i]$ is the number of white cells in row $i$ and $cnt_{column}[i]$ is the same for column $i$. The first two terms can be precalculated beforehand. Overall complexity: $O(nm)$ per query.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n\tint q;\n\tcin >> q;\n\tforn(_, q){\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tvector<string> s(n);\n\t\tforn(i, n)\n\t\t\tcin >> s[i];\n\t\tvector<int> cntn(n), cntm(m);\n\t\tforn(i, n) forn(j, m){\n\t\t\tcntn[i] += (s[i][j] == '.');\n\t\t\tcntm[j] += (s[i][j] == '.');\n\t\t}\n\t\tint ans = n + m;\n\t\tforn(i, n) forn(j, m){\n\t\t\tans = min(ans, cntn[i] + cntm[j] - (s[i][j] == '.'));\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1194",
    "index": "C",
    "title": "From S To T",
    "statement": "You are given three strings $s$, $t$ and $p$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.\n\nDuring each operation you choose any character from $p$, erase it from $p$ and insert it into string $s$ (you may insert this character anywhere you want: in the beginning of $s$, in the end or between any two consecutive characters).\n\nFor example, if $p$ is aba, and $s$ is de, then the following outcomes are possible (the character we erase from $p$ and insert into $s$ is highlighted):\n\n- \\textbf{a}ba $\\rightarrow$ ba, de $\\rightarrow$ \\textbf{a}de;\n- \\textbf{a}ba $\\rightarrow$ ba, de $\\rightarrow$ d\\textbf{a}e;\n- \\textbf{a}ba $\\rightarrow$ ba, de $\\rightarrow$ de\\textbf{a};\n- a\\textbf{b}a $\\rightarrow$ aa, de $\\rightarrow$ \\textbf{b}de;\n- a\\textbf{b}a $\\rightarrow$ aa, de $\\rightarrow$ d\\textbf{b}e;\n- a\\textbf{b}a $\\rightarrow$ aa, de $\\rightarrow$ de\\textbf{b};\n- ab\\textbf{a} $\\rightarrow$ ab, de $\\rightarrow$ \\textbf{a}de;\n- ab\\textbf{a} $\\rightarrow$ ab, de $\\rightarrow$ d\\textbf{a}e;\n- ab\\textbf{a} $\\rightarrow$ ab, de $\\rightarrow$ de\\textbf{a};\n\nYour goal is to perform several (maybe zero) operations so that $s$ becomes equal to $t$. Please determine whether it is possible.\n\nNote that you have to answer $q$ independent queries.",
    "tutorial": "If the answer exists then each element of string $s$ matches with some element of string $t$. Thereby string $s$ must be a subsequence of string $t$. Let $f(str, a)$ equal to the number of occurrences of the letter $a$ in the string $str$. Then for any letter $a$ condition $f(s, a) + f(p, a) \\ge f(t, a)$ must be hold. So the answer to the query is YES if following conditions hold: string $s$ is subsequence of string $t$; $f(s, a) + f(p, a) \\ge f(t, a)$ for any Latin latter $a$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint q;\nstring s, t, p;\nint cnt[30];\n\nint main() {\n\tcin >> q;\n\tfor(int iq = 0; iq < q; ++iq){\n\t\tcin >> s >> t >> p;\n\t\tmemset(cnt, 0, sizeof cnt);\n\t\tfor(auto x : p)\n\t\t\t++cnt[x - 'a'];\n\n\t\tbool ok = true;\n\t\tint is = 0, it = 0;\n\t\twhile(is < s.size()){\n\t\t\tif(it == t.size()){\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tif(s[is] == t[it]){\n\t\t\t\t++is, ++it;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t--cnt[t[it] - 'a'];\n\t\t\t++it;\n\t\t}\n        while(it < t.size()){\n            --cnt[t[it] - 'a'];\n\t\t\t++it;\n        }\n        \n\t\tif(*min_element(cnt, cnt + 30) < 0)\n\t\t\tok = false;\n\n\t\tif(ok) cout << \"YES\\n\";\n\t\telse cout << \"NO\\n\";\n\t}\t\t\n\treturn 0;\n}                             \t\n\n\n\n}                             \t\n\n\n",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1194",
    "index": "D",
    "title": "1-2-K Game",
    "statement": "Alice and Bob play a game. There is a paper strip which is divided into $n + 1$ cells numbered from left to right starting from $0$. There is a chip placed in the $n$-th cell (the last one).\n\nPlayers take turns, Alice is first. Each player during his or her turn has to move the chip $1$, $2$ or $k$ cells to the left (so, if the chip is currently in the cell $i$, the player can move it into cell $i - 1$, $i - 2$ or $i - k$). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it $k$ cells to the left if the current cell has number $i < k$. The player who can't make a move loses the game.\n\nWho wins if both participants play optimally?\n\nAlice and Bob would like to play several games, so you should determine the winner in each game.",
    "tutorial": "Let's determine for each cell whether it's winning or losing position (we can do it since the game is symmetric and doesn't depend on a player). The $0$-th cell is obviously losing, the $1$-st and $2$-nd ones is both winning, since we can move to the $0$-th cell and put our opponent in the losing position (here comes criterion: the position is winning if and only if there is a move to the losing position). If $k$ is large enough, then the $0$-th, $3$-rd, $6$-th, $9$-th... are losing. So here comes divisibility by $3$. If $k\\not\\equiv0\\:\\bmod3$ then this move doesn't change anything, since if $x\\equiv0{\\mathrm{~mod~}}3$ then $x-k\\not\\equiv0\\mod3$ so it's not the move to the losing position, so $x$ doesn't become the winning one. Otherwise, if $k\\equiv0{\\mathrm{~mod~}}3$ then the $k$-th positions becomes winning, but the $(k + 1)$-th cell is losing (all moves are to $(k - 1)$-th, $k$-th or $1$-st cells and all of them are winning). The $(k + 2)$-th and $(k + 3)$-th cells are winning and so on. In the end, we came up with cycle of length $k + 1$ where position divisible by $3$ except $k$ are losing. All we need to do is small case work.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n, k;\n\ninline bool read() {\n\tif(!(cin >> n >> k))\n\t\treturn false;\n\treturn true;\n}\n\nvoid solve() {\n\tbool win = true;\n\tif(k % 3 == 0) {\n\t\tint np = n % (k + 1);\n\t\tif(np % 3 == 0 && np != k)\n\t\t\twin = false;\n\t} else {\n\t\tint np = n % 3;\n\t\tif(np == 0)\n\t\t\twin = false;\n\t}\n\t\n\tputs(win ? \"Alice\" : \"Bob\");\n}\n\nint main(){\n\tint T; cin >> T;\n\twhile(T--) {\n\t\tread();\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "games",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1194",
    "index": "E",
    "title": "Count The Rectangles",
    "statement": "There are $n$ segments drawn on a plane; the $i$-th segment connects two points ($x_{i, 1}$, $y_{i, 1}$) and ($x_{i, 2}$, $y_{i, 2}$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $i \\in [1, n]$ either $x_{i, 1} = x_{i, 2}$ or $y_{i, 1} = y_{i, 2}$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.\n\nWe say that four segments having indices $h_1$, $h_2$, $v_1$ and $v_2$ such that $h_1 < h_2$ and $v_1 < v_2$ form a rectangle if the following conditions hold:\n\n- segments $h_1$ and $h_2$ are horizontal;\n- segments $v_1$ and $v_2$ are vertical;\n- segment $h_1$ intersects with segment $v_1$;\n- segment $h_2$ intersects with segment $v_1$;\n- segment $h_1$ intersects with segment $v_2$;\n- segment $h_2$ intersects with segment $v_2$.\n\nPlease calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $h_1 < h_2$ and $v_1 < v_2$ should hold.",
    "tutorial": "Let's iterate over the lower horizontal segment. Denote its coordinates as ($xl, yh$) and ($xr, yh$), where $xl < xr$. We call vertical segment ($x_{i, 1}$, $y_{i, 1}$), ($x_{i, 2}$, $y_{i, 2}$) good, if followings conditions holds: $xl \\le x_{i, 1} = x_{i, 2} \\le xr$; $min(y_{i, 1}, y_{i, 2}) \\le yh$. Now let's use the scanline method. At first, for each good vertical segment $i$ we increment the value of element in position $x_{i, 1}$ in some data structure (for example, Fenwick Tree). Next we will process two types of queries in order of increasing their y-coordinate: horizontal segments with coordinates ($x_{i, 1}$, $y_{i, 1}$), ($x_{i, 2}$, $y_{i, 2}$); upper point of some vertical segment with coordinates $(x_i, y_i)$. And if two events of different types have the same y-coordinate then the event of first type must be processed first. For event of first type we need to find sum on range $[x_{i, 1}, x_{i, 2}]$ ($x_{i, 1} < x_{i, 2}$) in our data structure. Let's denote this sum as $s$. Then we need to add $\\frac{s (s - 1)}{2}$ to the answer (because we have $s$ vertical segments which intersect with both fixed horizontal segments and we can choose two of them in so many ways). For event of second type we just need decrement the value of element in position $x_i$ in our data structure.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define mp make_pair\n\nconst int N = 10009;\nconst int INF = 1000000009;\n \nint n;\nvector <pair<int, int> > vs[N], hs[N];\nint f[N];\nvector <int> d[N];\n\nvoid upd(int pos, int x){\n\tfor(; pos < N; pos |= pos + 1)\n\t\tf[pos] += x;\n}\n\nint get(int pos){\n\tint res = 0;\n\tfor(; pos >= 0; pos = (pos & (pos + 1)) - 1)\n\t\tres += f[pos];\n\treturn res;\n}\n\nint get(int l, int r){\n\treturn get(r) - get(l - 1);\n}\n\nconst int D = 5000;\n\nint main() {\n\tcin >> n;\n\tfor(int i = 0; i < n; ++i){\n\t\tint x1, y1, x2, y2;\n\t\tcin >> x1 >> y1 >> x2 >> y2;\n\t\tx1 += D, y1 += D, x2 += D, y2 += D; \n\t\tif(y1 == y2) \n\t\t\ths[y1].push_back( mp(min(x1, x2), max(x1, x2)) );\t\n\t\telse \n\t\t\tvs[x1].push_back( mp(min(y1, y2), max(y1, y2)) );\t\n\t}\n\n\tlong long res = 0;\n\tfor(int y = 0; y < N; ++y) for(auto s : hs[y]){\n\t\tfor(int i = 0; i < N; ++i) d[i].clear();\n\t\tmemset(f, 0, sizeof f);\n\n\t\tint l = s.first, r = s.second;\n\t\tfor(int x = l; x <= r; ++x) for(auto s2 : vs[x])\n\t\t\tif(s2.first <= y && s2.second > y) {\n\t\t\t\td[s2.second].push_back(x);\n\t\t\t\tupd(x, 1);\n\t\t\t}\n\n\t\tfor(int y2 = y + 1; y2 < N; ++y2){\n\t\t\tfor(auto s2 : hs[y2]){\t\t\t\n\t\t\t\tint cur = get(s2.first, s2.second);\n\t\t\t\tres += cur * (cur - 1) / 2;\n\t\t\t}\n\t\t\tfor(auto x : d[y2]) upd(x, -1);\n\t\t}\n\t}\n\n\tcout << res << endl;\n\treturn 0;\n}                             \t\n\n\n\n",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "geometry",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1194",
    "index": "F",
    "title": "Crossword Expert",
    "statement": "Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only $T$ seconds after coming.\n\nFortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains $n$ Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number $t_i$ is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).\n\nAdilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either $t_i$ seconds or $t_i + 1$ seconds to solve the $i$-th crossword, equiprobably (with probability $\\frac{1}{2}$ he solves the crossword in exactly $t_i$ seconds, and with probability $\\frac{1}{2}$ he has to spend an additional second to finish the crossword). All these events are independent.\n\nAfter $T$ seconds pass (or after solving the last crossword, if he manages to do it in less than $T$ seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate $E$ — the expected number of crosswords he will be able to solve completely. Can you calculate it?\n\nRecall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as $E = \\sum \\limits_{i = 0}^{n} i p_i$, where $p_i$ is the probability that Adilbek will solve exactly $i$ crosswords.\n\nWe can represent $E$ as rational fraction $\\frac{P}{Q}$ with $Q > 0$. To give the answer, you should print $P \\cdot Q^{-1} \\bmod (10^9 + 7)$.",
    "tutorial": "Let's use (as usual) linearity of an expected value. $E = \\sum\\limits_{i = 1}^{n}{E(I(i))}$ where $I(i)$ is an indicator function and equal to $1$ iff Adilbek will be able to solve the $i$-th crossword. How to calculate $I(i)$? If $\\sum\\limits_{j = 1}^{i}{t_i} > T$ then $I(i)$ is always $0$. On the other hand, if $\\sum\\limits_{j = 1}^{i}{(t_i + 1)} = \\sum\\limits_{j = 1}^{i}{t_i} + i \\le T$ - $I(i)$ is always $1$. Otherwise, we need to calculate $E(I(i)) = P(i)$ - the needed probability. To calculate $P(i)$ we can iterate over $k$ - the number of crosswords among first $i$ ones which will require extra time. Obviously, if $k > T - \\sum\\limits_{j = 1}^{i}{t_i}$ then we don't have enough time to solve the $i$-th crossword, also $k \\le i$. Let's denote $m_i = \\min(T - \\sum\\limits_{j = 1}^{i}{t_i}, i)$. There are $\\binom{i}{k}$ ways to choose crosswords with extra time among all $2^i$ variants. So the final formula is following: $P(i) = \\frac{1}{2^i}\\sum\\limits_{k = 0}^{m_i}{\\binom{i}{k}}.$ The only problem is the efficiency. But we can find out several interesting properties. At first, $m_{i + 1} \\le m_i + 1$. The other one: since $\\binom{n}{k} + \\binom{n}{k + 1} = \\binom{n + 1}{k + 1}$, then $2 \\cdot \\sum\\limits_{k = 0}^{x}{\\binom{n}{k}} + \\binom{n}{x + 1} = \\sum\\limits_{k = 0}^{x + 1}{\\binom{n + 1}{k}}$. And this exactly the efficient way to transform $P(i) \\cdot 2^i$ to $P(i + 1) \\cdot 2^{i + 1}$: by multiplying and adding one coefficient we can transform the prefix sum of the $i$-th row to the prefix sum of the $i + 1$ row. And to reduce the length of the prefix sum we can just subtract unnecessary coefficients. In result, the total complexity is $O(n)$ (maybe with extra $\\log$ factor because of modular arithmetic).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n    return out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n    fore(i, 0, sz(v)) {\n        if(i) out << \" \";\n        out << v[i];\n    }\n    return out;\n}\n\nconst int MOD = int(1e9) + 7;\n\ninline int norm(int a) {\n    if(a >= MOD) a -= MOD;\n    if(a < 0) a += MOD;\n    return a;\n}\ninline int mul(int a, int b) {\n    return int(a * 1ll * b % MOD);\n}\ninline int binPow(int a, int k) {\n    int ans = 1;\n    while(k > 0) {\n        if(k & 1) ans = mul(ans, a);\n        a = mul(a, a);\n        k >>= 1;\n    }\n    return ans;\n}\ninline int inv(int a) {\n    return binPow(a, MOD - 2);\n}\n\nint n;\nli T;\nvector<li> t;\n\ninline bool read() {\n    if(!(cin >> n >> T))\n        return false;\n    t.resize(n);\n    fore(i, 0, n)\n        cin >> t[i];\n    return true;\n}\n\nvector<int> f, inf;\n\nint C(int n, li k) {\n    if(k > n || k < 0)\n        return 0;\n    return mul(f[n], mul(inf[k], inf[n - k]));\n}\n\ninline void solve() {\n    f.resize(n + 5);\n    inf.resize(n + 5);\n    f[0] = inf[0] = 1;\n    fore(i, 1, sz(f)) {\n        f[i] = mul(i, f[i - 1]);\n        inf[i] = mul(inf[i - 1], inv(i));\n    }\n\n    int sumC = 1;\n    li bd = T;\n    int pw2 = 1, i2 = (MOD + 1) / 2;\n\n    vector<int> p(n + 1, 0);\n    fore(i, 0, n) {\n        pw2 = mul(pw2, i2);\n\n        sumC = norm(mul(2, sumC) - C(i, bd));\n        li need = t[i];\n        if(bd > i + 1) {\n            li sub = min(bd - i - 1, need);\n            bd -= sub, need -= sub;\n        }\n        li rem = min(bd + 1, need);\n        fore(k, 0, rem)\n            sumC = norm(sumC - C(i + 1, bd - k));\n        bd -= rem;\n\n        p[i] = mul(sumC, pw2);\n    }\n\n    int ans = int(accumulate(p.begin(), p.end(), 0ll) % MOD);\n    cout << ans << endl;\n//    cerr << mul(ans, binPow(2, n)) << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    cout << fixed << setprecision(15);\n\n    if(read()) {\n        solve();\n\n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "number theory",
      "probabilities",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1194",
    "index": "G",
    "title": "Another Meme Problem",
    "statement": "Let's call a fraction $\\frac{x}{y}$ good if there exists at least one another fraction $\\frac{x'}{y'}$ such that $\\frac{x}{y} = \\frac{x'}{y'}$, $1 \\le x', y' \\le 9$, the digit denoting $x'$ is contained in the decimal representation of $x$, and the digit denoting $y'$ is contained in the decimal representation of $y$. For example, $\\frac{26}{13}$ is a good fraction, because $\\frac{26}{13} = \\frac{2}{1}$.\n\nYou are given an integer number $n$. Please calculate the number of good fractions $\\frac{x}{y}$ such that $1 \\le x \\le n$ and $1 \\le y \\le n$. The answer may be really large, so print it modulo $998244353$.",
    "tutorial": "Let's fix an irreducible fraction $\\frac{X}{Y}$ such that $1 \\le X, Y \\le 9$. Obviously, each good fraction is equal to exactly one of such irreducible fractions. So if we iterate on $X$ and $Y$, check that $gcd(X, Y) = 1$ and find the number of good fractions that are equal to $\\frac{X}{Y}$, we will solve the problem. Okay, suppose we fixed $X$ and $Y$. Any good fraction can be represented as $\\frac{zX}{zY}$, where $z$ is some positive integer. Let's try all possible values of $z$, and for them check whether they correspond to a good fraction. How do we try all values of $z$ without iterating on them? Let's construct the decimal representation of $z$ from the least significant digit to the most. As soon as we fix $k$ least significant digits of $z$, we know $k$ least significant digits of $zX$ and $zY$. So let's try to use digit DP to try all possible values of $z$. Which states do we have to consider? Of course, we need to know the number of digits we already placed, so that will be the first state. After we placed $k$ digits, we know first $k$ digits of the numerator of the fraction; but to get the value of digit $k + 1$, knowing only the value of the corresponding digit in $z$ is not enough: there could be some value carried over after multiplying already placed digits by $X$. For example, if $X = 3$, and we placed the first digit of $z$ and it is $7$, we know that the first (least significant) digit of $zX$ is $1$, and we know that after fixing the second digit of $z$ we should add $2$ to it to get the value of this digit in $zX$, since $2$ is carried over from the first digit. So, the second state of DP should represent the number that is carried over from the previous digit in the numerator, and the third state should do the same for the denominator. Okay, in order to know whether the fraction is good, we have to keep track of some digits in the numerator and denominator. If $\\frac{x'}{y'} = \\frac{X}{Y}$, $1 \\le x' \\le 9$ and $1 \\le y' \\le 9$, then we have to keep track of the digit representing $x'$ in the numerator and the digit representing $y'$ in the denominator. So we have two additional states that represent the masks of \"interesting\" digits we met in the numerator and in the denominator. The only thing that's left to check is that both $zX$ and $zY$ are not greater than $n$. Let's construct the decimal representation of $n$ and prepend it with some leading zeroes; and keep constructing the numerator and the denominator until they have the same number of digits as the decimal representation as $n$. Then we can compare the representation of, for example, numerator with the representation of $n$ as strings. Comparing can be done with the following technique: let's keep a flag denoting whether the number represented by the least significant digits of the numerator is less or equal than the number represented by the same digits from $n$. When we place another digit of the numerator, we can get the new value of this flag as follows: if new digit of the numerator is not equal to the corresponding digit of $n$, then the value of the flag is defined by comparing this pair of digits; otherwise the value of the flag is the same as it was without this new digit. Of course, we should do the same for the denominator. Okay, now we can actually start coding this DP: $dp[k][carry1][carry2][comp1][comp2][mask1][mask2]$ is the number of possible ways to put $k$ least significant digits in $z$ in such a way that: the value carried over to the next digit of the numerator is $carry1$ (and $carry2$ for the denominator); $comp1$ denotes whether the current numerator is less or equal to the number represented by $k$ least significant digits of $n$ ($comp2$ does the same for the denominator); $mask1$ denotes which \"interesting\" digits we already met in the numerator (of course, $mask2$ does the same for the denominator). If you are feeling confident in your programming abilities, you can just start implementing this DP on a seven-dimensional array. I was too afraid to do it (but, looking at participants' solutions, I realize that it sounds much more scary than it looks in the code), so I decided to write the model solution using a structure representing each state, and a map to store all these structures. This is a common technique: when a dynamic programming solution you come up with has some really complex states and transitions, it is sometimes better to use some self-implemented structures to define these states and store them in a map or a hashmap. Some advantages of this technique are: it's sometimes much easier to code (the code may be longer than the same solution with regular DP stored in a multi-dimensional array, but it's easier to write and understand this code); if most states are unreachable, they won't even appear in our map, so we skip them altogether; it is easy to add some optimizations related to reducing the number of states. For example, the number of different values for $mask1$ and $mask2$ may be too much, so we can use the following optimization: as soon as we find some pair of numbers in $mask1$ and $mask2$ that can represent $x'$ and $y'$, we can change these masks to some values that will mark that they are \"finished\" and stop updating them at all.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 105;\n\nint a[N];\nint n;\nint numPos[10], denPos[10];\nint num, den;\nconst int MOD = 998244353;\n\nstruct halfState\n{\n\tint carry;\n\tint mask;\n\tbool comp;\n\t\n\thalfState() {};\n\thalfState(int carry, int mask, bool comp) : carry(carry), mask(mask), comp(comp) {};\n};\n\nbool operator <(const halfState& x, const halfState& y)\n{\n\tif(x.carry != y.carry) return x.carry < y.carry;\n\tif(x.mask != y.mask) return x.mask < y.mask;\n\treturn x.comp < y.comp;\n}\n\nbool operator ==(const halfState& x, const halfState& y)\n{\n\treturn x.carry == y.carry && x.mask == y.mask && x.comp == y.comp;\n}\n\nbool operator !=(const halfState& x, const halfState& y)\n{\n\treturn x.carry != y.carry || x.mask != y.mask || x.comp != y.comp;\n}\n\nhalfState go(const halfState& s, int pos, int digit, bool isNum)\n{\n\tint newDigit = digit * (isNum ? num : den) + s.carry;\n\tint newCarry = newDigit / 10;\n\tnewDigit %= 10;\n\tint newMask = s.mask;\n\tint maskPos = (isNum ? numPos[newDigit] : denPos[newDigit]);\n\tif(maskPos != -1) newMask |= (1 << maskPos);\n\tbool newComp = (newDigit < a[pos]) || (newDigit == a[pos] && s.comp);\n\treturn halfState(newCarry, newMask, newComp);\n}\n\nstruct state\n{\n\thalfState numState;\n\thalfState denState;\n\t\n\tstate() {};\n\tstate(halfState numState, halfState denState) : numState(numState), denState(denState) {};\n\t\n\tvoid norm()\n\t{\n\t\tif(numState.mask & denState.mask)\n\t\t\tnumState.mask = denState.mask = 1;\n\t};\n\t\n\tbool valid()\n\t{\n\t\treturn bool(numState.mask & denState.mask) && numState.comp && denState.comp && (numState.carry == 0) && (denState.carry == 0);\n\t};\n};\n\nbool operator <(const state& x, const state& y)\n{\n\tif(x.numState != y.numState) return x.numState < y.numState;\n\treturn x.denState < y.denState;\n}\n\nstate go(const state& s, int pos, int digit)\n{\n\thalfState newNum = go(s.numState, pos, digit, true);\n\thalfState denNum = go(s.denState, pos, digit, false);\n\tstate res(newNum, denNum);\n\tres.norm();\n\treturn res;\n}\n\nint add(int x, int y)\n{\n\treturn (x + y) % MOD;\n}\n\nint ans = 0;\n\nvoid calcFixed(int x, int y)\n{\n\tnum = x;\n\tden = y;\n\tfor(int i = 0; i <= 9; i++)\n\t\tnumPos[i] = denPos[i] = -1;\n\tint cnt = 0;\n\tfor(int i = 1; i <= 9; i++)\n\t\tfor(int j = 1; j <= 9; j++)\n\t\t\tif(i * y == j * x)\n\t\t\t{\n\t\t\t\tnumPos[i] = denPos[j] = cnt++;\n\t\t\t}\n\tvector<map<state, int> > dp(102);\n\tdp[0][state(halfState(0, 0, true), halfState(0, 0, true))] = 1;\n\tfor(int i = 0; i <= 100; i++)\n\t\tfor(auto x : dp[i])\n\t\t{\n\t\t\tstate curState = x.first;\n\t\t\tint curCount = x.second;\n\t\t\tfor(int j = 0; j <= 9; j++)\n\t\t\t{\n\t\t\t\tstate newState = go(curState, i, j);\n\t\t\t\tdp[i + 1][newState] = add(dp[i + 1][newState], curCount);\n\t\t\t}\n\t\t}\n\tfor(auto x : dp[101])\n\t{\n\t\tstate curState = x.first;\n\t\tint curCount = x.second;\n\t\tif(curState.valid())\n\t\t\tans = add(ans, curCount);\n\t}\n}\n\nint main()\n{\n\tstring s;\n\tcin >> s;\n\tint len = s.size();\n\treverse(s.begin(), s.end());\n\tfor(int i = 0; i < len; i++)\n\t{\n\t\ta[i] = s[i] - '0';\n \t}\n \tfor(int i = 1; i <= 9; i++)\n \t\tfor(int j = 1; j <= 9; j++)\n \t\t\tif(__gcd(i, j) == 1)\n \t\t\t\tcalcFixed(i, j);\n \tcout << ans << endl;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1195",
    "index": "A",
    "title": "Drinks Choosing",
    "statement": "Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?\n\nThere are $n$ students living in a building, and for each of them the favorite drink $a_i$ is known. So you know $n$ integers $a_1, a_2, \\dots, a_n$, where $a_i$ ($1 \\le a_i \\le k$) is the type of the favorite drink of the $i$-th student. The drink types are numbered from $1$ to $k$.\n\nThere are infinite number of drink sets. Each set consists of \\textbf{exactly two} portions of the same drink. In other words, there are $k$ types of drink sets, the $j$-th type contains two portions of the drink $j$. The available number of sets of each of the $k$ types is infinite.\n\nYou know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $\\lceil \\frac{n}{2} \\rceil$, where $\\lceil x \\rceil$ is $x$ rounded up.\n\nAfter students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $n$ is odd then one portion will remain unused and the students' teacher will drink it.\n\nWhat is the maximum number of students that can get their favorite drink if $\\lceil \\frac{n}{2} \\rceil$ sets will be chosen optimally and students will distribute portions between themselves optimally?",
    "tutorial": "Let's take a look on a students. If two students have the same favorite drink, let's take one set with this drink. Let the number of such students (which we can satisfy as pairs) be $good$. Because the number of sets is $\\lceil\\frac{n}{2}\\rceil$ we always can do it. So there are students which are the only with their favorite drinks remain. It is obvious that if we take one set we can satisfy at most one student (and one of the others will gain not his favorite drink). Let the number of such students (which remain after satisfying pairs of students) be $bad$. Then the answer is $good + \\lceil\\frac{bad}{2}\\rceil$.",
    "code": "// Created by Nikolay Budin\n\n#ifdef LOCAL\n#  define _GLIBCXX_DEBUG\n#else\n#  define cerr __get_ce\n#endif\n#include <bits/stdc++.h>\n#define ff first\n#define ss second\n#define szof(x) ((int)x.size())\n\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef unsigned long long ull;\nint const INF = (int)1e9 + 1e3;\nll const INFL = (ll)1e18 + 1e6;\n#ifdef LOCAL\n\tmt19937 tw(9450189);\n#else\n\tmt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\nuniform_int_distribution<ll> ll_distr;\nll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; }\n\n\nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tmap<int, int> have;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint num;\n\t\tcin >> num;\n\t\thave[num]++;\n\t}\n\tint cnt = 0;\n\tint ans = 0;\n\tfor (pii p : have) {\n\t\tcnt += p.ss % 2;\n\t\tans += p.ss / 2 * 2;\n\t}\n\tans += (cnt + 1) / 2;\n\tcout << ans << \"\\n\";\n}\n\n\nint main() {\n#ifdef LOCAL\n\tauto start_time = clock();\n\tcerr << setprecision(3) << fixed;\n#endif\n\tcout << setprecision(15) << fixed;\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\n\tint test_count = 1;\n\t// cin >> test_count;\n\tfor (int test = 1; test <= test_count; ++test) {\n\t\tsolve();\n\t}\n\t\n#ifdef LOCAL\n\tauto end_time = clock();\n\tcerr << \"Execution time: \" << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << \" ms\\n\";\n#endif\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1195",
    "index": "B",
    "title": "Sport Mafia",
    "statement": "Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.\n\nFor the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs $n$ actions. The first action performed is to put a single candy into the box. For each of the remaining moves she can choose from two options:\n\n- the first option, in case the box contains at least one candy, is to take \\textbf{exactly one candy out and eat it}. This way the number of candies in the box decreased by $1$;\n- the second option is to put candies in the box. In this case, Alya will put $1$ more candy, than she put in the previous time.\n\nThus, if the box is empty, then it can only use the second option.\n\nFor example, one possible sequence of Alya's actions look as follows:\n\n- put one candy into the box;\n- put two candies into the box;\n- eat one candy from the box;\n- eat one candy from the box;\n- put three candies into the box;\n- eat one candy from the box;\n- put four candies into the box;\n- eat one candy from the box;\n- put five candies into the box;\n\nThis way she will perform $9$ actions, the number of candies at the end will be $11$, while Alya will eat $4$ candies in total.\n\nYou know the total number of actions $n$ and the number of candies at the end $k$. You need to find the total number of sweets Alya ate. That is the number of moves of the first option. It's guaranteed, that for the given $n$ and $k$ the answer always exists.\n\nPlease note, that during an action of the first option, Alya takes out and eats exactly one candy.",
    "tutorial": "In fact, we need to solve the following equation: $\\frac{x(x+1)}{2} - (n - x) = k$ and when we will find $x$ we need to print $n-x$ as the answer. $\\frac{x(x+1)}{2}$ is the number of candies Alya will put into the box with $x$ turns (sum of arithmetic progression). This equation can be solved mathematically. The only problem is getting the square root, it can be avoided with binary search or taking square root in non-integer numbers and checking some amount of integers in small range nearby the obtained root. The other solution is the binary search by $x$.",
    "code": "#include <iostream>\n#include <cmath>\n\nint main() {\n    long long n, k;\n    std::cin >> n >> k;\n    std::cout << static_cast<long long>(round(n + 1.5 - sqrt(2 * (n + k) + 2.75)));\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1195",
    "index": "C",
    "title": "Basketball Exercise",
    "statement": "Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $2 \\cdot n$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $n$ people in each row). Students are numbered from $1$ to $n$ in each row in order from left to right.\n\nNow Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one \\textbf{taken}) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $2n$ students (there are no additional constraints), and a team can consist of any number of students.\n\nDemid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.",
    "tutorial": "This is pretty standard dynamic programming problem. Let $dp_{i, 1}$ be the maximum total height of team members if the last student taken has the position $(i-1, 1)$, $dp_{i, 2}$ is the same but the last student taken has the position $(i-1, 2)$ and $dp_{i, 3}$ the same but we didn't take any student from position $i-1$. Transitions are pretty easy: $dp_{i, 1} = max(dp_{i-1, 2} + h_{i, 1}, dp_{i-1, 3} + h_{i, 1}, h_{i, 1})$; $dp_{i, 2} = max(dp_{i-1, 1} + h_{i, 2}, dp_{i-1, 3} + h_{i, 2}, h_{i, 2})$; $dp_{i, 3} = max(dp_{i-1, 1}, dp_{i-1, 2})$. This dynamic programming can be calculated almost without using memory because we need only the $i-1$-th row to calculate the $i$-th row of this dp. Moreover, we don't actually need $dp_{i, 3}$ if we will add transitions $dp_{i, 1} = max(dp_{i, 1}, dp_{i - 1, 1})$ and $dp_{i, 2} = max(dp_{i, 2}, dp_{i - 1, 2})$. These transition will change our dp a bit. Now $dp_{i, j}$ is the maximum total height of the team members if the last student taken has the position $(i-1,1)$ or less. The same with $dp_{i, 2}$. The answer is $max(dp_{n, 1}, dp_{n, 2})$. Time complexity: $O(n)$.",
    "code": "// Created by Nikolay Budin\n\n#ifdef LOCAL\n#  define _GLIBCXX_DEBUG\n#else\n#  define cerr __get_ce\n#endif\n#include <bits/stdc++.h>\n#define ff first\n#define ss second\n#define szof(x) ((int)x.size())\n\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef unsigned long long ull;\ntypedef pair<ll, ll> pll;\nint const INF = (int)1e9 + 1e3;\nll const INFL = (ll)1e18 + 1e6;\n#ifdef LOCAL\n\tmt19937 tw(9450189);\n#else\n\tmt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\nuniform_int_distribution<ll> ll_distr;\nll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; }\n\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<vector<int>> inp;\n\tfor (int i = 0; i < 2; ++i) {\n\t\tinp.push_back(vector<int>());\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tint num;\n\t\t\tcin >> num;\n\t\t\tinp[i].push_back(num);\n\t\t}\n\t}\n\n\tpll d = {0, 0};\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tpll next = {max(d.ff, d.ss + inp[0][i]), max(d.ss, d.ff + inp[1][i])};\n\t\td = next;\n\t}\n\n\tcout << max(d.ff, d.ss) << \"\\n\";\n}\n\n\nint main() {\n#ifdef LOCAL\n\tauto start_time = clock();\n\tcerr << setprecision(3) << fixed;\n#endif\n\tcout << setprecision(15) << fixed;\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\n\tint test_count = 1;\n\t// cin >> test_count;\n\tfor (int test = 1; test <= test_count; ++test) {\n\t\tsolve();\n\t}\n\t\n#ifdef LOCAL\n\tauto end_time = clock();\n\tcerr << \"Execution time: \" << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << \" ms\\n\";\n#endif\n}",
    "tags": [
      "dp"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1195",
    "index": "D1",
    "title": "Submarine in the Rybinsk Sea (easy edition)",
    "statement": "This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $a_1, a_2, \\dots, a_n$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.\n\nA team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.\n\nLet's denote a function that alternates digits of two numbers $f(a_1 a_2 \\dots a_{p - 1} a_p, b_1 b_2 \\dots b_{q - 1} b_q)$, where $a_1 \\dots a_p$ and $b_1 \\dots b_q$ are digits of two integers written in the decimal notation without leading zeros.\n\nIn other words, the function $f(x, y)$ alternately shuffles the digits of the numbers $x$ and $y$ by writing them from the lowest digits to the older ones, starting with the number $y$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.\n\nFor example: $$f(1111, 2222) = 12121212$$ $$f(7777, 888) = 7787878$$ $$f(33, 44444) = 4443434$$ $$f(555, 6) = 5556$$ $$f(111, 2222) = 2121212$$\n\nFormally,\n\n- if $p \\ge q$ then $f(a_1 \\dots a_p, b_1 \\dots b_q) = a_1 a_2 \\dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \\dots a_{p - 1} b_{q - 1} a_p b_q$;\n- if $p < q$ then $f(a_1 \\dots a_p, b_1 \\dots b_q) = b_1 b_2 \\dots b_{q - p} a_1 b_{q - p + 1} a_2 \\dots a_{p - 1} b_{q - 1} a_p b_q$.\n\nMishanya gives you an array consisting of $n$ integers $a_i$. \\textbf{All numbers in this array are of equal length (that is, they consist of the same number of digits).} Your task is to help students to calculate $\\sum_{i = 1}^{n}\\sum_{j = 1}^{n} f(a_i, a_j)$ modulo $998\\,244\\,353$.",
    "tutorial": "Let's take a look into some number $a = a_1, a_2, \\dots, a_{len}$, where $len$ is the length of each number in the array. We know that in $n$ cases it will be the first argument of the function $f(a, b)$ (where $b$ is some other number), and in $n$ cases it will be the second argument. What it means? It means that $a_1$ will have multiplier $10^{2len-1} \\cdot 10^{2len-2} \\cdot n$, $a_2$ will have multiplier $10^{2len-3} \\cdot 10^{2len-4} \\cdot n$, and so on. If we take a look closer, $a$ will add to the answer exactly $f(a, a) \\cdot n$. So the final answer is $n\\sum\\limits_{i=1}^{n} f(a_i, a_i)$. Don't forget about modulo and overflow (even $64$-bit datatype can overflow in this problem, because $f(10^9, 10^9)$ has $20$ digits in decimal notation).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int a, int b) {\n\ta += b;\n\tif (a >= MOD) a -= MOD;\n\tif (a < 0) a += MOD;\n\treturn a;\n}\n\nint mul(int a, int b) {\n\treturn a * 1ll * b % MOD;\n}\n\nint len;\nvector<int> pw10;\n\nint f(int a) {\n\tint pos = 0;\n\tint res = 0;\n\twhile (a > 0) {\n\t\tint cur = a % 10;\n\t\ta /= 10;\n\t\tres = add(res, mul(cur, pw10[2 * pos]));\n\t\tres = add(res, mul(cur, pw10[2 * pos + 1]));\n\t\t++pos;\n\t}\n\treturn res;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tpw10 = vector<int>(30);\n\tpw10[0] = 1;\n\tfor (int i = 1; i < 30; ++i) {\n\t\tpw10[i] = mul(pw10[i - 1], 10);\n\t}\n\t\n\tint n;\n\tcin >> n;\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint a;\n\t\tcin >> a;\n\t\tlen = to_string(a).size();\n\t\tans = add(ans, mul(n, f(a)));\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1195",
    "index": "D2",
    "title": "Submarine in the Rybinsk Sea (hard edition)",
    "statement": "This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $a_1, a_2, \\dots, a_n$.\n\nA team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.\n\nLet's denote a function that alternates digits of two numbers $f(a_1 a_2 \\dots a_{p - 1} a_p, b_1 b_2 \\dots b_{q - 1} b_q)$, where $a_1 \\dots a_p$ and $b_1 \\dots b_q$ are digits of two integers written in the decimal notation without leading zeros.\n\nIn other words, the function $f(x, y)$ alternately shuffles the digits of the numbers $x$ and $y$ by writing them from the lowest digits to the older ones, starting with the number $y$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.\n\nFor example: $$f(1111, 2222) = 12121212$$ $$f(7777, 888) = 7787878$$ $$f(33, 44444) = 4443434$$ $$f(555, 6) = 5556$$ $$f(111, 2222) = 2121212$$\n\nFormally,\n\n- if $p \\ge q$ then $f(a_1 \\dots a_p, b_1 \\dots b_q) = a_1 a_2 \\dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \\dots a_{p - 1} b_{q - 1} a_p b_q$;\n- if $p < q$ then $f(a_1 \\dots a_p, b_1 \\dots b_q) = b_1 b_2 \\dots b_{q - p} a_1 b_{q - p + 1} a_2 \\dots a_{p - 1} b_{q - 1} a_p b_q$.\n\nMishanya gives you an array consisting of $n$ integers $a_i$, your task is to help students to calculate $\\sum_{i = 1}^{n}\\sum_{j = 1}^{n} f(a_i, a_j)$ modulo $998\\,244\\,353$.",
    "tutorial": "Let $cnt_{len}$ be the number of $a_i$ with length $len$. We will calculate each number's contribution in the answer separately. When we calculate the contribution of the current number in the answer, let's iterate over all lengths $l$ from $1$ to $L$ where $L$ is the maximum length of some number in the array and add the following value to the answer: $cnt_{l} \\cdot (fl_{a_i, l} + fr_{a_i, l})$. The function $fl_{x, l}$ means that we merge the number $x$ with some (it does not matter) number of length $l$ and digits of $x$ will be on odd positions in the resulting number (except some leading digits which will be on odd and on even position as well). And the function $fr_{x, l}$ does almost the same thing but it counts digits of $x$ on even positions. Time complexity is $O(n)$ with the constant factor $L^2$.",
    "code": "// Created by Nikolay Budin\n\n#ifdef LOCAL\n#  define _GLIBCXX_DEBUG\n#else\n#  define cerr __get_ce\n#endif\n#include <bits/stdc++.h>\n#define ff first\n#define ss second\n#define szof(x) ((int)x.size())\n\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef unsigned long long ull;\nint const INF = (int)1e9 + 1e3;\nll const INFL = (ll)1e18 + 1e6;\n#ifdef LOCAL\n\tmt19937 tw(9450189);\n#else\n\tmt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\nuniform_int_distribution<ll> ll_distr;\nll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; }\n\nconst int MOD = 998244353;\n\nvoid add(int& a, int b) {\n\ta += b;\n\tif (a >= MOD) {\n\t\ta -= MOD;\n\t}\n}\n\nint sum(int a, int b) {\n\tadd(a, b);\n\treturn a;\n}\n\nint mult(int a, int b) {\n\treturn (ll) a * b % MOD;\n}\n\nint f(vector<int> const& a, int l) {\n\tint res = 0;\n\tint p = 1;\n\tfor (int i = 0; i < max(szof(a), l); ++i) {\n\t\tif (i < l) {\n\t\t\tp = mult(p, 10);\n\t\t}\n\t\tif (i < szof(a)) {\n\t\t\tadd(res, mult(a[i], p));\n\t\t\tp = mult(p, 10);\n\t\t}\n\t}\n\treturn res;\n}\n\nint f(int l, vector<int> const& b) {\n\tint res = 0;\n\tint p = 1;\n\tfor (int i = 0; i < max(l, szof(b)); ++i) {\n\t\tif (i < szof(b)) {\n\t\t\tadd(res, mult(b[i], p));\n\t\t\tp = mult(p, 10);\n\t\t}\n\t\tif (i < l) {\n\t\t\tp = mult(p, 10);\n\t\t}\n\t}\n\treturn res;\n}\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> arr;\n\tconst int MAXL = 11;\n\tvector<int> of_len(MAXL);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint num;\n\t\tcin >> num;\n\t\tarr.push_back(num);\n\t\tint l = 0;\n\t\tint tmp = num;\n\t\twhile (tmp) {\n\t\t\t++l;\n\t\t\ttmp /= 10;\n\t\t}\n\t\tof_len[l]++;\n\t}\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tvector<int> digits;\n\t\tint tmp = arr[i];\n\t\twhile (tmp) {\n\t\t\tdigits.push_back(tmp % 10);\n\t\t\ttmp /= 10;\n\t\t}\n\t\tfor (int l = 1; l < MAXL; ++l) {\n\t\t\tint sum = f(digits, l);\n\t\t\tadd(ans, mult(sum, of_len[l]));\n\n\n\t\t\tsum = f(l, digits);\n\t\t\tadd(ans, mult(sum, of_len[l]));\n\t\t}\n\t}\n\n\tcout << ans << \"\\n\";\n}\n\n\nint main() {\n#ifdef LOCAL\n\tauto start_time = clock();\n\tcerr << setprecision(3) << fixed;\n#endif\n\tcout << setprecision(15) << fixed;\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\n\tint test_count = 1;\n\t// cin >> test_count;\n\tfor (int test = 1; test <= test_count; ++test) {\n\t\tsolve();\n\t}\n\t\n#ifdef LOCAL\n\tauto end_time = clock();\n\tcerr << \"Execution time: \" << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << \" ms\\n\";\n#endif\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1195",
    "index": "E",
    "title": "OpenStreetMap",
    "statement": "Seryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size $n \\times m$ cells on a map (rows of grid are numbered from $1$ to $n$ from north to south, and columns are numbered from $1$ to $m$ from west to east). After that he measured the average height of each cell above Rybinsk sea level and obtained a matrix of heights of size $n \\times m$. The cell $(i, j)$ lies on the intersection of the $i$-th row and the $j$-th column and has height $h_{i, j}$.\n\nSeryozha is going to look at the result of his work in the browser. The screen of Seryozha's laptop can fit a subrectangle of size $a \\times b$ of matrix of heights ($1 \\le a \\le n$, $1 \\le b \\le m$). Seryozha tries to decide how the weather can affect the recreation center — for example, if it rains, where all the rainwater will gather. To do so, he is going to find the cell having minimum height among all cells that are shown on the screen of his laptop.\n\nHelp Seryozha to calculate the sum of heights of such cells for all possible subrectangles he can see on his screen. In other words, you have to calculate the sum of minimum heights in submatrices of size $a \\times b$ with top left corners in $(i, j)$ over all $1 \\le i \\le n - a + 1$ and $1 \\le j \\le m - b + 1$.\n\nConsider the sequence $g_i = (g_{i - 1} \\cdot x + y) \\bmod z$. You are given integers $g_0$, $x$, $y$ and $z$. By miraculous coincidence, $h_{i, j} = g_{(i - 1) \\cdot m + j - 1}$ ($(i - 1) \\cdot m + j - 1$ is the index).",
    "tutorial": "There is almost nothing to say about this problem. It is pretty standard data structure problem. Let $mn_{i, j}$ be the minimum value over all values $h_{i, j}, h_{i - 1, j}, \\dots, h_{i - a + 1}{j}$. If $i$ is less than $a$ then its value does not matter for us because the corresponding submatrix is not counted in the answer. These values can be calculated using std::deque or minimum queue. You can read more about it here: https://cp-algorithms.com/data_structures/stack_queue_modification.html. After building such matrix $mn$ we can actually calculate the answer. Let's iterate over all rows of the matrix (starting from row $a$) $i$ and carry the floating window of width $b$ of values $mn_{i, j}$. And when the size of the queue with minimums reaches $b$ we know the minimum on the corresponding submatrix that ends in the current element and we can add it to the answer. Time complexity: $O(nm)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long n, m, a, b, g, x, y, z;\nvector<deque<long long> > deq;\nvector<vector<long long> > mi;\nvector<int> power;\nconst long long MAX_V = 1000000000000000ll;\n\nvoid ins(deque<long long>& de, long long val) {\n    while(!de.empty() && de.back() > val) {\n        de.pop_back();\n    }\n    de.push_back(val);\n}\n\nvoid del(deque<long long>& de, long long val) {\n    if (!de.empty() && de.front() == val) {\n        de.pop_front();\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cin >> n >> m;\n    cin >> a >> b;\n    cin >> g >> x >> y >> z;\n    mi.resize(n);\n    deq.resize(m);\n    for (int i = 0; i < n; i++) {\n        mi[i].resize(m);\n        for (int j = 0; j < m; j++) {\n            mi[i][j] = g;\n            g = (g * x + y) % z;\n        }\n    }\n    for (int i = 0; i < m; i++) {\n        for (int j = 0; j < a; j++) {\n            ins(deq[i], mi[j][i]);\n        }\n    }\n    deque<long long> real_deq;\n    for (int i = 0; i < b; i++) {\n        ins(real_deq, deq[i].front());\n    }\n    long long ans = 0;\n    ans += real_deq.front();\n    for (int i = b; i < m; i++) {\n        del(real_deq, deq[i - b].front());\n        ins(real_deq, deq[i].front());\n        ans += real_deq.front();\n    }\n    for (int i = a; i < n; i++) {\n        for (int j = 0 ; j < m; j++) {\n            ins(deq[j], mi[i][j]);\n            del(deq[j], mi[i - a][j]);\n        }\n        deque<long long> real_d;\n        for (int j = 0; j < b; j++) {\n            ins(real_d, deq[j].front());\n        }\n        ans += real_d.front();\n        for (int j = b; j < m; j++) {\n            del(real_d, deq[j - b].front());\n            ins(real_d, deq[j].front());\n            ans += real_d.front();\n        }\n    }\n    cout << ans << \"\\n\";\n}",
    "tags": [
      "data structures",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1195",
    "index": "F",
    "title": "Geometers Anonymous Club",
    "statement": "Denis holds a Geometers Anonymous Club meeting in SIS. He has prepared $n$ convex polygons numbered from $1$ to $n$ for the club. He plans to offer members of the club to calculate Minkowski sums of these polygons. More precisely, he plans to give $q$ tasks, the $i$-th of them asks to calculate the sum of Minkowski of polygons with indices from $l_i$ to $r_i$ inclusive.\n\nThe sum of Minkowski of two sets $A$ and $B$ is the set $C = \\{a + b : a \\in A, b \\in B\\}$. It can be proven that if $A$ and $B$ are convex polygons then $C$ will also be a convex polygon.\n\n\\begin{center}\nSum of two convex polygons\n\\end{center}\n\nTo calculate the sum of Minkowski of $p$ polygons ($p > 2$), you need to calculate the sum of Minkowski of the first $p - 1$ polygons, and then calculate the sum of Minkowski of the resulting polygon and the $p$-th polygon.\n\nFor the convenience of checking answers, Denis has decided to prepare and calculate the number of vertices in the sum of Minkowski for each task he prepared. Help him to do it.",
    "tutorial": "Suppose we want to compute the Minkowski sum of two polygons $a$ and $b$. Let's denote two sequences of free vectors: $u_1$, $u_2$, ..., $u_{k_a}$ such that free vector $u_i$ is congruent to the bound vector starting in $i$-th vertex of the first polygon and ending in the $(i + 1)$-th vertex of this polygon (if $i = k_a$, then we use the $1$st point as the $(i + 1)$-th one); $v_1$, $v_2$, ..., $v_{k_b}$ such that free vector $v_i$ is congruent to the bound vector starting in $i$-th vertex of the second polygon and ending in the $(i + 1)$-th vertex of this polygon (if $i = k_b$, then we again use the $1$st point as the $(i + 1)$-th one). It's impossible to choose a pair of vectors from the same sequence in such a way that they are parallel, since there are no three points lying on the same line in the same polygon (but it may be possible to find a pair of antiparallel vectors belonging to the same sequence). Let's try to analyze how we can construct such sequence for the resulting polygon. For example, let's pick some side of the first polygon (let vector $u_i$ denote this side of the polygon) and analyze how this side can affect the resulting polygon. There are two cases: there is a vector $v_j$ such that it is parallel (not antiparallel) to $u_i$. Then this vector represents a side of the second polygon. If we construct the Minkowski sum of these two sides (the side represented by $u_i$ in the first polygon and the side represented by $v_j$ in the second polygon), then we will get a segment having length equal to $|u_i| + |v_j|$. The line coming through this segment divides the plane into two halfplanes, and all points belonging to the Minkowski sum of these polygons will be contained in the same halfplane. That's because all points of the first polygon belong to the same halfplane (if we divide the plane by the line coming through the side represented by $u_i$), and all points of the second polygon belong to the same halfplane (if we divide the plane by the line coming through the side represented by $v_j$) - moreover, both these halfplanes are either upper halfplanes (and then the whole resulting polygon belongs to the upper halfplane) or lower halfplanes (then result belongs to the lower halfplane). So, the resulting polygon will have a side represented by the free vector equal to $u_i + v_j$ (obviously, there can be only one such side); there is no such vector in the second sequence such that it is parallel to $u_i$. Then there exists exactly one vertex of the second polygon such that if we draw a line parallel to $u_i$ through this vertex, the whole second polygon will be contained in the upper halfplane or the lower halfplane (depending on whether the first polygon belongs to the upper halfplane or the lower halfplane in respect to the side parallel to $u_i$). Actually, this case can be analyzed as the case where $v_j$ exists, but has zero length: the resulting polygon will have a side represented by the vector $u_i$. So, for every vector in the sequences constructed by the given polygons, there will be a vector parallel to it in the resulting sequence of vectors. It is quite obvious that every vector in the resulting sequence is also parallel to some vector from the first two sequences. It means that the number of sides in the Minkowski sum is equal to the number of vectors in these two sequences, but all parallel vectors count as one. This fact can be extended to computing the Minkowski sum of multiple polygons: the resulting polygon will have the number of sides equal to the number of vectors in all sequences for given polygons, if we count all parallel vectors as one. Now we can solve the problem in such a way: construct the sequences of vectors for the given polygons and divide these vectors into equivalence classes in such a way that vectors belong to the same class if and only if they are parallel. The answer to each query is equal to the number of equivalence classes such that at least one vector belonging to this class is contained in at least one sequence on the segment of polygons; this can be modeled as the query \"count the number of distinct values on the given segment of the given array\". This problem can be solved with Mo's algorithm, mergesort tree or persistent segment tree.",
    "code": "// Created by Nikolay Budin\n\n#ifdef LOCAL\n#  define _GLIBCXX_DEBUG\n#else\n#  define cerr __get_ce\n#endif\n#include <bits/stdc++.h>\n#define ff first\n#define ss second\n#define szof(x) ((int)x.size())\n\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef unsigned long long ull;\nint const INF = (int)1e9 + 1e3;\nll const INFL = (ll)1e18 + 1e6;\n#ifdef LOCAL\n\tmt19937 tw(9450189);\n#else\n\tmt19937 tw(chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\nuniform_int_distribution<ll> ll_distr;\nll rnd(ll a, ll b) { return ll_distr(tw) % (b - a + 1) + a; }\n\nstruct point {\n\tint x, y;\n\tpoint(int _x, int _y) : x(_x), y(_y) {}\n\n\tpoint operator-(point const& other) const {\n\t\treturn point(x - other.x, y - other.y);\n\t}\n\n\tpoint& operator/=(int num) {\n\t\tx /= num;\n\t\ty /= num;\n\t\treturn *this;\n\t}\n\n\tbool operator<(point const& other) const {\n\t\treturn x < other.x || (x == other.x && y < other.y);\n\t}\n};\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<vector<point>> polys;\n\tvector<point> vecs;\n\tvector<int> borders;\n\tborders.push_back(0);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint k;\n\t\tcin >> k;\n\t\tborders.push_back(borders.back() + k);\n\t\tpolys.push_back({});\n\t\tfor (int j = 0; j < k; ++j) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y;\n\t\t\tpolys.back().push_back(point(x, y));\n\t\t}\n\n\t\tfor (int j = 0; j < k; ++j) {\n\t\t\tint next = (j + 1) % k;\n\t\t\tpoint v = polys[i][next] - polys[i][j];\n\t\t\tint tmp = __gcd(abs(v.x), abs(v.y));\n\t\t\tv /= tmp;\n\t\t\tvecs.push_back(v);\n\t\t}\n\t}\n\n\tvector<int> arr;\n\tmap<point, int> inds;\n\tfor (auto v : vecs) {\n\t\tif (!inds.count(v)) {\n\t\t\tint tmp = szof(inds);\n\t\t\tinds[v] = tmp;\n\t\t}\n\t\tarr.push_back(inds[v]);\n\t}\n\n\tvector<int> next(szof(vecs));\n\tvector<int> last(szof(inds), INF);\n\tfor (int i = szof(vecs) - 1; i >= 0; --i) {\n\t\tnext[i] = last[arr[i]];\n\t\tlast[arr[i]] = i;\n\t}\n\n\n\tvector<vector<pii>> here(szof(vecs));\n\tint q;\n\tcin >> q;\n\tvector<int> ans(q);\n\tfor (int i = 0; i < q; ++i) {\n\t\tint l, r;\n\t\tcin >> l >> r;\n\t\t--l;\n\t\tl = borders[l];\n\t\tr = borders[r];\n\t\there[l].push_back({r, i});\n\t}\n\n\tint bpv = 1;\n\twhile (bpv < szof(vecs)) {\n\t\tbpv *= 2;\n\t}\n\n\tvector<int> segtree(bpv * 2);\n\n\tfunction<void(int, int)> segtree_set = [&](int pos, int val) {\n\t\tpos += bpv;\n\t\tsegtree[pos] = val;\n\t\tpos /= 2;\n\t\twhile (pos) {\n\t\t\tsegtree[pos] = segtree[pos * 2] + segtree[pos * 2 + 1];\n\t\t\tpos /= 2;\n\t\t}\n\t};\n\n\tfunction<int(int, int, int, int, int)> segtree_get = [&](int v, int vl, int vr, int l, int r) {\n\t\tif (vr <= l || r <= vl) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (l <= vl && vr <= r) {\n\t\t\treturn segtree[v];\n\t\t}\n\t\tint vm = (vl + vr) / 2;\n\t\treturn segtree_get(v * 2, vl, vm, l, r) + segtree_get(v * 2 + 1, vm, vr, l, r);\n\t};\n\n\tfor (int i = 0; i < szof(inds); ++i) {\n\t\tsegtree_set(last[i], 1);\n\t}\n\n\tfor (int i = 0; i < szof(vecs); ++i) {\n\t\tfor (auto p : here[i]) {\n\t\t\tans[p.ss] = segtree_get(1, 0, bpv, i, p.ff);\n\t\t}\n\t\tsegtree_set(i, 0);\n\t\tif (next[i] != INF) {\n\t\t\tsegtree_set(next[i], 1);\n\t\t}\n\t}\n\n\tfor (int num : ans) {\n\t\tcout << num << \"\\n\";\n\t}\n}\n\n\nint main() {\n#ifdef LOCAL\n\tauto start_time = clock();\n\tcerr << setprecision(3) << fixed;\n#endif\n\tcout << setprecision(15) << fixed;\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\n\tint test_count = 1;\n\t// cin >> test_count;\n\tfor (int test = 1; test <= test_count; ++test) {\n\t\tsolve();\n\t}\n\t\n#ifdef LOCAL\n\tauto end_time = clock();\n\tcerr << \"Execution time: \" << (end_time - start_time) * (int)1e3 / CLOCKS_PER_SEC << \" ms\\n\";\n#endif\n}\n",
    "tags": [
      "data structures",
      "geometry",
      "math",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1196",
    "index": "A",
    "title": "Three Piles of Candies",
    "statement": "Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.\n\nAfter taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.\n\nAlice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).\n\nYou have to answer $q$ independent queries.\n\nLet's see the following example: $[1, 3, 4]$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $4$ candies, and Bob has $4$ candies.\n\nAnother example is $[1, 10, 100]$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $54$ candies, and Alice takes $46$ candies. Now Bob has $55$ candies, and Alice has $56$ candies, so she has to discard one candy — and after that, she has $55$ candies too.",
    "tutorial": "The answer is always $\\lfloor\\frac{a + b + c}{2}\\rfloor$. Let's understand why it is so. Let $a \\le b \\le c$. Then let Bob take the pile with $a$ candies and Alice take the pile with $b$ candies. Then because of $b \\le a + c$ we can see that Bob's pile always can reach size of Alice's pile (and remaining candies can be divided between them fairly except one candy if $a + b + c$ is odd).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tlong long a, b, c;\n\t\tcin >> a >> b >> c;\n\t\tcout << (a + b + c) / 2 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1196",
    "index": "B",
    "title": "Odd Sum Segments",
    "statement": "You are given an array $a$ consisting of $n$ integers $a_1, a_2, \\dots, a_n$. You want to split it into exactly $k$ \\textbf{non-empty non-intersecting subsegments} such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $n$ elements of the array $a$ must belong to exactly one of the $k$ subsegments.\n\nLet's see some examples of dividing the array of length $5$ into $3$ subsegments (not necessarily with odd sums): $[1, 2, 3, 4, 5]$ is the initial array, then all possible ways to divide it into $3$ non-empty non-intersecting subsegments are described below:\n\n- $[1], [2], [3, 4, 5]$;\n- $[1], [2, 3], [4, 5]$;\n- $[1], [2, 3, 4], [5]$;\n- $[1, 2], [3], [4, 5]$;\n- $[1, 2], [3, 4], [5]$;\n- $[1, 2, 3], [4], [5]$.\n\nOf course, it can be impossible to divide the initial array into exactly $k$ subsegments in such a way that each of them will have odd sum of elements. In this case print \"NO\". Otherwise, print \"YES\" and \\textbf{any} possible division of the array. See the output format for the detailed explanation.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "Firstly, let $cnt$ be the number of odd elements in the array. Note that even elements are don't matter at all because they cannot change the parity of the sum. If $cnt < k$ then it is obviously impossible to split the given array into $k$ subsegments with odd sum. And if $cnt \\% 2 \\ne k \\% 2$ then it is impossible to split the array into $k$ subsegments with odd sum also because at least one of $k$ segments will have even number of odd elements (so will have odd sum). In other cases the answer is always \"YES\" and you can print $k-1$ leftmost positions of odd elements and $n$ as right borders of segments (it means that when you find one odd element, you end one segment). Because $cnt \\% 2 = k \\% 2$ now, the last segment will have odd number of odd elements so it will have odd sum also.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<int> a(n);\n\t\tint cntodd = 0;\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tcin >> a[j];\n\t\t\tcntodd += a[j] % 2;\n\t\t}\n\t\tif (cntodd < k || cntodd % 2 != k % 2) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tcout << \"YES\" << endl;\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tif (k == 1) break;\n\t\t\tif (a[j] % 2 == 1) {\n\t\t\t\tcout << j + 1 << \" \";\n\t\t\t\t--k;\n\t\t\t}\n\t\t}\n\t\tcout << n << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1196",
    "index": "C",
    "title": "Robot Breakout",
    "statement": "$n$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!\n\nFortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $i$-th robot is currently located at the point having coordinates ($x_i$, $y_i$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $X$ and $Y$, and when each robot receives this command, it starts moving towards the point having coordinates ($X$, $Y$). The robot stops its movement in two cases:\n\n- either it reaches ($X$, $Y$);\n- or it cannot get any closer to ($X$, $Y$).\n\nNormally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($x_c$, $y_c$). Then the movement system allows it to move to any of the four adjacent points:\n\n- the first action allows it to move from ($x_c$, $y_c$) to ($x_c - 1$, $y_c$);\n- the second action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c + 1$);\n- the third action allows it to move from ($x_c$, $y_c$) to ($x_c + 1$, $y_c$);\n- the fourth action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c - 1$).\n\nUnfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.\n\nYou want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $X$ and $Y$ so that each robot can reach the point ($X$, $Y$). Is it possible to find such a point?",
    "tutorial": "In fact, we have some restrictions on $OX$ axis and $OY$ axis (for example, if some robot stays at the position $x$ and cannot move to the left, then the answer point should have $X \\ge x$). So we can take the minimum among all $y$-coordinates of robots that cannot go up and save it into $maxy$, maximum among all $y$-coordinates of robots that cannot go down and save it into $miny$, minimum among all $x$-coordinates of robots that cannot go right and save it into $maxx$ and maximum among all $x$-coordinates of robots that cannot go right and save it into $minx$. Initially $minx = miny = -\\infty, maxx = maxy = +\\infty$. So these restrictions are describe some rectangle (possibly incorrect, with $minx > maxx$ or $miny > maxy$). Let $(minx, miny)$ be the bottom-left point of this rectangle and $(maxx, maxy)$ be the top-right point of this rectangle. In case if this rectangle have $minx > maxx$ or $miny > maxy$, the answer is \"NO\". Otherwise this rectangle describes all integer points which can be reachable all robots and you can print any of them.",
    "code": "#include <algorithm>\n#include <iostream>\n\nusing namespace std;\n\nconst int MAXC = 1e5;\n\nint main() {\n    int q;\n    cin >> q;\n    while (q--) {\n        int n;\n        cin >> n;\n        int mnx = -MAXC, mxx = MAXC;\n        int mny = -MAXC, mxy = MAXC;\n        while (n--) {\n            int x, y, f1, f2, f3, f4;\n            cin >> x >> y >> f1 >> f2 >> f3 >> f4;\n            if (!f1) mnx = max(mnx, x);\n            if (!f2) mxy = min(mxy, y);\n            if (!f3) mxx = min(mxx, x);\n            if (!f4) mny = max(mny, y);\n        }\n        if (mnx <= mxx && mny <= mxy)\n            cout << \"1 \" << mnx << \" \" << mny << \"\\n\";\n        else\n            cout << \"0\\n\";\n    }\n\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1196",
    "index": "D1",
    "title": "RGB Substring (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the size of the input}.\n\nYou are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'.\n\nYou are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the changes there will be a string of length $k$ that is a substring of $s$, and is also a substring of the infinite string \"RGBRGBRGB ...\".\n\nA string $a$ is a substring of string $b$ if there exists a positive integer $i$ such that $a_1 = b_i$, $a_2 = b_{i + 1}$, $a_3 = b_{i + 2}$, ..., $a_{|a|} = b_{i + |a| - 1}$. For example, strings \"GBRG\", \"B\", \"BR\" are substrings of the infinite string \"RGBRGBRGB ...\" while \"GR\", \"RGR\" and \"GGG\" are not.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "You can just implement what is written in the problem statement and solve this problem this way. Let's iterate over all starting positions of the substring $i$ from $0$ to $n-k+1$ and over all possible offsets of the string $t$ = \"RGB\" $offset$ from $0$ to $2$ inclusive. Then let's iterate over all position of the current substring $pos$ from $0$ to $k-1$ and carry the variable $cur$ which denotes the answer for the current starting position and the current offset. And if $s_{i + pos} \\ne t_{(offset + pos) \\% 3}$ then let's increase $cur$ by $1$. After iterating over all positions $pos$ let's update the answer with the value of $cur$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tconst string t = \"RGB\";\n\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n, k;\n\t\tstring s;\n\t\tcin >> n >> k >> s;\n\t\tint ans = 1e9;\n\t\tfor (int j = 0; j < n - k + 1; ++j) {\n\t\t\tfor (int offset = 0; offset < 3; ++offset) {\n\t\t\t\tint cur = 0;\n\t\t\t\tfor (int pos = 0; pos < k; ++pos) {\n\t\t\t\t\tif (s[j + pos] != t[(pos + offset) % 3]) {\n\t\t\t\t\t\t++cur;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tans = min(ans, cur);\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1196",
    "index": "D2",
    "title": "RGB Substring (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the size of the input}.\n\nYou are given a string $s$ consisting of $n$ characters, each character is 'R', 'G' or 'B'.\n\nYou are also given an integer $k$. Your task is to change the minimum number of characters in the initial string $s$ so that after the changes there will be a string of length $k$ that is a substring of $s$, and is also a substring of the infinite string \"RGBRGBRGB ...\".\n\nA string $a$ is a substring of string $b$ if there exists a positive integer $i$ such that $a_1 = b_i$, $a_2 = b_{i + 1}$, $a_3 = b_{i + 2}$, ..., $a_{|a|} = b_{i + |a| - 1}$. For example, strings \"GBRG\", \"B\", \"BR\" are substrings of the infinite string \"RGBRGBRGB ...\" while \"GR\", \"RGR\" and \"GGG\" are not.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "In this problem you should make the same as in the previous one but faster. Let's consider three offsets of string \"RGB\": \"RGB\", \"GBR\" and \"BRG\". Let's copy the current offset of the string so that it will has the length $n$ (possibly, without some trailing characters) and save it in the string $t$. Then let's compare the string $s$ with this offset of length $n$ and build an array $diff$ of length $n$ where $diff_i = 1$ if $s_i \\ne t_i$. Then let's iterate over all possible continuous subsegments of this array $diff$ and maintain the variable $cur$ denoting the current answer. Firstly, for the current position $i$ let's add $diff_i$ to $cur$. Then if the current position $i$ is greater than or equal to $k-1$ ($0$-indexed) let's decrease $cur$ by $diff_{i-k}$. So now we have the continuous subsegment of the array $diff$ of length no more than $k$. Then if the current position $i$ is greater than or equal to $k$ ($0$-indexed again) (the current subsegment has the length $k$) then let's update the answer with $cur$. Then let's do the same with two remaining offsets.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tconst string t = \"RGB\";\n\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n, k;\n\t\tstring s;\n\t\tcin >> n >> k >> s;\n\t\tint ans = 1e9;\n\t\tfor (int offset = 0; offset < 3; ++offset) {\n\t\t\tvector<int> res(n);\n\t\t\tint cur = 0;\n\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\tres[j] = (s[j] != t[(j + offset) % 3]);\n\t\t\t\tcur += res[j];\n\t\t\t\tif (j >= k) cur -= res[j - k];\n\t\t\t\tif (j >= k - 1) ans = min(ans, cur);\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1196",
    "index": "E",
    "title": "Connected Component on a Chessboard",
    "statement": "You are given two integers $b$ and $w$. You have a chessboard of size $10^9 \\times 10^9$ with the top left cell at $(1; 1)$, the cell $(1; 1)$ is painted \\textbf{white}.\n\nYour task is to find a connected component on this chessboard that contains exactly $b$ black cells and exactly $w$ white cells. Two cells are called connected if they share a side (i.e. for the cell $(x, y)$ there are at most four connected cells: $(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)$). A set of cells is called a connected component if for every pair of cells $C_1$ and $C_2$ from this set, there exists a sequence of cells $c_1$, $c_2$, ..., $c_k$ such that $c_1 = C_1$, $c_k = C_2$, all $c_i$ from $1$ to $k$ are belong to this set of cells and for every $i \\in [1, k - 1]$, cells $c_i$ and $c_{i + 1}$ are connected.\n\nObviously, it can be impossible to find such component. In this case print \"NO\". Otherwise, print \"YES\" and \\textbf{any} suitable connected component.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "I'll consider the case when $b \\ge w$, the other case is symmetric and the answer I construct is the same but shifted by $1$ to the right. Consider the given field as a matrix where $x$ is the number of row and $y$ is the number of column. Firstly, let's build the line of length $2w-1$ from the cell $(2, 2)$ to the cell $(2, 2w)$. Then $b$ will decrease by $w-1$ and $w$ will (formally) become $0$. Then we have two black cells to the left and to the right ($(2, 1)$ and $(2, 2w+1)$) and $w-1$ black cells to the up (all cells ($1, 2w+2*i$) for all $i$ from $0$ to $w-1$) and $w-1$ black cells to the down (all cells ($3, 2w+2*i$) for all $i$ from $0$ to $w-1$). Let's add the required number of cells to the answer. If even after adding all these cells $b$ still be greater than $0$ then the answer is \"NO\" (maybe there will be a proof why it is so but you can read it already from other participants). Otherwise the answer is \"YES\" and we constructed the required component.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint b, w;\n\t\tcin >> b >> w;\n\t\tvector<pair<int, int>> res;\n\t\tbool need = b < w;\n\t\tif (need) swap(w, b);\n\t\tint x = 2, y = 2;\n\t\twhile (w > 0) {\n\t\t\tif ((x + y) % 2 == 1) {\n\t\t\t\tres.push_back({x, y});\n\t\t\t\t--b;\n\t\t\t} else {\n\t\t\t\tres.push_back({x, y});\n\t\t\t\t--w;\n\t\t\t}\n\t\t\t++y;\n\t\t}\n\t\tint cx = 1, cy = 2;\n\t\twhile (b > 0 && cy <= y) {\n\t\t\tres.push_back({cx, cy});\n\t\t\t--b;\n\t\t\tcy += 2;\n\t\t}\n\t\tcx = 3, cy = 2;\n\t\twhile (b > 0 && cy <= y) {\n\t\t\tres.push_back({cx, cy});\n\t\t\t--b;\n\t\t\tcy += 2;\n\t\t}\n\t\tif (b > 0) {\n\t\t\tres.push_back({2, 1});\n\t\t\t--b;\n\t\t}\n\t\tif (b > 0) {\n\t\t\tres.push_back({2, y});\n\t\t\t--b;\n\t\t}\n\t\tif (b > 0) {\n\t\t\tcout << \"NO\" << endl;\n\t\t} else {\n\t\t\tassert(w == 0);\n\t\t\tcout << \"YES\" << endl;\n\t\t\tfor (auto it : res) cout << it.first << \" \" << it.second + need << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1196",
    "index": "F",
    "title": "K-th Path",
    "statement": "You are given a connected undirected weighted graph consisting of $n$ vertices and $m$ edges.\n\nYou need to print the $k$-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from $i$ to $j$ and from $j$ to $i$ are counted as one).\n\nMore formally, if $d$ is the matrix of shortest paths, where $d_{i, j}$ is the length of the shortest path between vertices $i$ and $j$ ($1 \\le i < j \\le n$), then you need to print the $k$-th element in the sorted array consisting of all $d_{i, j}$, where $1 \\le i < j \\le n$.",
    "tutorial": "The main observation is that you don't need more than $min(k, m)$ smallest by weight edges (among all edges with the maximum weights you can choose any). Maybe there will be a proof later, but now I ask other participant to write it. So you sort the initial edges and after that you can construct a graph consisting of no more than $2min(k, m)$ vertices and no more than $min(m, k)$ edges. You just can build the new graph consisting only on these vertices and edges and run Floyd-Warshall algorithm to find the matrix of shortest paths. Then sort all shorted distances and print the $k$-th element of this sorted array. Time complexity: $O(m \\log m + k^3)$. I know that there are other approaches that can solve this problem with greater $k$, but to make this problem easily this solution is enough.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long INF64 = 1e18;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m, k;\n\tscanf(\"%d %d %d\", &n, &m, &k);\n\tvector<pair<int, pair<int, int>>> e;\n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y, w;\n\t\tscanf(\"%d %d %d\", &x, &y, &w);\n\t\t--x, --y;\n\t\te.push_back(make_pair(w, make_pair(x, y)));\n\t}\n\tsort(e.begin(), e.end());\n\t\n\tvector<int> vert;\n\tfor (int i = 0; i < min(m, k); ++i) {\n\t\tvert.push_back(e[i].second.first);\n\t\tvert.push_back(e[i].second.second);\n\t}\n\tsort(vert.begin(), vert.end());\n\tvert.resize(unique(vert.begin(), vert.end()) - vert.begin());\n\tint cntv = vert.size();\n\tvector<vector<long long>> dist(cntv, vector<long long>(cntv, INF64));\n\tfor (int i = 0; i < cntv; ++i) dist[i][i] = 0;\n\t\n\tfor (int i = 0; i < min(m, k); ++i) {\n\t\tint x = lower_bound(vert.begin(), vert.end(), e[i].second.first) - vert.begin();\n\t\tint y = lower_bound(vert.begin(), vert.end(), e[i].second.second) - vert.begin();\n\t\tdist[x][y] = dist[y][x] = min(dist[x][y], (long long)e[i].first);\n\t}\n\t\n\tfor (int z = 0; z < cntv; ++z) {\n\t\tfor (int x = 0; x < cntv; ++x) {\n\t\t\tfor (int y = 0; y < cntv; ++y) {\n\t\t\t\tdist[x][y] = min(dist[x][y], dist[x][z] + dist[z][y]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvector<long long> res;\n\tfor (int i = 0; i < cntv; ++i) {\n\t\tfor (int j = 0; j < i; ++j) {\n\t\t\tres.push_back(dist[i][j]);\n\t\t}\n\t}\n\t\n\tsort(res.begin(), res.end());\n\tcout << res[k - 1] << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "shortest paths",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1197",
    "index": "A",
    "title": "DIY Wooden Ladder",
    "statement": "Let's denote a $k$-step ladder as the following structure: exactly $k + 2$ wooden planks, of which\n\n- two planks of length \\textbf{at least} $k+1$ — the base of the ladder;\n- $k$ planks of length \\textbf{at least} $1$ — the steps of the ladder;\n\nNote that neither the base planks, nor the steps planks are required to be equal.\n\nFor example, ladders $1$ and $3$ are correct $2$-step ladders and ladder $2$ is a correct $1$-step ladder. On the first picture the lengths of planks are $[3, 3]$ for the base and $[1]$ for the step. On the second picture lengths are $[3, 3]$ for the base and $[2]$ for the step. On the third picture lengths are $[3, 4]$ for the base and $[2, 3]$ for the steps.\n\nYou have $n$ planks. The length of the $i$-th planks is $a_i$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised \"ladder\" from the planks.\n\nThe question is: what is the maximum number $k$ such that you can choose some subset of the given planks and assemble a $k$-step ladder using them?",
    "tutorial": "Since all planks have length at least $1$ so we can take any $n - 2$ planks as steps. So, all we need is to maximize the length of base planks. We can take the first and second maximum as base, then the answer is minimum among second maximum - 1 and $n - 2$.",
    "code": "fun main(args: Array<String>) {\n    val T = readLine()!!.toInt()\n    for (tc in 1..T) {\n        val n = readLine()!!.toInt()\n        val a = readLine()!!.split(' ').map { it.toInt() }.sortedDescending()\n        println(minOf(a[1] - 1, n - 2))\n    }\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1197",
    "index": "B",
    "title": "Pillars",
    "statement": "There are $n$ pillars aligned in a row and numbered from $1$ to $n$.\n\nInitially each pillar contains exactly one disk. The $i$-th pillar contains a disk having radius $a_i$.\n\nYou can move these disks from one pillar to another. You can take a disk from pillar $i$ and place it on top of pillar $j$ if all these conditions are met:\n\n- there is no other pillar between pillars $i$ and $j$. Formally, it means that $|i - j| = 1$;\n- pillar $i$ contains \\textbf{exactly} one disk;\n- either pillar $j$ contains no disks, or the topmost disk on pillar $j$ has radius strictly greater than the radius of the disk you move.\n\nWhen you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.\n\nYou may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $n$ disks on the same pillar simultaneously?",
    "tutorial": "Suppose we have a disk that is smaller than both of its neighbours. Then it's impossible to collect all the disks on the same pillar: eventually we will put this disk on the same pillar with one of its neighbours, and then we can't put the other neighbouring disk on the same pillar since it is greater than the middle disk. Okay, and what if there is no disk that is strictly smaller than both of its neighbours? Let $k$ be the index of the largest disk. $a_{k - 1} < a_k$, that implies $a_{k - 2} < a_{k - 1}$, and so on. $a_{k + 1} < a_k$, $a_{k + 2} < a_{k + 1}$, and so on. It means that the array $a$ is sorted in ascending until the index $k$, and after that it is sorted in descending order. If this condition is met, then we can collect all the disks on the pillar $k$ one by one, starting with the disk having radius $n - 1$ and ending with the disk having radius $1$. So the only thing that we need to check is the following condition: array $a$ is sorted in ascending order until $a_k = n$, and then it is sorted in descending order.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d\", &a[i]);\n\t\n\tint pos = max_element(a.begin(), a.end()) - a.begin();\n\tbool res = true;\n\tfor(int i = 0; i < pos; i++)\n\t\tres &= (a[i] < a[i + 1]);\n\tfor(int i = pos; i < n - 1; i++)\n\t\tres &= (a[i] > a[i + 1]);\n\n\tif(res)\n\t\tputs(\"YES\");\n\telse\n\t\tputs(\"NO\");\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1197",
    "index": "C",
    "title": "Array Splitting",
    "statement": "You are given a \\textbf{sorted} array $a_1, a_2, \\dots, a_n$ (for each index $i > 1$ condition $a_i \\ge a_{i-1}$ holds) and an integer $k$.\n\nYou are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.\n\nLet $max(i)$ be equal to the maximum in the $i$-th subarray, and $min(i)$ be equal to the minimum in the $i$-th subarray. The cost of division is equal to $\\sum\\limits_{i=1}^{k} (max(i) - min(i))$. For example, if $a = [2, 4, 5, 5, 8, 11, 19]$ and we divide it into $3$ subarrays in the following way: $[2, 4], [5, 5], [8, 11, 19]$, then the cost of division is equal to $(4 - 2) + (5 - 5) + (19 - 8) = 13$.\n\nCalculate the minimum cost you can obtain by dividing the array $a$ into $k$ non-empty consecutive subarrays.",
    "tutorial": "Let's carefully look at the coefficients with which the elements of the array will be included in the answer. If pair of adjacent elements $a_i$ and $a_{i+1}$ belong to different subarrays then element $a_i$ will be included in the answer with coefficient $1$, and element $a_{i+1}$ with coefficient $-1$. So they add value $a_{i} - a_{i+1}$ to the answer. If element belongs to subarray with length $1$ then it will be included in the sum with coefficient $0$ (because it will be included with coefficient $1$ and $-1$ simultaneously). Elements at positions $1$ and $n$ will be included with coefficients $-1$ and $1$ respectively. So initially our answer is $a_n - a_1$. All we have to do is consider $n-1$ values $a_1 - a_2, a_2 - a_3, \\dots , a_{n-1} - a_n$ and add up the $k-1$ minimal ones to the answer.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\n\nint n, k;\nint a[N];\n\nint main(){\n\tcin >> n >> k;\n\tfor(int i = 0; i < n; ++i)\n\t\tcin >> a[i];\n\t\n\tvector <int> v;\n\tfor(int i = 1; i < n; ++i) v.push_back(a[i - 1] - a[i]);\n\t\n\tsort(v.begin(), v.end());\n\t\n\tint res = a[n - 1] - a[0];\n\tfor(int i = 0; i < k - 1; ++i) res += v[i];\n\t\n\tcout << res << endl;\n \treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1197",
    "index": "D",
    "title": "Yet Another Subarray Problem",
    "statement": "You are given an array $a_1, a_2, \\dots , a_n$ and two integers $m$ and $k$.\n\nYou can choose some subarray $a_l, a_{l+1}, \\dots, a_{r-1}, a_r$.\n\nThe cost of subarray $a_l, a_{l+1}, \\dots, a_{r-1}, a_r$ is equal to $\\sum\\limits_{i=l}^{r} a_i - k \\lceil \\frac{r - l + 1}{m} \\rceil$, where $\\lceil x \\rceil$ is the least integer greater than or equal to $x$.\n\n\\textbf{The cost of empty subarray is equal to zero.}\n\nFor example, if $m = 3$, $k = 10$ and $a = [2, -4, 15, -3, 4, 8, 3]$, then the cost of some subarrays are:\n\n- $a_3 \\dots a_3: 15 - k \\lceil \\frac{1}{3} \\rceil = 15 - 10 = 5$;\n- $a_3 \\dots a_4: (15 - 3) - k \\lceil \\frac{2}{3} \\rceil = 12 - 10 = 2$;\n- $a_3 \\dots a_5: (15 - 3 + 4) - k \\lceil \\frac{3}{3} \\rceil = 16 - 10 = 6$;\n- $a_3 \\dots a_6: (15 - 3 + 4 + 8) - k \\lceil \\frac{4}{3} \\rceil = 24 - 20 = 4$;\n- $a_3 \\dots a_7: (15 - 3 + 4 + 8 + 3) - k \\lceil \\frac{5}{3} \\rceil = 27 - 20 = 7$.\n\nYour task is to find the maximum cost of some subarray (possibly empty) of array $a$.",
    "tutorial": "At first let's solve this problem when $m = 1$ and $k = 0$ (it is the problem of finding subarray with maximum sum). For each position from $1$ to $n$ we want to know the value of $maxl_i = \\max\\limits_{1 \\le j \\le i + 1} sum(j, i)$, where $sum(l, r) = \\sum\\limits_{k = l}^{k \\le r} a_k$, and $sum(x+1, x) = 0$. We will calculate it the following way. $maxl_i$ will be the maximum of two values: $0$ (because we can take segments of length $0$); $a_i + maxl_{i-1}$. The maximum sum of some subarray is equal to $\\max\\limits_{1\\le i \\le n} maxl_i$. So, now we can calculate the values of $best_i = \\max\\limits_{0 \\le len, i - len \\cdot m \\ge 0} (sum(i-len \\cdot m + 1, i) - len * k)$ the same way. $best_i$ is the maximum of two values: 0; $sum(i - m + 1, i) - k + best_{i-m}$. After calculating all values $best_i$ we can easily solve this problem. At first, let's iterate over the elements $best_i$. When we fix some element $best_i$, lets iterate over the value $len = 1, 2, \\dots, m$ and update the answer with value $best_i + sum(i - len, i - 1) - k$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\n\nint n, m, k;\nint a[N];\nlong long bst[N];\nlong long psum[N];\n\nlong long sum(int l, int r){\n    l = max(l, 0);\n\treturn psum[r] - (l == 0? 0 : psum[l - 1]);\n}\n\nint main() {\n\tcin >> n >> m >> k;\n\tfor(int i = 0; i < n; ++i){\n\t\tcin >> a[i];\n\t\tpsum[i] = a[i] + (i == 0? 0 : psum[i - 1]);\n\t}\n\n\tlong long res = 0;\n\tfor(int len = 1; len <= m && len <= n; ++len)\n\t\t\tres = max(res, sum(0, len - 1) - k);\n\tfor(int i = 0; i < n; ++i){\n\t\tif(i + 1 >= m){\n\t\t\tlong long nbst = sum(i - m + 1, i) - k;\n\t\t\tif(i - m >= 0) nbst += bst[i - m];\n\t\t\tbst[i] = max(bst[i], + nbst);\n\t\t}\n\n\t\tfor(int len = 0; len < m && i + len < n; ++len)\n\t\t\tres = max(res, bst[i] + sum(i + 1, i + len) - k * (len > 0));\n\t}\t\n\n\tcout << res << endl;\n\treturn 0;\n}                             \t",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1197",
    "index": "E",
    "title": "Culture Code",
    "statement": "There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $n$ different matryoshkas. Any matryoshka is a figure of volume $out_i$ with an empty space inside of volume $in_i$ (of course, $out_i > in_i$).\n\nYou don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll — inside the third one and so on. Matryoshka $i$ can be nested inside matryoshka $j$ if $out_i \\le in_j$. So only the last doll will take space inside your bag.\n\nLet's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \\dots + (in_{i_k} - out_{i_{k-1}})$, where $i_1$, $i_2$, ..., $i_k$ are the indices of the chosen dolls in the order they are nested in each other.\n\nFinally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.\n\nYou want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $i$ such that one of the subsets contains the $i$-th doll, and another subset doesn't.\n\nSince the answer can be large, print it modulo $10^9 + 7$.",
    "tutorial": "Let's, at first, sort all matryoshkas by increasing its inner volume $in_i$. Then each nested subset will appear as subsequence in its \"canonical\" order. Now we'll write the DP with $d[i] = (x, y)$ - the minimum extra space $x$ and number of such subsequences $y$ among all nested subsets, where the $i$-th doll is minimal. Why minimal (not maximal, for example)? It's just easier transitions (and easier proof). There are two main cases. If there isn't $j$, such that $out_i \\le in_j$ then we can't put the $i$-th doll inside any other. So, $d[i] = (in_i, 1)$. Otherwise, we must put the $i$-th doll inside other doll (otherwise, the subset won't be a big enough). If we put the $i$-th doll inside the $j$-th doll then we extra space of such subset is equal to $d[j].first - (out_i - in_i)$. Since we minimize the extra space, then $d[i].first = \\min\\limits_{out_i \\le in_j}{(d[j].first - (out_i - in_i))} = \\min\\limits_{out_i \\le in_j}{(d[j].first)} - (out_i - in_i).$ Since we sorted all matryoshkas, so there is a position $pos$ such that $\\forall j \\ge pos : out_i \\le in_j$ and $d[i].first = \\min\\limits_{j = pos}^{n}{(d[j].first)} - (out_i - in_i)$. The $d[i].second$ is just a sum from all minimums. As you can see: we can store $d[i]$ in Segment Tree with minimum + number of minimums. Why in the second transition we will build only big enough subsets? It's because not big enough subsets are not optimal in terms of minimality of extra space. The result complexity is $O(n \\log(n))$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9) + 555;\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nconst int MOD = int(1e9) + 7;\n\nint norm(int a) {\n\tif(a >= MOD) a -= MOD;\n\tif(a < 0) a += MOD;\n\treturn a;\n}\n\npt combine(const pt &a, const pt &b) {\n\tif(a.x < b.x)\n\t\treturn a;\n\tif(a.x > b.x)\n\t\treturn b;\n\treturn {a.x, norm(a.y + b.y)};\n}\n\nint n;\nvector<pt> p;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\tp.resize(n);\n\tfore(i, 0, n)\n\t\tcin >> p[i].x >> p[i].y;\n\t\n\treturn true;\n}\n\nvector<pt> T;\n\nvoid setVal(int pos, const pt &val) {\n\tT[pos += n] = val;\n\tfor(pos >>= 1; pos > 0; pos >>= 1)\n\t\tT[pos] = combine(T[2 * pos], T[2 * pos + 1]);\n}\n\npt getMin(int l, int r) {\n\tpt ans = {INF, 0};\n\tfor(l += n, r += n; l < r; l >>= 1, r >>= 1) {\n\t\tif(l & 1)\n\t\t\tans = combine(T[l++], ans);\n\t\tif(r & 1)\n\t\t\tans = combine(T[--r], ans);\n\t}\n\treturn ans;\n}\n\ninline void solve() {\n\tauto comp = [](const pt &a, const pt &b) {\n\t\tif(a.y != b.y)\n\t\t\treturn a.y < b.y;\n\t\treturn a.x < b.x;\n\t};\n\t\n\tsort(p.begin(), p.end(), comp);\n\t\n\tT.assign(2 * n, {INF, 0});\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\tint pos = int(lower_bound(p.begin(), p.end(), pt(0, p[i].x), comp) - p.begin());\n\t\t\n\t\tif(pos >= n) {\n\t\t\tsetVal(i, {p[i].y, 1});\n\t\t\tcontinue;\n\t\t}\n\t\tpt bst = getMin(pos, n);\n\t\tsetVal(i, {bst.x - (p[i].x - p[i].y), bst.y});\n\t}\n\t\n\tcout << getMin(0, n).y << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "data structures",
      "dp",
      "shortest paths",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1197",
    "index": "F",
    "title": "Coloring Game",
    "statement": "Alice and Bob want to play a game. They have $n$ colored paper strips; the $i$-th strip is divided into $a_i$ cells numbered from $1$ to $a_i$. Each cell can have one of $3$ colors.\n\nIn the beginning of the game, Alice and Bob put $n$ chips, the $i$-th chip is put in the $a_i$-th cell of the $i$-th strip. Then they take turns, Alice is first. Each player during their turn has to choose one chip and move it $1$, $2$ or $3$ cells backwards (i. e. if the current cell is $x$, then the chip can be moved to the cell $x - 1$, $x - 2$ or $x - 3$). There are two restrictions: the chip cannot leave the borders of the strip (for example, if the current cell is $3$, then you can't move the chip $3$ cells backwards); and some moves may be prohibited because of color of the current cell (a matrix $f$ with size $3 \\times 3$ is given, where $f_{i, j} = 1$ if it is possible to move the chip $j$ cells backwards from the cell which has color $i$, or $f_{i, j} = 0$ if such move is prohibited). The player who cannot make a move loses the game.\n\nInitially some cells may be uncolored. Bob can color all uncolored cells as he wants (but he cannot leave any cell uncolored). Let's call a coloring good if Bob can win the game no matter how Alice acts, if the cells are colored according to this coloring. Two colorings are different if at least one cell is colored in different colors in these two colorings.\n\nBob wants you to calculate the number of good colorings. Can you do it for him?\n\nSince the answer can be really large, you have to print it modulo $998244353$.",
    "tutorial": "Suppose there is only one strip and we want to count the number of ways to paint it. We can do it with some dynamic programming: let $dp_{i, r_1, r_2, r_3}$ be the number of ways to paint first $i$ cells of the strip so that $r_1$ denotes the result of the game if it starts in the last cell ($r_1 = 0$ if the player that makes a turn from this state loses, or $r_1 = 1$ if he wins), $r_2$ - the result if the game starts in the second-to-last, and so on. Then, if we paint the next cell, we can easily determine the result of the game starting in it, using the values of $r_i$ and the set of possible moves: if there is a value $r_i = 0$ such that we can move the chip $i$ cells backwards from the cell we just painted, then that cell is a winning one (if the game starts in it, the first player wins), otherwise it is a losing one. This dynamic programming works too slow since the strip can be very long, but we can skip long uncolored segments converting the transitions of this dp into matrix-vector multiplication: each possible combination of values of ($r_1$, $r_2$, $r_3$) can be encoded as a number from $0$ to $7$, and we may construct a $8 \\times 8$ transition matrix $T$: $T_{i, j}$ will be equal to the number of ways to color one cell so that the previous values of ($r_1$, $r_2$, $r_3$) have code $i$, and the next values have code $j$. To model painting $k$ consecutive uncolored segments, we may compute $T^k$ with fast exponentiation method. Now we can solve the problem for one strip. What changes if we try to apply the same method to solve the problem with many strips? Unfortunately, we can't analyze each cell as \"winning\" or \"losing\" now, we need more information. When solving a problem related to a combination of acyclic games, we may use Sprague-Grundy theory (you can read about it here: https://cp-algorithms.com/game_theory/sprague-grundy-nim.html). Instead of marking each cell as \"winning\" or \"losing\", we can analyze the Grundy value of each cell. When considering a strip, we should count the number of ways to color it so that its Grundy is exactly $x$ (we should do it for every possible value of $x$), which can help us to solve the initial problem with the following dynamic programming: $z_{i, j}$ is the number of ways to color $i$ first strips so that the Grundy value of their combination is exactly $j$. The only thing that's left to consider is how do we count the number of ways to color a single strip so that its Grundy value is fixed. We can to it by modifying the method described in the first paragraph: let $dp_{i, r_1, r_2, r_3}$ be the number of ways to paint $i$ first cells so that the Grundy value of the last cell is $r_1$, the value of the previous-to-last cell is $r_2$, and so on. Since we have only $3$ possible moves, the Grundy values are limited to $3$, and each possible combination of values of ($r_1$, $r_2$, $r_3$) can be encoded as a number from $0$ to $63$. The transition matrix $T$ that allows us to skip long uncolored segments will be a $64 \\times 64$ one, so if we will just exponentiate it every time we want to skip a segment, we'll get TL - but we can optimize it by precalculating $T$, $T^2$, $T^4$, ..., $T^{2^{30}}$ and using matrix-vector multiplication instead of matrix-matrix multiplication every time we skip an uncolored segment.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n\treturn (x + y) % MOD;\n}\n\nint mul(int x, int y)\n{\n\treturn (x * 1ll * y) % MOD;\n}\n\ntypedef vector<int> vec;\ntypedef vector<vec> mat;\n\nvec mul(const mat& a, const vec& b)\n{\n\tint n = a.size();\n\tint m = b.size();\n\tvector<int> c(m);\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < m; j++)\n\t\t\tc[i] = add(c[i], mul(b[j], a[i][j]));\n\treturn c;\n}\n\nmat add(const mat& a, const mat& b)\n{\n\tint n = a.size();\n\tint m = a[0].size();\n\tmat c(n, vec(m, 0));\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < m; j++)\n\t\t\tc[i][j] = add(a[i][j], b[i][j]);\n\treturn c;\n}\n\nmat mul(const mat& a, const mat& b)\n{\n\tint x = a.size();\n\tint y = b.size();\n\tint z = b[0].size();\n\tmat c(x, vec(z, 0));\n\tfor(int i = 0; i < x; i++)\n\t\tfor(int j = 0; j < y; j++)\n\t\t\tfor(int k = 0; k < z; k++)\n\t\t\t\tc[i][k] = add(c[i][k], mul(a[i][j], b[j][k]));\n\treturn c;\n}\n\nmat binpow(mat a, int d)\n{\n\tint n = a.size();\n\tmat c = mat(n, vec(n, 0));\n\tfor(int i = 0; i < n; i++) c[i][i] = 1;\n\twhile(d > 0)\n\t{\n\t\tif(d % 2 == 1) c = mul(c, a);\n\t\ta = mul(a, a);\n\t\td /= 2;\n\t}\n\treturn c;\n}\n\nint f[3][3];\n\nint extend(int color, vector<int> last_numbers)\n{\n\tvector<int> used(4, 0);\n\tfor(int i = 0; i < 3; i++)\n\t\tif(f[color][i])\n\t\t\tused[last_numbers[i]] = 1;\n\tfor(int i = 0; i <= 3; i++)\n\t\tif(used[i] == 0)\n\t\t\treturn i;\n\treturn 3;\n}\n\nvector<int> extend_state(int color, vector<int> last_numbers)\n{\n\tint z = extend(color, last_numbers);\n\tlast_numbers.insert(last_numbers.begin(), z);\n\tlast_numbers.pop_back();\n\treturn last_numbers;\n}\n\nvector<int> int2state(int x)\n{\n\tvector<int> res;\n\tfor(int i = 0; i < 3; i++)\n\t{\n\t\tres.push_back(x % 4);\n\t\tx /= 4;\n\t}\n\treturn res;\n}\n\nint state2int(const vector<int>& x)\n{\n\tint res = 0;\n\tint deg = 1;\n\tfor(auto y : x)\n\t{\n\t\tres += deg * y;\n\t\tdeg *= 4;\n\t}\n\treturn res;\n}\n\nmat form_matrix(int color)\n{\n\tmat res(64, vec(64, 0));\n\tfor(int i = 0; i < 64; i++)\n\t{\n\t\tint j = state2int(extend_state(color, int2state(i)));\n\t\tres[j][i] = add(res[j][i], 1);\n\t}\n\treturn res;\n}\n\nmat color_matrices[3];\nmat full_matrix;\n\nvector<pair<int, int> > colored[1043];\nint len[1043];\nint dp[1043][4];\n\nmat full_pows[31];\n\nvoid precalc_pows()\n{\n\tfull_pows[0] = full_matrix;\n\tfor(int i = 0; i <= 30; i++)\n\t\tfull_pows[i + 1] = mul(full_pows[i], full_pows[i]);\n}\n\nvec powmul(int d, vec b)\n{\n\tfor(int i = 0; i <= 30; i++)\n\t{\n\t\tif(d % 2 == 1) \n\t\t\tb = mul(full_pows[i], b);\n\t\td /= 2;\n\t}\n\treturn b;\n}\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\tfor(int i = 0; i < n; i++)\n\t\tcin >> len[i];\n\tint m;\n\tcin >> m;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint x, y, c;\n\t\tcin >> x >> y >> c;\n\t\t--x;\n\t\t--y;\n\t\t--c;\n\t\tcolored[x].push_back(make_pair(y, c));\n\t}\n\tfor(int i = 0; i < n; i++)\n\t\tsort(colored[i].begin(), colored[i].end());\n\tfor(int i = 0; i < 3; i++)\n\t\tfor(int j = 0; j < 3; j++)\n\t\t\tcin >> f[i][j];\n\t\n\tfor(int i = 0; i < 3; i++)\n\t\tcolor_matrices[i] = form_matrix(i);\n\tfull_matrix = color_matrices[0];\n\tfor(int i = 1; i < 3; i++)\n\t\tfull_matrix = add(full_matrix, color_matrices[i]);\n\tprecalc_pows();\n\t\t\n\tdp[0][0] = 1;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tvec cur(64);\n\t\tcur[state2int({3, 3, 3})] = 1;\n\t\tint last = 0;\n\t\tfor(auto x : colored[i])\n\t\t{\n\t\t\tcur = powmul(x.first - last, cur);\n\t\t\tcur = mul(color_matrices[x.second], cur);\n\t\t\tlast = x.first + 1;\n\t\t}\n\t\tcur = powmul(len[i] - last, cur);\n\t\tfor(int j = 0; j < 4; j++)\n\t\t\tfor(int k = 0; k < 64; k++)\n\t\t\t{\n\t\t\t\tvector<int> s = int2state(k);\n\t\t\t\tdp[i + 1][j ^ s[0]] = add(dp[i + 1][j ^ s[0]], mul(dp[i][j], cur[k]));\n\t\t\t}\n\t}\n\tcout << dp[n][0] << endl;\n}",
    "tags": [
      "dp",
      "games",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1198",
    "index": "A",
    "title": "MP3",
    "statement": "One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $n$ non-negative integers.\n\nIf there are exactly $K$ distinct values in the array, then we need $k = \\lceil \\log_{2} K \\rceil$ bits to store each value. It then takes $nk$ bits to store the whole file.\n\nTo reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $l \\le r$, and after that all intensity values are changed in the following way: if the intensity value is within the range $[l;r]$, we don't change it. If it is less than $l$, we change it to $l$; if it is greater than $r$, we change it to $r$. You can see that we lose some low and some high intensities.\n\nYour task is to apply this compression in such a way that the file fits onto a disk of size $I$ bytes, and the number of changed elements in the array is minimal possible.\n\nWe remind you that $1$ byte contains $8$ bits.\n\n$k = \\lceil log_{2} K \\rceil$ is the smallest integer such that $K \\le 2^{k}$. In particular, if $K = 1$, then $k = 0$.",
    "tutorial": "First let's calculate how many different values we can have. Maximal $k$ is $\\frac{8I}{n}$, maximal $K$ is $2^{k}$. We have to be careful not to overflow, let's use $K=2^{\\min(20, k)}$ ($2^{20}$ is bigger than any $n$). Let's sort the array and compress equal values. Now we have to choose no more than $K$ consecutive values in such a way that they cover as much elements as possible. If $K$ is bigger than number of different values, then answer is 0. Otherwise we can precalculate prefix sums and try all the variants to choose $K$ consecutive values. Complexity is $O(n \\log n)$.",
    "tags": [
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1198",
    "index": "B",
    "title": "Welfare State",
    "statement": "There is a country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.\n\nSometimes the government makes payouts to the poor: all citizens who have strictly less money than $x$ are paid accordingly so that after the payout they have exactly $x$ money. In this case the citizens don't send a receipt.\n\nYou know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.",
    "tutorial": "For every citizen only the last query of type $1$ matters. Moreover, all queries before don't matter at all. So the answer for each citizen is maximum of $x$ for last query of type $1$ for this citizen and maximum of all $x$ for queries of type $2$ after that. We can calculate maximum $x$ for all suffices of queries of type $2$, and remember the last query of type $1$ for each citizen. It can be implemented in $O(n+q)$ time.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1198",
    "index": "C",
    "title": "Matching vs  Independent Set",
    "statement": "You are given a graph with $3 \\cdot n$ vertices and $m$ edges. You are to find a matching of $n$ edges, \\textbf{or} an independent set of $n$ vertices.\n\nA set of edges is called a matching if no two edges share an endpoint.\n\nA set of vertices is called an independent set if no two vertices are connected with an edge.",
    "tutorial": "Let's try to take edges to matching greedily in some order. If we can add an edge to the matching (both endpoints are not covered), then we take it. It is easy to see that all vertices not covered by the matching form an independent set - otherwise we would add an edge to the matching. Either matching or independent set has size at least $n$. Complexity - $O(n+m)$.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1198",
    "index": "D",
    "title": "Rectangle Painting 1",
    "statement": "There is a square grid of size $n \\times n$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $\\max(h, w)$ to color a rectangle of size $h \\times w$. You are to make all cells white for minimum total cost.",
    "tutorial": "Let's solve the problem for rectangle $W \\times H$ ($W \\ge H$). Of course, we can cover all rectangle with itself for cost $W$. To get something smaller than $W$ we have to leave at least one column uncovered - otherwise we pay at least sum of $w$ over all rectangles which is at least $W$. This gives us an idea to use DP on rectangles to solve the problem: $dp[x_{1}][x_{2}][y_{1}][y_{2}]$ is minimal cost to cover the rectangle $[x_{1};x_{2})\\times[y_{1};y_{2})$. It is initialized by $\\max(x_{2}-x_{1}, y_{2}-y_{1})$, and we have to try not to cover every column/row. Of course, we have to check if it is all white from the beginning; to do that we will precalculate 2D prefix sums. Total complexity is $O(n^{5})$.",
    "tags": [
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1198",
    "index": "E",
    "title": "Rectangle Painting 2",
    "statement": "There is a square grid of size $n \\times n$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $\\min(h, w)$ to color a rectangle of size $h \\times w$. You are to make all cells white for minimum total cost.\n\nThe square is large, so we give it to you in a compressed way. The set of black cells is the union of $m$ rectangles.",
    "tutorial": "If we use some rectangle $[x_{1};x_{2}) \\times [y_{1};y_{2})$ ($x_{2}-x_{1} \\le y_{2}-y_{1}$), then we can change it to $[x_{1};x_{2}) \\times [0, n)$ without changing the cost. Also we can choose $w$ rectangles of width $1$ instead of one rectangle of width $w$, it will not change the cost. So, we have to choose minimal number of columns and rows such that all black cells are covered by at least one chosen column/row. If we will build a bipartite graph - left part is columns, right part is rows, there is an edge iff the cell in the intersection of given row and column is black - then the answer is minimal vertex cover in this graph. Minimal vertex cover is the same size as maximum matching, which can be found using flow. All that is left is to see that we can compress identical vertices, and we will have $O(m)$ vertices in both parts. With Dinic algorithm complexity is $O(m^{4})$.",
    "tags": [
      "flows",
      "graph matchings",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1198",
    "index": "F",
    "title": "GCD Groups 2",
    "statement": "You are given an array of $n$ integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.\n\nThe GCD of a group of integers is the largest non-negative integer that divides all the integers in the group.\n\nBoth groups have to be non-empty.",
    "tutorial": "All numbers have no more than $k=9$ different prime divisors. If there exist a solution, then for every number there exist a solution in which this number is in group of size not more than $(k+1)$, because all we have to do is to \"kill\" all prime numbers from this number, and to do it we only need one number for each prime. If $n \\le 2(k+1)$, we can try all the splits in time $O(2^{n} (n + \\log C))$. Let's take two numbers which will be in different groups. How to do it? - let's take random pair. For fixed first number probability of mistake is no more than $\\frac{k}{n-1}$. Now in each group we have to kill no more than $k$ primes. Let's do subset DP - our state is what primes are still alive. This solution has complexity $O(n 2^{2k})$. But we actually don't need all $n$ numbers. For each prime we can look at no more than $2k$ candidates which can kill it, because to kill all other primes we need strictly less numbers, and we will have a spare one anyways. Thus the solution has complexity $O(2^{2k}k^{2} + nk)$. We don't need factorization for any numbers except two chosen, and we can factorize them in $O(\\sqrt{C})$.",
    "tags": [
      "greedy",
      "number theory",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1199",
    "index": "A",
    "title": "City Day",
    "statement": "For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $n$ days of summer. On the $i$-th day, $a_i$ millimeters of rain will fall. All values $a_i$ are distinct.\n\nThe mayor knows that citizens will watch the weather $x$ days before the celebration and $y$ days after. Because of that, he says that a day $d$ is not-so-rainy if $a_d$ is smaller than rain amounts at each of $x$ days before day $d$ and and each of $y$ days after day $d$. In other words, $a_d < a_j$ should hold for all $d - x \\le j < d$ and $d < j \\le d + y$. Citizens only watch the weather during summer, so we only consider such $j$ that $1 \\le j \\le n$.\n\nHelp mayor find the \\textbf{earliest} not-so-rainy day of summer.",
    "tutorial": "$x$ and $y$ are small, so we can explicitly check every day. Complexity $O(n(x+y))$.",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1199",
    "index": "B",
    "title": "Water Lily",
    "statement": "While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $H$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $L$ centimeters. Exactly at this point the flower touched the water surface.\n\nSuppose that the lily grows at some point $A$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $A$. Also suppose that initially the flower was exactly above the point $A$, i.e. its stem was vertical. Can you determine the depth of the lake at point $A$?",
    "tutorial": "We can use Pythagorean theorem and get the equation $x^{2} + L^{2} = (H+x)^{2}$. Its solution is $x=\\frac{L^{2}-H^{2}}{2H}$.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1200",
    "index": "A",
    "title": "Hotelier",
    "statement": "Amugae has a hotel consisting of $10$ rooms. The rooms are numbered from $0$ to $9$ from left to right.\n\nThe hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.\n\nOne day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.",
    "tutorial": "Make an array of size 10 filled with 0. Then for each character from the input: L : Find the first position containing 0, then change it to 1. R : Find the last position containing 0, then change it to 1. 0 9 : array[x] = 0. Time complexity: $O(n)$",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1200",
    "index": "B",
    "title": "Block Adventure",
    "statement": "Gildong is playing a video game called Block Adventure. In Block Adventure, there are $n$ columns of blocks in a row, and the columns are numbered from $1$ to $n$. All blocks have equal heights. The height of the $i$-th column is represented as $h_i$, which is the number of blocks stacked in the $i$-th column.\n\nGildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $1$-st column. The goal of the game is to move the character to the top of the $n$-th column.\n\nThe character also has a bag that can hold infinitely many blocks. When the character is on the top of the $i$-th column, Gildong can take one of the following three actions as many times as he wants:\n\n- if there is at least one block on the column, remove one block from the top of the $i$-th column and put it in the bag;\n- if there is at least one block in the bag, take one block out of the bag and place it on the top of the $i$-th column;\n- if $i < n$ and $|h_i - h_{i+1}| \\le k$, move the character to the top of the $i+1$-st column. $k$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the \\textbf{next} column.\n\nIn actions of the first two types the character remains in the $i$-th column, and the value $h_i$ changes.\n\nThe character initially has $m$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.",
    "tutorial": "We can easily see that it's always optimal to have as many blocks as possible in the bag before getting to the next column. Therefore, if the character is currently on the top of the $i$-th column, Gildong just needs to make $h_i$ become $max(0, h_{i+1} - k)$ by repeating the $1$-st or the $2$-nd action. In other words, we should add $h_i - max(0, h_{i+1} - k)$ blocks to the bag. Adding or subtracting one by one will lead to TLE. If there exists a situation where the bag will have negative number of blocks, the answer is NO. Otherwise the answer is YES. Time complexity: $O(n)$ for each test case.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1200",
    "index": "C",
    "title": "Round Corridor",
    "statement": "Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by $n$ sectors, and the outer area is equally divided by $m$ sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wall always exists at the 12 o'clock position.\n\nThe inner area's sectors are denoted as $(1,1), (1,2), \\dots, (1,n)$ in clockwise direction. The outer area's sectors are denoted as $(2,1), (2,2), \\dots, (2,m)$ in the same manner. For a clear understanding, see the example image above.\n\nAmugae wants to know if he can move from one sector to another sector. He has $q$ questions.\n\nFor each question, check if he can move between two given sectors.",
    "tutorial": "Denote the corridor's length as $1$. Then, there is a wall at $(1, \\frac{1}{n}), (1, \\frac{2}{n}), \\cdots, (1, \\frac{n}{n}), (2, \\frac{1}{m}), (2, \\frac{2}{m}), \\cdots (2, \\frac{m}{m})$. For some value $x$, If there are walls at $(1, x)$ and $(2, x)$ at the same time, we can't move from $y$ to $z$ for $y \\lt x$ and $z \\gt x$. Let's call them a \"dual wall.\" Suppose $g = gcd(n, m)$. Then dual walls exist at $\\frac{1}{g}, \\frac{2}{g}, \\cdots, \\frac{g}{g}$. So we can make $g$ groups. We can move freely in the same group, and we can't move from one group to another group.For $x = 1$, $(1, 1), (1,2), \\cdots, (1,\\frac{n}{g})$ belong to group $1$, and $(1, \\frac{n}{g} + 1), (1, \\frac{n}{g} + 2), \\cdots, (1, \\frac{2n}{g})$ belong to group $2$, and so on. For $x = 2$, $(2, 1), (2, 2), \\cdots, (2, \\frac{m}{g})$ belong to group $1$, and $(2, \\frac{m}{g} + 1), (2, \\frac{m}{g} + 2), \\cdots, (2, \\frac{2m}{g})$ belong to group $2$, and so on. For each query, print YES if $(sx, sy)$ and $(ex, ey)$ belong to the same group. Otherwise, print NO. time complexity: $O(log(max(n,m)) + q)$",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1200",
    "index": "D",
    "title": "White Lines",
    "statement": "Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $n$ rows and $n$ columns of square cells. The rows are numbered from $1$ to $n$, from top to bottom, and the columns are numbered from $1$ to $n$, from left to right. The position of a cell at row $r$ and column $c$ is represented as $(r, c)$. There are only two colors for the cells in cfpaint — black and white.\n\nThere is a tool named eraser in cfpaint. The eraser has an integer size $k$ ($1 \\le k \\le n$). To use the eraser, Gildong needs to click on a cell $(i, j)$ where $1 \\le i, j \\le n - k + 1$. When a cell $(i, j)$ is clicked, all of the cells $(i', j')$ where $i \\le i' \\le i + k - 1$ and $j \\le j' \\le j + k - 1$ become white. In other words, a square with side equal to $k$ cells and top left corner at $(i, j)$ is colored white.\n\nA white line is a row or a column without any black cells.\n\nGildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser \\textbf{exactly once}. Help Gildong find the answer to his question.",
    "tutorial": "Let's consider a single row that contains at least one black cell. If the first appearance of a black cell is at the $l$-th column and the last appearance of a black cell is at the $r$-th column, we can determine whether it becomes a white line when a certain cell $(i, j)$ is clicked in $O(1)$, after some preprocessing. It becomes a white line if and only if a cell $(i,j)$ is clicked where the row is at $[i,i+k-1]$ and $j \\le l \\le r \\le j+k-1$. We just need to compute $l$ and $r$ in advance. Now let's consider all $n$ rows (not columns). First, count all rows that are already white lines before clicking. Then we count the number of white rows when the cell $(1,1)$ is clicked, by applying the above method to all rows from $1$ to $k$. Ignore the already-white rows that we counted before. So far we obtained the number of white rows when the cell $(1,1)$ is clicked. From now, we slide the window. Add the $k+1$-st row and remove the $1$-st row by applying the same method to them, and we obtain the number of white rows when the cell $(2,1)$ is clicked. We can repeat this until we calculate all $n-k+1$ cases for clicking the cells at the $1$-st column. Then we repeat the whole process for all $n-k+1$ columns. The same process can be done for counting white columns, too. Now we know the number of white rows and white columns when each cell is clicked, so we can find the maximum value among their sums. Time complexity: $O(n^2)$",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1200",
    "index": "E",
    "title": "Compress Words",
    "statement": "Amugae has a sentence consisting of $n$ words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges \"sample\" and \"please\" into \"samplease\".\n\nAmugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.",
    "tutorial": "Denote the words from left to right as $W_1, W_2, W_3, \\cdots, W_n$. If we define string $F(k)$ as the result of merging as described in the problem $k$ times, we can get $F(k+1)$ by the following process: If length of $F(k)$ > length of $W_{k+1}$ Assume the length of $F(K)$ is $x$, and the length of $W_{k+1}$ is $y$. Construct the string $c = W_{k+1} + F(k)[x-y...x]$ ( * $s[x..y]$ for string $s$ is the substring from index $x$ to $y$) Get the KMP failure function from string $c$. We can get maximum overlapped length of $W_{k+1}$'s prefix and $F(k)$'s suffix from this function. Suppose the last element of the failure function smaller than the length of $W_{k+1}$ is $z$. Then the longest overlapped length of $F(k)$'s suffix and $W_{k+1}$'s prefix is $min(z, y)$. Let $L = min(z, y)$. Then, $F(k+1) = F(k) + W_{k+1}[L+1...y]$ Otherwise Construct $c$ as $W_{k+1}[1...x] + F(k)$. We can get $F(k+1)$ from the same process described in 1. In this process, we can get $F(k+1)$ from $F(k)$ in time complexity $O(len(W_{k+1}))$. So, we can get $F(N)$ (the answer of this problem) in $O(len(W_1) + len(W_2) + \\cdots + len(W_N))$.",
    "tags": [
      "brute force",
      "hashing",
      "implementation",
      "string suffix structures",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1200",
    "index": "F",
    "title": "Graph Traveler",
    "statement": "Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of $n$ vertices numbered from $1$ to $n$. The $i$-th vertex has $m_i$ outgoing edges that are labeled as $e_i[0]$, $e_i[1]$, $\\ldots$, $e_i[m_i-1]$, each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The $i$-th vertex also has an integer $k_i$ written on itself.\n\nA travel on this graph works as follows.\n\n- Gildong chooses a vertex to start from, and an integer to start with. Set the variable $c$ to this integer.\n- After arriving at the vertex $i$, or when Gildong begins the travel at some vertex $i$, add $k_i$ to $c$.\n- The next vertex is $e_i[x]$ where $x$ is an integer $0 \\le x \\le m_i-1$ satisfying $x \\equiv c \\pmod {m_i}$. Go to the next vertex and go back to step 2.\n\nIt's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly.\n\nFor example, assume that Gildong starts at vertex $1$ with $c = 5$, and $m_1 = 2$, $e_1[0] = 1$, $e_1[1] = 2$, $k_1 = -3$. Right after he starts at vertex $1$, $c$ becomes $2$. Since the only integer $x$ ($0 \\le x \\le 1$) where $x \\equiv c \\pmod {m_i}$ is $0$, Gildong goes to vertex $e_1[0] = 1$. After arriving at vertex $1$ again, $c$ becomes $-1$. The only integer $x$ satisfying the conditions is $1$, so he goes to vertex $e_1[1] = 2$, and so on.\n\nSince Gildong is quite inquisitive, he's going to ask you $q$ queries. He wants to know how many \\textbf{distinct} vertices will be visited \\textbf{infinitely many times}, if he starts the travel from a certain vertex with a certain value of $c$. Note that you should \\textbf{not} count the vertices that will be visited only finite times.",
    "tutorial": "Since a travel will never end, it is clear that every travel will eventually get into an infinite loop. But we should consider more than just the vertices, since $c$ could be different every time he visits the same vertex. Since the number of outgoing edges of each vertex is at most $10$, we can see a state can be reduced to $lcm(1..10) = 2520$ for each vertex. Therefore, we can think that the graph actually has $2520 \\cdot n$ vertices, each with a single outgoing edge. To simulate the travels, we just need to follow the exact process written in the description, except that $c$ should be kept in modulo $2520$. The problem is when to stop, and how to count the number of distinct vertices that are in the loop. We can stop simulating until we find a state that we already have visited. There can be two cases when we find a visited state. The first case is when we have not visited this state in the previous travels, i.e. this is the first travel that visits this state. We need to check all of the states after the first visit of this state and count the number of distinct vertices. Duplicated vertices can be removed simply by using a set, or more efficiently, using timestamp. Then we can apply the answer to all of the states we visited in this travel. The second case is when the state was visited in one of the previous travels. We know that both the previous travel and the current travel will end in the same loop, so we can apply the same answer to all of the states we visited in this travel. On a side note, the simulation can be done with recursion, but this can lead to maximum of $2520000$ recursion depth. This causes stack overflow or recursion limit excess for some languages (including Java). Time complexity: $O(2520n + q)$",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1201",
    "index": "A",
    "title": "Important Exam",
    "statement": "A class of students wrote a multiple-choice test.\n\nThere are $n$ students in the class. The test had $m$ questions, each of them had $5$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $i$ worth $a_i$ points. Incorrect answers are graded with zero points.\n\nThe students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.",
    "tutorial": "For each of the question let's count the number of answers of different type. Let $cnt[i][A]=$The number of A answers to the i-th question. The maximum score for that answer is $a[i]\\cdot max(cnt[i][A], cnt[i][B], cnt[i][C], cnt[i][D], cnt[i][E])$. The answer is the sum of the maximum answer for the $m$ questions.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll n, m;\nstring s[1005];\nll a[1005];\nll ans;\nll b[1005][5];\nll ma;\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin>>n>>m;\n    for (ll i=1; i<=n; i++)\n    {\n        cin>>s[i];\n    }\n    for (ll i=0; i<m; i++)\n    {\n        cin>>a[i];\n    }\n    for (ll i=0; i<m; i++)\n    {\n        ma=0;\n        for (ll j=1; j<=n; j++)\n        {\n            b[i][s[j][i]-'A']++;\n        }\n        for (ll j=0; j<5; j++)\n        {\n            ma=max(ma, b[i][j]);\n        }\n        ans+=ma*a[i];\n    }\n    cout<<ans;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1201",
    "index": "B",
    "title": "Zero Array",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$.\n\nIn one operation you can choose two elements $a_i$ and $a_j$ ($i \\ne j$) and decrease each of them by one.\n\nYou need to check whether it is possible to make all the elements equal to zero or not.",
    "tutorial": "There are 2 things needed to be possible to make all elements zero: 1: The sum of the elements must be even. 2: The biggest element have to be less or equal than the sum of all the other elements. If both are true, the answer is \"YES\", otherwise \"NO\".",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll n, m, a, s;\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin>>n;\n    for (ll i=1; i<=n; i++)\n    {\n        cin>>a;\n        s+=a;\n        m=max(m, a);\n    }\n    if (s%2==1 || s<2*m)\n    {\n        cout<<\"NO\";\n        return 0;\n    }\n    cout<<\"YES\";\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1201",
    "index": "C",
    "title": "Maximum Median",
    "statement": "You are given an array $a$ of $n$ integers, where $n$ is odd. You can make the following operation with it:\n\n- Choose one of the elements of the array (for example $a_i$) and increase it by $1$ (that is, replace it with $a_i + 1$).\n\nYou want to make the median of the array the largest possible using at most $k$ operations.\n\nThe median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $[1, 5, 2, 3, 5]$ is $3$.",
    "tutorial": "Sort the array in non-decreasing order. In the new array $b_1, b_2, \\ldots, b_n$ you can make binary search with the maximum median value. For a given median value ($x$), it is required to make $\\sum_{i=(n+1)/2}^{n} max(0,x-b_i)$ operations. If this value is more than $k$, $x$ can't be median, otherwise it can. Time complexity: $O((n/2) \\cdot log(10^9))$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll n, k;\nll x;\nvector < ll > a;\nbool check(ll x)\n{\n    ll moves=0;\n    for (int i=n/2; i<n; i++)\n    {\n        if (x-a[i]>0) moves+=x-a[i];\n        if (moves>k) return false;\n    }\n    if (moves<=k) return true;\n    else return false;\n}\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin>>n>>k;\n    for (int i=1; i<=n; i++)\n    {\n        cin>>x;\n        a.push_back(x);\n    }\n    sort(a.begin(), a.end());\n    ll small=1;\n    ll big=2000000000;\n    while (small!=big)\n    {\n        ll mid=(small+big+1)/2;\n        if (check(mid))\n        {\n            small=mid;\n        }\n        else{\n            big=mid-1;\n        }\n    }\n    cout<<small;\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1201",
    "index": "D",
    "title": "Treasure Hunting",
    "statement": "You are on the island which can be represented as a $n \\times m$ table. The rows are numbered from $1$ to $n$ and the columns are numbered from $1$ to $m$. There are $k$ treasures on the island, the $i$-th of them is located at the position $(r_i, c_i)$.\n\nInitially you stand at the lower left corner of the island, at the position $(1, 1)$. If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from $(r, c)$ to $(r+1, c)$), left (from $(r, c)$ to $(r, c-1)$), or right (from position $(r, c)$ to $(r, c+1)$). Because of the traps, you can't move down.\n\nHowever, moving up is also risky. You can move up only if you are in a safe column. There are $q$ safe columns: $b_1, b_2, \\ldots, b_q$. You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures.",
    "tutorial": "Make two arrays: left and right. $left[i]$ is the treasure in the leftmost position in row i (0 if there are no treasures in row $i$). $right[i]$ is the treasure in the rightmost cell in row $i$ (0 if there are no treasures in row $i$). We can simply take out rows where there is no treasure (and add 1 to the result if there are treasure above that line, because we have to move up there). For every row, except the last, we have to leave that row at one of the safe columns. Let's notice that the last treasure we collect in the row will be either $left[i]$ or $right[i]$. Let's take a look at both possibilities: If we collect the $left[i]$ treasure last, we have to leave the row either going left or going right to the closest safe column, because going further wouldn't worth it (consider moving up earlier and keep doing the same thing at row $i+1$). The same is true for $right[i]$. For the first row, we start at the first column, we can calculate the moves required to go up the second row at the for cells. For all the other rows, we have 4 possibilities, and we have to calculate how many moves it takes to reach the row $i+1$ at the 4 possible columns. For the last row, we don't have to reach a safe column, we just have to collect all the treasures there. We can count the answer for the problem from the calculated results from the previous row. Time complexity: $O(16*n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll n, m, k, q;\nll tleft[300005];\nll tright[300005];\nll safeleft[300005];\nll saferight[300005];\nll a[300005][4];\nll b[4];\nll ans;\nvector < ll > safe;\nll dis(ll pa, ll pb)\n{\n    return abs(pa-pb);\n}\nll solve(ll i, ll x, ll y)\n{\n    ll ansa=dis(x, tright[i]);\n    ansa+=dis(tright[i], tleft[i]);\n    ansa+=dis(tleft[i], y);\n    ll ansb=dis(x, tleft[i]);\n    ansb+=dis(tright[i], tleft[i]);\n    ansb+=dis(tright[i], y);\n    return 1+min(ansa, ansb);\n}\nll solvelast(ll x)\n{\n    ll ansa=dis(x, tright[n]);\n    ansa+=dis(tright[n], tleft[n]);\n    ll ansb=dis(x, tleft[n]);\n    ansb+=dis(tright[n], tleft[n]);\n    return 1+min(ansa, ansb);\n}\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin>>n>>m>>k>>q;\n    ll x=0, y=0;\n    for (ll i=1; i<=k; i++)\n    {\n        cin>>x>>y;\n        if (tleft[x]==0) tleft[x]=y;\n        tleft[x]=min(tleft[x], y);\n        tright[x]=max(tright[x], y);\n    }\n    for (ll i=1; i<=q; i++)\n    {\n        cin>>x;\n        safe.push_back(x);\n    }\n    sort(safe.begin(), safe.end());\n    for (ll j=1; j<=safe[0]; j++)\n    {\n        saferight[j]=safe[0];\n    }\n    for (ll j=safe[0]; j<safe[1]; j++)\n    {\n        safeleft[j]=safe[0];\n    }\n    for (ll i=1; i<safe.size()-1; i++)\n    {\n        for (ll j=safe[i-1]+1; j<=safe[i]; j++)\n        {\n            saferight[j]=safe[i];\n        }\n        for (ll j=safe[i]; j<safe[i+1]; j++)\n        {\n            safeleft[j]=safe[i];\n        }\n    }\n    for (ll j=safe[safe.size()-2]+1; j<=safe[safe.size()-1]; j++)\n    {\n        saferight[j]=safe[safe.size()-1];\n    }\n    for (ll j=safe[safe.size()-1]; j<=m; j++)\n    {\n        safeleft[j]=safe[safe.size()-1];\n    }\n    while (tleft[n]==0)\n    {\n        n--;\n    }\n    if (n==1)\n    {\n        cout<<tright[1]-1;\n        return 0;\n    }\n    if (tright[1]==0)\n    {\n        a[1][0]=saferight[1]-1;\n        b[0]=saferight[1];\n    }\n    else{\n            if (safeleft[tright[1]]!=0)\n            {\n                a[1][0]=tright[1]-1+dis(tright[1], safeleft[tright[1]]);\n                b[0]=safeleft[tright[1]];\n            }\n            if (saferight[tright[1]]!=0)\n            {\n                a[1][1]=tright[1]-1+dis(tright[1], saferight[tright[1]]);\n                b[1]=saferight[tright[1]];\n            }\n    }\n    for (ll i=2; i<n; i++)\n    {\n        ll c[4];\n        if (tright[i]==0)\n        {\n            for (ll j=0; j<4; j++)\n            {\n            a[i][j]=a[i-1][j]+1;\n            }\n            continue;\n        }\n        c[0]=safeleft[tleft[i]];\n        c[1]=saferight[tleft[i]];\n        c[2]=safeleft[tright[i]];\n        c[3]=saferight[tright[i]];\n        for (ll p=0; p<4; p++)\n        {\n            a[i][p]=INT_MAX;\n            a[i][p]*=a[i][p];\n        }\n        for (ll j=0; j<4; j++)\n        {\n            if (b[j]!=0)\n            {\n                for (ll p=0; p<4; p++)\n                {\n                    if (c[p]!=0)\n                    {\n                        a[i][p]=min(a[i][p], a[i-1][j]+solve(i, b[j], c[p]));\n                    }\n                }\n            }\n        }\n        for (ll j=0; j<4; j++)\n        {\n            b[j]=c[j];\n        }\n    }\n    ans=INT_MAX;\n    ans*=ans;\n    for (ll j=0; j<4; j++)\n    {\n        if (b[j]!=0)\n        {\n            ans=min(ans, a[n-1][j]+solvelast(b[j]));\n        }\n    }\n    cout<<ans;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1201",
    "index": "E2",
    "title": "Knightmare (hard)",
    "statement": "This is an interactive problem.\n\nAlice and Bob are playing a game on the chessboard of size $n \\times m$ where $n$ and $m$ are \\textbf{even}. The rows are numbered from $1$ to $n$ and the columns are numbered from $1$ to $m$. There are two knights on the chessboard. A white one initially is on the position $(x_1, y_1)$, while the black one is on the position $(x_2, y_2)$. Alice will choose one of the knights to play with, and Bob will use the other one.\n\nThe Alice and Bob will play in turns and whoever controls \\textbf{the white} knight starts the game. During a turn, the player must move their knight adhering the chess rules. That is, if the knight is currently on the position $(x, y)$, it can be moved to any of those positions (as long as they are inside the chessboard):\n\n\\begin{center}\n$(x+1, y+2)$, $(x+1, y-2)$, $(x-1, y+2)$, $(x-1, y-2)$,$(x+2, y+1)$, $(x+2, y-1)$, $(x-2, y+1)$, $(x-2, y-1)$.\n\\end{center}\n\nWe all know that knights are strongest in the middle of the board. Both knight have a single position they want to reach:\n\n- the owner of the white knight wins if it captures the black knight or if the white knight is at $(n/2, m/2)$ and this position is not under attack of the black knight at this moment;\n- The owner of the black knight wins if it captures the white knight or if the black knight is at $(n/2+1, m/2)$ and this position is not under attack of the white knight at this moment.\n\nFormally, the player who captures the other knight wins. The player who is at its target square ($(n/2, m/2)$ for white, $(n/2+1, m/2)$ for black) and this position is not under opponent's attack, also wins.\n\nA position is under attack of a knight if it can move into this position. Capturing a knight means that a player moves their knight to the cell where the opponent's knight is.\n\nIf Alice made $350$ moves and nobody won, the game is a draw.\n\nAlice is unsure in her chess skills, so she asks you for a help. Choose a knight and win the game for her. It can be shown, that Alice always has a winning strategy.",
    "tutorial": "First calculate the number of moves needed to reach (without capturing) positions $(a_1;b_1)$ and $(a_2;b_2)$. If one of the knights can reach it's goal at least 2 moves faster than the other can and faster than the other can reach it's goal, than there is a winning strategy with it. Just go the shortest path. The other knight won't be able to capture your knight, because after you move you are $x$ moves away from it, than the other knight must be at least $x+2$ far, so it will be at least $x+1$ after it's move. If one of the knights can reach it's goal at exactly 1 move faster than the other can and faster than the other can reach it's goal, we have to count the moves needed to reach all the positions which is 1 move away from the goal. If there is a position from these which can be reached at least 2 moves faster, than that knight can win. Let's color the chessboard the regular way with white and black colors. If the 2 knights are in same color, than only the black knight can capture the white, otherwise only the white can capture the black (that is because knights always move to different color than they come from). In all the other situation there is at least drawing strategy with the knight that can capture the other: Move to the position that the other knight have to reach and stay there or 1 move away from it. The other knight won't be able to reach that position without getting captured. So we choose that knight and search for the winning strategy. You can win the game in 2 steps: First: Go to your opponent's target cell in the fastest way (if the opponent could go there faster, you can still outrun him, because there is no position which is 1 move away from the opponents goal and can be reached at least 2 moves faster (we already looked that situation), so you can take away the opponent's possibility to reach the target by threatening with capturing their knight). This is maximum of 333 moves. Second: Go from there to your target cell on the fastest way. It can be easily shown that it takes 3 moves to go there. When you are in the opponent's target position your opponent can be either exactly 1 move or at least 3 moves away from you (because the distance (in moves) between you and your opponent's knight after your opponent's turn is always odd). If it is 1 move away, you can capture his knight, if at least 3 or moves away from you (and therefore the target position), you can reach your target faster than your opponent. That's a total of 336 moves.",
    "code": "/**\n * This line was copied from template\n * This is nk_n4.cpp\n *\n * @author: Nikolay Kalinin\n * @date: Sun, 04 Aug 2019 03:59:47 +0300\n */\n#include <bits/stdc++.h>\n \nusing namespace std;\n \n#ifdef LOCAL\n    #define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n    #define eprintf(...) 42\n#endif\n \nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \nconst int maxn = 45;\n \nconst int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};\nconst int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};\n \nint n, m, xw, yw, xb, yb, mode;\nbool isterm[maxn][maxn][maxn][maxn][2];\nbool wins[maxn][maxn][maxn][maxn][2];\nint remmoves[maxn][maxn][maxn][maxn][2];\nint dist[maxn][maxn][maxn][maxn][2];\nvector<array<int, 6>> terms;\nint moves[maxn][maxn];\nint cntpos = 0;\n \nvoid markterm(int x1, int y1, int x2, int y2, int turn, int res)\n{\n    if (isterm[x1][y1][x2][y2][turn]) return;\n    isterm[x1][y1][x2][y2][turn] = true;\n    dist[x1][y1][x2][y2][turn] = 0;\n    terms.pb({x1, y1, x2, y2, turn, res});\n}\n \nvoid mark(int x1, int y1, int x2, int y2, int turn, int res)\n{\n    cntpos++;\n    wins[x1][y1][x2][y2][turn] = res;\n    isterm[x1][y1][x2][y2][turn] = true;\n    dist[x1][y1][x2][y2][turn]++;\n    if (turn == 1) // now second moves, previous move made first\n    {\n        for (int d = 0; d < 8; d++)\n        {\n            int nx = x1 + dx[d];\n            int ny = y1 + dy[d];\n            if (1 <= nx && nx <= n && 1 <= ny && ny <= m && !isterm[nx][ny][x2][y2][1 - turn])\n            {\n                if (res == 0)\n                {\n                    dist[nx][ny][x2][y2][1 - turn] = dist[x1][y1][x2][y2][turn];\n                    mark(nx, ny, x2, y2, 1 - turn, true);\n                } else\n                {\n                    remmoves[nx][ny][x2][y2][1 - turn]--;\n                    dist[nx][ny][x2][y2][1 - turn] = max(dist[nx][ny][x2][y2][1 - turn], dist[x1][y1][x2][y2][turn]);\n                    if (remmoves[nx][ny][x2][y2][1 - turn] == 0)\n                    {\n                        mark(nx, ny, x2, y2, 1 - turn, false);\n                    }\n                }\n            }\n        }\n    } else\n    {\n        for (int d = 0; d < 8; d++)\n        {\n            int nx = x2 + dx[d];\n            int ny = y2 + dy[d];\n            if (1 <= nx && nx <= n && 1 <= ny && ny <= m && !isterm[x1][y1][nx][ny][1 - turn])\n            {\n                if (res == 0)\n                {\n                    dist[x1][y1][nx][ny][1 - turn] = dist[x1][y1][x2][y2][turn];\n                    mark(x1, y1, nx, ny, 1 - turn, true);\n                } else\n                {\n                    remmoves[x1][y1][nx][ny][1 - turn]--;\n                    dist[x1][y1][nx][ny][1 - turn] = max(dist[x1][y1][nx][ny][1 - turn], dist[x1][y1][x2][y2][turn]);\n                    if (remmoves[x1][y1][nx][ny][1 - turn] == 0)\n                    {\n                        mark(x1, y1, nx, ny, 1 - turn, false);\n                    }\n                }\n            }\n        }\n    }\n}\n \ninline bool canmove(int x1, int y1, int x2, int y2)\n{\n    return minmax(abs(x1 - x2), abs(y1 - y2)) == minmax(1, 2);\n}\n \nbool won()\n{\n    if (xw == xb && yw == yb) return true;\n    if (mode == 0)\n    {\n        return xw == n / 2 && yw == m / 2 && !canmove(xw, yw, xb, yb);\n    } else\n    {\n        return xb == n / 2 + 1 && yb == m / 2 && !canmove(xw, yw, xb, yb);\n    }\n}\n \nint main()\n{\n    scanf(\"%d%d\", &n, &m);\n    for (int x1 = 1; x1 <= n; x1++)\n    {\n        for (int y1 = 1; y1 <= m; y1++)\n        {\n            moves[x1][y1] = 0;\n            for (int d = 0; d < 8; d++)\n            {\n                int nx = x1 + dx[d];\n                int ny = y1 + dy[d];\n                if (1 <= nx && nx <= n && 1 <= ny && ny <= m) moves[x1][y1]++;\n            }\n        }\n    }\n    for (int x1 = 1; x1 <= n; x1++)\n    {\n        for (int y1 = 1; y1 <= m; y1++)\n        {\n            for (int x2 = 1; x2 <= n; x2++)\n            {\n                for (int y2 = 1; y2 <= m; y2++)\n                {\n                    remmoves[x1][y1][x2][y2][0] = moves[x1][y1];\n                    remmoves[x1][y1][x2][y2][1] = moves[x2][y2];\n                }\n            }\n        }\n    }\n    for (int x1 = 1; x1 <= n; x1++)\n    {\n        for (int y1 = 1; y1 <= m; y1++)\n        {\n            if (x1 != n / 2 || y1 != m / 2)\n            {\n                if (!canmove(x1, y1, n / 2, m / 2)) markterm(n / 2, m / 2, x1, y1, 1, false);\n                markterm(n / 2, m / 2, x1, y1, 0, true);\n            }\n            if (x1 != n / 2 + 1 || y1 != m / 2)\n            {\n                if (!canmove(x1, y1, n / 2 + 1, m / 2)) markterm(x1, y1, n / 2 + 1, m / 2, 0, false);\n                markterm(x1, y1, n / 2 + 1, m / 2, 1, true);\n            }\n            markterm(x1, y1, x1, y1, 0, false);\n            markterm(x1, y1, x1, y1, 1, false);\n        }\n    }\n    for (auto &t : terms)\n    {\n        mark(t[0], t[1], t[2], t[3], t[4], t[5]);\n    }\n \n    assert(cntpos == n * m * n * m * 2);\n \n    scanf(\"%d%d\", &xw, &yw);\n    scanf(\"%d%d\", &xb, &yb);\n    if (wins[xw][yw][xb][yb][0]) mode = 0;\n    else mode = 1;\n    if (mode == 0) cout << \"WHITE\" << endl;\n    else cout << \"BLACK\" << endl;\n    for (int IT = 0; ; IT++)\n    {\n        if (IT % 2 == mode)\n        {\n            if (mode == 0)\n            {\n                for (int d = 0; d < 8; d++)\n                {\n                    int nx = xw + dx[d];\n                    int ny = yw + dy[d];\n                    if (nx >= 1 && nx <= n && ny >= 1 && ny <= m &&\n                        !wins[nx][ny][xb][yb][1] && dist[nx][ny][xb][yb][1] < dist[xw][yw][xb][yb][0])\n                    {\n                        cout << nx << ' ' << ny << endl;\n                        xw = nx;\n                        yw = ny;\n                        break;\n                    }\n                }\n            } else\n            {\n                for (int d = 0; d < 8; d++)\n                {\n                    int nx = xb + dx[d];\n                    int ny = yb + dy[d];\n                    if (nx >= 1 && nx <= n && ny >= 1 && ny <= m &&\n                        !wins[xw][yw][nx][ny][0] && dist[xw][yw][nx][ny][0] < dist[xw][yw][xb][yb][1])\n                    {\n                        cout << nx << ' ' << ny << endl;\n                        xb = nx;\n                        yb = ny;\n                        break;\n                    }\n                }\n            }\n        } else\n        {\n            int xx, yy;\n            cin >> xx >> yy;\n            if (mode == 0) xb = xx, yb = yy;\n            else xw = xx, yw = yy;\n        }\n        if (won()) break;\n    }\n    return 0;\n}",
    "tags": [
      "graphs",
      "interactive",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1202",
    "index": "A",
    "title": "You Are Given Two Binary Strings...",
    "statement": "You are given two binary strings $x$ and $y$, which are binary representations of some two integers (let's denote these integers as $f(x)$ and $f(y)$). You can choose any integer $k \\ge 0$, calculate the expression $s_k = f(x) + f(y) \\cdot 2^k$ and write the binary representation of $s_k$ in \\textbf{reverse order} (let's denote it as $rev_k$). For example, let $x = 1010$ and $y = 11$; you've chosen $k = 1$ and, since $2^1 = 10_2$, so $s_k = 1010_2 + 11_2 \\cdot 10_2 = 10000_2$ and $rev_k = 00001$.\n\nFor given $x$ and $y$, you need to choose such $k$ that $rev_k$ is \\textbf{lexicographically minimal} (read notes if you don't know what does \"lexicographically\" means).\n\nIt's guaranteed that, with given constraints, $k$ exists and is finite.",
    "tutorial": "Multiplying by power of $2$ is \"shift left\" binary operation (you, probably, should know it). Reverse $x$ and $y$ for the simplicity and look at leftmost $1$ in $y$ (let's denote its position as $pos_y$). If you move it to $0$ in $x$ then you make the $rev_k$ lexicographically bigger than the reverse of $x$. So you should move it to $1$ in $x$ too. You can choose any $1$ with position $\\ge pos_y$. Let $pos_x$ be the minimum position of $1$ in $x$, such that $pos_x \\ge pos_y$. You must move $pos_y$ to $pos_x$, otherwise the $1$ in $pos_x$ still be present in $rev_k$ and it will be not optimal. So, the solution is next: reverse $x$ and $y$, find $pos_y$, find $pos_x \\ge pos_y$, print $pos_x - pos_y$.",
    "code": "fun main(args: Array<String>) {\n    val T = readLine()!!.toInt()\n    for (tc in 1..T) {\n        val x = readLine()!!.reversed()\n        val y = readLine()!!.reversed()\n\n        val posY = y.indexOf('1')\n        val posX = x.indexOf('1', posY)\n        println(posX - posY)\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1202",
    "index": "B",
    "title": "You Are Given a Decimal String...",
    "statement": "Suppose you have a special $x$-$y$-counter. This counter can store some value as a decimal number; at first, the counter has value $0$.\n\nThe counter performs the following algorithm: it prints its lowest digit and, after that, adds either $x$ or $y$ to its value. So all sequences this counter generates are starting from $0$. For example, a $4$-$2$-counter can act as follows:\n\n- it prints $0$, and adds $4$ to its value, so the current value is $4$, and the output is $0$;\n- it prints $4$, and adds $4$ to its value, so the current value is $8$, and the output is $04$;\n- it prints $8$, and adds $4$ to its value, so the current value is $12$, and the output is $048$;\n- it prints $2$, and adds $2$ to its value, so the current value is $14$, and the output is $0482$;\n- it prints $4$, and adds $4$ to its value, so the current value is $18$, and the output is $04824$.\n\nThis is only one of the possible outputs; for example, the same counter could generate $0246802468024$ as the output, if we chose to add $2$ during each step.\n\nYou wrote down a printed sequence from one of such $x$-$y$-counters. But the sequence was corrupted and several elements from the sequence could be erased.\n\nNow you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string $s$ — the remaining data of the sequence.\n\nFor all $0 \\le x, y < 10$, calculate the minimum number of digits you have to insert in the string $s$ to make it a possible output of the $x$-$y$-counter. Note that you can't change the order of digits in string $s$ or erase any of them; only insertions are allowed.",
    "tutorial": "All you need to know to solve this task is the minimal number of steps to move from any digit $a$ to any digit $b$ for fixed $x$ and $y$ (let's denote it as $ds[a][b]$). Shortest path? BFS? Floyd? Of course, you can use it, but you can think a little harder and save nerves and time. Since order of choosing operations $x$ and $y$ doesn't matter for transferring from $a$ to $b$, so only number of $x$-s and $y$-s are matter. Let's denote them as $cnt_x$ and $cnt_y$. Since adding any fixed value $10$ times are meaningless, so $cnt_x, cnt_y < 10$. Now you can, for each $x < 10$, for each $y < 10$, for each $a < 10$ iterate over all possible $cnt_x < 10$ and $cnt_y < 10$. Digit $b$ you'd move to is equal to $(a + cnt_x \\cdot x + cnt_y \\cdot y) \\mod 10$. Just relax value of $ds[a][b]$ by $cnt_x + cnt_y$. Now you can, for each $x$ and $y$, calculate the answer by iterating over string $s$ by summing $ds[s[i]][s[i + 1]] - 1$ (number of inserted values is less by one than number of steps). But, it will work only in C++, since the language is fast and $2 \\cdot 10^8$ basic operations are executed in less than 0.5 second. But the model solution is written in Kotlin. How is it? The string $s$ can be long, but there are only $10 \\times 10$ different neighbouring digits, so you can just one time precalculate $cf[a][b]$ - the number of such $i$ that $s[i] = a$ and $s[i + 1] = b$. And calculate the answer not by iterating over $s$ but by multiplying $ds[a][b]$ by $cf[a][b]$. The result complexity is $O(|s| + A^5)$, where $A = 10$. But $O(A^2(n + A^3))$ will pass on fast languages like C++. P.S.: There are no real problem with I/O - both Python and Kotlin read one string up to $2 \\cdot 10^6$ in less than 0.5 seconds.",
    "code": "const val INF = 1e9.toInt()\n\nfun main(args: Array<String>) {\n    val s = readLine()!!.map { it - '0' }\n    val cf = Array(10) {Array(10) {0}}\n    for (i in 1 until s.size)\n        cf[s[i - 1]][s[i]]++\n\n    for (x in 0..9) {\n        for (y in 0..9) {\n            val ds = Array(10) {Array(10) {INF + 7}}\n\n            for (v in 0..9) {\n                for (cx in 0..9) {\n                    for (cy in 0..9) {\n                        if (cx + cy == 0)\n                            continue\n\n                        val to = (v + cx * x + cy * y) % 10\n                        ds[v][to] = minOf(ds[v][to], cx + cy)\n                    }\n                }\n            }\n\n            var res = 0\n            for (v in 0..9) {\n                for (to in 0..9) {\n                    if (ds[v][to] > INF && cf[v][to] > 0) {\n                        res = -1\n                        break\n                    }\n                    res += (ds[v][to] - 1) * cf[v][to]\n                }\n                if (res == -1)\n                    break\n            }\n\n            print(\"$res \")\n        }\n        println()\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1202",
    "index": "C",
    "title": "You Are Given a WASD-string...",
    "statement": "You have a string $s$ — a sequence of commands for your toy robot. The robot is placed in some cell of a \\textbf{rectangular} grid. He can perform four commands:\n\n- 'W' — move one cell up;\n- 'S' — move one cell down;\n- 'A' — move one cell left;\n- 'D' — move one cell right.\n\nLet $Grid(s)$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $s$. For example, if $s = \\text{DSAWWAW}$ then $Grid(s)$ is the $4 \\times 3$ grid:\n\n- you can place the robot in the cell $(3, 2)$;\n- the robot performs the command 'D' and moves to $(3, 3)$;\n- the robot performs the command 'S' and moves to $(4, 3)$;\n- the robot performs the command 'A' and moves to $(4, 2)$;\n- the robot performs the command 'W' and moves to $(3, 2)$;\n- the robot performs the command 'W' and moves to $(2, 2)$;\n- the robot performs the command 'A' and moves to $(2, 1)$;\n- the robot performs the command 'W' and moves to $(1, 1)$.\n\nYou have $4$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert \\textbf{at most one of these letters} in any position of sequence $s$ to minimize the area of $Grid(s)$.\n\nWhat is the minimum area of $Grid(s)$ you can achieve?",
    "tutorial": "The problem asks us to maintain the bounding box while inserting the character of one of $4$ types between every adjacent characters in $s$. Of course, we can do it, but do we really need to do it in such cumbersome way? Let's think a little. Inserting 'W' or 'S' doesn't affect the width of the bounding box, and 'A' or 'D' doesn't affect the height. So, they are absolutely independent! And we can divide our WASD-string on WS-string and AD-string. Moreover, inserting 'W' or 'S' in WS-string and 'A' or 'D' in AD-string is almost same thing, so we don't even need to write different code for different string! How to handle only WS-string? Let's replace 'W' as $+1$ and 'S' as $-1$ and suppose that we started in position $0$. Then the position, where we go after $i$ commands, is just prefix sum of first $i$ elements ($i \\ge 0$). Then the length of the bounding box is (maximum position - minimum position + 1). The maximum (minimum) position is a maximum (minimum) element in array of prefix sums $pSum$. What the inserted value do? It add $\\pm 1$ to suffix of $pSum$. Let's choose, for example, $+1$. The $+1$ can't decrease the maximum, but can increase the minimum, so we need to place it somewhere before all minimums in $pSum$ (or before the first minimum). But, if we place it before any of maximum elements then we will increase it and prevent decreasing the length of bounding box. So we need to place $+1$ somewhere after all maximums on $pSum$ (or after the last maximum). And here goes the solution: find position $firstMin$ of the first minimum in $pSum$ and position $lastMax$ of the last maximum. If $lastMax < firstMin$ then we can insert $+1$ and decrease the length of bounding box (but, since, we insert command that move robot, we can't achieve bounding box of length $< 2$). What to do with $-1$? Just multiply $pSum$ by $-1$ and now we can insert $+1$ instead of $-1$ in absolutely same manner. What to do with AD-string? Denote 'A' as $+1$ and 'D' as $-1$ and everything is absolutely the same.",
    "code": "const val INF = 1e9.toInt()\n\nfun main(args: Array<String>) {\n    val T = readLine()!!.toInt()\n    for (tc in 1..T) {\n        val s = readLine()!!\n        val alp = arrayOf(\"WS\", \"AD\")\n        val aDir = arrayOf(\n                s.filter { alp[0].indexOf(it) != -1 },\n                s.filter { alp[1].indexOf(it) != -1 }\n        )\n\n        val baseW = arrayOf(INF, INF)\n        val bestW = arrayOf(INF, INF)\n\n        for (k in 0..1) {\n            val pSum = arrayListOf(0)\n            for (c in aDir[k]) {\n                val add = if (c == alp[k][0]) +1 else -1\n                pSum.add(pSum.last() + add)\n            }\n\n            for (tp in 0..1) {\n                val firstMin = pSum.withIndex().minBy { it.value }!!.index\n                val lastMax = pSum.withIndex().reversed().maxBy { it.value }!!.index\n\n                val curBase = pSum[lastMax] - pSum[firstMin] + 1\n                var curBest = curBase\n                if (curBase > 2 && lastMax < firstMin)\n                    --curBest\n\n                baseW[k] = minOf(baseW[k], curBase)\n                bestW[k] = minOf(bestW[k], curBest)\n\n                for (i in pSum.indices)\n                    pSum[i] = -pSum[i]\n            }\n        }\n\n        println(\"${minOf(baseW[0] * 1L * bestW[1], baseW[1] * 1L * bestW[0] )}\")\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1202",
    "index": "D",
    "title": "Print a 1337-string...",
    "statement": "The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.\n\nYou are given an integer $n$.\n\nYou have to find a sequence $s$ consisting of digits $\\{1, 3, 7\\}$ such that it has exactly $n$ subsequences equal to $1337$.\n\nFor example, sequence $337133377$ has $6$ subsequences equal to $1337$:\n\n- $337\\underline{1}3\\underline{3}\\underline{3}7\\underline{7}$ (you can remove the second and fifth characters);\n- $337\\underline{1}\\underline{3}3\\underline{3}7\\underline{7}$ (you can remove the third and fifth characters);\n- $337\\underline{1}\\underline{3}\\underline{3}37\\underline{7}$ (you can remove the fourth and fifth characters);\n- $337\\underline{1}3\\underline{3}\\underline{3}\\underline{7}7$ (you can remove the second and sixth characters);\n- $337\\underline{1}\\underline{3}3\\underline{3}\\underline{7}7$ (you can remove the third and sixth characters);\n- $337\\underline{1}\\underline{3}\\underline{3}3\\underline{7}7$ (you can remove the fourth and sixth characters).\n\n\\textbf{Note that the length of the sequence $s$ must not exceed $10^5$.}\n\nYou have to answer $t$ independent queries.",
    "tutorial": "Let's consider the following string $1333 \\dots 3337$. If digit $3$ occurs $x$ times in it, then string have $\\frac{x (x-1)}{2}$ subsequences $1337$. Let's increase the number of digits $3$ in this string while condition $\\frac{x (x-1)}{2} \\le n$ holds ($x$ is the number of digits $3$ in this string). The length of this string will not exceed $45000$ because $\\frac{45000 (45000-1)}{2} > 10^9$. The value $rem = n - \\frac{x (x-1)}{2}$ will not exceed $45000$ as well. All we have to do is increase the number of subsequences $1337$ in the current string by $rem$. So if we add $rem$ digits $7$ after the first two digits $3$ we increase the number of subsequences $1337$ by $rem$. The string $s$ will look like this: $133{77 \\dots 77}{33 \\dots 33}7$, where sequence ${77\\dots77}$ consists of exactly $rem$ digits $7$ and sequence ${33\\dots33}$ consists of exactly $x-2$ digits $3$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    for(int tc = 0; tc < t; ++tc){\n    \tint n;\n    \tcin >> n;\n    \tint len = 2;\n    \twhile(len * (len + 1) / 2 <= n)\n    \t\t++len;\n    \n    \tn -= len * (len - 1) / 2;\n    \tassert(n >= 0);\n    \tassert(n <= 45000);\n    \t\n    \tstring s = \"133\";\n    \twhile(n > 0){\n    \t\t--n;\n    \t\ts += \"7\";\n    \t}\n    \n    \tlen -= 2;\n    \twhile(len > 0){\n    \t\t--len;\n    \t\ts += \"3\";\n    \t}\n    \ts += \"7\";\n    \tcout << s << endl;\n    }\n\treturn 0;\n} ",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1202",
    "index": "E",
    "title": "You Are Given Some Strings...",
    "statement": "You are given a string $t$ and $n$ strings $s_1, s_2, \\dots, s_n$. All strings consist of lowercase Latin letters.\n\nLet $f(t, s)$ be the number of occurences of string $s$ in string $t$. For example, $f('\\text{aaabacaa}', '\\text{aa}') = 3$, and $f('\\text{ababa}', '\\text{aba}') = 2$.\n\nCalculate the value of $\\sum\\limits_{i=1}^{n} \\sum\\limits_{j=1}^{n} f(t, s_i + s_j)$, where $s + t$ is the concatenation of strings $s$ and $t$. Note that if there are two pairs $i_1$, $j_1$ and $i_2$, $j_2$ such that $s_{i_1} + s_{j_1} = s_{i_2} + s_{j_2}$, you should include both $f(t, s_{i_1} + s_{j_1})$ and $f(t, s_{i_2} + s_{j_2})$ in answer.",
    "tutorial": "Let's look at any occurrence of arbitrary pair $s_i + s_j$. There is exactly one special split position, where the $s_i$ ends and $s_j$ starts. So, instead of counting occurrences for each pair, we can iterate over the position of split and count the number of pairs. This transformation is convenient, since any $s_i$, which ends in split position can be paired with any $s_j$ which starts here. So, all we need is to calculate for each suffix the number of strings $s_i$, which starts here, and for each prefix - the number of strings $s_i$, which ends here. But calculating the prefixes can be transformed to calculating suffixes by reversing both $t$ and all $s_i$. Now we need, for each position $pos$, calculate the number of strings $s_i$ which occur from $pos$. It can be done by Aho-Corasick, Suffix Array, Suffix Automaton, Suffix Tree, but do we really need them since constrains are pretty low? The answer is NO. We can use sqrt-heuristic! Let's divide all $s_i$ in two groups: short and long. The $s_i$ is short if $|s_i| \\le MAG$. There are no more than $\\frac{\\sum{|s_i|}}{MAG}$ long strings and, for each such string, we can find all its occurrences with z-function (or prefix-function). It will cost as $O(\\frac{\\sum{|s_i|}}{MAG} \\cdot |t| + \\sum{|s_i|})$. What to do with short strings? Let's add them to trie! The trie will have $O(\\sum{|s_i|})$ vertices, but only $MAG$ depth. So we can, for each $pos$, move down through the trie, while counting the occurrences, using only $s[pos..(pos + MAG)]$ substring. It will cost us $O(|t| \\cdot MAG)$. So, if we choose $MAG = \\sqrt{\\sum{|s_i|}}$ we can acquire $O(\\sum{|s_i|} + |t| \\sqrt{\\sum{|s_i|}})$ complexity, using only basic string structures.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) fore(i, 0, n)\n\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9) + 7;\nconst li INF64 = li(1e18) + 7;\n\nconst int N = 500005;\nconst int A = 27;\nconst int MAG = 500;\n\nstruct node {\n    node *to[A];\n    int cnt;\n} nodes[N];\nint szn = 0;\n\ntypedef node* vt;\n\nvt getNode() {\n    assert(szn < N);\n    fore(i, 0, A)\n        nodes[szn].to[i] = NULL;\n    nodes[szn].cnt = 0;\n    return &nodes[szn++];\n}\n\nvoid addWord(vt v, const string &s) {\n    fore(i, 0, sz(s)) {\n        int c = s[i] - 'a';\n        if (!v->to[c])\n            v->to[c] = getNode();\n        v = v->to[c];\n    }\n    v->cnt++;\n}\n\nint calcCnt(vt v, const string &s, int pos) {\n    assert(v->cnt == 0);\n    int ans = 0;\n    while(pos < sz(s)) {\n        int c = s[pos] - 'a';\n        if (!v->to[c])\n            break;\n        v = v->to[c];\n        ans += v->cnt;\n        pos++;\n    }\n    return ans;\n}\n\nvector<int> zf(string s) {\n    vector<int> z(sz(s), 0);\n    for (int i = 1, l = 0, r = 0; i < sz(s); ++i) {\n        if(i < r)\n            z[i] = min(r - i, z[i - l]);\n        while (i + z[i] < sz(s) && s[i + z[i]] == s[z[i]])\n            z[i]++;\n\n        if(i + z[i] > r)\n            l = i, r = i + z[i];\n    }\n    return z;\n}\n\nstring t;\nint n;\nvector<string> s;\n\ninline bool read() {\n    if(!(cin >> t))\n        return false;\n    cin >> n;\n    s.resize(n);\n    fore(i, 0, n)\n        cin >> s[i];\n    return true;\n}\n\ninline void solve() {\n    vector<int> cnt[2];\n    fore(k, 0, 2) {\n        cnt[k].assign(sz(t) + 1, 0);\n        szn = 0;\n        vt root = getNode();\n\n        forn(i, n) {\n            if (sz(s[i]) > MAG) {\n                auto z = zf(s[i] + t);\n                fore(j, 0, sz(t))\n                    cnt[k][j] += (z[sz(s[i]) + j] >= sz(s[i]));\n            } else {\n                addWord(root, s[i]);\n            }\n        }\n\n        fore(i, 0, sz(t))\n            cnt[k][i] += calcCnt(root, t, i);\n\n        reverse(all(t));\n        fore(i, 0, n)\n            reverse(all(s[i]));\n    }\n\n    li ans = 0;\n    fore(i, 0, sz(t) + 1)\n        ans += cnt[0][i] * 1ll * cnt[1][sz(t) - i];\n    cout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(0);\n    cin.tie(0), cout.tie(0);\n    cerr << fixed << setprecision(15);\n\n    if(read()) {\n        solve();\n\n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "string suffix structures",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1202",
    "index": "F",
    "title": "You Are Given Some Letters...",
    "statement": "You are given $a$ uppercase Latin letters 'A' and $b$ letters 'B'.\n\nThe period of the string is the smallest such positive integer $k$ that $s_i = s_{i~mod~k}$ ($0$-indexed) for each $i$. Note that this implies that $k$ won't always divide $a+b = |s|$.\n\nFor example, the period of string \"ABAABAA\" is $3$, the period of \"AAAA\" is $1$, and the period of \"AABBB\" is $5$.\n\nFind the number of different periods over all possible strings with $a$ letters 'A' and $b$ letters 'B'.",
    "tutorial": "Let's introduce the slightly naive solution. Iterate over all values for periods and check the possibility of each one being correct. The conditions for some period $k$ can be formulated the following way. $g = n / k$ ($n = a + b$ is the total length of the string) is the number of full periods of length $k$. Let's find at least one such pair $cnt_a$ and $cnt_b$ such that $cnt_a + cnt_b = x$ and the remainder part of the string can be filled with $a - cnt_a \\cdot g$ letters 'A' and $b - cnt_b \\cdot g$ letters 'B'. By easy construction one can deduce that the conditions of $a - cnt_a \\cdot g \\le cnt_a$ and $b - cnt_b \\cdot g \\le cnt_b$ are enough. Thus $cnt_a$ should be greater or equal to $\\frac{a}{g + 1}$ and $cnt_b \\ge \\frac{b}{g + 1}$. In order to move to the faster solution one should also remember that both remainder parts $a - cnt_a \\cdot g$ and $b - cnt_b \\cdot g$ should be non-negative. Let's learn how to solve the problem for the whole range of lengths which all have the number of full periods equal to the same value $g$. Let this range be $[l; r]$. From the aforementioned formulas one can notice that the restrictions on both $cnt_a$ and $cnt_b$ don't depend on the length itself but only on value of $g$. To be more specific: $\\frac{a}{g + 1} \\le cnt_a \\le \\frac{a}{g}$ $\\frac{b}{g + 1} \\le cnt_b \\le \\frac{b}{g}$ The lowest and the highest values for $cnt_a$ and $cnt_b$ will be the following: $a_{low} = \\lceil \\frac{a}{g + 1} \\rceil$ $a_{high} = \\lfloor \\frac{a}{g} \\rfloor$ $b_{low} = \\lceil \\frac{b}{g + 1} \\rceil$ $b_{high} = \\lfloor \\frac{b}{g} \\rfloor$ It is claimed that every value between $a_{low} + b_{low}$ and $a_{high} + b_{high}$ exists if the values are valid ($a_{low} \\le a_{high}$ and $b_{low} \\le b_{high}$). The full proof about the given conditions being sufficient and the existence of every value on that range is left to the reader. Some kind of a hint might be the suggestion to check how the inequalities change on the transition from some period $k$ to $k + 1$. Restrict the values by $l$ and $r$ to count each answer on exactly one range of lengths. Finally, the value of $min(r, a_{high} + b_{high}) - max(l, a_{low} + b_{low}) + 1$ is added to the answer. The number of ranges with the same $g$ is $O(\\sqrt n)$. Overall complexity: $O(\\sqrt n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint a, b;\n\tscanf(\"%d%d\", &a, &b);\n\t\n\tint n = a + b;\n\tint ans = 0;\n\tint l = 1;\n\twhile (l <= n){\n\t\tint g = n / l;\n\t\t\n\t\tif (a < g || b < g){\n\t\t\tl = n / g + 1;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tint r = n / g;\n\t\t\n\t\tint a_low = (a + g) / (g + 1);\n\t\tint a_high = a / g;\n\t\tint b_low = (b + g) / (g + 1);\n\t\tint b_high = b / g;\n\t\t\n\t\tif (a_low <= a_high && b_low <= b_high)\n\t\t\tans += max(0, min(r, a_high + b_high) - max(l, a_low + b_low) + 1);\n\t\tl = r + 1;\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1203",
    "index": "A",
    "title": "Circle of Students",
    "statement": "There are $n$ students standing in a circle in some order. The index of the $i$-th student is $p_i$. It is guaranteed that all indices of students are distinct integers from $1$ to $n$ (i. e. they form a permutation).\n\nStudents want to start a round dance. A \\textbf{clockwise} round dance can be started if the student $2$ comes right after the student $1$ in clockwise order (there are no students between them), the student $3$ comes right after the student $2$ in clockwise order, and so on, and the student $n$ comes right after the student $n - 1$ in clockwise order. A \\textbf{counterclockwise} round dance is almost the same thing — the only difference is that the student $i$ should be right after the student $i - 1$ in counterclockwise order (this condition should be met for every $i$ from $2$ to $n$).\n\nFor example, if the indices of students listed in clockwise order are $[2, 3, 4, 5, 1]$, then they can start a clockwise round dance. If the students have indices $[3, 2, 1, 4]$ in clockwise order, then they can start a counterclockwise round dance.\n\nYour task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "We just need to find the position of the $1$ in the array and then check if the sequence $2, 3, \\dots, n$ is going counterclockwise or clockwise from the position $pos-1$ or $pos+1$ correspondingly. We can do this by two cycles. Total complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tint pos = -1;\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tcin >> a[j];\n\t\t\tif (a[j] == 1) pos = j;\n\t\t}\n\t\tbool okl = true, okr = true;\n\t\tfor (int j = 1; j < n; ++j) {\n\t\t\tokl &= (a[(pos - j + n) % n] == j + 1);\n\t\t\tokr &= (a[(pos + j + n) % n] == j + 1);\n\t\t}\n\t\tif (okl || okr) cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1203",
    "index": "B",
    "title": "Equal Rectangles",
    "statement": "You are given $4n$ sticks, the length of the $i$-th stick is $a_i$.\n\nYou have to create $n$ rectangles, each rectangle will consist of exactly $4$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.\n\nYou want to all rectangles to have equal area. The area of the rectangle with sides $a$ and $b$ is $a \\cdot b$.\n\nYour task is to say if it is possible to create exactly $n$ rectangles of equal area or not.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "After sorting $a$ we can observe that if the answer is \"YES\" then the area of each rectangle is $area = a_{1} \\cdot a_{4n}$. Then we just need to check for each $i$ from $1$ to $n$ that $a_{2i-1} = a_{2i}$ and $a_{4n-2i+1} = a_{4n-2i+2}$ and $a_{2i-1} \\cdot a_{4n-2i+2} = area$. If all conditions are satisfied for all $i$ then the answer is \"YES\". Otherwise the answer is \"NO\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(4 * n);\n\t\tfor (int j = 0; j < 4 * n; ++j) {\n\t\t\tcin >> a[j];\n\t\t}\n\t\tsort(a.begin(), a.end());\n\t\tint area = a[0] * a.back();\n\t\tbool ok = true;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint lf = i * 2, rg = 4 * n - (i * 2) - 1;\n\t\t\tif (a[lf] != a[lf + 1] || a[rg] != a[rg - 1] || a[lf] * 1ll * a[rg] != area) {\n\t\t\t\tok = false;\n\t\t\t}\n\t\t}\n\t\tif (ok) cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1203",
    "index": "C",
    "title": "Common Divisors",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nYour task is to say the number of such positive integers $x$ such that $x$ divides \\textbf{each} number from the array. In other words, you have to find the number of common divisors of all elements in the array.\n\nFor example, if the array $a$ will be $[2, 4, 6, 2, 10]$, then $1$ and $2$ divide each number from the array (so the answer for this test is $2$).",
    "tutorial": "Let $g = gcd(a_1, a_2, \\dots, a_n)$ is the greatest common divisor of all elements of the array. You can find it by Euclidean algorithm or some standard library functions. Then the answer is just the number of divisors of $g$. You can find this value in $\\sqrt{g}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tlong long g = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tlong long x;\n\t\tcin >> x;\n\t\tg = __gcd(g, x);\n\t}\n\t\n\tint ans = 0;\n\tfor (int i = 1; i * 1ll * i <= g; ++i) {\n\t\tif (g % i == 0) {\n\t\t\t++ans;\n\t\t\tif (i != g / i) {\n\t\t\t\t++ans;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1203",
    "index": "D1",
    "title": "Remove the Substring (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the length of the string}.\n\nYou are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $s$ without changing order of remaining characters (in other words, it is guaranteed that $t$ is a subsequence of $s$).\n\nFor example, the strings \"test\", \"tst\", \"tt\", \"et\" and \"\" are subsequences of the string \"test\". But the strings \"tset\", \"se\", \"contest\" are not subsequences of the string \"test\".\n\nYou want to remove some substring (contiguous subsequence) from $s$ of \\textbf{maximum possible length} such that after removing this substring $t$ will remain a subsequence of $s$.\n\nIf you want to remove the substring $s[l;r]$ then the string $s$ will be transformed to $s_1 s_2 \\dots s_{l-1} s_{r+1} s_{r+2} \\dots s_{|s|-1} s_{|s|}$ (where $|s|$ is the length of $s$).\n\nYour task is to find the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$.",
    "tutorial": "In this problem we can just iterate over all possible substrings and try to remove each of them. After removing the substring we can check if $t$ remains the subsequence of $s$ in linear time. Let we remove the substring $s[l; r]$. Let's maintain a pointer $pos$ (the initial value of the pointer is $1$) and iterate over all possible $i$ from $1$ to $|s|$. If $pos \\le |t|$ and $s_i = t_{pos}$ let's increase $pos$ by one. If after all iterations $pos = |t| + 1$ then let's update the answer with the length of the current substring.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tstring s, t;\n\tcin >> s >> t;\n\tint ans = 0;\n\tfor (int i = 0; i < int(s.size()); ++i) {\n\t\tfor (int j = i; j < int(s.size()); ++j) {\n\t\t\tint pos = 0;\n\t\t\tfor (int p = 0; p < int(s.size()); ++p) {\n\t\t\t\tif (i <= p && p <= j) continue;\n\t\t\t\tif (pos < int(t.size()) && t[pos] == s[p]) ++pos;\n\t\t\t}\n\t\t\tif (pos == int(t.size())) ans = max(ans, j - i + 1);\n\t\t}\n\t}\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1203",
    "index": "D2",
    "title": "Remove the Substring (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the length of the string}.\n\nYou are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $s$ without changing order of remaining characters (in other words, it is guaranteed that $t$ is a subsequence of $s$).\n\nFor example, the strings \"test\", \"tst\", \"tt\", \"et\" and \"\" are subsequences of the string \"test\". But the strings \"tset\", \"se\", \"contest\" are not subsequences of the string \"test\".\n\nYou want to remove some substring (contiguous subsequence) from $s$ of \\textbf{maximum possible length} such that after removing this substring $t$ will remain a subsequence of $s$.\n\nIf you want to remove the substring $s[l;r]$ then the string $s$ will be transformed to $s_1 s_2 \\dots s_{l-1} s_{r+1} s_{r+2} \\dots s_{|s|-1} s_{|s|}$ (where $|s|$ is the length of $s$).\n\nYour task is to find the maximum possible length of the substring you can remove so that $t$ is still a subsequence of $s$.",
    "tutorial": "Let $rg_i$ be such rightmost position $x$ in $s$ that the substring $t[i;|t|]$ is the subsequence of $s[x;|s|]$. We need values $rg_i$ for all $i$ from $1$ to $|t|$. We can calculate it just iterating from right to left over all characters of $s$ and maintaining the pointer to the string $t$ as in easy version. Then let's iterate over all positions $i$ from $1$ to $|s|$ and maintain the pointer $pos$ as in the easy version which tells us the maximum length of the prefix of $t$ we can obtain using only the substring $s[1;i)$ (exclusively!). Suppose we want to remove the substring of $s$ starting from $i$. Then if $pos \\le |t|$ then let $rpos$ be $rg_{pos} - 1$, otherwise let $rpos$ be $|s|$. $rpos$ tells us the farthest rightmost character of the substring we can remove. So we can update the answer with the value $rpos - i + 1$ and go to the next position (and don't forget to increase $pos$ if needed).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tstring s, t;\n\tcin >> s >> t;\n\tvector<int> rg(t.size());\n\t\n\tfor (int i = int(t.size()) - 1; i >= 0; --i) {\n\t\tint pos = int(s.size()) - 1;\n\t\tif (i + 1 < int(t.size())) pos = rg[i + 1] - 1;\n\t\twhile (s[pos] != t[i]) --pos;\n\t\trg[i] = pos;\n\t}\n\t\n\tint ans = 0;\n\tint pos = 0;\n\tfor (int i = 0; i < int(s.size()); ++i) {\n\t\tint rpos = int(s.size()) - 1;\n\t\tif (pos < int(t.size())) rpos = rg[pos] - 1;\n\t\tans = max(ans, rpos - i + 1);\n\t\tif (pos < int(t.size()) && t[pos] == s[i]) ++pos;\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1203",
    "index": "E",
    "title": "Boxers",
    "statement": "There are $n$ boxers, the weight of the $i$-th boxer is $a_i$. Each of them can change the weight by no more than $1$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.\n\nIt is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).\n\nWrite a program that for given current values ​$a_i$ will find the maximum possible number of boxers in a team.\n\nIt is possible that after some change the weight of some boxer is $150001$ (but no more).",
    "tutorial": "Let $lst$ be the last weight of the boxer taken into the team. Initially $lst = \\infty$. Let's sort all boxers in order of non-increasing their weights and iterate over all boxers in order from left to right. If the current boxer has the weight $w$ then let's try to take him with weight $w+1$ (we can do it if $w+1<lst$). If we cannot do it, let's try to take him with weight $w$. And in case of fault let's try to take him with weight $w-1$. If we cannot take him even with weight $w-1$ then let's skip him. And if we take him let's replace $lst$ with him weight. The answer is the number of boxers we took.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tsort(a.rbegin(), a.rend());\n\tint lst = a[0] + 2;\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint cur = -1;\n\t\tfor (int dx = 1; dx >= -1; --dx) {\n\t\t\tif (a[i] + dx > 0 && a[i] + dx < lst) {\n\t\t\t\tcur = a[i] + dx;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (cur == -1) continue;\n\t\t++ans;\n\t\tlst = cur;\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1203",
    "index": "F1",
    "title": "Complete the Projects (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version}.\n\nPolycarp is a very famous freelancer. His current rating is $r$ units.\n\nSome very rich customers asked him to complete some projects for their companies. To complete the $i$-th project, Polycarp needs to have at least $a_i$ units of rating; after he completes this project, his rating will change by $b_i$ (his rating will increase or decrease by $b_i$) ($b_i$ can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer.\n\nIs it possible to complete all the projects? Formally, write a program to check if such an order of the projects exists, that Polycarp has enough rating before starting each project, and he has non-negative rating after completing each project.\n\nIn other words, you have to check that there exists such an order of projects in which Polycarp will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project.",
    "tutorial": "Firstly, let's divide all projects into two sets: all projects giving us non-negative rating changes (let this set be $pos$) and all projects giving up negative rating changes (let this set be $neg$). Firstly let's take all projects from the set $pos$. How do we do that? Let's sort them by $a_i$ in non-decreasing order because each project we take cannot make our rating less and we need to consider them in order of their requirements. If we can take the current project $i$ ($r \\ge a_i$), set $r := r + b_i$ and go further, otherwise print \"NO\" and terminate the program. Okay, what do we do with the projects that has negative $b_i$? Firstly, let's set $a_i := max(a_i, -b_i)$. This means the tighter requirement of this project, obviously. Then let's sort all projects in order of $a_i + b_i$ in non-increasing order and go from left to right and take all of them. If we cannot take at least one project, the answer is \"NO\". Otherwise the answer is \"YES\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool comp(const pair<int, int>& a, const pair<int, int>& b) {\n    return a.first + a.second > b.first + b.second;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, r;\n\tcin >> n >> r;\n\tvector<pair<int, int>> pos, neg;\n\tfor (int i = 0; i < n; ++i) {\n\t\tpair<int, int> cur;\n\t\tcin >> cur.first >> cur.second;\n\t\tif (cur.second >= 0) pos.push_back(cur);\n\t\telse {\n\t\t    cur.first = max(cur.first, abs(cur.second));\n\t\t    neg.push_back(cur);\n\t\t}\n\t}\n\t\n\tsort(pos.begin(), pos.end());\n\tsort(neg.begin(), neg.end(), comp);\n\t\n\tint taken = 0;\n\tfor (int i = 0; i < int(pos.size()); ++i) {\n\t\tif (r >= pos[i].first) {\n\t\t\tr += pos[i].second;\n\t\t\t++taken;\n\t\t}\n\t}\n\t\n\tvector<vector<int>> dp(neg.size() + 1, vector<int>(r + 1, 0));\n\tdp[0][r] = taken;\n\tfor (int i = 0; i < int(neg.size()); ++i) {\n\t\tfor (int cr = 0; cr <= r; ++cr) {\n\t\t\tif (cr >= neg[i].first && cr + neg[i].second >= 0) {\n\t\t\t\tdp[i + 1][cr + neg[i].second] = max(dp[i + 1][cr + neg[i].second], dp[i][cr] + 1);\n\t\t\t}\n\t\t\tdp[i + 1][cr] = max(dp[i + 1][cr], dp[i][cr]);\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\tfor (int cr = 0; cr <= r; ++cr) ans = max(ans, dp[int(neg.size())][cr]);\n\tcout << (ans == n ? \"YES\" : \"NO\") << endl;\n\t\n\treturn 0;\n}\n",
    "tags": [
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1203",
    "index": "F2",
    "title": "Complete the Projects (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version}.\n\nPolycarp is a very famous freelancer. His current rating is $r$ units.\n\nSome very rich customers asked him to complete some projects for their companies. To complete the $i$-th project, Polycarp needs to have at least $a_i$ units of rating; after he completes this project, his rating will change by $b_i$ (his rating will increase or decrease by $b_i$) ($b_i$ can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer.\n\nPolycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether.\n\nTo gain more experience (and money, of course) Polycarp wants to choose the subset of projects \\textbf{having maximum possible size} and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project.\n\nYour task is to calculate the maximum possible size of such subset of projects.",
    "tutorial": "To view the main idea of the problem, read the editorial of easy version. The only difference is that for non-negative $b_i$ we don't need to print \"NO\" if we cannot take the project, we just need to skip it because we cannot take it at all. And for negative $b_i$ we need to write the knapsack dynamic programming to take the maximum possible number of projects (we need to consider them in order of their sorting). Dynamic programming is pretty easy: $dp_{i, j}$ means that we consider $i$ projects and our current rating is $j$ and the value of dp is the maximum number of negative projects we can take. If the current project is the $i$-th negative project in order of sorting, we can do two transitions: $dp_{i + 1, j} = max(dp_{i + 1, j}, dp_{i, j})$ and if $r + b_i \\ge 0$ then we can make the transition $dp_{i + 1, j + b_i} = max(dp_{i + 1, j + b_i}, dp_{i, j} + 1)$. And then we just need to find the maximum value among all values of dp and add the number of positive projects we take to find the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool comp(const pair<int, int>& a, const pair<int, int>& b) {\n    return a.first + a.second > b.first + b.second;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, r;\n\tcin >> n >> r;\n\tvector<pair<int, int>> pos, neg;\n\tfor (int i = 0; i < n; ++i) {\n\t\tpair<int, int> cur;\n\t\tcin >> cur.first >> cur.second;\n\t\tif (cur.second >= 0) pos.push_back(cur);\n\t\telse {\n\t\t    cur.first = max(cur.first, abs(cur.second));\n\t\t    neg.push_back(cur);\n\t\t}\n\t}\n\t\n\tsort(pos.begin(), pos.end());\n\tsort(neg.begin(), neg.end(), comp);\n\t\n\tint taken = 0;\n\tfor (int i = 0; i < int(pos.size()); ++i) {\n\t\tif (r >= pos[i].first) {\n\t\t\tr += pos[i].second;\n\t\t\t++taken;\n\t\t}\n\t}\n\t\n\tvector<vector<int>> dp(neg.size() + 1, vector<int>(r + 1, 0));\n\tdp[0][r] = taken;\n\tfor (int i = 0; i < int(neg.size()); ++i) {\n\t\tfor (int cr = 0; cr <= r; ++cr) {\n\t\t\tif (cr >= neg[i].first && cr + neg[i].second >= 0) {\n\t\t\t\tdp[i + 1][cr + neg[i].second] = max(dp[i + 1][cr + neg[i].second], dp[i][cr] + 1);\n\t\t\t}\n\t\t\tdp[i + 1][cr] = max(dp[i + 1][cr], dp[i][cr]);\n\t\t}\n\t}\n\t\n\tint ans = 0;\n\tfor (int cr = 0; cr <= r; ++cr) ans = max(ans, dp[int(neg.size())][cr]);\n\tcout << ans << endl;\n\t\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1204",
    "index": "A",
    "title": "BowWow and the Timetable",
    "statement": "In the city of Saint Petersburg, a day lasts for $2^{100}$ minutes. From the main station of Saint Petersburg, a train departs after $1$ minute, $4$ minutes, $16$ minutes, and so on; in other words, the train departs at time $4^k$ for each integer $k \\geq 0$. Team BowWow has arrived at the station at the time $s$ and it is trying to count how many trains have they missed; in other words, the number of trains that have departed \\textbf{strictly before} time $s$. For example if $s = 20$, then they missed trains which have departed at $1$, $4$ and $16$. As you are the only one who knows the time, help them!\n\nNote that the number $s$ will be given you in a binary representation without leading zeroes.",
    "tutorial": "Basically, the problem asks you to count $\\lceil \\log_4 s \\rceil$, which is equal to $\\Bigl\\lceil \\dfrac{\\log_2 s}{\\log_2 4} \\Bigr\\rceil = \\Bigl\\lceil \\dfrac{\\log_2 s}{2} \\Bigr\\rceil$. If we denote $l$ as a length of the input number, then $\\lceil \\log_2 s \\rceil$ is either equal to $l-1$ if $s$ is the power of two (it can be checked by checking that there is not more than one $1$ in the input string), or to $l-1$ otherwise, so the answer to the problem is either $\\Bigl\\lceil \\dfrac{l-1}{2} \\Bigr\\rceil$ or $\\Bigl\\lceil \\dfrac{l}{2} \\Bigr\\rceil$. Also for $s=0$ the answer is $0$.",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1204",
    "index": "B",
    "title": "Mislove Has Lost an Array",
    "statement": "Mislove had an array $a_1$, $a_2$, $\\cdots$, $a_n$ of $n$ positive integers, but he has lost it. He only remembers the following facts about it:\n\n- The number of different numbers in the array is not less than $l$ and is not greater than $r$;\n- For each array's element $a_i$ either $a_i = 1$ or $a_i$ is even and there is a number $\\dfrac{a_i}{2}$ in the array.\n\nFor example, if $n=5$, $l=2$, $r=3$ then an array could be $[1,2,2,4,4]$ or $[1,1,1,1,2]$; but it couldn't be $[1,2,2,4,8]$ because this array contains $4$ different numbers; it couldn't be $[1,2,2,3,3]$ because $3$ is odd and isn't equal to $1$; and it couldn't be $[1,1,2,2,16]$ because there is a number $16$ in the array but there isn't a number $\\frac{16}{2} = 8$.\n\nAccording to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array.",
    "tutorial": "Any array that satisfies statements' conditions contains only powers of two from $2^0$ to $2^{k-1}$, where $l \\leq k \\leq r$, so the minimal sum is achieved when we take powers of two from $2^0$ to $2^{l-1}$ and set the other $n-l$ elements equal to $2^0$; the maximal sum is achieved when we take powers of two from $2^0$ to $2^{r-1}$ and set the other $n-r$ elements equal to $2^{r-1}$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1204",
    "index": "C",
    "title": "Anna, Svyatoslav and Maps",
    "statement": "The main characters have been omitted to be short.\n\nYou are given a directed unweighted graph without loops with $n$ vertexes and a path in it (that path is not necessary simple) given by a sequence $p_1, p_2, \\ldots, p_m$ of $m$ vertexes; for each $1 \\leq i < m$ there is an arc from $p_i$ to $p_{i+1}$.\n\nDefine the sequence $v_1, v_2, \\ldots, v_k$ of $k$ vertexes as good, if $v$ is a subsequence of $p$, $v_1 = p_1$, $v_k = p_m$, and $p$ is one of the shortest paths passing through the vertexes $v_1$, $\\ldots$, $v_k$ in that order.\n\nA sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $p$ is good but your task is to find the \\textbf{shortest} good subsequence.\n\nIf there are multiple shortest good subsequences, output any of them.",
    "tutorial": "Firstly, find the matrix of the shortest paths using Floyd-Warshall algortihm or running dfs from all vertexes; then a greedy approach works here: add $p_1$ to the answer and then go along the path; if the distance from the last vertex in the answer to the current vertex $p_i$ is shorter than in given path, add the vertex $p_{i-1}$ to the answer and continue traversing the path. Don't forget to add $p_m$ in the end!",
    "tags": [
      "dp",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1204",
    "index": "D2",
    "title": "Kirk and a Binary String (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.}\n\nKirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find a binary string $t$ of the same length which satisfies the following conditions:\n\n- For any $l$ and $r$ ($1 \\leq l \\leq r \\leq n$) the length of the longest non-decreasing subsequence of the substring $s_{l}s_{l+1} \\ldots s_{r}$ is equal to the length of the longest non-decreasing subsequence of the substring $t_{l}t_{l+1} \\ldots t_{r}$;\n- The number of zeroes in $t$ is the maximum possible.\n\nA non-decreasing subsequence of a string $p$ is a sequence of indices $i_1, i_2, \\ldots, i_k$ such that $i_1 < i_2 < \\ldots < i_k$ and $p_{i_1} \\leq p_{i_2} \\leq \\ldots \\leq p_{i_k}$. The length of the subsequence is $k$.\n\nIf there are multiple substrings which satisfy the conditions, output any.",
    "tutorial": "Solution 1: Let's call a string $p$ fixed if there isn't another string $t$ of the same length which satisfies the first condition of the statement (it was about the same lengths of the longest nondecreasing subsequences on substrings). The following statements are obivous: string $10$ is fixed; if strings $p$ and $q$ are fixed, then their concatenation $pq$ is fixed; if a string $p$ is fixed, then the string $1p0$ is fixed; each fixed string contains the same number of ones and zeroes; the length of the longest nondecreasing subsequence for any fixed string is equal to the half of its length, which can be obtained by taking all zeroes or all ones; So if we erase all fixed strings from the given string, the remaining parts consists of zeroes at prefix and ones at suffix; it is obvious that we can change all these ones to zeroes and the string still satisfies the condition. Solution 2: If we change any $1$ to $0$ and the longest nondecreasing sequence of the whole string remains the same, then we are able to change it to $0$. To count the longest nondecreasing sequence of a new string, store and maintain following arrays: $dp^p_i$ - the longest nondecreasing sequence of the substring $s_{1 \\ldots i}$; $zero_i$ - number of zeroes in the substring $s_{1 \\ldots i}$; $dp^s_i$ - the longest nondecreasing sequence of the substring $s_{i \\ldots n}$ and $ones_i$ - number of ones in the substring $s_{i \\ldots n}$; now, if we change $1$ to $0$ at a position $i$, then the length of the longest nondecreasing sequence of a new string is $\\max(dp^p_{i-1}+ones_{i+1},zero_{i-1}+1+dp^s_{i+1})$.",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1204",
    "index": "E",
    "title": "Natasha, Sasha and the Prefix Sums",
    "statement": "Natasha's favourite numbers are $n$ and $1$, and Sasha's favourite numbers are $m$ and $-1$. One day Natasha and Sasha met and wrote down every possible array of length $n+m$ such that some $n$ of its elements are equal to $1$ and another $m$ elements are equal to $-1$. For each such array they counted its maximal prefix sum, probably an empty one which is equal to $0$ (in another words, if every nonempty prefix sum is less to zero, then it is considered equal to zero). Formally, denote as $f(a)$ the maximal prefix sum of an array $a_{1, \\ldots ,l}$ of length $l \\geq 0$. Then:\n\n$$f(a) = \\max (0, \\smash{\\displaystyle\\max_{1 \\leq i \\leq l}} \\sum_{j=1}^{i} a_j )$$\n\nNow they want to count the sum of maximal prefix sums for each such an array and they are asking you to help. As this sum can be very large, output it modulo $998\\: 244\\: 853$.",
    "tutorial": "Let's count a dp $k[x][y]$ - the number of arrays consisting of $x$ ones and $y$ minus ones such that their maximal prefix sum is equal to $0$: if $x=0$ then $k[x][y] = 1$, else if $x>y$ then $k[x][y] = 0$, else $k[x][y] = k[x-1][y] + k[x][y-1]$, because if we consider any array consisting of $x$ ones and $y-1$ minus ones which maximal prefix sum is $0$ then adding a minus one to the end leaves it equal to $0$; also if we consider any array consisting of $x-1$ ones and $y$ minus ones which maximal prefix sum is $0$ then adding a one to the end leaves it equal to $0$, because $x \\leq y$. Now let's count a dp $d[x][y]$ - the answer to the problem for $n=x$ and $m=y$: if $x=0$ then $d[x][y]=0$, else if $y=0$ then $d[x][y]=x$, else $d[x][y] = (\\binom{x+y-1}{y}+d[x-1][y]) + (d[x][y-1] - (\\binom{x+y-1}{x}-k[x][y-1]))$. That is because if we consider any array of $x-1$ ones and $y$ minus ones (there are $\\binom{x+y-1}{y}$ such arrays) then adding a one in its beginning increases its maximal prefix sum by $1$; also if we consider any array of $x$ ones and $y-1$ minus ones then adding a minus one in its beginning either decreases its maximal prefix sum by $1$ if it was greater than $0$ (there are $\\binom{x+y-1}{x}-k[x][y-1]$ such arrays) or leaves it equal to $0$. So the answer to the problem is $d[n][m]$.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1205",
    "index": "A",
    "title": "Almost Equal",
    "statement": "You are given integer $n$. You have to arrange numbers from $1$ to $2n$, using each of them exactly once, on the circle, so that the following condition would be satisfied:\n\nFor every $n$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $2n$ numbers differ not more than by $1$.\n\nFor example, choose $n = 3$. On the left you can see an example of a valid arrangement: $1 + 4 + 5 = 10$, $4 + 5 + 2 = 11$, $5 + 2 + 3 = 10$, $2 + 3 + 6 = 11$, $3 + 6 + 1 = 10$, $6 + 1 + 4 = 11$, any two numbers differ by at most $1$. On the right you can see an invalid arrangement: for example, $5 + 1 + 6 = 12$, and $3 + 2 + 4 = 9$, $9$ and $12$ differ more than by $1$.",
    "tutorial": "Consider a valid arrangement for some $n$. We denote $S_i = a_i + a_ {i + 1} + a_ {i + 2} + \\dots + a_ {i + n-1}$ for each $i$ from $1$ to $2n$, where $a_ {t + 2n} = a_ {t}$. Then we have: $S_ {i + 1} -S_i = (a_ {i + 1} + a_ {i + 2} + a_ {i + 3} + \\dots + a_ {i + n}) - (a_i + a_ {i + 1} + a_ {i + 2} + \\dots + a_ {i + n-1}) = a_ {i + n} -a_i$. Hence $| a_ {i + n} -a_i | \\le 1$. Since $a_ {i + n}$ and $a_i$ are different, $| a_ {i + n} - a_i | =$ 1. It is also clear from this that $a_ {i + n} - a_i$ and $a_ {i + n + 1} - a_ {i + 1}$ have opposite signs: if they were both equal to $1$, we would get $S_ {i + 2} - S_i = (S_ {i + 2} - S_ {i + 1}) + (S_ {i + 1} - S_i) = (a_ {i + n + 1} - a {i + 1 }) + (a_ {i + n} - a_i) =$ 2, similarly with $-1$. Thus, the values $a_ {i + n} -a_i$ for $i$ from $1$ to $2n$ shoul be $1$ and $-1$ alternating, and this is a sufficient condition. Now, if $n$ is even, we get a contradiction, since $a_ {i + n} - a_i = - (a _ {(i + n) + n} - a_ {i + n})$, but due to the alternating they must be equal. If $n$ is odd, then it's now easy to build an example: for $i$ from $1$ to $n$ $a_i = 2i-1$, $a_i = 2i$, if $i$ is even, and $a_i = 2i$ , $a_i = 2i-1$ if $i$ is odd. Asymptotics $O (n)$. Challenge: For which pairs of $(n, k)$ ($n> k \\ge 1$) is there an arrangement of numbers from $1$ to $n$ on a circle such that the sums of each $k$ consecutive numbers differ by not more than $1$ ?",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1205",
    "index": "B",
    "title": "Shortest Cycle",
    "statement": "You are given $n$ integer numbers $a_1, a_2, \\dots, a_n$. Consider graph on $n$ nodes, in which nodes $i$, $j$ ($i\\neq j$) are connected if and only if, $a_i$ AND $a_j\\neq 0$, where AND denotes the bitwise AND operation.\n\nFind the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.",
    "tutorial": "The most important thing in this task is to notice that if any bit is contained at least $3$ numbers, then they will form a cycle of length $3$, and the answer is $3$. Suppose now that each bit is in no more than two numbers. It follows that each bit can be shared by at most one pair of numbers. From here we get that in the graph there are no more than $60$ edges. Then in it you can find the shortest cycle in $O (m ^ 2)$: for each edge between the vertices $u$ and $v$ we will try to remove it and find the shortest distance between the vertices $u$, $v$ in the resulting graph. If each time $u$ and $v$ turned out to be in different components, then there is no cycle in the graph, otherwise its length is $1$ + the minimal of the distances found. Asymptotics $O (n \\ log {10 ^ {18}} + 60 ^ 2)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "graphs",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1205",
    "index": "C",
    "title": "Palindromic Paths",
    "statement": "\\textbf{This is an interactive problem}\n\nYou are given a grid $n\\times n$, where $n$ is \\textbf{odd}. Rows are enumerated from $1$ to $n$ from up to down, columns are enumerated from $1$ to $n$ from left to right. Cell, standing on the intersection of row $x$ and column $y$, is denoted by $(x, y)$.\n\nEvery cell contains $0$ or $1$. It is known that the top-left cell contains $1$, and the bottom-right cell contains $0$.\n\nWe want to know numbers in all cells of the grid. To do so we can ask the following questions:\n\n\"$?$ $x_1$ $y_1$ $x_2$ $y_2$\", where $1 \\le x_1 \\le x_2 \\le n$, $1 \\le y_1 \\le y_2 \\le n$, and $x_1 + y_1 + 2 \\le x_2 + y_2$. In other words, we output two different cells $(x_1, y_1)$, $(x_2, y_2)$ of the grid such that we can get from the first to the second by moving only to the right and down, and they aren't adjacent.\n\nAs a response to such question you will be told if there exists a path between $(x_1, y_1)$ and $(x_2, y_2)$, going only to the right or down, numbers in cells of which form a palindrome.\n\nFor example, paths, shown in green, are palindromic, so answer for \"$?$ $1$ $1$ $2$ $3$\" and \"$?$ $1$ $2$ $3$ $3$\" would be that there exists such path. However, there is no palindromic path between $(1, 1)$ and $(3, 1)$.\n\nDetermine all cells of the grid by asking not more than $n^2$ questions. It can be shown that the answer always exists.",
    "tutorial": "Denote $ask ((x_1, y_1), (x_2, y_2)) = 1$ if there is a palindromic path between them, and $0$ otherwise. We also denote by $grid [i] [j]$ the number written in the cell $(i, j)$. Firstly, make an observation: if the Manhattan distance is $| x_2-x_1 | + | y_2-y_1 | =$ 2, then $ask ((x_1, y_1), (x_2, y_2)) = 1 \\iff board [x1] [y1] = board [x2] [y2]$. In fact, the path between the cells $(x_1, y_1)$ and $(x_2, y_2)$ has a length of $3$, and therefore it is palindromic if and only if $board [x1] [y1] = board [x2 ] [y2]$. Consider a chessboard coloring such that the upper left unit is painted white. Then, using the observation described above, we can restore the numbers in all white cells. In a similar way, if we fix a certain number in a black cell, then all other numbers in black cells will be restored uniquely. Thus, we only have two options for arranging numbers on the board, which differ in the fact that in the second option, the numbers in the black cells are opposite to those in the first option. In the figure below, green pairs of white cells are connected, about which we can ask questions to find out all the values in them, and red - pairs of black cells. Now there are two approaches. First: for each option, calculate $ask ((x_1, y_1), (x_2, y_2))$ for each pair of suitable cells, find where they differ, and ask a question about these two cells. This way we can uniquely identify the board option. It is possible to determine $ask ((x_1, y_1), (x_2, y_2)$ using dynamic programming: the answer is $1$ only when $grid [x_1] [y_1] = grid [x_2] [y_2]$ and there is a path -palindrome between a pair of $(x_1 + 1, y_1), (x_1, y_1 + 1)$ and $(x_2-1, y_2), (x_2, y_2-1)$. The second approach is a little more interesting, and it also shows why there is such a pair of cells for which the two options give different answers. Consider any path with a length of $4$ cells, denote the numbers in its cells as $c_1, c_2, c_3, c_4$. Then two of the cells of the path are black, and two are white. We know the relation between $c_1, c_3$, as well as between $c_2, c_4$ (by the relation we mean that we know are numbers in them same, or different). Suppose that the relation between $c_1, c_3$ is the same as between $c_2, c_4$. Then $ask (c_1, c_4)$ will make it possible to uniquely determine all the numbers! Indeed, if $c_1 = c_4$, then $c_2 = c_3$, and therefore the path will be palindromic. Otherwise, no path between $c_1$ and $c_4$ will be palindromic. Thus, we will be able to establish a relation between some white and some black cell, which will be enough to solve the problem. Suppose that for any path of four cells $c_1, c_2, c_3, c_4$, the relation between $c_1, c_3$ is different from the relation between $c_2, c_4$. This is equivalent to $c_1 \\oplus c_2 \\oplus c_3 \\oplus c_4 = 1$. Suppose that for any path of four cells $\\oplus$ of numbers in them is equal to $1$. Then we consider any path from the cell $(1, 1)$ to the cell $(n, n)$ of length $2n-1$. If the xor of each $4$ of neighboring cells in it is $1$, then the line is periodic with a period of $4$, but the numbers in the first and last cell in it are different from the condition! Thus, the algorithm is as follows: choose any path between $(1, 1)$ and $(4, 4)$, find on it four cells with a xor of numbers equal to $0$, and ask a question about it. Asymptotics $O (n ^ 2)$.",
    "tags": [
      "implementation",
      "interactive"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1205",
    "index": "D",
    "title": "Almost All",
    "statement": "You are given a tree with $n$ nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied:\n\nFor every two nodes $i$, $j$, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from $1$ to $\\lfloor \\frac{2n^2}{9} \\rfloor$ has to be written on the blackboard at least once.\n\nIt is guaranteed that such an arrangement exists.",
    "tutorial": "First we prove the following lemma: Suppose that there are $n$ vertices in the tree $G$ with the root $v$. Let also $0 <a_1 <a_2 \\dots <a_ {n-1}$ be any $n-1$ different positive numbers. Then we can arrange non-negative integers on the edges of $G$ so that the distances from $v$ to the remaining vertices of the tree are $a_1, a_2, \\dots, a_{n-1}$ in some order. Proof: for example, by induction. Let $s$ be some child of $v$ in whose subtree, including $s$, there are $m$ vertices. Then we write on the edge between $(v, s)$ $a_1$, and solve the problem for the subtree $s$ and the numbers $a_2-a_1, a_3-a_1, \\dots, a_m - a_1$. After that, we discard the subtree of $s$ from consideration and fill in the remaining edges for the numbers $a_{m + 1}, \\dots, a_{n-1}$. Thus, the lemma is proved. Now let $c$ be the centroid of tree. Root the tree from $c$ and let $s_1, s_2, \\dots, s_k$ be the sizes of the subtrees of his childs (as we know, $s_i \\le \\frac{n}{2}$). Divide the subtrees of the childs into two groups so that size of each group is at least $\\lceil \\frac{n-1}{3} \\rceil$. It is possible: while there are at least $4$ subtrees, there are two for which there are no more than $\\frac{n}{2}$ vertices in total, then we unite them. When we have $3$ subtrees left, we will unite two smaller ones into one group. It is easy to see that in each of the two groups there will be at least $\\lceil \\frac{n-1}{3} \\rceil$ vertices. Let the first group have $a$ vertices and the second $b$. Then, using the lemma, we put the numbers on the edges in $a$ and between $c$ and $a$ so that the distances from $c$ to the vertices of the first group are $1, 2, \\dots, a$. Similarly, we make the distance from $c$ to the vertices of the second group equal to $(a + 1), 2 (a + 1), \\dots, b (a + 1)$. Then each number from $1$ to $(a + 1) (b + 1) -1$ can be obtained as the distance between some vertex from the first group and some from the second. It is easy to show that $(a + 1) (b + 1) -1$ for $a + b = n-1$ and $a, b \\ge \\lceil \\frac{n-1}{3} \\rceil$ cannot be less than $\\frac {2n ^ 2} {9}$. (For example, we can say that this value is minimized at $a = \\frac{n-1}{3}$ and get $(a + 1) (b + 1) -1 \\ge (\\frac{n + 2 }{3}) (\\frac{2n + 1}{3}) - 1 = \\frac{2n ^ 2 + 5n + 3}{9} - 1 \\ge \\frac{2n ^ 2}{9}$ for $n> 1$ (the case of $n = 1$ is obvious)). Asymptotics $O (n)$ (but a checker takes $O (n ^ 2)$)",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1205",
    "index": "E",
    "title": "Expected Value Again",
    "statement": "You are given integers $n$, $k$. Let's consider the alphabet consisting of $k$ different elements.\n\nLet \\textbf{beauty} $f(s)$ of the string $s$ be the number of indexes $i$, $1\\le i<|s|$, for which prefix of $s$ of length $i$ equals to suffix of $s$ of length $i$. For example, beauty of the string $abacaba$ equals $2$, as for $i = 1, 3$ prefix and suffix of length $i$ are equal.\n\nConsider all words of length $n$ in the given alphabet. Find the expected value of $f(s)^2$ of a uniformly chosen at random word. We can show that it can be expressed as $\\frac{P}{Q}$, where $P$ and $Q$ are coprime and $Q$ isn't divided by $10^9 + 7$. Output $P\\cdot Q^{-1} \\bmod 10^9 + 7$.",
    "tutorial": "Let $f_i (s)$ be a function of the string $s$ equal to $1$ if the prefix and suffix of length $i$ are equal, and equal to $0$ otherwise. We need to calculate $E ((f_1 (s) + f_2 (s) + \\dots + f_{n-1}(s))^2) =$ (using linearity of expectation) $\\sum_{i = 1}^{n-1} E(f_i (s) ^ 2) + \\sum_{1 \\le i, j \\le n-1, i \\neq j} E (f_i (s) f_j (s))$. We will call the number $k$ the period of the string $s$ if $s [i] = s [i + k]$ for all $1 \\le i \\le len (s) + 1-k$. Moreover, the length of $s$ is not required to be divided by $k$. ** Statement 1: ** $f_i (s) = 1 \\iff$ $n-i$ is the period of the string is $s$. ** Proof: ** that $f_i (s) = 1$ is equivalent to $s[1]s[2] \\dots s[i] = s[n + 1-i]s[n + 2 -i] \\dots s[n]$, which is equivalent to the fact that $s [j] = s [j + n - i]$ for $j$ from $1$ to $i$. ** Statement 2: ** $E (f_i (s)) = k ^ {- i}$. ** Proof: ** The probability that $f_i (s) = 1$ is $k ^ {- i}$, since each of the last $i$ characters is uniquely determined from the previous ones. ** Statement 3: ** Let $i_1 = n-i, j_1 = n-j$. Then $E (f_i (s) f_j (s)) = k ^ {max (i_1 + j_1 - n, gcd (i_1, j_1)) - n}$. ** Proof: ** Assume that $f_i (s) = f_j (s) = 1$. We know that the string is $i_1$ and $j_1$-periodic. Consider a graph of $n$ string positions, and draw edges between positions at distances $i_1, j_1$. Then the number of different strings satisfying $f_i (s) = f_j (s) = 1$ is $k ^ {comps}$, where $comps$ is the number of connected components of our graph. Then $E (f_i (s) f_j (s)) = k ^ {comps-n}$. Thus, we need to show that $comps = max (i_1 + j_1 - n, gcd (i_1, j_1))$. The case of $i_1 + j_1 \\le n$ is obvious: in this case, by subtracting and adding $i_1, j_1$ we can show that the string has period $gcd (i_1, j_1)$, in this case $comps = gcd (i_1, j_1 )$. We now consider the case when $i_1 + j_1> n$. Without loss of generality, $i <j \\implies i_1> j_1$. We write out in a circle numbers from $1$ to $i_1$. They denote the components of connectivity when we draw only the edges connecting the positions at a distance of $i_1$. Now we need to add edges of the form $(k, k + j_1)$ for $k = 1, 2, \\dots, j$ (here $i_1 + 1 = 1, \\dots$). Moreover, we know that $j <i_1$. We will add these edges one at a time and observe how the connected components change. If we connected two positions that were not connected yet, then we reduced the number of connected components by $1$. Otherwise, we connected two already connected vertices and formed a cycle. When does a cycle form at all? If we consider all the edges of the form $(k, k + j_1)$, then our graph is divided into $gcd (i_1, j_1)$ cycles - components, each of which contains all positions giving the same residues when divided by $gcd (i_1, j_1)$. Thus, it is necessary to calculate how many of these cycles we form. If $t$ cycles are formed, then the number of components will be $i_1 - j + t = i_1 + j_1 - n + t$. How many cycles will we create? Let's see if the cycle consisting of positions giving the remainder $x$ when divided by $gcd (i_1, j_1)$ closes. It closes only if all its vertices are in $[1, j]$. This is equivalent to the fact that among the positions in $[j + 1, i_1]$, not a single number gives the remainder of $x$ when dividing by $gcd (i_1, j_1)$. If $i_1-j = i_1 + j_1 - n \\ge gcd (i_1, j_1)$, then this cannot happen for any $x$, $t = 0$, and $comp = i_1 + j_1 - n = max (i_1 + j_1 - n, gcd (i_1, j_1)$. Otherwise, there will be exactly $gcd (i_1, j_1) - (i_1 + j_1-n)$, where $comp = i_1 + j_1 - n + gcd (i_1, j_1) - (i_1 + j_1-n) = gcd (i_1, j_1)$. Thus, the statement is proved. Further reasoning is standard. We have shown that $E (f_i (s) f_j (s))$ depends only on $i_1 + j_1$ and $gcd (i_1, j_1)$. It remains for $s, gcd$ to count the number of pairs $i_1, j_1$ such that $s = i_1 + j_1$, $gcd = gcd (i1, j1)$, $1 \\le i_1, j_1 \\le n-1$. We will do it as follows: if $s_2 = \\frac{s}{gcd}$, $i_2 = \\frac{i_1}{gcd}$, $j_2 = \\frac{j_2}{gcd}$, then we rewrite it as $s_2 = i_2 + j_2$, $gcd (i_2, j_2) = 1$, $1 \\le i_2, j_2 \\le \\lfloor \\frac{n-1}{gcd} \\rfloor$. Now we just need to find the number of numbers coprime to $s_2$ on the segment $[max (1, s - \\lfloor \\frac{n-1}{gcd} \\rfloor), min (s-1, \\lfloor \\frac{n-1}{gcd} \\rfloor)]$. This can be done for $O (2 ^ {primes})$, where $primes$ is the number of prime divisors of $s_2$. It can be shown that this gives the asymptotics of $O (n\\log {n} ^ 2)$ (If you have a better one, please share in the comments!)",
    "tags": [
      "combinatorics",
      "strings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1205",
    "index": "F",
    "title": "Beauty of a Permutation",
    "statement": "Define the beauty of a permutation of numbers from $1$ to $n$ $(p_1, p_2, \\dots, p_n)$ as number of pairs $(L, R)$ such that $1 \\le L \\le R \\le n$ and numbers $p_L, p_{L+1}, \\dots, p_R$ are consecutive $R-L+1$ numbers in some order. For example, the beauty of the permutation $(1, 2, 5, 3, 4)$ equals $9$, and segments, corresponding to pairs, are $[1]$, $[2]$, $[5]$, $[4]$, $[3]$, $[1, 2]$, $[3, 4]$, $[5, 3, 4]$, $[1, 2, 5, 3, 4]$.\n\nAnswer $q$ independent queries. In each query, you will be given integers $n$ and $k$. Determine if there exists a permutation of numbers from $1$ to $n$ with beauty equal to $k$, and if there exists, output one of them.",
    "tutorial": "We will denote $(a, b)$ if there exists a permutation of length $a$ with beauty equal to $b$. To begin with, it is obvious that the beauty of a permutation of length $a$ is at least $a + 1$ for $a> 1$: indeed, you can take each element individually and the entire permutation completely. ** Statement 1 **: if $(a_1, b_1)$ and $(a_2, b_2)$, then $(a_1 + a_2 - 1, b_1 + b_2 - 1)$. Let $p_1, p_2, \\dots, p_ {a_1}$ be a permutation of length $a_1$, whose beauty is $b_1$, and $q_1, q_2, \\dots, q_ {a_2}$ be a permutation of length $a_2$, whose beauty is equal to $b_2$. Let us build from them a permutation of length $a_1 + a_2 - 1$, whose beauty is $b_1 + b_2 - 1$. We \"expand\" $p_1$ in the permutation $p$ to $p_1 + q_1 - 1, p_1 + q_2 - 1, \\dots, p_1 + q_ {a_2} - 1$, and to the rest of the elements $p$, greater than $p_1$ , add $a_2-1$. We got a permutation of length $a_1 + a_2 - 1$. Denote it by $t$. If $t_1$ is not between $t_ {a_2}, t_ {a_2 + 1}$, then we reverse the first $a_2$ elements, and this will be done in a new permutation. Now let $t_1$ be between $t_ {a_2}$, $t_ {a_2 + 1}$. Then what good pairs do we have in $t$? There are $b_2$ good pairs among the first $a_2$ elements, there are $b_1$ good pairs if you count the first $a_2$ elements in one, and we counted the interval from the first $a_2$ elements twice, so we counted $b_1 + b_2 - 1$ pairs At the same time, this is all pairs, because if some good segment contains $t_ {a_2}$ and $t_ {a_2 + 1}$, then it must contain $t_1$ as well. Thus, this statement is proved. ** Statement 2 **: if $(a, b)$, then either $b = a + 1$, or $b = \\frac{a (a + 1)}{2}$, or exist $(a_1 , b_1)$, $(a_2, b_2)$ such that $1 <a_1, a_2$, $a_1 + a_2 - 1 = a$ and $b_1 + b_2 - 1 = b$. Show it. We will call subsegments consisting of several consecutive numbers in some order good. Consider some kind of permutation of length $a$ of beauty $b$. Suppose that $b \\neq a + 1$. We want to show that in the permutation there is some good $[L, R]$ subsegment of length not equal to $1$ or $a$, with the following property: for any other good $[L1, R1]$ subsegment if $[L , R]$ and $[L1, R1]$ intersect, then one of them contains the second. In this case, by analogy with the proof of Proposition 1, we can \"squeeze\" the segment $[L, R]$ into one element, obtaining some kind of permutation $q$. Then the number of good segments in the entire permutation will be equal to the number of good sub-segments on the segment $[L, R] +$ the number of good segments in $q$ $-1$ (since we counted the segment $[L, R]$ twice). We will call such a segment very good. Thus, if in each permutation there is a very good segment, then the statement $2$ is true. Suppose that $b \\neq a + 1$, then in the permutation there is a good segment $[L, R]$ of length not equal to $1$ or $a$. Let's say he's not very good. Then there is another. We denote $(a, b)$ if there exists a permutation of length $a$ with beauty equal to $b$. To begin with, it is obvious that the beauty of a permutation of length $a$ is at least $a + 1$ for $a> 1$: indeed, you can take each element individually and the entire permutation completely. ** Statement 1 **: if $(a_1, b_1)$ and $(a_2, b_2)$, then $(a_1 + a_2 - 1, b_1 + b_2 - 1)$. Let $p_1, p_2, \\ dots, p_ {a_1}$ & mdash; a permutation of length $a_1$, whose beauty is $b_1$, and $q_1, q_2, \\ dots, q_ {a_2}$ & mdash; a permutation of length $a_2$, whose beauty is equal to $b_2$. Let us build from them a permutation of length $a_1 + a_2 - 1$, whose beauty is $b_1 + b_2 - 1$. We \"expand\" $p_1$ in the permutation $p$ to $p_1 + q_1 - 1, p_1 + q_2 - 1, \\ dots, p_1 + q_ {a_2} - 1$, and to the rest of the elements $p$, greater than $p_1$ , add $a_2-1$. We got a permutation of length $a_1 + a_2 - 1$. Denote it by $t$. If $t_1$ is not between $t_ {a_2}, t_ {a_2 + 1}$, then we reverse the first $a_2$ elements, and this will be done in a new permutation. Now let $t_1$ be between $t_ {a_2}$, $t_ {a_2 + 1}$. Then what good pairs do we have in $t$? There are $b_2$ good pairs among the first $a_2$ elements, there are $b_1$ good pairs if you count the first $a_2$ elements in one, and we counted the interval from the first $a_2$ elements twice, so we counted $b_1 + b_2 - 1$ pairs At the same time, this is all pairs, because if some good segment contains $t_ {a_2}$ and $t_ {a_2 + 1}$, then it must contain $t_1$ as well. Thus, this statement is proved. ** Statement 2 **: if $(a, b)$, then either $b = a + 1$, or $b = \\frac {a (a + 1)} {2}$, or $(a_1 exists , b_1)$, $(a_2, b_2)$ such that $1 <a_1, a_2$, $a_1 + a_2 - 1 = a$ and $b_1 + b_2 - 1 = b$. Show it. We will call subsegments consisting of several consecutive numbers in some order good. Consider some kind of permutation of length $a$ of beauty $b$. Suppose that $b \\neq a + 1$. We want to show that in the permutation there is some good $[L, R]$ subsegment of length not equal to $1$ or $a$, with the following property: for any other good $[L1, R1]$ subsegment if $[L , R]$ and $[L1, R1]$ intersect, then one of them contains the second. In this case, by analogy with the proof of Proposition 1, we can \"squeeze\" the segment $[L, R]$ into one element, obtaining some kind of permutation $q$. Then the number of good segments in the entire permutation will be equal to the number of good sub-segments on the segment $[L, R] +$ the number of good segments in $q$ $-1$ (since we counted the segment $[L, R]$ twice). We will call such a segment very good. Thus, if in each permutation there is a very good segment, then the statement $2$ is true. Let $[L, R]$ be a good segment that is not very good. Then there is a good segment $[L_1, R_1]$, which intersects with $[L, R]$, but does not contain and is not contained in it. The segments $[L, R]$ and $[L_1, R_1]$ form together $3$ segments. It is easy to show that each of them is good, and the numbers in the segments go monotonously. Let us demonstrate this with an example: $p = (2, 1, 3, 5, 4)$, the first segment is $[2, 1, 3]$, the second is $[3, 5, 4]$. Then together they will give the union of three segments: $[2, 1], [3], [5, 4]$. As we can see, each of these segments is good, and also all numbers in the second segment are larger than all numbers in the first, all numbers in the third segment are larger than all numbers in the second. Let at the moment we have lined up a chain of good segments (going consecutively) $s_1, s_2, \\dots, s_m$, where the union of any several consecutive ones is a good segment, as well as all the numbers in $s_ {i + 1}$ more than all the numbers in $s_i$ (or vice versa). As long as $S = s_1 + s_2 + \\dots + s_m$ is not equal to the whole segment, we will do this: since $S$ is very good, there is a segment $[L, R]$ that intersects with it but is not contained in it does not contain. It is easy to see that, thanks to the segment $[L, R]$, our chain of good segments is extended. Now suppose that $s_1 + s_2 + \\dots + s_m$ is the whole segment. While there is a segment of length greater than $1$ among the segments, we will do the same: if $len (s_i)> 1$, then we will find the necessary $[L, R]$ for it, then $s_i$ will be split into two smaller good segments . At the end of the process, we get $a$ good segments of length $1$ each, and the numbers are sorted monotonously. Hence, the numbers in the permutation were initially sorted monotonously, whence the number of good segments is $\\frac {a (a + 1)} {2}$. The statement $2$ is proved. Now the left is easy: for each $i$ from $1$ to $100$, we calculate what beauty values can be in a permutation of length $i$ using statement $2$, storing the corresponding values $(a_1, b_1), (a_2, b_2 )$. After that, it is easy to answer the request by building a permutation of the desired beauty according to the algorithm with the approval of $1$. Asymptotics of $O (n ^ 6)$ (With an incredibly small constant, up to $n = 100$ on $Codeforces$ this works for 300 ms).",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1206",
    "index": "A",
    "title": "Choose Two Numbers",
    "statement": "You are given an array $A$, consisting of $n$ positive integers $a_1, a_2, \\dots, a_n$, and an array $B$, consisting of $m$ positive integers $b_1, b_2, \\dots, b_m$.\n\nChoose some element $a$ of $A$ and some element $b$ of $B$ such that $a+b$ doesn't belong to $A$ and doesn't belong to $B$.\n\nFor example, if $A = [2, 1, 7]$ and $B = [1, 3, 4]$, we can choose $1$ from $A$ and $4$ from $B$, as number $5 = 1 + 4$ doesn't belong to $A$ and doesn't belong to $B$. However, we can't choose $2$ from $A$ and $1$ from $B$, as $3 = 2 + 1$ belongs to $B$.\n\nIt can be shown that such a pair exists. If there are multiple answers, print any.\n\nChoose and print any such two numbers.",
    "tutorial": "Let $a$ be the largest number in the array $A$, $b$ be the largest number in the array $B$. Then the number $a + b$ isn't present neither in the array $A$ nor in the array $B$. Indeed, $a + b> a$, and $a$ is the largest number in the array $A$, so $a + b$ is not included in $A$. Similarly, $a + b$ is not included in $B$. Thus, you can select $a$ from $A$, $b$ from $B$. The asymptotics is $O (m \\ log {m} + n \\ log {n})$ if you find the largest element by sorting (which many did), or $O (m + n)$ if you find it linearly.",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1206",
    "index": "B",
    "title": "Make Product Equal One",
    "statement": "You are given $n$ numbers $a_1, a_2, \\dots, a_n$. With a cost of one coin you can perform the following operation:\n\nChoose one of these numbers and add or subtract $1$ from it.\n\nIn particular, we can apply this operation to the same number several times.\n\nWe want to make the product of all these numbers equal to $1$, in other words, we want $a_1 \\cdot a_2$ $\\dots$ $\\cdot a_n = 1$.\n\nFor example, for $n = 3$ and numbers $[1, -3, 0]$ we can make product equal to $1$ in $3$ coins: add $1$ to second element, add $1$ to second element again, subtract $1$ from third element, so that array becomes $[1, -1, -1]$. And $1\\cdot (-1) \\cdot (-1) = 1$.\n\nWhat is the minimum cost we will have to pay to do that?",
    "tutorial": "The product of several integers is equal to one if and only if each of these numbers is $1$ or $-1$, and there must be an even number of $-1$. Then: we will have to reduce every positive $a_i$ at least to one, and we have to spend at least $a_i - 1$ coin on this. Similarly, we will have to increase every negative $a_i$ at least to $-1$, for this we will spend at least $-1 - a_i$ coins. Now we have all the numbers equal to $-1$, $0$, or $1$. Let $k$ be the number of $0$ among them. Let's analyze two cases: $k> 0$. We need to replace every zero with either $1$ or $-1$, so we will have to spend at least $k$ coins. It turns out that this is enough: change $k-1$ zeros to $1$ or $-1$ randomly, and change the last zero to $1$ or $-1$ so that the product is equal to one. $k = 0$. If the product of all numbers is $1$, we no longer need to spend coins. Otherwise, you have to change some $1$ to $-1$ or some $-1$ to $1$. This will take another $2$ coins. Asympotics $O (n)$.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1207",
    "index": "A",
    "title": "There Are Two Types Of Burgers",
    "statement": "There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet.\n\nYou have $b$ buns, $p$ beef patties and $f$ chicken cutlets in your restaurant. You can sell one hamburger for $h$ dollars and one chicken burger for $c$ dollars. Calculate the maximum profit you can achieve.\n\nYou have to answer $t$ independent queries.",
    "tutorial": "In this task you just can iterate over the numbers of hamburgers and chicken burgers you want to assemble, check that you have enough ingredients and update the answer. If you want to sell $x$ hamburgers and $y$ chicken burgers then you need $x$ beef patties, $y$ chicken cutlets and $2(x+y)$ buns.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nint b, p, f;\nint h, c;\n\nint main() {\n    cin >> t;\n    for(int tc = 0; tc < t; ++tc){\n        cin >> b >> p >> f;\n        cin >> h >> c;\n\n        b /= 2;\n        if(h < c){\n            swap(h, c);\n            swap(p, f);\n        }\n\n        int res = 0;\n\n        int cnt = min(b, p);\n        b -= cnt, p -= cnt;\n        res += h * cnt; \n        \n        cnt = min(b, f);\n        b -= cnt, f -= cnt;\n        res += c * cnt; \n            \n        cout << res << endl;\n    }\n    return 0;\n}                               ",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1207",
    "index": "B",
    "title": "Square Filling",
    "statement": "You are given two matrices $A$ and $B$. Each matrix contains exactly $n$ rows and $m$ columns. Each element of $A$ is either $0$ or $1$; each element of $B$ is initially $0$.\n\nYou may perform some operations with matrix $B$. During each operation, you choose any submatrix of $B$ having size $2 \\times 2$, and replace every element in the chosen submatrix with $1$. In other words, you choose two integers $x$ and $y$ such that $1 \\le x < n$ and $1 \\le y < m$, and then set $B_{x, y}$, $B_{x, y + 1}$, $B_{x + 1, y}$ and $B_{x + 1, y + 1}$ to $1$.\n\nYour goal is to make matrix $B$ equal to matrix $A$. Two matrices $A$ and $B$ are equal if and only if every element of matrix $A$ is equal to the corresponding element of matrix $B$.\n\nIs it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $B$ equal to $A$. Note that you don't have to minimize the number of operations.",
    "tutorial": "It is quite obvious that we can't choose any submatrix that contains at least one zero in $A$. The contrary is also true - if a submatrix of $A$ consists of only ones, then there's no reason not to choose it (suppose there is an answer that does not choose it - then choosing this submatrix won't affect it). So we may perform an operation on every submatrix of $B$ such that the corresponding submatrix in $A$ is filled with $1$'s, and check if our answer is correct.",
    "code": "n, m = map(int, input().split())\na = [[] for i in range(n)]\nfor i in range(n):\n    a[i] = list(map(int, input().split()))\n\nans = []\nfor i in range(n - 1):\n    for j in range(m - 1):\n        if(a[i][j] * a[i][j + 1] * a[i + 1][j] * a[i + 1][j + 1] > 0):\n            a[i][j] = 2\n            a[i + 1][j] = 2\n            a[i][j + 1] = 2\n            a[i + 1][j + 1] = 2\n            ans.append([i, j])\n\ncnt1 = 0\nfor i in range(n):\n    for j in range(m):\n        if(a[i][j] == 1):\n            cnt1 += 1\n\nif(cnt1 != 0):\n    print(-1)\nelse:\n    print(len(ans))\n    for x in ans:\n        print(x[0] + 1, x[1] + 1)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1207",
    "index": "C",
    "title": "Gas Pipeline",
    "statement": "You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $[0, n]$ on $OX$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $(x, x + 1)$ with integer $x$. So we can represent the road as a binary string consisting of $n$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.\n\nUsually, we can install the pipeline along the road on height of $1$ unit with supporting pillars in each integer point (so, if we are responsible for $[0, n]$ road, we must install $n + 1$ pillars). But on crossroads we should lift the pipeline up to the height $2$, so the pipeline won't obstruct the way for cars.\n\nWe can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $[x, x + 1]$ with integer $x$ consisting of three parts: $0.5$ units of horizontal pipe + $1$ unit of vertical pipe + $0.5$ of horizontal. Note that if pipeline is currently on height $2$, the pillars that support it should also have length equal to $2$ units.\n\nEach unit of gas pipeline costs us $a$ bourles, and each unit of pillar — $b$ bourles. So, it's not always optimal to make the whole pipeline on the height $2$. Find the shape of the pipeline with minimum possible cost and calculate that cost.\n\nNote that you \\textbf{must} start and finish the pipeline on height $1$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0.",
    "tutorial": "This task was designed as a simple dynamic programming problem, but it also can be solved greedily. The dp solution is following: when we have already built some prefix of the pipeline all we need to know is the length of the prefix the height of the pipeline's endpoint ($1$ or $2$). So we can calculate the following dynamic programming: $d[pos][add]$ is the minimal answer for prefix of length $pos$ with pipeline at height $1 + add$. Transitions are quite straightforward: if $s[pos] = 0$ then we can either leave the pipeline on the same level, or change it. If $s[pos] = 1$ then we have to stay on the height $2$. Look at the source code for the formal transitions. The answer is $d[n][0]$. The greedy solution is based on the following fact: let's look at some subsegment consisting of $0$'s. It's always optimal either to leave this subsegment on height $1$ or raise it to height $2$. We can calculate the amount we have to pay in both cases and choose the optimal one.",
    "code": "const val INF64 = 1e18.toLong()\n\nfun main(args: Array<String>) {\n    val tc = readLine()!!.toInt()\n    for (t in 1..tc) {\n        val (n, a, b) = readLine()!!.split(' ').map { it.toInt() }\n        val s = readLine()!!\n\n        val d = Array(n + 1) { arrayOf(INF64, INF64) }\n        d[0][0] = b.toLong()\n\n        for (pos in 0 until n) {\n            if (s[pos] == '0') {\n                d[pos + 1][0] = minOf(d[pos + 1][0], d[pos][0] + a + b)\n                d[pos + 1][1] = minOf(d[pos + 1][1], d[pos][0] + 2 * (a + b))\n\n                d[pos + 1][1] = minOf(d[pos + 1][1], d[pos][1] + a + 2 * b)\n                d[pos + 1][0] = minOf(d[pos + 1][0], d[pos][1] + 2 * a + b)\n            } else {\n                d[pos + 1][1] = minOf(d[pos + 1][1], d[pos][1] + a + 2 * b)\n            }\n        }\n        println(d[n][0])\n    }\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1207",
    "index": "D",
    "title": "Number Of Permutations",
    "statement": "You are given a sequence of $n$ pairs of integers: $(a_1, b_1), (a_2, b_2), \\dots , (a_n, b_n)$. This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences:\n\n- $s = [(1, 2), (3, 2), (3, 1)]$ is bad because the sequence of first elements is sorted: $[1, 3, 3]$;\n- $s = [(1, 2), (3, 2), (1, 2)]$ is bad because the sequence of second elements is sorted: $[2, 2, 2]$;\n- $s = [(1, 1), (2, 2), (3, 3)]$ is bad because both sequences (the sequence of first elements and the sequence of second elements) are sorted;\n- $s = [(1, 3), (3, 3), (2, 2)]$ is good because neither the sequence of first elements $([1, 3, 2])$ nor the sequence of second elements $([3, 3, 2])$ is sorted.\n\nCalculate the number of permutations of size $n$ such that after applying this permutation to the sequence $s$ it turns into a good sequence.\n\nA permutation $p$ of size $n$ is a sequence $p_1, p_2, \\dots , p_n$ consisting of $n$ distinct integers from $1$ to $n$ ($1 \\le p_i \\le n$). If you apply permutation $p_1, p_2, \\dots , p_n$ to the sequence $s_1, s_2, \\dots , s_n$ you get the sequence $s_{p_1}, s_{p_2}, \\dots , s_{p_n}$. For example, if $s = [(1, 2), (1, 3), (2, 3)]$ and $p = [2, 3, 1]$ then $s$ turns into $[(1, 3), (2, 3), (1, 2)]$.",
    "tutorial": "Let's suppose that all $n!$ permutation are good. We counted the permutations giving the sequences where the first elements are sorted (we denote the number of such permutations as $cnt_1$) and the permutations giving the sequences where the second elements are sorted (we denote the number of such permutations as $cnt_2$). Then the answer is $n! - cnt_1 - cnt_2$, right? No, because we subtracted the number of sequences where first and second elements are sorted simultaneously (we denote this number as $cnt_{12}$) twice. So, the answer is $n! - cnt_1 - cnt_2 + cnt_{12}$. How can we calculate the value of $cnt_1$? It's easy to understand that the elements having equal $a_i$ can be arranged in any order. So, $cnt_1 = c_1! ~ c_2! ~ \\dots ~ c_n!$, where $c_x$ is the number of elements equal to $x$ among $a_i$. $cnt_2$ can be calculated the same way. How can we calculate the value of $cnt_{12}$? First of all, there is a case where it is impossible to arrange the elements of the sequence so that the first elements and the second elements are sorted. To check that, we may sort the given sequence comparing two elements by $a_i$, and if $a_i$ are equal - by $b_i$. If the sequence of second elements in the resulting sequence is not sorted, then $cnt_{12} = 0$. Otherwise, equal elements of the given sequence can be arranged in any order. So $cnt_{12} = c_{s_1}! ~ c_{s_2}! ~ c_{s_k}!$, where $s_1$, $s_2$, ..., $s_k$ are the elements that appear in the given sequence of pairs at least once.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\nconst int MOD = 998244353;\n\nint mul(int a, int b){\n    return (a * 1LL * b) % MOD;\n}\n\n\nint sum(int a, int b){\n    return (a + b) % MOD;\n}\n\nint n;\npair<int, int> a[N];\nint f[N];\n\nint main() {\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; ++i)\n        scanf(\"%d%d\", &a[i].first, &a[i].second);\n\n    f[0] = 1;\n    for(int i = 1; i < N; ++i)\n        f[i] = mul(i, f[i - 1]);\n\n    int res = f[n];\n    for(int c = 0; c < 2; ++c){\n        int d = 1;\n        sort(a, a + n);\n        int l = 0;\n        while(l < n){\n            int r = l + 1;\n            while(r < n && a[l].first == a[r].first) ++r;\n            d = mul(d, f[r - l]);\n            l = r;\n        }\n        res = sum(res, MOD - d);\n        for(int i = 0; i < n; ++i) \n            swap(a[i].first, a[i].second);\n    }       \n\n    sort(a, a + n);\n    int l = 0;\n    int d = 1;\n    while(l < n){\n        int r = l + 1;\n        while(r < n && a[l].first == a[r].first) ++r;\n        map<int, int> m;\n        for(int i = l; i < r; ++i) ++m[a[i].second];\n        for(auto p : m) d = mul(d, f[p.second]);\n        l = r;\n    }\n    for(int i = 1; i < n; ++i) \n        if(a[i - 1].second > a[i].second) d = 0;\n\n    res = sum(res, d);\n    printf(\"%d\\n\", res);\n    return 0;\n}                               ",
    "tags": [
      "combinatorics"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1207",
    "index": "E",
    "title": "XOR Guessing",
    "statement": "\\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.\n\nThe jury picked an integer $x$ not less than $0$ and not greater than $2^{14} - 1$. You have to guess this integer.\n\nTo do so, you may ask no more than $2$ queries. Each query should consist of $100$ integer numbers $a_1$, $a_2$, ..., $a_{100}$ (each integer should be not less than $0$ and not greater than $2^{14} - 1$). In response to your query, the jury will pick one integer $i$ ($1 \\le i \\le 100$) and tell you the value of $a_i \\oplus x$ (the bitwise XOR of $a_i$ and $x$). There is an additional constraint on the queries: all $200$ integers you use in the queries should be distinct.\n\n\\textbf{It is guaranteed that the value of $x$ is fixed beforehand in each test, but the choice of $i$ in every query may depend on the integers you send.}",
    "tutorial": "Suppose all integers we input in some query have the same value in the $k$-th bit. Then no matter which $i$ is chosen by the jury, we can always deduce whether the $k$-th bit in $x$ is $0$ or $1$. This leads us to a simple solution: divide $14$ bits of $x$ into two groups of size $7$. In the first query, submit $100$ integers having the same values in the bits from the first group, and deduce the values of these bits in $x$. In the second query, do the same for the second group. Be careful to avoid submitting the same integer twice.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    cout << \"?\";\n    for(int i = 1; i <= 100; i++)\n        cout << \" \" << i;\n    cout << endl;\n    cout.flush();\n    int res1;\n    cin >> res1;\n    cout << \"?\";\n    for(int i = 1; i <= 100; i++)\n        cout << \" \" << (i << 7);\n    cout << endl;\n    cout.flush();\n    int res2;\n    cin >> res2;\n    int x = 0;\n    x |= (res1 & (((1 << 7) - 1) << 7));\n    x |= (res2 & ((1 << 7) - 1));\n    cout << \"! \" << x << endl;\n    cout.flush();\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "interactive",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1207",
    "index": "F",
    "title": "Remainder Problem",
    "statement": "You are given an array $a$ consisting of $500000$ integers (numbered from $1$ to $500000$). Initially all elements of $a$ are zero.\n\nYou have to process two types of queries to this array:\n\n- $1$ $x$ $y$ — increase $a_x$ by $y$;\n- $2$ $x$ $y$ — compute $\\sum\\limits_{i \\in R(x, y)} a_i$, where $R(x, y)$ is the set of all integers from $1$ to $500000$ which have remainder $y$ modulo $x$.\n\nCan you process all the queries?",
    "tutorial": "Let's notice that if we process the queries of type $2$ naively, then each such query consumes $O(\\frac{N}{x})$ time (where $N$ is the size of the array). So queries with large $x$ can be processed naively. For queries with small $x$ ($x \\le K$), we may notice two things: there are only $O(K^2)$ possible queries; each number in the array affects only $K$ possible queries. So, for small $x$, we may maintain the exact answer for each query and modify it each time we modify an element in the array. If we process naively all queries with $x > \\sqrt{N}$ and maintain the answers for all queries with $x \\le \\sqrt{N}$, we will obtain a solution having time complexity $O(q \\sqrt{N})$. Note that, as in most problems related to sqrt-heuristics, it may be optimal to choose the constant that is not exactly $\\sqrt{N}$, but something similar to it (but most solutions should pass without tuning the constant).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 500043;\nconst int K = 750;\n\nint a[N];\nint sum[K][K];\n\nint main()\n{\n    int q;\n    scanf(\"%d\", &q);\n    for(int i = 0; i < q; i++)\n    {\n        int t, x, y;\n        scanf(\"%d %d %d\", &t, &x, &y);\n        if(t == 1)\n        {\n            a[x] += y;\n            for(int i = 1; i < K; i++)\n                sum[i][x % i] += y;\n        }\n        else\n        {\n            if(x >= K)\n            {\n                int ans = 0;\n                for(int i = y; i <= 500000; i += x)\n                    ans += a[i];\n                printf(\"%d\\n\", ans);\n            }\n            else\n                printf(\"%d\\n\", sum[x][y]);\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1207",
    "index": "G",
    "title": "Indie Album",
    "statement": "Mishka's favourite experimental indie band has recently dropped a new album! Songs of that album share one gimmick. Each name $s_i$ is one of the following types:\n\n- $1~c$ — a single lowercase Latin letter;\n- $2~j~c$ — name $s_j$ ($1 \\le j < i$) with a single lowercase Latin letter appended to its end.\n\nSongs are numbered from $1$ to $n$. It's guaranteed that the first song is always of type $1$.\n\nVova is rather interested in the new album but he really doesn't have the time to listen to it entirely. Thus he asks Mishka some questions about it to determine if some song is worth listening to. Questions have the following format:\n\n- $i~t$ — count the number of occurrences of string $t$ in $s_i$ (the name of the $i$-th song of the album) as a continuous substring, $t$ consists only of lowercase Latin letters.\n\nMishka doesn't question the purpose of that information, yet he struggles to provide it. Can you please help Mishka answer all Vova's questions?",
    "tutorial": "There is a common approach for the problem \"you are given a lot of strings and texts, count the number of occurences of the strings in the texts\" - build an Aho-Corasick automaton on the given strings and somehow process the texts with it. Let's see if it can handle this problem. The names of the songs can be represented as a tree. We may build an Aho-Corasick on the strings given in the queries, then try to input the names of the album into the automaton character-by-character with DFS on the aforementioned tree (feeding a character to the automaton when we enter a node, and reverting the automaton to the previous state when we leave that node). Suppose that when we are in the vertex corresponding to the $v$-th song, the automaton is in state $c$. If $c$ is a terminal state corresponding to some string from the queries, it means that the string from the query is a suffix of the $v$-th song. But some other strings can also be the suffixes of the same song - to find all such strings, we can start ascending from the state $c$ to the root of Aho-Corasick automaton using suffix links or dictionary links. Since suffix links can be represented as the edges of some rooted tree, then we can build some data structure on this tree that allows adding an integer to all vertices on the path from the root to the given vertex (for example, we can use Fenwick tree over Euler tour of the tree). Then, to check whether some string $t$ from the query is a suffix of the song $v$, we may add $1$ to all vertices on the path to state $c$, and then check the value in the state corresponding to $t$. Okay, what about counting the occurences of $t$ in $v$? Let's consider the path from the root to $v$ in the \"song tree\". Every vertex on this path corresponds to some prefix of the song $v$, so we can add $1$ on the path to every state corresponding to some prefix, and then extract the answer from the state corresponding to $t$. In fact, that's all we have to do to obtain a solution. Build an automaton on strings from queries, a tree of suffix links over this automaton, and a data structure on this tree; for each vertex of the song tree, store all queries to it. Then run a DFS on the song tree. When we enter some vertex, input the corresponding character into the automaton and add $1$ to all states from the root of suffix link tree to the current state; when we have to process queries to the current vertex, extract the values from the data structure; and when we leave a vertex, subtract $1$ from all states from the root of suffix link tree to the current state, and revert to the previous state. This solution has complexity of $O(T \\log T)$, where $T$ is the total length of all strings in the input.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int AL = 26;\nconst int N = 400 * 1000 + 13;\n\nstruct node{\n    int nxt[AL];\n    node(){\n        memset(nxt, -1, sizeof(nxt));\n    }\n    int& operator [](int x){\n        return nxt[x];\n    }\n};\n\nstruct node_at{\n    int nxt[AL];\n    int p;\n    char pch;\n    int link;\n    int go[AL];\n    node_at(){\n        memset(nxt, -1, sizeof(nxt));\n        memset(go, -1, sizeof(go));\n        link = p = -1;\n    }\n    int& operator [](int x){\n        return nxt[x];\n    }\n};\n\nint cntnm;\nnode trienm[N];\n\nint cntqr;\nnode_at trieqr[N];\n\nint add_string(string s){\n    int v = 0;\n    for (auto it : s){\n        int c = it - 'a';\n        if (trieqr[v][c] == -1){\n            trieqr[cntqr] = node_at();\n            trieqr[cntqr].p = v;\n            trieqr[cntqr].pch = c;\n            trieqr[v][c] = cntqr;\n            ++cntqr;\n        }\n        v = trieqr[v][c];\n    }\n    return v;\n}\n\nint go(int v, int c);\n \nint get_link(int v){\n    if (trieqr[v].link == -1){\n        if (v == 0 || trieqr[v].p == 0)\n            trieqr[v].link = 0;\n        else\n            trieqr[v].link = go(get_link(trieqr[v].p), trieqr[v].pch);\n    }\n    return trieqr[v].link;\n}\n \nint go(int v, int c) {\n    if (trieqr[v].go[c] == -1){\n        if (trieqr[v][c] != -1)\n            trieqr[v].go[c] = trieqr[v][c];\n        else\n            trieqr[v].go[c] = (v == 0 ? 0 : go(get_link(v), c));\n    }\n    return trieqr[v].go[c];\n}\n\nint add_letter(int v, int c){\n    if (trienm[v][c] == -1){\n        trienm[cntnm] = node();\n        trienm[v][c] = cntnm;\n        ++cntnm;\n    }\n    return trienm[v][c];\n}\n\nvector<int> g[N];\nint tin[N], tout[N], T;\n\nvoid dfs_init(int v){\n    tin[v] = T++;\n    for (auto u : g[v])\n        dfs_init(u);\n    tout[v] = T;\n}\n\nint f[N];\n\nvoid upd(int v, int val){\n    for (int i = tin[v]; i < N; i |= i + 1)\n        f[i] += val;\n}\n\nint get(int x){\n    int sum = 0;\n    for (int i = x; i >= 0; i = (i & (i + 1)) - 1)\n        sum += f[i];\n    return sum;\n}\n\nint sum(int v){\n    return get(tout[v] - 1) - get(tin[v] - 1);\n}\n\nint n, m;\nint nm[N], qr[N];\nvector<int> nms[N];\nvector<int> reqs[N];\nint ans[N];\n\nvoid dfs(int v, int cur){\n    upd(cur, 1);\n    for (auto it : nms[v])\n        for (auto q : reqs[it])\n            ans[q] = sum(qr[q]);\n    forn(i, AL) if (trienm[v][i] != -1)\n        dfs(trienm[v][i], go(cur, i));\n    upd(cur, -1);\n}\n\nint main(){\n    cntqr = 0;\n    trieqr[cntqr++] = node_at();\n    \n    cntnm = 0;\n    trienm[cntnm++] = node();\n    \n    char buf[N];\n    scanf(\"%d\", &n);\n    forn(i, n){\n        int t;\n        scanf(\"%d\", &t);\n        if (t == 1){\n            scanf(\"%s\", buf);\n            nm[i] = add_letter(0, buf[0] - 'a');\n        }\n        else{\n            int j;\n            scanf(\"%d%s\", &j, buf);\n            --j;\n            nm[i] = add_letter(nm[j], buf[0] - 'a');\n        }\n        nms[nm[i]].push_back(i);\n    }\n    \n    scanf(\"%d\", &m);\n    forn(i, m){\n        int j;\n        scanf(\"%d%s\", &j, buf);\n        --j;\n        reqs[j].push_back(i);\n        qr[i] = add_string(buf);\n    }\n    \n    for (int v = 1; v < cntqr; ++v)\n        g[get_link(v)].push_back(v);\n    \n    T = 0;\n    dfs_init(0);\n    dfs(0, 0);\n    \n    forn(i, m)\n        printf(\"%d\\n\", ans[i]);\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "hashing",
      "string suffix structures",
      "strings",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1208",
    "index": "A",
    "title": "XORinacci",
    "statement": "Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:\n\n- $f(0) = a$;\n- $f(1) = b$;\n- $f(n) = f(n-1) \\oplus f(n-2)$ when $n > 1$, where $\\oplus$ denotes the bitwise XOR operation.\n\nYou are given three integers $a$, $b$, and $n$, calculate $f(n)$.\n\nYou have to answer for $T$ independent test cases.",
    "tutorial": "The sequence is $a$, $b$, $a\\oplus b$, $a$, $b$, $a\\oplus b$ $\\cdots$ Since, the sequence has a period of $3$, $f[i] = f[i \\mod 3]$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n    int test,a,b,n;\n    cin>>test;\n    while(test--){\n        cin>>a>>b>>n;\n        switch (n%3){\n            case 0:\n              cout<<a<<endl;\n              break;\n            case 1:\n              cout<<b<<endl;\n              break;\n            default:\n              cout<<(a^b)<<endl;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1208",
    "index": "B",
    "title": "Uniqueness",
    "statement": "You are given an array $a_{1}, a_{2}, \\ldots, a_{n}$. You can remove \\textbf{at most one} subsegment from it. The remaining elements should be pairwise distinct.\n\nIn other words, \\textbf{at most one} time you can choose two integers $l$ and $r$ ($1 \\leq l \\leq r \\leq n$) and delete integers $a_l, a_{l+1}, \\ldots, a_r$ from the array. Remaining elements should be pairwise distinct.\n\nFind the minimum size of the subsegment you need to remove to make all remaining elements distinct.",
    "tutorial": "After removing a sub-segment, a prefix and a suffix remain, possibly of length $0$. Let us fix the prefix which does not contain any duplicate elements and find the maximum suffix we can get without repeating the elements. We can use map/set to keep track of the elements. Time complexity: $O(n^2 \\cdot log(n))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2e3 + 5;\nint a[N];\n\nint main(){\n    int n;\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; ++i){\n        scanf(\"%d\", &a[i]);\n    }\n\n    int ans = n - 1;\n    map<int, int> freq; \n    for(int i = 0; i < n; ++i){\n        bool validPrefix = true;\n        for(int j = 0; j < i; ++j){\n            freq[a[j]]++;\n            if(freq[a[j]] == 2){\n                validPrefix = false;\n                break;\n            }\n        }\n        int min_index_suffix = n;\n        for(int j = n - 1; j >= i; --j){\n            freq[a[j]]++;\n            if(freq[a[j]] == 1){\n                min_index_suffix = j;\n            }\n            else break;\n        }\n        if(validPrefix){\n            ans = min(ans, min_index_suffix - i);\n        }\n        \n        freq.clear();\n    }\n    cout << ans << '\\n';",
    "tags": [
      "binary search",
      "brute force",
      "implementation",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1208",
    "index": "C",
    "title": "Magic Grid",
    "statement": "Let us define a magic grid to be a square matrix of integers of size $n \\times n$, satisfying the following conditions.\n\n- All integers from $0$ to $(n^2 - 1)$ inclusive appear in the matrix \\textbf{exactly once}.\n- Bitwise XOR of all elements in a row or a column must be the same for each row and column.\n\nYou are given an integer $n$ which is a \\textbf{multiple of $4$}. Construct a magic grid of size $n \\times n$.",
    "tutorial": "Divide the grid into four quadrants. Assign distinct integers to the first quadrant from $0$ to $(\\frac{N^2}{4} - 1)$. Copy this quadrant to the other three. This way XOR of each row and column becomes $0$. Now, to make numbers distinct among the quadrants, multiply the numbers by $4$. Add $1$, $2$, and $3$ to the numbers in $1^{st}$, $2^{nd}$ and $3^{rd}$ quadrants respectively. The XOR of each row and column would still remain $0$ as $N/2$ is also even but the elements will become distinct while being in the range $[0, N^2-1].$ Another approach in this problem is to use a $4 \\times 4$ grid given in the sample itself and replicate it in $N \\times N$ grid by adding $16, 32, 48 \\cdots$ to make the elements distinct. Of course, there are multiple ways to solve the problem. These are just a few of them.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int     long long\n#define ld      long double\n#define pii     pair<int ,int>\n#define pld     pair<ld ,ld>\n#define F       first\n#define S       second\n#define mod     1000000007\n#define pb      push_back\n#define mp      make_pair\n#define all(x)  x.begin(),x.end()\n#define mset(x) memset(x, 0, sizeof(x));\n#define ios     ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\nconst int N = 1000;\n\nint n, grid[N][N];\nvoid run(){\n    cin >> n;\n\n    /* \n    Divide Grid into Quandrants as follows:\n    1 | 2\n    -----\n    3 | 4\n    */\n\n    int fill = 0;\n    for(int i = 0; i < n/2; i++){\n        for(int j = 0; j < n/2; j++){\n\n            grid[i][j]              = 4*fill + 1;   // 1st quadrant\n            grid[i][j + n/2]        = 4*fill + 2;   // 2nd quadrant\n            grid[i + n/2][j]        = 4*fill + 3;   // 3rd quadrant\n            grid[i + n/2][j + n/2]  = 4*fill;       // 4th quadrant\n            \n            fill++;\n\n        }\n    }\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < n; j++){\n            cout << grid[i][j] << \" \";\n        }\n        cout << endl;\n    }\n}\n\nsigned main(){\n    int tests = 1;\n    // cin >> tests;\n    for(int i = 1; i <= tests; i++) run();\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1208",
    "index": "D",
    "title": "Restore Permutation",
    "statement": "An array of integers $p_{1},p_{2}, \\ldots,p_{n}$ is called a permutation if it contains each number from $1$ to $n$ exactly once. For example, the following arrays are permutations: $[3,1,2], [1], [1,2,3,4,5]$ and $[4,3,1,2]$. The following arrays are not permutations: $[2], [1,1], [2,3,4]$.\n\nThere is a hidden permutation of length $n$.\n\nFor each index $i$, you are given $s_{i}$, which equals to the sum of all $p_{j}$ such that $j < i$ and $p_{j} < p_{i}$. In other words, $s_i$ is the sum of elements before the $i$-th element that are smaller than the $i$-th element.\n\nYour task is to restore the permutation.",
    "tutorial": "Let us fill the array with numbers from $1$ to $N$ in increasing order. $1$ will lie at the last index $i$ such that $s_{i} = 0$. Find and remove this index $i$ from the array and for all indices greater than $i$, reduce their $s_{i}$ values by $1$. Repeat this process for numbers $2, 3, ...N$. In the $i^{th}$ turn, reduce the elements by $i$. To find the last index with value zero, we can use segment tree to get range minimum query with lazy propagation. Time complexity: $O(N \\cdot log(N))$ For every i from $N$ to 1, let's say the value of the $s_{i}$ is x. So it means there are $k$ smallest unused numbers whose sum is $x$. We simply put the $k+1$st number in the output permutation at this $i$, and continue to move left. This can be implemented using BIT and binary lifting. Thanks to izoomrood for expressing the solution in the above words.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 2e5 + 5;\nlong long BIT[N], s[N];\nint n;\nint ans[N];\n\nvoid update(int x, int delta){\n      for(; x <= n; x += x&-x)\n        BIT[x] += delta;\n}\n\nlong long query(int x){\n     long long sum = 0;\n     for(; x > 0; x -= x&-x)\n        sum += BIT[x];\n     return sum;\n}\n\nint searchNumber(long long prefSum){\n\n    int num = 0;\n    long long sum = 0;\n    for(int i = 21; i>=0 ; --i){\n        if((num + (1<<i) <= n) && (sum + BIT[num + (1<<i)] <= prefSum)){\n            num += (1<<i);\n            sum += BIT[num];\n        }\n    }\n    return num + 1;\n}\n\nint main(){\n\tscanf(\"%d\",&n);\n\tfor(int i = 1; i <= n; ++i){\n        update(i, i);\n\t\tscanf(\"%lld\", &s[i]);\n\t}\n\tfor(int i = n; i >= 1; --i){\n        ans[i] = searchNumber(s[i]);\n        update(ans[i], -ans[i]);\n    } \n    for(int i = 1; i <= n; ++i){\n        printf(\"%d\", ans[i]);\n        if(i < n){\n            printf(\" \");\n        }\n        else printf(\"\\n\");\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1208",
    "index": "E",
    "title": "Let Them Slide",
    "statement": "You are given $n$ arrays that can have different sizes. You also have a table with $w$ columns and $n$ rows. The $i$-th array is placed horizontally in the $i$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table.\n\nYou need to find the maximum sum of the integers in the $j$-th column for each $j$ from $1$ to $w$ independently.\n\n\\begin{center}\n{\\small Optimal placements for columns $1$, $2$ and $3$ are shown on the pictures from left to right.}\n\\end{center}\n\nNote that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero.",
    "tutorial": "For every array $i$ from $1$ to $N$, let us maintain 2 pointers $L[i]$ and $R[i]$, representing the range of elements in $i_{th}$ array, that can be accessed by the current column index $j$. Initially all $L[i]$ and $R[i]$ would be set equal to 0. As we move from $j_{th}$ index to $(j+1)_{th}$ index, some $L[i]$ and $R[i]$ would change. Specifically, all those arrays which have $size \\ge min(j,W-j-1)$ would have their $L[i]$ and $R[i]$ change. Since overall movement of $L[i]$ and $R[i]$ would be equal to $2 \\cdot$ size_of_array($i$). Overall change would be of order of $O(\\sum a[i])$. For every array we need range max query in $(L[i], R[i])$. We can use multisets/ segment trees/ deques to update the answers corresponding to an array if its $L[i], R[i]$ changes. This way we can get complexity $O(N)$ or $O(N \\cdot log(N))$ depending upon implementation.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1e6 + 5;\nlong long ans[N];\nvector<pair<int, int> > add_element[N], remove_element[N];\nmultiset<int> global_ms[N];\n\nint main(){\n\tint n,w;\n\tscanf(\"%d %d\", &n, &w);\n\tfor(int i = 0; i < n; ++i){\n\t\tint cnt;\n\t\tscanf(\"%d\", &cnt);\n\t\tfor(int j = 0; j < cnt; ++j){\n\t\t\tint x,l,r;\n\t\t\tscanf(\"%d\", &x);\n\t\t\tadd_element[j].push_back(make_pair(x, i));\n\t\t\tremove_element[j + w - cnt].push_back(make_pair(x, i));\n\t\t}\n\t\tif(cnt < w){\n\t\t\tadd_element[cnt].push_back(make_pair(0, i));\n\t\t\tremove_element[w - 1].push_back(make_pair(0, i));\n\t\t\tadd_element[0].push_back(make_pair(0, i));\n\t\t\tremove_element[w - 1 - cnt].push_back(make_pair(0, i));\n\t\t}\n\t}\n\tfor(int i = 0; i < w; ++i){\n\n\t\tfor(auto j:add_element[i]){\n\t\t\tint idx = j.second;\n\t\t\tint val = j.first;\n\t\t\tans[i] -= (global_ms[idx].empty()? 0: *global_ms[idx].rbegin());\n\t\t\tglobal_ms[idx].insert(val);\n\t\t\tans[i] += *global_ms[idx].rbegin();\n\t\t}\t\n\n\t\tif(i < w - 1){\n\t\t\tans[i + 1] = ans[i];\n\t\t\tfor(auto j:remove_element[i]){\n\t\t\t\tint idx = j.second;\n\t\t\t\tint val = j.first;\n\t\t\t\tans[i + 1] -= (*global_ms[idx].rbegin());\n\t\t\t\tglobal_ms[idx].erase(global_ms[idx].find(val));\n\t\t\t\tans[i + 1] += (global_ms[idx].empty()? 0: *global_ms[idx].rbegin());\n\t\t\t}\n\t\t}\n\t\tprintf(\"%lld \",ans[i]);\n\t}\n\tprintf(\"\\n\");\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1208",
    "index": "F",
    "title": "Bits And Pieces",
    "statement": "You are given an array $a$ of $n$ integers.\n\nYou need to find the maximum value of $a_{i} | ( a_{j} \\& a_{k} )$ over all triplets $(i,j,k)$ such that $i < j < k$.\n\nHere $\\&$ denotes the bitwise AND operation, and $|$ denotes the bitwise OR operation.",
    "tutorial": "The idea is to first fix some $a[i]$ and try to get the bits which are off in $a[i]$ from any $2$ elements to the right of $i$. Since, we need to maximize the value, we will try to get higher bits first. What we need now is, for every number $x$ from $0$ to $2^{21}-1$, the $2$ right most positions such that the bits present in $x$ are also present in the elements on those positions. This can be done by iterating over submasks(slow) or SOS-DP(fast). Once we process the positions for every $x$, let us fix some $a[i]$ and iterate over the bits which are off in $a[i]$ from the highest to the lowest. Lets say the current maximum we have got is $w$ and we are going to consider the $y^{th}$ bit. We can get this bit if the $2$ positions for $w|2^{y}$ are to the right of $i$ else we can not. The final answer would be the maximum of $a[i]|w$ over all $i$ from $1$ to $N$. Time complexity $O((M+N)\\cdot logM)$ where $M$ is the max element in the array.",
    "code": "#include <bits/stdc++.h>\n\n#define ll          long long\n#define pb          push_back\n#define pii         pair<int,int>\n#define vi          vector<int>\n#define vii         vector<pii>\n#define mi          map<int,int>\n#define mii         map<pii,int>\n#define all(a)      (a).begin(),(a).end()\n#define x           first\n#define y           second\n#define sz(x)       (int)x.size()\n#define endl        '\\n'\n#define hell        1000000007\n#define rep(i,a,b)  for(int i=a;i<b;i++)\nusing namespace std;\n\nint n,a[1000006],ans,bits;\npii dp[1<<21];\n\nvoid add(int mask,int w){\n    if(dp[mask].x==-1) dp[mask].x=w;\n    else if(dp[mask].y==-1){\n        if(dp[mask].x==w) return;\n        dp[mask].y=w;\n        if(dp[mask].x>dp[mask].y) swap(dp[mask].x,dp[mask].y);\n    }\n    else{\n        if(dp[mask].y<w){\n            dp[mask].x=dp[mask].y;\n            dp[mask].y=w;\n        }\n        else if(dp[mask].x<w and dp[mask].y!=w) dp[mask].x=w;\n    }\n}\n\n\nvoid merge(int m1,int m2){\n    if(dp[m2].x!=-1) add(m1,dp[m2].x);\n    if(dp[m2].y!=-1) add(m1,dp[m2].y);\n}\n\nvoid solve(){\n\tmemset(dp,-1,sizeof dp);\n    cin>>n;\n    rep(i,0,n){\n        cin>>a[i];\n        add(a[i],i);\n        bits=max((int)log2(a[i]),bits);\n    }\n    bits++;\n    rep(i,0,bits){\n        rep(mask,0,1<<bits){\n            if(mask&(1<<i)){\n                merge(mask^(1<<i),mask);\n            }\n        }\n    }\n    rep(i,0,n){\n        int cur=(1<<bits)-1-a[i];\n        int opt=0;\n        for(int j=bits-1;j>=0;j--){\n            if((cur>>j)&1){\n                if(dp[opt^(1<<j)].y!=-1 and dp[opt^(1<<j)].x>i){\n                    opt^=(1<<j);\n                }\n            }\n        }\n        if(dp[opt].y!=-1 and dp[opt].x>i) ans=max(ans,a[i]^opt);\n    }\n    cout<<ans<<endl;\n}\n\nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int t=1;\n    // cin>>t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1208",
    "index": "G",
    "title": "Polygons",
    "statement": "You are given two integers $n$ and $k$.\n\nYou need to construct $k$ regular polygons having same circumcircle, with \\textbf{distinct} number of sides $l$ between $3$ and $n$.\n\n\\begin{center}\n{\\small Illustration for the first example.}\n\\end{center}\n\nYou can rotate them to minimize the total number of distinct points on the circle. Find the minimum number of such points.",
    "tutorial": "If we choose a polygon with side length $l$, it is profitable to choose polygons with side lengths as divisors of $l$ as well, because this will not increase the answer. So our final set would be such that for every polygon with side length $l$, we would have polygons with side length as divisors of $l$ as well. All polygons should have at least one common point in the final arrangement, say $P$ or else we can rotate them and get such $P$. For formal proof, please refer this comment by orz. Let us represent points on the circle as the distance from point $P$. Like for $k$ sided polygon, $0$,$\\frac{1}{k} ,\\frac{2}{k} , \\dots \\frac{k-1}{k}$. Now the number of unique fractions over all the polygons would be our answer, which is equal to sum of $\\phi (l)$ over all side lengths $l$ of the polygons because for $l$ sided polygon there will be $\\phi(l)$ extra points required by it as compared to its divisors. One observation to get to the final solution is $\\phi(l) \\ge \\phi(divisor(l))$. So, we can sort the side lengths by their $\\phi$ values and take the smallest $k$ of them. This will minimize the number of points as well as satisfy the property of our set. NOTE: We can not consider polygon of side length $2$. This can be handled easily.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint phi[1000006];\nvoid process_phis(int n){\n    iota(phi,phi+n+1,0);\n    for(int i = 2 ; i<=n;i++){\n        if(phi[i]==i){\n            phi[i]=i-1;\n            for(int j=2*i;j<=n;j+=i){\n                phi[j]=(phi[j]/i)*(i-1);\n            }\n        }\n    }\n}\nint main(){\n    int n,k;\n    cin>>n>>k;\n    if(k==1){\n        cout<<3<<endl;\n        return 0;\n    }\n    process_phis(n);\n    k+=2;\n    sort(phi+1,phi+n+1);\n    cout<<accumulate(phi+1,phi+k+1,0LL)<<endl;\n    return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1208",
    "index": "H",
    "title": "Red Blue Tree",
    "statement": "You are given a tree of $n$ nodes. The tree is rooted at node $1$, which is not considered as a leaf regardless of its degree.\n\nEach leaf of the tree has one of the two colors: red or blue. Leaf node $v$ initially has color $s_{v}$.\n\nThe color of each of the internal nodes (including the root) is determined as follows.\n\n- Let $b$ be the number of blue immediate children, and $r$ be the number of red immediate children of a given vertex.\n- Then the color of this vertex is blue if and only if $b - r \\ge k$, otherwise red.\n\nInteger $k$ is a parameter that is same for all the nodes.\n\nYou need to handle the following types of queries:\n\n- 1 v: print the color of node $v$;\n- 2 v c: change the color of leaf $v$ to $c$ ($c = 0$ means red, $c = 1$ means blue);\n- 3 h: update the current value of $k$ to $h$.",
    "tutorial": "Transform queries into two types: \"change color of a leaf\", and \"answer color of some vertex if k is given\". Note that when $k = -\\infty$ all internal vertices are red. When increasing $k$, each vertex will change its color exactly once, let's call this value of $k$ as boundary value for this vertex. If we can keep boundary values for all vertices, answering queries is easy. Let's do sqrt decomposition on queries: group them in blocks and process in blocks of size $m$. When starting a block, compress the tree so that there are $O(m)$ interesting vertices: vertices involved in queries and LCAs of them. Let's call subtrees without interesting vertices as outer subtrees. We can compute the boundary values for all vertices in outer subtrees once for each block since the colors of leaves do not change. Now we should compress the paths between the interesting vertices. Note that the boundary values on a path only depend on the color of the vertex in the bottom end of the path. So for each such path compute two boundary values: if the vertex in the bottom end is red or blue. Now we can process queries by using the corresponding values of boundary values, going down-up. Straightforward implementation leads to $O(n\\log{n})$ preprocessing of each block and $O(m\\log{n})$ query time, meaning the overall complexity is $O((n + q) \\sqrt{n + q} \\log{n})$. The logarithms are from sorting and binary search, respectively, so this solution is already fast enough to get AC. To implement compression in $O(n)$ you need to go from lowest to highest possible $k$ and maintain which vertices are red in outer subtrees. Note that the number of different boundary values is $O(n)$, so you can store for each $k$ the list of vertices having this boundary value. To implement queries in $O(m)$, you need to precompute binary search outcomes for the given $O(m)$ values while computing the boundary values. This way the overall complexity becomes $O((n + q) \\sqrt{n + q})$.",
    "code": "/**\n * This line was copied from template\n * This is nk_sqrt_300.cpp\n * \n * @author: Nikolay Kalinin\n * @date: Fri, 23 Aug 2019 22:28:23 +0300\n */\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#ifdef LOCAL\n    #define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n    #define eprintf(...) 42\n#endif\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nconst int maxn = 100005;\nconst int infk = maxn;\n\nconst int BSZ = 700;\n\nvector<int> gr[maxn];\nvector<int> dead_ends[maxn];\nint th[maxn][2];\nint threshold[maxn];\nint up[maxn], fastup[maxn];\nbool isleaf[maxn];\nint curcnt[maxn];\nint was[maxn];\nint curk, curkid;\nint n;\nint timer;\nint c[maxn];\nbool isinteresting[maxn];\nvector<int> interesting;\npair2<int> qs[BSZ];\nvector<int> at[2 * BSZ];\nqueue<int> q;\nint path[maxn];\nvector<int> ks;\nvector<int> cntdead[2 * BSZ];\nint intid[maxn];\nvector<int> order;\nint newid[maxn];\nvector<int> grinit[maxn];\nint compk[2 * infk + 5];\n\nvoid leavedesc(int cur, int pr)\n{\n    newid[cur] = order.size();\n    up[newid[cur]] = newid[pr];\n    order.pb(cur);\n    for (int i = 0; i < (int)grinit[cur].size(); i++)\n    {\n        if (grinit[cur][i] == pr)\n        {\n            swap(grinit[cur][i], grinit[cur].back());\n            grinit[cur].pop_back();\n            i--;\n        } else\n        {\n            leavedesc(grinit[cur][i], cur);\n        }\n    }\n}\n\n\ninline void computecolor(int cur)\n{\n    if (was[cur] != timer) curcnt[cur] = 0;\n    int cntred = curcnt[cur];\n    cntred += (int)cntdead[intid[cur]].size() <= curkid ? cntdead[intid[cur]].back() : cntdead[intid[cur]][curkid];\n    int cntblue = (int)gr[cur].size() - cntred;\n    if (cntblue - cntred >= curk) c[cur] = 1;\n    else c[cur] = 0;\n}\n\ninline void pushtoparent(int cur)\n{\n    if (cur == 0) return;\n    int par = fastup[cur];\n    \n    int colorup = 1 - (curk >= th[cur][c[cur]]);\n    \n    if (was[par] != timer)\n    {\n        was[par] = timer;\n        curcnt[par] = 0;\n    }\n    curcnt[par] += 1 - colorup;\n}\n\nint main()\n{\n    scanf(\"%d%d\", &n, &curk);\n    for (int i = 0; i < n - 1; i++)\n    {\n        int u, v;\n        scanf(\"%d%d\", &u, &v);\n        u--, v--;\n        grinit[u].pb(v);\n        grinit[v].pb(u);\n    }\n    leavedesc(0, -1);\n    \n    for (int i = 0; i < n; i++)\n    {\n        for (auto t : grinit[i]) gr[newid[i]].pb(newid[t]);\n    }\n    \n    for (int i = 0; i < n; i++) scanf(\"%d\", &c[newid[i]]);\n        \n    for (int i = 0; i < n; i++) if (c[i] != -1) isleaf[i] = true;\n    int nq;\n    scanf(\"%d\", &nq);\n    for (int lq = 0; lq < nq; lq += BSZ)\n    {\n        int rq = min(nq, lq + BSZ);\n        memset(isinteresting, 0, sizeof isinteresting);\n        ks.clear();\n        ks.pb(curk);\n        for (int q = lq; q < rq; q++)\n        {\n            int t;\n            scanf(\"%d\", &t);\n            if (t == 1)\n            {\n                int v;\n                scanf(\"%d\", &v);\n                v--;\n                v = newid[v];\n                isinteresting[v] = true;\n                qs[q - lq] = {v, -1};\n            } else if (t == 2)\n            {\n                int v, newc;\n                scanf(\"%d%d\", &v, &newc);\n                v--;\n                v = newid[v];\n                isinteresting[v] = true;\n                qs[q - lq] = {v, newc};\n            } else\n            {\n                int newk;\n                scanf(\"%d\", &newk);\n                qs[q - lq] = {-1, newk};\n                ks.pb(newk);\n            }\n        }\n        \n        sort(all(ks));\n        ks.resize(unique(all(ks)) - ks.begin());\n        int kssz = ks.size();\n        ks.pb(infk);\n        int curcompkid = 0;\n        for (int i = -infk; i <= infk; i++)\n        {\n            compk[i + infk] = curcompkid;\n            if (curcompkid < kssz && ks[curcompkid] == i) curcompkid++;\n        }\n\n\n        isinteresting[0] = true;\n        interesting.clear();\n\n        for (int i = 0; i <= kssz; i++) at[i].clear();\n\n        for (int cur = 0; cur < n; cur++)\n        {\n            dead_ends[cur].clear();\n            path[cur] = -1;\n            if (isinteresting[cur])\n            {\n                path[cur] = -2;\n            }\n        }\n\n        for (int cur = n - 1; cur >= 0; cur--)\n        {\n            int ret = -1;\n            if (isinteresting[cur])\n            {\n                intid[cur] = interesting.size();\n                interesting.pb(cur);\n                cntdead[intid[cur]].clear();\n                cntdead[intid[cur]].pb(0);\n            }\n            if (path[cur] == -1)\n            {\n                if (isleaf[cur])\n                {\n                    if (c[cur] == 0) at[compk[-infk + infk]].pb(cur);\n                    else at[compk[infk + infk]].pb(cur);\n                } else\n                {\n                    curcnt[cur] = 0;\n                    int cntred = 0;\n                    int cntblue = gr[cur].size();\n                    at[compk[cntblue - cntred + 1 + infk]].pb(cur);\n                }\n            } else if (path[cur] == -2)\n            {\n                ret = cur;\n            } else\n            {\n                ret = path[cur];\n            }\n            if (cur == 0) break;\n            if (ret == -1) continue;\n            \n            if (path[up[cur]] == -1) path[up[cur]] = ret;\n            else if (path[up[cur]] >= 0)\n            {\n                isinteresting[up[cur]] = true;\n                fastup[path[up[cur]]] = up[cur];\n                fastup[ret] = up[cur];\n                path[up[cur]] = -2;\n            } else\n            {\n                fastup[ret] = up[cur];\n            }\n        }\n        \n        timer++;\n        for (int i = 0; i <= kssz; i++)\n        {\n            for (auto t : at[i]) q.push(t);\n            while (!q.empty())\n            {\n                int cur = q.front();\n                q.pop();\n                if (was[cur] == timer) continue;\n                was[cur] = timer;\n                if (path[up[cur]] == -1)\n                {\n                    curcnt[up[cur]]++;\n                    int cntred = curcnt[up[cur]];\n                    int cntblue = gr[up[cur]].size() - cntred;\n                    if (cntblue - cntred + 1 <= ks[i]) q.push(up[cur]);\n                    else at[compk[cntblue - cntred + 1 + infk]].pb(up[cur]);\n                } else if (path[up[cur]] == -2)\n                {\n                    int id = intid[up[cur]];\n                    while ((int)cntdead[id].size() <= i) cntdead[id].pb(cntdead[id].back());\n                    cntdead[id].back()++;\n                } else { // in path\n                    dead_ends[up[cur]].pb(ks[i]);\n                }\n            }\n        }\n        \n        for (int cur = n - 1; cur >= 0; cur--) if (path[cur] != -1)\n        {\n            int cntchildren = gr[cur].size();\n            if (path[cur] == -2)\n            {\n                th[cur][0] = -infk;\n                th[cur][1] = +infk;\n            } else\n            {\n                th[cur][0] = cntchildren + 1;\n                th[cur][1] = cntchildren + 1;\n                th[cur][0] = min(th[cur][0], max(th[path[cur]][0], cntchildren - 1 - 1 + 1));\n                th[cur][1] = min(th[cur][1], max(th[path[cur]][1], cntchildren - 1 - 1 + 1));\n                for (int i = 0; i < (int)dead_ends[cur].size(); i++)\n                {\n                    int cntred = i + 1;\n                    int cntblue = cntchildren - cntred;\n                    th[cur][0] = min(th[cur][0], max(dead_ends[cur][i], cntblue - cntred + 1));\n                    th[cur][1] = min(th[cur][1], max(dead_ends[cur][i], cntblue - cntred + 1));\n        \n                    cntred = i + 1 + 1;\n                    cntblue = cntchildren - cntred;\n                    th[cur][0] = min(th[cur][0], max(max(th[path[cur]][0], dead_ends[cur][i]), cntblue - cntred + 1));\n                    th[cur][1] = min(th[cur][1], max(max(th[path[cur]][1], dead_ends[cur][i]), cntblue - cntred + 1));\n                }\n                th[path[cur]][0] = th[cur][0];\n                th[path[cur]][1] = th[cur][1];\n            }\n        }\n        \n        \n        ::curkid = lower_bound(all(ks), curk) - ks.begin();\n        for (int q = 0; q < rq - lq; q++)\n        {\n            timer++;\n            if (qs[q].fi == -1)\n            {\n                curk = qs[q].se;\n                ::curkid = lower_bound(all(ks), curk) - ks.begin();\n            } else if (qs[q].se != -1) c[qs[q].fi] = qs[q].se;\n            else\n            {\n                for (auto v : interesting)\n                {\n                    if (!isleaf[v]) computecolor(v);\n                    pushtoparent(v);\n                }\n                printf(\"%d\\n\", c[qs[q].fi]);\n            }\n        }\n    }\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "implementation",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1209",
    "index": "A",
    "title": "Paint the Numbers",
    "statement": "You are given a sequence of integers $a_1, a_2, \\dots, a_n$. You need to paint elements in colors, so that:\n\n- If we consider any color, all elements of this color must be divisible by the minimal element of this color.\n- The number of used colors must be minimized.\n\nFor example, it's fine to paint elements $[40, 10, 60]$ in a single color, because they are all divisible by $10$. You can use any color an arbitrary amount of times (in particular, it is allowed to use a color only once). The elements painted in one color do not need to be consecutive.\n\nFor example, if $a=[6, 2, 3, 4, 12]$ then two colors are required: let's paint $6$, $3$ and $12$ in the first color ($6$, $3$ and $12$ are divisible by $3$) and paint $2$ and $4$ in the second color ($2$ and $4$ are divisible by $2$). For example, if $a=[10, 7, 15]$ then $3$ colors are required (we can simply paint each element in an unique color).",
    "tutorial": "Consider the smallest element $x$ in the array. We need to paint it in some color, right? Observe, that we can paint all elements divisible by $x$ in that color as well. So we can perform the following while the array is not empty: find the minimum element $x$, assign new color and remove all elements divisible by $x$ Complexity: $\\mathcal{O}(n^2)$.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1209",
    "index": "B",
    "title": "Koala and Lights",
    "statement": "It is a holiday season, and Koala is decorating his house with cool lights! He owns $n$ lights, all of which flash periodically.\n\nAfter taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $a_i$ and $b_i$. Light with parameters $a_i$ and $b_i$ will toggle (on to off, or off to on) every $a_i$ seconds starting from the $b_i$-th second. In other words, it will toggle at the moments $b_i$, $b_i + a_i$, $b_i + 2 \\cdot a_i$ and so on.\n\nYou know for each light whether it's initially on or off and its corresponding parameters $a_i$ and $b_i$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out.\n\n\\begin{center}\n{\\small Here is a graphic for the first example.}\n\\end{center}",
    "tutorial": "Because each individual light flashes periodically, all the lights together are periodic as well. Therefore, we can simulate the lights up to the period to get the answer. The actual period can be calculated as follows: If a light toggles every $t$ seconds, its period is $2t$. The overall period is the least common multiple of the individual periods $2,4,6,8,10$, which is $120$. There is also a \"pre-period\" of $5$ since lights can start toggling at time 5 in the worst case, so the time we need to simulate is bounded by $125$ However, computing the actual period is not necessary and a very large number will work (like $1000$). Challenge: Can we bound the time even more?",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1209",
    "index": "C",
    "title": "Paint the Digits",
    "statement": "You are given a sequence of $n$ digits $d_1d_2 \\dots d_{n}$. You need to paint all the digits in two colors so that:\n\n- each digit is painted either in the color $1$ or in the color $2$;\n- if you write in a row from left to right all the digits painted in the color $1$, and then after them all the digits painted in the color $2$, then the resulting sequence of $n$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit).\n\nFor example, for the sequence $d=914$ the only valid coloring is $211$ (paint in the color $1$ two last digits, paint in the color $2$ the first digit). But $122$ is not a valid coloring ($9$ concatenated with $14$ is not a non-decreasing sequence).\n\nIt is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.\n\nFind any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.",
    "tutorial": "The sequence must split into two non-decreasing where the end of the first $\\le$ start of the second. Let's bruteforce the value $x$, so that all elements $< x$ go to the color $1$, all elements $> x$ go to the color $2$, and for $=x$ we are not sure. Actually, we can say that all elements equal to $x$, which go before the first element $> x$ can safely go to the color $2$, while the rest can only go to the color $1$. So we colored our sequence and we now only need to check whether this coloring is fine. Complexity is $10 \\cdot n$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1209",
    "index": "D",
    "title": "Cow and Snacks",
    "statement": "The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!\n\nThere are $n$ snacks flavors, numbered with integers $1, 2, \\ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows:\n\n- First, Bessie will line up the guests in some way.\n- Then in this order, guests will approach the snacks one by one.\n- Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad.\n\nHelp Bessie to minimize the number of sad guests by lining the guests in an optimal way.",
    "tutorial": "Since every animal has exactly two favorite snacks, this hints that we should model the problem as a graph. The nodes are the snacks, and the edges are animals with preferences connecting snack nodes. Let's consider a connected component of the graph with size greater than $1$. The first animal (edge) in that component to eat must take two snacks (nodes), all other snack nodes will be eaten by exactly one animal edge. It is always possible to find an order so that no other animals takes two snacks (for example, BFS order). Thus, a connected component with $c$ vertices can satisfy at most $c-1$ animals. Let $N$ be the number of snacks, $M$ be the number of animals, and $C$ be the number of connected components (including those of size 1). The number of satisfied animals is $N-C$, so the number of of unhappy animals is $M-(N-C)$. Complexity: $\\mathcal{O}(n+m)$",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1209",
    "index": "E1",
    "title": "Rotate Columns (easy version)",
    "statement": "This is an easier version of the next problem. The difference is only in constraints.\n\nYou are given a rectangular $n \\times m$ matrix $a$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.\n\nAfter you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $i$-th row it is equal $r_i$. What is the maximal possible value of $r_1+r_2+\\ldots+r_n$?",
    "tutorial": "There many approaches possible, let's describe one of them. Let's change the problem to the following: Rotate columns any way you want. Select in each row one value, maximizing the sum. This can be done with a dp, states are (prefix of columns, mask of taken columns). Basically at each step we are rotating the current column and fixing values for some of the rows. The most simple way to write this makes $3^n \\cdot m \\cdot n^2$ (for every submask->mask transition iterate over all possible shifts and elements to consider in cost function). But if we precalculate the cost function in advance, we will have $\\mathcal{O}((3^n + 2^n n^2) \\cdot m)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1209",
    "index": "E2",
    "title": "Rotate Columns (hard version)",
    "statement": "This is a harder version of the problem. The difference is only in constraints.\n\nYou are given a rectangular $n \\times m$ matrix $a$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.\n\nAfter you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $i$-th row it is equal $r_i$. What is the maximal possible value of $r_1+r_2+\\ldots+r_n$?",
    "tutorial": "The previous solution is slightly too slow to pass the large constraints. Let's sort columns by the maximum element in them. Observe, that it is surely unoptimal to use columns which go after first $n$ columns in sorted order (we could've replaced them with some unused column). So we can solve the hard version with previous solution in which we consider only best $n$ columns. Complexity $\\mathcal{O}((3^n + 2^n \\cdot n^2) \\cdot n + T(sort))$",
    "tags": [
      "bitmasks",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1209",
    "index": "F",
    "title": "Koala and Notebook",
    "statement": "Koala Land consists of $m$ bidirectional roads connecting $n$ cities. The roads are numbered from $1$ to $m$ by order in input. It is guaranteed, that one can reach any city from every other city.\n\nKoala starts traveling from city $1$. Whenever he travels on a road, he writes its number down in his notebook. He doesn't put spaces between the numbers, so they all get concatenated into a single number.\n\nBefore embarking on his trip, Koala is curious about the resulting number for all possible destinations. For each possible destination, what is the smallest number he could have written for it?\n\nSince these numbers may be quite large, print their remainders modulo $10^9+7$. Please note, that you need to compute the remainder of the minimum possible number, \\textbf{not} the minimum possible remainder.",
    "tutorial": "First split all edges into directed edges with single digit labels, creating $\\mathcal{O}(m\\log{m})$ dummy vertices if necessary. Since the first edge will not be zero (no leading zeros), longer paths are always greater. With a BFS, this reduces the problem to finding lexicographical minimal paths in a DAG. To avoid needing to compare long sequences, we will instead visit all the vertices in order by their lexicographical minimal path. This can be done efficiently by something like BFS/DFS. The main idea is to visit sets of vertices at a time. If we have a set of vertices whose minimal paths are $P$, we can find the set of vertices whose minimal paths are $P0$ by following all outgoing $0$ edges. Then, we find the set of vertices whose minimal paths are $P1$ by following all outgoing $1$ edges, and so on for all digits. Since we ignore vertices once they are visited, this is $\\mathcal{O}(m\\log{m})$",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "shortest paths",
      "strings",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1209",
    "index": "G1",
    "title": "Into Blocks (easy version)",
    "statement": "This is an easier version of the next problem. In this version, $q = 0$.\n\nA sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal.\n\nLet's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value $x$ to value $y$, you must also change all other elements of value $x$ into $y$ as well. For example, for $[3, 3, 1, 3, 2, 1, 2]$ it isn't allowed to change first $1$ to $3$ and second $1$ to $2$. You need to leave $1$'s untouched or change them to the same value.\n\nYou are given a sequence of integers $a_1, a_2, \\ldots, a_n$ and $q$ updates.\n\nEach update is of form \"$i$ $x$\" — change $a_i$ to $x$. Updates are not independent (the change stays for the future).\n\nPrint the difficulty of the initial sequence and of the sequence after every update.",
    "tutorial": "Let's solve easier version first (we will reuse core ideas in hard version as well). Clearly, if some two integers are ``hooked'' like in $1 \\ldots 2 \\ldots 1 \\ldots 2$, then they will end up being turned into the same integer. So when we see integer $x$ with first occurrence at $a$ and last at $b$, let's mark segment $[a; b]$ as blocked. E.g. for array $[3, 3, 1, 2, 1, 2]$ we have not blocked only the bar between $3$ and $1$, that is we have $|3, 3 | 1, 2, 1, 2|$. Now for every such segment we have to change all elements into a common element. So the answer for a segment is segment length minus the number of occurrences of the most frequent element. One easy implementation is as follows: blocking is \"+= 1 on segment\" (can be done easily in $\\mathcal{O}{(n + operations)}$ in offline, then for an element $x$, put the number of it's occurrences in the position of first occurrences. Now we only need to compute max on disjoint segments, so it can be done in a naive way. Complexity: $\\mathcal{O}(n)$.",
    "tags": [
      "data structures",
      "dsu",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1209",
    "index": "G2",
    "title": "Into Blocks (hard version)",
    "statement": "This is a harder version of the problem. In this version $q \\le 200\\,000$.\n\nA sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal.\n\nLet's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value $x$ to value $y$, you must also change all other elements of value $x$ into $y$ as well. For example, for $[3, 3, 1, 3, 2, 1, 2]$ it isn't allowed to change first $1$ to $3$ and second $1$ to $2$. You need to leave $1$'s untouched or change them to the same value.\n\nYou are given a sequence of integers $a_1, a_2, \\ldots, a_n$ and $q$ updates.\n\nEach update is of form \"$i$ $x$\" — change $a_i$ to $x$. Updates are not independent (the change stays for the future).\n\nPrint the difficulty of the initial sequence and of the sequence after every update.",
    "tutorial": "To adjust the solution for many queries we need to create some sophisticated data structure. E.g. we all know that mentioned above \"+= 1 on a segment\" is easily done with a segtree. If we maintain for every value $a_i$ the corresponding set of occurrences, it's easy to update mentioned above ``number of occurrences in the first position''. So what we need to do now? We need to dynamically recalculate the sum of minimums (and the set segments to calculate minimum can change quite much due to updates). You probably also now that we can design a segtree which supports range increments and query (minimum, number of minimums) on the segment. In a similar way we can build a structure which returns (minimum, number of minimums, the sum of largest stored counts between minimums). Just maintain a few values in each node and do lazy propagation. Complexity $\\mathcal{O}(q \\log n)$.",
    "tags": [
      "data structures"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1209",
    "index": "H",
    "title": "Moving Walkways",
    "statement": "Airports often use moving walkways to help you walking big distances faster. Each such walkway has some speed that effectively increases your speed. You can stand on such a walkway and let it move you, or you could also walk and then your effective speed is your walking speed plus walkway's speed.\n\nLimak wants to get from point $0$ to point $L$ on a straight line. There are $n$ disjoint walkways in between. The $i$-th walkway is described by two integers $x_i$ and $y_i$ and a real value $s_i$. The $i$-th walkway starts at $x_i$, ends at $y_i$ and has speed $s_i$.\n\nEvery walkway is located inside the segment $[0, L]$ and no two walkways have positive intersection. However, they can touch by endpoints.\n\nLimak needs to decide how to distribute his energy. For example, it might make more sense to stand somewhere (or to walk slowly) to then have a lot of energy to walk faster.\n\nLimak's initial energy is $0$ and it must never drop below that value. At any moment, he can walk with any speed $v$ in the interval $[0, 2]$ and it will cost him $v$ energy per second, but he continuously recovers energy with speed of $1$ energy per second. So, when he walks with speed $v$, his energy increases by $(1-v)$. Note that negative value would mean losing energy.\n\nIn particular, he can walk with speed $1$ and this won't change his energy at all, while walking with speed $0.77$ effectively gives him $0.23$ energy per second.\n\nLimak can choose his speed arbitrarily (any real value in interval $[0, 2]$) at every moment of time (including the moments when he is located on non-integer positions). Everything is continuous (non-discrete).\n\nWhat is the fastest time Limak can get from $0$ to $L$?",
    "tutorial": "Some minor tips: Everything is a walkway. When there is no walkway, it is a walkway of speed $0$. You can increase all speeds by $1$ and assume that you own speed is in $[-1; +1]$ Energy is an entity which is $\\delta$ speed $\\times$ time, which is distance. Also if you spend $x$ energy per segment of len $l$ and speed $v$, it is not important how exactly you will distribute it over the walking process. In any way, you will walk by feet $l - x$ meters in time $(l - x) / v$. So it turns out it's better to distribute more energy to low-speeded walkways (because the denominator is smaller). Assume that you (by default) save up all energy on any non-feet path (for feet path it's always optimal to walk with speed $\\ge 1$ ($\\ge 0$ after speeds hack), so now save up's). Build an energy graphic where the Ox axis will correspond to the point you are in (not time). It will be a piecewise linear function, so it is enough to store it's value only in points corresponding to points between walkways. Iterate over walkways in the order of speed and try to steal as much energy as possible to the current walkway. What are the limits of stealing energy? there is a restriction based on $l$ and $v$ (if you take too much energy, you wouldn't be able to fully walk it up) the graphic must still be able above $0$ at all points. The latter condition is just a suffix minima on a segment tree. Complexity: $\\mathcal{O}(n \\log n)$.",
    "tags": [
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1210",
    "index": "A",
    "title": "Anadi and Domino",
    "statement": "Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every $a$ and $b$ such that $1 \\leq a \\leq b \\leq 6$, there is exactly one domino with $a$ dots on one half and $b$ dots on the other half. The set contains exactly $21$ dominoes. Here is an exact illustration of his set:\n\nAlso, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.\n\nWhen placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.\n\nHow many dominoes at most can Anadi place on the edges of his graph?",
    "tutorial": "We can imagine writing an integer from $1$ to $6$ in each vertex - if we write an integer $x$ in vertex $v$, then we want each half of the domino directed toward vertex $v$ to have exactly $x$ dots. Then, it's easy to calculate the result - we should place as many different dominoes as possible according to the written numbers so that we won't place any domino multiple times. If $n \\leq 6$, then it's optimal to write different numbers everywhere, so the result will be equal to $m$ (the number of edges). If $n=7$, then it's optimal to use only two equal numbers and it doesn't matter which number appears twice. Then, we can iterate over the pair of vertices with the same number and then easily calculate the result.",
    "tags": [
      "brute force",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1210",
    "index": "B",
    "title": "Marcin and Training Camp",
    "statement": "Marcin is a coach in his university. There are $n$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.\n\nLet's focus on the students. They are indexed with integers from $1$ to $n$. Each of them can be described with two integers $a_i$ and $b_i$; $b_i$ is equal to the skill level of the $i$-th student (the higher, the better). Also, there are $60$ known algorithms, which are numbered with integers from $0$ to $59$. If the $i$-th student knows the $j$-th algorithm, then the $j$-th bit ($2^j$) is set in the binary representation of $a_i$. Otherwise, this bit is not set.\n\nStudent $x$ thinks that he is better than student $y$ if and only if $x$ knows some algorithm which $y$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.\n\nMarcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?",
    "tutorial": "If there are multiple people with the same set of skills (i.e., the same values of $a$), it's optimal to take each of them to the camp as they won't think they're better than everyone else. Now consider a person $i$ which has a different set of skills than everyone else. If they have a strictly smaller set of skills than someone already in the group, they can safely be included in the group. If they don't, we can prove that they can't ever be included in the group. This allows us to implement a simple $O(n^2)$ solution: first take all people that have an equal set of skills as someone else, and then include everyone else who has a strictly smaller set of skills than someone already in the group.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1210",
    "index": "C",
    "title": "Kamil and Making a Stream",
    "statement": "Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached $100$ million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?\n\nYou're given a tree — a connected undirected graph consisting of $n$ vertices connected by $n - 1$ edges. The tree is rooted at vertex $1$. A vertex $u$ is called an ancestor of $v$ if it lies on the shortest path between the root and $v$. In particular, a vertex is an ancestor of itself.\n\nEach vertex $v$ is assigned its beauty $x_v$ — a non-negative integer not larger than $10^{12}$. This allows us to define the beauty of a path. Let $u$ be an ancestor of $v$. Then we define the beauty $f(u, v)$ as the greatest common divisor of the beauties of all vertices on the shortest path between $u$ and $v$. Formally, if $u=t_1, t_2, t_3, \\dots, t_k=v$ are the vertices on the shortest path between $u$ and $v$, then $f(u, v) = \\gcd(x_{t_1}, x_{t_2}, \\dots, x_{t_k})$. Here, $\\gcd$ denotes the greatest common divisor of a set of numbers. In particular, $f(u, u) = \\gcd(x_u) = x_u$.\n\nYour task is to find the sum\n\n$$ \\sum_{u\\text{ is an ancestor of }v} f(u, v). $$\n\nAs the result might be too large, please output it modulo $10^9 + 7$.\n\nNote that for each $y$, $\\gcd(0, y) = \\gcd(y, 0) = y$. In particular, $\\gcd(0, 0) = 0$.",
    "tutorial": "Let's prove the following observation: Fix a vertex $v$ (the bottom end of the path), and consider all its ancestors $u$. The number of distinct values of $f(u,v)$ is at most $\\log_2(10^{12})$. To prove this observation, consider the ancestors of $v$ in the order from the bottom-most to top-most: $v=u_0, u_1, u_2, u_3, \\dots, u_k=1$. Notice that $f(u_i, v) = \\gcd(x_{u_0}, x_{u_1}, x_{u_2}, \\dots, x_{u_i})$. Therefore, each consecutive $u_i$ adds another value $x_{u, i}$ to the gcd of all numbers. If a gcd of all numbers changes, it must be a divisor of the previous gcd. Therefore, it's easy to see that it can change at most $\\log_2(10^{12})$ times. We can now implement a depth-first search. If we invoke a recursive call in vertex $v$, we will receive the multiset of values $\\{f(u, v) \\mid u\\text{ is an ancestor of }v\\}$. We add all these values to the result and run the recursive calls in the children. This is currently $O(n^2)$ or $O(n^2\\log n)$, but we can improve it by actually using a map from the distinct values in the multiset to the number of their occurrences. Then each map will have no more than $O\\log_2(10^{12})$ elements. As we need to compute $\\gcd$'s throughout the algorithm, this solution allows us to solve the problem in $O(n\\log^2(10^{12}))$ time and in $O(n \\log(10^{12}))$ memory. It's also possible to solve the problem using jump-pointers. Each jump-pointer will additionally hold the greatest common divisor of all the numbers we jump over when following the pointer.",
    "tags": [
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1210",
    "index": "D",
    "title": "Konrad and Company Evaluation",
    "statement": "Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company.\n\nThere are $n$ people working for VoltModder, numbered from $1$ to $n$. Each employee earns a different amount of money in the company — initially, the $i$-th person earns $i$ rubles per day.\n\nOn each of $q$ following days, the salaries will be revised. At the end of the $i$-th day, employee $v_i$ will start earning $n+i$ rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again.\n\nSome pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people $a$ and $b$ dislike each other and $a$ earns more money than $b$, employee $a$ will brag about this to $b$. A dangerous triple is a triple of three employees $a$, $b$ and $c$, such that $a$ brags to $b$, who in turn brags to $c$. If $a$ dislikes $b$, then $b$ dislikes $a$.\n\nAt the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it?",
    "tutorial": "Let's imagine that the graph is directed as in the sample explanation (and edge $u\\to v$ exists if $u$ brags to $v$). We have to deal with two kinds of queries: Count the number of three-vertex directed paths. Change the direction of a single edge in the graph. If we remember indegrees $\\mathrm{indeg}$ and outdegrees $\\mathrm{outdeg}$ for each vertex, then we can see that the result for the first query is $\\sum_{v} \\mathrm{indeg}(v) \\cdot \\mathrm{outdeg}(v)$. It's also easy to maintain the in- and outdegrees for each vertex when updating the graph using the second query. Let's get back to the original problem. If a person $v$ becomes the best-paid employee in the company, we can model it as taking all the edges ending at $v$, and reversing their direction. It turns out that throughout the whole simulation, this edge-reversal won't happen too many times! Let's sort the vertices from left to right by their degree in the decreasing order. It now turns out that each vertex is adjacent with at most $\\sqrt{2m}$ vertices to its left: if there were more, it would mean that there exist more that $\\sqrt{2m}$ vertices with their degrees larger than $\\sqrt{2m}$. It would mean that the sum of degrees of all the vertices in the graph is more than $\\sqrt{2m} \\cdot \\sqrt{2m} = 2m$ - a contradiction. Define the potential of the graph as the number of edges which point from left to right. If we revise the salary for employee $v$, we might need to flip many edges, but at most $\\sqrt{2m}$ new edges will start pointing from left to right. The remaining edges incident to $v$ will now point from right to left. Therefore, we do the number of swaps proportional to the change of the potential, and the potential at each query can increase at most by $\\sqrt{2m}$. The potential at the beginning could be as high as $m$, and therefore the total number of swaps throughout the algorithm is at most $m + q\\sqrt{2m}$. The algorithm can be therefore implemented in $O(n + m + q\\sqrt{m})$ time. Note that we should store the adjacency list of the directed graph in vectors - when we revise the salary of employee $v$, we should process all edges entering $v$ and simply clear the corresponding vector. Storing the graph in sets or hashsets has worse complexity or a huge constant factor and will likely time out.",
    "tags": [
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1210",
    "index": "E",
    "title": "Wojtek and Card Tricks",
    "statement": "Wojtek has just won a maths competition in Byteland! The prize is admirable — a great book called 'Card Tricks for Everyone.' 'Great!' he thought, 'I can finally use this old, dusted deck of cards that's always been lying unused on my desk!'\n\nThe first chapter of the book is 'How to Shuffle $k$ Cards in Any Order You Want.' It's basically a list of $n$ intricate methods of shuffling the deck of $k$ cards in a deterministic way. Specifically, the $i$-th recipe can be described as a permutation $(P_{i,1}, P_{i,2}, \\dots, P_{i,k})$ of integers from $1$ to $k$. If we enumerate the cards in the deck from $1$ to $k$ from top to bottom, then $P_{i,j}$ indicates the number of the $j$-th card from the top of the deck after the shuffle.\n\nThe day is short and Wojtek wants to learn only some of the tricks today. He will pick two integers $l, r$ ($1 \\le l \\le r \\le n$), and he will memorize each trick from the $l$-th to the $r$-th, inclusive. He will then take a sorted deck of $k$ cards and repeatedly apply random memorized tricks until he gets bored. He still likes maths, so he started wondering: how many different decks can he have after he stops shuffling it?\n\nWojtek still didn't choose the integers $l$ and $r$, but he is still curious. Therefore, he defined $f(l, r)$ as the number of different decks he can get if he memorizes all the tricks between the $l$-th and the $r$-th, inclusive. What is the value of\n\n$$\\sum_{l=1}^n \\sum_{r=l}^n f(l, r)?$$",
    "tutorial": "Let's first enumerate all permutations by integers from $0$ to $k!-1$. Now, we can memoize all possible compositions of two permutations in an $k! \\times k!$ array. This will allow us to compose any two permutations in constant time. Let $l$ and $r$ be the left and right ends of any interval. We'll compute the sum in the problem statement for each $r$ separately. Set some $r$. Notice that if there are multiple occurrences of the same permutation before $r$, only the latest occurrence is important for us - any earlier occurrences won't help us create any new decks. Therefore, for each of $k!$ possible permutations, we can maintain its latest occurrence before $r$. We can also maintain a sorted list of such latest occurrences among all the permutations - from the latest to the earliest. This creates $k!$ intervals of value $l$ where the number of possible decks can't change. Now, we only need to be able to maintain the set of decks (permutations) we can generate using the tricks we already know. Initially, we can generate only one deck (with the cards in sorted order). When learning a new trick, one of two things can happen: If a single application of the new trick generates a deck we can already create using previous tricks, this trick gives us nothing - we can simply simulate this new trick by a sequence of old tricks. If this trick $T$ creates a brand-new deck of cards, we need to recalculate the set of achievable permutations. We maintain a set of generators $\\{g_1, g_2, \\dots, g_a\\}$, $g_a = T$ (these are the tricks that have increased the number of decks we can generate). Now, each deck in the new set of decks can be created using this repeatedly applying the generators from this set. We can use BFS/DFS to compute the new decks. This is obviously a correct algorithm, but why does it work fast enough? If you know some abstract algebra, then you can notice that what we're computing here is a chain of subgroups in a symmetric group $S_k$ (a group of all permutations of $k$ elements). By Lagrange's theorem, if a group $G$ is a subgroup of a finite group $H$, then $|H|$ is a multiple of $|G|$. Therefore, each new set of achievable decks is at least twice as large as the previous one. It means that: The set of generators is always at most as large as $\\log_2(k!)$, The time needed to compute all the subgroups can be bounded by $\\log_2(k!)$ times the sizes of all subgroups in the chain. As the sizes are growing exponentially large, the sum of sizes is at most $O(k!)$. Therefore, all the additions take at most $O(k! \\log k)$ time. The time complexity of the intended solution was therefore $O((k!)^2 + nk!k)$. The solution can be sped up significantly by computing all possible sets of achievable decks (i.e., all subgroups of $S_k$) - for $k = 5$, there are only $156$ of them. Some preprocessing will then allow us to add a single element to the subgroup in constant time. This was however not necessary to get AC.",
    "tags": [
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1210",
    "index": "F1",
    "title": "Marek and Matching (easy version)",
    "statement": "This is an easier version of the problem. In this version, $n \\le 6$.\n\nMarek is working hard on creating strong testcases to his new algorithmic problem. You want to know what it is? Nah, we're not telling you. However, we can tell you how he generates the testcases.\n\nMarek chooses an integer $n$ and $n^2$ integers $p_{ij}$ ($1 \\le i \\le n$, $1 \\le j \\le n$). He then generates a random bipartite graph with $2n$ vertices. There are $n$ vertices on the left side: $\\ell_1, \\ell_2, \\dots, \\ell_n$, and $n$ vertices on the right side: $r_1, r_2, \\dots, r_n$. For each $i$ and $j$, he puts an edge between vertices $\\ell_i$ and $r_j$ with probability $p_{ij}$ percent.\n\nIt turns out that the tests will be strong only if a perfect matching exists in the generated graph. What is the probability that this will occur?\n\nIt can be shown that this value can be represented as $\\frac{P}{Q}$ where $P$ and $Q$ are coprime integers and $Q \\not\\equiv 0 \\pmod{10^9+7}$. Let $Q^{-1}$ be an integer for which $Q \\cdot Q^{-1} \\equiv 1 \\pmod{10^9+7}$. Print the value of $P \\cdot Q^{-1}$ modulo $10^9+7$.",
    "tutorial": "Let's first discuss one of possible solutions for the easy subtask. Let's assume that $n=6$ (all smaller $n$'s can be easily reduced to this case). There are two layers of vertices: left $L = \\{\\ell_1, \\ell_2, \\dots, \\ell_6\\}$ and right $R = \\{r_1, r_2, \\dots, r_6\\}$. Let's do meet-in-the-middle on the right layer: $R_a = \\{r_1, r_2, r_3\\}$ and $R_b = \\{r_4, r_5, r_6\\}$. Consider two parts of the graph: between $L$ and $R_a$, and between $L$ and $R_b$. Each of them has $n \\cdot \\frac{n}{2} = 18$ edges, so we can try all subsets of edges in each of them separately. For each such subset: Compute the probability that we'll generate exactly this subset of edges. Find all $3$-element subsets of $L$ which can match perfectly with the currently considered half of $R$. This can be done easily in $2^{18} \\times \\mathrm{poly}(n)$ time. Now, here's a trick - there are only ${6 \\choose 3} = 20$ three-element subsets of $L$! Therefore, for each $20$-element mask $M$, we can find: $p_a(M)$ - the probability that the set of three-element subsets of $L$ matching perfectly with $R_a$ is exactly $M$, $p_b(M)$ - the probability that the set of three-element subsets of $L$ whose complements match perfectly with $R_b$ is exactly $M$. Let's find the probability that there is no perfect matching in the graph. We can see that it's $\\sum_{A \\cap B = \\varnothing} p_a(A) p_b(B)$ where $A$ and $B$ are $20$-element masks. This can be solved easily using SOS dynamic programming technique. If we let $q_b(X) := \\sum_{Y \\subseteq X} p_b(X)$, then the required sum is $\\sum_{A \\subseteq [20]} p_a(A) q_b([20] \\setminus A)$ where $[20] = \\{1,2,3,\\dots,20\\}$. Therefore, this algorithm allows us to solve the easy version of the problem in $2^{18} \\cdot \\mathrm{poly}(n) + 2^{20} \\cdot 20$ time.",
    "tags": [
      "brute force",
      "probabilities"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1210",
    "index": "F2",
    "title": "Marek and Matching (hard version)",
    "statement": "This is a harder version of the problem. In this version, $n \\le 7$.\n\nMarek is working hard on creating strong test cases to his new algorithmic problem. Do you want to know what it is? Nah, we're not telling you. However, we can tell you how he generates test cases.\n\nMarek chooses an integer $n$ and $n^2$ integers $p_{ij}$ ($1 \\le i \\le n$, $1 \\le j \\le n$). He then generates a random bipartite graph with $2n$ vertices. There are $n$ vertices on the left side: $\\ell_1, \\ell_2, \\dots, \\ell_n$, and $n$ vertices on the right side: $r_1, r_2, \\dots, r_n$. For each $i$ and $j$, he puts an edge between vertices $\\ell_i$ and $r_j$ with probability $p_{ij}$ percent.\n\nIt turns out that the tests will be strong only if a perfect matching exists in the generated graph. What is the probability that this will occur?\n\nIt can be shown that this value can be represented as $\\frac{P}{Q}$ where $P$ and $Q$ are coprime integers and $Q \\not\\equiv 0 \\pmod{10^9+7}$. Let $Q^{-1}$ be an integer for which $Q \\cdot Q^{-1} \\equiv 1 \\pmod{10^9+7}$. Print the value of $P \\cdot Q^{-1}$ modulo $10^9+7$.",
    "tutorial": "Let's consider another approach that can solve the hard subtask as well. In the algorithm above, we computed all $k$-element subsets of $L$, $|L|=n$, that can match perfectly with some fixed $k$ vertices on the right. It turns out that not all families of subsets can be generated - for instance, if two sets: $\\{\\ell_1, \\ell_2\\}$ and $\\{\\ell_3, \\ell_4\\}$ can both match perfectly with $\\{r_1, r_2\\}$, then one of the following subsets: $\\{\\ell_1, \\ell_3\\}$ and $\\{\\ell_1, \\ell_4\\}$ must match perfectly as well. We'll try to use this observation to solve the problem. Let's add the vertices of $R$ one by one. After adding vertices $r_1, r_2, \\dots, r_k$, consider all families of $k$-element subsets of $L$ which can match perfectly with $\\{r_1, r_2, \\dots, r_k\\}$ in any generated graph. Now try adding $r_{k+1}$. Check all $2^n$ ways of randomly drawing a subset of $n$ edges incident to $r_{k+1}$. For each such subset and for each family $\\mathcal{F}_k$ of $k$-element subsets computed previously, we need to compute the new family $\\mathcal{F}_{k+1}$ of $(k+1)$-element subsets of $L$ matching perfectly with $\\{r_1, r_2, \\dots, r_{k+1}\\}$. We can do it in a straightforward way - iterate over all $(k+1)$-element subsets $S \\subseteq L$. If $S$ matches perfectly with $k+1$ vertices on the right, then $r_{k+1}$ must be connected to some vertex $\\ell \\in S$, and $\\{r_1, \\dots, r_k\\}$ must match perfectly with $S \\setminus \\{\\ell\\}$. This allows us to solve the whole problem in $O(n \\cdot \\text{max number of families at any moment} \\cdot 2^n)$ time. It turns out that for $n=7$, here are at most $\\sim 30\\,000$ families for any value of $k$. This allows to solve the problem in a reasonable time. The model solution finishes within $1.5$ seconds, but some breathing space was added so that some less efficient implementations will pass as well.",
    "tags": [
      "brute force",
      "probabilities"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1210",
    "index": "G",
    "title": "Mateusz and Escape Room",
    "statement": "Mateusz likes to travel! However, on his $42$nd visit to Saint Computersburg there is not much left to sightsee. That's why he decided to go to an escape room with his friends!\n\nThe team has solved all riddles flawlessly. There is only one riddle remaining — a huge circular table! There are $n$ weighing scales lying on top of the table, distributed along the circle. Each scale is adjacent to exactly two other scales: for each $i \\in \\{1, 2, \\dots, n-1\\}$, the $i$-th and the $(i+1)$-th scales are adjacent to each other, as well as the first and the $n$-th scale.\n\nThe $i$-th scale initially contains $a_i$ heavy coins. Mateusz can perform moves — each move consists of fetching a single coin from one scale and putting it on any adjacent scale.\n\nIt turns out that the riddle will be solved when there is a specific amount of coins on each of the scales. Specifically, each scale has parameters $l_i$ and $r_i$. If each coin lies on a single scale and for each $i$, the $i$-th scale contains at least $l_i$ and at most $r_i$ coins, the riddle will be solved and Mateusz's team will win!\n\nMateusz is aiming for the best possible time. Therefore, he wants to solved the riddle as quickly as possible. What is the minimum possible number of moves required to fulfill all the conditions?",
    "tutorial": "Let's introduce the variables $x_1, x_2, \\dots, x_n$ where $x_i$ is the number of coins passed from the $i$-th to the $(i+1)$-th scale (or, $x_i < 0$, it means that $-x_i$ coins are passed from the $(i+1)$-th to the $i$-th scale). We can now create the following conditions regarding the final number of stones on each scale: $a_i - x_i + x_{i - 1} \\in [l_i, r_i] \\qquad \\text{for all } i.$ It turns out that for any sequence integers $x_1, \\dots, x_n$ satisfying the inequalities before, we can create a sequence of $|x_1| + |x_2| + \\dots + |x_n|$ moves satisfying all the conditions in the statement! In order to see this, consider a few cases: If $x_1, x_2, \\dots, x_n > 0$, then we take any coin and make a full lap with it along the circle in the order of increasing $i$'s. We can now decrease each $x_i$ by one. If $x_1, x_2, \\dots, x_n < 0$, we can do the similar thing, but we're decreasing $i$'s. In the remaining cases, we can pick a scale $i$ that won't receive coins anymore (that is, $x_i \\geq 0$ and $x_{i-1} \\leq 0$) and it still has some coins to distribute ($x_i > 0$ or $x_{i-1} < 0$). If $x_i > 0$, take a single coin, put it on the $(i+1)$-th scale, and decrease $x_i$ by one. If $x_{i-1} < 0$, take a coin, put it on the $(i-1)$-th scale, and increase $x_i$ by one. By following these operations, we will create the final configuration in $|x_1| + \\dots + |x_n|$ moves. Therefore, we need to minimize this value. Let's try to guess $x_1$ and try to optimize $|x_1| + |x_2| + \\dots + |x_n|$ for some fixed $x_1$. The simplest way is to write a dynamic programming: $dp(i, x_i) =$ the minimum value of $|x_1| + |x_2| + \\dots + |x_i|$ given a value of $x_i$ and such that the final numbers of stones on the second, third, fourth, $\\dots$, $i$-th scale are satisfied. To progress, we iterate over the possible values $x_{i+1}$ such that $a_i - x_i + x_{i - 1} \\in [l_i, r_i]$ and compute the best value of $dp(i+1, x_{i+1})$. Notice that the initial state is $dp(1, x_1) = |x_1|$ and $dp(1, \\star) = +\\infty$ everywhere else. To compute the result, we must take the minimum value $dp(n, x_n)$ for $x_n$ satisfying $a_1 - x_1 + x_n \\in [l_1, r_1]$. How to improve this DP? First of all, we'll try to maintain the $dp(i, x_i)$ as a function on $x_i$. In order to compute $dp(i+1, x)$ from $dp(i, x)$, we'll need to: Shift the function (left or right). Given a function $f$ and a constant $t$, compute $g(x) := \\min_{y \\in [x, x+t]} f(x)$. Given a function $f$, compute $g(x) := f(x) + |x|$. It turns out that after each of these operations, the function remains convex. We can therefore say that the function is linear on some segments with increasing slopes. Therefore, we can maintain a function as a set of segments, each segment described by its length and its slope. How to describe the second operation? We can see that it's actually adding a segment with slope $0$ and length $t$ to the function. Meanwhile, the third operation is splitting the function into two parts: for negative and positive $x$. We need to decrease the slopes in the first part by $1$, and increase the slopes in the second part by $1$. All these operations can be implemented on any balanced BST in $O(\\log n)$ time. Therefore, the whole subproblem (for fixed $x_1$) can be solved in $O(n \\log n)$ time. How to solve the general problem? It turns out that... Lemma. The function $F$ mapping $x_1$ into the optimal result for a fixed $x_1$ is convex. Proof will be added if anyone requests it. The basic idea is to prove that: (1) the answer won't change if $x_i$ could be any arbitrary real values, (2) if $(a_1, \\dots, a_n)$ and $(b_1, \\dots, b_n)$ are good candidates for $(x_1, \\dots, x_n)$, so is $\\left(\\frac{a_1+b_1}{2}, \\dots, \\frac{a_n+b_n}{2}\\right)$. We can use that to show that $\\frac{F(a_1) + F(b_1)}{2} \\ge F\\left(\\frac{a_1+b_1}{2}\\right)$. Therefore, we can run a ternary search on $x_1$ to find the optimal result for any $x_1$. This ternary search takes $O(\\log(\\sum a_i))$ iterations, so the final time complexity is $O(n \\log n \\log(\\sum a_i))$ with a rather large constant.",
    "tags": [
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1213",
    "index": "A",
    "title": "Chips Moving",
    "statement": "You are given $n$ chips on a number line. The $i$-th chip is placed at the integer coordinate $x_i$. Some chips \\textbf{can have equal coordinates}.\n\nYou can perform each of the two following types of moves any (possibly, zero) number of times on any chip:\n\n- Move the chip $i$ by $2$ to the left or $2$ to the right \\textbf{for free} (i.e. replace the current coordinate $x_i$ with $x_i - 2$ or with $x_i + 2$);\n- move the chip $i$ by $1$ to the left or $1$ to the right and pay \\textbf{one coin} for this move (i.e. replace the current coordinate $x_i$ with $x_i - 1$ or with $x_i + 1$).\n\nNote that it's allowed to move chips to any integer coordinate, including negative and zero.\n\nYour task is to find the minimum total number of coins required to move all $n$ chips to the same coordinate (i.e. all $x_i$ should be equal after some sequence of moves).",
    "tutorial": "We can see that the only information we need is the parity of the coordinate of each chip (because we can move all chips that have the same parity to one coordinate for free). So if the number of chips with odd coordinate is $cnto$ then the answer is $min(cnto, n - cnto)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tint cnto = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x;\n\t\tcin >> x;\n\t\tcnto += x & 1;\n\t}\n\t\n\tcout << min(cnto, n - cnto) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1213",
    "index": "B",
    "title": "Bad Prices",
    "statement": "Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $n$ last days: $a_1, a_2, \\dots, a_n$, where $a_i$ is the price of berPhone on the day $i$.\n\nPolycarp considers the price on the day $i$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $n=6$ and $a=[3, 9, 4, 6, 7, 5]$, then the number of days with a bad price is $3$ — these are days $2$ ($a_2=9$), $4$ ($a_4=6$) and $5$ ($a_5=7$).\n\nPrint the number of days with a bad price.\n\nYou have to answer $t$ independent data sets.",
    "tutorial": "Let $minPrice_i$ be the minimum price of the berPhone during days $i, i + 1, \\dots, n$. We can precalculate this array moving from right to left and carrying the minimum price we met (in other words, if we iterate over all $i$ from $n$ to $1$ then $minPrice_i = a_i$ if $i = n$ otherwise $minPrice_i = min(a_i, minPrice_{i + 1})$). Then the answer is the number of such days $i$ from $1$ to $n-1$ that $a_i > minPrice_{i + 1}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        forn(i, n)\n            cin >> a[i];\n        int ans = 0;\n        int right_min = INT_MAX;\n        for (int i = n -  1; i >= 0; i--) {\n            if (a[i] > right_min)\n                ans++;\n            right_min = min(right_min, a[i]);\n        }\n        cout << ans << endl;\n    }\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1213",
    "index": "C",
    "title": "Book Reading",
    "statement": "Polycarp is reading a book consisting of $n$ pages numbered from $1$ to $n$. Every time he finishes the page with the number divisible by $m$, he writes down the last digit of this page number. For example, if $n=15$ and $m=5$, pages divisible by $m$ are $5, 10, 15$. Their last digits are $5, 0, 5$ correspondingly, their sum is $10$.\n\nYour task is to calculate the sum of all digits Polycarp has written down.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "Let $k = \\lfloor\\frac{n}{m}\\rfloor$ be the number of integers from $1$ to $n$ divisible by $m$. We can notice that because we write down only the last digit of each number divisible by $m$ then the length of the \"cycle\" of digits does not exceed $10$. In fact, we can always suppose that it is $10$ because $i \\cdot m \\% 10 = (10 + i) \\cdot m \\% 10$ for all $i$ from $0$ to $9$. So let $cycle_i = m * (i + 1) \\% 10$ for all $i$ from $0$ to $9$. Then the answer is $\\lfloor\\frac{k}{10}\\rfloor \\cdot \\sum\\limits_{i=0}^{9} cycle_i + \\sum\\limits_{i=0}^{k \\% 10} cycle_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int q;\n    cin >> q;\n    forn(i, q) {\n        long long n, m;\n        cin >> n >> m;\n        n = n / m;\n        vector<int> digits(10);\n        forn(i, 10)\n            digits[i] = ((i + 1) * m) % 10;\n        long long sum = 0;\n        forn(i, n % 10)\n            sum += digits[i];\n        cout << sum + n / 10 * accumulate(digits.begin(), digits.end(), 0LL) << endl;\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1213",
    "index": "D1",
    "title": "Equalizing by Division (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the number of elements in the array}.\n\nYou are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \\lfloor\\frac{a_i}{2}\\rfloor$).\n\nYou can perform such an operation \\textbf{any} (possibly, zero) number of times with \\textbf{any} $a_i$.\n\nYour task is to calculate the minimum possible number of operations required to obtain at least $k$ equal numbers in the array.\n\n\\textbf{Don't forget that it is possible to have $a_i = 0$ after some operations, thus the answer always exists}.",
    "tutorial": "Let $x$ be the number such that after some sequence of moves there will be at least $k$ elements $x$ in the array. We can see that there is always $O(n \\log n)$ possible candidates because all values $x$ are among all possible values of $\\lfloor\\frac{a_i}{2^m}\\rfloor$ for some $m$ from $0$ to $18$. So we need to check each candidate separately and try to update the answer with it. How to do this? Let the current number we trying to obtain is $x$. Then let's iterate over all $a_i$ in any order. Let $y$ be the current value of $a_i$. Let's divide it by $2$ while its value is greater than $x$ and carry the number of divisions we made $cur$. If after all divisions $y=x$ then let's remember the value of $cur$ in some array $cnt$. If after iterating over all $n$ elements of $a$ the size of $cnt$ is greater than or equal to $k$ then let's sort it and update the answer with the sum of $k$ smallest values of $cnt$. Time complexity: $O(n^2 \\log^2max(a_i) \\log(n \\log max(a_i)))$ or $O(n^2 \\log^2max(a_i))$, depends on sorting method.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tvector<int> poss;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x = a[i];\n\t\twhile (x > 0) {\n\t\t\tposs.push_back(x);\n\t\t\tx /= 2;\n\t\t}\n\t}\n\t\n\tint ans = 1e9;\n\tfor (auto res : poss) {\n\t\tvector<int> cnt;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint x = a[i];\n\t\t\tint cur = 0;\n\t\t\twhile (x > res) {\n\t\t\t\tx /= 2;\n\t\t\t\t++cur;\n\t\t\t}\n\t\t\tif (x == res) {\n\t\t\t\tcnt.push_back(cur);\n\t\t\t}\n\t\t}\n\t\tif (int(cnt.size()) < k) continue;\n\t\tsort(cnt.begin(), cnt.end());\n\t\tans = min(ans, accumulate(cnt.begin(), cnt.begin() + k, 0));\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1213",
    "index": "D2",
    "title": "Equalizing by Division (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the number of elements in the array}.\n\nYou are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \\lfloor\\frac{a_i}{2}\\rfloor$).\n\nYou can perform such an operation \\textbf{any} (possibly, zero) number of times with \\textbf{any} $a_i$.\n\nYour task is to calculate the minimum possible number of operations required to obtain at least $k$ equal numbers in the array.\n\n\\textbf{Don't forget that it is possible to have $a_i = 0$ after some operations, thus the answer always exists}.",
    "tutorial": "In this problem we need to write almost the same solution as in the previous one (easy version) but faster. Observe that we calculate the value of $\\lfloor\\frac{a_i}{2^m}\\rfloor$ too many times. Let $vals_x$ for all $x$ from $1$ to $2 \\cdot 10^5$ be the array of numbers of divisions we need to obtain $x$ from every possible $a_i$ from which we can. We can calculate these arrays in time $O(n \\log n)$. How? Let's iterate over all $a_i$ and divide it by $2$ while it is positive (and carry the number of divisions $cur$). Then let's add to the array $vals_{a_i}$ the number $cur$ before each division. Then we can see that we obtain the array $cnt$ from the tutorial of the previous problem for each $x$ from $1$ to $2 \\cdot 10^5$. Let's iterate over all possible values of $x$ and try to update the answer with the sum of $k$ smallest values of $vals_x$ if there is at least $k$ elements in this array. Time complexity: $O(n \\log n \\log(n \\log n))$ or $O(n \\log n)$, depends on sorting method.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tvector<vector<int>> vals(200 * 1000 + 11);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x = a[i];\n\t\tint cur = 0;\n\t\twhile (x > 0) {\n\t\t\tvals[x].push_back(cur);\n\t\t\tx /= 2;\n\t\t\t++cur;\n\t\t}\n\t}\n\t\n\tint ans = 1e9;\n\tfor (int i = 0; i <= 200 * 1000; ++i) {\n\t\tsort(vals[i].begin(), vals[i].end());\n\t\tif (int(vals[i].size()) < k) continue;\n\t\tans = min(ans, accumulate(vals[i].begin(), vals[i].begin() + k, 0));\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1213",
    "index": "E",
    "title": "Two Small Strings",
    "statement": "You are given two strings $s$ and $t$ \\textbf{both of length $2$} and both consisting only of characters 'a', 'b' and 'c'.\n\nPossible examples of strings $s$ and $t$: \"ab\", \"ca\", \"bb\".\n\nYou have to find a string $res$ consisting of $3n$ characters, $n$ characters should be 'a', $n$ characters should be 'b' and $n$ characters should be 'c' and $s$ and $t$ should not occur in $res$ as substrings.\n\nA substring of a string is a contiguous subsequence of that string. So, the strings \"ab\", \"ac\" and \"cc\" are substrings of the string \"abacc\", but the strings \"bc\", \"aa\" and \"cb\" are not substrings of the string \"abacc\".\n\nIf there are multiple answers, you can print any of them.",
    "tutorial": "We can check the following solution by stress-testing (or maybe prove it somehow): let's iterate over all possible permutations of the string \"abc\". Let the first character of the current permutation be $c_1$, the second one be $c_2$ and the third one be $c_3$. Then let's add the following two candidates to the answer: \"c_1 c_2 c_3 c_1 c_2 c_3 ... c_1 c_2 c_3\" (the string consisting of $n$ copies of \"c_1 c_2 c_3\") and \"c_1 ... c_1 c_2 ... c_2 c_3 ... c_3\" (exactly $n$ copies of $c_1$ then exactly $n$ copies of $c_2$ and exactly $n$ copies of $c_3$). Then the answer will be among these $12$ strings and we can check each of them naively.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s, t;\n\tcin >> n >> s >> t;\n\tstring abc = \"abc\";\n\tvector<string> res;\n\tdo {\n\t\tstring cur;\n\t\tfor (int i = 0; i < n; ++i) cur += abc;\n\t\tres.push_back(cur);\n\t\tres.push_back(string(n, abc[0]) + string(n, abc[1]) + string(n, abc[2]));\n\t} while (next_permutation(abc.begin(), abc.end()));\n\t\n\tfor (auto str : res) {\n\t\tif (str.find(s) == string::npos && str.find(t) == string::npos) {\n\t\t\tcout << \"YES\" << endl << str << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tassert(false);\n\tcout << \"NO\" << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1213",
    "index": "F",
    "title": "Unstable String Sort",
    "statement": "Authors have come up with the string $s$ consisting of $n$ lowercase Latin letters.\n\nYou are given two permutations of its indices (not necessary equal) $p$ and $q$ (both of length $n$). Recall that the permutation is the array of length $n$ which contains each integer from $1$ to $n$ exactly once.\n\nFor all $i$ from $1$ to $n-1$ the following properties hold: $s[p_i] \\le s[p_{i + 1}]$ and $s[q_i] \\le s[q_{i + 1}]$. It means that if you will write down all characters of $s$ in order of permutation indices, the resulting string will be sorted in the non-decreasing order.\n\nYour task is to restore \\textbf{any} such string $s$ of length $n$ consisting of \\textbf{at least $k$ distinct lowercase Latin letters} which suits the given permutations.\n\nIf there are multiple answers, you can print any of them.",
    "tutorial": "Because if we write down all characters of $s$ in order of both permutations and this string will be sorted, it is obvious that these two strings are equal. Let's try the maximum possible number of distinct characters and then replace extra characters with 'z'. How to find the maximum number of distinct characters? Let's iterate over all values of $p$ (and $q$) in order from left to right. If we staying at the position $i$ now, let's add to the set $vals_1$ the value $p_i$ and to the set $vals_2$ the value $q_i$. And when these sets become equal the first time, let's say that the block of positions $i$ such that values $p_i$ are in the set right now, have the same letter, and then clear both sets. We can see that this segment of positions is the minimum by inclusion set that can contain equal letters. We don't need to compare sets naively and clear them naively, you can see implementation details in author's solution. If the number of such segments is less than $k$ then the answer is \"NO\", otherwise the answer is \"YES\" and we can fill the string $s$ with letters in order of these segments (if the segment is $[l; r]$ then all characters of $s$ with indices $p_l, p_{l + 1}, \\dots, p_r$ has the same letter, the first segment has the letter 'a', the second one has the letter 'b', and so on, all segments after $25$-th has the letter 'z'). Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> p1(n), p2(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> p1[i];\n\t\t--p1[i];\n\t}\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> p2[i];\n\t\t--p2[i];\n\t}\n\t\n\tset<int> vals1, vals2;\n\tvector<int> rb;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (vals2.count(p1[i])) {\n\t\t\tvals2.erase(p1[i]);\n\t\t} else {\n\t\t\tvals1.insert(p1[i]);\n\t\t}\n\t\tif (vals1.count(p2[i])) {\n\t\t\tvals1.erase(p2[i]);\n\t\t} else {\n\t\t\tvals2.insert(p2[i]);\n\t\t}\n\t\tif (vals1.empty() && vals2.empty()) {\n\t\t\trb.push_back(i);\n\t\t}\n\t}\n\t\n\tif (int(rb.size()) < k) {\n\t\tcout << \"NO\" << endl;\n\t} else {\n\t\tstring s(n, ' ');\n\t\tint l = 0;\n\t\tfor (int it = 0; it < int(rb.size()); ++it) {\n\t\t\tint r = rb[it];\n\t\t\tchar c = 'a' + min(it, 25);\n\t\t\tfor (int i = l; i <= r; ++i) {\n\t\t\t\ts[p1[i]] = c;\n\t\t\t}\n\t\t\tl = r + 1;\n\t\t}\n\t\tcout << \"YES\" << endl << s << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1213",
    "index": "G",
    "title": "Path Queries",
    "statement": "You are given a weighted tree consisting of $n$ vertices. Recall that a tree is a connected graph without cycles. Vertices $u_i$ and $v_i$ are connected by an edge with weight $w_i$.\n\nYou are given $m$ queries. The $i$-th query is given as an integer $q_i$. In this query you need to calculate the number of pairs of vertices $(u, v)$ ($u < v$) such that the maximum weight of an edge on a simple path between $u$ and $v$ doesn't exceed $q_i$.",
    "tutorial": "Let's carry the value $res$ that means the answer for the current set of edges. Initially it is $0$. Let's sort all edges by their weight and all queries by their weight also (both in non-decreasing order). Let's merge components of the tree using DSU (disjoint set union). We need to carry sizes of components also (it is easy if we use DSU). Then let's iterate over all queries in order of non-decreasing their weights. If the current query has weight $cw$ then let's merge all components connected by edges with weight $w_i \\le cw$. When we merge two components with sizes $s_1$ and $s_2$, the answer changes like that: $res := res - \\binom{s_1}{2} - \\binom{s_2}{2} + \\binom{s_1 + s_2}{2}$. The value $\\binom{x}{2}$ equals to $\\frac{x(x-1)}{2}$. It is so because we subtract all old paths corresponding to these components and add all new paths in the obtained component. So the answer for the current query will be $res$ after all required merges. Time complexity: $O(n \\log n + m \\log m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> p, rk;\n\nint getp(int v) {\n\tif (v == p[v]) return v;\n\treturn p[v] = getp(p[v]);\n}\n\nlong long res;\n\nlong long get(int cnt) {\n\treturn cnt * 1ll * (cnt - 1) / 2;\n}\n\nvoid merge(int u, int v) {\n\tu = getp(u);\n\tv = getp(v);\n\t\n\tif (rk[u] < rk[v]) swap(u, v);\n\t\n\tres -= get(rk[u]);\n\tres -= get(rk[v]);\n\t\n\trk[u] += rk[v];\n\t\n\tres += get(rk[u]);\n\t\n\tp[v] = u;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\t\n\tres = 0;\n\tp = rk = vector<int>(n, 1);\n\tiota(p.begin(), p.end(), 0);\n\t\n\tvector<pair<int, pair<int, int>>> e(n - 1);\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tcin >> e[i].second.first >> e[i].second.second >> e[i].first;\n\t\t--e[i].second.first;\n\t\t--e[i].second.second;\n\t}\n\t\n\tvector<pair<int, int>> q(m);\n\tvector<long long> ans(m);\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> q[i].first;\n\t\tq[i].second = i;\n\t}\n\t\n\tsort(e.begin(), e.end());\n\tsort(q.begin(), q.end());\n\t\n\tint pos = 0;\n\tfor (int i = 0; i < m; ++i) {\n\t\twhile (pos < n - 1 && e[pos].first <= q[i].first) {\n\t\t\tint u = e[pos].second.first;\n\t\t\tint v = e[pos].second.second;\n\t\t\tmerge(u, v);\n\t\t\t++pos;\n\t\t}\n\t\tans[q[i].second] = res;\n\t}\n\t\n\tfor (int i = 0; i < m; ++i) {\n\t\tcout << ans[i] << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "divide and conquer",
      "dsu",
      "graphs",
      "sortings",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1214",
    "index": "A",
    "title": "Optimal Currency Exchange",
    "statement": "Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $n$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $d$ rubles, and one euro costs $e$ rubles.\n\nRecall that there exist the following dollar bills: $1$, $2$, $5$, $10$, $20$, $50$, $100$, and the following euro bills — $5$, $10$, $20$, $50$, $100$, $200$ (note that, in this problem we do \\textbf{not} consider the $500$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.\n\nHelp him — write a program that given integers $n$, $e$ and $d$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.",
    "tutorial": "If we have bought dollar bills with value of two or more dollar bill, we can change it one-dollar bills. Same goes for euro, we can replace all euro bills with several $5$-euro bills. Now we can simply try buying some number of five-euro bills and buying all the rest with one-dollar bills. Complexity is $\\mathcal{O}(n)$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1214",
    "index": "B",
    "title": "Badges",
    "statement": "There are $b$ boys and $g$ girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and $n$ participants have accepted the invitation. The organizers do not know how many boys and girls are among them.\n\nOrganizers are preparing red badges for girls and blue ones for boys.\n\nVasya prepared $n+1$ decks of badges. The $i$-th (where $i$ is from $0$ to $n$, inclusive) deck contains $i$ blue badges and $n-i$ red ones. The total number of badges in any deck is exactly $n$.\n\nDetermine the \\textbf{minimum} number of decks among these $n+1$ that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament.",
    "tutorial": "Vasya must take one deck for each possible combination $(participants_{girls}, participants_{boys})$ (where $0 \\le participants_{girls} \\le g$, $0 \\le participants_{boys} \\le b$ and $participants_{girls} + participants_{boys} = n$). Let's determine how many girls can come for the game: at least $n - min(b, n)$, at most $min(g, n)$. All intermediate values are also possible, to the answer is just $min(g, n) - (n - min(b, n)) + 1$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1214",
    "index": "C",
    "title": "Bad Sequence",
    "statement": "Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself.\n\nTo make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning \"(\" into \")\" or vice versa) isn't allowed.\n\nWe remind that bracket sequence $s$ is called correct if:\n\n- $s$ is empty;\n- $s$ is equal to \"($t$)\", where $t$ is correct bracket sequence;\n- $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences.\n\nFor example, \"(()())\", \"()\" are correct, while \")(\" and \"())\" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.",
    "tutorial": "Let's call a balance of bracket sequence a number of opening brackets minus the number of closing brackets. Correct bracket sequence is such a sequence that balance of any of its prefixes is at least $0$ and the balance of the entire sequence is equal to $0$. To solve the problem let's consider the shortest prefix with balance equal to $-1$. In this prefix last symbol is obviously equal to \")\", so let's move this closing bracket to the end of the sequence. If the sequence is correct now, then the answer is \"Yes\", otherwise it is \"No\", because it means that in original sequence there exists some longer prefix with balance equal to $-2$. Let's show why we can't move some bracket so that the sequence becomes correct. Consider the shortest prefix with balance equal to $-2$. If we move some opening bracket to the beginning of the sequence, balance of considered prefix becomes $-1$ and the sequence is not correct yet. Moving opening bracket from considered prefix to the beginning doesn't change anything. Even more, if we move the closing bracket from the end of the considered prefix to the end of the sequence, it still doesn't become correct, because balance of the prefix is $-1$. This results in a following solution: if balance of all prefixes is not less than $-1$, answer is \"Yes\", otherwise it's \"No\".",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1214",
    "index": "D",
    "title": "Treasure Island",
    "statement": "All of us love treasures, right? That's why young Vasya is heading for a Treasure Island.\n\nTreasure Island may be represented as a rectangular table $n \\times m$ which is surrounded by the ocean. Let us number rows of the field with consecutive integers from $1$ to $n$ from top to bottom and columns with consecutive integers from $1$ to $m$ from left to right. Denote the cell in $r$-th row and $c$-th column as $(r, c)$. Some of the island cells contain impassable forests, and some cells are free and passable. Treasure is hidden in cell $(n, m)$.\n\nVasya got off the ship in cell $(1, 1)$. Now he wants to reach the treasure. He is hurrying up, so he can move only from cell to the cell in next row (downwards) or next column (rightwards), i.e. from cell $(x, y)$ he can move only to cells $(x+1, y)$ and $(x, y+1)$. Of course Vasya can't move through cells with impassable forests.\n\nEvil Witch is aware of Vasya's journey and she is going to prevent him from reaching the treasure. Before Vasya's first move she is able to grow using her evil magic impassable forests in previously free cells. Witch is able to grow a forest in any number of any free cells except cells $(1, 1)$ where Vasya got off his ship and $(n, m)$ where the treasure is hidden.\n\nHelp Evil Witch by finding out the minimum number of cells she has to turn into impassable forests so that Vasya is no longer able to reach the treasure.",
    "tutorial": "The answer is no more than two as we can block $(2, 1)$ and $(1, 2)$. If there is no way from $(1, 1)$ to $(n, m)$, the answer is zero. The only thing to do is to distinguish $k = 1$ and $k = 2$. If answer is one, there must exist such cell $(x, y)$ that each path from $(1, 1)$ to $(n, m)$ goes through that cell. Also we can notice that in each path the cell $(x, y)$ goes on the $(x + y - 1)^th$ place. Let's run $dfs$ to obtain the set of cells which are accessible from $(1, 1)$ and $dfs$ backwards to obtain the set on cells such that $(n, m)$ is accessible from them. Let's intersect these sets and group cells by the distance from $(1, 1)$. If some group has a single cell, that would be the cell to block and the answer is one. If each group has more than one cell, the answer is two.",
    "tags": [
      "dfs and similar",
      "dp",
      "flows",
      "hashing"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1214",
    "index": "E",
    "title": "Petya and Construction Set",
    "statement": "It's Petya's birthday party and his friends have presented him a brand new \"Electrician-$n$\" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.\n\nConstruction set \"Electrician-$n$\" consists of $2n - 1$ wires and $2n$ light bulbs. Each bulb has its own unique index that is an integer from $1$ to $2n$, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.\n\nPetya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed $2i$ and $2i - 1$ turn on if the chain connecting them consists of exactly $d_i$ wires. Moreover, the following \\textbf{important} condition holds: the value of $d_i$ is never greater than $n$.\n\nPetya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.",
    "tutorial": "Assume without loss of generality that the array $d$ sorted in non-increasing order. Let's make a linear (\"bamboo\") graph from the vertices $1, 3, 5, \\ldots, 2n - 1$ in this order. We will add nodes $2i$ one by one, we will also maintain the longest route during that. On the $i$-th step we are looking for the vertex at the distance $d_i - 1$ from $2i - 1$. That node is $(i + d_i - 1)$-th on the route. So we can connect to it vertex $2i$. If $2i$ was connected to the last vertex of the route we should add $2i$ to the end of it. $(i + d_i - 1)$-th node on the longest route always exists because of two limitations: $d_1 \\leq n$ for all $i \\geq 2$: $d_{i - 1} \\geq d_i$.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math",
      "sortings",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1214",
    "index": "F",
    "title": "Employment",
    "statement": "Two large companies \"Cecsi\" and \"Poca Pola\" are fighting against each other for a long time. In order to overcome their competitor, \"Poca Pola\" started a super secret project, for which it has total $n$ vacancies in all of their offices. After many tests and interviews $n$ candidates were selected and the only thing left was their employment.\n\nBecause all candidates have the same skills, it doesn't matter where each of them will work. That is why the company decided to distribute candidates between workplaces so that the total distance between home and workplace over all candidates is minimal.\n\nIt is well known that Earth is round, so it can be described as a circle, and all $m$ cities on Earth can be described as points on this circle. All cities are enumerated from $1$ to $m$ so that for each $i$ ($1 \\le i \\le m - 1$) cities with indexes $i$ and $i + 1$ are neighbors and cities with indexes $1$ and $m$ are neighbors as well. People can move only along the circle. The distance between any two cities equals to minimal number of transitions between neighboring cities you have to perform to get from one city to another. In particular, the distance between the city and itself equals $0$.\n\nThe \"Poca Pola\" vacancies are located at offices in cities $a_1, a_2, \\ldots, a_n$. The candidates live in cities $b_1, b_2, \\ldots, b_n$. It is possible that some vacancies are located in the same cities and some candidates live in the same cities.\n\nThe \"Poca Pola\" managers are too busy with super secret project, so you were asked to help \"Poca Pola\" to distribute candidates between workplaces, so that the sum of the distance between home and workplace over all candidates is minimum possible.",
    "tutorial": "First, let's notice that the optimal answer can be achieved without changing the relative order of candidates. That means that if we order candidates by circle clockwise, the second candidate will work at the next clockwise workplace from the first candidate's workplace, the third candidate will work at the next clockwise workplace from the second candidate's workplace and so on. Let's prove it. If in optimal answer the order has changed, then there should be 2 candidates, so that the first of them lives earlier clockwise then the second and works at workplace, which is further. If we swap their workplaces, the distance between home and workplace for each of them will either stay the same or decrease. So, doing this swaps, we can achieve the situation, when the relative order of candidates stay the same. Now we can come up with simple $O(n^2)$ solution. Let's first sort all candidates and workplaces by their city number. Let's select some workplace for the first candidate. Because in the optimal answer the order of candidates will not change, for each candidate we know his workplace. Now in $O(n)$ time we can calculate the total distance. And because there are $n$ possible workplaces for the first candidate, the solution works in $O(n^2)$ time. To solve problem faster, let's notice, that if some candidate lives in city with number $x$ and his workplace has number $y$, the the total distance from home to work for him will be: $-x + y + m$ if $y < x - m / 2$ $x - y$ if $x - m / 2 \\le y < x$ $-x + y$ if $x \\le y < x + m / 2$ $x - y + m$ if $x + m / 2 \\le y$",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1214",
    "index": "G",
    "title": "Feeling Good",
    "statement": "Recently biologists came to a fascinating conclusion about how to find a chameleon mood. Consider chameleon body to be a rectangular table $n \\times m$, each cell of which may be green or blue and may change between these two colors. We will denote as $(x, y)$ ($1 \\leq x \\leq n$, $1 \\leq y \\leq m$) the cell in row $x$ and column $y$.\n\nLet us define a chameleon good mood certificate to be four cells which are corners of some subrectangle of the table, such that colors in opposite cells among these four are similar, and at the same time not all of the four cell colors are similar. Formally, it is a group of four cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$ for some $1 \\leq x_1 < x_2 \\leq n$, $1 \\leq y_1 < y_2 \\leq m$, that colors of $(x_1, y_1)$ and $(x_2, y_2)$ coincide and colors of $(x_1, y_2)$ and $(x_2, y_1)$ coincide, but not all of the four cells share the same color. It was found that whenever such four cells are present, chameleon is in good mood, and vice versa: if there are no such four cells, chameleon is in bad mood.\n\nYou are asked to help scientists write a program determining the mood of chameleon. Let us consider that initially all cells of chameleon are green. After that chameleon coloring may change several times. On one change, colors of contiguous segment of some table row are replaced with the opposite. Formally, each color change is defined by three integers $a$, $l$, $r$ ($1 \\leq a \\leq n$, $1 \\leq l \\leq r \\leq m$). On such change colors of all cells $(a, b)$ such that $l \\leq b \\leq r$ are replaced with the opposite.\n\nWrite a program that reports mood of the chameleon after each change. Additionally, if the chameleon mood is good, program should find out any four numbers $x_1$, $y_1$, $x_2$, $y_2$ such that four cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$ are the good mood certificate.",
    "tutorial": "Let's define the set $A_i$ for each $1 \\leq i \\leq n$ as a set of columns $j$, such that the color of the cell $(i, j)$ is blue. If there exists two rows $1 \\leq x_1 < x_2 \\leq n$, such that $A_{x_1} \\not\\subset A_{x_2}$ and $A_{x_2} \\not\\subset A_{x_1}$ the good mood certificate exists. It's easy to see, because if $A_{x_1} \\not\\subset A_{x_2}$ there exists some $y_1$, such that $y_1 \\in A_{x_1}$ and $y_1 \\not\\in A_{x_2}$ and if $A_{x_2} \\not\\subset A_{x_1}$ there exists some $y_2$, such that $y_2 \\in A_{x_2}$ and $y_2 \\not\\in A_{x_1}$. Four cells $(x_1, y_1)$, $(x_1, y_2)$, $(x_2, y_1)$, $(x_2, y_2)$ will be the good mood certificate. Otherwise, if for any two rows $1 \\leq x_1 < x_2 \\leq n$ $A_{x_1} \\subset A_{x_2}$ or $A_{x_2} \\subset A_{x_1}$, there is no good mood certificate. Let's use bitset $a_i$ for each row, such that $a_{{i}{j}} = 1$, if the color of the cell $(i, j)$ is blue. For two rows $1 \\leq x_1 < x_2 \\leq n$ it's easy to check that $A_{x_1} \\subset A_{x_2}$ or $A_{x_2} \\subset A_{x_1}$ and find any good mood certificate if it is false using simple operations with two bitsets $a_{x_1}$ and $a_{x_2}$ in time $O(\\frac{m}{w})$. Let's sort rows by the size of $A_i$. If for every two adjacent rows in this order one of them was a subset of other it is true for every pair of rows. So, we can check only pairs of adjacent rows in the sorted order. Let's keep a set of rows, sorting them by the size of $A_i$. And let's keep set of any good mood certificate for every two adjacent rows in the first set, if it exists. Now, if some row $x$ changes, we can change bitset $a_x$ in time $O(\\frac{m}{w})$ and make $O(1)$ changes with our two sets. Time complexity: $O((\\log{n} + \\frac{m}{w})q)$, there $w=32$ or $w=64$.",
    "tags": [
      "bitmasks",
      "data structures"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1214",
    "index": "H",
    "title": "Tiles Placement",
    "statement": "The new pedestrian zone in Moscow city center consists of $n$ squares connected with each other by $n - 1$ footpaths. We define a simple path as a sequence of squares such that no square appears in this sequence twice and any two adjacent squares in this sequence are directly connected with a footpath. The size of a simple path is the number of squares in it. The footpaths are designed in a such a way that there is exactly one simple path between any pair of different squares.\n\nDuring preparations for Moscow City Day the city council decided to renew ground tiles on all $n$ squares. There are $k$ tile types of different colors, numbered from $1$ to $k$. For each square exactly one tile type must be selected and then used to cover this square surface. To make walking through the city center more fascinating, it was decided to select tiles types for each square in such a way that any possible simple path of size exactly $k$ contains squares with all $k$ possible tile colors.\n\nYou need to find out whether it is possible to place the tiles this way or not.",
    "tutorial": "Suppose there exists a vertex with tree with a tree paths going from it, with longest paths of lengths $a$, $b$ and $c$ (in edges). Then if $a + b \\ge k - 1$, $b + c \\ge k - 1$, $a + c \\ge k - 1$, then clearly the answer is Impossible. We can check whether such vertex exists in $\\mathcal{O}(n)$ using subtree dp and \"uptree dp\". Good news: this is the only case when the answer is \"No\". Bad news: providing the coloring is slightly more sophisticated. In fact, we can prove that the following coloring works: Construct a tree's diameter. Color vertices on diameter with periodic colors: $1$, $2$, ..., $k$, $1$, $2$, ... By the way, if diameter has less than $k$ vertices, any coloring will be correct. Cut the diameter in half, the parts' lengths will differ by $1$ atmost. Color both halves of the tree with dfs: colors in the left part will decrease $i \\to i - 1 \\to \\ldots$, while colors in the right part will increase $i \\to i + 1 \\to \\ldots$. The result will look roughly as follows: The total complexity is $\\mathcal{O}(n)$. Let's give a sketch of the proof why this coloring works. Well, suppose there is some bad path of $k$ vertices. Let's analyze path's position with respect to the diameter. Case 1. The bad path is not related to the diameter. It's easy to see that blue part of diameter is greater or equal than any half of the red path; so the vertex $v$ is a bad vertex to the our criterion. Case 2. The bad path goes through a diameter, but lies in one half of it. The vertex $v$ makes a bad vertex for the criterion, just for the same reasons. Case 3. The bad path goes through a diameter, and lies in both halves. If you recall how our coloring looks like, you will see that all paths of this form are well-colored.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1215",
    "index": "A",
    "title": "Yellow Cards",
    "statement": "The final match of the Berland Football Cup has been held recently. The referee has shown $n$ yellow cards throughout the match. At the beginning of the match there were $a_1$ players in the first team and $a_2$ players in the second team.\n\nThe rules of sending players off the game are a bit different in Berland football. If a player from the first team receives $k_1$ yellow cards throughout the match, he can no longer participate in the match — he's sent off. And if a player from the second team receives $k_2$ yellow cards, he's sent off. After a player leaves the match, he can no longer receive any yellow cards. Each of $n$ yellow cards was shown to exactly one player. Even if all players from one team (or even from both teams) leave the match, the game still continues.\n\nThe referee has lost his records on who has received each yellow card. Help him to determine the minimum and the maximum number of players that could have been thrown out of the game.",
    "tutorial": "At first, if $k_1 > k_2$, then we swap $k_1$ with $k_2$ and $a_1$ with $a_2$, so the number of yellow cards required to send a player of the first team off is not greater than the same value for the second team. If all players from the first team receive $k_1 - 1$ cards each and all players from the second team receive $k_2 - 1$ cards each, we will minimize the number of players who left the game. Let $cnt = a_1 \\cdot (k_1 - 1) + a_2 \\cdot (k_2 - 1)$. If $cnt \\le 0$, then the minimum number of players who left the game is equal to $0$. In the other case, if any player receivse one more yellow card, he leaves the game. So the minimum number of players who left the game is $(n - cnt)$. When we maximize the number of players who left the game, at first we should give cards to players in the first team, and then give cards to players in the second team. So, if $n \\le a_1 \\cdot k_1$, the answer is $\\lfloor \\frac{n}{k_1} \\rfloor$. In the other case, the answer is $a_1 + \\lfloor \\frac{n - a_1 \\cdot k_1}{k_2} \\rfloor$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint a1, a2, k1, k2, n;\n\ninline void read() {\n\tcin >> a1 >> a2 >> k1 >> k2 >> n;\t\n}\n\ninline void solve() {\n\tif (k1 > k2) {\n\t\tswap(k1, k2);\n\t\tswap(a1, a2);\n\t}\n\tint minCnt = max(0, n &mdash; a1 * (k1 &mdash; 1) &mdash; a2 * (k2 &mdash; 1));\n\tint maxCnt = 0;\n\tif (n <= a1 * k1) {\n\t\tmaxCnt = n / k1;\n\t} else {\n\t\tmaxCnt = a1 + (n &mdash; a1 * k1) / k2;\n    }    \n    cout << minCnt << ' ' << maxCnt << endl;\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    srand(time(NULL));\n    cerr << setprecision(10) << fixed;\n    \n    read();\n    solve();\n \n    //cerr << \"TIME: \" << clock() << endl;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1215",
    "index": "B",
    "title": "The Number of Products",
    "statement": "You are given a sequence $a_1, a_2, \\dots, a_n$ consisting of $n$ non-zero integers (i.e. $a_i \\ne 0$).\n\nYou have to calculate two following values:\n\n- the number of pairs of indices $(l, r)$ $(l \\le r)$ such that $a_l \\cdot a_{l + 1} \\dots a_{r - 1} \\cdot a_r$ is negative;\n- the number of pairs of indices $(l, r)$ $(l \\le r)$ such that $a_l \\cdot a_{l + 1} \\dots a_{r - 1} \\cdot a_r$ is positive;",
    "tutorial": "At first, let's calculate the value of $ans_p$ - the number of subsegments with positive product. We should iterate through the array and store $bal$ - the number of negative elements. Also we should store $cnt_1$ and $cnt_2$ - the number of elements such that there is an even number of negative elements before them ($cnt_1$) or an odd number of negative elements before them ($cnt_2$). If for the current element $bal$ is even, we should increase $cnt_1$ by one, else we should increase $cnt_2$ by one. Then if the current element is negative, we should increase $bal$ by one. Then we should add the number of subsegments ending in the current element and having positive product to $ans_p$. If $bal$ is even, then any subsegment ending in the current element and containing even number of negative elements should begin in a position where $bal$ was even too, so we should add $cnt_1$ to $ans_p$. If $bal$ is odd, we should add $cnt_2$ to $ans_p$ (we use similar reasoning). The number of segments having negative product can be calculated, for example, by subtracting $ans_p$ from the total number of subsegments, which is $\\frac{n \\cdot (n + 1)}{2}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\n\nint n;\nint a[N];\n\ninline void read() {\t\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n}\n\ninline void solve() {\n\tint pos = -1;\n\tli ans0 = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (a[i] == 0) {\n\t\t\tpos = i;\n\t\t}\n\t\tif (pos != -1) {\n\t\t\tans0 += pos + 1;\n\t\t}\n\t}\t\n\tint cnt1 = 0, cnt2 = 0;\n\tint bal = 0;\n\tli ansP = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (a[i] == 0) {\n\t\t\tcnt1 = 0, cnt2 = 0, bal = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (bal % 2 == 0) {\t\n\t\t\tcnt1++;\n\t\t} else {\n\t\t\tcnt2++;\n\t\t}\n\t\tif (a[i] < 0) {\n\t\t\tbal++;\n\t\t}\n\t\tif (bal % 2 == 0) {\n\t\t\tansP += cnt1;\n\t\t} else {\n\t\t\tansP += cnt2;\n\t\t}\n\t}\n\tcout << n * 1ll * (n + 1) / 2 - ans0 - ansP << ' ' << ansP << endl;\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    srand(time(NULL));\n    cerr << setprecision(10) << fixed;\n    \n    read();\n    solve();\n \n    //cerr << \"TIME: \" << clock() << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1215",
    "index": "C",
    "title": "Swap Letters",
    "statement": "Monocarp has got two strings $s$ and $t$ having equal length. Both strings consist of lowercase Latin letters \"a\" and \"b\".\n\nMonocarp wants to make these two strings $s$ and $t$ equal to each other. He can do the following operation any number of times: choose an index $pos_1$ in the string $s$, choose an index $pos_2$ in the string $t$, and swap $s_{pos_1}$ with $t_{pos_2}$.\n\nYou have to determine the minimum number of operations Monocarp has to perform to make $s$ and $t$ equal, and print any optimal sequence of operations — or say that it is impossible to make these strings equal.",
    "tutorial": "Let's calculate two vectors $pos_{01}$ and $pos_{10}$. $pos_{01}$ will contain all positions $x$ such that $s[x] = 0$ and $t[x] = 1$. Analogically, $pos_{10}$ will contain all positions $x$ such that $s[x] = 1$ and $t[x] = 0$. If the sizes of these vectors are not equal modulo $2$, the answer does not exist, because the total number of letters \"a\" and \"b\" should be even. In the other case, we should perform operations in a greedy way. In one operation we can make $s[a]$ equal to $t[a]$ and $s[b]$ equal to $t[b]$, if both $a$ and $b$ belong to $pos_{01}$, or if both these positions belong $pos_{10}$. If the sizes of $pos_{01}$ and $pos_{10}$ are even, we need only $(\\frac{|pos_{01}|}{2} + \\frac{|pos_{10}|}{2})$ operation. In the other case, there are two positions $x$ and $y$ such that $s[x] = 0$, $s[y] = 1$, $t[x] = 1$, $t[y] = 0$. We need two operations to make $s[x] = t[x]$ and $s[y] = t[y]$: at first we perform the operation $(x, x)$, and then the operation $(x, y)$. After that, strings $s$ and $t$ will be equal to each other.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nstring s, t;\n\ninline void read() {\t\n\tcin >> n >> s >> t;\n}\n\ninline void solve() {\n\tvector<int> pos01, pos10;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] != t[i]) {\n\t\t\tif (s[i] == 'a') {\n\t\t\t\tpos01.pb(i);\n\t\t\t} else {\n\t\t\t\tpos10.pb(i);\n\t\t\t}\n\t\t}\n\t}\n\tif (sz(pos01) % 2 != sz(pos10) % 2) {\n\t\tcout << -1 << endl;\n\t\treturn;\n\t}\n\tvector<pair<int, int> > ans;\n\tfor (int i = 0; i + 1 < sz(pos01); i += 2) {\n\t\tans.pb(mp(pos01[i], pos01[i + 1]));\n\t}\n\tfor (int i = 0; i + 1 < sz(pos10); i += 2) {\n\t\tans.pb(mp(pos10[i], pos10[i + 1]));\n\t}\n\tif (sz(pos01) % 2) {\n\t\tint x = pos01.back();\n\t\tint y = pos10.back();\n\t\tans.pb(mp(x, x));\n\t\tans.pb(mp(x, y));\n\t}\n\tcout << sz(ans) << endl;\n\tfor (int i = 0; i < sz(ans); i++) {\n\t\tcout << ans[i].ft + 1 << ' ' << ans[i].sc + 1 << endl;\n\t}\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    srand(time(NULL));\n    cerr << setprecision(10) << fixed;\n    \n    read();\n    solve();\n \n    //cerr << \"TIME: \" << clock() << endl;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1215",
    "index": "D",
    "title": "Ticket Game",
    "statement": "Monocarp and Bicarp live in Berland, where every bus ticket consists of $n$ digits ($n$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. \\textbf{The number of digits that have been erased is even}.\n\nMonocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $\\frac{n}{2}$ digits of this ticket is equal to the sum of the last $\\frac{n}{2}$ digits.\n\nMonocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $0$ to $9$. The game ends when there are no erased digits in the ticket.\n\nIf the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.",
    "tutorial": "Let's denote the balance as the difference between the sum of digits in the left half and the sum of digits in the right half. Also let $L$ be the minimum possible balance (it can be calculated if we replace all question marks in the left half with $0$'s and all the question marks in the right half with $9$'s), and let $R$ be the maximum possible balance. The second player wins if and only if $\\frac{L + R}{2} = 0$. Let's prove it by induction on the number of question marks left in the ticket. If all characters are digits, the second player wins only if the ticket is happy, and that is when $\\frac{L + R}{2} = 0$. Okay, now suppose the number of question marks is even, and now it's first player's turn. Each turn decreases the value of $R - L$ by $9$, and may set $L$ to any number from current $L$ to $L + 9$. If $L + R > 0$, then the first player can make $L$ as large as possible, and set it to $L + 9$. The best thing the second player can do on his turn is to set $R$ to $R - 9$ (and leave $L$ as it is), and the value of $L + R$ will be the same as it was two turns earlier. The case $L + R < 0$ can be analyzed similarly. And in the case $L + R = 0$ the second player has a symmetric strategy.",
    "code": "#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nint n;\n\nint main() {\n    cin >> n;\n    long double sum1 = 0, sum2 = 0;\n    string s;\n    cin >> s;\n    for (int i = 0; i < n; i++) {\n        if (s[i] != '?') {\n            if (i < n / 2) {\n                sum1 += (long double)(s[i] - '0');\n            } else {\n                sum2 += (long double)(s[i] - '0');\n            }\n        } else {\n            if (i < n / 2) {\n                sum1 += (long double)4.5;\n            } else {\n                sum2 += (long double)4.5;   \n            }\n        }\n    }\n    if (fabsl(sum1 - sum2) < 1e-9) {\n        cout << \"Bicarp\" << endl;\n    } else {\n        cout << \"Monocarp\" << endl;\n    }\n}",
    "tags": [
      "games",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1215",
    "index": "E",
    "title": "Marbles",
    "statement": "Monocarp has arranged $n$ colored marbles in a row. The color of the $i$-th marble is $a_i$. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).\n\nIn other words, Monocarp wants to rearrange marbles so that, for every color $j$, if the leftmost marble of color $j$ is $l$-th in the row, and the rightmost marble of this color has position $r$ in the row, then every marble from $l$ to $r$ has color $j$.\n\nTo achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.\n\nYou have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.",
    "tutorial": "The main fact is that the number of colors is less than $20$, which allows us to use exponential solutions. For each pair of colors $(i, j)$, we can calculate $cnt[i][j]$ - the number of swaps required to place all marbles of color $i$ before all marbles of color $j$ (if we consider only marbles of these two colors). We can store a sorted vector for each color, and calculate this information for a fixed pair with two pointers. Then let's use subset DP to fix the order of colors. Let $d[mask]$ be the minimum number of operations to correctly order all marbles from the $mask$ of colors. Let's iterate on the next color we consider - it should be a position in binary representation of $mask$ with $0$ in it. We will place all marbles of this color after all marbles we already placed. If we fix a new color $i$, let's calculate the $sum$ (the additional number of swaps we have to make) by iterating on the bit $j$ equal to $1$ in the $mask$, and increasing $sum$ by $cnt[j][i]$ for every such bit. The new state of DP can be calculated as $nmask = mask | (1 << i)$. So the transition can be implemented as $d[nmask] = min(d[nmask], d[mask] + sum)$. The answer is the minimum number of swaps required to place all the colors, and that is $d[2^{20} - 1]$.",
    "code": "#include <iostream>\n#include <set>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 1000 * 1000 + 13;\nconst int M = 20 + 1;\nconst long long INF = 1000 * 1000 * 1000 * 1ll * 1000 * 1000 * 1000;\n\nint n;\nlong long d[(1 << M)];\nlong long cnt[M][M];\nvector<int> col[M];\n\nint main() {\n    cin >> n;\n    for (int i = 0; i < n; i++) {\n        int x;\n        cin >> x;\n        x--;\n        col[x].push_back(i);\n    }\n    for (int i = 0; i < 20; i++) {\n        for (int j = 0; j < 20; j++) {\n            if (i == j) {\n                continue;\n            }\n            if ((int)col[i].size() == 0 || (int)col[j].size() == 0) {\n                continue;\n            }\n            int pos2 = 0;\n            for (int pos1 = 0; pos1 < (int)col[i].size(); pos1++) {\n                while (true) {\n                    if (pos2 == (int)col[j].size() - 1 || col[j][pos2 + 1] > col[i][pos1]) {\n                        break;\n                    }\n                    pos2++;\n                }\n                if (col[i][pos1] > col[j][pos2]) {\n                    cnt[i][j] += pos2 + 1;\n                }\n            }\n        }\n    }\n\n    for (int mask = 0; mask < (1 << 20); mask++) {\n        d[mask] = INF;\n    }\n    d[0] = 0;\n    for (int mask = 0; mask < (1 << 20); mask++) {\n        vector<int> was;\n        for (int i = 0; i < 20; i++) {\n            if (mask & (1 << i)) {\n                was.push_back(i);\n            }\n        }\n        for (int i = 0; i < 20; i++) {\n            if (mask & (1 << i)) {\n                continue;\n            }\n            long long sum = 0;\n            for (int j = 0; j < (int)was.size(); j++) {\n                sum += cnt[was[j]][i];\n            }\n            int nmask = mask | (1 << i);\n            d[nmask] = min(d[nmask], d[mask] + sum);\n        }\n    }\n    cout << d[(1 << 20) - 1] << endl;\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1215",
    "index": "F",
    "title": "Radio Stations",
    "statement": "In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. $n$ complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the $i$-th complaint, one of the radio fans has mentioned that the signals of two radio stations $x_i$ and $y_i$ are not covering some parts of the city, and demanded that the signal of \\textbf{at least one} of these stations can be received in the whole city.\n\nOf cousre, the mayor of Bertown is currently working to satisfy these complaints. A new radio tower has been installed in Bertown, it can transmit a signal with any integer power from $1$ to $M$ (let's denote the signal power as $f$). The mayor has decided that he will choose a set of radio stations and establish a contract with every chosen station. To establish a contract with the $i$-th station, the following conditions should be met:\n\n- the signal power $f$ should be not less than $l_i$, otherwise the signal of the $i$-th station won't cover the whole city;\n- the signal power $f$ should be not greater than $r_i$, otherwise the signal will be received by the residents of other towns which haven't established a contract with the $i$-th station.\n\nAll this information was already enough for the mayor to realise that choosing the stations is hard. But after consulting with specialists, he learned that some stations the signals of some stations may interfere with each other: there are $m$ pairs of stations ($u_i$, $v_i$) that use the same signal frequencies, and for each such pair it is impossible to establish contracts with both stations. \\textbf{If stations $x$ and $y$ use the same frequencies, and $y$ and $z$ use the same frequencies, it does not imply that $x$ and $z$ use the same frequencies}.\n\nThe mayor finds it really hard to analyze this situation, so he hired you to help him. You have to choose signal power $f$ and a set of stations to establish contracts with such that:\n\n- all complaints are satisfied (formally, for every $i \\in [1, n]$ the city establishes a contract either with station $x_i$, or with station $y_i$);\n- no two chosen stations interfere with each other (formally, for every $i \\in [1, m]$ the city \\textbf{does not} establish a contract either with station $u_i$, or with station $v_i$);\n- for each chosen station, the conditions on signal power are met (formally, for each chosen station $i$ the condition $l_i \\le f \\le r_i$ is met).",
    "tutorial": "Let's try to solve the problem without any constraints on $f$ (we just need to choose a set of stations that satisfies all the complaints and contains no forbidden pair). We can see that this is an instance of 2-SAT: we can convert it into a logical expression that is a conjunction of some clauses, and each clause contains exactly two variables (maybe negated), we have to assign some values to all variables so that this expression is true. The $i$-th variable $true$ if we include the $i$-th station in our answer, or $false$ otherwise. We can solve this problem in linear time by building an implication graph and finding strongly connected components in it. If the constraints were lower, we could iterate on $f$ and initially set all variables corresponding to stations we can't use with fixed $f$ to $false$. But this solution is quadratic, so we have to include $f$ into our original 2-SAT problem. Let's introduce $M$ additional variables, the $i$-th of them corresponding to the fact \"$f \\ge i$\". Add $M - 1$ clause of the form \"$f \\ge i$ OR NOT $f \\ge i + 1$\" into our conjunction. The prefix of additional variables which are equal to $true$ can be transformed into the value or $f$ we should use, and vice versa. If we introduce these variables, the constraints on $f$ that are implied by some station can be modeled with two additiona clauses: \"$f \\ge l_i$ OR station $i$ is not used\" and \"NOT $f \\ge r_i + 1$ OR station $i$ is not used\". So we get a linear solution (though with a noticeable constant factor).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1600043;\n\nvector<int> g[N];\nvector<int> gt[N];\nint used[N];\nvector<int> order;\nint comp[N];\nvector<int> result;\nint v;\n\nvoid add_edge(int v1, int v2)\n{\n\tg[v1].push_back(v2);\n\tgt[v2].push_back(v1);\n}\n\nvoid add_disjunction(int v1, int v2)\n{\n\tadd_edge(v1 ^ 1, v2);\n\tadd_edge(v2 ^ 1, v1);\n}\n\nvoid dfs1(int v)\n{\n\tif(used[v]) return;\n\tused[v] = 1;\n\tfor(auto u : g[v])\n\t\tdfs1(u);\n\torder.push_back(v);\n}\n\nvoid dfs2(int v, int cc)\n{\n\tif(comp[v]) return;\n\tcomp[v] = cc;\n\tfor(auto u : gt[v])\n\t\tdfs2(u, cc);\n}\n\nbool solve2SAT()\n{\n\tfor(int i = 0; i < v * 2; i++)\n\t\tdfs1(i);\n\treverse(order.begin(), order.end());\n\tint cc = 0;\n\tfor(auto x : order)\n\t{\n\t\tif(comp[x] == 0)\n\t\t{\n\t\t\tcc++;\n\t\t\tdfs2(x, cc);\n\t\t}\n\t}\n\tfor(int i = 0; i < v; i++)\n\t{\n\t\tif(comp[i * 2] == comp[i * 2 + 1])\n\t\t\treturn false;\n\t\telse if(comp[i * 2] > comp[i * 2 + 1])\n\t\t\tresult.push_back(i);\n\t}\n\treturn true;\n}\n\nint main()\n{\n\tint n, p, M, m;\n\tscanf(\"%d %d %d %d\", &n, &p, &M, &m);\n\tv = p + M - 1;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t--x;\n\t\t--y;\n\t\tadd_disjunction(x * 2, y * 2);\n\t}\n\tfor(int i = 0; i < p; i++)\n\t{\n\t\tint l, r;\n\t\tscanf(\"%d %d\", &l, &r);\n\t\tif(l != 1)\n\t\t\tadd_disjunction((l - 2 + p) * 2, i * 2 + 1);\n\t\tif(r != M)\n\t\t\tadd_disjunction((r - 1 + p) * 2 + 1, i * 2 + 1);\n\t}\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t--x;\n\t\t--y;\n\t\tadd_disjunction(x * 2 + 1, y * 2 + 1);\n\t}\n\tfor(int i = 2; i <= M - 1; i++)\n\t{\n\t    int f1 = i - 2 + p;\n\t    int f2 = f1 + 1;\n\t    add_disjunction(f1 * 2, f2 * 2 + 1);\n\t}\n\tif(!solve2SAT())\n\t{\n\t\tputs(\"-1\");\n\t\treturn 0;\n\t}\n\tint k = 1;\n\tvector<int> stations;\n\tfor(auto x : result)\n\t\tif(x < p)\n\t\t\tstations.push_back(x);\n\t\telse\n\t\t\tk = max(k, x - p + 2);\n\tprintf(\"%d %d\\n\", int(stations.size()), k);\n\tfor(auto x : stations)\n\t\tprintf(\"%d \", x + 1);\n\treturn 0;\n}",
    "tags": [
      "2-sat"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1216",
    "index": "A",
    "title": "Prefixes",
    "statement": "Nikolay got a string $s$ of \\textbf{even} length $n$, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from $1$ to $n$.\n\nHe wants to modify his string so that every its prefix of \\textbf{even} length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.\n\nThe prefix of string $s$ of length $l$ ($1 \\le l \\le n$) is a string $s[1..l]$.\n\nFor example, for the string $s=$\"abba\" there are two prefixes of the even length. The first is $s[1\\dots2]=$\"ab\" and the second $s[1\\dots4]=$\"abba\". Both of them have the same number of 'a' and 'b'.\n\nYour task is to calculate the minimum number of operations Nikolay has to perform with the string $s$ to modify it so that every its prefix of \\textbf{even} length has an equal amount of letters 'a' and 'b'.",
    "tutorial": "The problem can be solved like this: firstly let's iterate over all $i$ from $1$ to $\\frac{n}{2}$. If characters $s_{2i-1}$ and $s_{2i}$ are the same then we obviously need to replace one of them with the other character. We can see that such replacements are enough to make the string suitable.",
    "code": "n, s = int(input()), list(input())\nans = 0\nfor i in range(0, n, 2):\n\tif (s[i] == s[i + 1]):\n\t\ts[i] = chr(1 - ord(s[i]) + 2 * ord('a'))\n\t\tans += 1\nprint(ans)\nprint(''.join(s))",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1216",
    "index": "B",
    "title": "Shooting",
    "statement": "Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed $n$ cans in a row on a table. Cans are numbered from left to right from $1$ to $n$. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose \\textbf{the order} in which he will knock the cans down.\n\nVasya knows that the durability of the $i$-th can is $a_i$. It means that if Vasya has already knocked $x$ cans down and is now about to start shooting the $i$-th one, he will need $(a_i \\cdot x + 1)$ shots to knock it down. You can assume that if Vasya starts shooting the $i$-th can, he will be shooting it until he knocks it down.\n\nYour task is to choose such an order of shooting so that the number of shots required to knock each of the $n$ given cans down exactly once is minimum possible.",
    "tutorial": "We can see that because the multiplier $x$ in the formula $(a_i \\cdot x + 1)$ is the position of the number and we want to minimize the sum of such formulas, the following greedy solution comes up to mind: because we want to count greater values as earlier as possible, let's sort the array $a$ in non-increasing order (saving initial indices of elements), calculate the answer and print the permutation of indices in order from left to right.",
    "code": "n, a = int(input()), list(map(int, input().split()))\nres = []\nans = 0\nfor i in range(n):\n\tpos = -1\n\tfor j in range(n):\n\t\tif (pos == -1 or a[j] > a[pos]): pos = j\n\tres.append(pos + 1)\n\tans += i * a[pos] + 1\n\ta[pos] = 0\nprint(ans)\nprint(' '.join([str(x) for x in res]))",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1216",
    "index": "C",
    "title": "White Sheet",
    "statement": "There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates $(0, 0)$, and coordinate axes are left and bottom sides of the table, then the bottom left corner of the white sheet has coordinates $(x_1, y_1)$, and the top right — $(x_2, y_2)$.\n\nAfter that two black sheets of paper are placed on the table. Sides of both black sheets are also parallel to the sides of the table. Coordinates of the bottom left corner of the first black sheet are $(x_3, y_3)$, and the top right — $(x_4, y_4)$. Coordinates of the bottom left corner of the second black sheet are $(x_5, y_5)$, and the top right — $(x_6, y_6)$.\n\n\\begin{center}\n{\\small Example of three rectangles.}\n\\end{center}\n\nDetermine if some part of the white sheet can be seen from the above after the two black sheets are placed. The part of the white sheet can be seen if there is at least one point lying \\textbf{not strictly inside} the white sheet and \\textbf{strictly outside} of both black sheets.",
    "tutorial": "There are at least two solution to the problem. I'll describe both of them. The first solution: firstly let's notice that the point we search can have non-integer coordinates, but if the answer exists then there will be the answer such that its point has at most half-integer coordinates. So let's multiply all coordinates by two and solve the problem with integer coordinates. The second thing is that for some $x$ there is only two points we need to check - top point with this $x$ and bottom point with this $x$. The same for some $y$. So we can iterate over all possible values of $x$ and check if the point $(x, y_1)$ lies outside of both black rectangles. The same with point $(x, y_2)$. Then do the same for points $(y, x_1)$ and $(y, x_2)$. $x$ should be in range $[x_1; x_2]$ and $y$ should be in range $[y_1; y_2]$. Time complexity is linear on size of the white rectangle. The second solution is most tricky but has the better time complexity. Let $wb_1$ be the intersection of white rectangle and the first black rectangle, $wb_2$ the same but with the second black rectangle and $inter$ be the intersection of $wb_1$ and $wb_2$. Then it is obvious that the answer exists if $wb_1$ and $wb_2$ doesn't cover the whole white rectangle ($sq(w) > sq(wb_1) + sq(wb_2) - sq(inter)$). Time complexity: $O(1)$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cstdio>\n#include <random>\n#include <ctime>\n#include <string>\n#include <iomanip>\n#include <set>\n#include <map>\n#include <queue>\n#include <stack>\n\nusing namespace std;\n\ntypedef long long li;\ntypedef unsigned long long uli;\ntypedef pair<int, int> pii;\ntypedef long double ld;\n\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n#define pb push_back\n#define forn(i, n) for(int i = 0; i < int(n); ++i)\n#define fore(i, l, r) for(int i = int(l); i < int(r); ++i)\n#define forb(i, n) for(int i = int(n) - 1; i >= 0; --i)\n#define vi vector<int>\n#define x first\n#define y second\n\nconst int INF = 2e9;\nconst li INF64 = 1e18;\nconst int M = 2 * 1000 * 1000;\nconst int N = 300 * 1000 + 100;\nconst int MOD = 1e9 + 7;\nconst double EPS = 1e-9;\nconst double PI = 3.14159265359;\n\npair<pii, pii> intersect(pii a, pii b, pii c, pii d) {\n\tint lf, rg, up, dn;\n\tlf = max(min(a.x, b.x), min(c.x, d.x));\n\trg = min(max(a.x, b.x), max(c.x, d.x));\n\tup = min(max(a.y, b.y), max(c.y, d.y));\n\tdn = max(min(a.y, b.y), min(c.y, d.y));\n\n\tif (rg <= lf || up <= dn) return { {0, 0}, {0, 0} };\n\n\treturn { { lf, dn }, { rg, up } };\n}\n\nli square(pii a, pii b) {\n\treturn 1ll * abs(a.x - b.x) * abs(a.y - b.y);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\n\tvector<pii> p(6);\n\n\tforn(i, 6)\n\t\tcin >> p[i].x >> p[i].y;\n\n\tpair<pii, pii> wb1 = intersect(p[0], p[1], p[2], p[3]);\n\tpair<pii, pii> wb2 = intersect(p[0], p[1], p[4], p[5]);\n\tpair<pii, pii> inter = intersect(wb1.x, wb1.y, wb2.x, wb2.y);\n\n\tli swhite = square(p[0], p[1]);\n\tli swb1 = square(wb1.x, wb1.y);\n\tli swb2 = square(wb2.x, wb2.y);\n\tli sinter = square(inter.x, inter.y);\n\n\tif (swhite > swb1 + swb2 - sinter) cout << \"YES\\n\";\n\telse cout << \"NO\\n\";\n}",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1216",
    "index": "D",
    "title": "Swords",
    "statement": "There were $n$ types of swords in the theater basement which had been used during the plays. Moreover there were \\textbf{exactly} $x$ swords of each type. $y$ people have broken into the theater basement and each of them has taken exactly $z$ swords of some \\textbf{single type}. Note that different people might have taken different types of swords. Note that the values $x, y$ and $z$ are unknown for you.\n\nThe next morning the director of the theater discovers the loss. He counts all swords — exactly $a_i$ swords of the $i$-th type are left untouched.\n\nThe director has no clue about the initial number of swords of each type in the basement, the number of people who have broken into the basement and how many swords each of them have taken.\n\nFor example, if $n=3$, $a = [3, 12, 6]$ then one of the possible situations is $x=12$, $y=5$ and $z=3$. Then the first three people took swords of the first type and the other two people took swords of the third type. Note that you don't know values $x, y$ and $z$ beforehand but know values of $n$ and $a$.\n\nThus he seeks for your help. Determine the \\textbf{minimum} number of people $y$, which could have broken into the theater basement, and the number of swords $z$ each of them has taken.",
    "tutorial": "Firstly, let's notice that for the fixed value of $z$ our problem is reduced to the following: we are given $n$ numbers $a_1, a_2, \\dots, a_n$. We need to choose such values $k_1, k_2, \\dots, k_n$ that $a_1 + k_1 \\cdot z = a_2 + k_2 \\cdot z = \\dots = a_n + k_n \\cdot z$. And among all such values $k_1, k_2, \\dots, k_n$ we need to choose values in a way to minimize $\\sum\\limits_{i=1}^{n}k_i$. And the sum of $k_i$ is $y$! Of course, for the fixed value $z$ the minimum sum of $k_i$ can be only one. Let's start with $z=1$. It is obvious that if the maximum value in the array $a$ is $mx$ the value $k_i$ equals $mx - a_i$ (for $z=1$). Assume that each $k_i$ from $1$ to $n$ has some divisor $d$. Then if we multiply $z$ by $d$ and divide each $k_i$ by $d$ the answer will only become better. How to calculate this value of $z$ fast? We can see that this value equals to $gcd(k_1, k_2, \\dots, k_n)$! And it can be proven that this value of $z$ is always optimal and we can easily determine $y$ for such $z$. Time complexity: $O(n + \\log max(a_i))$.",
    "code": "#include <iostream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n#include <cmath>\n#include <queue>\n#include <string>\n#include <cstring>\n#include <cassert>\n#include <iomanip>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <ctime>\n#include <cmath>\n\n#define forn(i, n) for(int i=0;i<n;++i)\n#define fore(i, l, r) for(int i = int(l); i <= int(r); ++i)\n#define sz(v) int(v.size())\n#define all(v) v.begin(), v.end()\n#define pb push_back\n#define mp make_pair\n#define x first\n#define y1 ________y1\n#define y second\n#define ft first\n#define sc second\n#define pt pair<int, int>\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntypedef long long li;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int INF = 1000 * 1000 * 1000;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n\nconst int N = 200 * 1000 + 13;\n\nint n;\nint a[N];\n\ninline void read() {\t\n\tcin >> n;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n}\n\ninline int gcd(int a, int b) {\n\twhile (a != 0 && b != 0) {\n\t\tif (a > b) {\n\t\t\ta %= b;\n\t\t} else {\n\t\t\tb %= a;\n\t\t}\n\t}\n\treturn max(a, b);\n}\n\ninline void solve() {\n\tint ma = *max_element(a, a + n);\n    li sum = 0;\n    for (int i = 0; i < n; i++) {\n    \tsum += a[i];\n    }\n    int g = ma - a[0];\n    for (int i = 1; i < n; i++) {\n    \tg = gcd(g, ma - a[i]);\n    }    \n    li ans = (ma * 1ll * n - sum) / g;\n    cout << ans << ' ' << g << endl;\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    srand(time(NULL));\n    cerr << setprecision(10) << fixed;\n    \n    read();\n    solve();\n \n    //cerr << \"TIME: \" << clock() << endl;\n}",
    "tags": [
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1216",
    "index": "E1",
    "title": "Numerical Sequence (easy version)",
    "statement": "\\textbf{The only difference between the easy and the hard versions is the maximum value of $k$}.\n\nYou are given an infinite sequence of form \"112123123412345$\\dots$\" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the second one — from $1$ to $2$, the third one — from $1$ to $3$, $\\dots$, the $i$-th block consists of all numbers from $1$ to $i$.\n\nSo the first $56$ elements of the sequence are \"11212312341234512345612345671234567812345678912345678910\". Elements of the sequence are numbered from one. For example, the $1$-st element of the sequence is $1$, the $3$-rd element of the sequence is $2$, the $20$-th element of the sequence is $5$, the $38$-th element is $2$, the $56$-th element of the sequence is $0$.\n\nYour task is to answer $q$ independent queries. In the $i$-th query you are given one integer $k_i$. Calculate the digit at the position $k_i$ of the sequence.",
    "tutorial": "Let's take a look on the upper bound of the number $n$, where $n$ is the maximum possible number of block which can be asked. If we assume that each number has length $1$ then the sum of lengths will be equal to $1 + 2 + \\dots + n$. And as we know this value equals $\\frac{n(n+1)}{2}$. So the maximum value of $n$ is not greater than $O(\\sqrt{k})$. Now we can just iterate over all $i$ from $1$ to $n$ (where $n$ is no more than $5 \\cdot 10^4$) and carry the length of the last block. If this length is greater than or equal to $k$ ($0$-indexed) then let's decrease $k$ by this length, increase the length of the last block and continue. Otherwise our answer lies in the current block. So then let's iterate over all $j$ from $1$ to $i$ and if the decimal length of $j$ is greater than or equal to $k$ then decrease $k$ by this length otherwise our answer lies in the current number $j$ and we just need to print $j_k$ ($0$-indexed). Time complexity: $O(\\sqrt{k})$ per query.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\t\n\twhile (q--) {\n\t\tlong long k;\n\t\tcin >> k;\n\t\t--k;\n\t\tlong long lst = 0;\n\t\tlong long nxtpw = 1;\n\t\tint numlen = 0;\n\t\tfor (long long i = 1; ; ++i) {\n\t\t\tif (i == nxtpw) {\n\t\t\t\t++numlen;\n\t\t\t\tnxtpw *= 10;\n\t\t\t}\n\t\t\tlst += numlen;\n\t\t\tif (k >= lst) {\n\t\t\t\tk -= lst;\n\t\t\t} else {\n\t\t\t\tlong long nxtpw = 1;\n\t\t\t\tint numlen = 0;\n\t\t\t\tfor (long long j = 1; j <= i; ++j) {\n\t\t\t\t\tif (j == nxtpw) {\n\t\t\t\t\t\t++numlen;\n\t\t\t\t\t\tnxtpw *= 10;\n\t\t\t\t\t}\n\t\t\t\t\tif (k >= numlen) {\n\t\t\t\t\t\tk -= numlen;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcout << to_string(j)[k] << endl;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1216",
    "index": "E2",
    "title": "Numerical Sequence (hard version)",
    "statement": "\\textbf{The only difference between the easy and the hard versions is the maximum value of $k$}.\n\nYou are given an infinite sequence of form \"112123123412345$\\dots$\" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the second one — from $1$ to $2$, the third one — from $1$ to $3$, $\\dots$, the $i$-th block consists of all numbers from $1$ to $i$.\n\nSo the first $56$ elements of the sequence are \"11212312341234512345612345671234567812345678912345678910\". Elements of the sequence are numbered from one. For example, the $1$-st element of the sequence is $1$, the $3$-rd element of the sequence is $2$, the $20$-th element of the sequence is $5$, the $38$-th element is $2$, the $56$-th element of the sequence is $0$.\n\nYour task is to answer $q$ independent queries. In the $i$-th query you are given one integer $k_i$. Calculate the digit at the position $k_i$ of the sequence.",
    "tutorial": "This problem idea is not very hard. Now $n$ can be up to $10^9$ so we need to find the number of block $i$ faster. Let's do binary search on it! Now using some shitty pretty formulas we can determine if the total sum of lengths of blocks from $1$ to $i$ is greater than or equal to $k$ or not. And more about these formulas: let's iterate over all possible length of numbers from $1$ to $len(i)$ and carry the sum of lengths $add$ of numbers with length less than the current length $l$. We know that the number of numbers (he-he) of length $l$ is exactly $cnt = 10^{l+1}-10^l$ ($cnt = i - 10^l + 1$ for $l=len(i)$). Let's add $add \\cdot cnt + \\frac{cnt(cnt+1)}{2} \\cdot cnt$ to the total sum of lengths and increase $add$ by $cnt \\cdot len$. What does $add \\cdot cnt$ means? This formula means that we have exactly $cnt$ blocks ending with numbers of length $l$ and we need to add sum of lengths of all numbers with length less than $l$ exactly $cnt$ times. And what does $\\frac{cnt(cnt+1)}{2} \\cdot cnt$ means? It is the sum sums of lengths of all numbers of length $l$ (i.e. previously we added sum of lengths of numbers with length less than $l$ and now we add sum of sums of lengths of numbers with length $l$). When we found the number of block $i$, let's decrease $k$ by the total length of all blocks from $1$ to $i-1$ and continue solving the problem. This part was pretty hard to understand. And the easiest part: when we determined the number of block $i$ we can easily determine the number $j$ from $1$ to $i$ such that our answer lies in the number $j$. Let's iterate over all lengths from $1$ to $len(i)$ (here we go again) and for the current length $l$ let $cnt = 10^{l+1}-10^l$ ($cnt = j - 10^l + 1$ for $l=len(j)$). And now all we need is to increase the sum of lengths by $cnt \\cdot len$. After determining $j$ decrease $k$ by sum of lengths of numbers from $1$ to $j-1$ and print $j_k$. Time complexity: $O(\\log^2{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long get(long long r) {\n\treturn (r + 1) * r / 2;\n}\n\nlong long sumto(long long r, int need) {\n\tlong long pw = 1;\n\tlong long sum = 0;\n\tlong long add = 0;\n\tfor (int len = 1; ; ++len) {\n\t\tif (pw * 10 - 1 < r) {\n\t\t\tlong long cnt = pw * 10 - pw;\n\t\t\tif (need) {\n\t\t\t\tsum += add * cnt + get(cnt) * len;\n\t\t\t\tadd += cnt * len;\n\t\t\t} else {\n\t\t\t\tsum += cnt * len;\n\t\t\t}\n\t\t} else {\n\t\t\tlong long cnt = r - pw + 1;\n\t\t\tif (need) {\n\t\t\t\tsum += add * cnt + get(cnt) * len;\n\t\t\t} else {\n\t\t\t\tsum += cnt * len;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tpw *= 10;\n\t}\n\treturn sum;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tlong long k;\n\t\tcin >> k;\n\t\t--k;\n\t\t\n\t\tlong long l = 1\t, r = 1e9;\n\t\tlong long res = -1;\n\t\twhile (r - l >= 0) {\n\t\t\tlong long mid = (l + r) >> 1;\n\t\t\tif (sumto(mid, 1) > k) {\n\t\t\t\tres = mid;\n\t\t\t\tr = mid - 1;\n\t\t\t} else {\n\t\t\t\tl = mid + 1;\n\t\t\t}\n\t\t}\n\t\tk -= sumto(res - 1, 1);\n\t\t\n\t\tl = 1, r = res;\n\t\tlong long num = -1;\n\t\twhile (r - l >= 0) {\n\t\t\tint mid = (l + r) >> 1;\n\t\t\tif (sumto(mid, 0) > k) {\n\t\t\t\tnum = mid;\n\t\t\t\tr = mid - 1;\n\t\t\t} else {\n\t\t\t\tl = mid + 1;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcout << to_string(num)[k - sumto(num - 1, 0)] << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1216",
    "index": "F",
    "title": "Wi-Fi",
    "statement": "You work as a system administrator in a dormitory, which has $n$ rooms one after another along a straight hallway. Rooms are numbered from $1$ to $n$.\n\nYou have to connect all $n$ rooms to the Internet.\n\nYou can connect each room to the Internet directly, the cost of such connection for the $i$-th room is $i$ coins.\n\nSome rooms also have a spot for a router. The cost of placing a router in the $i$-th room is also $i$ coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room $i$, you connect all rooms with the numbers from $max(1,~i - k)$ to $min(n,~i + k)$ inclusive to the Internet, where $k$ is the range of router. The value of $k$ is the same for all routers.\n\nCalculate the minimum total cost of connecting all $n$ rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have.",
    "tutorial": "Firstly, I know that this problem has very pretty linear solution and its author can describe it if he wants. I'll describe my own solution without any data structures but std::set. Let $dp_i$ be the total cost to connect all rooms from $i$ to $n-1$ to the Internet ($0$-indexed). Initially $dp_{n} = 0$, all other values are $+\\infty$. Let's iterate over all $i$ from $n-1$ to $0$ and make some transitions. After all the answer will be $dp_0$. The first transition is the easier: update $dp_i$ with $dp_{i + 1} + i + 1$ (just connect the current room directly). To do other transitions, let's carry two sets $mins$ and $vals$ and one array of vectors $del$ of length $n$. Set $mins$ carries all values $dp_{i + 1}, dp_{i + 2}, \\dots, dp_{i + k + 1}$. Initially it carries $dp_n = 0$. Set $vals$ carries the minimum cost to cover some suffix of rooms that also covers the room $i$. Array of vectors $rem$ helps us to carry the set $vals$ efficiently. First of all, if $i + k + 2 \\le n$ then let's remove $dp_{i + k + 2}$ from $mins$. Then let's remove all values of $del_i$ from $vals$. Then if $vals$ is not empty, let's update $dp_i$ with the minimum value of $vals$. Then if $s_i =$ '1' then let $val$ be the minimum value of $mins$ plus $i + 1$. Update $dp_i$ with $val$ and insert $val$ into $vals$. Also let's add $val$ into $del_{i - k - 1}$ if $i - k - 1 \\ge 0$. And after we make all we need with the current $i$, add the value $dp_i$ to the set $mins$. Time complexity: $O(n \\log n)$. It can be optimized to $O(n)$ solution with some advanced data structures as a queue with minimums.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tstring s;\n\tcin >> s;\n\n\tvector<long long> dp(n + 1);\n\tmultiset<long long> mins, vals;\n\tmins.insert(0);\n\tvector<vector<long long>> del(n);\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tdp[i] = i + 1 +  dp[i + 1];\n\t\tif (i + k + 2 <= n) mins.erase(mins.find(dp[i + k + 2]));\n\t\tfor (auto it : del[i]) vals.erase(vals.find(it));\n\t\tif (!vals.empty()) dp[i] = min(dp[i], *vals.begin());\n\t\tif (s[i] == '1') {\n\t\t\tlong long val = (mins.empty() ? 0 : *mins.begin()) + i + 1;\n\t\t\tdp[i] = min(dp[i], val);\n\t\t\tvals.insert(val);\n\t\t\tif (i - k - 1 >= 0) del[i - k - 1].push_back(val);\n\t\t}\n\t\tmins.insert(dp[i]);\n\t}\n\t\n\tcout << dp[0] << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1217",
    "index": "A",
    "title": "Creating a Character",
    "statement": "You play your favourite game yet another time. You chose the character you didn't play before. It has $str$ points of strength and $int$ points of intelligence. Also, at start, the character has $exp$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $1$ or raise intelligence by $1$).\n\nSince you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is \\textbf{strictly greater} than the resulting intelligence).\n\nCalculate the number of different character builds you can create (for the purpose of replayability) if you must \\textbf{invest all free points}. Two character builds are different if their strength and/or intellect are different.",
    "tutorial": "Let $addS$ and $addI$ be number of free points that we invest in the strength and intelligence respectively. It's obvious that $addS + addI = exp$ since we must spend all free points. From the other side we must make $str + addS > int + addI$. Now we can expess $addI = exp - addS$ and put it in the inequality: $str + addS > int + (exp - addS)$ $2addS > exp + int - str$ $2addS \\ge exp + int - str + 1$ $addS \\ge \\left \\lceil \\frac{exp + int - str + 1}{2} \\right \\rceil$ Since $addS$ must be non negative we can get $addS \\ge \\max(0, \\left \\lceil \\frac{exp + int - str + 1}{2} \\right \\rceil)$ We can use or write the correct ceiling function that works with negative numerator or use one hack and magic and get $addS \\ge \\max(0, \\frac{exp + int - str + 2}{2})$ Since all integer values $addS$ from $[minAddS, exp]$ are good for us, so the number of pairs is equal to $\\max(0, exp - minAddS + 1)$. P.S.: Let me explain how to prove that $k \\cdot x > y$ is equal to $x \\ge \\left \\lfloor \\frac{y + k}{k} \\right \\rfloor$. $k \\cdot x > y \\Leftrightarrow k \\cdot x \\ge y + 1 \\Leftrightarrow x \\ge \\left \\lceil \\frac{y + 1}{k} \\right \\rceil \\Leftrightarrow x \\ge \\left \\lfloor \\frac{y + 1 + k - 1}{k} \\right \\rfloor \\Leftrightarrow x \\ge \\left \\lfloor \\frac{y + k}{k} \\right \\rfloor$ P.P.S.: Interesting fact: the formula above works for all positive $k$ and $y \\in [-k, +\\infty)$ thats why it works in our case even though $exp + int - str$ can be negative.",
    "code": "fun main() {\n    val t = readLine()!!.toInt()\n    for (ct in 1..t) {\n        val (str, int, exp) = readLine()!!.split(' ').map { it.toInt() }\n        val minAddStr = maxOf(0, (exp + int - str + 2) / 2)\n        println(maxOf(exp - minAddStr + 1, 0))\n    }\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1217",
    "index": "B",
    "title": "Zmei Gorynich",
    "statement": "You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!\n\nInitially Zmei Gorynich has $x$ heads. You can deal $n$ types of blows. If you deal a blow of the $i$-th type, you decrease the number of Gorynich's heads by $min(d_i, curX)$, there $curX$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $h_i$ new heads. If $curX = 0$ then Gorynich is defeated.\n\n\\textbf{You can deal each blow any number of times, in any order.}\n\nFor example, if $curX = 10$, $d = 7$, $h = 10$ then the number of heads changes to $13$ (you cut $7$ heads off, but then Zmei grows $10$ new ones), but if $curX = 10$, $d = 11$, $h = 100$ then number of heads changes to $0$ and Zmei Gorynich is considered defeated.\n\nCalculate the minimum number of blows to defeat Zmei Gorynich!\n\nYou have to answer $t$ independent queries.",
    "tutorial": "Lets divide all dealing blows into two parts: the last blow and others blows. The last hit should be with maximum value of $d$. The others blows should be with the maximum value of $d - h$. So, lets denote $\\max\\limits_{1 \\le i \\le n} d_i$ as $maxD$ and $\\max\\limits_{1 \\le i \\le n} (d_i - h_i)$ as $maxDH$. Then if $x \\le maxD$ the we can beat Zmei Gorynich with one blow. Otherwise, if $maxDH \\le 0$, then we cannot defeat Zmei Gorynich. Otherwise (if $x > maxD$ and $maxDH > 0$) the answer is $\\lceil \\frac{x - maxD}{maxDH} \\rceil$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 105;\n\nint t;\nint n, m;\nint d[N], h[N];\n\nint main() {\n\tcin >> t;\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tcin >> n >> m;\n\t\tint maxDH = -2e9;\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tcin >> d[i] >> h[i];\n\t\t\tmaxDH = max(maxDH, d[i] - h[i]);\n\t\t}\n\n\t\tint res = 1;\t\n\t\tint maxD = *max_element(d, d + n);\n\t\tm -= maxD;\n\t\tif(m > 0){\n\t\t\tif(maxDH <= 0) res = -1;\n\t\t\telse res += (m + maxDH - 1) / maxDH; \t\n\t\t}\t\n\t\tcout << res << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1217",
    "index": "C",
    "title": "The Number Of Good Substrings",
    "statement": "You are given a binary string $s$ (recall that a string is binary if each character is either $0$ or $1$).\n\nLet $f(t)$ be the decimal representation of integer $t$ written in binary form (possibly with leading zeroes). For example $f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$ and $f(000100) = 4$.\n\nThe substring $s_{l}, s_{l+1}, \\dots , s_{r}$ is good if $r - l + 1 = f(s_l \\dots s_r)$.\n\nFor example string $s = 1011$ has $5$ good substrings: $s_1 \\dots s_1 = 1$, $s_3 \\dots s_3 = 1$, $s_4 \\dots s_4 = 1$, $s_1 \\dots s_2 = 10$ and $s_2 \\dots s_4 = 011$.\n\nYour task is to calculate the number of good substrings of string $s$.\n\nYou have to answer $t$ independent queries.",
    "tutorial": "At first, lets precalc the array $nxt_1, nxt_2, \\dots , nxt_n$. The value of $nxt_i$ if equal the maximum position $j$ in range $1 \\dots i$ such that $s_j = 1$. After that lets iterate over the right boundary of substring and high $1$-bit position (denote it as $r$ and $l$ respectively). Note that if $r - l > 18$ then $f(l, r) > 2 \\cdot 10^5$. So we iterate over such pair $(l, r)$ that $1 \\le l \\le r \\le n$ and $r - l \\le 18$. Lets look at value $f(l, r)$. If $f(l, r) > r - l + 1$, then we have to increase the length of substring without increasing the value of $f(l, r)$. So we need to check if there exists a position $nl$ such that $f(nl, r) = f(l, r)$ and $r - nl + 1 = f(nl, r)$. This position exists if the condition $f(l, r) \\le r - nxt_{l - 1}$ is met ($nxt_0$ is equal to -1).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\n\nint t;\nstring s;\nint nxt[N];\n\nint main() {\n\tcin >> t;\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tcin >> s;\n\t\tfor(int i = 0; i < s.size(); ++i)\n\t\t\tif(s[i] == '1') nxt[i] = i;\n\t\t\telse nxt[i] = (i == 0? -1 : nxt[i - 1]);\t\t\n\t\tint res = 0;\n\t\tfor(int r = 0; r < s.size(); ++r){\n\t\t\tint sum = 0;\n\t\t\tfor(int l = r; l >= 0 && r - l < 20; --l){\n\t\t\t\tif(s[l] == '0') continue;\n\t\t\t\tsum += 1 << (r - l);\n\t\t\t\tif(sum <= r - (l == 0? -1 : nxt[l - 1]))\n\t\t\t\t\t++res;\n\t\t\t}\n\t\t}\n\t\tcout << res << endl;\n\t}\t\n\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1217",
    "index": "D",
    "title": "Coloring Edges",
    "statement": "You are given a directed graph with $n$ vertices and $m$ directed edges without self-loops or multiple edges.\n\nLet's denote the $k$-coloring of a digraph as following: you color each edge in one of $k$ colors. The $k$-coloring is \\textbf{good} if and only if there no cycle formed by edges of same color.\n\nFind a good $k$-coloring of given digraph with minimum possible $k$.",
    "tutorial": "Let's run dfs on the graph and color all \"back edges\" ($(u, v)$ is back edge if there is a path from $v$ to $u$ by edges from dfs tree) in black and all other edges in white. It can be proven that any cycle will have at least one white edge and at least black edge. Moreover each back edge connected with at least one cycle (path from $v$ to $u$ and $(u, v)$ back edge). So the coloring we got is exactly the answer. How to prove that any cycle have at least one edge of both colors? Let's look only at edges from dfs trees. We can always renumerate vertices in such way that index of parent $id(p)$ is bigger than the index of any its child $id(c)$. We can process and assign $id(p)$ with minimal free number after we processed all its children. Now we can note that for any white edge $(u, v)$ (not only tree edge) condition $id(u) > id(v)$ holds (because of properties of dfs: forward edges are obvious; cross edge $(u, v)$ becomes cross because dfs at first processed vertex $v$ and $u$ after that, so $id(v) < id(u)$). And for each back edge $(u, v)$ it's true that $id(u) < id(v)$. Since any cycle have both $id(u) > id(v)$ and $id(u) < id(v)$ situations, profit!",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(1e6) + 55;\n\nint n, m;\nvector <pair<int, int> > g[N];\nint col[N];\nbool cyc;\nint res[N];\n\nvoid dfs(int v){\n\tcol[v] = 1;\n\tfor(auto p : g[v]){\n\t\tint to = p.first, id = p.second;\n\t\tif(col[to] == 0){\n\t\t\tdfs(to);\n\t\t\tres[id] = 1;\n\t\t}\n\t\telse if(col[to] == 2)\n\t\t\tres[id] = 1;\n\t\telse{\n\t\t\tres[id] = 2;\n\t\t\tcyc = true;\n\t\t}\n\t}\n\tcol[v] = 2;\n}\n\nint main(){\n\tcin >> n >> m;\n\tfor(int i = 0; i < m; ++i){\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\t--u, --v;\n\t\tg[u].push_back(make_pair(v, i));\n\t}\n\t\n\tfor(int i = 0; i < n; ++i)\n\t\t\tif(col[i] == 0)\n\t\t\t\tdfs(i);\n\t\t\t\n\tcout << (cyc? 2 : 1) << endl;\n\tfor(int i = 0; i < m; ++i) cout << res[i] << ' ';\n\tcout << endl;\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1217",
    "index": "E",
    "title": "Sum Queries?",
    "statement": "Let's define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that holds for every position, then the multiset is balanced. Otherwise it's unbalanced.\n\nFor example, multiset $\\{20, 300, 10001\\}$ is balanced and multiset $\\{20, 310, 10001\\}$ is unbalanced:\n\nThe red digits mark the elements and the positions for which these elements have the same digit as the sum. The sum of the first multiset is $10321$, every position has the digit required. The sum of the second multiset is $10331$ and the second-to-last digit doesn't appear in any number, thus making the multiset unbalanced.\n\nYou are given an array $a_1, a_2, \\dots, a_n$, consisting of $n$ integers.\n\nYou are asked to perform some queries on it. The queries can be of two types:\n\n- $1~i~x$ — replace $a_i$ with the value $x$;\n- $2~l~r$ — find the \\textbf{unbalanced} subset of the multiset of the numbers $a_l, a_{l + 1}, \\dots, a_r$ with the minimum sum, or report that no unbalanced subset exists.\n\nNote that the empty multiset is balanced.\n\nFor each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.",
    "tutorial": "We are given the definition of the balanced multiset but let's instead fix the criteria to determine if the multiset is unbalanced. Take an empty multiset and start adding numbers to it until it becomes unbalanced. Empty set to the set of one number is trivial. Now for the second number. If there is some position such that both numbers have non-zero digits in it, then the multiset becomes unbalanced (let these be non-zero digits $d_1$ and $d_2$, then $d_1 + d_2$ can be neither $d_1$, nor $d_2$). After that let's prove that you can never make an unbalanced multiset balanced again by adding numbers to it. Let there be such multisets $a$ and $b$ such $a$ is unbalanced, $b$ is balanced and $a \\subset b$. Take a look at the lowest position which has non-zero digits in several numbers from $b$. The sum of these digits should be equal to at least one of them modulo $10$ (to satisfy the condition of balance). That can only mean their sum is greater or equal to $10$, thus is make a carry to the next position. The sum of digits on the next position plus carry should also be equal to some digit of them, thus pushing some other carry value to the next one. And so on until the carry makes it to the position greater than any position in any of the numbers. But the carry is non-zero and there is no number with any non-zero digit in this position. That makes our assumption incorrect. After all, it implies that any unbalanced multiset of size greater than two has an unbalanced multiset of size two. The problem now got reduced to: find a pair of numbers $a_i$ and $a_j$ such that $l \\le i < j \\le r$, there is at least one position such that both $a_i$ and $a_j$ have non-zero digits on it and $a_i + a_j$ is minimal possible. That can be easily maintained in a segment tree. Let a node corresponding to the interval $[l; r)$ keep the best answer on an interval (the sum of such a pair) and an array $min\\_by\\_digit[i]$ - the smallest number on an interval $[l; r)$ which has a non-zero digit at position $i$ or $\\infty$ if none exists. The update is easy. Iterate over the digits of a new number and update the values in the array $min\\_by\\_digit$ in the corresponding nodes. The merge is done the following way: push the best answers from children to the parent and then iterate over the positions and try to combine the smallest numbers at each one from the left child and the right child. Idea-wise this is the same as storing a segtree and calculating the answer by each position separately. However, these approaches differ by a huge constant factor performance-wise. The former one accesses the memory in a much more cache-friendly way. You might want to take that as a general advice on implementing multiple segtrees. Overall complexity: $O((n + m) \\cdot \\log n \\cdot \\log_{10} MAXN)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\nconst int INF = 2e9;\nconst int LOGN = 9;\n\nstruct node{\n\tint best;\n\tint mn[LOGN];\n\tnode(){\n\t\tbest = INF;\n\t\tforn(i, LOGN)\n\t\t\tmn[i] = INF;\n\t}\n\tint& operator [](int x){\n\t\treturn mn[x];\n\t}\n};\n\nint a[N];\nnode t[4 * N];\n\nvoid upd(node &t, int val){\n\tint x = val;\n\tforn(i, LOGN){\n\t\tif (x % 10 != 0)\n\t\t\tt[i] = min(t[i], val);\n\t\tx /= 10;\n\t}\n}\n\nnode merge(node &a, node &b){\n\tnode c;\n\tc.best = min(a.best, b.best);\n\tforn(i, LOGN){\n\t\tc[i] = min(a[i], b[i]);\n\t\tif (a[i] < INF && b[i] < INF)\n\t\t\tc.best = min(c.best, a[i] + b[i]);\n\t}\n\treturn c;\n}\n\nvoid build(int v, int l, int r){\n\tif (l == r - 1){\n\t\tt[v] = node();\n\t\tupd(t[v], a[l]);\n\t\treturn;\n\t}\n\tint m = (l + r) / 2;\n\tbuild(v * 2, l, m);\n\tbuild(v * 2 + 1, m, r);\n\tt[v] = merge(t[v * 2], t[v * 2 + 1]);\n}\n\nvoid upd(int v, int l, int r, int pos, int val){\n\tif (l == r - 1){\n\t\tt[v] = node();\n\t\tupd(t[v], val);\n\t\treturn;\n\t}\n\tint m = (l + r) / 2;\n\tif (pos < m)\n\t\tupd(v * 2, l, m, pos, val);\n\telse\n\t\tupd(v * 2 + 1, m, r, pos, val);\n\tt[v] = merge(t[v * 2], t[v * 2 + 1]);\n}\n\nnode get(int v, int l, int r, int L, int R){\n\tif (l == L && r == R)\n\t\treturn t[v];\n\tint m = (l + r) / 2;\n\tif (R <= m)\n\t\treturn get(v * 2, l, m, L, R);\n\tif (L >= m)\n\t\treturn get(v * 2 + 1, m, r, L, R);\n\tnode ln = get(v * 2, l, m, L, m);\n\tnode rn = get(v * 2 + 1, m, r, m, R);\n\treturn merge(ln, rn);\n}\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\tbuild(1, 0, n);\n\tforn(i, m){\n\t\tint t, x, y;\n\t\tscanf(\"%d%d%d\", &t, &x, &y);\n\t\t--x;\n\t\tif (t == 1)\n\t\t\tupd(1, 0, n, x, y);\n\t\telse{\n\t\t\tnode res = get(1, 0, n, x, y);\n\t\t\tprintf(\"%d\\n\", res.best == INF ? -1 : res.best);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1217",
    "index": "F",
    "title": "Forced Online Queries Problem",
    "statement": "You are given an undirected graph with $n$ vertices numbered from $1$ to $n$. Initially there are no edges.\n\nYou are asked to perform some queries on the graph. Let $last$ be the answer to the latest query of the second type, it is set to $0$ before the first such query. Then the queries are the following:\n\n- $1~x~y$ ($1 \\le x, y \\le n$, $x \\ne y$) — add an undirected edge between the vertices $(x + last - 1)~mod~n + 1$ and $(y + last - 1)~mod~n + 1$ if it doesn't exist yet, otherwise remove it;\n- $2~x~y$ ($1 \\le x, y \\le n$, $x \\ne y$) — check if there exists a path between the vertices $(x + last - 1)~mod~n + 1$ and $(y + last - 1)~mod~n + 1$, which goes only through currently existing edges, and set $last$ to $1$ if so and $0$ otherwise.\n\nGood luck!",
    "tutorial": "The problem directly tells you do solve some kind of Dynamic Connectivity Problem. You could use the online approach with Link-Cut Tree if you'd had its implementation beforehand. There is also a nice modification to the $log^2$ solution of the offline version of DCP (check out the comment). I'd tell the solution which is probably the easiest to come up with and to code. Let's recall the sqrt-optimization method of solving DCP. Process blocks of queries of size $P$ one at a time. Split the edges into two groups: The edges which were added on queries before the block and aren't touched by the queries in the block; the edges modified by the queries in the block. The first type of edges can be added to the graph before the block processing starts. You can use DSU for that. The second type contains no more than $P$ edges. Maintain the list of those of them which exist in the graph. On each ask query add them to graph, then delete them. This can be done explicitly by doing DFS only over these edges and the vertices which correspond to the connected components on the edges of the first type. Implicitly doing DSU merges for these edges and rolling them back is a viable option as well (costs extra log factor but has lower constant). It's easy to see that it isn't hard to modify this solution to our problem. Let's define the edges of the first type more generally: the edges which were added on queries before the block and could not be touched by the queries in the block. So neither $(v, u)$ from the add query, nor $(v~mod~n + 1, u~mod~n + 1)$ could be of the first type. Now there might be $2P$ edges of the second type in the list. However, that doesn't make the complexity any worse. Process block the same way, rebuild the DSU with the edges of the first type every $P$ queries. The overall complexity can be $O((n + m) \\sqrt{m})$ if you use DFS or $O((n + m) \\sqrt{m \\log n})$ if you use DSU (notice how the rebuild is $P \\cdot O(n + m)$ and the query is $m \\cdot O(\\frac{m}{P} \\cdot \\log n)$ and set the size of the block so that these parts are about the same).",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int BUF = 10 * 1000 * 1000 + 13;\nconst int N = 300 * 1000 + 13;\nconst int M = 300 * 1000 + 13;\nconst int P = 400;\n\nstruct query{\n\tint t, x, y;\n\tint e0, e1;\n};\n\nint n, m;\nquery q[M];\n\nint p[N], rk[N];\n\nint cnt;\nint* where[BUF];\nint val[BUF];\n\nvoid rollback(){\n\twhile (cnt > 0){\n\t\t*where[cnt - 1] = val[cnt - 1];\n\t\t--cnt;\n\t}\n}\n\nint getp(int a){\n\treturn (a == p[a] ? a : getp(p[a]));\n}\n\nvoid unite(int a, int b){\n\ta = getp(a), b = getp(b);\n\tif (a == b) return;\n\tif (rk[a] < rk[b]) swap(a, b);\n\twhere[cnt] = &rk[a];\n\tval[cnt++] = rk[a];\n\twhere[cnt] = &p[b];\n\tval[cnt++] = p[b];\n\tassert(cnt <= BUF);\n\trk[a] += rk[b];\n\tp[b] = a;\n}\n\nint getpFast(int a){\n\treturn (a == p[a] ? a : p[a] = getpFast(p[a]));\n}\n\nvoid uniteFast(int a, int b){\n\ta = getpFast(a), b = getpFast(b);\n\tif (a == b) return;\n\tif (rk[a] < rk[b]) swap(a, b);\n\trk[a] += rk[b];\n\tp[b] = a;\n}\n\nstruct edge{\n\tint v, u;\n};\n\nbool operator <(const edge &a, const edge &b){\n\tif (a.v != b.v)\n\t\treturn a.v < b.v;\n\treturn a.u < b.u;\n}\n\nedge edges[2 * M];\nmap<edge, int> rev;\n\nbool used[2 * M];\nbool state[2 * M];\nint ans[M];\nvector<int> cur;\n\nvoid rebuild(int l){\n\tint r = min(m, l + P);\n\tforn(i, n) p[i] = i, rk[i] = 1;\n\tmemset(used, 0, sizeof(used));\n\tmemset(state, 0, sizeof(state));\n\n\tforn(i, l) if (q[i].t == 1){\n\t\tint e = (ans[i] ? q[i].e1 : q[i].e0);\n\t\tused[e] = true;\n\t\tstate[e] ^= 1;\n\t}\n\t\n\tfor (int i = l; i < r; ++i) if (q[i].t == 1)\n\t\tused[q[i].e0] = used[q[i].e1] = false;\n\t\n\tcur.clear();\n\tcnt = 0;\n\tforn(i, l) if (q[i].t == 1){\n\t\tint e = (ans[i] ? q[i].e1 : q[i].e0);\n\t\tif (used[e] && state[e]){\n\t\t\tstate[e] = false;\n\t\t\tuniteFast(edges[e].v, edges[e].u);\n\t\t}\n\t\telse if (!used[e] && state[e]){\n\t\t\tstate[e] = false;\n\t\t\tcur.push_back(e);\n\t\t}\n\t}\n}\n\nint get_edge(edge e){\n\tif (!rev.count(e)){\n\t\tint k = rev.size();\n\t\tedges[k] = e;\n\t\trev[e] = k;\n\t}\n\treturn rev[e];\n}\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tforn(i, m){\n\t\tscanf(\"%d%d%d\", &q[i].t, &q[i].x, &q[i].y);\n\t\t--q[i].x, --q[i].y;\n\t\tif (q[i].t == 1){\n\t\t\tedge e({q[i].x, q[i].y});\n\t\t\tif (e.v > e.u) swap(e.v, e.u);\n\t\t\tq[i].e0 = get_edge(e);\n\t\t\te.v = (e.v + 1) % n, e.u = (e.u + 1) % n;\n\t\t\tif (e.v > e.u) swap(e.v, e.u);\n\t\t\tq[i].e1 = get_edge(e);\n\t\t}\n\t}\n\t\n\tstring res = \"\";\n\tans[0] = 0;\n\tforn(i, m){\n\t\tif (i % P == 0)\n\t\t\trebuild(i);\n\t\t\n\t\tint x = (q[i].x + ans[i]) % n;\n\t\tint y = (q[i].y + ans[i]) % n;\n\t\tif (x > y) swap(x, y);\n\t\t\n\t\tif (q[i].t == 1){\n\t\t\trollback();\n\t\t\tint e = get_edge({x, y});\n\t\t\tauto it = find(cur.begin(), cur.end(), e);\n\t\t\tif (it == cur.end())\n\t\t\t\tcur.push_back(e);\n\t\t\telse\n\t\t\t\tcur.erase(it);\n\t\t\tans[i + 1] = ans[i];\n\t\t}\n\t\telse{\n\t\t\tfor (auto e : cur)\n\t\t\t\tunite(edges[e].v, edges[e].u);\n\t\t\tbool rc = (getp(x) == getp(y));\n\t\t\tans[i + 1] = rc;\n\t\t\tres += ('0' + rc);\n\t\t}\n\t}\n\t\n\tputs(res.c_str());\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1220",
    "index": "A",
    "title": "Cards",
    "statement": "When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.",
    "tutorial": "It's easy to see that letter $\\text{z}$ contains only in $\\text{zero}$ and $\\text{n}$ contains only in $\\text{one}$, so we should print $1$ $count(\\text{n})$ times and then $0$ $count(\\text{z})$ times.",
    "tags": [
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1220",
    "index": "B",
    "title": "Multiplication Table",
    "statement": "Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $M$ with $n$ rows and $n$ columns such that $M_{ij}=a_i \\cdot a_j$ where $a_1, \\dots, a_n$ is some sequence of positive integers.\n\nOf course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $a_1, \\dots, a_n$. Help Sasha restore the array!",
    "tutorial": "Let's note that $\\frac{(xy) \\cdot (xz)}{(yz)} = x^2$ if $x, y, z > 0$. In this problem $n \\ge 3$, so we can get each value this way.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1220",
    "index": "C",
    "title": "Substring Game in the Lesson",
    "statement": "Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $s$ and a number $k$ ($0 \\le k < |s|$).\n\nAt the beginning of the game, players are given a substring of $s$ with left border $l$ and right border $r$, both equal to $k$ (i.e. initially $l=r=k$). Then players start to make moves one by one, according to the following rules:\n\n- A player chooses $l^{\\prime}$ and $r^{\\prime}$ so that $l^{\\prime} \\le l$, $r^{\\prime} \\ge r$ and $s[l^{\\prime}, r^{\\prime}]$ is lexicographically less than $s[l, r]$. Then the player changes $l$ and $r$ in this way: $l := l^{\\prime}$, $r := r^{\\prime}$.\n- Ann moves first.\n- The player, that can't make a move loses.\n\nRecall that a substring $s[l, r]$ ($l \\le r$) of a string $s$ is a continuous segment of letters from s that starts at position $l$ and ends at position $r$. For example, \"ehn\" is a substring ($s[3, 5]$) of \"aaaehnsvz\" and \"ahz\" is not.\n\nMike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only $s$ and $k$.\n\nUnfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes $s$ and determines the winner for all possible $k$.",
    "tutorial": "The main idea of this task is that Mike never moves. Lets fix $k$, there two cases: 1) $s[k] \\ge s[i]$ for all $i < k$, in this case $s[k, k] \\le s[l, r]$ for all $l \\le k$ and $r \\ge k$, so Ann can't make her first move (Mike wins). 2) There is $i < k$ such that $s[i] < s[k]$. In this case Ann can move with substring $s[i, r]$. If we choose the least possible $i < k$ such that $s[i]$ is minimal, we will deprive Misha of the opportunity to make a move (Ann wins) Final solution: for all $k$ we should check whether $s[k]$ is the least on substring $s[0, k]$. It can be done with one for in wich we should maintain a minimum on prefix. Complexity $O(|s|)$.",
    "tags": [
      "games",
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1220",
    "index": "D",
    "title": "Alex and Julian",
    "statement": "Boy Dima gave Julian a birthday present — set $B$ consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!\n\nJulian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two $i$ and $j$ with an edge if $|i - j|$ belongs to $B$.\n\nUnfortunately, Julian doesn't like the graph, that was built using $B$. Alex decided to rectify the situation, so he wants to erase some numbers from $B$, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of \\textbf{minimum} size from $B$ so that graph constructed on the new set is bipartite.\n\nRecall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.",
    "tutorial": "Let all numbers in $B$ be odd. If two vertices $i$ and $j$ are connected, then they have different parity, hence our graph is already bipartite (first part is even vertices, second - odd vertices). Now let's see that if we choose an integer $k > 0$, multiply all elements of the set by $2^k$ and build a new graph on this set, our new graph will also be bipartite. Proof: consider $k$-th bit. An edge connects only vertices with different $k$-th bit, so partition is clear. So, we found out that if all elements in $B$ have equal power of $2$ in their factorization, then this set builds a bipartite graph. What about other cases? Let $a, b \\in B$. They form a cycle with $len = \\frac{lcm(a, b)}{a} + \\frac{lcm(a, b)}{b} = \\frac{a}{gcd(a, b)} + \\frac{b}{gcd(a, b)}$. It's easy to see that $len$ is odd iff $a$ and $b$ contain different powers of $2$ in their factorization, so we just proved that there is no other cases. Finally, the solution is to find maximum power of $2$ that divides $B_i$ for all $1 \\le i \\le n$, find the largest subset $B'$ with equal power of $2$ and drop $B \\setminus B'$. Complexity $O(n \\log{maxB})$.",
    "tags": [
      "bitmasks",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1220",
    "index": "E",
    "title": "Tourism",
    "statement": "Alex decided to go on a touristic trip over the country.\n\nFor simplicity let's assume that the country has $n$ cities and $m$ bidirectional roads connecting them. Alex lives in city $s$ and initially located in it. To compare different cities Alex assigned each city a score $w_i$ which is as high as interesting city seems to Alex.\n\nAlex believes that his trip will be interesting only if he will not use any road twice in a row. That is if Alex came to city $v$ from city $u$, he may choose as the next city in the trip any city connected with $v$ by the road, except for the city $u$.\n\nYour task is to help Alex plan his city in a way that maximizes total score over all cities he visited. Note that for each city its score is counted at most once, even if Alex been there several times during his trip.",
    "tutorial": "Let's note that if you visit a vertex $u$ located on a loop, you can always add the numbers on vertices in this loop to answer and you can also add the numbers on vertices between $u$ and $s$. It is true because you can just visit $u$, go through the vertices of the cycle, return to $u$ and then go back to $s$. But if from the given vertex we can't get to the cycle, then we can't return back. So the problem is to choose the best branch leading only to the leaves. And from this point there are several solutions for this problem. Let's discuss one of them: Let $e_u$ be the maximum extra value we could get, if we are in $u$ and we want to go only to leaves. First of all just put all the leaves except $s$ in stack or queue. Then we choose the next vertex $u$ from our queue and look at its parent $v$. Let's decrease $v$'s degree and update $e_v = \\max(e_v, e_u + w_u)$. If $v$'s deegre became $1$, it means that $v$ is the leave now, so let's push it in our queue, if it isn't $s$. It looks like at each step, we just erase one leave from our graph and recompute $e$ value for its parent. At the end, we considered all vertexes which are not belong to the cycles and not belong to the pathes from $s$ to one of the cycles. So we need to sum up the biggest $e_u$ with the sum of all $w_v$, where $v$ wasn't considered during our leaves removing. There are also solutions that build edge-connectivity components and compute the value using DP on tree.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1220",
    "index": "F",
    "title": "Gardener Alex",
    "statement": "Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on $n$ vertices.\n\nToday he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from $1$ to $n$ which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.\n\nNow Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?\n\nWe remind that cyclic shift of permutation $a_1, a_2, \\ldots, a_k, \\ldots, a_n$ for $k$ elements to the left is the permutation $a_{k + 1}, a_{k + 2}, \\ldots, a_n, a_1, a_2, \\ldots, a_k$.",
    "tutorial": "Notice that element $a$ is an ancestor of an element $b$ when it's minimum on a subsegment from $a$ to $b$. Count amount of ancestors for every element in initial permutation. Now, when you remove element $l$ from the left, all elements between it and the leftmost element smaller than $l$ now have one ancestor less. When you move it to the right, all elements between it and the rightmost element smaller than it have one ancestor more. And new amount of ancestors for element moved to the right is one more than amount of ancestors of the rightmost element smaller than it. You can store amounts of ancestors in a segment tree with lazy propagation if you concatenate given permutation with itself.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1220",
    "index": "G",
    "title": "Geolocation",
    "statement": "You are working for the Gryzzl company, headquartered in Pawnee, Indiana.\n\nThe new national park has been opened near Pawnee recently and you are to implement a geolocation system, so people won't get lost. The concept you developed is innovative and minimalistic. There will be $n$ antennas located somewhere in the park. When someone would like to know their current location, their Gryzzl hologram phone will communicate with antennas and obtain distances from a user's current location to all antennas.\n\nKnowing those distances and antennas locations it should be easy to recover a user's location... Right? Well, almost. The only issue is that there is no way to distinguish antennas, so you don't know, which distance corresponds to each antenna. Your task is to find a user's location given as little as all antennas location and an unordered multiset of distances.",
    "tutorial": "Let's look on the sum of squared distances from unknown point $(x;y)$ to all known points $(x_i;y_i)$: $\\sum\\limits_{i=1}^n d_i^2 = \\sum\\limits_{i=1}^n\\left((x-x_i)^2+(y-y_i)^2\\right)= n(x^2+y^2)-2x\\sum\\limits_{i=1}^n x_i - 2y\\sum\\limits_{i=1}^n y_i + \\sum\\limits_{i=1}^n (x_i^2+y_i^2)$ If we switch to new coordinates with the origin in the center of mass of all points, terms $\\sum\\limits_{i=1}^n x_i$ and $\\sum\\limits_{i=1}^n y_i$ will be equal to zero, thus the whole sum will be equal to: $\\sum\\limits_{i=1}^n d_i^2 = n(x^2+y^2)+\\sum\\limits_{i=1}^n(x_i^2+y_i^2)$ From this we obtain that all possible points $(x;y)$ lie on the circumference with the center in the center of mass of all points with the squared radius equal to $\\frac{1}{n}\\sum\\limits_{i=1}^n (d_i^2-x_i^2-y_i^2)$. Due to the randomness of unknown point we may assume that there is only as much as $\\log n$ integer points on this circumference. If we try all possible distances from first point, we may reduce possible points to only those found on the intersection of two circumferences.",
    "tags": [
      "geometry"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1221",
    "index": "A",
    "title": "2048 Game",
    "statement": "You are playing a variation of game 2048. Initially you have a multiset $s$ of $n$ integers. Every integer in this multiset is a power of two.\n\nYou may perform any number (possibly, zero) operations with this multiset.\n\nDuring each operation you choose two \\textbf{equal} integers from $s$, remove them from $s$ and insert the number equal to their sum into $s$.\n\nFor example, if $s = \\{1, 2, 1, 1, 4, 2, 2\\}$ and you choose integers $2$ and $2$, then the multiset becomes $\\{1, 1, 1, 4, 4, 2\\}$.\n\nYou win if the number $2048$ belongs to your multiset. For example, if $s = \\{1024, 512, 512, 4\\}$ you can win as follows: choose $512$ and $512$, your multiset turns into $\\{1024, 1024, 4\\}$. Then choose $1024$ and $1024$, your multiset turns into $\\{2048, 4\\}$ and you win.\n\nYou have to determine if you can win this game.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "It's obvious that we don't need elements that are larger than $2048$. If the sum of the remaining elements is greater than or equal to 2048, then the answer is YES, and NO otherwise. It's true because for getting a integer $x$ that wasn't in the multiset initially, we first need to get integer $\\frac{x}{2}$.",
    "code": "for t in range(int(input())):\n\tn = input()\n\tl = filter(lambda x : x <= 2048,  map(int, input().split()) )\n\tprint('YES' if sum(l) >= 2048 else 'NO')",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1221",
    "index": "B",
    "title": "Knights",
    "statement": "You are given a chess board with $n$ rows and $n$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.\n\nA knight is a chess piece that can attack a piece in cell ($x_2$, $y_2$) from the cell ($x_1$, $y_1$) if one of the following conditions is met:\n\n- $|x_1 - x_2| = 2$ and $|y_1 - y_2| = 1$, or\n- $|x_1 - x_2| = 1$ and $|y_1 - y_2| = 2$.\n\nHere are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them).\n\nA duel of knights is a pair of knights of \\textbf{different} colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.",
    "tutorial": "Let's denote a cell ($i$, $j$) as black if $i + j$ is even, otherwise the cell is white. It's easy to see that if a knight is occupying a black cell, then all cells attacked by it are white, and vice versa. Using this fact, we can construct a solution where every pair of knights that attack each other have different colors - put black knights into black cells, and white knights into white cells, so every pair of knights that can possibly form a duel actually form it.",
    "code": "n = int(input())\nfor i in range(n):\n\tprint(''.join(['W' if (i + j) % 2 == 0 else 'B' for j in range(n)]))",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1221",
    "index": "C",
    "title": "Perfect Team",
    "statement": "You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. \\textbf{She/he can have no specialization, but can't have both at the same time.}\n\nSo the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.\n\nYou are a coach at a very large university and you know that $c$ of your students are coders, $m$ are mathematicians and $x$ have no specialization.\n\nWhat is the maximum number of full perfect teams you can distribute them into?\n\nNote that some students can be left without a team and each student can be a part of no more than one team.\n\nYou are also asked to answer $q$ independent queries.",
    "tutorial": "Notice that if $c \\ne m$, then you can equalize them to the min and re-qualify the rest into students without specialization. That won't change the answer. Now analyze the possible team formations: 1 of each kind, 2 coders and 1 mathematician or 1 coder and 2 mathematicians. Each of these squads have 1 coder and 1 mathematician, so you can only choose the type of the third member. The students without specialization can only be used in the first kind of teams, so let's use them first. After that you might have been left with a nonzero count of coders and mathematicians. These are equal however, so $\\lfloor \\frac{c + m}{3} \\rfloor$ can be added to the answer. This solves each query in $O(1)$. You can also run a binary search and solve each query in $O(\\log MAX)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i){\n\t\tint c, m, x;\n\t\tcin >> c >> m >> x;\n\t\tint l = 0, r = min(c, m);\n\t\tint ans = 0;\n\t\twhile (l <= r){\n\t\t\tint mid = (l + r) / 2;\n\t\t\tif (c + m + x - 2 * mid >= mid){\n\t\t\t\tl = mid + 1;\n\t\t\t\tans = mid;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tr = mid - 1;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1221",
    "index": "D",
    "title": "Make The Fence Great Again",
    "statement": "You have a fence consisting of $n$ vertical boards. The width of each board is $1$. The height of the $i$-th board is $a_i$. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from $2$ to $n$, the condition $a_{i-1} \\neq a_i$ holds.\n\nUnfortunately, it is possible that now your fence is not great. But you can change it! You can increase the length of the $i$-th board by $1$, but you have to pay $b_i$ rubles for it. The length of each board can be increased any number of times (possibly, zero).\n\nCalculate the minimum number of rubles you have to spend to make the fence great again!\n\nYou have to answer $q$ independent queries.",
    "tutorial": "Let's notice that in optimal answer all boards will be increased by no more than two. It is true because if it is beneficial to increase the length of some board by three or more (denote its length as $len$) then increasing to the length $len - 1$, $len - 2$ or $len - 3$ is cheaper and one of these boards is not equal to any of its adjacent boards. Noticing this, we can write a solution based on dynamic programming. Let's $dp_{pos, add}$ is minimum amount of money for making fence $a_1, a_2, \\dots , a_{pos}$ great, moreover the last board(with index $pos$) we increase by $add$. Then value $dp_{pos, add}$ can be calculated as follows: $dp_{pos, add} = add \\cdot b_{pos} + \\min\\limits_{x=0 \\dots 2, a_{pos-1}+x \\neq a_{pos}+add} dp_{pos-1, x}$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\nconst long long INF64 = (long long)(1e18) + 100;\n\nint t;\nint n;\nint a[N];\nint b[N];\nlong long dp[3][N];\n\nlong long calc(int add, int pos){\n\tlong long &res = dp[add][pos];\n\tif(res != -1) return res;\n\n\tres = INF64;\n\tif(pos == n) return res = 0;\n\tfor(long long x = 0; x <= 2; ++x)\n\t\tif(pos == 0 || a[pos] + x != a[pos - 1] + add)\n\t\t\tres = min(res, calc(x, pos + 1) + x * b[pos]);\n\t\t\n\treturn res;\n}\n\nint main() {\t\n\tscanf(\"%d\", &t);\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tscanf(\"%d\", &n);\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tscanf(\"%d\", a + i);\n\t\t\tscanf(\"%d\", b + i);\n\t\t}\n\n\t\tfor(int i = 0; i <= n; ++i) \n\t\t\tdp[0][i] = dp[1][i] = dp[2][i] = -1;\t\t\t\t\n\t\tprintf(\"%lld\\n\", calc(0, 0));\n\t}\n\treturn 0;\n} ",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1221",
    "index": "E",
    "title": "Game With String",
    "statement": "Alice and Bob play a game. Initially they have a string $s_1, s_2, \\dots, s_n$, consisting of only characters . and X. They take alternating turns, and Alice is moving first. During each turn, the player has to select a contiguous substring consisting only of characters . and replaces each of them with X. Alice must select a substing of length $a$, and Bob must select a substring of length $b$. It is guaranteed that $a > b$.\n\nFor example, if $s =$ ...X.. and $a = 3$, $b = 2$, then after Alice's move string can turn only into XXXX... And if it's Bob's turn and the string $s =$ ...X.., then after Bob's move the string can turn into XX.X.., .XXX.. or ...XXX.\n\nWhoever is unable to make a move, loses. You have to determine who wins if they both play optimally.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "At first, let's transform input to a more convenient form. We consider only such subsegments that consist of the symbols . and which cannot be expanded to the right or left. For example, for $s = XX...X.X...X..$ we consider segments of length $3$, $1$, $3$, and $2$. Let's divide all such segments into four groups by their length $len$: $len < b$; $b \\le len < a$; $a \\le len < 2b$; $len \\ge 2b$. In such a division, each segment belongs to exactly one type. Suppose that the Bob takes the first turn. If there is a segment of second type, then Bob wins, because he always have a spare turn that Alice cannot make. If there is a segment of fourth type then the Bob also wins because he can make the segment of second type by taking turn in this segment of four type. If there are no segments of second and four types, then victory depends on the parity of the number of segments of the third type. But it is true if the Bob takes first turn. If Alice takes first turn then she doesn't want, after her move, there are segments of the second and fourth types. So if initially there is a segment of second type then Alice loses because she can't take turns into segment of second type. If there are two or more segments of four type then Alice also loses, because after her turn at least one such segments remains. If there are only one segment of four type then Alice have to take turn into this segment. Since the length of this segment doesn't exceed $n$, we can iterate over all possible Alice moves. After Alice's move segment of fourth type can be divided into no more than two new segments, let's denote their types as $t_1$ and $t_2$. If at least one of these segments of second or fourth type, then it's bad turn for Alice. Otherwise Alice win if remaining number of segment of third type is even (note that $t_1$ or $t_2$ also can be the third type). And finally, if initially there are only segments of first or third type, then victory depends on the parity of the number of segments of the third type.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(2e5) + 99;\n\nint t;\nint a, b;\nstring s;\n\nint main() {\n\tcin >> t;\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tcin >> a >> b >> s;\n\t\tvector <int> v;\n\t\tint l = 0;\n\t\twhile(l < s.size()){\n\t\t\tif(s[l] == 'X'){\n\t\t\t\t++l;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint r = l + 1;\n\t\t\twhile(r < s.size() && s[r] == '.') ++r;\n\t\t\tv.push_back(r - l);\n\t\t\tl = r;\n\t\t}\n\t\t\n\t\tbool ok = true;\n\t\tint id = -1;\n\t\tint cnt = 0;\n\t\tfor(int i = 0; i < v.size(); ++i){\n\t\t\tif(b <= v[i] && v[i] < a) ok = false;\n\t\t\tif(b + b <= v[i]){\n\t\t\t\tif(id == -1) id = i;\n\t\t\t\telse ok = false;\n\t\t\t}\n\t\t\tif(a <= v[i] && v[i] < b + b) ++cnt; \n\t\t}\n\n\t\tif(!ok){\n\t\t\tcout << \"NO\" << endl;\t\t\t\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(id == -1){\n\t\t\tif(cnt & 1) cout << \"YES\" << endl;\n\t\t\telse cout << \"NO\" << endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tok = false;\n\t\tint sz = v[id];\n\t\tassert(sz >= a);\n\t\tfor(int rem1 = 0; sz - a - rem1 >= 0; ++rem1){\n\t\t\tint rem2 = sz - a - rem1;\n\t\t\tint ncnt = cnt;\n\t\t\tif((rem1 >= b + b) || (b <= rem1 && rem1 < a)) continue;\n\t\t\tif((rem2 >= b + b) || (b <= rem2 && rem2 < a)) continue;\n\n\t\t\tif(rem1 >= a) ++ncnt;\n\t\t\tif(rem2 >= a) ++ncnt;\n\t\t\tif(ncnt % 2 == 0) ok = true;\n\t\t}\n\t\t\n\t\tif(ok) cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n\treturn 0;\n}                             \t\n\n\n\n\n\n",
    "tags": [
      "games"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1221",
    "index": "F",
    "title": "Choose a Square",
    "statement": "Petya recently found a game \"Choose a Square\". In this game, there are $n$ points numbered from $1$ to $n$ on an infinite field. The $i$-th point has coordinates $(x_i, y_i)$ and cost $c_i$.\n\nYou have to choose a square such that its sides are parallel to coordinate axes, the lower left and upper right corners belong to the line $y = x$, and all corners have integer coordinates.\n\nThe score you get is the sum of costs of the points covered by the selected square minus the length of the side of the square. Note that the length of the side can be zero.\n\nPetya asks you to calculate the maximum possible score in the game that can be achieved by placing exactly one square.",
    "tutorial": "Notice that the square ($l, l$) ($r, r$) covers the point ($x, y$) if and only if $l \\le min(x, y) \\le max(x, y) \\le r$. Using this fact, let's reformulate the problem the following way: we have to find the segment $(l, r)$, such that the sum of the segments fully covered by it is maximal. Let's build a segment tree, the $r$-th of its leaves stores $f(l, r)$ - the sum of the segments covered by the segment $(l, r)$ . Initially, it's built for some $l$ such that it is to the right of all segments. Other nodes store the maximum in them. Now let's iterate over the values of $l$ in descending order. Let there be some segment starting in $l$ $(l, x)$ with the cost $c$. All the answers $f(l, r)$ for $r < x$ won't change because they don't cover that new segment. And the values on the suffix from the position $x$ ($r \\ge x$) will increase by $c$. The only thing left is to learn how to handle the subtraction of the length of the side. That term is $(r - l)$ and the thing we are looking for is $\\max \\limits_{r} f(l, r) - (r - l)$. Rewrite it in form $l + \\max \\limits_{r} f(l, r) - r$ and you'll see that you can just subtract $r$ from the value of the $r$-th leaf of the segment tree at the beginning to get the correct result. Surely, you'll need to add that $l$ after you ask the maximum of all the segtree to obtain the answer. You'll probably need to compress the coordinates - leave only such positions $i$ that there is at least one $x = i$ or $y = i$. Implicit segtree might work but neither ML, nor TL are not friendly to it. Also be careful with the case with all points being negative.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int N = 1000 * 1000 + 13;\n\nint n;\npair<pt, int> a[N];\nvector<int> vals;\nvector<pt> ev[N];\npair<li, int> t[4 * N];\nli add[4 * N];\n\nvoid build(int v, int l, int r) {\n\tif (l == r) {\n\t\tt[v] = mp(-vals[l], l);\n\t\tadd[v] = 0;\n\t\treturn;\n\t}\n\tint m = (l + r) >> 1;\n\tbuild(v * 2 + 1, l, m);\n\tbuild(v * 2 + 2, m + 1, r);\n\tt[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\nvoid push(int v, int l, int r) {\n\tif (add[v] == 0) return;\n\tt[v].x += add[v];\n\tif (l != r) {\n\t\tadd[v * 2 + 1] += add[v];\n\t\tadd[v * 2 + 2] += add[v];\n\t}\n\tadd[v] = 0;\n}\n\nvoid upd(int v, int l, int r, int L, int R, int val) {\n\tpush(v, l, r);\n\tif (L > R) return;\n\tif (l == L && r == R) {\n\t\tadd[v] += val;\n\t\tpush(v, l, r);\n\t\treturn;\n\t}\n\tint m = (l + r) >> 1;\n\tupd(v * 2 + 1, l, m, L, min(m, R), val);\n\tupd(v * 2 + 2, m + 1, r, max(m + 1, L), R, val);\n\tt[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\npair<li, int> get(int v, int l, int r, int L, int R) {\n\tpush(v, l, r);\n\tif (L > R) return mp(-li(1e18), 0);\n\tif (l == L && r == R) return t[v];\n\tint m = (l + r) >> 1;\n\tauto r1 = get(v * 2 + 1, l, m, L, min(m, R));\n\tauto r2 = get(v * 2 + 2, m + 1, r, max(m + 1, L), R);\n\treturn max(r1, r2);\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n) scanf(\"%d%d%d\", &a[i].x.x, &a[i].x.y, &a[i].y);\n\t\n\tforn(i, n) {\n\t\tvals.pb(a[i].x.x);\n\t\tvals.pb(a[i].x.y);\n\t}\n\t\n\tvals.pb(0);\n\tsort(all(vals));\n\tvals.pb(vals.back() + 1);\n\t\n\tvals.resize(unique(all(vals)) - vals.begin());\n\t\n\tforn(i, n) {\n\t\tint x = lower_bound(all(vals), a[i].x.x) - vals.begin();\n\t\tint y = lower_bound(all(vals), a[i].x.y) - vals.begin();\n\t\tev[min(x, y)].pb(mp(max(x, y), a[i].y));\n\t}\n\t\n\tn = sz(vals);\n\t\n\tbuild(0, 0, n - 1);\n\t\n\tli ans = -1;\n\tint ansl = -1, ansr = -1;\n\t\n\tfor (int i = sz(vals) - 1; i >= 0; i--) {\n\t\tfor (auto it : ev[i]) upd(0, 0, n - 1, it.x, n - 1, it.y);\n\t\tauto cur = get(0, 0, n - 1, i, n - 1);\n\t\tif (cur.x + vals[i] > ans) {\n\t\t\tans = cur.x + vals[i];\n\t\t\tansl = vals[i]; ansr = vals[cur.y]; \n\t\t}\n\t}\n\t\n\tprintf(\"%lld\\n%d %d %d %d\\n\", ans, ansl, ansl, ansr, ansr);\n\t\n}",
    "tags": [
      "binary search",
      "data structures",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1221",
    "index": "G",
    "title": "Graph And Numbers",
    "statement": "You are given an undirected graph with $n$ vertices and $m$ edges. You have to write a number on each vertex of this graph, each number should be either $0$ or $1$. After that, you write a number on each edge equal to the sum of numbers on vertices incident to that edge.\n\nYou have to choose the numbers you will write on the vertices so that there is at least one edge with $0$ written on it, at least one edge with $1$ and at least one edge with $2$. How many ways are there to do it? Two ways to choose numbers are different if there exists at least one vertex which has different numbers written on it in these two ways.",
    "tutorial": "Let $F(S)$ be the number of ways to paint the graph so that all numbers on edges belong to the set $S$. Using inclusion-exclusion we may get that the answer is $F(\\{0, 1, 2\\}) - F(\\{1, 2\\}) - F(\\{0, 2\\}) + F(\\{2\\}) - F(\\{0, 1\\}) + F(\\{1\\}) + F(\\{0\\}) - F(\\{\\})$. Okay, let's analyze everything separatedly. $F(\\{0, 1, 2\\})$ is $2^n$, because every number is allowed; $F(\\{1, 2\\})$ will be analyzed later; $F(\\{0, 2\\})$ is $2^C$, where $C$ is the number of connected components - in each component we have to use the same number; $F(\\{2\\})$ is $2^I$, where $I$ is the number of isolated vertices - every non-isolated vertex should have number $1$ on it, and all isolated vertices may have any numbers; $F(\\{0, 1\\}) = F(\\{1, 2\\})$, since these cases are symmetric; $F(\\{1\\})$ is the number of bipartite colorings of the graph. It is $0$ if the graph contains an odd cycle, or $2^C$ if it is bipartite; $F(\\{0\\}) = F(\\{2\\})$, since these cases are symmetric; $F(\\{\\})$ is $2^n$ if there are no edges in the graph, otherwise it is $0$. So, the only thing left to consider is $F(\\{1, 2\\})$. Actually, it is easier to calculate $F(\\{0, 1\\})$ - it is the number of independent sets of this graph. This problem is NP-complete, but when $n = 40$, we may apply meet-in-the-middle technique as follows: divide all vertices into two sets $S_1$ and $S_2$ of roughly equal size; for $S_1$, find all its independent subsets, and for each such subset, find which vertices from $S_2$ can be added to it without breaking its independency; for each subset of $S_2$, find the number of independent subsets of $S_1$ such that no vertex from chosen subset of $S_2$ is adjacent to any vertex from chosen subset of $S_1$ (you may use subset DP and OR-convolution here); find all independent subsets of $S_2$, and for every such subset, add the number of subsets of $S_1$ that can be merged with it so the resulting set is independent. The most time-consuming part is counting all independent sets, so the time complexity is $(O(n2^{n/2}))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 40;\nconst int M = 20;\n\nlong long incident_mask[N];\nvector<int> g[N];\nint n, m;\nlong long ans = 0;\nlong long cntmask[1 << M];\n\nlong long binpow(long long x, long long y)\n{\n\tlong long z = 1;\n\twhile(y > 0)\n\t{\n\t\tif(y % 2 == 1) z *= x;\n\t\tx *= x;\n\t\ty /= 2;\n\t}\n\treturn z;\n}\n\nint used[N];\n\nvoid dfs(int x, int c)\n{\n\tif(used[x])\n\t\treturn;\n\tused[x] = c;\n\tfor(auto y : g[x])\n\t\tdfs(y, 3 - c);\n}\n\nlong long countIsolated()\n{\n\tlong long ans = 0;\n\tfor(int i = 0; i < n; i++)\n\t\tif(g[i].empty())\n\t\t\tans++;\n\treturn ans;\n}\n\nlong long countComponents()\n{\n\tmemset(used, 0, sizeof used);\n\tlong long ans = 0;\n\tfor(int i = 0; i < n; i++)\n\t\tif(!used[i])\n\t\t{\n\t\t\tans++;\n\t\t\tdfs(i, 1);\n\t\t}\n\treturn ans;\n}\n\nbool bipartite()\n{\n\tmemset(used, 0, sizeof used);\n\tfor(int i = 0; i < n; i++)\n\t\tif(!used[i])\n\t\t\tdfs(i, 1);\n\tfor(int i = 0; i < n; i++)\n\t\tfor(auto j : g[i])\n\t\t\tif(used[i] == used[j])\n\t\t\t\treturn false;\n\treturn true;\n}\n\nlong long countIndependentSets()\n{\n\tint m1 = min(n, 20);\n\tint m2 = n - m1;\n\t//cerr << m1 << \" \" << m2 << endl;\n\tmemset(cntmask, 0, sizeof cntmask);\n\tfor(int i = 0; i < (1 << m1); i++)\n\t{\n\t\tlong long curmask = 0;\n\t\tbool good = true;\n\t\tfor(int j = 0; j < m1; j++)\n\t\t{\n\t\t\tif((i & (1 << j)) == 0)\n\t\t\t\tcontinue;\n\t\t\tif(curmask & (1 << j))\n\t\t\t\tgood = false;\n\t\t\tcurmask |= ((1 << j) | incident_mask[j]);\n\t\t}\n\t\tif(good)\n\t\t{\n\t\t\tcntmask[curmask >> m1]++;\n\t\t}\n\t}\t\n\tfor(int i = 0; i < m2; i++)\n\t\tfor(int j = 0; j < (1 << m2); j++)\n\t\t\tif(j & (1 << i))\n\t\t\t\tcntmask[j] += cntmask[j ^ (1 << i)];\n\tlong long ans = 0;\n\tfor(int i = 0; i < (1 << m2); i++)\n\t{\n\t\tlong long curmask = 0;\n\t\tbool good = true;\n\t\tfor(int j = m1; j < n; j++)\n\t\t{\n\t\t\tif((i & (1 << (j - m1))) == 0)\n\t\t\t\tcontinue;\n\t\t\tif(curmask & (1ll << j))\n\t\t\t\tgood = false;\n\t\t\tcurmask |= (1ll << j) | incident_mask[j];\n\t\t}\n\t\tif(good)\n\t\t{\n\t\t\t//cerr << i << endl;\n\t\t\tans += cntmask[(i ^ ((1 << m2) - 1))];\n\t\t}\n\t}\n\treturn ans;\n}\n\nlong long calc(int mask)\n{\n\tif(mask == 0)\n\t\treturn binpow(2, n);\n\tif(mask == 1 || mask == 4)\n\t\treturn countIndependentSets();\n\tif(mask == 2)\n\t\treturn binpow(2, countComponents());\n\tif(mask == 3 || mask == 6)\n\t\treturn binpow(2, countIsolated());\n\tif(mask == 5)\n\t\treturn (bipartite() ? binpow(2, countComponents()) : 0);\n\tif(mask == 7)\n\t\treturn (m == 0 ? binpow(2, n) : 0);\n\treturn 0;\n}\n\nint main() {\n\tcin >> n >> m;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x;\n\t\t--y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t\tincident_mask[x] ^= (1ll << y);\n\t\tincident_mask[y] ^= (1ll << x);\n\t}\n\tfor(int i = 0; i < 8; i++)\n\t{\n\t\t//cerr << i << \" \" << calc(i) << endl;\n\t\tif(__builtin_popcount(i) % 2 == 0)\n\t\t\tans += calc(i);\n\t\telse\n\t\t\tans -= calc(i);\n\t}\n\tcout << ans << endl;\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp",
      "meet-in-the-middle"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1223",
    "index": "A",
    "title": "CME",
    "statement": "Let's denote correct match equation (we will denote it as CME) an equation $a + b = c$ there all integers $a$, $b$ and $c$ are greater than zero.\n\nFor example, equations $2 + 2 = 4$ (||+||=||||) and $1 + 2 = 3$ (|+||=|||) are CME but equations $1 + 2 = 4$ (|+||=||||), $2 + 2 = 3$ (||+||=|||), and $0 + 1 = 1$ (+|=|) are not.\n\nNow, you have $n$ matches. You want to assemble a CME using \\textbf{all} your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!\n\nFor example, if $n = 2$, you can buy two matches and assemble |+|=||, and if $n = 5$ you can buy one match and assemble ||+|=|||.\n\nCalculate the minimum number of matches which you have to buy for assembling CME.\n\nNote, that you have to answer $q$ independent queries.",
    "tutorial": "If $n$ is odd then we have to buy at least one match because integers $a+b$ and $c$ ($a$, $b$ and $c$ is elements of equation $a+b=c$) must be of the same parity, so integer $a+b+c$ is always even. If $n$ is even then we can assemble an equation $1 + \\frac{n-2}{2} = \\frac{n}{2}$. But there is one corner case. If $n = 2$, then we have to buy two matches, because all integers $a$, $b$ and $c$ must be greater than zero. In this way, the answer is equal: $2$ if $n = 2$; $1$ if $n$ is odd; $0$ if $n$ is even and greater than $2$.",
    "code": "for t in range(int(input())):\n\tn = int(input())\n\tprint(2 if n == 2 else (n & 1))",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1223",
    "index": "B",
    "title": "Strings Equalization",
    "statement": "You are given two strings of equal length $s$ and $t$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.\n\nDuring each operation you choose two \\textbf{adjacent} characters in \\textbf{any} string and assign the value of the first character to the value of the second or vice versa.\n\nFor example, if $s$ is \"acbc\" you can get the following strings in \\textbf{one} operation:\n\n- \"aabc\" (if you perform $s_2 = s_1$);\n- \"ccbc\" (if you perform $s_1 = s_2$);\n- \"accc\" (if you perform $s_3 = s_2$ or $s_3 = s_4$);\n- \"abbc\" (if you perform $s_2 = s_3$);\n- \"acbb\" (if you perform $s_4 = s_3$);\n\nNote that you can also apply this operation to the string $t$.\n\nPlease determine whether it is possible to transform $s$ into $t$, applying the operation above any number of times.\n\nNote that you have to answer $q$ independent queries.",
    "tutorial": "If there is a character which is contained in string $s$ and $t$ (let's denote it as $c$), then we answer is \"YES\" because we can turn these string into string consisting only of this character $c$. Otherwise the answer is \"NO\", because if initially strings have not a common character, then after performing operation they also have not a common character.",
    "code": "for t in range(int(input())):\n    print('NO' if len(set(input()) & set(input())) == 0 else 'YES')",
    "tags": [
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1223",
    "index": "C",
    "title": "Save the Nature",
    "statement": "You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!\n\nYou have $n$ tickets to sell. The price of the $i$-th ticket is $p_i$. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them \\textbf{to the order you chose}:\n\n- The $x\\%$ of the price of each the $a$-th sold ticket ($a$-th, $2a$-th, $3a$-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources.\n- The $y\\%$ of the price of each the $b$-th sold ticket ($b$-th, $2b$-th, $3b$-th and so on) in the order you chose is aimed for pollution abatement.\n\nIf the ticket is in both programs then the $(x + y) \\%$ are used for environmental activities. Also, it's known that all prices are multiples of $100$, so there is no need in any rounding.\n\nFor example, if you'd like to sell tickets with prices $[400, 100, 300, 200]$ and the cinema pays $10\\%$ of each $2$-nd sold ticket and $20\\%$ of each $3$-rd sold ticket, then arranging them in order $[100, 200, 300, 400]$ will lead to contribution equal to $100 \\cdot 0 + 200 \\cdot 0.1 + 300 \\cdot 0.2 + 400 \\cdot 0.1 = 120$. But arranging them in order $[100, 300, 400, 200]$ will lead to $100 \\cdot 0 + 300 \\cdot 0.1 + 400 \\cdot 0.2 + 200 \\cdot 0.1 = 130$.\n\nNature can't wait, so you decided to change the order of tickets in such a way, so that the \\textbf{total} contribution to programs will reach at least $k$ in \\textbf{minimum} number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least $k$.",
    "tutorial": "At first, let's assume that $x \\ge y$ (otherwise, we can swap parameters of programs). Let's define $cont(len)$ as the maximum contribution we can get selling exactly $len$ tickets. Note, in general case sold ticket can be one of $4$ types: tickets with $(x + y)\\%$ of the price are contributed; the number of such tickets is $cXY$; tickets with $x\\%$ of the price are contributed; the number of such tickets is $cX$; tickets with $y\\%$ of the price are contributed; the number of such tickets is $cY$; tickets which are not in both programs. All values $cXY$, $cX$, $cY$ can be easily counted by iterating over indices $i$ from $1$ to $len$ and checking whenever $i$ is divisible by $a$ or by $b$ or both. Now we can understand that it's always optimal to choose in the first group $cXY$ maximums from $p$, in the second group next $cX$ maximums and in the third - next $cY$ maximums. Using the algorithm above we can calculate $cont(len)$ in linear time (just sort $p$ beforehand). The final step is to understand that function $cont(len)$ is non decreasing, so we can just binary search the minimal $len$ with $cont(len) \\ge k$. The time complexity is $O(n \\log{n})$, but $O(n \\log^2{n})$ can pass too.",
    "code": "fun calc(p: IntArray, len: Int, x: Int, a: Int, y: Int, b: Int): Long {\n    var ans = 0L\n    var (cX, cY, cXY) = listOf(0, 0, 0)\n    for (i in 1..len) {\n        if (i % a == 0 && i % b == 0) cXY++\n        else if (i % a == 0) cX++\n        else if (i % b == 0) cY++\n    }\n    for (i in 0 until cXY)\n        ans += p[i] * (x + y)\n    for (i in 0 until cX)\n        ans += p[cXY + i] * x\n    for (i in 0 until cY)\n        ans += p[cXY + cX + i] * y;\n    return ans\n}\n\nfun main() {\n    val q = readLine()!!.toInt()\n    for (ct in 1..q) {\n        val n = readLine()!!.toInt()\n        val p = readLine()!!.split(' ').map { it.toInt() / 100 }\n                .sortedDescending().toIntArray()\n        var (x, a) = readLine()!!.split(' ').map { it.toInt() }\n        var (y, b) = readLine()!!.split(' ').map { it.toInt() }\n        val k = readLine()!!.toLong()\n\n        if (x < y) {\n            x = y.also { y = x }\n            a = b.also { b = a }\n        }\n\n        var lf = 0; var rg = n + 1\n        while (rg - lf > 1) {\n            val mid = (lf + rg) / 2\n            if (calc(p, mid, x, a, y, b) >= k)\n                rg = mid\n            else\n                lf = mid\n        }\n\n        if (rg > n) rg = -1\n        println(rg)\n    }\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1223",
    "index": "D",
    "title": "Sequence Sorting",
    "statement": "You are given a sequence $a_1, a_2, \\dots, a_n$, consisting of integers.\n\nYou can apply the following operation to this sequence: choose some integer $x$ and move \\textbf{all} elements equal to $x$ either to the beginning, or to the end of $a$. Note that you have to move all these elements in \\textbf{one} direction in \\textbf{one} operation.\n\nFor example, if $a = [2, 1, 3, 1, 1, 3, 2]$, you can get the following sequences in one operation (for convenience, denote elements equal to $x$ as $x$-elements):\n\n- $[1, 1, 1, 2, 3, 3, 2]$ if you move all $1$-elements to the beginning;\n- $[2, 3, 3, 2, 1, 1, 1]$ if you move all $1$-elements to the end;\n- $[2, 2, 1, 3, 1, 1, 3]$ if you move all $2$-elements to the beginning;\n- $[1, 3, 1, 1, 3, 2, 2]$ if you move all $2$-elements to the end;\n- $[3, 3, 2, 1, 1, 1, 2]$ if you move all $3$-elements to the beginning;\n- $[2, 1, 1, 1, 2, 3, 3]$ if you move all $3$-elements to the end;\n\nYou have to determine the minimum number of such operations so that the sequence $a$ becomes sorted in non-descending order. Non-descending order means that for all $i$ from $2$ to $n$, the condition $a_{i-1} \\le a_i$ is satisfied.\n\nNote that you have to answer $q$ independent queries.",
    "tutorial": "Let's consider two sequences of integers $m_1 < m_2 < \\dots < m_k$ and $d_1 < d_2 < \\dots < d_l$. Sequence $m$ contains integers which were used in some operation in the optimal answer. Sequence $d$ contains integers which were not used. For example, if $a = [2, 1, 3, 5, 4]$, then optimal answer is move all $1$-elements to the beginning and then move all $5$-elements to the end, so $m = [1, 5]$ and $d = [2, 3, 4]$. Two important conditions are held for these sequences: $maxInd(d_{i-1}) < minInd(d_i)$ for every $i$ from $2$ to $l$. $minInd(x)$ is the minimum index $i$ such that $a_i = x$, and $maxInd(x)$ is the maximum index $i$ such that $a_i = x$; for each $i$ from $2$ to $l$ there is no such integer $x$, that $d_i < x < d_{i + 1}$ and sequence $m$ contains this integer $x$. Since the answer is equal to $|m| = k$, we want to minimize this value. So we want to maximize the length of sequence $d$. For each integer $l$ we want to find the maximum integer $dp_l = len$ such that we can sort sequence $a$ without moving elements in range $l \\dots l + len - 1$. We can do it with dynamic programming. Let's consider all integers occurring in sequence $a$ in descending order $s_1, s_2, \\dots, s_t$ ($s_{i - 1} > s_{i}$ for each $i$ from $2$ to $t$). If $maxInd(s_i) < minInd(s_{i+1})$ then $dp_i = dp_{i + 1} + 1$, otherwise $dp_i = 1$. The answer is equal to $t - \\max\\limits_{i=1 \\dots t} dp_i$, there $t$ is the number of distinct integers in sequence $a$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\nconst int INF = int(1e9) + 99;\n\nint t, n;\nint a[N];\nint l[N], r[N];\nint dp[N];\n\nint main() {\n\tscanf(\"%d\", &t);\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tscanf(\"%d\", &n);\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tl[i] = INF;\n\t\t\tr[i] = -INF;\n\t\t\tdp[i] = 0;\n\t\t}\n\n\t\tvector <int> v;\t\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tscanf(\"%d\", a + i);\n\t\t\t--a[i];\n\t\t\tv.push_back(a[i]);\n\t\t\tl[a[i]] = min(l[a[i]], i);\n\t\t\tr[a[i]] = max(r[a[i]], i);\n\t\t}\n\n\t\tsort(v.begin(), v.end());\n\t\tv.erase(unique(v.begin(), v.end()), v.end());\n\t\n\t\tint res = n;\n\t\tfor(int i = v.size() - 1; i >= 0; --i){\n\t\t\tif(i + 1 == v.size() || r[v[i]] >= l[v[i + 1]]) dp[i] = 1;\n\t\t\telse dp[i] = 1 + dp[i + 1];\n\t\t\tres = min(res, int(v.size())- dp[i]);\n\t\t}\n\n\t\tprintf(\"%d\\n\", res);\n\t}\t\n\n\treturn 0;\n}                             \t",
    "tags": [
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1223",
    "index": "E",
    "title": "Paint the Tree",
    "statement": "You are given a weighted tree consisting of $n$ vertices. Recall that a tree is a connected graph without cycles. Vertices $u_i$ and $v_i$ are connected by an edge with weight $w_i$.\n\nLet's define the $k$-coloring of the tree as an assignment of exactly $k$ colors to \\textbf{each} vertex, so that each color is used no more than two times. You can assume that you have infinitely many colors available. We say that an edge is saturated in the given $k$-coloring if its endpoints share at least one color (i.e. there exists a color that is assigned to both endpoints).\n\nLet's also define the value of a $k$-coloring as the sum of weights of saturated edges.\n\nPlease calculate the maximum possible value of a $k$-coloring of the given tree.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "It is obvious that if we paint two vertices in the same color, they should be adjacent to each other - otherwise we could paint them in different colors, and the answer would not be worse. So we can reduce the problem to the following: choose a set of edges with maximum cost such that no vertex is adjacent to more than $k$ chosen edges. This problem is very similar to maximum weighted matching on the tree, and we can try to use some methods that allow us to solve that problem. Let's solve the problem using dynamic programming $dp_{v, f}$ - the answer to the problem for the subtree of the vertex $v$, $f$ is the flag that denotes whether the edge from $v$ to its parent is chosen. Depending on the flag $f$, we can choose $k$ or $k - 1$ edges connecting our vertex to its children (let's denote the maximum number of edges we can choose as $t$). We have to select no more than $t$ child nodes of the vertex $v$. If we choose an edge leading to node $u$, then $dp_{u, 1} + w_ {v, u}$ is added to the $dp$ value we are currently calculating; otherwise, $dp_{u, 0}$ is added. Based on this formula, you have to choose no more than $t$ child nodes of vertex $v$ for which the total sum of $dp_{u, 1} + w_{v, u} - dp_{u, 0}$ is maximum.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int N = 500 * 1000 + 13;\n\nint n, k;\nvector<pair<int, int>> g[N];\nlong long dp[N][2];\n\nvoid calc(int v, int p = -1) {\n\tlong long cur = 0;\n\tvector<long long> adds;\n\t\n\tfor (auto it : g[v]) {\n\t\tint to = it.x;\n\t\tint w = it.y;\n\t\tif (to == p)\n\t\t\tcontinue;\n\t\tcalc(to, v);\n\t\t\n\t\tcur += dp[to][0];\n\t\tadds.pb(dp[to][1] + w - dp[to][0]);\n\t}\n\t\n\tsort(all(adds), greater<long long>());\n\tforn(i, min(sz(adds), k)) if (adds[i] > 0)\n\t\tcur += adds[i];\n\t\n\tdp[v][0] = dp[v][1] = cur;\n\tif (k <= sz(adds) && adds[k - 1] > 0)\n\t\tdp[v][1] -= adds[k - 1];\n}\n\nlong long solve() {\n    scanf(\"%d%d\", &n, &k);\n    forn(i, n) g[i].clear();\n\tforn(i, n - 1) {\n\t\tint x, y, w;\n\t\tscanf(\"%d%d%d\", &x, &y, &w);\n\t\t--x; --y;\n\t\tg[x].pb(mp(y, w));\n\t\tg[y].pb(mp(x, w));\n\t}\n\t\n\tcalc(0);\n\t\n\treturn dp[0][0];\n}\n\nint main() {\n\tint q;\n\tscanf(\"%d\", &q);\n\tforn(i, q) printf(\"%lld\\n\", solve());\n}",
    "tags": [
      "dp",
      "sortings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1223",
    "index": "F",
    "title": "Stack Exterminable Arrays",
    "statement": "Let's look at the following process: initially you have an empty stack and an array $s$ of the length $l$. You are trying to push array elements to the stack in the order $s_1, s_2, s_3, \\dots s_{l}$. Moreover, if the stack is empty or the element at the top of this stack is not equal to the current element, then you just push the current element to the top of the stack. Otherwise, you don't push the current element to the stack and, moreover, pop the top element of the stack.\n\nIf after this process the stack remains empty, the array $s$ is considered stack exterminable.\n\nThere are samples of stack exterminable arrays:\n\n- $[1, 1]$;\n- $[2, 1, 1, 2]$;\n- $[1, 1, 2, 2]$;\n- $[1, 3, 3, 1, 2, 2]$;\n- $[3, 1, 3, 3, 1, 3]$;\n- $[3, 3, 3, 3, 3, 3]$;\n- $[5, 1, 2, 2, 1, 4, 4, 5]$;\n\nLet's consider the changing of stack more details if $s = [5, 1, 2, 2, 1, 4, 4, 5]$ (the top of stack is highlighted).\n\n- after pushing $s_1 = 5$ the stack turn into $[\\textbf{5}]$;\n- after pushing $s_2 = 1$ the stack turn into $[5, \\textbf{1}]$;\n- after pushing $s_3 = 2$ the stack turn into $[5, 1, \\textbf{2}]$;\n- after pushing $s_4 = 2$ the stack turn into $[5, \\textbf{1}]$;\n- after pushing $s_5 = 1$ the stack turn into $[\\textbf{5}]$;\n- after pushing $s_6 = 4$ the stack turn into $[5, \\textbf{4}]$;\n- after pushing $s_7 = 4$ the stack turn into $[\\textbf{5}]$;\n- after pushing $s_8 = 5$ the stack is empty.\n\nYou are given an array $a_1, a_2, \\ldots, a_n$. You have to calculate the number of its subarrays which are stack exterminable.\n\nNote, that you have to answer $q$ independent queries.",
    "tutorial": "Let's understand how calculate the array $nxt$, such that $nxt_l$ is equal to the minimum index $r > l$ such that subarray $a_{l \\dots r}$ is stack exterminable. If there is no such index, then $nxt_l = -1$. If we calculate this array then we solve this task by simple dynamic programming. Let's calculate it in order $nxt_n, nxt_{n-1}, \\dots , nxt_1$ by dynamic programming. At first consider simple case. If $a_i = a_{i + 1}$, then $nxt_i = i + 1$. Otherwise we have to \"add\" the block $a_{i+1} \\dots a_{nxt_{i+1}}$ (of course, $nxt_{i + 1}$ should be not equal to $-1$) and check that $a_i = a_{1 + nxt_{i + 1}}$. If this ($a_i = a_{1 + nxt_{i + 1}}$) also is not true, then you have to add a new block $a_{1 + nxt_{i+1}} \\dots a_{nxt_{1 + nxt_{i+1}}}$ and check the condition $a_i = a_{1 + nxt_{1 + nxt_{i+1}}}$. If this condition also is not try, then you have to add a new block and so on. It is correct solution, but it can be too slowly. Let's understand, that we add blocks to $a_i$ until condition $a_i = a_{1 + nxt_{\\dots}}$ is holds. Let's assume, that we have an array $nxtX$ (this array contains a hashMaps, for example you can use map in C++), such that $nxtX_{i, x}$ is is equal to the minimum index $r > l$ such that subarray $a_{l \\dots r}$ is stack exterminable and $x = a_{r + 1}$. Then we can easily calculate the value $nxt_i = nxtX_{i+1, a_i} + 1$. Remains to understand, how to calculate $nxtX_{i}$. For this we just can make an assignment $nxtX_{i} = nxtX_{nxt_i + 1}$. And then update $nxtX_{i, a_{nxt_i + 1}} = nxt_{i} + 1$. But I deceived you a little. We can't make an assignment $nxtX_{i} = nxtX_{nxt_i + 1}$ because it is to slow. Instead that you need to swap elements $nxtX_{i}$ and $nxtX_{nxt_i + 1}$, this can be done using the function $swap$ in C++ or Java (time complexity of $swap$ if $O(1)$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\n\nint t, n;\nint a[N];\nint nxt[N];\nint dp[N];\nmap<int, int> nxtX[N];\n\n\nint main() {\t\n\tscanf(\"%d\", &t);\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tscanf(\"%d\", &n);\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tscanf(\"%d\", a + i);\n\t\tfor(int i = 0; i < n + 2; ++i){\n\t\t\tnxt[i] = -1;\n\t\t\tnxtX[i].clear();\n\t\t\tdp[i] = 0;\n\t\t}\n\n\t\tfor(int i = n - 1; i >= 0; --i){\n\t\t\tif(nxtX[i + 1].count(a[i])){\n\t\t\t\tint pos = nxtX[i + 1][a[i]];\n\t\t\t\tassert(pos < n && a[pos] == a[i]);\n\t\t\t\tnxt[i] = pos;\n\t\t\t\tswap(nxtX[i], nxtX[pos + 1]);\n\t\t\t\tif(pos < n - 1)\n\t\t\t\t\tnxtX[i][a[pos + 1]] = pos + 1;\n\t\t\t}\n\t\t\tnxtX[i][a[i]] = i;\n\t\t}\t\n\n\t\tlong long res = 0;\n\t\tfor(int i = n - 1; i >= 0; --i){\n\t\t\tif(nxt[i] == -1) continue;\t\n\t\t\tdp[i] = 1 + dp[nxt[i] + 1];\n\t\t\tres += dp[i];\n\t\t}\n\n\t\tprintf(\"%lld\\n\", res);\n\t}\n\treturn 0;\n} ",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "hashing"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1223",
    "index": "G",
    "title": "Wooden Raft",
    "statement": "Suppose you are stuck on a desert island. The only way to save yourself is to craft a wooden raft and go to the sea. Fortunately, you have a hand-made saw and a forest nearby. Moreover, you've already cut several trees and prepared it to the point that now you have $n$ logs and the $i$-th log has length $a_i$.\n\nThe wooden raft you'd like to build has the following structure: $2$ logs of length $x$ and $x$ logs of length $y$. Such raft would have the area equal to $x \\cdot y$. Both \\textbf{$x$ and $y$ must be integers} since it's the only way you can measure the lengths while being on a desert island. And both \\textbf{$x$ and $y$ must be at least $2$} since the raft that is one log wide is unstable.\n\nYou can cut logs in pieces but you can't merge two logs in one. What is the maximum area of the raft you can craft?",
    "tutorial": "Let's iterate $y$ from $2$ to $A$, where $A = \\max(a_i)$. And let's try to find the best answer for a fixed $y$ in $O(\\frac{A}{y})$ time. How to do so? At first, we can quite easily calculate the total number of logs of length $y$ we can acquire (denote it as $cntY$): since all $a_i \\in [ky, ky + y)$ give the same number of logs which is equal to $k$, then let's just count the number of $a_i$ in $[ky, ky + y)$ for each $k$. We can do so using frequency array and prefix sums on it. There are two cases in the problem: both logs of length $x$ lies in the same log $a_i$ or from the different logs $a_i$ and $a_j$. In the first case it's the same as finding one log of length $2x$. But in both cases we will divide all possible values of $x$ ($2x$) in segments $[ky, ky + y)$ and check each segment in $O(1)$ time. Let's suppose that $2x \\in [ky, ky + y)$ and there is $a_i$ such that $a_i \\ge 2x$ and $(a_i \\mod y) \\ge (2x \\mod y)$. In that case it's optimal to cut $2x$ from $a_i$ and, moreover, it's optimal to increase $2x$ while we can. It leads us straight to the solution, let's keep $\\max(a_i \\mod y)$ over $a_i \\ge ky$ and check only $2x = ky + \\max(a_i \\mod y)$ (maybe minus one in case of wrong parity). We can maintain this max iterating $k$ in descending order. And since $\\max(a_i \\mod y)$ for all $a_i \\in [ky, ky + y)$ is just a $\\max(a_i~|~a_i < ky + y)$. We can find such $a_i$ in $O(1)$ using precalc. To check the chosen $2x$ is trivial: the number of remaining logs $y$ is equal to $cntY - k$ and the plot will have the area $y \\cdot \\min(x, cntY - k)$. The case with cutting $x$-s from different $a_i$ and $a_j$ is based on the same idea, but we need to maintain two maximums $mx1$ and $mx2$ ($mx1 \\ge mx2$). But in this case $x$ can be equal to both $mx1$ or $mx2$. If $x = ky + mx2$ then everything is trivial: the number of logs $y$ is $cntY - 2 \\cdot k$ and so on. If $x = ky + mx1$ then we need to additional check the existence of $a_i \\ge x$ and $a_j \\ge x$. Remaining number of logs $y$ will be equal to $cntY - 2 \\cdot k - 1$ and so on. In result, for each $y$ we can calculate the answer in $O(\\frac{A}{y})$, so the total time complexity is $O(n + \\sum_{y = 2}^{A}{O(\\frac{A}{y})}) = O(n + A \\log A)$. P.S.: We decided to allow the $O(A \\log^2 A)$ solution which binary search $x$ for each $y$ to pass if it's carefully written. 1240F - Football",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) (int)(a).size()\n#define all(a) (a).begin(), (a).end()\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nint n;\nvector<int> a;\n\ninline bool read() {\n    if(!(cin >> n))\n        return false;\n    a.resize(n);\n    fore(i, 0, n)\n        cin >> a[i];\n    return true;\n}\n\ntemplate<class A>\npair<A, A> upd(const pair<A, A> &mx, const A &val) {\n    return {max(mx.x, val), max(mx.y, min(mx.x, val))};\n}\n\nvector<int> cnt, sum;\nvector<int> prv;\n\nli getSum(int l, int r) {\n    return sum[r] - sum[l];\n}\n\nli ans, rx, ry;\nvoid updAns(li x, li y) {\n    if (x < 2 || y < 2)\n        return;\n    if (ans >= x * y)\n        return;\n    ans = x * y;\n    rx = x, ry = y;\n}\n\ninline void solve() {\n    cnt.assign(*max_element(all(a)) + 1, 0);\n    fore(i, 0, n)\n        cnt[a[i]]++;\n    sum.assign(sz(cnt) + 1, 0);\n    fore(i, 0, sz(cnt))\n        sum[i + 1] = sum[i] + cnt[i];\n    prv.assign(sz(cnt), -1);\n    fore(i, 0, sz(prv)) {\n        if(i > 0)\n            prv[i] = prv[i - 1];\n        if(cnt[i] > 0)\n            prv[i] = i;\n    }\n\n    ans = 0;\n    fore(y, 2, sz(cnt)) {\n        li cntY = 0;\n        for(int i = 0; y * i < sz(cnt); i++)\n            cntY += i * 1ll * getSum(i * y, min((i + 1) * y, sz(cnt)));\n\n        pair<pt, pt> mx = {{-1, -1}, {-1, -1}};\n        int lf = (sz(cnt) - 1) / y * y, rg = sz(cnt);\n        while(lf >= 0) {\n            int cntMore = (mx.x.x >= 0) + (mx.y.x >= 0);\n            int val1 = prv[rg - 1];\n            if (val1 >= lf) {\n                mx = upd(mx, pt{val1 % y, val1});\n                if (cnt[val1] == 1)\n                    val1 = prv[val1 - 1];\n                if (val1 >= lf)\n                    mx = upd(mx, pt{val1 % y, val1});\n            }\n\n            if (mx.x.x >= 0) {\n                li x = (lf + mx.x.x) / 2;\n                li cur = cntY - lf / y;\n                updAns(min(cur, x), y);\n            }\n            if (mx.y.x >= 0) {\n                li x = lf + mx.y.x;\n                li cur = cntY - 2 * (lf / y);\n                updAns(min(cur, x), y);\n\n                if(cntMore + (mx.x.y < rg) >= 2) {\n                    x = lf + mx.x.x;\n                    cur--;\n                    updAns(min(cur, x), y);\n                }\n            }\n\n            rg = lf;\n            lf -= y;\n        }\n    }\n    cout << ans << endl;\n    cerr << rx << \" \" << ry << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(0);\n    cin.tie(0), cout.tie(0);\n    cerr << fixed << setprecision(15);\n\n    if(read()) {\n        solve();\n\n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "math",
      "number theory"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1225",
    "index": "A",
    "title": "Forgetting Things",
    "statement": "Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation $a + 1 = b$ with positive integers $a$ and $b$, but Kolya forgot the numbers $a$ and $b$. He does, however, remember that the first (leftmost) digit of $a$ was $d_a$, and the first (leftmost) digit of $b$ was $d_b$.\n\nCan you reconstruct any equation $a + 1 = b$ that satisfies this property? It may be possible that Kolya misremembers the digits, and there is no suitable equation, in which case report so.",
    "tutorial": "The answer exists only if $d_a = d_b$, $d_b = d_a + 1$, or $d_a = 9$ and $d_b = 1$. Alternatively, one could simply check all $a$ up to 100 (or another reasoable bound).",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1225",
    "index": "B1",
    "title": "TV Subscriptions (Easy Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints.}\n\nThe BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \\dots, a_n$ ($1 \\le a_i \\le k$), where $a_i$ is the show, the episode of which will be shown in $i$-th day.\n\nThe subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.\n\nHow many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $d$ ($1 \\le d \\le n$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $d$ consecutive days in which all episodes belong to the purchased shows.",
    "tutorial": "We are looking for a segment of length $d$ with the smallest number of distinct values. In small limitations one could just try all segments and count the number of distinct elements naively (for example, by sorting or with an std::set).",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1225",
    "index": "B2",
    "title": "TV Subscriptions (Hard Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints.}\n\nThe BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \\dots, a_n$ ($1 \\le a_i \\le k$), where $a_i$ is the show, the episode of which will be shown in $i$-th day.\n\nThe subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.\n\nHow many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $d$ ($1 \\le d \\le n$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $d$ consecutive days in which all episodes belong to the purchased shows.",
    "tutorial": "In larger limitations we have to use two pointers to maintain the number of distinct elements between segments. We can store a map or an array that counts the number of occurences of each element, as well as the number of distinct elements (i.e. the number of non-zero entries in the map). Moving the segment to the right involves changing two entries of the map, keeping track of which entries become/cease to be non-zero. The complexity is $O(n \\log n)$ or $O(n)$ (both are acceptable).",
    "tags": [
      "implementation",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1225",
    "index": "C",
    "title": "p-binary",
    "statement": "Vasya will fancy any number as long as it is an integer power of two. Petya, on the other hand, is very conservative and only likes a single integer $p$ (which may be positive, negative, or zero). To combine their tastes, they invented $p$-binary numbers of the form $2^x + p$, where $x$ is a \\textbf{non-negative} integer.\n\nFor example, some $-9$-binary (\"minus nine\" binary) numbers are: $-8$ (minus eight), $7$ and $1015$ ($-8=2^0-9$, $7=2^4-9$, $1015=2^{10}-9$).\n\nThe boys now use $p$-binary numbers to represent everything. They now face a problem: given a positive integer $n$, what's the smallest number of $p$-binary numbers (not necessarily distinct) they need to represent $n$ as their sum? It may be possible that representation is impossible altogether. Help them solve this problem.\n\nFor example, if $p=0$ we can represent $7$ as $2^0 + 2^1 + 2^2$.\n\nAnd if $p=-9$ we can represent $7$ as one number $(2^4-9)$.\n\nNote that negative $p$-binary numbers are allowed to be in the sum (see the Notes section for an example).",
    "tutorial": "Suppose we want to represent $n$ as the sum of $k$ $p$-binary numbers. We must have $n = \\sum_{i = 1}^k (2^{x_i} + p)$ for a suitable choice of $x_1, \\ldots, x_k$. Moving all $p$'s to the left-hand side, we must have $n - kp = \\sum_{i=1}^k 2^{x_i}$. In particular, $n - kp$ has to be at least $k$. Consider the binary representation of $n - kp$. If it has more than $k$ bits equal to $1$, there is no way we can split it into $k$ powers of two. Otherwise, we can start by taking the binary representation, and if it contains less than $k$ powers, we can always split larger powers into two smaller ones. We can now check all values of $k$ starting from the smallest. If $n \\geq 31p + 31$, then the answer will not exceed $31$ since $n - 31p$ is less than $2^{31}$, hence is always representable with $31$ powers. Otherwise, we have $n - 31(p + 1) < 0$. Since $n > 0$, it means that $p + 1 < 0$, and $n - kp < k$ for all $k > 31$, thus the answer does not exist.",
    "tags": [
      "bitmasks",
      "brute force",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1225",
    "index": "D",
    "title": "Power Products",
    "statement": "You are given $n$ positive integers $a_1, \\ldots, a_n$, and an integer $k \\geq 2$. Count the number of pairs $i, j$ such that $1 \\leq i < j \\leq n$, and there exists an integer $x$ such that $a_i \\cdot a_j = x^k$.",
    "tutorial": "Suppose that $x \\cdot y$ is a $k$-th power. The sufficient and necessary condition for that is: for any prime $p$, the total number of times it divides $x$ and $y$ must be divisible by $k$. Let us factorize each number $a_i = p_1^{b_1} \\ldots p_m^{b_m}$, and associate the list of pairs $L_i ((p_1, b_1 \\bmod k), \\ldots, (p_m, b_m \\bmod k))$, omitting the entries with $b_i \\bmod k = 0$. For example, for $360 = 2^3 2^2 5^1$ and $k = 2$, the corresponding list would be $((2, 1), (5, 1))$. If $a_i \\cdot a_j$ is a $k$-th power the the primes in the respective lists should match, and $b_i \\bmod k$ add up to $k$ for corresponding primes. Indeed, if a prime is absent from one of the lists (i.e. the exponent is divisible by $k$), then it should be absent from the other list too. Otherwise, the total exponent for this prime should be divisible by $k$, hence the remainders should add up to $k$. We now have that for every $a_i$ there is a unique possible list $L'_i$ for the other number that would give a $k$-th power product. We can now maintain the count for each of the occuring lists (e.g. with std::map), and every number we meet we add the number of occurences of $L'_i$ to the answer, and increase the count for $L_i$ by one. The total complexity comprises of factoring all the input numbers (in $O(\\sqrt{max a_i})$ or in $O(\\log \\max a_i)$ with precomputed sieve), and maintaining a map from vectors to numbers. The total size of all vectors is roughly $O(n \\log n)$, so the complexity of maintaining a map is $O(n \\log ^2 n)$, or $O(n \\log n)$ with a hashmap.",
    "tags": [
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1225",
    "index": "E",
    "title": "Rock Is Push",
    "statement": "You are at the top left cell $(1, 1)$ of an $n \\times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, y + 1)$, while moving down takes you to the cell $(x + 1, y)$.\n\nSome cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on.\n\nThe labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal.\n\nCount the number of different legal paths you can take from the start to the goal modulo $10^9 + 7$. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other.",
    "tutorial": "Let us compute $R_{i, j}$ and $D_{i, j}$ - the number of legal ways to reach the goal assuming: we've arrived at the cell $(i, j)$; our next move is right/down respectively; our previous move (if there was a previous move) was not in the same direction. By definition, let us put $D_{n, m} = R_{n, m} = 1$. We can see that all rocks reachable from $(i, j)$ in these assumptions should be in their original places, thus the answer is independent of the way we've reached the cell $(i, j)$ in the first place. Recalculation is fairly straightforward. For example, for $D_{i, j}$ let $k$ be the number of stones directly below $(i, j)$. We can make at most $n - k - i$ moves before we make the turn to the right, thus we have $D_{i, j} = \\sum_{t = 1}^{n - k - i} R_{i + t, j}$. This allows to compute $R_{i, j}$ and $D_{i, j}$ with dynamic programming starting from the cells with larger coordinates. The formula hints at some range summing techniques, like computing prefix sums or maintaing a more sophisticated RSQ structure. However, these are not needed in this problem. Indeed, as we consider summation ranges for $D_{i, j}$ and $D_{i + 1, j}$, we can see that they differ by at most one entry on each side. It follows that to compute $D_{i, j}$, we can take $D_{i, j}$ and add/subtract at most two values of $R_{i + t, j}$. The values near the goal cell may need some extra treatment since they are not always a proper range sum. Also, the case $n = m = 1$ need to be treated separately. The total complexity is $O(nm)$ (additional $\\log$ for RSQ should be fine though).",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1225",
    "index": "F",
    "title": "Tree Factory",
    "statement": "Bytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order.\n\nThe tree in question is a rooted tree with $n$ vertices labelled with distinct integers from $0$ to $n - 1$. The vertex labelled $0$ is the root of the tree, and for any non-root vertex $v$ the label of its parent $p(v)$ is less than the label of $v$.\n\nAll trees at the factory are made from bamboo blanks. A bamboo is a rooted tree such that each vertex has exactly one child, except for a single leaf vertex with no children. The vertices of a bamboo blank can be labelled arbitrarily before its processing is started.\n\nTo process a bamboo into another tree a single type of operation can be made: choose an arbitrary non-root vertex $v$ such that its parent $p(v)$ is not a root either. The operation consists of changing the parent of $v$ to its parent's parent $p(p(v))$. Note that parents of all other vertices remain unchanged, in particular, the subtree of $v$ does not change.\n\nEfficiency is crucial, hence you have to minimize the number of operations to make the desired tree from a bamboo blank. Construct any optimal sequence of operations to produce the desired tree.\n\nNote that the labelling of the resulting tree has to coincide with the labelling of the desired tree. Formally, the labels of the roots have to be equal, and for non-root vertices with the same label the labels of their parents should be the same.\n\nIt is guaranteed that for any test present in this problem an answer exists, and further, an optimal sequence contains at most $10^6$ operations. Note that \\textbf{any hack that does not meet these conditions will be invalid}.",
    "tutorial": "Let's solve the problem backwards: given a tree, transform it into a bamboo with reverse operations. A reverse operation in this context looks like this: given a vertex $v$ and its two distinct children $u$ and $w$, make $w$ the parent of $u$. What's the lower bound on the number of operations we need to make? We can see that the depth of the tree, i.e. the length of the longest vertical path starting from the root, can increase by at most one per operation. On the other hand, the depth of the bamboo is $n - 1$. Therefore, we'll need to make at least $n - 1 - (\\text{initial depth of the tree})$ operations. This number would always be enough if for any non-bamboo tree we could find an operation that would increase its depth. And indeed we can: consider a longest path starting from the root. If all its vertices have at most one children, the tree is a bamboo and we are done. Otherwise, take any vertex $v$ on the path with at least two children, its child $u$ on the longest path, and any other child $w$, then make $w$ the parent of $u$. One can see that there is a longer path now. One efficient way to do these operations successively is to keep track of the lowest candidate for $u$. After applying an operation, the candidate is either $u$ again, or one of its ancestors. With standard amortized analysis, we can now perform all these operations in $O(n)$ time. To output the answer, print the labelling of the final bamboo you obtain, followed by the reverse sequence of the operations you've made.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1225",
    "index": "G",
    "title": "To Make 1",
    "statement": "There are $n$ positive integers written on the blackboard. Also, a positive number $k \\geq 2$ is chosen, and none of the numbers on the blackboard are divisible by $k$. In one operation, you can choose any two integers $x$ and $y$, erase them and write one extra number $f(x + y)$, where $f(x)$ is equal to $x$ if $x$ is not divisible by $k$, otherwise $f(x) = f(x / k)$.\n\nIn the end, there will be a single number of the blackboard. Is it possible to make the final number equal to $1$? If so, restore any sequence of operations to do so.",
    "tutorial": "An experienced eye will immediately spot a subset dynamic programming solution in roughly $O(3^n \\sum a_i)$ time, but the time constraints will not allow this. What to do? Suppose there is a way to obtain 1 in the end. Looking at how many times each initial number $a_i$ gets divided by $k$ (including the divisions of the subsequent numbers containing it), we can obtain the expression $1 = \\sum_{i = 1}^n a_i k^{-b_i}$, where $b_i$ are respective numbers of divisions. What if we were given such an expression to start with? Can we always restore a sequence of operations? As it turns out, yes! Prove by induction. If there a single number, then it must be $1$ and we are done. Otherwise, let $B = \\max b_i$. We argue that there are at least two numbers $a_i$ and $a_j$ with $b_i = b_j = B$. Indeed, assume there was only one such number $a_j$. Multiply both sides of the expression to obtain $k^B = \\sum_{i = 1}^n a_i k^{B - b_i}$. The left-hand side, and all but one summand of the right-hand are divisible by $k$. But since $a_j$ is not divisible by $k$, the right-hand side is not divisible by $k$, a contradiction. Since we have two numbers $a_i$ and $a_j$, let's replace them with $f(a_i + a_j) = a'$, and put $b' = B - (\\text{the number of times }(a_i + a_j)\\text{ is divisible by }k)$. We can see that the new set of numbers still satisfies the expression above, hence by induction hypothesis we can always finish the operation sequence. Note that this argument can be converted into an answer restoration routine: given the numbers $b_i$, group any pair of numbers $a_i$ and $a_j$ with $b_i = b_j$. The question now becomes: can we find suitable numbers $b_1, \\ldots, b_n$ such that the above expression is satisfied? We can do this with a more refined subset dynamic programming. For a subset $S \\subseteq \\{1, \\ldots, n\\}$ and a number $x$, let $dp_{S, x}$ be true if and only if we can have an expression $x = \\sum_{i \\in S} a_i k^{-b_i}$ for suitable $b_i$. The initial state is $dp_{\\varnothing, 0} = 1$. The transitions are as follows: include $a_i$ into $S$: $dp_{S, x} \\implies dp_{S + a_i, x + a_i}$; increase all $b_i$ by 1: if $x$ is divisible by $k$, then $dp_{S, x} \\implies dp_{S, x / k}$. By definition, we can obtain 1 as the final number iff $dp_{\\{1, \\ldots, n\\}, 1}$. Straightforward recalculation requires $O(n 2^n \\cdot \\sum a_i)$ time. However, the first type of transition can be optimized using bitsets, bringing the complexity down to $O(2^n \\sum a_i \\cdot (1 + n / w))$, where $w$ is the size of the machine word ($32$ or $64$). To restore $b_i$, trace back from $dp_{\\{1, \\ldots, n\\}, 1}$ to $dp_{\\varnothing, 0}$ using reachable states.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy",
      "number theory"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1227",
    "index": "A",
    "title": "Math Problem",
    "statement": "Your math teacher gave you the following problem:\n\nThere are $n$ segments on the $x$-axis, $[l_1; r_1], [l_2; r_2], \\ldots, [l_n; r_n]$. The segment $[l; r]$ includes the bounds, i.e. it is a set of such $x$ that $l \\le x \\le r$. The length of the segment $[l; r]$ is equal to $r - l$.\n\nTwo segments $[a; b]$ and $[c; d]$ have a common point (intersect) if there exists $x$ that $a \\leq x \\leq b$ and $c \\leq x \\leq d$. For example, $[2; 5]$ and $[3; 10]$ have a common point, but $[5; 6]$ and $[1; 4]$ don't have.\n\nYou should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $n$ segments.\n\nIn other words, you need to find a segment $[a; b]$, such that $[a; b]$ and every $[l_i; r_i]$ have a common point for each $i$, and $b-a$ is minimal.",
    "tutorial": "Find the left most right point for all segments, call it $r_{min}$. The right most left point for all segments, call it $l_{max}$. It's easy to see that the answer is $\\max(0,l_{max} - r_{min})$.",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1227",
    "index": "B",
    "title": "Box",
    "statement": "Permutation $p$ is a sequence of integers $p=[p_1, p_2, \\dots, p_n]$, consisting of $n$ distinct (unique) positive integers between $1$ and $n$, inclusive. For example, the following sequences are permutations: $[3, 4, 1, 2]$, $[1]$, $[1, 2]$. The following sequences are not permutations: $[0]$, $[1, 2, 1]$, $[2, 3]$, $[0, 1, 2]$.\n\nThe important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $p$ of length $n$.\n\nYou don't know this permutation, you only know the array $q$ of prefix maximums of this permutation. Formally:\n\n- $q_1=p_1$,\n- $q_2=\\max(p_1, p_2)$,\n- $q_3=\\max(p_1, p_2,p_3)$,\n- ...\n- $q_n=\\max(p_1, p_2,\\dots,p_n)$.\n\nYou want to construct any possible suitable permutation (i.e. any such permutation, that calculated $q$ for this permutation is equal to the given array).",
    "tutorial": "Obviously, if $q_{i} \\neq q_{i-1}$ then $p_{i} = q_{i}$. We assume $q_{0} = 0$. Other positions can be filled with the left numbers in increasing order. Then check whether the permutation is correct or not.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1227",
    "index": "C",
    "title": "Messy",
    "statement": "You are fed up with your messy room, so you decided to clean it up.\n\nYour room is a bracket sequence $s=s_{1}s_{2}\\dots s_{n}$ of length $n$. Each character of this string is either an opening bracket '(' or a closing bracket ')'.\n\nIn one operation you can choose any consecutive substring of $s$ and reverse it. In other words, you can choose any substring $s[l \\dots r]=s_l, s_{l+1}, \\dots, s_r$ and change the order of elements in it into $s_r, s_{r-1}, \\dots, s_{l}$.\n\nFor example, if you will decide to reverse substring $s[2 \\dots 4]$ of string $s=$\"{(\\textbf{(()}))}\" it will be equal to $s=$\"{(\\textbf{)((}))}\".\n\nA regular (aka balanced) bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences \"()()\", \"(())\" are regular (the resulting expressions are: \"(1)+(1)\", \"((1+1)+1)\"), and \")(\" and \"(\" are not.\n\nA prefix of a string $s$ is a substring that starts at position $1$. For example, for $s=$\"(())()\" there are $6$ prefixes: \"(\", \"((\", \"(()\", \"(())\", \"(())(\" and \"(())()\".\n\nIn your opinion, a neat and clean room $s$ is a bracket sequence that:\n\n- the whole string $s$ is a regular bracket sequence;\n- \\textbf{and} there are exactly $k$ prefixes of this sequence which are regular (including whole $s$ itself).\n\nFor example, if $k = 2$, then \"(())()\" is a neat and clean room.\n\nYou want to use at most $n$ operations to make your room neat and clean. Operations are applied one after another sequentially.\n\nIt is guaranteed that the answer exists. Note that you \\textbf{do not need} to minimize the number of operations: find any way to achieve the desired configuration in $n$ or less operations.",
    "tutorial": "It's easy to construct a valid bracket sequence, for example \"()()()() ... (((...(())...))))\". Now let the initial bracket sequence be $s$, the target one be $t$. For each position, if $s_{i} = t_{i}$ then we needn't do anything, otherwise find a position $j$ which $j > i$ and $s_{j} = t_{i}$ (it exists), and reverse the segment $[i \\dots j]$. The number of operations is at most $n$, and the solution works in $O(n^{2})$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1227",
    "index": "D2",
    "title": "Optimal Subsequences (Hard Version)",
    "statement": "This is the harder version of the problem. In this version, $1 \\le n, m \\le 2\\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.\n\nYou are given a sequence of integers $a=[a_1,a_2,\\dots,a_n]$ of length $n$. Its subsequence is obtained by removing zero or more elements from the sequence $a$ (they do not necessarily go consecutively). For example, for the sequence $a=[11,20,11,33,11,20,11]$:\n\n- $[11,20,11,33,11,20,11]$, $[11,20,11,33,11,20]$, $[11,11,11,11]$, $[20]$, $[33,20]$ are subsequences (these are just some of the long list);\n- $[40]$, $[33,33]$, $[33,20,20]$, $[20,20,11,11]$ are not subsequences.\n\nSuppose that an additional non-negative integer $k$ ($1 \\le k \\le n$) is given, then the subsequence is called optimal if:\n\n- it has a length of $k$ and the sum of its elements is the maximum possible among all subsequences of length $k$;\n- and among all subsequences of length $k$ that satisfy the previous item, it is lexicographically minimal.\n\nRecall that the sequence $b=[b_1, b_2, \\dots, b_k]$ is lexicographically smaller than the sequence $c=[c_1, c_2, \\dots, c_k]$ if the first element (from the left) in which they differ less in the sequence $b$ than in $c$. Formally: there exists $t$ ($1 \\le t \\le k$) such that $b_1=c_1$, $b_2=c_2$, ..., $b_{t-1}=c_{t-1}$ and at the same time $b_t<c_t$. For example:\n\n- $[10, 20, 20]$ lexicographically less than $[10, 21, 1]$,\n- $[7, 99, 99]$ is lexicographically less than $[10, 21, 1]$,\n- $[10, 21, 0]$ is lexicographically less than $[10, 21, 1]$.\n\nYou are given a sequence of $a=[a_1,a_2,\\dots,a_n]$ and $m$ requests, each consisting of two numbers $k_j$ and $pos_j$ ($1 \\le k \\le n$, $1 \\le pos_j \\le k_j$). For each query, print the value that is in the index $pos_j$ of the optimal subsequence of the given sequence $a$ for $k=k_j$.\n\nFor example, if $n=4$, $a=[10,20,30,20]$, $k_j=2$, then the optimal subsequence is $[20,30]$ — it is the minimum lexicographically among all subsequences of length $2$ with the maximum total sum of items. Thus, the answer to the request $k_j=2$, $pos_j=1$ is the number $20$, and the answer to the request $k_j=2$, $pos_j=2$ is the number $30$.",
    "tutorial": "Let's first solve the simplified version (Easy Version) without paying attention to the efficiency of the algorithm. It is clear that the sum of the elements of the optimal subsequence is equal to the sum of $k$ maximal elements of the sequence $a$. Let the smallest (the $k$-th) of $k$ maximal elements be $x$. Obviously, all elements of $a$ that are greater than $x$ and several elements that are equal to $x$ will be included in the optimal subsequence. Among all the elements that are equal to $x$ you need to choose those that are located to the left. Thus, a simplified version solution might look like this: in order to build an optimal subsequence of length $k$, take an array $a$ and construct its copy $b$ sorted by non-increasing: $b_1 \\ge b_2 \\ge \\dots \\ge b_n$; let $x = b_k$; we take the following subsequence from $a$: all the elements $a_i > x$ and several leftmost occurrences of $a_i = x$ (you need to take such occurrences in order to get exactly $k$ elements in total). To solve the complicated version, we note that the solution above is equivalent to sorting all elements of $a$ first of all by value (non-increasing), and secondly by position (ascending). The desired optimal subsequence is simply $k$ first elements of $a$ in this order. To quickly process requests, we will use the opportunity to read all requests in the program, sort them by $k_j$ and process them in that order. Then, in order to answer the request $k_j$, $pos_j$ you need to take $k_j$ elements in this order and choose the $pos_j$-th from them (just in the order of indices). Thus, the problem is reduced to finding the $pos$-th element in a set, where only elements are added. This can be solved using a wide range of data structures (a tree of segments, a Fenwick tree, even sqrt-compositions), and using a non-standard tree built into g++ that supports the operation \"quickly find the $pos$ th element of a set\". Below is the solution code:",
    "code": "#include <bits/stdc++.h>\n\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\n\nint main() {\n    int n;\n    cin >> n;    \n\n    vector<int> a(n);\n    vector<pair<int,int>> b;\n    forn(i, n) {\n        cin >> a[i];\n        b.push_back({-a[i], i});\n    }\n    sort(b.begin(), b.end());\n\n    int m;\n    cin >> m;\n    vector<pair<pair<int,int>,int>> req(m);\n    forn(i, m) {\n        cin >> req[i].first.first >> req[i].first.second;\n        req[i].second = i;\n    }\n    sort(req.begin(), req.end());\n\n    vector<int> ans(m);\n    ordered_set pos;\n    int len = 0;\n    forn(i, m) {\n        while (len < req[i].first.first)\n            pos.insert(b[len++].second);\n        ans[req[i].second] = a[*pos.find_by_order(req[i].first.second - 1)];\n    }\n\n    forn(i, m)\n        cout << ans[i] << endl;\n}\n",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1227",
    "index": "E",
    "title": "Arson In Berland Forest",
    "statement": "The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.\n\nA destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a $n \\times m$ rectangle map which represents the damaged part of the Forest. The damaged trees were marked as \"X\" while the remaining ones were marked as \".\". \\textbf{You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.}\n\nThe firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as $0$) some trees were set on fire. At the beginning of minute $0$, only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of $8$ neighboring trees. At the beginning of minute $T$, the fire was extinguished.\n\nThe firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of $T$ (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of $T$ (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.\n\nNote that you'd like to maximize value $T$ but the set of trees can be arbitrary.",
    "tutorial": "Let's note that if there is a possible configuration in which the forest burnt $T$ minutes then there is a configuration when the forest burnt $T - 1$ minutes. So we can binary search the answer. Now we need to check the existence of the configuration for a fixed time $T$. Let's find all trees that can be set on fire. There are two equivalent conditions for such trees: either the square of length $2T + 1$ with a center in this cell contains only X-s or a distance between the current cell and any cell with \".\" (or border) is more or equal to $T$. We can use any of the conditions. The first condition can be checked with prefix sums on 2D - we can precalculate them one time and use them to take a sum on a rectangle. The second condition can be checked by running bfs from all \".\"-s or borders (or from X-s which are neighboring to \".\"-s or to the borders) also one time before the binary search. The second step is to check that it's possible to cover all burnt trees starting from all set-on-fire trees. We can check it either with \"add value on a rectangle\" (using prefix sums) since each set-on-fire tree will burn a $(2T + 1) \\times (2T + 1)$ square with center in it. Or, alternatively, we can run bfs from set-on-fire trees. Anyways, both algorithms have $O(nm)$ complexity. And, since all damaged trees are shown on the map, the answer can't be more than $\\min(n, m)$. So, the total complexity is $O(nm \\log(\\min(n, m)))$.",
    "tags": [
      "binary search",
      "graphs",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1227",
    "index": "F1",
    "title": "Wrong Answer on test 233 (Easy Version)",
    "statement": "\\begin{quote}\nYour program fails again. This time it gets \"Wrong answer on test 233\"\n\\end{quote}\n\n.This is the easier version of the problem. In this version $1 \\le n \\le 2000$. You can hack this problem only if you solve and lock both problems.\n\nThe problem is about a test containing $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \\dots, h_n$ are known to you in this problem.\n\nHowever, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.\n\nFormally, the mistake moves the answer for the question $i$ to the question $i \\bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$.\n\nWe call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total.\n\nYou're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\\,244\\,353$.\n\nFor example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.",
    "tutorial": "First of all, special judge for $k = 1$, where the answer is zero. Let $d$ be the difference between the points for latest answer suit and the previous one. An valid answer suit means $d > 0$. For positions satisfying $h_{i} = h_{i \\space \\mod \\space n + 1}$, the answer for this position will not affect $d$. Assume there's $t$ positions which $h_{i} \\neq h_{i \\space \\mod \\space n + 1}$. For a fixed position $i$ which $h_{i} \\neq h_{i \\space \\mod \\space n + 1}$, let your answer for this position is $a_{i}$ . If $a_{i} = h_{i}$, then the $d$ value will decrease by 1. We call this kind of position as a decreasing position. If $a_{i} = h_{i \\space \\mod \\space n + 1}$, then the $d$ value increase by 1. We call this kind of position as a increasing position. Otherwise $d$ value will not be affected, we call this kind of position zero position. Obviously the number of increasing position should be exact larger then the decreasing position. So let's enumerate the number of zero positions. We can find the answer is equal to $k^{n-t} \\times \\sum_{0 \\leq i \\leq t - 1}{[(k-2)^i \\times \\binom{t}{i} \\times \\sum_{[\\frac{t-i}{2}]+1 \\leq j \\leq t - i}{\\binom{t-i}{j}}]}$. $i$ represent the number of zero positions and $j$ represent the number of increasing positions. The only problem is how to calculate $\\sum_{[\\frac{t-i}{2}]+1 \\leq j \\leq t - i}{\\binom{t-i}{j}}$ quickly. Due to $\\binom{n}{x} = \\binom{n}{n-x}$, we can tell that when $t - i$ is odd, $\\sum_{[\\frac{t-i}{2}]+1 \\leq j \\leq t - i}{\\binom{t-i}{j}} = 2^{t-i-1}$. Otherwise it is equal to $\\frac{2^{t-i} - \\binom{t-i}{\\frac{t-i}{2}}}{2}$.",
    "tags": [
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1227",
    "index": "F2",
    "title": "Wrong Answer on test 233 (Hard Version)",
    "statement": "\\begin{quote}\nYour program fails again. This time it gets \"Wrong answer on test 233\"\n\\end{quote}\n\n.This is the harder version of the problem. In this version, $1 \\le n \\le 2\\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.\n\nThe problem is to finish $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \\dots, h_n$ are known to you in this problem.\n\nHowever, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.\n\nFormally, the mistake moves the answer for the question $i$ to the question $i \\bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$.\n\nWe call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total.\n\nYou're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\\,244\\,353$.\n\nFor example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.",
    "tutorial": "First of all, special judge for $k = 1$, where the answer is zero. Let $d$ be the difference between the points for latest answer suit and the previous one. An valid answer suit means $d > 0$. For positions satisfying $h_{i} = h_{i \\space \\mod \\space n + 1}$, the answer for this position will not affect $d$. Assume there's $t$ positions which $h_{i} \\neq h_{i \\space \\mod \\space n + 1}$. For a fixed position $i$ which $h_{i} \\neq h_{i \\space \\mod \\space n + 1}$, let your answer for this position is $a_{i}$ . If $a_{i} = h_{i}$, then the $d$ value will decrease by 1. We call this kind of position as a decreasing position. If $a_{i} = h_{i \\space \\mod \\space n + 1}$, then the $d$ value increase by 1. We call this kind of position as a increasing position. Otherwise $d$ value will not be affected, we call this kind of position zero position. Obviously the number of increasing position should be exact larger then the decreasing position. So let's enumerate the number of zero positions. We can find the answer is equal to $k^{n-t} \\times \\sum_{0 \\leq i \\leq t - 1}{[(k-2)^i \\times \\binom{t}{i} \\times \\sum_{[\\frac{t-i}{2}]+1 \\leq j \\leq t - i}{\\binom{t-i}{j}}]}$. $i$ represent the number of zero positions and $j$ represent the number of increasing positions. The only problem is how to calculate $\\sum_{[\\frac{t-i}{2}]+1 \\leq j \\leq t - i}{\\binom{t-i}{j}}$ quickly. Due to $\\binom{n}{x} = \\binom{n}{n-x}$, we can tell that when $t - i$ is odd, $\\sum_{[\\frac{t-i}{2}]+1 \\leq j \\leq t - i}{\\binom{t-i}{j}} = 2^{t-i-1}$. Otherwise it is equal to $\\frac{2^{t-i} - \\binom{t-i}{\\frac{t-i}{2}}}{2}$.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1227",
    "index": "G",
    "title": "Not Same",
    "statement": "You are given an integer array $a_1, a_2, \\dots, a_n$, where $a_i$ represents the number of blocks at the $i$-th position. It is guaranteed that $1 \\le a_i \\le n$.\n\nIn one operation you can choose a subset of indices of the given array and remove one block in each of these indices. You can't remove a block from a position without blocks.\n\nAll subsets that you choose should be different (unique).\n\nYou need to remove all blocks in the array using at most $n+1$ operations. It can be proved that the answer always exists.",
    "tutorial": "The solution can be inspired by the output format :) First of all, sort all numbers in decreasing order. Let them be $A_{1}, A_{2} \\dots , A_{n}$. We will construct the answer column by column. Let us use a set of binary string to represent a series of operations. For example $\\lbrace 10,10,10,11 \\rbrace$ represent operations for $\\lbrace 4,1\\rbrace$(invalid, however). Then we compress the same operations in a operation set as the number of this operation occurs. For example, $\\lbrace 10,10,10,11 \\rbrace$ can be compressed as $\\lbrace 3,1 \\rbrace$ as there's three $10$ and one $11$. Note we do not care whether the operation is, we only care how many times it occurs. Now, as we construct the answer column by column, new numbers will be added. A new number can split some elements in the compress set. For example, we add a new $1$ in $\\lbrace 4,1 \\rbrace$ as it becomes $\\lbrace 4,1,1 \\rbrace$. We can turn the operation set $\\lbrace 10,10,10,11 \\rbrace$ into $\\lbrace 100,100,101,11 \\rbrace$, while the compress set turns $\\lbrace 2,1,1 \\rbrace$ from $\\lbrace 3,1 \\rbrace$. In general, we can turn $\\lbrace X \\rbrace$ into $\\lbrace Y , X - Y \\rbrace$ uses a number $X(1 \\leq Y < X)$. Special condition: $\\lbrace Y \\rbrace$ can keep same but use number $Y$. Special judge for $A_{1} = 1$, thus we use one operation to erase all numbers. Obviously the first compress set is $\\lbrace A_{1} \\rbrace$, represent operation set $\\lbrace 1,1,1,1, \\dots ,1 \\rbrace$. If $A_{1} = A_{2}$, turn the second compress set as $\\lbrace 1,A_{1} - 1,1 \\rbrace$, otherwise turn it as $\\lbrace A_{2} , A_{1} - A_{2} \\rbrace$. Then we maintain the compress set by keeping the sum of the elements same but the number of the elements strictly increasing. For a current compress set, let $X$ be the minimal element, and $Y$ be the new number added. If $Y < X$, split $X$ into $\\lbrace Y , X - Y \\rbrace$. Otherwise split $X$ into $\\lbrace 1 , X - 1 \\rbrace$, the left number $(Y-X+1)$ can be randomly placed. The left number can be randomly placed if and if only the sum of the elements is larger then $Y$. Obviously the sum of the elements equals to $A_{1}$ or $A_{1} + 1$. If the sum of the elements equals to $A_{1}$, then $Y \\leq A_{2} < A_{1}$. After all split operations, the compress set must be $\\lbrace 1,1,1 \\dots ,1 \\rbrace$, which means all operation differ from each other. We can construct the final answer now in $O(n^2)$ .",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1228",
    "index": "A",
    "title": "Distinct Digits",
    "statement": "You have two integers $l$ and $r$. Find an integer $x$ which satisfies the conditions below:\n\n- $l \\le x \\le r$.\n- All digits of $x$ are different.\n\nIf there are multiple answers, print any of them.",
    "tutorial": "Let's see how to check if all digits of $x$ are different. Since there can be only $10$ different numbers($0$ to $9$) in single digit, you can count the occurrences of $10$ numbers by looking all digits of $x$. You can count all digits by using modulo $10$ or changing whole number to string. For example, if $x = 1217$, then occurrence of each number will be $[0, 2, 1, 0, 0, 0, 0, 1, 0, 0]$, because there are two $1$s, single $2$ and single $7$ in $x$. So $1217$ is invalid number. Now do the same thing for all $x$ where $l \\le x \\le r$. If you find any valid number then print it. Otherwise print $-1$. Time complexity is $O((r-l) \\log r)$.",
    "code": "# Return if given number's digits are distinct.\ndef is_distinct(x):\n    return len(set(str(x))) == len(str(x))\n \nL, R = [int(c) for c in input().split()]\nfound = False\nfor i in range(L, R+1):\n    if is_distinct(i):\n        found = True\n        print(i)\n        break\nif not found: print(-1)",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1228",
    "index": "B",
    "title": "Filling the Grid",
    "statement": "Suppose there is a $h \\times w$ grid consisting of empty or full cells. Let's make some definitions:\n\n- $r_{i}$ is the number of consecutive full cells connected to the left side in the $i$-th row ($1 \\le i \\le h$). In particular, $r_i=0$ if the leftmost cell of the $i$-th row is empty.\n- $c_{j}$ is the number of consecutive full cells connected to the top end in the $j$-th column ($1 \\le j \\le w$). In particular, $c_j=0$ if the topmost cell of the $j$-th column is empty.\n\nIn other words, the $i$-th row starts exactly with $r_i$ full cells. Similarly, the $j$-th column starts exactly with $c_j$ full cells.\n\n\\begin{center}\n{\\small These are the $r$ and $c$ values of some $3 \\times 4$ grid. Black cells are full and white cells are empty.}\n\\end{center}\n\nYou have values of $r$ and $c$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $r$ and $c$. Since the answer can be very large, find the answer modulo $1000000007\\,(10^{9} + 7)$. In other words, find the remainder after division of the answer by $1000000007\\,(10^{9} + 7)$.",
    "tutorial": "You can see some observations below; $r$ and $c$ values reserves some cells to be full, and some cells to be empty. Because they have to satisfy number of consecutive full cells in their row/column. If some cell is reserved to be full by some values and reserved to be empty by some other values, then it is impossible to fill grid. Let's call this kind of cell as invalid cell. If there is no invalid cell, then the answer is $2^{unreserved}$ where $unreserved$ means the number of unreserved cells, because setting state of unreserved cells doesn't affect validity of grid. For easier understanding, please look at the pictures below. Black cells are reserved to be full by some $r$ or $c$ value. White X cells are reserved to be empty by some $r$ or $c$ value. White ? cells are unreserved cells. Red X cells are invalid cells. This is the explanation of the first example. There is $1$ unreserved cell, so the answer is $2$. This is one of the impossible cases. That red X cell is reserved to be full by $r_{3}$, but reserved to be empty by $c_{2}$. So this is impossible. Time complexity is $O(wh)$.",
    "code": "# Get input\nh, w = [int(z) for z in input().split()]\nr = [int(z) for z in input().split()]\nc = [int(z) for z in input().split()]\nmod = 10**9 + 7\n \n# Make grid\ngrid = [['?' for col in range(w+1)] for row in range(h+1)]\ndef try_set(row, col, target):\n    if grid[row][col] == '?':\n        grid[row][col] = target\n    elif grid[row][col] != target:\n        raise ValueError\n \ndef go():\n    try:\n        for row in range(h):\n            for col in range(r[row]):\n                try_set(row, col, 'FULL')\n            try_set(row, r[row], 'EMPTY')\n        for col in range(w):\n            for row in range(c[col]):\n                try_set(row, col, 'FULL')\n            try_set(c[col], col, 'EMPTY')\n    except ValueError:\n        return 0\n    answer = 1\n    for row in range(h):\n        for col in range(w):\n            if grid[row][col] == '?': answer = answer * 2 % mod\n    return answer\n    \nprint(go())",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1228",
    "index": "C",
    "title": "Primes and Multiplication",
    "statement": "Let's introduce some definitions that will be needed later.\n\nLet $prime(x)$ be the set of prime divisors of $x$. For example, $prime(140) = \\{ 2, 5, 7 \\}$, $prime(169) = \\{ 13 \\}$.\n\nLet $g(x, p)$ be the maximum possible integer $p^k$ where $k$ is an integer such that $x$ is divisible by $p^k$. For example:\n\n- $g(45, 3) = 9$ ($45$ is divisible by $3^2=9$ but not divisible by $3^3=27$),\n- $g(63, 7) = 7$ ($63$ is divisible by $7^1=7$ but not divisible by $7^2=49$).\n\nLet $f(x, y)$ be the product of $g(y, p)$ for all $p$ in $prime(x)$. For example:\n\n- $f(30, 70) = g(70, 2) \\cdot g(70, 3) \\cdot g(70, 5) = 2^1 \\cdot 3^0 \\cdot 5^1 = 10$,\n- $f(525, 63) = g(63, 3) \\cdot g(63, 5) \\cdot g(63, 7) = 3^2 \\cdot 5^0 \\cdot 7^1 = 63$.\n\nYou have integers $x$ and $n$. Calculate $f(x, 1) \\cdot f(x, 2) \\cdot \\ldots \\cdot f(x, n) \\bmod{(10^{9} + 7)}$.",
    "tutorial": "Let's say $h(x, p) = \\log_{p} g(x, p)$, then $h(x, p) + h(y, p) = h(x y, p)$. Because if we describe $x = p^{h(x, p)} q_{x}$ and $y = p^{h(y, p)} q_{y}$, then $x y = p^{h(x, p) + h(y, p)} q_{x} q_{y}$. Now let's go to the main step; $\\begin{aligned} \\prod_{i=1}^{n} f(x, i) &= \\prod_{i=1}^{n} \\prod_{p \\in prime(x)} g(i, p) \\\\ &= \\prod_{i=1}^{n} \\prod_{p \\in prime(x)} p^{h(i,p)} \\\\ &= \\prod_{p \\in prime(x)} \\prod_{i=1}^{n} p^{h(i,p)} \\\\ &= \\prod_{p \\in prime(x)} p^{\\sum_{i=1}^{n} h(i, p)} \\\\ &= \\prod_{p \\in prime(x)} p^{h(n!, p)} \\end{aligned}$ So we have to count $h(n!, p)$ for each $p$ in $prime(x)$, and calculate exponents. You can count $h(n!, p)$ by following formula; $h(n!, p) = \\sum_{k=1}^{\\infty} \\Bigl \\lfloor \\frac{n}{p^k} \\Bigr \\rfloor$ Fortunately, since $h(n!, p)$ never exceeds $n$, we don't have to apply Euler's theorem here. You just have to be careful about overflow issue. Roughly calculated time complexity is $O( \\sqrt{x} + \\log \\log x \\cdot \\log n)$, because you use $O(\\sqrt{x})$ to get prime divisors of $x$, and the number of distinct prime divisors of $x$ is approximately $\\log \\log x$.",
    "code": "# Prime factorization\ndef prime_factorization(x):\n    answer = []\n    i = 2\n    while i*i <= x:\n        if x%i == 0:\n            answer.append(i)\n            while x%i == 0: x //= i\n        i += 1\n    if x > 1: answer.append(x)\n    return answer\n \n# Main\ndef main(X: int, N: int):\n    answer = 1\n    mod = 10**9 + 7\n    x_primes = prime_factorization(x)\n    for prime in x_primes:\n        power = 0\n        factor = prime\n        while factor <= N:\n            power += N // factor\n            factor *= prime\n        answer *= pow(prime, power, mod)\n        answer %= mod\n    return answer\n \nx, n = [int(c) for c in input().split()]\nprint(main(x, n))",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1228",
    "index": "D",
    "title": "Complete Tripartite",
    "statement": "You have a simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.\n\nLet's make a definition.\n\nLet $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied:\n\n- There are no edges with both endpoints in vertex set $v_1$.\n- There are no edges with both endpoints in vertex set $v_2$.\n- For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$.\n\nCreate three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below;\n\n- All vertex sets should not be empty.\n- Each vertex should be assigned to only one vertex set.\n- $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true.\n\nIs it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.",
    "tutorial": "You can make answer by following these steps; If two vertices $u_{1}$ and $u_{2}$ are in same vertex set, there should be no edge between them. Otherwise, there should be edge between them. If you choose any $u$ as first vertex of specific vertex set, then you can simply add all vertices which are not directly connected to $u$ in that vertex set. Make $3$ vertex sets by doing second step multiple times. If you can't make $3$ sets or there is any vertex which is not in any vertex set, then answer is impossible. If $m \\ne \\lvert v_{1} \\rvert \\cdot \\lvert v_{2} \\rvert + \\lvert v_{2} \\rvert \\cdot \\lvert v_{3} \\rvert + \\lvert v_{3} \\rvert \\cdot \\lvert v_{1} \\rvert$, then answer is impossible. $\\lvert v_{i} \\rvert$ means size of $i$-th vertex set. For all vertices $u_{1}$ and $u_{2}$ from different vertex sets, if there is no direct connection between $u_{1}$ and $u_{2}$, then answer is impossible. If you validated all steps, then current vertex set assignment is answer. Make sure you are doing all steps. If you forget any of these steps, your solution will print wrong answer. Time complexity is $O((n+m) \\log n)$.",
    "code": "// Standard libraries\n#include <stdio.h>\n#include <vector>\n#include <set>\n \n// Main\nint main(int argc, char **argv){\n \n#ifdef __McDic__ // Local testing I/O\n    freopen(\"VScode/IO/input.txt\", \"r\", stdin);\n    freopen(\"VScode/IO/output.txt\", \"w\", stdout);\n#endif\n \n    // Get input\n    int v, e; scanf(\"%d %d\", &v, &e);\n    std::vector<std::set<int>> edges(v+1);\n    for(int i=0; i<e; i++){\n        int e[2]; scanf(\"%d %d\", e, e+1);\n        edges[e[0]].insert(e[1]);\n        edges[e[1]].insert(e[0]);\n    }\n \n    // Assign groups\n    std::vector<int> group(v+1, -1);\n    for(int g = 0; g < 3; g++){\n        \n        // Find first point of group\n        int first;\n        for(first=1; first<=v; first++) if(group[first] == -1) break;\n        if(first == v+1){ printf(\"-1\\n\"); return 0;} // All are in some group\n \n        // Group settings\n        group[first] = g;\n        for(int second = 1; second <= v; second++) if(first != second && group[second] == -1 \n        && edges[first].find(second) == edges[first].end()) group[second] = g;\n    }\n \n    // All vertices should be in some group\n    std::vector<std::vector<int>> groups(3);\n    for(int now=1; now<=v; now++){\n        if(group[now] == -1){ printf(\"-1\\n\"); return 0;} // Non grouped vertex exist\n        else groups[group[now]].push_back(now);\n    }\n \n    // Edge counting\n    int found_edges = 0;\n    for(int g1=0; g1<3; g1++){\n        for(int g2=g1+1; g2<3; g2++){\n            for(int v1: groups[g1]) for(int v2: groups[g2]){\n                if(edges[v1].find(v2) == edges[v1].end()){ printf(\"-1\\n\"); return 0;} // Non complete bipartite\n                else found_edges++;\n            }\n        }\n    }\n \n    // Edge validation\n    if(found_edges != e){ printf(\"-1\\n\"); return 0;} // Remaining edges detected\n    for(int now=1; now<=v; now++) printf(\"%d \", group[now] + 1); // OK!!\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "hashing",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1228",
    "index": "E",
    "title": "Another Filling the Grid",
    "statement": "You have $n \\times n$ square grid and an integer $k$. Put an integer in each cell while satisfying the conditions below.\n\n- All numbers in the grid should be between $1$ and $k$ inclusive.\n- Minimum number of the $i$-th row is $1$ ($1 \\le i \\le n$).\n- Minimum number of the $j$-th column is $1$ ($1 \\le j \\le n$).\n\nFind the number of ways to put integers in the grid. Since the answer can be very large, find the answer modulo $(10^{9} + 7)$.\n\n\\begin{center}\nThese are the examples of valid and invalid grid when $n=k=2$.\n\\end{center}",
    "tutorial": "$O(n^{3})$ solution:Let $f(r, c)$ to be the number of filling grids of $r$ rows, $c$ incomplete columns, and $n-c$ complete columns. Incomplete columns means which doesn't contain $1$ in already filled part, and complete columns means opposite. Now you can see that the formula can be described as below; $f(r, 0) = (k^{n} - (k-1)^{n})^{r}$ ($1 \\le r$), because we don't have to care about minimum value of columns. However, there should be at least one cell which has $1$. $f(1, c) = k^{n-c}$ ($1 \\le c$), because we have to fill $1$ in all incomplete columns in that row. But, other cells are free. $f(r, c) = (k^{n-c} - (k-1)^{n-c}) \\cdot (k-1)^{c} \\cdot f(r-1, c) + k^{n-c} \\cdot \\sum_{c_{0}=1}^{c} \\binom{c}{c_{0}} \\cdot (k-1)^{c-c0} \\cdot f(r-1, c-c_{0})$ ($2 \\le r$, $1 \\le c$). Each part means number of cases when you select $c_{0}$ incomplete columns to be complete column in this row. The answer is $f(n, n)$. Let $f(r, c)$ to be the number of filling grids of $r$ rows, $c$ incomplete columns, and $n-c$ complete columns. Incomplete columns means which doesn't contain $1$ in already filled part, and complete columns means opposite. Now you can see that the formula can be described as below; $f(r, 0) = (k^{n} - (k-1)^{n})^{r}$ ($1 \\le r$), because we don't have to care about minimum value of columns. However, there should be at least one cell which has $1$. $f(1, c) = k^{n-c}$ ($1 \\le c$), because we have to fill $1$ in all incomplete columns in that row. But, other cells are free. $f(r, c) = (k^{n-c} - (k-1)^{n-c}) \\cdot (k-1)^{c} \\cdot f(r-1, c) + k^{n-c} \\cdot \\sum_{c_{0}=1}^{c} \\binom{c}{c_{0}} \\cdot (k-1)^{c-c0} \\cdot f(r-1, c-c_{0})$ ($2 \\le r$, $1 \\le c$). Each part means number of cases when you select $c_{0}$ incomplete columns to be complete column in this row. The answer is $f(n, n)$. $O(n^{2})$ and $O(n \\log n)$ solution:Let $R[i]$ be the restriction of the i-th row having some value <= 1 and $C[i]$ the same but for columns. We want $\\bigcap^n_{i=1}R[i] \\cap C[i]$. Negate that expression twice, and we'll get $U - \\bigcup^n_{i=1}\\neg R[i] \\cup \\neg C[i]$. Using inclusion-exclusion this is: $\\sum_{i=0}^{n} \\sum_{j=0}^{n} (-1)^{i+j} \\cdot {n\\choose j} \\cdot {n\\choose i} \\cdot k^{n^2 - n \\cdot (i+j) + i \\cdot j} \\cdot (k-1)^{n \\cdot (i+j) - i \\cdot j}$ This is enough for $O(n^{2} \\log n)$ with fast exponentiation or $O(n^{2})$ precomputing the needed powers. To get $O(n \\log n)$ note that we the second sum is a binomial expansion so the answer can be simplified to: $\\sum_{i=0}^{n} (-1)^i \\cdot {n\\choose i} \\cdot (k^{n-i} \\cdot (k-1)^{i} - (k-1)^{n})^n$ Let $R[i]$ be the restriction of the i-th row having some value <= 1 and $C[i]$ the same but for columns. We want $\\bigcap^n_{i=1}R[i] \\cap C[i]$. Negate that expression twice, and we'll get $U - \\bigcup^n_{i=1}\\neg R[i] \\cup \\neg C[i]$. Using inclusion-exclusion this is: $\\sum_{i=0}^{n} \\sum_{j=0}^{n} (-1)^{i+j} \\cdot {n\\choose j} \\cdot {n\\choose i} \\cdot k^{n^2 - n \\cdot (i+j) + i \\cdot j} \\cdot (k-1)^{n \\cdot (i+j) - i \\cdot j}$ This is enough for $O(n^{2} \\log n)$ with fast exponentiation or $O(n^{2})$ precomputing the needed powers. To get $O(n \\log n)$ note that we the second sum is a binomial expansion so the answer can be simplified to: $\\sum_{i=0}^{n} (-1)^i \\cdot {n\\choose i} \\cdot (k^{n-i} \\cdot (k-1)^{i} - (k-1)^{n})^n$",
    "code": "// Standard libraries\n#include <stdio.h>\n#include <vector>\n \n// Typedef\ntypedef long long int lld;\nconst lld mod = 1000 * 1000 * 1000 + 7;\n \n// Clean\nlld clean(lld x){\n    x %= mod;\n    if(x<0) x += mod;\n    return x;\n}\n \n// x^n\nlld power(lld x, lld n){\n    if(n==0) return 1;\n    x = clean(x);\n    lld half = power(x, n/2);\n    if(n%2 == 0) return half*half%mod;\n    else return half*half%mod*x%mod;\n}\n \nint main(int argc, char **argv){\n \n#ifdef __McDic__ // Local testing I/O\n    freopen(\"VScode/IO/input.txt\", \"r\", stdin);\n    freopen(\"VScode/IO/output.txt\", \"w\", stdout);\n#endif\n \n    // Get input\n    lld n, k; scanf(\"%lld %lld\", &n, &k);\n    std::vector<std::vector<lld>> f(n+1, std::vector<lld>(n+1, -1)); // Answer\n    if(k==1){printf(\"1\\n\"); return 0;} // edge case\n \n    // nCr combination\n    std::vector<std::vector<lld>> nCr(n+1, std::vector<lld>(n+1, -1));\n    for(int front=0; front<=n; front++){\n        nCr[front][0] = 1, nCr[front][front] = 1;\n        for(int back=1; back<front; back++) nCr[front][back] = (nCr[front-1][back-1] + nCr[front-1][back]) % mod;\n    }\n \n    std::vector<lld> kpower = {1}, k1power = {1};\n    for(int i=1; i<=n; i++){\n        kpower.push_back(kpower.back() * k % mod);\n        k1power.push_back(k1power.back() * (k-1) % mod);\n    }\n \n    // f(r, 0) = (k^n - (k-1)^n)^r\n    for(int r=1; r<=n; r++) f[r][0] = clean(power(power(k, n) - power(k-1, n), r));\n    // f(1, c) = k^(n-c) (c>=1)\n    for(int c=1; c<=n; c++) f[1][c] = power(k, n-c);\n \n    // f(r, c) = (k^(n-c) - (k-1)^(n-c)) f(r-1, c) + for_{c0} k^(n-c) [c]C[c0] f(r-1, c-c0)\n    for(int r=2; r<=n; r++) for(int c=1; c<=n; c++){\n        //if(c==n) f[r][c] = 0;\n        //else f[r][c] = clean(power(k, n-c) - power(k-1, n-c)) * power(k-1, c) % mod * f[r-1][c] % mod;\n        f[r][c] = clean(kpower[n-c] - k1power[n-c]) * k1power[c] % mod * f[r-1][c] % mod;\n        for(int c0=1; c0<=c; c0++){\n            //f[r][c] += power(k-1, c-c0) * power(k, n-c) % mod * nCr[c][c0] % mod * f[r-1][c-c0] % mod;\n            f[r][c] += k1power[c-c0] * kpower[n-c] % mod * nCr[c][c0] % mod * f[r-1][c-c0] % mod;\n            f[r][c] %= mod;\n        }\n    }\n    printf(\"%lld\\n\", f[n][n]);\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1228",
    "index": "F",
    "title": "One Node is Gone",
    "statement": "You have an integer $n$. Let's define following tree generation as McDic's generation:\n\n- Make a complete and full binary tree of $2^{n} - 1$ vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes.\n- Select a non-root vertex $v$ from that binary tree.\n- Remove $v$ from tree and make new edges between $v$'s parent and $v$'s direct children. If $v$ has no children, then no new edges will be made.\n\nYou have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree.",
    "tutorial": "Let me suggest this observation; Root of generated tree should be one of middle of diameter. Because only $1$ node is deleted from complete full binary tree. So there are $3$ valid cases; The removed node is child of root. In this case, there are $2$ answers($2$ center nodes), diameter is decreased by $1$ (odd), and tree looks like two complete full binary trees' roots are connected. You have to check if two center's subtrees are complete full binary tree. In this case, there are $2$ answers, which are $2$ centers of diameter. In this case, there are $2$ answers, which are $2$ centers of diameter. The removed node is leaf($n \\gt 2$) or normal node. In this case, there is only $1$ answer and $1$ root node. Check if whole tree is complete full binary tree with $1$ node error toleration. You can do case-handling by degree of nodes. If non-root has degree $3$, then this node is normal. If non-root has degree $2$ (error), then this node should be parent of removed leaf. You should check if this node's child node is leaf. If non-root has degree $1$, then this node should be leaf. If non-root has degree $4$ (error), then this node should be parent of removed normal node. This is the hardest case. I did this by checking depth of each child's subtree using DFS, then consider each tree to be complete and binary tree with no error, but with different depths. If you encountered multiple error nodes, then this tree is invalid. To check my exact approach, please look at my code. In these cases, we can fix the center of whole tree by center of diameter. If non-root has degree $3$, then this node is normal. If non-root has degree $2$ (error), then this node should be parent of removed leaf. You should check if this node's child node is leaf. If non-root has degree $1$, then this node should be leaf. If non-root has degree $4$ (error), then this node should be parent of removed normal node. This is the hardest case. I did this by checking depth of each child's subtree using DFS, then consider each tree to be complete and binary tree with no error, but with different depths. If you encountered multiple error nodes, then this tree is invalid. To check my exact approach, please look at my code. In these cases, we can fix the center of whole tree by center of diameter. To check if specific subtree is complete and full binary tree, you can use top-down recursive approach. Maybe you can use bottom-up approach by collapsing leaf nodes too, but it's very hard(at least I think) to check all conditions strictly. Time complexity is $O(2^{n})$. But you can solve this in like $O(n \\cdot 2^{n})$ or something bigger one.",
    "code": "// Standard libraries\n#include <stdio.h>\n#include <vector>\n#include <utility>\n \n// Max2\nint max2(int a, int b){return a>b ? a:b;}\n \n// Graph attributes\nint v;\nstd::vector<std::vector<int>> edges;\n \n// DFS from given vertex with avoidance. Return [(previous, distance), ...] \nstd::vector<std::pair<int, int>> DFS(int start, std::vector<int> avoidance = {}){\n    \n    // Answer\n    //printf(\"DFS start = %d, avoiding %d vertices\\n\", start, avoidance.size());\n    std::vector<std::pair<int, int>> result(v+1, {-1, -1});\n    \n    // Avoidance settings\n    std::vector<bool> avoidance_bool(v+1, false); // Avoidance converted to boolean array\n    for(int avoided: avoidance) avoidance_bool[avoided] = true;\n    if(avoidance_bool[start]) throw \"undefined\"; // If start is included in avoidance then raise\n    \n    // DFS with stack\n    std::vector<int> stack_previous = {-1}, stack_now = {start};\n    result[start] = {-1, 0};\n    while(!stack_now.empty()){\n        int prev = stack_previous.back(); stack_previous.pop_back();\n        int now = stack_now.back(); stack_now.pop_back();\n        //printf(\"- Looking now = %d, prev = %d\\n\", now, prev); fflush(stdout);\n        for(int next: edges[now]) if(prev != next && !avoidance_bool[next]){ // Visit only if visitable\n            result[next] = {now, result[now].second + 1};\n            stack_previous.push_back(now);\n            stack_now.push_back(next);\n        }\n    } return result;\n}\n \n// Find path [start, .., end]. If precomputed DFS(base on goal) is given, then don't do DFS process again.\nstd::vector<int> path(int start, int goal, std::vector<std::pair<int, int>> dfs_result = {}){\n    if(dfs_result.empty()) dfs_result = DFS(goal); // this represents goal->...\n    std::vector<int> answer;\n    for(int now = start; now != goal; now = dfs_result[now].first) answer.push_back(now);\n    answer.push_back(goal); return answer;\n}\n \n// Return diameter.\nstd::vector<int> diameter_path(){\n    int max_dist = -1, diameter_first = -1, diameter_second = -1;\n    std::vector<std::pair<int, int>> DFSresult1 = DFS(1);\n    for(int i=1; i<=v; i++) if(max_dist < DFSresult1[i].second)\n        max_dist = DFSresult1[i].second, diameter_first = i;\n    std::vector<std::pair<int, int>> DFSresult2 = DFS(diameter_first);\n    max_dist = -1;\n    for(int i=1; i<=v; i++) if(max_dist < DFSresult2[i].second)\n        max_dist = DFSresult2[i].second, diameter_second = i;\n    return path(diameter_second, diameter_first, DFSresult2);\n}\n \n// Validate tree: prev->now->... with level. \n// If errored is -1, then it can tolerate error only once.\nvoid treeValidation(int now, int prev, int level, int &errored, bool &globalValidationStatus){\n    if(!globalValidationStatus) return; // If global validation failed then do nothing\n \n    std::vector<int> childs; // Child nodes of now\n    for(int next: edges[now]) if(next != prev) childs.push_back(next);\n    //printf(\"Tree validation: now = %2d, prev = %2d, level = %2d, %2d child nodes, errored %2d\\n\", \n    //    now, prev, level, childs.size(), errored); fflush(stdout);\n \n    if(level == 0){ // now should be leaf\n        if(!childs.empty()) globalValidationStatus = false;\n        return;\n    }\n    else if(childs.size() == 2){ // This node has no errors\n        treeValidation(childs[0], now, level-1, errored, globalValidationStatus);\n        treeValidation(childs[1], now, level-1, errored, globalValidationStatus);\n        return;\n    }\n    else if(childs.size() == 1){ // Error: But this might be parent of removed leaf.\n        if(errored != -1 || level != 1){ \n            // Error can't be tolerated, or this node can't be parent of removed leaf\n            globalValidationStatus = false;\n            return;\n        }\n        errored = now; // Mark this vertex as errored\n        treeValidation(childs[0], now, level-1, errored, globalValidationStatus);\n        return;\n    }\n    else if(childs.size() == 3){ // Error: But this might be a parent of removed normal node.\n        if(errored != -1 || level < 2){\n            // Error can't be tolerated, or this node can't be parent of removed normal node\n            globalValidationStatus = false;\n            return;\n        }\n        errored = now; // Mark this vertex as errored\n        int maxdegree[3] = {-1, -1, -1}; // Find max degree of each subtree, then go further\n        for(int i=0; i<3; i++){\n            std::vector<std::pair<int, int>> DFSresult = DFS(childs[i], {now});\n            for(int j=1; j<=v; j++) maxdegree[i] = max2(maxdegree[i], DFSresult[j].second);\n        }\n        for(int i=0; i<3; i++) if(maxdegree[i] == level-1){ // Validation on subtrees\n            treeValidation(childs[i], now, level-1, errored, globalValidationStatus);\n            for(int j=0; j<3; j++) if(i != j) // Others are one-step smaller\n                treeValidation(childs[j], now, level-2, errored, globalValidationStatus);\n            return;\n        }\n        globalValidationStatus = false; // No validation proceeded\n    }\n    else globalValidationStatus = false; // Undefined error: Non-toleratable\n}\n \n// Main\nint main(int argc, char **argv){\n#ifdef __McDic__ // Local testing I/O\n    freopen(\"VScode/IO/input.txt\", \"r\", stdin);\n    freopen(\"VScode/IO/output.txt\", \"w\", stdout);\n#endif\n \n    // Get input\n    int n; scanf(\"%d\", &n);\n    v = (1<<n) - 2; edges.resize(v+1);\n    for(int i=0; i<v-1; i++){\n        int start, end; scanf(\"%d %d\", &start, &end);\n        edges[start].push_back(end);\n        edges[end].push_back(start);\n    }\n \n    // Get diameter and go validation\n    std::vector<int> diameter = diameter_path();\n    int diameter_size = diameter.size();\n    bool validationStatus = true;\n    if(diameter_size % 2 == 1){ // Found root; Single validation with tolerating single error\n        int root = diameter[diameter_size / 2], errored = -1;\n        treeValidation(root, -1, n-1, errored, validationStatus);\n        if(validationStatus) for(int i=1; i<=v; i++)  // At most 1 strange vertex\n        if(edges[i].size() != 1 && edges[i].size() != 3 && i != root){\n            printf(\"1\\n%d\\n\", i);    \n            return 0;\n        }\n        //printf(\"errored = %d\\n\", errored);\n    }\n    else{ // Dual validation with tolerating no error\n        int c1 = diameter[diameter_size / 2], c2 = diameter[diameter_size / 2 - 1], errored = -2;\n        treeValidation(c1, c2, n-2, errored, validationStatus);\n        treeValidation(c2, c1, n-2, errored, validationStatus);\n        if(validationStatus){\n            if(c1 > c2) std::swap(c1, c2);\n            printf(\"2\\n%d %d\\n\", c1, c2);\n            return 0;\n        }\n    }\n    printf(\"0\\n\"); // Invalid tree\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1230",
    "index": "A",
    "title": "Dawid and Bags of Candies",
    "statement": "Dawid has four bags of candies. The $i$-th of them contains $a_i$ candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?\n\nNote, that you can't keep bags for yourself or throw them away, each bag should be given to one of the friends.",
    "tutorial": "Let's firstly sort all the bags in non-decreasing order of capacities. As the order of friends doesn't matter, it turns out that one of them should take only the biggest bag or the biggest and the smallest bag. It's easy to check if any of these possibilities works.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1230",
    "index": "B",
    "title": "Ania and Minimizing",
    "statement": "Ania has a large integer $S$. Its decimal representation has length $n$ and doesn't contain any leading zeroes. Ania is allowed to change at most $k$ digits of $S$. She wants to do it in such a way that $S$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?",
    "tutorial": "There are a couple of corner cases: if $k=0$, we cannot change $S$. Otherwise, if $n=1$, we can change $S$ into $0$. Now assume that $n \\geq 2$ and $k \\geq 1$. A simple greedy approach works here: we can iterate over the digits from left to right and change them to the lowest possible digits as long as we still can change anything. The leftmost digit can be only changed to $1$, and all the remaining digits should be changed to $0$. We need to remember not to fix the digits that are currently the lowest possible. For instance, if $k=4$, the number $S=450456450$ will be changed to $\\color{blue}{\\bf 10}0\\color{blue}{\\bf00}6450$ (the modified digits are marked blue). The algorithm can be easily implemented in $O(n)$ time.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1234",
    "index": "A",
    "title": "Equalize Prices Again",
    "statement": "You are both a shop keeper and a shop assistant at a small nearby shop. You have $n$ goods, the $i$-th good costs $a_i$ coins.\n\nYou got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all $n$ goods you have.\n\nHowever, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all $n$ goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.\n\nOn the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.\n\nSo you need to find the minimum possible equal price of all $n$ goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "In this problem, we need to find the minimum possible $price$ such that $price \\cdot n \\ge sum$, where $sum$ is the sum of all $a_i$. $price$ equals to $\\lceil \\frac{sum}{n} \\rceil$, where $\\lceil \\frac{x}{y} \\rceil$ is $x$ divided by $y$ rounded up.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tint sum = 0;\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\tsum += x;\n\t\t}\n\t\tcout << (sum + n - 1) / n << endl;\n\t}\n\t\n\treturn 0;\n}\n",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1234",
    "index": "B1",
    "title": "Social Network (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions are constraints on $n$ and $k$}.\n\nYou are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$).\n\nEach conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.\n\nYou (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \\le id_i \\le 10^9$).\n\nIf you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.\n\nOtherwise (i.e. if there is no conversation with $id_i$ on the screen):\n\n- Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen.\n- Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen.\n- The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down.\n\nYour task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages.",
    "tutorial": "The solution to this problem is just the implementation of what is written in the problem statement. Let's carry the array $q$ which shows the current smartphone screen. When we receive the new message from the friend with ID $id_i$, let's do the following sequence of moves: Firstly, let's try to find him on the screen. If he is found, just do nothing and continue. Otherwise, let's check if the current number of conversations is $k$. If it is so then let's remove the last conversation. Now the number of conversations is less than $k$ and the current friend is not shown on the screen. Let's insert him into the first position. After processing all $n$ messages the answer is just the array $q$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> ids;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint id;\n\t\tcin >> id;\n\t\tif (find(ids.begin(), ids.end(), id) == ids.end()) {\n\t\t\tif (int(ids.size()) >= k) ids.pop_back();\n\t\t\tids.insert(ids.begin(), id);\n\t\t}\n\t}\n\t\n\tcout << ids.size() << endl;\n\tfor (auto it : ids) cout << it << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1234",
    "index": "B2",
    "title": "Social Network (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions are constraints on $n$ and $k$}.\n\nYou are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$).\n\nEach conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.\n\nYou (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \\le id_i \\le 10^9$).\n\nIf you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.\n\nOtherwise (i.e. if there is no conversation with $id_i$ on the screen):\n\n- Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen.\n- Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen.\n- The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down.\n\nYour task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages.",
    "tutorial": "The idea of this solution is the same as in the easy version, but now we need to do the same sequence of moves faster. We can notice that the smartphone screen works as a queue, so let store it as a queue! When the new message appears, we have to check if the friend with this ID is in the queue already, but we need to check it somehow fast. Let's use some logarithmic structure that stores the same information as the queue but in other order to find, add and remove elements fast. In C++ this structure is std::set. So let's check if the current friend is in the queue, and if no, let's check if the size of the queue is $k$. If it is so then let's remove the first element of the queue from it and the same element from the set also. Then add the current friend to the queue and to the set. After processing all messages, the reversed queue (the queue from tail to head) is the answer to the problem. Time complexity: $O(n \\log{k})$. And don't forget that std::unordered_map and other standard hashmaps can work in linear time in the worst case, so you need to redefine the hash function to use them. You can read more about this issue here: https://codeforces.com/blog/entry/62393.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\t\n\tqueue<int> q;\n\tset<int> vals;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint id;\n\t\tcin >> id;\n\t\tif (!vals.count(id)) {\n\t\t\tif (int(q.size()) >= k) {\n\t\t\t\tint cur = q.front();\n\t\t\t\tq.pop();\n\t\t\t\tvals.erase(cur);\n\t\t\t}\n\t\t\tvals.insert(id);\n\t\t\tq.push(id);\n\t\t}\n\t}\n\t\n\tvector<int> res;\n\twhile (!q.empty()) {\n\t\tres.push_back(q.front());\n\t\tq.pop();\n\t}\n\treverse(res.begin(), res.end());\n\tcout << res.size() << endl;\n\tfor (auto it : res) cout << it << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1234",
    "index": "C",
    "title": "Pipes",
    "statement": "You are given a system of pipes. It consists of two rows, each row consists of $n$ pipes. The top left pipe has the coordinates $(1, 1)$ and the bottom right — $(2, n)$.\n\nThere are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:\n\n\\begin{center}\nTypes of pipes\n\\end{center}\n\nYou can turn each of the given pipes $90$ degrees clockwise or counterclockwise \\textbf{arbitrary (possibly, zero) number of times} (so the types $1$ and $2$ can become each other and types $3, 4, 5, 6$ can become each other).\n\nYou want to turn some pipes in a way that the water flow can start at $(1, 0)$ (to the left of the top left pipe), move to the pipe at $(1, 1)$, flow somehow by \\textbf{connected pipes} to the pipe at $(2, n)$ and flow right to $(2, n + 1)$.\n\nPipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes:\n\n\\begin{center}\nExamples of connected pipes\n\\end{center}\n\nLet's describe the problem using some example:\n\n\\begin{center}\nThe first example input\n\\end{center}\n\nAnd its solution is below:\n\n\\begin{center}\nThe first example answer\n\\end{center}\n\nAs you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at $(1, 2)$ $90$ degrees clockwise, the pipe at $(2, 3)$ $90$ degrees, the pipe at $(1, 6)$ $90$ degrees, the pipe at $(1, 7)$ $180$ degrees and the pipe at $(2, 7)$ $180$ degrees. Then the flow of water can reach $(2, n + 1)$ from $(1, 0)$.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "Let's see how the water can flow when it meets the pipe of type $1$ or $2$ and in the other case. When the water meets the pipe of type $1$ or $2$ we cannot do anything but let it flow to the right of the current cell. Otherwise (if the current pipe is curved) then there are two cases: if the pipe on the same position but in the other row is not curved then the answer is \"NO\" because the water has to change the row but we cannot turn the next pipe to allow it to move to the right or to the left. So, the current pipe is curved and the pipe on the same position in the other row is also curved, let's change the row and move to the right (it is obvious that we never need to move to the left). So, the answer (and the sequence of pipes) is uniquely defined by types of pipes. If after iterating over all $n$ positions we didn't meet the case of \"NO\" and the current row is second, then the answer is \"YES\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tstring s[2];\n\t\tcin >> n >> s[0] >> s[1];\n\t\tint row = 0;\n\t\tint pos = 0;\n\t\tfor (pos = 0; pos < n; ++pos) {\n\t\t\tif (s[row][pos] >= '3') {\n\t\t\t\tif (s[row ^ 1][pos] < '3') {\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\trow ^= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (pos == n && row == 1) {\n\t\t\tcout << \"YES\" << endl;\n\t\t} else {\n\t\t\tcout << \"NO\" << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1234",
    "index": "D",
    "title": "Distinct Characters Queries",
    "statement": "You are given a string $s$ consisting of lowercase Latin letters and $q$ queries for this string.\n\nRecall that the substring $s[l; r]$ of the string $s$ is the string $s_l s_{l + 1} \\dots s_r$. For example, the substrings of \"codeforces\" are \"code\", \"force\", \"f\", \"for\", but not \"coder\" and \"top\".\n\nThere are two types of queries:\n\n- $1~ pos~ c$ ($1 \\le pos \\le |s|$, $c$ is lowercase Latin letter): replace $s_{pos}$ with $c$ (set $s_{pos} := c$);\n- $2~ l~ r$ ($1 \\le l \\le r \\le |s|$): calculate the number of distinct characters in the substring $s[l; r]$.",
    "tutorial": "Let's store for each letter all positions in which it appears in some data structure. We need such a data structure that can add, remove and find the next element greater than or equal to our element, fast enough. Suddenly, this data structure is std::set again (in C++). When we meet the first type query, let's just modify two elements of corresponding sets (one remove, one add). When we meet the second type query, let's iterate over all letters. If the current letter is in the segment $[l; r]$ then the first element greater than or equal to $l$ in the corresponding set should exist and be less than or equal to $r$. If it is so, let's increase the answer by one. After iterating over all letters just print the answer. Time complexity: $O(n \\log{n} AL)$, when $AL$ is the size of the alphabet.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tstring s;\n\tcin >> s;\n\tvector<set<int>> poss(26);\n\tfor (int i = 0; i < int(s.size()); ++i) {\n\t\tposs[s[i] - 'a'].insert(i);\n\t}\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint tp;\n\t\tcin >> tp;\n\t\tif (tp == 1) {\n\t\t\tint pos;\n\t\t\tchar c;\n\t\t\tcin >> pos >> c;\n\t\t\t--pos;\n\t\t\tposs[s[pos] - 'a'].erase(pos);\n\t\t\ts[pos] = c;\n\t\t\tposs[s[pos] - 'a'].insert(pos);\n\t\t} else {\n\t\t\tint l, r;\n\t\t\tcin >> l >> r;\n\t\t\t--l, --r;\n\t\t\tint cnt = 0;\n\t\t\tfor (int c = 0; c < 26; ++c) {\n\t\t\t\tauto it = poss[c].lower_bound(l);\n\t\t\t\tif (it != poss[c].end() && *it <= r) ++cnt;\n\t\t\t}\n\t\t\tcout << cnt << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1234",
    "index": "E",
    "title": "Special Permutations",
    "statement": "Let's define $p_i(n)$ as the following permutation: $[i, 1, 2, \\dots, i - 1, i + 1, \\dots, n]$. This means that the $i$-th permutation is \\textbf{almost identity} (i.e. which maps every element to itself) permutation but the element $i$ is on the first position. Examples:\n\n- $p_1(4) = [1, 2, 3, 4]$;\n- $p_2(4) = [2, 1, 3, 4]$;\n- $p_3(4) = [3, 1, 2, 4]$;\n- $p_4(4) = [4, 1, 2, 3]$.\n\nYou are given an array $x_1, x_2, \\dots, x_m$ ($1 \\le x_i \\le n$).\n\nLet $pos(p, val)$ be the position of the element $val$ in $p$. So, $pos(p_1(4), 3) = 3, pos(p_2(4), 2) = 1, pos(p_4(4), 4) = 1$.\n\nLet's define a function $f(p) = \\sum\\limits_{i=1}^{m - 1} |pos(p, x_i) - pos(p, x_{i + 1})|$, where $|val|$ is the absolute value of $val$. This function means the sum of distances between adjacent elements of $x$ in $p$.\n\nYour task is to calculate $f(p_1(n)), f(p_2(n)), \\dots, f(p_n(n))$.",
    "tutorial": "Let's calculate the answer for the first permutation $p_1(n)$ naively in $O(m)$. Then let's recalculate the answer somehow and then maybe prove that it works in linear time. Which summands will change when we try to recalculate the function $f(p_i(n))$ using $f(p_1(n))$? First of all, let's notice that each pair of adjacent elements of $x$ is the segment on the permutation. To calculate $f(p_i(n))$ fast, let's firstly notice that all segments that cover the element $i$ (but $i$ is not their endpoint) will change their length by minus one after placing $i$ at the first position (because $i$ will be removed from all such segments). This part can be calculated in $O(n + m)$. Let's use the standard trick with prefix sums and segments. Let $cnt$ be the array of length $n$. For each pair of adjacent elements $x_j$ and $x_{j+1}$ for all $j$ from $1$ to $m-1$ let's do the following sequence of moves: if $|x_j - x_{j + 1}| < 2$ then there are no points that covered by this segment not being its endpoints, so let's just skip this segment. Otherwise let's increase the value of $cnt[min(x_j, x_{j+1}) + 1]$ by one and decrease the value of $cnt[max(x_j, x_{j + 1})]$ by one. After this, let's build prefix sums on this array (make $cnt[i + 1] := cnt[i + 1] + cnt[i]$ for all $i$ from $1$ to $n-1$). And now $cnt_i$ equals to the number of segments covering the element $i$. The second part that will change is such segments that $i$ is their endpoint. Let's store the array of arrays $adj$ of length $n$ and $adj[i]$ will store all elements adjacent to $i$ in the array $x$ for all $i$ from $1$ to $n$. But one important thing: we don't need to consider such pairs $x_j$ and $x_{j + 1}$ that $x_j = x_{j + 1}$ (it broke my solution somehow so this part is important). Knowing these two parts we can easily calculate $f(p_i(n))$ using $f(p_1(n))$. Firstly, let's initialize the result as $res = f(p_1(n)) - cnt[i]$. Then we need to recalculate lengths of such segments that $i$ is their endpoint. Let's iterate over all elements $j$ in $adj[i]$, set $res := res - |j - i|$ (remove the old segment) and set $res := res + j$ (add the length of the segment from $j$ to $1$) and increase $res$ by one if $j < i$ (it means that $i$ and $j$ change their relative order and the length of the segment from $j$ to $i$ increases by one). Now we can see that after iterating over all $i$ from $1$ to $n$ we make at most $O(n + m)$ moves because each pair of adjacent elements in $x$ was considered at most twice. Total complexity: $O(n + m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tvector<int> a(m);\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> a[i];\n\t\t--a[i];\n\t}\n\t\n\tvector<long long> res(n);\n\tfor (int j = 0; j < m - 1; ++j) {\n\t\tres[0] += abs(a[j] - a[j + 1]);\n\t}\n\t\n\tvector<int> cnt(n);\n\tvector<vector<int>> adj(n);\n\tfor (int i = 0; i < m - 1; ++i) {\n\t\tint l = a[i], r = a[i + 1];\n\t\tif (l != r) {\n\t\t\tadj[l].push_back(r);\n\t\t\tadj[r].push_back(l);\n\t\t}\n\t\tif (l > r) swap(l, r);\n\t\tif (r - l < 2) continue;\n\t\t++cnt[l + 1];\n\t\t--cnt[r];\n\t}\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tcnt[i + 1] += cnt[i];\n\t}\n\t\n\tfor (int i = 1; i < n; ++i) {\n\t\tres[i] = res[0] - cnt[i];\n\t\tfor (auto j : adj[i]) {\n\t\t\tres[i] -= abs(i - j);\n\t\t\tres[i] += j + (j < i);\n\t\t}\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tcout << res[i] << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1234",
    "index": "F",
    "title": "Yet Another Substring Reverse",
    "statement": "You are given a string $s$ consisting only of first $20$ lowercase Latin letters ('a', 'b', ..., 't').\n\nRecall that the substring $s[l; r]$ of the string $s$ is the string $s_l s_{l + 1} \\dots s_r$. For example, the substrings of \"codeforces\" are \"code\", \"force\", \"f\", \"for\", but not \"coder\" and \"top\".\n\nYou can perform the following operation \\textbf{no more than once}: choose some substring $s[l; r]$ and \\textbf{reverse} it (i.e. the string $s_l s_{l + 1} \\dots s_r$ becomes $s_r s_{r - 1} \\dots s_l$).\n\nYour goal is to maximize the length of the maximum substring of $s$ consisting of \\textbf{distinct} (i.e. unique) characters.\n\nThe string consists of \\textbf{distinct} characters if no character in this string appears more than once. For example, strings \"abcde\", \"arctg\" and \"minecraft\" consist of distinct characters but strings \"codeforces\", \"abacaba\" do not consist of distinct characters.",
    "tutorial": "First of all, I wanted to offer you one little challenge: I found a solution that I can't break (and I don't sure if it can be broken) and I will be so happy if anyone will give me countertest which will break it. You can see its code below. Let's notice that we can reduce our problem to the following: find two substrings of the given string that letters in them do not intersect and the total length of these substrings is the maximum possible. Why can we make such a reduction? It is so because our answer consists of at most two non-intersecting parts: one fixed substring and at most one substring that we appended to the first one. We can always append any other substring to the first one by one reverse operation (just look at some examples to understand it). Let's iterate over all possible substrings of length at most $AL$ (where $AL$ is the size of the alphabet) which contain distinct letters. We can do it in $O(n AL)$. Let the current substring containing distinct letters be $s[i; j]$. Let's create the bitmask corresponding to this substring: the bit $pos$ is $1$ if the $pos$-th letter of the alphabet is presented in the substring and $0$ otherwise (letters are $0$-indexed). Store all these masks somewhere. Notice that our current problem can be reduced to the following: we have the set of masks and we need to find a pair of masks that they do not intersect and their total number of ones in them is the maximum possible. This reduction is less obvious than the previous one but you also can understand it considering some examples. So how to solve this problem? We can do it with easy bitmasks dynamic programming! Let $dp_{mask}$ be the maximum number of ones in some mask that is presented in the given string and it is the submask of $mask$. How to calculate this dynamic programming? First of all, all values $dp_{mask}$ for all masks presented in the string are equal to the number of ones in corresponding masks. Let's iterate over all masks from $0$ to $2^{AL} - 1$. Let the current mask be $mask$. Then let's try to update the answer for this mask with the answer for one of its submasks. It is obvious that because of dynamic programming we need to remove at most one bit from our mask to cover all possible submasks that can update our answer. So let's iterate over all bits in $mask$, let the current bit be $pos$. If this bit is zero then just skip it. Otherwise update $dp_{mask} := max(dp_{mask}, dp_{mask \\hat{} 2^{pos}})$, where $\\hat{}$ is the xor operation. After calculating this dynamic programming we can finally calculate the answer. Let's iterate over all masks presented in the string, let the current mask be $mask$. We can update the answer with the number of ones in $mask$ plus $dp_{mask \\hat{} (2^{AL} - 1)}$ ($mask \\hat{} (2^{AL} - 1)$ is the completion of $mask$). Total complexity: $O(n AL + AL 2^{AL})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint tt = clock();\n\t\n\tstring s;\n\tcin >> s;\n\t\n\tvector<int> dp(1 << 20);\n\tvector<int> masks;\n\tfor (int i = 0; i < int(s.size()); ++i) {\n\t\tvector<bool> used(20);\n\t\tint mask = 0;\n\t\tfor (int j = 0; i + j < int(s.size()); ++j) {\n\t\t\tif (used[s[i + j] - 'a']) break;\n\t\t\tused[s[i + j] - 'a'] = true;\n\t\t\tmask |= 1 << (s[i + j] - 'a');\n\t\t\tmasks.push_back(mask);\n\t\t}\n\t}\n\tsort(masks.begin(), masks.end());\n\tmasks.resize(unique(masks.begin(), masks.end()) - masks.begin());\n\tsort(masks.begin(), masks.end(), [](int x, int y){\n\t\treturn __builtin_popcount(x) > __builtin_popcount(y);\n\t});\n\t\n\tint ans = __builtin_popcount(masks[0]);\n\tfor (int i = 0; i < int(masks.size()); ++i) {\n\t\tif (clock() - tt > 1900) {\n\t\t\tbreak;\n\t\t}\n\t\tfor (int j = i + 1; j < int(masks.size()); ++j) {\n\t\t\tif (!(masks[i] & masks[j])) {\n\t\t\t\tans = max(ans, __builtin_popcount(masks[i]) + __builtin_popcount(masks[j]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1236",
    "index": "A",
    "title": "Stones",
    "statement": "Alice is playing with some stones.\n\nNow there are three numbered heaps of stones. The first of them contains $a$ stones, the second of them contains $b$ stones and the third of them contains $c$ stones.\n\nEach time she can do one of two operations:\n\n- take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);\n- take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones).\n\nShe wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $0$ stones. Can you help her?",
    "tutorial": "We can use many ways to solve the problem. If you just enumerate how many operations of the first and the second type, it will also pass. Of course there is a greedy solution. We make the second operation as much as possible, and then use the first operation. It takes $O(1)$ time.",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1236",
    "index": "B",
    "title": "Alice and the List of Presents",
    "statement": "Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.\n\nThere are $n$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind.\n\nAlso, there are $m$ boxes. All of them are for different people, so they are pairwise distinct (consider that the names of $m$ friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box.\n\nAlice wants to pack presents with the following rules:\n\n- She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of $n$ kinds, empty boxes are allowed);\n- For each kind at least one present should be packed into some box.\n\nNow Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo $10^9+7$.\n\nSee examples and their notes for clarification.",
    "tutorial": "The answer is $(2^m-1)^n$. If we consider each present, it may contain only in the first box, in the second ... both in the first and second box, in the first and the third one ... in the first,the second and the third one ... There are $2^m-1$ ways. There are $n$ presents, so there are $(2^m-1)^n$ ways in total according to the Multiplication Principle.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1236",
    "index": "C",
    "title": "Labs",
    "statement": "In order to do some research, $n^2$ labs are built on different heights of a mountain. Let's enumerate them with integers from $1$ to $n^2$, such that the lab with the number $1$ is at the lowest place, the lab with the number $2$ is at the second-lowest place, $\\ldots$, the lab with the number $n^2$ is at the highest place.\n\nTo transport water between the labs, pipes are built between every pair of labs. A pipe can transport at most one unit of water at a time from the lab with the number $u$ to the lab with the number $v$ if $u > v$.\n\nNow the labs need to be divided into $n$ groups, each group should contain exactly $n$ labs. The labs from different groups can transport water to each other. The sum of units of water that can be sent from a group $A$ to a group $B$ is equal to the number of pairs of labs ($u, v$) such that the lab with the number $u$ is from the group $A$, the lab with the number $v$ is from the group $B$ and $u > v$. Let's denote this value as $f(A,B)$ (i.e. $f(A,B)$ is the sum of units of water that can be sent from a group $A$ to a group $B$).\n\nFor example, if $n=3$ and there are $3$ groups $X$, $Y$ and $Z$: $X = \\{1, 5, 6\\}, Y = \\{2, 4, 9\\}$ and $Z = \\{3, 7, 8\\}$. In this case, the values of $f$ are equal to:\n\n- $f(X,Y)=4$ because of $5 \\rightarrow 2$, $5 \\rightarrow 4$, $6 \\rightarrow 2$, $6 \\rightarrow 4$,\n- $f(X,Z)=2$ because of $5 \\rightarrow 3$, $6 \\rightarrow 3$,\n- $f(Y,X)=5$ because of $2 \\rightarrow 1$, $4 \\rightarrow 1$, $9 \\rightarrow 1$, $9 \\rightarrow 5$, $9 \\rightarrow 6$,\n- $f(Y,Z)=4$ because of $4 \\rightarrow 3$, $9 \\rightarrow 3$, $9 \\rightarrow 7$, $9 \\rightarrow 8$,\n- $f(Z,X)=7$ because of $3 \\rightarrow 1$, $7 \\rightarrow 1$, $7 \\rightarrow 5$, $7 \\rightarrow 6$, $8 \\rightarrow 1$, $8 \\rightarrow 5$, $8 \\rightarrow 6$,\n- $f(Z,Y)=5$ because of $3 \\rightarrow 2$, $7 \\rightarrow 2$, $7 \\rightarrow 4$, $8 \\rightarrow 2$, $8 \\rightarrow 4$.\n\nPlease, divide labs into $n$ groups with size $n$, such that the value $\\min f(A,B)$ over all possible pairs of groups $A$ and $B$ ($A \\neq B$) is \\textbf{maximal}.\n\nIn other words, divide labs into $n$ groups with size $n$, such that minimum number of the sum of units of water that can be transported from a group $A$ to a group $B$ for every pair of different groups $A$ and $B$ ($A \\neq B$) as big as possible.\n\nNote, that the example above doesn't demonstrate an optimal division, but it demonstrates how to calculate the values $f$ for some division.\n\nIf there are many optimal divisions, you can find any.",
    "tutorial": "The maximum number is $\\lfloor\\frac{n^2}{2}\\rfloor$. It can be proved we cannot find a larger answer. There is $n^2$ pipes between any two groups. So the valid pairs of the minimum of them does not exceed $\\lfloor\\frac{n^2}{2}\\rfloor$. Then we try to find a way to achieve the maximum. We find if we put the first lab in the first group, the second one to the second group ... the $n$-th one to the $n$-th group. Then put the $n+1$-th one in the $n$-th group, the $n+2$-th one in the $n-1$-th group ... the $2n$-th one to the first group. And then again use the method for the $2n+1$-th to the $4n$-th lab. if $n$ is odd, then we will only use the previous half of the method.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1236",
    "index": "D",
    "title": "Alice and the Doll",
    "statement": "Alice got a new doll these days. It can even walk!\n\nAlice has built a maze for the doll and wants to test it. The maze is a grid with $n$ rows and $m$ columns. There are $k$ obstacles, the $i$-th of them is on the cell $(x_i, y_i)$, which means the cell in the intersection of the $x_i$-th row and the $y_i$-th column.\n\nHowever, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.\n\nMore formally, there exist $4$ directions, in which the doll can look:\n\n- The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell $(x, y)$ into the cell $(x, y + 1)$;\n- The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell $(x, y)$ into the cell $(x + 1, y)$;\n- The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell $(x, y)$ into the cell $(x, y - 1)$;\n- The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell $(x, y)$ into the cell $(x - 1, y)$.\n\n.Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: $1 \\to 2$, $2 \\to 3$, $3 \\to 4$, $4 \\to 1$. Standing in one cell, the doll can make at most one turn right.\n\nNow Alice is controlling the doll's moves. She puts the doll in of the cell $(1, 1)$ (the upper-left cell of the maze). Initially, the doll looks to the direction $1$, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?",
    "tutorial": "Consider just simulate the whole process. We walk straight, and then turn right when meet the obstacle or the border of the grid. Then we can use set to make it faster. We can check along the direction, which is the first obstacle. To check whether any cell is covered, we can calculate the number of cells we walk across and then check if it equals to $n*m-k$. Also,we can sort the obstacles by x and y, then use binary search to find the first obstacle along the direction. Time complexity is $O(nlogn)$.",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1236",
    "index": "E",
    "title": "Alice and the Unfair Game",
    "statement": "Alice is playing a game with her good friend, Marisa.\n\nThere are $n$ boxes arranged in a line, numbered with integers from $1$ to $n$ from left to right. Marisa will hide a doll in one of the boxes. Then Alice will have $m$ chances to guess where the doll is. If Alice will correctly guess the number of box, where doll is now, she will win the game, otherwise, her friend will win the game.\n\nIn order to win, Marisa will use some unfair tricks. After each time Alice guesses a box, she can move the doll to the neighboring box or just keep it at its place. Boxes $i$ and $i + 1$ are neighboring for all $1 \\leq i \\leq n - 1$. She can also use this trick once before the game starts.\n\nSo, the game happens in this order: the game starts, Marisa makes the trick, Alice makes the first guess, Marisa makes the trick, Alice makes the second guess, Marisa makes the trick, $\\ldots$, Alice makes $m$-th guess, Marisa makes the trick, the game ends.\n\nAlice has come up with a sequence $a_1, a_2, \\ldots, a_m$. In the $i$-th guess, she will ask if the doll is in the box $a_i$. She wants to know the number of scenarios $(x, y)$ (for all $1 \\leq x, y \\leq n$), such that Marisa can win the game if she will put the doll at the $x$-th box at the beginning and at the end of the game, the doll will be at the $y$-th box. Help her and calculate this number.",
    "tutorial": "First there is a conclusion: each start point will be able to reach a consecutive segment of end points except for n=1. It's easy to prove, when a place is banned, we can make a move to make it reachable again. So with the conclusion then we can solve the problem. First we will come up with a greedy algorithm. We can move the doll to the left (or right) if possible, otherwise we can keep it at its place. Then we will get the left bound and the right bound of one start point. It's $O(n^2)$ and not enough to pass. Consider we try to find the left bound. We scan the array $a$ and deal with all start points together. For the first element of $a$, it will only influence one start point (that is, if we start from there, we will meet the element can then we need to keep it at its place). So we can move the start point to its right box (because when it starts from that place, we will get the same answer). Then we can delete the first element. But then there will be more than one start point in the same cell, we can use dsu to merge two set of start points. Note that the doll cannot move to $0$ or $n+1$. We can also have to deal with this using the algorithm above. And it is the same to find the right bound. Time complexity is $O(n)$. Another solution: Consider a grid that there is obstacles on $(i,a_i)$. Each time we start from $(0,y)$ and if there is no obstacle on $(x+1,y-1)$ then we move to it, otherwise we move to $(x,y-1)$. We find we may change the direction only if we reach the place $(i-1,a_i+1)$ and we will walk to $(i,a_i+1)$. So only the $O(k)$ positions are useful. We can use binary search to find the next position for each useful position and start point. Then we get a tree. Just using dfs then we will get left bound for each start points. The Time complexity is $O(nlogn)$.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "dsu"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1236",
    "index": "F",
    "title": "Alice and the Cactus",
    "statement": "Alice recently found some cactuses growing near her house! After several months, more and more cactuses appeared and soon they blocked the road. So Alice wants to clear them.\n\nA cactus is a connected undirected graph. No edge of this graph lies on more than one simple cycle. Let's call a sequence of different nodes of the graph $x_1, x_2, \\ldots, x_k$ a simple cycle, if $k \\geq 3$ and all pairs of nodes $x_1$ and $x_2$, $x_2$ and $x_3$, $\\ldots$, $x_{k-1}$ and $x_k$, $x_k$ and $x_1$ are connected with edges. Edges $(x_1, x_2)$, $(x_2, x_3)$, $\\ldots$, $(x_{k-1}, x_k)$, $(x_k, x_1)$ lies on this simple cycle.\n\nThere are so many cactuses, so it seems hard to destroy them. But Alice has magic. When she uses the magic, every node of the cactus will be removed independently with the probability $\\frac{1}{2}$. When a node is removed, the edges connected to it are also removed.\n\nNow Alice wants to test her magic. She has picked a cactus with $n$ nodes and $m$ edges. Let $X[S]$ (where $S$ is a subset of the removed nodes) be the number of connected components in the remaining graph after removing nodes of set $S$. Before she uses magic, she wants to know the variance of random variable $X$, if all nodes of the graph have probability $\\frac{1}{2}$ to be removed and all $n$ of these events are independent. By the definition the variance is equal to $E[(X - E[X])^2]$, where $E[X]$ is the expected value of $X$. Help her and calculate this value by modulo $10^9+7$.\n\nFormally, let $M = 10^9 + 7$ (a prime number). It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, find such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "First we consider how to calculate $E(X)$. The number of connected components equals to the number of nodes minus the number of edges and then add the number of rings in it. So we can calculate the possibility of removing one node, one edge or one single ring. Then we can split the variance, it is equals to $E(X^2)-2*E(X)^2+E(X)^2=E(X^2)-E(X)^2$. Then we can again to split $X^2$. Let the number nodes equal to $a$, the number edges equal to $b$, the number rings equal to $c$. Then $X^2=(a-b+c)^2=a^2+b^2+c^2-2ab-2bc+2ac$. We can find there is contribution between a pair of nodes, edges, rings (the two may be the same) and between a node and an edge, a node and a ring, an edge and a ring. Then we can calculate the possibility of such pair that the elements in it remains at the same time. The answer is the same when the pair is a ring and a node on it, or when it is a ring and a node not on it, or an edge with one of its end point ... If we consider all the situation of intersection and not intersection, we can get a liner algorithm. But the Time Complexity is $O(nlogn)$ since we need to calculate the multiplicative inverse of modulo.",
    "tags": [
      "dfs and similar",
      "graphs",
      "math",
      "probabilities"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1237",
    "index": "A",
    "title": "Balanced Rating Changes",
    "statement": "Another Codeforces Round has just finished! It has gathered $n$ participants, and according to the results, the expected rating change of participant $i$ is $a_i$. These rating changes are perfectly balanced — their sum is equal to $0$.\n\nUnfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.\n\nThere are two conditions though:\n\n- For each participant $i$, their modified rating change $b_i$ must be integer, and as close to $\\frac{a_i}{2}$ as possible. It means that either $b_i = \\lfloor \\frac{a_i}{2} \\rfloor$ or $b_i = \\lceil \\frac{a_i}{2} \\rceil$. In particular, if $a_i$ is even, $b_i = \\frac{a_i}{2}$. Here $\\lfloor x \\rfloor$ denotes rounding down to the largest integer not greater than $x$, and $\\lceil x \\rceil$ denotes rounding up to the smallest integer not smaller than $x$.\n- The modified rating changes must be perfectly balanced — their sum must be equal to $0$.\n\nCan you help with that?",
    "tutorial": "Let $b_i = \\frac{a_i}{2} + \\delta_i$. It follows that if $a_i$ is even, then $\\delta_i = 0$, and if $a_i$ is odd, then either $\\delta_i = \\frac{1}{2}$ or $\\delta_i = -\\frac{1}{2}$. At the same time, the sum of $b_i$ is equal to the sum of $\\delta_i$, as the sum of $a_i$ is $0$. Thus, as the sum of $b_i$ must be equal to $0$, we need to have an equal number of $\\delta_i$ equal to $\\frac{1}{2}$ and $-\\frac{1}{2}$. In simple words, we have to divide all numbers by $2$, and out of all non-integers, exactly half of them must be rounded up and the other half must be rounded down.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n;\n  cin >> n;\n  int flag = 1;\n  for (int i = 0; i < n; i++) {\n    int x;\n    cin >> x;\n    if (x % 2 == 0) {\n      cout << x / 2 << '\\n';\n    } else {\n      cout << (x + flag) / 2 << '\\n';\n      flag *= -1;\n    }\n  }\n  return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1237",
    "index": "B",
    "title": "Balanced Tunnel",
    "statement": "Consider a tunnel on a one-way road. During a particular day, $n$ cars numbered from $1$ to $n$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.\n\nA traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.\n\nThanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.\n\nTraffic regulations prohibit overtaking inside the tunnel. If car $i$ overtakes any other car $j$ inside the tunnel, car $i$ must be fined. However, each car can be fined at most once.\n\nFormally, let's say that car $i$ definitely overtook car $j$ if car $i$ entered the tunnel later than car $j$ and exited the tunnel earlier than car $j$. Then, car $i$ must be fined if and only if it definitely overtook at least one other car.\n\nFind the number of cars that must be fined.",
    "tutorial": "This problem can be approached in several ways, here is one of them. Let's say that cars exit the tunnel at time moments $1, 2, \\ldots, n$, and let $c_i$ be time when car $a_i$ exited the tunnel. For instance, in the first example we had $a = \\langle 3, 5, 2, 1, 4 \\rangle$ and $b = \\langle 4, 3, 2, 5, 1 \\rangle$. Then, $c = \\langle 2, 4, 3, 5, 1 \\rangle$: car $3$ entered first and exited at time $2$, so $c_1 = 2$; car $5$ entered second and exited and time $4$, so $c_2 = 4$; and so on. Note that $c$ is a permutation, and not only it can be found in $O(n)$, but also it can be very useful for us. It turns out that we can use $c$ to easily determine if car $a_i$ must be fined. Specifically, car $a_i$ must be fined if $c_i$ is smaller than $\\max(c_1, c_2, \\ldots, c_{i-1})$. Why is that? Recall that car $a_i$ must be fined if there exists a car that entered the tunnel earlier and exited the tunnel later. If a car entered the tunnel earlier, it must be $a_j$ such that $j < i$. If a car exited the tunnel later, it must be that $c_j > c_i$. Therefore, now we can just go from left to right, keeping the maximum of $c_1, c_2, \\ldots, c_{i-1}$ to compare it to $c_i$. The overall complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n;\n  cin >> n;\n  vector<int> a(n), b(n);\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n    --a[i];\n  }\n  for (int i = 0; i < n; i++) {\n    cin >> b[i];\n    --b[i];\n  }\n  vector<int> pos(n);\n  for (int i = 0; i < n; i++) {\n    pos[b[i]] = i;\n  }\n  vector<int> c(n);\n  for (int i = 0; i < n; i++) {\n    c[i] = pos[a[i]];\n  }\n  int mx = -1, ans = 0;\n  for (int i = 0; i < n; i++) {\n    if (c[i] > mx) {\n      mx = c[i];\n    } else {\n      ++ans;\n    }\n  }\n  cout << ans << '\\n';\n  return 0;\n}",
    "tags": [
      "data structures",
      "sortings",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1237",
    "index": "C1",
    "title": "Balanced Removals (Easier)",
    "statement": "This is an easier version of the problem. In this version, $n \\le 2000$.\n\nThere are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even.\n\nYou'd like to remove all $n$ points using a sequence of $\\frac{n}{2}$ snaps. In one snap, you can remove any two points $a$ and $b$ that have not been removed yet and form a perfectly balanced pair. A pair of points $a$ and $b$ is perfectly balanced if no other point $c$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $a$ and $b$.\n\nFormally, point $c$ lies within the axis-aligned minimum bounding box of points $a$ and $b$ if and only if $\\min(x_a, x_b) \\le x_c \\le \\max(x_a, x_b)$, $\\min(y_a, y_b) \\le y_c \\le \\max(y_a, y_b)$, and $\\min(z_a, z_b) \\le z_c \\le \\max(z_a, z_b)$. Note that the bounding box might be degenerate.\n\nFind a way to remove all points in $\\frac{n}{2}$ snaps.",
    "tutorial": "Pick any two points $i$ and $j$, let's say that this is our candidate pair $(i, j)$ for removal. Loop over all other points. If some point $k$ lies inside the bounding box of $i$ and $j$, change our candidate pair to $(i, k)$. Note that the bounding box of $i$ and $k$ lies inside the bounding box of $i$ and $j$, so we don't need to recheck points that we have already checked. The candidate pair we get at the end of the loop can surely be removed. Another look at the situation is that we can pick any point $i$, and then pick point $j$ that is the closest to point $i$, either by Euclidean or Manhattan metric. Pair $(i, j)$ can be removed then, as if any point $k$ lies inside the bounding box of $i$ and $j$, it's strictly closer to $i$ than $j$. Both of these solutions work in $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<pair<int, int>, pair<int, int> > ii;\n\nint main(){\n    int n;\n    cin >> n;\n    \n    vector<ii> v(n);\n    for (int i = 0; i < n; i++){\n        cin >> v[i].first.first >> v[i].first.second >> v[i].second.first;\n        v[i].second.second = i + 1;\n    }\n    \n    while(!v.empty()){\n        sort(v.begin(), v.end());\n        int x = v.back().first.first;\n        int y = v.back().first.second;\n        int z = v.back().second.first;\n        int pos = v.back().second.second;\n        v.pop_back();\n        int ind = 0;\n        ll d = 1e10;\n        for (int i = 0; i < (int) v.size(); i++){\n            ll dist = abs(v[i].first.first - x);\n            dist += abs(v[i].first.second - y);\n            dist += abs(v[i].second.first - z);\n            if (dist < d){\n                d = dist;\n                ind = i;\n            }\n        }\n        cout << pos << \" \" << v[ind].second.second << endl;\n        v.erase(v.begin() + ind);\n    }\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1237",
    "index": "C2",
    "title": "Balanced Removals (Harder)",
    "statement": "This is a harder version of the problem. In this version, $n \\le 50\\,000$.\n\nThere are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even.\n\nYou'd like to remove all $n$ points using a sequence of $\\frac{n}{2}$ snaps. In one snap, you can remove any two points $a$ and $b$ that have not been removed yet and form a perfectly balanced pair. A pair of points $a$ and $b$ is perfectly balanced if no other point $c$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $a$ and $b$.\n\nFormally, point $c$ lies within the axis-aligned minimum bounding box of points $a$ and $b$ if and only if $\\min(x_a, x_b) \\le x_c \\le \\max(x_a, x_b)$, $\\min(y_a, y_b) \\le y_c \\le \\max(y_a, y_b)$, and $\\min(z_a, z_b) \\le z_c \\le \\max(z_a, z_b)$. Note that the bounding box might be degenerate.\n\nFind a way to remove all points in $\\frac{n}{2}$ snaps.",
    "tutorial": "Consider a one-dimensional version of the problem where $n$ is not necessarily even. We can sort all points by their $x$-coordinate and remove them in pairs. This way, we'll leave at most one point unremoved. Now, consider a two-dimensional version of the problem where $n$ is not necessarily even. For each $y$, consider all points that have this $y$-coordinate and solve the one-dimensional version on them. After we do this, we'll have at most one point on each $y$ left. Now we can sort the points by $y$ and remove them in pairs in this order. Again, we'll leave at most one point unremoved. Finally, consider a three-dimensional version of the problem. Again, for each $z$, consider all points that have this $z$-coordinate and solve the two-dimensional version on them. After we do this, we'll have at most one point on each $z$ left. Now we can sort the points by $z$ and remove them in pairs in this order. We can even generalize this solution to any number of dimensions and solve the problem in $O(dn \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int D = 3;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n;\n  cin >> n;\n  vector<vector<int>> p(n, vector<int>(D));\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < D; j++) {\n      cin >> p[i][j];\n    }\n  }\n  auto Solve = [&](auto& Self, vector<int> ids, int k) {\n    if (k == D) {\n      return ids[0];\n    }\n    map<int, vector<int>> mp;\n    for (int x : ids) {\n      mp[p[x][k]].push_back(x);\n    }\n    vector<int> a;\n    for (auto& q : mp) {\n      int cur = Self(Self, q.second, k + 1);\n      if (cur != -1) {\n        a.push_back(cur);\n      }\n    }\n    for (int i = 0; i + 1 < (int) a.size(); i += 2) {\n      cout << a[i] + 1 << \" \" << a[i + 1] + 1 << '\\n';\n    }\n    return (a.size() % 2 == 1 ? a.back() : -1);\n  };\n  vector<int> t(n);\n  iota(t.begin(), t.end(), 0);\n  Solve(Solve, t, 0);\n  return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "divide and conquer",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1237",
    "index": "D",
    "title": "Balanced Playlist",
    "statement": "Your favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of $n$ tracks numbered from $1$ to $n$. The playlist is automatic and cyclic: whenever track $i$ finishes playing, track $i+1$ starts playing automatically; after track $n$ goes track $1$.\n\nFor each track $i$, you have estimated its coolness $a_i$. The higher $a_i$ is, the cooler track $i$ is.\n\nEvery morning, you choose a track. The playlist then starts playing from this track in its usual cyclic fashion. At any moment, you remember the maximum coolness $x$ of already played tracks. Once you hear that a track with coolness \\textbf{strictly} less than $\\frac{x}{2}$ (no rounding) starts playing, you turn off the music immediately to keep yourself in a good mood.\n\nFor each track $i$, find out how many tracks you will listen to before turning off the music if you start your morning with track $i$, or determine that you will never turn the music off. Note that if you listen to the same track several times, every time must be counted.",
    "tutorial": "This problem allowed a lot of approaches. First, to determine if the answer is all $-1$, compare half of maximum $x_i$ and minimum $x_i$. Second, note that during the first $n$ tracks, we'll listen to the track with maximum $x_i$, and during the next $n$ tracks, we'll stop at the track with minimum $x_i$. Thus, to pretend that the cyclic playlist is linear, it's enough to repeat it three times. For each track $i$, let's find the next track $j$ with coolness more than $x_i$, and the next track $k$ with coolness less than $\\frac{x_i}{2}$. Then it's easy to see that if $j < k$, we have $c_i = c_j + j - i$, and if $j > k$, we have $c_i = k - i$. Thus, all that remains is to find the next track after every track $i$ whose coolness lies in some segment of values. This can be done with binary search over segment tree in $O(n \\log^2 n)$, binary search over sparse table in $O(n \\log n)$, binary search over stack in $O(n \\log n)$ as well... Alternatively, if we go through tracks in increasing/decreasing order of coolness, we can also answer these queries with two pointers and a structure like C++ set or Java TreeSet. Bonus: solve the problem in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n;\n  cin >> n;\n  vector<int> a(3 * n);\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n    a[i + n] = a[i + 2 * n] = a[i];\n  }\n  vector<int> ans(3 * n);\n  vector<int> st_max;\n  vector<int> st_min;\n  for (int i = 3 * n - 1; i >= 0; i--) {\n    while (!st_max.empty() && a[st_max.back()] < a[i]) {\n      st_max.pop_back();\n    }\n    while (!st_min.empty() && a[st_min.back()] > a[i]) {\n      st_min.pop_back();\n    }\n    int low = 0, high = (int) st_min.size();\n    while (low < high) {\n      int mid = (low + high) >> 1;\n      if (a[st_min[mid]] * 2 < a[i]) {\n        low = mid + 1;\n      } else {\n        high = mid;\n      }\n    }\n    int nxt = 3 * n;\n    if (low > 0) {\n      nxt = min(nxt, st_min[low - 1]);\n    }\n    if (!st_max.empty()) {\n      nxt = min(nxt, st_max.back());\n    }\n    if (nxt < 3 * n && a[nxt] >= a[i]) {\n      ans[i] = ans[nxt];\n    } else {\n      ans[i] = nxt;\n    }\n    st_min.push_back(i);\n    st_max.push_back(i);\n  }\n  for (int i = 0; i < n; i++) {\n    if (i > 0) {\n      cout << \" \";\n    }\n    cout << (ans[i] == 3 * n ? -1 : ans[i] - i);\n  }\n  cout << '\\n';\n  return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1237",
    "index": "E",
    "title": "Balanced Binary Search Trees",
    "statement": "Recall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree.\n\nThe depth of a vertex is the number of edges on the simple path from the vertex to the root. In particular, the depth of the root is $0$.\n\nLet's call a binary search tree perfectly balanced if there doesn't exist a binary search tree with the same number of vertices that has a strictly smaller sum of depths of its vertices.\n\nLet's call a binary search tree with integer keys striped if both of the following conditions are satisfied for every vertex $v$:\n\n- If $v$ has a \\textbf{left} subtree whose root is $u$, then the parity of the key of $v$ is \\textbf{different} from the parity of the key of $u$.\n- If $v$ has a \\textbf{right} subtree whose root is $w$, then the parity of the key of $v$ is the \\textbf{same} as the parity of the key of $w$.\n\nYou are given a single integer $n$. Find the number of perfectly balanced striped binary search trees with $n$ vertices that have distinct integer keys between $1$ and $n$, inclusive. Output this number modulo $998\\,244\\,353$.",
    "tutorial": "Consider perfectly balanced striped BSTs of some maximum depth $d$. Note that both the left and the right subtree of the root must be perfectly balanced striped BSTs of maximum depth $d-1$. Also note that the parity of the root must be equal to the parity of $n$, as $n$ lies on the rightmost branch of the tree; thus, the size of the right subtree must be even. Consider trees of maximum depth $2$: there is one with $n = 4$ and one with $n = 5$. A tree of maximum depth $3$ can have its right subtree of size $4$ only, and its left subtree can have size $4$ or $5$; thus, we have one tree with $n = 9$ and one with $n = 10$. Using induction, we can prove that for any maximum depth $d$, we have exactly two possible trees, of sizes $x$ and $x + 1$ for some $x$. We can enumerate these trees and check if $n$ belongs to the set of possible sizes in $O(\\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n;\n  cin >> n;\n  int x = 1;\n  while (x <= n) {\n    if (n == x || n == x + 1) {\n      cout << 1 << '\\n';\n      return 0;\n    }\n    if (x % 2 == 0) {\n      x = x + 1 + x;\n    } else {\n      x = (x + 1) + 1 + x;\n    }\n  }\n  cout << 0 << '\\n';\n  return 0;\n}",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1237",
    "index": "F",
    "title": "Balanced Domino Placements",
    "statement": "Consider a square grid with $h$ rows and $w$ columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.\n\nLet's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino.\n\nYou are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo $998\\,244\\,353$.",
    "tutorial": "Suppose we're going to place $d_h$ extra horizontal dominoes and $d_v$ extra vertical ones. Consider all rows of the grid, and mark them with $0$ if it's empty and with $1$ if it already has a covered cell. Do the same for columns. Now, let's find the number of ways $R$ to pick $d_h$ rows marked with $0$, and also $d_v$ pairs of neighboring rows marked with $0$, so that these sets of rows don't intersect. Similarly, let's find the number of ways $C$ to pick $d_h$ pairs of columns marked with $0$, and also $d_v$ columns marked with $0$. Then, the number of ways to place exactly $d_h$ horizontal dominoes and $d_v$ vertical ones is $R \\cdot C \\cdot d_h! \\cdot d_v!$. To find $R$, let's use DP: let $f(i, j)$ be the number of ways to pick $j$ pairs of neighboring rows out of the first $i$ rows. Then, $f(i, j) = f(i - 1, j)$ if any of rows $i$ or $i-1$ is marked with $1$, and $f(i, j) = f(i - 1, j) + f(i - 2, j - 1)$ if both are marked with $0$. It follows that $R = f(h, d_v) * \\binom{h - 2d_v}{d_h}$. $C$ can be found similarly. The complexity of this solution is $O((R+C)^2)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst int MOD = 998244353;\nconst int MAX = 3610;\nll dp1[MAX][MAX], dp2[MAX][MAX];\nint has1[MAX], has2[MAX];\nll fac[MAX], c[MAX][MAX];\nint n, m, k;\n\nvoid make(int n){\n    dp1[0][0] = 1;\n    for (int i = 1; i <= n; i++){\n        for (int j = 0; j <= m; j++){\n            dp1[i][j] = dp1[i - 1][j];\n            if (j && i >= 2 && has1[i] == 0 && has1[i - 1] == 0){\n                dp1[i][j] += dp1[i - 2][j - 1];\n            }\n            dp1[i][j] %= MOD;\n        }\n    }\n}\n\nint main(){\n    cin >> n >> m >> k;\n    int t = max(n, m) + 1;\n    vector<ll> f(t);\n    for (int i = 1; i <= k; i++){\n        int a, b, c, d;\n        cin >> a >> b >> c >> d;\n        if (has1[a] || has1[c] || has2[b] || has2[d]){\n            cout << 0 << endl;\n            return 0;\n        }\n        has1[a] = has1[c] = has2[b] = has2[d] = 1;\n    }\n    int N = n, M = m;\n    for (int i = 1; i <= n; i++){\n        N -= has1[i];\n    }\n    for (int i = 1; i <= m; i++){\n        M -= has2[i];\n    }\n    make(n);\n    swap(dp1, dp2);\n    swap(has1, has2);\n    make(m);\n    swap(dp1, dp2);\n    swap(has1, has2);\n    c[0][0] = 1;\n    f[0] = 1;\n    for (int i = 1; i < t; i++){\n        f[i] = (f[i - 1] * i) % MOD;\n        c[i][0] = c[i][i] = 1;\n        for (int j = 1; j < i; j++){\n            c[i][j] = c[i - 1][j - 1] + c[i - 1][j];\n            if (c[i][j] >= MOD){\n                c[i][j] -= MOD;\n            }\n        }\n    }\n    ll ans = 0;\n    for (int i = 0; (i << 1) <= N; i++){\n        for (int j = 0; (j << 1) <= M; j++){\n            int have1 = N - 2 * i;\n            int have2 = M - 2 * j;\n            ll res = dp1[n][i] * dp2[m][j];\n            res %= MOD;\n            res *= c[have1][j];\n            res %= MOD;\n            res *= c[have2][i];\n            res %= MOD;\n            res *= f[i];\n            res %= MOD;\n            res *= f[j];\n            res %= MOD;\n            ans += res;\n        }\n    }\n    ans %= MOD;\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1237",
    "index": "G",
    "title": "Balanced Distribution",
    "statement": "There are $n$ friends living on a circular street. The friends and their houses are numbered clockwise from $0$ to $n-1$.\n\nInitially person $i$ has $a_i$ stones. The friends want to make the distribution of stones among them perfectly balanced: everyone should possess the same number of stones.\n\nThe only way to change the distribution of stones is by conducting meetings. During a meeting, people from exactly $k$ consecutive houses (remember that the street is circular) gather at the same place and bring all their stones with them. All brought stones may be redistributed among people attending the meeting arbitrarily. The total number of stones they possess before the meeting and after the meeting must stay the same. After the meeting, everyone returns to their home.\n\nFind a way to make the distribution of stones perfectly balanced conducting as few meetings as possible.",
    "tutorial": "Let $A$ be the average of $a_i$, and let $p_i$ be the sum of $a_0, a_1, \\ldots, a_i$ minus $A$ times $i+1$. Consider a pair of friends $i$ and $(i+1) \\bmod n$ that never attend the same meeting. Then we can make a \"cut\" between them to transform the circle into a line. Consider some other pair of friends $j$ and $(j+1) \\bmod n$ with the same property. Now we can cut our line into two segments. As these segments never interact with each other, we must have $p_i = p_j$ if we want the problem to be solvable. Similarly, for all \"cuts\" we do, between some pairs $k$ and $(k+1) \\bmod n$, the value of $p_k$ must be the same. Now, considering some value $x$, let's make cuts at all positions $i$ with $p_i = x$. The circle is cut into several segments. For a segment of length $l$, I claim that it can always be balanced in $\\lceil \\frac{l-1}{k-1} \\rceil$ meetings. Let's trust this for a while. If we carefully look at the formulas, we may note that if a segment has length $l$ such that $l \\neq 1 (\\bmod (k-1))$, it can be merged to any neighboring segment without increasing the number of meetings. It follows that we either make just one cut anywhere, or in the sequence of $i \\bmod (k-1)$ for $i$ with $p_i = x$, we need to find the longest subsequence of $(0, 1, \\ldots, k-2)*$ in cyclic sense. This can be done, for example, with binary lifting. The complexity of this step will be proportional to $O(c \\log c)$, where $c$ is the number of positions with $p_i = x$. Thus, for any value of $x$, we can find the smallest number of meetings we need if we only make cuts at positions with $p_i = x$ in $O(n \\log n)$ overall, and we can pick the minimum over these. It remains to show that we can balance any segment of length $l$ in $\\lceil \\frac{l-1}{k-1} \\rceil$ meetings. Consider the $k$ leftmost positions. If we have at least $(k-1) \\cdot A$ stones there, then we can make a meeting on these positions, send whatever remains to the $k$-th leftmost position, and proceed inductively. If we have less than $(k-1) \\cdot A$ stones there, let's solve the problem for the rightmost $l-k+1$ positions first, with the goal of sending all the extra stones to the $k$-th leftmost position. This is similar to what we usually want to do, so again we can proceed inductively to reach the goal on the right first, and then conduct a meeting on the $k$ leftmost positions, this time having enough stones to satisfy the demand.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#ifdef LOCAL\n    #define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n    #define eprintf(...) 42\n#endif\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nconst int maxn = 200005;\nconst int maxk = 19;\nconst int inf = 1e9;\n\nll a[2 * maxn];\nll psum[2 * maxn];\npair2<int> go[maxk][2 * maxn];\nmap<ll, int> lst[maxn];\nint id[2 * maxn];\nint n, k;\nll need;\nvector<pair<int, vector<ll>>> answer;\n\nvoid perform(int l)\n{\n    int fn = min(l + k, n);\n    assert(psum[fn] >= 0);\n    ll wassum = psum[fn];\n    vector<ll> exchange = vector<ll>(k, need);\n    int start = min(n - k, l);\n    for (int i = start; i < l; i++) exchange[i - start] = need + a[i];\n    exchange[l - start] += -psum[l];\n    exchange.back() += psum[fn];\n    answer.pb({start, exchange});\n    for (int i = l; i < fn; i++) a[i] = 0;\n    a[l] += -psum[l];\n    a[fn - 1] += psum[fn];\n    for (int i = start; i < start + k; i++) psum[i + 1] = psum[i] + a[i];\n    assert(wassum == psum[fn]);\n}\n\nvoid restore(int l)\n{\n    if (l >= n) return;\n    if (a[l] == 0 && psum[l] == 0)\n    {\n        restore(l + 1);\n        return;\n    }\n    int fn = min(l + k, n);\n    if (psum[fn] >= 0)\n    {\n        perform(l);\n        restore(l + k - (psum[fn] > 0));\n        return;\n    } else\n    {\n        restore(l + k - 1);\n        assert(psum[fn] == 0);\n        perform(l);\n    }\n}\n\nint main()\n{\n    scanf(\"%d%d\", &n, &k);\n    for (int i = 0; i < n; i++) scanf(\"%lld\", &a[i]);\n    need = accumulate(a, a + n, 0LL);\n    assert(need % n == 0);\n    need /= n;\n    for (int i = 0; i < n; i++) a[i] -= need;\n    for (int i = 0; i < n; i++) a[i + n] = a[i];\n    partial_sum(a, a + 2 * n, psum + 1);\n    pair2<int> ans = {inf, -1};\n    for (int j = 0; j < maxk; j++) go[j][2 * n] = {2 * n, 0};\n    for (int i = 2 * n - 1; i >= 0; i--)\n    {\n        int curid = id[i + 1];\n        if (lst[curid].count(psum[i]))\n        {\n            int to = lst[curid][psum[i]];\n            go[0][i] = {to, (to - i - 1) / (k - 1)};\n        } else\n        {\n            int to = 2 * n;\n            go[0][i] = {to, (to - i + k - 2) / (k - 1)};\n        }\n        for (int j = 1; j < maxk; j++) go[j][i] = {go[j - 1][go[j - 1][i].fi].fi, go[j - 1][i].se + go[j - 1][go[j - 1][i].fi].se};\n        \n        if (i < n)\n        {\n            int to = n + i;\n            int cur = i;\n            int curans = 0;\n            for (int j = maxk - 1; j >= 0; j--) if (go[j][cur].fi <= to)\n            {\n                curans += go[j][cur].se;\n                cur = go[j][cur].fi;\n            }\n            if (cur < to) curans += (to - cur - 1 + k - 2) / (k - 1);\n            ans = min(ans, {curans, i});\n        }\n        \n        id[i] = (2 * n - i) % (k - 1);\n        lst[id[i]][psum[i]] = i;\n    }\n    \n    rotate(a, a + ans.se, a + n);\n    partial_sum(a, a + n, psum + 1);\n    restore(0);\n    \n    assert((int)answer.size() == ans.fi);\n    printf(\"%d\\n\", (int)answer.size());\n    for (auto &t : answer)\n    {\n        printf(\"%d\", (t.fi + ans.se) % n);\n        for (auto tt : t.se) printf(\" %lld\", tt);\n        printf(\"\\n\");\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1237",
    "index": "H",
    "title": "Balanced Reversals",
    "statement": "You have two strings $a$ and $b$ of equal even length $n$ consisting of characters 0 and 1.\n\nWe're in the endgame now. To finally make the universe perfectly balanced, you need to make strings $a$ and $b$ equal.\n\nIn one step, you can choose any prefix of $a$ of even length and reverse it. Formally, if $a = a_1 a_2 \\ldots a_n$, you can choose a positive even integer $p \\le n$ and set $a$ to $a_p a_{p-1} \\ldots a_1 a_{p+1} a_{p+2} \\ldots a_n$.\n\nFind a way to make $a$ equal to $b$ using at most $n + 1$ reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.",
    "tutorial": "Unfortunately, solutions used by most participant are different from what I expected. Here is the intended solution that works in exactly $n+1$ reversals. Let's form string $b$ from right to left at the front of string $a$. For each $i = 2, 4, 6, \\ldots, n$, we'll make some reversals so that $a[1..i] = b[n-i+1..n]$. For each $i$, we need to move the first $i-2$ characters by two characters to the right, and place some correct pair of characters at the front. Consider some pair of characters at positions $x$ and $x+1$, where $x \\bmod 2 = 1$ and $x > i$. What if we perform two reversals: first, reverse prefix of length $x-1$, then, reverse prefix of length $x+1$? The answer is: characters $x$ and $x+1$ will move to the beginning of $a$ in reverse order, while all the other characters will not change their relative positions. OK, what if we need to put some pair $00$ or $11$ to the front? Then we can just pick any $00$ or $11$ pair to the right of position $i$ and move it to the front in two steps, that's easy enough. It becomes harder when we need some pair $01$ or $10$ to get to the front. We might not have a suitable corresponding $10$ or $01$ pair in store, so we might need to use three steps here. Let's call this situation undesirable. Let's get back to the initial situation. Suppose that the number of $01$ pairs in $a$ matches the number of $10$ pairs in $b$. Then we'll never get into an undesirable situation. Let's call this initial situation handy. What if these counts don't match? Then we can actually make them match using just one reversal. Specifically, pick a string out of $a$ and $b$ that has higher absolute difference of counts of $01$ and $10$, and it turns out, due to some monotonicity, that we can always find a prefix to reverse to make our initial situation handy. (Note that when I say that we can reverse a prefix in $b$, that's equivalent to reversing the same prefix in $a$ as the last reversal.) Thus, we can solve the problem in $n+1$ reversals: one reversal to make the initial situation handy, and then $n/2$ times we make at most two reversals each step without ever getting into an undesirable situation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#ifdef LOCAL\n    #define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n    #define eprintf(...) 42\n#endif\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nconst int maxn = 4005;\n\nvector<int> ss, tt;\nchar s[maxn], t[maxn];\nint n;\nvector<int> answer;\nint cnt[5];\n\nvector<int> prepare(char *s)\n{\n    vector<int> ans;\n    for (int i = 0; i < 2 * n; i += 2) ans.pb((s[i] - '0') * 2 + (s[i + 1] - '0'));\n    return ans;\n}\n\ninline void addanswer(int x)\n{\n    if (x <= 0) return;\n    answer.pb(x);\n}\n\nvoid doreverse(vector<int> &v, int l)\n{\n    reverse(v.begin(), v.begin() + l);\n    for (int j = 0; j < l; j++) if (v[j] >= 1 && v[j] <= 2)\n    {\n        v[j] = 3 - v[j];\n    }\n}\n\nint main()\n{\n    int NT;\n    scanf(\"%d\", &NT);\n    for (int T = 0; T < NT; T++)\n    {\n        scanf(\"%s%s\", s, t);\n        n = strlen(s) / 2;\n        ss = prepare(s);\n        tt = prepare(t);\n        for (auto &t : tt) if (t == 1 || t == 2) t = 3 - t;\n        cnt[0] = cnt[1] = cnt[2] = cnt[3] = 0;\n        for (auto t : ss) cnt[t]++;\n        for (auto t : tt) cnt[t]--;\n        if (cnt[0] != 0 || cnt[3] != 0)\n        {\n            printf(\"-1\\n\");\n            continue;\n        }\n        bool found = cnt[1] == 0;\n        int before = -1;\n        int after = -1;\n        for (int i = 1; i <= n && !found; i++)\n        {\n            cnt[ss[i - 1]]--;\n            cnt[3 - ss[i - 1]]++;\n            if (cnt[1] == 0)\n            {\n                before = 2 * i;\n                doreverse(ss, i);\n                found = true;\n            }\n        }\n        if (!found)\n        {\n            for (int i = 1; i <= n; i++)\n            {\n                cnt[ss[i - 1]]++;\n                cnt[3 - ss[i - 1]]--;\n            }\n        }\n        for (int i = 1; i <= n && !found; i++)\n        {\n            cnt[tt[i - 1]]++;\n            cnt[3 - tt[i - 1]]--;\n            if (cnt[1] == 0)\n            {\n                after = 2 * i;\n                doreverse(tt, i);\n                found = true;\n            }\n        }\n        assert(found);\n        \n        answer.clear();\n        addanswer(before);\n        for (int i = n - 1; i >= 0; i--)\n        {\n            int wh = -1;\n            for (int j = n - 1 - i; j < n; j++) if (ss[j] == tt[i]) wh = j;\n            addanswer(2 * wh);\n            doreverse(ss, wh);\n            addanswer(2 * wh + 2);\n            doreverse(ss, wh + 1);\n        }\n        addanswer(after);\n        \n        for (auto t : answer) reverse(s, s + t);\n        assert(strcmp(s, t) == 0);\n        \n        printf(\"%d \", (int)answer.size());\n        for (auto t : answer) printf(\"%d \", t);\n        printf(\"\\n\");\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1238",
    "index": "A",
    "title": "Prime Subtraction",
    "statement": "You are given two integers $x$ and $y$ (it is guaranteed that $x > y$). You may choose any prime integer $p$ and subtract it any number of times from $x$. Is it possible to make $x$ equal to $y$?\n\nRecall that a prime number is a positive integer that has exactly two positive divisors: $1$ and this integer itself. The sequence of prime numbers starts with $2$, $3$, $5$, $7$, $11$.\n\nYour program should solve $t$ independent test cases.",
    "tutorial": "Let's denote the difference between $x$ and $y$ as $z$ ($z = x - y$). Then, if $z$ has a prime divisor $p$, we can subtract $p$ from $x$ $\\frac{z}{p}$ times. The only positive integer that doesn't have any prime divisors is $1$. So, the answer is NO if and only if $x - y = 1$.",
    "code": "t = int(input())\n\nfor i in range(t):\n\tx, y = map(int, input().split())\n\tif(x - y > 1):\n\t\tprint('YES')\n\telse:\n\t\tprint('NO')",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1238",
    "index": "B",
    "title": "Kill `Em All",
    "statement": "Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.\n\nThe main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point $x = 0$ is where these parts meet.\n\nThe right part of the corridor is filled with $n$ monsters — for each monster, its initial coordinate $x_i$ is given (and since all monsters are in the right part, every $x_i$ is positive).\n\nThe left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes \\textbf{less than or equal} to $0$), it gets instantly killed by a trap.\n\nThe main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point $c$. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be $y$, then:\n\n- if $c = y$, then the monster is killed;\n- if $y < c$, then the monster is pushed $r$ units to the left, so its current coordinate becomes $y - r$;\n- if $y > c$, then the monster is pushed $r$ units to the right, so its current coordinate becomes $y + r$.\n\nIvan is going to kill the monsters as follows: choose some integer point $d$ and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on.\n\nWhat is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "Notice the following fact: it's never optimal to fire a missile at such a position that there are monsters to the right of it. That suggests the next solution: sort the positions, leave only the unique ones and process to shoot at the rightmost alive monster until every monster is dead. Position of some monster after $s$ shots are made is the original position minus $r \\cdot s$, because the monster could only be pushed to the left. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nconst int N = 100 * 1000 + 13;\n\nint n, r;\nint a[N];\n\nvoid solve() {\n\tscanf(\"%d%d\", &n, &r);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\n\tsort(a, a + n);\n\tn = unique(a, a + n) - a;\n\t\n\tint ans = 0;\n\tfor (int i = n - 1; i >= 0; i--) \n\t\tans += (a[i] - ans * r > 0);\n\n\tprintf(\"%d\\n\", ans);\n}\n\nint main() {\n\tint q;\n\tscanf(\"%d\", &q);\n\tforn(i, q) solve();\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1238",
    "index": "C",
    "title": "Standard Free2play",
    "statement": "You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height $h$, and there is a moving platform on each height $x$ from $1$ to $h$.\n\nEach platform is either hidden inside the cliff or moved out. At first, there are $n$ moved out platforms on heights $p_1, p_2, \\dots, p_n$. The platform on height $h$ is moved out (and the character is initially standing there).\n\nIf you character is standing on some moved out platform on height $x$, then he can pull a special lever, which switches the state of \\textbf{two platforms: on height $x$ and $x - 1$}. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. \\textbf{Note that this is the only way to move from one platform to another}.\n\nYour character is quite fragile, so it can safely fall from the height no more than $2$. In other words falling from the platform $x$ to platform $x - 2$ is okay, but falling from $x$ to $x - 3$ (or lower) is certain death.\n\nSometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height $h$, which is unaffected by the crystals). After being used, the crystal disappears.\n\nWhat is the minimum number of magic crystal you need to buy to safely land on the $0$ ground level?",
    "tutorial": "You are given the input data in compressed format, let's decompress it in binary string, where the $i$-th character is 0 if the $i$-th platform is hidden and 1 otherwise. For, example, the third query is 101110011. Let's look how our string changes: if we had ...01... then after pulling the lever it becomes ...10... and if we had ...111... then we'd get ...100... (The underlined index is the platform we are currently on). So it looks like we are standing on 1 and move it to the left until it clashes with the next one. So we can determine that we should look only at subsegments on 1-s. Now we can note, that the \"good\" string should have all subsegments of ones with even length except two cases: the subsegment that starts from $h$ should have odd length and subsegment, which ends in $1$ can have any length. Now we can say, that the answer is equal to number of subsegments which doesn't match the pattern of the \"good string\", since we can fix each subsegment with one crystal. And we can prove that it's optimal since the only way to fix two subsegments with one crystal is to merge them but it does not help. Finally, we can understand that we have no need in decompressing the input and can determine subsegments of ones straightforwardly.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\nconst int INF = int(1e9);\n\nint h, n;\nvector<int> p;\n\ninline bool read() {\n\tif(!(cin >> h >> n))\n\t\treturn false;\n\tp.resize(n);\n\tfore(i, 0, n)\n\t\tcin >> p[i];\n\treturn true;\n}\n\ninline void solve() {\n\tint ans = 0;\n\t\n\tint lf = 0;\n\tfore(i, 0, n) {\n\t\tif (i > 0 && p[i - 1] > p[i] + 1) {\n\t\t\tif (lf > 0)\n\t\t\t\tans += (i - lf) & 1;\n\t\t\telse\n\t\t\t\tans += 1 - ((i - lf) & 1);\n\t\t\tlf = i;\n\t\t}\n\t}\n\tif (p[n - 1] > 1) {\n\t\tif (lf != 0)\n\t\t\tans += (n - lf) & 1;\n\t\telse\n\t\t\tans += 1 - ((n - lf) & 1);\n\t}\n\t\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\twhile(tc--) {\n\t\tread();\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1238",
    "index": "D",
    "title": "AB-string",
    "statement": "The string $t_1t_2 \\dots t_k$ is good if each letter of this string belongs to at least one palindrome of length \\textbf{greater} than 1.\n\nA palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.\n\nHere are some examples of good strings:\n\n- $t$ = AABBB (letters $t_1$, $t_2$ belong to palindrome $t_1 \\dots t_2$ and letters $t_3$, $t_4$, $t_5$ belong to palindrome $t_3 \\dots t_5$);\n- $t$ = ABAA (letters $t_1$, $t_2$, $t_3$ belong to palindrome $t_1 \\dots t_3$ and letter $t_4$ belongs to palindrome $t_3 \\dots t_4$);\n- $t$ = AAAAA (all letters belong to palindrome $t_1 \\dots t_5$);\n\nYou are given a string $s$ of length $n$, consisting of \\textbf{only} letters A and B.\n\nYou have to calculate the number of good substrings of string $s$.",
    "tutorial": "Instead of counting the number of good substrings, let's count the number of bad substrings $cntBad$, then number of good substrings is equal to $\\frac{n(n+1)}{2} - cntBad$. Let's call a character $t_i$ in string $t_1t_2 \\dots t_k$ is bad if there is no such palindrome $t_lt_{l+1} \\dots t_r$ that $l \\le i \\le r$. Any character in substring $t_2t_3 \\dots t_{k-1}$ is good. It can be proven as follows. If $t_i = t_{i+1}$ or $t_i = t_{i-1}$ then $t_i$ belong to a palindrome of length 2. If $t_i \\neq t_{i+1}$ and $t_i \\neq t_{i-1}$ then $t_i$ belong to a palindrome $t_{i-1} \\dots t_{i+1}$. So only characters $t_1$ and $t_k$ can be bad. But at the same time character $t_1$ is bad if there is no character $t_i$ such that $i > 1$ and $t_i = t_1$. It is true because substring $t_1t_2 \\dots t_i$ is palindrome (index $i$ is minimum index such that $t_i = t_1$). So, there are only 4 patterns of bad strings: $ABB \\dots BB$; $BAA \\dots AA$; $AA \\dots AAB$; $BB \\dots BBA$; All that remains is to count the number of substrings of this kind.",
    "code": "n = int(input())\ns = input()\nres = n * (n - 1) // 2\n\nfor x in range(2):\n\tcur = 1\n\tfor i in range(1, n):\n\t\tif s[i] == s[i - 1]:\n\t\t\tcur += 1\n\t\telse:\n\t\t\tres -= cur - x\n\t\t\tcur = 1\n\ts = s[::-1]\n\nprint(res) ",
    "tags": [
      "binary search",
      "combinatorics",
      "dp",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1238",
    "index": "E",
    "title": "Keyboard Purchase",
    "statement": "You have a password which you often type — a string $s$ of length $n$. Every character of this string is one of the first $m$ lowercase Latin letters.\n\nSince you spend a lot of time typing it, you want to buy a new keyboard.\n\nA keyboard is a permutation of the first $m$ Latin letters. For example, if $m = 3$, then there are six possible keyboards: abc, acb, bac, bca, cab and cba.\n\nSince you type your password with one finger, you need to spend time moving your finger from one password character to the next. The time to move from character $s_i$ to character $s_{i+1}$ is equal to the distance between these characters on keyboard. The total time you have to spend typing the password with a keyboard is called the slowness of this keyboard.\n\nMore formaly, the slowness of keyboard is equal to $\\sum\\limits_{i=2}^{n} |pos_{s_{i-1}} - pos_{s_i} |$, where $pos_x$ is position of letter $x$ in keyboard.\n\nFor example, if $s$ is aacabc and the keyboard is bac, then the total time of typing this password is $|pos_a - pos_a| + |pos_a - pos_c| + |pos_c - pos_a| + |pos_a - pos_b| + |pos_b - pos_c|$ = $|2 - 2| + |2 - 3| + |3 - 2| + |2 - 1| + |1 - 3|$ = $0 + 1 + 1 + 1 + 2 = 5$.\n\nBefore buying a new keyboard you want to know the minimum possible slowness that the keyboard can have.",
    "tutorial": "Let's solve this problem by subset dynamic programming. Let's denote $cnt_{x, y}$ as the number of adjacent characters ($s_i$ and $s_{i+1}$) in $s$ such that $s_i = x, s_{i+1} = y$ or $s_i = y, s_{i+1} = x$. Let's $dp_{msk}$ be some intermediate result (further it will be explained what kind of intermediate result) if we already added letters corresponding to subset $msk$ to the keyboard (and we don't care about the order of these letters). Now let's consider how to recalculate values of this dynamic programming using some $dp_{msk}$. Let's iterate over a new letter $x$ on keyboard (and we know the position of this letter on the keyboard: it's equal to the number of elements in $msk$). After adding this new letter, we want to calculate what it added to the $dp_{msk \\cup x}$. Let consider some letter $y \\neq x$ and calculate how much time will be spent on moving $x \\rightarrow y$ and $y \\rightarrow x$. There are two cases. If letter $y$ is already on current keyboard, then we should add to answer $cnt_{x, y} (pos_x - pos_y)$, and $cnt_{x, y} (pos_y - pos_x)$ otherwise (where $pox_a$ is the position of character $a$ on the keyboard). But we don't know the position of the letter $y$. Let's fix it as follows. We will add the contribution of some letter when it will be added to the keyboard. So, when we added letter $x$, we should add the value $\\sum\\limits_{y \\in msk} (cnt_{x, y} pos_x) - \\sum\\limits_{y \\notin msk} (cnt_{x, y} pos_x)$. So, the total complexity is $O(a^2 2^a + n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid upd(int &a, int b){\n\ta = min(a, b);\n}\n\nconst int N = 20;\nconst int M = (1 << N) + 55;\nconst int INF = int(1e9) + 100;\n\nint a, n;\nstring s;\nint cnt[N][N];\nint d[M][N];\nint dp[M];\nint cntBit[M];\nint minBit[M];\n\nint main() {\t\n\tcin >> n >> a >> s;\n\t\n\tint B = (1 << a) - 1;\n\tfor(int i = 1; i < s.size(); ++i){\n\t\t++cnt[s[i] - 'a'][s[i - 1] - 'a'];\n\t\t++cnt[s[i - 1] - 'a'][s[i] - 'a'];\n\t}\n\tfor(int i = 0; i < M; ++i)\n\t\tdp[i] = INF;\n\tdp[0] = 0;\n\tfor(int msk = 1; msk < M; ++msk){\n\t\tcntBit[msk] = 1 + cntBit[msk & (msk - 1)];\n\t\tfor(int i = 0; i < N; ++i) if((msk >> i) & 1){\n\t\t\tminBit[msk] = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(int msk = 1; msk < M; ++msk)\n\t\tfor(int i = 0; i < a; ++i){\n\t\t\tint b = minBit[msk];\n\t\t\td[msk][i] = d[msk ^ (1 << b)][i] + cnt[i][b];\t\t\n\t\t}\n\n\tfor(int msk = 0; msk < (1 << a); ++msk){\n\t\tfor(int i = 0; i < a; ++i){\n\t\t\tif((msk >> i) & 1) continue;\n\t\t\t//i -> x\n\t\t\tint pos = cntBit[msk];\n\t\t\tint nmsk = msk | (1 << i);\n\t\t\tupd(dp[nmsk], dp[msk] + pos * (d[msk][i] - d[B ^ nmsk][i]));\n\t\t}\n\t}\t\n\n\tcout << dp[B] << endl;\n\treturn 0;\n} \n",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1238",
    "index": "F",
    "title": "The Maximum Subtree",
    "statement": "Assume that you have $k$ one-dimensional segments $s_1, s_2, \\dots s_k$ (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of $k$ vertexes, and there is an edge between the $i$-th and the $j$-th vertexes ($i \\neq j$) if and only if the segments $s_i$ and $s_j$ intersect (there exists at least one point that belongs to both of them).\n\nFor example, if $s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18]$, then the resulting graph is the following:\n\nA tree of size $m$ is good if it is possible to choose $m$ one-dimensional segments so that the graph built on these segments coincides with this tree.\n\nYou are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree.\n\nNote that you have to answer $q$ independent queries.",
    "tutorial": "At first let's understand which trees are good. For this, let's consider some vertex $v$ (we denote its segment as $[l_v, r_v]$) which is not a leaf. Also let's consider some adjacent vertex $u$ (we denote its segment as $[l_u, r_u]$) which also is not leaf. It is claimed that segment $[l_v, r_v]$ can't be inside segment $[l_u, r_u]$ (it's means $l_u \\le l_v \\le r_v \\le r_u$) and vice versa. It's true because if segment $[l_v, r_v]$ is inside the segment $[l_u, r_u]$ then some vertex $t$ adjacent with $v$ also will be adjacent with $u$. So any non-leaf vertex can be adjacent with at most 2 non-leaf vertexes. Therefore good tree is a path with a leafs adjacent to this path. So all the have to do it's find the such subtree of maximum size. We can do it by subtree dynamic programming. At first, let chose the root of the tree - some not leaf vertex. Let $dp_{v, 0}$ be the answer for the subtree with root in $v$ and dp_{v, 1} be the answer for the subtree with root in $v$ if we already took $v$ and its parent to the answer. It can be calculated as follows: $dp_{v, 0} = \\max\\limits_{to} dp_{to, 0}$; $dp_{v, 0} = \\max(dp_{v, 0}, deg_v + 1 + firstMax + secondMax)$, there $firstMax$ is a first maximum of all $dp_{to, 1}$, and $secondMax$ is a second maximum, and $deg_v$ is a degree of vertex $v$; $dp_{v, 1} = deg_v - 1 + \\max\\limits_{to} dp_{to, 1}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\n\nint n;\nvector <int> g[N];\nint d[N];\nint dp[N][2];\n\nvoid dfs(int v, int p){\n\tvector <int> d1;\n\tdp[v][1] = d[v] - 1;\n\tfor(auto to : g[v]){\n\t\tif(to == p) continue;\n\t\tdfs(to, v);\n\t\tdp[v][0] = max(dp[v][0], dp[to][0]);\n\t\tif(g[to].size() > 1){\n\t\t\td1.push_back(dp[to][1]);\n\t\t\tdp[v][1] = max(dp[v][1], d[v] + dp[to][1] - 1);\t\n\t\t}\n\t}\n\n\tsort(d1.rbegin(), d1.rend());\n\tint x = d[v] + 1;\n\tfor(int i = 0; i < 2; ++i)\n\t\tif(i < d1.size())\n\t\t\tx += d1[i];\n    dp[v][0] = max(dp[v][0], x);\n}\n\nint main() {\t\n    int q;\n    scanf(\"%d\", &q);\n    for(int qc = 0; qc < q; ++qc){\n    \tscanf(\"%d\", &n);\n    \tfor(int i = 0; i < n; ++i){\n    \t    g[i].clear();\n    \t    d[i] = 0;\n    \t    dp[i][0] = dp[i][1] = 0;\n    \t}\n    \tfor(int i = 0; i < n - 1; ++i){\n    \t\tint u, v;\n    \t\tscanf(\"%d %d\", &u, &v);\n    \t\t--u, --v;\n    \t\tg[u].push_back(v), g[v].push_back(u);\n    \t}\n    \n        if(n <= 2){\n            printf(\"%d\\n\", n);\n            continue;\n        }\n        \n    \tfor(int v = 0; v < n; ++v){\n    \t\t//d[v] = 1;\n    \t\t//for(auto to : g[v])\t\n    \t\t//\td[v] += g[to].size() == 1;\n    \t\td[v] = g[v].size();\n    \t}\n        \n        int r = -1;\n        for(int v = 0; v < n; ++v)\n            if(g[v].size() != 1)\n                r = v;\n                \n    \tdfs(r, r);\n    \tprintf(\"%d\\n\", dp[r][0]);\n    }\n\treturn 0;\n}                             \t\n",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1238",
    "index": "G",
    "title": "Adilbek and the Watering System",
    "statement": "Adilbek has to water his garden. He is going to do it with the help of a complex watering system: he only has to deliver water to it, and the mechanisms will do all the remaining job.\n\nThe watering system consumes one liter of water per minute (if there is no water, it is not working). It can hold no more than $c$ liters. Adilbek has already poured $c_0$ liters of water into the system. He is going to start watering the garden right now and water it for $m$ minutes, and the watering system should contain at least one liter of water at the beginning of the $i$-th minute (for every $i$ from $0$ to $m - 1$).\n\nNow Adilbek wonders what he will do if the watering system runs out of water. He called $n$ his friends and asked them if they are going to bring some water. The $i$-th friend answered that he can bring no more than $a_i$ liters of water; he will arrive at the beginning of the $t_i$-th minute and pour all the water he has into the system (if the system cannot hold such amount of water, the excess water is poured out); and then he will ask Adilbek to pay $b_i$ dollars for each liter of water he has brought. You may assume that if a friend arrives at the beginning of the $t_i$-th minute and the system runs out of water at the beginning of the same minute, the friend pours his water fast enough so that the system does not stop working.\n\nOf course, Adilbek does not want to pay his friends, but he has to water the garden. So he has to tell his friends how much water should they bring. Formally, Adilbek wants to choose $n$ integers $k_1$, $k_2$, ..., $k_n$ in such a way that:\n\n- if each friend $i$ brings exactly $k_i$ liters of water, then the watering system works during the whole time required to water the garden;\n- the sum $\\sum\\limits_{i = 1}^{n} k_i b_i$ is minimum possible.\n\nHelp Adilbek to determine the minimum amount he has to pay his friends or determine that Adilbek not able to water the garden for $m$ minutes.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "Despite the fact that statement sounds like some dp or flow, the actual solution is pretty greedy. Let's iterate over all minutes Adilbek has to water at and maintain the cheapest $C$ liters he can obtain to this minute. Let this be some structure which stores data in form (price for 1 liter, total volume Adilbek can buy for this price). Pairs will be sorted by the price of a liter. The most convenient structure for that might be a C++ map, for example. When moving to the next minute, pop the cheapest liter out of this structure and add it to the answer. If that minute some friend comes, then push his water to the structure: if the total updated volume in the structure is greater than $C$, then pop the most expensive left-overs out of it so that the structure holds no more than $C$ liters total. That prevents out solution to fill the watering system over its capacity. The main idea for why this greedy strategy works is that it's never optimal to take not the cheapest liter because a liter of that price or cheaper will still be available in the future minutes. Note that between each pairs of adjacent coming friends basically nothing happens. Thus you can find the time between them and pop that number of cheapest liters right away instead of iterating minute by minute. Overall complexity: $O(n \\log n)$ per query.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int N = 500 * 1000 + 13;\n\nint n, m, c, c0;\npair<int, pt> a[N];\n\nli solve() {\n\tscanf(\"%d%d%d%d\", &n, &m, &c, &c0);\n\tforn(i, n) scanf(\"%d%d%d\", &a[i].x, &a[i].y.x, &a[i].y.y);\n\ta[n++] = mp(m, mp(0, 0));\n\tsort(a, a + n);\n\n\tint sum = c0;\n\tmap<int, int> q;\n\tq[0] = c0;\n\t\n\tli ans = 0;\n\tforn(i, n) {\n\t\tint x = a[i].x;\n\t\tint cnt = a[i].y.x;\n\t\tint cost = a[i].y.y;\n\t\n\t\tint dist = x - (i ? a[i - 1].x : 0);\n\t\twhile (!q.empty() && dist > 0) {\n\t\t\tint can = min(q.begin()->y, dist);\n\t\t\tans += q.begin()->x * 1ll * can;\n\t\t\tsum -= can;\n\t\t\tdist -= can;\n\t\t\tq.begin()->y -= can;\n\t\t\tif (q.begin()->y == 0) q.erase(q.begin());\n\t\t}\n\t\t\n\t\tif (dist > 0) \n\t\t\treturn -1;\n\t\t\n\t\tint add = min(c - sum, cnt);\n\t\tsum += add;\n\t\t\n\t\twhile (add < cnt && !q.empty() && q.rbegin()->x > cost) {\n\t\t\tif (cnt - add >= q.rbegin()->y) {\n\t\t\t\tadd += q.rbegin()->y;\n\t\t\t\tq.erase(--q.end());\n\t\t\t} else {\n\t\t\t\tq.rbegin()->y -= cnt - add;\n\t\t\t\tadd = cnt;\n\t\t\t}\n\t\t}\n\t\t\n\t\tq[cost] += add;\n\t}\n\t\n\treturn ans;\n}\n\nint main() {\n\tint q;\n\tscanf(\"%d\", &q);\n\tforn(i, q) printf(\"%lld\\n\", solve());\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1239",
    "index": "A",
    "title": "Ivan the Fool and the Probability Theory",
    "statement": "Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.\n\nTo prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of $n$ rows and $m$ columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has \\textbf{at most} one adjacent cell of the same color. Two cells are considered adjacent if they share a side.\n\nIvan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo $10^9 + 7$.",
    "tutorial": "If there is no adjecent cells with same color coloring is chess coloring. Otherwise there is exist two adjecent cells with same color. Let's decide for which cells we already know their color. It turns out that color rows or columns alternates. It means that this problem equal to the same problem about strip. Answer for the strip is $2F_n$. In this way the final answer is $2(F_n + F_m - 1)$.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1239",
    "index": "B",
    "title": "The World Is Just a Programming Task (Hard Version)",
    "statement": "This is a harder version of the problem. In this version, $n \\le 300\\,000$.\n\nVasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.\n\nTo digress from his problems, Vasya decided to select two positions of the string (\\textbf{not necessarily distinct}) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.\n\nWe remind that bracket sequence $s$ is called correct if:\n\n- $s$ is empty;\n- $s$ is equal to \"($t$)\", where $t$ is correct bracket sequence;\n- $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences.\n\nFor example, \"(()())\", \"()\" are correct, while \")(\" and \"())\" are not.\n\nThe cyclical shift of the string $s$ of length $n$ by $k$ ($0 \\leq k < n$) is a string formed by a concatenation of the last $k$ symbols of the string $s$ with the first $n - k$ symbols of string $s$. For example, the cyclical shift of string \"(())()\" by $2$ equals \"()(())\".\n\nCyclical shifts $i$ and $j$ are considered different, if $i \\ne j$.",
    "tutorial": "Note first that the number of opening brackets must be equal to the number of closing brackets, otherwise the answer is always $0$. The answer for a bracket sequence is the same as the answer for any of its cyclic shifts. Then find $i$- index of the minimum balance and perform a cyclic shift of the string by i to the left. The resulting line never has a balance below zero, which means it is a correct bracket sequence. Further we will work only with it Let us draw on the plane the prefix balances (the difference between the number of opening and closing brackets) of our correct bracket sequence in the form of a polyline. It will have a beginning at $(0, 0)$, an end - at $(2n, 0)$ and its points will be in the upper half-plane. It can easily be shown that the answer to the question of the number of cyclic shifts being correct bracket sequence is the number of times how much minimum balance is achieved in the array of prefix balances. For example, for string )(()))()((, the array of prefix balances is [-1, 0, 1, 0, -1, -2, -1, -2, -1, 0], and the number of cyclic shifts, $2$ - the number of minimums in it ($-2$). After swapping two different brackets (')' and '('), either on some sub-segment in an array of balances $2$ is added, or on some sub-segment $-2$ is added. In the first case (as you can see from the figure above), the minimum remains the same as it was - $0$, and its number does not increase due to the addition of $2$ to some sub-section of the array. So, there is no profit in swapping brackets in this case. In the second case, there are three options: the minimum becomes equal to $-2$, $-1$ or $0$. In the first case, the minimum reaches a value equal to $-2$ only at those points at which there was previously value equal to $0$, so this answer will less or equal than the one that would have turned out, if no operations were applied to the array at all. If the minimum becomes equal to $-1$, then on the segment in the balance array on which $2$ was deducted as a result of this operation there could not be balances equal to $0$, otherwise the new minimum would become equal to $-2$. So, if $0 = X_0 < X_1 < \\dots < X_k = 2n$ - positions of minimums in the array of prefix balances, then the operation $-2$ was performed on the segment $[L, R]$ ($X_i < L \\leq R < X_{i+1}$ for some $i$). After this operation, the number of local minimums will be equal to the number of elements of the array of balance on the segment $[L; R]$, equal to $1$. Since this number shall be maximized, the right border swall be maximised and the left border shall be minimised. So, for some fixed $i$ it is optimal to swap $X_i$-th and $X_{i+1}-1$-th brackets (see following figure) If the minimum remains equal to $0$, then using the reasoning similar to the reasoning above, it can be proven that for some $i$ if we consider points $X_i + 1 = Y_0 < Y_1 < \\dots < Y_m = X_{i+1}-1$ - positions of $1$ in the array of balances on the segment $[X_i; X_{i+1}]$, it is optimal for some $j$ to swap $Y_j$ and $Y_{j+1}-1$ brackets (see following figure) Thus, we have the solution of $\\mathcal{O}(n)$ complexity - we shall find all $X_i$, $Y_i$ and count on each of the segments of the form $[X_i; X_{i+1}]$ or $[Y_i; Y_{i+1}]$ the number of elements equal to $0$, $1$, $2$, then according to reasonings above, maximal answer can be found.",
    "tags": [
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1239",
    "index": "C",
    "title": "Queue in the Train",
    "statement": "There are $n$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $1$ to $n$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $i$ ($1 \\leq i \\leq n$) will decide to go for boiled water at minute $t_i$.\n\nTank with a boiled water is located to the left of the $1$-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly $p$ minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small.\n\nNobody likes to stand in a queue. So when the passenger occupying the $i$-th seat wants to go for a boiled water, he will first take a look on all seats from $1$ to $i - 1$. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than $i$ are busy, he will go to the tank.\n\nThere is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.\n\nYour goal is to find for each passenger, when he will receive the boiled water for his noodles.",
    "tutorial": "The problem can be solved easily with an abstraction of \"events\". Let's define an \"event\" as a tuple of variables $(time, type, index)$, where $index$ is the index of the passenger $(1 \\leq index \\leq n)$, $time$ is the time when the event will happen, $type$ is either $0$ (the passenger exits the queue) or $1$ (the passenger wants to enter the queue). To simulate the activity described in the problem it's necessary to handle events in sorted order. At the start there are $n$ events $(t_i, 1, i)$, where $1 \\leq i \\leq n$. While there are any unprocessed events, we take the \"smallest\" event and process it. Event $(a, b, c)$ is \"smaller\" than event $(d, e, f)$ either if $(a < d)$ or $(a = d\\ and\\ b < e)$ or $(a = d\\ and\\ b = e\\ and\\ c < f)$. Let's define a few sets: $want$ (the set of passengers who want to enter the queue), $in\\_queue$ (the set of passengers who are in the queue); and a few integer variables: $queue\\_time$ (the time when the queue becomes empty, to help calculate the time when a new passenger will exit the queue if he enters now), $cur\\_time$ (time of the last processed event). Suppose that we're processing an event. If the $type$ of the event is $1$, then we add $index$ to $want$, otherwise we remove $index$ from $in\\_queue$. After processing an event we ought to check if there is a passenger who can enter the queue. Let $x$ be the smallest element of $want$, and if $in\\_queue$ either is empty or $x$ is smaller than the smallest element of $in\\_queue$, then $x$ immediately enters the queue, therefore creating a new event $(max(cur\\_time, queue\\_time) + p, 0, x)$. The complexity of the solution is $O(n log n)$, because we need to use sorted data structures (for example, std::set of std::priority_queue).",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1239",
    "index": "D",
    "title": "Catowice City",
    "statement": "In the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are $n$ residents and $n$ cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from $1$ to $n$, where the $i$-th cat is living in the house of $i$-th resident.\n\nEach Catowice resident is in friendship with several cats, including the one living in his house. In order to conduct a contest, at least one jury member is needed and at least one cat contestant is needed. Of course, every jury member should know none of the contestants. For the contest to be successful, it's also needed that the number of jury members plus the number of contestants is equal to $n$.\n\nPlease help Catowice residents to select the jury and the contestants for the upcoming competition, or determine that it's impossible to do.",
    "tutorial": "You are given bipartite graph and a perfect matching in it. You have to find independent set of size $n$ which doesn't coincide with either of two parts. Suppose such independent set exists, let's call it $S$. Also, let's call left part of graph as $L$ and right part of graph as $R$. Then define $A = S \\cap L$, $B = L \\setminus A$, $A'$ is set of all nodes which are connected by edges from matching with $A$, $B'$ - similarly for $B$. It's easy to see that $S = A \\cup B'$. Let's direct all edges in graph. Edges from matching will be directed from right to left, and all other edges will be directed from left to right. Now edges from matching will direct from $A'$ to $A$ and from $B'$ to $B$. Other edges could direct from $A$ to $A'$, from $B$ to $B'$ and from $B$ to $A'$. Observe that edges cannot direct from $A$ to $B'$, cause it wouldn't be an independent set otherwise. It's easy to see that $B'$ isn't reachable from $A$. So, let's find all strongly connected components (SCC) in this graph. If there's only one such component, answer doesn't exist due to the fact that any node of $B'$ isn't reachable from any node of $A$. If SCC is only one, any node is reachable from any other node therefore in this case either $A$ or $B'$ are empty. If there are at least two SCC, let's choose any source SCC and call it $Q$. Consider $B' = Q \\cap R$ and define $A$ as set of all nodes in left part which are not connected by edges from matching with $B'$. Let's proof that if some $l \\in L$ lies in $B'$, then $r$ - pair of $l$ in matching also lies in $B'$. That's obvious since there are no incoming edges in $B'$ and there's edge from $r$ to $l$. So, none of nodes from $A$ will lay in chosen SCC. Thus $B'$ won't be reachable from $A$ and $A \\cup B'$ will be an independent set. The only exception is $n = 1$, in such case there are two SCC but answer doesn't exist (cause chosen $A$ will be empty).",
    "tags": [
      "2-sat",
      "dfs and similar",
      "graph matchings",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1239",
    "index": "E",
    "title": "Turtle",
    "statement": "Kolya has a turtle and a field of size $2 \\times n$. The field rows are numbered from $1$ to $2$ from top to bottom, while the columns are numbered from $1$ to $n$ from left to right.\n\nSuppose in each cell of the field there is a lettuce leaf. The energy value of lettuce leaf in row $i$ and column $j$ is equal to $a_{i,j}$. The turtle is initially in the top left cell and wants to reach the bottom right cell. The turtle can only move right and down and among all possible ways it will choose a way, maximizing the total energy value of lettuce leaves (in case there are several such paths, it will choose any of them).\n\nKolya is afraid, that if turtle will eat too much lettuce, it can be bad for its health. So he wants to reorder lettuce leaves in the field, so that the energetic cost of leaves eaten by turtle will be minimized.",
    "tutorial": "Consider that we already fixed the set in the top line and fixed. If we perform a swap in this situation, the answer will clearly won't become worse (some paths are not changing, and some are decreasing). So we can assume that the first line is sorted, and similarly the second line is sorted too (but descending). Now let's think which path the turtle will choose. Observe the difference between to paths: Then cost of path $i+1$ minus cost of path $i$ is equal to $x_{i+1} - y_{i}$. $x_i$ increases when $i$ increases, $y_i$ decreases, $x_{i+1} - y_{i}$ decreases, so the discrete derivative increases. Such function looks like: So clearly the turtle will choose either the first or the last path. So now we need to split our set into two of equal size, so that the maximum sum is smallest possible. This is a knapsack problem. The states are the prefix of elements considered, the number of elements taken, the weight. It works in $\\mathcal{O}(n^3 maxa)$ EDIT: it turned out it was inobvious... The corner cells take two minimal elements and are not considered in knapsack since they are contained in all paths. It's easy to prove that it's optimal to put minimal elements in corners.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1239",
    "index": "F",
    "title": "Swiper, no swiping!",
    "statement": "\\begin{quote}\nI'm the Map, I'm the Map! I'm the MAP!!!\n\\hfill Map\n\\end{quote}\n\nIn anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose $t$ graph's variants, which Dora might like. However fox Swiper wants to spoil his plan.\n\nThe Swiper knows, that Dora now is only able to count up to $3$, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every \\textbf{remaining} vertex wouldn't change it's degree modulo $3$. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan.\n\nBoots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not.",
    "tutorial": "We will look only on set of vertex, that will stay after deleting. Let node-$x$ - node with degree $mod\\ 3$ equal $x$. Let's consider some cases: Node-$0$ exists. It is the answer, except the case, when our graph consists of one node. Cycle on nodes-$2$ exists. So exists irreducible cycle on nodes-$2$. It is the answer, except the case, when our graph is cycle. Way between nodes-$1$ on nodes-$2$ exists. So exists irreducible way with same conditions. It is the answer, except the case, when our graph is way. Our graph contains one node-$1$ and nodes-$2$ form forest. Let's take two trees and delete all except two ways in this trees, such only endpoints are connected with node-$1$. Those ways and node-$1$ are the answer, except the case, when our graph is twho cycles with one common node. That's all cases. Let's show it: Nodes-$2$ form forest. Exists at least one leaf, that is connected with node-$1$. So in that case node-$1$ always exists. Degree of node-$1$ equals sum degree of nodes-$2$ minus doubled number of edges between nodes-$2$. Let $k$ - number of nodes-$2$. So degree of node-$1$ $mod\\ 3$ equals $2k - 2(k - 1) = 2$. Contradiction. So forest consist of at least two trees.",
    "tags": [
      "graphs",
      "implementation"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1240",
    "index": "F",
    "title": "Football",
    "statement": "There are $n$ football teams in the world.\n\nThe Main Football Organization (MFO) wants to host at most $m$ games. MFO wants the $i$-th game to be played between the teams $a_i$ and $b_i$ in one of the $k$ stadiums.\n\nLet $s_{ij}$ be the numbers of games the $i$-th team played in the $j$-th stadium. MFO does not want a team to have much more games in one stadium than in the others. Therefore, for each team $i$, the absolute difference between the maximum and minimum among $s_{i1}, s_{i2}, \\ldots, s_{ik}$ should not exceed $2$.\n\nEach team has $w_i$ — the amount of money MFO will earn for \\textbf{each} game of the $i$-th team. If the $i$-th team plays $l$ games, MFO will earn $w_i \\cdot l$.\n\nMFO needs to find what games in what stadiums they need to host in order to earn as much money as possible, not violating the rule they set.\n\nHowever, this problem is too complicated for MFO. Therefore, they are asking you to help them.",
    "tutorial": "Let's assume that $m \\leq n \\cdot k$. We can randomly assign colors to edges. If there is a vertex that does not satisfy the condition, then we can choose color $a$ which appears the smallest number of times and color $b$ which appears the biggest number of times. We will \"recolor\" edges that have one of these two colors. Let's consider this graph only with edges with colors $a$ and $b$. Let's add a \"fake\" vertex $0$. This graph may have many components. If a component has at least one vertex with odd degree, we connect each such vertex with $0$. Otherwise, let's choose any vertex from that component and add two edges to $0$. Therefore, the graph will be connected and each vertex will have an even degree. Thus, we will be able to find an Euler cycle. Let's color the odd edges in the cycle in $a$, and even edges in $b$. As a result, the difference between these two colors for each vertex will be at most $1$. Let's do this operation while there is a vertex which does not satisfy the condition. If $m > n \\cdot k$, let's split the edges into two groups with the equal sizes (that is, $\\lfloor \\frac{m}{2} \\rfloor$ and $\\lceil \\frac{m}{2} \\rceil$). If a group has not greater than $n \\cdot k$ edges, then do the algorithm at the beginning of the tutorial. Otherwise, split it again. If you found the answers for two groups, you need to find the answer for the combined graph. Let $f_1$ be the most popular color in the first group, $f_2$ the second most popular color, ..., $f_k$ the least popular color in the first group. Similarly, let $g_1$ be the most popular color in the second graph, etc. So, in the combined graph, $f_1$ should be equal to $g_k$, $f_2$ should be equal to $g_{k-1}$. In other words, we take the most popular color in the first group and color the least popular color in the second group with that color. If there is a vertex that does not satisfy the condition, \"recolor\" the graph according to the algorithm explained in the third paragraph.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int MAX_N = 101;\nconst int MAX_M = 1001;\n\nint n, m, k;\n\nvector<pair<int, int> > v[MAX_N];\nint w[MAX_N];\nint a[MAX_M], b[MAX_M], c[MAX_M], color[MAX_M];\n\nset<pair<int, int> > s[MAX_N], s2;\nint deg[MAX_N][MAX_M];\ninline pair<int, int> get_s2(int i){\n    return {s[i].begin()->first - s[i].rbegin()->first, i};\n}\ninline void change_edge_color(int edge, int d){\n    int pos1 = a[edge];\n    int pos2 = b[edge];\n    assert(s[pos1].find({deg[pos1][color[edge]], color[edge]}) != s[pos1].end());\n    s[pos1].erase({deg[pos1][color[edge]], color[edge]});\n    s[pos2].erase({deg[pos2][color[edge]], color[edge]});\n    deg[pos1][color[edge]] += d;\n    deg[pos2][color[edge]] += d;\n    s[pos1].insert({deg[pos1][color[edge]], color[edge]});\n    s[pos2].insert({deg[pos2][color[edge]], color[edge]});\n}\ninline void change_color(int edge, int col){\n    if (edge == 0 || edge > m || color[edge] == col)\n        return;\n    int pos1 = a[edge];\n    int pos2 = b[edge];\n    s2.erase(get_s2(pos1));\n    s2.erase(get_s2(pos2));\n    change_edge_color(edge, -1);\n    color[edge] = col;\n    change_edge_color(edge, 1);\n    s2.insert(get_s2(pos1));\n    s2.insert(get_s2(pos2));\n}\n\nvector<pair<int, int> > v2[MAX_N];\nint deg2[MAX_N];\nvector<int> vertices;\nint used[MAX_N];\nvoid dfs2(int pos){\n    used[pos] = 2;\n    for (auto e : v2[pos]){\n        if (used[e.first] != 2){\n            dfs2(e.first);\n        }\n    }\n    vertices.push_back(pos);\n}\nint _col[2];\nset<int> used3;\nint i;\nvector<int> euler;\nvoid dfs3(int pos, int prev = -1, int pr2 = 0){\n    while(!v2[pos].empty()){\n        int ind = v2[pos].back().second;\n        int to = v2[pos].back().first;\n        v2[pos].pop_back();\n        if (used3.find(ind) != used3.end()){\n            continue;\n        }\n        used3.insert(ind);\n        dfs3(to, ind, pos);\n    }\n    if (prev != -1){\n        euler.push_back(prev);\n    }\n}\n\nvoid stabilize_two_colors(const vector<int> &e, int col1, int col2){\n    assert(!e.empty());\n    v2[0].clear();\n    for (auto edge : e){\n        v2[a[edge]].clear();\n        v2[b[edge]].clear();\n        deg2[a[edge]] = 0;\n        deg2[b[edge]] = 0;\n        used[a[edge]] = 0;\n        used[b[edge]] = 0;\n    }\n    for (auto edge : e){\n        v2[a[edge]].push_back({b[edge], edge});\n        v2[b[edge]].push_back({a[edge], edge});\n    }\n    vertices.clear();\n    int u = m;\n    for (auto edge : e){\n        if (used[a[edge]] != 2){\n            int k = (int) vertices.size();\n            dfs2(a[edge]);\n            bool find = false;\n            for (int i = k; i < (int) vertices.size(); i++){\n                int v = vertices[i];\n                if (v2[v].size() % 2 == 1){\n                    find = true;\n                    ++u;\n                    v2[v].push_back({0, u});\n                    v2[0].push_back({v, u});\n                }\n            }\n            if (!find){\n                int v = vertices[k];\n                for (int j = 0; j < 2; j++){\n                    ++u;\n                    v2[v].push_back({0, u});\n                    v2[0].push_back({v, u});\n                }\n            }\n        }\n    }\n    used3.clear();\n    euler.clear();\n    dfs3(0);\n    for (int a : euler){\n        change_color(a, col1);\n        swap(col1, col2);\n    }\n}\n\nvoid stabilize(const vector<int> &e){\n    s2.clear();\n    for (int i = 1; i <= n; i++){\n        s[i].clear();\n        for (int j = 1; j <= k; j++){\n            deg[i][j] = 0;\n        }\n    }\n    for (int edge : e){\n        deg[a[edge]][color[edge]]++;\n        deg[b[edge]][color[edge]]++;\n    }\n    for (int i = 1; i <= n; i++){\n        for (int j = 1; j <= k; j++){\n            s[i].insert({deg[i][j], j});\n        }\n        s2.insert(get_s2(i));\n    }\n    while(-s2.begin()->first > 2){\n\n        int ind = s2.begin()->second;\n        int col1 = s[ind].begin()->second;\n        int col2 = s[ind].rbegin()->second;\n        vector<int> e2;\n        for (int edge : e){\n            if (color[edge] == col1 || color[edge] == col2){\n                e2.push_back(edge);\n            }\n        }\n        stabilize_two_colors(e2, col1, col2);\n    }\n}\n\nvoid make_random(vector<int> e){\n    random_shuffle(e.begin(), e.end());\n    for (int i = 0; i < (int) e.size(); i++){\n        color[e[i]] = i % k + 1;\n    }\n    stabilize(e);\n}\n\nint change[MAX_N];\n\nvoid build(vector<int> e){\n    if ((int) e.size() <= n * k){\n        make_random(e);\n        return;\n    }\n    random_shuffle(e.begin(), e.end());\n    vector<int> e1, e2;\n    int s = (int) e.size() / 2;\n    for (int i = 0; i < (int) e.size(); i++){\n        if (i < s){\n            e1.push_back(e[i]);\n        }else{\n            e2.push_back(e[i]);\n        }\n    }\n    build(e1);\n    build(e2);\n    vector<pair<int, int> > v1(k), v2(k);\n    for (int i = 1; i <= k; i++){\n        v1[i - 1].first = v2[i - 1].first = 0;\n        v1[i - 1].second = v2[i - 1].second = i;\n    }\n    for (int edge : e1){\n        v1[color[edge] - 1].first++;\n    }\n    for (int edge : e2){\n        v2[color[edge] - 1].first++;\n    }\n    sort(v1.rbegin(), v1.rend());\n    sort(v2.begin(), v2.end());\n    for (int i = 0; i < k; i++){\n        change[v1[i].second] = i + 1;\n    }\n    for (int edge : e1){\n        color[edge] = change[color[edge]];\n    }\n    for (int i = 0; i < k; i++){\n        change[v2[i].second] = i + 1;\n    }\n    for (int edge : e2){\n        color[edge] = change[color[edge]];\n    }\n    stabilize(e);\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    srand(time(NULL));\n#ifdef LOCAL\n    freopen(\"/Users/antontsypko/tsypko/input.txt\", \"r\", stdin);\n#endif\n    \n    cin >> n >> m >> k;\n    \n    for (int i = 1; i <= n; i++){\n        cin >> w[i];\n    }\n    \n    ll sum = 0;\n    vector<int> e;\n    for (int i = 1; i <= m; i++){\n        cin >> a[i] >> b[i];\n        sum += w[a[i]] + w[b[i]];\n        e.push_back(i);\n    }\n    \n    build(e);\n    \n    for (int i = 1; i <= m; i++){\n        assert(color[i]);\n        cout << color[i] << endl;\n    }\n    \n}",
    "tags": [
      "graphs"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1242",
    "index": "A",
    "title": "Tile Painting",
    "statement": "Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.\n\nThe path consists of $n$ consecutive tiles, numbered from $1$ to $n$. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two \\textbf{different} tiles with numbers $i$ and $j$, such that $|j - i|$ is a divisor of $n$ greater than $1$, they have the same color. Formally, the colors of two tiles with numbers $i$ and $j$ should be the same if $|i-j| > 1$ and $n \\bmod |i-j| = 0$ (where $x \\bmod y$ is the remainder when dividing $x$ by $y$).\n\nUjan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic?",
    "tutorial": "If $n = p^k$ for some prime $p$, then the answer is $p$ colors. Simply color all tiles with indices $i \\pmod p$ in color $i$. Since any divisor $d$ of $n$ greater than $1$ is divisible by $p$, then any two tiles $i$ and $i+d$ will have the same color. Also, if the first $p$ tiles are colored in $c$ different colors, then each next $p$ tiles have the same $c$ colors, hence the answer cannot be greater than $p$. If $n = pq$ for some $p, q > 1$ such that $\\gcd(p, q) = 1$ then the answer is $1$. Examine any two distinct indices $i, j$. Let's prove that they must have the same color. By the Chinese Remainder Theorem, there exists such $1 \\leq x \\leq n$ that $x \\equiv i \\pmod p$ and $x \\equiv j \\pmod q$. Therefore, both tiles $i$ and $j$ must be colored in the same color as the tile $x$. Hence, all tiles must have the same color. To check which case it is, we use the following algorithm: First we check whether $n$ is prime. We use the standard $O(\\sqrt n)$ algorithm. Otherwise, if $n = p^k$ for $k > 1$, then $p$ must be at most $\\sqrt n \\leq 10^6$. We can then find the smallest divisor $p$ of $n$ greater than $1$, which is at most $10^6$. Then we try to divide $n$ by the largest power of $p$. If $n = p^k$, then $n$ will become simply $1$; otherwise $n$ will remain greater than $1$, hence it is divisible by some prime other than $p$.",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1242",
    "index": "B",
    "title": "0-1 MST",
    "statement": "Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.\n\nIt is an undirected weighted graph on $n$ vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either $0$ or $1$; exactly $m$ edges have weight $1$, and all others have weight $0$.\n\nSince Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?",
    "tutorial": "First examine the given graph where there are only edges of weight $0$: suppose that the number of connected components in this subgraph is $k$. Then the minimum spanning tree of the given graph is equal to $k-1$. Therefore, we need to find the number of such (zero weight) components in the given graph. The following is a $O(m + n \\log n)$ solution. Let's maintain the zero weight components in the disjoint set union, and let's also store the size of each such component. Then we iterate over all vertices $v$ from $1$ to $n$. Put the vertex $v$ in a new component of size $1$. Then we iterate over the weight $1$ edges $\\{u, v\\}$ such that $u < v$. For each of the zero weight components, we count the number of edges from this component to $v$. If the number of such edges is less than the size of the component of $u$, we should merge the component of $u$ with $v$ (because there is at least one $0$ weight edge between this component and $v$). Otherwise we should not merge the component with $v$. In the end, we get the number of zero weight components. What is the complexity of such algorithm? In total, $n$ new components are created in the course of the algorithm (a new one for each of the $n$ vertices). When we merge some old component with $v$, the number of components decreases by $1$. Thus the total number of such cases during the algorithm is at most $O(n)$, and for each we have one merge call for DSU. This part has $O(n \\log n)$ complexity. When we don't merge an old component with $v$, there is at least one edge of weight $1$ from this component to $v$. Therefore, the total number of such cases is at most the number of edges, $m$. Thus the complexity of processing these cases is $O(m)$. Hence, the total complexity of the algorithm is $O(n \\log n + m)$.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1242",
    "index": "C",
    "title": "Sum Balance",
    "statement": "Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.\n\nThere are $k$ boxes numbered from $1$ to $k$. The $i$-th box contains $n_i$ integer numbers. The integers can be negative. \\textbf{All of the integers are distinct.}\n\nUjan is lazy, so he will do the following reordering of the numbers \\textbf{exactly once}. He will pick a single integer from each of the boxes, $k$ integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.\n\nUjan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?",
    "tutorial": "First, calculate the total average sum $s := (\\sum_{i=1}^n a_i)/k$. If the answer is positive, the sum of integers in each box must be equal to $s$ after reordering. If $s$ is not integer, then the answer is immediately negative. Now, suppose that an integer $x := a_{i,p}$ is taken out of some box $i$. Then we know that it should be replaced by $y := s - \\sum_{j = 1}^{n_i} a_{i,j} + a_{i,p}$. We then construct a graph where all of the given integers are vertices, and we draw a directed edge from $x$ to $y$. Note that we obtain a functional graph. Examine all of the cycles of this graph; since this a functional graph, no two cycles share the same vertex. Let $n := \\sum_{i=1}^k n_i$, then the total number of cycles is at most $n \\leq 15 \\cdot 5000 = 75000$. Examine any valid reordering. It is easy to see that it is a collection of cycles from the obtained graph such that each box is visited by some cycle exactly once. Therefore, lets extract all of the cycles from our graph such that do not pass through the same box twice. A valid reordering then is some subset of these cycles that visit all of the $k$ boxes exactly once. We can also reformulate this problem in the following way: each of the extracted cycles $C$ visits some set of boxes $S$. Find all of such subsets $S$; the number of such subsets is at most $2^k$. Now, the problem is reduced to exactly covering the set $\\{1,\\ldots,k\\}$ with some subset of such sets. This is a classical problem that can be solved in $O(3^n)$ using dynamic programming. For a subset $X$ of $\\{1,\\ldots,k\\}$, define $dp[X]$ to be true if $X$ can be exactly covered, and false otherwise. Firstly, $dp[\\varnothing] = true$. To find $dp[X]$ for $X \\neq \\varnothing$, iterate over all subsets $S$ of $X$, and check whether $S$ is visited by some cycle and $X \\setminus S$ can be covered (e.g., $dp[X \\setminus S]$ is true). Then the answer is $dp[\\{1,\\ldots,k\\}]$. This algorithm can be implemented with complexity $O(3^k)$, you can read about it here:https://cp-algorithms.com/algebra/all-submasks.html. The reordering can be restored from this DP table. The total complexity of the algorithm: $O(k \\cdot \\sum_{i=1}^k n_i + 3^k)$.",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1242",
    "index": "D",
    "title": "Number Discovery",
    "statement": "Ujan needs some rest from cleaning, so he started playing with infinite sequences. He has two integers $n$ and $k$. He creates an infinite sequence $s$ by repeating the following steps.\n\n- Find $k$ smallest distinct positive integers that are not in $s$. Let's call them $u_{1}, u_{2}, \\ldots, u_{k}$ from the smallest to the largest.\n- Append $u_{1}, u_{2}, \\ldots, u_{k}$ and $\\sum_{i=1}^{k} u_{i}$ to $s$ in this order.\n- Go back to the first step.\n\nUjan will stop procrastinating when he writes the number $n$ in the sequence $s$. Help him find the index of $n$ in $s$. In other words, find the integer $x$ such that $s_{x} = n$. It's possible to prove that all positive integers are included in $s$ only once.",
    "tutorial": "Let's make some definitions: $x$ is non-self number if $x$ is appended into $s$ by summation form. For example, if $k = 2$, then $3, 9, 13, 18, \\ldots$ are non-self numbers. $x$ is self number if $x$ is not non-self number. Let $I_{i} = [(k^2+1) \\cdot i + 1, (k^2+1) \\cdot i + 2, \\ldots, (k^2+1) \\cdot (i+1)]$. In other words, $I_{i}$ is $i$-th interval of positive integers with $k^2+1$ size. Now let me introduce some strong lemma - Every interval has exactly one non-self number. Furthermore, we can immediately determine the non-self number of $I_{k \\cdot i}, I_{k \\cdot i + 1}, I_{k \\cdot i + 2}, \\ldots, I_{k \\cdot i + k - 1}$ using non-self number of $I_{i}$. How is this possible? First, you can prove there is only $1$ non-self number in $I_{0}$. Now let's try induction. Suppose $I_{i}$ has only $1$ non-self number and each $k$ numbers of $k^2$ self numbers form summation, then you can describe generated summations as follows: $\\sum_{j=1}^{k} (i \\cdot (k^2 + 1) + t \\cdot k + j) + offset = (k \\cdot i + t) \\cdot (k^2 + 1) + \\frac{k \\cdot (k+1)}{2} - t + offset$ Where $t$ means index of subintervals in $I_{i}$ ($0 \\le t \\lt k$) and $offset$ means added offset into $t$-th subinterval ($0 \\le offset \\le k$) since $I_{i}$'s non-self number can be located at left or inside of $t$-th subinterval. Using this fact, you can solve this problem in $O(\\frac{\\log n}{\\log k})$ per test case. Some testers solved this problem by detecting pattern of distribution of non-self numbers.",
    "tags": [
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1242",
    "index": "E",
    "title": "Planar Perimeter",
    "statement": "Ujan has finally cleaned up his house and now wants to decorate the interior. He decided to place a beautiful carpet that would really tie the guest room together.\n\nHe is interested in carpets that are made up of polygonal patches such that each side of a patch is either a side of another (different) patch, or is an exterior side of the whole carpet. In other words, the carpet can be represented as a planar graph, where each patch corresponds to a face of the graph, each face is a simple polygon. The perimeter of the carpet is the number of the exterior sides.\n\nUjan considers a carpet beautiful if it consists of $f$ patches, where the $i$-th patch has exactly $a_i$ sides, and the perimeter is the smallest possible. Find an example of such a carpet, so that Ujan can order it!",
    "tutorial": "If there is just a single face, just output it. Suppose there are at least $2$ faces. Let's say that we \"glue\" a cycle to a planar graph along $k$ edges if we place this cycle so that the graph and the cycle share $k$ edges on their perimeters. First, sort the numbers in decreasing order (then we have $a_1 \\geq a_2 \\geq \\ldots \\geq a_n$). By gluing any $a_i$ to the $a_1$ cycle, we can decrease the number of edges by at most $a_i-2$. Also note that the answer is always at least $3$, because there cannot be multiple edges between two vertices. Thus, if $a_1-2 \\geq \\sum_{i=2}^n (a_i-2)$, then the answer is $a_1 - \\sum_{i=2}^n (a_i-2)$ (we subtract $2$ from $a_1$ to keep the perimeter at least $3$: these are the $2$ edges that we don't glue anything to). Otherwise the answer is either $3$ or $4$ (depending on the parity of $\\sum_{i=1}^n a_i$). The algorithm to construct the graph: let $C := a_1$. Iterate $i$ from $2$ to $n$. While $(C-2) + (a_i-2) < \\sum_{j=i+1}^n (a_j-2)$, glue the $i$-th cycle with the graph along one edge ($C += (a_i-2)$). For the first $a_i$ such that this does not hold, glue it so that $\\sum_{j=i+1}^n (a_j-2) \\leq C-2 \\leq \\sum_{j=i+1}^n (a_j-2) + 1$. Afterwards just glue each remaining cycles $a_j$ along $a_j-1$ edges with the graph. There is one problem with this algorithm: it can happen that we add multiple edges between two vertices. This situation is as follows: suppose you are at some point of the algorithm with a planar graph that you're building. Suppose there is an edge between some vertices $u$ and $v$ on the current perimeter, and you now happen to glue a cycle $C$ along the edges between $u$ and $v$, and the last edge of the cycle $C$ you're gluing must connect $u$ and $v$. To solve this situation, take the vertex $u'$ adjacent to $u$ to the right on the perimeter, and the vertex $v'$ adjacent to $v$ also to the right on the perimeter. Now, $u'$ and $v'$ cannot be connected by an edge in the current graph, because then it would intersect the edge between $u$ and $v$. This would be a contradiction, because the graph is planar. Then you glue the cycle $C$ along the edges between $u'$ and $v'$. The complexity of the algorithm: $O(\\sum_{i=1}^n a_i)$. You should be careful with the implementation: for example, not to make perimeter equal to $2$ at some point or use some edge in more than two faces.",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1243",
    "index": "A",
    "title": "Maximum Square",
    "statement": "Ujan decided to make a new wooden roof for the house. He has $n$ rectangular planks numbered from $1$ to $n$. The $i$-th plank has size $a_i \\times 1$ (that is, the width is $1$ and the height is $a_i$).\n\nNow, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.\n\nFor example, if Ujan had planks with lengths $4$, $3$, $1$, $4$ and $5$, he could choose planks with lengths $4$, $3$ and $5$. Then he can cut out a $3 \\times 3$ square, which is the maximum possible. Note that this is not the only way he can obtain a $3 \\times 3$ square.\n\nWhat is the maximum side length of the square Ujan can get?",
    "tutorial": "There are different solutions: Solution 1: Bruteforce the length of the square $l$ from $1$ to $n$. If you can make a square of side length $l$, then there should be at least $l$ planks of length at least $l$. The complexity of such solution: $O(n^2)$. The parameter $l$ can be also checked using binary search: then the complexity becomes $O(n \\log n)$. Solution 2: Suppose you want to take $i$ planks and cut the largest square from them. Of course, it is always better to take the longest $i$ planks. The side of the largest square that can be cut from them is bounded by the length of the smallest of these $i$ planks and the number of the planks, $i$. Therefore, the solution is: sort the numbers $a_i$ in descending order; then the solution is $\\max(\\min(i,a_i))$. The complexity: $O(n \\log n)$. Since the numbers $a_i$ are at most $n$, we can use counting sort and the complexity becomes $O(n)$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1243",
    "index": "B1",
    "title": "Character Swap (Easy Version)",
    "statement": "{This problem is different from the hard version. In this version Ujan makes \\textbf{exactly} one exchange. You can hack this problem only if you solve both problems.}\n\nAfter struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.\n\nUjan has two \\textbf{distinct} strings $s$ and $t$ of length $n$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions $i$ and $j$ ($1 \\le i,j \\le n$, the values $i$ and $j$ can be equal or different), and swaps the characters $s_i$ and $t_j$. Can he succeed?\n\nNote that he has to perform this operation \\textbf{exactly} once. He \\textbf{has} to perform this operation.",
    "tutorial": "First, suppose that we make the strings equal by picking some $i$, $j$. Then for all $p \\neq i, j$, we must have $s_p = t_p$, since these letters don't change. Suppose that $i = j$. Since the strings are distinct, we then must have $s_i \\neq t_i$. But then the strings are not equal also after the swap; hence, we always need to pick distinct $i$ and $j$. Now, if $i \\neq j$ and the strings are equal after the swap, we must have that $s_i = s_j$, $t_i = t_j$ and $s_i, s_j \\neq t_i, t_j$. Therefore, the solution is as follows: if the number of positions where $s$ and $t$ differ is not equal to $2$, the answer is \"No\". Otherwise we find the two positions $i$, $j$, where $s$ and $t$ differ, and check that the above conditions hold. Then the answer is \"Yes\". Complexity of the solution: $O(n)$.",
    "tags": [
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1243",
    "index": "B2",
    "title": "Character Swap (Hard Version)",
    "statement": "This problem is different from the easy version. In this version Ujan makes at most $2n$ swaps. In addition, $k \\le 1000, n \\le 50$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.\n\nAfter struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.\n\nUjan has two \\textbf{distinct} strings $s$ and $t$ of length $n$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $2n$ times: he takes two positions $i$ and $j$ ($1 \\le i,j \\le n$, the values $i$ and $j$ can be equal or different), and swaps the characters $s_i$ and $t_j$.\n\nUjan's goal is to make the strings $s$ and $t$ equal. He does not need to minimize the number of performed operations: \\textbf{any} sequence of operations of length $2n$ or shorter is suitable.",
    "tutorial": "We claim that you can make the strings equal if and only if the total number of each character in both of the strings $s$ and $t$ is even. Proof that this is a necessary condition. If we can make the strings equal, then for each position, the characters of $s$ and $t$ will be the same. Therefore, each character must appear an even number of times in both strings together. Algorithm, if all characters appear even number of times. Iterate over the index $i$ from $1$ to $n$. If $s_i \\neq t_i$, then one of the following cases holds: There is an index $j > i$ such that $s_i = s_j$. Then simply swap $s_j$ with $t_i$ and then the strings will have the same character at position $i$. There is an index $j > i$ such that $s_i = t_j$. Then first swap $t_j$ with $s_j$, and then swap $s_j$ with $t_i$. Again, the strings will have the same character at position $i$. This problem was introduced by [user:MikeMirzayanov] inspired by the easier version of the problem (with a single swap).",
    "tags": [
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1244",
    "index": "A",
    "title": "Pens and Pencils",
    "statement": "Tomorrow is a difficult day for Polycarp: he has to attend $a$ lectures and $b$ practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.\n\nWhile preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down $c$ lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during $d$ practical classes, after which it is unusable.\n\nPolycarp's pencilcase can hold no more than $k$ writing implements, so if Polycarp wants to take $x$ pens and $y$ pencils, they will fit in the pencilcase if and only if $x + y \\le k$.\n\nNow Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!\n\nNote that you don't have to minimize the number of writing implements (though their total number must not exceed $k$).",
    "tutorial": "There is a solution with brute force in $O(n^2)$ and a solution with formulas in $O(1)$. I'll describe the latter one. We should determine the minimum number of pens that we should take to be able to write all of the lectures. It is $\\lceil \\frac{a}{c} \\rceil$, but how to compute it easily? We can use some internal ceiling functions. We can also do something like \"compute the integer part of the quotient, and then add $1$ if the remainder is not zero\". But the easiest option, in my opinion, is to use the following formula: $\\lceil \\frac{a}{c} \\rceil = \\lfloor \\frac{a + c - 1}{c} \\rfloor$. The minimum number of pencils can be calculated using the same method. All that's left is to check that $k$ is not less than the total number of writing implements we should take.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1244",
    "index": "B",
    "title": "Rooms and Staircases",
    "statement": "Nikolay lives in a two-storied house. There are $n$ rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between $1$ and $n$).\n\nIf Nikolay is currently in some room, he can move to any of the neighbouring rooms (if they exist). Rooms with numbers $i$ and $i+1$ on each floor are neighbouring, for all $1 \\leq i \\leq n - 1$. There may also be staircases that connect two rooms from different floors having the same numbers. If there is a staircase connecting the room $x$ on the first floor and the room $x$ on the second floor, then Nikolay can use it to move from one room to another.\n\n\\begin{center}\n{\\small The picture illustrates a house with $n = 4$. There is a staircase between the room $2$ on the first floor and the room $2$ on the second floor, and another staircase between the room $4$ on the first floor and the room $4$ on the second floor. The arrows denote possible directions in which Nikolay can move. The picture corresponds to the string \"0101\" in the input.}\n\\end{center}\n\nNikolay wants to move through some rooms in his house. To do this, he firstly chooses any room where he starts. Then Nikolay moves between rooms according to the aforementioned rules. Nikolay never visits the same room twice (he won't enter a room where he has already been).\n\nCalculate the maximum number of rooms Nikolay can visit during his tour, if:\n\n- he can start \\textbf{in any room on any floor of his choice},\n- and \\textbf{he won't visit the same room twice}.",
    "tutorial": "If there are no stairs, the best we can do is to visit all the rooms on the same floor, so the answer is $n$. Otherwise, the best course of action is to choose exactly one stair (let's denote its number by $s$) and do one of the following: either start from the leftmost room on the first floor, then use the stair and move to the leftmost room on the second floor, or do the same, but start and end in rightmost rooms instead of leftmost ones. Then for choosing the stair in room $s$, we get $max(2s, 2(n - s + 1))$ as the answer. Why is it optimal? Let's denote the leftmost stair as $l$, and the rightmost stair as $r$. There are four special segments of rooms such that if we enter them, we can't leave. These are: rooms $[1 \\dots l - 1]$ on the first floor, rooms $[1 \\dots l - 1]$ on the second floor, rooms $[r + 1 \\dots n]$ on the first floor and rooms $[r + 1 \\dots n]$ on the second floor. We can visit only two of them, if one contains the starting room and the other contains the ending room. So the answer cannot be greater than $2n - 2min(l - 1, n - r - 1)$ - and our algorithm will give exactly this value either by choosing stair $l$, or by choosing the stair $r$.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1244",
    "index": "C",
    "title": "The Football Season",
    "statement": "The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets $w$ points, and the opposing team gets $0$ points. If the game results in a draw, both teams get $d$ points.\n\nThe manager of the Berland capital team wants to summarize the results of the season, but, unfortunately, all information about the results of each match is lost. The manager only knows that the team has played $n$ games and got $p$ points for them.\n\nYou have to determine three integers $x$, $y$ and $z$ — the number of wins, draws and loses of the team. If there are multiple answers, print any of them. If there is no suitable triple $(x, y, z)$, report about it.",
    "tutorial": "The crucial observation is that $d$ wins give us the same amount of points as $w$ draws. Let's use them to solve a problem where we want to minimize the total amount of wins and draws giving $p$ points (if it is not greater than $n$, we can just lose all other matches). If $y \\ge w$, then we can subtract $w$ from $y$ and add $d$ to $x$, the number of wins and draws will decrease, and the number of points will stay the same. So we can limit the number of draws to $w - 1$. And the solution is the following: iterate on the number of draws $y$ from $0$ to $w - 1$, and check if the current value of $y$ gives us the result we need ($p - yd$ should be non-negative and divisible by $w$, and $\\frac{p - yd}{w} + y$ should be not greater than $n$).",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1244",
    "index": "D",
    "title": "Paint the Tree",
    "statement": "You are given a tree consisting of $n$ vertices. A tree is an undirected connected acyclic graph.\n\n\\begin{center}\n{\\small Example of a tree.}\n\\end{center}\n\nYou have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.\n\nYou have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $(x, y, z)$ such that $x \\neq y, y \\neq z, x \\neq z$, $x$ is connected by an edge with $y$, and $y$ is connected by an edge with $z$. The colours of $x$, $y$ and $z$ should be pairwise distinct. Let's call a painting which meets this condition good.\n\nYou have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.",
    "tutorial": "The key observation is that if we fix the colors of two adjacent vertices $x$ and $y$, then the color of any vertex adjacent to $x$ or to $y$ can be only $6 - c_x - c_y$. So we can fix the colors of the endpoints of any edge (there are $6$ possibilities to do that), then do a traversal to color all other vertices, then do another traversal to check that we got a good painting. To avoid checking that the painting we got is good (which can be tricky to code), we can use the fact that, for each vertex, the colors of all its neighbours should be different from each other and from the color of the vertex we fixed. So, if some vertex has degree $3$ or greater, then there is no good painting; otherwise the painting we get is good, since the graph is a chain.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1244",
    "index": "E",
    "title": "Minimizing Difference",
    "statement": "You are given a sequence $a_1, a_2, \\dots, a_n$ consisting of $n$ integers.\n\nYou may perform the following operation on this sequence: choose any element and either increase or decrease it by one.\n\nCalculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation \\textbf{no more than} $k$ times.",
    "tutorial": "Suppose that the maximum value in the resulting array should be $R$, and the minimum value should be $L$. Let's estimate the required number of operations to make an array with such properties. All elements that are less than $L$ should be increased to $L$, and all elements that are greater than $R$ should be decreased to $R$ - and we don't have to do any operation with remaining elements. Now we claim that either $L$ or $R$ should belong to the initial array. Why so? Suppose we constructed an answer such that $L \\notin A$ and $R \\notin A$. If the number of elements we increased to $L$ is not less than the number of elements we decreased to $R$, then we could construct the answer with minimum equal to $L - 1$ and maximum equal to $R - 1$, and it would not require more operations. And if the number of elements we increased to $L$ is less than the number of elements we decreased to $R$, then we construct the answer for $L + 1$ as minimum and $R + 1$ as maximum. So we can shift the range $[L, R]$ so that one of its endpoints belongs to the initial array. Now we can solve the problem as follows: iterate on the maximum in the resulting array and find the largest minimum we can obtain with binary search, and then do it vice versa: iterate on the minimum in the resulting array and find the largest maximum we can obtain with binary search. To check how many operations we need, for example, to make all values not less than $L$, we can find the number of elements that we have to change with another binary search (let the number of such elements be $m$), and find their sum with prefix sums (let their sum be $S$). Then the required number of operations is exactly $Lm - S$. The same approach can be used to find the number of operations to make all elements not greater than $R$. This is the way the problem was supposed to solve, but, unfortunately, we failed to find a much easier greedy solution.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "sortings",
      "ternary search",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1244",
    "index": "F",
    "title": "Chips",
    "statement": "There are $n$ chips arranged in a circle, numbered from $1$ to $n$.\n\nInitially each chip has black or white color. Then $k$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $i$, three chips are considered: chip $i$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $i$ becomes white. Otherwise, the chip $i$ becomes black.\n\nNote that for each $i$ from $2$ to $(n - 1)$ two neighbouring chips have numbers $(i - 1)$ and $(i + 1)$. The neighbours for the chip $i = 1$ are $n$ and $2$. The neighbours of $i = n$ are $(n - 1)$ and $1$.\n\nThe following picture describes one iteration with $n = 6$. The chips $1$, $3$ and $4$ are initially black, and the chips $2$, $5$ and $6$ are white. After the iteration $2$, $3$ and $4$ become black, and $1$, $5$ and $6$ become white.\n\nYour task is to determine the color of each chip after $k$ iterations.",
    "tutorial": "The main observation for this problem is the following: a chip changes its color if and only if both of its neighbours have the opposite colors (so, a W chip changes its color only if both of its neighbours are B, and vice versa). Let's denote such chips as unstable, and also let's denote an unstable segment as a maximum by inclusion sequence of consecutive unstable chips. Let's analyze each unstable segment. If it covers the whole circle, then the whole circle changes during each iteration, so the answer depends on whether $k$ is odd or even. Otherwise the unstable segment we analyze is bounded by two stable chips. When the first chip in the unstable segment changes, its color becomes equal to the color of its neighbour that does not belong to the unstable segment. We can also say the same for the last chip. So, during each iteration all chips in the unstable segment change their colors, and after that, the segment shrinks (the first and the last chip become stable and won't change their colors anymore). All that's left is to find all unstable segments and analyze how they change.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1244",
    "index": "G",
    "title": "Running in Pairs",
    "statement": "Demonstrative competitions will be held in the run-up to the $20NN$ Berlatov Olympic Games. Today is the day for the running competition!\n\nBerlatov team consists of $2n$ runners which are placed on two running tracks; $n$ runners are placed on each track. The runners are numbered from $1$ to $n$ on each track. The runner with number $i$ runs through the entire track in $i$ seconds.\n\nThe competition is held as follows: first runners on both tracks start running at the same time; when the slower of them arrives at the end of the track, second runners on both tracks start running, and everyone waits until the slower of them finishes running, and so on, until all $n$ pairs run through the track.\n\nThe organizers want the run to be as long as possible, but if it lasts for more than $k$ seconds, the crowd will get bored. As the coach of the team, you may choose any order in which the runners are arranged on each track (but you can't change the number of runners on each track or swap runners between different tracks).\n\nYou have to choose the order of runners on each track so that the duration of the competition is as long as possible, but does not exceed $k$ seconds.\n\nFormally, you want to find two permutations $p$ and $q$ (both consisting of $n$ elements) such that $sum = \\sum\\limits_{i=1}^{n} max(p_i, q_i)$ is maximum possible, but does not exceed $k$. If there is no such pair, report about it.",
    "tutorial": "First of all, let's understand which values of $sum$ we can obtain at all. Obviously, the minimum possible value of $sum$ is $mn = \\frac{n(n+1)}{2}$. The maximum possible value of $sum$ is $mx = (\\lceil\\frac{n}{2}\\rceil + 1 + n) \\cdot \\lfloor\\frac{n}{2}\\rfloor + n \\% 2 \\cdot \\lceil\\frac{n}{2}\\rceil$. We can obtain every possible value of $sum$ between $mn$ and $mx$ and we will show how to do it below. If $k < mn$ then the answer is -1 (and this is the only such case). Otherwise, the answer exists and we need to construct it somehow. Firstly, suppose that the first permutation is identic permutation ($1, 2, \\dots, n$) and the only permutation we change is the second one. Initially, the second permutation is also identic. Now we have $sum = mn$ and we need to change it to $sum = k$ or to the maximum possible number not greater than $k$. To do that, let's learn how to increase $sum$ by one. Let's see what will happen if we swap $n$ and $n-1$. Then the value of $sum$ will increase by one. If we swap $n$ and $n-2$ then the value of $sum$ will increase by $2$, and so on. If we swap $n$ and $1$ then the value of $sum$ will increase by $n-1$. So, the following constructive algorithm comes to mind: let's carry the current segment of permutation $[l; r]$ we can change (it is always segment because after some swaps some leftmost and rightmost elements cannot increase our answer because they're will be already placed optimally) and the value $add$ we need to add to $sum$ to obtain the maximum possible sum not greater than $k$. Initially $l=1, r=n, add = k - mn$. Now let's understand the maximum value by which we can increase the value of $sum$. Now it is $r-l$. If this value is greater than $add$ then let's swap $p_r$ and $p_{r - add}$, and break the cycle ($p$ is the second permutation). Otherwise, let's swap $p_l$ and $p_r$, decrease $add$ by $r-l$ and set $l := l + 1, r := r - 1$ . If at some moment $l$ becomes greater than or equal to $r$ then break the cycle. Now we got the second permutation $p$ with the maximum possible value of $sum$ not greater than $k$, we can calculate the numeric answer (or print $min(mx, k)$), print identic permutation and the permutation $p$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1245",
    "index": "A",
    "title": "Good ol' Numbers Coloring",
    "statement": "Consider the set of all nonnegative integers: ${0, 1, 2, \\dots}$. Given two integers $a$ and $b$ ($1 \\le a, b \\le 10^4$). We paint all the numbers in increasing number first we paint $0$, then we paint $1$, then $2$ and so on.\n\nEach number is painted white or black. We paint a number $i$ according to the following rules:\n\n- if $i = 0$, it is colored white;\n- if $i \\ge a$ and $i - a$ is colored white, $i$ is also colored white;\n- if $i \\ge b$ and $i - b$ is colored white, $i$ is also colored white;\n- if $i$ is still not colored white, it is colored black.\n\nIn this way, each nonnegative integer gets one of two colors.\n\nFor example, if $a=3$, $b=5$, then the colors of the numbers (in the order from $0$) are: white ($0$), black ($1$), black ($2$), white ($3$), black ($4$), white ($5$), white ($6$), black ($7$), white ($8$), white ($9$), ...\n\nNote that:\n\n- It is possible that there are infinitely many nonnegative integers colored black. For example, if $a = 10$ and $b = 10$, then only $0, 10, 20, 30$ and any other nonnegative integers that end in $0$ when written in base 10 are white. The other integers are colored black.\n- It is also possible that there are only finitely many nonnegative integers colored black. For example, when $a = 1$ and $b = 10$, then there is no nonnegative integer colored black at all.\n\nYour task is to determine whether or not the number of nonnegative integers colored \\textbf{black} is infinite.\n\nIf there are infinitely many nonnegative integers colored black, simply print a line containing \"Infinite\" (without the quotes). Otherwise, print \"Finite\" (without the quotes).",
    "tutorial": "If $\\gcd(a, b) \\neq 1$, print \"Infinite\". This is correct because any integer that isn't divisible by $\\gcd(a, b)$ will not be expressible in the form $ax + by$ since $ax + by$ is always divisible by $\\gcd(a, b)$. Otherwise, print \"Finite\". To show that this is correct, we will prove that any integer greater than $ab$ is colored white. Let $x$ be an integer greater than $ab$. Consider the set $S = \\{x, x - a, x - 2a, \\ldots, x - (b - 1) a\\}$. If, for any $y \\in S$, $y$ is divisible by $b$, we are done. Otherwise, by the pigeonhole principle, there exists distinct $x - sa, x - ta \\in S$ such that they have the same remainder when divided by $b$, thus $b$ divides $(x - sa) - (x - ta) = a (t - s)$. WLOG, let $s < t$. Thus, $0 < t - s$ and $b$ divides $t - s$, since $\\gcd(a, b) = 1$. But $t - s \\leq t < b$. However, it is not possible for $b$ to divide any integer $x$ such that $0 < x < b$, thus we arrive at a contradiction.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint gcd(int a, int b)\n{\n    while (b)\n    {\n        a %= b;\n        swap(a, b);\n    }\n    \n    return a;\n}\n\nint main()\n{\n    int t;\n    for (cin >> t; t--;)\n    \n    {\n        int a, b;\n        cin >> a >> b;\n        \n        if (gcd(a, b) == 1)\n            cout << \"Finite\" << '\\n';\n        else\n            cout << \"Infinite\" << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1245",
    "index": "B",
    "title": "Restricted RPS",
    "statement": "Let $n$ be a positive integer. Let $a, b, c$ be nonnegative integers such that $a + b + c = n$.\n\nAlice and Bob are gonna play rock-paper-scissors $n$ times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock $a$ times, paper $b$ times, and scissors $c$ times.\n\nAlice wins if she beats Bob in at least $\\lceil \\frac{n}{2} \\rceil$ ($\\frac{n}{2}$ rounded up to the nearest integer) hands, otherwise Alice loses.\n\nNote that in rock-paper-scissors:\n\n- rock beats scissors;\n- paper beats rock;\n- scissors beat paper.\n\nThe task is, given the sequence of hands that Bob will play, and the numbers $a, b, c$, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win.\n\nIf there are multiple answers, print any of them.",
    "tutorial": "Let $A$, $B$, $C$ be the number of rocks, papers, and scissors in Bob's sequence, respectively. It is easy to see that Alice can win at most $w := \\min(A, b) + \\min(B, c) + \\min(C, a)$ hands. So if $2w < n$, Alice can't win. Otherwise, Alice can always win. One way to construct a winning sequence of hands for Alice is as follows: Create a sequence of length $n$. For Bob's first $\\min(A, b)$ rock hands, put a paper hand in the corresponding position in our sequence. For Bob's first $\\min(B, c)$ paper hands, put a scissors hand in the corresponding position in our sequence. For Bob's first $\\min(C, a)$ scissors hands, put a rock hand in the corresponding position in our sequence. Just fill in the other elements of the sequence by the remaining hands that Alice has. By construction, Alice uses exactly $a$ rock hands, $b$ paper hands, and $c$ scissors hands. Also, Alice beats Bob exactly $w$ times. Since $2w \\ge n$, Alice wins.",
    "code": "#include <vector>\n#include <string>\n#include <iostream>\n#include <cstdio>\n#include <algorithm>\n#include <stack>\n#include <queue>\n#include <deque>\n#include <set>\n#include <map>\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    \n    int q;\n    for (cin >> q; q--;)\n    {\n        int n;\n        cin >> n;\n        int a, b, c;\n        cin >> a >> b >> c;\n        string s;\n        cin >> s;\n        \n        vector<int> count(26);\n        for (char x : s)\n        \tcount[x - 'A']++;\n        \n        int wins = min(a, count['S' - 'A']) + min(b, count['R' - 'A']) + min(c, count['P' - 'A']);\n        \n        if (2 * wins < n)\n        {\n        \tcout << \"NO\" << '\\n';continue;\n        }\n        \n        cout << \"YES\" << '\\n';\n        string t;\n        for (int i = 0; i != n; ++i)\n        {\n        \tif (s[i] == 'S' && a)\n        \t{\n        \t\tt += 'R';\n        \t\ta--;\n        \t}\n        \telse if (s[i] == 'R' && b)\n        \t{\n        \t\tt += 'P';\n        \t\tb--;\n        \t}\n        \telse if (s[i] == 'P' && c)\n        \t{\n        \t\tt += 'S';\n        \t\tc--;\n        \t}\n        \telse\n        \t\tt += '_';\n        }\n        for (int i = 0; i != n; ++i)\n        {\n        \tif (t[i] != '_')\n        \t\tcontinue;\n        \t\n        \tif (a)\n        \t{\n        \t\tt[i] = 'R';\n        \t\ta--;\n        \t}\n        \telse if (b)\n        \t{\n        \t\tt[i] = 'P';\n        \t\tb--;\n        \t}\n        \telse\n        \t{\n        \t\tt[i] = 'S';\n        \t\tc--;\n        \t}\n        }\n        cout << t << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1245",
    "index": "C",
    "title": "Constanze's Machine",
    "statement": "Constanze is the smartest girl in her village but she has bad eyesight.\n\nOne day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe \"code\" onto the paper. Thanks to this machine, she can finally write messages without using her glasses.\n\nHowever, her dumb friend Akko decided to play a prank on her. Akko tinkered with the machine so that if you pronounce 'w', it will inscribe \"uu\" instead of \"w\", and if you pronounce 'm', it will inscribe \"nn\" instead of \"m\"! Since Constanze had bad eyesight, she was not able to realize what Akko did.\n\nThe rest of the letters behave the same as before: if you pronounce any letter besides 'w' and 'm', the machine will just inscribe it onto a piece of paper.\n\nThe next day, I received a letter in my mailbox. I can't understand it so I think it's either just some gibberish from Akko, or Constanze made it using her machine. But since I know what Akko did, I can just list down all possible strings that Constanze's machine would have turned into the message I got and see if anything makes sense.\n\nBut I need to know how much paper I will need, and that's why I'm asking you for help. Tell me the number of strings that Constanze's machine would've turned into the message I got.\n\nBut since this number can be quite large, tell me instead its remainder when divided by $10^9+7$.\n\nIf there are no strings that Constanze's machine would've turned into the message I got, then print $0$.",
    "tutorial": "If $s$ has any 'm' or 'w', the answer is 0. Otherwise, we can do dp. Define $dp_i$ to be the number of strings that Constanze's machine would've turned into the first $i$ characters of $s$. Then, $dp_0 = dp_1 = 1$. For $i > 1$, transition is $dp_i = dp_{i - 1} + dp_{i - 2}$ if both $s_i = s_{i - 1}$ and $s_i$ is either 'u' or 'n', and simply $dp_i = dp_{i - 1}$ otherwise. Answer is $dp_{|s|}$. Alternatively, notice that the maximum cardinality segment consisiting of $k$ letters 'u' or 'n' multiplies the answer by the $k$-th term of Fibonacci sequence. Thus, you can precalculate it and some sort of two iterators.",
    "code": "// In the name of Allah.\n// We're nothing and you're everything.\n// Ya Ali!\n \n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n \nconst int maxn = 1e5 + 14, mod = 1e9 + 7;\n\nint n, fib[maxn];\n\nint main(){\n    ios::sync_with_stdio(0), cin.tie(0);\n    fib[0] = fib[1] = 1;\n    for(int i = 2; i < maxn; i++)\n        fib[i] = (fib[i - 1] + fib[i - 2]) % mod;\n    string s;\n    cin >> s;\n    n = s.size();\n    if(s.find('m') != -1 || s.find('w') != -1)\n        return cout << \"0\\n\", 0;\n    int ans = 1;\n    for(int i = 0, j = 0; i < n; i = j){\n        while(j < n && s[j] == s[i])\n            j++;\n        if(s[i] == 'n' || s[i] == 'u')\n            ans = (ll) ans * fib[j - i] % mod;\n    }\n    cout << ans << '\\n';\n}",
    "tags": [
      "dp"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1245",
    "index": "D",
    "title": "Shichikuji and Power Grid",
    "statement": "Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:\n\nThere are $n$ new cities located in Prefecture X. Cities are numbered from $1$ to $n$. City $i$ is located $x_i$ km North of the shrine and $y_i$ km East of the shrine. It is possible that $(x_i, y_i) = (x_j, y_j)$ even when $i \\ne j$.\n\nShichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections.\n\n- Building a power station in City $i$ will cost $c_i$ yen;\n- Making a connection between City $i$ and City $j$ will cost $k_i + k_j$ yen \\textbf{per km of wire} used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City $i$ and City $j$ are connected by a wire, the wire will go through any shortest path from City $i$ to City $j$. Thus, the length of the wire if City $i$ and City $j$ are connected is $|x_i - x_j| + |y_i - y_j|$ km.\n\nShichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help.\n\nAnd so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made.\n\nIf there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.",
    "tutorial": "Claim. Let $i$ be such that $c_i$ is minimum, then there is an optimal configuration with a power station in City $i$. Proof. Consider an optimal configuration. Let's say that City $u$ and City $v$ are in the same component if they are connected or City $v$ is connected to a City $w$ such that City $w$ is in the same component as City $u$. Consider the cities that are in the same component as City $i$. Exactly one of these cities have a power station, since having a power station in one of these cities is enough to provide electricity to all of them. Let City $j$ be the one with a power station. If $i = j$, then we are done. Otherwise, there are three cases: $c_i < c_j$, $c_i = c_j$, $c_i > c_j$. The first case leads to a contradiction since having a power station in City $i$ would be more optimal. The third case also leads to a contradiction since $c_i$ is minimum. For the remaining case, having a power station in City $i$ would be just as optimal. Let $i$ be such that $c_i$ is minimum. Build a power station in City $i$. For $j \\neq i$, define $C_j := min(c_j, (k_i + k_j) \\cdot D(i, j))$ where $D(i, j)$ is the manhattan distance between City $i$ and City $j$. Notice that the problem has been reduced to a similar problem, except that there is one less city, and $c$ values have been changed to the corresponding $C$ values. Thus, we can keep reducing until there are no cities left. Alternatively, you can think of it the following way. Let's call a connection between City $u$ and City $v$, an undirected edge $(u, v)$ with the weight $(k_u + k_v) \\cdot D(u, v)$. Create a dummy City $0$ and connect each City $u$ to it with an edge $(0, u)$ with the weight $c_u$. The problem now is to find a minimal spanning tree of this graph. Prim's algorithm can do this in $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nint main(){\n    int n;\n    scanf(\"%d\", &n);\n    vector<int> x(n), y(n);\n    forn(i, n)\n        scanf(\"%d%d\", &x[i], &y[i]);\n    vector<int> c(n), k(n);\n    forn(i, n)\n        scanf(\"%d\", &c[i]);\n    forn(i, n)\n        scanf(\"%d\", &k[i]);\n    \n    ++n;\n    vector<int> p(n, -1);\n    vector<int> d(n, int(1e9));\n    vector<bool> used(n);\n    \n    forn(i, n - 1){\n        d[i] = c[i];\n        p[i] = n - 1;\n    }\n    used[n - 1] = true;\n    \n    long long ans = 0;\n    vector<int> vv;\n    vector<pair<int, int>> ee;\n    \n    forn(_, n - 1){\n        int v = -1;\n        forn(i, n) if (!used[i] && (v == -1 || d[v] > d[i]))\n            v = i;\n        \n        if (p[v] == n - 1)\n            vv.push_back(v + 1);\n        else\n            ee.push_back(make_pair(v + 1, p[v] + 1));\n        ans += d[v];\n        \n        used[v] = true;\n        forn(i, n) if (!used[i]){\n            long long dist = (k[v] + k[i]) * 1ll * (abs(x[v] - x[i]) + abs(y[v] - y[i]));\n            if (dist < d[i]){\n                d[i] = dist;\n                p[i] = v;\n            }\n        }\n    }\n    \n    printf(\"%lld\\n\", ans);\n    printf(\"%d\\n\", int(vv.size()));\n    for (auto it : vv)\n        printf(\"%d \", it);\n    puts(\"\");\n    printf(\"%d\\n\", int(ee.size()));\n    for (auto it : ee)\n        printf(\"%d %d\\n\", it.first, it.second);\n}",
    "tags": [
      "dsu",
      "graphs",
      "greedy",
      "shortest paths",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1245",
    "index": "E",
    "title": "Hyakugoku and Ladders",
    "statement": "Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing \"Cat's Cradle\" so now she wants to try a different game — \"Snakes and Ladders\". Unfortunately, she already killed all the snakes, so there are only ladders left now.\n\nThe game is played on a $10 \\times 10$ board as follows:\n\n- At the beginning of the game, the player is at the bottom left square.\n- The objective of the game is for the player to reach the Goal (the top left square) by following the path and climbing vertical ladders. Once the player reaches the Goal, the game ends.\n- The path is as follows: if a square is not the end of its row, it leads to the square next to it along the direction of its row; if a square is the end of its row, it leads to the square above it. The direction of a row is determined as follows: the direction of the bottom row is to the right; the direction of any other row is opposite the direction of the row below it. See Notes section for visualization of path.\n- During each turn, the player rolls a standard six-sided dice. Suppose that the number shown on the dice is $r$. If the Goal is less than $r$ squares away on the path, the player doesn't move (but the turn is performed). Otherwise, the player advances exactly $r$ squares along the path and then stops. If the player stops on a square with the bottom of a ladder, the player \\textbf{chooses whether or not to climb up} that ladder. If she chooses not to climb, then she stays in that square for the beginning of the next turn.\n- Some squares have a ladder in them. Ladders are only placed vertically — each one leads to the same square of some of the upper rows. In order for the player to climb up a ladder, after rolling the dice, she must stop at the square containing the bottom of the ladder. After using the ladder, the player will end up in the square containing the top of the ladder. She cannot leave the ladder in the middle of climbing. And if the square containing the top of the ladder also contains the bottom of another ladder, she is not allowed to use that second ladder.\n- The numbers on the faces of the dice are 1, 2, 3, 4, 5, and 6, with each number having the same probability of being shown.\n\nPlease note that:\n\n- it is possible for ladders to overlap, but the player cannot switch to the other ladder while in the middle of climbing the first one;\n- it is possible for ladders to go straight to the top row, but not any higher;\n- it is possible for two ladders to lead to the same tile;\n- it is possible for a ladder to lead to a tile that also has a ladder, but the player will not be able to use that second ladder if she uses the first one;\n- the player can only climb up ladders, not climb down.\n\nHyakugoku wants to finish the game as soon as possible. Thus, on each turn she chooses whether to climb the ladder or not optimally. Help her to determine the minimum expected number of turns the game will take.",
    "tutorial": "To make implementation easier, flatten the board into an array $a$ such that the $i$-th tile on the path is $a_i$. Define a function $f$ as follows: $f(i) = i$ if $a_i$ has no ladder, otherwise $f(i) = j$ where $j$ is such that the ladder from $a_i$ leads to $a_j$. Then, do dp. Define $dp_i$ to be the minimum expected number of turns before the game ends when the player is at $a_i$. Then, $dp_{100} = 0$ since $a_{100}$ is the Goal. Next, use the formula $dp_i = 1 + \\sum_{r = 1}^{6} \\frac{1}{6} \\cdot \\min(dp_{g(i, r)}, dp_{f(g(i, r))})$ where $g(i, r) = i + r$ if $i + r \\leq 100$ and $g(i, r) = i$ otherwise. Thus, for $95 \\leq i \\leq 99$, transition should be $dp_i = \\frac{6}{100 - i} \\cdot \\left( 1 + \\sum_{r = 1}^{100 - i} \\frac{1}{6} \\cdot \\min(dp_{i + r}, dp_{f(i + r)}) \\right)$. And for $i < 95$, transition is the same as the formula. Answer is $dp_1$. Alternatively, instead of doing dp, we can use numerical methods. Initialize $\\textrm{expected}_{100} = 0$ and $\\textrm{expected}_1 = \\textrm{expected}_2 = \\cdots = \\textrm{expected}_{99} = 1$. Then, repeat the following several times: from $i=99$ to $i=1$, assign $1 + \\sum_{r = 1}^{6} \\frac{1}{6} \\cdot \\min(\\textrm{expected}_{g(i, r)}, \\textrm{expected}_{f(g(i, r))})$ to $\\textrm{expected}_i$. After each iteration, $\\textrm{expected}_1$ will get closer to the answer. For this problem, 1000 iterations is more than enough to get AC using this method.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    \n    int grid[10][10];\n    for (int i = 0; i != 10; ++i)\n        for (int j = 0; j != 10; ++j)\n            cin >> grid[i][j];\n    \n    int flat[10][10];\n    for (int i = 0; i != 10; ++i)\n        for (int j = 0; j != 10; ++j)\n                flat[i][j] = (9 - i) * 10 + ((i & 1) ? j : 9 - j);\n    \n    int d = 1;\n    int x = 9;\n    int y = 0;\n    int arr[100];\n    for (int i = 0; i != 100; ++i)\n    {\n        arr[i] = flat[x - grid[x][y]][y];\n        \n        if (y + d == -1 || y + d == 10)\n        {\n            d *= -1;\n            x--;\n        }\n        else\n            y += d;\n    }\n    \n    double dp[100];\n    dp[99] = 0;\n    for (int i = 98; i >= 0; --i)\n    {\n        dp[i] = 1;\n        \n        int c = 6;\n        for (int r = 1; r <= 6; ++r)\n        {\n            if (i + r >= 100)\n                continue;\n            dp[i] += min(dp[i + r], dp[arr[i + r]]) / 6;\n            c--;\n        }\n        \n        dp[i] = 6 * dp[i] / (6 - c);\n    }\n    \n    cout << setprecision(10) << fixed << dp[0] << '\\n';\n    \n    return 0;\n}",
    "tags": [
      "dp",
      "probabilities",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1245",
    "index": "F",
    "title": "Daniel and Spring Cleaning",
    "statement": "While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute $1 + 3$ using the calculator, he gets $2$ instead of $4$. But when he tries computing $1 + 4$, he gets the correct answer, $5$. Puzzled by this mystery, he opened up his calculator and found the answer to the riddle: the full adders became half adders!\n\nSo, when he tries to compute the sum $a + b$ using the calculator, he instead gets the xorsum $a \\oplus b$ (read the definition by the link: https://en.wikipedia.org/wiki/Exclusive_or).\n\nAs he saw earlier, the calculator sometimes gives the correct answer. And so, he wonders, given integers $l$ and $r$, how many pairs of integers $(a, b)$ satisfy the following conditions: $$a + b = a \\oplus b$$ $$l \\leq a \\leq r$$ $$l \\leq b \\leq r$$\n\nHowever, Daniel the Barman is going to the bar and will return in two hours. He tells you to solve the problem before he returns, or else you will have to enjoy being blocked.",
    "tutorial": "Claim. Let $x$, $y$ be nonnegative integers. If $x + y = x \\oplus y$, then $x * y = 0$, where $x * y$ is the bitwise AND of $x$ and $y$. Proof. Recall that bitwise XOR is just addition in base two without carry. So if addition is to be equal to addition in base two without carry, then there must be no carry when added in base two, which is what we wanted. Define a function $f$ as follows: let $l$ and $r$ be nonnegative integers, then $f(l, r)$ should be the number of pairs of integers $(x, y)$ such that the following conditions are satisfied: $l \\leq x < r$ $l \\leq y < r$ $x + y = x \\oplus y$ Notice that $f(0, r) = 2r - 1 + f(1, r)$. Claim. Let $l$ and $r$ be positive integers. Then, $f(2l, 2r) = 3 \\cdot f(l, r)$. Proof. Let $x$, $y$ be positive integers. Suppose we want the following conditions to be satisfied: $2l \\leq x < 2r$ $2l \\leq y < 2r$ $x + y = x \\oplus y$ What if $l$ and $r$ are not both even? Define a function $g$ as follows: let $x$ and $n$ be nonnegative integers, then $g(x, n)$ should be the number of integers $y$ such that the following conditions are satisfied: $0 \\leq y < n$ $x + y = x \\oplus y$ Now all that remains is to implement $g$ efficiently. Define a function $\\textrm{LSB}$ as follows: let $n$ be a positive integer, then $\\textrm{LSB}(n)$ should be the least significant 1-bit of $n$. Next, define a function $h$ as follows: let $x$ and $n$ be positive integers, then $h(x, n)$ should be the number of integers $y$ such that the following conditions are satisfied: $n - \\textrm{LSB}(n) \\leq y < n$ $x + y = x \\oplus y$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint f(int a, int b)\n{\n    int ret = 0;\n    int zeroes = 0;\n    \n    for (int i = 1; i <= b; i <<= 1)\n    {\n        if (b & i)\n        {\n            b ^= i;\n            \n            if (!(a & b))\n                ret += 1 << zeroes;\n        }\n        \n        if (!(a & i))\n            zeroes++;\n    }\n    \n    return ret;\n}\n\nlong long rec(int a, int b)\n{\n    if (a == b)\n        return 0;\n    if (a == 0)\n        return 2 * b - 1 + rec(1, b);\n    \n    long long ret = 0;\n    if (a & 1)\n    {\n        ret += 2 * (f(a, b) - f(a, a));\n        a++;\n    }\n    if (b & 1)\n    {\n        ret += 2 * (f(b - 1, b) - f(b - 1, a));\n        b--;\n    }\n    \n    return ret + 3 * rec(a / 2, b / 2);\n}\n\nint main()\n{\n    int t;\n    for (cin >> t; t--;)\n    {\n        int a, b;\n        cin >> a >> b;\n        cout << rec(a, b + 1) << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1246",
    "index": "F",
    "title": "Cursor Distance",
    "statement": "There is a string $s$ of lowercase English letters. A cursor is positioned on one of the characters. The cursor can be moved with the following operation: choose a letter $c$ and a direction (left or right). The cursor is then moved to the closest occurence of $c$ in the chosen direction. If there is no letter $c$ in that direction, the cursor stays in place. For example, if $s = \\mathtt{abaab}$ with the cursor on the second character ($\\mathtt{a[b]aab}$), then:\n\n- moving to the closest letter $\\mathtt{a}$ to the left places the cursor on the first character ($\\mathtt{[a]baab}$);\n- moving to the closest letter $\\mathtt{a}$ to the right places the cursor the third character ($\\mathtt{ab[a]ab}$);\n- moving to the closest letter $\\mathtt{b}$ to the right places the cursor on the fifth character ($\\mathtt{abaa[b]}$);\n- any other operation leaves the cursor in place.\n\nLet $\\mathrm{dist}(i, j)$ be the smallest number of operations needed to move the cursor from the $i$-th character to the $j$-th character. Compute $\\displaystyle \\sum_{i = 1}^n \\sum_{j = 1}^n \\mathrm{dist}(i, j)$.",
    "tutorial": "Again, it's easier to solve the problem backwards. For a character $s_i$, from which characters $s_j$ can we reach $s_i$ in one step? Clearly, $s_j$ should lie in a subsegment of $s$ bounded by adjacent occurences of $s_i$ (inclusive), or by the borders of $s$. Let's denote this subsegment for $s_i$ by $[L_i, R_i)$ (we will use half-open intervals for convenience, as should you). Which characters can be reached from $s_i$ in $k$ reverse steps? We can see that these characters also form a subsegment, let's denote it $[L_i^{(k)}, R_i^{(k)})$. We have that $[L_i^{(0)}, R_i^{(0)}) = [i, i + 1)$, and $[L_i^{(k)}, R_i^{(k)}) = \\displaystyle \\cup_{j \\in [L_i^{(k - 1)}, R_i^{(k - 1)})} [L_j, R_j)$. Note that having values of $[L_i^{(k)}, R_i^{(k)})$ can be used to directly compute the answer, for example, with a formula $\\sum_{i = 1}^n \\sum_{k = 0}^{n - 1} (n - (R_i^{(k)} - L_i^{(k)}))$. This formula is correct since the expression inside the brackets is the number of characters not reachable from $i$ in $k$ reverse steps, hence a position $j$ reachable in exactly $d$ steps will be accounted for $d$ times. Simplifying a bit, we arrive at the formula $n^3 - \\sum_{i = 1}^n \\sum_{k = 0}^{n - 1} (R_i^{(k)} - L_i^{(k)})$. Values of $[L_i^{(k)}, R_i^{(k)})$ can be computed in $O(n^2)$ individually by applying the above recurrence and using a sparse table, but that is still way too slow. It's tempting to try and use binary lifting, but as $k$ grows, evolution of $L_i^{(k)}$ and $R_i^{(k)}$ is mutually dependent, and we can't store an $n^2$-sized table. They do, however, become independent at some point, namely, when the range $[L_i^{(k)}, R_i^{(k)})$ contains all distinct letters present in $s$. Indeed, to compute $R_i^{(k + 1)}$ we simply need to take the largest $R_j$, where $j$ ranges over the last occurences of letters a, $\\ldots$, z before $R_i^{(k)}$. Slightly more generally, we can treat the evolution of $L_i^{(k)}$ and $R_i^{(k)}$ independently in a range of $k$'s where the number of distinct characters in the segment doesn't change. And it can only change at most $\\alpha = 26$ times... Time to put this together. For each $i$, we will store $k_i$ - the number of expansions we've applied to $[L_i^{(k)}, R_i^{(k)})$, as well as the range's endpoints themselves. We will iterate over the parameter $t$ - the number of distinct characters in ranges we're going to expand now. For each right endpoint $r$, let's find $f_r(r)$ as the largest $R_j$ over $t$ closest distinct letters to the left of $r$; define $f_l(l)$ similarly. Additionally, compute binary lifts $f^{2^y}_r(r)$, $f^{2^y}_l(l)$, as well as the sums of $r$ and $l$ visited by each binary lift. Now, for each $i$ we use binary lifting to find the largest number of iterations to apply to $[L_i^{(k)}, R_i^{(k)})$ so that the number of distinct characters in the range stays equal to $t$. Doing this, we can update $k_i$ and endpoints of $[L_i^{(k)}, R_i^{(k)})$ accordingly, as well as add a part of $\\sum_{i = 1}^n \\sum_{k = 0}^{n - 1} (R_i^{(k)} - L_i^{(k)})$ to the total. Thus, going into the next phase with $t + 1$, we will have all necessary values up-to-date. How fast does this work? For every $t = 1, \\ldots, \\alpha = 26$, we'll need $O(n \\log n)$ work to construct binary lifts and update everything. The total complexity is thus $O(\\alpha n \\log n)$.",
    "tags": [],
    "rating": 3500
  },
  {
    "contest_id": "1248",
    "index": "A",
    "title": "Integer Points",
    "statement": "DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew $n$ distinct lines, given by equations $y = x + p_i$ for some distinct $p_1, p_2, \\ldots, p_n$.\n\nThen JLS drew on the same paper sheet $m$ distinct lines given by equations $y = -x + q_i$ for some distinct $q_1, q_2, \\ldots, q_m$.\n\nDLS and JLS are interested in counting how many line pairs have \\textbf{integer} intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help.",
    "tutorial": "Consider two lines $y = x + p$ and $y = -x + q$: $\\begin{cases} y = x + p \\\\ y = -x + q \\end{cases} \\Rightarrow \\begin{cases} 2y = p + q \\\\ y = -x + q \\end{cases} \\Rightarrow \\begin{cases} y = \\frac{p + q}{2} \\\\ y = -x + q \\end{cases} \\Rightarrow \\begin{cases} y = \\frac{p + q}{2} \\\\ x = \\frac{q - p}{2} \\end{cases}$ It's clear that they will have integral intersection point iff $p$ and $q$ have the same parity. Let's find $p_0$ and $p_1$ - number of even and odd $p_i$ respectively. Moreover let's find $q_0$ and $q_1$ for $q_i$. Now answer is $p_0 \\cdot q_0 + p_1 \\cdot q_1$. Complexity: $O(n + m)$. Pay attention that answer does not fit in 32-bit data type.",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1248",
    "index": "B",
    "title": "Grow The Tree",
    "statement": "Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.\n\nThe tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $(0, 0)$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $OX$ or $OY$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.\n\nAlexey wants to make a polyline in such a way that its end is as far as possible from $(0, 0)$. Please help him to grow the tree this way.\n\nNote that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.",
    "tutorial": "At first, let's do some maths. Consider having an expression $a^2 + b^2$ which we have to maximize, while $a + b = C$, where $C$ is some constant. Let's proof that the maximum is achieved when $a$ or $b$ is maximum possible. At first let $a$ or $b$ be about the same, while $a \\geq b$. Let's see what happens when we add $1$ to $a$ and subtract $1$ from $b$. $(a + 1)^2 + (b - 1)^2 = a^2 + 2a + 1 + b^2 - 2b + 1 = a^2 + b^2 + 2(a - b + 1)$. Since $a \\geq b$, this expression is greater than $a^2 + b^2$. It means that we should maximize $a$ (or $b$, doing the same steps) in order to achieve the maximum of $a^2 + b^2$. Notice that we should always grow the tree in one direction. For definiteness, let horizontal sticks go from left to right and vertical from down to top. Now, answer equals to square of the sum of lengths of horizontal sticks plus square of the sum of lengths of vertical sticks. As we proved earlier, to maximize this expression, we should maximize one of the numbers under the squares. Let's sort sticks by order and orient the half (and medium element if there's an odd amount of sticks) with the greater length vertically, and the other half horizontally. Work time: $O(n \\log n)$",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1248",
    "index": "D1",
    "title": "The World Is Just a Programming Task (Easy Version)",
    "statement": "This is an easier version of the problem. In this version, $n \\le 500$.\n\nVasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.\n\nTo digress from his problems, Vasya decided to select two positions of the string (\\textbf{not necessarily distinct}) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.\n\nWe remind that bracket sequence $s$ is called correct if:\n\n- $s$ is empty;\n- $s$ is equal to \"($t$)\", where $t$ is correct bracket sequence;\n- $s$ is equal to $t_1 t_2$, i.e. concatenation of $t_1$ and $t_2$, where $t_1$ and $t_2$ are correct bracket sequences.\n\nFor example, \"(()())\", \"()\" are correct, while \")(\" and \"())\" are not.\n\nThe cyclical shift of the string $s$ of length $n$ by $k$ ($0 \\leq k < n$) is a string formed by a concatenation of the last $k$ symbols of the string $s$ with the first $n - k$ symbols of string $s$. For example, the cyclical shift of string \"(())()\" by $2$ equals \"()(())\".\n\nCyclical shifts $i$ and $j$ are considered different, if $i \\ne j$.",
    "tutorial": "Note first that the number of opening brackets must be equal to the number of closing brackets, otherwise the answer is always $0$. Note that the answer to the question about the number of cyclic shifts, which are correct bracket sequences, equals the number of minimal prefix balances. For example, for string )(()))()((, the array of prefix balances is [-1, 0, 1, 0, -1, -2, -1, -2, -1, 0], and the number of cyclic shifts, $2$ - the number of minimums in it ($-2$). Now we have a solution of complexuty $\\mathcal{O}(n^3)$: let's iterate over all pairs of symbols that can be swapped. Let's do this and find the number of cyclic shifts that are correct bracket sequences according to the algorithm described above.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1249",
    "index": "A",
    "title": "Yet Another Dividing into Teams",
    "statement": "You are a coach of a group consisting of $n$ students. The $i$-th student has programming skill $a_i$. \\textbf{All students have distinct programming skills}. You want to divide them into teams in such a way that:\n\n- No two students $i$ and $j$ such that $|a_i - a_j| = 1$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $1$);\n- the number of teams is the minimum possible.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "The answer is always $1$ or $2$. Why it is so? Because if there is no such pair $i, j$ among all students that $|a_i - a_j| = 1$ then we can take all students into one team. Otherwise, we can divide them into two teams by their programming skill parity.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tcin >> a[j];\n\t\t}\n\t\tbool ok = true;\n\t\tfor (int p1 = 0; p1 < n; ++p1) {\n\t\t\tfor (int p2 = 0; p2 < p1; ++p2) {\n\t\t\t\tok &= abs(a[p1] - a[p2]) != 1;\n\t\t\t}\n\t\t}\n\t\tcout << 2 - ok << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1249",
    "index": "B1",
    "title": "Books Exchange (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints}.\n\nThere are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed.\n\nFor example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on.\n\nYour task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$.\n\nConsider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids:\n\n- after the $1$-st day it will belong to the $5$-th kid,\n- after the $2$-nd day it will belong to the $3$-rd kid,\n- after the $3$-rd day it will belong to the $2$-nd kid,\n- after the $4$-th day it will belong to the $1$-st kid.\n\nSo after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "In this problem you just need to implement what is written in the problem statement. For the kid $i$ the following pseudocode will calculate the answer (indices of the array $p$ and its values are $0$-indexed):",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> p(n);\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tcin >> p[j];\n\t\t\t--p[j];\n\t\t}\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tint cnt = 0;\n\t\t\tint k = j;\n\t\t\tdo {\n\t\t\t\t++cnt;\n\t\t\t\tk = p[k];\n\t\t\t} while (k != j);\n\t\t\tcout << cnt << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "dsu",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1249",
    "index": "B2",
    "title": "Books Exchange (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints}.\n\nThere are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed.\n\nFor example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on.\n\nYour task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$.\n\nConsider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids:\n\n- after the $1$-st day it will belong to the $5$-th kid,\n- after the $2$-nd day it will belong to the $3$-rd kid,\n- after the $3$-rd day it will belong to the $2$-nd kid,\n- after the $4$-th day it will belong to the $1$-st kid.\n\nSo after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "In this problem, we can notice that when we calculate the answer for the kid $i$, we also calculate the answer for kids $p_i$, $p_{p_i}$ and so on. So we can a little bit modify the pseudocode from the easy version to calculate answers faster: And of course, we don't need to run this while for all elements for which we already calculated the answer. Total time complexity is $O(n)$ because you'll process each element exactly once.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> p(n);\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tcin >> p[j];\n\t\t\t--p[j];\n\t\t}\n\t\tvector<int> used(n);\n\t\tvector<int> ans(n);\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tif (!used[j]) {\n\t\t\t\tvector<int> cur;\n\t\t\t\twhile (!used[j]) {\n\t\t\t\t\tcur.push_back(j);\n\t\t\t\t\tused[j] = true;\n\t\t\t\t\tj = p[j];\n\t\t\t\t}\n\t\t\t\tfor (auto el : cur) ans[el] = cur.size();\n\t\t\t}\n\t\t}\n\t\tfor (int j = 0; j < n; ++j) cout << ans[j] << \" \";\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1249",
    "index": "C1",
    "title": "Good Numbers (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the maximum value of $n$}.\n\nYou are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$.\n\nThe positive integer is called good if it can be represented as a sum of \\textbf{distinct} powers of $3$ (i.e. no duplicates of powers of $3$ are allowed).\n\nFor example:\n\n- $30$ is a good number: $30 = 3^3 + 3^1$,\n- $1$ is a good number: $1 = 3^0$,\n- $12$ is a good number: $12 = 3^2 + 3^1$,\n- but $2$ is \\textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ ($2 = 3^0 + 3^0$),\n- $19$ is \\textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representations $19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$ are invalid),\n- $20$ is also \\textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representation $20 = 3^2 + 3^2 + 3^0 + 3^0$ is invalid).\n\nNote, that there exist other representations of $19$ and $20$ as sums of powers of $3$ but none of them consists of \\textbf{distinct} powers of $3$.\n\nFor the given positive integer $n$ find such smallest $m$ ($n \\le m$) that $m$ is a good number.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "As you can see from the example, the maximum answer doesn't exceed $2 \\cdot 10^4$. So we can run some precalculation before all queries, which will find all good numbers less than $2 \\cdot 10^4$. The number is good if it has no $2$ in the ternary numeral system. When you read the next query, you can increase $n$ until you find some precalculated good number. Time complexity is $O(nq + n \\log n)$. You also can implement the solution which doesn't use any precalculations and just increase $n$ each time in each query and checks if the number is good inside this loop. Then time complexity will be $O(n q \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\twhile (true) {\n\t\t\tbool ok = true;\n\t\t\tint cur = n;\n\t\t\twhile (cur > 0) {\n\t\t\t\tif (ok && cur % 3 == 2) ok = false;\n\t\t\t\tcur /= 3;\n\t\t\t}\n\t\t\tif (ok) break;\n\t\t\t++n;\n\t\t}\n\t\tcout << n << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1249",
    "index": "C2",
    "title": "Good Numbers (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the maximum value of $n$}.\n\nYou are given a positive integer number $n$. You really love good numbers so you want to find the smallest good number greater than or equal to $n$.\n\nThe positive integer is called good if it can be represented as a sum of \\textbf{distinct} powers of $3$ (i.e. no duplicates of powers of $3$ are allowed).\n\nFor example:\n\n- $30$ is a good number: $30 = 3^3 + 3^1$,\n- $1$ is a good number: $1 = 3^0$,\n- $12$ is a good number: $12 = 3^2 + 3^1$,\n- but $2$ is \\textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ ($2 = 3^0 + 3^0$),\n- $19$ is \\textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representations $19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$ are invalid),\n- $20$ is also \\textbf{not} a good number: you can't represent it as a sum of distinct powers of $3$ (for example, the representation $20 = 3^2 + 3^2 + 3^0 + 3^0$ is invalid).\n\nNote, that there exist other representations of $19$ and $20$ as sums of powers of $3$ but none of them consists of \\textbf{distinct} powers of $3$.\n\nFor the given positive integer $n$ find such smallest $m$ ($n \\le m$) that $m$ is a good number.\n\nYou have to answer $q$ independent queries.",
    "tutorial": "Let's see the representation of $n$ in the ternary numeral system. If it has no twos, then the answer is $n$. Otherwise, let $pos_2$ be the maximum position of $2$ in the ternary representation. Then we obviously need to replace it with $0$ and add some power of three to the right from it. Let $pos_0$ be the leftmost position of $0$ to the right from $pos_2$. We can add $3^{pos_0}$ and replace all digits from the position $pos_0 - 1$ to the position $0$ with $0$. Then the resulting number will be good because we replaced all twos with zeros and the minimum because, in fact, we added only one power of three and this power is the minimum one we could add. Time complexity is $O(\\log n)$ per query.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long INF64 = 1e18;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tlong long n;\n\t\tcin >> n;\n\t\tvector<int> vals;\n\t\tint pos2 = -1;\n\t\twhile (n > 0) {\n\t\t\tvals.push_back(n % 3);\n\t\t\tif (vals.back() == 2) pos2 = int(vals.size()) - 1;\n\t\t\tn /= 3;\n\t\t}\n\t\tvals.push_back(0);\n\t\tif (pos2 != -1) {\n\t\t\tint pos0 = find(vals.begin() + pos2, vals.end(), 0) - vals.begin();\n\t\t\tvals[pos0] = 1;\n\t\t\tfor (int i = pos0 - 1; i >= 0; --i) {\n\t\t\t\tvals[i] = 0;\n\t\t\t}\n\t\t}\n\t\tlong long ans = 0;\n\t\tlong long pw = 1;\n\t\tfor (int i = 0; i < int(vals.size()); ++i) {\n\t\t\tans += pw * vals[i];\n\t\t\tpw *= 3;\n\t\t}\n\t\tif (vals.back() == 1) ans = pw / 3;\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1249",
    "index": "D1",
    "title": "Too Many Segments (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints}.\n\nYou are given $n$ segments on the coordinate axis $OX$. Segments can intersect, lie inside each other and even coincide. The $i$-th segment is $[l_i; r_i]$ ($l_i \\le r_i$) and it covers all integer points $j$ such that $l_i \\le j \\le r_i$.\n\nThe integer point is called \\textbf{bad} if it is covered by \\textbf{strictly more} than $k$ segments.\n\nYour task is to remove the minimum number of segments so that there are no \\textbf{bad} points at all.",
    "tutorial": "In this problem, the following greedy solution works: let's find the leftmost point covered by more than $k$ segments. We should fix it somehow. How to do it? Let's find some segment that was not removed already, it covers this point and its rightmost end is maximum possible, and remove this segment. You can implement it in any time you want, even in $O(n^3)$ naively.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 250;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<pair<int, int>> segs(n);\n\tvector<int> cnt(N);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> segs[i].first >> segs[i].second;\n\t\t++cnt[segs[i].first];\n\t\t--cnt[segs[i].second + 1];\n\t}\n\t\n\tfor (int i = 0; i + 1 < N; ++i) {\n\t\tcnt[i + 1] += cnt[i];\n\t}\n\t\n\tvector<int> ans(n);\n\tfor (int i = 0; i < N; ++i) {\n\t\twhile (cnt[i] > k) {\n\t\t\tint pos = -1;\n\t\t\tfor (int p = 0; p < n; ++p) {\n\t\t\t\tif (!ans[p] && (segs[p].first <= i && i <= segs[p].second) && (pos == -1 || segs[p].second > segs[pos].second)) {\n\t\t\t\t\tpos = p;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(pos != -1);\n\t\t\tfor (int j = segs[pos].first; j <= segs[pos].second; ++j) {\n\t\t\t\t--cnt[j];\n\t\t\t}\n\t\t\tans[pos] = 1;\n\t\t}\n\t}\n\t\n\tcout << accumulate(ans.begin(), ans.end(), 0) << endl;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (ans[i]) cout << i + 1 << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1249",
    "index": "D2",
    "title": "Too Many Segments (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints}.\n\nYou are given $n$ segments on the coordinate axis $OX$. Segments can intersect, lie inside each other and even coincide. The $i$-th segment is $[l_i; r_i]$ ($l_i \\le r_i$) and it covers all integer points $j$ such that $l_i \\le j \\le r_i$.\n\nThe integer point is called \\textbf{bad} if it is covered by \\textbf{strictly more} than $k$ segments.\n\nYour task is to remove the minimum number of segments so that there are no \\textbf{bad} points at all.",
    "tutorial": "In this problem, we need to implement the same greedy solution as in the easy version, but faster. Firstly, let's calculate for each point the number of segments covering it. We can do it using standard trick with prefix sums: increase $cnt_{l_i}$, decrease $cnt_{r_i + 1}$ and build prefix sums on the array $cnt$. Let's maintain the set of segments that cover the current point, sorted by the right endpoint. We can do this with almost the same trick: append to the array $ev_{l_i}$ the index $i$ that says us that in the point $l_i$ the $i$-th segment is opened. And add to the $ev_{r_i + 1}$ the index $-i$ that says us that in the point $r_i + 1$ the $i$-th segment is closed. Note that you need to add $1$-indexed values $i$ because $+0$ and $-0$ are the same thing actually. We can change the array $cnt$ to carry the number of segments covering each point using some structure, but we don't need to do it. Let's maintain the variable $curSub$ that will say us the number of segments covering the current point that was already removed. Also, let's carry another one array $sub$ which will say us when we need to decrease the variable $curSub$. So, we calculated the array of arrays $ev$, the array $cnt$ and we can solve the problem now. For the point $i$, let's remove and add all segments we need, using the array $ev_i$ and add $sub_i$ to $curSub$. Now we know that the set of segments is valid, $curSub$ is also valid and we can fix the current point if needed. While $cnt_i - curSub > k$, let's repeat the following sequence of operations: take the segment with the maximum right border $rmax$ from the set, remove it, increase $curSub$ by one and decrease $sub_{rmax + 1}$ by one. Note that when we remove segments from the set at the beginning of the sequence of moves for the point $i$, we don't need to remove segments that we removed by fixing some previous points, and we need to pay attention to it. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200200;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<pair<int, int>> segs(n);\n\tvector<int> cnt(N);\n\tvector<vector<int>> ev(N);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> segs[i].first >> segs[i].second;\n\t\t++cnt[segs[i].first];\n\t\t--cnt[segs[i].second + 1];\n\t\tev[segs[i].first].push_back(i + 1);\n\t\tev[segs[i].second + 1].push_back(-i - 1);\n\t}\n\t\n\tfor (int i = 0; i + 1 < N; ++i) {\n\t\tcnt[i + 1] += cnt[i];\n\t}\n\t\n\tvector<int> ans(n), sub(N);\n\tset<pair<int, int>> curSegs;\n\tint curSub = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\tfor (int i = 0; i < N; ++i) {\n\t\tcurSub += sub[i];\n\t\tfor (auto it : ev[i]) {\n\t\t\tif (it > 0) {\n\t\t\t\tcurSegs.insert(make_pair(segs[it - 1].second, it - 1));\n\t\t\t} else {\n\t\t\t\tauto iter = curSegs.find(make_pair(segs[-it - 1].second, -it - 1));\n\t\t\t\tif (iter != curSegs.end()) curSegs.erase(iter);\n\t\t\t}\n\t\t}\n\t\twhile (cnt[i] - curSub > k) {\n\t\t\tassert(!curSegs.empty());\n\t\t\tint pos = curSegs.rbegin()->second;\n\t\t\tcurSegs.erase(prev(curSegs.end()));\n\t\t\t++curSub;\n\t\t\t--sub[segs[pos].second + 1];\n\t\t\tans[pos] = 1;\n\t\t}\n\t}\n\t\n\tcout << accumulate(ans.begin(), ans.end(), 0) << endl;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (ans[i]) cout << i + 1 << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1249",
    "index": "E",
    "title": "By Elevator or Stairs?",
    "statement": "You are planning to buy an apartment in a $n$-floor building. The floors are numbered from $1$ to $n$ from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor.\n\nLet:\n\n- $a_i$ for all $i$ from $1$ to $n-1$ be the time required to go from the $i$-th floor to the $(i+1)$-th one (and from the $(i+1)$-th to the $i$-th as well) using the \\textbf{stairs};\n- $b_i$ for all $i$ from $1$ to $n-1$ be the time required to go from the $i$-th floor to the $(i+1)$-th one (and from the $(i+1)$-th to the $i$-th as well) using the \\textbf{elevator}, also there is a value $c$ — time overhead for elevator usage (you need to wait for it, the elevator doors are too slow!).\n\nIn one \\textbf{move}, you can go from the floor you are staying at $x$ to any floor $y$ ($x \\ne y$) in two different ways:\n\n- If you are using the stairs, just sum up the corresponding values of $a_i$. Formally, it will take $\\sum\\limits_{i=min(x, y)}^{max(x, y) - 1} a_i$ time units.\n- If you are using the elevator, just sum up $c$ and the corresponding values of $b_i$. Formally, it will take $c + \\sum\\limits_{i=min(x, y)}^{max(x, y) - 1} b_i$ time units.\n\nYou can perform as many \\textbf{moves} as you want (possibly zero).\n\nSo your task is for each $i$ to determine the minimum total time it takes to reach the $i$-th floor from the $1$-st (bottom) floor.",
    "tutorial": "This is easy dynamic programming problem. It is easy to understand that we don't need to go down at all (otherwise your solution will be Dijkstra's algorithm, not dynamic programming). Let $dp_{i, 0}$ be the minimum required time to reach the floor $i$ if we not in the elevator right now and $dp_{i, 1}$ be the minimum required time to reach the floor $i$ if we in the elevator right now. Initially, all values $dp$ are $+\\infty$, except $dp_{1, 0} = 0$ and $dp_{1, 1} = c$. Transitions are pretty easy: $dp_{i + 1, 0} = min(dp_{i + 1, 0}, dp_{i, 0} + a_i)$ (we was not in the elevator and going to the next floor using stairs); $dp_{i + 1, 0} = min(dp_{i + 1, 0}, dp_{i, 1} + a_i)$ (we was in the elevator and going to the next floor using stairs); $dp_{i + 1, 1} = min(dp_{i + 1, 1}, dp_{i, 0} + b_i + c)$ (we was not in the elevator and going to the next floor using elevator); $dp_{i + 1, 1} = min(dp_{i + 1, 1}, dp_{i, 1} + b_i)$ (we was in the elevator and going to the next floor using elevator). The answer for the $i$-th floor is $min(dp_{i, 0}, dp_{i, 1})$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, c;\n\tcin >> n >> c;\n\tvector<int> a(n - 1), b(n - 1);\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tcin >> a[i];\n\t}\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tcin >> b[i];\n\t}\n\tvector<vector<int>> dp(n, vector<int>(2, INF));\n\tdp[0][0] = 0, dp[0][1] = c;\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tdp[i + 1][0] = min(dp[i + 1][0], dp[i][1] + a[i]);\n\t\tdp[i + 1][0] = min(dp[i + 1][0], dp[i][0] + a[i]);\n\t\tdp[i + 1][1] = min(dp[i + 1][1], dp[i][1] + b[i]);\n\t\tdp[i + 1][1] = min(dp[i + 1][1], dp[i][0] + b[i] + c);\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tcout << min(dp[i][0], dp[i][1]) << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1249",
    "index": "F",
    "title": "Maximum Weight Subset",
    "statement": "You are given a tree, which consists of $n$ vertices. Recall that a tree is a connected undirected graph without cycles.\n\n\\begin{center}\n{\\small Example of a tree.}\n\\end{center}\n\nVertices are numbered from $1$ to $n$. All vertices have weights, the weight of the vertex $v$ is $a_v$.\n\nRecall that the distance between two vertices in the tree is the number of edges on a simple path between them.\n\nYour task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance $k$ or less between them in this subset.",
    "tutorial": "Let's solve this problem using dynamic programming on a tree. Suppose the tree is rooted and the root of the tree is $1$. Also, let's increase $k$ to find the subset in which any pair of vertices had distance $k$ or greater instead of $k+1$ or greater. Let $dp_{v, dep}$ be the maximum total weight of the subset in the subtree of $v$ if the vertex with the minimum depth we took has depth at least $dep$. Then the answer is $dp_{1, 0}$. Firstly, let's calculate this dynamic programming for all children of $v$. Then we are ready to calculate all $dp_{v, dep}$ for all $dep$ from $0$ to $n$. Let the current depth be $dep$, then there are two cases: if $dep = 0$ then $dp_{v, dep} = a_v + \\sum\\limits_{to \\in children(v)} dp_{to, max(0, k - dep - 1)}$. Otherwise, let's iterate over all children of $v$ and let $to$ be such child of $v$ that the vertex with the minimum depth we took is in the subtree of $to$. Then $dp_{v, dep} = max(dp_{v, dep}, dp_{to, dep - 1} + \\sum\\limits_{other \\in children(v) \\backslash \\{to\\}} dp_{other, max(dep - 1, k - dep - 1)}$. After we calculated all values of $dp_{v, dep}$ for the vertex $v$, we can notice that this is not what we wanted. The current value of $dp_{v, dep}$ means the maximum total weight of the subset in the subtree of $v$ if the vertex with the minimum depth we took has depth exactly $dep$. To fix this, let's push $dp_{v, dep}$ to $dp_{v, dep - 1}$ for all depths from $n$ to $1$. Time complexity: $O(n^3)$ but it can be easily optimized to $O(n^2)$ using some prefix and suffix maximums. You can ask, why this is $O(n^3)$ but not $O(n^4)$ because we iterating over all vertices, then over all possible depths, and then over children of the vertex, and again over children of the vertex. But in fact, this is $O(n^3)$ because if we change the order of multiplication, we can see that we are iterating over pairs (parent, child), then over children and possible depths, and the number of such pairs is $O(n)$, so the complexity is $O(n^3)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int N = 200 + 13;\nconst int INF = 1e9;\n\nint n, k;\nint a[N];\nvector<int> g[N];\nint dp[N][N];\nint d[N];\nint tmp[N];\n\nvoid dfs(int v, int p = -1){\n\td[v] = 1;\n\tdp[v][0] = a[v];\n\tfor (auto u : g[v]) if (u != p){\n\t\tdfs(u, v);\n\t\tint nw = max(d[v], d[u] + 1);\n\t\tforn(i, nw)\n\t\t\ttmp[i] = -INF;\n\t\tforn(i, d[v]) for (int j = max(0, k - i); j < d[u]; ++j)\n\t\t\ttmp[min(i, j + 1)] = max(tmp[min(i, j + 1)], dp[v][i] + dp[u][j]);\n\t\tforn(i, d[u])\n\t\t\ttmp[i + 1] = max(tmp[i + 1], dp[u][i]);\n\t\tforn(i, d[v])\n\t\t\tdp[v][i] = max(dp[v][i], tmp[i]);\n\t\tfor (int i = d[v]; i < nw; ++i)\n\t\t\tdp[v][i] = tmp[i];\n\t\td[v] = nw;\n\t\tfor (int i = d[v] - 1; i > 0; --i)\n\t\t\tdp[v][i - 1] = max(dp[v][i - 1], dp[v][i]);\n\t}\n}\n\nint main(){\n\tscanf(\"%d%d\", &n, &k);\n\tforn(i, n)\n\t\tscanf(\"%d\", &a[i]);\n\tforn(i, n - 1){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\tdfs(0);\n\tprintf(\"%d\\n\", dp[0][0]);\n}",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1251",
    "index": "A",
    "title": "Broken Keyboard",
    "statement": "Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $26$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning.\n\nTo check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $s$ appeared on the screen. When Polycarp presses a button with character $c$, one of the following events happened:\n\n- if the button was working correctly, a character $c$ appeared at the end of the string Polycarp was typing;\n- if the button was malfunctioning, \\textbf{two} characters $c$ appeared at the end of the string.\n\nFor example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $\\rightarrow$ abb $\\rightarrow$ abba $\\rightarrow$ abbac $\\rightarrow$ abbaca $\\rightarrow$ abbacabb $\\rightarrow$ abbacabba.\n\nYou are given a string $s$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).\n\nYou may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.",
    "tutorial": "If a key malfunctions, each sequence of presses of this key gives a string with even number of characters. So, if there is a substring consisting of odd number of equal characters $c$, such that it cannot be extended to the left or to the right without adding other characters, then it could not be produced by presses of button $c$ if $c$ was malfunctioning. The only thing that's left is to find all maximal by inclusion substrings consisting of the same character.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool ans[26];\n\nvoid solve() {\n\tstring s;\n\tcin >> s;\n\t\n\tmemset(ans, 0, sizeof(ans));\n\t\n\tfor (int i = 0; i < s.size(); i++) {\n\t\tint j = i;\n\t\twhile (j + 1 < s.size() && s[j + 1] == s[i])\n\t\t\tj++;\n\t\tif ((j - i) % 2 == 0)\n\t\t\tans[s[i] - 'a'] = true;\n\t\ti = j;\n\t}\n\t\n\tfor (int i = 0; i < 26; i++) if (ans[i])\n\t\tcout << char('a' + i);\n\tcout << endl;\n}\n\nint main() {\n\tint q;\n\tcin >> q;\n\twhile (q--) solve();\n}",
    "tags": [
      "brute force",
      "strings",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1251",
    "index": "B",
    "title": "Binary Palindromes",
    "statement": "A palindrome is a string $t$ which reads the same backward as forward (formally, $t[i] = t[|t| + 1 - i]$ for all $i \\in [1, |t|]$). Here $|t|$ denotes the length of a string $t$. For example, the strings 010, 1001 and 0 are palindromes.\n\nYou have $n$ binary strings $s_1, s_2, \\dots, s_n$ (each $s_i$ consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.\n\nFormally, in one move you:\n\n- choose four integer numbers $x, a, y, b$ such that $1 \\le x, y \\le n$ and $1 \\le a \\le |s_x|$ and $1 \\le b \\le |s_y|$ (where $x$ and $y$ are string indices and $a$ and $b$ are positions in strings $s_x$ and $s_y$ respectively),\n- swap (exchange) the characters $s_x[a]$ and $s_y[b]$.\n\nWhat is the maximum number of strings you can make palindromic simultaneously?",
    "tutorial": "Let's make several observations. At first, note that the lengths of the strings doesn't change. At second, note that if the string has even length then being palindromic is the same as having even number of zeroes and even number of ones. But if the string has odd length, then it always is palindromic. So the question is how to fix \"bad\" strings with even length but with odd number of zeroes and ones. If we have at least one string with odd length, then you can trade between \"bad\" string and \"odd\" string either zero to one or one to zero, fixing the \"bad\" string. Otherwise you can fix two \"bad\" strings swapping appropriate characters. In result, we can either make all strings palindromic or all strings except one in case of absence of \"odd\" strings and having odd number of \"bad\" strings.",
    "code": "fun main() {\n    val q = readLine()!!.toInt()\n    for (ct in 1..q) {\n        val n = readLine()!!.toInt()\n        var (odd, evenGood, evenBad) = listOf(0, 0, 0)\n        for (i in 1..n) {\n            val s = readLine()!!\n            when {\n                s.length % 2 == 1 -> odd++\n                s.count { it == '0' } % 2 == 0 -> evenGood++\n                else -> evenBad++\n            }\n        }\n        println(n - if (odd == 0 && evenBad % 2 == 1) 1 else 0)\n    }\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1251",
    "index": "C",
    "title": "Minimize The Integer",
    "statement": "You are given a huge integer $a$ consisting of $n$ digits ($n$ is between $1$ and $3 \\cdot 10^5$, inclusive). It may contain leading zeros.\n\nYou can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by $2$).\n\nFor example, if $a = 032867235$ you can get the following integers in a single operation:\n\n- $302867235$ if you swap the first and the second digits;\n- $023867235$ if you swap the second and the third digits;\n- $032876235$ if you swap the fifth and the sixth digits;\n- $032862735$ if you swap the sixth and the seventh digits;\n- $032867325$ if you swap the seventh and the eighth digits.\n\nNote, that you can't swap digits on positions $2$ and $4$ because the positions are not adjacent. Also, you can't swap digits on positions $3$ and $4$ because the digits have the same parity.\n\nYou can perform any number (possibly, zero) of such operations.\n\nFind the minimum integer you can obtain.\n\n\\textbf{Note that the resulting integer also may contain leading zeros.}",
    "tutorial": "Let's consider two sequences of digits: $e_1, e_2, \\dots , e_k$ and $o_1, o_2, \\dots , o_m$, there $e_1$ is the first even digit in $a$, $e_2$ is the second even digit and so on and $o_1$ is the first odd digit in $a$, $o_2$ is the second odd digit and so on. Since you can't swap digits of same parity, the sequence $e$ of even digits of $a$ never changed. Sequence $o$ of odd digits of $a$ also never changed. So the first digit in the answer will be equal to $e_1$ or to $o_1$. And since we have to minimize the answer, we have to chose the $min(e_1, o_1)$ as the first digit in answer and them delete it from the corresponding sequence (in this way sequence $e$ turn into $e_2, e_3, \\dots , e_k$ or sequence $o$ turn into $o_2, o_3, \\dots , o_m$). Second, third and followings digits need to choose in the same way.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nstring a;\n\nint main() {\t\n\tcin >> t;\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tcin >> a;\n\t\tstring s[2];\n\t\tfor(auto x : a)\n\t\t\ts[int(x - '0') & 1] += x;\n\t\t\n\t\treverse(s[0].begin(), s[0].end());\n\t\treverse(s[1].begin(), s[1].end());\n\n\t\tstring res = \"\";\n\t\twhile(!(s[0].empty() && s[1].empty())){\n\t\t\tif(s[0].empty()){\n\t\t\t\tres += s[1].back();\n\t\t\t\ts[1].pop_back();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(s[1].empty()){\n\t\t\t\tres += s[0].back();\n\t\t\t\ts[0].pop_back();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(s[0].back() < s[1].back()){\n\t\t\t\tres += s[0].back();\n\t\t\t\ts[0].pop_back();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tres += s[1].back();\n\t\t\t\ts[1].pop_back();\n\t\t\t}\n\t\t}\n\n\t\tcout << res << endl;\n\t}\t\n\treturn 0;\n} \n\n",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1251",
    "index": "D",
    "title": "Salary Changing",
    "statement": "You are the head of a large enterprise. $n$ people work at you, and $n$ is odd (i. e. $n$ is not divisible by $2$).\n\nYou have to distribute salaries to your employees. Initially, you have $s$ dollars for it, and the $i$-th employee should get a salary from $l_i$ to $r_i$ dollars. You have to distribute salaries in such a way that the median salary is maximum possible.\n\nTo find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:\n\n- the median of the sequence $[5, 1, 10, 17, 6]$ is $6$,\n- the median of the sequence $[1, 2, 1]$ is $1$.\n\nIt is guaranteed that you have enough money to pay the minimum salary, i.e $l_1 + l_2 + \\dots + l_n \\le s$.\n\n\\textbf{Note that you don't have to spend all your $s$ dollars on salaries.}\n\nYou have to answer $t$ test cases.",
    "tutorial": "Let $f(mid)$ be equal minimum amount of money to obtain the median salary at least $mid$. We'll solve this problem by binary search by $mid$. Suppose the have to calculate the minimum amount of money for obtaining median salary at least $mid$. Let's divide all salaries into three groups: $r_i < mid$; $mid \\le l_i$; $l_i < mid \\le r_i$. In order to the median salary be at least $mid$ there must be at least $\\frac{n+1}{2}$ salaries greater than or equal to $mid$. Let's denote the number of such salaries as $cnt$. Note that salaries of the first group can't increment the value of $cnt$, so it's beneficial for us to pay the minimum salary for this group. Salaries if second group always increment the value of $cnt$, so it's also beneficial for us to pay the minimum salary. The salaries from the third group are more interesting. For each salary $[l_i, r_i]$ in this group we can pay $mid$ and increment $cnt$, or we can pay $l_i$ and don't increase $cnt$. The value of $cnt$ should be increased by $rem = max(0, \\frac{n+1}{2} - cnt)$. So, if the size of the third group is less than $rem$ than we can't obtain the median salary $mid$. Otherwise, we can define how many salaries we can take with value $l_i$ and chose the minimal ones.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(2e5) + 99;\nconst int INF = int(1e9) + 100;\n\nint t;\nint n;\nlong long s;\npair<int, int> p[N];\n\nbool ok(int mid){\n\tlong long sum = 0;\n\tint cnt = 0;\n\tvector <int> v;\n\tfor(int i = 0; i < n; ++i){\n\t\tif(p[i].second < mid)\n\t\t\tsum += p[i].first;\n\t\telse if(p[i].first >= mid){\n\t\t\tsum += p[i].first;\n\t\t\t++cnt;\n\t\t}\n\t\telse\n\t\t\tv.push_back(p[i].first);\n\t}\n\n\tassert(is_sorted(v.begin(), v.end()));\n\t\n\tint need = max(0, (n + 1) / 2 - cnt);\n\tif(need > v.size()) return false;\n\tfor(int i = 0; i < v.size(); ++i){\n\t\tif(i < v.size() - need)\n\t\t\tsum += v[i];\n\t\telse\n\t\t\tsum += mid;\n\t}\n\n\treturn sum <= s;\n}\n\nint main() {\t\n\tscanf(\"%d\", &t);\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tscanf(\"%d %lld\", &n, &s);\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tscanf(\"%d %d\", &p[i].first, &p[i].second);\n\t\t\n\t\tsort(p, p + n);\n\t\tint lf = 1, rg = INF; ///WA -> 10^9\n\t\twhile(rg - lf > 1){\n\t\t\tint mid = (lf + rg) / 2;\n\t\t\tif(ok(mid)) lf = mid;\n\t\t\telse rg = mid;\n\t\t}\n\t\t\n\t\tprintf(\"%d\\n\", lf);\n\t}\n\treturn 0;\n}                             \t",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1251",
    "index": "E2",
    "title": "Voting (Hard Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints.}\n\nNow elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.\n\nThere are $n$ voters, and two ways to convince each of them to vote for you. The first way to convince the $i$-th voter is to pay him $p_i$ coins. The second way is to make $m_i$ other voters vote for you, and the $i$-th voter will vote for free.\n\nMoreover, the process of such voting takes place in several steps. For example, if there are five voters with $m_1 = 1$, $m_2 = 2$, $m_3 = 2$, $m_4 = 4$, $m_5 = 5$, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: ${5} \\rightarrow {1, 5} \\rightarrow {1, 2, 3, 5} \\rightarrow {1, 2, 3, 4, 5}$.\n\nCalculate the minimum number of coins you have to spend so that everyone votes for you.",
    "tutorial": "Denote the number of voters with $m_i = x$ as $c_x$. Also denote $pref_x = \\sum\\limits_{i=0}^{x-1} c_x$, i.e. $pref_x$ is equal to number of voters with $m_i < x$. Let's group all voters by value $m_i$. We'll consider all these group in decreasing value of $m_i$. Assume that now we consider group with $m_i = x$. Then there are two cases: if $pref_{x} + cnt \\ge x$ then all these voters will vote for you for free. $cnt$ is equal to the number of votes bought in previous steps; if $pref_{x} + cnt < x$ then we have to buy $x - pref_{s} - cnt$ additional votes. Moreover the value $m_i$ of this \"bought\" voter must be greater than or equal to $x$. Since these voters indistinguishable we have to buy $x - pref_{s} - cnt$ cheapest voter (with a minimal value of $p_i$). So, all we have to do it maintain values $p_i$ not yet bought voters in some data structure (for example multiset in C++).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(3e5) + 99;\n\nint t, n;\nvector <int> v[N];\n\nint main() {\t\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tscanf(\"%d\", &n);\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tv[i].clear();\n\t\tfor(int i = 0; i < n; ++i){\n\t\t\tint x, s;\n\t\t\tscanf(\"%d %d\", &x, &s);\n\t\t\tv[x].push_back(s);\n\t\t}\t\t\n\t\t\n\t\tmultiset <int > q;\n\t\tlong long res = 0;\n\t\tint pref = n;\n\t\tint cnt = 0;\n\t\tfor(int i = n - 1; i >= 0; --i){\n\t\t\tpref -= v[i].size();\n\t\t\tint need = i - pref;\n\t\t\tfor(auto x : v[i]) q.insert(x);\n\n\t\t\twhile(cnt < need){\n\t\t\t\t++cnt;\n\t\t\t\tres += *q.begin();\t\t\t\t\n\t\t\t\tq.erase(q.begin());\n\t\t\t}\n\t\t}\t\t\n\n        \tprintf(\"%lld\\n\", res);\n        }\n\treturn 0;\n}                             \t",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1251",
    "index": "F",
    "title": "Red-White Fence",
    "statement": "Polycarp wants to build a fence near his house. He has $n$ white boards and $k$ red boards he can use to build it. Each board is characterised by its length, which is an integer.\n\nA good fence should consist of \\textbf{exactly one} red board and several (possibly zero) white boards. The red board should be the longest one in the fence (every white board used in the fence should be strictly shorter), and the sequence of lengths of boards should be ascending before the red board and descending after it. Formally, if $m$ boards are used, and their lengths are $l_1$, $l_2$, ..., $l_m$ in the order they are placed in the fence, from left to right (let's call this array $[l_1, l_2, \\dots, l_m]$ the array of lengths), the following conditions should hold:\n\n- there should be exactly one red board in the fence (let its index be $j$);\n- for every $i \\in [1, j - 1]$ $l_i < l_{i + 1}$;\n- for every $i \\in [j, m - 1]$ $l_i > l_{i + 1}$.\n\nWhen Polycarp will build his fence, he will place all boards from left to right on the same height of $0$, without any gaps, so these boards compose a polygon:\n\n\\begin{center}\n{\\small Example: a fence with $[3, 5, 4, 2, 1]$ as the array of lengths. The second board is red. The perimeter of the fence is $20$.}\n\\end{center}\n\nPolycarp is interested in fences of some special perimeters. He has $q$ \\textbf{even} integers he really likes (these integers are $Q_1$, $Q_2$, ..., $Q_q$), and for every such integer $Q_i$, he wants to calculate the number of different fences with perimeter $Q_i$ he can build (two fences are considered different if their \\textbf{arrays of lengths} are different). Can you help him calculate these values?",
    "tutorial": "Let's analyze how the perimeter of the fence can be calculated, if we know its array of lengths. Suppose there are $m$ boards in the fence. The perimeter of the fence can be composed of the three following values: the lower border of the fence (with length $m$); $m$ horizontal segments in the upper border of the fence (with total length $m$); $m + 1$ vertical segment of the border. The total length of all vertical segments before the red board (including its left border) is $l_1 + (l_2 - l_1) + \\dots + (l_j - l_{j - 1}) = l_j$. The total length of all vertical segments after the red board (including its right border) is $l_j$ too. So, the perimeter of the fence is $2(m + l_j)$, where $m$ is the number of boards used in constructing the fence, and $l_j$ is the length of the red board. So, for example, if we want to create a fence that contains a red board with length $L$ and has perimeter $P$, it should contain exactly $\\frac{P}{2} - L - 1$ white boards. Now let's solve the problem as follows: iterate on the length of the red board that will be used, and for each $Q_i$ calculate the number of ways to construct a fence with a red board of length $L$ and exactly $\\frac{Q_i}{2} - L - 1$ white boards (which are shorter than $L$). Suppose all white boards shorter than $L$ have distinct lengths. Then for each board, there are three options: not place it at all, place it in the left part (to the left of the red board) or place it in the right part. So, if there are $n$ different white boards shorter than $L$, the number of ways to build a fence with $k$ white boards is ${n}\\choose{k}$ $2^k$. Okay, now let's consider the opposite situation: there is no unique white board; that is, for each length, we have either $0$ boards or at least $2$ boards. Suppose the number of different lengths is $m$. For each length, we can choose whether we place a board of such length in the left side and in the right side. So, the number of ways to build a fence with $k$ white boards is ${2m}\\choose{k}$. And now let's consider the general case. Divide all boards into two categories: \"unique\" and \"non-unique\". If we want to build a fence with exactly $k$ white boards, there are $\\sum \\limits_{i = 0}^{k}$ ${2m}\\choose{k - i}$ ${n}\\choose{i}$ $2^i$ ways to do it. Since we should calculate these values for many different values of $k$, we have to use FFT: we should form two polynomials $\\sum\\limits_{i = 0}^{n}$ ${n}\\choose{i}$ $2^i x^i$ and $\\sum\\limits_{i = 0}^{2m}$ ${2m}\\choose{i}$ $x^i$, and then multiply them. Since the modulo is special, it's better to use NTT.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int LOGN = 20;\nconst int N = (1 << LOGN);\nconst int MOD = 998244353;\nconst int g = 3;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++)\n\ninline int mul(int a, int b)\n{\n\treturn (a * 1ll * b) % MOD;\n}\n\ninline int norm(int a) \n{\n\twhile(a >= MOD)\n\t\ta -= MOD;\n\twhile(a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\ninline int binPow(int a, int k) \n{\n\tint ans = 1;\n\twhile(k > 0) \n\t{\n\t\tif(k & 1)\n\t\t\tans = mul(ans, a);\n\t\ta = mul(a, a);\n\t\tk >>= 1;\n\t}\n\treturn ans;\n}\n\ninline int inv(int a) \n{\n\treturn binPow(a, MOD - 2);\n}\n\nvector<int> w[LOGN];\nvector<int> iw[LOGN];\nvector<int> rv[LOGN];\n\nvoid precalc() \n{\n\tint wb = binPow(g, (MOD - 1) / (1 << LOGN));\n\t\n\tfor(int st = 0; st < LOGN; st++) \n\t{\n\t\tw[st].assign(1 << st, 1);\n\t\tiw[st].assign(1 << st, 1);\n\t\t\n\t\tint bw = binPow(wb, 1 << (LOGN - st - 1));\n\t\tint ibw = inv(bw);\n\t\t\n\t\tint cw = 1;\n\t\tint icw = 1;\n\t\t\n\t\tfor(int k = 0; k < (1 << st); k++) \n\t\t{\n\t\t\tw[st][k] = cw;\n\t\t\tiw[st][k] = icw;\n\t\t\t\n\t\t\tcw = mul(cw, bw);\n\t\t\ticw = mul(icw, ibw);\n\t\t}\n\t\t\n\t\trv[st].assign(1 << st, 0);\n\t\t\n\t\tif(st == 0) \n\t\t{\n\t\t\trv[st][0] = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tint h = (1 << (st - 1));\n\t\tfor(int k = 0; k < (1 << st); k++)\n\t\t\trv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);\n\t}\n}\n\ninline void fft(int a[N], int n, int ln, bool inverse) \n{\t\n\tfor(int i = 0; i < n; i++) \n\t{\n\t\tint ni = rv[ln][i];\n\t\tif(i < ni)\n\t\t\tswap(a[i], a[ni]);\n\t}\n\t\n\tfor(int st = 0; (1 << st) < n; st++) \n\t{\n\t\tint len = (1 << st);\n\t\tfor(int k = 0; k < n; k += (len << 1)) \n\t\t{\n\t\t\tfor(int pos = k; pos < k + len; pos++) \n\t\t\t{\n\t\t\t\tint l = a[pos];\n\t\t\t\tint r = mul(a[pos + len], (inverse ? iw[st][pos - k] : w[st][pos - k]));\n\t\t\t\t\n\t\t\t\ta[pos] = norm(l + r);\n\t\t\t\ta[pos + len] = norm(l - r);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(inverse) \n\t{\n\t\tint in = inv(n);\n\t\tfor(int i = 0; i < n; i++)\n\t\t\ta[i] = mul(a[i], in);\n\t}\n}\n\nint aa[N], bb[N], cc[N];\n\ninline void multiply(int a[N], int sza, int b[N], int szb, int c[N], int &szc) \n{\n\tint n = 1, ln = 0;\n\twhile(n < (sza + szb))\n\t\tn <<= 1, ln++;\n\tfor(int i = 0; i < n; i++)\n\t\taa[i] = (i < sza ? a[i] : 0);\n\tfor(int i = 0; i < n; i++)\n\t\tbb[i] = (i < szb ? b[i] : 0);\n\t\t\n\tfft(aa, n, ln, false);\n\tfft(bb, n, ln, false);\n\t\n\tfor(int i = 0; i < n; i++)\n\t\tcc[i] = mul(aa[i], bb[i]);\n\t\t\n\tfft(cc, n, ln, true);\n\t\n\tszc = n;\n\tfor(int i = 0; i < n; i++)\n\t\tc[i] = cc[i];\n}\n\nvector<int> T[N];\n\nint a[N];\nint b[N];\nint n, k;\nint ans[N];\nint Q[N];\nint fact[N];\nint rfact[N];\n\nint auxa[N];\nint auxb[N];\nint auxc[N];\n\nint C(int n, int k)\n{\n\tif(n < 0 || k < 0 || k > n) return 0;\n\treturn mul(fact[n], mul(rfact[k], rfact[n - k]));\n}\n\nvector<int> newtonExp(int a, int b, int p)\n{\n\tvector<int> res(p + 1);\n\tfor(int i = 0; i <= p; i++)\n\t\tres[i] = mul(C(p, i), mul(binPow(a, i), binPow(b, p - i)));\n\treturn res;\n}\n\nint main()\n{\n\tprecalc();\n\tfact[0] = 1;\n\tfor(int i = 1; i < N; i++) fact[i] = mul(fact[i - 1], i);\n\tfor(int i = 0; i < N; i++) rfact[i] = inv(fact[i]);\n\t\n\tscanf(\"%d %d\", &n, &k);\n\tfor(int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\n\tfor(int i = 0; i < k; i++) scanf(\"%d\", &b[i]);\n\tint q;\n\tscanf(\"%d\", &q);\n\tfor(int i = 0; i < q; i++) scanf(\"%d\", &Q[i]);\n\t\n\tmap<int, int> cnt;\n\tfor(int i = 0; i < n; i++)\n\t\tcnt[a[i]]++;\n\t\n\tfor(int i = 0; i < k; i++)\n\t{\n\t\tint redL = b[i];\n\t\tint cnt1 = 0;\n\t\tint cnt2 = 0;\n\t\tfor(auto x : cnt)\n\t\t{\n\t\t\tif(x.first >= redL) \n\t\t\t\tbreak;\n\t\t\tif(x.second == 1)\n\t\t\t\tcnt1++;\n\t\t\telse\n\t\t\t\tcnt2++;\n\t\t}\n\t\tmemset(auxa, 0, sizeof auxa);\n\t\tmemset(auxb, 0, sizeof auxb);\n\t\tmemset(auxc, 0, sizeof auxc);\n\t\tvector<int> p1 = newtonExp(2, 1, cnt1);\n\t\tvector<int> p2 = newtonExp(1, 1, cnt2 * 2);\n\t\tint sa = p1.size();\n\t\tint sb = p2.size();\n\t\tint sc;\n\t\tfor(int j = 0; j < sa; j++)\n\t\t\tauxa[j] = p1[j];\n\t\tfor(int j = 0; j < sb; j++)\n\t\t\tauxb[j] = p2[j];\n\t\tmultiply(auxa, sa, auxb, sb, auxc, sc);\n\t\tfor(int j = 0; j < q; j++)\n\t\t{\n\t\t\tint cntW = Q[j] / 2 - redL - 1;\n\t\t\tif(cntW >= 0 && cntW < sc)\n\t\t\t\tans[j] = norm(ans[j] + auxc[cntW]);\n\t\t}\n\t}\n\t\n\tfor(int i = 0; i < q; i++)\n\t\tprintf(\"%d\\n\", ans[i]);\n}",
    "tags": [
      "combinatorics",
      "fft"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1253",
    "index": "A",
    "title": "Single Push",
    "statement": "You're given two arrays $a[1 \\dots n]$ and $b[1 \\dots n]$, both of the same length $n$.\n\nIn order to perform a push operation, you have to choose three integers $l, r, k$ satisfying $1 \\le l \\le r \\le n$ and $k > 0$. Then, you will add $k$ to elements $a_l, a_{l+1}, \\ldots, a_r$.\n\nFor example, if $a = [3, 7, 1, 4, 1, 2]$ and you choose $(l = 3, r = 5, k = 2)$, the array $a$ will become $[3, 7, \\underline{3, 6, 3}, 2]$.\n\nYou can do this operation \\textbf{at most once}. Can you make array $a$ equal to array $b$?\n\n(We consider that $a = b$ if and only if, for every $1 \\le i \\le n$, $a_i = b_i$)",
    "tutorial": "If we set $d_i = b_i - a_i$, we have to check that $d$ has the following form: $[0, 0, \\ldots, 0, k, k, \\ldots, k, 0, 0, \\ldots, 0]$. Firstly check that there is no negative element in $d$. Solution 1 : add $0$ to the beginning and the end of the array $d$, then check that there is at most two indices $i$ such that $d_i \\neq d_{i+1}$. Solution 2 : let $l$ be the smallest integer such that $d_l \\neq 0$, and $r$ be the greatest integer such that $d_r \\neq 0$. Check that for all $l \\le i \\le r$, $d_i = d_l$. Complexity : $O(n)$ for each test case.",
    "code": "\"#include <iostream>\\n#include <vector>\\nusing namespace std;\\n\\nbool solve()\\n{\\n\\tint nbElem;\\n\\tcin >> nbElem;\\n\\n\\tint extSize = nbElem+2;\\n\\tvector<int> orig(extSize), target(extSize);\\n\\tvector<int> diff(extSize, 0);\\n\\n\\tfor (int iElem = 1; iElem <= nbElem; ++iElem) {\\n\\t\\tcin >> orig[iElem];\\n\\t}\\n\\n\\tfor (int iElem = 1; iElem <= nbElem; ++iElem) {\\n\\t\\tcin >> target[iElem];\\n\\t\\tdiff[iElem] = target[iElem] - orig[iElem];\\n\\t}\\n\\n\\tint cntModif = 0;\\n\\tfor (int iElem = 0; iElem < extSize-1; ++iElem) {\\n\\t\\tif (diff[iElem] < 0) {\\n\\t\\t\\treturn false;\\n\\t\\t}\\n\\t\\tif (diff[iElem] != diff[iElem+1]) {\\n\\t\\t\\t++cntModif;\\n\\t\\t}\\n\\t}\\n\\n\\treturn (cntModif <= 2);\\n}\\n\\nint main()\\n{\\n\\tios::sync_with_stdio(false);\\n\\tcin.tie(0);\\n\\n\\tint nbQueries;\\n\\tcin >> nbQueries;\\n\\n\\tfor (int iQuery = 0; iQuery < nbQueries; ++iQuery) {\\n\\t\\tif (solve()) {\\n\\t\\t\\tcout << \\\"YES\\\\n\\\";\\n\\t\\t} else {\\n\\t\\t\\tcout << \\\"NO\\\\n\\\";\\n\\t\\t}\\n\\t}\\n\\n\\treturn 0;\\n}\"",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1253",
    "index": "B",
    "title": "Silly Mistake",
    "statement": "The Central Company has an office with a sophisticated security system. There are $10^6$ employees, numbered from $1$ to $10^6$.\n\nThe security system logs entrances and departures. The entrance of the $i$-th employee is denoted by the integer $i$, while the departure of the $i$-th employee is denoted by the integer $-i$.\n\nThe company has some strict rules about access to its office:\n\n- An employee can enter the office \\textbf{at most} once per day.\n- He obviously can't leave the office if he didn't enter it earlier that day.\n- In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day.\n\nAny array of events satisfying these conditions is called a valid day.\n\nSome examples of valid or invalid days:\n\n- $[1, 7, -7, 3, -1, -3]$ is a valid day ($1$ enters, $7$ enters, $7$ leaves, $3$ enters, $1$ leaves, $3$ leaves).\n- $[2, -2, 3, -3]$ is also a valid day.\n- $[2, 5, -5, 5, -5, -2]$ is \\underline{not} a valid day, because $5$ entered the office twice during the same day.\n- $[-4, 4]$ is \\underline{not} a valid day, because $4$ left the office without being in it.\n- $[4]$ is \\underline{not} a valid day, because $4$ entered the office and didn't leave it before the end of the day.\n\nThere are $n$ events $a_1, a_2, \\ldots, a_n$, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events.\n\nYou must partition (to cut) the array $a$ of events into \\textbf{contiguous subarrays}, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day.\n\nFor example, if $n=8$ and $a=[1, -1, 1, 2, -1, -2, 3, -3]$ then he can partition it into two contiguous subarrays which are valid days: $a = [1, -1~ \\boldsymbol{|}~ 1, 2, -1, -2, 3, -3]$.\n\nHelp the administrator to partition the given array $a$ in the required way or report that it is impossible to do. Find any required partition, you should not minimize or maximize the number of parts.",
    "tutorial": "We can solve this problem with a straightforward greedy solution: simulate the events in the order in which they occured, and as soon as the office is empty, end the current day and begin a new one. We can prove that if there exists a valid solution, this greedy algorithm will find one (and furthermore, it will use maximum number of days, even if it wasn't required). To do the simulation efficiently, we should maintain the state of each employee in an array (never went to the office today / in the office / left the office) and the number of employees currently in the office. Each time we end a day, we have to reset all states of employees involved in the day (not all employees, otherwise the solution would be $O(n^2)$). Final complexity is $O(n + e)$ where $e$ is the number of employees, or $O(n)$ if you compress the array beforehand.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\nconst int borne = (int)(1e6) + 5;\\nconst int WAIT=0, ENTERED=1, LEFT=2;\\nint state[borne];\\n\\nbool solve()\\n{\\n\\tios::sync_with_stdio(false);\\n\\tint nbEvents;\\n\\tcin >> nbEvents;\\n\\tvector<int> res, cur;\\n\\tint ofs = 0;\\n\\n\\tfor (int ind = 0; ind < nbEvents; ++ind) {\\n\\t\\tint ev; cin >> ev;\\n\\t\\tint guy = abs(ev);\\n\\t\\tcur.push_back(guy);\\n\\t\\tif (ev > 0) {\\n\\t\\t\\tif (state[guy] != WAIT) return false;\\n\\t\\t\\tstate[guy] = ENTERED; ++ofs;\\n\\t\\t} else {\\n\\t\\t\\tif (state[guy] != ENTERED) return false;\\n\\t\\t\\tstate[guy] = LEFT; --ofs;\\n\\t\\t}\\n\\t\\tif (ofs == 0) {\\n\\t\\t\\tres.push_back(cur.size());\\n\\t\\t\\tfor (int x : cur) state[x] = WAIT;\\n\\t\\t\\tcur.clear();\\n\\t\\t}\\n\\t}\\n\\n\\tif (! cur.empty()) return false;\\n\\n\\tint nbDays = res.size();\\n\\tcout << nbDays << \\\"\\\\n\\\";\\n\\tfor (int i = 0; i < nbDays; ++i) {\\n\\t\\tcout << res[i];\\n\\t\\tif (i+1 < nbDays) cout << \\\" \\\";\\n\\t\\telse cout << \\\"\\\\n\\\";\\n\\t}\\n\\treturn true;\\n}\\n\\nint main()\\n{\\n\\tif (!solve()) cout << \\\"-1\\\\n\\\";\\n\\treturn 0;\\n}\"",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1253",
    "index": "C",
    "title": "Sweets Eating",
    "statement": "Tsumugi brought $n$ delicious sweets to the Light Music Club. They are numbered from $1$ to $n$, where the $i$-th sweet has a sugar concentration described by an integer $a_i$.\n\nYui loves sweets, but she can eat at most $m$ sweets each day for health reasons.\n\nDays are $1$-indexed (numbered $1, 2, 3, \\ldots$). Eating the sweet $i$ at the $d$-th day will cause a sugar penalty of $(d \\cdot a_i)$, as sweets become more sugary with time. A sweet can be eaten at most once.\n\nThe total sugar penalty will be the \\textbf{sum} of the individual penalties of each sweet eaten.\n\nSuppose that Yui chooses exactly $k$ sweets, and eats them in any order she wants. What is the \\textbf{minimum} total sugar penalty she can get?\n\nSince Yui is an undecided girl, she wants you to answer this question for every value of $k$ between $1$ and $n$.",
    "tutorial": "Let's sort array $a$. Now we can easily that if Yui wants to eat $k$ sweets, she has to eat sweets $k, k-1, \\ldots, 1$ in this order, because of rearrangement inequality (put lower coefficients (day) on higher values (sugar concentration)). A naive simulation of this strategy would have complexity $O(n^2)$, which is too slow. Let's look what happens when we replace $k$ by $k+m$. During the first day, Yui will eat sweets $k+m, k+(m-1), \\ldots, k+1$. Then, we reproduce the strategy used for $x_k$, but one day late : all coefficients are increased by $1$. Formally, $x_{k+m} - x_k = new + inc$ where $new = (a_{k+m} + \\ldots + a_{k+1})$ because of new sweets eaten and $inc = (a_k + \\ldots + a_1)$ because the coefficient of these sweets are all increased by $1$ (we eat them one day later). We can derive the following formula : $x_k = (a_k + a_{k-1} + \\ldots + a_1) + x_{k-m}$. If we maintain the current prefix sum, and all previous answers computed in an array, we can compute all answers in $O(n)$. Final complexity is $O(n \\log n)$, because sorting is the slowest part of the solution.",
    "code": "\"#include <iostream>\\n#include <vector>\\n#include <algorithm>\\nusing namespace std;\\n\\nint main()\\n{\\n\\tios::sync_with_stdio(false);\\n\\tcin.tie(0);\\n\\n\\tint nbSweets, maxPerDay;\\n\\tcin >> nbSweets >> maxPerDay;\\n\\n\\tvector<int> val(nbSweets);\\n\\n\\tfor (int iSweet = 0; iSweet < nbSweets; ++iSweet) {\\n\\t\\tcin >> val[iSweet];\\n\\t}\\n\\n\\tsort(val.begin(), val.end());\\n\\n\\tvector<long long> ans(nbSweets);\\n\\n\\tlong long curSum = 0;\\n\\n\\tfor (int lastTaken = 0; lastTaken < nbSweets; ++lastTaken) {\\n\\t\\tcurSum += val[lastTaken];\\n\\t\\tans[lastTaken] = curSum;\\n\\n\\t\\tif (lastTaken >= maxPerDay) {\\n\\t\\t\\tans[lastTaken] += ans[lastTaken - maxPerDay];\\n\\t\\t}\\n\\n\\t\\tcout << ans[lastTaken] << (lastTaken == nbSweets-1 ? '\\\\n' : ' ');\\n\\t}\\n\\n\\treturn 0;\\n}\"",
    "tags": [
      "dp",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1253",
    "index": "D",
    "title": "Harmonious Graph",
    "statement": "You're given an undirected graph with $n$ nodes and $m$ edges. Nodes are numbered from $1$ to $n$.\n\nThe graph is considered harmonious if and only if the following property holds:\n\n- For every triple of integers $(l, m, r)$ such that $1 \\le l < m < r \\le n$, if there exists a \\textbf{path} going from node $l$ to node $r$, then there exists a \\textbf{path} going from node $l$ to node $m$.\n\nIn other words, in a harmonious graph, if from a node $l$ we can reach a node $r$ through edges ($l < r$), then we should able to reach nodes $(l+1), (l+2), \\ldots, (r-1)$ too.\n\nWhat is the minimum number of edges we need to add to make the graph harmonious?",
    "tutorial": "For each connected component, let's find the weakest node $l$ and the biggest node $r$ in it (with one DFS per connected component). If we look for all components at their intervals $[l\\ ;\\ r]$, we can see that two components should be connected in the resulting graph if and only if their intervals intersect. This leads to a $O(n^2 + m)$ naive solution : create a second graph where nodes represent components, add an edge between all pairs of components with intersecting intervals, and choose any spanning forest. To optimize it, generate intervals in increasing order of $l$ (starting DFS in increasing order of nodes numbers). Look at them in this order, maintaining the biggest end $B$ seen. If $l \\le B$, it is necessary to connect current interval to the interval ending at $B$ (hence increment answer). It is quite easy to prove that doing only these connections is also sufficient (i.e. resulting graph will be harmonious). Final complexity is $O(n + m)$.",
    "code": "\"#include <iostream>\\n#include <vector>\\n#include <algorithm>\\nusing namespace std;\\n\\nconst int borne = 201*1000;\\nint nbNodes, nbEdges;\\n\\nvector<int> adj[borne];\\nbool vu[borne];\\nvector<pair<int, int>> ivComp;\\n\\nvoid dfs(int nod, int& weaker, int& bigger)\\n{\\n\\tvu[nod] = true;\\n\\tweaker = min(weaker, nod);\\n\\tbigger = max(bigger, nod);\\n\\n\\tfor (int neighbor : adj[nod]) if (! vu[neighbor]) {\\n\\t\\tdfs(neighbor, weaker, bigger);\\n\\t}\\n}\\n\\nint main()\\n{\\n\\tios::sync_with_stdio(false);\\n\\tcin.tie(0);\\n\\n\\tcin >> nbNodes >> nbEdges;\\n\\tfor (int iEdge = 0; iEdge < nbEdges; ++iEdge) {\\n\\t\\tint u, v;\\n\\t\\tcin >> u >> v;\\n\\t\\t--u; --v;\\n\\t\\tadj[u].push_back(v);\\n\\t\\tadj[v].push_back(u);\\n\\t}\\n\\n\\tfor (int nod = 0; nod < nbNodes; ++nod) {\\n\\t\\tif (! vu[nod]) {\\n\\t\\t\\tint weaker = nod, bigger = nod;\\n\\t\\t\\tdfs(nod, weaker, bigger);\\n\\t\\t\\tivComp.emplace_back(weaker, bigger);\\n\\t\\t}\\n\\t}\\n\\n\\t//sort(ivComp.begin(), ivComp.end()); // Useless, already sorted\\n\\n\\tint curEnd = -1;\\n\\tint rep = 0;\\n\\n\\tfor (auto comp : ivComp) {\\n\\t\\tif (comp.first <= curEnd) {\\n\\t\\t\\t++rep;\\n\\t\\t}\\n\\t\\tcurEnd = max(curEnd, comp.second);\\n\\t}\\n\\n    cout << rep << \\\"\\\\n\\\";\\n\\treturn 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1253",
    "index": "E",
    "title": "Antenna Coverage",
    "statement": "The mayor of the Central Town wants to modernize Central Street, represented in this problem by the $(Ox)$ axis.\n\nOn this street, there are $n$ antennas, numbered from $1$ to $n$. The $i$-th antenna lies on the position $x_i$ and has an initial scope of $s_i$: it covers all integer positions inside the interval $[x_i - s_i; x_i + s_i]$.\n\nIt is possible to increment the scope of any antenna by $1$, this operation costs $1$ coin. We can do this operation as much as we want (multiple times on the same antenna if we want).\n\nTo modernize the street, we need to make all \\underline{integer} positions from $1$ to $m$ inclusive covered by \\underline{at least} one antenna. Note that it is authorized to cover positions outside $[1; m]$, even if it's not required.\n\nWhat is the minimum amount of coins needed to achieve this modernization?",
    "tutorial": "We can add an antenna $(x=0, s=0)$. It will not modifiy the answer, because it would be non-optimal to increase the scope of this antenna. Let $dp_x$ be the minimum cost to cover all positions from $x$ to $m$ inclusive, knowing that position $x$ is covered. We compute $dp$ in decreasing order of $x$. Base case is $dp_m := 0$. The default transition is $dp_x := (m - x)$. If position $x+1$ is initially covered, $dp_x := dp_{x+1}$ Otherwise, let's consider all antennas and their initial intervals $[l_i; r_i]$. If $x < l_i$, let $u = (l_i - x - 1)$, then a possible transition is $dp_x := u + dp_{min(m, r_i + u)}$. We take the minimum of all these transitions. Note that we always extend intervals as less as possible, but it's optimal because : If after using this interval $i$, we use another interval $j$ (at the right of $i$), the time spent to extend $i$ could have been used to extend $j$ instead, which will be more optimal. If $i$ was the last interval used, we don't care because the default transition will take care of this case. The final answer will be $dp_0$. There are $O(m)$ states and $O(n)$ transitions, hence final complexity is $O(nm)$ with very low constant. $O(n^2 \\cdot m)$ can also get AC because of very low constant.",
    "code": "\"#include <iostream>\\n#include <vector>\\n#include <algorithm>\\nusing namespace std;\\n\\nstruct Antenna\\n{\\n\\tint iniLeft, iniRight;\\n};\\n\\nint main()\\n{\\n\\tios::sync_with_stdio(false);\\n\\tcin.tie(0);\\n\\n\\tint nbAntennas, totLen;\\n\\tcin >> nbAntennas >> totLen;\\n\\tvector<Antenna> ants(nbAntennas);\\n\\n\\tfor (int iAnt = 0; iAnt < nbAntennas; ++iAnt) {\\n\\t\\tint center, iniScope;\\n\\t\\tcin >> center >> iniScope;\\n\\t\\tants[iAnt].iniLeft = max(0, center - iniScope);\\n\\t\\tants[iAnt].iniRight = min(totLen, center + iniScope);\\n\\t}\\n\\n\\tvector<int> minCost(totLen+1);\\n\\tminCost[totLen] = 0;\\n\\n\\tfor (int pos = totLen-1; pos >= 0; --pos) {\\n\\t\\tminCost[pos] = (totLen - pos);\\n\\n\\t\\tfor (int iAnt = 0; iAnt < nbAntennas; ++iAnt) {\\n\\t\\t\\tint left = ants[iAnt].iniLeft, right = ants[iAnt].iniRight;\\n\\n\\t\\t\\tif (left <= pos+1 && pos+1 <= right) {\\n\\t\\t\\t\\tminCost[pos] = minCost[pos+1];\\n\\t\\t\\t\\tbreak;\\n\\t\\t\\t}\\n\\t\\t\\t\\n\\t\\t\\tif (pos < left) {\\n\\t\\t\\t\\tint accessCost = (left - pos - 1);\\n\\t\\t\\t\\tint nextPos = min(totLen, right + accessCost);\\n\\t\\t\\t\\tminCost[pos] = min(minCost[pos], accessCost + minCost[nextPos]);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tcout << minCost[0] << \\\"\\\\n\\\";\\n\\n\\treturn 0;\\n}\"",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1253",
    "index": "F",
    "title": "Cheap Robot",
    "statement": "You're given a simple, undirected, connected, weighted graph with $n$ nodes and $m$ edges.\n\nNodes are numbered from $1$ to $n$. There are exactly $k$ centrals (recharge points), which are nodes $1, 2, \\ldots, k$.\n\nWe consider a robot moving into this graph, with a battery of capacity $c$, not fixed by the constructor yet. At any time, the battery contains an integer amount $x$ of energy between $0$ and $c$ inclusive.\n\nTraversing an edge of weight $w_i$ is possible only if $x \\ge w_i$, and costs $w_i$ energy points ($x := x - w_i$).\n\nMoreover, when the robot reaches a central, its battery is entirely recharged ($x := c$).\n\nYou're given $q$ \\underline{independent} missions, the $i$-th mission requires to move the robot from \\underline{central} $a_i$ to \\underline{central} $b_i$.\n\nFor each mission, you should tell the minimum capacity required to acheive it.",
    "tutorial": "Key insight 1: Since we always end on a central, at any time our robot have to be able to reach the nearest central. Key insight 2: Since we always start from a central, from any node $u$, going to the nearest central, then going back to $u$ can't decrease the number of energy points in the battery. - Firstly, let's do a multi-source Dijkstra from all centrals. We denote $d_u$ the distance from node $u$ to the nearest central. Consider a fixed capacity $c$. Suppose that we're on node $u$ with $x$ energy points remaining in the battery. Note that $x \\le c - d_u$. If $x < d_u$, we can't do anything, the robot is lost because it can't reach any central anymore. Otherwise, if $x \\ge d_u$, we can go to the nearest central, then go back to $u$, hence we can always consider than $x = c - d_u$. This is a simple but very powerful observation that allows us to delete the battery level in states explored. Hence, we can now solve the problem in $O(m \\log m + qm \\log n)$, doing binary search on answer and simple DFS for each query. - We need to optimize this solution. Now, reaching a node $u$ will mean reaching it with $x \\ge d_u$. During exploration of nodes, the necessary and sufficient condition for being able to reach node $v$ from $u$, through an edge of weight $w$, is that $(c - d_u) - w \\ge d_v$, i.e. $d_u + d_v + w \\le c$. Hence, if we replace the weight of each edge $(u, v, w)$ by $w' = d_u + d_v + w$, the problem is reduced to find a shortest path from $a_i$ to $b_i$, in terms of maximum weight over edges used (which will be the capacity required by this path). Solution 1 (offline): Sort edges by new weight. Add them progressively, maintaining connexity with DSU. As soon as two endpoints of a query become connected, we should put current capacity (i.e. new weight of the last edge added) as answer for this query. To effeciently detect this, we can put tokens on endpoints of each query, and each time we do union (of DSU), we make tokens go up to the parent. If we do union by rank, each token will move at most $O(\\log n)$ times. Solution 2 (online): Let's construct a MST of the new graph with Kruskal. It is well-known that in this particular MST, for every pair of nodes $(u, v)$, the only path from $u$ to $v$ will be a shortest path (in terms of maximum weight over the path). Hence we just have to compute the weight of paths in a tree, which can be done with binary lifting. These two solutions both run in $O(m \\log m + q \\log n)$. Implementation of solution 1 is a bit shorter, but solution 2 can deal with online queries.",
    "code": "\"#include <iostream>\\n#include <algorithm>\\n#include <vector>\\n#include <queue>\\nusing namespace std;\\n\\nusing llg = long long;\\n\\nconst int maxNod = (int)(1e5) + 5;\\nconst int maxEdges = 3*(int)(1e5) + 5;\\nconst int maxQueries = 3*(int)(1e5) + 5;\\n\\nconst int maxTokens = 2*maxQueries;\\n\\nconst llg BIG = (llg)(1e9) * (llg)(1e9);\\n\\nint nbNod, nbEdges, nbCentrals, nbQueries;\\nllg rep[maxQueries];\\n\\n// DSU\\n\\nint dsuRepr[maxNod];\\nint dsuSize[maxNod];\\nvector<int> tokenIn[maxNod];\\n\\nint baseTok[maxTokens];\\n\\nvoid dsuInit()\\n{\\n\\tfor (int nod = 0; nod < maxNod; ++nod) {\\n\\t\\tdsuRepr[nod] = nod;\\n\\t\\tdsuSize[nod] = 1;\\n\\t}\\n}\\n\\nint dsuFind(int x)\\n{\\n\\tif (x != dsuRepr[x]) {\\n\\t\\tdsuRepr[x] = dsuFind(dsuRepr[x]);\\n\\t}\\n\\treturn dsuRepr[x];\\n}\\n\\nvoid dsuMerge(int small, int big, llg curCap)\\n{\\n\\tsmall = dsuFind(small);\\n\\tbig = dsuFind(big);\\n\\tif (small == big) return;\\n\\tif (dsuSize[small] > dsuSize[big]) swap(small, big);\\n\\n\\tfor (int token : tokenIn[small]) {\\n\\t\\tint oth = token^1;\\n\\t\\tint query = token/2;\\n\\t\\tif (dsuFind(baseTok[oth]) == big) {\\n\\t\\t\\trep[query] = curCap;\\n\\t\\t}\\n\\t\\ttokenIn[big].push_back(token);\\n\\t}\\n\\n\\ttokenIn[small].clear();\\n\\ttokenIn[small].shrink_to_fit();\\n\\n\\tdsuSize[big] += dsuSize[small];\\n\\tdsuRepr[small] = big;\\n}\\n\\n// Dijkstra\\n\\nvector<pair<int, llg>> adj[maxNod];\\nllg mdis[maxNod];\\n\\nvoid dijkstra()\\n{\\n\\tpriority_queue<pair<llg, int>> pq;\\n\\tfor (int nod = 0; nod < nbNod; ++nod) {\\n\\t\\tif (nod < nbCentrals) {\\n\\t\\t\\tpq.push({0, nod});\\n\\t\\t} else {\\n\\t\\t\\tmdis[nod] = BIG;\\n\\t\\t}\\n\\t}\\n\\n\\twhile (! pq.empty()) {\\n\\t\\tllg dist = -pq.top().first;\\n\\t\\tint nod = pq.top().second;\\n\\t\\tpq.pop();\\n\\t\\tif (dist != mdis[nod]) continue;\\n\\n\\t\\tfor (auto rawNeigh : adj[nod]) {\\n\\t\\t\\tint neighbor = rawNeigh.first;\\n\\t\\t\\tllg newDis = dist + rawNeigh.second;\\n\\t\\t\\tif (newDis < mdis[neighbor]) {\\n\\t\\t\\t\\tmdis[neighbor] = newDis;\\n\\t\\t\\t\\tpq.push({-newDis, neighbor});\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n}\\n\\n// Main\\n\\nstruct Edge\\n{\\n\\tllg weight, n1, n2;\\n};\\n\\nbool operator<(Edge a, Edge b)\\n{\\n\\treturn a.weight < b.weight;\\n}\\n\\nvector<Edge> tabEdges;\\n\\nint main()\\n{\\n\\tios::sync_with_stdio(false);\\n\\tcin.tie(0);\\n\\tdsuInit();\\n\\n\\tcin >> nbNod >> nbEdges >> nbCentrals >> nbQueries;\\n\\tfor (int iEdge = 0; iEdge < nbEdges; ++iEdge) {\\n\\t\\tint n1, n2; llg weight;\\n\\t\\tcin >> n1 >> n2 >> weight;\\n\\t\\t--n1; --n2;\\n\\t\\tadj[n1].emplace_back(n2, weight);\\n\\t\\tadj[n2].emplace_back(n1, weight);\\n\\t\\ttabEdges.push_back({weight, n1, n2});\\n\\t}\\n\\n\\tfor (int query = 0; query < nbQueries; ++query) {\\n\\t\\tint n1, n2;\\n\\t\\tcin >> n1 >> n2;\\n\\t\\t--n1; --n2;\\n\\t\\tint tk1 = 2*query, tk2 = 2*query+1;\\n\\n\\t\\tbaseTok[tk1] = n1;\\n\\t\\tbaseTok[tk2] = n2;\\n\\n\\t\\ttokenIn[n1].push_back(tk1);\\n\\t\\ttokenIn[n2].push_back(tk2);\\n\\t}\\n\\n\\tdijkstra();\\n\\n\\tfor (auto &edge : tabEdges) {\\n\\t\\tedge.weight += mdis[edge.n1] + mdis[edge.n2];\\n\\t}\\n\\n\\tsort(tabEdges.begin(), tabEdges.end());\\n\\n\\tfor (auto edge : tabEdges) {\\n\\t\\tdsuMerge(edge.n1, edge.n2, edge.weight);\\n\\t}\\n\\n\\tfor (int query = 0; query < nbQueries; ++query) {\\n\\t\\tcout << rep[query] << \\\"\\\\n\\\";\\n\\t}\\n}\"",
    "tags": [
      "binary search",
      "dsu",
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1254",
    "index": "A",
    "title": "Feeding Chicken",
    "statement": "Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm.\n\nHis farm is presented by a rectangle grid with $r$ rows and $c$ columns. Some of these cells contain rice, others are empty. $k$ chickens are living on his farm. \\textbf{The number of chickens is not greater than the number of cells with rice on the farm.}\n\nLong wants to give his chicken playgrounds by assigning these farm cells to his chickens. He would like to satisfy the following requirements:\n\n- Each cell of the farm is assigned to \\textbf{exactly one} chicken.\n- Each chicken is assigned \\textbf{at least one} cell.\n- The set of cells assigned to every chicken forms a connected area. More precisely, if two cells $(x, y)$ and $(u, v)$ are assigned to the same chicken, this chicken is able to walk from $(x, y)$ to $(u, v)$ by passing only its cells and moving from each cell to another cell sharing a side.\n\nLong also wants to prevent his chickens from fighting for food. Hence he wants the difference between the maximum and the minimum number of cells with rice assigned to a chicken to be as small as possible. Please help him.",
    "tutorial": "First, we will try to solve the problem when our rectangle is an array (or an $1 \\cdot n$ rectangle). Let $r$ be the number of rice cells. It's not hard to see that the difference between the maximum and the minimum number of cells with rice assigned to a chicken is either $0$, when $r$ $mod$ $k = 0$, or $1$ otherwise. Turns out, there is an easy way to assign: for the first $r$ $mod$ $k$ chicken, we will assign to the current chicken a prefix of the current array that contains exactly $\\lceil r/k \\rceil$ rice cells, and delete that prefix. The same for the others $k - (r$ $mod$ $k)$ chicken, we will assign to the current chicken a prefix of the current array that contains exactly $\\lfloor r/k \\rfloor$ rice cells. Notice that there exists a path that goes through every cell exactly once and every two consecutive cells on the path share a side. One such path is $(1, 1), (1, 2), ... (1,c), (2,c), (2, c-1), ..., (2, 1), (3, 1), (3, 2), ...$ By thinking the path as an array, we can assign regions on the path according to the above paragraph. Such an assignment is also a valid assignment for the original rectangle.",
    "code": "#include<bits/stdc++.h>\n#define FOR(i, a, b) for (int i = (a), _b = (b); i <= _b; i++)\n#define FORD(i, b, a) for (int i = (b), _a = (a); i >= _a; i--)\n#define REP(i, n) for (int i = 0, _n = (n); i < _n; i++)\n#define FORE(i, v) for (__typeof((v).begin()) i = (v).begin(); i != (v).end(); i++)\n#define ALL(v) (v).begin(), (v).end()\n#define IS_INF(x)   (std::isinf(x))\n#define IS_NAN(x)   (std::isnan(x))\n#define fi   first\n#define se   second\n#define MASK(i) (1LL << (i))\n#define BIT(x, i) (((x) >> (i)) & 1)\n#define div   ___div\n#define next   ___next\n#define prev   ___prev\n#define left   ___left\n#define right   ___right\n#define __builtin_popcount __builtin_popcountll\nusing namespace std;\ntemplate<class X, class Y>\n    bool minimize(X &x, const Y &y) {\n        X eps = 1e-9;\n        if (x > y + eps) {\n            x = y;\n            return true;\n        } else return false;\n    }\ntemplate<class X, class Y>\n    bool maximize(X &x, const Y &y) {\n        X eps = 1e-9;\n        if (x + eps < y) {\n            x = y;\n            return true;\n        } else return false;\n    }\ntemplate<class T>\n    T Abs(const T &x) {\n        return (x < 0 ? -x : x);\n    }\n\n/* Author: Van Hanh Pham */\n\n/** END OF TEMPLATE - ACTUAL SOLUTION COMES HERE **/\n\nconst string SYMBOLS = \"QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890\";\n\n#define MAX  111\nchar board[MAX][MAX], res[MAX][MAX];\nint numRow, numCol, numChicken;\n\nvoid process(void) {\n    memset(board, 0, sizeof board);\n    memset(res, 0, sizeof res);\n\n    scanf(\"%d%d%d\", &numRow, &numCol, &numChicken);\n    FOR(i, 1, numRow) scanf(\"%s\", board[i] + 1);\n\n    bool leftToRight = true;\n    vector<pair<int, int>> cells;\n    FOR(i, 1, numRow) {\n        if (leftToRight) {\n            FOR(j, 1, numCol) cells.push_back(make_pair(i, j));\n        } else {\n            FORD(j, numCol, 1) cells.push_back(make_pair(i, j));\n        }\n        leftToRight ^= 1;\n    }\n\n    int totRice = 0;\n    FOR(i, 1, numRow) FOR(j, 1, numCol) if (board[i][j] == 'R') totRice++;\n    int avg = totRice / numChicken;\n    int diff = totRice % numChicken == 0 ? 0 : 1;\n\n    REP(i, numChicken) {\n        int cntRice = 0;\n        while (true) {\n            int x = cells.back().fi, y = cells.back().se;\n            cells.pop_back();\n            res[x][y] = SYMBOLS[i];\n            if (board[x][y] == 'R') {\n                totRice--;\n                cntRice++;\n            }\n            if (cntRice < avg) continue;\n            if (avg * (numChicken - i - 1) <= totRice && totRice <= (avg + diff) * (numChicken - i - 1)) break;\n        }\n    }\n    while (!cells.empty()) {\n        int x = cells.back().fi, y = cells.back().se;\n        cells.pop_back();\n        res[x][y] = SYMBOLS[numChicken - 1];\n    }\n\n    FOR(i, 1, numRow) {\n        FOR(j, 1, numCol) printf(\"%c\", res[i][j]); printf(\"\\n\");\n    }\n}\n\nint main(void) {\n    int t; scanf(\"%d\", &t);\n    REP(love, t) process();\n    return 0;\n}\n\n/*** LOOK AT MY CODE. MY CODE IS AMAZING :D ***/",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1254",
    "index": "B1",
    "title": "Send Boxes to Alice (Easy Version)",
    "statement": "This is the easier version of the problem. In this version, $1 \\le n \\le 10^5$ and $0 \\le a_i \\le 1$. You can hack this problem only if you solve and lock both problems.\n\nChristmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $n$ boxes of chocolate, numbered from $1$ to $n$. Initially, the $i$-th box contains $a_i$ chocolate pieces.\n\nSince Bob is a typical nice guy, he will not send Alice $n$ empty boxes. In other words, \\textbf{at least one of $a_1, a_2, \\ldots, a_n$ is positive}. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $k > 1$ such that the number of pieces in each box is divisible by $k$. Note that Alice won't mind if there exists some empty boxes.\n\nCharlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $i$ and put it into either box $i-1$ or box $i+1$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.",
    "tutorial": "Author: MofK. Prepared by UncleGrandpa The problem asked you to move chocolate pieces between adjacent boxes so that the number of chocolate pieces in all boxes is divisible by $k$ ($k>1$). Now, it's clear that we will divide the array into segments, such that the sum of each segment is divisible by $k$, and move all chocolate pieces in that segment to a common box. Here we take notice of 2 things: First, in each segment, let $A$ be the array of all position with 1, then the position that we move all the 1 to is the median of that array $A$ (easy to prove). First, in each segment, let $A$ be the array of all position with 1, then the position that we move all the 1 to is the median of that array $A$ (easy to prove). Second, the sum of each segment should be all equal to $k$. It's easy to see that if there exists some segment of sum $x*k$, then separating them into $x$ segments of sum $k$ will improve the result. Second, the sum of each segment should be all equal to $k$. It's easy to see that if there exists some segment of sum $x*k$, then separating them into $x$ segments of sum $k$ will improve the result. With that two observations, we can iterate from 1 to n, push each position with value 1 into a temp array, and whenever the size of array become k, we add to our result the sum of $|a_i-median|$ and clear the array. It is clear that $k$ must be a divisor of the total number of chocolate pieces. So we iterate through all possible $k$ and minimize our answer with the number of steps to make all numbers divisible by k. A number $\\le 10^5$ has at most 128 divisors, and each calculation take $O(n)$ so the solution should pass easily.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 1000006;\nint n;\nint a[maxn];\nvector <int> v;\n\nlong long cost(int p) {\n    long long ret = 0;\n    for (int i = 0; i < v.size(); i += p) {\n        int median = v[(i + i + p - 1) / 2];\n        for (int j = i; j < i + p; ++j)\n            ret += abs(v[j] - median);\n    }\n    return ret;\n}\n\nint main(void) {\n    ios_base::sync_with_stdio(0);\n    cin.tie(NULL);\n    cin >> n;\n    for (int i = 1; i <= n; ++i) {\n        cin >> a[i];\n        if (a[i] == 1) v.push_back(i);\n    }\n    if (v.size() == 1) {\n        cout << -1 << endl;\n        return 0;\n    }\n    long long ans = 1e18;\n    int tmp = v.size(), p = 2;\n    while (p * p <= tmp) {\n        if (tmp % p == 0) {\n            ans = min(ans, cost(p));\n            while (tmp % p == 0)\n                tmp /= p;\n        }\n        ++p;\n    }\n    if (tmp > 1)\n        ans = min(ans, cost(tmp));\n    cout << ans << endl;\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory",
      "ternary search",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1254",
    "index": "B2",
    "title": "Send Boxes to Alice (Hard Version)",
    "statement": "This is the harder version of the problem. In this version, $1 \\le n \\le 10^6$ and $0 \\leq a_i \\leq 10^6$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems\n\nChristmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $n$ boxes of chocolate, numbered from $1$ to $n$. Initially, the $i$-th box contains $a_i$ chocolate pieces.\n\nSince Bob is a typical nice guy, he will not send Alice $n$ empty boxes. In other words, \\textbf{at least one of $a_1, a_2, \\ldots, a_n$ is positive}. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $k > 1$ such that the number of pieces in each box is divisible by $k$. Note that Alice won't mind if there exists some empty boxes.\n\nCharlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $i$ and put it into either box $i-1$ or box $i+1$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.",
    "tutorial": "Author: MofK. Prepared by MofK and UncleGrandpa The problem E2 is different from the problem E1 in some ways. Now all $A_i$ is at most $10^6$, and so is the number $n$. That makes our solution on E1 simply not usable in this problem. Let $S_i$ be the sum of $a_1 + a_2 + ... + a_i$. Now we see that: if we move a chocolate piece from box $i$ to box $i+1$, it is equivalent to decrease $S_i$ by 1. if we move a chocolate piece from box $i$ to box $i+1$, it is equivalent to decrease $S_i$ by 1. if we move a chocolate piece from box $i+1$ to box $i$, it is equivalent to increase $S_i$ by 1. if we move a chocolate piece from box $i+1$ to box $i$, it is equivalent to increase $S_i$ by 1. Wow, now each moving steps only affect one number. Next, we can see that if every $a_i$ is divisible by k, then so is every $S_i$. Thus, our problem is now transformed to: Given an array $S$. At each turn, you can choose one $S_i$ and increase (or decrease) it by one (except for $S_n$). Find the minimum number of steps to make all $S_i$ divisible by $k$. An intuitive approach is to try to increase (or decrease) each $S_i$ to the nearest multiple of $k$. If such a configuration can be achieved then it will obviously be the best answer. The only concern is that: is there any scenario when there exists some $i$ such that $S_i > S_{i+1}$, which is indeed a violation? Fortunately, the answer is no. We can enforce the solution to iterate each $S_i$ from $1$ to $n-1$ and always choose to decrease if there is a tie. This way, the sequence $S$ will remain non-decreasing throughout the process. So, the solution is as follows. Just iterate from $1$ to $n-1$ and for each $i$, add to our result $min(S_i\\%k,k-S_i\\%k)$. Again, like E1, it is clear that $k$ must be a divisor of the total number of chocolate pieces. But now the total number of chocolate pieces is at most $10^{12}$, which an iteration through all divisors will not be fast enough to fit in 1 second. (In fact, we did make just one single test case to block this solution. Nevertheless, on random testcases it runs super fast). But if you have solved the problem to this phase already, you can easily realize that we only need to consider prime $k$, because if $k$ is composite then picking any prime divisors of it will lead to either a better result or an equal result. That's it, there will be at most 12 distinct prime divisors. Each calculation takes $O(n)$. So the solution will also pass easily.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 1000006;\nint n;\nlong long a[maxn];\nlong long s[maxn];\n\nlong long cost(long long mod) {\n    long long ret = 0;\n    for (int i = 1; i <= n; ++i)\n        ret += min(s[i] % mod, mod - s[i] % mod);\n    return ret;\n}\n\nint main(void) {\n    ios_base::sync_with_stdio(0);\n    cin.tie(NULL);\n    cin >> n;\n    for (int i = 1; i <= n; ++i) {\n        cin >> a[i];\n        s[i] = s[i-1] + a[i];\n    }\n    if (s[n] == 1) {\n        cout << -1 << endl;\n        return 0;\n    }\n    long long ans = 1e18;\n    long long tmp = s[n], p = 2;\n    while (p * p <= tmp) {\n        if (tmp % p == 0) {\n            ans = min(ans, cost(p));\n            while (tmp % p == 0)\n                tmp /= p;\n        }\n        ++p;\n    }\n    if (tmp > 1)\n        ans = min(ans, cost(tmp));\n    cout << ans << endl;\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory",
      "ternary search",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1254",
    "index": "C",
    "title": "Point Ordering",
    "statement": "\\textbf{This is an interactive problem.}\n\nKhanh has $n$ points on the Cartesian plane, denoted by $a_1, a_2, \\ldots, a_n$. All points' coordinates are integers between $-10^9$ and $10^9$, inclusive. No three points are collinear. He says that these points are vertices of a convex polygon; in other words, there exists a permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$ such that the polygon $a_{p_1} a_{p_2} \\ldots a_{p_n}$ is convex and vertices are listed in counter-clockwise order.\n\nKhanh gives you the number $n$, but hides the coordinates of his points. Your task is to guess the above permutation by asking multiple queries. In each query, you give Khanh $4$ integers $t$, $i$, $j$, $k$; where either $t = 1$ or $t = 2$; and $i$, $j$, $k$ are three \\textbf{distinct} indices from $1$ to $n$, inclusive. In response, Khanh tells you:\n\n- if $t = 1$, the area of the triangle $a_ia_ja_k$ \\textbf{multiplied by $2$}.\n- if $t = 2$, the sign of the cross product of two \\textbf{vectors} $\\overrightarrow{a_ia_j}$ and $\\overrightarrow{a_ia_k}$.\n\nRecall that the cross product of vector $\\overrightarrow{a} = (x_a, y_a)$ and vector $\\overrightarrow{b} = (x_b, y_b)$ is the \\textbf{integer} $x_a \\cdot y_b - x_b \\cdot y_a$. The sign of a number is $1$ it it is positive, and $-1$ otherwise. It can be proven that the cross product obtained in the above queries can not be $0$.\n\nYou can ask at most $3 \\cdot n$ queries.\n\nPlease note that Khanh fixes the coordinates of his points and does not change it while answering your queries. You do not need to guess the coordinates. In your permutation $a_{p_1}a_{p_2}\\ldots a_{p_n}$, $p_1$ should be equal to $1$ and the indices of vertices should be \\textbf{listed in counter-clockwise order}.",
    "tutorial": "Let's start by choosing vertices $1$ and $2$ as pivots. Recall that if the cross product of two vectors $\\vec{A}$ and $\\vec{B}$ is positive, point $B$ lies to the left of $\\vec{A}$; if the product is negative, point $B$ lies to the right of $\\vec{A}$; and if the product is zero, the 3 points $(0,0)$, $A$, $B$ are collinear. With $n-2$ queries of type 2, we can know which vertices lie to the left or to the right of edge $1-2$ and then solve the two sides separately. Consider the left side and there are $a$ vertices lie to the left, we can use $a$ queries of type 1 to calculate the distance from those vertices to edge $1-2$ (the distance from vertex $X$ to edge $1-2$ is twice the area of the triangle forms by $1$, $2$, $X$, divides by the length of edge $1-2$). Let Y be the farthest from $1-2$ (there can be at most 2 such vertices). We can use $a-1$ queries of type 2 to see if the others vertices lie between $1, Y$ or between $Y, 2$, then sort them counter-clockwise with the asked distances. So we will use $n-2$ queries to calculate the distances from vertices $3, 4, .. n$ to edge $1-2$ and at most $n - 3$ for the latter step. This solution uses at most $3n-7$ queries. Another solution is to find the vertex that is consecutive to $1$ in $n-2$ queries and do the same as the solution above.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n;\n\nvoid check_if_zero(long long x){\n    if (x == 0) exit(0);\n}\n\nlong long get_area(int a,int b,int c){\n    long long result;\n    cout << 1 << ' ' << a << ' ' << b << ' ' << c << endl;\n    cin >> result;\n    check_if_zero(result);\n    assert(result > 0);\n    return result;\n}\n\nint get_sign(int o,int a,int b){\n    int result;\n    cout << 2 << ' ' << o << ' ' << a << ' ' << b << endl;\n    cin >> result;\n    check_if_zero(result);\n    assert(abs(result) == 1);\n    return result;\n}\n\nvector <int> lef, rig;\n\nvoid divide(){\n    for(int i=3;i<=n;i++){\n        int sign = get_sign(1, 2, i);\n\n        if (sign == 1)\n            lef.push_back(i);\n        else\n            rig.push_back(i);\n    }\n}\n\nlong long area12[1005];\n\nvoid _do(vector<int> &lst){\n    if (lst.size() <= 1)\n        return;\n\n    long long best = 0;\n    for(auto v: lst){\n        area12[v] = get_area(1, 2, v);\n        if (area12[v] > area12[best])\n            best = v;\n    }\n\n    vector <int> l, r;\n    for(auto v: lst){\n        if (v == best)\n            continue;\n\n        if (get_sign(1, best, v) == 1)\n            l.push_back(v);\n        else\n            r.push_back(v);\n    }\n\n    sort(l.begin(), l.end(), [&](int x,int y){\n        return area12[x] > area12[y];\n    });\n    sort(r.begin(), r.end(), [&](int x,int y){\n        return area12[x] < area12[y];\n    });\n\n    lst.clear();\n    for(auto v: r)  lst.push_back(v);\n    lst.push_back(best);\n    for(auto v: l)  lst.push_back(v);\n}\n\nvoid answer(){\n    cout << 0 << ' ' << 1 << ' ';\n    for(auto v: rig)  cout << v << ' ';\n    cout << 2 << ' ';\n    for(auto v: lef)  cout << v << ' ';\n    cout << endl;\n}\n\nint main(){\n    cin >> n;\n    assert(n >= 3);\n\n    divide();   // n-2 queries\n    _do(lef);\n    _do(rig);   //  2*(n-2) - 1 or 2*(n-2) - 2 queries\n    answer();\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "interactive",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1254",
    "index": "D",
    "title": "Tree Queries",
    "statement": "Hanh is a famous biologist. He loves growing trees and doing experiments on his own garden.\n\nOne day, he got a tree consisting of $n$ vertices. Vertices are numbered from $1$ to $n$. A tree with $n$ vertices is an undirected connected graph with $n-1$ edges. Initially, Hanh sets the value of every vertex to $0$.\n\nNow, Hanh performs $q$ operations, each is either of the following types:\n\n- Type $1$: Hanh selects a vertex $v$ and an integer $d$. Then he chooses some vertex $r$ \\textbf{uniformly at random}, lists all vertices $u$ such that the path from $r$ to $u$ passes through $v$. Hanh then increases the value of all such vertices $u$ by $d$.\n- Type $2$: Hanh selects a vertex $v$ and calculates the expected value of $v$.\n\nSince Hanh is good at biology but not math, he needs your help on these operations.",
    "tutorial": "Disclaimer: Our other authors and testers have found better solutions; our best complexity is $O(n \\times log^{2}(n))$. However, since this solution is the theoretically worst complexity that we intended to accept, I decided to write about it. Feel free to share your better solution in the comment section :) Consider two distinct vertices $u$, $v$, the number of vertices $r$ such that the path from $r$ to $u$ passes through $v$ is $n - |Tree(v, u)|$, where $Tree(v, u)$ is the subtree we get by cutting the first edge on the path from $v$ to $u$, then keep the part with vertex $u$. If $u = v$ then this value will be $n$. By linearity of expectation, we can see that adding $d$ to $a[v]$ will add to the expected value of $a[u]$ an amount equal to $\\frac{1}{n} \\times d \\times (n - |Tree(v, u)|)$. Note that this value is the same for all $u$ that lies on the same \"subtree branch\" of $v$. To update it efficiently, we can split the vertices into $2$ groups: those which has degree greater than $T$ (there are no more than $\\frac{n}{T}$ of them), and those which does not. When we update a \"light\" vertex $v$, we iterate over the neighbors of $v$ and update the subtrees accordingly. When we get the value of a vertex $v$, we already have the sum of contributions from all \"light\" vertices to $v$, hence we can iterate over all \"heavy\" vertices and calculate the contribution from each of them to $v$. If we use range-update point-query data structures such as Fenwick Trees then the complexity will be $O(Q \\times log(n) \\times (\\frac{n}{T} + T)) = O(Q \\times \\sqrt{n} \\times log(n))$ if we choose $T = O(\\sqrt{n})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int maxn = 150005;\nconst int mod = 998244353;\nconst int heavy = 300;\nint n, m, q;\nvector <int> adj[maxn];\nint dad[maxn];\nint sz[maxn];\nvector <int> pos[maxn];\nint tour[2*maxn];\nvector <int> heavy_vector;\nint weight[2*maxn];\n \nint pw(int x, int y) {\n    int r = 1;\n    while (y) {\n        if (y & 1) r = 1LL * r * x % mod;\n        x = 1LL * x * x % mod;\n        y >>= 1;\n    }\n    return r;\n}\n \nvoid dfs(int u) {\n    tour[++m] = u;\n    pos[u].push_back(m);\n    sz[u] = 1;\n    for (auto v: adj[u]) {\n        if (v == dad[u]) continue;\n        dad[v] = u;\n        dfs(v);\n        sz[u] += sz[v];\n        tour[++m] = u;\n        pos[u].push_back(m);\n    }\n}\n \nint fwt[2*maxn];\nvoid upd(int l, int r, int d) {\n    for (int p = l; p <= m; p += p & -p) fwt[p] = (fwt[p] + d) % mod;\n    ++r;\n    for (int p = r; p <= m; p += p & -p) fwt[p] = (fwt[p] + mod - d) % mod;\n}\nint get(int p) {\n    int ret = 0;\n    for (; p; p -= p & -p) ret = (ret + fwt[p]) % mod;\n    return ret;\n}\n \nint main(void) {\n    ios_base::sync_with_stdio(0);\n    cin.tie(NULL);\n    cin >> n >> q;\n    int inv_n = pw(n, mod - 2);\n    for (int i = 1; i < n; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n \n    dfs(1);\n    for (int i = 1; i <= n; ++i) if (adj[i].size() >= heavy)\n        heavy_vector.push_back(i);\n \n    while (q--) {\n        int type, v;\n        cin >> type >> v;\n        if (type == 1) {\n            int d;\n            cin >> d;\n            weight[v] = (weight[v] + d) % mod;\n            if (adj[v].size() < heavy) {\n                for (auto u: adj[v]) if (u != dad[v])\n                    upd(pos[u][0], pos[u].back(), 1LL * d * (n - sz[u]) % mod * inv_n % mod);\n                if (v == 1) continue;\n                upd(1, pos[v][0] - 1, 1LL * d * sz[v] % mod * inv_n % mod);\n                upd(pos[v].back() + 1, m, 1LL * d * sz[v] % mod * inv_n % mod);\n            }\n        }\n        else {\n            int ans = (weight[v] + get(pos[v][0])) % mod;\n            for (auto u: heavy_vector) {\n                if (u == v) continue;\n                auto it = lower_bound(pos[u].begin(), pos[u].end(), pos[v][0]);\n                if (it == pos[u].begin() || it == pos[u].end())\n                    ans = (ans + 1LL * weight[u] * sz[u] % mod * inv_n) % mod;\n                else {\n                    int p = tour[*(--it) + 1];\n                    ans = (ans + 1LL * weight[u] * (n - sz[p]) % mod * inv_n) % mod;\n                }\n            }\n            cout << ans << '\\n';\n        }\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "probabilities",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1254",
    "index": "E",
    "title": "Send Tree to Charlie",
    "statement": "Christmas was knocking on the door, and our protagonist, Bob, was preparing a spectacular present for his long-time second best friend Charlie. As chocolate boxes are lame, he decided to decorate a tree instead. Bob's tree can be represented as an undirected connected graph with $n$ nodes (numbered $1$ to $n$) and $n-1$ edges. Initially, Bob placed a decoration with label $i$ on node $i$, for each $1 \\le i \\le n$. However, as such a simple arrangement is lame, he decided to shuffle the decorations a bit. Formally, Bob did the following steps:\n\n- First, he listed the $n-1$ edges in some order.\n- Then, he considered the edges one by one in that order. For each edge $(u, v)$, he swapped the decorations of node $u$ with the one of node $v$.\n\nAfter finishing, Bob seemed satisfied with the arrangement, so he went to sleep.\n\nThe next morning, Bob wakes up only to find out that his beautiful arrangement has been ruined! Last night, Bob's younger brother Bobo dropped some of the decorations on the floor while he was playing with the tree. Fortunately, no decorations were lost, so Bob can repair the tree in no time. However, he completely forgets how the tree looked like yesterday. Therefore, given the labels of the decorations still on the tree, Bob wants to know the number of possible configurations of the tree. As the result can be quite large, Bob will be happy if you can output the result modulo $1000000007$ ($10^9+7$). Note that, it is possible that there exists no possible configurations.",
    "tutorial": "Let's solve an easier version of this problem first: when all $a_i$ is equal to $0$. Let $P[1..n-1]$ be some order of edges. If $n=2$ then the answer is clearly $1$. Otherwise, consider any leaf $u$ and its neighbor $v$. The label of $u$ in the end will depend solely on the relative position of the edge $(u, v)$ compared to other edges incident to $v$ in $P$. We can also prove that if that relative position is fixed then the final configuration will be the same. Therefore, if we add $u$ to the tree, the answer will be multiplied by $deg(v)$. It follows that the answer in this case will be $\\displaystyle\\prod_{u=1}^{n} deg(u)!$. We can also see that each configuration can be obtained by ordering the edges incident to $u$ for each vertex $u$. Now, let's consider some constraint of the form $a[u] = v$. If $u = v$ then clearly there's no such configuration. Otherwise, it will create some conditions of the orderings in each vertex. Formally, let $B(u)$ be the ordering of edges incident to $u$, and $u, t_1, \\ldots, t_k, v$ be the path from $u$ to $v$, we have the following conditions: $(u, t_1)$ is the first edge in $B(u)$. $(t_i, t_{i-1})$ must be followed immediately by $(t_i, t_{i+1})$ in $B(t_i)$, for all $1 \\le i \\le k$. $(v, t_k)$ is the last edge in $B(v)$. Another thing to note is that in the final configuration, the sum of distance between $u$ and the vertex that contains label $u$ will be exactly $2n-2$ because each swap increases the sum by exactly $2$. Therefore, we can quit immediately upon finding out that the sum is larger than $2n-2$, and by that we ensure the total number of conditions will be $O(n)$. Now, we can solve each vertex independently. For each vertex, there will be no possible configurations iff at least one of the following holds: Some edge follows or is followed by more than one edge. The conditions create some cycles. The conditions create a path from the first edge to the last edge, but there exists some edge not in it. Otherwise, the conditions create some chains. We then multiply the answer by $k!$, where $k$ is the number of such chains, excluding those that contain the first edge or the last edge. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int mod = 1e9 + 7;\nconst int maxn = 500005;\n\nint n;\nvector <int> adj[maxn];\nint a[maxn];\nint dad[maxn];\nint h[maxn];\nvector <pair <int, int> > conditions[maxn];\nint nxt[maxn], prv[maxn], seen[maxn];\n\nvoid no(int ncase) {\n    cerr << ncase << endl;\n    cout << 0 << endl;\n    exit(0);\n}\n\nvoid dfs(int u) {\n    for (auto v: adj[u]) if (v != dad[u]) {\n        dad[v] = u;\n        h[v] = h[u] + 1;\n        dfs(v);\n    }\n}\n\nint cnt; ///total distance, must not be more than 2n-2\n\nvoid go(int u, int v) {\n    if (u == v) no(0);\n    vector <int> from_u, to_v;\n    ///naive LCA works here as long as we exit upon finding a conflict\n    from_u.push_back(n + 1); ///first edge (fake)\n    to_v.push_back(n + 2); ///last edge (fake)\n    while (h[u] > h[v]) {\n        from_u.push_back(u);\n        u = dad[u];\n    }\n    while (h[v] > h[u]) {\n        to_v.push_back(v);\n        v = dad[v];\n    }\n    while (u != v) {\n        from_u.push_back(u);\n        u = dad[u];\n        to_v.push_back(v);\n        v = dad[v];\n    }\n    from_u.push_back(u);\n    from_u.insert(from_u.end(), to_v.rbegin(), to_v.rend());\n    for (int i = 1; i + 1 < from_u.size(); ++i)\n        conditions[from_u[i]].push_back({from_u[i-1], from_u[i+1]});\n    cnt += from_u.size() - 3;\n    if (cnt > 2 * n - 2) no(0); ///important break\n}\n\nint main(void) {\n    ios_base::sync_with_stdio(0);\n    cin.tie(NULL);\n    cin >> n;\n    for (int i = 1; i < n; ++i) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    for (int i = 1; i <= n; ++i) {\n        adj[i].push_back(n + 1); ///first edge (fake)\n        adj[i].push_back(n + 2); ///last edge (fake)\n    }\n    for (int i = 1; i <= n; ++i) cin >> a[i];\n\n    if (n == 1) {\n        cout << 1 << endl;\n        exit(0);\n    }\n\n    dfs(1);\n    for (int i = 1; i <= n; ++i) if (a[i] != 0) go(i, a[i]);\n\n    ///answer 0 if:\n    ///1. there are 2 or more incoming/outgoing\n    ///conditions to/from an edge, or\n    ///2. there is a cycle, or\n    ///3. first (n+1) is connected to last (n+2),\n    ///but does not contain all other edges.\n    int ans = 1;\n    for (int i = 1; i <= n; ++i) {\n        ///check case 1\n        for (auto edge: conditions[i]) {\n            int u = edge.first, v = edge.second;\n            if (nxt[u] && nxt[u] != v) no(1);\n            if (prv[v] && prv[v] != u) no(1);\n            nxt[u] = v;\n            prv[v] = u;\n        }\n        ///check case 2\n        for (auto u: adj[i]) if (!seen[u]) {\n            seen[u] = 1;\n            int cur = nxt[u];\n            while (cur) {\n                if (cur == u) no(2);\n                if (seen[cur]) break;\n                seen[cur] = 1;\n                cur = nxt[cur];\n            }\n        }\n        ///check case 3\n        if (nxt[n+1]) {\n            int cur = n + 1, all = 1;\n            while (cur) {\n                if (cur == n + 2) break;\n                ++all;\n                cur = nxt[cur];\n            }\n            if (cur == n + 2 && all < adj[i].size()) no(3);\n        }\n        ///all good - for now\n        int free = 0;\n        for (auto u: adj[i]) if (u <= n && !prv[u]) ///fake edges doesn't count\n            ++free;\n        if (prv[n+2]) --free; ///connected to last edge => not free\n        for (int j = 1; j <= free; ++j) ans = 1ll * ans * j % mod;\n        ///reset\n        for (auto u: adj[i]) nxt[u] = prv[u] = seen[u] = 0;\n    }\n\n    ///no conflicts\n    cout << ans << endl;\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dsu",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1255",
    "index": "A",
    "title": "Changing Volume",
    "statement": "Bob watches TV every day. He always sets the volume of his TV to $b$. However, today he is angry to find out someone has changed the volume to $a$. Of course, Bob has a remote control that can change the volume.\n\nThere are six buttons ($-5, -2, -1, +1, +2, +5$) on the control, which in one press can either increase or decrease the current volume by $1$, $2$, or $5$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $0$.\n\nAs Bob is so angry, he wants to change the volume to $b$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $a$ and $b$, finds the minimum number of presses to change the TV volume from $a$ to $b$.",
    "tutorial": "Notice that if at some moment we increase the volume and at some moment we decrease the volume, we can remove those two actions and replace them with at most two new actions that are both increasing or decreasing (for instance, $+5$ $-1$ can be replaced with $+2$ $+2$; $+2$ and $-2$ can be replaced with nothing and $+2$ and $-1$ can be replaced with $+1$). We can see that replacing like this will not make the volume goes below zero at any moment. So, we will increase the volume all the time, or decrease all the time. Assume that we only increase the volume. It can be proved that for any set consists of only $1$s and $2$s and the sum of its elements is greater than or equal to $5$, it has a subset which its elements sums to $5$. This means that if we use $+1$ and $+2$ to increase the volume by at least $5$, we can replace some of those actions with a $+5$. Hence, it is optimal to increase the volume by $5$ until the gap between $a$ and $b$ is less than $5$, then the remaining job is trivial.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1255",
    "index": "B",
    "title": "Fridge Lockers",
    "statement": "Hanh lives in a shared apartment. There are $n$ people (including Hanh) living there, each has a private fridge.\n\n$n$ fridges are secured by several steel chains. Each steel chain connects two \\textbf{different} fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of $n$ people can open it.\n\n\\begin{center}\n{\\small For exampe, in the picture there are $n=4$ people and $5$ chains. The first person knows passcodes of two chains: $1-4$ and $1-2$. The fridge $1$ can be open by its owner (the person $1$), also two people $2$ and $4$ (acting together) can open it.}\n\\end{center}\n\nThe weights of these fridges are $a_1, a_2, \\ldots, a_n$. To make a steel chain connecting fridges $u$ and $v$, you have to pay $a_u + a_v$ dollars. Note that the landlord allows you to create \\textbf{multiple chains connecting the same pair of fridges}.\n\nHanh's apartment landlord asks you to create exactly $m$ steel chains so that all fridges are private. A fridge is private if and only if, among $n$ people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge $i$ is not private if there exists the person $j$ ($i \\ne j$) that the person $j$ can open the fridge $i$.\n\nFor example, in the picture all the fridges are private. On the other hand, if there are $n=2$ fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).\n\nOf course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly $m$ chains, and if yes, output any solution that minimizes the total cost.",
    "tutorial": "Author: I_love_tigersugar ft. MikeMirzayanov. Prepared by UncleGrandpa We modelize the problem as graph, where each fridge is a vertex and each chain is an edge between two vertexes. The problem is now equivalent to: Given a graph with $n$ vertexes, each vertex has a value $a_i \\ge 0$. We have to add $m$ edges to the graph such that each vertex is connected to at least two different vertexes and the total cost of edges added is minimum. The cost of an edge is the sum of value of its two end-points. Now, each edge added will increase the sum of degree of all vertexes by 2. So adding m edges will make the sum of degree equal to $2 \\times m$. Since each vertexes must be connected to at least $2$ other vertexes, the minimum sum of degree is $2 \\times n$. Case 1: $2\\times m < 2\\times n \\Leftrightarrow m<n$ In this case, it is obvious that the answer is $-1$. Case 2: $2\\times m = 2\\times n \\Leftrightarrow m=n$ In this case, it is easy to see that the degree of each vertex will be exactly 2. As a result, no matter what edges we add, the result is still $2\\times (a_1+a_2+...+a_n)$. But please take note that if $n=2$, then the answer will be $-1$ since for each vertex we have at most $1$ different vertex to connect to. Case 3(Of the original, pre-modified version of the problem): $2\\times m > 2\\times n \\Leftrightarrow m>n$ Please read this excellent answer by Um_nik. All credit goes to him for the excellent proof.",
    "tags": [
      "graphs",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1255",
    "index": "C",
    "title": "League of Leesins",
    "statement": "Bob is an avid fan of the video game \"League of Leesins\", and today he celebrates as the League of Leesins World Championship comes to an end!\n\nThe tournament consisted of $n$ ($n \\ge 5$) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from $1$-st to $n$-th. After the final, he compared the prediction with the actual result and found out that the $i$-th team according to his prediction ended up at the $p_i$-th position ($1 \\le p_i \\le n$, all $p_i$ are unique). In other words, $p$ is a permutation of $1, 2, \\dots, n$.\n\nAs Bob's favorite League player is the famous \"3ga\", he decided to write down every $3$ consecutive elements of the permutation $p$. Formally, Bob created an array $q$ of $n-2$ triples, where $q_i = (p_i, p_{i+1}, p_{i+2})$ for each $1 \\le i \\le n-2$. Bob was very proud of his array, so he showed it to his friend Alice.\n\nAfter learning of Bob's array, Alice declared that she could retrieve the permutation $p$ even if Bob rearranges the elements of $q$ and the elements within each triple. Of course, Bob did not believe in such magic, so he did just the same as above to see Alice's respond.\n\nFor example, if $n = 5$ and $p = [1, 4, 2, 3, 5]$, then the original array $q$ will be $[(1, 4, 2), (4, 2, 3), (2, 3, 5)]$. Bob can then rearrange the numbers within each triple and the positions of the triples to get $[(4, 3, 2), (2, 3, 5), (4, 1, 2)]$. Note that $[(1, 4, 2), (4, 2, 2), (3, 3, 5)]$ is not a valid rearrangement of $q$, as Bob is not allowed to swap numbers belong to different triples.\n\nAs Alice's friend, you know for sure that Alice was just trying to show off, so you decided to save her some face by giving her \\textbf{any permutation} $p$ that is consistent with the array $q$ she was given.",
    "tutorial": "There will be exactly $2$ numbers that appear only once in the input and they are the first and the last element of the permutation. Let $p_1$ be any of them and start with the only triple that contains $p_1$. If $x, y$ are the other members of the mentioned triple, there exists a unique triple that contains $x, y$ but not $p_1$. We can easily find that triple by searching through every triple that contains $x$ (and there are at most $3$ such triples). By repeating doing this, we can get a list $r$ that $r_i = perm(p_i, p_{i+1}, p_{i+2})$. From $r$, we can construct a permutation that satisfies the problem. Assume we know $p_1$ and $p_2$, then we can find the rest of the permutation easily. To determine which number is $p_2$, we can use the fact $p_2$ is the only number that only appears in $r_1$ and $r_2$.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1256",
    "index": "A",
    "title": "Payment Without Change",
    "statement": "You have $a$ coins of value $n$ and $b$ coins of value $1$. You always pay in exact change, so you want to know if there exist such $x$ and $y$ that if you take $x$ ($0 \\le x \\le a$) coins of value $n$ and $y$ ($0 \\le y \\le b$) coins of value $1$, then the total value of taken coins will be $S$.\n\nYou have to answer $q$ independent test cases.",
    "tutorial": "Firstly, we obviously need to take at least $S \\% n$ coins of value $1$. If we cannot do it, the answer it NO. Otherwise we always can obtain the required sum $S$ if $a \\cdot n + b \\ge S$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint q;\n\tcin >> q;\n\n\tfor (int qr = 0; qr < q; ++qr) {\n\t\tint a, b, n, s;\n\t\tcin >> a >> b >> n >> s;\n\n\t\tif (s % n <= b && 1ll * a * n + b >= s) {\n\t\t\tcout << \"YES\\n\";\n\t\t}\n\t\telse {\n\t\t\tcout << \"NO\\n\";\n\t\t}\n\t}\n}",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1256",
    "index": "B",
    "title": "Minimize the Permutation",
    "statement": "You are given a permutation of length $n$. Recall that the permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2, 3, 1, 5, 4]$ is a permutation, but $[1, 2, 2]$ is not a permutation ($2$ appears twice in the array) and $[1, 3, 4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nYou can perform at most $n-1$ operations with the given permutation (it is possible that you don't perform any operations at all). The $i$-th operation allows you to swap elements of the given permutation on positions $i$ and $i+1$. \\textbf{Each operation can be performed at most once}. The operations can be performed in arbitrary order.\n\nYour task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.\n\nYou can see the definition of the lexicographical order in the notes section.\n\nYou have to answer $q$ independent test cases.\n\nFor example, let's consider the permutation $[5, 4, 1, 3, 2]$. The minimum possible permutation we can obtain is $[1, 5, 2, 4, 3]$ and we can do it in the following way:\n\n- perform the second operation (swap the second and the third elements) and obtain the permutation $[5, 1, 4, 3, 2]$;\n- perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $[5, 1, 4, 2, 3]$;\n- perform the third operation (swap the third and the fourth elements) and obtain the permutation $[5, 1, 2, 4, 3]$.\n- perform the first operation (swap the first and the second elements) and obtain the permutation $[1, 5, 2, 4, 3]$;\n\nAnother example is $[1, 2, 4, 3]$. The minimum possible permutation we can obtain is $[1, 2, 3, 4]$ by performing the third operation (swap the third and the fourth elements).",
    "tutorial": "The following greedy solution works: let's take the minimum element and move it to the leftmost position we can. With this algorithm, all forbidden operations are form the prefix of operations: ($1, 2$), $(2, 3)$, ..., and so on. So we can carry the position of the leftmost operation we can perform $pos$. Initially, it is $1$. We repeat the algorithm until $pos \\ge n$. Let's find the position of the minimum element among elements $a_{pos}, a_{pos + 1}, \\dots, a_{n}$. Let this position be $nxt$. If $nxt = pos$ then let's increase $pos$ and continue the algorithm. Otherwise, we need to move the element from the position $nxt$ to the position $pos$ and then set $pos := nxt$. Time complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tcin >> a[j];\n\t\t\t--a[j];\n\t\t}\n\t\tint pos = 0;\n\t\twhile (pos < n) {\n\t\t\tint nxt = min_element(a.begin() + pos, a.end()) - a.begin();\n\t\t\tint el = a[nxt];\n\t\t\ta.erase(a.begin() + nxt);\n\t\t\ta.insert(a.begin() + pos, el);\n\t\t\tif (pos == nxt) pos = nxt + 1;\n\t\t\telse pos = nxt;\n\t\t}\n\t\tfor (auto it : a) cout << it + 1 << \" \";\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1256",
    "index": "C",
    "title": "Platforms Jumping",
    "statement": "There is a river of width $n$. The left bank of the river is cell $0$ and the right bank is cell $n + 1$ (more formally, the river can be represented as a sequence of $n + 2$ cells numbered from $0$ to $n + 1$). There are also $m$ wooden platforms on a river, the $i$-th platform has length $c_i$ (so the $i$-th platform takes $c_i$ consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed $n$.\n\nYou are standing at $0$ and want to reach $n+1$ somehow. If you are standing at the position $x$, you can jump to any position in the range $[x + 1; x + d]$. \\textbf{However} you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if $d=1$, you can jump only to the next position (if it belongs to the wooden platform). \\textbf{You can assume that cells $0$ and $n+1$ belong to wooden platforms}.\n\nYou want to know if it is possible to reach $n+1$ from $0$ if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.\n\n\\textbf{Note that you should move platforms until you start jumping} (in other words, you first move the platforms and then start jumping).\n\nFor example, if $n=7$, $m=3$, $d=2$ and $c = [1, 2, 1]$, then one of the ways to reach $8$ from $0$ is follow:\n\n\\begin{center}\n{\\small The first example: $n=7$.}\n\\end{center}",
    "tutorial": "This problem has a very easy idea but requires terrible implementation. Firstly, let's place all platforms as rightmost as we can. Thus, we will have the array, in which the first $n - \\sum\\limits_{i=1}^{m} c_i$ elements are zeros and other elements are $1$, $2$, ..., $m$. Now, let's start the algorithm. Firstly, we need to jump to the position $d$ or less. If we could jump to the position $d$ then we don't need to jump to some position to the left from $d$. But if we cannot do it, let's take the leftmost platform to the right from the position $d$ and move it in such a way that its left border will be at the position $d$. Now we can jump to the position $d$ and then jump by $1$ right to reach the position $d + c_1 - 1$. Let's repeat the same algorithm and continue jumping. If after some move we can jump to the position at least $n+1$ then we are done. Time complexity: $O(n^2)$ but I'm sure it can be implemented in $O(n \\log n)$ or $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m, d;\n\tcin >> n >> m >> d;\n\tvector<int> c(m);\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> c[i];\n\t}\n\t\n\tvector<int> ans(n + 2);\n\tfor (int i = m - 1, pos = n; i >= 0; --i) {\n\t\tfor (int len = 0; len < c[i]; ++len) {\n\t\t\tans[pos - len] = i + 1;\n\t\t}\n\t\tpos -= c[i];\n\t}\n\t\n\tint now = 0;\n\twhile (true) {\n\t\twhile (now + 1 < n + 1 && ans[now + 1] > 0) ++now;\n\t\tif (now + d >= n + 1) break;\n\t\tif (ans[now + d] == 0) {\n\t\t\tint lpos = -1;\n\t\t\tfor (int i = now + d; i < n + 2; ++i) {\n\t\t\t\tif (ans[i] != 0) {\n\t\t\t\t\tlpos = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (lpos == -1) {\n\t\t\t\tcout << \"NO\" << endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tint rpos = -1;\n\t\t\tfor (int i = lpos; i < n + 2; ++i) {\n\t\t\t\tif (ans[i] == ans[lpos]) rpos = i;\n\t\t\t}\n\t\t\twhile (ans[now + d] == 0) {\n\t\t\t\tswap(ans[lpos - 1], ans[rpos]);\n\t\t\t\t--lpos, --rpos;\n\t\t\t}\n\t\t}\n\t\tnow += d;\n\t}\n\t\n\tcout << \"YES\" << endl;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tcout << ans[i] << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1256",
    "index": "D",
    "title": "Binary String Minimizing",
    "statement": "You are given a binary string of length $n$ (i. e. a string consisting of $n$ characters '0' and '1').\n\nIn one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform \\textbf{no more} than $k$ moves? It is possible that you do not perform any moves at all.\n\nNote that you can swap the same pair of adjacent characters with indices $i$ and $i+1$ arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.\n\nYou have to answer $q$ independent test cases.",
    "tutorial": "This problem has a very standard solution: let's take the leftmost zero, place it as left as possible, and solve the problem without this zero and all operations we spent. But we should do it fast. Let's go from left to right and carry the number of ones on the prefix $cnt$. If we meet $1$, let's just increase $cnt$ and continue the algorithm. It is obvious that if we meet $0$ we need to make exactly $cnt$ swaps to place it before all ones. If we can do it, let's just add $0$ to the answer, decrease $k$ by $cnt$ and continue. Otherwise, this zero will be between some of these $cnt$ ones and we can place it naively. In this case, the suffix of the string will not change. If after all operations we didn't meet the case above, let's add all ones to the suffix of the resulting string. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tint n;\n\t\tlong long k;\n\t\tstring s;\n\t\tcin >> n >> k >> s;\n\t\tstring res;\n\t\tint cnt = 0;\n\t\tbool printed = false;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (s[i] == '0') {\n\t\t\t\tif (cnt <= k) {\n\t\t\t\t\tres += '0';\n\t\t\t\t\tk -= cnt;\n\t\t\t\t} else {\n\t\t\t\t\tres += string(cnt - k, '1');\n\t\t\t\t\tres += '0';\n\t\t\t\t\tres += string(k, '1');\n\t\t\t\t\tres += s.substr(i + 1);\n\t\t\t\t\tcout << res << endl;\n\t\t\t\t\tprinted = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t++cnt;\n\t\t\t}\n\t\t}\n\t\n\t\tif (!printed) {\n\t\t\tres += string(cnt, '1');\n\t\t\tcout << res << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1256",
    "index": "E",
    "title": "Yet Another Division Into Teams",
    "statement": "There are $n$ students at your university. The programming skill of the $i$-th student is $a_i$. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has $2 \\cdot 10^5$ students ready for the finals!\n\nEach team should consist of \\textbf{at least three students}. Each student should belong to \\textbf{exactly one team}. The diversity of a team is the difference between the \\textbf{maximum} programming skill of some student that belongs to this team and the \\textbf{minimum} programming skill of some student that belongs to this team (in other words, if the team consists of $k$ students with programming skills $a[i_1], a[i_2], \\dots, a[i_k]$, then the diversity of this team is $\\max\\limits_{j=1}^{k} a[i_j] - \\min\\limits_{j=1}^{k} a[i_j]$).\n\nThe total diversity is the sum of diversities of all teams formed.\n\nYour task is to minimize the total diversity of the division of students and find the optimal way to divide the students.",
    "tutorial": "Let's sort all students by their programming skills but save the initial indices to restore the answer. Now we can understand that we don't need to compose the team of size greater than $5$ because in this case we can split it into more teams with fewer participants and obtain the same or even less answer. Now we can do the standard dynamic programming $dp_{i}$ - the minimum total diversity of the division if we divided the first $i$ students (in sorted order). Initially, $dp_{0} = 0$, all other values of $dp$ are $+\\infty$. Because of the fact above, we can do only three transitions ($0$-indexed): $dp_{i + 3} = min(dp_{i + 3}, dp_{i} + a_{i + 2} - a_{i})$; $dp_{i + 4} = min(dp_{i + 4}, dp_{i} + a_{i + 3} - a_{i})$; $dp_{i + 5} = min(dp_{i + 5}, dp_{i} + a_{i + 4} - a_{i})$. The answer is $dp_{n}$ and we can restore it by standard carrying parent values (as a parent of the state we can use, for example, the number of participants in the team).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pt;\n\n#define x first\n#define y second\n#define mp make_pair\n\nconst int N = 200043;\nconst int INF = int(1e9) + 43;\n\nint n;\nint dp[N];\nint p[N];\npt a[N];\nint t[N];\n\nint main() {\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++)\n    {\n    \ta[i].y = i;\n    \tscanf(\"%d\", &a[i].x);\n    }\n    sort(a, a + n);\n    for(int i = 1; i <= n; i++)\n    {\n    \tdp[i] = INF;\n    \tp[i] = -1;\n    }\n    for(int i = 0; i < n; i++)\n    \tfor(int j = 3; j <= 5 && i + j <= n; j++)\n    \t{\n    \t\tint diff = a[i + j - 1].x - a[i].x;\n    \t\tif(dp[i + j] > dp[i] + diff)\n    \t\t{\n    \t\t\tp[i + j] = i;\n    \t\t\tdp[i + j] = dp[i] + diff;\n    \t\t}\n    \t}\n    int cur = n;\n    int cnt = 0;\n    while(cur != 0)\n    {\n    \tfor(int i = cur - 1; i >= p[cur]; i--)\n    \t\tt[a[i].y] = cnt;\n    \tcnt++;\n    \tcur = p[cur]; \n    }\n    printf(\"%d %d\\n\", dp[n], cnt);\n    for(int i = 0; i < n; i++)\n    {\n    \tif(i) printf(\" \");\n    \tprintf(\"%d\", t[i] + 1); \n    }\n    puts(\"\");\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1256",
    "index": "F",
    "title": "Equalizing Two Strings",
    "statement": "You are given two strings $s$ and $t$ both of length $n$ and both consisting of lowercase Latin letters.\n\nIn one move, you can choose any length $len$ from $1$ to $n$ and perform the following operation:\n\n- Choose any contiguous substring of the string $s$ of length $len$ and reverse it;\n- \\textbf{at the same time} choose any contiguous substring of the string $t$ of length $len$ and reverse it as well.\n\nNote that during one move you reverse \\textbf{exactly one} substring of the string $s$ and \\textbf{exactly one} substring of the string $t$.\n\nAlso note that borders of substrings you reverse in $s$ and in $t$ \\textbf{can be different}, the only restriction is that you reverse the substrings of equal length. For example, if $len=3$ and $n=5$, you can reverse $s[1 \\dots 3]$ and $t[3 \\dots 5]$, $s[2 \\dots 4]$ and $t[2 \\dots 4]$, but not $s[1 \\dots 3]$ and $t[1 \\dots 2]$.\n\nYour task is to say if it is possible to make strings $s$ and $t$ equal after some (possibly, empty) sequence of moves.\n\nYou have to answer $q$ independent test cases.",
    "tutorial": "The necessary condition to make strings equal is that the number of occurrences of each character should be the same in both strings. Let's show that if some character appears more than once, we always can make strings equal. How? Let's sort the first string by swapping adjacent characters (and it does not matter what do we do in the second string). Then let's sort the second string also by swapping adjacent characters but choose the pair of adjacent equal characters in the first string (it always exists because the first string is already sorted). Otherwise, all characters in both strings are distinct and they lengths are at most $26$. Then the answer is YES if the parity of the number of inversions (the number inversions in the array $a$ is the number of such pairs of indices $i, j$ that $i < j$ but $a_i > a_j$) are the same. It can be proven in the following way: every swap of two adjacent elements changes the parity of the number of inversions. Time complexity: $O(max(n, AL^2))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tstring s, t;\n\t\tcin >> n >> s >> t;\n\t\tvector<int> cnts(26), cntt(26);\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t++cnts[s[j] - 'a'];\n\t\t\t++cntt[t[j] - 'a'];\n\t\t}\n\t\tbool ok = true;\n\t\tbool good = false;\n\t\tfor (int j = 0; j < 26; ++j) {\n\t\t\tok &= cnts[j] == cntt[j];\n\t\t\tgood |= cnts[j] > 1;\n\t\t}\n\t\tif (!ok) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tif (good) {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tint invs = 0, invt = 0;\n\t\tfor (int l = 0; l < n; ++l) {\n\t\t\tfor (int r = 0; r < l; ++r) {\n\t\t\t\tinvs += s[l] > s[r];\n\t\t\t\tinvt += t[l] > t[r];\n\t\t\t}\n\t\t}\n\t\tok &= (invs & 1) == (invt & 1);\n\t\tif (ok) cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "sortings",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1257",
    "index": "A",
    "title": "Two Rival Students",
    "statement": "You are the gym teacher in the school.\n\nThere are $n$ students in the row. And there are two rivalling students among them. The first one is in position $a$, the second in position $b$. Positions are numbered from $1$ to $n$ from left to right.\n\nSince they are rivals, you want to maximize the distance between them. If students are in positions $p$ and $s$ respectively, then distance between them is $|p - s|$.\n\nYou can do the following operation at most $x$ times: choose two \\textbf{adjacent (neighbouring)} students and swap them.\n\nCalculate the maximum distance between two rivalling students after at most $x$ swaps.",
    "tutorial": "To solve the problem you need to understand two facts: The answer can't be greater than $n - 1$; If current distance between rivaling student if less then $n-1$ we always can increment this distance by one swap; In means that answer is equal to $\\min (n - 1, |a - b| + x)$.",
    "code": "import kotlin.math.abs\nfun main() {\n    val q = readLine()!!.toInt()\n    for (ct in 1..q) {\n        val (n, x, a, b) = readLine()!!.split(' ').map { it.toInt() }\n        println(minOf(n - 1, abs(a - b) + x))\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1257",
    "index": "B",
    "title": "Magic Stick",
    "statement": "Recently Petya walked in the forest and found a magic stick.\n\nSince Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a \\textbf{positive} integer:\n\n- If the chosen number $a$ is even, then the spell will turn it into $\\frac{3a}{2}$;\n- If the chosen number $a$ is greater than one, then the spell will turn it into $a-1$.\n\nNote that if the number is even and greater than one, then Petya can choose which spell to apply.\n\nPetya now has only one number $x$. He wants to know if his favorite number $y$ can be obtained from $x$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $x$ as it is.",
    "tutorial": "$1$ cannot be transformed into any other number. $2$ can be transformed into $3$ or $1$, and $3$ can be transformed only into $2$. It means that if $x = 1$, then only $y = 1$ is reachable; and if $x = 2$ or $x = 3$, then $y$ should be less than $4$. Otherwise, we can make $x$ as large as we want, so if $x > 3$, any $y$ is reachable.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tint x, y;\n\tcin >> x >> y;\n\t\n\tif (x > 3) puts(\"YES\");\n\telse if (x == 1) puts(y == 1 ? \"YES\" : \"NO\");\n\telse puts(y <= 3 ? \"YES\" : \"NO\");\n}\n\nint main() {\n\tint tc;\n\tcin >> tc;\n\twhile (tc--) solve();\n}",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1257",
    "index": "C",
    "title": "Dominated Subarray",
    "statement": "Let's call an array $t$ dominated by value $v$ in the next situation.\n\nAt first, array $t$ should have at least $2$ elements. Now, let's calculate number of occurrences of each number $num$ in $t$ and define it as $occ(num)$. Then $t$ is dominated (by $v$) if (and only if) $occ(v) > occ(v')$ for any other number $v'$. For example, arrays $[1, 2, 3, 4, 5, 2]$, $[11, 11]$ and $[3, 2, 3, 2, 3]$ are dominated (by $2$, $11$ and $3$ respectevitely) but arrays $[3]$, $[1, 2]$ and $[3, 3, 2, 2, 1]$ are not.\n\nSmall remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.\n\nYou are given array $a_1, a_2, \\dots, a_n$. Calculate its shortest dominated subarray or say that there are no such subarrays.\n\nThe subarray of $a$ is a contiguous part of the array $a$, i. e. the array $a_i, a_{i + 1}, \\dots, a_j$ for some $1 \\le i \\le j \\le n$.",
    "tutorial": "At first, let's prove that the shortest dominated subarray has pattern like $v, c_1, c_2, \\dots, c_k, v$ with $k \\ge 0$ and dominated by value $v$. Otherwise, we can decrease its length by erasing an element from one of its ends which isn't equal to $v$ and it'd still be dominated. Now we should go over all pairs of the same numbers and check its subarrays... Or not? Let's look closely at the pattern: if $v$ and all $c_i$ are pairwise distinct then the pattern is dominated subarray itself. Otherwise, we can find in our pattern other shorter pattern and either the found pattern is dominated or it has the pattern inside it and so on. What does it mean? It means that the answer is just the shortest pattern we can find. And all we need to find is the shortest subarray with the same first and last elements or just distance between two consecutive occurrences of each number. We can do it by iterating over current position $i$ and keeping track of the last occurrence of each number in some array $lst[v]$. Then the current distance is $i - lst[a[i]] + 1$. The total complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define sz(a) int((a).size())\n\nint n;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tfor(int i = 0; i < n; i++)\n\t\tcin >> a[i];\n\treturn true;\n}\n\ninline void solve() {\n\tint ans = n + 5;\n\tvector<int> lst(n + 1, -1);\n\tfor(int i = 0; i < n; i++) {\n\t\tif(lst[a[i]] != -1)\n\t\t\tans = min(ans, i - lst[a[i]] + 1);\n\t\tlst[a[i]] = i;\n\t}\n\tif(ans > n)\n\t\tans = -1;\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\twhile(tc--) {\n\t\tassert(read());\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings",
      "strings",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1257",
    "index": "D",
    "title": "Yet Another Monster Killing Problem",
    "statement": "You play a computer game. In this game, you lead a party of $m$ heroes, and you have to clear a dungeon with $n$ monsters. Each monster is characterized by its power $a_i$. Each hero is characterized by his power $p_i$ and endurance $s_i$.\n\nThe heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day.\n\nWhen the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated $k$ monsters, the hero fights with the monster $k + 1$). When the hero fights the monster, there are two possible outcomes:\n\n- if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends;\n- otherwise, the monster is defeated.\n\nAfter defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the $i$-th hero cannot defeat more than $s_i$ monsters during each day), or if all monsters are defeated — otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends.\n\nYour goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.",
    "tutorial": "At first, lets precalc array $bst$; $bst_i$ is equal to maximum hero power whose endurance is greater than or equal to $i$. Now let's notice that every day it's profitable for as to kill as many monster as possible. Remains to understand how to calculate it. Suppose that we already killed $cnt$ monsters. If $a_{cnt+1} > bst_1$ then answer is -1, because we can't kill the $cnt+1$-th monster. Otherwise we can kill at least $x = 1$ monsters. All we have to do it increase the value $x$ until conditions $\\max\\limits_{cnt < i \\le cnt + x} a_i \\le bst_x$ holds. After calculating the value $x$ we just move to the next day with $cnt + x$ killed monsters.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(2e5) + 99;\n\nint t;\nint n;\nint a[N];\nint m;\nint p[N], s[N];\nint bst[N];\n\nint main() {\t\n\tscanf(\"%d\", &t);\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tscanf(\"%d\", &n);\n\t\tfor(int i = 0; i <= n; ++i) bst[i] = 0;\n\t\tfor(int i = 0; i < n; ++i)\n\t\t\tscanf(\"%d\", a + i);\n\t\tscanf(\"%d\", &m);\n\t\tfor(int i = 0; i < m; ++i){\n\t\t\tscanf(\"%d %d\", p + i, s + i);\n\t\t\tbst[s[i]] = max(bst[s[i]], p[i]);\n\t\t}\n\t\tfor(int i = n - 1; i >= 0; --i)\n\t\t\tbst[i] = max(bst[i], bst[i + 1]);\t\n\t\t\n\n\t\tint pos = 0;\n\t\tint res = 0;\n\t\tbool ok = true;\n\t\twhile(pos < n){\n\t\t\t++res;\n\t\t\tint npos = pos;\n\t\t\tint mx = 0;\n\t\t\twhile(true){\n\t\t\t\tmx = max(mx, a[npos]);\n\t\t\t\tif(mx > bst[npos - pos + 1]) break;\n\t\t\t\t++npos;\n\t\t\t}\n\t\n\t\t\tif(pos == npos){\n\t\t\t\tok = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpos = npos;\n\t\t}\n\n\t\tif(!ok) res = -1;\n\t\tprintf(\"%d\\n\", res);\n\t}\n\n\treturn 0;\n}                             \t            \t",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1257",
    "index": "E",
    "title": "The Contest",
    "statement": "A team of three programmers is going to play a contest. The contest consists of $n$ problems, numbered from $1$ to $n$. Each problem is printed on a separate sheet of paper. The participants have decided to divide the problem statements into three parts: the first programmer took some prefix of the statements (some number of first paper sheets), the third contestant took some suffix of the statements (some number of last paper sheets), and the second contestant took all remaining problems. But something went wrong — the statements were printed in the wrong order, so the contestants have received the problems in some random order.\n\nThe first contestant has received problems $a_{1, 1}, a_{1, 2}, \\dots, a_{1, k_1}$. The second one has received problems $a_{2, 1}, a_{2, 2}, \\dots, a_{2, k_2}$. The third one has received all remaining problems ($a_{3, 1}, a_{3, 2}, \\dots, a_{3, k_3}$).\n\nThe contestants don't want to play the contest before they redistribute the statements. They want to redistribute them so that the first contestant receives some prefix of the problemset, the third contestant receives some suffix of the problemset, and the second contestant receives all the remaining problems.\n\nDuring one move, some contestant may give one of their problems to other contestant. What is the minimum number of moves required to redistribute the problems?\n\n\\textbf{It is possible that after redistribution some participant (or even two of them) will not have any problems}.",
    "tutorial": "Suppose we want to divide $r$ first problems of the contest between the first contestant and the second contestant (the first contestant will get $l$ first problems, and the second contestant will get $r - l$ problems in the middle), and then give all the remaining problems to the third contestant. We are going to iterate on $r$ from $0$ to $n$ and, for each possible $r$, find the best value of $l$. Okay. Now suppose we fixed $l$ and $r$, and now we want to calculate the number of problems that should be redistributed. Let's denote $cnt_{l, i}$ as the number of problems among $l$ first ones given to the $i$-th contestant, $cnt_{r, i}$ as the number of problems among $r$ last ones given to the $i$-th contestant, and $cnt_{m, i}$ as the number of problems in the middle given to the $i$-th contestant. Obviously, the answer for fixed $l$ and $r$ is $cnt_{l, 2} + cnt_{l, 3} + cnt_{m, 1} + cnt_{m, 3} + cnt_{r, 1} + cnt_{r, 2}$, but we don't like this expression because we don't know how to minimize it for fixed $r$. We know that, for fixed $r$, the values of $cnt_{l, i} + cnt_{m, i}$ and $cnt_{r, i}$ are constant. Using that, we may arrive at the fact that minimizing $cnt_{l, 2} + cnt_{l, 3} + cnt_{m, 1} + cnt_{m, 3} + cnt_{r, 1} + cnt_{r, 2}$ is the same as minimizing $cnt_{l, 2} - cnt_{l, 1}$ for fixed $r$ - and now we have a way to quickly find best possible $l$ for fixed $r$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() \n{\n\tint k1, k2, k3;\n\tscanf(\"%d %d %d\", &k1, &k2, &k3);\n\tint n = k1 + k2 + k3;\n\tvector<int> a(n);\n\tfor(int i = 0; i < k1; i++)\n\t{\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\ta[x - 1] = 0;\n\t}\n\tfor(int i = 0; i < k2; i++)\n\t{\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\ta[x - 1] = 1;\n\t}\n\tfor(int i = 0; i < k3; i++)\n\t{\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\ta[x - 1] = 2;\n\t}\n\t\n\tint ans = 0;\n\tint bestp = 0;\n\tfor(int i = 0; i < n; i++)\n\t\tif(a[i] != 2)\n\t\t\tans++;\n\tvector<int> cntl(3);\n\tvector<int> cntr(3);\n\tfor(int i = 0; i < n; i++)\n\t\tcntr[a[i]]++;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tcntl[a[i]]++;\n\t\tcntr[a[i]]--;\n\t\tbestp = max(bestp, cntl[0] - cntl[1]);\n\t\tint curans = cntr[0] + cntr[1] + cntl[2] + cntl[0] - bestp;\n\t\tans = min(ans, curans);\n\t}\n\t\n\tcout << ans << endl;\n}                    \t",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1257",
    "index": "F",
    "title": "Make Them Similar",
    "statement": "Let's call two numbers similar if their binary representations contain the same number of digits equal to $1$. For example:\n\n- $2$ and $4$ are similar (binary representations are $10$ and $100$);\n- $1337$ and $4213$ are similar (binary representations are $10100111001$ and $1000001110101$);\n- $3$ and $2$ are not similar (binary representations are $11$ and $10$);\n- $42$ and $13$ are similar (binary representations are $101010$ and $1101$).\n\nYou are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$. You may choose a non-negative integer $x$, and then get another array of $n$ integers $b_1$, $b_2$, ..., $b_n$, where $b_i = a_i \\oplus x$ ($\\oplus$ denotes bitwise XOR).\n\nIs it possible to obtain an array $b$ where all numbers are similar to each other?",
    "tutorial": "Iterating over all possible values of $x$ and checking them may be too slow (though heavily optimized brute force is difficult to eliminate in this problem), so we need to speed this approach up. The resulting number consists of $30$ bits. Let's use the classical meet-in-the-middle trick: try all $2^{15}$ combinations of $15$ lowest bits, try all $2^{15}$ combinations of $15$ highest bits, and somehow \"merge\" the results. When we fix a combination of $15$ lowest bits, we fix $15$ lowest bits in every $b_i$. Suppose that there are $cnt_{0, i}$ ones among $15$ lowest bits of $b_i$. Analogically, when we fix a combination of $15$ highest bits, we fix $15$ highest bits in every $b_i$. Suppose that there are $cnt_{1, i}$ ones among $15$ highest bits of $b_i$. We want to find a combination of lowest and highest bits such that $cnt_{0, i} + cnt_{1, i}$ is the same for each $i$. Let's represent each combination of $15$ lowest bits with an $(n-1)$-dimensional vector with coordinates $(cnt_{0, 1} - cnt_{0, 2}, cnt_{0, 1} - cnt_{0, 3}, \\dots, cnt_{0, 1} - cnt_{0, n})$. Let's also represent each combination of $15$ highest bits with an $(n-1)$-dimensional vector with coordinates $(cnt_{1, 1} - cnt_{1, 2}, cnt_{1, 1} - cnt_{1, 3}, \\dots, cnt_{1, 1} - cnt_{1, n})$. We want to find a combination of lowest bits and a combination of highest bits such that their vectors are opposite. We can do so, for example, by precalculating all vectors for all combinations of $15$ lowest bits, storing them in a map or a trie, iterating on a combination of $15$ highest bits and searching for the opposite vector in the map/trie.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\nconst int N = 143;\nconst int K = 15;\nconst int V = 5000000;\n\nint n;\nli a[N];\nint lst[V];\nmap<int, int> nxt[V];\nint t = 1;\nli a1[N];\nli a2[N];\n\nint get_nxt(int v, int x)\n{\n\tif(!nxt[v].count(x))\n\t\tnxt[v][x] = t++;\n\treturn nxt[v][x];\n}\n\nvoid add(vector<int> diff, int x)\n{\n\tint v = 0;\n\tfor(auto i : diff)\n\t\tv = get_nxt(v, i);\n\tlst[v] = x;\n}\n\nint try_find(vector<int> diff)\n{\n\tint v = 0;\n\tfor(auto i : diff)\n\t{\n\t\tif(!nxt[v].count(i))\n\t\t\treturn -1;\n\t\tv = nxt[v][i];\n\t}\n\treturn lst[v];\n}\n\nvector<int> get_diff(li arr[N], int x)\n{\n\tvector<int> cnt(n);\n\tfor(int i = 0; i < n; i++)\n\t\tcnt[i] = __builtin_popcountll(arr[i] ^ x);\n\tvector<int> diff(n - 1);\n\tfor(int i = 0; i + 1 < n; i++)\n\t\tdiff[i] = cnt[i + 1] - cnt[0];\n\treturn diff;\n}\n\nint main()\n{\n\tcin >> n;\n\tfor(int i = 0; i < n; i++)\n\t\tcin >> a[i];\n\t\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\ta1[i] = (a[i] >> K);\n\t\ta2[i] = a[i] ^ (a1[i] << K);\n\t}\n\tfor(int i = 0; i < (1 << K); i++)\n\t{\n\t\tvector<int> d = get_diff(a1, i);\n\t\tadd(d, i);\n\t}\n\tfor(int i = 0; i < (1 << K); i++)\n\t{\n\t\tvector<int> d = get_diff(a2, i);\n\t\tfor(int j = 0; j + 1 < n; j++)\n\t\t\td[j] *= -1;\n\t\tint x = try_find(d);\n\t\tif(x != -1)\n\t\t{\n\t\t\tli res = (li(x) << K) ^ i;\n\t\t\tcout << res << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\tcout << -1 << endl;\n\treturn 0;\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "hashing",
      "meet-in-the-middle"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1257",
    "index": "G",
    "title": "Divisor Set",
    "statement": "You are given an integer $x$ represented as a product of $n$ its prime divisors $p_1 \\cdot p_2, \\cdot \\ldots \\cdot p_n$. Let $S$ be the set of all positive integer divisors of $x$ (including $1$ and $x$ itself).\n\nWe call a set of integers $D$ good if (and only if) there is no pair $a \\in D$, $b \\in D$ such that $a \\ne b$ and $a$ divides $b$.\n\nFind a good subset of $S$ with maximum possible size. Since the answer can be large, print the size of the subset modulo $998244353$.",
    "tutorial": "The problem consists of two parts: what do we want to calculate and how to calculate it? What do we want to calculate? There are several ways to figure it out. At first, you could have met this problem before and all you need is to remember a solution. At second, you can come up with the solution in a purely theoretical way - Hasse diagram can help with it greatly. Let's define $deg(x)$ as the number of primes in prime factorization of $x$. For example, $deg(2 \\cdot 3 \\cdot 2) = 3$ and $deg(1) = 0$. If you look at Hasse diagram of $p_1 \\cdot \\ldots \\cdot p_n$ you can see that all divisors with $deg(d) = i$ lies on level $i$. If $x$ is divisible by $y$ then $deg(x) > deg(y)$ so all divisors on the same level don't divide each other. Moreover, the diagram somehow symmetrical about its middle level and sizes of levels are increasing while moving to the middle. It gives us an idea that the answer is the size of the middle level, i.e. the number of divisors with $deg(d) = \\frac{n}{2}$. The final way is just to brute force the answers for small $x$-s and find the sequence in OEIS with name A096825, where the needed formulas are described. The second step is to calculate the number of divisors with $deg(d) = \\frac{n}{2}$. Suppose we have $m$ distinct primes $p_j$ and the number of occurences of $p_j$ is equal to $cnt_j$. Then we need to calculate pretty standard knapsack problem where you need to calculate number of ways to choose subset of size $\\frac{n}{2}$ where you can take each $p_j$ up to $cnt_j$ times. Or, formally, number of vectors $(x_1, x_2, \\dots x_m)$ with $\\sum\\limits_{j = 0}^{j = m}{x_j} = \\frac{n}{2}$ and $0 \\le x_j \\le cnt_j$. Calculating the answer using $dp[pos][sum]$ will lead to time limit, so we need to make the following transformation. Let's build for each $p_j$ a polynomial $f_j(x) = 1 + x + x^2 + \\dots + x^{cnt_j}$. Now the answer is just a coefficient before $x^{\\frac{n}{2}}$ in product $f_1(x) \\cdot f_2(x) \\cdot \\ldots \\cdot f_m(x)$. Note, that the product has degree $n$, so we can multiply polynomials efficiently with integer FFT in the special order to acquire $O(n \\log^2(n))$ time complexity. There several ways to choose the order of multiplications. At first, you can, at each step, choose two polynomials with the lowest degree and multiply them. At second, you can use the divide-and-conquer technique by dividing the current segment in two with pretty same total degrees. At third, you can also use D-n-C but divide the segment at halves and, it seems still to be $O(n \\log^2(n))$ in total. What about the proof of the solution? Thanks to tyrion__ for the link at the article: https://pure.tue.nl/ws/files/4373475/597494.pdf. The result complexity is $O(n \\log^2(n))$ time and $O(n)$ space (if carefully written). Note, that the hidden constant in integer FFT is pretty high and highly depends on the implementation, so it's possible for poor implementations not to pass the time limit.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nconst int LOGN = 18;\nconst int MOD = 998244353;\nint g = 3;\n\nint mul(int a, int b) {\n\treturn int(a * 1ll * b % MOD);\n}\nint norm(int a) {\n\twhile(a >= MOD) a -= MOD;\n\twhile(a < 0) a += MOD;\n\treturn a;\n}\nint binPow (int a, int k) {\n\tint ans = 1;\n\tfor (; k > 0; k >>= 1) {\n\t\tif (k & 1)\n\t\t\tans = mul(ans, a);\n\t\ta = mul(a, a);\n\t}\n\treturn ans;\n}\nint inv(int a) {\n\treturn binPow(a, MOD - 2);\n}\n\nvector<int> w[LOGN], rv;\nbool precalced = false;\n\nvoid precalc() {\n\tif(precalced)\n\t\treturn;\n\tprecalced = true;\n\t\n    int wb = binPow(g, (MOD - 1) / (1 << LOGN));\n    fore(st, 0, LOGN) {\n        w[st].assign(1 << st, 1);\n\n        int bw = binPow(wb, 1 << (LOGN - st - 1));\n        int cw = 1;\n\n        fore(k, 0, (1 << st)) {\n            w[st][k] = cw;\n            cw = mul(cw, bw);\n        }\n    }\n    \n    rv.assign(1 << LOGN, 0);\n    fore(i, 1, sz(rv))\n\t\trv[i] = (rv[i >> 1] >> 1) | ((i & 1) << (LOGN - 1));\n}\n\nconst int MX = (1 << LOGN) + 3;\n\ninline void fft(int a[MX], int n, bool inverse) {\n\tprecalc();\n\t\n    int ln = __builtin_ctz(n);\n    assert((1 << ln) < MX);\n    assert((1 << ln) == n);\n\n    fore(i, 0, n) {\n        int ni = rv[i] >> (LOGN - ln);\n        if(i < ni) swap(a[i], a[ni]);\n    }\n\n    for(int st = 0; (1 << st) < n; st++) {\n        int len = (1 << st);\n        for(int k = 0; k < n; k += (len << 1)) {\n        \tfore(pos, k, k + len) {\n                int l = a[pos];\n                int r = mul(a[pos + len], w[st][pos - k]);\n\n                a[pos] = norm(l + r);\n                a[pos + len] = norm(l - r);\n            }\n        }\n    }\n    \n    if(inverse) {\n        int in = inv(n);\n        fore(i, 0, n)\n            a[i] = mul(a[i], in);\n        reverse(a + 1, a + n);\n    }\n}\n\nint aa[MX], bb[MX], cc[MX];\n\nvector<int> multiply(const vector<int> &a, const vector<int> &b) {\n\tint ln = 1;\n\twhile(ln < (sz(a) + sz(b)))\n\t\tln <<= 1;\n\t\n\tfore(i, 0, ln)\n\t\taa[i] = (i < sz(a) ? a[i] : 0);\n\tfore(i, 0, ln)\n\t\tbb[i] = (i < sz(b) ? b[i] : 0);\n\t\t\n\tfft(aa, ln, false);\n\tfft(bb, ln, false);\n\t\n\tfore(i, 0, ln)\n\t\tcc[i] = mul(aa[i], bb[i]);\n\tfft(cc, ln, true);\n\t\n\tvector<int> ans(cc, cc + ln);\n\twhile(ans.back() == 0)\n\t\tans.pop_back();\n\treturn ans;\n}\n\nint n;\nvector<int> ps;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\tps.resize(n);\n\tfore(i, 0, n)\n\t\tcin >> ps[i];\n\treturn true;\n}\n\nstruct cmp {\n\tbool operator ()(const vector<int> &a, const vector<int> &b) {\n\t\treturn sz(a) < sz(b);\n\t}\n};\n\ninline void solve() {\n\tmap<int, int> cnt;\n\tfore (i, 0, n)\n\t\tcnt[ps[i]]++;\n\t\n\tmultiset< vector<int>, cmp > polys;\n\tfor (auto p : cnt)\n\t\tpolys.emplace(p.second + 1, 1);\n\t\n\twhile (sz(polys) > 1) {\n\t\tauto it2 = polys.begin();\n\t\tauto it1 = it2++;\n\t\tpolys.insert(multiply(*it1, *it2));\n\t\t\n\t\tpolys.erase(it1);\n\t\tpolys.erase(it2);\n\t}\n\n\tauto poly = *polys.begin();\n//\tcerr << '[';\n//\tfore(i, 0, sz(poly)) {\n//\t\tif(i) cerr << \", \";\n//\t\tcerr << poly[i];\n//\t}\n//\tcerr << ']' << endl;\n\n\tcout << poly[n / 2] << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "divide and conquer",
      "fft",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1260",
    "index": "A",
    "title": "Heating",
    "statement": "Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.\n\nYour house has $n$ rooms. In the $i$-th room you can install at most $c_i$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $k$ sections is equal to $k^2$ burles.\n\nSince rooms can have different sizes, you calculated that you need at least $sum_i$ sections in total in the $i$-th room.\n\nFor each room calculate the minimum cost to install at most $c_i$ radiators with total number of sections not less than $sum_i$.",
    "tutorial": "Let's denote the number of sections in the $i$-th radiator as $x_i$. Let's prove that in the optimal answer $\\max(x_i) - \\min(x_i) < 2$. Proof by contradiction: suppose we have $x$ and $y \\ge x + 2$ in the answer, let's move $1$ from $y$ to $x$ and check: $(x + 1)^2 + (y - 1)^2 = x^2 + 2x + 1 + y^2 - 2y + 1 = (x^2 + y^2) + 2(x - y + 1) < x^2 + y^2$ Finally, there is the only way to take $x_1 + x_2 + \\dots + x_c = sum$ with $\\max(x_i) - \\min(x_i) \\le 1$. And it's to take $(sum \\mod c)$ elements with value $\\left\\lfloor \\frac{sum}{c} \\right\\rfloor + 1$ and $c - (sum \\mod c)$ elements with $\\left\\lfloor \\frac{sum}{c} \\right\\rfloor$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint c, sum;\n\ninline bool read() {\n\tif(!(cin >> c >> sum))\n\t\treturn false;\n\treturn true;\n}\n\ninline void solve() {\n\tint d = sum / c;\n\tint rem = sum % c;\n\tcout << rem * (d + 1) * (d + 1) + (c - rem) * d * d << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tint n; cin >> n;\n\twhile(n--) {\n\t\tread();\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1260",
    "index": "B",
    "title": "Obtain Two Zeroes",
    "statement": "You are given two integers $a$ and $b$. You may perform any number of operations on them (possibly zero).\n\nDuring each operation you should choose any positive integer $x$ and set $a := a - x$, $b := b - 2x$ or $a := a - 2x$, $b := b - x$. Note that you may choose different values of $x$ in different operations.\n\nIs it possible to make $a$ and $b$ equal to $0$ simultaneously?\n\nYour program should answer $t$ independent test cases.",
    "tutorial": "Let's assume $a \\le b$. Then the answer is YES if two following conditions holds: $(a+b) \\equiv 0 \\mod 3$, because after each operation the value $(a+b) \\mod 3$ does not change; $a \\cdot 2 \\ge b$.",
    "code": "for t in range(int(input())):\n\ta, b = map(int, input().split())\n\tif a > b:\n\t\ta, b = b, a\n\tprint ('YES' if ( ((a + b) % 3) == 0 and a * 2 >= b) else 'NO')",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1260",
    "index": "C",
    "title": "Infinite Fence",
    "statement": "You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.\n\nYou must paint a fence which consists of $10^{100}$ planks in two colors in the following way (suppose planks are numbered from left to right from $0$):\n\n- if the index of the plank is divisible by $r$ (such planks have indices $0$, $r$, $2r$ and so on) then you must paint it red;\n- if the index of the plank is divisible by $b$ (such planks have indices $0$, $b$, $2b$ and so on) then you must paint it blue;\n- if the index is divisible both by $r$ and $b$ \\textbf{you can choose the color} to paint the plank;\n- otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it).\n\nFurthermore, the Government added one additional restriction to make your punishment worse. Let's list all \\textbf{painted} planks of the fence in ascending order: if there are $k$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.\n\nThe question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.",
    "tutorial": "At first, suppose that $r \\le b$ (if not - swap them). Let's look at the case, where $gcd(r, b) = 1$. We can be sure that there will be a situation where the $pos$-th plank is painted in blue and $pos + 1$ plank is painted in red. It's true because it's equivalent to the solution of equation $r \\cdot x - b \\cdot y = 1$. And all we need to check that interval $(pos, pos + b)$ contains less than $k$ red planks. Or, in formulas, $(k - 1) \\cdot r + 1 \\ge b$. The situation with $gcd(r, b) > 1$ is almost the same if we look only at positions, which are divisible by $gcd(r, b)$ - in other words we can just divide $r$ on $gcd$ and $b$ on $gcd$ and check the same condition.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long li;\n\nli a, b, k;\n\ninline bool read() {\n\tif(!(cin >> a >> b >> k))\n\t\treturn false;\n\treturn true;\n}\n\ninline void solve() {\n\tli g = __gcd(a, b);\n\ta /= g;\n\tb /= g;\n\tif(a > b)\n\t\tswap(a, b);\n\tif((k - 1) * a + 1 < b)\n\t\tcout << \"REBEL\";\n\telse\n\t\tcout << \"OBEY\";\n\tcout << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tint tc; cin >> tc;\n\twhile(tc--) {\n\t\tread();\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1260",
    "index": "D",
    "title": "A Game with Traps",
    "statement": "You are playing a computer game, where you lead a party of $m$ soldiers. Each soldier is characterised by his agility $a_i$.\n\nThe level you are trying to get through can be represented as a straight line segment from point $0$ (where you and your squad is initially located) to point $n + 1$ (where the boss is located).\n\nThe level is filled with $k$ traps. Each trap is represented by three numbers $l_i$, $r_i$ and $d_i$. $l_i$ is the location of the trap, and $d_i$ is the danger level of the trap: whenever a soldier with agility lower than $d_i$ steps on a trap (that is, moves to the point $l_i$), he gets instantly killed. Fortunately, you can disarm traps: if you move to the point $r_i$, you disarm this trap, and it no longer poses any danger to your soldiers. Traps don't affect you, only your soldiers.\n\nYou have $t$ seconds to complete the level — that is, to bring some soldiers from your squad to the boss. Before the level starts, you choose which soldiers will be coming with you, and which soldiers won't be. After that, you have to bring \\textbf{all of the chosen soldiers} to the boss. To do so, you may perform the following actions:\n\n- if your location is $x$, you may move to $x + 1$ or $x - 1$. This action consumes one second;\n- if your location is $x$ and the location of your squad is $x$, you may move to $x + 1$ or to $x - 1$ with your squad in one second. You may not perform this action if it puts some soldier in danger (i. e. the point your squad is moving into contains a non-disarmed trap with $d_i$ greater than agility of some soldier from the squad). This action consumes one second;\n- if your location is $x$ and there is a trap $i$ with $r_i = x$, you may disarm this trap. This action is done instantly (it consumes no time).\n\nNote that after each action both your coordinate and the coordinate of your squad should be integers.\n\nYou have to choose the maximum number of soldiers such that they all can be brought from the point $0$ to the point $n + 1$ (where the boss waits) in no more than $t$ seconds.",
    "tutorial": "When we fix a set of soldiers, we can determine a set of traps that may affect our squad: these are the traps with danger level greater than the lowest agility value. So we can use binary search on minimum possible agility of a soldier that we can choose. How should we actually bring our soldiers to the boss? Each trap that can affect our squad can be actually treated as a segment $[l_i, r_i]$ such that our squad cannot move to $l_i$ until we move to $r_i$ and disarm this trap. We should walk through such segments for three times: the first time we walk forwards without our squad to disarm the trap, the second time we walk backwards to return to our squad, and the third time we walk forwards with our squad. So the total time we have to spend can be calculated as $n + 1 + 2T$, where $T$ is the number of unit segments belonging to at least one trap-segment - and it can be calculated with event processing algorithms or with segment union. Time complexity is $O(n \\log n)$ or $O(n \\log^2 n)$, but it is possible to write a solution in $O(n \\alpha(n))$ without binary search.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n\n#include<iostream>\n#include<cstdio>\n#include<vector>\n#include<algorithm>\n#include<map>\n\nusing namespace std;\n\ntypedef pair<int, int> pt;\n\n#define x first\n#define y second\n\n\nint m, n, k, t;\nvector<int> l, r, d, a;\n\nbool can(int x)\n{\n\tint mn = int(1e9);\n\tfor (int i = 0; i < x; i++)\n\t\tmn = min(mn, a[i]);\n\tvector<pt> segm;\n\tfor (int i = 0; i < k; i++)\n\t\tif (d[i] > mn)\n\t\t\tsegm.push_back(make_pair(l[i], r[i]));\n\tint req_time = 0;\n\tsort(segm.begin(), segm.end());\n\tint lastr = 0;\n\tfor (auto s : segm)\n\t{\n\t\tif (s.x <= lastr)\n\t\t{\n\t\t\treq_time += max(0, s.y - lastr);\n\t\t\tlastr = max(s.y, lastr);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treq_time += s.y - s.x + 1;\n\t\t\tlastr = s.y;\n\t\t}\n\t}\n\treq_time = 2 * req_time + n + 1;\n\treturn req_time <= t;\n}\n\nint main()\n{\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\tscanf(\"%d %d %d %d\", &m, &n, &k, &t);\n\ta.resize(m);\n\tfor (int i = 0; i < m; i++)\n\t\tscanf(\"%d\", &a[i]);\n\tsort(a.begin(), a.end());\n\treverse(a.begin(), a.end());\n\tl.resize(k);\n\tr.resize(k);\n\td.resize(k);\n\tfor (int i = 0; i < k; i++)\n\t\tscanf(\"%d %d %d\", &l[i], &r[i], &d[i]);\n\n\tint lf = 0;\n\tint rg = m + 1;\n\twhile (rg - lf > 1)\n\t{\n\t\tint mid = (lf + rg) / 2;\n\t\tif (can(mid))\n\t\t\tlf = mid;\n\t\telse\n\t\t\trg = mid;\n\t}\n\tprintf(\"%d\\n\", lf);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1260",
    "index": "E",
    "title": "Tournament",
    "statement": "You are organizing a boxing tournament, where $n$ boxers will participate ($n$ is a power of $2$), and your friend is one of them. All boxers have different strength from $1$ to $n$, and boxer $i$ wins in the match against boxer $j$ if and only if $i$ is stronger than $j$.\n\nThe tournament will be organized as follows: $n$ boxers will be divided into pairs; the loser in each pair leaves the tournament, and $\\frac{n}{2}$ winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner).\n\nYour friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower.\n\nFurthermore, during each stage you distribute the boxers into pairs as you wish.\n\nThe boxer with strength $i$ can be bribed if you pay him $a_i$ dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?",
    "tutorial": "If our friend is the strongest boxer, he wins without any bribing. Otherwise, we have to bribe the strongest boxer - and he can defeat some $\\frac{n}{2} - 1$ other boxers (directly or indirectly). Suppose we chose the boxers he will defeat, then there is another strongest boxer. If our friend is the strongest now, we don't need to bribe anyone; otherwise we will bribe the strongest remaining boxer again, and he can defeat $\\frac{n}{4} - 1$ other boxers, and so on. The only thing that's unclear is which boxers should be defeated by the ones we bribe. We may use dynamic programming to bribe them: $dp_{i, j}$ is the minimum cost to bribe $i$ boxers so that all boxers among $j$ strongest ones are either bribed or defeated by some bribed boxer. For each value of $i$ we know the maximum amount of boxers that are defeated by $i$ bribed boxers, so the transitions in this dynamic programming are the following: if we can't defeat the next boxer \"for free\" (our bribed boxers have already defeated as many opponents as they could), we have to bribe him; otherwise, we either bribe him or consider him defeated by some other boxer. Overall complexity is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int LOGN = 20;\nconst int N = (1 << LOGN) + 99;\nconst long long INF = 1e18;\n\nint n;\nint a[N];\nlong long dp[LOGN+2][N];\nint sum[100];\n\nlong long calc(int cnt, int pos){\n\tlong long &res = dp[cnt][pos];\n\tif(res != -1) return res;\n\n\tif(a[pos] == -1) return res = 0;\n\tint rem = sum[cnt] - pos;\n\n\tres = INF;\n\tif(cnt < LOGN)\n\t\tres = calc(cnt + 1, pos + 1) + a[pos];\n\tif(rem > 0)\t\t\n\t\tres = min(res, calc(cnt, pos + 1));\n\n\treturn res;\n}\n\nint main() {\t\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", a + i);\n\n\tfor(int i = 1, x = n / 2; i < 100; ++i, x /= 2)\n\t\tsum[i] = sum[i - 1] + x;\n\t\n\treverse(a, a + n);\n\tmemset(dp, -1, sizeof dp);\n\tprintf(\"%lld\", calc(0, 0));\t\n\treturn 0;\n}                             \t",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1260",
    "index": "F",
    "title": "Colored Tree",
    "statement": "You're given a tree with $n$ vertices. The color of the $i$-th vertex is $h_{i}$.\n\nThe value of the tree is defined as $\\sum\\limits_{h_{i} = h_{j}, 1 \\le i < j \\le n}{dis(i,j)}$, where $dis(i,j)$ is the number of edges on the shortest path between $i$ and $j$.\n\nThe color of each vertex is lost, you only remember that $h_{i}$ can be any integer from $[l_{i}, r_{i}]$(inclusive). You want to calculate the sum of values of all trees meeting these conditions modulo $10^9 + 7$ (the set of edges is fixed, but each color is unknown, so there are $\\prod\\limits_{i = 1}^{n} (r_{i} - l_{i} + 1)$ different trees).",
    "tutorial": "Let's set the root as $1$. Define $lca(u,v)$ as the lowest common ancestor of vertices $u$ and $v$, $dep(u)$ as the depth of vertex $u$ $(dep(u) = dis(1,u))$. Obviously $dis(u,v) = dep(u) + dep(v) - 2 \\times dep(lca(u,v))$. The answer we want to calculate is $\\sum_{G}{\\sum_{h_{i} = h_{j},i < j}{dis(i,j)}}$ where $G$ represent all possible colorings of the tree. We can enumerate the color $c$. For a fixed color $c$, we need to calculate $\\sum_{l_{i} \\leq c \\leq r_{i} , l_{j} \\leq c \\leq r_{j}}{[dis(i,j) \\times \\prod_{k \\neq i,j}{(r_{k} - l_{k} + 1)}]}$ Let $P = \\prod_{1 \\leq i \\leq n}{(r_{i} - l_{i} + 1)} , g_{i} = r_{i} - l_{i} + 1$. Also denote $V(i)$ as a predicate which is true iff $l_{i} \\leq c \\leq r_{i}$. $\\begin{align} & \\sum_{l_{i} \\leq c \\leq r_{i} , l_{j} \\leq c \\leq r_{j}}{[dis(i,j) \\times \\prod_{k \\neq i,j}{(r_{k} - l_{k} + 1)}]} \\\\ = & \\sum_{V(i) \\land V(j)}{dep(i) \\times \\frac{P}{g_{i} \\times g_{j}}} + \\sum_{V(i) \\land V(j)}{dep(j) \\times \\frac{P}{g_{i} \\times g_{j}}} - 2 \\times \\sum_{V(i) \\land V(j)}{dep(lca(i,j)) \\times \\frac{P}{g_{i} \\times g_{j}}} \\\\ = & P \\times (\\sum_{V(i)}{\\frac{dep(i)}{g_{i}}}) \\times (\\sum_{V(i)}{\\frac{1}{g_{i}}}) - P \\times \\sum_{V(i)}{\\frac{dep(i)}{g_{i}^2}} - 2P \\times \\sum_{V(i) \\land V(j)}{dep(lca(i,j)) \\times \\frac{1}{g_{i} \\times g_{j}}} \\end{align}$ Now our problem is how to maintain this formula while enumerating the color $c$. $P \\times (\\sum_{V(i)}{\\frac{dep(i)}{g_{i}}}) \\times (\\sum_{V(i)}{\\frac{1}{g_{i}}})$ can be easily maintained. For $\\sum_{V(i) \\land V(j)}{dep(lca(i,j)) \\times \\frac{1}{g_{i} \\times g_{j}}}$, we can add $\\frac{1}{g_{i}}$ to all vertices in path $i$ to $1$ (for each existing vertex $i$), and when new vertex is added, just calculate the sum of vertices on path from $i$ to $1$, minus the contribution of vertex $1$ (because there are $dep(u) + 1$ vertices in the path $u$ to $1$), and multiply it $\\frac{1}{g_{i}}$. Similar operation can be used to handle the situation when some vertex disappears. All of this can be done with HLD. Overall it's $O(c_{max} + nlog^2(n))$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint n ;\nconst int maxn = 1e5 + 5;\nconst int mod = 1e9 + 7 ;\nvector<int> E[maxn];\nvector<int> in[maxn] , out[maxn];\nint cm = 0;\nint l[maxn] , dfn = 0 , dep[maxn];\nint g[maxn];\nint siz[maxn] , top[maxn] , h[maxn] , f[maxn];\n///-----segment tree\nstruct seg\n{\n    int l , r;\n    int sum , add ;\n}Node[maxn * 4];\n\nvoid build(int u,int l,int r)\n{\n    Node[u].l = l , Node[u].r = r;\n    Node[u].sum = Node[u].add = 0;\n    if(l == r) return ;\n    build(u<<1 , l , (l + r >> 1));\n    build(u<<1|1 , (l + r >>1) + 1 , r);\n    return ;\n}\nvoid pd(int u)\n{\n    Node[u].sum = (1LL*Node[u].add*(Node[u].r - Node[u].l + 1) + Node[u].sum) % mod ;\n    if(Node[u].l == Node[u].r) {\n        Node[u].add = 0 ;return ;\n    }\n    (Node[u<<1].add += Node[u].add ) %= mod;\n    (Node[u<<1|1].add += Node[u].add ) %= mod;\n    Node[u].add = 0 ; return ;\n}\nvoid modify(int u,int l,int r,int v)\n{\n    if(Node[u].l == l && Node[u].r == r) {\n        (Node[u].add += v ) %= mod;\n        pd(u) ; return ;\n        return ;\n    }\n    pd(u) ;\n    if(Node[u<<1].r >= r) {modify(u<<1 , l , r , v) ; pd(u<<1|1);}\n    else if(Node[u<<1|1].l <= l) {modify(u<<1|1 , l , r , v) ; pd(u<<1) ;}\n    else {\n        modify(u<<1 , l , Node[u<<1].r , v) ;\n        modify(u<<1|1 , Node[u<<1|1].l , r , v);\n    }\n    Node[u].sum = (Node[u<<1].sum + Node[u<<1|1].sum) % mod;\n    return ;\n}\nint query(int u,int l,int r)\n{\n    pd(u) ;\n    if(Node[u].l == l && Node[u].r == r) return Node[u].sum ;\n    if(Node[u<<1].r >= r) return query(u<<1 , l , r) ;\n    else if(Node[u<<1|1].l <= l) return query(u<<1|1 , l , r);\n    else return (query(u<<1 , l , Node[u<<1].r) + query(u<<1|1 , Node[u<<1|1].l , r)) % mod;\n}\n///---segment tree end\nvoid dfs(int fa,int u,int d)\n{\n    f[u] = fa;\n    dep[u] = d;siz[u] = 1;h[u] = -1;\n    for(int i = 0;i < E[u].size();i++) {\n        if(E[u][i] != fa) {\n            dfs(u , E[u][i] , d + 1) ;siz[u] += siz[E[u][i]];\n            if(h[u] == -1 || siz[E[u][i]] > siz[E[u][h[u]]]) h[u] = i;\n        }\n    }\n    return ;\n}\nvoid dfs2(int fa,int u)\n{\n    l[u] = ++dfn;\n    if(h[u] != -1) {\n        top[E[u][h[u]]] = top[u] ;\n        dfs2(u , E[u][h[u]]);\n    }\n    for(int i = 0;i < E[u].size();i++) {\n        if(E[u][i] != fa && i != h[u]) {\n            top[E[u][i]] = E[u][i] ;\n            dfs2(u , E[u][i]) ;\n        }\n    }\n    return ;\n}\nint fpow(int a,int b)\n{\n    int ans = 1;\n    while(b) {\n        if(b & 1) ans = (1LL * ans * a) % mod;\n        a = (1LL * a * a) % mod ;b >>= 1;\n    }\n    return ans;\n}\nvoid add(int u,int v)\n{\n    while(u) {\n        modify(1 , l[top[u]] , l[u] , v) ;\n        u = f[top[u]] ;\n    }\n    return ;\n}\nint cal(int u)\n{\n    int ans = mod - query(1 , 1 , 1);\n    while(u) {\n        ans = (ans + query(1 , l[top[u]] , l[u])) % mod;\n        u = f[top[u]] ;\n    }\n    return ans;\n}\nint main()\n{\n    scanf(\"%d\",&n) ;\n    int P = 1;\n    for(int i = 1;i <= n;i++) {\n        int l , r;scanf(\"%d%d\",&l,&r) ;\n        in[l].push_back(i) ;\n        out[r + 1].push_back(i) ; cm = max(cm , r);\n        g[i] = fpow(r - l + 1 , mod - 2) ;\n        P = 1LL * P * (r - l + 1) % mod;\n    }\n    for(int i = 1;i < n;i++) {\n        int u , v;scanf(\"%d%d\",&u,&v) ;\n        E[u].push_back(v) ; E[v].push_back(u) ;\n    }\n    dfs(0 , 1 , 0) ; top[1] = 1;\n    dfs2(0 , 1) ;\n    build(1 , 1 , n) ;\n    int ans = 0 , cur = 0;\n    int d1 = 0 , d2 = 0 , u , d3 = 0;\n    for(int i = 1;i <= cm;i++) {\n        for(int j = 0;j < out[i].size();j++) {\n            u = out[i][j] ;\n            d1 = (d1 - 1LL * dep[u] * g[u] % mod + mod) % mod;\n            d2 = (d2 - g[u] + mod) % mod ;\n            d3 = (d3 - 1LL*dep[u]*g[u] % mod * g[u] % mod + mod) % mod;\n            add(u , mod - g[u]) ;\n            cur = (cur - 1LL * g[u] * cal(u) % mod + mod) % mod;\n        }\n        for(int j = 0;j < in[i].size();j++) {\n            u = in[i][j] ;\n            d1 = (d1 + 1LL * dep[u] * g[u]) % mod;\n            d2 = (d2 + g[u]) % mod;\n            d3 = (d3 + 1LL*dep[u]*g[u]%mod*g[u]) % mod;\n            cur = (cur + 1LL * g[u] * cal(u)) % mod;\n            add(u , g[u]) ;\n        }\n        ans = (ans + 1LL * d1 * d2%mod - 2LL*cur - d3) % mod;\n        ans = (ans + mod) % mod;\n    }\n    ans = 1LL * ans * P % mod;\n    printf(\"%d\\n\",ans);\n    return 0;\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1261",
    "index": "F",
    "title": "Xor-Set",
    "statement": "You are given two sets of integers: $A$ and $B$. You need to output the sum of elements in the set $C = \\{x | x = a \\oplus b, a \\in A, b \\in B\\}$ modulo $998244353$, where $\\oplus$ denotes the bitwise XOR operation. Each number should be counted only once.\n\nFor example, if $A = \\{2, 3\\}$ and $B = \\{2, 3\\}$ you should count integer $1$ only once, despite the fact that you can get it as $3 \\oplus 2$ and as $2 \\oplus 3$. So the answer for this case is equal to $1 + 0 = 1$.\n\nLet's call a segment $[l; r]$ a set of integers $\\{l, l+1, \\dots, r\\}$.\n\nThe set $A$ is given as a union of $n_A$ segments, the set $B$ is given as a union of $n_B$ segments.",
    "tutorial": "Consider a segment tree over the interval $[0,2^{60}-1]$, a node representing a segment of length $2^n$ would represent all numbers with the first $60-n$ bits same, with all possible last n bits. In other words, the binary representation of any number in the segment would be $a_1a_2a_3\\ldots a_{59-n}a_{60-n}x_1x_2x_3\\ldots x_n$, where all $a_i$ and $x_i$ is either 0 or 1. $a_1$ to $a_{60-n}$ would be fixed and all $x_i$s can be arbitrarily chosen. We can observe that if we have two segments $A$ and $B$ in the tree, all possible numbers that equals the xor sum of a number in $A$ and a number in $B$ also forms a segment in the tree, with the length of $\\max(|A|,|B|)$, and the unchanging bits is equal to the xor sum of the two segment's unchanging bits. Using this observation we would get an $O( (n^2 \\log^2 10^{18}) \\log (n^2 \\log^2 10^{18}))$ or $O( n^2 \\log^2 10^{18})$ algorithm, depending on the sorting method. First, we get all segments that compose the intervals in $A$ and $B$, we can get $O( n^2 \\log^2 10^{18})$ resulting segments. Then we are left with evaluating the sum in the combination of segments. We can sort these segments to get the answer. This algorithm will get an MLE in practice since the number of resulting segments could easily exceed $10^8$. To improve this algorithm, we can make another observation that when segments of different sizes are combined as described above, the smaller segment is equivalent to the ancestor of the same size as the bigger segment. Let's call all the segments in the decomposition of the input the \"real\" segments, and all segments with a \"real\" segment in the subtree as \"auxiliary\" segments. Then we could iterate over 60 possible values of the size of the segment, and for each value, we could iterate over the \"real\" segments of set $A$ and \"auxiliary\" segments of set $B$ and add the results to the set. We can prove that the number of both \"real\" and \"auxiliary\" segments of any size is not greater than $4n$. Thus, the solution runs at $O( (n^2 \\log 10^{18}) \\log (n^2 \\log 10^{18}))$ or $O( n^2 \\log 10^{18})$ algorithm, depending on the sorting method.",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1263",
    "index": "A",
    "title": "Sweet Problem",
    "statement": "You have three piles of candies: red, green and blue candies:\n\n- the first pile contains only red candies and there are $r$ candies in it,\n- the second pile contains only green candies and there are $g$ candies in it,\n- the third pile contains only blue candies and there are $b$ candies in it.\n\nEach day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.\n\nFind the maximal number of days Tanya can eat candies? Each day she needs to eat \\textbf{exactly} two candies.",
    "tutorial": "Sort the values of $r$, $g$, $b$ such that $r \\geq g \\geq b$. Now consider two cases. If $r \\geq g + b$, then Tanya can take $g$ candies from piles $r$ and $g$, and then - $b$ candies from piles $r$ and $b$. After that there may be a bunch of candies left in the pile $r$ that Tanya won't be able to eat, so the answer is $g + b$. Otherwise, we need to achieve the equality of the piles $r$, $g$, $b$. First, we make equal $r$ and $g$ by eating $r - g$ from the piles $r$ and $b$ (this can always be done since $r < g + b$). Then we make equal the piles $g$, $b$ by eating $g - b$ from the piles $r$ and $g$. After that, $r = g = b$, and we can get three different cases. $r = g = b = 0$ - nothing needs to be done, Tanya has already eaten all the sweets; $r = g = b = 1$ - you can take candy from any of two piles so in the end there will always be one candy left; $r = g = b \\geq 2$ - we reduce all the piles by $2$, taking, for example, a candy from piles $r$ and $g$, $g$ and $b$, $r$ and $b$. With such actions, Tanya eventually reaches the two previous cases, since the sizes of the piles are reduced by 2. Since with this strategy we always have 0 or 1 candy at the end, Tanya will be able to eat candies for $\\lfloor \\frac{r + g + b}{2} \\rfloor$ days.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {   \n        int a[3];\n        cin >> a[0] >> a[1] >> a[2];\n        sort(a, a + 3);\n        if (a[2] <= a[0] + a[1])\n            cout << (a[0] + a[1] + a[2]) / 2 << endl;\n        else\n            cout << a[0] + a[1] << endl;\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1263",
    "index": "B",
    "title": "PIN Codes",
    "statement": "A PIN code is a string that consists of exactly $4$ digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.\n\nPolycarp has $n$ ($2 \\le n \\le 10$) bank cards, the PIN code of the $i$-th card is $p_i$.\n\nPolycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all $n$ codes would become different.\n\nFormally, in one step, Polycarp picks $i$-th card ($1 \\le i \\le n$), then in its PIN code $p_i$ selects one position (from $1$ to $4$), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different.\n\nPolycarp quickly solved this problem. Can you solve it?",
    "tutorial": "Group all the numbers into groups of equals PIN-Codes. Note that the size of each such group does not exceed $10$. Therefore, in each PIN-Code we need to change no more than $1$ digits. If the group consists of $1$ element, then we do nothing, otherwise, we take all the PIN-codes except one from this group and change exactly one digit in them so that the new PIN-code becomes unique.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\n\tvector<char> calced(n);\n\tvector<string> a(n);\n\tset<string> have;\n\tint res = 0;\n\n\tfor (string &pin : a) {\n\t\tcin >> pin;\n\t\thave.insert(pin);\n\t}\n\n\tfor (int i = 0; i < n; i++) {\n\t\tif (calced[i]) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvector<int> sameIds;\n\n\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\tif (a[i] == a[j]) {\n\t\t\t\tsameIds.push_back(j);\n\t\t\t\tcalced[j] = 1;\n\t\t\t\tres++;\n\n\t\t\t\tfor (int k = 0; k < 4 && a[i] == a[j]; k++) {\n\t\t\t\t\tfor (char c = '0'; c <= '9'; c++) {\n\t\t\t\t\t\tstring t = a[j];\n\t\t\t\t\t\tt[k] = c;\n\n\t\t\t\t\t\tif (!have.count(t)) {\n\t\t\t\t\t\t\thave.insert(t);\n\t\t\t\t\t\t\ta[j] = t;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << res << \"\\n\";\n\n\tfor (string& s : a) {\n\t\tcout << s << \"\\n\";\n\t}\n}\n\nint main() {\n\tint test;\n\tcin >> test;\n\n\twhile (test--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1263",
    "index": "C",
    "title": "Everyone is a Winner!",
    "statement": "On the well-known testing system MathForces, a draw of $n$ rating units is arranged. The rating will be distributed according to the following algorithm: if $k$ participants take part in this event, then the $n$ rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an unused rating may remain — it is not given to any of the participants.\n\nFor example, if $n = 5$ and $k = 3$, then each participant will recieve an $1$ rating unit, and also $2$ rating units will remain unused. If $n = 5$, and $k = 6$, then none of the participants will increase their rating.\n\nVasya participates in this rating draw but does not have information on the total number of participants in this event. Therefore, he wants to know what different values of the rating increment are possible to get as a result of this draw and asks you for help.\n\nFor example, if $n=5$, then the answer is equal to the sequence $0, 1, 2, 5$. Each of the sequence values (and only them) can be obtained as $\\lfloor n/k \\rfloor$ for some positive integer $k$ (where $\\lfloor x \\rfloor$ is the value of $x$ rounded down): $0 = \\lfloor 5/7 \\rfloor$, $1 = \\lfloor 5/5 \\rfloor$, $2 = \\lfloor 5/2 \\rfloor$, $5 = \\lfloor 5/1 \\rfloor$.\n\nWrite a program that, for a given $n$, finds a sequence of all possible rating increments.",
    "tutorial": "There are two approaches to solving this problem. Mathematical Solution Note that the answer will always contain the numbers $0 \\le x < \\lfloor \\sqrt{n} \\rfloor$. You can verify this by solving the equation $\\lfloor \\frac{n}{k} \\rfloor = x$, equivalent to the inequality $x \\le \\frac{n}{k} < x + 1$, for integer values of $k$. The solution to this double inequality is the interval $k \\in \\left (\\frac{n}{x + 1};\\; \\frac{n}{x} \\right]$, whose length is $\\frac{n}{x^2 + x}$. For $x < \\lfloor \\sqrt{n} \\rfloor$ $\\frac{n}{x^2 + x} > 1$, and on an interval of length greater than 1 there is always a whole solution $k = \\lfloor \\frac{n}{x} \\rfloor$, so all integers $0 \\le x < \\lfloor \\sqrt {n} \\rfloor$ belong to the answer. Note that we no longer need to iterate over the values of $k > \\lfloor \\sqrt{n} \\rfloor$, because these numbers always correspond to the values $0 \\le x < \\lfloor \\sqrt {n} \\rfloor$. Thus, it is possible, as in a naive solution, to iterate over all the values of $k$ upto $\\lfloor \\sqrt{n} \\rfloor$ and add $x = \\lfloor \\frac{n}{k} \\rfloor$ to the answer. It remains only to carefully handle the case $k = \\lfloor \\sqrt{n} \\rfloor$. Total complexity of the solution: $\\mathcal{O} (\\sqrt{n} \\log n)$ or $\\mathcal{O} (\\sqrt{n})$ Algorithmic Solution In the problem, it could be assumed that there are not so many numbers in the answer (after all, they still need to be printed, which takes the majority of the program execution time). Obviously, $n$ always belongs to the answer. Note that as $k$ increases, the value of $x = \\lfloor \\frac{n}{k} \\rfloor$ decreases. Thus, using a binary search, you can find the smallest value of $k'$ such that $\\frac{n}{k'} < x$. Value $x' = \\frac{n}{k'}$ will be the previous one for $x$ in the answer. Total complexity of the solution: $\\mathcal{O} (\\sqrt{n} \\log n)$",
    "code": "// #pragma GCC optimize(\"Ofast\")\n// #pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n\n#include <bits/stdc++.h>\n#define ALL(s) (s).begin(), (s).end()\n#define rALL(s) (s).rbegin(), (s).rend()\n#define sz(s) (int)(s).size()\n#define mkp make_pair\n#define pb push_back\n#define sqr(s) ((s) * (s))\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef unsigned long long ull;\ntypedef unsigned int ui;\n\n#ifdef EUGENE\n\tmt19937 rng(1337);\n#else\n\tmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n#endif\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> ans;\n\tint s = (int)sqrtl(n);\n\tfor (int i = 0; i <= s; i++)\n\t\tans.pb(i);\n\tfor (int i = 1; i <= s; i++)\n\t\tans.pb(n / i);\n\tsort(ALL(ans));\n\tans.resize(unique(ALL(ans)) - ans.begin());\n\tcout << sz(ans) << endl;\n\tfor (int &x : ans)\n\t\tcout << x << \" \";\n\tcout << endl;\n}\n\nint main() {\n\tios::sync_with_stdio(false); cin.tie(0);\n\t#ifdef EUGENE\n\t\tfreopen(\"input.txt\", \"r\", stdin);\n\t\t// freopen(\"output.txt\", \"r\", stdout);\n\t#endif\n\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n}",
    "tags": [
      "binary search",
      "math",
      "meet-in-the-middle",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1263",
    "index": "D",
    "title": "Secret Passwords",
    "statement": "One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $n$ passwords — strings, consists of small Latin letters.\n\nHacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $a$ and $b$ as follows:\n\n- two passwords $a$ and $b$ are equivalent if there is a letter, that exists in both $a$ and $b$;\n- two passwords $a$ and $b$ are equivalent if there is a password $c$ from the list, which is equivalent to both $a$ and $b$.\n\nIf a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.\n\nFor example, if the list contain passwords \"a\", \"b\", \"ab\", \"d\", then passwords \"a\", \"b\", \"ab\" are equivalent to each other, but the password \"d\" is not equivalent to any other password from list. In other words, if:\n\n- admin's password is \"b\", then you can access to system by using any of this passwords: \"a\", \"b\", \"ab\";\n- admin's password is \"d\", then you can access to system by using only \"d\".\n\n\\textbf{Only one} password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to \\textbf{guaranteed} access to the system. Keep in mind that the hacker does not know which password is set in the system.",
    "tutorial": "This problem can be solved in many ways (DSU, bipartite graph, std::set and so on). A solution using a bipartite graph will be described here. Consider a bipartite graph with $26$ vertices corresponding to each letter of the Latin alphabet in the first set and $n$ vertices corresponding to each password in the second set. Connect each password and the letters that are part of this password with an edge. From the definition of equivalence of passwords, it is easy to understand that the answer to the problem is the number of connected components in this bipartite graph. Total complexity: $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = (int)2e5 + 100;\n\nvector<int> g[N];\nchar used[N];\n\nvoid addEdge(int v, int u) {\n\tg[v].push_back(u);\n\tg[u].push_back(v);\n}\n\nvoid dfs(int v) {\n\tused[v] = 1;\n\n\tfor (int to : g[v]) {\n\t\tif (!used[to]) {\n\t\t\tdfs(to);\n\t\t}\n\t}\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\n\tfor (int i = 0; i < n; i++) {\n\t\tstring s;\n\t\tcin >> s;\n\n\t\tfor (char c : s) {\n\t\t\taddEdge(i, n + c - 'a');\n\t\t}\n\t}\n\n\tint res = 0;\n\n\tfor (int i = n; i < n + 26; i++) {\n\t\tif (!g[i].empty() && !used[i]) {\n\t\t\tdfs(i);\n\t\t\tres++;\n\t\t}\n\t}\n\n\tcout << res;\n\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1263",
    "index": "E",
    "title": "Editor",
    "statement": "The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.\n\nYour editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters). Thus, it points to an index character. The user can move the cursor left or right one position. If the cursor is already at the first (leftmost) position, then it does not move left.\n\nInitially, the cursor is in the first (leftmost) character.\n\nAlso, the user can write a letter or brackets (either (, or )) to the position that the cursor is currently pointing at. A new character always overwrites the old value at that position.\n\nYour editor must check, whether the current line is the correct text. Text is correct if the brackets in them form the correct bracket sequence.\n\nFormally, correct text (CT) must satisfy the following rules:\n\n- any line without brackets is CT (the line can contain whitespaces);\n- If the first character of the string — is (, the last — is ), and all the rest form a CT, then the whole line is a CT;\n- two consecutively written CT is also CT.\n\nExamples of correct texts: hello(codeforces), round, ((i)(write))edi(tor)s, ( me). Examples of incorrect texts: hello)oops(, round), ((me).\n\nThe user uses special commands to work with your editor. Each command has its symbol, which must be written to execute this command.\n\nThe correspondence of commands and characters is as follows:\n\n- L — move the cursor one character to the left (remains in place if it already points to the first character);\n- R — move the cursor one character to the right;\n- any lowercase Latin letter or bracket (( or )) — write the entered character to the position where the cursor is now.\n\nFor a complete understanding, take a look at the first example and its illustrations in the note below.\n\nYou are given a string containing the characters that the user entered. For the brackets coloring module's work, after each command you need to:\n\n- check if the current text in the editor is a correct text;\n- if it is, print the least number of colors that required, to color all brackets.\n\nIf two pairs of brackets are nested (the first in the second or vice versa), then these pairs of brackets should be painted in different colors. If two pairs of brackets are not nested, then they can be painted in different or the same colors. For example, for the bracket sequence ()(())()() the least number of colors is $2$, and for the bracket sequence (()(()())())(()) — is $3$.\n\nWrite a program that prints the minimal number of colors after processing each command.",
    "tutorial": "To respond to requests, you need two stacks. The first stack will contain all the brackets at the positions left than the cursor position, and the second one all the remaining ones. Also, for each closing bracket in the first stack, we will maintain the maximum depth of the correct bracket sequence (CBS) ending with this bracket. Similarly, in the second stack, we will maintain the maximum depth of CBS that starting in this bracket. Since the brackets are added to the stack at the end and one at a time, you can easily recalculate this value. Even in the left stack, you need to maintain the number of opening brackets that do not have a pair of closing brackets, and in the right stack the number of closing brackets that do not have a pair of opening brackets. If the previous two values are equal, then the current line is CBS. Otherwise, there is either one non-closed bracket or one bracket that does not have an opening one. The answer to the problem, after each query, will be a maximum of three values - the maximum depth in the left stack, the maximum depth in the right stack and the number of non-closed brackets (the number of non-opened brackets in the right stack does not need to be taken into account, since if the line is CBS, then it is the number of open brackets in the left). Total complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\nstruct MyStack {\n    int cnt = 0;\n    int allOpens = 0;\n    stack<int> s;\n    stack<int> minValue;\n    stack<int> maxValue;\n\n    void push(int x) {\n        s.push(x);\n        cnt += x;\n        if (x == 1) {\n            allOpens += 1;\n        }\n        minValue.push((minValue.size() ? min(minValue.top(), cnt) : cnt));\n        maxValue.push((maxValue.size() ? max(maxValue.top(), cnt) : cnt));\n    }\n\n    void pop() {\n        if (s.size() == 0) {\n            return;\n        }\n        cnt -= s.top();\n        if (s.top() == 1) {\n            allOpens -= 1;\n        }\n        s.pop();\n        minValue.pop();\n        maxValue.pop();\n    }\n\n    int top() {\n        return s.top();\n    }\n\n    bool isCorrect() {\n        return (minValue.size() == 0 || minValue.top() >= 0);\n    }\n\n    int depth() {\n        return (maxValue.size() ? maxValue.top() : 0);\n    }\n};\n\nint main() {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    MyStack left, right;\n    vector<int> ans(n);\n    for (int i = 0; i < n; i++) {\n        right.push(0);\n    }\n    left.push(0);\n    int pos = 0;\n    for (int i = 0; i < n; i++) {\n        if (s[i] == 'L') {\n            if (pos != 0) {\n                pos--;\n                right.push(-left.top());\n                left.pop();\n            }\n        } else if (s[i] == 'R') {\n            pos++;\n            left.push(-right.top());\n            right.pop();\n        } else if (s[i] == '(') {\n            left.pop();\n            left.push(1);\n        } else if (s[i] == ')') {\n            left.pop();\n            left.push(-1);\n        } else {\n            left.pop();\n            left.push(0);\n        }\n        if (left.isCorrect() && right.isCorrect() && left.cnt == right.cnt) {\n            cout << max({left.depth(), right.depth(), left.cnt}) << \" \";\n        } else {\n            cout << \"-1 \";\n        }\n    }\n}           \t",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1263",
    "index": "F",
    "title": "Economic Difficulties",
    "statement": "An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!\n\nEach grid (main and reserve) has a head node (its number is $1$). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly $n$ nodes, which do not spread electricity further.\n\nIn other words, every grid is a rooted directed tree on $n$ leaves with a root in the node, which number is $1$. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.\n\nAlso, the palace has $n$ electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device.\n\n\\begin{center}\n{\\small In this example the main grid contains $6$ nodes (the top tree) and the reserve grid contains $4$ nodes (the lower tree). There are $3$ devices with numbers colored in blue.}\n\\end{center}\n\nIt is guaranteed that the whole grid (two grids and $n$ devices) can be shown in this way (like in the picture above):\n\n- main grid is a top tree, whose wires are directed 'from the top to the down',\n- reserve grid is a lower tree, whose wires are directed 'from the down to the top',\n- devices — horizontal row between two grids, which are numbered from $1$ to $n$ from the left to the right,\n- wires between nodes do not intersect.\n\nFormally, for each tree exists a depth-first search from the node with number $1$, that visits leaves in order of connection to devices $1, 2, \\dots, n$ (firstly, the node, that is connected to the device $1$, then the node, that is connected to the device $2$, etc.).\n\nBusinessman wants to sell (remove) \\textbf{maximal} amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.",
    "tutorial": "We assume that the leaves of the trees are numbered in the same way as the devices to which these leaves are connected. Let's calculate $cost_{l, r}$ ($l \\le r$) for each tree (let's call them $upperCost_{l, r}$ and $lowerCost_{l, r}$) - the maximum number of edges that can be removed so that on the segment $[l, r]$ exists a path from each leaf to the root of the opposite tree. Let's calculate $cost_{l, r}$ for some fixed $l$. Let's call 'bamboo' the connected set of ancestors of the node $v$ such that each node has at most $1$ child, and the node $v$ itself is in this set. Obviously, $cost_{l, l}$ is the maximum length of $l$'s 'bamboo'. Suppose we have already calculated $cost_{l, r - 1}$. Let's calculate $cost_{l, r -1 }$. Obviously, we can remove all edges counted in $cost_{l, r - 1}$. We can also remove the resulting 'bamboo' of the leaf $r$ (because we do not need to have paths from the leaves $[l, r]$ to the root in the tree, for which we are calculating $cost$). Let's prove that we cannot remove more edges. For each tree exists a depth-first search from the node $1$, that visits leaves in order of connection to devices, so for each node $v$ the set of leaf indices in its subtree is a segment. If there is $r$ in the segment for the node $v$, then the $r$-th leaf is in the subtree of the node $v$. Let's have a look at the nodes whose subtree does not contain leaf $r$. If in their subtree there are nodes not from the segment $[l, r]$, then we cannot remove edge to the parent of this node, because we don't want to lose the path to the root for the nodes out of the segment $[l, r]$ (we are calculating the answer only for the segment $[l, r]$). So in the $v$'s subtree leaves are only from the segment $[l, r]$. Leaves from the segment $[l, r - 1]$ were calculated in $cost_{l, r - 1}$. Then the segment for the $v$'s nodes is $[i, r], l \\le i$. So we can remove the edge from each such node to its parent. And the set of these nodes is a 'bamboo' from the leaf $r$ because we have already removed all 'bamboos' on $[l, r - 1]$ segment. So to calculate $cost_{l, r}$ it is enough to know $cost_{l, r - 1}$ and the maximum length of $r$'s 'bamboo'. This can be calculated in $\\mathcal{O}(n(a + b))$ time complexity. Let's calculate $dp_i$ - the answer for the $i$-th prefix. Let's take a look at the answer: some suffix of leaves has a path to the root in only one tree, and the rest of prefix has a maximum answer (if not, then we take the maximum answer for the prefix, which will improve the answer). Then we get the formula $dp_i = \\max\\limits_{0 \\le j < i}(dp_{j} + \\max(upperCost_{j, i-1}, lowerCost_{j, i-1}))$ (and $dp_0 = 0$), which can be calculated in the $\\mathcal{O}(n^2)$ time complexity. Then the answer is $dp_n$. Challenge: Can you solve this problem with linear time complexity (for example, $\\mathcal{O}(n + a + b)$)?",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\n#define sz(x) int((x).size())\n#define all(x) begin(x), end(x)\n\n#ifdef LOCAL\n    #define eprint(x) cerr << #x << \" = \" << (x) << endl\n    #define eprintf(args...) fprintf(stderr, args), fflush(stderr)\n#else\n    #define eprint(x)\n    #define eprintf(...)\n#endif\n\nvector<vector<int>> precalc(int n, vector<int> p, vector<int> id) {\n    vector<vector<int>> res(n, vector<int>(n));\n\n    for (int l = 0; l < n; l++) {\n        vector<int> deg(sz(p));\n        for (int i = 1; i < sz(p); i++)\n            deg[p[i]]++;\n\n        int val = 0;\n        for (int r = l; r < n; r++) {\n            int v = id[r];\n            while (v != 0 && deg[v] == 0) {\n                deg[p[v]]--;\n                v = p[v];\n                val++;\n            }\n            res[l][r] = val;\n        }\n    }\n\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n;\n    cin >> n;\n\n    vector<vector<int>> p(2);\n    vector<vector<int>> id(2);\n    for (int i = 0; i < 2; i++) {\n        int vn;\n        cin >> vn;\n        p[i].resize(vn);\n        for (int v = 1; v < vn; v++) {\n            cin >> p[i][v];\n            p[i][v]--;\n        }\n        id[i].resize(n);\n        for (int j = 0; j < n; j++) {\n            cin >> id[i][j];\n            id[i][j]--;\n        }\n    }\n\n    vector<vector<vector<int>>> cost(2);\n    for (int i = 0; i < 2; i++)\n        cost[i] = precalc(n, p[i], id[i]);\n\n    vector<int> dp(n + 1);\n    for (int i = 0; i < n; i++) {\n        for (int j = i + 1; j <= n; j++) {\n            dp[j] = max(dp[j], dp[i] + max(\n                cost[0][i][j - 1],\n                cost[1][i][j - 1]\n            ));\n        }\n    }\n\n    cout << dp[n] << endl;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "flows",
      "graphs",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1264",
    "index": "A",
    "title": "Beautiful Regional Contest",
    "statement": "So the Beautiful Regional Contest (BeRC) has come to an end! $n$ students took part in the contest. The final standings are already known: the participant in the $i$-th place solved $p_i$ problems. Since the participants are primarily sorted by the number of solved problems, then $p_1 \\ge p_2 \\ge \\dots \\ge p_n$.\n\nHelp the jury distribute the gold, silver and bronze medals. Let their numbers be $g$, $s$ and $b$, respectively. Here is a list of requirements from the rules, which all must be satisfied:\n\n- for each of the three types of medals, at least one medal must be awarded (that is, $g>0$, $s>0$ and $b>0$);\n- the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, $g<s$ and $g<b$, but there are no requirements between $s$ and $b$);\n- each gold medalist must solve strictly more problems than any awarded with a silver medal;\n- each silver medalist must solve strictly more problems than any awarded a bronze medal;\n- each bronze medalist must solve strictly more problems than any participant not awarded a medal;\n- the total number of medalists $g+s+b$ should not exceed half of all participants (for example, if $n=21$, then you can award a maximum of $10$ participants, and if $n=26$, then you can award a maximum of $13$ participants).\n\nThe jury wants to reward with medals the total \\textbf{maximal} number participants (i.e. to maximize $g+s+b$) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals.",
    "tutorial": "To solve this problem, we have to make the following observations: All participants who solved the same number of problems must be either not awarded at all or all are awarded a same type of medal. All $g+s+b$ awarded participants are the first $g+s+b$ participants. Suppose we have an optimal solution with $g$ gold medals, $s$ silver medals and $b$ bronze medals where $g+s+b$ is maximized. We can make the followings changes that resulted in another valid (and still optimal) solution: Only keep gold medalist who solved most problem. For others, we change their medal types from gold to silver. After this change, $g+s+b$ is unchanged and other rules are still satisfied. Similarly, only keep a minimized number of silver medalist who solved most problems among all silver medalist and the number of kept silver must strictly larger than the number gold medals. For others, we change their medal types from silver to bronze. After this changed, $g+s+b$ is unchanged and other rules are still satisfied. Time complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        map<int,int> c;\n        forn(i, n) {\n            int pi;\n            cin >> pi;\n            c[-pi]++;\n        }\n        vector<int> pp;\n        for (auto p: c)\n            pp.push_back(p.second);\n        bool ok = false;\n        int g = pp[0];\n        int i = 1;\n        int s = 0;\n        while (s <= g && i < pp.size())\n            s += pp[i++];\n        if (g < s) {\n           int b = 0;\n           while (b <= g && i < pp.size())\n               b += pp[i++];\n           while (i < pp.size() && g + s + b + pp[i] <= n / 2)\n               b += pp[i++];\n           if (g < b && g + s + b <= n / 2) {\n               ok = true;\n               cout << g << \" \" << s << \" \" << b << endl;\n           }\n        }\n        if (!ok)\n            cout << 0 << \" \" << 0 << \" \" << 0 << endl;\n    }\n}\n",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1264",
    "index": "B",
    "title": "Beautiful Sequence",
    "statement": "An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to $1$. More formally, a sequence $s_1, s_2, \\ldots, s_{n}$ is beautiful if $|s_i - s_{i+1}| = 1$ for all $1 \\leq i \\leq n - 1$.\n\nTrans has $a$ numbers $0$, $b$ numbers $1$, $c$ numbers $2$ and $d$ numbers $3$. He wants to construct a beautiful sequence using all of these $a + b + c + d$ numbers.\n\nHowever, it turns out to be a non-trivial task, and Trans was not able to do it. Could you please help Trans?",
    "tutorial": "Firstly, let's arrange even numbers. It is optimal to arrange those numbers as $0, 0, 0,\\ldots,0,2, 2, \\ldots 2$. Because we can place number $1$ anywhere while number $3$ only between two numbers $2$ or at the end beside a number $2$. So we need to maximize the number of positions where we can place number $3$. The above gives us an optimal way. The next step is to place the remaining numbers $1, 3$. Inserting them in internal positions first then at the ends later. Base on the above argument, we can do as following way that eliminates corner case issues: Starting from a number (try all possible value $0, 1, 2, 3$). At any moment, if $x$ is the last element and there is at least number $x - 1$ remains, we append $x - 1$ otherwise we append $x + 1$ or stop if there is no $x + 1$ left. If we manage to use all numbers then we have a beautiful sequence and answer is 'YES'.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    map<int, int> hs;\n    cin >> hs[0] >> hs[1] >> hs[2] >> hs[3];\n    int total = hs[0] + hs[1] + hs[2] + hs[3];\n    for (int st = 0; st < 4; st++) if (hs[st]) {\n        vector<int> res;\n        auto ths = hs;\n        ths[st]--;\n        res.push_back(st);\n        int last = st;\n        for (int i = 0; i < total - 1; i++) {\n            if (ths[last - 1]) {\n                ths[last - 1]--;\n                res.push_back(last - 1);\n                last--;\n            }\n            else if (ths[last + 1]) {\n                ths[last + 1]--;\n                res.push_back(last + 1);\n                last++;\n            }\n            else {\n                break;\n            }\n        }\n        if ((int) res.size() == total) {\n            cout << \"YES\\n\";\n            for (int i = 0; i < (int) res.size(); i++) {\n                cout << res[i] << \" \\n\"[i == (int) res.size() - 1];\n            }\n            return 0;\n        }\n    }\n    cout << \"NO\\n\";\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1264",
    "index": "C",
    "title": "Beautiful Mirrors with queries",
    "statement": "Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror \"Am I beautiful?\". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\\frac{p_i}{100}$ for all $1 \\le i \\le n$.\n\n\\textbf{Some mirrors are called checkpoints}. Initially, only the $1$st mirror is a checkpoint. It remains a checkpoint all the time.\n\nCreatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he asks $i$-th mirror, there are two possibilities:\n\n- The $i$-th mirror tells Creatnx that he is beautiful. In this case, if $i = n$ Creatnx will stop and become happy, otherwise he will continue asking the $i+1$-th mirror next day;\n- In the other case, Creatnx will feel upset. The next day, Creatnx will start asking \\textbf{from the checkpoint with a maximal number that is less or equal to $i$}.\n\n\\textbf{There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints}. You are given $q$ queries, each query is represented by an integer $u$: If the $u$-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the $u$-th mirror is no longer a checkpoint.\n\nAfter each query, you need to calculate the expected number of days until Creatnx becomes happy.\n\nEach of this numbers should be found by modulo $998244353$. Formally, let $M = 998244353$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Assuming that currently there are $k$ checkpoints $1 = x_1 < x_2 < \\ldots < x_k \\leq n$, the journey becoming happy of Creatnx can be divided to $k$ stages where in $i$-th stage Creatnx \"moving\" from mirror $x_i$ to mirror at position $x_{i+1} - 1$. Denote the $i$-th stage as $(x_i, x_{i+1}-1)$. These $k$ stages are independent so the sum of expected number of days Creatnx spending in each stage will be the answer to this problem. When a new checkpoint $b$ appear between 2 old checkpoints $a$ and $c$, stage $(a, c - 1)$ will be removed from the set of stages and 2 new stages will be added, they are $(a, b - 1)$ and $(b, c - 1)$. Similarly, when a checkpoint $b$ between 2 checkpoints $a$ and $c$ is no longer a checkpoint, 2 stages $(a, b - 1)$ and $(b, c - 1)$ will be removed from the set of stages and new stage $(a, c-1)$ will be added. These removed/added stages can be fastly retrieved by storing all checkpoints in an ordered data structure such as set in C++. For removed/added stages, we subtract/add its expected number of days from/to the current answer. We see that when a query occurs, the number of stages removed/added is small (just 3 in total). Therefore, if we can calculate the expected number of days for an arbitrary stage fast enough, we can answer any query in a reasonable time. From the solution of problem Beautiful Mirror, we know that the expected number of days Creatnx spending in stage $(u, v)$ is: $\\frac{1 + p_u + p_u \\cdot p_{u+1} + \\ldots + p_u \\cdot p_{u+1} \\cdot \\ldots \\cdot p_{v-1}}{p_u \\cdot p_{u+1} \\cdot \\ldots \\cdot p_v} = \\frac{A}{B}$ The denominator $B$ can be computed by using a prefix product array - a common useful trick. We prepare an array $s$ where $s_i = p_1 \\cdot p_2 \\cdot \\ldots \\cdot p_i$. After that, $B$ can be obtained by using 1 division: $B = \\frac{s_v}{s_{u-1}}$. For numerator $A$, we also use the same trick. An array $t$ will be prepare where $t_i = p_1 + p_1 \\cdot p_2 + \\ldots + p_1 \\cdot p_2 \\ldots \\cdot p_i$. We have $t_{v-1} = t_{u-2} + p_1\\cdot p_2 \\cdot\\ldots\\cdot p_{u-1} \\cdot A$ so $A = \\frac{t_{v-1} - t_{u-2}}{p_1\\cdot p_2 \\cdot\\ldots\\cdot p_{u-1}} = \\frac{t_{v-1} - t_{u-2}}{s_{u-1}}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 119 << 23 | 1;\n\nstruct node_t {\n    int prd;\n    int val;\n    node_t() {\n        prd = val = 0;\n    }\n};\n\nnode_t operator + (node_t a, node_t b) {\n    if (!a.prd) return b;\n    if (!b.prd) return a;\n    node_t c;\n    c.prd = (long long) a.prd * b.prd % MOD;\n    c.val = (long long) a.val * b.prd % MOD;\n    c.val = (c.val + b.val) % MOD;\n    return c;\n}\n\nint inv(int a) {\n    int r = 1, t = a, k = MOD - 2;\n    while (k) {\n        if (k & 1) r = (long long) r * t % MOD;\n        t = (long long) t * t % MOD;\n        k >>= 1;\n    }\n    return r;\n}\n\nint main() {\n    int n, q; cin >> n >> q;\n    vector<int> p(n);\n    for (int i = 0; i < n; i++) cin >> p[i], p[i] = (long long) p[i] * inv(100) % MOD;\n    vector<node_t> st(n << 2);\n    auto upd = [&] (int p, node_t val) {\n        for (st[p += n] = val; 1 < p; ) p >>= 1, st[p] = st[p << 1] + st[p << 1 | 1];\n    };\n    auto query = [&] (int l, int r) {\n        node_t lres, rres;\n        for (l += n, r += n + 1; l < r; l >>= 1, r >>= 1) {\n            if (l & 1) {\n                lres = lres + st[l++];\n            }\n            if (r & 1) {\n                rres = st[--r] + rres;\n            }\n        }\n        return (lres + rres).val;\n    };\n    for (int i = 0; i < n; i++) {\n        node_t c;\n        c.val = c.prd = inv(p[i]);\n        upd(i, c);\n    }\n    set<int> ss;\n    ss.insert(0);\n    int res = query(0, n - 1);\n    for (int i = 0; i < q; i++) {\n        string op; int u; cin >> u; u--;\n        auto it = ss.lower_bound(u);\n        if (it == ss.end() || *it != u) {\n            it = ss.insert(u).first;\n            int lo = *(--it);\n            it++;\n            int hi = n;\n            if (++it != ss.end()) {\n                hi = *it;\n            }\n            res -= query(lo, hi - 1);\n            res += MOD;\n            res %= MOD;\n            res += query(lo, u - 1);\n            res %= MOD;\n            res += query(u, hi - 1);\n            res %= MOD;\n        }\n        else {\n            int lo = *(--it);\n            it++;\n            int hi = n;\n            if (++it != ss.end()) {\n                hi = *it;\n            }\n            res += query(lo, hi - 1);\n            res %= MOD;\n            res -= query(lo, u - 1);\n            res += MOD;\n            res %= MOD;\n            res -= query(u, hi - 1);\n            res += MOD;\n            res %= MOD;\n            ss.erase(u);\n        }\n        cout << res << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1264",
    "index": "C",
    "title": "Beautiful Mirrors with queries",
    "statement": "Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror \"Am I beautiful?\". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\\frac{p_i}{100}$ for all $1 \\le i \\le n$.\n\n\\textbf{Some mirrors are called checkpoints}. Initially, only the $1$st mirror is a checkpoint. It remains a checkpoint all the time.\n\nCreatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he asks $i$-th mirror, there are two possibilities:\n\n- The $i$-th mirror tells Creatnx that he is beautiful. In this case, if $i = n$ Creatnx will stop and become happy, otherwise he will continue asking the $i+1$-th mirror next day;\n- In the other case, Creatnx will feel upset. The next day, Creatnx will start asking \\textbf{from the checkpoint with a maximal number that is less or equal to $i$}.\n\n\\textbf{There are some changes occur over time: some mirrors become new checkpoints and some mirrors are no longer checkpoints}. You are given $q$ queries, each query is represented by an integer $u$: If the $u$-th mirror isn't a checkpoint then we set it as a checkpoint. Otherwise, the $u$-th mirror is no longer a checkpoint.\n\nAfter each query, you need to calculate the expected number of days until Creatnx becomes happy.\n\nEach of this numbers should be found by modulo $998244353$. Formally, let $M = 998244353$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "We calculate the depth of a sequence as follow: Let two pointers at each end of the sequence. If character at the left pointer is ')', we move the left pointer one position to the right. If character at the right pointer is '(', we move the right pointer one position to the left. If the character at the left pointer is '(' and the right pointer is ')' we increase our result and move the left pointer to the right and the right one to the left each with one position. We repeat while the left one is at the left of the right one. $dp[l][r] += dp[l + 1][r]$ if $a_l \\ne$ '('. $dp[l][r] += dp[l][r - 1]$ if $a_r \\ne$ ')'. $dp[l][r] -= dp[l + 1][r - 1]$ if $a_l \\ne$ '(' and $a_r \\ne$ ')'. $dp[l][r] += dp[l + 1][r - 1] + 2^k$ if $a_l \\ne$ ')' and $a_r \\ne$ '(', where $k$ is the number of '?' character in $s_{l + 1}s_{l + 2}\\ldots s_{r - 1}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 119 << 23 | 1;\n\nint fpow(int a, int k) {\n    int r = 1, t = a;\n    while (k) {\n        if (k & 1) r = (long long) r * t % MOD;\n        t = (long long) t * t % MOD;\n        k >>= 1;\n    }\n    return r;\n}\n\nint main() {\n    string s; cin >> s;\n    int n = s.size();\n    vector<vector<int>> dp(n, vector<int>(n));\n    vector<int> f(n + 1);\n    for (int i = 0; i < n; i++) {\n        f[i + 1] = f[i];\n        f[i + 1] += s[i] == '?';\n    }\n    for (int len = 2; len <= n; len++) {\n        for (int i = 0; i < n - len + 1; i++) {\n            int j = i + len - 1;\n            if (s[i] != '(') {\n                dp[i][j] += dp[i + 1][j];\n                dp[i][j] %= MOD;\n            }\n            if (s[j] != ')') {\n                dp[i][j] += dp[i][j - 1];\n                dp[i][j] %= MOD;\n            }\n            if (s[i] != '(' && s[j] != ')') {\n                dp[i][j] -= dp[i + 1][j - 1];\n                dp[i][j] += MOD;\n                dp[i][j] %= MOD;\n            }\n            if (s[i] != ')' && s[j] != '(') {\n                dp[i][j] += dp[i + 1][j - 1];\n                dp[i][j] %= MOD;\n                dp[i][j] += fpow(2, f[j] - f[i + 1]);\n                dp[i][j] %= MOD;\n            }\n        }\n    }\n    cout << dp[0][n - 1] << \"\\n\";\n    return 0;\n}",
    "tags": [
      "data structures",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1264",
    "index": "D2",
    "title": "Beautiful Bracket Sequence (hard version)",
    "statement": "This is the hard version of this problem. The only difference is the limit of $n$ - the length of the input string. In this version, $1 \\leq n \\leq 10^6$.\n\nLet's define a correct bracket sequence and its depth as follow:\n\n- An empty string is a correct bracket sequence with depth $0$.\n- If \"s\" is a correct bracket sequence with depth $d$ then \"(s)\" is a correct bracket sequence with depth $d + 1$.\n- If \"s\" and \"t\" are both correct bracket sequences then their concatenation \"st\" is a correct bracket sequence with depth equal to the maximum depth of $s$ and $t$.\n\nFor a (not necessarily correct) bracket sequence $s$, we define its depth as the maximum depth of any \\textbf{correct} bracket sequence induced by removing some characters from $s$ (possibly zero). For example: the bracket sequence $s = $\"())(())\" has depth $2$, because by removing the third character we obtain a correct bracket sequence \"()(())\" with depth $2$.\n\nGiven a string $a$ consists of only characters '(', ')' and '?'. Consider all (not necessarily correct) bracket sequences obtained by replacing all characters '?' in $a$ by either '(' or ')'. Calculate the sum of all the depths of all these bracket sequences. As this number can be large, find it modulo $998244353$.\n\n\\textbf{Hacks} in this problem can be done only if easy and hard versions of this problem was solved.",
    "tutorial": "By the way calculate the depth in easy version we can construct a maximal depth correct bracket $S$. At $i$-th position containing '(' or '?' we will count how many times it appears in $S$. Let $x$ be the number of '(' before the $i$-th position, $y$ be the number of ')' after the $i$-th position, $c$ be the number of '?' before the $i$-th position and $d$ be the number of '?' after the $i$-th position. The $i$-th position appears in $S$ iff the number of '(' before the $i$-th position must less than the number of ')' after the $i$-th position. So we can derive a mathematics formula: $\\sum_{a + i < b + j}{C(c, i)\\cdot C(d, j)} = \\sum_{a + i < b + j}{C(c, i)\\cdot C(d, d - j)} = \\sum_{i + j < b + d - a}{C(c, i)\\cdot C(d, j)}$. Expanding both hand sides of indentity $(x + 1)^{c + d} = (x + 1)^c\\cdot (x + 1)^d$, the above sum is simplified as: $\\sum_{0\\le i < b + d - a}{C(c + d, i)}$. Notice that $c + d$ doesn't change much, it only is one of two possible values. So we can prepare and obtain $O(N)$ complexity.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 119 << 23 | 1;\n\nint inv(int a) {\n    int r = 1, t = a, k = MOD - 2;\n    while (k) {\n        if (k & 1) r = (long long) r * t % MOD;\n        t = (long long) t * t % MOD;\n        k >>= 1;\n    }\n    return r;\n}\n\nint main() {\n    string s; cin >> s;\n    int k = s.size() + 1;\n    int a = 0, b = 0, c = 0, d = 0;\n    for (char e : s) {\n        if (e == ')') {\n            b++;\n        }\n        if (e == '?') {\n            d++;\n        }\n    }\n    map<int, vector<int>> dps;\n    auto calc = [&] (int a, int b, int c, int d) {\n        int x = b + d - a;\n        if (x < 0) return 0;\n        int k = c + d;\n        if (k < x) x = k;\n        if (dps.count(k)) return dps[k][x];\n        auto& dp = dps[k];\n        dp.resize(k + 1);\n        int t = 0, w = 1;\n        for (int i = 0; i <= k; i++) {\n            t += w;\n            t %= MOD;\n            dp[i] = t;\n            w = (long long) w * (c + d - i) % MOD;\n            w = (long long) w * inv(i + 1) % MOD;\n        }\n        return dp[x];\n    };\n    int res = 0;\n    for (int i = 0; i < (int) s.size(); i++) {\n        char e = s[i];\n        if (e == '(') {\n            a++;\n        }\n        if (e == ')') {\n            b--;\n        }\n        if (e == '?') {\n            c++;\n            d--;\n        }\n        if (e == '(') {\n            res += calc(a, b, c, d);\n            res %= MOD;\n        }\n        else if (e == '?') {\n            a++, c--;\n            res += calc(a, b, c, d);\n            res %= MOD;\n            a--, c++;\n        }\n    }\n    cout << res << \"\\n\";\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1264",
    "index": "E",
    "title": "Beautiful League",
    "statement": "A football league has recently begun in Beautiful land. There are $n$ teams participating in the league. Let's enumerate them with integers from $1$ to $n$.\n\nThere will be played exactly $\\frac{n(n-1)}{2}$ matches: each team will play against all other teams exactly once. In each match, there is always a winner and loser and there is no draw.\n\nAfter all matches are played, the organizers will count the number of beautiful triples. Let's call a triple of three teams $(A, B, C)$ beautiful if a team $A$ win against a team $B$, a team $B$ win against a team $C$ and a team $C$ win against a team $A$. We look only to a triples of different teams and the order of teams in the triple is important.\n\nThe beauty of the league is the number of beautiful triples.\n\nAt the moment, $m$ matches were played and their results are known.\n\nWhat is the maximum beauty of the league that can be, after playing all remaining matches? Also find a possible results for all remaining $\\frac{n(n-1)}{2} - m$ matches, so that the league has this maximum beauty.",
    "tutorial": "Firstly, Let's calculate the number of non-beautiful triples given all result of matches. It is obvious that for each non-beautiful triple $(A, B, C)$ there exactly is one team that wins over the others. So if a team $A$ wins $k$ other teams $B_1, B_2,\\ldots, B_k$ then team A corresponds to $\\frac{k\\cdot (k - 1)}{2}$ non-beautiful triple $(A, B_i, B_j)$. If we define $(p_1, p_2,\\ldots, p_n)$ as the number of wins of $n$ teams. Then the number of non-beautiful triples will be $\\frac{p_1\\cdot (p_1 - 1) + p_2\\cdot (p_2 - 1) +\\ldots+ p_n\\cdot (p_n - 1)}{2}$. Notice that $p_1 + p_2 +\\ldots+ p_n = \\frac{n\\cdot (n - 1)}{2}$. So we only need to minimize the square sum: $p_1^2 + p_2^2 +\\ldots+ p_n^2$. The remain can be solved easily by Mincost-Maxflow: Creating source $S$, sink $T$, each 'match node' for each match haven't played yet, each 'team node' for each team. Add an edge between source $S$ and each 'match node' with capacity $1$ cost $0$. Add an edge between each 'match node' and each of two 'team nodes' with capacity $1$ cost $0$. Assuming, after $m$ matches played, $i$-th team wins $q_i$ matches. We add $n - q_i - 1$ edges between the $i$-th 'team node' and sink $T$ with capacity $1$ and costs $2\\cdot q_i + 1, 2\\cdot q_i + 3,\\ldots, 2\\cdot n - 1$. The min cost after run Mincost-Maxflow plus $q_1^2 + q_2^2 +\\ldots+ q_n^2$ will give us the minimal square sum. Base on Mincost-Maxflow idea, we can solve in more sophisticated way. At any moment, we will try to pick a team with minimal number of wins. Then we try to give it one more win by setting result of a match (that haven't used so far) and possibly changing results of a path of matches to keep the number of win of others. If not pick next one and so on. Complexity: $O(N^4)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int n, m; cin >> n >> m;\n    vector<int> d(n);\n    vector<vector<int>> g(n, vector<int>(n));\n    vector<vector<int>> f(n, vector<int>(n, 1));\n    for (int i = 0; i < m; i++) {\n        int u, v; cin >> u >> v; u--, v--;\n        d[u]++;\n        g[u][v] = 1, g[v][u] = 2;\n        f[u][v] = f[v][u] = 0;\n    }\n    priority_queue<pair<int, int>> heap;\n    for (int i = 0; i < n; i++) {\n        if (d[i] < n - 1) {\n            heap.push({-d[i], i});\n        }\n    }\n    while (!heap.empty()) {\n        int u = heap.top().second;\n        heap.pop();\n        queue<int> que;\n        vector<int> vis(n), from(n);\n        que.push(u), vis[u] = 1;\n        int id = -1;\n        while (!que.empty()) {\n            int v = que.front(); que.pop();\n            int found = 0;\n            for (int w = 0; w < n; w++) if (w != v && !g[v][w]) {\n                found = 1;\n                break;\n            }\n            if (found) {\n                id = v;\n                break;\n            }\n            for (int w = 0; w < n; w++) if (!vis[w] && g[v][w] == 2 && f[v][w] == 1) {\n                que.push(w), vis[w] = 1;\n                from[w] = v;\n            }\n        }\n        if (id == -1) {\n            continue;\n        }\n        for (int v = 0; v < n; v++) if (v != id && !g[id][v]) {\n            g[id][v] = 1, g[v][id] = 2;\n            break;\n        }\n        while (id != u) {\n            int nid = from[id];\n            swap(g[id][nid], g[nid][id]);\n            id = nid;\n        }\n        d[u]++;\n        if (d[u] < n - 1) {\n            heap.push({-d[u], u});\n        }\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            if (i == j) {\n                cout << 0;\n            }\n            else {\n                cout << 2 - g[i][j];\n            }\n        }\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "flows",
      "graph matchings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1264",
    "index": "F",
    "title": "Beautiful Fibonacci Problem",
    "statement": "The well-known Fibonacci sequence $F_0, F_1, F_2,\\ldots $ is defined as follows:\n\n- $F_0 = 0, F_1 = 1$.\n- For each $i \\geq 2$: $F_i = F_{i - 1} + F_{i - 2}$.\n\nGiven an increasing arithmetic sequence of positive integers with $n$ elements: $(a, a + d, a + 2\\cdot d,\\ldots, a + (n - 1)\\cdot d)$.\n\nYou need to find another increasing arithmetic sequence of positive integers with $n$ elements $(b, b + e, b + 2\\cdot e,\\ldots, b + (n - 1)\\cdot e)$ such that:\n\n- $0 < b, e < 2^{64}$,\n- for all $0\\leq i < n$, the decimal representation of $a + i \\cdot d$ appears as substring in the last $18$ digits of the decimal representation of $F_{b + i \\cdot e}$ (if this number has less than $18$ digits, then we consider all its digits).",
    "tutorial": "Intuitively, we want to a formula for $F_{m + n}$. This is one we need: $F_{m + n} = F_m\\cdot F_{n + 1} + F_{m - 1}\\cdot F_n$. Denote $n = 12\\cdot 10^k$, one can verify that $F_{i\\cdot n} \\equiv 0$ modulo $10^k$ (directly calculate or use 'Pisano Period'). So we have following properties: $F_{2\\cdot n + 1} = F_{n + 1}^2 + F_n^2$ $\\Rightarrow F_{2\\cdot n + 1} = F_{n + 1}^2$ modulo $10^{2\\cdot k}$. $F_{3\\cdot n + 1} = F_{2\\cdot n + 1}\\cdot F_{n + 1} + F_{2\\cdot n}\\cdot F_n$ $\\Rightarrow F_{3\\cdot n + 1} = F_{n + 1}^3$ modulo $10^{2\\cdot k}$. So on, $F_{u\\cdot n + 1} = F_{n + 1}^u$ modulo $10^{2\\cdot k}$. Notice that $F_{n + 1} = 8\\cdot 10^k\\cdot t + 1$, where $gcd(t, 10) = 1$. So $F_{u\\cdot n + 1} = (8\\cdot 10^k\\cdot t + 1)^u = 8\\cdot u\\cdot t\\cdot 10^k + 1$ modulo $10^{2\\cdot k}$. Let $u = 125.a.t^{-1}$ modulo $10^k$, $v = 125.d.t^{-1}$ modulo $10^k$. Then we choose $b = u\\cdot n + 1, e = v\\cdot n$.",
    "code": "n,a,d=map(int,input().split())\nprint(368131125*a%10**9*12*10**9+1,368131125*d%10**9*12*10**9)\n",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1265",
    "index": "A",
    "title": "Beautiful String",
    "statement": "A string is called beautiful if no two consecutive characters are equal. For example, \"ababcb\", \"a\" and \"abab\" are beautiful strings, while \"aaaaaa\", \"abaa\" and \"bb\" are not.\n\nAhcl wants to construct a beautiful string. He has a string $s$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!\n\nMore formally, after replacing all characters '?', the condition $s_i \\neq s_{i+1}$ should be satisfied for all $1 \\leq i \\leq |s| - 1$, where $|s|$ is the length of the string $s$.",
    "tutorial": "If string $s$ initially contains 2 equal consecutive letters (\"aa\", \"bb\" or \"cc\") then the answer is obviously -1. Otherwise, it is always possible to replacing all characters '?' to make $s$ beautiful. We will replacing one '?' at a time and in any order (from left to right for example). For each '?', since it is adjacent to at most 2 other characters and we have 3 options ('a', 'b' and 'c') for this '?', there always exists at least one option which differ from 2 characters that are adjacent with this '?'. Simply find one and replace '?' by it. Time comlexity: $\\mathcal{O}(n)$ where $n$ is length of $s$.",
    "code": "T = int(input())\nfor tc in range(T):\n    s = [c for c in input()]\n    n = len(s)\n    i = 0\n    while (i < n):\n        if (s[i] == '?'):\n            prv = 'd' if i == 0 else s[i - 1]\n            nxt = 'e' if i + 1 >= n else s[i + 1]\n            for x in ['a', 'b', 'c']:\n                if (x != prv) and (x != nxt):\n                    s[i] = x\n                    break\n        else:\n            i += 1\n           \n    ok = True \n    for i in range(n - 1):\n        if (s[i] == s[i + 1]):\n            print(\"-1\")\n            ok = False\n            break\n    if (ok == True):  \n        print(\"\".join(s))",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1265",
    "index": "B",
    "title": "Beautiful Numbers",
    "statement": "You are given a permutation $p=[p_1, p_2, \\ldots, p_n]$ of integers from $1$ to $n$. Let's call the number $m$ ($1 \\le m \\le n$) beautiful, if there exists two indices $l, r$ ($1 \\le l \\le r \\le n$), such that the numbers $[p_l, p_{l+1}, \\ldots, p_r]$ is a permutation of numbers $1, 2, \\ldots, m$.\n\nFor example, let $p = [4, 5, 1, 3, 2, 6]$. In this case, the numbers $1, 3, 5, 6$ are beautiful and $2, 4$ are not. It is because:\n\n- if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$;\n- if $l = 3$ and $r = 5$ we will have a permutation $[1, 3, 2]$ for $m = 3$;\n- if $l = 1$ and $r = 5$ we will have a permutation $[4, 5, 1, 3, 2]$ for $m = 5$;\n- if $l = 1$ and $r = 6$ we will have a permutation $[4, 5, 1, 3, 2, 6]$ for $m = 6$;\n- it is impossible to take some $l$ and $r$, such that $[p_l, p_{l+1}, \\ldots, p_r]$ is a permutation of numbers $1, 2, \\ldots, m$ for $m = 2$ and for $m = 4$.\n\nYou are given a permutation $p=[p_1, p_2, \\ldots, p_n]$. For all $m$ ($1 \\le m \\le n$) determine if it is a beautiful number or not.",
    "tutorial": "A number $m$ is beautiful if and only if all numbers in range $[1, m]$ occupies $m$ consecutive positions in the given sequence $p$. This is equivalent to $pos_{max} - pos_{min} + 1 = m$ where $pos_{max}, pos_{min}$ are the largest, smallest position of $1, 2, \\dots, m$ in sequence $p$ respectively. We will consider $m$ in increasing order, that its $m = 1, 2, \\ldots, n$. For each $m$ we will find a way to update $pos_{max}, pos_{min}$ so we can tell either $m$ is a beautiful number or not in constant time. Denote $pos_i$ is the position of number $i$ in the sequence $p$. When $m=1$, we have $pos_{max} = pos_{min} = pos_1$. When $m>1$, the value of $pos_{max}, pos_{min}$ can be updated by the following formula: $new\\_pos_{max} = max(old\\_pos_{max}, pos_m)$ $new\\_pos_{min} = min(old\\_pos_{min}, pos_m)$ Total time comlexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int M = 2e5 + 239;\n\nint n, p[M], x;\n\nvoid solve()\n{\n    cin >> n;\n    for (int i = 0; i < n; i++)\n    {\n        cin >> x;\n        p[x - 1] = i;\n    }\n    int l = n;\n    int r = 0;\n    string ans = \"\";\n    for (int i = 0; i < n; i++)\n    {\n        l = min(l, p[i]);\n        r = max(r, p[i]);\n        if (r - l == i)\n            ans += '1';\n        else\n            ans += '0';\n    }\n    cout << ans << \"\\n\";\n}\n\nint main()\n{\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n    return 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1265",
    "index": "E",
    "title": "Beautiful Mirrors",
    "statement": "Creatnx has $n$ mirrors, numbered from $1$ to $n$. Every day, Creatnx asks exactly one mirror \"Am I beautiful?\". The $i$-th mirror will tell Creatnx that he is beautiful with probability $\\frac{p_i}{100}$ for all $1 \\le i \\le n$.\n\nCreatnx asks the mirrors one by one, starting from the $1$-st mirror. Every day, if he asks $i$-th mirror, there are two possibilities:\n\n- The $i$-th mirror tells Creatnx that he is beautiful. In this case, if $i = n$ Creatnx will stop and become happy, otherwise he will continue asking the $i+1$-th mirror next day;\n- In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the $1$-st mirror again.\n\nYou need to calculate the expected number of days until Creatnx becomes happy.\n\nThis number should be found by modulo $998244353$. Formally, let $M = 998244353$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Let $p_i$ be the probability that the $i$-th mirror will answer YES when it is asked. That is, this $p_i$ equals to $p_i$ in the problem statement divide by 100. Let $e_i$ be the expected number of days until Creatnx becomes happy when initially he is at the $i$-th mirror. For convenient, let $e_{n+1} = 0$ (because when Creatnx is at $(n+1)$-th mirror he is happy already). The answer of the problem will be $e_1$. By the definition of expectation value and its basic properties, the following must holds for all $1 \\leq i \\leq n$: $e_i = 1 + p_i \\cdot e_{i+1} + (1-p_i)\\cdot e_1$ Let explain this equation for those who are not familiar with probability. Expectation value is just average of all possible outcomes. The first number 1 in the right hand side means Creatnx spends 1 day to ask the $i$-th mirror. With probability of $p_i$ the $i$-th mirror will answer YES and Creatnx will move to the $(i+1)$-th mirror in the next day. At the $(i+1)$-th mirror, Creatnx on average needs to spend $e_{i+1}$ days more to become happy. The second term $p_i \\cdot e_{i+1}$ explains this case. Similarly, the third term $(1-p_i)\\cdot e_1$ represents the case where the $i$-th mirror answers NO. To find $e_1$ we need to solve $n$ equations: (1) $e_1 = 1 + p_1 \\cdot e_2 + (1-p_1)\\cdot e_1$ (2) $e_2 = 1 + p_2 \\cdot e_3 + (1-p_2)\\cdot e_1$ $\\ldots$ ($n$) $e_n = 1 + p_n \\cdot e_{n+1} + (1-p_n)\\cdot e_1$ We can solve this system of equations by using substitution - a common technique. From equation (1) we have $e_2 = e_1 - \\frac{1}{p_1}$. Substituting this in (2) we obtained $e_3=e_1-\\frac{1}{p_1 \\cdot p_2} - \\frac{1}{p_2}$. See the pattern now? Similarly by substituting to that last equation we have: $0 = e_{n+1}=e_1 - \\frac{1}{p_1\\cdot p_2 \\cdot \\ldots \\cdot p_n} - \\frac{1}{p_2\\cdot p_3 \\cdot \\ldots \\cdot p_n} - \\ldots - \\frac{1}{p_n}$ $e_1 = \\frac{1}{p_1\\cdot p_2 \\cdot \\ldots \\cdot p_n} + \\frac{1}{p_2\\cdot p_3 \\cdot \\ldots \\cdot p_n} + \\ldots + \\frac{1}{p_n}$ $e_1 = \\frac{1 + p_1 + p_1 \\cdot p_2 + \\ldots + p_1\\cdot p_2 \\cdot \\ldots \\cdot p_{n-1}}{p_1\\cdot p_2 \\cdot \\ldots \\cdot p_n}$ We can compute $e_1$ according to the above formula in $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 119 << 23 | 1;\n\nint inv(int a) {\n    int r = 1, t = a, k = MOD - 2;\n    while (k) {\n        if (k & 1) r = (long long) r * t % MOD;\n        t = (long long) t * t % MOD;\n        k >>= 1;\n    }\n    return r;\n}\n\nint main() {\n    int n; cin >> n;\n    vector<int> p(n);\n    for (int i = 0; i < n; i++) cin >> p[i], p[i] = (long long) p[i] * inv(100) % MOD;\n    int a = 1, b = 0;\n    for (int i = 0; i < n; i++) {\n        a = (long long) a * inv(p[i]) % MOD;\n        b = (long long) b * inv(p[i]) % MOD;\n        a = (a + (long long) (p[i] - 1) * inv(p[i])) % MOD;\n        b = (b - inv(p[i]) + MOD) % MOD;\n    }\n    cout <<  (long long) (MOD - b) * inv(a) % MOD << \"\\n\";\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1266",
    "index": "A",
    "title": "Competitive Programmer",
    "statement": "Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked $n$ of them how much effort they needed to reach red.\n\n\"Oh, I just spent $x_i$ \\textbf{hours} solving problems\", said the $i$-th of them.\n\nBob wants to train his math skills, so for each answer he wrote down the number of \\textbf{minutes} ($60 \\cdot x_i$), thanked the grandmasters and went home. Bob could write numbers with leading zeroes — for example, if some grandmaster answered that he had spent $2$ hours, Bob could write $000120$ instead of $120$.\n\nAlice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently:\n\n- rearranged its digits, or\n- wrote a random number.\n\nThis way, Alice generated $n$ numbers, denoted $y_1$, ..., $y_n$.\n\nFor each of the numbers, help Bob determine whether $y_i$ can be a permutation of a number divisible by $60$ (possibly with leading zeroes).",
    "tutorial": "Thanks to Chinese remainder theorem, a number is divisible by $60$ if and only if it is divisible by $3$ and $20$. A number is divisible by $3$ if and only if the sum of its digits is divisible by $3$. Note that as the sum doesn't change if we reorder digits, it applies also to the sum of digits of $s$. A number is divisible by $20$ if it ends in $20$, $40$, $60$, $80$ or $00$. Hence, it is necessary and sufficient if $s$ contains a $0$ and then at least one additional even digit. Overall, there are three conditions to check: The digit sum is divisible by $3$. There is at least a single $0$. There are at least two even digits (including $0$s).",
    "tags": [
      "chinese remainder theorem",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1266",
    "index": "B",
    "title": "Dice Tower",
    "statement": "Bob is playing with $6$-sided dice. A net of such standard cube is shown below.\n\nHe has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.\n\nFor example, the number of visible pips on the tower below is $29$ — the number visible on the top is $1$, from the south $5$ and $3$, from the west $4$ and $2$, from the north $2$ and $4$ and from the east $3$ and $5$.\n\nThe one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.\n\nBob also has $t$ favourite integers $x_i$, and for every such integer his goal is to build such a tower that the number of visible pips is exactly $x_i$. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.",
    "tutorial": "Consider a die other than the top-most one. As the sum of numbers on the opposite faces of a die is always $7$, the sum of numbers on the visible faces is always $14$, regardless of its orientation. For the top-most die, the numbers on the sides also add up to $14$, and there is an additional number on top of the die. The total number of visible pips is thus $14d + t$, where $d$ is the number of dice and $t$ is the number on top. For a given $x$, compute $t = x \\bmod 14$ and $d = \\lfloor \\frac{x}{14} \\rfloor$. The answer is positive if and only if $d \\geq 1$ and $1 \\leq t \\leq 6$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1266",
    "index": "C",
    "title": "Diverse Matrix",
    "statement": "Let $a$ be a matrix of size $r \\times c$ containing positive integers, not necessarily distinct. Rows of the matrix are numbered from $1$ to $r$, columns are numbered from $1$ to $c$. We can construct an array $b$ consisting of $r + c$ integers as follows: for each $i \\in [1, r]$, let $b_i$ be the greatest common divisor of integers in the $i$-th row, and for each $j \\in [1, c]$ let $b_{r+j}$ be the greatest common divisor of integers in the $j$-th column.\n\nWe call the matrix \\textbf{diverse} if all $r + c$ numbers $b_k$ ($k \\in [1, r + c]$) are pairwise distinct.\n\nThe \\textbf{magnitude} of a matrix equals to the maximum of $b_k$.\n\nFor example, suppose we have the following matrix:\n\n\\begin{center}\n$\\begin{pmatrix} 2 & 9 & 7\\\\ 4 & 144 & 84 \\end{pmatrix}$\n\\end{center}\n\nWe construct the array $b$:\n\n- $b_1$ is the greatest common divisor of $2$, $9$, and $7$, that is $1$;\n- $b_2$ is the greatest common divisor of $4$, $144$, and $84$, that is $4$;\n- $b_3$ is the greatest common divisor of $2$ and $4$, that is $2$;\n- $b_4$ is the greatest common divisor of $9$ and $144$, that is $9$;\n- $b_5$ is the greatest common divisor of $7$ and $84$, that is $7$.\n\nSo $b = [1, 4, 2, 9, 7]$. All values in this array are distinct, so the matrix is diverse. The magnitude is equal to $9$.\n\nFor a given $r$ and $c$, find a diverse matrix that minimises the magnitude. If there are multiple solutions, you may output any of them. If there are no solutions, output a single integer $0$.",
    "tutorial": "As the example reveals, the case when $r = c = 1$ is impossible. It turns out that this is the only impossible case. We will prove this by providing a construction that always achieves a magnitude of $r + c$. If $r = 1$, one optimal solution is $A = (2, 3, \\dots, c+1)$. The case where $c = 1$ is similar. Assume $r, c \\geq 2$ and assign $a_{i,j} = i * (j+r)$. We can now show that the gcd of the $i$-th row equals to $i$: $b_i = \\mathrm{gcd}\\left\\{i * (r+1), i * (r+2), \\dots i * (r+c)\\right\\} = i \\cdot \\mathrm{gcd}\\left\\{r+1, r+2, \\dots, r+c \\right\\}$ As $r+1$ and $r+2$ are coprime, $b_i = i$. Similarly, we can show that $b_{r+j}$ = $r + j$. To summarise, $b_k = k$ for all $k$, hence all row and column gcds are pairwise distinct, and the maximum is $r + c$. As the magnitude is a maximum of $r + c$ pairwise distinct positive integers, $r + c$ is optimal.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1266",
    "index": "D",
    "title": "Decreasing Debts",
    "statement": "There are $n$ people in this world, conveniently numbered $1$ through $n$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $d(a,b)$ denote the debt of $a$ towards $b$, or $0$ if there is no such debt.\n\nSometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money.\n\nWhen this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done:\n\n- Let $d(a,b) > 0$ and $d(c,d) > 0$ such that $a \\neq c$ or $b \\neq d$. We can decrease the $d(a,b)$ and $d(c,d)$ by $z$ and increase $d(c,b)$ and $d(a,d)$ by $z$, where $0 < z \\leq \\min(d(a,b),d(c,d))$.\n- Let $d(a,a) > 0$. We can set $d(a,a)$ to $0$.\n\nThe total debt is defined as the sum of all debts:\n\n$$\\Sigma_d = \\sum_{a,b} d(a,b)$$\n\nYour goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the \\textbf{number} of non-zero debts, only the \\textbf{total debt}.",
    "tutorial": "Consider a solution which minimises the total debt. Assume for contradiction that there is a triple of vertices $u \\neq v \\neq w$, such that $d(u,v) > 0$ and $d(v,w) > 0$. We can use the first rule with $a = u$, $b = c = v$, $d = w$ and $z = min(d(u,v), d(v,w))$ and then the second rule with $a = v$ and the same $z$. We have just reduced the total debt by $z$, which is a contradiction. So, there cannot be such a triple, in particular there cannot be a vertex $v$ that has both incoming and outgoing debt. Hence, every vertex has only outgoing edges or only incoming ones. Define $bal(u) = \\sum_v d(u,v) - \\sum_v d(v,u)$ to be the balance of $u$. Any application of either rule preserves balance of all vertices. It follows that any solution in which every vertex has either outgoing or incoming edges is constructible using finite number of applications of rules. This means that we can just find balances, and greedily match vertices with positive balance to vertices with negative balance. The total debt is then $\\Sigma_d = \\frac{\\sum_v |bal(v)|}{2}$ and it is clear that we cannot do better than that.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs",
      "greedy",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1266",
    "index": "E",
    "title": "Spaceship Solitaire",
    "statement": "Bob is playing a game of Spaceship Solitaire. The goal of this game is to build a spaceship. In order to do this, he first needs to accumulate enough resources for the construction. There are $n$ types of resources, numbered $1$ through $n$. Bob needs at least $a_i$ pieces of the $i$-th resource to build the spaceship. The number $a_i$ is called \\textbf{the goal for resource $i$}.\n\nEach resource takes $1$ turn to produce and in each turn only one resource can be produced. However, there are certain milestones that speed up production. Every milestone is a triple $(s_j, t_j, u_j)$, meaning that as soon as Bob has $t_j$ units of the resource $s_j$, he receives one unit of the resource $u_j$ for free, without him needing to spend a turn. It is possible that getting this free resource allows Bob to claim reward for another milestone. This way, he can obtain a large number of resources in a single turn.\n\nThe game is constructed in such a way that there are never two milestones that have the same $s_j$ \\textbf{and} $t_j$, that is, the award for reaching $t_j$ units of resource $s_j$ is at most one additional resource.\n\n\\textbf{A bonus is never awarded for $0$ of any resource, neither for reaching the goal $a_i$ nor for going past the goal — formally, for every milestone $0 < t_j < a_{s_j}$.}\n\nA bonus for reaching certain amount of a resource can be the resource itself, that is, $s_j = u_j$.\n\nInitially there are no milestones. You are to process $q$ updates, each of which adds, removes or modifies a milestone. After every update, output the minimum number of turns needed to finish the game, that is, to accumulate at least $a_i$ of $i$-th resource for each $i \\in [1, n]$.",
    "tutorial": "Consider a fixed game. Let $m_i$ be the total number of milestones having $u_j = i$, that is, the maximum possible number of \"free\" units of resource $i$ that can be obtained. We claim that in optimal solution, we (manually) produce this resource exactly $p_i = \\max\\left(a_i - m_i, 0\\right)$ times. It is obvious that we cannot do better and this number is necessary. Let's prove that it is also sufficient. First remove arbitrary milestones such that $a_i \\geq m_i$ for all $i$. This clearly cannot make the production work faster. Now, $p_i + m_i = a_i$ holds for each resource. Let's perform the production of $p_i$ units for all $i$ in arbitrary order and let $c_i$ be the total amount of $i$-th resource after this process finishes. Clearly $c_i \\leq a_i$. Assume for contradiciton that for a resource $i$ we have $c_i < a_i$, that is, the goal has not been reached. As we performed all $p_i$ manual productions for this resource, it means that we did not reach $a_i - c_i$ milestones claiming this resource. The total number of unclaimed awards is thus: $\\sum (a_i - c_i)$ Where are the milestones corresponding to these awards? Clearly, they can only be of form $(i, j, k)$ for $j > c_i$, otherwise we would have claimed them. There is never an award for reaching the goal, so the total number of positions for unreached milestones is $\\sum \\max(0, a_i - c_i - 1)$ As there is always at most one award for reaching a milestone, the number of unclaimed awards is at most the number of milestones not reached: $\\sum (a_i - c_i) \\leq \\sum \\max(0, a_i - c_i - 1)$ As $a_i \\geq c_i$, this is equivalent to $\\sum (a_i - c_i) \\leq \\sum_{a_i > c_i} (a_i - c_i - 1) + \\sum_{a_i = c_i} (a_i - c_i) = \\sum (a_i - c_i) - \\left|\\{i \\colon a_i > c_i\\}\\right|$ Subtracting $\\sum (a_i - c_i)$ from both sides and rearranging yields $\\left|\\{i \\colon a_i > c_i\\}\\right| \\leq 0$ so the number of resources that did not reach their goal is $0$, which is a contradiction. From here the solution is simple. We need to maintain all $m_i$ and the sum of $p_i$. Each update changes at most two $m_i$, so the total complexity is $\\mathcal O(n)$.",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1266",
    "index": "F",
    "title": "Almost Same Distance",
    "statement": "Let $G$ be a simple graph. Let $W$ be a non-empty subset of vertices. Then $W$ is \\textbf{almost-$k$-uniform} if for each pair of distinct vertices $u,v \\in W$ the distance between $u$ and $v$ is either $k$ or $k+1$.\n\nYou are given a tree on $n$ vertices. For each $i$ between $1$ and $n$, find the maximum size of an almost-$i$-uniform set.",
    "tutorial": "There are three cases of how an almost-$k$-uniform set looks like depending on the value of $k$. The first case is when $k = 1$. In this case, any maximal almost-$1$-uniform set is a vertex plus all of its neighbours. We can simply check each vertex and find the one with the highest degree. The second case is when $k$ is odd and greater than one: $k = 2l + 1$ for $l \\geq 1$. Then any almost-$k$-uniform set looks as follows. There is a middle vertex $v$, and every $w \\in W$ has distance of $l$ or $l+1$ from $v$. Additionally, at most one of the vertices is in distance $l$, and each $w$ is in a different subtree of $w$. The third case is when $k$ is even: $k = 2l$ for $l \\geq 1$. Then any almost-$k$-uniform set can be constructed in one of two ways. The first is similar to the previous case, except that all vertices have to be at distance of exactly $l$ from the middle vertex. The second construction begins by selecting a middle edge $\\{u, v\\}$, removing it from the tree and then finding a set of vertices $W$ such that each $w \\in W$ is in the distance of $l$ from either $u$ or $v$ (depending in which subtree it is) and each $w$ is in a different subtree of $u$ or $v$. Now we need to figure out how to make these constructions efficiently. We begin by calculating $d_v(u)$ - the depth of a subtree $u$ when the tree is rooted at $v$. We compute this for each edge $\\{u, v\\}$ by using the standard technique of two DFS traversals. Furthermore we use the fact that the answer is monotone with respect to parity: $Ans[i+2] \\leq Ans[i]$ for all $i$ - we only calculate the answer in some \"interesting\" points and then preserve this inequality in the end by taking suffix maximums. For the odd case, consider a middle vertex $v$. Sort the depths of subtrees of neighbours of $v$. Then, $Ans[2*l+1] \\geq x$ if there are at $x-1$ subtrees of depth at least $l+1$ and one additional subtree of depth $l$ or more. By sorting the depths, we can process each middle vertex in $\\mathcal O(\\mathrm{deg}_v \\log \\mathrm{deg}(v))$. In total, we have $\\mathcal O(n \\log n)$ for this step. For the even case there are two options. The first of these is very similar to the above construction, we just look for $x$ subtrees of depth at least $l$. The second option is more involved. Consider a middle edge $\\{u,v\\}$. Let $x$ be the number of $d_u(w) \\geq l$ for $w \\neq v$ and $y$ be the number of $d_v(w) \\geq l$ for $w \\neq u$. Then we can conclude that $Ans[2*l] \\geq x + y$. However, we cannot directly calculate the above quantity for each edge, as the processing of each vertex would take time quadratic in its degree. We will do a series of steps to improve upon this. The first optimization is that in the process of finding $x$ and $y$ above, we also consider $d_v(u)$ and $d_u(v)$, but then subtract $2$ from the answer. Why can we do that? First see that this case is only important if both $x \\geq 1$ and $y \\geq 1$ - otherwise this is the middle vertex case that is already processed. This means that $\\max d_v(w) \\geq l$ and hence $d_u(v) \\geq l+1 \\geq l$. This means that adding $d_u(v)$ to the set increases $x$ by one. The same argument shows that $y$ increases by $1$. How does this modification help us? There are two ways of proceeding now. We can fix $v$ as one of the endpoints of the middle edge and merge the subtree depths from individual subtrees by taking the maximum and process all neighbours of $u$ at the same time. This alone still does not change the complexity, because we still process each vertex once for each of its neighbours, and this processing takes time at least linear in the degree. Now comes the final step.Perform a centroid decomposition of the tree. When processing $v$ as the fixed end of the middle vertex, consider all $d_v(w)$ for the almost-$k$-universal set, but as the other endpoint of the middle edge we consider only the vertices in the tree where $v$ is the centroid. This way, each middle edge is processed exactly once. Each individual vertex is processed once when it is centroid and then once within each centroid tree it belongs to. Since the depth of centroid decomposition is $\\mathcal O(\\log n)$, we only process each vertex $\\mathcal O(\\log n)$ times. A single processing every vertex costs $\\mathcal O(\\mathrm{deg}_v \\log \\mathrm{deg}_v)$ time (because of sorting the degrees). Thus the total running time is $\\mathcal O(n \\log^2 n)$, which is the most expensive part of the algorithm. We can also replace the sort with parallel counting sort, and this makes the time $\\mathcal O(n \\log n)$, but that doesn't run faster in practice. Perform a centroid decomposition of the tree. When processing $v$ as the fixed end of the middle vertex, consider all $d_v(w)$ for the almost-$k$-universal set, but as the other endpoint of the middle edge we consider only the vertices in the tree where $v$ is the centroid. This way, each middle edge is processed exactly once. Each individual vertex is processed once when it is centroid and then once within each centroid tree it belongs to. Since the depth of centroid decomposition is $\\mathcal O(\\log n)$, we only process each vertex $\\mathcal O(\\log n)$ times. A single processing every vertex costs $\\mathcal O(\\mathrm{deg}_v \\log \\mathrm{deg}_v)$ time (because of sorting the degrees). Thus the total running time is $\\mathcal O(n \\log^2 n)$, which is the most expensive part of the algorithm. We can also replace the sort with parallel counting sort, and this makes the time $\\mathcal O(n \\log n)$, but that doesn't run faster in practice. For each vertex $u$, store the histogram of $d_u(v)$ in a map. Now, consider each edge separately, and merge calculate the answer naively, using a linear pass through $d_v(u)$ and $d_u(v)$. Why does it work fast? The sum of all $d_u(v)$ for a fixed $u$ equals to $n-1$, so there are at most $\\mathcal O(\\sqrt n)$ different values in the histogram, which makes the solution $\\mathcal O(n \\sqrt n)$ in total, and quite fast in practice.",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1266",
    "index": "G",
    "title": "Permutation Concatenation",
    "statement": "Let $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $P$. For example, if $n = 3$, then $P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence is $n \\cdot n!$.\n\nLet $1 \\leq i \\leq j \\leq n \\cdot n!$ be a pair of indices. We call the sequence $(P_i, P_{i+1}, \\dots, P_{j-1}, P_j)$ a \\textbf{subarray} of $P$.\n\nYou are given $n$. Find the number of distinct subarrays of $P$. Since this number may be large, output it modulo $998244353$ (a prime number).",
    "tutorial": "Let $LCP$ be the longest-common-prefix array associated with a suffix tree of the sequence $p$. The answer is $|p| \\cdot (|p| + 1) - \\sum_{i=1}^{p} LCP[i]$. Let's calculate $c_i$ - the number of positions for which $LCP[j] = i$. The following holds: $c_0 = n$ $c_i = \\frac{n!}{(n-i+1)!} * ((n-i) * (n-i) + 1)$ for all $i$ between $1$ and $n-1$ $c_i = n! - c_{i-n}$ for all $i$ between $n$ and $2n-1$ $c_i = 0$ for all $i \\geq 2n$ Using the above formulas, we can calculate the answer in $\\mathcal O(n)$. Below follows a proof of the above statement. Beware that it is neither complete, polished, nor interesting It is just case bashing that I used to convince myself that the pattern I observed during problem preparation is correct, an incomplete transript of my scribbles. Apologies to everybody who expected something nice here. Proof Construct the suffix array such that the terminator is strictly larger than $n$. This doesn't change the answer nor the LCP histogram, and it's easier to reason about. Here $LCP_n[i]$ denotes the longest-common-prefix of the suffix starting at position $i$ with the next suffix in lexicographic order. We will build the knowledge about the LCP values guided by induction over $n$. Lemma 1: For every $i$ between $1$ and $n-1$, and for every $k$ between $1$ and $n!$, it holds $LCP_n[k \\cdot n + i] = LCP_n[k \\cdot n + i - 1] - 1$ In other words, the LCP value is largest for the suffix aligned on permutation boundary, and shortening the suffix by one decreases the LCP by one. It is obvious that it can't decrease it more. Why does it always decrease by one? TODO For the above reason, we only need to consider positions divisible by $n$ (if we number from $0$), which we will do in the rest of the text. Lemma 2: Let $i$ be between $1$ and $n$ and $p = [n, n-1, \\dots, i+1, i-1, \\dots, 2, 1, i]$. Then $LCP_n[indexof(p)] = n-1$. We call such permutation semidecreasing. Proof: First, let's see that there is no position which has LCP of $n$ or more (even one that would be lexicographically smaller. Such position needs to have a permutation boundary somewhere, let it be after the number $j$: $[n, n-1, \\dots, j] + [j-1, j-2, \\dots, 2, 1, i]$. Note that the suffix of the left permutation is in decreasing order and it's first element is $n$. When this happens, the next permutation in must swap $n$ with the preceding element, and hence the prefix of the right permutation cannot be complemetary to the suffix of the left permutation. Next, see that there is a subarray of $P$ that has common prefix of exactly $n-1$ with this permutation, and the next element is larger. There are two cases: $i = n$, that is, the permutation is $[n-1, n-2, \\dots, 2, 1, n]$. Then there is a suffix $[n-1, n-2, \\dots, 2, 1, \\$]$ at the end of $P$. $i \\neq n$, a permutation of form $[n, n-1, \\dots, i+1, i-1, \\dots, 2, 1, i]$. Then there is lexicographically larger string with common prefix of length $n-1$ on the boundary of permutations $[i, n, n-1, \\dots, i+1, i-1, \\dots, 2, 1]$ and $[i+1, 1, 2, \\dots, i-1, i+1, \\dots, n-1, n]$ Definition (enlarged permutations) Consider a permutation on $n$ elements. There are $n+1$ permutation on $n+1$ elements that can be obtained from it by prefixing it with a number from set $\\{0.5, 1.5, \\dots, n+0.5\\}$ and renumbering. For example, from $p = [3,1,2,4]$ we obtain $q = \\{[1,4,2,3,5], [2,4,1,3,5], [3,4,1,2,5], [4,3,1,2,5], [5,3,1,2,4]\\}$. These enlarged permutations will be of great use within the proofs, as we will see soon. Their LCP values will be closely related. Lemma 3 (enlarging non-semidecreasing permutations): Let $LCP_n[k \\cdot n] \\geq n$. Then $LCP_{n+1}[(k + m \\cdot n!) \\cdot (n+1)] + 2$. In other words, the LCP of enlarged permutations is two more than that of the original permutation, provided the original permutation was having LCP large enough. Proof: The permutation with corresponding LCP $n$ and the following one are enlarged with the same number $e$ (because the last permutation of $P_{n-1}$ has $LCP = n-2$ as shown by Lemma 2). The lexicographically following permutation in $P_{n-1}$ can also be found in $P_n$, subject to insertion of element $e$ and renumbering. We will just demonstrate this fact informally. For example, consider permutation $p = [1,2,4,3]$. The lexicographically following suffix is on the boundary of permutations $q_1 = [3,1,2,4]$ and $q_2 = [3,1,4,2]$. Say we enlarge $p$ to $p' = [3,1,2,5,4]$. Then the boundary of permutations $q'_1 = [4,3,1,2,5]$ and $q'_2 = [4,3,1,5,2]$ contains the subarray $[3,1,2,5,4,3,1]$, which is longer than the original LCP by two. Here, we inserted $[3]$ after the first element and renumbered the old $3$ to $4$ and $4$ to $5$. Let's characterize the indices where $LCP_n[k \\cdot n] < n$. Lemma 4 (enlarging semidecreasing permutations): Let $p$ be a semidecreasing permutation on $n$ elements. Consider its enlargement $p^{+}$ - a permutation on $n+1$ elements. There are three cases: $p^{+}$ is also semidecreasing. Then $LCP_{n+1}[indexof(p^{+})] = n$. $p$ is the last permutation and the enlargement element is neither $0.5$ nor $n+0.5$. Then $LCP_{n+1}[indexof(p^{+})] = n+2$. Otherwise, $LCP_{n+1}[indexof(p^{+})] = n+1$. Proof: The first case is obvious. In the third case, the enlarged permutation is $p^{+} = [i, n+1, n, \\dots, i+1, i-1, \\dots, 2, 1]$. The lexicographically next permutation is on the boundary of $[1, i, n+1, n, \\dots, i+1, i-1, \\dots, 2]$ and $[1, i+1, 2, 3, \\dots, i, i+2, \\dots, n, n+1]$ and the LCP has length $n+2$. This is because there is an extra match of $i$ at the beginning, and $1$ and $i+1$ at the end. The second case is similar to the Lemma 3. Combined the above and induction on $n$ yields: Lemma 5: For all $k$ it holds $LCP_n[k \\cdot n] < 2n$. Using induction, we can also count the number of permutations $p_n$ for which $LCP_n[indexof(p_n)] = k$. Thanks to Lemma 1 this is extendable to suffices not aligned with a permutation, yielding the $c_i$ values in the statement.",
    "tags": [
      "string suffix structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1266",
    "index": "H",
    "title": "Red-Blue Graph",
    "statement": "There is a directed graph on $n$ vertices numbered $1$ through $n$ where each vertex (except $n$) has two outgoing arcs, red and blue. At any point in time, exactly one of the arcs is active for each vertex. Initially, all blue arcs are active and there is a token located at vertex $1$. In one second, the vertex with token first switches its active arcs — the inactive arc becomes active and vice versa. Then, the token is moved along the active arc. When the token reaches the vertex $n$, it stops. It is guaranteed that $n$ is reachable via arcs from every vertex.\n\nYou are given $q$ queries. Each query contains a state of the graph — a pair $(v, s)$ of the following form:\n\n- $v$ is the vertex where the token is currently located;\n- $s$ is a string consisting of $n - 1$ characters. The $i$-th character corresponds to the color of the active edge leading from the $i$-th vertex (the character is 'R' if red arc is active, otherwise the character is 'B').\n\nFor each query, determine whether the given state is reachable from the initial state and the first time this configuration appears. Note that the two operations (change active arc and traverse it) are atomic — a state is not considered reached if it appears after changing the active arc but before traversing it.",
    "tutorial": "Consider a fixed query $\\{s_i\\}_{i=1}^{n-1}$ and $v$. Let $x_i$ be the number of times the red arc from $i$ was traversed, and $y_i$ the number of times the blue arc was traversed. The answer for a given query, should the $x_i$ and $y_i$ exist, is the sum of all of them. Let's try to find these values. When the blue arc going from $i$ is active, we have $x_i = y_i$. Otherwise, $x_i = y_i + 1$. In both cases $x_i = y_i + [s_i = \\text{'R'}]\\,.$ Let's denote $B_i$ the set of blue arcs going to $i$, and $R_i$ the set of red arcs going to $i$. For every vertex other than $1$ and the current vertex $v$, the sum of traversals of incoming edges must equal the sum of traversals of outgoing edges. For the current vertex, the sum of incoming traversals is one more than the outgoing, and for vertex $1$ it is the opposite. This gives us $\\sum_{r \\in R_i} x_r + \\sum_{b \\in B_i} y_b + [ i = 1 ] = x_i + y_i + [ i = v ]\\,.$ Substituting the $y$s and rearranging yields: $2x_i - \\sum_{r \\in R_i} x_r - \\sum_{b \\in B_i} x_b = [ s_i = \\text{'R'} ] - \\sum_{b \\in B_i} [s_b = \\text{'R'}] + [ i = 1] - [ i = v ]\\,.$ Consider this equality for each $i$ from $1$ to $n-1$. We have $n-1$ equalities for $n-1$ unknowns, written in matrix form $Ax = z$. The value of $A$ does not depend on the actual query - it is determined by the structure of the graph. Let's look at the matrix in more detail. On the main diagonal, each value is $2$ - because each vertex has outdegree $2$. Then there are some negative values for incoming edges. Those values are either $-1$, or $-2$ when both the red and blue edge have the same endpoint. In each column, the sum of negative entries is between $0$ and $-2$, because each $-1$ corresponds to and outgoing edge, and because some of the edges may end in $n$, for which we don't have equation. This combined yields an important observation: the matrix $A$ is irreducibly diagonally dominant. That is, in each column it holds $|a_{ii}| \\geq \\sum_{i\\neq j}|a_{ij}|$, and there is at least one column for which there is strict inequality (because vertex $n$ is reachable). An interesting property of such matrix is that it is non-singular. For every right side $z$ there is thus exactly one solution for $x$. There are $2^{n-1} \\cdot (n - 1)$ possible queries, and each of them corresponds to some pair of vectors $(x, y)$. Clearly, every reachable state corresponds to exactly one pair that describes the process that led to this state. However, it is evident that there are input graphs in which the target vertex is reached in fewer moves, hence some $(x, y)$ pairs must correspond to invalid states. Let's look at which states are invalid. First, every element of $x$ must be non-negative and integer. Consider a graph on three vertices, where each arc, red or blue, goes to the vertex with higher ID ($1 \\rightarrow 2$ and $2 \\rightarrow 3$), $v = 2$ and $s = \\text{\"BB\"}$. The solution of this linear system is $x = \\left(\\frac{1}{2}, 0\\right)$. This is clearly not a valid state. There is one more situation that is invalid. Consider again a graph on three vertices where each red arc goes to the vertex with higher ID as before, but each blue arc is a loop. In this graph, the token moves to the last vertex in two moves, making both red edges active in the process. For query $v = 2$ and $s = \\text{\"RR\"}$, we get a solution $x = \\left(1, 0\\right)$ and $y = \\left(1, 0\\right)$. This is not a valid state. The reason for this is the fact that the active arc from $i$ speaks truth about a simple fact - where did the token go the last time it left vertex $i$. The active edge in vertex $1$ is blue, which leads to itself, meaning that the token never left the vertex. But this is a contradiction, because we know it is in vertex $2$. This condition can be phrased as follows: For every vertex that had the token at least once, the vertex containing the token must be reachable via the active arcs. These two conditions are in fact necessary and sufficient. Let's summarise what we have so far: Build a system of linear equations and solve for $x$. Check whether all $x$ are non-negative and integer. Verify that the current vertex is reachable from all visited vertices using active edges. If both conditions are true, calculate $y$ and sum all $x$ and $y$ to get the answer. Otherwise, the answer is negative. There are some technical details left to be solved. Firstly, as we already noticed, the matrix $A$ doesn't depend on the actual query, only on the graph structure. We can thus precompute its inverse and solve each query as a matrix vector implementation, reducing time per query from $\\mathcal O(n^3)$ to $\\mathcal O(n^2)$. Secondly, how do we compute $x$ precisely to check whether they are integers? There are two ways - either we use exact fractions with big integers, or compute everything in modular arithmetic and verify the solution on integers. Since $128$-bit integers are not a thing on codeforces, we either use Schrage's method for the modular multiplication, or use two moduli and Chinese remainder theorem. The total complexity is $\\mathcal O(n^3 + q \\cdot n^2)$.",
    "tags": [
      "dp",
      "graphs",
      "math",
      "matrices",
      "meet-in-the-middle"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1268",
    "index": "A",
    "title": "Long Beautiful Integer",
    "statement": "You are given an integer $x$ of $n$ digits $a_1, a_2, \\ldots, a_n$, which make up its decimal notation in order from left to right.\n\nAlso, you are given a positive integer $k < n$.\n\nLet's call integer $b_1, b_2, \\ldots, b_m$ \\textbf{beautiful} if $b_i = b_{i+k}$ for each $i$, such that $1 \\leq i \\leq m - k$.\n\nYou need to find the smallest \\textbf{beautiful} integer $y$, such that $y \\geq x$.",
    "tutorial": "At first, let's set $a_i=a_{i-k}$ for all $i>k$. If it is at least the initial $a$, then you can print it as the answer. Otherwise, Let's find the last non-nine digit among the first $k$, increase it by one, and change all $9$'s on the segment from it to $k$-th character to $0$. After that, again set $a_i = a_{i-k}$ for all $i>k$. Then, you can print it as the answer.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1268",
    "index": "B",
    "title": "Domino for Young",
    "statement": "You are given a Young diagram.\n\nGiven diagram is a histogram with $n$ columns of lengths $a_1, a_2, \\ldots, a_n$ ($a_1 \\geq a_2 \\geq \\ldots \\geq a_n \\geq 1$).\n\n\\begin{center}\n{\\small Young diagram for $a=[3,2,2,2,1]$.}\n\\end{center}\n\nYour goal is to find the largest number of non-overlapping dominos that you can draw inside of this histogram, a domino is a $1 \\times 2$ or $2 \\times 1$ rectangle.",
    "tutorial": "Let's color diagram into two colors as a chessboard. I claim that the Young diagram can be partitioned into domino if and only if the number of white cells inside it is equal to the number of black cells inside it. If the Young diagram has two equal rows (or columns) you can delete one domino, and the diagram will still have an equal number of white and black cells. If all rows and columns are different, it means that the Young diagram is a \"basic\" diagram, i.e have lengths of columns $1, 2, \\ldots, n$. But in a \"basic\" diagram the number of white and black cells is different! So, we have a contradiction! But what if the number of black and white cells are not the same? I claim that the answer is $\\min($ the number of white cells, the number of black cells $)$. Just because if you have more white cells (case with more black case is symmetrical), and there are no equal rows and columns, you can take the first column with more white cells than black cells and delete the last cell of this column, in the end, you will have a Young diagram with an equal number of black and white cells, so you can find the answer by algorithm described below.",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1268",
    "index": "C",
    "title": "K Integers",
    "statement": "You are given a permutation $p_1, p_2, \\ldots, p_n$.\n\nIn one move you can swap two adjacent values.\n\nYou want to perform a minimum number of moves, such that in the end there will exist a subsegment $1,2,\\ldots, k$, in other words in the end there should be an integer $i$, $1 \\leq i \\leq n-k+1$ such that $p_i = 1, p_{i+1} = 2, \\ldots, p_{i+k-1}=k$.\n\nLet $f(k)$ be the minimum number of moves that you need to make a subsegment with values $1,2,\\ldots,k$ appear in the permutation.\n\nYou need to find $f(1), f(2), \\ldots, f(n)$.",
    "tutorial": "At first, let's add to the answer number of inversions among numbers $1,2,\\ldots,k$. After that, let's say that $x \\leq k$ is one, and $x > k$ is zero. Then you need to calculate the smallest number of swaps to make segment $1,1,\\ldots,1$ of length $k$ appear in the permutation. For this, let's call $p_i$ the number of ones on the prefix. For all $s_i=0$ we need to add $\\min{(p_i, k - p_i)}$ to the answer (it is an obvious lower bound, and it is simple to prove that we always can do one operation to reduce this total value by one). How to calculate this for each $k$? Let's move $k$ from $1$ to $n$. You can maintain number of inversions with BIT. To calculate the second value, you can note that you just need to find $\\frac{k}{2}$-th number $\\leq k$ and add values at the left and add the right with different coefficients. To maintain them, you can recalculate everything when you are moving the median (in heap). But also it is possible to maintain the segment tree by $p_i$ and just take some sum.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1268",
    "index": "D",
    "title": "Invertation in Tournament",
    "statement": "You are given a tournament — complete directed graph.\n\nIn one operation you can pick any vertex $v$ and change the direction of all edges with $v$ on one of the ends (i.e all edges $u \\to v$ change their orientation to $v \\to u$ and vice versa).\n\nYou want to make the tournament strongly connected with the smallest possible number of such operations if it is possible.\n\nAlso, if it is possible, you need to find the number of ways to make this number of operations to make graph strongly connected (two ways are different if for some $i$ vertex that we chose on $i$-th operation in one way is different from vertex that we chose on $i$-th operation in another way). You only need to find this value modulo $998\\,244\\,353$.",
    "tutorial": "Lemma: for $n>6$ it is always possible to invert one vertex. Start by proving that for $n \\geq 4$ in the strongly connected tournament it is possible to invert one vertex so it will remain strongly connected, it is possible by induction. If there is a big SCC (with at least four vertices), invert good vertex in it. If there are at least three strongly connected components, invert random vertex in the middle one. If there are two SCCs, then all of them have size $\\leq 3$, so the number of vertices is $\\leq 6$. So you can check each vertex in $O(\\frac{n^2}{32})$ with bitset. But also it is possible to check that tournament is strongly connected by degree sequence in $O(n)$. For this, you can note that the degree of each vertex in the rightest SCC is smaller than degrees of all other vertices. So in the sorted by degree order you can check for the prefix of length $k$, that the number of edges outgoing from them (sum of degrees) is $\\frac{k(k-1)}{2}+k(n-k)$ if there exists $k<n$ which satisfy this constraint, then it is simple to prove that the graph is not strongly connected. So, you can solve this problem in $O(n^2)$ or in $O(\\frac{n^3}{32})$.",
    "tags": [
      "brute force",
      "divide and conquer",
      "graphs",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1268",
    "index": "E",
    "title": "Happy Cactus",
    "statement": "You are given a cactus graph, in this graph each edge lies on at most one simple cycle.\n\nIt is given as $m$ edges $a_i, b_i$, weight of $i$-th edge is $i$.\n\nLet's call a path in cactus \\textbf{increasing} if the weights of edges on this path are increasing.\n\nLet's call a pair of vertices $(u,v)$ \\textbf{happy} if there exists an increasing path that starts in $u$ and ends in $v$.\n\nFor each vertex $u$ find the number of other vertices $v$, such that pair $(u,v)$ is happy.",
    "tutorial": "At first, let's solve for the tree. Let $dp_v$ be the number of answer for vertex $v$. Let's look at edges in the order of decreasing weight. How $dp$ is changing when you are looking at edge $i$? I claim that $dp'_v = dp_v$ for $v \\neq a_i$and $v \\neq b_i$. And $dp'_{a_i} = dp'_{b_i} = dp_{a_i} + dp_{b_i}$. Why? I like this thinking about this problem: in each vertex sitting a rat, initially $i$-th rat is infected by $i$-th type of infection. After that, rats $a_m$ and $b_m$, $a_{m-1}$ and $b_{m-1}$, ..., $a_1$ and $b_1$ bite each other. When two rats bite each other, they have a union of their infections. I claim that the number of infections of $i$-th vertex, in the end, is equal to the required value. So on the tree, it is easy to see that the infections are not intersecting when two rats bite each other, so they just change the number to sum. But on the cactus, they may have some non-empty intersection. Now, it is easy to see that: Let's say that $f_i$ is equal to the number of infections of $a_i$ (same as the number of infections of $b_i$) after the moment when you meet this edge. Similar to the tree case, when $i$-th edge connects different connected components, $f_i$ is just equal to the sum of the number of infections. When $i$-th edge connects same connected components, $f_i$ is equal to the sum of the number of infections (let's call this value $x$). Or $f_i$ is equal to $x - f_e$ where $e$ is some edge on the path between $a_i$ and $b_i$ (note that it is a cactus, so this path is unique). This $e$ is always the largest edge on the path, and it is subtracted if and only if the path from it to $a_i$ and from it to $b_i$ is decreasing. So, we can solve the problem in $O(n+m)$.",
    "tags": [
      "dp"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1269",
    "index": "A",
    "title": "Equation",
    "statement": "Let's call a positive integer \\textbf{composite} if it has at least one divisor other than $1$ and itself. For example:\n\n- the following numbers are composite: $1024$, $4$, $6$, $9$;\n- the following numbers are not composite: $13$, $1$, $2$, $3$, $37$.\n\nYou are given a positive integer $n$. Find two composite integers $a,b$ such that $a-b=n$.\n\nIt can be proven that solution always exists.",
    "tutorial": "Print $9n$ and $8n$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1269",
    "index": "B",
    "title": "Modulo Equality",
    "statement": "You are given a positive integer $m$ and two integer sequence: $a=[a_1, a_2, \\ldots, a_n]$ and $b=[b_1, b_2, \\ldots, b_n]$. Both of these sequence have a length $n$.\n\nPermutation is a sequence of $n$ different positive integers from $1$ to $n$. For example, these sequences are permutations: $[1]$, $[1,2]$, $[2,1]$, $[6,7,3,4,1,2,5]$. These are not: $[0]$, $[1,1]$, $[2,3]$.\n\nYou need to find the non-negative integer $x$, and increase all elements of $a_i$ by $x$, modulo $m$ (i.e. you want to change $a_i$ to $(a_i + x) \\bmod m$), so it would be possible to rearrange elements of $a$ to make it equal $b$, among them you need to find the smallest possible $x$.\n\nIn other words, you need to find the smallest non-negative integer $x$, for which it is possible to find some permutation $p=[p_1, p_2, \\ldots, p_n]$, such that for all $1 \\leq i \\leq n$, $(a_i + x) \\bmod m = b_{p_i}$, where $y \\bmod m$ — remainder of division of $y$ by $m$.\n\nFor example, if $m=3$, $a = [0, 0, 2, 1], b = [2, 0, 1, 1]$, you can choose $x=1$, and $a$ will be equal to $[1, 1, 0, 2]$ and you can rearrange it to make it equal $[2, 0, 1, 1]$, which is equal to $b$.",
    "tutorial": "There exists some $i$, such that $(a_i + x) \\bmod m = b_1$. Let's enumerate it, then $x$ is $(b_1 - a_i) \\bmod m$. Like that you can get $O(n)$ candidates, each of them can be checked in $O(n \\log n)$ with sort or in $O(n)$ if you will note that the order is just cyclically shifting. Also, this problem can be solved in $O(n)$ with some string matching algorithms, I will leave it as a bonus.",
    "tags": [
      "brute force",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1270",
    "index": "A",
    "title": "Card Game",
    "statement": "Two players decided to play one interesting card game.\n\nThere is a deck of $n$ cards, with values from $1$ to $n$. The values of cards are \\textbf{pairwise different} (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card.\n\nThe game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.\n\nFor example, suppose that $n = 5$, the first player has cards with values $2$ and $3$, and the second player has cards with values $1$, $4$, $5$. Then one possible flow of the game is:\n\n- The first player chooses the card $3$. The second player chooses the card $1$. As $3>1$, the first player gets both cards. Now the first player has cards $1$, $2$, $3$, the second player has cards $4$, $5$.\n- The first player chooses the card $3$. The second player chooses the card $4$. As $3<4$, the second player gets both cards. Now the first player has cards $1$, $2$. The second player has cards $3$, $4$, $5$.\n- The first player chooses the card $1$. The second player chooses the card $3$. As $1<3$, the second player gets both cards. Now the first player has only the card $2$. The second player has cards $1$, $3$, $4$, $5$.\n- The first player chooses the card $2$. The second player chooses the card $4$. As $2<4$, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.\n\nWho will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.",
    "tutorial": "We can show that the player who has the largest card (the one with value $n$) has the winning strategy! Indeed, if a player has the card with value $n$, he can choose to play it every time, taking the card from the opponent every time (as every other card has a value smaller than $n$). In at most $n-1$ moves, the opponent will be out of cards (and he will lose).",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\n\\nvoid solve()\\n{\\n    int n, k1, k2;\\n    cin >> n >> k1 >> k2;\\n    \\n    vector<int> a(n);\\n    for (int i = 0; i<n; i++) cin>>a[i];\\n    for (int i = 0; i < k1; i++) \\n    {\\n        if (a[i] == n) {\\n            cout << \\\"YES\\\"<<endl;\\n            return;\\n        }\\n    }\\n    cout << \\\"NO\\\"<<endl;;\\n}\\n\\nint main() {\\n    int t;\\n    cin>>t;\\n    for (int i = 0; i<t; i++) solve();\\n}\"",
    "tags": [
      "games",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1270",
    "index": "B",
    "title": "Interesting Subarray",
    "statement": "For an array $a$ of integers let's denote its maximal element as $\\max(a)$, and minimal as $\\min(a)$. We will call an array $a$ of $k$ integers \\textbf{interesting} if $\\max(a) - \\min(a) \\ge k$. For example, array $[1, 3, 4, 3]$ isn't interesting as $\\max(a) - \\min(a) = 4 - 1 = 3 < 4$ while array $[7, 3, 0, 4, 3]$ is as $\\max(a) - \\min(a) = 7 - 0 = 7 \\ge 5$.\n\nYou are given an array $a$ of $n$ integers. Find some interesting \\textbf{nonempty} subarray of $a$, or tell that it doesn't exist.\n\nAn array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.",
    "tutorial": "We will show that if some interesting nonempty subarray exists, then also exists some interesting subarray of length $2$. Indeed, let $a[l..r]$ be some interesting nonempty subarray, let $a_{max}$ be the maximal element, $a_{min}$ - minimal, without loss of generality, $max > min$. Then $a_{max} - a_{min} \\ge r - l + 1 \\ge max - min + 1$, or $(a_{max} - a_{max - 1}) + (a_{max - 1} - a_{max - 2}) + \\dots + (a_{min+1} - a_{min}) \\ge max - min + 1$, so at least one of the terms had to be $\\ge 2$. Therefore, for some $i$ holds $a_{i+1} - a_i \\ge 2$, so subarray $[i, i+1]$ is interesting! Therefore, the solution is as follows: for each $i$ from $1$ to $n-1$ check if $|a_{i+1} - a_i|\\ge 2$ holds. If this is true for some $i$, we have found an interesting subarray of length $2$, else such subarray doesn't exist. Asymptotic $O(n)$.",
    "code": "\"#ifdef DEBUG\\n#define _GLIBCXX_DEBUG\\n#endif\\n#pragma GCC optimize(\\\"O3\\\")\\n#include <bits/stdc++.h>\\nusing namespace std;\\ntypedef long double ld;\\ntypedef long long ll;\\nconst int maxN = (int)3e5 + 100;\\nint a[maxN];\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr);\\n    //freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n    int tst;\\n    cin >> tst;\\n    while (tst--) {\\n        int n;\\n        cin >> n;\\n        for (int i = 1; i <= n; i++) cin >> a[i];\\n        bool fnd = false;\\n        for (int i = 1; i + 1 <= n; i++) {\\n            if (abs(a[i + 1] - a[i]) > 1) {\\n                cout << \\\"YES\\\" << '\\\\n' << i << \\\" \\\" << i + 1 << '\\\\n';\\n                fnd = true;\\n                break;\\n            }\\n        }\\n        if (!fnd) cout << \\\"NO\\\" << '\\\\n';\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1270",
    "index": "C",
    "title": "Make Good",
    "statement": "Let's call an array $a_1, a_2, \\dots, a_m$ of nonnegative integer numbers \\textbf{good} if $a_1 + a_2 + \\dots + a_m = 2\\cdot(a_1 \\oplus a_2 \\oplus \\dots \\oplus a_m)$, where $\\oplus$ denotes the bitwise XOR operation.\n\nFor example, array $[1, 2, 3, 6]$ is good, as $1 + 2 + 3 + 6 = 12 = 2\\cdot 6 = 2\\cdot (1\\oplus 2 \\oplus 3 \\oplus 6)$. At the same time, array $[1, 2, 1, 3]$ isn't good, as $1 + 2 + 1 + 3 = 7 \\neq 2\\cdot 1 = 2\\cdot(1\\oplus 2 \\oplus 1 \\oplus 3)$.\n\nYou are given an array of length $n$: $a_1, a_2, \\dots, a_n$. Append at most $3$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that \\textbf{you don't have to minimize the number of added elements!}. So, if an array is good already you are allowed to not append elements.",
    "tutorial": "Let the sum of numbers be $S$, and their $\\oplus$ be $X$. Solution 1: If $S\\le 2X$ and $S$ was even, it would be enough to add into the array $2$ numbers $\\frac{2X-S}{2}, \\frac{2X-S}{2}$: $X$ wouldn't change, and the sum would become $2X$. How to achieve this? Let's add to the array number $2^{50} + (S\\bmod 2)$. If new sum and $\\oplus$ of all numbers are $S_1$ and $X_1$ correspondently, then we know, that $S_1\\le 2\\cdot 2^{50} \\le 2X_1$, and $S_1$ is even. We spent $3$ numbers. Solution 2: It's enough to add to the array numbers $X$ and $S + X$. Indeed, $S + X + (S+X) = 2(S+X)$, and $X\\oplus X \\oplus (S+X) = (S+X)$. We spent only $2$ numbers! Both solutions have asymptotic $O(n)$ - to calculate $S$ and $X$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nusing ll = long long;\\n\\nvoid solve()\\n{\\n    int n;\\n    cin>>n;\\n    int temp;\\n    ll Sum = 0;\\n    ll Xor = 0;\\n    for (int i = 0; i<n; i++)\\n    {\\n        cin>>temp;\\n        Sum+=temp;\\n        Xor^=temp;\\n    }\\n    vector<ll> answer;\\n    ll good = (1ll<<50) + Sum%2;\\n    Sum+=good;\\n    Xor^=good;\\n    ll need = 2*Xor - Sum;\\n    cout<<3<<endl<<good<<' '<<need/2<<' '<<need/2<<endl; \\n}\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(nullptr);\\n\\n    int t;\\n    cin>>t;\\n    for (int i = 0; i<t; i++) solve();\\n\\n}\"",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1270",
    "index": "D",
    "title": "Strange Device",
    "statement": "\\textbf{This problem is interactive}.\n\nWe have hidden an array $a$ of $n$ \\textbf{pairwise different} numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon.\n\nThis device can answer queries of the following form: in response to the positions of $k$ different elements of the array, it will return the position and value of the $m$-th among them in the ascending order.\n\nUnfortunately, the instruction for the device was lost during delivery. However, you remember $k$, but don't remember $m$. Your task is to find $m$ using queries to this device.\n\nYou can ask \\textbf{not more than $n$ queries}.\n\nNote that the array $a$ and number $m$ are fixed before the start of the interaction and don't depend on your queries. In other words, \\textbf{interactor is not adaptive}.\n\nNote that you don't have to minimize the number of queries, and you don't need to guess array $a$. You just have to guess $m$.",
    "tutorial": "We will show how to guess $m$ with $k+1\\le n$ queries. Let's leave only first $k+1$ elements of the array. We will ask $k+1$ queries: $i$-th question - about all elements from $1$-th to $k+1$-th, except $i$-th. Denote elements from $1$-th to $k+1$-th in decreasing order as $b_1 < b_2 < \\dots < b_{k+1}$. Then, if we throw out element which is larger than $b_m$, then $b_m$ is the $m$-th largest among remaining elements. If we throw out element which is smaller of equal to $b_m$, then $b_{m+1}$ is the $m$-th largest among remaining elements. Therefore, among answers to our $k+1$ queries we will have $m$ times element $b_{m+1}$ and $k+1-m$ times element $b_m$. As $b_{m+1}>b_m$, we can first find $b_{m+1}$ (as the largest of all answers to the queries), and after that we can find $m$ as the number of times $b_{m+1}$ meets among these answers!",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(nullptr);\\n\\n    int n, k;\\n    cin>>n>>k;\\n    vector<int> elements;\\n    for (int i = 1; i<=k+1; i++)\\n    {\\n        cout<<\\\"? \\\";\\n        \\n        for (int j = 1; j<=k+1; j++) if (j!=i) cout<<j<<' ';\\n        cout<<endl;\\n        \\n        int pos, el;\\n        cin>>pos>>el;\\n        elements.push_back(el);\\n    }\\n    int maxx = elements[0];\\n    for (auto it: elements) maxx = max(maxx, it);\\n    int m = 0;\\n    for (auto it: elements) if (it==maxx) m++;\\n    cout<<\\\"! \\\"<<m<<endl;\\n\\n}\"",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1270",
    "index": "E",
    "title": "Divide Points",
    "statement": "You are given a set of $n\\ge 2$ \\textbf{pairwise different} points with integer coordinates. Your task is to partition these points into two \\textbf{nonempty} groups $A$ and $B$, such that the following condition holds:\n\nFor every two points $P$ and $Q$, write the Euclidean distance between them on the blackboard: if they belong to the \\textbf{same} group — with a \\textbf{yellow} pen, and if they belong to \\textbf{different} groups — with a \\textbf{blue} pen. \\textbf{Then no yellow number is equal to any blue number}.\n\nIt is guaranteed that such a partition exists for any possible input. If there exist multiple partitions, you are allowed to output any of them.",
    "tutorial": "Let's divide all points into $4$ groups by parity of their coordinates: $A_{00}$ - (even, even), $A_{01}$ - (even, odd), $A_{10}$ -(odd, even), $A_{11}$ - (odd, odd). If all points belong to one group, for example, $A_{00}$, let's divide all coordinates by $2$ and start again. We just scaled down the image in $2$ times, and all distances between points also got smaller in exactly $2$ times, so any valid partition for new points remains valid for old points. Note that this division by $2$ can't last long: as every division by $2$ decreases the distance between points in $2$ times, all the initial distances don't exceed $4\\cdot 10^6$, and distances can't get smaller than $1$, we can't have more than $\\log{4\\cdot 10^6}$ such divisions. From now on we suppose that at least two groups are nonempty. If there is at least one point with the odd sum of coordinates, and at least one point with even sum of coordinates, we can put to $A$ all points with even sum of coordinates, and to $B$ - all with odd. Then for any two points $(x_1, y_1), (x_2, y_2)$, the square of distance between them $(x_1 - x_2)^2 + (y_1 - y_2)^2$ will be even if these points are from the same group, and odd if they are from different groups. As square of every yellow number will be even, and of every blue odd, no blue number will be equal to any yellow, and the partition would be valid. If all points have even sum of coordinates, then only points $A_{00}$ and $A_{11}$ will be nonempty. Then we can set $A = A_{00}, B = A_{11}$: in this case for any two points $(x_1, y_1), (x_2, y_2)$, the square of distance between them $(x_1 - x_2)^2 + (y_1 - y_2)^2$ will be divisible by $4$, if these points are from the same group, and will give remainder $2$ under division by $4$, if from different. Similarly, if all points have odd sum of coordinates, then only points $A_{01}$ and $A_{10}$ will be nonempty. Then we can set $A = A_{01}, B = A_{10}$: in this case for any two points $(x_1, y_1), (x_2, y_2)$, the square of distance between them $(x_1 - x_2)^2 + (y_1 - y_2)^2$ will be divisible by $4$, if these points are from the same group, and will give remainder $2$ under division by $4$, if from different.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(nullptr);\\n\\n    int n;\\n    cin>>n;\\n    vector<pair<int, int>> p(n);\\n    for (int i = 0; i<n; i++) {cin>>p[i].first>>p[i].second; p[i].first+=1e6; p[i].second+=1e6;}\\n\\n    while (true)\\n    {\\n        vector<vector<int>> cnt(2, vector<int>(2));\\n        for (int i = 0; i<n; i++) cnt[p[i].first%2][p[i].second%2]++;\\n        if (cnt[0][0]+cnt[1][1]>0 && cnt[0][1]+cnt[1][0]>0)\\n        {\\n            vector<int> A;\\n            for (int i = 0; i<n; i++) if ((p[i].first + p[i].second)%2==0) A.push_back(i);\\n            cout<<A.size()<<endl;\\n            for (auto it: A) cout<<it+1<<' ';\\n            return 0;\\n        }\\n        if (cnt[0][0]+cnt[0][1]>0 && cnt[1][1]+cnt[1][0]>0)\\n        {\\n            vector<int> A;\\n            for (int i = 0; i<n; i++) if (p[i].first%2==0) A.push_back(i);\\n            cout<<A.size()<<endl;\\n            for (auto it: A) cout<<it+1<<' ';\\n            return 0;\\n        }\\n        int x, y;\\n        for (int i = 0; i<2; i++)\\n            for (int j = 0; j<2; j++) if (cnt[i][j]>0) {x = i; y = j;}\\n\\n        for (int i = 0; i<n; i++) {p[i].first = (p[i].first - x)/2; p[i].second = (p[i].second - y)/2;}\\n    }\\n\\n}\"",
    "tags": [
      "constructive algorithms",
      "geometry",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1270",
    "index": "F",
    "title": "Awesome Substrings",
    "statement": "Let's call a binary string $s$ \\textbf{awesome}, if it has at least $1$ symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are \\textbf{awesome}, but 0, 110, 01010 aren't.\n\nYou are given a binary string $s$. Count the number of its \\textbf{awesome} substrings.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.",
    "tutorial": "It will be easier for us to think that string is actually an array of ones and zeroes. Let's calculate array of preffix sums - $pref[]$. It's easy to see that, substring $[l;r]$ will be awesome, iff $r - l + 1 = k \\cdot (pref[r] - pref[l - 1])$ for some integer $k$. It's equivalent to $r - k \\cdot pref[r] = l - 1 - k \\cdot pref[l - 1]$. So, we must calculate number of pairs of equal integer in array $t[i] = i - k \\cdot pref[i]$ for each $k$ from $1$ to $n$. Let's fix some number $T$ and note, that if $k > T$, then $pref[r] - pref[l - 1] = \\frac{r - l + 1}{k} \\le \\frac{n}{T}$. In other words, in awesome substring number of ones or $k$ is not big. For $k \\le T$ we can calculate number of pairs of equal integers in $O(nT)$. To do this, note that $-nT \\le i - k \\cdot pref[i] \\le n$, so, independently for each $k$ we can put all numbers into one array and then calculate number of equal integers. After this, we can fix $l$ and iterate how many number of ones our string will contain(using this, we get bounds for $r$). Knowing number of ones, we'll know which remainder should give $r$. So, task comes down to calculate how many integeres on some segment give some fixed remainder if we divide them by some fixed integer. This can be calculated in constant time(but you should remember to count only such $r$ for whic $k > T$. This part works in $O(n \\cdot \\frac{n}{T})$. If we choose $T = \\sqrt{n}$,we will get that our solution works in $O(n\\sqrt{n})$(on practice, this solution easily fits in TL for $T$ from $300$ to $500$) Also note, that if you use some data structures for the first part(like map or unordered_map in C++) and choose big $T$, your solution can get TL. TL wasn't big because of fast bruteforces.",
    "code": "\"#define _CRT_SECURE_NO_WARNINGS\\n#include <bits/stdc++.h>\\n/*\\n#pragma GCC target (\\\"avx2\\\")\\n#pragma GCC optimization (\\\"O3\\\")\\n#pragma GCC optimization (\\\"unroll-loops\\\")*/\\n\\nusing namespace std;\\n\\n#define ll long long\\n#define ld long double\\n#define mp make_pair\\n\\n\\nll solve1 (string s)\\n{\\n\\n    int n = s.size();\\n    int m = sqrt(n);\\n\\n    vector<int> pos_one;\\n    for (int i = 0; i<n; i++) if (s[i]=='1') pos_one.push_back(i);\\n    if (pos_one.size()==0) return 0;\\n\\n    pos_one.push_back(n);\\n\\n\\n    vector<int> cnt(n*m+n);\\n\\n\\n    ll total = 0;\\n    for (ll i = 1; i<=m; i++)\\n    {\\n        int cur = 0;\\n        cnt[i*n]++;\\n        for (int j = 1; j<=n; j++)\\n        {\\n            if (s[j-1]=='1') cur++;\\n            int idx = j - i*cur;\\n            total+=cnt[idx+i*n];\\n            cnt[idx+i*n]++;\\n        }\\n\\n        cur = 0;\\n        cnt[i*n]--;\\n        for (int j = 1; j<=n; j++)\\n        {\\n            if (s[j-1]=='1') cur++;\\n            int idx = j - i*cur;\\n            cnt[idx+i*n]--;\\n        }\\n    }\\n\\n\\n    vector<int> idx(n, -1);\\n    int cur = 0;\\n    for (int i = 0; i<n; i++)\\n    {\\n        idx[i] = cur;\\n        if (s[i]=='1') cur++;\\n    }\\n\\n    for (int i = 0; i<n; i++)\\n    {\\n        for (ll j = 1; j<=n/m&&idx[i]+j<=cur; j++)\\n        {\\n\\n            ll l = pos_one[idx[i]+j-1] - i + 1;\\n            ll r = pos_one[idx[i]+j] - i;\\n            l = max(l, j*(m+1));\\n            if (l<=r) total+=r/j - (l-1)/j;\\n        }\\n    }\\n    return total;\\n}\\n\\nll solve2(string s)\\n{\\n    int n = s.size();\\n    vector<int> pref(n+1);\\n    for (int i = 1; i<=n; i++)\\n    {\\n        pref[i] = pref[i-1];\\n        if (s[i-1]=='1') pref[i]++;\\n    }\\n    ll cnt = 0;\\n    for (int i = 0; i<n; i++)\\n        for (int j = i+1; j<=n; j++)\\n        {\\n            if ((pref[j]>pref[i])&&((j-i)%(pref[j]-pref[i])==0)) cnt++;\\n        }\\n    return cnt;\\n}\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(nullptr);\\n\\n    string s;\\n    cin>>s;\\n    cout<<solve1(s);\\n}\"",
    "tags": [
      "math",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1270",
    "index": "G",
    "title": "Subset with Zero Sum",
    "statement": "You are given $n$ integers $a_1, a_2, \\dots, a_n$, such that for each $1\\le i \\le n$ holds $i-n\\le a_i\\le i-1$.\n\nFind some nonempty subset of these integers, whose sum is equal to $0$. It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find any of them.",
    "tutorial": "Note that the condition $i-n \\le a_i \\le i-1$ is equivalent to $1 \\le i - a_i \\le n$. Let's build an oriented graph $G$ on $n$ nodes with the following principle: for each $i$ from $1$ to $n$, draw an oriented edge from vertex $i$ to vertex $i - a_i$. In this graph, there is an outgoing edge from every vertex, so it has an oriented cycle. Let vertices of this cycle be - $i_1, i_2, \\dots, i_k$. Then: $i_1 - a_{i_1} = i_2$ $i_2 - a_{i_2} = i_3$ $\\vdots$ $i_n - a_{i_n} = i_1$ After adding all these equalities, we get $a_{i_1} + a_{i_2} + \\dots + a_{i_k} = 0$ We can find some oriented cycle in $O(n)$ (just go by an available edge until you get to previously visited vertex).",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nvoid solve()\\n{\\n    int n;\\n    cin >> n;\\n    vector<int> a(n+1);\\n    for (int i = 1; i <= n; i++) cin >> a[i];\\n    vector<bool> visited(n+1);\\n    int cur = 1;\\n    while (!visited[cur])\\n    {\\n        visited[cur] = true;\\n        cur = cur - a[cur];\\n    }\\n    vector<int> answer = {cur};\\n    int cur1 = cur - a[cur];\\n    while (cur1!=cur)\\n    {\\n        answer.push_back(cur1);\\n        cur1 = cur1 - a[cur1];\\n    }\\n    cout<<answer.size()<<'\\\\n';\\n    for (auto it: answer) cout<<it<<' ';\\n    cout<<'\\\\n';\\n}\\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(nullptr);\\n\\n    int t;\\n    cin>>t;\\n    for (int i = 0; i<t; i++) solve();\\n\\n\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1270",
    "index": "H",
    "title": "Number of Components",
    "statement": "Suppose that we have an array of $n$ distinct numbers $a_1, a_2, \\dots, a_n$. Let's build a graph on $n$ vertices as follows: for every pair of vertices $i < j$ let's connect $i$ and $j$ with an edge, if $a_i < a_j$. Let's define \\textbf{weight} of the array to be the number of connected components in this graph. For example, weight of array $[1, 4, 2]$ is $1$, weight of array $[5, 4, 3]$ is $3$.\n\nYou have to perform $q$ queries of the following form — change the value at some position of the array. After each operation, output the weight of the array. Updates are not independent (the change stays for the future).",
    "tutorial": "Firstly, note that all connected components form segments of sequential indexes. Indeed, let numbers $i$ and $j$ lie in one component and let's consider $i < x < j$. Because $i$ and $j$ lie in one component, there exists a path, which connects them: $v_1 = i, \\ldots, v_t = j$, such that $v_k$ and $v_{k+1}$ are connected with an edge for any $k$. Then there exists $p$, such that $v_p < x < v_{p+1}$.But if $a_{v_p} < a_x$, then there exists an edge $xv_p$, otherwise there exists an edge between $x$ and $a_{v_{p+1}}$(because $a_x < a_{v_p} < a_{v_{p+1}}$). So, because components are non-intersecting segments, there is no edge between $[l_1;r_1]$ and $[l_2;r_2]$, $l_1 \\le r_1 < l_2 \\le r_2$, iff $min_{x \\in [l_1;r_1]}(a) > max_{x \\in [l_2;r_2]}(a)$. That's why number of components is equal to number of $i$, such that $min_{x \\in [1;i]}(a) > max_{x \\in [i + 1; n]}(a)$, increased by $1$. So, our task is to calculate number of prefix minimums which are strictly greater than corresponding suffix maximums. To do this, let's set $a[0] = \\infty$ and $a[n + 1] = 0$. After this let's consider some number $h$ and build new array $b$, such that $b[i] = 1$ iff $a[i] \\ge h$. Then if $h = min_{x \\in [1;i]}(a)$ for some suitable $i$, array $b$ looks like $11\\ldots00$. On the other hand, if $b$ looks like $11..00$ for some $h = a[t]$, there exists a unique $i$ for which prefix minimum is greater than suffix maximum. So, we need to calculate number of $h$ for which array $b$ looks in a such way. Note, that array looks like this, iff number of adjacent pair of integers $b[t] \\ne b[t + 1]$ is equal to one. Moreover, for any $h$ this number is at least one. Thus, we just need to maintain $f[h]$ (number of adjacent non-equal integers in array $b$) for all $h$ and calculate number of $h$ that have $f[h]$ equal to minimum. It can be done with segment tree, if we note that, if we change one position in array $a$, value $f[h]$ can change only because of integers $a[i - 1], a[i], a[i + 1]$. Then, changing $f[h]$ is addition of $\\pm1$ on some segments. But we also need to remember, that we should count only values of $h$, which are equal to some integer in $a[]$(so if have query $pos, x$ we need to activate $h=x$ and deactivate $h=a[pos]$ in segment tree). We are sorry for rather strict TL. This was done because with aim to cut off $O(n\\sqrt{nlog(n)})$ solutions(not sure if we succeed), which worked not slower than solutions on Java with set.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nclass SegTree {\\nprivate:\\n    int n;\\n    vector<int> val, cnt, lazy;\\n    \\n    void push(int x, int l, int r) {\\n        if (lazy[x] == 0) return;\\n        val[x] += lazy[x];\\n        if (l != r) {\\n            lazy[x * 2] += lazy[x];\\n            lazy[x * 2 + 1] += lazy[x];\\n        }\\n        lazy[x] = 0;\\n    }\\n    \\n    void merge(int x) {\\n        if (val[x*2] == val[x*2+1]) {\\n            val[x] = val[x*2];\\n            cnt[x] = cnt[x*2] + cnt[x*2+1];\\n        } else if (val[x*2] < val[x*2+1]) {\\n            val[x] = val[x*2];\\n            cnt[x] = cnt[x*2];\\n        } else {\\n            val[x] = val[x*2+1];\\n            cnt[x] = cnt[x*2+1];\\n        }\\n    }\\n    \\n    void recount(int x, int tl, int tr, int pos, int delta) {\\n        push(x, tl, tr);\\n        if (tl == tr) {\\n            cnt[x] += delta;\\n            return;\\n        }\\n        int tm = (tl + tr) / 2;\\n        if (pos <= tm) {\\n            recount(x * 2, tl, tm, pos, delta);\\n            push(x * 2 + 1, tm + 1, tr);\\n        } else {\\n            push(x * 2, tl, tm);\\n            recount(x * 2 + 1, tm + 1, tr, pos, delta);\\n        }\\n        merge(x);\\n    }\\n    \\n    void update(int x, int tl, int tr, int l, int r, int val) {\\n        push(x, tl, tr);\\n        if (l > r) return;\\n        if (l == tl && tr == r) {\\n            lazy[x] += val;\\n            push(x, tl, tr);\\n            return;\\n        }\\n        int tm = (tl + tr) / 2;\\n        update(x * 2, tl, tm, l, min(r, tm), val);\\n        update(x * 2 + 1, tm + 1, tr, max(tm + 1, l), r, val);\\n        merge(x);\\n    }\\n    \\n    int query(int x, int tl, int tr, int l, int r) {\\n        push(x, tl, tr);\\n        if (l == tl && tr == r) {\\n            return val[x] == 1 ? cnt[x] : 0;\\n        }\\n        int tm = (tl + tr) / 2;\\n        if (r <= tm) {\\n            return query(x * 2, tl, tm, l, r);\\n        } else if (l > tm) {\\n            return query(x * 2 + 1, tm + 1, tr, l, r);\\n        } else {\\n            return query(x * 2, tl, tm, l, tm) +\\n                    query(x * 2 + 1, tm + 1, tr, tm + 1, r);\\n        }\\n    }\\npublic:\\n    inline void update(int l, int r, int val) {\\n        update(1, 0, n - 1, l, r, val);\\n    }\\n\\n    inline int query(int l, int r) {\\n        return query(1, 0, n - 1, l, r);\\n    }\\n\\n    inline void recount(int pos, int val) {\\n        recount(1, 0, n - 1, pos, val);\\n    }\\n\\n    SegTree(int n) : n(n), val(4*n), cnt(4*n), lazy(4*n) {}\\n};\\n\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    \\n    int n, q; cin >> n >> q;\\n    vector<int> a(n + 2);\\n    int mx = 0;\\n    for (int i = 0; i < n; ++i) {\\n        cin >> a[i+1];\\n        mx = max(mx, a[i+1]);\\n    }\\n    a[n+1] = 0;\\n    vector<int> pos(q), x(q);\\n    for (int i = 0; i < q; ++i) {\\n        cin >> pos[i] >> x[i];\\n        mx = max(mx, x[i]);\\n    }\\n    a[0] = mx+1;\\n    \\n    ++n;\\n    SegTree segTree(a[0] + 1);\\n    \\n    auto addDiff = [&](int a, int b, int sgn) {\\n        if (a == b) return;\\n        segTree.update(min(a, b), max(a, b) - 1, sgn);\\n    };\\n    \\n    for (int i = 0; i < n; ++i) {\\n        addDiff(a[i], a[i + 1], +1);\\n        segTree.recount(a[i], +1);\\n    }\\n    for (int i = 0; i < q; ++i) {\\n        int p = pos[i], y = x[i];\\n        segTree.recount(a[p], -1);\\n        addDiff(a[p - 1], a[p], -1);\\n        addDiff(a[p], a[p + 1], -1);\\n        segTree.recount(y, +1);\\n        addDiff(a[p - 1], y, +1);\\n        addDiff(y, a[p + 1], +1);\\n        a[p] = y;\\n        cout << segTree.query(1, a[0] - 1) << \\\"\\\\n\\\";\\n    }\\n}\"",
    "tags": [
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1270",
    "index": "I",
    "title": "Xor on Figures",
    "statement": "There is given an integer $k$ and a grid $2^k \\times 2^k$ with some numbers written in its cells, cell $(i, j)$ initially contains number $a_{ij}$. Grid is considered to be a torus, that is, the cell to the right of $(i, 2^k)$ is $(i, 1)$, the cell below the $(2^k, i)$ is $(1, i)$ There is also given a lattice figure $F$, consisting of $t$ cells, where $t$ is \\textbf{odd}. $F$ doesn't have to be connected.\n\nWe can perform the following operation: place $F$ at some position on the grid. (Only translations are allowed, rotations and reflections are prohibited). Now choose any nonnegative integer $p$. After that, for each cell $(i, j)$, covered by $F$, replace $a_{ij}$ by $a_{ij}\\oplus p$, where $\\oplus$ denotes the bitwise XOR operation.\n\nMore formally, let $F$ be given by cells $(x_1, y_1), (x_2, y_2), \\dots, (x_t, y_t)$. Then you can do the following operation: choose any $x, y$ with $1\\le x, y \\le 2^k$, any nonnegative integer $p$, and for every $i$ from $1$ to $n$ replace number in the cell $(((x + x_i - 1)\\bmod 2^k) + 1, ((y + y_i - 1)\\bmod 2^k) + 1)$ with $a_{((x + x_i - 1)\\bmod 2^k) + 1, ((y + y_i - 1)\\bmod 2^k) + 1}\\oplus p$.\n\nOur goal is to make all the numbers equal to $0$. Can we achieve it? If we can, find the smallest number of operations in which it is possible to do this.",
    "tutorial": "Let's fix first cell of fiqure - $(x_1, y_1)$. Then if figure is lied in a such way, that first cell will be cell $(p,q)$ of the original board, other figure cells will be in the cells $(a + x_i - x_1, b + y_i - y_1)$ of the original board. Let's name such shifts $(x_i - x_1, y_i - y_1)$ as $(c_i, d_i)$. Then let's compute value $f[p, q] = \\oplus a_{p - c_i, q - d_i}$ for $i = 1 \\ldots t$(all additions are done modulo $2^k$). $\\textbf{Lemma 1}$ If all numbers $f[p, q] = 0$, then all numbers in original array are zero too. It will be proved in the end. So our aim is to get zero array $f$. $\\textbf{Lemma 2}$ Assume, that we use operation in a such way that, that first figure cell is in $(p, q)$. Then values of $f$ will change in a such way: For all $p', q'$ of the form $p + 2\\cdot c_i, q + 2\\cdot d_i$ $f[p', q']$ values will xor with $x$, for other it will not change. Consider cell $(p', q')$. Then $f'[p', q'] = f[p', q'] \\oplus (x \\oplus x \\ldots \\oplus x)$, where we xor with $x$ for all pair $i, j$ such that $(p' - c_i, q' - d_i) = (p + c_j, q + d_j)$. Note, that if pair $i, j$ is suitable, then pair $j, i$ is suitable too. So, because $x \\oplus x = 0$, we can only have non-xored pairs $i, i$ in the end, but then $p', q'$ looks like $p + 2\\cdot c_i, q + 2\\cdot d_i$ for some $i$. We get that task for array $a$ is equivalent for task with array $f$ with figure scaled two times. Note that in this case, if we xor on some figure we change only cells with one parity of coordinates, so we can solve this task independently for $4$ boards of size $2^(k-1)$ (also, some cells of figure can map to the same one, then we should not use them). It's only left to show that if $f$ is zero, then $a$ is also zero.It's sufficient to show that for any values of $f$ we can get zero array(follow from linear algebra, both facts are equivalent to fact that $f$ is non-degenerate transform). But this statement can be easily proved using induction on $k$, because if we get all zeroes for problem with $k - 1$, then they will be zeroes in array $f$ too. In the end we get $k=0$ and figure with one cell(because $t$ is odd). We can get zero in one operation. Also, from non-degenerativity it follow that answer is unique(if we xor on each figure at most once).",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define ll long long\\n#define mp make_pair \\n\\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(nullptr);\\n\\n    int k;\\n    cin>>k;\\n    int n = 1<<k;\\n    vector<vector<ll>> a(n, vector<ll>(n));\\n    for (int i = 0; i<n; i++)\\n        for (int j = 0; j<n; j++) cin>>a[i][j];\\n\\n    int t;\\n    cin>>t;\\n    vector<pair<int, int>> F(t);\\n    for (int i = 0; i<t; i++) cin>>F[i].first>>F[i].second;\\n    vector<pair<int, int>> V;\\n    auto key = F[0];\\n    for (auto it: F)\\n    {\\n        V.push_back(mp(it.first - key.first, it.second - key.second));\\n    }\\n    for (int iteration = 0; iteration<k; iteration++)\\n    {\\n        vector<vector<ll>> new_grid(n, vector<ll>(n));\\n        for (int i = 0; i<n; i++)\\n            for (int j = 0; j<n; j++)\\n            {\\n                for (auto it: V) new_grid[i][j]^=a[(i+n-it.first)%n][(j+n-it.second)%n];\\n            }\\n        a = new_grid;\\n        for (int i = 0; i<t; i++)\\n        {\\n            V[i].first = (V[i].first*2)%n;\\n            V[i].second = (V[i].second*2)%n;\\n        }\\n    }\\n    int cnt = 0;\\n    for (int i = 0; i<n; i++)\\n        for (int j = 0; j<n; j++) if (a[i][j]) cnt++;\\n    cout<<cnt;\\n}\"",
    "tags": [
      "constructive algorithms",
      "fft",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1271",
    "index": "A",
    "title": "Suits",
    "statement": "A new delivery of clothing has arrived today to the clothing store. This delivery consists of $a$ ties, $b$ scarves, $c$ vests and $d$ jackets.\n\nThe store does not sell single clothing items — instead, it sells suits of two types:\n\n- a suit of the first type consists of one tie and one jacket;\n- a suit of the second type consists of one scarf, one vest and one jacket.\n\nEach suit of the first type costs $e$ coins, and each suit of the second type costs $f$ coins.\n\nCalculate the maximum possible cost of a set of suits that can be composed from the delivered clothing items. Note that one item cannot be used in more than one suit (though some items may be left unused).",
    "tutorial": "There are two ways to approach this problem. The first way is to iterate on the number of suits of one type that we will compose and calculate the number of suits of the second type we can compose from the remaining items. The second way is to use the fact that if $e > f$, then we have to make as many suits of the first type as possible (and the opposite is true if $f > e$). So we firstly make the maximum possible number of more expensive suits, and use the remaining items to compose cheaper suits.",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1271",
    "index": "B",
    "title": "Blocks",
    "statement": "There are $n$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.\n\nYou may perform the following operation zero or more times: choose two \\textbf{adjacent} blocks and invert their colors (white block becomes black, and vice versa).\n\nYou want to find a sequence of operations, such that they make all the blocks having the same color. You \\textbf{don't have} to minimize the number of operations, but it should not exceed $3 \\cdot n$. If it is impossible to find such a sequence of operations, you need to report it.",
    "tutorial": "Suppose we want to make all blocks white (if we want to make them black, the following algorithm still works with a few changes). The first block has to be white, so if it is black, we have to invert the pair $(1, 2)$ once, otherwise we should not invert it at all (inverting twice is the same as not inverting at all). Then consider the second block. We need to invert it once if it is black - but if we invert the pair $(1, 2)$, then the first block becomes black. So we can't invert the pair $(1, 2)$, and we have to invert the pair $(2, 3)$ (or don't invert anything if the second block is white now). And so on: for the $i$-th block, we cannot invert the pair $(i - 1, i)$, since it will affect the color of the previous block. So we don't have much choice in our algorithm. After that, we arrive at the last block. If it is white, we are done with no more than $n - 1$ actions. If it is black, run the same algorithm, but we have to paint everything black now. If it fails again, then there is no answer.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1271",
    "index": "C",
    "title": "Shawarma Tent",
    "statement": "The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.\n\nThe main school of the capital is located in $(s_x, s_y)$. There are $n$ students attending this school, the $i$-th of them lives in the house located in $(x_i, y_i)$. It is possible that some students live in the same house, but no student lives in $(s_x, s_y)$.\n\nAfter classes end, each student walks from the school to his house along one of the shortest paths. So the distance the $i$-th student goes from the school to his house is $|s_x - x_i| + |s_y - y_i|$.\n\nThe Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the $i$-th student will buy a shawarma if at least one of the shortest paths from the school to the $i$-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).\n\nYou want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.",
    "tutorial": "Suppose that the point $(t_x, t_y)$ is the answer. If the distance between this point $t$ and the school is greater than $1$, then there exists at least one point $(T_x, T_y)$ such that: the distance between $T$ and the school is exactly $1$; $T$ lies on the shortest path between the school and $t$. Now we claim that the $T$ can also be the optimal answer. That's because, if there exists a shortest path from the school to some point $i$ going through $t$, the shortest path from $s$ to $t$ going through $T$ can be extended to become the shortest path to $i$. So we only need to check four points adjacent to the school as possible answers. To check whether a point $(a_x, a_y)$ lies on the shortest path from $(b_x, b_y)$ to $(c_x, c_y)$, we need to verify that $min(b_x, c_x) \\le a_x \\le max(b_x, c_x)$ and $min(b_y, c_y) \\le a_y \\le max(b_y, c_y)$.",
    "tags": [
      "brute force",
      "geometry",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1271",
    "index": "D",
    "title": "Portals",
    "statement": "You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer $n$ castles of your opponent.\n\nLet's describe the game process in detail. Initially you control an army of $k$ warriors. Your enemy controls $n$ castles; to conquer the $i$-th castle, you need at least $a_i$ warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army — formally, after you capture the $i$-th castle, $b_i$ warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter $c_i$, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:\n\n- if you are currently in the castle $i$, you may leave one warrior to defend castle $i$;\n- there are $m$ one-way portals connecting the castles. Each portal is characterised by two numbers of castles $u$ and $v$ (for each portal holds $u > v$). A portal can be used as follows: if you are currently in the castle $u$, you may send one warrior to defend castle $v$.\n\nObviously, when you order your warrior to defend some castle, he leaves your army.\n\nYou capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle $i$ (but only before capturing castle $i + 1$) you may recruit new warriors from castle $i$, leave a warrior to defend castle $i$, and use any number of portals leading from castle $i$ to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle $i$ won't be available to you.\n\nIf, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it — your score will be calculated afterwards).\n\nCan you determine an optimal strategy of capturing and defending the castles?",
    "tutorial": "Note, that for every castle $i$ there is some list of castles $x$, such that you can defend castle $i$ standing in the castle $x$. The key observation is that it's always optimal to defend castle $i$ (assuming we decided to defend it) in the latest possible castle. Since it gives you more warriors in between of $i$ and $x$ (more freedom), it's always optimal. We will prune all other $x$'s except for the maximum one. Now our process looks like: Conquer next castle, Acquire new warriors, Decide whether or not you you defend previous castle $i$, such that the current castle is $x$ in terms of the paragraph above. There might be several such $i$ to process for the current castle. Since in this process we decide on each castle exactly only once, the process can be simulated as a simple dynamic programming with states \"number of castles conquered, number of warriors available\", it's possible to compute this dp in $\\mathcal{O}(n \\cdot C)$, where $C$ is the total number of warriors. Or you can use a greedy approach in $\\mathcal{O}(n \\log(n))$. Just maintain the process above, defending all the castles you can defend. In case it turns out you are lacking few warriors later, just undo several defended castes. To do so, just maintain undoable castles in a Heap or std::set.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1271",
    "index": "E",
    "title": "Common Number",
    "statement": "At first, let's define function $f(x)$ as follows: $$ \\begin{matrix} f(x) & = & \\left\\{ \\begin{matrix} \\frac{x}{2} & \\mbox{if } x \\text{ is even} \\\\ x - 1 & \\mbox{otherwise } \\end{matrix} \\right. \\end{matrix} $$\n\nWe can see that if we choose some value $v$ and will apply function $f$ to it, then apply $f$ to $f(v)$, and so on, we'll eventually get $1$. Let's write down all values we get in this process in a list and denote this list as $path(v)$. For example, $path(1) = [1]$, $path(15) = [15, 14, 7, 6, 3, 2, 1]$, $path(32) = [32, 16, 8, 4, 2, 1]$.\n\nLet's write all lists $path(x)$ for every $x$ from $1$ to $n$. The question is next: what is the maximum value $y$ such that $y$ is contained in at least $k$ different lists $path(x)$?\n\nFormally speaking, you need to find maximum $y$ such that $\\left| \\{ x ~|~ 1 \\le x \\le n, y \\in path(x) \\} \\right| \\ge k$.",
    "tutorial": "Let's introduce a function $count(x)$ - the number of $y \\in [1, n]$ such that $x \\in path(y)$. The problem is now to find the greatest number $x$ such that $count(x) \\ge k$. How can we calculate $count(x)$? First, let's consider the case when $x$ is odd. $x$ is contained in $path(x)$; then $x$ is contained in $path(2x)$ (since $\\frac{2x}{2} = x$) and in $path(2x + 1)$ (since $2x + 1$ is odd, $f(2x + 1) = 2x$). The next numbers containing $x$ in their paths are $4x$, $4x + 1$, $4x + 2$ and $4x + 3$, then $8x$, $8x + 1$, ..., $8x + 7$, and so on. By processing each segment of numbers containing $x$ in their paths in $O(1)$, we can calculate $count(x)$ for odd $x$ in $O(\\log n)$. What about even $x$? The first numbers containing $x$ in their paths are $x$ and $x + 1$, then $2x$, $2x + 1$, $2x + 2$ and $2x + 3$, then $4x$, $4x + 1$, ..., $4x + 7$, and so on. So the case with even $x$ can also be solved in $O(\\log n)$. We can also see that $count(x) \\ge count(x + 2)$ simply because for each number containing $x + 2$ in its path, there is another number that is less than it which contains $x$ in its path. And this fact means that if we want to find the greatest $x$ such that $count(x) \\ge k$, we only have to run two binary searches: one binary search over odd numbers, and another binary search over even numbers.",
    "tags": [
      "binary search",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1271",
    "index": "F",
    "title": "Divide The Students",
    "statement": "Recently a lot of students were enrolled in Berland State University. All students were divided into groups according to their education program. Some groups turned out to be too large to attend lessons in the same auditorium, so these groups should be divided into two subgroups. Your task is to help divide the first-year students of the computer science faculty.\n\nThere are $t$ new groups belonging to this faculty. Students have to attend classes on three different subjects — maths, programming and P. E. All classes are held in different places according to the subject — maths classes are held in auditoriums, programming classes are held in computer labs, and P. E. classes are held in gyms.\n\nEach group should be divided into two subgroups so that there is enough space in every auditorium, lab or gym for all students of the subgroup. For the first subgroup of the $i$-th group, maths classes are held in an auditorium with capacity of $a_{i, 1}$ students; programming classes are held in a lab that accomodates up to $b_{i, 1}$ students; and P. E. classes are held in a gym having enough place for $c_{i, 1}$ students. Analogically, the auditorium, lab and gym for the second subgroup can accept no more than $a_{i, 2}$, $b_{i, 2}$ and $c_{i, 2}$ students, respectively.\n\nAs usual, some students skip some classes. Each student considers some number of subjects (from $0$ to $3$) to be useless — that means, he skips all classes on these subjects (and attends all other classes). This data is given to you as follows — the $i$-th group consists of:\n\n- $d_{i, 1}$ students which attend all classes;\n- $d_{i, 2}$ students which attend all classes, except for P. E.;\n- $d_{i, 3}$ students which attend all classes, except for programming;\n- $d_{i, 4}$ students which attend only maths classes;\n- $d_{i, 5}$ students which attend all classes, except for maths;\n- $d_{i, 6}$ students which attend only programming classes;\n- $d_{i, 7}$ students which attend only P. E.\n\nThere is one more type of students — those who don't attend any classes at all (but they, obviously, don't need any place in auditoriums, labs or gyms, so the number of those students is insignificant in this problem).\n\nYour task is to divide each group into two subgroups so that every auditorium (or lab, or gym) assigned to each subgroup has enough place for all students from this subgroup attending the corresponding classes (if it is possible). Each student of the $i$-th group should belong to exactly one subgroup of the $i$-th group; it is forbidden to move students between groups.",
    "tutorial": "Suppose we have only students of types $1$, $4$, $6$ and $7$ (all students attend either all subjects or only one subject). We can divide these students into two subgroups in $O(1)$: the first subgroup can accomodate no more than $min(a_1, b_1, c_1)$ students of the first type; the second subgroup can accomodate no more than $min(a_2, b_2, c_2)$ students of the first type; it does not matter how we distribute them into groups, as long as their number does not exceed the limits. After that, it's easy to distribute three other types. Okay, we can solve the problem with four types in $O(1)$. How to solve the problem with seven types in $O(M^3)$? Let's iterate on $f_2$, $f_3$ and $f_5$, and check whether we can distribute the remaining types! Though it may seem slow, we will do only $10^9$ iterations, and the time limit is generous enough (model solution works in 1.8 seconds without any cutoffs).",
    "tags": [
      "brute force"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1272",
    "index": "A",
    "title": "Three Friends",
    "statement": "Three friends are going to meet each other. Initially, the first friend stays at the position $x = a$, the second friend stays at the position $x = b$ and the third friend stays at the position $x = c$ on the coordinate axis $Ox$.\n\nIn one minute \\textbf{each friend independently} from other friends can change the position $x$ by $1$ to the left or by $1$ to the right (i.e. set $x := x - 1$ or $x := x + 1$) or even don't change it.\n\nLet's introduce the total pairwise distance — the sum of distances between each pair of friends. Let $a'$, $b'$ and $c'$ be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is $|a' - b'| + |a' - c'| + |b' - c'|$, where $|x|$ is the absolute value of $x$.\n\nFriends are interested in the minimum total pairwise distance they can reach if they will move optimally. \\textbf{Each friend will move no more than once}. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.\n\nYou have to answer $q$ independent test cases.",
    "tutorial": "This problem can be solved with simple simulation. Let $na \\in \\{a - 1, a, a + 1\\}$ be the new position of the first friend, $nb \\in \\{b - 1, b, b + 1\\}$ and $nc \\in \\{c - 1, c, c + 1\\}$ are new positions of the second and the third friends correspondingly. For the fixed positions you can update the answer with the value $|na - nb| + |na - nc| + |nb - nc|$. And iterating over three positions can be implemented with nested loops. Time complexity: $O(1)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint calc(int a, int b, int c) {\n\treturn abs(a - b) + abs(a - c) + abs(b - c);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint a, b, c;\n\t\tcin >> a >> b >> c;\n\t\tint ans = calc(a, b, c);\n\t\tfor (int da = -1; da <= 1; ++da) {\n\t\t\tfor (int db = -1; db <= 1; ++db) {\n\t\t\t\tfor (int dc = -1; dc <= 1; ++dc) {\n\t\t\t\t\tint na = a + da;\n\t\t\t\t\tint nb = b + db;\n\t\t\t\t\tint nc = c + dc;\n\t\t\t\t\tans = min(ans, calc(na, nb, nc));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1272",
    "index": "B",
    "title": "Snow Walking Robot",
    "statement": "Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $(0, 0)$ on an infinite grid.\n\nYou also have the sequence of instructions of this robot. It is written as the string $s$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $(x, y)$ right now, he can move to one of the adjacent cells (depending on the current instruction).\n\n- If the current instruction is 'L', then the robot can move to the left to $(x - 1, y)$;\n- if the current instruction is 'R', then the robot can move to the right to $(x + 1, y)$;\n- if the current instruction is 'U', then the robot can move to the top to $(x, y + 1)$;\n- if the current instruction is 'D', then the robot can move to the bottom to $(x, y - 1)$.\n\nYou've noticed the warning on the last page of the manual: if the robot visits some cell (\\textbf{except} $(0, 0)$) twice then it breaks.\n\nSo the sequence of instructions is valid if the robot starts in the cell $(0, 0)$, performs the given instructions, visits no cell other than $(0, 0)$ two or more times and ends the path in the cell $(0, 0)$. Also cell $(0, 0)$ should be visited \\textbf{at most} two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: \"UD\", \"RL\", \"UUURULLDDDDLDDRRUU\", and the following are considered invalid: \"U\" (the endpoint is not $(0, 0)$) and \"UUDD\" (the cell $(0, 1)$ is visited twice).\n\nThe initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move.\n\nYour task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain.\n\nNote that you can choose \\textbf{any} order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric).\n\nYou have to answer $q$ independent test cases.",
    "tutorial": "Let $cnt[L]$ be the number of occurrences of the character 'L' in the initial string, $cnt[R]$ - the number of occurrences of the character 'R', $cnt[U]$ and $cnt[D]$ are the same things for remaining characters. It is obvious that in every answer the number of 'L' equals the number of 'R' and the same for 'D' and 'U'. The maximum theoretic answer we can obtain has length $2 \\cdot (min(cnt[L], cnt[R]) + min(cnt[U] + cnt[D]))$. And... We almost always can obtain this answer! If there is at least one occurrence of each character, then we can construct some kind of rectangular path: $min(cnt[L], cnt[R])$ moves right, then $min(cnt[U], cnt[D])$ moves up, and the completing part. But there are some corner cases when some characters are missing. If $min(cnt[U], cnt[D]) = 0$ then our answer is empty or (if it is possible) it is \"LR\". The same if $min(cnt[L], cnt[R]) = 0$. Time complexity: $O(|s|)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst string MOVES = \"LRUD\";\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tstring s;\n\t\tcin >> s;\n\t\tmap<char, int> cnt;\n\t\tfor (auto c : MOVES) cnt[c] = 0;\n\t\tfor (auto c : s) ++cnt[c];\n\t\tint v = min(cnt['U'], cnt['D']);\n\t\tint h = min(cnt['L'], cnt['R']);\n\t\tif (min(v, h) == 0) {\n\t\t\tif (v == 0) {\n\t\t\t\th = min(h, 1);\n\t\t\t\tcout << 2 * h << endl << string(h, 'L') + string(h, 'R') << endl;\n\t\t\t} else {\n\t\t\t\tv = min(v, 1);\n\t\t\t\tcout << 2 * v << endl << string(v, 'U') + string(v, 'D') << endl;\n\t\t\t}\n\t\t} else {\n\t\t\tstring res;\n\t\t\tres += string(h, 'L');\n\t\t\tres += string(v, 'U');\n\t\t\tres += string(h, 'R');\n\t\t\tres += string(v, 'D');\n\t\t\tcout << res.size() << endl << res << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1272",
    "index": "C",
    "title": "Yet Another Broken Keyboard",
    "statement": "Recently, Norge found a string $s = s_1 s_2 \\ldots s_n$ consisting of $n$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $s$. Yes, all $\\frac{n (n + 1)}{2}$ of them!\n\nA substring of $s$ is a non-empty string $x = s[a \\ldots b] = s_{a} s_{a + 1} \\ldots s_{b}$ ($1 \\leq a \\leq b \\leq n$). For example, \"auto\" and \"ton\" are substrings of \"automaton\".\n\nShortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $k$ Latin letters $c_1, c_2, \\ldots, c_k$ out of $26$.\n\nAfter that, Norge became interested in how many substrings of the string $s$ he could still type using his broken keyboard. Help him to find this number.",
    "tutorial": "Let's replace all characters of $s$ with zeros and ones (zero if the character is unavailable and one otherwise). Then we have the binary string and we have to calculate the number of contiguous segments of this string consisting only of ones. It can be done with two pointers approach. If we are staying at the position $i$ and its value is zero, just skip it. Otherwise, let's find the leftmost position $j$ such that $j > i$ and the $j$-th value is zero. Then we have to add to the answer the value $\\frac{(j - i) \\cdot (j - i + 1)}{2}$ and set $i := j$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tstring s;\n\tcin >> s;\n\tset<char> st;\n\tfor (int i = 0; i < k; ++i) {\n\t\tchar c;\n\t\tcin >> c;\n\t\tst.insert(c);\n\t}\n\t\n\tlong long ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint j = i;\n\t\twhile (j < n && st.count(s[j])) ++j;\n\t\tint len = j - i;\n\t\tans += len * 1ll * (len + 1) / 2;\n\t\ti = j;\n\t}\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1272",
    "index": "D",
    "title": "Remove One Element",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nYou can remove \\textbf{at most one} element from this array. Thus, the final length of the array is $n-1$ or $n$.\n\nYour task is to calculate the maximum possible length of the \\textbf{strictly increasing} contiguous subarray of the remaining array.\n\nRecall that the contiguous subarray $a$ with indices from $l$ to $r$ is $a[l \\dots r] = a_l, a_{l + 1}, \\dots, a_r$. The subarray $a[l \\dots r]$ is called strictly increasing if $a_l < a_{l+1} < \\dots < a_r$.",
    "tutorial": "Firstly, let's calculate for each $i$ from $1$ to $n$ two following values: $r_i$ and $l_i$. $r_i$ means the maximum length of the increasing sequence starting in the position $i$, and $l_i$ means the maximum length of the increasing sequence ending in the position $i$. Initially, all $2n$ values are $1$ (the element itself). The array $r$ can be calculated in order from right to left with the following condition: if $a_i < a_{i + 1}$ then $r_i = r_{i + 1} + 1$, otherwise it still remain $1$. The same with the array $l$, but we have to calculate its values in order from left to right, and if $a_i > a_{i - 1}$ then $l_i = l_{i - 1} + 1$, otherwise it still remain $1$. Having these arrays we can calculate the answer. The initial answer (if we don't remove any element) is the maximum value of the array $l$. And if we remove the $i$-th element (where $i = 2 \\dots n - 1$), then we can update the answer with the value $l_{i - 1} + r_{i + 1}$ if $a_{i - 1} < a_{i + 1}$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\tint ans = 1;\n\t\n\tvector<int> rg(n, 1);\n\tfor (int i = n - 2; i >= 0; --i) {\n\t\tif (a[i + 1] > a[i]) rg[i] = rg[i + 1] + 1;\n\t\tans = max(ans, rg[i]);\n\t}\n\t\n\tvector<int> lf(n, 1);\n\tfor (int i = 1; i < n; ++i) {\n\t\tif (a[i - 1] < a[i]) lf[i] = lf[i - 1] + 1;\n\t\tans = max(ans, lf[i]);\n\t}\n\t\n\tfor (int i = 0; i < n - 2; ++i) {\n\t\tif (a[i] < a[i + 2]) ans = max(ans, lf[i] + rg[i + 2]);\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1272",
    "index": "E",
    "title": "Nearest Opposite Parity",
    "statement": "You are given an array $a$ consisting of $n$ integers. In one move, you can jump from the position $i$ to the position $i - a_i$ (if $1 \\le i - a_i$) or to the position $i + a_i$ (if $i + a_i \\le n$).\n\nFor each position $i$ from $1$ to $n$ you want to know the minimum the number of moves required to reach any position $j$ such that $a_j$ has the opposite parity from $a_i$ (i.e. if $a_i$ is odd then $a_j$ has to be even and vice versa).",
    "tutorial": "In this problem, we have directed graph consisting of $n$ vertices (indices of the array) and at most $2n-2$ edges. Some vertices have the value $0$, some have the value $1$. Our problem is to find for every vertex the nearest vertex having the opposite parity. Let's try to solve the problem for odd numbers and then just run the same algorithm with even numbers. We have multiple odd vertices and we need to find the nearest even vertex for each of these vertices. This problem can be solved with the standard and simple but pretty idea. Let's inverse our graph and run a multi-source breadth-first search from all even vertices. The only difference between standard bfs and multi-source bfs is that the second one have many vertices at the first step (vertices having zero distance). Now we can notice that because of bfs every odd vertex of our graph has the distance equal to the minimum distance to some even vertex in the initial graph. This is exactly what we need. Then just run the same algorithm for even numbers and print the answer. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint n;\nvector<int> a;\nvector<int> ans;\nvector<vector<int>> g;\n\nvoid bfs(const vector<int> &start, const vector<int> &end) {\n\tvector<int> d(n, INF);\n\tqueue<int> q;\n\tfor (auto v : start) {\n\t\td[v] = 0;\n\t\tq.push(v);\n\t}\n\twhile (!q.empty()) {\n\t\tint v = q.front();\n\t\tq.pop();\n\t\tfor (auto to : g[v]) {\n\t\t\tif (d[to] == INF) {\n\t\t\t\td[to] = d[v] + 1;\n\t\t\t\tq.push(to);\n\t\t\t}\n\t\t}\n\t}\n\tfor (auto v : end) {\n\t\tif (d[v] != INF) {\n\t\t\tans[v] = d[v];\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n;\n\ta = vector<int>(n);\n\tg = vector<vector<int>>(n);\n\tvector<int> even, odd;\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\tif (a[i] & 1) odd.push_back(i);\n\t\telse even.push_back(i);\n\t}\n\tfor (int i = 0; i < n; ++i) {\n\t\tint lf = i - a[i];\n\t\tint rg = i + a[i];\n\t\tif (0 <= lf) g[lf].push_back(i);\n\t\tif (rg < n) g[rg].push_back(i);\n\t}\n\t\n\tans = vector<int>(n, -1);\n\tbfs(odd, even);\n\tbfs(even, odd);\n\tfor (auto it : ans) cout << it << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1272",
    "index": "F",
    "title": "Two Bracket Sequences",
    "statement": "You are given two bracket sequences (not necessarily regular) $s$ and $t$ consisting only of characters '(' and ')'. You want to construct the shortest \\textbf{regular} bracket sequence that contains both given bracket sequences as \\textbf{subsequences} (not necessarily contiguous).\n\nRecall what is the regular bracket sequence:\n\n- () is the regular bracket sequence;\n- if $S$ is the regular bracket sequence, then ($S$) is a regular bracket sequence;\n- if $S$ and $T$ regular bracket sequences, then $ST$ (concatenation of $S$ and $T$) is a regular bracket sequence.\n\nRecall that the subsequence of the string $s$ is such string $t$ that can be obtained from $s$ by removing some (possibly, zero) amount of characters. For example, \"coder\", \"force\", \"cf\" and \"cores\" are subsequences of \"codeforces\", but \"fed\" and \"z\" are not.",
    "tutorial": "Firstly, notice that the length of the answer cannot exceed $400$ ($200$ copies of ()). Now we can do some kind of simple dynamic programming. Let $dp_{i, j, bal}$ be the minimum possible length of the prefix of the regular bracket sequence if we are processed first $i$ characters of the first sequence, first $j$ characters of the second sequence and the current balance is $bal$. Each dimension of this dp should have a size nearby $200 + \\varepsilon$. The base of this dp is $dp_{0, 0, 0} = 0$, all other values $dp_{i, j, bal} = +\\infty$. Transitions are very easy: if we want to place the opening bracket, then we increase $i$ if the $i$-th character of $s$ exists and equals '(', the same with the second sequence and $j$, the balance increases by one, and the length of the answer increases by one. If we want to place the closing bracket, then we increase $i$ if the $i$-th character of $s$ exists and equals ')', the same with the second sequence and $j$, the balance decreases by one, and the length of the answer increases by one. Note that the balance cannot be greater than $200$ or less than $0$ at any moment. Don't forget to maintain parents in this dp to restore the actual answer! The last problem that can be unresolved is how to write this dp? The easiest way is bfs, because every single transition increases our answer by one. Then we can restore answer from the state $dp_{|s|, |t|, 0}$. You can write it recursively, but I don't sure this will look good. And you also can write it just with nested loops, if you are careful enough. Time complexity: $O(|s| \\cdot |t| \\cdot max(|s|, |t|))$. If you know the faster solution, please share it!",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 202;\nconst int INF = 1e9;\n\nint dp[N][N][2 * N];\npair<pair<int, int>, pair<int, char>> p[N][N][2 * N];\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tstring s, t;\n\tcin >> s >> t;\n\tint n = s.size(), m = t.size();\n\t\n\tfor (int i = 0; i <= n; ++i) {\n\t\tfor (int j = 0; j <= m; ++j) {\n\t\t\tfor (int bal = 0; bal < 2 * N; ++bal) {\n\t\t\t\tdp[i][j][bal] = INF;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tdp[0][0][0] = 0;\n\tfor (int i = 0; i <= n; ++i) {\n\t\tfor (int j = 0; j <= m; ++j) {\n\t\t\tfor (int bal = 0; bal < 2 * N; ++bal) {\n\t\t\t\tif (dp[i][j][bal] == INF) continue;\n\t\t\t\t\n\t\t\t\tint nxti = i + (i < n && s[i] == '(');\n\t\t\t\tint nxtj = j + (j < m && t[j] == '(');\n\t\t\t\tif (bal + 1 < 2 * N && dp[nxti][nxtj][bal + 1] > dp[i][j][bal] + 1) {\n\t\t\t\t\tdp[nxti][nxtj][bal + 1] = dp[i][j][bal] + 1;\n\t\t\t\t\tp[nxti][nxtj][bal + 1] = make_pair(make_pair(i, j), make_pair(bal, '('));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tnxti = i + (i < n && s[i] == ')');\n\t\t\t\tnxtj = j + (j < m && t[j] == ')');\n\t\t\t\tif (bal > 0 && dp[nxti][nxtj][bal - 1] > dp[i][j][bal] + 1) {\n\t\t\t\t\tdp[nxti][nxtj][bal - 1] = dp[i][j][bal] + 1;\n\t\t\t\t\tp[nxti][nxtj][bal - 1] = make_pair(make_pair(i, j), make_pair(bal, ')'));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint ci = n, cj = m, cbal = 0;\n\tfor (int bal = 0; bal < 2 * N; ++bal) {\n\t\tif (dp[n][m][bal] + bal < dp[n][m][cbal] + cbal) {\n\t\t\tcbal = bal;\n\t\t}\n\t}\n\tstring res = string(cbal, ')');\n\twhile (ci > 0 || cj > 0 || cbal != 0) {\n\t\tint nci = p[ci][cj][cbal].first.first;\n\t\tint ncj = p[ci][cj][cbal].first.second;\n\t\tint ncbal = p[ci][cj][cbal].second.first;\n\t\tres += p[ci][cj][cbal].second.second;\n\t\tci = nci;\n\t\tcj = ncj;\n\t\tcbal = ncbal;\n\t}\n\treverse(res.begin(), res.end());\n\tcout << res << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "strings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1276",
    "index": "A",
    "title": "As Simple as One and Two",
    "statement": "You are given a non-empty string $s=s_1s_2\\dots s_n$, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string \"one\" or at least one string \"two\" (or both at the same time) as a \\textbf{substring}. In other words, Polycarp does not like the string $s$ if there is an integer $j$ ($1 \\le j \\le n-2$), that $s_{j}s_{j+1}s_{j+2}=$\"one\" or $s_{j}s_{j+1}s_{j+2}=$\"two\".\n\nFor example:\n\n- Polycarp does not like strings \"oneee\", \"ontwow\", \"twone\" and \"oneonetwo\" (they all have at least one substring \"one\" or \"two\"),\n- Polycarp likes strings \"oonnee\", \"twwwo\" and \"twnoe\" (they have no substrings \"one\" and \"two\").\n\nPolycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.\n\nFor example, if the string looks like $s=$\"onetwone\", then if Polycarp selects two indices $3$ and $6$, then \"{on\\underline{\\textbf{e}}tw\\underline{\\textbf{o}}ne}\" will be selected and the result is \"ontwne\".\n\nWhat is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?",
    "tutorial": "Consider each occurrence of substrings one and two. Obviously, at least one character have to be deleted in such substrings. These substrings cannot intersect in any way, except for one case: twone. Thus, the answer is necessarily no less than the value $c_{21}+c_{1}+c_{2}$, where $c_{21}$ is the number of occurrences of the string twone and $c_{1}$ is the number of occurrences of the string one (which are not part of twone) and $c_{2}$ is the number of occurrences of the string two (which are not part of twone). Let's propose a method that does exactly $c_ {21} + c_ {1} + c_ {2}$ removals and, thus, will be optimal. Delete character o in each occurrence of twone. This action will delete both substrings one and two at the same time. Next, delete character n in each occurrence of one. This action will delete all substrings one. Next, delete character w in each occurrence of two. This action will delete all substrings two. Note that it is important to delete the middle letters in the last two paragraphs to avoid appearing a new occurrence after a line is collapsed. The following is an example of a possible implementation of the main part of a solution:",
    "code": "string s;\ncin >> s;\nvector<int> r;\nfor (string t: {\"twone\", \"one\", \"two\"}) {\n    for (size_t pos = 0; (pos = s.find(t, pos)) != string::npos;) {\n        s[pos + t.length() / 2] = '?';\n        r.push_back(pos + t.length() / 2);\n    }\n}\ncout << r.size() << endl;\nfor (auto rr: r)\n    cout << rr + 1 << \" \";\ncout << endl;\n",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1276",
    "index": "B",
    "title": "Two Fairs",
    "statement": "There are $n$ cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from $1$ to $n$.\n\nTwo fairs are currently taking place in Berland — they are held in two different cities $a$ and $b$ ($1 \\le a, b \\le n$; $a \\ne b$).\n\nFind the number of pairs of cities $x$ and $y$ ($x \\ne a, x \\ne b, y \\ne a, y \\ne b$) such that if you go from $x$ to $y$ you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities $x,y$ such that any path from $x$ to $y$ goes through $a$ and $b$ (in any order).\n\nPrint the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs $(x,y)$ and $(y,x)$ must be taken into account only once.",
    "tutorial": "This problem has a simple linear solution (just two depth-first searches) without involving cut points, biconnected components, and other advanced techniques. Let's reformulate this problem in the language of graph theory: you are given an undirected graph and two vertices $a$ and $b$, you need to find the number of pairs of vertices ($x, y$) such that any path from $x$ to $y$ contains both vertices $a$ and $b$. In other words, we are interested in pairs of vertices ($x, y$) such that deleting the vertex $a$ (while going from $b$) breaks the connection from $x$ to $y$ and deleting the vertex $b$ (while going from $a$) breaks the connection from $x$ to $y$. Let's remove the vertex $a$ and select the connected components in the resulting graph. Similarly, we remove the vertex $b$ and select the connected components in the resulting graph. Then the pair ($x, y$) interests us if $x$ and $y$ belong to different components both when removing $a$ and when removing $b$. Thus, let's find a pair of $(\\alpha_u, \\beta_u)$ for each vertex $u$. It will be numbers of the connected components when $a$ and $b$ are removed, respectively. The pair ($x, y$) interests us if $(\\alpha_x, \\beta_x) \\ne (\\alpha_y, \\beta_y)$. The total number of vertex pairs is $n \\cdot (n - 1) / 2$. Let's subtract the number of uninteresting pairs from it. Firstly, these are pairs such that $(\\alpha_x, \\beta_x)$ and $(\\alpha_y, \\beta_y)$ partially equals (in exactly one component). For example, let the equality be on the first component in the common value of $\\alpha$. Let the total number of pairs $(\\alpha_u, \\beta_u)$ such that $\\alpha_u = \\alpha$ be equal to $c$, then subtract $c \\cdot (c-1) / 2$ from the current answer. We will do this with all $\\alpha$ and $\\beta$. Note that some uninteresting pairs were counted twice. These are pairs of vertices such that $(\\alpha_x, \\beta_x)$ and $(\\alpha_y, \\beta_y)$ equals in both components. We can count the number of corresponding vertices $c$ and add $c \\cdot (c-1) / 2$ to the current answer for each pair. In the following code, let $p$ be an array of pairs of component numbers for all vertices except $a$ and $b$. Each pair is the number of the connected component of this vertex if $a$ is removed, and the number of the connected component of this vertex if $b$ is removed. Then the main part of the solution can be like this: To build the array $p$ we could use the code below:",
    "code": "void dfs(int u, int c) {\n    if (color[u] == 0) {\n        color[u] = c;\n        for (int v: g[u])\n            dfs(v, c);\n    }\n}\n\nvector<int> groups(int f) {\n    color = vector<int>(n);\n    color[f] = -1;\n    int c = 0;\n    forn(i, n)\n        if (i != f && color[i] == 0)\n            dfs(i, ++c);\n    return color;\n}\n\n// begin of read input and construct graph g\n// some code ...\n// end of read input and construct graph g\n\nvector<pair<int,int>> p(n - 2);\n{\n    int index = 0;\n    auto g = groups(a);\n    forn(i, n)\n        if (i != a && i != b)\n            p[index++].first = g[i];\n}\n{\n    int index = 0;\n    auto g = groups(b);\n    forn(i, n)\n        if (i != a && i != b)\n            p[index++].second = g[i];\n}\n",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1276",
    "index": "C",
    "title": "Beautiful Rectangle",
    "statement": "You are given $n$ integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the $n$ numbers may not be chosen.\n\nA rectangle (rectangular matrix) is called beautiful if in each row and in each column all values are different.\n\nWhat is the largest (by the total number of cells) beautiful rectangle you can construct? Print the rectangle itself.",
    "tutorial": "First, let's formulate the criteria that from the given set of numbers $x_1, x_2, \\dots, x_k$ we can create a beautiful rectangle $a \\times b$ (where $a \\cdot b = k, a \\le b$). Obviously, if some number occurs more than $a$ times, then among $a$ rows there will be such row that will contain two or more occurrences of the number (pigeonhole principle). Let's prove that if all numbers in $x[1 \\dots k]$ occur no more than $a$ times, we can create a beautiful rectangle $a \\times b$ (where $a \\cdot b = k, a \\le b$). We will numerate cells from the upper left corner in the order from one, moving diagonally each time. Assume rows are numerated from $0$ to $a-1$ and columns are numerated from $0$ to $b-1$. Let's begin from the cell ($0,0$) and move right-down each time. If we face to a border, we will move cyclically. Thus, from the cell ($i,j$) we will move to the cell $((i+1) \\bmod a, (j+1) \\bmod b)$ each time (where $p \\bmod q$ is the remainder when divided $p$ by $q$). If we are going to move to a visited cell, before moving let's assign $i := (i + 1) \\bmod a$. Example of the numeration for rectangles $3\\times3$ and $4\\times6$. We can also prove that while such numeration each row and each column contain numbers that differ by no less than $a-1$ (if we are on a row/column, we will make a turn before we will be on the row/column again). Moreover, the difference reaches $a-1$ (not $a$) when we move to the previously visited cell and assign $i := (i + 1) \\bmod a$. So, we can prove that the lengths of such orbits are equal $lcm(a,b)$ ($lcm$ is a least common multiple). Consequently, they are divided by $a$. It means that if we will arrange the numbers from $x$ in the order from the most common (at worst case those that meet $a$ times) to the least common, each row and each column will always contain different numbers. Thus, we have a plan of the solution: find optimal $a$ and $b$ so that the answer is the largest rectangle $a \\times b$ ($a \\le b$). For this we will iterate over all possible candidates in $a$ and for each candidate each number $v$ from $x$ we will use it no more than $\\min(c_v, a)$ times where $c_v$ is a number of occurrences $v$ in the given sequence. So, if we choose $a$, the upper bound of a rectangle area is $\\sum \\min(c_v, a)$ for all possible different numbers $v$ from the given sequence. Consequently, the maximal value of $b$ is $\\sum \\min(c_v, a) / a$. And let's update the answer if for current iteration $a \\cdot b$ is larger than previously found answer (still consider that $a \\le b$). We can maintain the value $\\sum \\min(c_v, a)$ while $a$ is incremented by one. For doing this we should each time add $geq[a]$ to this value, where $geq[a]$ is a number of different numbers in the given sequence, which occurs at least $a$ times (we can precalculate this array). Below is a code which reads the input data and precalculates the array $geq$. Below is a code which finds the optimal sizes of the rectangle by iterating its the smallest side $a$. And below is a code which prints the optimal rectangle sizes, generates the required beautiful rectangle and prints it. Thus, the total complexity of the algorithm is $O(n \\log n)$, where $\\log n$ appears only thanks for working with std::map (and we can easily get rid of it and make the linear algorithm).",
    "code": "cout << best << endl << best_a << \" \" << best_b << endl;\nvector<vector<int>> r(best_a, vector<int>(best_b));\n\nint x = 0, y = 0;\nfor (int i = n; i >= 1; i–)\n    for (auto val: val_by_cnt[i])\n        forn(j, min(i, best_a)) {\n            if (r[x][y] != 0)\n                x = (x + 1) % best_a;\n            if (r[x][y] == 0)\n                r[x][y] = val;\n            x = (x + 1) % best_a;\n            y = (y + 1) % best_b;\n        }\n\nforn(i, best_a) {\n    forn(j, best_b)\n        cout << r[i][j] << \" \";\n    cout << endl;\n}\n",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1276",
    "index": "D",
    "title": "Tree Elimination",
    "statement": "Vasya has a tree with $n$ vertices numbered from $1$ to $n$, and $n - 1$ edges numbered from $1$ to $n - 1$. Initially each vertex contains a token with the number of the vertex written on it.\n\nVasya plays a game. He considers all edges of the tree by increasing of their indices. For every edge he acts as follows:\n\n- If both endpoints of the edge contain a token, remove a token from one of the endpoints and write down its number.\n- Otherwise, do nothing.\n\nThe result of the game is the sequence of numbers Vasya has written down. Note that there may be many possible resulting sequences depending on the choice of endpoints when tokens are removed.\n\nVasya has played for such a long time that he thinks he exhausted all possible resulting sequences he can obtain. He wants you to verify him by computing the number of distinct sequences modulo $998\\,244\\,353$.",
    "tutorial": "First of all, counting different sequences is the same as counting the number of different playbacks of the elimination process (that is, different combinations of which token was removed on each step). Indeed, if we consider any resulting sequence, we can simulate the process and unambiguously determine which endpoint got its token removed on any step, skipping steps when no tokens can be removed. To count different playbacks, we will use subtree dynamic programming. Let us consider a vertex $v$, and forget about all edges not incident to any vertex that is not in a subtree of $v$; that is, we are only considering edges in the subtree of $v$, as well as the edge between $v$ and its parent $p$ (for convenience, assume that the root vertex has an edge with index $n$ to a \"virtual\" parent). Note that we assume that $p$ can not be eliminated by means other than considering its edge to $v$. As a shorthand, we will say \"$v$ was compared with $u$\" to mean \"when the edge $(v, u)$ was considered, both its endpoints had their token\", and \"$v$ was killed by $u$\" to mean \"$v$ was compared with $u$ and lost its token on that step\". We will distinguish three types of playbacks in $v$'s subtree: $v$ was killed before comparing to $p$ (situation $0$); $v$ was killed by $p$ (situation $1$); $v$ killed $p$ (situation $2$). We will write $dp_{v, s}$ the number of playbacks in the subtree of $v$ that correspond to the situation $s$. Let $u_1, \\ldots, u_k$ be the list of children of $v$ ordered by increasing of $\\mathrm{index}(u_i, v)$, and let $d$ be the largest index such that $\\mathrm{index}(u_d, v) < \\mathrm{index}(v, p)$. If $\\mathrm{index}(u_1, v) > \\mathrm{index}(v, p)$, put $d = 0$. Let us work out the recurrence relations for $dp_{v, s}$. For example, for $s = 0$ we must have that $v$ was killed by one of its children $u_i$ with $i \\leq d$. For a fixed $i$, the playback should have proceeded as follows: all children $u_1, \\ldots, u_i$ were either killed before comparing to $v$, or killed by $v$ (but they could not have survived comparing with $v$). $v$ was killed by $u_i$; all children $u_{i + 1}, \\ldots, u_k$ were either killed before comparing to $v$, or \"survived\" the non-existent comparison to $v$ (but they could not have been killed by $v$). Consequently, we have the formula $dp_{v, 0} = \\sum_{i = 1}^d \\left(\\prod_{j = 1}^{i = 1}(dp_{u_j, 0} + dp_{u_j, 1}) \\times dp_{u_i, 1} \\times \\prod_{j = i + 1}^k (dp_{u_j, 0} + dp_{u_j, 2})\\right).$ Arguing in a similar way, we can further obtain $dp_{v, 1} = \\prod_{j = 1}^{i = d}(dp_{u_j, 0} + dp_{u_j, 1}) \\times \\prod_{j = d + 1}^k (dp_{u_j, 0} + dp_{u_j, 2}),$ $dp_{v, 2} = \\sum_{i = d + 1}^k \\left(\\prod_{j = 1}^{i = 1}(dp_{u_j, 0} + dp_{u_j, 1}) \\times dp_{u_i, 1} \\times \\prod_{j = i + 1}^k (dp_{u_j, 0} + dp_{u_j, 2})\\right) + \\prod_{j = 1}^k (dp_{u_j, 0} + dp_{u_j, 1}).$ In all these formulas we naturally assume that empty products are equal to $1$. To compute these formulas fast enough we can use prefix products of $dp_{j, 0} + dp_{j, 1}$ and suffix products of $dp_{j, 0} + dp_{j, 2}$. Finally, the answer is equal to $dp_{root, 0} + dp_{root, 1}$ (either the root was killed, or it wasn't and we assume that it was killed by its virtual parent). This solution can implemented in $O(n)$ since the edges are already given by increasing of their indices, but $O(n \\log n)$ should also be enough.",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1276",
    "index": "E",
    "title": "Four Stones",
    "statement": "There are four stones on an infinite line in integer coordinates $a_1, a_2, a_3, a_4$. The goal is to have the stones in coordinates $b_1, b_2, b_3, b_4$. The order of the stones does not matter, that is, a stone from any position $a_i$ can end up in at any position $b_j$, provided there is a required number of stones in each position (that is, if a coordinate $x$ appears $k$ times among numbers $b_1, \\ldots, b_4$, there should be exactly $k$ stones at $x$ in the end).\n\nWe are allowed to move stones with the following operation: choose two stones at \\textbf{distinct} positions $x$ and $y$ with at least one stone each, and move one stone from $x$ to $2y - x$. In other words, the operation moves a stone to a symmetric position relative to some other stone. At any moment it is allowed to have any number of stones at the same position.\n\nFind any sequence of operations that achieves the goal, or determine that it is impossible. The sequence does not have to be shortest, but it may contain at most $1000$ operations.",
    "tutorial": "First, when is the task impossible? If all $a_i$ have the same remainder $d$ modulo an integer $g$, then it will always be true regardless of our moves. The largest $g$ we can take is equal to $\\mathrm{GCD}(a_2 - a_1, a_3 - a_1, a_4 - a_1)$. Remark: case when all $a_i$ are equal is special. If the GCD's or the remainders do not match for $a_i$ and $b_i$, then there is no answer. For convenience, let us apply the transformation $x \\to (x - d) / g$ to all coordinates, and assume that $g = 1$. We can observe further that parity of each coordinate is preserved under any operation, thus the number of even and odd numbers among $a_i$ and $b_i$ should also match. Otherwise, we will divide the task into two subproblems: Given four stones $a_1, \\ldots, a_4$, move them into a segment $[x, x + 1]$ for an arbitrary even $x$. Given four stones in a segment $[x, x + 1]$, shift them into a segment $[y, y + 1]$. Suppose we can gather $a_i$ and $b_i$ into segments $[x, x + 1]$ and $[y, y + 1]$. Then we can solve the problem as follows: gather $a_i$ into $[x, x + 1]$; shift the stones from $[x, x + 1]$ to $[y, y + 1]$; undo gathering $b_i$ into $[y, y + 1]$ (all moves are reversible). First subproblem. Throughout, let $\\Delta$ denote the maximum distance between any two stones. Our goal is to make $\\Delta = 1$. We will achieve this by repeatedly decreasing $\\Delta$ by at least a quarter, then we will be done in $O(\\log \\Delta)$ steps. Suppose $a_1 \\leq a_2 \\leq a_3 \\leq a_4$, and one of the stones $a_i$ is in the range $[a_1 + \\Delta / 4, a_1 + 3 \\Delta / 4]$. Consider two halves $[a_1, a_i]$ and $[a_i, a_4]$, and mirror all stones in the shorter half with respect to $a_i$. Then, $a_i$ becomes either the leftmost or the rightmost stone, and the new maximum distance $\\Delta'$ is at most $3 \\Delta / 4$, thus reaching our goal. What if no stones are in this range? Denote $d_i = \\min(a_i - a_1, a_4 - a_i)$ - the distance from $a_i$ to the closest extreme (leftmost or rightmost) stone. We suppose that $d_2, d_3 < \\Delta / 4$, otherwise we can reduce $\\Delta$ as shown above. Further at least one of $d_2, d_3$ is non-zero, since otherwise we would have $\\mathrm{GCD}(a_2 - a_1, a_3 - a_1, a_4 - a_1) = 1 = \\Delta$, and the goal would be reached. Observe that performing moves $(a_i, a_j)$, $(a_i, a_k)$ changes $a_i$ to $a_i + 2(a_k - a_j)$. With this we are able to change $d_i$ to $d_i + 2 d_j$. Repeatedly do this with $d_i \\leq d_j$ (that is, we are adding twice the largest distance to the smallest). In $O(\\log \\Delta)$ steps we will have $\\max(d_2, d_3) \\geq \\Delta / 4$, allowing us to decrease $\\Delta$ as shown above. Finally, we have all $a_i \\in [x, x + 1]$. To make things easier, if $x$ is odd, move all $a_i = x$ to $x + 2$. Second subproblem. We now have all stones in a range $[x, x + 1]$, and we want to shift them by $2d$ (we will assume that $2d \\geq 0$). Observe that any arrangement of stones can be shifted by $2\\Delta$ by mirroring all stones with respect to the rightmost stone twice. Consider an operation we will call Expand: when $a_1 \\leq a_2 \\leq a_3 \\leq a_4$, make moves $(a_3, a_1)$ and $(a_2, a_4)$. We can see that if we apply Expand $k$ times, the largest distance $\\Delta$ will grow exponentially in $k$. We can then shift the stones by $2d$ as follows: Apply Expand until $\\Delta > d$. While $\\Delta \\leq d$, shift all stones by $2\\Delta$ as shown above, and decrease $d$ by $\\Delta$. If $\\Delta = 1$, exit. Perform Expand${}^{-1}$ - the inverse operation to Expand, and return to step $2$. In the end, we will have $\\Delta = 1$ and $d = 0$. Further, since $\\Delta$ grows exponentially in the number of Expand's, for each value of $\\Delta$ we will be making $O(1)$ shifts, thus the total number of operations for this method $O(\\log d)$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1276",
    "index": "F",
    "title": "Asterisk Substrings",
    "statement": "Consider a string $s$ of $n$ lowercase English letters. Let $t_i$ be the string obtained by replacing the $i$-th character of $s$ with an asterisk character *. For example, when $s = \\mathtt{abc}$, we have $t_1 = \\tt{*bc}$, $t_2 = \\tt{a*c}$, and $t_3 = \\tt{ab*}$.\n\nGiven a string $s$, count the number of distinct strings of lowercase English letters and asterisks that occur as a substring of at least one string in the set $\\{s, t_1, \\ldots, t_n \\}$. The empty string should be counted.\n\nNote that *'s are just characters and do not play any special role as in, for example, regex matching.",
    "tutorial": "There are two types of substrings we have to count: with and without the *. The substrings without * are just all substrings of the intial string $s$, which can be counted in $O(n)$ or $O(n \\log n)$ using any standard suffix structure. We now want to count the substrings containing *. Consider all such substrings of the form \"$u$*$v$\", where $u$ and $v$ are letter strings. For a fixed prefix $u$, how many ways are there to choose the suffix $v$? Consider the right context $rc(u)$ - the set of positions $i + |u|$ such that the suffix $s_i s_{i + 1} \\ldots$ starts with $u$. Then, the number of valid $v$ is the number of distinct prefixes of suffixes starting at positions in the set $\\{i + 1 \\mid i \\in rc(u)\\}$. For an arbitrary set $X$ of suffixes of $s$ (given by their positions), how do we count the number of their distinct prefixes? If $X$ is ordered by lexicographic comparison of suffixes, the answer is $1 + \\sum_{i \\in X} (|s| - i) - \\sum_{i, j\\text{ are adjacent in }X} |LCP(i, j)|$, where $LCP(i, j)$ is the largest common prefix length of suffixes starting at $i$ and $j$. Recall that $LCP(i, j)$ queries can be answered online in $O(1)$ by constructing the suffix array of $s$ with adjacent LCPs, and using a sparse table to answer RMQ queries. With this, we can implement $X$ as a sorted set with lexicographic comparison. With a bit more work we can also process updates to $X$ and maintain $\\sum LCP(i, j)$ over adjacent pairs, thus always keeping the actual number of distinct prefixes. Now to solve the actual problem. Construct the suffix tree of $s$ in $O(n)$ or $O(n \\log n)$. We will run a DFS on the suffix tree that considers all possible positions of $u$. When we finish processing a vertex corresponding to a string $u$, we want to have the structure keeping the ordered set $X(u)$ of suffixes for $rc(u)$. To do this, consider children $w_1, \\ldots, w_k$ of $u$ in the suffix tree. Then, $X(u)$ can be obtained by merging $ex(X(w_1), |w_1| - |u|), \\ldots, ex(X(w_k), |w_k| - |u|)$, where $ex(X, l)$ is the structure obtained by prolonging all prefixes of $X$ by $l$, provided that all extensions are equal substrings. Note that $ex(X, l)$ does not require reordering of suffixes in $X$, and simply increases the answer by $l$, but we need to subtract $l$ from all starting positions in $X$, which can be done lazily. Using smallest-to-largest merging trick, we can always have an up-to-date $X(u)$ in $O(n \\log^2 n)$ total time. We compute the answer by summing over all $u$. Suppose the position of $u$ in the suffix tree is not a vertex, but is located on an edge $l$ characters above a vertex $u$. Then we need to add $l + ans(X(u))$ to the answer. Since we know $X(u)$ for all $u$, the total contribution of these positions can be accounted for in $O(1)$ per edge. If $u$ is a vertex, on the step of processing $u$ we add $ans(ex(X(w_1), |w_1| - |u| - 1) \\cup \\ldots \\cup ex(X(w_k), |w_k| - |u| - 1))$, using smallest-to-largest again. Note that we still need to return $X(u)$, thus after computing $u$'s contribution we need to undo the merging and merge again with different shifts. The total complexity is $O(n \\log^2 n)$. If we compute LCPs in $O(\\log n)$ instead of $O(1)$, we end up with $O(n \\log^3 n)$, which is pushing it, but can probably pass.",
    "tags": [
      "string suffix structures"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1277",
    "index": "A",
    "title": "Happy Birthday, Polycarp!",
    "statement": "Hooray! Polycarp turned $n$ years old! The Technocup Team sincerely congratulates Polycarp!\n\nPolycarp celebrated all of his $n$ birthdays: from the $1$-th to the $n$-th. At the moment, he is wondering: how many times he turned beautiful number of years?\n\nAccording to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $1$, $77$, $777$, $44$ and $999999$. The following numbers are not beautiful: $12$, $11110$, $6969$ and $987654321$.\n\nOf course, Polycarpus uses the decimal numeral system (i.e. radix is 10).\n\nHelp Polycarpus to find the number of numbers from $1$ to $n$ (inclusive) that are beautiful.",
    "tutorial": "It seems that one of the easiest ways to solve this problem is to iterate over all beautiful numbers up to $10^9$ and check each of the numbers to ensure that it does not exceed $n$. First of all, you can iterate over a length from $1$ to $8$, supporting a number of the form 11...1 of this length, and inside iterate over a factor for this number from $1$ to $9$. The main part of a solution might look like this:",
    "code": "cin >> n;\nint b = 0, ans = 0;\nfor (int len = 1; len <= 9; len++) {\n    b = b * 10 + 1;            \n    for (int m = 1; m <= 9; m++)\n        if (b * m <= n)\n            ans++;\n}\ncout << ans << endl;\n",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1277",
    "index": "B",
    "title": "Make Them Odd",
    "statement": "There are $n$ positive integers $a_1, a_2, \\dots, a_n$. For the one move you can choose any even value $c$ and divide by two \\textbf{all} elements that equal $c$.\n\nFor example, if $a=[6,8,12,6,3,12]$ and you choose $c=6$, and $a$ is transformed into $a=[3,8,12,3,3,12]$ after the move.\n\nYou need to find the minimal number of moves for transforming $a$ to an array of only odd integers (each element shouldn't be divisible by $2$).",
    "tutorial": "Consider the greatest positive value in the set. Anyway, once we will divide it by two. It is always optimal to do it on the first move because the result of the division can be divided again (if needed) later. So, the optimal way to solve this problem is: as long as there is at least one even value in the set, we need to choose the maximal even number in the set and divide all the numbers equal to it by $2$. For effective implementation, you can use features of the standard library to represent the set as std::set (for C++, in other languages there are alternatives of this data structure or you can modify the solution). Below is an example of a possible implementation of the main part of the solution:",
    "code": "cin >> n;\nset<int> a;\nfor (int i = 0; i < n; i++) {\n    int elem;\n    cin >> elem;\n    a.insert(elem);\n}\nint result = 0;\nwhile (!a.empty()) {\n    int m = *a.rbegin();\n    a.erase(m);\n    if (m % 2 == 0) {\n        result++;\n        a.insert(m / 2);\n    }\n}\ncout << result << endl;\n",
    "tags": [
      "greedy",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1277",
    "index": "D",
    "title": "Let's Play the Words?",
    "statement": "Polycarp has $n$ \\textbf{different} binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: \"0001\", \"11\", \"0\" and \"0011100\".\n\nPolycarp wants to offer his set of $n$ binary words to play a game \"words\". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: \"0101\", \"1\", \"10\", \"00\", \"00001\".\n\nWord reversal is the operation of reversing the order of the characters. For example, the word \"0111\" after the reversal becomes \"1110\", the word \"11010\" after the reversal becomes \"01011\".\n\nProbably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:\n\n- the final set of $n$ words still contains \\textbf{different} words (i.e. all words are unique);\n- there is a way to put all words of the final set of words in the order so that the final sequence of $n$ words is consistent with the game rules.\n\nPolycarp wants to reverse minimal number of words. Please, help him.",
    "tutorial": "For a concrete set of words, it's not hard to find a criteria for checking if there is a correct order of arrangement of words for playing a game. Let's call such sets of words correct. Firstly the set of words is correct if the number of words like 0...1 and the number of words like 1...0 differ by no more than $1$. Secondly it's correct if the number of words like 0...0 or like 1...1 is zero, because they have the same characters at the beginning and at the ending, and we can insert them in any position. And finally if words of both kinds 0...0 and 1...1 are present and there is at least one word like 0...1 or 1...0. It can be easily proved if we note that this problem is equivalent to the Euler traversal of a directed graph with two nodes. But let's prove it without resorting to graph theory: if there are words of both kinds 0...0 and 1...1, but there is no words of kinds 0...1 and 1...0, starting from a word of one kind you can't go to a word of another kind. Consequently, if words of both kinds 0...0 and 1...1 are present, there should be at least one word like 0...1 or 1...0 - is a necessary condition of the problem; if the number of words like 0...1 and the number of words like 1...0 differ by no more than $1$, we can call them alternately starting with a kind that is larger. If these numbers are equal, we can start with any kind. And we can insert words of kind 0...0 and 1...1 at any suitable moment. Reversals only affect the mutual number of lines of the kind 0...1 and 1...0. Therefore, immediately while reading the input data, we can check the necessary condition (first item above). Without loss of generality we may assume that the number of words like 0...1 equals $n_{01}$ and like 1...0 equals $n_{10}$. Also we assume that $n_{01}>n_{10}+1$. Remember that all words in the current set are unique. Let's prove that we can always choose some words of kind 0...1 and reverse them so that $n_{01}=n_{10}+1$ (and at the result all words would still be unique). In fact, the set of words of kind $n_{10}$ has no more than $n_{10}$ such words that after the reversing, the word will turn into an existing one (because it will become of type 1...0 and there are only $n_{10}$ such words). And it means that there is no less than $n_{01}-n_{10}$ words which we can reverse and get still unique word. So, we can choose any $n_{01}-n_{10}-1$ of them. Thus, after checking of the necessary condition (first item above), we need to reverse just $n_{01}-n_{10}-1$ words of kind that is larger, which reversals aren't duplicates. Below is an example of a possible implementation of the main part of the solution described above.",
    "code": "int n;\ncin >> n;\nvector<string> s(n);\nset<string> s01;\nset<string> s10;\nvector<bool> u(2);\nforn(i, n) {\n    cin >> s[i];\n    if (s[i][0] == '0' && s[i].back() == '1')\n        s01.insert(s[i]);\n    if (s[i][0] == '1' && s[i].back() == '0')\n        s10.insert(s[i]);\n    u[s[i][0] - '0'] = u[s[i].back() - '0'] = true;\n}\nif (u[0] && u[1] && s01.size() == 0 && s10.size() == 0) {\n    cout << -1 << endl;\n    continue;\n}\nvector<int> rev;\nif (s01.size() > s10.size() + 1) {\n    forn(i, n)\n        if (s[i][0] == '0' && s[i].back() == '1') {\n            string ss(s[i]);\n            reverse(ss.begin(), ss.end());\n            if (s10.count(ss) == 0)\n                rev.push_back(i);\n        }\n} else if (s10.size() > s01.size() + 1) {\n    forn(i, n)\n        if (s[i][0] == '1' && s[i].back() == '0') {\n            string ss(s[i]);\n            reverse(ss.begin(), ss.end());\n            if (s01.count(ss) == 0)\n                rev.push_back(i);\n        }\n}\nint ans = max(0, (int(max(s01.size(), s10.size())) - int(min(s01.size(), s10.size()))) / 2);\ncout << ans << endl;\nforn(i, ans)\n    cout << rev[i] + 1 << \" \";\ncout << endl;\n",
    "tags": [
      "data structures",
      "hashing",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1278",
    "index": "A",
    "title": "Shuffle Hashing",
    "statement": "Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.\n\nPolycarp decided to store the hash of the password, generated by the following algorithm:\n\n- take the password $p$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $p'$ ($p'$ can still be equal to $p$);\n- generate two random strings, consisting of lowercase Latin letters, $s_1$ and $s_2$ (any of these strings can be empty);\n- the resulting hash $h = s_1 + p' + s_2$, where addition is string concatenation.\n\nFor example, let the password $p =$ \"abacaba\". Then $p'$ can be equal to \"aabcaab\". Random strings $s1 =$ \"zyx\" and $s2 =$ \"kjh\". Then $h =$ \"zyxaabcaabkjh\".\n\nNote that no letters could be deleted or added to $p$ to obtain $p'$, only the order could be changed.\n\nNow Polycarp asks you to help him to implement the password check module. Given the password $p$ and the hash $h$, check that $h$ can be the hash for the password $p$.\n\nYour program should answer $t$ independent test cases.",
    "tutorial": "The general idea of the solution is to check that string $h$ contains some substring which is a permutation of $p$. The constraints were so low you could do it with any algorithm, even $O(n^3 \\log n)$ per test case could pass. The most straightforward way was to iterate over the substring of $h$, sort it and check if it's equal to $p$ sorted. That's $O(n^3 \\log n)$. Next you could notice than only substrings of length $|p|$ matter and shave another $n$ off the complexity to get $O(n^2 \\log n)$. After that you might remember that the size of the alphabet is pretty low. And one string is a permutation of another one if the amounts of letters 'a', letters 'b' and so on in them are equal. So you can precalculate array $cnt_p$, where $cnt_p[i]$ is equal to the amount of the $i$-th letter of the alphabet in $p$. Calculating this array for $O(n)$ substrings will be $O(n)$ each, so that makes it $O(n^2)$. Then notice how easy it is to recalculate the letter counts going from some substring $[i; i + |p| - 1]$ to $[i + 1; i + |p|]$. Just subtract $1$ from the amount of the $i$-th letter and add $1$ to the amount of the $(i + |p|)$-th letter. Comparing two array every time will still lead to $O(n \\cdot |AL|)$, though. The final optimization is to maintain the boolean array $eq$ such that $eq_i$ means that $cnt_p[i]$ is equal to the current value of $cnt$ of the substring. You are updating just two values of $cnt$ on each step, thus only two values of $eq$ might change. You want all the $|AL|$ values to be $true$, so keep the number of values $true$ in that array and say \"YES\" if that number is equal to $|AL|$. That finally makes the solution $O(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int AL = 26;\nstring p, h;\n\nbool read(){\n\tif (!(cin >> p >> h))\n\t\treturn false;\n\treturn true;\n}\n\nvoid solve(){\n\tvector<int> cntp(AL), cnt(AL);\n\tvector<bool> eq(AL);\n\tint sum = 0;\n\t\n\tauto chg = [&cntp, &cnt, &eq, &sum](int c, int val){\n\t\tsum -= eq[c];\n\t\tcnt[c] += val;\n\t\teq[c] = (cntp[c] == cnt[c]);\n\t\tsum += eq[c];\n\t};\n\t\n\tforn(i, p.size())\n\t\t++cntp[p[i] - 'a'];\n\tforn(i, AL){\n\t\teq[i] = (cnt[i] == cntp[i]);\n\t\tsum += eq[i];\n\t}\n\t\n\tint m = p.size();\n\tint n = h.size();\n\tforn(i, n){\n\t\tchg(h[i] - 'a', 1);\n\t\tif (i >= m) chg(h[i - m] - 'a', -1);\n\t\tif (sum == AL){\n\t\t\tputs(\"YES\");\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tputs(\"NO\");\n}\n\nint main() {\n\tint tc;\n\tscanf(\"%d\", &tc);\n\tforn(_, tc){\n\t\tread();\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1278",
    "index": "B",
    "title": "A and B",
    "statement": "You are given two integers $a$ and $b$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $1$; during the second operation you choose one of these numbers and increase it by $2$, and so on. You choose the number of these operations yourself.\n\nFor example, if $a = 1$ and $b = 3$, you can perform the following sequence of three operations:\n\n- add $1$ to $a$, then $a = 2$ and $b = 3$;\n- add $2$ to $b$, then $a = 2$ and $b = 5$;\n- add $3$ to $a$, then $a = 5$ and $b = 5$.\n\nCalculate the minimum number of operations required to make $a$ and $b$ equal.",
    "tutorial": "Assume that $a > b$. Let's denote the minimum number of operations required to make $a$ and $b$ equal as $x$. There are two restrictions on $x$: At first, $\\frac{x(x+1)}{2} \\ge a - b$, because if $\\frac{x(x+1)}{2} < a - b$ then $a$ will be greater than $b$ (after applying all operations); Secondly, integers $\\frac{x(x+1)}{2}$ and $a - b$ must have the same parity, because if they have different parity, then $a$ and $b$ will have different parity (after applying all operations). It turns out that we always can make integers $a$ and $b$ equal after applying $x$ operations. It's true because we have to add $\\frac{\\frac{x(x+1)}{2} - a + b}{2} + a - b$ to $b$ and the rest to $a$. And we can get any integer from $0$ to $\\frac{z(z+1)}{2}$ as a sum of subset of set $\\{1, 2, \\dots, z\\}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t, a, b;\n\nbool ok(int res, int d){\n\tlong long sum = res * 1LL * (res + 1) / 2;\n\tif(sum < d) return false;\n\treturn sum % 2 == d % 2;\n}\t\n\nint main() {\t\t\n\tcin >> t;\n\tfor(int tc = 0; tc < t; ++tc){\n\t\tcin >> a >> b;\n\t\tint d = abs(a - b);\n\t\tif(d == 0){ \n\t\t\tcout << \"0\\n\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tint res = 1;\n\t\twhile(!ok(res, d)) ++res;\n\t\tcout << res << endl;\n\t\t\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1278",
    "index": "C",
    "title": "Berry Jam",
    "statement": "Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $2n$ jars of strawberry and blueberry jam.\n\nAll the $2n$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $n$ jars to his left and $n$ jars to his right.\n\nFor example, the basement might look like this:\n\nBeing the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.\n\nFinally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.\n\nFor example, this might be the result:\n\n\\begin{center}\nHe has eaten $1$ jar to his left and then $5$ jars to his right. There remained exactly $3$ full jars of both strawberry and blueberry jam.\n\\end{center}\n\nJars are numbered from $1$ to $2n$ from left to right, so Karlsson initially stands between jars $n$ and $n+1$.\n\nWhat is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?\n\nYour program should answer $t$ independent test cases.",
    "tutorial": "Let's transit from counting strawberry and blueberry jam jars separately to their difference. Let $dif$ be equal to $\\#of\\_strawberry\\_jars - \\#of\\_blueberry\\_jars$. Then eating one strawberry jar decreases $dif$ by $1$ and eating one blueberry jar increases $dif$ by $1$. The goal is to make $dif$ equal to $0$. Let there be some initial difference $dif_{init}$. Let's eat first $l$ jars from the left and first $r$ jars from the right. Difference of the jars on the left is $difl$, on the right it's $difr$. So the goal becomes to find such $l$ and $r$ that $dif_{init} - difl_l - difr_r = 0$. Rewrite that as $dif_{init} - difl_l = difr_r$. Now for each unique value of $difr_r$ save the smallest $r$ to reach that value in a map. Finally, iterate over the $l$ and find the minimum answer. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n;\nvector<int> a;\n\nbool read(){\n\tif (scanf(\"%d\", &n) != 1)\n\t\treturn false;\n\ta.resize(2 * n);\n\tforn(i, 2 * n)\n\t\tscanf(\"%d\", &a[i]);\n\treturn true;\n}\n\nvoid solve(){\n\tint cur = 0;\n\tmap<int, int> difr;\n\t\n\tdifr[0] = 0;\n\tcur = 0;\n\tfor (int i = n; i < 2 * n; ++i){\n\t\tif (a[i] == 1)\n\t\t\t++cur;\n\t\telse\n\t\t\t--cur;\n\t\tif (!difr.count(cur))\n\t\t\tdifr[cur] = i - (n - 1);\n\t}\n\t\n\tint ans = 2 * n;\n\tint dif = count(a.begin(), a.end(), 1) - count(a.begin(), a.end(), 2);\n\t\n\tcur = 0;\n\tfor (int i = n - 1; i >= 0; --i){\n\t\tif (a[i] == 1)\n\t\t\t++cur;\n\t\telse\n\t\t\t--cur;\n\t\tif (difr.count(dif - cur))\n\t\t\tans = min(ans, n - i + difr[dif - cur]);\n\t}\n\tif (difr.count(dif)){\n\t\tans = min(ans, difr[dif]);\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}\n\nint main() {\n\tint tc;\n\tscanf(\"%d\", &tc);\n\tforn(_, tc){\n\t\tread();\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1278",
    "index": "D",
    "title": "Segment Tree",
    "statement": "As the name of the task implies, you are asked to do some work with segments and trees.\n\nRecall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices.\n\nYou are given $n$ segments $[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]$, $l_i < r_i$ for every $i$. It is guaranteed that all segments' endpoints are integers, and all endpoints are unique — there is no pair of segments such that they start in the same point, end in the same point or one starts in the same point the other one ends.\n\nLet's generate a graph with $n$ vertices from these segments. Vertices $v$ and $u$ are connected by an edge if and only if segments $[l_v, r_v]$ and $[l_u, r_u]$ intersect and neither of it lies fully inside the other one.\n\nFor example, pairs $([1, 3], [2, 4])$ and $([5, 10], [3, 7])$ will induce the edges but pairs $([1, 2], [3, 4])$ and $([5, 7], [3, 10])$ will not.\n\nDetermine if the resulting graph is a tree or not.",
    "tutorial": "The main idea of the solution is to find a linear number of intersections of segments. Intersections can be found with sweep line approach. We will maintain a set for the endpoints open segments. When we add a segment, we find all segments which intersect with it - that is, all segments that end earlier than it. Obviously, if the number of intersections are greater than $n-1$, then the answer is \"NO\". So as soon as we find $n$ intersections, we stop our algorithm. After that, it is necessary to check the connectivity of the resulting graph. You can use DFS or DSU to do this.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\ntypedef long long li;\ntypedef pair<li, li> pt;\n\nconst int N = 500010;\n\nint n;\npt a[N];\nvector<int> g[N];\nbool used[N];\n\nvoid dfs(int v, int p = -1) {\n\tused[v] = true;\n\tfor (auto to : g[v]) if (to != p) {\n\t\tif (!used[to])\n\t\t\tdfs(to, v);\n\t}\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n) scanf(\"%d%d\", &a[i].x, &a[i].y);\n\t\n\tvector<pt> evs;\n\tforn(i, n) {\n\t\tevs.pb(mp(a[i].x, i));\n\t\tevs.pb(mp(a[i].y, i));\n\t}\n\t\n\tsort(all(evs));\n\t\n\tint cnt = 0;\n\tset<pt> cur;\n\tfor (auto it : evs) {\n\t\tif (cnt >= n) break;\n\t\tif (cur.count(it)) {\n\t\t\tcur.erase(it);\n\t\t} else {\n\t\t\tint i = it.y;\n\t\t\tint r = a[i].y;\n\t\t\tfor (auto jt : cur) {\n\t\t\t\tif (jt.x > r) break;\n\t\t\t\tint j = jt.y;\n\t\t\t\tg[i].pb(j);\n\t\t\t\tg[j].pb(i);\n\t\t\t\tcnt++;\n\t\t\t\tif (cnt >= n) break;\n\t\t\t}\n\t\t\tcur.insert(mp(a[i].y, i));\n\t\t}\n\t}\n\t\n\tdfs(0);\n\tputs(cnt == n - 1 && count(used, used + n, 1) == n ? \"YES\" : \"NO\");\n}",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1278",
    "index": "E",
    "title": "Tests for problem D",
    "statement": "We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.\n\nGiven an undirected labeled tree consisting of $n$ vertices, find a set of segments such that:\n\n- both endpoints of each segment are integers from $1$ to $2n$, and each integer from $1$ to $2n$ should appear as an endpoint of exactly one segment;\n- all segments are non-degenerate;\n- for each pair $(i, j)$ such that $i \\ne j$, $i \\in [1, n]$ and $j \\in [1, n]$, the vertices $i$ and $j$ are connected with an edge if and only if the segments $i$ and $j$ intersect, but neither segment $i$ is fully contained in segment $j$, nor segment $j$ is fully contained in segment $i$.\n\nCan you solve this problem too?",
    "tutorial": "For each vertex, we will build the following structure for its children: the segment for the second child is nested in the segment for the first child, the nested for the third child is nested in the segment for the second child, and so on; and the children of different vertices do not intersect at all. Let's solve the problem recursively: for each of the children, create a set of segments with endpoints from $1$ to $2k$, where $k$ is the size of the subtree. After that, combine them. To do this, you can use small-to-large technique and change the coordinates of the segments or use the necessary offset in the function call for the next child. After that, it remains to cross children's segments with the segment of the vertex itself. To do this, you can move the right ends of all segments of the children by $1$ to the right, and add a segment that starts before the first one and ends immediately after the last one.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define pb push_back\n#define mp make_pair\n#define all(a) (a).begin(), (a).end()\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\ntypedef pair<int, int> pt;\n\nconst int N = 500 * 1000 + 13;\n\nint n;\nvector<int> g[N], vs[N];\npt segs[N];\n\nvoid dfs(int v, int p = -1) {\n\tint sum = 0;\n\tint bst = -1;\n\tfor (auto to : g[v]) if (to != p) {\n\t\tdfs(to, v);\n\t\tsum += 2 * sz(vs[to]);\n\t\tif (bst == -1 || sz(vs[to]) > sz(vs[bst]))\n\t\t\tbst = to;\n\t}\n\t\n\tif (bst == -1) {\n\t\tvs[v].pb(v);\n\t\tsegs[v] = mp(1, 2);\n\t\treturn;\n\t}\n\t\n\tswap(vs[v], vs[bst]);\n\tint lst = segs[bst].y;\n\t\n\tsum -= 2 * sz(vs[v]);\n\tsum += 1;\n\tsegs[bst].y += sum;\n\t\n\tfor (auto to : g[v]) if (to != p && to != bst) {\n\t\tint add = lst - 1;\n\t\tfor (auto u : vs[to]) {\n\t\t\tsegs[u].x += add;\n\t\t\tsegs[u].y += add;\n\t\t\tvs[v].pb(u);\n\t\t}\n\t\tlst = segs[to].y;\n\t\tsum -= 2 * sz(vs[to]);\n\t\tsegs[to].y += sum;\n\t\tvs[to].clear();\n\t}\n\t\n\tvs[v].pb(v);\n\tsegs[v] = mp(lst, segs[bst].y + 1);\n}\t\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n - 1) {\n\t\tint x, y;\n\t\tscanf(\"%d%d\", &x, &y);\n\t\t--x; --y;\n\t\tg[x].pb(y);\n\t\tg[y].pb(x);\n\t}\n\t\n\tdfs(0);\n\t\n\tfor (int i = 0; i < n; i++)\n\t\tprintf(\"%d %d\\n\", segs[i].x, segs[i].y);\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "divide and conquer",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1278",
    "index": "F",
    "title": "Cards",
    "statement": "Consider the following experiment. You have a deck of $m$ cards, and exactly one card is a joker. $n$ times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck.\n\nLet $x$ be the number of times you have taken the joker out of the deck during this experiment. Assuming that every time you shuffle the deck, all $m!$ possible permutations of cards are equiprobable, what is the expected value of $x^k$? Print the answer modulo $998244353$.",
    "tutorial": "First of all, I would like to thank Errichto for his awesome lecture on expected value: part 1, part 2. This problem was invented after I learned the concept of estimating the square of expected value from that lecture - and the editorial uses some ideas that were introduced there. Okay, now for the editorial itself. We call a number $a$ as good if $1 \\le a \\le n$, and the $a$-th shuffle of the deck resulted in a joker on top. $x$ from our problem is the number of such good numbers $a$. We can represent $x^2$ as the number of pairs $(a_1, a_2)$ such that every element of the pair is a good number, $x^3$ as the number of triples, and so on - $x^k$ is the number of $k$-tuples $(a_1, a_2, \\dots, a_k)$ such that each element of a tuple is a good number. So we can rewrite the expected value of $x^k$ as the expected number of such tuples, or the sum of $P(t)$ over all tuples $t$, where $P(t)$ is the probability that $t$ consists of good numbers. How to calculate the probability that $t$ is a good tuple? Since all shuffles of the deck result in a joker with probability $\\frac{1}{m}$, $P(t)$ should be equal to $\\frac{1}{m^k}$ - but that is true only if all elements in $t$ are unique. How to deal with tuples with repeating elements? Since all occurences of the same element are either good or bad (with probability $\\frac{1}{m}$ of being good), the correct formula for $P(t)$ is $P(t) = \\frac{1}{m^d}$, where $d$ is the number of distinct elements in the tuple. Okay, then for each $d \\in [1, k]$ we have to calculate the number of $k$-tuples with exactly $d$ distinct elements. To do that, we use dynamic programming: let $dp_{i, j}$ be the number of $i$-tuples with exactly $j$ distinct elements. Each transition in this dynamic programming solution models adding an element to the tuple; if we want to compute the transitions leading from $dp_{i, j}$, we either add a new element to the tuple (there are $n - j$ ways to choose it, and we enter the state $dp_{i + 1, j + 1}$), or we add an already existing element (there are $j$ ways to choose it, and we enter the state $dp_{i + 1, j}$). Overall complexity is $O(k^2 \\log MOD)$ or $O(k^2 + \\log MOD)$, depending on your implementation.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 5043;\n\nint add(int x, int y)\n{\n\tx += y;\n\twhile(x >= MOD) x -= MOD;\n\twhile(x < 0) x += MOD;\n\treturn x;\n}\n\nint mul(int x, int y)\n{\n\treturn (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n\tint z = 1;\n\twhile(y > 0)\n\t{\n\t\tif(y % 2 == 1)\n\t\t\tz = mul(z, x);\n\t\tx = mul(x, x);\n\t\ty /= 2;\n\t}\n\treturn z;\n}\n\nint inv(int x)\n{\n\treturn binpow(x, MOD - 2);\n}\n\nint n, m, k;\n\nint dp[N][N];\n\nint main()\n{\n\tcin >> n >> m >> k;\n\tdp[0][0] = 1;\n\tfor(int i = 0; i < k; i++)\n\t\tfor(int j = 0; j < k; j++)\n\t\t{\n\t\t\tdp[i + 1][j] = add(dp[i + 1][j], mul(dp[i][j], j));\n\t\t\tdp[i + 1][j + 1] = add(dp[i + 1][j + 1], mul(dp[i][j], n - j));\n\t\t}\n\tint ans = 0;\n\tfor(int i = 1; i <= k; i++)\n\t\tans = add(ans, mul(dp[k][i], binpow(inv(m), i)));\n\tcout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1279",
    "index": "A",
    "title": "New Year Garland",
    "statement": "Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.\n\nThe local store introduced a new service this year, called \"Build your own garland\". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!\n\nFor example, if you provide $3$ red, $3$ green and $3$ blue lamps, the resulting garland can look like this: \"RGBRBGBGR\" (\"RGB\" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.\n\nHowever, if you provide, say, $1$ red, $10$ green and $2$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.\n\nSo Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.",
    "tutorial": "Let $r \\le g \\le b$ (if it is not the case, do some swaps). If $b > r + g + 1$, then at least two blue lamps will be adjacent - so there is no solution. Otherwise the answer can be easily constucted. Place all blue lamps in a row. Then place red lamps: one between the first and the second blue lamp, one between the second and the third, and so on. Then place all green lamps: one between the $(b-1)$-th blue lamp and the $b$-th, one between the blue lamps with numbers $(b - 2)$ and $(b - 1)$, and so on. Since $r + g \\ge b - 1$, there is at least one non-blue lamp between each pair of blue lamps. If $g = b$, we didn't place all green lamps, we can place the remaining one before all other lamps (the same with $r = b$). So, if we swap $l$, $g$ and $b$ in such a way that $r \\le g \\le b$, we only have to check that $b \\le r + g + 1$.",
    "code": "for t in range(int(input())):\n\ta = sorted(list(map(int, input().split())))\n\tprint('Yes' if a[2] <= a[0] + a[1] + 1 else 'No')",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1279",
    "index": "B",
    "title": "Verse For Santa",
    "statement": "New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.\n\nVasya's verse contains $n$ parts. It takes $a_i$ seconds to recite the $i$-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes $a_1$ seconds, secondly — the part which takes $a_2$ seconds, and so on. After reciting the verse, Vasya will get the number of presents equal to the number of parts he fully recited.\n\nVasya can skip at most one part of the verse while reciting it (if he skips more than one part, then Santa will definitely notice it).\n\nSanta will listen to Vasya's verse for no more than $s$ seconds. For example, if $s = 10$, $a = [100, 9, 1, 1]$, and Vasya skips the first part of verse, then he gets two presents.\n\nNote that it is possible to recite the whole verse (if there is enough time).\n\nDetermine which part Vasya needs to skip to obtain the maximum possible number of gifts. If Vasya shouldn't skip anything, print 0. If there are multiple answers, print any of them.\n\nYou have to process $t$ test cases.",
    "tutorial": "If $\\sum\\limits_{i=1}^n a_i \\le s$ then answer is 0. Otherwise let's find we minimum index $x$ such that $\\sum\\limits_{i=1}^x a_i > s$. It's useless to skip a part $i > x$, because Vasya just has not time to recite previous part (it's change nothing). So he has to skip a part $i \\le x$. And among such parts it's beneficial to skip part with maximum value of $a_i$.",
    "code": "for t in range(int(input())):\n    n, t = map(int, input().split())\n    a = list(map(int, input().split()))\n    id = 0\n    for i in range(n):\n        if a[i] > a[id]:\n            id = i\n        t -= a[i]\n        if t < 0:\n            break\n\n    if t >= 0:\n        id = -1 \n    print(id + 1)",
    "tags": [
      "binary search",
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1279",
    "index": "C",
    "title": "Stack of Presents",
    "statement": "Santa has to send presents to the kids. He has a large stack of $n$ presents, numbered from $1$ to $n$; the topmost present has number $a_1$, the next present is $a_2$, and so on; the bottom present has number $a_n$. All numbers are distinct.\n\nSanta has a list of $m$ \\textbf{distinct} presents he has to send: $b_1$, $b_2$, ..., $b_m$. He will send them \\textbf{in the order they appear in the list}.\n\nTo send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $k$ presents above the present Santa wants to send, it takes him $2k + 1$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).\n\nWhat is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.\n\nYour program has to answer $t$ different test cases.",
    "tutorial": "At first let's precalculate array $pos$ such that $pos_{a_i} = i$. Now presume that we have to calculate answer for $b_i$. Then there are two cases (let's denote $lst = \\max\\limits_{1 \\le j < i} pos_{b_j}$, initially $lst = -1$): if $pos_{b_i} > lst$ then we have to spend $1 + 2 \\cdot (pos_{b_i} - (i - 1))$ seconds on it (1 second on the gift $b_i$, $pos_{b_i} - (i - 1)$ seconds on removing gifts above and $pos_{b_i} - (i - 1)$ seconds on pushing these gifts); if $pos_{b_i} < lst$ then we can reorder gifts by previous actions such that gift $b_i$ be on the top of stack. So we spend only 1 second on it.",
    "code": "for t in range(int(input())):\n\tn, m = map(int, input().split())\n\ta = [x - 1 for x in list(map(int, input().split()))]\n\tb = [x - 1 for x in list(map(int, input().split()))]\n\tpos = a[:]\n\tfor i in range(n):\n\t\tpos[a[i]] = i\n\t\n\tlst = -1\n\tres = m\n\tfor i in range(m):\n\t\tif pos[b[i]] > lst:\n\t\t\tres += 2 * (pos[b[i]] - i)\n\t\t\tlst = pos[b[i]]\n\t\n\tprint(res)",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1279",
    "index": "D",
    "title": "Santa's Bot",
    "statement": "Santa Claus has received letters from $n$ different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the $i$-th kid asked Santa to give them one of $k_i$ different items as a present. Some items could have been asked by multiple kids.\n\nSanta is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:\n\n- choose one kid $x$ equiprobably among all $n$ kids;\n- choose some item $y$ equiprobably among all $k_x$ items kid $x$ wants;\n- choose a kid $z$ who will receive the present equipropably among all $n$ kids (this choice is independent of choosing $x$ and $y$); the resulting triple $(x, y, z)$ is called \\textbf{the decision} of the Bot.\n\nIf kid $z$ listed item $y$ as an item they want to receive, then the decision \\textbf{valid}. Otherwise, the Bot's choice is \\textbf{invalid}.\n\nSanta is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is \\textbf{valid}. Can you help him?",
    "tutorial": "First of all, how to deal with the fractions modulo $998244353$? According to Fermat's little theorem, $x^{\\phi(m)} \\equiv 1 (mod m)$ if $x$ is coprime with $m$. So, the inverse element for the denominator $y$ is $y^{\\phi(998244353) - 1} = y^{998244351}$, taken modulo $998244353$. A cool property of fractions taken modulo $998244353$ (or any other number such that denominator is coprime with it) is that if we want to add two fractions together and calculate the result modulo some number, we can convert these fractions beforehand and then just add them as integer numbers. The same works with subtracting, multiplying, dividing and exponentiating fractions. Okay, now for the solution itself. We know that there are at most $10^6$ possible pairs of $(x, y)$; we can iterate on these pairs, calculate the probability that the fixed pair is included in the robot's decision (that probability is $\\frac{1}{x \\cdot k_x}$), and calculate the probability that $(x, y)$ extends to a valid triple (it is equal to $\\frac{cnt_y}{z}$, where $cnt_y$ is the number of kids who want item $y$). Multiplying these two probabilities, we get the probability that $(x, y)$ is chosen and produces a valid decision (since these events are independent), and we sum up these values over all possible pairs $(x, y)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define pb push_back\n#define mp make_pair\n#define sqr(a) ((a) * (a))\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int MOD = 998244353;\nconst int N = 1e6 + 7;\n\nint n;\nvector<int> a[N];\nint cnt[N];\nint inv[N];\n\nint add(int a, int b) {\n\ta += b;\n\tif (a >= MOD) a -= MOD;\n\treturn a;\n}\n\nint mul(int a, int b) {\n\treturn a * 1ll * b % MOD;\n}\n\nint binpow(int a, int b) {\n\tint res = 1;\n\twhile (b) {\n\t\tif (b & 1) res = mul(res, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n) {\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\ta[i].resize(k);\n\t\tforn(j, k) scanf(\"%d\", &a[i][j]);\n\t\tforn(j, k) cnt[a[i][j]]++;\n\t}\n\t\n\tforn(i, N) inv[i] = binpow(i, MOD - 2);\n\t\n\tint ans = 0;\n\tforn(i, n) for (auto x : a[i])\n\t\tans = add(ans, mul(mul(inv[n], inv[sz(a[i])]), mul(cnt[x], inv[n])));\n\t\t\t\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "combinatorics",
      "math",
      "probabilities"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1279",
    "index": "E",
    "title": "New Year Permutations",
    "statement": "Yeah, we failed to make up a New Year legend for this problem.\n\nA permutation of length $n$ is an array of $n$ integers such that every integer from $1$ to $n$ appears in it exactly once.\n\nAn element $y$ of permutation $p$ is reachable from element $x$ if $x = y$, or $p_x = y$, or $p_{p_x} = y$, and so on.\n\nThe \\textbf{decomposition} of a permutation $p$ is defined as follows: firstly, we have a permutation $p$, all elements of which are \\textbf{not marked}, and an empty list $l$. Then we do the following: while there is at least one \\textbf{not marked} element in $p$, we find the leftmost such element, list all elements that are reachable from it \\textbf{in the order they appear in $p$}, mark all of these elements, then cyclically shift the list of those elements so that the maximum appears at the first position, and add this list \\textbf{as an element} of $l$. After all elements are marked, $l$ is the result of this decomposition.\n\nFor example, if we want to build a decomposition of $p = [5, 4, 2, 3, 1, 7, 8, 6]$, we do the following:\n\n- initially $p = [5, 4, 2, 3, 1, 7, 8, 6]$ (bold elements are marked), $l = []$;\n- the leftmost unmarked element is $5$; $5$ and $1$ are reachable from it, so the list we want to shift is $[5, 1]$; there is no need to shift it, since maximum is already the first element;\n- $p = [\\textbf{5}, 4, 2, 3, \\textbf{1}, 7, 8, 6]$, $l = [[5, 1]]$;\n- the leftmost unmarked element is $4$, the list of reachable elements is $[4, 2, 3]$; the maximum is already the first element, so there's no need to shift it;\n- $p = [\\textbf{5}, \\textbf{4}, \\textbf{2}, \\textbf{3}, \\textbf{1}, 7, 8, 6]$, $l = [[5, 1], [4, 2, 3]]$;\n- the leftmost unmarked element is $7$, the list of reachable elements is $[7, 8, 6]$; we have to shift it, so it becomes $[8, 6, 7]$;\n- $p = [\\textbf{5}, \\textbf{4}, \\textbf{2}, \\textbf{3}, \\textbf{1}, \\textbf{7}, \\textbf{8}, \\textbf{6}]$, $l = [[5, 1], [4, 2, 3], [8, 6, 7]]$;\n- all elements are marked, so $[[5, 1], [4, 2, 3], [8, 6, 7]]$ is the result.\n\nThe New Year transformation of a permutation is defined as follows: we build the decomposition of this permutation; then we sort all lists in decomposition in ascending order of the first elements (we don't swap the elements in these lists, only the lists themselves); then we concatenate the lists into one list which becomes a new permutation. For example, the New Year transformation of $p = [5, 4, 2, 3, 1, 7, 8, 6]$ is built as follows:\n\n- the decomposition is $[[5, 1], [4, 2, 3], [8, 6, 7]]$;\n- after sorting the decomposition, it becomes $[[4, 2, 3], [5, 1], [8, 6, 7]]$;\n- $[4, 2, 3, 5, 1, 8, 6, 7]$ is the result of the transformation.\n\nWe call a permutation \\textbf{good} if the result of its transformation is the same as the permutation itself. For example, $[4, 3, 1, 2, 8, 5, 6, 7]$ is a good permutation; and $[5, 4, 2, 3, 1, 7, 8, 6]$ is bad, since the result of transformation is $[4, 2, 3, 5, 1, 8, 6, 7]$.\n\nYour task is the following: given $n$ and $k$, find the $k$-th (lexicographically) good permutation of length $n$.",
    "tutorial": "Let's calculate $cycle_n$ - the number of permutations of length $n$, which have a maximum at the position $1$ and consist of exactly one cycle. Each good permutation can be divided into such blocks, so we'll need this value later. It is easy to notice that $cycle_n = (n-2)!$. Let's calculate the following dynamic programming $dp_i$ - the number of good permutations consisting of elements $[i, n]$. To calculate $dp_i$, let's iterate over $j$ - the maximum element of the first block, it determines the length of this block $(j - i + 1)$. $dp_i = \\sum_{j=i}^n(dp_{j + 1} \\cdot cycle_{j - i - 1})$. Now let's use the standard method of lexicographic recovery. We will iterate over which element to put next, it immediately determines the size of the new block and all the elements in it. If the number of permutations starting with such block is at least $k$, then you need to restore this block entirely and reduce the task to the one without this block. Otherwise, you need to subtract the number of permutations starting on such block from $k$ and proceed to the next option for the block. We will also use lexicographic recovery to restore the block. You must carefully maintain the current block so that it consists of exactly one cycle. To do this, you can use DSU or explicitly check for a cycle.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define pb push_back\n#define mp make_pair\n#define sqr(a) ((a) * (a))\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)\n\ntypedef long long li;\ntypedef long double ld;\n\nconst int N = 55;\nconst li INF = 2e18;\n\nint n;\nli k;\n\nli cycl[N], cnt[N];\nbool used[N];\nint ans[N];\n\nli add(li x, li y) {\n\treturn min(INF, x + y);\n}\n\nli mul(li x, li y) {\n\tld t = ld(x) + y;\n\tif (t > INF) return INF;\n\treturn x * y;\n}\n\nvoid solve() {\n\tcin >> n >> k;\n\t--k;\n\n\tcycl[0] = cycl[1] = 1;\n\tfore(i, 2, n + 1) \n\t\tcycl[i] = mul(cycl[i - 1], i - 1);\n\t\t\n\tcnt[n] = 1;\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\tcnt[i] = 0;\n\t\tfore(val, i, n) {\n\t\t\tint len = (val - i) + 1;\n\t\t\tcnt[i] = add(cnt[i], mul(cnt[i + len], cycl[len - 1]));\n\t\t}\n\t}\n\t\n\tif (cnt[0] <= k) {\n\t\tcout << -1 << endl;\n\t\treturn;\n\t}\n\t\n\tmemset(used, 0, sizeof(used));\n\tmemset(ans, -1, sizeof(ans));\n\t\n\tforn(i, n) {\n\t\tfore(val, i, n) {\n\t\t\tint len = (val - i) + 1;\n\t\t\tli cur = mul(cnt[i + len], cycl[len - 1]); \n\t\t\t\n\t\t\tif (cur <= k)  {\n\t\t\t\tk -= cur;\n\t\t\t\tcontinue;\t\n\t\t\t}\n\t\t\t\n\t\t\tans[i] = val;\n\t\t\tused[val] = true;\n\t\t\t\n\t\t\tfor (int j = i + 1; j < i + len; j++) {\n\t\t\t\tint lft = len - (j - i) - 1;\n\t\t\t\tfore(nval, i, val) if (!used[nval] && j != nval) {\n\t\t\t\t\tif (j != i + len - 1) {\n\t\t\t\t\t\tint tmp = ans[nval];\n\t\t\t\t\t\twhile (tmp != -1 && tmp != j) \n\t\t\t\t\t\t\ttmp = ans[tmp];\n\t\t\t\t\t\tif (tmp == j) continue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tli cur = mul(cnt[i + len], cycl[lft]); \n\t\t\t\t\tif (cur <= k) {\n\t\t\t\t\t\tk -= cur;\n\t\t\t\t\t\tcontinue;\t\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tans[j] = nval;\n\t\t\t\t\tused[nval] = true;\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\n\t\t\ti += len - 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tforn(i, n) cout << ans[i] + 1 << ' ';\n\tcout << endl;\n}\n\nint main() {\n\tint tc;\n\tcin >> tc;\n\tforn(i, tc) solve();\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1279",
    "index": "F",
    "title": "New Year and Handle Change",
    "statement": "New Year is getting near. So it's time to change handles on codeforces. Mishka wants to change his handle but in such a way that people would not forget who he is.\n\nTo make it work, he only allowed to change letters case. More formally, during \\textbf{one} handle change he can choose any segment of his handle $[i; i + l - 1]$ and apply tolower or toupper to all letters of his handle on this segment (more fomally, replace all uppercase letters with corresponding lowercase or vice versa). The length $l$ is fixed for all changes.\n\nBecause it is not allowed to change codeforces handle too often, Mishka can perform at most $k$ such operations. What is the \\textbf{minimum} value of $min(lower, upper)$ (where $lower$ is the number of lowercase letters, and $upper$ is the number of uppercase letters) can be obtained after optimal sequence of changes?",
    "tutorial": "Let's simplify the problem a bit: we need either to minimize the number of lowercase letters or to minimize the number of uppercase letters. Both variants can be described by the following model: we have a binary array $a$ where $a[i] = 0$ if $s[i]$ is in the correct case and $a[i] = 1$ otherwise. We can do at most $k$ operations \"set $0$ on the segment $[i, i + l - 1]$\" and we'd like to minimize the total sum of $a$. At first, let's start with a solution which is pretty slow but correct. Let $dp[len][c]$ be the minimum sum of the prefix $a[0] \\dots a[len - 1]$ such that $c$ operations was already applied on it. In order to calculate this $dp$ somehow efficiently, we need to understand that it's optimal to avoid intersections of segments of applied operations so we can further specify the state of $dp$ with the following: all $c$ applied operations have their right borders $\\le len - 1$. It's easy to specify the transitions: we either apply set operation on $[len, len + l - 1]$ and relax $dp[len + l][c + 1]$ with $dp[len][c]$ or not and relax $d[len + 1][c]$ with $dp[len][c] + a[len]$. It still $O(nk)$ so we'd like to optimize it more - and we can do it using the \"lambda-optimization\" i. e. \"aliens trick\". Here we will try to describe what \"aliens trick\" is and the \"features\" of its application on the discrete calculations. In general, \"aliens trick\" allows you to get rid of the restriction on the total number of operations applied to the array (sometimes it's the number of segments in the partition of the array) by replacing it with the binary search of the value $\\lambda$ connected to it. The $\\lambda$ is the cost of using the operation (or the cost to use one more segment in the partition). In other words, we can use as many operations as we want but we need to pay for each of them. Often, we can calculate the answer without the restriction faster. The main restriction of the using this dp-optimization is the following (in case of the discrete model): consider the answer $ans(c)$ for the fixed $c$, or $dp[n][c]$. If we look at the function $ans(c)$ it should be \"somewhat convex\", i.e $ans(c - 1) - ans(c) \\ge ans(c) - ans(c + 1)$ (or, sometimes, $ans(c) - ans(c - 1) \\ge ans(c + 1) - ans(c)$) for all possible $c$. Let's look at the answers of the modified version of the problem (with cost $\\lambda$ for each used operation) as function $res(\\lambda, c)$. It's easy to prove that $res(\\lambda, c) = ans(c) + \\lambda c$ and it's also \"somewhat convex\" for a fixed $\\lambda$ (as a sum of convex functions). But, more important, it has the following property: let $c_\\lambda$ be the position where the $res(\\lambda, c)$ is the minimum possible. It can be proven (from the convex property) that $c_{\\lambda} \\ge c_{\\lambda + 1}$. This property leads to the solution: binary search $\\lambda$ while keeping track of the $c_\\lambda$, i. e. find the minimum $\\lambda$ that $c_\\lambda \\le k$. But there are several problems related to the discrete origin of the problem: The $c_\\lambda$ is not unique. In general case, there is a segment $[cl_\\lambda, cr_\\lambda]$ where the minimum $res(\\lambda, c)$ can be achieved. But there is still a property that $cl_\\lambda \\ge cl_{\\lambda + 1}$ and $cr_\\lambda \\ge cr_{\\lambda + 1}$. So we need to ensure that we will always find either minimum such $c_\\lambda$ or maximum such $c_\\lambda$. The second problem comes from the first one. There are situations when $c_\\lambda - c_{\\lambda + eps} > 1$. It creates a problem in the next situation: suppose the binary search finished with $\\lambda_{opt}$; the $c_{\\lambda_{opt} - 1} > k$ and $c_{\\lambda_{opt}} < k$. But we need to use exactly $k$ operations, what to do? Using float values will not help, so we don't need them (so we'll use usual integer bs). Suppose we minimized the $c_{\\lambda_{opt}}$ then we can show that $k \\in [cl_{\\lambda_{opt}}, cr_{\\lambda_{opt}}]$ or, in other words, $res(\\lambda_{opt}, k) = res(\\lambda_{opt}, c_{\\lambda_{opt}})$. So we can claim that we calculated the value not only for $c_{\\lambda_{opt}}$ but also for $k$. Using float values will not help, so we don't need them (so we'll use usual integer bs). Suppose we minimized the $c_{\\lambda_{opt}}$ then we can show that $k \\in [cl_{\\lambda_{opt}}, cr_{\\lambda_{opt}}]$ or, in other words, $res(\\lambda_{opt}, k) = res(\\lambda_{opt}, c_{\\lambda_{opt}})$. So we can claim that we calculated the value not only for $c_{\\lambda_{opt}}$ but also for $k$. In the end, if we can efficiently calculate $c_\\lambda$ and $res(\\lambda, c_\\lambda)$ for the fixed $\\lambda$, then we can binary search $\\lambda_{opt}$, extract $res(\\lambda_{opt}, c_{\\lambda_{opt}})$ and claim that the $dp[n][k] = res(\\lambda_{opt}, c_{\\lambda_{opt}}) - \\lambda_{opt} k$. Finally, let's discuss, how to calculate $c_\\lambda$ and $res(\\lambda, c_\\lambda)$ for a fixed $\\lambda$. Since $res(\\lambda, c_\\lambda)$ is just a minimum cost and the $c_\\lambda$ is the minimum number of operations with such cost. We can calculate it by simplifying our starting $dp$. (Remember, the cost is calculated in a next way: for each remaining $1$ in $a$ we pay $1$ and for each used operation we pay $\\lambda$). Let $d[len] = \\{cost_{len}, cnt_{len}\\}$, where $cost_{len}$ is minimum cost on the prefix of length $len$ and $cnt_{len}$ is minimum number of operations $cost_{len}$ can be achieved. Then the transitions are almost the same: we either let $a[len]$ be and relax $d[pos + 1]$ with $\\{cost_{len} + a[len], cnt_{len}\\}$ or start new operation and relax $d[pos + len]$ with $\\{cost_{len} + \\lambda, cnt_{len} + 1\\}$. The result is pair $d[n]$. Some additional information: we should carefully choose the borders of the binary search: we should choose the left border so it's optimal to use operation whenever we can (usually, $0$ or $-1$). And we should choose the right border so it's never optimal to use even one operation (usually more than the maximum possible answer). The total complexity is $O(n \\log{n})$. P. S.: We don't have the strict proof that the $ans(c)$ is convex, but we have faith and stress. We'd appreciate it if someone would share the proof in the comment section.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000 * 1000 + 11;\nconst int INF = 1e9;\n\nint n, k, l;\nstring s;\nint a[N];\npair<int, int> dp[N];\n\nint calc(int mid) {\n\tfor (int i = 0; i <= n; ++i) {\n\t\tdp[i] = make_pair(INF, INF);\n\t}\n\tdp[0] = make_pair(0, 0);\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (dp[i + 1] > make_pair(dp[i].first + a[i], dp[i].second)) {\n\t\t\tdp[i + 1] = make_pair(dp[i].first + a[i], dp[i].second);\n\t\t}\n\t\tif (dp[min(n, i + l)] > make_pair(dp[i].first + mid, dp[i].second + 1)) {\n\t\t\tdp[min(n, i + l)] = make_pair(dp[i].first + mid, dp[i].second + 1);\n\t\t}\n\t}\n\treturn dp[n].second;\n}\n\nint solve() {\n\tint l = 0, r = n;\n\tint res = 0;\n\twhile (l <= r) {\n\t\tint mid = (l + r) >> 1;\n\t\tif (calc(mid) > k) {\n\t\t\tl = mid + 1;\n\t\t\tres = mid;\n\t\t} else {\n\t\t\tr = mid - 1;\n\t\t}\n\t}\n\tif (calc(res) <= k) return 0;\n\tcalc(res + 1);\n\treturn dp[n].first - (res + 1) * 1ll * k;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n >> k >> l >> s;\n\tfor (int i = 0; i < n; ++i) {\n\t\ta[i] = islower(s[i]) > 0;\n\t}\n\tint ans = INF;\n\tans = min(ans, solve());\n\tfor (int i = 0; i < n; ++i) {\n\t\ta[i] = isupper(s[i]) > 0;\n\t}\n\tans = min(ans, solve());\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1280",
    "index": "A",
    "title": "Cut and Paste",
    "statement": "We start with a string $s$ consisting only of the digits $1$, $2$, or $3$. The length of $s$ is denoted by $|s|$. For each $i$ from $1$ to $|s|$, the $i$-th character of $s$ is denoted by $s_i$.\n\nThere is one cursor. The cursor's location $\\ell$ is denoted by an integer in $\\{0, \\ldots, |s|\\}$, with the following meaning:\n\n- If $\\ell = 0$, then the cursor is located before the first character of $s$.\n- If $\\ell = |s|$, then the cursor is located right after the last character of $s$.\n- If $0 < \\ell < |s|$, then the cursor is located between $s_\\ell$ and $s_{\\ell+1}$.\n\nWe denote by $s_\\text{left}$ the string to the left of the cursor and $s_\\text{right}$ the string to the right of the cursor.\n\nWe also have a string $c$, which we call our \\underline{clipboard}, which starts out as empty. There are three types of actions:\n\n- \\textbf{The Move action}. Move the cursor one step to the right. This increments $\\ell$ once.\n- \\textbf{The Cut action}. Set $c \\leftarrow s_\\text{right}$, then set $s \\leftarrow s_\\text{left}$.\n- \\textbf{The Paste action}. Append the value of $c$ to the end of the string $s$. Note that this doesn't modify $c$.\n\nThe cursor initially starts at $\\ell = 0$. Then, we perform the following procedure:\n\n- Perform the Move action once.\n- Perform the Cut action once.\n- Perform the Paste action $s_\\ell$ times.\n- If $\\ell = x$, stop. Otherwise, return to step 1.\n\nYou're given the initial string $s$ and the integer $x$. What is the length of $s$ when the procedure stops? Since this value may be very large, only find it modulo $10^9 + 7$.\n\nIt is guaranteed that $\\ell \\le |s|$ at any time.",
    "tutorial": "Let $S^t$ be the string $S$ after the $t$th round, and let $S^0$ be the initial $S$. We also denote by $S_{i\\ldots }$ the suffix of $S$ from the $i$th character, $S_i$, onwards. A single round turns $S^{t-1}$ into $S^t$ by replicating the suffix $S_{t+1\\ldots }^{t-1}$ exactly $S_t$ times. Hence, we have the recurrence $S^t = S^{t-1} + S_{t+1\\ldots }^{t-1}\\cdot \\left(S_t^{t-1} - 1\\right),$ In terms of lengths, we have $\\left|S^t\\right| = \\left|S^{t-1}\\right| + \\left|S_{t+1\\ldots }^{t-1}\\right|\\cdot \\left(S_t^{t-1} - 1\\right).$ $\\left|S^t\\right| = \\left|S^{t-1}\\right| + \\left(\\left|S^{t-1}\\right| - t\\right)\\cdot \\left(S_t^{t-1} - 1\\right).$ This cannot be simulated yet as it is since the length of $S$ could be growing very quickly. But notice that $S^{t-1}$ is always a prefix of $S^t$. Therefore, for any two $t_1$ and $t_2$, the $i$th letters of $S^{t_1}$ and $S^{t_2}$ are the same (as long as their lengths are at least $i$). Also, note that we only need to access up to the $x$th character, $S_x$. Therefore, we only need to grow $S$ just enough until it contains at least $x$ characters. After that, we can stop modifying $S$ at that point and simply keep track of the length, maintaining it using the recurrence above. The running time is $O(|S| + x)$. (But in languages where strings are immutable, you should use a dynamically-resizing list instead of appending strings repeatedly, otherwise, you'll get a running time of $O(x^2)$.)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconstexpr ll mod = 1'000'000'007;\nconstexpr int N = 1111;\n \nchar _s[N];\nll solve() {\n    int x;\n    scanf(\"%d%s\", &x, _s);\n    ll ls = strlen(_s);\n    vector<char> s(_s, _s + ls);\n    for (int i = 1; i <= x; i++) {\n        int v = s[i - 1] - '1';\n        if (s.size() < x) {\n            vector<char> sub(s.begin() + i, s.end());\n            for (int it = 0; it < v; it++) s.insert(s.end(), sub.begin(), sub.end());\n        }\n        ls = (ls + (ls - i) * v) % mod;\n    }\n    return ls;\n}\n \n \nint main() {\n    int z;\n    for (scanf(\"%d\", &z); z--; printf(\"%lld\\n\", (solve() % mod + mod) % mod));\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1280",
    "index": "B",
    "title": "Beingawesomeism",
    "statement": "You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a $r \\times c$ grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.\n\nOh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say $a$, passes by another country $b$, they change the dominant religion of country $b$ to the dominant religion of country $a$.\n\nIn particular, a single use of your power is this:\n\n- You choose a horizontal $1 \\times x$ subgrid or a vertical $x \\times 1$ subgrid. That value of $x$ is up to you;\n- You choose a direction $d$. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;\n- You choose the number $s$ of steps;\n- You command each country in the subgrid to send a missionary group that will travel $s$ steps towards direction $d$. In each step, they will visit (and in effect convert the dominant religion of) all $s$ countries they pass through, as detailed above.\n- The parameters $x$, $d$, $s$ must be chosen in such a way that any of the missionary groups won't leave the grid.\n\nThe following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a $1 \\times 4$ subgrid, the direction NORTH, and $s = 2$ steps.\n\nYou are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.\n\nWhat is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?\n\nWith god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.",
    "tutorial": "If everything is P, then it is clearly impossible (MORTAL). Otherwise, you can turn everything into A in at most $4$ moves, starting from any single A. Thus, the answer is between $0$ and $4$. We can exhaust all possibilities: The answer is $0$ if: Everything is an A. Otherwise, at least $1$ move is needed. Everything is an A. Otherwise, at least $1$ move is needed. The answer is $1$ if: At least one of the edge rows/columns is all As. Otherwise, it can be shown that at least $2$ moves are needed, because if every edge has at least one P, then no single move can simultaneously turn all four edges into A. To see this, note that our move must simultaneously touch all four edges. This forces us to select our initial row/column to be an entire edge row/column of the grid. But then, we are forced to have at least one P in our selection, and this P cannot be removed in this move. At least one of the edge rows/columns is all As. Otherwise, it can be shown that at least $2$ moves are needed, because if every edge has at least one P, then no single move can simultaneously turn all four edges into A. To see this, note that our move must simultaneously touch all four edges. This forces us to select our initial row/column to be an entire edge row/column of the grid. But then, we are forced to have at least one P in our selection, and this P cannot be removed in this move. The answer is $2$ if: There is one corner that's an A because in a single move, we can turn an edge into all As. There's a whole column or row of As, because again, in a single move, we can turn an edge into all As. (This case could be tricky to spot.) Otherwise, it can be shown that at least $3$ moves are needed. This is because, if we are only allowed $2$ moves, then our first move must take us to a configuration where only $1$ move is needed. In other words, in a single move, we must ensure that one edge has all As. Now, suppose we have decided which edge to turn into all As. Since all corners are Ps, our move must touch both corners of that edge, and so we are forced to copy an entire row/column up to that edge. But since every row/column has a P, this means that the edge will contain a P after the move, and hence, we have failed to turn that edge into all As. (We cannot also have accidentally turned another edge into all As since the other corners are still Ps.) There is one corner that's an A because in a single move, we can turn an edge into all As. There's a whole column or row of As, because again, in a single move, we can turn an edge into all As. (This case could be tricky to spot.) Otherwise, it can be shown that at least $3$ moves are needed. This is because, if we are only allowed $2$ moves, then our first move must take us to a configuration where only $1$ move is needed. In other words, in a single move, we must ensure that one edge has all As. Now, suppose we have decided which edge to turn into all As. Since all corners are Ps, our move must touch both corners of that edge, and so we are forced to copy an entire row/column up to that edge. But since every row/column has a P, this means that the edge will contain a P after the move, and hence, we have failed to turn that edge into all As. (We cannot also have accidentally turned another edge into all As since the other corners are still Ps.) The answer is $3$ if: There is at least one A in one of the edges, because in a single move, we can ensure that one corner becomes an A. Otherwise, it can be shown that at least $4$ moves are needed, because we can't turn any corner into A in a single move (because all edges are Ps, and only cells in edges get copied onto corners), and we also can't turn any row/column into all As in a single move (since that requires copying an entire row/column onto it, but again, note that the edges are all Ps). There is at least one A in one of the edges, because in a single move, we can ensure that one corner becomes an A. Otherwise, it can be shown that at least $4$ moves are needed, because we can't turn any corner into A in a single move (because all edges are Ps, and only cells in edges get copied onto corners), and we also can't turn any row/column into all As in a single move (since that requires copying an entire row/column onto it, but again, note that the edges are all Ps). The answer is $4$ if: It is not one of the cases above, since $4$ moves are always enough. It is not one of the cases above, since $4$ moves are always enough.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint solve(int r, int c, vector<string> grid) {\n    vector<int> rows(r), cols(c);\n    int total = 0;\n    for (int i = 0; i < r; i++) {\n        for (int j = 0; j < c; j++) {\n            if (grid[i][j] == 'A') rows[i]++, cols[j]++, total++;\n        }\n    }\n    if (total == r * c) return 0;\n    if (total == 0) return -1;\n \n    if (rows[0] == c || rows.back() == c || cols[0] == r || cols.back() == r) return 1;\n    if (grid[0][0] == 'A' || grid[0].back() == 'A' || grid.back()[0] == 'A' || grid.back().back() == 'A') return 2;\n    if (*max_element(rows.begin(), rows.end()) == c || *max_element(cols.begin(), cols.end()) == r) return 2;\n    if (rows[0] || rows.back() || cols[0] || cols.back()) return 3;\n    return 4;\n}\n \nint main() {\n    int z;\n    for (cin >> z; z--;) {\n        int r, c;\n        cin >> r >> c;\n        vector<string> grid(r);\n        for (int i = 0; i < r; i++) cin >> grid[i];\n        int res = solve(r, c, grid);\n        (~res ? cout << res : cout << \"MORTAL\") << '\\n';\n    }\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1280",
    "index": "C",
    "title": "Jeremy Bearimy",
    "statement": "Welcome! Everything is fine.\n\nYou have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.\n\nYou have a list of $k$ pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the $2k$ people into one of the $2k$ houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.\n\nOf course, in the neighborhood, it is possible to visit friends. There are $2k - 1$ roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.\n\nThe truth is, these $k$ pairs of people are actually soulmates. We index them from $1$ to $k$. We denote by $f(i)$ the amount of time it takes for the $i$-th pair of soulmates to go to each other's houses.\n\nAs we have said before, you will need to assign each of the $2k$ people into one of the $2k$ houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:\n\n- The first mission, from The Good Place, is to assign the people into the houses such that the sum of $f(i)$ over all pairs $i$ is minimized. Let's define this minimized sum as $G$. This makes sure that soulmates can easily and efficiently visit each other;\n- The second mission, from The Bad Place, is to assign the people into the houses such that the sum of $f(i)$ over all pairs $i$ is maximized. Let's define this maximized sum as $B$. This makes sure that soulmates will have a difficult time to visit each other.\n\nWhat are the values of $G$ and $B$?",
    "tutorial": "Maximization Suppose we're maximizing the sum. Consider a single edge $(a,b)$, and consider the two components on either side of this edge. Then we have an important observation: in the optimal solution, the nodes of one component are all paired with nodes on the other component. This is because otherwise, there will be at least one pair in each component that lies entirely in that component, say $(i_a, j_a)$ and $(i_b, j_b$). But if we switch the pairing to, say, $(i_a, i_b)$ and $(j_a, j_b)$, then the cost increases, because we're introducing new edges (namely $(a,b)$, among possibly others) while keeping everything from the previous pairing. Repeating this, we can construct an optimal solution where all nodes in one component are paired with nodes in the other component. This means that in the optimal solution, the edge $(a, b)$ is counted exactly $\\min(c_a, c_b)$ times, where $c_a$ is the size of the component on $a$'s side, and $c_b$ is the size of the component on $b$'s side. Therefore, the edge contributes exactly $\\mathit{weight}(a,b) \\cdot \\min(c_a, c_b)$ to the answer. But the same is true for all edges! Therefore, we can compute the answer by just summing up all contributions. The only remaining step needed is to compute the sizes of all subtrees, and this can be done with a single BFS/DFS and DP. This runs in $O(n)$. Minimization Now, suppose we're minimizing the sum. Consider again a single edge $(a,b)$. Again, we have an important observation: in the optimal solution, at most one pair passes through $(a,b)$. This is because otherwise, if there are at least two such pairs, then we can again switch the pairing (essentially the reverse of maximizing), which decreases the cost, because it doesn't introduce additional edges but it decreases the number of pairs passing through $(a,b)$ by $2$. Repeating this, we can ensure that at most one pair passes through $(a,b)$. Furthermore, the parity of the number of pairs passing through $(a,b)$ is fixed. (Why?) Therefore, in the optimal solution, $(a,b)$ is counted exactly $(c_a \\bmod 2)$ times. (Note that $c_a \\equiv c_b \\pmod{2}$) But again, the same is true for all edges! Therefore, we can compute the answer in $O(n)$ as well, by summing up all contributions.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    n <<= 1;\n    vector<vector<pair<int,ll>>> adj(n);\n    for (int i = 0; i < n - 1; i++) {\n        int a, b; ll c;\n        cin >> a >> b >> c;\n        a--, b--;\n        adj[a].emplace_back(b, c);\n        adj[b].emplace_back(a, c);\n    }\n \n    vector<int> parent(n, -1), que(1, 0);\n    vector<ll> parent_cost(n);\n    parent[0] = 0;\n    for (int f = 0; f < que.size(); f++) {\n        int i = que[f];\n        for (auto [j, c]: adj[i]) {\n            if (parent[j] == -1) {\n                parent[j] = i;\n                parent_cost[j] = c;\n                que.push_back(j);\n            }\n        }\n    }\n    vector<int> size(n, 1);\n    ll mn = 0, mx = 0;\n    reverse(que.begin(), que.end());\n    for (int i : que) {\n        size[parent[i]] += size[i];\n        mx += parent_cost[i] * min(size[i], n - size[i]);\n        mn += parent_cost[i] * (size[i] & 1);\n    }\n    cout << mn << \" \" << mx << '\\n';\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int z;\n    for (cin >> z; z--; solve());\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1280",
    "index": "D",
    "title": "Miss Punyverse",
    "statement": "The Oak has $n$ nesting places, numbered with integers from $1$ to $n$. Nesting place $i$ is home to $b_i$ bees and $w_i$ wasps.\n\nSome nesting places are connected by branches. We call two nesting places \\underline{adjacent} if there exists a branch between them. A \\underline{simple path} from nesting place $x$ to $y$ is given by a sequence $s_0, \\ldots, s_p$ of distinct nesting places, where $p$ is a non-negative integer, $s_0 = x$, $s_p = y$, and $s_{i-1}$ and $s_{i}$ are adjacent for each $i = 1, \\ldots, p$. The branches of The Oak are set up in such a way that for any two pairs of nesting places $x$ and $y$, there exists a unique simple path from $x$ to $y$. Because of this, biologists and computer scientists agree that The Oak is in fact, a tree.\n\nA \\underline{village} is a \\underline{nonempty} set $V$ of nesting places such that for any two $x$ and $y$ in $V$, there exists a simple path from $x$ to $y$ whose intermediate nesting places all lie in $V$.\n\nA set of villages $\\cal P$ is called a \\underline{partition} if each of the $n$ nesting places is contained in exactly one of the villages in $\\cal P$. In other words, no two villages in $\\cal P$ share any common nesting place, and altogether, they contain all $n$ nesting places.\n\nThe Oak holds its annual Miss Punyverse beauty pageant. The two contestants this year are Ugly Wasp and Pretty Bee. The winner of the beauty pageant is determined by voting, which we will now explain. Suppose $\\mathcal{P}$ is a partition of the nesting places into $m$ villages $V_1, \\ldots, V_m$. There is a local election in each village. Each of the insects in this village vote for their favorite contestant. If there are \\textbf{strictly} more votes for Ugly Wasp than Pretty Bee, then Ugly Wasp is said to win in that village. Otherwise, Pretty Bee wins. Whoever wins in the most number of villages wins.\n\nAs it always goes with these pageants, bees always vote for the bee (which is Pretty Bee this year) and wasps always vote for the wasp (which is Ugly Wasp this year). Unlike their general elections, no one abstains from voting for Miss Punyverse as everyone takes it very seriously.\n\nMayor Waspacito, and his assistant Alexwasp, wants Ugly Wasp to win. He has the power to choose how to partition The Oak into exactly $m$ villages. If he chooses the partition optimally, determine the maximum number of villages in which Ugly Wasp wins.",
    "tutorial": "Let's say a region is winning if there are strictly more wasps than bees. Thus, we're maximizing the number of winning regions. Tree DP seems natural in this sort of situation. For example, after rooting the tree arbitrarily, you could probably come up with something like $f(i, r)$: Given the subtree rooted at $i$ and the number of regions $r$, find the maximum number of winning regions if we partition that subtree into $r$ regions. However, this has an issue: we also need to merge our topmost component with the topmost component of some subtrees, so the subtrees' vote advantage at their topmost components matter, and must also be considered in the DP. Unfortunately, if we just naively insert the vote advantage to our DP state (or output), this means that there could potentially be too many states/outputs to fit in the time limit. Fortunately, we can keep the number of states the same by using the following greedy observation: It is optimal to maximize the number of winning regions first, and then to maximize the vote advantage at the top second. In other words, in a subtree, $(\\text{$x$ winning regions}, \\text{$-\\infty$ vote advantage})$ $(\\text{$x-1$ winning regions}, \\text{$+\\infty$ vote advantage}).$ So the DP now becomes $f(i, r)$: Given the subtree rooted at $i$ and the number of regions $r$, find the maximum number of winning regions, and among all such possibilities, find the maximum vote advantage of the top component. Just be careful that your DP solution doesn't construct size-$0$ partitions. Now, what about the time complexity? We have a state that looks like $(i, r)$, where $1 \\le r \\le \\mathit{size}(i)$, and a transition that runs in $O(r)$, so naively it feels like it runs in $O(n^3)$ in the worst case. However, if you've seen this before, this is actually the sort of DP pattern that is really $O(n^2)$, at least with the right implementation. Specifically, if we ensure that we only loop across the range where the substates are both valid, then you may check that the total amount of work done in each node is $O\\left(\\mathit{size}(i)^2 - \\sum\\limits_{\\text{$j$ is a child of $i$}} \\mathit{size}(j)^2\\right)$, and such a recurrence can be analyzed to be $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n \nstruct Group {\n    int win; ll adv;\n    Group(int win = -1, ll adv = 0): win(win), adv(adv) {}\n    Group operator+(const Group& o) const {\n        return Group(win + o.win, adv + o.adv);\n    }\n    Group operator+() const {\n        return Group(win + (adv > 0));\n    }\n    bool operator<(const Group& o) const {\n        return win < o.win || win == o.win && adv < o.adv;\n    }\n};\n \nvector<Group> convolve(const vector<Group>& fa, const vector<Group>& fb) {\n    vector<Group> fi(fa.size() + fb.size());\n    for (int a = 0; a < fa.size(); a++) {\n        for (int b = 0; b < fb.size(); b++) {\n            fi[a + b    ] = max(fi[a + b    ], fa[a] +  fb[b]);\n            fi[a + b + 1] = max(fi[a + b + 1], fa[a] + +fb[b]);\n        }\n    }\n    return fi;\n}\n \nvector<vector<Group>> f;\nvector<vector<int>> adj;\nvoid convolve_tree(int i, int p = -1) {\n    for (int j : adj[i]) {\n        if (j == p) continue;\n        convolve_tree(j, i);\n        f[i] = convolve(f[i], f[j]);\n    }\n}\n \nint solve() {\n    int n, m;\n    scanf(\"%d%d\", &n, &m);\n    f = vector<vector<Group>>(n, vector<Group>(1, Group(0)));\n    for (int i = 0, b; i < n; i++) {\n        scanf(\"%d\", &b);\n        f[i][0].adv -= b;\n    }\n    for (int i = 0, w; i < n; i++) {\n        scanf(\"%d\", &w);\n        f[i][0].adv += w;\n    }\n    adj = vector<vector<int>>(n);\n    for (int i = 1; i < n; i++) {\n        int x, y;\n        scanf(\"%d%d\", &x, &y);\n        x--, y--;\n        adj[x].push_back(y);\n        adj[y].push_back(x);\n    }\n    convolve_tree(0);\n    return (+f[0][m - 1]).win;\n}\n \nint main() {\n    int z;\n    for (scanf(\"%d\", &z); z--; printf(\"%d\\n\", solve()));\n}",
    "tags": [
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1280",
    "index": "E",
    "title": "Kirchhoff's Current Loss",
    "statement": "Your friend Kirchhoff is shocked with the current state of electronics design.\n\n\"Ohmygosh! Watt is wrong with the field? All these circuits are inefficient! There's so much capacity for improvement. The electrical engineers must not conduct their classes very well. It's absolutely revolting\" he said.\n\nThe negativity just keeps flowing out of him, but even after complaining so many times he still hasn't lepton the chance to directly change anything.\n\n\"These circuits have too much total resistance. Wire they designed this way? It's just causing a massive loss of resistors! Their entire field could conserve so much money if they just maximized the potential of their designs. Why can't they just try alternative ideas?\"\n\nThe frequency of his protests about the electrical engineering department hertz your soul, so you have decided to take charge and help them yourself. You plan to create a program that will optimize the circuits while keeping the same circuit layout and maintaining the same effective resistance.\n\nA \\underline{circuit} has two endpoints, and is associated with a certain constant, $R$, called its \\textbf{effective resistance}.\n\nThe circuits we'll consider will be formed from individual resistors joined together in \\underline{series} or in \\underline{parallel}, forming more complex circuits. The following image illustrates combining circuits in series or parallel.\n\nAccording to your friend Kirchhoff, the effective resistance can be calculated quite easily when joining circuits this way:\n\n- When joining $k$ circuits in \\underline{series} with effective resistances $R_1, R_2, \\ldots, R_k$, the effective resistance $R$ of the resulting circuit is the sum $$R = R_1 + R_2 + \\ldots + R_k.$$\n- When joining $k$ circuits in \\underline{parallel} with effective resistances $R_1, R_2, \\ldots, R_k$, the effective resistance $R$ of the resulting circuit is found by solving for $R$ in $$\\frac{1}{R} = \\frac{1}{R_1} + \\frac{1}{R_2} + \\ldots + \\frac{1}{R_k},$$ \\underline{assuming all $R_i > 0$}; if at least one $R_i = 0$, then the effective resistance of the whole circuit is simply $R = 0$.\n\nCircuits will be represented by strings. Individual resistors are represented by an asterisk, \"*\". For more complex circuits, suppose $s_1, s_2, \\ldots, s_k$ represent $k \\ge 2$ circuits. Then:\n\n- \"($s_1$ S $s_2$ S $\\ldots$ S $s_k$)\" represents their \\underline{series} circuit;\n- \"($s_1$ P $s_2$ P $\\ldots$ P $s_k$)\" represents their \\underline{parallel} circuit.\n\nFor example, \"(* P (* S *) P *)\" represents the following circuit:\n\nGiven a circuit, your task is to assign the resistances of the individual resistors such that they satisfy the following requirements:\n\n- Each individual resistor has a \\underline{nonnegative integer} resistance value;\n- The effective resistance of the whole circuit is $r$;\n- The sum of the resistances of the individual resistors is minimized.\n\nIf there are $n$ individual resistors, then you need to output the list $r_1, r_2, \\ldots, r_n$ ($0 \\le r_i$, and $r_i$ is an integer), where $r_i$ is the resistance assigned to the $i$-th individual resistor that appears in the input (from left to right). If it is impossible to accomplish the task, you must say so as well.\n\nIf it is possible, then it is guaranteed that the minimum sum of resistances is at most $10^{18}$.",
    "tutorial": "Instead of minimizing the integer cost (which feels like a hard number theory problem), let's try to minimize the real number cost first. This is a bit easier, but it should help us solve the integer case by at least giving us a lower bound. If we're allowed to assign arbitrary real numbers as costs, then we can deduce that the minimum cost to obtain a resistance of $r$ is proportional to $r$. This is because we can just scale resistances arbitrarily, so if we have an optimal solution for one given $r$ with optimal cost $c\\cdot r$, then to get any other target resistance $r'$, we can simply scale all resistances by $r'/r$, and we get a circuit with resistance $r'$ and cost $c\\cdot r'$ that should also be optimal. To prove this more rigorously, define $f(r)$ to be the optimal cost for a target resistance $r$. Then, the scaling idea above shows that $f(r') \\le f(r)\\cdot (r'/r)$, which is equivalent to $f(r')/r' \\le f(r)/r$. By symmetry, $f(r')/r' \\ge f(r)/r$, and so $f(r')/r' = f(r)/r$, for any $r, r' > 0$. Therefore, $f$ must be linear in $r$, i.e., $f(r) = c\\cdot r$ for some $c$. Thus, we just need to find this proportionality constant $c$ for our input circuit. This can be computed inductively. For a basic resistor, $c = 1$. For $k$ circuits with constants $c_1, \\ldots, c_k$ joined in series, $c = \\min(c_1, \\ldots, c_k)$. For $k$ circuits with constants $c_1, \\ldots, c_k$ joined in parallel, $\\sqrt{c} = \\sqrt{c_1} + \\ldots + \\sqrt{c_k}$. But note that all three statements imply (via induction) that $\\sqrt{c}$ is an integer! Even more, using the formulas above, we can deduce the following stronger statement: for the purposes of minimization, the whole circuit is equivalent to a parallel circuit with $\\sqrt{c}$ resistors. You can also prove this via induction, and it's actually not that hard. The hardest part is knowing what to prove in the first place. Once we have this statement, we can now turn its proof into a recursive algorithm that actually computes these $\\sqrt{c}$ parallel resistors the whole circuit is equivalent to. (The most straightforward proof of it naturally translates into such an algorithm.) We then assign a resistance of $0$ to everything else. Finally, using the same analysis as before, to obtain a resistance of $r$ in a parallel circuit of $\\sqrt{c}$ resistors, the optimal way is to assign $\\sqrt{c}\\cdot r$ to everything. But if $r$ is an integer, then $\\sqrt{c}\\cdot r$ is an integer as well, and since we're assigning $0$ to everything else, it means that the minimum cost to achieve $r$ can be achieved in integers as well!",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = 1LL << 60;\n \nclass Circuit {\npublic:\n    ll w = -1;\n    ll width() {\n        if (w == -1) compute_width();\n        return w;\n    }\n    virtual void compute_width() {}\n    virtual void assign(ll value) {}\n    virtual ostream& write_to(ostream& os) const { return os; }\n    void assign_minimal(ll value) { assign(value * width()); }\n    friend ostream& operator<<(ostream& os, const Circuit& circuit);\n};\n \nostream& operator<<(ostream& os, const Circuit& circuit) {\n    return circuit.write_to(os);\n}\n \nclass Resistor: public Circuit {\npublic:\n    ll value = -1;\n    Resistor() {}\n    void compute_width() override {\n        w = 1;\n    }\n    void assign(ll value) override {\n        this->value = value;\n    }\n    ostream& write_to(ostream& os) const override {\n        return os << ' ' << value;\n    }\n};\n \nclass Join: public Circuit {\npublic:\n    char typ;\n    vector<Circuit*> children;\n    Join() {}\n    void compute_width() override {\n        w = typ == 'S' ? INF : 0;\n        for (auto child: children) {\n            ll ww = child->width();\n            w = typ == 'S' ? min(w, ww) : w + ww;\n        }\n    }\n    void assign(ll value) override {\n        for (auto child: children) {\n            if (typ == 'S') {\n                if (child->width() == width()) {\n                    child->assign(value);\n                    value = 0;\n                } else {\n                    child->assign(0);\n                }\n            } else {\n                child->assign(value);\n            }\n        }\n    }\n    ostream& write_to(ostream& os) const override {\n        for (auto child: children) os << *child;\n        return os;\n    }\n};\n \nclass CircuitParser {\n    const string& s;\n    int i = 0;\n    CircuitParser(const string& s): s(s) {}\n    Circuit *parse() {\n        if (s[i++] == '(') {\n            Join *j = new Join();\n            while (true) {\n                j->children.push_back(parse());\n                if (s[i++] == ')') break;\n                j->typ = s[i++];\n                i++;\n            }\n            return j;\n        } else {\n            return new Resistor();\n        }\n    }\npublic:\n    static Circuit *parse(const string& s) {\n        return CircuitParser(s).parse();\n    }\n};\n \nvoid solve(ll a, const string& s) {\n    Circuit *c = CircuitParser::parse(s);\n    c->assign_minimal(a);\n    cout << \"REVOLTING\" << *c << '\\n';\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int z;\n    for (cin >> z; z--;) {\n        ll a;\n        string s;\n        cin >> a;\n        getline(cin, s);\n        assert(s[0] == ' ');\n        solve(a, s.substr(1));\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1280",
    "index": "F",
    "title": "Intergalactic Sliding Puzzle",
    "statement": "You are an intergalactic surgeon and you have an alien patient. For the purposes of this problem, we can and we will model this patient's body using a $2 \\times (2k + 1)$ rectangular grid. The alien has $4k + 1$ distinct organs, numbered $1$ to $4k + 1$.\n\nIn healthy such aliens, the organs are arranged in a particular way. For example, here is how the organs of a healthy such alien would be positioned, when viewed from the top, for $k = 4$:\n\nHere, the E represents empty space.\n\nIn general, the first row contains organs $1$ to $2k + 1$ (in that order from left to right), and the second row contains organs $2k + 2$ to $4k + 1$ (in that order from left to right) and then empty space right after.\n\nYour patient's organs are complete, and inside their body, but they somehow got shuffled around! Your job, as an intergalactic surgeon, is to put everything back in its correct position. All organs of the alien must be in its body during the entire procedure. This means that at any point during the procedure, there is exactly one cell (in the grid) that is empty. In addition, you can only move organs around by doing one of the following things:\n\n- You can switch the positions of the empty space E with any organ to its immediate left or to its immediate right (if they exist). In reality, you do this by sliding the organ in question to the empty space;\n- You can switch the positions of the empty space E with any organ to its immediate top or its immediate bottom (if they exist) \\underline{only if} the empty space is on the \\underline{leftmost} column, \\underline{rightmost} column or in the \\underline{centermost} column. Again, you do this by sliding the organ in question to the empty space.\n\nYour job is to figure out a sequence of moves you must do during the surgical procedure in order to place back all $4k + 1$ internal organs of your patient in the correct cells. If it is impossible to do so, you must say so.",
    "tutorial": "The \"shortcuts\" thing in the output section is basically a way for you to define subroutines, i.e., you can create simpler (useful) operations, and then you can combine them into more complex operations. Now, to solve the problem, we may represent the grid by the \"circular permutation\" obtained by going around the grid once, say in a clockwise order, starting from, say, the top-left corner. Without the middle column, this circular permutation cannot be changed; we can rotate it, but that's it. Thus, to make progress, we must use the middle column. The key insight here is that moving something through the middle column corresponds to one, and only one, kind of operation: which, on our circular permutation, corresponds to: Notice that it simply moved $4$ a couple of places to the right. In other words, moving through the middle corresponds to a rotation of $2k+1$ elements. Since we can also rotate the whole thing, this $(2k+1)$-rotation can be performed anywhere in our permutation. But since $(2k+1)$-rotations and full rotations (i.e., $(4k+1)$-rotations) are both even permutations, and these are the only available moves, this means that inputs that are an odd permutation away from the target state are unsolvable! (You can also notice this right away once you realize that this problem is essentially the \"sliding picture puzzle\" but with even more restricted moves.) Amazingly, the converse is true: all even permutations are solvable! This follows from the fact that we can produce a $3$-rotation from the given operations. You may want to try to come up with it yourself, so instead of giving the sequence of moves directly, I'll just give you a hint: there is a sequence of six $(2k+1)$-rotations that is equivalent to the $3$-rotation $(1 2 3)$ or $(1 3 2)$, and it only involves moving $1$, $2k+2$ and $2k+3$. (If you still can't find it, you could also write a backtracking program that finds it.) Once we have any single $3$-rotation, it can then be applied anywhere, again using with full rotations. Also, it is a well-known fact that any even permutation is representable by a product of $3$-rotations. This means that all even permutations are solvable! Now, determining which inputs are solvable is one thing, but actually finding the solution is a whole different beast. Fortunately, the \"shortcuts\" thing is here to make it a bit easier. The most important milestone is being able to come up with a sequence corresponding to a $3$-rotation; assign an uppercase letter for such an operation. After that, you will only need $3$-rotations and full rotations to solve the rest.",
    "code": "def solve(k, grid):\n    seek = *range(2*k + 2), *range(4*k + 1, 2*k + 1, -1)\n    flat = [seek[v] for v in grid[0] + grid[1][::-1] if v]\n \n    m = {\n        'L': 'l'*2*k + 'u' + 'r'*2*k + 'd',\n        'R': 'u' + 'l'*2*k + 'd' + 'r'*2*k,\n        'C': 'l'*k + 'u' + 'r'*k + 'd',\n        'D': 'CC' + 'R'*(2*k + 1) + 'CC' + 'R'*(2*k + 2),\n        'F': 'R'*(k - 1) + 'DD' + 'R'*(2*k + 1) + 'D' + 'L'*2*k + 'DD' + 'L'*k,\n        'G': 'FF',\n    }\n \n    [(i, j)] = [(i, j) for i in range(2) for j in range(2*k + 1) if grid[i][j] == 0]\n    st = 'r'*(2*k - j) + 'd'*(1 - i)\n \n    for v in range(2, 4*k + 2):\n        ct = flat.index(v)\n \n        if ct >= 2:\n            st += 'L'*(ct - 2) + 'GR'*(ct - 2) + 'G'\n            flat = flat[ct - 1: ct + 1] + flat[:ct - 1] + flat[ct + 1:]\n \n        if ct >= 1:\n            st += 'G'\n            flat = flat[1:3] + flat[:1] + flat[3:]\n \n        st += 'L'\n        flat = flat[1:] + flat[:1]\n        \n    if flat[0] == 1: return st, m\n \ndef main():\n    def get_line():\n        return [0 if x == 'E' else int(x) for x in input().split()]\n \n    for cas in range(int(input())):\n        res = solve(int(input()), [get_line() for i in range(2)])\n        if res is None:\n            print('SURGERY FAILED')\n        else:\n            print('SURGERY COMPLETE')\n            st, m = res\n            print(st)\n            for shortcut in m.items(): print(*shortcut)\n            print('DONE')\n \nmain()",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1281",
    "index": "A",
    "title": "Suffix Three",
    "statement": "We just discovered a new data structure in our research group: a \\textbf{suffix three}!\n\nIt's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.\n\nIt's super simple, 100% accurate, and doesn't involve advanced machine learning algorithms.\n\nLet us tell you how it works.\n\n- If a sentence ends with \"po\" the language is Filipino.\n- If a sentence ends with \"desu\" or \"masu\" the language is Japanese.\n- If a sentence ends with \"mnida\" the language is Korean.\n\nGiven this, we need you to implement a suffix three that can differentiate Filipino, Japanese, and Korean.\n\nOh, did I say three suffixes? I meant four.",
    "tutorial": "The simplest way to solve it is to use your language's builtin string methods like ends_with. (It might be different in your preferred language.) Alternatively, if you know how to access the individual letters of a string, then you may implement something similar to ends_with yourself. To print the required output, you can just use something like: Alternatively, notice that you can simply check the last letter since o, u and a are distinct, so it can be simplified slightly. One can even write a Python one-liner (for a single test case):",
    "code": "for cas in range(int(input())): print({'o': \"FILIPINO\", 'a': \"KOREAN\", 'u': \"JAPANESE\"}[input()[-1]])",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1281",
    "index": "B",
    "title": "Azamon Web Services",
    "statement": "Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call \\textbf{Azamon}. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.\n\nAfter doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!\n\nTo make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.\n\nPlease help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!\n\nGiven the string $s$ representing Jeff's product name and the string $c$ representing his competitor's product name, find a way to swap \\textbf{at most one pair} of characters in $s$ (that is, find two distinct indices $i$ and $j$ and swap $s_i$ and $s_j$) such that the resulting new name becomes strictly lexicographically smaller than $c$, or determine that it is impossible.\n\n\\textbf{Note:} String $a$ is \\underline{strictly lexicographically smaller} than string $b$ if and only if one of the following holds:\n\n- $a$ is a \\underline{proper prefix} of $b$, that is, $a$ is a \\underline{prefix} of $b$ such that $a \\neq b$;\n- There exists an integer $1 \\le i \\le \\min{(|a|, |b|)}$ such that $a_i < b_i$ and $a_j = b_j$ for $1 \\le j < i$.",
    "tutorial": "The problem becomes a bit easier if we try to answer a different question: What is the lexicographically smallest string we can form from $S$? We then simply compare this string with $C$. This works because if the smallest string we can form is not smaller than $C$, then clearly no other string we can form will be smaller than $C$. To find the lexicographically smallest string we can form, we can be greedy. We sort $S$ and find the first letter that isn't in its correct sorted position. In other words, find the first position where $S$ and $\\mathrm{sorted}(S)$ doesn't match. We then find the letter that should be in that position and put it in its correct position. If there are multiple choices, it is better to take the one that occurs last, since it makes the resulting string smallest. A special case is when $S$ is already sorted. In this case, we can't make $S$ any smaller, so we should not swap at all. The solution runs in $O(|S| \\log |S|)$, but solutions running in $O(|S|^2)$ are also accepted. (There are other, different solutions that run in $O(|S|^2)$.) This can be improved to $O(|S|)$ by replacing the sorting step with simpler operations, since we don't actually need the full sorted version of $S$.",
    "code": "def solve(s, t):\n    mns = list(s)\n    for i in range(len(s)-2,-1,-1): mns[i] = min(mns[i], mns[i + 1])\n    for i in range(len(s)):\n        if s[i] != mns[i]:\n            j = max(j for j, v in enumerate(s[i:], i) if v == mns[i])\n            s = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]\n            break\n    return s if s < t else '---'\n \nfor cas in range(int(input())):\n    print(solve(*input().split()))",
    "tags": [
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1282",
    "index": "A",
    "title": "Temporarily unavailable",
    "statement": "Polycarp lives on the coordinate axis $Ox$ and travels from the point $x=a$ to $x=b$. It moves uniformly rectilinearly at a speed of one unit of distance per minute.\n\nOn the axis $Ox$ at the point $x=c$ the base station of the mobile operator is placed. It is known that the radius of its coverage is $r$. Thus, if Polycarp is at a distance less than or equal to $r$ from the point $x=c$, then he is in the network coverage area, otherwise — no. The base station can be located both on the route of Polycarp and outside it.\n\nPrint the time in minutes during which Polycarp will \\textbf{not be} in the coverage area of the network, with a rectilinear uniform movement from $x=a$ to $x=b$. His speed — one unit of distance per minute.",
    "tutorial": "To get an answer, we need to subtract from the whole time the time that we will be in the coverage area. Let the left boundary of the cover be $L=c-r$, and the right boundary of the cover be $R=c+r$. Then the intersection boundaries will be $st=max(L,min(a,b))$, $ed=min(R, max(a,b))$. Then the answer is calculated by the formula $|b-a|-max(0, ed - st)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int a, b, c, r;\n        cin >> a >> b >> c >> r;\n        int L = max(min(a, b), c - r);\n        int R = min(max(a, b), c + r);\n        cout << max(a, b) - min(a, b) - max(0, R - L) << endl;\n    }\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1282",
    "index": "B2",
    "title": "K for the Price of One (Hard Version)",
    "statement": "This is the hard version of this problem. The only difference is the constraint on $k$ — the number of gifts in the offer. In this version: $2 \\le k \\le n$.\n\nVasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer \"$k$ of goods for the price of one\" is held in store.\n\nUsing this offer, Vasya can buy \\textbf{exactly} $k$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.\n\nMore formally, for each good, its price is determined by $a_i$ — the number of coins it costs. Initially, Vasya has $p$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:\n\n- Vasya can buy one good with the index $i$ if he currently has enough coins (i.e $p \\ge a_i$). After buying this good, the number of Vasya's coins will decrease by $a_i$, (i.e it becomes $p := p - a_i$).\n- Vasya can buy a good with the index $i$, and also choose exactly $k-1$ goods, the price of which does not exceed $a_i$, if he currently has enough coins (i.e $p \\ge a_i$). Thus, he buys all these $k$ goods, and his number of coins decreases by $a_i$ (i.e it becomes $p := p - a_i$).\n\nPlease note that each good can be bought no more than once.\n\nFor example, if the store now has $n=5$ goods worth $a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$, respectively, $k=2$, and Vasya has $6$ coins, then he can buy $3$ goods. A good with the index $1$ will be bought by Vasya without using the offer and he will pay $2$ coins. Goods with the indices $2$ and $3$ Vasya will buy using the offer and he will pay $4$ coins. It can be proved that Vasya can not buy more goods with six coins.\n\nHelp Vasya to find out the maximum number of goods he can buy.",
    "tutorial": "If you sort the array by costs, it will always be profitable to take segments of length $k$ with the cheapest possible end. It remains only to understand when you need to take gifts without a promotion. It makes no sense to take $k$ or more gifts without a promotion, so we can combine them and buy together. It also makes no sense to take not the cheapest gifts without a stock, since the total cost from this will only increase. So the solution to the problem is to iterate over the prefix in a sorted array of length no more than $k$, and then buy items together for $k$ pieces. This solution works in the linear time since we will always look at elements with a different index by modulo $k$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\nint main() {\n    int cntTest;\n    cin >> cntTest;\n    for (int test = 0; test < cntTest; test++) {\n        int n, p, k;\n        cin >> n >> p >> k;\n        int pref = 0;\n        int ans = 0;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n        sort(a.begin(), a.end());\n        for (int i = 0; i <= k; i++) {\n            int sum = pref;\n            if (sum > p) break;\n            int cnt = i;\n            for (int j = i + k - 1; j < n; j += k) {\n                if (sum + a[j] <= p) {\n                    cnt += k;\n                    sum += a[j];\n                } else {\n                    break;\n                }\n            }\n            pref += a[i];\n            ans = max(ans, cnt);\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1282",
    "index": "C",
    "title": "Petya and Exam",
    "statement": "Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.\n\nThe exam consists of $n$ problems that can be solved in $T$ minutes. Thus, the exam begins at time $0$ and ends at time $T$. Petya can leave the exam at any integer time from $0$ to $T$, inclusive.\n\nAll problems are divided into two types:\n\n- easy problems — Petya takes exactly $a$ minutes to solve any easy problem;\n- hard problems — Petya takes exactly $b$ minutes ($b > a$) to solve any hard problem.\n\nThus, if Petya starts solving an easy problem at time $x$, then it will be solved at time $x+a$. Similarly, if at a time $x$ Petya starts to solve a hard problem, then it will be solved at time $x+b$.\n\nFor every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $t_i$ ($0 \\le t_i \\le T$) at which it will become mandatory (required). If Petya leaves the exam at time $s$ and there is such a problem $i$ that $t_i \\le s$ and he didn't solve it, then he will receive $0$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $t_i \\le s$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $s$ Petya can have both \"mandatory\" and \"non-mandatory\" problems solved.\n\nFor example, if $n=2$, $T=5$, $a=2$, $b=3$, the first problem is hard and $t_1=3$ and the second problem is easy and $t_2=2$. Then:\n\n- if he leaves at time $s=0$, then he will receive $0$ points since he will not have time to solve any problems;\n- if he leaves at time $s=1$, he will receive $0$ points since he will not have time to solve any problems;\n- if he leaves at time $s=2$, then he can get a $1$ point by solving the problem with the number $2$ (it must be solved in the range from $0$ to $2$);\n- if he leaves at time $s=3$, then he will receive $0$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;\n- if he leaves at time $s=4$, then he will receive $0$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;\n- if he leaves at time $s=5$, then he can get $2$ points by solving all problems.\n\nThus, the answer to this test is $2$.\n\nHelp Petya to determine the maximal number of points that he can receive, before leaving the exam.",
    "tutorial": "Sort all problems by time $t_i$. You may notice that it is profitably to leave the exam at only one of the time points $t_i-1$. $t_i$ - a time when the task with the number $i$ becomes mandatory. Leaving at any other time in the range from $t_{i-1}$ to $t_i-2$ does not make sense since new mandatory tasks cannot appear at this time, and there is always less time to solve than at the moment $t_i - 1$. Then for each such moment, we need to know how many simple and hard tasks have already become mandatory. Then we know the time that we need to spend on solving them. The remaining time can be spent on other tasks. It is more profitable to solve simple at first, and then hard. It remains only to consider all such moments and take the maximum of the tasks solved among them, which will be the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\nint main() {\n    int cntTest;\n    cin >> cntTest;\n    for (int test = 0; test < cntTest; test++) {\n        ll n, t, a, b;\n        cin >> n >> t >> a >> b;\n        vector<pair<ll, ll>> v;\n        vector<int> hard(n);\n        int cntA = 0, cntB = 0;\n        for (int i = 0; i < n; i++) {\n            cin >> hard[i];\n            if (hard[i]) {\n                cntB++;\n            } else {\n                cntA++;\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            ll time;\n            cin >> time;\n            v.push_back({time, hard[i]});\n        }\n        v.push_back({t + 1, 0});\n        sort(v.begin(), v.end());\n        ll cnt1 = 0, cnt2 = 0;\n        ll ans = 0;\n        for (int i = 0; i <= n; i++) {\n            ll need = cnt1 * a + cnt2 * b;\n            ll has = v[i].first - 1 - need;\n            if (has >= 0) {\n                ll canA = min((cntA - cnt1), has / a);\n                has -= canA * a;\n                ll canB = min((cntB - cnt2), has / b);\n                ans = max(ans, cnt1 + cnt2 + canA + canB);\n            }\n            int l = i;\n            while (l < v.size() && v[l].first == v[i].first) {\n                if (v[l].second) {\n                    cnt2++;\n                } else {\n                    cnt1++;\n                }\n                l++;\n            }\n            i = l - 1;\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1282",
    "index": "D",
    "title": "Enchanted Artifact",
    "statement": "\\textbf{This is an interactive problem.}\n\nAfter completing the last level of the enchanted temple, you received a powerful artifact of the 255th level. Do not rush to celebrate, because this artifact has a powerful rune that can be destroyed with a single spell $s$, which you are going to find.\n\nWe define the spell as some \\textbf{non-empty string} consisting only of the letters a and b.\n\nAt any time, you can cast an arbitrary non-empty spell $t$, and the rune on the artifact will begin to resist. Resistance of the rune is the edit distance between the strings that specify the casted spell $t$ and the rune-destroying spell $s$.\n\nEdit distance of two strings $s$ and $t$ is a value equal to the minimum number of one-character operations of replacing, inserting and deleting characters in $s$ to get $t$. For example, the distance between ababa and aaa is $2$, the distance between aaa and aba is $1$, the distance between bbaba and abb is $3$. The edit distance is $0$ if and only if the strings are equal.\n\nIt is also worth considering that the artifact has a resistance limit  — if you cast more than $n + 2$ spells, where $n$ is the length of spell $s$, the rune will be blocked.\n\nThus, it takes $n + 2$ or fewer spells to destroy the rune that is on your artifact. Keep in mind that the required destructive spell $s$ must also be counted among these $n + 2$ spells.\n\nNote that the length $n$ of the rune-destroying spell $s$ is not known to you in advance. It is only known that its length $n$ does not exceed $300$.",
    "tutorial": "Firstly, let's find out the number of letters a and b in the hidden string in two queries. This can be done, for example, using queries aaa ... aaa and bbb ... bbb of length $300$. Let the answers to these queries be $q_a$ and $q_b$, then the number of letters a and b would be $\\#a = 300 - q_a$ and $\\#b = 300 - q_b$ respectively. These answers are explained by the fact that i. e. for string aaa ... aaa it takes $300 - \\#a - \\#b$ steps to remove the letters a at the end of the string and then replace $\\#b$ letters a with b to change the string aaa ... aaa into the string $s$. Now we know the length $l = \\#a + \\#b$. Consider an arbitrary string $t$ of length $l$ and let the answer to its query be $q$. Then if we replace the letter $t_i$ with the opposite one (from a to b or from b to a), then we may have one of two situations: $q$ decreased by $1$, then the letter $t_i$ after the change coincides with the letter $s_i$. otherwise the letter $t_i$ before the change matches the letter $s_i$. Thus, you can loop from left to right and for each position $i$ find out the character $t_i$, starting, for example, from the string aaa ... aaa of length $l$. The current algorithm guesses the string in $n + 3$ queries. In order to get rid of one unnecessary query, note that we do not need to make a query to find out the character in the last position. If the number of letters a whose location we know is equal to $\\#a$, then the last character cannot be a, which means it is b. Similarly for the symmetric case. Thus, we can guess the string in $n + 2$ queries. Similarly, it is possible to solve for an arbitrary alphabet in $(|\\Sigma| - 1) n + 2$ queries, where $|\\Sigma|$ is the size of the alphabet. For an arbitrary alphabet, there is also a solution using random which solves the problem on average in $\\frac{|\\Sigma|}{2} n + 2$ queries, but it will not work in this task, since the chance to spend more than $n + 2$ queries is quite large.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint f(string s) {\n    cout << s << endl;\n    int w;\n    cin >> w;\n    if (w == 0)\n        exit(0);\n    return w;\n}\n \nint main() {\n    const int N = 300;\n    int st = f(string(N, 'a'));\n    int n = 2 * N - (st + f(string(N, 'b')));\n    string t(n, 'a');\n    int A = N - st, B = n - A;\n    st = B;\n    for (int i = 0; i < n - 1; i++) {\n        t[i] = 'b';\n        if (f(t) > st)\n            t[i] = 'a';\n        else\n            st--;\n    }\n    if (st)\n        t.back() = 'b';\n    f(t);\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1282",
    "index": "E",
    "title": "The Cake Is a Lie",
    "statement": "We are committed to the well being of all participants. Therefore, instead of the problem, we suggest you enjoy a piece of cake.\n\nUh oh. Somebody cut the cake. We told them to wait for you, but they did it anyway. There is still some left, though, if you hurry back. Of course, before you taste the cake, you thought about how the cake was cut.\n\nIt is known that the cake was originally a regular $n$-sided polygon, each vertex of which had a unique number from $1$ to $n$. The vertices were numbered in random order.\n\nEach piece of the cake is a triangle. The cake was cut into $n - 2$ pieces as follows: each time one cut was made with a knife (from one vertex to another) such that exactly one triangular piece was separated from the current cake, and the rest continued to be a convex polygon. In other words, each time three consecutive vertices of the polygon were selected and the corresponding triangle was cut off.\n\nA possible process of cutting the cake is presented in the picture below.\n\n\\begin{center}\n{\\small Example of 6-sided cake slicing.}\n\\end{center}\n\nYou are given a set of $n-2$ triangular pieces in random order. The vertices of each piece are given in random order — clockwise or counterclockwise. Each piece is defined by three numbers — the numbers of the corresponding $n$-sided cake vertices.\n\nFor example, for the situation in the picture above, you could be given a set of pieces: $[3, 6, 5], [5, 2, 4], [5, 4, 6], [6, 3, 1]$.\n\nYou are interested in two questions.\n\n- What was the enumeration of the $n$-sided cake vertices?\n- In what order were the pieces cut?\n\nFormally, you have to find two permutations $p_1, p_2, \\dots, p_n$ ($1 \\le p_i \\le n$) and $q_1, q_2, \\dots, q_{n - 2}$ ($1 \\le q_i \\le n - 2$) such that if the cake vertices are numbered with the numbers $p_1, p_2, \\dots, p_n$ in order clockwise or counterclockwise, then when cutting pieces of the cake in the order $q_1, q_2, \\dots, q_{n - 2}$ always cuts off a triangular piece so that the remaining part forms one convex polygon.\n\nFor example, in the picture above the answer permutations could be: $p=[2, 4, 6, 1, 3, 5]$ (or any of its cyclic shifts, or its reversal and after that any cyclic shift) and $q=[2, 4, 1, 3]$.\n\nWrite a program that, based on the given triangular pieces, finds any suitable permutations $p$ and $q$.",
    "tutorial": "The problem can be solved in different ways: one can independently find both permutations, or use one to find another. Firstly, let's find $q$ - the order of cutting cake pieces. Let's take a look at the edges of the first piece. This triangle has a common side with no more than one other piece. If it has no common sides with other triangles - there is only one triangle, the answer is trivial. So we consider that the first triangle is adjacent to exactly one other triangle. After cutting off this triangle, we have a similar problem for a ($n - 1$)-sided cake. Let the first triangle be any triangle adjacent only to $1$ another triangle, cut it off, solve the problem recursively. This can be done by building for the polygon dual graph. The remaining problem is to find the permutation $p$: Let's use $q$ to find $p$. Reverse $q$ to get the order of adding triangles to obtain the desired polygon. This can be done by adding to the doubly-linked list a triangle vertex, that wasn't in the list before, between two existing ones. Let's note that each side of the cake is found exactly once in the input, the other edges are found twice. So we have to find these sides of the polygon, then we get a doubly-linked list, which represents $p$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid dfs_order(int u, int p, vector<vector<int>> const& g, vector<int> &order) {\n    for (auto v : g[u]) {\n        if (v != p) {\n            dfs_order(v, u, g, order);\n        }\n    }\n    order.push_back(u);\n}\n\nvoid get_order(map<pair<int, int>, vector<int>> const& in, int n, vector<int> &order) {\n    vector<vector<int>> g(n);\n    for (auto e : in) {\n        auto vs = e.second;\n\n        if (vs.size() == 2) {\n            g[vs[0]].push_back(vs[1]);\n            g[vs[1]].push_back(vs[0]);\n        }\n    }\n\n    dfs_order(0, -1, g, order);\n}\n\nvoid dfs_polygon(int u, vector<vector<int>> const& g, vector<bool> &used, vector<int> &res) {\n    if (used[u]) {\n        return;\n    }\n    used[u] = true;\n    res.push_back(u);\n    for (auto e : g[u]) {\n        dfs_polygon(e, g, used, res);\n    }\n}\n\nvoid get_polygon(map<pair<int, int>, vector<int>> const& in, int n, vector<int> &polygon) {\n    vector<vector<int>> g(n);\n    for (auto e : in) {\n        if (e.second.size() == 1) {\n            auto edge = e.first;\n            g[edge.first].push_back(edge.second);\n            g[edge.second].push_back(edge.first);\n        }\n    }\n\n    vector<bool> used(n);\n    dfs_polygon(0, g, used, polygon);\n}\n\nvoid get_polygon(vector<vector<int>> const& in, int n, vector<int> const& order, vector<int> &polygon) {\n    vector<pair<int, int>> listp(n, {-1, -1});\n    auto last = in[order.back()];\n    for (int i = 0; i < 3; i++) {\n        listp[last[i]] = {last[(i + 1) % 3], last[(i + 2) % 3]};\n    }\n\n    for (int i = (int) order.size() - 2; i >= 0; i--) {\n        auto x = in[order[i]];\n\n        int j = 0;\n        while (listp[x[j]] != pair<int, int>{-1, -1}) {\n            j++;\n        }\n\n        int x1 = x[j], x2 = x[(j + 1) % 3], x3 = x[(j + 2) % 3];\n        if (listp[x2].second != x3) {\n            swap(x2, x3);\n        }\n\n        listp[x1] = {x2, x3};\n        listp[x2].second = x1;\n        listp[x3].first = x1;\n    }\n\n    polygon.push_back(0);\n\n    int now = listp[0].second;\n    while (now != 0) {\n        polygon.push_back(now);\n        now = listp[now].second;\n    }\n}\n\nvoid out(vector<int> const& v) {\n    for (auto e : v) {\n        cout << e + 1 << ' ';\n    }\n    cout << endl;\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n\n    vector<vector<int>> in(n - 2, vector<int>(3));\n    for (int i = 0; i < n - 2; i++) {\n        for (int j = 0; j < 3; j++) {\n            cin >> in[i][j];\n            in[i][j]--;\n        }\n        sort(in[i].begin(), in[i].end());\n    }\n\n    map<pair<int, int>, vector<int>> mp;\n    for (int i = 0; i < n - 2; i++) {\n        auto tri = in[i];\n        for (int j = 0; j < 2; j++) {\n            for (int k = j + 1; k < 3; k++) {\n                mp[{tri[j], tri[k]}].push_back(i);\n            }\n        }\n    }\n\n    vector<int> order;\n    get_order(mp, n, order);\n\n    vector<int> polygon;\n    get_polygon(in, n, order, polygon);\n    // get_polygon(mp, n, polygon);  // another solution\n\n    out(polygon);\n    out(order);\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    for (int t_num = 1; t_num <= t; t_num++) {\n        solve();\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1283",
    "index": "A",
    "title": "Minutes Before the New Year",
    "statement": "New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $h$ hours and $m$ minutes, where $0 \\le hh < 24$ and $0 \\le mm < 60$. We use 24-hour time format!\n\nYour task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $0$ hours and $0$ minutes.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "In this problem we just need to print $1440 - 60h - m$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tscanf(\"%d\", &q);\n\tfor (int i = 0; i < q; ++i) {\n\t\tint h, m;\n\t\tscanf(\"%d %d\", &h, &m);\n\t\tprintf(\"%d\\n\", 1440 - h * 60 - m);\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1283",
    "index": "B",
    "title": "Candies Division",
    "statement": "Santa has $n$ candies and he wants to gift them to $k$ kids. He wants to divide as many candies as possible between all $k$ kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.\n\nSuppose the kid who recieves the minimum number of candies has $a$ candies and the kid who recieves the maximum number of candies has $b$ candies. Then Santa will be \\textbf{satisfied}, if the both conditions are met at the same time:\n\n- $b - a \\le 1$ (it means $b = a$ or $b = a + 1$);\n- the number of kids who has $a+1$ candies (\\textbf{note that $a+1$ not necessarily equals $b$}) does not exceed $\\lfloor\\frac{k}{2}\\rfloor$ (less than or equal to $\\lfloor\\frac{k}{2}\\rfloor$).\n\n$\\lfloor\\frac{k}{2}\\rfloor$ is $k$ divided by $2$ and rounded \\textbf{down} to the nearest integer. For example, if $k=5$ then $\\lfloor\\frac{k}{2}\\rfloor=\\lfloor\\frac{5}{2}\\rfloor=2$.\n\nYour task is to find the maximum number of candies Santa can give to kids so that he will be \\textbf{satisfied}.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, we can notice that we always can distribute $n - n \\% k$ (where $\\%$ is the modulo operation) candies between kids. In this case $a=\\lfloor\\frac{n}{k}\\rfloor$ and the answer is at least $ak$. And then we can add the value $min(n \\% k, \\lfloor\\frac{k}{2}\\rfloor)$ to the answer. Why? Because there is only $n \\% k$ candies remain and the maximum number of kids to whom we can give one more candy is $\\lfloor\\frac{k}{2}\\rfloor$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tint full = n - n % k;\n\t\tfull += min(n % k, k / 2);\n\t\tcout << full << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1283",
    "index": "C",
    "title": "Friends and Gifts",
    "statement": "There are $n$ friends who want to give gifts for the New Year to each other. Each friend should give \\textbf{exactly} one gift and receive \\textbf{exactly} one gift. The friend \\textbf{cannot} give the gift to himself.\n\nFor each friend the value $f_i$ is known: it is either $f_i = 0$ if the $i$-th friend doesn't know whom he wants to give the gift to or $1 \\le f_i \\le n$ if the $i$-th friend wants to give the gift to the friend $f_i$.\n\nYou want to fill in the unknown values ($f_i = 0$) in such a way that each friend gives \\textbf{exactly} one gift and receives \\textbf{exactly} one gift and there is \\textbf{no} friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.\n\nIf there are several answers, you can print any.",
    "tutorial": "In this problem, we need to print the permutation without fixed points (without values $p_i = i$) but some values are known in advance. Let's consider the permutation as a graph. We know that the permutation is the set of non-intersecting cycles. In this problem, we are given such a graph but some edges are removed. How to deal with it? Firstly, let's find isolated vertices in the graph. Let its number be $cnt$. If $cnt=0$ then all is ok and we skip the current step. If $cnt=1$ then let's pin this isolated vertex to any vertex to which we can pin it. Otherwise, $cnt>1$ and we can create the chine consisting of all isolated vertices. Now $cnt=0$ and we can finally construct the remaining part of the graph. We can notice that we have the same number of vertices with zero incoming and zero outcoming degrees. And because we got rid of all possible loops in the graph, we can match these vertices as we want. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> f(n);\n\tvector<int> in(n), out(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> f[i];\n\t\t--f[i];\n\t\tif (f[i] != -1) {\n\t\t\t++out[i];\n\t\t\t++in[f[i]];\n\t\t}\n\t}\n\t\n\tvector<int> loops;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (in[i] == 0 && out[i] == 0) {\n\t\t\tloops.push_back(i);\n\t\t}\n\t}\n\tif (loops.size() == 1) {\n\t\tint idx = loops[0];\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (in[i] == 0 && i != idx) {\n\t\t\t\tf[idx] = i;\n\t\t\t\t++out[idx];\n\t\t\t\t++in[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (loops.size() > 1) {\n\t\tfor (int i = 0; i < int(loops.size()); ++i) {\n\t\t\tint cur = loops[i];\n\t\t\tint nxt = loops[(i + 1) % int(loops.size())];\n\t\t\tf[cur] = nxt;\n\t\t\t++out[cur];\n\t\t\t++in[nxt];\n\t\t}\n\t}\n\tloops.clear();\n\tvector<int> ins, outs;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (in[i] == 0) ins.push_back(i);\n\t\tif (out[i] == 0) outs.push_back(i);\n\t}\n\tassert(ins.size() == outs.size());\n\tfor (int i = 0; i < int(outs.size()); ++i) {\n\t\tf[outs[i]] = ins[i];\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tcout << f[i] + 1 << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1283",
    "index": "D",
    "title": "Christmas Trees",
    "statement": "There are $n$ Christmas trees on an infinite number line. The $i$-th tree grows at the position $x_i$. All $x_i$ are guaranteed to be distinct.\n\nEach \\textbf{integer} point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.\n\nThere are $m$ people who want to celebrate Christmas. Let $y_1, y_2, \\dots, y_m$ be the positions of people (note that all values $x_1, x_2, \\dots, x_n, y_1, y_2, \\dots, y_m$ should be \\textbf{distinct} and all $y_j$ should be \\textbf{integer}). You want to find such an arrangement of people that the value $\\sum\\limits_{j=1}^{m}\\min\\limits_{i=1}^{n}|x_i - y_j|$ is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).\n\nIn other words, let $d_j$ be the distance from the $j$-th human to the nearest Christmas tree ($d_j = \\min\\limits_{i=1}^{n} |y_j - x_i|$). Then you need to choose such positions $y_1, y_2, \\dots, y_m$ that $\\sum\\limits_{j=1}^{m} d_j$ is the minimum possible.",
    "tutorial": "In this problem, we first need to consider all points adjacent to at least one Christmas tree, then all points at the distance two from the nearby Christmas tree and so on... What it looks like? Yes, well-known multi-source bfs. Let's maintain a queue of positions and the set of used positions (and the distance to each vertex, of course). In the first step, we add all positions of the Christmas tree with a zero distance as initial vertices. Let the current vertex is $v$. If $d_v = 0$ (this is the Christmas tree) then just add $v-1$ and $v+1$ to the queue (if these vertices aren't added already) and continue. Otherwise, increase the answer by $d_v$ and add $v$ to the array of positions of people. When the length of this array reaches $m$, interrupt bfs and print the answer. Don't forget about some special cases as using Arrays.sort in Java or using std::unordered_map in C++ because this can lead to the quadratic complexity. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nmt19937 rnd(time(NULL));\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tvector<int> x(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> x[i];\n\t}\n\tqueue<int> q;\n\tmap<int, int> d;\n\tfor (int i = 0; i < n; ++i) {\n\t\td[x[i]] = 0;\n\t\tq.push(x[i]);\n\t}\n\tlong long ans = 0;\n\tvector<int> res;\n\twhile (!q.empty()) {\n\t\tif (int(res.size()) == m) break;\n\t\tint cur = q.front();\n\t\tq.pop();\n\t\tif (d[cur] != 0) {\n\t\t\tans += d[cur];\n\t\t\tres.push_back(cur);\n\t\t}\n\t\tif (!d.count(cur - 1)) {\n\t\t\td[cur - 1] = d[cur] + 1;\n\t\t\tq.push(cur - 1);\n\t\t}\n\t\tif (!d.count(cur + 1)) {\n\t\t\td[cur + 1] = d[cur] + 1;\n\t\t\tq.push(cur + 1);\n\t\t}\n\t}\n\tcout << ans << endl;\n\tshuffle(res.begin(), res.end(), rnd);\n\tfor (auto it : res) cout << it << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1283",
    "index": "E",
    "title": "New Year Parties",
    "statement": "Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...\n\n$n$ friends live in a city which can be represented as a number line. The $i$-th friend lives in a house with an integer coordinate $x_i$. The $i$-th friend can come celebrate the New Year to the house with coordinate $x_i-1$, $x_i+1$ or stay at $x_i$. Each friend is allowed to move no more than once.\n\nFor all friends $1 \\le x_i \\le n$ holds, however, they can come to houses with coordinates $0$ and $n+1$ (if their houses are at $1$ or $n$, respectively).\n\nFor example, let the initial positions be $x = [1, 2, 4, 4]$. The final ones then can be $[1, 3, 3, 4]$, $[0, 2, 3, 3]$, $[2, 2, 5, 5]$, $[2, 1, 3, 5]$ and so on. The number of occupied houses is the number of distinct positions among the final ones.\n\nSo all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?",
    "tutorial": "At first treat the two subtasks as completely independent problems. For both solutions the array of frequences is more convinient to use, so let's build it ($cnt_i$ is the number of friends living in house $i$). 1) Minimum Collect the answer greedily from left to right. If $cnt_i = 0$ then proceed to $i+1$, otherwise add $1$ to the answer and proceed to $i+3$. To prove that let's maximize the number of merges of houses instead of minimizing the actual count of them. It's easy to show that the final number of houses is the initial one minus the number of merges. So if there are people in all $3$ consecutive houses starting from $i$, then $2$ merges is the absolute best you can do with them, skipping any of the merges won't get the better answer. For only $2$ of them occupied $1$ merge is the best and we can achieve that $1$ merge. And a single occupied house obviously will do $0$ merges. 2) Maximum Also greedy but let's process the houses in segments of consecutive positions with positive $cnt$. Take a look at the sum of some segment of houses. If the sum is greater than the length then you can enlarge that segment $1$ house to the left or to the right. If the sum is greater by at least $2$, than you can enlarge it both directions at the same time. Thus the following greedy will work. Let's update the segments from left to right. For each segments check the distance to the previous one (if it was enlarged to the right then consider the new right border). If you can enlarge the current segment and there is space on the left, then enlarge it. And if you still have possibility to enlarge the segment then enlarge it to the right. Notice that it doesn't matter which of any pair of consecutive segments will take the spot between them as the answer changes the same. The initial segments can be obtained with two pointers. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n;\nvector<int> a, cnt;\n\nint solvemin(){\n\tint res = 0;\n\tforn(i, n){\n\t\tif (!cnt[i]) continue;\n\t\t++res;\n\t\ti += 2;\n\t}\n\treturn res;\n}\n\nint solvemax(){\n\tint res = 0;\n\tint dist = 2;\n\tbool right = false;\n\tforn(i, n){\n\t\tif (!cnt[i]){\n\t\t\t++dist;\n\t\t\tcontinue;\n\t\t}\n\t\tint j = i - 1;\n\t\tint sum = 0;\n\t\twhile (j + 1 < n && cnt[j + 1]){\n\t\t\t++j;\n\t\t\tsum += cnt[j];\n\t\t}\n\t\tres += (j - i + 1);\n\t\tif (sum > j - i + 1 && (!right || dist > 1)){\n\t\t\t--sum;\n\t\t\t++res;\n\t\t}\n\t\tright = false;\n\t\tif (sum > j - i + 1){\n\t\t\tright = true;\n\t\t\t++res;\n\t\t}\n\t\ti = j;\n\t\tdist = 0;\n\t}\n\treturn res;\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\ta.resize(n);\n\tcnt.resize(n + 1);\n\tforn(i, n){\n\t\tscanf(\"%d\", &a[i]);\n\t\t++cnt[a[i] - 1];\n\t}\n\tprintf(\"%d %d\\n\", solvemin(), solvemax());\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1283",
    "index": "F",
    "title": "DIY Garland",
    "statement": "Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.\n\nSimple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of $n$ lamps and $n - 1$ wires. Exactly one lamp will be connected to power grid, and power will be transmitted from it to other lamps by the wires. Each wire connectes exactly two lamps; one lamp is called \\textbf{the main lamp} for this wire (the one that gets power from some other wire and transmits it to this wire), the other one is called \\textbf{the auxiliary lamp} (the one that gets power from this wire). Obviously, each lamp has at most one wire that brings power to it (and this lamp is the auxiliary lamp for this wire, and the main lamp for all other wires connected directly to it).\n\nEach lamp has a brightness value associated with it, the $i$-th lamp has brightness $2^i$. We define the \\textbf{importance} of the wire as the sum of brightness values over all lamps that become disconnected from the grid if the wire is cut (and all other wires are still working).\n\nPolycarp has drawn the scheme of the garland he wants to make (the scheme depicts all $n$ lamp and $n - 1$ wires, and the lamp that will be connected directly to the grid is marked; the wires are placed in such a way that the power can be transmitted to each lamp). After that, Polycarp calculated the importance of each wire, enumerated them from $1$ to $n - 1$ in descending order of their importance, and then wrote the index of the main lamp for each wire (in the order from the first wire to the last one).\n\nThe following day Polycarp bought all required components of the garland and decided to solder it — but he could not find the scheme. Fortunately, Polycarp found the list of indices of main lamps for all wires. Can you help him restore the original scheme?",
    "tutorial": "First of all, we don't like the fact that importance values can be integers up to $2^n$ (it is kinda hard to work with them). Let's rephrase the problem. The highest bit set to $1$ in the importance value denotes the maximum in the subtree rooted at the auxiliary lamp for the wire. So, we sort the wires according to the maximums in their subtrees. To break ties, we could consider the second maximum, then the third maximum - but that's not convenient. We can use something much easier: suppose there are two vertices with the same maximum in their subtrees; these vertices belong to the path from the root to the maximum in their subtrees, and the one which is closer to the root has the greater importance value. So, to get the order described in the problem statement, we could sort the vertices according to the maximum in their subtrees, and use depth as the tie-breaker. What does this imply? All vertices of some prefix are ancestors of vertex $n$, so some prefix denotes the path from the root to $n$ (excluding $n$ itself). Then there are some values describing the path from some already visited vertex to $n - 1$ (if $n - 1$ was not met before), then to $n - 2$, and so on. How can we use this information to restore the original tree? $a_1$ is the root, obviously. Then the sequence can be separated into several subsegments, each representing a vertical path in the tree (and each vertex is the parent of the next vertex in the sequence, if they belong to the same subsegment). How can we separate these vertices into subsegments, and how to find the parents for vertices which did not appear in the sequence at all? Suppose some vertex appears several times in our sequence. The first time it appeared in the sequence, it was in the middle of some vertical path, so the previous vertex is its parent; and every time this vertex appears again, it means that we start a new path - and that's how decomposition into paths is done. Determining the parents of vertices that did not appear in the sequence is a bit harder, but can also be done. Let's recall that our sequence is decomposed into paths from root to $n$, from some visited vertex to $n - 1$, from some visited vertex to $n - 2$, and so on; so, each time the path changes, it means that we have found the maximum vertex (among unvisited ones). So we should keep track of the maximum vertex that was not introduced in the sequence while we split it into paths, and each time a path breaks, it means that we found the vertex we were keeping track of. Overall, this solution can be implemented in $O(n)$.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n\n#include<cstdio>\n#include<vector>\n#include<algorithm>\n\nusing namespace std;\n\nint main()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n - 1);\n\tfor (int i = 0; i < n - 1; i++)\n\t{\n\t\tscanf(\"%d\", &a[i]);\n\t\ta[i]--;\n\t}\n\tint root = a[0];\n\tint last = -1;\n\tvector<int> used(n, 0);\n\tprintf(\"%d\\n\", root + 1);\n\tint cur = n - 1;\n\tfor (int i = 0; i < n - 1; i++)\n\t{\n\t\tused[a[i]] = 1;\n\t\twhile (used[cur])\n\t\t\tcur--;\n\t\tif (i == n - 2 || used[a[i + 1]])\n\t\t{\n\t\t\tprintf(\"%d %d\\n\", a[i] + 1, cur + 1);\n\t\t\tused[cur] = 1;\n\t\t}\n\t\telse\n\t\t\tprintf(\"%d %d\\n\", a[i + 1] + 1, a[i] + 1);\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1285",
    "index": "A",
    "title": "Mezo Playing Zoma",
    "statement": "Today, Mezo is playing a game. Zoma, a character in that game, is initially at position $x = 0$. Mezo starts sending $n$ commands to Zoma. There are two possible commands:\n\n- 'L' (Left) sets the position $x: =x - 1$;\n- 'R' (Right) sets the position $x: =x + 1$.\n\nUnfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position $x$ doesn't change and Mezo simply proceeds to the next command.\n\nFor example, if Mezo sends commands \"LRLR\", then here are some possible outcomes (underlined commands are sent successfully):\n\n- \"{\\underline{LRLR}}\" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position $0$;\n- \"LRLR\" — Zoma recieves no commands, doesn't move at all and ends up at position $0$ as well;\n- \"{\\underline{L}R\\underline{L}R}\" — Zoma moves to the left, then to the left again and ends up in position $-2$.\n\nMezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.",
    "tutorial": "Let $c_L$ and $c_R$ be the number of 'L's and 'R's in the string respectively. Note that Zoma may end up at any integer point in the interval $[-c_L, c_R]$. So, the answer equals $c_R - (-c_L) + 1 = n + 1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define finish(x) return cout << x << endl, 0\n#define ll long long\n\nint n;\nstring s;\n\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cin >> n >> s;\n    cout << n + 1 << endl;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1285",
    "index": "B",
    "title": "Just Eat It!",
    "statement": "Today, Yasser and Adel are at the shop buying cupcakes. There are $n$ cupcake types, arranged from $1$ to $n$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $i$ is an integer $a_i$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.\n\nYasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.\n\nOn the other hand, Adel will choose some segment $[l, r]$ $(1 \\le l \\le r \\le n)$ that does not include all of cupcakes (he can't choose $[l, r] = [1, n]$) and buy exactly one cupcake of each of types $l, l + 1, \\dots, r$.\n\nAfter that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is \\textbf{strictly} greater than the total tastiness of cupcakes Adel buys \\textbf{regardless of Adel's choice}.\n\nFor example, let the tastinesses of the cupcakes be $[7, 4, -1]$. Yasser will buy all of them, the total tastiness will be $7 + 4 - 1 = 10$. Adel can choose segments $[7], [4], [-1], [7, 4]$ or $[4, -1]$, their total tastinesses are $7, 4, -1, 11$ and $3$, respectively. Adel can choose segment with tastiness $11$, and as $10$ is not strictly greater than $11$, Yasser won't be happy :(\n\nFind out if Yasser will be happy after visiting the shop.",
    "tutorial": "If there is at least a prefix or a suffix with non-positive sum, we can delete that prefix/suffix and end up with an array with sum $\\geq$ the sum of the whole array. So, if that's the case, the answer is \"NO\". Otherwise, all the segments that Adel can choose will have sum $<$ than the sum of the whole array because the elements that are not in the segment will always have a strictly positive sum. So, in that case, the answer is \"YES\". Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define finish(x) return cout << x << endl, 0\n#define ll long long\n\nint n;\nvector <int> a;\n\nbool solve(){\n    cin >> n;\n    a.resize(n);\n    for(auto &i : a) cin >> i;\n    ll sum = 0;\n    for(int i = 0 ; i < n ; i++){\n        sum += a[i];\n        if(sum <= 0) return 0;\n    }\n    sum = 0;\n    for(int i = n - 1 ; i >= 0 ; i--){\n        sum += a[i];\n        if(sum <= 0) return 0;\n    }\n    return 1;\n}\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int T;\n    cin >> T;\n    while(T--){\n        if(solve()) cout << \"YES\\n\";\n        else cout << \"NO\\n\";\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1285",
    "index": "C",
    "title": "Fadi and LCM",
    "statement": "Today, Osama gave Fadi an integer $X$, and Fadi was wondering about the minimum possible value of $max(a, b)$ such that $LCM(a, b)$ equals $X$. Both $a$ and $b$ should be positive integers.\n\n$LCM(a, b)$ is the smallest positive integer that is divisible by both $a$ and $b$. For example, $LCM(6, 8) = 24$, $LCM(4, 12) = 12$, $LCM(2, 3) = 6$.\n\nOf course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?",
    "tutorial": "There will always be a solution where $a$ and $b$ are coprime. To see why, let's prime factorize $a$ and $b$. If they share a prime factor we can omit all its occurrences from one of them, precisely from the one that has fewer occurrences of that prime, without affecting their $LCM$. Now, let's prime factorize $X$. Since there will be at most $11$ distinct primes, we can distribute them between $a$ and $b$ with a bruteforce. For an easier implementation, you can loop over all divisors $d$ of $X$, check if $LCM(d, \\frac{X}{d})$ equals $X$, and minimize the answer with the pair $(d, \\frac{X}{d})$. Time complexity: $O(\\sqrt{n})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define finish(x) return cout << x << endl, 0\n#define ll long long\n\nll x;\n\nll lcm(ll a, ll b){\n    return a / __gcd(a, b) * b;\n}\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cin >> x;\n    ll ans;\n    for(ll i = 1 ; i * i <= x ; i++){\n        if(x % i == 0 && lcm(i, x / i) == x){\n            ans = i;\n        }\n    }\n    cout << ans << \" \" << x / ans << endl;\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1285",
    "index": "D",
    "title": "Dr. Evil Underscores",
    "statement": "Today, as a friendship gift, Bakry gave Badawy $n$ integers $a_1, a_2, \\dots, a_n$ and challenged him to choose an integer $X$ such that the value $\\underset{1 \\leq i \\leq n}{\\max} (a_i \\oplus X)$ is minimum possible, where $\\oplus$ denotes the bitwise XOR operation.\n\nAs always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $\\underset{1 \\leq i \\leq n}{\\max} (a_i \\oplus X)$.",
    "tutorial": "We will solve this problem recursively starting from the most significant bit. Let's split the elements into two groups, one with the elements which have the current bit on and one with the elements which have the current bit off. If either group is empty, we can assign the current bit of $X$ accordingly so that we have the current bit off in our answer, so we will just proceed to the next bit. Otherwise, both groups aren't empty, so whatever value we assign to the current bit of $X$, we will have this bit on in our answer. Now, to decide which value to assign to the current bit of $X$, we will solve the same problem recursively for each of the groups for the next bit; let $ans_{on}$ and $ans_{off}$ be the answers of the recursive calls for the on and the off groups respectively. Note that if we assign $1$ to the current bit of $X$, the answer will be $2^{i}+ans_{off}$, and if we assign $0$ to the current bit of $X$, the answer will be $2^{i}+ans_{on}$, where $i$ is the current bit. So, simply we will choose the minimum of these two cases for our answer to be $2^{i}+min(ans_{on}, ans_{off})$. Time complexity: $O(nlog(maxa_i))$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define finish(x) return cout << x << endl, 0\n#define ll long long\n\nint n;\nvector <int> a;\n\nint solve(vector <int> &c, int bit){\n    if(bit < 0) return 0;\n    vector <int> l, r;\n    for(auto &i : c){\n        if(((i >> bit) & 1) == 0) l.push_back(i);\n        else r.push_back(i);\n    }\n    if(l.size() == 0) return solve(r, bit - 1);\n    if(r.size() == 0) return solve(l, bit - 1);\n    return min(solve(l, bit - 1), solve(r, bit - 1)) + (1 << bit);\n}\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cin >> n;\n    a.resize(n);\n    for(auto &i : a) cin >> i;\n    cout << solve(a, 30) << endl;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "divide and conquer",
      "dp",
      "greedy",
      "strings",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1285",
    "index": "E",
    "title": "Delete a Segment",
    "statement": "There are $n$ segments on a $Ox$ axis $[l_1, r_1]$, $[l_2, r_2]$, ..., $[l_n, r_n]$. Segment $[l, r]$ covers all points from $l$ to $r$ inclusive, so all $x$ such that $l \\le x \\le r$.\n\nSegments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is $l_i=r_i$ is possible.\n\nUnion of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:\n\n- if $n=3$ and there are segments $[3, 6]$, $[100, 100]$, $[5, 8]$ then their union is $2$ segments: $[3, 8]$ and $[100, 100]$;\n- if $n=5$ and there are segments $[1, 2]$, $[2, 3]$, $[4, 5]$, $[4, 6]$, $[6, 6]$ then their union is $2$ segments: $[1, 3]$ and $[4, 6]$.\n\nObviously, a union is a set of pairwise non-intersecting segments.\n\nYou are asked to erase exactly one segment of the given $n$ so that the number of segments in the union of the rest $n-1$ segments is maximum possible.\n\nFor example, if $n=4$ and there are segments $[1, 4]$, $[2, 3]$, $[3, 6]$, $[5, 7]$, then:\n\n- erasing the first segment will lead to $[2, 3]$, $[3, 6]$, $[5, 7]$ remaining, which have $1$ segment in their union;\n- erasing the second segment will lead to $[1, 4]$, $[3, 6]$, $[5, 7]$ remaining, which have $1$ segment in their union;\n- erasing the third segment will lead to $[1, 4]$, $[2, 3]$, $[5, 7]$ remaining, which have $2$ segments in their union;\n- erasing the fourth segment will lead to $[1, 4]$, $[2, 3]$, $[3, 6]$ remaining, which have $1$ segment in their union.\n\nThus, you are required to erase the third segment to get answer $2$.\n\nWrite a program that will find the maximum number of segments in the union of $n-1$ segments if you erase any of the given $n$ segments.\n\nNote that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly $n-1$ segments.",
    "tutorial": "Ok, looking for a new number of segments in a union is actually hard. Let $nw_i$ be the union of segments after erasing the $i$-th one. Obviously, each of the segments in $nw[i]$ has its left and right borders. Let me show you how to calculate the number of any of these two kinds. Let's choose left borders. I will call the set of left borders of the set $s$ of segments $lf_s$. Build the initial union of all segments (that is a standart algorithm, google it if you want). Call it $init$. We are asked to find $\\max \\limits_{i} |nw[i]|$, but let's instead find $\\max \\limits_{i} |nw[i]| - |init|$ (that is the difference of sizes of the initial union and the new one for $i$). Surely, adding $|init|$ to this value will be the answer. Moreover, $\\max \\limits_{i} |nw[i]| - |init| = \\max \\limits_{i} |lf_{nw[i]}| - |lf_{init}|$ and that's what we are going to calculate. Call that difference $diff_i$. Let's do the following sweep line. Add queries of form $(l_i, i, 1)$ and $(r_i, i, -1)$. Process them in sorted order. Maintain the set of the open segments. This sweepline will add segment $i$ on a query of the first type and remove segment $i$ on a query of the second type. Initialize all the $diff_i$ with zeroes, this sweepline will help us to calculate all the values altogether. Look at the all updates on the same coordinate $x$. The only case we care about is: the current set of open segments contain exactly one segment and there is at least one adding update. Let this currently open segment be $j$. Consider what happens with $nw[j]$. $x$ is not in the $lf_{init}$ because at least that segment $j$ covers it. $x$ is also in $lf_{nf[j]}$ because after erasing segment $j$ $x$ becomes a left border of some segment of the union (you are adding a segment with the left border $x$ and points slightly to the left of $x$ are no longer covered by segment $j$). Thus, $diff_j$ increases by $1$. The other possible cases are: there are no open segments currently - this is not important because $x$ was a left border and stays as a left border; there are more than two open segments - not important because $x$ will still be covered by at least one of them after erasing some other; there are no adding updates - $x$ was a left border but doesn't become a new one. Thus, we handled all the left border count increasing cases. But there are also a decreasing case. Left border can get removed if the segment you are erasing had its left border in the initial union and was the only segment with such left border. You can get $lf_{init}$ while getting $init$. Then for each of $lf_{init}$ you can count how many segments start in it. Finally, iterate over $i$ and decrease $diff_i$ by one if the value for the left border of the segment $i$ is exactly $1$. Finally, $diff_i$ is obtained, $(\\max \\limits_i diff_i) + |init|$ is the answer. Overall complexity: $O(n \\log n)$. Author: MikeMirzayanov",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define x first\n#define y second\n\nusing namespace std;\n\nconst int INF = 2e9;\n\ntypedef pair<int, int> pt;\nmap<int, int> ls;\n\nint get(vector<pt> a){\n\tint cnt = 0;\n\tint l = -INF, r = -INF;\n\tsort(a.begin(), a.end());\n\tforn(i, a.size()){\n\t\tif (a[i].x > r){\n\t\t\tif (r != -INF)\n\t\t\t\tls[l] = 0;\n\t\t\t++cnt;\n\t\t\tl = a[i].x, r = a[i].y;\n\t\t}\n\t\telse{\n\t\t\tr = max(r, a[i].y);\n\t\t}\n\t}\n\tls[l] = 0;\n\treturn cnt;\n}\n\nvoid process(vector<pair<int, pt>> &qr, vector<int> &ans){\n\tset<int> open;\n\tforn(i, qr.size()){\n\t\tvector<int> op, cl;\n\t\tint j = i - 1;\n\t\twhile (j + 1 < int(qr.size()) && qr[j + 1].x == qr[i].x){\n\t\t\t++j;\n\t\t\tif (qr[j].y.x == 1)\n\t\t\t\top.push_back(qr[j].y.y);\n\t\t\telse\n\t\t\t\tcl.push_back(qr[j].y.y);\n\t\t}\n\t\tif (open.size() == 1 && !op.empty()){\n\t\t\t++ans[*open.begin()];\n\t\t}\n\t\tfor (auto it : op){\n\t\t\topen.insert(it);\n\t\t}\n\t\tfor (auto it : cl){\n\t\t\topen.erase(it);\n\t\t}\n\t\ti = j;\n\t}\n}\n\nvoid solve(){\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<pt> a(n);\n\tforn(i, n) scanf(\"%d%d\", &a[i].x, &a[i].y);\n\t\n\tvector<pair<int, pt>> qr;\n\tforn(i, n){\n\t\tqr.push_back({a[i].x, {1, i}});\n\t\tqr.push_back({a[i].y, {-1, i}});\n\t}\n\tsort(qr.begin(), qr.end());\n\t\n\tvector<int> ans(n, 0);\n\tls.clear();\n\tint cur = get(a);\n\t\n\tprocess(qr, ans);\n\tforn(i, n) if (ls.count(a[i].x)) ++ls[a[i].x];\n\tforn(i, n) if (ls[a[i].x] == 1) --ans[i];\n\t\n\tprintf(\"%d\\n\", *max_element(ans.begin(), ans.end()) + cur);\n}\n\nint main(){\n\tint tc;\n\tscanf(\"%d\", &tc);\n\tforn(i, tc)\n\t\tsolve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "dp",
      "graphs",
      "sortings",
      "trees",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1285",
    "index": "F",
    "title": "Classical?",
    "statement": "Given an array $a$, consisting of $n$ integers, find:\n\n$$\\max\\limits_{1 \\le i < j \\le n} LCM(a_i,a_j),$$\n\nwhere $LCM(x, y)$ is the smallest positive integer that is divisible by both $x$ and $y$. For example, $LCM(6, 8) = 24$, $LCM(4, 12) = 12$, $LCM(2, 3) = 6$.",
    "tutorial": "Since $LCM(x,y)=\\frac{x*y}{GCD(x,y)}$, it makes sense to try and fix $GCD(x,y)$. Let's call it $g$. Now, let's only care about the multiples of $g$ in the input. Assume we divide them all by $g$. We now want the maximum product of 2 coprime numbers in this new array. Let's sort the numbers and iterate from the biggest to the smallest, keeping a stack. Assume the current number you're iterating on is $x$. While there is a number in the stack coprime to $x$, you can actually pop the top of the stack; you'll never need it again. That's because this number together with a number smaller than $x$ can never give a better product than that of a greater, or equal, number together with $x$! Now, we just need to figure out whether there's a number coprime to $x$ in the stack. This could be easily done with inclusion-exclusion. Assume the number of multiples of $d$ in the stack is $cnt_d$; the number of elements in the stack coprime to $x$ is: $\\sum_{d|x} \\mu(d)*cnt_d$ The complexity is $O(\\sum\\limits_{i=1}^{n} \\sigma_{0}(i)^2)$ where $\\sigma_{0}$ is the divisor count function. That's because each number enters the routine of calculating the maximum product of a coprime pair $\\sigma_{0}$ times, and we iterate through its divisors in this routine.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define MX 100000\nint arr[100005],u[MX+5],cnt[MX+5];\nvector<int> d[MX+5];\nbool b[MX+5];\nint coprime(int x)\n{\n\tint ret=0;\n\tfor (int i:d[x])\n\tret+=cnt[i]*u[i];\n\treturn ret;\n}\nvoid update(int x,int a)\n{\n\tfor (int i:d[x])\n\tcnt[i]+=a;\n}\nint main()\n{\n\tfor (int i=1;i<=MX;i++)\n\t{\n\t\tfor (int j=i;j<=MX;j+=i)\n\t\td[j].push_back(i);\n\t\tif (i==1)\n\t\tu[i]=1;\n\t\telse if ((i/d[i][1])%d[i][1]==0)\n\t\tu[i]=0;\n\t\telse\n\t\tu[i]=-u[i/d[i][1]];\n\t}\n\tint n;\n\tscanf(\"%d\",&n);\n\tlong long ans=0;\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tint a;\n\t\tscanf(\"%d\",&a);\n\t\tans=max(ans,(long long)a);\n\t\tb[a]=1;\n\t}\n\tfor (int g=1;g<=MX;g++)\n\t{\n\t\tstack<int> s;\n\t\tfor (int i=MX/g;i>0;i--)\n\t\t{\n\t\t\tif (!b[i*g])\n\t\t\tcontinue;\n\t\t\tint c=coprime(i);\n\t\t\twhile (c)\n\t\t\t{\n\t\t\t\tif (__gcd(i,s.top())==1)\n\t\t\t\t{\n\t\t\t\t\tans=max(ans,1LL*i*s.top()*g);\n\t\t\t\t\tc--;\n\t\t\t\t}\n\t\t\t\tupdate(s.top(),-1);\n\t\t\t\ts.pop();\n\t\t\t}\n\t\t\tupdate(i,1);\n\t\t\ts.push(i);\n\t\t}\n\t\twhile (!s.empty())\n\t\t{\n\t\t\tupdate(s.top(),-1);\n\t\t\ts.pop();\n\t\t}\n\t}\n\tprintf(\"%I64d\",ans);\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1286",
    "index": "A",
    "title": "Garland",
    "statement": "Vadim loves decorating the Christmas tree, so he got a beautiful garland as a present. It consists of $n$ light bulbs in a single row. Each bulb has a number from $1$ to $n$ (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.\n\nVadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by $2$). For example, the complexity of 1 4 2 3 5 is $2$ and the complexity of 1 3 5 7 6 4 2 is $1$.\n\nNo one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.",
    "tutorial": "The problem can be solved using a greedy algorithm. Notice that the only information we need is parity of numbers on bulbs. So let's replace numbers by their remainders modulo $2$. Than complexity of garland will be the number of pairs of adjacent numbers that are different. Let's call such pairs as bad. Divide garland into segments of removed bulbs. Let's call number before segment as left border and number after segment as right border. If there's no number before/after the segment than the segment doesn't have left/right border. Notice that when filling a segment, one should place the same numbers in a row (if any). If the segment has different borders then the optimal way is to place all zeroes near zero-border and all ones near one-border. If the segment has the same borders and we place both numbers in the segment that there will be at least two bad pairs and we will achieve it by placing all zeroes and then all ones. Similarly one could prove cases with the absence of one or two borders. If the segment has both borders and they are different then this segment always will increase the complexity by $1$. If the segment has both borders and they are different then this segment will increase the complexity by $0$ or $2$. $0$ will be in case we fill segment by numbers of the same parity as its borders. Otherwise, it will be $2$. If the segment doesn't have at least one of borders, it will increase the complexity by $0$ if all numbers have the same parity as its border (if any) and $1$ otherwise. So in order to minimize the complexity of garland, first of all, we should fill segments with the same borders by the numbers of the same parity. Obviously we should consider such segments in increasing length order. Then we should fill segments with only one border such that complexity won't increase. After that, we can place the remaining numbers arbitrary (but inside one segment we should place the same numbers in a row). Because for all remaining segments number of bad pairs is fixed. Time complexity is $O(n \\log n)$. Also, this problem could be solved using dynamic programming.",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1286",
    "index": "B",
    "title": "Numbers on Tree",
    "statement": "Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $1$ to $n$. Each of its vertices also has an integer $a_i$ written on it. For each vertex $i$, Evlampiy calculated $c_i$ — the number of vertices $j$ in the subtree of vertex $i$, such that $a_j < a_i$.\n\n\\begin{center}\nIllustration for the second example, the first integer is $a_i$ and the integer in parentheses is $c_i$\n\\end{center}\n\nAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of $c_i$, but he completely forgot which integers $a_i$ were written on the vertices.\n\nHelp him to restore initial integers!",
    "tutorial": "There are several approaches to this problem. We will tell one of them. Note that if $c_i$ for some vertex is greater than the number of vertices in its subtree, then there is no answer. Now we prove that we can always build the answer, so that all $a_i$ will be numbers from $1$ to $n$. On those numbers, let's build some structure that supports deleting elements and searching for k-th element. Let's denote by $d_v$ the number of vertices in the subtree of vertex $v$. Now iterate over the subtree of $v$ in the order of the depth first search. Then let's set $a_v$ = $c_v$-th element in our structure (and after that delete this element). Firstly, such an element will always exist. This is true because when we examine the vertex $v$, all vertices in the subtree of this vertex are not yet considered $\\ Rightarrow$ since $c_v \\ leq d_v$ $\\ Rightarrow$ in our structure there are at least $c_v$ elements. Secondly, the set of all values in the subtree will be a prefix of our structure. If this is true, then the condition that the subtree contains exactly $c_v$ elements smaller than ours is guaranteed to be satisfied (because all elements from our structure that are smaller than ours are there, and we specifically took the $c_v$-th element). Let us prove this fact by induction on the size of the tree. For a tree of size $1$ this is obvious (we always take the first element). Now for size $k$, we have the root on which the number $c_x \\ leq k-1$ is written. Then when we throw out $c_x$, and then throw out all the vertices in the subtree, we will remove the prefix of at least $k-1$ vertices, which means that we will drop all the vertices up to $c_x$, as well as some prefix of vertices after it, thus in total we'll throw out some prefix of vertices. Now, we have reduced the problem to dfs and searching for k-order statistics. This can be done in a variety of ways - segment tree, Fenwick tree, sqrt decomposition, Cartesian tree, or a built-in c++ tree. Code of the author solution with this tree.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1286",
    "index": "C2",
    "title": "Madhouse (Hard version)",
    "statement": "\\textbf{This problem is different with easy version only by constraints on total answers length}\n\n\\textbf{It is an interactive problem}\n\nVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string $s$ of length $n$, consisting only of lowercase English letters. The player can ask two types of queries:\n\n- ? l r – ask to list all substrings of $s[l..r]$. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.\n- ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses.\n\nThe player can ask \\textbf{no more than $3$ queries} of the first type.\n\nTo make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed $\\left\\lceil 0.777(n+1)^2 \\right\\rceil$ ($\\lceil x \\rceil$ is $x$ rounded up).\n\nVenya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.\n\nYour program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.\n\nNote that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.",
    "tutorial": "Let's consider the solution that uses $2$ queries with the lengths $n$ and $n-1$ (it asks about too many substrings, so it will not pass all the tests, but it will help us further). Let's ask about substrings $[1..n]$ and $[1..n-1]$. For convenience, rearrange the letters in all strings in alphabetical order. Then note that all the suffixes of $S$ correspond to those strings that we get in the first case, and do not get in the second. Having found all such strings, we can easily find all suffixes of $S$ by looking at them from smaller ones to bigger. For a complete solution we should first find the first $n / 2$ characters of the string by the solution described above. Then ask about the whole string. Let $cnt_{i, x}$ be the number of times that the symbol $x$ occurs in total in all substrings of length $i$ in the last query. Note that the symbol at position $j$ is counted in $cnt_{i, x}$ exactly $min(i, j, n - j + 1)$ times. Then for all $i$ from $1$ to $n / 2$, the value $cnt_{i + 1, x}$ - $cnt_{i,x}$ is equal to the number of times that $x$ occurs on positions with indices from $i + 1$ to $n - i$. Knowing these quantities, it is possible to find out how many times the element x occurs on positions $i$ and $n - i + 1$ in sum for each $i$ from $1$ to $n / 2$. Since we already know the first half of the string, it is not difficult to restore the character at the position $n - i + 1$, and therefore the entire string. In total, we asked about the substrings $[1 .. n / 2]$, $[1..n / 2 - 1]$ and $[1..n]$, the total number of substrings received is $\\approx \\frac{(\\frac{n + 1}{2})^2}{2}+ \\frac{(\\frac{n + 1}{2})^2}{2} + \\frac{(n + 1)^2}{2} = 0.75 (n + 1)^2$, and that quite satisfies the limitations of the problem.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "hashing",
      "interactive",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1286",
    "index": "D",
    "title": "LCC",
    "statement": "An infinitely long Line Chillland Collider (LCC) was built in Chillland. There are $n$ pipes with coordinates $x_i$ that are connected to LCC. When the experiment starts at time 0, $i$-th proton flies from the $i$-th pipe with speed $v_i$. It flies to the right with probability $p_i$ and flies to the left with probability $(1 - p_i)$. The duration of the experiment is determined as the time of the first collision of any two protons. In case there is no collision, the duration of the experiment is considered to be zero.\n\nFind the expected value of the duration of the experiment.\n\n\\begin{center}\nIllustration for the first example\n\\end{center}",
    "tutorial": "Note, that the first collision will occur between two neighboring particles in the original array. These two particles have 3 options to collide: both particles move to the right, both move to the left, they move towards each other. Let's go through these options and calculate the time of the collision. Let's do this for each pair of neighboring vertices and sort them by the collision time. Then the probability that $i$th will occur first is equal to the probability that the first $(i-1)$ collisions will not occur minus the probability that the first i will not occur. To find these probabilities we can use the Segment Tree. In each of its vertices, we will maintain an answer for four masks on which way the first and the last particle of the segment are moving. The answer for the mask is the probability that none of the first $X$ collisions will not occur, and the extreme ones move in accordance with the mask. Then to add a ban for the $(i + 1)$th collision, it is enough to make an update at the point. The final asymptotic is $O(n \\cdot 2^4 \\cdot \\log(n))$",
    "tags": [
      "data structures",
      "math",
      "matrices",
      "probabilities"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1286",
    "index": "E",
    "title": "Fedya the Potter Strikes Back",
    "statement": "Fedya has a string $S$, initially empty, and an array $W$, also initially empty.\n\nThere are $n$ queries to process, one at a time. Query $i$ consists of a lowercase English letter $c_i$ and a nonnegative integer $w_i$. First, $c_i$ must be appended to $S$, and $w_i$ must be appended to $W$. The answer to the query is the sum of suspiciousnesses for all subsegments of $W$ $[L, \\ R]$, $(1 \\leq L \\leq R \\leq i)$.\n\nWe define the suspiciousness of a subsegment as follows: if the substring of $S$ corresponding to this subsegment (that is, a string of consecutive characters from $L$-th to $R$-th, inclusive) matches the prefix of $S$ of the same length (that is, a substring corresponding to the subsegment $[1, \\ R - L + 1]$), then its suspiciousness is equal to the minimum in the array $W$ on the $[L, \\ R]$ subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is $0$.\n\nHelp Fedya answer all the queries before the orderlies come for him!",
    "tutorial": "Let $ans_{i}$ be the answer for the moment after $i$ queries. Then, $s_{i} = ans_{i} - ans_{i-1}$ is equal to the sum of suspiciousness of suffixes of the string after $i$ queries. If we calculate $s_{i}$, $ans$ will be the prefix sums of this array. Let's maintain the KMP tree of the string. Each vertex of the tree corresponds to a prefix of the string. Let $S$ be the subset of suffixes, which are equal to the corresponding prefixes. We can note that $S$ is exactly the path from the root to the current vertex in the tree. Let $s_{v}$ be the next character of vertex of KMP, which corresponds to the prefix with length $v$ (the string is indexed from $0$). Let's find out what happens after adding a new character to the end of the string. Some suffixes from $S$ can't be extended with this character (keeping the condition about equality to the prefix), so they will be removed from the set. Also, if the new character is equal to $s_{0}$, a suffix with length $1$ will be added to the set. These are the only modifications that will be applied to $S$. We want to find all elements of $S$, which will be removed after a certain query. Let's denote the number of these elements by $r$. If we find them in $O(r)$, the amortized time will be $O(n)$. A suffix can't be extended if and only if the next character of its vertex is not equal to the new character. We need to find all these vertexes on the way up from the last vertex. Let $link_{v}$ be the closest ancestor of $v$ with the different next character (we can calculate it for each vertex when it is added). Let's ascend from vertex $v$. If we are in a vertex with the same next character as in the vertex $v$, then we will go to the $link_{v}$, otherwise, we will handle this vertex as a removing suffix and go to the parent vertex. It's clear that it works in $O(r)$. Now our task is just adding a suffix with length $1$, removing suffixes and adding an element to all suffixes. We can create a segment tree for minimum on $w$ in order to get the minimum on the removing segment. Let's maintain a mulitset of minimums on current suffixes. So, our queries are: Add element $x$ Remove element $x$ For each element $a$ make $a = min(a, x)$ Get the sum of the elements Let's store a map from an element to the number of its occurrences. Queries 1 and 2 can be done obviously. To perform the 3-rd query, we can just iterate through elements, which are bigger than $x$, remove them from the map, and add as many elements with value $x$. The amortized complexity of this solution is $O(n \\log n)$. BONUS: solve it when a suspiciousness of a \"suspicious\" segment is the $mex$ of elements instead of $min$. Code (with BigInt realization)",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1286",
    "index": "F",
    "title": "Harry The Potter",
    "statement": "To defeat Lord Voldemort, Harry needs to destroy all horcruxes first. The last horcrux is an array $a$ of $n$ integers, which also needs to be destroyed. The array is considered destroyed if all its elements are zeroes. To destroy the array, Harry can perform two types of operations:\n\n- choose an index $i$ ($1 \\le i \\le n$), an integer $x$, and subtract $x$ from $a_i$.\n- choose two indices $i$ and $j$ ($1 \\le i, j \\le n; i \\ne j$), an integer $x$, and subtract $x$ from $a_i$ and $x + 1$ from $a_j$.\n\nNote that $x$ does not have to be positive.\n\nHarry is in a hurry, please help him to find the minimum number of operations required to destroy the array and exterminate Lord Voldemort.",
    "tutorial": "Assume that we have done $m$ queries of the second type. On the $i$th query we subtracted $x_i$ from $a_{p_i}$ and $x_i + 1$ from $a_{q_i}$. Let's construct undirected graph on $n$ vertices with edges $(p_i, q_i)$. Assume we have a cycle $c_1, c_2, ..., c_k$ in this graph, then, we can replace queries along this cycle with single queries of the first type to each vertex. Therefore, in an optimal answer queries of the second type form a forest. Let's call subset good if it size is $k$ and it can be destroyed with $k - 1$ operations of the second type. So, the problem is equivalent to grouping some of the elements of $a_i$ into maximal number of disjoint good subsets. Elements that do not belong to any set can be destroyed with operations of the first type. Let's find out whether a subset $S$ is good or not. Let's forget about + 1 in a query(e.g. we subtract $x$ and $x$). Consider a sequence of $m$ queries $p_i$, $q_i$, $x_i$ that destroys $S$ and $(p_i, q_i)$ form a connected tree. Let's select an arbitrary vertex of this tree as a root. Then, it is easy to see that for each vertex only its height modulo 2 is matter. Therefore, we can consider only trees of the following structure: The elements with the even height contribute positive change to the root, the elements with the odd height contribute negative change to the root. So, our problem is equivalent to finding the set $T \\subset S$ such that $sum(S \\setminus T) - sum(T) = 0$ and $T \\neq \\emptyset, T \\neq S$. Now we subtract $x$ and $x + 1$. It turns out that it changes the above condition to $sum(S \\setminus T) - sum(T) \\in \\{-|S|, -|S| + 2, ..., |S| - 2, |S|\\}$ and $T \\neq \\emptyset, T \\neq S$. Such set $T$ can be found with MITM in $O((1 + \\sqrt{2}) ^ n)$ time (knapsack in $2^{n/2}$ over all subsets). So, now we know all good subsets. Let $A_{mask} = 1$ if $mask$ is a good subset and $0$ otherwise. Let's denote $A * B$ operation as OR convolution on independent subsets. Suppose $p$ is a minimum integer such that $\\underbrace{A * A * ... * A}_\\textit{p times} = 0$(e.g. all values of the product array are zero). It is clear that $n - p$ is a minimal number of operations required to destroy the array. OR convolution on independent subsets can be done in $O(n^2 \\cdot 2^n)$ time and the minimal power can be estimated in $O(\\log{n})$ time. Also, this part can be done with dynamic programming on subsets in $O(3^n)$ time which some participants managed to squeeze. So, the total time complexity is $O((1 + \\sqrt{2})^n + \\log{n} \\cdot n^2 \\cdot 2^n)$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "fft",
      "implementation",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1287",
    "index": "A",
    "title": "Angry Students",
    "statement": "It's a walking tour day in SIS.Winter, so $t$ groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.\n\nInitially, some students are angry. Let's describe a group of students by a string of capital letters \"A\" and \"P\":\n\n- \"A\" corresponds to an angry student\n- \"P\" corresponds to a patient student\n\nSuch string describes the row from the last to the first student.\n\nEvery minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index $i$ in the string describing a group then they will throw a snowball at the student that corresponds to the character with index $i+1$ (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.\n\nLet's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.\n\nYour task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.",
    "tutorial": "We will take a look at two different solutions. First has complexity $O(\\sum\\limits_{i = 0}^{t - 1} {k_i} ^ {2})$. In this solution, we will simulate the events described in the statement. We will simulate every minute. Note that every minute (until we have found the answer) number of angry students will increase by at least $1$, but it is bounded by $k$, so we don't need to simulate more than $k + 1$ minutes. Assume that $a_i$ describe students' states after $i$ minutes. Then $a_0[j] = 1$ if initially $j$-th student is angry. And $a_i[j] = \\max(a_{i - 1}[j], a_{i - 1}[j - 1])$. Second solution has complexity $O(\\sum\\limits_{i = 0}^{t - 1} {k_i})$. Note that every angry student will make angry every student between him and the next (closest to the right) angry student. Students will become angry one by one. So for every angry student, we should update the answer by number of patient students till the nearest angry student to the right (or till the end of row.).",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1287",
    "index": "B",
    "title": "Hyperset",
    "statement": "Bees Alice and Alesya gave beekeeper Polina famous card game \"Set\" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.\n\nPolina came up with a new game called \"Hyperset\". In her game, there are $n$ cards with $k$ features, each feature has three possible values: \"S\", \"E\", or \"T\". The original \"Set\" game can be viewed as \"Hyperset\" with $k = 4$.\n\nSimilarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.\n\nUnfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.",
    "tutorial": "Firstly, we can notice that two cards uniquely identify the third, which forms a set with them. If the $i$-th feature of two cards is the same, then in the third card also has the same, otherwise, it has a different feature. Thus, we can check all pairs of cards, find their third one, which forms a set with them, and find out if it exists. Time complexity: $O$($kn^{2}$ $log n$).",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1288",
    "index": "A",
    "title": "Deadline",
    "statement": "Adilbek was assigned to a special project. For Adilbek it means that he has $n$ days to run a special program and provide its results. But there is a problem: the program needs to run for $d$ days to calculate the results.\n\nFortunately, Adilbek can optimize the program. If he spends $x$ ($x$ is a non-negative integer) days optimizing the program, he will make the program run in $\\left\\lceil \\frac{d}{x + 1} \\right\\rceil$ days ($\\left\\lceil a \\right\\rceil$ is the ceiling function: $\\left\\lceil 2.4 \\right\\rceil = 3$, $\\left\\lceil 2 \\right\\rceil = 2$). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to $x + \\left\\lceil \\frac{d}{x + 1} \\right\\rceil$.\n\nWill Adilbek be able to provide the generated results in no more than $n$ days?",
    "tutorial": "At first, let's note that if $x$ is integer and $x$ and $y$ are non-negative then $x + \\left\\lceil y \\right\\rceil = \\left\\lceil x + y \\right\\rceil$. So, instead of looking at $x + \\left\\lceil \\frac{d}{x + 1} \\right\\rceil$ we can consider $\\left\\lceil x + \\frac{d}{x + 1} \\right\\rceil$. It's easier since the function $x + \\frac{d}{x + 1} = (x + 1) + \\frac{d}{(x + 1)} - 1$ is more common function and it can be proven that it's concave upward. It means that this function has a unique minimum and, moreover, we can calculate it: $f(x) = x + \\frac{d}{x + 1}$ has minimum value in $x_0 = \\sqrt{d} - 1$ and $f(x_0) = 2 \\sqrt{d} - 1$. Since the ceiling function is monotonically increasing so we can assume that $\\left\\lceil f(x) \\right\\rceil \\le \\left\\lceil f(x + 1) \\right\\rceil$ for all $x \\ge \\sqrt{d}$. So we can just iterate $x$ from $0$ to $\\left\\lfloor \\sqrt{d} \\right\\rfloor$ and check the unequation $\\left\\lceil f(x) \\right\\rceil \\le n$. The total complexity is equal to $O(T \\sqrt{d})$. There is a simple optimization: because of the monotone ceiling we can prove that we need to check only $\\left\\lfloor \\sqrt{d} - 1 \\right\\rfloor$ and $\\left\\lceil \\sqrt{d} - 1 \\right\\rceil$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tint tt = clock();\n#endif\n\t\n\tint T; cin >> T;\n\twhile(T--) {\n\t\tint n, d;\n\t\tcin >> n >> d;\n\t\t\n\t\tint x, MAG = (int)sqrt(d) + 10;\n\t\tfor(x = 0; x < MAG; x++) {\n\t\t\tif(x + (d + x) / (x + 1) <= n)\n\t\t\t\tbreak;\n\t\t}\n\t\tcout << (x < MAG ? \"YES\" : \"NO\") << endl;\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "math",
      "ternary search"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1288",
    "index": "B",
    "title": "Yet Another Meme Problem",
    "statement": "You are given two integers $A$ and $B$, calculate the number of pairs $(a, b)$ such that $1 \\le a \\le A$, $1 \\le b \\le B$, and the equation $a \\cdot b + a + b = conc(a, b)$ is true; $conc(a, b)$ is the concatenation of $a$ and $b$ (for example, $conc(12, 23) = 1223$, $conc(100, 11) = 10011$). \\textbf{$a$ and $b$ should not contain leading zeroes}.",
    "tutorial": "Let's perform some conversions: $a \\cdot b + a + b = conc(a, b)$ $a \\cdot b + a + b = a \\cdot 10^{|b|} + b$, where $|b|$ is the length of decimal representation of $b$. $a \\cdot b + a = a \\cdot 10^{|b|}$ $b + 1 = 10^{|b|}$ Thus, $b$ always look like $99 \\dots 99$. So, the answer is $a * (|b + 1| - 1)$.",
    "code": "for t in range(int(input())):\n\ta, b = map(int, input().split())\n\tprint(a * (len(str(b + 1)) - 1))",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1288",
    "index": "C",
    "title": "Two Arrays",
    "statement": "You are given two integers $n$ and $m$. Calculate the number of pairs of arrays $(a, b)$ such that:\n\n- the length of both arrays is equal to $m$;\n- each element of each array is an integer between $1$ and $n$ (inclusive);\n- $a_i \\le b_i$ for any index $i$ from $1$ to $m$;\n- array $a$ is sorted in non-descending order;\n- array $b$ is sorted in non-ascending order.\n\nAs the result can be very large, you should print it modulo $10^9+7$.",
    "tutorial": "Let's consider the following sequence: $a_1, a_2, \\dots, a_m, b_m, b_{m-1}, \\dots , b_1$. It's sequence of length $2m$ sorted in non-descending order, where each element of each sequence is an integer between $1$ and $n$. We can find the number of such sequences by simple combinatorics - it's combination with repetitions. So the answer is ${n+2m-1 \\choose 2m} = \\frac{(n + 2m - 1)!}{(2m)! (n-1)!}$.",
    "code": "from math import factorial as fact\nmod = 10**9 + 7\n\ndef C(n, k):\n\treturn fact(n) // (fact(k) * fact(n - k))\n\nn, m = map(int, input().split())\nprint(C(n + 2*m - 1, 2*m) % mod)",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1288",
    "index": "D",
    "title": "Minimax Problem",
    "statement": "You are given $n$ arrays $a_1$, $a_2$, ..., $a_n$; each array consists of exactly $m$ integers. We denote the $y$-th element of the $x$-th array as $a_{x, y}$.\n\nYou have to choose two arrays $a_i$ and $a_j$ ($1 \\le i, j \\le n$, it is possible that $i = j$). After that, you will obtain a new array $b$ consisting of $m$ integers, such that for every $k \\in [1, m]$ $b_k = \\max(a_{i, k}, a_{j, k})$.\n\nYour goal is to choose $i$ and $j$ so that the value of $\\min \\limits_{k = 1}^{m} b_k$ is maximum possible.",
    "tutorial": "We will use binary search to solve the problem. Suppose we want to know if the answer is not less than $x$. Each array can be represented by a $m$-bit mask, where the $i$-th bit is $1$ if the $i$-th element of the array is not less than $x$, or $0$ if the $i$-th element is less than $x$. If we want to verify that the answer is not less than $x$, we have to choose two arrays such that bitwise OR of their masks is $2^m - 1$. Checking all pairs of arrays is too slow. Instead, we can treat the arrays represented by the same masks as equal - so we will have no more than $2^m$ distinct arrays, and we can iterate over $4^m$ pairs. Overall, the solution works in $O(\\log A (4^m + nm))$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nvector<vector<int> > a;\nint a1, a2;\n\nbool can(int mid)\n{\n    vector<int> msk(1 << m, -1);\n    for(int i = 0; i < n; i++)\n    {\n        int cur = 0;\n        for(int j = 0; j < m; j++)\n            if(a[i][j] >= mid)\n                cur ^= (1 << j);\n        msk[cur] = i;\n    }\n    if(msk[(1 << m) - 1] != -1)\n    {\n        a1 = a2 = msk[(1 << m) - 1];\n        return true;\n    }\n    for(int i = 0; i < (1 << m); i++)\n        for(int j = 0; j < (1 << m); j++)\n            if(msk[i] != -1 && msk[j] != -1 && (i | j) == (1 << m) - 1)\n            {\n                a1 = msk[i];\n                a2 = msk[j];\n                return true;\n            }\n    return false;\n}\n\nint main()\n{\n    scanf(\"%d %d\", &n, &m);\n    a.resize(n, vector<int>(m));\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < m; j++)\n            scanf(\"%d\", &a[i][j]);\n    int lf = 0;\n    int rg = int(1e9) + 43;\n    while(rg - lf > 1)\n    {\n        int m = (lf + rg) / 2;\n        if(can(m))\n            lf = m;\n        else\n            rg = m;            \n    }\n    assert(can(lf));\n    printf(\"%d %d\\n\", a1 + 1, a2 + 1);\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1288",
    "index": "E",
    "title": "Messenger Simulator",
    "statement": "Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has $n$ friends, numbered from $1$ to $n$.\n\nRecall that a permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array.\n\nSo his recent chat list can be represented with a permutation $p$ of size $n$. $p_1$ is the most recent friend Polycarp talked to, $p_2$ is the second most recent and so on.\n\nInitially, Polycarp's recent chat list $p$ looks like $1, 2, \\dots, n$ (in other words, it is an identity permutation).\n\nAfter that he receives $m$ messages, the $j$-th message comes from the friend $a_j$. And that causes friend $a_j$ to move to the first position in a permutation, shifting everyone between the first position and the current position of $a_j$ by $1$. Note that if the friend $a_j$ is in the first position already then nothing happens.\n\nFor example, let the recent chat list be $p = [4, 1, 5, 3, 2]$:\n\n- if he gets messaged by friend $3$, then $p$ becomes $[3, 4, 1, 5, 2]$;\n- if he gets messaged by friend $4$, then $p$ doesn't change $[4, 1, 5, 3, 2]$;\n- if he gets messaged by friend $2$, then $p$ becomes $[2, 4, 1, 5, 3]$.\n\nFor each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.",
    "tutorial": "So I have two slightly different approaches to the problem. There is a straightforward (no brain) one and a bit smarter one. The minimum place is the same in both solutions. For the $i$-th friend it's just $i$ if he never moves and $1$ otherwise. Obtaining the maximum place is trickier. For the first approach, take a look what happens with some friend $i$ after he gets moved to the first position. Or what's more useful - what happens after he gets moved to the first position and before he gets moved again afterwards (or the queries end). Notice how every other friend is to the right of him initially. Thus, if anyone sends a message, then the position of the friend $i$ increases by one. However, if that friend moves again, nothing changes. That should remind of a well-known problem already. You are just required to count the number of distinct values on some segments. The constraints allow you to do whatever you want: segtree with vectors in nodes, Mo, persistent segtree (I hope ML is not too tight for that). Unfortunately, for each friend we have missed the part before his first move. In that case for each $i$ you need to count the number of distinct values greater than $i$, as only friends with greater index will matter. Luckily, you can do it in a single BIT. Let $j$-th its value be set to zero if the friend $j$ hasn't sent messages and one otherwise. Let's process messages from left to right. If the friend sends a message for the first time, then update the BIT with $1$ in his index and update his answer with the suffix sum of values greater than his index. Finally, there are also friends, who haven't sent messages at all. As we have built the BIT already, the only thing left is to iterate over these friends and update the answers for them with a suffix sum. Overall complexity: $O((n+m) \\log^2 m)$/$O((n+m) \\sqrt m)$/$O((n+m) \\log m)$. The attached solutions are $O((n+m) \\sqrt m)$ and $O((n+m) \\log^2 m)$. The second solution requires a small observation to be made. Notice that for each friend you can only check his position right before his moves and at the end of the messages. That works because the position can decrease only by his move, so it's either increases or stays the same between the moves. So let's learn to simulate the process quickly. The process we are given requires us to move someone to the first position and then shift some friends. Let's not shift! And let's also reverse the list, it's more convenient to append instead of prepending. So initially the list is $n, n - 1, \\dots, 1$ and the message moves a friend to the end of the list. Allocate $n + m$ positions in a BIT, for example. Initially the first $n$ positions are taken, the rest $m$ are free (mark them with ones and zeroes, respectively). For each friend his position in this BIT is known (initially they are $pos_i = n - i + 1$, because we reversed the list). On the $j$-th message sent count the number of taken positions to the right of $pos_{a[j]}$, set $0$ in $pos_{a[j]}$, update $pos_{a[j]}: =j+n$ and set $1$ in $pos_{a[j]}$. And don't forget to update each friend's maximum after all the messages are sent, that is the number of taken positions to the right of his final one as well. Overall complexity $O((n+m) \\log (n+m))$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int N = 600 * 1000 + 13;\n\nint f[N];\n\nvoid upd(int x, int val){\n\tfor (int i = x; i >= 0; i = (i & (i + 1)) - 1)\n\t\tf[i] += val;\n}\n\nint get(int x){\n\tint res = 0;\n\tfor (int i = x; i < N; i |= i + 1)\n\t\tres += f[i];\n\treturn res;\n}\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tvector<int> mn(n);\n\tiota(mn.begin(), mn.end(), 0);\n\tvector<int> mx = mn;\n\t\n\tvector<int> a(m);\n\tforn(i, m){\n\t\tscanf(\"%d\", &a[i]);\n\t\t--a[i];\n\t\tmn[a[i]] = 0;\n\t}\n\t\n\tvector<int> pos(n);\n\tforn(i, n) pos[i] = n - i - 1;\n\tforn(i, n) upd(i, 1);\n\t\n\tforn(i, m){\n\t\tmx[a[i]] = max(mx[a[i]], get(pos[a[i]] + 1));\n\t\tupd(pos[a[i]], -1);\n\t\tpos[a[i]] = i + n;\n\t\tupd(pos[a[i]], 1);\n\t}\n\tforn(i, n){\n\t\tmx[i] = max(mx[i], get(pos[i] + 1));\n\t}\n\t\n\tforn(i, n) printf(\"%d %d\\n\", mn[i] + 1, mx[i] + 1);\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1288",
    "index": "F",
    "title": "Red-Blue Graph",
    "statement": "You are given a bipartite graph: the first part of this graph contains $n_1$ vertices, the second part contains $n_2$ vertices, and there are $m$ edges. \\textbf{The graph can contain multiple edges}.\n\nInitially, each edge is colorless. For each edge, you may either leave it uncolored (it is free), paint it red (it costs $r$ coins) or paint it blue (it costs $b$ coins). No edge can be painted red and blue simultaneously.\n\nThere are three types of vertices in this graph — colorless, red and blue. Colored vertices impose additional constraints on edges' colours:\n\n- for each red vertex, the number of red edges indicent to it should be \\textbf{strictly greater} than the number of blue edges incident to it;\n- for each blue vertex, the number of blue edges indicent to it should be \\textbf{strictly greater} than the number of red edges incident to it.\n\nColorless vertices impose no additional constraints.\n\nYour goal is to paint some (possibly none) edges so that all constraints are met, and among all ways to do so, you should choose the one with minimum total cost.",
    "tutorial": "A lot of things in this problem may tell us that we should try thinking about a flow solution. Okay, let's try to model the problem as a flow network. First of all, our network will consist of vertices and edges of the original graph. We somehow have to denote \"red\", \"blue\" and \"colorless\" edges; we will do it as follows: each edge of the original graph corresponds to a bidirectional edge with capacity $1$ in the network; if the flow goes from the left part to the right part along the edge, it is red; if the flow goes from right to left, it is a blue edge; and if there is no flow along the edge, it is colorless. Okay, we need to impose some constraints on the vertices. Consider some vertex $v$ from the left part. Each red edge incident to it transfers one unit of flow from it to some other vertex, and each blue edge incident to it does the opposite. So, the difference between the number of blue and red edges incident to $v$ is the amount of excess flow that has to be transfered somewhere else. If $v$ is colorless, there are no constraints on the colors of edges, so this amount of excess flow does not matter - to model it, we can add a directed edge from source to $v$ with infinite capacity, and a directed edge from $v$ to sink with infinite capacity. What if $v$ is red? At least one unit of flow should be transfered to it; so we add a directed edge from the source to $v$ with infinite capacity such that there should be at least one unit of flow along it. And if $v$ is blue, we need to transfer at least one unit of excess flow from it - so we add a directed edge from $v$ to the sink with infinite capacity such that there is at least one unit of flow along it. The colors of the vertices in the right part can be modeled symmetrically. How to deal with edges such that there should be some flow along them? You may use classic \"flows with demands\" approach from here: https://cp-algorithms.com/graph/flow_with_demands.html. Or you can model it with the help of the costs: if the flow along the edge should be between $l$ and $r$, we can add two edges: one with capacity $l$ and cost $k$ (where $k$ is a negative number with sufficiently large absolute value, for example, $-10^9$), and another with capacity $r - l$ and cost $0$. Okay, now we know how to find at least one painting. How about finding the cheapest painting that meets all the constraints? One of the simplest ways to do it is to impose costs on the edges of the original graph: we can treat each edge of the original graph as a pair of directed edges, one going from left to right with capacity $1$ and cost $r$, and another going from right to left with capacity $1$ and cost $b$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 443;\n\nint n1, n2, m, r, b;\nstring s1, s2;\nint u[N];\nint v[N];\n\nstruct edge\n{\n    int y, c, f, cost;\n    edge() {};\n    edge(int y, int c, int f, int cost) : y(y), c(c), f(f), cost(cost) {};\n};\n\nint bal[N][N];\nint s, t, oldS, oldT, V;\nvector<int> g[N];\nvector<edge> e;\n\nvoid add(int x, int y, int c, int cost)\n{\n    g[x].push_back(e.size());\n    e.push_back(edge(y, c, 0, cost));\n    g[y].push_back(e.size());\n    e.push_back(edge(x, 0, 0, -cost));\n}\n\nint rem(int num)\n{\n    return e[num].c - e[num].f;\n}   \n\nvoid add_LR(int x, int y, int l, int r, int cost)\n{\n    int c = r - l;\n    if(l > 0)\n    {\n        add(s, y, l, cost);\n        add(x, t, l, cost);\n    }\n    if(c > 0)\n    {\n        add(x, y, c, cost);\n    }\n}\n\nint p[N];\nint d[N];\nint pe[N];\nint inq[N];\n\nbool enlarge()\n{\n    for(int i = 0; i < V; i++)\n    {\n        d[i] = int(1e9);\n        p[i] = -1;\n        pe[i] = -1;\n        inq[i] = 0;\n    }\n    d[s] = 0;\n    queue<int> q;\n    q.push(s);\n    inq[s] = 1;\n    while(!q.empty())\n    {\n        int k = q.front();\n        q.pop();\n        inq[k] = 0;\n        for(auto z : g[k])\n        {\n            if(!rem(z)) continue;\n            if(d[e[z].y] > d[k] + e[z].cost)\n            {\n                p[e[z].y] = k;\n                pe[e[z].y] = z;\n                d[e[z].y] = d[k] + e[z].cost;\n                if(!inq[e[z].y])\n                {\n                    q.push(e[z].y);\n                    inq[e[z].y] = 1;\n                }\n            }\n        }\n    }\n    if(p[t] == -1)\n        return false;\n    int cur = t;\n    while(cur != s)\n    {\n        e[pe[cur]].f++;\n        e[pe[cur] ^ 1].f--;\n        cur = p[cur];\n    }\n    return true;\n}\n\nvoid add_edge(int x, int y)\n{\n    add(x, y + n1, 1, r);\n    add(y + n1, x, 1, b);\n}\n\nvoid impose_left(int x)\n{\n    if(s1[x] == 'R')\n    {\n        add_LR(oldS, x, 1, m, 0);\n    }\n    else if(s1[x] == 'B')\n    {\n        add_LR(x, oldT, 1, m, 0);\n    }\n    else\n    {\n        add(oldS, x, m, 0);\n        add(x, oldT, m, 0);\n    }\n}\n\nvoid impose_right(int x)\n{\n    if(s2[x] == 'R')\n    {\n        add_LR(x + n1, oldT, 1, m, 0);\n    }\n    else if(s2[x] == 'B')\n    {\n        add_LR(oldS, x + n1, 1, m, 0);\n    }\n    else\n    {\n        add(oldS, x + n1, m, 0);\n        add(x + n1, oldT, m, 0);\n    }\n}\n\nvoid construct_bal()\n{\n    for(int i = 0; i < n1; i++)\n    {\n        for(auto z : g[i])\n        {\n            if(e[z].y >= n1 && e[z].y < n1 + n2)\n                bal[i][e[z].y - n1] += e[z].f;\n        }\n    }\n}\n\nvoid find_ans()\n{\n    int res = 0;\n    string w = \"\";\n    for(auto x : g[s])\n        if(rem(x))\n        {\n            cout << -1 << endl;\n            return;\n        }\n    for(int i = 0; i < m; i++)\n    {\n        if(bal[u[i]][v[i]] > 0)\n        {\n            bal[u[i]][v[i]]--;\n            res += r;\n            w += \"R\";\n        }\n        else if(bal[u[i]][v[i]] < 0)\n        {\n            bal[u[i]][v[i]]++;\n            res += b;\n            w += \"B\";\n        }\n        else w += \"U\";\n    }\n    cout << res << endl << w << endl;\n}\n\nint main()\n{                       \n    cin >> n1 >> n2 >> m >> r >> b;\n    cin >> s1;\n    cin >> s2;\n    for(int i = 0; i < m; i++)\n    {\n        cin >> u[i] >> v[i];\n        u[i]--;\n        v[i]--;\n    }\n\n    oldS = n1 + n2;\n    oldT = oldS + 1;\n    s = oldT + 1;\n    t = s + 1;\n    V = t + 1;\n\n    for(int i = 0; i < n1; i++)\n        impose_left(i);\n    for(int i = 0; i < n2; i++)\n        impose_right(i);\n    for(int i = 0; i < m; i++)\n        add_edge(u[i], v[i]);\n    add(oldT, oldS, 100000, 0);\n    while(enlarge());\n    construct_bal();\n    find_ans();\n}",
    "tags": [
      "constructive algorithms",
      "flows"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1290",
    "index": "A",
    "title": "Mind Control",
    "statement": "You and your $n - 1$ friends have found an array of integers $a_1, a_2, \\dots, a_n$. You have decided to share it in the following way: All $n$ of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.\n\nYou are standing in the $m$-th position in the line. \\textbf{Before the process starts}, you may choose up to $k$ different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. \\textbf{Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded}.\n\nSuppose that you're doing your choices optimally. What is the greatest integer $x$ such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be \\underline{greater than or equal to} $x$?\n\nPlease note that the friends you don't control may do their choice \\textbf{\\underline{arbitrarily}}, and they will not necessarily take the biggest element available.",
    "tutorial": "People behind you are useless, ignore them. Let's assume that $k \\le m-1$. It's always optimal to control as many people as possible. Your strategy can be summarized by a single integer $x$, the number of people you force to take the first element (among the $k$ you control). Similarly, the strategy of your opponents can be summarized by a single integer integer $y$, the number of non-controlled friends who choose to take the first element. When it will be your turn, the array will contain exactly $n-m+1$ elements. You will be able to take the biggest element among the first element $a_{1+x+y}$ and the last element $a_{1+x+y+(n-m)}$. These observations lead to an obvious $O(n^2)$ solution (iterate over all strategies $x$ and for each strategy, iterate over all cases $y$), which was sufficient to pass the tests. However, the second iteration can be easily optimized with a data structure. Let's note $b_i = \\max(a_{1+i}, a_{1+i+(n-m)})$. The final answer is $\\displaystyle \\max_{x \\in [0 ; k]} \\bigg[ \\min_{y \\in [0 ; m-1-k]} b_{x+y} \\bigg]$. Note that it can be rewritten as $\\displaystyle \\max_{x \\in [0 ; k]} \\bigg[ \\min_{y' \\in [x ; x+m-1-k]} b_{y'} \\bigg]$. It can be computed in $O(n \\log n)$ using segment tree or in $O(n)$ using monotonic deque.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n    int n, m, k;\n    cin >> n >> m >> k;\n    k = min(k, m - 1);\n    vector<int> a(n);\n    for(auto &x : a)\n        cin >> x;\n    vector<int> b;\n    for(int i = 0; i < m; i++)\n        b.push_back(max(a[i], a[i + n - m]));\n    int sz = m - k;\n    int ans = 0;\n    deque<int> q;\n    for(int i = 0, j = 0; i + sz - 1 < m; i++) {\n        while(q.size() && q.front() < i)\n            q.pop_front();\n        while(j < i + sz) {\n            while(q.size() && b[q.back()] >= b[j])\n                q.pop_back();\n            q.push_back(j++);\n        }\n        ans = max(ans, b[q.front()]);\n    }\n    cout << ans << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--)\n        solve();\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1290",
    "index": "B",
    "title": "Irreducible Anagrams",
    "statement": "Let's call two strings $s$ and $t$ anagrams of each other if it is possible to rearrange symbols in the string $s$ to get a string, equal to $t$.\n\nLet's consider two strings $s$ and $t$ \\textbf{which are anagrams of each other}. We say that $t$ is a reducible anagram of $s$ if there exists an integer $k \\ge 2$ and $2k$ non-empty strings $s_1, t_1, s_2, t_2, \\dots, s_k, t_k$ that satisfy the following conditions:\n\n- If we write the strings $s_1, s_2, \\dots, s_k$ in order, the resulting string will be equal to $s$;\n- If we write the strings $t_1, t_2, \\dots, t_k$ in order, the resulting string will be equal to $t$;\n- For all integers $i$ between $1$ and $k$ inclusive, $s_i$ and $t_i$ are anagrams of each other.\n\nIf such strings don't exist, then $t$ is said to be an irreducible anagram of $s$. \\textbf{Note that these notions are only defined when $s$ and $t$ are anagrams of each other}.\n\nFor example, consider the string $s = $ \"gamegame\". Then the string $t = $ \"megamage\" is a reducible anagram of $s$, we may choose for example $s_1 = $ \"game\", $s_2 = $ \"gam\", $s_3 = $ \"e\" and $t_1 = $ \"mega\", $t_2 = $ \"mag\", $t_3 = $ \"e\":\n\nOn the other hand, we can prove that $t = $ \"memegaga\" is an irreducible anagram of $s$.\n\nYou will be given a string $s$ and $q$ queries, represented by two integers $1 \\le l \\le r \\le |s|$ (where $|s|$ is equal to the length of the string $s$). For each query, you should find if the substring of $s$ formed by characters from the $l$-th to the $r$-th has \\underline{at least one} irreducible anagram.",
    "tutorial": "We claim that a string has at least one irreducible anagram if and only if one of the following conditions holds: Its length is equal to $1$. Its first and last characters are different. It contains at least three different characters. Once we have proven this characterization it is easy to solve the problem: For any given query, the first and second conditions are trivial to check, while the third condition can be checked efficiently if we maintain the number of appearances of each character in each prefix of our string. This allows us to answer queries in $O(k)$ where $k = 26$ is the size of our alphabet. Now let's prove the characterization. Consider any string $s$ with $n = |s| \\ge 2$. First note that for any two strings $a$ and $b$ that are anagrams, it is enough to check that no two proper prefixes of them are anagrams for them to be irreducible anagrams, because if $a$ and $b$ are reducible then $a_1$ and $b_1$ are two proper prefixes that are anagrams. We will consider three cases. In what follows all indices are $1$-based. If $s[1] \\neq s[n]$.Write all occurrences of $s[n]$ in $s$, and then write all the remaining characters of $s$ in any order. Every proper prefix of the resulting string will have more occurrences of $s[n]$ than the corresponding prefix of $s$, so no two of them will be anagrams. Write all occurrences of $s[n]$ in $s$, and then write all the remaining characters of $s$ in any order. Every proper prefix of the resulting string will have more occurrences of $s[n]$ than the corresponding prefix of $s$, so no two of them will be anagrams. If $s[1] = s[n]$ and $s$ has at least three different characters.Consider the last distinct character that appears in $s$. Write all occurrences of it, followed by all occurrences of $s[n]$, and then write the remaining characters of $s$ in any order. We can check that every proper prefix of the resulting strings contains more occurrences of either this last distinct character, or more occurrences of $s[n]$, than the corresponding prefix of $s$, so no two proper prefixes are anagrams. Consider the last distinct character that appears in $s$. Write all occurrences of it, followed by all occurrences of $s[n]$, and then write the remaining characters of $s$ in any order. We can check that every proper prefix of the resulting strings contains more occurrences of either this last distinct character, or more occurrences of $s[n]$, than the corresponding prefix of $s$, so no two proper prefixes are anagrams. If $s[1] = s[n]$ and $s$ has at most two different characters.Assume that $s$ only has characters $a$ and $b$, and that $s[1] = a$. Assume that $s$ has an irreducible anagram $t$. Then $t[1] = b$, as otherwise $s[1, 1]$ and $t[1, 1]$ are anagrams. Consider the leftmost position $x$ such that the prefix $s[1, x]$ has at least as many appearances of $b$ as $t$. We have $x \\le n - 1$ because $s[1, n - 1]$ contains every possible appearance of $b$. Moreover, we have $x > 1$. Now, notice that $t[1, x - 1]$ must have strictly more appearances of $b$ than $s[1, x - 1]$. This is only possible if this prefix had exactly one more appearance of $b$, and then $s[1, x]$ and $t[1, x]$ have the same number of appearances of $b$. But this means that the proper prefixes $s[1, x]$ and $t[1, x]$ are anagrams - a contradiction. Assume that $s$ only has characters $a$ and $b$, and that $s[1] = a$. Assume that $s$ has an irreducible anagram $t$. Then $t[1] = b$, as otherwise $s[1, 1]$ and $t[1, 1]$ are anagrams. Consider the leftmost position $x$ such that the prefix $s[1, x]$ has at least as many appearances of $b$ as $t$. We have $x \\le n - 1$ because $s[1, n - 1]$ contains every possible appearance of $b$. Moreover, we have $x > 1$. Now, notice that $t[1, x - 1]$ must have strictly more appearances of $b$ than $s[1, x - 1]$. This is only possible if this prefix had exactly one more appearance of $b$, and then $s[1, x]$ and $t[1, x]$ have the same number of appearances of $b$. But this means that the proper prefixes $s[1, x]$ and $t[1, x]$ are anagrams - a contradiction.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 200005;\n\nchar s[N];\nint n, q, l, r, sum[N][26];\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> (s + 1);\n    n = strlen(s + 1);\n    for (int i = 1; i <= n; i++) {\n        for (int j = 0; j < 26; j++) {\n            sum[i][j] = sum[i - 1][j];\n        }\n        sum[i][s[i] - 'a']++;\n    }\n    cin >> q;\n    while (q--) {\n        cin >> l >> r;\n        int cnt = 0;\n        for (int i = 0; i < 26; i++) {\n            cnt += (sum[r][i] - sum[l - 1][i] > 0);\n        }\n        if (l == r || cnt >= 3 || s[l] != s[r]) {\n            cout << \"Yes\\n\";\n        } else {\n            cout << \"No\\n\";\n        }\n    }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "strings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1290",
    "index": "C",
    "title": "Prefix Enlightenment",
    "statement": "There are $n$ lamps on a line, numbered from $1$ to $n$. Each one has an initial state off ($0$) or on ($1$).\n\nYou're given $k$ subsets $A_1, \\ldots, A_k$ of $\\{1, 2, \\dots, n\\}$, such that the intersection of any three subsets is empty. In other words, for all $1 \\le i_1 < i_2 < i_3 \\le k$, $A_{i_1} \\cap A_{i_2} \\cap A_{i_3} = \\varnothing$.\n\nIn one operation, you can choose one of these $k$ subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.\n\nLet $m_i$ be the minimum number of operations you have to do in order to make the $i$ first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between $i+1$ and $n$), they can be either off or on.\n\nYou have to compute $m_i$ for all $1 \\le i \\le n$.",
    "tutorial": "The condition \"the intersection of any three subsets is empty\" can be easily rephrased in a more useful way: each element appears in at most two subsets. Let's suppose for the moment that each elements appears in exactly two subsets. We can think of each element as an edge between the subsets, it's a classical point of view. If we see subsets as nodes, we can model the subsets choice by coloring nodes into two colors, \"taken\" or \"non-taken\". If an element is initially off, we need to take exactly one of the subsets containing it. The corresponding edge should have endpoints with different color. If an element is initially on, we must take none or both subsets : endpoints with same color. We recognize a sort of bipartition, obviously there are at most two correct colorings for each connected component: fixing the color of a node fix the color of all connected nodes. Hence, the final answer is the sum for each component, of the size of the smaller side of the partition. Since the answer exists for $i = n$, there exists a such partition of the graph (into \"red\" and \"blue\" nodes). We can find it with usual dfs, and keep it for lower values of $i$. In order to compute all $m_i$ efficiently, we start from a graph with no edges ($i = 0$), and we add edges with DSU, maintaining in each connected component the count of nodes in red side, and the count of nodes in blue side. Now, how to deal with elements that appears in exactly one subset? They don't add any edge in the graph, but they force to take one of the sides of the connected component. To simulate this, we can use a special forced flag, or just fix the count of the other side to $+\\infty$ (but be careful about overflow if you do that). Final complexity : $O((n+k) \\cdot \\alpha(k))$.",
    "code": "#include <bits/stdc++.h>\n#define fi first\n#define se second\nusing namespace std;\n\nconst int N = 1E6 + 5, K = 1E6 + 5, INF = 1E9 + 7;\n\nint n, k, c, v, ans = 0, dsu[K];\nchar s[N];\nvector<int> adj[N];\n\nstruct node {\n    int l, r, xo;\n\n    node(int _l = 0, int _r = 0, int _xo = 0) : l(_l), r(_r), xo(_xo) {}\n\n    int get() {\n        return min(l, r);\n    }\n\n    inline void operator+=(node oth) {\n        l = min(INF, l + oth.l);\n        r = min(INF, r + oth.r);\n    }\n} val[K];\n\npair<int, int> trace(int u) {\n    if (dsu[u] < 0) {\n        return {u, 0};\n    } else {\n        pair<int, int> tmp = trace(dsu[u]);\n        dsu[u] = tmp.fi;\n        val[u].xo ^= tmp.se;\n        return {dsu[u], val[u].xo};\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> n >> k >> (s + 1);\n    for (int i = 1; i <= k; i++) {\n        dsu[i] = -1;\n        val[i] = node(1, 0, 0);\n        cin >> c;\n        while (c--) {\n            cin >> v;\n            adj[v].push_back(i);\n        }\n    }\n    for (int i = 1; i <= n; i++) {\n        int typ = (s[i] - '0') ^ 1;\n        if (ans != -1) {\n            if (adj[i].size() == 1) {\n                pair<int, int> u = trace(adj[i][0]);\n                ans -= val[u.fi].get();\n                val[u.fi] += node((u.se == typ) * INF, (u.se != typ) * INF);\n                ans += val[u.fi].get();\n            } else if (adj[i].size() == 2) {\n                pair<int, int> u = trace(adj[i][0]);\n                pair<int, int> v = trace(adj[i][1]);\n                if (u.fi != v.fi) {\n                    ans -= val[u.fi].get() + val[v.fi].get();\n                    if (dsu[u.fi] > dsu[v.fi]) {\n                        swap(u, v);\n                    }\n                    if (u.se ^ v.se ^ typ) {\n                        swap(val[v.fi].l, val[v.fi].r);\n                        val[v.fi].xo = 1;\n                    }\n                    dsu[u.fi] += dsu[v.fi];\n                    dsu[v.fi] = u.fi;\n                    val[u.fi] += val[v.fi];\n                    ans += val[u.fi].get();\n                }\n            }\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1290",
    "index": "D",
    "title": "Coffee Varieties (hard version)",
    "statement": "This is the hard version of the problem. You can find the easy version in the Div. 2 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.\n\n\\textbf{This is an interactive problem.}\n\nYou're considering moving to another city, where one of your friends already lives. There are $n$ cafés in this city, where $n$ is a power of two. The $i$-th café produces a single variety of coffee $a_i$.\n\nAs you're a coffee-lover, before deciding to move or not, \\textbf{you want to know the number $d$ of distinct varieties of coffees} produced in this city.\n\nYou don't know the values $a_1, \\ldots, a_n$. Fortunately, your friend has a memory of size $k$, where $k$ is a power of two.\n\nOnce per day, you can ask him to taste a cup of coffee produced by the café $c$, and he will tell you if he tasted a similar coffee during the last $k$ days.\n\nYou can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most $30\\ 000$ times.\n\nMore formally, the memory of your friend is a queue $S$. Doing a query on café $c$ will:\n\n- Tell you if $a_c$ is in $S$;\n- Add $a_c$ at the back of $S$;\n- If $|S| > k$, pop the front element of $S$.\n\nDoing a reset request will pop all elements out of $S$.\n\nYour friend can taste at most $\\dfrac{3n^2}{2k}$ cups of coffee in total. Find the diversity $d$ (number of distinct values in the array $a$).\n\nNote that asking your friend to reset his memory \\textbf{does not count} towards the number of times you ask your friend to taste a cup of coffee.\n\nIn some test cases the behavior of the interactor \\textbf{is adaptive}. It means that the array $a$ may be \\textbf{not fixed} before the start of the interaction and may \\textbf{depend on your queries}. It is guaranteed that at any moment of the interaction, there is at least one array $a$ consistent with all the answers given so far.",
    "tutorial": "Easy version (constant 2) Let's try to maintain representative positions for each value. In the beginning, when we know nothing, every position can be a potential representative. We will call them alive positions, and using queries, we will try to kill some positions and ending up with exactly one alive position per value. The answer will be the number of alive positions. Note that when we kill a position, there must be another alive position with the same value. The danger here is to compare a position to a dead position of the same value: we may end up killing the single representative of the value. Create blocks of size $\\frac{k}{2}$, (or $1$ if $k = 1$). Query $1, 2, \\ldots, n$ and kill the element if you get Yes answer. Each value has at least one alive occurrence, its leftmost one. Moreover, all equalities inside blocks are removed. In order to remove equalities between blocks, compare all unordered pairs of blocks (for each pair, reset the memory, look all elements in the first one, then all elements in the second one, and kill elements in the second one for each Yes answer). Note that we don't need to compare adjacent blocks. The number of queries is a bit less than $\\frac{2n^2}{k}$. Hard version (constant 1.5) Querying $1, 2, \\ldots, n$ allowed us to compare pairs $(i, i+1)$ in a very efficient manner because we reuse the memory of the previous comparison. Let's try to generalize this. Consider a complete graph where nodes are blocks. Comparing pairs of blocks can be seen as covering edges of the graph. We can take any elementary path (that doesn't pass through a node twice), reset the memory and explore blocks in the corresponding order (killing elements for each Yes answer). Each path will require $(\\text{number of edges} + 1) \\cdot \\frac{k}{2}$ queries. It's optimal to have disjoint paths (if a path goes through an already visited edge, we can split it there). Hence, we want to use a few disjoint paths to cover all edges. A randomized DFS works experimentally well (constant around $1.2$). However, we can acheive constant $1$ using the following zig-zag pattern: $s \\rightarrow s-1 \\rightarrow s+1 \\rightarrow s-2 \\rightarrow s+2 \\rightarrow \\ldots$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nbool ask(int pos)\n{\n    cout << \"? \" << pos+1 << endl << flush;\n    char c; cin >> c;\n    if (c == 'E') exit(0);\n    return (c == 'Y');\n}\n\nint main()\n{\n    int nbElem, memSize, nbBlocks;\n    cin >> nbElem >> memSize;\n    nbBlocks = nbElem / memSize;\n\n    vector<bool> isAlive(nbElem, true);\n\n    for (int startBlock = 0; startBlock < nbBlocks; ++startBlock) {\n\t    int delta = 0;\n\t    cout << \"R\" << endl << flush;\n\t    for (int iDo = 0; iDo < nbBlocks; ++iDo) {\n\t\t    int curBlock = (startBlock+delta+nbBlocks) % nbBlocks;\n\t\t    int st = curBlock*memSize;\n\t\t    for (int elem = st; elem < st+memSize; ++elem) {\n\t\t\t    if (isAlive[elem]) {\n\t\t\t\t    if (ask(elem)) isAlive[elem] = false;\n\t\t\t    }\n\t\t    }\n\n\t\t    if (delta >= 0) ++delta;\n\t\t    delta = -delta;\n\t    }\n    }\n\n    int nbAlive = count(isAlive.begin(), isAlive.end(), true);\n    cout << \"! \" << nbAlive << endl << flush;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "interactive"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1290",
    "index": "E",
    "title": "Cartesian Tree ",
    "statement": "Ildar is the algorithm teacher of William and Harris. Today, Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.\n\nA cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows:\n\n- If the sequence is empty, return an empty tree;\n- Let the position of the \\textbf{maximum} element be $x$;\n- Remove element on the position $x$ from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily);\n- Build cartesian tree for each part;\n- Create a new vertex for the element, that was on the position $x$ which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex;\n- Return the tree we have gotten.\n\nFor example, this is the cartesian tree for the sequence $4, 2, 7, 3, 5, 6, 1$:\n\nAfter teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence $a$.\n\nIn the $i$-th round, he inserts an element with value $i$ somewhere in $a$. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence $a$?\n\nNode $v$ is in the node $u$ subtree if and only if $v = u$ or $v$ is in the subtree of one of the vertex $u$ children. The size of the subtree of node $u$ is the number of nodes $v$ such that $v$ is in the subtree of $u$.\n\nIldar will do $n$ rounds in total. The homework is the sequence of answers to the $n$ questions.\n\nThe next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence $a$ from William. However, he has no idea how to find the answers to the $n$ questions. Help Harris!",
    "tutorial": "Instead of inserting numbers one by one, let's imagine I have $n$ blanks in a row, and I will fill the blanks with integers from $[1,n]$ in order, and I want to know about the cartesian tree after each blank filled. In the following parts of the solution, I will use positions in the original array instead of positions in the contracted array to label things. In the process of building a cartesian tree, a node is created for each recursive call of building a tree for a subarray $[l,r]$. Let's label the node created at that moment to be $(l,r)$. We realize that $r-l+1$ will be the size of the subtree of that node. However, in our problem, some positions can be blanks, so the actual subtree size of a node $(l,r)$ is the number of positions that are not blanks in the subarray $[l,r]$. So now we are finding the sum of the number of non-blanks in the range for each node $(l,r)$ in our cartesian tree. Let $pf(r)$ be the number of non-blanks in the first $r$ positions of the sequence. Then we are finding sum of $pf(r)-pf(l-1)$ for each node $(l,r)$. To proceed, observe a property for a cartesian tree. Let's define for each integer $p$, let $maxr(p)$ to be the largest $r$ such that $(p,r)$ is a node, or just null if there is no nodes of the form $(p,r)$. Similarly, define $minl(p)$ to be the smallest $l$ such that $(l,p)$ is a node. Then, for each node $(l,r)$, exactly one of the following is true: $maxr(l)=r$. $minl(r)=l$. Except when $(l,r)$ is the root. If we know: sum of $pf(maxr(l))$ over all $maxr(l)$ that is not null. sum of $pf(l-1)$ over all $maxr(l)$ that is not null. sum of $pf(r)$ over all $minl(r)$that is not null. sum of $pf(minl(r)-1)$ over all $minl(r)$ that is not null. Then we can find out the answer. As it is more or less symmetric I will only care about part (1) and (2) from now on. Let's find out what would happen to nodes of our tree if we fill $i+1$ into position $x$, replacing a blank. Let's omit how the nodes connect each other and just track the labels of each node. For convenience, we will make the following definitions. Call $prv$ the nearest non-blank position on the left side of $x$. Call $nxt$ the nearest non-blank position on the right side of $x$. Call $head$ the leftmost non-blank position. Call $tail$ the rightmost non-blank position. Firstly, every node that is of the form $(p,q)$ where $p \\le x \\le q$, will be split into two halves of $(p,prv)$ and $(nxt,q)$. Then, duplicates (nodes that represent the same range) will be removed. Finally, there will be a new node that would represent the root, which is $(head,tail)$. Let's track how $maxr$ changes. $maxr(p)=\\min(maxr(p),prv)$ for all p in the range $[head,prv]$. Some modification to values of $maxr(head)$, $maxr(x)$ and $maxr(nxt)$. As the first step doesn't change whether values are null or not, and modifications to the second step can be easily handled, part (2) can be easily maintained by a Fenwick tree. So it remains to compute part (1). Imagine instead of computing sum of $pf(maxr(l))$, we are computing sum of $maxr(l)$ Then, we realise that we are having a Segment Tree Beats problem. You have to maintain a sequence with 3 kinds of operation: Do $a[x]=\\min(a[x],v)$ for $x$ in $[l,r]$. $a[x]=v$. Query the sum of the whole array. Check part 2 of this blog and this proof of time complexity. Then we can solve this variation of the problem in $O(n\\log n)$. So, we have to modify the above variant into solving the real problem. Look at what we do every time we are doing query 1. We are doing a total of $O(n\\log n)$ times of changing some occurrences of value $u$ to value $v$. Which means, we can maintain the frequency for values of $maxr$. Therefore, for each put-tag operation in our segment tree beats, we just modify a Fenwick tree that represents the frequency of values in $maxr$. Because we have $O(n\\log n)$ updates to the segment tree, the total time complexity is $O(n\\log^2 n)$. It is also possible to replace \"segment tree beats\" with \"treap beats\" and we can support online queries, but it is not required to pass this problem. We also allowed methods of slower complexity (i.e. $O(n \\sqrt{n})$) to pass. It basically is the same but does the above things by sqrt decomposition instead. Care is needed to be sure that there is no extra $log$ factor.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int N=3e5+1;\nconst int ts=1<<21;\nint n;\nll mx[ts],se[ts],mxc[ts];//max, 2nd max, max count\nint sz;\nll ch[N];//which values are changed\nll df[N];//change in frequency\nvoid pass(int id,int c){\n    if(mx[c]>mx[id]) mx[c]=mx[id];\n}\nvoid push(int id){\n    pass(id,id*2);\n    pass(id,id*2+1);\n}\nvoid pull(int id){\n    mx[id]=max(mx[id*2],mx[id*2+1]);\n    mxc[id]=0;\n    if(mx[id]==mx[id*2]) mxc[id]+=mxc[id*2];\n    if(mx[id]==mx[id*2+1]) mxc[id]+=mxc[id*2+1];\n    se[id]=max(se[id*2],se[id*2+1]);\n    if(mx[id*2]!=mx[id]) se[id]=max(se[id],mx[id*2]);\n    if(mx[id*2+1]!=mx[id]) se[id]=max(se[id],mx[id*2+1]);\n}\nvoid upd(int id,int l,int r,int ql,int qr,int v){\n    if(l>qr || r<ql || mx[id]<=v) return;\n    if(ql<=l && r<=qr && se[id]<v){\n\t    ch[++sz]=mx[id];df[mx[id]]-=mxc[id];\n\t    mx[id]=v;\n\t    ch[++sz]=mx[id];df[mx[id]]+=mxc[id];\n\t    return;\n    }\n    push(id);\n    int mid=(l+r)/2;\n    upd(id*2,l,mid,ql,qr,v);\n    upd(id*2+1,mid+1,r,ql,qr,v);\n    pull(id);\n}\nvoid upd2(int id,int l,int r,int p,int v){\n    if(l==r){\n\t    ch[++sz]=mx[id];df[mx[id]]-=mxc[id];\n\t    mx[id]=v;\n\t    ch[++sz]=mx[id];df[mx[id]]+=mxc[id];\n\t    return;\n    }\n    push(id);\n    int mid=(l+r)/2;\n    if(p<=mid) upd2(id*2,l,mid,p,v);\n    else upd2(id*2+1,mid+1,r,p,v);\n    pull(id);\n}\nvoid build(int id,int l,int r){\n    mx[id]=0;mxc[id]=r-l+1;se[id]=-1e9;\n    if(l==r) return;\n    int mid=(l+r)/2;\n    build(id*2,l,mid);\n    build(id*2+1,mid+1,r);\n}\n/////////////////////////////////////////////////\nll bit1[N],bit2[N];\nvoid bupd1(int id,ll v){\n    for(int i=id; i<=n ;i+=i&-i) bit1[i]+=v;\n}\nvoid bupd2(int id,ll v){\n    for(int i=id; i<=n ;i+=i&-i) bit2[i]+=v;\n}\nll bqry1(int id){\n    ll res=0;\n    for(int i=id; i>=1 ;i-=i&-i) res+=bit1[i];\n    return res;\n}\nll bqry2(int id){\n    ll res=0;\n    for(int i=id; i>=1 ;i-=i&-i) res+=bit2[i];\n    return res;\n}\nint a[N],p[N];\nll ans[N];\nset<int>s,t;\nvoid magic(int mg){\n    s.clear();t.clear();build(1,1,n);\n    for(int i=1; i<=n ;i++) bit1[i]=bit2[i]=0;\n    s.insert(p[1]);//set of existed elements\n    t.insert(p[1]);//set of l that maxr[] is not null\n    bupd1(p[1],1);\n    int mx=p[1];//largest existed position\n    upd2(1,1,n,p[1],p[1]);\n    bupd2(p[1],-1);\n    ll tot=-1;\n    for(int i=2; i<=n ;i++){\n\t    int cur=p[i];\n\t    auto it=s.lower_bound(cur);\n\t    bool rm=(it==s.end());//new element is rightmost\n\t    int nxt=0;\n\t    if(!rm) nxt=*it;//next\n\t    if(it==s.begin()){//new element is leftmost\n\t\t    tot-=bqry1(cur);bupd2(cur,-1);\n\t\t    t.insert(cur);\n\t\t    upd2(1,1,n,cur,mx);\n\t    }\n\t    else{\n\t\t    int prv=*(--it);\n\t\t    upd(1,1,n,1,prv,prv);\n\t\t    if(rm) mx=cur;\n\t\t    else{\n\t\t\t    upd2(1,1,n,nxt,mx);\n\t\t\t    if(t.find(nxt)==t.end()){\n\t\t\t\t    tot-=bqry1(nxt);bupd2(nxt,-1);\n\t\t\t\t    t.insert(nxt);\n\t\t\t    }\n\t\t    }\n\t\t    upd2(1,1,n,*s.begin(),mx);\n\t    }\n\t    s.insert(cur);\n\t    tot+=bqry2(n)-bqry2(cur-1);\n\t    bupd1(cur,1);\n\t    for(int j=1; j<=sz ;j++){\n\t\t    if(ch[j]!=0 && df[ch[j]]!=0){\n\t\t\t    tot+=df[ch[j]]*bqry1(ch[j]);\n\t\t\t    bupd2(ch[j],df[ch[j]]);\n\t\t\t    df[ch[j]]=0;\n\t\t    }\n\t    }\n\t    sz=0;\n\t    ans[i]+=tot;\n    }\n}\nvoid solve(){\n    for(int i=1; i<=n ;i++){\n\t    p[a[i]]=i;ans[i]=0;\n    }\n    magic(1);\n    for(int i=1; i<=n ;i++) p[i]=n+1-p[i];\n    magic(0);\n    for(int i=1; i<=n ;i++) ans[i]+=1;\n    for(int i=1; i<=n ;i++) cout << ans[i] << '\\n';\n}\nint main(){\n    ios::sync_with_stdio(false);\n    cin >> n;\n    for(int i=1; i<=n ;i++) cin >> a[i];\n    solve();\n}",
    "tags": [
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1290",
    "index": "F",
    "title": "Making Shapes",
    "statement": "You are given $n$ pairwise non-collinear two-dimensional vectors. You can make shapes in the two-dimensional plane with these vectors in the following fashion:\n\n- Start at the origin $(0, 0)$.\n- Choose a vector and add the segment of the vector to the current point. For example, if your current point is at $(x, y)$ and you choose the vector $(u, v)$, draw a segment from your current point to the point at $(x + u, y + v)$ and set your current point to $(x + u, y + v)$.\n- Repeat step 2 until you reach the origin again.\n\nYou can reuse a vector as many times as you want.\n\nCount the number of different, non-degenerate (with an area greater than $0$) and convex shapes made from applying the steps, such that the shape can be contained within a $m \\times m$ square, and the vectors building the shape are in counter-clockwise fashion. Since this number can be too large, you should calculate it by modulo $998244353$.\n\nTwo shapes are considered the same if there exists some parallel translation of the first shape to another.\n\nA shape can be contained within a $m \\times m$ square if there exists some parallel translation of this shape so that every point $(u, v)$ inside or on the border of the shape satisfies $0 \\leq u, v \\leq m$.",
    "tutorial": "Notice that there is a one-to-one correspondent between a non-degenerate convex shape and a non-empty multiset of vectors. That is because, for each shape, we can generate exactly one multiset of vectors by starting at the lowest-leftest point going counter-clockwise (this is possible because no two vectors are parallel); and for each multiset of vectors, we can generate a single convex shape by sorting the vectors by angle then add them in order. Our problem is now counting the number of multisets of vectors that makes non-degenerate convex shapes that can be contained in a $m \\times m$ square. Rather, we denote $c_i$ as the number of times the $i^{th}$ vector appears in our multiset. We need to count the number of arrays $c$ such that: $\\displaystyle \\sum_{i=1}^{n} c_ix_i = \\sum_{i=1}^{n} c_iy_i = 0$ $\\displaystyle \\sum_{1 \\leq i \\leq n,\\, x_i > 0} c_ix_i \\leq m$ $\\displaystyle \\sum_{1 \\leq i \\leq n,\\, y_i > 0} c_iy_i \\leq m$ Note that the first conditions are equivalent to $\\displaystyle \\sum_{1 \\leq i \\leq n,\\, x_i < 0} -c_ix_i = \\sum_{1 \\leq i \\leq n,\\, x_i > 0} c_ix_i$ and $\\displaystyle \\sum_{1 \\leq i \\leq n,\\, y_i < 0} -c_iy_i = \\sum_{1 \\leq i \\leq n,\\, y_i > 0} c_iy_i$. For the sake of brevity, let's call $\\displaystyle \\sum_{1 \\leq i \\leq n,\\, x_i < 0} -c_ix_i$, $\\displaystyle \\sum_{1 \\leq i \\leq n,\\, x_i > 0} c_ix_i$, $\\displaystyle \\sum_{1 \\leq i \\leq n,\\, y_i < 0} -c_iy_i$, and $\\displaystyle \\sum_{1 \\leq i \\leq n,\\, y_i > 0} c_iy_i$ by $nx$, $px$, $ny$, and $py$ respectively. We will now focus on $\\log_2{m}$ layers of the array $c$, the $i^{th}$ layer is represented by a bitmask of $n$ bits, where each bit $j$ is the $i^{th}$ bit in the binary representation of $c_j$. We see that if we iterate over these layers like this, we can slowly construct $nx$, $px$, $ny$, and $py$ bit by bit, and be able to compare them with each other and with $m$. So, we do a dynamic programming solution where we maintain these states: The current bit. The carry-over value for $nx$. The carry-over value for $px$. The carry-over value for $ny$. The carry-over value for $py$. Whether the suffix of $px$ is larger than the suffix of $m$. Whether the suffix of $py$ is larger than the suffix of $m$. When we iterate over the states, we iterate over the bitmask of the current layer and calculate and update on the next states. note that, for $px$ for example, the carry-over value has a limit of $\\displaystyle \\sum_{i=1}^{\\infty} \\lfloor \\frac{px}{2^i} \\rfloor = px$, and $px \\leq 4n$, so each carry-over dimension is at most $4n$ (practically they cannot all be $4n$ at the same time, so pre-calculating the bound for each dimension is necessary). Complexity: $O(\\log_2{m} \\cdot n^4 \\cdot 2^n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 5, MX = 4 * N, LG = 31, MOD = 998244353;\n\nint n, m, x[N], y[N];\nint px[1 << N], nx[1 << N], py[1 << N], ny[1 << N];\nint dp[LG][MX][MX][MX][MX][2][2];\n\nvoid add(int &x, int y) {\n    x += y;\n    if (x >= MOD) {\n        x -= MOD;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> n >> m;\n    for (int i = 0; i < n; i++) {\n        cin >> x[i] >> y[i];\n    }\n    for (int msk = 0; msk < (1 << n); msk++) {\n        for (int i = 0; i < n; i++) {\n            if (msk >> i & 1) {\n                (x[i] < 0 ? nx : px)[msk] += abs(x[i]);\n                (y[i] < 0 ? ny : py)[msk] += abs(y[i]);\n            }\n        }\n    }\n    int mpx = max(1, px[(1 << n) - 1]);\n    int mpy = max(1, py[(1 << n) - 1]);\n    int mnx = max(1, nx[(1 << n) - 1]);\n    int mny = max(1, ny[(1 << n) - 1]);\n    dp[0][0][0][0][0][0][0] = 1;\n    for (int lg = 0; (1 << lg) <= m; lg++) {                                // bit position\n        for (int cpx = 0; cpx < mpx; cpx++) {                               // carry of positive x\n            for (int cpy = 0; cpy < mpy; cpy++) {                           // carry of positive y\n                for (int cnx = 0; cnx < mnx; cnx++) {                       // carry of negative x\n                    for (int cny = 0; cny < mny; cny++) {                   // carry of negative y\n                        for (int sx = 0; sx < 2; sx++) {                    // is the suffix of x greater than the suffix of m\n                            for (int sy = 0; sy < 2; sy++) {                // is the suffix of y greater than the suffix of m\n                                for (int msk = 0; msk < (1 << n); msk++) {  // iterating over the mask of the current bit position\n                                    int spx = cpx + px[msk];\n                                    int spy = cpy + py[msk];\n                                    int snx = cnx + nx[msk];\n                                    int sny = cny + ny[msk];\n                                    if (((spx ^ snx) & 1) || ((spy ^ sny) & 1)) {\n                                        continue;\n                                    }\n                                    int bx = spx & 1, by = spy & 1;\n                                    int nsx = (bx < (m >> lg & 1) ? 0 : bx > (m >> lg & 1) ? 1 : sx);\n                                    int nsy = (by < (m >> lg & 1) ? 0 : by > (m >> lg & 1) ? 1 : sy);\n                                    add(dp[lg + 1][spx / 2][spy / 2][snx / 2][sny / 2][nsx][nsy], dp[lg][cpx][cpy][cnx][cny][sx][sy]);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    cout << (dp[__lg(m) + 1][0][0][0][0][0][0] + MOD - 1) % MOD << '\\n';\n}",
    "tags": [
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1291",
    "index": "A",
    "title": "Even But Not Even",
    "statement": "Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by $2$ but the number itself is not divisible by $2$. For example, $13$, $1227$, $185217$ are ebne numbers, while $12$, $2$, $177013$, $265918$ are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.\n\nYou are given a non-negative integer $s$, consisting of $n$ digits. You can delete some digits (they are \\textbf{not} necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between $0$ (do not delete any digits at all) and $n-1$.\n\nFor example, if you are given $s=$222373204424185217171912 then one of possible ways to make it ebne is: {\\textbf{\\sout{2}}22373\\textbf{\\sout{20}}442\\textbf{\\sout{4}}18521717191\\textbf{\\sout{2}}} $\\rightarrow$ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to $70$ and is divisible by $2$, but number itself is not divisible by $2$: it means that the resulting number is ebne.\n\nFind \\textbf{any} resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.",
    "tutorial": "If the number of odd digits is smaller than or equal to $1$, it is impossible to create an ebne number. Otherwise, we can output any 2 odd digits of the number (in correct order of course).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        int n; cin >> n;\n        string s; cin >> s;\n        int odd = 0;\n        for (char c : s) if ((c - '0') & 1) odd++;\n        if (odd <= 1) { cout << \"-1\\n\"; continue; }\n        int cnt = 0;\n        for (char c : s) {\n            if ((c - '0') & 1) { cout << c; cnt++; }\n            if (cnt == 2) break;\n        }\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1291",
    "index": "B",
    "title": "Array Sharpening",
    "statement": "You're given an array $a_1, \\ldots, a_n$ of $n$ non-negative integers.\n\nLet's call it sharpened if and only if there exists an integer $1 \\le k \\le n$ such that $a_1 < a_2 < \\ldots < a_k$ and $a_k > a_{k+1} > \\ldots > a_n$. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:\n\n- The arrays $[4]$, $[0, 1]$, $[12, 10, 8]$ and $[3, 11, 15, 9, 7, 4]$ are sharpened;\n- The arrays $[2, 8, 2, 8, 6, 5]$, $[0, 1, 1, 0]$ and $[2, 5, 6, 9, 8, 8]$ are \\textbf{not} sharpened.\n\nYou can do the following operation as many times as you want: choose any \\textbf{strictly positive} element of the array, and decrease it by one. Formally, you can choose any $i$ ($1 \\le i \\le n$) such that $a_i>0$ and assign $a_i := a_i - 1$.\n\nTell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.",
    "tutorial": "How to know if we can make the prefix $[1 ; k]$ strictly increasing? We just have to consider the following simple greedy solution: take down values to $0, 1, \\ldots, k-1$ (minimal possible values). It's possible if and only if $a_i \\ge i-1$ holds in the whole prefix. Similarly, the suffix $[k ; n]$ can be made strictly decreasing if and only if $a_i \\ge n-i$ holds in the whole suffix. Using these simple facts, we can compute the longest prefix we can make strictly increasing, and the longest suffix we can make strictly decreasing in $O(n)$. Then, we just have to check that their intersection is non-empty.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    ios::sync_with_stdio(false); cin.tie(0);\n\n    int nbTests; cin >> nbTests;\n    while (nbTests--) {\n\t    int nbElem; cin >> nbElem;\n\t    vector<int> tab(nbElem);\n\n\t    for (int i = 0; i < nbElem; ++i)\n\t\t    cin >> tab[i];\n\n\t    int prefixEnd = -1, suffixEnd = nbElem;\n\n\t    for (int i = 0; i < nbElem; ++i) {\n\t\t    if (tab[i] < i) break;\n\t\t    prefixEnd = i;\n\t    }\n\t    for (int i = nbElem-1; i >= 0; --i) {\n\t\t    if (tab[i] < (nbElem-1)-i) break;\n\t\t    suffixEnd = i;\n\t    }\n\n\t    if (suffixEnd <= prefixEnd) // Non-empty intersection\n\t\t    cout << \"Yes\\n\";\n\t    else\n\t\t    cout << \"No\\n\";\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1292",
    "index": "A",
    "title": "NEKO's Maze Game",
    "statement": "\\begin{quote}\n3R2 as DJ Mashiro - Happiness Breeze\n\\end{quote}\n\n\\begin{quote}\nIce - DJ Mashiro is dead or alive\n\\end{quote}\n\nNEKO#ΦωΦ has just got a new maze game on her PC!\n\nThe game's main puzzle is a maze, in the forms of a $2 \\times n$ rectangle grid. NEKO's task is to lead a Nekomimi girl from cell $(1, 1)$ to the gate at $(2, n)$ and escape the maze. The girl can only move between cells sharing a common side.\n\nHowever, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.\n\nAfter hours of streaming, NEKO finally figured out there are only $q$ such moments: the $i$-th moment toggles the state of cell $(r_i, c_i)$ (either from ground to lava or vice versa).\n\nKnowing this, NEKO wonders, after each of the $q$ moments, whether it is still possible to move from cell $(1, 1)$ to cell $(2, n)$ without going through any lava cells.\n\nAlthough NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?",
    "tutorial": "The main observation is that, it is possible to travel from $(1, 1)$ to $(2, n)$ if and only if there exist no pair of forbidden cell $(1, a)$ and $(2, b)$ such that $|a - b| \\le 1$. Therefore, to answer the query quickly, for every $d$ from $-1$ to $1$, one should keep track of the number of pair $(a, b)$ such that: $(1, a)$ and $(2, b)$ are both forbidden. $a - b = d$. One of the methods to do this is: after a cell $(x, y)$ has been swapped, check for all cells $(3-x, y-1)$, $(3-x, y)$, $(3-x, y+1)$ and update the number of pairs based on the status of those cells and new status of $(x, y)$. Since $n \\le 10^5$, the status of all cells can be easily kept in a 2D boolean array, and accessed in $\\mathcal{O}(1)$ time complexity. Total complexity: $\\mathcal{O}(n + q)$. Video by Errichto: https://www.youtube.com/watch?v=mhrvlor1qH0",
    "code": "T = 1\nfor test_no in range(T):\n\tn, q = map(int, input().split())\n\tlava = [[0 for j in range(n)] for i in range(2)]\n\n\tblockedPair = 0\n\twhile q > 0:\n\t\tq -= 1\n\t\tx, y = map(lambda s: int(s)-1, input().split())\n\t\tdelta = +1 if lava[x][y] == 0 else -1\n\n\t\tlava[x][y] = 1 - lava[x][y]\n\t\tfor dy in range(-1, 2):\n\t\t\tif y + dy >= 0 and y + dy < n and lava[1-x][y+dy] == 1:\n\t\t\t\tblockedPair += delta\n\t\t\n\t\tif blockedPair == 0: print('Yes')\n\t\telse: print('No')",
    "tags": [
      "data structures",
      "dsu",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1292",
    "index": "B",
    "title": "Aroma's Search",
    "statement": "\\begin{quote}\nTHE SxPLAY & KIVΛ - 漂流\n\\end{quote}\n\n\\begin{quote}\nKIVΛ & Nikki Simmons - Perspectives\n\\end{quote}\n\nWith a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.\n\nThe space can be considered a 2D plane, with an infinite number of data nodes, indexed from $0$, with their coordinates defined as follows:\n\n- The coordinates of the $0$-th node is $(x_0, y_0)$\n- For $i > 0$, the coordinates of $i$-th node is $(a_x \\cdot x_{i-1} + b_x, a_y \\cdot y_{i-1} + b_y)$\n\nInitially Aroma stands at the point $(x_s, y_s)$. She can stay in OS space for at most $t$ seconds, because after this time she has to warp back to the real world. She \\textbf{doesn't} need to return to the entry point $(x_s, y_s)$ to warp home.\n\nWhile within the OS space, Aroma can do the following actions:\n\n- From the point $(x, y)$, Aroma can move to one of the following points: $(x-1, y)$, $(x+1, y)$, $(x, y-1)$ or $(x, y+1)$. This action requires $1$ second.\n- If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs $0$ seconds. Of course, each data node can be collected at most once.\n\nAroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within $t$ seconds?",
    "tutorial": "First, keep a list of \"important\" nodes (nodes that are reachable from the starting point with $t$ seconds), and denote this list $[(x_1, y_1), (x_2, y_2), \\ldots, (x_k, y_k)]$. Since $a_x, a_y \\geq 2$, there are no more than $\\log_2(t)$ important nodes (in other words, $k \\leq \\log_2(t))$. In an optimal route, we must first reach a data node in fastest time possible. Suppose that we reach node $z$ first, and we now have $t'$ seconds left. Let's denote $d(i, j)$ the time required to travel from the $i$-th node to the $j$-th node. $d(i, j)$ is also the Manhattan distance between the $i$-th and the $j$-th node - in other words, $d(i, j) = |x_j - x_i| + |y_j - y_i|$. Since $x_i \\geq x_{i-1}$ and $y_i \\geq y_{i-1}$, we have $d(u, v) + d(v, w) = d(u, w)$ for all $1 \\leq u < v < w \\leq k$. Therefore, if we consider all the nodes to stay in a line in such a way that $x_i = x_{i-1} + d(i-1, i)$, the problem is reduced to the following problem: To solve the above problem, one should notice that it is optimal to collect nodes in a continuous segment. Suppose that we collect all nodes from the $l$-th to $r$-th (for some $l \\leq s \\leq r$). An optimal route is one of the two below: Go from $z$ to $r$ and then go to $l$. The time required for this route is $d(r, z) + d(r, l)$. Go from $z$ to $l$ and then go to $r$. The time required for this route is $d(z, l) + d(r, l)$. Therefore, the minimum amount of energy required to collect all the nodes from $l$-th to $r$-th is $d(r, l) + \\min(d(z, l), d(r, z))$. Since $k$ is small, one can brute-force through all triple of $(l, z, r)$ such that $1 \\leq l \\leq z \\leq r \\leq k$ and check if $t$ seconds are enough to go to $i$-th node and then collect all the nodes from $l$-th to $r$-th or not. The time complexity for that approach is $\\mathcal{O}(\\log_2(t)^3)$. However, we can notice that it's always the most optimal to choose $z$ as either $l$ or $r$, for a few reasons: As the aforementioned formula, either $d(z, l)$ or $d(r, z)$ will be counted twice (one there, and one within $d(r, l)$, so having it reduced to $0$ nullifies the exceeded step. The distance from $(x_z, y_z)$ to $(x_s, y_s)$ does not break the minimal properties of the endpoint(s) regardless of $(x_s, y_s)$'s position. We can prove it by considering all possible relative positions of $(x_s, y_s)$ over the segment (we'll consider the $x$-coordinates only, $y$-coordinates will have the same properties, without loss of generality): If $x_s \\le x_l$, the distance is minimal at $z = l$. If $x_r \\le x_s$, the distance is minimal at $z = r$. If $x_l \\le x_s \\le x_r$, the travelling time in $x$-coordinates is $d(s, z) + d(r, l) + \\min(d(z, l), d(r, z))$. One can see that $d(s, z) + \\min(d(z, l), d(r, z)) = \\min(d(s, l), d(s, r))$, therefore any $z$ (including the endpoints, of course) is equally optimal. Proof for the above formula is trivial. If $x_s \\le x_l$, the distance is minimal at $z = l$. If $x_r \\le x_s$, the distance is minimal at $z = r$. If $x_l \\le x_s \\le x_r$, the travelling time in $x$-coordinates is $d(s, z) + d(r, l) + \\min(d(z, l), d(r, z))$. One can see that $d(s, z) + \\min(d(z, l), d(r, z)) = \\min(d(s, l), d(s, r))$, therefore any $z$ (including the endpoints, of course) is equally optimal. Proof for the above formula is trivial. The optimal solution's time complexity is $\\mathcal{O}(\\log_2(t)^2)$.",
    "code": "T = 1\nfor test_no in range(T):\n\tx0, y0, ax, ay, bx, by = map(int, input().split())\n\txs, ys, t = map(int, input().split())\n\n\tLIMIT = 2 ** 62 - 1\n\tx, y = [x0], [y0]\n\twhile ((LIMIT - bx) / ax >= x[-1] and (LIMIT - by) / ay >= y[-1]):\n\t\tx.append(ax * x[-1] + bx)\n\t\ty.append(ay * y[-1] + by)\n\t\n\tn = len(x)\n\tans = 0\n\tfor i in range(n):\n\t\tfor j in range(i, n):\n\t\t\tlength = x[j] - x[i] + y[j] - y[i]\n\t\t\tdist2Left = abs(xs - x[i]) + abs(ys - y[i])\n\t\t\tdist2Right = abs(xs - x[j]) + abs(ys - y[j])\n\t\t\tif (length <= t - dist2Left or length <= t - dist2Right): ans = max(ans, j-i+1)\n\t\n\tprint(ans)",
    "tags": [
      "brute force",
      "constructive algorithms",
      "geometry",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1292",
    "index": "C",
    "title": "Xenon's Attack on the Gangs",
    "statement": "\\begin{quote}\nINSPION FullBand Master - INSPION\n\\end{quote}\n\n\\begin{quote}\nINSPION - IOLITE-SUNSTONE\n\\end{quote}\n\nOn another floor of the A.R.C. Markland-N, the young man Simon \"Xenon\" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker \"X\" instinct and fight against the gangs of the cyber world.\n\nHis target is a network of $n$ small gangs. This network contains exactly $n - 1$ direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.\n\nBy mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from $0$ to $n - 2$ such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass $S$ password layers, with $S$ being defined by the following formula:\n\n$$S = \\sum_{1 \\leq u < v \\leq n} mex(u, v)$$\n\nHere, $mex(u, v)$ denotes the smallest non-negative integer that does not appear on any link on the unique simple path from gang $u$ to gang $v$.\n\nXenon doesn't know the way the integers are assigned, but it's not a problem. He decides to let his AI's instances try all the passwords on his behalf, but before that, he needs to know the maximum possible value of $S$, so that the AIs can be deployed efficiently.\n\nNow, Xenon is out to write the AI scripts, and he is expected to finish them in two hours. Can you find the maximum possible $S$ before he returns?",
    "tutorial": "The first observation is that, the formula can be rewritten as: $S = \\sum_{1 \\leq u < v \\leq n} mex(u, v) = \\sum_{1 \\leq x \\leq n} \\left( \\sum_{mex(u, v) = x} x \\right) = \\sum_{1 \\leq x \\leq n} \\left( \\sum_{mex(u, v) \\geq x} 1 \\right) = \\sum_{1 \\leq x \\leq n} f(x)$ Where $f(x)$ is number of pairs $(u, v)$ such that $1 \\leq u < v \\leq n$ and $mex(u, v) \\geq x$ (in other word, the path from $u$ to $v$ contains all numbers from $0$ to $x-1$). Consider the process of placing numbers in order from $0$ to $n-1$ (first place number $0$, then place number $1$, etc.) on edges of the tree. Suppose that the placement for all numbers from $0$ to $x-1$ are fixed, and now we need to place number $x$. To maximize $S$, we should try to place $x$ in a way that there exists a path contain all numbers from $0$ to $x$ (if this is possible). In other word, in the optimal solution, there will be a path connecting two leaf vertices that contain all numbers from $0$ to $l - 1$ (where $l$ is the number of vertices in that path). The placement of numbers from $l$ to $n-2$ does not matter, since it will not affect the result. Now, suppose that the location of such path is fixed, and its length is $l$. Let $a$ the sequence of number on edges on the path from $u$ to $v$. One can show that, in other to archive maximum $S$, $a$ must be a 'valley' sequence (there exist some position $p$ such that $a_1 > a_2 > \\ldots > a_p < \\ldots < a_{l-1} < a_l$. All the observation above leads to the following dynamic programming solution: Let $dp[u][v]$ the maximum value of $\\sum_{1 \\leq x \\leq l} f(x)$ if all number from $0$ to $l-1$ are written on the edges on the path from $u$ to $v$ (with $l$ denote the length of that path). We also define: $par(r, u)$: the parent of vertex $u$ if we root the tree at vertex $r$. $sub(r, u)$: the number of vertices in the subtree of vertex $u$ if we root the tree at vertex $r$. The figure below demonstrate $par(u, v)$ and $par(v, u)$ for two vertices $u$ and $v$ (in the figure, $p_{u,v}$ is $par(u, v)$ and $p_{v,u}$ is $par(v, u)$). To calculate $dp[u][v]$, there are two cases: Putting number $l$ on the edge $(u, par(v, u))$. In this case: $\\sum_{1 \\leq x \\leq l} f(x) = f(l) + \\sum_{1 \\leq x \\leq l-1} f(x) = sub(u, v) \\times sub(v, u) + dp[par(v, u)][v]$ $\\sum_{1 \\leq x \\leq l} f(x) = f(l) + \\sum_{1 \\leq x \\leq l-1} f(x) = sub(u, v) \\times sub(v, u) + dp[par(v, u)][v]$ Putting number $l$ on the edge $(v, par(u, v))$. Similarly, $\\sum_{1 \\leq x \\leq l} f(x) = sub(u, v) \\times sub(v, u) + dp[u][par(u, v)]$ The final formula to calculate $dp[u][v]$ is: $dp[u][v] = sub(u, v) \\times sub(v, u) + \\max(dp[par(v, u)][v], dp[u][par(u, v)])$ The formula can be calculated in $O(1)$ if all the values of $par(r, u)$ and $sub(r, u)$ are calculated (we can preprocess to calculate these value in $\\mathcal{O}(n^2)$. by doing performing DFS once from each vertex). Therefore, the overall complexity for this algorithm is $\\mathcal{O}(n^2)$.",
    "code": "import sys\n \n# Read input and build the graph\ninp = [int(x) for x in sys.stdin.buffer.read().split()]; ii = 0\nn = inp[ii]; ii += 1\ncoupl = [[] for _ in range(n)]\nfor _ in range(n - 1):\n    u = inp[ii] - 1; ii += 1\n    v = inp[ii] - 1; ii += 1\n    coupl[u].append(v)\n    coupl[v].append(u)\n \n# Relabel to speed up n^2 operations later on\nbfs = [0]\nfound = [0]*n\nfound[0] = 1\nfor node in bfs:\n    for nei in coupl[node]:\n        if not found[nei]:\n            found[nei] = 1\n            bfs.append(nei)\n \nnew_label = [0]*n\nfor i in range(n):\n    new_label[bfs[i]] = i\n \ncoupl = [coupl[i] for i in bfs]\nfor c in coupl:\n    c[:] = [new_label[x] for x in c]\n \n##### DP using multisource bfs\n \nDP = [0] * (n * n)\nsize = [1] * (n * n)\nP = [-1] * (n * n)\n \n# Create the bfs ordering\nbfs = [root * n + root for root in range(n)]\nfor ind in bfs:\n    P[ind] = ind\n \nfor ind in bfs:\n    node, root = divmod(ind, n)\n    for nei in coupl[node]:\n        ind2 = nei * n + root\n        if P[ind2] == -1:\n            bfs.append(ind2)\n            P[ind2] = ind\n \ndel bfs[:n]\n \n# Do the DP\nfor ind in reversed(bfs):\n    node, root = divmod(ind, n)\n    ind2 = root * n + node\n    pind = P[ind]\n    parent = pind//n\n    \n    # Update size of (root, parent)\n    size[pind] += size[ind]\n \n    # Update DP value of (root, parent)\n    DP[pind] = max(DP[pind], max(DP[ind], DP[ind2]) + size[ind] * size[ind2])\nprint(max(DP[root * n + root] for root in range(n)))",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1292",
    "index": "D",
    "title": "Chaotic V.",
    "statement": "\\begin{quote}\nÆsir - CHAOS\n\\end{quote}\n\n\\begin{quote}\nÆsir - V.\n\\end{quote}\n\n\"Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.\n\nThe time right now...... 00:01:12......\n\nIt's time.\"\n\nThe emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.\n\nThe system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($1, 2, 3, \\ldots$). The node with a number $x$ ($x > 1$), is directly connected with a node with number $\\frac{x}{f(x)}$, with $f(x)$ being the lowest prime divisor of $x$.\n\nVanessa's mind is divided into $n$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $i$-th fragment is now located at the node with a number $k_i!$ (a factorial of $k_i$).\n\nTo maximize the chance of successful awakening, Ivy decides to place the samples in a node $P$, so that the total length of paths from each fragment to $P$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $P$ needs to be counted multiple times.\n\nIn the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.\n\nBut for a mere human like you, is this still possible?\n\nFor simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $P$.",
    "tutorial": "First of all, one can see that the network is a tree rooted at vertex $1$, thus for each pair of vertices in it there can only be one simple path. Also, the assembly node $P$ must be on at least one simple path of a fragment to the root (proof by contradiction, explicit solution is trivial). Let's start with $P$ being node $1$. From here, moving down to any branch will increase $1$ for each element not being in that branch and decrease $1$ for each element being in, thus we'll only move down to the branch having the most elements until the decreasing cannot outmatch the increasing (in other words, the number of fragments in a branch must be more than half for that branch to be reached). Given the criteria of the graph, we can see that: two nodes are in the same branch from the root if having the same one largest factor from the prime factorization, they are in the same branch from a depth-1-node if having the same two largest factors, ..., in the same branch from a depth-$k$-node if having the same $k+1$ largest factors. Keep in mind that here the largest factors can be the duplicated, i.e. in the case of $576 = 2^6 \\cdot 3^2$, the two largest factors are $3$ and $3$, and the three largest factors are $3$, $3$ and $2$. The process will now become factorizing the numbers, and then, cycle by cycle, pop the current largest factor of each number and group them, find out the group (branch) with most occurences and either move on (if the total sum can be lowered) or stop the process. Since all of these are factorials, the factorizing can be done with a bottom-up dynamic programming fashion. Also, as $k \\le 5000$ and $n \\le 10^6$, consider grouping duplicated elements to reduce calculating complexity. Both factorization and processing has the worst-case complexity of $\\mathcal{O}(MAXK^2 \\cdot f(MAXK))$, with $k \\cdot f(k)$ being the estimated quantity of prime divisors of $k!$. It's proven that $f(k) = M + \\ln \\ln k$, with $M$ being the Meissel-Mertens constant. The proof of this formula is based on the fact this number is calculated through the sum of the reciprocals of the primes.",
    "code": "T = 1\nfor test_no in range(T):\n\tMAXK = 5000\n\tn = int(input())\n\tcnt = [0] * (MAXK + 1)\n\tprimeExponential = [[0 for j in range(MAXK + 1)] for i in range(MAXK + 1)]\n\n\tline, num = (input() + ' '), 0\n\tfor c in line:\n\t\tif c != ' ': num = num * 10 + (ord(c) - 48)\n\t\telse:\n\t\t\tcnt[num] += 1\n\t\t\tnum = 0\n\n\tfor i in range(2, MAXK + 1):\n\t\tfor j in range(0, MAXK + 1): primeExponential[i][j] += primeExponential[i-1][j]\n\t\ttmp, x = i, 2\n\t\twhile x * x <= tmp:\n\t\t\twhile tmp % x == 0:\n\t\t\t\tprimeExponential[i][x] += 1\n\t\t\t\ttmp //= x\n\t\t\tx += 1\n\t\tif tmp > 1: primeExponential[i][tmp] += 1\n\n\tbestPD = [1] * (MAXK + 1)\n\tans, cur = 0, 0\n\n\tfor i in range(1, MAXK + 1):\n\t\tif cnt[i] == 0: continue\n\t\tfor j in range(1, MAXK + 1):\n\t\t\tans += primeExponential[i][j] * cnt[i]\n\t\t\tcur += primeExponential[i][j] * cnt[i]\n\t\t\tif primeExponential[i][j]: bestPD[i] = j\n\n\tfrequency = [0] * (MAXK + 1)\n\twhile max(bestPD) > 1:\n\t\tfor i in range(MAXK + 1): frequency[i] = 0\n\t\tfor i in range(MAXK + 1): frequency[bestPD[i]] += cnt[i]\n\n\t\tbestGroup = max(frequency)\n\t\tbestPrime = frequency.index(bestGroup)\n\t\tif bestGroup * 2 <= n: break\n\t\tif bestPrime == 1: break\n\t\tcur -= bestGroup\n\t\tcur += (n - bestGroup); ans = min(ans, cur)\n\n\t\tfor i in range(MAXK + 1):\n\t\t\tif bestPD[i] != bestPrime: bestPD[i] = 1\n\t\t\tif bestPD[i] == 1: continue\n\t\t\tprimeExponential[i][bestPD[i]] -= 1\n\t\t\twhile bestPD[i] > 1 and primeExponential[i][bestPD[i]] == 0: bestPD[i] -= 1\n\n\tprint(ans)",
    "tags": [
      "dp",
      "graphs",
      "greedy",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1292",
    "index": "E",
    "title": "Rin and The Unknown Flower",
    "statement": "\\begin{quote}\nMisoilePunch♪ - 彩\n\\end{quote}\n\nThis is an interactive problem!\n\nOn a normal day at the hidden office in A.R.C. Markland-N, Rin received an artifact, given to her by the exploration captain Sagar.\n\nAfter much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.\n\nThe chemical structure of this flower can be represented as a string $p$. From the unencrypted papers included, Rin already knows the length $n$ of that string, and she can also conclude that the string contains at most three distinct letters: \"C\" (as in Carbon), \"H\" (as in Hydrogen), and \"O\" (as in Oxygen).\n\nAt each moment, Rin can input a string $s$ of an arbitrary length into the artifact's terminal, and it will return every starting position of $s$ as a substring of $p$.\n\nHowever, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific:\n\n- The artifact only contains $\\frac{7}{5}$ units of energy.\n- For each time Rin inputs a string $s$ of length $t$, the artifact consumes $\\frac{1}{t^2}$ units of energy.\n- If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever.\n\nSince the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?",
    "tutorial": "To be fair, this is a complicated decision tree problem. I recommend instead of heading straight to read the main solutions for this, try to spend some time and come up with at least 2 solutions for the case when the query limit is 5/3 first. <spoilers> There are many solutions when limit = 5/3, and I'll point 2 of them out. The difference between the two solutions is how you approach the string and build a decision tree out of those queries: 1. The easiest to come up with: disclose every joint of the string (which is equivalent to find every position $i$ that S[i]==S[i+1]). All remaining letters can be filled up with the nearest disclosed letter to it. This can be done by asking 6 queries: \"CH\", \"HC\", \"CO\", \"OC\", \"OH\", \"HO\". If none of the letters is disclosed, then all of the letters are the same. You can disclose all of them by asking 2 more queries of length n and determine what letter is it. 2. The most natural solution (in my opinion): The idea of this is to disclose at least one letter of the string, to disclose the rest with at most one string of length $2$ to $n$ each. We could do this by simply asking \"C\". This could go either way: If a 'C' is disclosed at a position $i$, we can disclose the position $i+1$ with one query of length $2$, $i+2$ with one query of length $3$, ... and so on. From there, undisclose position $i-1$ with a query of length $n-i+1$, $i-2$ with a query of length $n-i+2$, ... and so on. If no letter is disclosed, the problem narrows down to solve with a binary string and total cost of $2/3$. There are multiple ways to tackle this so I won't spend any more time to explain this case. The key here is to come up with a strategy that works in all branches of the decision tree. And to do that, we must find a good starting query/set of queries to begin with. In the two strategies above, number 1 is too brutal, and number 2 is too naive. But my main solution contains the essences which can be seen in both solutions. The main idea is to find a set of queries to begin with like strat #2 but would give us more hints and cost us less when things go the other way. We'll start by asking queries with \"CH\", \"CO\", \"HC\", \"HO\", which in total have cost of $1$. That way, the non-disclosed parts can be one of those: Consecutive similar characters. A joint starting with \"O\". Supposed that after four above queries and no occurrences were found at all, the string can now be only in one of those kinds: An entire string constructed by a single character. A string of form \"OO...XX\", with \"X\" being either \"C\" or \"H\". In other words, the string is constructed by $n_0$ characters \"O\", followed by $n_1$ characters \"X\" ($n_0 + n_1 = n$). Proof for this is trivial. We'll find the trace of large chunks of \"C\" or \"H\" (cannot find every trace since the cost limit is very tight here, the minimum length allowed should only be $3$). To do this, we'll ask queries \"CCC\" and \"HHH\" sequentially. If any of the two queries return occurrence(s), that means all occurrences of \"C\" or \"H\" has been revealed (and also guaranteed to completely inherit the right side of the string), any undisclosed characters on the left will obviously be \"O\". From here, we can conclude and return the original string. However, if both queries return nothing, this means either the string contains only \"O\" characters or there are at most $2$ rightmost characters being \"C\" or \"H\". Given this, we ought to find the chunk of \"O\" by asking query \"OOO\" (similar logic to the former step). If it returns occurrence(s) and there are still undisclosed characters, we'll need another query of length $n$ to finalize: replacing all of the undisclosed positions to \"C\" then ask a query with that string, if it returns occurrence then \"C\" is for the missing characters, otherwise \"H\" is. This method works because there will always be one chunk with length at least $3$ (on either end of the string), except two cases: \"OOCC\" and \"OOHH\". You will get to this if all three above queries failed to return anything. However, since this is a matter of picking one from two, a single query of either string will work: the original string is the asked string if occurrence found, otherwise the other. This is also the worst case in this branch. Total cost would be $1 + 3 \\cdot \\frac{1}{9} + \\frac{1}{16} = 1.3958(3)$ - very close to the limit. Back to the case that some occurrence(s) are found when after asking the $4$ joint queries. The logic now is pretty similar to strat #2 mentioned above however due to the more varied undisclosed patterns, we'll need to take some extra caution. First of all, we'll start at the leftmost revealed segment, and disclose any hidden characters to the left of it. It's easy to see that the leftmost revealed character can never be \"O\", and since the leftmost hidden segment always come in one of two forms similar to the no-occurrence case branch above, you can always reveal the nearest character by assuming it is the same as the current leftmost revealed character and use it as a query to ask. If the assumption is incorrect, then it and any remaining hidden letters to the left of it will be \"O\". Now that we have a fully revealed prefix, we'll extend it by revealing letters to the right. For simplicity, let's split into two cases: one when there are revealed letter(s) not within our current prefix, one when there is none. If such revealed letters are found, consider the one being closest to our prefix. We can see that the hidden gap between our prefix and it can only be produced by some (probably none) characters being the same as our rightmost character in the prefix, followed by some (probably none) characters being the same as our leftmost character outside of the prefix. Thus, we can simply assume the next hidden character is the same as our rightmost in-prefix character, then ask the query. If the assumption is incorrect, fill it and all the remaining hidden characters in that segment with the other one. If there are none, then the last hidden segment is again, similar to the no-occurrence case branch. However, we have a significant clue this time: our rightmost in-prefix character. If it is not \"O\", we can quickly fill all the hidden positions with it, otherwise, we'll keep asking query again, assuming the next hidden character is still \"O\": if incorrect, take another query to ask if either it is \"C\" or \"H\", and then fill it and all the other hidden ones. ** Example interaction: The string is \"COHHHH...\" ($n = 50$, in other words the string is construct by appending $48$ character \"H\" to the string \"CO\"). => 50 (Finding joints not starting at O) ? CH => 0 ? CO => 1 1 ? HC => 0 ? HO => 0 (Now, the string can be deduced as \"CO????...\") ? COO => 0 (Assuming that the third character is still \"O\", sadly it isn't.) ? COC => 0 (Assuming that the third character is still \"C\", and it isn't either.) (By now we can deduce the string to be \"COHHHH....\", since the fourth character and beyond cannot be anything other than \"H\" (otherwise it would have raised a signal in the joints queries)). ! COHHHH... => 1 ** End of example. The maximum cost for this will be ($i = 3$ because starting from a joint means we have at least $2$ found characters, incremented by $1$ by the character we're about to guess): $\\displaystyle \\max_{4 \\le n \\le 50} \\left( 1 + \\sum_{i = 3}^{n} \\frac{1}{i^2} + \\frac{1}{n^2} \\right)$ With $n$ going to positive infinity, the limit of this function will be $\\frac{2 \\pi^2 - 3}{12} < 1.4$, therefore this solution still works. </spoilers> Big credits to Sooke for making this problem more interesting by pointing out a way to reduce the initial limit (5/3) and make this problem much less trivial.",
    "code": "import sys\nn, L, minID = None, None, None\ns = []\n\ndef fill(id, c):\n\tglobal n, L, s, minID\n\tL -= (s[id] == 'L')\n\ts = s[0:id] + c + s[id+1:]\n\tminID = min(minID, id)\n\ndef query(cmd, str):\n\tglobal n, L, s, minID\n\tprint(cmd, ''.join(str))\n\tprint(cmd, ''.join(str), file=sys.stderr)\n\tsys.stdout.flush()\n\tif (cmd == '?'):\n\t\tresult = list(map(int, input().split()))\n\t\tassert(result[0] != -1)\n\t\tfor z in result[1:]:\n\t\t\tz -= 1\n\t\t\tfor i in range(len(str)):\n\t\t\t\tassert(s[z+i] == 'L' or s[z+i] == str[i])\n\t\t\t\tfill(z+i, str[i])\n\telif (cmd == '!'):\n\t\tcorrect = int(input())\n\t\tassert(correct == 1)\n\nT = int(input())\nfor test_no in range(T):\n\tn = int(input())\n\tL, minID = n, n\n\ts = 'L' * n\n\n\tquery('?', \"CH\")\n\tquery('?', \"CO\")\n\tquery('?', \"HC\")\n\tquery('?', \"HO\")\n\tif (L == n):\n\t\t# the string exists in form O...OX...X, with X=C or X=H\n\t\t# or it's completely mono-character\n\t\tquery('?', \"CCC\")\n\t\tif (minID < n): \n\t\t\tfor x in range(minID-1, -1, -1): fill(x, 'O')\n\t\telse:\n\t\t\tquery('?', \"HHH\")\n\t\t\tif (minID < n):\n\t\t\t\tfor x in range(minID-1, -1, -1): fill(x, 'O')\n\t\t\telse:\n\t\t\t\tquery('?', \"OOO\")\n\t\t\t\tif (minID == n):\n\t\t\t\t\t# obviously n=4\n\t\t\t\t\tquery('?', \"OOCC\")\n\t\t\t\t\tif (minID == n):\n\t\t\t\t\t\tfill(0, 'O')\n\t\t\t\t\t\tfill(1, 'O')\n\t\t\t\t\t\tfill(2, 'H')\n\t\t\t\t\t\tfill(3, 'H')\n\t\t\t\t\n\t\t\t\tif (s[n-1] == 'L'):\n\t\t\t\t\tt = s[0:n-1] + 'C'\n\t\t\t\t\tif (t[n-2] == 'L'): t = t[0:n-2] + 'C' + t[n-1:]\n\t\t\t\t\tquery('?', t)\n\t\t\t\t\tif (s[n-1] == 'L'):\n\t\t\t\t\t\tfill(n-1, 'H')\n\t\t\t\t\t\tif (s[n-2] == 'L'): fill(n-2, 'H')\n\telse:\n\t\tmaxID = minID\n\t\twhile (maxID < n-1 and s[maxID+1] != 'L'): maxID += 1\n\t\tfor i in range(minID-1, -1, -1):\n\t\t\tquery('?', s[i+1:i+2] + s[minID:maxID+1])\n\t\t\tif (minID != i):\n\t\t\t\tfor x in range(i+1): fill(x, 'O')\n\t\t\t\tbreak\n\t\t\n\t\tnextFilled = None\n\t\ti = maxID + 1\n\t\twhile i < n:\n\t\t\tif (s[i] != 'L'):\n\t\t\t\ti += 1\n\t\t\t\tcontinue\n\t\t\tnextFilled = i\n\t\t\twhile (nextFilled < n and s[nextFilled] == 'L'): nextFilled += 1\n\t\t\tquery('?', s[0:i] + s[i-1])\n\t\t\tif (s[i] == 'L'):\n\t\t\t\tif (s[i-1] != 'O'): fill(i, 'O')\n\t\t\t\telse:\n\t\t\t\t\tif (nextFilled == n):\n\t\t\t\t\t\tquery('?', s[0:i] + 'C')\n\t\t\t\t\t\tif (s[i] == 'L'): fill(i, 'H')\n\t\t\t\t\t\tfor x in range(i+1, nextFilled): fill(x, s[i])\n\t\t\t\t\telse:\n\t\t\t\t\t\tfor x in range(i, nextFilled): fill(x, s[nextFilled])\n\t\t\t\t\ti = nextFilled - 1\n\t\t\ti += 1\n\tquery('!', s)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "interactive",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1292",
    "index": "F",
    "title": "Nora's Toy Boxes",
    "statement": "\\begin{quote}\nSIHanatsuka - EMber\n\\end{quote}\n\n\\begin{quote}\nSIHanatsuka - ATONEMENT\n\\end{quote}\n\nBack in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.\n\nOne day, Nora's adoptive father, Phoenix Wyle, brought Nora $n$ boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.\n\nShe labelled all $n$ boxes with $n$ distinct integers $a_1, a_2, \\ldots, a_n$ and asked ROBO to do the following action several (possibly zero) times:\n\n- Pick three distinct indices $i$, $j$ and $k$, such that $a_i \\mid a_j$ and $a_i \\mid a_k$. In other words, $a_i$ divides both $a_j$ and $a_k$, that is $a_j \\bmod a_i = 0$, $a_k \\bmod a_i = 0$.\n- After choosing, Nora will give the $k$-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty.\n- After doing so, the box $k$ becomes unavailable for any further actions.\n\nBeing amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the \\textbf{largest} amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.\n\nSince ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?\n\nAs the number of such piles can be very large, you should print the answer modulo $10^9 + 7$.",
    "tutorial": "We consider a directed graph $G$, where we draw an edge from vertex $i$ to vertex $j$ if $a_i \\mid a_j$. Notice that $G$ is a DAG and is transitive (if $(u, v), (v, w) \\in G$ then $(u, w) \\in G$). For each vertex, we consider two states: \"on\" (not deleted) and \"off\" (deleted). An edge is \"on\" if both end vertices are not deleted, and \"off\" otherwise. The operation is equivalent to choosing a vertices triple $(u, v, w)$ such that $u$, $v$, $w$ are on and $(u, v), (u, w) \\in G$; then turn off vertex $w$ and append $a_w$ to the end of $b$. We first solve the problem for a weakly connected component $C$ (only choosing vertices triple belong to this component in each operation). Define $S$ the set of all vertices with no incoming edges, and $T$ the set of remaining vertices ($T = C - S$). Obviously, vertices in $S$ can't be turned off. We need to figure out the maximum number of vertices in $T$ we can turn off. We consider the reversed process. Initially, some vertices in $T$ are turned off, and we can turn on a vertex with the following operation: choose a vertices triple $(u, v, w)$ such that $u$, $v$ are on, $w$ is off, and $(u, v), (u, w) \\in G$; then turn on $w$ and append $a_w$ to the beginning of $b$. Lemma 1: For each vertex $u \\in T$, there exist a vertex in $S$ that has an outgoing edge to $u$. Proof: Consider a vertex $u \\in T$. If $u$ has no incoming edge from another vertex in $T$, $u$ must has an incoming edge from a vertex in $S$ (if not, $u$ have no incoming edge, which mean $u$ should be in $S$ instead of $T$, contradiction). Otherwise, let $v$ the vertex with minimum $a_v$ among all vertices in $T$ with an outgoing edge to $u$. $v$ has no incoming edge from another vertex in $T$, so there exist a vertex $s \\in S$ that has an outgoing edge to $v$. Since $G$ is transitive and $(v, u), (s, v) \\in G$, $s$ has an outgoing edge to $u$. $\\blacksquare$ Lemma 2: If at least one vertex in $T$ is on, we can turn all other vertices in $T$ on. Proof: Let's $X$ the set of all vertices in $T$ that is currently on, and $Y$ the set of remaining vertices in $T$ ($Y = T - X$). We will prove that, if $X$ is not empty, we can always turn on a vertex in $Y$. If this is true, starting from the state where $X$ contain only one vertex (and $Y$ contain the remaining vertices of $T$), one can repeat turning on a vertex in $Y$ until all vertices in $T$ are on. To prove it, we need to show that there exist a vertex in $S$ that has an outgoing edge to some vertex in $X$ and some vertex in $Y$ (so we can choose the triple of three mentioned vertices to turn on a vertex in $Y$). Consider two cases: Case 1: There exist some edge $(v, w)$ with $v \\in X$ and $w \\in Y$.Let $s$ a vertex in $S$ that has an outgoing edge to $v$. Since $G$ is transitive and $(s, v)$, $(v, w)$ are in $G$, $(s, w)$ are also in $G$. In other word, $s \\in S$ has an outgoing edge to both $v \\in X$ and $w \\in Y$. Let $s$ a vertex in $S$ that has an outgoing edge to $v$. Since $G$ is transitive and $(s, v)$, $(v, w)$ are in $G$, $(s, w)$ are also in $G$. In other word, $s \\in S$ has an outgoing edge to both $v \\in X$ and $w \\in Y$. Case 2: There is no edge from a vertex in $X$ to a vertex in $Y$. In this case, if there exist no vertex in $S$ that has an outgoing edge to some vertex in $X$ and some vertex in $Y$, the component would be divided into two smaller component (one with all vertices in $X$ with their incoming vertices, one with all vertices in $Y$ with their incoming vertices). This contradict the fact that $S$, $X$ and $Y$ are weakly connected. $\\blacksquare$ In this case, if there exist no vertex in $S$ that has an outgoing edge to some vertex in $X$ and some vertex in $Y$, the component would be divided into two smaller component (one with all vertices in $X$ with their incoming vertices, one with all vertices in $Y$ with their incoming vertices). This contradict the fact that $S$, $X$ and $Y$ are weakly connected. $\\blacksquare$ The lemma above give us the maximum length of sequence $B$ we can construct: $|T| - 1$. Now we need to count the number of such sequence $B$. Equivalently, for each vertex $u \\in T$, we need to count the number of orders to turn on all other vertices in $T$ (given that $u$ is initially on and all other vertices in $T$ are initially off). Let $s_1, s_2, \\ldots, s_p$ the vertices in $S$ and $t_1, t_2, \\ldots, t_m$ the vertices in $T$. First, how can we know whether we can turn on a vertex in $T$, without having to consider the states of other vertices in $T$? Lemma 3: When perform the above operation, it is sufficient to consider only all triples $(u, v, w)$ such that $u \\in S$ and $v, w \\in T$. Proof: For a vertex $w$ in $T$ that is off, assume that we can turn on $w$ by choosing a triple $(u, v, w)$ such that $u, v \\in T$. In other to choose the triple, $u$, $v$ must be on and $(u, v), (u, w) \\in G$. Let $s$ the vertex in $S$ that has an outgoing edge to $u$ ($s$ is always on since $s \\in S$). Since the graph is transitive, $s$ also has outgoing edges to $v$ and $w$. Therefore, we can turn on $w$ by choosing the triple $(s, v, w)$ instead. $\\blacksquare$ With the above lemma, it is sufficient to only consider, for each vertex $u \\in S$, whether there is an on outgoing edge from $u$. We can use a bitmask of length $p$ to represent this information, with $x$-th bit equal $1$ if $s_x$ has an on outgoing edge (and equal $0$ otherwise). For each vertex $t_i \\in T$, let $inMask[i]$ the bitmask of length $p$, with $x$-th bit equal $1$ if $s_x$ has an outgoing edge to $t_i$ in $G$. Let $dp[mask][k]$ the number of distinct box piles of length $k$ ROBO can have, with the $x$-th bit of $mask$ equals $1$ if $s_x$ has an on outgoing edge to a vertex in $T$ that is turned on. For a vertex $t_j$ that is currently off, we can turn on $t_j$ if $inMask[j] \\; \\& \\; mask \\neq 0$. There are two cases: Turn on a currently-off vertex $t_j$ in a way that $mask$ is expanded (some bit(s) $0$ turn into bit(s) $1$). To archive this, we must select $t_j$ in such a way that $inMask[j]$ must not be a subset of $mask$, and we can turn on $t_j$ (if a $t_j$ satisfy these two conditions, we know for sure that $t_j$ is currently off). Therefore, for $1 \\le j \\leq m$ such that $inMask[j] \\nsubseteq mask$ and $inMask[j] \\; \\& \\; mask \\neq 0$, we update the following: $dp[mask \\; | \\; inMask[j]][k + 1] = dp[mask \\; | \\; inMask[j]][k + 1] + dp[mask][k]$ $dp[mask \\; | \\; inMask[j]][k + 1] = dp[mask \\; | \\; inMask[j]][k + 1] + dp[mask][k]$ Turn on a currently-off vertex $t_j$ in a way that $mask$ is not expanded. Let $cnt(mask)$ be the number of indices j such that $inMask[j] \\subseteq mask$. We can turn on one of the $cnt(mask) - k$ vertices that is currently off. Therefore, we update the following: $dp[mask][k + 1] = dp[mask][k + 1] + dp[mask][k] * (cnt(mask) - k)$ $dp[mask][k + 1] = dp[mask][k + 1] + dp[mask][k] * (cnt(mask) - k)$ To solve the general case, we can calculate the number of orders for each weakly connected component separately and then combine the result with some combinatorics formula. Complexity: $O(2^r * n^2)$, with $r$ the maximum number of vertices with no incoming vertices (number of vertices in set $S$) among all weakly connected component. We will prove that $r \\leq \\frac{X}{4}$ (where $X$ is the constraint of $n$ and $a_i$), therefore the algorithm fit the given time limit. Proof: For simplicity, assume that $X$ is divisible by $4$. Let's focus only on the weakly connected component $C$ with maximum number of vertices (which will equal $r$). Let's define $S$ and $T$ in the same manner as the above solution. Notice that, for all $x$ from $\\frac{X}{2}$ to $X$, if $x$ in $S$, then $x$ is a separate weakly connected component. Therefore, all numbers in $S$ should range from $1$ to $\\frac{X}{2}$. On another hand, there should be no number in $S$ that divide another one in $S$. In other word, consider the divisibility graph of all integer from $1$ to $\\frac{X}{2}$. Therefore, the size of $S$ cannot exceed the size of the maximum anti-chain (a subset of vertices such that no pair of vertices is connected by an edge) of the graph. The size of the maximum anti-chain of the divisibility graph with vertices from $1$ to $n$ is $\\frac{n}{2}$ (proof below). Therefore, the size of $S$ cannot exceed $\\frac{\\frac{X}{2}}{2} = \\frac{X}{4}$, or $r \\leq \\frac{X}{4}$. $\\blacksquare$ Though, for an anti-chain of the divisibility graph with $\\frac{X}{2}$ vertices, even if we include all the numbers from $\\frac{X}{2} + 1$ to $X$, it may happen that vertices of the anti-chain belong to different weakly connected component. In reality, our brute-force program figure out that in the worst case, $r = 11$ (achieved with $a = [2, 11, 13, \\ldots, 27, 29, 30, 31, \\ldots, 59, 60]$). We still need to prove that, for even $n$, the maximum anti-chain of the divisibility graph with vertices from $1$ to $n$ is $\\frac{n}{2}$. Proof: For any number $x$, let $f(x)$ the number received by continuously divide $x$ by $2$. In other word, let $k$ the maximum value of $i$ such that $x$ is divisible by $2^i$, then $f(x) = \\frac{x}{2^k}$. Notice that, for two number $x$ and $y$, if $f(x) = f(y)$ then $x$ divides $y$ or $y$ divides $x$. For all $x$ from $1$ to $n$, $f(x)$ has at most $\\frac{n}{2}$ different value (all odd number from $1$ to $n-1$). For any subset $s$ of integers from $1$ to $n$, if $s$ has $\\frac{n}{2} + 1$ elements or more, according to Pigeonhole principle, there are two elements in $s$ that have the same value of $f$. One of these two numbers will divide the other, so $s$ is not an anti-chain. $\\blacksquare$",
    "code": "MOD = 1000000007\n\n\ndef isSubset(a, b):\n\treturn (a & b) == a\n\n\ndef isIntersect(a, b):\n\treturn (a & b) != 0\n\n\n# Solve for each weakly connected component (WCC)\ndef cntOrder(s, t):\n\tp = len(s)\n\tm = len(t)\n\n\tinMask = [0 for i in range(m)]\n\n\tfor x in range(p):\n\t\tfor i in range(m):\n\t\t\tif t[i] % s[x] == 0:\n\t\t\t\tinMask[i] |= 1 << x\n\n\tcnt = [0 for mask in range(1<<p)]\n\tfor mask in range(1<<p):\n\t\tfor i in range(m):\n\t\t\tif isSubset(inMask[i], mask):\n\t\t\t\tcnt[mask] += 1\n\n\tdp = [[0 for mask in range(1<<p)] for k in range(m+1)]\n\tfor i in range(m):\n\t\tdp[1][inMask[i]] += 1\n\tfor k in range(m):\n\t\tfor mask in range(1<<p):\n\t\t\tfor i in range(m):\n\t\t\t\tif not isSubset(inMask[i], mask) and isIntersect(inMask[i], mask):\n\t\t\t\t\tdp[k+1][mask | inMask[i]] = (dp[k+1][mask | inMask[i]] + dp[k][mask]) % MOD\n\t\t\tdp[k+1][mask] = (dp[k+1][mask] + dp[k][mask] * (cnt[mask] - k)) % MOD\n\n\treturn dp[m][(1<<p)-1]\n\n\ndef dfs(u):\n\tglobal a, graph, degIn, visited, s, t\n\n\tvisited[u] = True\n\tif degIn[u] == 0:\n\t\ts.append(a[u])\n\telse:\n\t\tt.append(a[u])\n\n\tfor v in graph[u]:\n\t\tif not visited[v]:\n\t\t\tdfs(v)\n\n\ndef main():\n\tglobal a, graph, degIn, visited, s, t\n\n\t# Reading input\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\n\t# Pre-calculate C(n, k)\n\tc = [[0 for j in range(n)] for i in range(n)]\n\tfor i in range(n):\n\t\tc[i][0] = 1\n\t\tfor j in range(1, i+1):\n\t\t\tc[i][j] = (c[i-1][j-1] + c[i-1][j]) % MOD\t\n\n\t# Building divisibility graph\n\tdegIn = [0 for u in range(n)]\n\tgraph = [[] for u in range(n)]\n\tfor u in range(n):\n\t\tfor v in range(n):\n\t\t\tif u != v and a[v] % a[u] == 0:\n\t\t\t\tgraph[u].append(v)\n\t\t\t\tgraph[v].append(u)\n\t\t\t\tdegIn[v] += 1\n\n\t# Solve for each WCC of divisibility graph and combine result\n\tans = 1\n\tcurLen = 0\n\tvisited = [False for u in range(n)]\n\tfor u in range(n):\n\t\tif not visited[u]:\n\t\t\ts = []\n\t\t\tt = []\n\t\t\tdfs(u)\n\n\t\t\tif len(t) > 0:\n\t\t\t\tsz = len(t) - 1\n\t\t\t\tcnt = cntOrder(s, t)\n\n\t\t\t\t# Number of orders for current WCC\n\t\t\t\tans = (ans * cnt) % MOD\n\t\t\t\t# Number of ways to insert <sz> number to array of <curLen> elements\n\t\t\t\tans = (ans * c[curLen + sz][sz]) % MOD\n\t\t\t\tcurLen += sz\t\t\n\n\tprint(ans)\n\nif __name__ == \"__main__\":\n\tmain()",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1293",
    "index": "A",
    "title": "ConneR and the A.R.C. Markland-N",
    "statement": "\\begin{quote}\nSakuzyo - Imprinting\n\\end{quote}\n\nA.R.C. Markland-N is a tall building with $n$ floors numbered from $1$ to $n$. Between each two adjacent floors in the building, there is a staircase connecting them.\n\nIt's lunchtime for our sensei Colin \"ConneR\" Neumann Jr, and he's planning for a location to enjoy his meal.\n\nConneR's office is at floor $s$ of the building. On each floor (including floor $s$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $k$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.\n\nCooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.\n\nPlease answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!",
    "tutorial": "Since there's only $k$ closed restaurants, in the worst case we'll only have to walk for $k$ staircases only (one such case would be $s = n$ and all the restaurants from floor $s-k+1$ to $s$ are closed). Therefore, a brute force solution is possible: try out every distance $x$ from $0$ to $k$. For each, determine if either $s-x$ or $s+x$ is within range $[1, n]$ and not being in the closed list. The check of an element being a list or not can be done easily by a built-in function in most programming languages, for C++ it would be the \"find\" function with linear time complexity. Of course one would love to check with set/TreeSet, but for this problem it's an overkill. Time complexity: $\\mathcal{O}(k^2)$.",
    "code": "T = int(input())\nfor test_no in range(T):\n\tn, s, k = map(int, input().split())\n\ta = list(map(int, input().split()))\n\n\tfor i in range(0, k+1):\n\t\tif s-i >= 1 and not s-i in a: \n\t\t\tprint(i); break\n\t\tif s+i <= n and not s+i in a:\n\t\t\tprint(i); break\n\telse: assert(False) # if reached this line, the solution failed to find a free floor",
    "tags": [
      "binary search",
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1293",
    "index": "B",
    "title": "JOE is on TV!",
    "statement": "\\begin{quote}\n3R2 - Standby for Action\n\\end{quote}\n\nOur dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show \"1 vs. $n$\"!\n\nThe game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).\n\nFor each question JOE answers, if there are $s$ ($s > 0$) opponents remaining and $t$ ($0 \\le t \\le s$) of them make a mistake on it, JOE receives $\\displaystyle\\frac{t}{s}$ dollars, and consequently there will be $s - t$ opponents left for the next question.\n\nJOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?",
    "tutorial": "This is a greedy problem, with the optimal scenario being each question eliminating a single opponent. It is easy to see that we will want each question to eliminate one opponent only, since after each elimination, the ratio $t/s$ will be more and more rewarding (as $s$ lowers overtime) - as a result, each elimination should have the lowest possible $t$ (i.e. $t = 1$) so more opponents would have their rewards increased. Time complexity is $\\mathcal{O}(n)$.",
    "code": "T = 1\nfor test_no in range(T):\n\tn = int(input())\n\tans = sum([1.0 / i for i in range(1, n+1)])\n\n\tprint(ans)",
    "tags": [
      "combinatorics",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1294",
    "index": "A",
    "title": "Collecting Coins",
    "statement": "Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $a$ coins, Barbara has $b$ coins and Cerene has $c$ coins. Recently Polycarp has returned from the trip around the world and brought $n$ coins.\n\nHe wants to distribute \\textbf{all} these $n$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $A$ coins to Alice, $B$ coins to Barbara and $C$ coins to Cerene ($A+B+C=n$), then $a + A = b + B = c + C$.\n\n\\textbf{Note} that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.\n\nYour task is to find out if it is possible to distribute \\textbf{all} $n$ coins between sisters in a way described above.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Suppose $a \\le b \\le c$. If it isn't true then let's rearrange our variables. Then we need at least $2c - b - a$ coins to make $a$, $b$ and $c$ equal. So if $n < 2c - b - a$ then the answer is \"NO\". Otherwise, the answer if \"YES\" if the number $n - (2c - b - a)$ is divisible by $3$. This is true because after making $a, b$ and $c$ equal we need to distribute all remaining candies between three sisters.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint a[3], n;\n\t\tcin >> a[0] >> a[1] >> a[2] >> n;\n\t\tsort(a, a + 3);\n\t\tn -= 2 * a[2] - a[1] - a[0];\n\t\tif (n < 0 || n % 3 != 0) {\n\t\t\tcout << \"NO\" << endl;\n\t\t} else {\n\t\t\tcout << \"YES\" << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1294",
    "index": "B",
    "title": "Collecting Packages",
    "statement": "There is a robot in a warehouse and $n$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $(0, 0)$. The $i$-th package is at the point $(x_i, y_i)$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $(0, 0)$ doesn't contain a package.\n\nThe robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $(x, y)$ to the point ($x + 1, y$) or to the point $(x, y + 1)$.\n\nAs we say above, the robot wants to collect all $n$ packages (\\textbf{in arbitrary order}). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.\n\nThe string $s$ of length $n$ is lexicographically less than the string $t$ of length $n$ if there is some index $1 \\le j \\le n$ that for all $i$ from $1$ to $j-1$ $s_i = t_i$ and $s_j < t_j$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.",
    "tutorial": "It is obvious that if there is a pair of points $(x_i, y_i)$ and $(x_j, y_j)$ such that $x_i < x_j$ and $y_i > y_j$ then the answer is \"NO\". It means that if the answer is \"YES\" then there is some ordering of points such that $x_{i_1} \\le x_{i_2} \\le \\dots \\le x_{i_n}$ and $y_{i_1} \\le y_{i_2} \\le \\dots \\le y_{i_n}$ because we can only move right or up. But what is this ordering? it is just sorted order of points (firstly by $x_i$ then by $y_i$). So we can sort all points, check if this ordering is valid and traverse among all these points. For each $k$ from $2$ to $n$ firstly do $x_{i_k} - x_{i_{k-1}}$ moves to the right then do $y_{i_k} - y_{i_{k-1}}$ moves to the up (because this order minimizing the answer lexicographically). Time complexity: $O(n \\log n)$ or $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n    int t;\n    cin >> t;\n    \n    for (int tt = 0; tt < t; tt++) {\n     \tint n;\n    \tcin >> n;\n    \tvector<pair<int, int>> a(n);\n    \tfor (int i = 0; i < n; ++i) {\n    \t\tcin >> a[i].first >> a[i].second;\n    \t}\n    \tsort(a.begin(), a.end());\n    \tpair<int, int> cur = make_pair(0, 0);\n    \tstring ans;\n    \tbool ok = true;\n    \tfor (int i = 0; i < n; ++i) {\n    \t\tint r = a[i].first - cur.first;\n    \t\tint u = a[i].second - cur.second;\n    \t\tif (r < 0 || u < 0) {\n    \t\t\tcout << \"NO\" << endl;\n    \t\t\tok = false;\n    \t\t\tbreak;\n    \t\t}\n    \t\tans += string(r, 'R');\n    \t\tans += string(u, 'U');\n    \t\tcur = a[i];\n    \t}\n    \t\n    \tif (ok)\n    \t    cout << \"YES\" << endl << ans << endl;\n   }\n\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1294",
    "index": "C",
    "title": "Product of Three Numbers",
    "statement": "You are given one integer number $n$. Find three \\textbf{distinct integers} $a, b, c$ such that $2 \\le a, b, c$ and $a \\cdot b \\cdot c = n$ or say that it is impossible to do it.\n\nIf there are several answers, you can print any.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Suppose $a < b < c$. Let's try to minimize $a$ and maximize $c$. Let $a$ be the minimum divisor of $n$ greater than $1$. Then let $b$ be the minimum divisor of $\\frac{n}{a}$ that isn't equal $a$ and $1$. If $\\frac{n}{ab}$ isn't equal $a$, $b$ and $1$ then the answer is \"YES\", otherwise the answer is \"NO\". Time complexity: $O(\\sqrt{n})$ per query.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; ++i) {\n\t\tint n;\n\t\tcin >> n;\n\t\tset<int> used;\n\t\tfor (int i = 2; i * i <= n; ++i) {\n\t\t\tif (n % i == 0 && !used.count(i)) {\n\t\t\t\tused.insert(i);\n\t\t\t\tn /= i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 2; i * i <= n; ++i) {\n\t\t\tif (n % i == 0 && !used.count(i)) {\n\t\t\t\tused.insert(i);\n\t\t\t\tn /= i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (int(used.size()) < 2 || used.count(n) || n == 1) {\n\t\t\tcout << \"NO\" << endl;\n\t\t} else {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tused.insert(n);\n\t\t\tfor (auto it : used) cout << it << \" \";\n\t\t\tcout << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1294",
    "index": "D",
    "title": "MEX maximizing",
    "statement": "Recall that \\textbf{MEX} of an array is a \\textbf{minimum non-negative integer} that does not belong to the array. Examples:\n\n- for the array $[0, 0, 1, 0, 2]$ MEX equals to $3$ because numbers $0, 1$ and $2$ are presented in the array and $3$ is the minimum non-negative integer not presented in the array;\n- for the array $[1, 2, 3, 4]$ MEX equals to $0$ because $0$ is the minimum non-negative integer not presented in the array;\n- for the array $[0, 1, 4, 3]$ MEX equals to $2$ because $2$ is the minimum non-negative integer not presented in the array.\n\nYou are given an empty array $a=[]$ (in other words, a zero-length array). You are also given a positive integer $x$.\n\nYou are also given $q$ queries. The $j$-th query consists of one integer $y_j$ and means that you have to append one element $y_j$ to the array. The array length increases by $1$ after a query.\n\nIn one move, you can choose any index $i$ and set $a_i := a_i + x$ or $a_i := a_i - x$ (i.e. increase or decrease any element of the array by $x$). The only restriction is that \\textbf{$a_i$ cannot become negative}. Since initially the array is empty, you can perform moves only after the first query.\n\nYou have to maximize the \\textbf{MEX} (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).\n\nYou have to find the answer after each of $q$ queries (i.e. the $j$-th answer corresponds to the array of length $j$).\n\n\\textbf{Operations are discarded before each query. I.e. the array $a$ after the $j$-th query equals to $[y_1, y_2, \\dots, y_j]$.}",
    "tutorial": "Firstly, let's understand what the operation does. It changes the element but holds the remainder modulo $x$. So we can consider all elements modulo $x$. Let $cnt_0$ be the number of elements with the value $0$ modulo $x$, $cnt_1$ be the number of elements with the value $1$ modulo $x$, and so on. Let's understand, where is the \"bottleneck\" of MEX. Obviously, we can always fill exactly $min(cnt_0, cnt_1, \\dots, cnt_{x - 1})$ full blocks, so MEX is at least $min(cnt_0, cnt_1, \\dots, cnt_{x - 1}) \\cdot x$. MEX will be among all elements $y \\in [0; x - 1]$ such that $cnt_y = min(cnt_0, cnt_1, \\dots, cnt_{x - 1})$. Among all such elements MEX will be the minimum such $y$. Let it be $mn$. So the final value of MEX is $cnt_{mn} \\cdot x + mn$. How to deal with queries? Let's maintain the sorted set of pairs ($cnt_y, y$) for all $y \\in [0; x - 1]$ and change it with respect to appended values. During each query let's change the set correspondingly and take the answer as the first element of this set using the formula above. Time complexity: $O(n \\log n)$. There is also an easy linear solution that uses the same idea but in a different way.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint q, x;\n\tcin >> q >> x;\n\tvector<int> mods(x);\n\t\n\tset<pair<int, int>> vals;\n\tfor (int i = 0; i < x; ++i) {\n\t\tvals.insert(make_pair(mods[i], i));\n\t}\n\t\n\tfor (int i = 0; i < q; ++i) {\n\t\tint cur;\n\t\tcin >> cur;\n\t\tcur %= x;\n\t\tvals.erase(make_pair(mods[cur], cur));\n\t\t++mods[cur];\n\t\tvals.insert(make_pair(mods[cur], cur));\n\t\tcout << vals.begin()->first * x + vals.begin()->second << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1294",
    "index": "E",
    "title": "Obtain a Permutation",
    "statement": "You are given a rectangular matrix of size $n \\times m$ consisting of integers from $1$ to $2 \\cdot 10^5$.\n\nIn one move, you can:\n\n- choose \\textbf{any element} of the matrix and change its value to \\textbf{any} integer between $1$ and $n \\cdot m$, inclusive;\n- take \\textbf{any column} and shift it one cell up cyclically (see the example of such cyclic shift below).\n\nA cyclic shift is an operation such that you choose some $j$ ($1 \\le j \\le m$) and set $a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \\dots, a_{n, j} := a_{1, j}$ \\textbf{simultaneously}.\n\n\\begin{center}\nExample of cyclic shift of the first column\n\\end{center}\n\nYou want to perform the minimum number of moves to make this matrix look like this:\n\nIn other words, the goal is to obtain the matrix, where $a_{1, 1} = 1, a_{1, 2} = 2, \\dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \\dots, a_{n, m} = n \\cdot m$ (i.e. $a_{i, j} = (i - 1) \\cdot m + j$) with the \\textbf{minimum number of moves} performed.",
    "tutorial": "At first, let's decrease all elements by one and solve the problem in $0$-indexation. The first observation is that we can solve the problem independently for each column. Consider the column $j$ $(j \\in [0; m-1])$. It consists of elements $[j; m + j, 2m + j, \\dots, (n-1)m + j]$. Now consider some element $a_{i, j}$ $(i \\in [0; n - 1])$. We don't need to replace it with some other number in only one case: if we shift the column such that $a_{i, j}$ will coincide with the corresponding number of the required matrix. Obviously, there is only one cyclic shift of the column that can rid us of replacing $a_{i, j}$. So, the idea is the following: let's calculate for each cyclic shift the number of elements we don't need to replace if we use this cyclic shift. Let for the $i$-th cyclic shift ($0$-indexed) it be $cnt_i$. Then the answer for this column can be taken as $\\min\\limits_{i=0}^{n-1} n - cnt_i + i$. How to calculate for the element $a_{i, j}$ the corresponding cyclic shift? Firstly, if $a_{i, j} \\% m \\ne j$ ($\\%$ is modulo operation) then there is no such cyclic shift. Otherwise, let $pos = \\lfloor\\frac{a_{i, j}}{m}\\rfloor$. If $pos < n$ then there is such cyclic shift ($pos$ can be greater than or equal to $n$ because $a_{i, j}$ can be up to $2 \\cdot 10^5$) and the number of such cyclic shift is $(i - pos + n) \\% n$. So let's increase $cnt_{(i - pos + n) \\% n}$ and continue. After considering all elements of this column take the answer by the formula above and go to the next column. Time complexity: $O(nm)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tvector<vector<int>> a(n, vector<int>(m));\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < m; ++j) {\n\t\t\tcin >> a[i][j];\n\t\t\t--a[i][j];\t\n\t\t}\n\t}\n\t\n\tlong long ans = 0;\n\tfor (int j = 0; j < m; ++j) {\n\t\tvector<int> cnt(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (a[i][j] % m == j) {\n\t\t\t\tint pos = a[i][j] / m;\n\t\t\t\tif (pos < n) {\n\t\t\t\t\t++cnt[(i - pos + n) % n];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint cur = n - cnt[0];\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tcur = min(cur, n - cnt[i] + i);\n\t\t}\n\t\tans += cur;\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1294",
    "index": "F",
    "title": "Three Paths on a Tree",
    "statement": "You are given an unweighted tree with $n$ vertices. Recall that a tree is a connected undirected graph without cycles.\n\nYour task is to choose \\textbf{three distinct} vertices $a, b, c$ on this tree such that the number of edges which belong to \\textbf{at least} one of the simple paths between $a$ and $b$, $b$ and $c$, or $a$ and $c$ is the maximum possible. See the notes section for a better understanding.\n\nThe simple path is the path that visits each vertex at most once.",
    "tutorial": "There is some obvious dynamic programming solution that someone can describe in the comments, but I will describe another one, that, in my opinion, much easier to implement. Firstly, let's find some diameter of the tree. Let $a$ and $b$ be the endpoints of this diameter (and first two vertices of the answer). You can prove yourself why it is always good to take the diameter and why any diameter can be taken in the answer. Then there are two cases: the length of the diameter is $n-1$ or the length of the diameter is less than $n-1$. In the first case, you can take any other vertex as the third vertex of the answer $c$, it will not affect the answer anyway. Otherwise, we can run multi-source bfs from all vertices of the diameter and take the farthest vertex as the third vertex of the answer. It is always true because we can take any diameter and the farthest vertex will increase the answer as much as possible. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n\nvector<int> p;\nvector<vector<int>> g;\n\npair<int, int> dfs(int v, int par = -1, int dist = 0) {\n\tp[v] = par;\n\tpair<int, int> res = make_pair(dist, v);\n\tfor (auto to : g[v]) {\n\t\tif (to == par) continue;\n\t\tres = max(res, dfs(to, v, dist + 1));\n\t}\n\treturn res;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tp = vector<int>(n);\n\tg = vector<vector<int>>(n);\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\t\n\t}\n\t\n\t\n\tpair<int, int> da = dfs(0);\n\tpair<int, int> db = dfs(da.y);\n\tvector<int> diam;\n\tint v = db.y;\n\twhile (v != da.y) {\n\t\tdiam.push_back(v);\n\t\tv = p[v];\n\t}\n\tdiam.push_back(da.y);\n\t\n\tif (int(diam.size()) == n) {\n\t\tcout << n - 1 << \" \" << endl << diam[0] + 1 << \" \" << diam[1] + 1 << \" \" << diam.back() + 1 << endl;\n\t} else {\n\t\tqueue<int> q;\n\t\tvector<int> d(n, -1);\n\t\tfor (auto v : diam) {\n\t\t\td[v] = 0;\n\t\t\tq.push(v);\n\t\t}\n\t\twhile (!q.empty()) {\n\t\t\tint v = q.front();\n\t\t\tq.pop();\n\t\t\tfor (auto to : g[v]) {\n\t\t\t\tif (d[to] == -1) {\n\t\t\t\t\td[to] = d[v] + 1;\n\t\t\t\t\tq.push(to);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpair<int, int> mx = make_pair(d[0], 0);\n\t\tfor (int v = 1; v < n; ++v) {\n\t\t\tmx = max(mx, make_pair(d[v], v));\n\t\t}\n\t\tcout << int(diam.size()) - 1 + mx.x << endl << diam[0] + 1 << \" \" << mx.y + 1 << \" \" << diam.back() + 1 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1295",
    "index": "A",
    "title": "Display The Number",
    "statement": "You have a large electronic screen which can display up to $998244353$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $7$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $10$ decimal digits:\n\nAs you can see, different digits may require different number of segments to be turned on. For example, if you want to display $1$, you have to turn on $2$ segments of the screen, and if you want to display $8$, all $7$ segments of some place to display a digit should be turned on.\n\nYou want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $n$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $n$ segments.\n\nYour program should be able to process $t$ different test cases.",
    "tutorial": "First of all, we don't need to use any digits other than $1$ and $7$. If we use any other digit, it consists of $4$ or more segments, so it can be replaced by two $1$'s and the number will become greater. For the same reason we don't need to use more than one $7$: if we have two, we can replace them with three $1$'s. Obviously, it is always optimal to place $7$ before $1$. So our number is either a sequence of $1$'s, or a $7$ and a sequence of $1$'s. We should use $7$ only if $n$ is odd, because if $n$ is even, it will decrease the number of digits in the result.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    if(n % 2 == 1):\n        print(7, end='')\n        n -= 3\n    while(n > 0):\n        print(1, end='')\n        n -= 2\n    print()",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1295",
    "index": "B",
    "title": "Infinite Prefixes",
    "statement": "You are given string $s$ of length $n$ consisting of 0-s and 1-s. You build an infinite string $t$ as a concatenation of an infinite number of strings $s$, or $t = ssss \\dots$ For example, if $s =$ 10010, then $t =$ 100101001010010...\n\nCalculate the number of prefixes of $t$ with balance equal to $x$. The balance of some string $q$ is equal to $cnt_{0, q} - cnt_{1, q}$, where $cnt_{0, q}$ is the number of occurrences of 0 in $q$, and $cnt_{1, q}$ is the number of occurrences of 1 in $q$. The number of such prefixes can be infinite; if it is so, you must say that.\n\nA prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".",
    "tutorial": "Let's denote a prefix of length $i$ as $pref(i)$. We can note that each $pref(i) = k \\cdot pref(n) + pref(i \\mod n)$ where $k = \\left\\lfloor \\frac{i}{n} \\right\\rfloor$ and $+$ is a concatenation. Then balance $bal(i)$ of prefix of length $i$ is equal to $k \\cdot bal(n) + bal(i \\mod n)$. Now there two cases: $bal(n)$ is equal to $0$ or not. If $bal(n) = 0$ then if exist such $j$ ($0 \\le j < n$) that $bal(j) = x$ then for each $k \\ge 0$ $bal(j + kn) = x$ and answer is $-1$. Otherwise, for each such $j$ there will no more than one possible $k$: since there are zero or one solution to the equation $bal(j) + k \\cdot bal(n) = x$. The solution exists if and only if $x - bal(j) \\equiv 0 \\mod bal(n)$ and $k = \\frac{x - bal(j)}{bal(n)} \\ge 0$. So, just precalc $bal(n)$ and for each $0 \\le j < n$ check the equation.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\nint n, x;\nstring s;\n\ninline bool read() {\n\tif(!(cin >> n >> x >> s))\n\t\treturn false;\n\treturn true;\n}\n\ninline void solve() {\n\tint ans = 0;\n\tbool infAns = false;\n\t\n\tint cntZeros = (int)count(s.begin(), s.end(), '0');\n\tint total = cntZeros - (n - cntZeros);\n\t\n\tint bal = 0;\n\tfor(int i = 0; i < n; i++) {\n\t\tif(total == 0) {\n\t\t\tif(bal == x)\n\t\t\t\tinfAns = true;\n\t\t}\n\t\telse if(abs(x - bal) % abs(total) == 0) {\n\t\t\tif((x - bal) / total >= 0)\n\t\t\t\tans++;\n\t\t}\n\t\t\n\t\tif(s[i] == '0')\n\t\t\tbal++;\n\t\telse\n\t\t\tbal--;\n\t}\n\t\n\tif(infAns) ans = -1;\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\twhile(tc--) {\n\t\tread();\n\t\tsolve();\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1295",
    "index": "C",
    "title": "Obtain The String",
    "statement": "You are given two strings $s$ and $t$ consisting of lowercase Latin letters. Also you have a string $z$ which is initially empty. You want string $z$ to be equal to string $t$. You can perform the following operation to achieve this: append any subsequence of $s$ at the end of string $z$. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if $z = ac$, $s = abcde$, you may turn $z$ into following strings in one operation:\n\n- $z = acace$ (if we choose subsequence $ace$);\n- $z = acbcd$ (if we choose subsequence $bcd$);\n- $z = acbce$ (if we choose subsequence $bce$).\n\nNote that after this operation string $s$ doesn't change.\n\nCalculate the minimum number of such operations to turn string $z$ into string $t$.",
    "tutorial": "The answer is $-1$ when in string $t$ there is a character that is not in string $s$. Otherwise let's precalculate the following array $nxt_{i, j}$ = minimum index $x$ from $i$ to $|s|$ such that $s_x = j$ (if there is no such index then $nxt_{i, j} = inf$). Now we can solve this problem by simple greed. Presume that now $z = t_0 t_1 \\dots t_{i-1}$, and last taken symbol in $s$ is $s_{pos}$. Then there are two options: if $nxt_{pos, i} \\neq inf$, then $i = i + 1$, $pos = nxt_{pos+1, i}$; if $nxt_{pos, i} = inf$, then $pos = 0$ and $ans = ans + 1$ ($ans$ is equal to $0$ initially);",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = int(2e5) + 99;\nconst int INF = int(1e9) + 99;\n\nint tc;\nstring s, t;\nint nxt[N][26];\n\nint main() {\n    cin >> tc;\n    while(tc--){\n        cin >> s >> t;\n        for(int i = 0; i < s.size() + 5; ++i)\n            for(int j = 0; j < 26; ++j)\n                nxt[i][j] = INF;\n    \t\n        for(int i = int(s.size()) - 1; i >= 0; --i){\n            for(int j = 0; j < 26; ++j)\n                nxt[i][j] = nxt[i + 1][j];\n            nxt[i][s[i] - 'a'] = i;\n        }    \n    \n        int res = 1, pos = 0;\n        for(int i = 0; i < t.size(); ++i){\n            if(pos == s.size()){\n                pos = 0;\n                ++res;\n            }\n            if(nxt[pos][t[i] - 'a'] == INF){\n                pos = 0; \n                ++res;\n    \t\t}\n    \t\tif(nxt[pos][t[i] - 'a'] == INF && pos == 0){\n                res = INF;\n                break;\n            }    \n            pos = nxt[pos][t[i] - 'a'] + 1;\n            \n        }\n    \n        if(res >= INF) cout << -1 << endl;\n        else cout << res << endl;\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1295",
    "index": "D",
    "title": "Same GCDs",
    "statement": "You are given two integers $a$ and $m$. Calculate the number of integers $x$ such that $0 \\le x < m$ and $\\gcd(a, m) = \\gcd(a + x, m)$.\n\nNote: $\\gcd(a, b)$ is the greatest common divisor of $a$ and $b$.",
    "tutorial": "The Euclidean algorithm is based on the next fact: if $a \\ge b$ then $\\gcd(a, b) = \\gcd(a - b, b)$. So, if $(a + x) \\ge m$ then $\\gcd(a + x, m) = \\gcd(a + x - m, m)$. So we can declare that we are looking at $m$ different integers $x' = (a + x) \\mod m$ with $0 \\le x' < m$, so all $x'$ forms a segment $[0, m - 1]$. So, we need to find the number of $x'$ ($0 \\le x' < m$) such that $\\gcd(x', m) = \\gcd(a, m)$. Let's denote $g = \\gcd(a, m)$, then $a = ga'$ and $m = gm'$. So, $\\gcd(a, m) = \\gcd(ga', gm') = g \\cdot \\gcd(a', m') = g$ or $\\gcd(a', m') = 1$. Since $\\gcd(x', m) = \\gcd(a, m) = g$ so we also can represent $x' = x^{\"}g$ and, therefore $gcd(x^{\"}, m') = 1$. Since $0 \\le x' < m$, then $0 \\le x^{\"} < m'$ or we need to calaculate the number of $x^{\"}$ ($0 \\le x^{\"} < m'$) such that $\\gcd(x^{\"}, m') = 1$. Since $gcd(0, m') = m' > 1$ so we can consider $x^{\"} \\in [1, m' - 1]$ and this is the definition of Euler's totient function $\\varphi(m')$ which is the answer. Euler's totient function $\\varphi(m')$ can be calculated using factorization of $m' = \\prod\\limits_{i=1}^{l}{p_i^{a_i}}$. Then $\\varphi(m') = m' \\prod\\limits_{i=1}^{l}{(1 - \\frac{1}{p_i})}$.",
    "code": "fun gcd(a : Long, b : Long) : Long {\n    return if (a == 0L) b else gcd(b % a, a)\n}\nfun phi(a : Long) : Long {\n    var (tmp, ans) = listOf(a, a)\n    var d = 2L\n    while (d * d <= tmp) {\n        var cnt = 0\n        while (tmp % d == 0L) {\n            tmp /= d\n            cnt++\n        }\n        if (cnt > 0) ans -= ans / d\n        d++\n    }\n    if (tmp > 1L) ans -= ans / tmp\n    return ans\n}\n\nfun main() {\n    val t = readLine()!!.toInt()\n    for (tc in 1..t) {\n        val (a, m) = readLine()!!.split(' ').map { it.toLong() }\n        println(phi(m / gcd(a, m)))\n    }\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1295",
    "index": "E",
    "title": "Permutation Separation",
    "statement": "You are given a permutation $p_1, p_2, \\dots , p_n$ (an array where each integer from $1$ to $n$ appears exactly once). The weight of the $i$-th element of this permutation is $a_i$.\n\nAt first, you separate your permutation into two \\textbf{non-empty} sets — prefix and suffix. More formally, the first set contains elements $p_1, p_2, \\dots , p_k$, the second — $p_{k+1}, p_{k+2}, \\dots , p_n$, where $1 \\le k < n$.\n\nAfter that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay $a_i$ dollars to move the element $p_i$.\n\nYour goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.\n\nFor example, if $p = [3, 1, 2]$ and $a = [7, 1, 4]$, then the optimal strategy is: separate $p$ into two parts $[3, 1]$ and $[2]$ and then move the $2$-element into first set (it costs $4$). And if $p = [3, 5, 1, 6, 2, 4]$, $a = [9, 1, 9, 9, 1, 9]$, then the optimal strategy is: separate $p$ into two parts $[3, 5, 1]$ and $[6, 2, 4]$, and then move the $2$-element into first set (it costs $1$), and $5$-element into second set (it also costs $1$).\n\nCalculate the minimum number of dollars you have to spend.",
    "tutorial": "\"All elements in the left set smaller than all elements in the right set\" means that there is such value $val$ that all elements from the first set less than $val$ and all elements from the second set are more or equal to $val$. So let's make a sweep line on $val$ from $1$ to $n + 1$ while trying to maintain all answers for each prefix $pos$. Let's maintain for each $pos$ the total cost $t[pos]$ to make sets \"good\" if we split the permutation $p$ on sets $[p_1, \\dots, p_{pos}]$ and $[p_{pos} + 1, \\dots, p_n]$ in such way that after transformations all elements in the first set less than $val$. It's easy to see that the total cost is equal to sum of weights $a_i$ where $i \\le pos$ and $p_i \\ge val$ and $a_i$ where $i > pos$ and $p_i < val$. So what will happen if we increase $val$ by $1$? Let's define the position of $p_k = val$ as $k$. For each $pos \\ge k$ we don't need to move $p_k$ to the second set anymore, so we should make $t[pos] -= a_k$. On the other hand, for each $pos < k$ we need to move $p_k$ from the second set to the first one now, so we should make $t[pos] += a_k$. The answer will be equal to the $\\min\\limits_{1 \\le pos < n}(t[pos])$. It means that we should handle two operations: add some value on the segment and ask minimum on the segment. So we can store all $t[pos]$ in pretty standart Segment Tree with \"add on segment\" and \"minimum on segment\" while iterating over $val$. So the total complexity is $O(n \\log{n})$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = int(2e5) + 99;\n\nint n;\nint p[N];\nint rp[N];\nint a[N];\n\nlong long b[N];\nlong long t[4 * N];\nlong long add[4 * N];\n\nvoid build(int v, int l, int r){\n\tif(r - l == 1){\n\t\tt[v] = b[l];\n\t\treturn;\n\t}\n\n\tint mid = (l + r) / 2;\t\n\tbuild(v * 2 + 1, l, mid);\n\tbuild(v * 2 + 2, mid, r);\n\tt[v] = min(t[v * 2 + 1], t[v * 2 + 2]); \n}\n\nvoid push(int v, int l, int r){\n\tif(add[v] != 0){\n\t\tif(r - l > 1)\n\t\t\tfor(int i = v+v+1; i < v+v+3; ++i){\n\t\t\t\tadd[i] += add[v];\n\t\t\t\tt[i] += add[v];\n\t\t\t}\n\t\tadd[v] = 0;\n\t}\n}\n\nvoid upd(int v, int l, int r, int L, int R, int x){\n\tif(L >= R) return;\n\tif(l == L && r == R){\n\t\tadd[v] += x;\n\t\tt[v] += x;\n\t\tpush(v, l, r);\n\t\treturn;\n\t}\n\t\n\tpush(v, l, r);\n\tint mid = (l + r) / 2;\n\tupd(v * 2 + 1, l, mid, L, min(mid, R), x);\n\tupd(v * 2 + 2, mid, r, max(mid, L), R, x);\n\n\tt[v] = min(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\nvoid upd(int l, int r, int x){\n\tupd(0, 0, n, l, r, x);\n}\n\nlong long get(int v, int l, int r, int L, int R){\n\tif(L >= R) return 1e18;\n\n\tpush(v, l, r);\n\tif(l == L && r == R)\n\t\treturn t[v];\n\n\tint mid = (l + r) / 2;\n\treturn min(get(v * 2 + 1, l, mid, L, min(R, mid)), \n\t\t   get(v * 2 + 2, mid, r, max(L, mid), R));\t\t\n}\n\nlong long get(int l, int r){\n\treturn get(0, 0, n, l, r);\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; ++i){\n\t\tscanf(\"%d\", p + i);\n        --p[i];\n        rp[p[i]] = i;\n\t}\n\tfor(int i = 0; i < n; ++i)\n\t\tscanf(\"%d\", a + i);\n\t\n\tb[0] = a[0];\n\tfor(int i = 1; i < n; ++i)\n\t\tb[i] = a[i] + b[i - 1];\n\tbuild(0, 0, n);\n\t\n\tlong long res = get(0, n - 1);\n\t//for(int i = 0; i < n; ++i) cout << get(i, i+1) << ' ';cout << endl;\n\tfor(int i = 0; i < n; ++i){\n\t    int pos = rp[i];\n\t\tupd(pos, n, -a[pos]);\n\t\tupd(0, pos, a[pos]);\n\t\tres = min(res, get(0, n - 1));\n\t\t//for(int i = 0; i < n; ++i) cout << get(i, i+1) << ' ';cout << endl;\n\t}\n\t\n\tcout << res << endl;\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1295",
    "index": "F",
    "title": "Good Contest",
    "statement": "An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $n$ problems; and since the platform is very popular, $998244351$ coder from all over the world is going to solve them.\n\nFor each problem, the authors estimated the number of people who would solve it: for the $i$-th problem, the number of accepted solutions will be between $l_i$ and $r_i$, inclusive.\n\nThe creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $(x, y)$ such that $x$ is located earlier in the contest ($x < y$), but the number of accepted solutions for $y$ is \\textbf{strictly} greater.\n\nObviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be \\textbf{no} inversions in the problem order, assuming that for each problem $i$, any \\textbf{integral} number of accepted solutions for it (between $l_i$ and $r_i$) is equally probable, and all these numbers are independent.",
    "tutorial": "Model solution (slow, complicated and not cool): The naive solution is dynamic programming: let $dp_{i, x}$ be the probability that the first $i$ problems don't have any inversions, and the $i$-th one got $x$ accepted solutions. Let's somehow speed it up. For convenience, I will modify the variable denoting the maximum number of accepted solutions for each problem: $L_i = l_i$, $R_i = r_i + 1$; and I will also reverse the problem order, so that we don't want the number of solutions to decrease from problem to problem. We know that $dp_{i, x} = \\frac{1}{R_i - L_i} \\sum\\limits_{j = 0}^{x} dp_{i - 1, j}$, if $x \\in [L_i, R_i)$, and $dp_{i, x} = 0$ otherwise. Let's divide the whole segment between $0$ and $998244351$ into $O(n)$ segments with the values of $L_i$ and $R_i$ and analyse the behavior of $dp$ values on each such segment. Let $f_i(x) = dp_{i, x}$. If we consider the behavior of $f_i(x)$ on some segment we got, we can prove by induction that it is a polynomial of degree not exceeding $i$. All that is left is to carefully calculate and maintain these polynomials on segments. The main thing we will use to calculate the polynomials is interpolation. To transition from $f_i$ to $f_{i + 1}$, we will consider each segment separately, calculate the first several values of $f_{i + 1}$ on each segment (we need to calculate the sum $\\sum\\limits_{x = L}^{R} P(x)$ fast, if $P(x)$ is a polynomial, this can also be done with interpolation), and then interpolate it on the whole segment. This is actually slow (we have to interpolate at least $O(n^2)$ polynomials) and not easy to write. Let's consider a better solution. Participants' solution (much faster and easier to code): We will use combinatoric approach: instead of calculating probabilities, we will count all the non-descending sequences $(a_1, a_2, \\dots, a_n)$ such that $i \\in [L_i, R_i)$, and divide it by the number of all sequences without the non-descending condition (that is just $\\prod_{i=1}^{n} R_i - L_i$). Let's again divide $[0, 998244353]$ into $O(n)$ segments using the points $L_i$, $R_i$, and enumerate these segments from left to right. If there are two neighboring values $a_i$ and $a_{i + 1}$, they either belong to the same segment, or the segment $a_{i + 1}$ belongs to is to the right of the segment $a_i$ belongs to. We could try to write the following dynamic programming solution: $cnt_{i, j}$ is the number of non-descending prefixes of the sequence such that there are $i$ elements in the prefix, and the last one belongs to segment $j$. It's easy to model transitions from $cnt_{i, j}$ to $cnt_{i + 1, k}$ where $k > j$, but we don't know how to model the transition to $cnt_{i + 1, j}$. Let's get rid of them altogether! We will introduce an additional constraint in our dynamic programming: $cnt_{i, j}$ is the number of prefixes of the sequence of length $i$ such that all elements on prefix belong to one of the first $j$ segments, but next element should not belong to it. The transitions in this dynamic programming are different: we iterate on the number of elements $k$ belonging to the next segment and transition into $cnt_{i + k, j + 1}$ (if possible). Calculating the number of ways to take $k$ elements from an interval $[L, R)$ in sorted order can be reduced to calculating the number of ways to compose $k$ as the sum of $R - L$ non-negative summands (order matters). We should be able to calculate binomial coefficients with fairly large $n$ and not so large $k$, but that's not really hard if we use the formula $\\binom{n}{k} = \\binom{n}{k - 1} \\cdot \\frac{n - k + 1}{k}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y)\n    {\n        if(y & 1) z = mul(z, x);\n        x = mul(x, x);\n        y >>= 1;\n    }\n    return z;\n}\n\nint inv(int x)\n{\n    return binpow(x, MOD - 2);\n}\n\nint divide(int x, int y)\n{\n    return mul(x, inv(y));\n}\n\ntypedef vector<int> poly;\n\nvoid norm(poly& p)\n{\n    while(p.size() > 0 && p.back() == 0)\n        p.pop_back();\n}\n\npoly operator +(const poly& a, const poly& b)\n{\n    poly c = a;\n    while(c.size() < b.size()) c.push_back(0);\n    for(int i = 0; i < b.size(); i++) c[i] = add(c[i], b[i]);\n    norm(c);\n    return c;\n}\n\npoly operator +(const poly& a, int b)\n{\n    return a + poly(1, b);\n}\n\npoly operator +(int a, const poly& b)\n{\n    return b + a;\n}\n\npoly operator *(const poly& a, int b)\n{\n    poly c = a;                               \n    for(int i = 0; i < c.size(); i++) c[i] = mul(c[i], b);\n    norm(c);\n    return c;\n}\n\npoly operator /(const poly& a, int b)\n{   \n    return a * inv(b);\n}\n\npoly operator *(const poly& a, const poly& b)\n{\n    poly c(a.size() + b.size() - 1);\n    for(int i = 0; i < a.size(); i++)\n        for(int j = 0; j < b.size(); j++)\n            c[i + j] = add(c[i + j], mul(a[i], b[j]));\n\n    norm(c);\n    return c;\n}\n\npoly interpolate(const vector<int>& x, const vector<int>& y)\n{\n    int n = int(x.size()) - 1;\n    vector<vector<int> > f(n + 1);\n    f[0] = y;\n    for(int i = 1; i <= n; i++)\n        for(int j = 0; j <= n - i; j++)\n            f[i].push_back(divide(add(f[i - 1][j + 1], -f[i - 1][j]), add(x[i + j], -x[j])));\n    \n    poly cur = poly(1, 1);\n    poly res;\n    for(int i = 0; i <= n; i++)\n    {\n        res = res + cur * f[i][0];\n        cur = cur * poly({add(0, -x[i]), 1});\n    }\n\n    return res;\n}\n\nint eval(const poly& a, int x)\n{\n    int res = 0;\n    for(int i = int(a.size()) - 1; i >= 0; i--)\n        res = add(mul(res, x), a[i]);\n    return res;\n}\n\npoly sumFromL(const poly& a, int L, int n)\n{\n    vector<int> x;\n    for(int i = 0; i <= n; i++)\n        x.push_back(L + i);\n    vector<int> y;\n    int cur = 0;\n    for(int i = 0; i <= n; i++)\n    {\n        cur = add(cur, eval(a, x[i]));\n        y.push_back(cur);\n    }\n    return interpolate(x, y);\n}\n\nint sumOverSegment(const poly& a, int L, int R)\n{\n    return eval(sumFromL(a, L, a.size()), R - 1);\n}\n\nint main() {\n    int n;\n    cin >> n;\n    vector<int> L(n), R(n);\n    for(int i = 0; i < n; i++)\n    {\n        cin >> L[i] >> R[i];\n        R[i]++;\n    }\n    reverse(L.begin(), L.end());\n    reverse(R.begin(), R.end());\n\n    vector<int> coord = {0, MOD - 2};\n    for(int i = 0; i < n; i++)\n    {\n        coord.push_back(L[i]);\n        coord.push_back(R[i]);\n    }\n    sort(coord.begin(), coord.end());\n    coord.erase(unique(coord.begin(), coord.end()), coord.end());\n    vector<int> cL = coord, cR = coord;\n    cL.pop_back();\n    cR.erase(cR.begin());\n    int cnt = coord.size() - 1;\n    vector<poly> cur(cnt);\n    for(int i = 0; i < cnt; i++)\n        if(cL[i] >= L[0] && cR[i] <= R[0])\n            cur[i] = poly(1, inv(R[0] - L[0]));\n    for(int i = 1; i < n; i++)\n    {\n        vector<poly> nxt(cnt);        \n        int curSum = 0;\n        for(int j = 0; j < cnt; j++)\n        {\n            nxt[j] = sumFromL(cur[j], cL[j], i) + curSum;\n            curSum = add(curSum, sumOverSegment(cur[j], cL[j], cR[j]));    \n        }\n        for(int j = 0; j < cnt; j++)\n            nxt[j] = nxt[j] * (cL[j] >= L[i] && cR[j] <= R[i] ? inv(R[i] - L[i]) : 0);\n        cur = nxt;\n    }\n    int ans = 0;\n    for(int i = 0; i < cnt; i++)\n        ans = add(ans, sumOverSegment(cur[i], cL[i], cR[i]));\n\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1296",
    "index": "A",
    "title": "Array with Odd Sum",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nIn one move, you can choose two indices $1 \\le i, j \\le n$ such that $i \\ne j$ and set $a_i := a_j$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $i$ and $j$ and replace $a_i$ with $a_j$).\n\nYour task is to say if it is possible to obtain an array with an odd (not divisible by $2$) sum of elements.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, if the array already has an odd sum, the answer is \"YES\". Otherwise, we need to change the parity of the sum, so we need to change the parity of some number. We can do in only when we have at least one even number and at least one odd number. Otherwise, the answer is \"NO\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tint sum = 0;\n\t\tbool odd = false, even = false;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\tsum += x;\n\t\t\todd |= x % 2 != 0;\n\t\t\teven |= x % 2 == 0;\n\t\t}\n\t\tif (sum % 2 != 0 || (odd && even)) cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1296",
    "index": "B",
    "title": "Food Buying",
    "statement": "Mishka wants to buy some food in the nearby shop. Initially, he has $s$ burles on his card.\n\nMishka can perform the following operation any number of times (possibly, zero): choose some \\textbf{positive integer number} $1 \\le x \\le s$, buy food that costs exactly $x$ burles and obtain $\\lfloor\\frac{x}{10}\\rfloor$ burles as a cashback (in other words, Mishka spends $x$ burles and obtains $\\lfloor\\frac{x}{10}\\rfloor$ back). The operation $\\lfloor\\frac{a}{b}\\rfloor$ means $a$ divided by $b$ rounded down.\n\nIt is guaranteed that you can always buy some food that costs $x$ for any possible value of $x$.\n\nYour task is to say the maximum number of burles Mishka can spend if he buys food optimally.\n\nFor example, if Mishka has $s=19$ burles then the maximum number of burles he can spend is $21$. Firstly, he can spend $x=10$ burles, obtain $1$ burle as a cashback. Now he has $s=10$ burles, so can spend $x=10$ burles, obtain $1$ burle as a cashback and spend it too.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let's do the following greedy solution: it is obvious that when we buy food that costs exactly $10^k$ for $k \\ge 1$, we don't lose any burles because of rounding. Let's take the maximum power of $10$ that is not greater than $s$ (let it be $10^c$), buy food that costs $10^c$ (and add this number to the answer) and add $10^{c-1}$ to $s$. Apply this process until $s < 10$ and then add $s$ to the answer. Time complexity: $O(\\log s)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint s;\n\t\tcin >> s;\n\t\tint ans = 0;\n\t\tint pw = 1000 * 1000 * 1000;\n\t\twhile (s > 0) {\n\t\t\twhile (s < pw) pw /= 10;\n\t\t\tans += pw;\n\t\t\ts -= pw - pw / 10;\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1296",
    "index": "C",
    "title": "Yet Another Walking Robot",
    "statement": "There is a robot on a coordinate plane. Initially, the robot is located at the point $(0, 0)$. Its path is described as a string $s$ of length $n$ consisting of characters 'L', 'R', 'U', 'D'.\n\nEach of these characters corresponds to some move:\n\n- 'L' (left): means that the robot moves from the point $(x, y)$ to the point $(x - 1, y)$;\n- 'R' (right): means that the robot moves from the point $(x, y)$ to the point $(x + 1, y)$;\n- 'U' (up): means that the robot moves from the point $(x, y)$ to the point $(x, y + 1)$;\n- 'D' (down): means that the robot moves from the point $(x, y)$ to the point $(x, y - 1)$.\n\nThe company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove \\textbf{any non-empty substring} of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point $(x_e, y_e)$, then after optimization (i.e. removing some single substring from $s$) the robot also ends its path at the point $(x_e, y_e)$.\n\nThis optimization is a low-budget project so you need to remove \\textbf{the shortest} possible \\textbf{non-empty} substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string $s$).\n\nRecall that the substring of $s$ is such string that can be obtained from $s$ by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of \"LURLLR\" are \"LU\", \"LR\", \"LURLLR\", \"URL\", but not \"RR\" and \"UL\".\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Formally, the problem asks you to remove the shortest cycle from the robot's path. Because the endpoint of the path cannot be changed, the number of 'L's should be equal to the number of 'R's and the same with 'U' and 'D'. How to find the shortest cycle? Let's create the associative array $vis$ (std::map for C++) which will say for each point of the path the maximum number of operations $i$ such that if we apply first $i$ operations we will stay at this point. Initially, this array will contain only the point $(0, 0)$ with the value $0$. Let's go over all characters of $s$ in order from left to right. Let the current point be $(x_i, y_i)$ (we applied first $i+1$ operations, $0$-indexed). If this point is in the array already, let's try to update the answer with the value $i - vis[(x_i, y_i)] + 1$ and left and right borders with values $vis[(x_i, y_i)]$ and $i$ correspondingly. Then let's assign $vis[(x_i, y_i)] := i + 1$ and continue. If there were no updates of the answer, the answer is -1. Otherwise, you can print any substring you found. Time complexity: $O(n \\log n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tstring s;\n\t\tcin >> n >> s;\n\t\tint l = -1, r = n;\n\t\tmap<pair<int, int>, int> vis;\n\t\tpair<int, int> cur = {0, 0};\n\t\tvis[cur] = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (s[i] == 'L') --cur.first;\n\t\t\tif (s[i] == 'R') ++cur.first;\n\t\t\tif (s[i] == 'U') ++cur.second;\n\t\t\tif (s[i] == 'D') --cur.second;\n\t\t\tif (vis.count(cur)) {\n\t\t\t\tif (i - vis[cur] + 1 < r - l + 1) {\n\t\t\t\t\tl = vis[cur];\n\t\t\t\t\tr = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvis[cur] = i + 1;\n\t\t}\n\t\tif (l == -1) {\n\t\t\tcout << -1 << endl;\n\t\t} else {\n\t\t\tcout << l + 1 << \" \" << r + 1 << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1296",
    "index": "D",
    "title": "Fight with Monsters",
    "statement": "There are $n$ monsters standing in a row numbered from $1$ to $n$. The $i$-th monster has $h_i$ health points (hp). You have your attack power equal to $a$ hp and your opponent has his attack power equal to $b$ hp.\n\nYou and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to $0$.\n\nThe fight with a monster happens in turns.\n\n- You hit the monster by $a$ hp. If it is dead after your hit, \\textbf{you gain one point} and you both proceed to the next monster.\n- Your opponent hits the monster by $b$ hp. If it is dead after his hit, \\textbf{nobody gains a point} and you both proceed to the next monster.\n\nYou have some secret technique to force your opponent to skip his turn. You can use this technique at most $k$ times \\textbf{in total} (for example, if there are two monsters and $k=4$, then you can use the technique $2$ times on the first monster and $1$ time on the second monster, but not $2$ times on the first monster and $3$ times on the second monster).\n\nYour task is to determine the maximum number of points you can gain if you use the secret technique optimally.",
    "tutorial": "Let's calculate the minimum number of secret technique uses we need to kill each of the monsters. Let the current monster has $h$ hp. Firstly, it is obvious that we can take $h$ modulo $a+b$ (except one case). If it becomes zero, let's \"rollback\" it by one pair of turns. Then the number of uses of the secret technique we need is $\\lceil\\frac{h}{a}\\rceil - 1$. Let's sort all $n$ monsters by this value and take the \"cheapest\" set of monsters (prefix of the sorted array) with the sum of values less than or equal to $k$. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, a, b, k;\n\tcin >> n >> a >> b >> k;\n\tvector<int> h(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> h[i];\n\t\th[i] %= a + b;\n\t\tif (h[i] == 0) h[i] += a + b;\n\t\th[i] = ((h[i] + a - 1) / a) - 1;\n\t}\n\tsort(h.begin(), h.end());\n\tint ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (k - h[i] < 0) break;\n\t\t++ans;\n\t\tk -= h[i];\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1296",
    "index": "E1",
    "title": "String Coloring (easy version)",
    "statement": "\\textbf{This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different}.\n\nYou are given a string $s$ consisting of $n$ lowercase Latin letters.\n\nYou have to color \\textbf{all} its characters \\textbf{one of the two colors} (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $s$).\n\nAfter coloring, you can swap \\textbf{any} two neighboring characters of the string that are colored \\textbf{different} colors. You can perform such an operation arbitrary (possibly, zero) number of times.\n\nThe goal is to make the string sorted, i.e. all characters should be in alphabetical order.\n\nYour task is to say if it is possible to color the given string so that after coloring it can become sorted by \\textbf{some} sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.",
    "tutorial": "Note that the actual problem is to divide the string into two subsequences that both of them are non-decreasing. You can note that this is true because you cannot the relative order of the elements colored in the same color, but you can write down subsequences of different colors in any order you want. In this problem, you can write the following dynamic programming: $dp_{pos, c_1, c_2}$ is $1$ if you can split the prefix of the string $s[1..pos]$ into two non-decreasing sequences such that the first one ends with the character $c_1$ and the second one - with $c_2$ (characters are numbered from $0$ to $25$), otherwise $dp_{pos, c_1, c_2}$ is zero. Initially, only $dp_{0, 0, 0} = 1$, other values are zeros. Transitions are very easy: if the current value of dp is $dp_{i, c_1, c_2}$ then we can make a transition to $dp_{i + 1, c, c_2}$ if $c \\ge c_1$ and to $dp_{i + 1, c_1, c}$ if $c \\ge c_2$. Then you can restore the answer by carrying parent values. But there is another very interesting solution. Let's go from left to right and carry two sequences $s_1$ and $s_2$. If the current character is not less than the last character of $s_1$ then let's append it to $s_1$, otherwise, if this character is not less than the last character of $s_2$ then append it to $s_2$, otherwise the answer is \"NO\". If the answer isn't \"NO\" then $s_1$ and $s_2$ are required sequences. The proof and other stuff will be in the editorial of the hard version. Time complexity: $O(n \\cdot AL^2)$ or $O(n \\cdot AL)$ or $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\tstring res;\n\tchar lst0 = 'a', lst1 = 'a';\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (s[i] >= lst0) {\n\t\t\tres += '0';\n\t\t\tlst0 = s[i];\n\t\t} else if (s[i] >= lst1) {\n\t\t\tres += '1';\n\t\t\tlst1 = s[i];\n\t\t} else {\n\t\t\tcout << \"NO\" << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << \"YES\" << endl << res << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1296",
    "index": "E2",
    "title": "String Coloring (hard version)",
    "statement": "\\textbf{This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different}.\n\nYou are given a string $s$ consisting of $n$ lowercase Latin letters.\n\nYou have to color \\textbf{all} its characters \\textbf{the minimum number of colors} (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $s$).\n\nAfter coloring, you can swap \\textbf{any} two neighboring characters of the string that are colored \\textbf{different} colors. You can perform such an operation arbitrary (possibly, zero) number of times.\n\nThe goal is to make the string sorted, i.e. all characters should be in alphabetical order.\n\nYour task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by \\textbf{some} sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.",
    "tutorial": "The solution of this problem is based on Dilworth's theorem. You can read about it on Wikipedia. In two words, this theorem says that the minimum number of non-decreasing sequences we need to cover the whole sequence equals the length of longest decreasing subsequence. Let's calculate the dynamic programming $dp_i$ - the length of longest decreasing sequence that ends in the position $i$. To recalculate this dynamic, let's carry the array $maxdp$ of length $26$, where $maxdp_c$ means the maximum value of $dp$ for the character $c$ on the prefix we already considered. So, initially all $dp_i$ are ones, all values of $maxdp$ are zeros. For the position $i$ we update $dp_i$ with $max(maxdp_{s_i + 1}, maxdp_{s_i + 2}, \\dots, maxdp_{25}) + 1$ and update $maxdp_{s_i}$ with $dp_i$. Okay, how to restore the answer? That's pretty easy. The color of the $i$-th character is exactly $dp_i$. Why it is so? If $dp_i$ becomes greater than $max(maxdp_{s_i + 1}, maxdp_{s_i + 2}, \\dots, maxdp_{25})$ then we surely need to use the new color for this character because we cannot append it to the end of any existing sequence. Otherwise, we will append it to some existing sequence (with the maximum possible number) and because it has the maximum number and we didn't update the value of $dp$ with the number of this sequence plus one, the current character is not less than the last in this sequence. Time complexity: $O(n \\cdot AL)$ or $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tstring s;\n\tcin >> n >> s;\n\t\n\tvector<int> maxdp(26);\n\tvector<int> dp(n, 1);\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int c = 25; c > s[i] - 'a'; --c) {\n\t\t\tdp[i] = max(dp[i], maxdp[c] + 1);\n\t\t}\n\t\tmaxdp[s[i] - 'a'] =  max(maxdp[s[i] - 'a'], dp[i]);\n\t}\n\t\n\tcout << *max_element(maxdp.begin(), maxdp.end()) << endl;\n\tfor (int i = 0; i < n; ++i) cout << dp[i] << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1296",
    "index": "F",
    "title": "Berland Beauty",
    "statement": "There are $n$ railway stations in Berland. They are connected to each other by $n-1$ railway sections. The railway network is connected, i.e. can be represented as an undirected tree.\n\nYou have a map of that network, so for each railway section you know which stations it connects.\n\nEach of the $n-1$ sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from $1$ to $10^6$ inclusive.\n\nYou asked $m$ passengers some questions: the $j$-th one told you three values:\n\n- his departure station $a_j$;\n- his arrival station $b_j$;\n- minimum scenery beauty along the path from $a_j$ to $b_j$ (the train is moving along the shortest path from $a_j$ to $b_j$).\n\nYou are planning to update the map and set some value $f_i$ on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.\n\nPrint any valid set of values $f_1, f_2, \\dots, f_{n-1}$, which the passengers' answer is consistent with or report that it doesn't exist.",
    "tutorial": "Firstly, let's precalculate $n$ arrays $p_1, p_2, \\dots, p_n$. The array $p_v$ is the array of \"parents\" if we run dfs from the vertex $v$. So, $p_{v, u}$ is the vertex that is the previous one before $u$ on the directed path $(v, u)$. This part can be precalculated in time $O(n^2)$ and we need it just for convenience. Initially, all values $f_j$ (beauties of the edges) are zeros. Let's consider queries in order of non-decreasing $g_i$. For the current query, let's consider the whole path $(a_i, b_i)$ and update the value $f_j$ for each $j$ on this path in the following way: $f_j = max(f_j, g_i)$. After processing all queries, let's replace all values $f_j = 0$ with $f_j = 10^6$. This part works also in time $O(n^2)$. And the last part of the solution is to check if the data we constructed isn't contradictory. We can iterate over all paths $(a_i, b_i)$ and find the minimum value $f_j$ on this path. We have to sure if it equals $g_i$. If it isn't true for at least one query, then the answer is -1. Otherwise, we can print the resulting tree. Time complexity: $O(n^2)$, but it can be done in at least $O(n \\log n)$ (I hope someone can explain this solution because I am too lazy to do it now).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nvector<int> val;\nvector<vector<pair<int, int>>> g;\n\nvoid dfs(int v, int pv, int pe, vector<pair<int, int>> &p) {\n\tp[v] = make_pair(pv, pe);\n\tfor (auto it : g[v]) {\n\t\tint to = it.first;\n\t\tint idx = it.second;\n\t\tif (to == pv) continue;\n\t\tdfs(to, v, idx, p);\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tcin >> n;\n\tg = vector<vector<pair<int, int>>>(n);\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\t--u, --v;\n\t\tg[u].push_back(make_pair(v, i));\n\t\tg[v].push_back(make_pair(u, i));\n\t}\n\t\n\tvector<vector<pair<int, int>>> p(n, vector<pair<int, int>>(n));\n\tfor (int i = 0; i < n; ++i) {\n\t\tdfs(i, -1, -1, p[i]);\n\t}\n\t\n\tval = vector<int>(n - 1, 1000000);\n\n    cin >> m;\n\tvector<pair<pair<int, int>, int>> q(m);\n\tfor (int i = 0; i < m; ++i) {\n\t\tcin >> q[i].first.first >> q[i].first.second >> q[i].second;\n\t\t--q[i].first.first;\n\t\t--q[i].first.second;\n\t}\n\tsort(q.begin(), q.end(), [&](pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) {\n\t\treturn a.second < b.second;\n\t});\n\t\n\tfor (int i = 0; i < m; ++i) {\n\t\tint u = q[i].first.first;\n\t\tint v = q[i].first.second;\n\t\twhile (v != u) {\n\t\t\tint pv = p[u][v].first;\n\t\t\tint pe = p[u][v].second;\n\t\t\tval[pe] = q[i].second;\n\t\t\tv = pv;\n\t\t}\n\t}\n\t\n\tfor (int i = 0; i < m; ++i) {\n\t\tint u = q[i].first.first;\n\t\tint v = q[i].first.second;\n\t\tint mx = 1000000;\n\t\twhile (v != u) {\n\t\t\tint pv = p[u][v].first;\n\t\t\tint pe = p[u][v].second;\n\t\t\tmx = min(mx, val[pe]);\n\t\t\tv = pv;\n\t\t}\n\t\tif (mx != q[i].second) {\n\t\t\tcout << -1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tcout << val[i] << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1299",
    "index": "A",
    "title": "Anu Has a Function",
    "statement": "Anu has created her own function $f$: $f(x, y) = (x | y) - y$ where $|$ denotes the bitwise OR operation. For example, $f(11, 6) = (11|6) - 6 = 15 - 6 = 9$. It can be proved that for any nonnegative numbers $x$ and $y$ value of $f(x, y)$ is also nonnegative.\n\nShe would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.\n\nA value of an array $[a_1, a_2, \\dots, a_n]$ is defined as $f(f(\\dots f(f(a_1, a_2), a_3), \\dots a_{n-1}), a_n)$ (see notes). You are given an array with \\textbf{not necessarily distinct} elements. How should you reorder its elements so that the value of the array is maximal possible?",
    "tutorial": "If you work on the bits, you may see $f(a, b)$ can easily be written as $a \\& (\\sim b)$. And so, value of an array $[a_1, a_2, \\dots, a_n]$ would be $a_1 \\& (\\sim a_2) \\& \\dots (\\sim a_n)$, meaning that if we are to reorder, only the first element matters. By keeping prefix and suffix $AND$ after we apply $\\sim$ to the given array, we can find $(\\sim a_2) \\& \\dots (\\sim a_n)$ in $O(1)$. Or notice that if a bit was to be in the answer, it must be in $a_1$ and not in any of $a_2, a_3, \\dots a_n$. So you can start from the most significant bit and check if that bit can be in the answer to find $a_1$, resulting in $O(n)$.",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1299",
    "index": "B",
    "title": "Aerodynamic",
    "statement": "Guy-Manuel and Thomas are going to build a polygon spaceship.\n\nYou're given a \\textbf{strictly convex} (i. e. no three points are collinear) polygon $P$ which is defined by coordinates of its vertices. Define $P(x,y)$ as a polygon obtained by translating $P$ by vector $\\overrightarrow {(x,y)}$. The picture below depicts an example of the translation:\n\nDefine $T$ as a set of points which is the union of all $P(x,y)$ such that the origin $(0,0)$ lies in $P(x,y)$ (both strictly inside and on the boundary). There is also an equivalent definition: a point $(x,y)$ lies in $T$ only if there are two points $A,B$ in $P$ such that $\\overrightarrow {AB} = \\overrightarrow {(x,y)}$. One can prove $T$ is a polygon too. For example, if $P$ is a regular triangle then $T$ is a regular hexagon. At the picture below $P$ is drawn in black and some $P(x,y)$ which contain the origin are drawn in colored:\n\nThe spaceship has the best aerodynamic performance if $P$ and $T$ are similar. Your task is to check whether the polygons $P$ and $T$ are similar.",
    "tutorial": "$T$ has the central symmetry: indeed, if $P(x,y)$ covers $(0,0)$ and $(x_0,y_0)$ then $P(x-x_0,y-y_0)$ covers $(-x_0,-y_0)$ and $(0,0)$. So the answer for polygons which don't have the sentral symmetry is NO. Let's prove if $P$ has the central symmetry then the answer is YES. Translate $P$ in such a way that the origin becomes its center of symmetry. Let's show that the homothety with the center at the origin and the coefficient $2$ transforms $P$ into $T$: if a point $(x_0,y_0)$ lies in $P$, then $P(x_0,y_0)$ covers both $(0,0)$ and $(2x_0,2y_0)$; if a point $(x_0,y_0)$ doesn't lie in $P$, then consider a segment connecting the center of symmetry of the polygon $P$ (also known as origin) and $(x_0,y_0)$; it crosses some side of $P$; WLOG, assume this side is parallel to the $x$-axis and lies in the line $y=y_1, y_1>0$ (otherwise we can rotate the plane). Since the polygon is convex, it completely lies in the stripe $y \\in [-y_1;y_1]$, that's why there isn't any vector which connects two points in $P$ with a $y$-coordinate greater than $2y_1$. Since $2y_0 > 2y_1$, there isn't any vector which connects two points in $P$ with a $y$-coordinate equal to $2y_0$, that's why the point $(2x_0,2y_0)$ doesn't lie in $T$. To find whether a polygon has the central symmetry, check whether the midpoints of segments connecting the opposite vertexes coincide; if a polygon has an odd number of vertexes it can't have the central symmetry.",
    "tags": [
      "geometry"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1299",
    "index": "C",
    "title": "Water Balance",
    "statement": "There are $n$ water tanks in a row, $i$-th of them contains $a_i$ liters of water. The tanks are numbered from $1$ to $n$ from left to right.\n\nYou can perform the following operation: choose some subsegment $[l, r]$ ($1\\le l \\le r \\le n$), and redistribute water in tanks $l, l+1, \\dots, r$ evenly. In other words, replace each of $a_l, a_{l+1}, \\dots, a_r$ by $\\frac{a_l + a_{l+1} + \\dots + a_r}{r-l+1}$. For example, if for volumes $[1, 3, 6, 7]$ you choose $l = 2, r = 3$, new volumes of water will be $[1, 4.5, 4.5, 7]$. \\textbf{You can perform this operation any number of times}.\n\nWhat is the lexicographically smallest sequence of volumes of water that you can achieve?\n\nAs a reminder:\n\nA sequence $a$ is lexicographically smaller than a sequence $b$ of the same length if and only if the following holds: in the first (leftmost) position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.",
    "tutorial": "Let's try to make the operation simpler. When we apply the operation, only the sum of the segment matters. And so let's instead define the operation on prefix sum array: Replace each of $p_l, p_{l+1}, \\dots, p_r$ by $p_i = p_{l-1} + \\frac{p_r - p_{l - 1} }{r-l+1} \\cdot (i - l + 1)$. You may see how similar it is to a line function. Hence we get the idea to plot points $(i, p_i)$ ($(0, p_0 = 0)$ included), and our operation is just drawing a line between $2$ points on integer $x$ coordinates. Nicely if sequence $a$ is lexicographically smaller than sequence $b$, then prefix sum array of $a$ is smaller than prefix sum array of $b$. So we need to find the lexicographically smallest array $p$. And then it is easy to see the lexicographically smallest sequence $p$ will be the lower part of the convex hull. If you're interested you can solve IMO 2018 SL A4 by plotting similar points. I have written my solutionhere",
    "tags": [
      "data structures",
      "geometry",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1299",
    "index": "D",
    "title": "Around the World",
    "statement": "Guy-Manuel and Thomas are planning $144$ trips around the world.\n\nYou are given a simple weighted undirected connected graph with $n$ vertexes and $m$ edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than $3$ which passes through the vertex $1$. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.\n\nBut the trips with cost $0$ aren't exciting.\n\nYou may choose any subset of edges incident to the vertex $1$ and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to $0$ which passes through the vertex $1$ in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo $10^9+7$.",
    "tutorial": "It's common knowledge that in an undirected graph there is some subset (not necessarily unique) of simple cycles called basis such that any Eulerian subgraph (in connected graphs also known as a cyclic path) is a xor-combination of exactly one subset of basis cycles. In a given connected graph consider any spanning tree; any edge which isn't in that spanning tree forms a cycle with some tree's edges of some cost $c$. These cycles form the basis. A cost of a cyclic path is an XOR of costs of basis cycles that form this path. Now we can move from cycle space to the space of $5$-dimensional vectors $\\mathbb{Z}_2^5$. If the costs of basis cycles are linear dependent, then there is a cycle of cost $0$, else they form the basis of some subspace of $\\mathbb{Z}_2^5$. In the given graph there are two types of \"components\" connected to $1$, and after removing the edges each component contributes some subspace (possibly an empty one); these subspaces shouldn't intersect. These two types are components connected with an edge and components connected with two edges: In the first picture, the basis cycles are formed by the blue edges. We can cut the edge incident to $1$ or keep it; if we don't cut that edge, this component contributes a subspace formed by costs of basis cycles unless they are linear dependent, else it contributes the empty subspace. In the second picture, the basis cycles are formed by the blue edges and the red edge. We can cut both edges, and then this component contributes an empty subspace; if we cut one edge, the red edge moves to the spanning tree and no longer form a basis cycle, so this component contributes a subspace formed by costs of basis cycles formed by blue edges; if we don't cut any edges, then this component contributes a subspace formed by costs of basis cycles formed by blue and red edges. If any choice leads to keeping a set of linear dependent basis cycles' costs, then this choice is invalid. Now for every component, we have from $1$ to $4$ valid choices of choosing the contributing subspace. There are $374$ subspaces of $\\mathbb{Z}_2^5$, which can be precalculated as well as their sums. Now we can calculate a dp $dp_{i,j}$ - the number of ways to get the subspace $j$ using the first $i$ components. The transitions are obvious: if we can get the subspace $X$ at the $i$-th component, then for each existing subspace $Y$, if $X$ and $Y$ don't intersect, do $dp_{i,X+Y} := dp_{i,X+Y} + dp_{i-1,Y}$, where $X+Y$ is the sum of subspaces. The answer is a sum of dp values for the last component.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dfs and similar",
      "dp",
      "graphs",
      "math",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1299",
    "index": "E",
    "title": "So Mean",
    "statement": "\\textbf{This problem is interactive}.\n\nWe have hidden a permutation $p_1, p_2, \\dots, p_n$ of numbers from $1$ to $n$ from you, where $n$ \\textbf{is even}. You can try to guess it using the following queries:\n\n$?$ $k$ $a_1$ $a_2$ $\\dots$ $a_k$.\n\nIn response, you will learn if the average of elements with indexes $a_1, a_2, \\dots, a_k$ is an integer. In other words, you will receive $1$ if $\\frac{p_{a_1} + p_{a_2} + \\dots + p_{a_k}}{k}$ is integer, and $0$ otherwise.\n\nYou have to guess the permutation. You can ask \\textbf{not more than $18n$ queries}.\n\nNote that permutations $[p_1, p_2, \\dots, p_k]$ and $[n + 1 - p_1, n + 1 - p_2, \\dots, n + 1 - p_k]$ are indistinguishable. Therefore, \\textbf{you are guaranteed that $p_1 \\le \\frac{n}{2}$}.\n\nNote that the permutation $p$ is fixed before the start of the interaction and doesn't depend on your queries. In other words, \\textbf{interactor is not adaptive}.\n\nNote that you don't have to minimize the number of queries.",
    "tutorial": "Let's solve this problem in several steps. First, let's ask a query about each group of $n-1$ numbers. Note that $1 + 2 + \\dots + (i-1) + (i+1) + \\dots + n = \\frac{n(n+1)}{2} - i \\equiv \\frac{1\\cdot 2}{2} - i \\bmod (n-1)$. Therefore, answer will be YES only for numbers $1$ and $n$. Find the positions where $1$ and $n$ lie, assign one of them to be $1$ and the other one to be $n$ (it doesn't matter how to assign $1$ and $n$ to these $2$ spots, as permutations $[p_1, p_2, \\dots, p_k]$ and $[n + 1 - p_1, n + 1 - p_2, \\dots, n + 1 - p_k]$ are indistinguishable). $n$ queries. First, let's ask a query about each group of $n-1$ numbers. Note that $1 + 2 + \\dots + (i-1) + (i+1) + \\dots + n = \\frac{n(n+1)}{2} - i \\equiv \\frac{1\\cdot 2}{2} - i \\bmod (n-1)$. Therefore, answer will be YES only for numbers $1$ and $n$. Find the positions where $1$ and $n$ lie, assign one of them to be $1$ and the other one to be $n$ (it doesn't matter how to assign $1$ and $n$ to these $2$ spots, as permutations $[p_1, p_2, \\dots, p_k]$ and $[n + 1 - p_1, n + 1 - p_2, \\dots, n + 1 - p_k]$ are indistinguishable). $n$ queries. Note that knowing $1$, we can find parity of every other number. Indeed, just ask about $1$ and $p_i$, if answer is YES, $p_i$ is odd, else it is even. $n$ queries. Note that knowing $1$, we can find parity of every other number. Indeed, just ask about $1$ and $p_i$, if answer is YES, $p_i$ is odd, else it is even. $n$ queries. Suppose that we have found numbers $1, 2, \\dots, k, n-k+1, n-k+2, \\dots, n$ at some point. Let's find numbers $k+1$ and $n-k$. Consider all numbers except $1, 2, \\dots, k, n-k+1, n-k+2, \\dots, n$ now. Ask a query about each subset of $n - 2k - 1$ numbers among them. Again, we can see that we will get answer YES only when we omit $k+1$ and $n-k$. Indeed, $k+1 + \\dots (i-1) + (i+1) + \\dots + (n-k) = k\\cdot (n - 2k - 1) + \\frac{(n-2k)(n-2k+1)}{2} - (i-k) \\equiv 1 - (i-k) \\bmod (n-2k-1)$, which is $0$ only for $i = k+1$ and $n-k$. Now that we know parities of all numbers, we can distinguish between $k+1$ and $n-k$. So, we determined $k+1$ and $n-k$ in $n - 2k$ queries. Suppose that we have found numbers $1, 2, \\dots, k, n-k+1, n-k+2, \\dots, n$ at some point. Let's find numbers $k+1$ and $n-k$. Consider all numbers except $1, 2, \\dots, k, n-k+1, n-k+2, \\dots, n$ now. Ask a query about each subset of $n - 2k - 1$ numbers among them. Again, we can see that we will get answer YES only when we omit $k+1$ and $n-k$. Indeed, $k+1 + \\dots (i-1) + (i+1) + \\dots + (n-k) = k\\cdot (n - 2k - 1) + \\frac{(n-2k)(n-2k+1)}{2} - (i-k) \\equiv 1 - (i-k) \\bmod (n-2k-1)$, which is $0$ only for $i = k+1$ and $n-k$. Now that we know parities of all numbers, we can distinguish between $k+1$ and $n-k$. So, we determined $k+1$ and $n-k$ in $n - 2k$ queries. Note that this already means that we can solve our problem in $n + n + (n - 2) + (n - 4) + (n - 6) \\dots + (n - (n-2))$ queries, which is $\\frac{n^2 + 6n}{4}$ queries. Unfortunately, this is much larger than we are allowed. However, we will use this method for $n\\le 8$. Note that this already means that we can solve our problem in $n + n + (n - 2) + (n - 4) + (n - 6) \\dots + (n - (n-2))$ queries, which is $\\frac{n^2 + 6n}{4}$ queries. Unfortunately, this is much larger than we are allowed. However, we will use this method for $n\\le 8$. Let's use the procedure above to find numbers $1, 2, 3, 4, n-3, n-2, n-1, n$. We have used $5n - 12$ queries by now, but let's round this up to $5n$. Now, we are going to find the remainders of each element of permutation modulo $3$, $5$, $7$, $8$. As $3\\cdot 5 \\cdot 7 \\cdot 8 = 840 \\ge 800 \\ge n$, we will be able to restore each number uniquely. Let's use the procedure above to find numbers $1, 2, 3, 4, n-3, n-2, n-1, n$. We have used $5n - 12$ queries by now, but let's round this up to $5n$. Now, we are going to find the remainders of each element of permutation modulo $3$, $5$, $7$, $8$. As $3\\cdot 5 \\cdot 7 \\cdot 8 = 840 \\ge 800 \\ge n$, we will be able to restore each number uniquely. To find remainders modulo $3$, we will first ask each number with already found $1$ and $2$. We will get YES only for numbers, divisible by $3$. Next, we will ask each number whose remainder under division by $3$ we haven't yet found with $1$, $3$. This way we find all the numbers which give the remainder $2$. All others give the remainder $1$. We spend $n + \\frac{2n}{3}$ queries. To find remainders modulo $3$, we will first ask each number with already found $1$ and $2$. We will get YES only for numbers, divisible by $3$. Next, we will ask each number whose remainder under division by $3$ we haven't yet found with $1$, $3$. This way we find all the numbers which give the remainder $2$. All others give the remainder $1$. We spend $n + \\frac{2n}{3}$ queries. Similarly, we find remainders mod $5$ and mod $7$. For mod $5$, at step $i$ ask each number whose remainder we don't know yet with $n, n-2, n-3, i$ (for $i$ from $1$ to $4$). We spend $n + \\frac{4n}{5} + \\frac{3n}{5} + \\frac{2n}{5}$ queries. For mod $7$, first ask all numbers whose remainders we don't know yet with $\\{1, 2, 3, n-3, n-2, n-1\\}$, then with $\\{1, 2, 3, n-3, n-2, n\\}$, $\\{1, 2, 3, n-3, n-1, n\\}$, $\\{1, 2, 3, n-2, n-1, n\\}$, $\\{1, 2, 4, n-2, n-1, n\\}$, $\\{1, 3, 4, n-2, n-1, n\\}$ (sums of all these sets are different mod $7$). We spend $n + \\frac{6n}{7} + \\dots + \\frac{2n}{7}$ queries. Similarly, we find remainders mod $5$ and mod $7$. For mod $5$, at step $i$ ask each number whose remainder we don't know yet with $n, n-2, n-3, i$ (for $i$ from $1$ to $4$). We spend $n + \\frac{4n}{5} + \\frac{3n}{5} + \\frac{2n}{5}$ queries. For mod $7$, first ask all numbers whose remainders we don't know yet with $\\{1, 2, 3, n-3, n-2, n-1\\}$, then with $\\{1, 2, 3, n-3, n-2, n\\}$, $\\{1, 2, 3, n-3, n-1, n\\}$, $\\{1, 2, 3, n-2, n-1, n\\}$, $\\{1, 2, 4, n-2, n-1, n\\}$, $\\{1, 3, 4, n-2, n-1, n\\}$ (sums of all these sets are different mod $7$). We spend $n + \\frac{6n}{7} + \\dots + \\frac{2n}{7}$ queries. Now time to find remainders mod $4$. We already know all remainders mod $2$. To distinguish $4k$ from $4k+2$, ask with $1, 2, 3$. To distinguish $4k+1$ from $4k+3$, ask with $1, 2, 4$. We spend $n$ queries. Now time to find remainders mod $8$. We already know all remainders mod $4$. Similarly, to distinguish $8k$ from $8k+4$, ask with $n, n-1, n-2, n-3, 1, 2, 3$, $\\dots$, to distinguish $8k+3$ from $8k+7$, ask with $n, n-1, n-2, n-3, 1, 2, 4$. We spend $n$ queries. Now time to find remainders mod $4$. We already know all remainders mod $2$. To distinguish $4k$ from $4k+2$, ask with $1, 2, 3$. To distinguish $4k+1$ from $4k+3$, ask with $1, 2, 4$. We spend $n$ queries. Now time to find remainders mod $8$. We already know all remainders mod $4$. Similarly, to distinguish $8k$ from $8k+4$, ask with $n, n-1, n-2, n-3, 1, 2, 3$, $\\dots$, to distinguish $8k+3$ from $8k+7$, ask with $n, n-1, n-2, n-3, 1, 2, 4$. We spend $n$ queries. Overall, we spend $5n + (n + \\frac{2n}{3}) + (n + \\frac{4n}{5} + \\frac{3n}{5} + \\frac{2n}{5}) + (n + \\frac{6n}{7} + \\dots + \\frac{2n}{7}) + n + n \\sim 15.324 n$. Note that this bound is easy to optimize (for example, determine all remainders mod $3$ and $4$ from $1, 2, n, n-1$, and after that check only candidates which work mod $12$ in phase $5$. This will reduce the number of operations to $13.66 n$ operations. Of course, a lot of other optimizations are possible.",
    "tags": [
      "interactive",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1300",
    "index": "A",
    "title": "Non-zero",
    "statement": "Guy-Manuel and Thomas have an array $a$ of $n$ integers [$a_1, a_2, \\dots, a_n$]. In one step they can add $1$ to any element of the array. Formally, in one step they can choose any integer index $i$ ($1 \\le i \\le n$) and do $a_i := a_i + 1$.\n\nIf either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.\n\nWhat is the minimum number of steps they need to do to make both the sum and the product of all elements in the array \\textbf{different from zero}? Formally, find the minimum number of steps to make $a_1 + a_2 +$ $\\dots$ $+ a_n \\ne 0$ and $a_1 \\cdot a_2 \\cdot$ $\\dots$ $\\cdot a_n \\ne 0$.",
    "tutorial": "While there are any zeros in the array, the product will be zero, so we should add $1$ to each zero. Now, if the sum is zero, we should add $1$ to any positive number, so the sum becomes nonzero. So the answer is the number of zeroes in the array plus $1$ if the sum of numbers is equal to zero after adding $1$ to zeros.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1300",
    "index": "B",
    "title": "Assigning to Classes",
    "statement": "\\textbf{Reminder: the median} of the array $[a_1, a_2, \\dots, a_{2k+1}]$ of odd number of elements is defined as follows: let $[b_1, b_2, \\dots, b_{2k+1}]$ be the elements of the array in the sorted order. Then median of this array is equal to $b_{k+1}$.\n\nThere are $2n$ students, the $i$-th student has skill level $a_i$. It's \\textbf{not guaranteed} that all skill levels are distinct.\n\nLet's define \\textbf{skill level of a class} as the median of skill levels of students of the class.\n\nAs a principal of the school, you would like to assign each student to one of the $2$ classes such that each class has \\textbf{odd number of students} (not divisible by $2$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.\n\nWhat is the minimum possible absolute difference you can achieve?",
    "tutorial": "Let's sort the array. From now on, $a_1 \\le a_2 \\dots \\le a_{2n}$. Consider any partition. Suppose that the first class has $2k+1$ students, and the skill level of this class is $a_i$, and the second class had $2l+1$ students, and the skill level of this class is $a_j$, where $(2k + 1) + (2l + 1) = 2n \\implies k + l = n-1$. Without losing generality, $i<j$. At least $n+1$ students have skill level at least $a_i$. Indeed, as $a_i$ is a median of his class, he and $k$ other students have skill level at least $a_i$. As $a_j\\ge a_i$ and at least $l$ other students of the second class have skill level at least $a_j\\ge a_i$, we get at least $k + l + 2 = n + 1$ students (including $a_i$) with skill level at least $a_i$. Therefore, $a_i\\le a_n$. Similarly, we get that at least $n + 1$ students have skill level at most $a_j$. Therefore, $a_j\\ge a_{n+1}$. So, $|a_j - a_i| \\ge a_{n+1} - a_n$. However, $a_{n+1} - a_n$ is achievable. Let's put student $a_n$ into the class alone, and all other students into other class. $a_{n+1}$ will be the median skill level of that class, so the absolute difference will be exactly $a_{n+1} - a_n$. Therefore, it's enough to sort the array and to output the difference between two middle elements.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1301",
    "index": "A",
    "title": "Three Strings",
    "statement": "You are given three strings $a$, $b$ and $c$ of the same length $n$. The strings consist of lowercase English letters only. The $i$-th letter of $a$ is $a_i$, the $i$-th letter of $b$ is $b_i$, the $i$-th letter of $c$ is $c_i$.\n\nFor every $i$ ($1 \\leq i \\leq n$) you \\textbf{must} swap (i.e. exchange) $c_i$ with either $a_i$ or $b_i$. So in total you'll perform exactly $n$ swap operations, each of them either $c_i \\leftrightarrow a_i$ or $c_i \\leftrightarrow b_i$ ($i$ iterates over all integers between $1$ and $n$, inclusive).\n\nFor example, if $a$ is \"code\", $b$ is \"true\", and $c$ is \"help\", you can make $c$ equal to \"crue\" taking the $1$-st and the $4$-th letters from $a$ and the others from $b$. In this way $a$ becomes \"hodp\" and $b$ becomes \"tele\".\n\nIs it possible that after these swaps the string $a$ becomes exactly the same as the string $b$?",
    "tutorial": "For every $i$ $(1 \\leq i \\leq n)$ where $n$ is the length of the strings. If $c_i$ is equal to $a_i$ we can swap it with $b_i$ or if $c_i$ is equal to $b_i$ we can swap it with $a_i$, otherwise we can't swap it. So we only need to check that $c_i$ is equal $a_i$ or $c_i$ is equal to $b_i$. Complexity is $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define oo 1000000000\\n#define mod 998244353\\nconst int N = 500000;\\nstring a , b , c;\\n\\nvoid solve(){\\n    cin >> a >> b >> c;\\n    for(int i = 0 ;i < (int)a.size();i++){\\n        if(c[i] != a[i] && c[i] != b[i]){\\n            puts(\\\"NO\\\");\\n            return;\\n        }\\n    }\\n    puts(\\\"YES\\\");\\n    return;\\n}\\n\\nint main(){\\n    int t;\\n    cin >> t;\\n    while(t--){\\n        solve();\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1301",
    "index": "B",
    "title": "Motarack's Birthday",
    "statement": "Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $a$ of $n$ non-negative integers.\n\nDark created that array $1000$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $k$ ($0 \\leq k \\leq 10^{9}$) and replaces all missing elements in the array $a$ with $k$.\n\nLet $m$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $|a_i - a_{i+1}|$ for all $1 \\leq i \\leq n - 1$) in the array $a$ after Dark replaces all missing elements with $k$.\n\nDark should choose an integer $k$ so that $m$ is minimized. Can you help him?",
    "tutorial": "Let's take all non missing elements that are adjacent to at least one missing element, we need to find a value $k$ that minimises the maximum absolute difference between $k$ and these values. The best $k$ is equal to (minimum value + maximum value) / 2. Then we find the maximum absolute difference between all adjacent pairs. Complexity is $O(n)$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define oo 1000000010\\n#define mod 1000000007\\nconst int N = 300010;\\nint n , arr[N] ; \\n\\nvoid solve(){\\n    int mn = oo , mx = -oo;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor(int i=0;i<n;i++){\\n\\t\\tscanf(\\\"%d\\\",&arr[i]);\\n\\t}\\n\\tfor(int i = 0;i<n;i++){\\n\\t\\tif(i > 0 && arr[i] == -1 && arr[i - 1] != -1)\\n\\t\\t\\tmn = min(mn , arr[i - 1]) , mx = max(mx , arr[i - 1]);\\n\\t\\tif(i < n - 1 && arr[i] == - 1 && arr[i + 1] != -1)\\n\\t\\t\\tmn = min(mn , arr[i + 1]) , mx = max(mx , arr[i + 1]);\\n\\t}\\n\\tint res = (mx + mn) / 2;\\n\\tint ans = 0;\\n\\tfor(int i=0;i<n;i++){\\n\\t\\tif(arr[i] == -1)\\n\\t\\t\\tarr[i] = res;\\n\\t\\tif(i)\\n\\t\\t\\tans = max(ans,abs(arr[i] - arr[i - 1]));\\n\\t}\\n\\tprintf(\\\"%d %d\\\\n\\\",ans,res);\\n}\\n\\n\\nint main(){\\n\\tint t;\\n\\tcin >> t;\\n\\twhile(t--){\\n\\t    solve();\\n\\t}\\n\\treturn 0;\\n}\"",
    "tags": [
      "binary search",
      "greedy",
      "ternary search"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1301",
    "index": "C",
    "title": "Ayoub's function",
    "statement": "Ayoub thinks that he is a very smart person, so he created a function $f(s)$, where $s$ is a binary string (a string which contains only symbols \"0\" and \"1\"). The function $f(s)$ is equal to the number of substrings in the string $s$ that contains at least one symbol, that is equal to \"1\".\n\nMore formally, $f(s)$ is equal to the number of pairs of integers $(l, r)$, such that $1 \\leq l \\leq r \\leq |s|$ (where $|s|$ is equal to the length of string $s$), such that at least one of the symbols $s_l, s_{l+1}, \\ldots, s_r$ is equal to \"1\".\n\nFor example, if $s = $\"01010\" then $f(s) = 12$, because there are $12$ such pairs $(l, r)$: $(1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5)$.\n\nAyoub also thinks that he is smarter than Mahmoud so he gave him two integers $n$ and $m$ and asked him this problem. For all binary strings $s$ of length $n$ which contains exactly $m$ symbols equal to \"1\", find the maximum value of $f(s)$.\n\nMahmoud couldn't solve the problem so he asked you for help. Can you help him?",
    "tutorial": "We can calculate the number of sub-strings that has at least one symbol equals to \"1\" like this: $f(s)$ $=$ (number of all sub-strings) $-$ (number of sub-strings that doesn't have any symbol equals to \"1\"). if the size of $s$ is equal to $n$, $f(s)$ $=$ $\\frac{n\\cdot(n+1)}{2}$ $-$ (number of sub-strings that doesn't have any symbol equals to \"1\"). if we want to calculate them, we only need to find every continuous sub-string of 0's if it's length was $l$, then we subtract $\\frac{l\\cdot(l+1)}{2}$. now we have a string contains $(n - m)$ \"0\" symobol, and we want to divide these symbols into $(m+1)$ groups so that the summation of $\\frac{l\\cdot(l+1)}{2}$ for every group is minimised. The best way is to divide them into equal groups or as equal as possible. let $z$ be the number of zeroes in the string, $z=(n - m)$, and g be the number of groups, $g=m+1$. let $k$ equal to $\\lfloor$ $\\frac{z}{g}$ $\\rfloor$. we should give every group $k$ zeroes, except for the first $(z\\mod g)$ groups, we should give them $k+1$ zeroes. So the answer is $\\frac{n.(n+1)}{2}$ $-$ $\\frac{k.(k+1)}{2} \\cdot g$ $-$ $(k + 1) \\cdot (z\\mod g)$. Complexity is $O(1)$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define oo 1000000010\\n#define mod 1000000007\\nconst int N = 1010;\\n\\n\\nvoid solve(){\\n\\tint n , m;\\n\\tscanf(\\\"%d%d\\\",&n,&m);\\n\\tlong long ans = (long long)n * (long long)(n + 1) / 2LL;\\n\\tint z = n - m;\\n\\tint k = z / (m + 1);\\n\\tans -= (long long)(m + 1) * (long long)k * (long long)(k + 1) / 2LL;\\n\\tans -= (long long)(z % (m + 1)) * (long long)(k + 1);\\n\\tprintf(\\\"%lld\\\\n\\\",ans);\\n}\\n\\nint main(){\\n\\tint t;\\n\\tcin >> t;\\n\\twhile(t--){\\n\\t\\tsolve();\\n\\t}\\t\\n\\treturn 0;\\n}\"",
    "tags": [
      "binary search",
      "combinatorics",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1301",
    "index": "D",
    "title": "Time to Run",
    "statement": "Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.\n\nIn order to lose weight, Bashar is going to run for $k$ kilometers. Bashar is going to run in a place that looks like a grid of $n$ rows and $m$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $(4 n m - 2n - 2m)$ roads.\n\nLet's take, for example, $n = 3$ and $m = 4$. In this case, there are $34$ roads. It is the picture of this case (arrows describe roads):\n\nBashar wants to run by these rules:\n\n- He starts at the top-left cell in the grid;\n- In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $i$ and in the column $j$, i.e. in the cell $(i, j)$ he will move to:\n\n- in the case 'U' to the cell $(i-1, j)$;\n- in the case 'D' to the cell $(i+1, j)$;\n- in the case 'L' to the cell $(i, j-1)$;\n- in the case 'R' to the cell $(i, j+1)$;\n\n- He wants to run exactly $k$ kilometers, so he wants to make exactly $k$ moves;\n- Bashar can finish in any cell of the grid;\n- He can't go out of the grid so at any moment of the time he should be on some cell;\n- Bashar doesn't want to get bored while running so he must \\textbf{not} visit the same road twice. \\textbf{But he can visit the same cell any number of times}.\n\nBashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.\n\nYou should give him $a$ steps to do and since Bashar can't remember too many steps, $a$ should not exceed $3000$. In every step, you should give him an integer $f$ and a string of moves $s$ of length at most $4$ which means that he should repeat the moves in the string $s$ for $f$ times. He will perform the steps in the order you print them.\n\nFor example, if the steps are $2$ RUD, $3$ UUL then the moves he is going to move are RUD $+$ RUD $+$ UUL $+$ UUL $+$ UUL $=$ RUDRUDUULUULUUL.\n\nCan you help him and give him a correct sequence of moves such that the total distance he will run is equal to $k$ kilometers or say, that it is impossible?",
    "tutorial": "A strategy that guarantees that you can visit all the edges exactly once: 1- keep going right until you reach the last column in the first row. 2- keep going left until you reach the first column in the first row again. 3- go down. 4- keep going right until you reach the last column in the current row. 5- keep going {up, down, left} until you reach the first column in the current row again. 6- if you were at the last row, just keep going up until you reach the top left cell again, otherwise repeat moves 3, 4 and 5. We need only to take the first $k$ moves, and we can print them in about $3 \\cdot n$ steps. complexity $O(n)$",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define oo 1000000000\\n#define mod 998244853\\nconst int N = 100010;\\n\\nvector< pair< int , string > > v , v2;\\n\\nint n , m , k , all = 0 , cur;\\n\\nstring tmp;\\n\\nvoid fix(vector< pair< int , string > > &v){\\n    v2 = v;\\n    v.clear();\\n    for(int i = 0 ;i < (int)v2.size();i++){\\n        if(v2[i].first != 0)\\n            v.push_back(v2[i]);\\n    }\\n}\\n\\nint main(){\\n    scanf(\\\"%d%d%d\\\",&n,&m,&k);\\n    for(int i = 1;i <= n;i++){\\n        v.push_back(make_pair(m - 1 , \\\"R\\\"));\\n        all += (v.back().first * (int)v.back().second.size());\\n        if(i == 1)\\n            v.push_back(make_pair(m - 1 , \\\"L\\\"));\\n        else\\n            v.push_back(make_pair(m - 1 , \\\"UDL\\\"));\\n        all += (v.back().first * (int)v.back().second.size());\\n        if(i == n)\\n            v.push_back(make_pair(n - 1 , \\\"U\\\"));\\n        else\\n            v.push_back(make_pair(1 , \\\"D\\\"));\\n        all += (v.back().first * (int)v.back().second.size());\\n    }\\n    if(all < k){\\n        puts(\\\"NO\\\");\\n        return 0;\\n    }\\n    while(all > k){\\n        tmp = v.back().second;\\n        cur = (v.back().first * (int)v.back().second.size());\\n        v.pop_back();\\n        all -= cur;\\n        if(all >= k)\\n            continue;\\n        cur = k - all;\\n        if(cur / (int)tmp.size() > 0) v.push_back(make_pair(cur / (int)tmp.size() , tmp));\\n        tmp.resize(cur % (int)tmp.size());\\n        if((int)tmp.size() > 0) v.push_back(make_pair(1,tmp));\\n        all = k;\\n    }\\n    puts(\\\"YES\\\");\\n    fix(v);\\n    printf(\\\"%d\\\\n\\\",(int)v.size());\\n    for(int i = 0 ;i < (int)v.size();i++){\\n        printf(\\\"%d %s\\\\n\\\",v[i].first,v[i].second.c_str());\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1301",
    "index": "E",
    "title": "Nanosoft",
    "statement": "Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.\n\nThe logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.\n\nAn Example of some correct logos:\n\nAn Example of some incorrect logos:\n\nWarawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of $n$ rows and $m$ columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').\n\nAdhami gave Warawreh $q$ options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is $0$.\n\nWarawreh couldn't find the best option himself so he asked you for help, can you help him?",
    "tutorial": "For each cell, we will calculate the maximum size of a Nanosoft logo in which it is the bottom right cell, in the top left square. The cell marked with $x$ in this picture: If we had a grid like this: If we take the cell in the second row, second column, it can make a Nanosoft logo with size $4 \\times 4$, being the bottom right cell in the top left square. We can calculate the answer for every cell using binary search , and checking every sub-square using 2D cumulative sum. Now we build a 2D array that contains that previous calculated answer, lets call it $val[n][m]$. For the previous picture $val$ will be like this: Now for each query we can do binary search on its answer. We check the current mid this way: The mid will tell us the length of one of the sides divided by 2. Like if mid = 2, the area of the square we are checking is $(4 \\cdot 4 = 16)$. Now we should check the maximum element in the 2D array val, in the 2D range: $(r_1 + mid - 1, c_1 + mid - 1,r_2 - mid , c_2 - mid)$. The current mid is correct if the maximum element in that 2D range is greater than or equal to $(4 \\cdot mid \\cdot mid)$. We can get the maximum value in a 2D range using 2D sparse table, with build in $O(n \\cdot m \\cdot \\log{n} \\cdot \\log{m})$ and query in $O(1)$. total Complexity is $O(n \\cdot m \\cdot \\log{n} \\cdot \\log{m} + q \\cdot \\log{m})$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define oo 1000000010\\n#define mod 1000000007\\nconst int N = 510 , LOG = 10;\\nchar grid[N][N];\\nint val[N][N] , sum[N][N][4];\\nint st[N][N][LOG][LOG] , lg[N];\\nint n , q , m , r1 , c1 , r2, c2 , nr , nc;\\n\\nstring S = \\\"RGYB\\\";\\nint dr[4] = {0 , 0 , 1 , 1};\\nint dc[4] = {0 , 1 , 0 , 1};\\n\\ninline bool check(int r1,int c1,int r2,int c2,int k){\\n    r1++,c1++,r2++,c2++;\\n    return ((sum[r2][c2][k] - sum[r1 - 1][c2][k] - sum[r2][c1 - 1][k] + sum[r1 - 1][c1 - 1][k]) == (r2 - r1 + 1) * (c2 - c1 + 1));\\n}   \\n\\ninline bool can(int r,int c,int s){\\n    if(r < 0 || c < 0) return false;\\n    if(r + (s << 1) - 1 >= n || c + (s << 1) - 1 >= m) return false;\\n    for(int i =0  ;i < 4;i++){\\n        nr = r + dr[i] * s ;\\n        nc = c + dc[i] * s;\\n        if(!check(nr , nc , nr + s - 1 , nc + s - 1 , i))\\n            return false;\\n    }\\n    return true;\\n}\\n\\nvoid build(){\\n    lg[1] = 0;\\n    for(int i = 2;i<N;i++){\\n        lg[i] = lg[i - 1];\\n        if((1 << (lg[i] + 1)) == i)\\n            lg[i]++;\\n    }\\n    for(int k = 1;k < LOG;k++){\\n        for(int i=0;i + (1 << k) <= n;i++){\\n            for(int j=0;j<m;j++){\\n                st[i][j][k][0] = max(st[i][j][k - 1][0] , st[i + (1 << (k - 1))][j][k - 1][0]);\\n            }\\n        }\\n    }\\n    for(int l = 1;l < LOG;l++){\\n        for(int k = 0;k < LOG;k++){\\n            for(int i=0;i+(1 << k) <= n;i++){\\n                for(int j = 0;j + (1 << l) <= m;j++){\\n                    st[i][j][k][l] = max(st[i][j][k][l - 1] , st[i][j + (1 << (l - 1))][k][l-1]);\\n                }\\n            }\\n        }\\n    }\\n}\\n\\nint a , b;\\n\\ninline int getmax(int r1,int c1,int r2,int c2){\\n    if(r2 < r1 || c2 < c1 || r1 < 0 || r2 >= n || c1 < 0 || c2 >= m) return -oo;\\n    a = lg[(r2 - r1) + 1];\\n    b = lg[(c2 - c1) + 1];\\n    return max(max(st[r1][c1][a][b] , st[r2 - (1 << a) + 1][c1][a][b]) , max(st[r1][c2 - (1 << b) + 1][a][b] , st[r2 - (1 << a) + 1][c2 - (1 << b) + 1][a][b]));\\n}\\n\\n\\nint main(){\\n    scanf(\\\"%d%d%d\\\",&n,&m,&q);\\n    for(int i=0;i<n;i++){\\n        scanf(\\\" %s\\\",grid[i]);\\n        for(int j=0;j<m;j++){\\n            for(int k=0;k<4;k++){\\n                sum[i + 1][j + 1][k] = sum[i][j + 1][k] + sum[i + 1][j][k] - sum[i][j][k] + (S[k] == grid[i][j]);\\n            }\\n        }\\n    }\\n    int low , high , mid , res;\\n    for(int i=0;i<n;i++){\\n        for(int j=0;j<m;j++){\\n            low = 1 , high = min(min(i + 1,n - i) , min(j + 1,m - j));\\n            while(high >= low){\\n                mid = ((low + high) >> 1);\\n                if(can(i - mid + 1,j - mid + 1,mid))\\n                    st[i][j][0][0] = mid, low = mid + 1;\\n                else\\n                    high = mid - 1;\\n            }\\n        }\\n    }\\n    build();\\n    while(q--){\\n        scanf(\\\"%d%d%d%d\\\",&r1,&c1,&r2,&c2);\\n        r1--,c1--,r2--,c2--;\\n        low = 1 , high = (n >> 1) , res = 0;\\n        while(high >= low){\\n            mid = ((low + high) >> 1);\\n            if(getmax(r1 + mid - 1,c1 + mid - 1,r2 - mid , c2 - mid) >= mid)\\n                res = mid, low = mid + 1;\\n            else\\n                high = mid - 1;\\n        }\\n        printf(\\\"%d\\\\n\\\",res * res * 4);\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1301",
    "index": "F",
    "title": "Super Jaber",
    "statement": "Jaber is a superhero in a large country that can be described as a grid with $n$ rows and $m$ columns, where every cell in that grid contains a different city.\n\nJaber gave every city in that country a specific color between $1$ and $k$. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.\n\nJaber has to do $q$ missions. In every mission he will be in the city at row $r_1$ and column $c_1$, and he should help someone in the city at row $r_2$ and column $c_2$.\n\nJaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.",
    "tutorial": "In the shortest path between any two cells, you may use an edge that goes from a cell to another one with the same color at least once, or you may not. If you didn't use an edge that goes from a cell to another one with the same color then the distance will be the Manhattan distance. Otherwise you should find the best color that you will use that edge in it, the cost will be (the minimum cost between any cell of that color with first cell + the minimum cost between any cell of that color with the second cell + 1). In order to find the minimum cost from every color to each cell, we can run multi-source BFS for every color. But visiting all other cells that has the same color every time is too slow, so we can only visit these cells when we reach the first cell from every color. Complexity is $O(n \\cdot m \\cdot k + q \\cdot k)$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define oo 1000000000\\n#define mod 998244353\\nconst int N = 1010 , K = 45; \\nint n , m , k , r1 , r2 , c1 , c2 , grid[N][N] , ans = 0;\\n\\nint cost[K][N][N];\\nbool done[K];\\n\\nqueue < pair<int,int> > q;\\n\\nint dr[4] = {0 , 1 , 0 , -1};\\nint dc[4] = {1 , 0 ,-1 ,  0};\\n\\nvector < pair<int,int> > cells[K];\\n\\nvoid BFS(int col){\\n    for(int i = 0; i < (int)cells[col].size();i++){\\n        cost[col][cells[col][i].first][cells[col][i].second] = 0;\\n        q.push(make_pair(cells[col][i].first,cells[col][i].second));\\n    }\\n    for(int i = 1;i <= k;i++) done[i] = false;\\n    int r , c , nr , nc;\\n    while(!q.empty()){\\n        r = q.front().first;\\n        c = q.front().second;\\n        q.pop();\\n        if(!done[grid[r][c]]){\\n            done[grid[r][c]] = true;\\n            for(int i = 0 ; i < (int)cells[grid[r][c]].size() ;i++){\\n                nr = cells[grid[r][c]][i].first;\\n                nc = cells[grid[r][c]][i].second;\\n                if(cost[col][nr][nc] == -1){\\n                    cost[col][nr][nc] = cost[col][r][c] + 1;\\n                    q.push(make_pair(nr , nc));\\n                }\\n            }\\n        }\\n        for(int i = 0 ;i < 4;i++){\\n            nr = r + dr[i];\\n            nc = c + dc[i];\\n            if(nr >= 0 && nr < n && nc >= 0 && nc < m && cost[col][nr][nc] == -1){\\n                cost[col][nr][nc] = cost[col][r][c] + 1;\\n                q.push(make_pair(nr , nc));\\n            }\\n        }\\n    }\\n}\\n\\n\\nint main(){\\n    scanf(\\\"%d%d%d\\\",&n,&m,&k);\\n    for(int i = 0 ;i < n;i++){\\n        for(int j = 0 ;j < m;j++){\\n            scanf(\\\"%d\\\",&grid[i][j]);\\n            cells[grid[i][j]].push_back(make_pair(i , j));\\n        }\\n    }\\n    memset(cost,  -1, sizeof(cost));\\n    for(int i = 1;i <= k;i++)\\n        BFS(i);\\n    int q;\\n    scanf(\\\"%d\\\",&q);\\n    while(q--){\\n        scanf(\\\"%d%d%d%d\\\",&r1,&c1,&r2,&c2);\\n        r1--,c1--,r2--,c2--;\\n        ans = abs(r1 - r2) + abs(c1 - c2);\\n        for(int i = 1;i <= k;i++)\\n            ans = min(ans , 1 + cost[i][r1][c1] + cost[i][r2][c2]);\\n        printf(\\\"%d\\\\n\\\",ans);\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1303",
    "index": "A",
    "title": "Erasing Zeroes",
    "statement": "You are given a string $s$. Each character is either 0 or 1.\n\nYou want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.\n\nYou may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?",
    "tutorial": "Let's find the first and the last position of $1$-characters (denote them as $l$ and $r$ respectively). Since the can't delete $1$-characters, all $1$-characters between $s_l$ and $s_r$ will remain. So, we have to delete all $0$-characters between $s_l$ and $s_r$.",
    "code": "for t in range(int(input())):\n    print(input().strip('0').count('0'))",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1303",
    "index": "B",
    "title": "National Project",
    "statement": "Your company was appointed to lay new asphalt on the highway of length $n$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.\n\nSkipping the repair is necessary because of the climate. The climate in your region is periodical: there are $g$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $b$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $g$ good days, $b$ bad days and so on.\n\nYou can be sure that you start repairing at the start of a good season, in other words, days $1, 2, \\dots, g$ are good.\n\nYou don't really care about the quality of the highway, you just want to make sure that \\textbf{at least half of the highway} will have high-quality pavement. For example, if the $n = 5$ then at least $3$ units of the highway should have high quality; if $n = 4$ then at least $2$ units should have high quality.\n\nWhat is the minimum number of days is needed to finish the repair of \\textbf{the whole highway}?",
    "tutorial": "There are two conditions that should be met according to the statement. On the one hand, we should repair the whole highway, so we must spend at least $n$ days to do it. On the other hand, at least half of it should have high-quality pavement or at least $needG = \\left\\lceil \\frac{n}{2} \\right\\rceil$ units should be laid at good days. How to calculate the minimum number of days (name it as $totalG$) for the second condition to meet? Note that the first $totalG$ days can be represented as several (maybe zero) blocks of $g + b$ days, where exactly $g$ days in each block are good and some remaining days $1 \\le rem \\le g$. The $rem > 0$ because $totalG$ will not be minimum otherwise. There are plenty of ways to calculate $totalG$. One of them is the following: Firstly, let's calculate the number of $g + b$ cycles we need: $totatG = \\left\\lfloor \\frac{needG}{g} \\right\\rfloor \\cdot (g + b)$. Now, if $needG \\mod g > 0$ we just add it (since it's exactly the $rem$) or $totalG = totalG + (needG \\mod g)$. But if $needG \\mod g = 0$ we added to $totalG$ last $b$ block and should subtract it or $totalG = totalG - b$. The answer is $\\max(n, totalG)$.",
    "code": "fun main() {\n    val t = readLine()!!.toInt()\n    for (tc in 1..t) {\n        val (n, g, b) = readLine()!!.split(' ').map { it.toLong() }\n        \n        val needG = (n + 1) / 2\n        var totalG = needG / g * (b + g)\n        totalG += if (needG % g == 0L) -b else needG % g\n        println(maxOf(n, totalG))\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1303",
    "index": "C",
    "title": "Perfect Keyboard",
    "statement": "Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all $26$ lowercase Latin letters will be arranged in some order.\n\nPolycarp uses the same password $s$ on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in $s$, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in $s$, so, for example, the password cannot be password (two characters s are adjacent).\n\nCan you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?",
    "tutorial": "The problem can be solved using a greedy algorithm. We will maintain the current layout of the keyboard with letters that have already been encountered in the string, and the current position on the layout. If the next letter of the string is already on the layout, it must be adjacent to the current one, otherwise there is no answer. If there was no such letter yet, we can add it to the adjacent free position, if both of them is occupied, then there is no answer. At the end, you have to add letters that were not in the string $s$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nvoid solve() {\n    string s;\n    cin >> s;\n\n    vector<bool> used(26);\n    used[s[0] - 'a'] = true;\n    string t(1, s[0]);\n        \n    int pos = 0;\n    for (int i = 1; i < sz(s); i++) {\n        if (used[s[i] - 'a']) {\n            if (pos > 0 && t[pos - 1] == s[i]) {\n                pos--;\n            } else if (pos + 1 < sz(t) && t[pos + 1] == s[i]) {\n                pos++;\n            } else {\n                cout << \"NO\" << endl;\n                return;\n            }\n        } else {\n            if (pos == 0) {\n                t = s[i] + t;\n            } else if (pos == sz(t) - 1) {\n                t += s[i];\n                pos++;\n            } else {\n                cout << \"NO\" << endl;\n                return;\n            }\n        }\n        used[s[i] - 'a'] = true;\n    }\n        \n    forn(i, 26) if (!used[i])\n        t += char(i + 'a');\n    cout << \"YES\" << endl << t << endl;\n}\n\nint main() {\n    int tc;\n    cin >> tc;\n    \n    forn(i, tc) solve();\n}",
    "tags": [
      "dfs and similar",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1303",
    "index": "D",
    "title": "Fill The Bag",
    "statement": "You have a bag of size $n$. Also you have $m$ boxes. The size of $i$-th box is $a_i$, where each $a_i$ is an integer non-negative power of two.\n\nYou can divide boxes into two parts of equal size. Your goal is to fill the bag completely.\n\nFor example, if $n = 10$ and $a = [1, 1, 32]$ then you have to divide the box of size $32$ into two parts of size $16$, and then divide the box of size $16$. So you can fill the bag with boxes of size $1$, $1$ and $8$.\n\nCalculate the minimum number of divisions required to fill the bag of size $n$.",
    "tutorial": "If $\\sum\\limits_{i=1}^{n} a_i \\ge n$, then the answer is YES, because the just can divide all boxes to size $1$ and then fill the bag. Otherwise the answer is NO. If the answer is YES, let's calculate the minimum number of divisions. Let's consider all boxes from small to large. Presume that now we consider boxes of size $2^i$. Then there are three cases: if in binary representation of $n$ the $i$-th bit is equal to $0$, then we don't need boxes of size $2^i$ and we can merge it into boxes of size $2^{i+1}$; if in binary representation of $n$ the $i$-th bit is equal to $1$ and we have at most one box of size $2^i$, then we have to put it box in the bag and then merge the remaining boxes of size $2^i$ into boxes of size $2^{i+1}$; if in binary representation of $n$ the $i$-th bit is equal to $1$ and we have not boxes of size $2^i$, then we have to divide the large box into box of size $2^i$ (let's presume that it's box of size $2^x$). After that we just continue this algorithm with box of size $2^x$.",
    "code": "from math import log2\n\nfor t in range(int(input())):\n    n, m = map(int, input().split())\n    c = [0] * 61\n    s = 0\n    for x in map(int, input().split()):\n        c[int(log2(x))] += 1\n        s += x\n\n    if s < n:\n        print(-1)\n        continue\n\n    i, res = 0, 0\n    while i < 60:\n        if (1<<i)&n != 0:\n            if c[i] > 0:\n                c[i] -= 1\n            else:\n                while i < 60 and c[i] == 0:\n                    i += 1\n                    res += 1\n                c[i] -= 1\n                continue\n        c[i + 1] += c[i] // 2\n        i += 1\n\n    print(res)",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1303",
    "index": "E",
    "title": "Erase Subsequences",
    "statement": "You are given a string $s$. You can build new string $p$ from $s$ using the following operation \\textbf{no more than two times}:\n\n- choose any subsequence $s_{i_1}, s_{i_2}, \\dots, s_{i_k}$ where $1 \\le i_1 < i_2 < \\dots < i_k \\le |s|$;\n- erase the chosen subsequence from $s$ ($s$ can become empty);\n- concatenate chosen subsequence to the right of the string $p$ (in other words, $p = p + s_{i_1}s_{i_2}\\dots s_{i_k}$).\n\nOf course, initially the string $p$ is empty.\n\nFor example, let $s = \\text{ababcd}$. At first, let's choose subsequence $s_1 s_4 s_5 = \\text{abc}$ — we will get $s = \\text{bad}$ and $p = \\text{abc}$. At second, let's choose $s_1 s_2 = \\text{ba}$ — we will get $s = \\text{d}$ and $p = \\text{abcba}$. So we can build $\\text{abcba}$ from $\\text{ababcd}$.\n\nCan you build a given string $t$ using the algorithm above?",
    "tutorial": "Let's look at string $t$. Since we should get it using no more than two subsequences, then $t = a + b$ where $a$ is the first subsequence and $b$ is the second one. In the general case, $a$ can be empty. Let iterate all possible lengths of $a$ ($0 \\le |a| < |s|$), so we can check the existence of solution for each pair $a$ and $b$. If we'd fix $a$ and $b$ we need to check the following: is it true that $s$ contains $a$ and $b$ as subsequences and these subsequences don't intersect. Initially, we can invent the following dp: let $dp[len_s][len_a][len_b]$ be $1$ if the prefix of $s$ of length $len_s$ contains prefixes of $a$ and $b$ of length $len_a$ and $len_b$ as non-intersecting subsequences. The transitions are straingforward: if $dp[len_s][len_a][len_b] = 1$ we can either skip $s[len_s]$ ($0$-indexed) and update $dp[len_s + 1][len_a][len_b]$. If $s[len_s] = a[len_a]$ ($0$-indexed) then we can update $dp[len_s + 1][len_a + 1][len_b]$ and if $s[len_s] = b[len_b]$ then we can update $dp[len_s + 1][len_a][len_b + 1]$. But this dp has complexity $O(|s|^3)$ in general case. But we can transform it in the next way: instead of the boolean value, we will make $len_s$ as a value of dp. In other words, we will maintain $dp[len_a][len_b]$ as minimal appropriate prefix $len_s$. But the problem now is to define transitions. Let's note the next fact: suppose we have $len_s = dp[len_a][len_b]$ and we'd like to add next character to $a$ which is equal to $a[len_a]$. The idea is next: it's always optimal to choose the first occurrence of $a[len_a]$ in $s[len_s \\dots |s|)$. It can be proved by contradiction: if the first occurrence is free then it's better to take it, or if the first occurrence will be occupied by $b$ then this will be handled by the other state $dp[len_a][len_b']$ with $len_b' > len_b$. The logic for increasing $len_b$ is analogical. In result, we need to precalculate array $nxt[pos][c]$ with the next occurrence of character $c$ in suffix $pos$ of $s$ one time before choosing $a$ and $b$ and use it each time to acquire $O(|s|^2)$ complexity. The total complexity if $O(|s|^3)$ for each test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nstring s, t;\n\ninline bool read() {\n    if(!(cin >> s >> t))\n        return false;\n    for(auto &c : s)\n        c -= 'a';\n    for(auto &c : t)\n        c -= 'a';\n    return true;\n}\n\nvector< vector<int> > nxt;\n\nbool calc(const string &a, const string &b) {\n    vector< vector<int> > dp(sz(a) + 1, vector<int>(sz(b) + 1, INF));\n    dp[0][0] = 0;\n    fore(i, 0, sz(a) + 1) fore(j, 0, sz(b) + 1) {\n        if(dp[i][j] > sz(s))\n            continue;\n        \n        int len = dp[i][j];\n        if(i < sz(a) && nxt[len][a[i]] < INF) {\n            dp[i + 1][j] = min(dp[i + 1][j], nxt[len][a[i]] + 1);\n        }\n        if(j < sz(b) && nxt[len][b[j]] < INF) {\n            dp[i][j + 1] = min(dp[i][j + 1], nxt[len][b[j]] + 1);\n        }\n    }\n    return dp[sz(a)][sz(b)] < INF;\n}\n\ninline void solve() {\n    nxt.assign(sz(s) + 1, vector<int>(26, INF));\n    for(int i = sz(s) - 1; i >= 0; i--) {\n        nxt[i] = nxt[i + 1];\n        nxt[i][s[i]] = i;\n    }\n    \n    for(int i = 0; i < sz(t); i++) {\n        if(calc(t.substr(0, i), t.substr(i, sz(t)))) {\n            cout << \"YES\" << endl;\n            return;\n        }\n    }\n    cout << \"NO\" << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    int tc; cin >> tc;\n    \n    while(tc--) {\n        read();\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1303",
    "index": "F",
    "title": "Number of Components",
    "statement": "You are given a matrix $n \\times m$, initially filled with zeroes. We define $a_{i, j}$ as the element in the $i$-th row and the $j$-th column of the matrix.\n\nTwo cells of the matrix are connected if they share a side, and the elements in these cells are equal. Two cells of the matrix belong to the same connected component if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1$ is the first cell, $s_k$ is the second cell, and for every $i \\in [1, k - 1]$, $s_i$ and $s_{i + 1}$ are connected.\n\nYou are given $q$ queries of the form $x_i$ $y_i$ $c_i$ ($i \\in [1, q]$). For every such query, you have to do the following:\n\n- replace the element $a_{x, y}$ with $c$;\n- count the number of connected components in the matrix.\n\nThere is one additional constraint: for every $i \\in [1, q - 1]$, $c_i \\le c_{i + 1}$.",
    "tutorial": "Note that because of the low constraints on the number of colors, the problem can be solved independently for each color. Now you can divide the queries into two types: add a cell to the field and delete it. You have to maintain the number of components formed by added cells. Cell deletions will occur after all additions because of the condition $c_i \\le c_{i+1}$. The first part of the solution will be to calculate the number of components while adding new cells. This is a standard problem that can be solved using the DSU. After that, we should note that if we consider the process of removing cells from the end, this process is similar to the process of adding. Therefore, we have to process delete requests from the end in the same way as add requests, only their contribution to the number of components will be opposite in sign.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define pb push_back\n#define mp make_pair\n#define sqr(a) ((a) * (a))\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)\n#define forr(i, r, l) for (int i = int(r) - 1; i >= int(l); --i)\n\ntypedef pair<int, int> pt;\n\nconst int M = 310;\nconst int N = 2000 * 1000 + 13;\n\nint n, m, q;\nint a[M][M];\n\nint dx[] = {-1, 0, 1, 0};\nint dy[] = {0, -1, 0, 1};\n\nbool in(int x, int y) {\n    return 0 <= x && x < n && 0 <= y && y < m;\n}\n\nint p[M * M], rk[M * M];\n\nint getp(int v) {\n    return p[v] == v ? v : p[v] = getp(p[v]);\n}\n\nbool unite(int a, int b) {\n    a = getp(a); b = getp(b);\n    if (a == b) return false;\n    if (rk[a] < rk[b]) swap(a, b);\n    p[b] = a;\n    rk[a] += rk[b];\n    return true;\n}\n\nint dif[N];\nvector<pt> add[N], del[N];\n\nvoid recalc(const vector<pt>& ev, int coeff)  {\n    forn(i, n) forn(j, m) a[i][j] = 0;\n    forn(i, n * m) p[i] = i, rk[i] = 1;\n        \n    for (auto it : ev) {\n        int cur = 1;\n        int x = it.x / m, y = it.x % m;\n        a[x][y] = 1;\n        \n        forn(k, 4) {\n            int nx = x + dx[k];\n            int ny = y + dy[k];\n            if (in(nx, ny) && a[nx][ny] == 1)\n                cur -= unite(nx * m + ny, x * m + y);\n        }\n        \n        dif[it.y] += cur * coeff;\n    }\n}\n\nint main() {\n    scanf(\"%d%d%d\", &n, &m, &q);\n    int clrs = 1;\n    forn(i, q) {\n        int x, y, c;\n        scanf(\"%d%d%d\", &x, &y, &c);\n        --x; --y;\n        if (a[x][y] == c) continue;\n        clrs = c + 1;\n        add[c].pb(mp(x * m + y, i));\n        del[a[x][y]].pb(mp(x * m + y, i));\n        a[x][y] = c;\n    }\n    \n    forn(x, n) forn(y, m)\n        del[a[x][y]].pb(mp(x * m + y, q));\n    \n    forn(i, clrs) reverse(all(del[i]));\n    \n    forn(i, clrs) recalc(add[i], +1);\n    forn(i, clrs) recalc(del[i], -1);\n    \n    int cur = 1;\n    forn(i, q) {\n        cur += dif[i];\n        printf(\"%d\\n\", cur);\n    }\n}",
    "tags": [
      "dsu",
      "implementation"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1303",
    "index": "G",
    "title": "Sum of Prefix Sums",
    "statement": "We define the sum of prefix sums of an array $[s_1, s_2, \\dots, s_k]$ as $s_1 + (s_1 + s_2) + (s_1 + s_2 + s_3) + \\dots + (s_1 + s_2 + \\dots + s_k)$.\n\nYou are given a tree consisting of $n$ vertices. Each vertex $i$ has an integer $a_i$ written on it. We define the value of the simple path from vertex $u$ to vertex $v$ as follows: consider all vertices appearing on the path from $u$ to $v$, write down all the numbers written on these vertices in the order they appear on the path, and compute the sum of prefix sums of the resulting sequence.\n\nYour task is to calculate the maximum value over all paths in the tree.",
    "tutorial": "Let's use centroid decomposition to solve the problem. We need to process all the paths going through each centroid somehow. Consider a path from vertex $u$ to vertex $v$ going through vertex $c$, which is an ancestor of both $u$ and $v$ in the centroid decomposition tree. Suppose the sequence of numbers on path from $u$ to $c$ (including both these vertices) is $[a_1, a_2, \\dots, a_k]$, and the sequence of numbers on path from $c$ to $v$ (including $v$, but excluding $c$) is $[b_1, b_2, \\dots, b_m]$. Let $sum_a = \\sum\\limits_{i = 1}^{k} a_i$, $psum_a = \\sum\\limits_{i = 1}^{k} (k - i + 1) a_i$, and $psum_b = \\sum\\limits_{i = 1}^{m} (m - i + 1) b_i$. We can show that the sum of prefix sums of $[a_1, a_2, \\dots, a_k, b_1, b_2, \\dots, b_m]$ is equal to $psum_a + psum_b + sum_a \\cdot m$. Now, suppose we fix the second part of the path ($psum_b$ and $m$ are fixed), and we want to find the best first part for this second part. Each possible first part is represented by a linear function, and our goal is to find the maximum over all these linear functions in the point $m$, and add $psum_b$ to this maximum. This can be done with the help of convex hull or Li Chao tree. The most difficult part of implementation is how to process each centroid's subtree. It's easy to obtain all \"first parts\" and \"second parts\" of paths going through the centroid, but pairing them up can be complicated - for each second part, we have to build a convex hull or Li Chao tree on all first parts going to this centroid, excluding those which go through the same child of the centroid as the \"second part\" we are considering. One of the best ways to implement this is the following. Suppose our centroid has $m$ children, $fp_i$ is the set of \"first parts\" going from the $i$-th child of the centroid, and $sp_i$ is the set of \"second parts\" going to the $i$-th child. We will create a new data structure (initially empty), process all second parts from $sp_1$, add all first parts from $fp_1$, process all second parts from $sp_2$, add all first parts from $fp_2$, and so on. After that, we will clear our data structure, process all second parts from $sp_m$, add all first parts from $fp_m$, process all second parts from $sp_{m - 1}$, add all first parts from $fp_{m - 1}$, and so on, until we add all first parts from $fp_1$. That way we will consider all possible first parts for each second part we are trying to use.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 150043;\n\ntypedef pair<long long, long long> func;\n\nfunc T[4 * N];\nbool usedT[4 * N];\n\nvoid clear(int v, int l, int r)\n{\n    if(!usedT[v]) return;\n    usedT[v] = false;\n    T[v] = make_pair(0ll, 0ll);\n    if(l < r - 1)\n    {\n        int m = (l + r) / 2;\n        clear(v * 2 + 1, l, m);\n        clear(v * 2 + 2, m, r);\n    }\n}\n\nlong long eval(func f, int x)\n{\n    return f.first * x + f.second;\n}\n\nlong long get(int v, int l, int r, int x)\n{\n    long long ans = eval(T[v], x);\n    if(l < r - 1)\n    {\n        int m = (l + r) / 2;\n        if(m > x)\n            ans = max(ans, get(v * 2 + 1, l, m, x));\n        else\n            ans = max(ans, get(v * 2 + 2, m, r, x));\n    }\n    return ans;\n}\n\nvoid upd(int v, int l, int r, func f)\n{\n    usedT[v] = true;\n    int m = (l + r) / 2;\n    bool need_swap = eval(f, m) > eval(T[v], m);\n    if(need_swap)\n        swap(T[v], f);\n    if(l == r - 1)\n        return;\n    if(eval(f, l) > eval(T[v], l))\n        upd(v * 2 + 1, l, m, f);\n    else\n        upd(v * 2 + 2, m, r, f);\n}\n\nlong long ans = 0;\n\nvoid update_ans(vector<vector<func> > heads, vector<vector<func> > tails)\n{\n    int n = heads.size();\n    for(int i = 0; i < n; i++)\n    {\n        for(auto x : heads[i])\n            ans = max(ans, get(0, 0, N, x.first) + x.second);\n        for(auto x : tails[i])\n            upd(0, 0, N, x);\n    }\n    clear(0, 0, N);\n}\n\nint a[N];\nvector<int> g[N];\nint n;\nbool used[N];\nint siz[N];\n\nvoid dfs1(int x, int p = -1)\n{\n    if(used[x]) return;\n    siz[x] = 1;\n    for(auto to : g[x])\n    {                    \n        if(!used[to] && to != p)\n        {\n            dfs1(to, x);\n            siz[x] += siz[to];\n        }\n    }\n}\n\npair<int, int> c;\nint S = 0;\n\nvoid find_centroid(int x, int p = -1)\n{\n    if(used[x]) return;\n    int mx = 0;\n    for(auto to : g[x])\n    {\n        if(!used[to] && to != p)\n        {\n            find_centroid(to, x);\n            mx = max(mx, siz[to]);\n        }\n    }\n    if(p != -1)\n        mx = max(mx, S - siz[x]);\n    c = min(c, make_pair(mx, x));\n}\n\nvoid dfs_heads(int v, int p, int cnt, long long cursum, long long curadd, vector<func>& sink)\n{\n    if(used[v])\n        return;\n    cnt++;\n    curadd += a[v];\n    cursum += curadd;\n    sink.push_back(make_pair(cnt, cursum));\n    for(auto to : g[v])\n        if(to != p)\n            dfs_heads(to, v, cnt, cursum, curadd, sink);\n}\n\nvoid dfs_tails(int v, int p, int cnt, long long cursum, long long curadd, vector<func>& sink)\n{\n    if(used[v])\n        return;\n    cnt++;\n    curadd += a[v];\n    cursum += a[v] * 1ll * cnt;\n    sink.push_back(make_pair(curadd, cursum));\n    for(auto to : g[v])\n        if(to != p)\n            dfs_tails(to, v, cnt, cursum, curadd, sink);\n}\n\nvoid centroid(int v)\n{\n    if(used[v]) return;\n    dfs1(v);\n    S = siz[v];\n    c = make_pair(int(1e9), -1);\n    find_centroid(v);\n    int C = c.second;\n    used[C] = 1;\n    vector<vector<func> > heads, tails;\n    for(auto to : g[C])\n        if(!used[to])\n        {\n            heads.push_back(vector<func>());\n            dfs_heads(to, C, 1, a[C], a[C], heads.back());\n            tails.push_back(vector<func>());\n            dfs_tails(to, C, 0, 0, 0, tails.back());\n        }\n    heads.push_back(vector<func>({{1, a[C]}}));\n    tails.push_back(vector<func>({{0, 0}}));\n    update_ans(heads, tails);\n    reverse(heads.begin(), heads.end());\n    reverse(tails.begin(), tails.end());\n    update_ans(heads, tails);\n    for(auto to : g[C])\n        centroid(to);\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n - 1; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        --x;\n        --y;\n        g[x].push_back(y);\n        g[y].push_back(x);    \n    }\n    for(int i = 0; i < n; i++)\n        scanf(\"%d\", &a[i]);\n    centroid(0);\n    printf(\"%lld\\n\", ans);\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "geometry",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1304",
    "index": "A",
    "title": "Two Rabbits",
    "statement": "Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.\n\nHe noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $x$, and the shorter rabbit is currently on position $y$ ($x \\lt y$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $a$, and the shorter rabbit hops to the negative direction by $b$.\n\nFor example, let's say $x=0$, $y=10$, $a=2$, and $b=3$. At the $1$-st second, each rabbit will be at position $2$ and $7$. At the $2$-nd second, both rabbits will be at position $4$.\n\nGildong is now wondering: {Will the two rabbits be at the same position \\textbf{at the same moment}? If so, how long will it take?} Let's find a moment in time (in seconds) after which the rabbits will be at the same point.",
    "tutorial": "We can see that the taller rabbit will be at position $x + Ta$ and the shorter rabbit will be at position $y - Tb$ at the $T$-th second. We want to know when these two values are equal. Simplifying the equation, we get $\\cfrac{y - x}{a + b} = T$. Since we only consider positive integers for $T$, the answer is $\\cfrac{y - x}{a + b}$ only if $y - x$ is divisible by $a + b$. Otherwise, the answer is $-1$. Another intuitive approach is to think of it as relative speed. In the perspective of the taller rabbit, the shorter rabbit will move (or more like, teleport) to the negative direction at speed of $a + b$ per second. Therefore the initial distance $y - x$ must be divisible by $a + b$ in order to make the two rabbits meet at time $\\cfrac{y - x}{a + b}$. Time complexity: $O(1)$ for each test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint tc;\n\tcin >> tc;\n\twhile (tc--)\n\t{\n\t\tint x, y, a, b;\n\t\tcin >> x >> y >> a >> b;\n\t\tcout << ((y - x) % (a + b) == 0 ? (y - x) / (a + b) : -1) << endl;\n\t}\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1304",
    "index": "B",
    "title": "Longest Palindrome",
    "statement": "Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings \"pop\", \"noon\", \"x\", and \"kkkkkk\" are palindromes, while strings \"moon\", \"tv\", and \"abab\" are not. \\textbf{An empty string is also a palindrome.}\n\nGildong loves this concept so much, so he wants to play with it. He has $n$ distinct strings of equal length $m$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.",
    "tutorial": "Let's define $rev(S)$ as the reversed string of a string $S$. There are two cases when we choose $K$ strings to make a palindrome string $S_1 + S_2 + \\cdots + S_K$: If $K$ is even, for every integer $X$ ($1 \\le X \\le \\cfrac{K}{2}$), $S_X = rev(S_{K-X+1})$. if $K$ is odd, $S_{\\frac{K+1}{2}}$ must be palindrome. Also for every integer $X$ ($1 \\le X \\le \\cfrac{K-1}{2}$), $S_X = rev(S_{K-X+1})$. In either case we want to find as many pairs of strings as possible such that one is the reverse of the other. It is also clear that if $T$ is a palindrome string then $rev(T) = T$. We cannot make a pair of T and rev(T) because all strings in the input are distinct. Therefore, for each string we need to find if there is another string that is its reverse. If there exists one, put them on the left / right end respectively. If there are one or more strings that are palindrome themselves, pick any one of them and put it in the middle. Time complexity: $O(n^2m)$ if we implement it naively. $O(nmlogn)$ is possible if we use a data structure that provides $O(logn)$ search such as std::set in C++.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_N = 100;\nstring s[MAX_N];\n\nint main()\n{\n\tset<string> dict;\n\tint n, m, i;\n\tcin >> n >> m;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tcin >> s[i];\n\t\tdict.insert(s[i]);\n\t}\n\tvector<string> left, right;\n\tstring mid;\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tstring t = s[i];\n\t\treverse(t.begin(), t.end());\n\t\tif (t == s[i])\n\t\t\tmid = t;\n\t\telse if (dict.find(t) != dict.end())\n\t\t{\n\t\t\tleft.push_back(s[i]);\n\t\t\tright.push_back(t);\n\t\t\tdict.erase(s[i]);\n\t\t\tdict.erase(t);\n\t\t}\n\t}\n\tcout << left.size() * m * 2 + mid.size() << endl;\n\tfor (string x : left)\n\t\tcout << x;\n\tcout << mid;\n\treverse(right.begin(), right.end());\n\tfor (string x : right)\n\t\tcout << x;\n\tcout << endl;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1304",
    "index": "C",
    "title": "Air Conditioner",
    "statement": "Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.\n\nGildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.\n\nThe restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.\n\nEach customer is characterized by three values: $t_i$ — the time (in minutes) when the $i$-th customer visits the restaurant, $l_i$ — the lower bound of their preferred temperature range, and $h_i$ — the upper bound of their preferred temperature range.\n\nA customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $i$-th customer is satisfied if and only if the temperature is between $l_i$ and $h_i$ (inclusive) in the $t_i$-th minute.\n\nGiven the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.",
    "tutorial": "Since the range of temperatures can be large, it is impossible to consider all possible cases. However, we only need to find any case that can satisfy all customers, so let's try to maximize the possible range for each customer in the order of their visit time. Let's define two variables $mn$ and $mx$, each representing the minimum and maximum possible temperature that can be set now. Initially they are both $m$ and the current time is $0$. After $K$ minutes, we can see that the possible range is $[mn-K, mx+K]$. This means if a customer that visits after $K$ minutes has preferred temperature range $[L, R]$ that intersects with this range (inclusive), Gildong can satisfy that customer. In other words, $mn-K \\le R$ and $L \\le mx+K$ must be satisfied. Then we can reset $mn$ and $mx$ to fit this intersected range: $mn = max(mn-K, L)$ and $mx = min(mx+K, R)$. If this can be continued until the last customer, the answer is \"YES\". Otherwise, the answer is \"NO\". Time complexity: $O(n)$ for each test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_N = 100;\n\nint t[MAX_N], lo[MAX_N], hi[MAX_N];\n\nint main()\n{\n\tint tc;\n\tcin >> tc;\n\twhile (tc--)\n\t{\n\t\tint n, m, i;\n\t\tcin >> n >> m;\n\t\tfor (i = 0; i < n; i++)\n\t\t\tcin >> t[i] >> lo[i] >> hi[i];\n\t\tint prev = 0;\n\t\tint mn = m, mx = m;\n\t\tbool flag = true;\n\t\tfor (i = 0; i < n; i++)\n\t\t{\n\t\t\tmx += t[i] - prev;\n\t\t\tmn -= t[i] - prev;\n\t\t\tif (mx < lo[i] || mn > hi[i])\n\t\t\t{\n\t\t\t\tflag = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmx = min(mx, hi[i]);\n\t\t\tmn = max(mn, lo[i]);\n\t\t\tprev = t[i];\n\t\t}\n\t\tif (flag)\n\t\t\tcout << \"YES\\n\";\n\t\telse\n\t\t\tcout << \"NO\\n\";\n\t}\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1304",
    "index": "D",
    "title": "Shortest and Longest LIS",
    "statement": "Gildong recently learned how to find the longest increasing subsequence (LIS) in $O(n\\log{n})$ time for a sequence of length $n$. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of $n$ distinct integers between $1$ and $n$, inclusive, to test his code with your output.\n\nThe quiz is as follows.\n\nGildong provides a string of length $n-1$, consisting of characters '<' and '>' only. The $i$-th (1-indexed) character is the comparison result between the $i$-th element and the $i+1$-st element of the sequence. If the $i$-th character of the string is '<', then the $i$-th element of the sequence is less than the $i+1$-st element. If the $i$-th character of the string is '>', then the $i$-th element of the sequence is greater than the $i+1$-st element.\n\nHe wants you to find two possible sequences (not necessarily distinct) consisting of $n$ distinct integers between $1$ and $n$, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.",
    "tutorial": "There are various strategies to solve each part. I'll explain one of them for each. It would be fun to come up with your own strategy as well :) Shortest LIS Let's group each contiguously increasing part. We can easily see that we cannot make the LIS shorter than the maximum size among these groups. It can be shown that we can make the length of the LIS not longer than that as well. One strategy is to fill the largest unused numbers in increasing order for each group from left to right. There will be no indices $i$ and $j$ ($i \\lt j$) such that $perm[i]$ < $perm[j]$ where $i$ and $j$ are in different groups. Therefore the maximum size among the groups will be the length of the LIS. Longest LIS Let's group each contiguously decreasing part. We can easily see that there can be at most one element from each group that is included in any possible LIS. It can be shown that we can make a sequence that takes one element from every groups to form the LIS. One strategy is to fill the smallest unused numbers in decreasing order for each group from left to right. Then for every indices $i$ and $j$ ($i \\lt j$) where $i$ and $j$ are in different groups, $perm[j]$ will be always greater than $perm[i]$. Thus, we can take any one element from each and every groups to form the LIS. Time complexity: $O(n)$ for each test case. Here's a little challenge for people who want harder things: Can you make a sequence that has the length of its LIS exactly $k$?",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_N = 200000;\nint ans[MAX_N + 5];\n\nint main()\n{\n\tint tc;\n\tcin >> tc;\n\twhile (tc--)\n\t{\n\t\tint n, i, j;\n\t\tstring s;\n\t\tcin >> n >> s;\n\n\t\tint num = n, last = 0;\n\t\tfor (i = 0; i < n; i++)\n\t\t{\n\t\t\tif (i == n - 1 || s[i] == '>')\n\t\t\t{\n\t\t\t\tfor (j = i; j >= last; j--)\n\t\t\t\t\tans[j] = num--;\n\t\t\t\tlast = i + 1;\n\t\t\t}\n\t\t}\n\t\tfor (i = 0; i < n; i++)\n\t\t\tcout << ans[i] << (i == n - 1 ? '\\n' : ' ');\n\n\t\tnum = 1, last = 0;\n\t\tfor (i = 0; i < n; i++)\n\t\t{\n\t\t\tif (i == n - 1 || s[i] == '<')\n\t\t\t{\n\t\t\t\tfor (j = i; j >= last; j--)\n\t\t\t\t\tans[j] = num++;\n\t\t\t\tlast = i + 1;\n\t\t\t}\n\t\t}\n\t\tfor (i = 0; i < n; i++)\n\t\t\tcout << ans[i] << (i == n - 1 ? '\\n' : ' ');\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1304",
    "index": "E",
    "title": "1-Trees and Queries",
    "statement": "Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?\n\nThen he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.\n\nFirst, he'll provide you a tree (not 1-tree) with $n$ vertices, then he will ask you $q$ queries. Each query contains $5$ integers: $x$, $y$, $a$, $b$, and $k$. This means you're asked to determine if there exists a path from vertex $a$ to $b$ that contains exactly $k$ edges after adding a bidirectional edge between vertices $x$ and $y$. \\textbf{A path can contain the same vertices and same edges multiple times}. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.",
    "tutorial": "Assume that the length of a path from $a$ to $b$ is $L$. It is obvious that for every non-negative integer $Z$, there exists a path from $a$ to $b$ of length $L + 2Z$ since we can go back and forth any edge along the path any number of times. So, we want to find the shortest path from $a$ to $b$ where the parity (odd or even) of its length is same as the parity of $k$. Since it is a tree, the parity of the length of every paths from $a$ to $b$ is unique. However, if we add another edge, we can possibly find a path of length with different parity. The parity is changed only if you use the added edge odd number of times and the length of the simple path from $x$ to $y$ is even. Since there is no reason to take the path multiple times to find the shortest path of same parity, let's assume we use it only once. If it doesn't change the parity, we can think of it as trying to find a shorter path with same parity of length. Then there are three paths we need to check: The simple path from $a$ to $b$ without using the added edge. The simple path from $a$ to $x$ without using the added edge, plus the added edge, plus the simple path from $y$ to $b$ without using the added edge. The simple path from $a$ to $y$ without using the added edge, plus the added edge, plus the simple path from $x$ to $b$ without using the added edge. Finding the length of each simple path can be done in $O(\\log{n})$ time using the well-known LCA (Lowest Common Ancestor) algorithm with $O(n\\log{n})$ pre-processing. Now for the ones that have the same parity of length as $k$, we need to determine if the minimum of them is less than or equal to $k$. If there are no such paths, the answer is \"NO\". Otherwise the answer is \"YES\". Time complexity: $O((n+q)\\log{n})$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_N = 100000;\nconst int LIM = 17;\nconst int INF = (int)1e9 + 7;\n\nvector<int> adj[MAX_N + 5];\nint depth[MAX_N + 5];\nint par[MAX_N + 5][LIM + 1];\n\nvoid build(int cur, int p)\n{\n\tint i;\n\n\tdepth[cur] = depth[p] + 1;\n\tpar[cur][0] = p;\n\tfor (i = 1; i <= LIM; i++)\n\t\tpar[cur][i] = par[par[cur][i - 1]][i - 1];\n\n\tfor (int x : adj[cur])\n\t\tif (x != p)\n\t\t\tbuild(x, cur);\n}\n\nint lca_len(int a, int b)\n{\n\tint i, len = 0;\n\n\tif (depth[a] > depth[b])\n\t\tswap(a, b);\n\tfor (i = LIM; i >= 0; i--)\n\t{\n\t\tif (depth[par[b][i]] >= depth[a])\n\t\t{\n\t\t\tb = par[b][i];\n\t\t\tlen += (1 << i);\n\t\t}\n\t}\n\t\n\tif (a == b)\n\t\treturn len;\n\tfor (i = LIM; i >= 0; i--)\n\t{\n\t\tif (par[a][i] != par[b][i])\n\t\t{\n\t\t\ta = par[a][i];\n\t\t\tb = par[b][i];\n\t\t\tlen += (1 << (i + 1));\n\t\t}\n\t}\n\treturn len + 2;\n}\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint n, q, i;\n\tcin >> n;\n\t\n\tfor (i = 0; i < n - 1; i++)\n\t{\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tadj[u].push_back(v);\n\t\tadj[v].push_back(u);\n\t}\n\tbuild(1, 0);\n\n\tcin >> q;\n\twhile (q--)\n\t{\n\t\tint x, y, a, b, k;\n\t\tcin >> x >> y >> a >> b >> k;\n\t\tint without = lca_len(a, b);\n\t\tint with = min(lca_len(a, x) + lca_len(y, b), lca_len(a, y) + lca_len(x, b)) + 1;\n\t\tint ans = INF;\n\t\tif (without % 2 == k % 2)\n\t\t\tans = without;\n\t\tif (with % 2 == k % 2)\n\t\t\tans = min(ans, with);\n\t\tcout << (ans <= k ? \"YES\" : \"NO\") << '\\n';\n\t}\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "shortest paths",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1304",
    "index": "F1",
    "title": "Animal Observation (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the constraint on} $k$.\n\nGildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.\n\nGildong is going to take videos for $n$ days, starting from day $1$ to day $n$. The forest can be divided into $m$ areas, numbered from $1$ to $m$. He'll use the cameras in the following way:\n\n- On every odd day ($1$-st, $3$-rd, $5$-th, ...), bring the red camera to the forest and record a video for $2$ days.\n- On every even day ($2$-nd, $4$-th, $6$-th, ...), bring the blue camera to the forest and record a video for $2$ days.\n- If he starts recording on the $n$-th day with one of the cameras, the camera records for only one day.\n\nEach camera can observe $k$ consecutive areas of the forest. For example, if $m=5$ and $k=3$, he can put a camera to observe one of these three ranges of areas for two days: $[1,3]$, $[2,4]$, and $[3,5]$.\n\nGildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for $n$ days. \\textbf{Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.}",
    "tutorial": "For simplicity, we'll assume that there is the $n+1$-st day when no animals appear at all. Let's say $animal[i][j]$ is the number of animals appearing in the $j$-th area on the $i$-th day. Let's define $DP[i][j]$ ($1 \\le i \\le n, 1 \\le j \\le m - k + 1$) as the maximum number of animals that can be observed in total since day $1$, if Gildong puts a camera on the $i$-th day to observe area $[j, j+k-1]$ in day $i$ and $i+1$. Obviously, $DP[1][j]$ is the sum of the number of animals in area $[j, j+k-1]$ in day $1$ and day $2$. Now, for each day since day $2$, let's find three values to determine $DP[i][j]$, which is the maximum among them. For all $x$ ($1 \\le x \\le j-k$), maximum of $DP[i-1][x]$ plus $sum(animal[i \\ldots i+1][j \\ldots j+k-1])$. For all $y$ ($j+k \\le y \\le m-k+1$), maximum of $DP[i-1][y]$ plus $sum(animal[i \\ldots i+1][j \\ldots j+k-1])$. For all $z$ ($j-k+1 \\le z \\le j+k-1$), maximum of $DP[i-1][z]$ plus $sum(animal[i \\ldots i+1][j \\ldots j+k-1])$ minus the sum of animals in the intersected area on the $i$-th day. The summation parts can be calculated in $O(1)$ time by prefix sum technique after $O(nm)$ pre-processing. For the ones that have no intersection, we can pre-calculate the prefix max and suffix max for the values in $DP[i-1]$ in $O(m)$ time for each day, therefore finding it in $O(1)$ as well. Since $k$ is small in this problem, we can naively check all cases when there are one or more intersected areas. For each area we need to check $O(k)$ cases each in $O(1)$ time, so the problem can be solved in $O(nmk)$ time in total.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAX_N = 50;\nconst int MAX_M = 20000;\nconst int MAX_K = 20;\n\nint animal[MAX_N + 5][MAX_M + 5];\nint psum[MAX_N + 5][MAX_M + 5];\nint lmax[MAX_N + 5][MAX_M + 5];\nint rmax[MAX_N + 5][MAX_M + 5];\nint dp[MAX_N + 5][MAX_M + 5];\n\ninline int ps(int i, int j, int k)\n{\n\treturn psum[i][k] - psum[i][j - 1];\n}\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint i, j;\n\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tfor (i = 1; i <= n; i++)\n\t{\n\t\tfor (j = 1; j <= m; j++)\n\t\t{\n\t\t\tcin >> animal[i][j];\n\t\t\tpsum[i][j] = psum[i][j - 1] + animal[i][j];\n\t\t}\n\t}\n\n\tfor (i = 1; i <= n; i++)\n\t{\n\t\tfor (j = 1; j <= m - k + 1; j++)\n\t\t{\n\t\t\tint p = ps(i, j, j + k - 1) + ps(i + 1, j, j + k - 1);\n\t\t\tif (i == 1)\n\t\t\t{\n\t\t\t\tdp[i][j] = p;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint mx = 0;\n\t\t\tfor (int x = max(1, j - k + 1); x <= min(m - k + 1, j + k - 1); x++)\n\t\t\t\tmx = max(mx, dp[i - 1][x] + p - ps(i, max(x, j), min(x + k - 1, j + k - 1)));\n\t\t\tdp[i][j] = mx;\n\t\t\tif (j > k)\n\t\t\t\tdp[i][j] = max(dp[i][j], lmax[i - 1][j - k] + p);\n\t\t\tif (j + k - 1 <= m - k)\n\t\t\t\tdp[i][j] = max(dp[i][j], rmax[i - 1][j + k] + p);\n\t\t}\n\t\tfor (j = 1; j <= m - k + 1; j++)\n\t\t\tlmax[i][j] = max(lmax[i][j - 1], dp[i][j]);\n\t\tfor (j = m - k + 1; j >= 1; j--)\n\t\t\trmax[i][j] = max(rmax[i][j + 1], dp[i][j]);\n\t}\n\n\tcout << *max_element(dp[n] + 1, dp[n] + m + 1) << '\\n';\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1304",
    "index": "F2",
    "title": "Animal Observation (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the constraint on} $k$.\n\nGildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.\n\nGildong is going to take videos for $n$ days, starting from day $1$ to day $n$. The forest can be divided into $m$ areas, numbered from $1$ to $m$. He'll use the cameras in the following way:\n\n- On every odd day ($1$-st, $3$-rd, $5$-th, ...), bring the red camera to the forest and record a video for $2$ days.\n- On every even day ($2$-nd, $4$-th, $6$-th, ...), bring the blue camera to the forest and record a video for $2$ days.\n- If he starts recording on the $n$-th day with one of the cameras, the camera records for only one day.\n\nEach camera can observe $k$ consecutive areas of the forest. For example, if $m=5$ and $k=3$, he can put a camera to observe one of these three ranges of areas for two days: $[1,3]$, $[2,4]$, and $[3,5]$.\n\nGildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for $n$ days. \\textbf{Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.}",
    "tutorial": "We can further advance the idea we used in F1 to reduce the time complexity. Solution: $O(nm\\log{m})$ Let's generalize all three cases we discussed in F1. Let's make a lazy segment tree supporting range addition update and range maximum query. Each node represents the maximum value of ($DP[i-1]$ minus the sum of the animals appearing on the $i$-th day in the intersected area) in the corresponding interval. Then we can add $sum(animal[i \\ldots i+1][j \\ldots j+k-1])$ to the maximum value of the segment tree to determine $DP[i][j]$. For the $i$-th day, we insert $DP[i-1][j]$ in the respective index of the segment tree for all $j$ ($1 \\le j \\le m-k+1$) initially. Now, to determine $DP[i][j]$ for each $j$, we want to subtract $sum(animal[i][max(j, x) \\ldots min(j, x)+k-1])$ from the segment tree for all $x$ ($1 \\le x \\le m-k+1$). But it is infeasible to do this and add them back for every single $x$-s that has intersected areas. Here, we can use sliding window technique to improve it. To determine $DP[i][1]$, we can manually subtract the first $k$ elements of $animal[i]$ from the segment tree like above. Let's assume that we're done with determining $DP[i][j-1]$. When we move on to determining $DP[i][j]$, we can see that $animal[i][j-1]$ is no longer in the range and thus should be added back to the segment tree. Precisely, all $DP[i-1][x]$-s where $x$ is within range $[max(1, j-k), j-1]$ are affected by this and must be added with $animal[i][j-1]$. Similarly, $animal[i][j+k-1]$ is now in the range and thus should be subtracted from all $DP[i-1][y]$-s where $y$ is within range $[j, j+k-1]$. Each range update takes $O(\\log{m})$ time, and this happens only two times for determining each $DP[i][j]$. The 'initial' work takes $O(k)$ time but it happens only once for each day. Therefore, it takes $O(m\\log{m})$ time for each day and $O(nm\\log{m})$ time in total. Solution: $O(nm)$ It turns out that it's even possible without the segment tree. Of course, $O(nm\\log{m})$ is intended to pass so you don't really need to implement this to solve the problem. Instead of segment tree, we'll use monotonic queue structure (the core idea for convex hull trick) to have the values in decreasing order from front to back. If you don't know what monotonic queue is, make sure you understand it first. You can read about it here. We'll do basically the same thing we did for $O(nm\\log{m})$ solution, but there are two major differences. First, we'll slide the window two times, one from left to right and the other one from right to left. Second, we'll only consider the values where the range of their indices intersects with the window, but only a part of them. We'll see how it works when sliding the window from left to right, then we can also do it in reverse direction. We'll only consider all $DP[i-1][x]$ where $x$ is within range $[max(1, j-k+1), j]$. In other words, we only consider it when the intersected area is a prefix of the window. This means when we're about to determine $DP[i][j]$, $DP[i-1][j]$ (in fact, the actual value will be $DP[i-1][j] - sum(animal[i][j \\ldots j+k-1])$) is inserted into the queue and $DP[i-1][j-k]$ is removed from the queue. Now let's see how the 'real' values in the queue are changed while sliding the window. Since we'll only add the same value to all elements in the queue every time we slide the window, the order of the elements won't be changed, thus maintaining the monotone queue structure. However, we don't actually need to perform the 'add' action, simply because we can always calculate it in $O(1)$ time by calculating the sum of the animals between the index of that element (inclusive) and the window (exclusive). So to the 'real' value at the front of the queue, we can add $sum(animal[i \\ldots i+1][j \\ldots j+k-1])$ to determine $DP[i][j]$. The exact same thing can be done in the reversed way, too. Now let's take back the prefix and suffix max we discussed in F1, so that we can check the cases when they do not intersect. We can see that each of these operations can be done in $O(m)$ for each day. Therefore, the whole process is performed in $O(nm)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing pii = pair<int, int>;\nusing vi = vector<int>;\nusing vvi = vector<vi>;\n\nconst int MAX_N = 50;\nconst int MAX_M = 20000;\nconst int MAX_K = 20;\n\nint n, m, k;\n\ninline int ps(vvi &p, int i, int s, int e)\n{\n\tif (s < 1)\n\t\treturn p[i][e];\n\treturn p[i][e] - p[i][s - 1];\n}\n\nvoid calc_overlapped(vvi &ar, vvi &p, vvi &dp, int i)\n{\n\tint j;\n\tdeque<pii> dq;\n\tfor (j = 1; j <= m - k + 1; j++)\n\t{\n\t\tint num = dp[i - 1][j] - ps(p, i, j, j + k - 1);\n\t\tif (dq.size() && dq.front().second <= j - k)\n\t\t\tdq.pop_front();\n\t\twhile (dq.size() && dq.back().first + ps(p, i, dq.back().second, j - 1) <= num)\n\t\t\tdq.pop_back();\n\t\tdq.push_back({ num, j });\n\t\tdp[i][j] = dq.front().first + ps(p, i, dq.front().second, j - 1) + ps(p, i, j, j + k - 1) + ps(p, i + 1, j, j + k - 1);\n\t}\n}\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint i, j;\n\n\tcin >> n >> m >> k;\n\n\tvvi init(n + 5, vi(m + 5, 0));\n\tvvi animal, animal_rev, psum, psum_rev, lmax, rmax, dp, dpl, dpr;\n\tanimal = animal_rev = psum = psum_rev = lmax = rmax = dp = dpl = dpr = init;\t\n\n\tfor (i = 1; i <= n; i++)\n\t{\n\t\tfor (j = 1; j <= m; j++)\n\t\t{\n\t\t\tcin >> animal[i][j];\n\t\t\tpsum[i][j] = psum[i][j - 1] + animal[i][j];\n\t\t\tanimal_rev[i][m - j + 1] = animal[i][j];\n\t\t}\n\t\tfor (j = 1; j <= m; j++)\n\t\t\tpsum_rev[i][j] = psum_rev[i][j - 1] + animal_rev[i][j];\n\t}\n\n\tdeque<pii> dq;\n\tfor (i = 1; i <= n; i++)\n\t{\n\t\tfor (j = 1; j <= m - k + 1; j++)\n\t\t{\n\t\t\tif (j > k)\n\t\t\t\tdp[i][j] = lmax[i - 1][j - k];\n\t\t\tif (j <= m - k * 2 + 1)\n\t\t\t\tdp[i][j] = max(dp[i][j], rmax[i - 1][j + k]);\n\t\t\tdp[i][j] += ps(psum, i, j, j + k - 1) + ps(psum, i + 1, j, j + k - 1);\n\t\t}\n\n\t\tcalc_overlapped(animal, psum, dpl, i);\n\t\tcalc_overlapped(animal_rev, psum_rev, dpr, i);\n\n\t\tfor (j = 1; j <= m - k + 1; j++)\n\t\t{\n\t\t\tdp[i][j] = max({ dp[i][j], dpl[i][j], dpr[i][m - j - k + 2] });\n\t\t\tdpl[i][j] = dpr[i][m - j - k + 2] = dp[i][j];\n\t\t}\n\t\t\t\n\t\tfor (j = 1; j <= m - k + 1; j++)\n\t\t\tlmax[i][j] = max(lmax[i][j - 1], dp[i][j]);\n\t\tfor (j = m - k + 1; j >= 1; j--)\n\t\t\trmax[i][j] = max(rmax[i][j + 1], dp[i][j]);\n\t}\n\n\tcout << *max_element(dp[n].begin(), dp[n].end()) << endl;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1305",
    "index": "A",
    "title": "Kuroni and the Gifts",
    "statement": "Kuroni has $n$ daughters. As gifts for them, he bought $n$ necklaces and $n$ bracelets:\n\n- the $i$-th necklace has a brightness $a_i$, where all the $a_i$ are \\textbf{pairwise distinct} (i.e. all $a_i$ are different),\n- the $i$-th bracelet has a brightness $b_i$, where all the $b_i$ are \\textbf{pairwise distinct} (i.e. all $b_i$ are different).\n\nKuroni wants to give \\textbf{exactly one} necklace and \\textbf{exactly one} bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be \\textbf{pairwise distinct}. Formally, if the $i$-th daughter receives a necklace with brightness $x_i$ and a bracelet with brightness $y_i$, then the sums $x_i + y_i$ should be pairwise distinct. Help Kuroni to distribute the gifts.\n\nFor example, if the brightnesses are $a = [1, 7, 5]$ and $b = [6, 1, 2]$, then we may distribute the gifts as follows:\n\n- Give the third necklace and the first bracelet to the first daughter, for a total brightness of $a_3 + b_1 = 11$.\n- Give the first necklace and the third bracelet to the second daughter, for a total brightness of $a_1 + b_3 = 3$.\n- Give the second necklace and the second bracelet to the third daughter, for a total brightness of $a_2 + b_2 = 8$.\n\nHere is an example of an \\textbf{invalid} distribution:\n\n- Give the first necklace and the first bracelet to the first daughter, for a total brightness of $a_1 + b_1 = 7$.\n- Give the second necklace and the second bracelet to the second daughter, for a total brightness of $a_2 + b_2 = 8$.\n- Give the third necklace and the third bracelet to the third daughter, for a total brightness of $a_3 + b_3 = 7$.\n\nThis distribution is \\textbf{invalid}, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!",
    "tutorial": "We claim that if we sort the arrays $a$ and $b$, then giving the $i$-th daughter the $i$-th necklace and the $i$-th bracelet is a valid distribution. Notice that since all elements in each array are distinct, we have $a_1 < a_2 < \\dots < a_n$ $b_1 < b_2 < \\dots < b_n$ Then $a_i + b_i < a_{i + 1} + b_i < a_{i + 1} + b_{i + 1}$ for $1 \\le i \\le n$, so $a_1 + b_1 < a_2 + b_2 < \\dots < a_n + b_n$ And all these sums are distinct.",
    "code": "T = int(input())\nfor _ in range(T):\n\tn = int(input())\n\tA = sorted(list(map(int, input().split())))\n\tB = sorted(list(map(int, input().split())))\n\n\tprint(*A)\n\tprint(*B)",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1305",
    "index": "B",
    "title": "Kuroni and Simple Strings",
    "statement": "Now that Kuroni has reached 10 years old, he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!\n\nWe say that a string formed by $n$ characters '(' or ')' is \\textbf{simple} if its length $n$ is even and positive, its first $\\frac{n}{2}$ characters are '(', and its last $\\frac{n}{2}$ characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.\n\nKuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. \\textbf{Note that this subsequence doesn't have to be continuous}. For example, he can apply the operation to the string {')\\textbf{(})\\textbf{(}()\\textbf{))}'}, to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'.\n\nKuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string \\textbf{does not} have to be empty.\n\nSince the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?\n\nA sequence of characters $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.",
    "tutorial": "We claim that the answer is always $0$ or $1$. First, note we can't apply any operations if and only if each '(' symbol is left from each ')' symbol, so that the string looks as ')))(((((('. Let $a_1, a_2, \\dots, a_p$ be the indexes of symbols '(' in the string, and $b_1, b_2, \\dots, b_q$ be the indexes of symbols ')' in the string. Let $i$ be the largest index for which $a_i < b_{q-i+1}$. We claim that we can delete subsequence $\\{a_1, a_2, \\dots, a_i, b_{q-i+1}, \\dots, b_{q-1}, b_q\\}$, and won't be able to apply any operation to the resulting string. Indeed, suppose that in the resulting string some '(' symbol will be to the left from some ')' symbol, say they were $a_k$ and $b_l$ in out sequences. Then we must have $k>i$ and $l<q-i+1$, as they weren't deleted yet. So, we get that $b_{i+1} \\le b_k < b_l \\le b_{q-i}$, so $i$ wasn't maximal. In other words, just pick brackets greedily from ends, forming as large simple string as you can. Asymptotics $O(|s|)$.",
    "code": "string = input()\noList, cList = [], []\nfor i in range(len(string)):\n\tif string[i] == '(': oList.append(i)\n\tif string[i] == ')': cList.append(i)\n\noPtr, cPtr = 0, len(cList)-1\nremoval = []\nwhile oPtr < len(oList) and cPtr >= 0:\n\tif oList[oPtr] > cList[cPtr]: break\n\tremoval.append(oList[oPtr])\n\tremoval.append(cList[cPtr])\n\toPtr += 1\n\tcPtr -= 1\n\nremoval.sort()\nif len(removal) == 0: print(0)\nelse: print('1\\n{}\\n{}'.format(len(removal), ' '.join([str(x+1) for x in removal])))",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1305",
    "index": "C",
    "title": "Kuroni and Impossible Calculation",
    "statement": "To become the king of Codeforces, Kuroni has to solve the following problem.\n\nHe is given $n$ numbers $a_1, a_2, \\dots, a_n$. Help Kuroni to calculate $\\prod_{1\\le i<j\\le n} |a_i - a_j|$. As result can be very big, output it modulo $m$.\n\nIf you are not familiar with short notation, $\\prod_{1\\le i<j\\le n} |a_i - a_j|$ is equal to $|a_1 - a_2|\\cdot|a_1 - a_3|\\cdot$ $\\dots$ $\\cdot|a_1 - a_n|\\cdot|a_2 - a_3|\\cdot|a_2 - a_4|\\cdot$ $\\dots$ $\\cdot|a_2 - a_n| \\cdot$ $\\dots$ $\\cdot |a_{n-1} - a_n|$. In other words, this is the product of $|a_i - a_j|$ for all $1\\le i < j \\le n$.",
    "tutorial": "Let's consider $2$ cases. $n\\le m$. Then we can calculate this product directly in $O(n^2)$. $n\\le m$. Then we can calculate this product directly in $O(n^2)$. $n > m$. Note that there are only $m$ possible remainders under division by $m$, so some $2$ numbers of $n$ have the same remainder. Then their difference is divisible by $m$, so the entire product is $0 \\bmod m$. $n > m$. Note that there are only $m$ possible remainders under division by $m$, so some $2$ numbers of $n$ have the same remainder. Then their difference is divisible by $m$, so the entire product is $0 \\bmod m$. Asymptotic $O(m^2)$.",
    "code": "n, m = map(int, input().split())\na = list(map(int, input().split()))\n\nif n > m: exit(print(0))\n\nans = 1\nfor i in range(n):\n\tfor j in range(i+1, n):\n\t\tans *= abs(a[i] - a[j])\n\t\tans %= m\nprint(ans)",
    "tags": [
      "brute force",
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1305",
    "index": "D",
    "title": "Kuroni and the Celebration",
    "statement": "\\textbf{This is an interactive problem.}\n\nAfter getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!\n\nThe United States of America can be modeled as a tree (why though) with $n$ vertices. The tree is rooted at vertex $r$, wherein lies Kuroni's hotel.\n\nKuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $u$ and $v$, and it'll return a vertex $w$, which is the lowest common ancestor of those two vertices.\n\nHowever, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $\\lfloor \\frac{n}{2} \\rfloor$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(\n\nAs the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?",
    "tutorial": "For each question, pick any two leaves $u$ and $v$ and ask for the lowest common ancestor of them. The answer is either $u$ or $v$: The root of the tree must be the answer we received. The answer is neither $u$ nor $v$: Since $u$ and $v$ are leaves, there are no other vertices that lie within the subtree of either of these vertices. We remove $u$ and $v$ from the tree and repeat the process. We repeat the process until we find the root in one of the question, or there is one vertex remaining in tree which will be our root. Complexity: $O(n)$.",
    "code": "from sys import stdout\n\ndef ask(u, v):\n\tprint('? {} {}'.format(u+1, v+1))\n\tstdout.flush()\n\treturn (int(input()) - 1)\n\ndef answer(r):\n\tprint('! {}'.format(r+1))\n\tstdout.flush()\n\texit()\n\nn = int(input())\nadj = [{} for _ in range(n)]\nisLeaf = {}\n\ndef purge(z, last, blockpoint):\n\tif z in isLeaf: isLeaf.pop(z)\n\n\tfor t in adj[z].keys():\n\t\tif t == last: continue\n\t\tif t == blockpoint: adj[t].pop(z)\n\t\telif len(adj[t]) > 0: purge(t, z, blockpoint)\n\t\n\tadj[z].clear()\n\nfor _ in range(n-1):\n\tx, y = map(lambda s: int(s)-1, input().split())\n\tadj[x][y] = True\n\tadj[y][x] = True\n\nfor i in range(n):\n\tif len(adj[i]) == 1: isLeaf[i] = True\n\nwhile len(isLeaf) > 1:\n\ttaken = []\n\tfor key in isLeaf.keys():\n\t\ttaken.append(key)\n\t\tif len(taken) == 2: break\n\t\n\tfor key in taken: isLeaf.pop(key)\n\tw = ask(taken[0], taken[1])\n\n\tif w in taken: answer(w)\n\tfor key in taken: purge(key, -1, w)\n\tif len(adj[w]) <= 1: isLeaf[w] = True\n\nfor key in isLeaf.keys(): answer(key)",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "interactive",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1305",
    "index": "E",
    "title": "Kuroni and the Score Distribution",
    "statement": "Kuroni is the coordinator of the next Mathforces round written by the \"Proof by AC\" team. All the preparation has been done, and he is discussing with the team about the score distribution for the round.\n\nThe round consists of $n$ problems, numbered from $1$ to $n$. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array $a_1, a_2, \\dots, a_n$, where $a_i$ is the score of $i$-th problem.\n\nKuroni thinks that the score distribution should satisfy the following requirements:\n\n- The score of each problem should be a positive integer not exceeding $10^9$.\n- A harder problem should grant a strictly higher score than an easier problem. In other words, $1 \\leq a_1 < a_2 < \\dots < a_n \\leq 10^9$.\n- The \\textbf{balance} of the score distribution, defined as the number of triples $(i, j, k)$ such that $1 \\leq i < j < k \\leq n$ and $a_i + a_j = a_k$, should be exactly $m$.\n\nHelp the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output $-1$.",
    "tutorial": "Firstly, note that for each $i$, there can't be more than $\\lfloor \\frac{i-1}{2} \\rfloor$ triples of form $(x, y, i)$ with $a_x + a_y = a_i$. This is true as every index $j$ can meet at most once among all $x, y$ (as the third index is uniquely determined by $i$, $j$). Therefore, the answer can't exceed $\\lfloor \\frac{0}{2} \\rfloor + \\lfloor \\frac{1}{2} \\rfloor + \\dots + \\lfloor \\frac{n-1}{2} \\rfloor = N$. So, if $m>N$, answer is $-1$. Note that the sequence $a_i = i$ has balance exactly $N$. Now we show how to construct the answer for any given $m\\le N$. If $m = N$, we just output sequence $a_i = i$. Now suppose that $\\sum_{i = 1}^k \\lfloor \\frac{i-1}{2} \\rfloor \\le m < \\sum_{i = 1}^{k+1} \\lfloor \\frac{i-1}{2} \\rfloor$ for some $k$. Then let's choose $a_i = i$ for $i = 1, 2, \\dots, k$, and choose $a_{k+1} = 2k + 1 - 2(m - \\sum_{i = 1}^k \\lfloor \\frac{i-1}{2})$. We get balance of $\\sum_{i = 1}^k \\lfloor \\frac{i-1}{2} \\rfloor$ from first $k$ numbers, and $m - \\sum_{i = 1}^k \\lfloor \\frac{i-1}{2} \\rfloor$ triples of form $(x, y, k+1)$ (precisely $(k + 1 - 2(m - \\sum_{i = 1}^k \\lfloor \\frac{i-1}{2} \\rfloor), k, k+1), (k + 2 - 2(m - \\sum_{i = 1}^k \\lfloor \\frac{i-1}{2} \\rfloor), k-1, k+1), \\dots$). We have achieved the desired balance now, and just have to choose $a_i$ for $i>k+1$ such that they don't form any other good triples. For this, we can take $a_i = 10^8 + 1 + 10^4i$ for $i>k+1$, for example (sum of two odd numbers can't be odd, no $a_i$ with $i>k+1$ can be equal to $a_x + a_y$ with $x, y\\le k+1$ as $a_i$ is much larger, and $a_x + a_y = a_i$ for $i, y>k+1, x\\le k+1$ is impossible as $a_x<10^4$).",
    "code": "n, m = map(int, input().split())\n\nnumList = [x+1 for x in range(n)]\nbackdoor = []\n\ncount = sum([(i-1) // 2 for i in range(1, n+1)])\n\nif count < m: exit(print(-1))\n\nwhile count > m:\n\tlastpop = numList.pop()\n\tcount -= (lastpop - 1) // 2\n\n\tif count >= m:\n\t\tif len(backdoor) == 0: backdoor.append(10 ** 9)\n\t\telse: backdoor.append(backdoor[-1] - 2 ** 16)\n\telse:\n\t\tgap = m - count\n\t\tbackdoor.append(2 * (lastpop - gap) - 1)\n\t\tcount += gap\n\nwhile len(backdoor) > 0: numList.append(backdoor.pop())\n\nprint(' '.join([str(x) for x in numList]))",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1305",
    "index": "F",
    "title": "Kuroni and the Punishment",
    "statement": "Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:\n\nYou have an array $a$ consisting of $n$ positive integers. An operation consists of choosing an element and either adding $1$ to it or subtracting $1$ from it, such that the element remains positive. We say the array is \\textbf{good} if the greatest common divisor of all its elements is not $1$. Find the minimum number of operations needed to make the array good.\n\nUnable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!",
    "tutorial": "First, let's assume we have a fixed positive integer $d \\ge 2$, and we want to find the minimum number of operations needed to make all elements divisible by $d$. Then a simple greedy algorithm gives us the answer: For each element $x$ just apply operations to transform it into the closest multiple of $d$, which is either $x - x \\bmod{d}$ or $x + d - x \\bmod{d}$. This gives us a linear algorithm. Now we will reduce the integers that we have to check to a small set, and use this greedy algorithm to check each. First look at what happens if we choose $d = 2$. Every number is at distance at most $1$ from a multiple of $2$, so we apply at most one operation on each number. Therefore the answer to the problem is at most $n$. Now, notice that since the answer to the problem is at most $n$, when we apply the optimal sequence of operations there are at least $\\frac{n}{2}$ elements which are affected by at most one operation. Therefore, if we choose an element $x$ of the array at random, with probability at least $\\frac{1}{2}$ an optimal solution will be given by a prime divisor of $x$, $x - 1$ or $x + 1$. Then, to solve the problem we can repeatedly choose a random element $x$ of the array, find the prime factors of $x$, $x - 1$ and $x + 1$, and run our greedy algorithm with these prime factors. If we run this for enough operations we find the optimal answer with a very high probability. Final complexity is $O(it(\\sqrt{MAX} + n \\log MAX))$ where $it$ denotes the number of elements we choose. This is because we can factor in $O(\\sqrt{MAX})$ and each number has $O(\\log MAX)$ prime divisors. For $it = 20$ the probability of failure for each test case is at most $2^{-20}$, which is small enough to be sure that it is correct.",
    "code": "import random\n\nn = int(input())\na = list(map(int, input().split()))\n\nlimit = min(8, n)\niterations = [x for x in range(n)]\nrandom.shuffle(iterations)\niterations = iterations[:limit]\n\ndef factorization(x):\n\tprimes = []\n\ti = 2\n\twhile i * i <= x:\n\t\tif x % i == 0:\n\t\t\tprimes.append(i)\n\t\t\twhile x % i == 0: x //= i\n\t\ti = i + 1\n\tif x > 1: primes.append(x)\n\treturn primes\n\ndef solve_with_fixed_gcd(arr, gcd):\n\tresult = 0\n\tfor x in arr:\n\t\tif x < gcd: result += (gcd - x)\n\t\telse:\n\t\t\tremainder = x % gcd\n\t\t\tresult += min(remainder, gcd - remainder)\n\treturn result\n\nanswer = float(\"inf\")\nprime_list = set()\nfor index in iterations:\n\tfor x in range(-1, 2):\n\t\ttmp = factorization(a[index]-x)\n\t\tfor z in tmp: prime_list.add(z)\n\nfor prime in prime_list:\n\tanswer = min(answer, solve_with_fixed_gcd(a, prime))\n\tif answer == 0: break\n\nprint(answer)",
    "tags": [
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1305",
    "index": "G",
    "title": "Kuroni and Antihype",
    "statement": "Kuroni isn't good at economics. So he decided to found a new financial pyramid called \\textbf{Antihype}. It has the following rules:\n\n- You can join the pyramid for free and get $0$ coins.\n- If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite).\n\n$n$ people have heard about Antihype recently, the $i$-th person's age is $a_i$. Some of them are friends, but friendship is a weird thing now: the $i$-th person is a friend of the $j$-th person \\textbf{if and only if} $a_i \\text{ AND } a_j = 0$, where $\\text{AND}$ denotes the bitwise AND operation.\n\nNobody among the $n$ people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them?",
    "tutorial": "Let's forget about the structure of our graph of friendship first and let's solve a more general problem: what are the highest possible total gainings of all people given some edges. Firstly, let's suppose there is a $n+1$-th person with age $a_{n+1} = 0$ in Antihype already, who is friend with everybody. We can suppose that instead of someone joining Antihype for free, he is invited by this person. Now, let's color the edge between $i$ and $j$ in red if $a_i$ invited $a_j$ or $a_j$ invited $a_i$. Note that red edges form a tree. Let's write on an edge between $i$ and $j$ $a_i + a_j$. Surprising fact: For a given tree $G$ of invitations, the total gainings are equal to the sum of numbers on the edges of the tree - sum of all $a_i$! Proof: Suppose that the degree of person $i$ in $G$ is $v_i$. Then this person was invited once and invited $v_i - 1$ times, giving $a_i(v_i - 1)$ coins in total. $\\sum_{i = 1}^{n+1} a_i(v_i - 1) = \\sum_{i = 1}^{n+1} a_i\\cdot v_i - \\sum_{i = 1}^{n+1} a_i = \\sum_{(i, j)\\in G} (a_i + a_j) - \\sum_{i = 1}^{n+1} a_i$. Now the solution is easy: on each edge $(i, j)$, write $a_i + a_j$ on it, find Maximum Spanning Tree, and subtract sum of $a_i$. The $n+1$-th person works out well in out version of the problem: he is friend of everybody as $a_{n+1}\\text{ AND }a_i = 0\\text{ AND }a_i = 0$. However, we can't find MST directly, as there can be $\\Omega(n^2)$ edges. There are two approaches now: Approach 1: Find MST with Borůvka's algorithm. Let's do $\\log{n}$ iterations of the following: For each mask, find two largest present weights (from different components) which are submasks of this mask in $O(2^{18} \\cdot 18)$ with SOS DP. Then, for each component we can find the edge from this component to some other component with the largest weight, and do one iteration of Boruvka. Complexity $O(2^{18} \\cdot 18 \\cdot log(n)$). Approach 2: Make a list of people with each age first. Now, for $i$ from $2^{18} - 1$ to $0$, iterate through submasks of $i$, let it be $j$, and make edges between people with ages $j$ and $i\\text{ XOR }j$, this edge will have weight of $i$. This works in $O(3^{18}\\cdot\\alpha(n))$, which is fast enough to pass.",
    "code": "import sys\nrange = xrange\ninput = raw_input\n\nn = int(input())\nA = [int(x) for x in input().split()]\n\nm = 2**18\ncount = [0]*m\nfor a in A:\n    count[a] += 1\ncount[0] += 1\n\n# Using dsu with O(1) lookup and O(log(n)) merge\nowner = list(range(m))\nsets = [[i] for i in range(m)]\n \ntotal = 0\nfor profit in reversed(range(m)):\n    a = profit\n    b = a ^ profit\n    while a > b:\n        if count[a] and count[b] and owner[a] != owner[b]:\n            total += (count[a] + count[b] - 1) * profit\n            count[a] = 1\n            count[b] = 1\n            \n            small = owner[a]\n            big = owner[b]\n            if len(sets[small]) > len(sets[big]):\n                small, big = big, small\n            for c in sets[small]:\n                owner[c] = big\n            sets[big] += sets[small]\n        a = (a - 1) & profit\n        b = a ^ profit\nprint total - sum(A)",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "dsu",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1305",
    "index": "H",
    "title": "Kuroni the Private Tutor",
    "statement": "As a professional private tutor, Kuroni has to gather statistics of an exam. Kuroni has appointed you to complete this important task. You must not disappoint him.\n\nThe exam consists of $n$ questions, and $m$ students have taken the exam. Each question was worth $1$ point. Question $i$ was solved by at least $l_i$ and at most $r_i$ students. Additionally, you know that the total score of all students is $t$.\n\nFurthermore, you took a glance at the final ranklist of the quiz. The students were ranked from $1$ to $m$, where rank $1$ has the highest score and rank $m$ has the lowest score. Ties were broken arbitrarily.\n\nYou know that the student at rank $p_i$ had a score of $s_i$ for $1 \\le i \\le q$.\n\nYou wonder if there could have been a huge tie for first place. Help Kuroni determine the maximum number of students who could have gotten as many points as the student with rank $1$, and the maximum possible score for rank $1$ achieving this maximum number of students.",
    "tutorial": "Suppose we fix the scores of the students $b_0 \\le b_1 \\le  \\dots  \\le b_{m-1}$. We model our problem as a flow graph. Consider a flow graph where the left side contains the source and $n$ nodes denoting the problems, and the right side contains the sink and $m$ nodes denoting the students. Each problem node is connected to each student node with capacity $1$. The source is connected to the node for problem $i$ with minimum capacity $L_{i}$ and maximum capacity $R_{i}$. The node for student $i$ is connected to the sink with capacity $b_i$. Our assignment is valid iff there is a valid saturating flow. We can build a flow graph with demands (minimum capacity for some edges) as a normal flow graph. You can find more information on how to build it here: https://cp-algorithms.com/graph/flow_with_demands.html. We want to ensure that our minimum cut is at least $T$. Let $B[i] = \\displaystyle\\sum_{i=0}^{i}b_i$ (with $B[-1]=0$), $L[i]$ and $R[i]$ denote the sum of the $i$ smallest $L$ and $R$ values respectively. Let $s_L$ denote the sum of all $L$ values. Analyzing the possibilities for minimum cut, we can show that our minimum cut is at least $T$ iff the following two conditions hold for all $0 \\le i \\le m$ and $0 \\le j \\le n$: $R[j] + B[i-1] + (n-j)(m-i) \\ge T$ $L[j] + B[i-1] + (n-j)(m-i) \\ge s_L$ If we fix the values of $b_i$, we can check whether these conditions hold using Convex Hull Trick in $O(n+m)$ (by fixing $i$ and varying $j$). How to determine which $b_i$ values to use. From our formulas, it is clear that if there are no additional restrictions, if two sequences $a_i$, $b_i$ are such that $b_i$ majorizes $a_i$, then $b_i$ is a better choice than $a_i$. We can binary search the maximum number of students with a tie for first place. We try to assign the minimum possible score for each student satisfying all the constraints given. We still have some additional \"score\" left before our sum of scores reach $T$. We want to determine the maximum score our highest-scoring student can obtain. It can be proven that the set of valid maximum scores forms a range starting from the smallest $x$ such that there exists a valid $b_i$ arrangement satisfying all the problem conditions except the conditions for flow. Thus, we can binary search to find $x$ and also binary search to find the maximum possible score. The solution works in $O((n+m)\\log^{2}n)$ time.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n \nusing namespace std;\nusing namespace __gnu_pbds;\n \n#define fi first\n#define se second\n#define mp make_pair\n#define pb push_back\n#define fbo find_by_order\n#define ook order_of_key\n \ntypedef long long ll;\ntypedef pair<int,int> ii;\ntypedef vector<ll> vi;\ntypedef long double ld; \ntypedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds;\n\nconst int N = 150000; //number of problems\nconst int M = 150000; //number of students\n\nint L[N+10];\nint R[N+10];\nint a[N+10]; //array of fixed score\nll T; \nint n,m; \n\nvoid read()\n{\n\tcin>>n>>m;\n\tfor(int i=0;i<n;i++) //problem score\n\t{\n\t\tcin>>L[i]>>R[i];\n\t}\n\tfor(int i=0;i<m;i++) a[i]=-1;\n\tint q; cin>>q;\n\tfor(int i=0;i<q;i++)\n\t{\n\t\tint rk, sc; cin>>rk>>sc;\n\t\ta[m-rk] = sc;\n\t}\n\tcin>>T; //total score\t\n}\n\nvector<ll> sortedL,sortedR;\n\nstruct ConvexHull \n{\n    struct Line \n    {\n        ll m, c;\n\n        Line (ll _m, ll _c) : m(_m), c(_c) {}\n\n        ll pass(ll x) {\n            return m * x + c;\n        }\n    };\n    deque<Line> d;\n    bool irrelevant(Line Z) \n    {\n        if (int(d.size()) < 2) return false;\n    \n        Line X = d[int(d.size())-2], Y = d[int(d.size())-1];\n\n        return (X.c - Z.c) * (Y.m - X.m) <= (X.c - Y.c) * (Z.m - X.m);\n    }\n    void push_line(ll m, ll c) \n    {\n        Line l = Line(m,c);\n        while (irrelevant(l)) d.pop_back();\n        d.push_back(l);\n    }\n    ll query(ll x) {\n        while (int(d.size()) > 1 && (d[0].c - d[1].c <= x * (d[1].m - d[0].m))) d.pop_front();\n        return d.front().pass(x);\n    }\n};\n\nbool check_naive(vector<int> b) //check if your assignment is valid\n{\n\tll sumB = 0;\n\tll sumL = 0;\n\tsort(b.begin(),b.end());\n\tfor(int i=0;i<b.size();i++)\n\t{\n\t\tsumB+=b[i];\n\t\tif(a[i]!=-1) assert(a[i]==b[i]);\n\t\tif(i>0) assert(b[i]>=b[i-1]);\n\t}\n\tfor(int i=0;i<n;i++) sumL+=L[i];\n\tassert(int(b.size())==m&&sumB==T);\n\tll cursum=0;\n\tfor(int i=0;i<=m;i++)\n\t{\n\t\tfor(int j=0;j<=n;j++)\n\t\t{\n\t\t\tll s1 = sortedR[j]+cursum+(n-j)*1LL*(m-i);\n\t\t\tll s2 = sortedL[j]+cursum+(n-j)*1LL*(m-i);\n\t\t\tif(s1<sumB||s2<sumL) return false;\n\t\t}\n\t\tif(i<m) cursum+=b[i];\n\t}\n\treturn true;\n}\n\nbool check(vector<int> b) //check if your assignment is valid\n{\n\tll sumB = 0;\n\tll sumL = 0;\n\tsort(b.begin(),b.end());\n\tfor(int i=0;i<b.size();i++)\n\t{\n\t\tsumB+=b[i];\n\t\tif(a[i]!=-1) assert(a[i]==b[i]);\n\t\tif(i>0) assert(b[i]>=b[i-1]);\n\t}\n\tfor(int i=0;i<n;i++) sumL+=L[i];\n\tassert(int(b.size())==m&&sumB==T);\n\tll cursum=0;\n\tConvexHull ch1,ch2;\n\tfor(int j=n;j>=0;j--)\n\t{\n\t\tch1.push_line(n-j,-sortedR[j]+j*1LL*m);\n\t\tch2.push_line(n-j,-sortedL[j]+j*1LL*m);\n\t}\n\tfor(int i=0;i<=m;i++)\n\t{\n\t\tll v1 = -ch1.query(i);\n\t\tll v2 = -ch2.query(i);\n\t\tif(v1<sumB-(cursum+n*1LL*m)||v2<sumL-(cursum+n*1LL*m)) return false;\n\t\tif(i<m) cursum+=b[i];\n\t}\n\treturn true;\n}\n\nvoid greedyrange(vector<int> &v, int l, int r, int ub, ll &S) \n{\n\tif(S<=0) return ;\n\tll ext = 0;\n\tfor(int i=l;i<=r;i++)\n\t{\n\t\text+=ub-v[i];\n\t}\n\tif(ext<=S)\n\t{\n\t\tS-=ext;\n\t\tfor(int i=l;i<=r;i++)\n\t\t{\n\t\t\tv[i]=ub;\n\t\t}\n\t\treturn ;\n\t}\n\tdeque<ii> dq; \n\tfor(int i=l;i<=r;i++) \n\t{\n\t\tif(!dq.empty()&&dq.back().fi==v[i])\n\t\t{\n\t\t\tdq.back().se++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdq.pb({v[i],1});\n\t\t}\n\t}\n\twhile(S>0&&dq.size()>1)\n\t{\n\t\tint L = dq[0].fi; int cnt = dq[0].se;\n\t\tint R = dq[1].fi;\n\t\t//I have (R-L)*cnt before absolute merge\n\t\tif((R-L)*1LL*cnt<=S)\n\t\t{\n\t\t\tS-=(R-L)*1LL*cnt;\n\t\t\tdq[1].se+=cnt;\n\t\t\tdq.pop_front();\n\t\t\tcontinue;\n\t\t}\n\t\t//not enough space liao\n\t\tll q = S/cnt;\n\t\tll rem = S%cnt;\n\t\tdq[0].fi+=q;\n\t\tif(rem>0)\n\t\t{\n\t\t\tii tmp = dq.front();\n\t\t\tdq.pop_front();\n\t\t\tdq.push_front({rem,tmp.fi+1});\n\t\t\tdq.push_front({cnt-rem,tmp.fi});\n\t\t}\n\t\tS=0;\n\t\tbreak;\n\t}\n\t//S>0\n\tif(S>0)\n\t{\n\t\tassert(int(dq.size())==1);\n\t\tll q = S/(r-l+1);\n\t\tll rem = S%(r-l+1);\n\t\tfor(int i=l;i<=r;i++)\n\t\t{\n\t\t\tv[i]=dq[0].fi+q;\n\t\t}\n\t\tint ptr=r;\n\t\tfor(int i=0;i<rem;i++)\n\t\t{\n\t\t\tv[ptr--]++;\n\t\t}\n\t\tS=0;\n\t}\n\telse\n\t{\n\t\tint ptr=l;\n\t\tfor(ii x:dq)\n\t\t{\n\t\t\tfor(int j=0;j<x.se;j++) v[ptr++]=x.fi;\n\t\t}\n\t}\n}\n\nvoid greedy(vector<int> &v, ll &S)\n{\n\tif(S<=0) return ;\n\tvi ans;\n\tvector<ii> ranges;\n\tint l=0;\n\tfor(int i=0;i<m;i++)\n\t{\n\t\tif(a[i]==-1) continue;\n\t\tif(l<=i-1)\n\t\t{\n\t\t\tranges.pb({l,i-1});\n\t\t}\n\t\tl=i+1;\n\t}\n\tif(l<m) ranges.pb({l,m-1});\n\tfor(ii x:ranges)\n\t{\n\t\tint r=x.se;\n\t\tint ub = n;\n\t\tif(r+1<m&&a[r+1]!=-1) ub=a[r+1];\n\t\tgreedyrange(v,x.fi,x.se,ub,S);\n\t}\n}\n\nii solve_full()\n{\n\tsortedL.clear(); sortedR.clear();\n\tsortedL.pb(0); sortedR.pb(0);\n\tfor(int i=0;i<n;i++)\n\t{\n\t\tsortedL.pb(L[i]);\n\t\tsortedR.pb(R[i]);\n\t}\n\tsort(sortedL.begin(),sortedL.end());\n\tsort(sortedR.begin(),sortedR.end());\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tsortedL[i]+=sortedL[i-1];\n\t\tsortedR[i]+=sortedR[i-1];\n\t}\n\t//at least k people tie for first?\n\tint lo = 1; int hi = m; \n\tint anstie = -1;\n\tint ansm = 0;\n\tvector<int> testb;\n\tvi ori(m,-1);\n\twhile(lo<=hi)\n\t{\n\t\tint mid=(lo+hi)>>1;\n\t\tvector<int> b;\n\t\tint curmin=0;\n\t\tll cursum=0;\n\t\tfor(int i=0;i<m;i++)\n\t\t{\n\t\t\tif(a[i]!=-1) curmin=a[i];\n\t\t\tb.pb(curmin);\n\t\t\tcursum+=b[i];\n\t\t}\n\t\t//left T - cursum stuff to add :(\n\t\t//fix the maximum M\n\t\tbool pos=0;\n\t\tint forcedM=-1;\n\t\tfor(int j=m-mid;j<m;j++)\n\t\t{\n\t\t\tif(a[j]>=0)\n\t\t\t{\n\t\t\t\tif(forcedM>=0&&forcedM!=a[j]) forcedM=-2;\n\t\t\t\tforcedM = a[j];\n\t\t\t}\n\t\t}\n\t\tif(forcedM>=-1)\n\t\t{\n\t\t\tint L2 = curmin; int R2 = n;\n\t\t\tif(forcedM>=0) L2=R2=forcedM;\n\t\t\t//otherwise L2 is the smallest d+curmin such that there EXIST a good covering\n\t\t\tif(forcedM<0)\n\t\t\t{\n\t\t\t\tint lo2 = curmin; int hi2 = max(0LL,min(ll(n),(T-cursum)/mid+curmin)); //add to everyone i guess\n\t\t\t\tL2=int(1e9);\n\t\t\t\twhile(lo2<=hi2)\n\t\t\t\t{\n\t\t\t\t\tint mid2=(lo2+hi2)>>1;\n\t\t\t\t\tvector<int> nwb = b;\n\t\t\t\t\tll rem = T - cursum;\n\t\t\t\t\tint M = mid2;\n\t\t\t\t\tfor(int j=m-mid;j<m;j++)\n\t\t\t\t\t{\n\t\t\t\t\t\trem+=b[j];\n\t\t\t\t\t\trem-=M;\n\t\t\t\t\t\tnwb[j]=M;\n\t\t\t\t\t\tif(a[j]>=0&&nwb[j]!=a[j]) {rem=-ll(1e18);}\n\t\t\t\t\t\tori[j]=a[j];\n\t\t\t\t\t\ta[j]=M;\n\t\t\t\t\t}\n\t\t\t\t\tgreedy(nwb, rem);\n\t\t\t\t\tfor(int j=m-mid;j<m;j++)\n\t\t\t\t\t{\n\t\t\t\t\t\ta[j]=ori[j];\n\t\t\t\t\t}\n\t\t\t\t\tif(rem==0)\n\t\t\t\t\t{\n\t\t\t\t\t\thi2=mid2-1;\n\t\t\t\t\t\tL2=mid2;\n\t\t\t\t\t}\n\t\t\t\t\telse \n\t\t\t\t\t{\n\t\t\t\t\t\tlo2=mid2+1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\t//how to figure out L2 otherwise!?\n\t\t\twhile(L2<=R2)\n\t\t\t{\n\t\t\t\tint M = (L2+R2)>>1;\n\t\t\t\tvector<int> nwb = b;\n\t\t\t\tll rem = T - cursum;\n\t\t\t\tfor(int j=m-mid;j<m;j++)\n\t\t\t\t{\n\t\t\t\t\trem+=b[j];\n\t\t\t\t\trem-=M;\n\t\t\t\t\tnwb[j]=M;\n\t\t\t\t\tif(a[j]>=0&&nwb[j]!=a[j]) {rem=-ll(1e18);}\n\t\t\t\t\tori[j]=a[j];\n\t\t\t\t\ta[j]=M;\n\t\t\t\t}\n\t\t\t\tgreedy(nwb, rem);\n\t\t\t\tif(rem==0&&check(nwb))\n\t\t\t\t{\n\t\t\t\t\ttestb=nwb; ansm=M;\n\t\t\t\t\tpos=1; L2=M+1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tR2=M-1;\n\t\t\t\t}\n\t\t\t\tfor(int j=m-mid;j<m;j++)\n\t\t\t\t{\n\t\t\t\t\ta[j]=ori[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(pos)\n\t\t{\n\t\t\tanstie=mid;\n\t\t\tlo=mid+1;\n\t\t}\n\t\telse hi=mid-1;\n\t}\n\tif(anstie==-1)\n\t{\n\t\treturn {-1,-1};\n\t}\n\treturn {anstie,ansm};\n}\n\n\nint main()\n{\n\tios_base::sync_with_stdio(0); cin.tie(0);\n\t//freopen(\"student-scores.in\",\"r\",stdin);\n\tread();\n\tii sol2 = solve_full();\n\tcout<<sol2.fi<<' '<<sol2.se<<'\\n';\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1307",
    "index": "A",
    "title": "Cow and Haybales",
    "statement": "The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $n$ haybale piles on the farm. The $i$-th pile contains $a_i$ haybales.\n\nHowever, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $i$ and $j$ ($1 \\le i, j \\le n$) such that $|i-j|=1$ and $a_i>0$ and apply $a_i = a_i - 1$, $a_j = a_j + 1$. She may also decide to not do anything on some days because she is lazy.\n\nBessie wants to maximize the number of haybales in pile $1$ (i.e. to maximize $a_1$), and she only has $d$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $1$ if she acts optimally!",
    "tutorial": "At any point, it is optimal to move a haybale in the closest pile from pile $1$ to the left. So, for every day, we can loop through the piles from left to right and move the first haybale we see closer. If all the haybales are in pile $1$ at some point, we can stop early. Time Complexity: $O(n \\cdot d)$",
    "code": "#include <iostream>\nusing namespace std;\n\nint N,D,a[105],ans;\n\nint main(){\n  int T; cin>>T;\n  while (T--){\n    cin>>N>>D;\n    for (int i=1;i<=N;i++)\n      cin>>a[i];\n    for (int i=2;i<=N;i++){\n      int move=min(a[i],D/(i-1)); //number of haybales we can move from pile i to pile 1\n      a[1]+=move; //update pile 1\n      D-=move*(i-1); //update remaining days\n    }\n    cout<<a[1]<<endl;\n  }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1307",
    "index": "B",
    "title": "Cow and Friend",
    "statement": "Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play!\n\nMore specifically, he wants to get from $(0,0)$ to $(x,0)$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $n$ favorite numbers: $a_1, a_2, \\ldots, a_n$. What is the minimum number of hops Rabbit needs to get from $(0,0)$ to $(x,0)$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.\n\nRecall that the Euclidean distance between points $(x_i, y_i)$ and $(x_j, y_j)$ is $\\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$.\n\nFor example, if Rabbit has favorite numbers $1$ and $3$ he could hop from $(0,0)$ to $(4,0)$ in two hops as shown below. Note that there also exists other valid ways to hop to $(4,0)$ in $2$ hops (e.g. $(0,0)$ $\\rightarrow$ $(2,-\\sqrt{5})$ $\\rightarrow$ $(4,0)$).\n\n\\begin{center}\n{\\small Here is a graphic for the first example. Both hops have distance $3$, one of Rabbit's favorite numbers.}\n\\end{center}\n\nIn other words, each time Rabbit chooses some number $a_i$ and hops with distance equal to $a_i$ in any direction he wants. The same number can be used multiple times.",
    "tutorial": "If the distance $d$ is in the set, the answer is $1$. Otherwise, let $y$ denote Rabbit's largest favorite number. The answer is $max(2,\\lceil \\frac{d}{y}\\rceil)$. This is true because clearly the answer is at least $\\lceil\\frac{d}{y}\\rceil$: if it were less Rabbit can't even reach distance $d$ away from the origin. If $\\lceil\\frac{d}{y}\\rceil$ is at least $2$, we can reach $(d,0)$ in exactly that number of hops by hopping to the right $\\lceil\\frac{d}{y}\\rceil-2$ times using $y$ then using the last $2$ hops for up to $2y$ additional distance. Time Complexity: $O(n)$",
    "code": "#include <iostream>\n#include <set>\n#include <algorithm>\nusing namespace std;\n\nset<int>a;\n//you don't have to use set, it was just easier for us\n\nint main(){\n  int T; cin>>T;\n  while (T--){\n    int N,X;\n    cin>>N>>X;\n    int far=0; //largest favorite number\n    for (int i=0;i<N;i++){\n      int A;\n      cin>>A;\n      a.insert(A);\n      far=max(far,A);\n    }\n    if (a.count(X)) //X is favorite number\n      cout<<1<<endl;\n    else\n      cout<<max(2,(X+far-1)/far)<<endl; //expression as explained in tutorial\n    a.clear();\n  }\n}",
    "tags": [
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1307",
    "index": "C",
    "title": "Cow and Message",
    "statement": "Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.\n\nThe text is a string $s$ of lowercase Latin letters. She considers a string $t$ as hidden in string $s$ if $t$ exists as a subsequence of $s$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $1$, $3$, and $5$, which form an arithmetic progression with a common difference of $2$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $S$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!\n\nFor example, in the string aaabb, a is hidden $3$ times, b is hidden $2$ times, ab is hidden $6$ times, aa is hidden $3$ times, bb is hidden $1$ time, aab is hidden $2$ times, aaa is hidden $1$ time, abb is hidden $1$ time, aaab is hidden $1$ time, aabb is hidden $1$ time, and aaabb is hidden $1$ time. The number of occurrences of the secret message is $6$.",
    "tutorial": "We observe that if the hidden string that occurs the most times has length longer than $2$, then there must exist one that occurs just as many times of length exactly $2$. This is true because we can always just take the first $2$ letters; there can't be any collisions. Therefore, we only need to check strings of lengths $1$ and $2$. Checking strings of length $1$ is easy. To check strings of length $2$, we can iterate across $S$ from left to right and update the number of times we have seen each string of length $1$ and $2$ using DP. Time Complexity: $O(|s|c)$ (c is length of alphabet)",
    "code": "#include <iostream>\nusing namespace std;\n\ntypedef long long ll;\nll arr1[26],arr2[26][26];\n\nint main(){\n  string S;\n  cin>>S;\n  for (int i=0;i<S.length();i++){\n    int c=S[i]-'a';\n    for (int j=0;j<26;j++)\n      arr2[j][c]+=arr1[j];\n    arr1[c]++;\n  }\n  ll ans=0;\n  for (int i=0;i<26;i++)\n    ans=max(ans,arr1[i]);\n  for (int i=0;i<26;i++)\n    for (int j=0;j<26;j++)\n      ans=max(ans,arr2[i][j]);\n  cout<<ans<<endl;\n}",
    "tags": [
      "brute force",
      "dp",
      "math",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1307",
    "index": "D",
    "title": "Cow and Fields",
    "statement": "Bessie is out grazing on the farm, which consists of $n$ fields connected by $m$ bidirectional roads. She is currently at field $1$, and will return to her home at field $n$ at the end of the day.\n\nThe Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has $k$ special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.\n\nAfter the road is added, Bessie will return home on the shortest path from field $1$ to field $n$. Since Bessie needs more exercise, Farmer John must \\textbf{maximize} the length of this shortest path. Help him!",
    "tutorial": "There are a few solutions that involve breadth first search (BFS) and sorting, this is just one of them. First, let's use BFS to find the distance from fields $1$ and $n$ to each special field. For a special field $i$, let $x_i$ denote the distance to node $1$, and $y_i$ denote the distance to $n$. We want to choose two fields $a$ and $b$ to maximize $min(x_a+y_b,y_a+x_b)$. Without loss of generality, suppose $x_a+y_b \\le y_a+x_b$. Now we want to maximize $x_a+y_b$ subject to $x_a-y_a \\le x_b-y_b$. This can be done by sorting by $x_i-y_i$ and iterating $a$ over $x$ while keeping a suffix maximum array of $y$ to compute $\\max_{b>a}{y_b}$. Remember that an upper bound of the answer is the distance between field $1$ and $n$. Time Complexity: $O(n\\log{n}+m)$",
    "code": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\nconst int INF=1e9+7;\n\nint N;\nint as[200005];\n\nstd::vector<int> edges[200005];\n\nint dist[2][200005];\nint q[200005];\n\nvoid bfs(int* dist,int s){\n  std::fill(dist,dist+N,INF);\n  int qh=0,qt=0;\n  q[qh++]=s;\n  dist[s]=0;\n  while(qt<qh){\n    int x=q[qt++];\n    for(int y:edges[x]){\n      if(dist[y]==INF){\n\tdist[y]=dist[x]+1;\n\tq[qh++]=y;\n      }\n    }\n  }\n}\n\nint main(){\n  int M,K;\n  scanf(\"%d %d %d\",&N,&M,&K);\n  for(int i=0;i<K;i++){\n    scanf(\"%d\",&as[i]);\n    as[i]--;\n  }\n  std::sort(as,as+K);\n  for(int i=0;i<M;i++){\n    int X,Y;\n    scanf(\"%d %d\",&X,&Y);\n    X--,Y--;\n    edges[X].push_back(Y);\n    edges[Y].push_back(X);\n  }\n  bfs(dist[0],0);\n  bfs(dist[1],N-1);\n  std::vector<std::pair<int,int> > data;\n  for(int i=0;i<K;i++){\n    data.emplace_back(dist[0][as[i]]-dist[1][as[i]],as[i]);\n  }\n  std::sort(data.begin(),data.end());\n  int best=0;\n  int max=-INF;\n  for(auto it:data){\n    int a=it.second;\n    best=std::max(best,max+dist[1][a]);\n    max=std::max(max,dist[0][a]);\n  }\n  printf(\"%d\\n\",std::min(dist[0][N-1],best+1));\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1307",
    "index": "E",
    "title": "Cow and Treats",
    "statement": "After a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass!\n\nOn the field, there is a row of $n$ units of grass, each with a sweetness $s_i$. Farmer John has $m$ cows, each with a favorite sweetness $f_i$ and a hunger value $h_i$. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner:\n\n- The cows from the left and right side will take turns feeding in an order decided by Farmer John.\n- When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats $h_i$ units.\n- The moment a cow eats $h_i$ units, it will fall asleep there, preventing further cows from passing it from both directions.\n- If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset.\n\nNote that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them.\n\nSurprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo $10^9+7$)? The order in which FJ sends the cows does not matter as long as no cows get upset.",
    "tutorial": "First, we observe that it is impossible to send more than one cow with the same favorite sweetness on the same side without upsetting any of them. This means we can send at most two cows of each favorite sweetness, one on each side. Now, let's assume we know the index of the rightmost cow that came from the left side. For each sweetness $i$, we denote the number of units of grass to the left of the index as $l_i$ and to the right as $r_i$. There are three cases we have to consider. If there does not exist a cow of this favorite sweetness or the one of this favorite sweetness with minimum hunger cannot be satisfied from either direction, then $0$ cows of the type will be asleep. Otherwise, $1$ or $2$ cows will be asleep, and we can derive a simple formula based on $l_i$, $r_i$, and the cows of this type. Remember that we always maximize the number of sleeping cows first. We maintain how much each sweetness contributed to the answer. When we shift this index of the rightmost cow to the right, we can undo and recompute our answer. You can speed up the solution using binary search, but we chose not to require it. We also chose to allow other $O(n^2)$ and $O(n^2\\log{n})$ solutions to pass. Time Complexity: $O(n\\log{n})$",
    "code": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n#include <cassert>\n\nconst int MOD=1e9+7;\n\nint modexp(int base,int exp){\n  int ac=1;\n  for(;exp;exp>>=1){\n    if(exp&1) ac=1LL*ac*base%MOD;\n    base=1LL*base*base%MOD;\n  }\n  return ac;\n}\n\nint inverse(int x){\n  return modexp(x,MOD-2);\n}\n\nint fs[100005];\nint left[100005],right[100005];\nstd::vector<int> cows[100005];//cows[f]: hunger of cows that like flavor f \nint asleep[100005];\nint ways[100005];\nint total_asleep=0,total_ways=1;\n\nvoid calc_ways(int f){\n  int a=std::upper_bound(cows[f].begin(),cows[f].end(),left[f])-cows[f].begin();\n  int b=std::upper_bound(cows[f].begin(),cows[f].end(),right[f])-cows[f].begin();\n  if(a>b) std::swap(a,b);\n  long long cnt2=1LL*a*b-a;\n  int cnt1=a+b;\n  cnt2%=MOD;\n  if(cnt2>0){\n    asleep[f]=2;\n    ways[f]=cnt2;\n  }else if(cnt1>0){\n    asleep[f]=1;\n    ways[f]=cnt1;\n  }else{\n    asleep[f]=0;\n    ways[f]=1;\n  }\n}\n\n//fixed left cow, with hunger left[i]\n//precondition: such cow exists\nvoid calc_ways_stuck(int f){\n  int b=std::upper_bound(cows[f].begin(),cows[f].end(),right[f])-cows[f].begin();\n  if(right[f]>=left[f])\n    b--;\n  int cnt2=b;\n  if(cnt2>0){\n    asleep[f]=2;\n    ways[f]=cnt2;\n  }else{\n    asleep[f]=1;\n    ways[f]=1;\n  }\n}\n\nint ans_asleep=0,ans_ways=0;\n\nvoid add_to_ans(int asleep,int ways){\n  if(asleep>ans_asleep){\n    ans_asleep=asleep;\n    ans_ways=0;\n  }\n  if(asleep==ans_asleep)\n    ans_ways=(ans_ways+ways)%MOD;\n}\n\nint main(){\n  int N,M;\n  scanf(\"%d %d\",&N,&M);\n  for(int i=1;i<=N;i++){\n    scanf(\"%d\",&fs[i]);\n    right[fs[i]]++;\n  }\n  for(int i=0;i<M;i++){\n    int F,H;\n    scanf(\"%d %d\",&F,&H);\n    cows[F].push_back(H);\n  }\n  for(int f=1;f<=N;f++)\n    std::sort(cows[f].begin(),cows[f].end());\n  for(int f=1;f<=N;f++){\n    calc_ways(f);\n    total_asleep+=asleep[f];\n    total_ways=1LL*total_ways*ways[f]%MOD;\n  }\n  add_to_ans(total_asleep,total_ways);\n  for(int i=1;i<=N;i++){\n    total_asleep-=asleep[fs[i]];\n    total_ways=1LL*total_ways*inverse(ways[fs[i]])%MOD;\n    right[fs[i]]--;\n    left[fs[i]]++;\n    if(std::binary_search(cows[fs[i]].begin(),cows[fs[i]].end(),left[fs[i]])){\n      calc_ways_stuck(fs[i]);\n      int here_asleep=total_asleep+asleep[fs[i]];\n      int here_ways=1LL*total_ways*ways[fs[i]]%MOD;\n      add_to_ans(here_asleep,here_ways);\n    }\n    calc_ways(fs[i]);\n    total_asleep+=asleep[fs[i]];\n    total_ways=1LL*total_ways*ways[fs[i]]%MOD;\n  }\n  printf(\"%d %d\\n\",ans_asleep,ans_ways);\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1307",
    "index": "F",
    "title": "Cow and Vacation",
    "statement": "Bessie is planning a vacation! In Cow-lifornia, there are $n$ cities, with $n-1$ bidirectional roads connecting them. It is guaranteed that one can reach any city from any other city.\n\nBessie is considering $v$ possible vacation plans, with the $i$-th one consisting of a start city $a_i$ and destination city $b_i$.\n\nIt is known that only $r$ of the cities have rest stops. Bessie gets tired easily, and cannot travel across more than $k$ consecutive roads without resting. In fact, she is so desperate to rest that she may travel through the same city multiple times in order to do so.\n\nFor each of the vacation plans, does there exist a way for Bessie to travel from the starting city to the destination city?",
    "tutorial": "We will run a BFS from all the rest stops in parallel and use union-find to determine which rest stops can reach each other directly. We will split each edge into two to simplify this process. Note that this means Bessie can now travel at most $2k$ roads before needing a rest. While we perform the BFS, we also color all nodes that are within distance $k$ from a rest stop and store the rest stop that can reach each colored node in an array. When two frontiers collide, merge them. Let's consider each query individually. First of all, if $a$ can reach $b$ directly, the answer is YES. Otherwise, let's walk $a$ towards $b$ for $k$ edges, and $b$ towards $a$ for $k$ edges. Note that they may cross over $lca(a,b)$ in the process. The walks will not meet because if they did, the condition that $a$ can reach $b$ directly would have been satisfied. Then, the answer is YES if the new $a$ is a colored node, the new $b$ is a colored node, and they both belong to the same component of rest stops which we can check from our union find. Otherwise, the answer is NO. Time Complexity: $O((n+v)\\log{n})$",
    "code": "#include <cstdio>\n#include <vector>\n#include <cassert>\n#include <queue>\n#include <algorithm>\n\nconst int INF=1e9+7;\n\nstd::vector<int> edges[400005];\n\nint anc[19][400005];\nint depth[400005];\n\nvoid dfs(int node){\n  for(int child:edges[node]){\n    edges[child].erase(std::find(edges[child].begin(),edges[child].end(),node));\n    anc[0][child]=node;\n    for(int k=1;k<19;k++){\n      anc[k][child]=anc[k-1][anc[k-1][child]];\n    }\n    depth[child]=depth[node]+1;\n    dfs(child);\n  }\n}\n\nint la(int node,int len){\n  for(int k=19-1;k>=0;k--){\n    if(len&(1<<k)){\n      node=anc[k][node];\n    }\n  }\n  return node;\n}\n\nint lca(int a,int b){\n  if(depth[a]<depth[b]) std::swap(a,b);\n  a=la(a,depth[a]-depth[b]);\n  if(a==b) return a;\n  for(int k=19-1;k>=0;k--){\n    if(anc[k][a]!=anc[k][b]){\n      a=anc[k][a];\n      b=anc[k][b];\n    }\n  }\n  return anc[0][a];\n}\n\n//move x steps from a to b\n//assumes x<=dist(a,b)\nint walk(int a,int b,int x){\n  int c=lca(a,b);\n  if(x<=depth[a]-depth[c]){\n    return la(a,x);\n  }\n  int excess=x-(depth[a]-depth[c]);\n  assert(excess<=(depth[b]-depth[c]));\n  return la(b,depth[b]-depth[c]-excess);\n}\n\nint uf[400005];\nint dist[400005];//dist[x]=0 iff x is rest stop\n\nint find(int a){\n  while(a!=uf[a]){\n    a=uf[a]=uf[uf[a]];\n  }\n  return a;\n}\n\nbool query(int K){\n  int A,B;\n  scanf(\"%d %d\",&A,&B);\n  A--,B--;\n  int C=lca(A,B);\n  if(depth[A]+depth[B]-2*depth[C]<=2*K){\n    return true;\n  }else{\n    return find(walk(A,B,K))==find(walk(B,A,K));\n  }\n}\n\nint main(){\n  int N,K,R;\n  scanf(\"%d %d %d\",&N,&K,&R);\n  int oldN=N;\n  for(int i=0;i<oldN-1;i++){\n    int X,Y;\n    scanf(\"%d %d\",&X,&Y);\n    X--,Y--;\n    edges[X].push_back(N);\n    edges[N].push_back(X);\n    edges[Y].push_back(N);\n    edges[N].push_back(Y);\n    N++;\n  }\n  for(int i=0;i<N;i++){\n    uf[i]=i;\n  }\n  std::fill(dist,dist+N,INF);\n  std::queue<int> frontier;\n  for(int i=0;i<R;i++){\n    int X;\n    scanf(\"%d\",&X);\n    X--;\n    dist[X]=0;\n    frontier.push(X);\n  }\n  while(!frontier.empty()){\n    int x=frontier.front();\n    if(dist[x]>K-1) break;\n    frontier.pop();\n    for(int y:edges[x]){\n      uf[find(y)]=find(x);\n      if(dist[y]==INF){\n\tdist[y]=dist[x]+1;\n\tfrontier.push(y);\n      }\n    }\n  }\n  dfs(0);\n  int V;\n  scanf(\"%d\",&V);\n  while(V--){\n    if(query(K)){\n      printf(\"YES\\n\");\n    }else{\n      printf(\"NO\\n\");\n    }\n  }\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1307",
    "index": "G",
    "title": "Cow and Exercise",
    "statement": "Farmer John is obsessed with making Bessie exercise more!\n\nBessie is out grazing on the farm, which consists of $n$ fields connected by $m$ directed roads. Each road takes some time $w_i$ to cross. She is currently at field $1$ and will return to her home at field $n$ at the end of the day.\n\nFarmer John has plans to increase the time it takes to cross certain roads. He can increase the time it takes to cross each road by a nonnegative amount, but the total increase cannot exceed $x_i$ for the $i$-th plan.\n\nDetermine the maximum he can make the shortest path from $1$ to $n$ for each of the $q$ independent plans.",
    "tutorial": "This problem can be formulated as a linear program, and looks like the LP dual of min-cost flow. LP formulation of min-cost flow (see for example here: https://imada.sdu.dk/%7Ejbj/DM85/mincostnew.pdf): $x_{vw}$ is flow on edge $(v,w)$ $c_{vw}$ is cost on edge $(v,w)$ $u_{vw}$ is capacity on edge $(v,w)$ $b_v$ is demand at vertex $v$ (flow in minus flow out) Find $\\min{\\Sigma_{vw}c_{vw}x_{vw}}$ subject to $\\Sigma_{(v,w)\\in E}(x_{wv}-x_{vw})=b_v$ (Hopefully the signs are right.) $0\\le x_{vw} \\le u_{vw}$ The LP Dual is $\\max{\\Sigma{b_vy_v}-\\Sigma{u_{vw}z_{vw}}}$ $y_w\\le y_v+c_{vw}+z_{vw}$ $z_{vw}\\ge 0$ This is exactly what we need, except the objective function is a bit messy. Letting $b_{src}=-F$, $b_{snk}=F$, $b_v=0$ for other $v$, $D=y_{snk}-y_{src}$, $C=\\Sigma{vw}{u_{vw}z_{vw}}$, the objective becomes $\\max{FD-C}$ We have the unweighted case, so assign capacities (cost in original problem) $u_{vw}=1$ for all edges. We can interpret $y_v$ as distance from $src$ and $z_{vw}$ as the amount added to edge edge to it. The set of all valid assignments to the variables form a convex polytope. If we project it onto the 2D space of $D$ and $C$, it will still be convex. By varying $F$, we can get a piecewise linear function describing all Pareto optimal solutions. From this function, we can find the minimum $C$ required to get some fixed $D$ or maximum $D$ achieve by some fixed $C$. Since a feasible solution to a min-cost flow problem is optimal iff it has no negative cost cycles, and both successive shortest path and primal-dual never create negative cycles, they maintain optimal solutions to their current min-cost flow problems, which only differs in $F$. Thus, they effectively trace out the function as $F$ varies from $0$ to maximum. By binary searching and lerping, we can answer queries in $O(\\log{N})$. (Since the cost is integral and bounded by $N$, there are at most $N$ linear pieces.) Time Complexity: $O(n^2m+q\\log{n})$",
    "code": "#include <cstdio>\n#include <queue>\n#include <vector>\n#include <stdint.h>\n#include <algorithm>\n\nconst long long INF=1e9+7;\n\nconst long long MAXV=50;\nconst long long MAXE=MAXV*(MAXV-1);\n\nlong long SRC,SNK;\n\nlong long elist[MAXE*2];\nlong long next[MAXE*2];\nlong long head[MAXV];\nlong long cap[MAXE*2];\nlong long cost[MAXE*2];\nlong long tot=0;\n\nvoid add(long long x,long long c,long long w){\n  elist[tot]=x;\n  cap[tot]=c;\n  cost[tot]=w;\n  next[tot]=head[x];\n  head[x]=tot++;\n}\n\nlong long dist[MAXV];\nlong long prev[MAXV];\nstd::queue<long long> q;\n\nlong long total_cost=0;\nlong long total_flow=0;\n\nint main(){\n  long long N,M;\n  scanf(\"%lld %lld\",&N,&M);\n  SRC=0,SNK=N-1;\n  std::fill(head,head+N,-1);\n  for(long long i=0;i<M;i++){\n    long long A,B,C;\n    scanf(\"%lld %lld %lld\",&A,&B,&C);\n    A--,B--;\n    add(A,1,C);\n    add(B,0,-C);\n  }\n  std::vector<std::pair<long long,long long> > crit;\n  crit.push_back({0,0});\n  while(true){\n    std::fill(dist,dist+N,INF);\n    dist[SRC]=0;\n    prev[SRC]=-1;\n    q.push(SRC);\n    while(!q.empty()){\n      long long node=q.front();\n      q.pop();\n      for(long long e=head[node];e!=-1;e=next[e]){\n\tlong long i=elist[e^1];\n\tif(cap[e]){\n\t  if(dist[i]>dist[node]+cost[e]){\n\t    dist[i]=dist[node]+cost[e];\n\t    prev[i]=e;\n\t    q.push(i);\n\t  }\n\t}\n      }\n    }\n    crit.push_back({1LL*total_flow*dist[SNK]-total_cost,dist[SNK]});\n    if(dist[SNK]==INF) break;\n    long long aug=INF;\n    for(long long x=SNK;x!=SRC;x=elist[prev[x]]){\n      aug=std::min(aug,cap[prev[x]]);\n    }\n    for(long long x=SNK;x!=SRC;x=elist[prev[x]]){\n      cap[prev[x]]-=aug;\n      cap[prev[x]^1]+=aug;\n    }\n    total_flow+=aug;\n    total_cost+=1LL*dist[SNK]*aug;\n  }\n  long long Q;\n  scanf(\"%lld\",&Q);\n  while(Q--){\n    long long X;\n    scanf(\"%lld\",&X);\n    auto it=std::lower_bound(crit.begin(),crit.end(),std::pair<long long,long long>{X+1,0});\n    double D=(long double)((X-(it-1)->first)*it->second+(it->first-X)*((it-1)->second))/(it->first-(it-1)->first);\n    printf(\"%.10lf\\n\",D);\n  }\n  return 0;\n}",
    "tags": [
      "flows",
      "graphs",
      "shortest paths"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1310",
    "index": "A",
    "title": "Recommendations",
    "statement": "VK news recommendation system daily selects interesting publications of one of $n$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $i$ batch algorithm selects $a_i$ publications.\n\nThe latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $i$-th category within $t_i$ seconds.\n\nWhat is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.",
    "tutorial": "In this problem we have an array $a_1, \\ldots, a_n$, we can increase each $a_i$ by one with cost $t_i$, and we want to make all $a_i$ different with minimal total cost. Let's sort $a_i$ in a non-decreasing way (and permute the $t$ in a corresponding way). Let's see at the minimal number, $a_1$. If it is unique, e.g. $a_1 \\ne a_2$, then we don't need to change $a_1$ - it is already unique, and it can't get equal to something else if we don't increase it. In this case, we can just skip $a_1$ and solve the smaller problem without $a_1$. Otherwise, suppose there is some $j>1$ such that $a_1 = a_2 = \\ldots = a_j$. Obviously, we should leave at most one of them with the current value, and increase other $j-1$ numbers by one. Which one should be not increased? We shouldn't increase the $a_l$ ($1 \\le l \\le j$) with the maximal $t_l$ because it minimizes the total cost. So, we should remove the maximal value $t_l$ among all elements with minimal $a_l$, and increase all other by one. This effectively reduces our problem to the smaller one, decreasing $n$ by one. This gives us a $\\mathcal{O}(n^2)$ solution - $n$ times we discard one minimum from the array and increase all other minimums by one. We can further optimize it by using a multiset of values $t_l$ for all minimal $a_l$ and its sum. At each iteration, we should (probably) add some values to a multiset, if the number of minimums in array increases, discard one maximum from multiset and add the current sum to the answer. Continue the process until the array becomes empty. This is an $\\mathcal{O}(n \\log n)$ solution.",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1310",
    "index": "B",
    "title": "Double Elimination",
    "statement": "The biggest event of the year – Cota 2 world championship \"The Innernational\" is right around the corner. $2^n$ teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion.\n\nTeams are numbered from $1$ to $2^n$ and will play games one-on-one. All teams start in the upper bracket.\n\nAll upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.\n\nLower bracket starts with $2^{n-1}$ teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round $2^k$ teams play a game with each other (teams are split into games by team numbers). $2^{k-1}$ loosing teams are eliminated from the championship, $2^{k-1}$ winning teams are playing $2^{k-1}$ teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have $2^{k-1}$ teams remaining. See example notes for better understanding.\n\nSingle remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.\n\nYou are a fan of teams with numbers $a_1, a_2, ..., a_k$. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?",
    "tutorial": "The main observation in this problem is that for each set of players that lie in the subtree of any vertex of a binary tree of the upper bracket, exactly one player will win all matches in the upper bracket, and exactly one player will win all matches in the lower bracket. We can define this set of players (in 0-indexation instead of 1-indexation from statement) as $[a \\cdot 2^t; (a+1) \\cdot 2^t)$ for some $1 \\le t \\le n$, $0 \\le a < {{2^n} \\over {2^t}}$. For each fixed $t$ the players with different values of ${id \\over {2^t}}$ don't play with each other, and their upper and lower brackets are independent. For each of these sets of players, we are interested only in a number of interesting matches between them, and if the winner of their upper and lower brackets are the teams that are we're fans of. This leads us to the dynamic programming solution: $dp[l \\ldots r][f_{up}][f_{lower}]$ - the maximal number of matches between teams with indices in $[l; r)$, if $f_{up} \\in \\{ 0, 1 \\}$ is 1 if the we're fans of winner of upper bracket, and $f_{lower} \\in \\{ 0, 1 \\}$ is 1 if the we're fans of winner of lower bracket. Again, $l \\ldots r$ is the special segment: $l = a \\cdot 2^t, r =(a+1) \\cdot 2^t - 1$ for some $1 \\le t \\le n$, $0 \\le a < {{2^n} \\over {2^t}}$. $dp[l \\ldots r][f_{up}][f_{lower}]$ can be recalculated from $dp[l \\ldots {{l+r} \\over 2}][f_{up}^l][f_{lower}^l]$ and $dp[{{l+r} \\over 2} \\ldots r][f_{up}^r][f_{lower}^r]$ - we just iterate over all possible $f_{up}^l, f_{lower}^l, f_{up}^r, f_{lower}^r$, and the results of all three matches (one in the upper bracket and two in the lower bracket). In the end, we use $dp[0 \\ldots 2^n][f_{up}][f_{lower}]$ to count the result with the last, grand-finals match. This solution works in something like $\\mathcal{O}(2^n \\cdot 2^7)$ because there are $2^n$ interesting segments.",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1310",
    "index": "C",
    "title": "Au Pont Rouge",
    "statement": "VK just opened its second HQ in St. Petersburg! Side of its office building has a huge string $s$ written on its side. This part of the office is supposed to be split into $m$ meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of $s$ written on its side.\n\nFor each possible arrangement of $m$ meeting rooms we ordered a test meeting room label for the meeting room with lexicographically \\textbf{minimal} name. When delivered, those labels got sorted \\textbf{backward} lexicographically.\n\nWhat is printed on $k$th label of the delivery?",
    "tutorial": "Let's list all distinct substrings, sort them and make a binary search. Now, we need to count number of ways to make minimal string no more then given one. Let's count inverse value - number of wat to make minimal string greater. It could be done by quadratic dynamic programming $dp_{pos, count}$ - number of ways to split suffix starting at pos to count string all of which are greater then given value. Let's find first position where suffix differs which given string. If next character in suffix is smaller, no part can start here and answer is zero. Otherwise, any longer part is acceptable, so we need to find $\\sum\\limits_{i > lcp(S, s[pos:])}{dp_{i, count-1}}$, which can be done in O(1) time by suffix sums and precalculating lcp for all pairs of suffixes. Later can by done by another quadratic dynamic programming. lcp of two suffix is equal to 0 if first letter differs, and equal to lcp of two smaller suffixes +1 otherwise.",
    "tags": [
      "binary search",
      "dp",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1310",
    "index": "D",
    "title": "Tourism",
    "statement": "Masha lives in a country with $n$ cities numbered from $1$ to $n$. She lives in the city number $1$.\n\nThere is a direct train route between each pair of distinct cities $i$ and $j$, where $i \\neq j$. In total there are $n(n-1)$ distinct routes. Every route has a cost, cost for route from $i$ to $j$ may be different from the cost of route from $j$ to $i$.\n\nMasha wants to start her journey in city $1$, take \\textbf{exactly} $k$ routes from one city to another and as a result return to the city $1$. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.\n\nMasha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city $v$, take \\textbf{odd} number of routes used by Masha in her journey and return to the city $v$, such journey is considered unsuccessful.\n\nHelp Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.",
    "tutorial": "There are two different solutions possible. First, one is to fix all even vertices in the path. It can be done in $O(n^{k/2 - 1})$ time. If it's done, we need to join them by the minimal path of length 2, not going through these vertices. It can be done by precalculating 6 minimal paths of length 2 between each pair of vertices and ignoring no more than 5 best ones until good one found. Another solution is a randomized one. Let's color all vertices in 2 colors in a random way. We can find the best path which is consistent with given coloring in $O(k \\cdot E)$ time using dynamic programming. With probability $\\frac{1}{512}$ best path overall is consistent with coloring. So, if one repeats this operation $512 \\cdot 20$ time, probability of fail would be about $\\left(\\frac{511}{512}\\right)^{512 \\cdot 20} \\approx e^{-20} \\approx 2\\cdot 10^{-9}$.",
    "tags": [
      "dp",
      "graphs",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1310",
    "index": "E",
    "title": "Strange Function",
    "statement": "Let's define the function $f$ of multiset $a$ as the multiset of number of occurences of every number, that is present in $a$.\n\nE.g., $f(\\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\\}) = \\{1, 1, 2, 2, 4\\}$.\n\nLet's define $f^k(a)$, as applying $f$ to array $a$ $k$ times: $f^k(a) = f(f^{k-1}(a)), f^0(a) = a$.\n\nE.g., $f^2(\\{5, 5, 1, 2, 5, 2, 3, 3, 9, 5\\}) = \\{1, 2, 2\\}$.\n\nYou are given integers $n, k$ and you are asked how many different values the function $f^k(a)$ can have, where $a$ is arbitrary non-empty array with numbers of size no more than $n$. Print the answer modulo $998\\,244\\,353$.",
    "tutorial": "The solution of the task consists of three cases: $k = 1$. For fixed $n$ $f(a)$ can be equal to any partition of $n$. We need to count the number of arrays $b_1, b_2, \\ldots, b_m$, such that $b_1 \\ge b_2 \\ge \\ldots \\ge b_m$ and $\\sum \\limits_{i=1}^m b_i \\le n$. This can be done by simple dp in $\\mathcal{O}(n^2)$ (or even faster, much faster). $k = 2$. When the array $b_1 \\ge b_2 \\ge \\ldots \\ge b_m$ can be equal to value of $f^2(a)$ for some $|a| \\le n$? When there exists some array $c_1, \\ldots, c_l$ such that $\\sum \\limits_{i=1}^l c_i \\le n$, and $f(c) = b$. The values of $b$ are the numbers of occurences of numbers in $c$, so we need to minimize $\\sum \\limits_{i=1}^m b_i v_i$, where $v_i$ - the unique numbers in $c$. To minimize this sum we should take $v_1=1, \\ldots, v_m=m$, so we need $\\sum \\limits_{i=1}^m b_i i \\le n$. This can be done by simple dp: $dp[val][j][sum]$ - the number of prefixes of $b$ such that we already took $j$ elements to $b$, all elements on prefix are greater than or equal to $val$, and the $\\sum \\limits_{i=1}^j b_i i = sum$. This dp can look like it is $\\mathcal{O}(n^3)$, but it is actually $\\mathcal{O}(n^2 \\log n)$, because there is a limitation $val \\cdot j \\le n$, and there are $\\mathcal{O}(n \\log n)$ such pairs. There is also a subquadratic solution. To minimize this sum we should take $v_1=1, \\ldots, v_m=m$, so we need $\\sum \\limits_{i=1}^m b_i i \\le n$. This can be done by simple dp: $dp[val][j][sum]$ - the number of prefixes of $b$ such that we already took $j$ elements to $b$, all elements on prefix are greater than or equal to $val$, and the $\\sum \\limits_{i=1}^j b_i i = sum$. This dp can look like it is $\\mathcal{O}(n^3)$, but it is actually $\\mathcal{O}(n^2 \\log n)$, because there is a limitation $val \\cdot j \\le n$, and there are $\\mathcal{O}(n \\log n)$ such pairs. There is also a subquadratic solution. $k \\ge 3$. We can notice that in the array $f^2(a)$ there are at most $\\mathcal{O}(\\sqrt{2n})$ elements. We can use this fact to bruteforce all possible answers - candidates for the answer are the partitions of numbers not exceeding $\\sqrt{2n}=64$, there are few millions of them. How to check if the array $b_1 \\ge b_2 \\ge \\ldots \\ge b_m$ can be the falue of $f^k(a)$? It happens that we can make $k-2$ iterations of the unfolding algorithm from case $k=2$ and get the <<minimal>> possible array $a$, and check, if it contains no more than $n$ elements. This part works in $\\mathcal{O}(\\mathcal{P}(\\sqrt{2n}))$. How to check if the array $b_1 \\ge b_2 \\ge \\ldots \\ge b_m$ can be the falue of $f^k(a)$? It happens that we can make $k-2$ iterations of the unfolding algorithm from case $k=2$ and get the <<minimal>> possible array $a$, and check, if it contains no more than $n$ elements. This part works in $\\mathcal{O}(\\mathcal{P}(\\sqrt{2n}))$.",
    "tags": [
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1310",
    "index": "F",
    "title": "Bad Cryptography",
    "statement": "In modern cryptography much is tied to the algorithmic complexity of solving several problems. One of such problems is a discrete logarithm problem. It is formulated as follows:\n\n\\begin{center}\nLet's fix a finite field and two it's elements $a$ and $b$. One need to fun such $x$ that $a^x = b$ or detect there is no such x.\n\\end{center}\n\nIt is most likely that modern mankind cannot solve the problem of discrete logarithm for a sufficiently large field size. For example, for a field of residues modulo prime number, primes of 1024 or 2048 bits are considered to be safe. However, calculations with such large numbers can place a significant load on servers that perform cryptographic operations. For this reason, instead of a simple module residue field, more complex fields are often used. For such field no fast algorithms that use a field structure are known, smaller fields can be used and operations can be properly optimized.\n\nDeveloper Nikolai does not trust the generally accepted methods, so he wants to invent his own. Recently, he read about a very strange field — nimbers, and thinks it's a great fit for the purpose.\n\nThe field of nimbers is defined on a set of integers from 0 to $2^{2^k} - 1$ for some positive integer $k$ . Bitwise exclusive or ($\\oplus$) operation is used as addition. One of ways to define multiplication operation ($\\odot$) is following properties:\n\n- $0 \\odot a = a \\odot 0 = 0$\n- $1 \\odot a = a \\odot 1 = a$\n- $a \\odot b = b \\odot a$\n- $a \\odot (b \\odot c)= (a \\odot b) \\odot c$\n- $a \\odot (b \\oplus c) = (a \\odot b) \\oplus (a \\odot c)$\n- If $a = 2^{2^n}$ for some integer $n > 0$, and $b < a$, then $a \\odot b = a \\cdot b$.\n- If $a = 2^{2^n}$ for some integer $n > 0$, then $a \\odot a = \\frac{3}{2}\\cdot a$.\n\nFor example:\n\n- $ 4 \\odot 4 = 6$\n- $ 8 \\odot 8 = 4 \\odot 2 \\odot 4 \\odot 2 = 4 \\odot 4 \\odot 2 \\odot 2 = 6 \\odot 3 = (4 \\oplus 2) \\odot 3 = (4 \\odot 3) \\oplus (2 \\odot (2 \\oplus 1)) = (4 \\odot 3) \\oplus (2 \\odot 2) \\oplus (2 \\odot 1) = 12 \\oplus 3 \\oplus 2 = 13.$\n- $32 \\odot 64 = (16 \\odot 2) \\odot (16 \\odot 4) = (16 \\odot 16) \\odot (2 \\odot 4) = 24 \\odot 8 = (16 \\oplus 8) \\odot 8 = (16 \\odot 8) \\oplus (8 \\odot 8) = 128 \\oplus 13 = 141$\n- $5 \\odot 6 = (4 \\oplus 1) \\odot (4 \\oplus 2) = (4\\odot 4) \\oplus (4 \\odot 2) \\oplus (4 \\odot 1) \\oplus (1 \\odot 2) = 6 \\oplus 8 \\oplus 4 \\oplus 2 = 8$\n\nFormally, this algorithm can be described by following pseudo-code.\n\n\\begin{verbatim}\nmultiply(a, b) {\nans = 0\nfor p1 in bits(a) // numbers of bits of a equal to one\nfor p2 in bits(b) // numbers of bits of b equal to one\nans = ans xor multiply_powers_of_2(1 << p1, 1 << p2)\nreturn ans;\n}\nmultiply_powers_of_2(a, b) {\nif (a == 1 or b == 1) return a * b\nn = maximal value, such 2^{2^{n}} <= max(a, b)\npower = 2^{2^{n}};\nif (a >= power and b >= power) {\nreturn multiply(power * 3 / 2, multiply_powers_of_2(a / power, b / power))\n} else if (a >= power) {\nreturn multiply_powers_of_2(a / power, b) * power\n} else {\nreturn multiply_powers_of_2(a, b / power) * power\n}\n}\n\n\\end{verbatim}\n\nIt can be shown, that this operations really forms a field. Moreover, than can make sense as game theory operations, but that's not related to problem much. With the help of appropriate caching and grouping of operations, it is possible to calculate the product quickly enough, which is important to improve speed of the cryptoalgorithm. More formal definitions as well as additional properties can be clarified in the wikipedia article at link. The authors of the task hope that the properties listed in the statement should be enough for the solution.\n\nPowering for such muliplication is defined in same way, formally $a^{\\odot k} = \\underbrace{a \\odot a \\odot \\cdots \\odot a}_{k~times}$.\n\nYou need to analyze the proposed scheme strength. For pairs of numbers $a$ and $b$ you need to find such $x$, that $a^{\\odot x} = b$, or determine that it doesn't exist.",
    "tutorial": "One of the well-known algorithms for the discrete logarithm problem is baby step giant step algorithm based on the meet in the middle idea. It can solve the problem in $O(\\sqrt{|F|})$ time, which is definitely too much for the field of size $2^64$. Multiplicative group of field has size $F = 2^64 - 1 = 3 \\cdot 5 \\cdot 17 \\cdot 257 \\cdot 641 \\cdot 65537 \\cdot 6700417$. We can see, that all numbers in this factoring are not too big. Let's try to find an answer modulo each of these primes. If we do that, we can restore the answer by the Chinese remainder theorem, and we are done. Let $p$ be one of divisors. So, if $x = k * p + y$ is answer, than $a^{kp + y} = b$, than $a^{kF + y\\frac{F}{p}} = b^{\\frac{F}{p}}$. $a^F$ is equal to 1, so problem is equivalent to searching such an $y$, that $(a^{\\frac{F}{p}})^y = b^{\\frac{F}{p}}$, which is discrete logarithm problem on multiplicative subgroup of size $p$. So it can be solved using $O(\\sqrt{p})$ multiplications, which is about 6000 multiplications total for all values of $p$. If one of the discrete logarithms not exists, the total answer obviously not exists. Another corner case, that both values in subproblem can be equal to $1$. That means, that any value for this module is good. Also, this means, that $a$ and $b$ both have a smaller period, so any of these values would lead us to the correct answer. Another part of problem is making multiplication fast enough. The first idea is to cache multiplications for powers of 2. This solution works for about 5 seconds in my implementation, and probably can be squeezed in time limit with some hacks. But multiplication can be done asymptotically faster. Let's $a = a_1 \\cdot P + a_2$, $b = b_1 \\cdot P + b_2$ is decomposition to first and second half of bits (in fact P is equal to power in multiply_powers_of_2 function). Then $a \\odot b = (a_1 \\cdot P + a_2) \\cdot (b_1 \\cdot P + b_2) = (a_1 \\odot P \\oplus a_2) \\odot (b_1 \\odot P \\oplus b_2) = (a_1 \\odot b_1) \\odot (P \\odot P) \\oplus (a_2 \\odot b_2) \\oplus ((a_1 \\odot b_2)\\oplus(a_2\\odot b_1))\\odot P$. As in Karatsuba algroithm, this 4 products can be reduce for 3, if one notice, that $(a_1 \\odot b_2)\\oplus(a_2\\odot b_1) = (a_1 \\oplus a_2) \\odot(b_1\\oplus b_2) \\oplus (a_1\\odot b_1)\\oplus(a_2\\odot b_2)$. The only diffrenece is instead of shift for multiplying on $P\\cdot P$ we need to do one more multiplication. But $P\\odot P = P \\oplus \\frac{P}{2}$. We can multiply by them separately. Multiplying on $P$ is easy. The other one is multiplying on the power of 2, which can be done by the naive algorithm in linear time. On the other hand, we can just call multiply for the second one recursively, and it will work fast enough because most of the branches will lead to multiplying on zero. Also, to make things fast, one can precompute all multiplications for numbers smaller than 256. This makes multiplication about 5 times faster than naive approach.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1311",
    "index": "A",
    "title": "Add Odd or Subtract Even",
    "statement": "You are given two positive integers $a$ and $b$.\n\nIn one move, you can \\textbf{change} $a$ in the following way:\n\n- Choose any positive \\textbf{odd} integer $x$ ($x > 0$) and replace $a$ with $a+x$;\n- choose any positive \\textbf{even} integer $y$ ($y > 0$) and replace $a$ with $a-y$.\n\nYou can perform as many such operations as you want. You can choose the same numbers $x$ and $y$ in different moves.\n\nYour task is to find the minimum number of moves required to obtain $b$ from $a$. It is guaranteed that you can always obtain $b$ from $a$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If $a=b$ then the answer is $0$. Otherwise, if $a > b$ and $a - b$ is even or $a < b$ and $b - a$ is odd then the answer is $1$. Otherwise the answer is $2$ (you can always make $1$-case in one move).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tif (a == b) cout << 0 << endl;\n\t\telse cout << 1 + int((a < b) ^ ((b - a) & 1)) << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1311",
    "index": "B",
    "title": "WeirdSort",
    "statement": "You are given an array $a$ of length $n$.\n\nYou are also given a set of \\textbf{distinct} positions $p_1, p_2, \\dots, p_m$, where $1 \\le p_i < n$. The position $p_i$ means that you can swap elements $a[p_i]$ and $a[p_i + 1]$. You can apply this operation any number of times for each of the given \\textbf{positions}.\n\nYour task is to determine if it is possible to sort the initial array in non-decreasing order ($a_1 \\le a_2 \\le \\dots \\le a_n$) using only allowed swaps.\n\nFor example, if $a = [3, 2, 1]$ and $p = [1, 2]$, then we can first swap elements $a[2]$ and $a[3]$ (because position $2$ is contained in the given set $p$). We get the array $a = [3, 1, 2]$. Then we swap $a[1]$ and $a[2]$ (position $1$ is also contained in $p$). We get the array $a = [1, 3, 2]$. Finally, we swap $a[2]$ and $a[3]$ again and get the array $a = [1, 2, 3]$, sorted in non-decreasing order.\n\nYou can see that if $a = [4, 1, 2, 3]$ and $p = [3, 2]$ then you cannot sort the array.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The simple simulation works here: while there is at least one inversion (such a pair of indices $i$ and $i+1$ that $a[i] > a[i + 1]$) we can fix, let's fix it (we can fix this inversion if $i \\in p$). If there are inversions but we cannot fix any of them, the answer is \"NO\". Otherwise, the answer is \"YES\". There is also a $O(n \\log n)$ solution: it is obvious that we have some segments in which we can change the order of elements as we want. And it is also obvious that we cannot move elements between these \"allowed\" segments. So, each of them is independent of each other. We can just find all these segments of indices using two pointers and sort them independently. Then we just need to check if the array becomes sorted. Time complexity is $O(n^2)$ or $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tvector<int> a(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcin >> a[i];\n\t\t}\n\t\tvector<int> p(n);\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tint pos;\n\t\t\tcin >> pos;\n\t\t\tp[pos - 1] = 1;\n\t\t}\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (p[i] == 0) continue;\n\t\t\tint j = i;\n\t\t\twhile (j < n && p[j]) ++j;\n\t\t\tsort(a.begin() + i, a.begin() + j + 1);\n\t\t\ti = j;\n\t\t}\n\t\tbool ok = true;\n\t\tfor (int i = 0; i < n - 1; ++i) {\n\t\t\tok &= a[i] <= a[i + 1];\n\t\t}\n\t\tif (ok) cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n\t\n\treturn 0;\n}\n",
    "tags": [
      "dfs and similar",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1311",
    "index": "C",
    "title": "Perform the Combo",
    "statement": "You want to perform the combo on your opponent in one popular fighting game. The combo is the string $s$ consisting of $n$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $s$. I.e. if $s=$\"abca\" then you have to press 'a', then 'b', 'c' and 'a' again.\n\nYou know that you will spend $m$ wrong tries to perform the combo and during the $i$-th try you will make a mistake right after $p_i$-th button ($1 \\le p_i < n$) (i.e. you will press first $p_i$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $m+1$-th try you press all buttons right and finally perform the combo.\n\nI.e. if $s=$\"abca\", $m=2$ and $p = [1, 3]$ then the sequence of pressed buttons will be 'a' (\\textbf{here} you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (\\textbf{here} you're making a mistake and start performing the combo from the beginning), 'a' (\\textbf{note that at this point you will not perform the combo because of the mistake}), 'b', 'c', 'a'.\n\nYour task is to calculate for each button (letter) the number of times you'll press it.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "We can consider all tries independently. During the $i$-th try we press first $p_i$ buttons, so it makes $+1$ on the prefix of length $p_i$. So the $i$-th character of the string will be pressed (the number of $p_i \\ge i$ plus $1$) times. We can use sorting and some kind of binary search to find this number for each character but we also can build suffix sums to find all required numbers. We can build suffix sums using the following code: So as you can see, the $i$-th element of $p$ will add $1$ in each position from $1$ to $p_i$. So we got what we need. After that we can calculate the answer for each character in the following way: Time complexity: $O(n \\log n)$ or $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m;\n\t\tstring s;\n\t\tcin >> n >> m >> s;\n\t\tvector<int> pref(n);\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tint p;\n\t\t\tcin >> p;\n\t\t\t++pref[p - 1];\n\t\t}\n\t\tfor (int i = n - 1; i > 0; --i) {\n\t\t\tpref[i - 1] += pref[i];\n\t\t}\n\t\tvector<int> ans(26);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tans[s[i] - 'a'] += pref[i];\n\t\t\t++ans[s[i] - 'a'];\n\t\t}\n\t\tfor (int i = 0; i < 26; ++i) {\n\t\t\tcout << ans[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1311",
    "index": "D",
    "title": "Three Integers",
    "statement": "You are given three integers $a \\le b \\le c$.\n\nIn one move, you can add $+1$ or $-1$ to \\textbf{any} of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. \\textbf{Note that you cannot make non-positive numbers using such operations}.\n\nYou have to perform the minimum number of such operations in order to obtain three integers $A \\le B \\le C$ such that $B$ is divisible by $A$ and $C$ is divisible by $B$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let's iterate over all possible values of $A$ from $1$ to $2a$. It is obvious that $A$ cannot be bigger than $2a$, else we can just move $a$ to $1$. Then let's iterate over all possible multiples of $A$ from $1$ to $2b$. Let this number be $B$. Then we can find $C$ as the nearest number to $c$ that is divisible by $B$ (we can check two nearest numbers to be sure). These numbers are $C = \\lfloor\\frac{c}{B}\\rfloor \\cdot B$ and $C = \\lfloor\\frac{c}{B}\\rfloor \\cdot B + B$. Then we can update the answer with the found triple. Note that the only condition you need to check is that $B \\le C$. Time complexity: $O(n \\log n)$ because of the sum of the harmonic series.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint a, b, c;\n\t\tcin >> a >> b >> c;\n\t\tint ans = 1e9;\n\t\tint A = -1, B = -1, C = -1;\n\t\tfor (int cA = 1; cA <= 2 * a; ++cA) {\n\t\t\tfor (int cB = cA; cB <= 2 * b; cB += cA) {\n\t\t\t\tfor (int i = 0; i < 2; ++i) {\n\t\t\t\t\tint cC = cB * (c / cB) + i * cB;\n\t\t\t\t\tint res = abs(cA - a) + abs(cB - b) + abs(cC - c);\n\t\t\t\t\tif (ans > res) {\n\t\t\t\t\t\tans = res;\n\t\t\t\t\t\tA = cA;\n\t\t\t\t\t\tB = cB;\n\t\t\t\t\t\tC = cC;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl << A << \" \" << B << \" \" << C << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1311",
    "index": "E",
    "title": "Construct the Binary Tree",
    "statement": "You are given two integers $n$ and $d$. You need to construct a rooted binary tree consisting of $n$ vertices with a root at the vertex $1$ and the sum of depths of all vertices equals to $d$.\n\nA tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $v$ is the last different from $v$ vertex on the path from the root to the vertex $v$. The depth of the vertex $v$ is the length of the path from the root to the vertex $v$. Children of vertex $v$ are all vertices for which $v$ is the parent. The binary tree is such a tree that no vertex has more than $2$ children.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "This problem has an easy constructive solution. We can find lower and upper bounds on the value of $d$ for the given $n$. If the given $d$ does not belong to this segment, then the answer is \"NO\". Otherwise, the answer is \"YES\" for any $d$ in this segment. How to construct it? Let's start from the chain. The answer for the chain is the upper bound of $d$ and it is $\\frac{n(n-1)}{2}$. Then let's try to decrease the answer by $1$ in one move. Let's take some leaf $v$ (the vertex without children) with the smallest depth that is not bad and try to move it up. The definition of badness will be below. To do this, let's find such vertex $p$ that its depth is less than the depth of $v$ by $2$ and it has less than $2$ children. If we found such vertex $p$ then let's make $v$ the child of $p$ and decrease the answer by one. If we didn't find such vertex $p$, I claim that the vertex $v$ has the minimum possible depth it can have and we should not consider it in the future. Let's mark this vertex as bad and continue our algorithm. If at some moment we cannot find any not bad leaf $v$, then the answer is \"NO\". Otherwise, the answer is \"YES\". Time complexity: $O(nd)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, d;\n\t\tcin >> n >> d;\n\t\tint ld = 0, rd = n * (n - 1) / 2;\n\t\tfor (int i = 1, cd = 0; i <= n; ++i) {\n\t\t\tif (!(i & (i - 1))) ++cd;\n\t\t\tld += cd - 1;\n\t\t}\n\t\tif (!(ld <= d && d <= rd)) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\n\t\tvector<int> par(n);\n\t\tiota(par.begin(), par.end(), -1);\n\t\t\n\t\tvector<int> cnt(n, 1);\n\t\tcnt[n - 1] = 0;\n\t\t\n\t\tvector<int> bad(n);\n\t\t\n\t\tvector<int> dep(n);\n\t\tiota(dep.begin(), dep.end(), 0);\n\t\t\n\t\tint cur = n * (n - 1) / 2;\n\t\twhile (cur > d) {\n\t\t\tint v = -1;\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tif (!bad[i] && cnt[i] == 0 && (v == -1 || dep[v] > dep[i])) {\n\t\t\t\t\tv = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(v != -1);\n\t\t\tint p = -1;\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tif (cnt[i] < 2 && dep[i] < dep[v] - 1 && (p == -1 || dep[p] < dep[i])) {\n\t\t\t\t\tp = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (p == -1) {\n\t\t\t\tbad[v] = 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tassert(dep[v] - dep[p] == 2);\n\t\t\t--cnt[par[v]];\n\t\t\t--dep[v];\n\t\t\t++cnt[p];\n\t\t\tpar[v] = p;\n\t\t\t--cur;\n\t\t}\n\t\n\t\tcout << \"YES\" << endl;\n\t\tfor (int i = 1; i < n; ++i) cout << par[i] + 1 << \" \";\n\t\tcout << endl;\n\t}\n\t\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1311",
    "index": "F",
    "title": "Moving Points",
    "statement": "There are $n$ points on a coordinate axis $OX$. The $i$-th point is located at the integer point $x_i$ and has a speed $v_i$. It is guaranteed that no two points occupy the same coordinate. All $n$ points move with the constant speed, the coordinate of the $i$-th point at the moment $t$ ($t$ \\textbf{can be non-integer}) is calculated as $x_i + t \\cdot v_i$.\n\nConsider two points $i$ and $j$. Let $d(i, j)$ be the minimum possible distance between these two points over any possible moments of time (even \\textbf{non-integer}). It means that if two points $i$ and $j$ coincide at some moment, the value $d(i, j)$ will be $0$.\n\nYour task is to calculate the value $\\sum\\limits_{1 \\le i < j \\le n}$ $d(i, j)$ (the sum of minimum distances over all pairs of points).",
    "tutorial": "Let's understand when two points $i$ and $j$ coincide. Let $x_i < x_j$. Then they are coincide when $v_i > v_j$. Otherwise, these two points will never coincide and the distance between them will only increase. So, we need to consider only the initial positions of points. Let's sort all points by $x_i$ and consider them one by one from left to right. Let the $i$-th point be the rightmost in the pair of points that we want to add to the answer. We need to find the number of points $j$ such that $x_j < x_i$ and $v_j \\le v_i$ and the sum of $x_j$ for such points as well. We can do this using two BITs (Fenwick trees) if we compress coordinates (all values $v$) and do some kind of \"scanline\" by values $x$. Let the number of such points be $cnt$ and the sum of coordinates of such points be $sum$. Then we can increase the answer by $x_i \\cdot cnt - sum$ and add our current point to the Fenwick trees (add $1$ to the position $v_i$ in the first tree and $x_i$ to the position $v_i$ in the second tree). When we want to find the number of required points and the sum of its coordinates, we just need to find the sum on the prefix two times in Fenwick trees. Note that you can use any \"online\" logarithmic data structure you like in this solution (such as treap and segment tree). There is also another solution that uses pbds. Let's do the same thing, but there is one problem. Such data structure does not have \"sum on prefix\" function, so we have to replace it somehow. To do this, let's calculate only $x_i \\cdot cnt$ part when we go from left to right. Then let's clear our structure, go among all points again but from right to left and calculate the same thing, but with the opposite sign (find the number of points $j$ such that $x_j > x_i$ and $v_j \\ge v_i$). When we go from right to left, we need to decrease the answer by $x_i \\cdot cnt$. It is some kind of \"contribution to the sum\" technique. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef\ntree<\n\tpair<int, int>,\n\tnull_type,\n\tless<pair<int, int>>,\n\trb_tree_tag,\n\ttree_order_statistics_node_update>\nordered_set;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<pair<int, int>> p(n);\n\tfor (auto &pnt : p) cin >> pnt.first;\n\tfor (auto &pnt : p) cin >> pnt.second;\n\tsort(p.begin(), p.end());\n\t\n\tordered_set s;\n\tlong long ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint cnt = s.order_of_key(make_pair(p[i].second + 1, -1));\n\t\tans += cnt * 1ll * p[i].first;\n\t\ts.insert(make_pair(p[i].second, i));\n\t}\n\ts.clear();\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tint cnt = int(s.size()) - s.order_of_key(make_pair(p[i].second - 1, n));\n\t\tans -= cnt * 1ll * p[i].first;\n\t\ts.insert(make_pair(p[i].second, i));\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "implementation",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1312",
    "index": "A",
    "title": "Two Regular Polygons",
    "statement": "You are given two integers $n$ and $m$ ($m < n$). Consider a \\textbf{convex} regular polygon of $n$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).\n\n\\begin{center}\nExamples of convex regular polygons\n\\end{center}\n\nYour task is to say if it is possible to build another \\textbf{convex} regular polygon with $m$ vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The answer is \"YES\" if and only if $n$ is divisible by $m$ because if you number all vertices of the initial polygon from $0$ to $n-1$ clockwise then you need to take every vertex divisible by $\\frac{n}{m}$ (and this number obviously should be integer) and there is no other way to construct the other polygon.",
    "code": "for i in range(int(input())):\n    n, m = map(int, input().split())\n    print('YES' if n % m == 0 else 'NO')",
    "tags": [
      "geometry",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1312",
    "index": "B",
    "title": "Bogosort",
    "statement": "You are given an array $a_1, a_2, \\dots , a_n$. Array is good if for each pair of indexes $i < j$ the condition $j - a_j \\ne i - a_i$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).\n\nFor example, if $a = [1, 1, 3, 5]$, then shuffled arrays $[1, 3, 5, 1]$, $[3, 5, 1, 1]$ and $[5, 3, 1, 1]$ are good, but shuffled arrays $[3, 1, 5, 1]$, $[1, 1, 3, 5]$ and $[1, 1, 5, 3]$ aren't.\n\nIt's guaranteed that it's always possible to shuffle an array to meet this condition.",
    "tutorial": "Let's sort array $a$ in non-ascending order ($a_1 \\ge a_2 \\ge \\dots \\ge a_n$). In this case for each pair of indexes $i < j$ the condition $j - a_j \\ne i - a_i$ holds.",
    "code": "for t in range(int(input())):\n    n = input()\n    print(*sorted(map(int, input().split()))[::-1])",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1312",
    "index": "C",
    "title": "Adding Powers",
    "statement": "Suppose you are performing the following algorithm. There is an array $v_1, v_2, \\dots, v_n$ filled with zeroes at start. The following operation is applied to the array several times — at $i$-th step ($0$-indexed) you can:\n\n- either choose position $pos$ ($1 \\le pos \\le n$) and increase $v_{pos}$ by $k^i$;\n- or not choose any position and skip this step.\n\nYou can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array $v$ equal to the given array $a$ ($v_j = a_j$ for each $j$) after some step?",
    "tutorial": "This is the solution that doesn't involve masks. Let's reverse the process and try to get all zeroes from the array $a$: since all $a_i \\le 10^{16}$ we can start from maximum $k^s \\le 10^{16}$. The key idea: since $k^s > \\sum_{x=0}^{s-1}{k^x}$ then there should be no more than one position $pos$ such that $a_{pos} \\ge k^s$ and we should decrease it by $k^s$. Now we can decrease $s$ by $1$ and repeat the same process. If at any step there are at least two $a_{pos} \\ge k^s$ or as result, we won't get array filled with $0$ then there is no way to build the array $a$.",
    "code": "fun getMask(a: Long, k: Long): Long? {\n    var (tmp, res) = listOf(a, 0L)\n    var cnt = 0\n    while (tmp > 0) {\n        if (tmp % k > 1)\n            return null\n        res = res or ((tmp % k) shl cnt)\n        tmp /= k\n        cnt++\n    }\n    return res\n}\n\nfun main() {\n    val T = readLine()!!.toInt()\n    for (tc in 1..T) {\n        val (n, k) = readLine()!!.split(' ').map { it.toLong() }\n        val a = readLine()!!.split(' ').map { getMask(it.toLong(), k) }\n        val b = a.filterNotNull()\n        if (b.size < n) {\n            println(\"NO\")\n            continue\n        } else {\n            val res = b.reduce { acc, l -> if (acc < 0 || (acc and l) > 0) -1 else acc or l }\n            println(if (res < 0) \"NO\" else \"YES\")\n        }\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "implementation",
      "math",
      "number theory",
      "ternary search"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1312",
    "index": "D",
    "title": "Count the Arrays",
    "statement": "Your task is to calculate the number of arrays such that:\n\n- each array contains $n$ elements;\n- each element is an integer from $1$ to $m$;\n- for each array, there is \\textbf{exactly} one pair of equal elements;\n- for each array $a$, there exists an index $i$ such that the array is \\textbf{strictly ascending} before the $i$-th element and \\textbf{strictly descending} after it (formally, it means that $a_j < a_{j + 1}$, if $j < i$, and $a_j > a_{j + 1}$, if $j \\ge i$).",
    "tutorial": "First of all, there will be exactly $n - 1$ distinct elements in our array. Let's choose them, there are ${m}\\choose{n-1}$ ways to do that. After that, there should be exactly one element that appears twice. There are $n - 1$ elements to choose from, but are all of them eligible? If we duplicate the maximum element, there will be no way to meet the fourth condition. So we should multiply the current answer by $n - 2$, not $n - 1$. And finally, some elements will appear earlier than the maximum in our array, and some - later. The duplicated element will appear on both sides, but all other elements should appear either to the left or to the right, so there are $2^{n - 3}$ ways to choose their positions. Thus the answer is ${{m}\\choose{n - 1}} (n - 2)2^{n - 3}$. Note that you have to precompute all factorials and use their inverse elements to calculate ${m}\\choose{n-1}$. Note that there is a tricky case when $n = 2$: some binpow implementations go into infinite loop trying to compute $2^{-1}$, so you may have to handle it specifically.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y)\n    {\n        if(y & 1) z = mul(z, x);\n        x = mul(x, x);\n        y >>= 1;\n    }\n    return z;\n}\n\nint inv(int x)\n{\n    return binpow(x, MOD - 2);\n}\n\nint divide(int x, int y)\n{\n    return mul(x, inv(y));\n}\n\nint fact[N];\n\nvoid precalc()\n{\n    fact[0] = 1;\n    for(int i = 1; i < N; i++)\n        fact[i] = mul(fact[i - 1], i);\n}\n\nint C(int n, int k)\n{\n    return divide(fact[n], mul(fact[k], fact[n - k]));\n}\n\nint main() \n{\n    precalc();\n    int n, m;\n    cin >> n >> m;\n    int ans = 0;\n    if(n > 2)\n        ans = mul(C(m, n - 1), mul(n - 2, binpow(2, n - 3)));\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1312",
    "index": "E",
    "title": "Array Shrinking",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$. You can perform the following operation any number of times:\n\n- Choose a pair of two neighboring equal elements $a_i = a_{i + 1}$ (if there is at least one such pair).\n- Replace them by one element with value $a_i + 1$.\n\nAfter each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array $a$ you can get?",
    "tutorial": "Let's look at the answer: by construction, each element in the final answer was the result of replace series of elements on the corresponding segment. So all we need to find is the minimal (by size) partition of the array $a$ on segments where each segment can be transformed in one element by series of replaces. We can calculate it using standard prefix dynamic programming, or $dp2[len]$ is the size of such minimal partition of a prefix of length $len$. The transitions are standard: let's check all segments $[len, nxt)$ and if it can be replaced by one element let's relax $dp2[nxt]$. Now we need to check for all segments of $a$ - can it be replaced by one element. Let's calculate another $dp[l][r]$ using the following fact: if there is a way to replace all segment as one element so the segment either has the length $1$ or it can be divided into two parts where the prefix can be replaced by one element, the suffix also can be replaced by one element and these elements are equal. It's exactly the transitions we need to check to calculate $dp[l][r]$. The resulting complexity is $O(n^3)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n    return out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n    out << \"[\";\n    fore(i, 0, sz(v)) {\n        if(i) out << \", \";\n        out << v[i];\n    }\n    return out << \"]\";\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nconst int N = 555;\nint n, a[N];\n\ninline bool read() {\n    if(!(cin >> n))\n        return false;\n    fore(i, 0, n)\n        cin >> a[i];\n    return true;\n}\n\nint dp[N][N];\n\nint calcDP(int l, int r) {\n    assert(l < r);\n    if(l + 1 == r)\n        return dp[l][r] = a[l];\n    if(dp[l][r] != 0)\n        return dp[l][r];\n    \n    dp[l][r] = -1;\n    fore(mid, l + 1, r) {\n        int lf = calcDP(l, mid);\n        int rg = calcDP(mid, r);\n        if(lf > 0 && lf == rg)\n            return dp[l][r] = lf + 1;\n    }\n    return dp[l][r];\n}\n\nint dp2[N];\n\ninline void solve() {\n    fore(i, 0, N)\n        dp2[i] = INF;\n    \n    dp2[0] = 0;\n    fore(i, 0, n) {\n        fore(j, i + 1, n + 1) {\n            if(calcDP(i, j) > 0)\n                dp2[j] = min(dp2[j], dp2[i] + 1);\n        }\n    }\n    cout << dp2[n] << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1312",
    "index": "F",
    "title": "Attack on Red Kingdom",
    "statement": "The Red Kingdom is attacked by the White King and the Black King!\n\nThe Kingdom is guarded by $n$ castles, the $i$-th castle is defended by $a_i$ soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.\n\nEach day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.\n\nEach attack must target a castle with \\textbf{at least one} alive defender in it. There are three types of attacks:\n\n- a mixed attack decreases the number of defenders in the targeted castle by $x$ (or sets it to $0$ if there are already less than $x$ defenders);\n- an infantry attack decreases the number of defenders in the targeted castle by $y$ (or sets it to $0$ if there are already less than $y$ defenders);\n- a cavalry attack decreases the number of defenders in the targeted castle by $z$ (or sets it to $0$ if there are already less than $z$ defenders).\n\nThe mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the \\textbf{previous attack on the targeted castle} had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.\n\nThe King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.",
    "tutorial": "This problem seems like a version of Nim with some forbidden moves, so let's try to apply Sprague-Grundy theory to it. First of all, we may treat each castle as a separate game, compute its Grundy value, and then XOR them to determine who is the winner of the game. When analyzing the state of a castle, we have to know two things: the number of remaining soldiers in it and the type of the last attack performed on it. So, the state of the game can be treated as a pair. We can compute Grundy values for each state in a straightforward way, but the constraints are too large to do it. Instead, we should try to search for a period: five consecutive rows (by row we mean a vector of Grundy values for the same number of remaining soldiers, but different types of last attacks) of Grundy values determine all of the values after them, so as soon as we get the same five rows of Grundy values that we already met, we can determine the period. There are $15$ values stored in these five rows, so the period can be up to $4^{15}$ - but that's a really generous upper bound. Some intuition can help us to prove something like $10^5$ or $10^6$ as an upper bound, but it is better to check all cases with brute force and find out that the period is at most $36$. After we've found the period of Grundy values, it's easy to get them in $O(1)$ for any castle. To count the number of winning moves for the first player, we can compute the XOR-sum of all castles, and for each castle check what happens if we make some type of attack on it: if the XOR-sum becomes $0$, then this move is winning.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300043;\nconst int K = 5;\n\nint x, y, z, n;\nlong long a[N];\n\ntypedef vector<vector<int> > state;\nmap<state, int> d;\nint cnt;\nint p;\nvector<vector<int> > state_log;\n\nint mex(const vector<int>& a)\n{\n    for(int i = 0; i < a.size(); i++)\n    {\n        bool f = false;\n        for(auto x : a)\n            if(x == i)\n                f = true;\n        if(!f)\n            return i;\n    }\n    return a.size();\n}\n\nstate go(state s)\n{\n    int f1 = mex({s[0][K - x], s[1][K - y], s[2][K - z]});\n    int f2 = mex({s[0][K - x], s[2][K - z]});\n    int f3 = mex({s[0][K - x], s[1][K - y]});\n    state nw = s;\n    nw[0].push_back(f1);\n    nw[1].push_back(f2);\n    nw[2].push_back(f3);\n    for(int i = 0; i < 3; i++)\n        nw[i].erase(nw[i].begin());\n    return nw;\n}\n\nvoid precalc()\n{\n    d.clear();\n    state cur(3, vector<int>(K, 0));\n    cnt = 0;\n    state_log.clear();\n    while(!d.count(cur))\n    {\n        d[cur] = cnt;\n        state_log.push_back({cur[0].back(), cur[1].back(), cur[2].back()});\n        cur = go(cur);\n        cnt++;\n    }                   \n    p = cnt - d[cur];\n}\n\nint get_grundy(long long x, int t)\n{\n    if(x < cnt)\n        return state_log[x][t];\n    else\n    {\n        int pp = cnt - p;\n        x -= pp;\n        return state_log[pp + (x % p)][t];\n    }\n}\n\nvoid read()\n{\n    scanf(\"%d %d %d %d\", &n, &x, &y, &z);\n    for(int i = 0; i < n; i++)\n        scanf(\"%lld\", &a[i]);\n}                    \n\nint check(int x, int y)\n{\n    return x == y ? 1 : 0;\n}\n\nvoid solve()\n{\n    precalc();\n    int ans = 0;\n    for(int i = 0; i < n; i++)\n        ans ^= get_grundy(a[i], 0);\n    int res = 0;\n    for(int i = 0; i < n; i++)\n    {\n        ans ^= get_grundy(a[i], 0);\n        res += check(ans, get_grundy(max(0ll, a[i] - x), 0));\n        res += check(ans, get_grundy(max(0ll, a[i] - y), 1));\n        res += check(ans, get_grundy(max(0ll, a[i] - z), 2));\n        ans ^= get_grundy(a[i], 0);\n    }\n    printf(\"%d\\n\", res);\n}\n\nint main()\n{\n    int t;\n    scanf(\"%d\", &t);\n    for(int i = 0; i < t; i++)\n    {\n        read();\n        solve();\n    }\n}",
    "tags": [
      "games",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1312",
    "index": "G",
    "title": "Autocompletion",
    "statement": "You are given a set of strings $S$. Each string consists of lowercase Latin letters.\n\nFor each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions:\n\n- if the current string is $t$, choose some lowercase Latin letter $c$ and append it to the back of $t$, so the current string becomes $t + c$. This action takes $1$ second;\n- use autocompletion. When you try to autocomplete the current string $t$, a list of all strings $s \\in S$ such that $t$ is a prefix of $s$ is shown to you. \\textbf{This list includes $t$ itself, if $t$ is a string from $S$}, and the strings are ordered lexicographically. You can transform $t$ into the $i$-th string from this list in $i$ seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type.\n\nWhat is the minimum number of seconds that you have to spend to type each string from $S$?\n\n\\textbf{Note that the strings from $S$ are given in an unusual way}.",
    "tutorial": "First of all, the information given in the input is the structure of a trie built on $S$ and some other strings - so we can store this information in the same way as we store a trie. Okay, now let's calculate the number of seconds required to type each string with dynamic programming: let $dp_i$ be the number of seconds required to arrive to the $i$-th vertex of the trie. For regular vertices, $dp_i = dp_{p_i} + 1$, where $p_i$ is the parent of vertex $i$; for vertices corresponding to strings from $S$, $dp$ values should be updated with the time required to autocomplete some of the parents to the current vertex. To do these updates, let's calculate the answers for all strings in lexicographical order. We will run DFS on the trie and maintain a segment tree on the path from the root to the current vertex. In the segment tree, we will store the values of $dp_i + cost_i$, where $cost_i$ is the number of seconds required to autocomplete from $i$ to the current vertex. Obviously, if we are currently in a vertex representing a word from $S$, then we have to find the minimum in this segment tree - and that will be the cost to get to current vertex using autocompletion. How to maintain $dp_i + cost_i$? Recall that we are running DFS on trie in lexicographical order. When we want to compute the answer for the first string, the value of $cost_i$ for all vertices is $1$, since our string will be the first in all autocompletion lists. And here's a trick to maintain these values for other strings: whenever we compute the answer for some string, add $1$ on the whole tree. For vertices that are ancestors of both current string and some next string, this $+1$ will stay and increase the cost to autocomplete the next string accordingly; but for vertices which are not on the path to some next string, the values of $dp_i + cost_i$ will be already deleted from the segment tree and replaced by new values - so this addition does not affect them. Overall, this works in $O(n \\log n)$, but it can be written in $O(n)$ with a vector instead of a segment tree (since all additions and minimum queries affect the whole structure).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000043;\n\nmap<char, int> nxt[N];\nbool term[N];\nint n, k;\nchar buf[3];\nint dp[N];\nint dict[N];\n\nint T[4 * N];\nint f[4 * N];\n\nvoid build(int v, int l, int r)\n{\n    T[v] = int(1e9);\n    if(l != r - 1)\n    {\n        int m = (l + r) / 2;\n        build(v * 2 + 1, l, m);\n        build(v * 2 + 2, m, r);\n    }\n}\n\nint getVal(int v)\n{\n    return T[v] + f[v];\n}\n\nvoid push(int v, int l, int r)\n{\n    T[v] += f[v];\n    if(l != r - 1)\n    {\n        f[v * 2 + 1] += f[v];\n        f[v * 2 + 2] += f[v];\n    }\n    f[v] = 0;\n}\n\nvoid upd(int v, int l, int r)\n{\n    if(l != r - 1)\n    {\n        T[v] = min(getVal(v * 2 + 1), getVal(v * 2 + 2));\n    }\n}\n\nint get(int v, int l, int r, int L, int R)\n{\n    if(L >= R)\n        return int(1e9);\n    if(l == L && r == R)\n        return getVal(v);\n    push(v, l, r);\n    int m = (l + r) / 2;\n    int ans = min(get(v * 2 + 1, l, m, L, min(m, R)), get(v * 2 + 2, m, r, max(L, m), R));\n    upd(v, l, r);\n    return ans;\n}\n\nvoid add(int v, int l, int r, int L, int R, int val)\n{\n    if(L >= R)\n        return;\n    if(l == L && r == R)\n    {\n        f[v] += val;\n        return;\n    }\n    push(v, l, r);\n    int m = (l + r) / 2;\n    add(v * 2 + 1, l, m, L, min(m, R), val);\n    add(v * 2 + 2, m, r, max(L, m), R, val);\n    upd(v, l, r);\n}\n\nvoid setVal(int v, int l, int r, int pos, int val)\n{\n    if(l == r - 1)\n    {\n        f[v] = 0;\n        T[v] = val;\n        return;\n    }\n    push(v, l, r);\n    int m = (l + r) / 2;\n    if(pos < m)\n        setVal(v * 2 + 1, l, m, pos, val);\n    else\n        setVal(v * 2 + 2, m, r, pos, val);\n    upd(v, l, r);\n}\n\nvoid dfs(int v, int d, int last)\n{\n    dp[v] = last + 1;\n    if(term[v])\n        dp[v] = min(dp[v], get(0, 0, n + 1, 0, d));\n    setVal(0, 0, n + 1, d, dp[v] + 1);\n    if(term[v])\n        add(0, 0, n + 1, 0, d + 1, 1);\n    for(auto x : nxt[v])\n        dfs(x.second, d + 1, dp[v]);\n    setVal(0, 0, n + 1, d, int(1e9));\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++)\n    {\n        int p;\n        scanf(\"%d %s\", &p, buf);\n        char c = buf[0];\n        nxt[p][c] = i + 1;\n    }\n    scanf(\"%d\", &k);\n    for(int i = 0; i < k; i++)\n    {\n        scanf(\"%d\", &dict[i]);\n        term[dict[i]] = true;\n    }\n\n    build(0, 0, n + 1);\n    dfs(0, 0, -1);\n    for(int i = 0; i < k; i++)\n        printf(\"%d \", dp[dict[i]]);\n    puts(\"\");\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1313",
    "index": "A",
    "title": "Fast Food Restaurant",
    "statement": "Tired of boring office work, Denis decided to open a fast food restaurant.\n\nOn the first day he made $a$ portions of dumplings, $b$ portions of cranberry juice and $c$ pancakes with condensed milk.\n\nThe peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:\n\n- every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);\n- each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;\n- all visitors should receive different sets of dishes.\n\nWhat is the maximum number of visitors Denis can feed?",
    "tutorial": "Bruteforce solution There are seven possible sets of dishes, so the simplest solution is to iterate over all possible $2^7$ subsets of sets of dishes. You can also go over $7!$ permutations of sets of dishes and gather sets of dishes greedily in the selected order. Greedy solution Note that the solution can be optimal only when it is impossible to add an additional set of dishes to it. Let the solution be such that it is impossible to add a single set of dishes to it and it does not have any set consisting of one dish, but there is a set consisting of two or three dishes containing this one dish. Then you can replace the corresponding set with a set of one dish, without worsening the answer. This means that at the beginning you can greedily add all the sets consisting of one dish. The same can show that any set of three dishes can be replaced with a set of two dishes, so after the sets of one and two dishes are fixed, it is enough to simply check whether you can add a set of three dishes. However, it is wrong to choose sets of two dishes greedily. Suppose that after choosing sets of one dish, there is one dish of the first type, one dish of the second type and two dishes of the third type. Then you can choose two sets of dishes, but if you take at the beginning a set of dishes of the first and second types, you won't get two different sets. In this case, you can simply iterate over the order of choosing sets of two dishes or notice that all such tests have the form $2\\, 2\\, x$, $2\\, x\\, 2$, $x\\, 2\\, 2$, where $x \\geq 3$, and solve them separately.",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1313",
    "index": "B",
    "title": "Different Rules",
    "statement": "Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $n$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.\n\nSuppose in the first round participant A took $x$-th place and in the second round — $y$-th place. Then the total score of the participant A is sum $x + y$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $i$ from $1$ to $n$ \\textbf{exactly one} participant took $i$-th place in first round and \\textbf{exactly one} participant took $i$-th place in second round.\n\nRight after the end of the Olympiad, Nikolay was informed that he got $x$-th place in first round and $y$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.",
    "tutorial": "Without loss of generality, assume that $x \\leq y$. For convenience, we will number the participants from 1 to $n$ in the order of their places in the first round. Thus, the participant we are interested in is the participant $x$. First we can prove the formula: $\\operatorname{MIN\\_PLACE} = \\max(1, \\min(n, x + y - n + 1))$ First case: $x + y < n$. It can be shown that participant $x$ can achieve first place in the Olympics. In order to do this, the following example can be built: $i$-th participant ($1 \\leq i \\leq x-1$) takes $(x+y+1-i)$-th place in the second round (sum - $x+y+1$) $x$-th participant takes $y$-th place in the second round (sum - $x+y$) $j$-th participant ($x+1 \\leq j \\leq n-y$) takes $(n+x+1-j)$-th place in the second round (sum - $n+x+1$) $(n-y+1)$-th participant takes $(y+1)$-th place in the second round (sum - $n+2$) $t$-th participant ($n-y+2 \\leq t \\leq n$) takes $(n+1-t)$-th place in the second round (sum - $n+1$) The illustration below explains this example $i$-th participant ($1 \\leq i \\leq x-1$) takes $(x+y+1-i)$-th place in the second round (sum - $x+y+1$) $x$-th participant takes $y$-th place in the second round (sum - $x+y$) $j$-th participant ($x+1 \\leq j \\leq n-y$) takes $(n+x+1-j)$-th place in the second round (sum - $n+x+1$) $(n-y+1)$-th participant takes $(y+1)$-th place in the second round (sum - $n+2$) $t$-th participant ($n-y+2 \\leq t \\leq n$) takes $(n+1-t)$-th place in the second round (sum - $n+1$) Second case: $x + y \\geq n+1;\\; y \\ne n$Consider the participant with the number $k$ ($k \\leq x + y - n < x$). They will receive no more than $x+y-n+n = x + y$ in total (because $n$ is the maximum place in the second round they can take), that is guaranteed to overtake the main character. Thus we can't achieve any place better than $x+y-n+1$. For this assessment, an example below is given: $i$-th participant $(1 \\leq i \\leq x+y-n)$ takes $i$-th place in the second round (sum - $2i < x + y$) $j$-th participant $(x+y-n+1 \\leq j \\leq x-1)$ takes $(x+y+1-j)$-th place in the second round (sum - $x+y+1$) $x$-th participant takes the y-th place in the second round (sum - $x+y$) $(x+1)$-th participant takes $(y+1)$-th place in the second round (sum - $x+y+2$) $t$-th participant $(x+2 \\leq t \\leq n)$ takes $(x+y+1-t)$-th place in the second round (sum - $x+y+1$) The illustration below explains this example Consider the participant with the number $k$ ($k \\leq x + y - n < x$). They will receive no more than $x+y-n+n = x + y$ in total (because $n$ is the maximum place in the second round they can take), that is guaranteed to overtake the main character. Thus we can't achieve any place better than $x+y-n+1$. For this assessment, an example below is given: $i$-th participant $(1 \\leq i \\leq x+y-n)$ takes $i$-th place in the second round (sum - $2i < x + y$) $j$-th participant $(x+y-n+1 \\leq j \\leq x-1)$ takes $(x+y+1-j)$-th place in the second round (sum - $x+y+1$) $x$-th participant takes the y-th place in the second round (sum - $x+y$) $(x+1)$-th participant takes $(y+1)$-th place in the second round (sum - $x+y+2$) $t$-th participant $(x+2 \\leq t \\leq n)$ takes $(x+y+1-t)$-th place in the second round (sum - $x+y+1$) Third case: $x + y \\geq n+1$; $y = n$Then the participant with the number $k$ ($k \\leq x + y - n + 1 = x + 1$) will receive no more than $x+y-n+1+n-1 = x + y$ in total, that is guaranteed to overtake the main character. That is, we can't take places better than $x+y-n+1$. For this assessment, we give an example below: Participant $i < x$ takes $x$-th place, overtaking $x+y$ Participant $x + 1$ takes $(n-1)$-th place, overtaking $x+y$ Participant $j$ ($x + 2 \\leq j \\leq n$) takes $(x+y+1-j)$-th place A separate case: $x = y = n$, then the outcome is obvious Then the participant with the number $k$ ($k \\leq x + y - n + 1 = x + 1$) will receive no more than $x+y-n+1+n-1 = x + y$ in total, that is guaranteed to overtake the main character. That is, we can't take places better than $x+y-n+1$. For this assessment, we give an example below: Participant $i < x$ takes $x$-th place, overtaking $x+y$ Participant $x + 1$ takes $(n-1)$-th place, overtaking $x+y$ Participant $j$ ($x + 2 \\leq j \\leq n$) takes $(x+y+1-j)$-th place A separate case: $x = y = n$, then the outcome is obvious The formula for the minimum place is proved. The formula for the maximum place will be proven in the same way: We prove the formula: $\\operatorname{MAX\\_PLACE} = \\min(n, x + y-1)$ First case: $x + y \\geq n+1$. Then we can give an example in which we will take the last place: $i$-th participant ($1 \\leq i \\leq x+y-n-1$) takes $(y+x-n-i)$-th place in the second round (sum - $y + x-n$) $j$-th participant ($x+y-n-1 \\leq j \\leq n$) takes $(x+y-j)$-th place in the second round (sum - $y + x$) $i$-th participant ($1 \\leq i \\leq x+y-n-1$) takes $(y+x-n-i)$-th place in the second round (sum - $y + x-n$) $j$-th participant ($x+y-n-1 \\leq j \\leq n$) takes $(x+y-j)$-th place in the second round (sum - $y + x$) Second case: $x + y \\leq n$ Consider a participant with the number $k$ ($x+y \\leq k$). They are guaranteed to be overtaken by $x+y$ (main character) So the main character can not take any place worse than $x+y-1$: $i$-th participant ($1 \\leq i \\leq x+y-1$) takes ($y+x-i$)-th place in the second round (sum - $y + x-n$) $j$-th participant ($x+y-1 \\leq j \\leq n$) takes ($x+y+n-j$)-th place in the second round (sum - $y + x$) $i$-th participant ($1 \\leq i \\leq x+y-1$) takes ($y+x-i$)-th place in the second round (sum - $y + x-n$) $j$-th participant ($x+y-1 \\leq j \\leq n$) takes ($x+y+n-j$)-th place in the second round (sum - $y + x$) Thus, the problem was reduced to the problem of output of two numbers - $\\left< \\max(1, \\min(n, x + y - n + 1)),\\;\\;\\min(n, x + y-1)\\right>$",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1313",
    "index": "C2",
    "title": "Skyscrapers (hard version)",
    "statement": "This is a harder version of the problem. In this version $n \\le 500\\,000$\n\nThe outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $n$ plots along the highway and is preparing to build $n$ skyscrapers, one skyscraper per plot.\n\nArchitects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.\n\nFormally, let's number the plots from $1$ to $n$. Then if the skyscraper on the $i$-th plot has $a_i$ floors, it must hold that $a_i$ is at most $m_i$ ($1 \\le a_i \\le m_i$). Also there mustn't be integers $j$ and $k$ such that $j < i < k$ and $a_j > a_i < a_k$. Plots $j$ and $k$ are \\textbf{not} required to be adjacent to $i$.\n\nThe company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.",
    "tutorial": "Let's solve the task on an array $m$ of length $n$. Let's find a minimal element in this array. Let it be on the $i$-th ($1 \\leq i \\leq n$) position. We can build the skyscraper at the $i$-th position as high as possible, that is $a_i = m_i$. Now we should make a choice - we need to equate to $a_i$ either the left part of the array ($a_1 = a_i, a_2 = a_i, \\ldots, a_{i-1} = a_i$), or the right part ($a_{i+1} = a_i, a_{i+2} = a_i, \\ldots, a_{n} = a_i$), and solve the task recursively on the remaining part of the array, until we get an array of length 1. The described recursive task has $n$ different states. Depending on the approach of finding a minimal element on a segment, we can get solutions of complexity $O(n^2)$, $O(n \\sqrt{n})$ or $O(n \\log n)$. There is another solution. It can be proved that the answer looks like this: from the start of the array the heights are non-decreasing, and starting from the certain skyscraper the heights are non-increasing. Let's call a skyscraper \"peak\" if there is the change of direction on this skyscraper. We are to find the optimal \"peak\". We can build arrays $l$ and $r$ of length $n$. Let's iterate positions from left to right. Let we are on the $i$-th position. If $m_i$ is the smallest element among $m_1, \\ldots, m_i$, then $l_i = i \\times m_i$. Otherwise, let's look at $m_1, m_2, \\ldots, m_{i-1}$ and take the rightest number smaller than $m_i$, let it be $m_j$ on the $j$-th position. Then $l_i = l_j + (i - j) \\times m_i$. Similarly, we build $r$ (but changing the direction from right to left). The \"peak\" is the skyscraper $t$ such that $l_t + r_t - m_t$ is maximal. The complexity of this solution can be $O(n^2)$, $O(n \\log n)$, $O(n)$ depending on the approach of finding \"nearest\" numbers to the right and to the left that are smaller than the current one.",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1313",
    "index": "D",
    "title": "Happy New Year",
    "statement": "Being Santa Claus is very difficult. Sometimes you have to deal with difficult situations.\n\nToday Santa Claus came to the holiday and there were $m$ children lined up in front of him. Let's number them from $1$ to $m$. Grandfather Frost knows $n$ spells. The $i$-th spell gives a candy to every child whose place is in the $[L_i, R_i]$ range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most $k$ candies.\n\nIt is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.\n\nHelp Santa Claus to know the maximum number of children he can make happy by casting some of his spells.",
    "tutorial": "We wil use scanline to solve this problem. For all segments, we add event of its beginning and end. Let's maintain $dp_{i, mask}$, where $i$ is number of events that we have already processed. $mask$ is mask of $k$ bits, where $1$ in some bit means that segment corresponding to this bit is taken. How to move from one coordinate to another? For all masks we can count number of $1$ bits and if it is odd, we should add distance between to points to value of this $dp$. How to add new segment? As we know, at one point can be at most $k$ segments, so when we add segment we can find free bit and create match to this segment. After this operation we also should change some values of $dp$. Deleting of the segments is similar to adding. As you may notice, only $(i - 1)$-th lay is needed to calculate $i$-th lay, so we can use only $O(2^k)$ additional memory. Total complexity $O(n \\log n + n2^k)$.",
    "tags": [
      "bitmasks",
      "dp",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1313",
    "index": "E",
    "title": "Concatenation with intersection",
    "statement": "Vasya had three strings $a$, $b$ and $s$, which consist of lowercase English letters. The lengths of strings $a$ and $b$ are equal to $n$, the length of the string $s$ is equal to $m$.\n\nVasya decided to choose a substring of the string $a$, then choose a substring of the string $b$ and concatenate them. Formally, he chooses a segment $[l_1, r_1]$ ($1 \\leq l_1 \\leq r_1 \\leq n$) and a segment $[l_2, r_2]$ ($1 \\leq l_2 \\leq r_2 \\leq n$), and after concatenation he obtains a string $a[l_1, r_1] + b[l_2, r_2] = a_{l_1} a_{l_1 + 1} \\ldots a_{r_1} b_{l_2} b_{l_2 + 1} \\ldots b_{r_2}$.\n\nNow, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions:\n\n- segments $[l_1, r_1]$ and $[l_2, r_2]$ have non-empty intersection, i.e. there exists at least one integer $x$, such that $l_1 \\leq x \\leq r_1$ and $l_2 \\leq x \\leq r_2$;\n- the string $a[l_1, r_1] + b[l_2, r_2]$ is equal to the string $s$.",
    "tutorial": "For all $1 \\leq i \\leq n$ let's define $fa_i$ as the length of the longest common prefix of strings $a[i, n]$ and $s[1, m - 1]$, $fb_i$ as the length of the longest common suffix of strings $b[1, i]$ and $s[2, m]$. Values of $fa$ can be easily found from $z$-function of the string \"$s\\#a$\", values of $fb$ from $z$-function of the string \"$\\overline{s}\\#\\overline{b}$\" (here $\\overline{s}$ is defined as reversed string $s$). Let's fix $l_1$ and $r_2$. Let's note, that $l_1 \\leq r_2$, because segments have non-empty intersection. Also, the sum of lengths of segments is equal to $m$ and they have non-empty intersection, so $r_2 \\leq l_1 + m - 2$. It's easy to see, that segments will have non-empty intersection if and only if $l_1 \\leq r_2 \\leq l_1 + m - 2$. Let's note, that if for fixed $l_1$ and $r_2$ innequalities are true, the number of segments with such $l_1$ and $r_2$ is equal to $\\max{(fa_{l_1} + fb_{r_2} - m + 1, 0)}$. So, the answer to the problem is equal to $\\sum\\limits_{1 \\leq l_1 \\leq r_2 \\leq \\min{(l_1 + m - 2, n)}} {\\max{(fa_{l_1} + fb_{r_2} - m + 1, 0)}} = \\sum\\limits_{l_1 = 1}^{n} {\\sum\\limits_{r_2 = l_1}^{\\min{(l_1 + m - 2, n)}} {\\max{(fa_{l_1} + fb_{r_2} - m + 1, 0)}}}$. Let's make two Fenwick trees on arrays of size $m$. Let's iterate $l_1$ from $1$ to $n$. For $r_2 \\in [l_1, \\min{(l_1 + m - 2, n)}]$ let's add in the position $m - 1 - fb_{r_2}$ of the first tree the number $1$, in the position $m - 1 - fb_{r_2}$ of the second tree the number $fb_{r_2}$. After that the sum for fixed $l_1$ can be easily found from sums in Fenwick trees on prefixes $i \\leq fa_{l_1}$. The total complexity is $O(n \\log{n})$.",
    "tags": [
      "data structures",
      "hashing",
      "strings",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1315",
    "index": "A",
    "title": "Dead Pixel",
    "statement": "Screen resolution of Polycarp's monitor is $a \\times b$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $(x, y)$ ($0 \\le x < a, 0 \\le y < b$). You can consider columns of pixels to be numbered from $0$ to $a-1$, and rows — from $0$ to $b-1$.\n\nPolycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.\n\nPrint the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.",
    "tutorial": "You can see that you should place the window in such a way so that the dead pixel is next to one of the borders of the screen: otherwise we can definitely increase the size of the window. There are four possible ways to place the window right next to the dead pixel - you can place it below, above, to the left or to the right of the dead pixel. if you place the window to the left to the pixel, the maximal size of the screen will be $x \\cdot b$; if you place the window to the right to the pixel, the maximal size of the screen will be $(a - 1 - x) \\cdot b$; if you place the window above the pixel, the maximal size of the screen will be $a \\cdot y$; if you place the window above the pixel, the maximal size of the screen will be $a \\cdot (b - 1 - y)$. These four cases can be united to one formula like $\\max(\\max(x, a-1-x) \\cdot b, a \\cdot \\max(y, b-1-y))$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1315",
    "index": "B",
    "title": "Homecoming",
    "statement": "After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $n$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.\n\nThe crossroads are represented as a string $s$ of length $n$, where $s_i = A$, if there is a bus station at $i$-th crossroad, and $s_i = B$, if there is a tram station at $i$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $s_1$) and his goal is to get to the last crossroad (which corresponds to $s_n$).\n\nIf for two crossroads $i$ and $j$ for all crossroads $i, i+1, \\ldots, j-1$ there is a bus station, one can pay $a$ roubles for the bus ticket, and go from $i$-th crossroad to the $j$-th crossroad by the bus (it is not necessary to have a bus station at the $j$-th crossroad). Formally, paying $a$ roubles Petya can go from $i$ to $j$ if $s_t = A$ for all $i \\le t < j$.\n\nIf for two crossroads $i$ and $j$ for all crossroads $i, i+1, \\ldots, j-1$ there is a tram station, one can pay $b$ roubles for the tram ticket, and go from $i$-th crossroad to the $j$-th crossroad by the tram (it is not necessary to have a tram station at the $j$-th crossroad). Formally, paying $b$ roubles Petya can go from $i$ to $j$ if $s_t = B$ for all $i \\le t < j$.\n\nFor example, if $s$=\"AABBBAB\", $a=4$ and $b=3$ then Petya needs:\n\n- buy one bus ticket to get from $1$ to $3$,\n- buy one tram ticket to get from $3$ to $6$,\n- buy one bus ticket to get from $6$ to $7$.\n\nThus, in total he needs to spend $4+3+4=11$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $s_n$) does not affect the final expense.\n\nNow Petya is at the first crossroad, and he wants to get to the $n$-th crossroad. After the party he has left with $p$ roubles. He's decided to go to some station on foot, and then go to home using only public transport.\n\nHelp him to choose the closest crossroad $i$ to go on foot the first, so he has enough money to get from the $i$-th crossroad to the $n$-th, using only tram and bus tickets.",
    "tutorial": "The first thing you should do in this problem - you should understand the problem statement (which could be not very easy), and get the right answers to the sample test cases. Petya needs to find the minimal $i$ such that he has enough money to get from $i$ to $n$ (not $n+1$, he doesn't need to use the transport from the last crossroad. This was a rather common mistake in misunderstanding the statement) using only public transport. We can see that if Petya can get from $i$ to $n$ using only public transport, he can also get from any $j>i$ to $n$, using only public transport (because he will need fewer tickets). Let's iterate the candidates for $i$ from $n$ to $1$ and try to find the minimal possible $i$. Of course, Petya can go from $n$ to $n$ using only public transport (he doesn't need to buy any ticket). Suppose Petya can get from $j$ to $n$ for some $j$, and it would cost him $t_j$ money. How much money he would need to get from $j-1$ to $n$? He definitely should be able to buy a ticket at station $j-1$. So, if it is the same ticket he should buy at station $j$, he will need the same amount of money, because he doesn't need to buy two consecutive equal tickets, it has no sense. Otherwise, he should buy one more ticket. So, a minimal amount of money $t_{j-1}$ to get from $j-1$ to $j$ is $t_j$, if $j<n$ and $s_{j-1}=s_j$, and $t_j+cost(s_{j-1})$ otherwise ($cost(s_{j-1})$ is $a$ if $s_{j-1} = \\texttt{A}$, and $b$ otherwise). If this value is greater than $p$, he should go to $j$ by foot, otherwise, we should resume the process because he can go to $j-1$ or even some less-numbered crossroads.",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1315",
    "index": "C",
    "title": "Restoring Permutation",
    "statement": "You are given a sequence $b_1, b_2, \\ldots, b_n$. Find the lexicographically minimal permutation $a_1, a_2, \\ldots, a_{2n}$ such that $b_i = \\min(a_{2i-1}, a_{2i})$, or determine that it is impossible.",
    "tutorial": "This problem has a greedy solution. As you know the $b_i$, which is equal to $\\min(a_{2i-1}, a_{2i})$, then one of $a_{2i-1}, a_{2i}$ should be equal to $b_i$. Which one? Of course, $a_{2i-1}$, because we want to get the lexicographically minimal answer, and we want to place a smaller number before the larger number. So, we know that $a_1 = b_1$, $a_3 = b_2$, $a_5 = b_3$, and so on, so we know all elements of the permutation with odd indices. What number should be placed at $a_2$? We know that $a_2 \\ge a_1$ (as $a_1 \\ne a_2$, and $b_1 = \\min(a_1, a_2)$). So, let's take the $a_2 = x$ for minimal possible $x$ such that $x \\ge a_1$ and $x \\ne a_1, x \\ne a_3, \\ldots, x \\ne a_{2n-1}$. If there is no such $x$ (if all numbers greater than $a_1$ are already used), there is no appropriate permutation. Otherwise, we should take $a_2=x$ and resume the process. The question is, why do we can place the minimal not used integer each time? Suppose there is another optimal answer $a'_1, a'_2, \\ldots, a'_{2n}$, and we get $a_1, a_2, \\ldots, a_{2n}$ or we didn't get any permutation by our greedy algorithm. As these two sequences are different, there is the first $k$ such that $a'_{2k} \\ne a_{2k}$. As we tried to take the minimal possible $a_{2k}$, there are two options: $a_{2k} > a'_{2k}$. This is impossible as we tried to take the minimal possible $a_{2k}$, contradiction; $a_{2k} < a'_{2k}$. As $a'$ is <<optimal correct>> answer, we didn't finish our sequence $a$. Let's see, where is the number $a_{2k}$ in the sequence $a'$. It should be on some position $2l$, where $l>k$ (as $2k$ is the first difference between the sequences). But we can swap $a'_{2k}$ and $a'_{2l}$ and get smaller, but still correct sequence $a\"$, so $a'$ is not optimal. Contradiction.",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1316",
    "index": "A",
    "title": "Grade Allocation",
    "statement": "$n$ students are taking an exam. The highest possible score at this exam is $m$. Let $a_{i}$ be the score of the $i$-th student. You have access to the school database which stores the results of all students.\n\nYou can change each student's score as long as the following conditions are satisfied:\n\n- All scores are integers\n- $0 \\leq a_{i} \\leq m$\n- The average score of the class doesn't change.\n\nYou are student $1$ and you would like to maximize your own score.\n\nFind the highest possible score you can assign to yourself such that all conditions are satisfied.",
    "tutorial": "Since the average score of the class must remain same ,this means the sum of the scores of all students in the class must remain same. We want to maximize the score of the first student and since the minimum score of each student can be zero we can add the scores of the rest of students to the first student as long as his score is less than or equal to m. Therefore the answer is $\\min {(a_1+\\sum_{i=2}^{i = n} a_{i} , m )}$ Time complexity : $O(n)$ per testcase",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long int\nint main()\n{\n\tll test;\n\tcin>>test;\n\twhile(test--)\n\t{\n\t\tll n,m;\n\t\tcin>>n>>m;\n\t\tll s=0;\n\t\tfor(ll i=1;i<=n;i++)\n\t\t{\n\t\t\tll x;\n\t\t\tcin>>x;\n\t\t\ts=s+x;\n\t\t}\n\t\tcout<<min(s,m)<<\"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1316",
    "index": "B",
    "title": "String Modification",
    "statement": "Vasya has a string $s$ of length $n$. He decides to make the following modification to the string:\n\n- Pick an integer $k$, ($1 \\leq k \\leq n$).\n- For $i$ from $1$ to $n-k+1$, reverse the substring $s[i:i+k-1]$ of $s$. For example, if string $s$ is qwer and $k = 2$, below is the series of transformations the string goes through:\n\n- qwer (original string)\n- wqer (after reversing the first substring of length $2$)\n- weqr (after reversing the second substring of length $2$)\n- werq (after reversing the last substring of length $2$)\n\nHence, the resulting string after modifying $s$ with $k = 2$ is werq.\n\nVasya wants to choose a $k$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $k$. Among all such $k$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Let the input string $s$ be $s_{1}s_{2}..s_{n}$. We observe the sequence of modifications that the string goes through for some value of $k$. After reversing the first sub-string of length $k$, the string becomes $s_{k}s_{k-1}..s_{1}s_{k+1}s_{k+2}..s_{n}$. Notice that the first character of this string will not be part of any subsequent modifications. After the next step of modification, the string becomes $s_{k}s_{k+1}s_{1}..s_{k-1}s_{k+2}..s_{n}$. Again, notice that the first two characters of this string will not be part of any subsequent modifications. Keep repeating the steps of modification. Do you see any pattern? It is easy to realise that after $i$ steps of modifications, the prefix of the resulting string will be $s_{k}s_{k+1}..s_{k+i-1}$. Since the number of sub-strings to reverse is $(n - k + 1)$, the prefix of our answer string will be $s_{k}s_{k+1}..s_{k+(n-k+1)-1}$, which is just the suffix string $s_{k}..s_{n}$. What about the suffix of our answer string? It can be observed that the suffix will be $s_{1}..s_{k-1}$ if $n$ and $k$ have the same parity and $s_{k-1}..s_{1}$ otherwise. We can generate and compare the modified string for each possible value of $k$ from $1$ to $n$ and find the lexicographically smallest among them. Additionally, we need to take care that the solution outputs the smallest possible $k$ in case when multiple values give the optimal string. Time complexity: $\\mathcal{O}(n^{2})$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring modified(string& s, int n, int k) {\n\tstring result_prefix = s.substr(k - 1, n - k + 1);\n\tstring result_suffix = s.substr(0, k - 1);\n\tif (n % 2 == k % 2)\n\t\treverse(result_suffix.begin(), result_suffix.end());\n\treturn result_prefix + result_suffix;\n}\n\nint main () {\n\tios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\tstring s, best_s, temp;\n\tint t, n, best_k;\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> s;\n\t\tbest_s = modified(s, n, 1);\n\t\tbest_k = 1;\n\t\tfor (int k = 2; k <= n; ++k) {\n\t\t\ttemp = modified(s, n, k);\n\t\t\tif (temp < best_s) {\n\t\t\t\tbest_s = temp;\n\t\t\t\tbest_k = k;\n\t\t\t}\n\t\t}\n\t\tcout << best_s << '\\n' << best_k << '\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1316",
    "index": "C",
    "title": "Primitive Primes",
    "statement": "It is Professor R's last class of his teaching career. Every time Professor R taught a class, he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.\n\nYou are given two polynomials $f(x) = a_0 + a_1x + \\dots + a_{n-1}x^{n-1}$ and $g(x) = b_0 + b_1x + \\dots + b_{m-1}x^{m-1}$, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to $1$ for both the given polynomials. In other words, $gcd(a_0, a_1, \\dots, a_{n-1}) = gcd(b_0, b_1, \\dots, b_{m-1}) = 1$. Let $h(x) = f(x)\\cdot g(x)$. Suppose that $h(x) = c_0 + c_1x + \\dots + c_{n+m-2}x^{n+m-2}$.\n\nYou are also given a prime number $p$. Professor R challenges you to find any $t$ such that $c_t$ isn't divisible by $p$. He guarantees you that under these conditions such $t$ always exists. If there are several such $t$, output any of them.\n\n\\textbf{As the input is quite large, please use fast input reading methods.}",
    "tutorial": "We will prove a simple result thereby giving one of the power that satisfies the constraint: We know that cumulative gcd of coefficients is one in both cases. Hence no prime divides all the coefficients of the polynomial. We call such polynomials primitive polynomials. This question in a way tells us that the product of two primitive polynomials is also a primitive polynomial. Let $x_i$ be the lowest power of $x$ in $f(x)$ whose coefficient is coprime to given prime $p$, and $x_j$ be the lowest power of $x$ in $g(x)$ whose coefficient is coprime to given prime $p$. Since both such coefficients exist, the answer is proved to exist. When we multiply $f(x)$ and $g(x)$, we get the following as the coefficient for $x^{i + j}$, $(a_0 * b_{i + j} + a_1 * b_{i + j - 1} + ...) + a_i * b_j + (a_{i + 1} * b_{j - 1} + a_{i + 2} * b_{j - 2} +...)$ We see the terms inside parentheses are all divisible by the prime $p$, and only $a_i * b_j$ is not divisible by $p$. So, we can say that the coefficient of $x^{i+j}$ is not divisible by $p$. Time complexity : $O(n+m)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define ll long long int\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);cout.tie(0);\n\n\tll n,i,m,x,a,p,fir,sec;\n\t\n\tcin >> n >> m >> p;\n\ta=0;\n\tfor(i=0;i<n;i++)\n\t{\n\t\tcin >> x;\n\t\tif(x%p && !a)\n\t\t{\n\t\t\ta=1;\n\t\t\tfir=i;\n\t\t}\n\t}\n\ta=0;\n\tfor(i=0;i<m;i++)\n\t{\n\t\tcin >> x;\n\t\tif(x%p && !a)\n\t\t{\n\t\t\ta=1;\n\t\t\tsec=i;\n\t\t}\n\t}\n\tcout << fir+sec << endl;\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "math",
      "ternary search"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1316",
    "index": "D",
    "title": "Nash Matrix",
    "statement": "Nash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands.\n\nThis board game is played on the $n\\times n$ board. Rows and columns of this board are numbered from $1$ to $n$. The cell on the intersection of the $r$-th row and $c$-th column is denoted by $(r, c)$.\n\nSome cells on the board are called \\textbf{blocked zones}. On each cell of the board, there is written one of the following $5$ characters  — $U$, $D$, $L$, $R$ or $X$  — instructions for the player. Suppose that the current cell is $(r, c)$. If the character is $R$, the player should move to the right cell $(r, c+1)$, for $L$ the player should move to the left cell $(r, c-1)$, for $U$ the player should move to the top cell $(r-1, c)$, for $D$ the player should move to the bottom cell $(r+1, c)$. Finally, if the character in the cell is $X$, then this cell is the \\textbf{blocked zone}. The player should remain in this cell (the game for him isn't very interesting from now on).\n\nIt is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.\n\nAs a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.\n\nFor every of the $n^2$ cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell $(r, c)$ she wrote:\n\n- a pair ($x$,$y$), meaning if a player had started at $(r, c)$, he would end up at cell ($x$,$y$).\n- or a pair ($-1$,$-1$), meaning if a player had started at $(r, c)$, he would keep moving infinitely long and would never enter the blocked zone.\n\nIt might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.",
    "tutorial": "If there exists a valid board satisfying the input matrix, one can notice two types of clusters in the input matrix, first, a cluster of connected cells having the same stopping point and second, a cluster of connected cells which do not have any stopping point, i.e., all having pair $(-1,-1)$ . Among the cells, having a stopping point, we can start a dfs/bfs from all the cells having stopping point as the cell itself , i.e., cells $(i,j)$ has stopping cell as $(i,j)$. While performing the traversal, we move into any neighbouring cell from current cell if it has the same stopping cell as the current cell. This way, all the cells in clusters of first kind will have an instruction associated - $U$, $D$, $L$, $R$ or $X$ - . For the cells having no stopping cell, we need to put instructions on them such that starting on them, a player keeps moving in a cycle. So these cells are either a part of cycle, or have paths starting from them leading into a cycle. The simplest way to do so is to try to put such cells into disjoint pairs (cycles of length 2 of neighbouring cells), each cell in pair pointing towards the other. Note that after trying to pair up these cells having no stopping point, there are no more two adjacent such cells both unpaired. Now for any such cell which could not be paired up, if it has no adjacent paired up cell, then it is a case of INVALID , else , just put a direction on the cell so that player moves into the adjacent paired up cell. Now if any cell remains without having any instruction alloted, it is a case of INVALID. The complexity of the above solution : $O(n*n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int M = (1<<10)+5;\nchar mat[M][M];\nint x[M][M],y[M][M];\nint n;\n\nbool connect(int p,int q,int r,int s,char d1,char d2)\n{\n\tif(x[r][s] == -1)\n\t{\n\t\tmat[p][q] =  d1;\n\t\tif(mat[r][s] == '\\0') mat[r][s] = d2;\n\t\treturn 1;\n\t}\n\telse\n\t\treturn 0;\n}\n\nvoid dfs(int p,int q,char d)\n{\n\tif(mat[p][q] != '\\0') return;\n\tmat[p][q] = d;\n\n\tif(x[p][q] == x[p+1][q] && y[p][q] == y[p+1][q])\n\t\tdfs(p+1,q,'U');\n\tif(x[p][q] == x[p-1][q] && y[p][q] == y[p-1][q])\n\t\tdfs(p-1,q,'D');\n\tif(x[p][q] == x[p][q+1] && y[p][q] == y[p][q+1])\n\t\tdfs(p,q+1,'L');\n\tif(x[p][q] == x[p][q-1] && y[p][q] == y[p][q-1])\n\t\tdfs(p,q-1,'R');\n}\n\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\n\tint i,j;\n\n\tcin >> n;\n\n\tfor(i=1;i<=n;++i)\n\t{\n\t\tfor(j=1;j<=n;++j)\n\t\t\tcin >> x[i][j] >> y[i][j];\n\t}\n\n\tfor(i=1;i<=n;++i)\n\t{\n\t\tfor(j=1;j<=n;++j)\n\t\t{\n\t\t\tif(x[i][j] == -1)\n\t\t\t{\n\t\t\t\tbool res = (mat[i][j] != '\\0');\n\t\t\t\tif(res == 0) res = connect(i,j,i+1,j,'D','U');\n\t\t\t\tif(res == 0) res = connect(i,j,i,j+1,'R','L');\n\t\t\t\tif(res == 0) res = connect(i,j,i-1,j,'U','D');\n\t\t\t\tif(res == 0) res = connect(i,j,i,j-1,'L','R');\n\t\t\t\tif(res == 0)\n\t\t\t\t{\n\t\t\t\t\tcout << \"INVALID\" << \"\\n\";\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(x[i][j] == i && y[i][j] == j)\n\t\t\t\tdfs(i,j,'X');\n\t\t}\n\t}\n\n\tfor(i=1;i<=n;++i)\n\t{\n\t\tfor(j=1;j<=n;++j)\n\t\t{\n\t\t\tif(mat[i][j] == '\\0')\n\t\t\t{\n\t\t\t\tcout << \"INVALID\" << \"\\n\";\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\t\n\t}\n\n\tcout << \"VALID\" << \"\\n\";\n\n\tfor(i=1;i<=n;++i)\n\t{\n\t\tfor(j=1;j<=n;++j)\n\t\t{\n\t\t\tcout << mat[i][j];\n\t\t}\t\n\t\tcout << \"\\n\";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1316",
    "index": "E",
    "title": "Team Building",
    "statement": "Alice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of $p$ players playing in $p$ different positions. She also recognizes the importance of audience support, so she wants to select $k$ people as part of the audience.\n\nThere are $n$ people in Byteland. Alice needs to select exactly $p$ players, one for each position, and exactly $k$ members of the audience from this pool of $n$ people. Her ultimate goal is to maximize the total strength of the club.\n\nThe $i$-th of the $n$ persons has an integer $a_{i}$ associated with him — the strength he adds to the club if he is selected as a member of the audience.\n\nFor each person $i$ and for each position $j$, Alice knows $s_{i, j}$  — the strength added by the $i$-th person to the club if he is selected to play in the $j$-th position.\n\nEach person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.\n\nSince Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.",
    "tutorial": "Idea is DP(bitmask) First sort the people in non-increasing order of $a_{i}$. let $dp[i][mask]$ = maximum strength of the club if we choose players from $1 \\ldots i$, mask tells us about the positions in the team which have been covered. Don't worry about the audience part as of now, we will see how it is handled during transitions. $dp[0][0]=0$ - initial state. Lets try to find $dp[i][mask]$ If the $i$-th person is chosen to play in $j$-th position, $dp[i][mask] = dp[i-1][mask \\oplus 2^j] + s_{i,j}$ - $(1)$. If we don't choose $i$ as a player, then we can take him as an audience member or not take him at all. I claim that if the no. of audience members chosen till now < $k$, then we must select $i$ as an audience member , We can prove this. If we don't select $i$ as audience, we will need to select some $j$ ($j>i$), strength in that case will include $a_j$ but not $a_i$ , but as $a_i \\geq a_j$, it is always better to select $i$. We now need to know how many audience members have been selected for state $(i-1,mask)$. let $c$ be the no. of persons who have not been selected as players, then $c$ = $i-1$ - no. of set bits in mask.By the above logic, we can say that if $c \\geq k$, we have chosen already k audience members. So, the solution becomes: if $c < k$ , then $dp[i][mask] = dp[i-1][mask] + a_i$ - (2), else $dp[i][mask] = dp[i-1][mask]$ - (2), You need to choose maximum of $(1)$ and $(2)$ as $dp[i][mask]$. $dp[n][2^p-1]$ would be the answer to our question. Time Complexity : $O(n \\cdot p \\cdot 2^p)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long int\nconst ll M=1e5+5;\nll dp[M][(1<<7)+1],skill[M][7];\nll ind[M],a[M];\nbool cmp(ll p,ll q)\n{\n\treturn a[p]>a[q];\n}\nint main()\n{\n\tios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\tll n,p,k;\n\tcin>>n>>p>>k;\n\tmemset(dp,-1,sizeof(dp));\n\tfor(ll i=1;i<=n;i++)\n\t\tcin>>a[i];\n\tfor(ll i=1;i<=n;i++)\n\t\tfor(ll j=0;j<p;j++)\n\t\t\tcin>>skill[i][j];\n\tfor(ll i=1;i<=n;i++)\n\t\tind[i]=i;\n\tsort(ind+1,ind+n+1,cmp);\t\n\tdp[0][0]=0;\n\tfor(ll i=1;i<=n;i++)\n\t{\n\t\tll x=ind[i];\n\t\tfor(ll mask=0;mask<(1<<p);mask++)\n\t\t{\n\t\t\tll ct=0;\n\t\t\tfor(ll j=0;j<p;j++)\n\t\t\t\tif((mask&(1<<j)))\n\t\t\t\t\tct++;\n\t\t\tll z=(i-1)-ct;\n\t\t\tif(z<k)\n\t\t\t{\n\t\t\t\tif(dp[i-1][mask]!=-1)\n\t\t\t\t\tdp[i][mask]=dp[i-1][mask]+a[x];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(dp[i-1][mask]!=-1)\n\t\t\t\t\tdp[i][mask]=dp[i-1][mask];\n\t\t\t}\n\t\t\tfor(ll j=0;j<p;j++)\n\t\t\t{\n\t\t\t\tif((mask&(1<<j)) && dp[i-1][(mask^(1<<j))]!=-1)\n\t\t\t\t{\n\t\t\t\t\tll z=dp[i-1][(mask^(1<<j))]+skill[x][j];\n\t\t\t\t\tif(z>dp[i][mask])\n\t\t\t\t\t\tdp[i][mask]=z;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcout<<dp[n][(1<<p)-1]<<\"\\n\";\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1316",
    "index": "F",
    "title": "Battalion Strength",
    "statement": "There are $n$ officers in the Army of Byteland. Each officer has some power associated with him. The power of the $i$-th officer is denoted by $p_{i}$. As the war is fast approaching, the General would like to know the strength of the army.\n\nThe strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these $n$ officers and calls this subset a battalion.(All $2^n$ subsets of the $n$ officers can be chosen equally likely, including empty subset and the subset of all officers).\n\nThe strength of a battalion is calculated in the following way:\n\nLet the powers of the chosen officers be $a_{1},a_{2},\\ldots,a_{k}$, where $a_1 \\le a_2 \\le \\dots \\le a_k$. The strength of this battalion is equal to $a_1a_2 + a_2a_3 + \\dots + a_{k-1}a_k$. (If the size of Battalion is $\\leq 1$, then the strength of this battalion is $0$).\n\nThe strength of the army is equal to the expected value of the strength of the battalion.\n\nAs the war is really long, the powers of officers may change. Precisely, there will be $q$ changes. Each one of the form $i$ $x$ indicating that $p_{i}$ is changed to $x$.\n\nYou need to find the strength of the army initially and after each of these $q$ updates.\n\nNote that the changes are permanent.\n\nThe strength should be found by modulo $10^{9}+7$. Formally, let $M=10^{9}+7$. It can be shown that the answer can be expressed as an irreducible fraction $p/q$, where $p$ and $q$ are integers and $q\\not\\equiv 0 \\bmod M$). Output the integer equal to $p\\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\leq x < M$ and $x ⋅ q \\equiv p \\bmod M$).",
    "tutorial": "First lets try to find the initial strength of the army. Let $p_1,p_2,\\ldots,p_n$ be the powers of officers in sorted order. . Consider a pair ($i,j$) ($i < j$) and find how much it contributes to the answer, the term $p_i \\cdot p_j$ will be present in the strength of the subsets in which both $i$ and $j$ are present and there is no $k$ such that $i < k < j$. Probability of this happening is $\\frac {1}{2^{j-i+1}}$. By linearity of expectation we can say that the contribution of ($i,j$) to the strength of the army is $p_i \\cdot p_j \\cdot \\frac {1}{2^{j-i+1}}$. So the strenth of the army can be written as $S = \\sum_{i=1}^{n} \\sum_{j=i+1}^{n} prob_{i,j} \\cdot p_i \\cdot p_j$ where $prob_{i,j} = \\frac {1}{2^{j-i+1}}$. We can keep a sorted array having $p_1,p_2,\\ldots,p_n$, we can maintain a prefix sum of $pref_i$ = $p_i \\cdot 2^{i-1}$,so $S = \\sum_{j=1}^{n} pref_{j-1} \\cdot \\frac{p_j}{2^{j}}$. But this will not help in handling the updtes. To support updates, we need to process queries offline and use coordinate compression such that all powers lie in range $(1,10^6)$. We can build a segment tree on the compressed powers. For each node of the segment tree, let its range be $(s,e)$, consider that powers(mapped values by coordinate compression) $p_1,p_2,\\ldots,p_k$ line in the range of this node ($s \\leq p_1 \\leq p_2 \\leq \\ldots \\leq p_k \\leq e$). At each node, we need to maintain 4 values. $val: \\sum_{i=1}^{k} \\sum_{j=i+1}^{k} prob_{i,j} \\cdot p_i \\cdot p_j$ $Lval: \\sum_{i=1}^{k} p_i \\cdot 2^{i-1}$ $Rval: \\sum_{j=1}^{k} \\frac{p_j}{2^{j}}$ $count: k$ If we map each power to a unique value, the computation for this values at leaf node $(s=e)$ is trivial. If some power $p$ in the initial set is mapped to s, then values for this node are as follows $val: 0$ $Lval: p$ $Rval: \\frac{p}{2}$ $count: 1$. Lets try to compute these 4 values for non-leaf nodes of the segment tree. (lc and rc denote left and right children of the current node). If we try to write break these values in terms of their counterparts in lc and rc, we can easily write them as: $val : val_{lc}+val_{rc}+\\frac{Lval_{lc} \\cdot Rval_{rc}}{2^{count_{lc}}}$ $Lval : Lval_{lc} + Lval_{rc} \\cdot 2^{count_{lc}}$ $Rval : Rval_{lc} + \\frac {Rval_{rc}}{2^{count_{lc}}}$ $count : count_{lc} + count_{rc}$ Whenver we get a query ,we will need to update 2 leaves, reduce count of the power for old $p_i$ and increase the count of the new_power $p_i = x$. Answer to our problem would be $val$ at root node of the segment tree. Time Complexity: $O((n+q)log(n))$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long int\n#define ff first\n#define ss second\n#define pb push_back\n#define all(a) a.begin(),a.end()\n#define sz(a) (ll)(a.size())\nconst ll M=6e5+6;\nconst ll mod=1e9+7;\nll val[4*M],lt[4*M],rt[4*M];\nint no[4*M];\nll pw[M],ipw[M];\nint P[M],idx[M],qr[M],n,q;\nvector<pair<int,int> > v;\nll power(ll a,ll b)\n{\n\tll val=1;\n\twhile(b)\n\t{\n\t\tif(b%2)\n\t\t\tval=(val*a)%mod;\n\t\tb/=2;\n\t\ta=(a*a)%mod;\n\t}\n\treturn val;\n}\nvoid build(int i,int s,int e)\n{\n\tif(s==e)\n\t{\n\t\tif(v[s].ss>n)\n\t\t\treturn;\n\t\tval[i]=0;\n\t\tlt[i]=v[s].ff;\n\t\trt[i]=(v[s].ff*ipw[1])%mod;\n\t\tno[i]=1;\n\t\treturn;\n\t}\n\tint m=(s+e)/2;\n\tint lc=2*i,rc=2*i+1;\n\tbuild(lc,s,m);\n\tbuild(rc,m+1,e);\n\tll tp=(ipw[no[lc]]*rt[rc])%mod;\n\ttp=(tp*lt[lc])%mod;\n\tval[i]=(val[lc]+val[rc]+tp)%mod;\n\tlt[i]=(lt[lc]+pw[no[lc]]*lt[rc])%mod;\n\trt[i]=(rt[lc]+ipw[no[lc]]*rt[rc])%mod;\n\tno[i]=(no[lc]+no[rc]);\n}\nvoid update(int i,int s,int e,int x,int y)\n{\n\tif(s==e)\n\t{\n\t\tif(y==-1)\n\t\t{\n\t\t\tval[i]=0;\n\t\t\tlt[i]=0;\n\t\t\trt[i]=0;\n\t\t\tno[i]=0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tval[i]=0;\n\t\t\tlt[i]=v[s].ff;\n\t\t\trt[i]=(v[s].ff*ipw[1])%mod;\n\t\t\tno[i]=1;\n\t\t}\n\t\treturn;\n\t}\n\tint m=(s+e)/2;\n\tint lc=(i<<1),rc=(lc|1);\n\tif(x<=m)\n\t\tupdate(lc,s,m,x,y);\n\telse\n\t\tupdate(rc,m+1,e,x,y);\n\tll tp=(ipw[no[lc]]*rt[rc])%mod;\n\ttp=(tp*lt[lc])%mod;\n\tval[i]=(val[lc]+val[rc]+tp)%mod;\n\tlt[i]=(lt[lc]+pw[no[lc]]*lt[rc])%mod;\n\trt[i]=(rt[lc]+ipw[no[lc]]*rt[rc])%mod;\n\tno[i]=(no[lc]+no[rc]);\n}\nint main()\n{\n\tios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\tpw[0]=1;\n\tipw[0]=1;\n\tll inv=power(2,mod-2);\n\tfor(int i=1;i<M;i++)\n\t{\n\t\tpw[i]=(pw[i-1]*2)%mod;\n\t\tipw[i]=(ipw[i-1]*inv)%mod;\n\t}\n\tcin>>n;\n\tv.pb({-1LL,-1});\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tcin>>P[i];\n\t\tv.pb({P[i],i});\n\t}\n\tcin>>q;\n\tfor(int i=1;i<=q;i++)\n\t{\n\t\tcin>>idx[i]>>qr[i];\n\t\tv.pb({qr[i],n+i});\n\t}\n\tsort(all(v));\n\tstd::vector<int> pos(n+q+1,0);\n\tfor(int i=1;i<sz(v);i++)\n\t\tpos[v[i].ss]=i;\n\tbuild(1,1,n+q);\n\tcout<<val[1]<<\"\\n\";\n\tfor(int i=1;i<=q;i++)\n\t{\n\t\tupdate(1,1,n+q,pos[idx[i]],-1);\n\t\tpos[idx[i]]=pos[n+i];\n\t\tupdate(1,1,n+q,pos[idx[i]],1);\n\t\tcout<<val[1]<<\"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1320",
    "index": "A",
    "title": "Journey Planning",
    "statement": "Tanya wants to go on a journey across the cities of Berland. There are $n$ cities situated along the main railroad line of Berland, and these cities are numbered from $1$ to $n$.\n\nTanya plans her journey as follows. First of all, she will choose some city $c_1$ to start her journey. She will visit it, and after that go to some other city $c_2 > c_1$, then to some other city $c_3 > c_2$, and so on, until she chooses to end her journey in some city $c_k > c_{k - 1}$. So, the sequence of visited cities $[c_1, c_2, \\dots, c_k]$ should be strictly increasing.\n\nThere are some additional constraints on the sequence of cities Tanya visits. Each city $i$ has a beauty value $b_i$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $c_i$ and $c_{i + 1}$, the condition $c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$ must hold.\n\nFor example, if $n = 8$ and $b = [3, 4, 4, 6, 6, 7, 8, 9]$, there are several three possible ways to plan a journey:\n\n- $c = [1, 2, 4]$;\n- $c = [3, 5, 6, 8]$;\n- $c = [7]$ (a journey consisting of one city is also valid).\n\nThere are some additional ways to plan a journey that are not listed above.\n\nTanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?",
    "tutorial": "Let's rewrite the equality given in the statement as $c_{i + 1} - b_{c_{i + 1}} = c_i - b_{c_i}$. It means that all cities in our path will have the same value of $i - b_i$; furthermore, all cities with the same such value can always be visited in ascending order. So we may group cities by $i - b_i$, compute the sum in each group and find the maximum over all groups. For example, this can be done by storing the sum for each $i - b_i$ in an array (be careful with negative values of $i - b_i$, though!)",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1320",
    "index": "B",
    "title": "Navigation System",
    "statement": "The map of Bertown can be represented as a set of $n$ intersections, numbered from $1$ to $n$ and connected by $m$ one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection $v$ to another intersection $u$ is the path that starts in $v$, ends in $u$ and has the minimum length among all such paths.\n\nPolycarp lives near the intersection $s$ and works in a building near the intersection $t$. Every day he gets from $s$ to $t$ by car. Today he has chosen the following path to his workplace: $p_1$, $p_2$, ..., $p_k$, where $p_1 = s$, $p_k = t$, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. \\textbf{Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from $s$ to $t$}.\n\nPolycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection $s$, the system chooses some shortest path from $s$ to $t$ and shows it to Polycarp. Let's denote the next intersection in the chosen path as $v$. If Polycarp chooses to drive along the road from $s$ to $v$, then the navigator shows him the same shortest path (obviously, starting from $v$ as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection $w$ instead, the navigator \\textbf{rebuilds} the path: as soon as Polycarp arrives at $w$, the navigation system chooses some shortest path from $w$ to $t$ and shows it to Polycarp. The same process continues until Polycarp arrives at $t$: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system \\textbf{rebuilds} the path by the same rules.\n\nHere is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path $[1, 2, 3, 4]$ ($s = 1$, $t = 4$):\n\n\\begin{center}\nCheck the picture by the link http://tk.codeforces.com/a.png\n\\end{center}\n\n- When Polycarp starts at $1$, the system chooses some shortest path from $1$ to $4$. There is only one such path, it is $[1, 5, 4]$;\n- Polycarp chooses to drive to $2$, which is not along the path chosen by the system. When Polycarp arrives at $2$, the navigator \\textbf{rebuilds} the path by choosing some shortest path from $2$ to $4$, for example, $[2, 6, 4]$ (note that it could choose $[2, 3, 4]$);\n- Polycarp chooses to drive to $3$, which is not along the path chosen by the system. When Polycarp arrives at $3$, the navigator \\textbf{rebuilds} the path by choosing the only shortest path from $3$ to $4$, which is $[3, 4]$;\n- Polycarp arrives at $4$ along the road chosen by the navigator, so the system does not have to rebuild anything.\n\nOverall, we get $2$ rebuilds in this scenario. Note that if the system chose $[2, 3, 4]$ instead of $[2, 6, 4]$ during the second step, there would be only $1$ rebuild (since Polycarp goes along the path, so the system maintains the path $[3, 4]$ during the third step).\n\nThe example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?",
    "tutorial": "Let $d_v$ be the length of the shortest path from $v$ to $t$. If we move from vertex $v$ to vertex $u$ on our path, then: the rebuild will definitely occur if $d_u > d_v - 1$; the rebuild may occur if there exists at least one vertex $w \\ne u$ such that $d_w = d_v - 1$ (the navigation system could have built a path through $w$). We can calculate all values of $d_v$ using BFS from $t$ on a transposed graph. Now for each vertex, we can easily determine whether it should be added to the set of vertices where the route definitely rebuilds and to the set of vertices where a rebuild is possible.",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1320",
    "index": "C",
    "title": "World of Darkraft: Battle for Azathoth",
    "statement": "Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.\n\nRoma has a choice to buy \\textbf{exactly one} of $n$ different weapons and \\textbf{exactly one} of $m$ different armor sets. Weapon $i$ has attack modifier $a_i$ and is worth $ca_i$ coins, and armor set $j$ has defense modifier $b_j$ and is worth $cb_j$ coins.\n\nAfter choosing his equipment Roma can proceed to defeat some monsters. There are $p$ monsters he can try to defeat. Monster $k$ has defense $x_k$, attack $y_k$ and possesses $z_k$ coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster $k$ can be defeated with a weapon $i$ and an armor set $j$ if $a_i > x_k$ and $b_j > y_k$. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.\n\nThanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma \\textbf{must} purchase a weapon and an armor set even if he can not cover their cost with obtained coins.\n\nHelp Roma find the maximum profit of the grind.",
    "tutorial": "Let $S_a$ be the set of monsters which may be defeated with a weapon having attack $a$. Then the profit we get, if we use weapon $i$ with attack $a$ and armor $j$ with defense $b$, is $-ca_i-cb_j+( \\textrm{the sum of $z_k$ over all monsters $k$ from the set $S_a$ having $y_k < b$})$. We will iterate on weapons in non-descending order of their attack values and maintain $S_a$. For each armor option, maintain the value of $D_j = -cb_j+(\\textrm{total profit from monsters having attack less than $b_j$})$. If armor sets are sorted by their defense value, adding a new monster into $S_a$ adds some value on the suffix of $D_j$. So we can maintain the values of $D_j$ in a segment tree. So the solution is: Build a segment tree on values of $-cb_j$, where all armors are sorted by $b_j$. Iterate on weapons and monsters in sorted order (sort by $a_i$/$x_k$ in non-descending order). For each new weapon $i$ we should add all monsters $x_k < a_i$ which were not added yet (we can maintain a pointer on the last added monster to find them quickly). Adding a monster means adding $z_k$ on suffix of $D_i$. After that, for the current weapon $i$ we may try $-ca_i + \\max D_j$ as the answer.",
    "tags": [
      "brute force",
      "data structures",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1320",
    "index": "D",
    "title": "Reachable Strings",
    "statement": "In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ starting from the $l$-th character and ending with the $r$-th character as $s[l \\dots r]$. The characters of each string are numbered from $1$.\n\nWe can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.\n\nBinary string $a$ is considered reachable from binary string $b$ if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1 = a$, $s_k = b$, and for every $i \\in [1, k - 1]$, $s_i$ can be transformed into $s_{i + 1}$ using exactly one operation. Note that $k$ can be equal to $1$, i. e., \\textbf{every string is reachable from itself}.\n\nYou are given a string $t$ and $q$ queries to it. Each query consists of three integers $l_1$, $l_2$ and $len$. To answer each query, you have to determine whether $t[l_1 \\dots l_1 + len - 1]$ is reachable from $t[l_2 \\dots l_2 + len - 1]$.",
    "tutorial": "How to determine if two strings can be transformed into each other? Obviously, the number of ones in both strings should be the same. Also the following invariant holds: if all pairs of consecutive ones are deleted, the positions of remaining ones are not affected by any operations. We can prove that these conditions are sufficient: if we move all pairs of ones to the end of the string, the strings are the same if the positions of ones are the same and the number of characters is the same (moving all pairs of ones to the end of the string is almost the same as deleting them). One of the possible solutions is the following - build a segment tree, where each vertex should maintain: the number of deleted pairs of ones; the hash of positions of the remaining ones; the characters at the ends of the corresponding segment (we need these to delete pairs of consecutive ones, if they appear as a result of merging the segments). When merging a pair of vertices, we check if we have to delete a pair of consecutive ones and rebuild the hash for the new vertex. There are lots of other approaches, including a deterministic one (which uses suffix structures).",
    "tags": [
      "data structures",
      "hashing",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1320",
    "index": "E",
    "title": "Treeland and Viruses",
    "statement": "There are $n$ cities in Treeland connected with $n - 1$ bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.\n\nIn each scenario, several cities are initially infected with different virus species. Suppose that there are $k_i$ virus species in the $i$-th scenario. Let us denote $v_j$ the initial city for the virus $j$, and $s_j$ the propagation speed of the virus $j$. The spread of the viruses happens in turns: first virus $1$ spreads, followed by virus $2$, and so on. After virus $k_i$ spreads, the process starts again from virus $1$.\n\nA spread turn of virus $j$ proceeds as follows. For each city $x$ not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus $j$ if and only if there is such a city $y$ that:\n\n- city $y$ was infected with virus $j$ at the start of the turn;\n- the path between cities $x$ and $y$ contains at most $s_j$ edges;\n- all cities on the path between cities $x$ and $y$ (excluding $y$) were uninfected with any virus at the start of the turn.\n\nOnce a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.\n\nYou need to process $q$ independent scenarios. Each scenario is described by $k_i$ virus species and $m_i$ important cities. For each important city determine which the virus it will be infected by in the end.",
    "tutorial": "When processing a query, the key idea is to build a compressed version of the tree containing only some important vertices. We are not interested in vertices not belonging to any path between some $v_i$ and $u_i$. Furthermore, we can compress all chains in the tree by deleting all vertices with degree $< 2$ not listed in the query. To find all the important vertices in the compressed tree, we may do the following: sort all $v_i$ and $u_i$ by their entry time in DFS traversal of the tree, and then add LCA's of all neighbouring pairs in the sorted list. To restore the edges, we will consider all important vertices in sorted order and maintain the path to the current vertex in a stack. When we process a vertex, we delete vertices from top of the stack until we get an ancestor of current vertex on top of the stack, then this ancestor is the parent of the current vertex in the compressed tree. When we have the compressed tree, there are two approaches to determining the virus affecting each node: Run Dijkstra's algorithm. The distance for each vertex $v$ is the pair (the time when $v$ becomes infected, the index of a virus infecting $v$). For each initially infected vertex $v_i$ the initial distance is $(0,i)$. When processing a vertex with Dijkstra, we can try to infect all of its neighbours with the same virus. Use subtree DP. First of all, for each vertex we determine the virus from its subtree that will infecting it (not taking into account any viruses from above): it's either the virus in this vertex or the virus infecting one of its children. Then we may to the same thing in the other direction: push viruses down the tree and calculate whether they are infecting vertices faster than the viruses from the lower vertices. In any case, each query is processed in $O((k + m) \\log n)$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "shortest paths",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1320",
    "index": "F",
    "title": "Blocks and Sensors",
    "statement": "Polycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size $1 \\times 1 \\times 1$. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size $1 \\times 1 \\times 1$; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates $(x, y, z)$ (the cell with these coordinates is a cube with opposite corners in $(x, y, z)$ and $(x + 1, y + 1, z + 1)$) and its contents $a_{x, y, z}$; if the cell is empty, then $a_{x, y, z} = 0$, otherwise $a_{x, y, z}$ is equal to the type of the block placed in it (the types are integers from $1$ to $2 \\cdot 10^5$).\n\nPolycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size $n \\times m \\times k$, containing all cells $(x, y, z)$ such that $x \\in [1, n]$, $y \\in [1, m]$, and $z \\in [1, k]$. After that, Polycarp has installed $2nm + 2nk + 2mk$ sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into $6$ types:\n\n- there are $mk$ sensors of the first type; each such sensor is installed in $(0, y, z)$, where $y \\in [1, m]$ and $z \\in [1, k]$, and it sends a ray that is parallel to the $Ox$ axis and has the same direction;\n- there are $mk$ sensors of the second type; each such sensor is installed in $(n + 1, y, z)$, where $y \\in [1, m]$ and $z \\in [1, k]$, and it sends a ray that is parallel to the $Ox$ axis and has the opposite direction;\n- there are $nk$ sensors of the third type; each such sensor is installed in $(x, 0, z)$, where $x \\in [1, n]$ and $z \\in [1, k]$, and it sends a ray that is parallel to the $Oy$ axis and has the same direction;\n- there are $nk$ sensors of the fourth type; each such sensor is installed in $(x, m + 1, z)$, where $x \\in [1, n]$ and $z \\in [1, k]$, and it sends a ray that is parallel to the $Oy$ axis and has the opposite direction;\n- there are $nm$ sensors of the fifth type; each such sensor is installed in $(x, y, 0)$, where $x \\in [1, n]$ and $y \\in [1, m]$, and it sends a ray that is parallel to the $Oz$ axis and has the same direction;\n- finally, there are $nm$ sensors of the sixth type; each such sensor is installed in $(x, y, k + 1)$, where $x \\in [1, n]$ and $y \\in [1, m]$, and it sends a ray that is parallel to the $Oz$ axis and has the opposite direction.\n\nPolycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.\n\nAfter some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?",
    "tutorial": "Initially fill each cell with a colorless block, and then try to paint blocks and delete them if they definitely contradict the sensor data. We have to delete a block if: it is observed by a sensor which should see no blocks; it is observed by at least two sensors that report different block types. In any of these cases, we delete a block. Then we update all sensors which were looking at it: for each of them, find the next block which they are looking at, and maybe delete it (if the information for it is contradictory). If this results in deleting all blocks for a sensor that should see a block, then the answer is $-1$. If this process terminates without any contradictions, we can construct the answer. Now all sensors that should not see any blocks don't see them, and each block observed by sensors can be assigned a type that does not contradict the sensor data. If some block is not observed by sensors at all, we may assign any color to it (or even delete it). To maintain blocks that should be deleted, we may use a BFS-like approach with a queue, or a DFS-like function that deletes a block, updates the sensors looking at it, and maybe calls itself recursively for the blocks that have to be deleted after the updates.",
    "tags": [
      "brute force"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1321",
    "index": "A",
    "title": "Contest for Robots",
    "statement": "Polycarp is preparing the first programming contest for robots. There are $n$ problems in it, and a lot of robots are going to participate in it. Each robot solving the problem $i$ gets $p_i$ points, and the score of each robot in the competition is calculated as the sum of $p_i$ over all problems $i$ solved by it. For each problem, $p_i$ is an integer not less than $1$.\n\nTwo corporations specializing in problem-solving robot manufacturing, \"Robo-Coder Inc.\" and \"BionicSolver Industries\", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them.\n\nFor some reason (which absolutely cannot involve bribing), Polycarp wants the \"Robo-Coder Inc.\" robot to outperform the \"BionicSolver Industries\" robot in the competition. Polycarp wants to set the values of $p_i$ in such a way that the \"Robo-Coder Inc.\" robot gets \\textbf{strictly more} points than the \"BionicSolver Industries\" robot. However, if the values of $p_i$ will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of $p_i$ over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?",
    "tutorial": "Score distribution for problems having $r_i = b_i$ is irrelevant (we can make $p_i = 1$ for all of them). Let's consider the remaining problems. Suppose we have $x$ problems solved by the first robot (and not solved by the second one), and $y$ problems solved by the second robot (and not solved by the first one). If $x = 0$, then the score of the first robot won't exceed the score of the second robot by any means, so the answer is $-1$. Otherwise, we can set the score for problems solved by the first robot to some number $p$, and the score for all remaining problems to $1$. Then, the condition $xp > y$ must hold, or $p > \\frac{y}{x}$, so $p = \\lceil \\frac{y + 1}{x} \\rceil$ is the answer. Note that the constraints allow us to iterate on $p$ instead of implementing a formula for it.",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1321",
    "index": "C",
    "title": "Remove Adjacent",
    "statement": "You are given a string $s$ consisting of lowercase Latin letters. Let the length of $s$ be $|s|$. You may perform several operations on this string.\n\nIn one operation, you can choose some index $i$ and \\textbf{remove} the $i$-th character of $s$ ($s_i$) if \\textbf{at least one} of its adjacent characters is the previous letter in the Latin alphabet for $s_i$. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index $i$ should satisfy the condition $1 \\le i \\le |s|$ during each operation.\n\nFor the character $s_i$ adjacent characters are $s_{i-1}$ and $s_{i+1}$. The first and the last characters of $s$ both have only one adjacent character (unless $|s| = 1$).\n\nConsider the following example. Let $s=$ bacabcab.\n\n- During the first move, you can remove the first character $s_1=$ b because $s_2=$ a. Then the string becomes $s=$ acabcab.\n- During the second move, you can remove the fifth character $s_5=$ c because $s_4=$ b. Then the string becomes $s=$ acabab.\n- During the third move, you can remove the sixth character $s_6=$'b' because $s_5=$ a. Then the string becomes $s=$ acaba.\n- During the fourth move, the only character you can remove is $s_4=$ b, because $s_3=$ a (or $s_5=$ a). The string becomes $s=$ acaa and you cannot do anything with it.\n\nYour task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.",
    "tutorial": "The optimal answer can be obtained by the following algorithm: choose the maximum possible (alphabetically) letter we can remove and remove it. We can do it naively and it will lead to $O(n^2)$ time complexity. Why is it always true? Suppose we remove the maximum letter $i$ that can be used to remove some other letter $j$ (it is obvious that $s_i + 1 = s_j$ in such case). If there are no other letters between $s_i$ and $s_j$ then $s_i$ is not the maximum letter, so we got contradiction with our algorithm. Now suppose that we can remove all letters between $s_i$ and $s_j$. Then we first choose $s_j$ and only after that $s_i$ by our algorithm. Consider the last case - there is at least one letter $s_k$ between $s_i$ and $s_j$. Because we cannot remove $s_k$ then there are only two cases: $s_k > s_j + 1$ or $s_k + 1 < s_i$. Then we cannot use $s_i$ to remove $s_j$ at all.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1322",
    "index": "A",
    "title": "Unusual Competitions",
    "statement": "A bracketed sequence is called correct (regular) if by inserting \"+\" and \"1\" you can get a well-formed mathematical expression from it. For example, sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while \")(\", \"(()\" and \"(()))(\" are not.\n\nThe teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.\n\nDima suspects now that he simply missed the word \"correct\" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can \\textbf{the arbitrary number of times} (possibly zero) perform the reorder operation.\n\nThe reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $l$ nanoseconds, where $l$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for \"))((\" he can choose the substring \")(\" and do reorder \")()(\" (this operation will take $2$ nanoseconds).\n\nSince Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.",
    "tutorial": "Obviously, if the number of opening brackets is not equal to the number of closing ones, then since the described operation does not change their number, it will be impossible to get the correct sequence. Otherwise, if their numbers are equal, you can take the entire string and rearrange its $n$ characters so that the string becomes a right bracketed sequence, for example, \"(((($\\dots$))))\". Let $p_i$ be a prefix balance on the first $i$ characters, that is, the difference between the number of opening and closing brackets. Consider an index $i$ such that $bal_{i-1} \\leq 0$, $bal_{i} < 0$, or $bal_{i-1} < 0$, $bal_i \\leq 0$. Then, if the $s_i$ character does not participate in any shuffle oeration, the resulting string will have a $i$th or $i-1$th prefix balance negative, making the resulting sequence incorrect. This means that at least characters with such indexes $i$ must participate in at least one operation. It will be shown below how to use only them in shuffles to make a right bracketed sequence. Let's represent this bracketed sequence as a polyline. It will start at the point with coordinates $(0,0)$, end at the point with coordinates $(2n, 0)$, $i$ - th vector of this polyline will be equal to $(+1, +1)$, if $s_i =$ ( and $(+1, -1)$ otherwise. Then the above-described indexes $i$, which must participate in at least one operation - are exactly all the segments below the line $x=0$. To make the sequence correct, we will turn all consecutive segments of such brackets backwards. It's not hard to see that the sequence will become correct. An example of this conversion is shown below:",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1322",
    "index": "B",
    "title": "Present",
    "statement": "Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute\n\n$$ (a_1 + a_2) \\oplus (a_1 + a_3) \\oplus \\ldots \\oplus (a_1 + a_n) \\\\ \\oplus (a_2 + a_3) \\oplus \\ldots \\oplus (a_2 + a_n) \\\\ \\ldots \\\\ \\oplus (a_{n-1} + a_n) \\\\ $$\n\nHere $x \\oplus y$ is a bitwise XOR operation (i.e. $x$ ^ $y$ in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.",
    "tutorial": "Let's calculate each bit in the answer separately. Suppose we want to know the value of $k$-th (in 0-indexation) bit in the answer. Then we can notice that we are only interested in bits from $0$-th to $k$-th, which means that we can take all numbers modulo $2^{k+1}$. After that, the sum of the two numbers can't exceed $2^{k+2} - 2$. $k$-th bit is 1 if and only if sum belongs to $[2^k; 2^{k+1})$ or $[2^{k+1} + 2^k; 2^{k+2} - 2]$. So, we have to count the number of pairs of numbers that give a sum that belongs to these segments. Let's sort all numbers (taken by modulo) and make a pass with two pointers or do binary searches for each number. Total complexity: $O(n \\log n \\log C)$ Bonus: can you do it in $O(n \\log C)$?",
    "tags": [
      "binary search",
      "bitmasks",
      "constructive algorithms",
      "data structures",
      "math",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1322",
    "index": "C",
    "title": "Instant Noodles",
    "statement": "Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.\n\nYou are given a bipartite graph with positive integers in all vertices of the \\textbf{right} half. For a subset $S$ of vertices of the \\textbf{left} half we define $N(S)$ as the set of all vertices of the right half adjacent to at least one vertex in $S$, and $f(S)$ as the sum of all numbers in vertices of $N(S)$. Find the greatest common divisor of $f(S)$ for all possible non-empty subsets $S$ (assume that GCD of empty set is $0$).\n\nWu is too tired after his training to solve this problem. Help him!",
    "tutorial": "Let's split vertices of right half of graph in groups in such a way that group consists of vertices with same neighboring set. Then answer equals to $gcd$ of sums of numbers in all groups except the group with empty neighboring set. Let's prove it. If there are some vertices with same list of neighbors then they will both in some $N(S)$ or none of them will be in it. It means that we can replace such vertices with one vertex with value equals to sum of values in these vertices. After that numbers in all vertices are divisible by answer and thus sum of every subset is divisible by it. Let's divide all the numbers by answer and prove that after it answer will be 1. Consider some integer $k$ and we'll find some set of vertices $S$ such that $f(S)$ is not divisible by $k$. If sum of all numbers is not divisible by $k$ we can take all the left half and its sum is not divisible by $k$. Otherwise consider a vertex with minimum degree such that its value is not divisible by $k$ (such vertex exists because gcd of numbers in right half is 1 now). Let's take subset of vertices in left part which are not connected to $v$. Which vertices are not neighboring to this set? It is $v$ and all the vertices that their neighboring set it a subset of neighboring set of $v$ (and their sum is divisible by $k$). But value of $v$ is not divisible by $k$ so sum in complement of its neighboring set is not divisible by $k$ too.",
    "tags": [
      "graphs",
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1322",
    "index": "D",
    "title": "Reality Show",
    "statement": "A popular reality show is recruiting a new cast for the third season! $n$ candidates numbered from $1$ to $n$ have been interviewed. The candidate $i$ has aggressiveness level $l_i$, and recruiting this candidate will cost the show $s_i$ roubles.\n\nThe show host reviewes applications of all candidates from $i=1$ to $i=n$ by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate $i$ is strictly higher than that of any \\textbf{already accepted} candidates, then the candidate $i$ will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.\n\nThe show makes revenue as follows. For each aggressiveness level $v$ a corresponding profitability value $c_v$ is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant $i$ enters the stage, events proceed as follows:\n\n- The show makes $c_{l_i}$ roubles, where $l_i$ is initial aggressiveness level of the participant $i$.\n- If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is:\n\n- the defeated participant is hospitalized and leaves the show.\n- aggressiveness level of the victorious participant is increased by one, and the show makes $c_t$ roubles, where $t$ is the new aggressiveness level.\n\n- The fights continue until all participants on stage have distinct aggressiveness levels.\n\nIt is allowed to select an empty set of participants (to choose neither of the candidates).\n\nThe host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total $s_i$). Help the host to make the show as profitable as possible.",
    "tutorial": "First of all, we will notice that the order of entering doesn't affect the answer. Let's reverse the sequence. We will add people in the non-decreasing order. Let's use dynamic programming: $dp[i][k][cnt]$ is the answer if we processed first $i$ candidates with the maximum value less or equal $k$ and total number of people who will reach $l_j = k$ is $cnt \\leq n$. How we should change values of $dp$ when we go from $k$ to $k + 1$? $dp[i][k + 1][cnt / 2] \\leq dp[i][k][cnt] + (cnt / 2) \\cdot c_{k + 1}$ But how $dp$ changes when we take $i$-th element? $dp[i + 1][a_i][cnt] \\leq dp[i][a_i][cnt - 1] + s_i$ After adding $i$-th element we also should change $dp[i + 1][>a_i ]$. But every next lay will change less: $n + \\left \\lceil \\frac{n}{2} \\right \\rceil + \\left \\lceil \\frac{n}{4} \\right \\rceil + \\left \\lceil \\frac{n}{8} \\right \\rceil + \\ldots = O(n + m)$. It clear, that we can remove first parameter of $dp$ and finally get the asymptotics $O(n(n + m))$.",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1322",
    "index": "E",
    "title": "Median Mountain Range",
    "statement": "Berland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the \"Median mountain range\". This mountain range is $n$ mountain peaks, located on one straight line and numbered in order of $1$ to $n$. The height of the $i$-th mountain top is $a_i$.\n\n\"Median mountain range\" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from $2$ to $n - 1$ its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal $b_i$, then after the alignment new heights $a_i$ are as follows: $a_1 = b_1$, $a_n = b_n$ and for all $i$ from $2$ to $n - 1$ $a_i = median(b_{i-1}, b_i, b_{i+1})$. The median of three integers is the second largest number among them. For example, $median(5,1,2) = 2$, and $median(4,2,4) = 4$.\n\nRecently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of $c$ — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after $c$ alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!",
    "tutorial": "Let's assume that $1 \\le a_i \\le 2$. We can notice that if for some $i$ $a_i = a_{i + 1}$, than on $i$-th and $(i+1)$-th positions numbers will stay the same forever. So the only changes will happen to segments of consecutive alternating $1$ and $2$. Now let's look what will happen to such segments after first alignment of mountain peaks. The beginning and end of segment will stay the same, and all intermediate number will change ($1$ will change to $2$ and $2$ will change to $1$). So the second number will be equal to first and pre last number will be equal to last. That means that lengths of all segments of consecutive alternating $1$ and $2$ will decrease by $2$. So the number of alignments equals to length of longest segment divided by $2$, and for each segment its first half will be equal to beginning of segment, and its second half will be equal to the end of segment. Now let's fix some number $x$ and create array $b$, where $b_i = 1$ if $a_i < x$ and $b_i = 2$ if $a_i \\ge x$. It can be observed, that if we will make alignment with initial mountain heights and replace them with $1$ and $2$ the same way, we will get array $b$ after first alignment. So if we will get array $b$ after stabilization, we will know that on positions where $b_i = 1$ mountains will have height less than $x$, and on positions where $b_i = 2$ the mountain heights after stabilization will be grater or equal than $x$. So to get the number of alignments we will need to find the longest segment of consecutive alternating $1$ and $2$ for all possible $x$. Now we need to get the final heights. Let's assume that we know all positions where final heights will be grater than $x$. Let's create array $b$ the same way as described above. Using this array we can get positions where the mountain heights will be grater or equal than $x$ after stabilization. As we know positions where the heights will be grater than $x$, we can get positions where heights will be equal to $x$. So if we will decrease $x$ from maximum value to $1$, we can get the final heights of all mountains. To perform it quick enough, we can consider only those $x$, that equal to some of existing initial heights. Then we can decrease $x$ and in some set store all segments of consecutive alternating $1$ and $2$ in array $b$ for such $x$. When the $x$ is decreased, on some positions $1$ can change to $2$. The changes can happen only to the segments that have such positions. (The segments can be splited by this position, or this position can be merged with neighbouring segment(s)) So in total there will be $O(n)$ changes to segments, and we can perform all of them in $O(n \\log n)$ time. Also we can store in set all positions, for which we do not know the final heights, we for each new segment we can find positions where $1$ will be in the end (it will be some segment of consecutive positions) and search free positions among them in the set. In total it will take $O(n \\log n)$ time. There also exists solution in $O(n)$ time.",
    "tags": [
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1322",
    "index": "F",
    "title": "Assigning Fares",
    "statement": "Mayor of city M. decided to launch several new metro lines during 2020. Since the city has a very limited budget, it was decided not to dig new tunnels but to use the existing underground network.\n\nThe tunnel system of the city M. consists of $n$ metro stations. The stations are connected with $n - 1$ bidirectional tunnels. Between every two stations $v$ and $u$ there is exactly one simple path. Each metro line the mayor wants to create is a simple path between stations $a_i$ and $b_i$. Metro lines can intersects freely, that is, they can share common stations or even common tunnels. However, it's not yet decided which of two directions each line will go. More precisely, between the stations $a_i$ and $b_i$ the trains will go either from $a_i$ to $b_i$, or from $b_i$ to $a_i$, but not simultaneously.\n\nThe city $M$ uses complicated faring rules. Each station is assigned with a positive integer $c_i$ — the fare zone of the station. The cost of travel from $v$ to $u$ is defined as $c_u - c_v$ roubles. Of course, such travel only allowed in case there is a metro line, the trains on which go from $v$ to $u$. Mayor doesn't want to have any travels with a negative cost, so it was decided to assign directions of metro lines and station fare zones in such a way, that fare zones are strictly increasing during any travel on any metro line.\n\nMayor wants firstly assign each station a fare zone and then choose a lines direction, such that all fare zones are increasing along any line. In connection with the approaching celebration of the day of the city, the mayor wants to assign fare zones so that the maximum $c_i$ will be as low as possible. Please help mayor to design a new assignment or determine if it's impossible to do. Please note that you only need to assign the fare zones optimally, you don't need to print lines' directions. This way, you solution will be considered correct if there will be a way to assign directions of every metro line, so that the fare zones will be strictly increasing along any movement of the trains.",
    "tutorial": "Let's assume $c_v$ is the color of vertex v. So, we need to find a coloring of tree, where $c_v$ strictly increases along every path. First of all, if coloring exists, we can renumerate colors so that they will be in range [1, $n$]. Secondly, we can always revert our coloring, make $c_v \\rightarrow k + 1 - c_v$. Also, let's do binary search to find $k$. So, now we want to check if it is possible to paint tree using $k$ colors. Every path can be on of two directions. If we determine direction for path #0, then we also automatically determine direction for every path which has common edge with path #0. So, we can get a components of paths - if we choose one path direction, we choose every other paths direction. We can notice, that if a single component is not bipartite, answer is -1. So, for every path, we know it's component and it's orientation inside the component. It can be calculated using subtree sum - for vertexes $a$ and $b$ we make +1 for $a$, +1 for $b$, and -2 for $lca(a,\\,b)$. Let's make our tree rooted and then count dp on subtrees. $dp_v$ - minimal color of $v$, if all it's subtree is colored in a correct way and edge $v \\rightarrow parent_v$ goes from lower to higher color. How to calculate dp? If we fix $parent_v \\rightarrow v$ edge direction, for some edges $v \\rightarrow to$ we know the orientation. It happens when they were in same component as $parent_v \\rightarrow v$. For other components, we can or use $dp_{to}$ or $k + 1 - dp_{to}$ - depending on which direction of component we use. If we will try both variants and combine all the constraints, we will get two different segments $[l, r]$ and $[k + 1 - r, k + 1 - l]$, and $dp_v$ must be in one of them. It can be solved with scanline in $O(n \\log n)$ time. Now we can notice that $r = k + 1 - dp_{to}$. Let's think of segments as about two left constraints: $l_1$ and $l_2$. We have two sets $L$ and $R$. We either put $l_1 \\rightarrow L,\\ l_2 \\rightarrow R$ or $l_2 \\rightarrow L,\\ l_1 \\rightarrow R$. So, we want these conditions to be done: $\\begin{cases} \\max(L) \\le \\min(k - R) \\\\ \\max(L) \\rightarrow \\min \\end{cases} \\rightarrow \\begin{cases} \\max(L) + \\max(R) \\le k \\\\ \\max(L) \\rightarrow \\min \\end{cases}$ If we fix what is more - $\\max(R)$ or $\\max(L)$, we get fixed distribuition between $L$ and $R$ - max of $l_1$ and $l_2$ goes to max of two sets. Then we just need to check conditions and use best of variants. Solution will have complexity $O(n \\log n)$.",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1323",
    "index": "A",
    "title": "Even Subset Sum Problem",
    "statement": "You are given an array $a$ consisting of $n$ positive integers. Find a \\textbf{non-empty} subset of its elements such that their sum is \\textbf{even} (i.e. divisible by $2$) or determine that there is no such subset.\n\nBoth the given array and required subset may contain equal values.",
    "tutorial": "If there is an even element in array there is an answer consisting of only it. Otherwise if there is at least two odd elements in array there is an answer consisting of this two elements. Otherwise array is only one odd element and there is no answer.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1323",
    "index": "B",
    "title": "Count Subrectangles",
    "statement": "You are given an array $a$ of length $n$ and array $b$ of length $m$ both consisting of only integers $0$ and $1$. Consider a matrix $c$ of size $n \\times m$ formed by following rule: $c_{i, j} = a_i \\cdot b_j$ (i.e. $a_i$ multiplied by $b_j$). It's easy to see that $c$ consists of only zeroes and ones too.\n\nHow many subrectangles of size (area) $k$ consisting only of ones are there in $c$?\n\nA subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers $x_1, x_2, y_1, y_2$ ($1 \\le x_1 \\le x_2 \\le n$, $1 \\le y_1 \\le y_2 \\le m$) a subrectangle $c[x_1 \\dots x_2][y_1 \\dots y_2]$ is an intersection of the rows $x_1, x_1+1, x_1+2, \\dots, x_2$ and the columns $y_1, y_1+1, y_1+2, \\dots, y_2$.\n\nThe size (area) of a subrectangle is the total number of cells in it.",
    "tutorial": "Rectangle $[x1; x2][y1; y2]$ consists of only ones iff subsegment $[x1; x2]$ consists of only ones in $a$ and subsegment $[y1; y2]$ consists of only ones in $b$. Let's iterate over divisors of $k$. Let the current divisor be $p$ (i.e. $k = p \\cdot q$), so we are interested in number of subsegments consisting of ones of length $p$ in $a$ and number of subsegments consisting of ones of length $q$ in $b$. It's possible to precalculate number of segments consisting of ones in $a$ and $b$ of each length. Let's find all maximal subsegments consisting of ones in $a$ and $b$. Consider subsegment of length $l$. It adds $l - s + 1$ for amount of subsegments of length $s$.",
    "code": "#include <bits/stdc++.h>\n\nusing ll = long long;\nusing ld = long double;\nusing ull = unsigned long long;\n\nusing namespace std;\n\nvector<ll> gao(vector<int> a) {\n    int n = a.size();\n    vector<ll> res(n + 1);\n    int i = 0;\n    while (i < n) {\n        if (a[i] == 0) {\n            i++;\n            continue;\n        }\n\n        int j = i;\n        while (j < n && a[j] == 1) {\n            j++;\n        }\n        for (int len = 1; len <= j - i; len++) {\n            res[len] += j - i - len + 1;\n        }\n        i = j;\n    }\n\n    return res;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    int n, m;\n    ll k;\n    cin >> n >> m >> k;\n    vector<int> a(n);\n    vector<int> b(m);\n    for (int& x : a) {\n        cin >> x;\n    }\n    for (int& x : b) {\n        cin >> x;\n    }\n\n    ll ans = 0;\n\n    auto ga = gao(a);\n    auto gb = gao(b);\n    for (int i = 1; i < ga.size(); i++) {\n        if (k % i == 0 && k / i <= m) {\n            ans += ga[i] * gb[k / i];\n        }\n    }\n\n    cout << ans << \"\\n\";\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1324",
    "index": "A",
    "title": "Yet Another Tetris Problem",
    "statement": "You are given some Tetris field consisting of $n$ columns. The initial height of the $i$-th column of the field is $a_i$ blocks. On top of these columns you can place \\textbf{only} figures of size $2 \\times 1$ (i.e. the height of this figure is $2$ blocks and the width of this figure is $1$ block). Note that you \\textbf{cannot} rotate these figures.\n\nYour task is to say if you can clear the whole field by placing such figures.\n\nMore formally, the problem can be described like this:\n\nThe following process occurs while \\textbf{at least one $a_i$ is greater than $0$}:\n\n- You place one figure $2 \\times 1$ (choose some $i$ from $1$ to $n$ and replace $a_i$ with $a_i + 2$);\n- then, while all $a_i$ are greater than zero, replace each $a_i$ with $a_i - 1$.\n\nAnd your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The answer is \"YES\" only if all $a_i$ have the same parity (i.e. all $a_i$ are odd or all $a_i$ are even). That's because placing the block doesn't change the parity of the element and the $-1$ operation changes the parity of all elements in the array.",
    "code": "for i in range(int(input())):\n\tn = int(input())\n\tcnto = sum(list(map(lambda x: int(x) % 2, input().split())))\n\tprint('YES' if cnto == 0 or cnto == n else 'NO')",
    "tags": [
      "implementation",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1324",
    "index": "B",
    "title": "Yet Another Palindrome Problem",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nYour task is to determine if $a$ has some \\textbf{subsequence} of length at least $3$ that is a palindrome.\n\nRecall that an array $b$ is called a \\textbf{subsequence} of the array $a$ if $b$ can be obtained by removing some (possibly, zero) elements from $a$ (not necessarily consecutive) without changing the order of remaining elements. For example, $[2]$, $[1, 2, 1, 3]$ and $[2, 3]$ are subsequences of $[1, 2, 1, 3]$, but $[1, 1, 2]$ and $[4]$ are not.\n\nAlso, recall that a palindrome is an array that reads the same backward as forward. In other words, the array $a$ of length $n$ is the palindrome if $a_i = a_{n - i - 1}$ for all $i$ from $1$ to $n$. For example, arrays $[1234]$, $[1, 2, 1]$, $[1, 3, 2, 2, 3, 1]$ and $[10, 100, 10]$ are palindromes, but arrays $[1, 2]$ and $[1, 2, 3, 1]$ are not.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The first observation is that we can always try to find the palindrome of length $3$ (otherwise, we can remove some characters from the middle until its length becomes $3$). The second observation is that the palindrome of length $3$ is two equal characters and some other (maybe, the same) character between them. Now there are two ways: find the pair of equal non-adjacent characters in $O(n^2)$ or do it in $O(n)$ (for each character we only need to consider its left and right occurrences).",
    "code": "for i in range(int(input())):\n\tn = int(input())\n\ts = list(map(int, input().split()))\n\tok = False\n\tfor i in range(n):\n\t\tfor j in range(i + 2, n):\n\t\t\tif s[i] == s[j]: ok = True\n\tprint('YES' if ok else 'NO')",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1324",
    "index": "C",
    "title": "Frog Jumps",
    "statement": "There is a frog staying to the left of the string $s = s_1 s_2 \\ldots s_n$ consisting of $n$ characters (to be more precise, the frog initially stays at the cell $0$). Each character of $s$ is either 'L' or 'R'. It means that if the frog is staying at the $i$-th cell and the $i$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $i$-th cell and the $i$-th character is 'R', the frog can jump only to the right. \\textbf{The frog can jump only to the right from the cell $0$}.\n\n\\textbf{Note that the frog can jump into the same cell twice and can perform as many jumps as it needs}.\n\nThe frog wants to reach the $n+1$-th cell. The frog chooses some \\textbf{positive integer} value $d$ \\textbf{before the first jump} (and cannot change it later) and jumps by no more than $d$ cells at once. I.e. if the $i$-th character is 'L' then the frog can jump to any cell in a range $[max(0, i - d); i - 1]$, and if the $i$-th character is 'R' then the frog can jump to any cell in a range $[i + 1; min(n + 1; i + d)]$.\n\nThe frog doesn't want to jump far, so your task is to find the minimum possible value of $d$ such that the frog can reach the cell $n+1$ from the cell $0$ if it can jump by no more than $d$ cells at once. \\textbf{It is guaranteed that it is always possible to reach $n+1$ from $0$}.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The only observation we need is that we don't need to jump left at all. This only decreases our position so we have less freedom after the jump to the left. Then, to minimize $d$, we only need to jump between the closest 'R' cells. So, if we build the array $b = [0, r_1, r_2, \\dots, r_k, n + 1]$, where $r_i$ is the position of the $i$-th 'R' cell from left to right ($1$-indexed), then the answer is $\\max\\limits_{i=0}^{k} b_{i + 1} - b_i$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tstring s;\n\t\tcin >> s;\n\t\tvector<int> pos;\n\t\tpos.push_back(0);\n\t\tfor (int i = 0; i < int(s.size()); ++i) {\n\t\t\tif (s[i] == 'R') pos.push_back(i + 1);\n\t\t}\n\t\tpos.push_back(s.size() + 1);\n\t\tint ans = 0;\n\t\tfor (int i = 0; i < int(pos.size()) - 1; ++i) {\n\t\t\tans = max(ans, pos[i + 1] - pos[i]);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1324",
    "index": "D",
    "title": "Pair of Topics",
    "statement": "The next lecture in a high school requires two topics to be discussed. The $i$-th topic is interesting by $a_i$ units for the teacher and by $b_i$ units for the students.\n\nThe pair of topics $i$ and $j$ ($i < j$) is called \\textbf{good} if $a_i + a_j > b_i + b_j$ (i.e. it is more interesting for the teacher).\n\nYour task is to find the number of \\textbf{good} pairs of topics.",
    "tutorial": "Let's rewrite the inequality from $a_i + a_j > b_i + b_j$ to $(a_i - b_i) + (a_j - b_j) > 0$. This looks much simpler. Let's build the array $c$ where $c_i = a_i - b_i$ and sort this array. Now our problem is to find the number of pairs $i < j$ such that $c_i + c_j > 0$. Let's iterate over all elements of $c$ from left to right. For simplicity, we consider only \"greater\" summands. Because our sum ($c_i + c_j$) must be greater than $0$, then at least one of these summands will be positive. So, if $c_i \\le 0$, just skip it. Now $c_i > 0$ and we need to calculate the number of such $j$ that $c_i + c_j > 0$ and $j < i$. It means that each $c_j \\ge -c_i + 1$ (for some $j < i$) will be okay. Such leftmost position $j$ can be found with std::lower_bound or binary search. Then add the value $i-j$ to the answer and consider the next element. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tvector<int> a(n), b(n);\n\tfor (auto &it : a) cin >> it;\n\tfor (auto &it : b) cin >> it;\n\tvector<int> c(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tc[i] = a[i] - b[i];\n\t}\n\tsort(c.begin(), c.end());\n\t\n\tlong long ans = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (c[i] <= 0) continue;\n\t\tint pos = lower_bound(c.begin(), c.end(), -c[i] + 1) - c.begin();\n\t\tans += i - pos;\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1324",
    "index": "E",
    "title": "Sleeping Schedule",
    "statement": "Vova had a pretty weird sleeping schedule. There are $h$ hours in a day. Vova will sleep exactly $n$ times. The $i$-th time he will sleep exactly after $a_i$ hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is $0$). Each time Vova sleeps \\textbf{exactly one day} (in other words, $h$ hours).\n\nVova thinks that the $i$-th sleeping time is \\textbf{good} if he starts to sleep between hours $l$ and $r$ inclusive.\n\nVova can control himself and before the $i$-th time can choose between two options: go to sleep after $a_i$ hours or after $a_i - 1$ hours.\n\nYour task is to say the maximum number of \\textbf{good} sleeping times Vova can obtain if he acts optimally.",
    "tutorial": "This is a very standard dynamic programming problem. Let $dp_{i, j}$ be the maximum number of good sleeping times if Vova had a sleep $i$ times already and the number of times he goes to sleep earlier by one hour is exactly $j$. Then the value $\\max\\limits_{j=0}^{n} dp_{n, j}$ will be the answer. Initially, all $dp_{i, j} = -\\infty$ and $dp_{0, 0} = 0$. What about transitions? Let the current state of the dynamic programming be $dp_{i, j}$ and $s = \\sum\\limits_{k=0}^{i} a_k$. Then we can don't go to sleep earlier and make the first transition: $dp_{i + 1, j} = max(dp_{i + 1, j}, dp_{i, j} + |(s - j) \\% h \\in [l; r]|)$. The sign $\\%$ is modulo operation and the notation $|f|$ is the boolean result of the expression $f$ ($1$ if $f$ is true and $0$ otherwise). And the second transition if we go to sleep earlier: $dp_{i + 1, j + 1} = max(dp_{i + 1, j + 1}, dp_{i, j} + |(s - j - 1) \\% h \\in [l; r]|)$. Don't forget to don't make transitions from unreachable states. Time complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool in(int x, int l, int r) {\n\treturn l <= x && x <= r;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, h, l, r;\n\tcin >> n >> h >> l >> r;\n\tvector<int> a(n);\n\tfor (auto &it : a) cin >> it;\n\tvector<vector<int>> dp(n + 1, vector<int>(n + 1, INT_MIN));\n\tdp[0][0] = 0;\n\tint sum = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tsum += a[i];\n\t\tfor (int j = 0; j <= n; ++j) {\n\t\t\tdp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + in((sum - j) % h, l, r));\n\t\t\tif (j < n) dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + in((sum - j - 1) % h, l, r));\n\t\t}\n\t}\n\t\n\tcout << *max_element(dp[n].begin(), dp[n].end()) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1324",
    "index": "F",
    "title": "Maximum White Subtree",
    "statement": "You are given a tree consisting of $n$ vertices. A tree is a connected undirected graph with $n-1$ edges. Each vertex $v$ of this tree has a color assigned to it ($a_v = 1$ if the vertex $v$ is white and $0$ if the vertex $v$ is black).\n\nYou have to solve the following problem for each vertex $v$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that \\textbf{contains} the vertex $v$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $cnt_w$ white vertices and $cnt_b$ black vertices, you have to maximize $cnt_w - cnt_b$.",
    "tutorial": "This problem is about the \"rerooting\" technique. Firstly, let's calculate the answer for some fixed root. How can we do this? Let $dp_v$ be the maximum possible difference between the number of white and black vertices in some subtree of $v$ (yes, the subtree of the rooted tree, i.e. $v$ and all its direct and indirect children) that contains the vertex $v$. We can calculate this dynamic programming by simple dfs, for the vertex $v$ it will look like this: $dp_v = a_v + \\sum\\limits_{to \\in children(v)} max(0, dp_{to})$. Okay, we can store the answer for the root somewhere. What's next? Let's try to change the root from the vertex $v$ to some adjacent to it vertex $to$. Which states of dynamic programming will change? Only $dp_v$ and $dp_{to}$. Firstly, we need to \"remove\" the child $to$ from the subtree of the vertex $v$: $dp_v = dp_v - max(0, dp_{to})$. Then we need to \"attach\" the vertex $v$ and make it a child of the vertex $to$: $dp_{to} = dp_{to} + max(0, dp_v)$. Then we need to run this process recursively from $to$ (store the answer, reroot the tree and so on) and when it ends we need to \"rollback\" our changes. Now $v$ is the root again and we can try the next child of $v$ as the root. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> a;\nvector<int> dp;\nvector<int> ans;\nvector<vector<int>> g;\n\nvoid dfs(int v, int p = -1) {\n\tdp[v] = a[v];\n\tfor (auto to : g[v]) {\n\t\tif (to == p) continue;\n\t\tdfs(to, v);\n\t\tdp[v] += max(dp[to], 0);\n\t}\n}\n\nvoid dfs2(int v, int p = -1) {\n\tans[v] = dp[v];\n\tfor (auto to : g[v]) {\n\t\tif (to == p) continue;\n\t\tdp[v] -= max(0, dp[to]);\n\t\tdp[to] += max(0, dp[v]);\n\t\tdfs2(to, v);\n\t\tdp[to] -= max(0, dp[v]);\n\t\tdp[v] += max(0, dp[to]);\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\ta = dp = ans = vector<int>(n);\n\tg = vector<vector<int>>(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\tif (a[i] == 0) a[i] = -1;\n\t}\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\t\n\tdfs(0);\n\tdfs2(0);\n\tfor (auto it : ans) cout << it << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1325",
    "index": "A",
    "title": "EhAb AnD gCd",
    "statement": "You are given a positive integer $x$. Find \\textbf{any} such $2$ positive integers $a$ and $b$ such that $GCD(a,b)+LCM(a,b)=x$.\n\nAs a reminder, $GCD(a,b)$ is the greatest integer that divides both $a$ and $b$. Similarly, $LCM(a,b)$ is the smallest integer such that both $a$ and $b$ divide it.\n\nIt's guaranteed that the solution always exists. If there are several such pairs $(a, b)$, you can output any of them.",
    "tutorial": "$a=1$ and $b=x-1$ always work.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint main()\\n{\\n    int t;\\n    scanf(\\\"%d\\\",&t);\\n    while (t--)\\n    {\\n    \\tint x;\\n    \\tscanf(\\\"%d\\\",&x);\\n    \\tprintf(\\\"1 %d\\\\n\\\",x-1);\\n    }\\n}\"",
    "tags": [
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1325",
    "index": "B",
    "title": "CopyCopyCopyCopyCopy",
    "statement": "Ehab has an array $a$ of length $n$. He has just enough free time to make a new array consisting of $n$ copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?\n\nA sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.",
    "tutorial": "Let the number of distinct elements in $a$ be called $d$. Clearly, the answer is limited by $d$. Now, you can construct your subsequence as follows: take the smallest element from the first copy, the second smallest element from the second copy, and so on. Since there are enough copies to take every element, the answer is $d$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint main()\\n{\\n    int t;\\n    scanf(\\\"%d\\\",&t);\\n    while (t--)\\n    {\\n    \\tint n;\\n    \\tscanf(\\\"%d\\\",&n);\\n    \\tset<int> s;\\n    \\twhile (n--)\\n    \\t{\\n    \\t\\tint a;\\n    \\t\\tscanf(\\\"%d\\\",&a);\\n    \\t\\ts.insert(a);\\n    \\t}\\n    \\tprintf(\\\"%d\\\\n\\\",s.size());\\n    }\\n}\"",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1325",
    "index": "C",
    "title": "Ehab and Path-etic MEXs",
    "statement": "You are given a tree consisting of $n$ nodes. You want to write some labels on the tree's edges such that the following conditions hold:\n\n- Every label is an integer between $0$ and $n-2$ inclusive.\n- All the written labels are distinct.\n- The largest value among $MEX(u,v)$ over all pairs of nodes $(u,v)$ is as small as possible.\n\nHere, $MEX(u,v)$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $u$ to node $v$.",
    "tutorial": "Notice that there will be a path that passes through the edge labeled $0$ and the edge labeled $1$ no matter how you label the edges, so there's always a path with $MEX$ $2$ or more. If any node has degree 3 or more, you can distribute the labels $0$, $1$, and $2$ to edges incident to this node and distribute the rest of the labels arbitrarily. Otherwise, the tree is a bamboo, and it doesn't actually matter how you label the edges, since there will be a path with $MEX$ $n-1$ anyway.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nvector<int> v[100005];\\nint ans[100005];\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tint a,b;\\n\\t\\tscanf(\\\"%d%d\\\",&a,&b);\\n\\t\\tv[a].push_back(i);\\n\\t\\tv[b].push_back(i);\\n\\t\\tans[i]=-1;\\n\\t}\\n\\tpair<int,int> mx(0,0);\\n\\tfor (int i=1;i<=n;i++)\\n\\tmx=max(mx,make_pair((int)v[i].size(),i));\\n\\tint cur=0;\\n\\tfor (int i:v[mx.second])\\n\\tans[i]=cur++;\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tif (ans[i]==-1)\\n\\t\\tans[i]=cur++;\\n\\t\\tprintf(\\\"%d\\\\n\\\",ans[i]);\\n\\t}\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1325",
    "index": "D",
    "title": "Ehab the Xorcist",
    "statement": "Given 2 integers $u$ and $v$, find the shortest array such that bitwise-xor of its elements is $u$, and the sum of its elements is $v$.",
    "tutorial": "First, let's look at some special cases. If $u>v$ or $u$ and $v$ have different parities, there's no array. If $u=v=0$, the answer is an empty array. If $u=v \\neq 0$, the answer is $[u]$. Now, the length is at least 2. Let $x=\\frac{v-u}{2}$. The array $[u,x,x]$ satisfies the conditions, so the length is at most 3. We just need to figure out whether there's a pair of number $a$ and $b$. Such that $a \\oplus b=u$ and $a+b=v$. Notice that $a+b=a \\oplus b+2*(a$&$b)$, so we know that $a$&$b=\\frac{v-u}{2}=x$ (surprise surprise.) The benefit of getting rid of $a+b$ and looking at $a$&$b$ instead is that we can look at $a$ and $b$ bit by bit. If $x$ has a one in some bit, $a$ and $b$ must both have ones, so $a \\oplus b=u$ must have a 0. If $x$ has a zero, there are absolutely no limitation on $u$. So, if there's a bit where both $x$ and $u$ have a one, that is to say if $x$&$u\\neq0$, you can't find such $a$ and $b$, and the length will be 3. Otherwise, $x$&$u=0$ which means $x \\oplus u=x+u$, so the array $[u+x,x]$ works. Can you see how this array was constructed? We took $[u,x,x]$ which more obviously works and merged the first 2 elements, benefiting from the fact that $u$&$x=0$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint main()\\n{\\n\\tlong long u,v;\\n\\tscanf(\\\"%I64d%I64d\\\",&u,&v);\\n\\tif (u%2!=v%2 || u>v)\\n\\t{\\n\\t\\tprintf(\\\"-1\\\");\\n\\t\\treturn 0;\\n\\t}\\n\\tif (u==v)\\n\\t{\\n\\t\\tif (!u)\\n\\t\\tprintf(\\\"0\\\");\\n\\t\\telse\\n\\t\\tprintf(\\\"1\\\\n%I64d\\\",u);\\n\\t\\treturn 0;\\n\\t}\\n\\tlong long x=(v-u)/2;\\n\\tif (u&x)\\n\\tprintf(\\\"3\\\\n%I64d %I64d %I64d\\\",u,x,x);\\n\\telse\\n\\tprintf(\\\"2\\\\n%I64d %I64d\\\",(u^x),x);\\n}\"",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1325",
    "index": "E",
    "title": "Ehab's REAL Number Theory Problem",
    "statement": "You are given an array $a$ of length $n$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.\n\nA sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "Notice that for each element in the array, if some perfect square divides it, you can divide it by that perfect square, and the problem won't change. Let's define normalizing a number as dividing it by perfect squares until it doesn't contain any. Notice than any number that has 3 different prime divisors has at least 8 divisors, so after normalizing any element in the array, it will be $1$, $p$, or $p*q$ for some primes $p$ and $q$. Let's create a graph where the vertices are the prime numbers (and $1$,) and the edges are the elements of the array. For each element, we'll connect $p$ and $q$ (or $p$ and $1$ if it's a prime after normalizing, or $1$ with $1$ if it's $1$ after normalizing.) What's the significance of this graph? Well, if you take any walk from node $p$ to node $q$, multiply the elements on the edges you took, and normalize, the product you get will be $p*q$! That's because every node in the path will be visited an even number of times, except $p$ and $q$. So the shortest subsequence whose product is a perfect square is just the shortest cycle in this graph! The shortest cycle in an arbitrary graph takes $O(n^2)$ to compute: you take every node as a source and calculate the bfs tree, then you look at the edges the go back to the root to close the cycle. That only finds the shortest cycle if the bfs source is contained in one. The graph in this problem has a special condition: you can't connect 2 nodes with indices greater than $sqrt(maxAi)$. That's because their product would be greater than $maxAi$. So that means ANY walk in this graph has a node with index $\\le\\sqrt{maxAi}$. You can only try these nodes as sources for your bfs.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define MX 1000000\\nint lp[MX+5],dist[MX+5];\\nvector<int> d[MX+5],v[MX+5],pr;\\nvector<vector<int> > e;\\nint main()\\n{\\n    pr.push_back(1);\\n\\tfor (int i=2;i<=MX;i++)\\n\\t{\\n\\t\\tif (!lp[i])\\n\\t\\t{\\n\\t\\t    pr.push_back(i);\\n\\t\\t\\tfor (int j=i;j<=MX;j+=i)\\n\\t\\t\\tlp[j]=i;\\n\\t\\t}\\n\\t\\td[i]=d[i/lp[i]];\\n\\t\\tauto it=find(d[i].begin(),d[i].end(),lp[i]);\\n\\t\\tif (it!=d[i].end())\\n\\t\\td[i].erase(it);\\n\\t\\telse\\n\\t\\td[i].push_back(lp[i]);\\n\\t}\\n\\tint n,ans=1e9;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=0;i<n;i++)\\n\\t{\\n\\t\\tint a;\\n\\t\\tscanf(\\\"%d\\\",&a);\\n\\t\\tif (d[a].empty())\\n\\t\\t{\\n\\t\\t\\tprintf(\\\"1\\\");\\n\\t\\t\\treturn 0;\\n\\t\\t}\\n\\t\\tif (d[a].size()==1)\\n\\t\\td[a].push_back(1);\\n\\t\\te.push_back({d[a][0],d[a][1]});\\n\\t\\tv[d[a][0]].push_back(i);\\n\\t\\tv[d[a][1]].push_back(i);\\n\\t}\\n\\tfor (int i:pr)\\n\\t{\\n\\t    if (i*i>MX)\\n\\t    break;\\n\\t    for (int j:pr)\\n\\t    dist[j]=0;\\n\\t\\tqueue<pair<int,int> > q;\\n\\t\\tfor (int j:v[i])\\n\\t\\t{\\n\\t\\t\\tq.push({j,(e[j][0]==i)});\\n\\t\\t\\tdist[e[j][0]^e[j][1]^i]=1;\\n\\t\\t}\\n\\t\\twhile (!q.empty())\\n\\t\\t{\\n\\t\\t\\tauto p=q.front();\\n\\t\\t\\tq.pop();\\n\\t\\t\\tint node=e[p.first][p.second];\\n\\t\\t\\tfor (int u:v[node])\\n\\t\\t\\t{\\n\\t\\t\\t\\tif (u!=p.first)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tpair<int,int> np(u,(e[u][0]==node));\\n\\t\\t\\t\\t\\tint nnode=e[np.first][np.second];\\n\\t\\t\\t\\t\\tif (!dist[nnode] && nnode!=i)\\n\\t\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\t\\tq.push(np);\\n\\t\\t\\t\\t\\t\\tdist[nnode]=dist[node]+1;\\n\\t\\t\\t\\t\\t}\\n\\t\\t\\t\\t\\telse\\n\\t\\t\\t\\t\\tans=min(ans,dist[node]+dist[nnode]+1);\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\tif (ans==1e9)\\n\\tans=-1;\\n\\tprintf(\\\"%d\\\",ans);\\n}\"",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "number theory",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1325",
    "index": "F",
    "title": "Ehab's Last Theorem",
    "statement": "It's the year 5555. You have a graph, and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.\n\nGiven a connected graph with $n$ vertices, you can choose to either:\n\n- find an independent set that has \\textbf{exactly} $\\lceil\\sqrt{n}\\rceil$ vertices.\n- find a \\textbf{simple} cycle of length \\textbf{at least} $\\lceil\\sqrt{n}\\rceil$.\n\nAn independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.",
    "tutorial": "Let $sq$ denote $\\lceil\\sqrt{n}\\rceil$. If you're not familiar with back-edges, I recommend reading this first. Let's take the DFS tree of our graph. Assume you're currently in node $u$ in the DFS. If $u$ has $sq-1$ or more back-edges, look at the one that connects $u$ to its furthest ancestor. It forms a cycle of length at least $sq$. If $u$ doesn't have that many back-edges, you can add it to the independent set (if none of its neighbors was added.) That way, if you don't find a cycle, every node only blocks at most $sq-1$ other nodes, the ones connected to it by a back-edge, so you'll find an independent set! There's a pretty obvious greedy algorithm for finding large independent sets: take the node with the minimal degree, add it to the independent set, remove it and all its neighbors from the graph, and repeat. If at every step the node with the minimal degree has degree $<sq-1$, that algorithm solves the first problem. Otherwise, there's a step where EVERY node has degree at least $sq-1$. For graphs where every node has degree at least $d$, you can always find a cycle with length $d+1$. To do that, we'll first try to find a long path then close a cycle. Take an arbitrary node as a starting point, and keep trying to extend your path. If one of this node's neighbors is not already in the path, extend that path with it and repeat. Otherwise, all of the last node's $d$ neighbors are on the path. Take the edge to the furthest and you'll form a cycle of length at least $d+1$!",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nset<pair<int,int> > s;\\nvector<int> v[100005];\\nbool del[100005];\\nint deg[100005],occ[100005];\\nvoid remove(int node)\\n{\\n    if (del[node])\\n    return;\\n\\ts.erase({deg[node],node});\\n\\tdel[node]=1;\\n\\tfor (int u:v[node])\\n\\t{\\n\\t\\tif (!del[u])\\n\\t\\t{\\n\\t\\t\\ts.erase({deg[u],u});\\n\\t\\t\\tdeg[u]--;\\n\\t\\t\\ts.insert({deg[u],u});\\n\\t\\t}\\n\\t}\\n}\\nint main()\\n{\\n\\tint n,m,sq=1;\\n\\tscanf(\\\"%d%d\\\",&n,&m);\\n\\twhile (sq*sq<n)\\n\\tsq++;\\n\\twhile (m--)\\n\\t{\\n\\t\\tint a,b;\\n\\t\\tscanf(\\\"%d%d\\\",&a,&b);\\n\\t\\tv[a].push_back(b);\\n\\t\\tv[b].push_back(a);\\n\\t\\tdeg[a]++;\\n\\t\\tdeg[b]++;\\n\\t}\\n\\tfor (int i=1;i<=n;i++)\\n\\ts.insert({deg[i],i});\\n\\tvector<int> ans;\\n\\twhile (!s.empty())\\n\\t{\\n\\t\\tauto p=*s.begin();\\n\\t\\ts.erase(s.begin());\\n\\t\\tif (p.first+1>=sq)\\n\\t\\t{\\n\\t\\t\\tprintf(\\\"2\\\\n\\\");\\n\\t\\t\\tvector<int> d({p.second});\\n\\t\\t\\tocc[p.second]=1;\\n\\t\\t\\twhile (1)\\n\\t\\t\\t{\\n\\t\\t\\t\\tpair<int,int> nex(1e9,0);\\n\\t\\t\\t\\tfor (int u:v[d.back()])\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tif (!del[u])\\n\\t\\t\\t\\t\\tnex=min(nex,make_pair(occ[u],u));\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\tif (nex.first)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tprintf(\\\"%d\\\\n\\\",(int)d.size()-nex.first+1);\\n\\t\\t\\t\\t\\tfor (int i=nex.first-1;i<d.size();i++)\\n\\t\\t\\t\\t\\tprintf(\\\"%d \\\",d[i]);\\n\\t\\t\\t\\t\\treturn 0;\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\td.push_back(nex.second);\\n\\t\\t\\t\\tocc[nex.second]=d.size();\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tans.push_back(p.second);\\n\\t\\tremove(p.second);\\n\\t\\tfor (int u:v[p.second])\\n\\t\\tremove(u);\\n\\t}\\n\\tprintf(\\\"1\\\\n\\\");\\n\\tfor (int i=0;i<sq;i++)\\n\\tprintf(\\\"%d \\\",ans[i]);\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1326",
    "index": "A",
    "title": "Bad Ugly Numbers",
    "statement": "You are given a integer $n$ ($n > 0$). Find \\textbf{any} integer $s$ which satisfies these conditions, or report that there are no such numbers:\n\nIn the decimal representation of $s$:\n\n- $s > 0$,\n- $s$ consists of $n$ digits,\n- no digit in $s$ equals $0$,\n- $s$ is not divisible by any of it's digits.",
    "tutorial": "If $n = 1$, no solution exists. Otherwise, if $n \\geq 2$, the number $\\overline{2 3 3 \\ldots 3}$ ($n$ digits) satisfies all conditions, because it is not divisible by $2$ and $3$.",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1326",
    "index": "B",
    "title": "Maximums",
    "statement": "Alicia has an array, $a_1, a_2, \\ldots, a_n$, of non-negative integers. For each $1 \\leq i \\leq n$, she has found a non-negative integer $x_i = max(0, a_1, \\ldots, a_{i-1})$. Note that for $i=1$, $x_i = 0$.\n\nFor example, if Alicia had the array $a = \\{0, 1, 2, 0, 3\\}$, then $x = \\{0, 0, 1, 2, 2\\}$.\n\nThen, she calculated an array, $b_1, b_2, \\ldots, b_n$: $b_i = a_i - x_i$.\n\nFor example, if Alicia had the array $a = \\{0, 1, 2, 0, 3\\}$, $b = \\{0-0, 1-0, 2-1, 0-2, 3-2\\} = \\{0, 1, 1, -2, 1\\}$.\n\nAlicia gives you the values $b_1, b_2, \\ldots, b_n$ and asks you to restore the values $a_1, a_2, \\ldots, a_n$. Can you help her solve the problem?",
    "tutorial": "Let's restore $a_1, a_2, \\ldots, a_n$ from left to right. $a_1 = b_1$. For $i>1$, $x_i = \\max({a_1, \\ldots, a_{i-1}})$, so we can maintain the maximum of previous elements and get the value of $x_i$. Using this value, we can restore $a_i$ as $b_i + x_i$.",
    "code": "\"#include <cmath>\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n#include <unordered_map>\\n#include <unordered_set>\\n#include <iomanip>\\n#include <bitset>\\n#include <sstream>\\n#include <chrono>\\n#include <cstring>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\n\\n#ifdef iq\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nint main() {\\n#ifdef iq\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  int n;\\n  cin >> n;\\n  vector <int> a(n);\\n  int x = 0;\\n  for (int i = 0; i < n; i++) {\\n    cin >> a[i];\\n    a[i] += x;\\n    x = max(x, a[i]);\\n    cout << a[i] << ' ';\\n  }\\n}\"",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1326",
    "index": "C",
    "title": "Permutation Partitions",
    "statement": "You are given a permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$ and an integer $k$, such that $1 \\leq k \\leq n$. A permutation means that every number from $1$ to $n$ is contained in $p$ exactly once.\n\nLet's consider all partitions of this permutation into $k$ disjoint segments. Formally, a partition is a set of segments $\\{[l_1, r_1], [l_2, r_2], \\ldots, [l_k, r_k]\\}$, such that:\n\n- $1 \\leq l_i \\leq r_i \\leq n$ for all $1 \\leq i \\leq k$;\n- For all $1 \\leq j \\leq n$ there exists \\textbf{exactly one} segment $[l_i, r_i]$, such that $l_i \\leq j \\leq r_i$.\n\nTwo partitions are different if there exists a segment that lies in one partition but not the other.\n\nLet's calculate the partition value, defined as $\\sum\\limits_{i=1}^{k} {\\max\\limits_{l_i \\leq j \\leq r_i} {p_j}}$, for all possible partitions of the permutation into $k$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $998\\,244\\,353$.",
    "tutorial": "Note that the maximum possible partition value is equal to $(n - k + 1) + \\ldots + (n - 1) + n$. Let's define $a_1, a_2, \\ldots, a_k$ as positions of the numbers $(n-k+1), \\ldots, n$ in the increasing order ($a_1 < a_2 < \\ldots < a_k$). The number of partitions with the maximum possible value is equal to $\\prod\\limits_{i=1}^{k-1} {(a_{i+1}-a_i)}$. This is true because if we have the maximum possible value, each of the segments in a partition should contain exactly one of the values $(n-k+1), \\ldots, n$, and thus, one of the positions $a_1, a_2, \\ldots, a_k$. So, between each pair of neighboring positions, we should choose exactly one of the borders of the segments in the partition. There are $(a_{i+1}-a_i)$ ways to do this.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nconst int MOD = 998244353;\\n\\nint n, k, a;\\n\\nint main()\\n{\\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\\n    cin >> n >> k;\\n    int p = -1;\\n    int ans = 1;\\n    long long sum = 0;\\n    for (int i = 0; i < n; i++)\\n    {\\n        cin >> a;\\n        if (a >= n - k + 1)\\n        {\\n            if (p != -1)\\n                ans = 1LL * ans * (i - p) % MOD;\\n            sum += a;\\n            p = i;\\n        }\\n    }\\n    cout << sum << \\\" \\\" << ans << \\\"\\\\n\\\";\\n    return 0;\\n}\"",
    "tags": [
      "combinatorics",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1326",
    "index": "D2",
    "title": "Prefix-Suffix Palindrome (Hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.}\n\nYou are given a string $s$, consisting of lowercase English letters. Find the longest string, $t$, which satisfies the following conditions:\n\n- The length of $t$ does not exceed the length of $s$.\n- $t$ is a palindrome.\n- There exists two strings $a$ and $b$ (possibly empty), such that $t = a + b$ ( \"$+$\" represents concatenation), and $a$ is prefix of $s$ while $b$ is suffix of $s$.",
    "tutorial": "Each possible string $t$ can be modeled as $s[1..l] + s[(n-r+1)..n]$ for some numbers $l,r$ such that $0 \\leq l, r$ and $l + r \\leq n$. Let's find the maximum integer $0 \\leq k \\leq \\lfloor \\frac{n}{2} \\rfloor$ such that $s_1 = s_n, s_2 = s_{n-1}, \\ldots, s_k = s_{n-k+1}$. In some optimal solution, where $t$ is as long as possible, $\\min{(l, r)} = k$. This is because if $\\min{(l, r)} < k$, we can increase $l$ or $r$ by $1$ and decrease the other variable by $1$ (if needed), and the string will be still a palindrome. So if we know that $\\min{(l, r)} = k$, we just need to find the longest palindrome $w$ that is a prefix or suffix of the string $s[(k+1)..(n-k)]$. After that, the answer will be $s[1..k] + w + s[(n-k+1)..n]$. In order to find the longest palindrome which is a prefix of some string, $a$, let's find $p$ from the prefix function of the string $a +$ '#' $+ \\overline{a}$, where $\\overline{a}$ represents the reverse of $a$. The string $a[1..p]$ will be the longest palindrome which is a prefix of $a$. After that, we can repeat this process for $\\overline{a}$ to find the longest palindrome which is a suffix of the string. Time complexity: $O(|s|)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nconst int M = (int)(2e6 + 239);\\n\\nint pref[M], c;\\n\\nstring solve_palindrome(const string& s)\\n{\\n    string a = s;\\n    reverse(a.begin(), a.end());\\n    a = s + \\\"#\\\" + a;\\n    c = 0;\\n    for (int i = 1; i < (int)a.size(); i++)\\n    {\\n        while (c != 0 && a[c] != a[i])\\n            c = pref[c - 1];\\n        if (a[c] == a[i])\\n            c++;\\n        pref[i] = c;\\n    }\\n    return s.substr(0, c);\\n}\\n\\nvoid solve()\\n{\\n    string t;\\n    cin >> t;\\n    int l = 0;\\n    while (l < (int)t.size() - l - 1)\\n    {\\n        if (t[l] != t[(int)t.size() - l - 1])\\n            break;\\n        l++;\\n    }\\n    if (l > 0)\\n        cout << t.substr(0, l);\\n    if ((int)t.size() > 2 * l)\\n    {\\n        string s = t.substr(l, (int)t.size() - 2 * l);\\n        string a = solve_palindrome(s);\\n        reverse(s.begin(), s.end());\\n        string b = solve_palindrome(s);\\n        if ((int)a.size() < (int)b.size())\\n            swap(a, b);\\n        cout << a;\\n    }\\n    if (l > 0)\\n        cout << t.substr((int)t.size() - l, l);\\n    cout << \\\"\\\\n\\\";\\n}\\n\\nint main()\\n{\\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\\n    int t;\\n    cin >> t;\\n    while (t--)\\n        solve();\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "greedy",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1326",
    "index": "E",
    "title": "Bombs",
    "statement": "You are given a permutation, $p_1, p_2, \\ldots, p_n$.\n\nImagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb.\n\nFor some fixed configuration of bombs, consider the following process. Initially, there is an empty set, $A$.\n\nFor each $i$ from $1$ to $n$:\n\n- Add $p_i$ to $A$.\n- If the $i$-th position contains a bomb, remove the largest element in $A$.\n\nAfter the process is completed, $A$ will be non-empty. The cost of the configuration of bombs equals the largest element in $A$.\n\nYou are given another permutation, $q_1, q_2, \\ldots, q_n$.\n\nFor each $1 \\leq i \\leq n$, find the cost of a configuration of bombs such that there exists a bomb in positions $q_1, q_2, \\ldots, q_{i-1}$.\n\nFor example, for $i=1$, you need to find the cost of a configuration without bombs, and for $i=n$, you need to find the cost of a configuration with bombs in positions $q_1, q_2, \\ldots, q_{n-1}$.",
    "tutorial": "Let's come up with some criteria that answer is $< x$. We claim that the answer is $< x$ if: There is at least one bomb after the rightmost value $\\geq x$. There are at least two bombs after the next rightmost value $\\geq x$.... ... There are at least $k$ bombs after the $k$-th rightmost value $\\geq x$. Let $ans_i$ be the answer for bombs $q_1, q_2, \\ldots, q_{i-1}$. Then, $ans_i \\geq ans_{i+1}$. Let's add new bombs starting from $ans_{i-1}$, and while the actual answer is smaller than the current answer, decrease the actual answer. To do this quickly, we'll use a segment tree. In the segment tree, let's store $b_i =$ (number of values $\\geq x$ on suffix $i \\ldots n$) $-$ (number of bombs on this suffix). Then, the real answer is $< x$ if $b_i \\leq 0$ for all $i$. Using range addition updates and max queries, we can update $b$ and decrease the answer quickly. The total complexity is $\\mathcal{O}{(n \\log n)}$. Bonus: is it possible to solve the problem in $\\mathcal{O}{(n)}$?",
    "tags": [
      "data structures",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1326",
    "index": "F2",
    "title": "Wise Men (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved.}\n\n$n$ wise men live in a beautiful city. Some of them know each other.\n\nFor each of the $n!$ possible permutations $p_1, p_2, \\ldots, p_n$ of the wise men, let's generate a binary string of length $n-1$: for each $1 \\leq i < n$ set $s_i=1$ if $p_i$ and $p_{i+1}$ know each other, and $s_i=0$ otherwise.\n\nFor all possible $2^{n-1}$ binary strings, find the number of permutations that produce this binary string.",
    "tutorial": "For each binary string $s$, let's calculate $f(s)$ - the number of permutations, such that, if $s_i=1$, then $p_i$ and $p_{i+1}$ know each other, otherwise, they may know or don't know each other. To get real answers, we may use inclusion-exclusion, which may be optimized using a straightforward sum over subsets dp. To calculate $f(s)$, we need to note that $f$ depends only on the multiset of lengths of blocks of $1$'s in it. For example, $f(110111) = f(111011)$, because the multiset of lengths is $\\{1, 3, 4\\}$ (note that block of size $x$ of $1$'s corresponds to length $x+1$). And note that there are exactly $P(n)$ (the number of partitions of $n$) possible multisets. $P(18) = 385$ To process further, at first let's calculate $g_{len, mask}$ - the number of paths of length $len$, which pass only through the vertices from $mask$ (and only through them). You can calculate it with a straightforward $dp_{mask, v}$ in $\\mathcal{O}{(2^n \\cdot n^2)}$. Then, let's fix the multiset of lengths $a_1, a_2, \\ldots, a_k$. I claim that the $f(s)$ for this multiset is equal to $\\sum{\\prod{g_{a_i, m_i}}}$ over all masks $m_1, m_2, \\ldots m_k$, such that the bitwise OR of $m_1, m_2, \\ldots, m_k$ is equal to $2^n-1$ (note that we don't care about the number of bits like in a usual non-intersecting subsets convolution, because if some masks are intersecting, then their OR won't be equal to $2^n-1$ because $\\sum{a_i} = n$). You can calculate this sum by changing $g_{len}$ to the sum over subsets. And then, for this partition, you can just calculate $d_{mask} = \\prod{g_{a_i, mask}}$ in $\\mathcal{O}{(k \\cdot 2^n)}$, and you can restore the real value of $2^n-1$ by inclusion-exclusion in $\\mathcal{O}{(2^n)}$. If you will calculate this naively, you will get the $\\mathcal{O}$((sum of sizes of all partitions) $\\cdot 2^n)$ solution, which is enough to get AC. But you can optimize this because you can maintain $d_{mask}$ during the brute force of all partitions. And in the tree of all partitions, there are $\\mathcal{O}{(P(n))}$ intermediate vertices, so it will work in $\\mathcal{O}{(P(n) \\cdot 2^n)}$. The total complexity is $\\mathcal{O}{((P(n) + n^2) \\cdot 2^n))}$.",
    "code": "\"#include <cmath>\\n#include <functional>\\n#include <iostream>\\n#include <vector>\\n#include <algorithm>\\n#include <string>\\n#include <set>\\n#include <map>\\n#include <list>\\n#include <time.h>\\n#include <math.h>\\n#include <random>\\n#include <deque>\\n#include <queue>\\n#include <cassert>\\n#include <unordered_map>\\n#include <unordered_set>\\n#include <iomanip>\\n#include <bitset>\\n#include <sstream>\\n#include <chrono>\\n#include <cstring>\\n\\nusing namespace std;\\n\\ntypedef unsigned long long ll;\\n\\n#ifdef iq\\n  mt19937 rnd(228);\\n#else\\n  mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\\n#endif\\n\\nconst int N = 19;\\n\\nint g[N];\\nll dp[1 << N][N+1];\\nll ok[1 << N];\\n\\nll slen[N+1][1 << N];\\n\\nll cur[N+1][1 << N];\\nll val[1 << N];\\n\\nll ans[1 << N];\\n\\nint main() {\\n#ifdef iq\\n  freopen(\\\"a.in\\\", \\\"r\\\", stdin);\\n#endif\\n  ios::sync_with_stdio(0);\\n  cin.tie(0);\\n  int n;\\n  cin >> n;\\n  for (int i = 0; i < n; i++) {\\n    for (int j = 0; j < n; j++) {\\n      char c;\\n      cin >> c;\\n      if (c == '1') {\\n        g[i] |= (1 << j);\\n      }\\n    }\\n  }\\n  for (int i = 0; i < n; i++) {\\n    dp[1 << i][i] = 1;\\n  }\\n  for (int mask = 0; mask < (1 << n); mask++) {\\n    for (int i = 0; i < n; i++) {\\n      int cands = g[i] & (~mask);\\n      for (int j = 0; j < n; j++) {\\n        if ((cands >> j) & 1) {\\n          dp[mask | (1 << j)][j] += dp[mask][i];\\n        }\\n      }\\n      ok[mask] += dp[mask][i];\\n    }\\n  }\\n  for (int len = 1; len <= n; len++) {\\n    for (int mask = 0; mask < (1 << n); mask++) {\\n      if (__builtin_popcount(mask) == len) {\\n        slen[len][mask] += ok[mask];\\n      }\\n    }\\n    for (int i = 0; i < n; i++) {\\n      for (int mask = 0; mask < (1 << n); mask++) {\\n        if ((mask >> i) & 1) {\\n          slen[len][mask] += slen[len][mask ^ (1 << i)];\\n        }\\n      }\\n    }\\n  }\\n  map <vector <int>, vector <int> > ok;\\n  for (int mask = 0; mask < (1 << (n - 1)); mask++) {\\n    int x = 0;\\n    vector <int> t;\\n    while (x < n) {\\n      int len = 1;\\n      while ((mask >> x) & 1) {\\n        x++;\\n        len++;\\n      }\\n      t.push_back(len);\\n      x++;\\n    }\\n    sort(t.begin(), t.end());\\n    ok[t].push_back(mask);\\n  }\\n  vector <int> a;\\n  for (int mask = 0; mask < (1 << n); mask++)\\n    val[mask] = 1;\\n  function<void(int,int)> f = [&] (int s, int last) {\\n    if (s == n) {\\n      ll ret = 0;\\n      int x = (1 << n) - 1;\\n      for (int mask = 0; mask < (1 << n); mask++) {\\n        if (__builtin_popcount(mask) % 2 == 0)\\n          ret += val[x ^ mask];\\n        else\\n          ret -= val[x ^ mask];\\n      }\\n      for (auto c : ok[a]) {\\n        ans[c] += ret;\\n      }\\n      return;\\n    }\\n    if (s + last > n) {\\n      return;\\n    }\\n    for (int mask = 0; mask < (1 << n); mask++) {\\n      cur[s][mask] = val[mask];\\n    }\\n    for (int i = last; s + i <= n; i++) {\\n      if (s + i != n && s + i + i > n) continue;\\n      a.push_back(i);\\n      for (int mask = 0; mask < (1 << n); mask++) {\\n        val[mask] *= slen[i][mask];\\n      }\\n      f(s + i, i);\\n      for (int mask = 0; mask < (1 << n); mask++) {\\n        val[mask] = cur[s][mask];\\n      }\\n      a.pop_back();\\n    }\\n  };\\n  f(0, 1);\\n  for (int i = 0; i < (n - 1); i++) {\\n    for (int mask = 0; mask < (1 << (n - 1)); mask++) {\\n      if (!((mask >> i) & 1)) {\\n        ans[mask] -= ans[mask + (1 << i)];\\n      }\\n    }\\n  }\\n  for (int mask = 0; mask < (1 << (n - 1)); mask++) {\\n    cout << ans[mask] << ' ';\\n  }\\n  cout << endl;\\n}\"",
    "tags": [
      "bitmasks",
      "dp",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1326",
    "index": "G",
    "title": "Spiderweb Trees",
    "statement": "Let's call a graph with $n$ vertices, each of which has it's own point $A_i = (x_i, y_i)$ with integer coordinates, a planar tree if:\n\n- All points $A_1, A_2, \\ldots, A_n$ are different and no three points lie on the same line.\n- The graph is a tree, i.e. there are exactly $n-1$ edges there exists a path between any pair of vertices.\n- For all pairs of edges $(s_1, f_1)$ and $(s_2, f_2)$, such that $s_1 \\neq s_2, s_1 \\neq f_2,$ $f_1 \\neq s_2$, and $f_1 \\neq f_2$, the segments $A_{s_1} A_{f_1}$ and $A_{s_2} A_{f_2}$ don't intersect.\n\nImagine a planar tree with $n$ vertices. Consider the convex hull of points $A_1, A_2, \\ldots, A_n$. Let's call this tree a spiderweb tree if for all $1 \\leq i \\leq n$ the following statements are true:\n\n- All leaves (vertices with degree $\\leq 1$) of the tree lie on the border of the convex hull.\n- All vertices on the border of the convex hull are leaves.\n\nAn example of a spiderweb tree:\n\nThe points $A_3, A_6, A_7, A_4$ lie on the convex hull and the leaf vertices of the tree are $3, 6, 7, 4$.\n\nRefer to the notes for more examples.\n\nLet's call the subset $S \\subset \\{1, 2, \\ldots, n\\}$ of vertices a subtree of the tree if for all pairs of vertices in $S$, there exists a path that contains only vertices from $S$. Note that any subtree of the planar tree is a planar tree.\n\nYou are given a planar tree with $n$ vertexes. Let's call a partition of the set $\\{1, 2, \\ldots, n\\}$ into non-empty subsets $A_1, A_2, \\ldots, A_k$ (i.e. $A_i \\cap A_j = \\emptyset$ for all $1 \\leq i < j \\leq k$ and $A_1 \\cup A_2 \\cup \\ldots \\cup A_k = \\{1, 2, \\ldots, n\\}$) good if for all $1 \\leq i \\leq k$, the subtree $A_i$ is a spiderweb tree. Two partitions are different if there exists some set that lies in one parition, but not the other.\n\nFind the number of good partitions. Since this number can be very large, find it modulo $998\\,244\\,353$.",
    "tutorial": "Let's hang the tree on the vertex $1$. After that, we will calculate the value $dp_i$ for all vertices $i$, which is equal to the number of good partitions of the subtree of the vertex $i$ (subtree in the rooted tree). The answer to the problem in these definitions is $dp_1$. To calculate these values let's make dfs. We know in the vertex $p$ and we want to calculate $dp_p$. We know the values $dp_i$ for all $i$ in the subtree of $p$. Let's define the set of the partition, which contains $p$ as $S$. There are some cases: Case $1$: $|S| = 1$. In this case, the number of good partitions is $dp_{i_1} dp_{i_2} \\ldots dp_{i_k}$, there $i_1, i_2, \\ldots, i_k$ are all sons of the vertex $p$. Case $2$: $|S| = 2$. In this case, the number of good partitions is $\\sum\\limits_{i \\in Sons(p)} {f_i \\prod\\limits_{j \\in Sons(p), j \\neq i} dp_{j}}$, there $f_i = dp_{i_1} dp_{i_2} \\ldots dp_{i_k}$, there $i_1, i_2, \\ldots, i_k$ are all sons of the vertex $i$. The values in these cases are easy to find. We have one, last case: Case $3$: $|S| \\geq 3$. In this case, the number of good partitions is $\\sum\\limits_{p \\in S, \\, S \\, is \\, spiderweb} func(S)$. Let's define $func(S)$ as the product of $dp_i$ for all vertices $i$, which are going from $S$ (it means, that $i$ isn't in $S$, but ancestor of $i$ is in $S$). Let's try to calculate this sum faster. Let's call a pair of vertices $(i, j)$ good if they are not connected and all vertices $t$ on the path from $i$ to $j$ lies on the left side from the vector $\\overrightarrow{A_i A_j}$. It can be shown, that if the polygon $A_{i_1} A_{i_2} \\ldots A_{i_k}$ is convex and all pairs $(i_{j}, i_{j+1})$ are good, the subtree with leafs $i_1, i_2, \\ldots, i_k$ is spiderweb. So, let's fix all leaf vertices in $S$: $i_1, i_2, \\ldots, i_k$ (these are the vertices of the subtree of $p$, they can be equal to $p$). If $S$ is the spiderweb tree, the ways $(i_j, i_{j+1})$ divide the plane into infinite parts (for explanation look at the picture): The part is defined only with the way in the tree. Let's define $value_{ij}$ as the product of $dp_t$ for all vertices $t$, such that $A_t$ lies in the part for the way $(i, j)$, the vertex $t$ doesn't lie on the way and the ancestor of $t$ lies on the way. So, it's easy to see, that $func(S) = \\prod\\limits_{i=1}^{k} {value_{i_j i_{j+1}}}$. We can calculate the value for each path only one time during the dfs, after the moment, when all needed values of dp will be defined. So, let's take all pairs of vertices $(i, j)$, such that $i$ and $j$ are in the subtree of vertex $p$, the way $(i, j)$ is good and the point $A_p$ lies on the left side from the vector $\\overrightarrow{A_i A_j}$. After that, we should calculate the sum of products of $value_{i_j i_{j+1}}$ for all convex polygons $A_{i_1} A_{i_2} \\ldots A_{i_k}$, which contains the vertex $p$ on some path $(i_j i_{j+1)}$. This thing can be done by the standard dp in time $O(n^3)$ (the same dp as how we calculate the number of convex polygons). To fix the last condition we can make this dp two times: with all good pairs and with good pairs, which don't contain the vertex $p$. After that, the needed number is the subtraction of these two numbers. So, we have the solution with time complexity $O(n^4)$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\ntypedef long long ll;\\ntypedef pair<int, int> pi;\\n#define prev _prev\\n#define stack _stack\\n\\nll scal(pi a, pi b)\\n{\\n    return (ll)a.first * (ll)a.second + (ll)b.first * (ll)b.second;\\n}\\n\\nll mul(pi a, pi b)\\n{\\n    return (ll)a.first * (ll)b.second - (ll)a.second * (ll)b.first;\\n}\\n\\nint half(pi a)\\n{\\n    if (a.second > 0 || (a.second == 0 && a.first >= 0))\\n        return 0;\\n    return 1;\\n}\\n\\nint half(pi a, pi b)\\n{\\n    ll pr = mul(a, b);\\n    if (pr != 0)\\n        return (pr <= 0);\\n    return (scal(a, b) < 0);\\n}\\n\\nconst int M = 210;\\nconst int MOD = 998244353;\\n\\nint n, x[M], y[M], dp[M], val[M][M], ml[M], ei[M][M], first[M][M], last[M][M], sum[2 * M], ok[M][M];\\nvector<int> v[M];\\nvector<int> way[M][M];\\n\\npi vect(int i, int j)\\n{\\n    return make_pair(x[j] - x[i], y[j] - y[i]);\\n}\\n\\npi vect(pi t)\\n{\\n    return make_pair(x[t.second] - x[t.first], y[t.second] - y[t.first]);\\n}\\n\\nvoid dfs_help(int p, int pr)\\n{\\n    int id = -1;\\n    for (int i = 0; i < (int)v[p].size(); i++)\\n    {\\n        if (v[p][i] == pr)\\n            id = i;\\n        else\\n            dfs_help(v[p][i], p);\\n    }\\n    if (id != -1)\\n    {\\n        swap(v[p][id], v[p].back());\\n        v[p].pop_back();\\n    }\\n}\\n\\nvector<int> stack;\\n\\nvoid dfs_way(int p, int pr, int st)\\n{\\n    stack.push_back(p);\\n    if (p != st && (int)stack.size() >= 3)\\n    {\\n        bool ch = true;\\n        for (int i : stack)\\n            if (mul(vect(st, p), vect(st, i)) < 0)\\n            {\\n                ch = false;\\n                break;\\n            }\\n        if (ch)\\n            way[st][p] = stack;\\n    }\\n    for (int i : v[p])\\n        if (i != pr)\\n            dfs_way(i, p, st);\\n    stack.pop_back();\\n}\\n\\nbool cmp(pi a, pi b)\\n{\\n    pi va = vect(a);\\n    pi vb = vect(b);\\n    int ha = half(va);\\n    int hb = half(vb);\\n    if (ha != hb)\\n        return ha < hb;\\n    ll pr = mul(va, vb);\\n    if (pr != 0)\\n        return (pr > 0);\\n    return a < b;\\n}\\n\\nbool good(pi a, pi b, pi c)\\n{\\n    int hb = half(a, b);\\n    int hc = half(a, c);\\n    if (hb != hc)\\n        return hb < hc;\\n    return mul(b, c) > 0;\\n}\\n\\nvector<int> g[M];\\n\\nvector<int> dfs(int p)\\n{\\n    ml[p] = 1;\\n    vector<int> now = {p};\\n    for (int i : v[p])\\n    {\\n        vector<int> to = dfs(i);\\n        for (int x : to)\\n            now.push_back(x);\\n        ml[p] = (ll)ml[p] * dp[i] % MOD;\\n    }\\n    dp[p] = ml[p];\\n    for (int i : v[p])\\n    {\\n        int cur = ml[i];\\n        for (int j : v[p])\\n            if (j != i)\\n                cur = (ll)cur * dp[j] % MOD;\\n        dp[p] += cur;\\n        if (dp[p] >= MOD)\\n            dp[p] -= MOD;\\n    }\\n    for (int i : now)\\n        g[i].clear();\\n    int k = 0;\\n    for (int i : now)\\n        for (int j : v[i])\\n        {\\n            g[i].push_back(j);\\n            g[j].push_back(i);\\n            ei[i][j] = k++;\\n            ei[j][i] = k++;\\n        }\\n    for (int i : now)\\n        for (int j : now)\\n            ok[i][j] = 0;\\n    vector<pi> al;\\n    for (int i : now)\\n        for (int j : now)\\n            if (!way[i][j].empty() && mul(vect(i, j), vect(i, p)) >= 0)\\n            {\\n                al.push_back(make_pair(i, j));\\n                first[i][j] = ei[way[i][j][0]][way[i][j][1]];\\n                last[i][j] = ei[way[i][j][(int)way[i][j].size() - 1]][way[i][j][(int)way[i][j].size() - 2]];\\n                if (val[i][j] != -1)\\n                    continue;\\n                ok[i][j] = 1;\\n                val[i][j] = 1;\\n                for (int x = 0; x < (int)way[i][j].size(); x++)\\n                {\\n                    int v_cur = way[i][j][x];\\n                    pi lb, rb;\\n                    if (x == 0)\\n                    {\\n                        lb = vect(v_cur, way[i][j][x + 1]);\\n                        lb.first = -lb.first, lb.second = -lb.second;\\n                    }\\n                    else\\n                        lb = vect(v_cur, way[i][j][x - 1]);\\n                    if (x + 1 == (int)way[i][j].size())\\n                    {\\n                        rb = vect(v_cur, way[i][j][x - 1]);\\n                        rb.first = -rb.first, rb.second = -rb.second;\\n                    }\\n                    else\\n                        rb = vect(v_cur, way[i][j][x + 1]);\\n                    for (int to : v[v_cur])\\n                        if (good(lb, vect(v_cur, to), rb))\\n                        {\\n                            if (x != 0 && to == way[i][j][x - 1])\\n                                continue;\\n                            if (x + 1 < (int)way[i][j].size() && to == way[i][j][x + 1])\\n                                continue;\\n                            val[i][j] = (ll)val[i][j] * dp[to] % MOD;\\n                        }\\n                }\\n            }\\n    sort(al.begin(), al.end(), cmp);\\n    for (int v_st : now)\\n        for (int ig : g[v_st])\\n        {\\n            if (half(vect(v_st, ig)))\\n                continue;\\n            for (int ban = -1; ban <= 1; ban += 2)\\n            {\\n                for (int i = 0; i < k; i++)\\n                    sum[i] = 0;\\n                sum[ei[v_st][ig]] = 1;\\n                for (pi t : al)\\n                {\\n                    if (ban == -1 && ok[t.first][t.second])\\n                        continue;\\n                    int S = first[t.first][t.second];\\n                    int F = last[t.first][t.second];\\n                    sum[F] += (ll)sum[S] * val[t.first][t.second] % MOD;\\n                    if (sum[F] >= MOD)\\n                        sum[F] -= MOD;\\n                }\\n                sum[ei[v_st][ig]]--;\\n                if (sum[ei[v_st][ig]] < 0)\\n                    sum[ei[v_st][ig]] += MOD;\\n                dp[p] += ban * sum[ei[v_st][ig]];\\n                if (dp[p] >= MOD)\\n                    dp[p] -= MOD;\\n                if (dp[p] < 0)\\n                    dp[p] += MOD;\\n            }\\n        }\\n    return now;\\n}\\n\\nint main()\\n{\\n    cin >> n;\\n    for (int i = 0; i < n; i++)\\n        cin >> x[i] >> y[i];\\n    for (int i = 0; i < n - 1; i++)\\n    {\\n        int s, f;\\n        cin >> s >> f;\\n        s--, f--;\\n        v[s].push_back(f);\\n        v[f].push_back(s);\\n    }\\n    for (int i = 0; i < n; i++)\\n        dfs_way(i, -1, i);\\n    dfs_help(0, -1);\\n    memset(val, -1, sizeof(val));\\n    dfs(0);\\n    cout << dp[0] << \\\"\\\\n\\\";\\n    return 0;\\n}\"",
    "tags": [
      "dp",
      "geometry",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1327",
    "index": "A",
    "title": "Sum of Odd Integers",
    "statement": "You are given two integers $n$ and $k$. Your task is to find if $n$ can be represented as a sum of $k$ \\textbf{distinct positive odd} (not divisible by $2$) integers or not.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "First of all, notice that the sum of the first $k$ odd integers is $k^2$. If $k^2 > n$ then the answer obviously \"NO\". And if $n \\% 2 \\ne k \\% 2$ then the answer is \"NO\" also ($\\%$ is modulo operation). Otherwise, the answer is always \"YES\" and it seems like this: $[1, 3, 5, \\dots, 2(k-1)-1, rem]$, where $rem = n - \\sum\\limits_{i=1}^{k-1} (2i-1)$. It is obviously greater than $2(k-1)-1$ because $k^2 \\le n$ and it is obviously odd because the parity of $n$ and $k$ is the same.",
    "code": "for i in range(int(input())):\n    n, k = map(int, input().split())\n    print('YES' if k * k <= n and n % 2 == k % 2 else 'NO')",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1327",
    "index": "B",
    "title": "Princesses and Princes",
    "statement": "The King of Berland Polycarp LXXXIV has $n$ daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are $n$ other kingdoms as well.\n\nSo Polycarp LXXXIV has enumerated his daughters from $1$ to $n$ and the kingdoms from $1$ to $n$. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.\n\nPolycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.\n\nFor the first daughter he takes \\textbf{the kingdom with the lowest number from her list} and marries the daughter to their prince. For the second daughter he takes \\textbf{the kingdom with the lowest number from her list, prince of which hasn't been taken already}. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the $n$-th daughter.\n\nFor example, let there be $4$ daughters and kingdoms, the lists daughters have are $[2, 3]$, $[1, 2]$, $[3, 4]$, $[3]$, respectively.\n\nIn that case daughter $1$ marries the prince of kingdom $2$, daughter $2$ marries the prince of kingdom $1$, daughter $3$ marries the prince of kingdom $3$, leaving daughter $4$ nobody to marry to.\n\nActually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. \\textbf{Note that this kingdom should not be present in the daughter's list.}\n\nPolycarp LXXXIV wants to increase the number of married couples.\n\nUnfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.\n\nIf there are multiple ways to add an entry so that the total number of married couples increases then print any of them.\n\nFor your and our convenience you are asked to answer $t$ independent test cases.",
    "tutorial": "Simulate the process without adding the new entry. For this you can just maintain an array $taken$, $i$-th value of which is true if the $i$-th prince is married and false otherwise. Now observe that there are two possible outcomes: Every daughter is married - the answer is optimal. There is a daughter who isn't married. That means that there is a free prince as well. Marry them to each other because doing that won't affect any other marriages and add a new one to the answer. Overall complexity: $O(n + m)$.",
    "code": "from sys import stdin, stdout\n\nt = int(stdin.readline())\nfor _ in range(t):\n    n = int(stdin.readline())\n    used = [False for i in range(n)]\n    v = -1\n    for i in range(n):\n        l = [int(x) - 1 for x in stdin.readline().split()][1:]\n        for j in l:\n            if not used[j]:\n                used[j] = True\n                break\n        else:\n            v = i\n    if v == -1:\n        stdout.write(\"OPTIMAL\\n\")\n    else:\n        u = used.index(False)\n        stdout.write(\"IMPROVE\\n\" + str(v + 1) + \" \" + str(u + 1) + \"\\n\")",
    "tags": [
      "brute force",
      "graphs",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1327",
    "index": "C",
    "title": "Game with Chips",
    "statement": "Petya has a rectangular Board of size $n \\times m$. Initially, $k$ chips are placed on the board, $i$-th chip is located in the cell at the intersection of $sx_i$-th row and $sy_i$-th column.\n\nIn one action, Petya can move \\textbf{all the chips} to the left, right, down or up by $1$ cell.\n\nIf the chip was in the $(x, y)$ cell, then after the operation:\n\n- left, its coordinates will be $(x, y - 1)$;\n- right, its coordinates will be $(x, y + 1)$;\n- down, its coordinates will be $(x + 1, y)$;\n- up, its coordinates will be $(x - 1, y)$.\n\nIf the chip is located by the wall of the board, and the action chosen by Petya moves it towards the wall, then the chip remains in its current position.\n\n\\textbf{Note that several chips can be located in the same cell.}\n\nFor each chip, Petya chose the position which it should visit. Note that it's not necessary for a chip to end up in this position.\n\nSince Petya does not have a lot of free time, he is ready to do no more than $2nm$ actions.\n\nYou have to find out what actions Petya should do so that each chip visits the position that Petya selected for it at least once. Or determine that it is not possible to do this in $2nm$ actions.",
    "tutorial": "Note that $2nm$ is a fairly large number of operations. Therefore, we can first collect all the chips in one cell, and then go around the entire board. Let's calculate the required number of operations. First, let's collect all the chips in the $(1, 1)$ cell. To do this, let's do $n-1$ operations $U$ so that all the chips are in the first row, then do $m-1$ operations $L$. After such operations, wherever the chip is initially located, it will end up in the $(1, 1)$ cell. After that, we need to go around the entire board. Let's do it in such a way that the rows with odd numbers are be bypassed from left to right, and the even ones - from right to left. We also need $n-1$ operations $D$ to move from one row to the next one. In total, we got $(n-1) + (m-1) + n * (m-1) + (n-1) = nm + n + m - 3$ operations, which is completely suitable for us.",
    "code": "n, m, _ = map(int, input().split())\n\nprint(2 * (n - 1) + (n + 1) * (m - 1))\nprint(\"U\" * (n - 1) + \"L\" * (m - 1), end=\"\")\nfor i in range(n):\n    if i != 0:\n        print(\"D\", end=\"\")\n    if i % 2 == 0:\n        print(\"R\" * (m - 1), end=\"\")\n    else:\n        print(\"L\" * (m - 1), end=\"\")",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1327",
    "index": "D",
    "title": "Infinite Path",
    "statement": "You are given a colored permutation $p_1, p_2, \\dots, p_n$. The $i$-th element of the permutation has color $c_i$.\n\nLet's define an infinite path as infinite sequence $i, p[i], p[p[i]], p[p[p[i]]] \\dots$ where all elements have \\textbf{same color} ($c[i] = c[p[i]] = c[p[p[i]]] = \\dots$).\n\nWe can also define a multiplication of permutations $a$ and $b$ as permutation $c = a \\times b$ where $c[i] = b[a[i]]$. Moreover, we can define a power $k$ of permutation $p$ as $p^k=\\underbrace{p \\times p \\times \\dots \\times p}_{k \\text{ times}}$.\n\nFind the minimum $k > 0$ such that $p^k$ has at least one infinite path (i.e. there is a position $i$ in $p^k$ such that the sequence starting from $i$ is an infinite path).\n\nIt can be proved that the answer always exists.",
    "tutorial": "Let's look at the permutation as at a graph with $n$ vertices and edges $(i, p_i)$. It's not hard to prove that the graph consists of several cycles (self-loops are also considered as cycles). So, the sequence $i, p[i], p[p[i]], \\dots$ is just a walking on the corresponding cycle. Let's consider one cycle $c_1, c_2, \\dots, c_m$. In permutation $p$ we have $p[c_i] = c_{(i + 1) \\mod m}$. But since $p^2 = p \\times p$ or $p^2[i] = p[p[i]]$, so $p^2[c_i] = c_{(i + 2) \\mod m}$ and in general case, $p^k[c_i] = c_{(i + k) \\mod m}$. Now, walking with step $k$ we can note, that the initial cycle $c$ split up on $GCD(k, m)$ cycles of length $\\frac{m}{GCD(k, m)}$. Looking at the definition of infinite path we can understand that all we need to do is to check that at least one of $GCD(k, m)$ cycles have all vertices of the same color. We can check it in $O(m)$ time for the cycle $c$ and fixed $k$. The final observation is next: for $k_1$ and $k_2$ such that $GCD(k_1, m) = GCD(k_2, m)$ the produced cycles will have the same sets of vertices and differ only in the order of walking, so we can check only one representative for each $GCD(k, m)$, i.e. we can take only such $k$ which divide $m$. We can handle each cycle of $p$ separately. So, using the approximation that the number of divisors of $n$ is $O(n^{\\frac{1}{3}})$, we get $O(n^{\\frac{4}{3}})$ time complexity.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nint n;\nvector<int> p, c;\n\ninline bool read() {\n    if(!(cin >> n))\n        return false;\n    p.resize(n);\n    c.resize(n);\n    \n    fore(i, 0, n) {\n        cin >> p[i];\n        p[i]--;\n    }\n    fore(i, 0, n)\n        cin >> c[i];\n    return true;\n}\n\ninline void solve() {\n    vector<int> used(n, 0);\n    \n    int ans = INF;\n    fore(st, 0, n) {\n        if(used[st])\n            continue;\n        \n        vector<int> cycle;\n        int v = st;\n        while(!used[v]) {\n            used[v] = 1;\n            cycle.push_back(v);\n            v = p[v];\n        }\n        \n        fore(step, 1, sz(cycle) + 1) {\n            if(sz(cycle) % step != 0)\n                continue;\n            \n            fore(s, 0, step) {\n                bool eq = true;\n                for(int pos = s; pos + step < sz(cycle); pos += step) {\n                    if(c[cycle[pos]] != c[cycle[pos + step]])\n                        eq = false;\n                }\n                if(eq) {\n                    ans = min(ans, step);\n                    break;\n                }\n            }\n        }\n    }\n    cout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    int tc; cin >> tc;\n    \n    while(tc--) {\n        read();\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1327",
    "index": "E",
    "title": "Count The Blocks",
    "statement": "You wrote down all integers from $0$ to $10^n - 1$, padding them with leading zeroes so their lengths are exactly $n$. For example, if $n = 3$ then you wrote out 000, 001, ..., 998, 999.\n\nA block in an integer $x$ is a consecutive segment of equal digits that cannot be extended to the left or to the right.\n\nFor example, in the integer $00027734000$ there are three blocks of length $1$, one block of length $2$ and two blocks of length $3$.\n\nFor all integers $i$ from $1$ to $n$ count the number of blocks of length $i$ among the written down integers.\n\nSince these integers may be too large, print them modulo $998244353$.",
    "tutorial": "Presume that we want to calculate the number of blocks of length $len$. Let's divide this blocks into two types: blocks which first element is a first element of integer, or blocks which last element is a last element of integer (for example blocks $111$ and $0$ in integer $11173220$); other blocks. At first let's calculate the number of blocks of first type. We can choose $2$ positions of this block (at the start of end of the integer). Now we can choose $10$ digit for this block. After that we can chose $9$ digits of adjacent block (if these blocks contain the same digit then we length of blocks which we want calculate greater than $len$, so we have only $9$ variations of digit in adjacent block). Finally, the can chose the remaining digit $10^{n-len-1}$ ways. So, the total number of block of first type is $2 \\cdot 10 \\cdot 9 \\cdot 10^{n-len-1}$. Now let's calculate the number of blocks of second type. We can choose $n - len - 1$ positions of this block (all position except the start and end of integer). Now we can choose 10 digit for this block. After that we can chose $9^2$ digits of adjacent block ($9$ for block to the left and $9$ for block to the right). Finally, the can chose the remaining digit $10^{n-len-2}$ ways. So, the total number of block of second type is $(n - len - 1) \\cdot 10 \\cdot 9^2 \\cdot 10^{n-len-2}$. That's almost all. We have one corner case. If $len = n$, then we number of blocks is always $10$.",
    "code": "MOD = 998244353\np = [1] * 200005\nfor i in range(1, 200005):\n    p[i] = (p[i - 1] * 10) % MOD\n\nn = int(input())\nfor i in range(1, n):\n    res = 2 * 10 * 9 * p[n - i - 1]\n    res += (n - 1 - i) * 10 * 9 * 9 * p[n - i - 2]\n    print(res % MOD, end = ' ')\nprint(10)",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1327",
    "index": "F",
    "title": "AND Segments",
    "statement": "You are given three integers $n$, $k$, $m$ and $m$ conditions $(l_1, r_1, x_1), (l_2, r_2, x_2), \\dots, (l_m, r_m, x_m)$.\n\nCalculate the number of distinct arrays $a$, consisting of $n$ integers such that:\n\n- $0 \\le a_i < 2^k$ for each $1 \\le i \\le n$;\n- bitwise AND of numbers $a[l_i] \\& a[l_i + 1] \\& \\dots \\& a[r_i] = x_i$ for each $1 \\le i \\le m$.\n\nTwo arrays $a$ and $b$ are considered different if there exists such a position $i$ that $a_i \\neq b_i$.\n\nThe number can be pretty large so print it modulo $998244353$.",
    "tutorial": "We will solve the problem for each bit separately, and then multiply the results. Obviously, if the position is covered by a segment with the value $1$, then we have no choice, and we must put $1$ there. For segments with the value $0$, there must be at least one position that they cover and its value is $0$. So we can write the following dynamic programming: $dp_i$ - the number of arrays such that the last $0$ was exactly at the position $i$, and all $0$-segments to the left of it contain at least one zero. It remains to determine which states $j$ we can update from. The only restriction we have is that there should not be any segment $(l, r)$ with the value $0$, such that $j < l$ and $r < i$. Since in this case, this segment will not contain any zero values. For each position $i$, we may precalculate the rightmost position $f_i$ where some segment ending before $i$ begins, and while calculating $dp_i$, we should sum up only the values starting from position $f_i$. This can be done with prefix sums.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\ntypedef pair<int, int> pt;\n\nconst int MOD = 998244353;\nconst int N = 500 * 1000 + 13;\n\nint n, k, m;\npair<pt, int> q[N];\n\nint ones[N];\nint mx[N], sum[N];\n\nint add(int x, int y) {\n    x += y;\n    if (x >= MOD) x -= MOD;\n    if (x < 0) x += MOD;\n    return x;\n}\n\nint calc(int t) {\n    memset(ones, 0, sizeof(ones));\n    memset(mx, -1, sizeof(mx));\n    \n    forn(i, m) {\n        int l = q[i].x.x, r = q[i].x.y;\n        if (q[i].y & (1 << t)) {\n            ones[l]++;\n            ones[r + 1]--;\n        } else {\n            mx[r] = max(mx[r], l);\n        }\n    }\n    \n    int j = -1;\n    forn(i, n) {\n        int cur = 0;\n        if (!ones[i]) {\n            cur = sum[i];\n            if (j == -1) cur = add(cur, 1);\n            else cur = add(cur, -sum[j]);\n        }\n        \n        sum[i + 1] = add(sum[i], cur);\n        ones[i + 1] += ones[i];\n        j = max(j, mx[i]);\n    }\n    \n    return add(sum[n], j != -1 ? -sum[j] : 1);\n}\n\nint main() {\n    scanf(\"%d%d%d\", &n, &k, &m);\n    forn(i, m) {\n        scanf(\"%d%d%d\", &q[i].x.x, &q[i].x.y, &q[i].y);\n        --q[i].x.x; --q[i].x.y;\n    }\n    \n    int ans = 1;\n    forn(i, k) ans = (ans * 1ll * calc(i)) % MOD;\n    printf(\"%d\\n\", ans);\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1327",
    "index": "G",
    "title": "Letters and Question Marks",
    "statement": "You are given a string $S$ and an array of strings $[t_1, t_2, \\dots, t_k]$. Each string $t_i$ consists of lowercase Latin letters from a to n; $S$ consists of lowercase Latin letters from a to n and \\textbf{no more than $14$} question marks.\n\nEach string $t_i$ has its cost $c_i$ — an integer number. The value of some string $T$ is calculated as $\\sum\\limits_{i = 1}^{k} F(T, t_i) \\cdot c_i$, where $F(T, t_i)$ is the number of occurences of string $t_i$ in $T$ as a substring. For example, $F(\\text{aaabaaa}, \\text{aa}) = 4$.\n\nYou have to replace all question marks in $S$ with \\textbf{pairwise distinct} lowercase Latin letters from a to n so the value of $S$ is maximum possible.",
    "tutorial": "Suppose we want to calculate the value of some already fixed string (we should be able to do so at least to solve the test cases without question marks). How can we do it? We can use some substring searching algorithms to calculate $F(S, t_i)$, but a better solution is to build an Aho-Corasick automaton over the array $[t_1, t_k]$, and then for each node calculate the sum of costs of all strings ending in that node (these are the strings represented by that node and the strings represented by other nodes reachable by suffix links). After that, process $S$ by the automaton and calculate the sum of the aforementioned values over all states that were reached. Building an Aho-Corasick automaton can be done in $O(\\sum \\limits_{i = 1}^{k} |t_i|)$, and processing the string $S$ - in $O(|S|)$. Okay, what if we've got some question marks in our string? The first solution that comes to mind is to calculate $dp[i][mask][c]$ - we processed $i$ first positions in $S$, used a $mask$ of characters for question marks, and the current state of the automaton is $c$; then $dp[i][mask][c]$ denotes the maximum value of first $i$ characters of $S$ we could have got. But it's $O(L|S|2^KK)$, where $L = \\sum \\limits_{i = 1}^{k} |t_i|$ and $K$ is the size of the alphabet, which is too slow. To speed it up, we can see that there are only $14$ positions in our string where we actually choose something in our dynamic programming. All substrings not containing question marks can be skipped in $O(1)$ as follows: for each substring of $S$ bounded by two question marks (or bounded by one question mark and one of the ends of $S$) and each state of the automaton $x$, we may precalculate the resulting state of the automaton and the change to the value of the string, if we process this substring by the automaton with the initial state $x$. This precalculation is done in $O(L|S|)$ overall, and using this, we may skip the states of dynamic programming such that $i$ is not a position with a question mark, so our complexity becomes $O(L2^KK + L|S|)$. A note about the model solution: it's a bit more complicated because we wanted to increase the constraints to $|S| \\le 8 \\cdot 10^6$, but then we decided that it would be too complicated to code, so the main function still contains some parts of the code that were used to improve its complexity. We will post a clearer version of the model solution soon.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 8000043;\nconst int K = 15;\nconst int M = 1043;\n\nint k;\nchar buf[N], buf2[M];\nvector<string> t;\nvector<int> c;\nstring s;\n\nmap<char, int> nxt[M];\nint lnk[M];\nint p[M];\nchar pchar[M];\nmap<char, int> go[M];\nint term[M];\nint ts = 1;\nint A[M][K];\nint F[M][K];\nint dp[M];\n\nint get_nxt(int x, char c)\n{\n    if(!nxt[x].count(c))\n    {\n        p[ts] = x;\n        pchar[ts] = c;\n        nxt[x][c] = ts++;\n    }\n    return nxt[x][c];\n}\n\nvoid add_string(int i)\n{\n    int cur = 0;\n    for(auto x : t[i])\n    {\n        cur = get_nxt(cur, x);\n    }\n    term[cur] += c[i];\n}\n\nint get_go(int x, char c);\n\nint get_lnk(int x)\n{\n    if(lnk[x] != -1)\n        return lnk[x];\n    if(x == 0 || p[x] == 0)\n        return lnk[x] = 0;\n    return lnk[x] = get_go(get_lnk(p[x]), pchar[x]);\n}\n\nint get_dp(int x)\n{\n    if(dp[x] != -1)\n        return dp[x];\n    dp[x] = term[x];\n    if(get_lnk(x) != x)\n        dp[x] += get_dp(get_lnk(x));\n    return dp[x];\n}\n\nint get_go(int x, char c)\n{\n    if(go[x].count(c))\n        return go[x][c];\n    if(nxt[x].count(c))\n        return go[x][c] = nxt[x][c];\n    if(x == 0)\n        return go[x][c] = 0;\n    return go[x][c] = get_go(get_lnk(x), c);\n}\n\nvoid build_skip(const string& s, vector<int>& sA, vector<long long>& sF)\n{                     \n    sA = vector<int>(ts);\n    for(int i = 0; i < ts; i++)\n        sA[i] = i;\n    sF = vector<long long>(ts);\n    for(auto c : s)\n    {\n        int ci = int(c - 'a');\n        for(int i = 0; i < ts; i++)\n        {\n            sF[i] += F[sA[i]][ci];\n            sA[i] = A[sA[i]][ci];\n        }\n    }\n}\n\nlong long solve(const string& s)\n{\n    long long BAD = (long long)(-1e18);\n\n    vector<int> pos;\n    for(int i = 0; i < s.size(); i++)\n        if(s[i] == '?')\n            pos.push_back(i);\n    int cntQ = pos.size();\n    vector<vector<int> > skip_A(cntQ + 1);\n    vector<vector<long long> > skip_F(cntQ + 1);\n    build_skip(s.substr(0, pos[0]), skip_A[0], skip_F[0]);\n    for(int i = 1; i < cntQ; i++)\n        build_skip(s.substr(pos[i - 1] + 1, pos[i] - pos[i - 1] - 1), skip_A[i], skip_F[i]);\n    build_skip(s.substr(pos.back() + 1, s.size() - pos.back() - 1), skip_A[cntQ], skip_F[cntQ]);\n\n    vector<vector<long long> > dp(1 << (K - 1), vector<long long>(ts, BAD));\n    vector<int> used(1 << K);\n    dp[0][skip_A[0][0]] = skip_F[0][0];\n    queue<int> q;\n    q.push(0);\n    used[0] = 1;\n    long long ans = BAD;\n    while(!q.empty())\n    {\n        int k = q.front();\n        q.pop();\n        int step = __builtin_popcount(k);\n        if(step == cntQ)\n        {\n            for(int i = 0; i < ts; i++)\n                ans = max(ans, dp[k][i]);\n            continue;\n        }\n        for(int i = 0; i < K - 1; i++)\n        {\n            if(k & (1 << i)) continue;\n            int nk = (k ^ (1 << i));\n            if(used[nk] == 0)\n            {\n                used[nk] = 1;\n                q.push(nk);\n            }\n            for(int j = 0; j < ts; j++)\n            {\n                if(dp[k][j] == BAD)\n                    continue;\n                int nj = get_go(j, char('a' + i));\n                int newSt = skip_A[step + 1][nj];\n                long long add = get_dp(nj) + skip_F[step + 1][nj];\n                dp[nk][newSt] = max(dp[nk][newSt], dp[k][j] + add);\n            }\n        }\n    }\n    return ans;\n}\n\nint main()\n{\n    scanf(\"%d\", &k);\n    t.resize(k);\n    c.resize(k);\n    for(int i = 0; i < k; i++)\n    {\n        scanf(\"%s %d\", buf2, &c[i]);\n        t[i] = buf2;\n    }    \n    scanf(\"%s\", buf);\n    s = buf;\n\n    for(int i = 0; i < k; i++)\n        add_string(i);\n    for(int i = 0; i < ts; i++)\n    {\n        lnk[i] = -1;\n        dp[i] = -1;\n    }\n    for(int i = 0; i < ts; i++)\n    {\n        get_lnk(i);\n        for(char c = 'a'; c <= 'o'; c++)\n            get_go(i, c);\n    }\n    for(int i = 0; i < ts; i++)\n        get_dp(i);                               \n    for(int i = 0; i < ts; i++)\n    {\n        for(int j = 0; j < K; j++)\n        {\n            A[i][j] = get_go(i, char('a' + j));\n            F[i][j] = dp[A[i][j]];\n        }\n    }   \n    int n = s.size();\n    vector<int> leftQ(n, -1);\n    vector<int> rightQ(n, -1);\n    for(int i = 0; i < n; i++)\n    {\n        if(i != 0)\n            leftQ[i] = leftQ[i - 1];\n        if(s[i] == '?')\n            leftQ[i] = i;\n    }\n    for(int i = n - 1; i >= 0; i--)\n    {\n        if(i != n - 1)\n            rightQ[i] = rightQ[i + 1];\n        if(s[i] == '?')\n            rightQ[i] = i;\n    }\n    vector<int> bad(n, 0);\n    \n    if(leftQ.back() == -1)\n        bad = vector<int>(n, 1);\n\n    long long ans = 0;\n    int curSt = 0;\n    string news = \"\";\n    for(int i = 0; i < n; i++)\n    {\n        int ci = (s[i] == '?' ? 14 : int(s[i] - 'a'));\n        if(bad[i])\n            ans += F[curSt][ci];\n        curSt = A[curSt][ci];\n        if(!bad[i])\n            news.push_back(s[i]);\n        else if(i != 0 && !bad[i - 1])\n            news.push_back('o');\n    }                    \n    if(!news.empty())\n        ans += solve(news);\n    printf(\"%lld\\n\", ans);\n}",
    "tags": [
      "bitmasks",
      "dp",
      "string suffix structures"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1328",
    "index": "A",
    "title": "Divisibility Problem",
    "statement": "You are given two positive integers $a$ and $b$. In one move you can increase $a$ by $1$ (replace $a$ with $a+1$). Your task is to find the minimum number of moves you need to do in order to make $a$ divisible by $b$. It is possible, that you have to make $0$ moves, as $a$ is already divisible by $b$. You have to answer $t$ independent test cases.",
    "tutorial": "If $a \\% b = 0$ ($a$ is divisible by $b$), just print $0$. Otherwise, we need exactly $b - a \\% b$ moves to make zero remainder of $a$ modulo $b$. $\\%$ is modulo operation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tif (a % b == 0) cout << 0 << endl;\n\t\telse cout << b - a % b << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1328",
    "index": "B",
    "title": "K-th Beautiful String",
    "statement": "For the given integer $n$ ($n > 2$) let's write down all the strings of length $n$ which contain $n-2$ letters 'a' and two letters 'b' in \\textbf{lexicographical} (alphabetical) order.\n\nRecall that the string $s$ of length $n$ is lexicographically less than string $t$ of length $n$, if there exists such $i$ ($1 \\le i \\le n$), that $s_i < t_i$, and for any $j$ ($1 \\le j < i$) $s_j = t_j$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.\n\nFor example, if $n=5$ the strings are (the order does matter):\n\n- aaabb\n- aabab\n- aabba\n- abaab\n- ababa\n- abbaa\n- baaab\n- baaba\n- babaa\n- bbaaa\n\nIt is easy to show that such a list of strings will contain exactly $\\frac{n \\cdot (n-1)}{2}$ strings.\n\nYou are given $n$ ($n > 2$) and $k$ ($1 \\le k \\le \\frac{n \\cdot (n-1)}{2}$). Print the $k$-th string from the list.",
    "tutorial": "Let's try to find the position of the leftmost occurrence of 'b' (iterate over all positions from $n-2$ to $0$). If $k \\le n - i - 1$ then this is the required position of the leftmost occurrence of 'b'. Then the position of rightmost occurrence is $n - k$ so we can print the answer. Otherwise, let's decrease $k$ by $n-i-1$ (remove all strings which have the leftmost 'b' at the current position) and proceed to the next position. It is obvious that in such a way we consider all possible strings in lexicographic order.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n, k;\n        cin >> n >> k;\n        string s(n, 'a');\n        for (int i = n - 2; i >= 0; i--) {\n            if (k <= (n - i - 1)) {\n                s[i] = 'b';\n                s[n - k] = 'b';\n                cout << s << endl;\n                break;\n            }\n            k -= (n - i - 1);\n        }\n    }\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1328",
    "index": "C",
    "title": "Ternary XOR",
    "statement": "A number is ternary if it contains only digits $0$, $1$ and $2$. For example, the following numbers are ternary: $1022$, $11$, $21$, $2002$.\n\nYou are given a long ternary number $x$. The first (leftmost) digit of $x$ is guaranteed to be $2$, the other digits of $x$ can be $0$, $1$ or $2$.\n\nLet's define the ternary XOR operation $\\odot$ of two ternary numbers $a$ and $b$ (both of length $n$) as a number $c = a \\odot b$ of length $n$, where $c_i = (a_i + b_i) \\% 3$ (where $\\%$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $3$. For example, $10222 \\odot 11021 = 21210$.\n\nYour task is to find such ternary numbers $a$ and $b$ both of length $n$ and both without leading zeros that $a \\odot b = x$ and $max(a, b)$ is the minimum possible.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let's iterate from left to right over the digits of $x$. If the current digit is either $0$ or $2$ then we can set $a_i = b_i = 0$ or $a_i = b_i = 1$ correspondingly. There are no better choices. And if the current digit $x_i$ is $1$ then the optimal choise is to set $a_i = 1$ and $b_i = 0$. What happens after the first occurrence of $1$? Because of this choice $a$ is greater than $b$ even if all remaining digits in $b$ are $2$. So for each $j > i$ set $a_j = 0$ and $b_j = x_j$ and print the answer. The case without $1$ is even easier and in fact we handle it automatically.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tstring x;\n\t\tcin >> n >> x;\n\t\tstring a(n, '0'), b(n, '0');\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (x[i] == '1') {\n\t\t\t\ta[i] = '1';\n\t\t\t\tb[i] = '0';\n\t\t\t\tfor (int j = i + 1; j < n; ++j) {\n\t\t\t\t\tb[j] = x[j];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ta[i] = b[i] = '0' + (x[i] - '0') / 2;\n\t\t\t}\n\t\t}\n\t\tcout << a << endl << b << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1328",
    "index": "D",
    "title": "Carousel",
    "statement": "The round carousel consists of $n$ figures of animals. Figures are numbered from $1$ to $n$ in order of the carousel moving. Thus, after the $n$-th figure the figure with the number $1$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $i$-th figure equals $t_i$.\n\n\\begin{center}\n{\\small The example of the carousel for $n=9$ and $t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$}.\n\\end{center}\n\nYou want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.\n\nYour task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $k$ distinct colors, then the colors of figures should be denoted with integers from $1$ to $k$.",
    "tutorial": "The answer to this problem is at most $3$. Let's prove it by construction. Firstly, if all $t_i$ are equal then the answer is $1$. Otherwise, there are at least two different values in the array $t$ so the answer is at least $2$. If $n$ is even then the answer is always $2$ because you can color figures in the following way: $[1, 2, 1, 2, \\dots, 1, 2]$. If $n$ is odd then consider two cases. The first case is when some pair of adjacent figures have the same type. Then the answer is $2$ because you can merge these two values into one and get the case of even $n$. Otherwise, all pairs of adjacent figures have different types and if you consider this cyclic array as a graph (cycle of length $n$) then you can notice that it isn't bipartite so you need at least $3$ colors to achieve the answer (color all vertices in such a way that any two adjacent vertices have different colors). And the answer looks like $[1, 2, 1, 2, \\dots, 1, 2, 3]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> a[i];\n\t}\n\t\n\tif (count(a.begin(), a.end(), a[0]) == n) {\n\t\tcout << 1 << endl;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcout << 1 << \" \";\n\t\t}\n\t\tcout << endl;\n\t\treturn 0;\n\t}\n\t\n\tif (n % 2 == 0) {\n\t\tcout << 2 << endl;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcout << i % 2 + 1 << \" \";\n\t\t}\n\t\tcout << endl;\n\t\treturn 0;\n\t}\n\t\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (a[i] == a[(i + 1) % n]) {\n\t\t\tvector<int> ans(n);\n\t\t\tfor (int j = 0, pos = i + 1; pos < n; ++pos, j ^= 1) {\n\t\t\t\tans[pos] = j + 1;\n\t\t\t}\n\t\t\tfor (int j = 0, pos = i; pos >= 0; --pos, j ^= 1) {\n\t\t\t\tans[pos] = j + 1;\n\t\t\t}\n\t\t\tcout << 2 << endl;\n\t\t\tfor (int pos = 0; pos < n; ++pos) {\n\t\t\t\tcout << ans[pos] << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\n\tcout << 3 << endl;\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tcout << i % 2 + 1 << \" \";\n\t}\n\tcout << 3 << endl;\n    return 0;    \n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\nint q;\ncin >> q;\nfor (int qq = 0; qq < q; qq++) {\n    solve();\n}\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1328",
    "index": "E",
    "title": "Tree Queries",
    "statement": "You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is a vertex number $1$.\n\nA tree is a connected undirected graph with $n-1$ edges.\n\nYou are given $m$ queries. The $i$-th query consists of the set of $k_i$ distinct vertices $v_i[1], v_i[2], \\dots, v_i[k_i]$. Your task is to say if there is a path from the root to some vertex $u$ such that each of the given $k$ vertices is either belongs to this path or has the distance $1$ to some vertex of this path.",
    "tutorial": "Firstly, let's choose some deepest (farthest from the root) vertex $fv$ in the query (among all such vertices we can choose any). It is obvious that every vertex in the query should either belong to the path from the root to $fv$ or the distance to some vertex of this path should be at most one. Now there are two ways: write some LCA algorithms and other hard stuff which is unnecessary in this problem or write about $15$ lines of code and solve the problem. Let's take every non-root vertex (except $fv$) and replace it with its parent. So, what's next? Now the answer is \"YES\" if each vertex (after transformation) belongs to the path from root to $fv$. Now we just need to check if it is true. We can do this using the very standard technique: firstly, let's run dfs from the root and calculate for each vertex the first time we visited it ($tin$) and the last time we visited it ($tout$). We can do this using the following code: Initially, $T$ equals zero. Now we have a beautiful structure giving us so much information about the tree. Consider all segments $[tin_v; tout_v]$. We can see that there is no pair of intersecting segments. The pair of segments $[tin_v; tout_v]$ and $[tin_u; tout_u]$ is either non-intersecting at all or one segment lies inside the other one. The second beautiful fact is that for each vertex $u$ in the subtree of $v$ the segment $[tin_u; tout_u]$ lies inside the segment $[tin_v; tout_v]$. So, we can check if one vertex is the parent of the other: the vertex $v$ is the parent of the vertex $u$ if and only if $tin_v \\le tin_u$ and $tout_u \\le tout_v$ (the vertex is the parent of itself). How do we check if the vertex $u$ lies on the path from the root to the vertex $fv$? It lies on this path if the root is the parent of $u$ (it is always true) and $u$ is the parent of $fv$. This approach can be used for each vertical path (such a path from $x$ to $y$ that $lca(x, y)$ is either $x$ or $y$). Time complexity: $O(n + m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint T;\nvector<int> p, d;\nvector<int> tin, tout;\nvector<vector<int>> g;\n\nvoid dfs(int v, int par = -1, int dep = 0) {\n\tp[v] = par;\n\td[v] = dep;\n\ttin[v] = T++;\n\tfor (auto to : g[v]) {\n\t\tif (to == par) continue;\n\t\tdfs(to, v, dep + 1);\n\t}\n\ttout[v] = T++;\n}\n\nbool isAnc(int v, int u) {\n\treturn tin[v] <= tin[u] && tout[u] <= tout[v];\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tT = 0;\n\tp = d = vector<int>(n);\n\ttin = tout = vector<int>(n);\n\tg = vector<vector<int>>(n);\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x, --y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\tdfs(0);\n\t\n\tfor (int i = 0; i < m; ++i) {\n\t\tint k;\n\t\tcin >> k;\n\t\tvector<int> v(k);\n\t\tfor (auto &it : v) {\n\t\t\tcin >> it;\n\t\t\t--it;\n\t\t}\n\t\t\n\t\tint u = v[0];\n\t\tfor (auto it : v) if (d[u] < d[it]) u = it;\n\t\tfor (auto &it : v) {\n\t\t\tif (it == u) continue;\n\t\t\tif (p[it] != -1) it = p[it];\n\t\t}\n\t\tbool ok = true;\n\t\tfor (auto it : v) ok &= isAnc(it, u);\n\t\tif (ok) cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1328",
    "index": "F",
    "title": "Make k Equal",
    "statement": "You are given the array $a$ consisting of $n$ elements and the integer $k \\le n$.\n\nYou want to obtain \\textbf{at least} $k$ equal elements in the array $a$. In one move, you can make one of the following two operations:\n\n- Take \\textbf{one} of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $a$ is $mn$ then you choose such index $i$ that $a_i = mn$ and set $a_i := a_i + 1$);\n- take \\textbf{one} of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $a$ is $mx$ then you choose such index $i$ that $a_i = mx$ and set $a_i := a_i - 1$).\n\nYour task is to calculate the minimum number of moves required to obtain \\textbf{at least} $k$ equal elements in the array.",
    "tutorial": "This problem is just all about the implementation. Firstly, let's sort the initial values and compress them to pairs $(i, cnt[val])$, where $cnt[val]$ is the number of elements $val$. The first observation is pretty standard and easy: some equal elements will remain unchanged. So let's iterate over all elements $val$ in some order and suppose that all elements $val$ will remain unchanged. Firstly, we need $need = max(0, k - cnt[val])$ elements which we should obtain by some moves. The second observation is that we first need to take elements from one end (only less or only greater) and only then from the other (if needed). Consider the case when we first take less elements. The other case is almost symmetric. Let $needl = min(need, prefcnt_{prv})$ be the number of less than $val$ which we need to increase to $val$. If $needl = 0$ then skip the following step. Otherwise, let $prefcnt_i$ be the number of elements less than or equal to $i$, $prefsum_i$ be the sum of all elements less than or equal to $i$ and $prv$ be the previous value (the maximum value less than $val$). Then we need to increase all elements less than or equal to $prv$ at least to the value $val-1$. It costs $(val - 1) \\cdot prefcnt_{prv} - prefsum_{prv}$ moves. And then we need $needl$ moves to increase $needl$ elements to $val$. And let $needr = max(0, need - needl)$ be the number of elements greater than $val$ which we need to decrease to $val$ if we increased $needl$ elements already. If $needr = 0$ then skip the following step. Otherwise, let $sufcnt_i$ be the number of elements greater than or equal to $i$, $prefsum_i$ be the sum of all elements greater than or equal to $i$ and $nxt$ be the next value (the minimum value greater than $val$). Then we need to decrease all elements greater than or equal to $prv$ at least to the value $val+1$. It costs $sufsum_{nxt} - (val + 1) \\cdot sufcnt_{nxt}$ moves. And then we need $needr$ moves to decrease $needr$ elements to $val$. So we can update the answer with the sum of values described above and proceed to the next value. Arrays $prefcnt, sufcnt, prefsum, sufsum$ are just simple prefix and suffix sums which can be calculated in $O(n)$ using very standard and easy dynamic programming. Don't forget about the overflow. Total time complexity: $O(n \\log n)$ because of sorting.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long INF64 = 1e18;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> a(n);\n\tfor (auto &it : a) cin >> it;\n\t\n\tsort(a.begin(), a.end());\n\tvector<pair<int, int>> cnt;\n\tfor (auto it : a) {\n\t\tif (cnt.empty() || cnt.back().first != it) {\n\t\t\tcnt.push_back({it, 1});\n\t\t} else {\n\t\t\t++cnt.back().second;\n\t\t}\n\t}\n\tvector<long long> prefsum, sufsum;\n\tvector<int> prefcnt, sufcnt; \n\tfor (int i = 0; i < int(cnt.size()); ++i) {\n\t\tlong long cursum = cnt[i].first * 1ll * cnt[i].second;\n\t\tint curcnt = cnt[i].second;\n\t\tif (prefsum.empty()) {\n\t\t\tprefsum.push_back(cursum);\n\t\t\tprefcnt.push_back(curcnt);\n\t\t} else {\n\t\t\tprefsum.push_back(prefsum.back() + cursum);\n\t\t\tprefcnt.push_back(prefcnt.back() + curcnt);\n\t\t}\n\t}\n\tfor (int i = int(cnt.size()) - 1; i >= 0; --i) {\n\t\tlong long cursum = cnt[i].first * 1ll * cnt[i].second;\n\t\tint curcnt = cnt[i].second;\n\t\tif (sufsum.empty()) {\n\t\t\tsufsum.push_back(cursum);\n\t\t\tsufcnt.push_back(curcnt);\n\t\t} else {\n\t\t\tsufsum.push_back(sufsum.back() + cursum);\n\t\t\tsufcnt.push_back(sufcnt.back() + curcnt);\n\t\t}\n\t}\n\treverse(sufsum.begin(), sufsum.end());\n\treverse(sufcnt.begin(), sufcnt.end());\n\t\n\tlong long ans = INF64;\n\tfor (int i = 0; i < int(cnt.size()); ++i) {\n\t\tint cur = max(0, k - cnt[i].second);\n\t\t\n\t\tint needl = 0;\n\t\tif (i > 0) needl = min(cur, prefcnt[i - 1]);\n\t\tint needr = max(0, cur - needl);\n\t\tlong long res = 0;\n\t\tif (i > 0 && needl > 0) {\n\t\t\tres += prefcnt[i - 1] * 1ll * (cnt[i].first - 1) - prefsum[i - 1];\n\t\t\tres += needl;\n\t\t}\n\t\tif (i + 1 < int(cnt.size()) && needr > 0) {\n\t\t\tres += sufsum[i + 1] - sufcnt[i + 1] * 1ll * (cnt[i].first + 1);\n\t\t\tres += needr;\n\t\t}\n\t\tans = min(ans, res);\n\t\t\n\t\tneedr = 0;\n\t\tif (i + 1 < int(cnt.size())) needr = min(cur, sufcnt[i + 1]);\n\t\tneedl = max(0, cur - needr);\n\t\tres = 0;\n\t\tif (i > 0 && needl > 0) {\n\t\t\tres += prefcnt[i - 1] * 1ll * (cnt[i].first - 1) - prefsum[i - 1];\n\t\t\tres += needl;\n\t\t}\n\t\tif (i + 1 < int(cnt.size()) && needr > 0) {\n\t\t\tres += sufsum[i + 1] - sufcnt[i + 1] * 1ll * (cnt[i].first + 1);\n\t\t\tres += needr;\n\t\t}\n\t\tans = min(ans, res);\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1329",
    "index": "A",
    "title": "Dreamoon Likes Coloring",
    "statement": "Dreamoon likes coloring cells very much.\n\nThere is a row of $n$ cells. Initially, all cells are empty (don't contain any color). Cells are numbered from $1$ to $n$.\n\nYou are given an integer $m$ and $m$ integers $l_1, l_2, \\ldots, l_m$ ($1 \\le l_i \\le n$)\n\nDreamoon will perform $m$ operations.\n\nIn $i$-th operation, Dreamoon will choose a number $p_i$ from range $[1, n-l_i+1]$ (inclusive) and will paint all cells from $p_i$ to $p_i+l_i-1$ (inclusive) in $i$-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.\n\nDreamoon hopes that after these $m$ operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose $p_i$ in each operation to satisfy all constraints.",
    "tutorial": "After reading the statement, you may find this is a problem that will be tagged as \"constructive algorithms\" in Codefores. And you also can find this problem is just problem A in Div. 1. So basically we can expect there exist some simple methods to solve it. If a \"constructive algorithms\" problem asks you to determine whether the solution exists or not, usually they have a common pattern(especially in problem hardness which is before Div. 1 B(inclusive)), this is, there are some simple constraints can divide test data into \"Yes\", and \"No\". Therefore, the first thing to solve this problem is finding some trivial conditions that cannot achieve Dreamoon's hope. After some try, you may find there are two trivial conditions that achieving Dreamoon's hope is impossible. The two conditions are listed as follows: 1. Sum of $l_i$ is less than $n$. In this condition, there always is at least one empty grid. 2. There exists some $i$ such that $l_i + i - 1 > n$. If $n - l_i < i - 1$, it means after you do $i$-th operation, there only $n - l_i$ grid is not colored by $i$-th color. So at least one of previous $i-1$ color will disapear after this operation. Now I want to talk about another feature of some \"constructive algorithms\" first. Sometimes, the condition given by the problem is to \"open\", this is to say that if we added some more strict constraint, the problem is still can be solved. And when the constraint it more strict, we can deduce the solution more easily. One of common \"strict constraint\" is \"sorted\". I believe you have ever seen many problems that the first step is sorting something. Now, we also want to apply \"sorted\" in the problem. After applying \"sort\", we firstly consider the edge cases of above two impossible conditions. The first case is \"sum of $l_i$ is equal to $n$\". In this case, we have a unique solution after applying \"sort\", $p_i = m - \\sum\\limits_{j=i+1}^{m} l_j + 1$. The second case is $l_i + i - 1 = n$ is hold for all $i$. In this case, there is also a unique solution that $p_i = i$. The two cases coressond to $n$ is largest and $n$ is smallest among all $n$ that exist solutions for same $l_i$. And for same $l_i$, when we decrase $n$ from the largest possible value, we can just change $p_i$ from $m - \\sum\\limits_{j=i+1}^{m} l_j + 1$ to $i$ for some smallest indices $i$ to get solution. To sum it up, finally, we get the answer. The answer is just $p_i = \\max(i, n - suffix\\_sum[i] + 1)$, for each $i$. There exist many other methods to construct solutions. I believe the construction method one can think out is relative to the study experience.",
    "code": "#include<bits/stdc++.h>\nconst int SIZE = 100002;\nint len[SIZE];\nlong long suffix_sum[SIZE];\nvoid err() {puts(\"-1\");}\nvoid solve() {\n    int N, M;\n    scanf(\"%d%d\", &N, &M);\n    for(int i = 1; i <= M; i++) {\n        scanf(\"%d\", &len[i]);\n        if(len[i] + i - 1 > N) {\n            err();\n            return;\n        }\n    }\n    for(int i = M; i > 0; i--) {\n        suffix_sum[i] = suffix_sum[i + 1] + len[i];\n    }\n    if(suffix_sum[1] < N) {\n        err();\n        return;\n    }\n    for(int i = 1; i <= M; i++) {\n        printf(\"%lld\", std::max((long long)i, N - suffix_sum[i] + 1));\n        if(i < M) putchar(' ');\n        else puts(\"\");\n    }\n}\nint main() {\n    solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1329",
    "index": "B",
    "title": "Dreamoon Likes Sequences",
    "statement": "Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:\n\nYou are given two integers $d, m$, find the number of arrays $a$, satisfying the following constraints:\n\n- The length of $a$ is $n$, $n \\ge 1$\n- $1 \\le a_1 < a_2 < \\dots < a_n \\le d$\n- Define an array $b$ of length $n$ as follows: $b_1 = a_1$, $\\forall i > 1, b_i = b_{i - 1} \\oplus a_i$, where $\\oplus$ is the bitwise exclusive-or (xor). After constructing an array $b$, the constraint $b_1 < b_2 < \\dots < b_{n - 1} < b_n$ should hold.\n\nSince the number of possible arrays may be too large, you need to find the answer modulo $m$.",
    "tutorial": "Firstly, we define a function $h(x)$ as the position of the highest bit which is set to 1 in a positive integer $x$. For example, $h(1) = 0, h(2) = h(3) = 1$, and $h(4) = h(7) = 2$. If the constraints in this problem is satisfied, there is some observations, $h(a_i) = h(b_i)$ and $h(a_i)$ must less than $h(a_{i+1})$. And luckily, if $h(a_i) < h(a_{i+1})$ is always hold, the constraints in this problem will also be satisfied (Please prove them by yourself or wait for someone prove it in comments : ) P.S. the link of proof written by someone is int the end. ) In other words, for each non-negative integer $v$, there is at most one $i$ such that $h(a_i) = v$. This is, at most one of the positive numbers in range $[2^v, min(2^{(v+1)}-1,d)]$ can occur in $a_i$. In each non-empty range, we can choose one integer in it or don't choose anyone. So for each of them we have $min(2^{(v+1)}-1,d) - 2^v + 2$ different choice. Then according to the rule of product, we can multiply all number of choices for different $v$ and minus the value by one to get the answer. For example, when d = 6, there are $2$ choices for $v = 0$, $3$ choices for $v=1$, $4$ choices for $v=2$. So the answer for $d = 6$ is $2 \\times 3 \\times 4 - 1 = 23$. UPD: onthefloor provides proof for what I mention here.",
    "code": "#include<bits/stdc++.h>\nvoid solve(){\n    int d, m;\n    scanf(\"%d%d\",&d, &m);\n    long long answer=1;\n    for(int i = 0; i < 30; i++) {\n        if(d < (1 << i)) break;\n        answer = answer * (std::min((1 << (i+1)) - 1, d) - (1 << i) + 2) % m;\n    }\n    answer--;\n    if(answer < 0) answer += m;\n    printf(\"%lld\\n\",answer);\n}\nint main() {\n    int T;\n    scanf(\"%d\", &T);\n    while(T--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1329",
    "index": "C",
    "title": "Drazil Likes Heap",
    "statement": "Drazil likes heap very much. So he created a problem with heap:\n\nThere is a max heap with a height $h$ implemented on the array. The details of this heap are the following:\n\nThis heap contains exactly $2^h - 1$ \\textbf{distinct} positive non-zero integers. All integers are distinct. These numbers are stored in the array $a$ indexed from $1$ to $2^h-1$. For any $1 < i < 2^h$, $a[i] < a[\\left \\lfloor{\\frac{i}{2}}\\right \\rfloor]$.\n\nNow we want to reduce the height of this heap such that the height becomes $g$ with exactly $2^g-1$ numbers in heap. To reduce the height, we should perform the following action $2^h-2^g$ times:\n\nChoose an index $i$, which contains an element and call the following function $f$ in index $i$:\n\nNote that we suppose that if $a[i]=0$, then index $i$ don't contain an element.\n\nAfter all operations, the remaining $2^g-1$ element must be located in indices from $1$ to $2^g-1$. Now Drazil wonders what's the minimum possible sum of the remaining $2^g-1$ elements. Please find this sum and find a sequence of the function calls to achieve this value.",
    "tutorial": "The property of heap we concern in this problem mainly are: 1. The tree is a binary tree, each node has a weight value. 2. The weight of a node is always larger than the weight of its children. 3. We use $a[I]$ to record the weight of vertex $i$, and the number of its children are $2 \\times i$ and vertex $2 \\times i + 1$ (if exist). Another key point we should consider seriously is before all operations and after all operations, the tree must be a perfect binary tree. Many contestants didn't notice the constraint during the contest. I think there are two different thinking directions for this problem. One is considering node from bottom to top. Another one is considering node from top to bottom. For me, from bottom to top is more intuitive. Now we talk about \"from bottom to top\" first, it means we consider node from larger index to smaller index in the tree after all operations (call it final tree after). For the leaves in the final tree, it's not hard to know, the minimum possible final weight of each leaf is the minimum weight of nodes in its subtree before all operations (call it beginning tree after). For the other nodes in the final tree, its weight must satisfy two constraints, one is it should be larger than the final weight of his children, another is the weight should exist in its subtree of the beginning tree. Luckily, these lower bounds are all constraints we should consider to get the answer. For each leaf in the final tree, we maintain a data structure that stores all weight of its subtree in the beginning tree. Then the minimum value in this data structure is its final weight. For other nodes in the final tree, we merge the two data structures of its children. the remove all value which is less than the final weight of his children. There are many data structure can do these operations, such as min heap(author's code) or sorted array(isaf27's code). With the above method, we get the minimum possible sum of the remaining $2^g-1$ elements. But we still don't know how to construct it. All we know is which weight values are reaming in the final tree. Now I want to prove that no matter how the order I call the function $f$, if the remaining weight values set is the same, the final shape of the final tree will be the same. This time I prove it from top to bottom. We only know which weight values set to remain in the final, Then We iterate node from smallest index to the larger one. We always can determine the weight value of the iterated node, because the weight value only can be the maximum value in its subtree. This trait also can let us know that the final tree we get in our method is a perfect binary tree. Conclude all things above. after we can apply the function $f$ from bottom to top on these nodes with weight value doesn't exist in the final tree. In the \"from bottom to top\" method, it has some thinking level difference between calculating the minimum sum and constructing a list of possible operations. So I determine let competitors output the operations. - - - Now we talk about the \"from top to bottom\" method. The main idea of this method is iterating index from $1$ to $2^g-1$ and in each iteration, applying the function $f$ on $i$-th node until the shape of the final tree is impossible to become a perfect binary tree. The method is quite easy to write and almost has no difference when asking you to output the operations. But I think it's hard to prove. Evenly, I think the solution should be wrong until I write this solution and test it. Firstly I want to prove the minimum possible final weight value of node $1$ is the same as the above \"from top to bottom\" method get. We call the value as $mi_1$. If some algorithm $B$ can get more small weight value in the final tree, It means all weight values which are not smaller than $mi_1$ disappear. But according to the conclusion \"if the remaining weight values set is the same, the final shape of the final tree will be the same.\". the final tree generated by $B$ can also get with firstly applying the function $f$ on node $1$ at least one more time than above \"from top to bottom\" algorithm, and do some other operations. But it will make the final tree is impossible to be the perfect binary tree. Now we disprove it. Now we want to prove the final weight value of node $i$($i>1$) is the same as the above \"from top to bottom\" method get. Only when applying function $f$ on ancestors and descendants of node $i$ will affect the final weight value of node $i$. And when we apply on its ancestors, the $f$ may recursively apply $f$ on $it$ at most once. So each time $f$ applies on its ancestors is equivalent to apply on itself once or do nothing. Therefore, The proof can be don as what we do on node $1$ just by only considering the subtree of node $i$. Now, we have proved the \"top to bottom\" algorithm can make each node of the final tree has the minimum possible weight value. When I found the \"top to bottom\" algorithm during preparing the contest, I ever consider changing the problem to something else because the method is too easy to guess and to write. But I have no other more proper problem that can be used. It's a little pity for me. a super simple solution which is differet to this blog provided by Swistakk.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int SIZE = 1<<20;\nint INF = 1000000001;\nint a[SIZE], ops[SIZE];\nint h, g;\nint qq[24], qn;\nint pull(int id) {\n    int tmp = a[id];\n    a[id] = 0;\n    qn = 0;\n    qq[qn++] = id;\n    while(id * 2 < (1 << h) && a[id] < max(a[id<<1], a[(id<<1)|1])) {\n        if(a[id<<1] > a[(id << 1) | 1]) {\n            swap(a[id<<1], a[id]);\n            id <<= 1;\n        }\n        else {\n            swap(a[(id<<1)|1], a[id]);\n            id = (id << 1) | 1;\n        }\n        qq[qn++] = id;\n    }\n    if(id < (1 << g)) {\n        for(int i = qn - 1; i > 0; i--) {\n            a[qq[i]] = a[qq[i - 1]];\n        }\n        a[qq[0]] = tmp;\n        return 0;\n    }\n    return tmp;\n}\nvoid solve() {\n    scanf(\"%d%d\", &h, &g);\n    long long an = 0;\n    for(int i = 1; i < (1 << h); i++) {\n        scanf(\"%d\", &a[i]);\n        an += a[i];\n    }\n    int need = 0;\n    for(int i = 1; i < (1 << g); i++) {\n        while(1) {\n            int v = pull(i);\n            if(v) {\n                an -= v;\n                ops[need++] = i;\n            }\n            else break;\n        }\n    }\n    printf(\"%lld\\n\", an);\n    for(int i = 0; i < need; i++) printf(\"%d%c\", ops[i], \" \\n\"[i == need - 1]);\n}\nint main(){\n    int T;\n    scanf(\"%d\", &T);\n    while(T--) solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1329",
    "index": "D",
    "title": "Dreamoon Likes Strings",
    "statement": "Dreamoon likes strings. Today he created a game about strings:\n\nString $s_1, s_2, \\ldots, s_n$ is \\textbf{beautiful} if and only if for each $1 \\le i < n, s_i \\ne s_{i+1}$.\n\nInitially, Dreamoon has a string $a$. In each step Dreamoon can choose a \\textbf{beautiful} substring of $a$ and remove it. Then he should concatenate the remaining characters (in the same order).\n\nDreamoon wants to use the smallest number of steps to make $a$ empty. Please help Dreamoon, and print any sequence of the smallest number of steps to make $a$ empty.",
    "tutorial": "Denoting a string of length two which contains two $i$-th letter as $t_i$. For example, $t_0$ is \"aa\", $t_1$ is \"bb\" . And let $c_i$ be the occurrence count of $t_i$ as a substring in $a$. For example, when $a =$ \"aaabbcaa\", $c_0 = 3, c_1 = 1$, and for other $i$, $c_i = 0$. In this problem, if only asking contestants output the smallest number of steps to make $a$ empty, the answer is simple. You just need to output $\\max(\\left \\lceil\\frac{\\sum c_i}{2} \\right\\rceil,\\max_{0 \\le i \\le 25}\\limits{c_i})+1$. (I will call this fomula for a given string $a$ as $f(a)$ behind.) Firstly, let's see how the value of all $c_i$ change in one step. There are only four kinds of possible change for all $c_i$. 1. For some $i$, $c_i$ is decreased by one. For example, deleting the first two letters of \"abb\". 2. For two different values $i$ and $j$. $c_i$ and $c_j$ are both decrease by one. For example, deleting the second and third letter of \"aabb\". 3. Nothing changes for all $c_i$. For example, deleting the first letter from \"abb\". 4. For some $i$, $c_i$ is added by one. For example, deleting the second letter from \"aba\". Now, Let's consider how will these changes affect the $f(a)$. Amazing! All possible changes will decrease the value of $f(a)$ at most one! So if we can construct an algorithm to achieve it, then we solve it. Now I introduce an algorithm of which time complexity is $O(n)$. The algorithm can be divided into three phases. 1. In this phase, we maintain a stack that stores the position of substring $t_i$ in the current string from left to right. When we iterate to a string $t_i$, there are two cases. Assum the top element in the stack is $t_j$. When $i$ is equal to $j$, we just add t_i into the stack. But if $i \\ne j$, we do a step that removing all letters from the second letter of $t_j$ to the first letter of $t_i$. and pop $t_j$ from the stack. If there is any moment that $\\left \\lceil\\frac{\\sum c_i}{2} \\right\\rceil \\le \\max_{0 \\le i \\le 25}\\limits{c_i})+1$ is hold (So maybe you won't do anything in this phase), the phase will be terminated. 2. In this phase, there must be an unique $x$ satisifying $c_x \\ge \\left \\lceil\\frac{\\sum c_i}{2} \\right\\rceil$. we also maintain a stack that stores the position of substring $t_i$ in the current string from left to right. But when we iterate to a string $t_i$, the action we should do are different from the first phase. Assum the top element in the stack is $t_j$. When there is exactly one number among $i$ and $j$ is $x$, we do a step that removing all letters from the second letter of $t_j$ to the first letter of $t_i$. and pop $t_j$ from the stack. Otherwise, we just add $t_i$ into the stack. 3. When the algorithm enters the phase, for all $i$ except $x$, $c_i$ will be $0$. So we can use all occurrence of $t_x$ to divide the string into $c_x+1$ segment and remove each segment one by on. After that the string will become empty. Please see the reference code for the implementation detail.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int SIZE = 2e5+10;\nchar s[SIZE];\nint cnt[SIZE];\nint cc[26];\nint all_cnt;\nint ma;\nvoid update_ma() {\n    while(ma > 0 && !cnt[ma]) ma--;\n}\nvoid dec1(int id) {\n    cnt[cc[id]]--;\n    cc[id]--;\n    cnt[cc[id]]++;\n}\npair<int, int> stk[SIZE];\nint sn;\nint m;\nint now;\nint last_len;\nvoid add(int i, bool flag) {\n    if(flag) {\n        dec1(stk[sn - 1].second);\n        dec1(stk[i].second);\n        all_cnt -= 2;\n        printf(\"%d %d\\n\",now + 1, now + stk[i].first);\n        update_ma();\n        sn--;\n        now -= stk[sn].first;\n        if(i + 1 < m) {\n            stk[i + 1].first += stk[sn].first;\n        }\n        else{\n            last_len += stk[sn].first;\n        }\n    }\n    else {\n        stk[sn++] = stk[i];\n        now += stk[i].first;\n    }\n}\nvoid solve(){\n    scanf(\"%s\", s);\n    int n = strlen(s);\n    all_cnt = 0;\n    int lt = 0;\n    m = 0;\n    for(int i = 1; i < n; i++) {\n        if(s[i] == s[i - 1]) {\n            cc[s[i] - 'a']++;\n            all_cnt++;\n            stk[m++] = make_pair(i - lt, (int)(s[i] - 'a'));\n            lt = i;\n        }\n    }\n    last_len = n - lt;\n    ma = 0;\n    for(int i = 0; i < 26; i++) {\n        cnt[cc[i]]++;\n        ma = max(ma, cc[i]);\n    }\n    printf(\"%d\\n\", 1 + max(ma, (all_cnt + 1) / 2));\n    if(ma * 2 < all_cnt) {\n        sn = now = 0;\n        for(int i = 0; i < m; i++) {\n            add(i, sn && stk[sn - 1].second != stk[i].second && ma * 2 < all_cnt);\n        }\n        m = sn;\n    }\n    int main_id = -1;\n    for(int i = 0; i < 26; i++) {\n        if(cc[i] == ma) main_id = i;\n    }\n    sn = now = 0;\n    for(int i = 0; i < m; i++) {\n        add(i, sn && ((stk[sn - 1].second == main_id) ^ (stk[i].second == main_id)));\n    }\n    for(int i = 0; i < sn; i++) {\n        printf(\"%d %d\\n\",1 ,stk[i].first);\n    }\n    printf(\"%d %d\\n\", 1, last_len);\n    memset(cc, 0, sizeof(cc));\n    memset(cnt, 0, sizeof(int) * (ma + 1));\n}\nint main(){\n    int T;\n    scanf(\"%d\", &T);\n    for(int i = 1; i <= T; i++) solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1329",
    "index": "E",
    "title": "Dreamoon Loves AA",
    "statement": "There is a string of length $n+1$ of characters 'A' and 'B'. The first character and last character of the string are equal to 'A'.\n\nYou are given $m$ indices $p_1, p_2, \\ldots, p_m$ ($0$-indexation) denoting the other indices of characters 'A' in the string.\n\nLet's denote the minimum distance between two neighboring 'A' as $l$, and maximum distance between neighboring 'A' as $r$.\n\nFor example, $(l,r)$ of string \"ABBAABBBA\" is $(1,4)$.\n\nAnd let's denote the \\textbf{balance degree} of a string as the value of $r-l$.\n\nNow Dreamoon wants to change exactly $k$ characters from 'B' to 'A', and he wants to make the \\textbf{balance degree} of the string as small as possible.\n\nPlease calculate the required minimum possible value of balance degree.",
    "tutorial": "The idea of this problem comes to my brain when I recall that I'm cooking and I want to cut a carrot into many pieces and make the size of each piece as evenly as possible. I think this problem is very interesting. So that's why I determine to prepare a Codeforces contest after so many years. I hope I can share this problem with as many people as possible. There are some methods to solve this problem. I only show the most beautiful one below. This method is given by isaf27 (And most AC users solve it with this method. I admire them very much). Firstly, we translate the problem into a more convenient model. Let $p_{m+1} = n$, $a_i = p_i - p_{i-1}$ ($1 \\le i \\le m+1$), $M = m + 1$, and $K = m + 1 + k$. Then the problem is equivalent to we want to do integer partition on $M$ integers $a_1, a_2, \\ldots, a_M$, such that $a_i$ is divided into $d_i$ positive integers where $\\sum d_i = K$. Our target is to minimize the difference between the largest integer and smallest integer after division. An important observation is, we always can achieve our target by making the difference of the largest integer and the smallest integer that is divided from the same integer is at most one. So our target is minimizing $\\max_{1 \\le i \\le M}\\limits{(\\left\\lceil \\frac{a_i}{d_i} \\right \\rceil)} - \\min_{1 \\le i \\le M}\\limits{(\\left\\lfloor \\frac{a_i}{d_i} \\right \\rfloor)}$ where $1 \\le d_i$ and $\\sum_{i=1 \\sim M}\\limits d_i = K$. There are two key values under the constraints $1 \\le d_i$ and $\\sum_{i=1 \\sim M}\\limits d_i = K$, one is the minimum value of $\\max_{1 \\le i \\le M}\\limits{(\\left\\lceil \\frac{a_i}{d_i} \\right \\rceil)}$ (Let's call it $U$ after), another is the maximum value of $\\min_{1 \\le i \\le M}\\limits{(\\left\\lfloor \\frac{a_i}{d_i} \\right \\rfloor)}$ (Let's call it $D$ after). $L$ and $U$ can be calculated by binary searching with time complexity $O(M log M)$. (This part is relatively easy so I won't mention it here.) There are two conditions after calculating $L$ and $U$. One is, for all valid $i$, there exists at least one positive integer $d_i$ such that $L \\le \\left\\lfloor \\frac{a_i}{d_i} \\right \\rfloor \\le \\left\\lceil \\frac{a_i}{d_i} \\right \\rceil \\le U$. In this case, the answer is just $U - L$. proof is as below. Let $du_i$ as the largest positive integer such that $L \\le \\left\\lfloor \\frac{a_i}{d_i} \\right \\rfloor$ and $dl_i$ as the smallest positive integer such that $\\left\\lceil \\frac{a_i}{d_i} \\right \\rceil \\le U$. By the define of $L$ and $U$, we can get $\\sum\\limits_{i=1 \\sim M} du_i \\ge K$ and $\\sum\\limits_{i=1 \\sim M} dl_i \\le K$. So we always can choose some d_i where $d_l \\le d_i \\le d_u$ such that $\\sum\\limits_{i=1 \\sim M} d_i = K$ and $L \\le \\left\\lfloor \\frac{a_i}{d_i} \\right \\rfloor \\le \\left\\lceil \\frac{a_i}{d_i} \\right \\rceil \\le U$. Now the essential condition is resolved. Another condition is there are some indices $i$ that we cannot find any positive integer $d_i$ such that $L \\le \\left\\lfloor \\frac{a_i}{d_i} \\right \\rfloor \\le \\left\\lceil \\frac{a_i}{d_i} \\right \\rceil \\le U$. Let's call the set of these indices as $I$. For each element $j \\in I$, let's calculate another two key values for index $j$. That is, we want to know the closest two values of $\\frac{a_j}{d_j}$ near to range $[L, U]$ (one is above $[L,U]$ another is below $[L,U]$). Formulaically say, let $v$ be the smallest $d_j$ such that $\\left\\lfloor \\frac{a_j}{d_j} \\right \\rfloor < L$ and call $\\left\\lfloor \\frac{a_j}{v} \\right \\rfloor$ as $x_j$. And let $u$ be the largest $d_j$ such that $\\left\\lceil \\frac{a_j}{d_j} \\right \\rceil > U$ and call $\\left\\lceil \\frac{a_j}{u} \\right \\rceil$ as $y_j$. Imaging we have a set $S$ initially contains two positive integer $L$ and $U$. Now for each $j \\in I$, we want to choose either $x_i$ or $y_i$ to add to $S$. Then the minimum possbile value of difference between largest element and smallest element in $S$ is the answer in this condition. The minimum possible value can be calculated as below. Initially, for all $j \\in I$, we choose $y_j$ to add to the set $S$. Then iterate from largest $y_j$ to smallest $y_j$. In each iteration, we remove $y_j$ from $S$ and add $x_j$ to $S$. The minimum possible value will exist during the process. These steps can also be done in time complexity $O(M log M)$. The proof of correctness of the second condition is almost same as the first condition. We always can adjust $d_i$ such that $\\sum\\limits_{i=1 \\sim M} d_i$ equal to $K$ for constructed result. The overall time complexity is $O(m log m)$ for the above method. In the end, I want to thanks everyone who takes part in this contest. The worth of the contest will reveal on you, when you learn thing from these problems. Thanks a lot.",
    "code": "/*{{{*/\n#include<cstdio>\n#include<cstdlib>\n#include<cstring>\n#include<cmath>\n#include<algorithm>\n#include<string>\n#include<iostream>\n#include<sstream>\n#include<set>\n#include<map>\n#include<queue>\n#include<bitset>\n#include<vector>\n#include<limits.h>\n#include<assert.h>\n#define SZ(X) ((int)(X).size())\n#define ALL(X) (X).begin(), (X).end()\n#define REP(I, N) for (int I = 0; I < (N); ++I)\n#define REPP(I, A, B) for (int I = (A); I < (B); ++I)\n#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)\n#define FORS(I, S) for (int I = 0; S[I]; ++I)\n#define RS(X) scanf(\"%s\", (X))\n#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))\n#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())\n#define CASET int ___T; scanf(\"%d\", &___T); for(int cs=1;cs<=___T;cs++)\n#define MP make_pair\n#define PB push_back\n#define MS0(X) memset((X), 0, sizeof((X)))\n#define MS1(X) memset((X), -1, sizeof((X)))\n#define LEN(X) strlen(X)\n#define F first\n#define S second\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\ntypedef long double LD;\ntypedef pair<int,int> PII;\ntypedef vector<int> VI;\ntypedef vector<LL> VL;\ntypedef vector<PII> VPII;\ntypedef pair<LL,LL> PLL;\ntypedef vector<PLL> VPLL;\ntemplate<class T> void _R(T &x) { cin >> x; }\nvoid _R(int &x) { scanf(\"%d\", &x); }\nvoid _R(LL &x) { scanf(\"%lld\", &x); }\nvoid _R(double &x) { scanf(\"%lf\", &x); }\nvoid _R(char &x) { scanf(\" %c\", &x); }\nvoid _R(char *x) { scanf(\"%s\", x); }\nvoid R() {}\ntemplate<class T, class... U> void R(T &head, U &... tail) { _R(head); R(tail...); }\ntemplate<class T> void _W(const T &x) { cout << x; }\nvoid _W(const int &x) { printf(\"%d\", x); }\nvoid _W(const LL &x) { printf(\"%lld\", x); }\nvoid _W(const double &x) { printf(\"%.16f\", x); }\nvoid _W(const char &x) { putchar(x); }\nvoid _W(const char *x) { printf(\"%s\", x); }\ntemplate<class T,class U> void _W(const pair<T,U> &x) {_W(x.F); putchar(' '); _W(x.S);}\ntemplate<class T> void _W(const vector<T> &x) { for (auto i = x.begin(); i != x.end(); _W(*i++)) if (i != x.cbegin()) putchar(' '); }\nvoid W() {}\ntemplate<class T, class... U> void W(const T &head, const U &... tail) { _W(head); putchar(sizeof...(tail) ? ' ' : '\\n'); W(tail...); }\n#ifdef HOME\n #define DEBUG(...) {printf(\"# \");printf(__VA_ARGS__);puts(\"\");}\n#else\n #define DEBUG(...)\n#endif\nint MOD = 1e9+7;\nvoid ADD(LL& x,LL v){x=(x+v)%MOD;if(x<0)x+=MOD;}\n/*}}}*/\nconst int SIZE = 1e6+10;\nLL a[SIZE],num[SIZE];\nbool done[SIZE],be_added[SIZE];\nint n;\nLL K;\nLL get_upper_bound(int i){\n    LL v=a[i]/num[i];\n    if(v*num[i]!=a[i])v++;\n    return v;\n}\nLL get_next_upper_bound(int i){\n    LL v=a[i]/(num[i]-1);\n    if(v*(num[i]-1)!=a[i])v++;\n    return v;\n}\nLL go(){\n    if(K==n){\n        return a[n-1]-a[0];\n    }\n    LL ll=1,rr=a[n-1];\n    while(ll<rr){\n        LL mm=(ll+rr)/2;\n        LL need=0;\n        REP(i,n){\n            if(a[i]>mm)need+=a[i]/mm;\n            else need++;\n        }\n        if(need>=K)ll=mm+1;\n        else rr=mm;\n    }\n    LL low=ll;\n    VPLL pp;\n    LL need=0;\n    REP(i,n){\n        if(a[i]>=low){\n            num[i]=a[i]/low;\n            pp.PB({a[i]/(num[i]+1),i});\n        }\n        else {\n            num[i]=1;\n        }\n        need+=num[i];\n    }\n    {\n        bool fail=0;\n        REP(i,n){\n            if(get_upper_bound(i)>=low){\n                fail=1;\n                break;\n            }\n        }\n        if(!fail) return low-1-min(low-1,a[0]);\n    }\n    REP(i,n){\n        if(a[i]>=low&&a[i]/(num[i]+1)==low-1){\n            LL v=a[i]/(low-1);\n            LL mi=min(v-num[i],K-need);\n            num[i]+=mi;\n            need+=mi;\n            if(need==K)break;\n        }\n    }\n    priority_queue<PLL,VPLL,greater<PLL>>added;\n    priority_queue<PLL>top;\n    LL mi=a[0];\n    REP(i,n){\n        if(num[i]>1){\n            added.push(MP(get_next_upper_bound(i),i));\n        }\n        top.push(MP(get_upper_bound(i),i));\n        mi=min(mi,a[i]/num[i]);\n    }\n    LL an=top.top().F-mi;\n    REP(i,n)be_added[i]=done[i]=0;\n    LL ma=low-1;\n    while(!top.empty()&&!added.empty()){\n        int id=top.top().S;\n        if(be_added[id])break;\n        done[id]=1;\n        top.pop();\n        num[id]++;\n        mi=min(mi,a[id]/num[id]);\n        auto tmp=added.top();\n        added.pop();\n        if(done[tmp.S])break;\n        be_added[tmp.S]=1;\n        num[tmp.S]--;\n        if(num[tmp.S]>1)added.push({get_next_upper_bound(tmp.S),tmp.S});\n        ma=max(ma,tmp.F);\n        an=min(an,(top.empty()?ma:max(ma,top.top().F))-mi);\n    }\n    return an;\n}\nvoid solve(){\n    LL L;\n    //R(n,K,L);\n    R(L,n,K);\n    K+=n+1;\n    LL lt=0;\n    REP(i,n){\n        LL x;\n        R(x);\n        a[i]=x-lt;\n        lt=x;\n    }\n    a[n++]=L-lt;\n    sort(a,a+n);\n    W(go());\n}\nint main(){\n    CASET{\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1330",
    "index": "A",
    "title": "Dreamoon and Ranking Collection",
    "statement": "Dreamoon is a big fan of the Codeforces contests.\n\nOne day, he claimed that he will collect all the places from $1$ to $54$ after two more rated contests. It's amazing!\n\nBased on this, you come up with the following problem:\n\nThere is a person who participated in $n$ Codeforces rounds. His place in the first round is $a_1$, his place in the second round is $a_2$, ..., his place in the $n$-th round is $a_n$.\n\nYou are given a positive non-zero integer $x$.\n\nPlease, find the largest $v$ such that this person can collect all the places from $1$ to $v$ after $x$ more rated contests.\n\nIn other words, you need to find the largest $v$, such that it is possible, that after $x$ more rated contests, for each $1 \\leq i \\leq v$, there will exist a contest where this person took the $i$-th place.\n\nFor example, if $n=6$, $x=2$ and $a=[3,1,1,5,7,10]$ then answer is $v=5$, because if on the next two contest he will take places $2$ and $4$, then he will collect all places from $1$ to $5$, so it is possible to get $v=5$.",
    "tutorial": "The total number of rounds this person participates after $x$ more rated contests is $n+x$. So the number of places this person collects cannot exceed $n + x$. Then we can iterate $k$ from $n+x$ to $1$. In each iteration, let $r$ be the number of integers from $1$ to $k$ which doesn't appear in $a_i$. This person can collect all places from $1$ to $k$ if only if $r \\le x$. So the answer is the first $k$ meeting the condition $r \\le x$ when iterating. The solution can be implemented in time complexity $O((n+x)^2)$ as a reference solution. There are also many $O(n)$ solutions that can solve this problem. But in the experience of author and testers, it's easy to make some mistake in the detail when writing $O(n)$ solution : ) Please try it by yourself.",
    "code": "#include<cstdio>\nconst int MAX_V = 201;\nbool achieve[MAX_V];\nvoid solve() {\n    int n, x;\n    scanf(\"%d%d\", &n, &x);\n    for(int i = 1; i <= n + x; i++) {\n        achieve[i] = false;\n    }\n    for(int i = 1; i <= n; i++) {\n        int ranking;\n        scanf(\"%d\", &ranking);\n        achieve[ranking] = true;\n    }\n    for(int k = n + x; k > 0; k--) {\n        int v = 0;\n        for(int i = 1; i <= k; i++) {\n            if(!achieve[i]) v++;\n        }\n        if(v <= x) {\n            printf(\"%d\\n\", k);\n            return;\n        }\n    }\n}\nint main() {\n    int T;\n    scanf(\"%d\", &T);\n    while(T--) solve();\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1330",
    "index": "B",
    "title": "Dreamoon Likes Permutations",
    "statement": "The sequence of $m$ integers is called the permutation if it contains all integers from $1$ to $m$ exactly once. The number $m$ is called the length of the permutation.\n\nDreamoon has two permutations $p_1$ and $p_2$ of non-zero lengths $l_1$ and $l_2$.\n\nNow Dreamoon concatenates these two permutations into another sequence $a$ of length $l_1 + l_2$. First $l_1$ elements of $a$ is the permutation $p_1$ and next $l_2$ elements of $a$ is the permutation $p_2$.\n\nYou are given the sequence $a$, and you need to find two permutations $p_1$ and $p_2$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)",
    "tutorial": "Let $ma$ be the maximum value of all elements in $a$ . If you can recover the the array $a$ to two permutations $p1$ abd $p2$, then $ma$ must be $\\max(len1, len2)$. So there are at most two case: 1. $len1 = ma, len2 = n - ma$, 2. $len1 = n - ma, len2 = ma$. We can check the two cases separately with time complexity $O(n)$. Please see the example code for detail.",
    "code": "#include<cstdio>\nconst int SIZE = 200000;\nint p[SIZE];\nint ans[SIZE][2];\nint ans_cnt;\nbool judge(int a[], int n){\n    static int used[SIZE+1];\n    for(int i = 1; i <= n; i++) used[i] = 0;\n    for(int i = 0; i < n; i++) used[a[i]] = 1;\n    for(int i = 1; i <= n; i++) {\n        if(!used[i]) return 0;\n    }\n    return 1;\n}\nbool judge(int len1, int n){\n    return judge(p, len1) && judge(p + len1, n - len1);\n}\nint main() {\n    int t = 0;\n    scanf(\"%d\", &t);\n    while(t--) {\n        ans_cnt = 0;\n        int n;\n        scanf(\"%d\", &n);\n        int ma=0;\n        for(int i = 0; i < n; i++) {\n            scanf(\"%d\", &p[i]);\n            if(ma < p[i]) ma = p[i];\n        }\n        if(judge(n - ma,n)) {\n            ans[ans_cnt][0] = n - ma;\n            ans[ans_cnt++][1] = ma;\n        }\n        if(ma * 2 != n && judge(ma,n)) {\n            ans[ans_cnt][0] = ma;\n            ans[ans_cnt++][1] = n - ma;\n        }\n        printf(\"%d\\n\", ans_cnt);\n        for(int i = 0; i < ans_cnt; i++) {\n            printf(\"%d %d\\n\", ans[i][0], ans[i][1]);\n        }\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1332",
    "index": "A",
    "title": "Exercising Walk",
    "statement": "Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!\n\nInitially, Alice's cat is located in a cell $(x,y)$ of an infinite grid. According to Alice's theory, cat needs to move:\n\n- exactly $a$ steps left: from $(u,v)$ to $(u-1,v)$;\n- exactly $b$ steps right: from $(u,v)$ to $(u+1,v)$;\n- exactly $c$ steps down: from $(u,v)$ to $(u,v-1)$;\n- exactly $d$ steps up: from $(u,v)$ to $(u,v+1)$.\n\nNote that the moves can be performed in an \\textbf{arbitrary order}. For example, if the cat has to move $1$ step left, $3$ steps right and $2$ steps down, then the walk right, down, left, right, right, down is valid.\n\nAlice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is \\textbf{always} in the area $[x_1,x_2]\\times [y_1,y_2]$, i.e. for every cat's position $(u,v)$ of a walk $x_1 \\le u \\le x_2$ and $y_1 \\le v \\le y_2$ holds.\n\nAlso, note that the cat can visit the same cell multiple times.\n\nCan you help Alice find out if there exists a walk satisfying her wishes?\n\nFormally, the walk should contain exactly $a+b+c+d$ unit moves ($a$ to the left, $b$ to the right, $c$ to the down, $d$ to the up). Alice can do the moves in \\textbf{any} order. Her current position $(u, v)$ should \\textbf{always} satisfy the constraints: $x_1 \\le u \\le x_2$, $y_1 \\le v \\le y_2$. The staring point is $(x, y)$.\n\nYou are required to answer $t$ test cases \\textbf{independently}.",
    "tutorial": "The key observation is x-axis and y-axis is independent in this task as the area is a rectangle. Therefore, we should only consider 1D case (x-axis, for example). The optimal path to choose alternates between right and left moves until only one type of move is possible. And sometimes there is no place to make even one move, which has to handled separately. So the verdict is \"Yes\" if and only if $x_1 \\le x-a+b \\le x_2$ and ($x_1<x_2$ or $a+b=0$).",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint a,b,c,d,x,y,x1,y1,x2,y2,xx,yy;\n\nint main(){\n    int t;\n    cin>>t;\n    while (t--){\n        cin>>a>>b>>c>>d;\n        cin>>x>>y>>x1>>y1>>x2>>y2;\n        xx=x,yy=y;\n        x+=-a+b, y+=-c+d;\n        if (x>=x1&&x<=x2&&y>=y1&&y<=y2&&(x2>x1||a+b==0)&&(y2>y1||c+d==0)){\n            cout<<\"Yes\\n\";\n        }\n        else{\n            cout<<\"No\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1332",
    "index": "B",
    "title": "Composite Coloring",
    "statement": "A positive integer is called composite if it can be represented as a product of two positive integers, both greater than $1$. For example, the following numbers are composite: $6$, $4$, $120$, $27$. The following numbers aren't: $1$, $2$, $3$, $17$, $97$.\n\nAlice is given a sequence of $n$ composite numbers $a_1,a_2,\\ldots,a_n$.\n\nShe wants to choose an integer $m \\le 11$ and color each element one of $m$ colors from $1$ to $m$ so that:\n\n- for each color from $1$ to $m$ there is at least one element of this color;\n- each element is colored and colored exactly one color;\n- the greatest common divisor of any two elements that are colored the same color is greater than $1$, i.e. $\\gcd(a_i, a_j)>1$ for each pair $i, j$ if these elements are colored the same color.\n\nNote that equal elements can be colored different colors — you just have to choose one of $m$ colors for each of the indices from $1$ to $n$.\n\nAlice showed already that if all $a_i \\le 1000$ then she can always solve the task by choosing some $m \\le 11$.\n\nHelp Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some $m$ from $1$ to $11$.",
    "tutorial": "The solution is obvious once one note that for any composite number $k$, there exists a prime $d$ such that $d \\le \\sqrt{k}$ and $k$ is divisible by $d$. Coincidentally, there are exactly $11$ primes below $\\sqrt{1000}$. Thus, one can color balls according to their smallest divisor. That works because if all numbers of the same color have the same divisor then each pair has at least this divisor in their GCD.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint n,t;\nvector<int> ans[1007];\nint res[1007];\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    auto f=[&](int u){\n        for (int i=2;i<=u;++i){\n            if (u%i==0) return i;\n        }\n    };\n    cin>>t;\n    while (t--){\n        cin>>n;\n        for (int i=1;i<=1000;++i) ans[i].clear();\n        for (int i=1;i<=n;++i){\n           int u;\n           cin>>u; ans[f(u)].push_back(i);\n        }\n        int ret=0;\n        for (int i=1;i<=1000;++i){\n            if (ans[i].size()){\n                ++ret;\n                for (auto c:ans[i]){\n                    res[c]=ret;\n                }\n            }\n        }\n        cout<<ret<<\"\\n\";\n        for (int i=1;i<=n;++i){\n            cout<<res[i]<<\" \";\n        }\n        cout<<\"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1332",
    "index": "C",
    "title": "K-Complete Word",
    "statement": "Word $s$ of length $n$ is called $k$-complete if\n\n- $s$ is a palindrome, i.e. $s_i=s_{n+1-i}$ for all $1 \\le i \\le n$;\n- $s$ has a period of $k$, i.e. $s_i=s_{k+i}$ for all $1 \\le i \\le n-k$.\n\nFor example, \"abaaba\" is a $3$-complete word, while \"abccba\" is not.\n\nBob is given a word $s$ of length $n$ consisting of only lowercase Latin letters and an integer $k$, such that $n$ is divisible by $k$. He wants to convert $s$ to any $k$-complete word.\n\nTo do this Bob can choose some $i$ ($1 \\le i \\le n$) and replace the letter at position $i$ with some other lowercase Latin letter.\n\nSo now Bob wants to know the minimum number of letters he has to replace to convert $s$ to any $k$-complete word.\n\nNote that Bob can do zero changes if the word $s$ is already $k$-complete.\n\nYou are required to answer $t$ test cases \\textbf{independently}.",
    "tutorial": "One should notice that word $s$ of length $n$ is $k$-complete if and only if there exists a palindrome $t$ of length $k$ such that $s$ can be generated by several concatenations of $t$. So in the final string all characters at positions $i$, $k - i + 1$, $k + i$, $2k - i + 1$, $2k + i$, $3k - i + 1$, $\\dots$ for all $1 \\le i \\le k$ should all be equal. This helps us to solve the problem independently for each $i$. To minimize the required number of changes, you should make all the letters equal to the one which appears at these positions the most initially. Calculate that maximum number of appearances and sum up over all $i$. Be careful with an odd $k$ because the letter in the center of each block has a different formula.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int maxn=200007;\n\nint n,k,ans=0;\nint cnt[maxn][26];\nstring s;\n\nint differ(int u,int v){\n    int ret=0,mx=0;\n    for (int j=0;j<26;++j){\n        ret+=cnt[u][j]+cnt[v][j];\n        mx=max(mx,cnt[u][j]+cnt[v][j]);\n    }\n    return ret-mx;\n}\n\nint main(){\n    int t;\n    cin>>t;\n    while (t--){\n        cin>>n>>k>>s;\n        for (int i=0;i<k;++i){\n            for (int j=0;j<26;++j){\n                cnt[i][j]=0;\n            }\n        }\n        for (int i=0;i<n;++i){\n            cnt[i%k][s[i]-'a']++;\n        }\n        int ans=0;\n        for (int i=0;i<k;++i){\n            ans+=differ(i,k-1-i);\n        }\n        cout<<ans/2<<\"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1332",
    "index": "D",
    "title": "Walk on Matrix",
    "statement": "Bob is playing a game named \"Walk on Matrix\".\n\nIn this game, player is given an $n \\times m$ matrix $A=(a_{i,j})$, i.e. the element in the $i$-th row in the $j$-th column is $a_{i,j}$. Initially, player is located at position $(1,1)$ with score $a_{1,1}$.\n\nTo reach the goal, position $(n,m)$, player can move right or down, i.e. move from $(x,y)$ to $(x,y+1)$ or $(x+1,y)$, as long as player is still on the matrix.\n\nHowever, each move changes player's score to the bitwise AND of the current score and the value at the position he moves to.\n\nBob can't wait to find out the maximum score he can get using the tool he recently learnt  — dynamic programming. Here is his algorithm for this problem.\n\nHowever, he suddenly realize that the algorithm above fails to output the maximum score for some matrix $A$. Thus, for any given non-negative integer $k$, he wants to find out an $n \\times m$ matrix $A=(a_{i,j})$ such that\n\n- $1 \\le n,m \\le 500$ (as Bob hates large matrix);\n- $0 \\le a_{i,j} \\le 3 \\cdot 10^5$ for all $1 \\le i\\le n,1 \\le j\\le m$ (as Bob hates large numbers);\n- the difference between the maximum score he can get and the output of his algorithm is \\textbf{exactly} $k$.\n\nIt can be shown that for any given integer $k$ such that $0 \\le k \\le 10^5$, there exists a matrix satisfying the above constraints.\n\nPlease help him with it!",
    "tutorial": "In fact, the following matrix will work: $\\left( \\begin{array}{ccc} 2^{17}+k & 2^{17} & 0\\\\ k & 2^{17}+k & k\\\\ \\end{array} \\right)$ To find such a matrix, one should find out why the dp solution fails. One should notice that $dp_{2,2}=\\max(a_{1,1}\\&a_{1,2}\\&a_{2,2},a_{1,1}\\&a_{2,1}\\&a_{2,2})$ and dp solution will choose the optimal path from $(1,1)$ to $(2,2)$ for later decision. However, we should notice that we can only discard the suboptimal result if and only if $ans_{suboptimal} \\& ans_{optimal}=ans_{suboptimal}$ rather than $ans_{suboptimal} < ans_{optimal}$. Based on above analysis, we can construct the matrix easily. In fact, even if $n,m$ is fixed satisfying that $n \\ge 2,m \\ge 2$ and $n\\cdot m>4$, we could easily construct a matrix for a given $k$ based on our $2 \\times 3$ matrix.",
    "code": "k = int(input())\nx = 2**17\nprint(2, 3)\nprint(x^k, x, 0)\nprint(k, x^k, k)",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1332",
    "index": "E",
    "title": "Height All the Same",
    "statement": "Alice has got addicted to a game called Sirtet recently.\n\nIn Sirtet, player is given an $n \\times m$ grid. Initially $a_{i,j}$ cubes are stacked up in the cell $(i,j)$. Two cells are called adjacent if they share a side. Player can perform the following operations:\n\n- stack up one cube in two \\textbf{adjacent} cells;\n- stack up two cubes in one cell.\n\nCubes mentioned above are identical in height.\n\nHere is an illustration of the game. States on the right are obtained by performing one of the above operations on the state on the left, and grey cubes are added due to the operation.\n\nPlayer's goal is to \\textbf{make the height of all cells the same} (i.e. so that each cell has the same number of cubes in it) using above operations.\n\nAlice, however, has found out that on some starting grids she may never reach the goal no matter what strategy she uses. Thus, she is wondering the number of initial grids such that\n\n- $L \\le a_{i,j} \\le R$ for all $1 \\le i \\le n$, $1 \\le j \\le m$;\n- player can reach the goal using above operations.\n\nPlease help Alice with it. Notice that the answer might be large, please output the desired value modulo $998,244,353$.",
    "tutorial": "Observation 1. The actual values in the cells don't matter, only parity matters. Proof. Using the second operation one can make all the values of same parity equal by applying it to the lowest value until done. That observation helps us to get rid of the second operation, let us only have the first one. Observation 2. Player is able to change parity of any pair of cells at the same time. Proof. For any given cell $u$ and cell $v$, there exists a path from $u$ to $v$, namely $p=w_0w_1\\ldots w_k$, such that $w_0=u$ and $w_n=v$. Perform operation for adjacent cells $w_{i-1}$ and $w_{i}$ for all $1 \\le i \\le n$ Observation 3. If $n \\times m$ is odd, player can always reach the goal no matter what the initial state is. Proof. There are two cases: there is an even number of even cells or there is an even number of odd cells. Whichever of these holds, we can change all cells of that parity to the opposite one with the aforementioned operation, making all cells the same parity. Observation 4. If $n \\times m$ is even, and $\\sum_{i=1}^n \\sum_{j=1}^m a_{i,j}$ is even, player can reach the goal. Proof. Similar to the proof of Observation 3. Proof is omitted. Observation 5. If $n \\times m$ is even and $\\sum_{i=1}^n \\sum_{j=1}^m a_{i,j}$ is odd, player can never reach the goal no matter what strategies player takes. Proof. Note that applying the operation never changes the parity of the number of cells of each parity (i.e. if we start with an odd number of odd cells and an odd number of even cells, they will both be odd until the end). Thus, there is no way to make zero cells of some parity. How does that help us to calculate the answer? The first case ($n \\times m$ is odd) is trivial, the answer is all grids. Let's declare this as $total$ value. The second case ($n \\times m$ is even) is harder. Me and pikmike have different formulas to obtain it but the answer is the same. WLOG, let's move the range of values from $[L; R]$ to $[0; R - L]$, let $k = R - L$. Easy combinatorics solution (me): Let's find out the number of ways to choose the grid such that the number of even cells is even and $0 \\le a_i \\le k$. Suppose that there are $E$ even numbers in $[0,k]$, $O$ odds. Therefore, for any given $0 \\le i \\le nm$, the number of ways to have exactly $i$ even numbers should be $E^i O^{nm-i} \\times \\binom{nm}{i}$. Thus, the total answer should be $\\sum \\limits_{i=0}^{nm/2} E^{2i} O^{nm-2i} \\binom{nm}{2i}$, which should remind you of the Newton expansion. Note that $(E+O)^{nm}=\\sum_{i=0}^{nm/2}E^{2i}O^{nm-2i}\\binom{nm}{2i}+\\sum_{i=1}^{nm/2}E^{2i-1} O^{nm-(2i-1)} \\binom{nm}{2i-1}$ and $(E-O)^{nm}=\\sum_{i=0}^{nm/2}E^{2i}O^{nm-2i}\\binom{nm}{2i}-\\sum_{i=1}^{nm/2}E^{2i-1} O^{nm-(2i-1)} \\binom{nm}{2i-1}$ Adding those two formulas will get us exactly the formula we were looking for but doubled. Thus, the answer is that divided by $2$. Easy intuition solution (pikmike): There is a general solution to this kind of problems. Let's try to pair up each valid grid with exactly one invalid grid. Valid in our problem is such a grid that the number of even cells is even. If such a matching exists then the answer is exactly half of all grids $(\\frac{total}{2})$. Let's come up with some way to pair them up. For example, this works but leaves us with two cases to handle. Let $k$ be odd. For each grid let's replace $a_{0,0}$ with $a_{0,0}~xor~1$. You can see that the parity changed, thus the number of even cells also changed its parity. So if the grid was invalid it became valid and vice versa. For an even $k$ it's slightly trickier but actually one can show that almost all grids pair up with each other and only a single grid remains unpaired. So we can add a fake grid and claim that the answer is $\\frac{total + 1}{2}$. The algorithm is the following. Find the first position such that the value $a_{i,j}$ on it is not equal to $k$. Replace it with $a_{i,j}~xor~1$. You can easily see that only grid that consists of all numbers $k$ has no pair.",
    "code": "MOD = 998244353\n\nn, m, l, r = map(int, input().split())\nif n * m % 2 == 1:\n\tprint(pow(r - l + 1, n * m, MOD))\nelse:\n\te = r // 2 - (l - 1) // 2\t\n\to = (r - l + 1) - e\n\tprint((pow(e + o, n * m, MOD) + pow(e - o, n * m, MOD)) * (MOD + 1) // 2 % MOD)",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math",
      "matrices"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1332",
    "index": "F",
    "title": "Independent Set",
    "statement": "Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.\n\nGiven a graph $G=(V,E)$, an independent set is a subset of vertices $V' \\subset V$ such that for every pair $u,v \\in V'$, $(u,v) \\not \\in E$ (i.e. no edge in $E$ connects two vertices from $V'$).\n\nAn edge-induced subgraph consists of a subset of edges $E' \\subset E$ and all the vertices in the original graph that are incident on at least one edge in the subgraph.\n\nGiven $E' \\subset E$, denote $G[E']$ the edge-induced subgraph such that $E'$ is the edge set of the subgraph. Here is an illustration of those definitions:\n\nIn order to help his students get familiar with those definitions, he leaves the following problem as an exercise:\n\nGiven a tree $G=(V,E)$, calculate the sum of $w(H)$ over all except null edge-induced subgraph $H$ of $G$, where $w(H)$ is the number of independent sets in $H$. Formally, calculate $\\sum \\limits_{\\emptyset \\not= E' \\subset E} w(G[E'])$.\n\nShow Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo $998,244,353$.",
    "tutorial": "We will call one vertice is colored if and only if it is in the independent set. And a coloring is valid if and only if no two adjacent vertices are both colored. Therefore, we are asked to calculate the sum of number of valid colorings over all edge induced subgraphs. To deal with the task, one should notice that for a edge induced subgraph and one valid coloring, we may add those vertices which are removed due to the generation of edge induced subgraph, and remain it uncolored. Therefore, for a coloring on the original graph $G=(V,E)$, we could consider removing edges such that it will behave the same with above procedure. In fact, given a coloring, we can define edge removing is valid if and only if there is no adjacent colored vertice and no isolated vertex is colored. We can actually show that there is almost a one to one corresponding relation betweeen those two procedure except for the case where all vertices remains uncolored and all edges are removed. Therefore, we can actually solve the following task: Given a tree $G=(V,E)$, for any given coloring, define a edge removal is valid if it satisfies above constrains. And it will suddenly becoming something easy to solve with tree dp. Define $dp_{u,0}$ be the answer for subtree rooted at $u$ with additional constraint such that $u$ is not colored, $dp_{u,1}$ be the answer where $u$ is colored and $dp_u$ be the answer where edges from $u$ to its children are removed. Therefore, the dp formula should be $dp_{u,0}=\\prod_{v}(2dp_{v,0}+2dp_{v,1}-dp_v)$ $dp_{u,1}=\\prod_{v}(2dp_{v,0}+dp_{v,1}-dp_v)$ $dp_{u}=\\prod_{v}(dp_{v,0}+dp_{v,1}-dp_v)$ The answer is easily calculated with those three states.",
    "code": "#include<bits/stdc++.h>\n#define int long long\n#define ULL unsigned long long\n#define F first\n#define S second\n#define pb push_back\n#define rep(i,n) for(int i=0;i<(int)(n);++i)\n#define rep1(i,n) for(int i=1;i<=(int)(n);++i)\n#define range(a) a.begin(), a.end()\n#define PI pair<int,int>\n#define VI vector<int>\n#define debug cout<<\"potxdy\"<<endl; \nusing namespace std;\n \ntypedef long long ll;\n \nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nconst int maxn=300007;\nconst int mod=998244353;\n\nint n,dp[maxn][2],f[maxn]; \nVI vec[maxn];\n\nint mult(int u,int v){\n    u=(u%mod+mod)%mod, v=(v%mod+mod)%mod;\n    return 1ll*u*v%mod;\n}\n\nvoid dfs(int u,int p){\n    dp[u][0]=dp[u][1]=f[u]=1;\n    for (auto c:vec[u]){\n        if (c==p) continue;\n        dfs(c,u);\n        dp[u][0]=mult(dp[u][0],2*dp[c][0]+2*dp[c][1]-f[c]);\n        dp[u][1]=mult(dp[u][1],dp[c][1]+2*dp[c][0]-f[c]);\n        f[u]=mult(f[u],dp[c][0]+dp[c][1]-f[c]);\n    }\n}\n\n#undef int\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>n;\n    for (int i=1;i<n;++i){\n        int u,v;\n        cin>>u>>v;\n        vec[u].pb(v), vec[v].pb(u);\n    }\n    dfs(1,0);\n    cout<<(dp[1][0]+dp[1][1]-f[1]-1+2*mod)%mod<<endl;\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1332",
    "index": "G",
    "title": "No Monotone Triples",
    "statement": "Given a sequence of integers $a$ of length $n$, a tuple $(i,j,k)$ is called monotone triples if\n\n- $1 \\le i<j<k\\le n$;\n- $a_i \\le a_j \\le a_k$ or $a_i \\ge a_j \\ge a_k$ is satisfied.\n\nFor example, $a=[5,3,4,5]$, then $(2,3,4)$ is monotone triples for sequence $a$ while $(1,3,4)$ is not.\n\nBob is given a sequence of integers $a$ of length $n$ in a math exam. The exams itself contains questions of form $L, R$, for each of them he is asked to find any subsequence $b$ \\textbf{with size greater than $2$ (i.e. $|b| \\ge 3$)} of sequence $a_L, a_{L+1},\\ldots, a_{R}$.\n\nRecall that an sequence $b$ is a subsequence of sequence $a$ if $b$ can be obtained by deletion of several (possibly zero, or all) elements.\n\nHowever, he hates monotone stuff, and he wants to find a subsequence \\textbf{free from monotone triples}. Besides, he wants to find one subsequence with the \\textbf{largest} length among all subsequences free from monotone triples for every query.\n\nPlease help Bob find out subsequences meeting the above constraints.",
    "tutorial": "We will solve this task with the following observations. Observation 1. If an array $x$ of length $k$ ($k \\ge 3$) has no monotone triple, then one of the following is true: $x_1<x_2>x_3<x_4>x_5<\\ldots$ $x_1>x_2<x_3>x_4<x_5>\\ldots$ Observation 2. If an array $x$ of length $k$ ($k \\ge 4$) has no monotone triple, then its subsequence has no monotone triple. Observation 3. If an array $x$ of length 4 has no monotone triple, then $max(x_2,x_3)>max(x_1,x_4)$, $min(x_2,x_3)<min(x_1,x_4)$,vice versa. Proof. WLOG, we assume $max(x_2,x_3)\\le x_1$, by observation 1 we will know that $x_1>x_2<x_3>x_4$, since $x_1\\ge x_3$, we get a monotone triple $(1,3,4)$, leading to contradiction. Second part can be verified easily. Observation 4. For every array $x$ of length $k$ ($k \\ge 5$), $x$ must have monotone triple. Proof. WLOG, we just need to prove the observation holds when $k=5$ and cases when not all elements are equal. In that case, one of extremal can be reached in position other than $3$. WLOG, we will assume that maximum is reached at position $2$. However, $x_2,x_3,x_4,x_5$ cannot be monotone-triple-free, leading to contradiction! Combining those observations (or Erdos-Szekeres theorem if you know it), we would like to get the following solution, which runs in $O(q n^4)$. If the subsequence is monotone, the answer should be 0. If there exists $i,j,k,l$ such that $L \\le i<j<k<l \\le R$ and $a_i$, $a_l$ fails to reach maximum and minimum among those four numbers, the answer should be 4. Otherwise, the answer should be 3. In the following paragraphs, we will only focus on the case of $4$. Other stuffs can be dealt similarly (or easily). $O(n^2)$ solution(the observation is crucial to obtain a faster solution) Notice that constraint is equivalent to that there exists $i,j$ such that $a_i,a_j$ fails to reach maximum and minimum among $a_i,a_{i+1},\\ldots,a_j$. This observation allows us to solve this task in $O(n^2)$ with some precalculation. (though it's still not enough to get accepted). $O(n \\log n)$ solution Let's solve the task for a sequence of a pairwise distinct numbers and then change the conditions to a general sequence. Let's fix $a_i$ - the leftmost element of $b$ and look at what we are asked to find. So there should be some position $j$ to the right of $i$ so that the range of values on positions $[i, j]$ excluding the greatest and the smallest values includes both $a_i$ and $a_j$. Let's process the array from right to left, maintaining two stacks. The top element in both stacks is the currently processed one. Next element of the first stack is the closest to the right element greater than the top one, and the next element of the second stack is the closest to the right smaller than the top one. And the stacks go like that until the end of array. Iterating over one of these stacks will show the increase of the range of values in one direction, iterating over both at the same time will show how the range of values changes in total. So I claim that the sequence we are looking for exists iff both stacks include more than $1$ element and there is an element to the right of second elements of both stacks such that it is included in neither of the stacks. Naturally that condition tells that there is some position in which neither maximum, nor minimum values are updated. The values that are in neither of stacks can be maintained in a queue or in a BIT. Basically, the position when the range of values doesn't change is such a value which is both smaller than the maximum value on the segment and greater than the minimum one. Thus, we can choose $a_i$, the latest elements in both stacks up to that position and that position itself. How to deal with not pairwise distinct elements? Well, it's enough to change the conditions in stacks to the next greater or equal and the next smaller or equal. However, that will push the elements equal to the current one right next to it to the both stacks. Previously we kinda used the fact that no element except the current one is in both stacks. I think that the easiest way to deal with it is to get the answer for the rightmost of the consecutive equal elements and then just say that the answer for the rest of them is the same. Finally, push all these consecutive equal elements to the both stacks. As for queries. I previously said that we can take the position where the value range doesn't change. Basically, the first valid position is coincidentally the shortest length valid segment starting from $i$. So to find the first position you just need to do a binary search over that queue or BIT of the values which are in neither of the stacks. We can easily remember it for each position and then do a range minimum query checking if any of the positions in $[l, r]$ have their shortest right border smaller than $r$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn=200007;\nint n,q,a[maxn],b[maxn],c[maxn],t[maxn],sum[maxn];\nint st1[maxn],st2[maxn],p1,p2,r1,r2,s1,s2;\nint ans1[maxn][4],ans2[maxn][4];\nset<int> s;\n\nbool cmp1(int u,int v){\n    return a[u]<a[v];\n}\n\nbool cmp2(int u,int v){\n    return a[u]>a[v];\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>n>>q;\n    for (int i=1;i<=n;++i){\n        cin>>a[i];\n    }\n    p1=p2=r1=r2=0;\n    s.insert(n+1);\n    for (int i=n;i>0;--i){\n        while (p1){\n            int u=st1[p1];\n            if (a[u]>a[i]){\n                t[u]--;\n                if (!t[u]) s.insert(u);\n                p1--;\n                r1=0;\n            }\n            else{\n                break;\n            }\n        }\n        while (p2){\n            int u=st2[p2];\n            if (a[u]<a[i]){\n                t[u]--;\n                if (!t[u]) s.insert(u);\n                p2--;\n                r2=0;\n            }\n            else{\n                break;\n            }\n        }\n        s1=lower_bound(st1+1,st1+p1+1,i,cmp1)-st1-1, s2=lower_bound(st2+1,st2+p2+1,i,cmp2)-st2-1;\n        b[i]=i+max(r1,r2)+1;\n        ans1[i][0]=i, ans1[i][1]=b[i]-1, ans1[i][2]=b[i];\n        if (s1&&s2){\n            c[i]=*s.lower_bound(max(st1[s1],st2[s2]));\n            if (c[i]<=n){\n                int u=lower_bound(st1+1,st1+p1+1,c[i],greater<int>())-st1,v=lower_bound(st2+1,st2+p2+1,c[i],greater<int>())-st2;\n                ans2[i][0]=i, ans2[i][1]=min(st1[u],st2[v]), ans2[i][2]=max(st1[u],st2[v]), ans2[i][3]=c[i];\n            }\n        }\n        else{\n            c[i]=n+1;\n        }\n        st1[++p1]=i;\n        st2[++p2]=i;\n        r1++, r2++;\n        t[i]+=2;\n        if (i<n&&b[i]>b[i+1]){\n            b[i]=b[i+1];\n            for (int j=0;j<3;++j){\n                ans1[i][j]=ans1[i+1][j];\n            }\n        }\n        if (i<n&&c[i]>c[i+1]){\n            c[i]=c[i+1];\n            for (int j=0;j<4;++j){\n                ans2[i][j]=ans2[i+1][j];\n            }\n        }\n    }\n    while (q--){\n        int l,r;\n        cin>>l>>r;\n        if (r>=c[l]){\n            cout<<\"4\\n\";\n            for (int j=0;j<4;++j){\n                cout<<ans2[l][j]<<\" \";\n            }\n            cout<<\"\\n\";\n        }\n        else{\n            if (r>=b[l]){\n                cout<<\"3\\n\";\n                for (int j=0;j<3;++j){\n                    cout<<ans1[l][j]<<\" \";\n                }\n                cout<<\"\\n\";\n            }\n            else{\n                cout<<\"0\\n\\n\";\n            }\n        }\n    }\n    return 0;    \n}",
    "tags": [
      "data structures"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1333",
    "index": "A",
    "title": "Little Artem",
    "statement": "Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.\n\nArtem wants to paint an $n \\times m$ board. Each cell of the board should be colored in white or black.\n\nLets $B$ be the number of black cells that have at least one white neighbor adjacent by the side. Let $W$ be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called \\textbf{good} if $B = W + 1$.\n\nThe first coloring shown below has $B=5$ and $W=4$ (all cells have at least one neighbor with the opposite color). However, the second coloring is not \\textbf{good} as it has $B=4$, $W=4$ (only the bottom right cell doesn't have a neighbor with the opposite color).\n\nPlease, help Medina to find any \\textbf{good} coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them.",
    "tutorial": "In this problem it is enough to simply paint the upper left corner white and all the others black for any size of the board Like this: And there are $W=1$ (cell with coordinates $\\{1, 1\\}$) and $B=2$ (cells with coordinates $\\{1, 2\\}$ and $\\{2, 1\\}$). In the first version, the task restrictions were $1 \\le n, m$, but we thought it would be too difficult for div2A.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nvoid solve() {\n    int n, m; cin >> n >> m;\n    string black_row(m, 'B');\n    vector<string> result(n, black_row);\n    result[0][0] = 'W';\n    for (int i = 0; i < n; ++i) {\n        cout << result[i] << '\\n';\n    }\n}\n\n\nint main() {\n    int t; cin >> t;\n    while(t--) solve();\n}\n",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1333",
    "index": "B",
    "title": "Kind Anton",
    "statement": "Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:\n\nThere are two arrays of integers $a$ and $b$ of length $n$. It turned out that array $a$ contains only elements from the set $\\{-1, 0, 1\\}$.\n\nAnton can perform the following sequence of operations any number of times:\n\n- Choose any pair of indexes $(i, j)$ such that $1 \\le i < j \\le n$. It is possible to choose the same pair $(i, j)$ more than once.\n- Add $a_i$ to $a_j$. In other words, $j$-th element of the array becomes equal to $a_i + a_j$.\n\nFor example, if you are given array $[1, -1, 0]$, you can transform it only to $[1, -1, -1]$, $[1, 0, 0]$ and $[1, -1, 1]$ by one operation.\n\nAnton wants to predict if it is possible to apply some number (zero or more) of these operations to the array $a$ so that it becomes equal to array $b$. Can you help him?",
    "tutorial": "First of all, note that we can add an element with index $i$ to an element with index $j$ iff $i < j$. This means that the element $a_n$ cannot be added to any other element because there is no index $j > n$ in the array. This is why we can first equalize the elements $a_n$ and $b_n$. If $a_n = b_n$, they are already equal. If $a_n < b_n$, then we need to have element equal to $1$ along the elements $a$ with indexes $\\{1,..., n-1\\}$. For $a_n > b_n$, we need to have $-1$ along these elements. After the elements with index $n$ become equal, we can go to the element with index $n-1$ and do the same. Then indexes $n-2$, $n-3$, ..., $1$. You can implement this idea yourself! Final time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n), b(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    for (int i = 0; i < n; ++i) {\n        cin >> b[i];\n    }\n    vector<int> good(2, 0);\n    for (int i = 0; i < n; ++i) {\n        if (a[i] > b[i] && !good[0]) {\n            cout << \"NO\\n\";\n            return;\n        } else if (a[i] < b[i] && !good[1]) {\n            cout << \"NO\\n\";\n            return;\n        }\n        if (a[i] == -1) good[0] = 1;\n        if (a[i] == 1) good[1] = 1;\n    }\n    cout << \"YES\\n\";\n}\n\nint main() {\n    int t; cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1333",
    "index": "C",
    "title": "Eugene and an array",
    "statement": "Eugene likes working with arrays. And today he needs your help in solving one challenging task.\n\nAn array $c$ is a subarray of an array $b$ if $c$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\nLet's call a nonempty array \\textbf{good} if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array $[-1, 2, -3]$ is \\textbf{good}, as all arrays $[-1]$, $[-1, 2]$, $[-1, 2, -3]$, $[2]$, $[2, -3]$, $[-3]$ have nonzero sums of elements. However, array $[-1, 2, -1, -3]$ isn't \\textbf{good}, as his subarray $[-1, 2, -1]$ has sum of elements equal to $0$.\n\nHelp Eugene to calculate the number of nonempty \\textbf{good} subarrays of a given array $a$.",
    "tutorial": "Let's solve this problem in $O(n^2 \\times log (n))$for now. Note that if the subarray $[a_i,..., a_j]$ is good, then the subarray $[a_i,..., a_{j-1}]$ is also good, and if the subset $[a_i,..., a_j]$ is not good, then the subarray $[a_i,..., a_{j+1}]$ is not good either. Then for each left border $a_i$ we want to find the rightmost border $a_j$ such that $[a_i,..., a_j]$ is good and add to the answer $j - i + 1$ (subarrays $[a_i, ..., a_j], [a_i, ..., a_{j-1}], ..., [a_i]$) [1]. Let's denote the rightmost border $j$ for border $i$ as $R (i)$. Let's calculate the prefix-sum of the array $P$. $P_0 = 0, P_i = a_1 + .. + a_i, 1 \\le i \\le n$. Note that a subset of $[a_i,..., a_j]$ has a zero sum iff $P_{i-1} = P_j$. Then the subset $[a_i,..., a_j]$ is a good iff sum of prefixes $[P_{i-1},..., P_j]$ has no duplicates [2]. Using [1] and [2], we can simply iterate over $i$ from $0$ to $n$ and over $j$ from $i$ to $n$ and count the set of prefix sums $[P_i,..., P_j]$. The first moment $j_0$ when this set contains duplicates gives us the rightmost border $j_0-1$, and we add $(j_0-1) - i$ (no $+1$, because it is an array of prefix sums) to answer. To improve this solution to $O (n \\times log(n))$, we need to note that $R(i)$ is monotonous over $i$. Now we can iterate over $i$ from $0$ to $n$ and over $j$ from $R (i-1)$ to $n$ uses a set of prefix sums from the previous iteration. Thus we have a solution $O (n \\times log(n))$, because $j$ points to each element of the array exactly once. If you code in C++, it is important not to use std:: unordered_set in this task, but use std::set. One of the participants hacked the solution using std:: unordered_set, using collisions in this structure. I highly recommend you to read this blog for more info https://codeforces.com/blog/entry/62393. Final time complexity: $O(n \\times log(n))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint main() {\n    int n; cin >> n;\n    vector<long long> prefix(n + 1, 0);\n    for (int i = 0; i < n; ++i) {\n        int x; cin >> x;\n        prefix[i + 1] = prefix[i] + x;\n    }\n    int begin = 0, end = 0;\n    long long ans = 0;\n    set<long long> s = {0};\n    while(begin < n) {\n        while(end < n && !s.count(prefix[end + 1])) {\n            ++end;\n            s.insert(prefix[end]);\n        }\n        ans += end - begin;\n        s.erase(prefix[begin]);\n        ++begin;\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1333",
    "index": "D",
    "title": "Challenges in school №41",
    "statement": "There are $n$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.\n\nChildren can do the following: in one second several pairs of neighboring children who are \\textbf{looking at each other} can \\textbf{simultaneously} turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second \\textbf{at least one} pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.\n\nYou are given the number $n$, the initial arrangement of children and the number $k$. You have to find a way for the children to act if they want to finish the process in exactly $k$ seconds. More formally, for each of the $k$ moves, you need to output the numbers of the children who turn left during this move.\n\nFor instance, for the configuration shown below and $k = 2$ children can do the following steps:\n\nAt the beginning, two pairs make move: $(1, 2)$ and $(3, 4)$. After that, we receive the following configuration: At the second move pair $(2, 3)$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $n^2$ \"headturns\".",
    "tutorial": "If solution exist let's count the minimum and maximum bounds for $k$ for initial arrangement of children. A minimum $k$ achieved all possible pairs of children turn theirs heads at every step. The maximum $k$ reached if only one of possible pairs of children turn theirs heads at every step. This values is easy to count, I'll leave it to you! If $k$ from the statement not fit within our bounds, then we need to print $-1$. Otherwise solution exist and we need to construct them. For each next move we can use all pairs of children to turn theirs heads, decrease $k$ by 1 and recalculate maximum bound (lets call it $U$) on $k$ (just decrease them on the number of pairs used). If after moving new value of $k$ fits in the bound ($k \\le U$), then we proceed to the next iteration. Otherwise, we roll back to the previous iteration and use $U - k + 1$ pairs in this move. Number of remaining moves will be $k - 1$ and upper bound will be $U - (U - k + 1) = k - 1$. And from that moment, just use only one pair in one move to the end of the process (to find one of the pair quickly we need to store them in the queue). Final time complexity: $O(n^2)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, k;\n\nvector<int> find_steps(const vector<int>& a) {\n    vector<int> steps;\n    for (int i = 0; i < n - 1; ++i) {\n        if (a[i] == 1 && a[i + 1] == 0) steps.push_back(i);\n    }\n    return steps;\n}\n\n\nint main() {\n    cin >> n >> k;\n    string s; cin >> s;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) a[i] = (s[i] == 'L') ? 0 : 1;\n    int maxi = 0, mini = 0;\n    int cnt = 0;\n    int last = -1;\n    for (int i = n - 1; i >= 0; --i) {\n        if (a[i] == 0) {\n            ++cnt;\n        } else {\n            if (cnt == 0) continue;\n            maxi += cnt;\n            mini = max(cnt, last + 1);\n            last = mini;\n        }\n    }\n    if (k < mini || k > maxi) {\n        cout << -1;\n        return 0;\n    }\n    bool is_min = false;\n    vector<int> have_step;\n    for (int i = 0; i < k; ++i) {\n        if (!is_min) {\n            auto steps = find_steps(a);\n            cout << min(int(steps.size()), maxi - k + i + 1) << ' ';\n            int cur = 0;\n            while (k - i - 1 < maxi && cur < steps.size()) {\n                cout << steps[cur] + 1 << ' ';\n                a[steps[cur]] = 0;\n                a[steps[cur] + 1] = 1;\n                ++cur;\n                --maxi;\n            }\n            if (maxi == k - i - 1) {\n                is_min = true;\n                have_step = find_steps(a);\n            }\n        } else {\n            int v = have_step.back();\n            have_step.pop_back();\n            cout << \"1 \" << v + 1;\n            a[v] = 0;\n            a[v + 1] = 1;\n            if (v > 0 && a[v - 1] == 1) {\n                have_step.push_back(v - 1);\n            }\n            if (v + 2 < n && a[v + 2] == 0) {\n                have_step.push_back(v + 1);\n            }\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "games",
      "graphs",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1333",
    "index": "E",
    "title": "Road to 1600",
    "statement": "Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!\n\nBefore you start solving the problem, Egor wants to remind you how the chess pieces move. Chess \\textbf{rook} moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The \\textbf{queen} walks in all directions vertically and diagonally at any distance. You can see the examples below.\n\nTo reach the goal, Egor should research the next topic:\n\nThere is an $N \\times N$ board. Each cell of the board has a number from $1$ to $N ^ 2$ in it and numbers in all cells are distinct.\n\nIn the beginning, some chess figure stands in the cell with the number $1$. Note that this cell is already considered as visited. After that every move is determined by the following rules:\n\n- Among all \\textbf{not visited} yet cells to which the figure can get in one move, it goes to the cell that has \\textbf{minimal} number.\n- If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of $1$ \\textbf{vun}.\n- If all cells are already visited, the process is stopped.\n\nEgor should find an $N \\times N$ board on which the rook pays \\textbf{strictly less vuns} than the queen during the round with this numbering. Help him to find such $N \\times N$ numbered board, or tell that it doesn't exist.",
    "tutorial": "First of all notice that there are no such boards for $N=1,2$. Then you can find an example for $N=3$ by yourself or with counting all cases with program. One of possible examples (I find it using paper, pencil and my hands): $N=3$: For large $N$ we can walk by spiral (like snake) to the case $N=3$. $N=4$: $N=5$: Rook and Queen first going in a spiral and arrive to $N=3$ case. It can be used any of such spiral, not just this one. Final time complexity: $O(N^2)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint main() {\n    int n; cin >> n;\n    if (n < 3) {\n        cout << -1;\n        return 0;\n    }\n    vector<int> solution = {\n        1, 3, 4, 8, 2, 7, 9, 5, 6\n    };\n    vector<vector<int>> table(n, vector<int>(n, 0));\n    int cur = 1;\n    for (int i = 0; i < n - 3; ++i) {\n        if (i & 1) {\n            for (int j = n - 1; j >= 0; --j) {\n                table[i][j] = cur;\n                ++cur;\n            }\n        } else {\n            for (int j = 0; j < n; ++j) {\n                table[i][j] = cur;\n                ++cur;\n            }\n        }\n    }\n    if ((n - 3) & 1) {\n        for (int j = n - 1; j >= 0; --j) {\n            if (j & 1) {\n                for (int i = n - 3; i < n; ++i) {\n                    if (j > 2) {\n                        table[i][j] = cur;\n                        ++cur;\n                    } else {\n                        table[i][j] = solution[(2 - j) * 3 + i - n + 3] + n * n - 9;\n                    }\n                }\n            } else {\n                for (int i = n - 1; i >= n - 3; --i) {\n                    if (j > 2) {\n                        table[i][j] = cur;\n                        ++cur;\n                    } else {\n                        table[i][j] = solution[(2 - j) * 3 + n - 1 - i] + n * n - 9;\n                    }\n                }\n            }\n        }\n    } else {\n        for (int j = 0; j < n; ++j) {\n            if (j & 1) {\n                for (int i = n - 1; i >= n - 3; --i) {\n                    if (j < n - 3) {\n                        table[i][j] = cur;\n                        ++cur;\n                    } else {\n                        table[i][j] = solution[(j - n + 3) * 3 + n - 1 - i] + n * n - 9;\n                    }\n                }\n            } else {\n                for (int i = n - 3; i < n; ++i) {\n                    if (j < n - 3) {\n                        table[i][j] = cur;\n                        ++cur;\n                    } else {\n                        table[i][j] = solution[(j - n + 3) * 3 + i - n + 3] + n * n - 9;\n                    }\n                }\n            }\n        }\n    }\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << table[i][j] << ' ';\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1333",
    "index": "F",
    "title": "Kate and imperfection",
    "statement": "Kate has a set $S$ of $n$ integers $\\{1, \\dots, n\\} $.\n\nShe thinks that \\textbf{imperfection} of a subset $M \\subseteq S$ is equal to the \\textbf{maximum} of $gcd(a, b)$ over all pairs $(a, b)$ such that both $a$ and $b$ are in $M$ and $a \\neq b$.\n\nKate is a very neat girl and for each $k \\in \\{2, \\dots, n\\}$ she wants to find a subset that has the \\textbf{smallest imperfection} among all subsets in $S$ of size $k$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $k$, will name it $I_k$.\n\nPlease, help Kate to find $I_2$, $I_3$, ..., $I_n$.",
    "tutorial": "Let $A = \\{a_1, a_2, ..., a_k\\}$ be one of the possible subsets with smallest imperfection. If for any number $a_i$ in $A$ not all of its divisors contained in $A$ then we can replace $a_i$ with one of it divisor. The size os the subset does not change and imperfection may only decrease. Then we can assume that for any $a_i$ all of it divisors contained in $A$. Let $d(n)$ be the greatest divisor of $n$ exclude $n$ ($d(1)=1$). Since $A$ contains element with its divisors then smallest gcd of pair of an elements not less than maximum of $d(a_i)$ over elements of $A$ (because $A$ contains $a_i$ with $d(a_i)$). And for any element $a_i$ there is no element $a_j < a_i$ in $A$ with $gcd(a_i, a_j) > d(a_i)$ (because $d(a_i)$ is the greatest divisor). Then imperfection of $A$ is equal to greatest $d(a_i)$ over elements of $A$. After this observation we can just sort elements $\\{1, ..., n\\}$ by theirs $d(*)$ and take smallest $k$ for every $2 \\le k \\le n$. You can calculate $d(*)$ using the sieve of Eratosthenes. Final time complexity: $O(n \\times log(n))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nvector<int> max_div;\n\nvoid eratosthenes(int limit) {\n    max_div.assign(limit + 1, 0);\n    max_div[0] = limit + 10;\n    max_div[1] = 1;\n    for (int i = 2; i <= limit; ++i) {\n        if (max_div[i]) continue;\n        for (int j = i; j <= limit; j += i) {\n            if (max_div[j]) continue;\n            max_div[j] = j / i;\n        }\n    }\n}\n\n\nint main() {\n    int n; cin >> n;\n    eratosthenes(n);\n    sort(max_div.begin(), max_div.end());\n    for (int i = 1; i < n; ++i) {\n        cout << max_div[i] << ' ';\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory",
      "sortings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1334",
    "index": "A",
    "title": "Level Statistics",
    "statement": "Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.\n\nAll levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $1$. If he manages to finish the level successfully then the number of clears increases by $1$ as well. \\textbf{Note that both of the statistics update at the same time} (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).\n\nPolycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.\n\nSo he peeked at the stats $n$ times and wrote down $n$ pairs of integers — $(p_1, c_1), (p_2, c_2), \\dots, (p_n, c_n)$, where $p_i$ is the number of plays at the $i$-th moment of time and $c_i$ is the number of clears at the same moment of time. \\textbf{The stats are given in chronological order} (i.e. the order of given pairs is exactly the same as Polycarp has written down).\n\nBetween two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.\n\nFinally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.\n\nHelp him to check the correctness of his records.\n\nFor your convenience you have to answer multiple independent test cases.",
    "tutorial": "Let's use the fact that initially the level has $0$ plays and $0$ clears. Call the differences before the previous stats and the current ones $\\Delta p$ and $\\Delta c$. The stats are given in chronological order, so neither the number of plays, nor the number of clears should decrease (i.e. $\\Delta p \\ge 0$ and $\\Delta c \\ge 0$). Finally, $\\Delta p$ should be greater or equal to $\\Delta c$. It's easy to show that if $\\Delta c$ players pass the level successfully and $\\Delta p - \\Delta c$ players just try the level then such deltas are achieved. So in implementation it's enough to check these three conditions between the consecutive pieces of data (including the initial ($0, 0$)). Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n\tint tc;\n\tscanf(\"%d\", &tc);\n\twhile (tc--){\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tint p = 0, c = 0;\n\t\tbool fl = true;\n\t\tforn(i, n){\n\t\t\tint x, y;\n\t\t\tscanf(\"%d%d\", &x, &y);\n\t\t\tif (x < p || y < c || y - c > x - p)\n\t\t\t\tfl = false;\n\t\t\tp = x, c = y;\n\t\t}\n\t\tputs(fl ? \"YES\" : \"NO\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1334",
    "index": "B",
    "title": "Middle Class",
    "statement": "Many years ago Berland was a small country where only $n$ people lived. Each person had some savings: the $i$-th one had $a_i$ burles.\n\nThe government considered a person as wealthy if he had at least $x$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:\n\n- the government chooses some subset of people (maybe all of them);\n- the government takes all savings from the chosen people and redistributes the savings among the chosen people equally.\n\nFor example, consider the savings as list $[5, 1, 2, 1]$: if the government chose the $1$-st and the $3$-rd persons then it, at first, will take all $5 + 2 = 7$ burles and after that will return $3.5$ burles to the chosen people. As a result, the savings will become $[3.5, 1, 3.5, 1]$.\n\nA lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.",
    "tutorial": "In fact, to carry out only one reform is always enough. And it's easy to prove if you make only one reform it's always optimal to take the maximum such $k$ that the average of $k$ maximums in the array $a$ is at least $x$ (i.e. sum greater or equal to $kx$). So the solution is next: sort array $a$ and find the suffix with maximum length $k$ such that the sum on the suffix is at least $kx$. === To prove the fact about one reform we can prove another fact: after each reform, the sum of $k$ maximums doesn't increase for each $k$. We'll prove it in two steps. The first step. Let's look at some reform and form an array $b$ from the chosen elements in $a$ in descending order. After the reform we'll get array $b'$ where all $b'[i] = \\frac{1}{|b|} \\sum_{i=1}^{|b|}{b[i]}$. Let's just skip the proof and say it's obvious enough that $\\sum_{i=1}^{y}{b[i]} \\ge \\sum_{i=1}^{y}{b'[i]}$ for any $y$. The second step. Let fix $k$ and divide array $a$ on two parts: $k$ maximums as $a_1$ and other $n - k$ elements as $a_2$. And let's make the same division of $a'$ (the array after performing the reform) on $a'_1$ and $a'_2$. So, we need to prove that $sum(a'_1) \\le sum(a_1)$. Suppose $m$ elements were chosen in the reform: $cnt$ of them were in $a_1$ and $cnt'$ now in $a'_1$. If $cnt \\ge cnt'$ then we can think like maximum $cnt'$ elements from $cnt$ elements in $a$ were replaced by the average and other $cnt - cnt'$ were replaced by elements from $a_2$. Since $\\sum_{i=1}^{cnt'}{b[i]} \\ge \\sum_{i=1}^{cnt'}{b'[i]}$ and any element from $a_1$ is greater or equal to any element from $a_2$ then we proved that $sum(a'_1) \\le sum(a_1)$ when $cnt \\ge cnt'$. If $cnt < cnt'$ then let's look at $a_2$ and $a'_2$. The $a_2$ has $m - cnt$ chosen elements and $a'_2$ has $m - cnt'$, so $m - cnt > m - cnt'$ and we can prove that $sum(a'_2) \\ge sum(a_2)$ practically in the same way as before. Obviously, if $sum(a') = sum(a)$ and $sum(a'_2) \\ge sum(a_2)$ then $sum(a'_1) \\le sum(a_1)$. Q.E.D. The last step is easy, let's prove that the only reform is enough. The answer after several reforms is clearly equal to $k$ maximums which are at least $x$. But it means that the sum of $k$ maximums is at least $kx$, therefore the sum of $k$ maximums in the initial array is at least $kx$. So we can make them all at least $k$ by only one reform.",
    "code": "fun main() {\n    val T = readLine()!!.toInt()\n    for (tc in 1..T) {\n        val (n, x) = readLine()!!.split(' ').map { it.toInt() }\n        val a = readLine()!!.split(' ').map { it.toInt() }.sortedDescending()\n\n        var cnt = 0\n        var sum = 0L\n        while (cnt < n && sum + a[cnt] >= (cnt + 1) * x.toLong()) {\n            sum += a[cnt]\n            cnt++\n        }\n        println(cnt)\n    }\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1334",
    "index": "C",
    "title": "Circle of Monsters",
    "statement": "You are playing another computer game, and now you have to slay $n$ monsters. These monsters are standing in a circle, numbered clockwise from $1$ to $n$. Initially, the $i$-th monster has $a_i$ health.\n\nYou may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by $1$ (deals $1$ damage to it). Furthermore, when the health of some monster $i$ becomes $0$ or less than $0$, it dies and explodes, dealing $b_i$ damage to the next monster (monster $i + 1$, if $i < n$, or monster $1$, if $i = n$). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.\n\nYou have to calculate the minimum number of bullets you have to fire to kill all $n$ monsters in the circle.",
    "tutorial": "We cannot utilize the explosion of the last monster we kill. So the naive approach is to iterate on the monster we kill the last, break the circle between this monster and the next one, and then shoot the first monster in the broken circle until it's dead, then the second one, and so on. Let's calculate the number of bullets we will fire this way. If the circle is broken after the monster $i$, then the first monster gets $a_{i + 1}$ bullets, the second one - $\\max(0, a_{i + 2} - b_{i + 1})$, and so on; all monsters except the first one get exactly $\\max(0, a_i - b_{i - 1})$ bullets. So we should choose an index $i$ such that $a_{i + 1} - \\max(0, a_{i + 1} - b_i)$ is minimum possible, since this is the number of bullets we have to spend additionally since we cannot utilize the explosion of the $i$-th monster. After breaking the circle between the monsters $i$ and $i + 1$, you may use a formula to calculate the required number of bullets, or just model the shooting.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\ntypedef long long li;\n\nconst int N = 300 * 1000 + 13;\n\nint n;\nli a[N], b[N];\n\nvoid solve() {\n\tscanf(\"%d\", &n);\n\tforn(i, n) scanf(\"%lld%lld\", &a[i], &b[i]);\n\t\n\tli ans = 0, mn = 1e18;\n\tforn(i, n) {\n\t\tint ni = (i + 1) % n;\n\t\tli val = min(a[ni], b[i]);\n\t\tans += a[ni] - val;\n\t\tmn = min(mn, val);\n\t}\n\tans += mn;\n\tprintf(\"%lld\\n\", ans);\n}\n\nint main() {\n\tint T;\n\tscanf(\"%d\", &T);\n\tforn(i, T)\n\t\tsolve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1334",
    "index": "D",
    "title": "Minimum Euler Cycle",
    "statement": "You are given a complete directed graph $K_n$ with $n$ vertices: each pair of vertices $u \\neq v$ in $K_n$ have both directed edges $(u, v)$ and $(v, u)$; there are no self-loops.\n\nYou should find such a cycle in $K_n$ that visits every directed edge exactly once (allowing for revisiting vertices).\n\nWe can write such cycle as a list of $n(n - 1) + 1$ vertices $v_1, v_2, v_3, \\dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$ — a visiting order, where each $(v_i, v_{i + 1})$ occurs exactly once.\n\nFind the \\textbf{lexicographically smallest} such cycle. It's not hard to prove that the cycle always exists.\n\nSince the answer can be too large print its $[l, r]$ segment, in other words, $v_l, v_{l + 1}, \\dots, v_r$.",
    "tutorial": "The solution of the problem can be found clearly in constructive way. An example for $n=5$: (1 2 1 3 1 4 1 5 (2 3 2 4 2 5 (3 4 3 5 (4 5 ()))) 1) where brackets mean that we call here some recursive function $calc$. Since on each level of recursion we have only $O(n)$ elements and there $O(n)$ levels then the generation of the certificate is quite easy: if on the currect level of recursion we can skip the whole part - let's just skip it. Otherwise let's build this part. Anyway, the built part of the cycle will have only $O(n + (r - l))$ length so the whole algorithm has $O(n + (r - l))$ complexity. The answer is lexicographically minimum by the construction, since on each level of recursion there is no way to build lexicographically smaller sequence.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nint n;\nli l, r;\n\ninline bool read() {\n\tif(!(cin >> n >> l >> r))\n\t\treturn false;\n\treturn true;\n}\n\nbool intersect(li l1, li r1, li l2, li r2) {\n\treturn min(r1, r2) > max(l1, l2);\n}\n\nvector<int> ans;\n\nvoid calc(int lf, int rg, li &id) {\n\tif(lf == rg) return;\n\t\n\tif(intersect(l, r, id, id + 2 * (rg - lf))) {\n\t\tfore(to, lf + 1, rg + 1) {\n\t\t\tif(l <= id && id < r)\n\t\t\t\tans.push_back(lf);\n\t\t\tid++;\n\t\t\t\n\t\t\tif(l <= id && id < r)\n\t\t\t\tans.push_back(to);\n\t\t\tid++;\n\t\t}\n\t} else\n\t\tid += 2 * (rg - lf);\n\t\n\tcalc(lf + 1, rg, id);\n\t\n\tif(lf == 0) {\n\t\tif(l <= id && id < r)\n\t\t\tans.push_back(lf);\n\t\tid++;\n\t}\n}\n\ninline void solve() {\n\tans.clear();\n\tli id = 0;\n\tl--;\n\tcalc(0, n - 1, id);\n\t\n\tassert(sz(ans) == r - l);\n\tassert(id == n * li(n - 1) + 1);\n\t\n\tfor(int v : ans)\n\t\tcout << v + 1 << \" \";\n\tcout << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\t\n\twhile(tc--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1334",
    "index": "E",
    "title": "Divisor Paths",
    "statement": "You are given a positive integer $D$. Let's build the following graph from it:\n\n- each vertex is a divisor of $D$ (not necessarily prime, $1$ and $D$ itself are also included);\n- two vertices $x$ and $y$ ($x > y$) have an undirected edge between them if $x$ is divisible by $y$ and $\\frac x y$ is a prime;\n- the weight of an edge is the number of divisors of $x$ that are not divisors of $y$.\n\nFor example, here is the graph for $D=12$:\n\nEdge $(4,12)$ has weight $3$ because $12$ has divisors $[1,2,3,4,6,12]$ and $4$ has divisors $[1,2,4]$. Thus, there are $3$ divisors of $12$ that are not divisors of $4$ — $[3,6,12]$.\n\nThere is no edge between $3$ and $2$ because $3$ is not divisible by $2$. There is no edge between $12$ and $3$ because $\\frac{12}{3}=4$ is not a prime.\n\nLet the length of the path between some vertices $v$ and $u$ in the graph be the total weight of edges on it. For example, path $[(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)]$ has length $1+2+2+3+1+2=11$. The empty path has length $0$.\n\nSo the shortest path between two vertices $v$ and $u$ is the path that has the minimal possible length.\n\nTwo paths $a$ and $b$ are different if there is either a different number of edges in them or there is a position $i$ such that $a_i$ and $b_i$ are different edges.\n\nYou are given $q$ queries of the following form:\n\n- $v$ $u$ — calculate the \\textbf{number of the shortest paths} between vertices $v$ and $u$.\n\nThe answer for each query might be large so print it modulo $998244353$.",
    "tutorial": "Let's define the semantics of moving along the graph. On each step the current number is either multiplied by some prime or divided by it. I claim that the all shortest paths from $x$ to $y$ always go through $gcd(x, y)$. Moreover, the vertex numbers on the path first only decrease until $gcd(x, y)$ and only increase after it. Let's watch what happens to the divisors list on these paths. At first, all the divisors of $x$ that are not divisors of $y$ are removed from the list. Now we reach gcd and we start adding the divisors of $y$ that are missing from the list. The length of the path is this total number of changes to the list. That shows us that these paths are the shortest by definition. If we ever take a turn off that path, we either will add some divisor that we will need to remove later or remove some divisor that we will need to add later. That makes the length of the path not optimal. Now let's learn to calculate the number of paths. The parts before gcd and after it will be calculated separately, the answer is the product of answers for both parts. How many paths are there to gcd? Well, let's divide $x$ by $gcd$, that will give us the primes that should be removed from $x$. You can remove them in any order because the length of the path is always the same. That is just the number of their permutations with repetitions (you might also know that formula as multinomial coefficient). The number of paths from $gcd$ to $y$ is calculated the same way. To find the primes in $\\frac{x}{gcd(x, y)}$ you can factorize $D$ beforehand and only iterate over the primes of $D$. Overall complexity: $O(\\sqrt{D} + q \\log D)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\nint binpow(int a, int b){\n\tint res = 1;\n\twhile (b){\n\t\tif (b & 1)\n\t\t\tres = mul(res, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nint main() {\n\tlong long d;\n\tscanf(\"%lld\", &d);\n\tint q;\n\tscanf(\"%d\", &q);\n\t\n\tvector<long long> primes;\n\tfor (long long i = 2; i * i <= d; ++i) if (d % i == 0){\n\t\tprimes.push_back(i);\n\t\twhile (d % i == 0) d /= i;\n\t}\n\tif (d > 1){\n\t\tprimes.push_back(d);\n\t}\n\t\n\tvector<int> fact(100), rfact(100);\n\tfact[0] = 1;\n\tfor (int i = 1; i < 100; ++i)\n\t\tfact[i] = mul(fact[i - 1], i);\n\trfact[99] = binpow(fact[99], MOD - 2);\n\tfor (int i = 98; i >= 0; --i)\n\t\trfact[i] = mul(rfact[i + 1], i + 1);\n\t\n\tforn(i, q){\n\t\tlong long x, y;\n\t\tscanf(\"%lld%lld\", &x, &y);\n\t\tvector<int> up, dw;\n\t\tfor (auto p : primes){\n\t\t\tint cnt = 0;\n\t\t\twhile (x % p == 0){\n\t\t\t\t--cnt;\n\t\t\t\tx /= p;\n\t\t\t}\n\t\t\twhile (y % p == 0){\n\t\t\t\t++cnt;\n\t\t\t\ty /= p;\n\t\t\t}\n\t\t\tif (cnt < 0) dw.push_back(-cnt);\n\t\t\telse if (cnt > 0) up.push_back(cnt);\n\t\t}\n\t\tint ans = 1;\n\t\tans = mul(ans, fact[accumulate(up.begin(), up.end(), 0)]);\n\t\tfor (auto it : up) ans = mul(ans, rfact[it]);\n\t\tans = mul(ans, fact[accumulate(dw.begin(), dw.end(), 0)]);\n\t\tfor (auto it : dw) ans = mul(ans, rfact[it]);\n\t\tprintf(\"%d\\n\", ans);\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "graphs",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1334",
    "index": "F",
    "title": "Strange Function",
    "statement": "Let's denote the following function $f$. This function takes an array $a$ of length $n$ and returns an array. Initially the result is an empty array. For each integer $i$ from $1$ to $n$ we add element $a_i$ to the end of the resulting array if it is greater than all previous elements (more formally, if $a_i > \\max\\limits_{1 \\le j < i}a_j$). Some examples of the function $f$:\n\n- if $a = [3, 1, 2, 7, 7, 3, 6, 7, 8]$ then $f(a) = [3, 7, 8]$;\n- if $a = [1]$ then $f(a) = [1]$;\n- if $a = [4, 1, 1, 2, 3]$ then $f(a) = [4]$;\n- if $a = [1, 3, 1, 2, 6, 8, 7, 7, 4, 11, 10]$ then $f(a) = [1, 3, 6, 8, 11]$.\n\nYou are given two arrays: array $a_1, a_2, \\dots , a_n$ and array $b_1, b_2, \\dots , b_m$. You can delete some elements of array $a$ (possibly zero). To delete the element $a_i$, you have to pay $p_i$ coins (the value of $p_i$ can be negative, then you get $|p_i|$ coins, if you delete this element). Calculate the minimum number of coins (possibly negative) you have to spend for fulfilling equality $f(a) = b$.",
    "tutorial": "The \"naive\" version of the solution is just dynamic programming: let $dp_{i, j}$ be the minimum cost of removed elements (or the maximum cost of remaining elements) if we considered first $i$ elements of $a$, and the resulting sequence maps to the first $j$ elements of $b$. There are two versions of this solution, both working in $O(n^2)$: calculate this dp \"as it is\", so there are $O(nm)$ states and $O(1)$ transitions from each state; ensure that the $i$-th element is taken into $f(a)$, so there are $O(n)$ states (since each element appears in $b$ exactly once, the second state can be deduces from the first one), but up to $O(n)$ transitions from each state. It turns out that we can optimize the second approach. Let's calculate the values of $dp_i$ in ascending order of $a_i$: first of all, we calculate the values of $dp_i$ such that $a_i = b_1$, then transition into states such that $a_i = b_2$, and so on. Calculating $dp_i$ for $a_i = b_1$ is easy: since the first element of $a$ is always the first element of $f(a)$, we should delete all elements before the $i$-th if we want it to be the first element in $f(a)$. So, if $dp_i$ is the maximum possible sum of costs of remaining elements, if we considered the first $i$ elements of $a$ (and the $i$-th element gets included in $f(a)$), then $dp_i = c_i$ for indices $i$ such that $a_i = b_1$. Okay, now let's consider advancing from $b_k$ to $b_{k + 1}$. If we want to go from $dp_i$ to $dp_j$ such that $a_i = b_k$ and $a_j = b_{k + 1}$, we should leave the element $a_j$ in the array and delete some elements between indices $i$ and $j$. Which ones should be deleted? First of all, they are all elements with negative deletion cost; but we should also get rid of all elements which could replace $a_j$ in $f(a)$ - that is, all elements that are greater than $a_i$. So the remaining elements are $x$ which have $i < x < j$, $c_x > 0$ and $a_x \\le a_i$, and we should be able to compute the sum of such elements. Even if we manage to do it in $O(\\log n)$, which is possible, there may be up to $O(n^2)$ possible pairs of $dp_i$ and $dp_j$ to consider. The easiest way to get rid of that is to sort all occurences of $b_k$ and $b_{k + 1}$, and process them in ascending order, maintaining the best $dp_i$ that was already met. That way, each of the elements of $a$ will be considered at most twice, so this solution runs in $O(n \\log n)$. We know how to calculate the $dp$ values now, but how to determine the answer? We should consider all values of $dp_i$ such that $a_i = b_m$ and delete all elements with negative costs and all elements that are greater than $a_i$ from the suffix $[i + 1, n]$ - so this is another query of the form \"compute the sum of $c_x$ over $x$ which have $i < x < j$, $c_x > 0$ and $a_x \\le a_i$\". The most straightforward way to process them in $O(\\log n)$ is to use a persistent segment tree, but since $a_i$ does not decrease in these queries as we process them, we may maintain the elements we are interested in with a much simpler data structure, for example, Fenwick tree.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\nconst li INF64 = li(1e18);\nconst int N = 500043;\n\nli f[N];\n\nli get(int x)\n{\n    li ans = 0;    \n    for (; x >= 0; x = (x & (x + 1)) - 1)\n        ans += f[x];\n    return ans;\n}\n\nvoid inc(int x, li d)\n{\n    for (; x < N; x = (x | (x + 1)))\n        f[x] += d;    \n}\n\nli get(int l, int r)\n{\n    return get(r) - get(l - 1);\n}\n\nli dp[N];\nint a[N], b[N], p[N];\nint n, m;\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++)\n        scanf(\"%d\", &a[i]);\n    for(int i = 0; i < n; i++)\n        scanf(\"%d\", &p[i]);\n    scanf(\"%d\", &m);\n    for(int i = 0; i < m; i++)\n        scanf(\"%d\", &b[i]);\n\n    for(int i = 0; i < n; i++)\n        dp[i] = -INF64;\n    map<int, vector<int> > pos;\n    for(int i = 0; i < n; i++)\n        pos[a[i]].push_back(i);\n    set<pair<int, int> > q;\n    for(int i = 0; i < n; i++)\n        q.insert(make_pair(a[i], i));\n    \n    for(auto x : pos[b[0]])\n        dp[x] = p[x];\n    while(!q.empty() && q.begin()->first <= b[0])\n    {\n        int k = q.begin()->second;\n        q.erase(q.begin());\n        if(p[k] > 0)\n            inc(k, p[k]);\n    }  \n\n    for(int i = 1; i < m; i++)\n    {\n        int i1 = b[i - 1], i2 = b[i];\n        vector<int> both_pos;\n        for(auto x : pos[i1])\n            both_pos.push_back(x);\n        for(auto x : pos[i2])\n            both_pos.push_back(x);\n        li best = -INF64;\n        int last = -1;\n        sort(both_pos.begin(), both_pos.end());\n        for(auto x : both_pos)\n        {\n            best += get(last + 1, x);\n            last = x;\n            if(a[x] == i1)\n                best = max(best, dp[x]);\n            else\n                dp[x] = best + p[x];\n        }\n        while(!q.empty() && q.begin()->first <= i2)\n        {\n            int k = q.begin()->second;\n            q.erase(q.begin());\n            if(p[k] > 0)\n                inc(k, p[k]);\n        }\n    }\n\n    li best_dp = -INF64;\n    for(int i = 0; i < n; i++)\n        if(a[i] == b[m - 1])\n            best_dp = max(best_dp, dp[i] + get(i + 1, n - 1));\n    li ans = 0;\n    for(int i = 0; i < n; i++)\n        ans += p[i];\n    ans -= best_dp;\n    if(ans > li(1e15))\n        puts(\"NO\");\n    else     \n        printf(\"YES\\n%lld\\n\", ans);\n    \n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1334",
    "index": "G",
    "title": "Substring Search",
    "statement": "You are given a permutation $p$ consisting of exactly $26$ integers from $1$ to $26$ (since it is a permutation, each integer from $1$ to $26$ occurs in $p$ exactly once) and two strings $s$ and $t$ consisting of lowercase Latin letters.\n\nA substring $t'$ of string $t$ is an \\textbf{occurence} of string $s$ if the following conditions are met:\n\n- $|t'| = |s|$;\n- for each $i \\in [1, |s|]$, either $s_i = t'_i$, or $p_{idx(s_i)} = idx(t'_i)$, where $idx(c)$ is the index of character $c$ in Latin alphabet ($idx(\\text{a}) = 1$, $idx(\\text{b}) = 2$, $idx(\\text{z}) = 26$).\n\nFor example, if $p_1 = 2$, $p_2 = 3$, $p_3 = 1$, $s = \\text{abc}$, $t = \\text{abcaaba}$, then three substrings of $t$ are occurences of $s$ (they are $t' = \\text{abc}$, $t' = \\text{bca}$ and $t' = \\text{aba}$).\n\nFor each substring of $t$ having length equal to $|s|$, check if it is an \\textbf{occurence} of $s$.",
    "tutorial": "We will run two tests for each substring of $t$ we are interested in. If at least one of them shows that the substring is not an occurence of $s$, we print 0, otherwise we print 1. The first test is fairly easy. The given permutation can be decomposed into cycles. Let's replace each character with the index of its cycle (in both strings) and check if each substring of $t$ is equal to $s$ after this replacement (for example, using regular KMP algorithm). If some substring is not equal to $s$ after the replacement, then it is definitely not an occurence. The second test will help us distinguish the characters belonging to the same cycle. Let $[c_1, c_2, \\dots, c_k]$ be some cycle in our permutation (elements are listed in the order they appear in the cycle, so $p_{c_i} = c_{i + 1}$). We will replace each character with a complex number in such a way that the case when they match are easily distinguishable from the case when they don't match. One of the ways to do this is to replace $c_i$ with a complex number having magnitude equal to $1$ and argument equal to $\\dfrac{2 \\pi i}{k}$ (if this character belongs to $s$) or to $\\dfrac{\\pi - 2 \\pi i}{k}$ (if this character belongs to $t$). How does this replacement help us checking the occurence? If we multiply the numbers for two matching characters, we get a complex number with argument equal to $\\dfrac{\\pi}{k}$ or to $-\\dfrac{\\pi}{k}$, and its real part will be $\\cos \\dfrac{\\pi}{k}$. In any other case, the real part of the resulting number will be strictly less than $\\cos \\dfrac{\\pi}{k}$, and the difference will be at least $0.06$. So, if we compute the value of $\\sum \\limits_{i = 1}^{|s|} f(s_i) \\cdot f(t_{j + i - 1})$ for the $j$-th substring of $t$ (where $f(c)$ is the number that replaced the character $c$), we can check if the real part of the result is close to the value we would get if we matched $s$ with itself (and if the difference is big enough, at least one pair of characters didn't match). The only case when this method fails is if we try to match characters from different cycles of the permutation, that's why we needed the first test. Overall, the first test can be done in $O(|s| + |t|)$ using prefix function (or any other linear substring search algorithm), and the second test can be done in $O((|s| + |t|) \\log(|s| + |t|))$, if we compute the aforementioned values for each substring using FFT.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < n; i++)\n#define sz(a) ((int)(a).size())\n\nconst int LOGN = 20;\nconst int N = (1 << LOGN);\n\ntypedef long double ld;\ntypedef long long li;\n\nconst ld PI = acos(-1.0);\n\nstruct comp \n{\n    ld x, y;\n    comp(ld x = .0, ld y = .0) : x(x), y(y) {}\n    inline comp conj() { return comp(x, -y); }\n};\n\ninline comp operator +(const comp &a, const comp &b) \n{\n    return comp(a.x + b.x, a.y + b.y);\n}\n\ninline comp operator -(const comp &a, const comp &b) \n{\n    return comp(a.x - b.x, a.y - b.y);\n}\n\ninline comp operator *(const comp &a, const comp &b) \n{\n    return comp(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);\n}\n\ninline comp operator /(const comp &a, const ld &b) \n{\n    return comp(a.x / b, a.y / b);\n}\n\nvector<comp> w[LOGN];\nvector<int> rv[LOGN];\n\nvoid precalc() \n{\n    for(int st = 0; st < LOGN; st++) \n    {\n        w[st].assign(1 << st, comp());\n        for(int k = 0; k < (1 << st); k++) \n        {\n            double ang = PI / (1 << st) * k;\n            w[st][k] = comp(cos(ang), sin(ang));\n        }\n        \n        rv[st].assign(1 << st, 0);\n        if(st == 0) \n        {\n            rv[st][0] = 0;\n            continue;\n        }\n        int h = (1 << (st - 1));\n        for(int k = 0; k < (1 << st); k++)\n            rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);\n    }\n}\n\ninline void fft(comp a[N], int n, int ln, bool inv) \n{\n    for(int i = 0; i < n; i++) \n    {\n        int ni = rv[ln][i];\n        if(i < ni)\n            swap(a[i], a[ni]);\n    }\n    \n    for(int st = 0; (1 << st) < n; st++) \n    {\n        int len = (1 << st);\n        for(int k = 0; k < n; k += (len << 1)) \n        {\n            for(int pos = k; pos < k + len; pos++) \n            {\n                comp l = a[pos];\n                comp r = a[pos + len] * (inv ? w[st][pos - k].conj() : w[st][pos - k]);\n                \n                a[pos] = l + r;\n                a[pos + len] = l - r;\n            }\n        }\n    }\n    \n    if(inv) for(int i = 0; i < n; i++)\n        a[i] = a[i] / n;\n}\n\ncomp aa[N];\ncomp bb[N];\ncomp cc[N];\n\ninline void multiply(comp a[N], int sza, comp b[N], int szb, comp c[N], int &szc) \n{\n    int n = 1, ln = 0;\n    while(n < (sza + szb))\n        n <<= 1, ln++;\n    for(int i = 0; i < n; i++)\n        aa[i] = (i < sza ? a[i] : comp());\n    for(int i = 0; i < n; i++)\n        bb[i] = (i < szb ? b[i] : comp());\n        \n    fft(aa, n, ln, false);\n    fft(bb, n, ln, false);\n    \n    for(int i = 0; i < n; i++)\n        cc[i] = aa[i] * bb[i];\n        \n    fft(cc, n, ln, true);\n    \n    szc = n;\n    for(int i = 0; i < n; i++)\n        c[i] = cc[i];\n}\n\ncomp a[N];\ncomp b[N];\ncomp c[N];\n\nvector<int> p_function(const vector<int>& v)\n{\n    int n = v.size();\n    vector<int> p(n);\n    for(int i = 1; i < n; i++)\n    {\n        int j = p[i - 1];\n        while(j > 0 && v[j] != v[i])\n            j = p[j - 1];\n        if(v[j] == v[i])\n            j++;\n        p[i] = j;   \n    }\n    return p;\n}\n\nint p[26];\nchar buf[N];\nstring s, t;\n\nint main()\n{\n    precalc();                  \n    for(int i = 0; i < 26; i++)\n    {\n        scanf(\"%d\", &p[i]);\n        p[i]--;\n    }\n    scanf(\"%s\", buf);\n    s = buf;\n    scanf(\"%s\", buf);\n    t = buf;\n\n    int n = s.size();\n    int m = t.size();\n    vector<int> color(26, 0);\n    vector<vector<int> > cycles;\n    for(int i = 0; i < 26; i++)\n    {\n        if(color[i])\n            continue;\n        vector<int> cycle;\n        int cc = cycles.size() + 1;\n        int cur = i;\n        while(color[cur] == 0)\n        {\n            cycle.push_back(cur);\n            color[cur] = cc;\n            cur = p[cur];\n        }\n        cycles.push_back(cycle);\n    }\n\n    vector<int> ans(m - n + 1);\n    vector<int> s1, t1;\n    for(int i = 0; i < n; i++)\n        s1.push_back(color[int(s[i] - 'a')]);\n    for(int i = 0; i < m; i++)\n        t1.push_back(color[int(t[i] - 'a')]);\n    vector<int> st = s1;\n    st.push_back(0);\n    for(auto x : t1)\n        st.push_back(x);\n    vector<int> pf = p_function(st);\n    for(int i = 0; i < m - n + 1; i++)\n        if(pf[2 * n + i] == n)\n            ans[i] = 1;\n    map<char, comp> m1, m2;\n    for(auto cur : cycles)\n    {\n        int k = cur.size();\n        for(int i = 0; i < k; i++)\n        {\n            ld ang1 = 2 * PI * i / k;\n            ld ang2 = (PI - 2 * PI * i) / k;\n            m1[char('a' + cur[i])] = comp(cosl(ang1), sinl(ang1));\n            m2[char('a' + cur[i])] = comp(cosl(ang2), sinl(ang2));\n        }\n    }\n\n    ld ideal = 0;\n    for(int i = 0; i < n; i++)\n        ideal += (m1[s[i]] * m2[s[i]]).x;\n    reverse(s.begin(), s.end());\n    for(int i = 0; i < n; i++)                  \n        a[i] = m1[s[i]];                \n    for(int i = 0; i < m; i++)\n        b[i] = m2[t[i]];\n    int szc;\n    multiply(a, n, b, m, c, szc);\n    for(int i = 0; i < m - n + 1; i++)\n        if(fabsl(c[i + n - 1].x - ideal) > 0.01)\n            ans[i] = 0;\n    \n\n    for(int i = 0; i < m - n + 1; i++)\n        printf(\"%d\", ans[i]);\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "fft"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1335",
    "index": "A",
    "title": "Candies and Two Sisters",
    "statement": "There are two sisters Alice and Betty. You have $n$ candies. You want to distribute these $n$ candies between two sisters in such a way that:\n\n- Alice will get $a$ ($a > 0$) candies;\n- Betty will get $b$ ($b > 0$) candies;\n- each sister will get some \\textbf{integer} number of candies;\n- Alice will get a greater amount of candies than Betty (i.e. $a > b$);\n- all the candies will be given to one of two sisters (i.e. $a+b=n$).\n\nYour task is to calculate the number of ways to distribute exactly $n$ candies between sisters in a way described above. Candies are indistinguishable.\n\nFormally, find the number of ways to represent $n$ as the sum of $n=a+b$, where $a$ and $b$ are positive integers and $a>b$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The answer is $\\lfloor\\frac{n-1}{2}\\rfloor$, where $\\lfloor x \\rfloor$ is $x$ rounded down.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tcout << (n - 1) / 2 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1335",
    "index": "B",
    "title": "Construct the String",
    "statement": "You are given three positive integers $n$, $a$ and $b$. You have to construct a string $s$ of length $n$ consisting of lowercase Latin letters such that \\textbf{each substring} of length $a$ has \\textbf{exactly} $b$ distinct letters. It is guaranteed that the answer exists.\n\nYou have to answer $t$ independent test cases.\n\nRecall that the substring $s[l \\dots r]$ is the string $s_l, s_{l+1}, \\dots, s_{r}$ and its length is $r - l + 1$. In this problem you are only interested in substrings of length $a$.",
    "tutorial": "If we represent letters with digits, then the answer can be represented as $1, 2, \\dots, b, 1, 2, \\dots, b, \\dots$. There is no substring containing more than $b$ distinct characters and each substring of length $a$ contains exactly $b$ distinct characters because of the condition $b \\le a$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, a, b;\n\t\tcin >> n >> a >> b;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcout << char('a' + i % b);\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 900
  },
  {
    "contest_id": "1335",
    "index": "C",
    "title": "Two Teams Composing",
    "statement": "You have $n$ students under your control and you have to compose \\textbf{exactly two teams} consisting of some subset of your students. Each student had his own skill, the $i$-th student skill is denoted by an integer $a_i$ (different students can have the same skills).\n\nSo, about the teams. Firstly, these two teams should have the same size. Two more constraints:\n\n- The first team should consist of students with \\textbf{distinct} skills (i.e. all skills in the first team are unique).\n- The second team should consist of students with \\textbf{the same} skills (i.e. all skills in the second team are equal).\n\nNote that it is permissible that some student of the first team has the same skill as a student of the second team.\n\nConsider some examples (skills are given):\n\n- $[1, 2, 3]$, $[4, 4]$ is not a good pair of teams because sizes should be the same;\n- $[1, 1, 2]$, $[3, 3, 3]$ is not a good pair of teams because the first team should not contain students with the same skills;\n- $[1, 2, 3]$, $[3, 4, 4]$ is not a good pair of teams because the second team should contain students with the same skills;\n- $[1, 2, 3]$, $[3, 3, 3]$ is a good pair of teams;\n- $[5]$, $[6]$ is a good pair of teams.\n\nYour task is to find the maximum possible size $x$ for which it is possible to compose a valid pair of teams, where each team size is $x$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let the number of students with the skill $i$ is $cnt_i$ and the number of different skills is $diff$. Then the size of the first team can not exceed $diff$ and the size of the second team can not exceed $maxcnt = max(cnt_1, cnt_2, \\dots, cnt_n)$. So the answer is not greater than the minimum of these two values. Moreover, let's take a look at the skill with a maximum value of $cnt$. Then there are two cases: all students with this skill go to the second team then the sizes of teams are at most $diff-1$ and $maxcnt$ correspondingly. Otherwise, at least one student with this skill goes to the first team and the sizes are at most $diff$ and $maxcnt - 1$ correspondingly. So the answer is $max(min(diff - 1, maxcnt), min(diff, maxcnt - 1))$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> cnt(n + 1);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\t++cnt[x];\n\t\t}\n\t\tint mx = *max_element(cnt.begin(), cnt.end());\n\t\tint diff = n + 1 - count(cnt.begin(), cnt.end(), 0);\n\t\tcout << max(min(mx - 1, diff), min(mx, diff - 1)) << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1335",
    "index": "D",
    "title": "Anti-Sudoku",
    "statement": "You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.\n\nThe picture showing the correct sudoku solution:\n\nBlocks are bordered with bold black color.\n\nYour task is to change \\textbf{at most} $9$ elements of this field (i.e. choose some $1 \\le i, j \\le 9$ and change the number at the position $(i, j)$ to any other number in range $[1; 9]$) to make it \\textbf{anti-sudoku}. The \\textbf{anti-sudoku} is the $9 \\times 9$ field, in which:\n\n- Any number in this field is in range $[1; 9]$;\n- each row contains at least two equal elements;\n- each column contains at least two equal elements;\n- each $3 \\times 3$ block (you can read what is the block in the link above) contains at least two equal elements.\n\nIt is guaranteed that the answer exists.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Well, if we replace all occurrences of the number $2$ with the number $1$, then the initial solution will be anti-sudoku. It is easy to see that this replacement will make exactly two copies of $1$ in every row, column, and block. There are also other correct approaches but I found this one the most pretty.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tfor (int i = 0; i < 9; ++i) {\n\t\t\tstring s;\n\t\t\tcin >> s;\n\t\t\tfor (auto &c : s) if (c == '2') c = '1';\n\t\t\tcout << s << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1335",
    "index": "E1",
    "title": "Three Blocks Palindrome (easy version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints}.\n\nYou are given a sequence $a$ consisting of $n$ positive integers.\n\nLet's define a \\textbf{three blocks palindrome} as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\\underbrace{a, a, \\dots, a}_{x}, \\underbrace{b, b, \\dots, b}_{y}, \\underbrace{a, a, \\dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are \\textbf{three block palindromes} but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.\n\nYour task is to choose the maximum by length \\textbf{subsequence} of $a$ that is a \\textbf{three blocks palindrome}.\n\nYou have to answer $t$ independent test cases.\n\nRecall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.",
    "tutorial": "Let's precalculate for each number $c$ ($0$-indexed) the array $pref_c$ of length $n+1$, where $pref_c[i]$ is the number of occurrences of the number $c$ on the prefix of length $i$. This can be done with easy dynamic programming (just compute prefix sums). Also let $sum(c, l, r)$ be $pref_c[r + 1] - pref_c[l]$ and it's meaning is the number of occurrences of the number $c$ on the segment $[l; r]$ ($0$-indexed). Firstly, let's update the answer with $\\max\\limits_{c=0}^{25} pref_c[n]$ (we can always take all occurrences of the same element as the answer). Then let's iterate over all possible segments of the array. Let the current segment be $[l; r]$. Consider that all occurrences of the element in the middle block belong to $a_l, a_{l+1}, \\dots, a_r$. Then we can just take the most frequent number on this segment ($cntin = \\max\\limits_{c=0}^{25} sum(c, l, r)$). We also have to choose the number for the first and the last blocks. It is obvious that for the number $num$ the maximum amount of such numbers we can take is $min(sum(num, 0, l - 1), sum(num, r + 1, n - 1))$. So $cntout = \\max\\limits_{c=0}^{25} min(sum(c, 0, l - 1), sum(c, r + 1, n - 1))$. And we can update the answer with $2cntout + cntin$. Time complexity: $O(n^2 \\cdot AL)$, where $AL$ is the size of alphabet (the maximum value of $a_i$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tvector<vector<int>> cnt(26, vector<int>(n + 1));\n\t\tforn(i, n) {\n\t\t\tforn(j, 26) cnt[j][i + 1] = cnt[j][i];\n\t\t\t++cnt[a[i] - 1][i + 1];\n\t\t}\n\t\tint ans = 0;\n\t\tforn(i, 26) ans = max(ans, cnt[i][n - 1]);\n\t\tforn(l, n) fore(r, l, n) {\n\t\t\tint cntin = 0, cntout = 0;\n\t\t\tforn(el, 26) {\n\t\t\t\tcntin = max(cntin, cnt[el][r + 1] - cnt[el][l]);\n\t\t\t\tcntout = max(cntout, min(cnt[el][l], cnt[el][n] - cnt[el][r + 1]) * 2);\n\t\t\t}\n\t\t\tans = max(ans, cntin + cntout);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1335",
    "index": "E2",
    "title": "Three Blocks Palindrome (hard version)",
    "statement": "\\textbf{The only difference between easy and hard versions is constraints}.\n\nYou are given a sequence $a$ consisting of $n$ positive integers.\n\nLet's define a \\textbf{three blocks palindrome} as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\\underbrace{a, a, \\dots, a}_{x}, \\underbrace{b, b, \\dots, b}_{y}, \\underbrace{a, a, \\dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are \\textbf{three block palindromes} but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.\n\nYour task is to choose the maximum by length \\textbf{subsequence} of $a$ that is a \\textbf{three blocks palindrome}.\n\nYou have to answer $t$ independent test cases.\n\nRecall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.",
    "tutorial": "I'll take some definitions from the solution of the easy version, so you can read it first if you don't understand something. Let $sum(c, l, r)$ be the number of occurrences of $c$ on the segment $[l; r]$. We will try to do almost the same solution as in the easy version. The only difference is how do we iterate over all segments corresponding to the second block of the required palindrome. Consider some number which we want to use as the number for the first and third blocks. If we take $k$ occurrences in the first block then we also take $k$ occurrences in the third block. Let's take these occurrences greedily! If we take $k$ elements in the first block (and also in the third block) then it is obviously better to take $k$ leftmost and $k$ rightmost elements correspondingly. Define $pos_c[i]$ be the position of the $i$-th occurrence of the number $c$ ($0$-indexed). So, if $pos_c$ is the array of length $sum(c, 0, n - 1)$ and contains all occurrences of $c$ in order from left to right then let's iterate over its left half and fix the amount of numbers $c$ we will take in the first block (and also in the third block). Let it be $k$. Then the left border of the segment for the second block is $l = pos_c[k - 1] + 1$ and the right border is $r = pos_c[sum(c, 0, n - 1) - k] - 1$. So let $cntin = \\max\\limits_{c=0}^{199} sum(c, l, r)$ and $cntout = k$ and we can update the answer with $2cntout + cntin$. It is easy to see that the total number of segments we consider is $O(n)$ so the total time complexity is $O(n \\cdot AL)$ (there are also solutions not depending on the size of the alphabet, at least Mo's algorithm in $O(n \\sqrt{n})$, but all of them are pretty hard to implement so I won't describe them here). And I'm also interested in $O(n \\log n)$ solution, so if you know it, share it with us!",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tvector<vector<int>> cnt(200, vector<int>(n + 1));\n\t\tvector<vector<int>> pos(200);\n\t\tforn(i, n) {\n\t\t\tforn(j, 200) cnt[j][i + 1] = cnt[j][i];\n\t\t\t++cnt[a[i] - 1][i + 1];\n\t\t\tpos[a[i] - 1].push_back(i);\n\t\t}\n\t\tint ans = 0;\n\t\tforn(i, 200) {\n\t\t\tans = max(ans, sz(pos[i]));\n\t\t\tforn(p, sz(pos[i]) / 2) {\n\t\t\t\tint l = pos[i][p] + 1, r = pos[i][sz(pos[i]) - p - 1] - 1;\n\t\t\t\tforn(el, 200) {\n\t\t\t\t\tint sum = cnt[el][r + 1] - cnt[el][l];\n\t\t\t\t\tans = max(ans, (p + 1) * 2 + sum);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1335",
    "index": "F",
    "title": "Robots on a Grid",
    "statement": "There is a rectangular grid of size $n \\times m$. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell $(i, j)$ is $c_{i, j}$. You are also given a map of directions: for each cell, there is a direction $s_{i, j}$ which is one of the four characters 'U', 'R', 'D' and 'L'.\n\n- If $s_{i, j}$ is 'U' then there is a transition from the cell $(i, j)$ to the cell $(i - 1, j)$;\n- if $s_{i, j}$ is 'R' then there is a transition from the cell $(i, j)$ to the cell $(i, j + 1)$;\n- if $s_{i, j}$ is 'D' then there is a transition from the cell $(i, j)$ to the cell $(i + 1, j)$;\n- if $s_{i, j}$ is 'L' then there is a transition from the cell $(i, j)$ to the cell $(i, j - 1)$.\n\nIt is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.\n\nYou want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied.\n\n- Firstly, each robot \\textbf{should move} every time (i.e. it cannot skip the move). \\textbf{During one move each robot goes to the adjacent cell depending on the current direction}.\n- Secondly, you have to place robots in such a way that \\textbf{there is no move} before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is \"RL\" (one row, two columns, colors does not matter there) then you can place two robots in cells $(1, 1)$ and $(1, 2)$, but if the grid is \"RLL\" then you cannot place robots in cells $(1, 1)$ and $(1, 3)$ because during the first second both robots will occupy the cell $(1, 2)$.\n\nThe robots make an infinite number of moves.\n\nYour task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of \\textbf{black} cells occupied by robots \\textbf{before all movements} is the maximum possible. \\textbf{Note that you can place robots only before all movements}.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "First of all, I want to say about $O(nm)$ solution. You can extract cycles in the graph, do some dynamic programming on trees, use some hard formulas and so on, but it is a way harder to implement than the other solution that only has an additional log, so I'll describe the one which is easier to understand and much easier to implement. Firstly, consider the problem from the other side. What is this grid? It is a functional graph (such a directed graph that each its vertex has exactly one outgoing edge). This graph seems like a set of cycles and ordered trees going into these cycles. How can it help us? Let's notice that if two robots meet after some move, then they'll go together infinitely from this moment. It means that if we try to make at least $nm$ moves from each possible cell, we will obtain some \"equivalence classes\" (it means that if endpoints of two cells coincide after $nm$ moves then you cannot place robots in both cells at once). So, if we could calculate such endpoints, then we can take for each possible endpoint the robot starting from the black cell (if such exists) and otherwise the robot starting from the white cell (if such exists). How can we calculate such endpoints? Let's number all cells from $0$ to $nm-1$, where the number of the cell $(i, j)$ is $i \\cdot m + j$. Let the next cell after $(i, j)$ is $(ni, nj)$ (i.e. if you make a move from $(i, j)$, you go to $(ni, nj)$). Also, let's create the two-dimensional array $nxt$, where $nxt[v][deg]$ means the number of the cell in which you will be if you start in the cell number $v$ and make $2^{deg}$ moves. What is the upper bound of $deg$? It is exactly $lognm = \\lceil\\log_{2}(nm + 1)\\rceil$. Well, we need to calculate this matrix somehow. It is obvious that if the number of the cell $(i, j)$ is $id$ and the number of the next cell $(ni, nj)$ is $nid$ then $nxt[id][0] = nid$. Then let's iterate over all degrees $deg$ from $1$ to $lognm - 1$ and for each vertex $v$ set $nxt[v][deg] = nxt[nxt[v][deg - 1]][deg - 1]$. The logic behind this expresion is very simple: if we want to jump $2^{deg}$ times from $v$ and we have all values for $2^{deg - 1}$ calculated then let's just jump $2^{deg - 1}$ times from $v$ and $2^{deg - 1}$ times from the obtained vertex. This technique is called binary lifting. Now we can jump from every cell $nm$ times in $O(\\log nm)$ time: just iterate over all degrees $deg$ from $0$ to $lognm-1$ and if $nm$ has the $deg$-th bit on, just jump from the current vertex $2^{deg}$ times (set $v := nxt[v][deg]$). The rest of solution is described above. Time complexity: $O(nm \\log_{2}nm)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <map>\n#include <set>\n#include <queue>\n#include <algorithm>\n#include <string>\n#include <cmath>\n#include <cstdio>\n#include <iomanip>\n#include <fstream>\n#include <cassert>\n#include <cstring>\n#include <unordered_set>\n#include <unordered_map>\n#include <numeric>\n#include <ctime>\n#include <bitset>\n#include <complex>\n#include <chrono>\n#include <random>\n#include <functional>\n\nusing namespace std;\n\nconst int N = 1e6 + 7;\nconst int K = 24;\n\nint f[N];\nint dp[N];\nint ndp[N];\nint sel[N];\n\nint fans[N];\nint sans[N];\n\nvoid solve() {\n\tint n, m;\n\tcin >> n >> m;\n\tfor (int i = 0; i < n; i++) {\n\t\tstring s;\n\t\tcin >> s;\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tsel[i * m + j] = (s[j] == '0');\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tstring s;\n\t\tcin >> s;\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tint to = -1;\n\t\t\tif (s[j] == 'U') to = (i - 1) * m + j;\n\t\t\tif (s[j] == 'D') to = (i + 1) * m + j;\n\t\t\tif (s[j] == 'L') to = i * m + (j - 1);\n\t\t\tif (s[j] == 'R') to = i * m + (j + 1);\n\t\t\tf[i * m + j] = to;\n\t\t}\n\t}\n\tn *= m;\n\tfor (int i = 0; i < n; i++) {\n\t\tdp[i] = f[i];\n\t}\n\tfor (int j = 0; j < K; j++) {\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tndp[i] = dp[dp[i]];\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tdp[i] = ndp[i];\n\t\t}\n\t}\n\tfill(fans, fans + n, 0);\n\tfill(sans, sans + n, 0);\n\tfor (int i = 0; i < n; i++) {\n\t\tfans[dp[i]]++;\n\t\tsans[dp[i]] += sel[i];\n\t}\n\tint fs = 0, ss = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tfs += (fans[i] > 0);\n\t\tss += (sans[i] > 0);\n\t}\n\tcout << fs << ' ' << ss << '\\n';\n}\n\nsigned main() {\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "matrices"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1336",
    "index": "A",
    "title": "Linova and Kingdom",
    "statement": "Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.\n\n There are $n$ cities and $n-1$ two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from $1$ to $n$, and the city $1$ is the capital of the kingdom. So, the kingdom has a tree structure.\n\nAs the queen, Linova plans to choose \\textbf{exactly} $k$ cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.\n\nA meeting is held in the capital once a year. To attend the meeting, each \\textbf{industry city} sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).\n\nTraveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of \\textbf{tourism cities} on his path.\n\nIn order to be a queen loved by people, Linova wants to choose $k$ cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?",
    "tutorial": "Lemma: In the optimum solution, if a node (except the root) is chosen to develop tourism, its parent must be chosen to develop tourism, too. Proof: Otherwise, if we choose its parent to develop tourism instead of itself, the sum of happiness will be greater. Then we can calculate how much happiness we will get if we choose a certain node to develop tourism. Suppose the depth of node $u$ is $dep_u$ (i.e. there are $dep_u$ nodes on the path $(1,u)$), the size of the subtree rooted on $u$ is $siz_u$ (i.e. there are $siz_u$ nodes $v$ that $u$ is on the path $(1,v)$). Then, if we choose $u$ to develop tourism, compared to choose it to develop industry, the total happiness will be increased by $siz_u-dep_u$: the envoy of $u$ won't be sent, we will lose $dep_u-1$ happiness; a total of $siz_u-1$ envoys of all nodes in the subtree rooted on $u$ except $u$ itself will get one more happiness. So, just use DFS to calculate all $siz_u-dep_u$, then sort them from big to small, calculate the sum of the first $n-k$ elements. You can also use std::nth_element in STL to get an $O(n)$ solution.",
    "code": "#include <bits/stdc++.h>\n#define maxn 200005\nstd::vector<int>conj[maxn];\nint n,k,u,v,depth[maxn]={0},size[maxn]={0},det[maxn];\nlong long ans=0;\nint cmp(int a,int b){return a>b;}\nint dfs(int u,int f){depth[u]=depth[f]+1;size[u]=1;\n\tfor (int i=0;i<conj[u].size();++i){\n\t\tif ((v=conj[u][i])==f)continue;\n\t\tsize[u]+=dfs(v,u);\n\t}det[u]=size[u]-depth[u];return size[u];\n}\nint main(){\n\tscanf(\"%d%d\",&n,&k);\n\tfor (int i=1;i<n;++i){\n\t\tscanf(\"%d%d\",&u,&v);conj[u].push_back(v);conj[v].push_back(u);\n\t}dfs(1,0);\n\tstd::nth_element(det+1,det+n-k,det+n+1,cmp);\n\tfor (int i=1;i<=n-k;++i)ans+=det[i];std::cout<<ans;\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1336",
    "index": "B",
    "title": "Xenia and Colorful Gems",
    "statement": "Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself.\n\n Recently Xenia has bought $n_r$ red gems, $n_g$ green gems and $n_b$ blue gems. Each of the gems has a weight.\n\nNow, she is going to pick three gems.\n\nXenia loves colorful things, so she will pick exactly one gem of each color.\n\nXenia loves balance, so she will try to pick gems with little difference in weight.\n\nSpecifically, supposing the weights of the picked gems are $x$, $y$ and $z$, Xenia wants to find the minimum value of $(x-y)^2+(y-z)^2+(z-x)^2$. As her dear friend, can you help her?",
    "tutorial": "First, let's assume that there exists an optimum solution in which we choose $r_x$, $g_y$ and $b_z$ satisfying $r_x \\le g_y \\le b_z$. Here's a lemma: When $y$ is fixed, $r_x$ is the maximum one that $r_x \\le g_y$, and $b_z$ is the minimum one that $g_y \\le b_z$. It's easy to prove: no matter what $z$ is, the bigger $r_x$ is, the smaller $(r_x-g_y)^2$ and $(r_x-b_z)^2$ are; for $b_z$ it's similar. So, if we know that in one of the optimum solutions, $r_x \\le g_y \\le b_z$, we can sort each array at first and then find $x$ and $z$ by binary search or maintaining some pointers while enumerating $y$. Back to the original problem without $r_x \\le g_y \\le b_z$, we can enumerate the six possible situations: $r_x \\le g_y \\le b_z$, $r_x \\le b_z \\le g_y$, $g_y \\le r_x \\le b_z$, $g_y \\le b_z \\le r_x$, $b_z \\le r_x \\le g_y$ and $b_z \\le g_y \\le r_x$. Find the optimum solution in each situation and the optimum one among them is the answer.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint t, nr, ng, nb;\nlong long ans;\n\nlong long sq(int x) { return 1ll * x * x; }\n\nvoid solve(vector<int> a, vector<int> b, vector<int> c) {\n    for (auto x : a) {\n        auto y = lower_bound(b.begin(), b.end(), x);\n        auto z = upper_bound(c.begin(), c.end(), x);\n        if (y == b.end() || z == c.begin()) { continue; }\n        z--; ans = min(ans, sq(x - *y) + sq(*y - *z) + sq(*z - x));\n    }\n}\n\nint main() {\n    for (cin >> t; t; t--) {\n        cin >> nr >> ng >> nb;\n        vector<int> r(nr), g(ng), b(nb);\n        for (int i = 0; i < nr; i++) { cin >> r[i]; }\n        for (int i = 0; i < ng; i++) { cin >> g[i]; }\n        for (int i = 0; i < nb; i++) { cin >> b[i]; }\n        sort(r.begin(), r.end());\n        sort(g.begin(), g.end());\n        sort(b.begin(), b.end());\n        ans = 9e18;\n        solve(r, g, b); solve(r, b, g);\n        solve(g, b, r); solve(g, r, b);\n        solve(b, r, g); solve(b, g, r);\n        cout << ans << endl;\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1336",
    "index": "C",
    "title": "Kaavi and Magic Spell",
    "statement": "Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future.\n\n Kaavi has a string $T$ of length $m$ and all the strings with the prefix $T$ are magic spells. Kaavi also has a string $S$ of length $n$ and an empty string $A$.\n\nDuring the divination, Kaavi needs to perform a sequence of operations. There are two different operations:\n\n- Delete the first character of $S$ and add it at the \\textbf{front} of $A$.\n- Delete the first character of $S$ and add it at the \\textbf{back} of $A$.\n\nKaavi can perform \\textbf{no more than} $n$ operations. To finish the divination, she wants to know the number of different operation sequences to make $A$ a magic spell (i.e. with the prefix $T$). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo $998\\,244\\,353$.\n\nTwo operation sequences are considered different if they are different in length or there exists an $i$ that their $i$-th operation is different.\n\nA substring is a contiguous sequence of characters within a string. A prefix of a string $S$ is a substring of $S$ that occurs at the beginning of $S$.",
    "tutorial": "We can use DP to solve this problem. Let $f_{i,j}$ be the answer when $S[0..i-1]$ has already been used and the current $A[0..\\min(i-1,m-1-j)]$ will be in the position $[j..\\min(i+j-1,m-1)]$ after all operations are finished. Specially, $f_{i,m}$ means that all characters in the current $A$ won't be in the position $[j..\\min(i+j-1,m-1)]$ after all operations are finished. By definition, $f_{n,0}=1$ and $f_{n, j}=0 (j\\ge 1)$. The state transition: $j=0$If $i\\ge m$, $A$ has already had the prefix $T$, so you can stop performing operations at any position, there are $n-i+1$ positions in total. Otherwise, only when $S[i]=T[i]$, you can add $S[i]$ at the back of $A$, there are $f_{i+1,0}$ different operation sequences in this situation. If $i\\ge m$, $A$ has already had the prefix $T$, so you can stop performing operations at any position, there are $n-i+1$ positions in total. Otherwise, only when $S[i]=T[i]$, you can add $S[i]$ at the back of $A$, there are $f_{i+1,0}$ different operation sequences in this situation. $1\\le j \\le m-1$If $i+j\\ge m$ or $S[i]=T[i+j]$, you can add $S[i]$ at the back of $A$, there are $f_{i+1,j}$ different operation sequences in this situation. If $S[i]=T[j-1]$, you can add $S[i]$ at the front of $A$, there are $f_{i+1,j-1}$ different operation sequences in this situation. If $i+j\\ge m$ or $S[i]=T[i+j]$, you can add $S[i]$ at the back of $A$, there are $f_{i+1,j}$ different operation sequences in this situation. If $S[i]=T[j-1]$, you can add $S[i]$ at the front of $A$, there are $f_{i+1,j-1}$ different operation sequences in this situation. $j=m$You can always add $S[i]$ at the front/back of $A$ in this situation ($2f_{i+1,m}$ different operation sequences). However, if $S[i]=T[m-1]$, you can let $S[i]$ to match $T[m-1]$ ($f_{i+1,m-1}$ different operation sequences). So, if $S[i]=T[m-1]$, $f_{i,m}=2f_{i+1,m}+f_{i+1,m-1}$. Otherwise, $f_{i,m}=2f_{i+1,m}$. You can always add $S[i]$ at the front/back of $A$ in this situation ($2f_{i+1,m}$ different operation sequences). However, if $S[i]=T[m-1]$, you can let $S[i]$ to match $T[m-1]$ ($f_{i+1,m-1}$ different operation sequences). So, if $S[i]=T[m-1]$, $f_{i,m}=2f_{i+1,m}+f_{i+1,m-1}$. Otherwise, $f_{i,m}=2f_{i+1,m}$. The answer is $2(f_{1,m}+\\sum\\limits_{T[i]=S[0]}f_{1,i})$.",
    "code": "#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nconst int mod = 998244353;\n\nint main()\n{\n\tstring s, t;\n\t\n\tcin >> s >> t;\n\tint n = s.size();\n\tint m = t.size();\n\t\n\tvector<vector<int> > f(n + 1, vector<int>(m + 1));\n\t\n\tf[n][0] = 1;\n\t\n\tfor (int i = n - 1; i >= 1; --i)\n\t{\n\t\tfor (int j = 0; j <= m; ++j)\n\t\t{\n\t\t\tif (j == 0)\n\t\t\t{\n\t\t\t\tif (i >= m) f[i][0] = n - i + 1;\n\t\t\t\telse if (s[i] == t[i]) f[i][0] = f[i + 1][0];\n\t\t\t}\n\t\t\telse if (j == m)\n\t\t\t{\n\t\t\t\tf[i][m] = 2 * f[i + 1][m] % mod;\n\t\t\t\tif (s[i] == t[m - 1]) f[i][m] = (f[i][m] + f[i + 1][m - 1]) % mod;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (i + j >= m || s[i] == t[i + j]) f[i][j] = f[i + 1][j];\n\t\t\t\tif (s[i] == t[j - 1]) f[i][j] = (f[i][j] + f[i + 1][j - 1]) % mod;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint ans = f[1][m];\n\tfor (int i = 0; i < m; ++i) if (t[i] == s[0]) ans = (ans + f[1][i]) % mod;\n\tans = ans * 2 % mod;\n\t\n\tcout << ans;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1336",
    "index": "D",
    "title": "Yui and Mahjong Set",
    "statement": "\\textbf{This is an interactive problem.}\n\nYui is a girl who enjoys playing Mahjong.\n\n She has a mysterious set which consists of tiles (this set can be empty). Each tile has an integer value between $1$ and $n$, and \\textbf{at most $n$ tiles} in the set have the same value. So the set can contain at most $n^2$ tiles.\n\nYou want to figure out which values are on the tiles. But Yui is shy, she prefers to play a guessing game with you.\n\nLet's call a set consisting of \\textbf{three} tiles triplet if their values are the same. For example, $\\{2,\\,2,\\,2\\}$ is a triplet, but $\\{2,\\,3,\\,3\\}$ is not.\n\nLet's call a set consisting of \\textbf{three} tiles straight if their values are consecutive integers. For example, $\\{2,\\,3,\\,4\\}$ is a straight, but $\\{1,\\,3,\\,5\\}$ is not.\n\nAt first, Yui gives you the number of triplet subsets and straight subsets of the initial set respectively. After that, you can insert a tile with an integer value between $1$ and $n$ into the set \\textbf{at most $n$ times}. Every time you insert a tile, you will get the number of triplet subsets and straight subsets of the current set as well.\n\nNote that two tiles with the same value are treated different. In other words, in the set $\\{1,\\,1,\\,2,\\,2,\\,3\\}$ you can find $4$ subsets $\\{1,\\,2,\\,3\\}$.\n\nTry to guess the number of tiles in the initial set with value $i$ for all integers $i$ from $1$ to $n$.",
    "tutorial": "Suppose $c_i$ equals to the number of tiles in the current set with value $i$ (before making a query). If you insert a tile with value $x$: The delta of triplet subsets is $\\dbinom{c_x}{2}$. Once you're sure that $c_x \\neq 0$ holds, you can determine the exact value of $c_x$. The delta of straight subsets is $c_{x-2}c_{x-1}+c_{x-1}c_{x+1}+c_{x+1}c_{x+2}$. Once you've known the values of $c_{1} \\ldots c_{x+1}$ and you're sure that $c_{x+1} \\neq 0$, you can determine the exact value of $c_{x+2}$. Let's insert tiles with following values in order: $n-1$, $n-2$, $\\ldots$, $3$, $1$, $2$, $1$. We can easily get $a_1$ by the delta of triplet subsets since we insert tiles with value $1$ twice. Consider the delta of straight subsets when you insert the tile with value $1$. It equals to $a_2(a_3+1)$ for the first time and $(a_2+1)(a_3+1)$ for the second time. Use subtraction to get $a_3$, then use division to get $a_2$. (The divisor is $a_3+1$, which is non-zero) Finally, let do the following for each $x$ from $2$ to $n-2$. We've known the values of $a_{1} \\ldots a_{x+1}$. Since we've inserted a tile with value $x+1$ before inserting $x$, we can use division to get $a_{x+2}$ by the delta of straight subsets and avoid dividing zero. PinkRabbitAFO gives another solution which inserts tiles with value $1$, $2$, $\\ldots$, $n-1$, $1$ in order. See more details here.",
    "code": "#include <cstdio>\n\nconst int MN = 105;\n\nint N, lstv1, lstv2, v1, v2;\nint dv1[MN], dv2[MN], Tag[MN], Ans[MN];\n\nint main() {\n\tscanf(\"%d\", &N);\n\tscanf(\"%d%d\", &lstv1, &lstv2);\n\tfor (int i = 1; i < N; ++i) {\n\t\tprintf(\"+ %d\\n\", i), fflush(stdout);\n\t\tscanf(\"%d%d\", &v1, &v2);\n\t\tdv1[i] = v1 - lstv1, dv2[i] = v2 - lstv2;\n\t\tif (dv1[i] > 0)\n\t\t\tfor (int x = 2; x <= N; ++x)\n\t\t\t\tif (x * (x - 1) / 2 == dv1[i]) {\n\t\t\t\t\tTag[i] = x; break;\n\t\t\t\t}\n\t\tlstv1 = v1, lstv2 = v2;\n\t}\n\tprintf(\"+ 1\\n\"), fflush(stdout);\n\tscanf(\"%d%d\", &v1, &v2);\n\tint ndv1 = v1 - lstv1, ndv2 = v2 - lstv2;\n\tfor (int x = 0; x <= N; ++x)\n\t\tif (x * (x + 1) / 2 == ndv1) {\n\t\t\tAns[1] = x; break;\n\t\t}\n\tint delta = ndv2 - dv2[1] - 1; // delta = a[2] + a[3]\n\tif (Tag[2] >= 2) Ans[2] = Tag[2], Ans[3] = delta - Ans[2];\n\telse if (Tag[3] >= 2) Ans[3] = Tag[3], Ans[2] = delta - Ans[3];\n\telse if (delta == 0) Ans[3] = Ans[2] = 0;\n\telse if (delta == 2) Ans[3] = Ans[2] = 1;\n\telse if (dv2[2] > 0) Ans[2] = 0, Ans[3] = 1;\n\telse Ans[2] = 1, Ans[3] = 0;\n\tfor (int i = 3; i <= N - 2; ++i) {\n\t\tif (Tag[i + 1] >= 2) {\n\t\t\tAns[i + 1] = Tag[i + 1];\n\t\t\tcontinue;\n\t\t}\n\t\tif ((Ans[i - 2] + 1) * (Ans[i - 1] + 1) == dv2[i]) Ans[i + 1] = 0;\n\t\telse Ans[i + 1] = 1;\n\t}\n\tAns[N] = (dv2[N - 1] - (Ans[N - 3] + 1) * (Ans[N - 2] + 1)) / (Ans[N - 2] + 1);\n\tprintf(\"!\");\n\tfor (int i = 1; i <= N; ++i) printf(\" %d\", Ans[i]);\n\tputs(\"\"), fflush(stdout);\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "interactive"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1336",
    "index": "E2",
    "title": "Chiori and Doll Picking (hard version)",
    "statement": "This is the hard version of the problem. The only difference between easy and hard versions is the constraint of $m$. You can make hacks only if both versions are solved.\n\nChiori loves dolls and now she is going to decorate her bedroom!\n\n As a doll collector, Chiori has got $n$ dolls. The $i$-th doll has a non-negative integer value $a_i$ ($a_i < 2^m$, $m$ is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are $2^n$ different picking ways.\n\nLet $x$ be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls $x = 0$). The value of this picking way is equal to the number of $1$-bits in the binary representation of $x$. More formally, it is also equal to the number of indices $0 \\leq i < m$, such that $\\left\\lfloor \\frac{x}{2^i} \\right\\rfloor$ is odd.\n\nTell her the number of picking ways with value $i$ for each integer $i$ from $0$ to $m$. Due to the answers can be very huge, print them by modulo $998\\,244\\,353$.",
    "tutorial": "Build linear basis $A$ with given numbers. Suppose: $k$ is the length of $A$. $S(A)$ is the set consisted of numbers which can be produced in $A$. $p_i$ is equal to the number of $x$, where $x \\in S(A)$ and $\\text{popcount}(x)=i$. $ans_i$ is equal to the number of doll picking ways with value $i$. Thus, $ans_i = p_i \\cdot 2^{n-k}$. Algorithm 1 Enumerate each base of $A$ is picked or not, so you can find out the whole $S(A)$ in $O(2^k)$ and get $p_0 \\ldots p_m$. Note that you should implement $\\text{popcount}(x)$ in $O(1)$ to make sure the whole algorithm runs in $O(2^k)$. Algorithm 2 Let's assume the highest $1$-bits in every base are key bits, so in $A$ there are $k$ key bits and $m-k$ non-key bits. We can get a new array of bases by Gauss-Jordan Elimination, such that every key bit is $1$ in exactly one base and is $0$ in other bases. Then, let $f_{i,j,s}$ be if we consider the first $i$ bases in $A$, the number of ways that $j$ key bits are $1$ in xor-sum and the binary status of all non-key bits is $s$. Enumerate $i$-th base (suppose it is equal to $x$) is picked or not, we write the state transition: $f_{i,j,s} = f_{i-1,j,s}+f_{i-1,j-1,s \\oplus x}$. At last, we add up $f_{k,j,s}$ to $p_{j+\\text{popcount}(s)}$. In conclusion, we get an $O(k^2 \\cdot 2^{m-k})$ algorithm. So far, the easy version can be passed if you write a solution which runs Algorithm 1 or Algorithm 2 by the value of $k$. Algorithm 3 We can regard $A$ as a $2^m$ long zero-indexation array satisfying $a_i=[i \\in S(A)]$. Similarly, we define a $2^m$ long zero-indexation array $F^c$ satisfying $f^c_i=[\\text{popcount}(i)=c]$. By XOR Fast Walsh-Hadamard Transform, we calculate $\\text{IFWT}(\\text{FWT}(A) * \\text{FWT}(F^c))$ (also can be written as $A \\oplus F^c$). $p_c$ is equal to the $0$-th number of resulting array. That means $p_c$ is also equal to the sum of every number in $\\text{FWT}(A) * \\text{FWT}(F^c)$ divide $2^m$. Lemma 1: $\\text{FWT}(A)$ only contains two different values: $0$ and $2^k$. Proof: The linear space satisfies closure, which means $A \\oplus A = A * 2^k$. Thus, $\\text{FWT}(A) * \\text{FWT}(A) = \\text{FWT}(A) * 2^k$. We can proved the lemma by solving an equation. Lemma 2: The $i$-th number of $\\text{FWT}(A)$ is $2^k$, if and only if $\\text{popcount}(i\\ \\&\\ x)$ is always even, where $x$ is any of $k$ bases in $A$. Proof: XOR Fast Walsh-Hadamard Transform tells us, the $i$-th number of $\\text{FWT}(A)$ is equal to the sum of $(-1)^{\\text{popcount}(i\\ \\&\\ j)}$ for each $j \\in S(A)$. Once we find a base $x$ such that $\\text{popcount}(i\\ \\&\\ x)$ is odd, the sum must be $0$ according to Lemma 1. Lemma 3: The indices of $\\text{FWT}(A)$ which their values are $2^k$, compose an orthogonal linear basis. Proof: See Lemma 2. If $\\text{popcount}(i\\ \\&\\ x)$ is even, $\\text{popcount}(j\\ \\&\\ x)$ is even, obviously $\\text{popcount}((i \\oplus j)\\ \\&\\ x)$ is even. Lemma 4: Suppose $B$ is the orthogonal linear basis. The length of $B$ is $m-k$. Proof: We know that $A=\\text{IFWT}(B*2^k)$, so $a_0 = 1 = \\dfrac{1}{2^m}\\sum\\limits_{i=0}^{2^m-1} b_i \\cdot 2^k$. From this, we then find that $|S(B)|$ should be $2^{m-k}$, which means the length of $B$ is $m-k$. Let the key bits in $A$ are non-key bits in $B$ and the non-key bits in $A$ are key bits in $B$. Now I'll show you how to get the $m-k$ bases in $B$. Divide key bits for $A$ and put them to the left. Similarly, we put the key bits in $B$ to the right. Let's make those $1$ key bits form a diagonal. Look at the following picture. Do you notice that the non-key bit matrices (green areas) are symmetrical along the diagonal? The proof is intuitive. $\\text{popcount}(x\\ \\&\\ y)$ should be even according to Lemma 2, where $x$ is any of bases in $A$ and $y$ is any of bases in $B$. Since we've divided key bits for two linear basis, $\\text{popcount}(x\\ \\&\\ y)$ is not more than $2$. Once two symmetrical non-key bits are $0$, $1$ respectively, there will exist $x$, $y$ satisfying $\\text{popcount}(x\\ \\&\\ y) = 1$. Otherwise, $\\text{popcount}(x\\ \\&\\ y)$ is always $0$ or $2$. In order to get $B$, you can also divide $A$ into $k$ small linear basis, construct their orthogonal linear basis and intersect them. It is harder to implement. Lemma 5: The $i$-th number of $\\text{FWT}(F^c)$ only depends on $\\text{popcount}(i)$. Proof: The $i$-th number of $F^c$ only depends on $\\text{popcount}(i)$, so it still holds after Fast Walsh-Hadamard Transform. Let $w_d^c$ be the $(2^d-1)$-th number of $\\text{FWT}(F^c)$. Again, Fast Walsh-Hadamard Transform tells us: $w_d^c = \\sum\\limits_{i=0}^{2^m-1} [\\text{popcount}(i)=c](-1)^{\\text{popcount}(i\\ \\&\\ (2^d-1))}$ Note that $\\text{popcount}(2^d-1)=d$. Let's enumerate $j = \\text{popcount}(i\\ \\&\\ (2^d-1))$. There are $\\dbinom{d}{j}$ different intersections, each one has $\\dbinom{m-d}{c-j}$ ways to generate the remaining part of $i$. So: $w_d^c = \\sum\\limits_{j=0}^{d} (-1)^j \\dbinom{d}{j}\\dbinom{m-d}{c-j}$ It takes $O(m^3)$ to calculate all necessary combinatorial numbers and $w_d^c$. Finally, let's consider the sum of every number in $\\text{FWT}(A) * \\text{FWT}(F^c)$. Suppose $q_i$ is equal to the number of $x$, where $x \\in S(B)$ and $\\text{popcount}(x)=i$. We can easily get: $p_c = \\dfrac{1}{2^m}\\sum\\limits_{d=0}^{m} 2^k q_d w_d^c = \\dfrac{1}{2^{m-k}}\\sum\\limits_{d=0}^{m} q_d w_d^c$ Just like Algorithm 1. We can enumerate each base of $B$ is picked or not, find out the whole $S(B)$ in $O(2^{m-k})$, get $q_0 \\ldots q_m$ and calculate $p_0 \\ldots p_m$ at last. Since one of $A$, $B$ has a length of not more than $m/2$, we just need to enumerate bases of the smaller one in order to pass the hard version in $O(2^{m/2} + m^3 + n)$. Solve the same problem with $m \\le 63$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int mod = 998244353, inv2 = 499122177;\nconst int M = 64;\n\nint n, m, k, p[M], c[M][M];\nlong long a[M], b[M], f[M];\n\nvoid dfs(int i, long long x) {\n    if (i == k) { p[__builtin_popcountll(x)]++; return; }\n    dfs(i + 1, x); dfs(i + 1, x ^ a[i]);\n}\n\nint main() {\n    cin >> n >> m;\n    for (int i = 0; i < n; i++) {\n        long long x; cin >> x;\n        for (int j = m; j >= 0; j--) {\n            if (x >> j & 1) {\n                if (!f[j]) { f[j] = x; break; }\n                x ^= f[j];\n            }\n        }\n    }\n    for (int i = 0; i < m; i++) {\n        if (f[i]) {\n            for (int j = 0; j < i; j++) {\n                if (f[i] >> j & 1) { f[i] ^= f[j]; }\n            }\n            for (int j = 0; j < m; j++) {\n                if (!f[j]) { a[k] = a[k] * 2 + (f[i] >> j & 1); }\n            }\n            a[k] |= 1ll << m - 1 - k; k++;\n        }\n    }\n    if (k <= 26) {\n        dfs(0, 0);\n        for (int i = 0; i <= m; i++) {\n            int ans = p[i];\n            for (int j = 0; j < n - k; j++) { ans = ans * 2 % mod; }\n            cout << ans << \" \";\n        }\n    } else {\n        k = m - k; swap(a, b);\n        for (int i = 0; i < k; i++) {\n            for (int j = 0; j < m - k; j++) {\n                if (b[j] >> i & 1) { a[i] |= 1ll << j; }\n            }\n            a[i] |= 1ll << m - 1 - i;\n        }\n        dfs(0, 0);\n        for (int i = 0; i <= m; i++) {\n            c[i][0] = 1;\n            for (int j = 1; j <= i; j++) { c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; }\n        }\n        for (int i = 0; i <= m; i++) {\n            int ans = 0;\n            for (int j = 0; j <= m; j++) {\n                int coef = 0;\n                for (int k = 0; k <= i; k++) {\n                    coef = (coef + (k & 1 ? -1ll : 1ll) * c[j][k] * c[m - j][i - k] % mod + mod) % mod;\n                }\n                ans = (ans + 1ll * coef * p[j]) % mod;\n            }\n            for (int j = 0; j < k; j++) { ans = 1ll * ans * inv2 % mod; }\n            for (int j = 0; j < n - m + k; j++) { ans = ans * 2 % mod; }\n            cout << ans << \" \";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1336",
    "index": "F",
    "title": "Journey",
    "statement": "In the wilds far beyond lies the Land of Sacredness, which can be viewed as a tree  — connected undirected graph consisting of $n$ nodes and $n-1$ edges. The nodes are numbered from $1$ to $n$.\n\nThere are $m$ travelers attracted by its prosperity and beauty. Thereupon, they set off their journey on this land. The $i$-th traveler will travel along the shortest path from $s_i$ to $t_i$. In doing so, they will go through all edges in the shortest path from $s_i$ to $t_i$, which is unique in the tree.\n\nDuring their journey, the travelers will acquaint themselves with the others. Some may even become friends. To be specific, the $i$-th traveler and the $j$-th traveler will become friends if and only if there are \\textbf{at least} $k$ edges that both the $i$-th traveler and the $j$-th traveler will go through.\n\nYour task is to find out the number of pairs of travelers $(i, j)$ satisfying the following conditions:\n\n- $1 \\leq i < j \\leq m$.\n- the $i$-th traveler and the $j$-th traveler will become friends.",
    "tutorial": "Idea: EternalAlexander First, let's choose an arbitrary root for the tree. Then for all pairs of paths, their LCA (lowest common ancestor) can be either different or the same. Then, let's calculate the answer of pairs with different LCAs. In this case, if the intersection is not empty, it will be a vertical path as in the graph below. Here path $G-H$ and path $E-F$ intersects at path $B-G$. We can process all paths in decreasing order of the depth of their LCA. When processing a path $p$ we calculate the number of paths $q$, where $q$ is processed before $p$, and the edge-intersection of $p$ and $q$ is at least $k$. To do this we can plus one to the subtree of the nodes on the path $k$ edges away from the LCA (node $C$ and $D$ for path $G-H$ in the graph above), then we can query the value at the endpoints of the path (node $E$ and $F$ for path $E-F$). We can maintain this easily with BIT (binary indexed tree, or Fenwick tree). Next, we calculate pairs with the same LCA. This case is harder. For each node $u$ we calculate the number of pairs with the LCA $u$. For a pair of path $(x_1,y_1)$ and $(x_2, y_2)$, there are still two cases we need to handle. Let $dfn_x$ be the index of $x$ in the DFS order. For a path $(x,y)$ we assume that $dfn_x < dfn_y$ (otherwise you can just swap them) In the first case ( the right one in the graph above, where $(x_1,y_1) = (B,E), (x_2,y_2) = (C,F)$ ), the intersection of $(x_1,y_1)$ and $(x_2,y_2)$ is the path that goes from $\\operatorname{LCA}(x_1,x_2)$ to $\\operatorname{LCA}(y_1,y_2)$ (path $A - D$) In this case the intersection may cross over node $u$. For all paths $(x,y)$ with the LCA $u$. We can build a virtual-tree over all $x$ of the paths, and on node $x$ we store the value of $y$. Let's do a dfs on the virtual-tree. On each node $a$ we calculate pairs $(x_1,y_1)$,$(x_2,y_2)$ that $\\operatorname{LCA}(x_1,x_2) = a$. For $x_1$ , let's go from $a$ to $y_1$ for $k$ edges, assume the node we reached is $b$, all legal $y_2$ should be in the subtree of $b$. We can use a segment tree on the DFS-order to maintain all $y$s in the subtree and merge them with the small-to-large trick, meanwhile, iterate over all $x_1$ in the smaller segment tree, count the valid $y_2$'s in the larger segment tree. In fact, you can use HLD (heavy-light decomposition) instead of virtual-tree, which seems to be easier to implement. Now note that the solution above is based on the fact that the intersection of $(x_1,y_1)$ and $(x_2,y_2)$ is the path that goes from $\\operatorname{LCA}(x_1,x_2)$ to $\\operatorname{LCA}(y_1,y_2)$. But it is not always true, so here we have another case to handle. In this case, (the left one in the graph above), the intersection is definitely a vertical path that goes from $u$ to $\\operatorname{LCA(y_1,x_2)}$. This can be solved similarly to the case of different LCAs. The overall complexity of this solution is $O(m \\log^2 m + n\\log n)$.",
    "code": "#include <bits/stdc++.h>\n#define maxn 200005\nint n,m,k,u[maxn],v[maxn],ch[maxn<<6][2]={0},sum[maxn<<6]={0},pt[maxn],head[maxn]={0},tail=0,cnt=0,root[maxn]={0},\nanc[maxn][19]={0},son[maxn]={0},depth[maxn]={0},dfn[maxn],size[maxn],idx=0;\nlong long ans=0;\nstd::vector<int>in[maxn],vec[maxn];\nstruct edge {\n\tint v,next;\n}edges[maxn<<1];\nvoid add_edge(int u,int v){\n\tedges[++tail].v=v;\n\tedges[tail].next=head[u];\n\thead[u]=tail;\n}\nnamespace BIT {\n\tint sum[maxn<<2]={0};\n\tvoid add(int p,int x) {if (p==0) return;while (p<=n) {sum[p]+=x;p+=p&-p;}}\n\tint query(int p) {int ans=0;while (p>0) {ans+=sum[p];p-=p&-p;}return ans;}\n\tvoid Add(int l,int r){add(l,1);add(r+1,-1);}\n}\nvoid update(int x){sum[x]=sum[ch[x][0]]+sum[ch[x][1]];}\nint insert(int rt,int l,int r,int p){\n\tif (!rt) rt=++cnt;\n\tif (l==r) {sum[rt]++;return rt;}\n\tint mid=(l+r)>>1;\n\tif (p<=mid) ch[rt][0]=insert(ch[rt][0],l,mid,p);\n\telse ch[rt][1]=insert(ch[rt][1],mid+1,r,p);\n\tupdate(rt);\n\treturn rt;\n} int merge(int u,int v){\n\tif (!u||!v)return u+v;\n\tch[u][0]=merge(ch[u][0],ch[v][0]);\n\tch[u][1]=merge(ch[u][1],ch[v][1]);\n\tsum[u]=sum[u]+sum[v];return u;\n} int query(int rt,int L,int R,int l,int r){\n\tif (l>R||r<L)return 0;\n\tif (l<=L&&R<=r){return sum[rt];}\n\treturn query(ch[rt][0],L,(L+R)>>1,l,r)+query(ch[rt][1],((L+R)>>1)+1,R,l,r);\n}\n\nvoid dfs1(int u,int f){\n\tanc[u][0]=f;depth[u]=depth[f]+1;size[u]=1;\n\tfor (int i=1;i<=18;++i)anc[u][i]=anc[anc[u][i-1]][i-1];\n\tfor (int i=head[u];i;i=edges[i].next){\n\t\tint v=edges[i].v;\n\t\tif (v==f) continue;\n\t\tdfs1(v,u);size[u]+=size[v];\n\t\tif (size[v]>size[son[u]])son[u]=v;\n\t}\n} void dfsn(int u){\n\tdfn[u]=++idx;\n\tfor (int i=head[u];i;i=edges[i].next){\n\t\tint v=edges[i].v;\n\t\tif (v==son[u]||v==anc[u][0])continue;\n\t\tdfsn(v);\n\t}if (son[u]) dfsn(son[u]);\n}\n\nint lift(int u,int x){\n\tfor (int i=18;i>=0;i--)if (x>=(1<<i)) {u=anc[u][i];x-=(1<<i);}\n\treturn u;\n}\n\nint lca(int u,int v){\n\tif (depth[u]<depth[v])std::swap(u,v);\n\tfor (int i=18;i>=0;i--)if (depth[anc[u][i]]>=depth[v])u=anc[u][i];\n\tif (u==v)return u;\n\tfor (int i=18;i>=0;i--)if (anc[u][i]!=anc[v][i]){u=anc[u][i];v=anc[v][i];}\n\treturn anc[u][0];\n} \n\nvoid dfs3(int x,int rt){\n\tpt[x]=x;root[x]=0;\n\tfor (int i=0;i<in[x].size();++i) {\n\t\tint d=in[x][i];\n\t\tint rd=std::max(0,k-(depth[u[d]]-depth[rt]));\n\t\tif (depth[v[d]]-depth[rt]>=rd){\n\t\t\tint l=lift(v[d],depth[v[d]]-depth[rt]-rd);\n\t\t\tans+=query(root[x],1,n,dfn[l],dfn[l]+size[l]-1);\n\t\t}root[x]=insert(root[x],1,n,dfn[v[d]]);\n\t}for (int i=head[x];i;i=edges[i].next){\n\t\tint t=edges[i].v;\n\t\tif (t==anc[x][0]||(rt==x&&t==son[x])) continue;\n\t\tdfs3(t,rt);\n\t\tif (in[pt[x]].size()<in[pt[t]].size()){\n\t\t\tstd::swap(pt[x],pt[t]);\n\t\t\tstd::swap(root[x],root[t]);\n\t\t}while (!in[pt[t]].empty()){\n\t\t\tint d=in[pt[t]][in[pt[t]].size()-1];in[pt[t]].pop_back();\n\t\t\tint rd=std::max(0,k-(depth[x]-depth[rt]));\n\t\t\tif (depth[v[d]]-depth[rt]>=rd) {\n\t\t\t\tint l=lift(v[d],(depth[v[d]]-depth[rt]-rd));\n\t\t\t\tans+=query(root[x],1,n,dfn[l],dfn[l]+size[l]-1);\n\t\t\t}in[pt[x]].push_back(d);\n\t\t}root[x]=merge(root[x],root[t]);\n\t}\n}\n\nvoid dfs2(int x){\n\tint len=vec[x].size();\n\tfor (int i=head[x];i;i=edges[i].next)if (edges[i].v!=anc[x][0])dfs2(edges[i].v);\n\tfor (int i=0;i<len;++i)ans+=BIT::query(dfn[v[vec[x][i]]]);\n\tfor (int i=0;i<len;++i){\n\t\tint j=vec[x][i];\n\t\tif (depth[v[j]]-depth[x]>=k) {\n\t\t\tint l=lift(v[j],depth[v[j]]-depth[x]-k);\n\t\t\tBIT::Add(dfn[l],dfn[l]+size[l]-1);\n\t\t}\n\t}for (int i=0;i<len;++i){ans+=BIT::query(dfn[u[vec[x][i]]]);in[u[vec[x][i]]].push_back(vec[x][i]);}\n\tdfs3(x,x);\n\twhile (!in[pt[x]].empty())in[pt[x]].pop_back();\n\tfor (int i=0;i<len;++i){\n\t\tint j=vec[x][i];\n\t\tif (depth[u[j]]-depth[x]>=k) {\n\t\t\tint l=lift(u[j],depth[u[j]]-depth[x]-k);\n\t\t\tBIT::Add(dfn[l],dfn[l]+size[l]-1);\n\t\t}\n\t}\n}\n\t\nint main(){\n\tscanf(\"%d%d%d\",&n,&m,&k);\n\tfor(int i=1;i<n;++i){\n\t\tint u,v;\n\t\tscanf(\"%d%d\",&u,&v);\n\t\tadd_edge(u,v);\n\t\tadd_edge(v,u);\n\t}dfs1(1,0);dfsn(1);\n\tfor (int i=1;i<=m;++i){\n\t\tscanf(\"%d%d\",&u[i],&v[i]);\n\t\tif (dfn[u[i]]>dfn[v[i]]) std::swap(u[i],v[i]);\n\t\tint l=lca(u[i],v[i]);\n\t\tvec[l].push_back(i);\n\t} dfs2(1);\n\tstd::cout<<ans;\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "graphs",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1337",
    "index": "A",
    "title": "Ichihime and Triangle",
    "statement": "Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.\n\nThese days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem.\n\n You are given four positive integers $a$, $b$, $c$, $d$, such that $a \\leq b \\leq c \\leq d$.\n\nYour task is to find three integers $x$, $y$, $z$, satisfying the following conditions:\n\n- $a \\leq x \\leq b$.\n- $b \\leq y \\leq c$.\n- $c \\leq z \\leq d$.\n- There exists a triangle with a positive non-zero area and the lengths of its three sides are $x$, $y$, and $z$.\n\nIchihime desires to get the cookie, but the problem seems too hard for her. Can you help her?",
    "tutorial": "There are many possible solutions, one of them is to always output $b$, $c$, $c$. You can easily prove that $b$, $c$, $c$ always satisfies the requirements.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint t, a, b, c, d;\n\nint main() {\n    for (cin >> t; t; t--) {\n        cin >> a >> b >> c >> d;\n        cout << b << \" \" << c << \" \" << c << endl;\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1337",
    "index": "B",
    "title": "Kana and Dragon Quest game",
    "statement": "Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.\n\nOne day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.\n\n The dragon has a hit point of $x$ initially. When its hit point goes to $0$ or under $0$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells.\n\n- Void Absorption Assume that the dragon's current hit point is $h$, after casting this spell its hit point will become $\\left\\lfloor \\frac{h}{2} \\right\\rfloor + 10$. Here $\\left\\lfloor \\frac{h}{2} \\right\\rfloor$ denotes $h$ divided by two, rounded down.\n- Lightning Strike This spell will decrease the dragon's hit point by $10$. Assume that the dragon's current hit point is $h$, after casting this spell its hit point will be lowered to $h-10$.\n\nDue to some reasons Kana can only cast \\textbf{no more than} $n$ Void Absorptions and $m$ Lightning Strikes. She can cast the spells in any order and \\textbf{doesn't have to} cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.",
    "tutorial": "First, it's better not to cast Void Absorptions after a Lightning Strike. Otherwise, there will be a Void Absorption right after a Lightning Strike. Supposing the hit point was $x$ before casting these two spells, if you cast Lightning Strike first, after these two spells the hit point will be $\\left\\lfloor \\frac{x-10}{2} \\right\\rfloor +10 = \\left\\lfloor \\frac{x}{2} \\right\\rfloor + 5$, but if you cast Void Absorption first, after these two spells the hit point will be $\\left\\lfloor \\frac{x}{2} \\right\\rfloor$, which is smaller. So the solution is to cast Void Absorptions until the dragon's hit point won't decrease with more casts or you can't cast more Void Absorptions, then cast all Lightning Strikes you have. We can also use DP to solve this problem. Let $f_{i,j,k} = 0/1$ be possibility of defeating the dragon when the dragon's hit point is at $i$, you can cast $j$ more Void Absorptions and $k$ more Lightning Strikes. This is a slow solution but is enough to get accepted. You may have to use boolean arrays instead of integer arrays to save memory.",
    "code": "#include <bits/stdc++.h>\nint x,n,m,t;\nvoid solve(){\n\tscanf(\"%d%d%d\",&x,&n,&m);\n\twhile (x>0&&n&&x/2+10<x){n--;x=x/2+10;}\n\tif (x<=m*10)printf(\"YES\\n\");\n\telse printf(\"NO\\n\"); \n}\nint main(){\n\tscanf(\"%d\",&t);\n\twhile(t--)solve();\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1338",
    "index": "A",
    "title": "Powered Addition",
    "statement": "You have an array $a$ of length $n$. For every positive integer $x$ you are going to perform the following operation during the $x$-th second:\n\n- Select some distinct indices $i_{1}, i_{2}, \\ldots, i_{k}$ which are between $1$ and $n$ inclusive, and add $2^{x-1}$ to each corresponding position of $a$. Formally, $a_{i_{j}} := a_{i_{j}} + 2^{x-1}$ for $j = 1, 2, \\ldots, k$. \\textbf{Note that you are allowed to not select any indices at all.}\n\nYou have to make $a$ nondecreasing as fast as possible. Find the smallest number $T$ such that you can make the array nondecreasing after at most $T$ seconds.\n\nArray $a$ is nondecreasing if and only if $a_{1} \\le a_{2} \\le \\ldots \\le a_{n}$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "First, let's define $b$ as ideal destination of $a$, when we used operations. Observation 1. Whatever you select any $b$, there is only one way to make it, because there is no more than single way to make specific amount of addition. That means we just have to select optimal destination of $a$. For example, if you want to make $a_{1}$ from 10 to 21, then you must do $10 \\to 11 \\to 13 \\to 21$. There is no other way to make $10$ to $21$ using given operations. So now we have to minimize $max(b_{1} - a_{1}, b_{2} - a_{2}, \\ldots, b_{n} - a_{n})$, as smaller differences leads to use shorter time to make $a$ nondecreasing. Observation 2. $b$ is optimal when $b_{i}$ is the maximum value among $b_{1}, b_{2}, \\ldots, b_{i-1}$ and $a_{i}$. Because for each position $i$, we have to make $b_{i} - a_{i}$ as smallest possible. Since $b_{i}$ should be not smaller than previous $b$ values and also $a_{i}$, we derived such formula. So from position $1, 2, \\ldots, n$, greedily find a $b_{i}$, and check how many seconds needed to convert $a_{i}$ to $b_{i}$. The answer is maximum needed seconds among all positions. Time complexity is $O(n)$, but you can do $O(n \\log n)$ with \"std::set\" or whatever.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1338",
    "index": "B",
    "title": "Edge Weight Assignment",
    "statement": "You have unweighted tree of $n$ vertices. You have to assign a \\textbf{positive} weight to each edge so that the following condition would hold:\n\n- For every two different leaves $v_{1}$ and $v_{2}$ of this tree, bitwise XOR of weights of all edges on the simple path between $v_{1}$ and $v_{2}$ has to be equal to $0$.\n\nNote that you can put \\textbf{very large} positive integers (like $10^{(10^{10})}$).\n\nIt's guaranteed that such assignment always exists under given constraints. Now let's define $f$ as \\textbf{the number of distinct weights} in assignment.\n\n\\begin{center}\nIn this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is $0$. $f$ value is $2$ here, because there are $2$ distinct edge weights($4$ and $5$).In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex $1$ and vertex $6$ ($3, 4, 5, 4$) is not $0$.\n\\end{center}\n\nWhat are the minimum and the maximum possible values of $f$ for the given tree? Find and print both.",
    "tutorial": "Let's make an easy and good construction which can solve actual problem. Now reroot this tree at any leaf like picture below; Our goal in this construction is, we are trying to make $xor(path(l_{1}, lca(l_{1}, l_{2}))) = xor(path(l_{2}, lca(l_{1}, l_{2}))) = xor(path(root, lca(l_{1}, l_{2})))$ for all two leaves $l_{1}$ and $l_{2}$ to satisfy $xor(path(l_{1}, l_{2})) = 0$. First, let's solve about minimum $f$ value. Observation 1. You can prove that minimum value of $f$ is at most $3$, by following construction; Since we pick any leaf as root, root is not at the top in this picture. Weight of edges are only determined by degree of two vertices and whether that edge is connected to leaf or not. So answer for minimum value is at most $3$. Observation 2. If there is any construction such that $f = 2$, then it is always possible to have construction of $f = 1$. Because if $f = 2$ then there should be even number of edges for each weight, and you can simply change all weights them to single value without violating validity of edge weight assignment. If you want to check validity of $f = 1$ assignment, then you can simply check if all leaves have same parity of distance from root. Because distances between all nodes should be even. Now let's solve about maximum value. Observation 3. You can solve maximum value of $f$ by following construction; So for each non-root vertex $i$, assign weight to edge between $i$ and $p_{i}$ by followings ($p_{i}$ is parent of vertex $i$); If $i$ is not leaf, then assign $2^{i}$ as weight. Otherwise, assign $xor(path(root, p_{i}))$ as weight. This will differentize all edges' weights except for multiple leaves's edges which are connected to single vertex, because every non-leaf vertex have different weights of edge to its parent. So the answer for maximum value is $e - l + m$, where $e$ is number of edges in this tree. $l$ is number of leaves in this tree. $m$ is number of non-leaves which has at least one leaf as its neighbor. Time complexity is $O(n)$. ------ (Update) There is an another way to approach, provided by Darooha. If you label vertices instead of edges where all leaves have same label and none of neighbors have same label, then you can consider edge weight as xor of two vertices' labels, so this is basically equivalent to original problem. Now for minimum, you can see that labelling $0$ to leaves, and $1, 2$ to non-leaves are enough, so you can prove minimum value of $f$ is at most $3$. In same manner, you can try parity checking to check if $f$ value can be $1$ or not. For maximum, assign $0$ to all leaves and assign all different values($2^{1}, 2^{2}, \\ldots$) to non-leaf vertices, then you can see all edge weights(except leaves connected to same vertex) are different.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1338",
    "index": "C",
    "title": "Perfect Triples",
    "statement": "Consider the infinite sequence $s$ of positive integers, created by repeating the following steps:\n\n- Find the lexicographically smallest triple of positive integers $(a, b, c)$ such that\n\n- $a \\oplus b \\oplus c = 0$, where $\\oplus$ denotes the bitwise XOR operation.\n- $a$, $b$, $c$ are not in $s$.\n\nHere triple of integers $(a_1, b_1, c_1)$ is considered to be lexicographically smaller than triple $(a_2, b_2, c_2)$ if sequence $[a_1, b_1, c_1]$ is lexicographically smaller than sequence $[a_2, b_2, c_2]$.\n- Append $a$, $b$, $c$ to $s$ in this order.\n- Go back to the first step.\n\nYou have integer $n$. Find the $n$-th element of $s$.\n\nYou have to answer $t$ independent test cases.\n\nA sequence $a$ is lexicographically smaller than a sequence $b$ if in the first position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.",
    "tutorial": "Let's try mathematical induction. First, suppose you have fully used numbers only between $1$ and $4^{n} - 1$ inclusive. Now we are going to use all numbers between $4^{n}$ and $4^{n+1} - 1$ inclusive by following methods. Following picture is description of $a$, $b$ and $c$ in bitwise manner; First row means we have already used all numbers until $4^{n} - 1$. Other $3$ rows mean $a$, $b$ and $c$. Keep in mind that $a$, $b$, and $c$ are the lexicographically smallest triple, so $a \\oplus b = c$ and $a < b < c$ should be satisfied at the same time. Observation 1. $a_{2n} = 1$, $a_{2n+1} = 0$, $b_{2n} = 0$, $b_{2n+1} = 1$, $c_{2n} = c_{2n+1} = 1$. Otherwise, $a < b < c$ condition won't be satisfied, because top two digits of $a$, $b$, $c$ are either $01$, $10$, and $11$. Then we have more freedom in lower digits, because since the highest $2$ digits are all different, then we can fill lower digits of three numbers independently. Now look at picture below; This table shows you how to fill each $2$ digits of $a$, $b$ and $c$. Observation 2. For each $2$ digits, $a$, $b$ and $c$ should have form like this. Of course, you can use mathematical induction again here; Try to prove this in only $2$ digits at the first, then expand this lemma to $4$ digits, $6$ digits, ..., $2n$ digits. Now you know the pattern of digits of $a$, $b$, and $c$. Apply this pattern for each test case. Time complexity is $O(\\log n)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "divide and conquer",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1338",
    "index": "D",
    "title": "Nested Rubber Bands",
    "statement": "You have a tree of $n$ vertices. You are going to convert this tree into $n$ rubber bands on infinitely large plane. Conversion rule follows:\n\n- For every pair of vertices $a$ and $b$, rubber bands $a$ and $b$ should intersect if and only if there is an edge exists between $a$ and $b$ in the tree.\n- Shape of rubber bands must be a simple loop. In other words, rubber band is a loop which doesn't self-intersect.\n\nNow let's define following things:\n\n- Rubber band $a$ \\textbf{includes} rubber band $b$, if and only if rubber band $b$ is in rubber band $a$'s area, and they don't intersect each other.\n- Sequence of rubber bands $a_{1}, a_{2}, \\ldots, a_{k}$ ($k \\ge 2$) are \\textbf{nested}, if and only if for all $i$ ($2 \\le i \\le k$), $a_{i-1}$ includes $a_{i}$.\n\n\\begin{center}\nThis is an example of conversion. Note that rubber bands $5$ and $6$ are nested.\n\\end{center}\n\nIt can be proved that is it possible to make a conversion and sequence of nested rubber bands under given constraints.\n\nWhat is the maximum length of sequence of nested rubber bands can be obtained from given tree? Find and print it.",
    "tutorial": "Observation 1. You have to generate optimal sequence which is subsequence of path between some two vertices. Neighbors of vertices in optimal sequence will be used as nested rubber bands. This is an example of conversion. Red vertices are picked sequence, and blue vertices are neighbor of red vertices which are used as nested rubber bands. The reason why black vertices can't be used as nested rubber bands is, basically you have to make a tunnel between any two blue lines, but it's impossible, because in each tunnel there is at least one red vertex which blocks complete connection on tunnel. Also, this can be described as finding maximum independent set on subtree, which consists of vertices which has at most $1$ distance from the optimal path connection of red vertices. Now your goal is to maximize number of blue vertices. Observation 2. The distances between two adjacent red vertices are at most $2$. Adjacent in this sentence means adjacent elements in generated optimal sequence. Because if there is some unused It is always optimal to take more red vertices than abandoning black vertices. Note that if there are two black vertices between two red vertices, then we cannot use both of them as blue vertices. From those two observations, construct tree DP and run for it. Time complexity is $O(n)$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1338",
    "index": "E",
    "title": "JYPnation",
    "statement": "Due to the success of TWICE, JYP Entertainment has earned countless money and emerged as the biggest entertainment firm by market capitalization. Therefore, the boss, JYP, has decided to create a new nation and has appointed you to provide a design diagram.\n\nThe new nation consists of $n$ cities and some roads between them. JYP has given some restrictions:\n\n- To guarantee efficiency while avoiding chaos, \\textbf{for any $2$ different cities $A$ and $B$, there is exactly one road between them, and it is one-directional. There are no roads connecting a city to itself}.\n- The logo of rivaling companies should not appear in the plan, that is, \\textbf{there does not exist} $4$ \\textbf{distinct cities} $A$,$B$,$C$,$D$ \\textbf{, such that the following configuration occurs.}\n\nJYP has given criteria for your diagram. For two cities $A$,$B$, let $dis(A,B)$ be the smallest number of roads you have to go through to get from $A$ to $B$. If it is not possible to walk from $A$ to $B$, $dis(A,B) = 614n$. Then, the efficiency value is defined to be the sum of $dis(A,B)$ for all ordered pairs of distinct cities $(A,B)$.\n\n\\textbf{Note that $dis(A,B)$ doesn't have to be equal to $dis(B,A)$}.\n\nYou have drawn a design diagram that satisfies JYP's restrictions. Find the sum of $dis(A,B)$ over all ordered pairs of cities $(A,B)$ with $A\\neq B$.\n\n\\textbf{Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.}",
    "tutorial": "The solution contains several tricky observations, but its not hard to prove each of them seperately, so I will mention only the key points of the solution and proof. Firstly, we should repeatedly remove points that have no in-degree. We can calculate their contribution easily. For a node $x$, define $in(x)$ to be the set of nodes $u$ that $u \\rightarrow x$ exists. Lemma 1: $in(x) \\cup {x}$ has no cycles for any node $x$. Let's pick $X$ to be the node with maximum in-degree. Let $P$ = $in(X) \\cup {X}$, and let $Q$ = $Z \\setminus P$, where $Z$ is the set of all vertices. Lemma 2: There exist nodes $U \\in Q$,$V \\in P$, such that $U \\rightarrow V$ exists. Let $R$ = $in(V) \\cap Q$, and let $S$ = $Q \\setminus R$ Lemma 3: For all nodes $A \\in S$,$B \\in R$, $A \\rightarrow B$ exists. Lemma 4: $S$ has no cycles, $R$ has no cycles. Lemma 5: $P$ has no cycles, $Q$ has no cycles. That means we have partitioned the graph into two sets of nodes, where each set is completely ordered. Lets label the nodes in $P$ by $P_i$ where $i$ is an integer from $1$ to $|P|$, such that for two nodes $P_i$ and $P_j$, $P_j \\rightarrow P_i$ exists iff $j>i$. Label nodes in $Q$ by $Q_i$ in similar manner. Define $inP(x)$ to be the set of nodes $u \\in P$ that $u \\rightarrow x$ exists. Define $inQ(x)$ to be the set of nodes $u \\in Q$ that $u \\rightarrow x$ exists. Lemma 6a: If $|inQ(P_i)| = |inQ(P_j)|$ then $inQ(P_i) = inQ(P_j)$. Lemma 6b: If $|inP(Q_i)| = |inP(Q_j)|$ then $inP(Q_i) = inP(Q_j)$. Final observations: $dis(P_i,P_j)=1$ iff $i>j$ $dis(P_i,P_j)=2$ iff $i<j$ and $|inQ(P_i)| \\neq |inQ(P_j)|$ $dis(P_i,P_j)=3$ iff $i<j$ and $|inQ(P_i)| = |inQ(P_j)|$ $dis(Q_i,Q_j)=1$ iff $i>j$ $dis(Q_i,Q_j)=2$ iff $i<j$ and $|inP(Q_i)| \\neq |inP(Q_j)|$ $dis(Q_i,Q_j)=3$ iff $i<j$ and $|inP(Q_i)| = |inP(Q_j)|$ $dis(P_i,Q_j)+dis(Q_j,P_i)=3$ Finally, we can count the answer in $O(N^2)$ by the above observations.",
    "tags": [
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1339",
    "index": "A",
    "title": "Filling Diamonds",
    "statement": "You have integer $n$. Calculate how many ways are there to fully cover belt-like area of $4n-2$ triangles with diamond shapes.\n\nDiamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it.\n\n$2$ coverings are different if some $2$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.\n\nPlease look at pictures below for better understanding.\n\n\\begin{center}\nOn the left you can see the diamond shape you will use, and on the right you can see the area you want to fill.These are the figures of the area you want to fill for $n = 1, 2, 3, 4$.\n\\end{center}\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The key observation of this problem is, wherever you put vertical diamond at some point, all other places are uniquely placed by horizontal diamonds like picture below. There are $n$ places you can put vertical diamond, so answer is $n$ for each test case.",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1339",
    "index": "B",
    "title": "Sorted Adjacent Differences",
    "statement": "You have array of $n$ numbers $a_{1}, a_{2}, \\ldots, a_{n}$.\n\nRearrange these numbers to satisfy $|a_{1} - a_{2}| \\le |a_{2} - a_{3}| \\le \\ldots \\le |a_{n-1} - a_{n}|$, where $|x|$ denotes absolute value of $x$. It's always possible to find such rearrangement.\n\nNote that all numbers in $a$ are not necessarily different. In other words, some numbers of $a$ may be same.\n\nYou have to answer independent $t$ test cases.",
    "tutorial": "Sort the list, and make an oscillation centered on middle element like picture below. In this way, you will always achieve to make $|a_{i} - a_{i+1}| \\le |a_{i+1} - a_{i+2}|$ for all $i$. Time complexity is $O(n \\log n)$.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1340",
    "index": "A",
    "title": "Nastya and Strange Generator",
    "statement": "Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something.\n\nDenis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.\n\nWhen he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $n$ steps. At the $i$-th step, a place is chosen for the number $i$ $(1 \\leq i \\leq n)$. The position for the number $i$ is defined as follows:\n\n- For all $j$ from $1$ to $n$, we calculate $r_j$  — the minimum index such that $j \\leq r_j \\leq n$, and the position $r_j$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $r_j$ is not defined.\n- For all $t$ from $1$ to $n$, we calculate $count_t$  — the number of positions $1 \\leq j \\leq n$ such that $r_j$ is defined and $r_j = t$.\n- Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $count$ array is maximum.\n- The generator selects one of these positions for the number $i$. The generator can choose \\textbf{any} position.\n\nLet's have a look at the operation of the algorithm in the following example:\n\nLet $n = 5$ and the algorithm has already arranged the numbers $1, 2, 3$ in the permutation. Consider how the generator will choose a position for the number $4$:\n\n- The values of $r$ will be $r = [3, 3, 3, 4, \\times]$, where $\\times$ means an indefinite value.\n- Then the $count$ values will be $count = [0, 0, 3, 1, 0]$.\n- There are only two unoccupied positions in the permutation: $3$ and $4$. The value in the $count$ array for position $3$ is $3$, for position $4$ it is $1$.\n- The maximum value is reached only for position $3$, so the algorithm will uniquely select this position for number $4$.\n\nSatisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $p_1, p_2, \\ldots, p_n$ and decided to find out if it could be obtained as a result of the generator.\n\nUnfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.",
    "tutorial": "Consider the initial moment of time. Note that the array is $r = [1, 2, \\ldots, n]$, $count = [1, 1, \\ldots, 1]$. So the generator will choose a random position from the entire array - let it be the position $i_1$. In the next step, $r = [1, 2, \\ldots i_1 + 1, i_1 + 1, i + 2, \\ldots, n]$, $count = [1, 1, \\ldots, 0, 2, 1, \\ldots, 1]$. That is, now there is only one maximum and it is reached at the position $i_1 + 1$. Thus, we will fill in the entire suffix starting at position $i_1$: $a = [\\times, \\ldots, \\times, 1, \\ldots, i_1]$. After this, this procedure will be repeated for some $i_2$ ($1 \\leq i_2 < i_1$) and the array will become $a = [\\times, \\ldots, \\times, i_1 + 1, \\ldots, i_1 + i_2, 1, \\ldots, i_1]$ . That is, we need to check that the array consists of several ascending sequences.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> p(n);\n    for (int& i : p)\n        cin >> i;\n    vector<int> pos(n);\n    for (int i = 0; i < n; ++i)\n        pos[--p[i]] = i;\n    vector<bool> was(n);\n    for (int i = 0; i < n; ++i) {\n        if (was[i])\n            continue;\n        int me = pos[i];\n        while (me < n) {\n            was[me] = 1;\n            if (me + 1 == n) break;\n            if (was[me + 1]) break;\n            if (p[me + 1] == p[me] + 1) {\n                ++me;\n                continue;\n            }\n            cout << \"No\\n\";\n            return;\n        }\n    }\n    cout << \"Yes\\n\";\n}\n \nint main() {\n    int q;\n    cin >> q;\n    while (q--)\n        solve();\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1340",
    "index": "B",
    "title": "Nastya and Scoreboard",
    "statement": "Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer.\n\nThe poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $7$ segments, which can be turned on or off to display different numbers. The picture shows how all $10$ decimal digits are displayed:\n\nAfter the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke \\textbf{exactly} $k$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $k$ sticks (which are off now)?\n\nIt is \\textbf{allowed} that the number includes leading zeros.",
    "tutorial": "Let $dp[i][j] = true$, if at the suffix $i \\ldots n$ you can turn on exactly $j$ sticks and get the correct sequence of digits and $false$ otherwise. It is easy to recalculate this dynamics: we will make transitions to all possible digits (the mask at position $i$ should be a submask of the digit). Asymptotic calculate of the dynamics $O(10nd)$. Now let's go in order from $1$ to $n$ and will try to eagerly set the maximum possible figure using our dynamics. It is easy to understand that in this way we get the maximum possible number of $n$ digits.",
    "code": "/**\n *    author:  tourist\n *    created: 23.04.2020 17:45:43       \n**/\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nvector<string> digits = {\"1110111\", \"0010010\", \"1011101\", \"1011011\", \"0111010\", \"1101011\", \"1101111\", \"1010010\", \"1111111\", \"1111011\"};\n \nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n, k;\n  cin >> n >> k;\n  vector<string> s(n);\n  vector<vector<int>> dist(n, vector<int>(10));\n  for (int i = 0; i < n; i++) {\n    cin >> s[i];\n    for (int d = 0; d < 10; d++) {\n      for (int j = 0; j < 7; j++) {\n        char x = s[i][j];\n        char y = digits[d][j];\n        if (x == '1' && y == '0') {\n          dist[i][d] = -1;\n          break;\n        }\n        if (x == '0' && y == '1') {\n          ++dist[i][d];\n        }\n      }\n    }\n  }\n  vector<vector<int>> dp(n + 1, vector<int>(k + 1));\n  dp[n][0] = 1;\n  for (int i = n; i > 0; i--) {\n    for (int j = 0; j <= k; j++) {\n      if (dp[i][j]) {\n        for (int d = 0; d < 10; d++) {\n          if (dist[i - 1][d] != -1 && j + dist[i - 1][d] <= k) {\n            dp[i - 1][j + dist[i - 1][d]] = 1;\n          }\n        }\n      }\n    }\n  }\n  if (dp[0][k] == 0) {\n    cout << -1 << '\\n';\n    return 0;\n  }\n  for (int i = 0; i < n; i++) {\n    int now = -1;\n    for (int d = 9; d >= 0; d--) {\n      if (dist[i][d] != -1 && k >= dist[i][d] && dp[i + 1][k - dist[i][d]]) {\n        now = d;\n        k -= dist[i][d];\n        break;\n      }\n    }\n    assert(now != -1);\n    cout << now;\n  }\n  cout << '\\n';\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1340",
    "index": "C",
    "title": "Nastya and Unexpected Guest",
    "statement": "If the girl doesn't go to Denis, then Denis will go to the girl. Using this rule, the young man left home, bought flowers and went to Nastya.\n\nOn the way from Denis's house to the girl's house is a road of $n$ lines. This road can't be always crossed in one green light. Foreseeing this, the good mayor decided to place safety islands in some parts of the road. Each safety island is located after a line, as well as at the beginning and at the end of the road. Pedestrians can relax on them, gain strength and wait for a green light.\n\nDenis came to the edge of the road exactly at the moment when the green light turned on. The boy knows that the traffic light first lights up $g$ seconds green, and then $r$ seconds red, then again $g$ seconds green and so on.\n\nFormally, the road can be represented as a segment $[0, n]$. Initially, Denis is at point $0$. His task is to get to point $n$ in the shortest possible time.\n\nHe knows many different integers $d_1, d_2, \\ldots, d_m$, where $0 \\leq d_i \\leq n$  — are the coordinates of points, in which the safety islands are located. Only at one of these points, the boy can be at a time when the red light is on.\n\nUnfortunately, Denis isn't always able to control himself because of the excitement, so some restrictions are imposed:\n\n- He must always move while the green light is on because it's difficult to stand when so beautiful girl is waiting for you. Denis can change his position by $\\pm 1$ in $1$ second. While doing so, he must always stay inside the segment $[0, n]$.\n- He can change his direction only on the safety islands (because it is safe). This means that if in the previous second the boy changed his position by $+1$ and he walked on a safety island, then he can change his position by $\\pm 1$. Otherwise, he can change his position only by $+1$. Similarly, if in the previous second he changed his position by $-1$, on a safety island he can change position by $\\pm 1$, and at any other point by $-1$.\n- At the moment when the red light is on, the boy must be on one of the safety islands. He can continue moving in any direction when the green light is on.\n\nDenis has crossed the road as soon as his coordinate becomes equal to $n$.\n\nThis task was not so simple, because it's possible that it is impossible to cross the road. Since Denis has all thoughts about his love, he couldn't solve this problem and asked us to help him. Find the minimal possible time for which he can cross the road according to these rules, or find that it is impossible to do.",
    "tutorial": "Notice the fact: if we somehow came to safety island and time $i \\bmod g$ ($\\bmod$ - is a remainder after dividing $i$ by $g$), we don't need anymore to come to this island at time $j$ where $i<j$ and $i\\bmod g = j\\bmod g$, because this will form a cycle. So that we can rephrase our task like this: we have some vertices, which are denoted as a pair $(i, t)$, $i$ - is island index, $t$ is a remainder after dividing the time we came to $i$ by $g$. So it will be enough to use only edges between vertices $(i, t) \\to (i + 1, (t + a[i + 1] - a[i])\\bmod g)$ and $(i, t)\\to (i - 1, (t + a[i] - a[i - 1])\\bmod g)$, because all remaining edges can be expressed through these ones. Now lets notice that edges, which make time $t + a > g$ can't be used due to restriction of walking on red. But vertices with $t + a = g$ are good for us. So we can say, that while green light is on, Denis can walk without restrictions, and when $t + a = g$ we add $g + r$ to time. So we can use $01$-BFS to solve this task and at the end check find vertex and position from which we can go to our final destination. Time complexity will be $O(g * m)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long int;\n \nvector<vector<int>> dist;\nvector<vector<bool>> was;\n \nint main() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> arr(m + 2);\n    for (int i = 0; i < m; ++i)\n        cin >> arr[i + 1];\n    m += 2;\n    arr.back() = n;\n    sort(arr.begin(), arr.end());\n    ll G, R;\n    cin >> G >> R;\n    dist.resize(m, vector<int>(G+1));\n    was.resize(m, vector<bool>(G+1));\n    deque<pair<int, int>> bfs;\n    bfs.push_back({0, 0});\n    was[0][0] = 1;\n    ll ans = -1;\n    while (bfs.size()) {\n        int v = bfs.front().first;\n        int t = bfs.front().second;\n        bfs.pop_front();\n        if (t == 0) {\n            int tTo = n - arr[v];\n            if (tTo <= G) {\n                ll tempAns = (R + G) * dist[v][t] + tTo;\n                if (ans == -1 || ans > tempAns)\n                    ans = tempAns;\n            }\n        }\n        if (t == G) {\n            if (was[v][0] == 0) {\n                dist[v][0] = dist[v][t] + 1;\n                bfs.push_back({v, 0});\n                was[v][0] = 1;\n            }\n            continue;\n        }\n        if (v) {\n            int tTo = t + arr[v] - arr[v - 1];\n            if (tTo <= G && was[v-1][tTo] == 0) {\n                was[v-1][tTo] = 1;\n                dist[v-1][tTo] = dist[v][t];\n                bfs.push_front({v-1, tTo});\n            }\n        }\n        if (v < m - 1) {\n            int tTo = t + arr[v + 1] - arr[v];\n            if (tTo <= G && was[v+1][tTo] == 0) {\n                was[v+1][tTo] = 1;\n                dist[v+1][tTo] = dist[v][t];\n                bfs.push_front({v+1, tTo});\n            }\n        }\n    }\n    cout << ans;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1340",
    "index": "D",
    "title": "Nastya and Time Machine",
    "statement": "Denis came to Nastya and discovered that she was not happy to see him... There is only one chance that she can become happy. Denis wants to buy all things that Nastya likes so she will certainly agree to talk to him.\n\nThe map of the city where they live has a lot of squares, some of which are connected by roads. There is exactly one way between each pair of squares which does not visit any vertex twice. It turns out that the graph of the city is a tree.\n\nDenis is located at vertex $1$ at the time $0$. He wants to visit every vertex at least once and get back as soon as possible.\n\nDenis can walk one road in $1$ time. Unfortunately, the city is so large that it will take a very long time to visit all squares. Therefore, Denis took a desperate step. He pulled out his pocket time machine, which he constructed in his basement. With its help, Denis can change the time to any non-negative time, which is less than the current time.\n\nBut the time machine has one feature. If the hero finds himself in the same place and at the same time twice, there will be an explosion of universal proportions and Nastya will stay unhappy. Therefore, Denis asks you to find him a route using a time machine that he will get around all squares and will return to the first and at the same time the maximum time in which he visited any square will be minimal.\n\nFormally, Denis's route can be represented as a sequence of pairs: $\\{v_1, t_1\\}, \\{v_2, t_2\\}, \\{v_3, t_3\\}, \\ldots, \\{v_k, t_k\\}$, where $v_i$ is number of square, and $t_i$ is time in which the boy is now.\n\nThe following conditions must be met:\n\n- The route starts on square $1$ at time $0$, i.e. $v_1 = 1, t_1 = 0$ and ends on the square $1$, i.e. $v_k = 1$.\n- All transitions are divided into two types:\n\n- Being in the square change the time: $\\{ v_i, t_i \\} \\to \\{ v_{i+1}, t_{i+1} \\} : v_{i+1} = v_i, 0 \\leq t_{i+1} < t_i$.\n- Walk along one of the roads: $\\{ v_i, t_i \\} \\to \\{ v_{i+1}, t_{i+1} \\}$. Herewith, $v_i$ and $v_{i+1}$ are connected by road, and $t_{i+1} = t_i + 1$\n\n- All pairs $\\{ v_i, t_i \\}$ must be different.\n- All squares are among $v_1, v_2, \\ldots, v_k$.\n\nYou need to find a route such that the maximum time in any square will be minimal, that is, the route for which $\\max{(t_1, t_2, \\ldots, t_k)}$ will be the minimum possible.",
    "tutorial": "Lemma: The maximum time that Denis will visit will be at least $\\max\\limits_{v = 1}^{n} \\deg v = T$ Proof: consider an arbitrary vertex $v$. We will visit her $\\deg v - 1$ times when we will bypass all her neighbors and another $1$ when we return to her ancestor. But we can't go to vertex at 0 time. So, we need $\\deg v$ moments more than 0. We construct a graph traversal with a maximum time equal to $T$. Let us now stand at $v$ at a time $t$ and $v$ has an un visited son $u$. We want to go to $u$, go around its entire subtree and return to $v$ at time $t + 1$. That is, the route will be something like this: $(v, t) \\to (u, t + 1) \\to \\ldots \\to (u, t) \\to (v, t + 1)$. Let $k = \\deg u - 1$, for $w_i$ we denote the $i$ th son of $u$. If $t + 1 \\leq T - k$, then there are no problems, we will move back in time at the very end of the route: $(v, t)$ $\\to$ $(u, t + 1)$ $\\to$ $(w_1, t + 2)$ $\\to$ $\\ldots$ $\\to$ $(u, t + 2)$ $\\to$ $\\ldots$ $\\to$ $(w_k, t + k + 1)$ $\\to$ $\\ldots$ $\\to$ $(u, t + k)$ $\\to$ $(u, t)$ $\\to$ $(v, t + 1)$. Otherwise, you have to go back in time in the middle of the route (exactly when we get to T) so that after the last visit we will be in $(v, t + 1)$, that is: $(v, t)$ $\\to$ $(u, t + 1)$ $\\to$ $(w_1, t + 2)$ $\\to$ $\\ldots$ $\\to$ $(u, t + 2)$ $\\to$ $\\ldots$ $\\to$ $(u, T)$ $\\to$ $(u, t')$ $\\to$ $\\ldots$ $(w_k, t + k + 1)$ $\\to$ $\\ldots$ $\\to$ $(u, t + k)$ $\\to$ $(u, t)$ $\\to$ $(v, t + 1)$ , where $t'$ can be easily calculated by the number of not visited sons.",
    "code": "#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC optimize(\"O3\")\n#pragma optimize(\"SEX_ON_THE_BEACH\")\n#include<bits/stdc++.h>\n \nusing ll = long long int;\nusing ull = unsigned long long int;\nusing dd = double;\nusing ldd = long double;\n \nnamespace Hashes {\n    const int mod197 = 1e9 + 7;\n    const int mod199 = 1e9 + 9;\n    const int modfft = 998244353;\n    int MOD = mod197;\n \n    template<typename T = int>\n    struct Hash {\n        T me, mod;\n \n        Hash() {}\n        Hash(T _me, T _mod = MOD) { me = _me, mod = _mod; if (me >= mod) me %= mod; }\n \n        Hash operator+ (Hash to) {\n            to.me += me;\n            if (to.me >= to.mod)\n                to.me -= to.mod;\n            return to;\n        }\n        Hash operator- (Hash to) {\n            to.me -= me;\n            to.me *= -1;\n            if (to.me < 0)\n                to.me += to.mod;\n            return to;\n        }\n        Hash operator* (Hash to) {\n            to.me *= me;\n            to.me %= to.mod;\n            return to;\n        }\n        Hash& operator+= (Hash to) {\n            me += to.me;\n            if (me >= mod)\n                me -= mod;\n            return *this;\n        }\n        Hash& operator-= (Hash to) {\n            me -= to.me;\n            if (me < 0)\n                me += mod;\n            return *this;\n        }\n        Hash& operator*= (Hash to) {\n            me *= to.me;\n            me %= mod;\n            return *this;\n        }\n        bool operator==(Hash to) {\n            return me == to.me;\n        }\n        T operator*() {\n            return me;\n        }\n    };\n}\n \nnamespace someUsefull {\n    template<typename T1, typename T2>\n    inline void checkMin(T1& a, T2 b) {\n        if (a > b)\n            a = b;\n    }\n \n    template<typename T1, typename T2>\n    inline void checkMax(T1& a, T2 b) {\n        if (a < b)\n            a = b;\n    }\n}\n \n//name spaces\nusing namespace std;\nusing namespace Hashes;\nusing namespace someUsefull;\n//end of name spaces\n \n//defines\n#define ff first\n#define ss second\n#define all(x) (x).begin(), (x).end()\n \n#define NO cout << \"NO\" << '\\n';\n#define No cout << \"No\" << '\\n';\n#define YES cout << \"YES\" << '\\n';\n#define Yes cout << \"Yes\" << '\\n';\n//end of defines\n \n//debug defines\n#ifdef HOME\n#define debug(x) cout << #x << \" \" << x << endl;\n#define debug_p(x) cout << #x << \" \" << x.ff << \" \" << x.ss << endl;\n#define debug_v(x) {cout << #x << \" \"; for (auto ioi : x) cout << ioi << \" \"; cout << endl;}\n#define debug_vp(x) {cout << #x << \" \"; for (auto ioi : x) cout << '[' << ioi.ff << \" \" << ioi.ss << ']'; cout << endl;}\n#define debug_v_v(x) {cout << #x << \"/*\\n\"; for (auto ioi : x) { for (auto ioi2 : ioi) cout << ioi2 << \" \"; cout << '\\n';} cout << \"*/\" << #x << endl;}\nint jjj;\n#define wait() cin >> jjj;\n#define PO cout << \"POMELO\" << endl;\n#define OL cout << \"OLIVA\" << endl;\n#define gen_clock(x) ll x = clock(); cout << \"Clock \" << #x << \" created\" << endl;\n#define check_clock(x) cout << \"Time spent in \" << #x << \": \" << clock() - x << endl; x = clock();\n#define reset_clock(x) x = clock();\n#define say(x) cout << x << endl;\n#else\n#define debug(x) 0;\n#define debug_p(x) 0;\n#define debug_v(x) 0;\n#define debug_vp(x) 0;\n#define debug_v_v(x) 0;\n#define wait() 0;\n#define PO 0;\n#define OL 0;\n#define gen_clock(x) 0;\n#define check_clock(x) 0;\n#define reset_clock(x) 0;\n#define say(x) 0;\n#endif // HOME\n//end of debug defines\n \nvector<pair<int, int>> ans;\nvector<vector<int>> gr;\nint mad = 0;\n \nvoid dfs(int v, int& t, int backT = -1, int p = -1) {\n    ans.push_back({v, t});\n    int cntTo = 0;\n    for (int to : gr[v]) {\n        if (to != p)\n            ++cntTo;\n    }\n    for (int to : gr[v]) {\n        if (to == p)\n            continue;\n        if (t == mad) {\n            t = backT - 1 - cntTo;\n            ans.push_back({v, t});\n        }\n        t++;\n        dfs(to, t, t, v);\n        ans.push_back({v, t});\n        --cntTo;\n    }\n    if (p == -1)\n        return;\n    if (t >= backT) {\n        t = backT-1;\n        ans.push_back({v, t});\n    }\n    ++t;\n}\n \nvoid solve(int test) {\n    int n;\n    cin >> n;\n    gr.resize(n);\n    for (int i = 0; i < n - 1; ++i) {\n        int a, b;\n        cin >> a >> b;\n        --a;\n        --b;\n        gr[a].push_back(b);\n        gr[b].push_back(a);\n    }\n    int t = 0;\n    for (int i = 0; i < n; ++i)\n        mad = max(mad, int(gr[i].size()));\n    dfs(0, t);\n    cout << ans.size() << '\\n';\n    for (int i = 0; i < ans.size(); ++i) {\n        cout << ans[i].ff + 1 << \" \" << ans[i].ss << '\\n';\n    }\n}\n \n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cout.tie(0);\n    cin.tie(0);\n    int t = 1;\n    //cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve(i);\n    }\n    return 0;\n \n}\n/*\n*/",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1340",
    "index": "F",
    "title": "Nastya and CBS",
    "statement": "Nastya is a competitive programmer, but she is only studying now. Recently, Denis told her about the way to check if the string is correct bracket sequence. After that, unexpectedly, Nastya came up with a much more complex problem that Denis couldn't solve. Can you solve it?\n\nA string $s$ is given. It consists of $k$ kinds of pairs of brackets. Each bracket has the form $t$  — it is an integer, such that $1 \\leq |t| \\leq k$. If the bracket has a form $t$, then:\n\n- If $t > 0$, then it's an opening bracket of the type $t$.\n- If $t < 0$, then it's a closing bracket of the type $-t$.\n\nThus, there are $k$ types of pairs of brackets in total.\n\nThe queries need to be answered:\n\n- Replace the bracket at position $i$ with the bracket of the form $t$.\n- Check if the substring from the $l$-th to $r$-th position (including) is the correct bracket sequence.\n\nRecall the definition of the correct bracket sequence:\n\n- An empty sequence is correct.\n- If $A$ and $B$ are two correct bracket sequences, then their concatenation \"$A$ $B$\" is also correct bracket sequence.\n- If $A$ is the correct bracket sequence, $c$ $(1 \\leq c \\leq k)$ is a type of brackets, then the sequence \"$c$ $A$ $-c$\" is also correct bracket sequence.",
    "tutorial": "We will call the string exactly the wrong bracket sequence if we go through it with a stack and it will not be of the form $close + open$, where $close$ is the sequence of closing brackets, and $open$ is opening. Claim: if $s = a + b$ and $a$ is exactly not CBS or $b$ is exactly not CBS, then $s$ is also exactly not CBS. At the top of the Segment Tree, we will keep the line after going through it with the stack in the form $close + open$ or marking that it is exactly not CBS. How to merge $2$ segments of the form $\\{close_1 + open_1 \\}$ and $\\{close_2 + open_2 \\}$? Note that $3$ cases are possible: The suffix $open_1$ is $close_2$, then the result is $close_1 + (close_2 - \\text {prefix}) + open_2$. The prefix $close_1$ is equal to $open_2$, similarly. The result is exectly not CBS. How can we quickly consider this? Let's build a segment tree, which contains treaps (which contain hashes) in each node, then we need to check for equality some prefixes, glue some strings and save all versions in order to update the ST. The resulting asymptotics of $O (n \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\n \n#define fi first\n#define se second\n#define ll long long\n \nusing namespace std;\n \nmt19937 rnd(13'06'2019);\n \nconst int N = 4e5 + 1;\nconst int LN = 2e6 + 1;\nconst int mod = 1e9 + 7;\nconst long long div1 = 100'001;\n \nstruct dek {\n    int l, r, sz, key;\n    long long hesh;\n};\n \nint top = 0;\ndek m[LN];\nlong long t[N];\nint lft[N], righ[N], a[N];\nbool open[N], bad[N];\nbool use[LN];\n \nint get_next() {\n    while (use[top])\n        ++top;\n    use[top] = 1;\n    return top;\n}\n \nvoid recalc(int u) {\n    m[u].sz = m[m[u].l].sz + m[m[u].r].sz + 1;\n    m[u].hesh = (m[m[u].l].hesh * t[m[m[u].r].sz + 1] + t[m[m[u].r].sz] * m[u].key + m[m[u].r].hesh) % mod;\n}\n \nvoid copy_vert(int from, int to) {\n    m[to] = m[from];\n}\n \nint merg(int a, int b) {\n    if (a == 0)\n        return b;\n    if (b == 0)\n        return a;\n    int u = get_next();\n    if (rnd() % (m[a].sz + m[b].sz) < m[a].sz) {\n        copy_vert(a, u);\n        m[u].r = merg(m[a].r, b);\n    } else {\n        copy_vert(b, u);\n        m[u].l = merg(a, m[b].l);\n    }\n    recalc(u);\n    return u;\n}\n \n \nvoid split(int root, int &a, int &b, int x) {\n    if (root == 0) {\n        a = 0;\n        b = 0;\n        return;\n    }\n    int u = get_next();\n    copy_vert(root, u);\n    if (m[m[root].l].sz >= x) {\n        split(m[root].l, a, m[u].l, x);\n        b = u;\n    } else {\n        split(m[root].r, m[u].r, b, x - m[m[root].l].sz - 1);\n        a = u;\n    }\n    recalc(u);\n}\n \nint newv(int key) {\n    int u = get_next();\n    m[u].key = key;\n    m[u].l = m[u].r = 0;\n    m[u].sz = 1;\n    m[u].hesh = key;\n    return u;\n}\n \nvoid recalc_do(int v) {\n    if (bad[2*v + 1] || bad[2*v + 2])\n        bad[v] = 1;\n    else {\n        if (m[righ[2*v + 1]].sz >= m[lft[2*v + 2]].sz) {\n            int a, b;\n            split(righ[2*v + 1], a, b, m[righ[2*v + 1]].sz - m[lft[2*v + 2]].sz);\n            if (m[b].hesh != m[lft[2*v + 2]].hesh)\n                bad[v] = 1;\n            else {\n                lft[v] = lft[2*v + 1];\n                righ[v] = merg(a, righ[2*v + 2]);\n                bad[v] = 0;\n            }\n        } else {\n            int a, b;\n            split(lft[2*v + 2], a, b, m[lft[2*v + 2]].sz - m[righ[2*v + 1]].sz);\n            if (m[b].hesh != m[righ[2*v + 1]].hesh)\n                bad[v] = 1;\n            else {\n                lft[v] = merg(a, lft[2*v + 1]);\n                righ[v] = righ[2*v + 2];\n                bad[v] = 0;\n            }\n        }\n    }\n}\n \nvoid build_do(int v, int vl, int vr) {\n    if (vr - vl == 1) {\n        righ[v] = 0;\n        lft[v] = 0;\n        if (open[vl] == 1)\n            righ[v] = newv(a[vl]);\n        else\n            lft[v] = newv(a[vl]);\n        bad[v] = 0;\n    } else {\n        build_do(2*v + 1, vl, (vl + vr) / 2);\n        build_do(2*v + 2, (vl + vr) / 2, vr);\n        recalc_do(v);\n    }\n}\n \nvoid als(int v, int vl, int vr, int l, int x, bool op) {\n    if (vr - vl == 1) {\n        a[vl] = x;\n        open[vl] = op;\n        build_do(v, vl, vr);\n    } else {\n        if (l < (vl + vr) / 2)\n            als(2*v + 1, vl, (vl + vr) / 2, l, x, op);\n        else\n            als(2*v + 2, (vl + vr) / 2, vr, l, x, op);\n        recalc_do(v);\n    }\n}\n \nbool zpr(int v, int vl, int vr, int l, int r, int &lefq, int &rigq) {\n    if (l <= vl && vr <= r) {\n        lefq = lft[v];\n        rigq = righ[v];\n        return bad[v];\n    } else if (l >= vr || vl >= r) {\n        lefq = 0;\n        rigq = 0;\n        return 0;\n    } else {\n        bool b1, b2;\n        int l1, r1, l2, r2;\n        b1 = zpr(2*v + 1, vl, (vl + vr) / 2, l, r, l1, r1);\n        b2 = zpr(2*v + 2, (vl + vr) / 2, vr, l, r, l2, r2);\n        if (b1 || b2)\n            return true;\n        if (m[r1].sz >= m[l2].sz) {\n            int a, b;\n            split(r1, a, b, m[r1].sz - m[l2].sz);\n            if (m[b].hesh != m[l2].hesh)\n                return true;\n            rigq = merg(a, r2);\n            lefq = l1;\n        } else {\n            int a, b;\n            split(l2, a, b, m[l2].sz - m[r1].sz);\n            if (m[b].hesh != m[r1].hesh)\n                return true;\n            rigq = r2;\n            lefq = merg(a, l1);\n        }\n        return false;\n    }\n}\n \nvoid dfs(int u) {\n    if (use[u])\n        return;\n    use[u] = 1;\n    dfs(m[u].l);\n    dfs(m[u].r);\n}\n \nint main() {\n    int i, j, k, n, p, x, q, type;\n    //freopen(\"input.txt\", \"r\", stdin);\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    \n    use[0] = 1;\n    cin >> n >> k;\n    t[0] = 1;\n    for (i = 1; i <= n; ++i)\n        t[i] = (t[i - 1] * div1) % mod;\n    for (i = 1; i <= n; ++i) {\n        cin >> a[i];\n        if (a[i] > 0)\n            open[i] = 1;\n        else {\n            a[i] = -a[i];\n            open[i] = 0;\n        }\n    }\n    build_do(0, 1, n + 1);\n    cin >> q;\n    for (i = 0; i < q; ++i) {\n        cin >> type;\n        if (type == 1) {\n            cin >> p >> x;\n            bool op;\n            if (x > 0)\n                op = 1;\n            else {\n                x = -x;\n                op = 0;\n            }\n            als(0, 1, n + 1, p, x, op);\n        } else {\n            int l, r, lft, right;\n            cin >> l >> r;\n            bool bad = zpr(0, 1, n + 1, l, r + 1, lft, right);\n            if (bad || lft != 0 || right != 0)\n                cout << \"No\\n\";\n            else\n                cout << \"Yes\\n\";\n        }\n        if (top > LN - 1e4) {\n            memset(use, 0, sizeof(use));\n            for (j = 0; j < N; ++j) {\n                dfs(lft[j]);\n                dfs(righ[j]);\n            }\n            top = 0;\n        }\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "hashing"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1341",
    "index": "A",
    "title": "Nastya and Rice",
    "statement": "Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.\n\nIn total, Nastya dropped $n$ grains. Nastya read that each grain weighs some integer number of grams from $a - b$ to $a + b$, inclusive (numbers $a$ and $b$ are known), and the whole package of $n$ grains weighs from $c - d$ to $c + d$ grams, inclusive (numbers $c$ and $d$ are known). The weight of the package is the sum of the weights of all $n$ grains in it.\n\nHelp Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $i$-th grain weighs some integer number $x_i$ $(a - b \\leq x_i \\leq a + b)$, and in total they weigh from $c - d$ to $c + d$, inclusive ($c - d \\leq \\sum\\limits_{i=1}^{n}{x_i} \\leq c + d$).",
    "tutorial": "We can get any weight of all grains from $n(a - b)$ to $n(a + b)$, so we need to check that the segments $[n(a - b); n(a + b)]$ and $[c - d; c + d]$ intersect.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint main() {\n\tint q;\n\tcin >> q;\n\twhile (q--) {\n\t\tint n, a, b, c, d;\n\t\tcin >> n >> a >> b >> c >> d;\n\t\tint L = n * (a - b), R = n * (a + b);\n\t\tif (R < c - d || c + d < L)\n\t\t    cout << \"No\\n\";\n\t\telse\n\t\t    cout << \"Yes\\n\";\n\t}\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1341",
    "index": "B",
    "title": "Nastya and Door",
    "statement": "On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length $k$ ($k \\ge 3$). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.\n\nMountains are described by a sequence of heights $a_1, a_2, \\dots, a_n$ in order from left to right ($k \\le n$). It is guaranteed that neighboring heights are not equal to each other (that is, $a_i \\ne a_{i+1}$ for all $i$ from $1$ to $n-1$).\n\nPeaks of mountains on the segment $[l,r]$ (from $l$ to $r$) are called indexes $i$ such that $l < i < r$, $a_{i - 1} < a_i$ and $a_i > a_{i + 1}$. It is worth noting that the boundary indexes $l$ and $r$ for the segment \\textbf{are not peaks}. For example, if $n=8$ and $a=[3,1,4,1,5,9,2,6]$, then the segment $[1,8]$ has only two peaks (with indexes $3$ and $6$), and there are no peaks on the segment $[3, 6]$.\n\nTo break the door, Nastya throws it to a segment $[l,l+k-1]$ of consecutive mountains of length $k$ ($1 \\le l \\le n-k+1$). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to $p+1$, where $p$ is the number of peaks on the segment $[l,l+k-1]$.\n\nNastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains $[l, l+k-1]$ that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value $l$ is minimal.\n\nFormally, you need to choose a segment of mountains $[l, l+k-1]$ that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value $l$.",
    "tutorial": "Let's make an array consisting of $0$ and $1$, such that it shows whether the position $i$ is a peak on the whole segment. To do this, we will go through the indices from $2$ to $n - 1$, and if the conditions $a_{i - 1} < a_i$ and $a_i > a_{i + 1}$ are true, then we write $1$ in a new array at position $i$. After that, we calculate the prefix sum in the new array $pref$. Now the number of peaks in the segment $[l, l + k - 1]$ is calculated as $pref[l + k - 2] - pref[l]$, so we find out how many peaks in the desired segment, not including the boundaries of the segment. It remains only to go through all $l$ from $1$ to $n - k + 1$ and find the leftmost $l$, such that $pref[l + k - 2] - pref[l]$ as much as possible.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n#define _USE_MATH_DEFINES\n \n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <set>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n#include <fstream>\n#include <iomanip>\n#include <bitset>\n#include <random>\n#include <queue>\n#include <cstring>\n#include <cassert>\n \nusing namespace std;\n \n#define X first\n#define Y second\n#define mp make_pair\n#define all(x) x.begin(), x.end()\n#define all_(x) x.rbegin(), x.rend()\n#define multi_test 1\n \ntypedef long long ll;\ntypedef long long lint;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pld;\n \nconst ll INF = 1e9 + 9;\nconst ll INF1 = 1e18 + 19;\nconst ll MAXN = 1e6 + 7;\nconst ll MAXN1 = 300;\nconst ll MAXN2 = (1 << 24) + 7;\nconst ll MOD = 1e9 + 7;\nconst ll PW = 31;\nconst ll BLOCK = 317;\n \nvoid solve();\nmt19937_64 mt(1e9 + 7);\n \nsigned main() {\n    srand('a' + 'l' + 'e' + 'x' + 'X' + '5' + '1' + '2');\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n#ifdef _DEBUG\n#define MAXN 5000\n    freopen(\"input.txt\", \"r\", stdin);\n    freopen(\"output.txt\", \"w\", stdout);\n#endif\n    int q = 1;\n    if (multi_test) cin >> q;\n    while (q--)  {\n        solve();\n    }\n}\n \n/*-----------------------------------------------------------------------------------------------------------------------------*/\n \nbool pick(int i, vector<int>& v, int l, int r) {\n    if (i == l || i == r) return 0;\n    return v[i - 1] < v[i] && v[i] > v[i + 1];\n}\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    vector<int> v(n);\n    for (auto &i : v) cin >> i;\n    int ans = -1, l = -1, r = -1, now = 0;\n    for (int i = 1; i + 1 < k; ++i) {\n        if (pick(i, v, 0, k - 1)) ++now;\n    }\n    ans = now + 1, l = 0, r = k - 1;\n    for (int i = k; i < n; ++i) {\n        if (pick(i - k + 1, v, i - k, i - 1)) --now;\n        if (pick(i - 1, v, i - k + 1, i)) ++now;\n        if (now + 1 > ans) {\n            ans = now + 1;\n            l = i - k + 1;\n            r = i;\n        }\n    }\n    cout << ans << \" \" << l + 1 << \"\\n\";\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1342",
    "index": "A",
    "title": "Road To Zero",
    "statement": "You are given two integers $x$ and $y$. You can perform two types of operations:\n\n- Pay $a$ dollars and increase or decrease any of these integers by $1$. For example, if $x = 0$ and $y = 7$ there are four possible outcomes after this operation:\n\n- $x = 0$, $y = 6$;\n- $x = 0$, $y = 8$;\n- $x = -1$, $y = 7$;\n- $x = 1$, $y = 7$.\n\n- Pay $b$ dollars and increase or decrease both integers by $1$. For example, if $x = 0$ and $y = 7$ there are two possible outcomes after this operation:\n\n- $x = -1$, $y = 6$;\n- $x = 1$, $y = 8$.\n\nYour goal is to make both given integers equal zero simultaneously, i.e. $x = y = 0$. There are no other requirements. In particular, it is possible to move from $x=1$, $y=0$ to $x=y=0$.\n\nCalculate the minimum amount of dollars you have to spend on it.",
    "tutorial": "Let's presume that $x \\ge y$. Then there are two cases in the problem: If $a + a \\le b$ then we have to $x + y$ times perform the first operation. So the answer is $(x + y) \\cdot a$; If $a + a > b$ then we have to $y$ times perform the second operation and pass the remaining distance by performing the first operation. So the answer is $y \\cdot b + (x - y) \\cdot a$.",
    "code": "for _ in range(int(input())):\n    x, y = map(int, input().split())\n    a, b = map(int, input().split())\n    b = min(b, a + a)\n    if x < y:\n        x, y= y, x\n    print(y * b + (x - y) * a)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1342",
    "index": "B",
    "title": "Binary Period",
    "statement": "Let's say string $s$ has period $k$ if $s_i = s_{i + k}$ for all $i$ from $1$ to $|s| - k$ ($|s|$ means length of string $s$) and $k$ is the minimum positive integer with this property.\n\nSome examples of a period: for $s$=\"0101\" the period is $k=2$, for $s$=\"0000\" the period is $k=1$, for $s$=\"010\" the period is $k=2$, for $s$=\"0011\" the period is $k=4$.\n\nYou are given string $t$ consisting only of 0's and 1's and you need to find such string $s$ that:\n\n- String $s$ consists only of 0's and 1's;\n- The length of $s$ doesn't exceed $2 \\cdot |t|$;\n- String $t$ is a subsequence of string $s$;\n- String $s$ has smallest possible period among all strings that meet conditions 1—3.\n\nLet us recall that $t$ is a subsequence of $s$ if $t$ can be derived from $s$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $t$=\"011\" is a subsequence of $s$=\"10101\".",
    "tutorial": "Let's see how strings with periods $k = 1$ and $k = 2$ look. There are two types of strings with a period equal to $1$: 0000... and 1111.... And there are two types of strings with a period equal to $2$: 01010... and 10101.... It's easy to see if $t$ consists only of 0's (1's) then the string itself is an answer since it has period equal to $1$. Otherwise, it's also quite obvious that any string $t$ is a subsequence of 0101...01 (1010...10) of $2|t|$ length.",
    "code": "fun main() {\n    val T = readLine()!!.toInt()\n    for (tc in 1..T) {\n        val t = readLine()!!\n\n        val s = t.toCharArray().distinct().joinToString(\"\").repeat(t.length)\n        println(s)\n    }\n}",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1342",
    "index": "C",
    "title": "Yet Another Counting Problem",
    "statement": "You are given two integers $a$ and $b$, and $q$ queries. The $i$-th query consists of two numbers $l_i$ and $r_i$, and the answer to it is the number of integers $x$ such that $l_i \\le x \\le r_i$, and $((x \\bmod a) \\bmod b) \\ne ((x \\bmod b) \\bmod a)$. Calculate the answer for each query.\n\nRecall that $y \\bmod z$ is the remainder of the division of $y$ by $z$. For example, $5 \\bmod 3 = 2$, $7 \\bmod 8 = 7$, $9 \\bmod 4 = 1$, $9 \\bmod 9 = 0$.",
    "tutorial": "It's quite easy to see that $((ab + x) \\bmod a) \\bmod b = (x \\bmod a) \\bmod b$. What does it mean? The property given in the statement holds for $x$ if and only if it holds for $x \\bmod ab$. It allows us to answer each testcase in $O(ab + q)$ as follows: for each number from $0$ to $ab - 1$, we may check the given property before processing the queries, and build an array of prefix sums on it to efficiently count the number of integers satisfying the property from the segment $[0, y]$, where $y < ab$. Then each query $[l, r]$ can be divided into two prefix-queries $[0, l - 1]$ and $[0, r]$. To answer a prefix query $[0, p]$ in $O(1)$, we can calculate the number of \"full segments\" of length $ab$ inside this prefix (that is $\\lfloor \\frac{p}{ab} \\rfloor$) and the length of the last segment of numbers that don't belong into a full segment (that is $p \\bmod ab$). To handle full segments, we multiply the number of integers satisfying the property on one segment by the number of such segments, and to handle the last part of segment, we use prefix sums.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 40043;\n\nint len;\nint p[N];\n\nvoid build(int a, int b)\n{\n\tlen = a * b;\n\tp[0] = 0;\n\tfor(int i = 1; i <= len; i++)\n\t{\n\t\tp[i] = p[i - 1];\n\t\tif((i % a) % b != (i % b) % a)\n\t\t\tp[i]++;\n\t}\n}\n\nlong long query(long long l)\n{\n\tlong long cnt = l / len;\n\tint rem = l % len;\n\treturn p[len] * 1ll * cnt + p[rem]; \n}\n\nlong long query(long long l, long long r)\n{\n\treturn query(r) - query(l - 1);\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tint a, b, q;\n\t\tcin >> a >> b >> q;\n\t\tbuild(a, b);\n\t\tlong long l, r;\n\t\tfor(int j = 0; j < q; j++)\n\t\t{\n\t\t\tcin >> l >> r;\n\t\t\tcout << query(l, r) << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1342",
    "index": "D",
    "title": "Multiple Testcases",
    "statement": "So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!\n\nInitially, each test in that problem is just an array. The maximum size of an array is $k$. For simplicity, the contents of arrays don't matter. You have $n$ tests — the $i$-th test is an array of size $m_i$ ($1 \\le m_i \\le k$).\n\nYour coordinator asks you to distribute all of your arrays into multiple testcases. Each testcase can include multiple arrays. However, each testcase should include no more than $c_1$ arrays of size \\textbf{greater than or equal to $1$} ($\\ge 1$), no more than $c_2$ arrays of size \\textbf{greater than or equal to $2$}, $\\dots$, no more than $c_k$ arrays of size \\textbf{greater than or equal to $k$}. Also, $c_1 \\ge c_2 \\ge \\dots \\ge c_k$.\n\nSo now your goal is to create the new testcases in such a way that:\n\n- each of the initial arrays appears in \\textbf{exactly one} testcase;\n- for each testcase the given conditions hold;\n- the number of testcases is minimum possible.\n\nPrint the minimum possible number of testcases you can achieve and the sizes of arrays included in each testcase.",
    "tutorial": "Let's estimate the smallest possible achievable answer. Let the number of the arrays of size greater than or equal to $i$ be $g_i$. The answer is maximum $\\lceil \\frac{g_i}{c_i} \\rceil$ over all $i$ from $1$ to $k$. You can prove that you can't fit $g_i$ arrays in less than $\\lceil \\frac{g_i}{c_i} \\rceil$ testcases with the pigeonhole principle. Let that be called $ans$. Ok, let's now construct the solution for that estimate. Sort arrays in the increasing or decreasing order and assign the $i$-th array ($0$-indexed) in that order to the $i~mod~ans$ testcase. It's easy to see that for any $i$ the number of arrays of size greater than or equal to $i$ is always restricted by $\\lceil \\frac{g_i}{c_i} \\rceil$. Overall complexity: $O(n \\log n + k)$ or $O(n + k)$ if you care enough to do counting sort.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n\tint n, k;\n\tscanf(\"%d%d\", &n, &k);\n\tvector<int> a(n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tvector<int> c(k + 1);\n\tforn(i, k) scanf(\"%d\", &c[i + 1]);\n\t\n\tsort(a.begin(), a.end(), greater<int>());\n\tint ans = 0;\n\tfor (int i = k, g = 0; i >= 1; --i){\n\t\twhile (g < n && a[g] == i) ++g;\n\t\tans = max(ans, (g + c[i] - 1) / c[i]);\n\t}\n\tvector<vector<int>> res(ans);\n\tforn(i, n) res[i % ans].push_back(a[i]);\n\t\n\tprintf(\"%d\\n\", ans);\n\tforn(i, ans){\n\t\tprintf(\"%d\", int(res[i].size()));\n\t\tfor (auto it : res[i])\n\t\t\tprintf(\" %d\", it);\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1342",
    "index": "E",
    "title": "Placing Rooks",
    "statement": "Calculate the number of ways to place $n$ rooks on $n \\times n$ chessboard so that both following conditions are met:\n\n- each empty cell is under attack;\n- exactly $k$ pairs of rooks attack each other.\n\nAn empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two rooks attack each other if they share the same row or column, and there are no other rooks between them. For example, there are only two pairs of rooks that attack each other in the following picture:\n\n\\begin{center}\n{\\small One of the ways to place the rooks for $n = 3$ and $k = 2$}\n\\end{center}\n\nTwo ways to place the rooks are considered different if there exists at least one cell which is empty in one of the ways but contains a rook in another way.\n\nThe answer might be large, so print it modulo $998244353$.",
    "tutorial": "If we want to place $n$ rooks on an $n \\times n$ chessboard so all empty cells are under attack, then either each row or each column should contain at least one rook. Let's suppose that each row contains at least one rook, and multiply the answer by $2$ in the end. How to ensure that there are exactly $k$ pairs of rooks attacking each other? Since each row contains exactly one rook, only the rooks in the same column attack each other - moreover, if there are $x$ rooks in a non-empty column, they create $(x - 1)$ pairs. So our goal is to distribute $n$ rooks to $n - k$ columns so that each column contains at least one rook. How to calculate the number of ways to distribute the rooks into $c$ columns? One of the options is to choose the columns we use (the number of ways to do this is ${n}\\choose{c}$), and then use inclusion-exclusion to ensure that we are counting only the ways where each column contains at least one rook. The formula we will get is something like $\\sum \\limits_{i = 0}^{c} (-1)^i {{c}\\choose{i}} (c-i)^n$: we want to fix the number of columns that will not contain rooks (that is $i$), which are these columns (that is ${c}\\choose{i}$), and how many are there ways to distribute the rooks among remaining columns (that is $(c-i)^n$). Are we done? Almost. We wanted to multiply the answer by $2$ to count the ways where each column contains at least one rook, but we should not do it if $k = 0$, because in this case each placement of the rooks has exactly one rook in each row and exactly one rook in each column.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 200043;\n\nint add(int x, int y)\n{\n\treturn (x + y) % MOD;\n}\n\nint sub(int x, int y)\n{\n\treturn add(x, MOD - y);\n}\n\nint mul(int x, int y)\n{\n\treturn (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n\tint z = 1;\n\twhile(y > 0)\n\t{\n\t\tif(y % 2 == 1)\n\t\t\tz = mul(z, x);\n\t\tx = mul(x, x);\n\t\ty /= 2;\n\t}\n\treturn z;\n}\n\nint inv(int x)\n{\n\treturn binpow(x, MOD - 2);\n}\n\nint fact[N];\n\nint C(int n, int k)\n{\n\treturn mul(fact[n], inv(mul(fact[k], fact[n - k])));\n}\n\nint main()\n{\n\tint n, k;\n\tcin >> n >> k;\n\t\n\tif(k > n - 1)\n\t{\n\t\tcout << 0 << endl;\n\t\treturn 0;\n\t}\n\t\n\tfact[0] = 1;\n\tfor(int i = 1; i <= n; i++)\n\t\tfact[i] = mul(i, fact[i - 1]);\n\tint ans = 0;\n\tint c = n - k;\n\tfor(int i = c; i >= 0; i--)\n\t\tif(i % 2 == c % 2)\n\t\t\tans = add(ans, mul(binpow(i, n), C(c, i)));\n\t\telse\n\t\t\tans = sub(ans, mul(binpow(i, n), C(c, i)));\n\tans = mul(ans, C(n, c));\n\tif(k > 0)\n\t\tans = mul(ans, 2);\n\tcout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "fft",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1342",
    "index": "F",
    "title": "Make It Ascending",
    "statement": "You are given an array $a$ consisting of $n$ elements. You may apply several operations (possibly zero) to it.\n\nDuring each operation, you choose two indices $i$ and $j$ ($1 \\le i, j \\le n$; $i \\ne j$), increase $a_j$ by $a_i$, and remove the $i$-th element from the array (so the indices of all elements to the right to it decrease by $1$, and $n$ also decreases by $1$).\n\nYour goal is to make the array $a$ strictly ascending. That is, the condition $a_1 < a_2 < \\dots < a_n$ should hold (where $n$ is the resulting size of the array).\n\nCalculate the minimum number of actions required to make the array strictly ascending.",
    "tutorial": "Suppose we don't have any constraints on the order of elements, the resulting array just should not contain any duplicates. Let's build the result one element after another in ascending order, so each element we create is strictly greater than the previous. To create an element, just use some subset of elements and merge them into new element. This process can be efficiently modeled with the following dynamic programming: $dp_{cnt, mask}$ is the minimum value of the last element, if we merged all the elements from $mask$ into $cnt$ ascending numbers. To model transitions, we simply iterate on the mask of elements that will be merged into a new one, and check if its sum is greater than the last element we created. This runs in $O(n3^n)$, if we use an efficient way to iterate on all masks that don't intersect with the given mask. Okay, how about maintaining the order? When we create an element by merging some elements of the original array, let's choose some position of an element we use in merging and state that all other elements are added to it. Then, to ensure that the result is ascending, the position of this element should be greater than the position of the element we chose while building the previous number. We can add the position we have chosen for the last element to the states of our dynamic programming, so it becomes $dp_{cnt, mask, pos}$ - the minimum value of the last element, if we merged the $mask$ of elements into $cnt$ numbers, and the last element originally had index $pos$ in the array. Using some greedy optimizations (for example, we should not iterate on the position we are choosing to merge - it can be chosen greedily as the leftmost position after the position of previous element we are taking into consideration), we can make it $O(n^2 3^n)$, yet with a small constant factor. To restore the answer, we can maintain the previous values of $mask$ and $pos$ in each state, since $cnt$ just increases by $1$ with each transition.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\ntypedef pair<int, int> pt;\n\nconst int INF = 1e9;\nconst int N = 15;\n\nint n;\nint a[N];\nint sum[1 << N];\nint dp[N + 1][1 << N][N + 1];\npt p[N + 1][1 << N][N + 1];\n\nvoid solve() {\n\tscanf(\"%d\", &n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\n\tforn(mask, 1 << n) {\n\t\tsum[mask] = 0;\n\t\tforn(i, n) if (mask & (1 << i))\n\t\t\tsum[mask] += a[i];\n\t}\t\n\t\n\tforn(cnt, n + 1) forn(mask, 1 << n) forn(pos, n + 1)\n\t\tdp[cnt][mask][pos] = INF;\n\t\n\tdp[0][0][0] = 0;\n\tforn(cnt, n) forn(mask, 1 << n) forn(pos, n) if (dp[cnt][mask][pos] < INF) {\n\t\tint rmask = mask ^ ((1 << n) - 1);\n\t\tfor (int nmask = rmask; nmask; nmask = (nmask - 1) & rmask) {\n\t\t\tif (sum[nmask] <= dp[cnt][mask][pos])\n\t\t\t\tcontinue;\n\t\t\tif ((nmask >> pos) == 0)\n\t\t\t\tcontinue;\n\t\t\tint npos = pos + __builtin_ctz(nmask >> pos) + 1;\n\t\t\tif (dp[cnt + 1][mask | nmask][npos] > sum[nmask]) {\n\t\t\t\tdp[cnt + 1][mask | nmask][npos] = sum[nmask];\n\t\t\t\tp[cnt + 1][mask | nmask][npos] = mp(mask, pos);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint acnt = 0, apos = 0;\n\tforn(cnt, n + 1) forn(pos, n + 1) if (dp[cnt][(1 << n) - 1][pos] < INF)\n\t\tacnt = cnt, apos = pos;\n\t\t\n\tvector<pt> ans;\n\t\n\tint mask = (1 << n) - 1, pos = apos;\n\tfor (int cnt = acnt; cnt > 0; --cnt) {\n\t\tint nmask = p[cnt][mask][pos].x;\n\t\tint npos = p[cnt][mask][pos].y;\n\t\tforn(i, n) if ((nmask ^ mask) & (1 << i))\n\t\t\tif (i != pos - 1) ans.pb(mp(i, pos - 1));\n\t\tmask = nmask, pos = npos;\n\t}\n\t\n\t\n\tprintf(\"%d\\n\", sz(ans));\n\tforn(i, sz(ans)) {\n\t\tint from = ans[i].x;\n\t\tforn(j, i) from -= ans[j].x < ans[i].x;\n\t\tint to = ans[i].y;\n\t\tforn(j, i) to -= ans[j].x < ans[i].y;\n\t\tprintf(\"%d %d\\n\", from + 1, to + 1);\n\t}\n}\t\n\nint main() {\n\tint tc;\n\tscanf(\"%d\", &tc);\n\tforn(i, tc) solve();\n\t\t\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1343",
    "index": "A",
    "title": "Candies",
    "statement": "Recently Vova found $n$ candy wrappers. He remembers that he bought $x$ candies during the first day, $2x$ candies during the second day, $4x$ candies during the third day, $\\dots$, $2^{k-1} x$ candies during the $k$-th day. But there is an issue: Vova remembers neither $x$ nor $k$ but he is sure that $x$ and $k$ are positive integers and $k > 1$.\n\nVova will be satisfied if you tell him \\textbf{any positive} integer $x$ so there is an integer $k>1$ that $x + 2x + 4x + \\dots + 2^{k-1} x = n$. It is guaranteed that at least one solution exists. \\textbf{Note that $k > 1$}.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Notice that $\\sum\\limits_{i=0}^{k-1} 2^i = 2^k - 1$. Thus we can replace the initial equation with the following: $(2^k - 1) x = n$. So we can iterate over all possible $k$ in range $[2; 29]$ (because $2^{30} - 1 > 10^9$) and check if $n$ is divisible by $2^k-1$. If it is then we can print $x = \\frac{n}{2^k-1}$. P.S. I know that so many participants found the formula $\\sum\\limits_{i=0}^{k-1} 2^i = 2^k - 1$ using geometric progression sum but there is the other way to understand this and it is a way more intuitive for me. Just take a look at the binary representation of numbers: we can notice that $2^0 = 1, 2^1 = 10, 2^2 = 100$ and so on. Thus $2^0 = 1, 2^0+2^1=11, 2^0+2^1+2^2=111$ and so on. And if we add one to this number consisting of $k$ ones then we get $2^k$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tfor (int pw = 2; pw < 30; ++pw) {\n\t\t\tint val = (1 << pw) - 1;\n\t\t\tif (n % val == 0) {\n\t\t\t\tcerr << val << endl;\n\t\t\t\tcout << n / val << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1343",
    "index": "B",
    "title": "Balanced Array",
    "statement": "You are given a positive integer $n$, it is guaranteed that $n$ is even (i.e. divisible by $2$).\n\nYou want to construct the array $a$ of length $n$ such that:\n\n- The first $\\frac{n}{2}$ elements of $a$ are even (divisible by $2$);\n- the second $\\frac{n}{2}$ elements of $a$ are odd (not divisible by $2$);\n- \\textbf{all elements of $a$ are distinct and positive};\n- the sum of the first half equals to the sum of the second half ($\\sum\\limits_{i=1}^{\\frac{n}{2}} a_i = \\sum\\limits_{i=\\frac{n}{2} + 1}^{n} a_i$).\n\nIf there are multiple answers, you can print any. It is \\textbf{not guaranteed} that the answer exists.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, if $n$ is not divisible by $4$ then the answer is \"NO\" because the parities of halves won't match. Otherwise, the answer is always \"YES\". Let's construct it as follows: firstly, let's create the array $[2, 4, 6, \\dots, n, 1, 3, 5, \\dots, n - 1]$. This array is almost good except one thing: the sum in the right half is exactly $\\frac{n}{2}$ less than the sum in the left half. So we can fix it easily: just add $\\frac{n}{2}$ to the last element.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tn /= 2;\n\t\tif (n & 1) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tcout << \"YES\" << endl;\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\tcout << i * 2 << \" \";\n\t\t}\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tcout << i * 2 - 1 << \" \";\n\t\t}\n\t\tcout << 3 * n - 1 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1343",
    "index": "C",
    "title": "Alternating Subsequence",
    "statement": "Recall that the sequence $b$ is a a subsequence of the sequence $a$ if $b$ can be derived from $a$ by removing zero or more elements without changing the order of the remaining elements. For example, if $a=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.\n\nYou are given a sequence $a$ consisting of $n$ positive and negative elements (there is no zeros in the sequence).\n\nYour task is to choose \\textbf{maximum by size} (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the \\textbf{maximum sum} of elements.\n\nIn other words, if the maximum length of alternating subsequence is $k$ then your task is to find the \\textbf{maximum sum} of elements of some alternating subsequence of length $k$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, let's extract maximum by inclusion segments of the array that consists of the numbers with the same sign. For example, if the array is $[1, 1, 2, -1, -5, 2, 1, -3]$ then these segments are $[1, 1, 2]$, $[-1, -5]$, $[2, 1]$ and $[-3]$. We can do it with any \"two pointers\"-like algorithm. The number of these segments is the maximum possible length of the alternating subsequence because we can take only one element from each block. And as we want to maximize the sum, we need to take the maximum element from each block. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tauto sgn = [&](int x) {\n\t\tif (x > 0) return 1;\n\t\telse return -1;\n\t};\n\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tlong long sum = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint cur = a[i];\n\t\t\tint j = i;\n\t\t\twhile (j < n && sgn(a[i]) == sgn(a[j])) {\n\t\t\t\tcur = max(cur, a[j]);\n\t\t\t\t++j;\n\t\t\t}\n\t\t\tsum += cur;\n\t\t\ti = j - 1;\n\t\t}\n\t\tcout << sum << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1343",
    "index": "D",
    "title": "Constant Palindrome Sum",
    "statement": "You are given an array $a$ consisting of $n$ integers (it is guaranteed that $n$ is even, i.e. divisible by $2$). All $a_i$ does not exceed some integer $k$.\n\nYour task is to replace the \\textbf{minimum} number of elements (replacement is the following operation: choose some index $i$ from $1$ to $n$ and replace $a_i$ with some integer in range $[1; k]$) to satisfy the following conditions:\n\n- after all replacements, all $a_i$ are positive integers not greater than $k$;\n- for all $i$ from $1$ to $\\frac{n}{2}$ the following equation is true: $a_i + a_{n - i + 1} = x$, where $x$ should be \\textbf{the same} for all $\\frac{n}{2}$ pairs of elements.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "It is obvious that if we fix the value of $x$ then there are three cases for the pair of elements: We don't need to change anything in this pair; we can replace one element to fix this pair; we need to replace both elements to fix this pair. The first part can be calculated easily in $O(n+k)$, we just need to create the array of frequencies $cnt$, where $cnt_x$ is the number of such pairs $(a_i, a_{n-i+1})$ that $a_i + a_{n-i+1} = x$. The second part is a bit tricky but still doable in $O(n+k)$. For each pair, let's understand the minimum and the maximum sum we can obtain using at most one replacement. For the $i$-th pair, all such sums belong to the segment $[min(a_i, a_{n-i+1})+1; max(a_i, a_{n-i+1})+k]$. Let's make $+1$ on this segment using prefix sums (make $+1$ in the left border, $-1$ in the right border plus one and then just compute prefix sums on this array). Let this array be $pref$. Then the value $pref_x$ tells the number of such pairs that we need to replace at most one element in this pair to make it sum equals $x$. And the last part can be calculated as $\\frac{n}{2} - pref_x$. So, for the sum $x$ the answer is $(pref_x - cnt_x) + (\\frac{n}{2} - pref_x) \\cdot 2$. We just need to take the minimum such value among all possible sums from $2$ to $2k$. There is another one solution that uses scanline, not depends on $k$ and works in $O(n \\log n)$ but it has no cool ideas to explain it here (anyway the main idea is almost the same as in the solution above).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tvector<int> cnt(2 * k + 1);\n\t\tfor (int i = 0; i < n / 2; ++i) {\n\t\t\t++cnt[a[i] + a[n - i - 1]];\n\t\t}\n\t\tvector<int> pref(2 * k + 2);\n\t\tfor (int i = 0; i < n / 2; ++i) {\n\t\t\tint l1 = 1 + a[i], r1 = k + a[i];\n\t\t\tint l2 = 1 + a[n - i - 1], r2 = k + a[n - i - 1];\n\t\t\tassert(max(l1, l2) <= min(r1, r2));\n\t\t\t++pref[min(l1, l2)];\n\t\t\t--pref[max(r1, r2) + 1];\n\t\t}\n\t\tfor (int i = 1; i <= 2 * k + 1; ++i) {\n\t\t\tpref[i] += pref[i - 1];\n\t\t}\n\t\tint ans = 1e9;\n\t\tfor (int sum = 2; sum <= 2 * k; ++sum) {\n\t\t\tans = min(ans, (pref[sum] - cnt[sum]) + (n / 2 - pref[sum]) * 2);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1343",
    "index": "E",
    "title": "Weights Distributing",
    "statement": "You are given an undirected unweighted graph consisting of $n$ vertices and $m$ edges (which represents the map of Bertown) and the array of prices $p$ of length $m$. It is guaranteed that there is a path between each pair of vertices (districts).\n\nMike has planned a trip from the vertex (district) $a$ to the vertex (district) $b$ and then from the vertex (district) $b$ to the vertex (district) $c$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (\\textbf{he pays each time he goes along the road}). The list of prices that will be used $p$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.\n\nYou are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the \\textbf{minimum} possible. \\textbf{Note that you cannot rearrange prices after the start of the trip}.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If we distribute costs optimally, then this pair of paths ($a \\rightarrow b$ and $b \\rightarrow c$) can look like just a straight path that doesn't visit the same vertex twice or like three straight paths with one intersection point $x$. The first case is basically a subcase of the second one (with the intersection point $a, b$ or $c$). So, if we fix the intersection point $x$ then these two paths ($a \\rightarrow b$ and $b \\rightarrow c$) become four paths ($a \\rightarrow x$, $x \\rightarrow b$, $b \\rightarrow x$ and $x \\rightarrow c$). We can notice that each path we denoted should be the shortest possible because if it isn't the shortest one then we used some prices that we couldn't use. Let the length of the shortest path from $u$ to $v$ be $dist(u, v)$. Then it is obvious that for the fixed intersection point $x$ we don't need to use more than $dist(a, x) + dist(b, x) + dist(c, x)$ smallest costs. Now we want to distribute these costs between these three paths somehow. We can see that the path from $b$ to $x$ is used twice so it is more optimally to distribute the smallest costs along this part. So, let $pref_i$ be the sum of the first $i$ smallest costs (just prefix sums on the sorted array $p$). Then for the intersection point $x$ the answer is $pref_{dist(b, x)} + pref_{dist(a, x) + dist(b, x) + dist(c, x)}$ (if $dist(a, x) + dist(b, x) + dist(c, x) \\le m$). We can calculate distances from $a$, $b$ and $c$ to each vertex with three runs of bfs. Time complexity: $O(m \\log m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nvector<vector<int>> g;\n\nvoid bfs(int s, vector<int> &d) {\n\td[s] = 0;\n\tqueue<int> q;\n\tq.push(s);\n\twhile (!q.empty()) {\n\t\tint v = q.front();\n\t\tq.pop();\n\t\tfor (auto to : g[v]) {\n\t\t\tif (d[to] == INF) {\n\t\t\t\td[to] = d[v] + 1;\n\t\t\t\tq.push(to);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m, a, b, c;\n\t\tcin >> n >> m >> a >> b >> c;\n\t\t--a, --b, --c;\n\t\t\n\t\tvector<int> p(m);\n\t\tfor (auto &it : p) cin >> it;\n\t\tsort(p.begin(), p.end());\n\t\tvector<long long> pref(m + 1);\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tpref[i + 1] = pref[i] + p[i];\n\t\t}\n\t\t\n\t\tg = vector<vector<int>>(n);\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y;\n\t\t\t--x, --y;\n\t\t\tg[x].push_back(y);\n\t\t\tg[y].push_back(x);\n\t\t}\n\t\t\n\t\tvector<int> da(n, INF), db(n, INF), dc(n, INF);\n\t\tbfs(a, da);\n\t\tbfs(b, db);\n\t\tbfs(c, dc);\n\t\t\n\t\tlong long ans = 1e18;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (da[i] + db[i] + dc[i] > m) continue;\n\t\t\tans = min(ans, pref[db[i]] + pref[da[i] + db[i] + dc[i]]);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "graphs",
      "greedy",
      "shortest paths",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1343",
    "index": "F",
    "title": "Restore the Permutation by Sorted Segments",
    "statement": "We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you.\n\nFor each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p_{l + 1}, \\dots, p_r$ in \\textbf{sorted} order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly $n-1$ segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order.\n\nFor example, if the secret permutation is $p=[3, 1, 4, 6, 2, 5]$ then the possible given set of segments can be:\n\n- $[2, 5, 6]$\n- $[4, 6]$\n- $[1, 3, 4]$\n- $[1, 3]$\n- $[1, 2, 4, 6]$\n\nYour task is to find \\textbf{any} suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists).\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let's fix the first element and then try to restore permutation using this information. One interesting fact: if such permutation exists (with this first element) then it can be restored uniquely. Let's remove the first element from all segments containing it (we can use some logarithmic data structure for it). Then we just have a smaller problem but with one important condition: there is a segment consisting of one element (again, if such permutation exists). So, if the number of segments of length $1$ is zero or more than one by some reason then there is no answer for this first element. Otherwise, let's place this segment (a single element) in second place, remove it from all segments containing it and just solve a smaller problem again. If we succeed with restoring the permutation then we need to check if this permutation really satisfies the given input segments (see the first test case of the example to understand why this case appears). Let's just iterate over all $i$ from $2$ to $n$ and then over all $j$ from $i-1$ to $1$. If the segment $a_j, a_{j+1}, \\dots, a_i$ is in the list, remove it and go to the next $i$. If we can't find the segment for some $i$ then this permutation is wrong. Time complexity: $O(n^3 \\log n)$ (or less, maybe?)",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<set<int>> segs;\n\t\tfor (int i = 0; i < n - 1; ++i) {\n\t\t\tset<int> cur;\n\t\t\tint k;\n\t\t\tcin >> k;\n\t\t\tfor (int j = 0; j < k; ++j) {\n\t\t\t\tint x;\n\t\t\t\tcin >> x;\n\t\t\t\tcur.insert(x);\n\t\t\t}\n\t\t\tsegs.push_back(cur);\n\t\t}\n\t\tfor (int fst = 1; fst <= n; ++fst) {\n\t\t\tvector<int> ans;\n\t\t\tbool ok = true;\n\t\t\tvector<set<int>> cur = segs;\n\t\t\tfor (auto &it : cur) if (it.count(fst)) it.erase(fst);\n\t\t\tans.push_back(fst);\n\t\t\tfor (int i = 1; i < n; ++i) {\n\t\t\t\tint cnt1 = 0;\n\t\t\t\tint nxt = -1;\n\t\t\t\tfor (auto  &it : cur) if (it.size() == 1) {\n\t\t\t\t\t++cnt1;\n\t\t\t\t\tnxt = *it.begin();\n\t\t\t\t}\n\t\t\t\tif (cnt1 != 1) {\n\t\t\t\t\tok = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tfor (auto &it : cur) if (it.count(nxt)) it.erase(nxt);\n\t\t\t\tans.push_back(nxt);\n\t\t\t}\n\t\t\tif (ok) {\n\t\t\t\tset<set<int>> all(segs.begin(), segs.end());\n\t\t\t\tfor (int i = 1; i < n; ++i) {\n\t\t\t\t\tset<int> seg;\n\t\t\t\t\tseg.insert(ans[i]);\n\t\t\t\t\tbool found = false;\n\t\t\t\t\tfor (int j = i - 1; j >= 0; --j) {\n\t\t\t\t\t\tseg.insert(ans[j]);\n\t\t\t\t\t\tif (all.count(seg)) {\n\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\tall.erase(seg);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!found) ok = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ok) {\n\t\t\t\tfor (auto it : ans) cout << it << \" \";\n\t\t\t\tcout << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1344",
    "index": "A",
    "title": "Hilbert's Hotel",
    "statement": "Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, \\textbf{including zero and negative integers}. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).\n\nFor any integer $k$ and positive integer $n$, let $k\\bmod n$ denote the remainder when $k$ is divided by $n$. More formally, $r=k\\bmod n$ is the smallest non-negative integer such that $k-r$ is divisible by $n$. It always holds that $0\\le k\\bmod n\\le n-1$. For example, $100\\bmod 12=4$ and $(-1337)\\bmod 3=1$.\n\nThen the shuffling works as follows. There is an array of $n$ integers $a_0,a_1,\\ldots,a_{n-1}$. Then for each integer $k$, the guest in room $k$ is moved to room number $k+a_{k\\bmod n}$.\n\nAfter this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.",
    "tutorial": "Suppose that $i+a_i\\equiv j+a_j\\pmod{n}$ for some $0\\le i<j<n$. Then $i+a_i=j+a_j+kn$ for some integer $k$, so the guest in room $i$ is assigned the same room as guest $j+kn$. Similarly, suppose that two different guests $k$ and $m$ are assigned the same room. Then we have $i+a_i\\equiv j+a_j\\pmod{n}$ for $i=k\\bmod n$ and $j=m\\bmod n$. This proves there is a collision if and only if all $i+a_i$ are not distinct $\\pmod n$. That is, $\\{(0+a_0)\\bmod n,(1+a_1)\\bmod n,\\ldots,(n-1+a_{n-1})\\bmod n\\}=\\{0,1,\\ldots,n-1\\}$. This is simply checked with a boolean array to make sure each number from $0$ to $n-1$ is included. Note that there are also no vacancies if this condition holds: Let $k$ be some room. Then $k\\bmod n$ must appear in the array, so there is some $i$ with $i+a_i\\equiv k\\pmod n$. Then there is an integer $m$ with $i+mn+a_i=k$, meaning guest $i+mn$ is moved to room $k$. Complexity is $O(n)$.",
    "tags": [
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1344",
    "index": "B",
    "title": "Monopole Magnets",
    "statement": "A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.\n\nThere is an $n\\times m$ grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.\n\nAn operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.\n\nEach cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.\n\n- There is at least one south magnet in every row and every column.\n- If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations \\textbf{from the initial placement}.\n- If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations \\textbf{from the initial placement}.\n\nDetermine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).",
    "tutorial": "Suppose two cells $A$ and $B$ are colored black in the same row. Since there must be a south magnet in every row, there are segments of black cells from $A$ and $B$ to the cell with the south magnet. The same result holds for columns. Therefore, for a solution to exist, every row and every column has exactly one segment of black cells or is all-white. Suppose there is an all-white row, but not an all-white column. (Or similarly, an all-white column but not an all-white row.) Then wherever we place a south magnet in this row, its column will have a black cell. But then the south magnet would be reachable, contradicting the fact that the row is all-white. Therefore, there should be an all-white row if and only if there is an all-white column, or no solution exists. Now that we have excluded these cases where no solution exists, let's construct a solution. Place a south magnet in a cell if: The cell is colored black, or Its row and column are both all-white. Then place one north magnet in each connected component of black cells. A north magnet cannot travel between components, so this is optimal.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1344",
    "index": "C",
    "title": "Quantifier Question",
    "statement": "Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. \\textbf{The set of real numbers includes zero and negatives.} There are two kinds of quantifiers: universal ($\\forall$) and existential ($\\exists$). You can read more about them here.\n\nThe universal quantifier is used to make a claim that a statement holds for all real numbers. For example:\n\n- $\\forall x,x<100$ is read as: for all real numbers $x$, $x$ is less than $100$. This statement is false.\n- $\\forall x,x>x-1$ is read as: for all real numbers $x$, $x$ is greater than $x-1$. This statement is true.\n\nThe existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example:\n\n- $\\exists x,x<100$ is read as: there exists a real number $x$ such that $x$ is less than $100$. This statement is true.\n- $\\exists x,x>x-1$ is read as: there exists a real number $x$ such that $x$ is greater than $x-1$. This statement is true.\n\nMoreover, these quantifiers can be nested. For example:\n\n- $\\forall x,\\exists y,x<y$ is read as: for all real numbers $x$, there exists a real number $y$ such that $x$ is less than $y$. This statement is true since for every $x$, there exists $y=x+1$.\n- $\\exists y,\\forall x,x<y$ is read as: there exists a real number $y$ such that for all real numbers $x$, $x$ is less than $y$. This statement is false because it claims that there is a maximum real number: a number $y$ larger than every $x$.\n\n\\textbf{Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.}\n\nThere are $n$ variables $x_1,x_2,\\ldots,x_n$, and you are given some formula of the form $$ f(x_1,\\dots,x_n):=(x_{j_1}<x_{k_1})\\land (x_{j_2}<x_{k_2})\\land \\cdots\\land (x_{j_m}<x_{k_m}), $$\n\nwhere $\\land$ denotes logical AND. That is, $f(x_1,\\ldots, x_n)$ is true if every inequality $x_{j_i}<x_{k_i}$ holds. Otherwise, if at least one inequality does not hold, then $f(x_1,\\ldots,x_n)$ is false.\n\nYour task is to assign quantifiers $Q_1,\\ldots,Q_n$ to either universal ($\\forall$) or existential ($\\exists$) so that the statement $$ Q_1 x_1, Q_2 x_2, \\ldots, Q_n x_n, f(x_1,\\ldots, x_n) $$\n\nis true, and \\textbf{the number of universal quantifiers is maximized}, or determine that the statement is false for every possible assignment of quantifiers.\n\n\\textbf{Note that the order the variables appear in the statement is fixed.} For example, if $f(x_1,x_2):=(x_1<x_2)$ then you are not allowed to make $x_2$ appear first and use the statement $\\forall x_2,\\exists x_1, x_1<x_2$. If you assign $Q_1=\\exists$ and $Q_2=\\forall$, it will \\textbf{only} be interpreted as $\\exists x_1,\\forall x_2,x_1<x_2$.",
    "tutorial": "Build a directed graph of variables, where an edge $x_i\\to x_j$ corresponds to an inequality $x_i<x_j.$ Say that two variables are comparable if there is a directed path from one variable to the other. Suppose $x_i$ and $x_j$ are comparable with $i<j$. Then $x_j$ cannot be universal since $x_i$ is determined before $x_j$ in the order and their comparability restricts the value of $x_j$. So, a requirement for universality is that the variable is only comparable with larger-indexed variables. If there is a cycle of inequalities, then there is no solution since the formula is contradictory. Otherwise, the graph is acyclic, so we can find a topological order. For each variable, we can find the minimum index of a node comparable to it by doing DP in forward and reverse topological order. Then for every variable not comparable to a smaller indexed variable, let it be universal. All other variables must be existential. Our requirement of universality proves this is optimal. Let's prove this assignment gives a true statement (other than proof by AC). First, we can decrease the index of existential variables, which only strengthens the statement. So let's decrease the index of each existential variable to appear just after its largest-indexed comparable universal variable. An existential variable $x_i$ may be comparable to many universal variables, but $x_i$ must be either greater than them all or less than them all. (Otherwise, we would have two comparable universals.) Without loss of generality, say $x_i$ is greater than its comparable universals. And suppose $x_i$ is less than another existential variable $x_j$. Then $x_j$ is comparable to the same universals as $x_i$, so we can determine the value of $x_j$ later such that it depends on $x_i$. Therefore, each existential variable is only restricted by a lower bound or an upper bound of smaller-indexed variables. We can properly assign values to them, satisfying all inequalities.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1344",
    "index": "D",
    "title": "Résumé Review",
    "statement": "Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)\n\nYou have completed many programming projects. In fact, there are exactly $n$ types of programming projects, and you have completed $a_i$ projects of type $i$. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.\n\nYou want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:\n\n$$ f(b_1,\\ldots,b_n)=\\sum\\limits_{i=1}^n b_i(a_i-b_i^2). $$\n\nHere, $b_i$ denotes the number of projects of type $i$ you include in your résumé. Of course, you cannot include more projects than you have completed, so you require $0\\le b_i \\le a_i$ for all $i$.\n\nYour résumé only has enough room for $k$ projects, and you will absolutely not be hired if your résumé has empty space, so you require $\\sum\\limits_{i=1}^n b_i=k$.\n\nFind values for $b_1,\\ldots, b_n$ that maximize the value of $f(b_1,\\ldots,b_n)$ while satisfying the above two constraints.",
    "tutorial": "If we increment some $b_i$ to $x$, the value of $f$ changes by $\\Delta_i (x):=\\left[x(a_i-x^2)\\right]-\\left[(x-1)(a_i-(x-1)^2)\\right]=a_i-3x^2+3x-1,$ which decreases for $x\\ge 1.$ If we initially set all $b_i$ to $0$, then greedily incrementing the best index gives an optimal solution. Since $k$ is large, we cannot afford to do this one increment at a time. However, we can observe that this process increments the values as long as $\\Delta_i (x)\\ge A$ for some constant $A$. Simply binary search on the value of $A$ so that we increment exactly $k$ times. To compute the cutoffs for the $x$ values, we can either use the quadratic formula or do another binary search. There may be ties for the $\\Delta_i(x)$ values, but this can be handled without too much trouble. Let $A=\\max_{i=1,\\ldots,n}\\{a_i\\}$. Complexity is $O(n\\log(A))$ with the quadratic formula, or $O(n\\log^2(A))$ with another binary search.",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1344",
    "index": "E",
    "title": "Train Tracks",
    "statement": "That's right. I'm a Purdue student, and I shamelessly wrote a problem about trains.\n\nThere are $n$ stations and $m$ trains. The stations are connected by $n-1$ one-directional railroads that form a tree rooted at station $1$. All railroads are pointed in the direction from the root station $1$ to the leaves. A railroad connects a station $u$ to a station $v$, and has a distance $d$, meaning it takes $d$ time to travel from $u$ to $v$. Each station with at least one outgoing railroad has a switch that determines the child station an incoming train will be directed toward. For example, it might look like this:\n\n\\begin{center}\nHere, stations $1$ and $3$ have switches directed toward stations $2$ and $4$, respectively.\n\\end{center}\n\nInitially, no trains are at any station. Train $i$ will enter station $1$ at time $t_i$. Every unit of time, starting at time $1$, the following two steps happen:\n\n- You can switch at most one station to point to a different child station. A switch change takes effect before step $2$.\n- For every train that is on a station $u$, it is directed toward the station $v$ indicated by $u$'s switch. So, if the railroad from $u$ to $v$ has distance $d$, the train will enter station $v$ in $d$ units of time from now.\n\nEvery train has a destination station $s_i$. When it enters $s_i$, it will stop there permanently. If at some point the train is going in the wrong direction, so that it will never be able to reach $s_i$ no matter where the switches point, it will immediately explode.\n\nFind the \\textbf{latest possible time of the first explosion} if you change switches optimally, or determine that you can direct every train to its destination so that no explosion occurs. Also, find the \\textbf{minimum number of times you need to change a switch} to achieve this.",
    "tutorial": "First, observe that a train can never pass one that enters earlier. So let's consider the trains independently. For a train $i$, look at the path from $1$ to $s_i$. We may need to change the switches of several stations on this path. We must make each switch within a time interval $(L, R]$, where $L$ is the most recent time some other train was directed the other way, and $R$ is the time train $i$ will enter the station. Let's mark all of these switches as changed before processing the next train. Suppose the total number of switch changes is $k$, and for each station, we know its time intervals. We can manage all events in a priority queue of size $n$, always changing the switch with the earliest deadline that we can. Keep doing this until we are too late for a deadline, in which case an explosion happens, or until we have successfully made every switch change. This part will take $O(k\\log n)$ time. Let's find a nice upper bound on $k$. Note that the switches decompose the tree into a set of disjoint paths. When we process a train $i$, we are changing the switches to make a path from the root to $s_i$. It turns out this is exactly the same as an access operation on a link/cut tree! Because link/cut trees have $O(\\log n)$ amortized time per operation, we can guarantee that the total number of switch changes is $k=O(n+m\\log n)$. Now let's consider the problem of finding all time intervals. We could use a link/cut tree, but everyone hates those, so let's discuss other methods. One strategy is to maintain a list of trains that go through a station, for every station. We start at the leaves and merge the lists going up. We can merge the lists efficiently by inserting elements from the smaller list to the larger list. Then a switch only needs to be changed when consecutive trains go to different children. Unlike some of the testers, I wasn't smart enough to come up with the elegant small-to-large merging idea. So let's discuss an alternate solution using segment trees. When processing a train $i$, we want to do the following: Find the top node $x$ of the path leading to $s_i$. If $x$ is not the root, make the parent of $x$ point to $x$, and record the time interval we must make this switch. Repeat from step $1$ until $x$ is the root. The queries we want to support are thus: Find the time the most recent train passed through a node $x$ (ignoring trains with $s_i=x,$ where it only stops at $x$). Find the top node of the path containing node $x$. Let's handle queries of type $1$ with a segment tree. After processing train $i$, update the value at index $s_i$ to $i$. To answer a query, find the maximum value in the range corresponding to the relevant subtree. Let's also handle queries of type $2$ with a segment tree. At a segment tree node, store the minimum value on its range. To answer a query, check the range $[x,x]$. Support lazy updates of the form \"On a range $[l, r]$, replace all values $X$ with value $Y$, with the precondition that $X$ is currently the minimum value in $[l,r]$ and $Y$ will remain the minimum value after the update\". To make a switch change, we only need to do two lazy updates. Therefore, finding all the time intervals will take $O((m+k)\\log n)$ time. The overall complexity is $O(n\\log n+m\\log^2 n)$.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1344",
    "index": "F",
    "title": "Piet's Palette",
    "statement": "Piet Mondrian is an artist most famous for his minimalist works, consisting only of the four colors red, yellow, blue, and white. Most people attribute this to his style, but the truth is that his paint behaves in a very strange way where mixing two primary colors only produces another primary color!\n\n\\begin{center}\nA lesser known piece, entitled \"Pretentious rectangles\"\n\\end{center}\n\nA sequence of primary colors (red, yellow, blue) is mixed as follows. While there are at least two colors, look at the first two. If they are distinct, replace them with the missing color. If they are the same, remove them from the sequence. In the end, if there is one color, that is the resulting color. Otherwise, if the sequence is empty, we say the resulting color is white. Here are two example mixings:\n\n  Piet has a color palette with cells numbered from $1$ to $n$. Each cell contains a primary color or is empty. Piet is very secretive, and will not share his palette with you, so you do not know what colors belong to each cell.\n\nHowever, he did perform $k$ operations. There are four kinds of operations:\n\n- In a \\textbf{mix} operation, Piet chooses a subset of cells and mixes their colors together in some order. The order is not necessarily by increasing indexes. He records the resulting color. Empty cells are skipped over, having no effect on the mixing process. The mixing does not change the color values stored in the cells.\n- In a \\textbf{RY} operation, Piet chooses a subset of cells. Any red cells in this subset become yellow, and any yellow cells in this subset become red. Blue and empty cells remain unchanged.\n- In a \\textbf{RB} operation, Piet chooses a subset of cells. Any red cells in this subset become blue, and any blue cells in this subset become red. Yellow and empty cells remain unchanged.\n- In a \\textbf{YB} operation, Piet chooses a subset of cells. Any yellow cells in this subset become blue, and any blue cells in this subset become yellow. Red and empty cells remain unchanged.\n\nPiet only tells you the list of operations he performs in chronological order, the indexes involved, and the resulting color of each mix operation. For each mix operation, you also know the order in which the cells are mixed. Given this information, determine the color of each cell in the initial palette. That is, you should find one possible state of the palette (before any operations were performed), or say that the described situation is impossible.",
    "tutorial": "Equate an empty cell with the color white, and let's represent the colors as 0/1 vectors: $W=\\begin{bmatrix}0\\\\0\\end{bmatrix},\\ R=\\begin{bmatrix}1\\\\0\\end{bmatrix},\\ Y=\\begin{bmatrix}0\\\\1\\end{bmatrix},\\ B=\\begin{bmatrix}1\\\\1\\end{bmatrix}.$ Under this representation, mixing becomes addition $\\pmod{2}$. And the operations $\\mathrm{RY}$, $\\mathrm{RB}$, $\\mathrm{YB}$ are linear transformations of the colors. That is, each of these operations is equivalent to multiplying the corresponding matrix by a cell's vector: $\\mathrm{RY}=\\begin{bmatrix}0&1\\\\1&0\\end{bmatrix},\\ \\mathrm{RB}=\\begin{bmatrix}1&0\\\\1&1\\end{bmatrix},\\ \\mathrm{YB}=\\begin{bmatrix}1&1\\\\0&1\\end{bmatrix}.$ We simply have a system of $2k$ linear equations on $2n$ unknowns, which we can solve with Gaussian elimination using bitsets. Complexity is $O((2k)^2 (2n) / 64).$",
    "tags": [
      "matrices"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1345",
    "index": "A",
    "title": "Puzzle Pieces",
    "statement": "You are given a special jigsaw puzzle consisting of $n\\cdot m$ identical pieces. Every piece has three tabs and one blank, as pictured below.\n\nThe jigsaw puzzle is considered solved if the following conditions hold:\n\n- The pieces are arranged into a grid with $n$ rows and $m$ columns.\n- For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece.\n\nThrough rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.",
    "tutorial": "If $n=1$ or $m=1$, then we can chain the pieces together to form a solution. If $n=m=2$, we can make the following solution: Any other potential solution would contain a $2\\times 3$ or a $3\\times 2$ solution, which we can show is impossible. A $2\\times 3$ grid has $7$ shared edges between the pieces, and each shared edge must have a blank. But there are only $6$ blanks available as there are $6$ pieces.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1345",
    "index": "B",
    "title": "Card Constructions",
    "statement": "A card pyramid of height $1$ is constructed by resting two cards against each other. For $h>1$, a card pyramid of height $h$ is constructed by placing a card pyramid of height $h-1$ onto a base. A base consists of $h$ pyramids of height $1$, and $h-1$ cards on top. For example, card pyramids of heights $1$, $2$, and $3$ look as follows:\n\nYou start with $n$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?",
    "tutorial": "Let's count the number of cards in a pyramid of height $h$. There are $2(1+2+3+\\cdots+h)$ cards standing up, and there are $0+1+2+\\cdots+(h-1)$ horizontal cards. So, there are $2\\frac{h(h+1)}{2}+\\frac{(h-1)h}{2}=\\frac{3}{2}h^2+\\frac12 h$ cards total. Using this formula, we can quickly find the largest height $h$ that uses at most $n$ cards. The quadratic formula or binary search can be used here, but are unnecessary. Simply iterating through all $h$ values works in $O(\\sqrt n)$ time per test. It's enough to see that this takes $O(t\\sqrt N)$ time overall, where $N$ is the sum of $n$ across all test cases. But interestingly, we can argue for a tighter bound of $O(\\sqrt{tN})$ due to the Cauchy-Schwarz Inequality: $\\sum_{i=1}^t \\left(1\\cdot \\sqrt{n_i}\\right)\\le \\sqrt{\\left(\\sum_{i=1}^t1^2\\right)\\left(\\sum_{i=1}^t\\left(\\sqrt n_i\\right)^2\\right)}=\\sqrt{tN}$",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1348",
    "index": "A",
    "title": "Phoenix and Balance",
    "statement": "Phoenix has $n$ coins with weights $2^1, 2^2, \\dots, 2^n$. He knows that $n$ is even.\n\nHe wants to split the coins into two piles such that each pile has exactly $\\frac{n}{2}$ coins and the difference of weights between the two piles is \\textbf{minimized}. Formally, let $a$ denote the sum of weights in the first pile, and $b$ denote the sum of weights in the second pile. Help Phoenix minimize $|a-b|$, the absolute value of $a-b$.",
    "tutorial": "We observe that the coin with the weight $2^n$ is greater than the sum of all the other weights combined. This is true because $\\sum\\limits_{i = 1}^{n-1}2^i=2^n-2$. Therefore, the pile that has the heaviest coin will always weigh more. To minimize the weight differences, we put the $n/2-1$ lightest coins into the pile with the heaviest coin. The answer will be $(2^n+\\sum\\limits_{i = 1}^{n/2-1}2^i)-\\sum\\limits_{i = n/2}^{n-1}2^i$. Time complexity for each test case: $O(n)$ You can also solve the problem in $O(1)$ by simplifying the mathematical expression.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n  int N;\n  cin>>N;\n  //note: 1<<X means 2^X\n  //we put largest coin in first pile\n  int sum1=(1<<N), sum2=0;\n  //we put n/2-1 smallest coins in first pile\n  for (int i=1;i<N/2;i++)\n    sum1+=(1<<i);\n  //we put remaining n/2 coins in second pile\n  for (int i=N/2;i<N;i++)\n    sum2+=(1<<i);\n  cout<<sum1-sum2<<endl;\n}\n\nint main(){\n  int t; cin>>t;\n  while (t--)\n    solve();\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1348",
    "index": "B",
    "title": "Phoenix and Beauty",
    "statement": "Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $k$ have the same sum. A subarray of an array is any sequence of consecutive elements.\n\nPhoenix currently has an array $a$ of length $n$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $1$ and $n$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is \\textbf{not trying} to minimize the number of inserted integers.",
    "tutorial": "For an array to be beautiful for some $k$, the array must be periodic with period $k$. If there exists more than $k$ distinct numbers in the array $a$, there is no answer and we print -1 (because the array cannot be periodic with period $k$). Otherwise, we propose the following construction. Consider a list of all the distinct numbers in array $a$. If there are less than $k$ of them, we will append some $1$s (or any other number) until the list has size $k$. We can just print this list $n$ times. The length of our array $b$ is $nk$, which never exceeds $10^4$. Array $b$ can always be constructed by inserting some numbers into array $a$ because every number in $a$ corresponds to one list. Time complexity for each test case: $O(n \\log{n}+nk)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n  int N,K;\n  cin>>N>>K;\n  set<int>s;\n  for (int i=0;i<N;i++){\n    int a;\n    cin>>a;\n    s.insert(a);\n  }\n  //if more than K distinct numbers, print -1\n  if (s.size()>K){\n    cout<<-1<<endl;\n    return;\n  }\n  cout<<N*K<<endl;\n  for (int i=0;i<N;i++){\n    //print the distinct numbers\n    for (int b:s)\n      cout<<b<<' ';\n    //print the extra 1s\n    for (int j=0;j<K-(int)s.size();j++)\n      cout<<1<<' ';\n  }\n  cout<<endl;\n}\n\nint main(){\n  int t; cin>>t;\n  while (t--)\n    solve();\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1348",
    "index": "C",
    "title": "Phoenix and Distribution",
    "statement": "Phoenix has a string $s$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $k$ \\textbf{non-empty} strings $a_1, a_2, \\dots, a_k$ such that every letter of $s$ goes to exactly one of the strings $a_i$. The strings $a_i$ \\textbf{do not} need to be substrings of $s$. Phoenix can distribute letters of $s$ and rearrange the letters within each string $a_i$ however he wants.\n\nFor example, if $s = $ baba and $k=2$, Phoenix may distribute the letters of his string in many ways, such as:\n\n- ba and ba\n- a and abb\n- ab and ab\n- aa and bb\n\nBut these ways are invalid:\n\n- baa and ba\n- b and ba\n- baba and empty string ($a_i$ should be non-empty)\n\nPhoenix wants to distribute the letters of his string $s$ into $k$ strings $a_1, a_2, \\dots, a_k$ to \\textbf{minimize} the lexicographically maximum string among them, i. e. minimize $max(a_1, a_2, \\dots, a_k)$. Help him find the optimal distribution and print the minimal possible value of $max(a_1, a_2, \\dots, a_k)$.\n\nString $x$ is lexicographically less than string $y$ if either $x$ is a prefix of $y$ and $x \\ne y$, or there exists an index $i$ ($1 \\le i \\le min(|x|, |y|))$ such that $x_i$ < $y_i$ and for every $j$ $(1 \\le j < i)$ $x_j = y_j$. Here $|x|$ denotes the length of the string $x$.",
    "tutorial": "We first try to assign one letter to each string $a_i$. Let's denote the smallest letter in $s$ as $c$. If there exists at least $k$ occurrences of $c$ in $s$, we will assign $c$ as the first letter of each string $a_i$. Otherwise, the minimal solution is the $k$th smallest letter in $s$. For example, if $s=$aabbb and $k=3$, the $3$rd smallest letter is $b$ and that will be the answer. Otherwise, we consider the letters that are left in $s$. If they are all the same letter (or there are no letters left because $n=k$), we split the remaining letters as evenly as possible among $a_i$. If not, we will show that it is optimal to sort the remaining letters in $s$ and append them to arbitrary $a_i$. For example, let's suppose after assigning a letter to each $a_i$ that the remaining letters in $s$ are aaabb. We want to assign the $b$s as late as possible, so any string $a_i$ that receives a $b$ should have some number of $a$s before. It makes sense in fact that the string that receives a $b$ should receive all the $a$s, because if not it will be lexicographically larger. It can then be shown that all remaining larger letters should be sorted and added to the same string $a_i$ to minimize the answer. Time complexity for each test case: $O(n \\log{n})$ (for sorting $s$)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n  int n,k;\n  cin>>n>>k;\n  string s;\n  cin>>s;\n  sort(s.begin(),s.end());\n  //if smallest k letters are not all the same, answer is kth smallest letter\n  if (s[0]!=s[k-1]){\n    cout<<s[k-1]<<endl;\n    return;\n  }\n  cout<<s[0];\n  //if remaining letters aren't the same, we append remaining letters to answer\n  if (s[k]!=s[n-1]){\n    for (int i=k;i<n;i++)\n      cout<<s[i];\n  }\n  else{\n    //remaining letters are the same, so we distribute evenly\n    for (int i=0;i<(n-k+k-1)/k;i++)\n      cout<<s[n-1];\n  }\n  cout<<endl;\n}\n\nint main(){\n  int t; cin>>t;\n  while (t--)\n    solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1348",
    "index": "D",
    "title": "Phoenix and Science",
    "statement": "Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.\n\nInitially, on day $1$, there is one bacterium with mass $1$.\n\nEvery day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $m$ splits, it becomes two bacteria of mass $\\frac{m}{2}$ each. For example, a bacterium of mass $3$ can split into two bacteria of mass $1.5$.\n\nAlso, every night, the mass of every bacteria will increase by one.\n\nPhoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $n$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!",
    "tutorial": "There exists many constructive solutions, here is one I think is very elegant. We will try to approach the problem by considering how much the total mass increases every night. If there are $x$ bacteria some day before the splitting, that night can have a mass increase between $x$ and $2x$ inclusive (depending on how many bacteria split that day). Therefore, we can reword the problem as follows: construct a sequence $a$ of minimal length $a_0=1, a_1, \\dots, a_k$ such that $a_i \\le a_{i+1} \\le 2a_i$ and the sum of $a_i$ is $n$. To minimize the length of sequence $a$, we will start building our sequence with $1, 2, \\dots, 2^x$ such that the total sum $s$ is less than or equal to $n$. If the total sum is $n$, we are done. Otherwise, we insert $n-s$ into our sequence and sort. This gives a valid sequence of minimal length. To transform our sequence $a$ into the answer, we can just print the differences $a_i-a_{i-1}$ because the number of bacteria that split during the day is equal to how much the mass increase changes. Time complexity for each test case: $O(\\log{n})$, if you sort by insertion",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n  vector<int>inc;   \n  int N;\n  cin>>N;\n  //construct sequence 1, 2, 4, ... while sum <= N\n  for (int i=1;i<=N;i*=2){\n    inc.push_back(i);\n    N-=i;\n  }\n  //if sum is not N, we insert and sort\n  if (N>0){\n    inc.push_back(N);\n    sort(inc.begin(),inc.end());\n  }\n  cout<<inc.size()-1<<endl;\n  for (int i=1;i<(int)inc.size();i++)\n    cout<<inc[i]-inc[i-1]<<' ';\n  cout<<endl;\n}\n\nint main(){\n  int t; cin>>t;\n  while (t--)\n    solve();\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1348",
    "index": "E",
    "title": "Phoenix and Berries",
    "statement": "Phoenix is picking berries in his backyard. There are $n$ shrubs, and each shrub has $a_i$ red berries and $b_i$ blue berries.\n\nEach basket can contain $k$ berries. But, Phoenix has decided that each basket may only contain berries from the same shrub or berries of the same color (red or blue). In other words, all berries in a basket must be from the same shrub or/and have the same color.\n\nFor example, if there are two shrubs with $5$ red and $2$ blue berries in the first shrub and $2$ red and $1$ blue berries in the second shrub then Phoenix can fill $2$ baskets of capacity $4$ completely:\n\n- the first basket will contain $3$ red and $1$ blue berries from the first shrub;\n- the second basket will contain the $2$ remaining red berries from the first shrub and $2$ red berries from the second shrub.\n\nHelp Phoenix determine the maximum number of baskets he can \\textbf{fill completely}!",
    "tutorial": "Solution 1: There is no obvious greedy solution, so we will try dynamic programming. Let $dp[i][j]$ be a boolean array that denotes whether we can have $j$ extra red berries after considering the first $i$ shrubs. A berry is extra if it is not placed into a full basket (of any kind). Note that if we know that there are $j$ extra red berries, we can also easily calculate how many extra blue berries there are. Note that we can choose to never have more than $k-1$ extra red berries, because otherwise we can fill some number of baskets with them. To transition from shrub $i-1$ to shrub $i$, we loop over all possible values $l$ from $0$ to $min(k-1, a_i)$ and check whether or not we can leave $l$ extra red berries from the current shrub $i$. For some $i$ and $j$, we can leave $l$ extra red berries and put the remaining red berries in baskets possibly with blue berries from the same shrub if $(a_i-l)$ $mod$ $k+b_i \\ge k$. The reasoning for this is as follows: First of all, we are leaving $l$ red berries (or at least trying to). We show that from this shrub, there will be at most one basket containing both red and blue berries (all from this shrub). To place the remaining red berries into full baskets, the more blue berries we have the better. It is optimal to place the remaining $a_i-l$ red berries into their own separate baskets first before merging with the blue berries (this way requires fewest blue berries to satisfy the condition). Then, if $(a_i-l)$ $mod$ $k+b_i$ is at least $k$, we can fill some basket with the remaining red berries and possibly some blue berries. Remember that we do not care about how many extra blue berries we leave because that is uniquely determined by the number of extra red berries. Also note that we can always leave $a_i$ $mod$ $k$ extra red berries. Denote the total number of berries as $t$. The answer will be maximum over all $(t-j)/k$ such that $dp[n][j]$ is true, $0\\le j\\le k-1$. Time Complexity: $O(nk^2)$ Solution 2: We use dynamic programming. Let $dp[i][j]$ be true if after considering the first $i$ shrubs , $j$ is the number of red berries in heterogenous baskets modulo $k$. Heterogenous baskets contain berries from the same shrub, and homogenous baskets contain berries of the same type. Suppose we know the number of red berries in heterogeneous baskets modulo $k$. This determines the number of blue berries in heterogeneous baskets modulo $k$. Since the number of red berries in homogeneous baskets is a multiple of $k$, it also determines the number of red berries not in any baskets (we can safely assume this to be less than $k$ since otherwise we can form another basket). Similarly, we can determine the number of blue berries not in any basket, and thus deduce the number of baskets. To compute the possible numbers of red berries in heterogeneous baskets modulo $k$, it suffices to look at each shrub separately and determine the possible numbers of red berries modulo $k$ in heterogeneous baskets for that shrub. If there is more than one heterogeneous basket for one shrub, we can rearrange the berries to leave at most one heterogeneous. Now we have two cases. If there are no heterogeneous baskets, the number of red berries in those baskets is obviously zero. If there is one heterogeneous basket, let $x$ be the number of red berries in it and $k-x$ be the number of blue berries in it. Clearly, $0\\le x \\le a_i$ and $0 \\le k-x \\le b_i$. Rearranging, we get $max(0,k-b_i)\\le x \\le min(a_i,k)$. These correspond to the transitions for our DP. There exists faster solutions (like $O(nk)$), can you find it?",
    "code": "//Solution 1\n#include <bits/stdc++.h>\nusing namespace std;\n\nint N,K;\nint a[505],b[505];\nbool dp[505][505];  //number of shrubs considered, \"extra\" red berries\n\nint main(){\n  cin>>N>>K;\n  long long totA=0,totB=0;\n  for (int i=1;i<=N;i++){\n    cin>>a[i]>>b[i];\n    totA+=a[i];\n    totB+=b[i];\n  }\n  dp[0][0]=true;\n  for (int i=1;i<=N;i++){\n    for (int j=0;j<K;j++){\n      //leave a[i]%K extra red berries\n      dp[i][j]=dp[i-1][(j-a[i]%K+K)%K];\n      for (int l=0;l<=min(K-1,a[i]);l++){\n\t//check if we can leave l extra red berries\n\tif ((a[i]-l)%K+b[i]>=K)\n\t  dp[i][j]|=dp[i-1][(j-l+K)%K];\n      }\n    }\n  }\n  long long ans=0;\n  for (int i=0;i<K;i++){\n    if (dp[N][i])\n      ans=max(ans,(totA+totB-i)/K);\n  }\n  cout<<ans<<endl;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1348",
    "index": "F",
    "title": "Phoenix and Memory",
    "statement": "Phoenix is trying to take a photo of his $n$ friends with labels $1, 2, \\dots, n$ who are lined up in a row in a special order. But before he can take the photo, his friends get distracted by a duck and mess up their order.\n\nNow, Phoenix must restore the order but he doesn't remember completely! He only remembers that the $i$-th friend from the left had a label between $a_i$ and $b_i$ inclusive. Does there exist a unique way to order his friends based of his memory?",
    "tutorial": "There are many many many solutions to this problem (which is cool!). I describe two of them below. Both solutions first find an arbitrary valid ordering. This can be done in $O(n\\log{n})$ with a greedy algorithm. We can sort the intervals $(a_i,b_i)$ and sweep from left to right. To see which position that we can assign friend $j$ to, we process all intervals with $a_i \\le j$ and insert $b_i$ into a multiset (or similar) structure. We match friend $j$ to the interval with minimal $b_i$. Solution $1$: We prove that if there exists more than one valid ordering, we can transform one into another by swapping two friends. Proof: In our valid ordering, each friend is assigned a position. We can think of this as a point being assigned to an interval (Friend - point, position - interval). We will prove there exists a cycle of length $2$ or there exists no cycle at all. Suppose we have a cycle: each point is on its interval and its predecessor's interval. Let's take the shortest cycle of length at least two. Let $q$ be the leftmost point, $p$ be $q$'s predecessor, and $r$ be $q$'s successor. Case $1$: $q$'s interval's right endpoint is to the right of $p$. $p$ and $q$ form a cycle of length $2$. Case $2$: $q$'s interval's right endpoint is to the left of $p$. $r$ must be between $q$ and $p$. So, we can remove $q$ and get a shorter cycle. This is a contradiction. $\\square$ Denote $p_i$ as the position that friend $i$ is assigned to in our arbitrary ordering. Now, we are interested whether or not there exists a friend $i$ such that there also exists some friend $j$ with $p_j$ such that $p_i < p_j \\le b_{p_i}$ and $a_{p_j} \\le p_i$. If there does, we can swap friends $i$ and $j$ to make another valid ordering. This can be done with a segment tree (build it with values $a_i$). Time Complexity: $O(n \\log n)$ Solution $2$: The problem is equivalent to checking if there is a unique perfect matching in the following bipartite graph: The vertices on the left correspond to position. The vertices on the right correspond to labels of the friends. A directed edge from a position node to a label node exists iff the friend with that label can be at that position. Find a perfect matching (corresponding to finding any valid assignment) as described above. The matching is unique iff contracting the edges (merging nodes connected by edges from our perfect matching into one node) in the perfect matching creates a DAG. The reasoning is as follows: Consider a simpler graph, with only nodes representing positions. We draw a directed edge from node $i$ to node $j$ if the friend currently assigned at position $i$ (from our greedy) can also be assigned to position $j$. So, if there exists any cycle, we can shift the friends around the cycle to create another valid ordering. In other words, if our graph is a DAG, the perfect matching is unique. Now, returning back to the bipartite graph, we see that it is essentially the same. By contracting edges, all position nodes are equivalent to the friend node that is assigned to them (from the greedy). So, following an edge from the left side (position) to the right side (friend) puts us back on the left side (position), and this graph corresponds to the simpler version I explained above. So, this can be done by DFS in $O(n^2)$, but this is too slow. We can speed it up by storing a set of unvisited vertices and only iterating across those (by binary search on set-like structure). Binary search works because every position corresponds to a range of friends. Time Complexity: $O(n \\log{n})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint N;\nint a[200005],b[200005];\nint label[200005]; //the label of the person at i-th position in our perfect matching\nint label2[200005]; //which position the i-th person is at\n\nvoid perfectMatch(){ //finds a perfect matching\n  deque<pair<pair<int,int>,int>>v;\n  for (int i=1;i<=N;i++)\n    v.push_back({{a[i],b[i]},i});\n  sort(v.begin(),v.end());\n  multiset<pair<int,int>>mst;\n  for (int i=1;i<=N;i++){\n    while ((int)v.size()>0 && v[0].first.first<=i){\n      mst.insert({v[0].first.second,v[0].second});\n      v.pop_front();\n    }\n    //match person with label to earliest ending interval\n    label2[i]=mst.begin()->second;\n    label[mst.begin()->second]=i;\n    mst.erase(mst.find(*mst.begin()));\n  }\n}\n\nset<int>active;\nint vis[200005];\nint from[200005];\nint ans[200005];\n\nvoid foundAnother(int node, int nextNode){\n  vector<int>v;\n  int cur=node;\n  //backtracks on cycle to find other ordering\n  while (cur!=label2[nextNode]){\n    v.push_back(cur);\n    cur=from[cur];\n  }\n  reverse(v.begin(),v.end());\n  v.push_back(label2[nextNode]);\n  reverse(v.begin(),v.end());\n  cout<<\"NO\"<<endl;\n  for (int i=1;i<=N;i++)\n    cout<<label[i]<<' ';\n  cout<<endl;\n  for (int i=1;i<=N;i++)\n    ans[i]=label[i];\n  int temp=ans[v.back()];\n  for (int i=0;i<(int)v.size();i++)\n    swap(temp,ans[v[i]]);\n  for (int i=1;i<=N;i++)\n    cout<<ans[i]<<' ';\n  cout<<endl;\n  exit(0);\n}\n  \nvoid dfs(int node){\n  //activates node\n  vis[node]=1;\n  queue<int>toRemove;\n  for (;;){\n    //binary search for unvisisited neighbor\n    auto it=active.lower_bound(a[node]);\n    if (it!=active.end() && *it==label[node]){\n      toRemove.push(*it);\n      it++;\n    }\n    if (it==active.end() || *it>b[node])\n      break;\n    if (vis[label2[*it]]==1) //found cycle (another ordering)\n      foundAnother(node,*it);\n    toRemove.push(*it);\n    if (vis[label2[*it]]==2)\n      continue;\n    from[label2[*it]]=node;\n    dfs(label2[*it]);\n  }\n  //removes visited nodes from set\n  while (!toRemove.empty()){\n    if (active.count(toRemove.front()))\n      active.erase(toRemove.front());\n    toRemove.pop();\n  }\n  //deactivates and retire node\n  vis[node]=2;\n}\n\nint main(){\n  cin>>N;\n  for (int i=1;i<=N;i++)\n    cin>>a[i]>>b[i];\n  perfectMatch();\n  for (int i=1;i<=N;i++)\n    active.insert(i);\n  for (int i=1;i<=N;i++)\n    if (vis[i]==0)\n      dfs(i);\n  cout<<\"YES\"<<endl;\n  for (int i=1;i<=N;i++)\n    cout<<label[i]<<' ';\n  cout<<endl;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1349",
    "index": "A",
    "title": "Orac and LCM",
    "statement": "For the multiset of positive integers $s=\\{s_1,s_2,\\dots,s_k\\}$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $s$ as follow:\n\n- $\\gcd(s)$ is the maximum positive integer $x$, such that all integers in $s$ are divisible on $x$.\n- $\\textrm{lcm}(s)$ is the minimum positive integer $x$, that divisible on all integers from $s$.\n\nFor example, $\\gcd(\\{8,12\\})=4,\\gcd(\\{12,18,6\\})=6$ and $\\textrm{lcm}(\\{4,6\\})=12$. Note that for any positive integer $x$, $\\gcd(\\{x\\})=\\textrm{lcm}(\\{x\\})=x$.\n\nOrac has a sequence $a$ with length $n$. He come up with the multiset $t=\\{\\textrm{lcm}(\\{a_i,a_j\\})\\ |\\ i<j\\}$, and asked you to find the value of $\\gcd(t)$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.",
    "tutorial": "In this tutorial $p$ stands for a prime, $v$ stands for the maximum of $a_i$ and $ans$ stands for the answer. Observation. $p^k\\ \\mid\\ ans$ if and only if there are at least $n-1$ integers in $a$ that $\\mathrm{s.t. }\\ p^k\\mid\\ a_i$. Proof. if there are at most $n-2$ integers in $a$ that $\\mathrm{s.t. }\\ p^k\\mid\\ a_i$, there exists $x\\neq y$ $\\mathrm{s.t.}\\ p^k\\nmid a_x$ $\\mathrm{and}$ $p^k\\nmid a_y$, so $p^k \\nmid \\textrm{lcm}(\\{a_x,a_y\\})$ and $p^k\\ \\nmid\\ ans$. On the contrary, if there are at least $n-1$ integers in $a$ $\\mathrm{s.t. }\\ p^k\\mid\\ a_i$, between every two different $a_i$ there will be at least one multiple of $p^k$. So for every $(x,y)$, $p^k \\mid \\textrm{lcm}(\\{a_x,a_y\\})$. Therefore $p^k\\ \\mid\\ ans$. Solution 1. Define $d_i$ as a set that consists of all the numbers in $a$ except $a_i$. So $\\gcd(d_i)$ is divisible by at least $n-1$ numbers in $a$. Also, if at least $n-1$ integers in $a$ $\\mathrm{s.t. }\\ p^k\\ \\mid\\ a_i$, we can always find $i$ $\\mathrm{s.t. }\\ p^k \\mid \\gcd(d_i)$. According to the Observation, $ans=\\textrm{lcm}(\\{\\gcd(d_1),\\gcd(d_2),\\gcd(d_3),...,\\gcd(d_n)\\})$. Now consider how to calculate $\\gcd(d_i)$. For every $i$, calculate $pre_i=\\gcd(\\{a_1,a_2,...,a_i\\})$ and $suf_i=\\gcd(\\{a_{i},a_{i+1},...,a_n\\})$. Therefore $\\gcd(d_i)=\\gcd(\\{pre_{i-1},suf_{i+1}\\})$ and we can get $pre$ and $suf$ in $O(n\\cdot \\log(v))$ time. Time complexity: $O(n \\log v)$ Solution 2. Enumerate every prime $\\leq v$. For a prime $p$, enumerate every $a_i$ and calculate $k_i$ which stands for the maximum integer that $\\mathrm{s.t. }\\ p^{k_i} \\mid a_i$. According to the Observation, the second smallest $k_i$ is the maximum integer $k$ that $\\mathrm{s.t. }\\ p^k \\mid ans$. Now let's optimize this solution. If there has been at least two $a_i$ not divisible by $p$, then $p \\nmid ans$, so just stop enumerate $a_i$. Time complexity of the optimized solution is $O(v+n \\log v)$ because every integer can be divided for at most $\\log v$ times.",
    "code": "#include <iostream>\n#include <cstdio>\n\nusing namespace std;\ntypedef long long ll;\n\nconst int maxn=100005;\n\nint n;\nll a[maxn];\n\nll pre[maxn],suf[maxn];\n\nll gcd(ll x, ll y)\n{\n\tif(y==0) return x;\n\telse return gcd(y,x%y);\n}\n\nll ga,ans;\n\nint main()\n{\n\tscanf(\"%d\",&n);\n\tfor(int i=1;i<=n;i++) scanf(\"%lld\",&a[i]);\n\tpre[1]=a[1]; suf[n]=a[n];\n\tfor(int i=2;i<=n;i++)\n\t\tpre[i]=gcd(pre[i-1],a[i]);\n\tfor(int i=n-1;i>=1;i--)\n\t\tsuf[i]=gcd(suf[i+1],a[i]);\n\tfor(int i=0;i<=n-1;i++)\n\t{\n\t\tif(i==0)\n\t\t\tans=suf[2];\n\t\telse if(i==n-1)\n\t\t\tans=ans*pre[n-1]/gcd(pre[n-1],ans);\n\t\telse\n\t\t\tans=ans*gcd(pre[i],suf[i+2])/gcd(gcd(pre[i],suf[i+2]),ans);\n\t}\n\tprintf(\"%lld\\n\",ans);\n\treturn 0;\n}\n",
    "tags": [
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1349",
    "index": "B",
    "title": "Orac and Medians",
    "statement": "Slime has a sequence of positive integers $a_1, a_2, \\ldots, a_n$.\n\nIn one operation Orac can choose an arbitrary subsegment $[l \\ldots r]$ of this sequence and replace all values $a_l, a_{l + 1}, \\ldots, a_r$ to the value of median of $\\{a_l, a_{l + 1}, \\ldots, a_r\\}$.\n\nIn this problem, for the integer multiset $s$, the median of $s$ is equal to the $\\lfloor \\frac{|s|+1}{2}\\rfloor$-th smallest number in it. For example, the median of $\\{1,4,4,6,5\\}$ is $4$, and the median of $\\{1,7,5,8\\}$ is $5$.\n\nSlime wants Orac to make $a_1 = a_2 = \\ldots = a_n = k$ using these operations.\n\nOrac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.",
    "tutorial": "Let $B_i=\\left\\{\\begin{aligned} 0,A_i<k\\\\1,A_i=k\\\\2,A_i>k\\end{aligned} \\right.$,then just consider whether it can be done to make all elements in $B$ become $1$ in a finite number of operations. It can be proved that a solution exists if and only if $\\exists 1\\le i\\le n,\\mathrm{s.t.}B_i=1$ and $\\exists 1\\le i<j\\le n,\\mathrm{s.t.}j-i\\le2,B_i>0,B_j>0$ . The necessity is obvious: if $\\forall 1\\le i\\le n, B_i\\neq 1$ , no elements in $B$ can be transformed into $1$; If there are at least two zeros between any two positive numbers, then the median of each interval equals to $0$, no solution exists. Consider the sufficiency. If there are two adjacent elements in $B$ both equals to $1$ , just select an interval which contains at least three elements and exact one element unequal to $1$ , and operate once on this interval. After this operation, there are still two adjacent elements in $B$ both equals to $1$, so we keep doing this until all elements are transformed into $1$. Therefore, if there is a interval $[l,r]$ which satisfies $r-l+1\\ge2$ and the median of $\\{B_l,B_{l+1},\\dots,B_r\\}$ equals to $1$, just perform an operation on $[l,r]$ , then use the above strategy. It can be shown that such an interval can always be created in several operations with the condition. If an interval $[i,i+2]$ satisfies $\\{B_i,B_{i+1},B_{i+2}\\}=\\{0,1,2\\}$ or $\\{1,1,2\\}$ or $\\{0,1,1\\}$ or $\\{1,1,1\\}$,just perform an operation on $[i,i+2]$ . If $[i,i+2]$ satisfies $\\{B_i,B_{i+1},B_{i+2}\\}=\\{1,2,2\\}$ , then $\\{B_i,B_{i+1}\\}=\\{1,2\\}$ or $\\{B_{i+1},B_{i+2}\\}=\\{1,2\\}$ . Perform an operation on $[i,i+1]$ or $[i+1,i+2]$ . If any interval with three elements doesn't satisfy the above conditions, because $\\exists 1\\le i<j\\le n,\\mathrm{s.t.}j-i\\le2,B_i>0,B_j>0$ ,there is an interval $[i,i+2]$ which satisfies $\\{B_i,B_{i+1},B_{i+2}\\}=\\{0,2,2\\}$ or $\\{2,2,2\\}$ . Take such an interval $[i,i+2]$ , perform an operation on $[i,i+2]$ first, then select an interval which contains at least three elements and exact one element unequal to $2$ until two adjacent numbers equals to $1$ and $2$ respectively. Perform one operation on these two adjacent elements. Therefore, the sufficiency is proved. So just check whether there is an element in $B$ equals to $1$, and whether there is a pair of two positive integers $(i,j)$ which satisfies $1\\le j-i\\le 2,B_i>0,B_j>0$ . The complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef pair<int,int> pii;\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\ntemplate <typename TYPE> inline void chkmax(TYPE &x,TYPE y){x<y?x=y:TYPE();}\ntemplate <typename TYPE> inline void chkmin(TYPE &x,TYPE y){y<x?x=y:TYPE();}\ntemplate <typename TYPE> void readint(TYPE &x)\n{\n    x=0;int f=1;char c;\n    for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-1;\n    for(;isdigit(c);c=getchar())x=x*10+c-'0';\n    x*=f;\n}\nconst int MAXN=500005;\n\nint n,k,a[MAXN];\nbool solve()\n{\n\treadint(n),readint(k);\n\tbool flag=0;\n\tfor(int i=1;i<=n;++i)\n\t{\n\t\treadint(a[i]);\n\t\tif(a[i]<k)a[i]=0;\n\t\telse if(a[i]>k)a[i]=2;\n\t\telse a[i]=1;\n\t\tif(a[i]==1)flag=1;\n\t}\n\tif(!flag)return 0;\n\tif(n==1)return 1;\n\tfor(int i=1;i<=n;++i)\n\t\tfor(int j=i+1;j<=n && j-i<=2;++j)\n\t\t\tif(a[i] && a[j])return 1;\n\treturn 0;\n}\n\nint main()\n{\n\tint T;\n\treadint(T);\n\twhile(T--)printf(solve()?\"yes\\n\":\"no\\n\");\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1349",
    "index": "C",
    "title": "Orac and Game of Life",
    "statement": "\\textbf{Please notice the unusual memory limit of this problem.}\n\nOrac likes games. Recently he came up with the new game, \"Game of Life\".\n\nYou should play this game on a black and white grid with $n$ rows and $m$ columns. Each cell is either black or white.\n\nFor each iteration of the game (the initial iteration is $0$), the color of each cell will change under the following rules:\n\n- If there are no adjacent cells with the same color as this cell on the current iteration, the color of it on the next iteration will be the same.\n- Otherwise, the color of the cell on the next iteration will be different.\n\nTwo cells are adjacent if they have a mutual edge.\n\nNow Orac has set an initial situation, and he wants to know for the cell $(i,j)$ (in $i$-th row and $j$-th column), what will be its color at the iteration $p$. He may ask you these questions several times.",
    "tutorial": "A cell $(i,j)$ is said to be good if and only if there is a cell $(i',j')$ adjacent to $(i,j)$ which has the same color to $(i,j)$ . If a cell $(i,j)$ is not good, it is said to be bad. Therefore, the color of a cell changes after a turn if and only if the cell is good. According to the definition, any cell never changes its color if every cell is bad. Also, a good cell $(i,j)$ would never turn into a bad cell . For a bad cell $(i,j)$, if there is a good cell $(i',j')$ adjacent to $(i,j)$, $(i,j)$ will turn into a good cell after a turn because $(i',j')$ currently has a different color from $(i,j)$ and the color of $(i',j')$ will change after a turn but the color of $(i,j)$ won't change; otherwise, after a turn, the color of $(i,j)$ and cells adjacent to $(i,j)$ stays the same, so $(i,j)$ is still bad. For a cell $(i,j)$, let $f_{i,j}$ be the number of turns needed for that $(i,j)$ becomes a good cell. According to the paragraph above, $f_{i,j}$ equals to the minimal Manhattan distance from $(i,j)$ to a good cell. Therefore, $f_{i,j}$ can be figured out by BFS. Notice that for $k \\le f_{i,j}$ , the color of $(i,j)$ stays the same after the $k$-th turn; for $k>f_{i,j}$ , the color of $(i,j)$ changes after the $k$-th turn. Therefore, each query can be processed with $O(1)$ time complexity. The total time complexity is $O(nm+t)$ . P.S. R.I.P. John Horton Conway, you are a great mathematician that should be remembered forever.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <algorithm>\n#define pii pair<int,int>\n#define mp make_pair\n#define fi first\n#define se second\n\nusing namespace std;\ntypedef long long ll;\nconst int MAXN = 1005;\ninline ll readint()\n{\n\tll res = 0, f = 1;\n\tchar c = 0;\n\twhile(!isdigit(c))\n\t{\n\t\tc = getchar();\n\t\tif(c=='-')\n\t\t\tf = -1;\n\t}\n\twhile(isdigit(c))\n\t\tres = res*10+c-'0', c = getchar();\n\treturn res*f;\n}\nint n,m,T,a[MAXN][MAXN];\nchar str[MAXN];\nint f[MAXN][MAXN],pos[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};\nbool vis[MAXN][MAXN];\ninline bool check(int x, int y)\n{\n\tfor(int i = 0; i<4; i++)\n\t{\n\t\tint nx = x+pos[i][0], ny = y+pos[i][1];\n\t\tif(a[nx][ny]==a[x][y])\n\t\t\treturn true;\t\n\t}\n\treturn false;\n}\npii q[MAXN*MAXN];\ninline void bfs()\n{\n\tint front = 0, rear = 0;\n\tfor(int i = 1; i<=n; i++)\n\t\tfor(int j = 1; j<=m; j++)\n\t\t\tif(check(i,j))\n\t\t\t\tf[i][j] = 0, vis[i][j] = true, q[rear++] = mp(i,j);\n\twhile(front<rear)\n\t{\n\t\tpii now = q[front++];\n\t\tfor(int i = 0; i<4; i++)\n\t\t{\n\t\t\tint nx = now.fi+pos[i][0], ny = now.se+pos[i][1];\n\t\t\tif(nx<1||nx>n||ny<1||ny>m||vis[nx][ny])\n\t\t\t\tcontinue;\n\t\t\tf[nx][ny] = f[now.fi][now.se]+1;\n\t\t\tvis[nx][ny] = true;\n\t\t\tq[rear++] = mp(nx,ny);\n\t\t}\n\t}\n}\n\nint main()\n{\n\tn = readint(), m = readint(), T = readint();\n\tmemset(a,-1,sizeof(a));\n\tfor(int i = 1; i<=n; i++)\n\t{\n\t\tscanf(\"%s\",str+1);\n\t\tfor(int j = 1;\tj<=m; j++) \n\t\t\ta[i][j] = str[j]-'0';\n\t}\n\tbfs();\n\tint x,y;\n\tll t;\n\twhile(T--)\n\t{\n\t\tx = readint(), y = readint(), t = readint();\n\t\tif(vis[x][y])\n\t\t\tprintf(\"%d\\n\",a[x][y]^(max(0ll,t-f[x][y])&1)); \n\t\telse\n\t\t\tprintf(\"%d\\n\",a[x][y]);\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1349",
    "index": "D",
    "title": "Slime and Biscuits",
    "statement": "Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play.\n\nAt the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \\ldots + a_n$ biscuits, and the owner of this biscuit will give it to a random uniform player among $n-1$ players except himself. The game stops when one person will have all the biscuits.\n\nAs the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time.\n\nFor convenience, as the answer can be represented as a rational number $\\frac{p}{q}$ for coprime $p$ and $q$, you need to find the value of $(p \\cdot q^{-1})\\mod 998\\,244\\,353$. You can prove that $q\\mod 998\\,244\\,353 \\neq 0$.",
    "tutorial": "Let $E_x$ be the sum of probability times time when the game end up with all biscuits are owned by the x-th person (At here, the sum of probability is not 1, though the sum of probability in all $E_x$ is 1). So the answer is $\\sum\\limits_{i=1}^nE_i$ Let $E'_x$ be the expectation of time when the game only ends when the x-th person own all the biscuits. Let $P_x$ be the probability that the game end up with all biscuits are owned by the x-th person. It's easy to find that $\\sum\\limits_{i=1}^n P_i = 1$. And we let constant $C$ be the expect time from when all biscuits are owned by i-th person to when all biscuits are owned by j-th person (now the end condition is that all biscuits are owned by j-th person, is the same with $E'_x$ . And for all (i, j), the value of $C$ is the same). So we have a identity: $E_x = E'_x-\\sum\\limits_{i=1}^n[i\\neq x]( P_i\\cdot C+E_i)$ We can get this by consider which people own all the biscuits when the game ends in all possible situation of $E'_x$ . Then we can get: $\\sum\\limits_{i=1}^n E_i=E'_x-C\\cdot \\sum\\limits_{i=1}^n[i\\neq x]P_i$ Sum it up for $x=1,2,\\cdots,n$ , and we get: $n\\sum\\limits_{i=1}^nE_i=\\sum\\limits_{i=1}^nE'_i-C(n-1)\\sum\\limits_{i=1}^nP_i$ Mention that $ans=\\sum\\limits_{i=1}^nE_i$ and $\\sum\\limits_{i=1}^nP_i=1$ , so we find that: $n\\cdot ans=\\sum\\limits_{i=1}^nE'_i-C(n-1)$ When we find the value of $E'_x$ and $C$ , we only want to know whether the biscuit is owned by the person we want or not, so we can let $f_m$ represent the expect time the person will own $m+1$ biscuits when the person own $m$ biscuits now. We can easily get $f_0$ and equation between $f_i$ and $f_{i-1}$ . So we can get all $f_m$ and $C$ in $O(\\sum\\limits_{i=1}^na_i \\cdot \\log\\ mod)$ time. And we can get the answer. The overall complexity is $O(\\sum\\limits_{i=1}^na_i \\cdot \\log\\ mod)$ .",
    "code": "#include<bits/stdc++.h>\n\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\n\ntemplate <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;}\ntemplate <typename T> bool chkmin(T &x,T y){return x>y?x=y,true:false;}\n\nint readint(){\n\tint x=0,f=1; char ch=getchar();\n\twhile(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}\n\twhile(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}\n\treturn x*f;\n}\n\nconst int cys=998244353;\nint n,m;\nll a[100005],ans[300005];\n\nll qpow(ll x,ll p){\n\tll ret=1;\n\tfor(;p;p>>=1,x=x*x%cys) if(p&1) ret=ret*x%cys;\n\treturn ret;\n}\n\nint main(){\n\tn=readint();\n\tfor(int i=1;i<=n;i++) a[i]=readint(),m+=a[i];\n\tll invm=qpow(m,cys-2),invn1=qpow(n-1,cys-2);\n\tfor(int i=m;i>=1;i--){\n\t\tll k1=i*invm%cys*invn1%cys,k2=(m-i)*invm%cys;\n\t\tans[i]=(k2*ans[i+1]+1)%cys*qpow(k1,cys-2)%cys;\n\t}\n\tfor(int i=1;i<=m;i++) ans[i]=(ans[i]+ans[i-1])%cys;\n\tll res=0;\n\tfor(int i=1;i<=n;i++) res=(res+ans[m-a[i]])%cys;\n\tres=(res+cys-ans[m]*(n-1)%cys)%cys;\n\tprintf(\"%lld\\n\",res*qpow(n,cys-2)%cys);\n\treturn 0;\n}",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1349",
    "index": "E",
    "title": "Slime and Hats",
    "statement": "Slime and Orac are holding a turn-based game. In a big room, there are $n$ players sitting on the chairs, looking forward to a column and each of them is given a number: player $1$ sits in the front of the column, player $2$ sits directly behind him; player $3$ sits directly behind player $2$, and so on; player $n$ sits directly behind player $n-1$. Each player wears a hat that is either black or white. As each player faces forward, player $i$ knows the color of player $j$'s hat if and only if $i$ is larger than $j$.\n\nAt the start of each turn, Orac will tell \\textbf{whether there exists a player wearing a black hat in the room}.\n\nAfter Orac speaks, if the player can uniquely identify the color of his hat, he will put his hat on the chair, stand up and leave the room. All players are smart, so if it is possible to understand the color of their hat using the obtained information during this and previous rounds, they will understand it.\n\nIn each turn, all players who know the color of their hats will leave at the same time in this turn, which means a player can only leave in the next turn if he gets to know the color of his hat only after someone left the room at this turn.\n\nNote that when the player needs to leave, he will put the hat on the chair before leaving, so the players ahead of him still cannot see his hat.\n\nThe $i$-th player will know who exactly left the room among players $1,2,\\ldots,i-1$, and how many players among $i+1,i+2,\\ldots,n$ have left the room.\n\nSlime stands outdoor. He watches the players walking out and records the numbers of the players and the time they get out. Unfortunately, Slime is so careless that he has only recorded some of the data, and this given data is in the format \"player $x$ leaves in the $y$-th round\".\n\nSlime asked you to tell him the color of each player's hat. If there are multiple solutions, you can find any of them.",
    "tutorial": "First, let's renumber the players for convenience. Number the player at the front as $n$ ,the player sitting behind him as $n-1$ , and so on. Let $c_i$ be the color of player $i$'s hat. Consider how to calculate ${t_i}$ if we have already known $c_1,c_2,\\dots,c_n$. If $c_1=c_2=\\dots=c_n=0$, then $t_1=t_2=\\dots=t_n=1$. Otherwise, let $x$ be the maximal number of a player with a black hat. In the first turn, player $1$ knows that someone wears a black hat. If $x=1$, player $1$ finds out that everyone except him wears a white hat, so he wears a black hat and he leaves. In the second turn, other players can figure out that $c_2=c_3=\\dots=c_n=0$. Therefore, $t_1=1,t_2=t_3=\\dots=t_n=2$. If $x\\ge 2$, there is a player with a black hat sitting in front of player $1$ , so he can't figure out the color of his own hat and doesn't leave. Other players know that $x\\ge 2$ in the next turn, and the problem is transformed into a subproblem on player $2,3,\\dots,n$. No one leaves until the $x$-th turn, player $x$ knows that there is at least one player with a black hat in $x,x+1,\\dots,n$, but player $x,x+1,\\dots,n$ all wear white hats, so he leaves. In the next turn, $x+1,x+2,\\dots,n$ leaves. According to the above process, player $x$ leaves in the $x$-th turn, player $x+1,x+2,\\dots,n$ leave in the $(x+1)$-th turn, and a new process begins. Therefore, we can figure out the value of $t_1,t_2,\\dots,t_n$. - If $c_i=1$ , then $t_i=\\sum\\limits_{j\\ge i,c_j=1}j$ . Let $b_i=i$ . - If $c_i=0$ , let $k$ be the maximal number which satisfies $c_k=1$ and $k<i$ , then $t_i=t_k+1$ . For convenience, let $c_0=1, t_0=\\sum\\limits_{c_j=1}j$ , so $k$ always exists. Let $b_i=k$. Therefore, we can calculate $t_1,t_2,\\dots,t_n$ using $c_1,c_2,\\dots c_n$, and $t_i=t_{b_i}+(1-c_i)$ is satisfied. Consider how to solve the original problem. Before using dynamic programming to solve the problem, we need to do some preparation for that. If $i\\ge j$ and $c_i=c_j=1$ , it is obviously that $t_i\\le t_j$. Also, if $t_i>t_j$, $b_i\\ge b_j$. Therefore, $\\forall i>j, t_i-t_j=t_{b_i}+(1-c_i)-t_{b_j}-(1-c_j)=t_{b_i}-t_{b_j}+(c_j-c_i)\\le c_j-c_i\\le 1$ $\\left\\{ \\begin{array}{lcl} t_i-t_j=1,\\space\\mathrm{if}\\space c_j=1\\ \\textrm{and}\\ \\forall i\\ge k>j,c_k=0 \\\\ t_i-t_j=0,\\space\\mathrm{if}\\space \\exists i>k>j,c_k=1,c_1=c_2=\\dots=c_{k-1}=c_{k+1}=\\dots=c_n=0\\ \\textrm{or}\\ \\forall i\\ge k\\ge j,c_k=0 \\\\ t_i-t_j<0,\\space\\mathrm{otherwise} \\end{array} \\right.$ Define a set of intervals $A=\\{[l_1,r_1],[l_2,r_2],\\dots,[l_m,r_m]\\}$ which satisfies these rules: $1\\le l_1\\le r_1<l_2\\le r_2<\\dots<l_m\\le r_m\\le n$ $\\forall 1\\le k\\le m, \\exists l_k\\le i\\le r_k$, $t_i$ is given. $\\forall 1\\le i\\le n$, if $t_i$ is given, $\\exists k, \\mathrm{s.t.}\\space l_k\\le i\\le r_k$ For all pairs $(i,j)$ where $i>j$ and $t_i,t_j$ are both given, $i$ and $j$ are in the same interval if and only if $t_i\\ge t_j$. If $l_i\\neq 1$, it can be known that $c_{l_i+1}=c_{l_i+2}=\\dots=c_{r_i}=0$ and $b_{l_i}=b_{l_i+1}=\\dots=b_{r_i}$. Let $B_i=b_{l_i}$. After the preparatory work, let's work on dp. Let $f_{i,j}$ be the maximal possible value of $B_i$ when $c_{l_i}=j$ . Consider how to calculate $f_{i,j'}$ if we know the value of $f_{i+1,0}$ and $f_{i+1,1}$ . For $f_{i+1,j}$, enumerate all possible $f_{i,j'}$ from large to small, $B_i=f_{i,j'}$ might be satisfied if $t_{f_{i,j'}}=\\sum\\limits_{k\\ge f_{i,j'},c_k=1}k=\\left(\\sum\\limits_{k\\ge f_{i+1,j},c_k=1}k\\right) + \\left(\\sum\\limits_{f_{i+1,j}>k\\ge f_{i,j'},c_k=1}k\\right) =t_{f_{i+1,j}}+f_{i,j'}+\\sum\\limits_{r_i<k<f_{i+1,j},c_j=1}k$ Besides $f_{i,j}$, record whether $f_{i,j}$ is transformed from $f_{i+1,0}$ or $f_{i+1,1}$. Using these we can easily give a solution. Notice that when $l_1=1$, $[l_1,r_1]$ doesn't satisfy $c_{l_1+1}=c_{l_1+2}=\\dots=c_{r_1}=0$ . However, there is at most one $i$ in $[l_1,r_1]$ where $c_i=1$. Just brute force which $c_i$ equals to $1$ is okay. The whole complexity is $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int,ll> pii;\n#define x first\n#define y second\n#define pb push_back\nconst int MAXN=200005;\n\nint n,m,cnt;\npii a[MAXN];\nbool avis[MAXN];\nstruct Range\n{\n\tint l,r,type;\n\tll val;\n\tRange(){}\n\tRange(int l,int r,int type,ll val):l(l),r(r),type(type),val(val){}\n}b[MAXN];\n\nint f[2][MAXN],wh[2][MAXN],res[MAXN];\nvector<int> str[2][MAXN];\nbool check(ll s,int l,int r)\n{\n\tif(s<=0)return !s && r-l+1>=0;\n\tll L=1,R=r-l+1,mid,ans=0;\n\twhile(L<=R)\n\t{\n\t\tmid=(L+R)>>1;\n\t\tif((l+l+mid-1)*mid<=s*2)ans=mid,L=mid+1;\n\t\telse R=mid-1;\n\t}\n\treturn s*2<=(r+r-ans+1)*ans;\n}\nvoid modify(ll s,int l,int r,vector<int> &tar,int start)\n{\n\tll L=1,R=r-l+1,mid,ans=0;\n\twhile(L<=R)\n\t{\n\t\tmid=(L+R)>>1;\n\t\tif((l+l+mid-1)*mid<=s*2)ans=mid,L=mid+1;\n\t\telse R=mid-1;\n\t}\n\tfor(int i=l;i<=r;i++)\n\t\tif(ans && (i+i+ans-2)*(ans-1)<=(s-i)*2 && (s-i)*2<=(r+r-ans+2)*(ans-1))\n\t\t\t{--ans,s-=i;tar.pb(1);}\n\t\telse tar.pb(0);\n}\nvoid update(int i,int ti,int ti_1,int pos,ll d)\n{\n\tif(pos<=f[ti][i])return;\n\tstr[ti][i].clear();\n\tf[ti][i]=pos;wh[ti][i]=ti_1;\n\tstr[ti][i].pb(1);\n\tfor(int j=f[ti][i]+1;j<=b[i].r;j++)str[ti][i].pb(0);\n\tmodify(d-f[ti][i],b[i].r+1,f[ti_1][i-1]-1,str[ti][i],f[ti][i]);\n}\n\nint main()\n{\n\t#ifndef ONLINE_JUDGE\n\t//freopen(\"code.in\",\"r\",stdin);\n\t//freopen(\"code.out\",\"w\",stdout);\n\t#endif\n\tscanf(\"%d\",&n);\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tll y;\n\t\tscanf(\"%lld\",&y);\n\t\tif(!y)continue;\n\t\ta[++m]=make_pair(n-i+1,y);\n\t\tavis[n-i+1]=1;\n\t}\n\tif(!m)\n\t{\n\t\tfor(int i=1;i<=n;i++)putchar('0');\n\t\treturn 0;\n\t}\n\tsort(a+1,a+m+1);\n\tb[cnt=1]=Range(a[m].x,a[m].x,2,a[m].y);\n\tfor(int i=m-1;i;i--)\n\t{\n\t\tif(a[i].y==a[i+1].y)b[cnt].l=a[i].x,b[cnt].type=0;\n\t\telse if(a[i].y==a[i+1].y-1)b[cnt].l=a[i].x,b[cnt].type=1,b[cnt].val--;\n\t\telse b[++cnt]=Range(a[i].x,a[i].x,2,a[i].y);\n\t}\n\tb[cnt+1]=Range(-1,-1,0,0);\n\tbool error=0;\n\tf[0][0]=-1;f[1][0]=n+1;\n\tfor(int i=1;i<=cnt;i++)\n\t{\n\t\tf[0][i]=f[1][i]=-1;\n\t\tfor(int t=0;t<=1;t++)\n\t\t\tif(f[t][i-1]>b[i].r)\n\t\t\t{\n\t\t\t\tif(b[i].type==0 || b[i].type==2)\n\t\t\t\t{\n\t\t\t\t\tll d=(b[i].val-1)-(b[i-1].val-1+t);\n\t\t\t\t\tint pos=-1;\n\t\t\t\t\tfor(int j=min(b[i].l-1ll,d);j>b[i+1].r;--j)\n\t\t\t\t\t\tif(check(d-j,b[i].r+1,f[t][i-1]-1)){pos=j;break;}\n\t\t\t\t\tupdate(i,0,t,pos,d);\n\t\t\t\t}\n\t\t\t\tif(b[i].type==1 || b[i].type==2)\n\t\t\t\t{\n\t\t\t\t\tll d=b[i].val-(b[i-1].val-1+t);\n\t\t\t\t\tif(check(d-b[i].l,b[i].r+1,f[t][i-1]-1))\n\t\t\t\t\t\tupdate(i,1,t,b[i].l,d);\n\t\t\t\t}\n\t\t\t}\n\t\tif(f[0][i]<0 && f[1][i]<0 && i==cnt && !b[i].type)error=1;\n\t}\n\tif(error)\n\t{\n\t\tfor(int t=0;t<=1;t++)\n\t\t\tif(f[t][cnt-1]>b[cnt].r)\n\t\t\t{\n\t\t\t\tll d=(b[cnt].val-1)-(b[cnt-1].val-1+t);\n\t\t\t\tint pos=-1;\n\t\t\t\tfor(int j=min((ll)b[cnt].r,d);j>=b[cnt].l;--j)\n\t\t\t\t{\n\t\t\t\t\tif(avis[j])continue;\n\t\t\t\t\tif(check(d-j,b[cnt].r+1,f[t][cnt-1]-1)){pos=j;break;}\n\t\t\t\t}\n\t\t\t\tupdate(cnt,0,t,pos,d);\n\t\t\t}\n\t}\n\tint cur=(f[1][cnt]>0);\n\tfor(int i=1;i<f[cur][cnt];i++)res[i]=0;\n\tfor(int i=cnt;i>0;i--)\n\t{\n\t\tfor(int j=0;j<(int)str[cur][i].size();j++)res[j+f[cur][i]]=str[cur][i][j];\n\t\tcur=wh[cur][i];\n\t}\n\tfor(int i=n;i>0;i--)putchar(res[i]+'0');\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1349",
    "index": "F1",
    "title": "Slime and Sequences (Easy Version)",
    "statement": "\\textbf{Note that the only differences between easy and hard versions are the constraints on $n$ and the time limit. You can make hacks only if all versions are solved.}\n\nSlime is interested in sequences. He defined \\textbf{good} positive integer sequences $p$ of length $n$ as follows:\n\n- For each $k>1$ that presents in $p$, there should be at least one pair of indices $i,j$, such that $1 \\leq i < j \\leq n$, $p_i = k - 1$ and $p_j = k$.\n\nFor the given integer $n$, the set of all good sequences of length $n$ is $s_n$. For the fixed integer $k$ and the sequence $p$, let $f_p(k)$ be the number of times that $k$ appears in $p$. For each $k$ from $1$ to $n$, Slime wants to know the following value:\n\n$$\\left(\\sum_{p\\in s_n} f_p(k)\\right)\\ \\textrm{mod}\\ 998\\,244\\,353$$",
    "tutorial": "First we can make a bijection between all the good sequences and permutations. Let a permutation of length $n$ be $a_1,a_2,\\cdots , a_n$ , and we fill '>' or '<' sign between each $a_i$ and $a_{i+1}$ , so the value of $p_{a_i}$ is the number of '<' sign between $a_1,a_2,\\cdots, a_i$ plus one, it's easy to proof that this is a correct bijection. Let $d_{i,j}$ be the number of permutations of length $i+1$ that have at least $j$ '<' signs in it. Then for each '<' sign, we can combine the places next to it, so for some combined places, there are only one way to put the numbers in it for a fix set of numbers. And we know that $d_{i,j}$ have $i-j+1$ sets of combined places, so the value of $d_{i,j}$ is the number of ways to assign $i+1$ numbers into $i-j+1$ different sets. From the EGF of the second kind of Stirling numbers, we know that $d_{i,j}=(i+1)![z^{i+1}](e^z-1)^{i-j+1}$ . We can also use DP that similar with the Stirling numbers to get all $d_{i,j}$ . When we find the answers, for each $1\\leq i\\leq n$ , we consider the contribution of each places, so for each $a_j$ , we need to find the number of permutations that have $i-1$ '<' signs before it. So we can get: $ans_{i+1}=\\sum\\limits_{x=0}^{n-1}\\sum\\limits_{y=i}^x (-1)^{y-i} {y\\choose i}d_{x,y}\\frac{n!}{(x+1)!}$ $=\\frac {n!}{i!}\\sum\\limits_{x=0}^{n-1}\\sum\\limits_{y=i}^x (-1)^{y-i}\\frac{y!d_{x,y}}{(y-i)!(x+1)!}$ $=\\frac{n!}{i!} \\sum\\limits_{y=i}^{n-1}\\frac{(-1)^{y-i}y!}{(y-i)!}\\sum\\limits_{x=y}^{n-1}\\frac{d_{x,y}}{(x+1)!}$ $=\\frac {n!}{i!}\\sum\\limits_{y=i}^{n-1} \\frac{(-1)^{y-i}y!}{(y-i)!} \\sum\\limits_{x=y}^{n-1}[z^{x+1}](e^z-1)^{x-y+1}$ If we can find $\\sum\\limits_{x=y}^{n-1}[z^{x+1}](e^z-1)^{x-y+1}$ for each $y$ , then we can find the answer in one convolution. And because of the simple $O(n^2)$ DP algorithm to find all $d_{x,y}$ , so we can get a $O(n^2)$ complexity to solve the problem, and it can pass the easy version (other forms of DP can also get to this time complexity, but now we only introduce the form that leads to the solution of the hard version).",
    "code": "#include<bits/stdc++.h>\n\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\n\ntemplate <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;}\ntemplate <typename T> bool chkmin(T &x,T y){return x>y?x=y,true:false;}\n\nint readint(){\n\tint x=0,f=1; char ch=getchar();\n\twhile(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}\n\twhile(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}\n\treturn x*f;\n}\n\nconst int cys=998244353;\nint n;\nll fac[5005],inv[5005],d[5005][5005],ans[5005];\n\nll qpow(ll x,ll p){\n\tll ret=1;\n\tfor(;p;p>>=1,x=x*x%cys) if(p&1) ret=ret*x%cys;\n\treturn ret;\n}\n\nint main(){\n\tn=readint();\n\td[0][0]=fac[0]=inv[0]=1;\n\tfor(int i=1;i<=n;i++) fac[i]=fac[i-1]*i%cys;\n\tinv[n]=qpow(fac[n],cys-2);\n\tfor(int i=n-1;i>=1;i--) inv[i]=inv[i+1]*(i+1)%cys;\n\tfor(int i=1;i<=n;i++) for(int j=1;j<=i;j++) d[i][j]=(d[i-1][j-1]*(i-j+1)+d[i-1][j]*j)%cys;\n\tfor(int i=1;i<=n;i++) for(int j=1;j<=n;j++) ans[i]=(ans[i]+d[j][i]*inv[j])%cys;\n\tfor(int i=1;i<=n;i++) printf(\"%lld \",ans[i]*fac[n]%cys);\n\tprintf(\"\\n\");\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "fft",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1349",
    "index": "F2",
    "title": "Slime and Sequences (Hard Version)",
    "statement": "\\textbf{Note that the only differences between easy and hard versions are the constraints on $n$ and the time limit. You can make hacks only if all versions are solved.}\n\nSlime is interested in sequences. He defined \\textbf{good} positive integer sequences $p$ of length $n$ as follows:\n\n- For each $k>1$ that presents in $p$, there should be at least one pair of indices $i,j$, such that $1 \\leq i < j \\leq n$, $p_i = k - 1$ and $p_j = k$.\n\nFor the given integer $n$, the set of all good sequences of length $n$ is $s_n$. For the fixed integer $k$ and the sequence $p$, let $f_p(k)$ be the number of times that $k$ appears in $p$. For each $k$ from $1$ to $n$, Slime wants to know the following value:\n\n$$\\left(\\sum_{p\\in s_n} f_p(k)\\right)\\ \\textrm{mod}\\ 998\\,244\\,353$$",
    "tutorial": "Now we consider how to get these values in less than $O(n^2)$ time. $\\sum\\limits_{x=y}^{n-1}[z^{x+1}](e^z-1)^{x-y+1}=\\sum\\limits_{x=y+1}^n[z^x](e^z-1)^{x-y}$ $=[z^y]\\sum\\limits_{x=y+1}^n(\\frac{e^z-1}z)^{x-y}=[z^y]\\sum\\limits_{x=1}^{n-y}(\\frac{e^z-1}z)^x$ Let $F=\\frac{e^z-1}z$ , so now we just want to find $[z^i]\\sum\\limits_{k=1}^{n-i}F^k$ for each $0\\leq i\\leq n-1$ . $[z^i]\\sum\\limits_{k=1}^{n-i}F^k =[z^i]\\frac 1{1-F}-[z^i]\\frac{F^{n-i+1}}{1-F}$ We can get the value of $[z^i]\\frac 1{1-F}$ in one polynomial inversion, now we only need to deal with the second one. $[z^i]\\frac{F^{n-i+1}}{1-F}=[z^{n+1}]\\frac{(zF)^{n-i+1}}{1-F}$ Let $w(z)=zF(z)$ , $\\phi(z)$ satisfies $\\frac{w(z)}{\\phi (w(z))}=z$ , so $\\frac{zF(z)}{\\phi (w(z))}=z$ , $F=\\phi (w)$ . $[z^{n+1}]\\frac{(zF)^{n-i+1}}{1-F}=[z^{n+1}u^{n-i+1}]\\sum\\limits_{k=0}^\\infty \\frac{(uzF)^k}{1-F}$ $=[z^{n+1}u^{n-i+1}] \\frac 1{1-\\phi (w)}\\frac 1{1-uw}$ And from the Lagrange Inversion $=[u^{n-i+1}]\\frac 1{n+1} [z^n] ((\\frac 1{1-\\phi z}\\frac 1{1-uz})'\\cdot \\phi (z)^{n+1})$ $=\\frac 1{n+1} [z^nu^{n-i+1}] (\\phi (z)^{n+1}\\frac{u+\\phi'(z)-u\\phi(z)-uz\\phi'(z)}{(1-\\phi (z))^2(1-uz)^2})$ $=\\frac 1{n+1} [z^nu^{n-i+1}] (\\phi(z)^{n+1}(\\frac {u}{(1-\\phi (z))(1-uz)^2}+\\frac {\\phi'(z)}{(1-\\phi (z))^2(1-uz)}))$ $=\\frac 1{n+1}[z^nu^{n-i+1}](\\phi (z)^{n+1}(\\frac 1{1-\\phi(z)}\\sum\\limits_{k=0}^\\infty (k+1)z^ku^{k+1}+\\frac{\\phi'(z)}{(1-\\phi (z))^2}\\sum\\limits_{k=0}^\\infty z^ku^k))$ $=\\frac 1{n+1}[z^n](\\phi (z)^{n+1}(\\frac{(n-i+1)z^{n-i}}{1-\\phi (z)}+\\frac{\\phi'(z)z^{n-i+1}}{(1-\\phi(z))^2}))$ $=\\frac 1{n+1}([z^i](\\phi(z)^{n+1}\\frac{n-i+1}{1-\\phi(z)})+[z^{i-1}](\\phi(z)^{n+1}\\frac{\\phi'(z)}{(1-\\phi(z))^2}))$ We can get $\\phi(z)^{n+1}\\frac{n-i+1}{1-\\phi(z)}$ and $\\phi(z)^{n+1}\\frac{\\phi'(z)}{(1-\\phi(z))^2}$ in $O(n\\log n)$ or $O(n\\log ^2n)$ time, and then get the answer. The overall complexity is $O(n\\log n)$ or $O(n\\log ^2n)$ . You can also view",
    "code": "#include<bits/stdc++.h>\n\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef vector<ll> vi;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\n\ntemplate <typename T> bool chkmax(T &x,T y){return x<y?x=y,true:false;}\ntemplate <typename T> bool chkmin(T &x,T y){return x>y?x=y,true:false;}\n\nint readint(){\n\tint x=0,f=1; char ch=getchar();\n\twhile(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}\n\twhile(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}\n\treturn x*f;\n}\n\nconst int cys=998244353,g=3,invg=(cys+1)/3;\nint n;\nll ni[200015],fac[200015],inv[200015],tw[200005];\n\nint mod(int x){return x>=cys?x-cys:x;}\n\nll qpow(ll x,ll p){\n\tll ret=1;\n\tfor(;p;p>>=1,x=x*x%cys) if(p&1) ret=ret*x%cys;\n\treturn ret;\n}\n\nvi operator+(vi a,vi b){\n\tvi ret(max(a.size(),b.size()));\n\tfor(int i=0;i<ret.size();i++) ret[i]=mod((i<a.size()?a[i]:0)+(i<b.size()?b[i]:0));\n\treturn ret;\n}\n\nvi operator-(vi a,vi b){\n\tvi ret(max(a.size(),b.size()));\n\tfor(int i=0;i<ret.size();i++) ret[i]=mod((i<a.size()?a[i]:0)+cys-(i<b.size()?b[i]:0));\n\treturn ret;\n}\n\nvi operator*(vi a,ll b){\n\tfor(int i=0;i<a.size();i++) a[i]=1ll*a[i]*b%cys;\n\treturn a;\n}\n\nvi operator>>(vi a,int b){\n\tfor(int i=0;i<a.size()-b;i++) a[i]=a[i+b];\n\ta.resize(a.size()-b);\n\treturn a;\n}\n\nnamespace poly{\n\tint N,l;\n\tint A[1100000],B[1100000],r[1100000],pre1[20][600000],pre2[20][600000];\n\tvoid pre(){\n\t\tfor(int i=1,r=0;i<(1<<19);i<<=1,r++){\n\t\t\tint w=1,wn=qpow(g,(cys-1)/(i<<1));\n\t\t\tfor(int j=0;j<i;j++,w=1ll*w*wn%cys) pre1[r][j]=w;\n\t\t}\n\t\tfor(int i=1,r=0;i<(1<<19);i<<=1,r++){\n\t\t\tint w=1,wn=qpow(invg,(cys-1)/(i<<1));\n\t\t\tfor(int j=0;j<i;j++,w=1ll*w*wn%cys) pre2[r][j]=w;\n\t\t}\n\t}\n\tvoid ntt(int *A,int N,int f){\n\t\tfor(int i=0;i<N;i++) if(i<r[i]) swap(A[i],A[r[i]]);\n\t\tfor(int i=1,r=0;i<N;i<<=1,r++){\n\t\t\tfor(int j=0;j<N;j+=(i<<1)){\n\t\t\t\tfor(int k=j;k<j+i;k++){\n\t\t\t\t\tint x=A[k],y=1ll*A[k+i]*(f>0?pre1[r][k-j]:pre2[r][k-j])%cys;\n\t\t\t\t\tA[k]=mod(x+y); A[k+i]=mod(x+cys-y);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(f<0){\n\t\t\tint invn=qpow(N,cys-2);\n\t\t\tfor(int i=0;i<N;i++) A[i]=1ll*A[i]*invn%cys;\n\t\t}\n\t}\n\tvoid init(int t){\n\t\tN=1,l=0;\n\t\tfor(;N<t;N<<=1) l++;\n\t\tfor(int i=0;i<N;i++) r[i]=(r[i>>1]>>1)|((i&1)<<(l-1));\n\t}\n\tvoid getmul(){\n\t\tntt(A,N,1); ntt(B,N,1);\n\t\tfor(int i=0;i<N;i++) A[i]=1ll*A[i]*B[i]%cys;\n\t\tntt(A,N,-1);\n\t}\n\tvi mul(vi a,vi b){\n\t\tinit(a.size()+b.size());\n\t\tfor(int i=0;i<N;i++) A[i]=i<a.size()?a[i]:0;\n\t\tfor(int i=0;i<N;i++) B[i]=i<b.size()?b[i]:0;\n\t\tgetmul();\n\t\tvi ret(a.size()+b.size()-1);\n\t\tfor(int i=0;i<ret.size();i++) ret[i]=A[i];\n\t\treturn ret;\n\t}\n\tvi polyinv(vi a,int l){\n\t\tif(l==1) return vi(1,qpow(a[0],cys-2));\n\t\ta.resize(l);\n\t\tvi b=polyinv(a,(l+1)/2);\n\t\tinit(l<<1);\n\t\tfor(int i=0;i<N;i++) A[i]=i<l?a[i]:0;\n\t\tfor(int i=0;i<N;i++) B[i]=i<(l+1)/2?b[i]:0;\n\t\tntt(A,N,1); ntt(B,N,1);\n\t\tfor(int i=0;i<N;i++) A[i]=1ll*A[i]*B[i]%cys*B[i]%cys;\n\t\tntt(A,N,-1);\n\t\tvi t=b*2;\n\t\tt.resize(l);\n\t\tfor(int i=0;i<l;i++) t[i]=mod(t[i]+cys-A[i]);\n\t\treturn t;\n\t}\n\tvi polydiff(vi a){\n\t\tfor(int i=0;i<a.size()-1;i++) a[i]=1ll*(i+1)*a[i+1]%cys;\n\t\ta.resize(a.size()-1);\n\t\treturn a;\n\t}\n\tvi polyint(vi a){\n\t\ta.resize(a.size()+1);\n\t\tfor(int i=a.size()-1;i>=1;i--) a[i]=1ll*a[i-1]*ni[i]%cys;\n\t\ta[0]=0;\n\t\treturn a;\n\t}\n\tvi polyln(vi a,int l){\n\t\treturn polyint(mul(polydiff(a),polyinv(a,l)));\n\t}\n\tvi polyexp(vi a,int l){\n\t\tif(l==1) return vi(1,1);\n\t\ta.resize(l);\n\t\tvi b=polyexp(a,(l+1)/2);\n\t\tinit(l<<1);\n\t\tvi t=mul(b,vi(1,1)-polyln(b,l)+a);\n\t\tt.resize(l);\n\t\treturn t;\n\t}\n\tvi polypow(vi a,int l,int k){\n\t\treturn polyexp(polyln(a,l)*k,l);\n\t}\n}\n\nvi getans(){\n\tvi f(0);\n\tfor(int i=0;i<=n+1;i++) f.push_back(inv[i+1]);\n\tvi tmp=poly::mul(f,poly::polyinv((vi(1,1)-f)>>1,n+1));\n\tvi tw(0); tw.resize(n);\n\tfor(int i=0;i<n;i++) tw[i]=tmp[i+1];\n\tvi h(0);\n\th.push_back(1),h.push_back(1);\n\th=poly::polyinv(poly::polyln(h,n+3)>>1,n+2);\n\tvi g=poly::polyinv((vi(1,1)-h)>>1,n+1);\n\tvi ph=poly::polypow(h,n+1,n+1);\n\tvi t1=poly::mul(g,ph);\n\tvi tmp1=poly::mul(poly::polydiff(h),ph);\n\ttmp1.resize(n+1);\n\tvi tmp2=poly::mul(g,g);\n\ttmp2.resize(n+1);\n\tvi t2=poly::mul(tmp1,tmp2);\n\tfor(int i=0;i<n;i++) tw[i]=mod(tw[i]+cys-ni[n+1]*mod(t1[i+1]*(n-i+1)%cys+t2[i+1])%cys);\n\tfor(int i=0;i<n;i++) tw[i]=tw[i]*fac[i]%cys;\n\treverse(tw.begin(),tw.end());\n\ttmp.clear();\n\tfor(int i=0;i<n;i++) tmp.push_back(i&1?cys-inv[i]:inv[i]);\n\ttw=poly::mul(tw,tmp);\n\ttw.resize(n);\n\treverse(tw.begin(),tw.end());\n\treturn tw;\n}\n\nint main(){\n\tpoly::pre();\n\tn=readint();\n\tfac[0]=inv[0]=1;\n\tfor(int i=1;i<=n+5;i++) fac[i]=fac[i-1]*i%cys;\n\tinv[n+5]=qpow(fac[n+5],cys-2);\n\tfor(int i=n+4;i>=1;i--) inv[i]=inv[i+1]*(i+1)%cys;\n\tfor(int i=1;i<=n+5;i++) ni[i]=inv[i]*fac[i-1]%cys;\n\tvi res=getans();\n\tfor(int i=0;i<n;i++) printf(\"%lld \",res[i]*fac[n]%cys*inv[i]%cys);\n\tprintf(\"\\n\");\n\treturn 0;\n}",
    "tags": [
      "dp",
      "fft",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1350",
    "index": "A",
    "title": "Orac and Factors",
    "statement": "Orac is studying number theory, and he is interested in the properties of divisors.\n\nFor two positive integers $a$ and $b$, $a$ is a divisor of $b$ if and only if there exists an integer $c$, such that $a\\cdot c=b$.\n\nFor $n \\ge 2$, we will denote as $f(n)$ the smallest positive divisor of $n$, except $1$.\n\nFor example, $f(7)=7,f(10)=2,f(35)=5$.\n\nFor the fixed integer $n$, Orac decided to add $f(n)$ to $n$.\n\nFor example, if he had an integer $n=5$, the new value of $n$ will be equal to $10$. And if he had an integer $n=6$, $n$ will be changed to $8$.\n\nOrac loved it so much, so he decided to repeat this operation several times.\n\nNow, for two positive integers $n$ and $k$, Orac asked you to add $f(n)$ to $n$ exactly $k$ times (note that $n$ will change after each operation, so $f(n)$ may change too) and tell him the final value of $n$.\n\nFor example, if Orac gives you $n=5$ and $k=2$, at first you should add $f(5)=5$ to $n=5$, so your new value of $n$ will be equal to $n=10$, after that, you should add $f(10)=2$ to $10$, so your new (and the final!) value of $n$ will be equal to $12$.\n\nOrac may ask you these queries many times.",
    "tutorial": "If we simulate the whole process we will get TLE because $k$ is too large. So we need some trivial observations: If $n$ is even, then for each operation $n$ will be added by $2$ and keep being even. If $n$ is odd, then for the first time $n$ will be added by an odd number and then become even. So it's easy to see that the answer is $\\left\\{ \\begin{array}{lcl} n+2k & n\\textrm{ is even}\\\\ n+2(k-1)+d(n) & n\\textrm{ is odd}\\\\ \\end{array} \\right.$ The overall complexity is $O(n)$ .",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n\tint T;\n\tcin >> T;\n\twhile(T--)\n\t{\n\t\tint n,k;\n\t\tcin >> n >> k;\n\t\tif(n%2==0)\n\t\t{\n\t\t\tcout << n+2*k << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tint p = 0;\n\t\tfor(int i = n; i>=2; i--)\n\t\t\tif(n%i==0)\n\t\t    \tp = i;\n\t\tcout << n+p+2*(k-1) << endl;\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1350",
    "index": "B",
    "title": "Orac and Models",
    "statement": "There are $n$ models in the shop numbered from $1$ to $n$, with sizes $s_1, s_2, \\ldots, s_n$.\n\nOrac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).\n\nOrac thinks that the obtained arrangement is \\textbf{beatiful}, if for any two adjacent models with indices $i_j$ and $i_{j+1}$ (note that $i_j < i_{j+1}$, because Orac arranged them properly), $i_{j+1}$ is divisible by $i_j$ and $s_{i_j} < s_{i_{j+1}}$.\n\nFor example, for $6$ models with sizes $\\{3, 6, 7, 7, 7, 7\\}$, he can buy models with indices $1$, $2$, and $6$, and the obtained arrangement will be beautiful. Also, note that the arrangement with exactly one model is also considered beautiful.\n\nOrac wants to know the maximum number of models that he can buy, and he may ask you these queries many times.",
    "tutorial": "Considering DP, we can design DP statuses as follow: $f_i$ stands for the length of the longest beautiful sequence end up with index $i$. We can find the transformation easily: $f_i = \\max\\limits_{j\\mid i, s_j<s_i} \\{f_j + 1\\}$ Then, the length of answer sequence is the maximum value among $f_1,f_2,\\cdots,f_n$. About the complexity of DP: If you transform by iterating multiples, it will be $O(n\\log n)$ (According to properties of Harmonic Series); if you iterate divisors, then it will be $O(n\\sqrt n)$. Fortunately, both of them are acceptable in this problem.",
    "code": "#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <cstring>\n#include <algorithm>\n\nusing namespace std;\nconst int MAXN = 500005;\ninline int readint()\n{\n\tint res = 0;\n\tchar c = 0;\n\twhile(!isdigit(c))\n\t\tc = getchar();\n\twhile(isdigit(c))\n\t\tres = res*10+c-'0', c = getchar();\n\treturn res;\t\n}\nint n,a[MAXN],f[MAXN];\n\nint main()\n{\n\tint T = readint();\n\twhile(T--)\n\t{\n\t\tn = readint();\n\t\tfor(int i = 1; i<=n; i++)\n\t\t\ta[i] = readint();\n\t\tfor(int i = 1; i<=n; i++)\n\t\t\tf[i] = 1;\n\t\tfor(int i = 1; i<=n; i++) \n\t\t\tfor(int j = i*2; j<=n; j += i)\n\t\t\t\tif(a[i]<a[j])\n\t\t\t\t\tf[j] = max(f[j],f[i]+1);\n\t\tint ans = 0;\n\t\tfor(int i = 1; i<=n; i++)\n\t\t\tans = max(ans,f[i]);\n\t\tcout << ans << endl;\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1352",
    "index": "A",
    "title": "Sum of Round Numbers",
    "statement": "A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $1$ to $9$ (inclusive) are round.\n\nFor example, the following numbers are round: $4000$, $1$, $9$, $800$, $90$. The following numbers are \\textbf{not} round: $110$, $707$, $222$, $1001$.\n\nYou are given a positive integer $n$ ($1 \\le n \\le 10^4$). Represent the number $n$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $n$ as a sum of the least number of terms, each of which is a round number.",
    "tutorial": "Firstly, we need to understand the minimum amount of round numbers we need to represent $n$. It equals the number of non-zero digits in $n$. Why? Because we can \"remove\" exactly one non-zero digit in $n$ using exactly one round number (so we need at most this amount of round numbers) and, on the other hand, the sum of two round numbers has at most two non-zero digits (the sum of three round numbers has at most three non-zero digits and so on) so this is useless to try to remove more than one digit using the sum of several round numbers. So we need to find all digits of $n$ and print the required number for each of these digits. For example, if $n=103$ then $n=1 \\cdot 10^2 + 0 \\cdot 10^1 + 3 \\cdot 10^0$, so we need two round numbers: $1 \\cdot 10^2$ and $3 \\cdot 10^0$. Because the last digit of $n$ is $n \\% 10$ (the remainder of $n$ modulo $10$) and we can remove the last digit of the number by integer division on $10$, we can use the following code to solve the problem:",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> ans;\n\t\tint power = 1;\n\t\twhile (n > 0) {\n\t\t\tif (n % 10 > 0) {\n\t\t\t\tans.push_back((n % 10) * power);\n\t\t\t}\n\t\t\tn /= 10;\n\t\t\tpower *= 10;\n\t\t}\n\t\tcout << ans.size() << endl;\n\t\tfor (auto number : ans) cout << number << \" \";\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1352",
    "index": "B",
    "title": "Same Parity Summands",
    "statement": "You are given two positive integers $n$ ($1 \\le n \\le 10^9$) and $k$ ($1 \\le k \\le 100$). Represent the number $n$ as the sum of $k$ positive integers of the same parity (have the same remainder when divided by $2$).\n\nIn other words, find $a_1, a_2, \\ldots, a_k$ such that all $a_i>0$, $n = a_1 + a_2 + \\ldots + a_k$ and either all $a_i$ are even or all $a_i$ are odd at the same time.\n\nIf such a representation does not exist, then report it.",
    "tutorial": "Consider two cases: when we choose all odd numbers and all even numbers. In both cases let's try to maximize the maximum. So, if we choose odd numbers, let's try to take $k-1$ ones and the remainder $n-(k-1)$. But we need to sure that $n-k+1$ is greater than zero and odd. And in case of even numbers, let's try to take $k-1$ twos and the remainder $n-2(k-1)$. We also need to check that the remainder is greater than zero and even. If none of these cases is true, print \"NO\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tint n1 = n - (k - 1);\n\t\tif (n1 > 0 && n1 % 2 == 1) {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tfor (int i = 0; i < k - 1; ++i) cout << \"1 \";\n\t\t\tcout << n1 << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tint n2 = n - 2 * (k - 1);\n\t\tif (n2 > 0 && n2 % 2 == 0) {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tfor (int i = 0; i < k - 1; ++i) cout << \"2 \";\n\t\t\tcout << n2 << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tcout << \"NO\" << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1352",
    "index": "C",
    "title": "K-th Not Divisible by n",
    "statement": "You are given two positive integers $n$ and $k$. Print the $k$-th positive integer that is not divisible by $n$.\n\nFor example, if $n=3$, and $k=7$, then all numbers that are not divisible by $3$ are: $1, 2, 4, 5, 7, 8, 10, 11, 13 \\dots$. The $7$-th number among them is $10$.",
    "tutorial": "Suppose the answer is just $k$-th positive integer which we should \"shift right\" by some number. Each multiplier of $n$ shifts our answer by $1$. The number of such multipliers is $need = \\lfloor\\frac{k-1}{n-1}\\rfloor$, where $\\lfloor \\frac{x}{y} \\rfloor$ is $x$ divided by $y$ rounded down. So the final answer is $k + need$ ($k$-th positive integer with the required number of skipped integers multipliers of $n$). You can also use a binary search to solve this problem :)",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tint need = (k - 1) / (n - 1);\n\t\tcout << k + need << endl;\n\t}\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1352",
    "index": "D",
    "title": "Alice, Bob and Candies",
    "statement": "There are $n$ candies in a row, they are numbered from left to right from $1$ to $n$. The size of the $i$-th candy is $a_i$.\n\nAlice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy \\textbf{from left to right}, and Bob — \\textbf{from right to left}. The game ends if all the candies are eaten.\n\nThe process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).\n\nAlice makes the first move. During the first move, she will eat $1$ candy (its size is $a_1$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.\n\nOn each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is \\textbf{strictly greater} than the sum of the sizes of candies that the other player ate on the \\textbf{previous} move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.\n\nFor example, if $n=11$ and $a=[3,1,4,1,5,9,2,6,5,3,5]$, then:\n\n- move 1: Alice eats one candy of size $3$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3,5]$.\n- move 2: Alice ate $3$ on the previous move, which means Bob must eat $4$ or more. Bob eats one candy of size $5$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3]$.\n- move 3: Bob ate $5$ on the previous move, which means Alice must eat $6$ or more. Alice eats three candies with the total size of $1+4+1=6$ and the sequence of candies becomes $[5,9,2,6,5,3]$.\n- move 4: Alice ate $6$ on the previous move, which means Bob must eat $7$ or more. Bob eats two candies with the total size of $3+5=8$ and the sequence of candies becomes $[5,9,2,6]$.\n- move 5: Bob ate $8$ on the previous move, which means Alice must eat $9$ or more. Alice eats two candies with the total size of $5+9=14$ and the sequence of candies becomes $[2,6]$.\n- move 6 (the last): Alice ate $14$ on the previous move, which means Bob must eat $15$ or more. It is impossible, so Bob eats the two remaining candies and the game ends.\n\nPrint the number of moves in the game and two numbers:\n\n- $a$ — the total size of all sweets eaten by Alice during the game;\n- $b$ — the total size of all sweets eaten by Bob during the game.",
    "tutorial": "This is just an implementation problem and it can be solved in $O(n)$ time but we didn't ask for such solutions so you could solve it in $O(n^2)$ or maybe even in $O(n^2 log n)$. I'll describe $O(n)$ solution anyway. Firstly, we need to maintain several variables: $cnt$ (initially $0$, the number of moves passed), $l$ (the position of the leftmost remaining candy, initially $0$), $r$ (the position of the rightmost remaining candy, initially $n-1$), $ansl$ (the sum of candies eaten by Alice, initially $0$), $ansr$ (the sum of candied eaten by Bob, initially $0$), $suml$ (the sum of candies eaten by Alice during her last move, initially $0$) and $sumr$ (the sum of candies eaten by Bob during his last move, initially $0$). So, let's just simulate the following process while $l \\le r$: if the number of moves $cnt$ is even then now is Alice's move and we need to maintain one more variable $nsuml = 0$ - the sum of candies Alice eats during this move. How to calculate it? While $l \\le r$ and $nsuml \\le sumr$, let's eat the leftmost candy, so variables will change like this: $nsuml := nsuml + a_l, l := l + 1$. After all, let's add $nsuml$ to $ansl$, replace $suml$ with $nsuml$ (assign $suml := nsuml$) and increase $cnt$ by $1$. If the number of moves $cnt$ is odd then the process is the same but from the Bob's side. I'll also add a simply implemented $O(n^2)$ solution written by Gassa below :)",
    "code": "// Author: Ivan Kazmenko (gassa@mail.ru)\nimport std.algorithm;\nimport std.conv;\nimport std.range;\nimport std.stdio;\nimport std.string;\n\nvoid main ()\n{\n\tauto tests = readln.strip.to !(int);\n\tforeach (test; 0..tests)\n\t{\n\t\tauto n = readln.strip.to !(int);\n\t\tauto a = readln.splitter.map !(to !(int)).array;\n\t\tint [2] total;\n\t\tint prev = 0;\n\t\tint moves = 0;\n\t\twhile (!a.empty)\n\t\t{\n\t\t\tmoves += 1;\n\t\t\tint cur = 0;\n\t\t\twhile (!a.empty && cur <= prev)\n\t\t\t{\n\t\t\t\tcur += a[0];\n\t\t\t\ta = a[1..$];\n\t\t\t}\n\t\t\ttotal[moves % 2] += cur;\n\t\t\tprev = cur;\n\t\t\treverse (a);\n\t\t}\n\t\twriteln (moves, \" \", total[1], \" \", total[0]);\n\t}\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1352",
    "index": "E",
    "title": "Special Elements",
    "statement": "Pay attention to the non-standard memory limit in this problem.\n\nIn order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.\n\nThe array $a=[a_1, a_2, \\ldots, a_n]$ ($1 \\le a_i \\le n$) is given. Its element $a_i$ is called special if there exists a pair of indices $l$ and $r$ ($1 \\le l < r \\le n$) such that $a_i = a_l + a_{l+1} + \\ldots + a_r$. In other words, an element is called special if it can be represented as the sum of \\textbf{two or more consecutive elements} of an array (no matter if they are special or not).\n\nPrint the number of special elements of the given array $a$.\n\nFor example, if $n=9$ and $a=[3,1,4,1,5,9,2,6,5]$, then the answer is $5$:\n\n- $a_3=4$ is a special element, since $a_3=4=a_1+a_2=3+1$;\n- $a_5=5$ is a special element, since $a_5=5=a_2+a_3=1+4$;\n- $a_6=9$ is a special element, since $a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$;\n- $a_8=6$ is a special element, since $a_8=6=a_2+a_3+a_4=1+4+1$;\n- $a_9=5$ is a special element, since $a_9=5=a_2+a_3=1+4$.\n\nPlease note that some of the elements of the array $a$ may be equal — if several elements are equal and special, then all of them should be counted in the answer.",
    "tutorial": "The intended solution for this problem uses $O(n^2)$ time and $O(n)$ memory. Firstly, let's calculate $cnt_i$ for each $i$ from $1$ to $n$, where $cnt_i$ is the number of occurrences of $i$ in $a$. This part can be done in $O(n)$. Then let's iterate over all segments of $a$ of length at least $2$ maintaining the sum of the current segment $sum$. We can notice that we don't need sums greater than $n$ because all elements do not exceed $n$. So if the current sum does not exceed $n$ then add $cnt_{sum}$ to the answer and set $cnt_{sum} := 0$ to prevent counting the same elements several times. This part can be done in $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tvector<int> cnt(n + 1);\n\t\tint ans = 0;\n\t\tfor (auto &it : a) {\n\t\t\tcin >> it;\n\t\t\t++cnt[it];\n\t\t}\n\t\tfor (int l = 0; l < n; ++l) {\n\t\t\tint sum = 0;\n\t\t\tfor (int r = l; r < n; ++r) {\n\t\t\t\tsum += a[r];\n\t\t\t\tif (l == r) continue;\n\t\t\t\tif (sum <= n) {\n\t\t\t\t\tans += cnt[sum];\n\t\t\t\t\tcnt[sum] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n}",
    "tags": [
      "brute force",
      "implementation",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1352",
    "index": "F",
    "title": "Binary String Reconstruction",
    "statement": "For some binary string $s$ (i.e. each character $s_i$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $2$ were written. For each pair (substring of length $2$), the number of '1' (ones) in it was calculated.\n\nYou are given three numbers:\n\n- $n_0$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $0$;\n- $n_1$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $1$;\n- $n_2$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $2$.\n\nFor example, for the string $s=$\"1110011110\", the following substrings would be written: \"11\", \"11\", \"10\", \"00\", \"01\", \"11\", \"11\", \"11\", \"10\". Thus, $n_0=1$, $n_1=3$, $n_2=5$.\n\nYour task is to restore \\textbf{any} suitable binary string $s$ from the given values $n_0, n_1, n_2$. It is guaranteed that at least one of the numbers $n_0, n_1, n_2$ is greater than $0$. Also, it is guaranteed that a solution exists.",
    "tutorial": "Consider case $n_1 = 0$ separately and print the sting of $n_0 + 1$ zeros or $n_2 + 1$ ones correspondingly. Now our string has at least one pair \"10\" or \"01\". Let's form the pattern \"101010 ... 10\" of length $n_1 + 1$. So, all substrings with the sum $1$ are satisfied. Now let's insert $n_0$ zeros before the first zero, in this way we satisfy the substrings with the sum $0$. And then just insert $n_2$ ones before the first one, in this way we satisfy the substrings with the sum $2$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n0, n1, n2;\n\t\tcin >> n0 >> n1 >> n2;\n\t\tif (n1 == 0) {\n\t\t\tif (n0 != 0) {\n\t\t\t\tcout << string(n0 + 1, '0') << endl;\n\t\t\t} else {\n\t\t\t\tcout << string(n2 + 1, '1') << endl;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tstring ans;\n\t\tfor (int i = 0; i < n1 + 1; ++i) {\n\t\t\tif (i & 1) ans += \"0\";\n\t\t\telse ans += \"1\";\n\t\t}\n\t\tans.insert(1, string(n0, '0'));\n\t\tans.insert(0, string(n2, '1'));\n\t\tcout << ans << endl;\n\t}\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1352",
    "index": "G",
    "title": "Special Permutation",
    "statement": "A permutation of length $n$ is an array $p=[p_1,p_2,\\dots,p_n]$, which contains every integer from $1$ to $n$ (inclusive) and, moreover, each number appears exactly once. For example, $p=[3,1,4,2,5]$ is a permutation of length $5$.\n\nFor a given number $n$ ($n \\ge 2$), find a permutation $p$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $2$ and $4$, inclusive. Formally, find such permutation $p$ that $2 \\le |p_i - p_{i+1}| \\le 4$ for each $i$ ($1 \\le i < n$).\n\nPrint any such permutation for the given integer $n$ or determine that it does not exist.",
    "tutorial": "If $n < 4$ then there is no answer. You can do some handwork to be sure. Otherwise, the answer exists and there is one simple way to construct it: firstly, let's put all odd integers into the answer in decreasing order, then put $4$, $2$, and all other even numbers in increasing order. To test that it always works, you can run some kind of checker locally (you can check all $1000$ tests very fast, in less than one second, this may be very helpful sometimes).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tif (n < 4) {\n\t\t\tcout << -1 << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (int i = n; i >= 1; --i) {\n\t\t\tif (i & 1) cout << i << \" \";\n\t\t}\n\t\tcout << 4 << \" \" << 2 << \" \";\n\t\tfor (int i = 6; i <= n; i += 2) {\n\t\t\tcout << i << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1353",
    "index": "A",
    "title": "Most Unstable Array",
    "statement": "You are given two integers $n$ and $m$. You have to construct the array $a$ of length $n$ consisting of \\textbf{non-negative integers} (i.e. integers greater than or equal to zero) such that the sum of elements of this array is \\textbf{exactly} $m$ and the value $\\sum\\limits_{i=1}^{n-1} |a_i - a_{i+1}|$ is the maximum possible. Recall that $|x|$ is the absolute value of $x$.\n\nIn other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $a=[1, 3, 2, 5, 5, 0]$ then the value above for this array is $|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$. Note that this example \\textbf{doesn't show the optimal answer} but it shows how the required value for some array is calculated.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If $n=1$ then the answer is $0$. Otherwise, the best way is to construct the array $[0, m, 0, \\dots, 0]$. For $n=2$ we can't reach answer more than $m$ and for $n > 2$ we can't reach the answer more than $2m$ because each unit can't be used more than twice. So the answer can be represented as $min(2, n - 1) \\cdot m$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tcout << min(2, n - 1) * m << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1353",
    "index": "B",
    "title": "Two Arrays And Swaps",
    "statement": "You are given two arrays $a$ and $b$ both consisting of $n$ positive (greater than zero) integers. You are also given an integer $k$.\n\nIn one move, you can choose two indices $i$ and $j$ ($1 \\le i, j \\le n$) and swap $a_i$ and $b_j$ (i.e. $a_i$ becomes $b_j$ and vice versa). Note that $i$ and $j$ can be equal or different (in particular, swap $a_2$ with $b_2$ or swap $a_3$ and $b_9$ both are acceptable moves).\n\nYour task is to find the \\textbf{maximum} possible sum you can obtain in the array $a$ if you can do no more than (i.e. at most) $k$ such moves (swaps).\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Each move we can choose the minimum element in $a$, the maximum element in $b$ and swap them (if the minimum in $a$ is less than maximum in $b$). If we repeat this operation $k$ times, we get the answer. This can be done in $O(n^3)$, $O(n^2)$ but authors solution is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tvector<int> b(n);\n\t\tfor (auto &it : b) cin >> it;\n\t\tsort(a.begin(), a.end());\n\t\tsort(b.rbegin(), b.rend());\n\t\tint ans = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (i < k) ans += max(a[i], b[i]);\n\t\t\telse ans += a[i];\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1353",
    "index": "C",
    "title": "Board Moves",
    "statement": "You are given a board of size $n \\times n$, where $n$ is \\textbf{odd} (not divisible by $2$). Initially, each cell of the board contains one figure.\n\nIn one move, you can select \\textbf{exactly one figure} presented in some cell and move it to one of the cells \\textbf{sharing a side or a corner with the current cell}, i.e. from the cell $(i, j)$ you can move the figure to cells:\n\n- $(i - 1, j - 1)$;\n- $(i - 1, j)$;\n- $(i - 1, j + 1)$;\n- $(i, j - 1)$;\n- $(i, j + 1)$;\n- $(i + 1, j - 1)$;\n- $(i + 1, j)$;\n- $(i + 1, j + 1)$;\n\nOf course, you \\textbf{can not} move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.\n\nYour task is to find the minimum number of moves needed to get \\textbf{all the figures} into \\textbf{one} cell (i.e. $n^2-1$ cells should contain $0$ figures and one cell should contain $n^2$ figures).\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "It is intuitive (and provable) that the best strategy is to move each figure to the center cell $(\\frac{n+1}{2}, \\frac{n+1}{2})$. Now, with some paperwork or easy observations, we can notice that we have exactly $8$ cells with the shortest distance $1$, $16$ cells with the shortest distance $2$, $24$ cells with the shortest distance $3$ and so on. So we have $8i$ cells with the shortest distance $i$. So the answer is $1 \\cdot 8 + 2 \\cdot 16 + 3 \\cdot 24 + \\dots + (\\frac{n-1}{2})^2 \\cdot 8$. It can be rewritten as $8 (1 + 4 + 9 + \\dots + (\\frac{n-1}{2})^2)$ so we can just calculate the sum of squares of all integers from $1$ to $\\frac{n-1}{2}$ using loop (or formula $\\frac{n(n+1)(2n+1)}{6}$) and multiply the answer by $8$. Time complexity: $O(n)$ or $O(1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tlong long ans = 0;\n\t\tfor (int i = 1; i <= n / 2; ++i) {\n\t\t\tans += i * 1ll * i;\n\t\t}\n\t\tcout << ans * 8 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1353",
    "index": "D",
    "title": "Constructing the Array",
    "statement": "You are given an array $a$ of length $n$ consisting of zeros. You perform $n$ actions with this array: during the $i$-th action, the following sequence of operations appears:\n\n- Choose the maximum by length subarray (\\textbf{continuous subsegment}) consisting \\textbf{only} of zeros, among all such segments choose the \\textbf{leftmost} one;\n- Let this segment be $[l; r]$. If $r-l+1$ is odd (not divisible by $2$) then assign (set) $a[\\frac{l+r}{2}] := i$ (where $i$ is the number of the current action), otherwise (if $r-l+1$ is even) assign (set) $a[\\frac{l+r-1}{2}] := i$.\n\nConsider the array $a$ of length $5$ (initially $a=[0, 0, 0, 0, 0]$). Then it changes as follows:\n\n- Firstly, we choose the segment $[1; 5]$ and assign $a[3] := 1$, so $a$ becomes $[0, 0, 1, 0, 0]$;\n- then we choose the segment $[1; 2]$ and assign $a[1] := 2$, so $a$ becomes $[2, 0, 1, 0, 0]$;\n- then we choose the segment $[4; 5]$ and assign $a[4] := 3$, so $a$ becomes $[2, 0, 1, 3, 0]$;\n- then we choose the segment $[2; 2]$ and assign $a[2] := 4$, so $a$ becomes $[2, 4, 1, 3, 0]$;\n- and at last we choose the segment $[5; 5]$ and assign $a[5] := 5$, so $a$ becomes $[2, 4, 1, 3, 5]$.\n\nYour task is to find the array $a$ of length $n$ after performing all $n$ actions. \\textbf{Note that the answer exists and unique}.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "This is just an implementation problem. We can use some kind of heap or ordered set to store all segments we need in order we need. To solve this problem on C++ with std::set, we can just rewrite the comparator for std::set like this: And then just write the std::set like this: Now the minimum element of the set will be the segment that we need to choose. Initially, the set will contain only one segment $[0;n-1]$. Suppose we choose the segment $[l; r]$ during the $i$-th action. Let $id = \\lfloor\\frac{l+r}{2}\\rfloor$, where $\\lfloor\\frac{x}{y}\\rfloor$ is $x$ divided by $y$ rounded down. Assign (set) $a[id] := i$, then if the segment $[l; id-1]$ has positive (greater than zero) length, push this segment to the set and the same with the segment $[id+1;r]$. After $n$ such actions we get the answer. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct cmp {\n\tbool operator() (const pair<int, int> &a, const pair<int, int> &b) const {\n\t\tint lena = a.second - a.first + 1;\n\t\tint lenb = b.second - b.first + 1;\n\t\tif (lena == lenb) return a.first < b.first;\n\t\treturn lena > lenb;\n\t}\n};\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tset<pair<int, int>, cmp> segs;\n\t\tsegs.insert({0, n - 1});\n\t\tvector<int> a(n);\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\tpair<int, int> cur = *segs.begin();\n\t\t\tsegs.erase(segs.begin());\n\t\t\tint id = (cur.first + cur.second) / 2;\n\t\t\ta[id] = i;\n\t\t\tif (cur.first < id) segs.insert({cur.first, id - 1});\n\t\t\tif (id < cur.second) segs.insert({id + 1, cur.second});\n\t\t}\n\t\tfor (auto it : a) cout << it << \" \";\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1353",
    "index": "E",
    "title": "K-periodic Garland",
    "statement": "You are given a garland consisting of $n$ lamps. States of the lamps are represented by the string $s$ of length $n$. The $i$-th character of the string $s_i$ equals '0' if the $i$-th lamp is turned off or '1' if the $i$-th lamp is turned on. You are also given a positive integer $k$.\n\nIn one move, you can choose \\textbf{one lamp} and change its state (i.e. turn it on if it is turned off and vice versa).\n\nThe garland is called $k$-periodic if the distance between \\textbf{each pair of adjacent turned on lamps} is \\textbf{exactly} $k$. Consider the case $k=3$. Then garlands \"00010010\", \"1001001\", \"00010\" and \"0\" are good but garlands \"00101001\", \"1000001\" and \"01001100\" are not. Note that \\textbf{the garland is not cyclic}, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.\n\nYour task is to find the \\textbf{minimum} number of moves you need to make to obtain $k$-periodic garland from the given one.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let $t_i$ be the string containing all characters of $s$ that have indices $i, i + k, i + 2k$ and so on (i.e. all such positions that have the remainder $i$ modulo $k$). Suppose we choose that all turned on lamps will have remainder $i$ modulo $k$. Then we need to remove all ones at the positions that do not belong to this remainder. Also considering the string $t_i$, we need to spend the minimum number of moves to make this string of kind \"contiguous block of zeros, contiguous block of ones and again contiguous block of zeros\", because considering the characters modulo $k$ will lead us to exactly this pattern (notice that some blocks can be empty). How to calculate the answer for the string $t_i$ in linear time? Let $dp_i[p]$ be the number of moves we need to fix the prefix of $t_i$ till the $p$-th character in a way that the $p$-th character of $t_i$ is '1'. Let $cnt(S, l, r)$ be the number of ones in $S$ on the segment $[l; r]$. Notice that we can calculate all required values $cnt$ in linear time using prefix sums. Then we can calculate $dp_i[p]$ as $min(cnt(t_i, 0, p - 1) + [t_i[p] \\ne~ '1'], dp_i[p-1] + [t_i[p] \\ne~ '1'])$, where $[x]$ is the boolean value of the expression $x$ ($1$ if $x$ is true and $0$ otherwise). Let $len(S)$ be the length of $S$. Then the actual answer for the string $t_i$ can be calculated as $ans_i = \\min(cnt(t_i, 0, len(t_i) - 1), \\min\\limits_{p=0}^{len(t_i) - 1} (dp_i[p] + cnt(t_i, p + 1, len(t_i) - 1)))$ (thus we consider the case when the obtained string doesn't contan ones at all and consider each position as the last position of some one). So the actual answer can be calculated as $\\min\\limits_{i=0}^{k-1} (ans_i + cnt(s, 0, len(s) - 1) - cnt(t_i, 0, len(t_i) - 1))$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tauto solve = [](const string &s) {\n\t\tint n = s.size();\n\t\tint all = count(s.begin(), s.end(), '1');\n\t\tint ans = all;\n\t\tvector<int> res(n);\n\t\tint pref = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint cur = (s[i] == '1');\n\t\t\tpref += cur;\n\t\t\tres[i] = 1 - cur;\n\t\t\tif (i > 0) res[i] += min(res[i - 1], pref - cur);\n\t\t\tans = min(ans, res[i] + all - pref);\n\t\t}\n\t\treturn ans;\n\t};\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tstring s;\n\t\tcin >> n >> k >> s;\n\t\tvector<string> val(k);\n\t\tint cnt = count(s.begin(), s.end(), '1');\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tval[i % k] += s[i];\n\t\t}\n\t\tint ans = 1e9;\n\t\tfor (auto &it : val) ans = min(ans, solve(it) + (cnt - count(it.begin(), it.end(), '1')));\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1353",
    "index": "F",
    "title": "Decreasing Heights",
    "statement": "You are playing one famous sandbox game with the three-dimensional world. The map of the world can be represented as a matrix of size $n \\times m$, where the height of the cell $(i, j)$ is $a_{i, j}$.\n\nYou are in the cell $(1, 1)$ right now and want to get in the cell $(n, m)$. You can move only down (from the cell $(i, j)$ to the cell $(i + 1, j)$) or right (from the cell $(i, j)$ to the cell $(i, j + 1)$). There is an additional \\textbf{restriction}: if the height of the current cell is $x$ then you can move only to the cell with height $x+1$.\n\n\\textbf{Before the first move} you can perform several operations. During one operation, you can decrease the height of \\textbf{any} cell by one. I.e. you choose some cell $(i, j)$ and assign (set) $a_{i, j} := a_{i, j} - 1$. Note that you \\textbf{can} make heights \\textbf{less than or equal to zero}. Also note that you \\textbf{can} decrease the height of the cell $(1, 1)$.\n\nYour task is to find the \\textbf{minimum} number of operations you have to perform to obtain at least one suitable path from the cell $(1, 1)$ to the cell $(n, m)$. It is guaranteed that the answer exists.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, consider the field in $0$-indexation. Suppose that the cell $(0, 0)$ has some fixed height. Let it be $b_{0, 0}$. Then we can determine what should be the height of the cell $(i, j)$ as $b_{i, j} = b_{0, 0} + i + j$. In fact, it does not matter which way we choose, we actually need only the number of moves to reach the cell and the height of the cell $(0, 0)$. Then (when the height of the cell $(0, 0)$ is fixed) we can solve the problem with the following dynamic programming: $dp_{i, j}$ is the minimum number of operations we need to reach the cell $(i, j)$ from the cell $(0, 0)$. Initially, all values $dp_{i, j} = +\\infty$ except $dp_{0, 0} = 0$. Then $dp_{i, j}$ can be calculated as $min(dp_{i - 1, j}, dp_{i, j - 1}) + (a_{i, j} - b_{i, j})$. But one more thing: if $a_{i, j} < b_{i, j}$ then this value of $dp$ is incorrect and we cannot use it. We also can't update $dp$ from the incorrect values. The answer for the problem with the fixed height of the cell $(0, 0)$ is $dp_{n - 1, m - 1} + a_{0, 0} - b_{0, 0}$ (only when $dp_{n-1,m-1}$ is correct and $a_{i, j} \\ge b_{i, j}$). This part can be calculated in $O(n^2)$. But if we iterate over all possible heights, our solution obvious will get time limit exceeded verdict. Now we can notice one important fact: in the optimal answer, the height of some cell remains unchanged. Let this cell be $(i, j)$. Then we can restore the height of the cell $(0, 0)$ as $a_{i, j} - i - j$ and run our quadratic dynamic programming to find the answer for this height. Time complexity: $O(n^4)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst long long INF64 = 1e18;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tvector<vector<long long>> a(n, vector<long long>(m));\n\t\tforn(i, n) forn(j, m) {\n\t\t\tcin >> a[i][j];\n\t\t}\n\t\tlong long a00 = a[0][0];\n\t\tlong long ans = INF64;\n\t\tforn(x, n) forn(y, m) {\n\t\t\tlong long need = a[x][y] - x - y;\n\t\t\tif (need > a00) continue;\n\t\t\ta[0][0] = need;\n\t\t\tvector<vector<long long>> dp(n, vector<long long>(m, INF64));\n\t\t\tdp[0][0] = a00 - need;\n\t\t\tforn(i, n) forn(j, m) {\n\t\t\t\tlong long need = a[0][0] + i + j;\n\t\t\t\tif (need > a[i][j]) continue;\n\t\t\t\tif (i > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + a[i][j] - need);\n\t\t\t\tif (j > 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + a[i][j] - need);\n\t\t\t}\n\t\t\tans = min(ans, dp[n - 1][m - 1]);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1354",
    "index": "A",
    "title": "Alarm Clock",
    "statement": "Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $a$ minutes to feel refreshed.\n\n\\textbf{Polycarp can only wake up by hearing the sound of his alarm.} So he has just fallen asleep and his first alarm goes off in $b$ minutes.\n\nEvery time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $a$ minutes in total, then he sets his alarm to go off in $c$ minutes after it is reset and spends $d$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.\n\nIf the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $c$ minutes and tries to fall asleep for $d$ minutes again.\n\nYou just want to find out when will Polycarp get out of his bed or report that it will never happen.\n\n\\textbf{Please check out the notes for some explanations of the example.}",
    "tutorial": "Let's handle some cases. Firstly, if $b \\ge a$ then Polycarp wakes up rested enough immediately, so $b$ is the answer. Otherwise, what does Polycarp do? He sets alarm to go off in $c$ minutes and falls asleep in $d$ minutes. Thus, he spends $c-d$ minutes sleeping. Notice that if $c-d$ is non-positive, then Polycarp always resets his alarm without sleeping. So for that case the answer is -1. Finally, if Polycarp resets his alarm $x$ times then he ends up with $b + x \\cdot (c - d)$ minutes of sleep in total and ends up spending $b + x \\cdot c$ minutes of time. We know that $b + x \\cdot (c - d)$ should be greater or equal to $a$ and $x$ should be the smallest possible. $b + x \\cdot (c - d) \\ge a \\leftrightarrow x \\cdot (c - d) \\ge a - b \\leftrightarrow x \\ge \\frac{a - b}{c - d}$ Thus, the smallest possible integer $x$ is equal to $\\lceil \\frac{a - b}{c - d} \\rceil$. And the answer is $b + x \\cdot c$. Overall complexity: $O(1)$ per testcase.",
    "code": "t = int(input())\nfor _ in range(t):\n\ta, b, c, d = map(int, input().split())\n\tif b >= a:\n\t\tprint(b)\n\t\tcontinue\n\tif c <= d:\n\t\tprint(-1)\n\t\tcontinue\n\ta -= b\n\tdif = c - d\n\tprint(b + (a + dif - 1) // dif * c)",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1354",
    "index": "B",
    "title": "Ternary String",
    "statement": "You are given a string $s$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $s$ such that it contains each of these three characters at least once.\n\nA contiguous substring of string $s$ is a string that can be obtained from $s$ by removing some (possibly zero) characters from the beginning of $s$ and some (possibly zero) characters from the end of $s$.",
    "tutorial": "There are multiple solutions involving advanced methods such as binary search or two pointers, but I'll try to describe a simpler one. The main idea of my solution is that the answer should look like abb...bbbbbc: one character of type $a$, a block of characters of type $b$, and one character of type $c$. If we find all blocks of consecutive equal characters in our string, each candidate for the answer can be obtained by expanding a block to the left and to the right by exactly one character. So the total length of all candidates is $O(n)$, and we can check them all. Why does the answer look like abb...bbbbbc? If the first character of the substring appears somewhere else in it, it can be deleted. The same applies for the last character. So, the first and the last characters should be different, and should not appear anywhere else within the string. Since there are only three types of characters, the answer always looks like abb...bbbbbc.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nchar buf[200043];\n\nint main()\n{\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tscanf(\"%s\", buf);\n\t\tstring s = buf;\n\t\tint ans = int(1e9);\n\t\tint n = s.size();\n\t\tvector<pair<char, int> > c;\n\t\tfor(auto x : s)\n\t\t{\n\t\t\tif(c.empty() || c.back().first != x)\n\t\t\t\tc.push_back(make_pair(x, 1));\n\t\t\telse\n\t\t\t\tc.back().second++;\n\t\t}\n\t\tint m = c.size();\n\t\tfor(int i = 1; i < m - 1; i++)\n\t\t\tif(c[i - 1].first != c[i + 1].first)\n\t\t\t\tans = min(ans, c[i].second + 2);\n\t\tif(ans > n)\n\t\t\tans = 0;\n\t\tprintf(\"%d\\n\", ans);\n\t}\n}",
    "tags": [
      "binary search",
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1354",
    "index": "C1",
    "title": "Simple Polygon Embedding",
    "statement": "\\textbf{The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd.}\n\nYou are given a regular polygon with $2 \\cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$. Let's name it as $2n$-gon.\n\nYour task is to find the square of the minimum size such that you can embed $2n$-gon in the square. Embedding $2n$-gon in the square means that you need to place $2n$-gon in the square in such way that each point which lies inside or on a border of $2n$-gon should also lie inside or on a border of the square.\n\nYou can rotate $2n$-gon and/or the square.",
    "tutorial": "It's not hard to come up with a solution if you just imagine how $2n$-gon looks when $n$ is even. The solution is to rotate $2n$-gon in such way that several its sides are parallel to sides of the square. And the answer is equal to the distance from center to any side multiplied by two, or: $ans = \\frac{1}{\\tan{\\frac{\\pi}{2 \\cdot n}}}$",
    "tags": [
      "binary search",
      "geometry",
      "math",
      "ternary search"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1354",
    "index": "C2",
    "title": "Not So Simple Polygon Embedding",
    "statement": "\\textbf{The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, $n$ is always even, and in C2, $n$ is always odd.}\n\nYou are given a regular polygon with $2 \\cdot n$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $1$. Let's name it as $2n$-gon.\n\nYour task is to find the square of the minimum size such that you can embed $2n$-gon in the square. Embedding $2n$-gon in the square means that you need to place $2n$-gon in the square in such way that each point which lies inside or on a border of $2n$-gon should also lie inside or on a border of the square.\n\nYou can rotate $2n$-gon and/or the square.",
    "tutorial": "At first, lets place $2n$-gon in such way that the lowest side of $2n$-gon is horizontal. Now we can, without loss of generality, think that the square has horizontal and vertical sides and we just rotate $2n$-gon around its center. If we rotate the $2n$-gon at angle $\\frac{\\pi}{n}$ then it will move on itself. Moreover, after rotating at angle $\\frac{\\pi}{2n}$ we'll get left and right sides vertical and the following rotation is meaningless since it's the same as if we just swap $x$ and $y$ coordinates. So we don't we to rotate more than $\\frac{\\pi}{2n}$. Also, we can see that while rotating the difference between max $x$ and min $x$ decreasing while the distance between max $y$ and min $y$ increasing. The answer is, obviously, the maximum among these differences. So, for example, we can just ternary search the optimal answer. Or we can note that the behavior of differences is symmetrical (just swap $x$ and $y$ coordinates) so the answer is in the middle angle, i.e. we just need to rotate $2n$-gon at angle $\\frac{\\pi}{4n}$. Finally, observing several right triangles we can come up with quite an easy answer: $ans = \\frac{\\cos(\\frac{\\pi}{4n})}{\\sin(\\frac{\\pi}{2n})}$",
    "code": "import kotlin.math.*\n\nfun main() {\n    val PI = acos(-1.0)\n    val T = readLine()!!.toInt()\n    for (tc in 1..T) {\n        val n = readLine()!!.toInt()\n        var ans : Double\n        if (n % 2 == 0) {\n            ans = 1.0 / tan(PI / (2 * n))\n        } else {\n            ans = cos(PI / (4 * n)) / sin(PI / (2 * n))\n        }\n        println(\"%.9f\".format(ans))\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1354",
    "index": "D",
    "title": "Multiset",
    "statement": "\\textbf{Note that the memory limit is unusual.}\n\nYou are given a multiset consisting of $n$ integers. You have to process queries of two types:\n\n- add integer $k$ into the multiset;\n- find the $k$-th order statistics in the multiset and remove it.\n\n$k$-th order statistics in the multiset is the $k$-th element in the sorted list of all elements of the multiset. For example, if the multiset contains elements $1$, $4$, $2$, $1$, $4$, $5$, $7$, and $k = 3$, then you have to find the $3$-rd element in $[1, 1, 2, 4, 4, 5, 7]$, which is $2$. If you try to delete an element which occurs multiple times in the multiset, only one occurence is removed.\n\nAfter processing all queries, print \\textbf{any} number belonging to the multiset, or say that it is empty.",
    "tutorial": "First solution: write some data structure that would simulate the operations as they are given, for example, a segment tree or a Fenwick tree. Probably will require optimization since the limits are strict. Second solution: notice that we have to find only one number belonging to the multiset. For example, let's find the minimum element. We can do it with binary search as follows: let's write a function that, for a given element $x$, tells the number of elements not greater than $x$ in the resulting multiset. To implement it, use the fact that all elements $\\le x$ are indistinguishable, and all elements $> x$ are indistinguishable too, so the multiset can be maintained with just two counters. Okay, how does this function help? The minimum in the resulting multiset is the minimum $x$ such that this function returns non-zero for it, and since the function is monotonous, we can find the answer with binary search.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n, q;\nvector<int> a, k;\n\nint count_le(int x)\n{\n\tint cnt = 0;\n\tfor(auto y : a)\n\t\tif(y <= x)\n\t\t\tcnt++;\n\tfor(auto y : k)\n\t{\n\t\tif(y > 0 && y <= x)\n\t\t\tcnt++;\n\t\tif(y < 0 && abs(y) <= cnt)\n\t\t\tcnt--;\n\t}\n\treturn cnt;\n}\n\nint main()\n{\n\tscanf(\"%d %d\", &n, &q);\n\ta.resize(n);\n\tk.resize(q);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d\", &a[i]);\n\tfor(int i = 0; i < q; i++)\n\t\tscanf(\"%d\", &k[i]);\n\tif(count_le(int(1e9)) == 0)\n\t{\n\t\tputs(\"0\");\n\t\treturn 0;\n\t}\n\tint lf = 0;\n\tint rg = int(1e6) + 1;\n\twhile(rg - lf > 1)\n\t{\n\t\tint mid = (lf + rg) / 2;\n\t\tif(count_le(mid) > 0)\n\t\t\trg = mid;\n\t\telse\n\t\t\tlf = mid;\n\t}\n\tprintf(\"%d\\n\", rg);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1354",
    "index": "E",
    "title": "Graph Coloring",
    "statement": "You are given an undirected graph without self-loops or multiple edges which consists of $n$ vertices and $m$ edges. Also you are given three integers $n_1$, $n_2$ and $n_3$.\n\nCan you label each vertex with one of three numbers 1, 2 or 3 in such way, that:\n\n- Each vertex should be labeled by exactly one number 1, 2 or 3;\n- The total number of vertices with label 1 should be equal to $n_1$;\n- The total number of vertices with label 2 should be equal to $n_2$;\n- The total number of vertices with label 3 should be equal to $n_3$;\n- $|col_u - col_v| = 1$ for each edge $(u, v)$, where $col_x$ is the label of vertex $x$.\n\nIf there are multiple valid labelings, print any of them.",
    "tutorial": "Let's rephrase the fifth condition. Each edge should connect two vertices with the numbers of different parity (either $1$ to $2$ or $3$ to $2$). So the graph should actually be bipartite and the first partition should have only the odd numbers ($1$ or $3$) and the second partition should have only the even numbers (only $2$). Notice how $1$ and $3$ are completely interchangeable in the sense that if you have exactly $n_1 + n_3$ vertices which should be assigned odd numbers then you can assign whichever $n_1$ of them to $1$ and the rest to $3$ you want. So you can guess that the first step is to check if the given graph is bipartite. If it isn't then the answer doesn't exist. It can be done with a single dfs. Actually the algorithm for that extracts the exact partitions, which comes pretty handy. If the graph was a single connected component then the problem would be easy. Just check if either the first partition or the second one has size $n_2$ and assigned its vertices color $2$. If neither of them are of size $n_2$ then the answer obviously doesn't exist. However, the issue is that there might be multiple connected components and for each of them you can choose the partition to assign $2$ to independently. Still, each of the connected components should be bipartite for the answer to exist. This can be done with a knapsack-like dp. Let the $i$-th connected component have partitions of sizes $(l_i, r_i)$. Then the state can be $dp[i][j]$ is true if $i$ connected components are processed and it's possible to assign $2$ to exactly $j$ vertices of these components. As for transitions, for the $i$-th component you can either take the partition with $l_i$ vertices or with $r_i$ vertices. Thus, if $dp[i][j]$ is true then both of $dp[i + 1][j + l_i]$ and $dp[i + 1][j + r_i]$ are also true. If $dp[number\\_of\\_connected\\_components][n_2]$ is false then there is no answer. Otherwise, you can always restore the answer through the dp. The easiest way is probably to store not true/false in $dp[i][j]$ but three values: $-1$ for false, $0$ for the case the state is reached by taking the first partition of the $(i-1)$-th component and $1$ for the second partition. Also, you should store not only the sizes of the partitions but the vertices in each of them as well. This way you can recover the answer by backtracking from the final state. Overall complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define sqr(a) ((a) * (a))\n#define sz(a) int(a.size())\n#define all(a) a.begin(), a.end()\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {\n\treturn out << \"(\" << a.x << \", \" << a.y << \")\";\n}\n\ntemplate <class A> ostream& operator << (ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tforn(i, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nmt19937 rnd(time(NULL));\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst int MOD = int(1e9) + 7;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n\nconst int N = 5000 + 7;\n\nint n, m;\nint a[3];\nvector<int> g[N];\n\nbool read () {\n\tif (scanf(\"%d%d\", &n, &m) != 2)\n\t\treturn false;\n\tforn(i, 3) scanf(\"%d\", &a[i]);\n\tforn(i, n)\n\t\tg[i].clear();\n\tforn(i, m){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v].pb(u);\n\t\tg[u].pb(v);\n\t}\n\treturn true;\n}\n\nint tot0, tot1;\nint clr[N];\nvector<vector<int>> vts[2];\nbool ok;\n\nvoid dfs(int v){\n\ttot0 += clr[v] == 0;\n\ttot1 += clr[v] == 1;\n\tvts[clr[v]].back().pb(v);\n\tfor (auto u : g[v]){\n\t\tif (clr[u] == -1){\n\t\t\tclr[u] = clr[v] ^ 1;\n\t\t\tdfs(u);\n\t\t}\n\t\telse if (clr[u] == clr[v]){\n\t\t\tok = false;\n\t\t}\n\t}\n}\n\nint dp[N][N];\nint res[N];\n\nvoid solve() {\n\tvector<pt> siz;\n\tmemset(clr, -1, sizeof(clr));\n\tvts[0].clear();\n\tvts[1].clear();\n\tforn(i, n) if (clr[i] == -1){\n\t\ttot0 = tot1 = 0;\n\t\tclr[i] = 0;\n\t\tok = true;\n\t\tvts[0].pb(vector<int>());\n\t\tvts[1].pb(vector<int>());\n\t\tdfs(i);\n\t\tif (!ok){\n\t\t\tputs(\"NO\");\n\t\t\treturn;\n\t\t}\n\t\tsiz.pb(mp(tot0, tot1));\n\t}\n\t\n\tmemset(dp, -1, sizeof(dp));\n\tdp[0][0] = 0;\n\tforn(i, sz(siz)) forn(j, N) if (dp[i][j] != -1){\n\t\tdp[i + 1][j + siz[i].x] = 0;\n\t\tdp[i + 1][j + siz[i].y] = 1;\n\t}\n\t\n\tif (dp[sz(siz)][a[1]] == -1){\n\t\tputs(\"NO\");\n\t\treturn;\n\t}\n\t\n\tputs(\"YES\");\n\tmemset(res, -1, sizeof(res));\n\tint cur = a[1];\n\tfor (int i = sz(siz); i > 0; --i){\n\t\tfor (auto it : vts[dp[i][cur]][i - 1])\n\t\t\tres[it] = 2;\n\t\tcur -= sz(vts[dp[i][cur]][i - 1]);\n\t}\n\t\n\tforn(i, n) if (res[i] == -1){\n\t\tif (a[0] > 0){\n\t\t\tres[i] = 1;\n\t\t\t--a[0];\n\t\t}\n\t\telse{\n\t\t\tres[i] = 3;\n\t\t\t--a[2];\n\t\t}\n\t}\n\t\n\tforn(i, n) printf(\"%d\", res[i]);\n\tputs(\"\");\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n\t\n\tint tt = clock();\n\t\n#endif\n\t\n\tcerr.precision(15);\n\tcout.precision(15);\n\tcerr << fixed;\n\tcout << fixed;\n\n\twhile(read()) {\t\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\tcerr << \"TIME = \" << clock() - tt << endl;\n\ttt = clock();\n#endif\n\n\t}\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1354",
    "index": "F",
    "title": "Summoning Minions",
    "statement": "Polycarp plays a computer game. In this game, the players summon armies of magical minions, which then fight each other.\n\nPolycarp can summon $n$ different minions. The initial power level of the $i$-th minion is $a_i$, and when it is summoned, all previously summoned minions' power levels are increased by $b_i$. The minions can be summoned in any order.\n\nUnfortunately, Polycarp cannot have more than $k$ minions under his control. To get rid of unwanted minions after summoning them, he may destroy them. Each minion can be summoned (and destroyed) only once.\n\nPolycarp's goal is to summon the strongest possible army. Formally, he wants to maximize the sum of power levels of all minions under his control (those which are summoned and not destroyed).\n\nHelp Polycarp to make up a plan of actions to summon the strongest possible army!",
    "tutorial": "First of all, let's try to find the best strategy to play minions. All minions should be summoned (if someone is not summoned, summoning and deleting it won't make the answer worse), the resulting number of minions should be exactly $k$ (if it is less, then we didn't need to delete the last deleted minion). Furthermore, if some minion should be deleted, we can delete it just after it is summoned. All these greedy ideas lead to the following structure of the answer: we choose $k - 1$ minions and summon them in some order; we choose $n - k$ minions which will be summoned and instantly deleted; we summon the remaining minion. Let's analyze how these minions affect the answer. The first minion has power $a_i$ and does not give bonus to anyone, the second one has power $a_i$ and gives bonus to one minion, and so on - the $j$-th minion from the first group adds $a_i + (j - 1)b_i$ to the answer. Minions from the second group buff $k - 1$ minions each, so they add $b_i(k - 1)$ to the answer; and the last minion adds $a_i + b_i(k - 1)$. Let's unite the first group and the last minion; then we will have two groups of minions - those which are destroyed (the second group) and those which are not destroyed (the first group). From there, we will have two possible ways to finish the solution: there are $n$ minions and $n$ positions for them, and for each pair (minion, position) we may calculate the value this pair adds to the answer. After that, we should assign each monster a position in such a way that each position is chosen exactly once, and the sum of values is maximized. It can be done with mincost flows or Hungarian algorithm; the minions from the first group should be played in non-descending order of their $b_i$. Let's sort all minions by $b_i$ and write the following dynamic programming: $dp_{x, y}$ is the maximum answer if we considered $x$ first minions, and $y$ of them were assigned to the first group. Since the minions are sorted by $b_i$, whenever we add a minion to the first group, it should add exactly $a_i + yb_i$ to the answer (and increase $y$ by $1$); and if a minion is added to the second group, the answer is increased by $(k - 1)b_i$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define sqr(a) ((a) * (a))\n#define sz(a) int(a.size())\n#define all(a) a.begin(), a.end()\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n \ntemplate <class A, class B> ostream& operator << (ostream& out, const pair<A, B> &a) {\n\treturn out << \"(\" << a.x << \", \" << a.y << \")\";\n}\n \ntemplate <class A> ostream& operator << (ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tforn(i, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n \nmt19937 rnd(time(NULL));\n \nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst int MOD = int(1e9) + 7;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n \nconst int N = 100;\n \nint n, k;\npair<pt, int> a[N];\n \nbool read () {\n\tif (scanf(\"%d%d\", &n, &k) != 2)\n\t\treturn false;\n\tforn(i, n){\n\t\tscanf(\"%d%d\", &a[i].x.x, &a[i].x.y);\n\t\ta[i].y = i;\n\t}\n\treturn true;\n}\n \nint dp[N][N];\nint p[N][N];\n \nvoid solve() {\n\tsort(a, a + n, [](const pair<pt, int> &a, const pair<pt, int> &b){\n\t\tif (a.x.y != b.x.y)\n\t\t\treturn a.x.y < b.x.y;\n\t\treturn a.x.x < b.x.x;\n\t});\n\t\n\tforn(i, N) forn(j, N)\n\t\tdp[i][j] = -INF;\n\tdp[0][0] = 0;\n\tforn(i, n) forn(j, N) if (dp[i][j] >= 0){\n\t\tif (dp[i + 1][j] < dp[i][j] + a[i].x.y * (k - 1)){\n\t\t\tdp[i + 1][j] = dp[i][j] + a[i].x.y * (k - 1);\n\t\t\tp[i + 1][j] = j;\n\t\t}\n\t\tif (dp[i + 1][j + 1] < dp[i][j] + a[i].x.y * j + a[i].x.x){\n\t\t\tdp[i + 1][j + 1] = dp[i][j] + a[i].x.y * j + a[i].x.x;\n\t\t\tp[i + 1][j + 1] = j;\n\t\t}\n\t}\n\t\n\tvector<int> ans1, ans2;\n\tint cur = k;\n\tfor (int i = n; i > 0; --i){\n\t\tif (p[i][cur] == cur)\n\t\t\tans2.pb(a[i - 1].y + 1);\n\t\telse\n\t\t\tans1.pb(a[i - 1].y + 1);\n\t\tcur = p[i][cur];\n\t}\n\t\n\treverse(all(ans1));\n\treverse(all(ans2));\n\tprintf(\"%d\\n\", sz(ans1) + sz(ans2) * 2);\n\tforn(i, sz(ans1) - 1)\n\t\tprintf(\"%d \", ans1[i]);\n\tfor (auto it : ans2)\n\t\tprintf(\"%d %d \", it, -it);\n\tprintf(\"%d\\n\", ans1.back());\n}\n \nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n\t\n\tint tt = clock();\n\t\n#endif\n\t\n\tcerr.precision(15);\n\tcout.precision(15);\n\tcerr << fixed;\n\tcout << fixed;\n \n\tint tc;\n\tscanf(\"%d\", &tc);\n\twhile(tc--) {\t\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\tcerr << \"TIME = \" << clock() - tt << endl;\n\ttt = clock();\n#endif\n \n\t}\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "flows",
      "graph matchings",
      "greedy",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1354",
    "index": "G",
    "title": "Find a Gift",
    "statement": "This is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages.\n\nThere are $n$ gift boxes in a row, numbered from $1$ to $n$ from left to right. It's known that exactly $k$ of them contain valuable gifts — other boxes contain just lucky stones. All boxes look the same and differ only in weight. All boxes with stones have the same weight and are strictly heavier than boxes with valuable items. But valuable gifts may be different, so the boxes with valuable items may have different weights.\n\nYou can ask no more than $50$ queries (printing an answer doesn't count). By each query you can compare total weights of two non-intersecting subsets of boxes $a_1, a_2, \\dots, a_{k_a}$ and $b_1, b_2, \\dots, b_{k_b}$. In return you'll get one of four results:\n\n- FIRST, if subset $a_1, a_2, \\dots, a_{k_a}$ is strictly \\textbf{heavier};\n- SECOND, if subset $b_1, b_2, \\dots, b_{k_b}$ is strictly \\textbf{heavier};\n- EQUAL, if subsets have equal total weights;\n- WASTED, if the query is incorrect or the limit of queries is exceeded.\n\nUsing such queries (or, maybe, intuition) find the box with a valuable gift with \\textbf{the minimum index}.",
    "tutorial": "The solution consists of several steps. The first step. Let's find out \"does the first box contain stone or valuable gift\" using random. Let's make $30$ queries to compare the weight of the first box with the weight of another random box. If the first box is lighter than we found an answer, otherwise the probability of the first box having stones is at least $1 - 2^{-30}$. The second step. Let's compare the weights of the first box and the second one. If they are equal then let's compare the weights of boxes $[1, 2]$ and $[3,4]$. If they are equal then let's compare the boxes $[1 \\dots 4]$ and $[5 \\dots 8]$ and so on. In other words, let's find the minimum $k \\ge 0$ such that $[1, 2^k]$ contains only boxes with stones but $[2^k + 1, 2^{k + 1}]$ contain at least one box with a valuable gift. It's easy to see that we'd spend no more than $10$ queries. The third step. We have segment $[1, 2^k]$ with only stones and $[2^k + 1, 2^{k + 1}]$ with at least one gift. Let's just binary search the leftmost gift in the segment $[2^k + 1, 2^{k + 1}]$ using boxes from $[1, 2^k]$ as reference: if we need to know \"does segment of boxes $[l, mid)$ have at least one gift\", let's just compare it with segment $[0, mid - l)$ which have only stones. if $[l, mid)$ is lighter then it has, otherwise doesn't have. This part also requires no more than $10$ queries.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int MAG = 30;\nint lst;\n\nint n, k;\n\ninline bool read() {\n\tif(!(cin >> n >> k))\n\t\treturn false;\n\treturn true;\n}\n\nint ask(int l1, int r1, int l2, int r2) {\n\tassert(l1 < r1 && l2 < r2);\n\tassert(r1 <= l2 || r2 <= l1);\n\t\n\tcout << \"? \" << r1 - l1 << \" \" << r2 - l2 << endl;\n\tfore(i, l1, r1) {\n\t\tif (i > l1) cout << \" \";\n\t\tcout << i + 1;\n\t}\n\tcout << endl;\n\tfore(i, l2, r2) {\n\t\tif (i > l2) cout << \" \";\n\t\tcout << i + 1;\n\t}\n\tcout << endl;\n\tcout.flush();\n\t\n\tstring resp;\n\tcin >> resp;\n\t\n\tif (resp == \"FIRST\")\n\t\treturn -1;\n\tif (resp == \"SECOND\")\n\t\treturn 1;\n\tif (resp == \"EQUAL\")\n\t\treturn 0;\n\t\n\texit(0);\n}\n\ninline void solve() {\n\t//check first position\n\tmt19937 rnd(lst ^ (n * 1024 + k));\n\tfor(int q = 0; q < MAG; q++) {\n\t\tint cur = 1 + rnd() % (n - 1);\n\t\t\n\t\tint resp = ask(0, 1, cur, cur + 1);\n\t\tif (resp == 1) {\n\t\t\tcout << \"! 1\" << endl;\n\t\t\tcout.flush();\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tint len = 1;\n\twhile(true) {\n\t\tint cnt = min(len, n - len);\n\t\tint resp = ask(0, cnt, len, len + cnt);\n\t\tif (resp != 0) {\n\t\t\tassert(resp == -1);\n\t\t\tbreak;\n\t\t}\n\t\tlen <<= 1;\n\t}\n\t\n\tint lf = len, rg = min(2 * len, n);\n\twhile(rg - lf > 1) {\n\t\tint mid = (lf + rg) >> 1;\n\t\tint resp = ask(0, mid - lf, lf, mid);\n\t\tassert(resp != 1);\n\t\t\n\t\tif (resp == 0)\n\t\t\tlf = mid;\n\t\telse\n\t\t\trg = mid;\n\t}\n\tcout << \"! \" << lf + 1 << endl;\n\tcout.flush();\n\t\n\tlst = lf + 1;\n}\n\nint main() {\n\tint tc;\n\tcin >> tc;\n\t\n\tlst = tc;\n\twhile(tc--) {\n\t\tassert(read());\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "interactive",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1355",
    "index": "A",
    "title": "Sequence with Digits",
    "statement": "Let's define the following recurrence: $$a_{n+1} = a_{n} + minDigit(a_{n}) \\cdot maxDigit(a_{n}).$$\n\nHere $minDigit(x)$ and $maxDigit(x)$ are the minimal and maximal digits in the decimal representation of $x$ without leading zeroes. For examples refer to notes.\n\nYour task is calculate $a_{K}$ for given $a_{1}$ and $K$.",
    "tutorial": "Let's calculate the sequence for fixed $a_{1} = 1$: $1, 2, 6, 42, 50, 50, 50, \\ldots$ We got lucky and the minimal digit has become 0, after that the element has stopped changing because we always add 0. Actually it is not luck and that will always happen. Note that we add no more than $9 \\cdot 9 = 81$ every time, so the difference between two consecutive elements of the sequence is bounded by 81. Assume that we will never have minimal digit equal to 0. Then the sequence will go to infinity. Let's take $X = 1000(\\lfloor \\frac{a_{1}}{1000} \\rfloor + 1)$. All the numbers on segment $[X;X+99]$ have 0 in hundreds digit, so none of them can be element of our sequence. But our sequence should have numbers greater than $X$. Let's take the smallest of them, it should be at least $X + 100$. But then the previous number in the sequence is at least $(X + 100) - 81 = X + 19$. It is greater than $X$ but smaller than the minimal of such numbers. Contradiction. In the previous paragraph we have actually shown that we have no numbers greater than $X + 100$ in our sequence and we will see the number with 0 among first 1001 elements. That means that we can build the sequence till we find the first number with 0 and then it will repeat forever. In reality the maximal index of the first elements with 0 is 54 and minimal $a_{1}$ for that to happen is 28217.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\n#include <chrono>\n#include <random>\n#include <bitset>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);\n#else\n\t#define eprintf(...) 42\n#endif\n \nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \ndouble startTime;\ndouble getCurrentTime() {\n\treturn ((double)clock() - startTime) / CLOCKS_PER_SEC;\n}\n \nll getAdd(ll x) {\n\tll m1 = 10, m2 = 0;\n\twhile(x > 0) {\n\t\tll y = x % 10;\n\t\tx /= 10;\n\t\tm1 = min(m1, y);\n\t\tm2 = max(m2, y);\n\t}\n\treturn m1 * m2;\n}\n \nint main()\n{\n\tstartTime = (double)clock();\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tint t;\n\tscanf(\"%d\", &t);\n\twhile(t--) {\n\t\tll x, k;\n\t\tscanf(\"%lld%lld\", &x, &k);\n\t\tk--;\n\t\twhile(k--) {\n\t\t\tll y = getAdd(x);\n\t\t\tif (y == 0) break;\n\t\t\tx += y;\n\t\t}\n\t\tprintf(\"%lld\\n\", x);\n\t}\n \n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1355",
    "index": "B",
    "title": "Young Explorers",
    "statement": "Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...\n\nMost of the young explorers are inexperienced, and sending them alone would be a mistake. Even Russell himself became senior explorer not long ago. Each of young explorers has a positive integer parameter $e_i$ — his inexperience. Russell decided that an explorer with inexperience $e$ can only join the group of $e$ or more people.\n\nNow Russell needs to figure out how many groups he can organize. It's not necessary to include every explorer in one of the groups: some can stay in the camp. Russell is worried about this expedition, so he asked you to help him.",
    "tutorial": "Let's sort all the explorers by non-decreasing inexperience. Suppose we have formed some group, how can we check is this group is valid? Inexperience of all the explorers in the group should be not greater than the group size. But we have sorted all the explorers, so the last explorer from the group has the largest inexperience. Therefore, to check the group for validity it is necessary and sufficient to check that inexperience of the last explorer is not greater than the group size. We can notice that we don't even look at all the explorers except the last one, the only important thing is their number. In fact, we can organize the creation of groups in this way: first choose the explorers that will be the last in their groups, then assign sufficient number of other explorers to corresponding groups. It is not profitable to assign more explorers than needed for this particular last explorer, because we can always leave them at the camp. So how should we choose the last explorers? We want to make more groups, so the groups themselves should me smaller... It is tempting to use the following greedy algorithm: let's greedily pick the leftmost (which means with the smallest necessary group size) explorer such that they have enough explorers to the left of them to create a valid group. The idea is that we spend the smallest number of explorers and leave the most potential last explorers in the future. Let's strictly prove this greedy: The solution is defined by positions of the last explorers in their corresponding groups $1 \\le p_{1} < p_{2} < \\ldots < p_{k} \\le n$. Notice that the solution is valid if and only if $e_{p_{1}} + e_{p_{2}} + \\ldots + e_{p_{i}} \\le p_{i}$ for all $1 \\le i \\le k$ (we always have enough explorers to form first $i$ groups). Let $1 \\le p_{1} < p_{2} < \\ldots < p_{k} \\le n$ be the greedy solution and $1 \\le q_{1} < q_{2} < \\ldots < q_{m} \\le n$ be the optimal solution such that it has the largest common prefix with greedy one among all optimal solutions. Let $t$ be the position of first difference in these solutions. $t \\le k$ since otherwise the greedy algorithm couldn't add one more group but it was possible. $p_{t} < q_{t}$ since otherwise the greedy algorithm would take $q_{t}$ instead of $p_{t}$. Since the explorers are sorted we have $e_{p_{t}} \\le e_{q_{t}}$. But then $1 \\le q_{1} < q_{2} < \\ldots < q_{t - 1} < p_{t} < q_{t + 1} < \\ldots < q_{m} \\le n$ is a valid optimal solution and it has strictly larger common prefix with the greedy one which contradicts the choosing of our optimal solution. To implement this solution it is enough to sort the explorers by the non-decreasing inexperience, then go from left to right and maintain the number of unused explorers. As soon as we encounter the possibility to create a new group, we do it.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    \n    while (t--) {\n        int n;\n        cin >> n;\n        vector <int> a(n);\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n        sort(a.begin(), a.end());\n        int ans = 0, cur = 0;\n        for (int i = 0; i < n; i++) {\n            if (++cur == a[i]) {\n                ans++;\n                cur = 0;\n            }\n        }\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1355",
    "index": "C",
    "title": "Count Triangles",
    "statement": "Like any unknown mathematician, Yuri has favourite numbers: $A$, $B$, $C$, and $D$, where $A \\leq B \\leq C \\leq D$. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides $x$, $y$, and $z$ exist, such that $A \\leq x \\leq B \\leq y \\leq C \\leq z \\leq D$ holds?\n\nYuri is preparing problems for a new contest now, so he is very busy. That's why he asked you to calculate the number of triangles with described property.\n\nThe triangle is called non-degenerate if and only if its vertices are not collinear.",
    "tutorial": "Since $x \\le y \\le z$ to be a non-degenerate triangle for given triple it is necessary and sufficient to satisfy $z < x + y$. Let's calculate for all $s = x + y$ how many ways there are to choose $(x, y)$. To do that we will try all $x$ and add 1 on segment $[x + B; x + C]$ offline using prefix sums. Let's calculate prefix sums once more, now we can find in $O(1)$ how many ways there are to choose $(x, y)$ such that their sum if greater than $z$. Try all $z$, calculate the answer. Total complexity - $O(C)$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\n#include <chrono>\n#include <random>\n#include <bitset>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);\n#else\n\t#define eprintf(...) 42\n#endif\n \nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \ndouble startTime;\ndouble getCurrentTime() {\n\treturn ((double)clock() - startTime) / CLOCKS_PER_SEC;\n}\n \nconst int N = (int)1e6 + 77;\nint A, B, C, D;\nll a[N];\n \nint main()\n{\n\tstartTime = (double)clock();\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tscanf(\"%d%d%d%d\", &A, &B, &C, &D);\n\tfor (int i = A; i <= B; i++) {\n\t\ta[i + B]++;\n\t\ta[i + C + 1]--;\n\t}\n\tfor (int i = 1; i < N; i++)\n\t\ta[i] += a[i - 1];\n\tfor (int i = 1; i < N; i++)\n\t\ta[i] += a[i - 1];\n\tll ans = 0;\n\tfor (int i = C; i <= D; i++)\n\t\tans += a[N - 1] - a[i];\n\tprintf(\"%lld\\n\", ans);\n \n\treturn 0;\n}",
    "tags": [
      "binary search",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1355",
    "index": "D",
    "title": "Game With Array",
    "statement": "Petya and Vasya are competing with each other in a new interesting game as they always do.\n\nAt the beginning of the game Petya has to come up with an array of $N$ positive integers. Sum of all elements in his array should be equal to $S$. Then Petya has to select an integer $K$ such that $0 \\leq K \\leq S$.\n\nIn order to win, Vasya has to find a non-empty subarray in Petya's array such that the sum of all selected elements equals to either $K$ or $S - K$. Otherwise Vasya loses.\n\nYou are given integers $N$ and $S$. You should determine if Petya can win, considering Vasya plays optimally. If Petya can win, help him to do that.",
    "tutorial": "For $S \\ge 2N$ Petya wins: let's take array $[2, 2, \\ldots, 2, S - 2(N - 1)]$ and $K = 1$. All the elements are strictly greater than 1, so there are no segment with sum 1 or $S - 1$. Let's prove that for $S < 2N$ Petya will lose. Suppose it is not true and there exist an array and $K > 0$ (it is obvious that $K = 0$ is bad). Note that the condition that there is a segment with sum $K$ or $S - K$ is equivalent to the condition that there is a segment with sum $K$ in cyclic array. Let's calculate prefix sums for our array, and for prefix sum $M$ let's mark all the numbers of the form $M + TS$ for integer $T \\ge 0$. It is easy to see that numbers $X$ and $X + K$ cannot be marked simultaneously: otherwise there is a segment with sum $K$ in a cyclic array. Let's consider half-interval $[0; 2KS)$. It is clear that exactly $2KN$ numbers are marked on this half-interval. On the other hand, we can split all the numbers from this half-interval into $KS$ pairs with difference $K$: $(0, K), (1, K + 1), \\ldots, (K - 1, 2K - 1), (2K, 3K), (2K + 1, 3K + 1), \\ldots (2KS - K - 1, 2KS - 1)$. In every such pair no more than one number is marked, so the total number of marked numbers is bounded by $KS$. Therefore $2KN \\le KS$ which means $2N \\le S$. Contradiction.",
    "code": "#include <iostream>\nusing namespace std;\n \nint main() {\n\tint n, s;\n\tcin >> n >> s;\n\t\n\tif (2 * n <= s) {\n\t\tcout << \"YES\\n\";\n\t\tfor (int i = 0; i < n - 1; i++) {\n\t\t\tcout << 2 << ' ';\n\t\t\ts -= 2;\n\t\t}\n\t\tcout << s << '\\n' << 1;\n\t} else {\n\t\tcout << \"NO\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1355",
    "index": "E",
    "title": "Restorer Distance",
    "statement": "You have to restore the wall. The wall consists of $N$ pillars of bricks, the height of the $i$-th pillar is initially equal to $h_{i}$, the height is measured in number of bricks. After the restoration all the $N$ pillars should have equal heights.\n\nYou are allowed the following operations:\n\n- put a brick on top of one pillar, the cost of this operation is $A$;\n- remove a brick from the top of one non-empty pillar, the cost of this operation is $R$;\n- move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $M$.\n\nYou cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $0$.\n\nWhat is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?",
    "tutorial": "First of all let's do $M = \\min(M, A + R)$ - this is true since we can emulate moving by adding+removing. After that it is never profitable to add and remove in one solution, since we can always move instead. Suppose we have fixed $H$ - the resulting height for all pillars. How can we calculate the minimal cost for given $H$? Some pillars have no more than $H$ bricks, let the total number of missing bricks in these pillars be $P$. Other pillars have no less than $H$ bricks, let the total number of extra bricks in these pillars be $Q$. If $P \\ge Q$ then we are missing $(P - Q)$ bricks in total, so we have to make $(P - Q)$ additions. There won't be any more additions or removals, and we have to do at least $Q$ moves since we have to somehow get rid of extra bricks from those pillars which have more than $H$ bricks initially. It is clear that $Q$ moves is enough. Therefore the total cost will be $C = A(P - Q) + MQ$. Similarly, if $Q \\ge P$ then the total cost will be $C = R(Q - P) + MP$. Let's now assume that $P \\ge Q$, we have exactly $X$ pillars with no more than $H$ bricks and exactly $N - X$ pillars with strictly more than $H$ bricks. Let's try to increase $H$ by 1 and see how the total cost will change. $P' = P + X$, $Q' = Q - (N - X) = Q - N + X$. $C' = A(P' - Q') + MQ' = A(P + X - Q + N - X) + M(Q - N + X) = A(P - Q) + MQ + AN - M(N - X)$. We can see that the total cost has changed by $AN - M(N - X)$. While $X$ is constant the cost change will be constant. What are the moments when $X$ changes? When $H$ is equal to the initial height of some pillar. Therefore the cost as a function of $H$ is piecewise linear with breakpoints in points corresponding to initial heights. There is a nuance - we have assumed $P \\ge Q$. The same thing will be true for $P \\le Q$ but there can be additional breakpoints when we change between these two states. This change will happen only once for $H \\approx \\frac{\\sum h_{i}}{N}$ (approximate equality here means that this point can be non-integral so we should add both $\\lfloor \\frac{\\sum h_{i}}{N} \\rfloor$ and $\\lceil \\frac{\\sum h_{i}}{N} \\rceil$ as breakpoints). The minima of piecewise linear function are in breakpoints so it is enough to calculate the cost for breakpoints (initial heights and $H \\approx \\frac{\\sum h_{i}}{N}$) and choose minimal of them. To calculate the cost for given $H$ fast we can sort the initial heights and calculate prefix sums of heights. Then using binary search we can determine which pillars have height less than $H$ and greater than $H$ and then calculate $P$ and $Q$ using prefix sums. We can use two pointers instead of binary searches but it will not improve the total complexity which is $O(N \\log N)$ due to sorting (and binary searches if we are using them).",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\n#include <chrono>\n#include <random>\n#include <bitset>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);\n#else\n\t#define eprintf(...) 42\n#endif\n \nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \ndouble startTime;\ndouble getCurrentTime() {\n\treturn ((double)clock() - startTime) / CLOCKS_PER_SEC;\n}\n \nconst ll INF = (ll)2e18 + 77;\nconst int N = 100100;\nint n;\nll h[N];\nll pref[N];\nll A, R, M;\nll ans = INF;\n \nll solve(ll H) {\n\tint pos = lower_bound(h, h + n, H) - h;\n\tll res = 0;\n\tll k1 = H * pos - pref[pos];\n\tll k2 = pref[n] - pref[pos] - H * (n - pos);\n\tres = min(k1, k2);\n\tk1 -= res;\n\tk2 -= res;\n\tres *= M;\n\tres += k1 * A;\n\tres += k2 * R;\n\treturn res;\n}\n \nint main()\n{\n\tstartTime = (double)clock();\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tscanf(\"%d%lld%lld%lld\", &n, &A, &R, &M);\n\tM = min(M, A + R);\n\tfor (int i = 0; i < n; i++)\n\t\tscanf(\"%lld\", &h[i]);\n\tsort(h, h + n);\n\tfor (int i = 0; i < n; i++)\n\t\tpref[i + 1] = pref[i] + h[i];\n \n\tll L = h[0], R = h[n - 1];\n\twhile(R - L > (ll)1e6) {\n\t\tll M1 = L + (R - L) / 3, M2 = R - (R - L) / 3;\n\t\tif (solve(M1) > solve(M2)) {\n\t\t\tL = M1;\n\t\t} else {\n\t\t\tR = M2;\n\t\t}\n\t}\n\tfor (ll x = L; x <= R; x++)\n\t\tans = min(ans, solve(x));\n\tprintf(\"%lld\\n\", ans);\n \n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "sortings",
      "ternary search"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1355",
    "index": "F",
    "title": "Guess Divisors Count",
    "statement": "This is an interactive problem.\n\nWe have hidden an integer $1 \\le X \\le 10^{9}$. You \\textbf{don't have to} guess this number. You have to \\textbf{find the number of divisors} of this number, and you \\textbf{don't even have to find the exact number}: your answer will be considered correct if its absolute error is not greater than 7 \\textbf{or} its relative error is not greater than $0.5$. More formally, let your answer be $ans$ and the number of divisors of $X$ be $d$, then your answer will be considered correct if \\textbf{at least one} of the two following conditions is true:\n\n- $| ans - d | \\le 7$;\n- $\\frac{1}{2} \\le \\frac{ans}{d} \\le 2$.\n\nYou can make at most $22$ queries. One query consists of one integer $1 \\le Q \\le 10^{18}$. In response, you will get $gcd(X, Q)$ — the greatest common divisor of $X$ and $Q$.\n\nThe number $X$ is fixed before all queries. In other words, \\textbf{interactor is not adaptive}.\n\nLet's call the process of guessing the number of divisors of number $X$ a game. In one test you will have to play $T$ independent games, that is, guess the number of divisors $T$ times for $T$ independent values of $X$.",
    "tutorial": "If $X = p_{1}^{\\alpha_{1}} \\cdot p_{2}^{\\alpha_{2}} \\cdot \\ldots \\cdot p_{k}^{\\alpha_{k}}$ then $d(X) = (\\alpha_{1} + 1) \\cdot (\\alpha_{2} + 1) \\cdot \\ldots \\cdot (\\alpha_{k} + 1)$. If $X$ has prime $p$ in power $\\alpha$ and $Q$ has $p$ in power $\\beta$ then $gcd(X, Q)$ will have $p$ in power $\\gamma = \\min (\\alpha, \\beta)$. If $\\gamma < \\beta$ then $\\alpha = \\gamma$, otherwise $\\gamma = \\beta$ and $\\alpha \\ge \\gamma$. We don't know $X$, but we can choose $Q$. If we'll choose $Q$ with known prime factorization then we'll be able to extract all the information from query fast (in $O(\\log Q)$). After all the queries for each prime $p$ we'll know either the exact power in which $X$ has it, or lower bound for it. We can get upper bound from the fact that $X \\le 10^{9}$. It is clear that we cannot get information about all primes - there are too many of them and too few queries. We want to somehow use the fact that we don't have to find the exact answer... Suppose we have figured out that $X = X_{1} \\cdot X_{2}$ where we know $X_{1}$ exactly and we also know that $X_{2}$ has no more than $t$ prime factors (including multiplicity). Then $d(X_{1}) \\le d(X) \\le d(X_{1}) \\cdot d(X_{2}) \\le d(X_{1}) \\cdot 2^{t}$. If $t \\le 1$ then our answer will have relative error no more than $0.5$... One of the ways to guarantee that $X_{2}$ has few prime factors is to show that it cannot have small prime factors. That means that we have to calculate the exact power for all small primes. This gives an overall idea for the solution: let's make a query $Q=p^{\\beta}$ for all primes $p \\le B$ (for some bound $B$) where $\\beta$ is chosen in such a way that $p^{\\beta} > 10^{9}$. This allows us to know the exact power in which $X$ has $p$. This basic idea can be improved in several ways: $X$ has no more than 9 different prime factors, so for most primes its power is 0. If we could exclude these redundant primes fast it could speed up the solution significantly. And there is a way: we could make a query $Q = p_{1} p_{2} \\ldots p_{s}$ for $s$ different primes, after that we will know which of them are factors of $X$; $\\beta$ can be chosen such that $p^{\\beta + 1} > 10^{9}$, because even if $\\gamma = \\beta$ and $\\alpha \\ge \\gamma = \\beta$ we will know that $\\alpha \\le \\beta$ since otherwise $X > 10^{9}$; From the previous point follows that we can find the exact power for two primes simultaneously, just make a query with a product of two respective numbers. How to choose $B$? Apparently we want $B^{2} > 10^{9}$. But actually $t \\le 2$ is ok for us: if we know that $L \\le d(X) \\le 4L$ then we can answer $2L$ and the relative error will be no more than $0.5$. That means we want $B^{3} > 10^{9}$ or $B = 1001$. We are close: there are 168 primes less than 1001, we can check 6 primes (for being a factor of $X$) in one query since $1000^{6} \\le 10^{18}$, so we need 28 queries. Let's note that if we have found some prime factors of $X$ (let's say their product is $X_{1}$) then $X_{2} \\le \\frac{10^{9}}{X_{1}}$. Suppose we have checked all the primes not greater than $p$ and $X_{1} \\cdot p^{3} > 10^{9}$. That means that $X_{2}$ has no more than 2 prime divisors and we are good. What is left is to use our right to have absolute error: if $X_{1} \\le 3$ we can just print 8! Either $X_{1} \\le 3$ and we are fine with $X_{2}$ having 3 prime factors, or $X_{1} \\ge 4$ and we have to check all primes up to $\\sqrt[3]{10^{9} / 4} < 630$. There are 114 such primes, so we need only 19 queries. We will also need some queries to find out the exact power for those small prime factors of $X$ we have found. If we have found no more than 2 prime factors, we'll need 1 query, otherwise we'll have to check primes only up to $\\sqrt[3]{10^{9} / (2 \\cdot 3 \\cdot 5)} < 330$, of which there are only 66 so the first part of the solution spends no more than 11 queries. So we have shown that the solution spends no more than 20 queries. We did some rough estimations, the actual bound for this solution is 17 queries.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\n#include <chrono>\n#include <random>\n#include <bitset>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);\n#else\n\t#define eprintf(...) 42\n#endif\n \nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \ndouble startTime;\ndouble getCurrentTime() {\n\treturn ((double)clock() - startTime) / CLOCKS_PER_SEC;\n}\n \nconst int N = 2020;\nconst ll INF = (ll)1e18;\nbool p[N];\n \nll query(ll x) {\n\tprintf(\"? %lld\\n\", x);\n\tcerr << \"? \" << x << endl;\n\tfflush(stdout);\n\tscanf(\"%lld\", &x);\n\tcerr << \"gcd \" << x << endl;\n\treturn x;\n}\n \nvoid solve() {\n \n\tll C = (ll)1e9 / 2 / 2;\n\tvector<ll> hv;\n\tvector<ll> cur;\n\tll curProd = 1;\n\tfor (int i = 2; i < N; i++) {\n\t\tif (!p[i]) continue;\n\t\tll cc = C;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tcc /= i;\n\t\tif (cc == 0) break;\n\t\tif (INF / i < curProd) {\n\t\t\tll g = query(curProd);\n\t\t\twhile(!cur.empty()) {\n\t\t\t\tif (g % cur.back() == 0) {\n\t\t\t\t\thv.push_back(cur.back());\n\t\t\t\t\tif ((int)hv.size() <= 2) C *= 2;\n\t\t\t\t\tC /= hv.back();\n\t\t\t\t}\n\t\t\t\tcur.pop_back();\n\t\t\t}\n\t\t\tcurProd = 1;\n\t\t}\n\t\tcur.push_back((ll)i);\n\t\tcurProd *= i;\n\t}\n\tif (!cur.empty()) {\n\t\tll g = query(curProd);\n\t\twhile(!cur.empty()) {\n\t\t\tif (g % cur.back() == 0) hv.push_back(cur.back());\n\t\t\tcur.pop_back();\n\t\t}\n\t}\n\tif ((int)hv.size() & 1) {\n\t\tfor (int i = 2; i < N; i++) {\n\t\t\tif (!p[i]) continue;\n\t\t\tbool fnd = false;\n\t\t\tfor (ll x : hv)\n\t\t\t\tfnd |= i == x;\n\t\t\tif (!fnd) {\n\t\t\t\thv.push_back(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tll ans = 2;\n\tfor (int i = 0; i < (int)hv.size(); i += 2) {\n\t\tll p1 = hv[i], p2 = hv[i + 1];\n\t\tll x1 = 1, x2 = 1;\n\t\twhile(x1 * p1 <= (ll)1e9) x1 *= p1;\n\t\twhile(x2 * p2 <= (ll)1e9) x2 *= p2;\n\t\tll g = query(x1 * x2);\n\t\tint t1 = 1, t2 = 1;\n\t\twhile(g % p1 == 0) {\n\t\t\tg /= p1;\n\t\t\tt1++;\n\t\t}\n\t\twhile(g % p2 == 0) {\n\t\t\tg /= p2;\n\t\t\tt2++;\n\t\t}\n\t\tans *= t1 * t2;\n\t}\n\tprintf(\"! %lld\\n\", max(8LL, ans));\n\tcerr << \"ans \" << ans << endl;\n\tfflush(stdout);\n}\n \nint main()\n{\n\tstartTime = (double)clock();\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n \n\tfor (int i = 2; i < N; i++)\n\t\tp[i] = 1;\n\tfor (int i = 2; i < N; i++) {\n\t\tif (!p[i]) continue;\n\t\tfor (int j = 2 * i; j < N; j += i)\n\t\t\tp[j] = 0;\n\t}\n \n\tint t;\n\tscanf(\"%d\", &t);\n\tcerr << \"tests = \" << t << endl;\n\twhile(t--) solve();\n \n \n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1358",
    "index": "A",
    "title": "Park Lighting",
    "statement": "Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.\n\nThe park is a rectangular table with $n$ rows and $m$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $1$. For example, park with $n=m=2$ has $12$ streets.\n\nYou were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park).\n\n\\begin{center}\n{\\small The park sizes are: $n=4$, $m=5$. The lighted squares are marked yellow. Please note that all streets have length $1$. Lanterns are placed in the middle of the streets. In the picture \\textbf{not all} the squares are lit.}\n\\end{center}\n\nSemyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.",
    "tutorial": "Note that if at least one of the sides is even, the square can be divided into pairs of neighbors and the answer is $\\frac{nm}{2}$. If both sides are odd, we can first light up a $(n - 1) \\times m$ part of the park. Then we'll still have the part $m \\times 1$. We can light it up with $\\frac{m + 1}{2}$ lanterns. Then the total number of the lanterns is $\\frac{(n-1) \\cdot m}{2} + \\frac{m + 1}{2} = \\frac{nm - m + m + 1}{2} = \\frac{nm + 1}{2}$. Note that both cases can be combined into one formula: $\\lfloor \\frac{nm + 1}{2} \\rfloor$. The overall compexity is $\\mathcal{O}(1)$ per test.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n    int t, n, m;\n    cin >> t;\n    while (t--) {\n        cin >> n >> m;\n        cout << (n * m + 1) / 2 << '\\n';\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1358",
    "index": "B",
    "title": "Maria Breaks the Self-isolation",
    "statement": "Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.\n\nShe has $n$ friends who are also grannies (Maria is not included in this number). The $i$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $a_i$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $i$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $a_i$.\n\nGrannies gather in the courtyard like that.\n\n- Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $1$). All the remaining $n$ grannies are still sitting at home.\n- On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $a_i$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard \\textbf{at the same moment of time}.\n- She cannot deceive grannies, that is, the situation when the $i$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $a_i$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance.\n\nYour task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!\n\nConsider an example: if $n=6$ and $a=[1,5,4,5,1,9]$, then:\n\n- at the first step Maria can call grannies with numbers $1$ and $5$, each of them will see two grannies at the moment of going out into the yard (note that $a_1=1 \\le 2$ and $a_5=1 \\le 2$);\n- at the second step, Maria can call grannies with numbers $2$, $3$ and $4$, each of them will see five grannies at the moment of going out into the yard (note that $a_2=5 \\le 5$, $a_3=4 \\le 5$ and $a_4=5 \\le 5$);\n- the $6$-th granny cannot be called into the yard  — therefore, the answer is $6$ (Maria herself and another $5$ grannies).",
    "tutorial": "Let $x$ be the maximum number of grannies that can go out to the yard. Then if Maria Ivanovna calls them all at the same time, then everyone will see $x$ grannies. Since $x$ is the maximum answer, then each granny of them satisfy $a_i \\le x$ (otherwise there's no way for these grannies to gather in the yard), that is, such call is correct. So it is always enough to call once. Note that if you order grannies by $a_i$, Maria Ivanovna will have to call $x$ first grannies from this list. She can take $x$ grannies if $a_x \\le x$ (otherwise, after all $x$ grannies arrived, the last one will leave). To find $x$ we can do a linear search. The overall compexity is $\\mathcal{O}(n\\log{n})$ per test.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> arr(n);\n    for (int &el : arr)\n        cin >> el;\n    sort(arr.begin(), arr.end());\n    for (int i = n - 1; i >= 0; i--) {\n        if (arr[i] <= i + 1) {\n            cout << i + 2 << '\\n';\n            return;\n        }\n    }\n    cout << 1 << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}\n",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1358",
    "index": "C",
    "title": "Celex Update",
    "statement": "During the quarantine, Sicromoft has more free time to create the new functions in \"Celex-2021\". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:\n\nThe cell with coordinates $(x, y)$ is at the intersection of $x$-th row and $y$-th column. Upper left cell $(1,1)$ contains an integer $1$.The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell $(x,y)$ in one step you can move to the cell $(x+1, y)$ or $(x, y+1)$.\n\nAfter another Dinwows update, Levian started to study \"Celex-2021\" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell $(x_1, y_1)$ to another given cell $(x_2, y_2$), if you can only move one cell down or right.\n\nFormally, consider all the paths from the cell $(x_1, y_1)$ to cell $(x_2, y_2)$ such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths.",
    "tutorial": "Let's look at the way with the minimum sum (first we go $y_2-y_1$ steps right, and then $x_2-x_1$ steps down). Let's look at such a change in the \"bends\" of the way: After each step, the sum on the way will increase by $1$. We're going to bend like this until we get to the maximum sum. We're not going to miss any possible sum, because we're incrementing the sum by 1. We started with the minimum sum and finished with the maximum sum, so we can use these changes to get all possible sums. In order for us to come from the minimum to the maximum way, we must bend the way exactly 1 time per each cell of table (except for the cells of the minimum way). That is, the number of changes equals the number of cells not belonging to the minimum way - $(x_2-x_1)\\cdot(y_2-y_1)$. Then the number of different sums will be $(x_2-x_1)\\cdot(y_2-y_1) + 1$. The overall compexity is $\\mathcal{O}(1)$ per test.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        long long a, b, c, d;\n        cin >> a >> b >> c >> d;\n        cout << (c - a) * (d - b) + 1 << '\\n';\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1358",
    "index": "D",
    "title": "The Best Vacation",
    "statement": "You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.\n\nYou immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly $x$ days and that's the exact number of days you will spend visiting your friend. You will spend exactly $x$ consecutive (successive) days visiting Coronavirus-chan.\n\nThey use a very unusual calendar in Naha: there are $n$ months in a year, $i$-th month lasts exactly $d_i$ days. Days in the $i$-th month are numbered from $1$ to $d_i$. There are no leap years in Naha.\n\nThe mood of Coronavirus-chan (and, accordingly, her desire to hug you) depends on the number of the day in a month. In particular, you get $j$ hugs if you visit Coronavirus-chan on the $j$-th day of the month.\n\nYou know about this feature of your friend and want to plan your trip to get as many hugs as possible (and then maybe you can win the heart of Coronavirus-chan).\n\nPlease note that your trip should \\textbf{not necessarily} begin and end in the same year.",
    "tutorial": "We will double the array of days and solve the problem when the day vacation starts and the day it ends is always in the same year. Then $a$ is an array of number of days in each of the months. Consider array $B = [1, 2, ..., a_1] + [1, 2, ..., a_2] + ... [1, 2, ..., a_n] + [1, 2, ..., a_n]$. Our task is to find a subsection of length $k$ with the maximum sum in it. Further we will call this segment optimal. Statement: We will find such an optimal segment that its end coincides with the end of some month. Proof by contradiction: Pretend that's not the case. Consider the rightmost optimal segment. Let its last element be $x$, then the next one is $x+1$, otherwise $x$ coincides with $a_i$. Note that if we move this segment to the right, the sum must be reduced, which means that the first element of the segment $>x+1$. Then its left neighbor $>x$. It means that you can move the segment by $1$ to the left so that the sum increases. So, the chosen segment is not optimal. Contradiction. (see picture) Solution: now we just need to go through all the possible ends of the segment, which are only $\\mathcal{O}(n)$. Let's build two arrays of prefix sums: $c_i = a_1 + a_2 + ... + a_i\\\\$ $d_i = \\frac{a_1 (a_1 + z)}{2} + ... + \\frac{a_i (a_i + 1)}{2}$ $c_i$ is responsible for the number of days before the $i$-th month, and $d_i$ is responsible for the sum of numbers of all days before the $i$-th month. For each of the n ends, let's make a binsearch to find which month contains its left border ($k$ days less than the right one). You can use array $c_i$ to check whether the left border lies to the left/in the block/to the right, and use array $d_i$ to restore the answer. The overall compexity is $\\mathcal{O}(n\\log{n})$.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\n\n#define int long long\n\nusing namespace std;\n\nsigned main() {\n  int n, len;\n  cin >> n >> len;\n  vector<int> A(2 * n);\n  for (int i = 0; i < n; i++) {\n    cin >> A[i];\n    A[n + i] = A[i];\n  }\n  n *= 2;\n  \n  vector<int> B = {0}, C = {0};\n  for (int i = 0; i < n; i++) \n    B.push_back(B.back() + A[i]);\n  for (int i = 0; i < n; i++) \n    C.push_back(C.back() + (A[i] * (A[i] + 1)) / 2);\n  int ans = 0;\n  for (int i = 0; i < n; i++) {\n    if (B[i + 1] >= len) {\n      int z = upper_bound(B.begin(), B.end(), B[i + 1] - len) - B.begin();\n      int cnt = C[i + 1] - C[z];\n      int days = B[i + 1] - B[z];\n      int too = len - days;\n      cnt += ((A[z - 1] * (A[z - 1] + 1)) / 2);\n      cnt -= (((A[z - 1] - too) * (A[z - 1] - too + 1)) / 2);\n      ans = max(ans, cnt);\n    }\n  }\n  cout << ans;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1358",
    "index": "E",
    "title": "Are You Fired?",
    "statement": "Levian works as an accountant in a large company. Levian knows how much the company has earned in each of the $n$ consecutive months — in the $i$-th month the company had income equal to $a_i$ (positive income means profit, negative income means loss, zero income means no change). Because of the general self-isolation, the first $\\lceil \\tfrac{n}{2} \\rceil$ months income might have been completely unstable, but then everything stabilized and for the last $\\lfloor \\tfrac{n}{2} \\rfloor$ months \\textbf{the income was the same}.\n\nLevian decided to tell the directors $n-k+1$ numbers — the total income of the company for each $k$ consecutive months. In other words, for each $i$ between $1$ and $n-k+1$ he will say the value $a_i + a_{i+1} + \\ldots + a_{i + k - 1}$. For example, if $a=[-1, 0, 1, 2, 2]$ and $k=3$ he will say the numbers $0, 3, 5$.\n\nUnfortunately, if at least one total income reported by Levian is not a profit (income $\\le 0$), the directors will get angry and fire the failed accountant.\n\nSave Levian's career: find any such $k$, that for each $k$ months in a row the company had made a profit, or report that it is impossible.",
    "tutorial": "Let's call the value of all elements in the second half of the array $x$. Let $s_i = a_i + a_{i+1} + \\ldots + a_{i+k-1}$ - the reported incomes. Pretend there exists such a $k$ that $k\\le\\tfrac{n}{2}$. Consider the following reported incomes: $s_i$ and $s_{i+k}$. Notice that if we double $k$, the $i$-th reported income will be equal to $s_i+s_{i+k}$. $s_i>0$ and $s_{i+k}>0$ imply $s_i+s_{i+k}>0$. It means that after doubling $k$, the new value will still be correct $\\ \\implies\\$ if some $k$ exists, there's also $k>\\tfrac{n}{2}$. Now, let's notice that $s_{i+1} = s_i + (a_{i + k} - a_i)$. It means we can think of $s_i$ as prefix sums of the following array: $\\\\p = [s_1,\\ a_{k+1}-a_1,\\ a_{k+2}-a_2,\\ \\ldots,\\ a_n - a_{n-k}]$. $\\\\$ As $k>\\tfrac{n}{2}$, $a_{k+j} = x$ holds for $j \\ge 0$, so, actually $\\\\p = [s_1,\\ x-a_1,\\ x-a_2,\\ \\ldots,\\ x-a_{n-k}]$. How is this array changed when we increment $k$ by 1? $\\\\p_{new} = [s_1+a_{k+1},\\ a_{k+2}-a_1,\\ a_{k+3}-a_2,\\ \\ldots,\\ a_n-a_{n-k-1}]$, which equals $[s_1+x,\\ x-a_1,\\ x-a_2,\\ \\ldots,\\ x-a_{n-k-1}]$. $\\\\$ So, when you increase $k$ by 1, the first element is changed, and the last element is removed - and that's it. Recall that $s_i = p_1 + p_2 + \\ldots + p_i$. Notice that the minimum reported income (some number from $s$) doesn't depend on the first element of $p$ because it's a term of all sums ($s_1, s_2, \\ldots$). For example, if $p_1$ is increased by $1$, all $s_i$ are increased by $1$ too. So, let's calculate the following array $m$: $\\\\$ $m_i = min(s_1-p_1, s_2-p_1, \\ldots, s_i-p_1) = min(0, p_2,\\ p_2+p_3,\\ \\ldots,\\ p_2+\\ldots+p_i)$. $\\\\$ This can be done in $\\mathcal{O}(n)$. Notice that this array is the same for all $k$, except its size. So, it's obvious that the minimum reported income for a particular $k$ is $p_1+m_{n-k+1}=a_1+\\ldots+a_k+m_{n-k+1}$. So, we can just check if this number is greater than $0$ for some $k$. We can calculate prefix sums and $m$ in $\\mathcal{O}(n)$, so the overall complexity is $\\mathcal{O}(n)$.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\n#define int long long\n\nsigned main() {\n  int n;\n  cin >> n;\n  int N = (n + 1) / 2;\n  vector<int> a(N);\n  for (int &el : a)\n    cin >> el;\n  int Ax;\n  cin >> Ax;\n  vector<int> m(N + 1, 0);\n  int Pprefsm = 0;\n  for (int i = 1; i < N + 1; ++i) {\n    Pprefsm += Ax - a[i - 1];\n    m[i] = min(m[i - 1], Pprefsm);\n  }\n  int Aprefsm = 0;\n  for (int k = 1; k <= N; ++k)\n    Aprefsm += a[k - 1];\n  for (int k = N; k <= n; ++k) {\n    if (Aprefsm + m[n - k] > 0)\n      return cout << k, 0;\n    Aprefsm += Ax;\n  }\n  cout << -1;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1358",
    "index": "F",
    "title": "Tasty Cookie",
    "statement": "Oh, no!\n\nThe coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem.\n\nYou are given two arrays $A$ and $B$ of size $n$. You can do operations of two types with array $A$:\n\n- Reverse array $A$. That is the array $[A_1,\\ A_2,\\ \\ldots,\\ A_n]$ transformes into $[A_n,\\ A_{n-1},\\ \\ldots,\\ A_1]$.\n- Replace $A$ with an array of its prefix sums. That is, the array $[A_1,\\ A_2,\\ \\ldots,\\ A_n]$ goes to $[A_1,\\ (A_1+A_2),\\ \\ldots,\\ (A_1+A_2+\\ldots+A_n)]$.\n\nYou need to understand if you can get an array $B$ from the array $A$. If it is possible, you will have to restore the order of these operations by minimizing the number of operations of the second type. Fortunately, the coronavirus is good today, so he has allowed you not to restore actions if the minimum number of second type operations is more than $2\\cdot 10^5$. But coronavirus resents you, so if you restore the answer, the total number of operations should not exceed $5\\cdot 10^5$.\n\nSolve this problem and get the cookie, or the coronavirus will extend the quarantine for five years and make the whole economy collapse!",
    "tutorial": "Let's define a few operations and constants: $pref$ - replace an array with its prefix sums array $reverse$ - reverse an array $rollback$ - restore the original array from a prefix sums array $C$ - the array values upper bound - $10^{12}$ First, we can prove that $rollback$ is unambiguosly defined for strictly increasing arrays. Consider an array $X$. Let $Y$ be the prefix sums array of $X$. Notice that $X_0 = Y_0$, $X_i = Y_i - Y_{i - 1}$ (for $i>1$). Thus we can restore $X$ from $Y$. Note that if we apply $rollback$ to an array for which $Y_i > Y_{i - 1}$ doesn't hold, the resulting array will have a non-positive element which is forbidden by the statements. Now let's analyze how many $pref$ operations can theoretically be applied for arrays of different lengths (let's call their count $t$) (We can do that by applying $pref$ to array $[1, 1, ..., 1]$ while all numbers are below $C$): It's obvious that we'll need no more than $t$ $rollback$s for an array of length $n$. It can also be proved that $t = \\mathcal{O}(\\sqrt[n-1]{C\\cdot(n-1)!})$. Let's restore the array $B$ in steps. One each step we have several cases: If $B$ equals $A$ or $reverse(A)$, we know how to get $A$ from $B$. If $B$ is strictly increasing, apply $rollback$. If $B$ is strictly decreasing, apply $reverse$. Otherwise, the answer is \"$impossible$\". This solution will run infinitely when $n=1$ and $A \\ne B$, so the case when $n=1$ has to be handled separately. The asymptotic of this solution is $\\mathcal{O}(n\\cdot ans)$. Notice that $ans \\le 2t+1$ because we can't have two $reverse$ operations in a row. It means this solution will fit into TL for $n \\ge 3$, but we need a separate solution for $n=2$. Consider an array $[x, y]$. If we $rollback$ it while $x<y$, the array will be transformed into $[x, y \\mod x]$. It means we can $rollback$ several iterations at once. So, the solution for $n=2$ is: First sort $A$ and $B$ so that they both increase (and take this into account when printing answer) Now start the $rollback$ loop: If $B_1=A_1$, we can break the loop if $(B_2 - A_2) \\mod B_1=0$, otherwise the answer is \"$impossible$\". If $B_1 \\ne A_1$, we can calculate how many $rollback$ operations we should apply to transform $B=[x, y]$ into $[x, y \\mod x]$, modify the answer accordingly and jump to the next iteration for $B=[y \\mod x, x]$ (after applying one $reverse$ operation). If $B_1=A_1$, we can break the loop if $(B_2 - A_2) \\mod B_1=0$, otherwise the answer is \"$impossible$\". If $B_1 \\ne A_1$, we can calculate how many $rollback$ operations we should apply to transform $B=[x, y]$ into $[x, y \\mod x]$, modify the answer accordingly and jump to the next iteration for $B=[y \\mod x, x]$ (after applying one $reverse$ operation). This algorithm is very similar to the Euclidian's algorithm, and that's how we can prove there will be $\\mathcal{O}(\\log C)$ $rollback$s. The overall complexity is $\\mathcal{O}(n\\cdot ans)$ for $n>2$; $\\mathcal{O}(\\log C)$ for $n=2$. Thank you, everyone, for participating in the round! We hope you've raised your rating! And if you haven't, don't be sad, you'll do it!",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n#define int long long\n\nsigned main() {\n  int n;\n  cin >> n;\n  vector<int> a(n), b(n);\n  for (int i = 0; i < n; ++i) cin >> a[i];\n  for (int i = 0; i < n; ++i) cin >> b[i];\n  if (n == 1) {\n    if (a[0] == b[0]) cout << \"SMALL\\n\" << 0;\n    else cout << \"IMPOSSIBLE\";\n    return 0;\n  }\n  if (n == 2) {\n    vector<pair<int, bool>> res;\n    int kol = 0;\n    while (true) {\n      if (b[0] == 0 || b[1] == 0) {\n        cout << \"IMPOSSIBLE\";\n        return 0;\n      }\n      if (a == b) break;\n      if (a[0] == b[1] && a[1] == b[0]) {\n        res.emplace_back(1, false);\n        break;\n      }\n      if (b[0] == b[1]) {\n        cout << \"IMPOSSIBLE\";\n        return 0;\n      }\n      if (b[0] > b[1]) {\n        res.emplace_back(1, false);\n        swap(b[0], b[1]);\n      }\n      if (a[0] == b[0] && a[1] < b[1] && a[1] % b[0] == b[1] % b[0]) {\n        res.emplace_back((b[1] - a[1]) / b[0], true);\n        kol += res.back().first;\n        break;\n      }\n      if (a[1] == b[0] && a[0] < b[1] && a[0] % b[0] == b[1] % b[0]) {\n        res.emplace_back((b[1] - a[0]) / b[0], true);\n        kol += res.back().first;\n        res.emplace_back(1, false);\n        break;\n      }\n      kol += b[1] / b[0];\n      res.emplace_back(b[1] / b[0], true);\n      b[1] %= b[0];\n    }\n    if (kol > 2e5) {\n      cout << \"BIG\\n\";\n      cout << kol;\n    } else {\n      cout << \"SMALL\\n\";\n      int flex = 0;\n      for (auto i : res) flex += i.first;\n      cout << flex << \"\\n\";\n      for (int i = res.size() - 1; i >= 0; --i) {\n        for (int j = 0; j < res[i].first; ++j) {\n          if (res[i].second) cout << \"P\";\n          else cout << \"R\";\n        }\n      }\n    }\n    return 0;\n  }\n  vector<bool> ans;\n  int kol = 0;\n  while (true) {\n    if (a == b) break;\n    reverse(b.begin(), b.end());\n    if (a == b) {\n      ans.push_back(false);\n      break;\n    }\n    reverse(b.begin(), b.end());\n    bool vozr = false, ub = false, r = false;\n    for (int i = 1; i < n; ++i) {\n      if (b[i] > b[i - 1]) vozr = true;\n      else if (b[i] < b[i - 1]) ub = true;\n      else r = true;\n    }\n    if (r || (vozr && ub)) {\n      cout << \"IMPOSSIBLE\";\n      return 0;\n    }\n    vector<int> c(n);\n    if (ub) {\n      ans.push_back(false);\n      reverse(b.begin(), b.end());\n    }\n    c[0] = b[0];\n    for (int i = 1; i < n; ++i) {\n      c[i] = b[i] - b[i - 1];\n    }\n    ans.push_back(true);\n    b = c;\n    ++kol;\n  }\n  if (kol > 2e5) {\n    cout << \"BIG\\n\" << kol;\n  } else {\n    cout << \"SMALL\\n\" << ans.size() << \"\\n\";\n    for (int i = ans.size() - 1; i >= 0; --i) {\n      if (ans[i]) cout << \"P\";\n      else cout << \"R\";\n    }\n  }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1359",
    "index": "A",
    "title": "Berland Poker",
    "statement": "The game of Berland poker is played with a deck of $n$ cards, $m$ of which are jokers. $k$ players play this game ($n$ is divisible by $k$).\n\nAt the beginning of the game, each player takes $\\frac{n}{k}$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $x - y$, where $x$ is the number of jokers in the winner's hand, and $y$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $0$ points.\n\nHere are some examples:\n\n- $n = 8$, $m = 3$, $k = 2$. If one player gets $3$ jokers and $1$ plain card, and another player gets $0$ jokers and $4$ plain cards, then the first player is the winner and gets $3 - 0 = 3$ points;\n- $n = 4$, $m = 2$, $k = 4$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $0$ points;\n- $n = 9$, $m = 6$, $k = 3$. If the first player gets $3$ jokers, the second player gets $1$ joker and $2$ plain cards, and the third player gets $2$ jokers and $1$ plain card, then the first player is the winner, and he gets $3 - 2 = 1$ point;\n- $n = 42$, $m = 0$, $k = 7$. Since there are no jokers, everyone gets $0$ jokers, everyone is a winner, and everyone gets $0$ points.\n\nGiven $n$, $m$ and $k$, calculate the maximum number of points a player can get for winning the game.",
    "tutorial": "There are many different ways to solve this problem. The easiest one, in my opinion, is to iterate on the number of jokers the winner has (let it be $a_1$) and the number of jokers the runner-up has (let it be $a_2$). Then the following conditions should be met: $a_1 \\ge a_2$ (the winner doesn't have less jokers than the runner-up); $a_1 \\le \\frac{n}{k}$ (the number of jokers in the winner's hand does not exceed the number of cards in his hand); $a_1 + a_2 \\le m$ (the number of jokers for these two players does not exceed the total number of jokers); $a_1 + (k - 1)a_2 \\ge m$ (it is possible to redistribute remaining jokers among other players so that they have at most $a_2$ jokers). Iterating on $a_1$ and $a_2$, then checking these constraints gives us a $O(n^2)$ solution. It is possible to get a constant-time solution using some greedy assumptions and math (the first player should get as many jokers as possible, while the remaining jokers should be evenly distributed among other players).",
    "code": "t = int(input())\n\nfor i in range(t):\n    n, m, k = map(int, input().split())\n    ans = 0\n    d = n // k\n    for a1 in range(m + 1):\n        for a2 in range(a1 + 1):\n            if(a1 > d):\n                continue\n            if(a1 + a2 > m):\n                continue\n            if(a1 + (k - 1) * a2 < m):\n                continue\n            ans = max(ans, a1 - a2)\n    print(ans)",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1359",
    "index": "B",
    "title": "New Theatre Square",
    "statement": "You might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.\n\nThe square still has a rectangular shape of $n \\times m$ meters. However, the picture is about to get more complicated now. Let $a_{i,j}$ be the $j$-th square in the $i$-th row of the pavement.\n\nYou are given the picture of the squares:\n\n- if $a_{i,j} = $ \"*\", then the $j$-th square in the $i$-th row should be \\textbf{black};\n- if $a_{i,j} = $ \".\", then the $j$-th square in the $i$-th row should be \\textbf{white}.\n\nThe black squares are paved already. You have to pave the white squares. There are two options for pavement tiles:\n\n- $1 \\times 1$ tiles — each tile costs $x$ burles and covers exactly $1$ square;\n- $1 \\times 2$ tiles — each tile costs $y$ burles and covers exactly $2$ adjacent squares of the \\textbf{same row}. \\textbf{Note that you are not allowed to rotate these tiles or cut them into $1 \\times 1$ tiles.}\n\n\\textbf{You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.}\n\nWhat is the smallest total price of the tiles needed to cover all the white squares?",
    "tutorial": "Notice that rows can be solved completely separately of each other. Each tile takes either one or two squares but it's always in the same row. So let's take a look at a single row. There are sequences of dot characters separated by some asterisks. Once again each of these sequences can be solved independently of the others. Thus, we have these empty strips of empty squares $1 \\times k$ which, when solved, can be summed up into the whole answer. There are two cases, depending on if a $1 \\times 2$ is cheaper than two $1 \\times 1$ tiles. If it is then we want to use of many $1 \\times 2$ tiles as possible. So given $k$, we can place $\\lfloor \\frac k 2 \\rfloor$ $1 \\times 2$ tiles and cover the rest $k - 2 \\cdot \\lfloor \\frac k 2 \\rfloor = k~mod~2$ squares with $1 \\times 1$ tiles. If it isn't cheaper then we want to cover everything with $1 \\times 1$ tiles and never use $1 \\times 2$ ones. So all $k$ should be $1 \\times 1$. The easier way to implement this might be the following. Let's update the price of the $1 \\times 2$ tile with the minimum of $y$ and $2 \\cdot x$. This way the first algorithm will produce exactly the same result of the second one in the case when a $1 \\times 2$ tile isn't cheaper than two $1 \\times 1$ ones. Overall complexity: $O(nm)$ per testcase.",
    "code": "t = int(input())\nfor _ in range(t):\n\tn, m, x, y = map(int, input().split())\n\tans = 0\n\ty = min(y, 2 * x)\n\tfor __ in range(n):\n\t\ts = input()\n\t\ti = 0\n\t\twhile i < m:\n\t\t\tif s[i] == '*':\n\t\t\t\ti += 1\n\t\t\t\tcontinue\n\t\t\tj = i\n\t\t\twhile j + 1 < m and s[j + 1] == '.':\n\t\t\t\tj += 1\n\t\t\tl = j - i + 1\n\t\t\tans += l % 2 * x + l // 2 * y\n\t\t\ti = j + 1\n\tprint(ans)",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1359",
    "index": "C",
    "title": "Mixing Water",
    "statement": "There are two infinite sources of water:\n\n- hot water of temperature $h$;\n- cold water of temperature $c$ ($c < h$).\n\nYou perform the following procedure of alternating moves:\n\n- take \\textbf{one} cup of the \\textbf{hot} water and pour it into an infinitely deep barrel;\n- take \\textbf{one} cup of the \\textbf{cold} water and pour it into an infinitely deep barrel;\n- take \\textbf{one} cup of the \\textbf{hot} water $\\dots$\n- and so on $\\dots$\n\n\\textbf{Note that you always start with the cup of hot water}.\n\nThe barrel is initially empty. You have to pour \\textbf{at least one cup} into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.\n\nYou want to achieve a temperature as close as possible to $t$. So if the temperature in the barrel is $t_b$, then the \\textbf{absolute difference} of $t_b$ and $t$ ($|t_b - t|$) should be as small as possible.\n\nHow many cups should you pour into the barrel, so that the temperature in it is as close as possible to $t$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.",
    "tutorial": "Idea: adedalic So there are two kinds of stops to consider: $k$ hot and $k$ cold cup and $(k + 1)$ hot and $k$ cold cups. The first case is trivial: the temperature is always $\\frac{h + c}{2}$. In the second case the temperature is always strictly greater than $\\frac{h + c}{2}$. Thus, if $t \\le \\frac{h + c}{2}$, then the answer is $2$. Let's show that otherwise the answer is always achieved through the second case. The temperature after $(k + 1)$ hot cups and $k$ cold cups is $t_k = \\frac{(k + 1) \\cdot h + k \\cdot c}{2k + 1}$. The claim is that $t_0 > t_1 > \\dots$. Let's prove that by induction. $t_0 = h, t_1 = \\frac{2 \\cdot h + c}{3}$. $c < h$, thus $t_0 > t_1$. Now compare $t_k$ and $t_{k+1}$. $t_k > t_{k+1}$ $\\frac{(k + 1) \\cdot h + k \\cdot c}{2k + 1} > \\frac{(k + 2) \\cdot h + (k + 1) \\cdot c}{2k + 3}$ $\\frac{k \\cdot (h + c) + h}{2k + 1} > \\frac{(k + 1) \\cdot (h + c) + h}{2k + 3}$ $2k \\cdot (k \\cdot (h + c) + h) + 3k \\cdot (h + c) + 3h > 2k \\cdot ((k + 1) \\cdot (h + c) + h) + (k + 1) \\cdot (h + c) + h$ $2k \\cdot (k \\cdot (h + c) + h - (k + 1) \\cdot (h + c) - h) > (k + 1) \\cdot (h + c) + h - 3k \\cdot (h + c) - 3h$ $2k \\cdot (-(h + c)) > (-2k + 1) \\cdot (h + c) - 2h$ $2h > (h + c)$ $h > c$ We can also show that this series converges to $\\frac{h + c}{2}$: I'm sorry that I'm not proficient with any calculus but my intuition says that it's enough to show that $\\forall k~t_k > \\frac{h + c}{2}$ and $\\forall \\varepsilon \\exists k~t_k < \\frac{h + c}{2}$ with $k \\ge 0$. So the first part is: $\\frac{(k + 1) \\cdot h + k \\cdot c}{2k + 1} > \\frac{h + c}{2}$ $\\frac{k \\cdot (h + c) + h}{2k + 1} > \\frac{h + c}{2}$ $2k \\cdot (h + c) + 2h > (2k + 1) \\cdot (h + c)$ $2h > h + c$ $h > c$ And the second part is: $\\frac{(k + 1) \\cdot h + k \\cdot c}{2k + 1} < \\frac{h + c}{2} + \\varepsilon$ $\\frac{k \\cdot (h + c) + h}{2k + 1} < \\frac{h + c}{2} + \\varepsilon$ $2k \\cdot (h + c) + 2h < (2k + 1) \\cdot (h + c) + (2k + 1) \\cdot \\varepsilon$ $2h < (h + c) + (2k + 1) \\cdot \\varepsilon$ $h < c + (2k + 1) \\cdot \\varepsilon$ $\\frac{h - c}{\\varepsilon} < 2k + 1$ So that claim makes us see that for any $t$ greater than $\\frac{h + c}{2}$ the answer is always achieved from the second case. That allows us to find such $k$, that the value of $t_k$ is exactly $t$. However, such $k$ might not be integer. $\\frac{(k + 1) \\cdot h + k \\cdot c}{2k + 1} = t \\leftrightarrow$ $\\frac{k \\cdot (h + c) + h}{2k + 1} = t \\leftrightarrow$ $k \\cdot (h + c) + h = 2kt + t \\leftrightarrow$ $k \\cdot (h + c - 2t) = t - h \\leftrightarrow$ $k = \\frac{t - h}{h + c - 2t}$. The only thing left is to compare which side is better to round $k$ to. It seems some implementations with float numbers might fail due to precision errors. However, it's possible to do these calculations completely in integers. Let's actually rewrite that so that the denominator is always positive $k = \\frac{h - t}{2t - h - c}$. Now we can round this value down and compare $k$ and $k + 1$. So the optimal value is $k$ if $|\\frac{k \\cdot (h + c) + h}{2k + 1} - t| \\le |\\frac{(k + 1) \\cdot (h + c) + h}{2k + 3} - t|$. So $|(k \\cdot (h + c) + h) - t \\cdot (2k + 1)| \\cdot (2k + 3) \\le |((k + 1) \\cdot (h + c) + h) - t \\cdot (2k + 3)| \\cdot (2k + 1)$. Otherwise, the answer is $k + 1$. You can also find the optimal $k$ with binary search but the formulas are exactly the same and you have to rely on monotonosity as well. Also, these formulas can get you the better understanding for the upper bound of the answer. Overall complexity: $O(1)$ or $O(\\log h)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n\tint tc;\n\tscanf(\"%d\", &tc);\n\tforn(_, tc){\n\t\tint h, c, t;\n\t\tscanf(\"%d%d%d\", &h, &c, &t);\n\t\tif (h + c - 2 * t >= 0)\n\t\t\tputs(\"2\");\n\t\telse{\n\t\t\tint a = h - t;\n\t\t\tint b = 2 * t - c - h;\n\t\t\tint k = 2 * (a / b) + 1;\n\t\t\tlong long val1 = abs(k / 2 * 1ll * c + (k + 1) / 2 * 1ll * h - t * 1ll * k);\n\t\t\tlong long val2 = abs((k + 2) / 2 * 1ll * c + (k + 3) / 2 * 1ll * h - t * 1ll * (k + 2));\n\t\t\tprintf(\"%d\\n\", val1 * (k + 2) <= val2 * k ? k : k + 2);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1359",
    "index": "D",
    "title": "Yet Another Yet Another Task",
    "statement": "Alice and Bob are playing yet another card game. This time the rules are the following. There are $n$ cards lying in a row in front of them. The $i$-th card has value $a_i$.\n\nFirst, Alice chooses a non-empty consecutive segment of cards $[l; r]$ ($l \\le r$). After that Bob removes a single card $j$ from that segment $(l \\le j \\le r)$. The score of the game is the total value of the remaining cards on the segment $(a_l + a_{l + 1} + \\dots + a_{j - 1} + a_{j + 1} + \\dots + a_{r - 1} + a_r)$. In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is $0$.\n\nAlice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.\n\nWhat segment should Alice choose so that the score is maximum possible? Output the maximum score.",
    "tutorial": "Alice wants to choose such a segment $[l; r]$ that $\\sum \\limits_{l \\le i \\le r} a_i - \\max \\limits_{l \\le i \\le r} a_i$ is maximum possible. There is a well-known problem where you have to find a segment with maximum $\\sum \\limits_{l \\le i \\le r} a_i$. That problem is solved with Kadane algorithm. Let's learn how to reduce our problem to that one. Notice that the values in the array are unusually small. Let's iterate over the maximum value on segment. Let $mx$ be the current value. If we make all $a_i$ such that $a_i > mx$ equal to $-\\infty$, then it will never be optimal to take them in a segment. Find the maximum sum subarray in that modified array and update the answer with its $sum - mx$. Notice that you can ignore the fact if there is a value exactly equal to $mx$ on the maximum sum segment. If there isn't then you'll update the answer with a smaller value than the actual one. Let the actual maximum on the maximum sum segment be some $y$. You can see that for any value between $y$ and $mx$ the maximum sum segment will always be that chosen one. Thus, when you reach $y$, you'll update the answer with the correct value. Overall complexity: $O(\\max a_i \\cdot n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tlong long ans = 0;\n\tforn(mx, 31){\n\t\tlong long cur = 0;\n\t\tlong long best = 0;\n\t\tforn(i, n){\n\t\t\tint val = (a[i] > mx ? -INF : a[i]);\n\t\t\tcur += val;\n\t\t\tbest = min(best, cur);\n\t\t\tans = max(ans, (cur - best) - mx);\n\t\t}\n\t}\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1359",
    "index": "E",
    "title": "Modular Stability",
    "statement": "We define $x \\bmod y$ as the remainder of division of $x$ by $y$ ($\\%$ operator in C++ or Java, mod operator in Pascal).\n\nLet's call an array of positive integers $[a_1, a_2, \\dots, a_k]$ stable if for every permutation $p$ of integers from $1$ to $k$, and for every non-negative integer $x$, the following condition is met:\n\n\\begin{center}\n$ (((x \\bmod a_1) \\bmod a_2) \\dots \\bmod a_{k - 1}) \\bmod a_k = (((x \\bmod a_{p_1}) \\bmod a_{p_2}) \\dots \\bmod a_{p_{k - 1}}) \\bmod a_{p_k} $\n\\end{center}\n\nThat is, for each non-negative integer $x$, the value of $(((x \\bmod a_1) \\bmod a_2) \\dots \\bmod a_{k - 1}) \\bmod a_k$ does not change if we reorder the elements of the array $a$.\n\nFor two given integers $n$ and $k$, calculate the number of stable arrays $[a_1, a_2, \\dots, a_k]$ such that $1 \\le a_1 < a_2 < \\dots < a_k \\le n$.",
    "tutorial": "We claim that the array is stable if and only if all elements are divisible by its minimum. The proof of this fact will be at the end of the editorial. To calculate the number of stable arrays now, we need to iterate on the minimum in the array and choose the remaining elements so that they are multiples of it. If the minimum is $i$, then the resulting elements should be divisible by $i$. There are $d = \\lfloor\\frac{n}{i}\\rfloor$ such numbers between $1$ and $n$, and we have to choose $k - 1$ elements out of $d - 1$ (since $i$ is already chosen). The number of ways to do it can be calculated by precomputing factorials modulo $998244353$, since it is a binomial coefficient. Proof of the claim at the beginning of the editorial: On the one hand, since $(x \\bmod a) \\bmod (ba) = (x \\bmod (ba)) \\bmod a = x \\bmod a$, if all elements in the array are divisible by some element, nothing depends on the order of these elements. On the other hand, suppose there exists an element $a_i$ such that it is not divisible by $a_1$. Let's take $x = a_i$ and two following reorders of the array $a$: $[a_1, a_2, \\dots, a_k]$ and $[a_i, a_1, a_2, \\dots, a_{i - 1}, a_{i + 1}, \\dots, a_k]$. For the first array, we get $x \\bmod a_1 = a_i \\bmod a_1$, which is non-zero; and for the second array, $a_i \\bmod a_i = 0$, so the result is zero.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 500043;\nconst int MOD = 998244353;\n\nint fact[N];\n\nint add(int x, int y)\n{\n\tx += y;\n\twhile(x >= MOD) x -= MOD;\n\twhile(x < 0) x += MOD;\n\treturn x;\n}\n\nint mul(int x, int y)\n{\n\treturn (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n\tint z = 1;\n\twhile(y > 0)\n\t{\n\t\tif(y % 2 == 1)\n\t\t\tz = mul(z, x);\n\t\tx = mul(x, x);\n\t\ty /= 2;\n\t}\n\treturn z;\n}\n\nint inv(int x)\n{\n\treturn binpow(x, MOD - 2);\n}\n\nint divide(int x, int y)\n{\n\treturn mul(x, inv(y));\n}\n\nvoid precalc()\n{\n\tfact[0] = 1;\n\tfor(int i = 1; i < N; i++)\n\t\tfact[i] = mul(i, fact[i - 1]);\n}\n\nint C(int n, int k)\n{\n\tif(k > n) return 0;\n\treturn divide(fact[n], mul(fact[n - k], fact[k]));\n}\n\nint main()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tint ans = 0;\n\tprecalc();\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tint d = n / i;\n\t\tans = add(ans, C(d - 1, k - 1));\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1359",
    "index": "F",
    "title": "RC Kaboom Show",
    "statement": "You know, it's hard to conduct a show with lots of participants and spectators at the same place nowadays. Still, you are not giving up on your dream to make a car crash showcase! You decided to replace the real cars with remote controlled ones, call the event \"Remote Control Kaboom Show\" and stream everything online.\n\nFor the preparation you arranged an arena — an infinite 2D-field. You also bought $n$ remote controlled cars and set them up on the arena. Unfortunately, the cars you bought can only go forward without turning left, right or around. So you additionally put the cars in the direction you want them to go.\n\nTo be formal, for each car $i$ ($1 \\le i \\le n$) you chose its initial position ($x_i, y_i$) and a direction vector ($dx_i, dy_i$). Moreover, each car has a constant speed $s_i$ units per second. So after car $i$ is launched, it stars moving from ($x_i, y_i$) in the direction ($dx_i, dy_i$) with constant speed $s_i$.\n\nThe goal of the show is to create a car collision as fast as possible! You noted that launching every car at the beginning of the show often fails to produce any collisions at all. Thus, you plan to launch the $i$-th car at some moment $t_i$. \\textbf{You haven't chosen $t_i$, that's yet to be decided.} Note that it's not necessary for $t_i$ to be integer and $t_i$ is allowed to be equal to $t_j$ for any $i, j$.\n\nThe show starts at time $0$. The show ends when two cars $i$ and $j$ ($i \\ne j$) collide (i. e. come to the same coordinate at the same time). The duration of the show is the time between the start and the end.\n\nWhat's the fastest crash you can arrange by choosing all $t_i$? If it's possible to arrange a crash then print the shortest possible duration of the show. Otherwise, report that it's impossible.",
    "tutorial": "Let $f(t)$ be true if it's possible to have a collision before time $t$. That function is monotonous, thus let's binary search for $t$. For some fixed $t$ car $i$ can end up in any point from $(x_i, y_i)$ to $s_i \\cdot t$ units along the ray $((x_i, y_i), (x_i + dx_i, y_i + dy_i))$. That makes it a segment. So the collision can happen if some pair of segments intersects. Let's learn how to find that out. The general idea is to use sweep line. So let's add the events that the $i$-th segment $(x1_i, y1_i, x2_i, y2_i)$ such that $x1_i < x2_i$ opens at $x1_i$ and closes at $x2_i$. There were no vertical segments, so $x1_i$ and $x2_i$ are always different. At every moment of time $T$ we want to maintain the segments ordered by their intersection with the line $x = T$. Note that if two segments change their order moving along the sweep line, then they intersect. So we can maintain a set with a custom comparator that returns if one segment intersects the current line lower than the other one. When adding a segment to set, you want to check it's intersections with the next segment in the order and the previous one. When removing a segment, you want to check the intersection between the next and the previous segment in the order. If any check triggers, then return true immediately. It's easy to show that if the intersection happens between some pair of segments, then the intersection between only these pairs of segment also happens. Now for the implementation details. Precision errors play a huge role here since we use binary search and also store some stuff dependant on floats in the set. The solution I want to tell requires no epsilon comparisons, thus it calculates the answer only with the precision of binary search. So the first issue rises when we have to erase elements from the set. Notice that we can make a mistake when we are adding the segment and there is a segment with almost the same intersection point. That will not make the answer incorrect (that's not trivial to show but it's possible if you consider some cases). If you can find it later to remove, then it's not an issue at all. However, that will probably mess up the lower_bound in the set. Thus, let's save the pointer to each element in the set and remove it later by that pointer. The second issue comes when you have to check the intersection of two segments. The error might appear when one segment $((x_i, y_i), (nx_i, ny_i))$ (let the first point be the original $(x_i, y_i)$ and the second point be calculated depending on $t$) has it's intersection point with segment $((x_j, y_j), (nx_j, ny_j))$ at exactly $(x_i, y_i)$. So the slightest miscalculations could matter a lot. Let's learn to intersect in such a way that no epsilon comparisons are required. Firstly, we can store lines in the set instead of segments. Second, we can check the intersection of rays first and only then proceed to check the intersection of segments. So two rays intersect if: their lines intersect - easy to check in integers; the intersection point lies in the correct direction of both rays - the intersection point is always a pair of fractions $(\\frac{Dx}{D}, \\frac{Dy}{D})$ and you want to compare the signs of $dx_i$ and $\\frac{Dx}{D} - x_i$. Finally, if all the checks hold, then you can compare maximum of distances from $(x_i, y_i)$ and $(x_j, y_j)$ to the intersection point and $t$. If $t$ is greater or equal then they intersect in time. There is no way to make that comparison in integers. However, it's precision only depends on the precision of $t$ as in the error here can't affect the answer greatly. Overall complexity: $O(n \\log n \\log maxt)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define x first\n#define y second\n\nusing namespace std;\n\nconst double INF = 1e13;\n\nstruct line{\n\tint A, B, C;\n\tline(){}\n\tline(int x1, int y1, int x2, int y2){\n\t\tA = y1 - y2;\n\t\tB = x2 - x1;\n\t\tC = -A * x1 - B * y1;\n\t\t// A is guaranteed to be non-zero\n\t\tif (A < 0) A = -A, B = -B, C = -C;\n\t\tint g = __gcd(A, __gcd(abs(B), abs(C)));\n\t\tA /= g, B /= g, C /= g;\n\t}\n};\n\nbool operator ==(const line &a, const line &b){\n\treturn a.A == b.A && a.B == b.B && a.C == b.C;\n}\n\ndouble x;\n\nbool operator <(const line &a, const line &b){\n\tdouble val1 = (-a.A * x - a.C) / a.B;\n\tdouble val2 = (-b.A * x - b.C) / b.B;\n\treturn val1 < val2;\n}\n\nstruct car{\n\tint x, y, dx, dy, s;\n\tline l;\n\tdouble vx, vy;\n};\n\nint n;\nvector<car> a(n);\n\nlong long det(int a, int b, int c, int d){\n\treturn a * 1ll * d - b * 1ll * c;\n}\n\nbool inter(const line &a, const line &b, long long &D, long long &Dx, long long &Dy){\n\tD = det(a.A, a.B, b.A, b.B);\n\tif (D == 0) return false;\n\tDx = -det(a.C, a.B, b.C, b.B);\n\tDy = -det(a.A, a.C, b.A, b.C);\n\treturn true;\n}\n\nint sg(int x){\n\treturn x < 0 ? -1 : 1;\n}\n\nint sg(long long a, long long b, int c){\n\t// sign of a/b-c\n\tif (b < 0) a = -a, b = -b;\n\treturn a - c * b < 0 ? -1 : (a - c * b > 0);\n}\n\nbool inter(int i, int j, double &len){\n\tif (i == -1 || j == -1)\n\t\treturn false;\n\tlong long D, Dx, Dy;\n\tif (!inter(a[i].l, a[j].l, D, Dx, Dy))\n\t\treturn false;\n\tif (sg(Dx, D, a[i].x) != 0 && sg(a[i].dx) != sg(Dx, D, a[i].x))\n\t\treturn false;\n\tif (sg(Dx, D, a[j].x) != 0 && sg(a[j].dx) != sg(Dx, D, a[j].x))\n\t\treturn false;\n\tdouble x = Dx / double(D);\n\tdouble y = Dy / double(D);\n\tdouble di = (a[i].x - x) * (a[i].x - x) + (a[i].y - y) * (a[i].y - y);\n\tdouble dj = (a[j].x - x) * (a[j].x - x) + (a[j].y - y) * (a[j].y - y);\n\treturn len * len >= di / a[i].s && len * len >= dj / a[j].s;\n}\n\nvector<set<pair<line, int>>::iterator> del;\nset<pair<line, int>> q;\n\nvoid get_neighbours(int i, int &l, int &r){\n\tl = r = -1;\n\tauto it = q.lower_bound({a[i].l, -1});\n\tif (it != q.end())\n\t\tr = it->y;\n\tif (!q.empty() && it != q.begin()){\n\t\t--it;\n\t\tl = it->y;\n\t}\n}\n\nbool check(double t){\n\tvector<pair<double, pair<int, int>>> cur;\n\tdel.resize(n);\n\tforn(i, n){\n\t\tdouble x1 = a[i].x;\n\t\tdouble x2 = a[i].x + a[i].vx * t;\n\t\tif (x1 > x2) swap(x1, x2);\n\t\tcur.push_back({x1, {i, 0}});\n\t\tcur.push_back({x2, {i, 1}});\n\t}\n\tq.clear();\n\t\n\tsort(cur.begin(), cur.end());\n\tfor (auto &qr : cur){\t\t\n\t\tx = qr.x;\n\t\tint i = qr.y.x;\n\t\tint l, r;\n\t\t\n\t\tif (qr.y.y == 0){\n\t\t\tget_neighbours(i, l, r);\n\t\t\t\n\t\t\tif (r != -1 && a[i].l == a[r].l)\n\t\t\t\treturn true;\n\t\t\tif (inter(i, l, t))\n\t\t\t\treturn true;\n\t\t\tif (inter(i, r, t))\n\t\t\t\treturn true;\n\t\t\t\n\t\t\tdel[i] = q.insert({a[i].l, i}).x;\n\t\t}\n\t\telse{\t\t\t\n\t\t\tq.erase(del[i]);\n\t\t\tget_neighbours(i, l, r);\n\t\t\t\n\t\t\tif (inter(l, r, t))\n\t\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\ta.resize(n);\n\tforn(i, n){\n\t\tscanf(\"%d%d%d%d%d\", &a[i].x, &a[i].y, &a[i].dx, &a[i].dy, &a[i].s);\n\t\ta[i].l = line(a[i].x, a[i].y, a[i].x + a[i].dx, a[i].y + a[i].dy);\n\t\tdouble d = sqrt(a[i].dx * a[i].dx + a[i].dy * a[i].dy);\n\t\ta[i].vx = a[i].dx / d * a[i].s;\n\t\ta[i].vy = a[i].dy / d * a[i].s;\n\t\ta[i].s *= a[i].s;\n\t}\n\tdouble l = 0, r = INF;\n\tbool ok = false;\n\tforn(_, 100){\n\t\tdouble m = (l + r) / 2;\n\t\tif (check(m)){\n\t\t\tok = true;\n\t\t\tr = m;\n\t\t}\n\t\telse{\n\t\t\tl = m;\n\t\t}\n\t}\n\tif (!ok)\n\t\tputs(\"No show :(\");\n\telse\n\t\tprintf(\"%.15lf\\n\", l);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "geometry",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1360",
    "index": "A",
    "title": "Minimal Square",
    "statement": "Find the minimum area of a \\textbf{square} land on which you can place two identical rectangular $a \\times b$ houses. The sides of the houses should be parallel to the sides of the desired square land.\n\nFormally,\n\n- You are given two identical rectangles with side lengths $a$ and $b$ ($1 \\le a, b \\le 100$) — positive integers (you are given just the sizes, but \\textbf{not} their positions).\n- Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square.\n\nTwo rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding.\n\n\\begin{center}\n{\\small The picture shows a square that contains red and green rectangles.}\n\\end{center}",
    "tutorial": "Obviously that both rectangles should completely touch by one of the sides. Otherwise, you can move them closer to each other so that the total height or total width decreases, and the other dimension does not change. Thus, there are only two options: The rectangles touch by width, we get the side of the square equal to $\\max(2b, a)$, The rectangles touch by height, we get the side of the square equal to $\\max(2a, b)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint solve(int a, int b) {\n    int side = min(max(a * 2, b), max(a, b * 2));\n    return side * side;\n}\n\nint main(int argc, char* argv[]) {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int a, b;\n        cin >> a >> b;\n        cout << solve(a, b) << endl;\n    }\n}\n",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1360",
    "index": "B",
    "title": "Honest Coach",
    "statement": "There are $n$ athletes in front of you. Athletes are numbered from $1$ to $n$ from left to right. You know the strength of each athlete — the athlete number $i$ has the strength $s_i$.\n\nYou want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.\n\nYou want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $A$ and $B$ so that the value $|\\max(A) - \\min(B)|$ is as small as possible, where $\\max(A)$ is the maximum strength of an athlete from team $A$, and $\\min(B)$ is the minimum strength of an athlete from team $B$.\n\nFor example, if $n=5$ and the strength of the athletes is $s=[3, 1, 2, 6, 4]$, then one of the possible split into teams is:\n\n- first team: $A = [1, 2, 4]$,\n- second team: $B = [3, 6]$.\n\nIn this case, the value $|\\max(A) - \\min(B)|$ will be equal to $|4-3|=1$. This example illustrates one of the ways of optimal split into two teams.\n\nPrint the minimum value $|\\max(A) - \\min(B)|$.",
    "tutorial": "Let's found two athletes with numbers $a$ and $b$ (the strength of $a$ is not greater than the strength of $b$), which have the minimal modulus of the difference of their strength. Obviously, we cannot get an answer less than this. Let's show how to get the partition with exactly this answer. Sort all athletes by strength. Our two athletes will stand in neighboring positions (otherwise, we can decrease the answer). Let the first team contains all athletes who stand on positions not further than $a$, and the second team contains other athletes. We got a partition, in which the athlete with number $a$ has the maximal strength in the first team, and the athlete with number $b$ has the minimal strength in the second team.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint test;\n\tcin >> test;\n\n\tfor (int tt = 0; tt < test; tt++) {\n\t\tint n;\n\t\tcin >> n;\n\n\t\tvector<int> a(n);\n\n\t\tfor (int &x : a) {\n\t\t\tcin >> x;\n\t\t}\n\n\t\tsort(a.begin(), a.end());\n\n\t\tint result = a[n - 1] - a[0];\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\t\tresult = min(result, a[j] - a[i]);\n\t\t\t}\n\t\t}\n\n\t\tcout << result << endl;\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1360",
    "index": "C",
    "title": "Similar Pairs",
    "statement": "We call two numbers $x$ and $y$ similar if they have the same parity (the same remainder when divided by $2$), or if $|x-y|=1$. For example, in each of the pairs $(2, 6)$, $(4, 3)$, $(11, 7)$, the numbers are similar to each other, and in the pairs $(1, 4)$, $(3, 12)$, they are not.\n\nYou are given an array $a$ of $n$ ($n$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.\n\nFor example, for the array $a = [11, 14, 16, 12]$, there is a partition into pairs $(11, 12)$ and $(14, 16)$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.",
    "tutorial": "Let $e$ - be the number of even numbers in the array, and $o$ - be the number of odd numbers in the array. Note that if the parities of $e$ and of $o$ do not equal, then the answer does not exist. Otherwise, we consider two cases: $e$ and $o$ - are even numbers. Then all numbers can be combined into pairs of equal parity. $e$ and $o$ - are odd numbers. Then you need to check whether there are two numbers in the array such that the modulus of their difference is $1$. If there are two such numbers, then combine them into one pair. $e$ and $o$ will decrease by $1$ and become even, then the solution exists as shown in the previous case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ld = long double;\nusing ll = long long;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> v(n);\n    int a = 0, b = 0;\n    for (int &e : v) {\n        cin >> e;\n        if (e % 2 == 0) {\n            a++;\n        } else {\n            b++;\n        }\n    }\n    if (a % 2 != b % 2) {\n        cout << \"NO\\n\";\n    } else {\n        if (a % 2 == 0) {\n            cout << \"YES\\n\";\n        } else {\n            for (int i = 0; i < n; i++) {\n                for (int j = i + 1; j < n; j++) {\n                    if (v[i] % 2 != v[j] % 2 && abs(v[i] - v[j]) == 1) {\n                        cout << \"YES\\n\";\n                        return;\n                    }\n                }\n            }\n            cout << \"NO\\n\";\n        }\n    }\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "graph matchings",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1360",
    "index": "D",
    "title": "Buying Shovels",
    "statement": "Polycarp wants to buy \\textbf{exactly} $n$ shovels. The shop sells packages with shovels. The store has $k$ types of packages: the package of the $i$-th type consists of exactly $i$ shovels ($1 \\le i \\le k$). The store has an infinite number of packages of each type.\n\nPolycarp wants to choose \\textbf{one} type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $n$ shovels?\n\nFor example, if $n=8$ and $k=7$, then Polycarp will buy $2$ packages of $4$ shovels.\n\nHelp Polycarp find the minimum number of packages that he needs to buy, given that he:\n\n- will buy exactly $n$ shovels in total;\n- the sizes of \\textbf{all} packages he will buy are all the same and the number of shovels in each package is an integer from $1$ to $k$, inclusive.",
    "tutorial": "If Polycarp buys $a$ packages of $b$ shovels and gets exactly $n$ shovels in total, then $a \\cdot b = n$, that is, $a$ and $b$ are divisors of $n$. Then the problem reduces to the following, you need to find the maximum divisor of the number $n$ not greater than $k$. To do this, iterate over all the numbers $x$ from $1$ to $\\sqrt n$ inclusive and check whether $n$ is divisible by $x$. If so, then $x$ and $\\frac{n}{x}$ - are both divisors of $n$ and you can use them to try to improve the answer.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint test;\n\tcin >> test;\n\n\tfor (int tt = 0; tt < test; tt++) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\n\t\tint ans = n;\n\n\t\tfor (int j = 1; j * j <= n; j++) {\n\t\t\tif (n % j == 0) {\n\t\t\t\tif (j <= k) {\n\t\t\t\t\tans = min(ans, n / j);\n\t\t\t\t}\n\n\t\t\t\tif (n / j <= k) {\n\t\t\t\t\tans = min(ans, j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcout << ans << endl;\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1360",
    "index": "E",
    "title": "Polygon",
    "statement": "Polygon is not only the best platform for developing problems but also a square matrix with side $n$, initially filled with the character 0.\n\nOn the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $2n$ cannons were placed.\n\n\\begin{center}\n{\\small Initial polygon for $n=4$.}\n\\end{center}\n\nCannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.\n\nMore formally:\n\n- if a cannon stands in the row $i$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($i, 1$) and ends in some cell ($i, j$);\n- if a cannon stands in the column $j$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($1, j$) and ends in some cell ($i, j$).\n\nFor example, consider the following sequence of shots:\n\n\\begin{center}\n{\\small 1. Shoot the cannon in the row $2$.                         2. Shoot the cannon in the row $2$.                         3. Shoot the cannon in column $3$.}\n\\end{center}\n\nYou have a report from the military training on your desk. This report is a square matrix with side length $n$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?\n\nEach cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.",
    "tutorial": "Let's see how the matrix looks like after some sequence of shoots: The matrix consists of 0, or There is at least one 1 at position ($n, i$) or ($i, n$), and any 1 not at position ($n, j$) or ($j, n$) must have 1 below or right. If the second condition is violated, then the 1 in the corresponding cell would continue its flight. Thus, it is necessary and sufficient to verify that the matrix satisfies the condition above.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool a[50][50];\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests--) {\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        char c;\n        cin >> c;\n        a[i][j] = c - '0';\n      }\n    }\n\n    bool ans = true;\n    for (int i = n - 2; i >= 0; --i) {\n      for (int j = n - 2; j >= 0; --j) {\n        if (a[i][j] && !a[i + 1][j] && !a[i][j + 1]) {\n          ans = false;\n        }\n      }\n    }\n\n    cout << (ans ? \"YES\" : \"NO\") << endl;\n  }\n}",
    "tags": [
      "dp",
      "graphs",
      "implementation",
      "shortest paths"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1360",
    "index": "F",
    "title": "Spy-string",
    "statement": "You are given $n$ strings $a_1, a_2, \\ldots, a_n$: all of them have the same length $m$. The strings consist of lowercase English letters.\n\nFind any string $s$ of length $m$ such that each of the given $n$ strings differs from $s$ in at most one position. Formally, for each given string $a_i$, there is no more than one position $j$ such that $a_i[j] \\ne s[j]$.\n\nNote that the desired string $s$ may be equal to one of the given strings $a_i$, or it may differ from all the given strings.\n\nFor example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.",
    "tutorial": "Consider all strings that differ from the first one in no more than one position (this is either the first string or the first string with one character changed). We will go through all such strings and see if they can be the answer. To do this, go through all the strings and calculate the number of positions where they differ.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ld = long double;\nusing ll = long long;\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<string> v(n);\n    for (int i = 0; i < n; i++) {\n        cin >> v[i];\n    }\n    string ans = v[0];\n    for (int j = 0; j < m; j++) {\n        char save = ans[j];\n        for (char d = 'a'; d <= 'z'; d++) {\n            ans[j] = d;\n            bool flag = true;\n            for (int z = 0; z < n; z++) {\n                int cntErrors = 0;\n                for (int c = 0; c < m; c++) {\n                    if (v[z][c] != ans[c]) {\n                        cntErrors++;\n                    }\n                }\n                if (cntErrors > 1) {\n                    flag = false;\n                    break;\n                }\n            }\n            if (flag) {\n                cout << ans << endl;\n                return;\n            }\n        }\n        ans[j] = save;\n    }\n    cout << \"-1\" << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dp",
      "hashing",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1360",
    "index": "G",
    "title": "A/B Matrix",
    "statement": "You are given four positive integers $n$, $m$, $a$, $b$ ($1 \\le b \\le n \\le 50$; $1 \\le a \\le m \\le 50$). Find any such rectangular matrix of size $n \\times m$ that satisfies all of the following conditions:\n\n- each row of the matrix contains exactly $a$ ones;\n- each column of the matrix contains exactly $b$ ones;\n- all other elements are zeros.\n\nIf the desired matrix does not exist, indicate this.\n\nFor example, for $n=3$, $m=6$, $a=2$, $b=1$, there exists a matrix satisfying the conditions above:\n\n$$ \\begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\\\ 1 & 0 & 0 & 1 & 0 & 0 \\\\ 0 & 0 & 1 & 0 & 1 & 0 \\end{vmatrix} $$",
    "tutorial": "Let's see how the desired matrix looks like. Since each row should have exactly $a$ ones, and each column should have exactly $b$ ones, the number of ones in all rows $a \\cdot n$ should be equal to the number of ones in all columns $b \\cdot m$. Thus, the desired matrix exists iff $a \\cdot n = b \\cdot m$ or $\\frac{n}{m} = \\frac{b}{a}$. Let's show how to construct the desired matrix if it exists. Let's find any number $0<d<m$ such that $(d \\cdot n) \\% m = 0$, where $a \\% b$ - is the remainder of dividing $a$ by $b$. In the first row of the desired matrix, we put the ones at the positions $[1, a]$, and in the $i$-th row we put the ones, as in the $i-1$ row, but cyclically shifted by $d$ to the right.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  int test;\n  cin >> test;\n\n  for (int tt = 0; tt < test; tt++) {\n    int h, w, a, b;\n    cin >> h >> w >> a >> b;\n\n    if (h * a != w * b) {\n      cout << \"NO\" << endl;\n      continue;\n    }\n\n    vector<vector<int>> result(h, vector<int>(w, 0));\n\n    int shift = 0;\n\n    for (shift = 1; shift < w; shift++) {\n      if (shift * h % w == 0) {\n        break;\n      }\n    }\n\n    for (int i = 0, dx = 0; i < h; i++, dx += shift) {\n      for (int j = 0; j < a; j++) {\n        result[i][(j + dx) % w] = 1;\n      }\n    }\n\n    cout << \"YES\" << endl;\n\n    for (int i = 0; i < h; i++) {\n      for (int j = 0; j < w; j++) {\n        cout << result[i][j];\n      }\n\n      cout << endl;\n    }\n  }\n\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1360",
    "index": "H",
    "title": "Binary Median",
    "statement": "Consider all binary strings of length $m$ ($1 \\le m \\le 60$). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly $2^m$ such strings in total.\n\nThe string $s$ is lexicographically smaller than the string $t$ (both have the same length $m$) if in the first position $i$ from the left in which they differ, we have $s[i] < t[i]$. This is exactly the way strings are compared in dictionaries and in most modern programming languages when comparing them in a standard way. For example, the string 01011 is lexicographically smaller than the string 01100, because the first two characters are the same, and the third character in the first string is less than that in the second.\n\nWe remove from this set $n$ ($1 \\le n \\le \\min(2^m-1, 100)$) \\textbf{distinct} binary strings $a_1, a_2, \\ldots, a_n$, each of length $m$. Thus, the set will have $k=2^m-n$ strings. Sort all strings of the resulting set in lexicographical ascending order (as in the dictionary).\n\nWe number all the strings after sorting from $0$ to $k-1$. Print the string whose index is $\\lfloor \\frac{k-1}{2} \\rfloor$ (such an element is called median), where $\\lfloor x \\rfloor$ is the rounding of the number down to the nearest integer.\n\nFor example, if $n=3$, $m=3$ and $a=[$010, 111, 001$]$, then after removing the strings $a_i$ and sorting, the result will take the form: $[$000, 011, 100, 101, 110$]$. Thus, the desired median is 100.",
    "tutorial": "If we did not delete the strings, then the median would be equal to the binary notation of $2^{(m-1)}$. After deleting $n$ strings, the median cannot change (numerically) by more than $2 \\cdot n$. Let's start with the median $2^{(m-1)}$ and each time decrease it by one if there are fewer not deleted smaller numbers than not deleted large numbers. Similarly, you need to increase the median by one, otherwise. The algorithm stops when the result is the median of the current set. All these steps will run at most $200$ times.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ld = long double;\nusing ll = long long;\n\nvoid solve() {\n\tll m, n;\n\tcin >> n >> m;\n\tvector<ll> v(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tstring s;\n\t\tcin >> s;\n\t\tfor (char c : s) {\n\t\t\tv[i] *= 2;\n\t\t\tv[i] += c - '0';\n\t\t}\n\t}\n\tll need = ((1ll << m) - n - 1) / 2 + 1;\n\tll cur = (1ll << (m - 1)) - 1;\n\twhile (true) {\n\t\tll left = cur + 1;\n\t\tbool flag = false;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tflag |= v[i] == cur;\n\t\t\tif (v[i] <= cur) {\n\t\t\t\tleft--;\n\t\t\t}\n\t\t}\n\t\tif (left == need && !flag) {\n\t\t\tstring s;\n\t\t\tfor (int i = 0; i < m; i++) {\n\t\t\t\ts += (char)(cur % 2 + '0');\n\t\t\t\tcur /= 2;\n\t\t\t}\n\t\t\treverse(s.begin(), s.end());\n\t\t\tcout << s << endl;\n\t\t\treturn;\n\t\t} else if (left < need) {\n\t\t\tcur++;\n\t\t} else {\n\t\t\tcur--;\n\t\t}\n\t}\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "constructive algorithms"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1361",
    "index": "A",
    "title": "Johnny and Contribution",
    "statement": "Today Johnny wants to increase his contribution. His plan assumes writing $n$ blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.\n\nThere are $n$ different topics, numbered from $1$ to $n$ sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most $n - 1$ neighbors.\n\nFor example, if already written neighbors of the current blog have topics number $1$, $3$, $1$, $5$, and $2$, Johnny will choose the topic number $4$ for the current blog, because topics number $1$, $2$ and $3$ are already covered by neighbors and topic number $4$ isn't covered.\n\nAs a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?",
    "tutorial": "We can view blogs as a graph, references as edges, and topics as colors. Now we can reformulate our problem as finding a permutation of vertices such that given in the statement greedy coloring algorithm returns coloring as described in the input. Let us start with two observations: Observation 1: If there is an edge between vertices with the same color, then the answer is $-1$. Observation 2: If for a vertex $u$ with color $c$ there exist a color $c' < c$ such that $u$ has no edge to any vertex with color $c'$ then the answer is $-1$. Both observations are rather straightforward to prove, so we skip it. Let us create permutation where vertices are sorted firstly by desired color and secondly by indices. We claim that if there exists any ordering fulfilling given regulations, then this permutation fulfills these too. Let us prove it: Let us analyze vertex $u$ with color $c$. From observation $2$ we know that for each color $c' < c$ there exist $v$ with color $c'$ such that $u$ and $v$ are connected by an edge. Because vertices are sorted by colors in our permutation, $v$ is before $u$ in ordering. So the greedy algorithm will assign that vertex color $k \\geq c$. From observation $1$, we now that $u$ does not have an edge to vertex with color $c$, so the greedy algorithm has to assign to $u$ color $k \\leq c$. Combining both inequalities, we reach that greedy must assign color $k = c$, which completes our proof. So now the algorithm is rather straightforward - sort vertices by colors, check if that ordering fulfills given regulations, if so, then write it down, otherwise print $-1$. This can be implemented in $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1e6 + 7;\n\nint n, m;\nint ans[N];\n\nint last[N];\nvector <int> G[N];\nvector <int> in[N];\n\nint main(){\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 1; i <= m; ++i){\n\t\tint u, v;\n\t\tscanf(\"%d %d\", &u, &v);\n\t\t\n\t\tG[u].push_back(v);\n\t\tG[v].push_back(u);\n\t}\n\t\n\tfor(int i = 1; i <= n; ++i){\n\t\tint color;\n\t\tscanf(\"%d\", &color);\n\n\t\tin[color].push_back(i);\n\t\tif(color > n){\n\t\t\tputs(\"-1\");\n\t\t\texit(0);\n\t\t}\n\t}\n\t\n\tvector <int> result;\n\tfor(int i = 1; i <= n; ++i){\n\t\tfor(auto u: in[i]){\n\t\t\tfor(auto v: G[u])\n\t\t\t\tlast[ans[v]] = u;\n\t\t\t\n\t\t\tans[u] = 1;\n\t\t\twhile(last[ans[u]] == u)\n\t\t\t\t++ans[u];\n\t\t\t\n\t\t\tif(ans[u] != i){\n\t\t\t\tputs(\"-1\");\n\t\t\t\texit(0);\n\t\t\t}\n\t\t\t\n\t\t\tresult.push_back(u);\n\t\t}\n\t}\n\t\n\tfor(int i = 0; i < n; ++i)\n\t\tprintf(\"%d%c\", result[i], i == n - 1 ? '\\n' : ' ');\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1361",
    "index": "B",
    "title": "Johnny and Grandmaster",
    "statement": "Johnny has just found the new, great tutorial: \"How to become a grandmaster?\". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.\n\nThe boy has found an online judge with tasks divided by topics they cover. He has picked $p^{k_i}$ problems from $i$-th category ($p$ is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.\n\nFormally, given $n$ numbers $p^{k_i}$, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo $10^{9}+7$.",
    "tutorial": "The solution for the case $p = 1$ is trivial, the answer is $1$ for odd $n$ and $0$ for even $n$. From now on, I will assume that $p > 1$. Instead of partitioning the elements into two sets, I will think of placing plus and minus signs before them to minimize the absolute value of the resulting expression. We will process the exponents in non-increasing order and maintain the invariant that the current sum is nonnegative. Say we are processing $k_i.$ In such cases, we will know the current sum modulo $10^{9}+7$ and its exact value divided by $p^{k_i}$ (denoted as $v$) or information that it's too big. Initially, the sum (I will denote it $s$) equals $0$. While processing elements: If $s > 0$, subtract the current element from the sum (it easy to show that it won't be negative after this operation). If $s = 0$, add the current element to the sum. If at any point of the algorithm, $v = \\frac{s}{p^{k_i}} > n$, there is no need to store the exact value of $v$ anymore, because it is so big that all the elements from this moment on will be subtracted. Thus, it is enough to store this information and the current sum modulo $10^{9}+7$. When we move to the next element, the exponent may change, and $v$ needs to be multiplied by a power of $p$. Since the exponents can be large, we use fast multiplication. The time complexity of this solution is $\\mathcal{O}(n \\log n + n \\log \\max k_i)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst ll INF = 1e6+100;\nconst ll mod = ll(1e9)+7;\n\nll fexp (ll a, int e)\n{\n\tll ret = 1LL;\n\twhile (e>0)\n\t{\n\t\tif (e%2==1) ret = ret * a % mod;\n\t\ta = a*a % mod;\n\t\te/=2;\n\t}\n\treturn ret;\n}\n\nint main ()\n{\n\tint t;\n\tscanf (\"%d\", &t);\n\tfor (int test = 0; test < t; test++)\n\t{\n\t\tint n;\n\t\tll p;\n\t\tscanf (\"%d %lld\", &n, &p);\n\t\tvector <int> K(n);\n\t\tfor (int &x: K) scanf (\"%d\", &x);\n\t\tsort(K.begin(), K.end());\n\t\t\n\t\tvector <int> Exp = K;\n\t\t\n\t\tll currSum = 0;\n\t\tll result = 0;\n\t\tbool infty = false;\n\t\t\n\t\tint prevExp = 1e6+10;\n\t\twhile (!Exp.empty())\n\t\t{\n\t\t\t/* Update the currSum and result (multiply by a power of k) */\n\t\t\tint k = Exp.back();\n\t\t\tExp.pop_back();\n\t\t\tint delta = prevExp - k;\n\t\t\tprevExp = k;\n\t\t\t\n\t\t\tresult = result * fexp(p, delta) % mod;\n\t\t\t\n\t\t\t/* Multiplying by p 20 times will either \n\t\t\tnot change the currSum at all or make it bigger than n */\n\t\t\tfor (int i=0; i<min(delta, 20); i++)\n\t\t\t{\n\t\t\t\tcurrSum *= p;\n\t\t\t\tif (currSum > INF) infty = true;\n\t\t\t}\n\t\t\t\n\t\t\t/* Process all the elements equal p^k */\n\t\t\twhile (!K.empty() && K.back()==k)\n\t\t\t{\n\t\t\t\tK.pop_back();\n\t\t\t\tif (infty || currSum > 0)\n\t\t\t\t{\n\t\t\t\t\tcurrSum--;\n\t\t\t\t\tresult+=mod - 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrSum++;\n\t\t\t\t\tresult++;\n\t\t\t\t}\n\t\t\t\tresult%=mod;\n\t\t\t}\n\t\t}\n\t\t\n\t\tresult = result * fexp(p, prevExp) % mod;\n\t\t\n\t\tprintf (\"%lld\\n\", result % mod);\n\t}\n}\n",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1361",
    "index": "C",
    "title": "Johnny and Megan's Necklace",
    "statement": "Johnny's younger sister Megan had a birthday recently. Her brother has bought her a box signed as \"Your beautiful necklace — do it yourself!\". It contains many necklace parts and some magic glue.\n\nThe necklace part is a chain connecting two pearls. Color of each pearl can be defined by a non-negative integer. The magic glue allows Megan to merge two pearls (possibly from the same necklace part) into one. The beauty of a connection of pearls in colors $u$ and $v$ is defined as follows: let $2^k$ be the greatest power of two dividing $u \\oplus v$ — exclusive or of $u$ and $v$. Then the beauty equals $k$. If $u = v$, you may assume that beauty is equal to $20$.\n\nEach pearl can be combined with another at most once. Merging two parts of a necklace connects them. Using the glue multiple times, Megan can finally build the necklace, which is a cycle made from connected necklace parts (so every pearl in the necklace is combined with precisely one other pearl in it). The beauty of such a necklace is the minimum beauty of a single connection in it. The girl wants to use all available necklace parts to build \\textbf{exactly one} necklace consisting of \\textbf{all of them} with the largest possible beauty. Help her!",
    "tutorial": "Say that we want to check if it is possible to construct a necklace with beauty at least $b$. To this end, we will construct a graph of $2^{b}$ vertices. For a necklace part with pearls in colors $u$ and $v$ there will be an edge in this graph between vertices with zero-based indices $v\\text{ & }(2^b-1)$ and $u\\text{ & }(2^b-1)$. In a necklace with beauty (at least) $b$, only pearl with colors having last $b$ bits the same can be glued together. Note that this is the exact condition that the edge endpoints have to satisfy to be in the same vertex. Since all the necklace parts have to be used, a necklace of beauty at least $b$ is an Euler cycle of this graph. The solution will construct the graph mentioned above for all possible values of $b$ (we can iterate over all of them since there are only $21$ of them). If the constructed graph is Eulerian, it is possible to achieve the current value of $b$. In order to find a sample necklace with the optimal beauty, one has to find the Euler cycle in the graph corresponding to the optimal value. Challenge: In another version of this task you are not allowed to glue pearls of the same color together. There is also a guarantee that there are no three pearls of the same color. Time complexity of the solution is the same.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define st first\n#define nd second\n#define PII pair <int, int>\n\nconst int N = 1 << 20;\n\nint n;\nint part[N][2];\n\nbool vis[N];\nvector <int> ans;\nvector <PII> G[N];\n\n//mark whole component as visited\nvoid dfs(int u){\n\tvis[u] = true;\n\tfor(auto v: G[u])\n\t\tif(!vis[v.st])\n\t\t\tdfs(v.st);\n}\n\n//check if the graph for a given Mask is correct\nbool check(int Mask){\n\tfor(int i = 0; i <= Mask; ++i)\n\t\tG[i].clear(), vis[i] = false;\n\n\tfor(int i = 1; i <= n; ++i){\n\t\tint u = part[i][0] & Mask;\n\t\tint v = part[i][1] & Mask;\n\t\t\n\t\tG[u].push_back({v, 2 * i - 1});\n\t\tG[v].push_back({u, 2 * i - 2});\n\t}\n\t\n\t//calculate number of components and check if all degrees are even\n\tint comps = 0;\n\tfor(int i = 0; i <= Mask; ++i){\n\t\tif(G[i].size() & 1)\n\t\t\treturn false;\n\t\t\n\t\tif(!vis[i] && G[i].size() > 0){\n\t\t\t++comps;\n\t\t\tdfs(i);\n\t\t}\n\t}\n\t\n\treturn comps == 1;\n}\n\n//find euler cycle\nvoid go(int u, int prv = -1){\n\twhile(G[u].size()){\n\t\tauto e = G[u].back();\n\t\tG[u].pop_back();\n\n\t\tif(vis[e.nd / 2])\n\t\t\tcontinue;\n\t\t\n\t\tvis[e.nd / 2] = true;\n\t\tgo(e.st, e.nd);\n\t}\n\t\n\tif(prv != -1){\n\t\tans.push_back(prv);\n\t\tans.push_back(prv ^ 1);\n\t}\n}\n\n//restore the sequence corresponding to the result for given mask\n//the result is already checked so the graph is built\nvoid restore(int Mask){\n\tfor(int i = 0; i <= n; ++i)\n\t\tvis[i] = false;\n\t\n\tfor(int i = 0; i <= Mask; ++i)\n\t\tif(G[i].size()){\n\t\t\tgo(i);\n\t\t\tbreak;\n\t\t}\n\t\n\t//cycle is reversed but thats fine\n\tfor(int i = 0; i < n + n; ++i)\n\t\tprintf(\"%d%c\", ans[i] + 1, \" \\n\"[i + 1 == n + n]);\n}\n\nint main(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i)\n\t\tscanf(\"%d %d\", &part[i][0], &part[i][1]);\n\n\tfor(int i = 20; i >= 0; --i)\n\t\tif(check((1 << i) - 1)){\n\t\t\tprintf(\"%d\\n\", i);\n\t\t\trestore((1 << i) - 1);\n\t\t\texit(0);\n\t\t}\n\t\n\tassert(false);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1361",
    "index": "D",
    "title": "Johnny and James",
    "statement": "James Bond, Johnny's favorite secret agent, has a new mission. There are $n$ enemy bases, each of them is described by its coordinates so that we can think about them as points in the Cartesian plane.\n\nThe bases can communicate with each other, sending a signal, which is the ray directed from the chosen point to the origin or in the opposite direction. The exception is the central base, which lies at the origin and can send a signal in any direction.\n\nWhen some two bases want to communicate, there are two possible scenarios. If they lie on the same line with the origin, one of them can send a signal directly to the other one. Otherwise, the signal is sent from the first base to the central, and then the central sends it to the second base. We denote the distance between two bases as the total Euclidean distance that a signal sent between them has to travel.\n\nBond can damage all but some $k$ bases, which he can choose arbitrarily. A damaged base can't send or receive the direct signal but still can pass it between two working bases. In particular, James can damage the central base, and the signal \\textbf{can still be sent} between any two undamaged bases as before, so the distance between them remains the same. What is the maximal sum of the distances between all pairs of remaining bases that 007 can achieve by damaging exactly $n - k$ of them?",
    "tutorial": "We can easily model the way of calculating distances from the problem statement as a tree with $n$ vertices, each corresponding to a base. This tree has the following structure: there is only one vertex which can have degree bigger than $2$ (the one corresponding to the central base), I will call it the center of the tree. There are also some paths consisting of vertices corresponding to bases lying on the same half-line starting at point $(0, 0)$. We will call those arms of the tree. Assume that the center does not belong to any arm. The task is to choose $k$ vertices in a way that maximizes the sum of distances between them. Let us start with a lemma: If $x$ vertices are chosen from an arm, at least $min(x, \\lfloor \\frac{k}{2} \\rfloor)$ of them are the ones furthest from the center. Say that less than $min(x, \\lfloor \\frac{k}{2} \\rfloor)$ is chosen from the end of the arm (counting from the center). Then there exists such chosen vertex $v$ on the arm, that the next (counting from the center) vertex $u$ is not chosen. Let the length of the edge between them be $l$ and let there be $t$ vertices further from the center than $v$. If we had chosen $u$ instead of $v$, the sum of distances would change by $l \\cdot (k - t - 1) - l \\cdot t = l \\cdot (k - 2t - 1)$ (the chosen vertex would move closer by $l$ to $t$ vertices, but also it's distance to $k-t-1$ vertices would increase by $l$). But since $t < \\frac{k}{2}$, this value is non-negative (the sum of distances would not decrease). There are two cases which will be solved independently: First case: there is no arm containing more than $\\frac{k}{2}$ vertices chosen. By the lemma, in every arm, only vertices furthest from the center will be selected in an optimal solution. If a vertex is chosen, all the ones in the same arm further from the center are chosen as well. Using this knowledge, we can assign weights to vertices in such a way that the result for a set will be the sum of weights. Weight for vertex $v$ equals: $w_v = dist(center, v) * (k - 1 - t - t)$ where $t$ is the number of vertices further from center in the same arm as $v$. The weight of the center equals $0$. Note that (with exception to the center) $w_v \\leq 0$ iff taking $v$ would violate the condition that at most $\\frac{k}{2}$ are chosen from every arm. The algorithm for this case is to add the vertices greedily to the set until $k$ vertices have been chosen. The complexity of the above algorithm is $\\mathcal{O}(n \\log n)$. Second case: there is an arm, in which more than $\\frac{k}{2}$ vertices are chosen in the optimal solution. From the lemma, we know that $\\lfloor \\frac{k}{2} \\rfloor$ vertices lying furthest from the center will be chosen. It can be proved (in a similar manner as the lemma) that in an optimal solution, all other selected vertices from this arm will be as close to the center as possible. Furthermore, the center and all the vertices in the other arms will be selected. Intuitively, when there are $\\lfloor \\frac{k}{2} \\rfloor$ chosen vertices on a single-arm, we will not decrease the sum of distances by moving another selected vertex further from them along an edge. There is at most one set of $k$ vertices satisfying those conditions so that this part can be implemented in $\\mathcal{O}(n)$. The time complexity of this solution is $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long double T;\n\n#define st first\n#define nd second\n#define PII pair <int, int>\n\nconst int N = 1e6 + 7;\n\nint n, m, k;\nvector <T> arms[N];\n\nvoid read(){\n\tmap <PII, int> M;\n\n\tscanf(\"%d %d\", &n, &k);\t\n\tfor(int i = 1; i <= n; ++i){\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t\n\t\tif(x == 0 && y == 0)\n\t\t\tcontinue;\n\t\t\n\t\tint d = __gcd(abs(x), abs(y));\n\t\tPII my_id = {x / d, y / d};\n\t\t\n\t\tif(!M.count(my_id))\n\t\t\tM[my_id] = ++m;\n\t\t\n\t\tauto id = M[my_id];\n\t\tarms[id].push_back(sqrtl((T)x * x + (T)y * y));\n\t}\n\t\n\tfor(int i = 1; i <= m; ++i){\n\t\tsort(arms[i].begin(), arms[i].end());\n\t\treverse(arms[i].begin(), arms[i].end());\n\t}\n}\n\nT solve_center(){\n\tT ans = 0;\n\tvector <T> vals = {0};\n\n\tfor(int i = 1; i <= m; ++i){\n\t\tint it = 0;\n\t\tfor(auto v: arms[i]){\n\t\t\t++it;\n\t\t\tvals.push_back(v * (k - it - it + 1));\n\t\t}\n\t}\n\t\n\tsort(vals.begin(), vals.end());\n\treverse(vals.begin(), vals.end());\n\n\tfor(int i = 0; i < k; ++i)\n\t\tans += vals[i];\n\treturn ans;\n}\n\nT solve_arm(int id){\n\tT ans = 0;\n\tfor(int i = 1; i <= m; ++i){\n\t\tif(i == id)\n\t\t\tcontinue;\n\t\t\n\t\tint it = 0;\n\t\tfor(auto v: arms[i]){\n\t\t\t++it;\n\t\t\tans += v * (k - it - it + 1);\n\t\t}\n\t}\n\t\n\tint half = k / 2;\n\tint first_half = k - half - (n - arms[id].size());\n\t\t\n\tfor(int i = 0; i < half; ++i)\n\t\tans += arms[id][i] * (k - i - i - 1);\n\t\n\tfor(int i = 0; i < first_half; ++i){\n\t\tT val = arms[id][arms[id].size() - i - 1];\n\t\tans += val * (k - half - half - 2 * first_half + 2 * i + 1);\n\t}\n\t\n\treturn ans;\n}\n\nint main(){\n\tread();\n\tT ans = solve_center();\n\tif(k < n){\n\t\tfor(int i = 1; i <= m; ++i)\n\t\t\tif(2 * (n - (int)arms[i].size()) <= k)\n\t\t\t\tans = max(ans, solve_arm(i));\n\t}\n\n\tprintf(\"%.10Lf\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1361",
    "index": "E",
    "title": "James and the Chase",
    "statement": "James Bond has a new plan for catching his enemy. There are some cities and \\textbf{directed} roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there.\n\nThe city $a$ is called interesting, if for each city $b$, there is exactly one simple path from $a$ to $b$. By a simple path, we understand a sequence of distinct cities, such that for every two neighboring cities, there exists a directed road from the first to the second city.\n\nBond's enemy is the mistress of escapes, so only the chase started in an interesting city gives the possibility of catching her. James wants to arrange his people in such cities. However, if there are not enough interesting cities, the whole action doesn't make sense since Bond's people may wait too long for the enemy.\n\nYou are responsible for finding all the interesting cities or saying that there is not enough of them. By not enough, James means strictly less than $20\\%$ of all cities.",
    "tutorial": "First, let us describe an algorithm for checking if a vertex is interesting. Let $v$ be the vertex we want to check. Find any DFS tree rooted in that vertex. We can see that $v$ is interesting if and only if that tree is unique. The tree is unique iff every non-tree edge leads from some vertex $u$ to $u$'s ancestor. That condition can be easily checked in $\\mathcal{O}(n)$. Using the fact that we are interested only in cases when at least $20\\%$ of vertices are interesting, we can find any interesting vertex by choosing a random vertex, checking if it is interesting and repeating that algorithm $T$ times or until we find an interesting vertex. For $T = 100$ the probability of failure is around $2 \\cdot 10^{-10}$. Denote that vertex as $r$. Find the DFS tree rooted in that vertex. We can notice that vertex is interesting if and only if it has a unique path to all of its ancestors in this tree. We will say that edge is passing vertex $v$ if it starts in its subtree (including $v$) and ends in one of the proper ancestors of $v$. It is evident that if two edges pass through $v$, then $v$ cannot be interesting. Let us pick vertex $v$ such that there is at most one edge passing through it. It is evident that if $v \\neq r$, then there is at least one such edge (because our graph is strongly connected). Let $u$ be the endpoint of this edge being a proper ancestor of $v$. We prove that $v$ is interesting if and only if $u$ is interesting. Pick arbitrary ancestor of $v$ which is not an ancestor of $u$, let us denote it by $t$. There is precisely one simple path from $v$ to $t$ - descending in the subtree of $v$, using the non-tree edge to $u$ and then tree edges to reach $t$. Now pick arbitrary common ancestor of $v$ and $u$, let it be $k$. If there is more than one simple path from $u$ to $k$, then obviously there is more than one simple path from $v$ to $k$. Otherwise, there is precisely one simple path from $v$ to $k$ - descend in the subtree, use edge to $u$ and from $u$ there is one simple path to $k$. The above observations allow computing interesting vertices using simple DFSs. The final complexity is $\\mathcal{O}(Tn)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1e5 + 7;\n\nint n, m;\nbool bad[N];\nvector <int> G[N];\n\nint vis[N];\nbool interesting;\n\nint lvl[N];\nint best[N];\nint balance[N];\n\nvoid clear(){\n\tfor(int i = 1; i <= n; ++i){\n\t\tlvl[i] = 0;\n\t\tbest[i] = 0;\n\t\tbalance[i] = 0;\n\n\t\tG[i].clear();\t\t\n\t\tbad[i] = false;\n\t}\n}\n\nvoid no_answer(){\n\tputs(\"-1\");\n\tclear();\n}\n\nint getInt(int a = INT_MIN, int b = INT_MAX){\n\tstatic mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\treturn uniform_int_distribution <int> (a, b)(rng);\n}\n\nvoid dfs(int u){\n\tvis[u] = 1;\n\tfor(auto v: G[u])\n\t\tif(vis[v] == 0)\n\t\t\tdfs(v);\n\t\telse if(vis[v] == 2)\n\t\t\tinteresting = false;\n\tvis[u] = 2;\n}\n\nbool check(int r){\n\tfor(int i = 1; i <= n; ++i)\n\t\tvis[i] = 0;\n\tinteresting = true;\n\n\tdfs(r);\n\treturn interesting;\n}\n\nint find_any(){\n\tint tests = 100;\n\twhile(tests--){\n\t\tint r = getInt(1, n);\n\t\tif(check(r))\n\t\t\treturn r;\n\t}\n\t\n\treturn -1;\n}\n\nint find_bad(int u){\n\tvis[u] = 1;\n\tbest[u] = u;\n\tfor(auto v: G[u])\n\t\tif(vis[v] == 0){\n\t\t\tlvl[v] = lvl[u] + 1;\n\t\t\tbalance[u] += find_bad(v);\n\t\t\t\n\t\t\tif(lvl[best[v]] < lvl[best[u]])\n\t\t\t\tbest[u] = best[v];\n\t\t}\n\t\telse{\n\t\t\tbalance[u]++;\n\t\t\tbalance[v]--;\n\t\t\t\n\t\t\tif(lvl[v] < lvl[best[u]])\n\t\t\t\tbest[u] = v;\n\t\t}\n\t\n\tif(balance[u] > 1)\n\t\tbad[u] = true;\n\treturn balance[u];\n}\n\nvoid propagate_bad(int u){\n\tvis[u] = 1;\n\tif(!bad[u] && bad[best[u]])\n\t\tbad[u] = true;\n\n\tfor(auto v: G[u])\n\t\tif(vis[v] == 0)\n\t\t\tpropagate_bad(v);\n}\n\nvector <int> find_all(int r){\n\tfor(int i = 1; i <= n; ++i)\n\t\tvis[i] = 0;\n\tvector <int> ans;\n\n\tfind_bad(r);\n\tfor(int i = 1; i <= n; ++i)\n\t\tvis[i] = 0;\n\n\tpropagate_bad(r);\n\tfor(int i = 1; i <= n; ++i)\n\t\tif(!bad[i])\n\t\t\tans.push_back(i);\n\treturn ans;\n}\n\nvoid solve(){\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 1; i <= m; ++i){\n\t\tint u, v;\n\t\tscanf(\"%d %d\", &u, &v);\t\t\n\t\tG[u].push_back(v);\n\t}\n\t\n\tint id = find_any();\n\tif(id == -1){\n\t\tno_answer();\n\t\treturn;\n\t}\n\t\n\tauto ans = find_all(id);\n\tif(5 * ans.size() >= n){\n\t\tfor(auto v: ans)\n\t\t\tprintf(\"%d \", v);\n\t\tputs(\"\");\n\t\tclear();\n\t}\n\telse\n\t\tno_answer();\n}\n\nint main(){\n\tint cases;\n\tscanf(\"%d\", &cases);\n\t\n\twhile(cases--)\n\t\tsolve();\n\treturn 0;\n}\n",
    "tags": [
      "dfs and similar",
      "graphs",
      "probabilities",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1361",
    "index": "F",
    "title": "Johnny and New Toy",
    "statement": "Johnny has a new toy. As you may guess, it is a little bit extraordinary. The toy is a permutation $P$ of numbers from $1$ to $n$, written in one row next to each other.\n\nFor each $i$ from $1$ to $n - 1$ between $P_i$ and $P_{i + 1}$ there is a weight $W_i$ written, and those weights form a permutation of numbers from $1$ to $n - 1$. There are also extra weights $W_0 = W_n = 0$.\n\nThe instruction defines subsegment $[L, R]$ as good if $W_{L - 1} < W_i$ and $W_R < W_i$ for any $i$ in $\\{L, L + 1, \\ldots, R - 1\\}$. For such subsegment it also defines $W_M$ as minimum of set $\\{W_L, W_{L + 1}, \\ldots, W_{R - 1}\\}$.\n\nNow the fun begins. In one move, the player can choose one of the good subsegments, cut it into $[L, M]$ and $[M + 1, R]$ and swap the two parts. More precisely, before one move the chosen subsegment of our toy looks like: $$W_{L - 1}, P_L, W_L, \\ldots, W_{M - 1}, P_M, W_M, P_{M + 1}, W_{M + 1}, \\ldots, W_{R - 1}, P_R, W_R$$ and afterwards it looks like this: $$W_{L - 1}, P_{M + 1}, W_{M + 1}, \\ldots, W_{R - 1}, P_R, W_M, P_L, W_L, \\ldots, W_{M - 1}, P_M, W_R$$ Such a move can be performed multiple times (possibly zero), and the goal is to achieve the minimum number of inversions in $P$.\n\nJohnny's younger sister Megan thinks that the rules are too complicated, so she wants to test her brother by choosing some pair of indices $X$ and $Y$, and swapping $P_X$ and $P_Y$ ($X$ might be equal $Y$). After each sister's swap, Johnny wonders, what is the minimal number of inversions that he can achieve, starting with current $P$ and making legal moves?\n\nYou can assume that the input is generated \\textbf{randomly}. $P$ and $W$ were chosen independently and equiprobably over all permutations; also, Megan's requests were chosen independently and equiprobably over all pairs of indices.",
    "tutorial": "Let us start with an analysis of good subsegments for the fixed permutation. The whole permutation is a good subsegment itself, as $W_0 = W_n = 0 < W_k$ for any $k \\in [1, 2, \\ldots, n - 1]$. If we denote the minimal weight in $W_1, \\ldots, W_{n - 1}$ as $W_m$, then we can notice that subsegments $[1, m]$ and $[m + 1, n]$ contain all good subsegments except the whole permutation. As a result, we can recursively find all good subsegments by recursive calls in $[1, m]$ and $[m + 1, n]$. We can view the structure of good subsegments as a binary tree. Example structure of tree for $P = [3, 4, 6, 2, 1, 5]$ and $W = [5, 2, 3, 1, 4]$: Now we want to analyze the possible moves for players. It turns out that the player's move is equivalent to choosing a vertex of a tree and swapping its left and right subtree. Notice that moves made in different vertices influence disjoint pairs of elements, so in some sense these moves are independent if we are interested only in the number of inversions. This observation allows us to find a simple method for calculating the result. For each vertex, calculate the number of inversions between the left and right subtree. Using these numbers for each vertex, we can find out whether we want to swap its subtrees or not, so the result can be calculated by a simple loop over all vertices. From randomness of the input, we can deduce that the tree we built has height $\\mathcal{O}(\\log n)$. We can calculate the number of inversions easily if in each vertex we keep a structure with elements from permutation contained in that vertex. Such structure must support querying the number of elements smaller than some $x$. The shortest implementation uses the ordered set, but any BST can do it (segment tree needs some squeezing to fit into ML). The above solution works fast if there are no queries. We can view each request as two removals and additions of elements. If so, we can notice that each query modifies the number of inversions in at most $\\mathcal{O}(\\log n)$ vertices. So all we need to do is update the number of inversions in these vertices and recalculate the global result. Building a tree and calculating initial number of inversions takes $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n \\log^2n)$, answering each query cost $\\mathcal{O}(\\log^2 n)$, so the final complexity is $\\mathcal{O}(n \\log n + q \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef long long ll;\ntypedef tree < int, null_type, less <int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set;\n\nconst int N = 2e5 + 7;\n\n//cartesian tree node\n//while creating we calculate set of elements and number of inversions\nstruct node{\n\tint splitter = -1;\n\tlong long invs = 0;\t\n\t\n\tordered_set S;\n\tnode *left = nullptr, *right = nullptr;\n\tnode(){}\n};\n\nint n;\nint in[N];\nint weight[N];\n\nlong long ans = 0;\nnode *root = nullptr;\n\nvoid read(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &in[i]);\n\t\n\tfor(int i = 1; i < n; ++i)\n\t\tscanf(\"%d\", &weight[i]);\n}\n\n//add/delete contribution from fiven node to result\nvoid add_result(node *cur, int mt = 1){\n\tif(cur -> splitter == 0)\n\t\treturn;\n\tans += mt * min(cur -> invs, (ll)cur -> left -> S.size() * (ll)cur -> right -> S.size() - cur -> invs);\n}\n\n//Create cartesian tree\n//Because expected depth is O(logn) we can use bruteforce to find the smallest weight\nnode* get_cartesian(int from, int to){\n\tnode *ret = new node();\n\tif(from == to){\n\t\tret -> S.insert(in[from]);\n\t\treturn ret;\n\t}\n\t\n\tint id = from;\n\tfor(int i = from + 1; i < to; ++i)\n\t\tif(weight[i] < weight[id])\n\t\t\tid = i;\n\t\n\tret -> splitter = id;\n\tret -> left = get_cartesian(from, id);\n\tret -> right = get_cartesian(id + 1, to);\n\t\n\t//get elements from ordered set\n\tfor(auto v: ret -> right -> S)\n\t\tret -> S.insert(v);\n\t\n\t//calculate number of inversions\n\tfor(auto v: ret -> left -> S){\n\t\tret -> S.insert(v);\n\t\tret -> invs += ret -> right -> S.order_of_key(v);\n\t}\n\t\n\t//add contribution to the result\n\tadd_result(ret);\n\treturn ret;\n}\n\n//depending on mt, removes/add element val on position p\nvoid update_cart(int p, int val, int mt){\n\tnode *cur = root;\n\twhile(cur -> splitter != -1){\n\t\tadd_result(cur, -1);\n\t\tif(mt == -1)\n\t\t\tcur -> S.erase(val);\n\t\telse\n\t\t\tcur -> S.insert(val);\n\t\t\n\t\tif(p <= cur -> splitter){\n\t\t\tcur -> invs += mt * (int)(cur -> right -> S.order_of_key(val));\n\t\t\tcur = cur -> left;\n\t\t}\n\t\telse{\n\t\t\tcur -> invs += mt * (int)(cur -> left -> S.size() - cur -> left -> S.order_of_key(val));\n\t\t\tcur = cur -> right;\n\t\t}\n\t}\n\t\n\tif(mt == -1)\n\t\tcur -> S.erase(val);\n\telse\n\t\tcur -> S.insert(val);\t\n\n\tcur = root;\n\twhile(cur -> splitter != -1){\n\t\tadd_result(cur, 1);\n\t\tif(p <= cur -> splitter)\n\t\t\tcur = cur -> left;\n\t\telse\n\t\t\tcur = cur -> right;\n\t}\n}\n\nint main(){\n\tread();\n\troot = get_cartesian(1, n);\n\t\n\tint q;\n\tscanf(\"%d\", &q);\n\twhile(q--){\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t\n\t\tif(x == y){\n\t\t\tprintf(\"%lld\\n\", ans);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t//remove both numbers\n\t\tupdate_cart(x, in[x], -1);\n\t\tupdate_cart(y, in[y], -1);\n\t\tswap(in[x], in[y]);\n\t\t\n\t\t//add both numbers\n\t\tupdate_cart(x, in[x], 1);\n\t\tupdate_cart(y, in[y], 1);\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1362",
    "index": "A",
    "title": "Johnny and Ancient Computer",
    "statement": "Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it \\textbf{cuts off some ones}. So, in fact, in one operation, you can multiply or divide your number by $2$, $4$ or $8$, and division is only allowed if the number is divisible by the chosen divisor.\n\nFormally, if the register contains a positive integer $x$, in one operation it can be replaced by one of the following:\n\n- $x \\cdot 2$\n- $x \\cdot 4$\n- $x \\cdot 8$\n- $x / 2$, if $x$ is divisible by $2$\n- $x / 4$, if $x$ is divisible by $4$\n- $x / 8$, if $x$ is divisible by $8$\n\nFor example, if $x = 6$, in one operation it can be replaced by $12$, $24$, $48$ or $3$. Value $6$ isn't divisible by $4$ or $8$, so there're only four variants of replacement.\n\nNow Johnny wonders how many operations he needs to perform if he puts $a$ in the register and wants to get $b$ at the end.",
    "tutorial": "Let us write $a$ as $r_a \\cdot 2^x$ and $b$ as $r_b \\cdot 2^y$, where $r_a$ and $r_b$ are odd. The only operation we have changes $x$ by $\\{-3, -2, -1, 1, 2, 3\\}$ so $r_a$ must be equal to $r_b$, otherwise the answer is $-1$. It is easy to notice that we can greedily move $x$ toward $y$ so the answer is equal to $\\lceil \\frac{|x - y|}{3} \\rceil$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nLL getR(LL a){\n\twhile(a % 2 == 0)\n\t\ta /= 2;\n\treturn a;\n}\n\nvoid solve(){\n\tLL a, b;\n\tscanf(\"%lld %lld\", &a, &b);\n\tif(a > b)\tswap(a, b);\n\t\n\tLL r = getR(a);\n\tif(getR(b) != r){\n\t\tputs(\"-1\");\n\t\treturn;\n\t}\n\t\n\tint ans = 0;\n\tb /= a;\n\t\n\twhile(b >= 8)\n\t\tb /= 8, ++ans;\n\tif(b > 1)\t++ans;\n\tprintf(\"%d\\n\", ans);\n}\n\nint main(){\n\tint quest;\n\tscanf(\"%d\", &quest);\n\t\n\twhile(quest--)\n\t\tsolve();\n\treturn 0;\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1362",
    "index": "B",
    "title": "Johnny and His Hobbies",
    "statement": "Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.\n\nThere is a set $S$ containing very important numbers on his dad's desk. The minute Johnny heard about it, he decided that it's a good idea to choose a \\textbf{positive} integer $k$ and replace each element $s$ of the set $S$ with $s \\oplus k$ ($\\oplus$ denotes the exclusive or operation).\n\nHelp him choose such $k$ that Johnny's dad will not see any difference after his son is done playing (i.e. Johnny will get the same set as before playing). It is possible that no such number exists. It is also possible that there are many of them. In such a case, output the smallest one. Note that the order of elements in a set doesn't matter, i.e. set $\\{1, 2, 3\\}$ equals to set $\\{2, 1, 3\\}$.\n\nFormally, find the smallest positive integer $k$ such that $\\{s \\oplus k | s \\in S\\} = S$ or report that there is no such number.\n\nFor example, if $S = \\{1, 3, 4\\}$ and $k = 2$, new set will be equal to $\\{3, 1, 6\\}$. If $S = \\{0, 1, 2, 3\\}$ and $k = 1$, after playing set will stay the same.",
    "tutorial": "Consider $i$-th least significant bit ($0$ indexed). If it is set in $k$, but not in $s$, it will be set in $k \\oplus s$. Hence $k \\oplus s \\geq 2^i$. Consider such minimal positive integer $m$, that $2^m > s$ holds for all $s \\in S$. $k$ cannot have the $i$-th bit set for any $i \\geq m$. From this follows that $k < 2^m$. So there are only $2^m$ feasible choices of $k$. We can verify if a number satisfies the condition from the statement in $\\mathcal{O} \\left(n \\right)$ operations. This gives us a solution with complexity $\\mathcal{O} \\left(n \\cdot 2^m \\right)$. Note that in all tests $m$ is at most $10$. There is also another solution possible. It uses the observation that if $k$ satisfies the required conditions, then for every $s \\in S$ there exists such $t \\in S$ ($t \\neq s$) , that $t \\oplus s = k$. This gives us $n-1$ feasible choices of $k$ and thus the complexity of this solution is $\\mathcal{O} \\left( n^2 \\right)$.",
    "code": "//O(n * maxA) solution\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1025;\n\nint n;\nint in[N];\nbool is[N];\n\nbool check(int k){\n\tfor(int i = 1; i <= n; ++i)\n\t\tif(!is[in[i] ^ k])\n\t\t\treturn false;\n\treturn true;\n}\n\nvoid solve(){\n\tfor(int i = 0; i < N; ++i)\n\t\tis[i] = false;\n\t\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i){\n\t\tscanf(\"%d\", &in[i]);\n\t\tis[in[i]] = true;\n\t}\n\t\n\tfor(int k = 1; k < 1024; ++k)\n\t\tif(check(k)){\n\t\t\tprintf(\"%d\\n\", k);\n\t\t\treturn;\n\t\t}\n\t\n\tputs(\"-1\");\n}\n\nint main(){\n\tint cases;\n\tscanf(\"%d\", &cases);\n\t\n\twhile(cases--)\n\t\tsolve();\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "brute force"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1362",
    "index": "C",
    "title": "Johnny and Another Rating Drop",
    "statement": "The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.\n\nThe boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $5 = 101_2$ and $14 = 1110_2$ equals to $3$, since $0101$ and $1110$ differ in $3$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.\n\nJohnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of \\textbf{consecutive} integers from $0$ to $n$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.",
    "tutorial": "Let us start by calculating the result for $n = 2^k$. It can be quickly done by calculating the results for each bit separately and summing these up. For $i$-th bit, the result is equal to $\\frac{2^k}{2^{i}}$ as this bit is different in $d-1$ and $d$ iff $d$ is a multiple of $2^i$. Summing these up we get that the result for $n = 2^k$ is equal to $2^{k + 1} - 1 = 2n - 1$. How to compute the answer for arbitrary $n$? Let us denote $b_1 > b_2 > \\ldots > b_k$ as set bits in the binary representation of $n$. I claim that the answer is equal to the sum of answers for $2^{b_1}, 2^{b_2}, \\ldots, 2^{b_k}$. Why? We can compute results for intervals $[0, 2^{b_1}], [2^{b_1}, 2^{b_1} + 2^{b_2}], \\ldots, [n - 2^{b_k}, n]$. We can notice that the result for interval $[s, s + 2^i]$, where $s$ is a multiple of $2^i$, is equal to the answer for $[0, 2^i]$ so we can just compute the results for intervals $[0, 2^{b_1}], [0, 2^{b_2}], \\ldots, [0, 2^{b_k}]$! This allows us to compute the answer for arbitrary $n$ in $\\mathcal{O}(\\log n)$ - just iterate over all bits $b$ and add $2^{b + 1} - 1$ if $b$ is set. Equivalently we can just write down $2n - \\texttt{#bits set}$ as the answer. Final complexity is $\\mathcal{O}(t \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nvoid solve(){\n\tLL a;\n\tscanf(\"%lld\", &a);\n\t\n\tLL ans = 0;\n\tfor(int i = 0; i < 60; ++i)\n\t\tif(a & (1LL << i))\n\t\t\tans += (1LL << (i + 1)) - 1;\n\tprintf(\"%lld\\n\", ans);\n}\n\nint main(){\n\tint quest;\n\tscanf(\"%d\", &quest);\n\t\n\twhile(quest--)\n\t\tsolve();\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1363",
    "index": "A",
    "title": "Odd Selection",
    "statement": "Shubham has an array $a$ of size $n$, and wants to select exactly $x$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.\n\nTell him whether he can do so.",
    "tutorial": "Key Idea: The sum of $x$ numbers can only be odd if we have an odd number of numbers which are odd. (An odd statement, indeed). Detailed Explanation: We first maintain two variables, num_odd and num_even, representing the number of odd and even numbers in the array, respectively. We then iterate over the number of odd numbers we can choose; which are $1,3,5,...$ upto min(num_odd,x), and see if num_even $\\geq x - i$ where $i$ is the number of odd numbers we have chosen. Time complexity: $O(N)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N = 2e5 + 5;\n \nint n, x;\nint a[N], f[2];\n \nint32_t main()\n{\n\tIOS;\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t    f[0] = f[1] = 0;\n    \tcin >> n >> x;\n    \tfor(int i = 1; i <= n; i++)\n    \t{\n    \t\tcin >> a[i];\n    \t\tf[a[i] % 2]++;\n    \t}\n    \tbool flag = 0;\n    \tfor(int i = 1; i <= f[1] && i <= x; i += 2) //Fix no of odd\n    \t{\n    \t\tint have = f[0], need = x - i;\n    \t\tif(need <= f[0])\n    \t        flag = 1;\n    \t}\n    \tif(flag)\n    \t    cout << \"Yes\" << endl;\n    \telse\n    \t    cout << \"No\" << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1363",
    "index": "B",
    "title": "Subsequence Hate",
    "statement": "Shubham has a binary string $s$. A binary string is a string containing only characters \"0\" and \"1\".\n\nHe can perform the following operation on the string any amount of times:\n\n- Select an index of the string, and flip the character at that index. This means, if the character was \"0\", it becomes \"1\", and vice versa.\n\nA string is called good if it does not contain \"010\" or \"101\" as a subsequence  — for instance, \"1001\" contains \"101\" as a subsequence, hence it is not a good string, while \"1000\" doesn't contain neither \"010\" nor \"101\" as subsequences, so it is a good string.\n\nWhat is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.\n\nA string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.",
    "tutorial": "Key Idea: There are two types of good strings: Those which start with a series of $1$'s followed by $0$'s (such as $1111100$) and those which start with a series of $0$'s followed by $1$'s (such as $00111$). Note that there are strings which do belong to both categories (such as $000$). Detailed Explanation: We will use the key idea to compute the minimum change required to achieve every possible string of each of the two types, and then take the minimum across them. First, let us compute the total number of $1$'s and $0$'s in the string, denoted by num_ones and num_zeros. Now, as we iterate through the string, let us also maintain done_ones and done_zeros, which denote the number of $1$'s and $0$'s encountered so far. Let us iterate through the string. When we are at position $i$ (indexed from $1$), we want to answer two questions: what is the cost for changing the string into $11..000$ (where number of $1$'s = $i$) and what is the cost for changing the string into $00..111$ (where number of $0$'s = $i$). Assuming that done_zeros and done_ones also consider the current index, the answer to the first question is done_zeros + num_ones - done_ones. This is because done_zeros $0$'s must be converted to $1$'s, and num_ones - done_ones $1$'s must be converted to $0$'s. Similarly, the answer for the second question is done_ones + num_zeros - done_zeros. The answer is the minimum over all such changes possible. Please do not forget to consider the all $1$'s and all $0$'s string in the above solution. Time Complexity: $O(N)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N = 1e5 + 5;\n \nint32_t main()\n{\n\tIOS;\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tstring s;\n\t\tcin >> s;\n\t\tint suf0 = 0, suf1 = 0;\n\t\tfor(auto &it:s)\n\t\t{\n\t\t\tsuf0 += (it == '0');\n\t\t\tsuf1 += (it == '1');\n\t\t}\n\t\tint ans = min(suf0, suf1); //Make whole string 0/1\n\t\tint pref0 = 0, pref1 = 0;\n\t\tfor(auto &it:s)\n\t\t{\n\t\t\tpref0 += (it == '0'), suf0 -= (it == '0');\n\t\t\tpref1 += (it == '1'), suf1 -= (it == '1');\n\t\t\t//Cost of making string 0*1*\n\t\t\tans = min(ans, pref1 + suf0);\n\t\t\t//Cost of making string 1*0*\n\t\t\tans = min(ans, pref0 + suf1);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1363",
    "index": "C",
    "title": "Game On Leaves",
    "statement": "Ayush and Ashish play a game on an unrooted tree consisting of $n$ nodes numbered $1$ to $n$. Players make the following move in turns:\n\n- Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $1$.\n\nA tree is a connected undirected graph without cycles.\n\nThere is a special node numbered $x$. The player who removes this node wins the game.\n\nAyush moves first. Determine the winner of the game if each player plays optimally.",
    "tutorial": "Key Idea: The main idea of this problem is to think backwards. Instead of thinking about how the game will proceed, we think about how the penultimate state of the game will look like, etc. Also, we take care of the cases where the game will end immediately (i.e, when the special node is a leaf node). Detailed Explanation: First, let us take care of the cases where the game ends immediately. This only occurs when the special node $x$ is a leaf node, so all we must do is check that deg[$x$] = 1. Please note that $n = 1$ must be handled seperately here (just output Ayush). Now, in the case where $x$ is not a leaf node, the answer is as follows: Ashish wins if $n$ is odd, and Ayush wins if $n$ is even. I will provide a short sketch of the proof below. With the hint from the key idea, let us analyze this game backwards. (I will assume that $n>10$ for the sake of a clear explanation). When $x$ is removed from the game, it cannot be the only node remaining (because then the previous player could have also removed $x$, and thus he did not play optimally). Assume the structure of the game is something like the following WLOG at the last step (The tree attached to $x$ could be any tree): Consider also that Ayush won, and the last move was to remove $x$. Now, what could have been the state before this move? If Ashish had removed a node from the tree, then he did not play optimally - since he could have removed $x$! Thus, he must have removed something from $x$, which looks like the following: Considering this state, Ashish should not infact remove $6$, and instead remove something from the tree! Hence, the state that we assumed the game should look like at the end is impossible - and indeed, the tree attached to $x$ should only consist of only one node (we already proved that $x$ cannot be the only node remaining). Thus, all we have to do is find who's turn it will be when the structure of the tree is as follows: It is Ashish's turn if $n$ is odd, and Ayush's turn if $n$ is even. QED! Time complexity: $O(N)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N = 2e5 + 5;\n \nint n, x;\nint deg[N];\nvector<int> g[N];\n \nint32_t main()\n{\n\tIOS;\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tmemset(deg, 0, sizeof(deg));\n\t\tcin >> n >> x;\n\t\tfor(int i = 1; i <= n - 1; i++)\n\t\t{\n\t\t\tint u, v;\n\t\t\tcin >> u >> v;\n\t\t\tdeg[u]++, deg[v]++;\n\t\t}\n\t\tif(deg[x] <= 1)\n\t\t\tcout << \"Ayush\" << endl;\n\t\telse\n\t\t{\n\t\t\tif(n % 2)\n\t\t\t\tcout << \"Ashish\" << endl;\n\t\t\telse\n\t\t\t\tcout << \"Ayush\" << endl;\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "games",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1363",
    "index": "D",
    "title": "Guess The Maximums",
    "statement": "\\textbf{This is an interactive problem.}\n\nAyush devised a new scheme to set the password of his lock. The lock has $k$ slots where each slot can hold integers from $1$ to $n$. The password $P$ is a sequence of $k$ integers each in the range $[1, n]$, $i$-th element of which goes into the $i$-th slot of the lock.\n\nTo set the password of his lock, Ayush comes up with an array $A$ of $n$ integers each in the range $[1, n]$ (not necessarily distinct). He then picks $k$ \\textbf{non-empty mutually disjoint} subsets of indices $S_1, S_2, ..., S_k$ $(S_i \\underset{i \\neq j} \\cap S_j = \\emptyset)$ and sets his password as $P_i = \\max\\limits_{j \\notin S_i} A[j]$. In other words, the $i$-th integer in the password is equal to the maximum over all elements of $A$ whose indices do not belong to $S_i$.\n\nYou are given the subsets of indices chosen by Ayush. You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the maximum of all elements of the array with index in this subset. \\textbf{You can ask no more than 12 queries}.",
    "tutorial": "Key Idea: The maximum of the array is the password integer for all except atmost $1$ position. We find the subset (if the maximum is in a subset) in which the maximum exists using binary search, and then query the answer for this subset seperately. (For all the subsets, the answer is the maximum for the whole array). Detailed Explanation: I will be working with an example in this explanation; let the array be $a = [1,1,2,3,2,5,7,8,9,11,4]$, and array of length $11$, and let there be $10$ subsets, with first subset being $[1]$, second being $[2]$, etc (every index except $11$ is a subset). Thus, $a[1] = 1, a[3] = 2$, etc. First, let us query the maximum of the whole array using $1$ query. This gives $11$ as the output in our case. Now, we check if the maximum is present in the subsets. We do this in the following manner: we query the first half of the subsets. If the value returned here is not the maximum, then we search in the second half - else, we know that the maximum must be in the first half of subsets. Hence, we binary search in the first half itself. To proceed with our example, we query the maximum from subsets $1$ to $5$, which turns out to be $3$. Thus, $11$ must be present in subsets $6$ to $10$. Then we will query $6$ to $8$, which will return the value $8$ - thus, the maximum may be present in subset $9$, or $10$. Thus, we query subset $9$ and find that it does not contain the maximum. This step will require at most $10$ queries, and we will get a subset which (may or may not) contain the maximum element (remember, it is possible that the maximum element was not in any subset!) Thus, in our final query we ask about the maximum over all indices other than the canditate subset we found above. In our example, We query every index except those in subset $10$ using $1$ query, which gives us the answer as $9$. Hence, the password is $[11,11,11,11,11,11,11,11,11,9]$. Note: The bound of $12$ queries is tight. Time complexity: $O(N)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n#define vint vector<int>\n \nint interact(vint S){\n\tcout << \"? \" << S.size() << ' ';\n\tfor(int i : S)\n\t\tcout << i << ' ';\n\tcout << endl;\n\tint x;\n\tcin >> x;\n\treturn x;\n}\n \nvint get_complement(vint v, int n){\n\tvint ask, occur(n + 1);\n\tfor(int i : v)\n\t\toccur[i] = 1;\n\tfor(int i = 1; i <= n; i++)\n\t\tif(!occur[i])\n\t\t\task.push_back(i);\n\treturn ask;\n}\n \nint main(){\n\tint tc;\n\tcin >> tc;\n\twhile(tc--){\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<vint> S(k);\n\t\tvint ans(k);\n\t\tfor(int i = 0; i < k; i++){\n\t\t\tint c;\n\t\t\tcin >> c;\n\t\t\tS[i].resize(c);\n\t\t\tfor(int j = 0; j < c; j++)\n\t\t\t\tcin >> S[i][j];\n\t\t}\n\t\tvint ask;\n\t\tfor(int i = 1; i <= n; i++)\n\t\t\task.push_back(i);\n\t\tint max_element = interact(ask);\n\t\t//find subset with max element\n\t\tint st = 0, en = k - 1;\n\t\twhile(st < en){\n\t\t\tint mid = (st + en) / 2;\n\t\t\task.clear();\n\t\t\tfor(int i = 0; i <= mid; i++)\n\t\t\t\tfor(int j : S[i])\n\t\t\t\t\task.push_back(j);\n\t\t\tint x = interact(ask);\n\t\t\tif(x == max_element)\n\t\t\t\ten = mid;\n\t\t\telse st = mid + 1;\n\t\t}\n\t\task = get_complement(S[st], n);\n\t\tfor(int i = 0; i < k; i++)\n\t\t\tif(i == st)\n\t\t\t\tans[i] = interact(ask);\n\t\t\telse ans[i] = max_element;\n\t\tcout << \"! \";\n\t\tfor(int i : ans)\n\t\t\tcout << i << ' ';\n\t\tcout << endl;\n\t\tstring correct;\n\t\tcin >> correct;\n\t}\n}",
    "tags": [
      "binary search",
      "implementation",
      "interactive",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1363",
    "index": "E",
    "title": "Tree Shuffling",
    "statement": "Ashish has a tree consisting of $n$ nodes numbered $1$ to $n$ rooted at node $1$. The $i$-th node in the tree has a cost $a_i$, and binary digit $b_i$ is written in it. He wants to have binary digit $c_i$ written in the $i$-th node in the end.\n\nTo achieve this, he can perform the following operation any number of times:\n\n- Select any $k$ nodes from the subtree of any node $u$, and shuffle the digits in these nodes as he wishes, incurring a cost of $k \\cdot a_u$. Here, he can choose $k$ ranging from $1$ to the size of the subtree of $u$.\n\nHe wants to perform the operations in such a way that every node finally has the digit corresponding to its target.\n\nHelp him find the minimum total cost he needs to spend so that after all the operations, every node $u$ has digit $c_u$ written in it, or determine that it is impossible.",
    "tutorial": "Key Idea: Let the parent of node $i$ be $p$. If $a[i] \\geq a[p]$, we can do the shuffling which was done at $i$, at $p$ instead. Thus, we can do the operation $a[i] = min(a[i],a[p])$. Detailed Explanation: Let us denote nodes that have $b_i = 1$ and $c_i = 0$ as type $1$, and those that have $b_i = 0$ and $c_i = 1$ as type $2$. Firstly, the answer is $-1$ if and only if the number of nodes of type $1$ and type $2$ are unequal. We also observe that only nodes of type $1$ and $2$ should be shuffled - it is unoptimal to shuffle those which already have $b[i] = c[i]$. Thus, we should try to exchange the values of type $1$ and type $2$ nodes. We use the key idea by going down from the root, and at every node $i$, setting $a[i] = min(a[i],a[p])$ where $p$ is the parent node of $i$ in the tree. Thus, the $a[i]$'s now follow a special structure: they are non-increasing from the root to the leaves! This paves the way for our greedy solution: we will go upwards from the leaves, and at each node $i$ interchange type $1$ and type $2$ nodes until we have no nodes in one of these types. Then, we pass on the remaining nodes to the parent to be shuffled. Time complexity: $O(N)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N = 2e5 + 5;\n \nint n, cost = 0;\nint arr[N], b[N], c[N];\nvector<int> g[N];\n \npair<int, int> dfs(int u, int par, int mn)\n{\n\tpair<int, int> a = {0, 0};\n\tif(b[u] != c[u])\n\t{\n\t\tif(b[u])\n\t\t\ta.first++;\n\t\telse\n\t\t\ta.second++;\n\t}\n\tfor(auto &it:g[u])\n\t{\n\t\tif(it == par)\n\t\t\tcontinue;\n\t\tpair<int, int> p = dfs(it, u, min(mn, arr[u]));\n\t\ta.first += p.first;\n\t\ta.second += p.second;\n\t}\n\tif(arr[u] < mn)\n\t{\n\t\tint take = min(a.first, a.second);\n\t\tcost += 2 * take * arr[u];\n\t\ta.first -= take;\n\t\ta.second -= take;\n\t}\n\treturn a;\n}\n \nint32_t main()\n{\n\tIOS;\n\tcin >> n;\n\tfor(int i = 1; i <= n; i++)\n\t\tcin >> arr[i] >> b[i] >> c[i];\n\tfor(int i = 1; i <= n - 1; i++)\n\t{\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\t\n\tpair<int, int> ans = dfs(1, 0, 2e9);\n\tif(ans.first || ans.second)\n\t\tcout << -1;\n\telse\n\t\tcout << cost;\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1363",
    "index": "F",
    "title": "Rotating Substrings",
    "statement": "You are given two strings $s$ and $t$, each of length $n$ and consisting of lowercase Latin alphabets. You want to make $s$ equal to $t$.\n\nYou can perform the following operation on $s$ any number of times to achieve it —\n\n- Choose any substring of $s$ and rotate it clockwise once, that is, if the selected substring is $s[l,l+1...r]$, then it becomes $s[r,l,l + 1 ... r - 1]$. All the remaining characters of $s$ stay in their position. For example, on rotating the substring $[2,4]$ , string \"abcde\" becomes \"adbce\".\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nFind the minimum number of operations required to convert $s$ to $t$, or determine that it's impossible.",
    "tutorial": "Key Idea: We note that a clockwise rotation is the same as taking a character at any position in the string, and inserting it anywhere to it's left. Thus, we process the strings from the end, build the suffixes and move towards the prefix. Detailed Explanation: The answer is $-1$ if both s and t do not have the same count of every character. Else, we can prove that it is always possible to convert s to t. Now, let us remove the largest common suffix of both s and t. Now, using the key idea, we consider a move as picking a character at any position in s and inserting it to it's left. So, let us just \"pick up\" characters, and use them in any order as we iterate through s. Our total cost is equal to the number of characters we picked overall. After removing common suffixes, suppose the last character of s is c. Since the last characters of s and t differ, we can pick up this c. Now, we want to make s[1,n-1] equal to t[1,n], given that we can insert c anywhere in s. Let us consider dp[i][j] (only for when j $\\geq$ i, which means that we want to make s[1,i] = t[1,j] by inserting some characters that we have picked. What characters can we pick? We can pick the characters whose count in s[i+1,n] > t[j+1,n]. The base case is dp[0][i] = 0. Now, let us write the transitions for this dp solution. Suppose that t[j] = x. There are three possible transitions from dp[i][j]: If the count of x in s[i+1.n] is greater than it's count in t[j+1,n], then we can reach the state dp[i][j-1]. If s[i] = t[j], then we can reach the state dp[i-1][j-1]. We can pick up the character at position i (and insert it later) to reach dp[i-1][j] (with an additional cost of $1$). The final answer is dp[n][n]. Time complexity: $O(N^2)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n \nconst int N = 2005;\n \nint n;\nstring s, t;\nint suf[26][N], suf2[26][N];\nint cache[N][N];\n \nint dp(int i, int j)\n{\n\tif(j == 0)\n\t\treturn 0;\n\tint &ans = cache[i][j];\n\tif(ans != -1)\n\t\treturn ans;\n\tans = 2e9;\n\tif(i > 0)\n\t{\n\t\tans = 1 + dp(i - 1, j);\n\t\tif(s[i - 1] == t[j - 1])\n\t\t\tans = min(ans, dp(i - 1, j - 1));\n\t}\n\tint ch = t[j - 1] - 'a';\n\tif(suf[ch][i + 1] - suf2[ch][j + 1] > 0)\n\t\tans = min(ans, dp(i, j - 1));\n\treturn ans;\n}\n \nint32_t main()\n{\n\tIOS;\n\tint tc;\n\tcin >> tc;\n\twhile(tc--)\n\t{\n\t\tcin >> n >> s >> t;\n\t\tfor(int i = 0; i <= n; i++)\n\t\t\tfor(int j = 0; j <= n; j++)\n\t\t\t\tcache[i][j] = -1;\n\t\tfor(int i = 0; i <= 25; i++)\n\t\t\tfor(int j = 0; j <= n + 1; j++)\n\t\t\t\tsuf[i][j] = suf2[i][j] = 0;\n\t\tfor(int i = n; i >= 1; i--)\n\t\t{\n\t\t\tfor(int j = 0; j < 26; j++)\n\t\t\t{\n\t\t\t\tsuf[j][i] = suf[j][i + 1];\n\t\t\t\tsuf2[j][i] = suf2[j][i + 1];\n\t\t\t}\n\t\t\tsuf[s[i - 1] - 'a'][i]++;\n\t\t\tsuf2[t[i - 1] - 'a'][i]++;\n\t\t}\n\t\tint ans = dp(n, n);\n\t\tif(ans > 1e9)\n\t\t\tans = -1;\n\t\tcout << ans << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1364",
    "index": "A",
    "title": "XXXXX",
    "statement": "Ehab loves number theory, but for some reason he hates the number $x$. Given an array $a$, find the length of its longest subarray such that the sum of its elements \\textbf{isn't} divisible by $x$, or determine that such subarray doesn't exist.\n\nAn array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "Let's start with the whole array. If every element in it is divisible by $x$, the answer is $-1$; if its sum isn't divisible by $x$, the answer is $n$. Otherwise, we must remove some elements. The key idea is that removing an element that is divisible by $x$ doesn't do us any benefits, but once we remove an element that isn't, the sum won't be divisible by $x$. So let the first non-multiple of $x$ be at index $l$, and the last one be at index $r$. We must either remove the prefix all the way up to $l$ or the suffix all the way up to $r$, and we'll clearly remove whichever shorter.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint main()\\n{\\n\\tint t;\\n\\tscanf(\\\"%d\\\",&t);\\n\\twhile (t--)\\n\\t{\\n\\t\\tint n,x,sum=0,l=-1,r;\\n\\t\\tscanf(\\\"%d%d\\\",&n,&x);\\n\\t\\tfor (int i=0;i<n;i++)\\n\\t\\t{\\n\\t\\t\\tint a;\\n\\t\\t\\tscanf(\\\"%d\\\",&a);\\n\\t\\t\\tif (a%x)\\n\\t\\t\\t{\\n\\t\\t\\t\\tif (l==-1)\\n\\t\\t\\t\\tl=i;\\n\\t\\t\\t\\tr=i;\\n\\t\\t\\t}\\n\\t\\t\\tsum+=a;\\n\\t\\t}\\n\\t\\tif (sum%x)\\n\\t\\tprintf(\\\"%d\\\\n\\\",n);\\n\\t\\telse if (l==-1)\\n\\t\\tprintf(\\\"-1\\\\n\\\");\\n\\t\\telse\\n\\t\\tprintf(\\\"%d\\\\n\\\",n-min(l+1,n-r));\\n\\t}\\n}\"",
    "tags": [
      "brute force",
      "data structures",
      "number theory",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1364",
    "index": "B",
    "title": "Most socially-distanced subsequence",
    "statement": "Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\\ldots$, $s_k$ of length at least $2$ such that:\n\n- $|s_1-s_2|+|s_2-s_3|+\\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$.\n- Among all such subsequences, choose the one whose length, $k$, is as small as possible.\n\nIf multiple subsequences satisfy these conditions, you are allowed to find any of them.\n\nA sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.\n\nA permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.",
    "tutorial": "TL;DR the answer contains the first element, last element, and all the local minima and maxima, where a local minimum is an element less than its 2 adjacents, and a local maximum is an element greater than it 2 adjacents. Let's look at the expression in the problem for 3 numbers. If $a>b$ and $b>c$ or if $a<b$ and $b<c$, $|a-b|+|b-c|=|a-c|$, so it's never optimal to use $a$, $b$, and $c$ in a row because you can use just $a$ and $c$ and achieve a shorter subsequence. If you keep erasing your $b$'s from the original permutation, you'll end up with the first element, the last element, and the local minima and maxima. You can see that erasing any of them would decrease the expression, so this is the optimal answer.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint p[100005];\\nint main()\\n{\\n\\tint t;\\n\\tscanf(\\\"%d\\\",&t);\\n\\twhile (t--)\\n\\t{\\n\\t\\tint n;\\n\\t\\tscanf(\\\"%d\\\",&n);\\n\\t\\tfor (int i=1;i<=n;i++)\\n\\t\\tscanf(\\\"%d\\\",&p[i]);\\n\\t\\tvector<int> ans;\\n\\t\\tfor (int i=1;i<=n;i++)\\n\\t\\t{\\n\\t\\t\\tif (i==1 || i==n || (p[i-1]<p[i])!=(p[i]<p[i+1]))\\n\\t\\t\\tans.push_back(p[i]);\\n\\t\\t}\\n\\t\\tprintf(\\\"%d\\\\n\\\",ans.size());\\n\\t\\tfor (int i:ans)\\n\\t\\tprintf(\\\"%d \\\",i);\\n\\t\\tprintf(\\\"\\\\n\\\");\\n\\t}\\n}\"",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1364",
    "index": "C",
    "title": "Ehab and Prefix MEXs",
    "statement": "Given an array $a$ of length $n$, find another array, $b$, of length $n$ such that:\n\n- for each $i$ $(1 \\le i \\le n)$ $MEX(\\{b_1$, $b_2$, $\\ldots$, $b_i\\})=a_i$.\n\nThe $MEX$ of a set of integers is the smallest non-negative integer that doesn't belong to this set.\n\nIf such array doesn't exist, determine this.",
    "tutorial": "The key observation is: if for some index $i$, $a_i \\neq a_{i-1}$, then $b_i$ must be equal to $a_{i-1}$, since it's the only way to even change the prefix $MEX$. We can use this observation to fill some indices of $b$. Now, how do we fill the rest? Let's start by avoiding every element in $a$. Something special will happen if we avoid using any element from $a$ again. If we look at the first $i$ numbers in $b$, $a_i$ will indeed be excluded, so $MEX({b_1, b_2, \\ldots, b_i}) \\le a_i$. Now we need to make it as big as possible. How do we make it as big as possible? The logical thing to do is to fill the rest of $b$ with the numbers not in $a$ in increasing order. It turns out this construction always satisfies the conditions. Indeed, if we look at the first $i$ elements in $b$, every element less than $a_i$ will be present because $a_i \\le i$ and we added the rest of the elements in increasing order.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint a[100005],b[100005];\\nbool ex[100005];\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tfor (int i=1;i<=n;i++)\\n\\tscanf(\\\"%d\\\",&a[i]);\\n\\tmemset(b,-1,sizeof(b));\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\tif (a[i]!=a[i-1])\\n\\t\\t{\\n\\t\\t\\tb[i]=a[i-1];\\n\\t\\t\\tex[b[i]]=1;\\n\\t\\t}\\n\\t}\\n\\tex[a[n]]=1;\\n\\tint m=0;\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\twhile (ex[m])\\n\\t\\tm++;\\n\\t\\tif (b[i]==-1)\\n\\t\\t{\\n\\t\\t\\tb[i]=m;\\n\\t\\t\\tex[m]=1;\\n\\t\\t}\\n\\t\\tprintf(\\\"%d \\\",b[i]);\\n\\t}\\n}\"",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1364",
    "index": "D",
    "title": "Ehab's Last Corollary",
    "statement": "Given a connected undirected graph with $n$ vertices and an integer $k$, you have to either:\n\n- either find an independent set that has \\textbf{exactly} $\\lceil\\frac{k}{2}\\rceil$ vertices.\n- or find a \\textbf{simple} cycle of length \\textbf{at most} $k$.\n\nAn independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.\n\nI have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.",
    "tutorial": "The common idea is: if the graph is a tree, you can easily find an independent set with size $\\lceil\\frac{n}{2}\\rceil$ by bicoloring the vertices and taking the vertices from the more frequent color. Otherwise, the graph is cyclic. Let's get a cycle that doesn't have any edges \"cutting through it.\" In other words, it doesn't have any pair of non-adjacent vertices connected by an edge. If its length is at most $k$, print it. Otherwise, take every other vertex (take a vertex and leave a vertex) and you'll end up with a big enough independent set. How to find such cycle? Let's do a dfs in our graph. In the very first time we hit a node that has a back-edge, we take the back-edge that goes to the deepest possible node to close our cycle. This cycle can't have any edges crossing it because none of our node's ancestors has a back-edge (by definition.) Let's get any cycle in the graph. Now, let's iterate over the edges that don't belong to the cycle. Whenever we meet one that \"crosses the cycle,\" we use it to cut the cycle into 2 cycles with smaller length and keep any of them. When we finish, we'd have our desired cycle.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint pos[100005];\\nbool ex[100005];\\nvector<int> v[100005],col[100005],s;\\nvector<pair<int,int> > e;\\ndeque<int> cyc;\\nvoid dfs(int node)\\n{\\n\\tpos[node]=s.size();\\n\\tcol[pos[node]%2].push_back(node);\\n\\ts.push_back(node);\\n\\tfor (int u:v[node])\\n\\t{\\n\\t\\tif (pos[u]==-1)\\n\\t\\tdfs(u);\\n\\t\\telse if (cyc.empty() && pos[node]-pos[u]>1)\\n\\t\\t{\\n\\t\\t\\tfor (int i=pos[u];i<=pos[node];i++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tcyc.push_back(s[i]);\\n\\t\\t\\t\\tex[s[i]]=1;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\ts.pop_back();\\n}\\nint main()\\n{\\n\\tint n,m,k;\\n\\tscanf(\\\"%d%d%d\\\",&n,&m,&k);\\n\\twhile (m--)\\n\\t{\\n\\t\\tint a,b;\\n\\t\\tscanf(\\\"%d%d\\\",&a,&b);\\n\\t\\tv[a].push_back(b);\\n\\t\\tv[b].push_back(a);\\n\\t\\te.push_back({a,b});\\n\\t}\\n\\tmemset(pos,-1,sizeof(pos));\\n\\tdfs(1);\\n\\tif (cyc.empty())\\n\\t{\\n\\t\\tif (col[0].size()<col[1].size())\\n\\t\\tswap(col[0],col[1]);\\n\\t\\tprintf(\\\"1\\\\n\\\");\\n\\t\\tfor (int i=0;i<(k+1)/2;i++)\\n\\t\\tprintf(\\\"%d \\\",col[0][i]);\\n\\t}\\n\\telse\\n\\t{\\n\\t\\tfor (auto p:e)\\n\\t\\t{\\n\\t\\t\\tif (ex[p.first] && ex[p.second] && abs(pos[p.first]-pos[p.second])!=1)\\n\\t\\t\\t{\\n\\t\\t\\t\\twhile (cyc.front()!=p.first && cyc.front()!=p.second)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tex[cyc.front()]=0;\\n\\t\\t\\t\\t\\tcyc.pop_front();\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\twhile (cyc.back()!=p.first && cyc.back()!=p.second)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tex[cyc.back()]=0;\\n\\t\\t\\t\\t\\tcyc.pop_back();\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif (cyc.size()<=k)\\n\\t\\t{\\n\\t\\t\\tprintf(\\\"2\\\\n%d\\\\n\\\",cyc.size());\\n\\t\\t\\tfor (int i:cyc)\\n\\t\\t\\tprintf(\\\"%d \\\",i);\\n\\t\\t}\\n\\t\\telse\\n\\t\\t{\\n\\t\\t\\tprintf(\\\"1\\\\n\\\");\\n\\t\\t\\tfor (int i=0;i<(k+1)/2;i++)\\n\\t\\t\\tprintf(\\\"%d \\\",cyc[2*i]);\\n\\t\\t}\\n\\t}\\n}\"",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1364",
    "index": "E",
    "title": "X-OR",
    "statement": "\\textbf{This is an interactive problem!}\n\nEhab has a hidden permutation $p$ of length $n$ consisting of the elements from $0$ to $n-1$. You, for some reason, want to figure out the permutation. To do that, you can give Ehab $2$ \\textbf{different} indices $i$ and $j$, and he'll reply with $(p_i|p_j)$ where $|$ is the bitwise-or operation.\n\nEhab has just enough free time to answer $4269$ questions, and while he's OK with answering that many questions, he's too lazy to play your silly games, so he'll fix the permutation beforehand and will \\textbf{not} change it depending on your queries. Can you guess the permutation?",
    "tutorial": "The common idea is: if we find the index that contains $0$, we can query it with every element in $p$ and finish in $n$ queries (if you didn't do that, pleaaase share your solution.) How to get this index? Let's try to make a magic function that takes an index $i$ and tells us $p_i$. Assume you have an array $z$ such that $z_j$ is some index in the permutation that has a $0$ in the $j^{th}$ bit. Building our magic function with it turns out to be very easy. We'll just return $query(i,z_0)$&$query(i,z_1)$&$\\ldots$&$query(i,z_{10})$. Why does that work? If $p_i$ has a $1$ in the $j^{th}$ bit, this expression will also have a $1$ because $p_i$ will make every single clause have a $1$. If it has a $0$, $query(i,z_j)$ will also have a $0$, making the whole expression have a $0$! But how do we find $z$? This turns out to be very easy. We'll query random pairs of indices, see where the result has a $0$, and update $z$. We stop once we fill every index in $z$. This works quickly because for any bit, at least half the numbers from $0$ to $n-1$ will have a $0$. Now we already have an $nlog(n)$ solution (call our magic function with every index,) but how to make less calls? Let's carry an index $idx$ that's supposed to have the index of $0$ in the end, and let $p_{idx}$ be stored in $val$. Initially, $idx$ is $1$ and $val$ could be found with our magic function. Now, let's iterate over the permutation. We'll query the current index, $i$, with $idx$. If the result isn't a subset of $val$, $p_i$ can't be $0$, so let's throw it in the trash. Otherwise, we'll make $idx$ equal to $i$ and use our magic function to update $val$.  In my analysis, I'll use $c$ to denote something that's clearly small but needs big math to analyze it, so it's better to omit these analysis (or something that I can't analyze nervous chuckles.) Since every time $val$ is replaced with a subset of it, we only call our magic function at most $log(n)$ times, so the number of queries is at most $2n+log^2(n)+c$. The cool thing about this solution is that it barely relies on randomness, so even if you run it for a million test cases, it would still pass. In fact, try to make it deterministic with $\\frac{n}{2}$ more queries. There's a nice speed-up, but it relies much more on randomness: ask your indices in a random order, and make an itsy bitsy edit in the magic function: if $val$ has a $0$ in the $j^{th}$ bit, you don't really need to query $i$ with $z_j$. You can set the $j^{th}$ bit in the result to $0$ right away because $p_i$ is a subset of $val$. That way, it doesn't always do $log(n)$ queries; it does however many ones $val$ has queries. This actually improves the solution to $2n+2log(n)+c$ on average! The intuition is: you start with a random number that has $\\frac{log(n)}{2}$ ones in it (on average,) and every time you face a subset of it, the number of ones is expected to be halved, so the number of queries is around $log(n)+\\frac{log(n)}{2}+\\frac{log(n)}{4}+\\ldots<2log(n)$.  I'll describe a way to start with $n$ candidates to be $0$ and end up with $\\sqrt{n}$ candidates. Let's query random pairs until we find a pair whose bitwise-or has at most $\\frac{log(n)}{2}$ bits. Take one of the 2 indices in the pair (let's call it $i$) and query it with every candidate you have, and take the bitwise-and of the results. That will give you $p_i$. Now, let's make the numbers whose query result with $i$ is $p_i$ (hence, a subset of $p_i$) our new candidates. Since $i$ has at most $\\frac{log(n)}{2}$ ones, the number of its subsets is $\\sqrt{n}$, and we have our desired result! Now, to find the index of $0$, we'll just do this recursively until we have 2 candidates. We'll keep querying them with random indices until the results differ. The one giving a smaller result is our $0$. This solution does $2n+\\sqrt{n}+\\sqrt{\\sqrt{n}}+\\ldots+c$ queries. You may think this is much worse than the first solution, but apparently $\\sqrt{n}$ is smaller than $log^2(n)$ for small $n$. And by small, I mean ~$10^5$. Thanks, Mohammad_Yasser for this solution. Assume you have 2 candidates for $0$ called $a$ and $b$ such that one of them is the index of $0$ at the end of our algorithm, and we always know $(p_a|p_b)$. Let's iterate over our indices in a random order and try to update $a$ and $b$. Assume the current index is $c$. Let's query to get $(p_b|p_c)$. We have 3 cases: If $(p_a|p_b)<(p_b|p_c)$, $p_c$ can't be $0$, so we'll throw it away. If $(p_a|p_b)>(p_b|p_c)$, $p_a$ can't be $0$, so we'll throw it away and change $a$ to be $c$. Otherwise, $p_b$ can't be $0$ because that would imply $p_a=p_c$ (recall that $p$ is a permutation.) So we can throw it away and change $b$ to be $c$. But notice that we now don't know $(p_a|p_b)$, so we're gonna have to make one more query, since we need to keep track of it. After we're done, we can narrow our 2 candidates down to 1 with the same way described in the previous solution.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\\nint p[(1<<11)+5];\\nint query(int i,int j)\\n{\\n\\tprintf(\\\"? %d %d\\\\n\\\",i,j);\\n\\tfflush(stdout);\\n\\tint ans;\\n\\tscanf(\\\"%d\\\",&ans);\\n\\tassert(ans!=-1);\\n\\treturn ans;\\n}\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tvector<int> qp;\\n\\tfor (int i=1;i<=n;i++)\\n\\tqp.push_back(i);\\n\\tshuffle(qp.begin(),qp.end(),rng);\\n\\tint a=qp[0],b=qp[1],val=query(a,b);\\n\\tfor (int i=2;i<n;i++)\\n\\t{\\n\\t\\tint tmp=query(b,qp[i]);\\n\\t\\tif (tmp<val)\\n\\t\\t{\\n\\t\\t\\ta=qp[i];\\n\\t\\t\\tval=tmp;\\n\\t\\t}\\n\\t\\telse if (tmp==val)\\n\\t\\t{\\n\\t\\t\\tb=qp[i];\\n\\t\\t\\tval=query(a,qp[i]);\\n\\t\\t}\\n\\t}\\n\\tint idx;\\n\\twhile (1)\\n\\t{\\n\\t\\tint i=uniform_int_distribution<int>(1,n)(rng);\\n\\t\\tif (i==a || i==b)\\n\\t\\tcontinue;\\n\\t\\tint t1=query(i,a),t2=query(i,b);\\n\\t\\tif (t1!=t2)\\n\\t\\t{\\n\\t\\t\\tidx=(t1<t2? a:b);\\n\\t\\t\\tbreak;\\n\\t\\t}\\n\\t}\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\tif (i!=idx)\\n\\t\\tp[i]=query(i,idx);\\n\\t}\\n\\tprintf(\\\"!\\\");\\n\\tfor (int i=1;i<=n;i++)\\n\\tprintf(\\\" %d\\\",p[i]);\\n\\tprintf(\\\"\\\\n\\\");\\n\\tfflush(stdout);\\n}\"",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "divide and conquer",
      "interactive",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1365",
    "index": "A",
    "title": "Matrix Game",
    "statement": "Ashish and Vivek play a game on a matrix consisting of $n$ rows and $m$ columns, where they take turns claiming cells. Unclaimed cells are represented by $0$, while claimed cells are represented by $1$. The initial state of the matrix is given. There can be some claimed cells in the initial state.\n\nIn each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.\n\nIf Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.\n\nOptimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.",
    "tutorial": "Key Idea: Vivek and Ashish can never claim cells in rows and columns which already have at least one cell claimed. So we need to look at the parity of minimum of the number of rows and columns which have no cells claimed initially. Solution: Let $a$ be the number of rows which do not have any cell claimed in them initially and similarly $b$ be the number of columns which do not have any cell claimed initially. Each time a player makes a move both $a$ and $b$ decrease by $1$, since they only claim cells in rows and columns with no claimed cells. If either one of $a$ or $b$ becomes $0$, the player whose turn comes next loses the game. Since both $a$ and $b$ decrease by $1$ after each move, $\\min(a, b)$ becomes $0$ first. So, if $\\min(a, b)$ is odd, Ashish wins the game otherwise Vivek wins. Time complexity: $O(n \\cdot m)$",
    "code": "\n#include \nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n\nconst int N = 51;\n\nint n, m;\nint a[N][N];\n\nint32_t main()\n{\n\tIOS;\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tcin >> n >> m;\n\t\tset< int > r, c;\n\t\tfor(int i = 1; i <= n; i++)\n\t\t{\n\t\t\tfor(int j = 1; j <= m; j++)\n\t\t\t{\n\t\t\t\tcin >> a[i][j];\n\t\t\t\tif(a[i][j] == 1)\n\t\t\t\t\tr.insert(i), c.insert(j);\n\t\t\t}\n\t\t}\n\t\tint mn = min(n — r.size(), m — c.size());\n\t\tif(mn % 2)\n\t\t\tcout << \"Ashish\" << endl;\n\t\telse\n\t\t\tcout << \"Vivek\" << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1365",
    "index": "B",
    "title": "Trouble Sort",
    "statement": "Ashish has $n$ elements arranged in a line.\n\nThese elements are represented by two integers $a_i$ — the value of the element and $b_i$ — the type of the element (there are only two possible types: $0$ and $1$). He wants to sort the elements in non-decreasing values of $a_i$.\n\nHe can perform the following operation any number of times:\n\n- Select any two elements $i$ and $j$ such that $b_i \\ne b_j$ and swap them. That is, he can only swap two elements of different types in one move.\n\nTell him if he can sort the elements in non-decreasing values of $a_i$ after performing any number of operations.",
    "tutorial": "Key Idea: If there is at least one element of type $0$ and at least one element of type $1$, we can always sort the array. Solution: If all the elements are of the same type, we cannot swap any two elements. So, in this case, we just need to check if given elements are already in sorted order. Otherwise, there is at least one element of type $0$ and at least one element of type $1$. In this case, it is possible to swap any two elements! We can swap elements of different types using only one operation. Suppose we want to swap two elements $a$ and $b$ of the same type. We can do it in $3$ operations. Let $c$ be an element of the type different from $a$ and $b$. We can first swap $a$ and $c$, then swap $b$ and $c$ and then swap $a$ and $c$ again. In doing so, $c$ remains at its initial position and $a$, $b$ are swapped. This is exactly how we swap two integers using a temporary variable. Since we can swap any two elements, it is always possible to sort the array in this case. Time complexity: $O(n)$",
    "code": "\n#include \nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n\nconst int N = 1e3 + 5;\n\nint n;\nint a[N], b[N];\n\nint32_t main()\n{\n\tIOS;\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tcin >> n;\n\t\tbool sorted = 1, have0 = 0, have1 = 0;\n\t\tfor(int i = 1; i <= n; i++)\n\t\t{\n\t\t\tcin >> a[i];\n\t\t\tif(i >= 2 && a[i] < a[i - 1])\n\t\t\t\tsorted = 0;\n\t\t}\n\t\tfor(int i = 1; i <= n; i++)\n\t\t{\n\t\t\tcin >> b[i];\n\t\t\tif(!b[i])\n\t\t\t\thave0 = 1;\n\t\t\telse\n\t\t\t\thave1 = 1;\n\t\t}\n\t\tif(have0 && have1)\n\t\t\tcout << \"Yes\" << endl;\n\t\telse if(sorted)\n\t\t\tcout << \"Yes\" << endl;\n\t\telse\n\t\t\tcout << \"No\" << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1365",
    "index": "C",
    "title": "Rotation Matching",
    "statement": "After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $n$. Let's call them $a$ and $b$.\n\nNote that a permutation of $n$ elements is a sequence of numbers $a_1, a_2, \\ldots, a_n$, in which every number from $1$ to $n$ appears exactly once.\n\nThe message can be decoded by an arrangement of sequence $a$ and $b$, such that the number of matching pairs of elements between them is maximum. A pair of elements $a_i$ and $b_j$ is said to match if:\n\n- $i = j$, that is, they are at the same index.\n- $a_i = b_j$\n\nHis two disciples are allowed to perform the following operation any number of times:\n\n- choose a number $k$ and cyclically shift one of the permutations to the left or right $k$ times.\n\nA single cyclic shift to the left on any permutation $c$ is an operation that sets $c_1:=c_2, c_2:=c_3, \\ldots, c_n:=c_1$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $c$ is an operation that sets $c_1:=c_n, c_2:=c_1, \\ldots, c_n:=c_{n-1}$ simultaneously.\n\nHelp Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.",
    "tutorial": "Key Idea: We only need to perform shifts on one of the arrays. Moreover, all the shifts can be of the same type (right or left)! Solution: First of all, a left cyclic shift is the same as $n - 1$ right cyclic shifts and vice versa. So we only need to perform shifts of one type, say right. Moreover, a right cyclic shift of $b$ is the same as performing a left cyclic shift on $a$ and vice versa. So we don't need to perform any shifts on $b$. Now the problem reduces to finding the maximum number of matching pairs over all right cyclic shifts of $a$. Since $n$ right cyclic shifts on $a$ results in $a$ again, there are only $n - 1$ right cyclic shifts possible. Since both arrays are a permutation, each element in $a$ would match with its corresponding equal element in $b$ only for one of the shifts. For example, if $a$ is $\\{{2, 3, 1\\}}$ and $b$ is $\\{{3, 1, 2\\}}$, the number $3$ in $a$ would match with the number $3$ in $b$ only if one right cyclic shift is performed. So for each element in $a$ we can find the number of right cyclic shifts after which it would match with its corresponding equal element in $b$. If $a_i$ = $b_j$, then $a_i$ would match with $b_j$ after $k = j - i$ right cyclic shifts. If $j - i \\lt 0$, then $a_i$ would with $b_j$ after $n - j + i$ shifts. Now for each shift, we can find the number of matching pairs and take the maximum. Time complexity: $O(n)$ or $O(n \\cdot log(n))$ if you use a map.",
    "code": "\n#include \nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n\nconst int N = 2e5 + 5;\n\nint n;\nint a[N], b[N], pos[N];\nmap< int, int > offset;\n\nint32_t main()\n{\n\tIOS;\n\tcin >> n;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tcin >> a[i];\n\t\tpos[a[i]] = i;\n\t}\n\tfor(int i = 1; i <= n; i++)\n\t\tcin >> b[i];\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tint cur = pos[b[i]] - i;\n\t\tif(cur < 0)\n\t\t\tcur += n;\n\t\toffset[cur]++;\n\t}\n\tint ans = 0;\n\tfor(auto &it:offset)\n\t\tans = max(ans, it.second);\n\tcout << ans;\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1365",
    "index": "D",
    "title": "Solve The Maze",
    "statement": "Vivek has encountered a problem. He has a maze that can be represented as an $n \\times m$ grid. Each of the grid cells may represent the following:\n\n- Empty — '.'\n- Wall — '#'\n- Good person  — 'G'\n- Bad person — 'B'\n\nThe only escape from the maze is at cell $(n, m)$.\n\nA person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' \\textbf{cannot be blocked} and \\textbf{can be travelled through}.\n\nHelp him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.\n\n\\textbf{It is guaranteed that the cell $(n,m)$ is empty.} Vivek can also block this cell.",
    "tutorial": "Key Idea: We can block all empty neighbouring cells of bad people and then check if all good people can escape and no bad people are able to escape. Solution: Consider all the neighbouring cells of bad people. There shouldn't be any path from these cells to the cell $(n, m)$. If there is a path from any such cell, the bad person adjacent to that cell can also then reach the cell $(n, m)$. So, if any good and bad people are in adjacent cells, the answer is \"No\". Based on this idea, we can block any empty cell neighbouring a bad person. Suppose there is another solution in which a cell $(i, j)$ neighbouring a bad person does not need to be blocked. There still won't be any path from $(i, j)$ to $(n, m)$ in that solution. So we can block $(i, j)$ in that solution too without affecting the solution itself. It is sufficient to block only the empty neighbouring cells of bad people and check the required conditions, which can be done using a bfs on the grid. Proof: We will assume there are no adjacent good and bad people since in that case, the answer is \"No\". There are three cases: A bad person is adjacent to the cell $(n, m)$. In this case, the cell $(n, m)$ must be blocked. Now no one will be able to escape. If there is at least one good person present, the answer is \"No\". If after blocking the neighbouring cells of bad people, there is some good person who is not able to escape, then the answer is again \"No\". Otherwise, the answer is always \"Yes\". Suppose there is some path from a bad person at cell $(i, j)$ to the cell $(n, m)$. One of the neighbours of this person must be another bad person since the only other case is an adjacent good person (which is already covered above). Extending this, all the cells on the path from $(i, j)$ to $(n, m)$ must have bad people. This is not possible since in this case, there must be a bad person adjacent to $(n, m)$ and this case is already covered above. Time complexity: $O(n \\cdot m)$",
    "code": "\n#include \nusing namespace std;\n#define int long long\ntypedef int ll;\ntypedef long double ld;\nconst ll N = 55;\nchar en = '\\n';\nll inf = 1e16;\nll mod = 1e9 + 7;\nll power(ll x, ll n, ll mod) {\n  ll res = 1;\n  x %= mod;\n  while (n) {\n    if (n & 1)\n      res = (res * x) % mod;\n    x = (x * x) % mod;\n    n >>= 1;\n  }\n  return res;\n}\nll n, m;\nchar arr[N][N];\nll dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n\nbool valid(ll i, ll j) { return i >= 1 && i <= n && j >= 1 && j <= m; }\nint32_t main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n\n  ll t;\n  cin >> t;\n  while (t--) {\n\n    cin >> n >> m;\n\n    for (ll i = 1; i <= n; i++) {\n      cin >> (arr[i] + 1);\n    }\n\n    for (ll i = 1; i <= n; i++) {\n      for (ll j = 1; j <= m; j++) {\n        if (arr[i][j] == 'B') {\n          for (ll k = 0; k < 4; k++) {\n            ll ni = i + dir[k][0];\n            ll nj = j + dir[k][1];\n            if (valid(ni, nj) && arr[ni][nj] == '.')\n              arr[ni][nj] = '#';\n          }\n        }\n      }\n    }\n\n    queue> que;\n    bool visited[n + 5][m + 5];\n    memset(visited, false, sizeof(visited));\n    if (arr[n][m] == '.') {\n      que.push({n, m});\n      visited[n][m] = true;\n    }\n    while (!que.empty()) {\n      pair curr = que.front();\n      que.pop();\n      for (ll k = 0; k < 4; k++) {\n        ll ni = curr.first + dir[k][0];\n        ll nj = curr.second + dir[k][1];\n        if (valid(ni, nj) && !visited[ni][nj] && arr[ni][nj] != '#') {\n          que.push({ni, nj});\n          visited[ni][nj] = true;\n        }\n      }\n    }\n    bool good = true;\n    for (ll i = 1; i <= n; i++) {\n      for (ll j = 1; j <= m; j++) {\n        if ((arr[i][j] == 'G' && !visited[i][j]) or\n            (arr[i][j] == 'B' && visited[i][j])) {\n          good = false;\n          break;\n        }\n      }\n    }\n    cout << (good ? \"Yes\" : \"No\") << en;\n  }\n\n  return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1365",
    "index": "E",
    "title": "Maximum Subsequence Value",
    "statement": "Ridhiman challenged Ashish to find the maximum valued subsequence of an array $a$ of size $n$ consisting of positive integers.\n\nThe value of a non-empty subsequence of $k$ elements of $a$ is defined as $\\sum 2^i$ over all integers $i \\ge 0$ such that at least $\\max(1, k - 2)$ elements of the subsequence have the $i$-th bit set in their binary representation (value $x$ has the $i$-th bit set in its binary representation if $\\lfloor \\frac{x}{2^i} \\rfloor \\mod 2$ is equal to $1$).\n\nRecall that $b$ is a subsequence of $a$, if $b$ can be obtained by deleting some(possibly zero) elements from $a$.\n\nHelp Ashish find the maximum value he can get by choosing some subsequence of $a$.",
    "tutorial": "Key Idea: For subsets of size up to $3$, their value is the bitwise OR of all elements in it. For any subset $s$ of size greater than $3$, it turns out that if we pick any subset of $3$ elements within it, then its value is greater than or equal to the value of $s$! Solution: Let $k$ be the size of the chosen subset. For $k \\le 3$, $\\max(k - 2, 1)$ is equal to $1$. This implies that their value is equal to the bitwise OR of all the elements in it (since we need to add $2^i$ for all $i$ such that at least $1$ element in the subset has $i$-th bit set in its binary representation). Consider any subset $s$ of size $k \\gt 3$. Let $i$ be any number such that the $i$-th bit is set in at least $k - 2$ elements of $s$. If we pick any $3$ elements of this subset, then by Pigeonhole principle the $i$-th bit would also be set in at least one of these elements! If this is not true then the there are $3$ elements in $s$ which do not have the $i$-th bit set, which is not possible. So for any subset $s$ of size greater than $3$, its value is less than or equal to the value of any subset consisting of $3$ elements from $s$. Hence, we only need to check all subsets of size up to $3$. Time complexity: $O(n^3)$",
    "code": "\n#include \nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n\nconst int N = 505;\n\nint n;\nint a[N];\n\nint32_t main()\n{\n\tIOS;\n\tcin >> n;\n\tfor(int i = 1; i <= n; i++)\n\t\tcin >> a[i];\n\tint ans = 0;\n\tfor(int i = 1; i <= n; i++)\n\t\tfor(int j = i; j <= n; j++)\n\t\t\tfor(int k = j; k <= n; k++)\n\t\t\t\tans = max(ans, (a[i] | a[j] | a[k]));\n\tcout << ans;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1365",
    "index": "F",
    "title": "Swaps Again",
    "statement": "Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.\n\nEach test case consists of an integer $n$ and two arrays $a$ and $b$, of size $n$. If after some (possibly zero) operations described below, array $a$ can be transformed into array $b$, the input is said to be valid. Otherwise, it is invalid.\n\nAn operation on array $a$ is:\n\n- select an integer $k$ $(1 \\le k \\le \\lfloor\\frac{n}{2}\\rfloor)$\n- swap the prefix of length $k$ with the suffix of length $k$\n\nFor example, if array $a$ initially is $\\{1, 2, 3, 4, 5, 6\\}$, after performing an operation with $k = 2$, it is transformed into $\\{5, 6, 3, 4, 1, 2\\}$.\n\nGiven the set of test cases, help them determine if each one is valid or invalid.",
    "tutorial": "Key Idea: If we consider the unordered pair of elements $\\{{a_i, a_{n - i + 1}\\}}$, then after any operation, the multiset of these pairs (irrespective of the ordering of elements within the pair) stays the same! Solution: First of all, if the multiset of numbers in $a$ and $b$ are not the same, the answer is \"No\". Moreover, if $n$ is odd, it is not possible to change the middle element of $a$, i.e., $a_{(n + 1) / 2}$. So when $n$ is odd and elements at the position $(n + 1) / 2$ do not match in $a$ and $b$, the answer is again \"No\". Suppose we pair up the elements at equal distance from the middle element in $a$ (if $n$ is even, the middle element does not exist but we can treat it as the one between positions $n / 2$ and $n / 2 + 1$). That is, we pair up $\\{{a_i, a_{n - i + 1}\\}}$ (their individual order within the pair doesn't matter). After any operation on $a$, the multiset of these pairs does not change! If we swap a prefix of length $l$ with the suffix of length $l$, then consider any element at position $i \\le l$ before the swap. It's new position is $n - l + i$ and the element it was paired with, i.e. the element at position $n - i + 1$ goes to the position $l - i + 1$. $(n - l + i) + (l - i + 1) = n + 1$, so these two elements are still paired after the swap. For example, if $a$ is $[1, 4, 2, 3]$, then the pairs are $\\{{1, 3\\}}$ and $\\{{2, 4\\}}$ (their individual ordering in the pair doesn't matter). Suppose we first apply the operation on the prefix of length $1$ and then the prefix of length $2$. After the first operation, $a$ is $[3, 4, 2, 1]$ and after the second operation, $a$ is $[2, 1, 3, 4]$. Note that in both these arrays, the pairings are still the same, i.e., $\\{{1, 3\\}}$ and $\\{{2, 4\\}}$. We conclude that in any array resulting after some number of operations, these pairings do not change with respect to the initial array. It turns out that all such arrays with same pairings as the initial array can be formed by performing these operations! So we only need to check if the multiset of these pairs in $b$ is the same as the multiset of pairs in $a$. Proof: We will show that given any array $b$ such that the multiset of pairs in $b$ is the same as the multiset of pairs in $a$, then we can form $b$ from $a$ in atmost $\\lfloor{\\frac{3 n}{2}}\\rfloor$ operations. We will start constructing the pairs in $b$ starting from $b_{n / 2}$ to $b_{1}$, i.e., we first bring elements $b_{n / 2}$ and $b_{n - n / 2 + 1}$ to their position in $a$ followed by $b_{n / 2 - 1}$ and so on. Note that if we bring the elements $b_{n / 2}$ and $b_{n - n / 2 + 1}$ to their respective positions in $a$ then we can delete them in both $a$ and $b$ and continue the construction. Suppose we currently want to bring elements $b_i$ and $b_{n - i + 1}$ $(i \\le n/2)$ to their respective positions in $a$. If $b_i$ is at position $j$ in $a$, then $b_{n - i + 1}$ must be at the position $n - j + 1$. There are three cases: If $j = n$, then we can swap the prefix and suffix of length $i$ in $a$ to achieve this. Otherwise if $j = 1$, then we can first swap prefix and suffix of length $1$ and then swap prefix and suffix of length $i$. Else we can swap prefix and suffix of length $j$ in $a$ and proceed to steps $1$ and $2$. In atmost $3$ steps, we can bring each pair in $a$ to its required position in $b$. So we need atmost $\\lfloor{\\frac{3 n}{2}}\\rfloor$ operations overall. Time complexity: $O(n \\cdot \\log{n})$",
    "code": "\n#include\nusing namespace std;\n\nint main(){\n\tios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\tint tc;\n\tcin >> tc;\n\twhile(tc--){\n\t\tint n;\n\t\tcin >> n;\n\t\tmap< pair < int, int >, int > pairs;\n\t\tvector< int > a(n), b(n);\n\t\tbool possible = 1;\n\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tcin >> a[i];\n\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tcin >> b[i];\n\n\t\tif(n % 2 == 1 && a[n / 2] != b[n / 2])\n\t\t\tpossible = 0;\n\n\t\tfor(int i = 0; i < n / 2; i++){\n\t\t\tpair< int, int > p = {min(a[i], a[n — 1 — i]), max(a[i], a[n — 1 — i])};\n\t\t\tpairs[p]++;\n\t\t}\n\n\t\tfor(int i = 0; i < n / 2; i++){\n\t\t\tpair< int, int > p = {min(b[i], b[n — 1 — i]), max(b[i], b[n — 1 — i])};\n\t\t\tif(pairs[p] <= 0)\n\t\t\t\tpossible = 0;\n\t\t\tpairs[p]--;\n\t\t}\n\n\t\tif(possible)\n\t\t\tcout << \"Yes\" << endl;\n\n\t\telse cout << \"No\" << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1365",
    "index": "G",
    "title": "Secure Password",
    "statement": "\\textbf{This is an interactive problem.}\n\nAyush devised yet another scheme to set the password of his lock. The lock has $n$ slots where each slot can hold any non-negative integer. The password $P$ is a sequence of $n$ integers, $i$-th element of which goes into the $i$-th slot of the lock.\n\nTo set the password, Ayush comes up with an array $A$ of $n$ integers each in the range $[0, 2^{63}-1]$. He then sets the $i$-th element of $P$ as the bitwise OR of all integers in the array except $A_i$.\n\nYou need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the \\textbf{bitwise OR} all elements of the array with index in this subset. \\textbf{You can ask no more than 13 queries}.",
    "tutorial": "Key Idea: Unlike the last version of the problem, this is not doable using a binary search. Solution using more queries: It is possible to solve the problem using $2\\cdot \\log{n}$ queries in the following way: For each $i$, we ask the bitwise OR of all numbers at indices which have the $i$-th bit set in their binary representation. We also ask the bitwise OR of all numbers at indices which do not have the $i$-th bit set in their binary representation. Suppose we want to calculate the bitwise OR of all numbers except the $i$-th number. Let the bitwise OR be equal to $a$ (initialize $a= 0$). We iterate on all indices $j$ from $1$ to $n$ (except $i$). If $j$ is a submask of $i$, that is $j \\wedge i = j$ (where $\\wedge$ is the bitwise AND operator), then there must be some bit $k$ that is set in $i$ but not in $j$ (since $i \\ne j$). In this case we replace $a$ by $a \\vee x$ where $\\vee$ is the bitwise OR operator and $x$ is the bitwise OR of numbers at indices that do no have the $k$-th bit set. Similarly, if $j$ is not a submask of $i$ then there must be some bit $k$ which is set in $j$ but not in $i$. In that case we use the bitwise OR of numbers at indices that have the $k$-th bit set. In doing so, we included the contribution of each element except $i$ at least once. Note that this works because taking the bitwise OR with the same number more than once does not affect the answer. For example, if $n=4$ and indices are number $0$ to $3$, then we need to ask $4$ queries: $\\{{0, 2\\}}$ (bit $0$ not set), $\\{{1, 3\\}}$ (bit $0$ set), $\\{{0, 1\\}}$ (bit $1$ not set), $\\{{2, 3\\}}$ (bit $1$ set). Solution: Note that in the suboptimal solution, we assigned a bitmask to each index (in that case bitmask for index $i$ was equal to $i$). What if we assign these masks in a different way? Suppose we are able to assign the masks in such a way that no two masks assigned to two indices are submasks of each other. In this case, we do not need to ask bitwise OR of indices which do not have the $i$-th bit set since for each pair of indices, there is a bit which is set in one but not in the other. For example, if $n = 4$, we can assign masks 1100, 1010, 1001 and 0110 (in binary representation). Now for each bit $i$, we will only query the indices which have the $i$-th bit set. In this case, for bit $0$ we ask $\\{{3\\}}$, for bit $1$ we ask $\\{{2, 4\\}}$, for bit $2$ we ask $\\{{1, 4\\}}$ and for bit $3$ we ask $\\{{1, 2, 3\\}}$. Let $x_0, x_1, x_2, x_3$ be bitwise OR of these four subsets respectively. Then the elements of the password are $x_0 \\vee x_1$, $x_0 \\vee x_2$, $x_1 \\vee x_2$ and $x_0 \\vee x_3$ respectively. What is the minimum number of bits we need to assign masks in such a way? We are given the bound of $13$ queries. There are $1716$ numbers upto $2^{13}$ which have $6$ bits set in their binary representation. Clearly no two of these numbers would be submaks of each other. So we can use them to assign the masks! It can be shown using Sperner's theorem that we need at least $13$ queries to assign submaks in the above manner. Time complexity: $O(2^q + n \\cdot q)$ where $q$ is the number of queries asked.",
    "code": "\n#include\nusing namespace std;\n\n#define ll long long\n#define vint vector< int >\n\nconst int Q = 13;\n\nll query(vint v){\n\tcout << \"? \" << v.size() << ' ';\n\tfor(ll i : v)\n\t\tcout << i + 1 << ' ';\n\tcout << endl;\n\tfflush(stdout);\n\tll or_value;\n\tcin >> or_value;\n\treturn or_value;\n}\n\nint main(){\n\tint n;\n\tcin >> n;\n\n\tvector< vint > ask(Q);\n\tvint assign_mask(n);\n\n\tvector< ll > or_value(Q), answer(n);\n\n\tint assigned = 0;\n\n\tfor(int i = 1; i < (1 << Q); i++){\n\t\tif(__builtin_popcount(i) != Q / 2)\n\t\t\tcontinue;\n\t\tassign_mask[assigned] = i;\n\t\tfor(int j = 0; j < Q; j++)\n\t\t\tif((i >> j & 1) == 0)\n\t\t\t\task[j].push_back(assigned);\n\t\tassigned++;\n\t\tif(assigned == n)\n\t\t\tbreak;\n\t}\n\n\tfor(int i = 0; i < Q; i++)\n\t\tif(!ask[i].empty())\n\t\t\tor_value[i] = query(ask[i]);\n\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < Q; j++)\n\t\t\tif(assign_mask[i] >> j & 1)\n\t\t\t\tanswer[i] |= or_value[j];\n\n\tcout << \"! \";\n\n\tfor(ll i : answer)\n\t\tcout << i << ' ';\n\n\tcout << endl;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1366",
    "index": "A",
    "title": "Shovels and Swords",
    "statement": "Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.\n\nEach tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $a$ sticks and $b$ diamonds?",
    "tutorial": "There are three constraints on the number of emeralds: the number of emeralds can't be greater than $a$; the number of emeralds can't be greater than $b$; the number of emeralds can't be greater than $\\frac{a+b}{3}$. So the answer is $\\min(a, b, \\frac{a+b}{3})$.",
    "code": "for _ in range(int(input())):\n    l, r = map(int, input().split())\n    print(min(l, r, (l + r) // 3))",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1366",
    "index": "B",
    "title": "Shuffle",
    "statement": "You are given an array consisting of $n$ integers $a_1$, $a_2$, ..., $a_n$. Initially $a_x = 1$, all other elements are equal to $0$.\n\nYou have to perform $m$ operations. During the $i$-th operation, you choose two indices $c$ and $d$ such that $l_i \\le c, d \\le r_i$, and swap $a_c$ and $a_d$.\n\nCalculate the number of indices $k$ such that it is possible to choose the operations so that $a_k = 1$ in the end.",
    "tutorial": "Let's consider how the set of possible indices where the $1$ can be changes. Initially, only one index is correct - $x$. After performing an operation $l, r$ such that $x < l$ or $x > r$ this set does not change. But after performing an operation $l, r$ such that $l \\le x \\le r$ we should insert the elements $\\{l, l+1, l+2, \\dots, r-1, r\\}$ into this set, if they are not present. Now consider how the set $\\{L, L+1, L+2, \\dots, R-1, R\\}$ changes. If segments $[l, r]$ and $[L, R]$ do not share any indices, there are no changes - but if they do, the set turns into $\\{ \\min(l, L), \\min(l, L)+1, \\min(l, L)+2, \\dots, \\max(r, R)-1, \\max(r, R) \\}$. So the set of reachable indices is always a segment of numbers, and to process an operation, we should check whether the segment from operation intersects with the segment of indices we have - and if it is true, unite them.",
    "code": "for _ in range(int(input())):\n    n, x, m = map(int, input().split())\n    l, r = x, x\n    for _ in range(m):\n        L, R = map(int, input().split())\n        if max(l, L) <= min(r, R):\n            l = min(l, L)\n            r = max(r, R)\n            \n    print(r - l + 1)",
    "tags": [
      "math",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1366",
    "index": "C",
    "title": "Palindromic Paths",
    "statement": "You are given a matrix with $n$ rows (numbered from $1$ to $n$) and $m$ columns (numbered from $1$ to $m$). A number $a_{i, j}$ is written in the cell belonging to the $i$-th row and the $j$-th column, each number is either $0$ or $1$.\n\nA chip is initially in the cell $(1, 1)$, and it will be moved to the cell $(n, m)$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $(x, y)$, then after the move it can be either $(x + 1, y)$ or $(x, y + 1)$). The chip cannot leave the matrix.\n\nConsider each path of the chip from $(1, 1)$ to $(n, m)$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.\n\nYour goal is to change the values in the minimum number of cells so that \\textbf{every} path is palindromic.",
    "tutorial": "Let's group the cells by their distance from the starting point: the group $0$ consists of a single cell $(1, 1)$; the group $1$ consists of the cells $(1, 2)$ and $(2, 1)$, and so on. In total, there are $n + m - 1$ groups. Let's analyze the groups $k$ and $n + m - 2 - k$. There are two cases: if $k = 0$ or $n + m - 2 - k = 0$, then we are looking at the starting cell and the ending cell, and their contents should be equal; otherwise, suppose two cells $(x, y)$ and $(x + 1, y - 1)$ belong to the same group. We can easily prove that the contents of these two cells should be equal (for example, by analyzing two paths that go through cell $(x + 1, y)$ and coincide after this cell, but one goes to $(x + 1, y)$ from $(x, y)$, and another - from $(x + 1, y - 1)$) - and, using induction, we can prove that the contents of all cells in a group should be equal. And since the paths should be palindromic, the contents of the group $k$ should be equal to the contents of the group $n + m - 2 - k$. So, in each pair of groups, we should calculate the number of $1$'s and $0$'s, and choose which of them to change. Note that if $n + m$ is even, the central group has no pair, so it should not be modified.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve()\n{\n\tint n, m;\n\tcin >> n >> m;\n\tvector<vector<int> > a(n, vector<int>(m));\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < m; j++)\n\t\t\tcin >> a[i][j];\n\tvector<vector<int> > cnt(n + m - 1, vector<int>(2));\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < m; j++)\n\t\t\tcnt[i + j][a[i][j]]++;\n\tint ans = 0;\n\tfor(int i = 0; i <= n + m - 2; i++)\n\t{\n\t\tint j = n + m - 2 - i;\n\t\tif(i <= j) continue;\n\t\tans += min(cnt[i][0] + cnt[j][0], cnt[i][1] + cnt[j][1]);\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t\tsolve();\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1366",
    "index": "D",
    "title": "Two Divisors",
    "statement": "You are given $n$ integers $a_1, a_2, \\dots, a_n$.\n\nFor each $a_i$ find its \\textbf{two divisors} $d_1 > 1$ and $d_2 > 1$ such that $\\gcd(d_1 + d_2, a_i) = 1$ (where $\\gcd(a, b)$ is the greatest common divisor of $a$ and $b$) or say that there is no such pair.",
    "tutorial": "Firstly, for the fast factorization of given $a_i$, let's use Sieve of Eratosthenes: let's for each value $val \\le 10^7$ calculate its minimum prime divisor $minDiv[val]$ in the same manner as the sieve do. Now we can factorize each $a_i$ in $O(\\log{a_i})$ time by separating its prime divisors one by one using precalculated array $minDiv$. Suppose, we have a factorization $a_i = p_1^{s_1} p_2^{s_2} \\cdot \\ldots \\cdot p_k^{s_k}$. If $k = 1$ then any divisor of $a_i$ is divisible by $p_1$ so do the sum of divisors. Obviously, the answer is $-1$ $-1$. Otherwise, we can divide all prime divisors $p_i$ into two non-empty groups $\\{p_1, p_2, \\dots, p_x\\}$ and $\\{p_{x + 1}, \\dots, p_k\\}$ and take $d_1 = p_1 \\cdot p_2 \\cdot \\ldots \\cdot p_x$ and $d_2 = p_{x + 1} \\cdot \\ldots \\cdot p_k$. Any division is valid (proof is below), so, for example, we can take $d_1 = p_1$ and $d_2 = p_2 \\cdot \\ldots \\cdot p_k$. Let's prove that if $d_1 = p_1 \\cdot p_2 \\cdot \\ldots \\cdot p_x$ and $d_2 = p_{x + 1} \\cdot \\ldots \\cdot p_k$ then $\\gcd(d_1 + d_2, a_i) = 1$. Let's look at any $p_i$. We can assume that $a_i \\equiv 0 \\mod p_i$ and (without loss of generality) $d_1 \\equiv 0 \\mod p_i$. But it means that $d_2 \\not\\equiv 0 \\mod p_i$, then $d_1 + d_2 \\equiv 0 + d_2 \\equiv d_2 \\not\\equiv 0 \\mod p_i$. In other words, there are no prime divisor of $a_i$ which divides $d_1 + d_2$, so the $\\gcd(d_1 + d_2, a_i) = 1$. Time complexity is $O(A \\log{\\log{A}} + n \\log{A})$ for the sieve and finding answers ($A \\le 10^7$).",
    "code": "fun main() {\n    val n = readLine()!!.toInt()\n    val a = readLine()!!.split(' ').map { it.toInt() }\n\n    val minDiv = IntArray(1e7.toInt() + 2) { it }\n    for (i in 2 until minDiv.size) {\n        if (minDiv[i] != i)\n            continue\n        for (j in i until minDiv.size step i)\n            minDiv[j] = minOf(minDiv[j], i)\n    }\n\n    fun getPrimeDivisors(v: Int): ArrayList<Int> {\n        val ans = ArrayList<Int>()\n        var curVal = v\n        while (curVal != 1) {\n            if (ans.isEmpty() || ans.last() != minDiv[curVal])\n                ans.add(minDiv[curVal])\n            curVal /= minDiv[curVal]\n        }\n        return ans\n    }\n\n    val d1 = IntArray(n)\n    val d2 = IntArray(n)\n    for (id in a.indices) {\n        val list = getPrimeDivisors(a[id])\n        if (list.size < 2) {\n            d1[id] = -1\n            d2[id] = -1\n        } else {\n            d1[id] = list[0]\n            list.removeAt(0)\n            d2[id] = list.reduce { s, t -> s * t }\n        }\n    }\n    println(d1.joinToString(\" \"))\n    println(d2.joinToString(\" \"))\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1366",
    "index": "E",
    "title": "Two Arrays",
    "statement": "You are given two arrays $a_1, a_2, \\dots , a_n$ and $b_1, b_2, \\dots , b_m$. Array $b$ is sorted in ascending order ($b_i < b_{i + 1}$ for each $i$ from $1$ to $m - 1$).\n\nYou have to divide the array $a$ into $m$ consecutive subarrays so that, for each $i$ from $1$ to $m$, the minimum on the $i$-th subarray is equal to $b_i$. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of $a$ compose the first subarray, the next several elements of $a$ compose the second subarray, and so on.\n\nFor example, if $a = [12, 10, 20, 20, 25, 30]$ and $b = [10, 20, 30]$ then there are two good partitions of array $a$:\n\n- $[12, 10, 20], [20, 25], [30]$;\n- $[12, 10], [20, 20, 25], [30]$.\n\nYou have to calculate the number of ways to divide the array $a$. Since the number can be pretty large print it modulo 998244353.",
    "tutorial": "At first, let's reverse arrays $a$ and $b$. Now array $b$ is sorted in descending order. Now let's find minimum index $x$ such that $a_x = b_1$. If there is no such index or if $\\min\\limits_{1 \\le i \\le x}a_i < b_1$ then the answer is $0$ (because minimum on any prefix of array $a$ will never be equal to $b_1$). Otherwise, let's find the minimum index $y > x$ such that $a_y = b_2$. If there is no such index or if $\\min\\limits_{x \\le i \\le y}a_i < b_2$ then the answer is $0$. Also let's find the minimum index $mid > x$ such that $a_{mid} < b_1$ (it can't be greater than $y$). The first subarray starts in position $1$ and ends in any position $x, x + 1, x + 2, \\dots, mid - 1$ (because if it ends in position $mid$ or further, then the minimum in the first subarray is greater than $b_1$). So there are $mid - x$ ways to split subarrays $1$ and $2$. A similar approach can be used to calculate the number of ways to split the second and third subarrays and, so on. After all, you have to check that minimum in the last subarray is equal to $b_m$ (otherwise the answer is $0$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200005;\nconst int MOD = 998244353;\n\nint mul(int a, int b) {\n    return (a * 1LL * b) % MOD;\n}\n\nint n, m;\nint a[N], b[N];\n\nint main() {\t\n    scanf(\"%d %d\", &n, &m);\n    for (int i = 0; i < n; ++i) scanf(\"%d\", a + i);\n    for (int i = 0; i < m; ++i) scanf(\"%d\", b + i);\n    \n    reverse(a, a + n);\n    reverse(b, b + m);\n    a[n] = -1;\n    \n    int mn = a[0];\n    int pos = 0;\n    while (pos < n && mn > b[0]) {\n        ++pos;\n        mn = min(mn, a[pos]);\n    }\n    \n    if (pos == n || mn < b[0]) {\n       puts(\"0\");\n       return 0;\n    }\n    \n    assert(mn == b[0]);\n    int res = 1;\n    int ib = 0;\n    while (true) {\n        assert(mn == b[ib]);\n        if (ib == m - 1){\n            if(*min_element(a + pos, a + n) != b[ib]) {\n               puts(\"0\");\n               return 0;\n            }\n            break;\n        }\n        \n        bool f = true;\n        int npos = pos;\n        while (npos < n && mn != b[ib + 1]) {\n            ++npos;\n            mn = min(mn, a[npos]);\n            \n            if (f && mn < b[ib]){\n                f = false;\n                res = mul(res, npos - pos);\n            }\n        }\n        \n        if (npos == n || mn != b[ib + 1]) {\n            puts(\"0\");\n            return 0;\n        }\n        \n        ++ib;\n        pos = npos;\n    }\n    \n    printf(\"%d\\n\", res);\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "dp",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1366",
    "index": "F",
    "title": "Jog Around The Graph",
    "statement": "You are given a simple weighted connected undirected graph, consisting of $n$ vertices and $m$ edges.\n\nA path in the graph of length $k$ is a sequence of $k+1$ vertices $v_1, v_2, \\dots, v_{k+1}$ such that for each $i$ $(1 \\le i \\le k)$ the edge $(v_i, v_{i+1})$ is present in the graph. A path from some vertex $v$ also has vertex $v_1=v$. Note that edges and vertices are allowed to be included in the path multiple times.\n\nThe weight of the path is the total weight of edges in it.\n\nFor each $i$ from $1$ to $q$ consider a path from vertex $1$ of length $i$ of the maximum weight. What is the sum of weights of these $q$ paths?\n\nAnswer can be quite large, so print it modulo $10^9+7$.",
    "tutorial": "Let's observe what does the maximum weight of some fixed length path look like. Among the edges on that path the last one has the maximum weight. If it wasn't then the better total weight could be achieved by choosing a bigger weight edge earlier and going back and forth on it for the same number of steps. It actually helps us arrive to a conclusion that all optimal paths look like that: some simple path to an edge and then back and forth movement on it. Any simple path in the graph has its length at most $m$. Let's separate the queries into two parts. $k < m$ will be handled in a straightforward manner. Let $dp[v][k]$ be the maximum weight of a path that ends in $v$ and has exactly $k$ edges in it. That's pretty easy to calculate in $(n+m) \\cdot m$. You can also think of this $dp$ as some kind of Ford-Bellman algorithm - let $d_v$ on the $k$-th step be the maximum weight of the path to $v$ of length $k$. Iterate over all edges and try to update $d_v$ and $d_u$ for each edge $(v, u)$ (that's what I do in my solution if you refer to it). Now for $k \\ge m$. There was a very common assumption that after a bit more steps some edge will become the most optimal and will stay the most optimal until the end of time. However, that \"a bit\" cut-off is in fact too high to rely on (it must be somewhere around $n \\cdot max_w$). So the best path of length exactly $m$ ending in each vertex $v$ is $dp[v][m]$. Let the maximum weight adjacent edge to vertex $v$ be $mx_v$. So the path of length $k$ will have weight $mx_v \\cdot (k - m) + dp[v][m]$. Treat it like a line $kx + b$ with coefficients $mx_v$ and $dp[v][m]$. How do determine which line is the best for some $k$? Sure, experienced participants will immediately answer \"convex hull\". Build a lower envelope of the convex hull of these lines. If $q$ was a little smaller than we could query with binary search for each $k$, the same how convex hull is usually used. We have to examine the hull further. Each line in it becomes the best in some point, then stays the best for some interval and then never appears the best again. What are these line changing points? Well, it's just the intersection point of the adjacent lines in the hull. So having these points and the parameters of the line we can calculate its contribution to the answer with a sum of arithmetic progression formula. There were just $n$ lines in the hull so you can build the hull in any complexity, I think I saw up to $O(n^2 \\log n)$ performances in the participants codes. There is a cool solution that involves some kind of Divide&Conquer on these lines. I personally thought of it in a sense of traversing a Li-Chao tree without actually building it. If anyone wants to explain this solution, feel free to do it in comments. Overall complexity: $O((n+m) \\cdot m + n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst long long INF = 1e18;\nconst int MOD = 1000'000'007;\nconst int inv2 = (MOD + 1) / 2;\n\nstruct edge{\n\tint v, u, w;\n};\n\nstruct frac{\n\tlong long x, y;\n\tfrac(long long a, long long b){\n\t\tif (b < 0) a = -a, b = -b;\n\t\tx = a, y = b;\n\t}\n};\n\nbool operator <=(const frac &a, const frac &b){\n\treturn a.x * b.y <= a.y * b.x;\n}\n\nstruct line{\n\tlong long m, c;\n\tfrac intersectX(const line &l) { return frac(c - l.c, l.m - m); }\n};\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\nint calc(int a1, int d, int n){\n\tassert(n >= 0);\n\treturn mul(mul(n, inv2), add(mul(2, a1), mul(add(n, -1), d)));\n}\n\nint main() {\n\tint n, m;\n\tlong long q;\n\tscanf(\"%d%d%lld\", &n, &m, &q);\n\tvector<edge> e(m);\n\tvector<int> hv(n);\n\tforn(i, m){\n\t\tscanf(\"%d%d%d\", &e[i].v, &e[i].u, &e[i].w);\n\t\t--e[i].v, --e[i].u;\n\t\thv[e[i].v] = max(hv[e[i].v], e[i].w);\n\t\thv[e[i].u] = max(hv[e[i].u], e[i].w);\n\t}\n\t\n\tint ans = 0;\n\tvector<long long> d(n, -INF), nd(n);\n\td[0] = 0;\n\tforn(val, m){\n\t\tlong long mx = 0;\n\t\tforn(i, n)\n\t\t\tmx = max(mx, d[i]);\n\t\tif (val)\n\t\t\tans = add(ans, mx % MOD);\n\t\tnd = d;\n\t\tforn(i, m){\n\t\t\tnd[e[i].v] = max(nd[e[i].v], d[e[i].u] + e[i].w);\n\t\t\tnd[e[i].u] = max(nd[e[i].u], d[e[i].v] + e[i].w);\n\t\t}\n\t\td = nd;\n\t}\n\t\n\tvector<line> fin;\n\tforn(i, n) fin.push_back({hv[i], d[i]});\n\tsort(fin.begin(), fin.end(), [](const line &a, const line &b){\n\t\tif (a.m != b.m)\n\t\t\treturn a.m < b.m;\n\t\treturn a.c > b.c;\n\t});\n\tfin.resize(unique(fin.begin(), fin.end(), [](const line &a, const line &b){\n\t\treturn a.m == b.m;\n\t}) - fin.begin());\n\t\n\tvector<line> ch;\n\tfor (auto cur : fin){\n\t\twhile (ch.size() >= 2 && cur.intersectX(ch.back()) <= ch.back().intersectX(ch[int(ch.size()) - 2]))\n\t\t\tch.pop_back();\n\t\tch.push_back(cur);\n\t}\n\t\n\tlong long prv = 0;\n\tq -= m;\n\tforn(i, int(ch.size()) - 1){\n\t\tfrac f = ch[i].intersectX(ch[i + 1]);\n\t\tif (f.x < 0) continue;\n\t\tlong long lst = min(q, f.x / f.y);\n\t\tif (lst < prv) continue;\n\t\tans = add(ans, calc((ch[i].c + ch[i].m * prv) % MOD, ch[i].m % MOD, lst - prv + 1));\n\t\tprv = lst + 1;\n\t}\n\tans = add(ans, calc((ch.back().c + ch.back().m * prv) % MOD, ch.back().m % MOD, q - prv + 1));\n\t\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "geometry",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1366",
    "index": "G",
    "title": "Construct the String",
    "statement": "Let's denote the function $f(s)$ that takes a string $s$ consisting of lowercase Latin letters and dots, and returns a string consisting of lowercase Latin letters as follows:\n\n- let $r$ be an empty string;\n- process the characters of $s$ from left to right. For each character $c$, do the following: if $c$ is a lowercase Latin letter, append $c$ at the end of the string $r$; otherwise, delete the last character from $r$ (if $r$ is empty before deleting the last character — the function crashes);\n- return $r$ as the result of the function.\n\nYou are given two strings $s$ and $t$. You have to delete the minimum possible number of characters from $s$ so that $f(s) = t$ (and the function does not crash). Note that you aren't allowed to insert new characters into $s$ or reorder the existing ones.",
    "tutorial": "The core idea of the solution is the following dynamic programming: $dp_{i, j}$ is the minimum number of characters we have to delete if we considered a subsequence of $i$ first characters of $s$, and it maps to $j$ first characters of $t$. There are three obvious transitions in this dynamic programming: we can go from $dp_{i, j}$ to $dp_{i + 1, j}$ by skipping $s_i$; if $s_i = t_j$, we can go from $dp_{i, j}$ to $dp_{i + 1, j + 1}$; if $s_i$ is a dot, we can go from $dp_{i, j}$ to $dp_{i + 1, j - 1}$. Unfortunately, these transitions cannot fully handle the case when we want to put some character and then delete it (these transitions don't allow us to do it for any character, only for some specific ones in specific situations). To handle it, suppose we want to take the character $s_i$ and then delete it, and we model it as follows: there exists the fourth transition from $dp_{i,j}$ to $dp_{i+len_i, j}$ without deleting anything, where $len_i$ is the length of the shortest substring of $s$ starting from $i$ that becomes empty if we apply the function $f$ to it. This substring can be described as a regular bracket sequence, where opening brackets correspond to letters, and closing brackets - to dots. We can precalculate this substring for each $i$ in $O(n)$. Why is this transition enough? Suppose we don't want to take some letter from this shortest substring in the optimal answer; since it is the shortest substring meeting these constraints, the number of letters on each prefix of it (excluding the substring itself) is greater than the number of dots, so we can instead skip the first letter and try applying this transition from $dp_{i + 1, j}$, so this case is handled. And skipping any dots from this shortest substring is also suboptimal since we have to get rid of the character $s_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)\n\nconst int INF = 1e9;\nconst int N = 10010;\n\nint n, m;\nstring s, t;\nint dp[N][N];\nint nxt[N];\n\nint main() {\n\tcin >> s >> t;\n\tn = sz(s), m = sz(t);\n\t\n\tforn(i, n) if (s[i] != '.') {\n\t\tint bal = 0;\n\t\tnxt[i] = -1;\n\t\tfore(j, i, n) {\n\t\t\tif (s[j] == '.') --bal;\n\t\t\telse ++bal;\n\t\t\tif (bal == 0) {\n\t\t\t\tnxt[i] = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tforn(i, n + 1) forn(j, m + 1)\n\t\tdp[i][j] = INF;\n\tdp[0][0] = 0;\n\t\n\tforn(i, n) forn(j, m + 1) {\n\t\tdp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + 1);\n\t\tif (j < m && s[i] == t[j])\n\t\t\tdp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j]);\n\t\tif (s[i] != '.' && nxt[i] != -1)\n\t\t\tdp[nxt[i] + 1][j] = min(dp[nxt[i] + 1][j], dp[i][j]);\n\t}\n\t\n\tcout << dp[n][m] << endl;\n}",
    "tags": [
      "data structures",
      "dp",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1367",
    "index": "A",
    "title": "Short Substrings",
    "statement": "Alice guesses the strings that Bob made for her.\n\nAt first, Bob came up with the secret string $a$ consisting of lowercase English letters. The string $a$ has a length of $2$ or more characters. Then, from string $a$ he builds a new string $b$ and offers Alice the string $b$ so that she can guess the string $a$.\n\nBob builds $b$ from $a$ as follows: he writes all the substrings of length $2$ of the string $a$ in the order from left to right, and then joins them in the same order into the string $b$.\n\nFor example, if Bob came up with the string $a$=\"abac\", then all the substrings of length $2$ of the string $a$ are: \"ab\", \"ba\", \"ac\". Therefore, the string $b$=\"abbaac\".\n\nYou are given the string $b$. Help Alice to guess the string $a$ that Bob came up with. It is guaranteed that $b$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.",
    "tutorial": "Note that the first two characters of $a$ match the first two characters of $b$. The third character of the string $b$ again matches the second character of $a$ (since it is the first character in the second substring, which contains the second and the third character of $a$). The fourth character $b$ matches with the third character of $a$. It is easy to notice that such a pattern continues further. That is, the string $a$ consists of the first character $b$ and all characters at even positions in $b$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\n\tfor (int test = 1; test <= t; test++) {\n\t\tstring b;\n\t\tcin >> b;\n\n\t\tstring a = b.substr(0, 2);\n\n\t\tfor (int i = 3; i < b.size(); i += 2) {\n\t\t\ta += b[i];\n\t\t}\n\n\t\tcout << a << endl;\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1367",
    "index": "B",
    "title": "Even Array",
    "statement": "You are given an array $a[0 \\ldots n-1]$ of length $n$ which consists of non-negative integers. \\textbf{Note that array indices start from zero.}\n\nAn array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $i$ ($0 \\le i \\le n - 1$) the equality $i \\bmod 2 = a[i] \\bmod 2$ holds, where $x \\bmod 2$ is the remainder of dividing $x$ by 2.\n\nFor example, the arrays [$0, 5, 2, 1$] and [$0, 17, 0, 3$] are good, and the array [$2, 4, 6, 7$] is bad, because for $i=1$, the parities of $i$ and $a[i]$ are different: $i \\bmod 2 = 1 \\bmod 2 = 1$, but $a[i] \\bmod 2 = 4 \\bmod 2 = 0$.\n\nIn one move, you can take \\textbf{any} two elements of the array and swap them (these elements are not necessarily adjacent).\n\nFind the minimum number of moves in which you can make the array $a$ good, or say that this is not possible.",
    "tutorial": "We split all the positions in which the parity of the index does not match with the parity of the element into two arrays. If there is an odd number in the even index, add this index to the $e$ array. Otherwise, if there is an even number in the odd index, add this index to the $o$ array. Note that if the sizes of the $o$ and $e$ arrays are not equal, then there is no answer. Otherwise, the array $a$ can be made good by doing exactly $|o|$ operations by simply swapping all the elements in the $o$ and $e$ arrays.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ld = long double;\nusing ll = long long;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    int a = 0, b = 0;\n    for (int i = 0; i < n; i++) {\n        int x;\n        cin >> x;\n        if (x % 2 != i % 2) {\n            if (i % 2 == 0) {\n                a++;\n            } else {\n                b++;\n            }\n        }\n    }\n    if (a != b) {\n        cout << -1 << endl;\n    } else {\n        cout << a << endl;\n    }\n}\n\nint main() {\n    int n;\n    cin >> n;\n    while (n--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1367",
    "index": "C",
    "title": "Social Distance",
    "statement": "Polycarp and his friends want to visit a new restaurant. The restaurant has $n$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $1$ to $n$ in the order from left to right. The state of the restaurant is described by a string of length $n$ which contains characters \"1\" (the table is occupied) and \"0\" (the table is empty).\n\nRestaurant rules prohibit people to sit at a distance of $k$ or less from each other. That is, if a person sits at the table number $i$, then all tables with numbers from $i-k$ to $i+k$ (except for the $i$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $k$.\n\nFor example, if $n=8$ and $k=2$, then:\n\n- strings \"10010001\", \"10000010\", \"00000000\", \"00100000\" satisfy the rules of the restaurant;\n- strings \"10100100\", \"10011001\", \"11111111\" do not satisfy to the rules of the restaurant, since each of them has a pair of \"1\" with a distance less than or equal to $k=2$.\n\nIn particular, if the state of the restaurant is described by a string without \"1\" or a string with one \"1\", then the requirement of the restaurant is satisfied.\n\nYou are given a binary string $s$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $s$.\n\nFind the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of \"0\" that can be replaced by \"1\" such that the requirement will still be satisfied?\n\nFor example, if $n=6$, $k=1$, $s=$ \"100010\", then the answer to the problem will be $1$, since only the table at position $3$ can be occupied such that the rules are still satisfied.",
    "tutorial": "Let's split a given string into blocks of consecutive zeros. Then in each such block, you can independently put the maximum number of people who fit in it. But there are three cases to consider. If the current block is not the first and not the last, then there are ones at the border and this means that the first $k$ tables of the current block and the last $k$ are prohibited. Therefore, remove these zeroes from the string. If the current block is the first, then the one is at the end and you need to delete the last $k$ zeros. If the current block is the last, then in the beginning there is one and you need to delete the first $k$ zeros. Now all the tables in each block are free, then in each block we can put $\\lfloor \\frac{\\text{number of zeros}}{k} \\rfloor$. Sum these values over all blocks.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\n\tfor (int test = 1; test <= t; test++) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tstring s;\n\t\tcin >> s;\n\n\t\tint res = 0;\n\n\t\tfor (int i = 0; i < n;) {\n\t\t\tint j = i + 1;\n\n\t\t\tfor (; j < n && s[j] != '1'; j++);\n\n\t\t\tint left = s[i] == '1' ? k : 0;\n\t\t\tint right = j < n && s[j] == '1' ? k : 0;\n\t\t\tint len = j - i;\n\n\t\t\tif (left == k) {\n\t\t\t\tlen--;\n\t\t\t}\n\n\t\t\tlen -= left + right;\n\n\t\t\tif (len > 0) {\n\t\t\t\tres += (len + k) / (k + 1);\n\t\t\t}\n\n\t\t\ti = j;\n\t\t}\n\n\t\tcout << res << endl;\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1367",
    "index": "D",
    "title": "Task On The Board",
    "statement": "Polycarp wrote on the board a string $s$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.\n\nAfter that, he erased some letters from the string $s$, and he rewrote the remaining letters in \\textbf{any} order. As a result, he got some new string $t$. You have to find it with some additional information.\n\nSuppose that the string $t$ has length $m$ and the characters are numbered from left to right from $1$ to $m$. You are given a sequence of $m$ integers: $b_1, b_2, \\ldots, b_m$, where $b_i$ is the sum of the distances $|i-j|$ from the index $i$ to all such indices $j$ that $t_j > t_i$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $b_i$, Polycarp finds all such indices $j$ that the index $j$ contains a letter that is later in the alphabet than $t_i$ and sums all the values $|i-j|$.\n\nFor example, if $t$ = \"abzb\", then:\n\n- since $t_1$='a', all other indices contain letters which are later in the alphabet, that is: $b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$;\n- since $t_2$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_2=|2-3|=1$;\n- since $t_3$='z', then there are no indexes $j$ such that $t_j>t_i$, thus $b_3=0$;\n- since $t_4$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_4=|4-3|=1$.\n\nThus, if $t$ = \"abzb\", then $b=[6,1,0,1]$.\n\nGiven the string $s$ and the array $b$, find any possible string $t$ for which the following two requirements are fulfilled simultaneously:\n\n- $t$ is obtained from $s$ by erasing some letters (possibly zero) and then writing the rest in \\textbf{any} order;\n- the array, constructed from the string $t$ according to the rules above, equals to the array $b$ specified in the input data.",
    "tutorial": "We will construct the string $t$, starting with the largest letters. Note that if $b_i = 0$, then the $i$-th letter of the string $t$ is maximal, so we know that the $i$-th letter affect all $b_j \\ne 0$. While the string $t$ is not completely constructed, we will do the following: Find all $i$ such that $b_i = 0$ and the $i$-th character of string $t$ is not placed; Put on all these positions $i$ in the string $t$ the maximum letter not used in the string $t$ (there should be a sufficient number of letters in the string $s$); Subtract $|i - j|$ from all $b_j \\ne 0$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int q;\n    cin >> q;\n    forn(qq, q) {\n        string s;\n        cin >> s;\n        int n;\n        cin >> n;\n        vector<int> b(n);\n        forn(i, n)\n            cin >> b[i];\n        vector<vector<int>> groups;\n        while (true) {\n            vector<int> pos;\n            forn(i, n)\n                if (b[i] == 0)\n                    pos.push_back(i);\n            if (pos.empty())\n                break;\n            groups.push_back(pos);\n            forn(i, n)\n                if (b[i] == 0)\n                    b[i] = INT_MAX;\n                else\n                    for (int pp: pos)\n                        b[i] -= abs(i - pp);\n        }\n        map<char, int> cnts;\n        forn(i, s.size())\n            cnts[s[i]]++;\n        auto j = cnts.rbegin();\n        string t(n, '?');\n        for (auto g: groups) {\n            while (j->second < g.size())\n                j++;\n            for (int pp: g)\n                t[pp] = j->first;\n            j++;\n        }\n        cout << t << endl;\n    }\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1367",
    "index": "E",
    "title": "Necklace Assembly",
    "statement": "The store sells $n$ beads. The color of each bead is described by a lowercase letter of the English alphabet (\"a\"–\"z\"). You want to buy some beads to assemble a necklace from them.\n\nA necklace is a set of beads connected in a circle.\n\nFor example, if the store sells beads \"a\", \"b\", \"c\", \"a\", \"c\", \"c\", then you can assemble the following necklaces (these are not all possible options):\n\nAnd the following necklaces cannot be assembled from beads sold in the store:\n\n\\begin{center}\n{\\small The first necklace cannot be assembled because it has three beads \"a\" (of the two available). The second necklace cannot be assembled because it contains a bead \"d\", which is not sold in the store.}\n\\end{center}\n\nWe call a necklace $k$-beautiful if, when it is turned clockwise by $k$ beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace.\n\nAs you can see, this necklace is, for example, $3$-beautiful, $6$-beautiful, $9$-beautiful, and so on, but it is not $1$-beautiful or $2$-beautiful.In particular, a necklace of length $1$ is $k$-beautiful for any integer $k$. A necklace that consists of beads of the same color is also beautiful for any $k$.\n\nYou are given the integers $n$ and $k$, and also the string $s$ containing $n$ lowercase letters of the English alphabet — each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a $k$-beautiful necklace you can assemble.",
    "tutorial": "Let's iterate over the $m$ - length of the $k$-beautiful necklace. For each position $i$, make an edge to the position $p[i] = (i + k) \\bmod m$, where $a \\bmod b$ - is the remainder of dividing $a$ by $b$. What is a cyclic shift by $k$ in this construction? A bead located at position $i$ will go along the edge to position $p[i]$. Consider all the cycles of a graph constructed on $p$. You may notice that if only equal letters are found in each cycle, then with a cyclic shift by $k$ the graph and the string will remain unchanged. Thus, in order to check whether it is possible to make a $k$-beautiful necklace of length $m$, you need to make a graph $p$, find the cycles in it and check whether it is possible to distribute the letters from the string $s$ in cycles such that each cycle have equal letters. The last part of the solution can be done with simple greedy.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint test;\n\tcin >> test;\n\n\twhile (test--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tstring s;\n\t\tcin >> s;\n\n\t\tvector<int> cnt(26);\n\n\t\tfor (char c : s) {\n\t\t\tcnt[c - 'a']++;\n\t\t}\n\n\t\tfor (int len = n; len >= 1; len--) {\n\t\t\tvector<bool> used(len);\n\t\t\tvector<int> cycles;\n\n\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\tif (used[i]) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tint j = (i + k) % len;\n\t\t\t\tused[i] = true;\n\t\t\t\tcycles.push_back(0);\n\t\t\t\tcycles.back()++;\n\n\t\t\t\twhile (!used[j]) {\n\t\t\t\t\tcycles.back()++;\n\t\t\t\t\tused[j] = true;\n\t\t\t\t\tj = (j + k) % len;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvector<int> cur_cnt(cnt);\n\n\t\t\tsort(cycles.begin(), cycles.end());\n\t\t\tsort(cur_cnt.begin(), cur_cnt.end());\n\n\t\t\tbool can_fill = true;\n\n\t\t\twhile (!cycles.empty()) {\n\t\t\t\tif (cur_cnt.back() < cycles.back()) {\n\t\t\t\t\tcan_fill = false;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tcur_cnt.back() -= cycles.back();\n\t\t\t\t\tcycles.pop_back();\n\t\t\t\t\tsort(cur_cnt.begin(), cur_cnt.end());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (can_fill) {\n\t\t\t\tcout << len << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1367",
    "index": "F2",
    "title": "Flying Sort (Hard Version)",
    "statement": "\\textbf{This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on $n$ are greater than in the easy version of the problem.}\n\nYou are given an array $a$ of $n$ integers \\textbf{(the given array can contain equal elements)}. You can perform the following operations on array elements:\n\n- choose any index $i$ ($1 \\le i \\le n$) and move the element $a[i]$ to the \\textbf{begin} of the array;\n- choose any index $i$ ($1 \\le i \\le n$) and move the element $a[i]$ to the \\textbf{end} of the array.\n\nFor example, if $n = 5$, $a = [4, 7, 2, 2, 9]$, then the following sequence of operations can be performed:\n\n- after performing the operation of the first type to the second element, the array $a$ will become $[7, 4, 2, 2, 9]$;\n- after performing the operation of the second type to the second element, the array $a$ will become $[7, 2, 2, 9, 4]$.\n\nYou can perform operations of any type any number of times in any order.\n\nFind the minimum total number of operations of the first and second type that will make the $a$ array sorted in non-decreasing order. In other words, what is the minimum number of operations must be performed so the array satisfies the inequalities $a[1] \\le a[2] \\le \\ldots \\le a[n]$.",
    "tutorial": "Let's replace each number $a_i$ with the number of unique numbers less than $a_i$. For example, the array $a=[3, 7, 1, 2, 1, 3]$ will be replaced by $[2, 3, 0, 1, 0, 2]$. Note that the values of the numbers themselves were not important to us, only the order between them was important. Let's sort such an array. Let's see what maximum length of the segment from the array $a$ is already sorted (it forms a subsequence). This segment can be left in place, and all other numbers can be moved either to the beginning or to the end. That is, the task came down to finding the maximum sorted subsequence in the array. This problem can be solved with the help of simple dynamic programming. Let $dp[i]$ -- be the maximum length of a subsequence ending in position $i$. To calculate it, we will find the closest past position, which also has the value $a[i]$ and the position with value $a[i]-1$ (lower numbers cannot be used, since $a[i]-1$ must stand between them). Any of these positions can be extended, so we take the maximum out of them and add 1. It is necessary to separately consider the first numbers in the subsequence and the last, since the first should include their suffix, and the last should have their prefix.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ld = long double;\nusing ll = long long;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> v(n);\n    vector<pair<int, int>> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> v[i];\n        a[i] = {v[i], i};\n    }\n    sort(a.begin(), a.end());\n    vector<int> p(n);\n    int j = 0;\n    unordered_multiset<int> next;\n    for (int i = 0; i < n; i++) {\n        if (i > 0 && a[i].first != a[i - 1].first) {\n            j++;\n        }\n        p[a[i].second] = j;\n        next.insert(j);\n    }\n    unordered_map<int, int> d;\n    vector<int> dp1(n), dp2(n), dp3(n), cnt(n);\n    for (int i = 0; i < n; i++) {\n        if (next.count(p[i])) {\n            next.erase(next.find(p[i]));\n        }\n        if (d.count(p[i] - 1)) {\n            if (!d.count(p[i])) {\n                dp2[i] = max(dp2[i], dp1[d[p[i] - 1]] + 1);\n                if (!next.count(p[i] - 1)) {\n                    dp2[i] = max(dp2[i], dp2[d[p[i] - 1]] + 1);\n                }\n            }\n            if (!next.count(p[i] - 1)) {\n                dp3[i] = max(dp3[i], dp2[d[p[i] - 1]] + 1);\n            }\n            dp3[i] = max(dp3[i], dp1[d[p[i] - 1]] + 1);\n        }\n        if (d.count(p[i])) {\n            dp3[i] = max(dp3[i], dp3[d[p[i]]] + 1);\n            dp2[i] = max(dp2[i], dp2[d[p[i]]] + 1);\n            dp1[i] = dp1[d[p[i]]] + 1;\n        } else {\n            dp1[i] = 1;\n        }\n        dp2[i] = max(dp2[i], dp1[i]);\n        dp3[i] = max(dp3[i], dp2[i]);\n        d[p[i]] = i;\n    }\n    cout << n - *max_element(dp3.begin(), dp3.end()) << \"\\n\";\n}\n\nint main() {\n    int n;\n    cin >> n;\n    while (n--) {\n        solve();\n    }\n}\n\n",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1368",
    "index": "A",
    "title": "C+=",
    "statement": "Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a \"+=\" operation that adds the right-hand side value to the left-hand side variable. For example, performing \"a += b\" when a =$2$, b =$3$ changes the value of a to $5$ (the value of b does not change).\n\nIn a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations \"a += b\" or \"b += a\". Leo wants to test handling large integers, so he wants to make the value of either a or b \\textbf{strictly greater} than a given value $n$. What is the smallest number of operations he has to perform?",
    "tutorial": "After any operation either $a$ or $b$ becomes $a + b$. Out of the two options, clearly it is better to increase the smaller number. For example, with numbers $2, 3$ we can either get a pair $2, 5$ or $3, 5$; to obtain larger numbers, the last pair is better in every way. With this we can just simulate the process and count the number of steps. The worst case is $a = b = 1$, $n = 10^9$, where each new addition produces the next element of the Fibonacci sequence. At this point we can just run the simulation and find out that $43$ steps are always enough. In general, Fibonacci sequence grows exponentially, thus $O(\\log n)$ steps are needed. Find a closed formula for the answer. For simplicity assume $a \\leq b$,",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1368",
    "index": "B",
    "title": "Codeforces Subsequences",
    "statement": "Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least $k$ subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.\n\nFormally, a codeforces subsequence of a string $s$ is a subset of ten characters of $s$ that read codeforces from left to right. For example, codeforces contains codeforces a single time, while codeforcesisawesome contains codeforces four times: {\\textbf{codeforces}isawesome}, {\\textbf{codeforce}si\\textbf{s}awesome}, {\\textbf{codeforce}sisawe\\textbf{s}ome}, {\\textbf{codeforc}esisaw\\textbf{es}ome}.\n\nHelp Karl find any shortest string that contains at least $k$ codeforces subsequences.",
    "tutorial": "Suppose that instead of codeforces subsequences we're looking for, say, abcde subsequences. Then in an optimal string all a's appear at the front. Indeed, moving any other occurence of a to the front will leave all the other occurences intact, and can only possibly create new ones. For a similar reason, all b's should immediately follow, then go all c's, and so on. The only question is how many a's, b's, etc should we take. The answer is we should have quantities of each letter as close as possible to each other. Indeed, the number of subsequences is $n_a \\times n_b \\times \\ldots \\times n_e$, where $n_a, n_b, \\ldots$ are the number of occurences of each letter. If, say, $n_a - n_b > 1$, then it is not hard to show that transforming an a to a b increases the product. Now the optimal distribution can be obtained simply by increasing $n_a, n_b, \\ldots$ one by one in a loop. We should stop once the product is at least $k$. This approach will, however, not work quite as well if the subsequence has repeated letters. Still, it is natural to expect that the same pattern applies to optimal strings with codeforces subsequences: it has a lot of unique letters, and repeated letters are far apart. It was hardly necessary, but here's one way to prove that the pattern works (math and casework alert): Letters d, f, r, s should form consecutive blocks. If, say, two d's are separated by other letters, we can look which d is present in fewer number of subsequences, and more it next to the more popular one. The same argument works for all other letters. It doesn't make sense to put anything other than e's between d's and f's. Indeed, any other letter won't be present in any subsequences. Similarly, there can only be o's between f's and r's. Now we know the string looks like ???dddeeefffooorrr???sss. Finally, only c's and o's can precede d's, and it doesn't make sense to place o's before c's. Similarly, c's and e's in this order occupy the space between r's and s's. It follows that the same solution as above can be applied to solve this problem. As mentioned above, the problem is not that easy in general case when there are a lot of repeated letters. Still, is it possible to do? Any solution faster than brute-force would be interesting, or even some ideas or observations. I find it much harder to create a good easy problem than a good hard problem. This position in paricular gave me a lot of trouble, we had to scratch three or four other versions. Not to say the result is very inspiring, but the previous ones were even worse... What do you except to see in a good easy problem, say, up to Div1A? What are you favourite easy problems of this level? I would especially appreciate answers from high-rated coders.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1368",
    "index": "C",
    "title": "Even Picture",
    "statement": "Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.\n\nTo draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied:\n\n- The picture is \\textbf{connected}, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side).\n- Each gray cell has an \\textbf{even number of gray neighbours}.\n- There are \\textbf{exactly $n$ gray cells with all gray neighbours}. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).\n\nLeo Jr. is now struggling to draw a beautiful picture with a particular choice of $n$. Help him, and provide any example of a beautiful picture.\n\nTo output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $(0, 0)$, axes $0x$ and $0y$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.",
    "tutorial": "The sample picture was a red herring, it's hard to generalize to work for arbitrary $n$. After drawing for a while you may come up with something like this: or like this: or something even more complicated. Of course, having a simpler construction (like the first one) saves time on implementation compared to other ones. Don't settle for a solution if it feels too clunky, take a moment and see if you can make it simpler. How to minimize the total number of squares for a given $n$? The squares-on-a-diagonal construction in the first picture is pretty efficient, but e.g. for $n=4$ the picture in the sample has fewer squares. How does the minimum-square picture look in general?",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1368",
    "index": "D",
    "title": "AND, OR and square sum",
    "statement": "Gottfried learned about binary number representation. He then came up with this task and presented it to you.\n\nYou are given a collection of $n$ non-negative integers $a_1, \\ldots, a_n$. You are allowed to perform the following operation: choose two distinct indices $1 \\leq i, j \\leq n$. If before the operation $a_i = x$, $a_j = y$, then after the operation $a_i = x~\\mathsf{AND}~y$, $a_j = x~\\mathsf{OR}~y$, where $\\mathsf{AND}$ and $\\mathsf{OR}$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero).\n\nAfter all operations are done, compute $\\sum_{i=1}^n a_i^2$ — the sum of squares of all $a_i$. What is the largest sum of squares you can achieve?",
    "tutorial": "Let's look at a single operation $x, y \\to x~\\mathsf{AND}~y, x~\\mathsf{OR}~y$, let the last two be $z$ and $w$ respectively. We can notice that $x + y = z + w$. Indeed, looking at each bit separately we can see that the number of $1$'s in this bit is preserved. Clearly $z \\leq w$, and suppose also that $x \\leq y$. Since the sum is preserved, we must have $z = x - d$, $w = y + d$ for some non-negative $d$. But then the sum of squares of all numbers changes by $z^2 + w^2 - x^2 - y^2$. Substituting for $z$ and $w$ and simplifying, this is equal to $2d(d + y - x)$, which is positive when $d > 0$. Side note: an easier (?) way to spot the same thing is to remember that $f(x) = x^2$ is convex, thus moving two points on the parabola away from each other by the same amount increases the sum of values. It follows that any operation increases the square sum (as long as any numbers change), and we should keep doing operations while we can. When can we no longer make meaningful operations? At that point all numbers should be submasks of each other. The only way that could happen is when for any bit only several largest numbers have $1$ in that position. We also know that the number of $1$'s in each bit across all numbers is preserved. Thus, it's easy to recover the final configuration: for each bit count the number of $1$'s, and move all these $1$'s to the last (=greatest) numbers. For example, for the array $[1, 2, 3, 4, 5, 6, 7]$ there are four $1$'s in each of the smallest three bits, thus the final configuration is $[0, 0, 0, 7, 7, 7, 7]$. Finally, print the sum of squares of all these numbers. The total complexity is $O(n \\log_2 A)$, where $A$ is the largest possible number (thus $\\log_2 A$ is roughly the number of bits involved). How to find the smallest number of operations we need to make until there are no more we can make? Any solution polynomial in $n$ and $\\log_2 \\max A$ would be interesting.",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1368",
    "index": "E",
    "title": "Ski Accidents",
    "statement": "Arthur owns a ski resort on a mountain. There are $n$ landing spots on the mountain numbered from $1$ to $n$ from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are \\textbf{no directed cycles} formed by the tracks. There are \\textbf{at most two tracks leaving each spot}, but many tracks may enter the same spot.\n\nA skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks.\n\nArthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable.\n\nFormally, after closing some of the spots, \\textbf{there should not be a path that consists of two or more tracks}.\n\nArthur doesn't want to close too many spots. He will be happy to find any way to close \\textbf{at most $\\frac{4}{7}n$ spots} so that the remaining part is safe. Help him find any suitable way to do so.",
    "tutorial": "Let's consider vertices from $1$ to $n$ (that is, in topological order). We divide them into three sets $V_0$, $V_1$, $V_2$: $V_0$ contains all vertices that only have incoming edges from $V_2$; $V_1$ contains all vertices that have an incoming edge from $V_0$, but not from $V_1$; $V_2$ contains all vertices that have an incoming edge from $V_1$. It is not hard to see that erasing all vertices in $V_2$ leaves no two-edge paths. The same solution can be simply rephrased as: go from left to right, and remove current vertex if it is at the end of a two-edge path. Why does this work? Every vertex of $V_2$ has to have at least one incoming edge from $V_1$. There are at most $2|V_1|$ such edges, thus $|V_2| \\leq 2|V_1|$, and $|V_1| \\geq |V_2| / 2$. Similarly, $|V_0| \\geq |V_1| / 2 \\geq |V_2| / 4$. But then $n = |V_0| + |V_1| + |V_2| \\geq |V_2| (1 + 1/2 + 1/4) = 7|V_2|/4$, thus $|V_2| \\leq 4n/7$. This is very easy to implement in $O(n)$ time. It's not hard to construct a test where $n/2$ spots have to be closed. However, I could not find a test where more that $n/2$ spots need to be closed, nor do I know of a solution that closes less than $4n/7$ spots in the worst case. In other words, if $\\alpha$ is the optimal constant such that $\\alpha n + o(n)$ spots need to be closed, we know that $1/2 \\leq \\alpha \\leq 4/7$. Can I find better bounds for $\\alpha$, or even find its precise value? Huge thanks to our tester kocko for pointing out many mistakes in an old version of this problem's statement, and even proposing a revision of a big part of the statement which we've adopted. Sadly, many other parts of the statement still were not very clear...",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1368",
    "index": "F",
    "title": "Lamps on a Circle",
    "statement": "This is an interactive problem.\n\nJohn and his imaginary friend play a game. There are $n$ lamps arranged in a circle. Lamps are numbered $1$ through $n$ in clockwise order, that is, lamps $i$ and $i + 1$ are adjacent for any $i = 1, \\ldots, n - 1$, and also lamps $n$ and $1$ are adjacent. Initially all lamps are turned off.\n\nJohn and his friend take turns, with John moving first. On his turn John can choose to terminate the game, or to make a move. To make a move, John can choose any positive number $k$ and turn any $k$ lamps of his choosing on. In response to this move, John's friend will choose $k$ \\textbf{consecutive} lamps and turn all of them off (the lamps in the range that were off before this move stay off). Note that the value of $k$ is the same as John's number on his last move. For example, if $n = 5$ and John have just turned three lamps on, John's friend may choose to turn off lamps $1, 2, 3$, or $2, 3, 4$, or $3, 4, 5$, or $4, 5, 1$, or $5, 1, 2$.\n\nAfter this, John may choose to terminate or move again, and so on. However, John can not make more than $10^4$ moves.\n\nJohn wants to maximize the number of lamps turned on at the end of the game, while his friend wants to minimize this number. Your task is to provide a strategy for John to achieve optimal result. Your program will play interactively for John against the jury's interactor program playing for John's friend.\n\nSuppose there are $n$ lamps in the game. Let $R(n)$ be the number of turned on lamps at the end of the game if both players act optimally. Your program has to terminate the game with at least $R(n)$ turned on lamps within $10^4$ moves. Refer to Interaction section below for interaction details.\n\nFor technical reasons \\textbf{hacks for this problem are disabled.}",
    "tutorial": "Let try to come up with an upper bound on $R(n)$. Let $x$ be the number of currently turned on lamps. Consider our last move that resulted in increasing $x$ (after the response was made), and suppose it turned on $k$ lamps. If the opponent could then find a segment of $k$ consecutive lamps and turn them off, the move could be reverted. From this we can conclude that $x$ could not be too large. Indeed, after the move $x + k$ lamps should have been divided into segments of length at most $k - 1$ each (since the opponent couldn't turn $k$ lamps off), separated by turned off lamps. The number of segments should have been at least $\\frac{x + k}{k - 1}$, and the same bound applies to the number of separating lamps. Thus we must have had $x + k + \\frac{x + k}{k - 1} \\leq n$. After some boring transformations we obtain $x \\leq n - k - \\frac{n}{k} + 1$. It follows that $x$ can not be increased past this threshold with turning on $k$ lamps. This implies that $x$ can not be increased past $\\max_k \\left(n - k - \\frac{n}{k} + 1\\right)$ with any move, thus $R(n) \\leq \\max_k \\left(n - k - \\left\\lceil\\frac{n}{k}\\right\\rceil + 1\\right)$. On the other hand, let's take such a $k$ that maximizes $n - k - \\left\\lceil\\frac{n}{k}\\right\\rceil + 1$, and adopt the following strategy: Pick $\\left\\lceil\\frac{n}{k}\\right\\rceil$ lamps that divide the circle into segments of length $\\leq k - 1$ each, and never turn these lamps on. We can choose these lamps greedily at distance $k$ from each other, until we go full circle (at that point the distance from the last to the first lamp may be less than $k$). On each move, turn on any $k$ lamps except for the forbidden ones. Since the turned on lamps never form a segment of length $k$, we will successfully increase $x$ with this move. We stop once there are less than $k$ non-forbidden lamps to turn on. At this point we will have $x \\geq n - \\left\\lceil\\frac{n}{k}\\right\\rceil - k + 1$, thus $R(n)$ can not be less than this value. We've determined that $R(n) = \\max_k \\left(n - k - \\left\\lceil\\frac{n}{k}\\right\\rceil + 1\\right)$, and provided a quite simple strategy to achieve this result. For large $n$, the maximum is attained at $k \\approx \\sqrt{n}$, thus $R(n) \\approx n - 2\\sqrt{n}$. If the first player wants to minimize the number of turns until $R(n)$ lamps are lit, and the second player wants to maximize it, what is the resulting number of turns $T(n)$ is going to be? Precise formula would be awesome, but asymptotics or interesting bounds for $T(n)$ would be interesting too.",
    "tags": [
      "games",
      "implementation",
      "interactive",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1368",
    "index": "G",
    "title": "Shifting Dominoes",
    "statement": "Bill likes to play with dominoes. He took an $n \\times m$ board divided into equal square cells, and covered it with dominoes. Each domino covers two adjacent cells of the board either horizontally or vertically, and each cell is covered exactly once with a half of one domino (that is, there are no uncovered cells, and no two dominoes cover the same cell twice).\n\nAfter that Bill decided to play with the covered board and share some photos of it on social media. First, he removes exactly one domino from the board, freeing two of the cells. Next, he moves dominoes around. A domino can only be moved \\textbf{along the line parallel to its longer side}. A move in the chosen direction is possible if the next cell in this direction is currently free. Bill doesn't want to lose track of what the original tiling looks like, so he makes sure that at any point each domino \\textbf{shares at least one cell with its original position}.\n\nAfter removing a domino and making several (possibly, zero) moves Bill takes a photo of the board and posts it. However, with the amount of filters Bill is using, domino borders are not visible, so \\textbf{only the two free cells of the board} can be identified. When the photo is posted, Bill reverts the board to its original state and starts the process again.\n\nBill wants to post as many photos as possible, but he will not post any photo twice. How many distinct photos can he take? Recall that photos are different if the pairs of free cells in the photos are different.",
    "tutorial": "Let's think of how a certain cell can be freed up. One way is to just lift the domino covering it from the start. If we didn't do it, then we must move the domino covering the cell, and there is exactly one way of doing so. But at this point the cell we've moved to should have been free. We can follow this chain of events, and we must eventually arrive to a cell that was covered by the initially removed domino. This is more readily seen if we draw a graph with vertices being cells, and edges leading from the cell freed up by moving a domino to the cell becoming occupied by doing so. Note that some of the cells are impossible to free up with such a move. Let us study this graph a bit more. If we color the board like a chessboard, we can see that edges always connect cells of the same color, so the two subgraphs for white and black cells are independent. Further, since initially a white and a black cell are freed, the two free cells will always have different colors. In this graph each vertex (= cell) has out-degree at most $1$. In general directed graphs of this kind are called functional graphs, and look like a bunch of trees linked to directed cycles. However, it turns out that our graph can not have cycles! To prove this, let's look a how this cycle would look like: Centers of all the cells in a cycle form a lattice polygon. The area of such a polygon can be found with Pick's formula: $S = I + B / 2 - 1$, where $I$ and $B$ is the number of lattice points inside and on the boundary respectively. However, we can observe that: $B$ is the length of the boundary. The boundary can be broken into segments of length $2$. The length of upward and downward arrows is the same, therefore the length of vertical borders is divisible by $4$, same for horizontal arrows. Thus $B$ is divisible by $4$, and $B / 2$ must be even. Inside of the polygon can be broken down into $2 \\times 2$ squares, therefore $S$ must be even. $I = S - B / 2 + 1$ should therefore be odd. However, the inside of the cycle is isolated from the outside, and therefore should be independently tilable with dominoes. But the number of cells (= vertices) inside the cycle is odd, therefore it's impossible. Since our directed graph has no cycles, it must be a directed forest, which makes it much easier to handle. Now consider a pair of cells $c_1, c_2$ of different colors, and look at the paths $P_1$ and $P_2$ starting at these cells. If these paths reach the boundary without visiting the same domino, then the pair $c_1, c_2$ is impossible to free up, since we would have to remove at least two dominoes. If the paths do visit at least one common domino, then we argue that the pair is possible to free up. Indeed, consider the first domino $D$ on $P_1$ that is also visited by $P_2$. If we remove $D$, then the parts of $P_1$ and $P_2$ until $D$ can not intersect, thus it is possible to move dominoes to free $c_1$ and $c_2$ without trying to move any domino twice. To figure out the answer, consider the two forests $F_1$ and $F_2$ built up by black and white cells of the board. If we label each cell of each forest with the index of the domino covering this cell, then the answer is equal to the number of pairs of cells $c_1 \\in F_1$, $c_2 \\in F_2$ such that the paths starting at $c_1$ and $c_2$ have common labels. To actually compute the answer we will instead count the cell pairs with label-disjoint paths. This is now a fairly standard data structure problem. Construct Euler tours in both $F_1$ and $F_2$. Then, the subtree of each vertex is a segment in the Euler tour. For a cell $c_1 \\in F_1$ labeled with domino $D$, suitable cells in $F_2$ are the ones not in the subtree of a cell sharing the label with $c_1$ or with any parent of $c_1$. Perform a DFS of $F_1$, following edges in reverse. When we enter a cell labeled $D$, locate the cell with this label in $F_2$ and mark all vertices in its subtree. At this point, we should add the number of unmarked cells in $F_2$ to the answer. When we leave the cell, revert to the previous configuration before marking the subtree. Implementation-wise, this can be done with a segment tree that supports adding on a segment (= subtree in the Euler tour), and finding the number of zeros (= unmarked cells). Segment tree is the most demanding component of the solution, thus the complexity is $O(nm \\log (nm))$. What are the minimum and maximum possible answers among all tilings of the board of given dimensions $n$ and $m$? The final version of this problem is due to 300iq who proposed an interesting modification to my initial idea.",
    "tags": [
      "data structures",
      "geometry",
      "graphs",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1368",
    "index": "H2",
    "title": "Breadboard Capacity (hard version)",
    "statement": "This is a harder version of the problem H with modification queries.\n\nLester and Delbert work at an electronics company. They are currently working on a microchip component serving to connect two independent parts of a large supercomputer.\n\nThe component is built on top of a breadboard — a grid-like base for a microchip. The breadboard has $n$ rows and $m$ columns, and each row-column intersection contains a node. Also, on each side of the breadboard there are ports that can be attached to adjacent nodes. Left and right side have $n$ ports each, and top and bottom side have $m$ ports each. Each of the ports is connected on the outside to one of the parts bridged by the breadboard, and is colored red or blue respectively.\n\nPorts can be connected by wires going inside the breadboard. However, there are a few rules to follow:\n\n- Each wire should connect a red port with a blue port, and each port should be connected to at most one wire.\n- Each part of the wire should be horizontal or vertical, and turns are only possible at one of the nodes.\n- To avoid interference, wires can not have common parts of non-zero length (but may have common nodes). Also, a wire can not cover the same segment of non-zero length twice.\n\nThe capacity of the breadboard is the largest number of red-blue wire connections that can be made subject to the rules above. For example, the breadboard above has capacity $7$, and one way to make seven connections is pictured below.\n\nUp to this point statements of both versions are identical. Differences follow below.\n\nAs is common, specifications of the project change a lot during development, so coloring of the ports is not yet fixed. There are $q$ modifications to process, each of them has the form of \"colors of all ports in a contiguous range along one of the sides are switched (red become blue, and blue become red)\". All modifications are persistent, that is, the previous modifications are not undone before the next one is made.\n\nTo estimate how bad the changes are, Lester and Delbert need to find the breadboard capacity after each change. Help them do this efficiently.",
    "tutorial": "We are basically asked to find the maximum flow value from red ports to blue ports in the grid network. All edges can be assumed to be bidirectional and have capacity $1$. By Ford-Fulkerson theorem, the maximum flow value is equal to the minimum cut capacity. In our context it is convenient to think about minimum cut as a way to paint nodes inside the grid red and blue so that the number of edges connecting differently colored nodes is smallest possible. For a given coloring, let us construct a cut in the dual graph by connecting the faces separated by multicolored edges. Note that the cut can be decomposed into cycles, paths connecting two points on the border, and single edge cuts adjacent to the ports. We may assume that different parts of the cut do not cross each other since we can just reassign parts at the crossing. The following actions modify the cut without increasing its capacity (the number of crossed edges): Interior of any cycle can be recolored, which makes the cycle disappear. If a path connects a pair of adjacent sides, we may get rid of the path and instead cut/uncut ports in the corner separated by the path. A path connecting opposite sides can be transformed into a straight segment, possibly with cutting/uncutting some ports. Applying these operations to any minimum cut, we can obtain a minimum cut that only consists of port cuts and straight segments parallel to one of the sides. Note that a port cut is essentially equivalent to recoloring of that port, with increase $1$ towards the cut capacity. Each straight segment contributes $n$ or $m$ to the capacity depending on the orientation. A minimum cut of the form above can be found with a simple linear dynamic programming. First, choose the direction of straight cuts (say, vertical). All ports along each vertical side should be recolored to the same color. Then, proceeding in the horizontal direction we may decide to recolor ports adjacent to horizontal sides, and/or to make a straight vertical cut. We need to make sure that each connected part between the cuts has uniform color. In addition to the horizontal position, the only extra parameter for this DP is the color immediately behind the current vertical line. This solves the easy version of the problem. To solve the hard version, we need to combine this DP with lazy propagation segment tree. We will store a separate segment tree for each direction of straight cuts. Say, for vertical cuts, a node $[L, R)$ should store costs to properly recolor and/or make straight cuts in the horizontal range $[L, R)$ so that the leftmost/rightmost nodes are red/blue (all four options). Make sure to take fixing vertical sides into account when calculating the answer. Merging the cost values from two halves of a node segment follows directly from the original DP recalculation. To be able to make range flips fast enough, we need to store four more values - the answers assuming that the opposite sides take opposite colors instead of the same colors. Now to flip a node in the segment tree simply exchange the correct values with the opposite ones. Implementation details are left for the reader to work out. =) With this approach we are able to process each modification query in $O(\\log n + \\log m)$ time, although the constant factor is fairly large because of complicated merging process. Can you solve the same problem in 3D? The breadboard is now an $n \\times m \\times k$ parallelepiped, and there are $2(nm + nk + mk)$ adjacent ports.",
    "tags": [],
    "rating": 3500
  },
  {
    "contest_id": "1369",
    "index": "A",
    "title": "FashionabLee",
    "statement": "Lee is going to fashionably decorate his house for a party, using some regular convex polygons...\n\nLee thinks a regular $n$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $OX$-axis and at least one of its edges is parallel to the $OY$-axis at the same time.\n\nRecall that a regular $n$-sided polygon is a convex polygon with $n$ vertices such that all the edges and angles are equal.\n\nNow he is shopping: the market has $t$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.",
    "tutorial": "$\\mathcal Complete\\;\\mathcal Proof :$ Proof by contradiction : One can prove that if two edges in a regular polygon make a $x < 180$ degrees angle, then for each edge $a$ there exist two another edges $b$ and $c$ such that $a$ and $b$ make a $x$ degrees angle as well as $a$ and $c$. (proof is left as an exercise for the reader) Consider a rotation such that an edge $a$ is parallel to $OX$-axis and an edge $b$ is parallel to $OY$-axis, then $a \\perp b$ ($a$ and $b$ are perpendicular, i. e. the angle between them is $90$ degrees), we can see that there exist a third edge $c$ such that it's also parallel to $OX$-axis and a forth edge $d$ such that it's also parallel to $OY$-axis, so $a \\perp d$ and $b \\perp c$ and $c \\perp d$. Our polygon is regular so all the angles are equal, so that the number of angles between $a$ and $b$ is equal to the number of angles between $b$ and $c$ and so on, also we know that a regular $n$-sided convex polygon has $n$ angles, so $n$ is divisible by $4$, contradiction!",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        int n;\n        cin >> n;\n        if(n % 4 == 0){\n            cout << \"YES\\n\";\n        }\n        else cout << \"NO\\n\";\n    }\n}\n",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1369",
    "index": "B",
    "title": "AccurateLee",
    "statement": "Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...\n\nThe string $s$ he found is a binary string of length $n$ (i. e. string consists only of 0-s and 1-s).\n\nIn one move he can choose two consecutive characters $s_i$ and $s_{i+1}$, and if $s_i$ is 1 and $s_{i + 1}$ is 0, he can erase \\textbf{exactly one of them} (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.\n\nLee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $s$ as clean as possible. He thinks for two different strings $x$ and $y$, the \\textbf{shorter} string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.\n\nNow you should answer $t$ test cases: for the $i$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.\n\nSmall reminder: if we have two strings $x$ and $y$ of the same length then $x$ is lexicographically smaller than $y$ if there is a position $i$ such that $x_1 = y_1$, $x_2 = y_2$,..., $x_{i - 1} = y_{i - 1}$ and $x_i < y_i$.",
    "tutorial": "$\\mathcal Complete\\; \\mathcal Proof$ : Realize that the answer is always non-descending, and we can't perform any operations on non-descending strings. First we know that we can't perform any operations on non-descending strings, so the answer to a non-descending string is itself. From now we consider our string $s$ to not to be non-descending. (i.e. there exist index $i$ such that $1 \\le i \\le n-1$ and $s_i > s_{i+1}$) Also realize that the remaining string wont be empty, so \"0\" is the cleanest possible answer, but we can't reach it probable. Now realize that leading zeroes and trailing ones can't be present in any operation. So they have to be in the answer, erase them from $s$, and add them to the answer for the modified $s$. From now we know that the string $s$ has no leading zeroes and/or trailing ones, and is not non-descending, so it starts with $1$ and ends with $0$. (why?) With some small paperwork, we will realize that the answer to a string that starts with $1$ and ends with $0$ is a single $0$(proof is bellow). So if the string $s$ is non-descending and it has $x$ leading zeroes and $y$ trailing ones($x$ and $y$ can be equal to zero), then the answer is $\\underbrace{0\\,0\\dots0}_{x}\\,0\\,\\underbrace{1\\,1\\dots1}_{y}$ (its $x+1$ zeroes and $y$ ones in order) $\\mathcal The\\;\\mathcal Small\\;\\mathcal Paperwork:$ We will randomly perform operations until we can't do any more or the string's length is equal to $2$, but we wont erase the first $1$ and the last $0$, we want to prove that the remaining string's length is exactly $2$ after the process ends, proof by contradiction : So it's length is at least $3$, so we have at least two $1$ or at least two $0$. If we had two or more $0$ then the string $[s_1\\,s_2\\dots s_{n-1}]$ will not be non-descending(so we can perform more operations as we proved in STAR, but the process have ended, contradiction!) and if we had two or more $1$ then the string $[s_2\\,s_3\\dots s_n]$ will not be non-descending. So the length of the remaining string is exactly $2$, and we haven't erased first '1' and last '0', so the string is equal to \"10\", now erase '1' to get the cleanest string. Sorry if the proof seems too long and hard, i wanted to explain it accurately. ^-^",
    "code": "#include <iostream>\n#include <string>\n \nusing namespace std;\n \nint main(){\n    \n    int t;\n    cin >> t;\n    while(t--){\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        int sw = 1;\n        for(int i = 1; i < s.size(); i++){\n            if(s[i] < s[i-1])sw = 0;\n        }\n        if(sw){\n            cout << s << '\\n';\n            continue;\n        }\n        string ans;\n        for(int i = 0; i < s.size(); i++){\n            if(s[i] == '1')break;\n            ans.push_back('0');\n        }\n        ans.push_back('0');\n        for(int i = s.size()-1; i >= 0; i--){\n            if(s[i] == '0')break;\n            ans.push_back('1');\n        }\n        cout << ans << '\\n';\n    }\n}\n",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1369",
    "index": "C",
    "title": "RationalLee",
    "statement": "Lee just became Master in Codeforces, and so, he went out to buy some gifts for his friends. He bought $n$ integers, now it's time to distribute them between his friends rationally...\n\nLee has $n$ integers $a_1, a_2, \\ldots, a_n$ in his backpack and he has $k$ friends. Lee would like to distribute \\textbf{all} integers in his backpack between his friends, such that the $i$-th friend will get exactly $w_i$ integers and each integer will be handed over to exactly one friend.\n\nLet's define the happiness of a friend as the sum of the maximum and the minimum integer he'll get.\n\nLee would like to make his friends as happy as possible, in other words, he'd like to maximize the sum of friends' happiness. Now he asks you to calculate the maximum sum of friends' happiness.",
    "tutorial": "$\\mathcal Complete\\; \\mathcal Proof$ : First if $w_i = 1$ for some $i$, then assign the greatest element to $i$-th friends, it's always better obviously. Sort the elements in non-descending order and sort the friends in non-ascending order of $w_i$. Define $v_i$ the set of indices of elements to give to $i$-th friend. Also define $l_i$ the minimum element to give to $i$-th friend and $r_i$ the maximum element to give to $i$-th friend, and define $m = \\max\\limits_{1\\,\\le\\,i\\,\\le\\,k} w_i$. Now it's easy to see that the first element of $a$(the smallest element) is always equal to $l_i$ for some $i$, Indeed it's better to have the rest of $v_i$ equal to a small number except one of them, which should be equal to a very large number. So we can greedily assign $a_1$, $a_2$ ... $a_{{w_i}-1}$ to $v_i$, and then assign $a_n$ to it, also it's better to have $w_i = m$. One can prove that there exist an optimal distributing such that the set($\\{a_1, a_2 \\ldots a_{m-1}, a_n\\}$) is equal to one of $v_i$-s(proof is blow). So add $a_1 + a_n$ to the answer for remaining elements of $a$(excluding the set) and remaining friends(excluding one of the friends with maximum $w_i$) and so, it will be optimal. Look at an optimal distributing (which maximizes sum of happiness), first element of $a$ is in $v_i$ for example, we want to prove that in at least one of the optimal distributings $w_i-1$ smallest elements of $a$ are in $v_i$ (including the first element), proof by contradiction: If at least one of the smallest $w_i-1$ elements is not in $v_i$, then call the smallest of them $x$, lets say it's in $v_j$, now add $x$ to $v_i$(and erase it from $v_j$), instead add a greater number than $x$ in $v_i$ to $v_j$ (it's at least two of them, and one of them is $r_i$, so there exist another one, erase it from $v_i$ and add it to $v_j$), it's easy to see that sum of happiness won't decrease that way, continue the process until all $w_i-1$ smallest elements are in $v_i$, so we have an optimal answer which has all $w_i-1$ smallest elements in $v_i$, contradiction! As we proved above, we have an optimal distributing such that all $w_i-1$ smallest elements are in $v_i$(for some $i$), now we want to prove that the greatest element is in $v_i$ in at least one of the optimal distributings, again proof by contradiction. Lets say it's not that way, so look at an optimal distributing such that first $w_i-1$ elements are in $v_i$ and $r_i$ is not equal to the greatest element(for some $i$), if there exist such $j$ that $r_i < l_j$, then swap $r_i$ and $l_j$, the resulting distributing has the same happiness, continue it until no such $j$ exist, now lets say the greatest element of $a$ is in $v_j$ for some $j$, also we know that $r_j$ is equal to the greatest element of $a$ and $l_j \\le r_i$(if $r_i < l_j$ then the process of swapping is not finished, which is contradiction). So now we can swap $r_i$ and $r_j$, again the resulting distributing has happiness greater than or equal to the happiness of the optimal distributing(the one we chose in the beginning), and so, its also an optimal distributing, and $r_i$ is equal to the greatest element, we have found an optimal distributing such that first $w_i-1$ elements of $a$ and $a_n$ are in $v_i$(for some $i$), contradiction! Now we have proved that there exist an optimal distributing such that first $w_i-1$ elements of $a$ and $a_n$ are in $v_i$(for some $i$), call such optimal distributing STAR, and now the only remaining part is to prove that there exist an optimal distributing such that first $m-1$ elements of $a$ and $a_n$ are in $v_i$(for some $i$). See the whole algorithm, its like \"we choose a permutation of friends then we do that greedy assignment to them one by one from left to right\", now we want to prove that there exist an optimal distributing such that it's STAR and it's permutation is sorted in non-descending order of $w$, call them GOOD distributings. Again, proof by contradiction : Choose a distributing such that it's a STAR, it's permutation(called $p$) is not sorted in non-descending order of $w$(otherwise it's a GOOD distributing, contradiction!), so there exist an $i$ such that $w_{p_i} > w_{p_{i+1}}$, now swap them(i. e. swap $p_i$ and $p_{i+1}$ and then do the same greedy assignment using the modified permutation of friends), it's easy to see that happiness of friends after $i+1$ in permutation $p$ wont change, also happiness of friends before $i$ in the permutation wont change as well. Now look at the happiness of $p_i$ and $p_{i+1}$, you can realize that sum of happiness will increase. You really don't need to prove it like that, it's not time friendly at all. ^-^",
    "code": "#include <bits/stdc++.h>\n#define ll long long\n#define fr first\n#define sc second\n#define int ll\n\nusing namespace std;\nconst int MN = 2e5+7;\n\nvector<int> v[MN];\n\nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie();\n    cout.tie();\n\n    int t;\n    cin >> t;\n    while(t--){\n        int n, k;\n        cin >> n >> k;\n        for(int i = 0; i <= n; i++)v[i].clear();\n        ll a[n], w[k];\n        for(int i = 0; i < n; i++){\n            cin >> a[i];\n        }\n        for(int i = 0; i < k; i++){\n            cin >> w[i];\n        }\n        sort(w, w+k);\n        sort(a, a+n);\n        for(int i = 0; i < k/2; i++)swap(w[i], w[k-i-1]);\n        int po = 0;\n        for(int i = 0; i < n-k; i++){\n            while(w[po] == v[po].size()+1)po++;\n            v[po].push_back(a[i]);\n        }\n        ll ans = 0;\n        int qf = 1;\n        for(int i = 0; i < k; i++){\n            ans += a[n-i-1];\n            if(v[i].size())ans += v[i][0];\n            else ans += a[n-qf], qf++;\n        }\n        \n        cout << ans << '\\n';\n    }\n}\n",
    "tags": [
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1369",
    "index": "D",
    "title": "TediousLee",
    "statement": "Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...\n\nLet's define a Rooted Dead Bush (RDB) of level $n$ as a rooted tree constructed as described below.\n\nA rooted dead bush of level $1$ is a single vertex. To construct an RDB of level $i$ we, at first, construct an RDB of level $i-1$, then for each vertex $u$:\n\n- if $u$ has no children then we will add a single child to it;\n- if $u$ has one child then we will add two children to it;\n- if $u$ has more than one child, then we will skip it.\n\n\\begin{center}\n{\\small Rooted Dead Bushes of level $1$, $2$ and $3$.}\n\\end{center}\n\nLet's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:\n\n\\begin{center}\n{\\small The center of the claw is the vertex with label $1$.}\n\\end{center}\n\nLee has a Rooted Dead Bush of level $n$. Initially, all vertices of his RDB are green.\n\nIn one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.\n\nHe'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $10^9+7$.",
    "tutorial": "$\\mathcal Complete \\mathcal Proof$ : First realize that a RDB of level $i$ is consisted of a vertex (the root of the RDB of level $i$) connected to the roots of two RDBs of level $i-2$ and a RDB of level $i-1$. Now define $dp_i$ equal to the answer for a RDB of level $i$. Also define $r_i$ equal to $1$ if Lee can achieve $dp_i$ yellow vertices in a RDB of level $i$ such that the root is green, and $0$ otherwise. It's easy to see that $dp_i$ is equal to either $2 \\cdot dp_{i-2} + dp_{i-1}$ or $2 \\cdot dp_{i-2} + dp_{i-1} + 4$. If both $r_{i-1}$ and $r_{i-2}$ are equal to $1$, then we can color the claw rooted at the root of the RDB, then $r_i = 0$ and $dp_i = 2 \\cdot dp_{i-2} + dp_{i-1} + 4$. Also if either $r_{i-2}$ or $r_{i-1}$ is equal to $0$ then $r_i = 1$ and $dp_i = 2 \\cdot dp_{i-2} + dp_{i-1}$. Challenge : Try solving problem D for $n \\le 10^{18}$. (no matrix-multiplication)",
    "code": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\nconst int mod = int(1e9+7);\nconst int MN = int(2e6+7);\n\nint dp[MN];\n\nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie();\n    cout.tie();\n    dp[0] = dp[1] = 0;\n    dp[2] = 4;\n    for(int i = 3; i < MN; i++){\n        long long w = dp[i-1];\n        w += 2*dp[i-2] + (i % 3 == 2)*4;\n        w %= mod;\n        dp[i] = w;\n    }\n\n    int t;\n    cin >> t;\n    while(t--){\n        int n;\n        cin >> n;\n        n--;\n        cout << dp[n]%mod << '\\n';\n    }\n}\n",
    "tags": [
      "dp",
      "graphs",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1369",
    "index": "E",
    "title": "DeadLee",
    "statement": "Lee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020...\n\nThere are $n$ different types of food and $m$ Lee's best friends. Lee has $w_i$ plates of the $i$-th type of food and each friend has two different favorite types of food: the $i$-th friend's favorite types of food are $x_i$ and $y_i$ ($x_i \\ne y_i$).\n\nLee will start calling his friends one by one. Whoever is called will go to the kitchen and will try to eat \\textbf{one plate of each of his favorite food types}. Each of the friends will go to the kitchen exactly once.\n\nThe only problem is the following: if a friend will eat at least one plate of food (in total) then he will be harmless. But if there is nothing left for him to eat (neither $x_i$ nor $y_i$), he will eat Lee instead $\\times\\_\\times$.\n\nLee can choose the order of friends to call, so he'd like to determine if he can survive dinner or not. Also, he'd like to know the order itself.",
    "tutorial": "$\\mathcal Complete\\;\\mathcal Solution$ : Define $s_i$ equal to the number of friends who likes food $i$. We want to proof that if $\\forall 1 \\le i \\le m \\Rightarrow s_i > w_i\\, \\text{or} \\, s_i = 0$ then no answer exist, it can be proved easily by contradiction, just look at the last friend in any suitable permutation, he will eat Lee as there is no food for him. So if it was the case, then print Dead and terminate, otherwise place all the guys who likes food $i$ in the end of the permutation, they wont eat Lee as they can always eat food $i$, also it's always better to place them in the end, as if we place them in the end, then they wont eat two plates. Continue the process until no friends exist or no $i$ exist such that $w_i \\ge s_i > 0$. Note that when we erase the friends, we have to update $s_i$, also if $s_i = 0$ we should erase food $i$ from the set of foods. $\\mathcal Implementation\\;\\mathcal Details$ : Instead of erasing friends/foods, just remember if a friend/food is erased or not using another array. Also updating $s$ should not be that much hard(when marking $i$-th friend, decrease $s_{x_i}$ and $s_{y_i}$ by one, if there exist any), also you can have the food $i$ with maximum $w_i-s_i$ with a priority queue, or any other data structure in $O(\\log_2{n})$. The whole solution will work in $O((n+m)\\cdot \\log_2{(n+m)}$ time, you can also try achieving $O(n+m)$ and then show-off it in the comment section ^_^.",
    "code": "#include <bits/stdc++.h>\n\n#define ll long long\n#define fr first\n#define sc second\n#define pii pair<int, int>\n#define all(v) v.begin(), v.end()\n\nusing namespace std;\nconst int MN = 2e5+7;\n\nint x[MN], y[MN], s[MN], w[MN], mark[MN], colmark[MN];\n\nvector<int> v[MN], a;\nvector<pii> f;\n\npriority_queue<pii, vector<pii>, greater<pii>> pq;\n\nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie();\n    cout.tie();\n    int n, m;\n    cin >> n >> m;\n    for(int i = 1; i <= n; i++)cin >> w[i];\n    for(int i = 0; i < m; i++){\n        cin >> x[i] >> y[i];\n        s[x[i]]++;\n        s[y[i]]++;\n        v[x[i]].push_back(i);\n        v[y[i]].push_back(i);\n    }\n    for(int i = 1; i <= n; i++){\n        if(s[i])pq.push({max(0, s[i]-w[i]), i});\n        else colmark[i] = 1;\n    }\n\n    while(pq.size()){\n        auto q = pq.top();\n        pq.pop();\n        if(q.fr != max(0, s[q.sc]-w[q.sc]))continue;\n        if(q.fr > 0){\n            cout << \"DEAD\\n\";\n            exit(0);\n        }\n        int id = q.sc;\n        vector<int> wt;\n        for(auto u : v[id]){\n            if(mark[u])continue;\n            a.push_back(u);\n            if(x[u] == id)\n                swap(x[u], y[u]);\n            if(!colmark[x[u]])wt.push_back(x[u]);\n            mark[u] = 1;\n        }\n        sort(all(wt));\n        for(int i = 0; i < wt.size(); i++){\n            s[wt[i]]--;\n            if(i == wt.size()-1 || wt[i+1] != wt[i]){\n                if(s[wt[i]]){\n                    if(max(0, s[wt[i]]-w[wt[i]]) == 0)colmark[wt[i]] = 1;\n                    pq.push({max(0, s[wt[i]]-w[wt[i]]), wt[i]});\n                }\n            }\n        }\n    }\n    cout << \"ALIVE\\n\";\n    for(int i = 0; i < a.size()/2; i++)swap(a[i], a[a.size()-i-1]);\n    for(auto u : a){\n        cout << u+1 << ' ';\n    }\n    cout << '\\n';\n}\n",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1369",
    "index": "F",
    "title": "BareLee",
    "statement": "Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called \"Critic\"...\n\nThe game is a one versus one game. It has $t$ rounds, each round has two integers $s_i$ and $e_i$ (which are determined and are known before the game begins, $s_i$ and $e_i$ may differ from round to round). The integer $s_i$ is written on the board at the beginning of the corresponding round.\n\nThe players will take turns. Each player will erase the number on the board (let's say it was $a$) and will choose to write either $2 \\cdot a$ or $a + 1$ instead. Whoever writes a number strictly greater than $e_i$ loses that round and the other one wins that round.\n\nNow Lee wants to play \"Critic\" against Ice Bear, for each round he has chosen the round's $s_i$ and $e_i$ in advance. Lee will start the first round, the loser of each round will start the next round.\n\nThe winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.\n\nDetermine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.",
    "tutorial": "$\\mathcal Complete \\mathcal Proof$ : Define $w_{s,\\,e}$ ($s \\le e$) equal to $1$ if Lee can win the game when $s$ is written on the board, and equal to $0$ otherwise, also define $l_{s,\\,e}$ the same way. This leads to a simple dp. Forget $l$ for now. Recall that a state ${i,\\,j}$ of our dp is a losing state if $w_{i,\\,j} = 0$, and is a winning state otherwise. You can guess $w_{s,\\,e}$ for all $s$ in range $\\frac e 4 < s \\le e$ in $O(1)$, you don't have to store them : If $e$ is odd then it will be $w_{1,\\,e} = 1, w{2,\\,e} = 0, w{3,\\,e} = 1 \\dots w{e,\\,e} = 0$, in other words if $e$ is odd, then if $s$ is odd too $w{s,\\,e} = 0$, otherwise $w{s,\\,e} = 1$. Prove it by induction, for $s = e$ it's correct, assume that for an integer $i$ ($1 \\le i < e$) we have proved that the statement is correct for all $j$ where $i < j \\le e$, now we want to prove the statement for $i$ : If $i$ is odd then both $i + 1$ and $2 \\cdot i$ are winning states (as they are even), also if $i$ is even then $i + 1$ is odd, $i+1$ is smaller than $e$ so it's a losing state(induction assumption). From now we consider $e$ to be even. Also $\\times 2$ operation is replacing $a$, the number on the board, with $2 \\cdot a$, and $+ 1$ operation is the other move. For $\\frac e 2 < s \\le e$ whoever uses $\\times 2$ operation will lose. So they all have to use $+ 1$ operation, so for ${e \\over 2} < s \\le e$ if $w$ is odd, then $w_{s,\\,e} = 1$, otherwise $w_{s,\\,e} = 0$. (it's obvious, it can be proved with a simple induction like the one in previous part) For ${e \\over 4} < s \\le {e \\over 2}$, Lee can do a $\\times 2$ operation in the first turn and he will win because his opponent is starting a losing state. For $s \\le {e \\over 4}$, $w_{s,\\,e}$ is equal to $\\displaystyle w_{s,\\,\\lfloor {e \\over 4} \\rfloor}$. (why?) Now it's time to calculate $l_{s,\\,e}$. Remember, whoever writes an integer greater than $e$ will lose, so if $e < 2 \\cdot s$ then the first guy can immediately lose. So $l_{s,\\,e}$ for ${e \\over 2} < s \\le e$ is equal to $1$. And $l_{s,\\,e}$ for $s \\le {e \\over 2}$ is equal to $\\displaystyle w_{s,\\,{\\lfloor {e \\over 2} \\rfloor}}$. (why?)",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n#define fr first\n#define sc second\n#define ll long long\n#define int ll\n\nusing namespace std;\n\nconst int MN = 1e5+7;\n\npair<int, int> c[MN];\n\nint chk(ll s, ll e){\n    if(e == s)return 0;\n    if(e == s+1)return 1;\n    if(e & 1){\n        if(s & 1)return 0;\n        return 1;\n    }\n    if(s <= e/4)\n        return chk(s, e/4);\n    if(s > (e/4)*2)return ((e-s)&1);\n    else return 1;\n}\n\nint lck(ll s, ll e){\n    if(s*2 > e)return 1;\n    int w = e/2 + 3;\n    while(w*2 > e)w--;\n    return chk(s, w);\n}\n\nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie();\n    cout.tie();\n\n    int n;\n    cin >> n;\n\n    for(int i = 0; i < n; i++){\n        ll x, y;\n        cin >> x >> y;\n        c[i] = {chk(x, y), lck(x, y)};\n    }\n\n    int f = 1;\n    int s = 0;\n    for(int i = 0; i < n; i++){\n        if(f == 1 && s == 1)break;\n        if(f == 0 && s == 0)break;\n        if(s == 1) c[i].fr^=1, c[i].sc^=1;\n        f = c[i].sc;\n        s = c[i].fr;\n    }\n    cout << s << ' ' << f << '\\n';\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "games"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1370",
    "index": "A",
    "title": "Maximum GCD",
    "statement": "Let's consider all integers in the range from $1$ to $n$ (inclusive).\n\nAmong all pairs of \\textbf{distinct} integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $\\mathrm{gcd}(a, b)$, where $1 \\leq a < b \\leq n$.\n\nThe greatest common divisor, $\\mathrm{gcd}(a, b)$, of two positive integers $a$ and $b$ is the biggest integer that is a divisor of both $a$ and $b$.",
    "tutorial": "Key Idea: Answer for any $n \\ge 2$ is equal to $\\lfloor{\\frac{n}{2}}\\rfloor$ . Solution: Let the maximum gcd be equal to $g$. Since the two numbers in a pair are distinct, one of them must be $\\gt g$ and both of them must be divisible by $g$. The smallest multiple of $g$, greater than $g$, is $2 \\cdot g$. Since each number in the pair must be $\\le n$, we must have $2 \\cdot g \\le n$, or $g \\le \\lfloor{\\frac{n}{2}}\\rfloor$. We can achieve $g = \\lfloor{\\frac{n}{2}}\\rfloor$, by choosing $\\lfloor{\\frac{n}{2}}\\rfloor$ and $2 \\cdot \\lfloor{\\frac{n}{2}}\\rfloor$. Time Complexity: $O(1)$",
    "code": "\n#include < bits/stdc++.h >\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n\nconst int N = 1e5 + 5;\n\nint32_t main()\n{\n\tIOS;\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin >> n;\n\t\tcout << n / 2 << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1370",
    "index": "B",
    "title": "GCD Compression",
    "statement": "Ashish has an array $a$ of consisting of $2n$ positive integers. He wants to compress $a$ into an array $b$ of size $n-1$. To do this, he first discards exactly $2$ (any two) elements from $a$. He then performs the following operation until there are no elements left in $a$:\n\n- Remove any two elements from $a$ and append their sum to $b$.\n\nThe compressed array $b$ has to have a special property. The greatest common divisor ($\\mathrm{gcd}$) of all its elements should be greater than $1$.\n\nRecall that the $\\mathrm{gcd}$ of an array of positive integers is the biggest integer that is a divisor of all integers in the array.\n\nIt can be proven that it is always possible to compress array $a$ into an array $b$ of size $n-1$ such that $gcd(b_1, b_2..., b_{n-1}) > 1$.\n\nHelp Ashish find a way to do so.",
    "tutorial": "Key Idea: It is always possible to form $n-1$ pairs of elements such that their gcd is divisible by $2$. Solution: We can pair up the odd numbers and even numbers separately so that the sum of numbers in each pair is divisible by $2$. Note that we can always form $n - 1$ pairs in the above manner because in the worst case, we would discard one odd number and one even number from $a$. If we discarded more than one even or odd numbers, we could instead form another pair with even sum. Time Complexity: $O(n)$",
    "code": "\n#include < bits/stdc++.h >\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n\nconst int N = 2e5 + 5;\n\nint n;\nint a[N];\n\nint32_t main()\n{\n\tIOS;\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tcin >> n;\n\t\tvector< int > even, odd;\n\t\tfor(int i = 1; i <= 2 * n; i++)\n\t\t{\n\t\t\tcin >> a[i];\n\t\t\tif(a[i] % 2)\n\t\t\t\todd.push_back(i);\n\t\t\telse\n\t\t\t\teven.push_back(i);\n\t\t}\n\t\tvector< pair< int, int > > ans;\n\t\tfor(int i = 0; i + 1 < odd.size(); i += 2)\n\t\t\tans.push_back({odd[i], odd[i + 1]});\n\t\tfor(int i = 0; i + 1 < even.size(); i += 2)\n\t\t\tans.push_back({even[i], even[i + 1]});\n\t\tfor(int i = 0; i < n - 1; i++)\n\t\t\tcout << ans[i].first << \" \" << ans[i].second << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1370",
    "index": "C",
    "title": "Number Game",
    "statement": "Ashishgup and FastestFinger play a game.\n\nThey start with a number $n$ and play in turns. In each turn, a player can make \\textbf{any one} of the following moves:\n\n- Divide $n$ by any of its odd divisors greater than $1$.\n- Subtract $1$ from $n$ if $n$ is greater than $1$.\n\nDivisors of a number include the number itself.\n\nThe player who is \\textbf{unable to make a move} loses the game.\n\nAshishgup moves first. Determine the winner of the game if both of them play optimally.",
    "tutorial": "Key Idea: FastestFinger wins for $n=1$ , $n=2^x$ where ($x>1$) and $n= 2 \\cdot p$ where $p$ is a prime $\\ge 3$ else Ashishgup wins. Solution: Let's analyse the problem for the following $3$ cases: Case $1$: n is oddHere Ashishgup can divide $n$ by itself, since it is odd and hence $\\frac{n}{n} = 1$, and FastestFinger loses. Here $n = 1$ is an exception. Here Ashishgup can divide $n$ by itself, since it is odd and hence $\\frac{n}{n} = 1$, and FastestFinger loses. Here $n = 1$ is an exception. Case $2$: $n$ is even and has no odd divisors greater than $1$Here $n$ is of the form $2^x$. As $n$ has no odd divisors greater than $1$, Ashishgup is forced to subtract it by $1$ making $n$ odd. So if $x > 1$, FastestFinger wins. For $x = 1$, $n - 1$ is equal to $1$, so Ashishgup wins. Here $n$ is of the form $2^x$. As $n$ has no odd divisors greater than $1$, Ashishgup is forced to subtract it by $1$ making $n$ odd. So if $x > 1$, FastestFinger wins. For $x = 1$, $n - 1$ is equal to $1$, so Ashishgup wins. Case $3$: $n$ is even and has odd divisorsIf $n$ is divisible by $4$ then Ashishgup can divide $n$ by its largest odd factor after which $n$ becomes of the form $2^x$ where $x \\gt 1$, so Ashishgup wins. Otherwise $n$ must be of the form $2 \\cdot p$, where $p$ is odd. If $p$ is prime, Ashishgup loses since he can either reduce $n$ by $1$ or divide it by $p$ both of which would be losing for him. If $p$ is not prime then $p$ must be of the form $p_1 \\cdot p_2$ where $p_1$ is prime and $p_2$ is any odd number $\\gt 1$. Ashishgup can win by dividing $n$ by $p_2$. If $n$ is divisible by $4$ then Ashishgup can divide $n$ by its largest odd factor after which $n$ becomes of the form $2^x$ where $x \\gt 1$, so Ashishgup wins. Otherwise $n$ must be of the form $2 \\cdot p$, where $p$ is odd. If $p$ is prime, Ashishgup loses since he can either reduce $n$ by $1$ or divide it by $p$ both of which would be losing for him. If $p$ is not prime then $p$ must be of the form $p_1 \\cdot p_2$ where $p_1$ is prime and $p_2$ is any odd number $\\gt 1$. Ashishgup can win by dividing $n$ by $p_2$.",
    "code": "\n#include< bits/stdc++.h >\nusing namespace std;\n\nconst int N = 50000;\n\nvoid player_1(){\n\tcout << \"Ashishgup\" << endl;\n}\n\nvoid player_2(){\n\tcout << \"FastestFinger\" << endl;\n}\n\nbool check_prime(int n){\n\tfor(int i = 2; i < min(N, n); i++)\n\t\tif(n % i == 0)\n\t\t\treturn 0;\n\treturn 1;\n}\n\nint main(){\n\tint tc;\n\tcin >> tc;\n\twhile(tc--){\n\t\tint n;\n\t\tcin >> n;\n\t\tbool lose = (n == 1);\n\t\tif(n > 2 && n % 2 == 0){\n\t\t\tif((n & (n — 1)) == 0)\n\t\t\t\tlose = 1;\n\t\t\telse if(n % 4 != 0 && check_prime(n / 2))\n\t\t\t\tlose = 1;\n\t\t}\n\t\tif(lose)\n\t\t\tplayer_2();\n\t\telse player_1();\n\t}\n}",
    "tags": [
      "games",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1370",
    "index": "D",
    "title": "Odd-Even Subsequence",
    "statement": "Ashish has an array $a$ of size $n$.\n\nA subsequence of $a$ is defined as a sequence that can be obtained from $a$ by deleting some elements (possibly none), without changing the order of the remaining elements.\n\nConsider a subsequence $s$ of $a$. He defines the cost of $s$ as the minimum between:\n\n- The maximum among all elements at odd indices of $s$.\n- The maximum among all elements at even indices of $s$.\n\nNote that the index of an element is its index in $s$, rather than its index in $a$. The positions are numbered from $1$. So, the cost of $s$ is equal to $min(max(s_1, s_3, s_5, \\ldots), max(s_2, s_4, s_6, \\ldots))$.\n\nFor example, the cost of $\\{7, 5, 6\\}$ is $min( max(7, 6), max(5) ) = min(7, 5) = 5$.\n\nHelp him find the minimum cost of a subsequence of size $k$.",
    "tutorial": "Key Idea: Binary search over the answer and check if given $x$, it is possible to form a subsequence of length at least $k$ such that either all elements at odd indices or even indices are $\\le x$. Solution: Let us binary search over the answer and fix if the answer comes from elements at odd or even indices in the subsequence. Suppose we want to find if there exists a subsequence of length at least $k$ such that the elements at odd indices are $\\le x$. We will construct the subsequence greedily. Let's iterate on the array from left to right. Suppose we are at index $i$ in the array and the current length of the subsequence formed is $l$. If $l$ is odd, the next added element would be at an even index. In this case, we do not care about what this element is as we only want elements at odd indices to be $\\le x$. So, in this case, we add $a_i$ to the subsequence. If $l$ is even, then the next added element would be at an odd index, so, it must be $\\le x$. If $a_i \\le x$, we can add $a_i$ to the subsequence, otherwise we do not add $a_i$ to the subsequence and continue to the next element in $a$. Note that we can do a similar greedy construction for elements at even indices. If the length of the subsequence formed is $\\ge k$ (either by construction from odd indices or even indices), then the answer can be equal to $x$ and we can reduce the upper bound of the binary search otherwise we increase the lower bound. Time Complexity - $O(n \\cdot log_2 (A_i))$ or $O(n \\cdot log_2 (n))$",
    "code": "\n\n#include < bits/stdc++.h >\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n\nconst int N = 2e5 + 5;\n\nint n, k;\nint a[N];\n\nbool check(int x, int cur)\n{\n\tint ans = 0;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tif(!cur)\n\t\t{\n\t\t\tans++;\n\t\t\tcur ^= 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(a[i] <= x)\n\t\t\t{\n\t\t\t\tans++;\n\t\t\t\tcur ^= 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn ans >= k;\n}\n\nint binsearch(int lo, int hi)\n{\n\twhile(lo < hi)\n\t{\n\t\tint mid = (lo + hi) / 2;\n\t\tif(check(mid, 0) || check(mid, 1))\n\t\t\thi = mid;\n\t\telse\n\t\t\tlo = mid + 1;\n\t}\n\treturn lo;\n}\n\nint32_t main()\n{\n\tIOS;\n\tcin >> n >> k;\n\tfor(int i = 1; i <= n; i++)\n\t\tcin >> a[i];\n\tint ans = binsearch(1, 1e9);\n\tcout << ans;\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "dp",
      "dsu",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1370",
    "index": "E",
    "title": "Binary Subsequence Rotation",
    "statement": "Naman has two binary strings $s$ and $t$ of length $n$ (a binary string is a string which only consists of the characters \"0\" and \"1\"). He wants to convert $s$ into $t$ using the following operation as few times as possible.\n\nIn one operation, he can choose any subsequence of $s$ and rotate it clockwise once.\n\nFor example, if $s = 1\\textbf{1}101\\textbf{00}$, he can choose a subsequence corresponding to indices ($1$-based) $\\{2, 6, 7 \\}$ and rotate them clockwise. The resulting string would then be $s = 1\\textbf{0}101\\textbf{10}$.\n\nA string $a$ is said to be a subsequence of string $b$ if $a$ can be obtained from $b$ by deleting some characters without changing the ordering of the remaining characters.\n\nTo perform a clockwise rotation on a sequence $c$ of size $k$ is to perform an operation which sets $c_1:=c_k, c_2:=c_1, c_3:=c_2, \\ldots, c_k:=c_{k-1}$ simultaneously.\n\nDetermine the minimum number of operations Naman has to perform to convert $s$ into $t$ or say that it is impossible.",
    "tutorial": "Key Idea: Firstly, if $s$ is not an anagram of $t$, it is impossible to convert $s$ to $t$ - since total number of $0$s and $1$s are conserved. However, if they are anagrams, we can always convert $s$ to $t$. We can ignore all the indices where $s_i = t_i$ as it is never optimal to include those indices in a rotation. The remaining indices must be satisfy $s_i = 0, t_i = 1$ or $s_i = 1, t_i = 0$. In the optimal answer, the chosen subsequences should be of the form 01010101... or 10101010... Solution: There are many approaches to solving the problem, all revolving around the key idea. We can greedily find the minimum number of chains of alternating 0 and 1 that the string can be broken down into - using faster ways of simulation, such as a counter-based for loop or using sets and deleting successive indices, etc. However, we will discuss an elegant approach which allows us to solve the problem and also prove its optimality. Moreover, it allows us to solve the problem for queries of the form $(l, r)$ - which denotes the answer for the strings $s[l,r]$ and $t[l,r]$ respectively. Logic: Let's create an array $a$ with values from $(-1, 0, 1)$ as follows: If $s_i = t_i$, $a_i = 0$ Else if $s_i = 1$, $a_i = 1$ Else $a_i = -1$ Proof: The chosen subsequences must be of the form 01010101 or 10101010 (alternating 0s and 1s). If there are two consecutive $0$s or $1$s we can remove any one of them as applying the rotation operation could only affect one of them. The maximum absolute value of subarray sum in $a$ is a lower bound on the answer. Let the sum of any subarray in $a$ be $c$. We can assume that $c \\ge 0$ (otherwise we can interchange $1$ and $-1$). In any move, $c$ cannot be reduced by more than $1$, since we must choose subsequences of the form 010101 or 101010. We can achieve the above lower bound, and hence it is the answer. To prove the claim, we just need to show that in every operation, we can reduce the value of maximum absolute subarray sum by $1$ (if there are multiple such subarrays, then we must reduce all of them by $1$). For the above, a key realization is: suppose the maximum comes from a subarray $(l, r)$ with a positive sum. Then it is necessary that on both sides of its endpoints if there is an element, it must be $-1$ (we can ignore the $0$s), since if either side had a $+1$, we would have a higher valued subarray. Now we can pick any $1$ from this subarray and a $-1$ either from its left or right to reduce its sum by $1$, thus completing the proof. (Note that any subarray with maximum absolute sum must have at least one element with sign opposite to its sum either to its left or right.) Time complexity: $O(n)$",
    "code": "\n#include < bits/stdc++.h >\nusing namespace std;\n \n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n#define endl \"\\n\"\n#define int long long\n\nconst int N = 1e6 + 5;\n\nint n;\nstring s, t;\nint a[N];\n\nint get(int x)\n{\n\tint cur = 0, mx = 0;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tcur += x * a[i];\n\t\tmx = max(mx, cur);\n\t\tif(cur < 0)\n\t\t\tcur = 0;\n\t}\n\treturn mx;\n}\n\nint32_t main()\n{\n\tIOS;\n\tcin >> n >> s >> t;\n\tint sum = 0;\n\tfor(int i = 1; i <= n; i++)\n\t{\n\t\tif(s[i - 1] != t[i - 1])\n\t\t{\n\t\t\tif(s[i - 1] == '1')\n\t\t\t\ta[i] = -1;\n\t\t\telse\n\t\t\t\ta[i] = 1;\n\t\t}\n\t\tsum += a[i];\n\t}\n\tif(sum != 0)\n\t{\n\t\tcout << -1;\n\t\treturn 0;\n\t}\n\tint ans = max(get(1), get(-1));\n\tcout << ans;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1370",
    "index": "F2",
    "title": "The Hidden Pair (Hard Version)",
    "statement": "\\textbf{Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.}\n\n\\textbf{This is an interactive problem.}\n\nYou are given a tree consisting of $n$ nodes numbered with integers from $1$ to $n$. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query:\n\n- Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes.\n\nRecall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.\n\nMore formally, let's define two hidden nodes as $s$ and $f$. In one query you can provide the set of nodes $\\{a_1, a_2, \\ldots, a_c\\}$ of the tree. As a result, you will get two numbers $a_i$ and $dist(a_i, s) + dist(a_i, f)$. The node $a_i$ is any node from the provided set, for which the number $dist(a_i, s) + dist(a_i, f)$ is minimal.\n\n\\textbf{You can ask no more than $11$ queries.}",
    "tutorial": "Key Idea: We can find out one of the nodes in the path between the two hidden nodes using a single query. We can then root the tree at this node find one of the hidden nodes using binary search on its distance from the root. Solution: If we query all nodes in the tree, we will receive one of the nodes in the path between the two hidden nodes and also the distance between the two hidden nodes. Proof: Suppose the distance between the hidden nodes is equal to $l$. All the nodes in the simple path between the two hidden nodes have the sum of distances equal to $l$. For all other nodes, the sum of distances is $\\gt l$. Now that we found a node $r$ in the path between the hidden nodes, we will root the tree at $r$. If we can find one of the hidden nodes, we can easily find the other hidden node by querying all nodes at distance $l$ from the first hidden node. We can find one of the hidden nodes using binary search on its distance from the root. Suppose we query all the nodes at distance $d$ from the root and receive the minimum sum of distance as $x$. If there is at least one hidden node whose distance from the root is $\\ge d$, then $x$ must be equal to $l$. Otherwise, $x$ must be greater than $l$. So we can binary search on $d$ and appropriately change the upper or lower bound of the binary search based on the minimum sum of distances received for the query. This takes $10$ queries as the maximum depth could be up to $n$. Then we need one more query to find the other hidden node. This takes a total of $12$ queries. Note that this is sufficient to pass the easy version. We can further reduce the number of queries by $1$ if we notice that at least one of the hidden nodes must be at least at a distance of $\\lceil{\\frac{l}{2}}\\rceil$ from the root. So we can set the lower bound of the binary search to $\\lceil{\\frac{l}{2}}\\rceil$. Note that if we discard the largest child subtree of the root, it also reduces the number of queries by $1$. Time complexity: $O(n^2)$",
    "code": "\n\n#include< bits/stdc++.h >\nusing namespace std;\n\nconst int N = 1001;\n\nvector< int > adj[N], depth(N), max_depth(N);\n\nint n, root, dist;\n\nvoid dfs(int i, int par){\n\tmax_depth[i] = depth[i];\n\tfor(int j : adj[i]){\n\t\tif(j == par)\n\t\t\tcontinue;\n\t\tdepth[j] = 1 + depth[i], dfs(j, i);\n\t\tmax_depth[i] = max(max_depth[i], max_depth[j]);\n\t}\n}\n\nvoid find_nodes(int i, int par, int req_depth, vector< int > &nodes){\n\tif(depth[i] == req_depth){\n\t\tnodes.push_back(i);\n\t\treturn;\n\t}\n\tfor(int j : adj[i])\n\t\tif(j != par && max_depth[j] <= n / 2)\n\t\t\tfind_nodes(j, i, req_depth, nodes);\n}\n\npair query(vector< int > nodes){\n\tcout << \"? \" << nodes.size() << ' ';\n\tfor(int i : nodes)\n\t\tcout << i << ' ';\n\tcout << endl;\n\tfflush(stdout);\n\n\tint x, dist;\n\tcin >> x >> dist;\n\n\treturn {x, dist};\n}\n\nint main(){\n\tint t;\n\tcin >> t;\n\twhile(t--){\n\t\tcin >> n;\n\n\t\tfor(int i = 1; i <= n; i++)\n\t\t\tadj[i].clear(), depth[i] = 0, max_depth[i] = 0;\n\n\t\tfor(int i = 1; i < n; i++){\n\t\t\tint u, v;\n\t\t\tcin >> u >> v;\n\t\t\tadj[u].push_back(v);\n\t\t\tadj[v].push_back(u);\n\t\t}\n\n\t\tvector< int > nodes;\n\t\tfor(int i = 1; i <= n; i++)\n\t\t\tnodes.push_back(i);\n\n\t\tpair< int, int > res = query(nodes);\n\t\troot = res.first, dist = res.second;\n\n\t\tdfs(root, 0);\n\n\t\tint st = 0, en = n / 2, first_node = root;\n\t\twhile(st <= en){\n\t\t\tint mid = st + en >> 1;\n\n\t\t\tvector< int > node_set;\n\t\t\tfind_nodes(root, 0, mid, node_set);\n\n\t\t\tif(node_set.empty())\n\t\t\t\ten = mid — 1;\n\t\t\telse{\n\t\t\t\tpair< int, int > res = query(node_set);\n\t\t\t\tif(res.second == dist)\n\t\t\t\t\tfirst_node = res.first, st = mid + 1;\n\t\t\t\telse en = mid — 1;\n\t\t\t}\n\t\t}\n\t\tvector< int > candidate_second;\n\t\tqueue< pair< int, int > > q;\n\t\tvector< int > vis(n + 1);\n\t\tq.push({first_node, 0});\n\t\twhile(!q.empty()){\n\t\t\tpair< int, int > node = q.front();\n\t\t\tq.pop();\n\t\t\tvis[node.first] = 1;\n\t\t\tif(node.second == dist)\n\t\t\t\tcandidate_second.push_back(node.first);\n\n\t\t\tfor(int j : adj[node.first])\n\t\t\t\tif(!vis[j])\n\t\t\t\t\tvis[j] = 1, q.push({j, node.second + 1});\n\t\t}\n\t\tpair< int, int > second_node = query(candidate_second);\n\t\tcout << \"! \" << first_node << ' ' << second_node.first << endl;\n\n\t\tstring correct;\n\t\tcin >> correct;\n\t}\n}\n",
    "tags": [
      "binary search",
      "dfs and similar",
      "graphs",
      "interactive",
      "shortest paths",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1371",
    "index": "A",
    "title": "Magical Sticks",
    "statement": "A penguin Rocher has $n$ sticks. He has exactly one stick with length $i$ for all $1 \\le i \\le n$.\n\nHe can connect some sticks. If he connects two sticks that have lengths $a$ and $b$, he gets one stick with length $a + b$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.\n\nHe wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?",
    "tutorial": "Output $\\lceil \\frac{n}{2} \\rceil$. When $n$ is even, we can create $1+n = 2+(n-1) = 3+(n-2) = ...$ When $n$ is odd, we can create $n = 1+(n-1) = 2+(n-2) = ...$ Initially, there are only $1$ stick which has length $i (1 \\le i \\le n)$. If we connect $2$ sticks $s_1$ and $s_2$, after that, there is a stick which has a different length from $s_1$ and $s_2$. Then, we can create at most $1 + \\lfloor \\frac{n-1}{2} \\rfloor$ sticks that have the same length. The value is equal to $\\lceil \\frac{n}{2} \\rceil$. Total complexity: $O(1)$",
    "code": "#include<stdio.h>\n \nint main(){\n  long long n,t;\n  scanf(\"%lld\",&t);\n  while(t>0){\n    t--;\n    scanf(\"%lld\",&n);\n    if(n%2){printf(\"%lld\\n\",(n/2)+1);}\n    else{printf(\"%lld\\n\",n/2);}\n  }\n  return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1371",
    "index": "B",
    "title": "Magical Calendar",
    "statement": "A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $7$ days!\n\nIn detail, she can choose any integer $k$ which satisfies $1 \\leq k \\leq r$, and set $k$ days as the number of days in a week.\n\nAlice is going to paint some $n$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.\n\nShe wants to make \\textbf{all of the painted cells to be connected by side}. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.\n\nAlice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped \\textbf{using only parallel moves, parallel to the calendar's sides}.\n\nFor example, in the picture, a week has $4$ days and Alice paints $5$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes.\n\nAlice wants to know \\textbf{how many possible shapes} exists \\textbf{if she set how many days a week has and choose consecutive $n$ days and paints them in calendar started in one of the days of the week}. As was said before, she considers only shapes, there all cells are connected by side.",
    "tutorial": "First, let's consider in case of a week has exactly $w$ days. If $w<n$ , the length of painted cells is strictly more than one week. So there are $w$ valid shapes. (The first week contains $1,2,...,w$ days) The shapes have $w$-day width, then if the value of $w$ are different, the shapes are also different. Otherwise $(n \\le w)$ , there is only one valid liner pattern. The shape is insensitive to the chosen value of $w$. We can sum up this for $1 \\le w \\le r$, by using following well-known formula: $a+(a+1)+(a+2)+...+b = \\frac{(a+b)*(b-a+1)}{2}$ Total complexity : $O(1)$",
    "code": "#include<stdio.h>\n \nint main(){\n  long long n,l=1,r,t,res;\n  scanf(\"%lld\",&t);\n  while(t>0){\n    t--;\n    res=0;\n    scanf(\"%lld%lld\",&n,&r);\n    if(n<=l){printf(\"1\\n\");continue;}\n    if(n<=r){r=n-1;res=1;}\n    printf(\"%lld\\n\",res+((l+r)*(r-l+1))/2);\n  }\n  return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1371",
    "index": "C",
    "title": "A Cookie for You",
    "statement": "Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $a$ vanilla cookies and $b$ chocolate cookies for the party.\n\nShe invited $n$ guests of the first type and $m$ guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type:\n\nIf there are $v$ vanilla cookies and $c$ chocolate cookies at the moment, when the guest comes, then\n\n- if the guest of the first type: if $v>c$ the guest selects a \\textbf{vanilla} cookie. Otherwise, the guest selects a \\textbf{chocolate} cookie.\n- if the guest of the second type: if $v>c$ the guest selects a \\textbf{chocolate} cookie. Otherwise, the guest selects a \\textbf{vanilla} cookie.\n\nAfter that:\n\n- If there is at least one cookie of the selected type, the guest eats one.\n- Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home.\n\nAnna wants to know if there exists some order of guests, such that \\textbf{no one guest gets angry}. Your task is to answer her question.",
    "tutorial": "If $m < \\min (a,b) , n+m \\le a+b$ are satisfied, the answer is \"Yes\". Otherwise, the answer is \"No\". Let's proof it. Of course, $n+m \\le a+b$ must be satisfied, because violating this inequality means lack of cookies. When a type $2$ guest comes, or when $a=b$, the value of $\\min(a,b)$ is decremented by $1$. You need to consider only about the case that all type $2$ guests come first and after that all type $1$ guests come, because if there is a type $1$ guest before a type $2$ guest, swapping them is better to make no one angry. (Because if there is a type $1$ guest before a type $2$ guest, the type $1$ guest have a possibility to decrease the value of $min(a,b)$ unnecessarily.) At last, all of type $1$ guests eat one cookie when there is at least one cookie(both types are ok). Total complexity: $O(1)$ UPD: $m<\\min(a,b)$ is wrong, the right text is $m\\le \\min(a,b)$",
    "code": "#include<stdio.h>\n \nint main(){\n  long long t,a,b,n,m,k;\n  scanf(\"%lld\",&t);\n  while(t>0){\n    t--;\n    scanf(\"%lld%lld%lld%lld\",&a,&b,&n,&m);\n    if(a>b){k=a;a=b;b=k;}\n    if(a<m){printf(\"No\\n\");continue;}\n    if(a+b<n+m){printf(\"No\\n\");continue;}\n    printf(\"Yes\\n\");\n  }\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1371",
    "index": "D",
    "title": "Grid-00100",
    "statement": "A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!\n\nYou are given integers $n,k$. Construct a grid $A$ with size $n \\times n$ \\textbf{consisting of integers $0$ and $1$}. The very important condition should be satisfied: the sum of all elements in the grid is exactly $k$. In other words, the number of $1$ in the grid is equal to $k$.\n\nLet's define:\n\n- $A_{i,j}$ as the integer in the $i$-th row and the $j$-th column.\n- $R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$ (for all $1 \\le i \\le n$).\n- $C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$ (for all $1 \\le j \\le n$).\n- In other words, $R_i$ are row sums and $C_j$ are column sums of the grid $A$.\n- For the grid $A$ let's define the value $f(A) = (\\max(R)-\\min(R))^2 + (\\max(C)-\\min(C))^2$ (here for an integer sequence $X$ we define $\\max(X)$ as the maximum value in $X$ and $\\min(X)$ as the minimum value in $X$).\n\nFind any grid $A$, which satisfies the following condition. Among such grids find any, for which the value $f(A)$ is the minimum possible. Among such tables, you can find any.",
    "tutorial": "We can construct a grid $A$ which has $f(A)=0$ if $k\\%n=0$ , $f(A)=2(1^2+1^2)$ otherwise (the values are smallest almost obviously.) in following method: First, initialize $A_{i,j}=0$ for all $i,j$. Then, change a $0$ into $1$ $k$ times by using following pseudo code: let p=0 , q=0 for i = 1..k Change A[p+1][q+1] into 1 let p=(p+1) , q=(q+1)%n if(p==n) let p=0 , q=(q+1)%n Total complexity : $O(n^2)$",
    "code": "#include<stdio.h>\n \nint main(){\n  int n,k,t,i,j,p,q;\n  char res[305][305];\n  scanf(\"%d\",&t);\n  while(t>0){\n    t--;\n    scanf(\"%d%d\",&n,&k);\n    if(k%n==0){printf(\"0\\n\");}\n    else{printf(\"2\\n\");}\n    for(i=0;i<n;i++){\n      for(j=0;j<n;j++){\n        res[i][j]='0';\n      }\n      res[i][n]=0;\n    }\n    p=0;q=0;\n    while(k>0){\n      k--;\n      res[p][q]='1';\n      p++;q++;q%=n;\n      if(p==n){\n        p=0;q++;q%=n;\n      }\n    }\n    for(i=0;i<n;i++){\n      printf(\"%s\\n\",res[i]);\n    }\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1371",
    "index": "E1",
    "title": "Asterism (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.}\n\nFirst, Aoi came up with the following idea for the competitive programming problem:\n\nYuzu is a girl who collecting candies. Originally, she has $x$ candies. There are also $n$ enemies numbered with integers from $1$ to $n$. Enemy $i$ has $a_i$ candies.\n\nYuzu is going to determine a permutation $P$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $\\{2,3,1,5,4\\}$ is a permutation, but $\\{1,2,2\\}$ is not a permutation ($2$ appears twice in the array) and $\\{1,3,4\\}$ is also not a permutation (because $n=3$ but there is the number $4$ in the array).\n\nAfter that, she will do $n$ duels with the enemies with the following rules:\n\n- If Yuzu has \\textbf{equal or more} number of candies than enemy $P_i$, she wins the duel and \\textbf{gets $1$ candy}. Otherwise, she loses the duel and gets nothing.\n- The candy which Yuzu gets will be used in the next duels.\n\nYuzu wants to \\textbf{win all duels}. How many valid permutations $P$ exist?\n\nThis problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:\n\nLet's define $f(x)$ as the number of valid permutations for the integer $x$.\n\nYou are given $n$, $a$ and \\textbf{a prime number} $p \\le n$. Let's call a positive integer $x$ \\textbf{good}, if the value $f(x)$ is \\textbf{not} divisible by $p$. Find \\textbf{all} good integers $x$.\n\nYour task is to solve this problem made by Akari.",
    "tutorial": "Let's define $m = max(a_1,a_2,...,a_n)$. Yuzu should have at least $m-n+1$ candies initially to win all duels, then $f(x)=0$ for $x < m-n+1$. This is divisible by $p$. And if Yuzu have equal or more than $m$ candies initially, any permutation will be valid, then $f(x)=n!$ for $x \\ge m$. This is divisible by $p$ , too. (because $p \\le n$) Then, in this subtask, you should find whether each $f(x)$ are divisible by $p$ for $m-n+1 \\le x < m$ in $O(n)$. You can find the value of $f(x)$ by following simulation: First, let $v$={the number of enemies they have strictly less than $x$ candies}, $ans=1$. Then do the following steps for $i=x,x+1,...,x+(n-1)$. $v = v$ + {the number of enemies they have exactly $i$ candies} $ans = ans * v$ $v = v - 1$ Now, $p$ is a prime. Then, \"Whether $f(x)$ is divisible by $p$\" is \"Whether $p$ was multiplied to $ans$ as $v$ at least once.\" This can be simulated in $O(n)$ time for each $x$. Total complexity : $O(n^2)$",
    "code": "#include<stdio.h>\n \nint max(int a,int b){if(a>b){return a;}return b;}\n \nint main(){\n  int n,p;\n  int st,fi;\n  int a[131072],bk[262144]={0},bas=0,i,j;\n  int res[131072],rc=0;\n  scanf(\"%d%d\",&n,&p);\n  for(i=0;i<n;i++){\n    scanf(\"%d\",&a[i]);\n    bas=max(a[i],bas);\n  }\n  for(i=0;i<n;i++){bk[max(0,a[i]-bas+n)]++;}\n  for(i=1;i<262144;i++){bk[i]+=bk[i-1];}\n  for(i=0;i<=n;i++){\n    for(j=0;j<n;j++){\n      if((bk[i+j]-j)<=0){break;}\n      if((bk[i+j]-j)%p==0){break;}\n      if(j==n-1){res[rc]=i+(bas-n);rc++;}\n    }\n  }\n  printf(\"%d\\n\",rc);\n  for(i=0;i<rc;i++){\n    if(i){printf(\" \");}\n    printf(\"%d\",res[i]);\n  }printf(\"\\n\");\n}",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1371",
    "index": "E2",
    "title": "Asterism (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.}\n\nFirst, Aoi came up with the following idea for the competitive programming problem:\n\nYuzu is a girl who collecting candies. Originally, she has $x$ candies. There are also $n$ enemies numbered with integers from $1$ to $n$. Enemy $i$ has $a_i$ candies.\n\nYuzu is going to determine a permutation $P$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $\\{2,3,1,5,4\\}$ is a permutation, but $\\{1,2,2\\}$ is not a permutation ($2$ appears twice in the array) and $\\{1,3,4\\}$ is also not a permutation (because $n=3$ but there is the number $4$ in the array).\n\nAfter that, she will do $n$ duels with the enemies with the following rules:\n\n- If Yuzu has \\textbf{equal or more} number of candies than enemy $P_i$, she wins the duel and \\textbf{gets $1$ candy}. Otherwise, she loses the duel and gets nothing.\n- The candy which Yuzu gets will be used in the next duels.\n\nYuzu wants to \\textbf{win all duels}. How many valid permutations $P$ exist?\n\nThis problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:\n\nLet's define $f(x)$ as the number of valid permutations for the integer $x$.\n\nYou are given $n$, $a$ and \\textbf{a prime number} $p \\le n$. Let's call a positive integer $x$ \\textbf{good}, if the value $f(x)$ is \\textbf{not} divisible by $p$. Find \\textbf{all} good integers $x$.\n\nYour task is to solve this problem made by Akari.",
    "tutorial": "There are two different solutions to solve this problem. Solution 1: First, find the minimum $s$ which has $f(s) > 0$. You can use binary search or cumulative sum for it. Now, we can say the answers form a segment $[s,t]$ (or there are no answers). Find $t$ and proof this. Let's define $b_i$ as the number of the enemies who has equal or less than $i$ candies. Then, observe the value $C_i(x) = b_{x+i}-i \\ (0 \\le i \\le N-1)$ : $f(x) = \\prod_{i=0}^{N-1} C_i(x)$ once the value $C_i(x)$ exceed $p$ , $f(x)$ is divisible by $p$ because $C(x)$ is decremented by (at most) 1 in one step and contains some $C_i(x) = p$ in this $x$. $C_i(x) \\le C_i(x+1)$ are always satisfied. Then, once $f(x)$ is divisible by $p$ , $f(x+\\alpha)$ is also divisible by $p$, so $t$ can be find by using binary search. We can find $t$ without binary search by the following method:1. let $i \\leftarrow 0, t \\leftarrow max(A)$ 2. if($C_i(t)<p$){i++;}else{t-;} 3. Repeat the step 2. And when become $i=N$ and the algorithm stops, $t$ is the maximum value which we want. 1. let $i \\leftarrow 0, t \\leftarrow max(A)$ 2. if($C_i(t)<p$){i++;}else{t-;} 3. Repeat the step 2. And when become $i=N$ and the algorithm stops, $t$ is the maximum value which we want. Solution 2: We can say that $f(x) = \\prod\\limits_{i=x}^{x+n-1} b_i-(i-x) = \\prod\\limits_{i=x}^{x+n-1} x-(i-b_i)$ . We should find all $x \\in \\mathbb{Z}$, such that there is no $x \\leq i < x + n$, such that $x \\equiv i - b_i \\, (\\bmod p)$. It's easy to see, that there should be $max(a_i) - n \\leq x \\leq max(a_i)$ to have $f(x) \\neq 0$ and $f(x) \\neq n!$ (they are both divisible by $p$). Let's calculate $i - b_i$ for all necessary values $max(a_i) - n \\leq x \\leq max(a_i) + n$ and after that we can solve the problem by $O(n)$. Anyway, the total complexity is $O(n)$ or $O(n \\log n)$.",
    "code": "#include<stdio.h>\n \nint max(int a,int b){if(a>b){return a;}return b;}\n \nint modp(int x,int p){\n  if(x>=0){return x%p;}\n  x*=-1;x%=p;\n  return (p-x)%p;\n}\n \nint main(){\n  int n,p;\n  int st,fi;\n  int a[131072],bk[262144]={0},bas=0,i;\n  int fl[131072]={0};\n  int res[131072],rc=0;\n \n  scanf(\"%d%d\",&n,&p);\n  for(i=0;i<n;i++){\n    scanf(\"%d\",&a[i]);\n    bas=max(a[i],bas);\n  }\n  for(i=0;i<n;i++){bk[max(0,a[i]-bas+n)]++;}\n  for(i=1;i<262144;i++){bk[i]+=bk[i-1];}\n \n  for(i=0;i<n;i++){\n    fl[modp((i+(bas-n))-bk[i],p)]++;\n  }\n \n  for(i=0;i<=n;i++){\n    if(fl[modp(i+(bas-n),p)]==0){\n      res[rc]=i+(bas-n);\n      rc++;\n    }\n    fl[modp((i+(bas-n))-bk[i],p)]--;\n    fl[modp(((n+i)+(bas-n))-bk[(n+i)],p)]++;\n  }\n  printf(\"%d\\n\",rc);\n  for(i=0;i<rc;i++){\n    if(i){printf(\" \");}\n    printf(\"%d\",res[i]);\n  }printf(\"\\n\");\n  return 0;\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "dp",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1371",
    "index": "F",
    "title": "Raging Thunder",
    "statement": "You are a warrior fighting against the machine god Thor.\n\nThor challenge you to solve the following problem:\n\nThere are $n$ conveyors arranged in a line numbered with integers from $1$ to $n$ from left to right. Each conveyor has a symbol \"<\" or \">\". The initial state of the conveyor $i$ is equal to the $i$-th character of the string $s$. There are $n+1$ holes numbered with integers from $0$ to $n$. The hole $0$ is on the left side of the conveyor $1$, and for all $i \\geq 1$ the hole $i$ is on the right side of the conveyor $i$.\n\nWhen a ball is on the conveyor $i$, the ball moves by the next rules:\n\nIf the symbol \"<\" is on the conveyor $i$, then:\n\n- If $i=1$, the ball falls into the hole $0$.\n- If the symbol \"<\" is on the conveyor $i-1$, the ball moves to the conveyor $i-1$.\n- If the symbol \">\" is on the conveyor $i-1$, the ball falls into the hole $i-1$.\n\nIf the symbol \">\" is on the conveyor $i$, then:\n\n- If $i=n$, the ball falls into the hole $n$.\n- If the symbol \">\" is on the conveyor $i+1$, the ball moves to the conveyor $i+1$.\n- If the symbol \"<\" is on the conveyor $i+1$, the ball falls into the hole $i$.\n\nYou should answer next $q$ queries, each query is defined by the pair of integers $l, r$ ($1 \\leq l \\leq r \\leq n$):\n\n- First, for all conveyors $l,l+1,...,r$, the symbol \"<\" changes to \">\" and vice versa. \\textbf{These changes remain for the next queries.}\n- After that, put \\textbf{one ball} on each conveyor $l,l+1,...,r$. Then, each ball falls into some hole. Find the maximum number of balls in one hole. \\textbf{After the query all balls disappear and don't considered in the next queries.}",
    "tutorial": "First, observe where the balls fall. When there is a \">>>...>><<...<<<\" structure, the balls on there will fall into one hole. So, our goal is handling this structure. Each query is asking about a segment. Then, to solve this problem, we can use segment tree. Each node maintains following: Prefix structure Suffix structure The answer for between above structures For example, a string \"><<>><>><<>>>>\" will be converted to the following data: Prefix structure : \"><<\" Suffix structure : \">>>>\" The answer for between above structures : take the answer of \">><\" or \">><<\". the largest answer is $4$. And we need to implement that combining two data ( [left data] + [right data] ). Mainly we should merge left suffix and right prefix, and calculate the answer for the segment, but notice that there are some exceptions. The exceptions are in case of there are only one structure in the merged node, like \">>><<\" or \"<<<\". (You may maintain other flags for your implement.) Then, how to handling each queries? We also keep above data for when '>' are changed into '<' and vice versa on each node of the segment tree. And when a change query actually comes to some nodes, swap these data. Apply lazy propagation for handling this. When calculate the answer for a query, don't forget to consider about the prefix(or the suffix). Total complexity : $O(n + q \\log n)$",
    "code": "#include<stdio.h>\n#include<stdbool.h>\n#define ssize 1048576\n \nint max(int a,int b){if(a>b){return a;}return b;}\n \ntypedef struct{\n  //str[0] = prefix\n  //str[1] = suffix\n  //str[][0] = >>>>\n  //str[][1] = <<<<\n  int str[2][2];\n  int res;\n  int dvd;\n}stnode;\n \nstnode stree[2*ssize][2],vd;\nint fl[2*ssize];\n \nvoid stnpr(stnode x,int br){\n  printf(\"<%d %d %d %d %d : %d>\",x.str[0][0],x.str[0][1],x.str[1][0],x.str[1][1],x.dvd,x.res);\n  if(br){printf(\"\\n\");}\n}\n \nstnode merge(stnode l,stnode r){\n  stnode res;\n  //stnpr(l,0);printf(\"+\");stnpr(r,1);\n  res.res=max(l.res,r.res);\n  if(l.dvd==1&&r.dvd==1){\n    res.str[0][0]=l.str[0][0];\n    res.str[0][1]=l.str[0][1];\n    if(l.str[1][1]!=0 && r.str[0][0]!=0){\n      res.res=max(max(l.str[1][0]+l.str[1][1],r.str[0][0]+r.str[0][1]),res.res);\n    }\n    else{\n      res.res=max(l.str[1][0]+l.str[1][1]+r.str[0][0]+r.str[0][1],res.res);\n    }\n    res.str[1][0]=r.str[1][0];\n    res.str[1][1]=r.str[1][1];\n    res.dvd=1;\n  }\n  else if(l.dvd==1&&r.dvd==0){\n    res.str[0][0]=l.str[0][0];\n    res.str[0][1]=l.str[0][1];\n    if(l.str[1][1]!=0 && r.str[0][0]!=0){\n      res.res=max(l.str[1][0]+l.str[1][1],res.res);\n      res.str[1][0]=r.str[0][0];\n      res.str[1][1]=r.str[0][1];\n    }\n    else{\n      res.str[1][0]=l.str[1][0]+r.str[0][0];\n      res.str[1][1]=l.str[1][1]+r.str[0][1];\n    }\n    res.dvd=1;\n  }\n  else if(l.dvd==0&&r.dvd==1){\n    if(l.str[0][1]!=0 && r.str[0][0]!=0){\n      res.res=max(r.str[0][0]+r.str[0][1],res.res);\n      res.str[0][0]=l.str[0][0];\n      res.str[0][1]=l.str[0][1];\n    }\n    else{\n      res.str[0][0]=l.str[0][0]+r.str[0][0];\n      res.str[0][1]=l.str[0][1]+r.str[0][1];\n    }\n    res.str[1][0]=r.str[1][0];\n    res.str[1][1]=r.str[1][1];\n    res.dvd=1;\n  }\n  else{\n    if(l.str[0][1]!=0&&r.str[0][0]!=0){\n      res.str[0][0]=l.str[0][0];\n      res.str[0][1]=l.str[0][1];\n      res.str[1][0]=r.str[0][0];\n      res.str[1][1]=r.str[0][1];\n      res.dvd=1;\n    }\n    else{\n      res.str[0][0]=l.str[0][0]+r.str[0][0];\n      res.str[0][1]=l.str[0][1]+r.str[0][1];\n      res.str[1][0]=0;\n      res.str[1][1]=0;\n      res.dvd=0;\n    }\n  }\n  //stnpr(res,1);\n  return res;\n}\n \nvoid stinit(){\n  int i;\n  for(i=(ssize-2);i>=0;i--){\n    stree[i][0]=merge(stree[i*2+1][0],stree[i*2+2][0]);\n    stree[i][1]=merge(stree[i*2+1][1],stree[i*2+2][1]);\n  }\n  for(i=0;i<2*ssize;i++){\n    fl[i]=0;\n  }\n}\n \nvoid eval(int k){\n  if(fl[k]%2==1){\n    //printf(\"rev %d\\n\",k);\n    stnode c;\n    c=stree[k][0];\n    stree[k][0]=stree[k][1];\n    stree[k][1]=c;\n    if(k<(ssize-1)){\n      fl[k*2+1]++;\n      fl[k*2+2]++;\n    }\n  }\n  fl[k]=0;\n}\n \nvoid revquery(int a,int b,int k,int l,int r){\n  eval(k);\n  if(r<=a || b<=l){return;}\n  if(a<=l && r<=b){\n    fl[k]++;\n    eval(k);\n    return;\n  }\n  else{\n    eval(k*2+1);\n    eval(k*2+2);\n    revquery(a,b,k*2+1,l,(l+r)/2);\n    revquery(a,b,k*2+2,(l+r)/2,r);\n    stree[k][0]=merge(stree[k*2+1][0],stree[k*2+2][0]);\n    stree[k][1]=merge(stree[k*2+1][1],stree[k*2+2][1]);\n    fl[k]=0;\n  }\n}\n \nstnode getquery(int a,int b,int k,int l,int r){\n  //printf(\"call %d : [%d , %d) vs [%d , %d)\\n\",k,l,r,a,b);\n  eval(k);\n  if(r<=a || b<=l){return vd;}\n  if(a<=l && r<=b){\n    //printf(\"%d back:<%d %d %d %d %d : %d>\\n\",k,stree[k][0].str[0][0],stree[k][0].str[0][1],stree[k][0].str[1][0],stree[k][0].str[1][1],stree[k][0].dvd,stree[k][0].res);\n    return stree[k][0];\n  }\n  stnode ld,rd;\n  ld=getquery(a,b,k*2+1,l,(l+r)/2);\n  rd=getquery(a,b,k*2+2,(l+r)/2,r);\n  //printf(\"%d l:<%d %d %d %d %d : %d>\\n\",k,ld.str[0][0],ld.str[0][1],ld.str[1][0],ld.str[1][1],ld.dvd,ld.res);\n  //printf(\"%d r:<%d %d %d %d %d : %d>\\n\",k,rd.str[0][0],rd.str[0][1],rd.str[1][0],rd.str[1][1],rd.dvd,rd.res);\n  return merge(ld,rd);\n}\n \nint main(){\n  vd.str[0][0]=0;vd.str[0][1]=0;\n  vd.str[1][0]=0;vd.str[1][1]=0;\n  vd.res=0;vd.dvd=0;\n  stnode tl,tr;\n  tl.str[0][0]=0;tl.str[0][1]=1;\n  tl.str[1][0]=0;tl.str[1][1]=0;\n  tl.res=0;tl.dvd=0;\n  tr.str[0][0]=1;tr.str[0][1]=0;\n  tr.str[1][0]=0;tr.str[1][1]=0;\n  tr.res=0;tr.dvd=0;\n  int n,q,i;\n  int l,r,ans;\n  stnode res;\n  char s[ssize];\n  scanf(\"%d%d%s\",&n,&q,&s[1]);\n  for(i=0;i<2*ssize;i++){\n    stree[i][0]=vd;\n    stree[i][1]=vd;\n  }\n  for(i=1;i<=n;i++){\n    if(s[i]=='<'){\n      stree[i+(ssize-1)][0]=tl;\n      stree[i+(ssize-1)][1]=tr;\n    }\n    else{\n      stree[i+(ssize-1)][0]=tr;\n      stree[i+(ssize-1)][1]=tl;\n    }\n  }\n  stinit();\n  while(q>0){\n    q--;\n    scanf(\"%d%d\",&l,&r);\n    revquery(l,r+1,0,0,ssize);\n    res=getquery(l,r+1,0,0,ssize);\n    //stnpr(res,1);\n    ans=max(res.str[0][0]+res.str[0][1],res.str[1][0]+res.str[1][1]);\n    ans=max(res.res,ans);\n    printf(\"%d\\n\",ans);\n  }\n  return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "implementation"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1372",
    "index": "A",
    "title": "Omkar and Completion",
    "statement": "You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!\n\nAn array $a$ of length $n$ is called \\textbf{complete} if all elements are positive and don't exceed $1000$, and for all indices $x$,$y$,$z$ ($1 \\leq x,y,z \\leq n$), $a_{x}+a_{y} \\neq a_{z}$ (not necessarily distinct).\n\nYou are given one integer $n$. Please find any \\textbf{complete} array of length $n$. It is guaranteed that under given constraints such array exists.",
    "tutorial": "Notice that since all elements must be positive, $k \\neq 2k$. The most simple construction of this problem is to simply make all elements equal to $1$.",
    "code": "import java.util.*\n \nfun main() {\n    val jin = Scanner(System.`in`)\n    for (c in 1..jin.nextInt()) {\n        val n = jin.nextInt()\n        for (j in 1..n) {\n            print(\"1 \")\n        }\n        println()\n    }\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1372",
    "index": "B",
    "title": "Omkar and Last Class of Math",
    "statement": "In Omkar's last class of math, he learned about the least common multiple, or $LCM$. $LCM(a, b)$ is the smallest positive integer $x$ which is divisible by both $a$ and $b$.\n\nOmkar, having a laudably curious mind, immediately thought of a problem involving the $LCM$ operation: given an integer $n$, find positive integers $a$ and $b$ such that $a + b = n$ and $LCM(a, b)$ is the minimum value possible.\n\nCan you help Omkar solve his ludicrously challenging math problem?",
    "tutorial": "Short Solution: The two integers are $k$ and $n-k$, where $k$ is the largest proper factor of $n$. Proof: Let the two integers be $k$ and $n-k$. Assume WLOG that $k \\leq n-k$. Notice that this implies that $n - k \\geq \\frac n 2$. We first claim that $LCM(k, n-k) = n-k < n$ if $k \\mid n$, and we prove this as follows: if $k \\mid n$, then there exists some integer $m$ such that $m \\cdot k = n$. The integer $n-k$ can then be written as $(m-1) \\cdot k$, which is a multiple of $k$. Thus, $LCM(k, n-k) = n-k$ if $k \\mid n$. We now show that $LCM(k, n-k) \\geq n$ if $k \\nmid n$. We show this by using the fact that $LCM(a, b) = b$ iff $a \\mid b$, so if $k \\nmid n$, $k \\nmid n - k$, and so $LCM(k, n-k) \\neq n-k$. And since $LCM(k, n - k)$ must be a multiple of both $k$ and $n - k$, it follows that $LCM(k, n-k) \\geq 2 \\cdot (n-k) \\geq 2 \\cdot \\frac n 2 = n$. We have now established that to minimize $LCM(k, n-k)$, $k$ must be a factor of $n$. And, since $LCM(k, n-k) = n-k$ when $k$ is a factor of $n$, we need to minimize $n-k$, so we must maximize $k$ by choosing it to be the largest proper factor of $n$ (i. e. the largest factor of $n$ other than $n$). We then simply need to find $k$, the largest proper factor of $n$. If $p$ is the smallest prime dividing $n$, then $k = \\frac n p$, so it suffices to find the smallest prime factor of $n$. We can do this by simply checking all values of $p$ such that $2 \\leq p \\leq \\sqrt n$. If $n$ is not prime, then it must have a prime factor not exceeding $\\sqrt{n}$. Furthermore, if we do not find a factor of $n$ between $2$ and $\\sqrt n$, then $n$ must be prime so we simply get $p = n$ and $k = \\frac n p = 1$. We're given that $n \\leq 10^9$, so $\\sqrt n \\leq 10^{\\frac 9 2} < 10^5$. $t \\leq 10$, meaning that we will check less than $10^6$ numbers, which runs well under the time limit.",
    "code": "fun main() {\n    for (c in 1..readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        var p = 0\n        for (m in 2..100000) {\n            if (n % m == 0) {\n                p = m\n                break\n            }\n        }\n        if (p == 0) {\n            p = n\n        }\n        println(\"${n / p} ${n - (n / p)}\")\n    }\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1372",
    "index": "C",
    "title": "Omkar and Baseball",
    "statement": "Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up!\n\nDefine a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $[1,2,3]$ can yield $[3,1,2]$ but it cannot yield $[3,2,1]$ since the $2$ is in the same position.\n\nGiven a permutation of $n$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $10^{18}$.\n\nAn array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "You need at most $2$ special exchanges to sort the permutation. Obviously, $0$ special exchanges are needed if the array is already sorted. Let's look into cases in which you need $1$ special exchange to sort the array. Refer to i as a matching index if $a_i = i$. If there are no matching indices, then you can just use one special exchange to sort the entire thing. Otherwise, you can use the location of matching indices to determine whether you need more than $1$ special exchange. If all matching indices are located in some prefix of the permutation, you can sort the permutation with one special exchange. The same is true for a suffix. In other words, if you can choose a subarray in the permutation such that all elements contained in the subarray are NOT matching and the elements outside of this subarray are matching, then one special exchange is needed to sort the array. Otherwise, you need $2$ special exchanges to sort the permutation. Let's prove why you do not need more than $2$ special exchanges. You can quickly check that you need at most $2$ special exchanges for all permutations of length $\\leq 3$. For permutations of length $\\geq 4$, I claim that we can perform $2$ special exchanges on the whole array; to show this it suffices to construct a permutation $p$ that has no matching indices with either the given permutation or the identity permutation $1, 2, \\ldots, n$. We can do this as follows: For simplicity, assume that $n$ is even. We will assign the numbers $\\frac n 2 + 1, \\frac n 2 + 2, \\ldots, n$ to the first $\\frac n 2$ positions of our permutation $p$ and the numbers $1, 2, \\ldots, \\frac n 2$ to the last $\\frac n 2$ positions of $p$. This ensures that $p$ has no matching indices with the identity permutation. Then, for all integers $b$ such that their position $i$ in $a$ (i. e. the $j$ such that $a_j = b$) is in the appropriate half of $p$, assign $p_i = b$; assign other $b$ to arbitrary positions in the appropriate half of $p$. Finally, cyclically rotate each half of $p$ - this ensures that $p$ has no matching indices with $a$. As an example, let's take $a = [3, 6, 2, 4, 5, 1]$. You can quickly check that this cannot be done in less than $2$ special exchanges. The construction of $p$ goes as follows: First, we move all numbers to the proper half of $p$, so that $p = [4, 5, 6, 1, 2, 3]$. Observing that $a_2 = 6$ and $a_6 = 1$, we set $p_2 = 6$ and $p_6 = 1$ then replace the remaining elements arbitrarily into the correct half, so we can get, for example, $p = [4, 6, 5, 2, 3, 1]$. Finally, we cyclically rotate each half of $p$, obtaining $p = [5, 4, 6, 1, 2, 3]$, which has no matching indexes with either $a = [3, 6, 2, 4, 5, 1]$ or $[1, 2, 3, 4, 5, 6]$. This can be extended to odd $n$ by first choosing some element other than $1$ and $a_1$ to be $p_1$ (this works for $n \\geq 3$ and we must have $n \\geq 5$ anyway in this case), and then running the same algorithm on the rest of $p$.",
    "code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\n \nfun main() {\n    val jin = BufferedReader(InputStreamReader(System.`in`))\n    for (c in 1..jin.readLine().toInt()) {\n        val n = jin.readLine().toInt()\n        val scores = jin.readLine().split(\" \").map { it.toInt() - 1 }\n        if ((1 until n).all { scores[it - 1] < scores[it] }) {\n            println(0)\n        } else {\n            var stage = 0\n            var answer = 1\n            for (j in 0 until n) {\n                if (scores[j] == j) {\n                    if (stage == 1) {\n                        stage = 2\n                    }\n                } else {\n                    if (stage == 0) {\n                        stage = 1\n                    } else if (stage == 2) {\n                        answer = 2\n                        break\n                    }\n                }\n            }\n            println(answer)\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1372",
    "index": "D",
    "title": "Omkar and Circle",
    "statement": "Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!\n\nYou are given $n$ nonnegative integers $a_1, a_2, \\dots, a_n$ arranged in a circle, where $n$ must be odd (ie. $n-1$ is divisible by $2$). Formally, for all $i$ such that $2 \\leq i \\leq n$, the elements $a_{i - 1}$ and $a_i$ are considered to be adjacent, and $a_n$ and $a_1$ are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value.\n\nHelp Danny find the maximum possible circular value after some sequences of operations.",
    "tutorial": "First note that any possible circular value consists of the sum of some $(n+1)/2$ elements. Now let's think about how these $(n+1)/2$ values would look like in the circle. Let's consider any one move on index $i$. $a_i$ will be replaced with the sum of $a_{i-1}$ and $a_{i+1}$ (wrap around to index $1$ or $n$ if needed). Then let's consider making a move on $i+2$, since it will be adjacent to $i$ after the first move. Then its value will become $a_{i-1}+a_{i+1}+a_{i+3}$. This implies that alternating values play a role in the construction of the $(n+1)/2$ values contained in the final circular value. Now let's consider the final move when there's $3$ elements left in the circle. This is the only move that takes the sum of two adjacent elements in the initial circle. With this observation, we can achieve our final construction as follows: Choose any $(n+1)/2$ elements in the initial circle such that exactly one pair of chosen numbers are adjacent to each other. The answer will be the maximum of the circular value over all possible constructions. While there are ways involving complicated prefix sums/segment trees, the cleanest implementation is as follows: create an array whose values consists of $[a_1, a_3, ..., a_n, a_2, a_4, ..., a_{n-1}]$. Append this new array to itself to account for the circular structure. Now all you simply have to do is to find the maximum sum over all subarrays of length $(n+1)/2$. This can be done with sliding window in $O(n)$ time.",
    "code": "import kotlin.math.max\n \nfun main() {\n    val n = readLine()!!.toInt()\n    val m = (n + 1) / 2\n    val array = readLine()!!.split(\" \").map { it.toLong() }\n    var curr = 0L\n    for (j in 0 until m) {\n        curr += array[2 * j]\n    }\n    var answer = curr\n    for (j in 0..n - 2) {\n        curr -= array[(2 * j) % n]\n        curr += array[(2 * (j + m)) % n]\n        answer = max(answer, curr)\n    }\n    println(answer)\n}",
    "tags": [
      "brute force",
      "dp",
      "games",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1372",
    "index": "E",
    "title": "Omkar and Last Floor",
    "statement": "Omkar is building a house. He wants to decide how to make the floor plan for the last floor.\n\nOmkar's floor starts out as $n$ rows of $m$ zeros ($1 \\le n,m \\le 100$). Every row is divided into intervals such that every $0$ in the row is in exactly $1$ interval. For every interval for every row, Omkar can change exactly one of the $0$s contained in that interval to a $1$. Omkar defines the quality of a floor as the sum of the squares of the sums of the values in each column, i. e. if the sum of the values in the $i$-th column is $q_i$, then the quality of the floor is $\\sum_{i = 1}^m q_i^2$.\n\nHelp Omkar find the maximum quality that the floor can have.",
    "tutorial": "Let $dp_{l,r}$ be the answer for the columns from $l$ to $r$. To solve $dp_{l,r}$, it is optimal to always fill some column within $l$ to $r$ to the max. Let's call this column $k$. The transition is thus $dp_{l,k-1} + ($ number of intervals that are fully within $l$ and $r$ and include $k)^2 + dp_{k+1,r}$. For every $dp_{l,r}$ loop through all possible columns to be $k$ and take the max. The answer is $dp_{1,m}$. The efficiency is $O(N \\cdot M^3)$. There are $M^2$ dp states. For every state, you transition based on $M$ cases of $k$, and it takes $O(N)$ to determine how much the max column contributes. Proof: Consider an optimal arrangement and the column with the most 1's in that arrangement. If there is an interval intersecting that column whose 1 isn't in that column, then moving the 1 to that column would not decrease (and possibly would increase) the quality of that arrangement. Thus, it's optimal for the column with the most 1s to have all the possible 1s that it can have.",
    "code": "import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport kotlin.math.max\n \nfun main() {\n    val jin = BufferedReader(InputStreamReader(System.`in`))\n    val (n, m) = jin.readLine().split(\" \").map { it.toInt() }\n    val left = Array(n + 1) { IntArray(m + 1) }\n    val right = Array(n + 1) { IntArray(m + 1) }\n    for (y in 1..n) {\n        val k = jin.readLine().toInt()\n        for (j in 1..k) {\n            val (l, r) = jin.readLine().split(\" \").map { it.toInt() }\n            for (x in l..r) {\n                left[y][x] = l\n                right[y][x] = r\n            }\n        }\n    }\n    val dp = Array(m + 2) { IntArray(m + 2) }\n    for (l in m downTo 1) {\n        for (r in l..m) {\n            for (x in l..r) {\n                var amt = 0\n                for (y in 1..n) {\n                    if (left[y][x] >= l && right[y][x] <= r) {\n                        amt++\n                    }\n                }\n                dp[l][r] = max(dp[l][r], dp[l][x - 1] + (amt * amt) + dp[x + 1][r])\n            }\n        }\n    }\n    println(dp[1][m])\n}",
    "tags": [
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1372",
    "index": "F",
    "title": "Omkar and Modes",
    "statement": "Ray lost his array and needs to find it by asking Omkar. Omkar is willing to disclose that the array has the following qualities:\n\n- The array has $n$ ($1 \\le n \\le 2 \\cdot 10^5$) elements.\n- Every element in the array $a_i$ is an integer in the range $1 \\le a_i \\le 10^9.$\n- The array is sorted in nondecreasing order.\n\nRay is allowed to send Omkar a series of queries. A query consists of two integers, $l$ and $r$ such that $1 \\le l \\le r \\le n$. Omkar will respond with two integers, $x$ and $f$. $x$ is the mode of the subarray from index $l$ to index $r$ inclusive. The mode of an array is defined by the number that appears the most frequently. If there are multiple numbers that appear the most number of times, the smallest such number is considered to be the mode. $f$ is the amount of times that $x$ appears in the queried subarray.\n\nThe array has $k$ ($1 \\le k \\le \\min(25000,n)$) distinct elements. However, due to Ray's sins, Omkar will not tell Ray what $k$ is. Ray is allowed to send at most $4k$ queries.\n\nHelp Ray find his lost array.",
    "tutorial": "For both solutions, we must first make the critical observation that because the array is sorted, all occurrences of a value $x$ occur as a single contiguous block. Solution 1 We will define a recursive function $determine(l, r)$ which will use queries to determine the array. We will also store an auxiliary list of previously returned query values $(x, f)$ - not the queries themselves, but only the values returned, so that we know that if $(x, f)$ is in the list then some previous query revealed that there were $f$ instances of $x$ in some query, and that we haven't already determined exactly where in the array those $f$ instances of $x$ are. The execution of $determine(l, r)$ will proceed as follows: first, query the interval $[l, r]$, and let the result be $(x_1, f_1)$. If there exists some previous query result $(x_1, f_2)$ in our auxiliary list, then we will guarantee by details yet to be explained of $determine(l, r)$ that the interval that produced that result contained $[l, r]$ and that no part of those $f_2$ occurrences of $x_1$ occurred to the left of $[l, r]$. This allows us to exactly determine the location of those $f_2$ occurrences of $x_1$. We mark these occurrences in our answer, and then remove $(x_1, f_2)$ from our auxiliary list and do not add $(x_1, f_1)$. If $[l, r]$ is not entirely composed of occurrences of $x_1$, then the remaineder of the interval must be $[l, r']$ for some $r'$, and in that case we then call $determine(l, r')$. If there does not exist some previous query result $(x_1, f_2)$ in our auxiliary list, then we add $(x_1, f_1)$ to the list and do as follows: while the exact locations of those $f_1$ occurrences of $x_1$ have not been determined, call $determine(l', l' + f_1 - 1)$, where $l'$ is the leftmost index in $[l, r]$ which has not yet been determined. Once those locations have been determined, call $determine(l', r)$. To determine the entire array we simply call $determine(1, n)$. It is clear that this will correctly determine the array. We can see that it uses at most $4k$ queries as follows: for each block of integers of the same value represented by a query result $(x, f)$ that we add to our auxiliary list, we use $2$ queries to determine the exact location of those integers: one when added $(x, f)$ to the list, and one when removing $(x, f)$ from the list. This does not guarantee that the algorithm uses $2k$ queries because some calls of $determine$ can split a block of integers of the same value into two blocks. However, we can show that any blocks formed by splitting a single block into two cannot be further split as they occur either at the beginning or end of a queried interval (the full proof is left as an exercise to the reader), so each distinct value in the array will produce at most $2$ blocks, each of which will be determined in $2$ queries, meaning that the algorithm uses at most $4k$ queries. Side note: you can in fact further show that the algorithm always uses at most $4k - 4$ queries and that there exists an array for all $k \\geq 2$ which forces the algorithm to use $4k - 4$ queries. Solution 2 Again, we will define a recursive function $determine(l, r)$, but this time we will only additionally maintain the currently known values in the answer. The execution of $determine(l, r)$ will proceed as follows: first, query the interval $[l, r]$ and let the result be $(x, f)$. Then, find the largest integer $k$ such that $2^k \\leq f$ and then for all $j$ in $[l, r]$ that are multiples of $2^k$, determine the value located at index $j$, either by querying $[j, j]$ or by using already known values. By the definition of $k$, there will be either one or two such indexes $j$ such that the values at those indexes are equal to $x$. If there is only one such index, let this index be $j_1$. Make two queries $[j_1 - 2^k + 1, j_1]$ and $[j_1, j_1 + 2^k - 1]$ and let the results of these queries be $(x_1, f_1)$ and $(x_2, f_2)$ respectively. We can show that at least one of $x_1$ and $x_2$ must be equal to $x$. If $x_1 = x$, then we see that the $f$ occurrences of $x$ must be precisely the interval $[j_1 - f_1 + 1, j_1 - f_1 + f]$. If $x_2 = x$, then we see that the $f$ occurrences of $x$ must be precisely the interval $[j_1 + f_2 - f, j_1 + f_2 - 1]$. If there are two such indexes, let these indexes be $j_1$ and $j_2$ so that $j_1 < j_2$. Note that it must be true that $j_1 + 2^k = j_2$. Make a single query $[j_1 - 2^k + 1, j_2]$ and let the result be $(x_1, f_1)$. We can show that $x_1$ must be equal to $x$, so we can then conclude that the $f$ occurrences fo $x$ must be precisely the interval $[j_2 - f_1 + 1, j_2 - f_1 + f]$. After the interval containing the $f$ occurrences of $x$ has been determined, mark these occurrences in our answer and then call $determine$ on the remaining not-fully-determined interval to the left if it exists and the remaining not-fully-determined interval to the right if it exists. To determine the entire array we simply call $determine(1, n)$. It is clear that this will correctly determine the array. We can see that it uses at most $4k$ queries as follows: Each call to $determine$ finds all occurrences of a distinct value $x$. We will refer to the queries of single indexes $j$ that were multiples of some $2^k$ as $j$-queries. For each $x$, we perform the following queries other than $j$-queries: the first query in $determine$, and then either two additional queries if only one $j$-query was found to equal $x$, or a single additional query if two $j$-queries were found to equal $x$. This means that if we group each $j$-query with the value $x$ that it equaled, then we will have performed exactly $4$ queries for each $x$, and so the algorithm must therefore use exactly $4k$ queries.",
    "code": "import kotlin.math.max\nimport kotlin.math.min\n \nfun main() {\n    val n = readLine()!!.toInt()\n    val answer = IntArray(n + 1)\n    val occurrences = mutableMapOf<Int, MutableList<Int>>()\n    fun query(l: Int, r: Int): Pair<Int, Int> {\n        println(\"? $l $r\")\n        val line = readLine()!!.split(\" \")\n        return Pair(line[0].toInt(), line[1].toInt())\n    }\n    fun calc(l: Int, r: Int, ePrev: Int) {\n        if (l > r) {\n            return\n        }\n        var q = query(l, r)\n        val x = q.first\n        val f = q.second\n        var e = ePrev\n        while (1 shl e > f) {\n            e--\n        }\n        if (e < ePrev) {\n            var j = l - (l % (1 shl e))\n            if (j < l) {\n                j += 1 shl e\n            }\n            while (j <= r) {\n                if (j % (1 shl ePrev) != 0) {\n                    q = query(j, j)\n                    occurrences.computeIfAbsent(q.first) { mutableListOf() }.add(j)\n                }\n                j += 1 shl e\n            }\n        }\n        val ixs = occurrences[x]!!\n        var leftBound = 0\n        if (ixs.size == 1) {\n            q = query(max(l, ixs[0] - (1 shl e) + 1), ixs[0])\n            if (q.first == x) {\n                leftBound = ixs[0] - q.second + 1\n            } else {\n                q = query(ixs[0], min(r, ixs[0] + (1 shl e) - 1))\n                leftBound = ixs[0] + q.second - f\n            }\n        } else {\n            q = query(max(l, ixs.min()!! - (1 shl e) + 1), ixs.max()!!)\n            leftBound = ixs.max()!! - q.second + 1\n        }\n        for (j in leftBound until leftBound + f) {\n            answer[j] = x\n        }\n        calc(l, leftBound - 1, e)\n        calc(leftBound + f, r, e)\n    }\n    calc(1, n, 20)\n    println('!' + answer.joinToString(\" \").substring(1))\n}",
    "tags": [
      "binary search",
      "divide and conquer",
      "interactive"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1373",
    "index": "A",
    "title": "Donut Shops",
    "statement": "There are two rival donut shops.\n\nThe first shop sells donuts at retail: each donut costs $a$ dollars.\n\nThe second shop sells donuts only in bulk: box of $b$ donuts costs $c$ dollars. So if you want to buy $x$ donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to $x$.\n\nYou want to determine two \\textbf{positive integer} values:\n\n- how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop?\n- how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop?\n\nIf any of these values doesn't exist then that value should be equal to $-1$. If there are multiple possible answers, then print any of them.\n\n\\textbf{The printed values should be less or equal to $10^9$. It can be shown that under the given constraints such values always exist if any values exist at all.}",
    "tutorial": "At first notice that if there exists a value for the second shop, then the value divisible by $b$ also exists. For any $x$ you can round it up to the nearest multiple of $b$. That won't change the price for the second shop and only increase the price for the first shop. You can also guess that if there exists a value for the first shop, then the value with $1$ modulo $b$ also exists (exactly $1$ donut on top of some number of full boxes). Following the same logic - the second shop needs an entire new box and the first shop needs only an extra donut. So let's take a look at the smallest values of two kinds: $x = b$: this value is valid for the second shop if one box is cheaper than $b$ donuts in the first shop. Otherwise, no matter how many boxes will you take, they will never be cheaper than the corresponding number of donuts. $x = 1$: this value is valid for the first shop if one donut is cheaper than one box in the second shop. Apply the same idea - otherwise no value for the first shop is valid. Overall complexity: $O(1)$ per testcase.",
    "code": "for tc in range(int(input())):\n\ta, b, c = map(int, input().split())\n\tprint(1 if a < c else -1, end=\" \")\n\tprint(b if c < a * b else -1)",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1373",
    "index": "B",
    "title": "01 Game",
    "statement": "Alica and Bob are playing a game.\n\nInitially they have a binary string $s$ consisting of only characters 0 and 1.\n\nAlice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two \\textbf{different adjacent} characters of string $s$ and delete them. For example, if $s = 1011001$ then the following moves are possible:\n\n- delete $s_1$ and $s_2$: $\\textbf{10}11001 \\rightarrow 11001$;\n- delete $s_2$ and $s_3$: $1\\textbf{01}1001 \\rightarrow 11001$;\n- delete $s_4$ and $s_5$: $101\\textbf{10}01 \\rightarrow 10101$;\n- delete $s_6$ and $s_7$: $10110\\textbf{01} \\rightarrow 10110$.\n\nIf a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.",
    "tutorial": "If there is at least one character 0 and at least one character 1, then current player can always make a move. After the move the number of character 0 decreases by one, and the number of character 1 decreases by one too. So the number of moves is always $min(c0, c1)$, where $c0$ is the number of characters 0 in string $s$, and $c1$ is the number of characters 1 in string $s$. So if $min(c0, c1)$ is odd then Alice wins, otherwise Bob wins.",
    "code": "for _ in range(int(input())):\n    s = input()\n    print('DA' if min(s.count('0'), s.count('1')) % 2 == 1 else 'NET')",
    "tags": [
      "games"
    ],
    "rating": 900
  },
  {
    "contest_id": "1373",
    "index": "C",
    "title": "Pluses and Minuses",
    "statement": "You are given a string $s$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode:\n\n\\begin{verbatim}\nres = 0\nfor init = 0 to inf\ncur = init\nok = true\nfor i = 1 to |s|\nres = res + 1\nif s[i] == '+'\ncur = cur + 1\nelse\ncur = cur - 1\nif cur < 0\nok = false\nbreak\nif ok\nbreak\n\n\\end{verbatim}\n\nNote that the $inf$ denotes infinity, and the characters of the string are numbered from $1$ to $|s|$.\n\nYou have to calculate the value of the $res$ after the process ends.",
    "tutorial": "Let's replace all + with 1, and all - with -1. After that let's create a preffix-sum array $p$ ($p_i = \\sum\\limits_{j=1}^{i} s_j$). Also lets create array $f$ such that $f_i$ is equal minimum index $j$ such that $p_j = -i$ (if there is no such index $p_i = -1$). Let's consider the first iteration of loop $for ~ init ~ = ~ 0 ~ to ~ inf$. If $f_1 = -1$ then process ends and $res = |s|$. Otherwise the condition $if ~ cur ~ < ~ 0$ fulfilled then the value of $i$ will be equal to $f_1$. So, the value of $res$ is equal to $f_1$ after first iteration. Now, let's consider the second iteration of loop $for ~ init ~ = ~ 0 ~ to ~ inf$. If $f_2 = -1$ then process ends and $res = f_1 + |s|$. Otherwise the condition $if ~ cur ~ < ~ 0$ fulfilled then the value of $i$ will be equal to $f_2$. So, the value of $res$ is equal to $f_1 + f_2$ after second iteration. In this way we can calculate the value of $res$ after the process ends.",
    "code": "for _ in range(int(input())):\n    s = input()\n    cur, mn, res = 0, 0, len(s)\n    for i in range(len(s)):\n        cur += 1 if s[i] == '+' else -1\n        if cur < mn:\n            mn = cur\n            res += i + 1\n        \n    print(res)",
    "tags": [
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1373",
    "index": "D",
    "title": "Maximum Sum on Even Positions",
    "statement": "You are given an array $a$ consisting of $n$ integers. Indices of the array start from zero (i. e. the first element is $a_0$, the second one is $a_1$, and so on).\n\nYou can reverse \\textbf{at most one} subarray (continuous subsegment) of this array. Recall that the subarray of $a$ with borders $l$ and $r$ is $a[l; r] = a_l, a_{l + 1}, \\dots, a_{r}$.\n\nYour task is to reverse such a subarray that the sum of elements on \\textbf{even} positions of the resulting array is \\textbf{maximized} (i. e. the sum of elements $a_0, a_2, \\dots, a_{2k}$ for integer $k = \\lfloor\\frac{n-1}{2}\\rfloor$ should be maximum possible).\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, we can notice that the reverse of of odd length subarray does nothing because it doesn't change parities of indices of affected elements. Secondly, we can consider the reverse of the subarray of length $2x$ as $x$ reverses of subarrays of length $2$ (i.e. it doesn't matter for us how exactly the subarray will be reversed, we can only consider changing parities). Now, there are two ways: the first one is smart and the second one is dynamic programming. Consider the first way. Calculate the initial sum of elements on even positions $sum$. Then let's create two arrays $v_1$ and $v_2$. There $v_1[i]$ is $a[2i+1] - a[2i]$ for all $i$ from $0$ to $\\lfloor\\frac{n}{2}\\rfloor - 1$ and $v_2[i]$ is $a[2i] - a[2i+1]$ for all $i$ from $0$ to $\\lfloor\\frac{n}{2}\\rfloor - 1$. Elements of the first array deonte the profit if we reverse the subarray tarting from the even position, and elemnts of the second array denote the profit if we reverse the subarray starting from the odd position. Now we need to find the subarray with the maximum sum in both arrays (this will maximize overall profit) and add this value to $sum$ to get the answer. This problem can be solved easily: consider the sum of the subarray $[l; r]$ as the difference of two prefix sums $pref_{r} - pref_{l-1}$. To maximize it, consider all right borders and minimize the value $pref_{l-1}$. Iterate over all positions of the array, maintaining the current prefix sum $csum$ and the minimum prefix sum we meet $msum$. Update $csum := csum + a_i$, then update $msum := min(msum, csum)$ and then update the answer with the value $csum - msum$. And the second way is author's solution and it is dynamic programming. This idea can be transformed to solve such problems in which you need to apply some function to some small number of subsegments (of course, under some constraints on functions). State of our dynamic programming is $dp_{i, j}$ where $i \\in [0; n]$ and $j \\in [0; 2]$. $dp_{i, 0}$ denotes the answer on the prefix of length $i$ if we didn't start reversing the subarray, $dp_{i, 1}$ denotes the answer if we started reversing the subarray but didn't end it and $dp_{i, 2}$ denotes the answer if we ended reversing the subarray. Transitions are pretty easy: $dp_{i + 1, 0} = max(dp_{i + 1, 0}, dp_{i, 0} + [i \\% 2 == 0? a_i : 0])$; $dp_{i + 2, 1} = max(dp_{i + 2, 1}, max(dp_{i, 0}, dp_{i, 1}) + [i \\% 2 == 0 ? a_{i + 1} : a_i])$; $dp_{i + 1, 2} = max(dp_{i + 1, 2}, max(dp_{i, 0}, dp_{i, 1}, dp_{i, 2}) + [i \\% 2 == 0? a_i : 0])$. The value $x ? y : z$ is just a ternary if statement. If $x$ is true then return $y$ otherwise return $z$. The answer is $max(dp_{n, 0}, dp_{n, 1}, dp_{n, 2})$. Time complexity with both approaches is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tvector<vector<long long>> dp(n + 1, vector<long long>(3));\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tdp[i + 1][0] = max(dp[i + 1][0], dp[i][0] + (i & 1 ? 0 : a[i]));\n\t\t\tif (i + 2 <= n) dp[i + 2][1] = max(dp[i + 2][1], max(dp[i][0], dp[i][1]) + (i & 1 ? a[i] : a[i + 1]));\n\t\t\tdp[i + 1][2] = max(dp[i + 1][2], max({dp[i][0], dp[i][1], dp[i][2]}) + (i & 1 ? 0 : a[i]));\n\t\t}\n\t\tcout << max({dp[n][0], dp[n][1], dp[n][2]}) << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "divide and conquer",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1373",
    "index": "E",
    "title": "Sum of Digits",
    "statement": "Let $f(x)$ be the sum of digits of a decimal number $x$.\n\nFind the smallest non-negative integer $x$ such that $f(x) + f(x + 1) + \\dots + f(x + k) = n$.",
    "tutorial": "There are many ways to solve this problem (including precalculating all answers), but the model solution is based on the following: In most cases, $f(x + 1) = f(x) + 1$. It is not true only when the last digit of $x$ is $9$ (and if we know the number of $9$-digits at the end of $x$, we can easily derive the formula for $f(x + 1)$). And since $k \\le 9$, there will be at most one number with last digit equal to $9$ in $[x, x + 1, \\dots, x + k]$. Let's iterate on the last digit of $x$ and the number of $9$-digits before it. Suppose the fixed $x$ has no other digits other than the last one and several $9$-digits before it. Let's calculate $s = f(x) + f(x + 1) + f(x + 2) \\dots + f(x + k)$. Here goes the trick. If we prepend $x$ with several digits such that the last of them is not $9$, and the sum of those digits is $d$, then $f(x) + f(x + 1) + f(x + 2) \\dots + f(x + k) = s + d(k + 1)$. So we can easily derive the value of $d$ we need and construct the smallest number with sum of digits equal to $d$ (don't forget that the last digit should not be $9$).",
    "code": "def get(s):\n\treturn str(s % 9) + '9' * (s // 9)\n\nfor tc in range(int(input())):\n\tn, k = map(int, input().split())\n\tk += 1\n\tbst = 10**100\n\tfor d in range(10):\n\t\tends = 0\n\t\tfor i in range(k):\n\t\t\tends += (d + i) % 10\n\t\tif ends > n:\n\t\t\tcontinue\n\t\tif d + k > 10:\n\t\t\tfor cnt in range(12):\n\t\t\t\ts = 9 * cnt * (10 - d)\n\t\t\t\tif s > n - ends:\n\t\t\t\t\tbreak\n\t\t\t\tfor nd in range(9):\n\t\t\t\t\tns = s + (10 - d) * nd + (k - (10 - d)) * (nd + 1)\n\t\t\t\t\tif ns > n - ends:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif (n - ends - ns) % k == 0:\n\t\t\t\t\t\tbst = min(bst, int(get((n - ends - ns) // k) + str(nd) + '9' * cnt + str(d)))\n\t\telif (n - ends) % k == 0:\n\t\t\tbst = min(bst, int(get((n - ends) // k) + str(d)))\n\tprint(-1 if bst == 10**100 else bst)",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1373",
    "index": "F",
    "title": "Network Coverage",
    "statement": "The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and $n$ cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the $i$-th city contains $a_i$ households that require a connection.\n\nThe government designed a plan to build $n$ network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the $i$-th network station will provide service only for the $i$-th and the $(i + 1)$-th city (the $n$-th station is connected to the $n$-th and the $1$-st city).\n\nAll network stations have capacities: the $i$-th station can provide the connection to at most $b_i$ households.\n\nNow the government asks you to check can the designed stations meet the needs of all cities or not — that is, is it possible to assign each household a network station so that each network station $i$ provides the connection to at most $b_i$ households.",
    "tutorial": "There are plenty of different solutions to this problem. Here is one that doesn't use Hall's theorem. Let's look at pair $(a_i, b_i)$ as fuction $f_i(in) = out$: how many connections $out$ will be left for the $(i + 1)$-th city if we take $in$ connections from the $(i - 1)$-th station. This function has the following structure: there is a minimum required $in$ (let's name it $minx_i$) to meet the needs of the $i$-th city and with $minx_i$ borrowed connections there will be $f_i(minx_i) = mink_i$ free connections to the $(i + 1)$-th city. Increasing $minx_i$ by some $x$ we can get $f_i(minx_i + x) = mink_i + x$ free connections, but there is upper bound to number of free connections $maxk_i$. In other words, the function $f_i(minx_i + x) = \\min(mink_i + x, maxk_i)$ where $x \\ge 0$. For example, let's calculate the corresponding coefficients for the $i$-th function: if $a_i \\le b_i$ then $minx_i = 0$, $mink_i = b_i - a_i$ and $maxk_i = b_i$; if $a_i > b_i$ then $minx_i = a_i - b_i$, $mink_i = 0$ and $maxk_i = b_i$. Why did we define such functions? If we can calculate result function $f_{[1,n]}(in) = f_n(f_{n - 1}(\\dots f_2(f_1(in))\\dots))$ then we can check the possibility of meeting all needs by checking that this fuction exists and $minx_{[1,n]} \\le mink_{[1,n]}$, i. e. the minimum free $mink_{[1,n]}$ can be used as borrowed $minx_{[1,n]}$. Fortunately, it turns out that the superposition $f_{i+1}(f_i(in))$ is either don't exists (if, for example, $maxk_i < minx_{i + 1}$) or it has the same structure as any function $f_i$. So we can calculate $f_{[1,n]}$ in one pass and find the answer. We will skip the detailed formulas to calculate $f_{i+1}(f_i(in))$: you can either find them by yourself or look at function $merge()$ in author's solution. The resulting complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\ntypedef long long li;\nconst int N = 1000 * 1000 + 13;\n\nint n;\nint a[N], b[N];\n \nvoid solve() {\n\tscanf(\"%d\", &n);\n\tfor (int i = 0; i < n; ++i) scanf(\"%d\", &a[i]);\n\tfor (int i = 0; i < n; ++i) scanf(\"%d\", &b[i]);\n\t\n\tli need = 0, add = 0, extra = 2e9;\n\tfor (int i = n - 1; i >= 0; --i) {\n\t\tif (b[i] < need) {\n\t\t\tputs(\"NO\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tli val = b[i] - a[i];\n\t\tli to_add = min(extra, max(0LL, val - need));\n\t\tadd += to_add;\n\t\textra = min(extra - to_add, b[i] - need - to_add);\n\t\tneed = max(0LL, need - val);\n\t}\n\t\n\tputs(add >= need ? \"YES\" : \"NO\");\n}\n \nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor (int i = 0; i < t; ++i)\n\t\tsolve();\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1373",
    "index": "G",
    "title": "Pawns",
    "statement": "You are given a chessboard consisting of $n$ rows and $n$ columns. Rows are numbered from bottom to top from $1$ to $n$. Columns are numbered from left to right from $1$ to $n$. The cell at the intersection of the $x$-th column and the $y$-th row is denoted as $(x, y)$. Furthermore, the $k$-th column is a special column.\n\nInitially, the board is empty. There are $m$ changes to the board. During the $i$-th change one pawn is added or removed from the board. The current board is good if we can move all pawns to the special column by the followings rules:\n\n- Pawn in the cell $(x, y)$ can be moved to the cell $(x, y + 1)$, $(x - 1, y + 1)$ or $(x + 1, y + 1)$;\n- You can make as many such moves as you like;\n- Pawns can not be moved outside the chessboard;\n- Each cell can not contain more than one pawn.\n\nThe current board may not always be good. To fix it, you can add new rows to the board. New rows are added at the top, i. e. they will have numbers $n+1, n+2, n+3, \\dots$.\n\nAfter each of $m$ changes, print one integer — the minimum number of rows which you have to add to make the board good.",
    "tutorial": "For each pawn with initial position $(x, y)$ there exists a minimum index of row $i$ such that the pawn can reach the cell $(k, i)$, but cannot reach the cell $(k, i - 1)$. It's easy to see that $i = |k - x| + y$. In the resulting configuration, this pawn can occupy the cell $(k, i)$, $(k, i + 1)$, $(k, i + 2)$ or any other cell $(k, j)$ having $j \\ge i$. Suppose the board consists of $r$ rows. For each row, the number of rows above it should be not less than the number of pawns that occupy the cells above it (that is, having $i$ greater than the index of that row) - because, if this condition is not fulfilled, we can't assign each pawn a unique cell. If we denote the number of pawns that should go strictly above the $j$-th row as $f(j)$, then for every row, the condition $f(j) \\le r - j$ must be met. To prove that this condition is sufficient, we may, for example, use Hall's theorem. Okay, now what about finding the minimum $r$ satisfying it? Let's initially set $r$ to $n$, and for each row maintain the value of $j + f(j) - n$ - the minimum number of rows we have to add to our board so that the condition for the row $j$ is met (we also have to maintain this value for $n - 1$ auxiliary rows from $n + 1$ to $2n - 1$, since some pawns cannot fit in the initial board at all). Finding the minimum value we have to add to $r$ equals finding the maximum of all these values on some prefix (we don't need to look at the values on some rows with large indices, if there are no pawns after them, so we need a maximum query on the segment $[1, \\max_i]$, where $\\max_i$ is the maximum index $i$ among all pawns); and when a pawn is added or removed, we should add $+1$ or $-1$ to all values on some suffix. A segment tree with lazy propagation will do the trick, solving the problem for us in $O(m \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(2e5) + 9;\n\nint n, k;\nint m;\nint t[8 * N];\nint add[8 * N];\nint cnt[2 * N];\n\nvoid push(int v, int l, int r) {\n    if (r - l != 1 && add[v] != 0) {\n        t[v * 2 + 1] += add[v];\n        t[v * 2 + 2] += add[v];\n        add[v * 2 + 1] += add[v];\n        add[v * 2 + 2] += add[v];\n        add[v] = 0;\n    }\n}\n\nvoid upd(int v, int l, int r, int L, int R, int x) {\n    if (L >= R) return;\n    if(l == L && r == R) {\n        t[v] += x;\n        add[v] += x;\n        return;\n    } \n    \n    push(v, l, r);\n    int mid = (l + r) / 2;\n    upd(v * 2 + 1, l, mid, L, min(R, mid), x);\n    upd(v * 2 + 2, mid, r, max(L, mid), R, x);\n    t[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\nvoid upd(int l, int r, int x) {\n    upd(0, 0, n + n, l, r, x);\n}\n\nint get(int v, int l, int r, int L, int R) {\n    if (L >= R) return 0;\n    if (l == L && r == R) return t[v];\n    \n    push(v, l, r);\n    int mid = (l + r) >> 1;\n    return max(get(v * 2 + 1, l, mid, L, min(R, mid))\n    \t\t , get(v * 2 + 2, mid, r, max(L, mid), R));\n}\n\nint get(int l, int r) {\n    return get(0, 0, n + n, l, r);\n}\n\nint getAns(set <int> &smx) {\n    if (smx.empty()) return 0;\n    return max(0, get(0, *smx.rbegin() + 1) - n);\n}\n\nvoid build(int v, int l, int r) {\n    if (r - l == 1) {\n        t[v] = l;\n        return;\n    }\n    \n    int mid = (l + r) >> 1;\n    build(v * 2 + 1, l, mid);\n    build(v * 2 + 2, mid, r);\n    t[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\nint main(){\n    scanf(\"%d %d %d\", &n, &k, &m);\n    \n    build(0, 0, n + n);\n    set <pair<int, int> > s;\n    set <int> smx;\n    for (int i = 0; i < m; ++i) {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        int pos = abs(x - k) + y - 1;\n        pair <int, int> p = make_pair(x, y);\n        if (s.count(p)) {\n            --cnt[pos];\n            if (cnt[pos] == 0) smx.erase(pos);\n            upd(0, pos + 1, -1);\n            s.erase(p);\n        } else {\n            ++cnt[pos];\n            if (cnt[pos] == 1) smx.insert(pos);\n            upd(0, pos + 1, 1);\n            s.insert(p);\n        }\n        \n        printf(\"%d\\n\", getAns(smx));\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1374",
    "index": "A",
    "title": "Required Remainder",
    "statement": "You are given three integers $x, y$ and $n$. Your task is to find the \\textbf{maximum} integer $k$ such that $0 \\le k \\le n$ that $k \\bmod x = y$, where $\\bmod$ is modulo operation. Many programming languages use percent operator % to implement it.\n\nIn other words, with given $x, y$ and $n$ you need to find the maximum possible integer from $0$ to $n$ that has the remainder $y$ modulo $x$.\n\nYou have to answer $t$ independent test cases. It is guaranteed that such $k$ exists for each test case.",
    "tutorial": "There are two cases in this problem. If we try to maximize the answer, we need to consider only two integers: $n - n \\bmod x + y$ and $n - n \\bmod x - (x - y)$. Of course, the first one is better (we get rid of the existing remainder and trying to add $y$ to this number). If it's too big, then we can and need to take the second one (this number is just the first one but decreased by $x$). The answer can be always found between these numbers. Time complexity: $O(1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint x, y, n;\n\t\tcin >> x >> y >> n;\n\t\tif (n - n % x + y <= n) {\n\t\t\tcout << n - n % x + y << endl;\n\t\t} else {\n\t\t\tcout << n - n % x - (x - y) << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1374",
    "index": "B",
    "title": "Multiply by 2, divide by 6",
    "statement": "You are given an integer $n$. In one move, you can either multiply $n$ by two or divide $n$ by $6$ (if it is divisible by $6$ without the remainder).\n\nYour task is to find the minimum number of moves needed to obtain $1$ from $n$ or determine if it's impossible to do that.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If the number consists of other primes than $2$ and $3$ then the answer is -1. Otherwise, let $cnt_2$ be the number of twos in the factorization of $n$ and $cnt_3$ be the number of threes in the factorization of $n$. If $cnt_2 > cnt_3$ then the answer is -1 because we can't get rid of all twos. Otherwise, the answer is $(cnt_3 - cnt_2) + cnt_3$. Time complexity: $O(\\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tint cnt2 = 0, cnt3 = 0;\n\t\twhile (n % 2 == 0) {\n\t\t\tn /= 2;\n\t\t\t++cnt2;\n\t\t}\n\t\twhile (n % 3 == 0) {\n\t\t\tn /= 3;\n\t\t\t++cnt3;\n\t\t}\n\t\tif (n == 1 && cnt2 <= cnt3) {\n\t\t\tcout << 2 * cnt3 - cnt2 << endl;\n\t\t} else {\n\t\t\tcout << -1 << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1374",
    "index": "C",
    "title": "Move Brackets",
    "statement": "You are given a bracket sequence $s$ of length $n$, where $n$ is even (divisible by two). The string $s$ consists of $\\frac{n}{2}$ opening brackets '(' and $\\frac{n}{2}$ closing brackets ')'.\n\nIn one move, you can choose \\textbf{exactly one bracket} and move it to the beginning of the string or to the end of the string (i.e. you choose some index $i$, remove the $i$-th character of $s$ and insert it before or after all remaining characters of $s$).\n\nYour task is to find the minimum number of moves required to obtain \\textbf{regular bracket sequence} from $s$. It can be proved that the answer always exists under the given constraints.\n\nRecall what the regular bracket sequence is:\n\n- \"()\" is regular bracket sequence;\n- if $s$ is regular bracket sequence then \"(\" + $s$ + \")\" is regular bracket sequence;\n- if $s$ and $t$ are regular bracket sequences then $s$ + $t$ is regular bracket sequence.\n\nFor example, \"()()\", \"(())()\", \"(())\" and \"()\" are regular bracket sequences, but \")(\", \"()(\" and \")))\" are not.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let's go from left to right over characters of $s$ maintaining the current bracket balance (for the position $i$ the balance is the number of opening brackets on the prefix till the $i$-th character minus the number of closing brackets on the same prefix). If the current balance becomes less than zero, then let's just take some opening bracket after the current position (it obviously exists because the number of opening equals the number of closing brackets) and move it to the beginning (so the negative balance becomes zero again and the answer increases by one). Or we can move the current closing bracket to the end of the string because it leads to the same result. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tstring s;\n\t\tcin >> n >> s;\n\t\tint ans = 0;\n\t\tint bal = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (s[i] == '(') ++bal;\n\t\t\telse {\n\t\t\t\t--bal;\n\t\t\t\tif (bal < 0) {\n\t\t\t\t\tbal = 0;\n\t\t\t\t\t++ans;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1374",
    "index": "D",
    "title": "Zero Remainder Array",
    "statement": "You are given an array $a$ consisting of $n$ positive integers.\n\nInitially, you have an integer $x = 0$. During one move, you can do one of the following two operations:\n\n- Choose \\textbf{exactly one} $i$ from $1$ to $n$ and increase $a_i$ by $x$ ($a_i := a_i + x$), then increase $x$ by $1$ ($x := x + 1$).\n- Just increase $x$ by $1$ ($x := x + 1$).\n\nThe first operation can be applied \\textbf{no more than once} to each $i$ from $1$ to $n$.\n\nYour task is to find the minimum number of moves required to obtain such an array that each its element is \\textbf{divisible by} $k$ (the value $k$ is given).\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, we can understand that during each full cycle of $x$ from $0$ to $k-1$ we can fix each remainder only once. Notice that when we add some $x$ then we fix the remainder $k-x$ (and we don't need to fix elements which are already divisible by $k$). So, let $cnt_i$ be the number of such elements for which the condition $k - a_i \\bmod k = i$ holds (i.e. the number of such elements that we can fix if we add the value $i \\bmod k$ to them). We can count this using some logarithmic data structure (like std::map in C++). So, what's the number of full cycles? It equals to the amount of most frequent element in $cnt$ minus one. So, the answer is at least $k \\cdot (max(cnt) - 1)$. And there can be one last cycle which will be incomplete. So what is the remanining number of moves? It equals to the maximum possible $i$ among all $cnt_i = max(cnt)$. So if $key$ is the maximum such $i$ that $cnt_{key} = max(cnt)$ then the answer is $k \\cdot (cnt_{key} - 1) + key + 1$. Time complexity: $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tmap<int, int> cnt;\n\t\tint mx = 0;\n\t\tfor (auto &it : a) {\n\t\t\tif (it % k == 0) continue;\n\t\t\t++cnt[k - it % k];\n\t\t\tmx = max(mx, cnt[k - it % k]);\n\t\t}\n\t\tlong long ans = 0;\n\t\tfor (auto [key, value] : cnt) {\n\t\t\tif (value == mx) {\n\t\t\t\tans = k * 1ll * (value - 1) + key + 1;\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1374",
    "index": "E1",
    "title": "Reading Books (easy version)",
    "statement": "\\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully}.\n\nSummer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book \\textbf{together} to end this exercise faster.\n\nThere are $n$ books in the family library. The $i$-th book is described by three integers: $t_i$ — the amount of time Alice and Bob need to spend to read it, $a_i$ (equals $1$ if Alice likes the $i$-th book and $0$ if not), and $b_i$ (equals $1$ if Bob likes the $i$-th book and $0$ if not).\n\nSo they need to choose some books from the given $n$ books in such a way that:\n\n- Alice likes \\textbf{at least} $k$ books from the chosen set and Bob likes \\textbf{at least} $k$ books from the chosen set;\n- the total reading time of these books is \\textbf{minimized} (they are children and want to play and joy as soon a possible).\n\nThe set they choose is \\textbf{the same} for both Alice an Bob (it's shared between them) and they read all books \\textbf{together}, so the total reading time is the sum of $t_i$ over all books that are in the chosen set.\n\nYour task is to help them and find any suitable set of books or determine that it is impossible to find such a set.",
    "tutorial": "Let's divide all books into four groups: 00 - both Alice and Bob doesn't like these books; 01 - only Alice likes these books; 10 - only Bob likes these books; 11 - both ALice and Bob like these books. Obviously, 00-group is useless now. So, how to solve the problem? Let's iterate over the number of books we take from 11-group. Let it be $cnt$. Then we obviously need to take exactly $k-cnt$ books from groups 01 and 10. Among all books in these three groups we have to choose the cheapest ones. To calculate sum of times in each group fast enought, we can sort each group independently and implement prefix sums on these arrays. If $k-cnt$ is less than zero or greater than the size of 01 or 10-group for each possible $cnt$ then the answer is -1. And don't forget that the answer can be up to $2 \\cdot 10^9$. Time complexity: $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 2e9 + 1;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> times[4];\n\tvector<int> sums[4];\n\tfor (int i = 0; i < n; ++i) {\n\t\tint t, a, b;\n\t\tcin >> t >> a >> b;\n\t\ttimes[a * 2 + b].push_back(t);\n\t}\n\tfor (int i = 0; i < 4; ++i) {\n\t\tsort(times[i].begin(), times[i].end());\n\t\tsums[i].push_back(0);\n\t\tfor (auto it : times[i]) {\n\t\t\tsums[i].push_back(sums[i].back() + it);\n\t\t}\n\t}\n\t\n\tint ans = INF;\n\tfor (int cnt = 0; cnt < min(k + 1, int(sums[3].size())); ++cnt) {\n\t\tif (k - cnt < int(sums[1].size()) && k - cnt < int(sums[2].size())) {\n\t\t\tans = min(ans, sums[3][cnt] + sums[1][k - cnt] + sums[2][k - cnt]);\n\t\t}\n\t}\n\t\n\tif (ans == INF) ans = -1;\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1374",
    "index": "E2",
    "title": "Reading Books (hard version)",
    "statement": "\\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully}.\n\nSummer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read \\textbf{exactly} $m$ books before all entertainments. Alice and Bob will read each book \\textbf{together} to end this exercise faster.\n\nThere are $n$ books in the family library. The $i$-th book is described by three integers: $t_i$ — the amount of time Alice and Bob need to spend to read it, $a_i$ (equals $1$ if Alice likes the $i$-th book and $0$ if not), and $b_i$ (equals $1$ if Bob likes the $i$-th book and $0$ if not).\n\nSo they need to choose \\textbf{exactly} $m$ books from the given $n$ books in such a way that:\n\n- Alice likes \\textbf{at least} $k$ books from the chosen set and Bob likes \\textbf{at least} $k$ books from the chosen set;\n- the total reading time of these $m$ books is \\textbf{minimized} (they are children and want to play and joy as soon a possible).\n\nThe set they choose is \\textbf{the same} for both Alice an Bob (it's shared between them) and they read all books \\textbf{together}, so the total reading time is the sum of $t_i$ over all books that are in the chosen set.\n\nYour task is to help them and find any suitable set of books or determine that it is impossible to find such a set.",
    "tutorial": "A little explanation: this editorial will be based on the easy version editorial so I'll use some definitions from it. Here we go, the most beautiful problem of the contest is waiting us. Well, the key idea of this problem almost the same with the easy version idea. Let's iterate over the number of elements in 11-group, we need to take the cheapest ones again. If the number of elements we take from 11-group is $cnt$ then we need to take $k-cnt$ elements from 01 and 10-groups. But one more thing: let's iterate over $cnt$ not from zero but from the smallest possible number which can give us any correct set of books (the numeric value of the answer doesn't matter) $start$. The value of $start$ can be calculated using $k, m$ and sizes of groups by formula or even simple loop. If we can't find any suitable value of $start$, the answer is -1. Let's call $cnt$ elements from 11-group and $k-cnt$ elements from 01 and 10-groups we take necessary. Other elements of the whole set of books are free (but elements of 11-group are not free). Let's create the set $fr$ which contains all free elements (and fill it beforehand). So, now we took some necessary elements, but we need to take some free elements to complete our set. Let's create the other set $st$ which contains free elements we take to the answer (and maintain the variable $sum$ describing the sum of elements of $st$). How do we recalculate $st$? Before the start of the first iteration our set $fr$ is already filled with some elements, let's update $st$ using them. Update is such an operation (function) that tosses the elements between $fr$ and $st$. It will do the following things (repeatedly, and stop when it cannot do anything): While the size of $st$ is greater than needed (so we take more than $m$ books in total), let's remove the most expensive element from $st$ and add it to $fr$; while the size of $st$ is less than needed (so we take less than $m$ books in total), let's remove the cheapest element from $fr$ and add it to $st$; while the cheapest element from $fr$ is cheaper than the most expensive element form $st$, let's swap them. Note that during updates you need to recalculate $sum$ as well. So, we go over all possible values $cnt$, updating $st$ before the first iteration and after each iteration. The size of both sets changes pretty smooth: if we go from $cnt$ to $cnt+1$, we need to remove at most one element from $st$ (because we take one element from 11-group during each iteration) and we need to add at most two elements to $st$ and $fr$ (because we remove at most two elements from 01 and 10-groups during one iteration). To restore the answer, let's save such a value $cnt$ that the answer is minimum with this value $cnt$ (let it be $pos$). Then let's just run the same simulation once more from the beginning but stop when we reach $pos$. Then $st$ will contain free elements we need to take to the answer, $pos$ describes the number of elements we need to take from 11-group and $k-pos$ describes which elements from 01 and 01-groups we need to take. Of course, there are some really tough technical things like case-handling (there is a lot of cases, for example, the size of $st$ can be negative at some moment and you need to carefully handle that, and $k-cnt$ can be negative after some number of iterations and there are other cases because of that, and so on). Time complexity: $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 2e9 + 1;\n\n#define size(a) int((a).size())\n\nvoid updateSt(set<pair<int, int>> &st, set<pair<int, int>> &fr, int &sum, int need) {\n\tneed = max(need, 0);\n\twhile (true) {\n\t\tbool useful = false;\n\t\twhile (size(st) > need) {\n\t\t\tsum -= st.rbegin()->first;\n\t\t\tfr.insert(*st.rbegin());\n\t\t\tst.erase(prev(st.end()));\n\t\t\tuseful = true;\n\t\t}\n\t\twhile (size(st) < need && size(fr) > 0) {\n\t\t\tsum += fr.begin()->first;\n\t\t\tst.insert(*fr.begin());\n\t\t\tfr.erase(fr.begin());\n\t\t\tuseful = true;\n\t\t}\n\t\twhile (!st.empty() && !fr.empty() && fr.begin()->first < st.rbegin()->first) {\n\t\t\tsum -= st.rbegin()->first;\n\t\t\tsum += fr.begin()->first;\n\t\t\tfr.insert(*st.rbegin());\n\t\t\tst.erase(prev(st.end()));\n\t\t\tst.insert(*fr.begin());\n\t\t\tfr.erase(fr.begin());\n\t\t\tuseful = true;\n\t\t}\n\t\tif (!useful) break;\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tvector<pair<int, int>> times[4];\n\tvector<int> sums[4];\n\tfor (int i = 0; i < n; ++i) {\n\t\tint t, a, b;\n\t\tcin >> t >> a >> b;\n\t\ttimes[a * 2 + b].push_back({t, i});\n\t}\n\tfor (int i = 0; i < 4; ++i) {\n\t\tsort(times[i].begin(), times[i].end());\n\t\tsums[i].push_back(0);\n\t\tfor (auto it : times[i]) {\n\t\t\tsums[i].push_back(sums[i].back() + it.first);\n\t\t}\n\t}\n\t\n\tint ans = INF;\n\tint pos = INF;\n\tset<pair<int, int>> st;\n\tset<pair<int, int>> fr;\n\tint sum = 0;\n\tvector<int> res;\n\tfor (int iter = 0; iter < 2; ++iter) {\n\t\tst.clear();\n\t\tfr.clear();\n\t\tsum = 0;\n\t\tint start = 0;\n\t\twhile (k - start >= size(sums[1]) || k - start >= size(sums[2]) || m - start - (k - start) * 2 < 0) {\n\t\t\t++start;\n\t\t}\n\t\tif (start >= size(sums[3])) {\n\t\t\tcout << -1 << endl;\n\t\t\treturn 0;\n\t\t}\n\t\tint need = m - start - (k - start) * 2;\n\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\tfor (int p = size(times[i]) - 1; p >= (i == 0 ? 0 : k - start); --p) {\n\t\t\t\tfr.insert(times[i][p]);\n\t\t\t}\n\t\t}\n\t\tupdateSt(st, fr, sum, need);\n\t\tfor (int cnt = start; cnt < (iter == 0 ? size(sums[3]) : pos); ++cnt) {\n\t\t\tif (k - cnt >= 0) {\t\n\t\t\t\tif (cnt + (k - cnt) * 2 + size(st) == m) {\n\t\t\t\t\tif (ans > sums[3][cnt] + sums[1][k - cnt] + sums[2][k - cnt] + sum) {\n\t\t\t\t\t\tans = sums[3][cnt] + sums[1][k - cnt] + sums[2][k - cnt] + sum;\n\t\t\t\t\t\tpos = cnt + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (cnt + size(st) == m) {\n\t\t\t\t\tif (ans > sums[3][cnt] + sum) {\n\t\t\t\t\t\tans = sums[3][cnt] + sum;\n\t\t\t\t\t\tpos = cnt + 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (iter == 1 && cnt + 1 == pos) break;\n\t\t\tneed -= 1;\n\t\t\tif (k - cnt > 0) {\n\t\t\t\tneed += 2;\n\t\t\t\tfr.insert(times[1][k - cnt - 1]);\n\t\t\t\tfr.insert(times[2][k - cnt - 1]);\n\t\t\t}\n\t\t\tupdateSt(st, fr, sum, need);\n\t\t}\n\t\tif (iter == 1) {\n\t\t\tfor (int i = 0; i + 1 < pos; ++i) res.push_back(times[3][i].second);\n\t\t\tfor (int i = 0; i <= k - pos; ++i) {\n\t\t\t\tres.push_back(times[1][i].second);\n\t\t\t\tres.push_back(times[2][i].second);\n\t\t\t}\n\t\t\tfor (auto [value, position] : st) res.push_back(position);\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\tfor (auto it : res) cout << it + 1 << \" \";\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings",
      "ternary search",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1374",
    "index": "F",
    "title": "Cyclic Shifts Sorting",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nIn one move, you can choose some index $i$ ($1 \\le i \\le n - 2$) and shift the segment $[a_i, a_{i + 1}, a_{i + 2}]$ cyclically to the right (i.e. replace the segment $[a_i, a_{i + 1}, a_{i + 2}]$ with $[a_{i + 2}, a_i, a_{i + 1}]$).\n\nYour task is to sort the initial array by \\textbf{no more than $n^2$ such operations} or say that it is impossible to do that.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, let's solve the easier version of the problem. Assume we are given a permutation, not an array. Notice that the given operation applied to some segment of the permutation cannot change the parity of number of inversions (the number of inversions is the number of such pairs of indices $(i, j)$ that $j > i$ and $a_j < a_i$). So if the number of inversions in the given permutation is odd then we can't sort this permutation (we can't obtain zero inversions). But if the number of inversions is even then we can always sort the permutation with the following greedy algorithm: let's find the minimum element and move it to the first position. If its position is $i$ then we can apply the operation to the segment $[i-2; i]$ and our element will move by two positions to the left. So, after all, our element is either at the first or at the second position. If it's at the second position, let's just apply two additional operations to the segment $[1; 3]$. Then let's just cut off the first element and solve the problem without it. At the end we have only two numbers that can be not sorted and we can check all three possibilities and choose one which is suitable for us (it's always exists because the number of inversions is even). How do we solve the problem if we are given the array, not the permutation? First of all, we can prove that if the array contains at least two equal elements, we can always sort it (we will prove it by construction). Let's just renumerate the elements of the given array in a way to obtian the permutation with the even number of inversions. Thus, if $a[i_1] \\le a[i_2] \\le \\dots \\le a[i_n]$ then let's find such a permutation $p$ that $p[i_1] < p[i_2] < \\dots < p[i_n]$. We can find this permutation easily if we sort the array of pairs $(a_i, i)$ in increasing order. But there can be one problem: this permutation can have odd number of inversions. Then we need to find two consecutive pairs with the same first values and swap these two elements in the permutation. Because in fact these two numbers are equal in the array and have consecutive values in the permutation, we guaranteed change the parity of number of inversions. Then we can apply our algorithm for permutations and solve the problem for the array. If we failed then the answer is -1. Otherwise the number of operations always does not exceed $n^2$ (because this sort works like a bubble sort) so our answer is suitable. Time complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tauto make = [](vector<int> &a, int pos) {\n\t\tswap(a[pos + 1], a[pos + 2]);\n\t\tswap(a[pos], a[pos + 1]);\n\t};\n\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tvector<pair<int, int>> res(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcin >> a[i];\n\t\t\tres[i] = { a[i], i };\n\t\t}\n\t\tsort(res.begin(), res.end());\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\ta[res[i].second] = i;\n\t\t}\n\t\tint cnt = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfor (int j = i + 1; j < n; ++j) {\n\t\t\t\tcnt += a[j] < a[i];\n\t\t\t}\n\t\t}\n\t\tif (cnt & 1) {\n\t\t\tfor (int i = 0; i < n - 1; ++i) {\n\t\t\t\tif (res[i].first == res[i + 1].first) {\n\t\t\t\t\tswap(a[res[i].second], a[res[i + 1].second]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvector<int> ans;\n\t\tfor (int i = 0; i < n - 2; ++i) {\n\t\t\tint pos = min_element(a.begin() + i, a.end()) - a.begin();\n\t\t\twhile (pos > i + 1) {\n\t\t\t\tmake(a, pos - 2);\n\t\t\t\tans.push_back(pos - 2);\n\t\t\t\tpos -= 2;\n\t\t\t}\n\t\t\tif (pos != i) {\n\t\t\t\tmake(a, i);\n\t\t\t\tmake(a, i);\n\t\t\t\tans.push_back(i);\n\t\t\t\tans.push_back(i);\n\t\t\t\tpos = i;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\tif (is_sorted(a.begin(), a.end())) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmake(a, n - 3);\n\t\t\tans.push_back(n - 3);\n\t\t}\n\t\tif (!is_sorted(a.begin(), a.end())) {\n\t\t\tcout << -1 << endl;\n\t\t} else {\n\t\t\tcout << ans.size() << endl;\n\t\t\tfor (auto it : ans) cout << it + 1 << \" \";\n\t\t\tcout << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1375",
    "index": "A",
    "title": "Sign Flipping",
    "statement": "You are given $n$ integers $a_1, a_2, \\dots, a_n$, where $n$ \\textbf{is odd}. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:\n\n- At least $\\frac{n - 1}{2}$ of the adjacent differences $a_{i + 1} - a_i$ for $i = 1, 2, \\dots, n - 1$ are \\textbf{greater than or equal to} $0$.\n- At least $\\frac{n - 1}{2}$ of the adjacent differences $a_{i + 1} - a_i$ for $i = 1, 2, \\dots, n - 1$ are \\textbf{less than or equal to} $0$.\n\nFind any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.",
    "tutorial": "Notice that $a_{i + 1} - a_i \\ge 0$ is equivalent to $a_{i + 1} \\ge a_i$. Similarly $a_{i + 1} - a_i \\le 0$ is equivalent to $a_{i + 1} \\le a_i$. Flip the signs in such a way that $a_i \\ge 0$ for odd $i$, while $a_i \\le 0$ for even $i$. Then $a_{i + 1} \\ge 0 \\ge a_i$, and thus $a_{i + 1} \\ge a_i$, for $i = 2, 4, \\dots, n - 1$. $a_{i + 1} \\le 0 \\le a_i$, and thus $a_{i + 1} \\le a_i$, for $i = 1, 3, \\dots, n - 2$. Giving at least $\\frac{n - 1}{2}$ of each, as desired.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1375",
    "index": "B",
    "title": "Neighbor Grid",
    "statement": "You are given a grid with $n$ rows and $m$ columns, where each cell has a non-negative integer written on it. We say the grid is \\textbf{good} if for each cell the following condition holds: if it has a number $k > 0$ written on it, then exactly $k$ of its neighboring cells have a number greater than $0$ written on them. Note that if the number in the cell is $0$, there is no such restriction on neighboring cells.\n\nYou are allowed to take any number in the grid and increase it by $1$. You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them.\n\nTwo cells are considered to be neighboring if they have a common edge.",
    "tutorial": "For every cell $(i, j)$ let's denote by $n_{i, j}$ the number of neighbors it has (either zero or non-zero, it doesn't matter). Then for each cell, it must hold that $a_{i, j} \\le n_{i, j}$, otherwise, no solution exists because it is impossible to decrease $a_{i, j}$. Let's now suppose that $a_{i, j} \\le n_{i, j}$ for all cells $(i, j)$. Then a solution always exists: We can increase each $a_{i, j}$ to make it equal to $n_{i, j}$. This always works because every number will be non-zero, so every neighbor of every cell will be non-zero, and every cell has a value equal to its number of neighbors.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1375",
    "index": "C",
    "title": "Element Extermination",
    "statement": "You are given an array $a$ of length $n$, which initially is a \\textbf{permutation} of numbers from $1$ to $n$. In one operation, you can choose an index $i$ ($1 \\leq i < n$) such that $a_i < a_{i + 1}$, and remove either $a_i$ or $a_{i + 1}$ from the array (after the removal, the remaining parts are concatenated).\n\nFor example, if you have the array $[1, 3, 2]$, you can choose $i = 1$ (since $a_1 = 1 < a_2 = 3$), then either remove $a_1$ which gives the new array $[3, 2]$, or remove $a_2$ which gives the new array $[1, 2]$.\n\nIs it possible to make the length of this array equal to $1$ with these operations?",
    "tutorial": "The answer is YES iff $a_1 < a_n$. Let's find out why. When $a_1 < a_n$, we can repeatedly use this algorithm while the permutation contains more than one element: Find the smallest index $r$ such that $a_1 < a_r$. Choose $a_r$ and the element comes right before $a_r$ and delete the element before $a_r$. Repeat step 2 until $a_r$ is adjacent to $a_1$. Choose $a_1$ and $a_r$, and delete $a_r$. When $a_1 > a_n$, we have some observations: The leftmost element is non-decreasing. That is because if we want to remove the old leftmost element $a_1$, we need to pair it with $a_2 > a_1$, and that will result in the leftmost element increasing. Likewise, we can use the same argument to show that the rightmost element is non-increasing.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1375",
    "index": "D",
    "title": "Replace by MEX",
    "statement": "You're given an array of $n$ integers between $0$ and $n$ inclusive.\n\nIn one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).\n\nFor example, if the current array is $[0, 2, 2, 1, 4]$, you can choose the second element and replace it by the MEX of the present elements  — $3$. Array will become $[0, 3, 2, 1, 4]$.\n\nYou must make the array non-decreasing, using at most $2n$ operations.\n\nIt can be proven that it is always possible. Please note that you do \\textbf{not} have to minimize the number of operations. If there are many solutions, you can print any of them.\n\n–\n\nAn array $b[1 \\ldots n]$ is non-decreasing if and only if $b_1 \\le b_2 \\le \\ldots \\le b_n$.\n\nThe MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:\n\n- The MEX of $[2, 2, 1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3, 1, 0, 1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0, 3, 1, 2]$ is $4$ because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.\n\nIt's worth mentioning that the MEX of an array of length $n$ is always between $0$ and $n$ inclusive.",
    "tutorial": "(We consider the array $0$-indexed) Instead of trying to reach any non-decreasing array, we will try to reach precisely $[0, 1, \\ldots, n-1]$. Let's call any index $i$ such that $a_i \\neq i$ an unfixed point. We will repeat the following procedure in order to remove all unfixed points: If $\\text{mex} = n$, we apply an operation on any unfixed point. Now that $\\text{mex} < n$, we apply an operation on index $\\text{mex}$ (which was an unfixed point, since $\\text{mex}$ was not present in the array). Each turn uses at most $2$ operations, and decrease the number of unfixed points by exactly $1$. Since there are at most $n$ unfixed points initially, we use at most $2n$ operations. It was not necessary under the given constraints, but one can notice that if $\\text{mex} = n$, the current array is a permutation, and that solving a cycle will take $\\text{size} + 1$ operations. Hence, the described algorithm use in fact at most $1.5n$ operations, the worst case being $[1, 0, 3, 2, 5, 4, \\ldots]$ when there are a lot of $2$-cycles. Since the constraint on $n$ is low, we can recompute naively the $\\text{mex}$ each time in $\\mathcal{O}(n)$, leading to an $\\mathcal{O}(n^2)$ final time complexity.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1375",
    "index": "E",
    "title": "Inversion SwapSort",
    "statement": "Madeline has an array $a$ of $n$ integers. A pair $(u, v)$ of integers forms an inversion in $a$ if:\n\n- $1 \\le u < v \\le n$.\n- $a_u > a_v$.\n\nMadeline recently found a magical paper, which allows her to write two indices $u$ and $v$ and swap the values $a_u$ and $a_v$. Being bored, she decided to write a list of pairs $(u_i, v_i)$ with the following conditions:\n\n- all the pairs in the list are distinct and form an inversion in $a$.\n- all the pairs that form an inversion in $a$ are in the list.\n- Starting from the given array, if you swap the values at indices $u_1$ and $v_1$, then the values at indices $u_2$ and $v_2$ and so on, then after all pairs are processed, the array $a$ will be sorted in \\textbf{non-decreasing order}.\n\nConstruct such a list or determine that no such list exists. If there are multiple possible answers, you may find any of them.",
    "tutorial": "We can prove that the answer always exists. Let's first solve the problem for a permutation of length $n$. Let's define $pos_i (1 \\le i \\le n)$ as the index of $i$ in the permutation. First we are going to use all the pairs whose second element is $n$. Let's define the resulting permutation that we get, after using all these pairs in some order, as $b$. We want $b$ to satisfy all of these conditions. $b_n=n$ If $a_i>a_j$ then $b_i>b_j$ ($1 \\le i<j \\le n-1$) If $a_i<a_j$ then $b_i<b_j$ ($1 \\le i<j \\le n-1$) So we solved the problem for a permutation, how can we approach the general problem? For every $i>j, a_i=a_j$ we can assume that $a_i>a_j$, and this won't change anything because the order of equal elements doesn't matter and we are not adding any inversions by assuming this. So after doing this we can easily squeeze the numbers into a permutation and solve the problem for a permutation. Total complexity $O(n^2logn)$ or $O(n^2)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1375",
    "index": "F",
    "title": "Integer Game",
    "statement": "\\textbf{This is an interactive problem.}\n\nAnton and Harris are playing a game to decide which of them is the king of problemsetting.\n\nThere are three piles of stones, initially containing $a$, $b$, and $c$ stones, where $a$, $b$, and $c$ are \\textbf{distinct} positive integers. On each turn of the game, the following sequence of events takes place:\n\n- The first player chooses a positive integer $y$ and provides it to the second player.\n- The second player adds $y$ stones to one of the piles, with the condition that \\textbf{he cannot choose the same pile in two consecutive turns}.\n\nThe second player loses if, at any point, two of the piles contain the same number of stones. The first player loses if $1000$ turns have passed without the second player losing.\n\nFeeling confident in his skills, Anton decided to let Harris choose whether he wants to go first or second. Help Harris defeat Anton and become the king of problemsetting!",
    "tutorial": "Let's prove that the first player can always win in at most three turns. Assume that the initial numbers of stones are $p < q < r$. On the first turn, choose $y = 2r - p - q$. We then have three cases: Case 1. $y$ is added to $p$. The piles now have $2r - q$, $q$ and $r$ stones. Now choose $y = r - q$. Since the pile with $2r - q$ stones cannot be chosen on this turn, this results in a win. Case 2. $y$ is added to $q$. The piles now have $p$, $2r - p$ and $r$ stones. Choose $y = r - p$. Similarly to the previous case this results in a win since the pile with $2r - p$ stones cannot be chosen on this turn. Case 3. $y$ is added to $r$. The piles have $p < q < 3r - p - q$ stones. We now have a situation similar to the initial one, with the difference that the pile with the largest number of stones cannot be chosen on the next turn. Thus we may repeat the strategy and obtain a guaranteed win this time.",
    "tags": [
      "constructive algorithms",
      "games",
      "interactive",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1375",
    "index": "G",
    "title": "Tree Modification",
    "statement": "You are given a tree with $n$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation:\n\n- Choose three vertices $a$, $b$, and $c$ such that $b$ is adjacent to both $a$ and $c$.\n- For every vertex $d$ \\textbf{other than $b$} that is adjacent to $a$, remove the edge connecting $d$ and $a$ and add the edge connecting $d$ and $c$.\n- Delete the edge connecting $a$ and $b$ and add the edge connecting $a$ and $c$.\n\nAs an example, consider the following tree:\n\nThe following diagram illustrates the sequence of steps that happen when we apply an operation to vertices $2$, $4$, and $5$:\n\nIt can be proven that after each operation, the resulting graph is still a tree.\n\nFind the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree $n - 1$, called its center, and $n - 1$ vertices of degree $1$.",
    "tutorial": "The solution is based on the following observation: Every tree is a bipartite graph, i. e. its vertices can be colored black or white in such a way that every white vertex is adjacent only to black vertices and vice versa. Notice that a tree is a star if and only if one of the colors appears exactly once. Let's fix a bipartite coloring of the tree and look at what happens when we apply the operation to vertices $a$, $b$, and $c$. For concreteness, let's suppose that $b$ is black, so $a$ and $c$ must be white. When we perform the operation: Every neighbor of $a$ other than $b$ is black. After connecting it to $c$ it remains black since $c$ is white. After connecting $a$ to $c$ it must switch from being white to being black since $c$ is white. Every other vertex is unaffected by the operation. Thus every operation changes the color of exactly one vertex! Suppose that initially there are $b$ black vertices and $w$ white vertices. Then we need at least $\\min(w, b) - 1$ operations to turn the tree into a star since one of the colors must end up having a single vertex. This is always achievable: as long as there are at least two vertices with a certain color we can choose two which are adjacent to a common neighbor and use the operation to recolor one of them. The values of $w$ and $b$ can be found through a simple DFS, leading to an $O(n)$ solution.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graph matchings",
      "graphs",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1375",
    "index": "H",
    "title": "Set Merging",
    "statement": "You are given a permutation $a_1, a_2, \\dots, a_n$ of numbers from $1$ to $n$. Also, you have $n$ sets $S_1,S_2,\\dots, S_n$, where $S_i=\\{a_i\\}$. Lastly, you have a variable $cnt$, representing the current number of sets. Initially, $cnt = n$.\n\nWe define two kinds of functions on sets:\n\n$f(S)=\\min\\limits_{u\\in S} u$;\n\n$g(S)=\\max\\limits_{u\\in S} u$.\n\nYou can obtain a new set by merging two sets $A$ and $B$, if they satisfy $g(A)<f(B)$ (Notice that the old sets do not disappear).\n\nFormally, you can perform the following sequence of operations:\n\n- $cnt\\gets cnt+1$;\n- $S_{cnt}=S_u\\cup S_v$, you are free to choose $u$ and $v$ for which $1\\le u, v < cnt$ and which satisfy $g(S_u)<f(S_v)$.\n\nYou are required to obtain some specific sets.\n\nThere are $q$ requirements, each of which contains two integers $l_i$,$r_i$, which means that there must exist a set $S_{k_i}$ ($k_i$ is the ID of the set, you should determine it) which equals $\\{a_u\\mid l_i\\leq u\\leq r_i\\}$, which is, the set consisting of all $a_i$ with indices between $l_i$ and $r_i$.\n\nIn the end you must ensure that $cnt\\leq 2.2\\times 10^6$. Note that you \\textbf{don't} have to minimize $cnt$. It is guaranteed that a solution under given constraints exists.",
    "tutorial": "First, two sets $a$ and $b$ can be merged if and only if the range of elements in $a$ do not intersect with the range of elements in $b$. It is obvious because if they intersect, neither $g(a)<f(b)$ nor $g(b)<f(a)$ are satisfied. If they do not intersect, there must be one of them satisfied. Notice that $2\\times n\\sqrt{q}$ is near to $2.2\\times 10^6$, this hints us to use sqrt-decomposition. We separate the numbers $1,2,\\cdots,n$ into $\\dfrac{n}{S}$ consecutive blocks, each of size $S$. Consider a block $B_i=[l,r]$, we take all elements in the original permutation that satisfy $l\\leq a_i \\leq r$, and form a new sequence that preserves the original order. For example, if the permutation $9,8,2,1,5,6,3,7,4$ is divided into $3$ blocks $B_1=[1,3],B_2=[4,6],B_3=[7,9]$, their sequences will be $2,1,3$ and $5,6,4$ and $9,8,7$. Consider any consecutive subsequence in the permutation. We want to construct a set that just contains all elements in it. We can first divide this subsequence into $\\dfrac{n}S$ subsequences in each block that contains only elements in this block and merge them up. For example, if we want the subsequence $8,2,1,5,6,3,7$ in the permutation above, then we can divide it into $2,1,3$ and $5,6$ and $8,7$. Notice that those subsequences in each block are also consecutive subsequences. Also, notice that since the range of elements in each block do not intersect, the range of elements in these subsequences also do not intersect. This means that if we can somehow construct the set that equals the set of each of those subsequences, we can just merge those subsequences of each block to form the original subsequence that we want to obtain in $\\dfrac{n}S-1$ merges. Thus the process of constructing sets in total costs less that $\\dfrac{qn}S$ merges. Now we have to construct the subsequences of each block, notice that the subsequences are consecutive, thus we can just construct sets of all of those $\\dfrac12S(S+1)$ consecutive subsequences. Consider divide and conquer. We can divide a sequence in to two parts of equal size, construct subsequences of them, and try to merge them to obtain the new sets. So how do we split and merge? Consider two sequences, that elements in the first sequence is less than elements in the second, and we have already constructed the sets of all the consecutive subsequences in each of those sequences. Now we consider a sequence that contains the union of the elements in the two subsequences. All elements in sequences here are ordered according to the order in the original permutation. Now we want to construct all the consecutive subsequences in the new sequence. Consider for each consecutive subsequence in the new sequence, it must be composed by two parts, the ones present in the first sequence, and the one present in the second. It is obvious that each part is also a consecutive subsequence in the respective sequence, thus the sets representing them is already constructed. Because the two sequence do not intersect in range of elements, we can just merge those two sets to form the new one. For example, we want to obtain all subsequences of the sequence $1,4,3,2,6,5$, and we have already obtained the ones of $1,3,2$ and $4,6,5$. So if we want to get the consecutive subsequence $1,4,3,2,6$, we first divide it into $1,3,2$ and $4,6$. Because the sets of them are already constructed(they are consecutive subsequences of $1,3,2$ and $4,6,5$), and their range of elements do not intersect, we can merge it in one operation. Other consecutive subsequences can also be obtained similarly. Thus there are $\\dfrac12S(S+1)$ subsequences, and less than $\\dfrac12S(S-1)$ need a merge operation (because those with only one element in it need no operation). We use $f(S)$ to denote the number of operation needed to construct all consecutive subsequences of a block of length $S$ There is $f(1)=0$ and $f(x)\\leq \\dfrac12x^2+f(\\lfloor x/2\\rfloor)+f(\\lceil x/2\\rceil)$,(if we divide a subsequence evenly),it can be proved that $f(x)\\leq x^2$ So, we need $\\dfrac{n}S\\times S^2$ operations to construct all consecutive subsequences. So in total, $nS+\\dfrac{nq}S$ operations are needed. According to the mean inequality, there is $nS+\\dfrac{nq}S\\geq 2\\sqrt{n^2q}=2n\\sqrt{q}$, and if $S=\\sqrt{q}$, $nS+\\dfrac{nq}S=2\\sqrt{n^2q}=2n\\sqrt{q}$ And, $2n\\sqrt{q}\\leq 2^{21}< 2.2\\times 10^6$, thus the restriction is satisfied. Also, there exists a solution based on segment-tree. The main idea is to maintain a segment-tree of $1$ to $n$, in each node, we save a hash-map of sets with elements in the range of that node already constructed. Anytime we want a new set, we do a query on the segment tree, if the set on that node is constructed, we return it. Otherwise, we split the wanted set into two parts, and query on its sons, and merge them. The details is omitted due to laziness issue. And we find that this solution can pass, why? Suppose $n=2^N$ and $q=2^Q$ We can calculate that we need no more than $\\sum_{i=0}^n 2^{N-i}\\min(2^{2i-1},2^Q)$ sets. This is because in the $i$th layer(bottom to top) of the segment-tree, there are $2^{N-i}$ nodes, each one can contain no more than $2^i(2^i-1)/2$ sets (the consecutive subsegment limitation). but it is also bounded by $2^Q$ queries, because a query can only visit a node at most once. Calculating this sum yield a bound lower that the resiriction. Also we can find that this solution is similar to the previous sol. We find that For $i \\leq Q/2$,the sum is $\\sum_{i=0}^{Q/2} 2^{N-i}2^{2i-1}= \\sum_{i=0}^{Q/2} 2^{N+i-1}\\leq 2^{N+Q/2}$ And for $i> Q/2$ the sum is $2^Q \\sum_{i=Q/2+1}^N 2^{N-i}\\leq 2^Q 2^{N-Q/2}=2^{N+Q/2}$ Summing these two parts yield $2^{N+Q/2+1}$ which is also $2n\\sqrt{q}$ So these solutions have the same complexity. Other than that, we observe that the lower-$Q/2$ layers is just like those blocks constructed in the first solution, only the merging in the upper one is different, the first solution used brute-force, while the second just extended the segment-tree up. Thus, we say that the first solution is just the second one, but bounded manually. So these two solutions are intrinsically similar.",
    "tags": [
      "constructive algorithms",
      "divide and conquer"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1375",
    "index": "I",
    "title": "Cubic Lattice",
    "statement": "A cubic lattice $L$ in $3$-dimensional euclidean space is a set of points defined in the following way: $$L=\\{u \\cdot \\vec r_1 + v \\cdot \\vec r_2 + w \\cdot \\vec r_3\\}_{u, v, w \\in \\mathbb Z}$$ Where $\\vec r_1, \\vec r_2, \\vec r_3 \\in \\mathbb{Z}^3$ are some integer vectors such that:\n\n- $\\vec r_1$, $\\vec r_2$ and $\\vec r_3$ are pairwise orthogonal: $$\\vec r_1 \\cdot \\vec r_2 = \\vec r_1 \\cdot \\vec r_3 = \\vec r_2 \\cdot \\vec r_3 = 0$$ Where $\\vec a \\cdot \\vec b$ is a dot product of vectors $\\vec a$ and $\\vec b$.\n- $\\vec r_1$, $\\vec r_2$ and $\\vec r_3$ all have the same length: $$|\\vec r_1| = |\\vec r_2| = |\\vec r_3| = r$$\n\nYou're given a set $A=\\{\\vec a_1, \\vec a_2, \\dots, \\vec a_n\\}$ of integer points, $i$-th point has coordinates $a_i=(x_i;y_i;z_i)$. Let $g_i=\\gcd(x_i,y_i,z_i)$. It is guaranteed that $\\gcd(g_1,g_2,\\dots,g_n)=1$.You have to find a cubic lattice $L$ such that $A \\subset L$ and $r$ is the maximum possible.",
    "tutorial": "$2$-dimensional version of this problem appeared as problem K in Makoto Soejima Contest 4 from Petrozavodsk Winter Training Camp 2016 (Also known as GP of Asia in OpenCup XVI). Solution for this case is based on the fact that the whole lattice equation may be represented as the product of two Gaussian integers $a_k = \\alpha_k \\cdot g$, where $g$ is the complex number representing $(\\vec r_1, \\vec r_2)$ basis. Thus, the solution was to find largest $g$ which divides every point $a_k$. This can be done with Euclidean algorithm. Similar idea applies to this problem except for rotations in $3$-dimensional case are represented with quaternions rather than complex numbers. You may get some basic notion of quaternions from this article. Note that in $3$-dimensional space if integer vectors $\\vec r_1$, $\\vec r_2$ and $\\vec r_3$ are pairwise orthogonal and have the same length, then their length is an integer number as well. This is due to the fact that $\\vec r_3$ may be represented explicitly in the following form: $\\vec r_3 = \\pm\\frac{\\vec r_1 \\times \\vec r_2}{|r_1|}$ We should note here that both $\\vec r_3$ and $\\vec r_1 \\times \\vec r_2$ have integer coordinates, thus $|r_1|$ is rational. But since $|r_1|^2$ is integer, we may conclude that $|r_1|$ is integer as well. This brings us to the conclusion that vectors $\\frac{\\vec r_1}{|\\vec r_1|}$, $\\frac{\\vec r_2}{|\\vec r_2|}$ and $\\frac{\\vec r_3}{|\\vec r_3|}$ have rational coordinates, thus the transformation which maps basis vectors $\\vec e_x$, $\\vec e_y$ and $\\vec e_z$ into $\\vec r_1$, $\\vec r_2$ and $\\vec r_3$ may be represented as the combination of rational rotation and scaling, that is: $\\vec v \\mapsto k \\cdot \\frac{q \\cdot \\vec v \\cdot \\bar q}{q \\cdot \\bar q}$ Here $q = s + ix + jy + kz$ is an integer quaternion representing the rotation, $\\bar q = s - ix - jy - kz$ is its conjugate quaternion, and $k=r$ is some integer scaling factor. If we write this transform explicitly in matrix form, its matrix will be as follows: $\\frac{k}{s^2+x^2+y^2+z^2} \\cdot \\begin{pmatrix} s^2+x^2-y^2-z^2 & 2xy-2sz & 2xz+2sy \\\\ 2xy+2sz & s^2-x^2+y^2-z^2 & 2yz-2sx \\\\ 2xz-2sy & 2yz+2sx & s^2-x^2-y^2+z^2 \\end{pmatrix}$ Since this transform maps $\\vec e_x$, $\\vec e_y$ and $\\vec e_z$ to integer vectors $\\vec r_1$, $\\vec r_2$ and $\\vec r_3$, all matrix elements should be integer. That is, if we reduce the fraction $\\frac{k}{s^2+x^2+y^2+z^2}$, its denominator should divide every matrix element. Without loss of generality we may assume that $\\gcd(s,x,y,z)=1$, because otherwise we may simply reduce all quaternion coordinates by this common divisor and matrix elements will stay same. Now if $\\frac{k}{s^2+x^2+y^2+z^2}=\\frac{P}{Q}$ then $Q$ should divide every element of the matrix and it also should divide $s^2+x^2+y^2+z^2$. Thus, it divides: $\\gcd\\begin{pmatrix} s^2+x^2+y^2+z^2\\\\ s^2+x^2-y^2-z^2\\\\ s^2-x^2+y^2-z^2\\\\ s^2-x^2-y^2+z^2 \\end{pmatrix}=\\gcd\\begin{pmatrix} s^2+x^2+y^2+z^2\\\\ 2(y^2+z^2)\\\\ 2(x^2+z^2)\\\\ 2(x^2+y^2) \\end{pmatrix}=\\gcd\\begin{pmatrix} s^2+x^2+y^2+z^2\\\\ 2(y^2+z^2)\\\\ 2(x^2+z^2)\\\\ 4z^2 \\end{pmatrix}$ Here we utilized the fact that $\\gcd(a\\pm b, b)=\\gcd(a, b)=\\gcd(-a,b)$. Next thing to note is that $\\gcd(a, b)$ always divides $\\gcd(k\\cdot a, b)$, thus $Q$ should divide: $\\gcd\\begin{pmatrix} 4(s^2+x^2+y^2+z^2)\\\\ 4(y^2+z^2)\\\\ 4(x^2+z^2)\\\\ 4z^2 \\end{pmatrix}=4\\gcd(s^2,x^2,y^2,z^2)=4$ Which means that every transform we're looking for may be represented in the following form: $\\vec v \\mapsto \\frac{k}{4} \\cdot q \\cdot \\vec v \\cdot \\bar q$ Where $q$ is some integer quaternion with $\\gcd(s,x,y,z)=1$ and $k$ is some integer scaling factor. Quaternions having all integer components are called Lipschitz quaternions. But in this problem we will need to find greatest common divisor of some quaternions and using Lipschitz quaternions won't be enough for us because they don't form an Euclidean domain. Instead, we'll stick to Hurwitz quaternions in which it's also allowed for quaternion to have all of its coordinates semi-integer. With such quaternions we may further divide quaternion by $2$ if all its components are odd, which will reduce the set of possible denominators to $\\{1,2\\}$ only, thus in Hurwitz quaternions any transform may be represented as: $\\vec v \\mapsto \\frac{k}{2} \\cdot q \\cdot \\vec v \\cdot \\bar q$ Now, given this knowledge, we have to find a Hurwitz quaternion $q$ and scaling factor $k$ such that every point from the set $A$ is the image of some integer vector under this transform. Basically, we assume here that $\\vec r_1$, $\\vec r_2$ and $\\vec r_3$ are images of unit basis vectors $\\vec e_x$, $\\vec e_y$ and $\\vec e_z$. If this is true, then $a_k = u_k \\cdot \\vec r_1 + v_k \\cdot \\vec r_2 + w_k \\cdot \\vec r_3$ is the image of the vector $b_k$ defined as $b_k = u_k \\cdot \\vec e_x + v_k \\cdot \\vec e_y + w_k \\cdot \\vec e_z$. For simplicity we will further work with vectors $a_i$ multiplied by $2$, as in this way we may safely assume that they were obtained with $v \\mapsto k \\cdot q \\cdot \\vec v \\cdot \\bar q$ mapping. Now we should further work with the quaternion $g=\\gcd(a_1,\\dots,a_n)$ which is obtained as GCD of input vectors as if they were Hurwitz quaternions and with the number $G=\\gcd(\\|a_1\\|,\\dots,\\|a_n\\|)$, where $\\|q\\|=q\\cdot\\bar q = s^2+x^2+y^2+z^2$ is the norm of $q$. Among major properties of quaternionic norm we should note that it's multiplicative, that is $\\|a\\cdot b\\| =\\|a\\| \\cdot \\|b\\|$. Due to this we may conclude that $\\|k\\|\\cdot \\|q\\|^2=k^2 \\|q\\|^2$ should always divide $G$. Thus with the number $G$ fixed there may only be at most $O(G^{1/6})$ possible values of $\\|q\\|$ which may be found in $O(G^{1/3})$ because if $a^2$ divides $b$ then either $a$ or $b/a$ is at most $b^{1/3}$. In our problem $G$ may only be up to $10^{16}$, which makes it up to nearly $500$ candidate numbers for being equal to $\\|q\\|$ which may be found in $\\approx 2.5\\cdot 10^5$ arithmetic operations. Now to check if it's possible to obtain $q$ with $\\|q\\|$ being fixed we should look on the quaternion $g$. Under given constraints $g$ is primitive (not divisible by any integer constant larger than $1$). It may be proven thus that if $g$ is primitive and $\\|g\\|=ab$ then $g$ may be uniquely (up to units) represented as $g=qp$ where $\\|q\\|=a$ and $\\|p\\|=b$. Due to this if we fix $\\|q\\|$ we may find actual $q$ as $\\gcd(g,\\|q\\|)$ because $q\\bar q =\\|q\\|$. After this we only have to check if this $q$ actually produces all points from the input set, which may be done in $O(n)$. Therefore, the total complexity of described solution is $O(G^{1/3}+G^{1/6}n)$.",
    "tags": [
      "geometry",
      "math",
      "matrices",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1379",
    "index": "A",
    "title": "Acacius and String",
    "statement": "Acacius is studying strings theory. Today he came with the following problem.\n\nYou are given a string $s$ of length $n$ consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string \"abacaba\" occurs as a substring in a resulting string exactly once?\n\nEach question mark should be replaced with \\textbf{exactly one} lowercase English letter. For example, string \"a?b?c\" can be transformed into strings \"aabbc\" and \"azbzc\", but can't be transformed into strings \"aabc\", \"a?bbc\" and \"babbc\".\n\nOccurrence of a string $t$ of length $m$ in the string $s$ of length $n$ as a substring is a index $i$ ($1 \\leq i \\leq n - m + 1$) such that string $s[i..i+m-1]$ consisting of $m$ consecutive symbols of $s$ starting from $i$-th equals to string $t$. For example string \"ababa\" has two occurrences of a string \"aba\" as a substring with $i = 1$ and $i = 3$, but there are no occurrences of a string \"aba\" in the string \"acba\" as a substring.\n\nPlease help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string \"abacaba\" occurs as a substring in a resulting string \\textbf{exactly once}.",
    "tutorial": "At first, we will check if some string of length $n$ contains exactly one occurrence of \"abacaba\". Lemma 1. This check can be done in $O(n)$ time. Proof. We can try all the possible positions $i$ of a string $s$ and check whether $i$ is a starting position for a substring \"abacaba\". This check can be performed in a $O(1)$ time by checking if $s_{i + j} = t_j$ for all $j \\in [0; 6]$ where string $t$ is \"abacaba\". So, overall complexity of such a check works in $n \\cdot O(1) = O(n)$ time. To solve the problem we will iterate over all positions $i$ and check whether there exists a valid string such that its single occurrence of a substring \"abacaba\" starts from position $i$. String $s$ has a single occurrence $i$ of a substring \"abacaba\" if and only if two following criteria are satisfied. $i$ is a occurrence of a substring \"abacaba\" in $s$. There are no occurrence $j$ of a substring \"abacaba\" in $s$ such that $i \\neq j$. First criterion can be checked directly. $i$ can be an occurrence of a substring \"abacaba\" in a resulting string if and only if for all $j \\in [0; 6]$ $s_{i + j} = t_j$ or $s_{i + j} = '?'$. To check the second criterion we need the following lemma. Lemma 2. Question marks in string $s$ can be replaced with lowercase English letters in such a way that no new occurrences of \"abacaba\" will appear. Proof. Let's replace all the questing marks with \"z\" letter. Any substring of $s$ that contained question mark will not become a occurrence of \"abacaba\" since \"abacaba\" does not contain \"z\". So after fixing position of a single occurrence $i$ resulting string can be constructed directly. This leads to a $O(n^2)$ solution. Refer to author's solution code for more details.",
    "code": "#include <bits/stdc++.h>\n\nusing ll = long long;\nusing ld = long double;\nusing ull = unsigned long long;\n\nusing namespace std;\n\nconst string T = \"abacaba\";\n\nint count(const string& s) {\n    int cnt = 0;\n    for (int i = 0; i < (int)s.size(); ++i) {\n        if (s.substr(i, T.size()) == T) {\n            ++cnt;\n        }\n    }\n\n    return cnt;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    int t;\n    cin >> t;\n    for (int tt = 1; tt <= t; ++tt) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        bool F = false;\n\n        for (int i = 0; i + T.size() <= n; ++i) {\n            string ss = s;\n            bool ok = true;\n            for (int j = 0; j < T.size(); j++) {\n                if (ss[i + j] != '?' && ss[i + j] != T[j]) {\n                    ok = false;\n                    break;\n                }\n                ss[i + j] = T[j];\n            }\n            if (ok && count(ss) == 1) {\n                for (int j = 0; j < n; j++) {\n                    if (ss[j] == '?') {\n                        ss[j] = 'd';\n                    }\n                }\n                F = true;\n                cout << \"Yes\\n\";\n                cout << ss << \"\\n\";\n                break;\n            }\n        }\n        if (!F) {\n            cout << \"No\\n\";\n        }\n    }\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1379",
    "index": "B",
    "title": "Dubious Cyrpto",
    "statement": "Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer $n$, he encrypts it in the following way: he picks three integers $a$, $b$ and $c$ such that $l \\leq a,b,c \\leq r$, and then he computes the encrypted value $m = n \\cdot a + b - c$.\n\nUnfortunately, an adversary intercepted the values $l$, $r$ and $m$. Is it possible to recover the original values of $a$, $b$ and $c$ from this information? More formally, you are asked to find any values of $a$, $b$ and $c$ such that\n\n- $a$, $b$ and $c$ are integers,\n- $l \\leq a, b, c \\leq r$,\n- there exists a strictly positive integer $n$, such that $n \\cdot a + b - c = m$.",
    "tutorial": "The task is to solve equation $n\\cdot a + b - c = m$ in integers, where $n$ - is some natural number, and $a, b, c \\in [l; r]$. Note that the expression $b - c$ can take any value from $[l-r; r-l]$ and only these values. Indeed, if $0 \\leq x \\leq r-l$, then if we denote $b = x + l$, $c = l$, we get $b - c = x$. A similar statement is true for $l - r \\leq x \\leq 0$. So, since it was necessary to solve the equation $n\\cdot a + b - c = m$, this is equivalent to solving the equation $n \\cdot a \\in [m - (r - l); m + (r - l)]$, where $a \\in [l; r]$, $n \\in \\mathbb N$. Let's fix some arbitrary $a$. Then we find the maximum $n$ for which $n\\cdot a \\leq m + (r - l)$ - this $n$ will be equal to $n' = \\lfloor \\frac{m + r - l}{a} \\rfloor$. Let's check whether it is true that $n' > 0$ and $n' \\cdot a \\in [m- (r-l); m + (r - l)]$. If this is the case, then restore $b$ and $c$ as indicated above. This solution iterates over all possible values of $a$, and checks if such $a$ can be used in answer if the manner described above. Thus, this solution has complexity $\\mathcal O (r - l)$",
    "tags": [
      "binary search",
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1379",
    "index": "C",
    "title": "Choosing flowers",
    "statement": "Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her \\textbf{exactly} $n$ flowers.\n\nVladimir went to a flower shop, and he was amazed to see that there are $m$ types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers to maximize the happiness of his wife. He knows that after receiving the first flower of the $i$-th type happiness of his wife increases by $a_i$ and after receiving each consecutive flower of this type her happiness increases by $b_i$. That is, if among the chosen flowers there are $x_i > 0$ flowers of type $i$, his wife gets $a_i + (x_i - 1) \\cdot b_i$ additional happiness (and if there are no flowers of type $i$, she gets nothing for this particular type).\n\nPlease help Vladimir to choose exactly $n$ flowers to maximize the total happiness of his wife.",
    "tutorial": "Let's look at sorts, for which there is more than one flower in the bouquet. We can prove, that there can be only one such sort. Let's assume that there are sorts $x$ and $y$ with $b_x \\ge b_y$, such that for both sorts there are at least 2 flowers. Let's exclude flower of sort $y$ from bouquet and add flower of sort $x$. The total happiness will change by $b_x - b_y$, so it will not decrease. Repeating this, we can leave bouquet with only one flower of sort $y$ without decreasing the total happiness. So, there always exists an answer where there is only one sort with multiple flowers. Using this fact, we can solve the problem the following way. Let's iterate over each sort of flowers and for every $x$ suppose that there are multiple flowers of sort $x$. It is obvious, that if some sort $y$ has $a_y > b_x$, then we should take one flower of such sort, and if $a_y \\le b_x$, then we would better take another flower of sort $x$. So, we need to know sum of $a_i$ for all flowers that have $a_i > b_x$. To do it in $O(\\log m)$, we can sort all flowers by $a_y$ in decreasing order, calculate prefix sums on that array, and using binary search find maximum $k$, such that $a_k > b_x$ and get prefix sum of $a_i$ for first $k$ sorts. All the rest $n - k$ flowers will be of the sort $x$. Also we should take into account the case when for each sort only one flower of that sort is taken. In that case we should take $n$ sorts with largest $a_i$. That way we can get the answer in $O(m \\log m)$ time.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1379",
    "index": "D",
    "title": "New Passenger Trams",
    "statement": "There are many freight trains departing from Kirnes planet every day. One day on that planet consists of $h$ hours, and each hour consists of $m$ minutes, where $m$ is an even number. Currently, there are $n$ freight trains, and they depart every day at the same time: $i$-th train departs at $h_i$ hours and $m_i$ minutes.\n\nThe government decided to add passenger trams as well: they plan to add a regular tram service with half-hour intervals. It means that the first tram of the day must depart at $0$ hours and $t$ minutes, where $0 \\le t < {m \\over 2}$, the second tram departs $m \\over 2$ minutes after the first one and so on. This schedule allows exactly two passenger trams per hour, which is a great improvement.\n\nTo allow passengers to board the tram safely, the tram must arrive $k$ minutes before. During the time when passengers are boarding the tram, no freight train can depart from the planet. However, freight trains are allowed to depart at the very moment when the boarding starts, as well as at the moment when the passenger tram departs. Note that, if the first passenger tram departs at $0$ hours and $t$ minutes, where $t < k$, then the freight trains can not depart during the last $k - t$ minutes of the day.\n\n\\begin{center}\n{\\small A schematic picture of the correct way to run passenger trams. Here $h=2$ (therefore, the number of passenger trams is $2h=4$), the number of freight trains is $n=6$. The passenger trams are marked in red (note that the spaces between them are the same). The freight trains are marked in blue. Time segments of length $k$ before each passenger tram are highlighted in red. Note that there are no freight trains inside these segments.}\n\\end{center}\n\nUnfortunately, it might not be possible to satisfy the requirements of the government without canceling some of the freight trains. Please help the government find the optimal value of $t$ to minimize the number of canceled freight trains in case all passenger trams depart according to schedule.",
    "tutorial": "Let's look what happens if we fix $t$ for answer. Start time leads to canceling every train, which has $m_i$ in one of ranges $[t - k + 1, t - 1],\\ [t + \\frac{m}{2} - k + 1, t + \\frac{m}{2} - 1]$. Some borders may be either negative or greater than $m$, but values must be count modulo $m$. We may imagine them as segments on a circle with length m. Now let's look at every train. If train departs at $m_i$ then it must be canceled if we choose $t$ in segments $[m_i + 1, m_i + k - 1],\\ [m_i + \\frac{m}{2} + 1, m_i + \\frac{m}{2} + k - 1]$. Otherwise it shouldn't be canceled. So, we need to find such point $t$ in $[0, \\frac{m}{2} - 1]$, that $t$ is covered by minimal number of segments. Note that we block two simmetrical segments - difference between their borders is equal to half of circle's length. Cause we need only segments in first half of the cycle, we can look at these segments modulo $\\frac{m}{2}$, where they collapse into one segment. Now we need to sort segment's borders. Segments are placed on circle, so some of them should be split in two - one ends in $\\frac{m}{2} - 1$, another starts at $0$. Now we need to find point, which is covered by minimal number of segments. For that we will keep a variable counting current number of open segments, and change it from one coordinate to another. We can skip coordinates with no events on them, so all solution will take $O(n \\log n)$ time to solve.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "sortings",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1379",
    "index": "E",
    "title": "Inverse Genealogy",
    "statement": "Ivan is fond of genealogy. Currently he is studying a particular genealogical structure, which consists of some people. In this structure every person has either both parents specified, or none. Additionally, each person has exactly one child, except for one special person, who does not have any children. The people in this structure are conveniently numbered from $1$ to $n$, and $s_i$ denotes the child of the person $i$ (and $s_i = 0$ for exactly one person who does not have any children).\n\nWe say that $a$ is an ancestor of $b$ if either $a = b$, or $a$ has a child, who is an ancestor of $b$. That is $a$ is an ancestor for $a$, $s_a$, $s_{s_a}$, etc.\n\nWe say that person $i$ is imbalanced in case this person has both parents specified, and the total number of ancestors of one of the parents is at least double the other.\n\nIvan counted the number of imbalanced people in the structure, and got $k$ people in total. However, he is not sure whether he computed it correctly, and would like to check if there is at least one construction with $n$ people that have $k$ imbalanced people in total. Please help him to find one such construction, or determine if it does not exist.",
    "tutorial": "Let's rephrase the statement. Critical node - a non-leaf node with subtrees, where one $2$ or more times smaller than another. We need to find an example of the binary tree with $n$ nodes there $k$ of them are critical. First of all, let's count number of nodes if we know that there $m$ leafs. Because of the fact, that tree is binary, size of the tree should be $2m - 1$. So for even $n$ there is no answer. A number of critical nodes can't be more than $max\\left(0, \\frac{n - 3}{2}\\right)$. It is obvious that caterpillar tree have maximum number of critical nodes. Let's say that $n$ is almost a power of two then $n + 1$ is a power of two. If there $0$ critical nodes, then $n$ is almost a power of two (example full binary tree). Suppose exist trees that don't satisfy the condition. Let's look on the smallest one. Left and right subtrees satisfy the condition. If they are different, then one of them $2$ times bigger than another and root is critical. If they are have equal sizes, then our tree satisfied the condition. If there $1$ critical nodes, then $n$ isn't almost a power of two. Suppose there exist trees that don't satisfy the condition. Let's look on the smallest one. One of the subtrees is almost a power of two. If both subtrees are almost a power of two, then they are equal and there is no critical nodes. In other case, the root isn't critical. Then second subtree isn't almost a power of two. If we write two inequalities with the size of the tree and the size of the first subtree, then it becomes clear that size of the tree can't be almost a power of two. How to construct an example with $1$ critical node? Let $m$ be some integer that: $2^m < n < 2^{m + 1}$. It can be shown that one subtree in answer can be equals $2^{m} - 1$ or $2^{m - 1} - 1$. And finally, what we should do when $k \\geq 2$? Let's go from $(n, k)$ to $(n - 2, k - 1)$. If $n \\geq 13$ we can just make one subtree size of $1$. In other cases we should precalculate answers. So we have solution with complexity $O(n)$. The easy way to write a solution is make a function $can(n, k)$ that return True if there exists needed tree and else False. Then we can find the smallest subtree with simple brute force. In this case complexity is $O(n \\log n)$.",
    "tags": [
      "constructive algorithms",
      "divide and conquer",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1379",
    "index": "F1",
    "title": "Chess Strikes Back (easy version)",
    "statement": "\\textbf{Note that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.}\n\nIldar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The field is a chessboard $2n \\times 2m$: it has $2n$ rows, $2m$ columns, and the cell in row $i$ and column $j$ is colored white if $i+j$ is even, and is colored black otherwise.\n\nThe game proceeds as follows: Ildar marks some of the \\textbf{white} cells of the chessboard as unavailable, and asks Ivan to place $n \\times m$ kings on the remaining \\textbf{white} cells in such way, so that there are no kings attacking each other. A king can attack another king if they are located in the adjacent cells, sharing an edge or a corner.\n\nIldar would like to explore different combinations of cells. Initially all cells are marked as available, and then he has $q$ queries. In each query he marks a cell as unavailable. After each query he would like to know whether it is possible to place the kings on the available cells in a desired way. Please help him!",
    "tutorial": "Let's divide the grid into $nm$ squares of size $2 \\times 2$. Each square contains exactly two white cells. So, we should put exactly one king into one square. Let's mark a square L, if its left upper cell is banned and R if its right down cell is banned. Square can be L and R at the same time. If there exists some L-square $(x_1, y_1)$ and R-square $(x_2, y_2)$, such that: $x_1 \\leq x_2$ $y_1 \\leq y_2$ the answer is NO. It's easy to prove because if such pair of cells exists we can consider path from $(x_1, y_1)$ to $(x_2, y_2)$. In this path, there will be two neighboring cells. If no such pairs of cells exist the answer is YES. Note that in this version of the problem cells cannot become available againg. This means that for some prefix of queries the answer is YES and for the remaining suffix the answer is NO. Let's do a binary search to find position of the last YES. How to check that the answer is YES fast enough? Let's calculate the values: $a_x =$ minimal $y$, such that $(x, y)$ is L-square $b_x =$ maximal $y$, such that $(x - 1, y)$ is R-square After that, we should check, that $a_i > b_j$ for all $i > j$. We can easily do this using prefix maximums for $a$ and suffix minimums for $b$ Total complexity is $O((n+q) \\log{q})$.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1379",
    "index": "F2",
    "title": "Chess Strikes Back (hard version)",
    "statement": "\\textbf{Note that the difference between easy and hard versions is that in hard version unavailable cells can become available again and in easy version can't. You can make hacks only if all versions are solved.}\n\nIldar and Ivan are tired of chess, but they really like the chessboard, so they invented a new game. The field is a chessboard $2n \\times 2m$: it has $2n$ rows, $2m$ columns, and the cell in row $i$ and column $j$ is colored white if $i+j$ is even, and is colored black otherwise.\n\nThe game proceeds as follows: Ildar marks some of the \\textbf{white} cells of the chessboard as unavailable, and asks Ivan to place $n \\times m$ kings on the remaining \\textbf{white} cells in such way, so that there are no kings attacking each other. A king can attack another king if they are located in the adjacent cells, sharing an edge or a corner.\n\nIldar would like to explore different combinations of cells. Initially all cells are marked as available, and then he has $q$ queries. In each query he either marks a cell as unavailable, or marks the previously unavailable cell as available. After each query he would like to know whether it is possible to place the kings on the available cells in a desired way. Please help him!",
    "tutorial": "Let's divide the grid into $nm$ squares of size $2 \\times 2$. Each square contains exactly two white cells. So, we should put exactly one king into one square. Let's mark a square L, if its left upper cell is banned and R if its right down cell is banned. Square can be L and R at the same time. If there exists some L-square $(x_1, y_1)$ and R-square $(x_2, y_2)$, such that: $x_1 \\leq x_2$ $y_1 \\leq y_2$ the answer is NO. It's easy to prove because if such pair of cells exists we can consider path from $(x_1, y_1)$ to $(x_2, y_2)$. In this path, there will be two neighboring cells. If no such pairs of cells exist the answer is YES. So, after each query, we should check this condition. Let's maintain the values: $a_x =$ minimal $y$, such that $(x, y)$ is L-square $b_x =$ maximal $y$, such that $(x - 1, y)$ is R-square These values can be maintained using $O(n)$ sets in $O(\\log{q})$ time. After that, we should check, that $a_i > b_j$ for all $i > j$. Let's make a segment tree with values: minimal $a_i$ on segment maximal $b_i$ on segment the flag, that for all $i > j$ from the segment it is true, that $a_i > b_j$ It is easy to merge two such segments, to calculate the flag, we should check, that $min_{left} > max_{right}$. So, the total time to answer the query is $O(\\log{n}+\\log{q})$. Total complexity is $O((n+q)(\\log{n}+\\log{q}))$.",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1380",
    "index": "A",
    "title": "Three Indices",
    "statement": "You are given a permutation $p_1, p_2, \\dots, p_n$. Recall that sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.\n\nFind three indices $i$, $j$ and $k$ such that:\n\n- $1 \\le i < j < k \\le n$;\n- $p_i < p_j$ and $p_j > p_k$.\n\nOr say that there are no such indices.",
    "tutorial": "A solution in $O(n^2)$: iterate on $j$, check that there exists an element lower than $a_j$ to the left of it, and check that there exists an element lower than $a_j$ to the right of it. Can be optimized to $O(n)$ with prefix/suffix minima. A solution in $O(n)$: note that if there is some answer, we can find an index $j$ such that $a_{j - 1} < a_j$ and $a_j > a_{j + 1}$ (if there is no such triple, the array descends to some point and ascends after that, so there is no answer). So we only have to check $n - 2$ consecutive triples.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000;\n\nint n;\nint a[N];\n\nvoid solve() {\n\tcin >> n;\n\tfor (int i = 0; i < n; ++i)\n\t\tcin >> a[i];\n\tfor (int i = 1; i < n - 1; ++i) {\n\t\tif (a[i] > a[i - 1] && a[i] > a[i + 1]) {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tcout << i << ' ' << i + 1 << ' ' << i + 2 << endl;\n\t\t\treturn;\n\t\t}\n\t}\n\tcout << \"NO\" << endl;\n}\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile (T--)\n\t\tsolve();\n}",
    "tags": [
      "brute force",
      "data structures"
    ],
    "rating": 900
  },
  {
    "contest_id": "1380",
    "index": "B",
    "title": "Universal Solution",
    "statement": "Recently, you found a bot to play \"Rock paper scissors\" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $s = s_1 s_2 \\dots s_{n}$ of length $n$ where each letter is either R, S or P.\n\nWhile initializing, the bot is choosing a starting index $pos$ ($1 \\le pos \\le n$), and then it can play any number of rounds. In the first round, he chooses \"Rock\", \"Scissors\" or \"Paper\" based on the value of $s_{pos}$:\n\n- if $s_{pos}$ is equal to R the bot chooses \"Rock\";\n- if $s_{pos}$ is equal to S the bot chooses \"Scissors\";\n- if $s_{pos}$ is equal to P the bot chooses \"Paper\";\n\nIn the second round, the bot's choice is based on the value of $s_{pos + 1}$. In the third round — on $s_{pos + 2}$ and so on. After $s_n$ the bot returns to $s_1$ and continues his game.\n\nYou plan to play $n$ rounds and you've already figured out the string $s$ but still don't know what is the starting index $pos$. But since the bot's tactic is so boring, you've decided to find $n$ choices to each round to maximize the average number of wins.\n\nIn other words, let's suggest your choices are $c_1 c_2 \\dots c_n$ and if the bot starts from index $pos$ then you'll win in $win(pos)$ rounds. Find $c_1 c_2 \\dots c_n$ such that $\\frac{win(1) + win(2) + \\dots + win(n)}{n}$ is maximum possible.",
    "tutorial": "Let's look at the contribution of each choice $c_i$ to the total number of wins $win(1) + win(2) + \\dots + win(n)$ (we can look at \"total\" instead of \"average\", since \"average\" is equal to \"total\" divided by $n$). For example, let's look at the first choice $c_1$: in $win(1)$ we compare $c_1$ with $s_1$, in $win(2)$ - $c_1$ with $s_2$, in $win(3)$ - $c_1$ with $s_3$ and so on. In the result, we compare $c_1$ with all $s_i$ once. So, to maximize the total sum, we need to choose $c_1$ that beats the maximum number of $s_i$ or, in other words, let's find the most frequent character in $s$ and choose $c_1$ that beats it. Okay, we found the optimal $c_1$. But if we look at the contribution of any other $c_i$ we can note that we compare any $c_i$ with all $s_i$ once. So we can choose all $c_i$ equal to $c_1$ which is equal to the choice that beats the most frequent choice in $s$.",
    "code": "fun main() {\n    val winBy = mapOf('R' to 'P', 'S' to 'R', 'P' to 'S')\n    repeat(readLine()!!.toInt()) {\n        val s = readLine()!!\n        val maxCnt = s.groupingBy { it }.eachCount().maxBy { it.value }!!.key\n        println(\"${winBy[maxCnt]}\".repeat(s.length))\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1380",
    "index": "C",
    "title": "Create The Teams",
    "statement": "There are $n$ programmers that you want to split into several non-empty teams. The skill of the $i$-th programmer is $a_i$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least $x$.\n\nEach programmer should belong to at most one team. Some programmers may be left without a team.\n\nCalculate the maximum number of teams that you can assemble.",
    "tutorial": "At first, notice that if only $k < n$ programmers are taken, then the same or even better answer can be achieved if $k$ strongest programmers are taken. Now let's sort the programmers in a non-increasing order and choose some assignment into the teams. For each team only the rightmost taken programmer of that team matters (the sorted sequence implies that the rightmost is the weakest). Take a look at the team with the strongest weakest member. If the number of programmers in it is less than the position of the weakest member, then you can safely rearrange the programmers before him in such a way that none of parameters of later teams change and the weakest member in the first one only becomes stronger. After that you can get rid of the first team (as it takes exactly the prefix of all the programmers) and proceed to fix the later teams. Thus, we can see that there is an optimal solution such that each team is a segment and all the teams together take some prefix of the programmers. So we can finally run a greedy solution that takes programmers from left to right and increases the answer if the conditions for the latest team hold. Overall complexity: $O(n \\log n)$.",
    "code": "for _ in range(int(input())):\n    n, x = map(int, input().split())\n    a = sorted(list(map(int, input().split())), reverse=True)\n    res, cur = 0, 1\n    for s in a:\n        if s * cur >= x:\n            res += 1\n            cur = 0\n        cur += 1\n    print(res)\n    ",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1380",
    "index": "D",
    "title": "Berserk And Fireball",
    "statement": "There are $n$ warriors in a row. The power of the $i$-th warrior is $a_i$. All powers are pairwise distinct.\n\nYou have two types of spells which you may cast:\n\n- Fireball: you spend $x$ mana and destroy \\textbf{exactly} $k$ consecutive warriors;\n- Berserk: you spend $y$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power.\n\nFor example, let the powers of warriors be $[2, 3, 7, 8, 11, 5, 4]$, and $k = 3$. If you cast Berserk on warriors with powers $8$ and $11$, the resulting sequence of powers becomes $[2, 3, 7, 11, 5, 4]$. Then, for example, if you cast Fireball on consecutive warriors with powers $[7, 11, 5]$, the resulting sequence of powers becomes $[2, 3, 4]$.\n\nYou want to turn the current sequence of warriors powers $a_1, a_2, \\dots, a_n$ into $b_1, b_2, \\dots, b_m$. Calculate the minimum amount of mana you need to spend on it.",
    "tutorial": "The first thing we need to do is to find the occurrences of $b_i$ in the sequence $[a_1, a_2, \\dots, a_n]$ - these are the monsters that have to remain. Since both spells (Fireball and Berserk) affect consecutive monsters, we should treat each subsegment of monsters we have to delete separately. Consider a segment with $x$ monsters we have to delete such that the last monster before it has power $l$, the first monster after the segment has power $r$, and the strongest monster on the segment has power $p$. If $x \\bmod k \\ne 0$, then we have to use Berserk at least $x \\bmod k$ times. Let's make the strongest monster on segment kill some other monster. If $x < k$, then the strongest monster should also be killed by one of the monsters bounding the segment, so if $l < p$ and $r < p$, there is no solution. Okay, now the number of monsters is divisible by $k$. If it is more profitable to use Fireball, we use the required number of Fireballs to kill all of them. Otherwise, we have to kill the maximum possible number of monsters with Berserk and finish the remaining ones with Fireball. If $l > p$ or $r > p$, then one of the monsters just outside the segment can kill all the monsters inside the segment; otherwise, the strongest monster should kill adjacent monsters until exactly $k$ remain, and those $k$ monsters are finished with a single Fireball. Now we know what we need to consider when processing a single segment; all that's left is to sum the minimum required mana over all such segments. Since the total length of these segments is at most $n - 1$ and we can process each segment in linear time, we have a solution with complexity $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(2e5) + 9;\n\nint n, m;\nlong long x, k, y;\nint a[N];\nint b[N];\n\nbool upd(int l, int r, long long &res) {\n    if (l > r) return true;\n    bool canDel = false;\n    int mx = *max_element(a + l, a + r + 1);\n    int len = r - l + 1;\n    if (l - 1 >= 0 && a[l - 1] > mx) canDel = true;\n    if (r + 1 < n && a[r + 1] > mx) canDel = true;\n    if (len < k && !canDel) return false;\n    \n    int need = len % k;\n    res += need * y;\n    len -= need;\n    \n    if (y * k >= x) {\n        res += len / k * x;\n    } else if(canDel) {\n        res += len * y;\n    } else {\n        res += (len - k) * y + x;\n    }\n    \n    return true;\n}\n\nint main(){\n    scanf(\"%d %d\", &n, &m);\n    scanf(\"%lld %lld %lld\", &x, &k, &y);\n    for (int i = 0; i < n; ++i) scanf(\"%d\", a + i);\n    for (int i = 0; i < m; ++i) scanf(\"%d\", b + i);\n    \n    long long res = 0;\n    int lst = -1, posa = 0, posb = 0;\n    while (posb < m) {\n        while(posa < n && a[posa] != b[posb]) ++posa;\n        if (posa == n) {\n            puts(\"-1\");\n            return 0;\n        }\n        \n        if (!upd(lst + 1, posa - 1, res)) {\n            puts(\"-1\");\n            return 0;\n        }\n        \n        lst = posa;\n        ++posb;\n    }\n    \n    if (!upd(lst + 1, n - 1, res)) {\n        puts(\"-1\");\n        return 0;\n    }\n    \n    printf(\"%lld\\n\", res);\n    \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1380",
    "index": "E",
    "title": "Merging Towers",
    "statement": "You have a set of $n$ discs, the $i$-th disc has radius $i$. Initially, these discs are split among $m$ towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top.\n\nYou would like to assemble one tower containing all of those discs. To do so, you may choose two different towers $i$ and $j$ (each containing at least one disc), take several (possibly all) top discs from the tower $i$ and put them on top of the tower $j$ in the same order, as long as the top disc of tower $j$ is bigger than each of the discs you move. You may perform this operation any number of times.\n\nFor example, if you have two towers containing discs $[6, 4, 2, 1]$ and $[8, 7, 5, 3]$ (in order from bottom to top), there are only two possible operations:\n\n- move disc $1$ from the first tower to the second tower, so the towers are $[6, 4, 2]$ and $[8, 7, 5, 3, 1]$;\n- move discs $[2, 1]$ from the first tower to the second tower, so the towers are $[6, 4]$ and $[8, 7, 5, 3, 2, 1]$.\n\nLet the difficulty of some set of towers be the minimum number of operations required to assemble one tower containing all of the discs. For example, the difficulty of the set of towers $[[3, 1], [2]]$ is $2$: you may move the disc $1$ to the second tower, and then move both discs from the second tower to the first tower.\n\nYou are given $m - 1$ queries. Each query is denoted by two numbers $a_i$ and $b_i$, and means \"merge the towers $a_i$ and $b_i$\" (that is, take all discs from these two towers and assemble a new tower containing all of them in descending order of their radii from top to bottom). The resulting tower gets index $a_i$.\n\nFor each $k \\in [0, m - 1]$, calculate the difficulty of the set of towers after the first $k$ queries are performed.",
    "tutorial": "First of all, let's try to find a simple way to evaluate the difficulty of a given set of towers. I claim that the difficulty is equal to the number of pairs of discs $(i, i + 1)$ that belong to different towers. The beginning of the proof during each operation we can \"merge\" at most one such pair: if we move discs to the tower with disk $i$ on top of it, only the pair $(i - 1, i)$ can be affected; we can always take the first several $k$ discs belonging to the same tower and move them to the tower containing disc $k + 1$, thus merging exactly one pair in exactly one operation. The end of the proof After that, there are two main approaches: LCA and small-to-large merging. The model solution uses LCA, so I'll describe it. For each pair $(i, i + 1)$, we have to find the first moment these discs belong to the same tower. To do so, let's build a rooted tree on $2m - 1$ vertices. The vertices $1$ to $m$ will be the leaves of the tree and will represent the original towers. The vertex $m + i$ will represent the tower created during the $i$-th query and will have two children - the vertices representing the towers we merge during the $i$-th query. The vertex $2m - 1$ is the root. Now, if some vertex $x$ is an ancestor of vertex $y$, it means that the tower represented by vertex $x$ contains all the discs from the tower represented by vertex $y$. So, to find the first tower containing two discs $i$ and $i + 1$, we have to find the lowest common ancestor of the vertices representing the towers $t_i$ and $t_{i + 1}$. The easiest way to do it is to implement something like binary lifting, which allows us to solve the problem in $O(n \\log m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n, m;\nvector<int> p;\nvector<vector<int>> val;\nvector<int> who;\n\nint getp(int a){\n\treturn a == p[a] ? a : p[a] = getp(p[a]);\n}\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tp.resize(m);\n\tval.resize(m);\n\twho.resize(n);\n\tint ans = n - 1;\n\tforn(i, m)\n\t\tp[i] = i;\n\tforn(i, n){\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\t--x;\n\t\twho[i] = x;\n\t\tans -= (i && who[i] == who[i - 1]);\n\t\tval[who[i]].push_back(i);\n\t}\n\tprintf(\"%d\\n\", ans);\n\tforn(i, m - 1){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\tv = getp(v - 1), u = getp(u - 1);\n\t\tif (val[v].size() < val[u].size())\n\t\t\tswap(v, u);\n\t\tfor (int x : val[u]){\n\t\t\tif (x) ans -= who[x - 1] == v;\n\t\t\tif (x < n - 1) ans -= who[x + 1] == v;\n\t\t}\n\t\tfor (int x : val[u]){\n\t\t\tval[v].push_back(x);\n\t\t\twho[x] = v;\n\t\t}\n\t\tp[u] = v;\n\t\tprintf(\"%d\\n\", ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "implementation",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1380",
    "index": "F",
    "title": "Strange Addition",
    "statement": "Let $a$ and $b$ be some non-negative integers. Let's define strange addition of $a$ and $b$ as following:\n\n- write down the numbers one under another and align them by their least significant digit;\n- add them up digit by digit and concatenate the respective sums together.\n\nAssume that both numbers have an infinite number of leading zeros.\n\nFor example, let's take a look at a strange addition of numbers $3248$ and $908$:\n\nYou are given a string $c$, consisting of $n$ digits from $0$ to $9$. You are also given $m$ updates of form:\n\n- $x~d$ — replace the digit at the $x$-th position of $c$ with a digit $d$.\n\nNote that string $c$ might have leading zeros at any point of time.\n\nAfter each update print the number of pairs $(a, b)$ such that both $a$ and $b$ are non-negative integers and the result of a strange addition of $a$ and $b$ is equal to $c$.\n\nNote that the numbers of pairs can be quite large, so print them modulo $998244353$.",
    "tutorial": "Let's solve the task as if there are no updates. This can be done with a pretty straightforward dp. $dp_i$ is the number of pairs $(a, b)$ such that the result of the strange addition of $a$ and $b$ is the prefix of $c$ of length $i$. $dp_0 = 1$. From each state you can add a single digit to $a$ and to $b$ at the same time. You can either go to $dp_{i+1}$ and multiply the answer by the number of pairs of digits than sum up to $c_i$. Or go to $dp_{i+2}$ and multiply the answer by the number of pairs of digits than sum up to $c_i c_{i+1}$. Note that no pair of digits can sum up to a three-digit value, so it makes no sense to go further. Let's optimize this dp with some data structure. Segment tree will work well. Let the node store the number of ways to split the segment $[l; r)$ into blocks of size $1$ or $2$ so that: both the leftmost character and the rightmost character are not taken into any block; the leftmost character is taken into some block and the rightmost character is not taken into any block; the leftmost character is not taken into any block and the rightmost character is taken into some block; both the leftmost and the rightmost characters are taken into some blocks. This structure makes the merge pretty manageable. You should glue up the segments in such a way that all the middle characters are taken into some block: either in separate blocks in their own segments or into the same block of length $2$. The answer will be in the root of the tree in a value such that both characters are taken. The update in the segment tree will still work in $O(\\log n)$. Overall complexity: $O(n + m \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(5e5) + 9;\nconst int MOD = 998244353;\n\nint mul(int a, int b) {\n    return (a * 1LL * b) % MOD;\n}\n\nvoid add(int &a, int x) {\n    a += x;\n    a %= MOD;\n}\n\nint bp(int a, int n) {\n    int res = 1;\n    for (; n > 0; n >>= 1) {\n        if (n & 1) res = mul(res, a);\n        a = mul(a, a);\n    }\n    return res;\n}\n\nint inv(int a) {\n    int ia = bp(a, MOD - 2);\n    assert(mul(a, ia) == 1);\n    return ia;\n}\n\nint n, m;\nstring s;\nint dp[N][10];\nint idp[N][10];\nset <pair<int, int> > lr;\nint res = 1;\n\nvoid updRes(int l, int r, int c) {\n    assert(l <= r);\n    if (c == 1) {\n        assert(!lr.count(make_pair(l, r)));\n        lr.insert(make_pair(l, r));\n        res = mul(res, dp[r - l + (r + 1 != n)][r + 1 == n? 1 : s[r + 1] - '0']);\n    } else {\n        assert(lr.count(make_pair(l, r)));\n        lr.erase(make_pair(l, r));\n        res = mul(res, inv(dp[r - l + (r + 1 != n)][r + 1 == n? 1 : s[r + 1] - '0']));\n    }\n}\n\nvoid getLR(int &l, int &r, int pos) {\n    l = r = -1;\n    auto it = lr.lower_bound(make_pair(pos, n));\n    if(it == lr.begin()) return;\n    --it;\n    if(!(it->first <= pos && pos <= it->second)) return;\n    l = it->first, r = it->second;\n}\n\nchar buf[N];\nint main(){\n    scanf(\"%d %d\\n\", &n, &m);\n    scanf(\"%s\", buf);\n    s = string(buf);\n    for (int i = 0; i <= 9; ++i) {\n        dp[0][i] = i + 1; //idp[0][i] = inv(dp[0][i]);\n        dp[1][i] = 2 * (i + 1) + (9 - i); //idp[1][i] = inv(dp[1][i]);\n    }\n    for (int i = 2; i < N; ++i)\n        for (int j = 0; j <= 9; ++j) {\n            dp[i][j] = (2LL * dp[i - 1][j] + 8LL * dp[i - 2][j]) % MOD;\n            //idp[i][j] = inv(dp[i][j]);\n        }\n    for (int i = 0; i < N; ++i) for(int j = 0; j < 10; ++j) assert(dp[i][j] != 0);\n    for (int l = 0; l < n; ) {\n        int r = l;\n        while(r < n && s[r] == '1') ++r;\n        res = mul(res, dp[r - l - (r == n)][r == n? 1 : s[r] - '0']);\n        if (l != r) lr.insert(make_pair(l, r - 1));\n        l = r + 1;\n    }\n    \n    for (int i = 0; i < m; ++i) {\n        int pos;\n        char x;\n        scanf(\"%d %c\\n\", &pos, &x);\n        --pos;\n        if (x == '1') {\n            if (s[pos] != '1'){ \n                int l1, r1, l2, r2;\n                getLR(l1, r1, pos - 1);\n                getLR(l2, r2, pos + 1);\n                \n                int l = pos, r = pos;\n                if (l1 != -1) {\n                    assert(r1 == pos - 1);\n                    updRes(l1, r1, -1);\n                    l = l1;\n                } else {\n                    res = mul(res, inv(dp[0][s[pos] - '0']));\n                }\n                \n                if (l2 != -1) {\n                    assert(l2 == pos + 1);\n                    updRes(l2, r2, -1);\n                    r = r2;\n                } else {\n                    if (pos + 1 != n) res = mul(res, inv(dp[0][s[pos + 1] - '0']));\n                }\n                \n                s[pos] = x;\n                updRes(l, r, 1);\n            }\n        } else {\n            if (s[pos] != '1') {\n                if (pos - 1 >= 0 && s[pos - 1] == '1') {\n                    int l, r;\n                    getLR(l, r, pos - 1);\n                    updRes(l, r, -1);\n                    s[pos] = x;\n                    updRes(l, r, 1);\n                } else {\n                    res = mul(res, dp[0][x - '0']);\n                    res = mul(res, inv(dp[0][s[pos] - '0']));\n                    s[pos] = x;\n                }\n            } else {\n                int l, r;\n                getLR(l, r, pos);\n                assert(l != -1 && r != -1);\n                \n                updRes(l, r, -1);\n                s[pos] = x;\n                if (l == r) {\n                    res = mul(res, dp[0][s[pos] - '0']);\n                    if (pos + 1 < n) res = mul(res, dp[0][s[pos + 1] - '0']);\n                } else if (pos == l) {\n                    res = mul(res, dp[0][s[pos] - '0']);\n                    updRes(l + 1, r, 1);\n                } else if (pos == r) {\n                    if (pos + 1 != n) res = mul(res, dp[0][s[pos + 1] - '0']);\n                    updRes(l, r - 1, 1);\n                } else {\n                    updRes(l, pos - 1, 1);\n                    updRes(pos + 1, r, 1);\n                }\n            }\n            \n        }\n        printf(\"%d\\n\", res);\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "matrices"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1380",
    "index": "G",
    "title": "Circular Dungeon",
    "statement": "You are creating a level for a video game. The level consists of $n$ rooms placed in a circle. The rooms are numbered $1$ through $n$. Each room contains exactly one exit: completing the $j$-th room allows you to go the $(j+1)$-th room (and completing the $n$-th room allows you to go the $1$-st room).\n\nYou are given the description of the multiset of $n$ chests: the $i$-th chest has treasure value $c_i$.\n\nEach chest can be of one of two types:\n\n- regular chest — when a player enters a room with this chest, he grabs the treasure and proceeds to the next room;\n- mimic chest — when a player enters a room with this chest, the chest eats him alive, and he loses.\n\nThe player starts in a random room with each room having an equal probability of being chosen. The players earnings is equal to the total value of treasure chests he'd collected before he lost.\n\nYou are allowed to choose the order the chests go into the rooms. For each $k$ from $1$ to $n$ place the chests into the rooms in such a way that:\n\n- each room contains \\textbf{exactly} one chest;\n- \\textbf{exactly} $k$ chests are mimics;\n- the expected value of players earnings is \\textbf{minimum} possible.\n\nPlease note that for each $k$ the placement is chosen independently.\n\nIt can be shown that it is in the form of $\\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \\ne 0$. Report the values of $P \\cdot Q^{-1} \\pmod {998244353}$.",
    "tutorial": "Idea: BledDest At first, let's say that the expected value is equal to the average of total earnings over all positions and is equal to the sum of earnings over all positions divided by $n$. So we can trasition to minimizing the sum. Let's learn how to solve the task for some fixed $k$. Fix some arrangement and rotate the rooms so that the last room contains a mimic. So now you have $cnt_1$ regular chests, then a single mimic, $cnt_2$ regular chests, single mimic, $\\dots$, $cnt_k$ regular chests, single mimic. All $cnt_i \\ge 0$ and $\\sum \\limits_{i=1}^{k} cnt_i = n - k$. Take a look at some of these intervals of length $cnt_i$. The last chest in the interval is taken from $cnt_i$ starting positions, the second-to-last is taken $cnt_i - 1$ times and so on. Now let's find the optimal way to choose $cnt_i$. Fix some values of $cnt_i$. Take a look at the smallest of these values and the largest of them. Let the values be $x$ and $y$. If they differ by at least $2$ ($x \\le y - 2$), then the smaller result can always be achieved by moving a regular chest from the larger one to the smaller one. Consider two sequences of coefficients for both intervals: $[1, 2, \\dots, x - 1, x]$ and $[1, 2, \\dots, y - 1, y]$. However, if you remove one chest, then they will be equal to $[1, 2, \\dots, x - 1, x, x + 1]$ and $[1, 2, \\dots, y - 1]$. If you only consider the difference between the numbers of both sequences, then you can see that only coefficient $y$ got removed and coefficient $x + 1$ was added. So you can rearrange the chests in such a way that all chests are assigned to the same value and only the chest that was assigned to $y$ becomes assigned to $x+1$, thus decreasing the total value. Now we have all $cnt_i$ set now. The only thing left is to assign chests optimally. Write down the union of all the coefficient sequences from all the intervals $\\bigcup \\limits_{i=1}^{n-k} [1, \\dots, cnt_i-1, cnt_i]$ and sort them in the non-decreasing order. It's easy to show that the chests should be sorted in the non-increasing order (really classical thing, you can try proving that by showing that any other arrangement can easily be improved once again). That allows us to write a solution in $O(n^2)$. Sort all the chests in the beginning, after that for some $k$ multiply the value of the $i$-th chest by $\\lfloor \\frac{i}{k} \\rfloor$ and sum up the results. Finally, let's speed this up with prefix sums. Notice that the first $k$ values are multiplied by $0$, the second $k$ values - by $1$ and so on. If $n$ is not divisible by $k$, then the last block just has length smaller than $k$. Thus, we can calculate the answer for some $k$ in $O(\\frac{n}{k})$. And that's equal to $O(\\sum \\limits_{k=1}^{n} \\frac{n}{k})$ = $O(n \\log n)$. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\nint binpow(int a, int b){\n\tint res = 1;\n\twhile (b){\n\t\tif (b & 1)\n\t\t\tres = mul(res, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nvector<int> pr;\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> c(n);\n\tforn(i, n)\n\t\tscanf(\"%d\", &c[i]);\n\tsort(c.begin(), c.end(), greater<int>());\n\tpr.push_back(0);\n\tforn(i, n)\n\t\tpr.push_back(add(pr.back(), c[i]));\n\t\n\tint invn = binpow(n, MOD - 2);\n\tfor (int k = 1; k <= n; ++k){\n\t\tint ans = 0;\n\t\tfor (int i = 0, j = 0; i < n; i += k, ++j)\n\t\t\tans = add(ans, mul(j, add(pr[min(n, i + k)], -pr[i])));\n\t\tprintf(\"%d \", mul(ans, invn));\n\t}\n\tputs(\"\");\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1381",
    "index": "A1",
    "title": "Prefix Flip (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved.}\n\nThere are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix.\n\nFor example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$.\n\nYour task is to transform the string $a$ into $b$ in at most $3n$ operations. It can be proved that it is always possible.",
    "tutorial": "The easy version has two main solutions: Solution 1: $O(n)$ time with $3n$ operations The idea is to fix the bits one-by-one. That is, make $s_1=t_1$, then make $s_2=t_2$, etc. To fix the bit $i$ (when $s_i\\ne t_i$), we can flip the prefix of length $i$, then flip the prefix of length $1$, and again flip the prefix of length $i$. These three operations do not change any other bits in $s$, so it's simple to implement in $O(n)$. Since we use $3$ operations per bit, we use at most $3n$ operations overall. Solution 2: $O(n^2)$ time with $2n$ operations In this solution, we take a similar approach to solution 1, in that we fix the bits one-by-one. This time, we will fix the bits in reverse order. To fix the bit $i$, we can either flip the prefix of length $i$, or flip the first bit and then flip the prefix of length $i$. Since we do this in reverse order, the previously fixed bits do not get messed up by this procedure. And we use at most $2$ operations per bit, so $2n$ operations overall. However, we do have to simulate the operations in order to check if we should flip the first bit. Simulating an operation can easily be done in $O(n)$ time per operation, or $O(n^2)$ time to simulate all operations.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n// Solution 2 from editorial\n// Fix the bits one-by-one in reverse order.\n// Simulate the operations manually, achieving O(n^2) time complexity\n \nint t, n;\nstring a, b;\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> t;\n    while(t--) {\n        cin >> n >> a >> b;\n        vector<int> ops;\n        for(int i = n - 1; i >= 0; i--) {\n            if(a[i] != b[i]) {\n                if(a[0] == b[i]) {\n                    ops.push_back(1);\n                    a[0] = '0' + !(a[0] - '0');\n                }\n                reverse(a.begin(), a.begin() + i + 1);\n                for(int j = 0; j <= i; j++) {\n                    a[j] = '0' + !(a[j] - '0');\n                }\n                ops.push_back(i + 1);\n            }\n        }\n        cout << ops.size() << ' ';\n        for(int x : ops) {\n            cout << x << ' ';\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1381",
    "index": "A2",
    "title": "Prefix Flip (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is the constraint on $n$ and the required number of operations. You can make hacks only if all versions of the problem are solved.}\n\nThere are two binary strings $a$ and $b$ of length $n$ (a binary string is a string consisting of symbols $0$ and $1$). In an operation, you select a prefix of $a$, and simultaneously invert the bits in the prefix ($0$ changes to $1$ and $1$ changes to $0$) and reverse the order of the bits in the prefix.\n\nFor example, if $a=001011$ and you select the prefix of length $3$, it becomes $011011$. Then if you select the entire string, it becomes $001001$.\n\nYour task is to transform the string $a$ into $b$ in at most $2n$ operations. It can be proved that it is always possible.",
    "tutorial": "There are several ways to solve the hard version as well. Solution 1 Given an arbitrary binary string $s$, we can make all bits $0$ in at most $n$ operations. Simply scan the string from left to right. If bits $i$ and $i+1$ disagree, apply the operation to the prefix of length $i$. This is also easy to simulate in $O(n)$ time. We can make $s$ all zeros in at most $n$ operations, and we can make $t$ all zeros in at most $n$ operations. By reversing the order of the operations on $t$, we have transformed $s$ into $t$ in at most $2n$ operations, as desired. Solution 2 Another approach is to optimize the simulation for solution 2 from the easy version. You can do this with a data structure such as a balanced binary search tree in $O(n \\log n)$ time, but there is no need. Instead, we can observe that after making the last $k$ bits correct with our procedure, the prefix of $s$ of length $n-k$ will correspond to some segment of the original string $s$, except it will be possibly flipped (inverted and reversed). So, we need only keep track of the starting index of this segment, and a flag for whether it is flipped. Complexity is $O(n)$. Solution 3 A third solution uses randomization to improve the number of operations from $3n$ in solution 1 of the easy version. We can observe that in a random test case, approximately half the bits of $s$ will be mismatches with $t$. Solution 1 in the easy version uses $3$ operations per mismatch, which is $3n/2$ operations in expectation. Obviously, you don't get to decide that all test cases are random. But you can spend a small number of operations initially, flipping random prefixes to make the string more random. If it doesn't work, you can try again repeatedly. Flipping random prefixes is a complicated process that might be hard to compute the exact probability. But if the probability is $p$, and we try to flip $k$ prefixes randomly, the time complexity is $O((k+1)n)\\log p$. If you find a deterministic solution with a strictly lower ratio than $2$ operations per bit, we would love to hear about it!",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n// Solution 2 from editorial\n// instead of simulating, we store two variables idx and flip\n// they tell us enough information to ask the value of the first bit during the process\n// If flip is false, it means the substring s[idx, ..., idx + i) is currently the beginning of s\n// If flip is true, it means the flipped substring s[idx - i + 1, ..., idx] is currently the beginning of s\n// we update idx and flip correctly after fixing each bit in O(1) time per bit, or O(n) time overall\n \nint t, n;\nstring a, b;\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> t;\n    while(t--) {\n        cin >> n >> a >> b;\n        bool flip = false;\n        int idx = 0;\n        vector<int> ops;\n        for(int i = n - 1; i >= 0; i--) {\n            if(flip ^ (a[idx] == b[i])) {\n                ops.push_back(1);\n            }\n            ops.push_back(i + 1);\n            if(flip) idx -= i;\n            else idx += i;\n            flip = !flip;\n        }\n        cout << ops.size() << ' ';\n        for(int x : ops) {\n            cout << x << ' ';\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "implementation",
      "strings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1381",
    "index": "B",
    "title": "Unmerge",
    "statement": "Let $a$ and $b$ be two arrays of lengths $n$ and $m$, respectively, with no elements in common. We can define a new array $\\mathrm{merge}(a,b)$ of length $n+m$ recursively as follows:\n\n- If one of the arrays is empty, the result is the other array. That is, $\\mathrm{merge}(\\emptyset,b)=b$ and $\\mathrm{merge}(a,\\emptyset)=a$. In particular, $\\mathrm{merge}(\\emptyset,\\emptyset)=\\emptyset$.\n- If both arrays are non-empty, and $a_1<b_1$, then $\\mathrm{merge}(a,b)=[a_1]+\\mathrm{merge}([a_2,\\ldots,a_n],b)$. That is, we delete the first element $a_1$ of $a$, merge the remaining arrays, then add $a_1$ to the beginning of the result.\n- If both arrays are non-empty, and $a_1>b_1$, then $\\mathrm{merge}(a,b)=[b_1]+\\mathrm{merge}(a,[b_2,\\ldots,b_m])$. That is, we delete the first element $b_1$ of $b$, merge the remaining arrays, then add $b_1$ to the beginning of the result.\n\nThis algorithm has the nice property that if $a$ and $b$ are sorted, then $\\mathrm{merge}(a,b)$ will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if $a=[3,1]$ and $b=[2,4]$, then $\\mathrm{merge}(a,b)=[2,3,1,4]$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nThere is a permutation $p$ of length $2n$. Determine if there exist two arrays $a$ and $b$, each of length $n$ and with no elements in common, so that $p=\\mathrm{merge}(a,b)$.",
    "tutorial": "Consider the maximum element $2n$ of $p$. Assume without loss of generality that it comes from array $a$. Then the merge algorithm will exhaust array $b$ before it takes the element $2n$. Therefore, if $2n$ appears at index $i$ in $p$, the entire suffix of $p$ beginning at index $i$ must be a contiguous block in one of the arrays $a$ or $b$. Then if we ignore this suffix of $p$, we should determine if the prefix of $p$ can be the merge of two arrays of certain sizes. We can repeat the same argument, as the maximum remaining element also corresponds to a contiguous block. Taking this argument all the way, consider all indices $i$ where $p_i$ is greater than all elements that come before. This gives us all the lengths of the contiguous blocks, and we should determine if a subset of them add up to $n$. We've shown this condition is necessary. It is also sufficient because if we assign the blocks to $a$ and $b$ accordingly, the merge algorithm works correctly. Now, this is just a subset-sum problem. The standard subset-sum DP approach takes $O(n^2)$ time, which is good enough. It's also possible to do $O(n\\sqrt n)$ by using the fact that sum of values is $2n$ (as they are the lengths of disjoint blocks), meaning there are only $O(\\sqrt n)$ distinct values.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n// compute block lengths, and do subset sum.\n// O(n^2) subset sum is a standard dp\n// For educational purposes, here is the O(n sqrt(n)) solution\n// we treat each distinct length independently, and remember the number of occurrences\n// use the helper array a to update the dp states\n \nconst int N = 1e5 + 5;\nint t, n, p[2 * N], a[N];\nbool vis[N];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> t;\n    while(t--) {\n        cin >> n;\n        int mx = 0;\n        vector<int> ind;\n        for(int i = 1; i <= 2 * n; i++) {\n            cin >> p[i];\n            if(p[i] > mx) {\n                mx = p[i];\n                ind.push_back(i);\n            }\n        }\n        ind.push_back(2 * n + 1);\n        vector<int> lens;\n        for(int i = 1; i < (int) ind.size(); i++) {\n            lens.push_back(ind[i] - ind[i - 1]);\n        }\n        sort(lens.begin(), lens.end());\n        fill(vis, vis + n + 1, false);\n        vis[0] = true;\n        int m = lens.size();\n        for(int k = 0; k < m; k++) {\n            int r = k;\n            while(r < m && lens[r] == lens[k]) r++;\n            fill(a, a + n + 1, 0);\n            for(int i = lens[k]; i <= n; i++) {\n                if(!vis[i] && vis[i - lens[k]] && a[i - lens[k]] < r - k) {\n                    a[i] = a[i - lens[k]] + 1;\n                    vis[i] = true;\n                }\n            }\n            k = r - 1;\n        }\n        cout << (vis[n] ? \"YES\" : \"NO\") << '\\n';\n    }\n}",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1381",
    "index": "C",
    "title": "Mastermind",
    "statement": "In the game of Mastermind, there are two players  — Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of $n$ colors. There are exactly $n+1$ colors in the entire universe, numbered from $1$ to $n+1$ inclusive.\n\nWhen Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers $x$ and $y$.\n\nThe first integer $x$ is the number of indices where Bob's guess correctly matches Alice's code. The second integer $y$ is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, $y$ is the maximum number of indices he could get correct.\n\nFor example, suppose $n=5$, Alice's code is $[3,1,6,1,2]$, and Bob's guess is $[3,1,1,2,5]$. At indices $1$ and $2$ colors are equal, while in the other indices they are not equal. So $x=2$. And the two codes have the four colors $1,1,2,3$ in common, so $y=4$.\n\n\\begin{center}\nSolid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. $x$ is the number of solid lines, and $y$ is the total number of lines.\n\\end{center}\n\nYou are given Bob's guess and two values $x$ and $y$. Can you find one possibility of Alice's code so that the values of $x$ and $y$ are correct?",
    "tutorial": "Suppose we have already decided which $x$ indices agree on color. We should shuffle the remaining $n-x$ indices in a way that minimizes the number of matches. We should also replace $n-y$ indices with a color that doesn't contribute to the multiset intersection. Because there are $n+1>n$ colors, there is some color $c$ that doesn't appear in $a$, and we can use it to fill these $n-y$ indices. Assuming that $n-y$ is greater than or equal to the minimum number of excess matches we're forced to make, we have a solution. Let $f$ be the number of occurrences of the most frequent color in the $n-x$ indices. Then the number of forced matches is clearly at least $2f-(n-x)$. And it can be achieved as follows. Let's reindex so that we have contiguous blocks of the same color. Then rotate everything by $\\left\\lfloor \\frac{n-x}{2}\\right\\rfloor$ indices. Now we need to decide on the $x$ indices that minimize $f$. This can be done simply by always choosing the most frequent color remaining. We can do this with a priority queue in $O(n\\log n)$, or $O(n)$ with counting sort. To make the solution clearer, let's see how it works on the sixth test case in the sample: $[3,3,2,1,1,1]$ with $x=2,y=4$. First, we greedily choose the most frequent color two times: $[3,\\_,\\_,1,\\_,\\_]$. After choosing $1$ the first time, there is a tie between $1$ and $3$. So alternatively, we could choose the color $1$ twice. Then the remaining indices have colors $3,2,1,1$. Rotating by $(n-x)/2=2$ indices, we can place the colors as $1,1,2,3$ to get $[3,1,1,1,2,3]$. The color $4$ does not appear in $a$, so we should fill $n-y=2$ indices with $4$. (But not where we already forced a match.) For example, we get the solution $[3,4,1,1,4,3]$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n// ind[color] = list of indices that have this color\n// hist[frequency] = list of colors with this frequency\n// a solution with priority_queue is perhaps simpler to implement,\n// but here is an O(n) solution because we can.\n \nconst int N = 1e5 + 5;\nint t, n, x, y, b[N], a[N];\nvector<int> ind[N], hist[N];\nbool mis[N];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> t;\n    while(t--) {\n        cin >> n >> x >> y;\n        for(int i = 0; i <= n + 1; i++) {\n            ind[i].clear();\n            hist[i].clear();\n            mis[i] = false;\n            a[i] = 0;\n        }\n        for(int i = 1; i <= n; i++) {\n            cin >> b[i];\n            ind[b[i]].push_back(i);\n        }\n        for(int i = 1; i <= n + 1; i++) {\n            hist[ind[i].size()].push_back(i);\n        }\n        // greedily choose x indices by frequency\n        int idx = n;\n        for(int k = 1; k <= x; k++) {\n            while(hist[idx].empty()) idx--;\n            int col = hist[idx].back();\n            // match the color and update our ind/hist structures\n            a[ind[col].back()] = col;\n            ind[col].pop_back();\n            hist[idx].pop_back();\n            hist[idx - 1].push_back(col);\n        }\n        while(idx > 0 && hist[idx].empty()) idx--;\n        vector<int> ve;\n        // idx = max frequency color of the remaining unmatched indices\n        if(idx * 2 > 2 * n - x - y) {\n            cout << \"NO\\n\";\n            continue;\n        }\n        // create a vector of the indices\n        // put same colors together so that all we have to do is rotate by floor((n - x) / 2)\n        for(int i = 1; i <= idx; i++) {\n            for(int col : hist[i]) {\n                ve.insert(ve.end(), ind[col].begin(), ind[col].end());\n            }\n        }\n        int mismatch = n - y;\n        auto makemismatch = [&](int i) {\n            a[i] = hist[0][0];\n            mismatch--;\n            mis[i] = true;\n        };\n        for(int i = 0; i < n - x; i++) {\n            a[ve[i]] = b[ve[(i + (n - x) / 2) % (n - x)]];\n            if(a[ve[i]] == b[ve[i]]) makemismatch(ve[i]);\n        }\n        for(int i = 0; mismatch > 0; i++) {\n            if(!mis[ve[i]]) makemismatch(ve[i]);\n        }\n        cout << \"YES\\n\";\n        for(int i = 1; i <= n; i++) {\n            cout << a[i] << ' ';\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "graph matchings",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1381",
    "index": "D",
    "title": "The Majestic Brown Tree Snake",
    "statement": "There is an undirected tree of $n$ vertices, connected by $n-1$ bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex $a$ and its tail is at vertex $b$. The snake's body occupies all vertices on the unique simple path between $a$ and $b$.\n\nThe snake wants to know if it can reverse itself  — that is, to move its head to where its tail started, and its tail to where its head started. Unfortunately, the snake's movements are restricted to the tree's structure.\n\nIn an operation, the snake can move its head to an adjacent vertex not currently occupied by the snake. When it does this, the tail moves one vertex closer to the head, so that the length of the snake remains unchanged. Similarly, the snake can also move its tail to an adjacent vertex not currently occupied by the snake. When it does this, the head moves one unit closer to the tail.\n\n\\begin{center}\nLet's denote a snake position by $(h,t)$, where $h$ is the index of the vertex with the snake's head, $t$ is the index of the vertex with the snake's tail. This snake can reverse itself with the movements $(4,7)\\to (5,1)\\to (4,2)\\to (1, 3)\\to (7,2)\\to (8,1)\\to (7,4)$.\n\\end{center}\n\nDetermine if it is possible to reverse the snake with some sequence of operations.",
    "tutorial": "Let the length of the snake be $L$. Let's call a node $p$ a \"pivot\" if there exist three edge-disjoint paths of length $L$ extending from $p$. Clearly, if one of the snake's endpoints (head or tail) can reach a pivot, then the snake can rotate through these $3$ paths, reversing itself. I claim two things: If a snake's endpoint can reach some pivot, then it can reach all pivots. If a snake's endpoint cannot reach a pivot, the snake cannot reverse itself. Let's prove claim 1. Say there are two pivots $p_1$ and $p_2$, and a snake's endpoint can reach $p_1$. At most one edge from $p_1$ is on the path between $p_1$ and $p_2$. So let's put the snake in one of the other branches of $p_1$. Then we can move the snake back through $p_1$ and on the path to $p_2$. Let's prove claim 2. Consider the longest path in the tree. If it is impossible for the snake to enter this path, we may delete the path without changing the possible snake positions, so we apply induction on the smaller tree. Otherwise, if the snake can enter the path, we can show that it can never leave. (And therefore, it is also initially in the path, because snake moves are reversible.) Assume for contradiction that the snake can leave the path. Then in its last move leaving the path, it occupies a length $L$ path from a node in the longest path. And because we said it was the longest path, both of those branches must have length at least $L$ as well. But then the snake's endpoint is at a pivot, giving us a contradiction. This completes the proof of claim 2. Solution 1 Now that we understand claims 1 and 2, how can we use them? First, we can detect if any node is a pivot using DP to find the longest 3 paths from each node. If a pivot does not exist, we output NO. Otherwise, root the tree at the pivot $p$. Let's move the snake back and forth in a greedy fashion like this: Move the head to the deepest leaf it can reach. Then move the tail to the deepest leaf it can reach. And repeat. If at any point, one endpoint becomes an ancestor of the other, we can move the snake up to $p$. Otherwise, if no more progress can be made (progress is determined by the smallest reachable depth of an endpoint), then the snake cannot reverse itself. Clearly, the snake can only go back and forth $O(n)$ times before progress stops. We can simulate the back-and-forth motion by answering $k$-th ancestor queries with binary lifting. Complexity is $O(n\\log n)$. Solution 2 It's also possible to achieve $O(n)$ with two pointers. Consider the path of nodes initially occupied by the snake, numbered from $1$ to $L$. Each node has a subtree of non-snake nodes. Let $a_i$ be the height of the non-snake subtree of node $i$. We can maintain two pointers $\\ell$ and $r$, where $\\ell$ is the maximum achievable index of the head, and $r$ is the minimum achievable index of the tail. We do a similar back-and-forth motion as in solution $1$. Send the head to the node that minimizes $r$, then send the tail to the node that maximizes $\\ell$, and repeat. The snake can reverse itself if and only if a pivot exists and $\\ell,r$ can swap places. Bonus: Can you prove that the number of times the snake must switch between moving the head and tail is $O(\\sqrt n)$?",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n// This is the O(n) two-pointer solution from the editorial\n \nconst int N = 1e5 + 5;\nint t, n, a, b, u, v, par[N], branch[N], depth[N];\nvector<int> adj[N], Q[N];\n \n// find largest branch lengths from each node, using 2 DFS's.\n// first DFS is for root = a\n// second DFS is for re-rooting\nvoid findpivots(int x, int p) {\n    Q[x].assign(3, 0);\n    branch[x] = 0;\n    for(int y : adj[x]) {\n        if(y != p) {\n            depth[y] = 1 + depth[x];\n            findpivots(y, x);\n            Q[x].push_back(1 + branch[y]);\n            branch[x] = max(branch[x], 1 + branch[y]);\n        }\n    }\n}\nvoid findpivots2(int x, int p) {\n    // move the three largest branch lengths to the front\n    partial_sort(Q[x].begin(), Q[x].begin() + 3, Q[x].end(), greater<int>());\n    for(int y : adj[x]) {\n        if(y != p) {\n            Q[y].push_back(1 + Q[x][branch[y] + 1 == Q[x][0]]);\n            findpivots2(y, x);\n        }\n    }\n}\n \n// compute branch[x] = height of subtree of non-snake nodes\nbool dfs(int x, int p) {\n    par[x] = p;\n    branch[x] = 0;\n    bool hasb = (x == b);\n    for(int y : adj[x]) {\n        if(y != p) {\n            if(dfs(y, x)) hasb = true;\n            else branch[x] = max(branch[x], 1 + branch[y]);\n        }\n    }\n    return hasb;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> t;\n    while(t--) {\n        cin >> n >> a >> b;\n        for(int i = 1; i <= n; i++) adj[i].clear();\n        for(int i = 0; i < n - 1; i++) {\n            cin >> u >> v;\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n        depth[a] = 0;\n        findpivots(a, -1);\n        findpivots2(a, -1);\n        bool pivot = false;\n        for(int i = 1; i <= n; i++)\n            pivot |= (Q[i][2] >= depth[b]);\n        if(!pivot) {\n            cout << \"NO\\n\";\n            continue;\n        }\n        dfs(a, -1);\n        // trace out path from a to b, converting into an array problem\n        vector<int> ve;\n        ve.push_back(branch[b]);\n        while(b != a) {\n            b = par[b];\n            ve.push_back(branch[b]);\n        }\n        // two-pointers on the array.\n        int len = (int) ve.size(), l = 0, r = len - 1;\n        int L = ve[r], R = r - ve[l];\n        while(l < r) {\n            if(l < L) {\n                l++;\n                R = min(R, len - 1 - (ve[l] - l));\n            }else if(r > R) {\n                r--;\n                L = max(L, ve[r] - (len - 1 - r));\n            }else break;\n        }\n        cout << (l == r ? \"YES\" : \"NO\") << '\\n';\n    }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees",
      "two pointers"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1381",
    "index": "E",
    "title": "Origami",
    "statement": "After being discouraged by 13 time-limit-exceeded verdicts on an ugly geometry problem, you decided to take a relaxing break for arts and crafts.\n\nThere is a piece of paper in the shape of a simple polygon with $n$ vertices. The polygon may be non-convex, but we all know that proper origami paper has the property that \\textbf{any horizontal line intersects the boundary of the polygon in at most two points.}\n\nIf you fold the paper along the vertical line $x=f$, what will be the area of the resulting shape? When you fold, the part of the paper to the left of the line is symmetrically reflected on the right side.\n\nYour task is to answer $q$ independent queries for values $f_1,\\ldots,f_q$.",
    "tutorial": "First, let's imagine the problem in one dimension. And let's see how the length of the folded segment changes as we sweep the fold line from left to right. If the fold line is to the left of the paper, it's just the length of the segment. Then as the fold line enters the left side of the paper, we subtract the length of paper to the left of the fold line, since it gets folded onto the right half. Then as the fold line passes the midpoint of the segment, we should add back the length we passed after the midpoint, since the left half gets folded past the right end of the paper. Finally, after the line exits the paper, the answer stays constant again. Now let's advance to the two-dimensional setting. Imagine the process described above applied to all horizontal segments of the polygon simultaneously. We see that the answer is the integral of the answers for all the segments. Now, let's split the polygon into two halves by the midpoints of each horizontal segment. For a fold line, the answer is the total area, minus the area left of the sweep line belonging to the first polygon, plus the area left of the sweep line belonging to the second polygon. We can sort all line segments and queries, and answer all queries in a sweep line. To simplify the process, it helps to know the standard algorithm to compute the area of a polygon by considering a trapezoid for each line segment and combining their areas with inclusion-exclusion. Essentially, we have to sweep the integral of a piecewise linear function. Complexity is $O((n+q)\\log(n+q))$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n// pro-tip: use complex<double> if you're really lazy\n// and don't like typing a custom point struct\n \n#define pt complex<double>\n#define x real()\n#define y imag()\n \nconst int N = 1e5 + 5;\nint n, q;\ndouble f[N], ans[N];\npt p[N];\n \n// list of events (x coordinate, query index if applicable, A, B)\n// where we should answer at this x if a query, or\n// we should integrate the line Ax+B starting at x coordinate if not query\n// to integrate on interval, we integrate its negation\n// starting at the right endpoint of the interval.\nvector<tuple<double, int, double, double>> ve;\n \nvoid add_segment(const pt &p, const pt &q, int k) {\n    // vertical line has no effect on the area.\n    if(abs(q.x - p.x) < 1e-10) return;\n    if(p.x > q.x) return add_segment(q, p, -k);\n    double A = (q.y - p.y) / (q.x - p.x);\n    double B = p.y - p.x * A;\n    ve.emplace_back(p.x, 0, k * A, k * B);\n    ve.emplace_back(q.x, 0, -k * A, -k * B);\n}\n \n// point on line segment AB with the same y coordinate as p\npt proj(pt a, pt b, pt p) {\n    return {(b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x, p.y};\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> n >> q;\n    // j = index of point with minimum y coordinate\n    // L, R = two pointers that we use to scan polygon vertically,\n    // drawing the midpoint lines\n    int j = 0, X, Y, L = 0, R = 0, idx;\n    double area = 0, a = 0, b = 0, pos, A, B;\n    for(int i = 0; i < n; i++) {\n        cin >> X >> Y;\n        p[i] = pt(X, Y);\n        if(p[i].y < p[j].y) j = i;\n    }\n    for(int i = 1; i <= q; i++) {\n        cin >> f[i];\n        ve.emplace_back(f[i], i, -1, -1);\n    }\n    // compute total area of polygon\n    for(int i = 0; i < n; i++) {\n        int j = (i + 1) % n;\n        area += (conj(p[i]) * p[j]).y;\n        if(p[i].y > p[j].y) add_segment(p[i], p[j], 1);\n        else add_segment(p[j], p[i], 1);\n    }\n    area = abs(0.5 * area);\n    rotate(p, p + j, p + n);\n    pt mid = p[0], mid2;\n    for(int i = 0; i < n - 1; i++) {\n        int L2 = L + 1;\n        int R2 = (R + n - 1) % n;\n        if(p[L2].y < p[R2].y) {\n            mid2 = (p[L2] + proj(p[R], p[R2], p[L2])) * 0.5;\n            L = L2;\n        }else {\n            mid2 = (p[R2] + proj(p[L], p[L2], p[R2])) * 0.5;\n            R = R2;\n        }\n        add_segment(mid, mid2, 2);\n        mid = mid2;\n    }\n    sort(ve.begin(), ve.end());\n    for(auto &e : ve) {\n        tie(pos, idx, A, B) = e;\n        if(idx > 0) {\n            ans[idx] = area + (0.5 * a * pos * pos + b * pos);\n        }else {\n            area -= (0.5 * A * pos * pos + B * pos);\n            a += A, b += B;\n        }\n    }\n    cout << fixed << setprecision(6);\n    for(int i = 1; i <= q; i++) {\n        cout << ans[i] << '\\n';\n    }\n}",
    "tags": [
      "geometry",
      "math",
      "sortings"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1382",
    "index": "A",
    "title": "Common Subsequence",
    "statement": "You are given two arrays of integers $a_1,\\ldots,a_n$ and $b_1,\\ldots,b_m$.\n\nYour task is to find a \\textbf{non-empty} array $c_1,\\ldots,c_k$ that is a subsequence of $a_1,\\ldots,a_n$, and also a subsequence of $b_1,\\ldots,b_m$. If there are multiple answers, find one of the \\textbf{smallest} possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.\n\nA sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero) elements. For example, $[3,1]$ is a subsequence of $[3,2,1]$ and $[4,3,1]$, but not a subsequence of $[1,3,3,7]$ and $[3,10,4]$.",
    "tutorial": "If there is any common subsequence, then there is a common element of $a$ and $b$. And a common element is also a common subsequence of length $1$. Therefore, we need only find a common element of the two arrays, or say that they share no elements. Complexity is $O(nm)$ if we compare each pair of elements, $O((n+m)\\log(n+m))$ if we sort the arrays and take their intersection, or use a set data structure, or $O(n+m)$ if we use a hash table.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 1005;\nint t, n, m, a[N], b;\nbool vis[N];\n \n// vis[x] = true if x appears in array a\n// for each element b[i], we check if it is also in a\n// don't forget to reset vis array before the next test case\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> t;\n    while(t--) {\n        cin >> n >> m;\n        for(int i = 0; i < n; i++) {\n            cin >> a[i];\n            vis[a[i]] = true;\n        }\n        int e = -1;\n        for(int j = 0; j < m; j++) {\n            cin >> b;\n            if(vis[b]) e = b;\n        }\n        for(int i = 0; i < n; i++) {\n            vis[a[i]] = false;\n        }\n        if(e == -1) {\n            cout << \"NO\\n\";\n        }else {\n            cout << \"YES\\n1 \" << e << '\\n';\n        }\n    }\n}",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "1382",
    "index": "B",
    "title": "Sequential Nim",
    "statement": "There are $n$ piles of stones, where the $i$-th pile has $a_i$ stones. Two people play a game, where they take alternating turns removing stones.\n\nIn a move, a player may remove a positive number of stones from the \\textbf{first non-empty pile} (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.",
    "tutorial": "Suppose $a_1>1$. If removing the entire first pile is winning, player 1 will do that. Otherwise, player 1 can leave exactly one stone in the first pile, forcing player 2 to remove it, leaving player 1 in the winning position. Otherwise, if $a_1=1$, then it is forced to remove the first pile. So, whichever player gets the first pile with more than one stone wins. That is, let $k$ be the maximum number such that $a_1=\\cdots=a_k=1$. If $k$ is even, the first player will win. Otherwise, the second player will win. The only exception is when all piles have exactly $1$ stone. In that case, the first player wins when $k$ is odd. Complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 1e5 + 5;\nint t, n, a[N];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> t;\n    while(t--) {\n        cin >> n;\n        for(int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n        // count number of 1's in the prefix\n        // parity of k determines which player makes the first non-forced move\n        // or if k = n, all moves are forced, and the parity is reversed\n        int k = 0;\n        while(k < n && a[k] == 1) {\n            k++;\n        }\n        cout << ((k == n) ^ (k % 2) ? \"Second\" : \"First\") << '\\n';\n    }\n}",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1383",
    "index": "A",
    "title": "String Transformation 1",
    "statement": "\\textbf{Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $y$ Koa selects must be strictly greater alphabetically than $x$ (read statement for better understanding). You can make hacks in these problems independently.}\n\nKoa the Koala has two strings $A$ and $B$ of the same length $n$ ($|A|=|B|=n$) consisting of the first $20$ lowercase English alphabet letters (ie. from a to t).\n\nIn one move Koa:\n\n- selects some subset of positions $p_1, p_2, \\ldots, p_k$ ($k \\ge 1; 1 \\le p_i \\le n; p_i \\neq p_j$ if $i \\neq j$) of $A$ such that $A_{p_1} = A_{p_2} = \\ldots = A_{p_k} = x$ (ie. all letters on this positions are equal to some letter $x$).\n- selects a letter $y$ (from the first $20$ lowercase letters in English alphabet) such that $y>x$ (ie. letter $y$ is \\textbf{strictly greater} alphabetically than $x$).\n- sets each letter in positions $p_1, p_2, \\ldots, p_k$ to letter $y$. More formally: for each $i$ ($1 \\le i \\le k$) Koa sets $A_{p_i} = y$.\\textbf{Note that you can only modify letters in string $A$}.\n\nKoa wants to know the smallest number of moves she has to do to make strings equal to each other ($A = B$) or to determine that there is no way to make them equal. Help her!",
    "tutorial": "First of all, if there exists some $i$ such that $A_i > B_i$ there isn't a solution. Otherwise, create a graph where every character is a node, and put a directed edge between node $u$ and node $v$ if character $u$ must be transformed into character $v$ (ie. from $A_i$ to $B_i$ for all $i$). We must select a list with minimum number of operations such that if there is an edge from node $u$ to node $v$, then it must exist a subsequence of the operations in the list that transforms $u$ into $v$. Each weakly connected component $C$ can be solved independently and the answer for each component is $|C| - 1$. So total answer is $|ALP| - k$ where $k$ is the number of weakly connected components in the graph. Proof: Each weakly connected component $C$ requires at least $|C| - 1$ operations (because they are connected). Since there are no cycles in the graph a topological order exists. Find one and select each pair of consecutive nodes in this order as the list of operations. Time complexity: $O(|A| + |B| + |ALP|)$ per test case where $|ALP| = 20$ denotes size of alphabet",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int Alp = 20;\n\nint main()\n{\n\tios_base::sync_with_stdio(0), cin.tie(0);\n\n\tint test;\n\tcin >> test;\n\twhile (test--)\n\t{\n\t    int n;\n\t\tstring a, b;\n\t\tcin >> n >> a >> b;\n\n\t\tbool bad = false;\n\t\tvector<vector<int>> adj(Alp);\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tif (a[i] != b[i])\n\t\t\t{\n\t\t\t\tif (a[i] > b[i])\n\t\t\t\t{\n\t\t\t\t\tbad = true;\n\t\t\t\t\tcout << \"-1\\n\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tadj[a[i]-'a'].push_back(b[i]-'a');\n\t\t\t\tadj[b[i]-'a'].push_back(a[i]-'a');\n\t\t\t}\n\n\t\tif (bad) continue;\n\n\t\tvector<bool> mark(Alp);\n\t\tfunction<void(int)> dfs = [&](int u)\n\t\t{\n\t\t\tmark[u] = true;\n\t\t\tfor (auto v : adj[u])\n\t\t\t\tif (!mark[v])\n\t\t\t\t\tdfs(v);\n\t\t};\n\n\t\tint ans = Alp;\n\t\tfor (int i = 0; i < Alp; ++i)\n\t\t\tif (!mark[i])\n\t\t\t\tdfs(i), --ans;\n\t\tcout << ans << \"\\n\";\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "dsu",
      "graphs",
      "greedy",
      "sortings",
      "strings",
      "trees",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1383",
    "index": "B",
    "title": "GameGame",
    "statement": "Koa the Koala and her best friend want to play a game.\n\nThe game starts with an array $a$ of length $n$ consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to $0$. Koa starts.\n\nLet's describe a move in the game:\n\n- During his move, a player chooses any element of the array and removes it from this array, xor-ing it with the current score of the player.More formally: if the current score of the player is $x$ and the chosen element is $y$, his new score will be $x \\oplus y$. Here $\\oplus$ denotes bitwise XOR operation.\n\nNote that after a move element $y$ is removed from $a$.\n- The game ends when the array is empty.\n\nAt the end of the game the winner is the player with the maximum score. If both players have the same score then it's a draw.\n\nIf both players play optimally find out whether Koa will win, lose or draw the game.",
    "tutorial": "Let $x$ be the number of ones and $y$ be the numbers of zeros in the most significant bit of the numbers: if $x$ is even, whatever decision players take, both will end with the same score in that bit, so go to the next bit (if it doesn't exist the game ends in a draw). Indeed, the parity of the result of both players will be the same, since $x$ is even. if $x$ is odd, one of the players ends with $0$ in this bit and the other with $1$, the player with $1$ in this bit wins the game because the well know inequality $2^k > \\sum\\limits_{i=0}^{k-1} 2^i$ for $k \\ge 1$, so the game is equivalent to play on an array of $x$ ones and $y$ zeros. Lemma: The second player wins iff $x \\bmod 4 = 3$ and $y \\bmod 2 = 0$ otherwise the first player wins. Proof: We know that $x \\bmod 2 = 1$ so $x \\bmod 4$ can be $1$ or $3$ if $x \\bmod 4 = 1$ the first player can choose one $1$ and the remaining number of $1$ is a multiple of $4$, if the first player always repeats the last move of the second player (if $y \\bmod 2 = 1$ and the second player takes the last $0$ both players start taking all the remaining ones), then both ends with the same number of ones which divided by $2$ is even and therefore the first player wins. if $x \\bmod 4 = 3$ if $y \\bmod 2 = 0$ the second player can repeat the last move of the first player always so the first ends with a even numbers of $1$ and therefore the second player wins. if $y \\bmod 2 = 1$ the first player takes one $0$ and the game now is exactly the previous case with the first player as the second player. Lemma: The second player wins iff $x \\bmod 4 = 3$ and $y \\bmod 2 = 0$ otherwise the first player wins. Proof: We know that $x \\bmod 2 = 1$ so $x \\bmod 4$ can be $1$ or $3$ if $x \\bmod 4 = 1$ the first player can choose one $1$ and the remaining number of $1$ is a multiple of $4$, if the first player always repeats the last move of the second player (if $y \\bmod 2 = 1$ and the second player takes the last $0$ both players start taking all the remaining ones), then both ends with the same number of ones which divided by $2$ is even and therefore the first player wins. if $x \\bmod 4 = 3$ if $y \\bmod 2 = 0$ the second player can repeat the last move of the first player always so the first ends with a even numbers of $1$ and therefore the second player wins. if $y \\bmod 2 = 1$ the first player takes one $0$ and the game now is exactly the previous case with the first player as the second player. if $y \\bmod 2 = 0$ the second player can repeat the last move of the first player always so the first ends with a even numbers of $1$ and therefore the second player wins. if $y \\bmod 2 = 1$ the first player takes one $0$ and the game now is exactly the previous case with the first player as the second player. Time complexity: $O(n)$ per testcase",
    "code": "import sys\ninput = sys.stdin.readline\n\nd = { 1: 'WIN', 0: 'LOSE', -1: 'DRAW' }\n\ndef main():\n    t = int(input())\n\n    for _ in range(t):\n        n = int(input())\n        a = map(int, input().split())\n\n        f = [0] * 30\n\n        for x in a:\n            for b in range(30):\n                if x >> b & 1:\n                    f[b] += 1\n\n        ans = -1\n        for x in reversed(range(30)):\n            if f[x] % 2 == 1:\n                ans = 0 if f[x] % 4 == 3 and (n - f[x]) % 2 == 0 else 1\n                break\n\n        print(d[ans])\n\nmain()",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "games",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1383",
    "index": "C",
    "title": "String Transformation 2",
    "statement": "\\textbf{Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $y$ Koa selects can be any letter from the first $20$ lowercase letters of English alphabet (read statement for better understanding). You can make hacks in these problems independently.}\n\nKoa the Koala has two strings $A$ and $B$ of the same length $n$ ($|A|=|B|=n$) consisting of the first $20$ lowercase English alphabet letters (ie. from a to t).\n\nIn one move Koa:\n\n- selects some subset of positions $p_1, p_2, \\ldots, p_k$ ($k \\ge 1; 1 \\le p_i \\le n; p_i \\neq p_j$ if $i \\neq j$) of $A$ such that $A_{p_1} = A_{p_2} = \\ldots = A_{p_k} = x$ (ie. all letters on this positions are equal to some letter $x$).\n- selects \\textbf{any} letter $y$ (from the first $20$ lowercase letters in English alphabet).\n- sets each letter in positions $p_1, p_2, \\ldots, p_k$ to letter $y$. More formally: for each $i$ ($1 \\le i \\le k$) Koa sets $A_{p_i} = y$.\\textbf{Note that you can only modify letters in string $A$}.\n\nKoa wants to know the smallest number of moves she has to do to make strings equal to each other ($A = B$) or to determine that there is no way to make them equal. Help her!",
    "tutorial": "The only difference between this problem and the previous problem is that the underlying graph might have cycles. Each weakly connected component can be solved independently and the answer is $2 \\cdot n - |LDAG| - 1$ where $n$ is the number of nodes in the component and $|LDAG|$ is the size of the largest Directed Acyclic Graph. The largest directed acyclic graph can be computed using dynamic programming in $O(2^n \\cdot n)$. For every node $u$ store a mask $reach[u]$ with all nodes it can reach directly. Then go through every possible mask from $1$ to $2^n - 1$ and check whether this set of nodes is acyclic or not. It is acyclic if there exists at least one node $u$ (the last node in one topological order) such that the set without this node is acyclic and this node doesn't reach any other node in this set: Proof by @eatmore: Lemma 1: Suppose that there is a weakly connected component with $n$ vertices, and there is a solution with $k$ edges. Then, the size of the largest DAG is at least $2 \\cdot n-1-k$. Proof: Let's keep track of current weakly connected components. Also, in each of the components, let's keep track of some DAG. Initially, each vertex is in a separate component, and each DAG consists of a single vertex. So, there are $n$ components, and the total size of all DAGs is $n$. Processing an edge $(u, v)$: If $u$ and $v$ are in the same component: if $v$ is in the DAG, remove it. Number of components is unchanged, the total size of all DAGs is decreased by at most 1. If $u$ and $v$ are in different components, join the components. Concatenate the DAGs (DAG of $u$'s component comes before DAG of $v$'s component). Number of components decreases by $1$, the total size of all DAGs is unchanged. At the end, the number of components becomes $1$, so $n-1$ edges are used to decrease the number of components. The remaining $k-n+1$ edges could decrease the size of DAGs, so the final size is at least $n-(k-n+1) = 2 \\cdot n-1-k$. From lemma 1 we know that $k >= 2 \\cdot n - 1 - |DAG|$, then $k$ is minimized when the size of the final DAG is maximized. Time complexity: $O(|A| + |B| + 2^n \\cdot n)$ per test case",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int Alp = 20;\n\nint main()\n{\n\tios_base::sync_with_stdio(0), cin.tie(0);\n\n\tint test;\n\tcin >> test;\n\twhile (test--)\n\t{\n\t    int len;\n\t\tstring a, b;\n\t\tcin >> len >> a >> b;\n\t\t\n\t\tvector<int> adj(Alp);\n\t\tvector<vector<int>> G(Alp);\n\t\tfor (int i = 0; i < len; ++i)\n\t\t\tif (a[i] != b[i])\n\t\t\t{\n\t\t\t\tadj[a[i]-'a'] |= 1 << (b[i]-'a');\n\t\t\t\tG[a[i]-'a'].push_back(b[i]-'a');\n\t\t\t\tG[b[i]-'a'].push_back(a[i]-'a');\n\t\t\t}\n\n\t\tvector<bool> mark(Alp);\n\t\tfunction<void(int)> dfs = [&](int u)\n\t\t{\n\t\t\tmark[u] = true;\n\t\t\tfor (auto v : G[u])\n\t\t\t\tif (!mark[v])\n\t\t\t\t\tdfs(v);\n\t\t};\n\n\t\tint comp = 0;\n\t\tfor (int i = 0; i < Alp; ++i)\n\t\t\tif (!mark[i])\n\t\t\t\tdfs(i), ++comp;\n\n\t\tint ans = 0;\n\t\tvector<bool> dp(1<<Alp);\n\t\tdp[0] = true;\n\t\tfor (int mask = 0; mask < 1<<Alp; ++mask)\n\t\t\tif (dp[mask])\n\t\t\t{\n\t\t\t\tans = max(ans, __builtin_popcount(mask));\n\t\t\t\tfor (int u = 0; u < Alp; ++u)\n\t\t\t\t\tif ((~mask >> u & 1) && (adj[u] & mask) == 0)\n\t\t\t\t\t\tdp[mask | 1 << u] = true;\n\t\t\t}\n\n\t\tcout << 2*Alp - comp - ans << \"\\n\";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1383",
    "index": "D",
    "title": "Rearrange",
    "statement": "Koa the Koala has a matrix $A$ of $n$ rows and $m$ columns. Elements of this matrix are distinct integers from $1$ to $n \\cdot m$ (each number from $1$ to $n \\cdot m$ appears exactly once in the matrix).\n\nFor any matrix $M$ of $n$ rows and $m$ columns let's define the following:\n\n- The $i$-th row of $M$ is defined as $R_i(M) = [ M_{i1}, M_{i2}, \\ldots, M_{im} ]$ for all $i$ ($1 \\le i \\le n$).\n- The $j$-th column of $M$ is defined as $C_j(M) = [ M_{1j}, M_{2j}, \\ldots, M_{nj} ]$ for all $j$ ($1 \\le j \\le m$).\n\nKoa defines $S(A) = (X, Y)$ as the spectrum of $A$, where $X$ is the set of the maximum values in rows of $A$ and $Y$ is the set of the maximum values in columns of $A$.\n\nMore formally:\n\n- $X = \\{ \\max(R_1(A)), \\max(R_2(A)), \\ldots, \\max(R_n(A)) \\}$\n- $Y = \\{ \\max(C_1(A)), \\max(C_2(A)), \\ldots, \\max(C_m(A)) \\}$\n\nKoa asks you to find some matrix $A'$ of $n$ rows and $m$ columns, such that each number from $1$ to $n \\cdot m$ appears exactly once in the matrix, and the following conditions hold:\n\n- $S(A') = S(A)$\n- $R_i(A')$ is bitonic for all $i$ ($1 \\le i \\le n$)\n- $C_j(A')$ is bitonic for all $j$ ($1 \\le j \\le m$)\n\nAn array $t$ ($t_1, t_2, \\ldots, t_k$) is called bitonic if it first increases and then decreases.More formally: $t$ is bitonic if there exists some position $p$ ($1 \\le p \\le k$) such that: $t_1 < t_2 < \\ldots < t_p > t_{p+1} > \\ldots > t_k$.\n\nHelp Koa to find such matrix or to determine that it doesn't exist.",
    "tutorial": "Let $A$ be a matrix of size $n \\cdot m$ that is formed by a permutation of elements from $1$ to $n \\cdot m$. Find the maximum element on each row and column (i.e. the spectrum) Now we are going to build the answer adding numbers one by one in decreasing order. We start with an empty 2 dimensional matrix (both dimensions have length 0) and at the end of each iteration the following invariants will be maintained on the matrix: All elements processed are inside of the matrix. Each row and column is bitonic. The horizontal/vertical spectrum of this matrix is a subset of the expected horizontal/vertical spectrum. In addition we are keeping a queue with all positions in the matrix that doesn't contain any element yet. At the end of each iteration the following invariants will be maintained on the queue: Let $A$ be a position on the queue and $B$ a position that contains a value that belongs to the horizontal spectrum in the matrix such that $A$ and $B$ are in the same row, then all positions between $A$ and $B$ have already an element in the matrix or occur in the queue before $A$. Let $A$ be a position on the queue and $B$ a position that contains a value that belongs to the vertical spectrum in the matrix such that $A$ and $B$ are in the same column, then all positions between $A$ and $B$ have already an element in the matrix or occur in the queue before $A$. In the end, invariants on the matrix guarantee that all elements are placed, each row and column consist in a bitonic sequence as required and the spectrums are equal to the expected spectrums. Let's prove each invariant on the matrix is kept: Clearly on each step a different element is placed on the matrix on an empty position, we should only show that the operation pop element from Queue doesn't fail with Queue empty. Say the current element is $t$, so the matrix is filled with elements larger than $t$. Now we know that in original matrix there were at least $n-x$ rows with maximums less than t and at least m-y columns with maximums less than $t$, so there could be at most $x \\cdot y$ elements greater or equal than t but there are $x \\cdot y+1$ already. On each row and column the first element added is the maximum and then elements are added in each direction starting from it toward each edge, since elements are processed from largest to smallest then each row and column is bitonic. The first element added on each row and column is the maximum, and we only add it if it is part of the expected spectrum. Time complexity: $O(n \\cdot m)$",
    "code": "#include <bits/stdc++.h>\n\n#define endl '\\n'\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    int n, m;\n    cin >> n >> m;\n\n    vector<vector<int>> mat(n, vector<int>(m));\n\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < m; ++j)\n            cin >> mat[i][j];\n\n    vector<int> h(n * m + 1);\n    vector<int> v(n * m + 1);\n\n    for (int i = 0; i < n; ++i)\n    {\n        int a = 0;\n        for (int j = 0; j < m; ++j)\n            a = max(a, mat[i][j]);\n        h[a] = 1;\n    }\n\n    for (int i = 0; i < m; ++i)\n    {\n        int a = 0;\n        for (int j = 0; j < n; ++j)\n            a = max(a, mat[j][i]);\n        v[a] = 1;\n    }\n\n    vector<vector<int>> fin(n, vector<int>(m));\n    queue<pair<int, int>> q;\n\n    int x = -1, y = -1;\n\n    for (int u = n * m; u >= 1; --u)\n    {\n        x += h[u];\n        y += v[u];\n\n        if (h[u] || v[u])\n        {\n            fin[x][y] = u;\n        }\n        else\n        {\n            int qx, qy;\n            tie(qx, qy) = q.front();\n            q.pop();\n            fin[qx][qy] = u;\n        }\n\n        if (h[u])\n            for (int i = y - 1; i >= 0; --i)\n                q.push({x, i});\n\n        if (v[u])\n            for (int i = x - 1; i >= 0; --i)\n                q.push({i, y});\n    }\n\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < m; ++j)\n            cout << fin[i][j] << \" \\n\"[j + 1 == m];\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1383",
    "index": "E",
    "title": "Strange Operation",
    "statement": "Koa the Koala has a binary string $s$ of length $n$. Koa can perform no more than $n-1$ (possibly zero) operations of the following form:\n\nIn one operation Koa selects positions $i$ and $i+1$ for some $i$ with $1 \\le i < |s|$ and sets $s_i$ to $max(s_i, s_{i+1})$. Then Koa deletes position $i+1$ from $s$ (after the removal, the remaining parts are concatenated).\n\nNote that after every operation the length of $s$ decreases by $1$.\n\nHow many different binary strings can Koa obtain by doing no more than $n-1$ (possibly zero) operations modulo $10^9+7$ ($1000000007$)?",
    "tutorial": "Firstly the described operation can be seen as divide $s$ in sub-strings and take the bitwise or in each one. For each possible resultant string $w$ let's think in the following way of obtain it from $s$: Suppose we already have a $1$ in $w$ in previous steps (if not it can be handled later) and we used the firsts $i$ characters of $s$ to get the firsts $j$ characters of $w$. if the $(j+1)$-th character in $w$ is $1$, find the next $1$ in $s$, (ie first $i' > i$ such that $s_{i'} = 1$), merge everything between the last $1$ and $i'-1$ and take the new $1$. if the $(j+1)$-th character in $w$ is $0$, and we have $k$ zeros after the last $1$ in $w$ find the next block of $k+1$ zeros in $s$, (ie first $i' > i$ such that for each $(0 \\le k' \\le k)$ $s_{i' - k'} = 0$), if $i'$ is equal to $i+1$ just append the new $0$ to $w$ otherwise merge everything between the last $1$ and $i'-k$ and take the new zeros from $i'-k+1$ to $i'$.We can prove that in this way every possible resultant string $w$ is generated in a unique way and it uses the minimum number of characters from $s$ to obtain $w$. We can prove that in this way every possible resultant string $w$ is generated in a unique way and it uses the minimum number of characters from $s$ to obtain $w$. So we can start thinking about dynamic programming keeping in mind this greedy. Let $dp(i)$ be the number of strings that we can obtain using the last $n-i$ characters from $s$, the transitions are the previous described two cases, taking care of the case of ending with certain numbers of $0$. Therefore: If there is at least a $1$ in $s$, let $i$ be the first position such that $s_i = 1$, answer equals $dp(i) \\cdot i$ (because we start assuming that there exists some previous $1$ and before this $1$ there are exactly $i$ possibilities: empty, one $0$, two $0$s, ..., $i - 1$ $0$s). Otherwise answer is $|s|$ (because $s$ consists of all $0$). Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int mod = 1000000007;\n\nint main()\n{\n\tios::sync_with_stdio(false), cin.tie(0);\n\n\tstring s; cin >> s;\n\tint n = s.length();\n\tvector<int> dist(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tif (s[i] == '0') dist[i] = (i ? dist[i-1] : 0) + 1;\n\n\tvector<int> dp(n + 2), nxt(n+2, n);\n\tauto get = [&](int i) { return nxt[i] < n ? dp[nxt[i]] : 0; };\n\n\tfor (int i = n-1; i >= 0; --i)\n\t{\n\t\tdp[i] = ((dist[i] <= dist.back()) + get(0) + get(dist[i] + 1)) % mod;\n\t\tnxt[dist[i]] = i;\n\t}\n\n\tint ans = n;\n\tif (nxt[0] < n)\n\t\tans = ((long long)get(0) * (nxt[0] + 1)) % mod;\n\tcout << ans << \"\\n\";\n\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1383",
    "index": "F",
    "title": "Special Edges",
    "statement": "Koa the Koala has a \\textbf{directed} graph $G$ with $n$ nodes and $m$ edges. Each edge has a capacity associated with it. Exactly $k$ edges of the graph, numbered from $1$ to $k$, are special, such edges initially have a capacity equal to $0$.\n\nKoa asks you $q$ queries. In each query she gives you $k$ integers $w_1, w_2, \\ldots, w_k$. This means that capacity of the $i$-th special edge becomes $w_i$ (and other capacities remain the same).\n\nKoa wonders: what is the maximum flow that goes from node $1$ to node $n$ after each such query?\n\nHelp her!",
    "tutorial": "Finding maximum flow from $1$ to $n$ is equivalent to find the minimum cut from $1$ to $n$. Let's use the later interpretation to solve the problem. Suppose there is a single special edge ($k = 1$), on each query there are two options, either this edge belong to the minimum cut or it doesn't. If the edge doesn't belong to the minimum cut, the value of the cut won't change even if we increase the capacity of each edge arbitrarily (let's say to $\\infty$). On the other hand, if the edge belong to the cut, then the value of the cut will be equal to the capacity of the edge + the value of the cut if the capacity of the edge was $0$. With this in mind we can compute each query in O(1). Let $MC_0$ be the value of the minimum cut if the capacity of the special edge is 0, and $MC_{\\infty}$ be the value of the minimum cut if the capacity of the special edge is $\\infty$. Then for each query $c_i$ the minimum cut will be equal to $min(MC_{\\infty}, MC_0 + c_i)$. We can generalize this ideas to multiple edges in the following way. For each subset of special edges, they either belong to the minimum cut, or they don't. If we fix a subset $S$ and say those are among the special edges the only ones that belong to the minimum cut, then the value of the cut will be equal to the sum of the values of the capacities of these edges plus the minimum cut in the graph were each of these edges has capacity 0 and other special edges has capacity $\\infty$. In a similar way as we did for the case of $k=1$ we can pre-compute $2^k$ cuts, fixing $S$ as each possible set in $O(2^k \\cdot max\\_flow(n, m))$, and then answer each query in $O(2^k)$. The overall complexity of this solution will be $O(2^k \\cdot max\\_flow(n, m) + q \\cdot 2^k)$. However the preprocessing can be done faster. If we have the maximum flow (and the residual network) for a mask, we can compute the maximum flow adding one new edge in $O(w * m)$, doing at most $w$ steps of augmentation as done by Ford-Fulkerson algorithm. To remove an edge we just store the residual network before augmenting, in such a way that we can undo the last change. The time complexity of the preprocessing will be $O(max\\_flow(n, m) + 2^k \\cdot w \\cdot m)$ and since we need to be able to undo the last operation spatial complexity will be $O(k \\cdot m)$. It was possible to solve the problem without the last trick, but it was not guaranteed that slow flows implementations would work in $O(2^k \\cdot max\\_flow(n, m))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate<typename C, typename R = C>\nstruct dinic\n{\n\ttypedef C flow_type;\n\ttypedef R result_type;\n\n\tstatic_assert(std::is_arithmetic<flow_type>::value, \"flow_type must be arithmetic\");\n\tstatic_assert(std::is_arithmetic<result_type>::value, \"result_type must be arithmetic\");\n\n\tstatic const flow_type oo = std::numeric_limits<flow_type>::max();\n\n\tstruct edge\n\t{\n\t\t//int src; // not needed, can be deleted to save memory\n\t\tint dst;\n\t\tint rev;\n\t\tflow_type cap, flowp;\n\n\t\tedge(int src, int dst, int rev, flow_type cap, int flowp) :\n\t\t\t/*src(src),*/ dst(dst), rev(rev), cap(cap), flowp(flowp) {}\n\t};\n\n\tdinic(int n) : adj(n), que(n), level(n), edge_pos(n), flow_id(0) {}\n\n\tint add_edge(int src, int dst, flow_type cap, flow_type rcap = 0)\n\t{\n\t\tadj[src].emplace_back(src, dst, (int) adj[dst].size(), cap, flow_id++);\n\t\tif (src == dst) adj[src].back().rev++;\n\t\tadj[dst].emplace_back(dst, src,  (int) adj[src].size() - 1, rcap, flow_id++);\n\t\treturn (int) adj[src].size() - 1 - (src == dst);\n\t}\n\n\tinline bool side_of_S(int u) { return level[u] == -1; }\n\n\tresult_type max_flow(int source, int sink, vector<flow_type> &flow_e)\n\t{\n\t\tresult_type flow = 0;\n\t\twhile (true)\n\t\t{\n\t\t\tint front = 0, back = 0;\n\t\t\tstd::fill(level.begin(), level.end(), -1);\n\t\t\tfor (level[que[back++] = sink] = 0; front < back && level[source] == -1; ++front)\n\t\t\t{\n\t\t\t\tint u = que[front];\n\t\t\t\tfor (const edge &e : adj[u])\n\t\t\t\t\tif (level[e.dst] == -1 && flow_e[rev(e).flowp] < rev(e).cap)\n\t\t\t\t\t\tlevel[que[back++] = e.dst] = 1 + level[u];\n\t\t\t}\n\t\t\tif (level[source] == -1)\n\t\t\t\tbreak;\n\t\t\tstd::fill(edge_pos.begin(), edge_pos.end(), 0);\n\t\t\tstd::function<flow_type(int, flow_type)> find_path = [&](int from, flow_type res)\n\t\t\t{\n\t\t\t\tif (from == sink)\n\t\t\t\t\treturn res;\n\t\t\t\tfor (int &ept = edge_pos[from]; ept < (int) adj[from].size(); ++ept)\n\t\t\t\t{\n\t\t\t\t\tedge &e = adj[from][ept];\n\t\t\t\t\tif (flow_e[e.flowp] == e.cap || level[e.dst] + 1 != level[from]) continue;\n\t\t\t\t\tflow_type push = find_path(e.dst, std::min(res, e.cap - flow_e[e.flowp]));\n\t\t\t\t\tif (push > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tflow_e[e.flowp] += push;\n\t\t\t\t\t\tflow_e[rev(e).flowp] -= push;\n\t\t\t\t\t\tif (flow_e[e.flowp] == e.cap)\n\t\t\t\t\t\t\t++ept;\n\t\t\t\t\t\treturn push;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn static_cast<flow_type>(0);\n\t\t\t};\n\t\t\tfor (flow_type f; (f = find_path(source, oo)) > 0;)\n\t\t\t\tflow += f;\n\t\t}\n\t\treturn flow;\n\t}\n\n\tresult_type max_flow2(int source, int sink, vector<flow_type> &flow_e)\n\t{\n\t\tresult_type flow = 0;\n\t\tstd::function<flow_type(int, flow_type)> find_path = [&](int from, flow_type res)\n\t\t{\n\t\t\tlevel[from] = 1;\n\t\t\tif (from == sink)\n\t\t\t\treturn res;\n\t\t\tfor (int &ept = edge_pos[from]; ept < (int) adj[from].size(); ++ept)\n\t\t\t{\n\t\t\t\tedge &e = adj[from][ept];\n\t\t\t\tif (level[e.dst] == 1 || flow_e[e.flowp] == e.cap) continue;\n\t\t\t\tflow_type push = find_path(e.dst, std::min(res, e.cap - flow_e[e.flowp]));\n\t\t\t\tif (push > 0)\n\t\t\t\t{\n\t\t\t\t\tflow_e[e.flowp] += push;\n\t\t\t\t\tflow_e[rev(e).flowp] -= push;\n\t\t\t\t\tif (flow_e[e.flowp] == e.cap)\n\t\t\t\t\t\t++ept;\n\t\t\t\t\treturn push;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn static_cast<flow_type>(0);\n\t\t};\n\t\t\n\t\tfor (bool ok = true; ok; )\n\t\t{\n\t\t\tint it = 0;\n\t\t\tstd::fill(edge_pos.begin(), edge_pos.end(), 0);\n\t\t\tfor (flow_type f; ; ++it)\n\t\t\t{\n\t\t\t\tstd::fill(level.begin(), level.end(), -1);\n\t\t\t\tf = find_path(source, oo);\n\t\t\t\tif (f == 0)\n\t\t\t\t{\n\t\t\t\t\tif (it == 0) ok = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tflow += f;\n\t\t\t}\n\t\t}\n\t\treturn flow;\n\t}\n\n\tint flow_id;\nprivate:\n\tstd::vector<std::vector<edge>> adj;\n\tstd::vector<int> que;\n\tstd::vector<int> level;\n\tstd::vector<int> edge_pos;\n\n\tinline edge& rev(const edge &e) { return adj[e.dst][e.rev]; }\n};\n\nconst int inf = 25;\n\nstruct edge\n{\n\tint u, v, w;\n};\n\nmt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n\nvoid relabel(int n, vector<edge> &e, int k)\n{\n\tshuffle(e.begin() + k, e.end(), rng);\n\n\tvector<vector<pair<int, int>>> adj(n);\n\tfor (auto &i : e)\n\t\tadj[i.u].push_back({ i.v, &i-&e[0] });\n\n\tvector<edge> ne = e;\n\tvector<int> id(n, -1);\n\tid[0] = 0;\n\tid[n-1] = n-1;\n\tint sz = 1, esz = k;\n\n\tfunction<void(int)> dfs = [&](int u)\n\t{\n\t\tfor (auto &v : adj[u])\n\t\t{\n\t\t\tif (v.second >= k)\n\t\t\t{\n\t\t\t\tne[esz++] = e[v.second];\n\t\t\t\tv.second = -1;\n\t\t\t}\n\t\t\tif (id[v.first] == -1)\n\t\t\t{\n\t\t\t\tid[v.first] = sz++;\n\t\t\t\tdfs(v.first);\n\t\t\t}\n\t\t}\n\t};\n\tdfs(0);\n\t\n\tfor (auto &u : adj)\n\t\tfor (auto v : u)\n\t\t\tif (v.second >= k)\n\t\t\t\tne[esz++] = e[v.second];\n\t\n\tfor (int i = 0; i < n; ++i)\n\t\tif (id[i] == -1)\n\t\t\tid[i] = sz++;\n\t\t\t\n\te = ne;\n\tfor (auto &i : e)\n\t{\n\t\ti.u = id[i.u];\n\t\ti.v = id[i.v];\n\t}\n}\n\nstruct masks\n{\n\tint x, cost;\n\tvector<int> flow_e;\n\t\n\tbool operator<(const masks &o) const\n\t{\n\t\treturn cost < o.cost;\n\t}\n};\n\ntypedef std::chrono::_V2::system_clock::time_point timepoint;\n\ntimepoint get_time()\n{\n\treturn std::chrono::high_resolution_clock::now();\n}\n\nint get_elapsed(timepoint t)\n{\n\treturn std::chrono::duration_cast<std::chrono::milliseconds>(get_time() - t).count();\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(0), cin.tie(0);\n\n\tint n, m, k, q;\n\tcin >> n >> m >> k >> q;\n\tvector<edge> e(m);\n\tfor (auto &i : e) cin >> i.u >> i.v >> i.w, --i.u, --i.v;\n\n\tvector<int> mask(1 << k, -1);\n\t\n\trelabel(n, e, k);\n\tdinic<int> d(n);\n\tfor (int i = 0; i < m; ++i)\n\t\td.add_edge(e[i].u, e[i].v, ((i < k) ? inf : e[i].w));\n\n\tvector<int> flow_e(d.flow_id);\n\tfor (int i = 0; i < k; ++i)\n\t\tflow_e[2*i] = inf;\n\n\tmask[0] = d.max_flow(0, n-1, flow_e);\n\t\n\tpriority_queue<masks> pq;\n\tpq.push({ 0, 0, flow_e });\n\twhile (!pq.empty())\n\t{\n\t\tint x = pq.top().x;\n\t\tflow_e = pq.top().flow_e;\n\t\tpq.pop();\n\t\t\n\t\tfor (int j = 0; j < k; ++j)\n\t\t\tif ((~x >> j & 1) && mask[x | 1 << j] == -1)\n\t\t\t{\n\t\t\t\tauto n_flow_e = flow_e;\n\t\t\t\tn_flow_e[2 * j] = 0;\n\t\t\t\tauto t = get_time();\n\t\t\t\tmask[x | 1 << j] = mask[x] + d.max_flow2(0, n-1, n_flow_e);\n\t\t\t\tpq.push({ x | 1 << j, get_elapsed(t), n_flow_e });\n\t\t\t}\n\t}\n\n\tvector<int> cut(1 << k), bit(1 << k);\n\tfor (int i = 1; i < 1 << k; ++i)\n\t\tbit[i] = i & -i;\n\n\tconst int U = (1 << k) - 1;\n\twhile (q--)\n\t{\n\t\tfor (int i = 0; i < k; ++i)\n\t\t\tcin >> cut[1 << i];\n\n\t\tint ans = mask[U];\n\t\tfor (int i = 1; i < 1<<k; ++i)\n\t\t{\n\t\t\tcut[i] = cut[i ^ bit[i]] + cut[bit[i]];\n\t\t\tans = min(ans, cut[i] + mask[U ^ i]);\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1384",
    "index": "A",
    "title": "Common Prefixes",
    "statement": "The length of the \\textbf{longest common prefix} of two strings $s = s_1 s_2 \\ldots s_n$ and $t = t_1 t_2 \\ldots t_m$ is defined as the maximum integer $k$ ($0 \\le k \\le min(n,m)$) such that $s_1 s_2 \\ldots s_k$ equals $t_1 t_2 \\ldots t_k$.\n\nKoa the Koala initially has $n+1$ strings $s_1, s_2, \\dots, s_{n+1}$.\n\nFor each $i$ ($1 \\le i \\le n$) she calculated $a_i$ — the length of the \\textbf{longest common prefix} of $s_i$ and $s_{i+1}$.\n\nSeveral days later Koa found these numbers, but she couldn't remember the strings.\n\nSo Koa would like to find some strings $s_1, s_2, \\dots, s_{n+1}$ which would have generated numbers $a_1, a_2, \\dots, a_n$. Can you help her?\n\nIf there are many answers print any. We can show that answer always exists for the given constraints.",
    "tutorial": "The problem asks to find $n+1$ strings such that $LCP(s_i, s_{i + 1}) = a_i$ for all $i$ ($1 \\le i \\le n$). A way to solve this problem is the following: Set $s_1 =$ \"aaaa...aaaaaaa\" (ie. $200$ times 'a'). For $i$ such that ($1 \\le i \\le n$) set $s_{i + 1} := s_i$ and then flip $(a_i + 1)$-th character of $s_{i + 1}$ (ie. if it was 'a' put 'b' otherwise 'a'). So for each $i$: $s_{i}$ and $s_{i + 1}$ will have exactly $a_i$ common characters from the prefix. The $(a_i + 1)$-th character of $s_{i+1}$ is different than $(a_i + 1)$-th character of $s_i$ (this character always exists since $0 \\le a_i \\le 50$ and each string has length exactly $200$). Therefore the LCP is $a_i$ as desired. So for each $i$: $s_{i}$ and $s_{i + 1}$ will have exactly $a_i$ common characters from the prefix. The $(a_i + 1)$-th character of $s_{i+1}$ is different than $(a_i + 1)$-th character of $s_i$ (this character always exists since $0 \\le a_i \\le 50$ and each string has length exactly $200$). Therefore the LCP is $a_i$ as desired. Time complexity: $O(n)$ per testcase",
    "code": "import sys\ninput = sys.stdin.readline\n\ndef main():\n    t = int(input())\n    \n    for _ in range(t):\n        n = int(input())\n        a = list(map(int, input().split()))\n    \n        mx = max(a)\n        ans = [ 'a' * (mx + 1) ] * (n + 1)\n    \n        for i, x in enumerate(a):\n            who = 'a' if ans[i][x] == 'b' else 'b'\n            ans[i + 1] = ans[i][:x] + who + ans[i][x + 1:]\n    \n        print('\\n'.join(ans))    \n\nmain()",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1384",
    "index": "B1",
    "title": "Koa and the Beach (Easy Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is on constraints. In this version constraints are lower. You can make hacks only if all versions of the problem are solved.}\n\nKoa the Koala is at the beach!\n\nThe beach consists (from left to right) of a shore, $n+1$ meters of sea and an island at $n+1$ meters from the shore.\n\nShe measured the depth of the sea at $1, 2, \\dots, n$ meters from the shore and saved them in array $d$. $d_i$ denotes the depth of the sea at $i$ meters from the shore for $1 \\le i \\le n$.\n\nLike any beach this one has tide, the intensity of the tide is measured by parameter $k$ and affects all depths \\textbf{from the beginning at time $t=0$} in the following way:\n\n- For a total of $k$ seconds, each second, tide \\textbf{increases} all depths by $1$.\n- Then, for a total of $k$ seconds, each second, tide \\textbf{decreases} all depths by $1$.\n- This process repeats again and again (ie. depths increase for $k$ seconds then decrease for $k$ seconds and so on ...).Formally, let's define $0$-indexed array $p = [0, 1, 2, \\ldots, k - 2, k - 1, k, k - 1, k - 2, \\ldots, 2, 1]$ of length $2k$. At time $t$ ($0 \\le t$) depth at $i$ meters from the shore equals $d_i + p[t \\bmod 2k]$ ($t \\bmod 2k$ denotes the remainder of the division of $t$ by $2k$). Note that the changes occur \\textbf{instantaneously} after each second, see the notes for better understanding.\n\nAt time $t=0$ Koa is standing at the shore and wants to get to the island. Suppose that at some time $t$ ($0 \\le t$) she is at $x$ ($0 \\le x \\le n$) meters from the shore:\n\n- In one second Koa can swim $1$ meter further from the shore ($x$ changes to $x+1$) or not swim at all ($x$ stays the same), in both cases $t$ changes to $t+1$.\n- As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed $l$ at integer points of time (or she will drown). More formally, if Koa is at $x$ ($1 \\le x \\le n$) meters from the shore at the moment $t$ (for some integer $t\\ge 0$), the depth of the sea at this point  — $d_x + p[t \\bmod 2k]$  — can't exceed $l$. In other words, $d_x + p[t \\bmod 2k] \\le l$ must hold always.\n- Once Koa reaches the island at $n+1$ meters from the shore, she stops and can rest.Note that \\textbf{while Koa swims tide doesn't have effect on her} (ie. she can't drown while swimming). Note that \\textbf{Koa can choose to stay on the shore for as long as she needs} and \\textbf{neither the shore or the island are affected by the tide} (they are solid ground and she won't drown there).\n\nKoa wants to know whether she can go from the shore to the island. Help her!",
    "tutorial": "For this version you can just simulate each possible action of Koa. Let $(pos, tide, down)$ a state where $pos$ is the current position of Koa (ie $0$ is the shore, from $1$ to $n$ is the $i$-th meter of sea and $n+1$ is the island), $tide$ is the current increment of the tide, and $down$ is a boolean that is true if the tide is decreasing and false otherwise. You can see each state like a node and each action (ie. wait or swim) like an edge, so you can just do a dfs to see if the island is reachable from the shore. The number of nodes and edges is $O(n \\cdot k)$. Time complexity: $O(n \\cdot k)$ per testcase",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tios_base::sync_with_stdio(0), cin.tie(0);\n\n\tint test;\n\tcin >> test;\n\twhile (test--)\n\t{\n\t\tint n, k, l;\n\t\tcin >> n >> k >> l;\n\t\tvector<int> d(n+2, -k);\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t\tcin >> d[i];\n\n\t\tset<tuple<int, int, bool>> mark;\n\t\tfunction<bool(int, int, bool)> go = [&](int pos, int tide, bool down)\n\t\t{\n\t\t\tif (pos > n) return true;\n\t\t\t\n\t\t\tif (mark.find({ pos, tide, down }) != mark.end())\n\t\t\t\treturn false;\n\n\t\t\tmark.insert({ pos, tide, down });\n\n\t\t\ttide += down ? -1 : +1;\n\t\t\tif (tide == 0) down = false;\n\t\t\tif (tide == k) down = true;\n\n\t\t\tif (d[pos] + tide <= l && go(pos, tide, down))\n\t\t\t\treturn true;\n\t\t\tif (d[pos + 1] + tide <= l && go(pos + 1, tide, down))\n\t\t\t\treturn true;\n\t\t\treturn false;\n\t\t};\n\n\t\tif (go(0, 0, false)) cout << \"Yes\\n\";\n\t\telse cout << \"No\\n\";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1384",
    "index": "B2",
    "title": "Koa and the Beach (Hard Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.}\n\nKoa the Koala is at the beach!\n\nThe beach consists (from left to right) of a shore, $n+1$ meters of sea and an island at $n+1$ meters from the shore.\n\nShe measured the depth of the sea at $1, 2, \\dots, n$ meters from the shore and saved them in array $d$. $d_i$ denotes the depth of the sea at $i$ meters from the shore for $1 \\le i \\le n$.\n\nLike any beach this one has tide, the intensity of the tide is measured by parameter $k$ and affects all depths \\textbf{from the beginning at time $t=0$} in the following way:\n\n- For a total of $k$ seconds, each second, tide \\textbf{increases} all depths by $1$.\n- Then, for a total of $k$ seconds, each second, tide \\textbf{decreases} all depths by $1$.\n- This process repeats again and again (ie. depths increase for $k$ seconds then decrease for $k$ seconds and so on ...).Formally, let's define $0$-indexed array $p = [0, 1, 2, \\ldots, k - 2, k - 1, k, k - 1, k - 2, \\ldots, 2, 1]$ of length $2k$. At time $t$ ($0 \\le t$) depth at $i$ meters from the shore equals $d_i + p[t \\bmod 2k]$ ($t \\bmod 2k$ denotes the remainder of the division of $t$ by $2k$). Note that the changes occur \\textbf{instantaneously} after each second, see the notes for better understanding.\n\nAt time $t=0$ Koa is standing at the shore and wants to get to the island. Suppose that at some time $t$ ($0 \\le t$) she is at $x$ ($0 \\le x \\le n$) meters from the shore:\n\n- In one second Koa can swim $1$ meter further from the shore ($x$ changes to $x+1$) or not swim at all ($x$ stays the same), in both cases $t$ changes to $t+1$.\n- As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed $l$ at integer points of time (or she will drown). More formally, if Koa is at $x$ ($1 \\le x \\le n$) meters from the shore at the moment $t$ (for some integer $t\\ge 0$), the depth of the sea at this point  — $d_x + p[t \\bmod 2k]$  — can't exceed $l$. In other words, $d_x + p[t \\bmod 2k] \\le l$ must hold always.\n- Once Koa reaches the island at $n+1$ meters from the shore, she stops and can rest.Note that \\textbf{while Koa swims tide doesn't have effect on her} (ie. she can't drown while swimming). Note that \\textbf{Koa can choose to stay on the shore for as long as she needs} and \\textbf{neither the shore or the island are affected by the tide} (they are solid ground and she won't drown there).\n\nKoa wants to know whether she can go from the shore to the island. Help her!",
    "tutorial": "Let's define positions $i$ such that ($1 \\le i \\le n$) and $d_i + k \\le l$ as safe positions, also positions $0$ and $n + 1$ are safe too (ie. the shore and the island respectively). Remaining positions are unsafe. Koa can wait indefinitely on safe positions without drowning, so she can reach the island (ie. position $n+1$) if and only if she can reach each safe position from the previous one. Suppose Koa is at some safe position $i$ and wants to reach the next safe position $j$ ($0 \\le i < j \\le n + 1$): A solution strategy for Koa is the following: If Koa is at an unsafe position $x$ at time $t_0$, she must swim to $x + 1$ as soon as she can, that is, at the first moment of time $t \\ge t_0$ such that $d_{x + 1} + p[(t + 1) \\bmod 2k] \\le l$ (to not drown). If Koa is at a safe position $x$ at time $t_0$, she must wait to some moment of time $t_1$ such that tide is exactly at $k$ units. After that she must follow the unsafe positions strategy until the next safe position. So a way to go from $i$ to $j$ would be, apply point $2$ on $i$, and apply point $1$ to reach each position $p$ such that ($i < p \\le j$). This works because: If there exists some position with $d_p$ greater than $l$ she would drown with any tide so let's assume that all positions are less or equal to $l$. Suppose Koa drowns at some position $p$, she can leave $i$ with some value of tide because $d_{i+1} \\le l$ and as long as the tide is decreasing whether she chooses to wait or not she would be safe. So she must have drown with the tide increasing. If she leaves $i$ with other tide (different from $k$): suppose she would be able to reach position $p$, then the tide will have increased and it will be higher and therefore she would drown too, this is true because the tide never can be $k$ and start decreasing again between $i$ and $j$ because these positions are unsafe ones. Time complexity: $O(n)$ per test case",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tios_base::sync_with_stdio(0), cin.tie(0);\n\n\tint test;\n\tcin >> test;\n\twhile (test--)\n\t{\n\t\tint n, k, l;\n\t\tcin >> n >> k >> l;\n\t\tvector<int> d(n+1), safe = { 0 };\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t{\n\t\t\tcin >> d[i];\n\t\t\tif (d[i] + k <= l)\n\t\t\t\tsafe.push_back(i);\n\t\t}\n\n\t\tsafe.push_back(n+1);\n\t\tbool ok = true;\n\t\tfor (size_t i = 1; i < safe.size() && ok; ++i)\n\t\t{\n\t\t\tint tide = k; bool down = true;\n\t\t\tfor (int j = safe[i-1] + 1; j < safe[i]; ++j)\n\t\t\t{\n\t\t\t\ttide += down ? -1 : +1;\n\n\t\t\t\tif (down) tide -= max(0, d[j] + tide - l);\n\t\t\t\tif (tide < 0 || d[j] + tide > l) { ok = false; break; }\n\n\t\t\t\tif (tide == 0) down = false;\n\t\t\t}\n\t\t}\n\n\t\tif (ok) cout << \"Yes\\n\";\n\t\telse cout << \"No\\n\";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1385",
    "index": "A",
    "title": "Three Pairwise Maximums",
    "statement": "You are given three positive (i.e. strictly greater than zero) integers $x$, $y$ and $z$.\n\nYour task is to find positive integers $a$, $b$ and $c$ such that $x = \\max(a, b)$, $y = \\max(a, c)$ and $z = \\max(b, c)$, or determine that it is impossible to find such $a$, $b$ and $c$.\n\nYou have to answer $t$ independent test cases. Print required $a$, $b$ and $c$ in any (arbitrary) order.",
    "tutorial": "Suppose $x \\le y \\le z$. If $y \\ne z$ then the answer is -1, because $z$ is the overall maximum among all three integers $a$, $b$ and $c$ and it appears in two pairs (so it should appear at most twice among $x$, $y$ and $z$). Otherwise, the answer exists and it can be $x$, $x$ and $z$ (it is easy to see that this triple fits well).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tvector<int> a(3);\n\t\tfor (auto &it : a) cin >> it;\n\t\tsort(a.begin(), a.end());\n\t\tif (a[1] != a[2]) {\n\t\t\tcout << \"NO\" << endl;\n\t\t} else {\n\t\t\tcout << \"YES\" << endl << a[0] << \" \" << a[0] << \" \" << a[2] << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1385",
    "index": "B",
    "title": "Restore the Permutation by Merger",
    "statement": "A permutation of length $n$ is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ are permutations, and $[1, 1]$, $[0, 1]$, $[2, 2, 1, 4]$ are not.\n\nThere was a permutation $p[1 \\dots n]$. It was merged with itself. In other words, let's take two instances of $p$ and insert elements of the second $p$ into the first maintaining relative order of elements. The result is a sequence of the length $2n$.\n\nFor example, if $p=[3, 1, 2]$ some possible results are: $[3, 1, 2, 3, 1, 2]$, $[3, 3, 1, 1, 2, 2]$, $[3, 1, 3, 1, 2, 2]$. The following sequences are not possible results of a merging: $[1, 3, 2, 1, 2, 3$], [$3, 1, 2, 3, 2, 1]$, $[3, 3, 1, 2, 2, 1]$.\n\nFor example, if $p=[2, 1]$ the possible results are: $[2, 2, 1, 1]$, $[2, 1, 2, 1]$. The following sequences are not possible results of a merging: $[1, 1, 2, 2$], [$2, 1, 1, 2]$, $[1, 2, 2, 1]$.\n\nYour task is to restore the permutation $p$ by the given resulting sequence $a$. It is guaranteed that the answer \\textbf{exists and is unique}.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The solution is pretty simple: it's obvious that the first element of $a$ is the first element of the permutation $p$. Let's take it to $p$, remove it and its its copy from $a$. So we just have the smaller problem and can solve it in the same way. It can be implemented as \"go from left to right, if the current element isn't used, take it and mark it's used\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(2 * n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tvector<int> used(n);\n\t\tvector<int> p;\n\t\tfor (int i = 0; i < 2 * n; ++i) {\n\t\t\tif (!used[a[i] - 1]) {\n\t\t\t\tused[a[i] - 1] = true;\n\t\t\t\tp.push_back(a[i]);\n\t\t\t}\n\t\t}\n\t\tfor (auto it : p) cout << it << \" \";\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1385",
    "index": "C",
    "title": "Make It Good",
    "statement": "You are given an array $a$ consisting of $n$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $a$ to make it a good array. Recall that the prefix of the array $a=[a_1, a_2, \\dots, a_n]$ is a subarray consisting several first elements: the prefix of the array $a$ of length $k$ is the array $[a_1, a_2, \\dots, a_k]$ ($0 \\le k \\le n$).\n\nThe array $b$ of length $m$ is called good, if you can obtain a \\textbf{non-decreasing} array $c$ ($c_1 \\le c_2 \\le \\dots \\le c_{m}$) from it, repeating the following operation $m$ times (initially, $c$ is empty):\n\n- select either the first or the last element of $b$, remove it from $b$, and append it to the end of the array $c$.\n\nFor example, if we do $4$ operations: take $b_1$, then $b_{m}$, then $b_{m-1}$ and at last $b_2$, then $b$ becomes $[b_3, b_4, \\dots, b_{m-3}]$ and $c =[b_1, b_{m}, b_{m-1}, b_2]$.\n\nConsider the following example: $b = [1, 2, 3, 4, 4, 2, 1]$. This array is \\textbf{good} because we can obtain \\textbf{non-decreasing} array $c$ from it by the following sequence of operations:\n\n- take the first element of $b$, so $b = [2, 3, 4, 4, 2, 1]$, $c = [1]$;\n- take the last element of $b$, so $b = [2, 3, 4, 4, 2]$, $c = [1, 1]$;\n- take the last element of $b$, so $b = [2, 3, 4, 4]$, $c = [1, 1, 2]$;\n- take the first element of $b$, so $b = [3, 4, 4]$, $c = [1, 1, 2, 2]$;\n- take the first element of $b$, so $b = [4, 4]$, $c = [1, 1, 2, 2, 3]$;\n- take the last element of $b$, so $b = [4]$, $c = [1, 1, 2, 2, 3, 4]$;\n- take the only element of $b$, so $b = []$, $c = [1, 1, 2, 2, 3, 4, 4]$ — $c$ is non-decreasing.\n\nNote that the array consisting of one element is good.\n\nPrint the length of the shortest prefix of $a$ to delete (erase), to make $a$ to be a good array. Note that the required length can be $0$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Consider the maximum element $a_{mx}$ of the good array $a$ of length $k$. Then we can notice that the array $a$ looks like $[a_1 \\le a_2 \\le \\dots \\le a_{mx} \\ge \\dots \\ge a_{k-1} \\ge a_k]$. And this is pretty obvious that if the array doesn't have this structure, then it isn't good (you can see it yourself). So we need to find the longest such suffix. It's pretty easy doable with pointer: initially, the pointer $pos$ is at the last element. Then, while $pos > 1$ and $a_{pos - 1} \\ge a_{pos}$, decrease $pos$ by one. If we're done with the previous step, we do the same, but while $pos > 1$ and $a_{pos - 1} \\le a_{pos}$. The answer is $pos-1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tint pos = n - 1;\n\t\twhile (pos > 0 && a[pos - 1] >= a[pos]) --pos;\n\t\twhile (pos > 0 && a[pos - 1] <= a[pos]) --pos;\n\t\tcout << pos << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1385",
    "index": "D",
    "title": "a-Good String",
    "statement": "You are given a string $s[1 \\dots n]$ consisting of lowercase Latin letters. It is guaranteed that $n = 2^k$ for some integer $k \\ge 0$.\n\nThe string $s[1 \\dots n]$ is called $c$-good if \\textbf{at least one} of the following three conditions is satisfied:\n\n- The length of $s$ is $1$, and it consists of the character $c$ (i.e. $s_1=c$);\n- The length of $s$ is greater than $1$, the first half of the string consists of only the character $c$ (i.e. $s_1=s_2=\\dots=s_{\\frac{n}{2}}=c$) and the second half of the string (i.e. the string $s_{\\frac{n}{2} + 1}s_{\\frac{n}{2} + 2} \\dots s_n$) is a $(c+1)$-good string;\n- The length of $s$ is greater than $1$, the second half of the string consists of only the character $c$ (i.e. $s_{\\frac{n}{2} + 1}=s_{\\frac{n}{2} + 2}=\\dots=s_n=c$) and the first half of the string (i.e. the string $s_1s_2 \\dots s_{\\frac{n}{2}}$) is a $(c+1)$-good string.\n\nFor example: \"aabc\" is 'a'-good, \"ffgheeee\" is 'e'-good.\n\nIn one move, you can choose one index $i$ from $1$ to $n$ and replace $s_i$ with any lowercase Latin letter (any character from 'a' to 'z').\n\nYour task is to find the minimum number of moves required to obtain an 'a'-good string from $s$ (i.e. $c$-good string for $c=$ 'a'). It is guaranteed that the answer always exists.\n\nYou have to answer $t$ independent test cases.\n\nAnother example of an 'a'-good string is as follows. Consider the string $s = $\"cdbbaaaa\". It is an 'a'-good string, because:\n\n- the second half of the string (\"aaaa\") consists of only the character 'a';\n- the first half of the string (\"cdbb\") is 'b'-good string, because:\n\n- the second half of the string (\"bb\") consists of only the character 'b';\n- the first half of the string (\"cd\") is 'c'-good string, because:\n\n- the first half of the string (\"c\") consists of only the character 'c';\n- the second half of the string (\"d\") is 'd'-good string.",
    "tutorial": "Consider the problem in $0$-indexation. Define the function $calc(l, r, c)$ which finds the minimum number of changes to make the string $s[l \\dots r)$ $c$-good string. Let $mid = \\frac{l + r}{2}$. Then let $cnt_l = \\frac{r - l}{2} - count(s[l \\dots mid), c) + calc(mid, r, c + 1)$ and $cnt_r = \\frac{r - l}{2} - count(s[mid \\dots r), c) + calc(l, mid, c + 1)$, where $count(s, c)$ is the number of occurrences of the character $c$ in $s$. We can see that $cnt_l$ describes the second condition from the statement and $cnt_r$ describes the third one. So, $calc(l, r, c)$ returns $min(cnt_l, cnt_r)$ except one case. When $r - l = 1$, we need to return $1$ if $s_l \\ne c$ and $0$ otherwise. This function works in $O(n \\log n)$ (each element of $s$ belongs to exactly $\\log{n}$ segments, like segment tree). You can get the answer if you run $calc(0, n,~ 'a')$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint calc(const string &s, char c) {\n\tif (s.size() == 1) {\n\t\treturn s[0] != c;\n\t}\n\tint mid = s.size() / 2;\n\tint cntl = calc(string(s.begin(), s.begin() + mid), c + 1);\n\tcntl += s.size() / 2 - count(s.begin() + mid, s.end(), c);\n\tint cntr = calc(string(s.begin() + mid, s.end()), c + 1);\n\tcntr += s.size() / 2 - count(s.begin(), s.begin() + mid, c);\n\treturn min(cntl, cntr);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tstring s;\n\t\tcin >> n >> s;\n\t\tcout << calc(s, 'a') << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "divide and conquer",
      "dp",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1385",
    "index": "E",
    "title": "Directing Edges",
    "statement": "You are given a graph consisting of $n$ vertices and $m$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.\n\nYou have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct \\textbf{all} undirected edges.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, if the graph consisting of initial vertices and only directed edges contains at least one cycle then the answer is \"NO\". Otherwise, the answer is always \"YES\". Let's build it. Let's build the topological sort of the graph without undirected edges. Then let's check for each directed edge if it's going from left to right (in order of topological sort). If it isn't true then there is a cycle and the answer is \"NO\". Otherwise, let's direct each edge from left to right in order of the topological sort.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> ord;\nvector<int> used;\nvector<vector<int>> g;\n\nvoid dfs(int v) {\n\tused[v] = 1;\n\tfor (auto to : g[v]) {\n\t\tif (!used[to]) dfs(to);\n\t}\n\tord.push_back(v);\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tg = vector<vector<int>>(n);\n\t\tvector<pair<int, int>> edges;\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tint t, x, y;\n\t\t\tcin >> t >> x >> y;\n\t\t\t--x, --y;\n\t\t\tif (t == 1) {\n\t\t\t\tg[x].push_back(y);\n\t\t\t}\n\t\t\tedges.push_back({x, y});\n\t\t}\n\t\t\n\t\tord.clear();\n\t\tused = vector<int>(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (!used[i]) dfs(i);\n\t\t}\n\t\tvector<int> pos(n);\n\t\treverse(ord.begin(), ord.end());\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tpos[ord[i]] = i;\n\t\t}\n\t\tbool bad = false;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfor (auto j : g[i]) {\n\t\t\t\tif (pos[i] > pos[j]) bad = true;\n\t\t\t}\n\t\t}\n\t\tif (bad) {\n\t\t\tcout << \"NO\" << endl;\n\t\t} else {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tfor (auto [x, y] : edges) {\n\t\t\t\tif (pos[x] < pos[y]) {\n\t\t\t\t\tcout << x + 1 << \" \" << y + 1 << endl;\n\t\t\t\t} else {\n\t\t\t\t\tcout << y + 1 << \" \" << x + 1 << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1385",
    "index": "F",
    "title": "Removing Leaves",
    "statement": "You are given a tree (connected graph without cycles) consisting of $n$ vertices. The tree is unrooted — it is just a connected undirected graph without cycles.\n\nIn one move, you can choose exactly $k$ leaves (leaf is such a vertex that is connected to only one another vertex) connected \\textbf{to the same vertex} and remove them with edges incident to them. I.e. you choose such leaves $u_1, u_2, \\dots, u_k$ that there are edges $(u_1, v)$, $(u_2, v)$, $\\dots$, $(u_k, v)$ and remove these leaves and these edges.\n\nYour task is to find the \\textbf{maximum} number of moves you can perform if you remove leaves optimally.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "This is mostly implementation problem. We can notice that all leaves are indistinguishable for us. So if we have some vertex with at least $k$ leaves attached to it, we can choose it, remove these leaves from the tree and continue the algorithm. The rest is just an implementation: let's maintain for each vertex $v$ the list of all leaves which are connected to it $leaves_v$ and the set of vertices which is sorted by the size of $leaves_v$. So let's take any vertex which Is connected with at least $k$ leaves (we can just take the vertex with the maximum value in the set) and remove any $k$ leaves attached to it. If it has zero leaves after the current move, let's mark is as a leaf and append it to the list of the corresponding vertex (you also need to remove edges from the graph fast to find the required vertex, so you may need to maintain the graph as the list of sets). And don't forget about the case $k=1$ because it may be special for your solution so you could handle it in a special way. Time complexity: $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, k, ans;\nvector<set<int>> g;\nvector<set<int>> leaves;\n\nstruct comp {\n\tbool operator() (int a, int b) const {\n\t\tif (leaves[a].size() == leaves[b].size()) return a < b;\n\t\treturn leaves[a].size() > leaves[b].size();\n\t}\n};\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tcin >> n >> k;\n\t\tg = leaves = vector<set<int>>(n);\n\t\tfor (int i = 0; i < n - 1; ++i) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y;\n\t\t\t--x, --y;\n\t\t\tg[x].insert(y);\n\t\t\tg[y].insert(x);\n\t\t}\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (g[i].size() == 1) {\n\t\t\t\tleaves[*g[i].begin()].insert(i);\n\t\t\t}\n\t\t}\n\t\tset<int, comp> st;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tst.insert(i);\n\t\t}\n\t\tint ans = 0;\n\t\twhile (true) {\n\t\t\tint v = *st.begin();\n\t\t\tif (int(leaves[v].size()) < k) break;\n\t\t\tfor (int i = 0; i < k; ++i) {\n\t\t\t\tint leaf = *leaves[v].begin();\n\t\t\t\tg[leaf].erase(v);\n\t\t\t\tg[v].erase(leaf);\n\t\t\t\tst.erase(v);\n\t\t\t\tst.erase(leaf);\n\t\t\t\tleaves[v].erase(leaf);\n\t\t\t\tif (leaves[leaf].count(v)) leaves[leaf].erase(v);\n\t\t\t\tif (g[v].size() == 1) {\n\t\t\t\t\tint to = *g[v].begin();\n\t\t\t\t\tst.erase(to);\n\t\t\t\t\tleaves[to].insert(v);\n\t\t\t\t\tst.insert(to);\n\t\t\t\t}\n\t\t\t\tst.insert(v);\n\t\t\t\tst.insert(leaf);\n\t\t\t\t\n\t\t\t}\n\t\t\tans += 1;\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1385",
    "index": "G",
    "title": "Columns Swaps",
    "statement": "You are given a table $a$ of size $2 \\times n$ (i.e. two rows and $n$ columns) consisting of integers from $1$ to $n$.\n\nIn one move, you can choose some \\textbf{column} $j$ ($1 \\le j \\le n$) and swap values $a_{1, j}$ and $a_{2, j}$ in it. Each column can be chosen \\textbf{no more than once}.\n\nYour task is to find the \\textbf{minimum} number of moves required to obtain permutations of size $n$ in both first and second rows of the table or determine if it is impossible to do that.\n\nYou have to answer $t$ independent test cases.\n\nRecall that the permutation of size $n$ is such an array of size $n$ that contains each integer from $1$ to $n$ exactly once (the order of elements doesn't matter).",
    "tutorial": "Firstly, we can determine that the answer is -1 if some number has not two occurrences. Otherwise, the answer exists (and we actually don't need to prove it because we can check it later). Let's find for each number $i$ from $1$ to $n$ indices of columns in which it appears $c_1[i]$ and $c_2[i]$. Consider some number $i$. If $c_1[i] = c_2[i]$ then let's just skip it, we can't change anything by swapping values in this column. Otherwise, let $r_1[i]$ be the number of row of the number $i$ in the column $c_1[i]$ and $r_2[i]$ is the number of row of the number $i$ in the column $c_2[i]$. If $r_1[i] = r_2[i]$ then it's obvious that at exactly one of these two columns should be swapped. The same, if $r_1[i] \\ne r_2[i]$ then it's obvious that we either swap both of them or don't swap both of them. Let's build a graph consisting of $n$ vertices, when the vertex $v$ determines the state of the $v$-th column. If $r_1[i] = r_2[i]$ then let's add edge of color $1$ between vertices $c_1[i]$ and $c_2[i]$. Otherwise, let's add the edge of color $0$ between these vertices. So, we have the graph consisting of several connected components and some strange edges. Let's color it. If the edge $(v, to)$ has the color $1$ then the color of the vertex $to$ should be different from the color of the vertex $v$. The same, if the edge $(v, to)$ has the color $0$ then the color of the vertex $to$ should be the same as the color of the vertex $v$. This makes sense, because edges with color $1$ mean that exactly one of the columns connected by this edge should be swapped (and vice versa). So, after we colored the graph, we can ensure that conditions for each edge are satisfied. If it isn't so, the answer is -1 (but this case can't actually appear). Otherwise, we need to decide for each component independently, what is the color $0$ and the color $1$ means for it. The color $0$ can mean that the column having this color isn't swapped (and the color $1$ means that the column having this color is swapped in this case) and vice versa. We can choose greedily the minimum number of swaps for each component and print the answer. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint cnt0, cnt1;\nvector<int> col, comp;\nvector<vector<pair<int, int>>> g;\n\nvoid dfs(int v, int c, int cmp) {\n\tcol[v] = c;\n\tif (col[v] == 0) ++cnt0;\n\telse ++cnt1;\n\tcomp[v] = cmp;\n\tfor (auto [to, change] : g[v]) {\n\t\tif (col[to] == -1) {\n\t\t\tdfs(to, c ^ change, cmp);\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<vector<int>> a(2, vector<int>(n));\n\t\tvector<vector<int>> pos(n);\n\t\tfor (int i = 0; i < 2; ++i) {\n\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\tcin >> a[i][j];\n\t\t\t\t--a[i][j];\n\t\t\t\tpos[a[i][j]].push_back(j);\n\t\t\t}\n\t\t}\n\t\tbool bad = false;\n\t\tg = vector<vector<pair<int, int>>>(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (pos[i].size() != 2) {\n\t\t\t\tbad = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint c1 = pos[i][0], c2 = pos[i][1];\n\t\t\tif (c1 == c2) continue;\n\t\t\tint r1 = a[0][c1] != i, r2 = a[0][c2] != i;\n\t\t\tg[c1].push_back({c2, r1 == r2});\n\t\t\tg[c2].push_back({c1, r1 == r2});\n\t\t}\n\t\tcol = comp = vector<int>(n, -1);\n\t\tint cnt = 0;\n\t\tvector<pair<int, int>> colcnt;\n\t\tint ans = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (col[i] == -1) {\n\t\t\t\tcnt0 = cnt1 = 0;\n\t\t\t\tdfs(i, 0, cnt);\n\t\t\t\t++cnt;\n\t\t\t\tcolcnt.push_back({cnt0, cnt1});\n\t\t\t\tans += min(cnt0, cnt1);\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfor (auto [j, diff] : g[i]) {\n\t\t\t\tif ((col[i] ^ col[j]) != diff) {\n\t\t\t\t\tbad = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (bad) {\n\t\t\tcout << -1 << endl;\n\t\t} else {\n\t\t\tcout << ans << endl;\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tint changeZero = colcnt[comp[i]].first < colcnt[comp[i]].second;\n\t\t\t\tif (col[i] ^ changeZero) {\n\t\t\t\t\tcout << i + 1 << \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "2-sat",
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1386",
    "index": "A",
    "title": "Colors",
    "statement": "Linda likes to change her hair color from time to time, and would be pleased if her boyfriend Archie would notice the difference between the previous and the new color. Archie always comments on Linda's hair color if and only if he notices a difference — so Linda always knows whether Archie has spotted the difference or not.\n\nThere is a new hair dye series in the market where all available colors are numbered by integers from $1$ to $N$ such that a smaller difference of the numerical values also means less visual difference.\n\nLinda assumes that for these series there should be some critical color difference $C$ ($1 \\le C \\le N$) for which Archie will notice color difference between the current color $\\mathrm{color}_{\\mathrm{new}}$ and the previous color $\\mathrm{color}_{\\mathrm{prev}}$ if $\\left|\\mathrm{color}_{\\mathrm{new}} - \\mathrm{color}_{\\mathrm{prev}}\\right| \\ge C$ and will not if $\\left|\\mathrm{color}_{\\mathrm{new}} - \\mathrm{color}_{\\mathrm{prev}}\\right| < C$.\n\nNow she has bought $N$ sets of hair dye from the new series — one for each of the colors from $1$ to $N$, and is ready to set up an experiment. Linda will change her hair color on a regular basis and will observe Archie's reaction — whether he will notice the color change or not. Since for the proper dye each set should be used completely, each hair color can be obtained no more than once.\n\nBefore the experiment, Linda was using a dye from a different series which is not compatible with the new one, so for the clearness of the experiment Archie's reaction to the first used color is meaningless.\n\nHer aim is to find the precise value of $C$ in a limited number of dyes. Write a program which finds the value of $C$ by experimenting with the given $N$ colors and observing Archie's reactions to color changes.",
    "tutorial": "Subtask 1 ($N \\leq 64$) We will use the colors in this order: $1$, $N$, $2$, $N-1$, $3$, $N-2$, $\\ldots$; this way we will check each difference $N-1$, $N-2$, $N-3$, $N-4$, $\\ldots$ and the answer is the first difference that is not recognized by Archie. Complexity: $N$ queries. Subtask 2 ($N \\leq 125$) We can first ask the colors $N/2$ and $1$. If Archie recognizes the difference, then $C \\leq N/2$, and as in the Subtask 1, we can ask the queries $N/2-1$, $2$, $N/2-2$, $3$, $N/2-3$, $4$, $\\ldots$, until we find the first difference that Archie does not recognize. Otherwise we ask the queries $N$, $2$, $N-1$, $3$, $N-2$, $\\ldots$ until we find the first difference that Archie recognizes. Complexity: $N/2+1$ queries. Subtask 3 ($N \\leq 1000$) First use $\\sqrt N$ values and try to understand $k$ value for which it is true that $C$ is between $k \\sqrt N$ and $(k+1) \\sqrt N$. For example, if $N = 100$, then use values $5$, $15$, $25$, $\\ldots$, $95$ and use the Subtask 1 $N$-query algorithm to find the value of $k$. And then again use the Subtask 1 $N$-query algorithm to calculate the precise $C$ value. Complexity: $2 \\sqrt N$ queries. Subtask 4 ($N \\leq 10^9$) Let assume that we have a correct strategy for all values of $N$ that do not exceed $k$. If $k$ is even ($k = 2 j$) we will use the strategy that was used for $j$ numbers and use only even (or odd) numbers. This way each jump in $j$ becomes twice as long and in the result (when the strategy for $j$ has finished) we will know that the answer is $1$ or $2$, $3$ or $4$, $5$ or $6$, and so on. We then know for some $x$ that Archie recognizes the difference $2 x$ and we need to understand whether he recognizes the difference $2 x - 1$. It can be proved that if possible answers are $2x-1$ and $2x$, then the last difference that was checked was either $2x$ or $2x-2$ and in both cases we will be able to make a jump in the opposite direction with length $2x-1$. If $k$ is odd ($k = 2 j + 1$) we use the strategy for $j$ colors and use the numbers $2$, $4$, $6$, $8$, $10$, and so on. When the strategy for $j$ is finished, we know that the answer is $1$ or $2$, $3$ or $4$, $5$ or $6$, $\\ldots$, $2j-1$ or $2j$ or $2j+1$. And then in almost all cases we can calculate the answer with one additional query, but if the possible answer is one of $2j-1$, $2j$ or $2j+1$ then we need to use two additional queries. Complexity: $2 \\log_2 N$ queries. For example, for the base cases $N = 3$ and $N = 4$ we can use the following algorithms: Then using our construction, we get the following algorithm for $N = 8$: Subtask 5 ($N \\leq 10^{18}$) Let's assume that we have a correct strategy for all values of $N$ that do not exceed $k$. We will restrict our strategy even more - consecutive jumps need to be made in the opposite directions. Suppose that $k$ is even ($k = 2 j$) and the first color used in the $j$ strategy is $f$. Then we make the first jump from $f$ to $f+j$ (or from $f+j$ to $f$). With this jump we will understand whether $C$ is bigger than $j$ (if the answer is negative) or smaller or equal than $j$ (if the answer is positive). If the answer is smaller or equal to $j$ then we use strategy for $j$ on numbers from $1$ to $j$ (we already have the color $f$). If the answer is bigger than $j$, then we extend all jumps in the $j$ strategy by $j$ (if we had a jump with length $p$, then now we will make jump with length $p + j$). As we are always jumping back and forth then we will never jump out of range from $1$ to $n$ and will return the answer in the range $j+1$ to $2j$. If $k$ is odd, we can use a similar strategy. Complexity: $\\log_2 N+1$ queries. In this case, we get the following algorithm for $N = 8$:",
    "tags": [
      "*special",
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1386",
    "index": "B",
    "title": "Mixture",
    "statement": "Serge, the chef of the famous restaurant \"Salt, Pepper & Garlic\" is trying to obtain his first Michelin star. He has been informed that a secret expert plans to visit his restaurant this evening.\n\nEven though the expert's name hasn't been disclosed, Serge is certain he knows which dish from the menu will be ordered as well as what the taste preferences of the expert are. Namely, the expert requires an extremely precise proportion of salt, pepper and garlic powder in his dish.\n\nSerge keeps a set of bottles with mixtures of salt, pepper and garlic powder on a special shelf in the kitchen. For each bottle, he knows the exact amount of each of the ingredients in kilograms. Serge can combine any number of bottled mixtures (or just use one of them directly) to get a mixture of particular proportions needed for a certain dish.\n\nLuckily, the absolute amount of a mixture that needs to be added to a dish is so small that you can assume that the amounts in the bottles will always be sufficient. However, the numeric values describing the proportions may be quite large.\n\nSerge would like to know whether it is possible to obtain the expert's favourite mixture from the available bottles, and if so—what is the smallest possible number of bottles needed to achieve that.\n\nFurthermore, the set of bottles on the shelf may change over time as Serge receives new ones or lends his to other chefs. So he would like to answer this question after each such change.\n\nFor example, assume that expert's favorite mixture is $1:1:1$ and there are three bottles of mixtures on the shelf:\n\n\\begin{center}\n$$ \\begin{array}{cccc} \\hline \\text{Mixture} & \\text{Salt} & \\text{Pepper} & \\text{Garlic powder} \\\\ \\hline 1 & 10 & 20 & 30 \\\\ 2 & 300 & 200 & 100 \\\\ 3 & 12 & 15 & 27 \\\\ \\hline \\end{array} $$ Amount of ingredient in the bottle, kg\n\\end{center}\n\nTo obtain the desired mixture it is enough to use an equivalent amount of mixtures from bottles 1 and 2. If bottle 2 is removed, then it is no longer possible to obtain it.\n\nWrite a program that helps Serge to solve this task!",
    "tutorial": "The crux of solving this problem is to think about it from a geometric perspective and discover a couple of properties, afterwards it's a matter of implementing efficient ways / data structures to process the queries accordingly. There are a couple of possible approaches, but it seems easiest to translate it to a 2D geometry problem. We first translate all mixtures - the target mixture and the bottles - to 2D points in the following way: given a mixture with proportions $(S, P, G)$ we transform it to a point $(x, y) = (S/(S+P+G), P/(S+P+G))$. Intuitively $x$ and $y$ are the relative amounts of salt and pepper, respectively, in the mixture. Now scaling the proportion values (i.e., multiplying $S$, $P$, $G$ with the same coefficient, which describes an identical mixture) keeps $(x, y)$ constant. Mixing two or more bottles ends up combining these 2D points (or vectors) with positive weights the sum of which is 1. Having that, we consider these lemmas (proofs are left as an exercise): Lemma 1. If a bottle point matches the target point, the target mixture can be obtained using only that one bottle. Lemma 2. If the line segment defined by two different bottle points contains the target point, the target mixture can be obtained using those two bottles. Lemma 3. If the triangle defined by three different bottle points contains the target point, the target mixture can be obtained using those three bottles. Lemma 4. If the target point is not contained by any triangle defined by three different bottles, the target mixture cannot be obtained. Based on these properties we can define the following general algorithm: Maintain the set of points. At each step, check the state to find the answer: 2a. If there is a point matching the target point $\\Rightarrow$ 1. 2b. Otherwise, if there is a pair of points whose line segment contains the target point $\\Rightarrow$ 2. 2c. Otherwise, if there is a triplet of points whose triangle contains the target point $\\Rightarrow$ 3. 2d. Otherwise $\\Rightarrow$ 0. 2a. If there is a point matching the target point $\\Rightarrow$ 1. 2b. Otherwise, if there is a pair of points whose line segment contains the target point $\\Rightarrow$ 2. 2c. Otherwise, if there is a triplet of points whose triangle contains the target point $\\Rightarrow$ 3. 2d. Otherwise $\\Rightarrow$ 0. Subtask 1 ($N \\leq 50$) At each step we can simply check each point / pair of points / triplet of points to see if we have case (2a), (2b), or (2c). This takes $O(N)$ / $O(N^2)$ / $O(N^3)$ time for each query, so the total time complexity to process all queries is $O(N^4)$. Complexity: $O(N^4)$ Subtask 2 ($N \\leq 500$) Full search on all points / pairs of points is still feasible here. We need to speed-up the case (2c): checking the triangles. Here the key observation is that instead of considering all triangles individually we can check whether the target point is inside the convex hull defined all bottle points; namely, if the target point is inside the convex hull there exists at least one triplet of bottle points the triangle of which contains the target point, and if it is outside the hull no such triplet exists. It's possible to build the convex hull and check if the target point is inside it in time $O(N \\log N)$, but for this subtask a sub-optimal approach up to $O(N^2)$ is also good enough. Complexity: $O(N^3)$ Subtask 3 ($N \\leq 5000$) Full search on all single points still feasible. To check triplets we do the same convex hull approach as in the previous subtask, but we have to use the optimal $O(N \\log N)$ method this time. For pairs of points we need something better. If we fix a point as one end of the line segment, to have the target point on the segment we know that the other point has to be exactly opposite from the first point relative to the target point (direction-wise, the distance doesn't matter). In other words, after fixing the first point we know exactly at what angle the second point should be (with respect to the target point). So if we have a data structure that we can store points in and test for existence by angle (e.g., using tangent value), we can load all current points in it and then go through each bottle point and quickly check whether an opposite point currently exists. If there is never an opposite point, it means we don't have any line segment containing the target point, and vice versa. It can be done in $O(N \\log N)$ for each query. Complexity: $O(N^2 \\log N)$ Subtask 4 ($N \\leq 10^5$) For the previous subtasks we were answering each query completely independently. For the full solution we aim for a $O(\\log N)$ time for each query so we need to find a way to maintain the state of points through time so that we can update the state (add / remove bottles) and check the current answer quickly for each query. Let's look at all cases (single point, pair, triplet) separately: a. For single point checks we can keep the points in a structure that let's us add/remove/find in $O(\\log N)$ time. We can also just maintain a counter for matching bottles that we increase/decrease whenever we add/remove a point that matches the target point - then at any step the answer is 1 if the counter is greater than zero. b. For solving the line segment case we go back to the previous idea. If we have all bottle points stored in an appropriate data structure, we need $O(N \\log N)$ time per query to check whether there exist opposite points ($N$ points, $O(\\log N)$ check if an opposite point exists), which is too slow. However, we can maintain a counter for the total number of pairs of points that are opposite to each other (with respect to the target point) within the set of all current points, and update it after each query. Then, similarly to the single point case, the answer is 2 if this counter is greater than zero. To achieve this we need to maintain a data structure that stores all angles of points (e.g., tangent value) and checks for (and allows to update) the number of elements with a certain value currently stored. This can be done in $O(\\log N)$ time for each operation. c. For the triplet case we can use the same convex hull idea, but we need a dynamic version that we can update query-to-query (add/remove points) and test whether the target point is inside it. This can be done with an amortized time of $O(\\log N)$ per query. However, we don't really need to construct the exact convex hull itself, we just need a way to tell whether the (single fixed) target point is inside of it. If we order all points around the target point by angle, then it's enough to check whether all angles between consecutive points are less than 180 degrees. If that's not the case (i.e., some two consecutive points are more than 180 degrees apart) then the target point is outside the hull (and the answer is 0), otherwise inside (answer 3). We need to maintain the points ordered in such a way by adding/removing points for each query, and be able to check for angles bigger than 180 degrees. There are various ways how to do this technically, and it can be done in $O(\\log N)$ time per query. Complexity: $O(N \\log N)$. Final notes In the end for the final solution all cases can be handled using the same data structure that stores the points/angles, so the solution becomes relatively concise. This problem requires divisions. You can simply use floating point numbers, but there is a risk of making the wrong discrete decisions due to floating point imprecision. The correct way here is to work with rational number, i.e., store and operate with values as numerators and denominators ($p/q$). However, you still have to be careful to not cause overflows. Note that subtasks have varying constraints on the proportion values, which allows more freedom in operations without causing overflows. The full problem has a constraint of $10^6$, and it is possible to implement a solution that only multiplies these values once so we use 2nd order values. (3rd order is also tolerated, but more typical careless approaches that yield 4th or 8th degree values are penalized in later subtasks).",
    "tags": [
      "*special",
      "data structures",
      "geometry",
      "math",
      "sortings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1386",
    "index": "C",
    "title": "Joker",
    "statement": "Joker returns to Gotham City to execute another evil plan. In Gotham City, there are $N$ street junctions (numbered from $1$ to $N$) and $M$ streets (numbered from $1$ to $M$). Each street connects two distinct junctions, and two junctions are connected by at most one street.\n\nFor his evil plan, Joker needs to use an odd number of streets that together form a cycle. That is, for a junction $S$ and an \\textbf{even} positive integer $k$, there is a sequence of junctions $S, s_1, \\ldots, s_k, S$ such that there are streets connecting (a) $S$ and $s_1$, (b) $s_k$ and $S$, and (c) $s_{i-1}$ and $s_i$ for each $i = 2, \\ldots, k$.\n\nHowever, the police are controlling the streets of Gotham City. On each day $i$, they monitor a different subset of all streets with consecutive numbers $j$: $l_i \\leq j \\leq r_i$. These monitored streets cannot be a part of Joker's plan, of course. Unfortunately for the police, Joker has spies within the Gotham City Police Department; they tell him which streets are monitored on which day. Now Joker wants to find out, for some given number of days, whether he can execute his evil plan. On such a day there must be a cycle of streets, consisting of an odd number of streets which are not monitored on that day.",
    "tutorial": "In this task, you are given a graph with $N$ nodes and $M$ edges. Furthermore, you are required to answer $Q$ queries. In every query, all the edges from the interval $[l_i,r_i]$ are temporarily removed and you should check whether the graph contains an odd cycle or not. Thanks for the solutions to the Germany (Subtasks 1-5) and Poland (Subtask 6) BOI teams. Subtask 1 ($N, M, Q \\leq 200$) For every query do a DFS from every node and check if an odd cycle is formed. Complexity: $O(QNM)$. Subtask 2 ($N, M, Q \\leq 2000$) The graph is bipartite if and only if it contains no odd cycle. Therefore we can color the nodes with two colors (with DFS or BFS) and check if two adjacent nodes share the same color or not. Complexity: $O(QM)$. Subtask 3 ($l_i=1$ for all queries) We can sort the queries by their right endpoints ($r_i$) and answer them offline. Therefore we insert all the edges in the decreasing order of their indices into a DSU structure. Complexity: $O(Q \\log Q +M \\alpha(N))$. Subtask 4 ($l_i \\leq 200$ for all queries) We can sort the queries by their left endpoint ($l_i$) and apply our solution from Subtask 3 to all queries with the same $l_i$. Complexity: $O(Q \\log Q + 200 M \\alpha(N))$. Subtask 5 ($Q \\leq 2000$) We use the \"Mo's algorithm\" technique. Split the range $[1, M]$ of edge indices into blocks of size $B$ and sort the queries by $l_i/B$ or by $r_i$ if their left endpoint is in the same block. We can now keep two pointers to hold the current range of removed edges. If we answer all queries in the current block, the right pointer moves at most $M$ steps. The left pointer moves at most $QB$ steps in total. Since the left pointer may move to the left and the right inside the current block we need to modify our DSU to allow rollbacks. If we choose $B = M / \\sqrt Q$ we get the following runtime: Complexity: $O(Q \\log Q + M \\sqrt Q \\log N)$. Subtask 6 (no further constraints) For any $1 \\leq l \\leq M$, let $\\mathrm{last}[l]$ be the last index $r$ such that the answer for the query $[l, r]$ is positive (or $M+1$ if no such index exists). That is, the graph exluding the edges $[l,r]$ is bipartite, but the graph excluding the edges $[l,r-1]$ is not. We can prove that if $l_1 < l_2$, then $\\mathrm{last}[l_1] \\leq \\mathrm{last}[l_2]$. We will exploit this fact in order to compute the array $\\mathrm{last}$ using a divide & conquer algorithm. We write a recursive function $\\mathrm{rec}$, which takes two intervals: $[l_1, l_2], [r_1, r_2]$ ($1 \\leq l_1 \\leq l_2 \\leq M$, $1 \\leq r_1 \\leq r_2 \\leq M+1$), possibly intersecting, but $l_1 \\leq r_1$ and $l_2 \\leq r_2$. This function will compute $\\mathrm{last}[l]$ for each $l \\in [l_1, l_2]$, assuming that for these values of $l$, we have $\\mathrm{last}[l] \\in [r_1, r_2]$. We will initially call $\\mathrm{rec}([1, M], [1, M+1])$. We assume that when $\\mathrm{rec}([l_1, l_2], [r_1, r_2])$ is called, then our DSU contains all edges with indices to the left of $l_1$ and to the right of $r_2$. For instance, when $M=9$ and $\\mathrm{rec}([2, 5], [3, 7])$ is called, then edges with indices $1$, $8$, and $9$ should be in the DSU. We also assume that the graph in the DSU is bipartite. We take $l_{\\mathrm{mid}} := (l_1 + l_2) / 2$ and compute $\\mathrm{last}[l_{\\mathrm{mid}}]$; this can be done by adding all edges $[l_1, l_{\\mathrm{mid}}-1]$ to the DSU, and then trying to add all edges with indices $r_2, r_2-1, r_2-2, \\ldots$, until we try to add an edge breaking the bipartiteness. The index $r_{\\mathrm{mid}}$ of such an edge is exactly $\\mathrm{last}[l_{\\mathrm{mid}}]$. We then rollback all edges added so far in our recursive call. Now that we know that $\\mathrm{last}[l_{\\mathrm{mid}}] = r_{\\mathrm{mid}}$, we will run two recursive calls: For each $l \\in [l_1, l_{\\mathrm{mid}}-1]$, we know that $\\mathrm{last}[l] \\in [r_1, r_{\\mathrm{mid}}]$. We run $\\mathrm{rec}([l_1, l_{\\mathrm{mid}}-1], [r_1, r_{\\mathrm{mid}}])$, remembering to add all necessary edges to the right of $r_{\\mathrm{mid}}$. After the recursive call, we rollback them. For each $l \\in [l_{\\mathrm{mid}}+1, l_2]$, we know that $\\mathrm{last}[l] \\in [r_{\\mathrm{mid}}, r_2]$. We run $\\mathrm{rec}([l_{\\mathrm{mid}}+1, l_2], [\\max(l_{\\mathrm{mid}}+1, r_{\\mathrm{mid}}), r_2])$, now adding all necessary edges to the left of $l_{\\mathrm{mid}}+1$. We rollback them after the recursive call. We can see that each recursive call uses at most $O((l_2-l_1) + (r_2-r_1))$ edge additions and rollbacks in DSU, each taking $O(\\log N)$ time pessimistically. Also, on each level of recursion, the total length of all intervals is bounded by $2M$. Hence, all intervals in all recursive calls have total length bounded by $O(M \\log M)$. Hence, the total time of the preprocessing is $O(M \\log M \\log N)$. With our preprocessing, each query $[l, r]$ reduces to simply verifying $r \\leq \\mathrm{last}[l]$, which can be done in constant time. Complexity: $O(M \\log M \\log N + Q)$.",
    "tags": [
      "*special",
      "bitmasks",
      "data structures",
      "divide and conquer",
      "dsu"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1387",
    "index": "A",
    "title": "Graph",
    "statement": "You are given an undirected graph where each edge has one of two colors: black or red.\n\nYour task is to assign a real number to each node so that:\n\n- for each black edge the sum of values at its endpoints is $1$;\n- for each red edge the sum of values at its endpoints is $2$;\n- the sum of the absolute values of all assigned numbers is the smallest possible.\n\nOtherwise, if it is not possible, report that there is no feasible assignment of the numbers.",
    "tutorial": "Subtasks 1-4 These subtasks essentially are for the solutions that have the correct idea (see Subtask 5), but with slower implementation. Subtask 5 According to the last example in the task statement it is clear that the graph may actually be a multigraph, i.e., may contain more than one edge between a pair of vertices, loops, or isolated vertices. Reading the input carefully allows us to get rid of extraordinary situations: Loops define the values of the vertices (0.5 or 1 depending on the color of the edge). For the multi-edges it should be checked that all edges are of the same color. If not, there is no solution. For each isolated vertex a 0 should be assigned. Since there may be several connected components, the task should be solved for each component separately. Minimum sums of absolute values found for separate components will sum up to the minimum sum for the whole graph. Let's investigate a solution for a single connected component. For each vertex we will assign a tuple $(a, b)$ which corresponds to the value in the form $ax + b$ where $a \\in \\{-1,0,1\\}$ and $b$ - any real number. Any vertex may be already processed or not yet processed. Value $a=0$ means that for the particular vertex the exact value is already known ($b$). If $a \\neq 0$, it means that we still do not know the exact value for the particular vertex - it still contains a variable part. We start with an arbitrary vertex $v_0$ and assign $(1,0)$ to it. This means that the vertex is processed while the exact value is still unknown (we can denote it by a variable $x$). Now let's process all other vertices by DFS going from already processed vertices via edges. Let's see what are the possible cases if an already processed vertex $v$ is connected with a vertex $u$. We first calculate $(a_u', b_u')$, the values for $u$ that follow from values for $v$ and the color of the edge that connects them. Namely, $a_u' = -a_v$ and $b_u' = 1 - b_v$ if the edge is black or $b_u' = 2 - b_v$ if the edge is red. Then we check whether $u$ is already processed. If not, we assign $(a_u, b_u) = (a_u', b_u')$ and proceed with DFS. If, however, the vertex is already processed (we have found a cycle), there are several cases: If $a_u = a_u'$ and $b_u = b_u'$, there is no additional information and we proceed with DFS. If $a_u = a_u'$ and $b_u \\neq b_u'$, there is contradiction and we can stop DFS. Otherwise we have $a_u a_v = -1$, in which case it is possible to establish the value of $x$: $x_{\\mathrm{val}}=(b_v-b_u)/(a_u-a_v)$. Now that we know $x_{val}$ we need to recalculate the values for all the already processed vertices by replacing $(a_w, b_w)$ with $(0, a_w x_{\\mathrm{val}} + b_w)$. It can be seen that during the DFS we may need to replace the values for already processed vertices only once, and after that all further processed vertices will have exact values ($a_v=0$). If at the end we have $a_v=0$ for all vertices, this is the only valid solution. Otherwise ($|a_v|=1$) we need to find the value of $x$ giving the overall minimum for the sum of absolute values. Lets take all values of $b_v$ (for $a_v = -1$) and $-b_v$ (for $a_v = 1$) and find the median of them. It can be proved that this is the value of $x$ resulting in the overall minimum (proof left as an exercise). To find the median of $N$ numbers, you can use various algorithms: You can sort the numbers and take the middle one ($O(N \\log N)$). You can use the quickselect algorithm (expected running time $O(N)$, $O(N^2)$ worst-case). You can use the median-of-medians algorithm ($O(N)$ worst-case). Complexity: $O(N + M)$ / $O(N \\log N + M)$.",
    "tags": [
      "*special",
      "binary search",
      "dfs and similar",
      "dp",
      "math",
      "ternary search"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1387",
    "index": "B1",
    "title": "Village (Minimum)",
    "statement": "\\textbf{This problem is split into two tasks. In this task, you are required to find the minimum possible answer. In the task Village (Maximum) you are required to find the maximum possible answer. Each task is worth $50$ points.}\n\nThere are $N$ houses in a certain village. A single villager lives in each of the houses. The houses are connected by roads. Each road connects two houses and is exactly $1$ kilometer long. From each house it is possible to reach any other using one or several consecutive roads. In total there are $N-1$ roads in the village.\n\nOne day all villagers decided to move to different houses — that is, after moving each house should again have a single villager living in it, but no villager should be living in the same house as before. We would like to know the smallest possible total length in kilometers of the shortest paths between the old and the new houses for all villagers.\n\n\\begin{center}\nExample village with seven houses\n\\end{center}\n\nFor example, if there are seven houses connected by roads as shown on the figure, the smallest total length is $8$ km (this can be achieved by moving $1 \\to 6$, $2 \\to 4$, $3 \\to 1$, $4 \\to 2$, $5 \\to 7$, $6 \\to 3$, $7 \\to 5$).\n\nWrite a program that finds the smallest total length of the shortest paths in kilometers and an example assignment of the new houses to the villagers.",
    "tutorial": "Subtask 1 We can try each permutation of villagers, claculate the total distance and find the answer. Complexity: $O(N!)$. Subtask 2 See the Subtask 3 solution; here we can store the tree in slower data structures and work with the tree slower. Complexity: $O(N^2)$. Subtask 3 Each villager needs to move to a new place so we can process the tree from leaves (greedy): if a villager that currently is in a leaf has been there from the very beginning (still needs to move to other place), change places with its (only) neighbour node villager, add $2$ to the answer and mark the leaf node as processed (or remove it from the tree so that new nodes can become leaves). If the last villager is not moved then it can change with any of it neighbors. Complexity: $O(N)$.",
    "tags": [
      "*special",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1387",
    "index": "B2",
    "title": "Village (Maximum)",
    "statement": "\\textbf{This problem is split into two tasks. In this task, you are required to find the maximum possible answer. In the task Village (Minimum) you are required to find the minimum possible answer. Each task is worth $50$ points.}\n\nThere are $N$ houses in a certain village. A single villager lives in each of the houses. The houses are connected by roads. Each road connects two houses and is exactly $1$ kilometer long. From each house it is possible to reach any other using one or several consecutive roads. In total there are $N-1$ roads in the village.\n\nOne day all villagers decided to move to different houses — that is, after moving each house should again have a single villager living in it, but no villager should be living in the same house as before. We would like to know the largest possible total length in kilometers of the shortest paths between the old and the new houses for all villagers.\n\n\\begin{center}\nExample village with seven houses\n\\end{center}\n\nFor example, if there are seven houses connected by roads as shown on the figure, the largest total length is $18$ km (this can be achieved by moving $1 \\to 7$, $2 \\to 3$, $3 \\to 4$, $4 \\to 1$, $5 \\to 2$, $6 \\to 5$, $7 \\to 6$).\n\nWrite a program that finds the largest total length of the shortest paths in kilometers and an example assignment of the new houses to the villagers.",
    "tutorial": "Subtask 1 We can try each permutation of villagers, claculate the total distance and find the answer. Complexity: $O(N!)$. Subtask 2 See the Subtask 3 solution; here we can store the tree in slower data structures and work with the tree slower. Complexity: $O(N^2)$. Subtask 3 In the beginning let's think about each edge independently - how many villagers can go through it in each direction? If the edge is between nodes $a$ and $b$ then the maximal number of such villagers is $\\min(\\mathrm{subtreeSize}(a), \\mathrm{subtreeSize}(b))$. Calculate this value for each edge and add them up - this way we get the theoretically maximal achievable total distance. Now we find a node in the tree with a property that the biggest neighbour subtree is at most $N / 2$. Such vertex is called a tree centroid and can be found in linear time. Now we just need to arrange all nodes from the neighbour subtrees and the centroid node itself so that no nodes stay in the same subtree where they were before. This is possible because no subtree is bigger than the sum of all other subtrees and it guarantees that the maximal possible number of villagers will pass through each of the edges. Complexity: $O(N)$.",
    "tags": [
      "*special",
      "dfs and similar",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1387",
    "index": "C",
    "title": "Viruses",
    "statement": "The Committee for Research on Binary Viruses discovered a method of replication for a large family of viruses whose genetic codes are sequences of zeros and ones. Each virus originates from a single gene; for simplicity genes are denoted by integers from $0$ to $G - 1$. At each moment in time a virus is a sequence of genes. When mutation occurs, one of the genes from the sequence is replaced by a certain sequence of genes, according to the mutation table. The virus stops mutating when it consists only of genes $0$ and $1$.\n\nFor instance, for the following mutation table: $$ 2 \\to \\langle 0\\ 1 \\rangle \\\\ 3 \\to \\langle 2\\ 0\\ 0\\rangle\\\\ 3 \\to \\langle 1\\ 3\\rangle\\\\ 4 \\to \\langle 0\\ 3\\ 1\\ 2\\rangle\\\\ 5 \\to \\langle 2\\ 1\\rangle\\\\ 5 \\to \\langle 5\\rangle $$ a virus that initially consisted of a single gene $4$, could have mutated as follows: $$ \\langle 4 \\rangle \\to \\langle \\underline{0\\ 3\\ 1\\ 2} \\rangle \\to \\langle 0\\ \\underline{2\\ 0\\ 0}\\ 1\\ 2 \\rangle \\to \\langle 0\\ \\underline{0\\ 1}\\ 0\\ 0\\ 1\\ 2 \\rangle \\to \\langle 0\\ 0\\ 1\\ 0\\ 0\\ 1\\ \\underline{0\\ 1} \\rangle $$ or in another way: $$ \\langle 4 \\rangle \\to \\langle \\underline{0\\ 3\\ 1\\ 2} \\rangle \\to \\langle 0\\ \\underline{1\\ 3}\\ 1\\ 2 \\rangle \\to \\langle 0\\ 1\\ 3\\ 1\\ \\underline{0\\ 1} \\rangle \\to \\langle 0\\ 1\\ \\underline{2\\ 0\\ 0}\\ 1\\ 0\\ 1 \\rangle \\to \\langle 0\\ 1\\ \\underline{0\\ 1}\\ 0\\ 0\\ 1\\ 0\\ 1 \\rangle $$\n\nViruses are detected by antibodies that identify the presence of specific continuous fragments of zeros and ones in the viruses' codes. For example, an antibody reacting to a fragment $\\langle 0\\ 0\\ 1\\ 0\\ 0 \\rangle$ will detect a virus $\\langle 0\\ 0\\ 1\\ 0\\ 0\\ 1\\ 0\\ 1 \\rangle$, but it will not detect a virus $\\langle 0\\ 1\\ 0\\ 1\\ 0\\ 0\\ 1\\ 0\\ 1 \\rangle$.\n\nFor each gene from $2$ to $G-1$, the scientists are wondering whether a given set of antibodies is enough to detect all viruses that can emerge through mutations from this gene. If not, they want to know the length of the shortest virus that cannot be detected.\n\nIt may happen that sometimes scientists don't have any antibodies. Then of course no virus can be detected, so the scientists are only interested in the length of the shortest possible virus that can emerge from the gene mutations.",
    "tutorial": "From reading the task you may think that there aren't enough constraints. This is not true as you actually have enough information. $k$. You are given that the sum of all values $k$ does not exceed 100, so naturally, $1 \\leq k \\leq 100$. $l$. You are given that the sum of all values $l$ does not exceed 50, so naturally, $1 \\leq l \\leq 50$. $N$. You are given that the sum of all values $k$ does not exceed 100 and that $k \\geq 1$ in every row of the mutation table. Thus, there are at most 100 rows, meaning $G - 2 \\leq N \\leq 100$. Since $G > 2$, $0 < N \\leq 100$. $G$. You are given that every integer from $2$ to $G - 1$ appears in the table as $a$ at least once. This means that $N \\geq G - 2$ (which you are also conveniently given). Hence, $2 < G \\leq N + 2$, or remembering constraints on $N$, $2 < G \\leq 102$. $M$. You are given that the sum of all values $l$ does not exceed 50 and that $l \\geq 1$ for every antibody. Thus, there are at most 50 antibodies, meaning $0 \\leq M \\leq 50$. Note that this means that a test with $G = 102$ is a valid test, and it may fail some solutions. We were nice though, and only put it in the first subtask, so if you're failing that one, this may be the answer why. In all subtasks, we'll use the same approaches, which will be similar to dynamic programming and Dijkstra's algorithm. Imagine we are computing $dp_i$ - the minimal length of a virus that we can obtain from gene $i$ and is not detected by any antibodies. Then, similar to Dijkstra, we can take the smallest unprocessed value of $dp_i$ and process it, that is, for every transition $a \\to \\langle b_1\\ b_2\\ \\ldots\\ b_k \\rangle$, where for some $j$, $b_j = i$, we can update the value of $dp_a$ using that transition. Since every transition is non-empty, we know that once we picked something as the smallest unprocessed value of $dp_i$, it cannot be updated to a better result anymore, hence it's our answer. Once you have no more unprocessed values (or they're all $\\infty$), you're done. Subtask 1 (No antibodies ($M = 0$)) In this subtask we're not interested in viruses themselves, just in their length as any virus is valid. So, just do what was discussed above. Initially, $dp_0 = dp_1 = 1$. For any other $i$, $dp_i = \\infty$. Then repeatedly pick the smallest unprocessed value of $dp_i$ and process it - for every transition $a \\to \\langle b_1\\ b_2\\ \\ldots\\ b_k \\rangle$, $dp_a = \\min(dp_a, dp_{b_1} + dp_{b_2} + ... + dp_{b_k})$. You don't really need to even do transition selection or a queue for minimal values here, the most basic implementation will yield $O(G \\cdot (G + \\sum{l}))$. Subtask 2 ($N = G - 2$) In this subtask, due to the restriction that every integer from $2$ to $G - 1$ appears in the table as $a$ at least once, every gene has strictly one outgoing mutation. This means that from every gene, there can be either no or a single virus only. However, viruses can still be quite large, so you can't just compute it. It could also be infinite. Luckily, you can use similar approach here, except this time you'd also need to store some information about the virus itself rather than only the length of it. What information do we need about the virus then? Well, our dynamic programming state already has a condition that it's the shortest virus that is not detected by any antibodies. So, our initialization is changed slightly: $dp_0 = \\begin{cases} 0, & \\text{if $0$ is an antibody}\\\\ 1, & \\text{otherwise} \\end{cases}$ $dp_1 = \\begin{cases} 0, & \\text{if $1$ is an antibody}\\\\ 1, & \\text{otherwise} \\end{cases}$ Now, what about transitions? Similarly, $dp_a = \\min(dp_a, dp_{b_1} + dp_{b_2} + ... + dp_{b_k})$. We also know that there can't be an antibody fully inside each individual $dp_{b_j}$. But what about overlaps? Well, since each antibody length is at most $\\ell \\leq 50$, we know we are only interested in storing the first and the last 50 characters for every value of $dp$. Then when we are doing a transition and gluing up multiple states together, we just have to check if due to this an antibody won't appear in the result, which will make this transition invalid. It's possible that the most inefficient way of doing so will time out, but you have plenty of leeway here, so it shouldn't cause too many issues. Subtask 3 (One antibody ($M = 1$)) Here we need to expand our DP a bit. Given that unlike in the previous subtask, there can be multiple different viruses originating from a single gene, it's no longer enough to store the information about the virus, we need to encode it inside a state. So, the general approach will be as follows: We are now calculating $dp_{i, st, en}$, the minimal length of a virus such that we start in the state $st$, obtain a virus from the gene $i$ that is not detected by any antibodies and end up in the state $en$. The transition then becomes where for transition $a \\to \\langle b_1\\ b_2\\ \\ldots\\ b_k \\rangle$; $dp_{a, st, en} = \\min(dp_{a, st, en}, dp_{b_1, st, x_1} + dp_{b_2, x_1, x_2} + \\ldots + dp_{b_k, x_{k - 1}, en})$. But wait! We have to now compute for every value of $k - 1$ variables of $x$, and $k \\leq 100$! Well, we can notice that we can do a second dynamic programming, somewhat reducing the running cost, but this will only be enough for Subtask 4. Instead we can transform the transitions themselves. What we want to do is to make sure that in every transition $a \\to \\langle b_1\\ b_2\\ \\ldots\\ b_k \\rangle$, $k \\leq 2$. We can do that, since $a \\to \\langle b_1\\ b_2\\ \\ldots\\ b_k \\rangle = \\begin{cases} a \\to \\langle b_1\\ z \\rangle, \\text{where $z$ is a new gene}\\\\ z \\to \\langle b_2\\ \\ldots\\ b_k \\rangle \\end{cases}$ reduces the length of a transition. Note that by doing so we would have at most $\\sum{k}$ transitions still and the sum of all values $k$ would still be $O(\\sum{k})$, since it could only double worst-case. We are also creating new genes, but similarly, we'll still have $O(G)$ of them. However, now transition is a lot smoother. For a transition $a \\to \\langle b_1\\rangle$, we have $dp_{a, st, en} = \\min(dp_{a, st, en}, dp_{b_1, st, en})$. For a transition $a \\to \\langle b_1\\ b_2\\rangle$, we have $dp_{a, st, en} = \\min(dp_{a, st, en}, dp_{b_1, st, x} + dp_{b_2, x, en})$. Now, remember that from $dp_{i, st, en}$ we only need to consider transitions that contain $i$ as the right hand side. Now, imagine we fix $st$ and $en$ and iterate freely over $i$. It's clear that we will consider every transition at most twice. This means that to compute all $O(G \\cdot S^2)$ states we need to process $O(G \\cdot S^2)$ transitions. As such, if we assume that the amount of states is $S$, then if we're using fast structure to find minimal states, the complexity would be $O(G \\cdot S^2 \\cdot (S \\cdot \\log(G \\cdot S^2)))$. The last logarithm comes from the necessity to update the queue of the smallest values every time we update a value successfully. So, the final question we need to answer is what is the state here? We can observe that since we have one antibody, it's enough to have a state encoding at what length of prefix for the antibody you are. For an antibody of length $l$, this gives you $l$ states (because you can't visit prefix of length $l$ as that just means that you can detect this virus). So, you are now looking for $dp_{i, st, en}$, the minimal length of a virus such that we start by already having part of the virus ending with a prefix of antibody of length $st$, obtain a virus from gene $i$ that is not detected by any antibodies and end up with a virus ending with a prefix of antibody length $en$. Now, your answer for a gene $i$ is $\\min(dp_{i, 0, x})$ for any $0 \\leq x < l$. The transition doesn't really have any additional work either as the fact that we are not having an antibody in the virus is encoded in the states themselves. The initialization is where all of the work happens now. What we can do is to iterate over terminal genes $i$ (0 and 1) and starting states $st$. Then, let's observe the virus obtained from virus corresponding to the state $st$ (e.g. prefix of antibody of length $st$) and the gene $i$ appended to it. Well, we get a string and need to check what is the maximum its suffix that is also a prefix for the antibody. Doing so naively is enough, but you can also observe that it's exactly what KMP algorithm is looking for. Let's call this new length $en$. Then we've found that for this $i$ and $st$, as long as $en < l$, $dp_{i, st, en} = 1$. Everything that's not initialized after we've iterated over every $i$ and $st$ has a value of $\\infty$ as it's impossible. So, our $S = \\sum{l}$ and as such our total complexity is $O(G \\cdot (\\sum{l})^3 \\cdot \\log(G \\cdot (\\sum{l})^2))$. Subtask 5 (No further constraints) We can use the same solution as Subtask 3, but the state needs to change. Now that we have multiple antibodies, we need to compute a set of prefixes for all antibodies, where some of them would be invalid. Please note that the definition of a bad prefix isn't if it's equal to one antibody or not. The prefix is bad if and only if it has a suffix that is an antibody, since we may have that a prefix of one antibody already ends with a different antibody. Now a similar initialization can occur, where we would iterate over every $i$ and $st$, obtain a string from $st$ and $i$ and find its largest suffix that is in the prefix set to make the transition. Doing so naively is enough, but once again, you can also observe that it's exactly what the Aho-Corasick algorithm is doing. We can also see that we'll still have at most $O(\\sum{l})$ states, and as such the rest of the algorithm and the total complexity is the same as in Subtask 3. Subtask 4 (The sum of all values $l$ does not exceed 10) This was a subtask designed to award points to conceptually right solutions but inefficiently written. Such as, for example, not implementing fast enough structure for picking the minimal values of $dp$ or not transforming the transitions and as such having to write a separate dynamic programming for executing the transitions.",
    "tags": [
      "*special",
      "dp",
      "shortest paths",
      "string suffix structures"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1388",
    "index": "A",
    "title": "Captain Flint and Crew Recruitment",
    "statement": "Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.\n\nRecently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer $x$ as \\textbf{nearly prime} if it can be represented as $p \\cdot q$, where $1 < p < q$ and $p$ and $q$ are prime numbers. For example, integers $6$ and $10$ are nearly primes (since $2 \\cdot 3 = 6$ and $2 \\cdot 5 = 10$), but integers $1$, $3$, $4$, $16$, $17$ or $44$ are not.\n\nCaptain Flint guessed an integer $n$ and asked you: can you represent it as {the sum of $4$ \\textbf{different positive} integers} where \\textbf{at least $3$} of them should be nearly prime.\n\nUncle Bogdan easily solved the task and joined the crew. Can you do the same?",
    "tutorial": "Consider the three smallest nearly prime numbers: $6, 10$ and $14$: if $n \\le 30=6+10+14$, then the answer is NO. otherwise the answer is YES. The easiest way is to display $6, 10, 14, n-30$ in cases where $n-30 \\neq 6, 10, 14$. If $n = 36, 40, 44,$ then we can output $6, 10, 15, n-31$. In addition, it was possible to generate the first nearly prime numbers and iterate over all their possible triplets. Complexity: $O(1)$ or more if brute-force is written.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n\n    int q;\n    cin >> q;\n\n    while(q--){\n        int n; cin >> n;\n        if(n <= 30){\n            cout << \"NO\" << endl;\n        }\n        else{\n            cout << \"YES\" << endl;\n            if(n == 36 || n == 40 || n == 44){\n                cout << 6 << ' ' << 10 << ' ' << 15 << ' ' << n - 31 << endl;\n            }\n            else{\n                cout << 6 << ' ' << 10 << ' ' << 14 << ' ' << n - 30 << endl;\n            }\n        }\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1388",
    "index": "B",
    "title": "Captain Flint and a Long Voyage",
    "statement": "Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.\n\nIn the beginning, uncle Bogdan wrote on a board a positive integer $x$ consisting of $n$ digits. After that, he wiped out $x$ and wrote integer $k$ instead, which was the concatenation of binary representations of digits $x$ consists of (without leading zeroes). For example, let $x = 729$, then $k = 111101001$ (since $7 = 111$, $2 = 10$, $9 = 1001$).\n\nAfter some time, uncle Bogdan understood that he doesn't know what to do with $k$ and asked Denis to help. Denis decided to wipe last $n$ digits of $k$ and named the new number as $r$.\n\nAs a result, Denis proposed to find such integer $x$ of length $n$ that $r$ (as number) is maximum possible. If there are multiple valid $x$ then Denis is interested in the minimum one.\n\nAll crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?\n\nNote: in this task, we compare integers ($x$ or $k$) as numbers (despite what representations they are written in), so $729 < 1999$ or $111 < 1000$.",
    "tutorial": "Statement: $x$ consists of digits $8-9$. This is so, because if $x$ contains digits $0-7$, which in their binary notation are shorter than digits $8-9$, then the number $k$ written on the board, and therefore the number $r$ (obtained by removing the last $n$ digits of the number $k$) will be shorter than if you use only the digits $8$ and $9$, which means it will not be the maximum possible. Statement: $x$ is $99 \\dots 988 \\dots 8$. Obviously, the more $x$, the more $k$ and $r$. Therefore, to maximize $k$, $x$ must be $99 \\dots 999$. However, due to the fact that $r$ is $k$ without the last $n$ digits, at the end of the number $x$ it is possible to replace a certain number of $9$ digits with $8$ so that $r$ will still be the maximum possible. Statement: the number of digits $8$ in the number $x$ of length $n$ is equal to $\\left\\lceil \\frac{n}{4} \\right\\rceil$. $8_{10}=1000_2$ and $9_ {10}=1001_2$. We can see that the binary notations of the digits $8$ and $9$ are $4$ long and differ in the last digit. Suppose the suffix of a number $x$ consists of $p$ digits $8$. Then the maximum $r$ is achieved if at least $4 \\cdot p - 3$ digits are removed from the end of $k$. By the condition of the problem, exactly $n$ digits are removed, which means $4 \\cdot p - 3 \\le n$ and then $p = \\left \\lfloor \\frac {n + 3} {4} \\right \\rfloor = \\left \\lceil \\frac {n} {4} \\right \\rceil$. Complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n\n    int q;\n    cin >> q;\n\n    while (q--) {\n        int n; cin >> n;\n        int x = (n + 3) / 4;\n        for (int i = 0; i < n - x; ++i) {\n            cout << 9;\n        }\n        for (int i = 0; i < x; ++i) {\n            cout << 8;\n        }\n        cout << endl;\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1388",
    "index": "C",
    "title": "Uncle Bogdan and Country Happiness",
    "statement": "Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.\n\nThere are $n$ cities and $n−1$ undirected roads connecting pairs of cities. Citizens of any city can reach any other city traveling by these roads. Cities are numbered from $1$ to $n$ and the city $1$ is a capital. In other words, the country has a tree structure.\n\nThere are $m$ citizens living in the country. A $p_i$ people live in the $i$-th city but all of them are working in the capital. At evening all citizens return to their home cities using the shortest paths.\n\nEvery person has its own mood: somebody leaves his workplace in good mood but somebody are already in bad mood. Moreover any person can ruin his mood on the way to the hometown. \\textbf{If person is in bad mood he won't improve it}.\n\nHappiness detectors are installed in each city to monitor the happiness of \\textbf{each} person who visits the city. The detector in the $i$-th city calculates a happiness index $h_i$ as the number of people in good mood minus the number of people in bad mood. Let's say for the simplicity that mood of a person doesn't change inside the city.\n\nHappiness detector is still in development, so there is a probability of a mistake in judging a person's happiness. One late evening, when all citizens successfully returned home, the government asked uncle Bogdan (the best programmer of the country) to check the correctness of the collected happiness indexes.\n\nUncle Bogdan successfully solved the problem. Can you do the same?\n\nMore formally, You need to check: \"Is it possible that, after all people return home, for each city $i$ the happiness index will be equal exactly to $h_i$\".",
    "tutorial": "For each city $v$ count $a_v$ - how many people will visit it. Knowing this value and the value of the level of happiness - $h_v$, we can calculate how many people visited the city in a good mood: $g_v=\\frac {a_v + h_v} {2}$. We can single out the $3$ criterions for the correctness of the values of the happiness indices: $a_v + h_v$ is a multiple of $2$. For each $v$, $g_v$ - an integer. $0 \\le g_v \\le a_v$. In each city $v$ the number of residents who passed this city in a good mood - a non-negative number not exceeding $a_v$. $g_{to_1} + g_{to_2} + \\ldots + g_{to_k} \\le g_v,$ where $to_1,$ $to_2,$ $\\ldots,$ $to_k$ are the cities where the resident can move out of the city $v$ on the way home. This follows from the fact that the mood of the inhabitants can be deteriorated and cannot be improved. This is enough, since these conditions guarantee the correctness of the happiness indices by definition, as well as the peculiarities of changes in the mood of residents.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1e5 + 7;\n\nvector < int > gr[N];\n\nbool access = true;\n\nint p[N], h[N], a[N], g[N];\n\nvoid dfs(int v, int ancestor = -1) {\n    a[v] = p[v];\n    int sum_g = 0;\n    for (int to : gr[v]) {\n        if (to == ancestor) continue;\n        dfs(to, v);\n        sum_g += g[to];\n        a[v] += a[to];\n    }\n    if ((a[v] + h[v]) % 2 == 0) {} // first\n    else access = false;\n    g[v] = (a[v] + h[v]) / 2;\n    if (g[v] >= 0 && g[v] <= a[v]) {} // second\n    else access = false;\n    if (sum_g <= g[v]) {} // third\n    else access = false;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n\n    int q;\n    cin >> q;\n\n    while (q--) {\n        int n, m; cin >> n >> m;\n        for (int i = 0; i < n; ++i) cin >> p[i];\n        for (int i = 0; i < n; ++i) cin >> h[i];\n        for (int i = 0; i < n - 1; ++i) {\n            int a, b; cin >> a >> b;\n            --a, --b;\n            gr[a].push_back(b);\n            gr[b].push_back(a);\n        }\n        dfs(0);\n        cout << (access ? \"YES\" : \"NO\") << endl;\n        access = true;\n        for (int i = 0; i < n; ++i) gr[i].clear();\n    }\n}",
    "tags": [
      "dfs and similar",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1388",
    "index": "D",
    "title": "Captain Flint and Treasure",
    "statement": "Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...\n\nThere are two arrays $a$ and $b$ of length $n$. Initially, an $ans$ is equal to $0$ and the following operation is defined:\n\n- Choose position $i$ ($1 \\le i \\le n$);\n- Add $a_i$ to $ans$;\n- If $b_i \\neq -1$ then add $a_i$ to $a_{b_i}$.\n\nWhat is the maximum $ans$ you can get by performing the operation on each $i$ ($1 \\le i \\le n$) exactly once?\n\nUncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.",
    "tutorial": "Let's construct a graph $G$ with $n$ vertices and directed edges $(i; b_i)$. Note that it is not profitable to process the vertex $i$ if the vertices $j$, for which $b_j=i$, have not yet been processed, since it is possible to process these vertices $j$ so that they will not decrease $a_i$. We will do the following operation $n$ times: Choose a vertex $V$ which does not contain any edge (there is always such a vertex due to an additional condition in the problem). Let's process it as follows: if $a_V> 0$, then apply the operation from the condition to this vertex. This is beneficial because if $b_v \\neq -1$ then we will improve the value of $a_{b_V}$. if $a_V \\le 0$, then the value of $a_{b_V}$ will not improve, which means that it is profitable to apply the operation to the vertex $V$ after $b_V$ (if $b_V \\neq -1$). Let's store two containers $now$ and $after$. In $now$ we store the order of processing of vertices for which $a_V>0$. In $after$ - for which $a_V \\le 0$. Then let's notice that the order $now + reverse (after)$ is appropriate to achieve the maximum answer. Total $O(n)$ or $O(n \\cdot log(n))$ depending on the implementation.",
    "code": "#include <bits/stdc++.h>\n\n#define Vanya Unstoppable\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n    \n    int n;\n    cin >> n;\n    \n    long long a[n];\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    \n    set < int > s;\n    for (int i = 0; i < n; ++i) {\n        s.insert(i);\n    }\n    \n    int b[n];\n    vector < int > sz(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> b[i]; --b[i];\n        if (b[i] == -2) continue;\n        ++sz[b[i]];\n        if (sz[b[i]] == 1) {\n            s.erase(b[i]);\n        }\n    }\n    \n    long long sum = 0;\n    vector < int > ans[2];\n    \n    while (!s.empty()) {\n        int v = *s.begin();\n        s.erase(s.begin());\n        int w = b[v];\n        sum += a[v];\n        if (a[v] >= 0) {\n            if (w >= 0) {\n                a[w] += a[v];\n            }\n            ans[0].push_back(v);\n        } else {\n            ans[1].push_back(v);\n        }\n        if (w >= 0) {\n            --sz[w];\n            if (sz[w] == 0) {\n                s.insert(w);\n            }\n        }\n    }\n    \n    cout << sum << endl;\n    for (int to : ans[0]) cout << to + 1 << ' ';\n    \n    reverse(ans[1].begin(), ans[1].end());\n    \n    for (int to : ans[1]) cout << to + 1 << ' ';\n    cout << endl;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1388",
    "index": "E",
    "title": "Uncle Bogdan and Projections",
    "statement": "After returning to shore, uncle Bogdan usually visits the computer club \"The Rock\", to solve tasks in a pleasant company. One day, uncle Bogdan met his good old friend who told him one unusual task...\n\nThere are $n$ non-intersecting horizontal segments with ends in integers points on the plane with the standard cartesian coordinate system. All segments are strictly above the $OX$ axis. You can choose an arbitrary vector ($a$, $b$), where $b < 0$ and coordinates are real numbers, and project all segments to $OX$ axis along this vector. The projections shouldn't intersect but may touch each other.\n\nFind the minimum possible difference between $x$ coordinate of the right end of the rightmost projection and $x$ coordinate of the left end of the leftmost projection.",
    "tutorial": "It is easy to understand that there is an optimal vector at which the value we need is minimal and at least one pair of projections is touching. Note also that the vector is completely described by the angle between it and the positive direction of the $OX$ axis. If two line segments are at different heights, then there are two ways to select a vector so that their projections touch. Let's find two angles that describe these vectors. If we project along a vector with an angle that is in the interval that the found two angles form, then the projections will intersect. So, this range of angles is 'forbidden'. Using the scanline method, we can find such angles that they are the boundaries of some 'forbidden' interval and do not fall into any 'forbidden' interval. Then we only need to check these angles. We also need to quickly find the rightmost and leftmost points for each angle. Let's take two points at different heights. Let them project to one point with a vector with an angle $\\alpha$. Then on the interval $(0^\\circ;\\alpha)$ the upper one will be to the right, and on the interval $(\\alpha; 180^\\circ)$ the upper one will be to the left. We will process two types of requests using the scanning line: Check the answer for the current angle; Swap two points. It is necessary to carefully handle the case when, at some angle, several points are swapped. Alternative way: if you project the point $(x; y)$ along the vector with the angle $\\alpha$, you get the point $(x + y * ctg (\\ alpha); 0)$. We'll use the Convex Hull Trick to quickly find the rightmost and leftmost points for each angle. We will store CHT for maximums and minimums with lines $k = y_i, b = x_i$. Queries at $ctg(\\alpha)$ will give us the leftmost and rightmost points. It is a corner case if all points are at the same height. Then the answer is $max(xr_i) - min(xl_i)$. Complexity of solution - $O(n^2log(n))$.",
    "code": "#include <bits/stdc++.h>\n\n#define pb push_back\n#define x first\n#define y second\n\nusing namespace std;\n\nconst int N = 1e5 + 10;\nconst double eps = 1e-9;\n\ndouble xl[N], xr[N], y[N], pi = acos(-1), mn_x, mx_x;\nint ind_l, ind_r;\n\ndouble point_pr(double x, double y, double ctg) {\n    return x - y * ctg;\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n;\n    vector<pair<double, int> > q;\n    vector<pair<double, pair<int, int> > > events, prom_left, prom_right;\n    cin >> n;\n    pair<double, double> mx, mn;\n    mx = {-1.0, -1.0};\n    mn = {2e9, 2e9};\n    mn_x = 2e9;\n    mx_x = -2e9;\n    for(int i = 0; i < n; ++i) {\n        cin >> xl[i] >> xr[i] >> y[i];\n\n        if(xl[i] < mn_x) {\n            mn_x = xl[i];\n        }\n        if(xr[i] > mx_x) {\n            mx_x = xr[i];\n        }\n\n        if(mx.y < y[i]) {\n            mx.y = y[i];\n            mx.x = xl[i];\n            ind_l = i;\n        }\n        else if(mx.y == y[i] && mx.x > xl[i]) {\n            mx.y = y[i];\n            mx.x = xl[i];\n            ind_l = i;\n        }\n\n        if(mn.y > y[i]) {\n            mn.y = y[i];\n            mn.x = xl[i];\n            ind_r = i;\n        }\n        else if(mn.y == y[i] && mn.x < xl[i]) {\n            mn.y = y[i];\n            mn.x = xl[i];\n            ind_r = i;\n        }\n    }\n    double a1, a2;\n    for(int i = 0; i < n; ++i) {\n        for(int j = 0; j < n; ++j) {\n            if(y[i] > y[j]) {\n                a1 = (xr[i] - xl[j]) / (y[i] - y[j]);\n                a2 = (xl[i] - xr[j]) / (y[i] - y[j]);\n                q.pb({a1, 1});\n                q.pb({a2, 2});\n\n                a1 = (xl[i] - xl[j]) / (y[i] - y[j]);\n                a2 = (xr[i] - xr[j]) / (y[i] - y[j]);\n                events.pb({a1, {i, j}});\n                events.pb({a2, {-i - 1, j}});\n            }\n        }\n    }\n\n    if(q.empty()) {\n        cout << fixed << setprecision(9) << mx_x - mn_x << endl;\n        return 0;\n    }\n\n    sort(q.rbegin(), q.rend());\n    int cnt = 0;\n    double last = 0;\n    for(auto i : q) {\n        if(i.y == 2) {\n            --cnt;\n            if(!cnt) {\n                events.pb({i.x, {-1e9, -1e9}});\n            }\n        }\n        else {\n            if(!cnt) {\n                events.pb({i.x, {-1e9, -1e9}});\n            }\n            ++cnt;\n        }\n    }\n    sort(events.rbegin(), events.rend());\n    double ans = 1e18, ang;\n    last = -1e18;\n    for(auto i : events) {\n        if(i.y.x == i.y.y) {\n            unordered_set<int> s;\n            vector<int> to_check;\n            for(auto j : prom_left) {\n                s.insert(j.y.x);\n                if(j.y.x == ind_l) {\n                    to_check.pb(j.y.y);\n                }\n            }\n            prom_left.clear();\n            for(auto j : to_check) {\n                if(!s.count(j)) {\n                    ind_l = j;\n                    break;\n                }\n            }\n            s.clear();\n            to_check.clear();\n\n            for(auto j : prom_right) {\n                s.insert(j.y.y);\n                if(j.y.y == ind_r) {\n                    to_check.pb(-j.y.x - 1);\n                }\n            }\n            prom_right.clear();\n            for(auto j : to_check) {\n                if(!s.count(j)) {\n                    ind_r = j;\n                    break;\n                }\n            }\n            s.clear();\n            to_check.clear();\n\n            double res = point_pr(xr[ind_r], y[ind_r], i.x) - point_pr(xl[ind_l], y[ind_l], i.x);\n            if(ans > res) {\n                ans = res;\n                ang = i.x;\n            }\n        }\n        else if(i.y.x < 0) {\n            if(abs(i.x - last) > eps) {\n                unordered_set<int> s;\n                vector<int> to_check;\n                for(auto j : prom_right) {\n                    s.insert(j.y.y);\n                    if(j.y.y == ind_r) {\n                        to_check.pb(-j.y.x - 1);\n                    }\n                }\n                prom_right.clear();\n                for(auto j : to_check) {\n                    if(!s.count(j)) {\n                        ind_r = j;\n                        break;\n                    }\n                }\n                s.clear();\n                to_check.clear();\n            }\n            prom_right.pb(i);\n        }\n        else {\n            if(abs(i.x - last) > eps) {\n                unordered_set<int> s;\n                vector<int> to_check;\n                for(auto j : prom_left) {\n                    s.insert(j.y.x);\n                    if(j.y.x == ind_l) {\n                        to_check.pb(j.y.y);\n                    }\n                }\n                prom_left.clear();\n                for(auto j : to_check) {\n                    if(!s.count(j)) {\n                        ind_l = j;\n                        break;\n                    }\n                }\n                s.clear();\n                to_check.clear();\n            }\n            prom_left.pb(i);\n        }\n        last = i.x;\n    }\n    cout << fixed << setprecision(9) << ans << endl;\n    return 0;\n}",
    "tags": [
      "data structures",
      "geometry",
      "sortings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1389",
    "index": "A",
    "title": "LCM Problem",
    "statement": "Let $LCM(x, y)$ be the minimum positive integer that is divisible by both $x$ and $y$. For example, $LCM(13, 37) = 481$, $LCM(9, 6) = 18$.\n\nYou are given two integers $l$ and $r$. Find two integers $x$ and $y$ such that $l \\le x < y \\le r$ and $l \\le LCM(x, y) \\le r$.",
    "tutorial": "Suppose we have chosen $x$ and $y$ as the answer, and $x$ is not a divisor of $y$. Since $LCM(x, y)$ belongs to $[l, r]$, we could have chosen $x$ and $LCM(x, y)$ instead. So if the answer exists, there also exists an answer where $x$ is a divisor of $y$. If $2l > r$, then there is no pair $(x, y)$ such that $l \\le x < y \\le r$ and $x|y$. Otherwise, $x = l$ and $y = 2l$ is the answer.",
    "code": "t = int(input())\nfor i in range(t):\n    l, r = map(int, input().split())\n    if l * 2 > r:\n        print(-1, -1)\n    else:\n        print(l, l * 2)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1389",
    "index": "B",
    "title": "Array Walk",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$, consisting of $n$ \\textbf{positive} integers.\n\nInitially you are standing at index $1$ and have a score equal to $a_1$. You can perform two kinds of moves:\n\n- move right — go from your current index $x$ to $x+1$ and add $a_{x+1}$ to your score. This move can only be performed if $x<n$.\n- move left — go from your current index $x$ to $x-1$ and add $a_{x-1}$ to your score. This move can only be performed if $x>1$. \\textbf{Also, you can't perform two or more moves to the left in a row.}\n\nYou want to perform \\textbf{exactly} $k$ moves. Also, there should be no more than $z$ moves to the left among them.\n\nWhat is the maximum score you can achieve?",
    "tutorial": "Notice that your final position is determined by the number of moves to the left you make. Let there be exactly $t$ moves to the left, that leaves us with $k - t$ moves to the right. However, let's interpret this the other way. You have $t$ pairs of moves (right, left) to insert somewhere inside the sequence of $k - 2t$ moves to the right. Easy to see that all the positions from $1$ to $k - 2t + 1$ will always be visited. And the extra pairs can also increase the score by visiting some positions ($i+1$, $i$) for some $i$ from $1$ to $k - 2t + 1$. Notice that it's always optimal to choose exactly the same $i$ for all the pairs (right, left). And that $i$ should be such that $a_{i+1} + a_i$ is maximum possible. You can implement this idea in a straightforward manner: iterate over $t$ and calculate the sum of values from $1$ to $k - 2t + 1$ and the maximum value of $a_{i+1} + a_i$ over $i$ from $1$ to $k - 2t + 1$. That will lead to a $O(zn)$ solution per testcase. You can optimize it to $O(n)$ with prefix sums or with some clever order to iterate over $t$. It's also possible to iterate over the final position and restore the number of left moves required to achieve it. Overall complexity: $O(zn)$ or $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn, k, z = map(int, input().split())\n\ta = [int(x) for x in input().split()]\n\tans = 0\n\ts = 0\n\tmx = 0\n\tfor i in range(k + 1):\n\t\tif i < n - 1:\n\t\t\tmx = max(mx, a[i] + a[i + 1])\n\t\ts += a[i]\n\t\tif i % 2 == k % 2:\n\t\t\ttmp = (k - i) // 2\n\t\t\tif tmp <= z:\n\t\t\t\tans = max(ans, s + mx * tmp)\n\tprint(ans)",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1389",
    "index": "C",
    "title": "Good String",
    "statement": "Let's call left cyclic shift of some string $t_1 t_2 t_3 \\dots t_{n - 1} t_n$ as string $t_2 t_3 \\dots t_{n - 1} t_n t_1$.\n\nAnalogically, let's call right cyclic shift of string $t$ as string $t_n t_1 t_2 t_3 \\dots t_{n - 1}$.\n\nLet's say string $t$ is \\textbf{good} if its left cyclic shift is equal to its right cyclic shift.\n\nYou are given string $s$ which consists of digits 0–9.\n\nWhat is the minimum number of characters you need to erase from $s$ to make it good?",
    "tutorial": "Let's analyze when the string is good. Suppose it is $t_1t_2 \\dots t_k$. The cyclic shifts of this string are $t_kt_1t_2 \\dots t_{k-1}$ and $t_2t_3 \\dots t_k t_1$. We get the following constraints for a good string: $t_k = t_2$, $t_1 = t_3$, $t_2 = t_4$, ..., $t_{k - 2} = t_k$, $t_{k - 1} = t_1$. If the string has odd length, then all characters should be equal to each other; otherwise, all characters on odd positions should be equal, and all characters on even positions should be equal. Now, since there are only $10$ different types of characters, we can brute force all possible combinations of the first and the second character of the string we want to obtain (there are only $100$ of them) and, for each combination, greedily construct the longest possible subsequence of $s$ beginning with those characters in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nint solve(const string& s, int x, int y) {\n\tint res = 0;\n\tfor (auto c : s) if (c - '0' == x) {\n\t\t++res;\n\t\tswap(x, y);\n\t}\n\tif (x != y && res % 2 == 1)\n\t\t--res;\n\treturn res;\n}\n\nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tint ans = 0;\n\tforn(x, 10) forn(y, 10)\n\t\tans = max(ans, solve(s, x, y));\n\tcout << sz(s) - ans << endl;\n}\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile (T--) solve();\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1389",
    "index": "D",
    "title": "Segment Intersections",
    "statement": "You are given two lists of segments $[al_1, ar_1], [al_2, ar_2], \\dots, [al_n, ar_n]$ and $[bl_1, br_1], [bl_2, br_2], \\dots, [bl_n, br_n]$.\n\nInitially, all segments $[al_i, ar_i]$ are equal to $[l_1, r_1]$ and all segments $[bl_i, br_i]$ are equal to $[l_2, r_2]$.\n\nIn one step, you can choose one segment (either from the first or from the second list) and extend it by $1$. In other words, suppose you've chosen segment $[x, y]$ then you can transform it either into $[x - 1, y]$ or into $[x, y + 1]$.\n\nLet's define a total intersection $I$ as the sum of lengths of intersections of the corresponding pairs of segments, i.e. $\\sum\\limits_{i=1}^{n}{\\text{intersection_length}([al_i, ar_i], [bl_i, br_i])}$. Empty intersection has length $0$ and length of a segment $[x, y]$ is equal to $y - x$.\n\nWhat is the minimum number of steps you need to make $I$ greater or equal to $k$?",
    "tutorial": "At first, note that intersection_length of segments $[l_1, r_1]$ and $[l_2, r_2]$ can be calculated as $\\min(r_1, r_2) - \\max(l_1, l_2)$. If it's negative then segments don't intersect, otherwise it's exactly length of intersection. Now we have two major cases: do segments $[l_1, r_1]$ and $[l_2, r_2]$ already intersect or not. If segments intersect then we already have $n \\cdot (\\min(r_1, r_2) - \\max(l_1, l_2))$ as the total intersection. Note, that making both segments equal to $[\\min(l_1, l_2), \\max(r_1, r_2)]$ in each pair are always optimal since in each step we will increase the total intersection by $1$. After making all segments equal to $[\\min(l_1, l_2), \\max(r_1, r_2)]$ we can increase total intersection by $1$ only in two steps: we need to extend both segments in one pair. In result, we can find not a hard formula to calculate the minimum number of steps: we already have $n \\cdot (\\min(r_1, r_2) - \\max(l_1, l_2))$ of the total intersection, then we can increase it by at most $n \\cdot ((\\max(r_1, r_2) - \\min(l_1, l_2)) - (\\min(r_1, r_2) - \\max(l_1, l_2)))$ using one step per increase, and then to any number using two steps per increase. In the case of non-intersecting $[l_1, l_2]$ and $[r_1, r_2]$, we should at first \"invest\" some number of steps in each pair to make them intersect. So let's iterate over the number of segments to \"invest\" $cntInv$. We should make $cntInv \\cdot (\\max(l_1, l_2) - \\min(r_1, r_2))$ steps to make segments touch. Now, $cntInv$ segments touch so we can use almost the same formulas for them as in the previous case. The total complexity is $O(n)$ per test case.",
    "code": "import kotlin.math.*\n\nfun main() {\n    repeat(readLine()!!.toInt()) {\n        val (n, k) = readLine()!!.split(' ').map { it.toLong() }\n        val (l1, r1) = readLine()!!.split(' ').map { it.toLong() }\n        val (l2, r2) = readLine()!!.split(' ').map { it.toLong() }\n\n        var ans = 1e18.toLong()\n        if (max(l1, l2) <= min(r1, r2)) {\n            val rem = max(0L, k - n * (min(r1, r2) - max(l1, l2)))\n            val maxPossible = n * (abs(l1 - l2) + abs(r1 - r2))\n            ans = min(rem, maxPossible) + max(0L, rem - maxPossible) * 2\n        } else {\n            val invest = max(l1, l2) - min(r1, r2)\n            for (cntInv in 1..n) {\n                var curAns = invest * cntInv\n                val maxPossible = (max(r1, r2) - min(l1, l2)) * cntInv\n                curAns += min(k, maxPossible) + max(0L, k - maxPossible) * 2\n                ans = min(ans, curAns)\n            }\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1389",
    "index": "E",
    "title": "Calendar Ambiguity",
    "statement": "Berland year consists of $m$ months with $d$ days each. Months are numbered from $1$ to $m$. Berland week consists of $w$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $w$ days.\n\nA pair $(x, y)$ such that $x < y$ is ambiguous if day $x$ of month $y$ is the same day of the week as day $y$ of month $x$.\n\nCount the number of ambiguous pairs.",
    "tutorial": "Let the month, the days in them and the days of the week be numbered $0$-based. Translate the $x$-th day of the $y$-th month to the index of that day in a year; that would be $yd + x$. Thus, the corresponding day of the week is $(yd + x)~mod~w$. So we can rewrite the condition for a pair as $xd + y \\equiv yd + x~(mod~w)$. That's also $(xd + y) - (yd + x) \\equiv 0~(mod~w)$. Continue with $(x - y)(d - 1) \\equiv 0~(mod~w)$. So $(x - y)(d - 1)$ should be divisible by $w$. $d - 1$ is fixed and some prime divisors of $w$ might have appeared in it already. If we remove them from $w$ then $(x - y)$ should just be divisible by the resulting number. So we can divide $w$ by $gcd(w, d - 1)$ and obtain that $w'$. Now we should just count the number of pairs $(x, y)$ such that $x - y$ is divisible by $w'$. We know that the difference $x - y$ should be from $1$ to $min(d, m)$. So we can fix the difference and add the number of pairs for that difference. That would be $mn - k$ for a difference $k$. Finally, the answer is $\\sum \\limits_{i=1}^{min(d, m) / w'} mn - i \\cdot w'$. Use the formula for the sum of arithmetic progression to solve that in $O(1)$. Overall complexity: $O(\\log(w + d))$ per testcase.",
    "code": "fun gcd(a: Long, b: Long): Long {\n\tif (a == 0L) return b\n\treturn gcd(b % a, a)\n}\n\nfun main() {\n\trepeat(readLine()!!.toInt()) {\n\t\tval (m, d, w) = readLine()!!.split(' ').map { it.toLong() }\n\t\tval w2 = w / gcd(d - 1, w)\n\t\tval mn = minOf(m, d)\n\t\tvar cnt = mn / w2\n\t\tprintln((2 * (mn - w2) - w2 * (cnt - 1)) * cnt / 2)\n\t}\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1389",
    "index": "F",
    "title": "Bicolored Segments",
    "statement": "You are given $n$ segments $[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]$. Each segment has one of two colors: the $i$-th segment's color is $t_i$.\n\nLet's call a pair of segments $i$ and $j$ bad if the following two conditions are met:\n\n- $t_i \\ne t_j$;\n- the segments $[l_i, r_i]$ and $[l_j, r_j]$ intersect, embed or touch, i. e. there exists an integer $x$ such that $x \\in [l_i, r_i]$ and $x \\in [l_j, r_j]$.\n\nCalculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.",
    "tutorial": "There are two approaches to this problem. Most of the participants of the round got AC by implementing dynamic programming with data structures such as segment tree, but I will describe another solution which is much easier to code. Let's consider a graph where each vertex represents a segment, and two vertices are connected by an edge if the corresponding segments compose a bad pair. Since each bad pair is formed by two segments of different colors, the graph is bipartite. The problem asks us to find the maximum independent set, and in bipartite graphs, the size of the independent set is equal to $V - M$, where $V$ is the number of vertices, and $M$ is the size of the maximum matching. The only thing that's left is finding the maximum matching. Let's use event processing approach to do it: for each segment, create two events \"the segment begins\" and \"the segment ends\". While processing the events, maintain the currently existing segments in two sets (grouped by their colors and sorted by the time they end). When a segment ends, let's try to match it with some segment of the opposite color - and it's quite obvious that we should choose a segment with the minimum $r_i$ to form a pair. Overall, this solution runs in $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define pb push_back\n#define mp make_pair\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\ntypedef pair<int, int> pt;\n\nconst int INF = 1e9;\nconst int N = 200 * 1000;\n\nint n;\nvector<pt> a[2];\n\nstruct segtree {\n\tint n;\n\tvector<int> t, ps;\n\tsegtree(int n) : n(n) {\n\t\tt.resize(4 * n, -INF);\n\t\tps.resize(4 * n, 0);\n\t}\n\t\n\tvoid push(int v, int l, int r) {\n\t\tif (l + 1 != r) {\n\t\t\tps[v * 2 + 1] += ps[v];\n\t\t\tps[v * 2 + 2] += ps[v];\n\t\t}\n\t\tt[v] += ps[v];\n\t\tps[v] = 0;\n\t}\n\t\n\tvoid upd(int v, int l, int r, int pos, int val) {\n\t\tpush(v, l, r);\n\t\tif (l + 1 == r) {\n\t\t\tt[v] = val;\n\t\t\treturn;\n\t\t}\n\t\tint m = (l + r) >> 1;\n\t\tif (pos < m) upd(v * 2 + 1, l, m, pos, val);\n\t\telse upd(v * 2 + 2, m, r, pos, val);\n\t\tt[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n\t}\n\t\n\tvoid add(int v, int l, int r, int L, int R, int val) {\n\t\tpush(v, l, r);\n\t\tif (L >= R) return;\n\t\tif (l == L && r == R) {\n\t\t\tps[v] += val;\n\t\t\tpush(v, l, r);\n\t\t\treturn;\n\t\t}\n\t\tint m = (l + r) >> 1;\n\t\tadd(v * 2 + 1, l, m, L, min(m, R), val);\n\t\tadd(v * 2 + 2, m, r, max(m, L), R, val);\n\t\tt[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n\t}\n\t\n\tint get(int v, int l, int r, int L, int R) {\n\t\tpush(v, l, r);\n\t\tif (L >= R) return -INF;\n\t\tif (l == L && r == R) \n\t\t\treturn t[v];\n\t\tint m = (l + r) >> 1;\n\t\tint r1 = get(v * 2 + 1, l, m, L, min(m, R));\n\t\tint r2 = get(v * 2 + 2, m, r, max(m, L), R);\n\t\tt[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n\t\treturn max(r1, r2);\n\t}\n\t\n\tvoid upd(int pos, int val) {\n\t\treturn upd(0, 0, n, pos, val);\n\t}\n\t\n\tvoid add(int l, int r, int val) {\n\t\treturn add(0, 0, n, l, r, val);\n\t}\n\t\n\tint get(int l, int r) {\n\t\treturn get(0, 0, n, l, r);\n\t}\n};\n\nint main() {\n\tscanf(\"%d\", &n);\n\tforn(i, n) {\n\t\tint l, r, t;\n\t\tscanf(\"%d%d%d\", &l, &r, &t);\n\t\ta[t - 1].pb(mp(r, l));\n\t}\n\t\n\tforn(i, 2) sort(all(a[i]), [](pt a, pt b) {\n\t\tif (a.x == b.x) return a.y > b.y;\n\t\treturn a.x < b.x;\n\t});\n\t\n\tsegtree t1(sz(a[0]) + 1), t2(sz(a[1]) + 1);\n\tt1.upd(0, 0);\n\tt2.upd(0, 0);\n\t\t\n\tint ans = 0;\n\tfor (int i = 0, j = 0; i + j < n; ) {\n\t\tif (i < sz(a[0]) && (j == sz(a[1]) || a[0][i].x <= a[1][j].x)) {\n\t\t\tint pos = upper_bound(all(a[1]), mp(a[0][i].y, -INF)) - a[1].begin() + 1; \n\t\t\tint cur = t2.get(0, pos) + 1;\n\t\t\tans = max(ans, cur);\n\t\t\tt1.upd(i + 1, cur);\n\t\t\tt2.add(0, pos, 1);\n\t\t\t++i;\n\t\t} else {\n\t\t\tint pos = upper_bound(all(a[0]), mp(a[1][j].y, -INF)) - a[0].begin() + 1; \n\t\t\tint cur = t1.get(0, pos) + 1;\n\t\t\tans = max(ans, cur);\n\t\t\tt2.upd(j + 1, cur);\n\t\t\tt1.add(0, pos, 1);\n\t\t\t++j;\n\t\t}\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "data structures",
      "dp",
      "graph matchings",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1389",
    "index": "G",
    "title": "Directing Edges",
    "statement": "You are given an undirected connected graph consisting of $n$ vertices and $m$ edges. $k$ vertices of this graph are special.\n\nYou have to direct each edge of this graph or leave it undirected. If you leave the $i$-th edge undirected, you pay $w_i$ coins, and if you direct it, you don't have to pay for it.\n\nLet's call a vertex saturated if it is reachable from each special vertex along the edges of the graph (if an edge is undirected, it can be traversed in both directions). After you direct the edges of the graph (possibly leaving some of them undirected), you receive $c_i$ coins for each saturated vertex $i$. Thus, your total profit can be calculated as $\\sum \\limits_{i \\in S} c_i - \\sum \\limits_{j \\in U} w_j$, where $S$ is the set of saturated vertices, and $U$ is the set of edges you leave undirected.\n\nFor each vertex $i$, calculate the maximum possible profit you can get if you have to make the vertex $i$ saturated.",
    "tutorial": "Suppose we want to calculate the maximum profit for some vertex in $O(n)$. Let's try to find out how it can be done, and then optimize this process so we don't have to run it $n$ times. First of all, we have to find the bridges and biconnected components in our graph. Why do we need them? Edges in each biconnected component can be directed in such a way that it becomes a strongly connected component, so we don't have to leave these edges undirected (it is never optimal). Furthermore, for each such component, either all vertices are saturated or no vertex is saturated. Let's build a tree where each vertex represents a biconnected component of the original graph, and each edge represents a bridge. We can solve the problem for this tree, and then the answer for some vertex of the original graph is equal to the answer for the biconnected component this vertex belongs to. Okay, now we have a problem on tree. Let's implement the following dynamic programming solution: root the tree at the vertex we want to find the answer for, and for each vertex, calculate the value of $dp_v$ - the maximum profit we can get for the subtree of vertex $v$, if it should be reachable by all special vertices from its subtree. Let's analyze how we can calculate these $dp$ values. Suppose we have a vertex $v$ with children $v_1$, $v_2$, ..., $v_d$, we have already calculated the $dp$ values for the children, and we want to calculate $dp_v$. First of all, since the vertex $v$ is going to be saturated, we will get the profit from it, so we initialize $dp_v$ with $c_v$. Then we should decide whether we want to get the profit from the children of vertex $v$. Suppose the edge leading from $v$ to $v_i$ has weight $w_i$. If we want to take the profit from the subtree of $v_i$, we (usually) have to make this edge undirected, so both vertices are saturated, thus we get $dp_{v_i} - w_i$ as profit - or we could leave this edge directed from $v_i$ to $v$, so the vertex $v$ is saturated, and $v_i$ is not, and get $0$ as the profit. But sometimes we can gain the profit from the vertex $v_i$ and its subtree without leaving the edge undirected: if all special vertices belong to the subtree of $v_i$, we can just direct this edge from $v_i$ to $v$, and there is no reason to choose the opposite direction or leave the edge undirected. Similarly, if all special vertices are outside of this subtree, there's no reason to direct the edge from $v_i$ to $v$. So, if one of this conditions is met, we can get the full profit from the subtree of $v_i$ without leaving the edge undirected. Okay, let's summarize it. We can calculate $dp_v$ as $dp_v = c_v + \\sum \\limits_{i=1}^{d} f(v_i)$, where $f(v_i)$ is either $dp_{v_i}$ if one of the aforementioned conditions is met (we don't have to leave the edge undirected if we want to saturate both vertices), or $f(v_i) = \\max(0, dp_{v_i} - w_i)$ otherwise. Now we have an $O(n^2)$ solution. Let's optimize it to $O(n)$. Root the tree at vertex $1$ and calculate the dynamic programming as if $1$ is the root. Then, we shall use rerooting technique to recalculate the dynamic programming for all other vertices: we will try each vertex as the root of the tree, and $dp_v$ is the answer for the vertex $v$ if it is the root. The rerooting technique works as follows: let's run DFS from the initial root of the tree, and when we traverse an edge by starting or finishing a recursive call of DFS, we move the root along the edge; so, if we call $DFS(x)$, $x$ is the current root; if it has some child $y$, we move the root to $y$ the same moment when we call $DFS(y)$, and when the call of $DFS(y)$ ends, the root moves back to $x$. Okay, the only thing that's left is to describe how we move the root. If the current root is $x$, and we want to move it to $y$ (a vertex adjacent to $x$), then we have to change only the values of $dp_x$ and $dp_y$: first of all, since $y$ is no longer a child of $x$, we have to subtract the value that was added to $dp_x$ while we considered vertex $y$; then, we have to make $x$ the child of vertex $y$, so we add the profit we can get from the vertex $x$ to $dp_y$. It can be done in $O(1)$, so our solution runs in $O(n)$, though with a very heavy constant factor.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\nconst int N = 300043;\n\nbool is_bridge[N];\nint w[N];\nint c[N];\nint v[N];\nvector<pair<int, int> > g[N];\n\nvector<pair<int, int> > g2[N];\nint comp[N];\nli sum[N];\nli dp[N];\nint cnt[N];\nint fup[N];\nint tin[N];\nint T = 0;\nli ans[N];\nint v1[N], v2[N];\n\nint n, m, k;\n\nint dfs1(int x, int e)\n{\n\ttin[x] = T++;\n\tfup[x] = tin[x];\n\tfor(auto p : g[x])\n\t{\n\t\tint y = p.first;\n\t\tint i = p.second;\n\t\tif(i == e)\n\t\t\tcontinue;\n\t\tif(tin[y] != -1)\n\t\t\tfup[x] = min(fup[x], tin[y]);\n\t\telse\n\t\t{\n\t\t\tfup[x] = min(fup[x], dfs1(y, i));\n\t\t\tif(fup[y] > tin[x])\n\t\t\t\tis_bridge[i] = true;\n\t\t}\n\t}\n\treturn fup[x];\n}\n\nvoid dfs2(int x, int cc)\n{\n\tif(comp[x] != -1)\n\t\treturn;\n\tcomp[x] = cc;\n\tcnt[cc] += v[x];\n\tsum[cc] += c[x];\n\tfor(auto y : g[x])\n\t\tif(!is_bridge[y.second])\n\t\t\tdfs2(y.first, cc);\n}\n\nvoid process_edge(int x, int y, int m, int weight)\n{\n\tli add_dp = dp[y];\n\tif(cnt[y] > 0 && cnt[y] < k)\n\t\tadd_dp = max(0ll, add_dp - weight);\n\t\n\tcnt[x] += m * cnt[y];\n\tdp[x] += m * add_dp;\n}\n\nvoid link(int x, int y, int weight)\n{\n\tprocess_edge(x, y, 1, weight);\n}\n\nvoid cut(int x, int y, int weight)\n{\n\tprocess_edge(x, y, -1, weight);\n}\n\nvoid dfs3(int x, int p)\n{\n    dp[x] = sum[x];\n\tfor(auto e : g2[x])\n\t{\n\t\tint i = e.second;\n\t\tint y = e.first;\n\t\tif(y == p)\n\t\t\tcontinue;\n\t\tdfs3(y, x);\n\t\tlink(x, y, w[i]);\n\t}\n}\n\nvoid dfs4(int x, int p)\n{\n\tans[x] = dp[x];\n\tfor(auto e : g2[x])\n\t{\n\t\tint i = e.second;\n\t\tint y = e.first;\n\t\tif(y == p)\n\t\t\tcontinue;\n\t\tcut(x, y, w[i]);\n\t\tlink(y, x, w[i]);\n\t\tdfs4(y, x);\n\t\tcut(y, x, w[i]);\n\t\tlink(x, y, w[i]);\n\t}\n}\n\nint main()\n{\n\tscanf(\"%d %d %d\", &n, &m, &k);\n\tfor(int  i = 0; i < k; i++)\n\t{\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\t--x;\n\t\tv[x] = 1;\n\t}\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d\", &c[i]);\n\tfor(int i = 0; i < m; i++)\n\t\tscanf(\"%d\", &w[i]);\n\tfor(int i = 0; i < m; i++)\n\t{\n\t\tscanf(\"%d %d\", &v1[i], &v2[i]);\n\t\t--v1[i];\n\t\t--v2[i];\n\t\tg[v1[i]].push_back(make_pair(v2[i], i));\n\t\tg[v2[i]].push_back(make_pair(v1[i], i));\n\t}\n\t\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\ttin[i] = -1;\n\t\tcomp[i] = -1;\n\t}\n\tdfs1(0, -1);\n\tint cc = 0;\n\tfor(int i = 0; i < n; i++)\n\t\tif(comp[i] == -1)\n\t\t\tdfs2(i, cc++);\n\tfor(int i = 0; i < m; i++)\n\t\tif(is_bridge[i])\n\t\t{\n\t\t\tg2[comp[v1[i]]].push_back(make_pair(comp[v2[i]], i));\n\t\t\tg2[comp[v2[i]]].push_back(make_pair(comp[v1[i]], i));\n\t\t}\n\tdfs3(0, 0);\n\tdfs4(0, 0);\n\tfor(int i = 0; i < n; i++)\n\t\tprintf(\"%lld \", ans[comp[i]]);\n\tputs(\"\");\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1391",
    "index": "A",
    "title": "Suborrays",
    "statement": "A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nFor a positive integer $n$, we call a permutation $p$ of length $n$ \\textbf{good} if the following condition holds for every pair $i$ and $j$ ($1 \\le i \\le j \\le n$) —\n\n- $(p_i \\text{ OR } p_{i+1} \\text{ OR } \\ldots \\text{ OR } p_{j-1} \\text{ OR } p_{j}) \\ge j-i+1$, where $\\text{OR}$ denotes the bitwise OR operation.\n\nIn other words, a permutation $p$ is \\textbf{good} if for every subarray of $p$, the $\\text{OR}$ of all elements in it is not less than the number of elements in that subarray.\n\nGiven a positive integer $n$, output any \\textbf{good} permutation of length $n$. We can show that for the given constraints such a permutation always exists.",
    "tutorial": "Every permutation is good. Proof: We use the fact that for any set of numbers, it's bitwise OR is at least the maximum value in it. Now, we just need to show that any subarray of length $len$ has at least one element greater than or equal to $len$. If the maximum element is $< len$, then, we have $len$ elements all with values in the range $[1,len-1]$. By the pigeonhole principle, at least $2$ of them must be the same contradicting the fact the it's a permutation. Time Complexity: $\\mathcal{O}(n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nmt19937 rng((int) std::chrono::steady_clock::now().time_since_epoch().count());\n \nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int> all;\n    for(int i = 1;i <= n;i++)all.push_back(i);\n    shuffle(all.begin(),all.end(),rng);\n    for(int i = 0;i < n;i++){\n        cout << all[i] << \" \";\n    }\n    cout << endl;\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1391",
    "index": "B",
    "title": "Fix You",
    "statement": "Consider a conveyor belt represented using a grid consisting of $n$ rows and $m$ columns. The cell in the $i$-th row from the top and the $j$-th column from the left is labelled $(i,j)$.\n\nEvery cell, except $(n,m)$, has a direction R (Right) or D (Down) assigned to it. If the cell $(i,j)$ is assigned direction R, any luggage kept on that will move to the cell $(i,j+1)$. Similarly, if the cell $(i,j)$ is assigned direction D, any luggage kept on that will move to the cell $(i+1,j)$. If at any moment, the luggage moves out of the grid, it is considered to be lost.\n\nThere is a counter at the cell $(n,m)$ from where all luggage is picked. A conveyor belt is called \\textbf{functional} if and only if any luggage reaches the counter regardless of which cell it is placed in initially. More formally, for every cell $(i,j)$, any luggage placed in this cell should eventually end up in the cell $(n,m)$.\n\nThis may not hold initially; you are, however, allowed to \\textbf{change} the directions of some cells to make the conveyor belt functional. Please determine the minimum amount of cells you have to change.\n\nPlease note that it is always possible to make any conveyor belt functional by changing the directions of some set of cells.",
    "tutorial": "The answer is $#R in the last column + #D in the last row$. It's obvious that we must change all Rs in the last column and all Ds in the last row. Otherwise, anything placed in those cells will move out of the grid. We claim that doing just this is enough to make the grid functional. Indeed, for any other cell, any luggage placed in it will eventually reach either the last row or the last column, from which it will move to the counter. Time Complexity: $\\mathcal{O}(n*m)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint n,m;\n \nvoid solve(){\n\tcin >> n >> m;\n\tint ans = 0;\n\tfor(int i = 1;i <= n;i++){\n\t\tfor(int j = 1;j <= m;j++){\n\t\t\tchar o;cin >> o;\n\t\t\tif(o == 'C')continue;\n\t\t\tif(i == n and o == 'D')ans++;\n\t\t\tif(j == m and o == 'R')ans++;\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n \nint main(){\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tint t;cin >> t;\n\twhile(t--){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1391",
    "index": "C",
    "title": "Cyclic Permutations ",
    "statement": "A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nConsider a permutation $p$ of length $n$, we build a graph of size $n$ using it as follows:\n\n- For every $1 \\leq i \\leq n$, find the \\textbf{largest} $j$ such that $1 \\leq j < i$ and $p_j > p_i$, and add an undirected edge between node $i$ and node $j$\n- For every $1 \\leq i \\leq n$, find the \\textbf{smallest} $j$ such that $i < j \\leq n$ and $p_j > p_i$, and add an undirected edge between node $i$ and node $j$\n\nIn cases where no such $j$ exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.\n\nFor clarity, consider as an example $n = 4$, and $p = [3,1,4,2]$; here, the edges of the graph are $(1,3),(2,1),(2,3),(4,3)$.\n\nA permutation $p$ is \\textbf{cyclic} if the graph built using $p$ has at least one simple cycle.\n\nGiven $n$, find the number of cyclic permutations of length $n$. Since the number may be very large, output it modulo $10^9+7$.\n\nPlease refer to the Notes section for the formal definition of a simple cycle",
    "tutorial": "The answer is $n!-2^{n-1}$. Consider an arbitrary cyclic permutation - for example, [4,2,3,1,5,6]; it contains many cycles of length $3$: $[1,2,3]$, $[1,3,5]$, $[3,4,5]$. Note that all the listed cycles contain nodes obtained from just one choice of $i$. We can generalize this to the following. If for any $i$, we make edges on both sides of it, this will create a simple cycle of length $3$. The proof is simple and is an exercise for you. Thus, there has to at most one peak that is the element $n$- all acyclic permutations increase, then reach $n$, and, finally, decrease. These are formally called unimodal permutations, and it's easy to see that any unimodal permutation forms a tree, and, thus, contains no simple cycle - each element, except $n$, has a uniquely defined parent. We can construct any unimodal permutation by adding the numbers $n, n-1, \\ldots, 1$ into a deque in the same order. For example, $[2,3,4,1]$ can be constructed by first pushing $4$, $3$, $2$ to the front, and, finally, $1$ at the back. Thus, for every element, except $n$, we have the choice of pushing it to the front or the back, making the total number of ways equal to $2^{n-1}$. Time Complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\nconst int MOD = 1e9+7;\n \nint n;\nint res,fact;\n \nsigned main(){\n\tcin >> n;\n\tres = 1;\n\tfact = 1;\n\tfor(int i = 1;i <= n-1;i++){\n\t\tres *= 2;\n\t\tfact *= i;\n\t\tfact %= MOD;\n\t\tres %= MOD;\n\t}\n\tfact *= n;\n\tfact %= MOD;\n\tfact -= res;\n\tfact %= MOD;\n\tif(fact < 0)fact += MOD;\n\tcout << fact;\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "graphs",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1391",
    "index": "D",
    "title": "505",
    "statement": "A binary matrix is called \\textbf{good} if every \\textbf{even} length square sub-matrix has an \\textbf{odd} number of ones.\n\nGiven a binary matrix $a$ consisting of $n$ rows and $m$ columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all.\n\nAll the terms above have their usual meanings — refer to the Notes section for their formal definitions.",
    "tutorial": "Firstly, if $min(n,m) > 3$, then, no solution exists because this means the grid contains at least one $4\\times4$ sub-matrix, which can further be decomposed into four $2\\times2$ sub-matrices. Since all four of these $2\\times2$ sub-matrices are supposed to have an odd number of ones, the union of them will have an even number of ones. The problem, now, reduces to changing the least number of cells such that every $2\\times2$ sub-matrix has an odd number of ones - this is possible to achieve for every valid grid. For example, for every even-indexed row, alternate the cells, and for every odd-indexed row, make all cells equal to $1$. We will solve this reduction using dynamic programming. We represent the $i^{th}$ column as a $n$-bit integer - $a_i$; let $dp(i,mask)$ be the minimum cells we have to flip to make the first $i$ columns valid, and the $i^{th}$ column is represented by $mask$. The transition is quite simple: $dp(i,cmask) = min( dp(i-1,pmask)+bitcount(cmask \\oplus a[i]), dp(i,cmask)).$ The term $bitcount(cmask \\oplus a[i])$ is equal to the number of positions where these two masks differ. Please note that we only consider those pairs, $\\{pmask,cmask\\}$, that when put adjacent do not form a $2\\times2$ sub-matrix with an even number of ones. To speed up the transition, they can be pre-calculated. Time Complexity: $\\mathcal{O}(m*2^{2n} + n*m)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nconst int N = 5e5+1;\nint n,m;\nint a[4][N];\nint dp3[N][8];\nint dp2[N][4];\nbool ok3[8][8];\nbool ok2[4][4];\n \nvoid fill3(){\n\tfor(int i = 0;i < 8;i++){\n\t\tfor(int j = 0;j < 8;j++){\n\t\t\tbool bad = 0;\n\t\t\tfor(int st = 0;st < 2;st++){\n\t\t\t\tint bits = (bool)(i&(1<<st))+(bool)(i&(1<<(st+1)));\n\t\t\t\tbits += (bool)(j&(1<<st))+(bool)(j&(1<<(st+1)));\n\t\t\t\tif(bits%2 == 0){\n\t\t\t\t\tbad = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!bad){\n\t\t\t\tok3[i][j] = 1;\n\t\t\t}\n\t\t}\n\t}\n}\n \nvoid fill2(){\n\tfor(int i = 0;i < 4;i++){\n\t\tfor(int j = 0;j < 4;j++){\n\t\t\tbool bad = 0;\n\t\t\tfor(int st = 0;st < 1;st++){\n\t\t\t\tint bits = (bool)(i&(1<<st))+(bool)(i&(1<<(st+1)));\n\t\t\t\tbits += (bool)(j&(1<<st))+(bool)(j&(1<<(st+1)));\n\t\t\t\tif(bits%2 == 0){\n\t\t\t\t\tbad = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!bad){\n\t\t\t\tok2[i][j] = 1;\n\t\t\t}\n\t\t}\n\t}\n}\n \n \nvoid solve2(){\n\tfor(int i = 1;i <= m;i++){\n\t\tint mask = a[1][i]+2*a[2][i];\n\t\tfor(int cur = 0;cur < 4;cur++){\n\t\t\tdp2[i][cur] = 1e9;\n\t\t\tfor(int prev = 0;prev < 4;prev++){\n\t\t\t\tif(!ok2[prev][cur])continue;\n\t\t\t\tdp2[i][cur] = min(dp2[i][cur],dp2[i-1][prev]+__builtin_popcount(cur^mask));\n\t\t\t}\n\t\t}\n\t}\n\tint ans = 1e9;\n\tfor(int i = 0;i < 4;i++)ans = min(ans,dp2[m][i]);\n\tcout << ans;\n}\n \nvoid solve3(){\n\tfor(int i = 1;i <= m;i++){\n\t\tint mask = a[1][i]+2*a[2][i]+4*a[3][i];\n\t\tfor(int cur = 0;cur < 8;cur++){\n\t\t\tdp3[i][cur] = 1e9;\n\t\t\tfor(int prev = 0;prev < 8;prev++){\n\t\t\t\tif(!ok3[prev][cur])continue;\n\t\t\t\tdp3[i][cur] = min(dp3[i][cur],dp3[i-1][prev]+__builtin_popcount(cur^mask));\n\t\t\t}\n\t\t}\n\t}\n\tint ans = 1e9;\n\tfor(int i = 0;i < 8;i++)ans = min(ans,dp3[m][i]);\n\tcout << ans;\n}\n \nvoid solve(){\n\tcin >> n >> m;\n\tif(min(n,m) > 3){\n\t\tcout << -1;\n\t\treturn;\n\t}\n\tif(min(n,m) == 1){\n\t\tcout << 0;\n\t\treturn;\n\t}\n\tfor(int i = 1;i <= n;i++){\n\t\tfor(int j = 1;j <= m;j++){\n\t\t\tchar o;cin >> o;\n\t\t\ta[i][j] = o-'0';\n\t\t}\n\t}\n\tif(n == 3)solve3();\n\telse solve2();\n}\n \nint main(){\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tfill2();\n\tfill3();\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1391",
    "index": "E",
    "title": "Pairs of Pairs",
    "statement": "You have a simple and connected undirected graph consisting of $n$ nodes and $m$ edges.\n\nConsider any way to pair some subset of these $n$ nodes such that no node is present in more than one pair.\n\nThis pairing is \\textbf{valid} if for every pair of pairs, the induced subgraph containing all $4$ nodes, two from each pair, has at most $2$ edges (out of the $6$ possible edges). More formally, for any two pairs, $(a,b)$ and $(c,d)$, the induced subgraph with nodes $\\{a,b,c,d\\}$ should have at most $2$ edges.\n\nPlease note that the subgraph induced by a set of nodes contains nodes only from this set and edges which have both of its end points in this set.\n\nNow, do one of the following:\n\n- Find a simple path consisting of at least $\\lceil \\frac{n}{2} \\rceil$ nodes. Here, a path is called simple if it does not visit any node multiple times.\n- Find a valid pairing in which at least $\\lceil \\frac{n}{2} \\rceil$ nodes are paired.\n\nIt can be shown that it is possible to find at least one of the two in every graph satisfying constraints from the statement.",
    "tutorial": "Let's build the DFS tree of the given graph, and let $dep(u)$ denote the depth of node $u$ in the tree. If $dep(u) \\ge \\lceil \\frac{n}{2} \\rceil$ holds for any node $u$, we have found a path. Otherwise, the maximum depth is at most $\\lfloor \\frac{n}{2} \\rfloor$, and we can find a valid pairing as follows: For every depth $i$ ($1 \\le i \\le \\lfloor \\frac{n}{2} \\rfloor$), keep pairing nodes at this depth until $0$ or $1$ remain. Clearly, at most $1$ node from each depth will remain unpaired, so, in total, we have paired at least $n - \\lfloor \\frac{n}{2} \\rfloor = \\lceil \\frac{n}{2} \\rceil$ nodes. Finally, let's prove that every subgraph induced from some $2$ pairs has at most $2$ edges. Consider $2$ arbitrary pairs, ($a,b$) and ($c,d$), where $dep(a) = dep(b)$ and $dep(c) = dep(d)$. W.L.O.G, let $dep(a) < dep(c)$. Obviously, the edges ($a,b$) and ($c,d$) cannot exist because edges can only go from a descendant to an ancestor. We can, further, show that each of $c$ and $d$ can have an edge to at most one of $a$ and $b$. For example, if $c$ has an edge to both $a$ and $b$, we can conclude that $a$ and $b$ are ancestor-descendants, which is not possible because both of them are at the same depth. Time Complexity: $\\mathcal{O}(n+m)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 5e5+1;\nint n,m;\nvector<int> adj[N];\nbool vis[N];\nvector<int> all[N];\nint dep[N];\nint par[N];\nint pairs = 0;\nbool outputted = 0;\n \nvoid dfs(int u){\n\tif(outputted)return;\n\tvis[u] = 1;\n\tpairs -= all[dep[u]].size()/2;\n\tall[dep[u]].push_back(u);\n\tpairs += all[dep[u]].size()/2;\n\tif(dep[u] >= (n+1)/2){\n\t\toutputted = 1;\n\t\tcout << \"PATH\" << \"\\n\";\n\t\tint cur = u;\n\t\tcout << dep[u] << \"\\n\";\n\t\twhile(cur != 0){\n\t\t\tcout << cur << \" \";\n\t\t\tcur = par[cur];\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n\tfor(int v:adj[u]){\n\t\tif(vis[v])continue;\n\t\tpar[v] = u;\n\t\tdep[v] = dep[u]+1;\n\t\tdfs(v);\n\t}\n}\n \n \nvoid solve(){\n\tcin >> n >> m;\n\toutputted = 0;\n\tfor(int i = 1;i <= n;i++){\n\t    adj[i].clear();\n\t    all[i].clear();\n\t    vis[i] = 0;\n\t}\n\tpairs = 0;\n\tfor(int i = 1;i <= m;i++){\n\t\tint a,b;cin >> a >> b;\n\t\tadj[a].push_back(b);\n\t\tadj[b].push_back(a);\n\t}\n\tdep[1] = 1;\n\tdfs(1);\n\tif(outputted)return;\n\tcout << \"PAIRING\" << \"\\n\";\n\tcout << pairs << \"\\n\";\n\tfor(int i = 1;i < (n+1)/2;i++){\n\t\tfor(int j = 0;j+1 < all[i].size();j+=2){\n\t\t\tcout << all[i][j] << \" \" << all[i][j+1] << \"\\n\";\n\t\t}\n\t}\n}\n \nint main(){\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tint t;cin >> t;\n\twhile(t--){\n\t    solve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1392",
    "index": "A",
    "title": "Omkar and Password",
    "statement": "Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!\n\nA password is an array $a$ of $n$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index $i$ such that $1 \\leq i < n$ and $a_{i} \\neq a_{i+1}$, delete both $a_i$ and $a_{i+1}$ from the array and put $a_{i}+a_{i+1}$ in their place.\n\nFor example, for array $[7, 4, 3, 7]$ you can choose $i = 2$ and the array will become $[7, 4+3, 7] = [7, 7, 7]$. Note that in this array you can't apply this operation anymore.\n\nNotice that one operation will decrease the size of the password by $1$. What is the shortest possible length of the password after some number (possibly $0$) of operations?",
    "tutorial": "If your array consists of one number repeated $n$ times, then you obviously can't do any moves to shorten the password. Otherwise, you can show that it is always possible to shorten the password to $1$ number. For an array consisting of $2$ or more distinct elements, considering the maximum value of the array. If its max value appears once, you can just repeat operations on the maximum array value until you are left with one number. What if the maximum elements appears more than once? Well, because there must exist at least $2$ distinct numbers, you can always pick a maximum element adjacent to a different number to perform an operation on. The array will then have one occurrence of a maximum and you can simply repeat using aforementioned logic.",
    "code": "#include <bits/stdc++.h>\n#define len(v) ((int)((v).size()))\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n#define chmax(x, v) x = max((x), (v))\n#define chmin(x, v) x = min((x), (v))\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n\tint n; cin >> n;\n\tvector<int> vec(n);\n\tfor (int i = 0; i < n; ++i) {\n\t\tcin >> vec[i];\n\t}\n\tsort(all(vec));\n\tif (vec.front() == vec.back()) cout << n << \"\\n\";\n\telse cout << \"1\\n\";\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint nbTests;\n\tcin >> nbTests;\n\tfor (int iTest = 0; iTest < nbTests; ++iTest) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1392",
    "index": "B",
    "title": "Omkar and Infinity Clock",
    "statement": "Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:\n\nYou are given an array $a$ of $n$ integers. You are also given an integer $k$. Lord Omkar wants you to do $k$ operations with this array.\n\nDefine one operation as the following:\n\n- Set $d$ to be the maximum value of your array.\n- For every $i$ from $1$ to $n$, replace $a_{i}$ with $d-a_{i}$.\n\nThe goal is to predict the contents in the array after $k$ operations. Please help Ray determine what the final sequence will look like!",
    "tutorial": "There's only two possible states the array can end up as. Which state it becomes after $k$ turns is determined solely by the parity of $k$. After the first move, the array will consists of all non-negative numbers ($d-a_{i}$ will never be negative because $a_{i}$ never exceeds $d$). After one turn, let's define $x$ as max($a_{i}$) over all $i$. For any number $a_{i}$, it will turn into $x-a_{i}$. Because a zero will always exist after any one operation, $x$ will be the maximum of the array in the next turn as well. Then the value at index $i$ will turn into $x-(x-a_{i})$. This is just equal to $a_{i}$! Now that it's obvious that our array will enter a cycle with a period of $2$, we simply do the following: If $k$ is odd, perform $1$ operation. Otherwise perform $2$ operations.",
    "code": "#include <iostream>\n#include <vector>\n#include <chrono>\n#include <random>\n#include <cassert>\n\nstd::mt19937 rng((int) std::chrono::steady_clock::now().time_since_epoch().count());\n\nint main() {\n\tstd::ios_base::sync_with_stdio(false); std::cin.tie(NULL);\n\tint t;\n\tstd::cin >> t;\n\twhile(t--) {\n\t\tint n;\n\t\tlong long k;\n\t\tstd::cin >> n >> k;\n\t\tstd::vector<int> a(n);\n\t\tfor(int i = 0; i < n; i++) {\n\t\t\tstd::cin >> a[i];\n\t\t}\n\t\tif(k > 1) {\n\t\t\tk = 2 + k % 2;\n\t\t}\n\t\twhile(k--) {\n\t\t\tint mx = -1000000000;\n\t\t\tfor(int i = 0; i < n; i++) {\n\t\t\t\tmx = std::max(mx, a[i]);\n\t\t\t}\n\t\t\tfor(int i = 0; i < n; i++) {\n\t\t\t\ta[i] = mx - a[i];\n\t\t\t}\n\t\t}\n\t\tfor(int i = 0; i < n; i++) {\n\t\t\tstd::cout << a[i] << (i + 1 == n ? '\\n' : ' ');\n\t\t}\n\t}\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1392",
    "index": "C",
    "title": "Omkar and Waterslide",
    "statement": "Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.\n\nOmkar currently has $n$ supports arranged in a line, the $i$-th of which has height $a_i$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $1$ operation, Omkar can do the following: take any \\textbf{contiguous subsegment} of supports which is \\textbf{nondecreasing by heights} and add $1$ to each of their heights.\n\nHelp Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!\n\nAn array $b$ is a subsegment of an array $c$ if $b$ can be obtained from $c$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.\n\nAn array $b_1, b_2, \\dots, b_n$ is called nondecreasing if $b_i\\le b_{i+1}$ for every $i$ from $1$ to $n-1$.",
    "tutorial": "Call the initial array $a$. We claim that the answer is $\\sum max(a_i-a_{i+1}, 0)$ over the entire array of supports (call this value $ans$). Now let's show why. First, notice that in a nondecreasing array, $ans = 0$. So, the problem is now to apply operations to the array such that $ans = 0$. Now, let's see how applying one operation affects $ans$. Perform an operation on an arbitrary nondecreasing subarray that begins at index $i$ and ends at index $j$. Note that the differences of elements within the subarray stay the same, so the only two pairs of elements which affect the sum are $a_{i-1}, a_i$ and $a_j, a_{j+1}$. Let's initially look at the pair $a_{i-1}, a_i$. If $a_{i-1} \\leq a_i$ (or if $i = 1$), applying an operation would not change $ans$. But, if $a_{i-1} /gt a_i$, applying an operation would decrease $ans$ by $1$. Now let's look at the pair $a_j, a_{j+1}$. If $a_j \\leq a_{j+1}$ (or if $j = n$), applying an operation would not change $ans$. But, if $a_j \\gt a_{j+1}$, applying an operation would increase $ans$ by $1$. We have now shown that we can decrease $ans$ by at most $1$ with each operation, showing that it is impossible to make his supports able to hold the waterslide in fewer than $\\sum max(a_i-a_{i+1}, 0)$ over the initial array. Now, let's construct a solution that applies exactly $\\sum max(a_i-a_{i+1}, 0)$ operations to make the array valid. Consider applying operations to each suffix of length $j$ until the suffix of length $j+1$ is nondecreasing. Since operations are applied iff $a_{n-j+1} \\lt a_{n-j}$, and each operation decreases $a_{n-j+1} \\lt a_{n-j}$ by $1$, the total number of operations would just be the sum of $max(0, a_{n-j}-a_{n-j+1})$, which is equal to $\\sum max(a_i-a_{i+1}, 0)$ over the entire array.",
    "code": "#include <iostream>\n#include <vector>\n#include <chrono>\n#include <random>\n#include <cassert>\n\nstd::mt19937 rng((int) std::chrono::steady_clock::now().time_since_epoch().count());\n\nint main() {\n\tstd::ios_base::sync_with_stdio(false); std::cin.tie(NULL);\n\tint t;\n\tstd::cin >> t;\n\twhile(t--) {\n\t\tint n;\n\t\tstd::cin >> n;\n\t\tlong long last = 0;\n\t\tlong long ans = 0;\n\t\twhile(n--) {\n\t\t\tlong long x;\n\t\t\tstd::cin >> x;\n\t\t\tx += ans;\n\t\t\tif(x >= last) {\n\t\t\t\tlast = x;\n\t\t\t} else {\n\t\t\t\tans += last &mdash; x;\n\t\t\t}\n\t\t}\n\t\tstd::cout << ans << '\\n';\n\t}\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1392",
    "index": "D",
    "title": "Omkar and Bed Wars",
    "statement": "Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $n$ players arranged in a circle, so that for all $j$ such that $2 \\leq j \\leq n$, player $j - 1$ is to the left of the player $j$, and player $j$ is to the right of player $j - 1$. Additionally, player $n$ is to the left of player $1$, and player $1$ is to the right of player $n$.\n\nCurrently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $0$, $1$, or $2$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $1$ other player, then they should logically attack that player in response. If instead a player is being attacked by $0$ or $2$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.\n\nUnfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $n$ players in the game to make them instead attack another player  — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left.\n\nOmkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.",
    "tutorial": "As described in the statement, the only situation in which a player is not acting logically according to Bed Wars strategy is when they are being attacked by exactly $1$ player, but they are not attacking that player in response. Let the player acting illogically be player $j$. There are two cases in which player $j$ is acting illogically: The first case is that player $j$ is being attacked by the player to their left, player $j - 1$, and not by the player to their right, player $j + 1$. This means that $s_{j - 1} =$ R, as they are attacking player $j$ who is to their right, and $s_{j + 1} =$ R, as they are attacking the player to the right instead of player $j$ who is to their left. Furthermore, since player $j$ is not being logical, instead of attacking player $j - 1$, they are attacking player $j + 1$, so $s_j =$ R. This means that in this case $s_{j - 1} = s_j = s_{j + 1} =$ R, i. e. R occurs $3$ times in a row somewhere in $s$. We want to avoid this case, so the final string (after Omkar has convinced some player to change) cannot have $3$ Rs in a row. The second case is that player $j$ is being attacked by the player to their right, player $j + 1$, and not by the player to their left, player $j - 1$. It is easy to see that this case is essentially the same as the first case, but reversed, meaning that the final string also cannot have $3$ Ls in a row. Combining these two cases, the condition in the statement reduces to the simple condition that the same character cannot occur $3$ times in a row in our final string. If we have some subsegment of length $l$ of the same character in $s$, and this subsegment is maximal, so that the characters preceding and following it in $s$ are different from the characters in it, then we can make all players in this subsegment logical by having Omkar talk to $\\lfloor \\frac l 3 \\rfloor$ of the players in that subsegment. Therefore, assuming that not all characters in $s$ are the same, we simply find the lengths of all maximal subsegments of the same characters in $s$ (noting that we need to wrap around if $s_1 = s_n$), and sum over their lengths divided (rounding down) by $3$. Finding these lengths and summing over their quotients can be done easily by looping through $s$ in $O(n)$. If all the characters in $s$ are the same, then we can see similarly that Omkar needs to talk to $\\lceil \\frac n 3 \\rceil$ of the players. (Note that we are rounding up instead of down - this is due to the circular nature of $s$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n    int n, ans = 0;\n    cin >> n;\n    string s;\n    cin >> s;\n    int cnt = 0;\n    while(s.size() && s[0] == s.back()) {\n        cnt++;\n        s.pop_back();\n    }\n    if(s.empty()) {\n        if(cnt <= 2) {\n            cout << \"0\\n\";\n            return;\n        }\n        if(cnt == 3) {\n            cout << \"1\\n\";\n            return;\n        }\n        cout << (cnt + 2) / 3 << '\\n';\n        return;\n    }\n    s.push_back('$');\n    for(int i = 0; i + 1 < s.size(); i++) {\n        cnt++;\n        if(s[i] != s[i + 1]) {\n            ans += cnt / 3;\n            cnt = 0;\n        }\n    }\n    cout << ans << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int t;\n    cin >> t;\n    while(t--)\n        solve();\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1392",
    "index": "E",
    "title": "Omkar and Duck",
    "statement": "\\textbf{This is an interactive problem.}\n\nOmkar has just come across a duck! The duck is walking on a grid with $n$ rows and $n$ columns ($2 \\leq n \\leq 25$) so that the grid contains a total of $n^2$ cells. Let's denote by $(x, y)$ the cell in the $x$-th row from the top and the $y$-th column from the left. Right now, the duck is at the cell $(1, 1)$ (the cell in the top left corner) and would like to reach the cell $(n, n)$ (the cell in the bottom right corner) by moving either down $1$ cell or to the right $1$ cell each second.\n\nSince Omkar thinks ducks are fun, he wants to play a game with you based on the movement of the duck. First, for each cell $(x, y)$ in the grid, you will tell Omkar a nonnegative integer $a_{x,y}$ not exceeding $10^{16}$, and Omkar will then put $a_{x,y}$ uninteresting problems in the cell $(x, y)$. After that, the duck will start their journey from $(1, 1)$ to $(n, n)$. For each cell $(x, y)$ that the duck crosses during their journey (including the cells $(1, 1)$ and $(n, n)$), the duck will eat the $a_{x,y}$ uninteresting problems in that cell. Once the duck has completed their journey, Omkar will measure their mass to determine the total number $k$ of uninteresting problems that the duck ate on their journey, and then tell you $k$.\n\nYour challenge, given $k$, is to exactly reproduce the duck's path, i. e. to tell Omkar precisely which cells the duck crossed on their journey. To be sure of your mastery of this game, Omkar will have the duck complete $q$ different journeys ($1 \\leq q \\leq 10^3$). Note that all journeys are independent: at the beginning of each journey, the cell $(x, y)$ will still contain $a_{x,y}$ uninteresting tasks.",
    "tutorial": "The problem essentially boils down to constructing a grid such that any path from $(1, 1)$ to $(n, n)$ has a different sum and you can easily determine any path from its sum. You can do this using the following construction: for all $(x, y)$, if $x$ is even, then let $a_{x,y} = 2^{x + y}$; otherwise, let $a_{x,y} = 0$. The construction is illustrated below for $n = 8$: $\\begin{matrix} 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 2^{3} & 2^{4} & 2^{5} & 2^{6} & 2^{7} & 2^{8} & 2^{9} & 2^{10} \\\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 2^{5} & 2^{6} & 2^{7} & 2^{8} & 2^{9} & 2^{10} & 2^{11} & 2^{12} \\\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 2^{7} & 2^{8} & 2^{9} & 2^{10} & 2^{11} & 2^{12} & 2^{13} & 2^{14} \\\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\ 2^{9} & 2^{10} & 2^{11} & 2^{12} & 2^{13} & 2^{14} & 2^{15} & 2^{16} \\\\ \\end{matrix}$ You can see that this construction works using the following observations: The maximum value of $n$ is $25$, and $2^{2 \\cdot 25} = 2^{50} < 10^{16}$. For any integer $j$ between $2$ and $2n$ (inclusive), all paths cross exactly one cell $(x, y)$ such that $x + y = j$. For any cell $(x, y)$, you can move to either one or two cells, and if you can move to two cells, then exactly one of those will have $x'$ even and exactly one of those will have $x'$ odd, as the cells will necessarily be $(x + 1, y)$ and $(x, y + 1)$ which have different parities of $x'$. This means that the sum on any path will be the sum of distinct powers of $2$ between $2^2$ and $2^{2n}$ (inclusive), meaning that given that we know which cell $(x, y)$ the path crossed satisfying $x + y = j$, we can determine which cell $(x', y')$ the path crossed satisfying $x' + y' = j + 1$ by checking whether the path sum contains $2^{j + 1}$ and then appropriately selecting either $(x', y') = (x + 1, y)$ or $(x', y') = (x, y + 1)$. We know that the path must start at $(1, 1)$ so we can therefore easily determine the rest of the path given the sum.",
    "code": "#include <bits/stdc++.h>\n#define len(v) ((int)((v).size()))\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n#define chmax(x, v) x = max((x), (v))\n#define chmin(x, v) x = min((x), (v))\nusing namespace std;\nusing ll = long long;\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0);\n\tint side; cin >> side;\n\tvector<vector<ll>> grid(side, vector<ll>(side, 0));\n\tfor (int i = 0; i < side; ++i) {\n\t\tfor (int j = 0; j < side; ++j) {\n\t\t\tif ((i-j+side)&2LL) grid[i][j] = (1LL << (i+j));\n\t\t\tcout << grid[i][j] << \" \\n\"[j==side-1];\n\t\t}\n\t}\n\tcout << flush;\n\tint nbQuery; cin >> nbQuery;\n\tfor (int iQuery = 0; iQuery < nbQuery; ++iQuery) {\n\t\tll sum; cin >> sum;\n\t\tcout << \"1 1\";\n\t\tint row = 0, col = 0;\n\t\tfor (int diag = 0; diag < 2*side-2; ++diag) {\n\t\t\tll should = sum&(1LL<<(diag+1));\n\t\t\tif (row+1<side && grid[row+1][col] == should) ++row;\n\t\t\telse ++col;\n\t\t\tcout << \" \" << row+1 << \" \" << col+1;\n\t\t}\n\t\tcout << endl << flush;\n\t}\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1392",
    "index": "F",
    "title": "Omkar and Landslide",
    "statement": "Omkar is standing at the foot of Celeste mountain. The summit is $n$ meters away from him, and he can see all of the mountains up to the summit, so for all $1 \\leq j \\leq n$ he knows that the height of the mountain at the point $j$ meters away from himself is $h_j$ meters. It turns out that for all $j$ satisfying $1 \\leq j \\leq n - 1$, $h_j < h_{j + 1}$ (meaning that heights are strictly increasing).\n\nSuddenly, a landslide occurs! While the landslide is occurring, the following occurs: every minute, if $h_j + 2 \\leq h_{j + 1}$, then one square meter of dirt will slide from position $j + 1$ to position $j$, so that $h_{j + 1}$ is decreased by $1$ and $h_j$ is increased by $1$. These changes occur simultaneously, so for example, if $h_j + 2 \\leq h_{j + 1}$ and $h_{j + 1} + 2 \\leq h_{j + 2}$ for some $j$, then $h_j$ will be increased by $1$, $h_{j + 2}$ will be decreased by $1$, and $h_{j + 1}$ will be both increased and decreased by $1$, meaning that in effect $h_{j + 1}$ is unchanged during that minute.\n\nThe landslide ends when there is no $j$ such that $h_j + 2 \\leq h_{j + 1}$. Help Omkar figure out what the values of $h_1, \\dots, h_n$ will be after the landslide ends. It can be proven that under the given constraints, the landslide will always end in finitely many minutes.\n\nNote that because of the large amount of input, it is recommended that your code uses fast IO.",
    "tutorial": "Fun fact: This problem was originally proposed as B. TL;DR: We can show that in the resulting array, every pair of adjacent elements differs by exactly $1$ except that there may be at most one pair of adjacent equal elements. It is easy to see that there is only one such array satisfying that condition that also has the same length and sum as the given array, so we simply calculate that array based on the sum of the given array. Proof: Clearly, the order in which we perform the slides (transfers of one square meter of dirt from $a_{j + 1}$ to $a_j$ for some $j$) does not matter. Consider then performing slides in the following manner: whenever we perform a slide from $a_j$ to $a_{j - 1}$, after that slide, if it is possible to perform a slide from $a_{j - 1}$ to $a_{j - 2}$, we will do so, and then from $a_{j - 2}$ to $a_{j - 3}$ and so on. We will call this action \"performing a sequence of slides from $a_j$\". Assume that we have just performed a sequence of slides from $a_j$. We can see that if there was a pair of adjacent elements to the left of $a_j$ that were equal, i. e. some $k < j$ such that $a_{k - 1} = a_k$, then, assuming that $a_{k -1}, a_k$ is the rightmost such pair, then the sequence of slides that we started will end with $a_k$ being increased. In this case, $a_{k - 1}$ and $a_k$ are no longer equal, but $a_k, a_{k + 1}$ may now be equal, so the amount of pairs of adjacent equal elements to the left of $a_j$ has either decreased or stayed the same. On the other hand, if there was no such pair, then the sequence of slides would end with $a_1$ being increased, meaning it might now be true that $a_1$ and $a_2$ are equal, so that the amount of pairs of adjacent equal elements to the left of $a_j$ is either still $0$ or now $1$. Combining these two facts, we see that if there were either $0$ or $1$ pairs of adjacent equal elements to the left of $a_j$ to start with, then there will only be either $0$ or $1$ pairs of adjacent equal elements to the left of $a_j$ after performing a sequence of slides from $a_j$. Noting that as our array is initially strictly increasing, there are initially no pairs of adjacent equal elements, we can simply first perform as many sequences of slides from $a_2$ as possible, then perform as many sequences of slides from $a_3$ as possible, and so on, until we perform as many sequences of slides from $a_n$ as possible. When we are performing sequences of slides from $a_j$, there can clearly only be either $0$ or $1$ pairs of adjacent equal elements to the left of $a_j$, and there can't be any such pairs to the right of $a_j$ as that part of the array hasn't been touched yet and is therefore still strictly increasing. Therefore, we can conclude that once all possible slides have been performed, the entire array will contain at most $1$ pair of adjacent equal elements. Since it cannot be possible to perform any more slides once all possible slides have been performed, all pairs of adjacent elements that are not equal must differ by at most $1$. It is easy to see that there is only one array satisfying these conditions that has the same length $n$ and sum $S = \\sum_{j = 1}^n a_j$. You can construct this array by starting with the array $0, 1, 2, \\dots, n - 1$, then adding $1$ to each element from left to right, looping back to the beginning when you reach the end, until the sum of the array is $S$. From this construction we can derive the following formula for the array: $a_j = j - 1 + \\lfloor \\frac {S - \\frac {n(n - 1)} 2} n \\rfloor + \\{j \\leq (S - \\frac {n(n - 1)} 2) \\% n\\}$ where $\\{C\\}$ is $1$ if the condition $C$ is satisfied, and $0$ otherwise. EDIT: The fact that the order of operations doesn't matter turned out to be harder to prove than I thought (thanks to the comments for pointing this out), so I decided to add the following proof: If you have two sequences of maximal operations, then what we want to show is that they have to consist of the same operations (possibly in different orders). Since they are both maximal, they must either both be empty or both be nonempty. If they are both empty then we are done. If they are both nonempty: consider the current state of the vector (before applying either sequence of operations). Since the sequences are nonempty, there is at least one operation $\\alpha$ that can be immediately applied on the vector. Here we should make the observation that applying an operation at some index cannot prevent operations at other indexes from being able to be applied (it can only allow other operations to be applied). Therefore, applying other (different) operations cannot prevent operation $\\alpha$ from being able to be applied, so operation $\\alpha$ must occur in both sequences. From our observation, we can see that if, in either sequence, operation $\\alpha$ does not occur initially, then operation $\\alpha$ can be applied initially because by performing it earlier we are not preventing any of the operations in between from being applied. Thus, the first operation of each sequence is now the same, so we can apply the same argument to the remainder of the sequence (since it must be finite).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main()\n{\n\tios_base::sync_with_stdio(0), cin.tie(0);\n\tll n;\n\tcin >> n;\n\tll s = 0;\n\tfor (ll x, i = 0; i < n; ++i)\n\t\tcin >> x, s += x;\n\n\tll l = (s - n * (n-1) / 2) / n + 1;\n\ts = l * n + n * (n-1) / 2 - s;\n\tfor (int i = 0; i < n; ++i)\n\t\tcout << l + i - (n-i <= s) << \" \\n\"[i+1==n];\n\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1392",
    "index": "G",
    "title": "Omkar and Pies",
    "statement": "Omkar has a pie tray with $k$ ($2 \\leq k \\leq 20$) spots. Each spot in the tray contains either a chocolate pie or a pumpkin pie. However, Omkar does not like the way that the pies are currently arranged, and has another ideal arrangement that he would prefer instead.\n\nTo assist Omkar, $n$ elves have gathered in a line to swap the pies in Omkar's tray. The $j$-th elf from the left is able to swap the pies at positions $a_j$ and $b_j$ in the tray.\n\nIn order to get as close to his ideal arrangement as possible, Omkar may choose a contiguous subsegment of the elves and then pass his pie tray through the subsegment starting from the left. However, since the elves have gone to so much effort to gather in a line, they request that Omkar's chosen segment contain at least $m$ ($1 \\leq m \\leq n$) elves.\n\nFormally, Omkar may choose two integers $l$ and $r$ satisfying $1 \\leq l \\leq r \\leq n$ and $r - l + 1 \\geq m$ so that first the pies in positions $a_l$ and $b_l$ will be swapped, then the pies in positions $a_{l + 1}$ and $b_{l + 1}$ will be swapped, etc. until finally the pies in positions $a_r$ and $b_r$ are swapped.\n\nHelp Omkar choose a segment of elves such that the amount of positions in Omkar's final arrangement that contain the same type of pie as in his ideal arrangement is the maximum possible. \\textbf{Note that since Omkar has a big imagination, it might be that the amounts of each type of pie in his original arrangement and in his ideal arrangement do not match}.",
    "tutorial": "Consider any two binary strings $u$ and $v$ of length $k$. Notice that if you swap the bits at positions $\\alpha$ and $\\beta$ in $u$ and also swap the bits at positions $\\alpha$ and $\\beta$ in $v$, then the amount of common bits in $u$ and $v$ remains the same. Furthermore, you can do this multiple times - i. e. applying the same sequence of swaps to $u$ and $v$ doesn't change their amount of common bits. Let's apply this to the problem at hand. Assume that Omkar has selected the subsegment of elves between some $l$ and $r$. Let $s$ be Omkar's original binary string, let $s'$ be $s$ after applying the subsegment of swaps between $l$ and $r$ (inclusive) to it, and let $t$ be Omkar's ideal binary string. Now consider applying all the swaps in the subsegment from $1$ to $r$ (inclusive) to both $s$ and $t$, but in reverse - first we apply the $r$-th swap, then the $r - 1$-th swap, and so on, until we finally apply the $1$-st swap. From our first observation, these new strings $s^{\\prime\\prime}$ and $t^{\\prime\\prime}$ have the same amount of common bits as $s'$ and $t$. We additionally notice that just as $t^{\\prime\\prime}$ is $t$ with the subsegment of swaps from $1$ to $r$ applied in reverse, $s^{\\prime\\prime}$ is actually $s$ with the subsegment of swaps from $1$ to $l - 1$ applied in reverse, as the subsegment of swaps from $l$ to $r$ that were applied to $s$ to create $s'$ has been undone. Let us then define some more strings as follows: for all $j$ such that ($0 \\leq j \\leq n$), let $s_j$ be the result of applying the subsegment of swaps from $1$ to $j$ in reverse to $s$, and let $t_j$ be the result of applying the subsegment of swaps from $1$ to $j$ in reverse to $s$ (so $s_0 = s$ and $t_0 = t$). We now see that the amount of common bits that result from choosing a subsegment of swaps between $l$ and $r$ is equivalent to the amount of common bits between $s_{l - 1}$ and $t_r$, and so the problem is now simply to find two indices $j_1$ and $j_2$ such that $j_2 - j_1 \\geq m$ and the amount of common bits between $s_{j_1}$ and $t_{j_2}$ is the maximum possible. Here we make another observation: if $\\omega$ is the amount of common bits between two binary strings $u$ and $v$ of length $k$, $\\epsilon$ is the amount of bits set to $1$ in $u$, $\\zeta$ is the amount of bits set to $1$ in $v$, and $\\lambda$ is the amount of common bits set to $1$ in $u$ and $v$, then $\\omega = 2\\lambda + k - \\epsilon - \\zeta$. Since we are only comparing strings derived from performing swaps on $s$ to strings derived from performing swaps on $t$, and swaps don't change the overall amount of $1$ bits in a string, $\\epsilon$ and $\\zeta$, like $k$, are constants - $\\epsilon$ is the amount of $1$ bits in $s$, and $\\zeta$ is the amount of $1$ bits in $t$. This means that maximizing $\\omega$, the amount of common bits in $u$ and $v$, is equivalent to maximizing $\\lambda$, the amount of common $1$ bits in $u$ and $v$. Therefore, we can now proceed with bitmask DP to finish the problem. For a binary string $\\mu$ of length $k$, let $left_\\mu$ be the smallest index $j$ such that $\\mu$ is a subset of $s_j$ considering $1$ bits, and let $right_\\mu$ be the largest index $j$ such that $\\mu$ is a subset of $t_j$ considering $1$ bits. These DP values are straightforward to compute, and we can obtain our answer by choosing the subsegment of swaps from $left_\\mu$ to $right_\\mu$ for any $\\mu$ with the largest amount of $1$ bits such that $left_\\mu$ and $right_\\mu$ both exist and $right_\\mu - left_\\mu \\geq m$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint p[20],dp[2][(1<<20)];\nint getmask(string s)\n{\n\tint ans=0;\n\tfor (int i=0;i<s.size();i++)\n\tans|=((s[i]-'0')<<i);\n\treturn ans;\n}\nint main()\n{\n\tint n,m,k;\n\tscanf(\"%d%d%d\",&n,&m,&k);\n\tstring a,b;\n\tcin >> a >> b;\n\tfor (int i=0;i<k;i++)\n\tp[i]=i;\n\tfor (int i=0;i<(1<<k);i++)\n\t{\n\t\tdp[0][i]=1e9;\n\t\tdp[1][i]=-1e9;\n\t}\n\tdp[0][getmask(a)]=0;\n\tdp[1][getmask(b)]=0;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tint x,y;\n\t\tscanf(\"%d%d\",&x,&y);\n\t\tx--;\n\t\ty--;\n\t\tswap(p[x],p[y]);\n\t\tstring aa(k,'0'),bb(k,'0');\n\t\tfor (int j=0;j<k;j++)\n\t\t{\n\t\t\taa[p[j]]=a[j];\n\t\t\tbb[p[j]]=b[j];\n\t\t}\n\t\tdp[0][getmask(aa)]=min(dp[0][getmask(aa)],i);\n\t\tdp[1][getmask(bb)]=i;\n\t}\n\tint o1=count(a.begin(),a.end(),'1'),o2=count(b.begin(),b.end(),'1');\n\tpair<int,pair<int,int> > ans(0,{0,0});\n\tfor (int i=(1<<k)-1;i>=0;i--)\n\t{\n\t\tif (dp[1][i]-dp[0][i]>=m)\n\t\tans=max(ans,make_pair(k-(o1+o2-2*__builtin_popcount(i)),make_pair(dp[0][i]+1,dp[1][i])));\n\t\tfor (int j=0;j<k;j++)\n\t\t{\n\t\t\tif (i&(1<<j))\n\t\t\t{\n\t\t\t\tdp[0][i^(1<<j)]=min(dp[0][i^(1<<j)],dp[0][i]);\n\t\t\t\tdp[1][i^(1<<j)]=max(dp[1][i^(1<<j)],dp[1][i]);\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"%d\\n%d %d\",ans.first,ans.second.first,ans.second.second);\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "math",
      "shortest paths"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1392",
    "index": "H",
    "title": "ZS Shuffles Cards",
    "statement": "zscoder has a deck of $n+m$ custom-made cards, which consists of $n$ cards labelled from $1$ to $n$ and $m$ jokers. Since zscoder is lonely, he wants to play a game with himself using those cards.\n\nInitially, the deck is shuffled uniformly randomly and placed on the table. zscoder has a set $S$ which is initially empty.\n\nEvery second, zscoder draws the top card from the deck.\n\n- If the card has a number $x$ written on it, zscoder removes the card and adds $x$ to the set $S$.\n- If the card drawn is a joker, zscoder places all the cards back into the deck and reshuffles (uniformly randomly) the $n+m$ cards to form a new deck (hence the new deck now contains all cards from $1$ to $n$ and the $m$ jokers). Then, if $S$ currently contains all the elements from $1$ to $n$, the game ends. Shuffling the deck doesn't take time at all.\n\nWhat is the expected number of seconds before the game ends? We can show that the answer can be written in the form $\\frac{P}{Q}$ where $P, Q$ are relatively prime integers and $Q \\neq 0 \\bmod 998244353$. Output the value of $(P \\cdot Q^{-1})$ modulo $998244353$.",
    "tutorial": "Firstly, let's find a simple dp. Let $f(x)$ denote the expected time before the game ends with the deck is full (with $n+m$ cards) and $S$ contains $n - x$ elements. Hence, $f(0)=0$. Our goal is to find $f(n)$. Suppose the jokers are also numbered from $1$ to $m$ and $S$ contains $n-x$ elements. Consider the cards drawn before we draw our first joker (which causes the deck to be reshuffled). Suppose we draw $i$ cards with a number, $l$ of which is a number not in $S$, before drawing our first joker. There are $\\binom{x}{l} \\cdot \\binom{n-x}{i-l} \\cdot i!$ ways to choose and permute the first $i$ cards, $m$ ways to choose the first joker and $(n+m-i-1)!$ ways to permute the cards that were not drawn. The total time taken is $i+1+f(x-l)$. Hence, $f(x) = \\displaystyle\\sum_{l=0}^{x}\\displaystyle\\sum_{i=0}^{n}\\binom{x}{l}\\binom{n-x}{i-l} \\cdot i! \\cdot m \\cdot \\frac{(n+m-i-1)!}{(n+m)!} \\cdot (f(x-l)+i+1).$ This gives us an easy $O(n^{3})$ solution. Note that $f(x)$ is also on the right hand side, so you need to move the corresponding term to the left first before computing (this is not difficult). To optimize our solution, we just need to manipulate the sums. I will show how to simplify $\\displaystyle\\sum_{l=0}^{x}\\displaystyle\\sum_{i=0}^{n}\\binom{x}{l}\\binom{n-x}{i-l} \\cdot i! \\cdot m \\cdot \\frac{(n+m-i-1)!}{(n+m)!} \\cdot (i+1)$. The way to simplify $\\displaystyle\\sum_{l=0}^{x}\\displaystyle\\sum_{i=0}^{n}\\binom{x}{l}\\binom{n-x}{i-l} \\cdot i! \\cdot m \\cdot \\frac{(n+m-i-1)!}{(n+m)!} \\cdot f(x-l)$ is analogous. We have $\\displaystyle\\sum_{l=0}^{x}\\displaystyle\\sum_{i=0}^{n}\\binom{x}{l}\\binom{n-x}{i-l} \\cdot i! \\cdot m \\cdot \\frac{(n+m-i-1)!}{(n+m)!} \\cdot (i+1)$ $= \\frac{m \\cdot x! \\cdot (n-x)!}{(n+m)!} \\cdot \\displaystyle\\sum_{l=0}^{x}\\frac{1}{l!(x-l)!} \\displaystyle \\sum_{i=0}^{n}\\frac{(i+1)! \\cdot (n+m-i-1)!}{(i-l)! \\cdot (n-x-i+l)!}$ (expanding and regrouping) $= \\frac{m \\cdot x! \\cdot (n-x)!}{(n+m)!} \\cdot \\displaystyle\\sum_{l=0}^{x}\\frac{(m-1+x-l)!(l+1)}{(x-l)!} \\displaystyle \\sum_{i=0}^{n}\\frac{(i+1)!}{(l+1)!(i-l)!} \\cdot \\frac{(n+m-i-1)!}{(n-x-i+l)!(m-1+x-l)!}$ (making binomial coefficients appear) $= \\frac{m \\cdot x! \\cdot (n-x)!}{(n+m)!} \\cdot \\displaystyle\\sum_{l=0}^{x}\\frac{(m-1+x-l)!(l+1)}{(x-l)!} \\displaystyle \\sum_{i=0}^{n}\\binom{i+1}{l+1}\\binom{n+m-i-1}{m-1+x-l}$ Recall that $\\displaystyle\\sum_{i}\\binom{i}{a}\\binom{n-i}{b-a} = \\binom{n+1}{b+1}$, because we can count the right hand side by fixing the position of the $(a+1)$-th element, where $i$ denotes the number of elements on the left of the $(a+1)$-th element. Hence, $= \\frac{m \\cdot x! \\cdot (n-x)!}{(n+m)!} \\cdot \\displaystyle\\sum_{l=0}^{x}\\frac{(m-1+x-l)!(l+1)}{(x-l)!} \\cdot \\binom{n+m+1}{m+x+1}$ $= \\frac{m \\cdot x! \\cdot (n-x)!}{(n+m)!} \\cdot \\binom{n+m+1}{m+x+1} \\cdot \\displaystyle\\sum_{l=0}^{x}\\frac{(m-1+x-l)!}{(x-l)!} \\cdot (l+1)$ $= \\frac{m \\cdot x! \\cdot (n-x)!}{(n+m)!} \\cdot \\binom{n+m+1}{m+x+1} \\cdot \\displaystyle\\sum_{l=0}^{x}\\frac{(m-1+l)!}{l!} \\cdot (x-l+1)$. We can compute the latter sum in $O(1)$ via prefix sums (after splitting $x+1$ and $-l$). A similar computation can be done for $\\displaystyle\\sum_{l=0}^{x}\\displaystyle\\sum_{i=0}^{n}\\binom{x}{l}\\binom{n-x}{i-l} \\cdot i! \\cdot m \\cdot \\frac{(n+m-i-1)!}{(n+m)!} \\cdot f(x-l)$. Hence, $f(x)$ can be computed in $O(1)$ (with prefix sums) for $x=1$ to $n$. This gives a $O(n+m)$ time solution if you precompute factorials.",
    "code": "const val MOD = 998244353L\n\nfun main() {\n    val (n, m) = readLine()!!.split(\" \").map { it.toInt() }\n    val factorial = LongArray(4000002)\n    factorial[0] = 1L\n    for (j in 1..4000001) {\n        factorial[j] = (j.toLong() * factorial[j - 1]) % MOD\n    }\n    val factInv = LongArray(4000002)\n    factInv[4000001] = factorial[4000001] pow -1\n    for (j in 4000000 downTo 0) {\n        factInv[j] = ((j + 1).toLong() * factInv[j + 1]) % MOD\n    }\n    fun choose(a: Int, b: Int) = if (a < 0 || b < 0 || b > a) 0L else (factorial[a] * ((factInv[b] * factInv[a - b]) % MOD)) % MOD\n    val answer = LongArray(n + 1)\n    var currSum = 0L\n    for (k in 1..n) {\n        var sum = currSum * choose(n + m, m + k)\n        sum %= MOD\n        sum += factorial[m - 1] * ((choose(m + k + 1, m + 1) * choose(n + m + 1, m + k + 1)) % MOD)\n        sum %= MOD\n        sum *= (factorial[k] * ((factorial[n - k] * ((factInv[n + m] * m.toLong()) % MOD)) % MOD)) % MOD\n        sum %= MOD\n        answer[k] = sum * (((m + k).toLong() * ((factInv[k] * factorial[k - 1]) % MOD)) % MOD)\n        answer[k] %= MOD\n        currSum += factorial[m + k - 1] * ((factInv[k] * answer[k]) % MOD)\n        currSum %= MOD\n    }\n    println(answer[n])\n}\n\nconst val MOD_TOTIENT = MOD.toInt() - 1\n\ninfix fun Long.pow(power: Int): Long {\n    var e = power\n    e %= MOD_TOTIENT\n    if (e < 0) {\n        e += MOD_TOTIENT\n    }\n    if (e == 0 && this == 0L) {\n        return this\n    }\n    var b = this % MOD\n    var res = 1L\n    while (e > 0) {\n        if (e and 1 != 0) {\n            res *= b\n            res %= MOD\n        }\n        b *= b\n        b %= MOD\n        e = e shr 1\n    }\n    return res\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1392",
    "index": "I",
    "title": "Kevin and Grid",
    "statement": "As Kevin is in BigMan's house, suddenly a trap sends him onto a grid with $n$ rows and $m$ columns.\n\nBigMan's trap is configured by two arrays: an array $a_1,a_2,\\ldots,a_n$ and an array $b_1,b_2,\\ldots,b_m$.\n\nIn the $i$-th row there is a heater which heats the row by $a_i$ degrees, and in the $j$-th column there is a heater which heats the column by $b_j$ degrees, so that the temperature of cell $(i,j)$ is $a_i+b_j$.\n\nFortunately, Kevin has a suit with one parameter $x$ and two modes:\n\n- heat resistance. In this mode suit can stand all temperatures greater or equal to $x$, but freezes as soon as reaches a cell with temperature less than $x$.\n- cold resistance. In this mode suit can stand all temperatures less than $x$, but will burn as soon as reaches a cell with temperature at least $x$.\n\nOnce Kevin lands on a cell the suit automatically turns to cold resistance mode if the cell has temperature less than $x$, or to heat resistance mode otherwise, and cannot change after that.\n\nWe say that two cells are adjacent if they share an edge.\n\nLet a path be a sequence $c_1,c_2,\\ldots,c_k$ of cells such that $c_i$ and $c_{i+1}$ are adjacent for $1 \\leq i \\leq k-1$.\n\nWe say that two cells are connected if there is a path between the two cells consisting only of cells that Kevin can step on.\n\nA connected component is a maximal set of pairwise connected cells.\n\nWe say that a connected component is \\textbf{good} if Kevin can escape the grid starting from it  — when it contains at least one border cell of the grid, and that it's \\textbf{bad} otherwise.\n\nTo evaluate the situation, Kevin gives a score of $1$ to each good component and a score of $2$ for each bad component.\n\nThe final score will be the difference between the total score of components with temperatures bigger than or equal to $x$ and the score of components with temperatures smaller than $x$.\n\nThere are $q$ possible values of $x$ that Kevin can use, and for each of them Kevin wants to know the final score.\n\nHelp Kevin defeat BigMan!",
    "tutorial": "An obvious solution would be to do DFS, but it is $O(nmq)$. Firstly we focus on answering a single question. We represent our input with two graphs (one for cells with temperature less than X and other for temperatures greater than X), in which we add an edge between two neigbouring cells. As it is a subgraph of the grid graph, this means that this graph is planar and thus we may apply Euler's formula on both graphs: $V_1+F_1=E_1+C_1$, where V1 is the number of vertices in graph 1, F1 is the number of faces in graph 1, $\\dots$. However, some faces are not interesting, namely the $2 \\times 2$ square of adjacent cells. Let $Q_1$ be the number of such squares. Similarly, $V_2+F_2=E_2+1+C_2$. We see that interesting faces in graph 1 represent connected components in graph 2 that cannot reach the border, and vice-versa. In this way, if we subtract the equations, we get $C_1-F_1+F_2-C_2=V_1-E_1+E_2-V_1+Q_1-Q_2$. We can observe that, because of this interpretation, the LHS of the equation is the answer. We have to devise an algorithm to calculate efficiently the number of squares/edges. Let's calculate horizontal edges, and do the same for vertical edges. Firstly, if $a_i+b_j \\geq X$ and $a_i+b_{j+1} \\geq X$ then $a_i+min(b_j,b_{j+1}) \\geq X$. So we create array $B$ such that $B_j=min(b_j,b_{j+1})$. The number of edges is the number of indexes $i,j$ such that $a_i+B_j \\geq X$. This trick can also be used to calculate edges in cold regions. To have a more efficient solution, we must calculate faster the number of indexes $i,j$ such that $a_i+B_j \\geq X$. We can thus apply fast Fourier transform to arrays representing frequencies of $a$ and $B$ and multiply them, inverting the Fourier transform in order to get the answers quickly in O(1) with prefix sums. By doing this we can calculate the number of edges, and the number of $2 \\times 2$ squares can be calculated in a similar way. The final complexity is, thus, $O((n+m)log(n+m)+max(a_i,b_i)log(max(a_i,b_i)))$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n#define MAX 262144\n#define MAXN 1000000\nlong long int a[MAXN],b[MAXN];\n\n\nusing cd = complex<double>;\nconst double PI = acos(-1);\nvector<cd> A(MAX),B(MAX);\nvector<cd> Amx(MAX),Bmx(MAX);\nvector<cd> Amn(MAX),Bmn(MAX);\nvector<cd> E11(MAX),E12(MAX),E21(MAX),E22(MAX);\nvector<cd> SQ1(MAX),SQ2(MAX);\nvector<cd> V(MAX);\nvector<long long int> A1(MAX),A2(MAX);\n\nvoid fft(vector<cd> & a, bool invert) {\n    int n = a.size();\n\n    for (int i = 1, j = 0; i < n; i++) {\n        int bit = n >> 1;\n        for (; j & bit; bit >>= 1)\n            j ^= bit;\n        j ^= bit;\n\n        if (i < j)\n            swap(a[i], a[j]);\n    }\n\n    for (int len = 2; len <= n; len <<= 1) {\n        double ang = 2 * PI / len * (invert ? -1 : 1);\n        cd wlen(cos(ang), sin(ang));\n        for (int i = 0; i < n; i += len) {\n            cd w(1);\n            for (int j = 0; j < len / 2; j++) {\n                cd u = a[i+j], v = a[i+j+len/2] * w;\n                a[i+j] = u + v;\n                a[i+j+len/2] = u - v;\n                w *= wlen;\n            }\n        }\n    }\n\n    if (invert) {\n        for (cd & x : a)\n            x /= n;\n    }\n}\nvoid prod(vector<cd> &a, vector<cd> &b, vector<cd> &c){\n  for(int i=0;i<a.size();i++){\n    c[i]=a[i]*b[i];\n  }\n}\n\nint main(){\n  long long int n,m,q;\n  scanf(\"%lld %lld %lld\",&n,&m,&q);\n  \n  for(int i=0;i<n;i++){\n    scanf(\"%lld\",&a[i]);\n  }\n  for(int i=0;i<m;i++){\n    scanf(\"%lld\",&b[i]);\n  }\n  for(int i=0;i<MAX;i++){\n    A[i]=cd(0,0);\n    Amn[i]=cd(0,0);\n    Amx[i]=cd(0,0);\n    B[i]=cd(0,0);\n    Bmn[i]=cd(0,0);\n    Bmx[i]=cd(0,0);\n  }\n  for(int i=0;i<n;i++){\n    A[a[i]]+=cd(1,0);\n  }\n  for(int i=0;i<n-1;i++){\n    Amn[min(a[i],a[i+1])]+=cd(1,0);\n  }\n  for(int i=0;i<n-1;i++){\n    Amx[max(a[i],a[i+1])]+=cd(1,0);\n  }\n  for(int i=0;i<m;i++){\n    B[b[i]]+=cd(1,0);\n  }\n  for(int i=0;i<m-1;i++){\n    Bmn[min(b[i],b[i+1])]+=cd(1,0);\n  }\n  for(int i=0;i<m-1;i++){\n    Bmx[max(b[i],b[i+1])]+=cd(1,0);\n  }\n  \n  fft(A,0);\n  fft(Amn,0);\n  fft(Amx,0);\n  fft(B,0);\n  fft(Bmn,0);\n  fft(Bmx,0);\n  prod(A,Bmn,E11);\n  prod(Amn,B,E12);\n  prod(Amx,B,E21);\n  prod(A,Bmx,E22);\n  prod(Amn,Bmn,SQ1);\n  prod(Amx,Bmx,SQ2);\n  prod(A,B,V);\n  fft(E11,1);\n  fft(E12,1);\n  fft(E21,1);\n  fft(E22,1);\n  fft(SQ1,1);\n  fft(SQ2,1);\n  fft(V,1);\n  for(int i=0;i<MAX;i++){\n    A1[i]=round(SQ1[i].real())-round(E11[i].real())-round(E12[i].real())+round(V[i].real());\n    A2[i]=round(SQ2[i].real())-round(E21[i].real())-round(E22[i].real())+round(V[i].real());\n  }\n  for(int i=1;i<MAX;i++){\n    A2[i]+=A2[i-1];\n  }\n  for(int i=MAX-2;i>-1;i--){\n    A1[i]+=A1[i+1];\n  }\n  for(int i=0;i<q;i++){\n    int query;\n    scanf(\"%d\",&query);\n    //cout<<A1[query]<<\" \"<<A2[query-1]<<endl;\n    printf(\"%lld\\n\",A1[query]-A2[query-1]);\n  }\n  return 0;\n}",
    "tags": [
      "fft",
      "graphs",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1393",
    "index": "A",
    "title": "Rainbow Dash, Fluttershy and Chess Coloring",
    "statement": "One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal.\n\nThe game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $1\\times1$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks.\n\nThe blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.\n\nRainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a \\textbf{chess coloring}. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!\n\nSince the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.\n\nThe chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.",
    "tutorial": "By modeling the game on different grids it was possible to notice that the answer is equal to $\\lfloor \\frac{n}{2} \\rfloor + 1$. You can prove that this is the answer by using induction method separately for grids with even and odd sides. Initially it was asked to solve the problem for rectangular grids. You can think about this version of the problem.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t, n;\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        cout << n / 2 + 1 << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1393",
    "index": "B",
    "title": "Applejack and Storages",
    "statement": "This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).\n\nApplejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $n$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format:\n\n- $+$ $x$: the storehouse received a plank with length $x$\n- $-$ $x$: one plank with length $x$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $x$).\n\nApplejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!\n\nWe remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.",
    "tutorial": "Let's maintain the array $cnt_i$, in it we are going to store the number of planks for each length. Let's note that to be able to build a square and a rectangle we need to have four planks of the same length and also two pairs of planks of the same length. To check it we can maintain two values: $sum2=\\sum_{i=1}^{10^5}\\lfloor \\frac{cnt_i}{2}\\rfloor$ and $sum4=\\sum_{i=1}^{10^5}\\lfloor \\frac{cnt_i}{4}\\rfloor$. Then, you will be able to build a square and a rectangular storage if $sum4 \\ge 1$ and $sum2 \\ge 4$. The first constraint satisfies the requirement about a square (you should have $\\ge 4$ planks of some length), and the second constraint satisfies the requirement about a rectangle (two pairs of the same length should be used and also two pairs are already used in the square).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint const MAXN = 1e5 + 5;\nint cnt[MAXN];\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int n, q, x, cnt2 = 0, cnt4 = 0;\n    char type;\n    cin >> n;\n\n    for (int i = 1; i <= n; ++i) {\n        cin >> x;\n        \n        cnt2 -= cnt[x] / 2;\n        cnt4 -= cnt[x] / 4;\n        cnt[x]++;\n        cnt2 += cnt[x] / 2;\n        cnt4 += cnt[x] / 4;\n    }\n\n    cin >> q;\n\n    for (int i = 1; i <= q; ++i) {\n        cin >> type >> x;\n        cnt2 -= cnt[x] / 2;\n        cnt4 -= cnt[x] / 4;\n        \n        if (type == '+') cnt[x]++;\n        else cnt[x]--;\n        \n        cnt2 += cnt[x] / 2;\n        cnt4 += cnt[x] / 4;\n        \n        if (cnt4 >= 1 && cnt2 >= 4) cout << \"YES\" << '\\n';\n        else cout << \"NO\" << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1393",
    "index": "C",
    "title": "Pinkie Pie Eats Patty-cakes",
    "statement": "Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.\n\nPinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.\n\nPinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!\n\nPinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!",
    "tutorial": "Let's note that if you can find the arrangement with the maximum distance $\\geq X$, then you can also find the arrangement with the maximum distance $\\geq X-1$. It allows you to use the binary search on the answer. To check that the answer is at least $X$, we can use the greedy algorithm. Each time let's use the element that we can use (we didn't use it on the last $x-1$ steps) and the number of the remaining elements equal to it is as large as possible. You can store the set of elements that you can use in the sorted by the number of appearances in $std::set$. This sol works $O(n log^2 n)$. Also there is a solution in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 100009;\nint cnt[MAXN];\nvector<int> a;\nint n;\n\nbool check(int x) {\n    for (int i = 1; i <= n; i ++) cnt[i] = 0;\n    for (int i = 0; i < n; i ++) cnt[a[i]]++;\n\n    set<pair<int, int>, greater<pair<int, int>>> ss; //use greater comparator to sort set in descending order\n    for (int i = 1; i <= n; i ++) {\n        if (cnt[i] > 0) ss.insert({cnt[i], i});\n    }\n\n    vector<int> b;\n    for (int i = 0; i < n; i ++) {\n        if (i >= x && cnt[b[i - x]]) {\n            ss.insert({cnt[b[i - x]], b[i - x]});\n        }\n\n        if (ss.empty()) return 0;\n        b.push_back(ss.begin()->second);\n        ss.erase(ss.begin());\n        cnt[b.back()]--;\n    }\n\n    return 1;\n}\n\nsigned main() {\n\tios :: sync_with_stdio(0);\n\tcin.tie(0);\n\n\tint ttt;\n\tcin >> ttt;\n\n\twhile (ttt--) {\n        cin >> n;\n\n        a.resize(n);\n        for (int i = 0; i < n; i ++) {\n            cin >> a[i];\n        }\n\n        int l = 0, r = n;\n        while (r - l > 1) {\n            int m = (r + l) / 2;\n            if (check(m)) {\n                l = m;\n            }\n\n            else {\n                r = m;\n            }\n        }\n\n        cout << l - 1 << \"\\n\";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1393",
    "index": "D",
    "title": "Rarity and New Dress",
    "statement": "Carousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric.\n\nThe piece of the multicolored fabric consists of $n \\times m$ separate square scraps. Since Rarity likes dresses in style, a dress pattern must only include scraps sharing the same color. A dress pattern must be the square, and since Rarity is fond of rhombuses, the sides of a pattern must form a $45^{\\circ}$ angle with sides of a piece of fabric (that way it will be resembling the traditional picture of a rhombus).\n\nExamples of proper dress patterns: Examples of improper dress patterns: The first one consists of multi-colored scraps, the second one goes beyond the bounds of the piece of fabric, the third one is not a square with sides forming a $45^{\\circ}$ angle with sides of the piece of fabric.\n\nRarity wonders how many ways to cut out a dress pattern that satisfies all the conditions that do exist. Please help her and satisfy her curiosity so she can continue working on her new masterpiece!",
    "tutorial": "Let's note that if there is a rhombus of size $X$ in the cell $(i, j)$, then there are also rhombuses with the smaller sizes. Let's divide the rhombus into the left part and the right part. Let's solve the problem separately for both of them and then the answer for the cell is going to be equal to the minimum of these values. Note that if the maximum size for the cell $(i, j)$ is $X$, then the maximum size for the cell $(i, j+1)$ is at most $X+1$ (and at most $1$, if these two cells are not equal). Also the maximums size for the left part is at most minimum of the number of consecutive cells to the up and to left from the fixed cell. To find the number of consective equal cells to the up, we will use the dynamic programming. If the cells $(i, j)$ and $(i-1, j)$ are equal, then the answer for the cell $(i, j)$ is equal to the answer for the cell $(i-1, j)$ plus $1$, otherwise it is equal to $1$. Similarly we can find the answer for the cells to the left. Now we need to find the maximum size of the left part. We can use dynamic programming and calculate it accordingly to our observations. Similarly for the right part. The total complexity is $O(nm)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nint const maxn = 2005;\nchar a[maxn][maxn];\nint cnt_up[maxn][maxn], cnt_down[maxn][maxn], L[maxn], R[maxn];\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n, m;\n    cin >> n >> m;\n    for (int i = 1; i <= n; ++i) {\n        for (int j = 1; j <= m; ++j) cin >> a[i][j];\n    }\n    ll ans = 0;\n    for (int i = 1; i <= n; ++i) {\n        for (int j = 1; j <= m; ++j) {\n            if (i != 1 && a[i][j] == a[i - 1][j]) cnt_up[i][j] = cnt_up[i - 1][j] + 1;\n            else cnt_up[i][j] = 0;\n        }\n    }\n    for (int i = n; i >= 1; --i) {\n        for (int j = 1; j <= m; ++j) {\n            if (i != n && a[i][j] == a[i + 1][j]) cnt_down[i][j] = cnt_down[i + 1][j] + 1;\n            else cnt_down[i][j] = 0;\n        }\n    }\n    for (int i = 1; i <= n; ++i) {\n        for (int j = 1; j <= m; ++j) {\n            int go = j;\n            while (go <= m && a[i][j] == a[i][go]) go++;\n            go--;\n            for (int pos = j; pos <= go; ++pos) {\n                if (pos == j) L[pos] = pos;\n                else {\n                    L[pos] = max(L[pos - 1], pos - min(cnt_up[i][pos], cnt_down[i][pos]));\n                }\n            }\n            j = go;\n        }\n        for (int j = m; j >= 1; --j) {\n            int go = j;\n            while (go >= 1 && a[i][j] == a[i][go]) go--;\n            go++;\n            for (int pos = j; pos >= go; --pos) {\n                if (pos == j) R[pos] = pos;\n                else {\n                    R[pos] = min(R[pos + 1], pos + min(cnt_up[i][pos], cnt_down[i][pos]));\n                }\n            }\n            j = go;\n        }\n        for (int j = 1; j <= m; ++j) {\n            ans += (ll)min(j - L[j] + 1, R[j] - j + 1);\n        }\n    }\n    cout << ans << '\\n';\n    return 0;\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "implementation",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1393",
    "index": "E2",
    "title": "Twilight and Ancient Scroll (harder version)",
    "statement": "This is a harder version of the problem E with larger constraints.\n\nTwilight Sparkle has received a new task from Princess Celestia. This time she asked to decipher the ancient scroll containing important knowledge of pony origin.\n\nTo hide the crucial information from evil eyes, pony elders cast a spell on the scroll. That spell adds exactly one letter in any place to each word it is cast on. To make the path to the knowledge more tangled elders chose some of words in the scroll and cast a spell on them.\n\nTwilight Sparkle knows that the elders admired the order in all things so the scroll original scroll contained words in \\textbf{lexicographically non-decreasing order}. She is asked to delete one letter from some of the words of the scroll (to undo the spell) to get some version of the original scroll.\n\nUnfortunately, there may be more than one way to recover the ancient scroll. To not let the important knowledge slip by Twilight has to look through all variants of the original scroll and find the required one. To estimate the maximum time Twilight may spend on the work she needs to know the number of variants she has to look through. She asks you to find that number! Since that number can be very big, Twilight asks you to find it modulo $10^9+7$.\n\nIt may occur that princess Celestia has sent a wrong scroll so the answer may not exist.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Let's use dynamic programming. $dp[i][j]$: the number of ways to form the non-decreasing subsequence on the strings $1 \\ldots i$, s.t. the delete character in string $i$ is $j$. This works in $O(L^3)$, where $L$ is the total length of all strings. Let's optimize this solution. For each string, sort all strings obtained by deleting at most one character from this string. You can do it in $O(L^2 \\cdot log L)$ for all strings. Then you can use two pointers to calculate or dp. To calculate the answer for the layer $i$ we will consider strings in the sorted order, and add all dp values for the smaller strings. We can calculate this dp in $O(L^2)$ and solve the problem in $O(L^2 \\cdot log L)$. We can use binary search and hash to compare strings in $O(log L)$. Then you can sort all the strings in $O(L \\cdot log^2 L)$. Note that you can sort the strings in $O(L)$. Look at the string $s$. For each character find the first character to the right not equal to it (array $nxt[i]$). Then we will store two pointers: to the beginning and the end of the list. Consider characters in the order from left to right. If $s_i$ > $s_{nxt[i]}$, add $i$ to the beginning of the list (to the position $l$ and increase $l$ by $1$), otherwise add it to the end of the list (to the position $r$ and decrease $r$ by $1$). Then add $s$ to some position in the list ($s$ will be in the list after it without the last character). Then you can use the hash to make the comparisons for two pointers in $O(log L)$. This sol works in $O(L \\cdot log L)$ and fits into TL.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nint const maxn = 1e5 + 5, maxc = 1e6 + 5;\nll mod[2], P[2], p[2][maxc], rev_P[2];\nvector < ll > h[2][maxn];\nvector < int > sorted[maxn];\nstring s[maxn];\nint nxt[maxc];\nint a[maxc], dp[2][maxc], inf = 1e9 + 7;\nint MOD = 1e9 + 7;\n\nll st(ll x, int y, int ok) {\n    if (y == 0) return 1;\n    if (y % 2 == 0) {\n        ll d = st(x, y / 2, ok);\n        return d * d % mod[ok];\n    }\n    return x * st(x, y - 1, ok) % mod[ok];\n}\n\ninline char get_c(int i, int x, int numb) {\n    if (numb < x) return s[i][numb];\n    if (numb + 1 < (int)s[i].size()) return s[i][numb + 1];\n    return ' ';\n}\n\ninline ll get_hash(int t, int i, int x, int len) {\n    if (len < x) return h[t][i][len];\n    return (h[t][i][x] + (h[t][i][len + 1] - h[t][i][x + 1] + mod[t]) * rev_P[t]) % mod[t];\n}\n\ninline pair < ll, ll > get_h(int i, int x, int len) {\n    return {get_hash(0, i, x, len), get_hash(1, i, x, len)};\n}\n\ninline int check(int i, int x, int j, int y) {\n    int len1 = (int)s[i].size(), len2 = (int)s[j].size();\n    if (x != len1) len1--;\n    if (y != len2) len2--;\n    int lef = 0, righ = min(len1, len2) + 1;\n    while (righ - lef > 1) {\n        int mid = (righ + lef) / 2;\n        if (get_h(i, x, mid) == get_h(j, y, mid)) lef = mid;\n        else righ = mid;\n    }\n    return get_c(i, x, lef) >= get_c(j, y, lef);\n}\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    mod[0] = 1e9 + 7, mod[1] = 1e9 + 9, P[0] = 29, P[1] = 31, rev_P[0] = st(P[0], mod[0] - 2, 0), rev_P[1] = st(P[1], mod[1] - 2, 1);\n    p[0][0] = 1, p[1][0] = 1;\n    for (int i = 1; i < maxc; ++i) {\n        for (int j = 0; j <= 1; ++j) p[j][i] = p[j][i - 1] * P[j] % mod[j];\n    }\n    int n;\n    cin >> n;\n    for (int i = 1; i <= n; ++i) {\n        cin >> s[i];\n        for (int j = 0; j <= 1; ++j) {\n            h[j][i].push_back(0);\n            for (int pos = 0; pos < (int)s[i].size(); ++pos) {\n                h[j][i].push_back((h[j][i][pos] + p[j][pos] * (s[i][pos] - 'a' + 1)) % mod[j]);\n            }\n        }\n        nxt[(int)s[i].size() - 1] = (int)s[i].size() - 1;\n        for (int pos = (int)s[i].size() - 2; pos >= 0; --pos) {\n            if (s[i][pos] != s[i][pos + 1]) nxt[pos] = pos + 1;\n            else nxt[pos] = nxt[pos + 1];\n        }\n        int l = 0, r = (int)s[i].size() - 1;\n        for (int j = 0; j < (int)s[i].size(); ++j) {\n            if (s[i][nxt[j]] <= s[i][j]) a[l++] = j;\n            else a[r--] = j;\n        }\n        for (int j = 0; j < (int)s[i].size(); ++j) {\n            sorted[i].push_back(a[j]);\n            if (a[j] == (int)s[i].size() - 1) sorted[i].push_back((int)s[i].size());\n        }\n    }\n    for (int i = 0; i <= (int)s[1].size(); ++i) {\n        dp[0][i] = 1;\n    }\n    for (int i = 2; i <= n; ++i) {\n        int oks = (i - 1) % 2, ptr = 0, sum = 0, cur = -1;\n        for (auto key : sorted[i]) {\n            cur++;\n            while (ptr < (int)sorted[i - 1].size() && check(i, key, i - 1, sorted[i - 1][ptr])) {\n                sum += dp[(1^oks)][ptr];\n                if (sum >= MOD) sum -= MOD;\n                ptr++;\n            }\n            dp[oks][cur] = sum;\n        }\n    }\n    int ans = 0;\n    for (int i = 0; i <= (int)s[n].size(); ++i) {\n        ans += dp[(n - 1) % 2][i];\n        if (ans >= MOD) ans -= MOD;\n    }\n    cout << ans << '\\n';\n    return 0;\n}",
    "tags": [
      "dp",
      "hashing",
      "implementation",
      "string suffix structures",
      "strings",
      "two pointers"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1394",
    "index": "A",
    "title": "Boboniu Chats with Du",
    "statement": "Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.\n\nIn Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.\n\nDu will chat in the group for $n$ days. On the $i$-th day:\n\n- If Du can speak, he'll make fun of Boboniu with fun factor $a_i$. But after that, he may be muzzled depending on Boboniu's mood.\n- Otherwise, Du won't do anything.\n\nBoboniu's mood is a constant $m$. On the $i$-th day:\n\n- If Du can speak and $a_i>m$, then Boboniu will be angry and muzzle him for $d$ days, which means that Du won't be able to speak on the $i+1, i+2, \\cdots, \\min(i+d,n)$-th days.\n- Otherwise, Boboniu won't do anything.\n\nThe total fun factor is the sum of the fun factors on the days when Du can speak.\n\nDu asked you to find the maximum total fun factor among all possible permutations of $a$.",
    "tutorial": "If $a_i>m$, we consider it as a big item with value $a_i$, else a small item with value $a_i$. We are asked to choose some items and maximize the total value. If an item is not chosen, it means we put it on a muzzled day. Enumerate the number of chosen big item, which is denoted by $x$. Thus they take $(x-1)(d+1)+1$ days. The remaining days are used to place small item on it. Choose items greedily. i. e. We sort items by value from largest to smallest, choose previous $x$ big items and previous $n-(x-1)(d+1)-1$ small items and update the answer. The total time complexity is $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\n#define rep(i, a, b) for (int i = (a); i <= int(b); i++)\nusing namespace std;\n\ntypedef long long ll;\nconst int maxn = 1e5;\nint n, d, m, k, l;\nll a[maxn + 5], b[maxn + 5];\n\nvoid solve(ll a[], int n) {\n\tsort(a + 1, a + n + 1);\n\treverse(a + 1, a + n + 1);\n\trep(i, 1, n) a[i] += a[i - 1];\n}\n\nint main() {\n\tscanf(\"%d %d %d\", &n, &d, &m);\n\tfor (int i = 0, x; i < n; i++) {\n\t\tscanf(\"%d\", &x);\n\t\tif (x > m) a[++k] = x;\n\t\telse b[++l] = x;\n\t}\n\tif (k == 0) {\n\t\tll s = 0;\n\t\trep(i, 1, n) s += b[i];\n\t\tprintf(\"%lld\\n\", s);\n\t\texit(0);\n\t}\n\tsolve(a, k);\n\tsolve(b, l);\n\tfill(b + l + 1, b + n + 1, b[l]);\n\tll res = 0;\n\trep(i, (k + d) / (1 + d), k) if (1ll * (i - 1) * (d + 1) + 1 <= n) {\n\t\tres = max(res, a[i] + b[n - 1ll * (i - 1) * (d + 1) - 1]);\n\t}\n\tprintf(\"%lld\\n\", res);\n\treturn 0;\n}\t",
    "tags": [
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1394",
    "index": "B",
    "title": "Boboniu Walks on Graph",
    "statement": "Boboniu has a \\textbf{directed} graph with $n$ vertices and $m$ edges.\n\nThe out-degree of each vertex is at most $k$.\n\nEach edge has an integer weight between $1$ and $m$. No two edges have equal weights.\n\nBoboniu likes to walk on the graph with some specific rules, which is represented by a tuple $(c_1,c_2,\\ldots,c_k)$. If he now stands on a vertex $u$ with out-degree $i$, then he will go to the next vertex by the edge with the $c_i$-th $(1\\le c_i\\le i)$ smallest weight among all edges outgoing from $u$.\n\nNow Boboniu asks you to calculate the number of tuples $(c_1,c_2,\\ldots,c_k)$ such that\n\n- $1\\le c_i\\le i$ for all $i$ ($1\\le i\\le k$).\n- Starting from any vertex $u$, it is possible to go back to $u$ in finite time by walking on the graph under the described rules.",
    "tutorial": "Let $\\deg u$ denote the out degree of $u$. Let $nex_{u,i}$ denote the vertex, which the edge with the $i$-the smallest weight among all edges start from $u$ ends at. For a fixed tuple $(t_1,t_2,\\ldots,t_k)$, if $\\{ nex_{i,t_{\\deg i}} | 1\\le i\\le n \\}=\\{1,2,\\ldots,n\\}$ (i. e. each vertex appears exactly once), then it is a correct tuple. Let $S_{i,j}$ denote if $c_i=j$, the set for vertex with out degree $i$, which is $\\{ nex_{u,j} | \\deg u=i \\}$. Thus the condition above can be changed to: $S_{1,t_1} \\cup S_{2,t_2} \\cup \\ldots \\cup S_{k,t_k}=\\{1,2,\\ldots,n\\}$. Let's enumerate all $k!$ situations and use hash to check if it's correct. The hash function is diverse. For example, for a integer set $T$, we can use $h(T)=\\sum_{x\\in T}val_x\\bmod p$ or $h(T)=\\prod_{x\\in T}val_x\\bmod p$. Just make sure it has associative property. Here $val_x$ may be a random number. Let alone using multiple hash. The total time complexity is $O(n+m+k!)$.",
    "code": "//by Sshwy\n#include<bits/stdc++.h>\nusing namespace std;\n#define pb push_back\n#define FOR(i,a,b) for(int i=(a);i<=(b);++i)\n#define ROF(i,a,b) for(int i=(a);i>=(b);--i)\n\nmt19937 mt_rand(chrono::high_resolution_clock::now().time_since_epoch().count());\nconst int N=2e5+5,HS=3,K=10;\nint n,m,k;\nvector< pair<int,int> > g[N];\n\nint mod[HS];\n\nstruct hash_number{\n    int a[HS];\n    hash_number(){ fill(a,a+HS,0); }\n    hash_number(long long x){\n        FOR(i,0,HS-1)a[i]=(x%mod[i]+mod[i])%mod[i];\n    }\n    hash_number operator+(hash_number x){\n        hash_number res;\n        res.a[0]=(a[0]+x.a[0])%mod[0];\n        res.a[1]=(a[1]*1ll*x.a[1])%mod[1];\n        res.a[2]=(a[2]+x.a[2])%mod[2];\n        return res;\n    }\n    bool operator==(const hash_number& x)const {\n        FOR(i,0,HS-1)if(a[i]!=x.a[i])return 0;\n        return 1;\n    }\n}val[N],c[K][K],s;\nint ans;\nint status[K];\nvoid dfs(int x,hash_number hsh){\n    if(x==k){\n        if(hsh == s) ++ans;\n        return;\n    }\n    FOR(i,1,x+1){\n        status[x+1]=i;\n        dfs(x+1,hsh+c[x+1][i]);\n    }\n}\nint main(){\n    mod[0]=998244353;\n    mod[1]=1e9+7;\n    mod[2]=std::uniform_int_distribution<int>(1e8,1e9)(mt_rand);\n\n    fprintf(stderr,\"%d %d %d\\n\",mod[0],mod[1],mod[2]);\n\n    scanf(\"%d%d%d\",&n,&m,&k);\n    FOR(i,1,m){\n        int u,v,w;\n        scanf(\"%d%d%d\",&u,&v,&w);\n        g[u].pb({w,v});\n    }\n    std::uniform_int_distribution<long long> rg(1,1e18);\n    FOR(i,1,n)val[i]=hash_number(rg(mt_rand));\n    FOR(i,1,n)s=s+val[i];\n    FOR(u,1,n){\n        int d=g[u].size();\n        sort(g[u].begin(),g[u].end());\n        for(int i=1;i<=g[u].size();++i){\n            int v=g[u][i-1].second;\n            c[d][i]=c[d][i]+val[v];\n        }\n    }\n    dfs(0,hash_number());\n    printf(\"%d\\n\",ans);\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "hashing"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1394",
    "index": "C",
    "title": "Boboniu and String",
    "statement": "Boboniu defines BN-string as a string $s$ of characters 'B' and 'N'.\n\nYou can perform the following operations on the BN-string $s$:\n\n- Remove a character of $s$.\n- Remove a substring \"BN\" or \"NB\" of $s$.\n- Add a character 'B' or 'N' to the end of $s$.\n- Add a string \"BN\" or \"NB\" to the end of $s$.\n\nNote that a string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nBoboniu thinks that BN-strings $s$ and $t$ are similar if and only if:\n\n- $|s|=|t|$.\n- There exists a permutation $p_1, p_2, \\ldots, p_{|s|}$ such that for all $i$ ($1\\le i\\le |s|$), $s_{p_i}=t_i$.\n\nBoboniu also defines $\\text{dist}(s,t)$, the distance between $s$ and $t$, as the minimum number of operations that makes $s$ similar to $t$.\n\nNow Boboniu gives you $n$ non-empty BN-strings $s_1,s_2,\\ldots, s_n$ and asks you to find a \\textbf{non-empty} BN-string $t$ such that the maximum distance to string $s$ is minimized, i.e. you need to minimize $\\max_{i=1}^n \\text{dist}(s_i,t)$.",
    "tutorial": "It's obvious that the operation of BN-string is equivalent to the operation of BN-set, which I'm talking about, for a multi set $s$ contains only B and N: Remove a B or an N (if exists) from $s$. Insert a B or an N into $s$. Remove a B and an N from $s$. Insert a B and an N into $s$. So let's use pair $(x,y)$ to denote a BN-set, which means there are $x$ B and $y$ N in it. We can do an operation to move to $(x,y\\pm 1),(x\\pm 1,y),(x\\pm 1,y\\pm 1)$. The definition of similar of BN-set $(x_1,y_1)$ and $(x_2,y_2)$ is simply $x_1=x_2$ and $y_1=y_2$. Now the problem is to find a $(x_t,y_t)$ and minimize $\\max_{i=1}^n\\text{dist}(s_i,t)$. There are many algorithms to solve it and I'll describe two of them. We can figure out the distance between $s_1=(x_1,y_1)$ and $s_2=(x_2,y_2)$ is: $\\text{dist}(s_1,s_2)=\\begin{cases} |x_1-x_2|+|y_1-y_2| & (x_1-x_2)(y_1-y_2)<0\\\\ \\max(|x_1-x_2|,|y_1-y_2|) & (x_1-x_2)(y_1-y_2) \\ge 0 \\end{cases}$ We also have non randomized algorithm. It can be shown that for a fixed pair $P=(p_x,p_y)$, all the pair with distance $x$ from $P$ forms a hexagon: So if we draw a hexagon centered on $(x_t,y_t)$ with radius $\\max_{i=1}^n\\text{dist}(s_i,t)$, then it must cover all $s_i$. So we can try to find a hexagon with minimal radius $r$ to cover all $s_i$ and then we can easily calculate $(x_t,y_t)$. Let's use binary search and do some condition tests to calculate $r$. The total time complexity is $O(n\\log_2n)$.",
    "code": "//by Sshwy\n#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i=(a);i<=(b);++i)\n#define ROF(i,a,b) for(int i=(a);i>=(b);--i)\nconst int INF=1e9;\n\nint n;\n\nint main(){\n    cin>>n;\n    int lx=INF,rx=-INF,ly=INF,ry=-INF,lz=INF,rz=-INF;\n    FOR(i,1,n){\n        string s;\n        cin>>s;\n        int x=0,y=0;\n        for(char c:s){\n            if(c=='B')++x;\n            else ++y;\n        }\n        //printf(\"%d %d\\n\",x,y);\n        lx=min(lx,x), rx=max(rx,x);\n        ly=min(ly,y), ry=max(ry,y);\n        lz=min(lz,x-y), rz=max(rz,x-y);\n    }\n\n    int ans=INF,ax=0,ay=0,az=0;\n    auto calc = [&](){\n        int l=0,r=lz-(lx-ry),mid;\n        auto check = [&](int a){\n            return lx+a+a>=rx && lx-ry+a+a+a>=rz && ry-a-a<=ly;\n        };\n        if(check(r)==0)return INF;\n        while(l<r)mid=(l+r)>>1, check(mid)?r=mid:l=mid+1;\n        return l;\n    };\n    FOR(_,1,6){\n        assert(lx<=rx && ly<=ry && lz<=rz);\n        int v=calc();\n        if(v<ans){\n            ans=v;\n            ax=lx+v, ay=ry-v, az=ax-ay;\n        }\n        int Lx=ly,Rx=ry,Ly=-rz,Ry=-lz,Lz=lx,Rz=rx;\n        lx=Lx, rx=Rx, ly=Ly, ry=Ry, lz=Lz, rz=Rz;\n        int Ax=ay,Ay=-az,Az=ax;\n        ax=Ax,ay=Ay,az=Az;\n    }\n    cout<<ans<<endl;\n    FOR(i,1,ax)cout<<'B';\n    FOR(i,1,ay)cout<<'N';\n    cout<<endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "geometry",
      "ternary search"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1394",
    "index": "D",
    "title": "Boboniu and Jianghu",
    "statement": "Since Boboniu finished building his Jianghu, he has been doing Kungfu on these mountains every day.\n\nBoboniu designs a map for his $n$ mountains. He uses $n-1$ roads to connect all $n$ mountains. Every pair of mountains is connected via roads.\n\nFor the $i$-th mountain, Boboniu estimated the tiredness of doing Kungfu on the top of it as $t_i$. He also estimated the height of each mountain as $h_i$.\n\nA path is a sequence of mountains $M$ such that for each $i$ ($1 \\le i < |M|$), there exists a road between $M_i$ and $M_{i+1}$. Boboniu would regard the path as a challenge if for each $i$ ($1\\le i<|M|$), $h_{M_i}\\le h_{M_{i+1}}$.\n\nBoboniu wants to divide \\textbf{all} $n-1$ roads into several challenges. Note that each road must appear in \\textbf{exactly one} challenge, but a mountain may appear in several challenges.\n\nBoboniu wants to minimize the total tiredness to do all the challenges. The tiredness of a challenge $M$ is the sum of tiredness of all mountains in it, i.e. $\\sum_{i=1}^{|M|}t_{M_i}$.\n\nHe asked you to find the minimum total tiredness. As a reward for your work, you'll become a guardian in his Jianghu.",
    "tutorial": "Generally speaking, you're asked to use some simple directed paths (challenges) to cover the original tree and minimize the total cost (tiredness). Those edges with $h_u \\neq h_v$ are already oriented, and for the other ones, we need to determine their directions. At first, let's consider the case where each edge has already been oriented (or, for all edges $(u, v)$, $h_u \\neq h_v$ holds). We use $P(u, v)$ to denote the directed path from $u$ to $v$. In the beginning, for each edge $u \\to v$, let's set up $P(u, v)$ to cover it. Thus the total cost of it is obviously $\\sum_{i = 1}^{n} \\text{deg}(i) \\cdot t_i$, where $\\text{deg}_i$ denotes the degree of vertex $i$. We can choose two challenge $P(x, y)$ and $P(y, z)$ ($y$ should be on $P(x, z)$) and merge them together to get a single challenge $P(x, z)$. This operation will reduce the total tiredness by $t_y$. Thus we try to do such operation to maximize the total reduction. For vertex $i$, suppose that there are $\\text{in}_i$ challenges end at $i$ and $\\text{out}_i$ challenges start from $i$. Thus the total reduction is $\\sum_{i = 1}^{n} \\min(\\text{in}_i, \\text{out}_i) \\cdot t_i$. Now, let's try to solve the original problem. For the directed edges, we calculate $\\text{in}'_i$ and $\\text{out}'_i$ for every vertex $i$, and we can delete them from the tree. For the undirected edges, they form several small trees (a forest). Let's choose an arbitrary root for each tree and do a DP on it. Let $p_u$ be the father of $u$. For a non-root vertex $u$ and its subtree, $f_u$ denotes the maximum reduction when we orient $p_u \\to u$ (down), and $g_u$ denotes the maximum reduction when we orient $u \\to p_u$ (up). Take $f_u$ for example. To calculate it, we should know the in degree and out degree of $u$ (after directing the edges). Suppose that $u$ has $c$ children. If $x$ of them are oriented end at $u$ (up) and $(s - x)$ of them are oriented start from $u$ (down), the reduction of $u$ is $\\min(\\text{in}'_u + 1 + x, \\text{out}'_u + (s - x)) \\cdot t_u$ ($+ 1$ because $p_u \\to u$). Now the question changes to: You are given $c$ vertices $v_1, v_2,\\ldots, v_c$, choose $x$ of them forming a set $A$. Maximize $\\sum_{v \\in A} g_v + \\sum_{v \\notin A} f_v$. Calculate the maximum value for all $0 \\le x \\le c$. Actually, you can sort $[v_1, v_2, \\cdots, v_c]$ by $(f_v - g_v)$ and calculate the prefix sum $s_i$. The answer for $x = i$ is simply $s_i + \\sum_v g_v$. The calculation for $g_u$ and the root is similar. The total time complexity is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\nconst int maxn = 2e5;\nint n, h[maxn + 3], t[maxn + 3], in[maxn + 3], out[maxn + 3];\nvector<int> G[maxn + 3];\nbool vis[maxn + 3];\nll ans, f[maxn + 3], g[maxn + 3], a[maxn + 3];\n\nvoid dfs(int u, int fa = 0) {\n\tvis[u] = true;\n\tfor (int i = 0, v; i < G[u].size(); i++) {\n\t\tif ((v = G[u][i]) == fa) continue;\n\t\tdfs(v, u);\n\t}\n\tint s = 0;\n\tll cur = 0;\n\tfor (int i = 0, v; i < G[u].size(); i++) {\n\t\tif ((v = G[u][i]) == fa) continue;\n\t\tcur += g[v], a[++s] = f[v] - g[v];\n\t}\n\tsort(a + 1, a + s + 1);\n\treverse(a + 1, a + s + 1);\n\tfor (int i = 0; i <= s; i++) {\n\t\tcur += a[i];\n\t\tif (fa) {\n\t\t\tf[u] = max(f[u], 1ll * min(in[u] + 1 + s - i, out[u] + i) * t[u] + cur);\n\t\t\tg[u] = max(g[u], 1ll * min(in[u] + s - i, out[u] + 1 + i) * t[u] + cur);\n\t\t} else {\n\t\t\tf[u] = max(f[u], 1ll * min(in[u] + s - i, out[u] + i) * t[u] + cur);\n\t\t}\n\t}\n}\n\nint main() {\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; i++) scanf(\"%d\", &t[i]);\n\tfor (int i = 1; i <= n; i++) scanf(\"%d\", &h[i]);\n\tfor (int i = 1, u, v; i < n; i++) {\n\t\tscanf(\"%d %d\", &u, &v);\n\t\tans += t[u] + t[v];\n\t\tif (h[u] == h[v]) {\n\t\t\tG[u].push_back(v), G[v].push_back(u);\n\t\t} else {\n\t\t\tif (h[u] > h[v]) swap(u, v);\n\t\t\tin[u]++, out[v]++;\n\t\t}\n\t}\n\tfor (int i = 1; i <= n; i++) if (!vis[i]) {\n\t\tdfs(i), ans -= f[i];\n\t}\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1394",
    "index": "E",
    "title": "Boboniu and Banknote Collection",
    "statement": "No matter what trouble you're in, don't be afraid, but face it with a smile.\n\nI've made another billion dollars!\n\n— Boboniu\n\nBoboniu has issued his currencies, named Bobo Yuan. Bobo Yuan (BBY) is a series of currencies. Boboniu gives each of them a positive integer identifier, such as BBY-1, BBY-2, etc.\n\nBoboniu has a BBY collection. His collection looks like a sequence. For example:\n\nWe can use sequence $a=[1,2,3,3,2,1,4,4,1]$ of length $n=9$ to denote it.\n\nNow Boboniu wants to fold his collection. You can imagine that Boboniu stick his collection to a long piece of paper and fold it between currencies:\n\nBoboniu will only fold the same identifier of currencies together. In other words, if $a_i$ is folded over $a_j$ ($1\\le i,j\\le n$), then $a_i=a_j$ must hold. Boboniu doesn't care if you follow this rule in the process of folding. But once it is finished, the rule should be obeyed.\n\nA formal definition of fold is described in notes.\n\nAccording to the picture above, you can fold $a$ two times. In fact, you can fold $a=[1,2,3,3,2,1,4,4,1]$ at most two times. So the maximum number of folds of it is $2$.\n\nAs an international fan of Boboniu, you're asked to calculate the maximum number of folds.\n\nYou're given a sequence $a$ of length $n$, for each $i$ ($1\\le i\\le n$), you need to calculate the maximum number of folds of $[a_1,a_2,\\ldots,a_i]$.",
    "tutorial": "At first, I'd like to explanation the fold operation in a intuitive way. Section 1 Fold To be exact, the origin problem isn't ask us to calculate the number of folds, but the number of folding marks. Section 1.1 Example 1 For example, you can fold $[1,1,1,1]$ three times, but you have different method to fold it: Method 1: Method 2: The first method can be represent by folding sequence (defined in the statement) $[1,-1,1,-1]$. The second method seems to be invalid under the definition of fold (in statement). But really? In fact, those methods are equivalent. The position of their folding marks are exactly the same, but different in whether it's valley folds or mountain folds. For the first method, the folding type of each fold mark is: mountain, valley, mountain. For the second method, it's: mountain, mountain, valley. (Try it yourself!) Although the second method does only two folds, it folds two layers of paper together so it gets two folding marks in one fold. Section 1.2 Example 2 For $[1,2,2,2,2,1,1,2,2]$, there are different folding methods. I'll display two of them: Firstly to be notice, they have same number of folding marks. The first method can be represent by folding sequence $[1,1,-1,1,-1,-1,1,1,1]$. We can change the result of the second method to the first method: Just change the blue part to red part. Section 1.3 Summary In fact, the definition of fold in statement always lead to alternate mountain and valley folds. But you can also use different folding method, because any results can be transform into alternate mountain and valley folds. key point 1: While folding, we don't care whether it's mountain or valley folds, we just care about the position of folding marks (and the rule in statement). key point 2: Fix the sequence $a$, for all folding methods of $a$, as long as the results of them don't have any available folds, then the number of folding marks of them must be equal, and their results must be the same (or simply reverse sequence). Although I'll provide proof for these key points, I want you to first think of it intuitively. Section 2 X-Y-X Folding Method If understanding the folding operation intuitively, it'll be quite easy to come up with a naive algorithm runs in polynomial time. Now I'll describe a general folding method. Note: I will consider sequence as a string (with a large character set). The definition of substring, palindrome is similar for sequence. Let's consider $[\\ldots,a,b,b,b,c,\\ldots]$, we can fold three $b$ into one $b$ with a mountain fold and a valley fold. Similarly, consider three continuous substring $\\textit{XYX}$, where $Y$ is the reverse string of $X$: We can fold them into one $X$ with a mountain fold and a valley fold, according to the first two key points. Let's call it X-Y-X substring and the folding method X-Y-X fold. The questions are: How many layers of paper are folded during a X-Y-X fold? Can we find a proper folding method where each fold contains only one layer of paper? How to fold a string which doesn't contain X-Y-X substring? Section 3 Key Points (For high level competitor) I display all the key points firstly which may lead you to final solution quickly. Intuitively, we will fold $a$ from left to right. Let's maintain another string $b$. Each time: Push $a_i$ to the end of $b$ and check if $b$ contains new X-Y-X substring. If it does, then fold it. Calculate the number of folds of $b$. Note that this step won't actually change $b$. After that you get the answer of $[a_1,a_2,\\cdots,a_i]$. key point 3: Using this folding method, each fold contains exactly one layer of paper. key point 4: After pushing $a_i$ to the end of $b$, $b$ contains at most one X-Y-X substring and it must be a suffix if exists. lemma: For string $s$ and two even palindromic substring $s[l_1,r_1]$, $s[l_2,r_2]$ of it, if $[l_1,r_1]$ contains center position of $s[l_2,r_2]$ and $[l_2,r_2]$ contains center position of $s[l_1,r_1]$, then $s$ must contain X-Y-X substring. Use information above, we can figure out a $O(n^3)$ or $O(n^2)$ solution. key point 5: For a string $b$ which doesn't contain X-Y-X substring, we can only fold its prefix or suffix. And it can be folded at most $O(\\sqrt{|b|})$ times. key point 6: For a string $b$ which doesn't contain X-Y-X substring, after pushing an element to the end of $b$, it has at most $O(\\log_2|b|)$ even palindromic suffixes. Use information above, we can figure out a $O(n\\log_2n+n\\sqrt{n})$ or $O(n\\log_2n)$ solution, which is enough to pass. Section 3.1 Example Let's say $a=[1,2,2,2,2,1,1,2,2]$. So the folding method performs like: $b=[1]$. It doesn't have any available folds. The answer is $0$. $b=[1,2]$. It doesn't have any available folds. The answer is $0$. $b=[1,2,2]$. It can be folded once. The answer is $1$. $b=[1,2,2,2]$, has X-Y-X substring $[2,2,2]$, so $b$ is changed to $[1,2]$. Plus X-Y-X counter by $2$. After that, $b$ doesn't have any available folds. The answer is $2$. $b=[1,2]+a_5=[1,2,2]$. It can be folded once. The answer is $3$. $b=[1,2,2]+a_6=[1,2,2,1]$. It can be folded once. The answer is $3$. $b=[1,2,2,1]+a_7=[1,2,2,1,1]$. It can be folded twice. The answer is $4$. $b=[1,2,2,1,1]+a_8=[1,2,2,1,1,2]$, has X-Y-X substring $[1,2,2,1,1,2]$, so $b$ is changed to $[1,2]$. Plus X-Y-X counter by $2$. After that, $b$ doesn't have any available folds. The answer is $4$. $b=[1,2]+a_9=[1,2,2]$. It can be folded once. The answer is $5$. Each time the answer is the sum of X-Y-X counter and number of folds of $b$. So the total output will be $[0,0,1,2,3,3,4,4,5]$. Section 4 Proof and Understanding Now I'll describe the proof of some key points. If you have already understand them, skip this section and read the algorithm part. Section 4.1 Lemma Description: For string $S$ and two even palindromic substring $S[l_1,r_1]$, $S[l_2,r_2]$ of it, if $[l_1,r_1]$ contains center position of $S[l_2,r_r]$ and $[l_2,r_2]$ contains center position of $S[l_1,r_1]$, then $S$ must contain X-Y-X substring. Lets say $l_1<l_2$ and $|r_1-l_1|\\ge |r_2-l_2|$. By construction we can get: Blue lines denotes the center position of two substrings and the red part forms a X-Y-X substring. Q. E. D. Section 4.2 X-Y-X and Simple X-Y-X Let define Simple X-Y-X substring (S-X-Y-X) as a X-Y-X string which doesn't contain any X-Y-X substring except itself. key point 7: S-X-Y-X string contains exactly one even palindromic suffix. i. e. the Y-X part of it. Proof: Use reduction to absurdity and the lemma. Section 4.3 Key Point 4 Description: After pushing $a_i$ to the end of $b$, $b$ contains at most one X-Y-X substring and it must be a suffix if exists. Let $b'=b+a_i$. Just like the picture above, if $b'$ contains two or more X-Y-X substring, there are three cases: black and red black and blue black and green All of the three cases can be negate by the lemma or plain discovery. Q. E. D. By the way: key point 4 shows us that if $b'$ has a X-Y-X substring, it must be a S-X-Y-X substring. key point 7 shows us that that if $b'$ has a X-Y-X substring, it must be produced by its shortest even palindromic suffix. Section 4.4 Key Point 5 Description: For a string $b$ which doesn't contain X-Y-X substring, we can only fold its prefix or suffix. And it can be folded at most $O(\\sqrt{|b|})$ times. Let's take suffix for example. Each time you can fold an even palindromic suffix if exists. And the length of it must be increasing: So that it won't contain X-Y-X substring. Similar for prefix. So the folds will end up being Thus you can fold less than $2\\sqrt{|b|}$ times. Q. E. D. Section 4.5 Key Point 6 Description: For a string $b$ which doesn't contain X-Y-X substring, after pushing an element to the end of $b$, it has at most $O(\\log_2|b|)$ even palindromic suffixes. Because of the lemma, even palindromic suffixes of $b$ cannot both contain center position of each other, so that if we sort them by length, then every even palindromic suffix must be at least twice as long as the previous one: Thus $b$ has at most $O(\\log_2|b|)$ even palindromic suffixes. Q. E. D. Section 5 Algorithm The algorithm itself is quite simple. Remember that: Intuitively, we will fold $a$ from left to right. Let's maintain another string $b$. Each time: Push $a_i$ to the end of $b$ and check if $b$ contains new X-Y-X substring. If so, then fold it. Calculate the number of folds of $b$. Note that this step won't change $b$. After that you get the answer of $[a_1,a_2,\\cdots,a_i]$. Section 5.1 Part 1 Let's maintain $S_i$, the set of even palindromic suffixes of $b$ after the $i$-th time. Since the size of it is $O(\\log_2n)$, use any data structure you want. Calculate $S_i$ from $S_{i-1}$ in $O(\\log_2n)$ is trivial. Then we simply find the shortest even palindromic suffix of $b$ and check if it produce a X-Y-X substring in $O(\\log_2n)$. If it does produce, then we simply fold it, which means remove the shortest even palindromic suffix of $b$. Don't forget to update X-Y-X counter. Section 5.2 Part 2 To calculate the number of folds of $b$, which doesn't contain X-Y-X substring: Let $p_i$ denote the length of shortest even palindromic suffix of $b[1,i]$ (index starts from $1$). Let $q_i$ denote that, if we fold the shortest even palindromic prefix start from $b[1,i]$ and repeat folding until you can't fold, the position of the first character of the result. i. e. $b[1,i]$ is folded to $b[q_i,i]$ finally. Let $c_i$ denote the number of folds during the process. Calculate $q_i$ from $q_{i-1}$ in $O(\\log_2n)$. Don't forget $c_i$. Get $p_i$ from $S_i$. $c_i$ denotes the number of prefix folds of $b$. You can fold suffix of $b$ using $p$ and calculate the number of suffix folds in $O(\\sqrt{n})$. The sum of two above is the number of folds of $b$. Plus it by X-Y-X counter you'll get the answer. Remove suffix of $b$ is trivial. The total time complexity is $O(n\\log_2n+n\\sqrt{n})$. Section 5.3 Bonus Can you optimize the time complexity of part 2 to $O(\\log_2n)$ and implement the algorithm in $O(n\\log_2n)$?",
    "code": "//by Sshwy\n#include<bits/stdc++.h>\nusing namespace std;\n#define pb push_back\n#define FOR(i,a,b) for(int i=(a);i<=(b);++i)\n#define ROF(i,a,b) for(int i=(a);i>=(b);--i)\n\nconst int N=1e5+5;\nint n,a[N],xyx,q[N],c[N],p[N];\nvector<int> v[N];\n\nint pos;\n\nvoid get_v(int pos){\n    v[pos].clear();\n    if(pos==1)return;\n    if(a[pos]==a[pos-1])v[pos].pb(2);\n    for(auto x:v[pos-1])if(a[pos]==a[pos-x-1])v[pos].pb(x+2);\n}\nbool check_even_pal(int L,int R){\n    assert(R<=pos);\n    for(auto x:v[R])if(x==R-L+1)return 1;\n    return 0;\n}\n\nint qry(){\n    int res=xyx+c[pos];\n    int cur=pos;\n    while(p[cur] && q[pos]<=cur-p[cur]/2){\n        cur-=p[cur]/2;\n        ++res;\n    }\n    return res;\n}\n\nint main(){\n    scanf(\"%d\",&n);\n    q[0]=1;\n    FOR(i,1,n){\n        ++pos;\n        scanf(\"%d\",&a[pos]);\n        get_v(pos);\n        int x;\n        if(v[pos].size() && (x=v[pos][0], check_even_pal(pos-x/2-x+1,pos-x/2))){\n            pos-=x;\n            xyx+=2;\n        }else {\n            p[pos]=v[pos].size()? v[pos][0]:0;\n            q[pos]=q[pos-1],c[pos]=c[pos-1];\n            if(check_even_pal(q[pos],pos)){\n                q[pos]+=(pos-q[pos]+1)/2;\n                c[pos]++;\n            }\n        }\n        printf(\"%d%c\",qry(),\" \\n\"[i==n]);\n    }\n    return 0;\n}",
    "tags": [
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1395",
    "index": "A",
    "title": "Boboniu Likes to Color Balls",
    "statement": "Boboniu gives you\n\n- $r$ red balls,\n- $g$ green balls,\n- $b$ blue balls,\n- $w$ white balls.\n\nHe allows you to do the following operation as many times as you want:\n\n- Pick a red ball, a green ball, and a blue ball and then change their color to white.\n\nYou should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations.",
    "tutorial": "If there are less than or equal to one odd number in $r$, $b$, $g$, $w$, then you can order them to be a palindrome. Otherwise, do the operation once (if you can) and check the condition above. It is meaningless to do operation more than once because we only care about the parity of $r$, $b$, $g$, $w$.",
    "code": "def check(r,g,b,w):\n    return False if r%2 + g%2 + b%2 + w%2 > 1 else True\n\nif __name__ == '__main__':\n    T = int(input())\n    for ttt in range(T):\n        r,g,b,w = map(int,input().split())\n        if check(r,g,b,w):\n            print(\"Yes\")\n        elif r>0 and g>0 and b>0 and check(r-1,g-1,b-1,w+1):\n            print(\"Yes\")\n        else :\n            print(\"No\")",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1395",
    "index": "B",
    "title": "Boboniu Plays Chess",
    "statement": "Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.\n\nYou are a new applicant for his company. Boboniu will test you with the following chess question:\n\nConsider a $n\\times m$ grid (rows are numbered from $1$ to $n$, and columns are numbered from $1$ to $m$). You have a chess piece, and it stands at some cell $(S_x,S_y)$ which is not on the border (i.e. $2 \\le S_x \\le n-1$ and $2 \\le S_y \\le m-1$).\n\nFrom the cell $(x,y)$, you can move your chess piece to $(x,y')$ ($1\\le y'\\le m, y' \\neq y$) or $(x',y)$ ($1\\le x'\\le n, x'\\neq x$). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.\n\nYour goal is to visit each cell exactly once. Can you find a solution?\n\nNote that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.",
    "tutorial": "There are many solutions and I will describe one of them. Let say $f(i,j) = ( (i+S_x-2)\\bmod n+1, (j+S_y-2)\\bmod m+1 )$. Iterate $i$ from $1$ to $n$: if $i$ is odd, print $f(i,1),f(i,2),\\ldots,f(i,m)$. Else print $f(i,m),f(i,m-1),\\ldots,f(i,1)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for(int i=(a);i<=(b);++i)\n#define ROF(i,a,b) for(int i=(a);i>=(b);--i)\n\nint n,m,sx,sy;\n\nvoid f(int i,int j){\n    printf(\"%d %d\\n\",(i+sx-2)%n+1,(j+sy-2)%m+1);\n}\nint main(){\n    scanf(\"%d%d%d%d\",&n,&m,&sx,&sy);\n    FOR(i,1,n){\n        if(i&1)FOR(j,1,m)f(i,j);\n        else ROF(j,m,1)f(i,j);\n    }\n    return 0;\n}\t",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1395",
    "index": "C",
    "title": "Boboniu and Bit Operations",
    "statement": "Boboniu likes bit operations. He wants to play a game with you.\n\nBoboniu gives you two sequences of non-negative integers $a_1,a_2,\\ldots,a_n$ and $b_1,b_2,\\ldots,b_m$.\n\nFor each $i$ ($1\\le i\\le n$), you're asked to choose a $j$ ($1\\le j\\le m$) and let $c_i=a_i\\& b_j$, where $\\&$ denotes the bitwise AND operation. Note that you can pick the same $j$ for different $i$'s.\n\nFind the minimum possible $c_1 | c_2 | \\ldots | c_n$, where $|$ denotes the bitwise OR operation.",
    "tutorial": "Suppose the answer is $A$. Thus for all $i$ ($1\\le i\\le n$), $c_i | A = A$. Since $a_i, b_i <2^9$, we can enumerate all integers from $0$ to $2^9-1$, and check if there exists $j$ for each $i$ that $(a_i \\& b_j) | A = A$. The minimum of them will be the answer. The time complexity is $O(2^9\\cdot n^2)$",
    "code": "#include<bits/stdc++.h>\n#define ci const int&\nusing namespace std;\nint n,m,p[210],d[210],ans;\nbool Check(ci x){\n\tfor(int i=1;i<=n;++i){\n\t\tfor(int j=1;j<=m;++j)if(((p[i]&d[j])|x)==x)goto Next;\n\t\treturn 0;\n\t\tNext:;\n\t}\n\treturn 1;\n}\nint main(){\n\tscanf(\"%d%d\",&n,&m);\n\tfor(int i=1;i<=n;++i)scanf(\"%d\",&p[i]);\n\tfor(int i=1;i<=m;++i)scanf(\"%d\",&d[i]);\n\tans=(1<<9)-1;\n\tfor(int i=8;i>=0;--i)Check(ans^(1<<i))?ans^=(1<<i):0;\n\tprintf(\"%d\",ans);\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1396",
    "index": "A",
    "title": "Multiples of Length",
    "statement": "You are given an array $a$ of $n$ integers.\n\nYou want to make all elements of $a$ equal to zero by doing the following operation \\textbf{exactly three} times:\n\n- Select a segment, for each number in this segment we can add a multiple of $len$ to it, where $len$ is the length of this segment (added integers can be different).\n\nIt can be proven that it is always possible to make all elements of $a$ equal to zero.",
    "tutorial": "In this problem, the answer is rather simple. Here is one possible solution to this task. $1 \\space \\space 1$ $0$ $1 \\space \\space 1$ $0$ $1 \\space \\space 1$ $-a_1$ $1 \\space \\space 1$ $-a_1$ $1 \\space \\space n$ $0, \\space -n \\cdot a_2, \\space -n \\cdot a_3, \\space \\dots , \\space -n \\cdot a_n$ $2 \\space \\space n$ $(n-1) \\cdot a_2, \\space (n-1) \\cdot a_3, \\space \\dots , \\space (n-1) \\cdot a_n$",
    "code": "n = int(input())\na = list(map(int, input().split()))\n\nif n == 1:\n    print('1 1', -a[0], '1 1', '0', '1 1', '0', sep='\\n')\n    exit(0)\n\nprint(1, n)\nfor i in range(n):\n    print(-a[i] * n, end = ' ')\n    a[i] -= a[i] * n\nprint()\n\nprint(1, n - 1)\nfor i in range(n - 1):\n    print(-a[i], end = ' ')\n    a[i] = 0\nprint()\n\nprint(2, n)\nfor i in range(1, n):\n    print(-a[i], end = ' ')\n    a[i] = 0\nprint()",
    "tags": [
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1396",
    "index": "B",
    "title": "Stoned Game",
    "statement": "T is playing a game with his friend, HL.\n\nThere are $n$ piles of stones, the $i$-th pile initially has $a_i$ stones.\n\nT and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends.\n\nAssuming both players play optimally, given the starting configuration of $t$ games, determine the winner of each game.",
    "tutorial": "Let us denote $S$ as the current total number of stones. Consider the following cases: Case A: There is a pile that has more than $\\lfloor \\frac{S}{2} \\rfloor$ stones. The first player (T) can always choose from this pile, thus he (T) is the winner. Case B: Every pile has at most $\\lfloor \\frac{S}{2} \\rfloor$ stones, and $S$ is even. It can be proven that the second player (HL) always wins. Let us prove by induction: When $S = 0$, the second player obviously wins. When $S \\geq 2$, consider the game state after the first player moves. If there is a pile that now has more than $\\lfloor \\frac{S}{2} \\rfloor$ stones, then we arrive back at case A where the next player to move wins. Otherwise, the second player can choose from any valid pile (note that the case condition implies that there are at least two non-empty piles before the first player's move). Now $S$ has been reduced by $2$, and every pile still has at most $\\lfloor \\frac{S}{2} \\rfloor$ stones. The condition allows us to assign a perfect matching of stones, where one stone is matched with exactly one stone from a different pile. A greedy way to create such a matching: Give each label $0, 1, \\dots, S - 1$ to a different stone so that for every pair of stones with labels $l < r$ that are from the same pile, stones $l + 1, l + 2, \\dots, r - 1$ are also from that pile; then match stones $i$ with $i + \\frac{S}{2}$ for all $0 \\le i < \\frac{S}{2}$. For every stone that the first player removes, the second player can always remove its matching stone, until the first player can no longer make a move and loses. Case C: Every pile has at most $\\lfloor \\frac{S}{2} \\rfloor$ stones, and $S$ is odd. The first player (T) can choose from any pile, and we arrive back at case B where the next player to move loses. So the first player (T) wins if and only if there is a pile that has more than $\\lfloor \\frac{S}{2} \\rfloor$ stones or $S$ is odd. This can be easily checked in $O(n)$.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    a = [int(x) for x in input().split()]\n\n    maxPile = max(a)\n    numStones = sum(a)\n\n    if maxPile * 2 > numStones or (numStones & 1):\n        print('T')\n    else:\n        print('HL')",
    "tags": [
      "brute force",
      "constructive algorithms",
      "games",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1396",
    "index": "C",
    "title": "Monster Invaders",
    "statement": "Ziota found a video game called \"Monster Invaders\".\n\nSimilar to every other shooting RPG game, \"Monster Invaders\" involves killing monsters and bosses with guns.\n\nFor the sake of simplicity, we only consider two different types of monsters and three different types of guns.\n\nNamely, the two types of monsters are:\n\n- a normal monster with $1$ hp.\n- a boss with $2$ hp.\n\nAnd the three types of guns are:\n\n- Pistol, deals $1$ hp in damage to one monster, $r_1$ reloading time\n- Laser gun, deals $1$ hp in damage to all the monsters in the current level (including the boss), $r_2$ reloading time\n- AWP, instantly kills any monster, $r_3$ reloading time\n\n\\textbf{The guns are initially not loaded, and the Ziota can only reload 1 gun at a time.}\n\nThe levels of the game can be considered as an array $a_1, a_2, \\ldots, a_n$, in which \\textbf{the $i$-th stage has $a_i$ normal monsters and 1 boss}. Due to the nature of the game, \\textbf{Ziota cannot use the Pistol (the first type of gun) or AWP (the third type of gun) to shoot the boss before killing all of the $a_i$ normal monsters}.\n\nIf Ziota damages the boss but does not kill it immediately, \\textbf{he is forced to move out of the current level to an arbitrary adjacent level} (adjacent levels of level $i$ $(1 < i < n)$ are levels $i - 1$ and $i + 1$, the only adjacent level of level $1$ is level $2$, the only adjacent level of level $n$ is level $n - 1$). Ziota can also choose to move to an adjacent level at any time. \\textbf{Each move between adjacent levels are managed by portals with $d$ teleportation time.}\n\nIn order not to disrupt the space-time continuum within the game, \\textbf{it is strictly forbidden to reload or shoot monsters during teleportation.}\n\nZiota starts the game at level 1. The objective of the game is rather simple, to kill all the bosses in all the levels. He is curious about the minimum time to finish the game (assuming it takes no time to shoot the monsters with a loaded gun and Ziota has infinite ammo on all the three guns). Please help him find this value.",
    "tutorial": "In this problem, it is useful to note that when the boss only has $1$ hp left, just use the pistol because it has the least reloading time. So there are 3 strategies we will use when playing at stage $i$ $(1 \\le i \\le n)$: Take $a_i$ pistol shots to kill first $a_i$ monsters and shoot the boss with the AWP. Take $a_i + 1$ pistol shots and move back to this stage later to take another pistol shot to finish the boss. Use the laser gun and move back to this stage later to kill the boss with a pistol shot. Observation: We will always finish the game at stage $n$ or $n - 1$. Considering we are at stage $i$ $(i \\le n - 1)$ and the boss at both stage $i$ stage $i - 1$ has $1$ hp left, we can spend $2 * d$ time to finish both these stages instead of going back later, which costs us exactly the same. Therefore, we will calculate $dp(i,0/1)$ as the minimum time to finish first $i - 1$ stages and 0/1 is the remaining hp of the boss at stage $i$. The transitions are easy to figure out by using 3 strategies as above. The only thing we should note is that we can actually finish the game at stage $n - 1$ by instantly kill the boss at stage $n$ with the AWP so we don't have to go back to this level later. Answer to the problem is $dp(n, 0)$. Time complexity: $O(n)$.",
    "code": "/*input\n4 2 4 4 1\n4 5 1 2\n*/\n#include <bits/stdc++.h>\nusing namespace std;\n\nint read() {\n\tint x = 0, c = getchar();\n\tfor(; !(c > 47 && c < 58); c = getchar());\n\tfor(; (c > 47 && c < 58); c = getchar()) x = x * 10 + c - 48;\n\treturn x;\n}\n\nvoid upd(long long &a, long long b) {\n\ta = (a < b) ? a : b;\n}\n\nconst int N = 1e6 + 5;\n\nlong long f[N][2];\nint n, r1, r2, r3, d, a[N];\n\nint main(){ \n\tn = read(), r1 = read(), r2 = read(), r3 = read(), d = read();\n\tfor(int i = 1; i <= n; a[i ++] = read());\n\n\tfor(int i = 2; i <= n; ++ i) f[i][0] = f[i][1] = 1e18;\n\n\tf[1][0] = 1ll * r1 * a[1] + r3;\n\tf[1][1] = min(0ll + r2, 1ll * r1 * a[1] + r1);\n\tfor(int i = 1; i < n; ++ i) {\n\t\t// 0 -> 0\n\t\t// so we clear this one and the next one as well\n\t\tupd(f[i + 1][0], f[i][0] + d + 1ll * r1 * a[i + 1] + r3);\n\n\t\t// 0 -> 1\n\t\t// this one is cleared, but next one isnt\n\t\tupd(f[i + 1][1], f[i][0] + d + min(0ll + r2, 1ll * r1 * a[i + 1] + r1));\n\t\t\n\t\t// 1 -> 0\n\t\tupd(f[i + 1][0], f[i][1] + d + 1ll * r1 * a[i + 1] + r3 + 2 * d + r1);\n\t\tupd(f[i + 1][0], f[i][1] + d + 1ll * r1 * a[i + 1] + r1 + d + r1 + d + r1);\n\t\tupd(f[i + 1][0], f[i][1] + d + r2 + d + r1 + d + r1);\n\n\t\t// 1 -> 1\n\t\tupd(f[i + 1][1], f[i][1] + d + r2 + d + r1 + d);\n\t\tupd(f[i + 1][1], f[i][1] + d + 1ll * r1 * a[i + 1] + r1 + d + r1 + d);\n\n\t\tif(i == n - 1) {\n\t\t\tupd(f[i + 1][0], f[i][1] + d + 1ll * r1 * a[i + 1] + r3 + d + r1);\n\t\t}\n\t}\n\tcout << f[n][0] << endl;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1396",
    "index": "D",
    "title": "Rainbow Rectangles",
    "statement": "Shrimpy Duc is a fat and greedy boy who is always hungry. After a while of searching for food to satisfy his never-ending hunger, Shrimpy Duc finds M&M candies lying unguarded on a $L \\times L$ grid. There are $n$ M&M candies on the grid, the $i$-th M&M is currently located at $(x_i + 0.5, y_i + 0.5),$ and has color $c_i$ out of a total of $k$ colors (the size of M&Ms are insignificant).\n\nShrimpy Duc wants to steal a \\textbf{rectangle} of M&Ms, specifically, he wants to select a rectangle with \\textbf{integer} coordinates within the grid and steal all candies within the rectangle. Shrimpy Duc doesn't need to steal every single candy, however, he would like to steal \\textbf{at least one candy for each color}.\n\nIn other words, he wants to select a rectangle whose sides are parallel to the coordinate axes and whose left-bottom vertex $(X_1, Y_1)$ and right-top vertex $(X_2, Y_2)$ are points with integer coordinates satisfying $0 \\le X_1 < X_2 \\le L$ and $0 \\le Y_1 < Y_2 \\le L$, so that for every color $1 \\le c \\le k$ there is at least one M&M with color $c$ that lies within that rectangle.\n\nHow many such rectangles are there? This number may be large, so you only need to find it modulo $10^9 + 7$.",
    "tutorial": "Let $xl, xr, yd, yu$ denote a rectangle with opposite corners $(xl, yd)$ and $(xr, yu)$. For convenience, assume $(xl \\le xr)$ and $(yd \\le yu)$. Let's try solving the problem if coordinates are in range $[1, n]$. We could easily do this by coordinates compression. First, let's look at the problem with $(yd, yu)$ fixed. We define $f_x$ to be the smallest integer such that $x \\le f_x$ and $(x, yd), (f_x, yu)$ is a $\\textbf{good}$ rectangle (If there is no such integer, let $f_x = inf$). It can be proven that $f_x$ is non-decreasing, i.e. if $x < y$, then $f_x \\le f_y$. Now, let's see how $f_x$ changes when we iterate $yd$ over a fixed $yu$. It is hard to add points to the set, so we will try to support deleting points operation. For point $i$, we have the following definitions: Let set $S = \\{ j | c_j = c_i, y_i < y_j \\le yu, x_j \\le x_i \\}$. Let $prv_i = j \\in S$ with the largest $x_j$. Let set $S' = \\{ j | c_j = c_i, y_i < y_j \\le yu, x_j \\ge x_i \\}$. Let $nxt_i = j \\in S'$ with the smallest $x_j$. (Note that $S$ or $S'$ might represent empty set). With these two functions, we could see how $f_x$ changes after we delete point $i$. It looks something like this: For every $xl \\in (x_{prv_i}, x_i]$ such that $f_{xl} \\ge x_i, f_{xl} = max(f_{xl}, x_{nxt_i})$; We could support this operation using segment tree with lazy propagation. The total time complexity is $O(n^2 \\cdot log_n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nconst int MOD = 1000000007;\n\nint L;\nll sum[8040];\nint len[8040];\nint last[8040];\nint lazy[8040];\n\nvoid init(int v, int l, int r, const vector<int> &xs) {\n   len[v] = xs[r] - xs[l - 1];\n   if (l < r) {\n      int md = (l + r) >> 1;\n      init(v << 1, l, md, xs);\n      init(v << 1 | 1, md + 1, r, xs);\n   }\n}\n\nvoid reset(int v, int l, int r, const vector<int> &go) {\n   lazy[v] = -1;\n   if (l == r) {\n      sum[v] = ll(len[v]) * (L - go[l]);\n      last[v] = go[l];\n      return;\n   }\n   int md = (l + r) >> 1;\n   reset(v << 1, l, md, go);\n   reset(v << 1 | 1, md + 1, r, go);\n   sum[v] = sum[v << 1] + sum[v << 1 | 1];\n   last[v] = last[v << 1 | 1];\n}\n\nvoid push(int v, int l, int r) {\n   if (lazy[v] != -1) {\n      last[v] = lazy[v];\n      sum[v] = ll(len[v]) * (L - lazy[v]);\n      if (l < r) {\n         lazy[v << 1] = lazy[v];\n         lazy[v << 1 | 1] = lazy[v];\n      }\n      lazy[v] = -1;\n   }\n}\n\nvoid modify(int v, int l, int r, int L, int R, int qv) {\n   push(v, l, r);\n   if (L > r || R < l) return;\n   if (L <= l && r <= R) {\n      lazy[v] = qv;\n      push(v, l, r);\n      return;\n   }\n   int md = (l + r) >> 1;\n   modify(v << 1, l, md, L, R, qv);\n   modify(v << 1 | 1, md + 1, r, L, R, qv);\n   sum[v] = sum[v << 1] + sum[v << 1 | 1];\n   last[v] = last[v << 1 | 1];\n}\n\nint walk(int v, int l, int r, int qv) {\n   push(v, l, r);\n   if (last[v] <= qv) return -1;\n   if (l == r) return l;\n   int md = (l + r) >> 1;\n   int ans = walk(v << 1, l, md, qv);\n   if (ans == -1) ans = walk(v << 1 | 1, md + 1, r, qv);\n   return ans;\n}\n\nint main() {\n   ios_base::sync_with_stdio(false); cin.tie(nullptr);\n   int N, K; cin >> N >> K >> L;\n   vector<int> X(N), Y(N), C(N);\n   vector<int> xs = {-1, L};\n   vector<int> ys = {-1, L};\n   for (int i = 0; i < N; ++i) {\n      cin >> X[i] >> Y[i] >> C[i];\n      --C[i];\n      xs.emplace_back(X[i]);\n      ys.emplace_back(Y[i]);\n   }\n   sort(xs.begin(), xs.end());\n   xs.resize(unique(xs.begin(), xs.end()) - xs.begin());\n   sort(ys.begin(), ys.end());\n   ys.resize(unique(ys.begin(), ys.end()) - ys.begin());\n   int NX = xs.size();\n   int NY = ys.size();\n   {\n      vector<int> order(N);\n      iota(order.begin(), order.end(), 0);\n      sort(order.begin(), order.end(), [&](int i, int j) {\n         return make_pair(Y[i], -X[i]) > make_pair(Y[j], -X[j]);\n      });\n      vector<int> newX(N), newY(N), newC(N);\n      for (int i = 0; i < N; ++i) {\n         newX[i] = X[order[i]];\n         newY[i] = Y[order[i]];\n         newC[i] = C[order[i]];\n      }\n      X.swap(newX), Y.swap(newY), C.swap(newC);\n   }\n   init(1, 1, NX - 2, xs);\n   int ans = 0;\n   for (int yr = 1; yr + 1 < NY; ++yr) {\n      vector<vector<int>> addAt(NX);\n      for (int i = 0; i < N; ++i) {\n         if (Y[i] <= ys[yr]) {\n            int xi = lower_bound(xs.begin(), xs.end(), X[i]) - xs.begin();\n            addAt[xi].emplace_back(C[i]);\n         }\n      }\n      int bad = K;\n      vector<int> cnts(K);\n      auto inc = [&](int z) {\n         if (++cnts[z] == 1) --bad;\n      };\n      auto dec = [&](int z) {\n         if (--cnts[z] == 0) ++bad;\n      };\n      vector<int> go(NX);\n      int ptr = 0;\n      for (int i = 1; i + 1 < NX; ++i) {\n         while (bad && ptr + 2 < NX) {\n            ptr++;\n            for (int z : addAt[ptr]) inc(z);\n         }\n         if (bad) go[i] = L;\n         else go[i] = xs[ptr];\n         for (int z : addAt[i]) dec(z);\n      }\n      reset(1, 1, NX - 2, go);\n      vector<int> prv(N);\n      vector<int> nxt(N);\n      vector<map<int, int>> mp(K);\n      for (int i = 0; i < N; ++i) {\n         if (Y[i] <= ys[yr]) {\n            auto it = mp[C[i]].lower_bound(X[i]);\n            if (it == mp[C[i]].end()) {\n               nxt[i] = -1;\n            } else {\n               nxt[i] = it->second;\n            }\n            it = mp[C[i]].upper_bound(X[i]);\n            if (it == mp[C[i]].begin()) {\n               prv[i] = -1;\n            } else {\n               prv[i] = prev(it)->second;\n            }\n            mp[C[i]][X[i]] = i;\n         }\n      }\n      auto remove = [&](int i) {\n         int xprv = (prv[i] == -1 ? -1 : X[prv[i]]);\n         int xcur = X[i];\n         int xnxt = (nxt[i] == -1 ? L : X[nxt[i]]);\n         int l =  lower_bound(xs.begin(), xs.end(), xprv) - xs.begin() + 1;\n         int r = walk(1, 1, NX - 2, xnxt);\n         if (r == -1) r = NX - 1; --r;\n         r = min(r, int(lower_bound(xs.begin(), xs.end(), xcur) - xs.begin()));\n         if (l <= r) modify(1, 1, NX - 2, l, r, xnxt);\n      };\n      ptr = N - 1;\n      for (int yl = 1; yl <= yr; ++yl) {\n         ll add = sum[1] % MOD * (ys[yr + 1] - ys[yr]) % MOD * (ys[yl] - ys[yl - 1]) % MOD;\n         ans = (ans + add) % MOD;\n         while (ptr >= 0 && Y[ptr] == ys[yl]) remove(ptr--);\n      }\n      assert(sum[1] == 0);\n   }\n   cout << ans << \"\\n\";\n   return 0;\n}",
    "tags": [
      "data structures",
      "sortings",
      "two pointers"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1396",
    "index": "E",
    "title": "Distance Matching",
    "statement": "You are given an integer $k$ and a tree $T$ with $n$ nodes ($n$ is even).\n\nLet $dist(u, v)$ be the number of edges on the shortest path from node $u$ to node $v$ in $T$.\n\nLet us define a undirected weighted complete graph $G = (V, E)$ as following:\n\n- $V = \\{x \\mid 1 \\le x \\le n \\}$ i.e. the set of integers from $1$ to $n$\n- $E = \\{(u, v, w) \\mid 1 \\le u, v \\le n, u \\neq v, w = dist(u, v) \\}$ i.e. there is an edge between every pair of distinct nodes, the weight being the distance between their respective nodes in $T$\n\nYour task is simple, find a perfect matching in $G$ with total edge weight $k$ $(1 \\le k \\le n^2)$.",
    "tutorial": "Root the tree at centroid $c$. First, determine if there is any matching that satisfies the requirement. Consider an edge $e$ that splits the tree into $2$ subtrees with sizes $x$ and $N - x$ respectively, let $z$ be the number of paths passing through $e$, then we have $z$ has the same parity as $x$ and $x \\% 2 \\le z \\le min(x, N - x)$. Thus the necessary condition for a matching is $\\sum (sub(v) \\% 2) \\le K \\le \\sum sub(v)$ and $K$ has the same parity as $\\sum sub(v)$, where $v \\ne c$ and $sub(v)$ is the size of the subtree rooted at $v$. We prove that this is also the sufficient condition by its construction: Consider the matching with maximum $K$, note that $c$ lies on all the paths in the matching. We can see that if we remove two vertices from the largest subtree, rooted at $w \\ne c$, then $c$ is still the centroid. Also, if we match two vertices $v$ and $u$ in the subtree rooted at $w$, the answer decreases by $2 \\cdot dist(c, lca(u, v))$. Based on this, we can achieve the target $K$ by repeating the following operation ($currentK$ is the current maximum possible $K$, initially $\\sum sub(v)$): Let $z$ be a non-leaf vertex in the largest subtree such that $dist(c, z) \\le \\frac{currentK - targetK}{2}$ (if there are many $z$, take any $z$ with maximum $dist(c, z)$). Match two vertices $v$ and $u$ whose LCA is $z$, then remove $v$ and $u$ from the tree. After some time $currentK = targetK$, so we just need to greedily match the remaining vertices to create the final matching. The final complexity is $O(N log N)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\n\nint main() {\n   ios_base::sync_with_stdio(false); cin.tie(nullptr);\n   int N; ll K;\n   cin >> N >> K;\n   vector<vector<int>> adj(N);\n   for (int i = 0; i < N - 1; ++i) {\n      int v, u;\n      cin >> v >> u;\n      adj[--v].emplace_back(--u);\n      adj[u].emplace_back(v);\n   }\n   vector<int> sz(N);\n   function<void(int, int)> dfs1 = [&](int v, int p) {\n      sz[v] = 1;\n      for (int u : adj[v]) if (u != p) {\n         dfs1(u, v);\n         sz[v] += sz[u];\n      }\n   };\n   dfs1(0, -1);\n   int root = 0;\n   for (int i = 1; i < N; ++i) {\n      if (sz[i] >= N / 2 && sz[i] < sz[root]) root = i;\n   }\n   vector<int> dist(N);\n   vector<int> top(N, -1);\n   vector<int> par(N, -1);\n   ll low = 0, high = 0;\n   function<void(int, int, int)> dfs2 = [&](int v, int p, int r) {\n      dist[v] = dist[p] + 1;\n      top[v] = r;\n      par[v] = p;\n      {\n         auto it = find(adj[v].begin(), adj[v].end(), p);\n         assert(it != adj[v].end());\n         adj[v].erase(it);\n      }\n      sz[v] = 1;\n      for (int u : adj[v]) {\n         dfs2(u, v, r);\n         sz[v] += sz[u];\n      }\n      low += (sz[v] & 1);\n      high += sz[v];\n   };\n   for (int v : adj[root]) {\n      dfs2(v, root, v);\n   }\n   if (low > K || high < K || (high - K) % 2) {\n      cout << \"NO\\n\";\n      return 0;\n   }\n   set<pair<int, int>> sizes;\n   for (int v : adj[root]) {\n      sizes.emplace(sz[v], v);\n   }\n   vector<set<pair<int, int>>> lcas(N);\n   vector<int> deg(N);\n   for (int v = 0; v < N; ++v) deg[v] = adj[v].size();\n   for (int v = 0; v < N; ++v) if (v != root) {\n      if (deg[v] == 0) {\n      } else {\n         lcas[top[v]].emplace(dist[v], v);\n      }\n   }\n   vector<bool> matched(N);\n   function<void(int)> kill = [&](int v) {\n      assert(deg[v] == 0);\n      if (--deg[par[v]] == 0) {\n         v = par[v];\n         lcas[top[v]].erase(pair<int, int>(dist[v], v));\n      }\n   };\n   cout << \"YES\\n\";\n   while (high > K) {\n      assert(sizes.size());\n      int v = (--sizes.end())->second;\n      sizes.erase(pair<int, int>(sz[v], v));\n      assert(lcas[v].size());\n      int mdist = (--lcas[v].end())->first;\n      if (high - 2 * mdist <= K) {\n         int x = lcas[v].lower_bound(pair<int, int>((high - K) / 2, -1))->second;\n         int y = -1;\n         for (int z : adj[x]) if (!matched[z]) {\n            y = z;\n            break;\n         }\n         high = K;\n         cout << x + 1 << \" \" << y + 1 << \"\\n\";\n         matched[x] = true;\n         matched[y] = true;\n         break;\n      } else {\n         high -= 2 * mdist;\n         assert(lcas[v].size());\n         int u = (--lcas[v].end())->second;\n         vector<int> nxts;\n         while (nxts.size() < 2 && adj[u].size()) {\n            int w = adj[u].back();\n            adj[u].pop_back();\n            if (!matched[w]) {\n               nxts.emplace_back(w);\n            }\n         }\n         if (nxts.size() < 2) nxts.emplace_back(u);\n         assert(nxts.size() == 2);\n         cout << nxts[0] + 1 << \" \" << nxts[1] + 1 << \"\\n\";\n         matched[nxts[0]] = true;\n         matched[nxts[1]] = true;\n         kill(nxts[0]);\n         kill(nxts[1]);\n         sz[v] -= 2;\n         if (sz[v]) sizes.emplace(sz[v], v);\n      }\n   }\n   vector<int> seq;\n   function<void(int)> dfs3 = [&](int v) {\n      if (!matched[v]) seq.emplace_back(v);\n      for (int u : adj[v]) dfs3(u);\n   };\n   dfs3(root);\n   int h = seq.size() / 2;\n   for (int i = 0; i < h; ++i) {\n      cout << seq[i] + 1 << \" \" << seq[i + h] + 1 << \"\\n\";\n   }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1397",
    "index": "A",
    "title": "Juggling Letters",
    "statement": "You are given $n$ strings $s_1, s_2, \\ldots, s_n$ consisting of lowercase Latin letters.\n\nIn one operation you can remove a character from a string $s_i$ and insert it to an arbitrary position in a string $s_j$ ($j$ may be equal to $i$). You may perform this operation any number of times. Is it possible to make all $n$ strings equal?",
    "tutorial": "If the total number of occurrences of some character $c$ is not a multiple of $n$, then it is impossible to make all $n$ strings equal - because then it is impossible for all $n$ strings to have the same number of $c$. On the other hand, if the total number of occurrences of every character $c$ is a multiple of $n$, then it is always possible to make all $n$ strings equal. To achieve this, for every character $c$ we move exactly ((the total number of occurrences of $c$) $/$ $n$) characters $c$ to the end of each string, and by the end we will have all $n$ strings equal each other. We can easily check if the condition satisfies by counting the total number of occurrences of each character $c$ and check its divisibility by $n$. The final complexity is $O(S \\cdot 26)$ or $O(S)$ where $S$ is the sum of lengths of all strings.",
    "code": "numTests = int(input())\nfor testNo in range(numTests):\n\tn = int(input())\n\tcnt = [0 for i in range(26)]\n\tfor _ in range(n):\n\t    s = input()\n\t    for i in s:\n\t        cnt[ord(i) - 97] += 1\n\n\tans = True\n\tfor i in range(26):\n\t    if cnt[i] % n != 0:\n\t        ans = False\n\t        break\n\n\tif ans:\n\t    print('YES')\n\telse:\n\t    print('NO')",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1397",
    "index": "B",
    "title": "Power Sequence",
    "statement": "Let's call a list of positive integers $a_0, a_1, ..., a_{n-1}$ a \\textbf{power sequence} if there is a positive integer $c$, so that for every $0 \\le i \\le n-1$ then $a_i = c^i$.\n\nGiven a list of $n$ positive integers $a_0, a_1, ..., a_{n-1}$, you are allowed to:\n\n- Reorder the list (i.e. pick a permutation $p$ of $\\{0,1,...,n - 1\\}$ and change $a_i$ to $a_{p_i}$), then\n- Do the following operation any number of times: pick an index $i$ and change $a_i$ to $a_i - 1$ or $a_i + 1$ (i.e. increment or decrement $a_i$ by $1$) with a cost of $1$.\n\nFind the minimum cost to transform $a_0, a_1, ..., a_{n-1}$ into a power sequence.",
    "tutorial": "First of all, the optimal way to reorder is to sort $a$ in non-decreasing order. Note that the cost the transform $a_i$ to $c^i$ is $\\lvert a_i - c^i \\rvert$. While there is a pair $(a_i, a_j)$ such that $i < j$ and $a_i > a_j$, swap $a_i$ and $a_j$. Since $\\lvert x \\rvert + \\lvert y \\rvert = max \\{ \\lvert x + y \\rvert, \\lvert x - y \\rvert \\}$, we have $\\lvert a_i - c^i \\rvert + \\lvert a_j - c^j \\rvert$ $= max \\{ \\lvert (a_i + a_j) - (c^i + c^j) \\rvert, \\lvert (a_i - a_j) - (c^i - c^j) \\rvert \\}$ $\\ge max \\{ \\lvert (a_j + a_i) - (c^i + c^j) \\rvert, \\lvert (a_j - a_i) - (c^i - c^j) \\rvert \\}$ $= \\lvert a_j - c^i \\rvert + \\lvert a_i - c^j \\rvert$ when $a_i > a_j$ and $c^i \\le c^j$, so the total cost does not increase. Hence, it is best to have $a_0 \\le a_1 \\le \\cdots \\le a_{n-1}$. From now on, we assume $a$ is sorted in non-decreasing order. Denote $a_{max} = a_{n - 1}$ as the maximum value in $a$, $f(x) = \\sum{\\lvert a_i - x^i \\rvert}$ as the minimum cost to transform $a$ into ${x^0, x^1, \\cdots, x^{n-1}}$, and $c$ as the value where $f(c)$ is minimum. Note that $c^{n - 1} - a_{max} \\le f(c) \\le f(1)$, which implies $c^{n - 1} \\le f(1) + a_{max}$. We enumerate $x$ from $1, 2, 3, \\dots$ until $x^{n - 1}$ exceeds $f(1) + a_{max}$, calculate $f(x)$ in $O(n)$, and the final answer is the minimum among all calculated values. The final complexity is $O(n \\cdot max(x))$. But why doesn't this get TLE? Because $f(1) = \\sum{(a_i - 1)} < a_{max} \\cdot n \\le 10^9 \\cdot n$, thus $x^{n - 1} \\le f(1) + a_{max} \\le 10^9 \\cdot (n + 1)$. When $n = 3, 4, 5, 6$, $max(x)$ does not exceed $63245, 1709, 278, 93$ respectively; so we can see that $O(n \\cdot max(x))$ comfortably fits in the time limit.",
    "code": "n = int(input())\na = [int(x) for x in input().split()]\na.sort()\ninf = 10**18\n\nif n <= 2:\n    print(a[0] - 1)\nelse:\n    ans = sum(a) - n\n\n    for x in range(1, 10**9):\n        curPow = 1\n        curCost = 0\n        for i in range(n):\n            curCost += abs(a[i] - curPow)\n            curPow *= x\n            if curPow > inf:\n                break\n\n        if curPow > inf:\n            break\n        if curPow / x > ans + a[n - 1]:\n            break\n\n        ans = min(ans, curCost)\n\n    print(ans)",
    "tags": [
      "brute force",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1398",
    "index": "A",
    "title": "Bad Triangle",
    "statement": "You are given an array $a_1, a_2, \\dots , a_n$, which is sorted in non-decreasing order ($a_i \\le a_{i + 1})$.\n\nFind three indices $i$, $j$, $k$ such that $1 \\le i < j < k \\le n$ and it is \\textbf{impossible} to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $a_i$, $a_j$ and $a_k$ (for example it is possible to construct a non-degenerate triangle with sides $3$, $4$ and $5$ but impossible with sides $3$, $4$ and $7$). If it is impossible to find such triple, report it.",
    "tutorial": "The triangle with side $a \\ge b \\ge c$ is degenerate if $a \\ge b + c$. So we have to maximize the length of the longest side ($a$) and minimize the total length of other sides ($b + c$). Thus, if $a_n \\ge a_1 + a_2$ then we answer if $1, 2, n$, otherwise the answer is -1.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    if a[0] + a[1] > a[-1]:\n        print(-1)\n    else:\n        print(1, 2, n)",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1398",
    "index": "B",
    "title": "Substring Removal Game",
    "statement": "Alice and Bob play a game. They have a binary string $s$ (a string such that each character in it is either $0$ or $1$). Alice moves first, then Bob, then Alice again, and so on.\n\nDuring their move, the player can choose any number (not less than one) of \\textbf{consecutive equal characters} in $s$ and delete them.\n\nFor example, if the string is $10110$, there are $6$ possible moves (deleted characters are bold):\n\n- $\\textbf{1}0110 \\to 0110$;\n- $1\\textbf{0}110 \\to 1110$;\n- $10\\textbf{1}10 \\to 1010$;\n- $101\\textbf{1}0 \\to 1010$;\n- $10\\textbf{11}0 \\to 100$;\n- $1011\\textbf{0} \\to 1011$.\n\nAfter the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $10\\textbf{11}0 \\to 1\\textbf{00} \\to 1$.\n\nThe game ends when the string becomes empty, and the score of each player is \\textbf{the number of $1$-characters deleted by them}.\n\nEach player wants to maximize their score. Calculate the resulting score of Alice.",
    "tutorial": "The following greedy strategy works: during each turn, delete the largest possible substring consisting of $1$-characters. So we have to find all blocks of $1$-characters, sort them according to their length and model which blocks are taken by Alice, and which - by Bob. Why does the greedy strategy work? It's never optimal to delete some part of the block of ones - because we either have to spend an additional turn to delete the remaining part, or allow our opponent to take it (which is never good). Why don't we need to delete zeroes? If we delete a whole block of zeroes, our opponent can take the newly formed block of $1$'s during their turn, and it is obviously worse than taking a part of that block. And deleting some part of a block of zeroes doesn't do anything - our opponent will never delete the remaining part because it's suboptimal.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tvector<int> a;\n\tforn(i, sz(s)) if (s[i] == '1') {\n\t\tint j = i;\n\t\twhile (j + 1 < sz(s) && s[j + 1] == '1')\n\t\t\t++j;\n\t\ta.push_back(j - i + 1);\n\t\ti = j;\n\t}\n\tsort(a.rbegin(), a.rend());\n\tint ans = 0;\n\tfor (int i = 0; i < sz(a); i += 2)\n\t\tans += a[i];\n\tcout << ans << endl;\n}\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile (T--) solve();\n}",
    "tags": [
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1398",
    "index": "C",
    "title": "Good Subarrays",
    "statement": "You are given an array $a_1, a_2, \\dots , a_n$ consisting of integers from $0$ to $9$. A subarray $a_l, a_{l+1}, a_{l+2}, \\dots , a_{r-1}, a_r$ is good if the sum of elements of this subarray is equal to the length of this subarray ($\\sum\\limits_{i=l}^{r} a_i = r - l + 1$).\n\nFor example, if $a = [1, 2, 0]$, then there are $3$ good subarrays: $a_{1 \\dots 1} = [1], a_{2 \\dots 3} = [2, 0]$ and $a_{1 \\dots 3} = [1, 2, 0]$.\n\nCalculate the number of good subarrays of the array $a$.",
    "tutorial": "We use zero indexing in this solution. We also use half-closed interval (so subarray $[l, r]$ is $a_l, a_{l + 1}, \\dots, a_{r-1}$). Let's precalculate the array $p$, where $p_i = \\sum\\limits_{j = 0}^{i - 1} a_j$ (so $p_x$ if sum of first $x$ elements of $a$). Then subarray $[l, r]$ is good if $p_r - p_l = r - l$, so $p_r - r = p_l - l$. Thus, we have to group all prefix by value $p_i - i$ for $i$ from $0$ to $n$. And if the have $x$ prefix with same value of $p_i - i$ then we have to add $\\frac{x (x-1)}{2}$ to the answer.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = input()\n    d = {0 : 1}\n    res, s = 0, 0\n    \n    for i in range(n):\n        s += int(a[i])\n        x = s - i - 1\n        if x not in d:\n            d[x] = 0\n        d[x] += 1\n        res += d[x] - 1\n        \n    print(res)",
    "tags": [
      "data structures",
      "dp",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1398",
    "index": "D",
    "title": "Colored Rectangles",
    "statement": "You are given three multisets of pairs of colored sticks:\n\n- $R$ pairs of red sticks, the first pair has length $r_1$, the second pair has length $r_2$, $\\dots$, the $R$-th pair has length $r_R$;\n- $G$ pairs of green sticks, the first pair has length $g_1$, the second pair has length $g_2$, $\\dots$, the $G$-th pair has length $g_G$;\n- $B$ pairs of blue sticks, the first pair has length $b_1$, the second pair has length $b_2$, $\\dots$, the $B$-th pair has length $b_B$;\n\nYou are constructing rectangles from these pairs of sticks with the following process:\n\n- take a pair of sticks of one color;\n- take a pair of sticks of another color different from the first one;\n- add the area of the resulting rectangle to the total area.\n\nThus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.\n\nEach pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.\n\nWhat is the maximum area you can achieve?",
    "tutorial": "Let's build some rectangles and take a look at the resulting pairings. For example, consider only red/green rectangles. Let the rectangles be $(r_{i1}, g_{i1})$, $(r_{i2}, g_{i2})$, .... Sort them in a non-decreasing order of $r_{ij}$. I claim that in the most optimal set $g_{ij}$ are also sorted in a non-decreasing order. It's easy to prove with some induction. Moreover, if there are some green or red sticks that are not taken and that are longer than the smallest taken corresponding sticks, then it's always optimal to take those instead. These facts helps us to conclude that from each set only some suffix of the largest sticks are taken. And they also give us the idea of the solution: sort the sticks in each set and pick the largest from any of the two sets into a pair until no pairs can be taken. However, the greedy approach of \"take from any two of the three sets\" is incorrect. We need to choose these two sets smartly. Let $dp[r][g][b]$ store the maximum total area that can be obtained by taking $r$ largest red sticks, $g$ largest green sticks and $b$ largest blue sticks. Each transition chooses a pair of colors and takes the next pairs in both of them. The answer is the maximum value in all the $dp$. Overall complexity: $O(RGB + R \\log R + G \\log G + B \\log B)$.",
    "code": "n = [int(x) for x in input().split()]\na = []\nfor i in range(3):\n\ta.append([int(x) for x in input().split()])\n\ta[i].sort(reverse=True)\n\ndp = [[[0 for i in range(n[2] + 1)] for j in range(n[1] + 1)] for k in range(n[0] + 1)]\nans = 0\nfor i in range(n[0] + 1):\n\tfor j in range(n[1] + 1):\n\t\tfor k in range(n[2] + 1):\n\t\t\tif i < n[0] and j < n[1]:\n\t\t\t\tdp[i + 1][j + 1][k] = max(dp[i + 1][j + 1][k], dp[i][j][k] + a[0][i] * a[1][j])\n\t\t\tif i < n[0] and k < n[2]:\n\t\t\t\tdp[i + 1][j][k + 1] = max(dp[i + 1][j][k + 1], dp[i][j][k] + a[0][i] * a[2][k])\n\t\t\tif j < n[1] and k < n[2]:\n\t\t\t\tdp[i][j + 1][k + 1] = max(dp[i][j + 1][k + 1], dp[i][j][k] + a[1][j] * a[2][k])\n\t\t\tans = max(ans, dp[i][j][k])\n\nprint(ans)",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1398",
    "index": "E",
    "title": "Two Types of Spells",
    "statement": "Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.\n\nThere are two types of spells: fire spell of power $x$ deals $x$ damage to the monster, and lightning spell of power $y$ deals $y$ damage to the monster and \\textbf{doubles} the damage of the next spell Polycarp casts. Each spell can be cast \\textbf{only once per battle}, but Polycarp can cast them in any order.\n\nFor example, suppose that Polycarp knows three spells: a fire spell of power $5$, a lightning spell of power $1$, and a lightning spell of power $8$. There are $6$ ways to choose the order in which he casts the spells:\n\n- first, second, third. This order deals $5 + 1 + 2 \\cdot 8 = 22$ damage;\n- first, third, second. This order deals $5 + 8 + 2 \\cdot 1 = 15$ damage;\n- second, first, third. This order deals $1 + 2 \\cdot 5 + 8 = 19$ damage;\n- second, third, first. This order deals $1 + 2 \\cdot 8 + 2 \\cdot 5 = 27$ damage;\n- third, first, second. This order deals $8 + 2 \\cdot 5 + 1 = 19$ damage;\n- third, second, first. This order deals $8 + 2 \\cdot 1 + 2 \\cdot 5 = 20$ damage.\n\nInitially, Polycarp knows $0$ spells. His spell set changes $n$ times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.",
    "tutorial": "Let's solve this problem for fixed set of spells. For example, we have a fireball spells with powers $f_1, f_2, \\dots , f_m$ and lighting spells with powers $l_1, l_2, \\dots, l_k$. We reach the maximum total damage if we can double all $k$ spells with maximum damage. It's possibly iff the set of $k$ largest by power spell (let's denote this set as $s$) contains at least one fireball spell. Otherwise (if set $s$ contains only lightning spells) the maximum damage reach when we double $k-1$ largest spells in set $s$ and one largest spell not from set $s$ (if such spell exist). Now how do you solve the original problem when spells are added and removed? All we have to do it maintain the set of $x$ largest by power spells (where $x$ is current number of lightning spells), and change this set by adding or removing one spell. Also you have to maintain the sum of spells power in set this set and the number of fireball spells in this set. You can do it by set in C++ or TreeSet on Java.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(1e5) + 9;\n\nint n;\nset <int> sDouble;\nlong long sum[2];\nset <int> s[2];\nint cntDouble[2];\n\n// 0: 0 -> 1\n// 1: 1 -> 0\nvoid upd(int id) {\n    assert(s[id].size() > 0);\n    int x = *s[id].rbegin();\n    if (id == 1) x = *s[id].begin();\n    bool d = sDouble.count(x);\n    \n    sum[id] -= x, sum[!id] += x;\n    s[id].erase(x), s[!id].insert(x);\n    cntDouble[id] -= d, cntDouble[!id] += d;\n}\n\n\nint main(){\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n        int tp, x;\n        cin >> tp >> x;// tp = 1 if double\n        \n        if (x > 0) {\n            sum[0] += x;\n            s[0].insert(x);\n            cntDouble[0] += tp;\n            if (tp) sDouble.insert(x);\n        } else {\n            x = -x;\n            int id = 0;\n            if (s[1].count(x)) id = 1;\n            else assert(s[0].count(x));\n            \n            sum[id] -= x;\n            s[id].erase(x);\n            cntDouble[id] -= tp;\n            if (tp) { \n                assert(sDouble.count(x));\n                sDouble.erase(x);\n            }\n        }\n        \n        int sumDouble = cntDouble[0] + cntDouble[1];\n        while (s[1].size() < sumDouble) upd(0);\n        while (s[1].size() > sumDouble) upd(1);\n        while (s[1].size() > 0 && s[0].size() > 0 && *s[0].rbegin() > *s[1].begin()) {\n            upd(0);\n            upd(1);\n        }\n        assert(s[1].size() == sumDouble);\n        \n        long long res = sum[0] + sum[1] * 2;\n        if (cntDouble[1] == sumDouble && sumDouble > 0) {\n            res -= *s[1].begin();\n            if (s[0].size() > 0) res += *s[0].rbegin();\n        }\n        cout << res << endl;\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1398",
    "index": "F",
    "title": "Controversial Rounds",
    "statement": "Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won $x$ rounds in a row. For example, if Bob won five rounds in a row and $x = 2$, then two sets ends.\n\nYou know that Alice and Bob have already played $n$ rounds, and you know the results of some rounds. For each $x$ from $1$ to $n$, calculate the maximum possible number of sets that could have already finished if each set lasts until one of the players wins $x$ rounds in a row. It is possible that the last set is still not finished — in that case, you should not count it in the answer.",
    "tutorial": "Let's consider the following function $f(pos, x)$: minimum index $npos$ such that there is a substring of string $s_{pos}, s_{pos+1}, \\dots, s_{npos-1}$ of length $x$ consisting of only characters $1$ and $?$ or $0$ and $?$. If this function has asymptotic $O(1)$ then we can solve problem for $O(n log n)$. Now, let's precalculate two array $nxt0$ and $nxt1$; $nxt0[i]$ is equal the maximum integer $len$ such that substring $s_i, s_{i+1}, \\dots, s_{i+len-1}$ consist only characters $1$ and $?$. $nxt1[i]$ is equal the maximum integer $len$ such that substring $s_i, s_{i+1}, \\dots, s_{i+len-1}$ consist only characters $0$ and $?$. Also let's precalculate the arrays $p0$ and $p1$ of size $n$; $p0[len]$ contain all positions $pos$ such that substring $s_{pos}, s_{pos+1}, \\dots, s_{pos+len-1}$ consist only characters $1$ and $?$ and $pos = 0$ or $s_{pos - 1} = 0$; $p1[len]$ contain all positions $pos$ such that substring $s_{pos}, s_{pos+1}, \\dots, s_{pos+len-1}$ consist only characters $0$ and $?$ and $pos = 0$ or $s_{pos - 1} = 1$. After that let's solve problem for some $x$. Suppose, that now we already processed first $pos$ elements of $s$. If $nxt0[pos] \\ge x$ or $nxt1[pos] \\ge x$ then we increase the answer and change $pos = pos + x$. Otherwise we have to find the minimum element (denote this element as $npos$) in $p0[x]$ or $p1[x]$ such that $npos \\ge pos$. If there is no such element then we found the final answer . Otherwise let's increase answer and change $pos = npos + x$ and continue this algorithm.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(1e6) + 99;\nconst int INF = int(1e9) + 99;\n\nint n;\nstring s;\nvector <int> p[2][N];\nint nxt[2][N];\nint ptr[2];\nchar buf[N];\n\nint main(){\n    cin >> n >> s;\n    \n    for (int i = n - 1; i >= 0; --i) {\n        if (s[i] != '0') nxt[0][i] = 1 + nxt[0][i + 1];\n        if (s[i] != '1') nxt[1][i] = 1 + nxt[1][i + 1];\n    }\n    \n    for (int b = 0; b <= 1; ++b) {\n        int l = 0;\n        while (l < n) {\n            if (s[l] == char('0' + b)) {\n                ++l;\n                continue;\n            }\n            int r = l + 1;\n            while (r < n && s[r] != char('0' + b)) ++r;\n            for (int len = 1; len <= r - l; ++len)\n                p[b][len].push_back(l);\n            l = r;\n        }\n    }\n\n    for (int len = 1; len <= n; ++len) {\n        int pos = 0, res = 0;\n        ptr[0] = ptr[1] = 0;\n        \n        while (pos < n) {\n            int npos = INF;\n            for (int b = 0; b <= 1; ++b) {\n                if (nxt[b][pos] >= len) \n                    npos = min(npos, pos + len);\n                while (ptr[b] < p[b][len].size() && pos > p[b][len][ ptr[b] ]) \n                    ++ptr[b];\n                if (ptr[b] < p[b][len].size()) \n                    npos = min(npos, p[b][len][ ptr[b] ] + len);\n            }\n            if (npos != INF) \n                ++res;\n            pos = npos;\n        }\n        \n        cout << res << ' ';\n    }\n    cout << endl;\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1398",
    "index": "G",
    "title": "Running Competition",
    "statement": "A running competition is going to be held soon. The stadium where the competition will be held can be represented by several segments on the coordinate plane:\n\n- two horizontal segments: one connecting the points $(0, 0)$ and $(x, 0)$, the other connecting the points $(0, y)$ and $(x, y)$;\n- $n + 1$ vertical segments, numbered from $0$ to $n$. The $i$-th segment connects the points $(a_i, 0)$ and $(a_i, y)$; $0 = a_0 < a_1 < a_2 < \\dots < a_{n - 1} < a_n = x$.\n\nFor example, here is a picture of the stadium with $x = 10$, $y = 5$, $n = 3$ and $a = [0, 3, 5, 10]$:\n\nA lap is a route that goes along the segments, starts and finishes at the same point, and never intersects itself (the only two points of a lap that coincide are its starting point and ending point). The length of a lap is a total distance travelled around it. For example, the red route in the picture representing the stadium is a lap of length $24$.\n\nThe competition will be held in $q$ stages. The $i$-th stage has length $l_i$, and the organizers want to choose a lap for each stage such that the length of the lap is a \\textbf{divisor of $l_i$}. The organizers don't want to choose short laps for the stages, so for each stage, they want to find the maximum possible length of a suitable lap.\n\nHelp the organizers to calculate the maximum possible lengths of the laps for the stages! In other words, for every $l_i$, find the maximum possible integer $L$ such that $l_i \\bmod L = 0$, and there exists a lap of length \\textbf{exactly} $L$.\n\nIf it is impossible to choose such a lap then print $-1$.",
    "tutorial": "First of all, let's find all possible lengths of the laps (after doing that, we can just check every divisor of $l_i$ to find the maximum possible length of a lap for a given query). A lap is always a rectangle - you can't construct a lap without using any vertical segments or using an odd number of vertical segments, and if you try to use $4$ or more vertical segments, you can't go back to the point where you started because both horizontal segments are already partially visited. So, a lap is a rectangle bounded by two vertical segments; and if we use vertical segments $i$ and $j$, the perimeter of this rectangle is $2(a_i - a_j + y)$. Let's find all values that can be represented as $a_i - a_j$. A naive $O(n^2)$ approach will be too slow, we have to speed it up somehow. Let's build an array $b$ of $n + 1$ numbers where $b_j = K - a_j$ ($K$ is some integer greater than $200000$). Each number that can be represented as $a_i - a_j$ can also be represented as $a_i + b_j - K$, so we have to find all possible sums of two elements belonging to different arrays. The key observation here is that, if $a_i$ and $b_j$ are small, we can treat each array as a polynomial: let $A(x) = \\sum \\limits_{i=0}^{n} x^{a_i}$, and similarly, $B(x) = \\sum \\limits_{j=0}^{n} x^{b_j}$. Let's look at the product of that polynomials. The coefficient for $x^k$ is non-zero if and only if there exist $i$ and $j$ such that $a_i + b_j = k$, so finding all possible sums (and all possible differences) can be reduced to multiplying two polynomials, which can be done faster than $O(n^2)$ using Karatsuba's algorithm or FFT.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < n; i++)\n#define sz(a) ((int)(a).size())\n\nconst int LOGN = 20;\nconst int N = (1 << LOGN);\nconst int K = 200043;\nconst int M = 1000043;\n\ntypedef double ld;\ntypedef long long li;\n\nconst ld PI = acos(-1.0);\n\nstruct comp \n{\n    ld x, y;\n    comp(ld x = .0, ld y = .0) : x(x), y(y) {}\n    inline comp conj() { return comp(x, -y); }\n};\n\ninline comp operator +(const comp &a, const comp &b) \n{\n    return comp(a.x + b.x, a.y + b.y);\n}\n\ninline comp operator -(const comp &a, const comp &b) \n{\n    return comp(a.x - b.x, a.y - b.y);\n}\n\ninline comp operator *(const comp &a, const comp &b) \n{\n    return comp(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);\n}\n\ninline comp operator /(const comp &a, const ld &b) \n{\n    return comp(a.x / b, a.y / b);\n}\n\nvector<comp> w[LOGN];\nvector<int> rv[LOGN];\n\nvoid precalc() \n{\n    for(int st = 0; st < LOGN; st++) \n    {\n        w[st].assign(1 << st, comp());\n        for(int k = 0; k < (1 << st); k++) \n        {\n            double ang = PI / (1 << st) * k;\n            w[st][k] = comp(cos(ang), sin(ang));\n        }\n        \n        rv[st].assign(1 << st, 0);\n        if(st == 0) \n        {\n            rv[st][0] = 0;\n            continue;\n        }\n        int h = (1 << (st - 1));\n        for(int k = 0; k < (1 << st); k++)\n            rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);\n    }\n}\n\ninline void fft(comp a[N], int n, int ln, bool inv) \n{\n    for(int i = 0; i < n; i++) \n    {\n        int ni = rv[ln][i];\n        if(i < ni)\n            swap(a[i], a[ni]);\n    }\n    \n    for(int st = 0; (1 << st) < n; st++) \n    {\n        int len = (1 << st);\n        for(int k = 0; k < n; k += (len << 1)) \n        {\n            for(int pos = k; pos < k + len; pos++) \n            {\n                comp l = a[pos];\n                comp r = a[pos + len] * (inv ? w[st][pos - k].conj() : w[st][pos - k]);\n                \n                a[pos] = l + r;\n                a[pos + len] = l - r;\n            }\n        }\n    }\n    \n    if(inv) for(int i = 0; i < n; i++)\n        a[i] = a[i] / n;\n}\n\ncomp aa[N];\ncomp bb[N];\ncomp cc[N];\n\ninline void multiply(comp a[N], int sza, comp b[N], int szb, comp c[N], int &szc) \n{\n    int n = 1, ln = 0;\n    while(n < (sza + szb))\n        n <<= 1, ln++;\n    for(int i = 0; i < n; i++)\n        aa[i] = (i < sza ? a[i] : comp());\n    for(int i = 0; i < n; i++)\n        bb[i] = (i < szb ? b[i] : comp());\n        \n    fft(aa, n, ln, false);\n    fft(bb, n, ln, false);\n    \n    for(int i = 0; i < n; i++)\n        cc[i] = aa[i] * bb[i];\n        \n    fft(cc, n, ln, true);\n    \n    szc = n;\n    for(int i = 0; i < n; i++)\n        c[i] = cc[i];\n}\n\ncomp a[N];\ncomp b[N];\ncomp c[N];\nint used[M];\nint dp[M];\n\nint main()\n{\n    precalc();\n    int n, x, y;\n    for(int i = 0; i < M; i++)\n        dp[i] = -1;\n    scanf(\"%d %d %d\", &n, &x, &y);\n    vector<int> A(n + 1);\n    for(int i = 0; i <= n; i++)\n        scanf(\"%d\", &A[i]);\n    for(int i = 0; i <= n; i++)\n    {\n        a[A[i]] = comp(1.0, 0.0);\n        b[K - A[i]] = comp(1.0, 0.0);\n    }\n    int s = 0;\n    multiply(a, K + 1, b, K + 1, c, s);\n    for(int i = K + 1; i < s; i++)\n        if(c[i].x > 0.5)\n            used[(i - K + y) * 2] = 1;\n    for(int i = 1; i < M; i++)\n    {\n        if(!used[i]) continue;\n        for(int j = i; j < M; j += i)\n            dp[j] = max(dp[j], i);\n    }\n    int q;\n    scanf(\"%d\", &q);\n    for(int i = 0; i < q; i++)\n    {\n        int l;\n        scanf(\"%d\", &l);\n        printf(\"%d \", dp[l]);\n    }\n}",
    "tags": [
      "bitmasks",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1399",
    "index": "A",
    "title": "Remove Smallest",
    "statement": "You are given the array $a$ consisting of $n$ positive (greater than zero) integers.\n\nIn one move, you can choose two indices $i$ and $j$ ($i \\ne j$) such that the absolute difference between $a_i$ and $a_j$ is no more than one ($|a_i - a_j| \\le 1$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).\n\nYour task is to find if it is possible to obtain the array consisting of \\textbf{only one element} using several (possibly, zero) such moves or not.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, let's sort the initial array. Then it's obvious that the best way to remove elements is from smallest to biggest. And if there is at least one $i$ such that $2 \\le i \\le n$ and $a_i - a_{i-1} > 1$ then the answer is \"NO\", because we have no way to remove $a_{i-1}$. Otherwise, the answer is \"YES\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tsort(a.begin(), a.end());\n\t\tbool ok = true;\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tok &= (a[i] - a[i - 1] <= 1);\n\t\t}\n\t\tif (ok) cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1399",
    "index": "B",
    "title": "Gifts Fixing",
    "statement": "You have $n$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $i$-th gift consists of $a_i$ candies and $b_i$ oranges.\n\nDuring one move, you can choose some gift $1 \\le i \\le n$ and do one of the following operations:\n\n- eat exactly \\textbf{one candy} from this gift (decrease $a_i$ by one);\n- eat exactly \\textbf{one orange} from this gift (decrease $b_i$ by one);\n- eat exactly \\textbf{one candy} and exactly \\textbf{one orange} from this gift (decrease both $a_i$ and $b_i$ by one).\n\nOf course, you can not eat a candy or orange if it's not present in the gift (so neither $a_i$ nor $b_i$ can become less than zero).\n\nAs said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: $a_1 = a_2 = \\dots = a_n$ and $b_1 = b_2 = \\dots = b_n$ (and $a_i$ equals $b_i$ is \\textbf{not necessary}).\n\nYour task is to find the \\textbf{minimum} number of moves required to equalize all the given gifts.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "At first, consider the problems on candies and oranges independently. Then it's pretty obvious that for candies the optimal way is to decrease all $a_i$ to the value $min(a)$ (we need obtain at least this value to equalize all the elements and there is no point to decrease elements further). The same works for the array $b$. Then, if we unite these two problems, we need to take the maximum moves we need for each $i$, because we need exactly that amount of moves to decrease $a_i$ to $min(a)$ and $b_i$ to $min(b)$ simultaneously. So, the answer is $\\sum\\limits_{i=1}^{n} max(a_i - min(a), b_i - min(b))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n), b(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tfor (auto &it : b) cin >> it;\n\t\tint mna = *min_element(a.begin(), a.end());\n\t\tint mnb = *min_element(b.begin(), b.end());\n\t\tlong long ans = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tans += max(a[i] - mna, b[i] - mnb);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1399",
    "index": "C",
    "title": "Boats Competition",
    "statement": "There are $n$ people who want to participate in a boat competition. The weight of the $i$-th participant is $w_i$. Only teams consisting of \\textbf{two} people can participate in this competition. As an organizer, you think that it's fair to allow only teams with \\textbf{the same total weight}.\n\nSo, if there are $k$ teams $(a_1, b_1)$, $(a_2, b_2)$, $\\dots$, $(a_k, b_k)$, where $a_i$ is the weight of the first participant of the $i$-th team and $b_i$ is the weight of the second participant of the $i$-th team, then the condition $a_1 + b_1 = a_2 + b_2 = \\dots = a_k + b_k = s$, where $s$ is the total weight of \\textbf{each} team, should be satisfied.\n\nYour task is to choose such $s$ that the number of teams people can create is the \\textbf{maximum} possible. Note that each participant can be in \\textbf{no more than one} team.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "This is just an implementation problem. Firstly, let's fix $s$ (it can be in range $[2; 2n]$), find the maximum number of boats we can obtain with this $s$ and choose the maximum among all found values. To find the number of pairs, let's iterate over the smallest weight in the team in range $[1; \\lfloor\\frac{s + 1}{2}\\rfloor - 1]$. Let this weight be $i$. Then (because the sum of weights is $s$) the biggest weight is $s-i$. And the number of pairs we can obtain with such two weights and the total weight $s$ is $min(cnt_i, cnt_{s - i})$, where $cnt_i$ is the number of occurrences of $i$ in $w$. And the additional case: if $s$ is even, we need to add $\\lfloor\\frac{cnt_{\\frac{s}{2}}}{2}\\rfloor$. Don't forget that there is a case $s - i > n$, so you need to assume that these values $cnt$ are zeros.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> cnt(n + 1);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\t++cnt[x];\n\t\t}\n\t\tint ans = 0;\n\t\tfor (int s = 2; s <= 2 * n; ++s) {\n\t\t\tint cur = 0;\n\t\t\tfor (int i = 1; i < (s + 1) / 2; ++i) {\n\t\t\t\tif (s - i > n) continue;\n\t\t\t\tcur += min(cnt[i], cnt[s - i]);\n\t\t\t}\n\t\t\tif (s % 2 == 0) cur += cnt[s / 2] / 2;\n\t\t\tans = max(ans, cur);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1399",
    "index": "D",
    "title": "Binary String To Subsequences",
    "statement": "You are given a binary string $s$ consisting of $n$ zeros and ones.\n\nYour task is to divide the given string into the \\textbf{minimum} number of \\textbf{subsequences} in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like \"010101 ...\" or \"101010 ...\" (i.e. the subsequence should not contain two adjacent zeros or ones).\n\nRecall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of \"1011101\" are \"0\", \"1\", \"11111\", \"0111\", \"101\", \"1001\", but not \"000\", \"101010\" and \"11100\".\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let's iterate over all characters of $s$ from left to right, maintaining two arrays $pos_0$ and $pos_1$, where $pos_0$ stores indices of all subsequences which end with '0' and $pos_1$ stores indices of all subsequences which end with '1'. If we met '0', then the best choice is to append it to some existing subsequence which ends with '1'. If there are no such sequences, we need to create new one which ends with '0'. Otherwise we need to convert one of '1'-sequences to '0'-sequence. The same works with characters '1'. So, when we don't need to create the new sequence, we try to don't do that. And values in arrays $pos_0$ and $pos_1$ help us to determine the number of sequence we assign to each character. And also, there is a cute proof of this solution from Gassa: let $f(i)$ be the difference between the number of '1' and the number of '0' on the prefix of $s$ of length $i$. We claim that the answer is $max(f(i)) - min(f(i))$ and let's show why is it true. Let's build a function on a plane with points $(i, f(i))$. Then we can match each $x$ between $min(f(i))$ and $max(f(i))$ with some subsequence.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tstring s;\n\t\tcin >> n >> s;\n\t\tvector<int> ans(n);\n\t\tvector<int> pos0, pos1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint newpos = pos0.size() + pos1.size();\n\t\t\tif (s[i] == '0') {\n\t\t\t\tif (pos1.empty()) {\n\t\t\t\t\tpos0.push_back(newpos);\n\t\t\t\t} else {\n\t\t\t\t\tnewpos = pos1.back();\n\t\t\t\t\tpos1.pop_back();\n\t\t\t\t\tpos0.push_back(newpos);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (pos0.empty()) {\n\t\t\t\t\tpos1.push_back(newpos);\n\t\t\t\t} else {\n\t\t\t\t\tnewpos = pos0.back();\n\t\t\t\t\tpos0.pop_back();\n\t\t\t\t\tpos1.push_back(newpos);\n\t\t\t\t}\n\t\t\t}\n\t\t\tans[i] = newpos;\n\t\t}\n\t\tcout << pos0.size() + pos1.size() << endl;\n\t\tfor (auto it : ans) cout << it + 1 << \" \";\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1399",
    "index": "E1",
    "title": "Weights Division (easy version)",
    "statement": "\\textbf{Easy and hard versions are actually different problems, so we advise you to read both statements carefully}.\n\nYou are given a weighted rooted tree, vertex $1$ is the root of this tree.\n\nA tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $v$ is the last different from $v$ vertex on the path from the root to the vertex $v$. Children of vertex $v$ are all vertices for which $v$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.\n\nThe weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $0$.\n\nYou can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $2$ rounding down. More formally, during one move, you choose some edge $i$ and divide its weight by $2$ rounding down ($w_i := \\left\\lfloor\\frac{w_i}{2}\\right\\rfloor$).\n\nYour task is to find the minimum number of \\textbf{moves} required to make the \\textbf{sum of weights of paths} from the root to each leaf at most $S$. In other words, if $w(i, j)$ is the weight of the path from the vertex $i$ to the vertex $j$, then you have to make $\\sum\\limits_{v \\in leaves} w(root, v) \\le S$, where $leaves$ is the list of all leaves.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let's define $cnt_i$ as the number of leaves in the subtree of the $i$-th edge (of course, in terms of vertices, in the subtree of the lower vertex of this edge). Values of $cnt$ can be calculated with pretty standard and simple dfs and dynamic programming. Then we can notice that our edges are independent and we can consider the initial answer (sum of weights of paths) as $\\sum\\limits_{i=1}^{n-1} w_i \\cdot cnt_i$. Let $diff(i)$ be the difference between the current impact of the $i$-th edge and the impact of the $i$-th edge if we divide its weight by $2$. $diff(i) = w_i \\cdot cnt_i - \\lfloor\\frac{w_i}{2}\\rfloor \\cdot cnt_i$. This value means how the sum of weights decreases if we divide the weight of the $i$-th edge by $2$. Create ordered set which contains pairs $(diff(i), i)$. Then the following greedy solution works: let's take the edge with maximum $diff(i)$ and divide its weight by $2$. Then re-add it into the set with new value $diff(i)$. When the sum becomes less than or equal to $S$, just stop and print the number of divisions we made. The maximum number of operations can reach $O(n \\log w)$ so the solution complexity is $O(n \\log{w} \\log{n})$ (each operation takes $O(\\log{n})$ time because the size of the set is $O(n)$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> w, cnt;\nvector<vector<pair<int, int>>> g;\n\nlong long getdiff(int i) {\n\treturn w[i] * 1ll * cnt[i] - (w[i] / 2) * 1ll * cnt[i];\n}\n\nvoid dfs(int v, int p = -1) {\n\tif (g[v].size() == 1) cnt[p] = 1;\n\tfor (auto [to, id] : g[v]) {\n\t\tif (id == p) continue;\n\t\tdfs(to, id);\n\t\tif (p != -1) cnt[p] += cnt[id];\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tlong long s;\n\t\tcin >> n >> s;\n\t\tw = cnt = vector<int>(n - 1);\n\t\tg = vector<vector<pair<int, int>>>(n);\n\t\tfor (int i = 0; i < n - 1; ++i) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y >> w[i];\n\t\t\t--x, --y;\n\t\t\tg[x].push_back({y, i});\n\t\t\tg[y].push_back({x, i});\n\t\t}\n\t\tdfs(0);\n\t\tset<pair<long long, int>> st;\n\t\tlong long cur = 0;\n\t\tfor (int i = 0; i < n - 1; ++i) {\n\t\t\tst.insert({getdiff(i), i});\n\t\t\tcur += w[i] * 1ll * cnt[i];\n\t\t}\n\t\tcerr << cur << endl;\n\t\tint ans = 0;\n\t\twhile (cur > s) {\n\t\t\tint id = st.rbegin()->second;\n\t\t\tst.erase(prev(st.end()));\n\t\t\tcur -= getdiff(id);\n\t\t\tw[id] /= 2;\n\t\t\tst.insert({getdiff(id), id});\n\t\t\t++ans;\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1399",
    "index": "E2",
    "title": "Weights Division (hard version)",
    "statement": "\\textbf{Easy and hard versions are actually different problems, so we advise you to read both statements carefully}.\n\nYou are given a weighted rooted tree, vertex $1$ is the root of this tree. \\textbf{Also, each edge has its own cost}.\n\nA tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $v$ is the last different from $v$ vertex on the path from the root to the vertex $v$. Children of vertex $v$ are all vertices for which $v$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.\n\nThe weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $0$.\n\nYou can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $2$ rounding down. More formally, during one move, you choose some edge $i$ and divide its weight by $2$ rounding down ($w_i := \\left\\lfloor\\frac{w_i}{2}\\right\\rfloor$).\n\nEach edge $i$ has an associated cost $c_i$ which is either $1$ or $2$ coins. Each move with edge $i$ costs $c_i$ coins.\n\nYour task is to find the minimum total \\textbf{cost} to make the \\textbf{sum of weights of paths} from the root to each leaf at most $S$. In other words, if $w(i, j)$ is the weight of the path from the vertex $i$ to the vertex $j$, then you have to make $\\sum\\limits_{v \\in leaves} w(root, v) \\le S$, where $leaves$ is the list of all leaves.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Read the easy version editorial first, because almost all solution is the solution to the easy version with little changes. Firstly, let's simulate the greedy process we used to solve the easy version problem, for edges with cost $1$ and edges with cost $2$, independently. But we don't stop when our sum reach something, let's simulate until our sum becomes $0$ and store each intermediate result in the array $v_1$ for edges with cost $1$ and $v_2$ for edges with cost $2$. So, the array $v_1$ contains the initial total impact of edges of cost $1$, then the impact after making one move, two moves, and so on... The same with $v_2$ but for edges with cost $2$. Now let's fix how many moves on edges with cost $1$ we do. Let it be $i$ (and arrays $v_1$ and $v_2$ are $0$-indexed). Then the sum we obtain from the $1$-cost edges is $v_1[i]$. So we need to find the minimum number of moves $p$ we can do on $2$-cost edges so that $v_1[i] + v_2[p] \\le S$. This can be done using binary search or moving pointer (if we iterate over $i$ in increasing order, place $p$ at the end of $v_2$ and move it to the left while $v_1[i] + v_2[p] \\le S$). Then, if $v_1[i] + v_2[p] \\le S$, we can update the answer with the value $i + 2p$. Time complexity is actually the same as in easy version of the problem: $O(n \\log{w} \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint n;\nvector<int> w, c, cnt;\nvector<vector<pair<int, int>>> g;\n\nlong long getdiff(int i) {\n\treturn w[i] * 1ll * cnt[i] - (w[i] / 2) * 1ll * cnt[i];\n}\n\nvoid dfs(int v, int p = -1) {\n\tif (g[v].size() == 1) cnt[p] = 1;\n\tfor (auto [to, id] : g[v]) {\n\t\tif (id == p) continue;\n\t\tdfs(to, id);\n\t\tif (p != -1) cnt[p] += cnt[id];\n\t}\n}\n\nvector<long long> get(int clr) {\n\tset<pair<long long, int>> st;\n\tlong long cur = 0;\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tif (c[i] == clr) {\n\t\t\tst.insert({getdiff(i), i});\n\t\t\tcur += w[i] * 1ll * cnt[i];\n\t\t}\n\t}\n\tvector<long long> res;\n\tres.push_back(cur);\n\twhile (cur > 0 && !st.empty()) {\n\t\tint id = st.rbegin()->second;\n\t\tst.erase(prev(st.end()));\n\t\tcur -= getdiff(id);\n\t\tres.push_back(cur);\n\t\tw[id] /= 2;\n\t\tst.insert({getdiff(id), id});\n\t}\n\treturn res;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tlong long s;\n\t\tcin >> n >> s;\n\t\tw = c = cnt = vector<int>(n - 1);\n\t\tg = vector<vector<pair<int, int>>>(n);\n\t\tfor (int i = 0; i < n - 1; ++i) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y >> w[i] >> c[i];\n\t\t\t--x, --y;\n\t\t\tg[x].push_back({y, i});\n\t\t\tg[y].push_back({x, i});\n\t\t}\n\t\tdfs(0);\n\t\tvector<long long> v1 = get(1), v2 = get(2);\n\t\tint pos = int(v2.size()) - 1;\n\t\tint ans = INF;\n\t\tfor (int i = 0; i < int(v1.size()); ++i) {\n\t\t\twhile (pos > 0 && v1[i] + v2[pos - 1] <= s) --pos;\n\t\t\tif (v1[i] + v2[pos] <= s) {\n\t\t\t\tans = min(ans, i + pos * 2);\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "greedy",
      "sortings",
      "trees",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1399",
    "index": "F",
    "title": "Yet Another Segments Subset",
    "statement": "You are given $n$ segments on a coordinate axis $OX$. The $i$-th segment has borders $[l_i; r_i]$. All points $x$, for which $l_i \\le x \\le r_i$ holds, belong to the $i$-th segment.\n\nYour task is to choose the \\textbf{maximum} by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.\n\nTwo segments $[l_i; r_i]$ and $[l_j; r_j]$ are non-intersecting if they have \\textbf{no common points}. For example, segments $[1; 2]$ and $[3; 4]$, $[1; 3]$ and $[5; 5]$ are non-intersecting, while segments $[1; 2]$ and $[2; 3]$, $[1; 2]$ and $[2; 2]$ are intersecting.\n\nThe segment $[l_i; r_i]$ lies inside the segment $[l_j; r_j]$ if $l_j \\le l_i$ and $r_i \\le r_j$. For example, segments $[2; 2]$, $[2, 3]$, $[3; 4]$ and $[2; 4]$ lie inside the segment $[2; 4]$, while $[2; 5]$ and $[1; 4]$ are not.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, let's compress the given borders of segments (just renumerate them in such a way that the maximum value is the minimum possible and the relative order of integers doesn't change). Pretty standard approach. Now let's do recursive dynamic programming $dp_{l, r}$. This state stores the answer for the segment $[l; r]$ (not necessarily input segment!). How about transitions? Firstly, if there is a segment covering the whole segment $[l; r]$, why don't just take it? It doesn't change anything for us. The first transition is just skip the current left border and try to take the additional answer from the state $dp_{l + 1, r}$. The second transition is the following: let's iterate over all possible segments starting at $l$ (we can store all right borders of such segments in some array $rg_l$). Let the current segment be $[l; nr]$. If $nr \\ge r$, just skip it (if $nr > r$ then we can't take this segment into the answer because it's out of $[l; r]$, and if $nr = r$ then we can't take it because we considered it already). Then we can take two additional answers: from $dp_{l, nr}$ and from $dp_{nr + 1, r}$. Don't forger about some corner cases, like when $nr + 1 > r$ or $l + 1 > r$ and something like that. You can get the answer if you run the calculation from the whole segment. What is the time complexity of this solution? We obviously have $O(n^2)$ states. And the number of transitions is also pretty easy to calculate. Let's fix some right border $r$. For this right border, we consider $O(n)$ segments in total. Summing up, we get $O(n^2)$ transitions. So the time complexity is $O(n^2)$. P.S. I am sorry about pretty tight ML (yeah, I saw Geothermal got some memory issues because of using map). I really wanted to make it 512MB but just forgot to do that.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<vector<int>> rg;\nvector<vector<int>> dp;\n\nint calc(int l, int r) {\n\tif (dp[l][r] != -1) return dp[l][r];\n\tdp[l][r] = 0;\n\tif (l > r) return dp[l][r];\n\tbool add = count(rg[l].begin(), rg[l].end(), r); // can't be greater than 1\n\tdp[l][r] = max(dp[l][r], add + (l + 1 > r ? 0 : calc(l + 1, r)));\n\tfor (auto nr : rg[l]) {\n\t\tif (nr >= r) continue;\n\t\tdp[l][r] = max(dp[l][r], add + calc(l, nr) + (nr + 1 > r ? 0 : calc(nr + 1, r)));\n\t}\n\treturn dp[l][r];\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> l(n), r(n);\n\t\tvector<int> val;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcin >> l[i] >> r[i];\n\t\t\tval.push_back(l[i]);\n\t\t\tval.push_back(r[i]);\n\t\t}\n\t\tsort(val.begin(), val.end());\n\t\tval.resize(unique(val.begin(), val.end()) - val.begin());\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tl[i] = lower_bound(val.begin(), val.end(), l[i]) - val.begin();\n\t\t\tr[i] = lower_bound(val.begin(), val.end(), r[i]) - val.begin();\n\t\t}\n\t\tint siz = val.size();\n\t\tdp = vector<vector<int>>(siz, vector<int>(siz, -1));\n\t\trg = vector<vector<int>>(siz);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\trg[l[i]].push_back(r[i]);\n\t\t}\n\t\tcout << calc(0, siz - 1) << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "graphs",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1400",
    "index": "A",
    "title": "String Similarity",
    "statement": "A binary string is a string where each character is either 0 or 1. Two binary strings $a$ and $b$ of equal length are similar, if they have the same character in some position (there exists an integer $i$ such that $a_i = b_i$). For example:\n\n- 10010 and 01111 are similar (they have the same character in position $4$);\n- 10010 and 11111 are similar;\n- 111 and 111 are similar;\n- 0110 and 1001 are not similar.\n\nYou are given an integer $n$ and a binary string $s$ consisting of $2n-1$ characters. Let's denote $s[l..r]$ as the contiguous substring of $s$ starting with $l$-th character and ending with $r$-th character (in other words, $s[l..r] = s_l s_{l + 1} s_{l + 2} \\dots s_r$).\n\nYou have to construct a binary string $w$ of length $n$ which is similar to \\textbf{all of the following strings}: $s[1..n]$, $s[2..n+1]$, $s[3..n+2]$, ..., $s[n..2n-1]$.",
    "tutorial": "There are many ways to solve this problem: let the answer be $s_1 s_3 s_5 \\dots s_{2n-1}$, so it coincides with $s[1..n]$ in the first character, with $s[2..n+1]$ in the second character, and so on; copy the character $s_n$ $n$ times, since it appears in every substring we are interested in; find the character that occurs at least $n$ times in $s$, and build the answer by copying it $n$ times; and many others.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val c = readLine()!!.groupingBy { it }.eachCount().maxBy { it.value }!!.key\n        println(c.toString().repeat(n))\n    }\n}",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1400",
    "index": "B",
    "title": "RPG Protagonist",
    "statement": "You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.\n\nYou decided to rob a town's blacksmith and you take a follower with you. You can carry at most $p$ units and your follower — at most $f$ units.\n\nIn the blacksmith shop, you found $cnt_s$ swords and $cnt_w$ war axes. Each sword weights $s$ units and each war axe — $w$ units. You don't care what to take, since each of them will melt into one steel ingot.\n\nWhat is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?",
    "tutorial": "Let's say (without loss of generality) that $s \\le w$ (a sword is lighter than a war axe). If not, then we can swap swords and axes. Now, let's iterate over the number of swords $s_1$ we will take ourselves. We can take at least $0$ and at most $\\min(cnt_s, \\frac{p}{s})$ swords. If we have taken $s_1$ swords, then we can fill the remaining capacity with axes, i. e. we can take $w_1 = \\min(cnt_w, \\frac{p - s_1 \\cdot s}{w})$ axes. The last thing is to decide, what the follower will take: since swords are lighter, it's optimal to take as many swords as possible, i. e. to take $s_2 = \\min(cnt_s - s_1, \\frac{f}{s})$ swords and fill the remaining space with war axes, i. e. to take $w_2 = \\min(cnt_w - w_1, \\frac{f - s_2 \\cdot s}{w})$ axes. In other words, if we fix the number of swords $s_1$ we'll take $s_1 + s_2 + w_1 + w_2$ weapons in total. The result complexity is $O(cnt_s)$.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (p, f) = readLine()!!.split(' ').map { it.toInt() }\n        var (cntS, cntW) = readLine()!!.split(' ').map { it.toInt() }\n        var (s, w) = readLine()!!.split(' ').map { it.toInt() }\n        \n        if (s > w) {\n            s = w.also { w = s }\n            cntS = cntW.also { cntW = cntS }\n        }\n\n        var ans = 0\n        for (s1 in 0..minOf((p / s), cntS)) {\n            val w1 = minOf(cntW, (p - s * s1) / w)\n            val s2 = minOf(cntS - s1, f / s)\n            val w2 = minOf(cntW - w1, (f - s * s2) / w)\n            ans = maxOf(ans, s1 + s2 + w1 + w2)\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1400",
    "index": "C",
    "title": "Binary String Reconstruction",
    "statement": "Consider the following process. You have a binary string (a string where each character is either 0 or 1) $w$ of length $n$ and an integer $x$. You build a new binary string $s$ consisting of $n$ characters. The $i$-th character of $s$ is chosen as follows:\n\n- if the character $w_{i-x}$ exists and is equal to 1, then $s_i$ is 1 (formally, if $i > x$ and $w_{i-x} = $ 1, then $s_i = $ 1);\n- if the character $w_{i+x}$ exists and is equal to 1, then $s_i$ is 1 (formally, if $i + x \\le n$ and $w_{i+x} = $ 1, then $s_i = $ 1);\n- if both of the aforementioned conditions are false, then $s_i$ is 0.\n\nYou are given the integer $x$ and the resulting string $s$. Reconstruct the original string $w$.",
    "tutorial": "At first, let's replace all elements of string $w$ by 1. Now, let's consider all indices $i$ such that $s_i = 0$. If $s_i = 0$, then $w_{i - x}$ must be equal to 0 (if it exists) and $w_{i + x}$ must be equal to 0 (if it exists), so let's replace all such elements by 0. And after let's perform the process described in statement on string $w$. If we get the string $s$, then we can print $w$ as the answer, otherwise the answer is $-1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t;\nstring s;\nint x;\n\nstring f(string s) {\n    string res = s;\n    for (int i = 0; i < s.size(); ++i) {\n        if (i - x >= 0 && s[i - x] == '1' || i + x < s.size() && s[i + x] == '1')\n            res[i] = '1';\n        else\n            res[i] = '0';\n    }\n    return res;\n}\n\nint main() {    \n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        cin >> s >> x;\n        int n = s.size();\n \n        string ns = string(n, '1');\n        for (int i = 0; i < n; ++i) {\n            if (s[i] == '0') {\n                if (i - x >= 0) ns[i - x] = '0';\n                if (i + x < n) ns[i + x] = '0';\n            }\n        }\n        if (f(ns) == s) cout << ns << endl;\n        else cout << -1 << endl;\n    }\n    return 0;\n}",
    "tags": [
      "2-sat",
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1400",
    "index": "D",
    "title": "Zigzags",
    "statement": "You are given an array $a_1, a_2 \\dots a_n$. Calculate the number of tuples $(i, j, k, l)$ such that:\n\n- $1 \\le i < j < k < l \\le n$;\n- $a_i = a_k$ and $a_j = a_l$;",
    "tutorial": "Let's iterate indices $j$ and $k$. For simplicity, for each $j$ we'll iterate $k$ in descending order. To calculate the number of tuples for a fixed $(j, k)$ we just need the number of $i < j$ such that $a_i = a_k$ and the number of $l > k$ with $a_l = a_j$. We can maintain both values in two frequency arrays $cntLeft$ and $cntRight$, where $cntLeft[x]$ ($cntRight[x]$) is the number of $a_i = x$ for $i < j$ ($i > k$). It's easy to update $cntLeft$ ($cntRight$) when moving $j$ to $j + 1$ ($k$ to $k - 1$). The time complexity is $O(n^2)$.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val a = readLine()!!.split(' ').map { it.toInt() - 1 }.toIntArray()\n\n        val cntLeft = IntArray(n) { 0 }\n        val cntRight = IntArray(n) { 0 }\n\n        var ans = 0L\n        for (j in a.indices) {\n            cntRight.fill(0)\n            for (k in n - 1 downTo j + 1) {\n                ans += cntLeft[a[k]] * cntRight[a[j]]\n                cntRight[a[k]]++\n            }\n            cntLeft[a[j]]++\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "data structures",
      "math",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1400",
    "index": "E",
    "title": "Clear the Multiset",
    "statement": "You have a multiset containing several integers. Initially, it contains $a_1$ elements equal to $1$, $a_2$ elements equal to $2$, ..., $a_n$ elements equal to $n$.\n\nYou may apply two types of operations:\n\n- choose two integers $l$ and $r$ ($l \\le r$), then remove one occurrence of $l$, one occurrence of $l + 1$, ..., one occurrence of $r$ from the multiset. This operation can be applied only if each number from $l$ to $r$ occurs at least once in the multiset;\n- choose two integers $i$ and $x$ ($x \\ge 1$), then remove $x$ occurrences of $i$ from the multiset. This operation can be applied only if the multiset contains at least $x$ occurrences of $i$.\n\nWhat is the minimum number of operations required to delete all elements from the multiset?",
    "tutorial": "Let's solve the problem by dynamic programing. Let $dp_{i, j}$ be the minimum number of operations to delete all elements from $1$ to $i$, if we have $j$ \"unclosed\" operations of the first type. In each transition, we either advance to the right (and possibly \"close\" some operations of the second type, so we go from $dp_{i, j}$ to $dp_{i + 1, \\min(a_{i + 1}, j)}$, adding $1$ to the answer if $j < a_{i + 1}$), or \"open\" a new operation of the second type (so we go from $dp_{i, j}$ to $dp_{i, j + 1}$, adding $1$ to the answer). This solution runs in $O(nA)$, which is too slow. The observation that helps us to speed this up is that we have to use only values from the array $a$ as the second state of our dynamic programming. Let's prove it. The proof begins here Let's call an integer $i$ saturated if all occurrences of $i$ were deleted by operations of the first type. Also, let's denote $c_i$ as the number of elements equal to $i$ deleted by the operations of the first type (so, $i$ is saturated iff $a_i = c_i$). Suppose $k$ is the minimum integer such that $c_k$ is not a value from the array $a$. Obviously, $k$ is not saturated. Since the number of operations of the first type covering some integer decreases only when we have to close them, it always decreases to some number in $a$, so it is impossible that $c_{k - 1} > c_k$. It is also impossible that $c_{k - 1} = c_k$, since $k$ is the minimum integer such that $c_k$ does not belong to array $a$. So, $c_{k - 1} < c_k$, it means that some number of operations of the first type started in integer $k$. We can either get rid of them altogether (if they end in $k$ as well), or shift them to $k + 1$, so $c_k$ belongs to the array $a$. That way, if in the optimal answer some value $c_k$ does not belong to $a$, we can reconstruct it so it is no longer the case. The proof ends here Overall, since we have only up $n$ disctict values of $j$, the solution runs in $O(n^2)$ (though it is possible to solve the problem faster).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(5e3) + 9;\n\nint n;\nint a[N];\nint dp[N][N];\n\nint calc (int pos, int x) {\n    int &res = dp[pos][x];\n    if (res != -1) return res;\n    \n    if (pos == n) return res = 0;\n    res = 1 + calc(pos + 1, n);\n    res = min(res, calc(pos + 1, pos) + a[pos]);\n    if (x != n) {\n        if (a[x] >= a[pos])\n            res = min(res, calc(pos + 1, pos));\n        else {\n            res = min(res, calc(pos + 1, pos) + a[pos] - a[x]);\n            res = min(res, 1 + calc(pos + 1, x));\n        }\n    }\n    \n    return res;\n}\n\nint main(){\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i)\n        scanf(\"%d\", a + i);\n\n    memset(dp, -1, sizeof(dp));       \n    printf(\"%d\\n\", calc(0, n));\n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1400",
    "index": "F",
    "title": "x-prime Substrings",
    "statement": "You are given an integer value $x$ and a string $s$ consisting of digits from $1$ to $9$ inclusive.\n\nA substring of a string is a contiguous subsequence of that string.\n\nLet $f(l, r)$ be the sum of digits of a substring $s[l..r]$.\n\nLet's call substring $s[l_1..r_1]$ $x$-prime if\n\n- $f(l_1, r_1) = x$;\n- there are no values $l_2, r_2$ such that\n\n- $l_1 \\le l_2 \\le r_2 \\le r_1$;\n- $f(l_2, r_2) \\neq x$;\n- $x$ is divisible by $f(l_2, r_2)$.\n\nYou are allowed to erase some characters from the string. If you erase a character, the two resulting parts of the string are concatenated without changing their order.\n\nWhat is the minimum number of characters you should erase from the string so that there are no $x$-prime substrings in it? If there are no $x$-prime substrings in the given string $s$, then print $0$.",
    "tutorial": "The number of $x$-prime strings is relatively small, so is their total length (you may bruteforce all of them and check that the total length of $x$-prime strings never exceeds $5000$, we will need that bruteforce in the solution). Now we have the following problem: given a set of strings with total length up to $5000$ and a string with length up to $1000$, erase the minimum number of characters from that string so no string from the set appears there as a substring. You may have already encountered the similar problem in some previous contests. The solution to this problem is dynamic programming - let $dp[x][y]$ be the minimum number of characters to erase, if we considered first $x$ characters, there were no occurrences of strings from the set in the resulting string... and the second state of dynamic programming ($y$) is a bit more complicated. We want to make sure that no string appears in the result as a substring, so $y$ should somehow handle that. Let $y$ be the longest suffix of the current string that coincides with some prefix of a string from the set. If some string from the set is a suffix of $y$, then the state is clearly bad - we have an occurrence of an $x$-prime string. Otherwise, there is no occurrence ending in the last character, since we considered the longest possible suffix that matches some prefix from the set. The transitions in $dp$ are the following - we either take the next character and recalculate $y$, or skip the next character and add $1$ to the number of removed characters. If we maintain and recalculate $y$ naively, as a string, the solution will be too slow. There are only up to $5000$ different values of $y$, but their total length may be much greater, so we don't even have enough memory to store our dynamic programming values. Let's enumerate all strings that are prefixes of some $x$-prime string and map each of these strings to some integer, so the second state in dynamic programming can be an integer instead of a string. Then we have to mark the bad integers (which correspond to strings having some $x$-prime string as a suffix) and calculate the two-dimensional transition matrix $T$, where $T[x][a]$ is the integer corresponding to a string that we get, if we append the $x$-th string with character $a$, so the transitions in dynamic programming can be done in $O(1)$. There are many ways to precalculate this matrix and mark all of the bad integers, but the most efficient one is to use Aho-Corasick algorithm (the transition matrix $T$ is exactly the automaton that the Aho-Corasick algorithm builds). If you are not familiar with it, I recommend you to read about it here: https://cp-algorithms.com/string/aho_corasick.html",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int AL = 9;\nconst int N = 5000;\nconst int INF = 1e9;\n\nstring s;\nint x;\n\nstruct node{\n    int nxt[AL];\n    int p;\n    char pch;\n    int link;\n    int go[AL];\n    bool term;\n    node(){\n        memset(nxt, -1, sizeof(nxt));\n        memset(go, -1, sizeof(go));\n        link = p = -1;\n        term = false;\n    }\n    int& operator [](int x){\n        return nxt[x];\n    }\n};\n\nvector<node> trie;\n\nvoid add_string(string s){\n    int v = 0;\n    for (auto it : s){\n        int c = it - '1';\n        if (trie[v][c] == -1){\n            trie.push_back(node());\n            trie[trie.size() - 1].p = v;\n            trie[trie.size() - 1].pch = c;\n            trie[v][c] = trie.size() - 1;\n        }\n        v = trie[v][c];\n    }\n    trie[v].term = true;\n}\n\nint go(int v, int c);\n \nint get_link(int v){\n    if (trie[v].link == -1){\n        if (v == 0 || trie[v].p == 0)\n            trie[v].link = 0;\n        else\n            trie[v].link = go(get_link(trie[v].p), trie[v].pch);\n    }\n    return trie[v].link;\n}\n \nint go(int v, int c) {\n    if (trie[v].go[c] == -1){\n        if (trie[v][c] != -1)\n            trie[v].go[c] = trie[v][c];\n        else\n            trie[v].go[c] = (v == 0 ? 0 : go(get_link(v), c));\n    }\n    return trie[v].go[c];\n}\n\nstring t;\n\nvoid brute(int i, int sum){\n    if (sum == x){\n        bool ok = true;\n        for (int l = 0; l < int(t.size()); ++l){\n            int cur = 0;\n            for (int r = l; r < int(t.size()); ++r){\n                cur += (t[r] - '0');\n                if (x % cur == 0 && cur != x)\n                    ok = false;\n            }\n        }\n        if (ok){\n            add_string(t);\n        }\n        return;\n    }\n    for (int j = 1; j <= min(x - sum, 9); ++j){\n        t += '0' + j;\n        brute(i + 1, sum + j);\n        t.pop_back();\n    }\n}\n\nint main() {\n    cin >> s >> x;\n    trie.push_back(node());\n    brute(0, 0);\n    vector<vector<int>> dp(s.size() + 1, vector<int>(trie.size(), INF));\n    dp[0][0] = 0;\n    forn(i, s.size()) forn(j, trie.size()) if (dp[i][j] != INF){\n        dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + 1);\n        int nxt = go(j, s[i] - '1');\n        if (!trie[nxt].term)\n            dp[i + 1][nxt] = min(dp[i + 1][nxt], dp[i][j]);\n    }\n    printf(\"%d\\n\", *min_element(dp[s.size()].begin(), dp[s.size()].end()));\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "string suffix structures",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1400",
    "index": "G",
    "title": "Mercenaries",
    "statement": "Polycarp plays a (yet another!) strategic computer game. In this game, he leads an army of mercenaries.\n\nPolycarp wants to gather his army for a quest. There are $n$ mercenaries for hire, and the army should consist of some subset of them.\n\nThe $i$-th mercenary can be chosen if the \\textbf{resulting} number of chosen mercenaries is not less than $l_i$ (otherwise he deems the quest to be doomed) and not greater than $r_i$ (he doesn't want to share the trophies with too many other mercenaries). Furthermore, $m$ pairs of mercenaries hate each other and cannot be chosen for the same quest.\n\nHow many \\textbf{non-empty} subsets does Polycarp need to consider? In other words, calculate the number of non-empty subsets of mercenaries such that the size of this subset belongs to $[l_i, r_i]$ for each chosen mercenary, and there are no two mercenaries in the subset that hate each other.\n\nThe answer may be large, so calculate it modulo $998244353$.",
    "tutorial": "We will use inclusion-exclusion formula to solve this problem (you may read about it here: https://cp-algorithms.com/combinatorics/inclusion-exclusion.html). To put it simply, we are going to count the number of subsets that meet the restrictions on $[l_i, r_i]$, ignoring the edges (I'll call the pairs of mercenaries that hate each other \"edges\" for simplicity). This number is not the answer, since we counted some subsets that violate the conditions for the edges - so, for each edge, we count the number of subsets that violate the condition on that edge, and subtract it from the answer. But it means that if a subset violates the conditions on multiple edges, we subtracted it multiple times, so, for each pair of edges, we count the subsets that violate both edges in that pair and add them back, then remove the subsets violating the triples, and so on. The mathematical formula for the answer is $\\sum \\limits_{E \\in S} f(E)$, where $S$ is the set containing all $2^m$ subsets of edges, and $f(E)$ is the number of subsets that meet the constraints on $[l_i, r_i]$, and violate the constraints for every edge $e \\in E$. Now we have to calculate $f(E)$ efficiently, since the outer loop already runs in $O(2^m)$. If we have to violate a set of edges, then we have a set of mercenaries that we should take (the \"endpoints\" of the edges), and the number of those mercenaries (let's denote it as $k$) is up to $40$. The size of the subset should meet the constraints on $[l_i, r_i]$ for each of those mercenaries, so let's intersect the segments $[l_i, r_i]$ for them (and if the intersection is empty, then there are no subsets that violate all of those edges). Let the intersection of those segments be $[L, R]$. The naive solution would be to iterate on the size of the subset and calculate the number of ways to compose a subset that contains some fixed mercenaries of given size (if the size is $s$, and $c_s$ is the number of mercenaries that are willing to be in a subset of size $s$, then we have to add ${{c_s - k} \\choose {s - k}}$ to the answer). So, for each subset $E$, $f(E) = \\sum \\limits_{s = L}^{R} {{c_s - k} \\choose {s - k}}$. This sum can be calculated in $O(1)$ as follows: note that $k$ is up to $40$, so for every possible value of $k$, precalculate the array of prefix sums of those binomial coefficients. This precalculation runs in $O(nm + n \\log MOD)$, and each $f(E)$ can be calculated in $O(m \\log m)$, so overall the complexity is $O(nm + n \\log MOD + 2^m m \\log m)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300043;\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    return ((x + y) % MOD + MOD) % MOD;\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1)\n            z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nint inv(int x)\n{\n    return binpow(x, MOD - 2);\n}\n\nint fact[N];\nint rfact[N];\n\nvoid prepare_fact()\n{\n    fact[0] = 1;\n    for(int i = 1; i < N; i++)\n        fact[i] = mul(i, fact[i - 1]);\n    for(int i = 0; i < N; i++)\n        rfact[i] = inv(fact[i]);\n}\n\nint c(int n, int k)\n{\n    if(n < 0 || n < k || k < 0)\n        return 0;\n    return mul(fact[n], mul(rfact[k], rfact[n - k]));\n}\n\nint main()\n{\n    int n, m;\n    scanf(\"%d %d\", &n, &m);\n    vector<int> l(n), r(n), a(m), b(m);\n    for(int i = 0; i < n; i++)\n        scanf(\"%d %d\", &l[i], &r[i]);\n    for(int i = 0; i < m; i++)\n        scanf(\"%d %d\", &a[i], &b[i]);\n    vector<int> cnt(n + 2);\n    for(int i = 0; i < n; i++)\n    {\n        cnt[l[i]]++;\n        cnt[r[i] + 1]--;\n    }\n    for(int i = 0; i < n + 1; i++)\n        cnt[i + 1] += cnt[i];\n    prepare_fact();\n    vector<vector<int> > p(2 * m + 1, vector<int>(n + 1));\n    for(int i = 1; i <= n; i++)\n        for(int j = 0; j <= 2 * m; j++)\n            p[j][i] = add(p[j][i - 1], c(cnt[i] - j, i - j));\n    int ans = 0;\n    for(int mask = 0; mask < (1 << m); mask++)\n    {\n        int sign = 1;\n        set<int> used;\n        for(int i = 0; i < m; i++)\n            if(mask & (1 << i))\n            {\n                sign = mul(sign, MOD - 1);\n                used.insert(a[i] - 1);\n                used.insert(b[i] - 1);\n            }\n        int L = 1, R = n;\n        for(auto x : used)\n        {\n            L = max(L, l[x]);\n            R = min(R, r[x]);\n        }\n        if(R < L) continue;\n        ans = add(ans, mul(sign, add(p[used.size()][R], -p[used.size()][L - 1])));\n    }\n    printf(\"%d\\n\", ans);\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp",
      "dsu",
      "math",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1401",
    "index": "A",
    "title": "Distance and Axis",
    "statement": "We have a point $A$ with coordinate $x = n$ on $OX$-axis. We'd like to find an integer point $B$ (also on $OX$-axis), such that the absolute difference between the distance from $O$ to $B$ and the distance from $A$ to $B$ is equal to $k$.\n\n\\begin{center}\n{\\small The description of the first test case.}\n\\end{center}\n\nSince sometimes it's impossible to find such point $B$, we can, in one step, increase or decrease the coordinate of $A$ by $1$. What is the minimum number of steps we should do to make such point $B$ exist?",
    "tutorial": "If $n$ is less than $k$, we have to move $A$ to coordinate $k$, and set the coordinate of $B$ as $0$ or $k$. So the answer is $k - n$. If $n$ is not less than $k$, let's define the coordinate of $B$ as $m$($m \\times 2 \\le n$). By the condition in the problem, the difference between ($m - 0$) and ($n - m$) should be equal to $k$. That is, $(n - m) - (m - 0)$ is $k$, and summarizing the formula, $m = (n - k) / 2$. Because the coordinate of $B$ is integer, if the parity of $n$ and $k$ is same the answer is $0$, otherwise the answer is $1$(If we increase the coordinate of $A$ by $1$, m becomes integer). Time complexity : $O(1)$",
    "code": "#include<bits/stdc++.h>\n\n#define endl '\\n'\n\nusing namespace std;\n\nmain()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    int k, n, t;\n\n    cin >> t;\n    for(;t--;)\n    {\n        cin >> n >> k;\n\n        if(n < k)\n            cout << k - n << endl;\n\n        else if(n % 2 == k % 2)\n            cout << 0 << endl;\n\n        else\n            cout << 1 << endl;\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1401",
    "index": "B",
    "title": "Ternary Sequence",
    "statement": "You are given two sequences $a_1, a_2, \\dots, a_n$ and $b_1, b_2, \\dots, b_n$. Each element of both sequences is either $0$, $1$ or $2$. The number of elements $0$, $1$, $2$ in the sequence $a$ is $x_1$, $y_1$, $z_1$ respectively, and the number of elements $0$, $1$, $2$ in the sequence $b$ is $x_2$, $y_2$, $z_2$ respectively.\n\nYou can rearrange the elements in both sequences $a$ and $b$ however you like. After that, let's define a sequence $c$ as follows:\n\n$c_i = \\begin{cases} a_i b_i & \\mbox{if }a_i > b_i \\\\ 0 & \\mbox{if }a_i = b_i \\\\ -a_i b_i & \\mbox{if }a_i < b_i \\end{cases}$\n\nYou'd like to make $\\sum_{i=1}^n c_i$ (the sum of all elements of the sequence $c$) as large as possible. What is the maximum possible sum?",
    "tutorial": "We can find the kind of the value of $c_i$ is three $\\left(-2, 0, 2\\right)$. And $c_i$ is $-2$ only if $a_i$ is $1$ and $b_i$ is $2$, and $c_i$ is $2$ only if $a_i$ is $2$ and $b_i$ is $1$. Otherwise $c_i$ is $0$. So we have to make ($a_i, b_i$) pair ($1, 2$) as little as possible, and pair ($2, 1$) as much as possible. To do this, first we can make ($1, 0$) pair, ($0, 2$) pair, and ($2, 1$) pair as much as possible. After that, pairing the remaining values doesn't affect the sum of $c_i$. (It $a_i$ in which value is $1$ and $b_i$ in which value is $2$ are all left, we have to pair them although the sum decreases.) Time complexity : $O(1)$",
    "code": "#include<bits/stdc++.h>\n\n#define endl '\\n'\n\nusing namespace std;\n\nmain()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    int t;\n\n    cin >> t;\n    for(;t--;)\n    {\n\tint m, sum = 0, x0, x1, x2, y0, y1, y2;\n\n\tcin >> x0 >> x1 >> x2 >> y0 >> y1 >> y2;\n\n\tm = min(x0, y2);\n\tx0 -= m;\n\ty2 -= m;\n\n\tm = min(x1, y0);\n\tx1 -= m;\n\ty0 -= m;\n\n\tm = min(x2, y1);\n\tx2 -= m;\n\ty1 -= m;\n\tsum += 2 * m;\n\n\tsum -= 2 * min(x1, y2);\n\n\tcout << sum << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1401",
    "index": "C",
    "title": "Mere Array",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$ where all $a_i$ are integers and greater than $0$.\n\nIn one operation, you can choose two different indices $i$ and $j$ ($1 \\le i, j \\le n$). If $gcd(a_i, a_j)$ is equal to the minimum element of the \\textbf{whole array} $a$, you can swap $a_i$ and $a_j$. $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\nNow you'd like to make $a$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this.\n\nAn array $a$ is non-decreasing if and only if $a_1 \\le a_2 \\le \\ldots \\le a_n$.",
    "tutorial": "Let's define the minimum element of $a$ as $m$. We can find the position of the elements which is not divisible by $m$ cannot be changed because these elements don't have $m$ as factor. But we can rearrange elements divisible by $m$ whatever we want in the following way: $\\bullet$ Let's suppose $m$ = $a_x$, and there is two elements $a_y$, $a_z$ in which $x$, $y$, $z$ are all different. Swap($a_x$, $a_y$), swap($a_y$, $a_z$), and swap($a_z$, $a_x$). Then only $a_y$ and $a_z$ are swapped from the initial state. Repeat this process. So we can rearrange elements divisible by $m$ in non-descending order. After that if whole array is non-descending the answer is $YES$, otherwise $NO$. Time complexity : $O(n \\log n)$",
    "code": "#import<bits/stdc++.h>\n\n#define endl '\\n'\n\nusing namespace std;\n\nint a[100005], b[100005];\nmain()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    int t;\n    cin >> t;\n    for(;t--;)\n    {\n\tint k = 0, m = 1000000000, n;\n\n\tcin >> n;\n\n\tfor(int i = 0; i < n; i++)\n\t{\n\t    cin >> a[i];\n            b[i] = a[i];\n\t    m = min(m, a[i]);\n\t}\n\n        sort(b, b + n);\n\n\tfor(int i = 0; i < n; i++)\n\t    if(a[i] != b[i] && a[i] % m > 0)\n\t\tk = 1;\n\n\tif(k)\n\t    cout<<\"NO\"<<endl;\n\telse\n\t    cout<<\"YES\"<<endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1401",
    "index": "D",
    "title": "Maximum Distributed Tree",
    "statement": "You are given a tree that consists of $n$ nodes. You should label each of its $n-1$ edges with an integer in such way that satisfies the following conditions:\n\n- each integer must be greater than $0$;\n- the product of all $n-1$ numbers should be equal to $k$;\n- the number of $1$-s among all $n-1$ integers must be minimum possible.\n\nLet's define $f(u,v)$ as the sum of the numbers on the simple path from node $u$ to node $v$. Also, let $\\sum\\limits_{i=1}^{n-1} \\sum\\limits_{j=i+1}^n f(i,j)$ be a distribution index of the tree.\n\nFind the maximum possible distribution index you can get. Since answer can be too large, print it modulo $10^9 + 7$.\n\nIn this problem, since the number $k$ can be large, the result of the prime factorization of $k$ is given instead.",
    "tutorial": "Let's define $w_i$ as the product of the number of vertices belonging to each of the two components divided when the $i_{th}$ edge is removed from the tree, and $z_i$ as the number on $i_{th}$ edge. Now a distribution index is equal to $\\sum_{i=1}^{n-1}(w_i \\times z_i)$. Now there are two cases: $A$ : $m \\le n-1$ In this case, we have to label $p_1, p_2, \\ldots p_m$ to $m$ distinct edges because we have to minimize the number of $1$-s. And to maximize distribution index, we can label a larger $p_i$ to the edge in which $w_i$ is larger because the following holds: $\\bullet$ For four positive integers $a, b, c, d$ ($a \\ge b, c \\ge d$), $ac + bd \\ge ad + bc$ Let's suppose $a=b+x, c=d+y$ $(x, y \\ge 0)$. Then the equation can be written as follows: $(b+x)(d+y)+bd \\ge (b+x)d+b(d+y)$ $bd+by+xd+xy+bd \\ge bd+xd+bd+by$ $xy \\ge 0$ Because $x, y \\ge 0$, we proved it. And label $1$ to the remaining edges. $B$ : $m > n-1$ In this case, we can make no $1$-s exist out of $n-1$ integers, and some of $n-1$ number would be composite. And to maximize distribution index, we can label the product of $m-n+2$ largest $p_i$ to the edge in which $w_i$ is largest, and label the remaining $p_i$ to the remaining edges in the same way as case $A$ because the following holds: $\\bullet$ For five positive integers $a, b, c, d, e$ ($a \\ge b, d \\ge e$), $acd+be \\ge bcd+ae$ Substituting $f = cd$ in the above equation, we can find the equation is same as before. So we proved it. After filling in the edge, calculate it and find the answer. Time complexity : $O(\\max(n, m) \\log \\max(n,m))$",
    "code": "#include<bits/stdc++.h>\n\n#define endl '\\n'\n\nusing namespace std;\n\ntypedef long long LL;\n\nstruct H{int x, y;};\n\nint ii, n;\nconst int q = 1e9 + 7;\nLL p[100005], pv[100005], vi[100005], w[100005];\nH e[200040];\n\nint C(H a, H b){return a.x < b.x;}\nint G(LL a, LL b){return a > b;}\n\nLL dfs(int v)\n{\n    LL d = 1;\n\n    vi[v] = 1;\n\n    for(int i = pv[v]; i < pv[v+1]; i++)\n\tif(!vi[e[i].y])\n\t    d += dfs(e[i].y);\n\n    w[ii] = d * (n - d);\n    ii++;\n\n    return d;\n}\n\nmain()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    int t;\n\n    cin >> t;\n\n    for(;t--;)\n    {\n\tint k = 0, m;\n\tLL x = 1;\n\n\tcin >> n;\n\n\tfor(int i = 0; i < n - 1; i++)\n\t{\n\t    cin >> e[i].x >> e[i].y;\n\t    e[i + n - 1].x = e[i].y;\n\t    e[i + n - 1].y = e[i].x;\n\t}\n\n\tint sz = 2 * n - 2;\n\n\tsort(e, e + sz, C);\n\n\tfor(int i = 1; i < sz; i++)\n\t{\n\t    if(e[i].x > e[i - 1].x)\n\t    {\n\t\tfor(int j = e[i - 1].x + 1; j <= e[i].x; j++)\n\t\t    pv[j] = i;\n\t    }\n\t}\n\tfor(int j = e[sz - 1].x + 1; j <= n + 2; j++)\n\t    pv[j] = sz;\n\n\tii = k = 0;\n\tdfs(1);\n\n\tcin >> m;\n\n\tfor(int i = 0; i < m; i++)\n\t    cin >> p[i];\n\n\tsort(p, p + m, G);\n\tsort(w, w + n - 1, G);\n\n\tif(m < n)\n\t    for(int i = m; i < n - 1; i++)\n\t\tp[i] = 1;\n\telse\n\t{\n\t    int i;\n\n\t    for(i = m - 1; i > m - n; k = i, i--)\n\t\tw[i] = w[i - m + n - 1];\n\n\t    for(; i; i--)\n\t\tw[i] = w[0];\n\t}\n\n\tint l = max(m, n - 1);\n\t\n\tint i;\n\tfor(i = 0, x = w[0]; i <= k; i++)\n\t    x = x * p[i] % q;\n\n\tfor(;i < l; i++)\n\t    x = (x + w[i] * p[i]) % q;\n\n\tcout << x << endl;\n\n\tfor(int i = 1; i <= n; i++)\n\t    vi[i] = 0;\n    }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "implementation",
      "math",
      "number theory",
      "sortings",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1401",
    "index": "E",
    "title": "Divide Square",
    "statement": "There is a square of size $10^6 \\times 10^6$ on the coordinate plane with four points $(0, 0)$, $(0, 10^6)$, $(10^6, 0)$, and $(10^6, 10^6)$ as its vertices.\n\nYou are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.\n\nNow you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.",
    "tutorial": "Under given condition, there are only two cases in which the number of pieces increases. $\\bullet$ When a segment intersects with two sides (facing each other) of the square, the number of pieces increases by one. $\\bullet$ When two segment intersects in the square (not including sides), the number of pieces increases by one. So the answer is equal to (the number of segment intersecting with two sides of the square) $+$ (the number of intersection in the square). You can sort the segments by ascending order of $y$-coordinate (Set the start and end points of vertical lines separately.) and do sweeping using segment tree to calculate the number of intersections in the square. Time complexity : $O(n \\log n + m \\log m)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long LL;\n\nstruct H{int k, l, r;};\n\nconst int p = 1048576;\n\nLL l[2100000], r[2100000], z[2100000];\n\nH h[100005], v[200040];\n\nint C(H a, H b){return a.k < b.k;}\nint D(H a, H b){return a.l < b.l || a.l == b.l && a.r > b.r;}\n\nLL sum(int x, int y, int d) // find the sum of range [x, y]\n{\n    if(x <= l[d] && r[d] <= y)\n\treturn z[d];\n\n    if(x > r[d] || y < l[d])\n\treturn 0;\n\n    return sum(x, y, d << 1) + sum(x, y, (d << 1) + 1);\n}\n\nvoid REP(int i, LL k) // add k to i-th number\n{\n    i += p;\n\n    for(z[i] += k; i >>= 1;)\n\tz[i] = z[i << 1] + z[(i << 1) + 1];\n}\n\nmain()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    LL m, n, s = 1;\n\n    cin >> n >> m;\n\n    for(int i = 0; i < p; i++)\n\tl[i + p] = r[i + p] = i;\n\n    for(int i = p; --i;)\n    {\n\tl[i] = l[i << 1];\n\tr[i] = r[(i << 1) + 1];\n    }\n\n    for(int i = 0; i < n; i++)\n    {\n\tcin >> h[i].k >> h[i].l >> h[i].r;\n\n\tif(h[i].r - h[i].l == 1000000)\n\t    s++;\n    }\n\n    sort(h, h + n, C);\n\n    for(int i = 0; i < m; i++)\n    {\n\tint j = i << 1;\n\n\tcin >> v[j].k >> v[j].l >> v[j+1].l;\n\n\tv[j + 1].k = v[j].k;\n\tv[j].r = 1;\n\tv[j + 1].r = -1;\n\n\tif(v[j + 1].l - v[j].l == 1000000)\n\t    s++;\n    }\n\n    sort(v, v + 2 * m, D);\n\n    for(int i = 0, j = 0; i < n && j < 2 * m;)\n    {\n\tif(h[i].k < v[j].l || h[i].k == v[j].l && v[j].r < 0)\n\t{\n\t    s += sum(h[i].l, h[i].r, 1);\n\t    i++;\n\t}\n\telse\n\t{\n\t    REP(v[j].k, v[j].r);\n\t    j++;\n\t}\n    }\n\n    cout << s;\n\n    return 0;\n}",
    "tags": [
      "data structures",
      "geometry",
      "implementation",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1401",
    "index": "F",
    "title": "Reverse and Swap",
    "statement": "You are given an array $a$ of length $2^n$. You should process $q$ queries on it. Each query has one of the following $4$ types:\n\n- $Replace(x, k)$ — change $a_x$ to $k$;\n- $Reverse(k)$ — reverse each subarray $[(i-1) \\cdot 2^k+1, i \\cdot 2^k]$ for all $i$ ($i \\ge 1$);\n- $Swap(k)$ — swap subarrays $[(2i-2) \\cdot 2^k+1, (2i-1) \\cdot 2^k]$ and $[(2i-1) \\cdot 2^k+1, 2i \\cdot 2^k]$ for all $i$ ($i \\ge 1$);\n- $Sum(l, r)$ — print the sum of the elements of subarray $[l, r]$.\n\nWrite a program that can quickly process given queries.",
    "tutorial": "Let's consider the sequence as $0$-based. Then we can find the following two facts: $\\bullet$ If we do $Reverse(k)$ operation once, $a_i$ becomes $a_{i\\text{^}(2^k-1)}$. $\\bullet$ If we do $Swap(k)$ operation once, $a_i$ becomes $a_{i\\text{^}(2^k)}.$ So in any state there is an integer $x$ that makes the current $a_i$ equal to the initial $a_{i\\text{^}x}$ and current $a_{i\\text{^}x}$ is equal to the initial $a_i$ for each $i$ ($0 \\le i \\le 2^n-1$). (Don't consider the change of the values by $Replace(x,k)$ operation.) Therefore, if we can calculate $\\sum_{i=l}^r a_{i\\text{^}x}$ fast for arbitrary $x$, also can solve the problem, and it can be done using segment tree. When processing $Replace(i,k)$ queries, replace $a_{i\\text{^}x}$ as $k$. And when processing $Reverse(k)$ or $Swap(k)$ queries, just replace $x$ as $x\\text{^}(2^k-1)$ or $x\\text{^}(2^k)$. And $Sum(l,r)$ queries are left. To calculate this value, divide the segment $[l, r]$ into smaller segments, in which length of each segment is power of $2$ and can be found in the segment tree. (ex : segment $[3, 9]$ is divided into three segments - $[3, 3]$, $[4, 7]$, $[8, 9]$) Next, find the sum of numbers in which index is in each segment. For divided segment $[l, r]$ in which length is $2^k$, the values $l\\text{^}x, (l+1)\\text{^}x, \\ldots (r-1)\\text{^}x, r\\text{^}x$ are, when sorted, form another segment $[l\\text{^}(x\\text{&~}(2^k-1)), r\\text{^}(x\\text{&~}(2^k-1))]$, which $x\\text{&~}(2^k-1)$ means the largest of multiples of $2^k$ not greater than $x$. So you can find the sum of numbers in each divided segment $\\sum_{i=l}^r$(current $a_i$) as $\\sum_{i=l\\text{^}(x\\text{&~}(2^k-1))}^{r\\text{^}(x\\text{&~}(2^k-1))}$(initial $a_i$). Repeat this and we can find the answer for each $Sum$ query. Time complexity : $O(nq)$",
    "code": "#include<bits/stdc++.h>\n\n#define endl '\\n'\n\nusing namespace std;\n\ntypedef long long LL;\n\nLL p, a[528000], ll[528000], rr[528000];\n\nLL SUM(LL l, LL r, LL d)\n{\n    LL x, y, z;\n\n    x = ll[d];\n    y = rr[d];\n    z = b & ~(y - x);\n\n    x ^= z;\n    y ^= z;\n\n    if(x > r || y < l)\n\treturn 0;\n\n    else if(x < l || y > r)\n\treturn(SUM(l, r, z << 1) + SUM(l, r, (z << 1) + 1));\n\n    else\n\treturn a[z];\n}\n\nvoid REP(LL i,LL k)\n{\n    i += p;\n\n    for(a[i] = k; i >>= 1;)\n\ta[i] = (a[i << 1] + a[(i << 1) + 1]);\n}\n\nmain()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    int b = 0, i, n, q;\n\n    cin >> n >> q;\n    p = 1 << n;\n\n    for(i = 0; i < p; i++)\n    {\n\tcin >> a[p + i];\n\tll[p + i] = rr[p + i] = i;\n    }\n\n    for(; i < p; i++)\n\tll[p + i] = rr[p + i] = i;\n\n    for(; --i;)\n    {\n\ta[i] = (a[i << 1] + a[(i << 1) + 1]);\n\tll[i] = ll[i << 1];\n\trr[i] = rr[(i << 1) + 1];\n    }\n\n    for(; q--;)\n    {\n\tint m;\n\n\tcin >> m;\n\n\tif(m == 1)\n\t{\n\t    int k, x;\n\n\t    cin >> x >> k;\n\n\t    REP((x - 1) ^ b, k);\n\t}\n\n\telse if(m == 2)\n\t{\n\t    int k;\n\n\t    cin >> k;\n\n\t    b ^= (1 << k) - 1;\n\t}\n\n\telse if(m == 3)\n\t{\n\t    int k;\n\n\t    cin >> k;\n\n\t    b ^= 1 << k;\n\t}\n\n\telse\n\t{\n\t    int l, r;\n\n\t    cin >> l >> r;\n\n\t    cout << SUM(l - 1, r - 1, 1) << endl;\n\t}\n    }\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1402",
    "index": "A",
    "title": "Fancy Fence",
    "statement": "Everybody knows that Balázs has the fanciest fence in the whole town. It's built up from $N$ fancy sections. The sections are rectangles standing closely next to each other on the ground. The $i$th section has integer height $h_i$ and integer width $w_i$. We are looking for fancy rectangles on this fancy fence. A rectangle is fancy if:\n\n- its sides are either horizontal or vertical and have integer lengths\n- the distance between the rectangle and the ground is integer\n- the distance between the rectangle and the left side of the first section is integer\n- it's lying completely on sections\n\nWhat is the number of fancy rectangles? This number can be very big, so we are interested in it modulo $10^9+7$.",
    "tutorial": "Subtask 2 $N, h_i \\leq 50, w_i = 1$ There are at most $50^4$ different rectangles. For all of them, we can check if they are fancy or not. This can be done in constant time with some precomputation. Subtask 3 $h_i = 1$ or $h_i = 2$ for all $i$. Consider a rectangle with height $1$ and width $K$. Lemma: There are $\\binom{K+1}{2}$ fancy rectangles in it. Proof: There are $K-p+1$ fancy rectangles with width $p$: $\\sum_{p=1}^{K} (K-p+1) = \\binom{K+1}{2}$ Now we can solve subtask 3: There are 2 types of fancy rectangles, the ones with height $1$, and the ones with height $2$. We can easily calculate the answer, applying the previous lemma in $O(N)$ time. A helpful observation Consider a rectangle with height $A$ and width $B$. Let's denote the number of fancy rectangles contained within this big rectangle by $T_{A,B}$. Now we have $T_{A,B} = \\binom{A+1}{2} \\cdot \\binom{B+1}{2}$ Note that $\\binom{X}{2} = \\dfrac{X(X-1)}{2}$, where $X(X-1)$ is always divisible by 2. Subtask 4 The solution follows easily from the previous lemma. This subtask can be solved in $O(N)$ time. Subtask 5 The heights are in increasing order. Let $W_i$ be the sum of section widths from the $i$th to the $N$th section. The answer is given by the formula: $\\sum_{i=1}^{N} T_{h_i,W_i} - T_{h_{i-1},W_i},$ This way, the subtask can be solved in $O(N)$ time. Subtask 6 $N \\leq 1000$ For all $1 \\leq i \\leq j \\leq N$, we calculate the number of fancy rectangles whose left side is part of the $i$th section and right side is part of the $j$th section. Let $H$ be the minimum of section heights from the $i$th to the $j$th section. Let $W$ be the sum of section widths from the $i$th to the $j$th section. The number of fancy rectangles is (if $i \\ne j$): $T_{H,W} - T_{H,W-w_i} - T_{H,W-w_j} + T_{H,W-w_i-w_j},$ This subtask can be solved in $O(N^2)$. Subtask 7 Original constraints. Sorting Let's sort the sections in decreasing order according to their heights. Let us denote the original index of the $i$ section by $p_i$. In the $i$th step, we calculate the number of fancy rectangles lying exclusively on the first $i$ sections. Let $x$ be the smallest index for which the $x$th, $x+1$th ... $p_i-1$th sections preceed the $p_i$th section. Let $y$ be the biggest index for which the $p_i+1$th, $p_i+2$th ... $y$th sections succeed the $p_i$th section. Write $X_i = \\sum_{j=x}^{p_i-1} w_j, \\qquad Y_i = \\sum_{j=p_i+1}^{y} w_j.$ This subtask can be solved in $O(NlogN)$ time. Linear Let's iterate through the sectionss from left to right maintaining a stack of sections with the following property: from bottom to top the height of sections are increasing and after the $i$th section is processed every fancy rectangle not present in the stack is already counted. When at the $i$th section three cases are possible, let the top of the stack contain a section with dimensions $H\\times W$: if $h_i=H$ we can easily modify $W$ and increase it by $w_i$ not hurting the invariant described above if $h_i>H$ we can just push a $h_i \\times w_i$ rectangle to the top of the stack if $h_i<H$ then we have to pop some elements from the stack until $h_i$ will be greater or equal to the height of the section on the top of the stack. While doing the popping we accumulate the width of the new top element (i.e. the sum of widths of all elements popped plus $w_i$) and also with a similar strategy to subtask 5 the number of fancy rectangles that will not be present in the stack should be calculated. Overall the time complexity of this solution is $O(N)$ since every rectangle is pushed and popped exactly once while doing a constant amount of operations.",
    "tags": [
      "*special",
      "data structures",
      "dsu",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1402",
    "index": "B",
    "title": "Roads",
    "statement": "The government of Treeland wants to build a new road network. There are $2N$ cities in Treeland. The unfinished plan of the road network already contains $N$ road segments, each of which connects two cities with a straight line. No two road segments have a common point (including their endpoints). Your task is to determine $N-1$ additional road segments satisfying the following conditions:\n\n- Every new road segment must connect two cities with a straight line.\n- If two segments (new or old) have a common point, then this point must be an endpoint of both segments.\n- The road network connects all cities: for each pair of cities there is a path consisting of segments that connects the two cities.",
    "tutorial": "We assume that for segment $s=(p,q)$ the relation $p.x<q.x$ or $p.x=q.x$ and $p.y<q.y$ holds, therefore we can say that $p$ is the left endpoint of the segment. Consider the sequence of segment endpoints ordered by their x-coordinates. We apply the sweep-line method, the event points of the sweeping are the x-coordinates of the endpoints. For a given $sx$ coordinate let us denote by $Sl(sx)$ the set of segments intersecting the vertical line whose $x$ coordinate is $sx$. Elements of the set $Sl$ are ordered according to the $y$-coordinate of the intersection points. As the sweep progresses from left to right, if the point is a left endpoint, then it is inserted into $Sl$, and deleted if it is a right endpoint. We add a sentinel, as the figure shows. Each segment endpoint which is on the left of the sweep-line is already a node of the tree, the partial output. For each segment $u \\in Sl$ we compute a segment endpoint $Rmost(u)$, with the following property. Let $u \\in Sl$ and $v \\in Sl$ be segments such that $v$ is directly next to $u$ according to the ordering. Then for every point $q$ on the sweep-line located between the intersection points of $u$ and $v$, if the $\\overline{Rmost(u), q}$ intersects any old or newly added segment then the intersection point must be an endpoint. Therefore if we insert a left endpoint $q$ into $Sl$ then the segment $(Rmost(u), q)$ will be added to the solution. Moreover, during both insertion and deletion we can update $Rmost(u)$ value in $O(log\\, N)$ time if we represent the set $Sl$ by STL ordered set. The running time of the whole algorithm is $O(N \\log N)$. Subtask 1 Constraint: All segments are vertical. This subtask can be solved by sorting the segments and connecting consecutive segments' left and right endpoints. The sorting relation is easy to compute: $s_1=(p_1,q_1) < s_2=(p_2, q_2)$ iff $p_1.x<p_2.x$ or $p_1.x=p_2.x$ and $p_1.y< p_2.y$. Subtask 2 Constraint: Each pair of segments are parallel. This subtask also admits solution by sorting, but the computation of the sorting relation is not so easy. Namely, $s_1=(p_1,q_1) < s_2=(p_2, q_2)$ iff both $p_1$ and $q_1$ located on the left of the line determined by $s_2$ or $s_1$ and $s_2$ are colinear and $q_1$ is inbetween $p_2$ and $q_2$. Subtask 3 Constraint: Each segment is either horizontal or vertical. This subtask can be solved by a simplified implementation of the model solution algorithm, because it is easy to compute the sorting relation of the set $Sl$. Subtask 4 Constraint: $N \\le 10000$ There is an $O(N^2)$running time algorithm that can solve this subtask. For example if we represent the set $Sl(sx)$ by sorted array.",
    "tags": [
      "*special",
      "geometry",
      "sortings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1402",
    "index": "C",
    "title": "Star Trek",
    "statement": "The United Federation of Planets is an alliance of $N$ planets, they are indexed from $1$ to $N$. Some planets are connected by space tunnels. In a space tunnel, a starship can fly both ways really fast. There are exactly $N-1$ space tunnels, and we can travel from any planet to any other planet in the Federation using these tunnels.\n\nIt's well known that there are $D$ additional parallel universes. These are exact copies of our universe, they have the same planets and space tunnels. They are indexed from $1$ to $D$ (our universe has index $0$). We denote the planet $x$ in universe $i$ by $P_x^i$. We can travel from one universe to another using dimension portals. For every $i$ ($0\\leq i \\leq D-1$), we will place exactly one portal that allows us to fly from $P_{A_i}^i$ to $P_{B_i}^{i+1}$, for some planet indices $A_i$ and $B_i$ (i.e. $1 \\leq A_i, B_i \\leq N$).\n\nOnce all the portals are placed, Starship Batthyány will embark on its maiden voyage. It is currently orbiting around $P_1^0$. Captain Ágnes and Lieutenant Gábor have decided to play the following game: they choose alternately a destination (a planet) to fly to. This planet can be in the same universe, if a space tunnel goes there, or it can be in another universe, if a portal goes there. Their aim is to visit places \\underline{where no one has gone before}. That's why, once they have visited a planet $P_x^i$, they never go back there (but they can visit the planet $x$ in another universe). Captain Ágnes chooses the first destination (then Gábor, then Ágnes etc.). If somebody can't choose a planet where they have not been before in his/her turn, he/she loses.\n\nCaptain Ágnes and Lieutenant Gábor are both very clever: they know the locations of all tunnels and portals, and they both play optimally. For how many different placements of portals does Captain Ágnes win the game? Two placements are different if there is an index $i$ ($0\\leq i \\leq D-1$), where the $i$th portal connects different pairs of planets in the two placements (i.e $A_i$ or $B_i$ differs).\n\nThis number can be very big, so we are interested in it modulo $10^9+7$.",
    "tutorial": "Subtask 2 $N = 2$ The Captain always wins. A possible winning strategy: she uses only tunnels. In this way, Gábor is forced to use only portals. After using a portal they will be in a new universe where the Captain can use the tunnel. So Captain can always move after Gábor, but there is a point where Gábor can't move. That's why Gábor can't win. The answer is the total number of possible placements: $4^D$. it can be computed in $O(logD)$ operations via fast exponentiation. This subtask can be solved in $O(logD)$ Winning-Losing states Lets play this game in a rooted tree where the first player moves from the root $r$. Let's call a node L(osing)-state if the player moving from there can't win. Call that node W(inning)-state otherwise. The players can only increase the distance from $r$; that's why every leaf is an L-state. A node is W-state iff it has an L-state child. The root's state can be calculated in $O(N)$ operation with dfs if the size of the tree is $N$. $\\mathbf{L}$ : set of nodes that are L-states as the root $\\mathbf{W}$ : set of nodes that are W-states as the root Subtask 3 $N \\leq 100, D = 1$ We test all possible placements. A placement will give us a tree of size $2N$ rooted at $P_1^0$. For all possibility we check the root's state. There are $O(N^2)$ different placements and it takes $O(N)$ operation to check a single one. This subtask can be solved in $O(N^3)$ Critical L-state It's clear that we have $D+1$ trees of the same structure and they are connected into a bigger tree. This big tree is rooted at $P_1^0$, but all small trees have a root-like node in the big tree ($P_1^0$ in the first universe and $P_{B_{i-1}}^i$ in the $i$th parallel universe). We will work now with the small tree of size $N$. Let's root this tree in an arbitrary node $r$. Let's call this tree $tree_r$. Let's denote the parent of node $c$ by $P(c)$. Connecting a new node $y$ with a given state to a node $x$ (of the original tree) may change some states. It can be proved that the state of $x$ changes iff $x$ and $y$ are both L-states. In this case, $x$ will become W-state. This may cause further changes in the tree: If $P(x)$ has only one L-state child ($x$), then its state will also change from W to L. If $P(P(x))$ is L-state, then its state will also change from L to W. $P(P(P(x)))$ will act like $P(x)$. This wave of change will stop at some node $z$, where $z$ will be the uppermost node whose state changed. We call $x$ a critical L-state if $z = r$. $\\mathbf{C_r}$ : set of nodes that are critical L-states when $r$ is the root. $\\mathbf{C_r}$ can be computed in $O(N)$ time for a given $r$ using dfs. Subtask 4 $N \\leq 1000$ and $D = 1$ We should connect 2 uniform trees of size N. The first tree is rooted at index 1 (the starting node). If the root of $tree_1$ is W-state it will only change it's state if we connect a L-state to one of its critical node. That's why; the answer is $N*|W| + (N-|C_1|)*|L|$. If the root of $tree_1$ is L-state it will only change it's state if we connect a L-state to one of its critical node. That's why; the answer is $|C_1|*|L|$. Calculating $|C_1|$ requires $O(N)$ time while calculating $|L|$ and $|W|$ requires $O(N^2)$. This subtask can be solved in $O(N^2)$ Subtask 5 $D = 1$ We must calculate $|L|$ and $|W|$ faster than in subtask 4. Let's say the original tree is rooted in $v$ and we want to reroot this tree in one of its neighbors, $u$. We can see that only $v$'s and $u$'s state may change while doing this. The new states can be computed in constant time if we know the number of L-state children for every node (which can be computed by a single dfs). We can reroot the tree easily in all nodes with one dfs. This subtask can be solved in $O(N)$ Subtask 6 $N \\leq 1000, D \\leq 10^5$ For all possible roots $r$ we calculate $|C_r|$. This takes $O(N^2)$ time. Let us define $L_D$ as the number of ways to choose a starting node, and install portals, By definition, the W/L status of the starting node $v$ will change if and only if we add an edge from a node in $\\mathbf{C_v}$ leading to an L state. Therefore, the number of ways to add all $D$ portals in a way that changes the status of the starting node is $\\left|\\mathbf{C_v}\\right| L_{D-1}.$ We can now calculate $(L_D)_v$, the number of ways to make $v$ a losing root with respect to the remaining $D$ (plus one) universes: if $v$ is W, then we have to add the remaining portals in a way that changes the status of $v$; if $v$ is L, then we have to add them in any other way. Hence, $(L_D)_v = \\begin{cases} \\left|\\mathbf{C_v}\\right| L_{D-1}& \\textit{if } v\\in W\\\\ N^{2D} - \\left|\\mathbf{C_v}\\right| L_{D-1} & \\textit{if }v\\in L. \\end{cases}$ $L_D = \\sum_{v} (L_D)_v\\\\ = \\sum_{v\\in W}\\left|\\mathbf{C_v}\\right| L_{D-1} + \\sum_{v\\in L}(N^{2D} - \\left|\\mathbf{C_v}\\right| L_{D-1})\\\\ = \\left|\\mathbf{L}\\right|N^{2D} + \\left(\\sum_{v\\in W}\\left|\\mathbf{C_v}\\right| - \\sum_{v\\in L}\\left|\\mathbf{C_v}\\right|\\right) L_{D-1}\\\\ = \\left|\\mathbf{L}\\right|N^{2D} + E \\cdot L_{D-1} \\textit{where }E\\triangleq \\left(\\sum_{v\\in W}\\left|\\mathbf{C_v}\\right| - \\sum_{v\\in L}\\left|\\mathbf{C_v}\\right|\\right).$ In the last universe, we have $L_0 = |\\mathbf{L}|$, by definition. The answer to the original question is the number of ways to make the starting node $v_1$ into W, which is given by $\\textit{Solution} = N^{2D} - (L_D)_{v_1}.$ We can calculate this value in $O(D)$ time using dynamic programming. This subtask can be solved in $O(N^2+D)$ Subtask 7 $D \\leq 10^5$ We must calculate $|C_r|$ for all $r$ faster than in subtask 6. We can use the idea described in subtask 5 (when calculating $|L|$ and $|W|$ fast). This subtask can be solved in $O(N+D)$ Subtask 8 Original constraints. Solution 1: This subtask can be solved like subtask 6 but we calculate $L_1$, $L_2$, $L_4$, $L_8$ ... (i.e. $L_{2^i}$), where we can compute $L_{2^i}$ from $L_{2^{i-1}}$. With the bit-representation of $D-1$ we can calculate $L_{D-1}$ in $O(logD)$ operations. This subtask can be solved in $O(N+logD)$ Solution 2: Closed Form To solve the last subtask, we need to calculate $L_{D-1}$ in sub-linear time. To do this, we can solve the recurrence relation, which yields the closed form $L_{D-1} = |L| \\frac{N^{2D} - E^{D}}{N^2 - E}.$ This could be calculated via $O(\\log D)$ exponentiation and modular inverse, but this is not necessary: we can easily eliminate the division by writing $a \\triangleq N^2$ and $b \\triangleq E$, and using the well-known identity for $(a^D - b^D)$ to get $L_X = |L| \\sum_{k=0}^{X} a^{k} b^{X-k}.$ $L_{2X+1} = (b^{X+1} + a^{X+1}) L_{X}\\\\ L_{2X} = b^{X+1} L_{X-1} + |L| a^X b^X + a^{X+1} L_{X-1}.$",
    "tags": [
      "*special",
      "combinatorics",
      "dfs and similar",
      "dp",
      "games",
      "graphs",
      "matrices",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1403",
    "index": "A",
    "title": "The Potion of Great Power",
    "statement": "Once upon a time, in the Land of the Shamans, everyone lived on the Sky-High Beanstalk. Each shaman had a unique identifying number $i$ between $0$ and $N-1$, and an altitude value $H_i$, representing how high he lived above ground level. The distance between two altitudes is the absolute value of their difference.\n\nAll shamans lived together in peace, until one of them stole the formula of the world-famous Potion of Great Power. To cover his/her tracks, the Thief has put a Curse on the land: most inhabitants could no longer trust each other...\n\nDespite the very difficult circumstances, the Order of Good Investigators have gained the following information about the Curse:\n\n- When the Curse first takes effect, everyone stops trusting each other.\n- The Curse is unstable: at the end of each day (exactly at midnight), one pair of shamans will start or stop trusting each other.\n- Unfortunately, each shaman will only ever trust at most $D$ others at any given time.\n\nThey have also reconstructed a log of who trusted whom: for each night they know which pair of shamans started/stopped trusting each other.They believe the Thief has whispered the formula to an Evil Shaman. To avoid detection, both of them visited the home of one of their (respective) trusted friends. During the visit, the Thief whispered the formula to the Evil Shaman through the window. (Note: this trusted friend did not have to be home at the time. In fact, it's even possible that they visited each other's houses – shamans are weird.)\n\nFortunately, whispers only travel short distances, so the Order knows the two trusted friends visited (by the Thief and the Evil Shaman) must live very close to each other.\n\nThey ask you to help with their investigation. They would like to test their suspicions: what if the Thief was $x$, the Evil Shaman was $y$, and the formula was whispered on day $v$? What is the smallest distance the whispered formula had to travel? That is, what is the minimum distance between the apartments of some shamans $x'$ and $y'$ (i.e. $\\min\\left(\\left|H_{x'} - H_{y'}\\right|\\right)$), such that $x'$ was a trusted friend of $x$ and $y'$ was a trusted friend of $y$ on day $v$?\n\nThey will share all their information with you, then ask you a number of questions. You need to answer each question immediately, before receiving the next one.",
    "tutorial": "We denote the maximum number of edges in the graph by $M$. You can see that $U$ is an upper bound for it. Subtask 2 $Q, U \\leq 1000$ We can store each operation, and replay them for each question. We can store all edges in a data structure, or keep neighbours in separate data structures for each node. When answering a question, find the neighbours of both nodes, and consider the distance of each pair of neighbours, computing the minimum. This yields to a simple solution in $O(QUD + QD^2)$ time, or $O(QU\\log(D) + QD^2)$ when using an associative container, like std::set. Ordering Trick Although not required for this subtask, we can improve the second part by ordering the neighbour lists by $H$ value, and stepping through them simultaneously, using two pointers. We always step in the list in which the pointer points to the entry with the smaller $H$ value out of the two, and consider the current pair for the minimum computation: The correctness of this is easy to prove. Subtask 3 $V=U$ for all queries In this case, each question will refer to the same version (the final one). Hence, we can just apply all updates at the start once (applying updates is done in the same way as in Subtask 2), and then answer questions on this single version (like before). Using an efficient data structure and the ordering trick (we can actually pre-sort, before answering any questions), we can solve this subtask in $O(U\\log(D) + M\\log(D) + Q D \\log(D))$. Subtask 4 $H[i] \\in \\{0,1\\}$ for all nodes $i$ For a node $u$ and version $V$, we need to be able to tell whether $u$ had a neighbour $u'$ with $H[u'] = f$ for both possible values of $f$ ($0$ or $1$). Once we have obtained this information for both $X$ and $Y$, we can easily work out the answer. For each node $u$ and possible $f$ value, let us build an ordered list of 'events' of the following types: Node $u$ stopped having any neighbours $u'$ with $H[u'] = f$ in version $V$. Node $u$ started having neighbours with $H[u'] = f$ in version $V$. This yields a solution in $O(U\\log(M) + Q\\log(U))$ time and $O(U)$ space for this special case. Subtask 5 $U,N \\leq 10000$ $\\sqrt{U}$ checkpoints We first apply all updates in order, producing $\\sqrt{U}$ checkpoints, evenly spaced, then - for each question - we simulate updates from the closest checkpoint (in the same way as we did for Subtask 1). An efficient implementation of this can achieve $O(U\\log(M) + \\sqrt{U} M + Q \\sqrt{U} \\log(M) + Q D \\log(D))$ time and $O(\\sqrt{U}M)$ memory. Save neighbour list by node, binary search by version Another solution is to separate updates by node, and save the neighbour list of the updated node for each update (in a vector of neighbour lists for that node). Then, we can binary search for the neighbour list at version $V$. This can be implemented in $O(UD + Q \\log(U) + QD)$ time and $O(UD)$ space. Self-copying data structures We can use a self-copying (also known as persistent or copy-on-write) data structure. These data structures are constructed as a (directed) tree, where each node holds some information. When updates are applied, we copy every node that was modified, including nodes whose children are modified, thus each version will have its own root node, from which queries can be performed. There are multiple possibilities here from static binary trees (holding neighbour lists, or neighbours directly) to balanced binary search trees (e.g. treap). These will solve this subtask, but will struggle to gain full marks for the problem due to exceeding memory constraints: the static versions have a high complexity ($O(ND + U\\log(ND))$ space, or worse), and the BST version has very high constants (both in space and time). One segment tree We need to find when each edge is present in the graph. For each edge, this is the union of contiguous intervals. In total, we have at most $U$ intervals. Take a segment tree of length $U$, with one leaf per version. Each node will contain a vector of edges, ordered by starting node (edge $e$ is stored in the tree node for $[a,b]$, if edge is present in each version during the interval $[a,b]$ - and not entirely present in the parent's interval). This has a combined space requirement of $O(U\\log(U))$. For each question, we look up edges starting from $X$ and $Y$ using binary search in the vector of each of the $\\log U$ relevant tree nodes. This can be implemented in $O(U\\log^2(U) + Q\\log^2(U) + QD\\log(D))$ time and $O(U\\log U)$ space. With a few tricks and an efficient implementation, this solution could possibly pass subtask 6. Subtask 6 No additional constraints Save neighbour list by node, reduce storage space by constant factor Clearly, saving each version of the neighbour lists of each node will not fit in memory for these limits. However, since memory limits are very generous, we can cut this down by a reasonably small constant $C$: we only save the neighbour list of node $u$ after every $C$'th update that affects $u$. We also save an ordered list of updates affecting each node. For each question, we only need to replay at most $2C$ updates ($C$ for $X$ and $C$ for $Y$). Choosing $C\\approx 50$ will suffice the pass every subtask. The time complexity is $O(U\\log D + \\frac{UD}{C} + Q(D+C\\log C))$, using $O(\\frac{UD}{C})$ memory. We think this solution is interesting in the sense that it demonstrates how big-$O$ complexity can often be misleading for real-world problems: this solution is far simpler than other solutions, some of which do not even gain $100$ marks, and it passes the limits because the constants involved (normally hidden by big-$O$ complexity classes) are far smaller. Multiple segment trees We can eliminate the binary search from the previous segment tree solution, by keeping a separate segment tree for each node. Na\"ively, this will not fit in the memory limits. However, we can save space by only keeping a leaf for each update where the given node was affected. This yields a solution in $O(U\\log(U) + Q\\log(U) + QD\\log(D))$ time and $O(U\\log(U))$ space.",
    "code": "p1 = 0, p2 = 0\nwhile (p1 < l1.length) and (p2 < l2.length)\n\tconsider(H[l1[p1]], H[l2[p2]])\n\tif (H[l1[p1]] <= H[l2[p2]])\n\t\tthen p1++\n\t\telse p2++\n",
    "tags": [
      "*special",
      "2-sat",
      "binary search",
      "data structures",
      "graphs",
      "interactive",
      "sortings",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1403",
    "index": "B",
    "title": "Spring cleaning",
    "statement": "Spring cleanings are probably the most boring parts of our lives, except this year, when Flóra and her mother found a dusty old tree graph under the carpet.\n\nThis tree has $N$ nodes (numbered from $1$ to $N$), connected by $N-1$ edges. The edges gathered too much dust, so Flóra's mom decided to clean them.\n\nCleaning the edges of an arbitrary tree is done by repeating the following process: She chooses 2 different leaves (a node is a leaf if it is connected to exactly one other node by an edge), and cleans every edge lying on the shortest path between them. If this path has $d$ edges, then the cost of cleaning this path is $d$.\n\nShe doesn't want to harm the leaves of the tree, so she chooses every one of them \\textbf{at most once}. A tree is cleaned when all of its edges are cleaned. The cost of this is the sum of costs for all cleaned paths.\n\nFlóra thinks the tree they found is too small and simple, so she imagines $Q$ variations of it. In the $i$-th variation, she adds a total of $D_i$ extra leaves to the \\textbf{original} tree: for each new leaf, she chooses a node from the \\textbf{original} tree, and connects that node with the new leaf by an edge. Note that some nodes may stop being leaves during this step.\n\nFor all these $Q$ variations, we are interested in the minimum cost that is required to clean the tree.",
    "tutorial": "Cleanable tree It is obvious that a tree is not cleanable if it has an odd number of leaves. Also, every tree with an even number of leaves is cleanable. Subtask 2 $Q = 1$, there is an edge between node $1$ and $i$ for every $i$ $(2 \\leq i \\leq N)$ Flóra can't add extra leaf to node $1$ If we add 2 extra leaves to an inner node (not a leaf), it's a good strategy to clean the path between these extra leaves. So if we add an even number of extra leaves to an inner node, we can pair all these extra leaves. Otherwise there is an extra leaf without a pair. This leaf will be added to the tree. A similar thing happens if we add leaves to an original leaf. In this subtask we know that every path cleaning will go throw through node $1$ (except those that we already paired). So we just have to add the distances from node $1$. This subtask can be solved in $O(N + D_1)$ Subtask 3 $Q$ = 1, there is an edge between nodes $i$ and $i+1$ for all $i$ $(1 \\leq i < N)$ Flóra can't add extra leaf to node $1$ nor node $N$ It's a good idea to clean the path between node 1 and node N. After this we should just simply pair the extra leaves in an optimal way. This subtask can be solved in $O(N+sum(D_i))$ Even-odd nodes It can be proved that in the optimal solution, all edges are cleaned at most twice. So our task is to minimize the number of edges cleaned twice. Let's root the tree in an inner node $r$ (It's possible since $N>2$). We denote the parent of a node $u$ by $P(u)$ in this rooted tree. Let's call a node $u$ even if in it's subtree there are even number of leaves. Call it odd otherwise (all leaves are odd nodes). It can be proved that we clean the edge from $u$ to $P(u)$ twice iff $u$ is an even node (where $u \\ne r$). Let $E$ be the set of even nodes. In this case, the minimum required cost for the original tree is $N + |E| - 2$ if $r$ is an even node. We can compute which nodes are even in $O(N)$ time with a single dfs. Subtask 4 $N \\leq 20000$, $Q \\leq 300$ We can build up every tree variation and calculate the number of even nodes for it. This subtask can be solved in $O(N\\cdot Q + sum(D_i))$ Path to the root For every node $u$ let's denote its distance from the root $r$ by $D(u)$. Let $S(u)$ denote the number of even nodes on the path from $u$ to $r$. This means that the number of odd nodes on the path from $u$ to $r$ is $D(u)+1-S(u)$. The previous values can be computed in $O(N)$ time for the original tree using a single dfs. Subtask 5 The original tree is a perfect binary tree rooted at node $1$ In this case $D(u) <= logN$ for every $u$. When adding a leaf to node $u$, we change all parities from $u$ to $r$, which takes at most $O(logN)$ time. This subtask can be solved in $O(N + sum(D_I) \\cdot logN)$. Subtask 6 $D_i = 1$ We calculate the minimum required cost for the original tree in $O(N)$. If we add an extra leaf to an original leaf the cleaning cost increases by 1, but nothing else happens. If we add an extra leaf to an inner node $u$, then every node on the path from $u$ to $r$ will change parity. So the answer is $N + |E| - S(u) + (D(u) - S(u))$ if $r$ was and odd node in the original tree. This subtask can be solved in $O(N + Q)$ Subtask 7 Original constraints. Virtual tree approach Adding an extra leaf to node $u$ may cause parity change on the path from $u$ to $r$. If we add an extra leaf to node $v$ too then the parities from node $LCA(u,v)$ (LCA=lowest common ancestor) to $r$ will change twice, i.e. it doesn't change at all. If we add more leaves then there will be paths where the parity has changed odd times and where it has changed even times. If we added a new leaf to a node $u$ let's call it a critical node. Let's define $L$ as a subset of original nodes where: If we add a node to node $u$, then $u \\in L$. If $u,v \\in L$ then $LCA(u,v) \\in L$ too. It can be proved that $|L| \\leq min(N,2\\cdot D_i - 1)$ for the $i$th variation. We can form a new tree from the nodes of $L$ in the following way: In this tree, the parent of node $u \\in L$ is node $v \\in L$ if $v$ is an ancestor of $u$ in the original tree and $D(v)$ is maximal. Let's denote the parent of node $u$ in the new tree by $P_{L}(u)$. In the new tree, for all nodes $u$ we calculate the number of critical nodes in the subtree rooted in $u$. (This can be computed in $O(|L|)$ using a single dfs.) If this number is even then nothing happens. If it's odd, the parity from node $u$ to $P_{L}(u)$ will change in the original tree (but will not change in $P_{L}(u)$. We can say that the parity has changed from $u$ to $r$, and then from $P_{L}(u)$ to $r$. These can be handled by using $S(u)$ and $S(P_{L}(u))$ the same way we described in subtask 5. Note that we don't have to know the $i+1$th variation before answering the $i$th one. So this solution can solve this problem \"online\". This subtask can be solved in $O((N + sum(D_i))logN)$. We remark that the problem can also be solved by utilizing the Heavy-Light Decomposition (HLD) of the original tree, this solution was also passing if the implementation was not too messy. Dynamic offline solution Instead of computing the value changes for every variation online, we can preread and store for each individual node which variations we add leaves to them. Then, using a dfs in a bottom-up DP manner, starting from the leaves for each node we pair the unpaired leaves in its subtree. We can store the unpaired leaves (only the variation's and parent node's identifiers are interesting for us) in some collections (e.g. set/map) and at each node, we merge the collections of all of its children. If we encounter two children having an unpaired leaf for the same variation, it means the current node is the LCA for those two additions, and we can compute the change in the cost of cleaning for that variation and store it. In order to maintain low complexity (i.e. logarithmic in terms of sums of $D_i$, we must make sure to not copy any collections needlessly, and always insert the elements of the smaller into the bigger one. After computing the cost changes for all variations simultaneously by a single dfs, we can contruct the answer for each variation by checking if it has any unpaired leaves in the final collection, and adding the cost change to the basic cleaning cost of the original tree. HLD approach The main idea is that we can calculate $|E|$ directly with heavy-light decomposition. First root the tree arbitrarily. Then, we need a segment tree that counts the amount of even numbers in a range with lazy range increases. After this, do hld on the input tree ith the inner data structure being the aforementioned segment tree. Then, for every leaf $l$ we increase every edge by $1$ on the path from $l$ up to the root. Now, without any variations we know $|E|$, but it's also clear that for the $i$th variaton we will only do $O(D_i)$ queries on the hld, if we attach the nodes one by one there are two cases: currently we attach a node to a leaf, then that leaf will no longer be a leaf, but attaching a new leaf to it basically cancels this effect so we don't need to do anything. we are not attaching to a leaf, then we can simply do the same increasing stuff we did.",
    "tags": [
      "*special",
      "data structures",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1403",
    "index": "C",
    "title": "Chess Rush",
    "statement": "The mythic world of Chess Land is a rectangular grid of squares with $R$ rows and $C$ columns, $R$ being greater than or equal to $C$. Its rows and columns are numbered from $1$ to $R$ and $1$ to $C$, respectively.\n\nThe inhabitants of Chess Land are usually mentioned as \\underline{pieces} in everyday language, and there are $5$ specific types of them roaming the land: pawns, rooks, bishops, queens and kings. Contrary to popular belief, chivalry is long dead in Chess Land, so there are no knights to be found.\n\nEach piece is unique in the way it moves around from square to square: in one step,\n\n- a pawn can move one row forward (i.e. from row $r$ to $r+1$), without changing columns;\n- a rook can move any number of columns left/right without changing rows OR move any number of rows forward/backward without changing columns;\n- a bishop can move to any square of the two diagonals intersecting at its currently occupied square;\n- a queen can move to any square where a rook or a bishop could move to from her position;\n- and a king can move to any of the $8$ adjacent squares.\n\nIn the following figure, we marked by X the squares each piece can move to in a single step (here, the rows are numbered from bottom to top, and the columns from left to right).Recently, Chess Land has become a dangerous place: pieces that are passing through the land can get captured unexpectedly by unknown forces and simply disappear. As a consequence, they would like to reach their destinations as fast (i.e. in as few moves) as possible, and they are also interested in the number of different ways it is possible for them to reach it, using the minimal number of steps – because more paths being available could mean lower chances of getting captured. Two paths are considered different if they differ in at least one visited square.\n\nFor this problem, let us assume that pieces are entering Chess Land in a given column of row $1$, and exit the land in a given column of row $R$. Your task is to answer $Q$ questions: given the type of a piece, the column it enters row $1$ and the column it must reach in row $R$ in order to exit, compute the minimal number of moves it has to make in Chess Land, and the number of different ways it is able to do so.",
    "tutorial": "Pawns, Rooks and Queens If $c_1=c_R$ then there is a unique shortest path, which takes $1$ step for the rook and the queen, and $R-1$ steps for the pawn. Otherwise, it is impossible getting to the exit square for the pawn, and it takes exactly $2$ steps for both the queen and the rook. It is also obvious that the latter can always do it in two different ways. Therefore, we only have to be careful about enumerating the number of ways to do the required $2$ steps for the queen. She always has the same two paths as the rook available, plus we need to take into account all the options involving one or two diagonal moves. For these, we have to check if any path is blocked by the edges Chess Land, and also note that two diagonal moves are only possible if $1+c_1$ and $R+c_R$ have the same parity. Bishops First note that the bishop can reach its destination iff $1+c_1$ and $R+c_R$ have the same parity, otherwise the answer is $0$. For a small number of rows, a carefully implemented bruteforce evaluation can also solve the problem, but if $R$ is large, we need to be more thorough. It is useful to note that we can count the number of steps and paths separately for the cases when the bishops leaves the first row using the left diagonal and the right diagonal, and in the end, if one is shorter than the other then choose that one, and if they take the same number of steps, just sum them to get the answer. Now, for a given starting direction, we can use a combinatorial argument to find the answer. First, imagine that we move forward in a greedy manner, bouncing between the left and right edges of Chess Land until we reach the last row in some impact column $c_I$. This way, we can jump $C-1$ rows forward before hitting a wall and having to move again, except the first and last moves, which are easy to handle. This gives us an initial guess for the number of steps. It is relatively easy to see that if $c_I=c_R$ then this shortest path is unique and the previously computed length is correct. Otherwise, there are two cases depending on how we arrive at the last row: for example, if we reach the last row while moving from left to right, and the target square is further to the right of $c_I$ (i.e. $c_I<c_R$), then the previous step length is once again correct, as we could have chosen to not go all the way to the edges in one or more previous step, which would increase the vaule of $c_I$ so we ensure $c_I=c_R$. However, if we reach the last row while moving from left to right, and the target square is to the left of $c_I$ (i.e. $c_R<c_I$ and we effectively \"jump over\" the requred destination), then we need to include one additional step into our path somewhere along the way in order to ensure $c_I=c_R$. This way, we obtain the number $n$ of required steps, and the number $f$ of diagonal movements we can spare by stopping before hitting an edge, and we need to distribute them arbitrarily over $n-1$ steps, as we cannot stop during the last step. This is equivalent to the well-known combinatorial problem of distributing $f$ balls into $n-1$ boxes, but is also relatively easy to figure out that it is the combination $\\binom{f+n-2}{f}.$ Regarding the implementation of the solution, one has to be very careful about handling corner cases such as starting from the first or last column or arriving there, the direction of arrival and so. Note that in the formula above, $n-2$ can be $O(R/C)$ large which makes the evaluation a bit tricky when $C$ is small: notice that $\\binom{f+n-2}{f} = \\frac{(f+n-2)!}{f! (n-2)!} = \\frac{(f+n-2)(f+n-3)\\cdots (n-1)}{f!},$ We remark that alternately, the answers to all possible queries could be precomputed in $O(C^2)$ time, using the fact that while cycling through all the possible values of $c_R$ for a fixed $c_1$, the values $n$ and $f$ can change by at most $2$, making it possible to adjust the answer in constant time, but this is much more difficult to implement and was not required to pass. Kings It is easy to see that the king has to make exactly $R-1$ bottom-up moves, and if $|c_R-c_1|\\leq R-1$, we need to advance one row in each step in order to have a shortest path. The other case, when $|c_R-c_1| > R-1$ means we need to advance one column towards the destination each step and have some free maneuverability between rows, can be solved seperately in a similar manner as the easiest case of the bottom-up problem, since this can only occur when $R<C$. From now on, we assume $R\\geq C$, so the king moves one row forward in each step and takes $R-1$ steps total, so we just need to count the number of paths. First, we observe that the number of ways we can reach the $j$-th column of a row is initially ways[c1]=1 and otherwise ways[j]=0 for the first row, and for any further row can be computed dynamically as next_ways[j] = ways[j - 1]+ ways[j] + ways[j + 1], where $j=1,\\ldots,C$. Next, we have to notice that with the same technique, we can precompute and store the answer for every $(c_1,c_R)$ pair, and answer each query in $O(1)$ time after, by adding another dimension to our dynamic programming: let DP[i][j] denote the number of ways to go from the $i$-th column of the first row to the $j$-th column of some current row, so initially we have DP[i][i] = 1 and every other entry is 0. Now we just repeat next_DP[i][j] = DP[i][j - 1]+ DP[i][j] + DP[i][j + 1] Our next observation is to notice that at each iteration, instead of advancing a sinle row $r\\to r+1$, we can choose to compute the answer for $r\\to 2r-1$ instead. Indeed, our current DP array stores all the numbers of ways to get from the columns of the first row to the columns of the $r$-th row, or in other words, to advance $r$ rows forward. So if we want to count the number of ways to get from the $i$-th column of the first row to the $j$-th column of the $2r-1$-st row, we can enumerate all the possible paths going through the intermediate $k$-th column of the $r$-th row ($k=1,\\ldots,C$) by the formula double_DP[i][j] = $\\displaystyle\\sum_{k=1}^C$ DP[i][k] $\\cdot$ DP[k][j]. Notice that the cost of advancing a single row was $O(C^2)$, so if we could somehow speed up the computation of $r\\to 2r-1$ advancements too, then generating all answers for the king could be done in $O(C^2 \\log R)$ time. There are multiple ways to do this step, but they all can be a bit tricky to find, so implementing a previous, less efficient approach and studying some of its outputs for small $C$ and different $R$ values could be very useful to figure out the main ideas and guess how a solution works. First, the entries of double_DP[i][1], i.e. going from any column of the first row to a fixed column $j=0$, can be computed in $O(C^2)$ time, and since reversing the paths from the $i$-th to the $j$-th column gives exactly the paths from the $j$-th to the $i$-th column, double_DP[i][j] is symmetric and we obtain every double_DP[1][j] entry immediately. Now suppose $1<i<j<C/2$ holds. The key observation is that we don't have to use the values of DP anymore, as the paths going from the $i$-th to the $j$-th column are almost the same as the paths going from the $i-1$-st column to the $j-1$-st column, shifted by a single column to the right. In fact, the relation double_DP[i][j] = double_DP[i-1][j-1] + double_DP[1][1+i+j] double_DP[i][j] = double_DP[i+1][j-1] + double_DP[1][1+i-j],",
    "tags": [
      "*special",
      "combinatorics",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1404",
    "index": "A",
    "title": "Balanced Bitstring",
    "statement": "A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $k$-\\textbf{balanced} if every substring of size $k$ of this bitstring has an equal amount of 0 and 1 characters ($\\frac{k}{2}$ of each).\n\nYou are given an integer $k$ and a string $s$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $k$-balanced bitstring by replacing every ? characters in $s$ with either 0 or 1.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.",
    "tutorial": "Let's denote the balanced bitstring (if any) deriving from $s$ to be $t$. Also, for the ease of the tutorial, let the strings be $0$-indexed (so the first character has index $0$ and the last character has index $n - 1$). First of all, let's prove a very important observation: for every $i$ such that $0 \\leq i < n - k$, $t_i = t_{i + k}$. This is because the length $k$ substrings starting at $i$ and $i + 1$ share the $k - 1$ characters $t_{i + 1} \\dots t_{i + k - 1}$, so in order for both strings to have the same number of 1 characters, their remaining characters $t_i$ and $t_{i + k}$ must both be 1, or both be 0. Extending this fact, we can easily prove that $t_i = t_j$ if $i \\equiv j \\pmod{k}$. So first of all, for each $0 \\leq i < k$, we need to find out if all $s_j$ such that $j\\text{ mod }k = i$ can be converted to the same character (i.e. there can't exist both 0 and 1 among these characters). Furthermore, we can deduce some information for $t_i$: it must be 0 if at least one character among $s_j$ is 0, must be 1 if at least one character among $s_j$ is 1, or it can be undecided and can be freely assigned to 0 or 1 if all $s_j$ are ?. An illustration for $n = 9$, $k = 4$. The positions highlighted with the same colors must have the same characters. By using the information from the known characters we can fill some of the unknown positions. An illustration for $n = 9$, $k = 4$. The positions highlighted with the same colors must have the same characters. By using the information from the known characters we can fill some of the unknown positions. Lastly, we need to check if we can make the substring $t_0t_1 \\dots t_{k - 1}$ have exactly half of the characters are equal to 1 (we don't need to check for any other substring, because the condition $t_i = t_{i + k}$ implies that all the substrings of size $k$ will have the same number of 1 characters). We simply need to check if the number of decided 1 characters and the number of decided 0 characters do not exceed $\\frac{k}{2}$. It can easily be shown that if these numbers don't exceed this value then we can assign the undecided characters so that half of the characters are 1, and if one exceeds then it is impossible to do so.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint n, k, t;\nstring s;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> t;\n    while (t--) {\n        cin >> n >> k >> s;\n        int zer = 0, one = 0;\n        bool chk = true;\n        for (int i = 0; i < k; i++) {\n            int tmp = -1;\n            for (int j = i; j < n; j += k) {\n                if (s[j] != '?') {\n                    if (tmp != -1 && s[j] - '0' != tmp) {\n                        chk = false;\n                        break;\n                    }\n                    tmp = s[j] - '0';\n                }\n            }\n            if (tmp != -1) {\n                (tmp == 0 ? zer : one)++;\n            }\n        }\n        if (max(zer, one) > k / 2) {\n            chk = false;\n        }\n        cout << (chk ? \"YES\\n\" : \"NO\\n\");\n    }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1404",
    "index": "B",
    "title": "Tree Tag",
    "statement": "Alice and Bob are playing a fun game of tree tag.\n\nThe game is played on a tree of $n$ vertices numbered from $1$ to $n$. Recall that a tree on $n$ vertices is an undirected, connected graph with $n-1$ edges.\n\nInitially, Alice is located at vertex $a$, and Bob at vertex $b$. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance \\textbf{at most} $da$ from the current vertex. And in a move, Bob can jump to a vertex with distance \\textbf{at most} $db$ from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them.\n\nIf after at most $10^{100}$ moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins.\n\nDetermine the winner if both players play optimally.",
    "tutorial": "Let's consider several cases independently. Case 1: $\\mathrm{dist}(a, b)\\le da$ Unsurprisingly, Alice wins in this case by tagging Bob on the first move. Case 2: $2da\\ge \\mathrm{tree\\ diameter}$ Here, the diameter of a tree is defined as the length of the longest simple path. In this case, Alice can move to a center of the tree. Once Alice is there, it doesn't matter where Bob is, since Alice can reach any vertex in the tree in just one move, winning the game. Case 3: $db > 2da$ In this case, let's describe a strategy for Bob to win. Because we are not in case 1, Bob will not lose before his first move. Then it is sufficient to show that Bob can always end his turn with distance greater than $da$ from Alice. Since we are not in case 2, there is at least one vertex with distance at least $da$ from Alice. If Bob is at such a vertex at the start of his turn, he should simply stay there. Otherwise, there is some vertex $v$ with $\\mathrm{dist}(a,v)=da+1$. Then $\\mathrm{dist}(b,v)\\le \\mathrm{dist}(b,a)+\\mathrm{dist}(a,v)\\le da+(da+1)=2da+1\\le db$, so Bob can jump to $v$ on his turn. Case 4: $db \\le 2da$ In this case, Alice's strategy will be to capture Bob whenever possible or move one vertex closer to Bob otherwise. Let's prove that Alice will win in a finite number of moves with this strategy. Let's root the tree at $a$. Bob is located in some subtree of $a$, say with $k$ vertices. Alice moves one vertex deeper, decreasing Bob's subtree size by at least one vertex. Since $db\\le 2da$, Bob cannot move to another subtree without being immediately captured, so Bob must stay in this shrinking subtree until he meets his inevitable defeat. Solution The only non-trivial part in the implementation is checking for cases $1$ and $2$. Case $1$ is simply checked with DFS. Case 2 only requires computing the diameter of the tree, which is a standard problem. Complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 1e5 + 5;\nint n, a, b, da, db, depth[N];\nvector<int> adj[N];\nint diam = 0;\n \nint dfs(int x, int p) {\n    int len = 0;\n    for(int y : adj[x]) {\n        if(y != p) {\n            depth[y] = depth[x] + 1;\n            int cur = 1 + dfs(y, x);\n            diam = max(diam, cur + len);\n            len = max(len, cur);\n        }\n    }\n    return len;\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int te;\n    cin >> te;\n    while(te--) {\n        cin >> n >> a >> b >> da >> db;\n        for(int i = 1; i <= n; i++) adj[i].clear();\n        for(int i = 0; i < n - 1; i++) {\n            int u, v;\n            cin >> u >> v;\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n        diam = 0;\n        depth[a] = 0;\n        dfs(a, -1);\n        cout << (2 * da >= min(diam, db) || depth[b] <= da ? \"Alice\" : \"Bob\") << '\\n';\n    }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1404",
    "index": "C",
    "title": "Fixed Point Removal",
    "statement": "Let $a_1, \\ldots, a_n$ be an array of $n$ positive integers. In one operation, you can choose an index $i$ such that $a_i = i$, and remove $a_i$ from the array (after the removal, the remaining parts are concatenated).\n\nThe weight of $a$ is defined as the maximum number of elements you can remove.\n\nYou must answer $q$ independent queries $(x, y)$: after replacing the $x$ first elements of $a$ and the $y$ last elements of $a$ by $n+1$ (making them impossible to remove), what would be the weight of $a$?",
    "tutorial": "Convenient transformation Replace $a_i$ by $i - a_i$. The new operation becomes: remove a zero, and decrement all elements after by one. For each query, note $l = 1+x$ and $r = n-y$ the endpoints of the non-protected subarray. The main idea of the solution is iterating over $r$, maintaining answers for each $l$ in a BIT (increment on prefix) and answer queries offline (when we meet a right endpoint). What follows is a detailed explanation of this idea. Simplified version Let's suppose that $l = 1$ holds for all queries. We can intuitively see that $a_i$ is removable iff $a_i \\ge 0$ and we can remove at least $a_i$ elements before. We're going to rewrite this more formally. Let $f(r)$ be the maximum number of elements we can remove in the subarray $a[1 \\ldots r]$. If $a_r < 0$ or $a_r > f(r-1)$, then it's obviously impossible to remove $a_r$ and in that case, $f(r) := f(r-1)$. Otherwise, if $0 \\le a_r \\le f(r-1)$, then $f(r) := f(r-1)+1$. We can reach this with the following strategy: Perform the $a_r$ first steps in the prefix $[1, r-1]$ Remove $a_r$ (which is equal to $0$ at that moment) Perform the remaining $f(r-1) - a_r$ steps in the prefix $[1, r-1]$. Hence, we can compute successively $f(1), f(2), \\ldots, f(n)$ with a single loop: maintain current $f(r)$ in a variable $s$, and at each iteration increment $s$ if and only if $0 \\le a_r \\le s$. Complete version Note $f(l, r)$ the maximum number of elements we can remove in the subarray $a[l \\ldots r]$ (zero if $l > r$). During our iteration over $r$, we're going to maintain the answers for each $l$: $s = [f(1, r), f(2, r), \\ldots, f(n, r)]$ When the iteration continues, discovering a new element $a_r$, what happens? If $a_r < 0$, nothing happens. Otherwise, $s_l$ is incremented by one if and only if $s_l \\ge a_r$. Let $l_\\max$ be the greatest $l$ such that $l \\le r$ and $s_{l_\\max} \\ge a_r$. We should increment the prefix ending here by one: $\\boxed{s_1 \\ge \\ldots \\ge s_{l_\\max}} \\ge a_r > s_{l_\\max + 1} \\ge \\ldots \\ge s_n$ A binary indexed tree (aka Fenwick tree) is obviously the structure we need in order to maintain $s$, since it allows to add on segment and get one element in $\\mathcal{O}(\\log n)$ (segment tree could work, but is slower in practice). In order to find $l_\\max$, the easiest solution is to binary search, it takes $\\mathcal{O}(\\log^2 n)$ time which is fast enough to get AC. We can also use binary lifting in order to optimize the search in $\\mathcal{O}(\\log n)$. This technique is explained in this blog. We have to read all queries in advance (offline algorithm). When the iteration over $r$ meets the right endpoint of a query, we set its answer to the current weight of $s_l$. In order to get an online algorithm (answer the query before reading the next one), we would have to use a persistent data structure. Final complexity: $\\mathcal{O}((n + q) \\log n)$ with low constant factor. Under given time limit, $\\log^2$ solutions with reasonable constant factor could also pass.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n\tios::sync_with_stdio(false), cin.tie(0);\n\tint n, q; cin >> n >> q;\n\tvector<int> a(n+1), ans(q), leftBound(q);\n\tvector<vector<int>> endHere(n+1);\n \n\tfor (int i = 1; i <= n; ++i) {\n\t\tcin >> a[i];\n\t\ta[i] = i - a[i];\n\t}\n \n\tfor (int i = 0; i < q; ++i) {\n\t\tint x, y; cin >> x >> y;\n\t\tint l = 1+x, r = n-y;\n\t\tleftBound[i] = l;\n\t\tendHere[r].push_back(i);\n\t}\n \n\tvector<int> BIT(n+1);\n\tint global = 0;\n\tfor (int r = 1; r <= n; ++r) {\n\t\tint target = a[r];\n\t\tif (target >= 0) {\n\t\t\t// Find rightmost pos such that s[pos] >= target\n\t\t\tint pos = 0, cur = global;\n\t\t\tfor (int jump = 1 << __lg(n); jump >= 1; jump /= 2)\n\t\t\t\tif (pos+jump <= r && cur - BIT[pos+jump] >= target)\n\t\t\t\t\tpos += jump, cur -= BIT[pos];\n \n\t\t\t// Increment prefix (+1 on whole array, -1 on suffix)\n\t\t\t++global;\n\t\t\tfor (int i = pos+1; i <= n; i += i & -i)\n\t\t\t\t++BIT[i];\n\t\t}\n \n\t\tfor (int iQuery : endHere[r]) {\n\t\t\tans[iQuery] = global;\n\t\t\tfor (int i = leftBound[iQuery]; i > 0; i -= i & -i)\n\t\t\t\tans[iQuery] -= BIT[i];\t\n\t\t}\n\t}\n \n\tfor (int i = 0; i < q; ++i)\n\t\tcout << ans[i] << \"\\n\";\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1404",
    "index": "D",
    "title": "Game of Pairs",
    "statement": "\\textbf{This is an interactive problem.}\n\nConsider a fixed positive integer $n$. Two players, First and Second play a game as follows:\n\n- First considers the $2n$ numbers $1, 2, \\dots, 2n$, and partitions them as he wants into $n$ disjoint pairs.\n- Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants).\n\nTo determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of $2n$, then Second wins. Otherwise, First wins.\n\nYou are given the integer $n$. Your task is to decide which player you wish to play as and win the game.",
    "tutorial": "We split the problem into two cases: $n$ is even We claim that First can guarantee a win by forming the pairs $(1, n + 1), \\dots, (n, 2n)$. Note that no matter which elements Second chooses, he will always take one element having each remainder modulo $n$. Thus the total sum is $0 + 1 + 2 + \\dots + n - 1 \\equiv \\frac{n(n - 1)}{2} \\pmod{n}$ Say $n = 2m$, then this reduces to $m(2m - 1) \\pmod{2m}$. Since $2m - 1$ is an odd integer this is nonzero, and the sum isn't even divisible by $n$, let alone $2n$. $n$ is odd This is the more difficult part of the problem. We claim that now Second is able to win, and present a strategy. We have two important claims: Claim 1. It is enough for Second to find a choice of elements from each pair such that the sum of the chosen numbers is divisible by $n$ (instead of $2n$). Proof. Notice that the sum of all the numbers is $1 + 2 + \\dots + 2n = n(2n + 1)$, which is congruent to $n \\pmod{2n}$. If the sum of some numbers, one from each pair, is divisible by $n$, then it is either $0 \\pmod{2n}$ or $n \\pmod{2n}$. In the first case, we have already won. Otherwise, if we take every other number instead, the sum of those numbers will be $0 \\pmod{2n}$, and we will also win. Claim 2. It is always possible to take one element from each pair such that each of the remainders modulo $n$ appears exactly once. Proof. Consider a graph with $2n$ vertices $1, 2, \\dots, 2n$ and regard the pairs chosen by First as red edges in this graph. We will additionally create $n$ edges connecting the vertices $i$ and $i + n$ for each $i \\le n$, and paint them blue. Then every vertex is adjacent to one red edge and one blue edge. In particular, all vertices have degree $2$, so the graph splits into disjoint cycles. An illustration for the case $n = 5$. The pairs are $(1, 6)$, $(2, 7)$, $(3, 5)$, $(4, 8)$ and $(9, 10)$. The numbers $1, 7, 3, 4, 10$ on the white vertices cover all residues $\\bmod n$. An illustration for the case $n = 5$. The pairs are $(1, 6)$, $(2, 7)$, $(3, 5)$, $(4, 8)$ and $(9, 10)$. The numbers $1, 7, 3, 4, 10$ on the white vertices cover all residues $\\bmod n$. Since the edges in each cycle alternate between being red and blue, they all have even lengths, so it's possible to color their vertices alternately black and white, and we can construct such a coloring by a simple DFS. Finally, after doing this for all cycles, take the numbers corresponding to all the white vertices. Since no two of them are joined by a red edge, they are all in different pairs, and since no two of them are joined by a blue edge, their residues modulo $n$ are all different, and thus each one appears exactly once. Finally, by combining the two previous claims the problem is solved, since $0 + 1 + \\dots + n - 1 \\equiv 0 \\pmod{n}$. Complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int MAXN = 1e6 + 10;\nvector<int> adj[MAXN];\nint vi[MAXN], pv[MAXN];\nvector<int> choices[2];\n \nvoid dfs(int s, int x) {\n    vi[s] = 1;\n    choices[x].push_back(s);\n    for(auto v : adj[s])\n        if(!vi[v])\n            dfs(v, x ^ 1);\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int n;\n    cin >> n;\n    if(n % 2) {\n        cout << \"Second\" << endl;\n        for(int i = 1; i <= 2 * n; i++) {\n            int x;\n            cin >> x;\n            if(pv[x]) {\n                adj[pv[x]].push_back(i);\n                adj[i].push_back(pv[x]);\n            }\n            else {\n                pv[x] = i;\n            }\n        }\n        for(int i = 1; i <= n; i++) {\n            adj[i].push_back(n + i);\n            adj[n + i].push_back(i);\n        }\n        for(int i = 1; i <= 2 * n; i++) {\n            if(!vi[i])\n                dfs(i, 0);\n        }\n        long long sum = 0;\n        for(auto x : choices[0])\n            sum += x;\n        if(sum % (2 * n) != 0)\n            swap(choices[0], choices[1]);\n        for(auto x : choices[0])\n            cout << x << \" \";\n        cout << endl;\n        int res;\n        cin >> res;\n        //assert(res == 0);\n        return 0;\n    }\n    else {\n        cout << \"First\" << endl;\n        for(int i = 0; i < 2 * n; i++)\n            cout << (i % n) + 1 << \" \";\n        cout << endl;\n        int res;\n        cin >> res;\n        //assert(res == 0);\n        return 0;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1404",
    "index": "E",
    "title": "Bricks",
    "statement": "A brick is defined as a rectangle with integer side lengths with either width $1$ or height $1$ (or both).\n\nThere is an $n\\times m$ grid, and each cell is colored either black or white. A tiling is a way to place bricks onto the grid such that each black cell is covered by exactly one brick, and each white cell is not covered by any brick. In other words, bricks are placed on black cells only, cover all black cells, and \\textbf{no two bricks overlap}.\n\n\\begin{center}\nAn example tiling of the first test case using $5$ bricks. It is possible to do better, using only $4$ bricks.\n\\end{center}\n\nWhat is the minimum number of bricks required to make a valid tiling?",
    "tutorial": "Instead of placing a minimum number of bricks into the cells, let's imagine that we start out with all $1\\times 1$ bricks and delete the maximum number of borders. Of course, we need to make sure that when we delete borders, all the regions are in fact bricks. A region is a brick if and only if it contains no \"L\" shape. Let's construct a graph where each vertex is a border between two black cells, and we connect two vertices if deleting both would create an \"L\" shape. Then the tilings correspond exactly with the independent vertex sets in this graph, and the optimal tiling corresponds to the maximum independent set. The number of bricks is simply the total number of black cells minus the size of our independent set. Here is the graph and independent vertex set corresponding to a tiling: In general, computing the maximum independent vertex set of a graph is NP-complete. But in our special case, this graph is bipartite (the bipartition being horizontal borders and vertical borders). And Kőnig's Theorem states that for bipartite graphs, the size of the maximum matching is equal to the size of the minimum vertex cover. Recall that the complement of a minimum vertex cover is a maximum independent set. The maximum matching can be computed using maximum flow. In particular, Dinic's algorithm runs in $O(\\sqrt{V}E)$ time. For our graph, $V$ and $E$ are both $O(nm)$. Overall complexity is therefore $O(nm\\sqrt{nm})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define SOURCE 0\n#define HORZ(i, j) (m * (i) + (j) + 1)\n#define VERT(i, j) ((n - 1) * m + n * (j) + (i) + 1)\n#define SINK ((n - 1) * m + n * (m - 1) + 1)\n \nconst int N = 305, V = 2e5 + 5;\n \nstruct edge {\n    int u, v, cap, flow;\n};\n \nstruct Dinic {\n    vector<edge> e;\n    vector<vector<int>> adj;\n    vector<int> ptr;\n    vector<int> level;\n    int n, source, sink;\n    Dinic(int n, int s, int t): n(n), source(s), sink(t) {\n        level.assign(n, -1);\n        adj.assign(n, vector<int>());\n        ptr.assign(n, 0);\n    }\n    void add_edge(int a, int b, int c) {\n        int k = e.size();\n        e.push_back({a, b, c, 0});\n        e.push_back({b, a, c, c});\n        adj[a].push_back(k);\n        adj[b].push_back(k + 1);\n    }\n    bool bfs() {\n        fill(level.begin(), level.end(), -1);\n        level[source] = 0;\n        queue<int> Q;\n        Q.push(source);\n        while(!Q.empty()) {\n            int x = Q.front(); Q.pop();\n            for(int i : adj[x]) {\n                if(level[e[i].v] == -1 && e[i].flow < e[i].cap) {\n                    level[e[i].v] = level[x] + 1;\n                    Q.push(e[i].v);\n                }\n            }\n        }\n        return level[sink] != -1;\n    }\n    int dfs(int x, int pushed) {\n        if(x == sink) return pushed;\n        for(int &id = ptr[x]; id < (int) adj[x].size(); id++) {\n            int i = adj[x][id];\n            if(level[e[i].v] == level[x] + 1 && e[i].flow < e[i].cap) {\n                int f = dfs(e[i].v, min(pushed, e[i].cap - e[i].flow));\n                if(f > 0) {\n                    e[i].flow += f;\n                    e[i ^ 1].flow -= f;\n                    return f;\n                }\n            }\n        }\n        return 0;\n    }\n    int calc() {\n        int ans = 0;\n        while(bfs()) {\n            fill(ptr.begin(), ptr.end(), 0);\n            while(true) {\n                int f = dfs(source, INT_MAX);\n                if(f == 0) break;\n                ans += f;\n            }\n        }\n        return ans;\n    }\n};\n \nint n, m;\nstring s[N];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> n >> m;\n    int ans = 0;\n    Dinic F(SINK + 1, SOURCE, SINK);\n    for(int i = 0; i < n; i++) {\n        cin >> s[i];\n        for(int j = 0; j < m; j++) {\n            if(s[i][j] == '#') {\n                ans++;\n                if(i > 0 && s[i - 1][j] == '#') {\n                    F.add_edge(SOURCE, HORZ(i - 1, j), 1);\n                    ans--;\n                }\n                if(j > 0 && s[i][j - 1] == '#') {\n                    F.add_edge(VERT(i, j - 1), SINK, 1);\n                    ans--;\n                }\n            }\n        }\n    }\n    for(int i = 0; i < n; i++) {\n        for(int j = 0; j < m; j++) {\n            if(s[i][j] == '#') {\n                // right, down\n                if(i < n - 1 && j < m - 1 && s[i + 1][j] == '#' && s[i][j + 1] == '#') {\n                    F.add_edge(HORZ(i, j), VERT(i, j), 1);\n                }\n                // right, up\n                if(i > 0 && j < m - 1 && s[i - 1][j] == '#' && s[i][j + 1] == '#') {\n                    F.add_edge(HORZ(i - 1, j), VERT(i, j), 1);\n                }\n                // left, down\n                if(i < n - 1 && j > 0 && s[i + 1][j] == '#' && s[i][j - 1] == '#') {\n                    F.add_edge(HORZ(i, j), VERT(i, j - 1), 1);\n                }\n                // left, up\n                if(i > 0 && j > 0 && s[i - 1][j] == '#' && s[i][j - 1] == '#') {\n                    F.add_edge(HORZ(i - 1, j), VERT(i, j - 1), 1);\n                }\n            }\n        }\n    }\n    ans += F.calc();\n    cout << ans << '\\n';\n}",
    "tags": [
      "flows",
      "graph matchings",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1405",
    "index": "A",
    "title": "Permutation Forgery",
    "statement": "A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nLet $p$ be any permutation of length $n$. We define the \\textbf{fingerprint} $F(p)$ of $p$ as the sorted array of sums of adjacent elements in $p$. More formally,\n\n$$F(p)=\\mathrm{sort}([p_1+p_2,p_2+p_3,\\ldots,p_{n-1}+p_n]).$$\n\nFor example, if $n=4$ and $p=[1,4,2,3],$ then the fingerprint is given by $F(p)=\\mathrm{sort}([1+4,4+2,2+3])=\\mathrm{sort}([5,6,5])=[5,5,6]$.\n\nYou are given a permutation $p$ of length $n$. Your task is to find a \\textbf{different} permutation $p'$ with the same fingerprint. Two permutations $p$ and $p'$ are considered different if there is some index $i$ such that $p_i \\ne p'_i$.",
    "tutorial": "Let $p'=\\mathrm{reverse}(p).$ Then $p'$ is a permutation, since every value from $1$ to $n$ appears exactly once. $p'\\ne p$ since $p'_1=p_n\\ne p_1$. (Here, we use $n\\ge 2$.) $F(p')=F(p)$ since any two adjacent values in $p$ remain adjacent in $p'$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int te;\n    cin >> te;\n    while(te--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for(int &x : a) cin >> x;\n        reverse(a.begin(), a.end());\n        for(int x : a) cout << x << ' ';\n        cout << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1405",
    "index": "B",
    "title": "Array Cancellation",
    "statement": "You're given an array $a$ of $n$ integers, such that $a_1 + a_2 + \\cdots + a_n = 0$.\n\nIn one operation, you can choose two \\textbf{different} indices $i$ and $j$ ($1 \\le i, j \\le n$), decrement $a_i$ by one and increment $a_j$ by one. If $i < j$ this operation is free, otherwise it costs one coin.\n\nHow many coins do you have to spend in order to make all elements equal to $0$?",
    "tutorial": "The answer is the maximum suffix sum, which can be computed in $\\mathcal{O}(n)$. Formal proof. Define $c_i = a_i + a_{i+1} + \\cdots + a_n$ (partial suffix sum). Note $M = \\max(c)$. We can observe that $a_1 = \\cdots = a_n = 0$ if and only if $c_1 = \\cdots = c_n = 0$. (If $c$ is null, $a_i = c_i - c_{i+1} = 0 - 0 = 0$.) A free operation on $i < j$ is equivalent to incrementing $c_{i+1}, \\ldots, c_j$. Free operations can only increment elements of $c$, so we obviously need at least $M$ coins. Let's do $M$ times the operation $(i = n, j = 1)$, which decrement every element $M$ times. Now, for every $i$, $c_i \\le 0$ and we can make it equal to $0$ by performing $-c_i$ times the free operation $(i-1, i)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n\tios::sync_with_stdio(false), cin.tie(0);\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tlong long cur = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tlong long x; cin >> x;\n\t\t\tcur = max(0LL, cur + x);\n\t\t}\n\t\tcout << cur << \"\\n\";\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1406",
    "index": "A",
    "title": "Subset Mex",
    "statement": "Given a set of integers (it can contain equal elements).\n\nYou have to split it into two subsets $A$ and $B$ (both of them can contain equal elements or be empty). You have to maximize the value of $mex(A)+mex(B)$.\n\nHere $mex$ of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:\n\n- $mex(\\{1,4,0,2,2,1\\})=3$\n- $mex(\\{3,3,2,1,3,0,0\\})=4$\n- $mex(\\varnothing)=0$ ($mex$ for empty set)\n\nThe set is splitted into two subsets $A$ and $B$ if for any integer number $x$ the number of occurrences of $x$ into this set is equal to the sum of the number of occurrences of $x$ into $A$ and the number of occurrences of $x$ into $B$.",
    "tutorial": "Let us store the count of each number from $0$ to $100$ in array $cnt$. Now $mex(A)$ would be the smallest $i$ for which $cnt_i=0$.Let this $i$ be $x$. $mex(B)$ would be smallest $i$ for which $cnt_i\\leq 1$. This is because one count of each number less than $x$ would go to $A$ therefore the element which was present initially once would now not be available for $B$. Overall Complexity: $O(n)$.",
    "code": "#include<bits/stdc++.h>\n#define re register\nusing namespace std;\ninline int read(){\n\tre int t=0;re char v=getchar();\n\twhile(v<'0')v=getchar();\n\twhile(v>='0')t=(t<<3)+(t<<1)+v-48,v=getchar();\n\treturn t;\n}\nint n,a[102],vis[2][102],ansa,ansb;\nint main(){\n\tre int t=read();\n\twhile(t--){\n\tn=read();\n\tfor(re int i=1;i<=n;++i)a[i]=read();memset(vis,0,sizeof(vis));\n\tfor(re int i=1;i<=n;++i){\n\t\tif(!vis[0][a[i]])vis[0][a[i]]=1;\n\t\telse vis[1][a[i]]=1;\n\t}ansa=ansb=0;\n\twhile(vis[0][ansa])++ansa;\n\twhile(vis[1][ansb])++ansb;\n\tprintf(\"%d\\n\",ansa+ansb);\n\t}\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1406",
    "index": "B",
    "title": "Maximum Product",
    "statement": "You are given an array of integers $a_1,a_2,\\ldots,a_n$. Find the maximum possible value of $a_ia_ja_ka_la_t$ among all five indices $(i, j, k, l, t)$ ($i<j<k<l<t$).",
    "tutorial": "First, if all numbers are less than $0$, then you should print the product of the five biggest numbers of them. Otherwise, the maximum product must be non-negative. Sort the numbers by their absolute value from big to small. If the first five numbers' product is positive then print it. Then we can always change one of the five to one of the $n-5$ other numbers to make this product positive. Enumerate which one to replace, and you can solve this problem in $O(n)$ time.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nlong long ans,a[100005];\nint main() {\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile(t--){\n\t\tint n;\n\t\tlong long mx=-1e9;\n\t\tscanf(\"%d\",&n);\n\t\tfor(int i=1;i<=n;i++)scanf(\"%lld\",&a[i]),mx=max(mx,a[i]);\n\t\tsort(a+1,a+n+1,[](long long x,long long y){return abs(x)>abs(y);});\n\t\tif(mx<0){\n\t\t    cout<<a[n]*a[n-1]*a[n-2]*a[n-3]*a[n-4]<<'\\n';\n\t\t    continue;\n\t\t}\n\t\tans=a[1]*a[2]*a[3]*a[4]*a[5];\n\t\tfor(int i=6;i<=n;i++){\n\t\t    for(int j=1;j<=5;j++){\n\t\t        long long tmp=a[i];\n\t\t        for(int k=1;k<=5;k++){\n\t\t            if(k!=j)tmp*=a[k];\n\t\t        }\n\t\t        ans=max(ans,tmp);\n\t\t    }\n\t\t}\n\t\tprintf(\"%lld\\n\",ans);\n\t}\n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1406",
    "index": "C",
    "title": "Link Cut Centroids",
    "statement": "Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.\n\nA vertex is a \\textbf{centroid} of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible.\n\nFor example, the centroid of the following tree is $2$, because when you cut it, the size of the largest connected component of the remaining graph is $2$ and it can't be smaller.\n\nHowever, in some trees, there might be more than one centroid, for example:\n\nBoth vertex $1$ and vertex $2$ are centroids because the size of the largest connected component is $3$ after cutting each of them.\n\nNow Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut.\n\nHe wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists.",
    "tutorial": "Let vertex $1$ be the root of the tree. If there is only one centroid, just cut any edge and link it back. Otherwise there are two centroids. Let them be $x$ and $y$, then there must be an edge connecting $x$ and $y$. (If not, choose any other vertex on the path from $x$ to $y$ and the size of the largest connected component after cutting it will be smaller than $x$ and $y$). Let $x$ be $y$'s father. (If not, swap $x$ and $y$) Then just cut a leaf from $y$'s subtree and link it with $x$. After that, $x$ becomes the only centroid. Proof: It's easy to see that the size of $y$'s subtree must be exactly $\\dfrac{n}{2}$. After cutting and linking, the maxinum component size of $y$ becomes $\\dfrac{n}{2}+1$ while the maxinum component size of $x$ is still $\\dfrac{n}{2}$.",
    "code": "#include<iostream>\n#include<cstdio>\n#include<algorithm>\n#include<vector>\nusing namespace std;\nint n,size[100005],fa[100005],minn=1e9,cent1,cent2;\nvector<int> g[100005];\nvoid dfs(int x,int f){\n\tfa[x]=f,size[x]=1;\n\tint mx=0;\n\tfor(int y:g[x]){\n\t\tif(y==f)continue;\n\t\tdfs(y,x);\n\t\tsize[x]+=size[y];\n\t\tmx=max(mx,size[y]);\n\t}\n\tmx=max(mx,n-size[x]);\n\tif(mx<minn)minn=mx,cent1=x,cent2=0;\n\telse if(mx==minn)cent2=x;\n}\nint S;\nvoid dfs2(int x,int f){\n\tif(g[x].size()==1){\n\t\tS=x;\n\t\treturn ;\n\t}\n\tfor(int y:g[x]){\n\t\tif(y==f)continue;\n\t\tdfs2(y,x);\n\t}\n}\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\tcin>>n,cent1=cent2=0,minn=1e9;\n\tfor(int i=1;i<=n;i++)g[i].clear(),fa[i]=0;\n\tfor(int i=1;i<n;i++){\n\t\tint x,y;\n\t\tcin>>x>>y;\n\t\tg[x].push_back(y),g[y].push_back(x);\n\t}\n\tdfs(1,0);\n\tif(!cent2){\n\t\tprintf(\"1 %d\\n1 %d\\n\",g[1][0],g[1][0]);\n\t\tcontinue;\n\t}\n\tif(fa[cent1]!=cent2)swap(cent1,cent2);\n\tdfs2(cent1,cent2);\n\tprintf(\"%d %d\\n%d %d\\n\",S,fa[S],S,cent2);}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1406",
    "index": "D",
    "title": "Three Sequences",
    "statement": "You are given a sequence of $n$ integers $a_1, a_2, \\ldots, a_n$.\n\nYou have to construct two sequences of integers $b$ and $c$ with length $n$ that satisfy:\n\n- for every $i$ ($1\\leq i\\leq n$) $b_i+c_i=a_i$\n- $b$ is non-decreasing, which means that for every $1<i\\leq n$, $b_i\\geq b_{i-1}$ must hold\n- $c$ is non-increasing, which means that for every $1<i\\leq n$, $c_i\\leq c_{i-1}$ must hold\n\nYou have to minimize $\\max(b_i,c_i)$. In other words, you have to minimize the maximum number in sequences $b$ and $c$.\n\nAlso there will be $q$ changes, the $i$-th change is described by three integers $l,r,x$. You should add $x$ to $a_l,a_{l+1}, \\ldots, a_r$.\n\nYou have to find the minimum possible value of $\\max(b_i,c_i)$ for the initial sequence and for sequence after each change.",
    "tutorial": "Since sequence $b$ is non-decreasing and sequence $c$ is non-increasing, we need to mimimize $\\max(c_1,b_n)$. Now observe that if $a_i>a_{i-1}$ then $b_i=b_{i-1}+a_i-a_{i-1}$ and $c_i=c_{i-1}$.Else if $a_i<a_{i-1}$ then $b_i=b_{i-1}$ but $c_i=c_{i-1}+a_i-a_{i-1}$. Now we calculate $\\sum\\limits_{i=2}^{n}\\max(0,a_i-a_{i-1})$.Let this sum be $K$. Now lets assume $c_1$ is $x$. So then $b_1$ is $a_1-x$.And as observed before $b_n = a_1-x+K$. Now we just need to minimize $\\max(x,a_1-x+K)$. Now it is easily observable that $x$ should be $\\dfrac{a_1+K}{2}$. For the changes, since we only need to know $\\sum\\max(0,a_i-a_{i-1})$, so only $a_l-a_{l-1}$ and $a_r-a_{r-1}$ will change. Total time complexity: $O(n+q)$.",
    "code": "#include<cstdio>\n#include<cmath>\n#define re register\n#define int long long\nusing namespace std;\ninline int read(){\n\tre int t=0,f=0;re char v=getchar();\n\twhile(v<'0')f|=(v=='-'),v=getchar();\n\twhile(v>='0')t=(t<<3)+(t<<1)+v-48,v=getchar();\n\treturn f?-t:t;\n}\nint n,a[100002],sumg,suml,a1,A,B,C,q;\ninline int check(){\n\treturn ceil((double)(a1+sumg)/2.0);\n}\ninline void cg(re int x,re int y){\n\tif(x>n)return;\n\ta[x]>0?sumg-=a[x]:suml+=a[x];\n\ta[x]+=y;\n\ta[x]>0?sumg+=a[x]:suml-=a[x];\n}\nsigned main(){\n\tn=read();\n\tfor(re int i=1;i<=n;++i)a[i]=read();\n\tfor(re int i=2;i<=n;++i){\n\t\tif(a[i]>a[i-1])sumg+=a[i]-a[i-1];else suml+=a[i-1]-a[i];\n\t}\n\tfor(re int i=n;i;--i)a[i]=a[i]-a[i-1];\n\ta1=a[1];\n\tprintf(\"%lld\\n\",check());\n\tq=read();\n\twhile(q--){\n\t\tre int l=read(),r=read(),x=read();\n\t\tif(l==1)a1+=x;\n\t\telse cg(l,x);\n\t\tcg(r+1,-x);\n\t\tprintf(\"%lld\\n\",check());\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1406",
    "index": "E",
    "title": "Deleting Numbers",
    "statement": "\\textbf{This is an interactive problem.}\n\nThere is an unknown integer $x$ ($1\\le x\\le n$). You want to find $x$.\n\nAt first, you have a set of integers $\\{1, 2, \\ldots, n\\}$. You can perform the following operations no more than $10000$ times:\n\n- A $a$: find how many numbers are multiples of $a$ in the current set.\n- B $a$: find how many numbers are multiples of $a$ in this set, and then delete all multiples of $a$, but $x$ will never be deleted (even if it is a multiple of $a$). In this operation, $a$ must be greater than $1$.\n- C $a$: it means that you know that $x=a$. This operation can be only performed once.\n\nRemember that in the operation of type B $a>1$ must hold.\n\nWrite a program, that will find the value of $x$.",
    "tutorial": "If we know what prime factors x has, we can find $x$ just using bruteforce. To find the prime factors, we can just do $B~p$ for every prime $p$ in ascending order, meanwhile calculate the numbers there supposed to be without $x$, if it differs with the number the interactor gives, then $x$ contains the prime factor $p$. This way, we can find every prime factor except for the smallest one. Let $m$ be the number of primes no greater than $n$. Then we can split the prime numbers into $\\sqrt m$ groups. After finishing asking a group, ask $A~1$ and check if the return value same as it supposed to be without $x$. If it's the first time finding it different, it means the smallest prime number is in the range, then just check every prime numbers in the range by asking $A~p$. After finding the prime factors, for each factor, ask $A~p^k$, it can be proved this step will be done around $\\log(n)$ times. The total number of operations if around $m+2\\sqrt m+\\log(n)$, the total time complexity is $O(n\\log n)$",
    "code": "#include<bits/stdc++.h>\n#define re register\n#define int long long\nusing namespace std;\nbool vis[100002];\nint pri[100002],tot,n,x,sum,ans,ia;\nsigned main(){\n\tsrand(19260817); \n\tscanf(\"%lld\",&n);\n\tfor(re int i=2; i<=n; ++i) {\n\t\tif(!vis[i]) {\n\t\t\tpri[++tot]=i;\n\t\t\tif(i<=sqrt(n))\n\t\t\tfor(re int j=i*i; j<=n; j+=i)vis[j]=1;\n\t\t\t}\n\t}\n\tmemset(vis,0,sizeof(vis));\n\tre int k=sqrt(tot);sum=n;ans=1;\n\tfor(re int i=1;i<=tot;++i){\n\t    if(i>=k&&ans*pri[i-k+1]>n)break;\n\t\tprintf(\"B %lld\",pri[i]);cout<<endl;\n\t\tre int num=0;\n\t\tfor(re int j=pri[i];j<=n;j+=pri[i]){\n\t\t\tif(!vis[j]){\n\t\t\t\t++num;--sum;\n\t\t\t\tvis[j]=1;\n\t\t\t}\n\t\t}\n\t\tscanf(\"%lld\",&x);\n\t\tif(x!=num){\n\t\t\tfor(re int kk=pri[i];kk<=n;kk*=pri[i]){\n\t\t\t\t\tprintf(\"A %lld\",kk);cout<<endl;\n\t\t\t\t\tscanf(\"%lld\",&x);\n\t\t\t\t\tif(x)ans*=pri[i];\n\t\t\t\t\telse break;\n\t\t\t}\n\t\t}\n\t\tif((i==tot||i%k==0)&&!ia){\n\t\t\tprintf(\"A 1\");cout<<endl;\n\t\t\tscanf(\"%lld\",&x);\n\t\t\tif(x!=sum){\n\t\t\t\tfor(re int j=i-k+1;j<=i;++j){\n\t\t\t\t\tfor(re int kk=pri[j];kk<=n;kk*=pri[j]){\n\t\t\t\t\t\tprintf(\"A %lld\",kk);cout<<endl;\n\t\t\t\t\t\tscanf(\"%lld\",&x);\n\t\t\t\t\t\tif(x)ans*=pri[j],ia=1;\n\t\t\t\t\t\telse break;\n\t\t\t\t\t}\n\t\t\t\t\tif(ia)break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"C %lld\",ans);cout<<endl;\n}",
    "tags": [
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1407",
    "index": "A",
    "title": "Ahahahahahahahaha",
    "statement": "Alexandra has an even-length array $a$, consisting of $0$s and $1$s. The elements of the array are enumerated from $1$ to $n$. She wants to remove \\textbf{at most} $\\frac{n}{2}$ elements (where $n$ — length of array) in the way that alternating sum of the array will be equal $0$ (i.e. $a_1 - a_2 + a_3 - a_4 + \\dotsc = 0$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.\n\nFor example, if she has $a = [1, 0, 1, 0, 0, 0]$ and she removes $2$nd and $4$th elements, $a$ will become equal $[1, 1, 0, 0]$ and its alternating sum is $1 - 1 + 0 - 0 = 0$.\n\nHelp her!",
    "tutorial": "Let $cnt_0$ be the count of zeroes in the array, $cnt_1$ - count of ones. Then if $cnt_1 \\leq \\frac{n}{2}$, we remove all ones and alternating sum, obliously, equals $0$. Otherwise, $cnt_0 < \\frac{n}{2}$, we remove all zeroes and if $cnt_1$ is odd - plus another $1$. In this case, alternating sum equals $1 - 1 + 1 - \\ldots - 1 = 0$ (because count of remaining ones if even) and we'll remove not more than $cnt_0 + 1 \\leq \\frac{n}{2}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int>a(n), ans;\n        int cnt0 = 0;\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n            if (!a[i]) cnt0++;\n        }\n        int cnt1 = n - cnt0;\n        if (cnt0 >= n / 2) {\n            cout << cnt0 << '\\n';\n            for (int i = 0; i < cnt0; i++) cout << 0 << ' ';\n        } else {\n            cout << cnt1 - cnt1 % 2 << '\\n';\n            for (int i = 0; i < cnt1 - cnt1 % 2; i++) {\n                cout << 1 << ' ';\n            }\n        }\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1407",
    "index": "B",
    "title": "Big Vova",
    "statement": "Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace \"Zmey-Gorynych\", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years.\n\nYou're given $n$ positive integers $a_1, a_2, \\dots, a_n$. Using each of them \\textbf{exactly at once}, you're to make such sequence $b_1, b_2, \\dots, b_n$ that sequence $c_1, c_2, \\dots, c_n$ is lexicographically maximal, where $c_i=GCD(b_1,\\dots,b_i)$ - the greatest common divisor of the first $i$ elements of $b$.\n\nAlexander is really afraid of the conditions of this simple task, so he asks you to solve it.\n\nA sequence $a$ is lexicographically smaller than a sequence $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.",
    "tutorial": "We'll describe several constructive solutions for this task, differing by the time complexity: 1. $O(n^2log A)$ Let $b$ be an empty sequence in the beginning. We'll consequently transfer elements from $a$ to $b$ in a certain order. Let's notice that if we've already transfered $(k-1)$ elements then we can always choose to the place of $b_k$ any element $a_j$ left in $a$ such that $c_k=gcd(b_1,\\dots,b_{k-1},a_j)$ is maximal. A-priory, if we've fixed the first $(k-1)$ elements of the sequence, lexicographically greater would be the one in which $c_k$ is maximal. The particular value of $b_k$ here doesn't matter: each element $c_i$ divides all the previous ones, so $gcd(b_k, c_j)=gcd(c_k,c_j)$ for any $j>=k$. So the algorithm is following: let's say that we have auxiliary element of the sequence $c_0=0$, and $gcd(0, k)=k$ for any integer $k\\geq1$. Then we make $n$ iterations: during the $i$-th one we choose such $a_j$ (overall elements left in $a$) that the value of $gcd(a_j, c_{i-1})$ is maximal, and make $b_i=a_j$, removing $a_j$ from the sequence $a$. The $i$-th iteration will be passed in $O((n-i)log A)$, where $A$ is the greatest possible value in the original $a$ sequence, $log A$ is the time complexity of the Euclidean algorithm for searching $GCD$. Via summing time complexities overall iterations we get summary $O(n^2log A)$ time complexity of the algorithm. 2. $O(Anlog A)$ The main idea is the same as in the first solution, but the realisation is different: the main array $a$ is contained as an array $cnt$ of size $A$, where $cnt_x$ is the amount of elements in $a$ that are equal to $x$. Searching for the optimal element $b_k$ is $O(Alog A)$ for each of $n$ iterations, so the summary is $O(Anlog A)$. 3. $O(nlog^2 A)$ This solution is based on the following idea: for each $i>1$ either $c_i=c_{i-1}$ or $2c_i\\leq c_{i-1}$. That means any possible sequence $c$ contains $O(log A)$ different values. So we do $O(log A)$ iterations, on each we find the value $x$ among the elements left in $a$ that maximizes $O(c_k, x)$ (where $k$ is the amount of elements already transfered to $b$, and $c_k=gcd(b_1,\\dots,b_k)$) and transfer all the elements left in $a$ of the value equal to $x$ to the end of $b$. Each iteration is done in $O(n log A)$ so the total time complexity is $O(n log^2 A)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    int a[n];\n    int mi = 0;\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n        mi = (a[i] > a[mi] ? i : mi);\n    }\n    vector<int> b(n);\n    b[0] = a[mi]; a[mi] = 0;\n    int cg = b[0];\n    for (int i = 1; i < n; i++) {\n        int ci = 0, cans = 0;\n        for (int j = 0; j < n; j++)\n            if (a[j] && __gcd(a[j], cg) > cans) {\n                cans = __gcd(a[j], cg);\n                ci = j;\n            }\n        b[i] = a[ci];\n        cg = cans;\n        a[ci] = 0;\n    }\n    for (int i = 0; i < n; i++)\n        cout << b[i] << ' ';\n    cout << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n    return 0;\n}\n\n",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1407",
    "index": "C",
    "title": "Chocolate Bunny",
    "statement": "\\textbf{This is an interactive problem.}\n\nWe hid from you a permutation $p$ of length $n$, consisting of the elements from $1$ to $n$. You want to guess it. To do that, you can give us 2 different indices $i$ and $j$, and we will reply with $p_{i} \\bmod p_{j}$ (remainder of division $p_{i}$ by $p_{j}$).\n\nWe have enough patience to answer at most $2 \\cdot n$ queries, so you should fit in this constraint. Can you do it?\n\nAs a reminder, a permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Observation: $(a \\bmod b > b \\bmod a) \\Leftrightarrow (a < b)$. Proof: if $a > b$, then $(a \\bmod b) < b = (b \\bmod a$). If $a = b$, then $(a \\bmod b) = (b \\bmod a) = 0$. Let's maintain index $mx$ of maximal number on the reviewed prefix (initially $mx = 1$). Let's consider index $i$. Ask two queries: ? i mx and ? mx i. We'll know the less from both of them and either guess $p_{mx}$ and update $mx = i$ or guess $p_i$. In the end, all numbers will be guessed except $p_{mx}$, that, obviously, equals $n$. In total, we'll make $2 \\cdot n - 2$ queries.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint ask(int x, int y) {\n    cout << \"? \" << x + 1 << ' ' << y + 1 << endl;\n    int z;\n    cin >> z;\n    return z;\n}\nint main() {\n    int n;\n    cin >> n;\n    vector<int>ans(n, -1);\n    int mx = 0;\n    for (int i = 1; i < n; i++) {\n        int a = ask(mx, i);\n        int b = ask(i, mx);\n        if (a > b) {\n            ans[mx] = a;\n            mx = i;\n        } else {\n            ans[i] = b;\n        }\n    }\n    ans[mx] = n;\n    cout << \"! \";\n    for (int i = 0; i < n; i++) cout << ans[i] << ' ';\n    cout << endl;\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1407",
    "index": "D",
    "title": "Discrete Centrifugal Jumps",
    "statement": "There are $n$ beautiful skyscrapers in New York, the height of the $i$-th one is $h_i$. Today some villains have set on fire first $n - 1$ of them, and now the only safety building is $n$-th skyscraper.\n\nLet's call a jump from $i$-th skyscraper to $j$-th ($i < j$) \\textbf{discrete}, if all skyscrapers between are strictly lower or higher than both of them. Formally, jump is discrete, if $i < j$ and one of the following conditions satisfied:\n\n- $i + 1 = j$\n- $\\max(h_{i + 1}, \\ldots, h_{j - 1}) < \\min(h_i, h_j)$\n- $\\max(h_i, h_j) < \\min(h_{i + 1}, \\ldots, h_{j - 1})$.\n\nAt the moment, Vasya is staying on the first skyscraper and wants to live a little longer, so his goal is to reach $n$-th skyscraper with minimal count of discrete jumps. Help him with calcualting this number.",
    "tutorial": "Consider such a jump, when all of the skyscrapers between are smaller than initial and final (another case is similar). Let's stand on the skyscraper with index $x$. We want to find out whether $y$-th skyscraper satisfies our conditions. We have two cases: $h_x \\leq h_y$. Then, obviously, $y$ is the first skyscraper that not lower than $x$ (otherwise we have a building that higher than starter, it's contradiction). $h_x > h_y$. Then, it's easy to see, that $x$ is the first skyscraper to the left of $y$, that higher than $y$ for the same reason. For another case, reasoning is similar, but skyscaper should be lower, not higher. We can see, that amount of pairs $i, j : i < j$ such that we can jump from $i$ to $j$, we can estimate as $O(n)$. So, we can find for each skyscraper the nearest bigger (and smaller) one using stack and simply count $dp_i$ - minimal count of jumps that we need to reach $i$-th skyscraper. Check the solution for a better understanding.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int INF = 1e9 + 1;\nconst int maxn = 3e5 + 1;\nint h[maxn], dp[maxn], lge[maxn], lle[maxn], rge[maxn], rle[maxn];\nvector<int>jumps[maxn];\nint main() {\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; i++) {\n        cin >> h[i];\n        dp[i] = INF;\n    }\n    dp[0] = 0;\n    vector<pair<int, int> >st;\n    for (int i = 0; i < n; i++) { // the nearest greater from the left\n        while (!st.empty() && st.back().first < h[i]) {\n            st.pop_back();\n        }\n        if (st.empty()) lge[i] = -1;\n        else lge[i] = st.back().second;\n        st.push_back({h[i], i});\n    }\n    st.clear();\n    for (int i = 0; i < n; i++) { // the nearest less from the left\n        while (!st.empty() && st.back().first > h[i]) {\n            st.pop_back();\n        }\n        if (st.empty()) lle[i] = -1;\n        else lle[i] = st.back().second;\n        st.push_back({h[i], i});\n    }\n    st.clear();\n    for (int i = n - 1; i >= 0; i--) { // the nearest greater from the right\n        while (!st.empty() && st.back().first < h[i]) {\n            st.pop_back();\n        }\n        if (st.empty()) rge[i] = -1;\n        else rge[i] = st.back().second;\n        st.push_back({h[i], i});\n    }\n    st.clear();\n    for (int i = n - 1; i >= 0; i--) { // the nearest less from the right\n        while (!st.empty() && st.back().first > h[i]) {\n            st.pop_back();\n        }\n        if (st.empty()) rle[i] = -1;\n        else rle[i] = st.back().second;\n        st.push_back({h[i], i});\n    }\n    st.clear();\n    for (int i = 0; i < n; i++) {\n        if (rle[i] != -1) jumps[i].push_back(rle[i]);\n        if (rge[i] != -1) jumps[i].push_back(rge[i]);\n        if (lle[i] != -1) jumps[lle[i]].push_back(i);\n        if (lge[i] != -1) jumps[lge[i]].push_back(i);\n    }\n    for (int i = 0; i < n; i++) {\n        for (int to : jumps[i]) {\n            dp[to] = min(dp[to], dp[i] + 1);\n        }\n    }\n    cout << dp[n - 1];\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1407",
    "index": "E",
    "title": "Egor in the Republic of Dagestan",
    "statement": "Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.\n\nThere are $n$ cities in the republic, some of them are connected by $m$ directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city $1$, travel to the city $n$ by roads along some path, give a concert and fly away.\n\nAs any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads — in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from $1$ to $n$, and for security reasons it has to be the shortest possible.\n\nEgor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from $1$ to $n$ or the shortest path's length would be greatest possible.\n\nA path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only.\n\nThe path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.",
    "tutorial": "**This task has a simple intuitive proof, but I wanted to describe it formally so it's pretty complicated.** We'll show a constructive algorithm for this task and proof it's correctness. We also provide a realisation with $O(n+m)$ time complexity. Let's change each edge's direction to the opposite. Then for vertex of color $c$ all incoming edges of color $c$ and only they are safe. We call a schedule optimal for $x$ if the shortest path (from $n$) to $x$ along the safe edges is the longest possible. We call a path (from $n$) to $x$ optimal if it's the shortest path for any optimal schedule for $x$. So we have to find an optimal schedule for $1$ and the length of optimal path for $1$. Let's make four parameters for each vertex $x$: $b[x]$ - the length of optimal path to $x$, if $x$ is black, $w[x]$ - the length of optimal path to $x$, if $x$ is white, $dp[x]$ - the length of optimal path to $x$ among all possible schedules, $col[x]$ - the color of $x$. The algorithm is following: Initially $b[n]=w[n]=dp[n]=0$, $b[x]=w[x]=dp[x]=+\\infty$ for all $x\\neq n$. All vertices are unpainted. If there is no unpainted vertex $x$ such that $dp[x]<+\\infty$ (including the case when all vertices are painted) - go to point $6$ Among all unpainted vertices choose vertex $u$ with the smallest possible value of $dp[u]$. If $b[u] > w[u]$ set $col[u]=0$. If $w[u] > b[u]$ set $col[u]=1$. If $w[u] = b[u]$ then $col[u]$ can be either $0$ or $1$. If $b[u] > w[u]$ set $col[u]=0$. If $w[u] > b[u]$ set $col[u]=1$. If $w[u] = b[u]$ then $col[u]$ can be either $0$ or $1$. Watch each edge $(u, v)$ outgoing from $u$. Let an edge's color be $t$.If $t=0$ (black edge) - set $b[v]=min(b[v], dp[u]+1)$. If $t=1$ (white edge) - set $w[v]=min(w[v], dp[u]+1)$. Then set $dp[v]=max(b[v], w[v])$. If $t=0$ (black edge) - set $b[v]=min(b[v], dp[u]+1)$. If $t=1$ (white edge) - set $w[v]=min(w[v], dp[u]+1)$. Then set $dp[v]=max(b[v], w[v])$. Go to point $2$. For each unpainted vertex set the color just as in point $3$. The value of $dp[1]$ is equal to the desired answer (excluding $dp[1]=\\infty$ case: that means there's no way from $n$ to $1$ for the constructed schedule, and the answer is $-1$), and the values of $col$ form the optimal schedule. Correctness proof Let $lb[x]$, $lw[x]$ and $l[x]$ be the real optimal values of $b[x]$, $w[x]$ and $dp[x]$. We'll show that the parameters found by the algorithm are optimal. Let's proof some statements: 1. Any optimal path is simple. This statement is obvious, because the shortest path in any graph doesn't contain repeating vertices. 2. For any black edge $(u, v$) $l[u]+1\\geq lb[v]$. For any schedule the length of the shortest path from $n$ to $u$ is not greater than $l[u]$, and the color of $v$ is fixed, so the length of the shortest path from $n$ to $v$ is not greater than $l[u]+1$. For white edges and correspondingly $lw[u]$ the analogous statement is correct. 3. $b[x]\\geq lb[x]$, $w[x]\\geq lw[x]$ for any vertex $x$ at every moment. Before the first iteration the statement $3$ is correct. Let $u$ be selected in the beginning of some iteration, and we update the parameters of $v$ for a black edge $(u, v)$. Let the statement $3$ be correct before the update. Then due to the statement $2$ $l[u]+1\\geq lb[v]$. $b[u]\\geq lb[u]$ and $w[u]\\geq lw[u]$, so $dp[u]=max(b[u],w[u])\\geq l[u]=max(lb[u],lw[u])$, and $dp[u]+1\\geq l[u]+1\\geq lb[v]$. After the update the value of $b[v]$ can stay the same or be changed to $dp[u]+1$, but since as $b[v]\\geq l[v]$, the final value of $b[v]$ is not less than $l[v]$, so the statement $3$ remains correct after the update. Analogously we can show that for white edges it's correct, too. By induction we have that the statement $3$ is invariant, i.e. it's always correct. We can notice that for each painted vertex $x$ it's value of $dp[x]$ is not smaller than the value of $dp[y]$ for any vertex $y$ painted before the $x$. Also, the values of $dp[x]$, $b[x]$ and $w[x]$ remain constant after the iteration when $x$ is painted. These facts are easy-to-proof, but for shortness we won't do it here. Lemma: in the end of the $k$-th iteration for each vertex $x$ the values of $b[x]$, $w[x]$ and $dp[x]$ correspond to the shortest (for the current schedule) paths passing through the painted vertices only (excluding $x$). Proof: we'll show it by induction on the number of iterations. It's easy to see that after the first iteration the Lemma remains correct. Let the Lemma be correct after the first $k$ iterations. Let $x$ be painted during the $(k+1)$-th iteration. Then $b[x]$ and $w[x]$ are already equal to the lengths of shortest paths to $x$, passing through painted vertices only and ending by black and white edges, correspondingly (it's obvious, proof it yourself if you don't believe). The length of the shortest path for already painted vertices won't change, because $dp[x]$ is not smaller than the values of $dp$ of previously painted vertices. Thus, at the end of the algorithm we get the desired schedule, where $dp[x]$ for each $x$ is equal to the length of the shortest path to $x$, and $dp[x]\\geq l[x]$; then from these two statements follows the fact that $dp[x]=l[x]$ for all vertices $x$, what means that the constructed schedule is optimal. Realisation This algorithm can be realised as a modified BFS, where the vertex is added to the queue just as it's value becomes smaller than infinity (in the code the value of <<infinity>> can be just $n$). It's easy to proof that such realisation is equivalent to the algorithm.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 1e6 + 1;\n\nvector<int> bg[maxn], rg[maxn];\nint b[maxn], r[maxn], d[maxn], col[maxn];\nint n, m;\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0); cout.tie(0);\n    cin >> n >> m;\n    for (int i = 0; i < m; i++) {\n        int u, v, t;\n        cin >> u >> v >> t;\n        --u; --v;\n        if (!t) bg[v].push_back(u);\n        else rg[v].push_back(u);\n    }\n    for (int i = 0; i < n; i++)\n        d[i] = b[i] = r[i] = n;\n    queue<int> q;\n    q.push(n - 1);\n    d[n - 1] = r[n - 1] = b[n - 1] = 0;\n    while (!q.empty()) {\n        int x = q.front();\n        q.pop();\n        for (auto to : bg[x]) {\n            if (b[to] < n) continue;\n            b[to] = d[x] + 1;\n            if (max(b[to], r[to]) < n) {\n                q.push(to);\n                d[to] = max(b[to], r[to]);\n            }\n        }\n        for (auto to : rg[x]) {\n            if (r[to] < n) continue;\n            r[to] = d[x] + 1;\n            if (max(b[to], r[to]) < n) {\n                q.push(to);\n                d[to] = max(b[to], r[to]);\n            }\n        }\n    }\n    if (d[0] == n) cout << \"-1\\n\";\n    else cout << d[0] << '\\n';\n    for (int i = 0; i < n; i++) {\n        if (b[i] > r[i]) col[i] = 0;\n        else col[i] = 1;\n        cout << col[i];\n    }\n    return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1408",
    "index": "A",
    "title": "Circle Coloring",
    "statement": "You are given three sequences: $a_1, a_2, \\ldots, a_n$; $b_1, b_2, \\ldots, b_n$; $c_1, c_2, \\ldots, c_n$.\n\nFor each $i$, $a_i \\neq b_i$, $a_i \\neq c_i$, $b_i \\neq c_i$.\n\nFind a sequence $p_1, p_2, \\ldots, p_n$, that satisfy the following conditions:\n\n- $p_i \\in \\{a_i, b_i, c_i\\}$\n- $p_i \\neq p_{(i \\mod n) + 1}$.\n\nIn other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $i,i+1$ adjacent for $i<n$ and also elements $1$ and $n$) will have equal value.\n\nIt can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.",
    "tutorial": "At first, set $p_1 = a_1$. Then for $i \\in \\{2, \\ldots, n-1\\}$ if $a_i = p_{i-1}$, then set $p_i = b_i$. Otherwise, set $p_i = a_i$. In the end, set $p_n$ to one of $\\{a_n, b_n, c_n\\}$, which is not equal to $p_1$ or $p_{n-1}$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1408",
    "index": "B",
    "title": "Arrays Sum",
    "statement": "You are given a \\textbf{non-decreasing} array of \\textbf{non-negative} integers $a_1, a_2, \\ldots, a_n$. Also you are given a positive integer $k$.\n\nYou want to find $m$ \\textbf{non-decreasing} arrays of \\textbf{non-negative} integers $b_1, b_2, \\ldots, b_m$, such that:\n\n- The size of $b_i$ is equal to $n$ for all $1 \\leq i \\leq m$.\n- For all $1 \\leq j \\leq n$, $a_j = b_{1, j} + b_{2, j} + \\ldots + b_{m, j}$. In the other word, array $a$ is the sum of arrays $b_i$.\n- The number of different elements in the array $b_i$ is at most $k$ for all $1 \\leq i \\leq m$.\n\nFind the minimum possible value of $m$, or report that there is no possible $m$.",
    "tutorial": "Case $k = 1$: If all $a_i$ are equal the answer is $1$. Otherwise the answer is $-1$. Case $k > 1$: Let's consider an array $a' = (a_2 - a_1, a_3 - a_2, \\ldots, a_n - a_{n-1})$ and arrays $b_i' = (b_{i, 2} - b_{i, 1}, b_{i, 3} - b_{i, 2}, \\ldots, b_{i, n} - b_{i, n-1})$. The number of non-zero elements in $b_i'$ is at most $k-1$. Let's define $c$ as the number of non-zero elements in $a'$ or in the other words the number of indices $i$, such that $a_i \\neq a_{i+1}$. The answer is at least $\\lceil \\frac{c}{k-1} \\rceil$. It's easy to prove that there exists arrays $b_i$ with such number $m$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1408",
    "index": "C",
    "title": "Discrete Acceleration",
    "statement": "There is a road with length $l$ meters. The start of the road has coordinate $0$, the end of the road has coordinate $l$.\n\nThere are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end and the second car will drive from the end to the start.\n\nInitially, they will drive with a speed of $1$ meter per second. There are $n$ flags at \\textbf{different} coordinates $a_1, a_2, \\ldots, a_n$. Each time when any of two cars drives through a flag, the speed of that car increases by $1$ meter per second.\n\nFind how long will it take for cars to meet (to reach the same coordinate).",
    "tutorial": "Solution $1$: Let's make a binary search on the answer. If we have some time $t$ we can calculate the coordinate of each car after $t$ seconds. Let's define them as $x_1$ and $x_2$. If $x_1 \\leq x_2$ let's move the left bound of the binary search, otherwise, let's move the right bound. Time complexity: $O(n \\log{\\frac{1}{\\epsilon}})$. Solution $2$: Let's calculate the time for each car and each flag, after which the car will reach this flag. We can find the first flag from left to right, on which the second car was before the first car. Using it we can find the segment between flags, on which the cars will meet. After that the answer can be found by some simple formula using their speed and times, on which they will reach the left and the right bound of this segment. Time complexity: $O(n)$.",
    "tags": [
      "binary search",
      "dp",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1408",
    "index": "D",
    "title": "Searchlights",
    "statement": "There are $n$ robbers at coordinates $(a_1, b_1)$, $(a_2, b_2)$, ..., $(a_n, b_n)$ and $m$ searchlight at coordinates $(c_1, d_1)$, $(c_2, d_2)$, ..., $(c_m, d_m)$.\n\nIn one move you can move each robber to the right (increase $a_i$ of each robber by one) or move each robber up (increase $b_i$ of each robber by one). Note that you should either increase \\textbf{all} $a_i$ or \\textbf{all} $b_i$, you \\textbf{can't} increase $a_i$ for some points and $b_i$ for some other points.\n\nSearchlight $j$ can see a robber $i$ if $a_i \\leq c_j$ and $b_i \\leq d_j$.\n\nA configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair $i,j$ such that searchlight $j$ can see a robber $i$).\n\nWhat is the minimum number of moves you need to perform to reach a safe configuration?",
    "tutorial": "Let's define as $x$ our move to the right and as $y$ our move to the up. For all pairs $(i, j)$ of (robber, searchlight) at least one of this should be true: $x + a_i > c_j$, $y + b_i > d_j$. So if $x \\leq c_j - a_i$ then $y \\geq d_j - b_i + 1$. Let's make an array $r$ of length $C = 10^6$ and write on each position of $x$ the minimum value of $y$. For each $(i, j)$ we should make $r_x = max(r_x, d_j - b_i + 1)$ for all $x \\leq c_j - a_i$. So we have $nm$ queries of $max=$ on prefix. We can do it using suffix maximums. After we will calculate all $a_x$ the answer is $\\min\\limits_{x}{(x + r_x)}$. Time complexity: $O(nm + C)$.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1408",
    "index": "E",
    "title": "Avoid Rainbow Cycles",
    "statement": "You are given $m$ sets of integers $A_1, A_2, \\ldots, A_m$; elements of these sets are integers between $1$ and $n$, inclusive.\n\nThere are two arrays of positive integers $a_1, a_2, \\ldots, a_m$ and $b_1, b_2, \\ldots, b_n$.\n\nIn one operation you can delete an element $j$ from the set $A_i$ and pay $a_i + b_j$ coins for that.\n\nYou can make several (maybe none) operations (some sets can become empty).\n\nAfter that, you will make an edge-colored undirected graph consisting of $n$ vertices. For each set $A_i$ you will add an edge $(x, y)$ with color $i$ for all $x, y \\in A_i$ and $x < y$. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.\n\nYou call a cycle $i_1 \\to e_1 \\to i_2 \\to e_2 \\to \\ldots \\to i_k \\to e_k \\to i_1$ ($e_j$ is some edge connecting vertices $i_j$ and $i_{j+1}$ in this graph) rainbow if all edges on it have different colors.\n\nFind the minimum number of coins you should pay to get a graph without rainbow cycles.",
    "tutorial": "Let's make a bipartite graph with $m$ vertices on the left side and $n$ vertices on the right side. We will connect vertex $i$ from the left side with all elements of $A_i$. It can be proven, that the graph, which we create using our sets don't have rainbow cycles if and only if our bipartite graph don't have cycles. So, our task is equivalent of finding the Maximum Spanning Tree of this bipartite graph, where edge between $i$ (from left side) and $j$ (from right side) has weight equal to $a_i + b_j$.",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1408",
    "index": "F",
    "title": "Two Different",
    "statement": "You are given an integer $n$.\n\nYou should find a list of pairs $(x_1, y_1)$, $(x_2, y_2)$, ..., $(x_q, y_q)$ ($1 \\leq x_i, y_i \\leq n$) satisfying the following condition.\n\nLet's consider some function $f: \\mathbb{N} \\times \\mathbb{N} \\to \\mathbb{N}$ (we define $\\mathbb{N}$ as the set of positive integers). In other words, $f$ is a function that returns a positive integer for a pair of positive integers.\n\nLet's make an array $a_1, a_2, \\ldots, a_n$, where $a_i = i$ initially.\n\nYou will perform $q$ operations, in $i$-th of them you will:\n\n- assign $t = f(a_{x_i}, a_{y_i})$ ($t$ is a temporary variable, it is used \\textbf{only} for the next two assignments);\n- assign $a_{x_i} = t$;\n- assign $a_{y_i} = t$.\n\nIn other words, you need to \\textbf{simultaneously} change $a_{x_i}$ and $a_{y_i}$ to $f(a_{x_i}, a_{y_i})$. Note that during this process $f(p, q)$ is always the same for a fixed pair of $p$ and $q$.\n\nIn the end, there should be at most two different numbers in the array $a$.\n\nIt should be true for any function $f$.\n\nFind any possible list of pairs. The number of pairs should not exceed $5 \\cdot 10^5$.",
    "tutorial": "Claim: for each $k$, we can perform operations on $2^k$ elements to make all numbers the same. You can prove this fact with induction by $k$. For $k=0$ this fact is obvious, For $k>0$, at first change first $2^{k-1}$ and last $2^{k-1}$ points to the same value (assume that those values are $x$ and $y$, respectively). And then, perform operations on points $i$ and $i + 2^{k-1}$, to simultaneously change them to $f(x,y)$. After that, all values will be equal $\\blacksquare$. Using this observation, it is easy to leave only two different values in the array. Find the maximum $2^k \\leq n$, and then change first $2^k$ numbers to the same number, and then change last $2^k$ elements to the same number (note that $2^k + 2^k > n$, so in the end there will be only two different elements).",
    "tags": [
      "constructive algorithms",
      "divide and conquer"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1408",
    "index": "G",
    "title": "Clusterization Counting",
    "statement": "There are $n$ computers in the company network. They are numbered from $1$ to $n$.\n\nFor each pair of two computers $1 \\leq i < j \\leq n$ you know the value $a_{i,j}$: the difficulty of sending data between computers $i$ and $j$. All values $a_{i,j}$ for $i<j$ are different.\n\nYou want to separate all computers into $k$ sets $A_1, A_2, \\ldots, A_k$, such that the following conditions are satisfied:\n\n- for each computer $1 \\leq i \\leq n$ there is \\textbf{exactly} one set $A_j$, such that $i \\in A_j$;\n- for each two pairs of computers $(s, f)$ and $(x, y)$ ($s \\neq f$, $x \\neq y$), such that $s$, $f$, $x$ are from the same set but $x$ and $y$ are from different sets, $a_{s,f} < a_{x,y}$.\n\nFor each $1 \\leq k \\leq n$ find the number of ways to divide computers into $k$ groups, such that all required conditions are satisfied. These values can be large, so you need to find them by modulo $998\\,244\\,353$.",
    "tutorial": "Sort all edges by their weights. In this order, maintain the DSU. For each connected component, let's maintain $dp_k$: the number of ways to divide this component into $k$ groups. When you merge two connected clusters, you have to recalculate the DP as in the multiplication of two polynomials (of course, if you bound $k$ by the size of the connected component, similarly to the similar tree DP's, it works in $O(n^2)$ total). Once some connected component becomes a clique, then we obtain a new cluster, and you should increase $dp_1$ for this connected component by $1$.",
    "tags": [
      "combinatorics",
      "dp",
      "dsu",
      "fft",
      "graphs",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1408",
    "index": "H",
    "title": "Rainbow Triples",
    "statement": "You are given a sequence $a_1, a_2, \\ldots, a_n$ of non-negative integers.\n\nYou need to find the largest number $m$ of triples $(i_1, j_1, k_1)$, $(i_2, j_2, k_2)$, ..., $(i_m, j_m, k_m)$ such that:\n\n- $1 \\leq i_p < j_p < k_p \\leq n$ for each $p$ in $1, 2, \\ldots, m$;\n- $a_{i_p} = a_{k_p} = 0$, $a_{j_p} \\neq 0$;\n- all $a_{j_1}, a_{j_2}, \\ldots, a_{j_m}$ are different;\n- all $i_1, j_1, k_1, i_2, j_2, k_2, \\ldots, i_m, j_m, k_m$ are different.",
    "tutorial": "Let's reformulate this problem: you should choose different $i$ with different $a_i > 0$, and for each of them choose one zero to the left and one zero to the right (i.e. for each chosen guy we can assume that we have two vertices in the bipartite graph, and we want to match the left of them with some zero to the left, and the right of them with some zero to the right). Denote the number of zeroes as $z$. Observation 1. The answer does not exceed $\\frac{z}{2}$. Observation 2. If the number of zeroes to the right of number is $\\geq \\frac{z}{2}$, then we will always be able to match it with some zeroes to the right (from Observation 2). You can also make a similar symmetrical observation. Observation 3. Using observation 2, we can separate non-zero numbers into two groups, s.t. numbers on prefix can always be matched with zero to the right, and numbers on suffix can always be matched with zero to the left. Let's denote those sets as $L$ (prefix) and $R$ suffix. Observation 4. For each colour only two numbers are interesting: the rightmost in $L$ and the leftmost in $R$. It is easy to show, for example, if you decided to take some colour but not in the rightmost in $L$ position, you can replace it by the rightmost position in $L$ (of course, corresponding zero to the left can be matched with the new position, as you moved it to the right, and you can still match it with some zero to the right). Symmetrical proof holds for $R$. Observation 5. We derive the following problem: for each colour you want to either choose it in the $L$, choose it in the $R$, or not choose it all. And if you choose it in $L$, then you want to match it with some zeroes on the prefix. If you choose it in $R$, then you want to match it with some zeroes on the suffix. So we can replace each colour to the tuple $(l,r)$ which means that this colour can be matched with either some zero on the prefix of length $l$ of some zero on the suffix of length $r$. And our goal is to find the largest matching. Observation 6. The maximum matching for this type of graph can be found easily: move $x$ backwards, and each time match $x$ with some unmatched pair $(l, r)$ such that $l \\geq x$, and $r$ is minimum among them. Observation 7. After you saw observation 6, you can optimize the solution with a priority queue. And don't remember that the real answer is the smaller value of $\\frac{z}{2}$ and your matching size. P.S. You can also formulate this problem as a matroid intersection, and find the answer using the minimax formula for the matroid intersection + segment tree.",
    "tags": [
      "binary search",
      "data structures",
      "flows",
      "greedy"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1408",
    "index": "I",
    "title": "Bitwise Magic",
    "statement": "You are given a positive integer $k$ and an array $a_1, a_2, \\ldots, a_n$ of non-negative distinct integers not smaller than $k$ and not greater than $2^c-1$.\n\nIn each of the next $k$ seconds, one element is chosen randomly equiprobably out of all $n$ elements and decreased by $1$.\n\nFor each integer $x$, $0 \\leq x \\leq 2^c - 1$, you need to find the probability that in the end the bitwise XOR of all elements of the array is equal to $x$.\n\nEach of these values can be represented as an irreducible fraction $\\frac{p}{q}$, and you need to find the value of $p \\cdot q^{-1}$ modulo $998\\,244\\,353$.",
    "tutorial": "There are several solutions to this problem, with various complexities. Some of our solutions work in less than half a second. The constraints were set to allow most non-naive solutions. Solution 1, DP on Trie Let's look at the bitwise trie. Each node corresponds to some segment $[l, r]$ of possible numbers. Let's note that if you perform operations on numbers in $[l + k, \\ldots, r]$, then the resulting numbers for them won't leave the trie node. So we can come up with the following solution: let's maintain some kind of a DP on this trie. When we took into account numbers from $a$ among $[l + k, \\ldots, r]$, and we should store the FWHT for each number of operations (we can assume that we store some kind of an exponential generating functions for each value in FHWT and maintain the product of those genfuncs for numbers with the corresponding signs). Note that in this FWHT you are interested only in $O(r - l)$ values (because all given numbers have equal prefixes, so if you know the parity of the number, you know the prefix of the total XOR). To recalculate this DP, when we calculated it for children, at first in $O((r - l)k^2)$ you should multiply DP's for the children, and then you should add first $k$ numbers of the right subtree (that you didn't consider yet) to this DP, you can do it for each of them in $O((r - l)k^2)$. If some details are not clear for you here, probably you are not familiar with FWHT enough. Deriving the total complexity of $2^c \\cdot c \\cdot k^3$. Of course, a lot of different further optimizations possible for this solution. Solution 2, Observations The main observation: the number of different tuples $x \\oplus x, x \\oplus (x-1), x \\oplus (x-2), \\ldots, x \\oplus (x - k)$ is around $O(kc)$. Why? Because consider how $x$ is changed during the process, usually only $O(\\log k)$ bits are changed, but once one block of zeroes of the length $O(\\log n)$ is changed to ones. So if we know the last $O(\\log k)$ bits of the number and the length of the block of zeroes after them, we can identify s $x \\oplus x, x \\oplus (x-1), x \\oplus (x-2), \\ldots, x \\oplus (x - k)$. If you notice this, you can note a lot of other similar observations, and derive another solution with better complexity than naive. And then using DP/FWHT, you can upgrade those ideas to the solution. For example, QAQautomaton wrote the solution in $2^c \\cdot c^2 + c^6$ using this idea. I will leave all remaining details as an exercise for the reader.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1409",
    "index": "A",
    "title": "Yet Another Two Integers Problem",
    "statement": "You are given two integers $a$ and $b$.\n\nIn one move, you can choose some \\textbf{integer} $k$ from $1$ to $10$ and add it to $a$ or subtract it from $a$. In other words, you choose an integer $k \\in [1; 10]$ and perform $a := a + k$ or $a := a - k$. You may use \\textbf{different} values of $k$ in different moves.\n\nYour task is to find the \\textbf{minimum} number of moves required to obtain $b$ from $a$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "We can add or subtract $10$ until the difference between $a$ and $b$ becomes less than $10$. And if it is not $0$ after all such moves, we need one additional move. Let $d = |a - b|$ is the absolute difference between $a$ and $b$. The final answer is $\\left\\lfloor\\frac{d}{10}\\right\\rfloor$ plus one if $d \\mod 10 > 0$. This formula can be represented as $d$ divided by $10$ rounded up, in other words $\\left\\lfloor\\frac{d+9}{10}\\right\\rfloor$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tcout << (abs(a - b) + 9) / 10 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1409",
    "index": "B",
    "title": "Minimum Product",
    "statement": "You are given four integers $a$, $b$, $x$ and $y$. Initially, $a \\ge x$ and $b \\ge y$. You can do the following operation \\textbf{no more than} $n$ times:\n\n- Choose either $a$ or $b$ and decrease it by one. However, as a result of this operation, value of $a$ cannot become less than $x$, and value of $b$ cannot become less than $y$.\n\nYour task is to find the \\textbf{minimum} possible product of $a$ and $b$ ($a \\cdot b$) you can achieve by applying the given operation no more than $n$ times.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The only fact required to solve the problem: if we start decreasing the number, we are better to end decreasing it and only then decrease the other number. So, we can just consider two cases: when we decrease $a$ first, and $b$ after that and vice versa, and just take the minimum product of these two results. The rest is just implementation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint a, b, x, y, n;\n\t\tcin >> a >> b >> x >> y >> n;\n\t\tlong long ans = 1e18;\n\t\tfor (int i = 0; i < 2; ++i) {\n\t\t\tint da = min(n, a - x);\n\t\t\tint db = min(n - da, b - y);\n\t\t\tans = min(ans, (a - da) * 1ll * (b - db));\n\t\t\tswap(a, b);\n\t\t\tswap(x, y);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1409",
    "index": "C",
    "title": "Yet Another Array Restoration",
    "statement": "We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array:\n\n- The array consists of $n$ \\textbf{distinct positive} (greater than $0$) integers.\n- The array contains two elements $x$ and $y$ (these elements are \\textbf{known} for you) such that $x < y$.\n- If you sort the array in increasing order (such that $a_1 < a_2 < \\ldots < a_n$), differences between all adjacent (consecutive) elements are equal (i.e. $a_2 - a_1 = a_3 - a_2 = \\ldots = a_n - a_{n-1})$.\n\nIt can be proven that such an array always exists under the constraints given below.\n\nAmong all possible arrays that satisfy the given conditions, we ask you to restore one which has the \\textbf{minimum possible} maximum element. In other words, you have to minimize $\\max(a_1, a_2, \\dots, a_n)$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The only fact required to solve this problem is just to notice that the answer array is just an arithmetic progression. After that, we can fix the first element $start$, fix the difference $d$, construct the array $[start, start + d, start + 2d, \\dots, start + d \\cdot (n-1)]$, check if $x$ and $y$ are in this array and, if yes, update the answer with $start + d \\cdot (n-1)$. This is $O(n^3)$ solution. There are faster solutions, though. Other author's solution is $O(n \\sqrt{y})$ but I didn't want to make this problem harder, so I allowed $O(n^3)$ solutions. It is obvious that the difference of the progression is some divisor of $y-x$. Let it be $d$. Let's add some elements starting from $y$ \"to the left\" ($y, y-d, y-2d$ and so on) and stop if we reach $n$ elements or the next element is less than $1$. If we didn't find $x$ among these elements, just skip this difference, it is useless for us. Otherwise, if we have less than $n$ elements, let's add $y+d, y+2d, y+3d$ and so on until we get $n$ elements. And then update the answer with the maximum element of the array. There is also a solution in $O(n + \\sqrt{y})$ with some greedy observations :)",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int tcs;\n    cin >> tcs;\n\n    while (tcs--) {\n        int n, x, y;\n        cin >> n >> x >> y;\n        int diff = y - x;\n        for (int delta = 1; delta <= diff; ++delta) {\n            if (diff % delta) continue;\n            if (diff / delta + 1 > n) continue;\n            int k = min((y - 1) / delta, n - 1);\n            int a0 = y - k * delta;\n            for (int i = 0; i < n; ++i) {\n                cout << (a0 + i * delta) << ' ';\n            }\n            cout << endl;\n            break;\n        }\n    }\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1409",
    "index": "D",
    "title": "Decrease the Sum of Digits",
    "statement": "You are given a positive integer $n$. In one move, you can increase $n$ by one (i.e. make $n := n + 1$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $n$ be less than or equal to $s$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, let's check if the initial $n$ fits the conditions. If it is, print $0$ and continue. Otherwise, let's solve the problem greedily. At first, let's try to set the last digit to zero. Let $dig = n \\mod 10$. We need exactly $(10 - dig) \\mod 10$ moves to do that. Let's add this number to $n$ and to the answer and check if the current $n$ fits the conditions. If it isn't, let's try to set the previous last digit to zero. Let $dig = \\left\\lfloor\\frac{n}{10}\\right\\rfloor \\mod 10$. Then we need $((10 - dig) \\mod 10) \\cdot 10$ moves to do that. Let's add this number to $n$ and to the answer and check if the current $n$ fits the conditions. If it isn't, repeat the same with the third digit and so on. This cycle can do no more than $18$ iterations. And we can fing the sum of digits of $n$ in at most $18$ iterations too (decimal logarithm of $n$). So, the total time complexity is $O(\\log_{10}^2{(n)})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint sum(long long n) {\n\tint res = 0;\n\twhile (n > 0) {\n\t\tres += n % 10;\n\t\tn /= 10;\n\t}\n\treturn res;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tlong long n;\n\t\tint s;\n\t\tcin >> n >> s;\n\t\tlong long ans = 0;\n\t\tif (sum(n) <= s) {\n\t\t\tcout << 0 << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tlong long pw = 1;\n\t\tfor (int i = 0; i < 18; ++i) {\n\t\t\tint digit = (n / pw) % 10;\n\t\t\tlong long add = pw * ((10 - digit) % 10);\n\t\t\tn += add;\n\t\t\tans += add;\n\t\t\tif (sum(n) <= s) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpw *= 10;\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1409",
    "index": "E",
    "title": "Two Platforms",
    "statement": "There are $n$ points on a plane. The $i$-th point has coordinates $(x_i, y_i)$. You have two horizontal platforms, both of length $k$. Each platform can be placed anywhere on a plane but it should be placed \\textbf{horizontally} (on the same $y$-coordinate) and have \\textbf{integer borders}. If the left border of the platform is $(x, y)$ then the right border is $(x + k, y)$ and all points between borders (including borders) belong to the platform.\n\nNote that platforms can share common points (overlap) and it is not necessary to place both platforms on the same $y$-coordinate.\n\nWhen you place both platforms on a plane, all points start falling down decreasing their $y$-coordinate. If a point collides with some platform at some moment, the point stops and is \\textbf{saved}. Points which never collide with any platform are lost.\n\nYour task is to find the maximum number of points you can \\textbf{save} if you place both platforms optimally.\n\nYou have to answer $t$ independent test cases.\n\nFor better understanding, please read the \\textbf{Note} section below to see a picture for the first test case.",
    "tutorial": "Firstly, we obviously don't need $y$-coordinates at all because we can place both platforms at $y=-\\infty$. Let's sort all $x$-coordinates in non-decreasing order. Calculate for each point $i$ two values $l_i$ and $r_i$, where $l_i$ is the number of points to the left from the point $i$ (including $i$) that are not further than $k$ from the $i$-th point (i.e. the number of such points $j$ that $|x_i - x_j| \\le k$). And $r_i$ is the number of points to the right from the point $i$ (including $i$) that are not further than $k$ from the $i$-th point. Both these parts can be done in $O(n)$ using two pointers. Then let's build suffix maximum array on $r$ and prefix maximum array on $l$. For $l$, just iterate over all $i$ from $2$ to $n$ and do $l_i := max(l_i, l_{i-1})$. For $r$, just iterate over all $i$ from $n-1$ to $1$ and do $r_i := max(r_i, r_{i + 1})$. The question is: what? What did we do? We did the following thing: the answer always can be represented as two non-intersecting segments of length $k$ such that at least one endpoint of each segment is some input point (except the case $n=1$). Now, let's fix this border between segments. Iterate over all $i$ from $1$ to $n-1$ and update the answer with $max(l_{i}, r_{i + 1})$. So we took some segment that starts at some point to the left from $i$ (including $i$) and goes to the left and took some segment that starts further than $i+1$ (including $i+1$) and goes to the right. With this model, we considered all optimal answers that can exist. Time complexity: $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<int> x(n), y(n);\n\t\tfor (auto &it : x) cin >> it;\n\t\tfor (auto &it : y) cin >> it;\n\t\tsort(x.begin(), x.end());\n\t\tint j = n - 1;\n\t\tvector<int> l(n), r(n);\n\t\tfor (int i = n - 1; i >= 0; --i) {\n\t\t\twhile (x[j] - x[i] > k) --j;\n\t\t\tr[i] = j - i + 1;\n\t\t\tif (i + 1 < n) r[i] = max(r[i], r[i + 1]);\n\t\t}\n\t\tj = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\twhile (x[i] - x[j] > k) ++j;\n\t\t\tl[i] = i - j + 1;\n\t\t\tif (i > 0) l[i] = max(l[i], l[i - 1]);\n\t\t}\n\t\tint ans = 1;\n\t\tfor (int i = 0; i < n - 1; ++i) {\n\t\t\tans = max(ans, r[i + 1] + l[i]);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1409",
    "index": "F",
    "title": "Subsequences of Length Two",
    "statement": "You are given two strings $s$ and $t$ consisting of lowercase Latin letters. The length of $t$ is $2$ (i.e. this string consists only of two characters).\n\nIn one move, you can choose \\textbf{any} character of $s$ and replace it with \\textbf{any} lowercase Latin letter. More formally, you choose some $i$ and replace $s_i$ (the character at the position $i$) with some character from 'a' to 'z'.\n\nYou want to do \\textbf{no more than} $k$ replacements in such a way that \\textbf{maximizes} the number of occurrences of $t$ in $s$ as a \\textbf{subsequence}.\n\nRecall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.",
    "tutorial": "I'm almost sure this problem can be solved faster and with greater constraints but this version is fine for the last problem. Consider both strings $0$-indexed and let's do the dynamic programming $dp_{i, j, cnt_0}$. It means the maximum number of occurrences of $t$ if we considered first $i$ characters of $s$, did $j$ moves and the number of characters $t_0$ is $cnt_0$. The answer to the problem is $\\max\\limits_{ck=0}^{k} \\max\\limits_{cnt_0=0}^{n} dp_{n, ck, cnt_0}$. Initially all states are $-\\infty$ and $dp_{0, 0, 0}$ is $0$. What about transitions? There are essentially three types of them: don't change the current character, change the current character to $t_0$ and change the current character to $t_1$. Let's create three additional variables to make our life easier (if that were true...). $e_0$ is $1$ if $s_i = t_0$ and $0$ otherwise, $e_1$ is $1$ if $s_i = t_1$ and $0$ otherwise and $e_{01}$ is $1$ if $t_0 = t_1$ and $0$ otherwise. Now let's make and describe our transitions: Don't change the $i$-th character:$dp_{i + 1, ck, cnt_0 + e_0} = max(dp_{i + 1, ck, cnt_0 + e_0}, dp_{i, ck, cnt_0} + (e_1~ ?~ cnt_0 : 0))$. The expression $x~ ?~ y : z$ is just ternary if statement: if $x$ is true, return $y$, otherwise return $z$. So, the number of characters $t_0$ increases if $s_i$ equals $t_0$ and the answer increases if the $i$-th character equals $t_1$ (because we added all occurrences that end in the $i$-th character). $dp_{i + 1, ck, cnt_0 + e_0} = max(dp_{i + 1, ck, cnt_0 + e_0}, dp_{i, ck, cnt_0} + (e_1~ ?~ cnt_0 : 0))$. The expression $x~ ?~ y : z$ is just ternary if statement: if $x$ is true, return $y$, otherwise return $z$. So, the number of characters $t_0$ increases if $s_i$ equals $t_0$ and the answer increases if the $i$-th character equals $t_1$ (because we added all occurrences that end in the $i$-th character). Change the $i$-th character to $t_0$ (possible only when $ck < k$):$dp_{i + 1, ck + 1, cnt_0 + 1} = max(dp_{i + 1, ck + 1, cnt_0 + 1}, dp_{i, ck, cnt_0} + (e_{01}~ ?~ cnt_0 : 0))$. The number of characters $t_0$ always increases and the answer increases if $t_0$ equals $t_1$ by the same reason as in the previous transition. $dp_{i + 1, ck + 1, cnt_0 + 1} = max(dp_{i + 1, ck + 1, cnt_0 + 1}, dp_{i, ck, cnt_0} + (e_{01}~ ?~ cnt_0 : 0))$. The number of characters $t_0$ always increases and the answer increases if $t_0$ equals $t_1$ by the same reason as in the previous transition. Change the $i$-th character to $t_1$ (possible only when $ck < k$):$dp_{i + 1, ck + 1, cnt_0 + e_{01}} = max(dp_{i + 1, ck + 1, cnt_0 + e_{01}}, dp_{i, ck, cnt_0} + cnt_0)$. The number of characters $t_0$ increases only if $t_0 = t_1$ and the answer always increases. $dp_{i + 1, ck + 1, cnt_0 + e_{01}} = max(dp_{i + 1, ck + 1, cnt_0 + e_{01}}, dp_{i, ck, cnt_0} + cnt_0)$. The number of characters $t_0$ increases only if $t_0 = t_1$ and the answer always increases. Note that we always increase the number of moves in the second and the third transitions even when $s_i$ equals $t_0$ or $t_1$ because this case is handled in the first transition, so we don't care. Time complexity: $O(n^3)$. There are also some greedy approaches which work in $O(n^4)$ with pretty small constant and can be optimized even further.",
    "code": "// Author: Ivan Kazmenko (gassa@mail.ru)\nmodule solution;\nimport std.algorithm;\nimport std.conv;\nimport std.range;\nimport std.stdio;\nimport std.string;\n\nvoid main ()\n{\n\tint n, k;\n\twhile (readf !(\" %s %s\") (n, k) > 0)\n\t{\n\t\treadln;\n\t\tauto s0 = readln.strip;\n\t\tauto t = readln.strip;\n\t\tauto s = s0.dup;\n\t\tint res = 0;\n\t\tforeach (b0; 0..k + 1)\n\t\t{\n\t\t\tauto e0 = k - b0;\nloop_x0:\n\t\t\tforeach (x0; 0..b0 + 1)\n\t\t\t{\nloop_y0:\n\t\t\t\tforeach (y0; 0..e0 + 1)\n\t\t\t\t{\n\t\t\t\t\tint b = b0;\n\t\t\t\t\tint e = e0;\n\t\t\t\t\tint x = x0;\n\t\t\t\t\tint y = y0;\n\t\t\t\t\ts[] = s0[];\n\t\t\t\t\tfor (int i = 0; i < n && b; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (s[i] == t[0])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (s[i] != t[1])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ts[i] = t[0];\n\t\t\t\t\t\t\tb -= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (x > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ts[i] = t[0];\n\t\t\t\t\t\t\tx -= 1;\n\t\t\t\t\t\t\tb -= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (int j = n - 1; j >= 0 && e; j--)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (s[j] == t[1])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (s[j] != t[0])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ts[j] = t[1];\n\t\t\t\t\t\t\te -= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (y > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ts[j] = t[1];\n\t\t\t\t\t\t\ty -= 1;\n\t\t\t\t\t\t\te -= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tint cur = 0;\n\t\t\t\t\tint add = 0;\n\t\t\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (s[i] == t[1])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcur += add;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (s[i] == t[0])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tadd += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tres = max (res, cur);\n\n\t\t\t\t\tif (x > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak loop_x0;\n\t\t\t\t\t}\n\t\t\t\t\tif (y > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak loop_y0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twriteln (res);\n\t}\n}",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1411",
    "index": "A",
    "title": "In-game Chat",
    "statement": "You have been assigned to develop a filter for bad messages in the in-game chat. A message is a string $S$ of length $n$, consisting of lowercase English letters and characters ')'. The message is bad if the number of characters ')' at the end of the string strictly greater than the number of remaining characters. For example, the string \")bc)))\" has three parentheses at the end, three remaining characters, and is not considered bad.",
    "tutorial": "You should count the number of parentheses at the end of the string, suppose there are $x$ such parentheses. Then if $x > \\frac{n}{2}$, message is bad. Note that you should divide $n$ by $2$ without rounding. Or you can compare $2 \\cdot x$ and $n$ instead. If $2 \\cdot x > n$, the message is bad.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1411",
    "index": "B",
    "title": "Fair Numbers",
    "statement": "We call a positive integer number fair if it is divisible by each of its nonzero digits. For example, $102$ is fair (because it is divisible by $1$ and $2$), but $282$ is not, because it isn't divisible by $8$. Given a positive integer $n$. Find the minimum integer $x$, such that $n \\leq x$ and $x$ is fair.",
    "tutorial": "Let's call a number super-fair if it is divisible by each of the numbers $1..9$. It is fair to say that super-fair numbers are also divisible by $LCM(1..9)$ which is equal to $2520$. The answer isn't larger than the nearest super-fair number, which means that you can increase the original $n$ by one until it becomes fair. We will determine if the number is fair by checking each of its digits separately.",
    "tags": [
      "brute force",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1411",
    "index": "C",
    "title": "Peaceful Rooks",
    "statement": "You are given a $n \\times n$ chessboard. Rows and columns of the board are numbered from $1$ to $n$. Cell $(x, y)$ lies on the intersection of column number $x$ and row number $y$.\n\nRook is a chess piece, that can in one turn move any number of cells vertically or horizontally. There are $m$ rooks ($m < n$) placed on the chessboard in such a way that no pair of rooks attack each other. I.e. there are no pair of rooks that share a row or a column.\n\nIn one turn you can move one of the rooks any number of cells vertically or horizontally. Additionally, it shouldn't be attacked by any other rook after movement. What is the minimum number of moves required to place all the rooks on the main diagonal?\n\nThe main diagonal of the chessboard is all the cells $(i, i)$, where $1 \\le i \\le n$.",
    "tutorial": "Consider rooks as edges in a graph. The position $(x, y)$ will correspond to an edge $(x \\to y)$. From the condition that there're at most one edge exits leading from each vertex and at most one edge leading to each vertex, it follows that the graph decomposes into cycles, paths, and loops (edges of type $v \\to v$). What happens to the graph when we move the rook? The edge changes exactly one of its endpoints. By such operations, we must turn all edges into loops, and the constraint on the number of edges going in and out of a vertex must be satisfied. A path is quite easy to turn into loops, just start from one end. A cycle must first be turned into a path, which is always possible. We've only spent one extra move, it's not hard to see that this is optimal. The answer is the number of rooks minus the number of loops plus the number of cycles.",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1411",
    "index": "D",
    "title": "Grime Zoo",
    "statement": "Currently, XXOC's rap is a string consisting of zeroes, ones, and question marks. Unfortunately, haters gonna hate. They will write $x$ angry comments for every occurrence of \\textbf{subsequence} 01 and $y$ angry comments for every occurrence of \\textbf{subsequence} 10. You should replace all the question marks with 0 or 1 in such a way that the number of angry comments would be as small as possible.\n\nString $b$ is a subsequence of string $a$, if it can be obtained by removing some characters from $a$. Two occurrences of a subsequence are considered distinct if sets of positions of remaining characters are distinct.",
    "tutorial": "Consider two adjacent question marks at positions $l$ and $r$ ($l < r$). Let $c_0$ zeros and $c_1$ ones be on the interval $(l, r)$. In case $s_l = 0$, $s_r = 1$ there will be written $(c_1 + 1) \\cdot x + c_0 \\cdot x + out = (c_0 + c_1 + 1) \\cdot x + out = (r - l) \\cdot x + out$ comments, where $out$ is the number of comments for subsequences, at least one element of which is outside $[l, r]$. In the case $s_l = 1$, $s_r = 0$ we get $(c_0 + 1) \\cdot y + c_1 \\cdot y + out = (c_0 + c_1 + 1) \\cdot y + out = (r - l) \\cdot y + out$ comments. Subtract the second from the first, we get $(r - l) \\cdot (x - y)$. This means the following: if $x \\geq y$, it is always better to change $01$ to $10$. That is, there is such an optimal substitution of $?$ by $0$ and $1$ that some prefix of $?$ are replaced by $1$, and the remaining by $0$. In the case of $x < y$, similarly, there will be some prefix of $0$, then suffix of $1$. For $\\mathcal{O}(n)$ implementation you can count how many ones and zeros on each prefix and iterate over the separation boundary.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1411",
    "index": "E",
    "title": "Poman Numbers",
    "statement": "You've got a string $S$ consisting of $n$ lowercase English letters from your friend. It turned out that this is a number written in poman numerals. The poman numeral system is long forgotten. All that's left is the algorithm to transform number from poman numerals to the numeral system familiar to us. Characters of $S$ are numbered from $1$ to $n$ from left to right. Let's denote the value of $S$ as $f(S)$, it is defined as follows:\n\n- If $|S| > 1$, an arbitrary integer $m$ ($1 \\le m < |S|$) is chosen, and it is defined that $f(S) = -f(S[1, m]) + f(S[m + 1, |S|])$, where $S[l, r]$ denotes the substring of $S$ from the $l$-th to the $r$-th position, inclusively.\n- Otherwise $S = c$, where $c$ is some English letter. Then $f(S) = 2^{pos(c)}$, where $pos(c)$ is the position of letter $c$ in the alphabet ($pos($a$) = 0$, $pos($z$) = 25$).\n\nNote that $m$ is chosen independently on each step.\n\nYour friend thinks it is possible to get $f(S) = T$ by choosing the right $m$ on every step. Is he right?",
    "tutorial": "First, note that the last digit will always be taken with a plus sign, and the one before the last - with a minus sign. It turns out that all other digits may be taken with any sign. Let's prove it. Suppose we want to get the mask $---++--++---+$. All minuses on the left can be obtained by simply splitting one character at a time. We are left with the $++--++---+$ mask, split it as follows: $(++--++-)(--+)$. That is, we left in the left part only one minus from the last segment of consecutive minuses. Change the signs in the left part: $(--++--+)(--+)$. We reduced it to a smaller problem. Doing this, we will end up with masks of the form $+$. Now the problem is reduced to whether we can get the number $X$ using the first $n - 2$ letters. Since the weights of the items are powers of two, we can choose them greedily. Bonus. Can you construct an answer in linear time (i.e. output a binary tree)?",
    "tags": [
      "bitmasks",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1411",
    "index": "F",
    "title": "The Thorny Path",
    "statement": "According to a legend the Hanoi Temple holds a permutation of integers from $1$ to $n$. There are $n$ stones of distinct colors lying in one line in front of the temple. Monks can perform the following operation on stones: choose a position $i$ ($1 \\le i \\le n$) and cyclically shift stones at positions $i$, $p[i]$, $p[p[i]]$, .... That is, a stone from position $i$ will move to position $p[i]$, a stone from position $p[i]$ will move to position $p[p[i]]$, and so on, a stone from position $j$, such that $p[j] = i$, will move to position $i$.\n\nEach day the monks must obtain a new arrangement of stones using an arbitrary number of these operations. When all possible arrangements will have been obtained, the world will end. You are wondering, what if some elements of the permutation could be swapped just before the beginning? How many days would the world last?\n\nYou want to get a permutation that will allow the world to last as long as possible, using the minimum number of exchanges of two elements of the permutation.\n\nTwo arrangements of stones are considered different if there exists a position $i$ such that the colors of the stones on that position are different in these arrangements.",
    "tutorial": "The problem boils down to getting an array consisting of threes and a remainder (2 or 2+2 or 4) using split and merge operations. It helps to think that all merge operations are done before split operations. To solve the problem, you can brute which elements of the array the remainder is subtracted from, then the rest of the operations are done greedily. Bonus. Given $k$. We need to get an array consisting of $k$ using these operations. Assume that the sum of the array elements is divisible by $k$. This can be represented as minimum cover of the hypergraph by edges with weights = (number of vertices - 1) + (sum of elements / $k$ - 1). Is there a polynomial solution ($k$ is a parameter)?",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1411",
    "index": "G",
    "title": "No Game No Life",
    "statement": "Let's consider the following game of Alice and Bob on a directed acyclic graph. Each vertex may contain an arbitrary number of chips. Alice and Bob make turns alternating. Alice goes first. In one turn player can move exactly one chip along any edge outgoing from the vertex that contains this chip to the end of this edge. The one who cannot make a turn loses. Both players play optimally.\n\nConsider the following process that takes place every second on a given graph with $n$ vertices:\n\n- An integer $v$ is chosen equiprobably from $[1, n + 1]$.\n- If $v \\leq n$, we add a chip to the $v$-th vertex and go back to step 1.\n- If $v = n + 1$, Alice and Bob play the game with the current arrangement of chips and the winner is determined. After that, the process is terminated.\n\nFind the probability that Alice will win the game. It can be shown that the answer can be represented as $\\frac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q \\not\\equiv 0 \\pmod{998\\,244\\,353}$. Print the value of $P \\cdot Q^{-1} \\bmod 998\\,244\\,353$.",
    "tutorial": "The winner of the game is determined by xor of Grundy values for all chips' vertices. Notice that every Grundy value $\\leq\\sqrt m$ so xor doesn't exceed 512. Let $P_v$ be a probability of Alice's victory if the current xor is $v$. $P_v = \\sum P_{to}\\cdot prob(v \\rightarrow to) + [v\\neq 0] \\cdot\\frac{1}{n + 1}$ In the second term, we got $n + 1$ and the process ended. It is clear that $prob(v \\rightarrow to) = \\frac{cnt[v \\oplus to]}{n + 1}$, where $cnt[x]$ is the number of vertices with the Grundy value equal to $x$. Now we have a system of 512 linear equations with variables $P_v$. We can solve it using the Gauss method. The answer is in $P_0$. The proof that Gauss won't break along the way is left to the reader as an exercise. There is also a solution using the Hadamard transform.",
    "tags": [
      "bitmasks",
      "games",
      "math",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1413",
    "index": "A",
    "title": "Finding Sasuke",
    "statement": "Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are $T$ rooms there. Every room has a door into it, each door can be described by the number $n$ of seals on it and their integer energies $a_1$, $a_2$, ..., $a_n$. All energies $a_i$ are \\textbf{nonzero} and do not exceed $100$ by absolute value. Also, \\textbf{$n$ is even}.\n\nIn order to open a door, Naruto must find such $n$ seals with integer energies $b_1$, $b_2$, ..., $b_n$ that the following equality holds: $a_{1} \\cdot b_{1} + a_{2} \\cdot b_{2} + ... + a_{n} \\cdot b_{n} = 0$. All $b_i$ must \\textbf{be nonzero} as well as $a_i$ are, and also \\textbf{must not exceed $100$} by absolute value. Please find required seals for every room there.",
    "tutorial": "The following is always a valid answer: $-a_2, a_1, -a_4, a_3, ..., -a_n, a_{n-1}$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1413",
    "index": "B",
    "title": "A New Technique",
    "statement": "All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $n\\cdot m$ different seals, denoted by distinct numbers. All of them were written in an $n\\times m$ table.\n\nThe table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.",
    "tutorial": "To solve this problem it's sufficient to find the position of each row in the table. If we consider the first number of each row and find a column containing it, we will automatically obtain the position of the row. Since all numbers are distinct, the positions will be determined uniquely.",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1413",
    "index": "C",
    "title": "Perform Easily",
    "statement": "After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has $6$ strings and an infinite number of frets numbered from $1$. Fretting the fret number $j$ on the $i$-th string produces the note $a_{i} + j$.\n\nTayuya wants to play a melody of $n$ notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference.\n\nFor example, if $a = [1, 1, 2, 2, 3, 3]$, and the sequence of notes is $4, 11, 11, 12, 12, 13, 13$ (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be $10$, the minimal one will be $3$, and the answer is $10 - 3 = 7$, as shown on the picture.",
    "tutorial": "Consider all possible frets we may need to use. To do this we sort all the pairs $(b_j - a_i, j)$ lexicographically. Now we need to find a subsegment with the minimal range containing the first fields and also so that all numbers from $1$ to $n$ occur among the second fields (so it will mean that for each note there is at least one string-fret combination). For each $l$, denote the minimal $right(l)$ so that $[l, right(l)]$ is a valid subsegment. It's easy to see that $right(l) \\leq right(l + 1)$, because if $[l + 1, right(l + 1)]$ contains all numbers from $1$ to $n$ among the second fields, then so does $[l, right(l + 1)]$. So to find all $right(l)$ one can just use two pointers, maintaining the set of notes that occur on the segment. Once we calculated it, we just print the minimal difference between the first fields of the endpoints of all possible segments $[l, right(l)]$. The final complexity is $O(nm\\log(nm))$.",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1413",
    "index": "D",
    "title": "Shurikens",
    "statement": "Tenten runs a weapon shop for ninjas. Today she is willing to sell $n$ shurikens which cost $1$, $2$, ..., $n$ ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the \\textbf{cheapest} shuriken from the showcase.\n\nTenten keeps a record for all events, and she ends up with a list of the following types of records:\n\n- + means that she placed another shuriken on the showcase;\n- - x means that the shuriken of price $x$ was bought.\n\nToday was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!",
    "tutorial": "Let's note that if a shuriken of price $x$ is being bought right now, then the only information we obtain about all the remaining shurikens is that they are of prices $\\geq x$. It's also clear that if we consider two shurikens on the showcase then the one which was placed earlier has the stronger constraints (as written above). Now consider all events that can happen when the shuriken of price $x$ is bought. If for all shurikens that are currently on the showcase we know that they must have prices $> x$, then the answer is negative. Otherwise, for all shurikens that had a lower bound of something less than $x$ we increase it to $x$, and remove any one of them, because we cannot remove any other shuriken, and these are indistinguishable. However, since we know that the last placed shuriken has the weakest constraint, we can just remove the last placed shuriken each time and check the consistency in the end. This verification can be done using any min-heap. The final time complexity is $O(n \\cdot \\log{n})$.",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1413",
    "index": "E",
    "title": "Solo mid Oracle",
    "statement": "Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal $a$ instant damage to him, and then heal that enemy $b$ health points at the end of every second, for exactly $c$ seconds, starting one second after the ability is used. That means that if the ability is used at time $t$, the enemy's health decreases by $a$ at time $t$, and then increases by $b$ at time points $t + 1$, $t + 2$, ..., $t + c$ due to this ability.\n\nThe ability has a cooldown of $d$ seconds, i. e. if Meka-Naruto uses it at time moment $t$, next time he can use it is the time $t + d$. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.\n\nThe effects from different uses of the ability may stack with each other; that is, the enemy which is currently under $k$ spells gets $k\\cdot b$ amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.\n\nNow Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every $d$ seconds). The enemy is killed if their health points become $0$ or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?",
    "tutorial": "It will be easier to explain using illustrations. We will use timelines, where each cast spell instance will occupy a separate row; and each second will be represented as a column. First of all, if $a > b\\cdot c$ then the answer is $-1$. Indeed, after time $t$ the total amount of damage dealt is $(a - bc)$ for each spell which has expired completely plus some damage from spells which have not expired. The first summand can be as great as we want it to, and the second one is bounded by, say, $-bc^2$ as there are at most $c$ spells which have not yet expired, and each of them healed the enemy by at most $b$ units each second, for at most $c$ seconds. Therefore, the damage may be arbitrarily huge. On the other hand, if $a\\leq bc$, then the answer always exists, and here is why. First of all, let's only look at the moments divisible by $d$ - that is, the moments when damage was dealt. It is obvious that for every other moment $t$ the enemy had less (or the same amount of) health at time $t-1$. Second, if $t\\geq c$, then the enemy had no more health than now at the moment $t-d$. Indeed, the difference between damages then and now is exactly one full-lasted spell, which is non-negative, as we know. For clarity take a look at the pictures below: So now we know that we may consider only $t < c$, and it follows in particular that the answer exists. Also, when in general should we subtract $d$ from $t$ to obtain a more damaged enemy? One can see that if $t < c$ then the damage we subtract is $a - tb$, and since $t = dk$ for some integer nonnegative $k$, then we subtract $a - bdk$ damage. It makes sense to do this while $a - bdk < 0$: In other words, we have reduced the task to the following: find the greatest $k$ so that $a \\geq bdk$, and cast the spell $(k+1)$ time. The enemy will have the least amount of health just after we cast the spell for the $(k+1)$-st time. The answer is thus $a(k+1) - \\dfrac{k(k+1)}{2}bd$. The time complexity of this solution is $O(1)$ per test. One could also find out that the enemy's health is convex over time and use ternary search to find the minimum. It requires $O(\\log{maxanswer})$ per test, which is still ok.",
    "tags": [
      "greedy",
      "math",
      "ternary search"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1413",
    "index": "F",
    "title": "Roads and Ramen",
    "statement": "In the Land of Fire there are $n$ villages and $n-1$ bidirectional road, and there is a path between any pair of villages by roads. There are only two types of roads: stone ones and sand ones. Since the Land of Fire is constantly renovating, every morning workers choose a single road and flip its type (so it becomes a stone road if it was a sand road and vice versa). Also everyone here loves ramen, that's why every morning a ramen pavilion is set in the middle of every \\textbf{stone} road, and at the end of each day all the pavilions are removed.\n\nFor each of the following $m$ days, after another road is flipped, Naruto and Jiraiya choose a simple path — that is, a route which starts in a village and ends in a (possibly, the same) village, and doesn't contain any road twice. Since Naruto and Jiraiya also love ramen very much, they buy a single cup of ramen on each stone road and one of them eats it. Since they don't want to offend each other, they only choose routes where they can eat equal number of ramen cups. Since they both like traveling, they choose any longest possible path. After every renovation find the maximal possible length of a path (that is, the number of roads in it) they can follow.",
    "tutorial": "Fix any diameter of the tree. One of the optimal paths always starts at one of the diameter's endpoints. Proof: Let $AB$ be a diameter of the tree, and the optimal answer be $EF$. Then the parity of the number of stone roads on $DE$ is the same as on $DF$, and also the same holds for $CE$ and $CF$. Since a diameter has the greatest length among all paths in the tree, the stone roads parity is different on $AC$ and on $BC$ (otherwise, the diameter would be an answer). Hence, the stone roads parity on $CE$ coincides with one of $AC$ and $BC$. Assume without loss of generality that the stone roads parities of $AC$ and $CE$ are the same. Then the path $AE$ contains an even number of stone roads. Note that since $AB$ is a diameter, $AC$ is no shorter than $CF$, hence $AD$ is no shorter than $DF$, which implies that $AE$ is not shorter than $EF$. This means that there is an optimal path starting at one of the diameter's endpoints. Now remaining is to solve the problem if one of the endpoints is fixed. If we root the tree from it, and write down for each vertex the stone roads parity between it and the root, then each query is basically changing the parity of a subtree. In an euler-tour traversal every such subtree is represented by a contiguous subsegment. Now the original problem can be reformulated in a following way: we have a binary array, there are queries of type \"flip a subsegment\", and after each query we need to find a zero with the greatest depth parameter. This can be done via a segment tree, where in each node we store the deepest zero and the deepest one on the subsegment corresponding to that node. The final time complexity is $O(n\\log{n})$.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1415",
    "index": "A",
    "title": "Prison Break",
    "statement": "There is a prison that can be represented as a rectangular matrix with $n$ rows and $m$ columns. Therefore, there are $n \\cdot m$ prison cells. There are also $n \\cdot m$ prisoners, one in each prison cell. Let's denote the cell in the $i$-th row and the $j$-th column as $(i, j)$.\n\nThere's a secret tunnel in the cell $(r, c)$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.\n\nBefore the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $(i, j)$ can move to cells $( i - 1 , j )$ , $( i + 1 , j )$ , $( i , j - 1 )$ , or $( i , j + 1 )$, as long as the target cell is inside the prison. They can also choose to stay in cell $(i, j)$.\n\nThe prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $( r , c )$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.",
    "tutorial": "The problem is equivalent to finding the farthest cell from $( x , y )$. It is easy to see that, if they move optimally, $( i , j )$ can reach $( x , y )$ just by moving in an L shape, and this is equivalent to the Manhattan distance between the two points. The longest distance a prisoner will move on rows is $max( x - 1 , n - x )$, and for the columns it is $( y - 1 , m - y )$. So answer is just $max( x - 1 , n - x ) + max( y - 1 , m - y )$",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1415",
    "index": "B",
    "title": "Repainting Street",
    "statement": "There is a street with $n$ houses in a line, numbered from $1$ to $n$. The house $i$ is initially painted in color $c_i$. The street is considered beautiful if all houses are painted in the same color. Tom, the painter, is in charge of making the street beautiful. Tom's painting capacity is defined by an integer, let's call it $k$.\n\nOn one day, Tom can do the following repainting process that consists of two steps:\n\n- He chooses two integers $l$ and $r$ such that $ 1 \\le l \\le r \\le n $ and $ r - l + 1 = k $.\n- For each house $i$ such that $l \\le i \\le r$, he can either repaint it with any color he wants, or ignore it and let it keep its current color.\n\nNote that in the same day Tom can use different colors to repaint different houses.\n\nTom wants to know the minimum number of days needed to repaint the street so that it becomes beautiful.",
    "tutorial": "If we want to paint every house on the street with color $x$, it is easy to see that we need to change every house with color different from $x$, and not necessarily repaint houses already painted in color $x$. We can do the following greedy algorithm to minimize the number of days: Find leftmost house not painted in color $x$. Assume this is in position $i$. Then we will paint $[i,i+k-1]$ with color $x$. Repeat this until all houses are painted in color $x$. Why is this optimal? When we find the leftmost house not painted in $x$, we know we need to change it, and as it is the leftmost one, everything before it is painted in $x$. To maximize our chances of changing other houses that need repainting, we choose this as the leftmost position in our painting range. This can be implemented easily with a linear pass. However, we don't know the color $x$ that we will have at the end. Limit of colors are small enough, so we can try all of them and just keep the smallest answer. Time complexity: $O(n \\cdot max(c))$ Space complexity: $O(n)$",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1415",
    "index": "C",
    "title": "Bouncing Ball",
    "statement": "You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $1$, and in each cell you can either put a platform or leave it empty.\n\nIn order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $p$, then bounces off it, then bounces off a platform in the cell $(p + k)$, then a platform in the cell $(p + 2k)$, and so on every $k$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $p$ and $k$.\n\nYou already have some level pattern $a_1$, $a_2$, $a_3$, ..., $a_n$, where $a_i = 0$ means there is no platform in the cell $i$, and $a_i = 1$ means there is one. You want to modify it so that the level can be passed with given $p$ and $k$. In $x$ seconds you can add a platform in some empty cell. In $y$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You \\textbf{can not} reduce the number of cells to less than $p$.\n\n\\begin{center}\n{\\small Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added.}\n\\end{center}\n\nWhat is the minimum number of seconds you need to make this level passable with given $p$ and $k$?",
    "tutorial": "Note that instead of deletion of the first cell we can increase the value of $p$ by one, these operations are equivalent. Now let's loop through the possible final values of $p$, let it be $q$ ($p \\le q \\le n$). Then we need to add missing platforms in cells $q$, $(q + k)$, $(q + 2k)$, and so on. Let's compute the array $c_i$ - the number of cells without a platform among cells $i$, $(i + k)$, $(i + 2k)$, an so on. It can be computed using the method of dynamic programming, going from large $i$ to small: $c_i = c_{i + k} + (1 - a_i)$. Now the time required to add the platforms for a given value of $q$ is $c_q \\cdot x$, while the time needed to increase $p$ to $q$ is $(q - p) \\cdot y$. The total time equals $c_q \\cdot x + (q - p) \\cdot y$. We only have to choose minimum among all possible values of $q$.",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1415",
    "index": "D",
    "title": "XOR-gun",
    "statement": "Arkady owns a \\textbf{non-decreasing} array $a_1, a_2, \\ldots, a_n$. You are jealous of its beauty and want to destroy this property. You have a so-called XOR-gun that you can use one or more times.\n\nIn one step you can select two \\textbf{consecutive} elements of the array, let's say $x$ and $y$, remove them from the array and insert the integer $x \\oplus y$ on their place, where $\\oplus$ denotes the bitwise XOR operation. Note that the length of the array decreases by one after the operation. You can't perform this operation when the length of the array reaches one.\n\nFor example, if the array is $[2, 5, 6, 8]$, you can select $5$ and $6$ and replace them with $5 \\oplus 6 = 3$. The array becomes $[2, 3, 8]$.\n\nYou want the array no longer be non-decreasing. What is the minimum number of steps needed? If the array stays non-decreasing no matter what you do, print $-1$.",
    "tutorial": "First let's compute array $b_1, b_2, \\ldots, b_n$, where $b_i$ is the index of the highest bit equal to $1$ in the binary notation of $a_i$. The statement says $b_i \\le b_{i + 1}$. These values can be computed by dividing the given numbers by $2$ until they are zero. Note that if for a given $i$ the equality $b_{i - 1} = b_i = b_{i + 1} = t$ holds, then we can apply an operation to $a_i$ and $a_{i + 1}$, and the resulting integer is smaller than $a_{i - 1}$. Indeed, in $a_{i - 1}$ the highest bit set is $t$, but in $a_i \\oplus a_{i + 1}$ the $t$-th and higher bits are zeros. That means if there is such an $i$ (it is easy to check in a single linear pass), then the answer is $1$. Now note that if there is no such $i$, then the size of the array $n$ is not bigger than $2 \\cdot \\left(\\lfloor\\log_2{10^9}\\rfloor + 1\\right) = 60$! Indeed, there are no more than two integers with the same highest bit set. It is much easier to solve the problem in such constraints. Consider some solution. In the final array, let's denote it as $c$, there is $i$ such that $c_i > c_{i + 1}$. Note that each element of the final array is equal to XOR of some subsegment of the initial array, and each element of the initial array belongs to exactly one such subsegment. Let this subsegment for $c_i$ be $a_l, a_{l + 1}, \\ldots, a_m$, and for $c_{i + 1}$ be $a_{m + 1}, a_{m + 2}, \\ldots, a_r$. Then it's clear that to find an optimal solution it is enough to loop through all possible values of $l$, $m$, and $r$ and check whether XOR of all elements of the left subsegment is larger than XOR of all elements of the right subsegment. If this inequality holds, update answer with value $r - l - 1$. The complexity of this part is $O(n^3)$ or $O(n^4)$ depending on implementation.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1415",
    "index": "E",
    "title": "New Game Plus!",
    "statement": "Wabbit is playing a game with $n$ bosses numbered from $1$ to $n$. The bosses can be fought in any order. Each boss needs to be defeated \\textbf{exactly once}. There is a parameter called \\textbf{boss bonus} which is initially $0$.\n\nWhen the $i$-th boss is defeated, the current \\textbf{boss bonus} is added to Wabbit's score, and then the value of the \\textbf{boss bonus} increases by the point increment $c_i$. Note that $c_i$ can be negative, which means that other bosses now give fewer points.\n\nHowever, Wabbit has found a glitch in the game. At any point in time, he can reset the playthrough and start a New Game Plus playthrough. This will set the current \\textbf{boss bonus} to $0$, while all defeated bosses remain defeated. The current score is also saved and does \\textbf{not} reset to zero after this operation. This glitch can be used \\textbf{at most} $k$ times. He can reset after defeating any number of bosses (including before or after defeating all of them), and he also can reset the game several times in a row without defeating any boss.\n\nHelp Wabbit determine the maximum score he can obtain if he has to defeat \\textbf{all} $n$ bosses.",
    "tutorial": "We see that each playthrough (whether it is the first one or any of the playthroughs after the reset) is completely independent of any other playthrough. Thus, we should instead think of the problem as partitioning the $n$ bosses into $k+1$ playthroughs. Consider a playthrough with $x$ bosses which have point increments $a_1,a_2,\\cdots,a_{x}$ when fought in order. Then, the number of points that we will get is $(x-1)a_1 + (x-2)a_2 + \\ldots + (1)a_{x-1} + (0)a_{x}$. A simple greedy argument tell us that within a single playthrough, we should always fight the bosses in non-increasing order of point increments, i.e. $a_1 \\geq a_2 \\geq \\ldots \\geq a_{x}$. We can visualize this with $k+1$ stacks, each representing a playthrough. Each stack contains all of the bosses that will be fought in that playthrough, and the stack is non-increasing from top to bottom, meaning we fight the bosses from top to bottom. We now see that $k=0$ is a fairly trivial case; just fight the bosses in non-increasing order of point increments. For the rest of the tutorial, we will assume $k \\geq 1$. For simplicity, we say that a boss is in position $p$ of a playthrough if there are $p$ more bosses below this one on its playthrough stack. Notice that if we have two bosses in two different playthroughs with point increments $a$ and $b$ with positions $i$ and $j$ in their respective playthroughs, then the total points gained from the two bosses is $ia + jb$. We now see that if $a \\geq b$, then $i \\geq j$ and vice versa. For example, the configuration below is not optimal because swapping the $-5$ and $-3$ gives a better answer. Therefore, all bosses in lower-numbered positions should have point increments that are less than any boss in a higher-numbered position. This means that we can place the bosses on the stacks one at a time in non-decreasing order of point increments to reach an optimal configuration. Call a boss good if it has a non-negative point increment, and bad otherwise. Let's fix the arrangement of bad bosses and try to place the good bosses in non-decreasing order of point increments. We can see that placing a boss with point increment $a$ on a stack with height $h$ will add $ah$ to the total, so we should always pick the stack with maximum height. Thus, all of the good bosses will always end up on the same stack, and that stack will be the stack of maximum height. Call this stack the main stack; the other $k$ stacks are the side stacks. If there exists two side stacks whose heights differ by at least $2$, then we can always move the top-most bad boss of the taller side stack to the shorter side stack and decrease the loss in points. In the example below, the $-10$ on the left stack (of height $5$) can be moved down to the top of the right stack (of height $3$). Thus, the maximum and minimum heights of these $k$ side stacks cannot differ by more than 1. Let the minimum height of these $k$ stacks be $h$. If we consider the bottom $h$ bosses of all $k+1$ stacks, we see that they still must have the property that all bosses in lower positions have point increments that are less than any boss in higher positions. Thus, they must consist of the $h(k+1)$ bosses with smallest point increments. Direct Greedy We first sort the bosses in non-decreasing order of point increments. For each possible prefix $P$ that contains only negative point increments, we take all bosses in $P$ and distribute them evenly across the $k+1$ stacks. We then take the remaining bosses and place them on the tallest of the stacks (if there are multiple stacks of the same height, the result is the same). Performing this computation naively takes $O(n^2)$ time, but this can be sped up using precomputation of weighted prefix and suffix sums to evaluate all configurations in $O(n)$. The final time complexity is $O(n \\log n)$ due to sorting. Smarter Greedy Let's take all $n$ point increments and place them in a \"sliding\" stack such that they are arranged in non-decreasing order from bottom to top. We will slide the stack across the $k+1$ playthroughs and leave the bottom point increment behind. Shown below is an example with $n=8$ and $k=2$. Every time we slide the stack, we reduce the total by the sum of all of the point increments that we slide down by $1$ position. Thus, we should only slide it down if the sum of those is less than $0$ as that will give us a more optimal solution. We notice that the point increments that we slide down always form a suffix of the point increments when sorted in non-decreasing order. The moment we stop sliding is when the sum of the suffix is non-negative, giving the optimal solution. Thus, we can find the optimal configuration directly by finding the right suffix and distributing the remaining negative point increments evenly. Genius Greedy (found by K0u1e) Sort the point increments in non-increasing order $a_1,a_2,\\ldots,a_n$. Maintain a priority queue that initially contains $k+1$ zeros. We now process the point increments in non-increasing order. To process the current point increment $a_i$, we perform the following steps in order: Find the largest number $x$ in the priority queue and remove it from the priority queue Add $x$ to our running total Push $x+a_i$ back into the priority queue The answer is the final total at the end. It will be left as an exercise to the reader to figure out why this solution is indeed equivalent to the previous solution.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1415",
    "index": "F",
    "title": "Cakes for Clones",
    "statement": "You live on a number line. You are initially (at time moment $t = 0$) located at point $x = 0$. There are $n$ events of the following type: at time $t_i$ a small cake appears at coordinate $x_i$. To collect this cake, you have to be at this coordinate at this point, otherwise the cake spoils immediately. No two cakes appear at the same time and no two cakes appear at the same coordinate.\n\nYou can move with the speed of $1$ length unit per one time unit. Also, at any moment you can create a clone of yourself at the same point where you are located. The clone can't move, but it will collect the cakes appearing at this position for you. The clone \\textbf{disappears} when you create another clone. If the new clone is created at time moment $t$, the old clone can collect the cakes that appear before or at the time moment $t$, and the new clone can collect the cakes that appear at or after time moment $t$.\n\nCan you collect all the cakes (by yourself or with the help of clones)?",
    "tutorial": "Let $mintime_i$ be the minimum time we can get to coordinate $x_i$ given that all previous cakes are collected and the latest created clone is already useless. Also let $dp_{i, j}$ be a boolean being true if we can reach a situation where we just collected the $i$-th cake, and our clone is currently waiting for the cake $j$ in correct position. Let us currently be in the position of the $i$-th event and the latest clone is useless (state $mintime_i$). Then it is always optimal to collect the $i$-th cake with a new clone while we move somewhere. There are two possible options for further actions: We directly go to the next event. Then we just need to update $mintime_{i + 1}$, and not forget to wait for the clone to collect the $i$-th cake. We want to leave clone somewhere waiting for some $j$-th cake and go take the $(i + 1)$-th cake ourselves. Then if we have enough time to do that, make $dp_{i+1, j}$ reachable. Let us be in the state $dp_{i, j}$ (we have just collected the $i$-th cake, and our clone is waiting for the $j$-th cake). If $i + 1 \\neq j$, then we should just go and collect the $i + 1$-th cake, otherwise there are two possibilities: The $j+1$-th cake is collected by a new clone, then we have to updated $mintime_{j+1}$. We want to leave a new clone waiting for some later cake $k$ (after the old one collects cake $j$), and take the $j+1$-th cake ourselves, then the transition leads to the state $dp_{j+1, k}$. We can collect all cakes if $mintime_n \\leq t_n$, or $dp_{n - 1, n}$ is reachable. The total complexity is $O(n^2)$, because we only loop through the position of the next clone in $O(n)$ states.",
    "tags": [
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1416",
    "index": "A",
    "title": "k-Amazing Numbers",
    "statement": "You are given an array $a$ consisting of $n$ integers numbered from $1$ to $n$.\n\nLet's define the $k$-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length $k$ (recall that a subsegment of $a$ of length $k$ is a contiguous part of $a$ containing exactly $k$ elements). If there is no integer occuring in all subsegments of length $k$ for some value of $k$, then the $k$-amazing number is $-1$.\n\nFor each $k$ from $1$ to $n$ calculate the $k$-amazing number of the array $a$.",
    "tutorial": "Let's fix some arbitrary number $x$ and calculate the minimum value of $k$ such that $x$ occurs in all segments of length $k$. Let $p_1 < p_2 < \\dots < p_m$ be the indices of entries of $x$ in the array. Then, for each $1 \\le i < m$ it is clear that $k$ should be at least the value of $p_{i+1}-p_i$. Also, $k \\ge p_1$ and $k \\ge n - p_m + 1$. It is enough to just take the maximum of those values. Let's call this derived value of $k$ as $f(x)$. Now, we can just go in increasing order of $x$ from $1$ to $n$ and try update the suffix $[f(x), n]$ with $x$. This can be done straightforwardly, just iterating over the range $[f(x), n]$. If we arrive at a cell for which the value of $x$ is already calculated, we immediately terminate our loop and continue our algorithm from $x+1$. Time complexity: $O(n)$. Space complexity: $O(n)$.",
    "code": "// chrono::system_clock::now().time_since_epoch().count()\n#include<bits/stdc++.h>\n\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define debug(x) cerr << #x << \" = \" << x << endl;\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\n\nconst int MAXN = (int)3e5 + 5;\n\nint f[MAXN], last[MAXN], arr[MAXN], ans[MAXN];\nint n;\n\nvoid solve() {\n  scanf(\"%d\", &n);\n  \n  for (int i = 1; i <= n; ++i) {\n    f[i] = last[i] = 0;\n    ans[i] = -1;\n  }\n  \n  for (int i = 1; i <= n; ++i) {\n    scanf(\"%d\", &arr[i]);\n  }\n  \n  for (int i = 1; i <= n; ++i) {\n    int x = arr[i];\n    f[x] = max(f[x], i - last[x]);\n    last[x] = i;\n  }\n  \n  for (int x = 1; x <= n; ++x) {\n    f[x] = max(f[x], n - last[x] + 1);\n    \n    for (int i = f[x]; i <= n && ans[i] == -1; ++i) {\n      ans[i] = x;\n    }\n  }\n  \n  for (int i = 1; i <= n; ++i) {\n    printf(\"%d%c\", ans[i], \" \\n\"[i == n]);\n  }\n}\n\nint main() {\n  int tt;\n  scanf(\"%d\", &tt);\n  \n  while (tt--) {\n    solve();\n  }\n\n  return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1416",
    "index": "B",
    "title": "Make Them Equal",
    "statement": "You are given an array $a$ consisting of $n$ \\textbf{positive} integers, numbered from $1$ to $n$. You can perform the following operation no more than $3n$ times:\n\n- choose three integers $i$, $j$ and $x$ ($1 \\le i, j \\le n$; $0 \\le x \\le 10^9$);\n- assign $a_i := a_i - x \\cdot i$, $a_j := a_j + x \\cdot i$.\n\nAfter each operation, all elements of the array should be \\textbf{non-negative}.\n\nCan you find a sequence of no more than $3n$ operations after which all elements of the array are equal?",
    "tutorial": "Let $S$ be the sum of the array. If $S$ is not divisible by $n$, then the answer is obviously $-1$. Otherwise, there always exists a solution which uses no more than $3n$ queries. We will solve this problem in two phases. First phase: gather the sum in $a_1$. Let's iterate over $2 \\le i \\le n$ in increasing order. If $a_i$ is divisible by $i$, we can immediately transfer it using one operation. Otherwise, we have to make it divisible by transferring $i - (a_i \\bmod i)$ from $a_1$ to $a_i$. Note that this operation does not break a condition on non-negativity because all $a_i$ are initially positive. This way, we successfully finish this phase using at most $2(n-1)$ operations. Second phase: distribute the sum across all elements. Just iterate over all $2 \\le i \\le n$ and make a transfer of $S/n$ from $a_1$ to $a_i$. This phase takes exactly $n-1$ operations. Time complexity: $O(n)$ Space complexity: $O(n)$",
    "code": "// chrono::system_clock::now().time_since_epoch().count()\n#include<bits/stdc++.h>\n\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define debug(x) cerr << #x << \" = \" << x << endl;\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\n\nconst int MAXN = (int)1e4 + 5;\n\nvector<array<int, 3>> ans;\nint arr[MAXN];\nint n;\n\nvoid go(int x, int y, int z) {\n  arr[x] -= x * z;\n  arr[y] += x * z;\n  ans.pb({x, y, z});\n}\n\nvoid solve() {\n  scanf(\"%d\", &n);\n  \n  for (int i = 1; i <= n; ++i) {\n    scanf(\"%d\", &arr[i]);\n  }\n  \n  ans.clear();\n  int sum = accumulate(arr + 1, arr + n + 1, 0);\n  \n  if (sum % n) {\n    printf(\"-1\\n\");\n    return;\n  }\n  \n  for (int i = 2; i <= n; ++i) {\n    if (arr[i] % i) {\n      go(1, i, i - arr[i] % i);\n    }\n    \n    go(i, 1, arr[i] / i);\n  }\n  \n  for (int i = 2; i <= n; ++i) {\n    go(1, i, sum / n);\n  }\n  \n  for (int i = 1; i <= n; ++i) {\n    assert(arr[i] == sum / n);\n  }\n  \n  assert((int)ans.size() <= 3 * n);\n  printf(\"%d\\n\", (int)ans.size());\n  \n  for (auto &[x, y, z] : ans) {\n    printf(\"%d %d %d\\n\", x, y, z);\n  }\n}\n\nint main() {\n  int tt;\n  scanf(\"%d\", &tt);\n  \n  while (tt--) {\n    solve();\n  }\n\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1416",
    "index": "C",
    "title": "XOR Inverse",
    "statement": "You are given an array $a$ consisting of $n$ non-negative integers. You have to choose a non-negative integer $x$ and form a new array $b$ of size $n$ according to the following rule: for all $i$ from $1$ to $n$, $b_i = a_i \\oplus x$ ($\\oplus$ denotes the operation bitwise XOR).\n\nAn inversion in the $b$ array is a pair of integers $i$ and $j$ such that $1 \\le i < j \\le n$ and $b_i > b_j$.\n\nYou should choose $x$ in such a way that the number of inversions in $b$ is minimized. If there are several options for $x$ — output the smallest one.",
    "tutorial": "Note: the integer $x$ from the statement is marked as an uppercase $X$ for clarity. Take any arbitrary integers $x$ and $y$. It is a well-known fact that whether $x < y$ or $x > y$ depends only on one bit - the highest bit which differs in both. So, let's construct a trie on our array integers. Represent each number as a binary string from the highest bit ($29$) to the lowest bit ($0$). Each leaf will keep a corresponding index/indices from the array and each non-leaf node will have at most two children - one for $0$-edge and one for $1$-edge. Let's denote $S(v)$ as a sorted list of indices of all values in the subtree of $v$. These lists can be easily maintained while inserting our numbers into trie. Take any arbitrary vertex $v$ which has both children and has a depth (distance from root) of $k$. Let $a$ and $b$ be its children. Here comes the most important thing to notice: If the $k$-th highest bit of $X$ is toggled, lists $S(a)$ and $S(b)$ will change their relative order. Otherwise, it will not change. Thus, exploiting the fact that both lists are sorted, we can efficiently calculate the corresponding number of inversions between those lists and add them to our values $sum[k][0]$ and $sum[k][1]$. $sum[i][j]$ means the number of inversions we have to add if $i$-th highest bit of $X$ is equal to $j$. After the calculation of our $sum$ table is done, the value of $X$ can be easily restored. Time complexity: $O(n \\log 10^9)$ Memory complexity: $O(n \\log 10^9)$",
    "code": "#include <bits/stdc++.h>\n \n#define mp make_pair\n#define pb push_back\n#define f first\n#define s second\n#define ll long long\n#define forn(i, a, b) for(int i = (a); i <= (b); ++i)\n#define forev(i, b, a) for(int i = (b); i >= (a); --i)\n#define VAR(v, i) __typeof( i) v=(i)\n#define forit(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)\n#define all(x) (x).begin(), (x).end()\n#define sz(x) ((int)(x).size())\n#define file(s) freopen(s\".in\",\"r\",stdin); freopen(s\".out\",\"w\",stdout);\n \nusing namespace std;\n \nconst int maxn = (int)5e6 + 100;\nconst int maxm = (int)1e6 + 100;\nconst int mod = (int)1e9 + 7;\nconst int P = (int) 1e6 + 7; \nconst double pi = acos(-1.0);\n \n#define inf mod\n \ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;   \ntypedef vector<ll> Vll;               \ntypedef vector<pair<int, int> > vpii;\ntypedef vector<pair<ll, ll> > vpll;                        \n\nint n, t[2][maxn], id = 1;\nll dp[2][30];\nvi g[maxn];\n\nvoid add(int x, int pos){\n\tint v = 0;\n\tforev(i, 29, 0){\n\t\tint bit = ((x >> i) & 1);\n\t\tif(!t[bit][v]) t[bit][v] = id++;\n\t\tv = t[bit][v];\n\t\tg[v].pb(pos);\t\n\t}\n}\nvoid go(int v, int b = 29){\n\tint l = t[0][v], r = t[1][v];\n\tif(l) go(l, b - 1);\n\tif(r) go(r, b - 1);\n\tif(!l || !r) return;\n\tll res = 0;\n\tint ptr = 0;\n\tfor(auto x : g[l]){\n\t\twhile(ptr < sz(g[r]) && g[r][ptr] < x) ptr++;\n\t\tres += ptr;\n\t}\n\tdp[0][b] += res;\n\tdp[1][b] += sz(g[l]) * 1ll * sz(g[r]) - res;\n}\nvoid solve(){\n\tscanf(\"%d\", &n);\n\tforn(i, 1, n){\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\tadd(x, i);\n\t}\n\tgo(0);\n\tll inv = 0;\n\tint res = 0;\n\tforn(i, 0, 29){\n\t\tinv += min(dp[0][i], dp[1][i]);\n\t\tif(dp[1][i] < dp[0][i])\n\t\t\tres += (1 << i);\n\t}\n\tprintf(\"%lld %d\", inv, res);\n}\n \nint main () {\n\tint t = 1;\n\t//scanf(\"%d\", &t);\n\twhile(t--) solve();\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "divide and conquer",
      "dp",
      "greedy",
      "math",
      "sortings",
      "strings",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1416",
    "index": "D",
    "title": "Graph and Queries",
    "statement": "You are given an undirected graph consisting of $n$ vertices and $m$ edges. Initially there is a single integer written on every vertex: the vertex $i$ has $p_i$ written on it. All $p_i$ are distinct integers from $1$ to $n$.\n\nYou have to process $q$ queries of two types:\n\n- $1$ $v$ — among all vertices reachable from the vertex $v$ using the edges of the graph (including the vertex $v$ itself), find a vertex $u$ with the largest number $p_u$ written on it, print $p_u$ and replace $p_u$ with $0$;\n- $2$ $i$ — delete the $i$-th edge from the graph.\n\nNote that, in a query of the first type, it is possible that all vertices reachable from $v$ have $0$ written on them. In this case, $u$ is not explicitly defined, but since the selection of $u$ does not affect anything, you can choose any vertex reachable from $v$ and print its value (which is $0$).",
    "tutorial": "Basically, we want to transform each \"connected component maximum\" query into \"segment maximum\" query. It can be efficiently done using DSU and processing all queries in reversed order. For simplicity, let's assume all edges will eventually get deleted in the process. If not, you can always add some extra queries at the end. Initially, each vertex is a connected component on its own. We are processing all queries in reverse order. If the current query is of first type, remember the \"boss\" of the corresponding vertex. Otherwise, unite the corresponding vertices accordingly. If we want to unite two bosses $a$ and $b$, we create a new fake vertex $c$ and add edges $(a, c)$, $(b, c)$ so that the subtree of $c$ becomes responsible for both components of $a$ and $b$. Notice that we cannot apply small-to-large merging to our DSU, but we are still able to use path-compression heuristic. Now, our DSU-tree is ready. Each query of first type is now a subtree-maximum query and all queries of second type can be ignored. The solution onwards should be pretty straightforward. We first do an Eulerian tour on our tree to transform each subtree into a segment. Using segment tree we are able to efficiently process all queries. Time complexity: $O((n + m + q) \\log n)$ Space complexity: $O(n + m + q)$",
    "code": "// chrono::system_clock::now().time_since_epoch().count()\n#include<bits/stdc++.h>\n\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define debug(x) cerr << #x << \" = \" << x << endl;\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\n\nconst int MAXN = (int)5e5 + 5;\nconst int MAXM = (int)3e5 + 5;\nconst int MAXQ = (int)5e5 + 5;\n\npii e[MAXM], que[MAXQ], t[MAXN << 2];\nvector<int> adj[MAXN];\nint tin[MAXN], tout[MAXN], timer;\nint par[MAXN], arr[MAXN];\nbool del[MAXM];\nint n, m, q;\n\nint getPar(int x) {\n  if (x == par[x]) {\n    return x;\n  }\n  \n  return par[x] = getPar(par[x]);\n}\n\nvoid uni(int a, int b) {\n  a = getPar(a);\n  b = getPar(b);\n  \n  if (a == b) {\n    return;\n  }\n  \n  ++n;\n  par[n] = n;\n  par[a] = n;\n  par[b] = n;\n  adj[n].pb(a);\n  adj[n].pb(b);\n}\n\nvoid dfs(int v) {\n  tin[v] = ++timer;\n  \n  for (int to : adj[v]) {\n    dfs(to);\n  }\n  \n  tout[v] = timer;\n}\n\npii segMax(int v, int tl, int tr, int l, int r) {\n  if (l > r || tl > r || tr < l) {\n    return mp(0, 0);\n  }\n  \n  if (l <= tl && tr <= r) {\n    return t[v];\n  }\n  \n  int mid = (tl + tr) >> 1;\n  int c1 = (v << 1), c2 = (c1 | 1);\n  \n  return max(segMax(c1, tl, mid, l, r), segMax(c2, mid + 1, tr, l, r));\n}\n\nvoid updPos(int v, int tl, int tr, int p, pii x) {\n  if (tl == tr) {\n    t[v] = x;\n    return;\n  }\n  \n  int mid = (tl + tr) >> 1;\n  int c1 = (v << 1), c2 = (c1 | 1);\n  \n  if (p <= mid) {\n    updPos(c1, tl, mid, p, x);\n  }\n  else {\n    updPos(c2, mid + 1, tr, p, x);\n  }\n  \n  t[v] = max(t[c1], t[c2]);\n}\n\nvoid solve() {\n  scanf(\"%d %d %d\", &n, &m, &q);\n  \n  for (int i = 1; i <= n; ++i) {\n    scanf(\"%d\", &arr[i]);\n  }\n  \n  for (int i = 1; i <= m; ++i) {\n    int u, v;\n    scanf(\"%d %d\", &u, &v);\n    e[i] = mp(u, v);\n  }\n  \n  for (int i = 1; i <= q; ++i) {\n    int a, b;\n    scanf(\"%d %d\", &a, &b);\n    que[i] = mp(a, b);\n    \n    if (a == 2) {\n      del[b] = 1;\n    }\n  }\n  \n  for (int i = 1; i <= n; ++i) {\n    par[i] = i;\n  }\n  \n  for (int i = 1; i <= m; ++i) {\n    if (!del[i]) {\n      uni(e[i].fi, e[i].se);\n    }\n  }\n  \n  for (int i = q; i > 0; --i) {\n    int tp = que[i].fi;\n    \n    if (tp == 2) {\n      int id = que[i].se;\n      uni(e[id].fi, e[id].se);\n    }\n    else {\n      que[i].se = getPar(que[i].se);\n    }\n  }\n  \n  for (int i = 1; i <= n; ++i) {\n    if (getPar(i) == i) {\n      dfs(i);\n    }\n  }\n  \n  for (int i = 1; i <= n; ++i) {\n    updPos(1, 1, n, tin[i], mp(arr[i], tin[i]));\n  }\n  \n  for (int i = 1; i <= q; ++i) {\n    int tp = que[i].fi;\n   \n    if (tp == 1) {\n      int v = que[i].se;\n      pii tmp = segMax(1, 1, n, tin[v], tout[v]);\n      \n      if (tmp.fi == 0) {\n        printf(\"0\\n\");\n      }\n      else {\n        printf(\"%d\\n\", tmp.fi);\n        updPos(1, 1, n, tmp.se, mp(0, 0));\n      }\n    }\n  }\n}\n\nint main() {\n  int tt = 1;\n  \n  while (tt--) {\n    solve();\n  }\n\n  return 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1416",
    "index": "E",
    "title": "Split",
    "statement": "One day, BThero decided to play around with arrays and came up with the following problem:\n\nYou are given an array $a$, which consists of $n$ positive integers. The array is numerated $1$ through $n$. You execute the following procedure \\textbf{exactly once}:\n\n- You create a new array $b$ which consists of $2n$ \\textbf{positive} integers, where for each $1 \\le i \\le n$ the condition $b_{2i-1}+b_{2i} = a_i$ holds. For example, for the array $a = [6, 8, 2]$ you can create $b = [2, 4, 4, 4, 1, 1]$.\n- You merge consecutive equal numbers in $b$. For example, $b = [2, 4, 4, 4, 1, 1]$ becomes $b = [2, 4, 1]$.\n\nFind and print the minimum possible value of $|b|$ (size of $b$) which can be achieved at the end of the procedure. It can be shown that under the given constraints there is at least one way to construct $b$.",
    "tutorial": "Note that minimizing $|b|$ is the same as maximizing the number of consecutive equal pairs. We will focus on the second version. Let's forget about constraints and consider the most naive solution with dynamic programming. $DP[i][j]$ will store the answer if we have already considered ($a_1$, ..., $a_i$) and our last element $b_{2i}$ is equal to $j$. Let's get rid of our dimension $i$ and keep our $DP$ table by layers. Suppose that our current $i$-th layer is called $curDP$, next layer is called $nxtDP$, and $a_{i+1}$ is called $X$. After carefully analyzing our transitions, we have the following observations: for any $i$, $nxtDP[i] \\ge max(curDP)$, since we always have a transition from our maximum. $max(nxtDP[i]) - min(nxtDP[i]) \\le 2$, since we can add at most two pairs. The case $max(nxtDP[i]) - min(nxtDP[i]) = 2$ may occur only if $a_i$ is even. Moreover, $nxtDP[a_i/2]$ will be the only maximum element. For some suffix upto $i$ we always have a transition from $curDP[X-i] + 1$ to $nxtDP[i]$. If $X$ is even, instead of calculating $nxtDP[X/2]$ separately, we can calculate it as usual and increase its value by $1$ at the end. Using everything said above, we could replace our naive $DP$ with the following: A variable called $zero$ - the value of minimum of our current layer. A set called $one$ - it keeps all indices $i$ such that $curDP[i] = zero + 1$. A variable called $two$ - it is equal to $-1$ or $X/2$ depending on the parity of $X$ and the value of $curDP[X/2]$. Basically, we want to be able to: Erase some elements from the prefix/suffix of our set $one$. Check if some number $x$ is in our set $one$. Add a segment of values $[l, r]$ into out set $one$. Rotate all elements in our set by a pivot $x$. That is, a number $y$ should turn into $x-y$. We can efficiently process all queries by maintaining $one$ as a simple set of non-intersecting segments. The rotation operation can be done as follows: Suppose we had an integer $X$ at the beginning. We rotate everything by a pivot $A$. $X$ becomes $A-X$. We rotate everything by a pivot $B$. $A-X$ becomes $B-A+X$. Following the logic, $C-B+A-X$, $D-C+B-A+X$, ... We can just maintain the sign of $X$ and a global pivot, which is the combination of all our rotation operations. Time complexity: $O(n \\log n)$ Space complexity: $O(n)$",
    "code": "// chrono::system_clock::now().time_since_epoch().count()\n#include<bits/stdc++.h>\n\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define debug(x) cerr << #x << \" = \" << x << endl;\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\n\nconst int dx[] = {0, 1, 0, -1};\nconst int dy[] = {1, 0, -1, 0};\nconst char dc[] = {'R', 'D', 'L', 'U'};\nconst int INF = (int)1e6;\nconst int MAXN = (int)3e5 + 5;\n\nnamespace {\n  struct Edge {\n    int v, to, f, c;\n    \n    Edge() {\n      v = to = f = c = 0;\n    }\n    \n    Edge(int v, int to, int c) : v(v), to(to), c(c) {\n      f = 0;\n    }\n  };\n  \n  vector<Edge> e;\n  vector<int> adj[MAXN];\n  int ptr[MAXN], d[MAXN], q[MAXN];\n  int S, T, newS, newT, V;\n  int cap[2][MAXN];\n  \n  void prep() {\n    e.clear();\n    \n    for (int i = 0; i < V; ++i) {\n      adj[i].clear();\n      ptr[i] = d[i] = q[i] = 0;\n      cap[0][i] = cap[1][i] = 0;\n    }\n  }\n  \n  void addEdge(int u, int v, int c) {\n    //printf(\"E %d %d %d\\n\", u, v, c);\n  \n    adj[u].pb((int)e.size());\n    e.pb(Edge(u, v, c));\n    adj[v].pb((int)e.size());\n    e.pb(Edge(v, u, 0));\n  }\n  \n  void addEdgeLim(int u, int v) {\n    //printf(\"F %d %d\\n\", u, v);\n    ++cap[0][v];\n    ++cap[1][u];\n  }\n  \n  bool bfs() {\n    fill(d, d + V, -1);\n    d[newS] = 0;\n    int l = 0, r = 0;\n    q[r++] = newS;\n    \n    while (l < r) {\n      int v = q[l++];\n      \n      for (int id : adj[v]) {\n        if (e[id].f < e[id].c) {\n          int to = e[id].to;\n          \n          if (d[to] == -1) {\n            d[to] = d[v] + 1;\n            q[r++] = to;\n          }\n        }\n      }\n    }\n    \n    return d[newT] != -1;\n  }\n  \n  int dfs(int v, int flow = INF) {\n    if (!flow || v == newT) {\n      return flow;\n    }\n    \n    int sum = 0;\n    \n    for (; ptr[v] < (int)adj[v].size(); ++ptr[v]) {\n      int id = adj[v][ptr[v]];\n      int to = e[id].to;\n      int can = e[id].c - e[id].f;\n      \n      if (d[to] != d[v] + 1 || can == 0) {\n        continue;\n      }\n      \n      int pushed = dfs(to, min(flow, can));\n      \n      if (pushed > 0) {\n        e[id].f += pushed;\n        e[id ^ 1].f -= pushed;\n        sum += pushed;\n        flow -= pushed;\n        \n        if (flow == 0) {\n          return sum;\n        }\n      }\n    }\n    \n    return sum;\n  }\n  \n  int maxFlow() {\n    int ret = 0;\n    \n    while (bfs()) {\n      fill(ptr, ptr + V, 0);\n    \n      while (int pushed = dfs(newS)) {\n        ret += pushed;\n      }\n    }\n    \n    return ret;\n  }\n}\n\nvvi arr, follow;\nint n, m;\n\nbool inside(int x, int y) {\n  return 0 <= x && x < n && 0 <= y && y < m;\n}\n\nint id(int x, int y) {\n  return x * m + y;\n}\n\nvoid solve() {\n  scanf(\"%d %d\", &n, &m);\n  arr = follow = vvi(n, vi(m, -1));\n  S = n * m;\n  T = S + 1;\n  newS = T + 1;\n  newT = newS + 1;\n  V = newT + 1;\n  prep();\n  \n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < m; ++j) {\n      scanf(\"%d\", &arr[i][j]);\n    }\n  }\n  \n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < m; ++j) {\n      for (int dir = 0; dir < 4; ++dir) {\n        int ni = i + dx[dir], nj = j + dy[dir];\n        \n        if (inside(ni, nj)) {\n          if (arr[ni][nj] < arr[i][j]) {\n            follow[i][j] = dir;\n          }\n          else if ((i + j) % 2 == 0 && arr[ni][nj] == arr[i][j]) {\n            addEdge(id(i, j), id(ni, nj), 1);\n          }\n        }\n      }\n      \n      if (follow[i][j] == -1) {\n        // important vertex\n        if ((i + j) % 2) {\n          addEdgeLim(id(i, j), T);\n        }\n        else {\n          addEdgeLim(S, id(i, j));\n        }\n      }\n      else {\n        if ((i + j) % 2) {\n          addEdge(id(i, j), T, 1);\n        }\n        else {\n          addEdge(S, id(i, j), 1);\n        }\n      }\n    }\n  }\n  \n  for (int i = 0; i <= T; ++i) {\n    if (cap[0][i] > 0) {\n      addEdge(newS, i, cap[0][i]);\n    }\n    \n    if (cap[1][i] > 0) {\n      addEdge(i, newT, cap[1][i]);\n    }\n  }\n  \n  addEdge(T, S, INF);\n  maxFlow();\n  \n  for (int id : adj[newS]) {\n    if (e[id].f != e[id].c) {\n      printf(\"NO\\n\");\n      return;\n    }\n  }\n  \n  vvi ansv, ansc;\n  ansv = ansc = vvi(n, vi(m));\n  \n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < m; ++j) {\n      int dir = follow[i][j];\n      \n      if (dir != -1) {\n        int ni = i + dx[dir], nj = j + dy[dir];\n        ansv[i][j] = arr[i][j] - arr[ni][nj];\n        ansc[i][j] = dir;\n      }\n    }\n  }\n  \n  for (Edge it : e) {\n    int v = it.v, to = it.to;\n    \n    if (max(v, to) < n * m && it.f == it.c && it.c == 1) {\n      int ax = v / m, ay = v % m;\n      int bx = to / m, by = to % m;\n      ansv[ax][ay] = arr[ax][ay] - 1;\n      ansv[bx][by] = 1;\n      \n      for (int dir = 0; dir < 4; ++dir) {\n        if (mp(ax + dx[dir], ay + dy[dir]) == mp(bx, by)) {\n          ansc[ax][ay] = dir;\n          ansc[bx][by] = (dir + 2) % 4;\n        }\n      }\n    }\n  }\n  \n  printf(\"YES\\n\");\n  \n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < m; ++j) {\n      printf(\"%d%c\", ansv[i][j], \" \\n\"[j == m - 1]);\n    }\n  }\n  \n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j < m; ++j) {\n      printf(\"%c%c\", dc[ansc[i][j]], \" \\n\"[j == m - 1]);\n    }\n  }\n}\n\nint main() {\n  int tt;\n  scanf(\"%d\", &tt);\n  \n  while (tt--) {\n    solve();\n  }\n\n  return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1417",
    "index": "A",
    "title": "Copy-paste",
    "statement": "\\begin{quote}\n— Hey folks, how do you like this problem?— That'll do it.\n\\end{quote}\n\nBThero is a powerful magician. He has got $n$ piles of candies, the $i$-th pile initially contains $a_i$ candies. BThero can cast a copy-paste spell as follows:\n\n- He chooses two piles $(i, j)$ such that $1 \\le i, j \\le n$ and $i \\ne j$.\n- All candies from pile $i$ are copied into pile $j$. Formally, the operation $a_j := a_j + a_i$ is performed.\n\nBThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than $k$ candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power?",
    "tutorial": "If we do our operation on two arbitrary integers $x \\le y$, it is always better to copy $x$ into $y$ rather than to copy $y$ into $x$ (since a resulting pair $(x, x + y)$ is better than $(y, x + y)$). Now, let's assume that we do our operation on two integers $x \\le y$ such that $x$ is not the minimum element of our array. If we replace $x$ with minimum, we can always achieve at least the same answer. Thus, we can take any index $m$ such that $a_m$ is the array minimum and use it to increase all other values. Time complexity: $O(n)$ or $O(nk)$ per testcase. Space complexity: $O(n)$",
    "code": "// chrono::system_clock::now().time_since_epoch().count()\n#include<bits/stdc++.h>\n\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define debug(x) cerr << #x << \" = \" << x << endl;\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\n\nconst int MAXN = (int)1e3 + 5;\n\nint n, k;\nint arr[MAXN];\n\nvoid solve() {\n  scanf(\"%d %d\", &n, &k);\n  \n  for (int i = 1; i <= n; ++i) {\n    scanf(\"%d\", &arr[i]);\n  }\n  \n  int mn = min_element(arr + 1, arr + n + 1) - arr;\n  int ans = 0;\n  \n  for (int i = 1; i <= n; ++i) {\n    if (i != mn) {\n      while (arr[i] + arr[mn] <= k) {\n        arr[i] += arr[mn];\n        ++ans;\n      }\n    }\n  }\n  \n  printf(\"%d\\n\", ans);\n}\n\nint main() {\n  int tt;\n  scanf(\"%d\", &tt);\n  \n  while (tt--) {\n    solve();\n  }\n\n  return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1417",
    "index": "B",
    "title": "Two Arrays",
    "statement": "RedDreamer has an array $a$ consisting of $n$ non-negative integers, and an unlucky integer $T$.\n\nLet's denote the misfortune of array $b$ having length $m$ as $f(b)$ — the number of pairs of integers $(i, j)$ such that $1 \\le i < j \\le m$ and $b_i + b_j = T$. RedDreamer has to paint each element of $a$ into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays $c$ and $d$ so that all white elements belong to $c$, and all black elements belong to $d$ \\textbf{(it is possible that one of these two arrays becomes empty)}. RedDreamer wants to paint the elements in such a way that $f(c) + f(d)$ is \\textbf{minimum} possible.\n\nFor example:\n\n- if $n = 6$, $T = 7$ and $a = [1, 2, 3, 4, 5, 6]$, it is possible to paint the $1$-st, the $4$-th and the $5$-th elements white, and all other elements black. So $c = [1, 4, 5]$, $d = [2, 3, 6]$, and $f(c) + f(d) = 0 + 0 = 0$;\n- if $n = 3$, $T = 6$ and $a = [3, 3, 3]$, it is possible to paint the $1$-st element white, and all other elements black. So $c = [3]$, $d = [3, 3]$, and $f(c) + f(d) = 0 + 1 = 1$.\n\nHelp RedDreamer to paint the array optimally!",
    "tutorial": "Let us partition the array into three sets $X$, $Y$, $Z$ such that $X$ contains all numbers less than $T/2$, $Y$ contains all numbers equal to $T/2$ and $Z$ contains all numbers greater than $T/2$. It is clear that $f(X) = f(Z) = 0$. Now, since each pair in $Y$ makes a sum of $T$, the best solution is to distribute all numbers in $Y$ equally among $X$ and $Z$. Time complexity: $O(n)$ Space complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n#define len(v) ((int)((v).size()))\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n#define chmax(x, v) x = max((x), (v))\n#define chmin(x, v) x = min((x), (v))\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n\tint n, tar;\n\tcin >> n >> tar;\n\tint curMid = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tint x; cin >> x;\n\t\tint r;\n\t\tif (tar % 2 == 0 && x == tar/2)\n\t\t\tr = (curMid++) % 2;\n\t\telse if (2*x < tar)\n\t\t\tr = 0;\n\t\telse\n\t\t\tr = 1;\n\t\tcout << r << \" \\n\"[i==n-1];\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false), cin.tie(0);\n\n\tint nbTests;\n\tcin >> nbTests;\n\tfor (int iTest = 0; iTest < nbTests; ++iTest) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1418",
    "index": "A",
    "title": "Buying Torches",
    "statement": "You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $k$ torches. One torch can be crafted using \\textbf{one stick and one coal}.\n\nHopefully, you've met a very handsome wandering trader who has two trade offers:\n\n- exchange $1$ stick for $x$ sticks (you lose $1$ stick and gain $x$ sticks).\n- exchange $y$ sticks for $1$ coal (you lose $y$ sticks and gain $1$ coal).\n\nDuring one trade, you can use \\textbf{only one} of these two trade offers. You can use each trade offer any number of times you want to, in any order.\n\nYour task is to find the minimum number of trades you need to craft at least $k$ torches. The answer always exists under the given constraints.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "You need $s = yk + k - 1$ additional sticks to get $k$ torches ($yk$ sticks for $y$ units of coal and also $k$ sticks required to craft torches) and you get $x-1$ sticks per one trade. To buy this number of sticks, you need $\\left\\lceil\\frac{s}{x-1}\\right\\rceil$ trades. And also, you need $k$ additional trades to turn some sticks into coals. And the final answer is $\\left\\lceil\\frac{s}{x-1}\\right\\rceil + k$.",
    "code": "for i in range(int(input())):\n    x, y, k = map(int, input().split())\n    print(((y + 1) * k - 1 + x - 2) // (x - 1) + k)",
    "tags": [
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1418",
    "index": "B",
    "title": "Negative Prefixes",
    "statement": "You are given an array $a$, consisting of $n$ integers.\n\nEach position $i$ ($1 \\le i \\le n$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.\n\nFor example, let $a = [-1, 1, \\underline{3}, 2, \\underline{-2}, 1, -4, \\underline{0}]$, the underlined positions are locked. You can obtain the following arrays:\n\n- $[-1, 1, \\underline{3}, 2, \\underline{-2}, 1, -4, \\underline{0}]$;\n- $[-4, -1, \\underline{3}, 2, \\underline{-2}, 1, 1, \\underline{0}]$;\n- $[1, -1, \\underline{3}, 2, \\underline{-2}, 1, -4, \\underline{0}]$;\n- $[1, 2, \\underline{3}, -1, \\underline{-2}, -4, 1, \\underline{0}]$;\n- and some others.\n\nLet $p$ be a sequence of prefix sums of the array $a$ after the rearrangement. So $p_1 = a_1$, $p_2 = a_1 + a_2$, $p_3 = a_1 + a_2 + a_3$, $\\dots$, $p_n = a_1 + a_2 + \\dots + a_n$.\n\nLet $k$ be the maximum $j$ ($1 \\le j \\le n$) such that $p_j < 0$. If there are no $j$ such that $p_j < 0$, then $k = 0$.\n\nYour goal is to rearrange the values in such a way that $k$ is minimum possible.\n\nOutput the array $a$ after the rearrangement such that the value $k$ for it is minimum possible. If there are multiple answers then print any of them.",
    "tutorial": "Let's collect the prefix sums of the initial array $a$. How do they change if you swap two values in the array? Let's swap values on positions $l$ and $r$ ($l < r$). Prefix sums from $1$ to $l-1$ aren't changed. Prefix sums from $l$ to $r-1$ are increased by $a_r-a_l$ (note that if $a_l>a_r$ then these sums become smaller). Finally, prefix sums from $r$ to $n$ aren't changed as well. Thus, swapping two values $a_l<a_r$ will only increase some prefix sums but never decrease any of them. That helps us see that the array such that all values on the unlocked positions are sorted in a non-increasing order is the most optimal one. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n), c;\n    forn(i, n) cin >> a[i];\n    forn(i, n) cin >> b[i];\n    forn(i, n) if (!b[i])\n        c.push_back(a[i]);\n    sort(c.rbegin(), c.rend());\n    int j = 0;\n    forn(i, n) {\n        if (b[i]) cout << a[i] << ' ';\n        else cout << c[j++] << ' ';\n    }\n    cout << '\\n';\n}\n\nint main() {\n    int T;\n    cin >> T;\n    while (T--) solve();\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1418",
    "index": "C",
    "title": "Mortal Kombat Tower",
    "statement": "You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $n$ bosses in this tower, numbered from $1$ to $n$. The type of the $i$-th boss is $a_i$. If the $i$-th boss is easy then its type is $a_i = 0$, otherwise this boss is hard and its type is $a_i = 1$.\n\nDuring one session, either you or your friend can kill \\textbf{one or two} bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. \\textbf{The first session is your friend's session}.\n\nYour friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.\n\nYour task is to find the \\textbf{minimum} number of skip points your friend needs to use so you and your friend kill all $n$ bosses in the given order.\n\nFor example: suppose $n = 8$, $a = [1, 0, 1, 1, 0, 1, 1, 1]$. Then the best course of action is the following:\n\n- your friend kills two first bosses, using one skip point for the first boss;\n- you kill the third and the fourth bosses;\n- your friend kills the fifth boss;\n- you kill the sixth and the seventh bosses;\n- your friend kills the last boss, using one skip point, so the tower is completed using two skip points.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If $a_1 = 1$ then our friend always needs one skip point because he always has to kill the first boss. Let's just remove this boss from our consideration and increase the answer if needed. What about other skip points? Firstly, let's understand that we can always do our moves in such a way that the first hard boss will always be killed by us (except the first one). So, if it's our friend turn now and there is only one easy boss before the hard, our friend just kills this easy boss. If there are two easy bosses, he kills both. If there are three, friend kills the first, we kill the second, and he kills the third. And so on. So we can always assume that each segment of hard bosses starts with our move. We can kill each such segment greedily: we kill two bosses and our friend kills one. If there are less than three bosses in the segment, we just kill remaining and proceed. So if the length of the current segment of hard bosses is $k$ then we need $\\left\\lfloor\\frac{k}{3}\\right\\rfloor$ skip points. Summing up these values over all segments we get the answer (and don't forget that the first boss should be handled separately). Segments of ones can be extracted using two pointers. There are also dynamic programming solution but I found this one more clever.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (auto &it : a) cin >> it;\n        int ans = 0;\n        ans += a[0] == 1;\n        for (int i = 1; i < n; ++i) {\n            if (a[i] == 0) {\n                continue;\n            }\n            int j = i;\n            while (j < n && a[j] == 1) {\n                ++j;\n            }\n            ans += (j - i) / 3;\n            i = j - 1;\n        }\n        cout << ans << endl;\n    }\n    \n    return 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1418",
    "index": "D",
    "title": "Trash Problem",
    "statement": "Vova decided to clean his room. The room can be represented as the coordinate axis $OX$. There are $n$ piles of trash in the room, coordinate of the $i$-th pile is the integer $p_i$. All piles have \\textbf{different} coordinates.\n\nLet's define a total cleanup as the following process. The goal of this process is to collect \\textbf{all} the piles in \\textbf{no more than two} different $x$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $x$ and move \\textbf{all piles} from $x$ to $x+1$ or $x-1$ using his broom. Note that he can't choose how many piles he will move.\n\nAlso, there are two types of queries:\n\n- $0$ $x$ — remove a pile of trash from the coordinate $x$. It is guaranteed that there is a pile in the coordinate $x$ at this moment.\n- $1$ $x$ — add a pile of trash to the coordinate $x$. It is guaranteed that there is no pile in the coordinate $x$ at this moment.\n\nNote that it is possible that there are zero piles of trash in the room at some moment.\n\nVova wants to know the \\textbf{minimum} number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.\n\nFor better understanding, please read the \\textbf{Notes} section below to see an explanation for the first example.",
    "tutorial": "First, let's understand that if we choose some subset of points $x_1, x_2, \\dots, x_k$, then it does not matter to which point we move it (inside the segment [$\\min(x_1, x_2, \\dots, x_k); \\max(x_1, x_2, \\dots, x_k)]$) because the minimum number of moves will always be the same and it is equal to $\\max(x_1, x_2, \\dots, x_k) - \\min(x_1, x_2, \\dots, x_k)$. Okay, we need to split all points into two subsets and collect all points of the first subset in some point inside it and the same with the second subset. What can we notice? If we sort the points, it's always optimal to choose these subsets as segments. I.e. if the maximum point of the first subset is $x_r$, the minimum point of the second subset is $x_l$ and $x_l < x_r$, we can swap them and decrease answers for both subsets. So, we need to cover all the points with two segments with the minimum total length. What is this length? It is $x_n - x_1 - maxGap$. $MaxGap$ is the maximum distance between two consecutive points (i.e. $max(x_2 - x_1, x_3 - x_2, \\dots, x_n - x_{n-1})$. So, we can solve the problem in $O(n \\log{n})$ without queries. But how to deal with queries? Let's maintain the set which contains all points $x_i$ and the multiset (set with repetitions) that maintains all gaps between two adjacent points. So, the answer is maximum in the set of points minus minimum in the set of points minus maximum in the multiset of lengths. How do we recalculate these sets between queries? If some point $x$ is removed, let's find the maximum point less than $x$ (let it be $x_l$) and the minimum point greater than $x$ (let it be $x_r$) in the current set of points. Both these points can be found in a logarithmic time. Then we need to remove $x - x_l$ with $x_r - x$ from the multiset and add $x_r - x_l$ to the multiset (and, of course, remove $x$ from the set). If some point $x$ is added, then we need to remove $x_r - x_l$ from the multiset and add $x - x_l$ with $x_r - x$ to the multiset (and add $x$ to the set). So, we can process every query in $O(\\log{n + q})$ time and the total time complexity is $O((n+q) \\log{(n + q)})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint get(const set<int> &x, const multiset<int> &len) {\n    if (len.empty()) return 0;\n    return *x.rbegin() - *x.begin() - *len.rbegin();\n}\n\nvoid add(int p, set<int> &x, multiset<int> &len) {\n    x.insert(p);\n    auto it = x.find(p);\n    int prv = -1, nxt = -1;\n    if (it != x.begin()) {\n        --it;\n        len.insert(p - *it);\n        prv = *it;\n        ++it;\n    }\n    ++it;\n    if (it != x.end()) {\n        len.insert(*it - p);\n        nxt = *it;\n    }\n    if (prv != -1 && nxt != -1) {\n        len.erase(len.find(nxt - prv));\n    }\n}\n\nvoid rem(int p, set<int> &x, multiset<int> &len) {\n    auto it = x.find(p);\n    int prv = -1, nxt = -1;\n    if (it != x.begin()) {\n        --it;\n        len.erase(len.find(p - *it));\n        prv = *it;\n        ++it;\n    }\n    ++it;\n    if (it != x.end()) {\n        len.erase(len.find(*it - p));\n        nxt = *it;\n    }\n    x.erase(p);\n    if (prv != -1 && nxt != -1) {\n        len.insert(nxt - prv);\n    }\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int n, q;\n    cin >> n >> q;\n    set<int> x;\n    multiset<int> len;\n    for (int i = 0; i < n; ++i) {\n        int p;\n        cin >> p;\n        add(p, x, len);\n    }\n    \n    cout << get(x, len) << endl;\n    for (int i = 0; i < q; ++i) {\n        int t, p;\n        cin >> t >> p;\n        if (t == 0) {\n            rem(p, x, len);\n        } else {\n            add(p, x, len);\n        }\n        cout << get(x, len) << endl;\n    }\n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1418",
    "index": "E",
    "title": "Expected Damage",
    "statement": "You are playing a computer game. In this game, you have to fight $n$ monsters.\n\nTo defend from monsters, you need a shield. Each shield has two parameters: its current durability $a$ and its defence rating $b$. Each monster has only one parameter: its strength $d$.\n\nWhen you fight a monster with strength $d$ while having a shield with current durability $a$ and defence $b$, there are three possible outcomes:\n\n- if $a = 0$, then you receive $d$ damage;\n- if $a > 0$ and $d \\ge b$, you receive no damage, but the current durability of the shield decreases by $1$;\n- if $a > 0$ and $d < b$, nothing happens.\n\nThe $i$-th monster has strength $d_i$, and you will fight each of the monsters exactly once, in some random order (all $n!$ orders are equiprobable). You have to consider $m$ different shields, the $i$-th shield has initial durability $a_i$ and defence rating $b_i$. For each shield, calculate the expected amount of damage you will receive if you take this shield and fight the given $n$ monsters in random order.",
    "tutorial": "First of all, let's find a solution in $O(nm)$. We will use the lineriality of expectation: the answer for some shield $j$ is equal to $\\sum\\limits_{i = 1}^{n} d_i P(i, j)$, where $P(i, j)$ is the probability that the monster $i$ will deal damage if we use the $j$-th shield. Let's see how to calculate $P(i, j)$. Consider a monster $i$ such that $d_i \\ge b_j$. To deal damage, he should be preceded by at least $a_j$ other monsters having $d_i \\ge b_j$. We can write a complicated formula with binomial coefficients to calculate the probability of this happening, and then simplify it, but a much easier solution is to consider the order of these \"strong\" monsters. Suppose there are $k$ of them, then there are $\\max(k - a_j, 0)$ strong monsters that will deal damage. Since all orderings are equiprobable, the probability that our fixed monster will deal damage is $\\dfrac{\\max(k - a_j, 0)}{k}$ - since it is the probability that it will take one of the last places in the order. Okay, what about \"weak\" monsters? It turns out that we can use the same approach: to deal damage, a weak monster should be preceded by at least $a_j$ strong monsters. Consider the relative order of $k$ strong monsters and that weak monster we are analyzing. There are $\\max(k + 1 - a_j, 0)$ positions where the weak monster will deal damage, so the probability of weak monster dealing damage is $\\dfrac{\\max(k + 1 - a_j, 0)}{k + 1}$. Okay, we got a solution in $O(nm)$. How to make it faster? Whenever we consider a shield, all monsters are split into two types: strong and weak, and we may sort the monsters beforehand, so the number of strong monsters (and their total strength) can be found with binary search. Since the probabilities for all strong monsters are the same, we can multiply their total strength by the probability that one fixed strong monster will deal damage (we already described how to calculate it). The same applies for the weak monsters, so the total complexity is $O(n \\log n + m (\\log n + \\log MOD))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = int(2e5) + 9;\nconst int MOD = 998244353;\n\nint mul(int a, int b) {\n    return (a * 1LL * b) % MOD;\n}\n\nint bp(int a, int n) {\n    int res = 1;\n    for (; n > 0; n /= 2) {\n        if (n & 1) res = mul(res, a);\n        a = mul(a, a);\n    }\n    \n    return res;\n}\n\nint inv(int a) {\n    int ia = bp(a, MOD - 2);\n    assert(mul(a, ia) == 1);\n    return ia;\n}\n\nint n, m;\nint d[N];\nlong long sd[N];\n\nlong long sum (int l, int r) {\n    return (sd[r] - sd[l]) % MOD;\n}\n\nint main(){\n    cin >> n >> m;\n    for (int i = 0; i < n; ++i)\n        scanf(\"%d\", d + i);\n    sort(d, d + n);\n    for (int i = 0; i < n; ++i)\n        sd[i + 1] = sd[i] + d[i];\n        \n    for (int i = 0; i < m; ++i) {\n        int a, b;\n        scanf(\"%d%d\", &a, &b); // dur, def\n        int cnt = (d + n) - lower_bound(d, d + n, b);\n        int res = 0;\n        if (cnt >= a) {\n            res = mul( mul(cnt - a, inv(cnt)), sum(n - cnt, n) );\n            res += mul( mul(cnt - a + 1, inv(cnt + 1)), sum(0, n - cnt) );\n            res %= MOD;\n        }\n        printf(\"%d\\n\", res);\n    }\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1418",
    "index": "F",
    "title": "Equal Product",
    "statement": "You are given four integers $n$, $m$, $l$ and $r$.\n\nLet's name a tuple $(x_1, y_1, x_2, y_2)$ as good if:\n\n- $1 \\le x_1 < x_2 \\le n$;\n- $1 \\le y_2 < y_1 \\le m$;\n- $x_1 \\cdot y_1 = x_2 \\cdot y_2$;\n- $l \\le x_1 \\cdot y_1 \\le r$.\n\nFind any good tuple \\textbf{for each $x_1$ from $1$ to $n$ inclusive}.",
    "tutorial": "Let's look at $x_1 y_1 = x_2 y_2$ where $x_1 < x_2$. It can be proven that there always exists such pair $(a, b)$ ($a \\mid x_1$, $b \\mid y_1$ and $a < b$) that $x_2 = \\frac{x_1}{a} b$ and $y_2 = \\frac{y_1}{b} a$. Brief proof is following: calculate $g = \\gcd(x_1, x_2)$, then let $a = \\frac{x_1}{g}$ and $b = \\frac{x_2}{g}$. Obviously, such $(a, b)$ will make $x_2$ from $x_1$ and $y_2$ from $y_1$ (if $b \\mid y_1$). And since $b = \\frac{x_2}{g} \\Rightarrow$ $b \\mid \\frac{x_2 y_2}{g} \\Rightarrow$ $b \\mid \\frac{x_1 y_1}{g} \\Rightarrow$ $b \\mid \\frac{x_1}{g} y_1$ and since $\\gcd(b, \\frac{x_1}{g}) = 1 \\Rightarrow$ $b \\mid y_1$. As we can see $a$ divides $x_1$, so if we will iterate over all pairs $(x_1, a)$ where $1 \\le x_1 \\le n$ there will be $O(n \\log n)$ pairs in total. Let's fix value of $x_1$. Then, from one side, $y_1 \\le m$ but, from the other side, since $l \\le x_1 y_1 \\le r$, then $\\left\\lceil \\frac{l}{x_1} \\right\\rceil \\le y_1 \\le \\left\\lfloor \\frac{r}{x_1} \\right\\rfloor$. Anyway, all valid $y_1$ form a segment (possibly, empty segment). And we need to find any $b > a$ that divides any $y_1$ from the segment and $x_2 = \\frac{x_1}{a} b$ doesn't exceed $n$. Obviously, it's optimally to find the minimum possible such $b$ and just check inequality $\\frac{x_1}{a} b \\le n$. We can find such $b$ for a fixed $(x_1, a)$ using, for example, built-in upper_bound in a set with all divisors for all valid $y_1$. To maintain this set we can note that $\\frac{l}{x_1 + 1} \\le \\frac{l}{x_1}$ (simillary, $\\frac{r}{x_1 + 1} \\le \\frac{r}{x_1}$). So we can move valid segment's ends as two pointers. Each pair $(y_1, b)$ will be added and erased from the segment exactly once. That's why the total complexity of maintaining the set of divisors (as well as the total complexity of queries for each $(x_1, a)$) will be equal to $O((n + m) \\log^2 (n + m))$. All pairs $(x_1, a)$ (and $(y_1, b)$) can be precalculated in $O((n + m) \\log (n + m))$ using the sieve-like algorithm.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n    return out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n    out << \"[\";\n    fore(i, 0, sz(v)) {\n        if(i) out << \", \";\n        out << v[i];\n    }\n    return out << \"]\";\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nint n, m;\nli l, r;\n\ninline bool read() {\n    if(!(cin >> n >> m))\n        return false;\n    cin >> l >> r;\n    return true;\n}\n\nconst int N = int(2e5) + 555;\nvector<int> divs[N];\n\ninline void solve() {\n    fore(d, 1, N) {\n        for(int pos = d; pos < N; pos += d)\n            divs[pos].push_back(d);\n    }\n    \n    li lf = m + 1, rg = m;\n    vector<int> cnt(m + 1, 0);\n    vector<int> id(m + 1, -1);\n    set<int> curDivs;\n    \n    vector< vector<int> > ans(n + 1);\n    \n    fore(x1, 1, n + 1) {\n        li newlf = (l + x1 - 1) / x1;\n        li newrg = r / x1;\n        assert(newrg - newlf + 1 >= 0);\n        \n        while (lf > newlf) {\n            lf--;\n            for (int d : divs[lf]) {\n                if (cnt[d] == 0)\n                    curDivs.insert(d);\n                cnt[d]++;\n                id[d] = (int)lf;\n            }\n        }\n        while (rg > newrg) {\n            for (int d : divs[rg]) {\n                cnt[d]--;\n                if (cnt[d] == 0)\n                    curDivs.erase(d);\n            }\n            rg--;\n        }\n        \n        for (int a : divs[x1]) {\n            auto it = curDivs.upper_bound(a);\n            if (it == curDivs.end())\n                continue;\n            \n            int b = *it;\n            if (x1 / a * 1ll * b <= n) {\n                int y1 = id[b];\n                \n                ans[x1] = {x1, y1, x1 / a * b, y1 / b * a};\n            }\n        }\n    }\n    \n    fore(i, 1, n + 1) {\n        if (ans[i].empty())\n            cout << -1 << '\\n';\n        else {\n            cout << ans[i][0] << \" \" << ans[i][1] << \" \" << ans[i][2] << \" \" << ans[i][3] << '\\n';\n        }\n    }\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1418",
    "index": "G",
    "title": "Three Occurrences",
    "statement": "You are given an array $a$ consisting of $n$ integers. We denote the subarray $a[l..r]$ as the array $[a_l, a_{l + 1}, \\dots, a_r]$ ($1 \\le l \\le r \\le n$).\n\nA subarray is considered good if every integer that occurs in this subarray occurs there \\textbf{exactly thrice}. For example, the array $[1, 2, 2, 2, 1, 1, 2, 2, 2]$ has three good subarrays:\n\n- $a[1..6] = [1, 2, 2, 2, 1, 1]$;\n- $a[2..4] = [2, 2, 2]$;\n- $a[7..9] = [2, 2, 2]$.\n\nCalculate the number of good subarrays of the given array $a$.",
    "tutorial": "Let's consider two solutions: a non-deterministic and a deterministic one. The random solution goes like that. Let's assign a random integer to each value from $1$ to $n$ (to value, not to a position). Let the value of the subarray be the trit-wise sum of the assigned integers of all values on it. Trit-wise is the analogue of bit-wise sum (xor) but in ternary system. So adding up the same integer three times trit-wise is always equal to zero. Thus, if the value on a subarray is zero then each value appears on it a multiple of three times. How to count the number of such subarrays? Process the array from left to right and store the prefix trit-wise sums in a map. The number of the valid subarrays that end in the current position is the number of occurrences of the current prefix trit-wise sum in a map. The current sum should be added to the map afterwards. However, that's not what the problem asks us to find. Let's consider another problem: count the number of subarray such that each number appears no more than three times. This can be done with two pointers. Process the array from left to right and for each number store the positions it occurred on. If some number appears at least four times than the left pointer should be moved to the next position after the fourth-to-last position. The number of valid subarrays the end in the current position is the distance to the left pointer. Let's combine these problems: maintain the pointer to only the valid positions and remove the prefix trit-wise sums from the map as you increase the pointer. That way the map will only store the valid sums, and they can be added to answer as they are. Assume you use $K$ trits. I guess the probability of the collision is the same as two vectors (out of $n$) colliding in a $K$-dimensional space with their coordinates being from $0$ to $2$. That will be about $\\frac{1}{2}$ when $n \\approx \\sqrt{3^K}$ (according to birthday paradox) - and way less if we increase $K$. Overall complexity: $O(nK \\log n)$. The deterministic solution (a.k.a. the boring one) goes like that. Let's again process the array from left to right. Let the current position be the right border of the segment. Each number makes some constraints on where the left border might be. More specifically, it's two possible segments: between its last occurrence and the current position and between its fourth-to-last occurrence and its third-to-last one. Let's actually invert these segments. Bad segments are from the beginning of the array to the fourth-to-last occurrence, then from the second-to-last occurrence to the last one. So the valid left borders are in such positions that are covered by zero bad segments. Let's keep track of them in a segment tree. Add $1$ on the bad subarrays. Now you have to count the number of $0$ values in a segtree. That's a pretty common problem. As we know that no values can go below $0$, $0$ should be a minimum element on the segment. So we can store a pair of (minimum on segment, number of minimums on segment). At the end the second value is the number of zeros if the first value is zero. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++)\n\ntypedef unsigned long long uli;\n\nvector<int> a;\nvector<pair<int, int>> t;\nvector<int> ps;\n\npair<int, int> merge(const pair<int, int> &a, const pair<int, int> &b){\n    if (a.first != b.first)\n        return min(a, b);\n    return make_pair(a.first, a.second + b.second);\n}\n\nvoid push(int v){\n    if (v * 2 + 1 < int(ps.size())){\n        ps[v * 2] += ps[v];\n        ps[v * 2 + 1] += ps[v];\n    }\n    t[v].first += ps[v];\n    ps[v] = 0;\n}\n\nvoid build(int v, int l, int r){\n    if (l == r - 1){\n        t[v] = make_pair(0, 1);\n        return;\n    }\n    int m = (l + r) / 2;\n    build(v * 2, l, m);\n    build(v * 2 + 1, m, r);\n    t[v] = merge(t[v * 2], t[v * 2 + 1]);\n}\n\nvoid upd(int v, int l, int r, int L, int R, int val){\n    push(v);\n    if (L >= R)\n        return;\n    if (l == L && r == R){\n        ps[v] = val;\n        push(v);\n        return;\n    }\n    int m = (l + r) / 2;\n    upd(v * 2, l, m, L, min(m, R), val);\n    upd(v * 2 + 1, m, r, max(m, L), R, val);\n    t[v] = merge(t[v * 2], t[v * 2 + 1]);\n}\n\nint main(){\n    int n;\n    scanf(\"%d\", &n);\n    a.resize(n);\n    forn(i, n){\n        scanf(\"%d\", &a[i]);\n        --a[i];\n    }\n    t.resize(4 * n);\n    ps.resize(4 * n);\n    build(1, 0, n);\n    vector<vector<int>> pos(n, vector<int>(1, -1));\n    long long ans = 0;\n    forn(i, n){\n        int k = pos[a[i]].size();\n        if (k >= 1) upd(1, 0, n, pos[a[i]][k - 1] + 1, i + 1, 1);\n        if (k >= 3) upd(1, 0, n, pos[a[i]][k - 3] + 1, pos[a[i]][k - 2] + 1, -1);\n        if (k >= 4) upd(1, 0, n, pos[a[i]][k - 4] + 1, pos[a[i]][k - 3] + 1, 1);\n        pos[a[i]].push_back(i);\n        push(1);\n        if (t[1].first == 0) ans += t[1].second - (n - i - 1);\n    }\n    printf(\"%lld\\n\", ans);\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "hashing",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1419",
    "index": "A",
    "title": "Digit Game",
    "statement": "Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $t$ matches of a digit game...\n\nIn each of $t$ matches of the digit game, a positive integer is generated. It consists of $n$ digits. The digits of this integer are numerated from $1$ to $n$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.\n\nAgents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.\n\nIt can be proved, that before the end of the match (for every initial integer with $n$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.\n\nFor each of $t$ matches find out, which agent wins, if both of them want to win and play optimally.",
    "tutorial": "Let's say that digits on odd positions are blue and digits on even positions are red. If $n$ is even the remaining digit will be red. If there is at least one even red digit then Breach wins (he can mark all digits except the one that will remain in the end). In other case Raze wins, because any digit that may remain is odd. If $n$ is odd the remaining digit will be blue. If there is at least one odd blue digit then Raze wins (using the same strategy applied to her). In other case Breach wins.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\nsigned main() {\\n\\tint T;\\n\\tcin >> T;\\n\\twhile (T --> 0) {\\n\\t\\tint n;\\n\\t\\tstring s;\\n\\t\\tcin >> n >> s;\\n\\t\\tbool odd = false, even = false;\\n\\t\\tfor (int i = 1; i <= n; ++i) {\\n\\t\\t\\tif (i % 2 == 1) {\\n\\t\\t\\t\\todd |= ((s[i - 1] - '0') % 2 == 1);\\n\\t\\t\\t} else {\\n\\t\\t\\t\\teven |= ((s[i - 1] - '0') % 2 == 0);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif (n % 2 == 1) {\\n\\t\\t\\tcout << (odd ? 1 : 2) << '\\\\n';\\n\\t\\t} else {\\n\\t\\t\\tcout << (even ? 2 : 1) << '\\\\n';\\n\\t\\t}\\n\\t}\\n\\treturn 0;\\n}\"",
    "tags": [
      "games",
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1419",
    "index": "B",
    "title": "Stairs",
    "statement": "Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.\n\nA staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $n$ stairs, then it is made of $n$ columns, the first column is $1$ cell high, the second column is $2$ cells high, $\\ldots$, the $n$-th column if $n$ cells high. The lowest cells of all stairs must be in the same row.\n\nA staircase with $n$ stairs is called nice, if it may be covered by $n$ \\textbf{disjoint} squares made of cells. All squares should fully consist of cells of a staircase.\n\n\\begin{center}\nThis is how a nice covered staircase with $7$ stairs looks like:\n\\end{center}\n\nFind out the maximal number of \\textbf{different} nice staircases, that can be built, using no more than $x$ cells, \\textbf{in total}. No cell can be used more than once.",
    "tutorial": "Let's prove, that the minimal amount of squares needed to cover the staircase is not less than $n$, where $n$ is the height of a staircase. To highest cell of each stair is the top left cell of some square. That's why we need at least $n$ squares. You need exactly $n$ squares if and only if the top left cell of each stair is a top left cell of some sqaure. Let's consider a square that covers the lowest cell in the last stair. Its top left corner should contain the highest cell with index $\\frac{n + 1}{2}$ for odd $n$. Then the staircase is divided into 2 staircases, each $\\frac{n - 1}{2}$ stairs high. These staircases should be nice, too. It means that nice staircases are $2^k - 1$ stairs high, where $k \\ge 1$. To maximize the amount of different staircases we should create staircases greedily. If $n$ is even, then we can consider a square that will have the lowest cell of the last stair. The top left corner of this square may not contain any top cells of a staircase, that's why you will need more than $n$ squares. This means that a staircase with an even height may not be nice.",
    "code": "\"#include <bits/stdc++.h>\\n \\nusing namespace std;\\n \\n#define ll long long\\nconst int INF = 2e9 + 1;\\n \\nll getS(ll x) {\\n\\treturn x * (x + 1) / 2;\\t\\n}\\n \\nint main() {\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(0);\\n    cout.tie(0);\\n    int T;\\n    cin >> T;\\n    while (T --> 0) {\\n        ll x;\\n        cin >> x;\\n        int ans = 0;\\n        for (int i = 1; getS((1LL << i) - 1) <= x; i++) {\\n            ans++;\\n            x -= getS((1LL << i) - 1);\\n        }\\n        cout << ans << '\\\\n';\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1419",
    "index": "C",
    "title": "Killjoy",
    "statement": "A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by \\textbf{an integer} (it can possibly be negative or very large).\n\nKilljoy's account is already infected and has a rating equal to $x$. Its rating is constant. There are $n$ accounts except hers, numbered from $1$ to $n$. The $i$-th account's initial rating is $a_i$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.\n\nContests are regularly held on Codeforces. In each contest, any of these $n$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.\n\nFind out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.\n\nIt can be proven that all accounts can be infected in some finite number of contests.",
    "tutorial": "If all $n$ accounts have the rating equal to $x$ then the answer is $0$. Now let's consider other cases. Let's try to make all ratings equal to $x$ in a single contest. It's possible only in two cases: 1. If at least one account is already infected we can infect all other accounts in a single contest. Let's say that some account $i$ is already infected, then we can change all other accounts to $x$ except $i$. Let's say that summary changes are $d$, then we can decrease $i$-th account's rating by $d$ and every account will be infected while the summary changes will be equal to zero. So this will take only $1$ contest. 2. $\\sum\\limits_{i=1}^{n}$ $(a_i - x) = 0$. In this case we can just make all ratings equal $x$ and the sum of all changes will be $0$ because of the equality, which means that we can infect everyone in only $1$ contest. In all other cases the answer is $2$. Let's prove that. We can make the ratings of first $(n-1)$ accounts equal to $x$ after the first contest and the last account will have rating equal to $a_n$ $-$ $\\sum\\limits_{i=1}^{n-1}$ $(a_i - x)$ so that the sum of rating changes is still equal to zero. After that first $(n-1)$ accounts are already infected and we can change the rating of the last account by $d$ so it's equal to $x$ and we will decrease the rating of the first account by $d$ so that the sum of rating changes is still equal to zero. After such two contests all accounts will be infected.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\nsigned main() {\\n    int T;\\n    cin >> T;\\n    while (T --> 0) {\\n        int n, x;\\n        cin >> n >> x;\\n        int cnt = 0;\\n        int sum = 0;\\n        for (int i = 0; i < n; ++i) {\\n            int val;\\n            cin >> val;\\n            cnt += (val == x);\\n            sum += val;\\n        }\\n        if (cnt == n) {\\n        \\tcout << 0 << '\\\\n';\\n        } else if (cnt > 0) {\\n        \\tcout << 1 << '\\\\n';\\n        } else if (sum == n * x) {\\n        \\tcout << 1 << '\\\\n';\\n        } else {\\n        \\tcout << 2 << '\\\\n';\\n        }\\n    }\\n    return 0;\\n}\"",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1419",
    "index": "D2",
    "title": "Sage's Birthday (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in the easy version all prices $a_i$ are different. You can make hacks if and only if you solved both versions of the problem.}\n\nToday is Sage's birthday, and she will go shopping to buy ice spheres. All $n$ ice spheres are placed in a row and they are numbered from $1$ to $n$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.\n\nAn ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.\n\nYou can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.",
    "tutorial": "Let's learn how to check whether it's possible to buy $x$ ice spheres. Let's sort the array $a$ in the non-decreasing order and then take $x$ smallest elements of it. We will suppose that these $x$ ice spheres will be cheap. To make these ice spheres cheap, we need $x+1$ ice spheres more, so let's take $x+1$ most expensive ice spheres. Why it's always good to take $x+1$ most expensive ice spheres? If we had an ice sphere with the price $y$ and we took an ice sphere with price $z \\ge y$ the answer will not become worse. Now we know how to check whether it's possible to buy $x$ ice spheres. If we can buy $x$ ice spheres then it's also possible to buy $x-1$ ice spheres. For that reason the binary search for the answer is working.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(NULL);\\n    cout.tie(NULL);\\n    int n;\\n    cin >> n;\\n    vector<int> a(n);\\n    for (int i = 0; i < n; ++i) {\\n        cin >> a[i];\\n    }\\n    sort(a.begin(), a.end());\\n    int l = 0, r = n + 1;\\n    while (r - l > 1) {\\n        int m = (l + r) / 2;\\n        bool f = true;\\n        if (2 * m + 1 > n) {\\n            f = false;\\n        }\\n        else {\\n            vector<int> b;\\n            int pos_a = 0, pos_b = n - (m + 1);\\n            for (int i = 0; i < 2 * m + 1; ++i) {\\n                if (i % 2 == 0) {\\n                    b.emplace_back(a[pos_b]);\\n                    ++pos_b;\\n                }\\n                else {\\n                    b.emplace_back(a[pos_a]);\\n                    ++pos_a;\\n                }\\n            }\\n            for (int i = 1; i < 2 * m + 1; i += 2) {\\n                if (b[i] >= b[i - 1] || b[i] >= b[i + 1])\\n                    f = false;\\n            }\\n        }\\n        if (f)\\n            l = m;\\n        else\\n            r = m;\\n    }\\n    cout << l << endl;\\n    vector<int> b;\\n    int pos_a = 0, pos_b = n - (l + 1);\\n    for (int i = 0; i < 2 * l + 1; ++i) {\\n        if (i % 2 == 0) {\\n            b.emplace_back(a[pos_b]);\\n            ++pos_b;\\n        }\\n        else {\\n            b.emplace_back(a[pos_a]);\\n            ++pos_a;\\n        }\\n    }\\n    for (int i = pos_a; i < n - (l + 1); ++i) {\\n        b.emplace_back(a[i]);\\n    }\\n    for (auto &c : b) {\\n        cout << c << \\\" \\\";\\n    }\\n}\"",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1419",
    "index": "E",
    "title": "Decryption",
    "statement": "An agent called Cypher is decrypting a message, that contains a composite number $n$. All divisors of $n$, which are greater than $1$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.\n\nIn one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.\n\nA message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.\n\nFind the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.",
    "tutorial": "Let's factorize $n$: $n = p_1^{q_1} \\cdot p_2^{q_2} \\cdot \\dots \\cdot p_k^{q_k}$ If $k = 2$ and $q_1 = q_2 = 1$ (i.e. $n$ is the product of two different prime numbers)Divisors $p_1$ and $p_2$ will definately be adjacent and they are coprime so we should make one operation to insert their lcm between them. After that the circle will be $p_1$, $p_1 \\cdot p_2 = n$, $p_2$, $p_1 \\cdot p_2 = n$ and there will be no such two adjacent numbers that are coprime. The answer is 1. Divisors $p_1$ and $p_2$ will definately be adjacent and they are coprime so we should make one operation to insert their lcm between them. After that the circle will be $p_1$, $p_1 \\cdot p_2 = n$, $p_2$, $p_1 \\cdot p_2 = n$ and there will be no such two adjacent numbers that are coprime. The answer is 1. If $k = 2$ and $q_1 > 1$ or $q_2 > 1$, then we can firstly place numbers $p_1, p_1 \\cdot p_2, p_2, n$. After that we can insert all unused divisors that are multiples of $p_1$ between $p_1$ and $n$, all divisors that are multiples of $p_2$ between $p_2$ and $n$. It is easy to see that in this case the answer is 0. In another case it is possible to arrange the divisors so that there are no such two adjacent numbers that are coprime. Firstly, we need to arrange in a circle these numbers: $p_1$, $p_2$, $p_3$, ..., $p_k$ After that we need to write down the products of these numbers between them: $p_1$, $p_1 \\cdot p_2$, $p_2$, $p_2 \\cdot p_3$, ..., $p_k$, $p_k \\cdot p_1$ From now on we can just place unused numbers that way: insert all unused divisors, that are multiples of $p_1$, after $p_1$, insert all unused divisors, that are multiples of $p_2$, after $p_2$ and so on. If the solution is still unclear you may take a look at the image below. The answer in this case is 0. $p_1$, $p_2$, $p_3$, ..., $p_k$ After that we need to write down the products of these numbers between them: $p_1$, $p_1 \\cdot p_2$, $p_2$, $p_2 \\cdot p_3$, ..., $p_k$, $p_k \\cdot p_1$ From now on we can just place unused numbers that way: insert all unused divisors, that are multiples of $p_1$, after $p_1$, insert all unused divisors, that are multiples of $p_2$, after $p_2$ and so on. If the solution is still unclear you may take a look at the image below. The answer in this case is 0.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n\\nbool prime(int x) {\\n\\tif (x == 2 || x == 3) return true;\\n\\tfor (int i = 2; i * i <= x; ++i) {\\n\\t\\tif (x % i == 0) return false;\\n\\t}\\n\\treturn true;\\n}\\n\\nsigned main() {\\n\\tint T;\\n\\tcin >> T;\\n\\twhile (T --> 0) {\\n\\t\\tint n;\\n\\t\\tcin >> n;\\n\\t\\tvector<int> d;\\n\\t\\tfor (int i = 2; i * i <= n; ++i) {\\n\\t\\t\\tif (n % i == 0) {\\n\\t\\t\\t\\td.emplace_back(i);\\n\\t\\t\\t\\td.emplace_back(n / i);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\td.emplace_back(n);\\n\\t\\tsort(d.begin(), d.end());\\n\\t\\td.resize(unique(d.begin(), d.end()) - d.begin());\\n\\n\\t\\tif (d.size() == 3 && prime(d[0]) && prime(d[1])) {\\n\\t\\t\\tfor (auto x : d) cout << x << ' ';\\n\\t\\t\\tcout << '\\\\n' << 1 << '\\\\n';\\n\\t\\t\\tcontinue;\\n\\t\\t}\\n\\n\\t\\tunordered_map<int, bool> used;\\n\\t\\tvector<int> primes;\\n\\t\\tfor (int i = 2; i * i <= n; ++i) {\\n\\t\\t\\tif (n % i == 0) {\\n\\t\\t\\t\\tprimes.emplace_back(i);\\n\\t\\t\\t\\twhile (n % i == 0) n /= i;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tif (n > 1) primes.emplace_back(n);\\n\\n\\t\\tvector<int> connect(primes.size());\\n\\t\\tfor (int i = 0; i < (int)primes.size(); ++i) {\\n\\t\\t\\tint p = primes[i], q = primes[(i + 1) % primes.size()];\\n\\t\\t\\tfor (int j = 0; j < (int)d.size(); ++j) {\\n\\t\\t\\t\\tif (!used[d[j]] && d[j] % p == 0 && d[j] % q == 0) {\\n\\t\\t\\t\\t\\tused[d[j]] = true;\\n\\t\\t\\t\\t\\tconnect[i] = d[j];\\n\\t\\t\\t\\t\\tbreak;\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\n\\t\\tfor (int i = 0; i < (int)primes.size(); ++i) {\\n\\t\\t\\tint p = primes[i];\\n\\t\\t\\tused[p] = true;\\n\\t\\t\\tcout << p << ' ';\\n\\t\\t\\tfor (int j = 0; j < (int)d.size(); ++j) {\\n\\t\\t\\t\\tif (!used[d[j]] && d[j] % p == 0) {\\n\\t\\t\\t\\t\\tused[d[j]] = true;\\n\\t\\t\\t\\t\\tcout << d[j] << ' ';\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\tif (primes.size() > 1) {\\n\\t\\t\\t\\tcout << connect[i] << ' ';\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tcout << '\\\\n' << 0 << '\\\\n';\\n\\t}\\n\\treturn 0;\\n}\"",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1419",
    "index": "F",
    "title": "Rain of Fire",
    "statement": "There are $n$ detachments on the surface, numbered from $1$ to $n$, the $i$-th detachment is placed in a point with coordinates $(x_i, y_i)$. All detachments are placed in different points.\n\nBrimstone should visit each detachment at least once. You can choose the detachment where Brimstone starts.\n\nTo move from one detachment to another he should first choose one of four directions of movement (up, right, left or down) and then start moving with the constant speed of one unit interval in a second until he comes to a detachment. After he reaches an arbitrary detachment, he can repeat the same process.\n\nEach $t$ seconds an orbital strike covers the whole surface, so at that moment Brimstone should be in a point where some detachment is located. He can stay with any detachment as long as needed.\n\nBrimstone is a good commander, that's why he can create \\textbf{at most one} detachment and place it in any empty point with integer coordinates he wants before his trip. Keep in mind that Brimstone will need to visit this detachment, too.\n\nHelp Brimstone and find such minimal $t$ that it is possible to check each detachment. If there is no such $t$ report about it.",
    "tutorial": "We can consider a graph where vertices are the points (detachments), and there is an edge between two points, if it's possible to move from one point to another. It is possible if these points are on the same line ($x_i = x_j$ or $y_i = y_j$) and the distance between them is $\\le T$. Now we can check, whether current $t$ value is good (whether it is possible to check all detachments). It is easy to see, that it is only possible, when the graph is connected. This means, that we can make a binary search for $t$. Let's now learn how to check, whether it is possible to add at most one point to make the graph connected. If there is $1$ component, then the graph is already connected. If there are $2$ components, then we can search through all such pairs of points, that one point is from the first component, and another point is from the second component. We can connect these points, if they are on one line, and the distance between them is $\\le 2T$ or the differences $|x_1 - x_2| \\le T$ and $y_1 - y_2 \\le T$. If $3$ are three components, then we should consider triples of points. Two of these points should be on the same line. The added point should be on a segment between these two points, and there are $O(n)$ such segments. Now let's search through all such pairs (segment, point) and check whether it is possible to place a point on the segment and connect it with the point from the pair. If there are $4$ components, then you can search trough pairs (segment, segment), so that one segment is horizontal and another one is vertical (they should make a cross). Now we just need to check whether it is possible to connect their intersection point with all 4 endpoints of the segments. If there are more, than $4$ components, then it is not possible to connect them adding only one point, because there are 4 movement directions. If your binary search did not find the answer even for $T = 2 \\cdot 10^9$, then the answer is $-1$, because the maximal distance between any two points is $\\le 2 \\cdot 10^9$.",
    "code": "\"#include<bits/stdc++.h>\\n\\nusing namespace std;\\n\\n#define pb emplace_back\\n#define fi first\\n#define se second\\n#define all(x) (x).begin(), (x).end()\\n#define ll long long\\n#define pii pair<int, int>\\n\\nconst int INF = 2e9 + 1;\\n\\nvector<vector<int>> g;\\nvector<int> usd;\\n\\nvoid dfs(int v, int col) {\\n    usd[v] = col;\\n    for (auto &to : g[v]) {\\n        if (!usd[to]) dfs(to, col);\\n    }\\n}\\n\\nint main(){\\n    cin.tie(0);\\n    cout.tie(0);\\n    ios_base::sync_with_stdio(0);\\n    int n;\\n    cin >> n;\\n    vector<int> x(n), y(n);\\n    for (int i = 0; i < n; i++) cin >> x[i] >> y[i];\\n    map<int, vector<pii>> same_x, same_y;\\n    for (int i = 0; i < n; i++) {\\n        same_x[x[i]].pb(y[i], i);\\n        same_y[y[i]].pb(x[i], i);\\n    }\\n    for (auto &c : same_x) sort(all(c.se));\\n    for (auto &c : same_y) sort(all(c.se));\\n    ll left = -1, right = INF;\\n    while (right - left > 1) {\\n        ll mid = (left + right) / 2;\\n        g.clear();\\n        g.resize(n);\\n        for (auto &c : same_x) {\\n            for (int i = 1; i < (int)c.se.size(); i++) {\\n                if (c.se[i].fi - c.se[i - 1].fi <= mid) {\\n                    g[c.se[i].se].pb(c.se[i - 1].se);\\n                    g[c.se[i - 1].se].pb(c.se[i].se);\\n                }\\n            }\\n        }\\n        for (auto &c : same_y) {\\n            for (int i = 1; i < (int)c.se.size(); i++) {\\n                if (c.se[i].fi - c.se[i - 1].fi <= mid) {\\n                    g[c.se[i].se].pb(c.se[i - 1].se);\\n                    g[c.se[i - 1].se].pb(c.se[i].se);\\n                }\\n            }\\n        }\\n        int cur = 1;\\n        usd.assign(n, 0);\\n        for (int i = 0; i < n; i++) {\\n            if (usd[i]) continue;\\n            dfs(i, cur);\\n            cur++;\\n        }\\n        cur--;\\n        if (cur > 4) {\\n            left = mid;\\n            continue;\\n        }\\n        bool ok = false;\\n        if (cur == 1) {\\n            ok = true;\\n        } else if (cur == 2) {\\n            for (int i = 0; i < n; i++) {\\n                for (int j = i + 1; j < n; j++) {\\n                    if (usd[i] == usd[j]) continue;\\n                    if (x[i] == x[j] && abs(y[i] - y[j]) <= 2 * mid) ok = true;\\n                    if (y[i] == y[j] && abs(x[i] - x[j]) <= 2 * mid) ok = true;\\n                    if (abs(x[i] - x[j]) <= mid && abs(y[i] - y[j]) <= mid) ok = true;\\n                }\\n            }\\n        } else if (cur == 3) {\\n            vector<pii> seg;\\n            for (auto &c : same_x) {\\n                for (int i = 1; i < (int)c.se.size(); i++) {\\n                    if (usd[c.se[i].se] != usd[c.se[i - 1].se]) {\\n                        seg.pb(c.se[i].se, c.se[i - 1].se);\\n                    }\\n                }\\n            }\\n            for (auto &c : same_y) {\\n                for (int i = 1; i < (int)c.se.size(); i++) {\\n                    if (usd[c.se[i].se] != usd[c.se[i - 1].se]) {\\n                        seg.pb(c.se[i].se, c.se[i - 1].se);\\n                    }\\n                }\\n            }\\n            for (auto &c : seg) {\\n                int i = c.fi, j = c.se;\\n                for (int k = 0; k < n; k++) {\\n                    if (usd[k] == usd[i] || usd[k] == usd[j]) continue;\\n                    if (x[i] == x[j]) {\\n                        if (min(y[i], y[j]) >= y[k] || max(y[i], y[j]) <= y[k]) continue;\\n                        if (abs(x[i] - x[k]) > mid) continue;\\n                        if (abs(y[i] - y[k]) <= mid && abs(y[j] - y[k]) <= mid) ok = true;\\n                    } else {\\n                        if (min(x[i], x[j]) >= x[k] || max(x[i], x[j]) <= x[k]) continue;\\n                        if (abs(y[i] - y[k]) > mid) continue;\\n                        if (abs(x[i] - x[k]) <= mid && abs(x[j] - x[k]) <= mid) ok = true;\\n                    }\\n                }\\n            }\\n        } else {\\n            vector<pii> segx, segy;\\n            for (auto &c : same_x) {\\n                for (int i = 1; i < (int)c.se.size(); i++) {\\n                    if (usd[c.se[i].se] != usd[c.se[i - 1].se]) {\\n                        segx.pb(c.se[i].se, c.se[i - 1].se);\\n                    }\\n                }\\n            }\\n            for (auto &c : same_y) {\\n                for (int i = 1; i < (int)c.se.size(); i++) {\\n                    if (usd[c.se[i].se] != usd[c.se[i - 1].se]) {\\n                        segy.pb(c.se[i].se, c.se[i - 1].se);\\n                    }\\n                }\\n            }\\n            for (auto &c : segx) {\\n                for (auto &l : segy) {\\n                    int i = c.fi, j = c.se, k = l.fi, p = l.se;\\n                    if (usd[i] == usd[k] || usd[i] == usd[p] || usd[j] == usd[p] || usd[j] == usd[k]) continue;\\n                    if (min(y[i], y[j]) >= y[k]) continue;\\n                    if (max(y[i], y[j]) <= y[k]) continue;\\n                    if (min(x[k], x[p]) >= x[i]) continue;\\n                    if (max(x[k], x[p]) <= x[i]) continue;\\n                    int x0 = x[i], y0 = y[k];\\n                    if (abs(y[i] - y0) <= mid && abs(y[j] - y0) <= mid && abs(x[p] - x0) <= mid && abs(x[k] - x0) <= mid) ok = true;\\n                }\\n            }\\n        }\\n        if (ok) right = mid;\\n        else left = mid;\\n    }\\n    cout << (right == INF ? -1 : right);\\n    return 0;\\n}\"",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1420",
    "index": "A",
    "title": "Cubes Sorting",
    "statement": "\\begin{quote}\n{{\\small For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it!}}\n\\end{quote}\n\nWheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.\n\nFor completing the chamber Wheatley needs $n$ cubes. $i$-th cube has a volume $a_i$.\n\nWheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $i>1$, $a_{i-1} \\le a_i$ must hold.\n\nTo achieve his goal, Wheatley can exchange two \\textbf{neighbouring} cubes. It means that for any $i>1$ you can exchange cubes on positions $i-1$ and $i$.\n\nBut there is a problem: Wheatley is very impatient. If Wheatley needs more than $\\frac{n \\cdot (n-1)}{2}-1$ exchange operations, he won't do this boring work.\n\nWheatly wants to know: can cubes be sorted under this conditions?",
    "tutorial": "It is not difficult to see that the answer <<NO>> in this task is possible when and only when all $a_i$ are different and sorted in descending order. In this case we need $\\frac{n \\cdot (n-1)}{2}$ operations. Otherwise the answer is always <<YES>>. Why does this solution work? Let's define number of inversions as the number of pairs $1 \\le i < j \\le n$ such as $a_i > a_j$. Note that if the number of inversions is zero, the $a$ array is sorted in non-decreasing order. If the array is not sorted, we can always choose two neighboring elements such that $a_i > a_{i+1}$ and swap them. In this case, the number of inversions is reduced by one. In this case, we cannot reduce the number of inversions by more than one, so it is equal to the minimum number of operations we must perform. Now, all we have to do is notice that the number of inversions does not exceed $\\frac{n(n-1)}2$, and the maximum is only reached when $a_i > a_j$ for all pairs $1 \\le i < j \\le n$. It follows that in this case the array must be strictly descending. Thus, we have a solution with a time of $O(n)$.",
    "code": "#include<iostream>\n\nusing namespace std;\n\nint a[1000000+5];\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin>>t;\n    while (t--)\n    {\n        int n;\n        cin>>n;\n        for (int i=0; i<n; i++)\n        {\n            cin>>a[i];\n        }\n        bool can=false;\n        for (int i=1; i<n; i++)\n        {\n            if (a[i]>=a[i-1])\n            {\n                can=true;\n                break;\n            }\n        }\n        if (can) cout<<\"YES\"<<'\\n';\n        else cout<<\"NO\"<<'\\n';\n    }\n}",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1420",
    "index": "B",
    "title": "Rock and Lever",
    "statement": "\\begin{quote}\n{{\\small \"You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you.\"}}\n\\end{quote}\n\nDanik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.\n\nHermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.\n\nYou are given a positive integer $n$, and an array $a$ of positive integers. The task is to calculate the number of such pairs $(i,j)$ that $i<j$ and $a_i$ $\\&$ $a_j \\ge a_i \\oplus a_j$, where $\\&$ denotes the bitwise AND operation, and $\\oplus$ denotes the bitwise XOR operation.\n\nDanik has solved this task. But can you solve it?",
    "tutorial": "Let's take a pair $(a_i, a_j)$ and see in which case $a_i\\ \\&\\ a_j \\ge a_i \\oplus a_j$ will hold. For this we will follow the bits $a_i$ and $a_j$ from highest to lowest. If we meet two zero bits, the values of $a_i\\ \\&\\ a_j$ and $a_i \\oplus a_j$ will match in this bit, so we move on. If we meet a zero bit in $a_i$ and in $a_j$ -one bit(or vice versa), then we get $a_i\\ \\&\\ a_j < a_i \\oplus a_j$, and we can immediately say that the required condition is false. And if we meet two one bits, then the required condition is fulfilled, e. $a_i\\ \\&\\ a_j > a_i \\oplus a_j$, and then the bits can no longer be considered. Now let's consider the highest one bit in the number of $a_i$ (let it stand at $p_i$ position) and the highest single bit in the number of $a_j$ (let it stand at $p_j$ position). (Here, we consider that the bits are numbered in order of lowest to highest.) Then, $p_i = p_j$ must hold. If $p_i > p_j$, then there is zero in the $a_j$ position and one unit in the $a_i$ position. But then from the reasoning above we get that $a_i\\ \\&\\ a_j < a_i \\oplus a_j$. The case of $p_i < p_j$ is treated in a similar way. It is also easy to see that if $p_i = p_j$ then we automatically get the condition $a_i\\ \\&\\ a_j > a_i \\oplus a_j$. From here the problem is solved. For each number we find the position of the highest one bit $p_i$. Then we need to calculate the number of pairs of numbers, for which $p_i = p_j$. You may notice that the answer is $\\sum\\limits_\\ell \\frac{k_\\ell\\cdot(k_\\ell-1)}2$, where $k_\\ell$ - the number of numbers for which $p_i = p_j$. The complexity of the solution is $O(n)$.",
    "code": "#include<iostream>\n#include<vector>\n#include<algorithm>\n#include<ctime>\n#include<random>\n\nusing namespace std;\n\nmt19937 rnd(time(NULL));\n\nint a[1000000+5];\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin>>t;\n    while (t--)\n    {\n        int n;\n        cin>>n;\n        for (int i=0; i<n; i++)\n        {\n            cin>>a[i];\n        }\n        int64_t ans=0;\n        for (int j=29; j>=0; j--)\n        {\n            int64_t cnt=0;\n            for (int i=0; i<n; i++)\n            {\n                if (a[i]>=(1<<j)&&a[i]<(1<<(j+1)))\n                {\n                    cnt++;\n                }\n            }\n            ans+=cnt*(cnt-1)/2;\n        }\n        cout<<ans<<'\\n';\n    }\n}",
    "tags": [
      "bitmasks",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1420",
    "index": "C1",
    "title": "Pokémon Army (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.}\n\nPikachu is a cute and friendly pokémon living in the wild pikachu herd.\n\nBut it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.\n\nFirst, Andrew counted all the pokémon — there were exactly $n$ pikachu. The strength of the $i$-th pokémon is equal to $a_i$, and all these numbers are distinct.\n\nAs an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $b$ from $k$ indices such that $1 \\le b_1 < b_2 < \\dots < b_k \\le n$, and his army will consist of pokémons with forces $a_{b_1}, a_{b_2}, \\dots, a_{b_k}$.\n\nThe strength of the army is equal to the alternating sum of elements of the subsequence; that is, $a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \\dots$.\n\nAndrew is experimenting with pokémon order. He performs $q$ operations. In $i$-th operation Andrew swaps $l_i$-th and $r_i$-th pokémon.\n\n\\textbf{Note: $q=0$ in this version of the task.}\n\nAndrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.\n\nHelp Andrew and the pokémon, or team R will realize their tricky plan!",
    "tutorial": "The easy version of the task can be solved in different ways. For example, you can use the dynamic programming method. Let $d1_i$ - be the maximum possible sum of a subsequence on a prefix from the first $i$ elements, provided that the length of the subsequence is odd. Similarly enter $d2_i$, only for subsequences of even length. Then $d1_i$ and $d2_i$ are easy to recalculate: $d1_{i+1} = \\max(d1_i,\\ d2_i + a_i),$ $d2_{i+1} = \\max(d2_i,\\ d1_i - a_i).$ This solution works for $O(n)$ in time. Its main drawback is that it cannot be used to solve a complex version of a task where a different approach is needed.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ninline int64_t calc(const vector<int> &a) {\n\tint n = a.size();\n\tvector<int64_t> d1(n+1), d2(n+1);\n\td1[0] = -static_cast<int64_t>(1e18);\n\td2[0] = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\td1[i+1] = max(d1[i], d2[i] + a[i]);\n\t\td2[i+1] = max(d2[i], d1[i] - a[i]);\n\t}\n\treturn max(d1.back(), d2.back());\n}\n\nint main() {\n\tios_base::sync_with_stdio(false);\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tint n, q; cin >> n >> q;\n\t\tvector<int> a(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcin >> a[i];\n\t\t}\n\t\tcout << calc(a) << \"\\n\";\n\t\tfor (int i = 0; i < q; ++i) {\n\t\t\tint l, r; cin >> l >> r; --l; --r;\n\t\t\tswap(a[l], a[r]);\n\t\t\tcout << calc(a) << \"\\n\";\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1420",
    "index": "C2",
    "title": "Pokémon Army (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.}\n\nPikachu is a cute and friendly pokémon living in the wild pikachu herd.\n\nBut it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.\n\nFirst, Andrew counted all the pokémon — there were exactly $n$ pikachu. The strength of the $i$-th pokémon is equal to $a_i$, and all these numbers are distinct.\n\nAs an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array $b$ from $k$ indices such that $1 \\le b_1 < b_2 < \\dots < b_k \\le n$, and his army will consist of pokémons with forces $a_{b_1}, a_{b_2}, \\dots, a_{b_k}$.\n\nThe strength of the army is equal to the alternating sum of elements of the subsequence; that is, $a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + \\dots$.\n\nAndrew is experimenting with pokémon order. He performs $q$ operations. In $i$-th operation Andrew swaps $l_i$-th and $r_i$-th pokémon.\n\nAndrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.\n\nHelp Andrew and the pokémon, or team R will realize their tricky plan!",
    "tutorial": "Let's give a solution for a fixed array and then prove its optimality. Let us name the element $a_i$ a local maximum if $a_i > a_{i-1}$ and $a_i > a_{i+1}$. Similarly let's call the element $a_i$ a local minimum if $a_i < a_{i-1}$ and $a_i < a_{i+1}$. If any of the $a_{i-1}$ or $a_{i+1}$ does not exist in the definitions above, we assume it is equal to $-\\infty$. Note that the optimal subsequence will always be an odd length (otherwise we can delete the last element and increase the response). Elements with odd numbers shall be located at local maximums, and elements with even numbers - at local minimums. It is not difficult to see that the first local maximum is always placed earlier than the first local minimum (otherwise it would happen that the initial permutation decreases from the first element to the local minimum, in which case the first element itself is the local maximum). Similarly, you may notice that the last local maximum always costs later than the last local minimum. Given that the local maximums and minimums alternate, you can simply take a subsequence of all the local maximums and minimums and get the best response. Let's show that this construction is alpways optimal. Let's start with the case when an element with an odd number is not a local maximum. In this case, it shall be replaced with a bigger neighbor, and if the bigger neighbor is already in the sub-set, just delete both of these elements. After that, the response shall always increase. The same shall apply if the even-numbered element is not a local minimum. In this case, it may still happen that we cannot move the element downwards because it is on the edge. But then it is the last one in the subsequence, and it can be easily removed. Thus, it is optimal to take only local highs and lows into the subsequence (considering that highs are on odd positions and lows - on even positions). It remains to be shown that it is profitable to take all local maximums and minimums. Indeed, if not all of them are involved, then there is a pair of standing local highs and lows. By adding them to the subsequence, we will increase the answer. Okay. We know how to solve a problem for an initial array by reducing it to the sum of all local maximums and minimums. We will now learn how to process requests quickly. To do this, we will store whether an element is a local minimum or maximum and recalculate this information when exchanging elements. Suddenly it turns out that a single request will change the state of no more than six elements, so we can easily recalculate the response for $O(1)$ per request. Thus, we have a solution with an asymptotic $O(n + q)$ in time.",
    "code": "#include<iostream>\n\nusing namespace std;\n\n#define int long long\n\nint a[1000000+5];\n\nint n;\n\nint ans=0;\n\ninline void insert(int i)\n{\n    if (i==0||i==n+1) return;\n    if (a[i-1]<a[i]&&a[i]>a[i+1]) ans+=a[i];\n    if (a[i-1]>a[i]&&a[i]<a[i+1]) ans-=a[i];\n}\n\ninline void erase(int i)\n{\n    if (i==0||i==n+1) return;\n    if (a[i-1]<a[i]&&a[i]>a[i+1]) ans-=a[i];\n    if (a[i-1]>a[i]&&a[i]<a[i+1]) ans+=a[i];\n}\n\nint32_t main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin>>t;\n    while (t--)\n    {\n        int q;\n        cin>>n>>q;\n        for (int i=1; i<=n; i++)\n        {\n            cin>>a[i];\n        }\n        a[0]=-1;\n        a[n+1]=-1;\n        ans=0;\n        for (int i=1; i<=n; i++)\n        {\n            if (a[i-1]<a[i]&&a[i]>a[i+1]) ans+=a[i];\n            if (a[i-1]>a[i]&&a[i]<a[i+1]) ans-=a[i];\n        }\n        cout<<ans<<'\\n';\n        while (q--)\n        {\n            int l,r;\n            cin>>l>>r;\n            erase(l-1);\n            erase(l);\n            erase(l+1);\n            if (l!=r)\n            {\n                if (r-1!=l+1&&r-1!=l) erase(r-1);\n                if (r!=l+1) erase(r);\n                erase(r+1);\n            }\n            swap(a[l],a[r]);\n            insert(l-1);\n            insert(l);\n            insert(l+1);\n            if (l!=r)\n            {\n                if (r-1!=l+1&&r-1!=l) insert(r-1);\n                if (r!=l+1) insert(r);\n                insert(r+1);\n            }\n            cout<<ans<<'\\n';\n        }\n    }\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1420",
    "index": "D",
    "title": "Rescue Nibel!",
    "statement": "Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.\n\nOri was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.\n\nThere are $n$ lamps with Spirit Tree's light. Sein knows the time of turning on and off for the $i$-th lamp — $l_i$ and $r_i$ respectively. To open the door you have to choose $k$ lamps in such a way that there will be a moment of time when they all will be turned on.\n\nWhile Sein decides which of the $k$ lamps to pick, Ori is interested: how many ways there are to pick such $k$ lamps that the door will open? It may happen that Sein may be wrong and there are no such $k$ lamps. The answer might be large, so print it modulo $998\\,244\\,353$.",
    "tutorial": "In this task, we need to find the number of sets of $k$ segments such that these $k$ segments intersect at least in one point. Let's look at the starting point of the intersection. This point will always be the beginning of a segment. Let us find the number of sets of segments that their intersection begins at the point $x$. Let us denote $p(x)$ as number of segments that pass through this point, and $s(x)$ as numbers of segments that start at this point. Then all the $k$ segments must pass through $x$ and at least one segment must start at $x$. The number of sets of segments passing through $x$ is ${p(x) \\choose k}$ and the number of sets of segments passing through $x$, none of which starts at $x$, is ${p(x) - s(x) \\choose k}$. From here we obtain that the required number of piece sets is ${p(x) \\choose k}. - {p(x) - s(x) \\choose k}$. By summing up all possible $x$ values, we get the answer to the task. It should be noted that $p(x)$ and $s(x)$ can be easily supported using the event method. Then, the total runtime will be $O(n\\log n)$.",
    "code": "import java.io.*;\nimport java.util.*;\n\npublic class D_Java {\n\tpublic static final int MOD = 998244353;\n\t\n\tpublic static int mul(int a, int b) {\n\t\treturn (int)((long)a * (long)b % MOD);\n\t}\n\t\n\tint[] f;\n\tint[] rf;\n\t\n\tpublic int C(int n, int k) {\n\t\treturn (k < 0 || k > n) ? 0 : mul(f[n], mul(rf[n-k], rf[k]));\n\t}\n\t\n\tpublic static int pow(int a, int n) {\n\t\tint res = 1;\n\t\twhile (n != 0) {\n\t\t\tif ((n & 1) == 1) {\n\t\t\t\tres = mul(res, a);\n\t\t\t}\n\t\t\ta = mul(a, a);\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn res;\n\t}\n\t\n\tstatic void shuffleArray(int[] a) {\n\t\tRandom rnd = new Random();\n\t\tfor (int i = a.length-1; i > 0; i--) {\n\t\t\tint index = rnd.nextInt(i + 1);\n\t\t\tint tmp = a[index];\n\t\t\ta[index] = a[i];\n\t\t\ta[i] = tmp;\n\t\t}\n\t}\n\t\n\tpublic static int inv(int a) {\n\t\treturn pow(a, MOD-2);\n\t}\n\t\n\tpublic void doIt() throws IOException {\n\t\tBufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n\t\t\n\t\tStringTokenizer tok = new StringTokenizer(in.readLine());\n\t\tint n = Integer.parseInt(tok.nextToken());\n\t\tint k = Integer.parseInt(tok.nextToken());\n\t\t\n\t\tf = new int[n+42];\n\t\trf = new int[n+42];\n\t\tf[0] = rf[0] = 1;\n\t\tfor (int i = 1; i < f.length; ++i) {\n\t\t\tf[i] = mul(f[i-1], i);\n\t\t\trf[i] = mul(rf[i-1], inv(i));\n\t\t}\n\t\t\n\t\tint[] events = new int[2*n];\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\ttok = new StringTokenizer(in.readLine());\n\t\t\tint le = Integer.parseInt(tok.nextToken());\n\t\t\tint ri = Integer.parseInt(tok.nextToken());\n\t\t\tevents[i] = le*2;\n\t\t\tevents[i + n] = ri*2 + 1;\n\t\t}\n\t\tshuffleArray(events);\n\t\tArrays.sort(events);\n\t\t\n\t\tint ans = 0;\n\t\tint balance = 0;\n\t\tfor (int r = 0; r < 2*n;) {\n\t\t\tint l = r;\n\t\t\twhile (r < 2*n && events[l] == events[r]) {\n\t\t\t\t++r;\n\t\t\t}\n\t\t\tint added = r - l;\n\t\t\tif (events[l] % 2 == 0) {\n\t\t\t\t// Open event\n\t\t\t\tans += C(balance + added, k);\n\t\t\t\tif (ans >= MOD) ans -= MOD;\n\t\t\t\tans += MOD - C(balance, k);\n\t\t\t\tif (ans >= MOD) ans -= MOD;\n\t\t\t\tbalance += added;\n\t\t\t} else {\n\t\t\t\t// Close event\n\t\t\t\tbalance -= added;\n\t\t\t}\n\t\t}\n\t\t\n\t\tin.close();\n\t\tSystem.out.println(ans);\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException {\n\t\t(new D_Java()).doIt();\n\t}\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1420",
    "index": "E",
    "title": "Battle Lemmings",
    "statement": "A lighthouse keeper Peter commands an army of $n$ battle lemmings. He ordered his army to stand in a line and numbered the lemmings from $1$ to $n$ from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield.\n\nThe more protected Peter's army is, the better. To calculate the protection of the army, he finds the number of protected pairs of lemmings, that is such pairs that both lemmings in the pair don't hold a shield, but there is a lemming with a shield between them.\n\nNow it's time to prepare for defence and increase the protection of the army. To do this, Peter can give orders. He chooses a lemming with a shield and gives him one of the two orders:\n\n- give the shield to the left neighbor if it exists and doesn't have a shield;\n- give the shield to the right neighbor if it exists and doesn't have a shield.\n\nIn one second Peter can give exactly one order.\n\nIt's not clear how much time Peter has before the defence. So he decided to determine the maximal value of army protection for each $k$ from $0$ to $\\frac{n(n-1)}2$, if he gives no more that $k$ orders. Help Peter to calculate it!",
    "tutorial": "First, let us denote $f(A)$ as a conversion of the original sequence of $A$. In the beginning, we will write down the number of zeros before the the first one. Then, we write down the number of zeros standing between the first and second ones, then - between the second and third ones, and so on. For example, $f(011000101100) = \\{1, 0, 3, 1, 0, 2\\}$, because there is one zero before the first one, there are no zeros between the first and second ones, there are three zeros between the second and third ones, etc. d. It is not difficult to see that the original sequence $A$ can be unambiguously recovered with $f(A)$. Now, let us consider how $f(A)$ will change if we change two different adjacent elements in the original $A$ sequence. In this case, two neighboring numbers will change in $f(A)$, one of which will decrease by one and the other - will increase by one. The reversed statement is also true: if we choose two neighboring numbers in $f(A)$, one of them will increase by one, and the other - will decrease by one so that they both remain non-negative, this operation will correspond to an exchange of two neighboring elements in $A$. Let us name this operation (choosing two neighboring numbers, increasing one of them by one and reducing the other by one). pouring. Let us consider such a task. We have two arrays $A = \\{a_1, a_2, \\dots, a_k\\}$ and $B = \\{b_1, b_2, \\dots, b_k\\}$. We have to calculate the minimum amount of pouring operations we can turn $A$ into $B$. (Obviously, the sum of the numbers in $A$ and in $B$ must be the same.) To solve this, let's try to split the array into two \"barriers\", standing after $i$-th position. Then, the $A$ array is split into two parts: the left (elements from $1$ to $i$) and the right (elements from $i+1$ to $n$). For the left part of the $A$ array to have the same number of elements as in $B$, you need $g_{A, B}(i) = \\left|\\sum_{j=1}^{i} a_i - \\sum_{j=1}^i b_i\\right|$ pouring operations involving $i$ and $i+1$ elements. To sum up the number of necessary pouring operations for each pair of neighboring elements, you have to sum $g_{A,B}(i)$ for all $i$ from $1$ to $n-1$. It can be shown that the sum obtained will be the required number of pouring operations, because since it is equal to zero only in case of equal arrays, and each pouring operation will reduce it by no more than $1$ (and there is always a transfusion that reduces this sum by $1$). So, this subtask has been sorted out, let's move on. We have to learn how to read security for the sequence $A$, knowing $f(A) = \\{f_1, f_2, \\dots, f_k\\}$. It is not difficult to see that it is equal to $p(A) = \\sum_{1 \\le i < j \\le k} f_i\\cdot f_j = \\frac 12 \\left( \\sum_{1 \\le i, j \\le k} f_i\\cdot f_j - \\sum_{i=1}^k f_i^2 \\right) = \\frac 12 \\left( \\left(\\sum_{i=1}^k f_i \\right)^2 - \\sum_{i=1}^k f_i^2 \\right).$ Now we can finally get down to the task. To do this, let's try to build an optimal sequence of $f(A) = \\{f_1, f_2, \\dots, f_k\\}$ by applying no more than $k$ of transfusions. Of course, we need to use the dynamic programming of $dp_{i,\\ s,\\ k}$. This means that we have looked at the first $i$ elements in $f(A)$ and done with $k$ pouring operations so that $\\sum_{i=1}^k f_i$ equals $s$. The DP itself will store the minimum possible value of $\\sum_{i=1}^k f_i^2$. To get the answer we need to refer to $dp_{i,\\ c_0,\\ k}$ where $c_0$ - is the number of zeros in the original sequence. And to recalculate the dynamics of $dp_{i,\\ s,\\ k}$ we have to go through what $f_{i+1}$ will be as a result. Let it be $h$. Then, the answer recovery happens in the following way: $dp_{i+1,\\ s + h,\\ k + \\left|z_i - (s + h)\\right|} \\text{min=} dp_{i,\\ s,\\ k} + h^2.$ Here $z_i$ denotes $\\sum_{j=1}^i f_i$ in the original sequence $f(A)$. The total asymptotic is $O(n^5)$ in time and $O(n^4)$ in memory, although with a correct implementation the constant is very small (the author's solution works for $\\frac{n^5}{27}$). In this task, there are solutions for $O(n^4\\log n)$, but I will not describe them here.",
    "code": "#include <cassert>\n#include <climits>\n#include <iostream>\n#include <vector>\n#include <numeric>\n\nusing namespace std;\n\ntemplate<typename T>\ninline void umin(T &a, const T &b) {\n\ta = min(a, b);\n}\n\ntemplate<typename T>\ninline void umax(T &a, const T &b) {\n\ta = max(a, b);\n}\n\nint main() {\n\tios_base::sync_with_stdio(false);\n\t\n\tint n; cin >> n;\n\tvector<int> a(n);\n\tfor (int &x : a) {\n\t\tcin >> x;\n\t}\n\ta.push_back(1);\n\t\n\tvector<int> gg;\n\tfor (int i = 0; i <= n; ++i) {\n\t\tint s = i;\n\t\twhile (a[i] == 0) ++i;\n\t\tgg.push_back(i - s);\n\t}\n\t\n\tvector<int> p = gg;\n\tpartial_sum(begin(p), end(p), begin(p));\n\t\n\tconstexpr int mx = 103;\n\tconstexpr int dx = mx + 1, dy = mx + 1, dz = mx * (mx + 1) / 2 + 1;\n\tstatic int dp[dx][dy][dz] = {};\n\t\n\tfor (int i = 0; i < dx; ++i) {\n\t\tfor (int j = 0; j < dy; ++j) {\n\t\t\tfor (int k = 0; k < dz; ++k) {\n\t\t\t\tdp[i][j][k] = INT_MAX;\n\t\t\t}\n\t\t}\n\t}\n\tdp[0][0][0] = 0;\n\t\n\tint k = gg.size(), l = p.back();\n\tfor (int i = 0; i < k; ++i) {\n\t\tfor (int j = 0; j <= l; ++j) {\n\t\t\tfor (int s = 0; s <= n * (n-1) / 2; ++s) {\n\t\t\t\tif (dp[i][j][s] == INT_MAX) continue;\n\t\t\t\tfor (int q = j; q <= l; ++q) {\n\t\t\t\t\tumin(dp[i+1][q][s + abs(q - p[i])], dp[i][j][s] + (q-j)*(q-j));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint mn = INT_MAX;\n\tfor (int s = 0; s <= n * (n-1) / 2; ++s) {\n\t\tumin(mn, dp[k][l][s]);\n\t\tint val = l*l - mn;\n\t\tassert(val % 2 == 0);\n\t\tcout << val/2 << \" \";\n\t}\n\tcout << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1421",
    "index": "A",
    "title": "XORwice",
    "statement": "In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.\n\nTzuyu gave Sana two integers $a$ and $b$ and a really important quest.\n\nIn order to complete the quest, Sana has to output the smallest possible value of ($a \\oplus x$) + ($b \\oplus x$) for any given $x$, where $\\oplus$ denotes the bitwise XOR operation.",
    "tutorial": "Think about addition in base two. Say $a$ = $10101$ and $b$ = $1001$. What your operation does is it modifies the bits in your numbers, so if the first bit in $a$ is $1$ and the first bit in $b$ is $1$ (as is the case above) you can make both $0$ by making that bit $1$ in $x$. This is actually the only way you can decrease the resulting sum, so $x$ = $1$ is an answer above. Noticing the hint above we now deduce $x$ = $a$ & $b$ where & is bitwise $AND$. So just printing ($a$ $\\oplus$ ($a$ & $b$)) + ($b$ $\\oplus$ ($a$ & $b$)) works, but there's an even nicer formula. We'll leave it up to you to prove that ($a$ $\\oplus$ ($a$ & $b$)) + ($b$ $\\oplus$ ($a$ & $b$)) = $a$ $\\oplus$ $b$, where $\\oplus$ is the bitwise $XOR$ :)",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1421",
    "index": "B",
    "title": "Putting Bricks in the Wall",
    "statement": "Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like walls, he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.\n\nRoger Waters has a square grid of size $n\\times n$ and he wants to traverse his grid from the upper left ($1,1$) corner to the lower right corner ($n,n$). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells ($1,1$) and ($n,n$) every cell has a value $0$ or $1$ in it.\n\nBefore starting his traversal he will pick either a $0$ or a $1$ and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells ($1,1$) and ($n,n$) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell ($1,1$) takes value the letter 'S' and the cell ($n,n$) takes value the letter 'F'.\n\nFor example, in the first example test case, he can go from ($1, 1$) to ($n, n$) by using the zeroes on this path: ($1, 1$), ($2, 1$), ($2, 2$), ($2, 3$), ($3, 3$), ($3, 4$), ($4, 4$)\n\nThe rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will \\textbf{invert at most two cells} in the grid (from $0$ to $1$ or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. \\textbf{Note that you cannot invert cells $(1, 1)$ and $(n, n)$}.\n\nWe can show that there always exists a solution for the given constraints.\n\nAlso note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach ($n,n$) no matter what digit he picks.",
    "tutorial": "It's hard to use the two valuable switches somewhere in the middle of the matrix, a much wiser choice would be to somehow block the $S$ cell or the $F$ cell. Perhaps you can set both neighbours of $S$ to $1$ to force Roger to pick $1$. If we pick the neighbours of $S$ to be $1$ we can make the neighbours of $F$ $0$ and there would be no way to go from $S$ to $F$. But this requires in the worst case $4$ switches, which is not good enough. Luckily, in order to get down to $2$ switches we only have to consider the other way around, making the squares neighboring $S$ become $0$ and the squares neighboring $F$ $1$. There must be a solution of the two with at most two switches and you won't get from $S$ to $F$ since you're forced to pick $1$ (or $0$) and can't get past the neighbours of $F$ which are opposite.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1421",
    "index": "C",
    "title": "Palindromifier",
    "statement": "Ringo found a string $s$ of length $n$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $s$ into a palindrome by applying two types of operations to the string.\n\nThe first operation allows him to choose $i$ ($2 \\le i \\le n-1$) and to append the substring $s_2s_3 \\ldots s_i$ ($i - 1$ characters) reversed to the front of $s$.\n\nThe second operation allows him to choose $i$ ($2 \\le i \\le n-1$) and to append the substring $s_i s_{i + 1}\\ldots s_{n - 1}$ ($n - i$ characters) reversed to the end of $s$.\n\nNote that characters in the string in this problem are indexed from $1$.\n\nFor example suppose $s=$abcdef. If he performs the first operation with $i=3$ then he appends cb to the front of $s$ and the result will be cbabcdef. Performing the second operation on the resulted string with $i=5$ will yield cbabcdefedc.\n\nYour task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) \\textbf{at most $30$ times}. \\textbf{The length of the resulting palindrome must not exceed $10^6$}\n\nIt is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.",
    "tutorial": "You're not allowed to just pick the whole string and append its reversed result to the front, but what's the next best thing? We're very close to the answer if we take the whole string except for a letter (so for $abcde$ we make $dcbabcde$). The operation above which transformed $abcde$ into $dcbabcde$ is very close, if only we could've somehow append $e$ to the left. Turns out you can set that up, so from $abcde$ first append $d$ to the end, then you have $abcded$. Now apply the operation from the hint on this string and get $edcbabcded$. See why we added that $d$ first? We can now append it to the front just like we wanted!. Do the operation $L$ $2$ and the job is finished. Yep, amazingly just printing $R$ $n-1$ $L$ $n$ $L$ $2$ works!",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1421",
    "index": "D",
    "title": "Hexagons",
    "statement": "Lindsey Buckingham told Stevie Nicks \"Go your own way\". Nicks is now sad and wants to go away as quickly as possible, but she lives in a 2D hexagonal world.\n\nConsider a hexagonal tiling of the plane as on the picture below.\n\nNicks wishes to go from the cell marked $(0, 0)$ to a certain cell given by the coordinates. She may go from a hexagon to any of its six neighbors you want, but there is a cost associated with each of them. The costs depend only on the direction in which you travel. Going from $(0, 0)$ to $(1, 1)$ will take the exact same cost as going from $(-2, -1)$ to $(-1, 0)$. The costs are given in the input in the order $c_1$, $c_2$, $c_3$, $c_4$, $c_5$, $c_6$ as in the picture below.\n\nPrint the smallest cost of a path from the origin which has coordinates $(0, 0)$ to the given cell.",
    "tutorial": "Using too many edges in the solution feels wasteful, the solution surely has some neat line as straight as possible. Perhaps we can prove only two edges are required? Indeed two edges are required in the solution, so one approach would be picking all combinations of edges and do linear algebra so see how many times each is required (or if it's impossible). To prove that let's suppose our target is somewhere reachable by only taking $C1$ and $C2$ (the upper right sextant, a sixth division of the plane). $C4$ and $C5$ will never be used since they contribute in the wrong direction. We can now use $C6$, $C1$, $C2$ or $C3$ for our solution. If using $C1$ and $C2$ is not optimal we can choose $C3$ or $C6$, without loss of generality we choose $C3$. $C6$ cannot be used because it simply counters $C3$. Now we either use $C1$, $C2$ or $C3$, but we can further narrow down to just two edges. If we use all three this means we use $C1$ + $C3$ which goes the same way as $C2$, and $C2$ also goes the same way as $C1$ + $C3$. So we can just not use $C2$ if $C1$ + $C3$ < $C2$, or use $C2$ instead of $C1$ + $C3$ until either of $C1$ or $C3$ doesn't appear anymore on our solution.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1421",
    "index": "E",
    "title": "Swedish Heroes",
    "statement": "While playing yet another strategy game, Mans has recruited $n$ Swedish heroes, whose powers which can be represented as an array $a$.\n\nUnfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to accomplish his goal, he can pick two consecutive heroes, with powers $a_i$ and $a_{i+1}$, remove them and insert a hero with power $-(a_i+a_{i+1})$ back in the same position.\n\nFor example if the array contains the elements $[5, 6, 7, 8]$, he can pick $6$ and $7$ and get $[5, -(6+7), 8] = [5, -13, 8]$.\n\nAfter he will perform this operation $n-1$ times, Mans will end up having only one hero. He wants his power to be as big as possible. What's the largest possible power he can achieve?",
    "tutorial": "The problem gives us an array and we have to come up with an achievable sequence of pluses and minuses such that summing the numbers after applying the signs we get the largest sum. Intuitively we can probably assign $+$ to most positive numbers and - to most negative numbers somehow, but we should investigate exactly which are possible. Before you try to find patterns you should observe that there is one case that is impossible to reach. You cannot assign alternating + and - to the array, like $+-+-+-+-$ or $-+-+-+-+$. The reason is very simple, the very first thing you do is apply the operation on two consecutive numbers and make them both $--$, and whenever you apply further operations on the both of them they remain the same sign. In the end we decided to give this in the samples but we know from testing many would miss this case. In order to explain the solution we will add some notations: $n$ = the length of the array. $m$ = the number of elements we multiply by $-1$ in the solution (put - in front of them). $p$ = the number of elements we do not multiply by $-1$ in the solution (put $+$ in front of them). The mysterious pattern is as follows: ($n$ $+$ $m$) % $3$ = $1$ So yes, for $n$ = $7$ for example we can put $3$ minus signs anywhere, like $++--+-+$, or $6$ minus signs like $--+----$ or full plus signs $+++++++$. We can arrange the pluses and minuses however we want as long as there are $2$ consecutive equal signs and ($n$ $+$ $m$) % $3$ = $1$. The solution now simply requires us to sort the array and multiply by $-1$ each number one by one and when ($n$ $+$ $m$) % $3$ = $1$ update the answer with the current sum. Of course there is one point where all the elements might form the forbidden $+-+-+-$ so you should check that in that case they do not, or if they do pick the next smallest number to turn into - instead of the last one. So for the sample $[4, -5, 9, -2, 1]$ you sort and get $[-5, -2, 1, 4, 9]$ and when you turn $-5$ into $5$ instead of turning $-2$ into $2$ you turn $1$ into $-1$ and the array will be $[5, -2, -1, 4, 9]$. After that undo your modification, turn $-2$ into $2$ and revert $-1$ to $1$. The proof can be done via induction, but I will try to explain why this happens. Suppose your solution looks like $+--+---+$. What we need to do is to split into two substrings such that their negation is achievable and we are done, they will concatenate and reverse each sign. So we can split into ($+--$) and ($+---+$) and notice that their negations are ($-++$) and ($-+++-$) which are achievable (($n$ $+$ $m$) % $3$ = $1$ for both and are not alternating). We can always find such a split, start at the left-most point and see if you can split into ($+$) and ($--+---+$). You can't, the negation of ($+$) is just ($-$) which you can't have. Splitting into ($+-$) and ($+---+$) won't do either for the same reasons, but ($+--$) and ($+---+$) work, actually if the left substring starts with a $+$ the very first time the last two signs are equal is a time where we can make the split, something like ($+-+-++$) when reversed will always have ($n$ $+$ $m$) % $3$ = $1$. So now you see even clearer why the corner case $+-+-+$ exists, you can never split it into two substrings where the last two signs of the first substring are equal.",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1422",
    "index": "A",
    "title": "Fence",
    "statement": "Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $a$, $b$, and $c$. Now he needs to find out some possible integer length $d$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $a$, $b$, $c$, and $d$. Help Yura, find any possible length of the fourth side.\n\nA non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.",
    "tutorial": "A quadrilateral can be built when $max (a, b, c, d) < a + b + c + d - max (a, b, c, d)$, that is, the sum of the minimum three numbers is greater than the maximum. To do this, you could choose $max (a, b, c)$ or $a + b + c - 1$ as $d$.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())\n#define sz(v) ((int)(v).size())\n \n#define vec1d(x) vector<x>\n#define vec2d(x) vector<vec1d(x)>\n#define vec3d(x) vector<vec2d(x)>\n#define vec4d(x) vector<vec3d(x)>\n \n#define ivec1d(x, n, v) vec1d(x)(n, v)\n#define ivec2d(x, n, m, v) vec2d(x)(n, ivec1d(x, m, v))\n#define ivec3d(x, n, m, k, v) vec3d(x)(n, ivec2d(x, m, k, v))\n#define ivec4d(x, n, m, k, l, v) vec4d(x)(n, ivec3d(x, m, k, l, v))\n \n#ifdef LOCAL\n#include \"pretty_print.h\"\n#define dbg(...) cerr << \"[\" << #__VA_ARGS__ << \"]: \", debug_out(__VA_ARGS__)\n#else\n#define dbg(...) 42\n#endif\n \n#define nl \"\\n\"\n \ntypedef long double ld;\ntypedef long long ll;\ntypedef unsigned long long ull;\n \ntemplate <typename T> T sqr(T x) { return x * x; }\ntemplate <typename T> T abs(T x) { return x < 0? -x : x; }\ntemplate <typename T> T gcd(T a, T b) { return b? gcd(b, a % b) : a; }\ntemplate <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }\ntemplate <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }\n \nauto random_address = [] { char *p = new char; delete p; return (uint64_t) p; };\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\nmt19937_64 rngll(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\n \n \nint main(int /* argc */, char** /* argv */)\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n#ifdef LOCAL\n    assert(freopen(\"i.txt\", \"r\", stdin));\n    assert(freopen(\"o.txt\", \"w\", stdout));\n#endif\n \n    int t;\n    cin >> t;\n    while (t--) {\n        int a, b, c;\n        cin >> a >> b >> c;\n        if (a > b) {\n            swap(a, b);\n        }\n        if (b > c) {\n            swap(b, c);\n        }\n        cout << max(1, c - a - b + 1) << nl;\n    }\n \n#ifdef LOCAL\n    cerr << \"Time execute: \" << clock() / (double)CLOCKS_PER_SEC << \" sec\" << endl;\n#endif\n    return 0;\n}",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1422",
    "index": "B",
    "title": "Nice Matrix",
    "statement": "A matrix of size $n \\times m$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $(a_1, a_2, \\dots , a_k)$ is a palindrome, if for any integer $i$ ($1 \\le i \\le k$) the equality $a_i = a_{k - i + 1}$ holds.\n\nSasha owns a matrix $a$ of size $n \\times m$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.\n\nHelp him!",
    "tutorial": "Note, that if the value of $a_{1, 1}$ is equal to some number $x$, then values of $a_{n, 1}$, $a_{1, m}$ and $a_{n, m}$ must also be equal to this number $x$ by the palindrome property. A similar property holds for all of the following elements $a_{x, y}$ ($a_{x, y}=a_{n - x + 1, y}=a_{1,m - y + 1}=a_{n - x + 1, m - y + 1}$), so the problem is reduced to finding the optimal number for each four of numbers (maybe less for some positions in matrix). This number is the median of these numbers (the average of the sorted set). The answer will be the sum of the differences between the median of the \"four\" and each number in the \"four\" for all \"fours\".",
    "code": "#include <bits/stdc++.h>\n \n#define fi first\n#define se second\n#define m_p make_pair\n#define endl '\\n'\n#define fast_io ios_base::sync_with_stdio(0); cin.tie(0)\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int MAXN = 412345;\nconst int MAXINT = 2047483098;\nconst ll MOD = 1e9 + 7;\nconst int MAX = 1e4;\n \nconst long double EPS = 1e-10;\n \nlong long calcAnswer(vector <long long> &numbers) {\n    sort(begin(numbers), end(numbers));\n    long long result = 0;\n    \n    int sz = numbers.size();\n    for (int i = 0; i < sz; ++i) result += abs(numbers[i] - numbers[sz / 2]);\n    return result;\n}\n \nvoid solve() {\n     int n, m;\n \n    cin >> n >> m;\n    vector <vector <long long> > matrix(n);\n    for (int i = 0; i < n; ++i) {\n        matrix[i].resize(m);\n        for (int j = 0; j < m; ++j) cin >> matrix[i][j];\n    }\n \n    long long answer = 0;\n \n    int left_row = 0, right_row = n - 1;\n    while(left_row <= right_row) {\n        int left_column = 0, right_column = m - 1;\n        while(left_column <= right_column) {\n            vector <long long> cur_numbers = {matrix[left_row][left_column]};\n            if (left_row != right_row) cur_numbers.push_back(matrix[right_row][left_column]);\n            if (right_column != left_column) cur_numbers.push_back(matrix[left_row][right_column]);\n            if (left_column != right_column && left_row != right_row) cur_numbers.push_back(matrix[right_row][right_column]);\n            \n            answer += calcAnswer(cur_numbers);\n \n            left_column++, right_column--;\n        }\n \n        left_row++, right_row--;\n    }\n \n    cout << answer << endl;\n \n}\n \nint main()\n{\n    fast_io;\n    \n    int T;\n    cin >> T;\n    while(T--) {\n        solve();\n    }\n   \n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1422",
    "index": "C",
    "title": "Bargain",
    "statement": "Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price $n$, Vova removes a non-empty substring of (consecutive) digits from the price, the remaining digits close the gap, and the resulting integer is the price.\n\nFor example, is Sasha names $1213121$, Vova can remove the substring $1312$, and the result is $121$.\n\nIt is allowed for result to contain leading zeros. If Vova removes all digits, the price is considered to be $0$.\n\nSasha wants to come up with some constraints so that Vova can't just remove all digits, but he needs some arguments supporting the constraints. To start with, he wants to compute the sum of all possible resulting prices after Vova's move.\n\nHelp Sasha to compute this sum. Since the answer can be very large, print it modulo $10^9 + 7$.",
    "tutorial": "Let's count for each digit how many times it will be included in the final sum and in what place. Let's denote $m$ as the length of the number $n$. Consider the digit $a_i$ at the position $i$ in the number $n$ ($1 \\le i \\le m$). If some part of the number to the left of the digit is removed, then the current digit will remain in its place - and we add the number of ways to remove the subsegment to the left to the answer multiplied by the current digit $i * (i - 1) / 2 \\times 10 ^ {m - i} \\times a_i$. If the segment to the right is deleted, then the place of the digit will change - $(j + 1) \\times 10^j \\times a_i$ for all $0 \\le j < m - i$, or $\\sum_ {j = 0 }^{m - i - 1} {(j + 1) \\times 10 ^ j} \\times a_i$. The $j$ sum can be pre-calculated for all values.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())\n#define sz(v) ((int)(v).size())\n \n#define vec1d(x) vector<x>\n#define vec2d(x) vector<vec1d(x)>\n#define vec3d(x) vector<vec2d(x)>\n#define vec4d(x) vector<vec3d(x)>\n \n#define ivec1d(x, n, v) vec1d(x)(n, v)\n#define ivec2d(x, n, m, v) vec2d(x)(n, ivec1d(x, m, v))\n#define ivec3d(x, n, m, k, v) vec3d(x)(n, ivec2d(x, m, k, v))\n#define ivec4d(x, n, m, k, l, v) vec4d(x)(n, ivec3d(x, m, k, l, v))\n \n#ifdef LOCAL\n#include \"pretty_print.h\"\n#define dbg(...) cerr << \"[\" << #__VA_ARGS__ << \"]: \", debug_out(__VA_ARGS__)\n#else\n#define dbg(...) 42\n#endif\n \n#define nl \"\\n\"\n \ntypedef long double ld;\ntypedef long long ll;\ntypedef unsigned long long ull;\n \ntemplate <typename T> T sqr(T x) { return x * x; }\ntemplate <typename T> T abs(T x) { return x < 0? -x : x; }\ntemplate <typename T> T gcd(T a, T b) { return b? gcd(b, a % b) : a; }\ntemplate <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }\ntemplate <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }\n \nauto random_address = [] { char *p = new char; delete p; return (uint64_t) p; };\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\nmt19937_64 rngll(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\n \n \nint main(int /* argc */, char** /* argv */)\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n#ifdef LOCAL\n    assert(freopen(\"i.txt\", \"r\", stdin));\n    assert(freopen(\"o.txt\", \"w\", stdout));\n#endif\n \n    string s;\n    cin >> s;\n \n    int n = s.size();\n    vector<ll> a(n);\n    for (int i = 0; i < n; ++i) {\n        a[i] = s[i] - '0';\n    }\n \n    const int MOD = (int)1e+9 + 7;\n \n    ll ans = 0;\n    ll sum = 0;\n    ll p = 1;\n \n    for (ll i = n - 1; i >= 0; --i) {\n        ll k = (i * (i + 1) / 2 % MOD * p % MOD + sum) % MOD;\n        sum = (sum + p * (n - i) % MOD) % MOD;\n        p = p * 10 % MOD;\n        ans = (ans + a[i] * k % MOD) % MOD;\n    }\n \n    cout << ans << endl;\n \n#ifdef LOCAL\n    cerr << \"Time execute: \" << clock() / (double)CLOCKS_PER_SEC << \" sec\" << endl;\n#endif\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1422",
    "index": "D",
    "title": "Returning Home",
    "statement": "Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.\n\nLet's represent the city as an area of $n \\times n$ square blocks. Yura needs to move from the block with coordinates $(s_x,s_y)$ to the block with coordinates $(f_x,f_y)$. In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are $m$ instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate $x$ or with the same coordinate $y$ as the location.\n\nHelp Yura to find the smallest time needed to get home.",
    "tutorial": "You can build a graph with vertices at the start point and all fast travel points. The distance between the vertices $(x_1, y_1)$ and $(x_2, y_2)$ is calculated as $min (|x_1 - x_2|, |y_1 - y_2|)$. To avoid drawing all $m * (m + 1) / 2$ edges in the graph, note that for a pair of points $(x_1, y_1)$ and $(x_2, y_2)$ such that $|x_1 - x_2| \\le |y_1 - y_2|$, if there is a point with coordinate $x_3$ such that it is between $x_1$ and $x_2$ ($min (x_1, x_2) \\le x_3 \\le max (x_1, x_2)$), then the distance between the first and second point will be equal to the sum of the distances between the first and third and between the third and second. In this case, the edge between the first and second points does not need to be drawn - it will be unnecessary. It turns out that for each point of the graph it will be enough to draw the edges to the points nearest along the $x$ axis in both directions. Similarly for $y$. Next, in the constructed graph, we find the minimum distance from the starting point to each point of the graph $(x, y)$ and sum it up with the distance to the end point $(f_x, f_y)$, which is equal to $|x - f_x| + |y - f_y|$. Among all the distances, we choose the minimum one.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())\n#define sz(v) ((int)(v).size())\n \n#define vec1d(x) vector<x>\n#define vec2d(x) vector<vec1d(x)>\n#define vec3d(x) vector<vec2d(x)>\n#define vec4d(x) vector<vec3d(x)>\n \n#define ivec1d(x, n, v) vec1d(x)(n, v)\n#define ivec2d(x, n, m, v) vec2d(x)(n, ivec1d(x, m, v))\n#define ivec3d(x, n, m, k, v) vec3d(x)(n, ivec2d(x, m, k, v))\n#define ivec4d(x, n, m, k, l, v) vec4d(x)(n, ivec3d(x, m, k, l, v))\n \n#ifdef LOCAL\n#include \"pretty_print.h\"\n#define dbg(...) cerr << \"[\" << #__VA_ARGS__ << \"]: \", debug_out(__VA_ARGS__)\n#else\n#define dbg(...) 42\n#endif\n \n#define nl \"\\n\"\n \ntypedef long double ld;\ntypedef long long ll;\ntypedef unsigned long long ull;\n \ntemplate <typename T> T sqr(T x) { return x * x; }\ntemplate <typename T> T abs(T x) { return x < 0? -x : x; }\ntemplate <typename T> T gcd(T a, T b) { return b? gcd(b, a % b) : a; }\ntemplate <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }\ntemplate <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }\n \nauto random_address = [] { char *p = new char; delete p; return (uint64_t) p; };\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\nmt19937_64 rngll(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\n \n \nint main(int /* argc */, char** /* argv */)\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n#ifdef LOCAL\n    assert(freopen(\"i.txt\", \"r\", stdin));\n    assert(freopen(\"o.txt\", \"w\", stdout));\n#endif\n \n    int _, n;\n    cin >> _ >> n;\n    int sx, sy, fx, fy;\n    cin >> sx >> sy >> fx >> fy;\n    vector<pair<int, int>> p(n);\n    vector<tuple<int, int, int>> a(n), b(n);\n    for (int i = 0; i < n; ++i) {\n        int x, y;\n        cin >> x >> y;\n        p[i] = {x, y};\n        a[i] = make_tuple(x, y, i);\n        b[i] = make_tuple(y, x, i);\n    }\n \n    vector<vector<pair<int, int>>> e(n);\n    for (auto& s : vector{a, b}) {\n        sort(all(s));\n        for (int i = 1; i < n; ++i) {\n            auto [x1, y1, u] = s[i - 1];\n            auto [x2, y2, v] = s[i];\n            int d = min(abs(x1 - x2), abs(y1 - y2));\n            e[u].push_back({v, d});\n            e[v].push_back({u, d});\n        }\n    }\n \n    priority_queue<pair<ll, int>> h;\n    vector<ll> d(n);\n    for (int i = 0; i < n; ++i) {\n        d[i] = min(abs(sx - p[i].first), abs(sy - p[i].second));\n        h.push({-d[i], i});\n    }\n \n    while (h.size()) {\n        int x;\n        ll w;\n        tie(w, x) = h.top();\n        h.pop();\n        w = -w;\n        if (d[x] != w) {\n            continue;\n        }\n        for (auto& [y, c] : e[x]) {\n            if (chmin(d[y], w + c)) {\n                h.push({-d[y], y});\n            }\n        }\n    }\n \n    ll ans = abs(sx - fx) + abs(sy - fy);\n    for (int i = 0; i < n; ++i) {\n        chmin(ans, d[i] + abs(fx - p[i].first) + abs(fy - p[i].second));\n    }\n \n    cout << ans << nl;\n \n#ifdef LOCAL\n    cerr << \"Time execute: \" << clock() / (double)CLOCKS_PER_SEC << \" sec\" << endl;\n#endif\n    return 0;\n}",
    "tags": [
      "graphs",
      "shortest paths",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1422",
    "index": "E",
    "title": "Minlexes",
    "statement": "Some time ago Lesha found an entertaining string $s$ consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.\n\nLesha chooses an arbitrary (possibly zero) number of pairs on positions $(i, i + 1)$ in such a way that the following conditions are satisfied:\n\n- for each pair $(i, i + 1)$ the inequality $0 \\le i < |s| - 1$ holds;\n- for each pair $(i, i + 1)$ the equality $s_i = s_{i + 1}$ holds;\n- there is no index that is contained in more than one pair.\n\nAfter that Lesha removes all characters on indexes contained in these pairs and the algorithm is over. Lesha is interested in the lexicographically smallest strings he can obtain by applying the algorithm to the suffixes of the given string.",
    "tutorial": "Let's find the answer $ans_i$ for all suffixes, starting with the smallest in length. $ans_n$ is equal to an empty string. Then if $s_i = s_{i + 1}$ ($0 \\le i + 1 < n$), then $ans_i = min (s_i + ans_{i + 1}, ans_{i + 2})$, and otherwise $ans_i = s_i + ans_{i + 1}$. To quickly find minimum of two strings, they can be stored as \"binary lifts\" - $next_ {i, j}$ will be equal to the position in the string $s$, on which the $2 ^ j$ character $ans_i$ will be located, and $hash_{i, j}$ - hash from the prefix $ans_i$ of length $2 ^ j$. Values for $(i, j)$ can be obtained from $(i, j-1)$ and $(i + 2 ^ {j-1}, j-1)$. To restore the answer, $next_ {i, j}$ will be enough for us, and for simplicity we can additionally store the length of each answer.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())\n#define sz(v) ((int)(v).size())\n \n#define vec1d(x) vector<x>\n#define vec2d(x) vector<vec1d(x)>\n#define vec3d(x) vector<vec2d(x)>\n#define vec4d(x) vector<vec3d(x)>\n \n#define ivec1d(x, n, v) vec1d(x)(n, v)\n#define ivec2d(x, n, m, v) vec2d(x)(n, ivec1d(x, m, v))\n#define ivec3d(x, n, m, k, v) vec3d(x)(n, ivec2d(x, m, k, v))\n#define ivec4d(x, n, m, k, l, v) vec4d(x)(n, ivec3d(x, m, k, l, v))\n \n#ifdef LOCAL\n#include \"pretty_print.h\"\n#define dbg(...) cerr << \"[\" << #__VA_ARGS__ << \"]: \", debug_out(__VA_ARGS__)\n#else\n#define dbg(...) 42\n#endif\n \n#define nl \"\\n\"\n \ntypedef long double ld;\ntypedef long long ll;\ntypedef unsigned long long ull;\n \ntemplate <typename T> T sqr(T x) { return x * x; }\ntemplate <typename T> T abs(T x) { return x < 0? -x : x; }\ntemplate <typename T> T gcd(T a, T b) { return b? gcd(b, a % b) : a; }\ntemplate <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }\ntemplate <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }\n \nauto random_address = [] { char *p = new char; delete p; return (uint64_t) p; };\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\nmt19937_64 rngll(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\n \n \nint main(int /* argc */, char** /* argv */)\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n#ifdef LOCAL\n    assert(freopen(\"i.txt\", \"r\", stdin));\n    assert(freopen(\"o.txt\", \"w\", stdout));\n#endif\n \n    string s;\n    while (cin >> s) {\n        int n = s.size();\n        vector<int> a(n + 2, 0);\n        for (int i = 0; i < n; ++i) {\n            a[i] = s[i] - 'a' + 1;\n        }\n \n        int m = 1;\n        while ((1 << m) <= n) {\n            m += 1;\n        }\n \n        const int P = 29;\n        vector<ull> p(n + 1);\n        p[0] = 1;\n        for (int i = 1; i <= n; ++i) {\n            p[i] = p[i - 1] * P;\n        }\n \n        auto hsh = ivec2d(ull, n + 1, m, 0);\n        auto nxt = ivec2d(int, n + 1, m, n);\n        auto len = ivec1d(int, n + 1, 0);\n        auto jmp = ivec1d(int, n + 1, 0);\n        iota(all(jmp), 0);\n \n        auto cmp = [&](int x, int y) {\n            x = jmp[x];\n            y = jmp[y];\n            for (int i = m - 1; i >= 0; --i) {\n                if (hsh[x][i] == hsh[y][i]) {\n                    x = nxt[x][i];\n                    y = nxt[y][i];\n                }\n            }\n            return a[x] < a[y];\n        };\n \n        auto upd = [&](int x, int v) {\n            v = jmp[v];\n            len[x] = len[v] + 1;\n            hsh[x][0] = a[x];\n            nxt[x][0] = v;\n            for (int i = 1; i < m; ++i) {\n                int y = nxt[x][i - 1];\n                nxt[x][i] = nxt[y][i - 1];\n                hsh[x][i] = hsh[x][i - 1] * p[1 << (i - 1)] + hsh[y][i - 1];\n            }\n        };\n \n        for (int i = n - 1; i >= 0; --i) {\n            upd(i, i + 1);\n            if (i + 1 < n && a[i] == a[i + 1] && cmp(i + 2, i)) {\n                jmp[i] = jmp[jmp[i + 2]];\n                len[i] = len[jmp[i]];\n            }\n        }\n \n        for (int i = 0; i < n; ++i) {\n            cout << len[i] << \" \";\n            int x = jmp[i];\n            for (int j = 0, limit = len[i] <= 10? len[i] : 5; j < limit; ++j, x = nxt[x][0]) {\n                cout << s[x];\n            }\n            if (len[i] > 10) {\n                int d = len[i] - 5 - 2;\n                for (int i = m - 1; i >= 0; --i) {\n                    if ((1 << i) <= d) {\n                        d -= 1 << i;\n                        x = nxt[x][i];\n                    }\n                }\n                cout << \"...\";\n                for (int j = 0; j < 2; ++j, x = nxt[x][0]) {\n                    cout << s[x];\n                }\n            }\n            cout << nl;\n        }\n    }\n \n#ifdef LOCAL\n    cerr << \"Time execute: \" << clock() / (double)CLOCKS_PER_SEC << \" sec\" << endl;\n#endif\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1422",
    "index": "F",
    "title": "Boring Queries",
    "statement": "Yura owns a quite ordinary and boring array $a$ of length $n$. You think there is nothing more boring than that, but Vladik doesn't agree!\n\nIn order to make Yura's array even more boring, Vladik makes $q$ boring queries. Each query consists of two integers $x$ and $y$. Before answering a query, the bounds $l$ and $r$ for this query are calculated: $l = (last + x) \\bmod n + 1$, $r = (last + y) \\bmod n + 1$, where $last$ is the answer on the previous query (zero initially), and $\\bmod$ is the remainder operation. Whenever $l > r$, they are swapped.\n\nAfter Vladik computes $l$ and $r$ for a query, he is to compute the least common multiple (LCM) on the segment $[l; r]$ of the initial array $a$ modulo $10^9 + 7$. LCM of a multiset of integers is the smallest positive integer that is divisible by all the elements of the multiset. The obtained LCM is the answer for this query.\n\nHelp Vladik and compute the answer for each query!",
    "tutorial": "In order to find the LCM of numbers on a segment, you can, for each prime number, find the maximum power with which it enters into any number on the segment and multiply the answer with this power. Let's calculate the LCM for primes less than $\\sqrt {MaxA}$ and greater than $\\sqrt {MaxA}$ separately using the segment tree. There are $k = 86$ prime numbers less than $\\sqrt {MaxA}$. Let's store a sorted list of prime numbers with their maximum power in each subsegment of the tree. The union of two segments can be done in $O (k)$. Then the construction of the entire tree can be done in $O (n \\cdot k)$. In order to answer the query, we split it into $O (log (n))$ subsegments of the segment tree and sequentially combine them in $O (k)$. For each number $a_i$ in the array, there will be no more than one prime divisor $p_i$ greater than $\\sqrt {MaxA}$. For a query, you need to find the product of unique numbers $p_i$ on a segment. To do this, for each such simple $p_i$ number, find $prev_i$ - the closest position to the left in the array of the same prime number (or $-1$ if there is no such number on the left). For a subsegment, we will store a sorted list of $(prev_i, p_i)$ pairs, and also pre-calculate the product $p_i$ for each prefix. Now, for each subsegment of the tree that will be included in the query $(l, r)$, you need to select all such pairs for which $prev_i <l$ and take product of $p_i$. Since the list is ordered, all these numbers will form a prefix. The prefix can be found using a binary search for $log (n)$. Total complexity $O (n \\cdot k + q \\cdot log (n) \\cdot k + q \\cdot log^2 (n))$, where $k = \\frac {\\sqrt {MaxA}} {\\ln \\sqrt {MaxA}}$ (the number of primes up to the root).",
    "code": "#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())\n#define sz(v) ((int)(v).size())\n \n#define vec1d(x) vector<x>\n#define vec2d(x) vector<vec1d(x)>\n#define vec3d(x) vector<vec2d(x)>\n#define vec4d(x) vector<vec3d(x)>\n \n#define ivec1d(x, n, v) vec1d(x)(n, v)\n#define ivec2d(x, n, m, v) vec2d(x)(n, ivec1d(x, m, v))\n#define ivec3d(x, n, m, k, v) vec3d(x)(n, ivec2d(x, m, k, v))\n#define ivec4d(x, n, m, k, l, v) vec4d(x)(n, ivec3d(x, m, k, l, v))\n \n#ifdef LOCAL\n#include \"pretty_print.h\"\n#define dbg(...) cerr << \"[\" << #__VA_ARGS__ << \"]: \", debug_out(__VA_ARGS__)\n#else\n#define dbg(...) 42\n#endif\n \n#define nl \"\\n\"\n \ntypedef long double ld;\ntypedef long long ll;\ntypedef unsigned long long ull;\n \ntemplate <typename T> T sqr(T x) { return x * x; }\ntemplate <typename T> T abs(T x) { return x < 0? -x : x; }\ntemplate <typename T> T gcd(T a, T b) { return b? gcd(b, a % b) : a; }\ntemplate <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }\ntemplate <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }\n \nauto random_address = [] { char *p = new char; delete p; return (uint64_t) p; };\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\nmt19937_64 rngll(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\n \n \nconst int MAXX = (int)sqrt(2e+5 + 42);\nconst int MAXN = 1e+5 + 42;\nconst int MAXT = 4 * MAXN;\nconst int MOD = (int)1e+9 + 7;\n \nstruct TNode {\n    vector<pair<int, int>> low;\n    vector<pair<int, int>> high;\n    vector<int> prod;\n};\n \nvector<TNode> t(MAXT);\nmap<int, int> lst;\nvector<int> a;\nvector<int> ps;\n \nvector<int> upd(MAXX, 0);\nvector<int> val(MAXX, 0);\nvector<int> seq(MAXX, 0);\nint cnt = 0;\nint ans = 0;\n \nvoid node_merge(TNode& a, TNode& b, TNode& r) {\n    {\n        auto fs = a.low.begin();\n        auto sc = b.low.begin();\n        while (fs != a.low.end() || sc != b.low.end()) {\n            if (sc == b.low.end() || (fs != a.low.end() && fs->first < sc->first)) {\n                r.low.emplace_back(fs->first, fs->second);\n                ++fs;\n            } else if (fs == a.low.end() || (sc != b.low.end() && sc->first < fs->first)) {\n                r.low.emplace_back(sc->first, sc->second);\n                ++sc;\n            } else {\n                assert(fs != a.low.end());\n                assert(sc != b.low.end());\n                assert(fs->first == sc->first);\n                r.low.emplace_back(fs->first, max(fs->second, sc->second));\n                ++fs;\n                ++sc;\n            }\n        }\n    }\n    merge(all(a.high), all(b.high), back_inserter(r.high));\n \n    int p = 1;\n    for (auto& [_, x] : r.high) {\n        p = p * (ll)x % MOD;\n        r.prod.push_back(p);\n    }\n}\n \nvoid build_tree(int idx, int l, int r) {\n    if (l + 1 == r) {\n        int x = a[l];\n        for (auto& p : ps) {\n            if (p * p > x) {\n                break;\n            }\n            int c = 0;\n            while (x % p == 0) {\n                x /= p;\n                ++c;\n            }\n            if (c) {\n                t[idx].low.emplace_back(p, c);\n            }\n        }\n        if (x > 1) {\n            if (x >= MAXX) {\n                auto it = lst.find(x);\n                int prv = it == lst.end()? -1 : it->second;\n                t[idx].high.emplace_back(prv, x);\n                t[idx].prod.emplace_back(x);\n                lst[x] = l;\n            } else {\n                t[idx].low.emplace_back(x, 1);\n            }\n        }\n \n        return;\n    }\n \n    int c = (l + r) / 2;\n    int lid = 2 * idx + 0;\n    int rid = 2 * idx + 1;\n    build_tree(lid, l, c);\n    build_tree(rid, c, r);\n    node_merge(t[lid], t[rid], t[idx]);\n}\n \nvoid get(int idx, int l, int r, int lq, int rq) {\n    if (lq <= l && r <= rq) {\n        for (auto& [p, s] : t[idx].low) {\n            if (upd[p] != cnt) {\n                upd[p] = cnt;\n                seq.push_back(p);\n                val[p] = 0;\n            }\n            chmax(val[p], s);\n        }\n \n        int pos = lower_bound(all(t[idx].high), make_pair(lq, 0)) - t[idx].high.begin();\n        if (pos) {\n            ans = ans * (ll)t[idx].prod[pos - 1] % MOD;\n        }\n        return;\n    }\n \n    int c = (l + r) / 2;\n    int lid = 2 * idx + 0;\n    int rid = 2 * idx + 1;\n \n    if (lq < c) {\n        get(lid, l, c, lq, rq);\n    }\n \n    if (c < rq) {\n        get(rid, c, r, lq, rq);\n    }\n}\n \nint powmod(int a, int b) {\n    ll s = a;\n    ll ret = 1;\n    while (b) {\n        if (b & 1) {\n            ret = ret * s % MOD;\n        }\n        s = s * s % MOD;\n        b >>= 1;\n    }\n    return ret;\n}\n \nint main(int /* argc */, char** /* argv */)\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n#ifdef LOCAL\n    assert(freopen(\"i.txt\", \"r\", stdin));\n    assert(freopen(\"o.txt\", \"w\", stdout));\n#endif\n \n    vector<int> fp(MAXX, 1);\n    for (int i = 2; i < MAXX; ++i) {\n        if (!fp[i]) {\n            continue;\n        }\n        ps.push_back(i);\n        if (i <= MAXX / i) {\n            for (int j = i * i; j < MAXX; j += i) {\n                fp[j] = false;\n            }\n        }\n    }\n \n    int n;\n    cin >> n;\n    a.resize(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n \n    int root = 1;\n    build_tree(root, 0, n);\n \n    int Q;\n    cin >> Q;\n    for (int q = 0; q < Q; ++q) {\n        int l, r;\n        cin >> l >> r;\n        l = (l + ans) % n;\n        r = (r + ans) % n;\n        if (l > r) {\n            swap(l, r);\n        }\n \n        ++cnt;\n        seq.clear();\n \n        ans = 1;\n        get(root, 0, n, l, r + 1);\n \n        for (auto& x : seq) {\n            ans = ans * (ll)powmod(x, val[x]) % MOD;\n        }\n \n        cout << ans << nl;\n    }\n \n \n#ifdef LOCAL\n    cerr << \"Time execute: \" << clock() / (double)CLOCKS_PER_SEC << \" sec\" << endl;\n#endif\n    return 0;\n}",
    "tags": [
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1425",
    "index": "A",
    "title": "Arena of Greed",
    "statement": "Lately, Mr. Chanek frequently plays the game \\textbf{Arena of Greed}. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.\n\nThe game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing $N$ gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves:\n\n- Take one gold coin from the chest.\n- Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even.\n\nBoth players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.",
    "tutorial": "We can solve this problem greedily. The tricky case is if the current number of coins is a multiple of $4$ greater than $8$, it is optimal to take 1 coin instead of taking $\\frac{N}{2}$ coins. The proof: Lets say the number of of coins is $4k$ for some $k>0$. If we take $2k$ coins: Mr. Chanek takes $2k$ coins. (remaining: $2k$) Opponent takes $k$ coins. (remaining: $k$) The number of coins Mr. Chanek gets is $2k$ coins. Lets say we take $1$ coin: Mr. Chanek takes $1$ coin. (remaining: $4k-1$) Opponent takes $1$ coin. (remaining: $4k-2$) Mr. Chanek takes $2k -1$ coins. (remaining: $2k-1$). Opponent takes $1$ coin. (remaining: $2k-2$). In both cases, Mr. Chanek ends up with $2k$ coins. However, there are $2k-2$ coins remaining in the second example, while only $k$ coins remain in the first example. So, if $2k-2 > k$, we take the second case. It turns out, $2k - 2 \\le k$ is only true if $k = 1$. So if the number of coins is $4$, we take $2$ coins, else we take $1$ coin. Alternatively, you can also look at the number of coins the opponent gained. On the first case, the opponent gains $k$ coins, while on the second case, the opponent gains $2$ coins. In both cases, we gain $2k$ coins. So, it's optimal to choose the option that maximizes the difference of coins gained ($k$ or $2$). For other possible number of coins: if the number of coins is even not multiple of $4$, we take half coins. If the number of coins is odd, we take $1$ coin. Time complexity: $O(T log N)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define pb push_back\n#define pf push_front\n#define pob pop_back\n#define pof pop_front\n#define mp make_pair\n#define fi first\n#define se second\n \ntypedef long long lli;\ntypedef pair<int, int> ii;\ntypedef pair<lli, lli> ll;\n \nlli solve(lli n) {\n\tif (n < 5)\n\t\treturn max(1ll, n - 1);\n\tif ((n % 2 == 1) || (n % 4 == 0))\n\t\treturn (n - solve(n - 1));\n\treturn (n - solve(n / 2));\n}\n \nint main() {\n\tlli tc, n;\n\tscanf(\"%lld\", &tc);\n\twhile (tc--) {\n\t\tscanf(\"%lld\", &n);\n\t\tprintf(\"%lld\\n\", solve(n));\n\t}\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1425",
    "index": "B",
    "title": "Blue and Red of Our Faculty!",
    "statement": "It's our faculty's 34th anniversary! To celebrate this great event, the Faculty of Computer Science, University of Indonesia (Fasilkom), held CPC - Coloring Pavements Competition. The gist of CPC is two players color the predetermined routes of Fasilkom in Blue and Red. There are $N$ Checkpoints and $M$ undirected predetermined routes. Routes $i$ connects checkpoint $U_i$ and $V_i$, for $(1 \\le i \\le M)$. It is guaranteed that any pair of checkpoints are connected by using one or more routes.\n\nThe rules of CPC is as follows:\n\n- Two players play in each round. One player plays as blue, the other plays as red. For simplicity, let's call these players $Blue$ and $Red$.\n- $Blue$ will color every route in he walks on blue, $Red$ will color the route he walks on red. Both players start at checkpoint number $1$. Initially, all routes are gray.\n- Each phase, from their current checkpoint, $Blue$ and $Red$ select a \\textbf{different} gray route and moves to the checkpoint on the other end of the route simultaneously.\n- The game ends when $Blue$ or $Red$ can no longer move. That is, there is no two distinct gray routes they can choose to continue moving.\n\nChaneka is interested in participating. However, she does not want to waste much energy. So, She is only interested in the number of final configurations of the routes after each round. Turns out, counting this is also exhausting, so Chaneka asks you to figure this out!\n\nTwo final configurations are considered different if there is a route $U$ in a different color in the two configurations.",
    "tutorial": "First, we must notice that the graph is a clover graph. The graph has cycles with vertex $1$ in common. We can transform the graph into an array $A$, where $A_i$ is the number of edges in cycle $i$. On the final configuration, each cycle has three possible endings: The whole cycle is colored red or blue The whole cycle is gray exactly one cycle is colored in two different colors (can be red and blue, red and gray, blue and gray). This is the last cycle they visit. The third point suggests a dynamic programming approach: for each cycle in $A$, set this cycle as the last cycle, and count how many configurations. So for the other cycles, we can calculate $DP[i][diff][takeAll]$, the number of configurations using the first $i$ cycles, where $diff$ is the absolute difference between the number edges blue and red took, and $takeAll$ is a boolean that indicates all cycles 1...i must be taken by either $red$ or $blue$. The transitions are quite straightforward, and its easier to see the code if you are confused. Calculating this DP is done in $O(N^2)$ Why flag $takeAll$? because for a fixed last cycle, there are two possible final positions for $red$ and $blue$, assuming $C$ is the size of the fixed cycle: If one player ends in vertex $1$: $2 \\cdot DP[N][C-1][1]$. All other cycles must be colored, else both players can still move. If both players ends inside the cycle: $2 \\cdot \\sum\\limits_{i=0}^{C-2}DP[N][i][0]$ There is an additional case where both players finish at vertex $1$. TO find this, we recalculate DP using the whole array. The number of configurations is $DP[N][0][1]$. Calculating this for all elements of $A$ will give an $O(N^3)$ solution. However, since $\\sum A = N$, there are atmost $\\sqrt{N}$ different values in $A$. So, we can calculate DP for only these $\\sqrt{N}$ values. This gives a $O(N^2 \\sqrt{N})$ solution which if sufficient to get accepted. Bonus $O(N^2)$ solution: The solution can be optimized further by partitioning $A$ into two parts: first part consists of all distinct values in the area (each appears once). The size of this part is at most $\\sqrt{N}$. the second part is all other elements We notice that when fixing cycles, the second part does not change so we can calculate DP on this part exactly once in $O(N^2)$. We can then only recalculate DP in the first part. Since there are $\\sqrt{N}$ elements, calculating DP on this is $O(N \\sqrt{N})$. Since we calculate DP $\\sqrt{N}$ times, the total complexity is $O(N^2)$. Then, merges with the first DP. $O(N^2 \\sqrt{N})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int MAXN=2e3+5;\n \nint N, M, SA, SB, ans;\nint P[MAXN];\nint H[MAXN];\nint DP[MAXN][3*MAXN];\nint PD[MAXN][3*MAXN];\nvector <int> A, B;\nvector <int> V[MAXN];\nset <int> S;\n \n//BEGIN TEMODPLATE\n//Template for DP Combin to avoid RLE\nconst long long MOD=1e9+7, D=(1LL<<61)/MOD;\n \n//fast modulo for addition\ninline int add(int a) {\n\treturn a<MOD?a:a-MOD;\n}\n \n//fast modulo for subtraction\ninline int sub(int a) {\n\treturn a<0?a+MOD:a;\n}\n \n//fast modulo for multiplication\ninline int mul(long long a) {\n\treturn add(a-MOD*((a>>29)*D>>32));\n}\n \n//one-line fast exponentation\nint expo(long long a,int b) {\n\treturn b?b&1?mul(a*expo(mul(a*a),b>>1)):expo(mul(a*a),b>>1):1;\n}\n \n//modular inverse for division\ninline int div(int a) {\n\treturn expo(a,MOD-2);\n}\n//END TEMODPLATE\n \nvoid input() {\n\tcin>>N>>M;\n\t\n\tfor (int i=0;i<M;i++) {\n\t\tint X, Y;\n\t\tcin>>X>>Y;\n\t\tV[X].push_back(Y);\n\t\tV[Y].push_back(X);\n\t}\n\t\n\tfor (int X : V[1]) {\n\t\tint Y=1, H=1;\n\t\twhile (X!=1) {\n\t\t\tY=V[X][0]+V[X][1]-Y;\n\t\t\tswap(X,Y);\n\t\t\tH++;\n\t\t}\n\t\tB.push_back(H);\n\t}\n}\n \nvoid debug() {\n\tcin>>N;\n\t\n\tfor (int i=0;i<N;i++) {\n\t\tcin>>M;\n\t\tB.push_back(M);\n\t\tB.push_back(M);\n\t}\n}\n \nint main () {\n\tinput();\n\t//debug();\n\t\n\tsort(B.begin(),B.end());\n\t\n\tfor (int i=0;i<B.size();i+=2) {\n\t\tif (S.count(B[i])) {\n\t\t\tA.push_back(B[i]);\n\t\t}\n\t\telse {\n\t\t\tS.insert(B[i]);\n\t\t}\n\t}\n\t\n\tSA=A.size();\n\t\n\tfor (int x : S) {\n\t\tA.push_back(x);\n\t}\n\t\n\tSB=A.size();\n\tDP[0][0]=1;\n\t\n\tfor (int i=0;i<SB;i++) {\n\t\tP[i+1]=P[i]+A[i];\n\t\t\n\t\tfor (int j=0;j<=P[i+1];j++) {\n\t\t\tDP[i+1][j]=add(DP[i][j>A[i]?j-A[i]:A[i]-j]+DP[i][j+A[i]]);\n\t\t\tPD[i+1][j]=add(add(DP[i][j>A[i]?j-A[i]:A[i]-j]+PD[i][j+A[i]])+(j>=A[i]?PD[i][j-A[i]]:sub(mul((long long)i*DP[i][A[i]-j])-PD[i][A[i]-j])));\n\t\t}\n\t}\n\t\n\tans=add(DP[SB][0]+add(add(PD[SB][1]<<1)<<1));\n\t\n\tfor (int i=0;i<SB;i++) {\n\t\tfor (int j=0;j<=P[i+1];j++) {\n\t\t\tDP[i+1][j]=add(DP[i][j]+add(DP[i][j>A[i]?j-A[i]:A[i]-j]+DP[i][j+A[i]]));\n\t\t}\n\t}\n\t\n\tfor (int h=SB-1;h>=SA;h--) {\n\t\tfor (int i=h+1;i<SB;i++) {\n\t\t\tfor (int j=0;j<=P[i+1];j++) {\n\t\t\t\tDP[i][j]=add(DP[i-1][j]+add(DP[i-1][j>A[i]?j-A[i]:A[i]-j]+DP[i-1][j+A[i]]));\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor (int i=1;i<A[h]-1;i++) {\n\t\t\tH[A[h]]=add(H[A[h]]+DP[SB-1][i]);\n\t\t}\n\t\t\n\t\tH[A[h]]=add(H[A[h]]<<1);\n\t\tH[A[h]]=add(H[A[h]]+DP[SB-1][0]);\n\t\tH[A[h]]=add(H[A[h]]<<1);\n\t}\n\t\n\tfor (int i=0;i<SB;i++) {\n\t\tans=add(ans+H[A[i]]);\n\t}\n\t\n\tcout<<ans<<'\\n';\n}",
    "tags": [
      "divide and conquer",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1425",
    "index": "C",
    "title": "Captain of Knights",
    "statement": "Mr. Chanek just won the national chess tournament and got a huge chessboard of size $N \\times M$. Bored with playing conventional chess, Mr. Chanek now defines a function $F(X, Y)$, which denotes the minimum number of moves to move a knight from square $(1, 1)$ to square $(X, Y)$. It turns out finding $F(X, Y)$ is too simple, so Mr. Chanek defines:\n\n$G(X, Y) = \\sum_{i=X}^{N} \\sum_{j=Y}^{M} F(i, j)$\n\nGiven X and Y, you are tasked to find $G(X, Y)$.\n\nA knight can move from square $(a, b)$ to square $(a', b')$ if and only if $|a - a'| > 0$, $|b - b'| > 0$, and $|a - a'| + |b - b'| = 3$. Of course, the knight cannot leave the chessboard.",
    "tutorial": "An important observation is that it is guaranteed there is a sequence of moves from $(1, 1)$ to $(X, Y)$ where we only visit squares in the rectangle $(1, 1)$ to $(X, Y)$. So we can calculate $F(X, Y)$ independently without concerning $N$ dan $M$. To ease the implementation and explanation, we define $\\int(f(x)) = \\sum_{i = 1}^{x}f(i)$. So the sum of an order two polynomial $F(x) = a \\cdot x^2 + b \\cdot x + c$ is $\\int{F(x} = \\frac{a}{3} x^3 + \\frac{a + b}{2} x^2 + \\frac{a + 3b + 6c}{6} x$ Since the number of formulas in this problem tutorial is quite large, we will omit the method to find it because then the editorial will be quite long Lets define $P(x,y) = \\sum_{i = 3}^{x} \\sum_{j = 3}^{y} F(i,j)$. If we can find $P(x, y)$ fast, the answer is $P(N,M) - P(X-1,M) - P(N,Y-1) + P(X-1,Y-1)$. Calculating $P$ can be divided into three cases: $\\bullet$ Case 1, For $x = 3$, $y \\le 5$. we can use brute force. $\\bullet$ Case 2,For $x < 2y$ and $y < 2x$. Let $z = (x + y - 2)$, $F(x, y) = s(z) = \\frac{z}{3} + z \\bmod 3$. Assume $t(x) = \\int(s(x))$. For rows $i$ from 4 to $\\frac{y}{2}$, the sum of $F$ is $t(3(i-1)) - t(\\frac{3i}{2}-2)$. For rows $i$ greater than $\\frac{y}{2}$ next rows, the sum of $F$ is $t(i+y-2) - t(\\frac{3i}{2}-2)$. To ease in finding the sum, we define: $a(x) = t(1) + t(2) + ... + t(x)$ $b(x) = t(3) + t(6) + ... + t(3x)$ $c(x) = t(1) + t(2) + t(4) + t(5) + ... + t(\\frac{3x-1}{2})$ $t(3x) = \\int(3x+1)$, $a(3x) = \\int(3 \\int(3x+1) - (3x+1))$ $b(x) = \\int(\\int(3x+1))$ $c(2x) = a(3x) - b(x)$. $\\bullet$ Case 3, for $2y \\le 2 \\cdot x$ or $x \\le 2 \\cdot y$. First see the illustration below for context. The sum of $F(x, y)$ for each blocks of two columns starting at an even number is the same. We define $blocks$ as these columns. So, block $1$ is the $[3, 4]$ block, block $2$ is the $[5, 4]$ block, and so on. The sum of a row in block $i$ is $(2 \\cdot x + 5)$. Since there are $i$ rows in block $i$, the sum of all rows in block $i$ is $i(2 \\cdot i + 5)$. To ease, lets define two functions: $d(x) = \\int{x (2 \\cdot x + 5)}$. Sum of all $F$ for the first $x$ blocks. $e(x) = \\int{(2 \\cdot x + 5 )}$. Sum of a row for the first $x$ blocks. The sum of this part is divided into three regions which is also described in the image above (red, yellow, green). the sum on the green area is $d(N-1)$. There is a square of height $N$ from colums $N-1$ to $\\frac{M}{2}$. So, the sum of this region is $N(e(\\frac{M}{2})-e(N-1))$ The red area. This is a single row at the end if $M$ is odd. If $N$ is even, the sum is $\\frac{N}{2} \\cdot (M + 6)$. If N is odd, we add an additional square which is $F(N + 2, M + 5)$ (remember we simplify $N$ and $M$ at the beginning. So, the sum of case three is $d(N-1) + N(e(\\frac{M}{2})-e(N-1))$ + red area. Calculate this formula again with the rows swapped to for case $y \\ge 2 \\cdot x$. note: Calculating $t(x)$ and $a(x)$ when $x$ is not a multiple of $3$ can be done by finding the closest multiple of $3$ and then bruteforcing the last columns. That can also be used to calculate $c(x)$ and $e(x)$ when $x$ is odd. Time Complexity: $O(T)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst long long MOD=1e9+7;\n \nstruct intmod {\n\tlong long val;\n\t\n\tintmod operator + (const intmod other) const {\n\t\tintmod ret;\n\t\tret.val=val+other.val;\n\t\t\n\t\tif (ret.val>=MOD) {\n\t\t\tret.val-=MOD;\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\tintmod operator - (const intmod other) const {\n\t\tintmod ret;\n\t\tret.val=val+MOD-other.val;\n\t\t\n\t\tif (ret.val>=MOD) {\n\t\t\tret.val-=MOD;\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\tintmod operator * (const intmod other) const {\n\t\tintmod ret;\n\t\tret.val=val*other.val%MOD;\n\t\t\n\t\treturn ret;\n\t}\n}\nHALF={(MOD+1)/2}, THIRD={(MOD+1)/3};\n \nintmod make_int(long long x) {\n\treturn {x};\n}\n \nstruct polinom {\n\tintmod koef[4];\n\t\n\tintmod ans(intmod x) {\n\t\tintmod ret;\n\t\tret=koef[3];\n\t\tret=(ret*x)+koef[2];\n\t\tret=(ret*x)+koef[1];\n\t\tret=(ret*x)+koef[0];\n\t\t\n\t\treturn ret;\n\t}\n\t\n\tpolinom sum() {\n\t\tpolinom ret;\n\t\t\n\t\tret.koef[0]={0};\n\t\tret.koef[1]=koef[0]+((koef[1]+(koef[2]*THIRD))*HALF);\n\t\tret.koef[2]=(koef[1]+koef[2])*HALF;\n\t\tret.koef[3]=koef[2]*THIRD;\n\t\t\n\t\treturn ret;\n\t}\n\t\n\tpolinom operator + (const polinom other) const {\n\t\tpolinom ret;\n\t\t\n\t\tret.koef[0]=koef[0]+other.koef[0];\n\t\tret.koef[1]=koef[1]+other.koef[1];\n\t\tret.koef[2]=koef[2]+other.koef[2];\n\t\tret.koef[3]=koef[3]+other.koef[3];\n\t\t\n\t\treturn ret;\n\t}\n\t\n\tpolinom operator - (const polinom other) const {\n\t\tpolinom ret;\n\t\t\n\t\tret.koef[0]=koef[0]-other.koef[0];\n\t\tret.koef[1]=koef[1]-other.koef[1];\n\t\tret.koef[2]=koef[2]-other.koef[2];\n\t\tret.koef[3]=koef[3]-other.koef[3];\n\t\t\n\t\treturn ret;\n\t}\n\t\n\tpolinom operator * (const intmod other) const {\n\t\tpolinom ret;\n\t\t\n\t\tret.koef[0]=koef[0]*other;\n\t\tret.koef[1]=koef[1]*other;\n\t\tret.koef[2]=koef[2]*other;\n\t\tret.koef[3]=koef[3]*other;\n\t\t\n\t\treturn ret;\n\t}\n}\nBASE={1,3,0,0};\n \nintmod f(long long K) {\n\tpolinom save;\n\tsave=BASE;\n\tsave=save.sum();\n\t\n\tintmod ret;\n\tret=save.ans({K/3});\n\t\n\tif (K%3>=1) {\n\t\tret=ret+make_int(K/3+1);\n\t}\n\t\n\tif (K%3>=2) {\n\t\tret=ret+make_int(K/3+2);\n\t}\n\t\n\treturn ret;\n}\n \nintmod a(long long K) {\n\tpolinom save;\n\tsave=BASE;\n\tsave=save.sum();\n\tsave=save*make_int(3);\n\tsave=save-BASE;\n\tsave=save.sum();\n\t\n\tintmod ret;\n\tret=save.ans({K/3});\n\t\n\tif (K%3>=1) {\n\t\tret=ret+f(K);\n\t}\n\t\n\tif (K%3>=2) {\n\t\tret=ret+f(K-1);\n\t}\n\t\n\treturn ret;\n}\n \nintmod b(long long K) {\n\tpolinom save;\n\tsave=BASE;\n\tsave=save.sum();\n\tsave=save.sum();\n\t\n\treturn save.ans({K});\n}\n \nintmod c(long long K) {\n\treturn a(3*K/2)-b(K/2);\n}\n \nintmod d(long long K) {\n\tpolinom save;\n\tsave={0,5,2,0};\n\tsave=save.sum();\n\t\n\treturn save.ans({K});\n}\n \nintmod e(long long K) {\n\tpolinom save;\n\tsave={5,2,0,0};\n\tsave=save.sum();\n\t\n\treturn save.ans({K});\n}\n \nintmod P(long long N,long long M) {\n\tlong long K;\n\tN=min(N,2*M-1);\n\tM=min(M,2*N-1);\n\tK=max(3LL,M/2);\n\t\n\tif (N<=3) {\n\t\treturn {0};\n\t}\n\t\n\tintmod ret;\n\tret=a(N+M-2)-a(M+K-2);\n\tret=ret+b(K-1)-b(2);\n\tret=ret-c(N-1)+c(2);\n\t\n\treturn ret;\n}\n \nintmod Q(long long N,long long M) {\n\tN=min(N,M/2)-2;\n\tM=M-5;\n\t\n\tif (N<=0) {\n\t\treturn {0};\n\t}\n\t\n\tintmod ret;\n\tret=d(N-1);\n\tret=ret+((e(M/2)-e(N-1))*make_int(N));\n\t\n\tif (M%2>=1) {\n\t\tret=ret+(make_int(N/2)*make_int(M+6));\n\t\t\n\t\tif (N%2>=1) {\n\t\t\tret=ret+make_int(2*((M+1)/4)+3);\n\t\t}\n\t}\n\t\n\treturn ret;\n}\n \nintmod area(long long N,long long M) {\n\tif (N<3) {\n\t\treturn {0};\n\t}\n\t\n\tintmod ret;\n\tret={0};\n\t\n\tfor (long long i=3;i<=5;i++) {\n\t\tif (i<=M) {\n\t\t\tret=ret+make_int(7-i);\n\t\t}\n\t}\n\t\n\tret=ret+P(N,M);\n\tret=ret+Q(N,M);\n\tret=ret+Q(M,N);\n\t\n\treturn ret;\n}\n \nlong long Nmin, Mmin;\nlong long Nmax, Mmax;\nintmod ans;\n \nint main () {\n\tios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\t\n\tlong long tc;\n\tcin>>tc;\n\twhile(tc--) {\n\t\tcin>>Nmin>>Mmin;\n\t\tcin>>Nmax>>Mmax;\n\t\t\n\t\tans=area(Nmax,Mmax)+area(Nmin-1,Mmin-1);\n\t\tans=ans-(area(Nmax,Mmin-1)+area(Nmin-1,Mmax));\n\t\t\n\t\tcout<<ans.val<<'\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1425",
    "index": "D",
    "title": "Danger of Mad Snakes",
    "statement": "Mr. Chanek The Ninja is one day tasked with a mission to handle mad snakes that are attacking a site. Now, Mr. Chanek already arrived at the hills where the destination is right below these hills. The mission area can be divided into a grid of size $1000 \\times 1000$ squares. There are $N$ mad snakes on the site, the i'th mad snake is located on square $(X_i, Y_i)$ and has a danger level $B_i$.\n\nMr. Chanek is going to use the Shadow Clone Jutsu and Rasengan that he learned from Lord Seventh to complete this mission. His attack strategy is as follows:\n\n- Mr. Chanek is going to make $M$ clones.\n- Each clone will choose a mad snake as the attack target. Each clone must pick a different mad snake to attack.\n- All clones jump off the hills and attack their respective chosen target at once with Rasengan of radius $R$. If the mad snake at square $(X, Y)$ is attacked with a direct Rasengan, it and all mad snakes at squares $(X', Y')$ where $max(|X' - X|, |Y' - Y|) \\le R$ will die.\n- The real Mr. Chanek will calculate the score of this attack. The score is defined as the square of the sum of the danger levels of all the killed snakes.\n\nNow Mr. Chanek is curious, what is the sum of scores for every possible attack strategy? Because this number can be huge, Mr. Chanek only needs the output modulo $10^9 + 7$.",
    "tutorial": "We are going to count the contribution of two snakes $(I, J)$ separately. Assume that the current snake we are interested in has danger value $B_1$ and $B_2$. The terms where they are killed must be on the form $(... + B_1 + B_2 + ...)^2$. Expanding this gives $B_1^2 + B_2^2 + 2B_1B_2$. So, the contribution of $B_1B_2$ to the answer is the number of attack strategies where both $I$ and $J$ are killed. We can find this using the inclusion-exclusion principle. First, let's define: $W$: the number of squares where when hit will result in $I$ and $J$ being killed. $U$: the number of squares where when hit will result in $I$ killed, but not $J$. $V$: the number of squared where when hit will result in $J$ killed, but not $I$. We can calculate all these values easily using prefix sum DP. Then, there are two cases to consider: Case 1: a square in $W$ is hit. The number of ways is $C(N, M) - C(N - W, M)$ Case 2: a square in $W$ is not hit. However, a square in $U$ and $V$ is hit. Lets define $N' = N - W$. The number of ways is $C(N', M) - C(N' - U, M) - C(N' - V, M) + C(N' - U - V, M)$ Sum the number of ways times $2B_1B_2$ to the answer. Don't also forget to count the contribution of $B_{1}^2$. Time Complexity: $O(N^2)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define MAXN 1010\n#define MOD 1000000007\n \ntypedef long long ll;\ntypedef pair<int,int> pii;\n \nll pref[MAXN+1][MAXN+1];\n \nint dnc(int bas, int power, int mod) {\n\tif(power==0)\treturn 1;\n\tif(power%2==0) {\n\t\tint res=dnc(bas,power/2,mod);\n\t\treturn 1LL*res*res%mod;\n\t}\n\treturn 1LL*bas*dnc(bas,power-1,mod)%mod;\n}\n \n \nll f[2*MAXN+1],inv[2*MAXN+1];\n \nvoid precalc() {\n\tf[0] = inv[0]=1;\n \n\tfor(int temp=1;temp<=2*MAXN;temp++) {\n\t\t//cout<<temp<<\"\\n\";\n\t\tf[temp]=1ll*temp*f[temp-1]%MOD;\n\t\tinv[temp]=1ll*dnc(temp, MOD-2, MOD)*inv[temp-1]%MOD;\n\t}\n}\n \nll comb(int n, int k) {\n\tif(k>n || k<0) return 0;\n\t//cout<<\"combo \"<<n<<\" \"<<k<<\"\\n\";\n\treturn  f[n]*inv[k]%MOD*inv[n-k]%MOD;\n}\n \nll getsum(int x1, int y1, int x2, int y2) {\n\tx1 = max(x1, 1); x2 = min(x2, 1000);\n\ty1 = max(y1, 1); y2 = min(y2, 1000);\n\tif(x1 > x2 || y1 > y2) return 0;\n\t//cout<<\"getsum \"<<x1<<\" \"<<y1<<\" \"<<x2<<\" \"<<y2<<\" \"<<pref[x2][y2] - pref[x2][y1-1] - pref[x1-1][y2] + pref[x1-1][y1-1]<<\"\\n\";\n\treturn pref[x2][y2] - pref[x2][y1-1] - pref[x1-1][y2] + pref[x1-1][y1-1];\n}\n \nll getNumberThatCanKill(int x, int y, int r) {\n \n\treturn getsum(x-r, y-r, x+r, y+r);\n}\n \nint main() {\n \n\tprecalc();\n\tint n, m, r;\n\tcin>>n>>m>>r;\n\tint temp, temp2;\n \n\tvector<pii> snakes;\n \n\tint b[n];\n\t//cout<<\"in\\n\";\n\tfor(temp=0;temp<n;temp++) {\n\t\tint x,y;\n\t\tcin>>x>>y>>b[temp];\n\t\tpref[x][y] += 1;\n\t\tsnakes.push_back({x, y});\n\t}\n \n\tfor(int temp=1;temp<=MAXN;temp++)\n\t\tfor(int temp2=1;temp2<=MAXN;temp2++) {\n\t\t\tpref[temp][temp2] = pref[temp][temp2] + pref[temp-1][temp2] + pref[temp][temp2-1] - pref[temp-1][temp2-1];\n\t\t}\n \n\t//cout<<\"out\\n\";\n\tll sum = 0;\n \n\tfor(temp=0;temp<snakes.size();temp++) {\n\t\tfor(temp2=temp;temp2<snakes.size();temp2++) {\n \n\t\t\t//cout<<temp<<\" \"<<temp2<<\"\\n\";\n\t\t\tll cnt = 0;\n \n\t\t\tint x1 = snakes[temp].first, y1 = snakes[temp].second;\n\t\t\tint x2 = snakes[temp2].first, y2 = snakes[temp2].second;\n \n\t\t\t// case 1, exist point that hits both\n\t\t\tint minX = max(x1, x2) - r, minY = max(y1, y2) - r;\n\t\t\tint maxX = min(x1, x2) + r, maxY = min(y1, y2) + r;\n\t\t\tint w = getsum(minX, minY, maxX, maxY);\n\t\t\tcnt += comb(n, m) - comb(n-w, m);\n\t\t\tif(cnt<0) cnt+=MOD;\n \n\t\t\t//cout<<\"yeah\\n\";\n \n\t\t\t// case 2, no snakes hits both\n\t\t\tint u = getNumberThatCanKill(x1, y1, r) - w, v = getNumberThatCanKill(x2, y2, r) - w;\n\t\t\tcnt += comb(n-w, m) - comb(n-u-w, m) - comb(n-v-w, m) + comb(n-u-v-w, m);\n\t\t\tcnt%=MOD;\n\t\t\tif(cnt<0) cnt+=MOD;\n \n\t\t\t\n\t\t\tif(temp == temp2) sum+=cnt*b[temp]%MOD*b[temp2]%MOD;\n\t\t\telse sum+=2ll*cnt*b[temp]%MOD*b[temp2]%MOD;\n \n\t\t\tsum%=MOD;\n \n\t\t}\n\t}\n \n\tcout<<sum<<\"\\n\";\n \n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1425",
    "index": "E",
    "title": "Excitation of Atoms",
    "statement": "Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.\n\nThere are $N$ atoms numbered from $1$ to $N$. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom $i$ requires $D_i$ energy. When atom $i$ is excited, it will give $A_i$ energy. You can excite any number of atoms (including zero).\n\nThese atoms also form a peculiar one-way bond. For each $i$, $(1 \\le i < N)$, if atom $i$ is excited, atom $E_i$ will also be excited at no cost. Initially, $E_i$ = $i+1$. Note that atom $N$ cannot form a bond to any atom.\n\nMr. Chanek must change \\textbf{exactly} $K$ bonds. Exactly $K$ times, Mr. Chanek chooses an atom $i$, $(1 \\le i < N)$ and changes $E_i$ to a different value other than $i$ and the current $E_i$. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!\n\n\\textbf{note:} You must first change \\textbf{exactly} $K$ bonds before you can start exciting atoms.",
    "tutorial": "Notice that for $K = 2$, we can always make an excitation route starting from any atom in $i$ in $1 \\le i < N$ that excites all atoms. So, for $K > 2$, we can always make the routes by toggling bonds. So, there are three cases: If $K = 0$, it is optimal to excite only one atom. We try to excite atom $i$ for every $i$ and calculate the gained energy using prefix sum. If $K \\ge 2$, we can either excite one atom $i$ in $1 \\le i < N$, which will excite all atoms or excite only the last atom (which can be optimal if it has the lowest $D$). $K = 1$ is a tricky one. there are 5 cases to consider: change $E_{N-1}$ to $1$. Then excite the atom with the $D_i$ in $1 \\le i < N$. Also, excite atom $N$ if the energy gained is positive. change $E_i$ to $1$ and then excite atom $i$ and $i+1$ for $(1 < i < N)$. It is optimal to excite $i+1$ because if not, it will be worse than case 1. Change $E_1$ to $3$ and then excite $1$ and $2$. Change $E_1$ to $N$ and then excite atom $i$, for $(1 < i \\le N)$ Change $E_i$ to $i+2$ and then excite atom $1$, for $(1 < i < N)$. Note that this is only optimal if we excite atom $1$, else it is worse than case $4$ Handling all these cases will get you accepted Time complexity: $O(N)$",
    "code": "#include <iostream>\nusing namespace std;\ntypedef long long LL;\ntypedef pair<LL, LL> PLL;\n \n#define fi first\n#define se second\n \nconst LL LINF = 4557430888798830399LL;\nconst LL MAXN = 1000000;\n \nLL n,k;\nLL sum[MAXN+5];\nPLL isi[MAXN+5];\n \n// Define X is a node that make this true (1 <= X < N)\n \n/**\n * [This checks with no arrow change]\n * \n * Try to pick 1:\n *   Do prefix sum, earn X..N\n *\n * Try to pick >= 2:\n *   No Use, assume you must pick 2, so you take u and v\n *   the case is whether u will reach v or v will reach u,\n *   its better just to take one of those who will reach the other.\n */\nLL check0(){\n    LL ans = 0;\n    for(int i = n;i >= 1;i--) ans = max(ans, sum[i]-isi[i].se);\n    return ans;\n}\n \n/**\n * [This checks with one arrow change]\n *\n * Try to pick 1:\n *   If you pick X:\n *     Case 1: the answer N is included. If X != 1, just do prefix sum.\n *             if X is one, pick one smallest to skip.\n *     Case 2: The answer N is not included. You can make 2 cycle.\n *             Make 2 cycle\n *             1 -> 2 -> .. -> N-1 -> 1  and N\n *             earn 1..N-1.\n * Try to pick 2:\n *   If you pick X and N:\n *     Make 2 cycle\n *     1 -> 2 -> .. -> N-1 -> 1  and N\n *     earn 1..N\n *   If you pick U and V, both non N:\n *     earn 1..N\n *      \n */\nLL check1a(){\n    LL ans = LINF;\n    for(int i = 1;i < n;i++) ans = min(ans, isi[i].se);\n    ans = (sum[1]-isi[n].fi)-ans;\n    LL profit = max(0LL, isi[n].fi-isi[n].se);\n    return max(ans+profit, profit);\n}\n \nLL check1b(){\n    PLL maksi = {LINF, LINF};\n    for(int i = 1;i < n;i++){\n        if(isi[i].se <= maksi.fi){\n            maksi.se = maksi.fi;\n            maksi.fi = isi[i].se;\n        }else if(isi[i].se <= maksi.se){\n            maksi.se = isi[i].se;\n        }\n    }\n    return sum[1]-(maksi.fi+maksi.se);\n}\n \nLL check1c(){\n    LL ans = 0;\n    for(int i = n;i >= 2;i--) ans = max(ans, sum[i]-isi[i].se);\n \n    LL mini = LINF;\n    for(int i = 2;i < n;i++) mini = min(mini, isi[i].fi);\n \n    return max(ans, sum[1]-mini-isi[1].se);\n}\n \n/**\n * [This checks with two or more arrow changes with toggle to two]\n *\n * Try to pick 1:\n *   Case 1: Pick X\n *     Make line graph ending at N, visiting all 1..N\n *     The way is X->1->2->...(X-1)->(X+1)->..->(N-1)->N\n *     with only 2 changes.\n *     earn 1..N\n *   Case 2: Pick N\n *     Handled at check 0, because it can't go anywhere\n *\n * Try to pick >= 2:\n *   No use, X must be picked, but you can just pick X to visit all\n * \n */\nLL check2(){\n    LL ans = LINF;\n    for(int i = 1;i < n;i++) ans = min(ans, isi[i].se);\n    return max(isi[n].fi-isi[n].se, sum[1]-ans);\n}\n \nint main(){\n    cin >> n >> k;\n    for(int i = 1;i <= n;i++) cin >> isi[i].fi;\n    for(int i = 1;i <= n;i++) cin >> isi[i].se;\n    for(int i = n;i >= 1;i--) sum[i] = isi[i].fi+sum[i+1];\n    LL ans = 0;\n    if(k == 0) ans = max(ans, check0());\n    else if(k == 1) ans = max(ans, max(check1c(), max(check1a(), check1b())));\n    else ans = max(ans, check2());\n    cout << ans << endl;\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1425",
    "index": "F",
    "title": "Flamingoes of Mystery",
    "statement": "This is an interactive problem. You have to use a flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush().\n\nMr. Chanek wants to buy a flamingo to accompany his chickens on his farm. Before going to the pet shop, Mr. Chanek stops at an animal festival to have fun. It turns out there is a carnival game with a flamingo as the prize.\n\nThere are $N$ mysterious cages, which are numbered from $1$ to $N$. Cage $i$ has $A_i$ $(0 \\le A_i \\le 10^3)$ flamingoes inside $(1 \\le i \\le N)$. However, the game master keeps the number of flamingoes inside a secret. To win the flamingo, Mr. Chanek must guess the number of flamingoes in each cage.\n\nCoincidentally, Mr. Chanek has $N$ coins. Each coin can be used to ask once, what is the total number of flamingoes inside cages numbered $L$ to $R$ inclusive? With $L < R$.",
    "tutorial": "First get the values of the first three elements using three queries: \"? 1 3\" \"? 1 2\" \"? 2 3\" Once you get $A_i$, element $A_{i+1}$ can be obtained using \"? i i+1\" Time complexity: $O(N)$",
    "code": "#include <iostream>\nusing namespace std;\n \nconst int MAXN = 1000;\nint n, ans[MAXN+5];\n \nint ask(int l, int r){\n    cout << \"? \" << l << \" \" << r << endl;\n    int ret; cin >> ret;\n    return ret;\n}\n \nvoid answer(){\n    cout << \"!\";\n    for(int i = 1;i <= n;i++) cout << \" \" << ans[i];\n    cout << endl;\n}\n \nint main(){\n    cin >> n;\n    ans[n] = ask(1, n);\n    ans[1] = ans[n]-ask(2, n);\n    for(int i = 2;i <= n-1;i++) ans[i] = ask(i-1, i)-ans[i-1];\n    for(int i = 1;i < n;i++) ans[n] -= ans[i];\n    answer();\n}",
    "tags": [
      "interactive"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1425",
    "index": "H",
    "title": "Huge Boxes of Animal Toys",
    "statement": "Chaneka has a hobby of playing with animal toys. Every toy has a different fun value, a real number. Chaneka has four boxes to store the toys with specification:\n\n- The first box stores toys with fun values in range of $(-\\infty,-1]$.\n- The second box stores toys with fun values in range of $(-1, 0)$.\n- The third box stores toys with fun values in range of $(0, 1)$.\n- The fourth box stores toys with fun value in range of $[1, \\infty)$.\n\nChaneka has $A$, $B$, $C$, $D$ toys in the first, second, third, and fourth box, respectively. One day she decides that she only wants one toy, a super toy. So she begins to create this super toy by sewing all the toys she has.\n\nWhile the number of toys Chaneka has is more than 1, she takes two different toys randomly and then sews them together, creating a new toy. The fun value of this new toy is equal to the multiplication of fun values of the sewn toys. She then puts this new toy in the appropriate box. She repeats this process until she only has one toy. This last toy is the super toy, and the box that stores this toy is the special box.\n\nAs an observer, you only know the number of toys in each box initially but do not know their fun values. You also don't see the sequence of Chaneka's sewing. Determine which boxes can be the special box after Chaneka found her super toy.",
    "tutorial": "The main observation of this problem is that the sewing order does not matter. The final fun value is the multiplication of fun values of all toys. There are two separate cases we must consider: Cek the sign of the toy. If $(A + B)$ is even, the sign is positive. Else, it's negative. Cek whether it is possible to make a fun value with absolute value lower than 1 and greater than 1. The former is possible if $(B+ C) > 0$, the latter is possible if $(A + D) > 0$. Combining these two cases will give you the solution. Time Complexity: $O(T)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint T;\nint A,B,C,D;\nint main(){\n\tcin>>T;\n\tfor(int i=0;i<T;i++){\n\t\tcin>>A>>B>>C>>D;\n\t\tif(A==0 && D == 0){\n\t\t\tif(B % 2 == 1){\n\t\t\t\tcout<<\"Tidak Ya Tidak Tidak\\n\";\n\t\t\t} else {\n\t\t\t\tcout<<\"Tidak Tidak Ya Tidak\\n\";\n\t\t\t}\n\t\t} else if(B == 0 && C == 0){\n\t\t\tif(A % 2 == 1){\n\t\t\t\tcout<<\"Ya Tidak Tidak Tidak\\n\";\n\t\t\t} else {\n\t\t\t\tcout<<\"Tidak Tidak Tidak Ya\\n\";\n\t\t\t}\n\t\t} else {\n\t\t\tif((A+B) % 2 == 1){\n\t\t\t\tcout<<\"Ya Ya Tidak Tidak\\n\";\n\t\t\t} else{\n\t\t\t\tcout<<\"Tidak Tidak Ya Ya\\n\";\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1425",
    "index": "I",
    "title": "Impressive Harvesting of The Orchard",
    "statement": "Mr. Chanek has an orchard structured as a rooted ternary tree with $N$ vertices numbered from $1$ to $N$. The root of the tree is vertex $1$. $P_i$ denotes the parent of vertex $i$, for $(2 \\le i \\le N)$. Interestingly, the height of the tree is not greater than $10$. Height of a tree is defined to be the largest distance from the root to a vertex in the tree.\n\nThere exist a bush on each vertex of the tree. Initially, all bushes have fruits. Fruits will not grow on bushes that currently already have fruits. The bush at vertex $i$ will grow fruits after $A_i$ days since its last harvest.\n\nMr. Chanek will visit his orchard for $Q$ days. In day $i$, he will harvest all bushes that have fruits on the subtree of vertex $X_i$. For each day, determine the sum of distances from every harvested bush to $X_i$, and the number of harvested bush that day. Harvesting a bush means collecting \\textbf{all} fruits on the bush.\n\nFor example, if Mr. Chanek harvests all fruits on subtree of vertex $X$, and harvested bushes $[Y_1, Y_2, \\dots, Y_M]$, the sum of distances is $\\sum_{i = 1}^M \\text{distance}(X, Y_i)$\n\n$\\text{distance}(U, V)$ in a tree is defined to be the number of edges on the simple path from $U$ to $V$.",
    "tutorial": "We classify each vertex $i$ into two types. heavy if $A_i > \\sqrt{Q}$ and light if $A_i \\le \\sqrt{Q}$. We craft two different algorithms to solve each case separately. heavy nodes: Flatten the tree using pre-order transversal. Now querying a subtree becomes querying a subarray. Maintain a global set $S$ with all currently heavy node harvestable bushes, sorted by their pre-order index. We simulate each query. When querying subtree of $X$, we find all harvestable nodes in the set, remove them, and then add to the answer their contribution. The node is re-added the next time it is available to be queried. We can do this by maintaining a list of vectors denoting which nodes are harvestable again at each time. Since all nodes have $A_i > \\sqrt{Q}$, each node is removed and re-added at most $\\sqrt{Q}$ times. Since we are using set, it adds a log factor. So the total complexity of this is $O(N \\sqrt{Q} log N)$. light nodes: We solve separately for each different value of $A_i$. Assume the current value we are solving is $A$. We build a segment tree beats aggeration directly on the tree. we do not flatten the tree; you will see why in the proof below. In each vertex, we store $R_i$, when this bush is available to be harvested. We also store $max_i$ and $min_i$, the maximum and minimum value of $R_i$ on the subtrees of $i$, respectively. Initially, $R_i = 0$ for all $i$. We do the following in order for each query $X$: Find all highest depth $i$ vertices in the subtree of $X$ with $max_i = 0$. Add their contribution to the answer and then lazily update the vertex and all of it's child's $R_i$ to $A$. Update the values of all $R_i$ to be $max(R_i - 1, 0)$. We can achieve this using segment tree beats. The break condition is when $min_i > 0$, the tag condition is when $max_i = 0$. We are going to prove that is yields an average complexity of $log N$. We are using the jargon from https://www.youtube.com/watch?v=UJyBHCXa-1g: Assume $mark$ is the maximum $R_i$ of a subtree. If a vertex has mark $M$, all marks $M$ on its subtree is deleted. We define $F(X)$ as the number of vertices with mark $0$ on the $X$ subtree. We also define P as the sum of $F(X)$ for all $X$. Initially, $P = F(1) = 1$. We observe the change of $P$ for each query when we query in the subtree of $X$: We put tag $A$ of $X$. Note that this does not increase the value of $P$. However, this gives an important property: each nonzero mark can appear at most once at any given time. This does not hold if we flatten the tree. $P$ will increase at most $log N$ for each $mark$ that decreases from $1$ to $0$ from our subtraction update. Since there can be at most one mark $1$ at any given time, the maximum increase of $P$ is $log N$ per query. $P$ will decrease by at least $1$ for each extra node we visit. And this is the only way to decrease $P$. Since option $2$ is the only way to increase $P$, we find our maximum value of $P$ is $Q log N$. Since option $3$ is the only way to decrease $P$ and $P$ cannot be negative, we find the number of extra nodes we visit is at most $Q log N$, giving us a $Q log N$ solution. Note: it is possible to omit the lazy propagation by storing the last time each vertex is harvested, instead of $R_i$. Dropping lazy propagation will speed up the code almost two times faster! Since we are solving for each $A_i < \\sqrt{Q}$, the total complexity of this part is $O(Q \\sqrt{N} log N)$. Combining the two algorithms (heavy and light), we get the accepted solution. In practice, the optimal bucket size is arround $\\sqrt{Q}/2$, since STB has a larger constant factor. Sadly, it turns out a sophisticated $O(NQ)$ solution can pass. We should've made all $A's$ have the same value, so the solution is in $O(Q log N)$. Oh well, we hope this problem can be educational to you all :)",
    "code": "#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,sse4.1,sse4.2,popcnt,abm,mmx,avx,avx2,fma,tune=native\") \n \n#include <vector>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <algorithm>\n#include <assert.h>\nusing namespace std;\n \nconst int NMAX = 50010;\nvector <int> adia[NMAX];\nint ord[NMAX], last[NMAX], adancime[NMAX];\nint perioada[NMAX];\nint perioada_init[NMAX];\nint active[NMAX];\n \nvoid dfs(int nod, int& last_val, int h = 0)\n{\n\tord[nod] = last_val++;\n\tadancime[ord[nod]] = h;\n\tfor (auto i : adia[nod])\n\t\tdfs(i, last_val, h + 1);\n\tlast[ord[nod]] = last_val;\n}\n \nint main()\n{\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tint n, q;\n\tcin >> n >> q;\n\tfor (int i = 1; i <= n; i++)\n\t\tcin >> perioada_init[i];\n \n\tfor (int i = 2; i <= n; i++) {\n\t\tint tata;\n\t\tcin >> tata;\n\t\tadia[tata].push_back(i);\n\t}\n \n\tint last_val = 0;\n\tdfs(1, last_val);\n \n\tfor (int i = 1; i <= n; i++)\n\t\tperioada[ord[i]] = perioada_init[i];\n\t\n \tfor (int t = 0; t < q; t++) {\n\t\tint nod;\n\t\tcin >> nod;\n\t\tnod = ord[nod];\n\t\tint sum_h = 0, nr = 0;\n\t\tfor (int i = nod; i < last[nod]; i++) {\n\t\t\tint take = (active[i] <= t);\n\t\t\tsum_h += take * adancime[i];\n\t\t\tnr += take;\n\t\t\tactive[i] = active[i] * (1 - take) + (t + perioada[i]) * take;\n\t\t}\n\t\tsum_h -= nr * adancime[nod];\n\t\tcout << sum_h << ' ' << nr << '\\n';\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1426",
    "index": "A",
    "title": "Floor Number",
    "statement": "Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is $n$.\n\nThere is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains $2$ apartments, every other floor contains $x$ apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers $1$ and $2$, apartments on the second floor have numbers from $3$ to $(x + 2)$, apartments on the third floor have numbers from $(x + 3)$ to $(2 \\cdot x + 2)$, and so on.\n\nYour task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least $n$ apartments.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If $n \\le 2$ then the answer is $1$. Otherwise, you can \"remove\" the first floor and then the answer is $\\left\\lfloor\\frac{n - 3}{x}\\right\\rfloor + 2$.",
    "code": "for i in range(int(input())):\n    n, x = map(int, input().split())\n    print(1 if n <= 2 else (n - 3) // x + 2)",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1426",
    "index": "B",
    "title": "Symmetric Matrix",
    "statement": "Masha has $n$ types of tiles of size $2 \\times 2$. Each cell of the tile contains one integer. Masha has an \\textbf{infinite number} of tiles of each type.\n\nMasha decides to construct the square of size $m \\times m$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.\n\nSymmetric with respect to the main diagonal matrix is such a square $s$ that for each pair $(i, j)$ the condition $s[i][j] = s[j][i]$ holds. I.e. it is true that the element written in the $i$-row and $j$-th column equals to the element written in the $j$-th row and $i$-th column.\n\nYour task is to determine if Masha can construct a square of size $m \\times m$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she \\textbf{can not} rotate tiles, she can only place them in the orientation they have in the input.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, if $m$ is odd then the answer is \"NO\" by obvious reasons. Otherwise, we can notice that the top left and the bottom right values of the tile do not matter (since we can place tiles symmetrically). So we only need to check that there is some tile that its top right value equals its bottom left value (because this is how we get main diagonal symmetry).",
    "code": "for i in range(int(input())):\n\tn, m = map(int, input().split())\n\ta = []\n\tfor i in range(n):\n\t\ta.append([[int(x) for x in input().split()] for i in range(2)])\n\tok = False\n\tfor i in range(n):\n\t\tok |= a[i][0][1] == a[i][1][0]\n\tok &= m % 2 == 0\n\tprint(\"YES\" if ok else \"NO\") ",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1426",
    "index": "C",
    "title": "Increase and Copy",
    "statement": "Initially, you have the array $a$ consisting of one element $1$ ($a = [1]$).\n\nIn one move, you can do one of the following things:\n\n- Increase some (\\textbf{single}) element of $a$ by $1$ (choose some $i$ from $1$ to the current length of $a$ and increase $a_i$ by one);\n- Append the copy of some (\\textbf{single}) element of $a$ to the end of the array (choose some $i$ from $1$ to the current length of $a$ and append $a_i$ to the end of the array).\n\nFor example, consider the sequence of five moves:\n\n- You take the first element $a_1$, append its copy to the end of the array and get $a = [1, 1]$.\n- You take the first element $a_1$, increase it by $1$ and get $a = [2, 1]$.\n- You take the second element $a_2$, append its copy to the end of the array and get $a = [2, 1, 1]$.\n- You take the first element $a_1$, append its copy to the end of the array and get $a = [2, 1, 1, 2]$.\n- You take the fourth element $a_4$, increase it by $1$ and get $a = [2, 1, 1, 3]$.\n\nYour task is to find the \\textbf{minimum} number of moves required to obtain the array with the sum at least $n$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "It is pretty intuitive that we firstly need to do all increments and only then copy numbers (because otherwise we can swap the order of moves and the sum will not decrease). You could notice that the answer does not exceed $O(\\sqrt{n})$ so we can just iterate from $1$ to $\\left\\lfloor\\sqrt{n}\\right\\rfloor$ and fix the number we will copy. Let it be $x$. Then we need $x-1$ moves to obtain it and also need $\\left\\lceil\\frac{n-x}{x}\\right\\rceil$ moves to get the enough number of copies. So, we can update the answer with this number of moves. Time complexity: $O(\\sqrt{n})$ per test case. Actually, the required number is always pretty near to $\\left\\lfloor\\sqrt{n}\\right\\rfloor$ so it is enough to try a few options in range $[\\left\\lfloor\\sqrt{n}\\right\\rfloor - 5; \\left\\lfloor\\sqrt{n}\\right\\rfloor + 5]$ to get the optimal answer. This is $O(1)$ solution.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst long double EPS = 1e-9;\n\nlong long f(long long x)\n{                                                        \n\tlong long z = sqrtl(x);\n\tlong long ans = 1e18;\n\tfor(int i = -5; i <= 5; i++)\n\t{\n\t \tlong long z2 = z - i;\n\t \tif(z2 > x || z2 < 1)\n\t \t\tcontinue;\n\t \tans = min(ans, z2 - 2 + (x + z2 - 1) / z2);\n\t}\n\treturn ans;\n}\n\nint main()\n{\n \tint t;\n \tcin >> t;\n \tfor(int i = 0; i < t; i++)\n \t{\n \t \tlong long x;\n \t \tcin >> x;\n \t \tcout << f(x) << endl;\n \t}\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1426",
    "index": "D",
    "title": "Non-zero Segments",
    "statement": "Kolya got an integer array $a_1, a_2, \\dots, a_n$. The array can contain both positive and negative integers, but Kolya doesn't like $0$, so the array doesn't contain any zeros.\n\nKolya doesn't like that the sum of some subsegments of his array can be $0$. The subsegment is some consecutive segment of elements of the array.\n\nYou have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum $0$. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, $0$, any by absolute value, even such a huge that they can't be represented in most standard programming languages).\n\nYour task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $0$.",
    "tutorial": "Firstly, let's understand that the sum of the segment $[l; r]$ is zero if $p_r - p_{l - 1}$ is zero (in other words, $p_{l - 1} = p_r$), where $p_i$ is the sum of the first $i$ elements ($p_0 = 0$). Let's iterate over elements from left to right and add all prefix sums in the set. If we get the sum that is already in the set, we get some segment with sum $0$, and we need to fix it somehow. Let's insert some huge number before the current element in such a way that all prefix sums starting from the current element to the end will be significantly bigger than all prefix sums to the left. In words of implementation, we just get rid of all prefix sums to the left (clear the set) and continue doing the same process starting from the current element (so we just cut off the prefix of the array). This way is optimal because we remove all segments with sum $0$ ending at the current element using only one insertion (and we need to use at least one insertion to do that). Time complexity: $O(n \\log{n})$.",
    "code": "n = int(input())\na = [int(x) for x in input().split()]\nd = set()\nd.add(0)\ncur = 0\nans = 0\nfor i in range(n):\n\tcur += a[i]\n\tif cur in d:\n\t\tans += 1\n\t\td = set()\n\t\td.add(0)\n\t\tcur = a[i]\n\td.add(cur)\nprint(ans)",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1426",
    "index": "E",
    "title": "Rock, Paper, Scissors",
    "statement": "Alice and Bob have decided to play the game \"Rock, Paper, Scissors\".\n\nThe game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a draw. Otherwise, the following rules applied:\n\n- if one player showed rock and the other one showed scissors, then the player who showed rock is considered the winner and the other one is considered the loser;\n- if one player showed scissors and the other one showed paper, then the player who showed scissors is considered the winner and the other one is considered the loser;\n- if one player showed paper and the other one showed rock, then the player who showed paper is considered the winner and the other one is considered the loser.\n\nAlice and Bob decided to play exactly $n$ rounds of the game described above. Alice decided to show rock $a_1$ times, show scissors $a_2$ times and show paper $a_3$ times. Bob decided to show rock $b_1$ times, show scissors $b_2$ times and show paper $b_3$ times. Though, both Alice and Bob \\textbf{did not choose} the sequence in which they show things. It is guaranteed that $a_1 + a_2 + a_3 = n$ and $b_1 + b_2 + b_3 = n$.\n\nYour task is to find two numbers:\n\n- the minimum number of round Alice can win;\n- the maximum number of rounds Alice can win.",
    "tutorial": "The maximum number of rounds Alice can win is pretty easy to calculate greedily: $min(a_1, b_2) + min(a_2, b_3) + min(a_3, b_1)$. What about the minimum number of rounds? It can be shown that if we started using some combination we are better to end it before using the other one. There are six possible combinations to not win the round: $a_1$ and $b_1$. $a_2$ and $b_2$. $a_3$ and $b_3$. $a_1$ and $b_3$. $a_2$ and $b_1$. $a_3$ and $b_2$. We can iterate over all permutations of these combinations (there are $6! = 720$ possible permutations) and greedily apply them. Use the first while it is possible, then the second, and so on, and find the best answer. It is also possible that the order of these combinations does not matter, but we didn't prove that fact. Time complexity: $O(1)$.",
    "code": "#include <bits/stdc++.h>\n\n#define sz(v) int(v.size())\n#define all(v) v.begin(), v.end()\n#define pb push_back\n#define ft first\n#define sc second\n\nusing namespace std;\n\nint n;\nvector<int> a, b;\n\ninline void read() {\n\tcin >> n;\n\ta.resize(3);\n\tb.resize(3);\n\tfor (int i = 0; i < 3; i++) cin >> a[i];\n\tfor (int i = 0; i < 3; i++) cin >> b[i];\n}\n\t\ninline void solve() {\n\tint ans1 = INT_MAX;\n\tvector<pair<int, int> > ord;\n\tord.pb({0, 0});\n\tord.pb({0, 2});\n\tord.pb({1, 1});\n\tord.pb({1, 0});\n\tord.pb({2, 2});\n\tord.pb({2, 1});\n\tsort(all(ord));\n\tdo {\n\t\tvector<int> a1 = a, b1 = b;\n\t\tfor (int i = 0; i < sz(ord); i++) {\n\t\t\tint cnt = min(a1[ord[i].ft], b1[ord[i].sc]);\n\t\t\ta1[ord[i].ft] -= cnt;\n\t\t\tb1[ord[i].sc] -= cnt;\t\t\t\n\t\t}\n\t\tint cur = min(a1[0], b1[1]) + min(a1[1], b1[2]) + min(a1[2], b1[0]);\n\t\tans1 = min(ans1, cur);\n\t} while(next_permutation(all(ord)));\n\tint ans2 = min(a[0], b[1]) + min(a[1], b[2]) + min(a[2], b[0]);\n\tcout << ans1 << ' ' << ans2 << endl;\n}\n\nint main () {\n    read();\n    solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "flows",
      "greedy",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1426",
    "index": "F",
    "title": "Number of Subsequences",
    "statement": "You are given a string $s$ consisting of lowercase Latin letters \"a\", \"b\" and \"c\" and question marks \"?\".\n\nLet the number of question marks in the string $s$ be $k$. Let's replace each question mark with one of the letters \"a\", \"b\" and \"c\". Here we can obtain all $3^{k}$ possible strings consisting only of letters \"a\", \"b\" and \"c\". For example, if $s = $\"ac?b?c\" then we can obtain the following strings: $[$\"acabac\", \"acabbc\", \"acabcc\", \"acbbac\", \"acbbbc\", \"acbbcc\", \"accbac\", \"accbbc\", \"accbcc\"$]$.\n\nYour task is to count the total number of subsequences \"abc\" in all resulting strings. Since the answer can be very large, print it modulo $10^{9} + 7$.\n\nA subsequence of the string $t$ is such a sequence that can be derived from the string $t$ after removing some (possibly, zero) number of letters without changing the order of remaining letters. For example, the string \"baacbc\" contains two subsequences \"abc\" — a subsequence consisting of letters at positions $(2, 5, 6)$ and a subsequence consisting of letters at positions $(3, 5, 6)$.",
    "tutorial": "There are several more or less complicated combinatorial solutions to this problem, but I will describe a dynamic programming one which, I think, is way easier to understand and to implement. Suppose we have fixed the positions of a, b and c that compose the subsequence (let these positions be $p_a$, $p_b$ and $p_c$). How many strings contain the required subsequence on these positions? Obviously, if some of these characters is already not a question mark and does not match the expected character on that position, the number of strings containing the subsequence on that position is $0$. Otherwise, since we have fixed three characters, all question marks on other positions can be anything we want - so the number of such strings is $3^x$, where $x$ is the number of question marks on positions other than $p_a$, $p_b$ and $p_c$. It allows us to write an $O(n^3)$ solution by iterating on $p_a$, $p_b$ and $p_c$, and for every such triple, calculating the number of strings containing the required subsequence on those positions. But that's too slow. Let's notice that, for every such subsequence, the number of strings containing it is $3^{k - qPos({p_a, p_b, p_c})}$, where $qPos({p_a, p_b, p_c})$ is the number of positions from ${p_a, p_b, p_c}$ that contain a question mark. So, for each integer $i$ from $0$ to $3$, let's calculate the number of subsequences matching abc that contain exactly $i$ question marks - and that will allow us to solve the problem faster. How can we calculate the required number of subsequences for every $i$? In my opinion, the simplest way is dynamic programming: let $dp_{i, j, k}$ be the number of subsequences of $s$ that end up in position $i$, match $j$ first characters of abc and contain $k$ question marks. The transitions in this dynamic programming are quadratic (since we have to iterate on the next/previous position from the subsequence), but can be sped up to linear if we rewrite $dp_{i, j, k}$ as the number of subsequences of $s$ that end up in position not later than $i$, match $j$ first characters of abc and contain $k$ question marks. Each transition is either to take the current character or to skip it, so they can be modeled in $O(1)$, and overall this dynamic programming solution works in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n                            \nusing namespace std;\n\nconst int MOD = int(1e9) + 7;\nconst int N = 200043;\nconst int K = 4;\n\nint add(int x, int y)\n{\n \tx += y;\n \twhile(x >= MOD) x -= MOD;\n \twhile(x < 0) x += MOD;\n \treturn x;\n}\n\nint mul(int x, int y)\n{\n \treturn (x * 1ll * y) % MOD;\n}\n\nint n;\nstring s;\nint dp[N][K][K];\nchar buf[N];\nint pow3[N];\n\nint main() {\n\tscanf(\"%d\", &n);\n\tscanf(\"%s\", buf);\n\ts = buf;\n\tint cntQ = 0;\n\tfor(auto c : s)\n\t\tif(c == '?')\n\t\t\tcntQ++;\n\tpow3[0] = 1;\n\tfor(int i = 1; i < N; i++)\n\t\tpow3[i] = mul(pow3[i - 1], 3);\n\tdp[0][0][0] = 1;\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j <= 3; j++)\n\t\t\tfor(int k = 0; k <= 3; k++)\n\t\t\t{\n\t\t\t \tif(!dp[i][j][k]) continue;\n\t\t\t \tdp[i + 1][j][k] = add(dp[i + 1][j][k], dp[i][j][k]);\n\t\t\t \tif(j < 3 && (s[i] == '?' || s[i] - 'a' == j))\n\t\t\t \t{\n\t\t\t \t \tint nk = (s[i] == '?' ? k + 1 : k);\n\t\t\t \t \tdp[i + 1][j + 1][nk] = add(dp[i + 1][j + 1][nk], dp[i][j][k]);\n\t\t\t \t}\n\t\t   \t}\n\tint ans = 0;\n\tfor(int i = 0; i <= 3; i++)\n\t\tif(cntQ >= i)\n\t\t\tans = add(ans, mul(dp[n][3][i], pow3[cntQ - i]));\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "combinatorics",
      "dp",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1427",
    "index": "A",
    "title": "Avoiding Zero",
    "statement": "You are given an array of $n$ integers $a_1,a_2,\\dots,a_n$.\n\nYou have to create an array of $n$ integers $b_1,b_2,\\dots,b_n$ such that:\n\n- The array $b$ is a rearrangement of the array $a$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $\\{a_1,a_2,\\dots,a_n\\}$ and $\\{b_1,b_2,\\dots,b_n\\}$ are equal.For example, if $a=[1,-1,0,1]$, then $b=[-1,1,1,0]$ and $b=[0,1,-1,1]$ are rearrangements of $a$, but $b=[1,-1,-1,0]$ and $b=[1,0,2,-3]$ are not rearrangements of $a$.\n- For all $k=1,2,\\dots,n$ the sum of the first $k$ elements of $b$ is nonzero. Formally, for all $k=1,2,\\dots,n$, it must hold $$b_1+b_2+\\cdots+b_k\\not=0\\,.$$\n\nIf an array $b_1,b_2,\\dots, b_n$ with the required properties does not exist, you have to print NO.",
    "tutorial": "First of all, notice that if the sum $a_1+a_2+\\cdots+a_n$ is $0$, then, since $b$ is a rearrangement of $a$, it holds $b_1+b_2+\\cdots+b_n=0$ and therefore the answer is NO. On the other hand, if $a_1+a_2+\\cdots+a_n\\not=0$, then there is a valid array $b$. To show this, let us consider two cases. If $a_1+a_2+\\cdots+a_n > 0$, then $b$ can be chosen as the array $a$ sorted in decreasing order. In this way, for any $k=1,\\dots, n$, it holds $b_{1}+\\cdots+b_{k} > 0$. Let us prove it by dividing in two cases. If $b_{k}>0$, then also $b_{1},\\dots,b_{k-1}$ are positive and therefore the sum is positive. If $b_{k}\\le 0$, then also $b_{k+1},\\dots,b_{n}$ are nonpositive and therefore $b_{1}+\\cdots+b_{k} = b_{1}+\\cdots+b_{n} - (b_{k+1}+\\cdots+b_{n}) \\ge b_{1}+\\cdots+b_{n} > 0\\,.$ If $b_{k}>0$, then also $b_{1},\\dots,b_{k-1}$ are positive and therefore the sum is positive. If $b_{k}\\le 0$, then also $b_{k+1},\\dots,b_{n}$ are nonpositive and therefore $b_{1}+\\cdots+b_{k} = b_{1}+\\cdots+b_{n} - (b_{k+1}+\\cdots+b_{n}) \\ge b_{1}+\\cdots+b_{n} > 0\\,.$ $b_{1}+\\cdots+b_{k} = b_{1}+\\cdots+b_{n} - (b_{k+1}+\\cdots+b_{n}) \\ge b_{1}+\\cdots+b_{n} > 0\\,.$ If $a_1+a_2+\\cdots+a_n < 0$, then $b$ can be chosen as the array $a$ sorted in increasing order. The proof that this choice works is analogous to the previous case. Alternative, randomized solution If the sum $a_1+\\cdots+a_n=0$, then the answer is NO (as explained in the previous solution). Otherwise, we repeatedly random shuffle the cities until all the conditions are satisfied. It can be proven that a random shuffle works with probability $\\ge\\frac1n$ (see this comment for a neat proof). Notice that the probability is exactly $\\frac1n$ in at least two cases: $a_1=a_2=\\cdots=a_{n-1}=0$ and $a_n=1$. $a_1=a_2=\\cdots=a_{m+1}=1$ and $a_{m+2}=a_{m+3}=\\cdots=a_{2m+1}=-1$ (and $n=2m+1$).",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \nvector<int> SortIndex(int size, std::function<bool(int, int)> compare) {\n    vector<int> ord(size);\n    for (int i = 0; i < size; i++) ord[i] = i;\n    sort(ord.begin(), ord.end(), compare);\n    return ord;\n}\n \ntemplate <typename T>\nbool MinPlace(T& a, const T& b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename T>\nbool MaxPlace(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \nmap<vector<int>, string> samples = {\n    {{1, -2, 3, -4}, \"1 -2 3 -4\"},\n    {{1, -1, 1, -1, 1}, \"1 1 -1 1 -1\"},\n    {{40, -31, -9, 0, 13, -40}, \"-40 13 40 0 -9 -31\"}\n};\n \nbool is_sample(const vector<int>& a) {\n    if (!samples.count(a)) return false;\n    cout << samples[a] << \"\\n\";\n    return true;\n}\n \n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n \n    int T;\n    cin >> T;\n    for (int t = 1; t <= T; t++) {\n        int N;\n        cin >> N;\n        vector<int> a(N);\n        int sum = 0;\n        for (int i = 0; i < N; i++) cin >> a[i], sum += a[i];\n        if (sum == 0) {\n            cout << \"NO\\n\";\n            continue;\n        }\n        cout << \"YES\\n\";\n \n        if (is_sample(a)) continue;\n        sort(a.begin(), a.end());\n        if (sum > 0) reverse(a.begin(), a.end());\n        for (int x: a) cout << x << \" \";\n        cout << \"\\n\";\n    }\n}",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1427",
    "index": "B",
    "title": "Chess Cheater",
    "statement": "You like playing chess tournaments online.\n\nIn your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a \"previous game\").\n\nThe outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.\n\nAfter the tournament, you notice a bug on the website that allows you to change the outcome of \\textbf{at most} $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.\n\nCompute the maximum score you can get by cheating in the optimal way.",
    "tutorial": "Notice that the score is equal to $\\texttt{score} = 2\\cdot\\texttt{#\\{wins\\}} - \\texttt{#\\{winning_streaks\\}}\\,,$ In the explanation that follows, the variables $\\texttt{#\\{wins\\}}$, $\\texttt{#\\{winning_streaks\\}}$ are always related to the initial situation. If $k+\\texttt{#\\{wins\\}}\\ge n$, then it is possible to win all games and therefore the answer is $2n-1$. Otherwise, it is clear that we want to transform $k$ losses in $k$ wins. Thus, after the cheating, the number of wins will be $k+\\texttt{#\\{wins\\}}$. Considering the formula above, it remains only to minimize the number of winning streaks. How can we minimize the number of winning streaks? It is very intuitive that we shall \"fill\" the gaps between consecutive winning streaks starting from the shortest gap in increasing order of length. This can be proven noticing that if $g$ gaps are not filled (i.e., after cheating this $g$ gaps still contain at least one loss each) then there are at least $g+1$ winning streaks. The implementation goes as follows. With a linear scan we find the lengths of the gaps and then we sort them. Finally we count how many we can select with a sum of lengths $\\le k$. The answer is $2\\cdot\\big(k+\\texttt{#\\{wins\\}}\\big) - \\texttt{#\\{winning_streaks\\}} + \\texttt{#\\{gaps_we_can_fill\\}} \\,.$ The complexity of the solution is $O(n\\log(n))$.",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \nvector<int> SortIndex(int size, std::function<bool(int, int)> compare) {\n    vector<int> ord(size);\n    for (int i = 0; i < size; i++) ord[i] = i;\n    sort(ord.begin(), ord.end(), compare);\n    return ord;\n}\n \ntemplate <typename T>\nbool MinPlace(T& a, const T& b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename T>\nbool MaxPlace(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n \n    int T;\n    cin >> T;\n    for (int t = 1; t <= T; t++) {\n        int N, K;\n        cin >> N >> K;\n        string S;\n        cin >> S;\n        int winning_streaks_cnt = 0;\n        int wins = 0;\n        int losses = 0;\n        vector<int> losing_streaks; \n        for (int i = 0; i < N; i++) {\n            if (S[i] == 'W') {\n                wins++;\n                if (i == 0 or S[i-1] == 'L') winning_streaks_cnt++;\n            }\n            if (S[i] == 'L') {\n                losses++;\n                if (i == 0 or S[i-1] == 'W') losing_streaks.push_back(0);\n                losing_streaks.back()++;\n            }\n        }\n        if (K >= losses) {\n            cout << 2*N-1 << \"\\n\";\n            continue;\n        }\n        if (wins == 0) {\n            if (K == 0) cout << 0 << \"\\n\";\n            else cout << 2*K-1 << \"\\n\";\n            continue;\n        }\n        if (S[0] == 'L') losing_streaks[0] = 1e8;\n        if (S[N-1] == 'L') losing_streaks.back() = 1e8;\n        sort(losing_streaks.begin(), losing_streaks.end());\n        wins += K;\n        for (int ls: losing_streaks) {\n            if (ls > K) break;\n            K -= ls;\n            winning_streaks_cnt--;\n        }\n        cout << 2*wins - winning_streaks_cnt << \"\\n\";\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1427",
    "index": "C",
    "title": "The Hard Work of Paparazzi",
    "statement": "You are a paparazzi working in Manhattan.\n\nManhattan has $r$ south-to-north streets, denoted by numbers $1, 2,\\ldots, r$ in order from west to east, and $r$ west-to-east streets, denoted by numbers $1,2,\\ldots,r$ in order from south to north. Each of the $r$ south-to-north streets intersects each of the $r$ west-to-east streets; the intersection between the $x$-th south-to-north street and the $y$-th west-to-east street is denoted by $(x, y)$. In order to move from the intersection $(x,y)$ to the intersection $(x', y')$ you need $|x-x'|+|y-y'|$ minutes.\n\nYou know about the presence of $n$ celebrities in the city and you want to take photos of as many of them as possible. More precisely, for each $i=1,\\dots, n$, you know that the $i$-th celebrity will be at the intersection $(x_i, y_i)$ in exactly $t_i$ minutes from now (and he will stay there for a very short time, so you may take a photo of him only if at the $t_i$-th minute from now you are at the intersection $(x_i, y_i)$). You are very good at your job, so you are able to take photos instantaneously. You know that $t_i < t_{i+1}$ for any $i=1,2,\\ldots, n-1$.\n\nCurrently you are at your office, which is located at the intersection $(1, 1)$. If you plan your working day optimally, what is the maximum number of celebrities you can take a photo of?",
    "tutorial": "This is a classical dynamic-programming task with a twist. For the solution to work it is fundamental that the city has a small diameter (i.e., $r$ shall not be large) and that there are not simultaneous appearances. We say that two celebrities $i<j$ are compatible if it is possible to take a photo of both, that is $|x_i-x_j| + |y_i-y_j| \\le t_j-t_i\\,.$ Let $ans_k$ be the maximum number of photos we can take of the first $k$ celebrities assuming that we take a photo of celebrity $k$ (if we cannot take a photo of celebrity $k$, then $ans_k:=-\\infty$). It holds (assuming that we can take a photo of celebrity $k$) $ans_k = 1 + \\max\\Big(0, \\max_{\\substack{1\\le i < k,\\\\ \\text{$i$ is compatible with $k$}}} ans_i\\Big)\\,.$ How can we speed up this algorithm? The idea is that if $|k-i|$ is big, then $i$ and $k$ are always compatible. More precisely, if $k - i \\ge 2r$ then $t_k-t_i \\ge 2r$ (because there are no simultaneous appearances) and therefore $|x_i-x_k| + |y_i-y_k| \\le 2r \\le t_k-t_i\\,,$ $ans_k = 1 + \\max\\Big(0, \\max_{1\\le i \\le k-2r} ans_i, \\max_{\\substack{k-2r< i < k,\\\\ \\text{$i$ is_compatible_with $k$}}} ans_i\\Big)\\,.$ Alternative optimization It is also true that any optimal solution does not skip more than $4r$ consecutive celebrities (we leave the proof to the reader). Hence another possible optimization of the naive formula is to take the maximum only over $k-4r\\le i < k$.",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \nvector<int> SortIndex(int size, std::function<bool(int, int)> compare) {\n    vector<int> ord(size);\n    for (int i = 0; i < size; i++) ord[i] = i;\n    sort(ord.begin(), ord.end(), compare);\n    return ord;\n}\n \ntemplate <typename T>\nbool MinPlace(T& a, const T& b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename T>\nbool MaxPlace(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \nconst int MAXN = 1e5 + 100;\nint t[MAXN];\nint x[MAXN], y[MAXN];\nint ans[MAXN];\nint max_ans[MAXN];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n \n    x[0] = 1, y[0] = 1;\n \n    int R, N;\n    cin >> R >> N;\n    for (int i = 1; i <= N; i++) {\n        cin >> t[i] >> x[i] >> y[i];\n        ans[i] = -1e9;\n        for (int j = max(i-2*R, 0); j < i; j++) {\n            if (abs(x[i]-x[j]) + abs(y[i]-y[j]) <= t[i]-t[j])\n                ans[i] = max(ans[i], 1 + ans[j]);\n        }\n        if (i > 2*R) ans[i] = max(ans[i], 1 + max_ans[i-2*R]);\n \n        max_ans[i] = max(ans[i], max_ans[i-1]);\n    }\n    cout << max_ans[N] << \"\\n\";\n}",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1427",
    "index": "D",
    "title": "Unshuffling a Deck",
    "statement": "You are given a deck of $n$ cards numbered from $1$ to $n$ (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.\n\n- Choose $2 \\le k \\le n$ and split the deck in $k$ nonempty contiguous parts $D_1, D_2,\\dots, D_k$ ($D_1$ contains the first $|D_1|$ cards of the deck, $D_2$ contains the following $|D_2|$ cards and so on). Then reverse the order of the parts, transforming the deck into $D_k, D_{k-1}, \\dots, D_2, D_1$ (so, the first $|D_k|$ cards of the new deck are $D_k$, the following $|D_{k-1}|$ cards are $D_{k-1}$ and so on). The internal order of each packet of cards $D_i$ is unchanged by the operation.\n\nYou have to obtain a sorted deck (i.e., a deck where the first card is $1$, the second is $2$ and so on) performing at most $n$ operations. It can be proven that it is always possible to sort the deck performing at most $n$ operations.\n\n\\textbf{Examples of operation:} The following are three examples of valid operations (on three decks with different sizes).\n\n- If the deck is [3 6 2 1 4 5 7] (so $3$ is the first card and $7$ is the last card), we may apply the operation with $k=4$ and $D_1=$[3 6], $D_2=$[2 1 4], $D_3=$[5], $D_4=$[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].\n- If the deck is [3 1 2], we may apply the operation with $k=3$ and $D_1=$[3], $D_2=$[1], $D_3=$[2]. Doing so, the deck becomes [2 1 3].\n- If the deck is [5 1 2 4 3 6], we may apply the operation with $k=2$ and $D_1=$[5 1], $D_2=$[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].",
    "tutorial": "We say that a pair of consecutive cards in the deck is good if they have consecutive numbers (in the right order). Let $m$ be the number of good pairs. We show that, if the deck is not sorted, with one move we can increase $m$. Hence after at most $n-1$ moves it will hold $m=n-1$ and the deck will be sorted. Since the deck is not sorted, there must be two indices $i<j$ such that $c_i=c_j+1$. Moreover, since $c_i > c_j$, there is $i\\le t<j$ such that $c_t > c_{t+1}$. We split the deck as (with $k=4$ packets, or less if some of the packets are empty) $D_1=[c_1,c_2,\\dots,c_{i-1}],\\ D_2=[c_i,c_{i+1},\\dots, c_t],\\ D_3=[c_{t+1},c_{t+2},\\dots, c_j],\\ D_4=[c_{j+1},c_{j+2},\\dots, c_n]$ $[c_{j+1},c_{j+2},\\dots, c_n, c_{t+1},c_{t+2},\\dots, c_j, c_i,c_{i+1},\\dots, c_t, c_1,c_2,\\dots,c_{i-1}]\\,.$ The limit on $n$ is so small that fundamentally any polynomial implementation gets accepted. Producing an $O(n^2)$ implementation is trivial, but it should also be possible to produce a pseudo-linear implementation.",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \nvector<int> SortIndex(int size, std::function<bool(int, int)> compare) {\n    vector<int> ord(size);\n    for (int i = 0; i < size; i++) ord[i] = i;\n    sort(ord.begin(), ord.end(), compare);\n    return ord;\n}\n \ntemplate <typename T>\nbool MinPlace(T& a, const T& b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename T>\nbool MaxPlace(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \n \nmap<vector<int>, string> samples = {\n    {{3, 1, 2, 4}, \"2\\n3 1 2 1\\n2 1 3\"},\n    {{6, 5, 4, 3, 2, 1}, \"1\\n6 1 1 1 1 1 1\"}\n};\n \nconst int MAXN = 52;\nint N;\nint deck[MAXN];\nint new_deck[MAXN];\n \nbool is_sample() {\n    vector<int> vec(deck, deck+N);\n    if (!samples.count(vec)) return false;\n    cout << samples[vec] << \"\\n\";\n    return true;\n}\n \nvoid make_op(vector<int> D) {\n    int sum = 0;\n    for (int d: D) {\n        for (int i = 0; i < d; i++) new_deck[N-sum-d+i] = deck[sum + i];\n        sum += d;\n    }\n    assert(sum == N);\n    for (int i = 0; i < N; i++) deck[i] = new_deck[i];\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n \n    cin >> N;\n    for (int i = 0; i < N; i++) cin >> deck[i];\n \n    if (is_sample()) return 0;\n \n    vector<vector<int>> ops;\n    while (1) {\n        vector<int> op;\n        for (int i = 0; i < N; i++) {\n            if (deck[i] == i+1) continue;\n            if (i != 0) op.push_back(i);\n            for (int j = i+1; j < N; j++) {\n                if (deck[j] == deck[j-1] + 1) continue;\n                op.push_back(j-i);\n                for (int k = j; k < N; k++) {\n                    if (deck[k] != deck[i]-1) continue;\n                    op.push_back(k-j+1);\n                    if (k < N-1) op.push_back(N-1-k);\n                    break;\n                }\n                break;\n            }\n            break;\n        }\n        if (op.empty()) break;\n        ops.push_back(op);\n        make_op(op);\n    }\n \n    cout << ops.size() << \"\\n\";\n    for (auto op: ops) {\n        cout << op.size() << \" \";\n        for (int x: op) cout << x << \" \";\n        cout << \"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1427",
    "index": "E",
    "title": "Xum",
    "statement": "You have a blackboard and initially only an \\textbf{odd} number $x$ is written on it. Your goal is to write the number $1$ on the blackboard.\n\nYou may write new numbers on the blackboard with the following two operations.\n\n- You may take two numbers (not necessarily distinct) already on the blackboard and write their sum on the blackboard. The two numbers you have chosen remain on the blackboard.\n- You may take two numbers (not necessarily distinct) already on the blackboard and write their bitwise XOR on the blackboard. The two numbers you have chosen remain on the blackboard.\n\nPerform a sequence of operations such that at the end the number $1$ is on the blackboard.",
    "tutorial": "We present two different solutions. The first solution is by Anton, the second is mine. The first solution is deterministic, it is fundamentally based on Bezout's Theorem and comes with a proof. It performs $\\approx 100$ operations and writes numbers up to $O(x^3)$. The second solution is randomized, uses some xor-linear-algebra and comes without a proof. It performs $\\approx 1000$ operations and writes numbers up to $O(x^2)$. Deterministic, provable, \"gcd\" solution Step 0: If $u$ is written on the blackboard, then we can write $nu$ on the blackboard with $O(\\log(n))$ operations. How? Just using the sum operation as in the binary exponentiation (same algorithm, just replace multiplication with addition and exponentiation with multiplication). Step 1: Write on the blackboard a number $y$ coprime with $x$. Let $e\\in\\mathbb N$ be the largest integer such that $2^e\\le x$ (i.e., $2^e$ is the largest bit of $x$). Notice that $y=(2^ex)\\wedge x = (2^e+1)x - 2^{e+1}$ and therefore $gcd(x,y)=gcd(x,2^{e+1})=1$. Step 2: Write $1=gcd(x,y)$ on the blackboard. Let $a, b\\ge 0$ be such that $ax-by=1$ ($a,b$ exist thanks to Bezout's theorem) with $b$ even (if $b$ is odd, we can add $y$ to $a$ and $x$ to $b$, getting an even $b$). Since $by$ is even, we have $ax\\wedge by = 1$ and therefore we are able to write $1$ on the blackboard. Randomized, unproven, linear-algebraic solution We are going to talk about subspaces and basis; they shall be understood with respect to the operation xor on nonnegative integers. The rough idea is to sample randomly two numbers from the subspace generated by the numbers currently on the blackboard and write their sum on the blackboard. First, we choose the maximum number of bits $L$ that any number on the blackboard will ever have. A good choice is $2^L > x^2$ ($L=40$ works for any odd $x$ below $10^6$). We iterate the following process until $1$ belongs to the subspace generated by the numbers written on the blackboard. Let $S$ be the subspace generated by the numbers currently on the blackboard (i.e., the set of numbers that can be written as the xor of some numbers on the blackboard). Let $b_1,\\dots, b_k$ be a basis for $S$. Randomly choosing $k$ bits $e_1,\\dots,e_k$ we can produce a random element in $S$ as $(e_1b_1)\\wedge(e_2b_2)\\wedge\\cdots \\wedge(e_kb_k) \\,.$ If $u+v \\ge 2^L$, we choose a different pair of numbers. If $u+v\\in S$ (we can check this in $O(k)$ since we know a basis for $S$), we choose a different pair of numbers. Otherwise, we add $u+v$ to $S$ and update the basis accordingly. It turns out that this approach solves all odd values $3\\le x\\le 999,999$ instantaneously. Could we choose a much smaller $L$? The answer is no. If $x=2^{19}+1$ then there is a xor-subspace $S$ that contains $x$ and such that if $u,v\\in S$ and $u+v<2^{38}$ then $u+v\\in S$. Notice that this implies that any strategy needs to write on the blackboard some \"some big numbers\". This is why any approach that avoids large numbers by design is doomed to fail. Comment: Why should this solution work? Fundamentally, and this is the main idea of the problem, because the two operations $+$ and $\\wedge$ are not related by any strange hidden structure. It would be a miracle if we could find a very big subspace for $\\wedge$ that is closed also for $+$. And, since miracles are rare, here there is no miracle. It should not be very hard to show that this solution works for any odd $x$, i.e. there is not a subspace that contains $x$ and is closed for sums that are below $2^L$ (if $2^L>x^2$). Nonetheless, I could not show it. On the other hand, I think that proving that this solution has a very good (expected) time-complexity is very hard, but I would be happy if someone proves me wrong.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \nvector<int> SortIndex(int size, std::function<bool(int, int)> compare) {\n    vector<int> ord(size);\n    for (int i = 0; i < size; i++) ord[i] = i;\n    sort(ord.begin(), ord.end(), compare);\n    return ord;\n}\n \ntemplate <typename T>\nbool MinPlace(T& a, const T& b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename T>\nbool MaxPlace(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \nLL Inverse(LL n, LL m) {\n    n %= m;\n    if (n <= 1) return n; // Handles properly (n = 0, m = 1).\n    return m - ((m * Inverse(m, n) - 1) / n);\n}\n \n \nvector<ULL> A;\nvector<char> op;\nvector<ULL> B;\n \nvoid add_op(ULL a, char o, ULL b) {\n    if (a == 0 or b == 0) return;\n    A.push_back(a);\n    op.push_back(o);\n    B.push_back(b);\n}\n \nULL xxor(ULL a, ULL b) {\n    add_op(a, '^', b);\n    return a^b;\n}\n \nULL sum(ULL a, ULL b) {\n    add_op(a, '+', b);\n    return a+b;\n}\n \nULL mul(ULL a, ULL n) {\n    ULL pot = a;\n    ULL curr = 0;\n    while (n > 0) {\n        if (n%2) curr = sum(curr, pot);\n        pot = sum(pot, pot);\n        n /= 2;\n    }\n    return curr;\n}\n \nint main() {\n    ULL x;\n    cin >> x;\n    while (x != 1) {\n        for (ULL n = 2; ; n *= 2) {\n            sum((n/2)*x, (n/2)*x);\n            if (((n*x)^x)%x == 0) continue;\n            ULL y = xxor(n*x, x);\n            ULL g = __gcd(x, y);\n            ULL a = mul(x, Inverse(x/g, y/g));\n            ULL b = mul(y, (a-g)/y);\n            ULL pot = 1<<20; // must be larger than g\n            ULL q = (pot- b%pot) * Inverse(x, pot) % pot;\n            ULL c = mul(x, q);\n            x = xxor(sum(a, c), sum(b, c));\n            break;\n        }\n    }\n \n    cout << A.size() << \"\\n\";\n    for (int i = 0; i < (int)A.size(); i++)\n        cout << A[i] << \" \" << op[i] << \" \" << B[i] << \"\\n\";\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math",
      "matrices",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1427",
    "index": "F",
    "title": "Boring Card Game",
    "statement": "When they are bored, Federico and Giada often play the following card game with a deck containing $6n$ cards.\n\nEach card contains one number between $1$ and $6n$ and each number appears on exactly one card. Initially the deck is sorted, so the first card contains the number $1$, the second card contains the number $2$, $\\dots$, and the last one contains the number $6n$.\n\nFederico and Giada take turns, alternating; Federico starts.\n\nIn his turn, the player takes $3$ contiguous cards from the deck and puts them in his pocket. The order of the cards remaining in the deck is not changed. They play until the deck is empty (after exactly $2n$ turns). At the end of the game both Federico and Giada have $3n$ cards in their pockets.\n\nYou are given the cards in Federico's pocket at the end of the game. Describe a sequence of moves that produces that set of cards in Federico's pocket.",
    "tutorial": "Before describing the solution, let us comment it. The solution is naturally split in two parts: Solving the problem without the \"alternating turns\" constraint. Noticing that a simple greedy is sufficient to take care of the \"alternating turns\" constraint. The first part of the solution is a rather standard greedy approach with complexity $O(n)$. It is quite easy (considering that this is problem F) to guess that such a greedy approach works. On the other hand, the second part of the solution (i.e. noticing that Giada takes the last turn and this imposes a condition on the appropriate forest provided by the first part of the solution) is still a greedy with $O(n)$ complexity, but harder to guess and less standard. The constraint on $n$ is very low as we did not want to implicitly hint towards a greedy approach. Moreover the greedy used in the first part of the solution can be replaced with an $O(n^3)$ dynamic-programming approach (which fits in the timelimit if implemented carefully) and the greedy described in the second part of the solution is slightly easier to implement with complexity $O(n^2)$. Simpler problem, not alternating turns Let us first consider a different (and easier) problem. Federico and Giada don't take turns, they take $3$ cards in the order they prefer (so at the end they may have a different number of cards). You are given a final situation (that is, the cards in Federico's pocket at the end) and you have to produce a sequence of moves that generates that set of cards at the end of the game. We assume that the final situation is fixed, hence each card is assigned to either Federico or Giada. We are going to describe what is natural to call the stack-partitioning. The stack-partitioning is a particular partition of the deck into $2n$ groups of $3$ cards each (not necessarily contiguous) such that each group of cards contain cards taken by the same player (either all $3$ by Federico or all $3$ by Giada). A priori the stack-partitioning might fail, not producing the described partition (but we will se that if the set of cards in Federico's pocket is achievable then the stack-partitioning does not fail). In order to create the stack-partitioning we iterate over the cards in the deck (hence the numbers from $1$ to $6n$) and we keep a stack of partial groups (i.e. of groups of less than $3$ cards). When we process a card, if it was taken by the same player that took the cards in the group at the top of the stack, then we add it to that group. If the group has now $3$ cards, we pop it from the stack and it becomes a group in the stack-partitioning. if it was taken by the other player, we add it on top of the stack (as a group with just that card). For example, if $n=2$ and the cards in Federico's pocket are $\\{1,5,8,9,10,12\\}$ then the stack-partitioning works and produces the partition $\\{\\{2,3,4\\},\\{8,9,10\\},\\{6,7,8\\},\\{1,5,12\\}\\} \\,.$ The fundamental observation is: Lemma: Let us fix a possible final situation. Let us perform the stack-partition starting with a nonempty stack, i.e. at the beginning the stack already contains some partial groups assigned to either Federico and Giada (these groups do not correspond to cards in the deck). At the end of the algorithm the stack will be as it was at the beginning, i.e., same number of partial groups, with same sizes and assigned to the same player. proof: The proof is by induction on the number of cards in the deck. Since it is not hard and quite standard, we leave it to the reader. Corollary: A final situation (i.e., a set of cards in Federico's pocket) is possible if and only if the stack-partitioning works. Moreover the stack-partitioning yields a way to produce the final situation. proof: If the stack-partitioning works, then it clearly yields a way to produce the final situation (players take the groups of three cards in the same order as they are popped out of the stack). The other implication follows directly from the Lemma. Original problem Now, we can go back to the original statement. Let us notice a couple more properties of the stack-partitioning (both observations are valid both in the simpler version of the problem and in the harder): The stack-partitioning produces a forest where each node is a group of $3$ cards taken by the same player (hence we will say that a node is owned by Federico or Giada). More precisely any group $G$ of $3$ cards is son of the group of $3$ cards at the top of the stack after $G$ is popped out (or $G$ is a root if the stack becomes empty). We will refer to this forest as the stack-forest. Notice that in the stack-forest two adjacent vertices are owned by different players. In any possible sequence of moves, the group taken in the last move intersects at least one root of the stack-forest. Indeed, the cards before the first card of the group can be taken independently from the others (without alternating turns) and therefore, thanks to the Lemma, when the first card of the group is processed the stack is empty (thus it belongs to a root). We prove that a certain final situation is possible if and only if the stack-partitioning works and there is a root of the stack-forest that is owned by Giada. First, if a situation is possible then the stack-partitioning works (because of the lemma). Moreover, since Giada performs the last move, thanks to the second property above, there must be a root of the stack-forest owned by Giada. Let us now describe a greedy algorithm to produce a given final situation provided that the stack-partitioning works and there is a root owned by Giada in the stack-forest. Notice that if we remove leaves from the stack-forest, alternating between nodes owned by Federico and Giada, we are actually performing a sequence of valid moves. The algorithm is the following: When it is Federico's turn, we remove an arbitrary leaf owned by Federico. When it is Giada's turn we remove an arbitrary leaf owned by Giada taking care of not removing a root if there is only one root owned by Giada. Why does the algorithm work? When it is Federico's turn, since there is at least one root owned by Giada and the number of nodes owned by Federico and Giada is the same, there must be at least one leaf owned by Federico (recall that adjacent vertices have different owners). When it is Giada's turn, there are more nodes owned by Giada then by Federico, hence there is at least one leaf owned by Giada. Could it be that such a leaf is also a root and it is the only root owned by Giada? It can be the case only if that is in fact the only remaining vertex.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \nvector<int> SortIndex(int size, std::function<bool(int, int)> compare) {\n    vector<int> ord(size);\n    for (int i = 0; i < size; i++) ord[i] = i;\n    sort(ord.begin(), ord.end(), compare);\n    return ord;\n}\n \ntemplate <typename T>\nbool MinPlace(T& a, const T& b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename T>\nbool MaxPlace(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \nmap<vector<int>, string> samples = {\n    {{2, 3, 4, 9, 10, 11}, \"9 10 11\\n6 7 8\\n2 3 4\\n1 5 12\"},\n    {{1, 2, 3, 4, 5, 9, 11, 12, 13, 18, 19, 20, 21, 22, 23}, \"19 20 21\\n24 25 26\\n11 12 13\\n27 28 29\\n1 2 3\\n14 15 16\\n18 22 23\\n6 7 8\\n4 5 9\\n10 17 30\"}\n};\n \nbool is_sample(const vector<int>& player) {\n    vector<int> vec;\n    for (int i = 1; i < (int)player.size(); i++) if (player[i]) vec.push_back(i);\n    if (!samples.count(vec)) return false;\n    cout << samples[vec] << \"\\n\";\n    return true;\n}\n \nstruct Node {\n    int cnt;\n    int cards[3];\n    int father;\n    int deg;\n    int player;\n    bool used;\n};\n \nint main() {\n    int N;\n    cin >> N;\n    vector<int> player(6*N+1, 0);\n    for (int i = 0; i < 3*N; i++) {\n        int x;\n        cin >> x;\n        player[x] = true;\n    }\n \n    if (is_sample(player)) return 0;\n \n    Node root;\n    root.cnt = 0, root.deg = 0, root.player = -1, root.used = true;\n    vector<Node> nodes;\n    nodes.push_back(root);\n    stack<int> S;\n    S.push(0);\n    for (int i = 1; i <= 6*N; i++) {\n        if (nodes[S.top()].player == player[i]) {\n            int it = S.top();\n            nodes[it].cards[nodes[it].cnt++] = i;\n            if (nodes[it].cnt == 3) S.pop();\n        } else {\n            Node X;\n            X.cnt = 1;\n            X.cards[0] = i;\n            X.father = S.top();\n            X.player = player[i];\n            X.deg = 0;\n            X.used = false;\n            nodes[S.top()].deg++;\n            S.push(nodes.size());\n            nodes.push_back(X);\n        }\n    }\n    assert(S.size() == 1);\n    for (int i = 1; i <= 2*N; i++) {\n        int choice = -1;\n        for (int j = 1; j <= 2*N; j++) {\n            if (nodes[j].used or nodes[j].player != i%2 or nodes[j].deg > 0) continue;\n            choice = j;\n            if (i%2 or nodes[j].father != 0) break;\n        }\n        assert(choice != -1);\n        Node& X = nodes[choice];\n        cout << X.cards[0] << \" \" << X.cards[1] << \" \" << X.cards[2] << \"\\n\";\n        X.used = true;\n        nodes[X.father].deg--;\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1427",
    "index": "G",
    "title": "One Billion Shades of Grey",
    "statement": "You have to paint with shades of grey the tiles of an $n\\times n$ wall. The wall has $n$ rows of tiles, each with $n$ tiles.\n\nThe tiles on the boundary of the wall (i.e., on the first row, last row, first column and last column) are already painted and you shall not change their color. All the other tiles are not painted. Some of the tiles are broken, you shall not paint those tiles. It is guaranteed that the tiles on the boundary are not broken.\n\nYou shall paint all the non-broken tiles that are not already painted. When you paint a tile you can choose from $10^9$ shades of grey, indexed from $1$ to $10^9$. You can paint multiple tiles with the same shade. Formally, painting the wall is equivalent to assigning a shade (an integer between $1$ and $10^9$) to each non-broken tile that is not already painted.\n\nThe contrast between two tiles is the absolute value of the difference between the shades of the two tiles. The total contrast of the wall is the sum of the contrast of all the pairs of adjacent non-broken tiles (two tiles are adjacent if they share a side).\n\nCompute the minimum possible total contrast of the wall.",
    "tutorial": "We present two solutions: the first solution is mine, the second is by dacin21. The first solution reduces the problem to the computation of $O(n)$ min-cuts and then computes the min-cuts with total complexity $O(n^3)$. This solution requires no advanced knowledge and it fits easily in the time-limit. The second solution solves the dual of the problem, which happens to be a min-cost flow. This shall be implemented with complexity $O(n^3)$ (or $O(n^3\\log(n))$ and some optimizations) to fit in the time-limit. We will solve the problem on a general graph (tiles = vertices, two tiles are adjacent if there is an edge between them). Solution via many min-cuts The solution is naturally split in two parts: Reduce the problem to the computation of $O(n)$ min-cuts in the grid-graph (here $O(n)$ represents the number of already painted tiles). Compute all the min-cuts with overall complexity $O(n^3)$. Reducing to many min-cuts A natural way to come up with this solution is to consider the special case in which the painted tiles have only two colors. In such a case the problems is clearly equivalent to the min-cut. We show that something similar holds true in general. Given a graph $(V, E)$, let $B$ be the set of vertices that are already painted (in our problem, $B$ contains the tiles on the boundary). Let us fix a choice of all the shades, that is a function $s:V\\to\\mathbb N$ such that $s(v)$ is the shade assigned to vertex $v$. Let TC be the total contrast. We have (using that, for $x\\le y$, it holds $|x-y|=\\sum_{k\\ge 1}[x\\le k\\text{ and } y > k]$) $\\texttt{TC} = \\sum_{(u,v)\\in E} |s(u)-s(v)| = \\sum_{k\\ge 1} \\#\\{(u,v)\\in E:\\ s(u)\\le k,\\, s(v)>k\\} \\,.$ $\\texttt{TC} = \\sum_{k\\ge 1} mc(\\{v\\in V: s(v)\\le k\\}, \\{v\\in V: s(v)>k\\}) \\ge \\sum_{k\\ge 1} mc(\\{v\\in B: s(v)\\le k\\}, \\{v\\in B: s(v)>k\\})\\,.$ Given two disjoint subsets $U_1,U_2$, let $\\mathcal{MC}(U_1,U_2)$ be the family of all the subsets $U_1\\subseteq W\\subseteq V\\setminus U_2$ such that $mc(U_1, U_2)=mc(W,V\\setminus W)$, i.e. the family of subsets achieving the minimum-cut. We are going to need the following lemma. Even though the proof is unilluminating, the statement is very intuitive. Lemma: Take $U_1,U_2$ disjoint and $\\tilde U_1,\\tilde U_2$ disjoint, such that $U_1\\subseteq \\tilde U_1$ and $\\tilde U_2\\subseteq U_2$ (that is, $U_1$ grows and $U_2$ shrinks). If $W\\in \\mathcal{MC}(U_1,U_2)$ and $\\tilde W\\in \\mathcal{MC}(\\tilde U_1, \\tilde U_2)$, then $W\\cup \\tilde W\\in \\mathcal{MC}(\\tilde U_1, \\tilde U_2)$. proof. Given two disjoint sets $A,B\\subseteq V$, let $c(A,B):=|(A\\times B)\\cap E|$ be the number of cross-edges. It holds (without using any assumption on $W$ or $\\tilde W$) $c(W\\cup \\tilde W, (W\\cup \\tilde W)^c) - c(\\tilde W, \\tilde W^c) = c(W\\setminus \\tilde W, (W\\cup \\tilde W)^c) - c(\\tilde W, W\\setminus\\tilde W) \\\\ \\quad\\quad\\quad\\le c(W\\setminus \\tilde W,W^c) - c(W\\cap \\tilde W, W\\setminus \\tilde W) = c(W,W^c) - c(W\\cap \\tilde W, (W\\cap \\tilde W)^c)\\,.$ Applying the lemma, we may find an increasing family of subsets $W_1\\subseteq W_2\\subseteq W_3\\subseteq \\cdots$ such that for all $k\\ge 1$ it holds $W_k\\in \\mathcal{MC}(\\{v\\in B: s(v)\\le k\\}, \\{v\\in B: s(v)>k\\}) \\,.$ Hence, we may solve the problem running many maximum-flow algorithms. Running $O(n)$ times a max-flow algorithm should get time-limit-exceeded independently on how good your implementation of the maximum-flow is. Remark. For those interested, the relation between min-cuts and the minimization of the contrast is very similar to the relation between the isoperimetric problem and the 1-Sobolev inequality (see this wiki page). In the continuous setting, the strategy employed in this solution corresponds to the coarea formula. Computing quickly many min-cuts Our goal is computing $mc(\\{v\\in B: s(v)\\le k\\}, \\{v\\in B: s(v)>k\\})$ for all values of $k$. The number of interesting values of $k$ is clearly $O(n)$. For simplicity, we assume that the interesting values of $k$ are contiguous and that all the tiles on the boundary have different shades. Let us assume that we have computed, via a simple augmenting-path algorithm, a max-flow between $\\{v\\in B: s(v)\\le k\\}$ and $\\{v\\in B: s(v)> k\\}$. In particular we are keeping the flow as a union of disjoint paths. We show how to update it to a max-flow between $\\{v\\in B: s(v)\\le k+1\\}$ and $\\{v\\in B: s(v)> k+1\\}$ in $O(n^2)$ time (thus the overall complexity will be $O(n^3)$). Passing from $k$ to $k+1$ we only need to transform a sink into a source (in particular the vertex such that $s(v)=k+1$ becomes a source). How shall we do that?. First of all we remove all the paths that ends in $v$ (there are at most $3$, which is the degree of $v$). Then we look for augmenting paths. Due to the optimality of the flow before the update, it is not hard to prove that there can be at most $6$ augmenting paths. The overall complexity of the update is $3n^2 + 6n^2 = O(n^2)$. Solution via min-cost flow The crucial point is formulating the problem as a linear programming problem and computing its dual, which somewhat magically turns out to be a min-cost flow. Then a very careful implementation of the min-cost flow algorithm is necessary to get accepted (with some optimizations, it is possible to get accepted with execution time below $1$ second). Let $x_v$ be the shade of vertex $v$. For any edge $u\\sim v$, let $c_{uv}$ be the contrast between $u$ and $v$. Then we have $c_{uv} \\ge x_u-x_v \\quad \\text{ and }\\quad c_{uv}\\ge x_v-x_u \\,,$ Hence, we have formulated the minimization of the total contrast as a linear programming problem. In this form, it's not clear how to solve it efficiently (the simplex algorithm would be way to slow). Computing the dual problem is straight-forward (using well-known formulas) but a bit heavy on notation. In the end, the dual problem turns out to be the min-cost flow with the following parameters: There is a source, connected to all the vertices $v$ already painted via an edge (from the source to $v$) with capacity $1$ and cost $x_v$. There is a sink, connected to all the vertices $v$ already painted via an edge (from $v$ to the sink) with capacity $1$ and cost $-x_v$. All the edges of the graph have capacity $1$ and cost $0$. Remove the edges between already painted vertices (taking care of the contrast generated by adjacent painted vertices). Use a radix-heap instead of a standard heap for Dijkstra.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\n#define SZ(x) ((int)((x).size()))\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n \nconst int MAXN = 200 + 5;\nint vals[MAXN][MAXN];\nint available[MAXN][MAXN][4];\nint dt[4] = {0, 1, 0, -1};\nint N;\n \nbool sources[MAXN][MAXN];\nbool sinks[MAXN][MAXN];\nbool visited[MAXN][MAXN];\n \nvoid reset_visited() {\n    for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) visited[x][y] = false;\n}\n \nbool dfs(int x, int y, bool is_goal[MAXN][MAXN]) {\n    visited[x][y] = true;\n    if (is_goal[x][y]) return true;\n    for (int t = 0; t < 4; t++) {\n        if (!available[x][y][t]) continue;\n        int x1 = x + dt[t];\n        int y1 = y + dt[t^1];\n        if (is_goal == sources and available[x1][y1][t^2]) continue;\n        if (visited[x1][y1]) continue;\n        if (dfs(x1, y1, is_goal)) {\n            if (available[x1][y1][t^2]) available[x][y][t] = false;\n            else available[x1][y1][t^2] = true;\n            return true;\n        }\n    }\n    return false;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n \n    cin >> N;\n \n    vector<pair<int,int>> tiles;\n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) cin >> vals[i][j];\n    for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) {\n        if (vals[i][j] >= 1) {\n            tiles.push_back({i, j});\n            sinks[i][j] = true;\n        }\n    }\n    \n    for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) {\n        if (vals[x][y] == -1) continue;\n        for (int t = 0; t < 4; t++) {\n            int x1 = x + dt[t];\n            int y1 = y + dt[t^1];\n            if (x1 < 0 or x1 >= N or y1 < 0 or y1 >= N) continue;\n            if (vals[x1][y1] == -1) continue;\n            available[x][y][t] = true;\n        }\n    }\n    sort(tiles.begin(), tiles.end(), [&](pair<int,int> A, pair<int,int> B) {\n        return vals[A.first][A.second] < vals[B.first][B.second];\n    });\n    \n    LL res = 0;\n    int flow = 0;\n \n    for (int it = 0; it < SZ(tiles)-1; it++) {\n        int x = tiles[it].first, y = tiles[it].second;\n        \n        while (dfs(x, y, sources)) {\n            reset_visited();\n            flow--;\n        }\n        reset_visited();\n        sinks[x][y] = false;\n        sources[x][y] = true;\n        for (auto pp: tiles) {\n        // for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) {\n            int i = pp.first, j = pp.second;\n            if (sources[i][j] and !visited[i][j]) {\n                while (dfs(i, j, sinks)) {\n                    reset_visited();\n                    flow++;\n                }\n            }\n        }\n        // for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) {\n            // if (visited[i][j] and !vals[i][j]) vals[i][j] = vals[x][y];\n        // }\n        reset_visited();\n        \n        LL cost = vals[tiles[it+1].first][tiles[it+1].second]-vals[x][y];\n        res += cost * flow;\n    }\n    // for (int i = 0; i < N; i++) {\n        // for (int j = 0; j < N; j++) cout << vals[i][j] << \" \";\n        // cout << \"\\n\";\n    // }\n    cout << res << endl;\n    \n}",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1427",
    "index": "H",
    "title": "Prison Break",
    "statement": "A prisoner wants to escape from a prison. The prison is represented by the interior of the convex polygon with vertices $P_1, P_2, P_3, \\ldots, P_{n+1}, P_{n+2}, P_{n+3}$. It holds $P_1=(0,0)$, $P_{n+1}=(0, h)$, $P_{n+2}=(-10^{18}, h)$ and $P_{n+3}=(-10^{18}, 0)$.\n\nThe prison walls $P_{n+1}P_{n+2}$, $P_{n+2}P_{n+3}$ and $P_{n+3}P_1$ are very high and the prisoner is not able to climb them. Hence his only chance is to reach a point on one of the walls $P_1P_2, P_2P_3,\\dots, P_{n}P_{n+1}$ and escape from there. On the perimeter of the prison, there are two guards. The prisoner moves at speed $1$ while the guards move, \\textbf{remaining always on the perimeter of the prison}, with speed $v$.\n\nIf the prisoner reaches a point of the perimeter where there is a guard, the guard kills the prisoner. If the prisoner reaches a point of the part of the perimeter he is able to climb and there is no guard there, he escapes immediately. Initially the prisoner is at the point $(-10^{17}, h/2)$ and the guards are at $P_1$.\n\nFind the minimum speed $v$ such that the guards can guarantee that the prisoner will not escape (assuming that both the prisoner and the guards move optimally).\n\n\\textbf{Notes:}\n\n- At any moment, the guards and the prisoner can see each other.\n- The \"climbing part\" of the escape takes no time.\n- You may assume that both the prisoner and the guards can change direction and velocity instantly and that they both have perfect reflexes (so they can react instantly to whatever the other one is doing).\n- The two guards can plan ahead how to react to the prisoner movements.",
    "tutorial": "We fix the unit of measure and say that the prisoner moves at $1$ meter per second. Let us parametrize the boundary of the prison as follows (ignoring the very long, very high walls). Start walking with speed $1$ from $P_1$ towards $P_{n+1}$ staying on the prison wall and let $\\gamma(t)$ be the point you are at after time $t$ (so $\\gamma$ is a curve with speed $1$). Let $L$ be the total length of such curve (i.e., $\\gamma(L)=P_{n+1}$). With an abuse of notation, we will denote with $\\gamma$ also the image of $\\gamma$ (i.e., the climbable walls). A criterion for the prison break The prisoner can escape if and only if there are three times $0\\le t_1<t_2<t_3\\le L$ such that $\\quad |\\gamma(t_2)-\\gamma(t_1)| < \\frac{t_2-t_1}{v} \\quad \\text{ and } |\\gamma(t_3)-\\gamma(t_2)| < \\frac{t_3-t_2}{v} \\,.\\tag{$\\star$}$ proof. If there are three times $t_1<t_2<t_3$ such that $(\\star)$ holds, then the prisoner can escape. The strategy of the prisoner is as follows. He begins by going (very close) to the point $\\gamma(t_2)$. If there is not a guard there, he escapes. Otherwise, there must be a guard at (a point very close to) $\\gamma(t_2)$. Without loss of generality we may assume that the other guard is at $\\gamma(t)$ with $t<t_2$. Then the prisoner goes directly to $\\gamma(t_3)$ and escapes from there. Notice that the prisoner reaches $\\gamma(t_3)$ in $|\\gamma(t_3)-\\gamma(t_2)|$ seconds, while the closest guard (the one at $\\gamma(t_2)$) needs $\\frac{t_3-t_2}v$ seconds. The assumption guarantees that the prisoner reaches $\\gamma(t_3)$ before the guard. If there are not three such times such that $(\\star)$ holds, then the guards have a strategy to avoid the prison break. This implication is harder; we split its proof into various steps. The strategy of the guards is encoded by two functions $f_1,f_2$. Assume that we are given two functions $f_1,f_2:\\mathcal Z\\to [0,L]$, where $\\mathcal Z$ denotes the interior of the prison, such that they are both $v$-Lipschitz (i.e., $|f(A)-f(B)|\\le v|A-B|$) and, for any $0\\le t\\le L$, either $f_1(\\gamma(t))=t$ or $f_2(\\gamma(t))=t$ (or also both). Denoting with $Q$ the position of the prisoner, the guards may follow the following strategy (it is easy to adapt this strategy to the fact that initially the guards are at $P_1$, we leave it to the reader): The first guard will always be at $\\gamma(f_1(Q))$. The second guard will always be at $\\gamma(f_2(Q))$. Extending Lipschitz functions. It remains to construct two such functions $f_1,f_2$. The idea is to define them on $\\gamma$ and then extend them inside $\\mathcal Z$ through a standard technique. Assume that we are able to define them on $\\gamma$, it is well-known that a real-valued Lipschitz function defined on a subset of a metric space (the metric space is $\\mathcal Z$, its subset is $\\gamma$) can be extended to the whole metric space without increasing the Lipschitz constant (this may sound as abstract nonsense, but it's easy... prove it!). From two functions to two subsets. The existence of the desired $f_1,f_2$ boils down to finding two functions on $\\gamma$ that are $v$-Lipschitz and for each $0\\le t\\le L$ we have either $f_1(\\gamma(t))=t$ or $f_2(\\gamma(t))=t$. Let $\\gamma_1,\\gamma_2$ be the subsets of $\\gamma$ where, respectively, $f_1(\\gamma(t))=t$ and $f_2(\\gamma(t))=t$. What can we say on the two subsets $\\gamma_1$ and $\\gamma_2$? Well, restricted on them, the function $\\gamma(t)\\mapsto t$ must be $v$-Lipschitz! Thus, applying again the extension argument described above, the problem reduces to finding two subsets $\\gamma_1,\\gamma_2$ of $\\gamma$ such that $\\gamma_1\\cup\\gamma_2=\\gamma$ and the function $\\gamma(t)\\mapsto t$ is $v$-Lipschitz on $\\gamma_1$ and $\\gamma_2$. Existence of the subsets via a bipartition argument. We have finally arrived at the core of the proof, constructing $\\gamma_1$ and $\\gamma_2$. Given two points $\\gamma(s)$ and $\\gamma(t)$, we say that they are compatible if $v|\\gamma(s)-\\gamma(t)| \\ge |s-t|$. The conditions on $\\gamma_1$ and $\\gamma_2$ are equivalent to: It holds $\\gamma_1\\cup\\gamma_2=\\gamma$. Any two points in $\\gamma_1$ are compatible. Any two points in $\\gamma_2$ are compatible. Computing the minimal speed $v$ In order to find the minimal $v$ such that the guards can avoid the prison break, we binary search the answer. Given a certain $v$, we must check whether there are three times $0\\le t_1<t_2<t_3\\le L$ such that $(\\star)$ holds. We say that $t_2$ is left-incompatible if there is a $t_1<t_2$ such that $(\\star)$ holds and we say that it is right-incompatible if there is a $t_3>t_2$ such that $(\\star)$ holds. We have to check whether there is a time that is both left-incompatible and right-incompatible. Let us assume that $\\gamma(t_1)\\in [P_i,P_{i+1}]$ and $\\gamma(t_2)\\in[P_j,P_{j+1}]$ with $i < j$. Under this additional constraint, characterizing the \"left-incompatible\" times $t_2$ reduces to finding all the points $\\gamma(t_2)\\in[P_j,P_{j+1}]$ such that $\\min_{\\gamma(t_1)\\in[P_i,P_{i+1}]} |\\gamma(t_2)-\\gamma(t_1)|-\\frac{t_2-t_1}{v} < 0 \\,.$ The first method, based on solving quadratic equations, needs some care to avoid precision issues/division by zero. The complexity is $O(1)$ (once $i$ and $j$ are fixed) and produces a complete algorithm with complexity $O(n^2\\log(n)\\log(\\varepsilon^{-1}))$ (or a slightly easier to implement $O(n^3\\log(\\varepsilon^{-1}))$ that is super-fast. The second method, based on ternary search, is pretty straight-forward to implement but proving its correctness is rather hard. The complexity is $O(\\log(\\varepsilon^{-1})^2)$ and produces a complete algorithm with complexity $O(n^2\\log(\\varepsilon^{-1})^3 + n^3\\log(\\varepsilon^{-1}))$ which is rather slow in practice; some care might be necessary to get it accepted. Since we will need them in both approaches, let us define $t^{\\pm}_{12}$ as the values such that $\\gamma(t_1^-)=P_i$, $\\gamma(t_1^+)=P_{i+1}$, $\\gamma(t_2^-)=P_j$, $\\gamma(t_2^+)=P_{j+1}$. Via quadratic equations. Consider the function $F(t_1,t_2):= |\\gamma(t_2)-\\gamma(t_1)|^2v^2-(t_2-t_1)^2$. We have to find the values $t_2\\in[t_2^-,t_2^+]$ such that $\\min_{t_1\\in [t_1^-,t_1^+]} F(t_1, t_2) < 0\\,.$ Let us remark that, even if everything seems elementary and easy, implementing this is not a cakewalk. Via ternary search. Consider the function $G(t_1,t_2):= \\frac{|\\gamma(t_2)-\\gamma(t_1)|}{t_2-t_1}$. We have to find the values $t_2\\in[t_2^-,t_2^+]$ such that $\\min_{t_1\\in[t_1^-,t_1^+]} G(t_1, t_2) < v^{-1} \\,.$ $\\tilde G(t_2) := \\min_{t_1\\in[t_1^-, t_1^+]} G(t_1, t_2) \\,.$ For a proof that the above functions are really unimodal, take a look at this short pdf. Implementing this second approach might be a bit tedious, but presents no real difficulty. Since this is quite slow, it might need some care to get accepted (for example, the arg-min of $\\tilde G$ shall be computed only once and not for each binary-search iteration on $v$).",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \nvector<int> SortIndex(int size, std::function<bool(int, int)> compare) {\n    vector<int> ord(size);\n    for (int i = 0; i < size; i++) ord[i] = i;\n    sort(ord.begin(), ord.end(), compare);\n    return ord;\n}\n \ntemplate <typename T>\nbool MinPlace(T& a, const T& b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename T>\nbool MaxPlace(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \nstruct pt {\n    double x, y;\n    pt(): x(0), y(0) {}\n    pt(double x, double y): x(x), y(y) {}\n};\npt operator -(pt A, pt B) { return {A.x-B.x, A.y-B.y}; }\ndouble operator *(pt A, pt B) { return A.x*B.x + A.y*B.y; }\ndouble norm(pt A) { return sqrt(A*A); }\npt operator /(pt A, double lambda) { return {A.x/lambda, A.y/lambda}; }\nostream& operator<<(ostream& out, pt P) {\n    out << \"(\" << P.x << \", \" << P.y << \")\";\n    return out;\n}\n \n// P(s) = as² + bs +c\n// {l < s < r: P(s) < 0}\nvoid neg_interval(double a, double b, double c, double l, double r,\n                  vector<pair<double,double>>& ans) {\n    assert(abs(a-1) < 1e-5 or a < 0);\n    if (a > 0) {\n        b /= a, c /= a, a = 1;\n        if (b*b < 4*a*c) return;\n        double delta = sqrt(b*b-4*a*c);\n        double l0 = (-b - delta)/2;\n        double r0 = (-b + delta)/2;\n        l0 = max(l0, l);\n        r0 = min(r0, r);\n        if (l0 < r0) ans.emplace_back(l0, r0);\n    }\n    if (a < 0) {\n        double s = sqrt(a*a + b*b + c*c);\n        a /= s, b /= s, c /= s; // renormalization\n        if (b*b < 4*a*c) {\n            ans.emplace_back(l, r);\n            return;\n        }\n        double delta = sqrt(b*b-4*a*c);\n        double l0 = (-b + delta)/(2*a);\n        double r0 = (-b - delta)/(2*a);\n        // The following lines are necessary to handle appropriately a close to 0.\n        if (-0.01 < a) {\n            if (b > 0) l0 = (-2*c)/(b+delta);\n            else r0 = (2*c)/(-b + delta);\n        }\n        \n        if (l < l0) ans.emplace_back(l, min(l0, r));\n        if (r0 < r) ans.emplace_back(max(l, r0), r);\n    }\n}\n \n// Q(s, t) = s² + t² + ast + bs + ct + d\n// {l0 < s < r0: \\min_{l1 < t < r1} Q(s, t) < 0}\nvoid neg_interval(double a, double b, double c, double d,\n                  double l0, double r0, double l1, double r1,\n                  vector<pair<double,double>>& ans) {\n    assert(a >= 1.99);\n    // argmin_t Q(s, t) = -(as+c)/2 in [l1, r1]\n    double lmin = (-2 * r1 - c)/a;\n    double rmin = (-2 * l1 - c)/a;\n    lmin = max(lmin, l0);\n    rmin = min(rmin, r0);\n    // argmin in [l1,r1] <-> lmin < s < rmin\n    if (lmin < rmin) neg_interval(1-a*a/4, b-a*c/2, d-c*c/4, lmin, rmin, ans);\n    neg_interval(1, a*l1+b, l1*l1+c*l1+d, l0, r0, ans);\n    neg_interval(1, a*r1+b, r1*r1+c*r1+d, l0, r0, ans);\n}\n \nvoid good_interval(pt A, pt B, pt C, pt D, double v, double l, vector<pair<double,double>>& ans) {\n    double lA = 0;\n    double rA = norm(B-A);\n    pt dA = (B-A)/rA;\n    double lC = 0;\n    double rC = norm(D-C);\n    pt dC = (D-C)/rC;\n    // v*v*(A+s*dA - C - t*dC)^2 - (l + t - s)^2 < 0\n    if (v >= sqrt(2/(1+dA*dC))) return; // if ==, then c2 = 2c1 (and a = 2).\n    double c1 = v*v - 1; // s² and t²\n    double c2 = 2*(1- (v*v)*(dA*dC)); // st\n    double c3 = 2*v*v*((A-C)*dA) + 2*l; // s\n    double c4 = -2*v*v*((A-C)*dC) - 2*l; // t\n    double c5 = v*v * ((A-C)*(A-C)) - l*l; // const\n    c2 /= c1, c3 /= c1, c4 /= c1, c5 /= c1;\n    \n    neg_interval(c2, c3, c4, c5, lA, rA, lC, rC, ans);\n}\n \nbool nonempty_intersection(pair<double,double> I1, pair<double,double> I2) {\n    return max(I1.first, I2.first) < min(I1.second, I2.second);\n}\n \nconst int MAXN = 51;\npt P[MAXN];\ndouble len[MAXN];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n \n    int N;\n    cin >> N;\n    for (int i = 0; i <= N; i++) cin >> P[i].x >> P[i].y;\n    for (int i = 1; i < N; i++) len[i] = len[i-1] + norm(P[i]-P[i-1]);\n \n    if (N <= 2) {\n        cout << 1 << \"\\n\";\n        return 0;\n    }\n \n    double l = 1;\n    double r = 20;\n    for (int it = 0; it < 50; it++) {\n        bool good = false;\n        double v = (l+r)/2;\n        for (int i = 1; i < N-1; i++) {\n            vector<pair<double,double>> bef, aft;\n            for (int j = 0; j < i; j++)\n                good_interval(P[i], P[i+1], P[j], P[j+1], v, len[j]-len[i], bef);\n            for (int j = i+1; j < N; j++)\n                good_interval(P[i], P[i+1], P[j], P[j+1], v, len[j]-len[i], aft);\n            for (auto& I: bef) for (auto& J: aft) good |= nonempty_intersection(I, J);\n        }\n        if (good) l = v;\n        else r = v;\n    }\n \n    cout.precision(10);\n    cout << l << \"\\n\";\n}",
    "tags": [
      "binary search",
      "games",
      "geometry",
      "ternary search"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1428",
    "index": "A",
    "title": "Box is Pull",
    "statement": "Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $(x_1,y_1)$ to the point $(x_2,y_2)$.\n\nHe has a rope, which he can use to pull the box. He can only pull the box if he stands \\textbf{exactly} $1$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $1$ unit.\n\nFor example, if the box is at the point $(1,2)$ and Wabbit is standing at the point $(2,2)$, he can pull the box right by $1$ unit, with the box ending up at the point $(2,2)$ and Wabbit ending at the point $(3,2)$.\n\nAlso, Wabbit can move $1$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $1$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.\n\nWabbit can start at any point. It takes $1$ second to travel $1$ unit right, left, up, or down, regardless of whether he pulls the box while moving.\n\nDetermine the minimum amount of time he needs to move the box from $(x_1,y_1)$ to $(x_2,y_2)$. Note that the point where Wabbit ends up at does not matter.",
    "tutorial": "Consider when $x_1=x_2$ Consider when $x_1 \\ne x_2$ We consider 2 cases. The first is that the starting and ending point lie on an axis-aligned line. In this case, we simply pull the box in 1 direction, and the time needed is the distance between the 2 points as we need 1 second to decrease the distance by 1. The second is that they do not lie on any axis-aligned line. Wabbit can pull the box horizontally (left or right depends on the relative values of $x_1$ and $x_2$) for $|x_1-x_2|$ seconds, take 2 seconds to move either above or below the box, then take another $|y_1-y_2|$ seconds to move the box to $(x_2,y_2)$.",
    "code": "tc=int(input())\nfor i in range(tc):\n    a,b,c,d=map(int,input().split(\" \"))\n\n    ans=abs(a-c)+abs(b-d)\n    if (a!=c and b!=d): ans+=2\n\n    print(ans)",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1428",
    "index": "B",
    "title": "Belted Rooms",
    "statement": "In the snake exhibition, there are $n$ rooms (numbered $0$ to $n - 1$) arranged in a circle, with a snake in each room. The rooms are connected by $n$ conveyor belts, and the $i$-th conveyor belt connects the rooms $i$ and $(i+1) \\bmod n$. In the other words, rooms $0$ and $1$, $1$ and $2$, $\\ldots$, $n-2$ and $n-1$, $n-1$ and $0$ are connected with conveyor belts.\n\nThe $i$-th conveyor belt is in one of three states:\n\n- If it is clockwise, snakes can only go from room $i$ to $(i+1) \\bmod n$.\n- If it is anticlockwise, snakes can only go from room $(i+1) \\bmod n$ to $i$.\n- If it is off, snakes can travel in either direction.\n\nAbove is an example with $4$ rooms, where belts $0$ and $3$ are off, $1$ is clockwise, and $2$ is anticlockwise.\n\nEach snake wants to leave its room and come back to it later. A room is \\textbf{returnable} if the snake there can leave the room, and later come back to it using the conveyor belts. How many such \\textbf{returnable} rooms are there?",
    "tutorial": "There are 2 cases to consider for a room to be returnable. For a room to be returnable, either go one big round around all the rooms or move to an adjacent room and move back. Let's consider two ways to return to the start point. The first is to go one big round around the circle. The second is to move 1 step to the side, and return back immediately. Going one big round is only possible if and only if: There are no clockwise belts OR There are no anticlockwise belts If we can go one big round, all rooms are returnable. If there are both clockwise and anticlockwise belts, then we can't go one big round. For any room to be returnable, it must have an off belt to the left or to the right. In summary, check if clockwise belts are absent or if anticlockwise belts are absent. If either is absent, the answer is $n$. Otherwise, we have to count the number of rooms with an off belt to the left or to the right. Sorry for the unclear statement for B, we should've explained each sample testcase more clearly with better diagrams. Additionally, we're also sorry for the weak pretests. We should've added more testcases of smaller length, and thanks to hackers for adding stronger tests.",
    "code": "TC = int(input())\nfor tc in range(TC):\n    n = int(input())\n    s = input()\n\n    hasCW = False\n    hasCCW = False \n    for c in s:\n        if c == '>':\n            hasCW = True\n        if c == '<':\n            hasCCW = True\n            \n    if hasCW and hasCCW:\n        s += s[0]\n        ans = 0;\n        for i in range(n):\n            if s[i] == '-' or s[i+1] == '-':\n                ans += 1\n        print(ans)\n        \n    else:\n        print(n)",
    "tags": [
      "graphs",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1428",
    "index": "C",
    "title": "ABBB",
    "statement": "Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either \"AB\" or \"BB\". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.\n\nFor example, Zookeeper can use two such operations: AAB\\underline{AB}BA $\\to$ AA\\underline{BB}A $\\to$ AAA.\n\nZookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?",
    "tutorial": "and oolimry AB and BB means that ?B can be removed. The final string is BAAA... or AAA.... This game is equivalent to processing left to right and maintaining a stack. If the current processed character is A, we add it to the stack, if the current processed character is B, we can either add it to the stack or pop the top of the stack. In the optimal solution, we will always pop from the stack whenever possible. To prove this, we will use the stay ahead argument. Firstly, we notice that the contents of the stack do not actually matter. We actually only need to maintain the length of this stack. Decrementing the size of the stack whenever possible is optimal as it is the best we can do. And in the case where we must push `B' to the stack, this is optimal as the parity of the length of the stack must be the same as the parity of the processed string, so obtaining a stack of length 0 is impossble. Bonus: what is the length of the longest string that Zookeeper can make such that there are no moves left? We're also sorry for the weak pretests in this problem. About 1 hour before the contest, we found out that c++ $O(N^2)$ solution using find and erase would pass. Then we added testcases to kill the c++ solutions, but we didn't test the $O(N^2)$ solution for python using replace.",
    "code": "TC = int(input())\nfor tc in range(TC):\n\ts = input()\n\tans=0\n\tfor i in s:\n\t\tif (i=='B' and ans!=0): ans-=1\n\t\telse: ans+=1\n\tprint(ans)",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1428",
    "index": "D",
    "title": "Bouncing Boomerangs",
    "statement": "To improve the boomerang throwing skills of the animals, Zookeeper has set up an $n \\times n$ grid with some targets, \\textbf{where each row and each column has at most $2$ targets each}. The rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $n$ from left to right.\n\nFor each column, Zookeeper will throw a boomerang from the bottom of the column (below the grid) upwards. When the boomerang hits any target, it will bounce off, make a $90$ degree turn to the right and fly off in a straight line in its new direction. The boomerang can hit multiple targets and does not stop until it leaves the grid.\n\nIn the above example, $n=6$ and the black crosses are the targets. The boomerang in column $1$ (blue arrows) bounces $2$ times while the boomerang in column $3$ (red arrows) bounces $3$ times.\n\nThe boomerang in column $i$ hits exactly $a_i$ targets before flying out of the grid. \\textbf{It is known that $a_i \\leq 3$.}\n\nHowever, Zookeeper has lost the original positions of the targets. Thus, he asks you to construct a valid configuration of targets that matches the number of hits for each column, or tell him that no such configuration exists. If multiple valid configurations exist, you may print any of them.",
    "tutorial": "Consider $a_i \\in \\{0,1,2\\}$. Consider $a_i=\\{3,3,3, \\ldots , 3,1\\}$. Clearly, columns with $a_j=0$ are completely empty and we can ignore them. Let's first consider just columns with $1$ s and $2$ s. When a boomerang strikes its first target, it will change directions from upwards to rightwards. If $a_j=1$, the boomerang in column $j$ exits the grid on the right. This means that if the target that it hits in on row $r$, there is no other target to its right on row $r$. For columns with $a_j=2$, the boomerang in column $j$ has to hit second target in some column $k$ before moving downwards. The $2$ targets that this boomerang hits must be in the same row, and since no row contains more than $2$ targets, these are the only $2$ targets in the row. Additionally, there isn't any target below the second target. This means $a_k=1$. This tells us that columns $j$ with $a_j=2$ must be matched with columns $k$ with $a_k=1$ to its right with $j < k$. If we only had $a_j=1$ and $a_j=2$, we can simply greedily match $2$ s to $1$ s that are available. $3$ s initially seem difficult to handle. The key observation is that $3$ s can \"link\" to $3$ s to its right. The way to do this for the have the first target for one boomerang be the third target for another boomerang. This allows us to \"chain\" the $3$ s together in one long chain. Thus, we only care about the first $3$, which has to use either a $2$ or a $1$ (if it uses a $1$, that $1$ cannot be matched with a $2$). We should always use a $2$ if possible since it will never be used by anything else, and the exact $1$ that we use also doesn't matter. Thus the solution is as follows: Process from right to left. If the current value is a $1$, add it to a list of available ones. If the current value is a $2$, match it with an available $1$ and remove the $1$ from the list. If the current value is a $3$, match it with $3$,$2$ or $1$ in that order of preference. Once we have found the chains and matches, we can go from left to right and give each chain / match some number of rows to use so that they do not overlap. The final time complexity is $O(n)$. Bonus $1$: Show that the directly simulating the path of each boomerang is overall $O(n)$. Bonus $2$ (unsolved): Solve for $0 \\leq a_j \\leq 4$.",
    "code": "def die():\n    print(-1)\n    exit(0)\n \nones = []\nans = []\nH = 1\nlastThree = (-1,-1)\n \nn = int(input())\narr = list(map(int,input().split(\" \")))\n \nfor i in range(n-1, -1, -1):\n    if arr[i] == 0:\n        continue\n    elif arr[i] == 1:\n        ones.append((i,H))\n        ans.append((i,H))\n        H += 1\n    elif arr[i] == 2:\n        if len(ones) == 0:\n            die()\n        T = ones[-1]\n        ones.pop()\n        ans.append((i, T[1]))\n        lastThree = (i,T[1])\n    elif arr[i] == 3:\n        if lastThree[0] == -1:\n            if len(ones) == 0:\n                die()\n            else:\n                lastThree = ones[-1]\n                ones.pop()\n        ans.append((i, H))\n        ans.append((lastThree[0], H))\n        lastThree = (i,H)\n        H += 1\n \nprint(len(ans))\nfor ii in ans:\n    print(n-ii[1] + 1, end = ' ')\n    print(ii[0] + 1)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1428",
    "index": "E",
    "title": "Carrots for Rabbits",
    "statement": "There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought $n$ carrots with lengths $a_1, a_2, a_3, \\ldots, a_n$. However, rabbits are very fertile and multiply very quickly. Zookeeper now has $k$ rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into $k$ pieces. For some reason, all resulting carrot lengths must be positive integers.\n\nBig carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size $x$ is $x^2$.\n\nHelp Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots.",
    "tutorial": "Orz proof by: oolimry Greedy. Let us define $f(l,p)$ as the sum of time needed when we have a single carrot of length $l$ and it is split into $p$ pieces. We can show that $f(l,p-1)-f(l,p) \\ge f(l,p)-f(l,p+1)$. Let us define $f(l,p)$ as the sum of time needed when we have a single carrot of length $l$ and it is split into $p$ pieces. In an optimal cutting for a single carrot, we will only cut it into pieces of length $w$ and $w+1$, for some $w$. Such cutting is optimal as suppose we have $2$ pieces of length $\\alpha$ and $\\beta$, and $\\alpha+2 \\leq \\beta$. Then, it is better to replace those $2$ pieces of carrots with length $\\alpha+1$ and $\\beta-1$, since $(\\alpha+1)^2+(\\beta-1)^2 \\leq \\alpha^2+\\beta^2$. To calculate $f(l,p)$, we need to find $p_1,p_2$ such that $p_1 (w) + p_2 (w+1)=l$ and $p_1+p_2=p$, minimizing $p_1(w)^2+p_2(w+1)^2$. Clearly, $w=\\lfloor \\frac{l}{p} \\rfloor$ and $p_2=l\\mod p$. Thus, calculating $f(l,p)$ can be done in $O(1)$. We can use the following greedy algorithm. We consider making zero cuts at first. We will make $k$ cuts one by one. When deciding where to make each cut, consider for all the carrots, which carrot gives us the largest decrease in cost when we add an extra cut. If a carrot of length $l$ currently is in $p$ pieces, then the decrease in cost by making one extra cut is $f(l,p) - f(l,p+1)$. The important observation here is that $f(l,p-1)-f(l,p) \\geq f(l,p)-f(l,p+1)$. Consider $f(2l,2p)$. Since the length is even and we have an even number of pieces, we know that the will be one cut down the middle and each half will have $p$ pieces. As such, $f(2l,2p) = 2f(l,p)$ This is because there even number of $w$ length pieces and an even number of $w+1$ length pieces, hence the left half and the right half are the same. Also, $f(l,p-1) + f(l,p+1) \\geq f(2l,2p)$, since $f(l,p-1) + f(l,p+1)$ is describing cutting a carrot of length $2l$ first into $2$ carrots of length $l$ and cutting it into $p-1$ and $p+1$ pieces respectively. The inequality must hold because this is a way to cut a carrot of length $2l$ into $2p$ pieces. Since we have $f(l,p-1) + f(l,p+1) \\geq f(2l,2p)$ and $f(2l,2p) = 2f(l,p)$. We have $f(l,p-1) + f(l,p+1) \\geq f(l,p) + f(l,p)$. Rearranging terms gives $f(l,p-1)-f(l,p) \\geq f(l,p)-f(l,p+1)$ In other words, the more cuts we make to a carrot, there is a diminishing returns in the decrease in cost per cut. As such, For any carrot, we don't need to think about making the $(p+1)$-th cut before making the $p$-th cut. Hence, all we need to do is choose carrot with the largest decrease in cost, and add one extra cut for that. Which carrot has the largest decrease in cost can be maintained with a priority queue. Hence, we get a time complexity of $O(klog(n))$. Bonus: solve this problem for $k \\leq 10^{18}$. When preparing this problem, I started with putting $n,k\\leq 5000$ because i thought if I put larger values it would be guessforces. However, several testers made $O(nk \\log n)$ and $O(nk)$ dp solutions. Which version of the problem do you think is better?",
    "code": "from heapq import *\n\nn,k=map(int,input().split(\" \"))\n\n\ndef val(l,nums):\n    unit=l//nums\n    extra=l-unit*nums\n    return (nums-extra)*unit*unit+extra*(unit+1)*(unit+1)\n    \npq=[]\narr=list(map(int,input().split(\" \")))\n\ntotal=0\nfor x in range(n):\n    total+=arr[x]*arr[x]\n    heappush(pq,(-val(arr[x],1)+val(arr[x],2),arr[x],2))\n\nfor x in range(k-n):\n    temp=heappop(pq)\n    total+=temp[0]\n    a,b=temp[1],temp[2]\n    heappush(pq,(-val(a,b)+val(a,b+1),a,b+1))\n\nprint(total)",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1428",
    "index": "F",
    "title": "Fruit Sequences",
    "statement": "Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange.\n\nSince wabbit is allergic to eating oranges, Zookeeper would like to find the longest \\textbf{contiguous} sequence of apples. Let $f(l,r)$ be the longest \\textbf{contiguous} sequence of apples in the substring $s_{l}s_{l+1}\\ldots s_{r}$.\n\nHelp Zookeeper find $\\sum_{l=1}^{n} \\sum_{r=l}^{n} f(l,r)$, or the sum of $f$ across all substrings.",
    "tutorial": "Line sweep. How does $f(l,r)$ change when we increase r? For a fixed $r$, let us graph $f(l,r)$ in a histogram with $l$ as the $x$-axis. We notice that this histogram is non-increasing from left to right. Shown below is the histogram for the string $11101011$ with $r = 6$, where $1$ box represents $1$ unit. The area under this histogram is the sum of all $f(l,r)$ for a fixed $r$. Consider what happens to the histogram when we move from $r$ to $r+1$. If $s_{r+1} = 0$, then the histogram does not change at all. If $s_{r+1} = 1$, then we may need to update the histogram accordingly. Above is the histogram for $11101011$ when $r=7$. And this is the histogram for $11101011$ when $r=8$. When adding a new segment of $k$ $1$s, we essentially fill up the bottom $k$ rows of the histogram. Thus, we let $L_x$ be the largest $l$ such that $f(l,r) = x$. We maintain these $L_x$ values in an array. When we process a group of $k$ 1s, we update the values for $L_1, L_2, \\cdots, L_k$, change the area of the histogram and update the cumulative sum accordingly. With proper processing of the segments of 1s, this can be done in $O(n)$ time. Interestingly, many testers found F not much harder than E, as such we gave them the same score. However, it seems that F was signficicantly harder than E based on the number of solves. Another thing was that FST for this problem were caused by testdata that involved sequences of '1's of increasing length.",
    "code": "import sys\nrange = xrange\ninput = raw_input\n\ninp=sys.stdin.read().split()\n\nn = int(inp[0])\ns=inp[1]\n\ntot=0\ncur=0\n\nhist=[0]*1000005\n\ni=0\n\nwhile (i<n):\n    if (s[i]=='0'):\n        tot+=cur\n    else:\n        l=i\n        r=i\n        while (r+1<n and s[r+1]=='1'): r+=1\n        for x in range(r-l+1):\n            cur+=(l+x+1)-hist[x]\n            tot+=cur\n            hist[x]=r-x+1\n    \n        i=r\n    i+=1\n\nprint(tot)",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dp",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1428",
    "index": "G2",
    "title": "Lucky Numbers (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is in the constraint on $q$. You can make hacks only if all versions of the problem are solved.}\n\nZookeeper has been teaching his $q$ sheep how to write and how to add. The $i$-th sheep has to write exactly $k$ \\textbf{non-negative integers} with the sum $n_i$.\n\nStrangely, sheep have superstitions about digits and believe that the digits $3$, $6$, and $9$ are lucky. To them, the fortune of a number depends on the decimal representation of the number; the fortune of a number is equal to the sum of fortunes of its digits, and the fortune of a digit depends on its value and position and can be described by the following table. For example, the number $319$ has fortune $F_{2} + 3F_{0}$.\n\nEach sheep wants to maximize the \\textbf{sum of fortune} among all its $k$ written integers. Can you help them?",
    "tutorial": "0 is a lucky number as well. There is at most one number whose digits is not entirely 0, 3, 6, 9. Knapsack. Group same items. Suppose in our final solution, there is a certain position (ones, tens...) that has two digits which are not $0$, $3$, $6$, or $9$. Let these two digits are $a$ and $b$. If $a+b \\leq 9$, we can replace these two digits with $0$, and $a+b$. Otherwise, we can replace these two digits with $9$ and $a+b-9$. By doing this, our solution is still valid as the sum remains the same, and the total fortune will not decrease since $a$ and $b$ are not $3$, $6$ or $9$. As such, in the optimal solution, there should be at most one number that consists of digits that are not $0$, $3$, $6$ or $9$. Let's call this number that has other digits $x$. Since there's only one query, we can try all possibilities of $x$. The question reduces to finding the maximum sum of fortune among $k-1$ numbers containing the digits $0$, $3$, $6$ and $9$ that sum up to exactly $n-r$. We can model this as a 0-1 knapsack problem, where the knapsack capacity is $n-r$. For the ones position, the value (fortune) can be increased by $F_0$ for a weight of $3$ a total of $3(k-1)$ times, so we can create $3(k - 1)$ objects of weight $3$ and value $F_0$. For tens it's $F_1$ for a weight of $30$, and so on. Since there are many duplicate objects, we can group these duplicate objects in powers of $2$. For example, $25$ objects can be grouped into groups of $1$, $2$, $4$, $8$, $10$. This runs in $O(ndlogk)$ where $d$ is the number of digits (6 in this case) In the hard version, we are not able to search all $n$ possibilities for the last number $x$ as there are many queries. Using the 0-1 knapsack with duplicates, we have computed the dp table for the first $k-1$ numbers. The rest is incorporating the last number into the dp table. We can do this by considering each digit separately. Then, we can update the dp table by considering all possible transitions for all digits from $0$ to $9$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long inf = (1LL << 58LL);\nlong long F[6];\nlong long fortune[10] = {0, 0, 0, 1, 0, 0, 2, 0, 0, 3};\nlong long ten[6] = {1, 10, 100, 1000, 10000, 100000};\nlong long dp[1000005];\n\nint main(){\n\tios_base::sync_with_stdio(false); cin.tie(0);\n\tint K; int N = 999999;\n\t\n\tcin >> K;\n\tfor(int i = 0;i <= 5;i++) cin >> F[i];\n\t\n\t\n\tfill(dp,dp+N+1,-inf); dp[0] = 0;\n\tfor(int d = 0;d <= 5;d++){\n\t\tlong long left = 3 * (K - 1);\n\t\tlong long group = 1;\n\t\t\n\t\t///grouping 3*(K-1) elements into groups of powers of 2\n\t\twhile(left > 0){\n\t\t\tgroup = min(group, left);\n\t\t\t\n\t\t\tlong long value = group * F[d];\n\t\t\tlong long weight = group * ten[d] * 3;\n\t\t\tfor(int i = N;i >= weight;i--) dp[i] = max(dp[i], dp[i-weight] + value); ///knapsack DP\n\t\t\t\n\t\t\tleft -= group;\n\t\t\tgroup *= 2;\n\t\t}\n\t}\n\t\n\tfor(int d = 0;d <= 5;d++){\n\t\tfor(int i = N;i >= 0;i--){\n\t\t\tfor(int b = 1;b <= 9;b++){\n\t\t\t\tint pre = i - ten[d] * b;\n\t\t\t\tif(pre < 0) break;\n\t\t\t\tdp[i] = max(dp[i], dp[pre] + fortune[b] * F[d]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint Q; cin >> Q;\n\twhile(Q--){\n\t\tint n; cin >> n;\n\t\tcout << dp[n] << \"\\n\";\n\t}\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1428",
    "index": "H",
    "title": "Rotary Laser Lock",
    "statement": "\\textbf{This is an interactive problem.}\n\nTo prevent the mischievous rabbits from freely roaming around the zoo, Zookeeper has set up a special lock for the rabbit enclosure. This lock is called the Rotary Laser Lock.\n\nThe lock consists of $n$ concentric rings numbered from $0$ to $n-1$. The innermost ring is ring $0$ and the outermost ring is ring $n-1$. All rings are split equally into $nm$ sections each. Each of those rings contains a single metal arc that covers exactly $m$ contiguous sections. At the center of the ring is a core and surrounding the entire lock are $nm$ receivers aligned to the $nm$ sections.\n\nThe core has $nm$ lasers that shine outward from the center, one for each section. The lasers can be blocked by any of the arcs. A display on the outside of the lock shows how many lasers hit the outer receivers.\n\nIn the example above, there are $n=3$ rings, each covering $m=4$ sections. The arcs are colored in green (ring $0$), purple (ring $1$), and blue (ring $2$) while the lasers beams are shown in red. There are $nm=12$ sections and $3$ of the lasers are not blocked by any arc, thus the display will show $3$ in this case.\n\nWabbit is trying to open the lock to free the rabbits, but the lock is completely opaque, and he cannot see where any of the arcs are. Given the \\textbf{relative positions} of the arcs, Wabbit can open the lock on his own.\n\nTo be precise, Wabbit needs $n-1$ integers $p_1,p_2,\\ldots,p_{n-1}$ satisfying $0 \\leq p_i < nm$ such that for each $i$ $(1 \\leq i < n)$, Wabbit can rotate ring $0$ clockwise exactly $p_i$ times such that the sections that ring $0$ covers perfectly aligns with the sections that ring $i$ covers. In the example above, the relative positions are $p_1 = 1$ and $p_2 = 7$.\n\nTo operate the lock, he can pick any of the $n$ rings and rotate them by $1$ section either clockwise or anti-clockwise. You will see the number on the display after every rotation.\n\nBecause his paws are small, Wabbit has asked you to help him to find the \\textbf{relative positions} of the arcs \\textbf{after all of your rotations are completed}. You may perform up to $15000$ rotations before Wabbit gets impatient.",
    "tutorial": "Using only arc $0$, find at least $1$ position where arc $0$ exactly matches another arc. Binary Search. Flatten the circle such that it becomes $n$ rows of length $nm$ with vertical sections numbered from $0$ to $nm-1$ that loops on the end. We say that the position of an arc is $x$ if the left endpoint of the arc is at section $x$. Indices are taken modulo $nm$ at all times. Moving arcs right is equivalent to rotating them clockwise, and moving arcs left is equivalent to rotating them counter-clockwise. Notice that if we shift arc 0 right and the display increases, then the leftmost section of arc 0 had no other arcs in the same section. Thus, if we shift arc 0 right again and the display does not increase, we are certain that there was another arc at that position, so we shift arc 0 left. We now enter the detection stage to find any arc that coincides with arc 0 (of which there exists at least 1) at this position. Let's note down this positions as $x$. Let $S$ be the set of arcs that we do not know the positions of yet (this set initially contains all arcs from 1 to $N-1$) and $T$ and $F$ be an empty sets. $T$ will be the set of all candidate arcs (those that may coincide here) and $F$ will contain all arcs that we have shifted leftwards. Take all elements in $S$ and put them in $T$, and pick half of the elements in $S$ and add them to the set $F$. We now shift all elements in $F$ left. We move arc 0 left to check if any arc is at position $x-1$. If there is, then we know that an arc that initially coincided at $x$ lies in $F$. In this case, we set $T$ to $T \\cap F$ (elements of $T$ that are in $F$), pick half of the elements in $T$ to move right and remove those from $F$. If no arc is at position $x-1$, then the arc we are looking for lies in $T \\ \\backslash \\ F$ (elements in $T$ that are not in $F$). We set $T$ to be $T \\ \\backslash \\ F$ and pick half of $T$ to move left and add those to $F$. We then shift arc 0 right and recurse. When we have narrowed $T$ to exactly 1 arc, we know where exactly that arc is now. We shift that arc left such that its right endpoint is at $x-2$ so that it does not cover position $x-1$, which we may still need for future tests. Now we remove the arc found from $S$ and leave the detection stage and continue searching for the other arcs. Once we have found all $n-1$ other arcs, we find the relative position to arc 0 and print them as the final output. Whenever we shift arc 0 right and are not in the detection stage, we use 1 shift. This occurs at most $2nm-m$ times because it takes up to $nm-m$ shifts right to find the first position where arc 0 coincides, and another $nm$ to traverse the entire circle again to find all of the arcs. Whenever we enter the detection stage, we find one arc and use $2$ shifts initially when we move arc 0 right then left, yielding a total of $2n-2$ such shifts. Each binary search requires $2 \\log |T|$ shifts of arc 0 (left and right), so across the $n-1$ detection stages this is at most $2n\\log n$ when summed across all stages. The way we perform the binary search is quite important here. Performing it in a naive manner (e.g. shifting half left, test and shifting them back) can use up to $n^2$ queries. Instead, we set the number of elements that move in / out of $F$ at each iteration of the binary search to be the smaller half. This way we can guarantee that the number of shifts done by the candidate arcs is at most the total number of candidate arcs in the first place. This becomes $\\frac{n(n-1)}{2}$ since we start with $n-1$ candidate arcs and reduce that number by 1 after each detection stage. When we shift each of the arcs left by $m$ or $m+1$ (depending on whether they were in $F$ when we narrowed it down to 1 arc), we use at most $(n-1)(m+1) = nm+n-m-1$ shifts. Thus in total, we use at most $2nm-m+2n-2+2n\\log n + \\frac{n(n-1)}{2} + nm+n-m-1$ shifts. For $n=100,m=20$, this is less than $13000$, which is much lower than the query limit of $15000$. The limit was set higher than the provable bound to allow for other possible solutions. At least $1$ tester found a different solution that used around $13500$ queries. Some other optimizations that empirically improve the number of queries: Instead of using arc $0$ as the detector, we can randomly pick one of the $n$ arcs as the detector arcs. Instead of using arc $0$ as the detector, we can randomly pick one of the $n$ arcs as the detector arcs. At the very beginning, we perform some constant number of random shifts of the arcs (e.g. $300$ to $400$ random shifts). This helps to break up long groups of arcs that overlap, which speeds up the initial $nm$ search. At the very beginning, we perform some constant number of random shifts of the arcs (e.g. $300$ to $400$ random shifts). This helps to break up long groups of arcs that overlap, which speeds up the initial $nm$ search. The official solution, augmented with these optimizations uses well below $11500$ queries and is very consistent for non-handcrafted test cases.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint queryRotation(int r, int d){ // Auxiliary function to print query and receive answer\n\tint res;\n\tcout << \"? \" << r << ' ' << d << endl << flush; \t// Print query\n\tcout.flush();\n\tcin >> res; \t\t\t\t\t\t\t\t\t\t// Get response\n\tif (res == -1) exit(1); \t\t\t\t\t\t\t// Error occured, exit immediately\n\telse return res; \t\t\t\t\t\t\t\t\t// Return result\n}\n\n\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\n\tint N, M; \t\t\t\t// Number of rings and number of sections per ring\n\tint totalPositions; \t// totalPositions = N*M\n\tint newNum; \n\tint currentNum; \t\t// track the current number on the display (responses from interactor)\n\tint state = 0;\t\t\t// 0 means searching for rings, 1 means finding the ring at this position\n\tint relpos[105] = {}; \t\t// Array to store the final relative positions\n\n\tcin >> N >> M;\n\ttotalPositions = N*M;\n\n\t// While this statement doesn't do anything, \n\t// it serves as a reminder that we are taking \n\t// the initial starting position of ring 0 \n\t// to be position 0\n\trelpos[0] = 0; \n\t\n\tcurrentNum = queryRotation(0,1);\n\trelpos[0] = (relpos[0] + 1) % totalPositions;\n\t\n\n\t// Now we prepare the set of unknown rings S\n\tvector<int> S;\n\tfor (int i = 1; i < N; ++i){\n\t\tS.push_back(i);\n\t}\n\n\t// We now perform a preliminary rotation of ring 0 around until \n\t// we are certain that ring 0 coincides with another ring \n\t// at its leftmost point and the section to its left is empty\n\n\t// This occurs when the difference changes from increasing when \n\t// ring 0 moves right to non-increasing when ring 0\n\t// moves right\n\tint hasIncreased = 0; \n\twhile (1){\n\t\t// Rotate once, get the new number\n\t\tnewNum = queryRotation(0,1);\n\t\trelpos[0] = (relpos[0] + 1) % totalPositions;\n\t\t// Check if the number has increased\t\t\n\t\tif (newNum > currentNum){\n\t\t\thasIncreased = 1;\t\n\t\t\tcurrentNum = newNum;\n\t\t} \t\n\t\telse{ // Otherwise the number hasn't increased\t\t\n\t\t\tcurrentNum = newNum;\n\t\t\t// Check if we have increased before\n\t\t\tif (hasIncreased){ \n\n\t\t\t\t// If we have, it means that our previous position \n\t\t\t\t// coincided with the left endpoint of another arc\n\t\t\t\t// Time to begin the detection stage\n\t\t\t\tstate = 1;\n\t\t\t\tcurrentNum = queryRotation(0,-1);\n\t\t\t\trelpos[0] = (relpos[0] - 1 + totalPositions) % totalPositions;\n\t\t\t\tbreak;\n\t\t\t}\t\t\t\t\t\t\t\n\t\t}\n\t\t\n\t}\n\t\n\twhile (!S.empty()){ // While we haven't found all of the rings yet\n\t\tif (state == 1){ // If we are searching for an arc here\n\t\t\tint curArc = 0; // to store the new arc\n\n\t\t\tvector<int> T = S;\t// set of candiate arcs\n\t\t\tvector<int> F;\t\t// set of arcs that have been moved left\n\n\t\t\tfor (int i = 0; i < T.size()/2; ++i){ // take the smaller half\n\t\t\t\tF.push_back(T[i]);\n\t\t\t\tcurrentNum = queryRotation(T[i],-1);\n\t\t\t}\n\n\t\t\twhile (T.size() > 1){ // while the number of candidate arcs is > 1, we binary search on the remaining arcs\n\t\t\t\tint newNum = queryRotation(0,-1);\n\t\t\t\trelpos[0] = (relpos[0] - 1 + totalPositions) % totalPositions;\n\t\t\t\tif (newNum >= currentNum){ // the arc that we are looking for lies in F\n\n\t\t\t\t\t// Set T to F\n\t\t\t\t\tT.clear();\n\t\t\t\t\tfor (auto it : F){\n\t\t\t\t\t    T.push_back(it);\n\t\t\t\t\t}\t\n\n\t\t\t\t\t// Half the size of F by moving the smaller half to the right\t\t\t\t\t\t\t\n\t\t\t\t\tint sz = F.size()/2;\n\t\t\t\t\tfor (int i = 0; i < sz; ++i){\n\t\t\t\t\t\tint revRing = F.back();\n\t\t\t\t\t\tcurrentNum = queryRotation(revRing,1);\n\t\t\t\t\t\tF.pop_back();\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\telse{ // the arc we are looking for does not lie in F\n\t\t\t\t\tvector<int> temp;\n\t\t\t\t\tfor (auto it1 : T){\n\t\t\t\t\t    int check = 0;\n\t\t\t\t\t    for (auto it2 : F){\n\t\t\t\t\t        if (it1 == it2) check = 1;\n\t\t\t\t\t    }\n\t\t\t\t\t    if (!check) temp.push_back(it1);\n\t\t\t\t\t}\n\t\t\t\t\tT = temp;\n\t\t\t\t\tF.clear();\n\t\t\t\t\tfor (int i = 0; i < T.size()/2; ++i){ // take the smaller half once again\n\t\t\t\t\t\tcurrentNum = queryRotation(T[i],-1);\n\t\t\t\t\t\tF.push_back(T[i]);\n\t\t\t\t\t}\n\t\t\t\t}\t\n\t\t\t\tcurrentNum = queryRotation(0,1); // bring arc 0 back\n\t\t\t\trelpos[0] = (relpos[0] + 1) % totalPositions;\n\t\t\t}\n            \n\t\t\tcurArc = T[0]; // we have found the arc\n\t\t\t\n\n\t\t\t// we want this arc to be M+1 sections away from the current position \n\t\t\t// of arc 0 so that it does not interfere with later searches\n\n\t\t\tif (!F.empty()){ // the arc we found still lies in F\n\t\t\t\tfor (int i = 0; i < M; ++i){ // move the arc back by M sections\n\t\t\t\t\tcurrentNum = queryRotation(curArc,-1);\n\t\t\t\t}\n\t\t\t\trelpos[curArc] = relpos[0] - M - 1;\n\t\t\t}\n\t\t\telse{ // the arc we found does not lie in F\n\t\t\t\tfor (int i = 0; i <= M; ++i){ // move the arc back by M+1 sections\n\t\t\t\t\tcurrentNum = queryRotation(curArc,-1);\n\t\t\t\t}\n\t\t\t\trelpos[curArc] = relpos[0] - M - 1;\n\t\t\t}\n\t\t\t// We now remove curArc from S\n\t\t\tvector<int> temp;\n\t\t\tfor (auto it : S){\n\t\t\t\tif (it != curArc) temp.push_back(it); \n\t\t\t}\n\t\t\tS.clear();\n\t\t\tfor (auto it : temp) S.push_back(it);\n\t\t\t\n\t\t\t\n\t\t\tstate = 0;\n\t\t\tcurrentNum = queryRotation(0,-1);\n\t\t\trelpos[0] = (relpos[0] - 1 + totalPositions) % totalPositions;\n\t\t\thasIncreased = 0;\n\t\t}\n\t\telse{ // keep moving right\n\t\t    \n\t\t\tnewNum = queryRotation(0,1);\n\t\t\trelpos[0] = (relpos[0] + 1) % totalPositions;\n\t\t\tif (newNum <= currentNum && hasIncreased == 1){ // start searching\n\t\t\t\tnewNum = queryRotation(0,-1);\n\t\t\t\trelpos[0] = (relpos[0] - 1 + totalPositions) % totalPositions;\n\t\t\t\tstate = 1;\n\t\t\t}\n\t\t\telse if (newNum > currentNum) hasIncreased = 1;\n\t\t\tcurrentNum = newNum;\n\t\t}\n\n\t}\n\tcout << \"! \";\n\tfor (int i = 1; i < N; ++i){\n\t\tcout << (((relpos[i] - relpos[0] + 5 * totalPositions)%totalPositions) + totalPositions) % totalPositions << ' ';\n\t}\n\tcout << endl << flush;\n\n}",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1430",
    "index": "A",
    "title": "Number of Apartments",
    "statement": "Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.\n\nMonocarp went around the building and counted $n$ windows. Now he is wondering, how many apartments of each type the building may have.\n\nUnfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $n$ windows. If there are multiple answers, you can print any of them.\n\nHere are some examples:\n\n- if Monocarp has counted $30$ windows, there could have been $2$ three-room apartments, $2$ five-room apartments and $2$ seven-room apartments, since $2 \\cdot 3 + 2 \\cdot 5 + 2 \\cdot 7 = 30$;\n- if Monocarp has counted $67$ windows, there could have been $7$ three-room apartments, $5$ five-room apartments and $3$ seven-room apartments, since $7 \\cdot 3 + 5 \\cdot 5 + 3 \\cdot 7 = 67$;\n- if Monocarp has counted $4$ windows, he should have mistaken since no building with the aforementioned layout can have $4$ windows.",
    "tutorial": "There are many possible solutions to this problem. The simplest one is to notice that, using several flats of size $3$ and one flat of some size (possibly also $3$, possibly not), we can get any $n$ equal to $[3, 6, 9, \\dots]$, $[5, 8, 11, \\dots]$ or $[7, 10, 13, \\dots]$. The only numbers that don't belong to these lists are $1$, $2$ and $4$, and it's easy to see that there is no answer for that numbers. So the solution is to try all possible sizes of one flat, and if the remaining number of windows is non-negative and divisible by $3$, then take the required number of three-room flats.",
    "code": "#include <iostream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n#include <cmath>\n#include <queue>\n#include <string>\n#include <cstring>\n#include <cassert>\n#include <iomanip>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <ctime>\n#include <cmath>\n\n#define forn(i, n) for(int i=0;i<n;++i)\n#define fore(i, l, r) for(int i = int(l); i <= int(r); ++i)\n#define sz(v) int(v.size())\n#define all(v) v.begin(), v.end()\n#define pb push_back\n#define mp make_pair\n#define x first\n#define y1 ________y1\n#define y second\n#define ft first\n#define sc second\n#define pt pair<int, int>\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntypedef long long li;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int INF = 1000 * 1000 * 1000;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n\nli n;\n\ninline void read() {\t\n\tcin >> n;\n}\n\ninline void solve() {\n\tif (n == 1 || n == 2 || n == 4) {\n\t\tcout << -1 << endl;\n\t\treturn;\n\t}\n\tif (n % 3 == 0) {\n\t\tcout << n / 3 << ' ' << 0 << ' ' << 0 << endl;\n\t} else if (n % 3 == 1) {\n\t\tcout << (n - 7) / 3 << ' ' << 0 << ' ' << 1 << endl;\n\t} else {\n\t\tcout << (n - 5) / 3 << ' ' << 1 << ' ' << 0 << endl;\n\t}\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    cerr << setprecision(10) << fixed;\n    \n    int t; cin >> t;\n    while(t--) {\n    \tread();\n    \tsolve();\n    }\n \n    //cerr << \"TIME: \" << clock() << endl;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1430",
    "index": "B",
    "title": "Barrels",
    "statement": "You have $n$ barrels lined up in a row, numbered from left to right from one. Initially, the $i$-th barrel contains $a_i$ liters of water.\n\nYou can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $x$ and $y$ (the $x$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $x$ to barrel $y$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them.\n\nCalculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water \\textbf{at most} $k$ times.\n\nSome examples:\n\n- if you have four barrels, each containing $5$ liters of water, and $k = 1$, you may pour $5$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $[5, 0, 5, 10]$, and the difference between the maximum and the minimum is $10$;\n- if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $0$.",
    "tutorial": "A greedy strategy always works: take $k + 1$ largest barrels, choose one barrel among them and pour all water from those barrels to the chosen barrel. That way, we make the minimum amount equal to $0$ (it's quite obvious that we can't do anything better here), and the maximum amount as large as possible, so the difference between them will be as large as possible.",
    "code": "#include <iostream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n#include <cmath>\n#include <queue>\n#include <string>\n#include <cstring>\n#include <cassert>\n#include <iomanip>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <ctime>\n#include <cmath>\n\n#define forn(i, n) for(int i=0;i<n;++i)\n#define fore(i, l, r) for(int i = int(l); i <= int(r); ++i)\n#define sz(v) int(v.size())\n#define all(v) v.begin(), v.end()\n#define pb push_back\n#define mp make_pair\n#define x first\n#define y1 ________y1\n#define y second\n#define ft first\n#define sc second\n#define pt pair<int, int>\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntypedef long long li;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int INF = 1000 * 1000 * 1000;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\nconst int N = 200 * 1000 + 13;\n\nint n, k;\nint a[N];\n\ninline void read() {\t\n\tcin >> n >> k;\n\tfor (int i = 0; i < n; i++) cin >> a[i];\n}\n\ninline void solve() {\n\tsort(a, a + n);\n\treverse(a, a + n);\n\tli ans = 0;\n\tfor (int i = 0; i <= k; i++) {\n\t\tans += a[i];\n\t}\n\tcout << ans << endl;\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    cerr << setprecision(10) << fixed;\n    \n    int t; cin >> t;\n    while(t--) {\n    \tread();\n    \tsolve();\n \t}\n    //cerr << \"TIME: \" << clock() << endl;\n}\n",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1430",
    "index": "C",
    "title": "Numbers on Whiteboard",
    "statement": "Numbers $1, 2, 3, \\dots n$ (each integer from $1$ to $n$ once) are written on a board. In one operation you can erase any two numbers $a$ and $b$ from the board and write one integer $\\frac{a + b}{2}$ rounded up instead.\n\nYou should perform the given operation $n - 1$ times and make the resulting number that will be left on the board as small as possible.\n\nFor example, if $n = 4$, the following course of action is optimal:\n\n- choose $a = 4$ and $b = 2$, so the new number is $3$, and the whiteboard contains $[1, 3, 3]$;\n- choose $a = 3$ and $b = 3$, so the new number is $3$, and the whiteboard contains $[1, 3]$;\n- choose $a = 1$ and $b = 3$, so the new number is $2$, and the whiteboard contains $[2]$.\n\nIt's easy to see that after $n - 1$ operations, there will be left only one number. Your goal is to minimize it.",
    "tutorial": "It's easy to see that we can't get the result less than $2$, because, if we merge two positive numbers, and at least one of them is $2$ or greater, the new number is always greater than $1$. So we can't get rid of all numbers greater than $1$. To always achieve $2$, we can use a greedy algorithm: always merge two maximum numbers. During the first step, we merge $n$ and $n - 1$, get $n$; then we merge $n$ and $n - 2$, get $n - 1$; then we merge $n - 1$ and $n - 3$, get $n - 2$; and it's easy to see that the last operation is merging $3$ and $1$, so the result is $2$.",
    "code": "#include <iostream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n#include <cmath>\n#include <queue>\n#include <string>\n#include <cstring>\n#include <cassert>\n#include <iomanip>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <ctime>\n#include <cmath>\n\n#define forn(i, n) for(int i=0;i<n;++i)\n#define fore(i, l, r) for(int i = int(l); i <= int(r); ++i)\n#define sz(v) int(v.size())\n#define all(v) v.begin(), v.end()\n#define pb push_back\n#define mp make_pair\n#define x first\n#define y1 ________y1\n#define y second\n#define ft first\n#define sc second\n#define pt pair<int, int>\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntypedef long long li;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int INF = 1000 * 1000 * 1000;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n\nint n;\n\ninline void read() {\t\n\tcin >> n;\n}\n\ninline void solve() {\n\tmultiset<int> was;\n\tfor (int i = 1; i <= n; i++) {\n\t\twas.insert(i);\n\t}\n\tvector<pair<int, int> > ans;\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tauto it = was.end();\n\t\tit--;\n\t\tint a = *it;\n\t\twas.erase(it);\n\t\tit = was.end();\n\t\tit--;\n\t\tint b = *it;\n\t\twas.erase(it);\n\t\twas.insert((a + b + 1) / 2);\n\t\tans.pb(mp(a, b));\n\t}\n\tcout << *was.begin() << endl;\n\tfor (int i = 0; i < sz(ans); i++) {\n\t\tcout << ans[i].ft << ' ' << ans[i].sc << endl;\n\t}\t\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    cerr << setprecision(10) << fixed;\n    \n    int t; cin >> t;\n    while(t--) {\n    \tread();\n    \tsolve();\n    }\n    //cerr << \"TIME: \" << clock() << endl;\n}\n",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1430",
    "index": "D",
    "title": "String Deletion",
    "statement": "You have a string $s$ consisting of $n$ characters. Each character is either 0 or 1.\n\nYou can perform operations on the string. Each operation consists of two steps:\n\n- select an integer $i$ from $1$ to the length of the string $s$, then delete the character $s_i$ (the string length gets reduced by $1$, the indices of characters to the right of the deleted one also get reduced by $1$);\n- if the string $s$ is not empty, delete the maximum length prefix consisting of the same characters (the indices of the remaining characters and the string length get reduced by the length of the deleted prefix).\n\nNote that both steps are mandatory in each operation, and their order cannot be changed.\n\nFor example, if you have a string $s =$ 111010, the first operation can be one of the following:\n\n- select $i = 1$: we'll get 111010 $\\rightarrow$ 11010 $\\rightarrow$ 010;\n- select $i = 2$: we'll get 111010 $\\rightarrow$ 11010 $\\rightarrow$ 010;\n- select $i = 3$: we'll get 111010 $\\rightarrow$ 11010 $\\rightarrow$ 010;\n- select $i = 4$: we'll get 111010 $\\rightarrow$ 11110 $\\rightarrow$ 0;\n- select $i = 5$: we'll get 111010 $\\rightarrow$ 11100 $\\rightarrow$ 00;\n- select $i = 6$: we'll get 111010 $\\rightarrow$ 11101 $\\rightarrow$ 01.\n\nYou finish performing operations when the string $s$ becomes empty. What is the maximum number of operations you can perform?",
    "tutorial": "Suppose the string consists of $n$ characters, and each character is different from the adjacent ones (so the string looks like 01010... or 10101...). It's easy to see that we can't make more than $\\lceil \\frac{n}{2} \\rceil$ operations (each operation deletes at least two characters, except for the case when the string consists of only one character). And there is an easy way to perform exactly $\\lceil \\frac{n}{2} \\rceil$ operations: always choose the last character and delete it. Okay, what about the case when some adjacent characters in the string are equal? It's never optimal to delete a character that's different from both adjacent characters: since the second part of each operation always deletes the left block of equal characters, this action merges two blocks, so they will be deleted in one second part of the operation (which decreases the total number of operations). So, we should always delete a character from a block with at least two equal characters. From which of the blocks, if there are more than one? It's easy to see that we should choose a character from the leftmost such block, since that block is the earliest to be deleted (and if we want to make the same action later, we might be unable to do it). So, the solution is greedy: during each action, we have to find the leftmost block consisting of at least $2$ equal characters, and delete a character from it (or the last character of the string, if there are no such blocks). Since the length of the string is up to $2 \\cdot 10^5$ and the number of operations is up to $10^5$, we should do it efficiently, for example, by storing the eligible blocks in some data structure.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nchar buf[200043];\n\nint main()\n{\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int tc = 1; tc <= t; tc++) {\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tscanf(\"%s\", buf);\n\t\tstring s = buf;\n\t\tqueue<int> q;\n\t\tint cur = 0;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t \tif(i > 0 && s[i] != s[i - 1])\n\t\t \t\tcur++;\n\t\t \tif(i > 0 && s[i] == s[i - 1])\n\t\t \t\tq.push(cur);\n\t\t}\n\t\tint deleted = 0;       \n\t\tint score = 0;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tif(q.empty())\n\t\t\t\tbreak;\n\t\t\tq.pop();\n\t\t\tdeleted++;\n\t\t\tscore++;\n\t\t\twhile(!q.empty() && q.front() == i)\n\t\t\t{\n\t\t\t\tq.pop();\n\t\t\t\tdeleted++; \t\n\t\t\t}\n\t\t\tdeleted++;\n\t\t\t//cerr << deleted << endl;\n\t\t}\n\t\tscore += (n - deleted + 1) / 2;\n\t\tprintf(\"%d\\n\", score);\n\t}\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1430",
    "index": "E",
    "title": "String Reversal",
    "statement": "You are given a string $s$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string \"abddea\", you should get the string \"aeddba\". To accomplish your goal, you can swap the \\textbf{neighboring elements of the string}.\n\nYour task is to calculate the minimum number of swaps you have to perform to reverse the given string.",
    "tutorial": "First of all, let's find the resulting position for each character of the string. It's easy to see that we don't need to swap equal adjacent characters (it changes nothing), so the first character a in the original string is the first character a in the resulting string, the second character a in the original string is the second character a in the resulting string, and so on. Now, let's build a permutation $p$ of $n$ elements, where $p_i$ is the resulting position of the element that was on position $i$ in the original string. For example, for the string abcad this permutation will be $p = [2, 4, 3, 5, 1]$. In one operation, we may swap two elements in this permutation, and our goal is to sort it (since each character of the string has its own required position, and when for every $i$ the condition $p_i = i$ holds, each character is on the position it should be). The required number of swaps of adjacent elements to sort a permutation is exactly the number of inversions in it (since each swap changes the number of inversions by $1$), and this number can be calculated using many different techniques, for example, mergesort tree or Fenwick tree.",
    "code": "#include <iostream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n#include <cmath>\n#include <queue>\n#include <string>\n#include <cstring>\n#include <cassert>\n#include <iomanip>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <ctime>\n#include <cmath>\n\n#define forn(i, n) for(int i=0;i<n;++i)\n#define fore(i, l, r) for(int i = int(l); i <= int(r); ++i)\n#define sz(v) int(v.size())\n#define all(v) v.begin(), v.end()\n#define pb push_back\n#define mp make_pair\n#define x first\n#define y1 ________y1\n#define y second\n#define ft first\n#define sc second\n#define pt pair<int, int>\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntypedef long long li;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int INF = 1000 * 1000 * 1000;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\nconst int N = 200 * 1000 + 13;\n\nint n;\nstring s;\nstring revS;\nvector<int> posS[30];\nvector<int> posT[30];\nint cnt[30];\nint t[N];\n\ninline int sum (int r) {\n\tint result = 0;\n\tfor (; r >= 0; r = (r & (r+1)) - 1)\n\t\tresult += t[r];\n\treturn result;\n}\n\ninline void inc (int i, int d) {\n\tfor (; i < n; i = (i | (i+1)))\n\t\tt[i] += d;\n}\n\nint sum (int l, int r) {\n\treturn sum (r) - sum (l-1);\n}\n     \ninline void read() {\t\n\tcin >> n >> s;\n}\n\ninline void solve() {\n\trevS = s;\n\treverse(all(revS));\n\tfor (int i = 0; i < sz(s); i++) {\n\t\tposS[s[i] - 'a'].pb(i);\n\t\tposT[revS[i] - 'a'].pb(i);\n\t}\n\tli ans = 0;\n\tfor (int i = 0; i < sz(revS); i++) {\n\t\tint let = revS[i] - 'a';\n\t\tint cur = posS[let][cnt[let]];\n\t\tint oldC = cur;\n\t\tcur += sum(cur, n - 1);\n\t\tint need = i;\n\t\tans += cur - need;\n\t\tinc(oldC, 1);\n\t\tcnt[let]++;\n\t}\n\tcout << ans << endl;\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    srand(time(NULL));\n    cerr << setprecision(10) << fixed;\n    \n    read();\n    solve();\n \n    //cerr << \"TIME: \" << clock() << endl;\n}\n",
    "tags": [
      "data structures",
      "greedy",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1430",
    "index": "F",
    "title": "Realistic Gameplay",
    "statement": "Recently you've discovered a new shooter. They say it has realistic game mechanics.\n\nYour character has a gun with magazine size equal to $k$ and should exterminate $n$ waves of monsters. The $i$-th wave consists of $a_i$ monsters and happens from the $l_i$-th moment of time up to the $r_i$-th moments of time. All $a_i$ monsters spawn at moment $l_i$ and you have to exterminate all of them before the moment $r_i$ ends (you can kill monsters right at moment $r_i$). For every two consecutive waves, the second wave starts not earlier than the first wave ends (though the second wave can start at the same moment when the first wave ends) — formally, the condition $r_i \\le l_{i + 1}$ holds. Take a look at the notes for the examples to understand the process better.\n\nYou are confident in yours and your character's skills so you can assume that aiming and shooting are instant and you need exactly one bullet to kill one monster. But reloading takes exactly $1$ unit of time.\n\nOne of the realistic mechanics is a mechanic of reloading: when you reload you throw away the old magazine with all remaining bullets in it. That's why constant reloads may cost you excessive amounts of spent bullets.\n\nYou've taken a liking to this mechanic so now you are wondering: what is the minimum possible number of bullets you need to spend (both used and thrown) to exterminate all waves.\n\nNote that you don't throw the remaining bullets away after eradicating all monsters, and you start with a full magazine.",
    "tutorial": "Note some observations: if we meet a new wave and start shooting it's optimal to shoot monsters in the wave using full magazines while we can and there are no reasons to take breaks between shooting monsters from one wave. That's why we can track only moments when waves start and the number of remaining bullets in magazine we have at these moments. Moreover, since the next wave starts not earlier than the previous ends, we can think that when we start dealing with one wave we've already dealt with the previous one. Also, instead of keeping track of the remaining bullets, let's just look only at such indices of waves when we reloaded and threw remaining bullets before reaching them. So, we can write the next dp: $d[i]$ is the minimum number of bullets we spend dealing with the first $i$ waves and now we standing at the moment $l_i$ with full magazine. Obviously, $dp[0] = 0$. Now, with fixed $i$ we can iterate over the index $j$ of a wave before which we'll reload throwing away remaining bullets. And for waves $[i, j)$ we need to check that we are able to exterminate all these waves without throwing away any bullets. We can check it with several formulas. If it's possible for segment $[i, j)$ then the possibility for the segment $[i, j + 1)$ is just checking that we can exterminate the $j$-th wave having $rem \\ge 0$ bullets in the start in no more than $r_j - l_j$ reloads plus checking that we have at least one unit before $l_{j + 1}$ for a reload. As a result, the time complexity of the solution is $O(n^2)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nint n, k;\nvector<int> l, r, a;\n\ninline bool read() {\n\tif(!(cin >> n >> k))\n\t\treturn false;\n\tl.resize(n);\n\tr.resize(n);\n\ta.resize(n);\n\t\n\tfore(i, 0, n)\n\t\tcin >> l[i] >> r[i] >> a[i];\n\t\n\treturn true;\n}\n\ninline void solve() {\n\tvector<li> d(n + 1, INF64);\n\td[0] = 0;\n\t\n\tli ans = INF64;\n\tfore(i, 0, n) {\n\t\tli rem = k, total = d[i];\n\t\tfor (int j = i; j < n; j++) {\n\t\t\tli cntReloads = (max(0LL, a[j] - rem) + k - 1) / k;\n\t\t\tif (cntReloads > r[j] - l[j])\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tli newRem = (rem + cntReloads * k) - a[j];\n\t\t\ttotal += a[j];\n\t\t\tif (j + 1 < n) {\n\t\t\t\tif (l[j] + cntReloads < l[j + 1])\n\t\t\t\t\td[j + 1] = min(d[j + 1], total + newRem);\n\t\t\t} else\n\t\t\t\tans = min(ans, total);\n\t\t\trem = newRem;\n\t\t}\n\t}\n\tif (ans > INF64 / 2)\n\t\tans = -1;\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1430",
    "index": "G",
    "title": "Yet Another DAG Problem",
    "statement": "You are given a directed acyclic graph (a directed graph that does not contain cycles) of $n$ vertices and $m$ arcs. The $i$-th arc leads from the vertex $x_i$ to the vertex $y_i$ and has the weight $w_i$.\n\nYour task is to select an integer $a_v$ for each vertex $v$, and then write a number $b_i$ on each arcs $i$ such that $b_i = a_{x_i} - a_{y_i}$. You must select the numbers so that:\n\n- all $b_i$ are positive;\n- the value of the expression $\\sum \\limits_{i = 1}^{m} w_i b_i$ is the lowest possible.\n\nIt can be shown that for any directed acyclic graph with non-negative $w_i$, such a way to choose numbers exists.",
    "tutorial": "The key observation in this problem is that the values of $a_v$ should form a contiguous segment of integers. For example, suppose there exists a value $k$ such that there is at least one $a_v < k$, there is at least one $a_v > k$, but no $a_v = k$. We can decrease all values of $a_v$ that are greater than $k$ by $1$, so the answer will still be valid, but the value of $\\sum \\limits_{i = 1}^{m} w_i b_i$ will decrease. So, the values of $a_v$ form a contiguous segment of integers. We can always assume that this segment is $[0, n - 1]$, since subtracting the same value from each $a_v$ does not change anything. The other observation we need is that we can rewrite the expression we have to minimize as follows: $\\sum \\limits_{i = 1}^{m} w_i b_i = \\sum \\limits_{v = 1}^{n} a_v c_v$, where $c_v$ is the signed sum of weights of all arcs incident to the vertex $v$ (the weights of all arcs leading from $v$ are taken with positive sign, and the weights of all arcs leading to $v$ are taken with negative sign). These two observations lead us to a bitmask dynamic programming solution: let $dp_{i, mask}$ be the minimum value of $\\sum \\limits_{v = 1}^{n} a_v c_v$, if we assigned the values from $[0, i - 1]$ to the vertices from $mask$. A naive way to calculate this dynamic programming is to iterate on the submask of $mask$, check that choosing the integer $i - 1$ for each vertex from that submask doesn't ruin anything (for each vertex that belongs to this submask, all vertices that are reachable from it should have $a_v < i - 1$, so they should belong to $mask$, but not to the submask we iterate on), and update the dynamic programming value. But this solution is $O(n 3^n)$, and, depending on your implementation, this might be too slow. It's possible to speed this up to $O(n^2 2^n)$ in a way similar to how profile dp can be optimized from $O(3^n)$ to $O(n 2^n)$: we won't iterate on the submask; instead, we will try to add the vertices one by one, and we should be able to add a vertex to the mask only if all vertices that are reachable from it already belong to the mask. There is a possibility that we add two vertices connected by an arc with the same value of $a_v$, so, for a fixed value of $a_v$, we should consider assigning it to vertices in topological sorting order (that way, if one vertex is reachable from another, it will be considered later, so we won't add both of those with the same value of $a_v$).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\nconst int N = 18;\nconst int M = (1 << N);\nconst li INF64 = li(1e18);\n\nint n, m;\nvector<int> g[N];\nli sum[N];\nint need_mask[N];\nli dp[N + 1][N + 1][M];\nbool p[N + 1][N + 1][M];\n\nvector<int> order;       \nvector<int> used;\n\nvoid dfs(int x, bool build_topo)\n{\n    if(used[x])\n    \treturn;\n    used[x] = 1;\n    for(auto y : g[x])\n    \tdfs(y, build_topo);\n    if(build_topo)\n    \torder.push_back(x);\n}\n\nint main()\n{\n\tcin >> n >> m;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t \tint x, y, w;\n\t \tcin >> x >> y >> w;\n\t \t--x;\n\t \t--y;\n\t \tsum[x] += w;\n\t \tsum[y] -= w;\n\t \tg[x].push_back(y);\n\t}\n\tused.resize(n);\n\tfor(int i = 0; i < n; i++)\n\t\tdfs(i, true);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t \tused = vector<int>(n, 0);\n\t \tdfs(i, false);\n\t \tfor(int j = 0; j < n; j++)\n\t \t\tif(j != i && used[j] == 1)\n\t \t\t\tneed_mask[i] |= (1 << j);\t\t\n\t}\n\tfor(int i = 0; i <= n; i++)\n\t\tfor(int j = 0; j <= n; j++)\n\t\t\tfor(int k = 0; k < (1 << n); k++)\n\t\t\t\tdp[i][j][k] = INF64;\n\tdp[0][0][0] = 0;\n\treverse(order.begin(), order.end());\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j <= n; j++)\n\t\t\tfor(int k = 0; k < (1 << n); k++)\n\t\t\t{\n\t\t\t \tif(dp[i][j][k] > INF64 / 2)\n\t\t\t \t\tcontinue;\n\t\t\t \tif(j == n)\n\t\t\t \t{\n\t\t\t \t \tif(dp[i + 1][0][k] > dp[i][j][k])\n\t\t\t \t \t{\n\t\t\t \t \t \tdp[i + 1][0][k] = dp[i][j][k];\n\t\t\t \t \t \tp[i + 1][0][k] = false;\n\t\t\t \t \t}\n\t\t\t \t}\n\t\t\t \telse\n\t\t\t \t{\n\t\t\t \t\tint v = order[j];\n\t\t\t \t\tli add = sum[v] * i;\n\t\t\t \t\tif(dp[i][j + 1][k] > dp[i][j][k])\n\t\t\t \t\t{\n\t\t\t \t\t \tdp[i][j + 1][k] = dp[i][j][k];\n\t\t\t \t\t \tp[i][j + 1][k] = false;\n\t\t\t \t\t}\n\t\t\t \t\tif(((k & (1 << v)) == 0) && ((need_mask[v] & k) == need_mask[v]))\n\t\t\t \t\t{\n\t\t\t \t\t \tint nk = k | (1 << v);\n\t\t\t \t\t \tif(dp[i][j + 1][nk] > dp[i][j][k] + add)\n\t\t\t \t\t \t{\n\t\t\t \t\t \t \tdp[i][j + 1][nk] = dp[i][j][k] + add;\n\t\t\t \t\t \t \tp[i][j + 1][nk] = true;\n\t\t\t \t\t \t}\n\t\t\t\t \t}\n\t\t\t\t}\n\t\t\t}\n\tvector<int> ans(n);\n\tint i = n;\n\tint j = 0;\n\tint k = (1 << n) - 1;\n\twhile(i > 0 || j > 0 || k > 0)\n\t{\n\t \tif(j == 0)\n\t \t{\n\t \t \tj = n;\n\t \t \ti--;\n\t \t}\n\t \telse\n\t \t{\n\t \t \tif(p[i][j][k])\n\t \t \t{\n\t \t \t \tint v = order[j - 1];\n\t \t \t \tans[v] = i;\n\t \t \t \tk ^= (1 << v);\n\t \t\t}\n\t \t\tj--;\n\t \t}\n\t}\n\tfor(int i = 0; i < n; i++)\n\t\tcout << ans[i] << \" \\n\"[i == n - 1];\n}\n",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "flows",
      "graphs",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1433",
    "index": "A",
    "title": "Boring Apartments",
    "statement": "There is a building consisting of $10~000$ apartments numbered from $1$ to $10~000$, inclusive.\n\nCall an apartment \\textbf{boring}, if its number consists of the same digit. Examples of boring apartments are $11, 2, 777, 9999$ and so on.\n\nOur character is a troublemaker, and he calls the intercoms of all \\textbf{boring} apartments, till someone answers the call, in the following order:\n\n- First he calls all apartments consisting of digit $1$, in increasing order ($1, 11, 111, 1111$).\n- Next he calls all apartments consisting of digit $2$, in increasing order ($2, 22, 222, 2222$)\n- And so on.\n\nThe resident of the boring apartment $x$ answers the call, and our character \\textbf{stops} calling anyone further.\n\nOur character wants to know how many digits he pressed in total and your task is to help him to count the total number of keypresses.\n\nFor example, if the resident of boring apartment $22$ answered, then our character called apartments with numbers $1, 11, 111, 1111, 2, 22$ and the total number of digits he pressed is $1 + 2 + 3 + 4 + 1 + 2 = 13$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "This problem has a lot of solutions. You could even hard code all possible tests to solve it. But this problem has $O(1)$ solution. Let the digit of $x$ be $dig$. Then our character pressed each digit before $dig$ exactly $10$ times ($1 + 2 + 3 + 4$). And the amount of times he pressed the digit $dig$ depends on the length of $x$. Let $len$ be the length of $x$, then the amount of times he pressed the digit $dig$ is $1 + 2 + \\ldots + len = \\frac{len(len + 1)}{2}$. So the final answer is $10 \\cdot (dig - 1) + \\frac{len(len + 1)}{2}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tstring x;\n\t\tcin >> x;\n\t\tint dig = x[0] - '0' - 1;\n\t\tint len = x.size();\n\t\tcout << dig * 10 + len * (len + 1) / 2 << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1433",
    "index": "B",
    "title": "Yet Another Bookshelf",
    "statement": "There is a bookshelf which can fit $n$ books. The $i$-th position of bookshelf is $a_i = 1$ if there is a book on this position and $a_i = 0$ otherwise. It is guaranteed that there is \\textbf{at least one book} on the bookshelf.\n\nIn one move, you can choose some contiguous segment $[l; r]$ consisting of books (i.e. for each $i$ from $l$ to $r$ the condition $a_i = 1$ holds) and:\n\n- Shift it to the right by $1$: move the book at index $i$ to $i + 1$ for all $l \\le i \\le r$. This move can be done only if $r+1 \\le n$ and there is no book at the position $r+1$.\n- Shift it to the left by $1$: move the book at index $i$ to $i-1$ for all $l \\le i \\le r$. This move can be done only if $l-1 \\ge 1$ and there is no book at the position $l-1$.\n\nYour task is to find the \\textbf{minimum} number of moves required to collect all the books on the shelf as a \\textbf{contiguous} (consecutive) segment (i.e. the segment without any gaps).\n\nFor example, for $a = [0, 0, 1, 0, 1]$ there is a gap between books ($a_4 = 0$ when $a_3 = 1$ and $a_5 = 1$), for $a = [1, 1, 0]$ there are no gaps between books and for $a = [0, 0,0]$ there are also no gaps between books.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "We can notice that the answer is the number of zeros between the leftmost occurrence of $1$ and the rightmost occurrence of $1$. Why is it true? Let's take the leftmost maximum by inclusion segment of $1$ and just shift it right. We can see that using this algorithm we will do exactly described amount of moves and there is no way improve the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\twhile (a.back() == 0) a.pop_back();\n\t\treverse(a.begin(), a.end());\n\t\twhile (a.back() == 0) a.pop_back();\n\t\tcout << count(a.begin(), a.end(), 0) << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1433",
    "index": "C",
    "title": "Dominant Piranha",
    "statement": "There are $n$ piranhas with sizes $a_1, a_2, \\ldots, a_n$ in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.\n\nScientists of the Berland State University want to find if there is \\textbf{dominant} piranha in the aquarium. The piranha is called \\textbf{dominant} if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the \\textbf{dominant} piranha will eat them.\n\nBecause the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely:\n\n- The piranha $i$ can eat the piranha $i-1$ if the piranha $i-1$ exists and $a_{i - 1} < a_i$.\n- The piranha $i$ can eat the piranha $i+1$ if the piranha $i+1$ exists and $a_{i + 1} < a_i$.\n\nWhen the piranha $i$ eats some piranha, its \\textbf{size increases by one} ($a_i$ becomes $a_i + 1$).\n\nYour task is to find \\textbf{any dominant} piranha in the aquarium or determine if there are no such piranhas.\n\nNote that you have to find \\textbf{any} (exactly one) dominant piranha, you don't have to find all of them.\n\nFor example, if $a = [5, 3, 4, 4, 5]$, then the third piranha can be \\textbf{dominant}. Consider the sequence of its moves:\n\n- The piranha eats the second piranha and $a$ becomes $[5, \\underline{5}, 4, 5]$ (the underlined piranha is our candidate).\n- The piranha eats the third piranha and $a$ becomes $[5, \\underline{6}, 5]$.\n- The piranha eats the first piranha and $a$ becomes $[\\underline{7}, 5]$.\n- The piranha eats the second piranha and $a$ becomes $[\\underline{8}]$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If all the piranhas have the same size then the answer is -1. Otherwise, there are at least two different sizes of piranhas and the answer always exists. Claim that the answer is such a piranha with the maximum size that one of the adjacent piranhas has the size less than a maximum. Why is it true and why the answer always exists? First, if the piranha with the maximum size eats some other piranha, it becomes the only maximum in the array and can eat all other piranhas. Why is there always such a pair of piranhas? Let's change our array a bit: replace every maximum with $1$ and every non-maximum with $0$. There is always some $01$-pair or $10$-pair in such array because we have at least two different elements.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tint mx = 0;\n\t\tfor (auto &it : a) {\n\t\t\tcin >> it;\n\t\t\tmx = max(mx, it);\n\t\t}\n\t\tint idx = -1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (a[i] != mx) continue;\n\t\t\tif (i > 0 && a[i - 1] != mx) idx = i + 1;\n\t\t\tif (i < n - 1 && a[i + 1] != mx) idx = i + 1;\n\t\t}\n\t\tcout << idx << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1433",
    "index": "D",
    "title": "Districts Connection",
    "statement": "There are $n$ districts in the town, the $i$-th district belongs to the $a_i$-th bandit gang. Initially, no districts are connected to each other.\n\nYou are the mayor of the city and want to build $n-1$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).\n\nIf two districts belonging to the same gang are connected \\textbf{directly} with a road, this gang will revolt.\n\nYou don't want this so your task is to build $n-1$ two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and \\textbf{each pair} of directly connected districts belong to \\textbf{different gangs}, or determine that it is impossible to build $n-1$ roads to satisfy all the conditions.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If all districts belong to the same gang then the answer is NO. Otherwise, the answer is always YES (yeah, as in the previous problem). How to construct it? Let's choose the first \"root\" as the district $1$ and connect all such districts $i$ that $a_1 \\ne a_i$ to the district $1$. So, all disconnected districts that remain are under control of the gang $a_1$. Let's find any district $i$ that $a_i \\ne a_1$ and just connect all remaining districts of the gang $a_1$ to this district. This district always exists because we have at least two different gangs and it is connected to the remaining structure because its gang is not $a_1$. So, all conditions are satisfied.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tvector<pair<int, int>> res;\n\t\tint idx = -1;\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tif (a[i] != a[0]) {\n\t\t\t\tidx = i;\n\t\t\t\tres.push_back({1, i + 1});\n\t\t\t}\n\t\t}\n\t\tif (idx == -1) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tif (a[i] == a[0]) {\n\t\t\t\tres.push_back({idx + 1, i + 1});\n\t\t\t}\n\t\t}\n\t\tcout << \"YES\" << endl;\n\t\tfor (auto [x, y] : res) cout << x << \" \" << y << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1433",
    "index": "E",
    "title": "Two Round Dances",
    "statement": "One day, $n$ people ($n$ is an even number) met on a plaza and made two round dances, each round dance consists of exactly $\\frac{n}{2}$ people. Your task is to find the number of ways $n$ people can make two round dances if each round dance consists of exactly $\\frac{n}{2}$ people. Each person should belong to exactly one of these two round dances.\n\nRound dance is a dance circle consisting of $1$ or more people. Two round dances are indistinguishable (equal) if one can be transformed to another by choosing the first participant. For example, round dances $[1, 3, 4, 2]$, $[4, 2, 1, 3]$ and $[2, 1, 3, 4]$ are indistinguishable.\n\nFor example, if $n=2$ then the number of ways is $1$: one round dance consists of the first person and the second one of the second person.\n\nFor example, if $n=4$ then the number of ways is $3$. Possible options:\n\n- one round dance — $[1,2]$, another — $[3,4]$;\n- one round dance — $[2,4]$, another — $[3,1]$;\n- one round dance — $[4,1]$, another — $[3,2]$.\n\nYour task is to find the number of ways $n$ people can make two round dances if each round dance consists of exactly $\\frac{n}{2}$ people.",
    "tutorial": "Firstly, we need to choose the set of $\\frac{n}{2}$ people to be in the first round dance (the other half is going to the second one). The number of ways to do that is $\\binom{n}{\\frac{n}{2}}$. Then we need to set some order of people in both round dances, but we don't want to forget about rotation (because rotation can lead us to counting the same ways several times). So, the number of ways to arrange people inside one round dance is $(\\frac{n}{2} - 1)!$. This is true because we just \"fixed\" who will be the first in the round dance, and place others in every possible order. So, we need to multiply our initial answer by this value twice because we have two round dances. And, finally, we have to divide our answer by $2$ because we counted \"ordered\" pairs (i.e. we distinguish pairs of kind $(x, y)$ and $(y, x)$ but we don't have to do that). So, the final answer is $\\binom{n}{\\frac{n}{2}} \\cdot (\\frac{n}{2} - 1)! \\cdot (\\frac{n}{2} - 1)!$ divided by $2$. This formula can be reduced to $\\frac{n!}{\\frac{n}{2}^2 \\cdot 2}$. You could also find the sequence of answers in OEIS (and this can be really useful skill sometimes).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 21;\n\nlong long f[N];\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n;\n\tcin >> n;\n\tf[0] = 1;\n\tfor (int i = 1; i < N; ++i) {\n\t\tf[i] = f[i - 1] * i;\n\t}\n\t\n\tlong long ans = f[n] / f[n / 2] / f[n / 2];\n\tans = ans * f[n / 2 - 1];\n\tans = ans * f[n / 2 - 1];\n\tans /= 2;\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}\n",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1433",
    "index": "F",
    "title": "Zero Remainder Sum ",
    "statement": "You are given a matrix $a$ of size $n \\times m$ consisting of integers.\n\nYou can choose \\textbf{no more than} $\\left\\lfloor\\frac{m}{2}\\right\\rfloor$ elements in \\textbf{each row}. Your task is to choose these elements in such a way that their sum is \\textbf{divisible by} $k$ and this sum is the \\textbf{maximum}.\n\nIn other words, you can choose no more than a half (rounded down) of elements in each row, you have to find the maximum sum of these elements divisible by $k$.\n\nNote that you can choose zero elements (and the sum of such set is $0$).",
    "tutorial": "This is pretty standard dynamic programming problem. Let $dp[x][y][cnt][rem]$ be the maximum possible sum we can obtain if we are at the element $a_{x, y}$ right now, we took $cnt$ elements in the row $x$ and our current remainder is $rem$. Initially, all states are $-\\infty$ except $dp[0][0][0][0] = 0$. Transitions are standard because this is a knapsack problem: we either take the element if $cnt < \\left\\lfloor\\frac{m}{2}\\right\\rfloor$ or don't take it. If the element $a_{x, y}$ is not the last element of the row, then transitions look like that: $dp[x][y + 1][cnt][rem] = max(dp[x][y + 1][cnt][rem], dp[x][y][cnt][rem])$ - we don't take the current element. $dp[x][y + 1][cnt + 1][(rem + a_{x, y}) \\% k] = max(dp[x][y + 1][cnt + 1][(rem + a_{x, y}) \\% k], dp[x][y][cnt][rem] + a_{x, y})$ - we take the current element (this transition is only possible if $cnt < \\left\\lfloor\\frac{m}{2}\\right\\rfloor$). The transitions from the last element of the row are almost the same, but the next element is $a_{x + 1, 0}$ and the new value of $cnt$ is always zero. The answer is $max(0, dp[n][0][0][0])$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int N = 75;\nconst int INF = 1e9;\n\nint a[N][N];\nint dp[N][N][N][N];\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tforn(i, n) forn(j, m) {\n\t\tcin >> a[i][j];\n\t}\n\t\n\tforn(i, N) forn(j, N) forn(cnt, N) forn(rem, N) dp[i][j][cnt][rem] = -INF;\n\tdp[0][0][0][0] = 0;\n\tforn(i, n) forn(j, m) forn(cnt, m / 2 + 1) forn(rem, k) {\n\t\tif (dp[i][j][cnt][rem] == -INF) continue;\n\t\tint ni = (j == m - 1 ? i + 1 : i);\n\t\tint nj = (j == m - 1 ? 0 : j + 1);\n\t\tif (i != ni) {\n\t\t\tdp[ni][nj][0][rem] = max(dp[ni][nj][0][rem], dp[i][j][cnt][rem]);\n\t\t} else {\n\t\t\tdp[ni][nj][cnt][rem] = max(dp[ni][nj][cnt][rem], dp[i][j][cnt][rem]);\n\t\t}\n\t\tif (cnt + 1 <= m / 2) {\n\t\t\tint nrem = (rem + a[i][j]) % k;\n\t\t\tif (i != ni) {\n\t\t\t\tdp[ni][nj][0][nrem] = max(dp[ni][nj][0][nrem], dp[i][j][cnt][rem] + a[i][j]);\n\t\t\t} else {\n\t\t\t\tdp[ni][nj][cnt + 1][nrem] = max(dp[ni][nj][cnt + 1][nrem], dp[i][j][cnt][rem] + a[i][j]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcout << max(0, dp[n][0][0][0]) << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1433",
    "index": "G",
    "title": "Reducing Delivery Cost",
    "statement": "You are a mayor of Berlyatov. There are $n$ districts and $m$ two-way roads between them. The $i$-th road connects districts $x_i$ and $y_i$. The cost of travelling along this road is $w_i$. There is some path between each pair of districts, so the city is connected.\n\nThere are $k$ delivery routes in Berlyatov. The $i$-th route is going from the district $a_i$ to the district $b_i$. There is one courier on each route and the courier will always choose the \\textbf{cheapest} (minimum by total cost) path from the district $a_i$ to the district $b_i$ to deliver products.\n\nThe route can go from the district to itself, some couriers routes can coincide (\\textbf{and you have to count them independently}).\n\nYou can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $0$).\n\nLet $d(x, y)$ be the cheapest cost of travel between districts $x$ and $y$.\n\nYour task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $0$. In other words, you have to find the minimum possible value of $\\sum\\limits_{i = 1}^{k} d(a_i, b_i)$ after applying the operation described above optimally.",
    "tutorial": "If we would naively solve the problem, we would just try to replace each edge's cost with zero and run Dijkstra algorithm $n$ times to get the cheapest paths. But this is too slow. Let's try to replace each edge's cost with zero anyway but use some precalculations to improve the speed of the solution. Let's firstly run Dijkstra $n$ times to calculate all cheapest pairwise paths. Then, let's fix which edge we \"remove\" $(x, y)$. There are three cases for the path $(a, b)$: this edge was not on the cheapest path before removing and is not on the cheapest path after removing. Then the cost of this path is $d(a, b)$. The second case is when this edge was not on the cheapest path before removing but it is on the cheapest path after removing. Then the cost of this path is $min(d(a, x) + d(y, b), d(a, y) + d(x, b))$. So we are just going from $a$ to $x$ using the cheapest path, then going through the zero edge and then going from $y$ to $b$ using the cheapest path also (or vice versa, from $a$ to $y$ and from $x$ to $b$). And the third case is when this edge was already on the cheapest path between $a$ and $b$ but this case is essentially the same as the second one. So, if we fix the edge $(x, y)$, then the answer for this edge is $\\sum\\limits_{i=1}^{k} min(d(a_i, b_i), d(a_i, x) + d(y, b_i), d(a_i, y) + d(x, b_i))$. Taking the minimum over all edges, we will get the answer. The precalculating part works in $O(n m \\log n)$ and the second part works in $O(k m)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint n;\nvector<vector<int>> d;\nvector<vector<pair<int, int>>> g;\n\nvoid dijkstra(int s, vector<int> &d) {\n\td = vector<int>(n, INF);\n\td[s] = 0;\n\tset<pair<int, int>> st;\n\tst.insert({d[s], s});\n\twhile (!st.empty()) {\n\t\tint v = st.begin()->second;\n\t\tst.erase(st.begin());\n\t\tfor (auto [to, w] : g[v]) {\n\t\t\tif (d[to] > d[v] + w) {\n\t\t\t\tauto it = st.find({d[to], to});\n\t\t\t\tif (it != st.end()) st.erase(it);\n\t\t\t\td[to] = d[v] + w;\n\t\t\t\tst.insert({d[to], to});\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint m, k;\n\tcin >> n >> m >> k;\n\tg = vector<vector<pair<int, int>>>(n);\n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y, w;\n\t\tcin >> x >> y >> w;\n\t\t--x, --y;\n\t\tg[x].push_back({y, w});\n\t\tg[y].push_back({x, w});\n\t}\n\t\n\tvector<pair<int, int>> r(k);\n\tfor (auto &[a, b] : r) {\n\t\tcin >> a >> b;\n\t\t--a, --b;\n\t}\n\t\n\td = vector<vector<int>>(n);\n\tfor (int v = 0; v < n; ++v) {\n\t\tdijkstra(v, d[v]);\n\t}\n\t\n\tint ans = INF;\n\tfor (int v = 0; v < n; ++v) {\n\t\tfor (auto [to, w] : g[v]) {\n\t\t\tint cur = 0;\n\t\t\tfor (auto [a, b] : r) {\n\t\t\t\tcur += min({d[a][b], d[a][v] + d[to][b], d[a][to] + d[v][b]});\n\t\t\t}\n\t\t\tans = min(ans, cur);\n\t\t}\n\t}\n\t\n\tcout << ans << endl;\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1434",
    "index": "E",
    "title": "A Convex Game",
    "statement": "Shikamaru and Asuma like to play different games, and sometimes they play the following: given an increasing list of numbers, they take turns to move. Each move consists of picking a number from the list.\n\nAssume the picked numbers are $v_{i_1}$, $v_{i_2}$, $\\ldots$, $v_{i_k}$. The following conditions must hold:\n\n- $i_{j} < i_{j+1}$ for all $1 \\leq j \\leq k-1$;\n- $v_{i_{j+1}} - v_{i_j} < v_{i_{j+2}} - v_{i_{j+1}}$ for all $1 \\leq j \\leq k-2$.\n\nHowever, it's easy to play only one instance of game, so today Shikamaru and Asuma decided to play $n$ simultaneous games. They agreed on taking turns as for just one game, \\textbf{Shikamaru goes first}. At each turn, the player performs a valid move in any single game. The player who cannot move loses. Find out who wins, provided that both play optimally.",
    "tutorial": "It's sufficient to calculate the Grundy value for each game instance. Consider a single game. Let $maxc$ be the maximal value in the sequence $v$. We are going to prove that the Grundy value does not exceed $\\sqrt{2 \\cdot maxc} + 1$. Proof: Assume the contrary; that is, that the Grundy value equals $d > \\sqrt{2 \\cdot maxc} + 1$. Then, by definition, there is a sequence $v_{i_0}$, $v_{i_1}$, ..., $v_{i_{d - 1}}$ which is a valid sequence of moves. Indeed, initially there is a move into a position in game with the value $d - 1$, then there is a move from it to the position with value $d - 2$, and so on. It's easy to see that $v_{i_{j + 1}} - v_{i_j} \\geq j + 1$ for all $j\\leq d - 2$. Then $v_{i_{d - 1}} - v_{i_0} \\geq \\frac {d (d - 1)} {2} \\geq \\frac {(d - 1) (d - 1)} {2} \\geq maxc$, which leads to a contradiction. It is clear from the statement that the outcome of the game is defined by the index of the last move and the last difference between the elements. It follows from the Grundy theory that if we fix the last index and gradually decrease the last difference, the grundy value will not decrease. It'd be great to calculate the value of $dp[i][d]$ standing for the maximal possible last difference so that the Grundy value equals $d$, for each index $i$ and each possible Grundy value $d$. This, in its turn, can be done by calculating $maxv[d][i]$ being the maximal $v_j$ so that after the move from $v_i$ to $v_j$ the Grundy value will equal $d$. If we know it, then, standing at some index $j$ and knowing the range of last differences so that the Grundy value equals $d$ for all $d$ (we can obtain it from the values of $dp[i]$), we need to remax the values of $maxv[d]$ on some subsegment. Hence, we can already implement a segment tree solution working for $O(n \\cdot maxc + \\sum m_i \\cdot \\sqrt{2 \\cdot maxc} \\cdot log(m_i))$. However, it's too long. Now recall that the initial array is increasing in each game. This means that during the calculation of $dp$ and $maxv$ from left to right, we only need to remax something a single time (the first time). This operation can be done via DSU, if we compress subsegments of all already calculated values and one not yet calculated into a single component. Then the final time complexity will be $O(n \\cdot maxc + \\sum m_i \\cdot \\sqrt{2 \\cdot maxc} \\cdot \\alpha(m_i))$.",
    "tags": [
      "dsu",
      "games"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1436",
    "index": "A",
    "title": "Reorder",
    "statement": "For a given array $a$ consisting of $n$ integers and a given integer $m$ find if it is possible to reorder elements of the array $a$ in such a way that $\\sum_{i=1}^{n}{\\sum_{j=i}^{n}{\\frac{a_j}{j}}}$ equals $m$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $\\frac{5}{2}=2.5$.",
    "tutorial": "You can notice that the $i$-th number in the array will be included in the sum $i$ times, which means that the value $\\frac {a_i} {i}$ will add $a_i$ to the sum. That is, the permutation of the elements does not affect the required sum, and therefore it is enough to check whether the sum of the array elements is equal to the given number.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())\n#define sz(v) ((int)(v).size())\n \n#define vec1d(x) vector<x>\n#define vec2d(x) vector<vec1d(x)>\n#define vec3d(x) vector<vec2d(x)>\n#define vec4d(x) vector<vec3d(x)>\n \n#define ivec1d(x, n, v) vec1d(x)(n, v)\n#define ivec2d(x, n, m, v) vec2d(x)(n, ivec1d(x, m, v))\n#define ivec3d(x, n, m, k, v) vec3d(x)(n, ivec2d(x, m, k, v))\n#define ivec4d(x, n, m, k, l, v) vec4d(x)(n, ivec3d(x, m, k, l, v))\n \n#ifdef LOCAL\n#include \"pretty_print.h\"\n#define dbg(...) cerr << \"[\" << #__VA_ARGS__ << \"]: \", debug_out(__VA_ARGS__)\n#else\n#define dbg(...) 42\n#endif\n \n#define nl \"\\n\"\n \ntypedef long double ld;\ntypedef long long ll;\ntypedef unsigned long long ull;\n \ntemplate <typename T> T sqr(T x) { return x * x; }\ntemplate <typename T> T abs(T x) { return x < 0? -x : x; }\ntemplate <typename T> T gcd(T a, T b) { return b? gcd(b, a % b) : a; }\ntemplate <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }\ntemplate <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }\n \nauto random_address = [] { char *p = new char; delete p; return (uint64_t) p; };\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\nmt19937_64 rngll(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\n \n \nint main(int /* argc */, char** /* argv */)\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n#ifdef LOCAL\n    assert(freopen(\"i.txt\", \"r\", stdin));\n    assert(freopen(\"o.txt\", \"w\", stdout));\n#endif\n \n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        int s = 0;\n        for (int i = 0; i < n; ++i) {\n            int x;\n            cin >> x;\n            s += x;\n        }\n        cout << (s == m? \"YES\" : \"NO\") << nl;\n    }\n \n#ifdef LOCAL\n    cerr << \"Time execute: \" << clock() / (double)CLOCKS_PER_SEC << \" sec\" << endl;\n#endif\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1436",
    "index": "B",
    "title": "Prime Square",
    "statement": "Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square.\n\nA square of size $n \\times n$ is called prime if the following three conditions are held simultaneously:\n\n- all numbers on the square are non-negative integers not exceeding $10^5$;\n- there are no prime numbers in the square;\n- sums of integers in each row and each column are prime numbers.\n\nSasha has an integer $n$. He asks you to find any prime square of size $n \\times n$. Sasha is absolutely sure such squares exist, so just help him!",
    "tutorial": "First, note that the numbers 0 and 1 are not prime. Now let's try to build a square from only these numbers. To begin with, fill in the main and secondary diagonal of the square with ones. If $n$ is even, then the sum in each row and each column is $2$ (prime number), and we have met the condition. If $n$ is odd, then the sum in the row with the number $\\frac {n + 1} {2}$ and in the column with the number $\\frac {n + 1} {2}$ will be equal to one. To fix this, add ones to the cells $(\\frac {n} {2}, \\frac {n + 1} {2})$ and $(\\frac {n + 1} {2}, \\frac {n + 1} {2} + 1)$. As a result, the sum in columns and rows will be equal to two or three, and we have fulfilled the condition of the problem.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector <vector <int> > a(n);\n    for (int i = 0; i < n; ++i) {\n        a[i].resize(n, 0);\n    }\n \n    if (n == 4) {\n        vector <vector <int> > matrix = {{4, 6, 8, 1}, {4, 9, 9, 9}, {4, 10, 10, 65}, {1, 4, 4, 4}};\n        cout << \"4 6 8 1\\n4 9 9 9\\n4 10 10 65\\n1 4 4 4\\n\";\n        return;\n    }\n \n    for (int i = 0; i < n; ++i) {\n        a[i][i] = 1;\n        a[i][n - i - 1] = 1;\n    }\n \n    if (n % 2) {\n        a[n / 2 - 1][n / 2] = 1;\n        a[n / 2][n / 2 + 1] = 1;\n    }\n \n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cout << a[i][j];\n            if (j < n - 1) cout << \" \";\n            else cout << \"\\n\";\n        }\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int t;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n \n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1436",
    "index": "C",
    "title": "Binary Search",
    "statement": "Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number $x$ in an array. For an array $a$ indexed from zero, and an integer $x$ the pseudocode of the algorithm is as follows:\n\nNote that the elements of the array are indexed from zero, and the division is done in integers (rounding down).\n\nAndrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find $x$!\n\nAndrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size $n$ such that the algorithm finds $x$ in them. A permutation of size $n$ is an array consisting of $n$ distinct integers between $1$ and $n$ in arbitrary order.\n\nHelp Andrey and find the number of permutations of size $n$ which contain $x$ at position $pos$ and for which the given implementation of the binary search algorithm finds $x$ (returns true). As the result may be extremely large, print the remainder of its division by $10^9+7$.",
    "tutorial": "Let's simulate a binary search algorithm. Initially, we have the required position $pos$. For the next $middle$ position in the binary search, we can determine exactly whether the next number at this position should be greater or less than $x$. For all other positions, the values can be eiteher greater or less than $x$. As a result of the simulation of the algorithm, we have $cntBig$ positions at which numbers must be greater than $x$ and $cntLess$ positions at which numbers must be less than $x$. Let the large numbers be $hasBig$, and the smaller ones $hasLess$. Now let's count the number of ways to place large numbers in $cntBig$ positions using the formula $C(hasBig, cntBig) \\cdot cntBig!$. Let's calculate in a similar way for smaller numbers, and the product of the resulting results will be the answer to the problem.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 1e9 + 7;\n \nint binPow(int a, int n) {\n    int res = 1;\n    while (n) {\n        if (n & 1)\n            res = (1LL * res * a) % MOD;\n        a = (1LL * a * a) % MOD;\n \n        n >>= 1;\n    }\n    return res;\n}\n \nvoid binarySearch(int n, int x_position, int &cnt_big, int &cnt_less) {\n    int left = 0, right = n;\n \n    while(left < right) {\n        int middle = (left + right) / 2;\n        if (x_position >= middle) {\n            if (x_position != middle) cnt_less++;\n            left = middle + 1;\n        }\n        else if (x_position < middle){\n            cnt_big++;\n            right = middle;\n        }\n    }\n}\n \nint C(int n, int k, const vector <long long> &fact, const vector <long long> &inv) {\n    if (k > n) return 0;\n    int multiply = (1LL * fact[n] * inv[k]) % MOD;\n    multiply = (1LL * multiply * inv[n - k]) % MOD;\n    return multiply;\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int n, x, x_position;\n    long long ans = 0;\n \n \n    cin >> n >> x >> x_position;\n    vector <long long> fact(n + 1, 1LL);\n    vector <long long> inv(n + 1, 1LL);\n    for (int i = 1; i <= n; ++i) {\n        fact[i] = (fact[i - 1] * i) % MOD;\n        inv[i] = binPow(fact[i], MOD - 2);\n    }\n \n    int cnt_big = 0, cnt_less = 0;\n    binarySearch(n, x_position, cnt_big, cnt_less);\n \n    int other = (n - cnt_big - cnt_less - 1);\n    int can_big = n - x, can_less = x - 1;\n \n    int countLess = C(can_less, cnt_less, fact, inv);\n    int countBig = C(can_big, cnt_big, fact, inv);\n \n    countBig = (1LL * countBig * fact[cnt_big]) % MOD;\n    countLess = (1LL * countLess * fact[cnt_less]) % MOD;\n \n    int multiply = (1LL * countBig * countLess) % MOD;\n    multiply = (1LL * multiply * fact[other]) % MOD;\n \n    ans = (ans + multiply) % MOD;\n \n    cout << ans << endl;\n \n    return 0;\n}",
    "tags": [
      "binary search",
      "combinatorics"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1436",
    "index": "D",
    "title": "Bandit in a City",
    "statement": "Bandits appeared in the city! One of them is trying to catch as many citizens as he can.\n\nThe city consists of $n$ squares connected by $n-1$ roads in such a way that it is possible to reach any square from any other square. The square number $1$ is the main square.\n\nAfter Sunday walk all the roads were changed to \\textbf{one-way} roads in such a way that it is possible to reach any square from the main square.\n\nAt the moment when the bandit appeared on the main square there were $a_i$ citizens on the $i$-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.\n\nThe bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?",
    "tutorial": "First, let's assume that all the citizens are at the root of the tree. Then the answer to the problem will be $\\lceil \\frac{a_1}{leaves} \\rceil$, where $leaves$ is the number of leaves in the tree. According to the Dirichlet principle, this would be the minimum possible number of caught citizens. The answer to the original problem is $max_i {\\lceil \\frac{sum_{a_v}}{leafs_i} \\rceil}$, where $v$ lies in the subtree of $i$, $leaves_i$ is the number of leaves in the subtree $i$. Consider some vertex $i$, for which it is impossible to split the citizens equally. Then there will be a vertex $m$ in which in the optimal splitup will have the maximum number of citizens. Obviously, it is not profitable for us to send any citizen from vertex $i$ to $m$. In this case, we can go one level down in the tree in the direction of $m$. We will repeat this step until we can divide the citizens equally. Hence it is clear why the above formula is correct.",
    "code": "#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC optimize(\"Ofast\")\n \n// hloya template v26\n \n// ░░░░░░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░░░░░\n// ░░░░░░█░░▄▀▀▀▀▀▀▀▀▀▀▀▀▀▄░░█░░░░░\n// ░░░░░░█░█░▀░░░░░▀░░▀░░░░█░█░░░░░\n// ░░░░░░█░█░░░░░░░░▄▀▀▄░▀░█░█▄▀▀▄░\n// █▀▀█▄░█░█░░▀░░░░░█░░░▀▄▄█▄▀░░░█░\n// ▀▄▄░▀██░█▄░▀░░░▄▄▀░░░░░░░░░░░░▀▄\n// ░░▀█▄▄█░█░░░░▄░░█░░░▄█░░░▄░▄█░░█\n// ░░░░░▀█░▀▄▀░░░░░█░██░▄░░▄░░▄░███\n// ░░░░░▄█▄░░▀▀▀▀▀▀▀▀▄░░▀▀▀▀▀▀▀░▄▀░\n// ░░░░█░░▄█▀█▀▀█▀▀▀▀▀▀█▀▀█▀█▀▀█░░░\n// ░░░░▀▀▀▀░░▀▀▀░░░░░░░░▀▀▀░░▀▀░░░░\n \n#include <bits/stdc++.h>\nusing namespace std;\n \nbool dbg = 0;\n  \nclock_t start_time = clock();\n#define current_time fixed<<setprecision(6)<<(ld)(clock()-start_time)/CLOCKS_PER_SEC\n  \n#define f first\n#define s second\n#define mp make_pair\n#define mt make_tuple\n#define pb push_back\n#define eb emplace_back\n#define all(v) (v).begin(), (v).end()\n#define sz(v) ((int)(v).size())\n#define sqr(x) ((x) * (x))\n \n#define ull unsigned long long\n#define ll long long\n#define ld long double\n#define pii pair<int,int>\n#define umap unordered_map<int, int>\n \n#define files1 freopen(\"input.txt\",\"r\",stdin)\n#define files2 freopen(\"output.txt\",\"w\",stdout)\n#define files files1;files2\n#define fast_io ios_base::sync_with_stdio(0);cin.tie(0)\n \n// #define endl '\\n'\n#define ln(i,n) \" \\n\"[(i) == (n) - 1]\n \nvoid bad(string mes = \"NO\"){cout << mes;exit(0);}\nvoid bad(int mes){cout << mes;exit(0);}\n \ntemplate<typename T>\nstring bin(T x, int st = 2){\n    string ans = \"\";\n    while (x > 0){\n        ans += char('0' + x % st);\n        x /= st;\n    }\n    reverse(ans.begin(), ans.end());\n    return ans.empty() ? \"0\" : ans;\n}\n \nmt19937_64 mt_rand(\n    228// chrono::system_clock::now().time_since_epoch().count()\n);\n \ntemplate<typename T1, typename T2> inline bool upmax(T1& a, T2 b) { return (a < b ? (a = b, true) : false); }\ntemplate<typename T1, typename T2> inline bool upmin(T1& a, T2 b) { return (b < a ? (a = b, true) : false); }\n \n// inline int popcount(int x){\n//     int count = 0;\n//     __asm__ volatile(\"POPCNT %1, %0;\":\"=r\"(count):\"r\"(x):);\n//     return count;\n// }\n  \ntemplate<typename T>\nT input(){\n    T ans = 0, m = 1;\n    char c = ' ';\n  \n    while (!((c >= '0' && c <= '9') || c == '-')) {\n        c = getchar();\n    }\n  \n    if (c == '-')\n        m = -1, c = getchar();\n    while (c >= '0' && c <= '9'){\n        ans = ans * 10 + (c - '0'), c = getchar();\n    }\n    return ans * m;\n}\n \ntemplate<typename T>\nT gcd (T a, T b) { while (b) { a %= b; swap (a, b); } return a; }\n  \ntemplate<typename T> void read(T& a) { a = input<T>(); }\ntemplate<typename T> void read(T& a, T& b) { read(a), read(b); }\ntemplate<typename T> void read(T& a, T& b, T& c) { read(a, b), read(c); }\ntemplate<typename T> void read(T& a, T& b, T& c, T& d) { read(a, b), read(c, d); }\n \nconst int inf = 1e9 + 20;\nconst short short_inf = 3e4 + 20;\nconst long double eps = 1e-12;\nconst int maxn = (int)2e5 + 3, base = 1e9 + 7;\nconst ll llinf = 2e18 + 5;\nconst int mod = 998244353;\n \nint binpow (int a, int n) {\n    int res = 1;\n    while (n) {\n        if (n & 1)\n            res = 1ll * res * a % base;\n        a = 1ll * a * a % base;\n        n >>= 1;\n    }\n    return res;\n}\n \nint a[maxn];\nint p[maxn];\n \nvector<int> g[maxn];\n \nmap<ll, int> *cnt[maxn];\n \nvoid add(int v, ll val) {\n  ll prev = 0;\n  int cc  = 0;\n \n  while (cnt[v]->size()) {\n    auto [h, c1] = *cnt[v]->begin();\n    ll allup = 1ll * cc * (h - prev);\n    if (val >= allup) {\n      val -= allup;\n      prev = h;\n      cc += c1;\n      cnt[v]->erase(cnt[v]->begin());\n    } else {\n      break;\n    }\n  }\n \n  if (cc == 0) {\n      (*cnt[v])[val]++;\n  } else {\n    ll x = prev + (val / cc);\n    if (val % cc > 0) {\n      (*cnt[v])[x + 1] += val % cc;\n    }\n    (*cnt[v])[x] += cc - val % cc;\n  }\n}\n \nint sz[maxn];\n \nvoid dfs(int v){\n    int mx = -1, bigChild = -1;\n    sz[v] = 1;\n    for(auto u : g[v]) {\n       dfs(u);\n       sz[v] += sz[u];\n       if(sz[u] > mx) {\n           mx = sz[u], bigChild = u;\n       }\n    }\n    if(bigChild != -1)\n        cnt[v] = cnt[bigChild];\n    else\n        cnt[v] = new map<ll, int> ();\n    for(auto u : g[v])\n       if(u != bigChild){\n           for(auto x : *cnt[u])\n               (*cnt[v])[x.first] += x.second;\n       }\n   add(v, a[v]);\n}\n \n \nint main() {\n//   files1;\n  fast_io;\n \n  int n;\n  cin >> n;\n \n  for (int i = 1; i < n; i++) {\n    int par;\n    cin >> par;\n    par--;\n \n    g[par].push_back(i);\n  }\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n  }\n \n  dfs(0);\n \n  ll ans = 0;\n  for (auto [k, v] : *cnt[0]) {\n    // if (v > 0) {\n      ans = max(ans, k);\n    // }\n  }\n  cout << ans << \"\\n\";\n  return 0;\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1436",
    "index": "E",
    "title": "Complicated Computations",
    "statement": "In this problem MEX of a certain array is the smallest \\textbf{positive} integer not contained in this array.\n\nEveryone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today.\n\nYou are given an array $a$ of length $n$. Lesha considers all the \\textbf{non-empty} subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers.\n\nAn array $b$ is a subarray of an array $a$, if $b$ can be obtained from $a$ by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself.\n\nLesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays!",
    "tutorial": "Let's iterate over the answer. Let the current answer be $x$, then we can get it only when there are no subarrays, whose MEX is $x$. Note that we need to check the MEX of the subarrays that are between all occurrences of $x$. This can be done, for example, using a segment tree, processing its occurrences in order. A number for which MEX is not found will be the answer.",
    "code": "#include <bits/stdc++.h>\n \n#define fi first\n#define se second\n#define p_b push_back\n#define pll pair<ll,ll>\n#define pii pair<int,int>\n#define m_p make_pair\n#define all(x) x.begin(),x.end()\n#define sset ordered_set\n#define sqr(x) (x)*(x)\n#define pw(x) (1ll << x)\n#define sz(x) (int)x.size()\n#define fout(x) {cout << x << \"\\n\"; return; }\n \nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\nconst ll N = 1e5 + 5;\nconst ll M = 1e5 + 2;\nconst int inf = 1e8;\nconst ll mod = 1e9 + 7;\n \ntemplate <typename T> void vout(T s){cout << s << endl;exit(0);}\n \nint t[4 * N];\n \nvoid modify(int v, int tl, int tr, int pos, int val){\n    if(tl == tr)t[v] = val;\n    else{\n        int tm = (tl + tr) >> 1;\n        if(pos <= tm)modify(v << 1, tl, tm, pos, val);\n        else modify(v << 1 | 1, tm + 1, tr, pos, val);\n        t[v] = min(t[v << 1 | 1], t[v << 1]);\n    }\n}\n \nint find(int v, int tl, int tr, int k){\n    if(tl == tr)return tl;\n    int tm = (tl + tr) >> 1;\n    if(t[v << 1] < k){\n        return find(v << 1, tl, tm, k);\n    }\n    return find(v << 1 | 1, tm + 1, tr, k);\n}\n \nint last[2 * N];\n \nint main(){\n    ios_base :: sync_with_stdio(0);\n    cin.tie(0);\n \n    map <int, bool> mp;\n \n    int n;\n    cin >> n;\n \n    vector <int> a(n + 1);\n \n    for(int i = 1; i <= n; i++)cin >> a[i];\n \n    for(int i = 1; i <= n; i++){\n        int x = a[i];\n        if(last[x] + 1 < i){\n            mp[find(1, 1, M, last[x] + 1)] = 1;\n        }\n        modify(1, 1, M, a[i], i);\n        last[x] = i;\n    }\n \n    for(int i = 1; i <= M; i++)if(last[i] && last[i] != n){\n            mp[find(1, 1, M, last[i] + 1)] = 1;\n        }\n \n    mp[find(1, 1, M, 1)] = 1;\n \n    for(int i = 1; ; i++)if(!mp[i])vout(i);\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1436",
    "index": "F",
    "title": "Sum Over Subsets",
    "statement": "You are given a multiset $S$. Over all pairs of subsets $A$ and $B$, such that:\n\n- $B \\subset A$;\n- $|B| = |A| - 1$;\n- greatest common divisor of all elements in $A$ is equal to one;\n\nfind the sum of $\\sum_{x \\in A}{x} \\cdot \\sum_{x \\in B}{x}$, modulo $998\\,244\\,353$.",
    "tutorial": "Let's calculate the required product of the sums $ans_i$ for the sets, the greatest common divisor of the elements of which is $i$. First, let's select all the elements that are divisible by $i$. To find only those sets whose GCD is exactly $i$, one can find the product of the sums for all subsets and subtract the answers of all $ans_j$ such that $i<j$ and $i$ divides $j$ without a remainder. To find the products of all subsets of a set of $k$ elements, consider two cases: the product $a_i \\cdot a_i$ will be counted $2^{k-2} \\cdot (k - 1)$ times. Each element in the set $A$ can be removed and this will add the product $a_i^2$. The number of elements $k - 1$ and the number, select the rest of the subset $2 ^ {k-2}$; the product $a_i \\cdot a_j$ will be counted $2 ^ {k-3} \\cdot (k - 2) + 2 ^ {k-2}$. The first term is similar to the example above. And the second is obtained if $a_i$ is removed from the set $A$ - the number of ways to choose a subset of $k - 2$ elements is $2 ^ {k-2}$.",
    "code": "#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())\n#define sz(v) ((int)(v).size())\n \n#define vec1d(x) vector<x>\n#define vec2d(x) vector<vec1d(x)>\n#define vec3d(x) vector<vec2d(x)>\n#define vec4d(x) vector<vec3d(x)>\n \n#define ivec1d(x, n, v) vec1d(x)(n, v)\n#define ivec2d(x, n, m, v) vec2d(x)(n, ivec1d(x, m, v))\n#define ivec3d(x, n, m, k, v) vec3d(x)(n, ivec2d(x, m, k, v))\n#define ivec4d(x, n, m, k, l, v) vec4d(x)(n, ivec3d(x, m, k, l, v))\n \n#ifdef LOCAL\n#include \"pretty_print.h\"\n#define dbg(...) cerr << \"[\" << #__VA_ARGS__ << \"]: \", debug_out(__VA_ARGS__)\n#else\n#define dbg(...) 42\n#endif\n \n#define nl \"\\n\"\n \ntypedef long double ld;\ntypedef long long ll;\ntypedef unsigned long long ull;\n \ntemplate <typename T> T sqr(T x) { return x * x; }\ntemplate <typename T> T abs(T x) { return x < 0? -x : x; }\ntemplate <typename T> T gcd(T a, T b) { return b? gcd(b, a % b) : a; }\ntemplate <typename T> bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }\ntemplate <typename T> bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }\n \nauto random_address = [] { char *p = new char; delete p; return (uint64_t) p; };\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\nmt19937_64 rngll(chrono::steady_clock::now().time_since_epoch().count() * (random_address() | 1));\n \n \nconst int MOD = 998244353;\n \nvoid addmod(ll &x, ll d) {\n    x += d;\n    if (x >= MOD) {\n        x -= MOD;\n    }\n    if (x < 0) {\n        x += MOD;\n    }\n}\n \nll powmod(ll a, ll b) {\n    ll ret = 1;\n    ll p = a;\n    while (b) {\n        if (b & 1) {\n            ret = ret * p % MOD;\n        }\n        p = p * p % MOD;\n        b >>= 1;\n    }\n    return ret;\n}\n \nll divmod(ll a, ll b) {\n    return a * powmod(b, MOD - 2) % MOD;\n}\n \nint main(int /* argc */, char** /* argv */)\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n#ifdef LOCAL\n    assert(freopen(\"i.txt\", \"r\", stdin));\n    assert(freopen(\"o.txt\", \"w\", stdout));\n#endif\n \n    int m;\n    cin >> m;\n \n    const int n = 1e+5;\n \n    vector<ll> sum(n + 1, 0);\n    vector<ll> sum1(n + 1, 0);\n    vector<ll> sum2(n + 1, 0);\n    vector<ll> cnt(n + 1, 0);\n \n \n    for (int i = 0; i < m; ++i) {\n        ll x, f;\n        cin >> x >> f;\n        ll s = x * f % MOD;\n        ll s1 = x * x % MOD * f % MOD;\n        ll s2 = x * x % MOD * ((f - 1) * f % MOD) % MOD;\n \n        auto add = [&](int i) {\n            addmod(sum2[i], (s2 + 2 * s * sum[i]) % MOD);\n            addmod(sum1[i], s1);\n            addmod(sum[i], s);\n            cnt[i] += f;\n        };\n \n        for (int j = 1; j * j <= x; ++j) {\n            if (x % j) {\n                continue;\n            }\n            add(j);\n            if (x / j != j) {\n                add(x / j);\n            }\n        }\n    }\n \n    vector<ll> f(n + 1, 0);\n    for (int i = n; i >= 1; --i) {\n        if (!cnt[i]) {\n            continue;\n        }\n        ll& ret = f[i];\n        ll k = cnt[i];\n        ll p3, p2;\n        p3 = p2 = 0;\n        if (k > 2) {\n            p3 = powmod(2, k - 3);\n            p2 = p3 * 2 % MOD;\n        } else if (k > 1) {\n            p2 = powmod(2, k - 2);\n        }\n \n        if (k > 1) {\n            addmod(ret, p2 * ((k - 1) % MOD) % MOD * sum1[i] % MOD);\n            addmod(ret, p2 % MOD * sum2[i] % MOD);\n        }\n        if (k > 2) {\n            addmod(ret, p3 * ((k - 2) % MOD) % MOD * sum2[i] % MOD);\n        }\n \n        for (int j = i + i; j <= n; j += i) {\n            addmod(ret, -f[j]);\n        }\n    }\n \n    cout << f[1] << nl;\n \n#ifdef LOCAL\n    cerr << \"Time execute: \" << clock() / (double)CLOCKS_PER_SEC << \" sec\" << endl;\n#endif\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1437",
    "index": "A",
    "title": "Marketing Scheme",
    "statement": "You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.\n\nSuppose you decided to sell packs with $a$ cans in a pack with a discount and some customer wants to buy $x$ cans of cat food. Then he follows a greedy strategy:\n\n- he buys $\\left\\lfloor \\frac{x}{a} \\right\\rfloor$ packs with a discount;\n- then he wants to buy the remaining $(x \\bmod a)$ cans one by one.\n\n{$\\left\\lfloor \\frac{x}{a} \\right\\rfloor$ is $x$ divided by $a$ rounded down, $x \\bmod a$ is the remainer of $x$ divided by $a$.}\n\nBut customers are greedy in general, so if the customer wants to buy $(x \\bmod a)$ cans one by one and it happens that $(x \\bmod a) \\ge \\frac{a}{2}$ he decides to buy the whole pack of $a$ cans (instead of buying $(x \\bmod a)$ cans). It makes you, as a marketer, happy since the customer bought more than he wanted initially.\n\nYou know that each of the customers that come to your shop can buy any number of cans from $l$ to $r$ inclusive. Can you choose such size of pack $a$ that each customer buys more cans than they wanted initially?",
    "tutorial": "Note that if $\\left\\lfloor \\frac{l}{a} \\right\\rfloor < \\left\\lfloor \\frac{r}{a} \\right\\rfloor$ then exists such $k \\cdot a$ that $l \\le ka \\le r$ and, obviously, a customer, who wants to buy $ka$ cans won't buy more than he wants. That's why $\\left\\lfloor \\frac{l}{a} \\right\\rfloor = \\left\\lfloor \\frac{r}{a} \\right\\rfloor$ and we can rephrase our task as finding such $a$ that $\\frac{a}{2} \\le (l \\bmod a) \\le (r \\bmod a) < a$. The longer the segment $[\\frac{a}{2}, a)$ is the better and the maximum we can take is $a = 2l$. As a result, we need to check that $r < a \\leftrightarrow r < 2l$.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (l, r) = readLine()!!.split(' ').map { it.toInt() }\n        println(if (2 * l > r) \"YES\" else \"NO\");\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1437",
    "index": "B",
    "title": "Reverse Binary Strings",
    "statement": "You are given a string $s$ of even length $n$. String $s$ is binary, in other words, consists only of 0's and 1's.\n\nString $s$ has exactly $\\frac{n}{2}$ zeroes and $\\frac{n}{2}$ ones ($n$ is even).\n\nIn one operation you can reverse any substring of $s$. A substring of a string is a contiguous subsequence of that string.\n\nWhat is the minimum number of operations you need to make string $s$ alternating? A string is alternating if $s_i \\neq s_{i + 1}$ for all $i$. There are two types of alternating strings in general: 01010101... or 10101010...",
    "tutorial": "We need to make our string alternating, i. e. $s_i \\neq s_{i + 1}$. When we reverse substring $s_l \\dots s_r$, we change no more than two pairs $s_{l - 1}, s_l$ and $s_r, s_{r + 1}$. Moreover, one pair should be a consecutive pair 00 and other - 11. So, we can find lower bound to our answer as maximum between number of pairs of 00 and number of pairs of 11. And we can always reach this lower bound, by pairing 00 with 11 or with left/right border of $s$. Another way to count the answer is next: suppose we want to make string 0101..., then let's transform $s$ to 1 + $s$ + 0. For example, if $s =$ 0110, we will get 101100. We claim that after this transformation, we will have equal number of 00 and 11, so the answer is the number of consecutive pairs of the same character divided by two. The answer is the minimum between answers for 1 + $s$ + 0 and 0 + $s$ + 1.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nconst int INF = int(1e9);\n\nint n;\nstring s;\n\ninline bool read() {\n\tif(!(cin >> n >> s))\n\t\treturn false;\n\treturn true;\n}\n\nint cntSame(const string &s) {\n\tint ans = 0;\n\tfore (i, 1, sz(s))\n\t\tans += (s[i - 1] == s[i]);\n\tassert(ans % 2 == 0);\n\treturn ans / 2;\n}\n\ninline void solve() {\n\tint ans = INF;\n\tfore (k, 0, 2) {\n\t\tans = min(ans, cntSame(string(1, '0' + k) + s + string(1, '1' - k)));\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\twhile(tc--) {\n\t\tassert(read());\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1437",
    "index": "C",
    "title": "Chef Monocarp",
    "statement": "Chef Monocarp has just put $n$ dishes into an oven. He knows that the $i$-th dish has its optimal cooking time equal to $t_i$ minutes.\n\nAt any \\textbf{positive integer} minute $T$ Monocarp can put \\textbf{no more than one} dish out of the oven. If the $i$-th dish is put out at some minute $T$, then its unpleasant value is $|T - t_i|$ — the absolute difference between $T$ and $t_i$. Once the dish is out of the oven, it can't go back in.\n\nMonocarp should put all the dishes out of the oven. What is the minimum total unpleasant value Monocarp can obtain?",
    "tutorial": "There are a lot of solutions for the problem. Let's start with the easiest one. Sort the dishes in the non-decreasing order of their optimal time. I claim that there is an optimal answer such that the times $T$ for each dish go in the increasing order. That's not too hard to prove (something along the lines of if there are two dishes $i$ and $j$ such that $t_i < t_j$ and $T_i > T_j$, then $|t_i - T_i| + |t_j - T_j|$ is always greater than $|t_i - T_j| + |t_j - T_i|$). So we can use dynamic programming to solve the task. Let $dp[i][T]$ be the minimum total unpleasant value if $i$ dishes are processed and the current minute is $T$. For the transitions you can either put out the current dish $i$ at the current minute $T$ or wait one more minute. Notice that you'll never need more time than $2n$ minutes (the actual constraint is even smaller, just consider the case with all dishes times equal to $n$). So that dp works in $O(n^2)$. The other possible solution is matching. Let's build the following graph. The left partition is $n$ vertices corresponding to dishes. The right partition is $2n$ vertices corresponding to minutes (as we saw in previous solution $2n$ is always enough). Now add the edges between all dishes and all minutes with the cost of their absolute different. Finally, find the minimum cost maximum matching. That can be done with MCMF or Hungarian algorithm. Both should pass pretty easily. There's also a solution in $O(n \\log n)$ involving the slope trick.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\ntemplate<typename T>\nT hungarian(const vector<vector<T>>& cost) {\n    const T INF = numeric_limits<T>::max();\n    int n = cost.size(), m = cost[0].size();\n    vector<T> u(n + 1), v(m + 1), dist(m + 1);\n    vector<int> p(m + 1), way(m + 1), used(m + 1);\n    for (int i = 1; i <= n; ++i) {\n        p[0] = i;\n        int j0 = 0;\n        fill(dist.begin(), dist.end(), INF);\n        do {\n            used[j0] = i;\n            int i0 = p[j0], j1 = -1;\n            T delta = INF;\n            for (int j = 1; j <= m; ++j) if (used[j] != i) {\n                T cur = cost[i0 - 1][j - 1] - u[i0] - v[j];\n                if (cur < dist[j]) dist[j] = cur, way[j] = j0;\n                if (dist[j] < delta) delta = dist[j], j1 = j;\n            }\n            forn(j, m + 1) {\n                if (used[j] == i) u[p[j]] += delta, v[j] -= delta;\n                else dist[j] -= delta;\n            }\n            j0 = j1;\n        } while (p[j0] != 0);\n        for (int j1; j0; j0 = j1)\n            p[j0] = p[j1 = way[j0]];\n    }\n    \n    return -v[0];\n}\n\nvoid solve(){\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> t(n);\n\tforn(i, n){\n\t\tscanf(\"%d\", &t[i]);\n\t\t--t[i];\n\t}\n\tvector<vector<int>> cost(n, vector<int>(2 * n));\n\tforn(i, n) forn(j, 2 * n) cost[i][j] = abs(t[i] - j);\n\tprintf(\"%d\\n\", hungarian(cost));\n}\n\nint main() {\n\tint q;\n\tscanf(\"%d\", &q);\n\tforn(_, q) solve();\n}",
    "tags": [
      "dp",
      "flows",
      "graph matchings",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1437",
    "index": "D",
    "title": "Minimal Height Tree",
    "statement": "Monocarp had a tree which consisted of $n$ vertices and was rooted at vertex $1$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:\n\n\\begin{verbatim}\na = [] # the order in which vertices were processed\nq = Queue()\nq.put(1) # place the root at the end of the queue\nwhile not q.empty():\nk = q.pop() # retrieve the first vertex from the queue\na.append(k) # append k to the end of the sequence in which vertices were visited\nfor y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order\nq.put(y)\n\n\\end{verbatim}\n\nMonocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.\n\nMonocarp knows that there are many trees (in the general case) with the same visiting order $a$, so he doesn't hope to restore his tree. Monocarp is okay with any tree that \\textbf{has minimum height}.\n\nThe height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex $1$ is $0$, since it's the root, and the depth of all root's children are $1$.\n\nHelp Monocarp to find any tree with given visiting order $a$ and minimum height.",
    "tutorial": "Due to the nature of BFS, the visiting order consists of several segments: first goes root (has depth $0$), then all vertices with depth $1$, then all vertices with depth $2$ and so on. Since any vertex of depth $d$ is a child of vertex of depth $d - 1$, then it's optimal to make the number of vertices with depth $1$ as many as possible, then make the number of vertices with depth $2$ as many as possible and so on. Since children of a vertex are viewed in ascending order and form a segment in visiting order then an arbitrary segment of visiting order can be children of the same vertex iff elements in the segments are in ascending order. These two observations lead us to a greedy strategy: $a_1 = 1$, then let's find the maximum $r_1$ that segment $a_2, \\dots, a_{r_1}$ is in ascending order - they will be the children of $a_1$ and the only vertices of depth $1$. Next search the maximum $r_2$ such that segment $a_{r_1 + 1}, \\dots, a_{r_2}$ is in ascending order - they will be the children of $a_2$, and so on. It's easy to see that this strategy maximizes the number of vertices of each depth level, so minimize the height of the tree.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nint n;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> a[i];\n\treturn true;\n}\n\ninline void solve() {\n\tvector<int> h(n, INF);\n\th[0] = 0;\n\tint lst = 0;\n\tfore (i, 1, n) {\n\t\tif (i - 1 > 0 && a[i - 1] > a[i])\n\t\t\tlst++;\n\t\th[i] = h[lst] + 1;\n\t}\n\tcout << h[n - 1] << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\twhile(tc--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1437",
    "index": "E",
    "title": "Make It Increasing",
    "statement": "You are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$, and a set $b$ of $k$ distinct integers from $1$ to $n$.\n\nIn one operation, you may choose two integers $i$ and $x$ ($1 \\le i \\le n$, $x$ can be any integer) and assign $a_i := x$. This operation can be done only if $i$ does not belong to the set $b$.\n\nCalculate the minimum number of operations you should perform so the array $a$ is increasing (that is, $a_1 < a_2 < a_3 < \\dots < a_n$), or report that it is impossible.",
    "tutorial": "First, let's solve the problem without blocked positions. Let's look at the array $b_i = a_i - i$. Obviously, if $a$ strictly increases, then $b$ does not decrease, and vice versa. Now we have to find the maximum number of positions in the $b$ array that can be left unchanged. And you can always choose an integer that will not break the non-decreasing array $b$ for the rest of positions. This problem can be solved in $O(n \\log{n})$ by analogy with the largest increasing subsequence, but now you can take equal elements. Now you can realize that the segments between two blocked positions do not depend on each other, and the initial problem can be solved as the problem described above. All that remains is to check that all blocked positions do not break the strict array increment.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int N = 500 * 1000 + 13;\n\nint n, k;\nint a[N], b[N];\n\nint main() {\n\tscanf(\"%d%d\", &n, &k);\n\tforn(i, n) scanf(\"%d\", &a[i + 1]);\n\ta[0] = -1e9;\n\ta[n + 1] = 2e9;\n\tforn(i, n + 2) a[i] -= i;\n\tforn(i, k) scanf(\"%d\", &b[i + 1]);\n\tb[k + 1] = n + 1;\n\t\n\tint ans = 0;\n\tforn(i, k + 1) {\n\t\tint l = b[i], r = b[i + 1];\n\t\tif (a[l] > a[r]) {\n\t\t\tputs(\"-1\");\n\t\t\treturn 0;\n\t\t}\n\t\tvector<int> lis;\n\t\tfor (int j = l + 1; j < r; ++j) if (a[l] <= a[j] && a[j] <= a[r]) {\n\t\t\tauto pos = upper_bound(lis.begin(), lis.end(), a[j]);\n\t\t\tif (pos == lis.end()) lis.push_back(a[j]);\n\t\t\telse *pos = a[j];\n\t\t}\n\t\tans += (r - l - 1) - int(lis.size());\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "dp",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1437",
    "index": "F",
    "title": "Emotional Fishermen",
    "statement": "$n$ fishermen have just returned from a fishing vacation. The $i$-th fisherman has caught a fish of weight $a_i$.\n\nFishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of showing fish is a permutation of integers from $1$ to $n$). Then they show the fish they caught according to the chosen order. When a fisherman shows his fish, he might either become happy, become sad, or stay content.\n\nSuppose a fisherman shows a fish of weight $x$, and the maximum weight of a previously shown fish is $y$ ($y = 0$ if that fisherman is the first to show his fish). Then:\n\n- if $x \\ge 2y$, the fisherman becomes happy;\n- if $2x \\le y$, the fisherman becomes sad;\n- if none of these two conditions is met, the fisherman stays content.\n\nLet's call an order in which the fishermen show their fish emotional if, after all fishermen show their fish according to this order, each fisherman becomes either happy or sad. Calculate the number of emotional orders modulo $998244353$.",
    "tutorial": "First of all, sort the fishermen so it is easier to consider them in ascending order. The key observation that allows us to solve the problem is the following: there will be an increasing sequence of happy fishermen, and all other fishermen will be unhappy. Consider the fisherman $i$ which belongs to the increasing sequence. Let's analyze which fisherman will be next to it in the order. It is either a fisherman that will be happy, or a fisherman that will be sad. In the first case, the fish caught by this fisherman must have a size of at least $2a_i$, in the second case - at most $\\frac{a_i}{2}$. The first case will be considered later. For the second case, if we know the number of fishermen that were already placed in the order, we know that all of them (except the $i$-th one) belong to the \"sad\" category (that is, the fish of every already placed fisherman, except for the $i$-th one, is at least two times smaller than the fish of the $i$-th fisherman). So, if we have already placed $j$ fishermen, the last happy fisherman was the $i$-th one, and we want to place a sad fisherman, then the number of ways to choose this sad fisherman is exactly $cntLess(i) - j + 1$, where $cntLess(i)$ is the number of fishermen $k$ such that $2 a_k \\le a_i$. If we can handle the first case, this observation will allow us to solve the problem with dynamic programming. Let $dp_{i, j}$ be the number of ways to choose $j$ first fishermen in the order so that the $i$-th fisherman is the last happy one. The case when the next fisherman is sad can be handled with a transition to the state $dp_{i, j + 1}$ (don't forget to multiply by the number of ways to choose the next sad fisherman, as described earlier). What about the case when the next fisherman is happy? We should iterate on the fisherman $k$ such that $a_k \\ge 2a_i$ and transition from $dp_{i, j}$ to $dp_{k, j + 1}$, but this part works in $O(n^3)$. To get an $O(n^2)$ solution, we have to speed it up with prefix sums or something like that.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5043;\nconst int MOD = 998244353;\n\nint dp[N][N];\nint pdp[N][N];\nint cntLess[N];\nint lastLess[N];\nint a[N];\nint n;\n\nint add(int x, int y)\n{\n \tx += y;\n \twhile(x >= MOD) x -= MOD;\n \twhile(x < 0) x += MOD;\n \treturn x;\n}\n\nint sub(int x, int y)\n{\n \treturn add(x, MOD - y);\n}\n\nint mul(int x, int y)\n{\n \treturn (x * 1ll * y) % MOD;\n}\n\nint main()\n{\n\tcin >> n;\n\tfor(int i = 0; i < n; i++)\n\t\tcin >> a[i];\n\tsort(a, a + n);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t \tcntLess[i] = 0;\n\t \tlastLess[i] = -1;\n\t \tfor(int j = 0; j < n; j++)\n\t \t\tif(a[j] * 2 <= a[i])\n\t \t\t{\n\t \t\t \tlastLess[i] = j;\n\t \t\t \tcntLess[i]++;\n\t \t\t}\n\t}\n\tfor(int i = 0; i < n; i++)\n\t{\n\t \tdp[i][1] = 1;\n\t \tpdp[i + 1][1] = add(pdp[i][1], dp[i][1]);\n\t}\n\tfor(int k = 2; k <= n; k++)\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tif(cntLess[i] + 1 >= k)\n\t\t \t\tdp[i][k] = add(mul(dp[i][k - 1], add(cntLess[i], sub(2, k))), pdp[lastLess[i] + 1][k - 1]);\n\t\t \telse\n\t\t \t\tdp[i][k] = 0;\n\t\t \t//cerr << i << \" \" << k << \" \" << dp[i][k] << endl;                                \n\t\t \tpdp[i + 1][k] = add(pdp[i][k], dp[i][k]);\n\t\t}\n\n\tcout << dp[n - 1][n] << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1437",
    "index": "G",
    "title": "Death DBMS",
    "statement": "For the simplicity, let's say that the \"Death Note\" is a notebook that kills a person when their name is written in it.\n\nIt's easy to kill with it, but it's pretty hard to keep track of people you haven't killed and still plan to. You decided to make a \"Death Database Management System\" — a computer program that provides the easy access to the database of possible victims. Let me describe its specifications to you.\n\nLet's define a victim entity: a victim has a name (not necessarily unique) that consists only of lowercase Latin letters and an integer suspicion value.\n\nAt the start of the program the user enters a list of $n$ victim names into a database, each suspicion value is set to $0$.\n\nThen the user makes queries of two types:\n\n- $1~i~x$ — set the suspicion value of the $i$-th victim to $x$;\n- $2~q$ — given a string $q$ find the maximum suspicion value of a victim whose name is a contiguous substring of $q$.\n\nJust to remind you, this program doesn't kill people, it only helps to search for the names to write down in an actual notebook. Thus, the list of the victims in the database doesn't change throughout the queries.\n\nWhat are you waiting for? Write that program now!",
    "tutorial": "I'm feeling extremely amused by the power of Aho-Corasick lately, so I will describe two solutions of this problem with it. Feel free to point out how cool you are solving the task with hashes or some suffix structure but Aho solutions will still be cooler. I also want to mention I'm quite proud of the name I came up with for that task :) First, let's assume that the words in the dictionary are unique. Build an Aho-Corasick automaton on the dictionary. Then build the tree of its suffix links. For the first solution you can use the fact that there are not a lot of words in the dictionary that can end in each position. To be exact, at most one word per unique word length. Thus, that's bounded by the square root of the total length. For that reason you can iterate over all the words that end in all positions of the queries in $O(q \\sqrt n)$. How to do that fast? For each vertex of the automaton precalculate the closest vertex up the suffix link tree that's a terminal. Feed the query word into the automaton and from each vertex you stay at just jump up the tree until you reach the root. Take the maximum value over all the visited terminals. The second solution actually involves an extra data structure on top of that. No, it's not HLD. You are boring for using it. Let's abuse the fact that you are allowed to solve the problem fully offline. For each word you can save the list of pairs (time, value) of the times the value of the word changed. For each vertex of the automaton you can save all the times that vertex has been queried from. Now traverse the tree with dfs. When you enter the vertex, you want to apply all the updates that are saved for the words that are terminals here. What are the updates? From the list we obtained for a word you can generate such triples $(l, r, x)$ that this word had value $x$ from query $l$ to query $r$. Don't forget the $0$ value from $0$ to the first update to this word. Then ask all the queries. Then go to children. When you exit the vertex, you want all the updates to be gone. Well, there is a trick for these kinds of operations, it's called rollbacks. Maintain a segment tree over the query times, the $i$-th leaf should store the maximum value during the $i$-th query. The update operation updates the range with the new possible maximum. How to avoid using lazy propagation with such updates? Well, on point query you can collect all the values from the segtree nodes you visit on your way down. That way you don't have to push the updates all the way to the leaves. Not that it matters that much but the number of values to be saved for future rollbacks is decreased dramatically. That solution works in $O((n + q) \\log q)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int AL = 26;\nvector<vector<pair<int, int>>> upd;\nvector<int> ans;\nint n, m;\n\nstruct segtree{\n\tvector<int*> where;\n\tvector<int> vals;\n\tvector<int> t;\n\tint n;\n\t\n\tsegtree(){}\n\t\n\tsegtree(int n) : n(n){\n\t\tt.assign(4 * n, -1);\n\t\twhere.clear();\n\t\tvals.clear();\n\t}\n\t\n\tvoid updh(int v, int l, int r, int L, int R, int val){\n\t\tif (L >= R)\n\t\t\treturn;\n\t\tif (l == L && r == R){\n\t\t\twhere.push_back(&t[v]);\n\t\t\tvals.push_back(t[v]);\n\t\t\tt[v] = max(t[v], val);\n\t\t\treturn;\n\t\t}\n\t\tint m = (l + r) / 2;\n\t\tupdh(v * 2, l, m, L, min(m, R), val);\n\t\tupdh(v * 2 + 1, m, r, max(m, L), R, val);\n\t}\n\t\n\tvoid upd(int l, int r, int val){\n\t\tupdh(1, 0, n, l, r, val);\n\t}\n\t\n\tint geth(int v, int l, int r, int pos){\n\t\tif (l == r - 1)\n\t\t\treturn t[v];\n\t\tint m = (l + r) / 2;\n\t\tif (pos < m)\n\t\t\treturn max(t[v], geth(v * 2, l, m, pos));\n\t\treturn max(t[v], geth(v * 2 + 1, m, r, pos));\n\t}\n\t\n\tint get(int pos){\n\t\treturn geth(1, 0, n, pos);\n\t}\n\t\n\tvoid rollback(){\n\t\t*where.back() = vals.back();\n\t\twhere.pop_back();\n\t\tvals.pop_back();\n\t}\n};\n\nsegtree st;\n\nstruct aho_corasick {\n\tstruct node {\n\t\tmap<int, int> nxt, go;\n\t\tint p, pch;\n\t\tint suf, ssuf;\n\t\tvector<int> term, qs;\n\t\t\n\t\tnode() {\n\t\t\tnxt.clear();\n\t\t\tgo.clear();\n\t\t\tsuf = ssuf = -1;\n\t\t\tterm.clear();\n\t\t\tp = -1, pch = -1;\n\t\t\tqs.clear();\n\t\t}\n\t};\n\n\tvector<node> nodes;\n\tvector<vector<int>> g;\n\t\n\taho_corasick() {\n\t\tnodes = vector<node>(1, node());\n\t}\n\n\tvoid add(const string& s, int id) {\n\t\tint v = 0;\n\t\tforn(i, s.size()) {\n\t\t\tint c = s[i] - 'a';\n\t\t\tif (!nodes[v].nxt.count(c)) {\n\t\t\t\tnodes.push_back(node());\n\t\t\t\tnodes[v].nxt[c] = int(nodes.size()) - 1;\n\t\t\t\tnodes.back().p = v;\n\t\t\t\tnodes.back().pch = c;\n\t\t\t}\n\t\t\tv = nodes[v].nxt[c];\n\t\t}\n\t\tnodes[v].term.push_back(id);\n\t}\n\t\n\tvoid feed(const string &s, int id){\n\t\tint v = 0;\n\t\tforn(i, s.size()){\n\t\t\tint c = s[i] - 'a';\n\t\t\tv = go(v, c);\n\t\t\tnodes[v].qs.push_back(id);\n\t\t}\n\t}\n\t\n\tint go(int v, int c) {\n\t\tif (nodes[v].go.count(c))\n\t\t\treturn nodes[v].go[c];\n\t\tif (nodes[v].nxt.count(c))\n\t\t\treturn nodes[v].go[c] = nodes[v].nxt[c];\n\t\tif (v == 0)\n\t\t\treturn nodes[v].go[c] = 0;\n\t\treturn nodes[v].go[c] = go(suf(v), c);\n\t}\n\t\n\tint suf(int v) {\n\t\tif (nodes[v].suf != -1)\n\t\t\treturn nodes[v].suf;\n\t\tif (v == 0 || nodes[v].p == 0)\n\t\t\treturn nodes[v].suf = 0;\n\t\treturn nodes[v].suf = go(suf(nodes[v].p), nodes[v].pch);\n\t}\n\t\n\tvoid build_tree() {\n\t\tg.resize(nodes.size());\n\t\tforn(v, nodes.size()) {\n\t\t\tint u = suf(v);\n\t\t\tif (v != u)\n\t\t\t\tg[u].push_back(v);\n\t\t}\n\t}\n\t\n\tvoid dfs(int v){\n\t\tint cur = st.where.size();\n\t\tfor (auto i : nodes[v].term){\n\t\t\tint lst = m;\n\t\t\tfor (auto it : upd[i]){\n\t\t\t\tst.upd(it.first, lst, it.second);\n\t\t\t\tlst = it.first;\n\t\t\t}\n\t\t\tst.upd(0, lst, 0);\n\t\t}\n\t\tfor (auto j : nodes[v].qs){\n\t\t\tans[j] = max(ans[j], st.get(j));\n\t\t}\n\t\tfor (int u : g[v]){\n\t\t\tdfs(u);\n\t\t}\n\t\tint nw = st.where.size();\n\t\tforn(_, nw - cur){\n\t\t\tst.rollback();\n\t\t}\n\t}\n};\n\naho_corasick ac;\n\nint main() {\n\tios::sync_with_stdio(!cin.tie(0));\n\tcin >> n >> m;\n\tupd.resize(n);\n\tans.resize(m, -1);\n\t\n\tvector<int> tp2;\n\t\n\tac = aho_corasick();\n\tst = segtree(m);\n\t\n\tforn(i, n){\n\t\tstring s;\n\t\tcin >> s;\n\t\tac.add(s, i);\n\t}\n\tforn(i, m){\n\t\tint t;\n\t\tcin >> t;\n\t\tif (t == 1){\n\t\t\tint j, x;\n\t\t\tcin >> j >> x;\n\t\t\t--j;\n\t\t\tupd[j].push_back(make_pair(i, x));\n\t\t}\n\t\telse{\n\t\t\tstring q;\n\t\t\tcin >> q;\n\t\t\tac.feed(q, i);\n\t\t\ttp2.push_back(i);\n\t\t}\n\t}\n\tforn(i, n){\n\t\treverse(upd[i].begin(), upd[i].end());\n\t}\n\t\n\tac.build_tree();\n\tac.dfs(0);\n\tfor (auto it : tp2)\n\t\tcout << ans[it] << \"\\n\";\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "string suffix structures",
      "strings",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1438",
    "index": "A",
    "title": "Specific Tastes of Andre ",
    "statement": "Andre has very specific tastes. Recently he started falling in love with arrays.\n\nAndre calls an nonempty array $b$ \\textbf{good}, if sum of its elements is divisible by the length of this array. For example, array $[2, 3, 1]$ is good, as sum of its elements — $6$ — is divisible by $3$, but array $[1, 1, 2, 3]$ isn't good, as $7$ isn't divisible by $4$.\n\nAndre calls an array $a$ of length $n$ \\textbf{perfect} if the following conditions hold:\n\n- Every nonempty subarray of this array is \\textbf{good}.\n- For every $i$ ($1 \\le i \\le n$), $1 \\leq a_i \\leq 100$.\n\nGiven a positive integer $n$, output any \\textbf{perfect} array of length $n$. We can show that for the given constraints such an array always exists.\n\nAn array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "The array $a$ = $[1,1,\\ldots,1,1]$ is perfect since the sum of every subarray is exactly equal to its length, and thus divisible by it.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1438",
    "index": "B",
    "title": "Valerii Against Everyone",
    "statement": "You're given an array $b$ of length $n$. Let's define another array $a$, also of length $n$, for which $a_i = 2^{b_i}$ ($1 \\leq i \\leq n$).\n\nValerii says that every two non-intersecting subarrays of $a$ have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers $l_1,r_1,l_2,r_2$ that satisfy the following conditions:\n\nIf such four integers exist, you will prove Valerii wrong. Do they exist?\n\nAn array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "We claim the answer is NO if and only if the elements are pairwise distinct. If any element has two occurrences, we can trivially select them as the two subarrays. Otherwise, since all elements are distinct, choosing a subarray is the same as choosing the set bits of a $10^9$ digit long binary number. Since every number has a unique binary representation, no two subarrays can have the same sum.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1438",
    "index": "C",
    "title": "Engineer Artem",
    "statement": "Artem is building a new robot. He has a matrix $a$ consisting of $n$ rows and $m$ columns. The cell located on the $i$-th row from the top and the $j$-th column from the left has a value $a_{i,j}$ written in it.\n\nIf two adjacent cells contain the same value, the robot will break. A matrix is called \\textbf{good} if no two adjacent cells contain the same value, where two cells are called adjacent if they share a side.\n\nArtem wants to \\textbf{increment the values in some cells by one} to make $a$ good.\n\nMore formally, find a good matrix $b$ that satisfies the following condition —\n\n- For all valid ($i,j$), either $b_{i,j} = a_{i,j}$ or $b_{i,j} = a_{i,j}+1$.\n\nFor the constraints of this problem, it can be shown that such a matrix $b$ always exists. If there are several such tables, you can output any of them. Please note that you do not have to minimize the number of increments.",
    "tutorial": "The increment by one operation essentially allows us to change the parity of any position. Let's color the matrix like a chessboard. Since every pair of adjacent cells consist of cells with different colors, we can make values at all black cells even and values at all white cells odd.",
    "tags": [
      "2-sat",
      "chinese remainder theorem",
      "constructive algorithms",
      "fft",
      "flows"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1438",
    "index": "D",
    "title": "Powerful Ksenia",
    "statement": "Ksenia has an array $a$ consisting of $n$ positive integers $a_1, a_2, \\ldots, a_n$.\n\nIn one operation she can do the following:\n\n- choose three distinct indices $i$, $j$, $k$, and then\n- change all of $a_i, a_j, a_k$ to $a_i \\oplus a_j \\oplus a_k$ simultaneously, where $\\oplus$ denotes the bitwise XOR operation.\n\nShe wants to make all $a_i$ equal \\textbf{in at most $n$ operations}, or to determine that it is impossible to do so. She wouldn't ask for your help, but please, help her!",
    "tutorial": "We will first solve the problem for odd $n$, and then extend the solution to even $n$. Note that applying the operation to $a, b, b$ makes all of them equal to $a$. Thus, we can try making pairs of equal elements. This is easy for odd $n$: While at least $3$ unpaired elements exist, apply the operation on any $3$. Pair any two of them and repeat. The number of operations used is exactly $n-1$. Let us denote $X$ as the xor of all elements in the original array. To solve for even $n$, we note that applying the given operation does not change $X$. Since the xor of an even number of same elements is $0$, the answer is impossible for arrays with $X \\neq 0$. To solve for even $n$ and $X = 0$, we can just solve the problem for the first $n-1$ using the odd approach and the last element will magically be equal to the first $n-1$. This problem was set by Anti-Light and prepared by knightron00",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1438",
    "index": "E",
    "title": "Yurii Can Do Everything",
    "statement": "Yurii is sure he can do everything. Can he solve this task, though?\n\nHe has an array $a$ consisting of $n$ positive integers. Let's call a subarray $a[l...r]$ \\textbf{good} if the following conditions are simultaneously satisfied:\n\n- $l+1 \\leq r-1$, i. e. the subarray has length at least $3$;\n- $(a_l \\oplus a_r) = (a_{l+1}+a_{l+2}+\\ldots+a_{r-2}+a_{r-1})$, where $\\oplus$ denotes the bitwise XOR operation.\n\nIn other words, a subarray is good if the bitwise XOR of the two border elements is equal to the sum of the rest of the elements.\n\nYurii wants to calculate the total number of good subarrays. What is it equal to?\n\nAn array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "It's natural to think that the number of good subarrays cannot be very large; this is indeed true. The following algorithm works: Fix the left endpoint $l$. Let $k$ be the most significant set bit in $a_l$. Check every $r$ in increasing order by bruteforce while $\\text{sum}(l+1,r-1)$ is smaller than $2^{k+1}$. Reverse the array, and do the same again. Note that we need to be careful here since we might count the same subarray twice. We, now, prove its correctness and efficiency. Consider any good subarray $a[l...r]$, let $k_1$ be the most significant set bit in $\\text{max}(a_l,a_r)$ and $k_2$ the most significant set bit in $\\text{sum}(l+1,r-1)$. We must have $k_1 \\geq k_2$ because all bits greater than $k_1$ will be unset in $a_l \\oplus a_r$, but $k_2$ is set. Hence, the algorithm counts all possible good subarrays. We now prove the number of subarrays our algorithm checks is of the order $\\mathcal{O}(n\\log{}a_i)$. For every $r$, let's count the number of $l$'s it can be reached by. For a particular $k$, notice that only the $2$ closest $l$'s to the left with this bit set can reach this $r$. For the third one and beyond, the sum will be at least $2*2^k = 2^{k+1}$ simply due the to the contribution of the closest two. Since there are $n$ right endpoints and only $\\log{}a_i$ possible values of $k$, our claim is true.",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "divide and conquer",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1438",
    "index": "F",
    "title": "Olha and Igor",
    "statement": "\\textbf{This is an interactive problem.}\n\nIgor wants to find the key to Olha's heart. The problem is, that it's at the root of a binary tree.\n\nThere is a perfect binary tree of height $h$ consisting of $n = 2^{h} - 1$ nodes. The nodes have been assigned distinct labels from $1$ to $n$. However, \\textbf{Igor only knows $h$ and does not know which label corresponds to which node}.\n\nTo find key to Olha's heart he needs to find the label assigned to the root by making queries of the following type \\textbf{at most $n+420$ times}:\n\n- Select three \\textbf{distinct} labels $u$, $v$ and $w$ ($1 \\leq u,v,w \\leq n$).\n- In response, Olha (the grader) will tell him the label of the \\textbf{lowest common ancestor} of nodes labelled $u$ and $v$, if the tree was \\textbf{rooted} at the node labelled $w$ instead.\n\nHelp Igor to find the root!\n\n\\textbf{Note:} the grader is not adaptive: the labels are fixed before any queries are made.",
    "tutorial": "The solution is as follows. Query $420$ random triples. Let $c_1$ and $c_2$ be the two most frequently returned nodes - these are the children of the root. Query $c_1,c_2$ with every other $i$, and only the root will return $i$. Firstly, note that a query - $u$, $v$, and $w$ - returns a node $x$ that minimizes the sum of distances from all the three nodes. Thus, the order of the $3$ nodes is irrelevant. You can think of $x$ as the node that lies on the path of every possible pair formed from the $3$ nodes. Now, let's calculate the number of triples for which node $u$ is returned as the answer. For this, we will root the tree at $u$, and calculate the subtree sizes of its children - $s_1$, $s_2$, and $s_3$ ($s_3 = 0$, if $u$ is the actual root). With these values with us, the number of triples is: $(s_1\\times s_2\\times s_3)+(s_1\\times s_2)+(s_2\\times s_3)+(s_3\\times s_1)$ In the above expression, the first term calculates the triples in which $u$ is not present, while the other $3$ terms assume $u$ is one of the nodes in the triple. Nodes at the same depth will, of course, have the same count. At this point, we can either observe that this expression is maximum when $u$ is a child of the root or calculate values for every depth and compare them. For example, for $h = 5$, each child of the root is the answer to about $23\\%$ of the triples. This value converges to $18\\%$ per child when $h$ approaches $18$. Thus, when we query $420$ random triples, we can be sure enough that the two most frequently appearing values will be the children of the root. Finally, we just note that for all non-root nodes $v$, querying $c_1$, $c_2$, and $v$ gives either $c_1$ or $c_2$. Time Complexity: $\\mathcal{O}(n)$",
    "tags": [
      "interactive",
      "probabilities",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1439",
    "index": "A2",
    "title": "Binary Table (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.}\n\nYou are given a binary table of size $n \\times m$. This table consists of symbols $0$ and $1$.\n\nYou can make such operation: select $3$ different cells that belong to one $2 \\times 2$ square and change the symbols in these cells (change $0$ to $1$ and $1$ to $0$).\n\nYour task is to make all symbols in the table equal to $0$. You are allowed to make at most $nm$ operations. \\textbf{You don't need to minimize the number of operations.}\n\nIt can be proved, that it is always possible.",
    "tutorial": "Consider two cases: If $n = 2$ and $m = 2$, there are only $4$ possible operations, and we can use up to $4$ operations. So, one can check all the $2^4$ possible ways of choosing these operations, and seeing which combination of these operation will result in a full $0$ grid. Otherwise, at least one of $n$ and $m$ is bigger than $2$. Without loss of generality imagine $n > 2$. Take the $n$th row. For each cell within that row, we can use one operation on it, its left neighbour and the two cells above to fix this cell. We can do this for the first $n - 2$ cells in the row, and fix the last two with one operation on them. We will make at most $n - 1$ operations and reach a situation with one empty row. We can take the last row away and apply this procedure for the remaining $(n - 1) \\times m$ grid. If we say inductively that we will have at most $(n - 1)m$ operations for the remaining grid, we will have done at most $(n - 1)m + n - 1 = nm - 1 < nm$ operations in total. When $n = 2$, we can do the same with the columns, and when $n = m = 2$, we can fix the remaining $2 \\times 2$ grid as we discussed above. Time complexity: $O(nm)$ for each case.",
    "code": "//                             In The Name Of Allah\n#include <bits/stdc++.h>\n#define\tss second\n#define ff first\n#define use_fast ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)\n#define ret(n) return cout << n, 0\n#define se(n) cout << setprecision(n) << fixed\n#define pb push_back\n#define ll long long\n#define ld long double\n#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops\")\n#pragma GCC optimize(\"no-stack-protector,fast-math\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\nusing namespace std; \n\nconst int N = 200, OO = 1e9 + 7, T = 50, M = 1e9 + 7, P = 6151, SQ = 280, lg = 20;\ntypedef pair <int, int> pii;\nchar c[N][N];\nbool cnt[N][N];\n\nstruct node {int x1, y1, x2, y2, x3, y3;} p[5];\nvector <node> v;\n\nvoid upd(int x, int y, int tp, bool is) {\n    if(is)\n        v.pb({x + p[tp].x1, y + p[tp].y1, x + p[tp].x2, y + p[tp].y2, x + p[tp].x3, y + p[tp].y3});\n    else \n        cnt[x + p[tp].x1][y + p[tp].y1] ^= 1, cnt[x + p[tp].x2][y + p[tp].y2] ^= 1, cnt[x + p[tp].x3][y + p[tp].y3] ^= 1;\n}\n\nvoid solve() {\n\tint n, m, od = 0;\n\tv.clear();\n\tcin >> n >> m;\n\tfor(int i = 1; i <= n; i++) {\n\t\tfor(int j = 1; j <= m; j++) {\n\t\t\tcin >> c[i][j];\n\t\t\tif(c[i][j] == '1')\n\t\t\t\tod++, cnt[i][j] = true;\n\t\t\telse\n\t\t\t    cnt[i][j] = false;\n\t\t}\n\t}\n\tif(od == 0) {\n\t\tcout << 0 << endl;\n\t\treturn;\n\t}\n\tif(n == 1 || m == 1) {\n\t\tcout << -1 << endl;\n\t\treturn;\n\t}\n    for(int i = 1; i <= n - 2; i++) {\n\t\tfor(int j = 1; j <= m; j++) {\n\t\t\tif(cnt[i][j]) {\n\t\t\t    if(j != m) {\n\t\t\t        v.pb({i, j, i + 1, j, i + 1, j + 1});\n\t\t\t        cnt[i][j] ^= 1, cnt[i + 1][j] ^= 1, cnt[i + 1][j + 1] ^= 1;\n\t\t\t    } \n\t\t\t    else {\n\t\t\t        v.pb({i, j, i + 1, j, i + 1, j - 1});\n\t\t\t        cnt[i][j] ^= 1, cnt[i + 1][j] ^= 1, cnt[i + 1][j - 1] ^= 1;\n\t\t\t    }\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i = 1; i <= m - 2; i++) {\n\t    if(cnt[n - 1][i]) {\n\t        v.pb({n - 1, i, n - 1, i + 1, n, i + 1});\n\t        cnt[n - 1][i] ^= 1, cnt[n - 1][i + 1] ^= 1, cnt[n][i + 1] ^= 1; \n\t    }\n\t    if(cnt[n][i]) {\n\t        v.pb({n, i, n - 1, i + 1, n, i + 1});\n\t        cnt[n][i] ^= 1, cnt[n - 1][i + 1] ^= 1, cnt[n][i + 1] ^= 1; \n\t    }\n\t}\n\tfor(int msk = 0; msk < (1 << 4); msk++) {\n\t    for(int j = 0; j < 4; j++) \n\t       if(msk & (1 << j))\n\t           upd(n - 1, m - 1, j, 0);\n\t    if(!cnt[n - 1][m - 1] && !cnt[n - 1][m] && !cnt[n][m - 1] && !cnt[n][m]) {\n\t        for(int j = 0; j < 4; j++) \n\t            if(msk & (1 << j))\n\t                upd(n - 1, m - 1, j, 1);\n\t        break;\n\t    }\n\t    for(int j = 0; j < 4; j++)\n\t        if(msk & (1 << j))\n\t            upd(n - 1, m - 1, j, 0);\n\t}\n\tcout << (int)v.size() << endl;\n\tfor(auto u : v)\n        cout << u.x1 << \" \" << u.y1 << \" \" << u.x2 << \" \" << u.y2 << \" \" << u.x3 << \" \" << u.y3 << endl;\n}\n\nint32_t main(){\n\tuse_fast;\n    p[0] = {0, 0, 0, 1, 1, 0}, p[1] = {0, 1, 0, 0, 1, 1}, p[2] = {1, 0, 1, 1, 0, 0}, p[3] = {1, 1, 0, 1, 1, 0};\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1439",
    "index": "B",
    "title": "Graph Subset Problem",
    "statement": "You are given an undirected graph with $n$ vertices and $m$ edges. Also, you are given an integer $k$.\n\nFind either a clique of size $k$ or a non-empty subset of vertices such that each vertex of this subset has at least $k$ neighbors in the subset. If there are no such cliques and subsets report about it.\n\nA subset of vertices is called a clique of size $k$ if its size is $k$ and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.",
    "tutorial": "div1 B : It is easy to see that if $k > \\sqrt{2m}$ the answer is $-1$; because if $k > \\sqrt{2m}$, no matter whether we have a clique of size $k$ or a subset of the graph with $\\delta \\geq k$, we will have more than $m$ edges in total. Now, the main idea is to suppose $u$ is the vertex with minimum degree; if $d(u) < k - 1$ we should delete $u$ becuase $u$ can not be in clique or the subset of vertices such that each vertex of this subset has at least $k$ neighbors in the subset; so we have to erase $u$ and all edges attached to it. If $d(u) > k$, remaining vertices will form a subset that every vertex have at least $k$ neighbors in the subset, so we'll print this subset as answer. If $d(u) = k - 1$, we consider $u$ and all neighbors of $u$ as candidate for clique of size $k$. then we erase $u$ and all edges attached to it. If we erase all vertices and didn't found any good subset, then we should check clique candidates. for checking clique candidates fast, iterate over vertices and name current vertex $v$. then for neighbors of $v$ set $nei_v$ to $1$ and $0$ otherwise. for each clique candidate that contains $v$ like $C$, we check edge between $v$ and $u \\in C$ in $O(1)$ using array $nei$. every time we find new clique candidate, we remove at least $k - 1$ edges, so number of clique candidates is at most $\\frac{m}{k-1}$. for every candidate we check $\\mathcal{O}(k^2)$ edges in overall. so time complexity is $\\mathcal{O}(\\frac{m}{k}).\\mathcal{O}(k^2) \\in \\mathcal{O}(m.k)$.",
    "code": "//                             In The Name Of Allah                                           \n#include <bits/stdc++.h>\n#define\tss second\n#define ff first\n#define use_fast ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)\n#define se(n) cout << setprecision(n) << fixed\n#define pb push_back\n//#define int long long\n#define ld long double\n#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops\")\n#pragma GCC optimize(\"no-stack-protector,fast-math\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\nusing namespace std; \nconst int N = 1e5 + 100, OO = 1e9 + 7, T = 22, M = 1e9 + 7, P = 6151, SQ = 1300, lg = 22;\ntypedef pair <int, int> pii;\nint mark[N], deg[N], ct[N];\nbool ans[N], can[N];\nvector <int> v[N], A;\nvector <pii> ch[N];\nbool cmp(int x, int y) {\n\treturn mark[x] < mark[y];\n}\n\nvoid solve() {\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tA.clear();\n\tfor(int i = 0; i <= n; i++)\n\t    v[i].clear(), ch[i].clear(), mark[i] = deg[i] = ct[i] = 0, ans[i] = can[i] = false;\n\tfor(int i = 0; i < m; i++) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\tv[x].pb(y);\n\t\tv[y].pb(x);\n\t}\n\tif(k > 500) {\n\t   cout << -1 << endl;\n\t   return;\n\t}\n\tset <pii> st;\n\tfor(int i = 1; i <= n; i++)\n\t\tst.insert({deg[i] = (int)v[i].size(), i});\n\tint cnt = 1;\n\twhile((int)st.size()) {\n\t\tpii p = *st.begin();\n\t\tif(p.ff >= k) {\n\t\t\tcout << 1 << \" \" << (int)st.size() << endl;\n\t\t\tfor(auto u : st)\n\t\t\t\tcout << u.ss << \" \";\n\t\t\tcout << endl;\n\t\t\treturn;\n\t\t}\n\t\telse {\n\t\t\tst.erase(p);\n\t\t\tmark[p.ss] = cnt;\n\t\t\tfor(auto u : v[p.ss])\n\t\t\t\tif(!mark[u])\n\t\t\t\t\tst.erase({deg[u], u}), st.insert({--deg[u], u});\n\t\t\tA.pb(p.ss);\n\t\t}\n\t\tcnt++;\n\t}\n\tfor(auto i : A) {\n\t\tint nxt = 0;\n\t\tfor(auto u : v[i]) \n\t\t\tif(mark[u] > mark[i])\n\t\t\t\tct[nxt++] = u, can[u] = true;\n\t\tfor(auto u : ch[i]) \n\t\t\tif(!can[u.ff])\n\t\t\t\tans[u.ss] = false;\n\t\tfor(int j = 0; j < nxt; j++)\n\t\t\tcan[ct[j]] = false;\n\t\tif(nxt != k - 1)\n\t\t\tcontinue;\n\t\tans[i] = true;\n\t\tsort(ct, ct + nxt, cmp);\n\t\tfor(int j = 0; j < nxt; j++)\n\t\t\tfor(int k = j + 1; k < nxt; k++)\n\t\t\t\tch[ct[j]].pb({ct[k], i});\n\t}\n\tfor(auto i : A) {\n\t\tif(!ans[i])\n\t\t\tcontinue;\n\t\tcout << 2 << endl;\n\t\tcout << i << \" \";\n\t\tfor(auto u : v[i])\n\t\t\tif(mark[u] > mark[i])\n\t\t\t\tcout << u << \" \";\n\t\tcout << endl;\n\t\treturn;\n\t}\n\tcout << -1 << endl;\n\treturn;\n}\n\nint32_t main() {\n\tuse_fast;\n\tint t;\n    cin >> t;\n    while(t--)\n        solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1439",
    "index": "C",
    "title": "Greedy Shopping",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$ of integers. This array is \\textbf{non-increasing}.\n\nLet's consider a line with $n$ shops. The shops are numbered with integers from $1$ to $n$ from left to right. The cost of a meal in the $i$-th shop is equal to $a_i$.\n\nYou should process $q$ queries of two types:\n\n- 1 x y: for each shop $1 \\leq i \\leq x$ set $a_{i} = max(a_{i}, y)$.\n- 2 x y: let's consider a hungry man with $y$ money. He visits the shops from $x$-th shop to $n$-th and if he can buy a meal in the current shop he buys one item of it. Find how many meals he will purchase. The man can buy a meal in the shop $i$ if he has at least $a_i$ money, and after it his money decreases by $a_i$.",
    "tutorial": "We can prove that the hungry man will eat at most $log_2(maxY)$ continiuous subsegments, where $maxY$ is the maximum amount of money possible. Why is that so? Suppose the hungry man buys a meal from the $i$ th shop but can't buy a meal from the $(i + 1)$th one after that. Then, the money the hungry man had before buying the $i$th food is at most twice the money he has after buying the $i$th food because $a_i > a_{i+1}$. So every time he breaks the subsegment of shops, his money is cut in at least half, so he will eat atmost $log_2(maxY)$ continuous subsegments. Now we need a data structure with the following queries: range_max and range_sum. Since our array is non-increasing, a segment tree will suffice. The first type of query is just a range_max query. For the second type of query you can find the first element that is equal to or smaller than the hungry man's money and after that find the segment that he will eat, in which we can use a binary-search on the tree to find these both. After that we can repeat this action untill we reach the end of the array, or until his money runs out. Time complexity: $O((n + q)log(maxY)log(n))$",
    "code": "#include <bits/stdc++.h>\n#pragma GCC optimize (\"O2,unroll-loops\")\n#pragma GCC optimize(\"no-stack-protector,fast-math\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<pii, int> piii;\ntypedef pair<ll, ll> pll;\n#define debug(x) cerr<<#x<<'='<<(x)<<endl;\n#define debugp(x) cerr<<#x<<\"= {\"<<(x.first)<<\", \"<<(x.second)<<\"}\"<<endl;\n#define debug2(x, y) cerr<<\"{\"<<#x<<\", \"<<#y<<\"} = {\"<<(x)<<\", \"<<(y)<<\"}\"<<endl;\n#define debugv(v) {cerr<<#v<<\" : \";for (auto x:v) cerr<<x<<' ';cerr<<endl;}\n#define all(x) x.begin(), x.end()\n#define pb push_back\n#define kill(x) return cout<<x<<'\\n', 0;\n\nconst int inf=1000000010;\nconst ll INF=10000000000000010LL;\nconst int mod=1000000007;\nconst int MAXN=200010, LOG=20;\n\nll n, m, k, u, v, x, y, t, a, b, ans;\nll A[MAXN];\nll seg[MAXN<<2], lazy[MAXN<<2];\nint Mn[MAXN<<2], Mx[MAXN<<2];\n\nvoid Build(int id, int tl, int tr){\n\tif (tr-tl==1){\n\t\tMn[id]=Mx[id]=seg[id]=A[tl];\n\t\treturn ;\n\t}\n\tint mid=(tl+tr)>>1;\n\tBuild(id<<1, tl, mid);\n\tBuild(id<<1 | 1, mid, tr);\n\tMn[id]=min(Mn[id<<1], Mn[id<<1 | 1]);\n\tMx[id]=max(Mx[id<<1], Mx[id<<1 | 1]);\n\tseg[id]=seg[id<<1] + seg[id<<1 | 1];\t\n}\ninline void add_lazy(int id, int len, ll val){\n\tMn[id]=val;\n\tMx[id]=val;\n\tlazy[id]=val;\n\tseg[id]=len*val;\n}\ninline void shift(int id, int tl, int tr){\n\tif (!lazy[id]) return ;\n\tint mid=(tl+tr)>>1;\n\tadd_lazy(id<<1, mid-tl, lazy[id]);\n\tadd_lazy(id<<1 | 1, tr-mid, lazy[id]);\n\tlazy[id]=0;\n}\nvoid Maximize(int id, int tl, int tr, int pos, ll val){\n\tif (pos<=tl || val<=Mn[id]) return ;\n\tif (tr<=pos && Mx[id]<=val){\n\t\tadd_lazy(id, tr-tl, val);\n\t\treturn ;\n\t}\n\tshift(id, tl, tr);\n\tint mid=(tl+tr)>>1;\n\tMaximize(id<<1, tl, mid, pos, val);\n\tMaximize(id<<1 | 1, mid, tr, pos, val);\n\tMn[id]=min(Mn[id<<1], Mn[id<<1 | 1]);\n\tMx[id]=max(Mx[id<<1], Mx[id<<1 | 1]);\n\tseg[id]=seg[id<<1] + seg[id<<1 | 1];\n}\nint BS1(int id, int tl, int tr, int pos, ll val){\n\tif (tr<=pos || val<Mn[id]) return tr;\n\tif (tr-tl==1) return tl;\n\tshift(id, tl, tr);\n\tint mid=(tl+tr)>>1, tmp=BS1(id<<1, tl, mid, pos, val);\n\tif (tmp==mid) return BS1(id<<1 | 1, mid, tr, pos, val);\n\treturn tmp;\n}\nint BS2(int id, int tl, int tr, ll val){\n\tif (seg[id]<=val) return tr;\n\tif (tr-tl==1) return tl;\n\tshift(id, tl, tr);\n\tint mid=(tl+tr)>>1, tmp=BS2(id<<1, tl, mid, val);\n\tif (tmp<mid) return tmp;\n\treturn BS2(id<<1 | 1, mid, tr, val-seg[id<<1]);\n}\nll Get(int id, int tl, int tr, int l, int r){\n\tif (r<=tl || tr<=l) return 0;\n\tif (l<=tl && tr<=r) return seg[id];\n\tshift(id, tl, tr);\n\tint mid=(tl+tr)>>1;\n\treturn Get(id<<1, tl, mid, l, r) + Get(id<<1 | 1, mid, tr, l, r);\n}\n\nint main(){\n\tios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\tcin>>n>>m;\n\tfor (int i=1; i<=n; i++) cin>>A[i];\n\tBuild(1, 1, n+1);\n\twhile (m--){\n\t\tcin>>t>>x>>y;\n\t\tif (t==1) Maximize(1, 1, n+1, x+1, y);\n\t\telse{\n\t\t\tans=0;\n\t\t\twhile (1){\n\t\t\t\tx=BS1(1, 1, n+1, x, y);\n\t\t\t\tif (x==n+1) break ;\n\t\t\t\tll val=y+Get(1, 1, n+1, 1, x);\n\t\t\t\tint xx=BS2(1, 1, n+1, val);\n\t\t\t\t// buy [x, xx)\n\t\t\t\tans+=xx-x;\n\t\t\t\ty-=Get(1, 1, n+1, x, xx);\n\t\t\t\tx=xx;\n\t\t\t}\n\t\t\tcout<<ans<<\"\\n\";\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "greedy",
      "implementation"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1439",
    "index": "D",
    "title": "INOI Final Contests",
    "statement": "Today is the final contest of INOI (Iranian National Olympiad in Informatics). The contest room is a row with $n$ computers. All computers are numbered with integers from $1$ to $n$ from left to right. There are $m$ participants, numbered with integers from $1$ to $m$.\n\nWe have an array $a$ of length $m$ where $a_{i}$ ($1 \\leq a_i \\leq n$) is the computer behind which the $i$-th participant wants to sit.\n\nAlso, we have another array $b$ of length $m$ consisting of characters 'L' and 'R'. $b_i$ is the side from which the $i$-th participant enters the room. 'L' means the participant enters from the left of computer $1$ and goes from left to right, and 'R' means the participant enters from the right of computer $n$ and goes from right to left.\n\nThe participants in the order from $1$ to $m$ enter the room one by one. The $i$-th of them enters the contest room in the direction $b_i$ and goes to sit behind the $a_i$-th computer. If it is occupied he keeps walking in his direction until he reaches the first unoccupied computer. After that, he sits behind it. If he doesn't find any computer he gets upset and gives up on the contest.\n\nThe madness of the $i$-th participant is the distance between his assigned computer ($a_i$) and the computer he ends up sitting behind. The distance between computers $i$ and $j$ is equal to $|i - j|$.\n\nThe values in the array $a$ \\textbf{can be} equal. There exist $n^m \\cdot 2^m$ possible pairs of arrays $(a, b)$.\n\nConsider all pairs of arrays $(a, b)$ such that no person becomes upset. For each of them let's calculate the sum of participants madnesses. Find the sum of all these values.\n\nYou will be given some prime modulo $p$. Find this sum by modulo $p$.",
    "tutorial": "Suppose $n = m$. Let $dp1_i$ be the number of $(A , B)$ pairs for $i$ participants and $i$ computers so that no one gets upset. For updating this array we can consider the last participant, and where he will sit. Suppose he sits behind the $j$-th computer. If he comes from left to right, there are $i$ choices of computers for him to sit behind, and if he comes from right to left there are $n - i + 1$ choices for him. If the last participant sits behind the $j$-th computer there are $dp1_{j-1} \\cdot dp1_{i-j}$ ${i-1}\\choose{j-1}$ ways to fill in the rest of the seats because after removing we have two independent subsegments. So $dp1_i = (i+1) \\sum_{j=1}^{i} dp1_{j-1} \\cdot dp1_{i-j}$ ${i-1}\\choose{j-1}$. Now let $dp2_i$ be the sum of the total madnesses for all cases with $i$ participants and $i$ computers. Imagine the last person sitting on the $j$-th computer. The madness of every participant except the last one is $(i+1) \\cdot (dp2_{j-1} \\cdot dp1_{i-j} + dp2_{i-j} \\cdot dp1_{j-1})$ ${i-1}\\choose{j-1}$. However, the madness of the last participant is $($ ${j-1}\\choose{2}$ $+$ ${i-j}\\choose{2}$ $) \\cdot dp1_{j-1}\\cdot dp1_{i-j}$ ${i-1}\\choose{j-1}$. Now what if $n > m$? Suppose $dp3_{i ,j}$ is the number of $(A , B)$ pairs for $i$ computers and $j$ participants so that no one gets upset. For updating it we can consider the maximal suffix that all of the computers in that suffix will get occupied by participants. Consider its lenghth is $l$ . If $l = 0$ then we add $dp3_{i-1,j}$ to $dp3_{i,j}$; if not, we add $dp1_l \\cdot dp3_{i-l-1,j-l}$ ${j}\\choose{l}$ to $dp3_{i, j}$. The update is similar to $dp1$. The update is done correctly because the subsegments are independant. At last, suppose $dp4_{i, j}$ is the sum of the total madnesses for all cases with $i$ computers and $j$ participants. Consider $l$ to be the lenghth of the maximal suffix that all of the computers in that suffix will get occupied by participants. If $l = 0$ then to $dp4_{i, j}$ we add $dp4_{i - 1, j}$. If $l > 0$ then $(dp4_{i-1-l, j-l} \\cdot dp1_l + dp3_{i-1-l,j-l} \\cdot dp2_l)$ ${j}\\choose{l}$ is added to $dp4_{i, j}$. The answer shall be $dp4_{n, m}$. Time complexity: $O(n^3)$. Computing $dp1$ and $dp2$ is an $O(n^2)$ task, while computing $dp3$ and $dp4$ has a complexity of $O(n^3)$. Challenge: Can you find a solution with a better time complexity?",
    "code": "// And you curse yourself for things you never done\n// Shayan.P  2020-08-29\n\n#include<bits/stdc++.h>\n\n#define F first\n#define S second\n#define PB push_back\n#define sz(s) int((s).size())\n#define bit(n,k) (((n)>>(k))&1)\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int,int> pii;\n\nconst int maxn = 510, inf = 1e9 + 10, mod=1e9+7;\n\nll n, m;\n\nll Pow(ll a, ll b){\n    b = (b + (mod-1)) % (mod-1); // to handle b == -1\n    int ans=1;\n    for(; b; b>>=1, a=a*a%mod) if (b&1) ans=ans*a%mod;\n    return ans;\n}\ninline void add(ll &a, ll b){\n    a = (a + b) % mod;\n}\n    \nll fac[maxn], ifac[maxn];\n\nll C(ll n, ll k){\n\tif (n<k || k<0) return 0;\n\treturn fac[n]*ifac[k]%mod*ifac[n-k]%mod;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie();\n    \n    fac[0] = 1;\n    for(int i = 1; i < maxn; i++) fac[i]=fac[i-1]*i%mod;\n    ifac[maxn-1] = Pow(fac[maxn-1], mod-2);\n    for(int i = maxn-2; i >= 0; i--) ifac[i]=ifac[i+1]*(i+1)%mod;\n    \n    cin >> n >> m;\n    ++n; //!\n    \n\tint ans = 0;\n    for(ll bef = 0; bef < m; bef++){\n\t\tfor(ll w = 1; w + bef < m; w++){ // corner case : bef == 0\n\t\t\tll cnt1=Pow(w+1, w-1)*Pow(2, w)%mod;\n\t\t\tll cnt2=Pow(n-w-1, bef-1)*Pow(2, bef)%mod*(n-w-1-bef)%mod;\n\t\t\tll cnt=cnt1*cnt2%mod*C(w+bef, bef)%mod;\n\t\t\tll score=w*(w+1)%mod*n%mod;\n\t\t\tll after=Pow(n, m-bef-w-1)*Pow(2, m-bef-w-1) % mod;\n\t\t\tans=(ans + cnt*score%mod*after) % mod;\n\t\t}\n    }    \n    cout << 1ll * (n-m) * ans % mod * Pow(n, -1) % mod << \"\\n\";\n    return 0;\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "fft"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1439",
    "index": "E",
    "title": "Cheat and Win",
    "statement": "Let's consider a $(10^9+1) \\times (10^9+1)$ field. The rows are numbered with integers from $0$ to $10^9$ and the columns are numbered with integers from $0$ to $10^9$. Let's define as $(x, y)$ the cell located in the $x$-th row and $y$-th column.\n\nLet's call a cell $(x, y)$ good if $x \\& y = 0$, there $\\&$ is the bitwise and operation.\n\nLet's build a graph where vertices will be all good cells of the field and we will make an edge between all pairs of adjacent by side good cells. It can be proved that this graph will be a tree — connected graph without cycles. Let's hang this tree on vertex $(0, 0)$, so we will have a rooted tree with root $(0, 0)$.\n\nTwo players will play the game. Initially, some good cells are black and others are white. Each player on his turn chooses a black good cell and a subset of its ancestors (possibly empty) and inverts their colors (from white to black and vice versa). The player who can't move (because all good cells are white) loses. It can be proved that the game is always finite.\n\nInitially, all cells are white. You are given $m$ pairs of cells. For each pair color all cells in a simple path between them as black. Note that we do not invert their colors, we paint them black.\n\nSohrab and Mashtali are going to play this game. Sohrab is the first player and Mashtali is the second.\n\nMashtali wants to win and decided to cheat. He can make the following operation multiple times before the game starts: choose a cell and invert colors of all vertices on the path between it and the root of the tree.\n\nMammad who was watching them wondered: \"what is the minimum number of operations Mashtali should do to have a winning strategy?\".\n\nFind the answer to this question for the initial painting of the tree. It can be proved that at least one possible way to cheat always exists.",
    "tutorial": "First let's solve the problem on arbitrary trees. Consider the following game: on some vertices of the tree we have some tokens. At each step you remove a token from some vertex and put a token in any subset of its ancestors. The first game can be transformed to this one by putting a token in each black vertex. So now we'll solve the new game. Obviously the game is independent for different tokens, so we can use Grundy numbers. After working around some examples you can find that the Grundy number for a vertex at height $h$ is $2^h$. it can be easily proved by induction since any number less than it can be built by exactly one subset of it's ancestors. Consider the binary representation of the grundy for the game(let it be S). Each cheating move means reversing the bits of a prefix of S. So the minimum number of operations needed can be shown as $T = (S[0] \\oplus S[1]) + (S[1] \\oplus S[2]) + ...$ Since each operation decreases this expression at most once, we will need at least $T$ operations, and there is an obvious way to make $S$ equal zero with that number of operations. Now to solve the original problem, we need to find a compressed tree of the marked vertices and then represent the black vertices as union of $O(m)$ paths from the root. After this we can finally calculate the compressed form of the total Grundy number and find the answer. For compressing the tree we need to do some operations, like sorting the vertices by starting time(dfs order), finding the LCA of 2 vertices, etc. in $O(H)$ time, where $H = log(10^9)$. How to do these? Well they can be done with the following observation (the details are left for the reader but they can be found in the model solution): For some $h$, consider the tree on these 3 set of cells: $T1: 0 \\leq x < 2^h, 0 \\leq y < 2^h$ $T2: 0 \\leq x < 2^h, 2^h \\leq y < 2^{h+1}$ $T3: 2^h \\leq x < 2^{h+1}, 0 \\leq y < 2^h$ One can see (and can prove) that these 3 trees are similar; so this gives us some recursive approach. Time complexity: $O(mH)$, where $H = log(10^9)$.",
    "code": "#include <bits/stdc++.h>\n#pragma GCC optimize (\"O2,unroll-loops\")\n//#pragma GCC optimize(\"no-stack-protector,fast-math\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<pii, int> piii;\ntypedef pair<ll, ll> pll;\n#define debug(x) cerr<<#x<<'='<<(x)<<endl;\n#define debugp(x) cerr<<#x<<\"= {\"<<(x.first)<<\", \"<<(x.second)<<\"}\"<<endl;\n#define debug2(x, y) cerr<<\"{\"<<#x<<\", \"<<#y<<\"} = {\"<<(x)<<\", \"<<(y)<<\"}\"<<endl;\n#define debugv(v) {cerr<<#v<<\" : \";for (auto x:v) cerr<<x<<' ';cerr<<endl;}\n#define all(x) x.begin(), x.end()\n#define pb push_back\n#define kill(x) return cout<<x<<'\\n', 0;\n\nconst ld eps=1e-7;\nconst int inf=1000000010;\nconst ll INF=10000000000000010LL;\nconst int mod=1000000007;\nconst int MAXN=400010, LOG=30;\n\nint n, m, k, u, v, x, y, t, a, b, root, ans;\npii A[MAXN], V[MAXN];\nint par[MAXN], sum[MAXN];\nbool is[MAXN];\nvector<int> G[MAXN], grundy;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\ninline int GetH(pii p){ return p.first+p.second;}\ninline pii GetPar(pii p, int k){\n\tint x=p.first, y=p.second;\n\twhile (k){\n\t\tint xx=(x&-x), yy=(y&-y);\n\t\tif (!xx) xx=2*inf;\n\t\tif (!yy) yy=2*inf;\n\t\tint tmp=min(k, min(xx, yy));\n\t\tk-=tmp;\n\t\tif (xx<yy) x-=tmp;\n\t\telse y-=tmp;\n\t}\n\treturn {x, y};\n}\ninline int Zone(pii p, int n){\n    if (p.first&(1<<(n-1))) return 2;\n    if (p.second&(1<<(n-1))) return 1;\n    return 0;\n}\nvoid dfs_order(vector<pii> &vec, int n=LOG) {\n\tif (n==0 || vec.size()==0) return ;\n\tvector<pii> v[3];\n\tfor (pii p:vec) {\n\t\tint z=Zone(p, n);\n\t\tp.first&=(1<<(n-1))-1;\n\t\tp.second&=(1<<(n-1))-1;\n\t\tv[z].pb(p);\n    }\n\tvec.clear();\n\tfor (int i:{0, 1, 2}) dfs_order(v[i], n-1);\n\tfor (pii p:v[0]) if (!p.first) vec.pb(p);\n    for (pii p:v[1]) vec.pb({p.first, p.second|(1<<(n-1))});\n    for (pii p:v[0]) if (p.first) vec.pb(p);\n    for (pii p:v[2]) vec.pb({p.first|(1<<(n-1)), p.second});\n}\npii Lca(pii u, pii v, int n=LOG) {\n\tif (n==0) return {0, 0};\n\tint zu = Zone(u, n), zv = Zone(v, n);\n\tif (zu > zv) swap(u, v), swap(zu, zv);\n\tu.first&=(1<<(n-1))-1;\n\tu.second&=(1<<(n-1))-1;\n\tv.first&=(1<<(n-1))-1;\n\tv.second&=(1<<(n-1))-1;\n\tif (zu == 1 && zv == 2) return {0, 0};\n\tif (zu == 2 && zv == 2){\n\t\tpii A = Lca(u, v, n-1);\n\t\treturn {A.first+(1<<(n-1)), A.second};\n\t}\n\tif (zu == 1 && zv == 1) {\n\t\tpii A = Lca(u, v, n-1);\n\t\treturn {A.first, A.second+(1<<(n-1))};\n\t}\n\tif (zv == 1) return Lca(u, {0, (1<<(n-1))-1}, n-1);\n\tif (zv == 2) return Lca(u, {(1<<(n-1))-1, 0}, n-1);\n\treturn Lca(u, v, n-1);\n}\ninline int GetId(pii p){\n\treturn lower_bound(V, V+n, p)-V;\n}\ninline bool IsPar(pii u, pii v){\n\tif (GetH(u)>GetH(v)) return 0;\n\treturn GetPar(v, GetH(v)-GetH(u))==u;\n}\nint dfs(int node){\n\tfor (int v:G[node]) sum[node]+=dfs(v);\n\treturn sum[node];\n}\n\nint main(){\n\tios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\tvector<pii> vec;\n\tcin>>m;\n\tfor (int i=0; i<2*m; i++) cin>>A[i].first>>A[i].second, vec.pb(A[i]);\n\tsort(all(vec));\n\tvec.resize(unique(all(vec))-vec.begin());\n\tdfs_order(vec);\n\tfor (int i=vec.size()-1; i; i--) vec.pb(Lca(vec[i], vec[i-1]));\n\tsort(all(vec));\n\tvec.resize(unique(all(vec))-vec.begin());\n\tdfs_order(vec);\n\tn=vec.size();\n\t\n\tdebug(\"sorted\")\n\t\n\tfor (int i=0; i<n; i++) V[i]=vec[i];\n\tsort(V, V+n);\n\tvector<int> stk={root=GetId(vec[0])};\n\tfor (int i=1; i<n; i++){\n\t\tint v=GetId(vec[i]);\n\t\twhile (!IsPar(V[stk.back()], V[v])) stk.pop_back();\n\t\tpar[v]=stk.back();\n\t\tG[stk.back()].pb(v);\n\t\tstk.pb(v);\t\t\n\t}\n\t\n\tfor (int i=0; i<2*m; i+=2){\n\t\tint u=GetId(A[i]), v=GetId(A[i+1]), lca=GetId(Lca(A[i], A[i+1]));\n\t\tsum[u]++;\n\t\tsum[v]++;\n\t\tsum[lca]-=2;\n\t\tis[lca]=1;\n\t}\n\tdfs(root);\n\tfor (int v=0; v<n; v++){\n\t\tif (sum[v]){\n\t\t\tgrundy.pb(GetH(V[par[v]])+1);\n\t\t\tgrundy.pb(GetH(V[v])+1);\n\t\t}\n\t\telse if (is[v]){\n\t\t\tgrundy.pb(GetH(V[v]));\n\t\t\tgrundy.pb(GetH(V[v])+1);\n\t\t}\n\t}\n\tsort(all(grundy));\n\tvec.clear();\n\tint last=-1;\n\tfor (int x:grundy){\n\t\tif (last==-1){\n\t\t\tif (vec.empty() || vec.back().second<x) last=x;\n\t\t\telse{\n\t\t\t\tlast=vec.back().first;\n\t\t\t\tvec.pop_back();\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tif (last<x) vec.pb({last, x});\n\t\t\tlast=-1;\n\t\t}\n\t}\n\tans=2*vec.size();\n\tif (ans && vec[0].first==0) ans--;\n\tcout<<ans<<\"\\n\";\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "games",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1440",
    "index": "A",
    "title": "Buy the String",
    "statement": "You are given four integers $n$, $c_0$, $c_1$ and $h$ and a binary string $s$ of length $n$.\n\nA binary string is a string consisting of characters $0$ and $1$.\n\nYou can change any character of the string $s$ (the string should be still binary after the change). You should pay $h$ coins for each change.\n\nAfter some changes (possibly zero) you want to buy the string. To buy the string you should buy all its characters. To buy the character $0$ you should pay $c_0$ coins, to buy the character $1$ you should pay $c_1$ coins.\n\nFind the minimum number of coins needed to buy the string.",
    "tutorial": "We will consider each character seperately. Look at the $i$-th character; if it is originally a $1$, we can either change it to a $0$ and pay $h + c_0$ coins for this specific character, or we can not change it and pay $c_1$ coins for it. Since we want to pay as little as possible, we take the minimum of these two. So if the $i$th character is a $1$, we will have to pay $min(c_1, h + c_0)$ coins for it. A similar logic can be used for the zeroes; if the $i$th character is a $0$ we will have to pay $min(c_0, h + c_1)$ coins. So we iterate over $s$, and for each character we add the required minimum to the sum, depending on whether it's a $0$ or $1$. Time complexity: $O(n)$",
    "code": "//                                In The Name Of Allah\n#include <bits/stdc++.h>\n#define\tss second\n#define ff first\n#define use_fast ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)\n#define ret(n) return cout << n, 0\n#define se(n) cout << setprecision(n) << fixed\n#define pb push_back\n#define ll long long\n#define ld long double\n//#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops\")\n//#pragma GCC optimize(\"no-stack-protector,fast-math\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\nusing namespace std; \n\nconst int N = 3e5 + 100, OO = 1e9 + 7, T = 50, M = 1e9 + 7, P = 6151, SQ = 280, lg = 20;\ntypedef pair <int, int> pii;\n\nvoid solve() {\n\tint n, c0, c1, t;\n\tstring s;\n\tcin >> n >> c0 >> c1 >> t >> s;\n\tint ans = 0;\n\tfor(auto u : s) {\n\t\tif(u == '0') \n\t\t\tans += min(c0, c1 + t);\n\t\telse \n\t\t\tans += min(c1, c0 + t);\n\t}\n\tcout << ans << endl;\n}\n\nint32_t main() {\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1440",
    "index": "B",
    "title": "Sum of Medians",
    "statement": "A median of an array of integers of length $n$ is the number standing on the $\\lceil {\\frac{n}{2}} \\rceil$ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with $1$. For example, a median of the array $[2, 6, 4, 1, 3, 5]$ is equal to $3$. \\textbf{There exist some other definitions of the median, but in this problem, we will use the described one.}\n\nGiven two integers $n$ and $k$ and \\textbf{non-decreasing} array of $nk$ integers. Divide all numbers into $k$ arrays of size $n$, such that each number belongs to \\textbf{exactly} one array.\n\nYou want the sum of medians of all $k$ arrays to be the maximum possible. Find this maximum possible sum.",
    "tutorial": "We will consider a greedy approach. We take the $\\lceil {\\frac{n}{2}} \\rceil$ biggest numbers from the end of the array and the $\\lfloor {\\frac{n}{2}} \\rfloor$ smallest numbers from the beginning. We take these elements as one group, erase them from our array and then continue the same procedure on the remaining array. This can be done in a loop of $O(k)$, by taking every $\\lceil {\\frac{n}{2}} \\rceil$th character. We can also prove this claim. Imagine we have marked $k$ elements to be the medians of these arrays. Each one of these elements need at least $\\lceil {\\frac{n}{2}} \\rceil - 1$ elements bigger than them and at least $\\lfloor {\\frac{n}{2}} \\rfloor$ elements smaller than them to form a group in which it they are the median. So we can always push the biggest of these $k$ numbers forward until we have exactly $\\lceil {\\frac{n}{2}} \\rceil - 1$ elements bigger than them, and by pushing forward the sum of medians either doesn't change or gets larger. So our algorithm will always give the biggest possible answer. Time complexity: $O(nk)$ for each testcase",
    "code": "#include <bits/stdc++.h>\ntypedef long long int ll;\ntypedef long double ld;\n#define pb push_back\n#define pii pair < int , int >\n#define F first\n#define S second\n#define endl '\\n'\n#define int long long\n#define sync ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)\n#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops,fast-math\")\n#define kill(x) return cout<<x<<'\\n', 0;\nusing namespace std;\nconst int N=2e5+100;\nll a[N];\nint Main(){\n    ll n, k;\n    cin >> k >> n;\n    for (int i=1;i<=n*k;i++){\n        cin >> a[i];\n    }\n    ll x=(k+1)/2 - 1;\n    x = k - x;\n    ll z=n*k+1;\n    ll ans=0;\n    while(n--){\n        z-=x;\n        if (z<=0) break;\n        ans+=a[z];\n    }\n    cout << ans << endl;\n}\nint32_t main(){\n    ll t;\n    cin >> t;\n    while(t--){\n        Main();\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1442",
    "index": "A",
    "title": "Extreme Subtraction",
    "statement": "You are given an array $a$ of $n$ positive integers.\n\nYou can use the following operation as many times as you like: select any integer $1 \\le k \\le n$ and do one of two things:\n\n- decrement by one $k$ of the first elements of the array.\n- decrement by one $k$ of the last elements of the array.\n\nFor example, if $n=5$ and $a=[3,2,2,1,4]$, then you can apply one of the following operations to it (not all possible options are listed below):\n\n- decrement from the first two elements of the array. After this operation $a=[2, 1, 2, 1, 4]$;\n- decrement from the last three elements of the array. After this operation $a=[3, 2, 1, 0, 3]$;\n- decrement from the first five elements of the array. After this operation $a=[2, 1, 1, 0, 3]$;\n\nDetermine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations.",
    "tutorial": "The problem sounds like this - check that there are increasing and decreasing arrays, the element-wise sum of which is equal to the given array. This problem can be solved greedily. Let's maximize each element of the decreasing array (let's call this array $a$, and the increasing one $b$). Suppose initial array is $v$ and we have solved the problem on a prefix of length $i-1$. Then, for the element $a[i]$, $a[i] \\le a[i - 1]$ and $v[i] - a[i] \\ge b[i - 1]$ must be fulfilled. Rewriting the second inequality and combining with the first one, we get $a[i] \\le min(a[i - 1], v[i] - b[i - 1])$. It is clear that taking $a[i] = min(a[i - 1], v[i] - b[i - 1])$ is best by construction.",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1442",
    "index": "B",
    "title": "Identify the Operations",
    "statement": "We start with a permutation $a_1, a_2, \\ldots, a_n$ and with an empty array $b$. We apply the following operation $k$ times.\n\nOn the $i$-th iteration, we select an index $t_i$ ($1 \\le t_i \\le n-i+1$), remove $a_{t_i}$ from the array, and append one of the numbers $a_{t_i-1}$ or $a_{t_i+1}$ (if $t_i-1$ or $t_i+1$ are within the array bounds) to the right end of the array $b$. Then we move elements $a_{t_i+1}, \\ldots, a_n$ to the left in order to fill in the empty space.\n\nYou are given the initial permutation $a_1, a_2, \\ldots, a_n$ and the resulting array $b_1, b_2, \\ldots, b_k$. All elements of an array $b$ are \\textbf{distinct}. Calculate the number of possible sequences of indices $t_1, t_2, \\ldots, t_k$ modulo $998\\,244\\,353$.",
    "tutorial": "Consider element with index $i$ that has value $b_1$ in the array $a$ - $a_i$. There are three options: Both $a_{i-1}$ and $a_{i+1}$ are present in the array $b$. Then both of them should stay in the array $a$ after the first operation - we will write them down later on. However, $a_i$ can only be added to the array b while removing one of the neighbors. We have reached a contradiction, so the answer is 0. One of the numbers $a_{i-1}$, $a_{i+1}$ is present in the array $b$, another is not. Then we have to remove the one that is not present in $b$ and continue solving the problem. Neither $a_{i-1}$ nor $a_{i+1}$ is present in $b$. $a_i$ is not present in any other place in $b$ (because all number in $b$ are unique), and $a_{i-1}$, $a_i$ and $a_{i+1}$ are indistinguishable by the following operations. Let us then remove any one of them (say, left) and \"remove\" all remaining tags. In this case, we can multiply answer by 2 and continue solving the problem. Now we know that the answer is either 0 or a power of 2. To calculate the answer we only need to implement the above-mentioned algorithm. Let us store a set of available numbers in the array $a$, and a set of numbers that are yet to appear in the array $b$ to implement necessary checks. The solution will have $\\mathcal{O}(n \\log n)$ complexity (that can be optimized to $\\mathcal{O}(n)$ with help of arrays and double-linked lists, but it was not necessary for this particular problem).",
    "tags": [
      "combinatorics",
      "data structures",
      "dsu",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1442",
    "index": "C",
    "title": "Graph Transpositions",
    "statement": "You are given a directed graph of $n$ vertices and $m$ edges. Vertices are numbered from $1$ to $n$. There is a token in vertex $1$.\n\nThe following actions are allowed:\n\n- Token movement. To move the token from vertex $u$ to vertex $v$ if there is an edge $u \\to v$ in the graph. This action takes $1$ second.\n- Graph transposition. To transpose all the edges in the graph: replace each edge $u \\to v$ by an edge $v \\to u$. This action takes increasingly more time: $k$-th transposition takes $2^{k-1}$ seconds, i.e. the first transposition takes $1$ second, the second one takes $2$ seconds, the third one takes $4$ seconds, and so on.\n\nThe goal is to move the token from vertex $1$ to vertex $n$ in the shortest possible time. Print this time modulo $998\\,244\\,353$.",
    "tutorial": "Consider a sequence of actions that moves the token from vertex $1$ to vertex $n$. Let us say it has $A$ token movements and $B$ graph transpositions. This sequence takes $A + 2^{B} - 1$ seconds. Note that the optimal path does not visit any edge twice. That means we need to consider only paths with $A \\le m$. Consider another sequence consisting of $A'$ token movements and $B'$ graph transpositions. Let $lm = \\lceil\\log_2 m\\rceil$. Note the following. If $B < lm < B'$ then $A + 2^{B} - 1$ < $A' + 2^{B'} - 1$. This is true because the difference between $A$ and $A'$ does not exceed $m$ and $2^{B'} - 2^{B} > m$. This gives us the following: if there is any sequence of actions with $B < lm$ that moves the token from vertex $1$ to vertex $n$ then optimal path's $B$ is less than $lm$ too. Let us check this with the following algorithm, and if it is so, find the optimal sequence of actions. We can now build a new graph that consists of $lm$ copies of the original graph: Reverse all the edges in every even graph copy. For every vertex $u$ add new edge between $k$-th and $k+1$-th copies of vertex $u$ with weight $2^{k-1}$ for $k = 1 \\ldots lm - 1$. We can find optimal paths from the first copy of vertex $1$ to all the copies of vertex $n$ using Dijkstra algorithm. Shortest of these paths would correspond to the answer: movement along a copy of original edge denotes token movement; movement along a new edge denotes graph transposition. If the algorithm found no paths, then the sequence of actions that moves the token to from vertex 1 to vertex $n$ consists of at least $lm + 1$ transpositions. Note that if $lm < B < B'$ then $A + 2^{B} - 1$ < $A' + 2^{B'} - 1$. It means that all sequences of actions can be compared using ordered vector $(B, A)$ lexicographically. Let us build another graph consisting of $2$ copies of the original graph: Reverse all the edges in the second copy of the graph. Assign $(0, 1)$ to weights of all of these edges. For every vertex $u$ add two new edges between copies of $u$: from the first to the second copy and back. Weights of both edges is $(1, 0)$. Let us find optimal paths from the first copy of vertex $1$ to both copies of vertex $n$ using Dijkstra algorithm. Let $(B, A)$ be the length of the shortest one. New graph allows us to restore the optimal sequence of actions that moves the token from vertex $1$ to vertex $n$ that will take $A + 2^{B} - 1$ seconds.",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1442",
    "index": "D",
    "title": "Sum",
    "statement": "You are given $n$ \\textbf{non-decreasing} arrays of non-negative numbers.\n\nVasya repeats the following operation $k$ times:\n\n- Selects a non-empty array.\n- Puts the first element of the selected array in his pocket.\n- Removes the first element from the selected array.\n\nVasya wants to maximize the sum of the elements in his pocket.",
    "tutorial": "Straightforward dp solution, where $s(i, j)$ - max possible sum after $j$ operations on first $i$ arrays and transition in $O(k)$, has complexity of $O(nk^2)$ or precisely $O(k \\cdot min(nk, \\sum\\limits_{i=1}^n t_i))$ and doesn't fit into the time limit. Taking into account the fact that the arrays are sorted helps to optimize it. Consider the optimal solution. Let's denote as $x_i$ number of operations on $i$-th array. Let's call the array partially removed if we applied at least one operation to that array, but the array is not yet empty. Consider two partially removed arrays within the optimal solution and integers $p$ and $q$ where $0 < x_p < t_p$ and $0 < x_q < t_q$. Assume, without loss of generality, $a_{p, x_p+1} \\le a_{q, x_q+1}$. Let $y = min(x_p, t_q - x_q) \\ge 1$. If we replace $y$ operations on $p$-th array with $y$ operations on $q$-th array, total sum will increase by $\\sum\\limits_{i=1}^y a_{q, x_q + i} - \\sum\\limits_{i=1}^y a_{p, x_p + 1 - i} \\ge y \\cdot a_{q, x_q + 1} - y \\cdot a_{p, x_p + 1} \\ge 0$, but the number of partially removed arrays will lower by 1. We can repeat that substitution until we get a single partially removed array. Now we need to identify the single partially removed array in the final solution. Every other array can either all be Vasya's pocket, or remain as is. We can solve the knapsack problem with $(n-1)$ items, with array sizes as weights and sum of array's elements as value. For each $0 \\le w \\le k$ we need to find $g(w)$ - max possible total value of items with total weight $w$. The only remaining step is to brute force the size of prefix, Vasya removed from the single partially removed array and combine it with $g(w)$. Solving each knapsack problem independently results in $O(n^2k + \\sum\\limits_{i=1}^n t_i)$ complexity, but the similarities between the problems allows to optimize down to $O(kn\\log n)$ using divide and conquer approach. Let's split the items into two halves of approximately similar size. Before going in recursively into the first half we will relax dp values with each element of the second half (just like in usual knapsack problem) and undo the changes after. This way as soon as we reach the subset with just one piece we have already calculated dp for every other piece. Adding each piece into dp takes $O(\\log n)$, each relaxation takes $O(k)$, final complexity is $O(kn\\log n + \\sum\\limits_{i=1}^n t_i)$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1442",
    "index": "E",
    "title": "Black, White and Grey Tree",
    "statement": "You are given a tree with each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.\n\nWhat is the minimum number of removals necessary to remove all vertices from the tree?",
    "tutorial": "Let's solve the task step by step: Suppose that tree is a bamboo without the grey vertices. Such a tree can be viewed as an array of colors $1$ and $2$. We can see that if there are two adjacent vertices of equal color, we can always delete them together in one operation. We can merge adjacent vertices of the same color, and get an array of colors $b_1, b_2, \\ldots, b_k$, such that $b_i \\in \\{1, 2\\}; b_i \\ne b_{i+1}$. Such an array can be defined by two numbers - $b_1, k$.We can see that such an array $b$ of length $k$ can not be deleted in less than $\\lfloor {k \\over 2} \\rfloor + 1$ removals. It can be proved by induction. Also, you can delete all elements in this number of removals by deleting opposite leaves (after the first removal opposite leaves will have the same color). We can see that such an array $b$ of length $k$ can not be deleted in less than $\\lfloor {k \\over 2} \\rfloor + 1$ removals. It can be proved by induction. Also, you can delete all elements in this number of removals by deleting opposite leaves (after the first removal opposite leaves will have the same color). Let's solve the task for a general tree without grey vertices. Let's assign the edge $uv$ with weight $0$ if $a_u=a_v$, and $1$ otherwise. Let's find the longest path (diameter) in this weighted tree, and let it be the vertices $v_1, v_2, \\ldots, v_m$. We can see this path as bamboo from the previous paragraph, and find the corresponding value $k$ for this path (it is equal to diameter + 1). It is obvious that we can't delete the tree in less than $\\lfloor {k \\over 2} \\rfloor + 1$ removals (otherwise we would be able to delete the bamboo in a smaller number of removals). Turns out that we can delete all vertices in this number of removals. We can do the same algorithm - let's delete the opposite leaves of diameter, and also let's delete all leaves in the tree that have the same color (why not). After one such removal, our path will still be a diameter (if another path becomes the diameter, then one of its leaves should have the same color, and was going to be deleted). We can find the diameter in such a 0/1 tree in linear time, or we can solve the task even simpler. We can see that we alternate the removal of black and white vertices, and we delete all the leaves with the same color. So, we can choose the first operation (delete black or white), and at each iteration just delete all corresponding leaves. It works in linear time. Turns out that we can delete all vertices in this number of removals. We can do the same algorithm - let's delete the opposite leaves of diameter, and also let's delete all leaves in the tree that have the same color (why not). After one such removal, our path will still be a diameter (if another path becomes the diameter, then one of its leaves should have the same color, and was going to be deleted). We can find the diameter in such a 0/1 tree in linear time, or we can solve the task even simpler. We can see that we alternate the removal of black and white vertices, and we delete all the leaves with the same color. So, we can choose the first operation (delete black or white), and at each iteration just delete all corresponding leaves. It works in linear time. Let's solve the task without additional constraints. Now there are the grey vertices. How do they change the solution? Let's see at the last removal - suppose we deleted vertex $v$, which was not grey. Then we can imagine that we make $v$ the root of the tree, and paint all the grey vertices in the color of their parents. Then we have a tree without grey vertices, which we can solve. Obviously, the answer for such a colored tree is not less than the answer for the initial tree (because we can make the same removals as in a colored tree). But we can see that we can't get the smaller answer, as by coloring grey vertices we effectively removed them from the tree, and the value $\\lfloor {k \\over 2} \\rfloor + 1$ (over subsequences of black and white vertices) hasn't changed. So, overall, the solution is to choose the first removal (1 or 2), and alternate removals of black and white vertices. For removal of $c \\in \\{ 1, 2 \\}$ we delete all the leaves with color $0$ or $c$. Also, we can note that the tree remains connected in this process.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1442",
    "index": "F",
    "title": "Differentiating Games",
    "statement": "This is an interactive problem\n\nGinny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam.\n\nAs known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called.\n\nFor the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices $S$ several times and ask the professor: \"If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset $S$, and then one more in the selected vertex, what would be the result of the combinatorial game?\".\n\nHaving given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear.",
    "tutorial": "Let's first solve the problem for an empty graph. To do this we need to build a construction with not too many edges, where all vertices are pairwise not equivalent. For acyclic graph, there is not such construction. All Grundy functions of vertices should be different, so they must be integers from 0 to $n-1$. The only such graph is full, and it has quadratic number of edges. Moreover, if there is a part from which no cycles are reachable, it must be full acyclic graph, so it can't be too big. So, how can other graph look? No vertices can be equivalent to any of vertices in acyclic part. The easiest way to achieve it is to add a loop to every vertex. Let's note, that after doing so all this vertices can't be losing in sum with any other game, because we can just go through loop and don't change anything. So, this games differ from each other be set of games in sum with which they would be winning, not draw. One can see, that such a game would be winning with any acyclic game, it have a move to, because we can go to it, and this will be move to acyclic game with Grundy function 0. The game would be draw with any other acyclic game (and with not acyclic too, but this is not important for solution). This is true, because if we don't move in game with loop, resulting position is not winning. Therefore, to win we must go out from loop vertex. But than we come into acyclic game with non-zero Grundy function, and it's winning, so we can't win. And we can go through loop, achieving a draw. So, we need to build a graph, with acyclic part of full graph on $k$ vertices, and all other vertices should have a loop and some edges to this $k$ vertices, and all vertices should have different set of edges. If done, all vertices would be pairwise distinguishable by $k$ queries for each acyclic part vertex. If any of them is lost, this vertex is chosen. If all of them is winning or draw, than the vertex with loop, which have an edge if and only if sum with this vertex is winning, is chosen. In opposite to acyclic case, we can distinguish exponentially many vertices. Returning to the initial problem, one can get $k = 20$, and get all subsets of size 0, 1 and 2, and required part of subsets of size $3$. In such a graph there would be $190 + 980 + 1 \\cdot 0 + 20 \\cdot 1 + 190 \\cdot 2 + 769 \\cdot 3 = 3877$ edges. The only remaining part is to understand what to do with existing edges. One can not, then in built construction any edges between vertices with loops can be added, because they change nothing. If position is winning, then after first move they become unreachable, and doesn't change anything. If it was draw, they can't change anything too, because they are led to vertex with loop, which can't be losing. Let's use 20 vertices, which have no edges outside of this set as vertices of acyclic part. Initial graph was acyclic, so we can find such vertices. Let's add loop to all other vertices. Now, we need to modify graph in a way that all sets of edges to acyclic part would be different. Let's go through vertices in any order, and change minimal possible number of edges, so, that this vertex set would not be equal to any of previous. For first vertex we won't do anything. For next 20 vertices, we would need to change at most 1 edge. For next 190 vertices, we would need to change at most 2 edges, and at most 3 for others. This led us to the same 3877 edges to change. In general case we can do either $O(nlogn)$ edges changes and $O(logn)$ queries or $O((d+1)*n)$ edges changes and $O(\\sqrt[d]{d!n})$ queries. For this problem we need d = 3.",
    "tags": [
      "games",
      "interactive"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1443",
    "index": "A",
    "title": "Kids Seating",
    "statement": "Today the kindergarten has a new group of $n$ kids who need to be seated at the dinner table. The chairs at the table are numbered from $1$ to $4n$. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers $a$ and $b$ ($a \\neq b$) will indulge if:\n\n- $gcd(a, b) = 1$ or,\n- $a$ divides $b$ or $b$ divides $a$.\n\n$gcd(a, b)$ — the maximum number $x$ such that $a$ is divisible by $x$ and $b$ is divisible by $x$.\n\nFor example, if $n=3$ and the kids sit on chairs with numbers $2$, $3$, $4$, then they will indulge since $4$ is divided by $2$ and $gcd(2, 3) = 1$. If kids sit on chairs with numbers $4$, $6$, $10$, then they will not indulge.\n\nThe teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no $2$ of the kid that can indulge. More formally, she wants no pair of chairs $a$ and $b$ that the kids occupy to fulfill the condition above.\n\nSince the teacher is very busy with the entertainment of the kids, she asked you to solve this problem.",
    "tutorial": "Note that this seating arrangement for children satisfies all conditions: $4n, 4n-2, 4n-4, \\ldots, 2n+2$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1443",
    "index": "B",
    "title": "Saving the City",
    "statement": "Bertown is a city with $n$ buildings in a straight line.\n\nThe city's security service discovered that some buildings were mined. A map was compiled, which is a string of length $n$, where the $i$-th character is \"1\" if there is a mine under the building number $i$ and \"0\" otherwise.\n\nBertown's best sapper knows how to activate mines so that the buildings above them are not damaged. When a mine under the building numbered $x$ is activated, it explodes and activates two adjacent mines under the buildings numbered $x-1$ and $x+1$ (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment. For manual activation of one mine, the sapper takes $a$ coins. He can repeat this operation as many times as you want.\n\nAlso, a sapper can place a mine under a building if it wasn't there. For such an operation, he takes $b$ coins. He can also repeat this operation as many times as you want.\n\nThe sapper can carry out operations in any order.\n\nYou want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city.",
    "tutorial": "Since the activation of any mine explodes the entire segment of mines, which it is, you can immediately replace the input string with an array of mine segments. We now have two operations. We can delete any segment by $a$ coins, or turn two adjacent segments $[l_1, r_1]$, $[l_2, r_2]$ ($r_1 < l_2$) into one segment for $b \\cdot (l_2-r_1)$. That is, two segments can be deleted for a cost of $2 \\cdot a$ or $a + b \\cdot (l_2-r_1)$. This means that you need to merge two segments while $b \\cdot (l_2-r_1) \\le a$. You need to go through all adjacent segments and check this condition.",
    "tags": [
      "dp",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1443",
    "index": "C",
    "title": "The Delivery Dilemma",
    "statement": "Petya is preparing for his birthday. He decided that there would be $n$ different dishes on the dinner table, numbered from $1$ to $n$. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.\n\nUnfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from $n$ different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it:\n\n- the dish will be delivered by a courier from the restaurant $i$, in this case the courier will arrive in $a_i$ minutes,\n- Petya goes to the restaurant $i$ on his own and picks up the dish, he will spend $b_i$ minutes on this.\n\nEach restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.\n\nFor example, if Petya wants to order $n = 4$ dishes and $a = [3, 7, 4, 5]$, and $b = [2, 1, 2, 4]$, then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in $3$ minutes, the courier of the fourth restaurant will bring the order in $5$ minutes, and Petya will pick up the remaining dishes in $1 + 2 = 3$ minutes. Thus, in $5$ minutes all the dishes will be at Petya's house.\n\nFind the minimum time after which all the dishes can be at Petya's home.",
    "tutorial": "If we order a courier with time $x$, then all couriers with time $y < x$ can also be ordered, since they do not change the answer (all couriers work in parallel). Therefore, you can sort the array, couriers always bring the prefix of the array, and Petya will go for the suffix. The time prefix is the maximum $b[i]$, and the suffix is the sum $a[i]$. Therefore, you need to calculate the suffix amounts and go through all the options.",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1443",
    "index": "E",
    "title": "Long Permutation",
    "statement": "A permutation is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$, $[3, 2, 1]$ — are permutations, and $[1, 1]$, $[4, 3, 1]$, $[2, 3, 4]$ — no.\n\nPermutation $a$ is lexicographically smaller than permutation $b$ (they have the same length $n$), if in the first index $i$ in which they differ, $a[i] < b[i]$. For example, the permutation $[1, 3, 2, 4]$ is lexicographically smaller than the permutation $[1, 3, 4, 2]$, because the first two elements are equal, and the third element in the first permutation is smaller than in the second.\n\nThe next permutation for a permutation $a$ of length $n$ — is the lexicographically smallest permutation $b$ of length $n$ that lexicographically larger than $a$. For example:\n\n- for permutation $[2, 1, 4, 3]$ the next permutation is $[2, 3, 1, 4]$;\n- for permutation $[1, 2, 3]$ the next permutation is $[1, 3, 2]$;\n- for permutation $[2, 1]$ next permutation does not exist.\n\nYou are given the number $n$ — the length of the initial permutation. The initial permutation has the form $a = [1, 2, \\ldots, n]$. In other words, $a[i] = i$ ($1 \\le i \\le n$).\n\nYou need to process $q$ queries of two types:\n\n- $1$ $l$ $r$: query for the sum of all elements on the segment $[l, r]$. More formally, you need to find $a[l] + a[l + 1] + \\ldots + a[r]$.\n- $2$ $x$: $x$ times replace the current permutation with the next permutation. For example, if $x=2$ and the current permutation has the form $[1, 3, 4, 2]$, then we should perform such a chain of replacements $[1, 3, 4, 2] \\rightarrow [1, 4, 2, 3] \\rightarrow [1, 4, 3, 2]$.\n\nFor each query of the $1$-st type output the required sum.",
    "tutorial": "Let's notice that most of the elements in the original permutation will not change during all queries. Since the maximum permutation number does not exceed $10^{10}$, only the last $15$ elements of the permutation will change. Thus, after each query of the second type, you need to generate a permutation with the corresponding number. To answer the query of the first type, you need to split the segment into two parts: we sum the part of the segment that fell in the last $15$ elements in a simple cycle and calculate the other part of the segment using the formula of an arithmetic progression.",
    "tags": [
      "brute force",
      "math",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1444",
    "index": "A",
    "title": "Division",
    "statement": "Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.\n\nTo improve his division skills, Oleg came up with $t$ pairs of integers $p_i$ and $q_i$ and for each pair decided to find the \\textbf{greatest} integer $x_i$, such that:\n\n- $p_i$ is divisible by $x_i$;\n- $x_i$ is not divisible by $q_i$.\n\nOleg is really good at division and managed to find all the answers quickly, how about you?",
    "tutorial": "Let $y = p / x$. Let's assume, that there exists prime $a$, such that $a$ divides $y$, but $q$ is not divisible by $a$. Then we can multiply $x$ and $a$ and the result will still divide $p$, but will not be divisible by $q$. So for maximal $x$ there is no such $a$. Let's assume, that there are two primes $a$ and $b$, such that they both divide $y$, and both divide $q$. Because $q$ is not divisible by $x$, there exists some prime $c$ ($c$ can be equal to $a$ or $b$), such that number of occurrences of $c$ in $x$ is less than number of occurrences of $c$ in $q$. One of $a$ and $b$ is not equal to $c$, so if we will multiply $x$ and such number, the result will not be divisible by $q$. So for maximal $x$ there are no such $a$ and $b$. That means that $x = p /$(power of some primal divisor of $q$). So to find maximal $x$, we have to find all prime divisors of $q$ (we have to factorise $q$ for it in time $O(\\sqrt{q})$) and for each of them divide $p$ by it until result is not divisible by $q$. That will be all our candidates for greatest $x$. We will do all of that in time $O(\\sqrt{q} + \\log q \\cdot \\log p)$.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1444",
    "index": "B",
    "title": "Divide and Sum",
    "statement": "You are given an array $a$ of length $2n$. Consider a partition of array $a$ into two subsequences $p$ and $q$ of length $n$ each (each element of array $a$ should be in exactly one subsequence: either in $p$ or in $q$).\n\nLet's sort $p$ in non-decreasing order, and $q$ in non-increasing order, we can denote the sorted versions by $x$ and $y$, respectively. Then the cost of a partition is defined as $f(p, q) = \\sum_{i = 1}^n |x_i - y_i|$.\n\nFind the sum of $f(p, q)$ over all correct partitions of array $a$. Since the answer might be too big, print its remainder modulo $998244353$.",
    "tutorial": "No matter how we split the array, the cost of a partition will always be the same. Let's prove it. Without loss of generality we will consider that the array $a$ sorted and denote for $L$ the set of elements with indexes from $1$ to $n$, and for $R$ the set of elements with indexes from $n + 1$ to $2n$. Then split the array $a$ into any two arrays $p$ and $q$ of size $n$. Let's sort $p$ in non-decreasing order and $q$ by non-increasing order. Any difference $|p_i - q_i|$ in our sum will be the difference of one element of $R$ and one element of $L$. If this is not the case, then there is an index $i$ such that both $p_i$ and $q_i$ belong to the same set. Let's assume that this is $L$. All elements with indexes less than or equal to $i$ in $p$ belong to $L$ ($i$ elements) All items with indexes greater than or equal to $i$ in $q$ belong to $L$ ($n - (i - 1)$ elements) Then $L$ has at least $i + n - (i-1) = n + 1$ elements, but there must be exactly $n$. Contradiction. For the set $R$ the proof is similar. Then the answer to the problem is (the sum of the elements of the set $R$ minus the sum of the elements of the set $L$) multiplied by the number of partitions of the array $C^{n}_{2n}$. Complexity: $O(n \\log n)$ (due to sorting)",
    "tags": [
      "combinatorics",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1444",
    "index": "C",
    "title": "Team-Building",
    "statement": "The new academic year has started, and Berland's university has $n$ first-year students. They are divided into $k$ academic groups, however, some of the groups might be empty. Among the students, there are $m$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.\n\nAlice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.\n\nAlice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.\n\nPlease note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty).",
    "tutorial": "You're given an undirected graph without loops and multiple edges, each vertex has some color from $1$ to $k$. Count the number of pairs of colors such that graph induced by vertices of these two colors will be bipartite. Let's check for each color whether the graph induced by it is bipartite (for example, using depth-first search). This can be done in $O(n + m)$. We will not use non-bipartite colors further since they can't be in any pairs. Now let's construct a slow solution that we will make faster later. Consider some color $x$. There're edges from vertices of this color to vertices of colors $y_1, y_2, \\ldots, y_k$. Let's check whether the graphs induced by pairs $(x, y_1), (x, y_2), \\ldots, (x, y_k)$ are bipartite (also using depth-first search), thereby finding out which colors cannot be in pair with $x$. The others can. After doing this for each color $x$, we can find the asnwer. How fast does this work? Notice that any edge between different colors we will use in DFS only two times. The problem are edges between vertices of the same color, we can use them up to $k$ times, and there can be a lot of them. Let's solve this problem and construct a faster solution. A graph is bipartite if and only if it doesn't contains odd cycles. Consider some connected bipartite component induced by color $x$. If a cycle goes through this component, it doesn't matter how exactly it does it. If the path of the cycle in this component ends in the same side where it has started, then it has even length, and odd otherwise. This fact lets us compress this component to two vertices (one for each side) connected by one edge. For each color this way we compress all components formed by it. Now we have the compressed graph, where all connected components are either one vertex or two vertices connected by one edge. Let's do the same process we did in slow solution and check every connected pair of colors whether the graph induced by it is bipartite. To check the pair $(x, y)$, for each edge between vertices of colors $x$ and $y$ in the original graph add a new edge to the compressed graph between corresponding vertices. After that use DFS to check if graph is bipartite, rollback the changes and do the same for all other pairs. How long does this work for one pair $(x, y)$? Let's start DFS only from components that were connected by added edges, since the others do not affect whether the graph is bipartite or not, but there can be a lot of them. This way DFS will use only added edges and some edges between vertices of the same color $x$ or $y$. However, there will be at most two times more of the latter than the added, because each added edge connects at most two new components, and each new component has at most one edge. So, we check one pair in the time proportional to amount of edges between its colors, and it sums up to $O(m)$ for all pairs. So, the whole solution works in $O(n + m)$ or $O(m \\log n)$, depending on the implementation.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1444",
    "index": "D",
    "title": "Rectangular Polyline",
    "statement": "One drew a closed polyline on a plane, that consisted only of vertical and horizontal segments (parallel to the coordinate axes). The segments alternated between horizontal and vertical ones (a horizontal segment was always followed by a vertical one, and vice versa). The polyline did not contain strict self-intersections, which means that in case any two segments shared a common point, that point was an endpoint for both of them (please consult the examples in the notes section).\n\nUnfortunately, the polyline was erased, and you only know the lengths of the horizonal and vertical segments. Please construct any polyline matching the description with such segments, or determine that it does not exist.",
    "tutorial": "First, note that in a correct polyline, since the horizontal and vertical segments alternate, $h=v$: if this equality does not hold, the answer is negative. Now let's fix a vertex and go around the polyline in some direction. Then in the process of traversin, we will move in one of four possible directions: up, down, right or left. Since the polyline is closed, this means that we will move to the left in total by the same distance as we will move to the left in total. The same is true for moving up and down. This means that if we split all the segments into four sets named $Up$, $Down$, $Left$, $Right$, then the total length of the segments in $Up$ will be equal to the total length of the segments in $Down$, and the total length of the segments in $Right$ will be equal to the total length of the segments in $Left$. But it means that the set of lengths of all horizontal segments can be divided into two sets with the same sum. The same should hold for vertical segments. Let's check whether it is possible to divide the set of lengths of horizontal segments into two sets of the same sum. This classic problem can be solved by applying the dynamic programming method to solve the backpack problem. The complexity of this solution will be $\\mathcal O\\left({nC^2}\\right)$ If it is impossible to split horizontal or vertical lengths into two sets of equal length, the answer is \"No\". Now we will show how to construct a correct answer if such divisions exist. Let us divide all horizontal lengths into two sets of equal total length. We denote the smaller set as $R$, and the larger set as $L$. We will do the same with the set of lengths of vertical segments: we will denote the smaller set as $D$, and the larger one as $U$. Since $|R| \\leq |L|$, $|R| \\leq h / 2 = v / 2$. Similarly, we have $v / 2 \\leq |U|$, which follows that $|R| \\leq |U/$, $|D| \\leq |L|$. Now let's divide all the segments into pairs as follows: each segment of $R$, we match with a segment from $U$. All remaining segments of $L$ are matched with one of the remaining vertical segments. Thus, we have divided all these segments into three sets of pairs: in the first one, a segment from $R$ is paired with a segment from $U$. In the second set a segment from $L$ is paired with a segment from $U$. In the third set a segment from $D$ is paired with a segment from $L$. From the first set of pairs, we make up the set of vectors directed up and to the right (from the pair (r, u), we construct the vector (r, u)). This way we can construct a set of vectors $A$. We will do the same with the second set of pairs (constructing a set of vectors $B$) and the third set of pairs (constructing a set of vectors $C$). for a better understanding, see the picture above. Note that the set $B$ may be empty, while the other two can not. Let's make a convex polyline from the vectors of $A$. In order to do this, sort them in ascending order by the polar angle and make a polyline from them in this order (see the picture below). Now we will replace each of the vectors of our polyline with two vectors: one vector directed to the right and one vector directed upwards. We will do the same for vectors from $C$: sort them in ascending order by the polar angle and make a convex polyline from them: Let's combine these two polylines so that the first one goes from the point $O$ to the point $A$ and the second one goes from the point $B$ to the point $O$: We don't have much left to do: we hate to connect the points $A$ and $B$ using vectors from the set $B$. Let's take these vectors (directed up and to the left) in any arbitrary order, then, since the sum of all vectors is 0, the resulting polyline, if you draw it with the beginning at the point $A$, will end at the point $B$. Since the first two polylines were convex, this means that none of the points of the first two polylines will lie strictly inside the angle $AOB$, which means that if you replace each of the vectors of the third polyline with two vectors, one directed to the left and one directed upwards, the resulting closed polyline will not contain self-intersections. It is easy to show that the resulting polyline will be closed and will satisfy all the conditions of the problem:",
    "tags": [
      "constructive algorithms",
      "dp",
      "geometry"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1444",
    "index": "E",
    "title": "Finding the Vertex",
    "statement": "\\textbf{This is an interactive problem.}\n\nYou are given a tree — connected undirected graph without cycles. One vertex of the tree is special, and you have to find which one. You can ask questions in the following form: given an edge of the tree, which endpoint is closer to the special vertex, meaning which endpoint's shortest path to the special vertex contains fewer edges. You have to find the special vertex by asking the minimum number of questions in the worst case for a given tree.\n\nPlease note that the special vertex might not be fixed by the interactor in advance: it might change the vertex to any other one, with the requirement of being consistent with the previously given answers.",
    "tutorial": "Consider the optimal strategy. Some edge will be your first query, mark it with a number $0$. After that, build similar colourings (recursively) for components on both sides of the edge, but increase their weights by one (to have only one zero in total). This colouring corresponds to the strategy, and if $k$ is the maximum weight of an edge in it, then this strategy can find a vertex in $k+1$ queries in the worst case. This colouring has a wonderful property that helps us identify the vertex: on a path between any two edges with the same colour an edge with the smaller colour presents. And any colouring with this property corresponds to a proper strategy! (Each time you can ask an edge with the smallest weight in the current component) To make it easier for us, \"invert\" all weights in the colouring, mark the first edge with the weight $k-1$, and then use the same construction as we had before for our colouring, but now subtract $1$ from the edges (weights should remain non-negative). Now our goal is to find colouring with the min weight of the max edge, such that each pair of edges with the same colours have an edge with the larger colour between them. We will build this colouring using subtree DP. For the fixed colouring of a subtree of the vertex $v$, let's see which colours are visibile if you will look from $v$ towards the subtree. The colour is visible, if there is such an edge of this colour, that there are no edges with the larger colour on a path from this edge to $v$. Potential function of our colouring is the sum $2^{c_1} + 2^{c_2} + \\ldots + 2^{c_k}$, where $c_i$ are visible colours. Note that this value is a long number! Because our answer can be large. Lemma: we are interested only in the colouring of our subtree with the smallest potential. Assume that all subtrees of vertex $v$ are already coloured into colourings with the smallest potentials. Then we have to choose some weights of edges outgoing from $v$, such that after adding these edges to $v$, different subtrees won't have common visible colours (otherwise you will get a bad pair of edges of the same colour). You can color an edge from vertex $v$ to its child $u$ in a colour $c$, if a colour $c$ is not visible from $u$. After that, all weights smaller than $c$ will disappear from the set of visible colours, but the colour $c$ will be added. You have to change colourings of the subtrees in this way, to not have carries during the addition of the potentials (it will correspond to the situation without common visible colours). Under this constraint, we have to minimize the total sum, the potential of $v$. From this setting, the proof of the previous lemma is clear: for larger values of the potential, possible choices are not better. You have to solve a problem: you are given an array $a_1, a_2, \\ldots, a_k$ of long binary numbers. You have to find an array with the smallest sum $b_1, b_2, \\ldots, b_k$, such that $b_i > a_i$, and no carries will happen during the addition $b_1 + b_2 + \\ldots + b_k$. You can solve this problem with a quite simple greedy algorithm: we will set bits greedily from left to right, and check that we can finish our goal with the fixed prefix. To check that you can get some answer with the fixed prefix of bits and the upper bound on the used bits, you can go from left to right and each time when you have to replace some number to the current bit, replace the number with the largest suffix. You can implement it in a naive way in $\\mathcal{O}{(n^3)}$, but it also can be implemented in $\\mathcal{O}{(n \\log n)}$. You have to solve this subtask $n$ times, and we will get the solution with complexity $\\mathcal{O}{(n \\cdot T(n))} = \\mathcal{O}{(n^2 \\log n \\ldots n^4)}$.",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "interactive",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1445",
    "index": "A",
    "title": "Array Rearrangment",
    "statement": "You are given two arrays $a$ and $b$, each consisting of $n$ positive integers, and an integer $x$. Please determine if one can rearrange the elements of $b$ so that $a_i + b_i \\leq x$ holds for each $i$ ($1 \\le i \\le n$).",
    "tutorial": "It's enough to sort $a$ in non-decreasing order and sort $b$ in non-increasing order and check, whether $a_i + b_i \\leq x$ for all $i$. Correctness can be proven by induction: let's show that if answer exists, there is a solution with minimum in $a$ and maximum in $b$ are paired. Let $m_a$ be minimum in $a$ and $m_b$ be maximum in $b$. Let $p$ be number paired with $m_a$ and $q$ be number paired with $m_b$. Since solution is correct, $m_a + p \\leq x$ and $m_b + q \\leq x$. Since $m_a \\leq q$, $m_a + m_b \\leq x$. Since $p \\leq m_b$, $p + q \\leq x$. So, $m_a$ can be paired with $m_b$.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1445",
    "index": "B",
    "title": "Elimination",
    "statement": "There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.\n\nA result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately.\n\nIn each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct).\n\nIn the first contest, the participant on the 100-th place scored $a$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $b$ points in the second contest.\n\nSimilarly, for the second contest, the participant on the 100-th place has $c$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $d$ points in the first contest.\n\nAfter two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The \\textbf{cutoff score} to qualify to the final stage is the total score of the participant on the 100-th place.\n\nGiven integers $a$, $b$, $c$, $d$, please help the jury determine the smallest possible value of the cutoff score.",
    "tutorial": "The answer is at least $\\max(a + b, d + c)$ because we have at least $100$ participants with the sum of $a + b$ and at least $100$ participants with the sum of $d + c$. If we have $99$ participants with points equal to $(a, c)$, and $2$ participants with points equal to $(a, b)$ and $(d, c)$, then the 100th participant will have a total of $\\max(a + b, d + c)$ points, and the condition will be met, because $a \\ge d$, $c \\ge b$ and $a + c \\ge \\max(a + b, d + c)$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1446",
    "index": "A",
    "title": "Knapsack",
    "statement": "You have a knapsack with the capacity of $W$. There are also $n$ items, the $i$-th one has weight $w_i$.\n\nYou want to put some of these items into the knapsack in such a way that their total weight $C$ is at least half of its size, but (obviously) does not exceed it. Formally, $C$ should satisfy: $\\lceil \\frac{W}{2}\\rceil \\le C \\le W$.\n\nOutput the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible.\n\nIf there are several possible lists of items satisfying the conditions, you can output any. Note that you \\textbf{don't} have to maximize the sum of weights of items in the knapsack.",
    "tutorial": "Are there any items which you can put in the knapsack to fulfill the goal with one item? What happens if there are none? If there is an item of size $C$ satisfying: $\\lceil \\frac{W}{2}\\rceil \\le C \\le W$, it is enough to output only that item. Otherwise, we should exclude items which are larger than the size of the knapsack and take a closer look at the situation. Consider greedily adding items in any order until we find a valid solution or run out of items. This is correct because all items have sizes less than $\\frac{W}{2}$, so it is not possible to exceed knapsack size by adding one item in a situation where the sum of items $C$ doesn't satisfy constraint $\\lceil \\frac{W}{2}\\rceil \\le C \\le W$. This gives us a solution in $O(n)$. From the analysis above, we can also conclude that greedily adding the items from largest to smallest if they still fit in the knapsack will always find a solution if one exists. This gives us a solution in $O(n log n)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1446",
    "index": "B",
    "title": "Catching Cheaters",
    "statement": "You are given two strings $A$ and $B$ representing essays of two students who are suspected cheaters. For any two strings $C$, $D$ we define their similarity score $S(C,D)$ as $4\\cdot LCS(C,D) - |C| - |D|$, where $LCS(C,D)$ denotes the length of the Longest Common \\textbf{Subsequence} of strings $C$ and $D$.\n\nYou believe that only some part of the essays could have been copied, therefore you're interested in their \\textbf{substrings}.\n\nCalculate the maximal similarity score over all pairs of substrings. More formally, output maximal $S(C, D)$ over all pairs $(C, D)$, where $C$ is some substring of $A$, and $D$ is some substring of $B$.\n\nIf $X$ is a string, $|X|$ denotes its length.\n\nA string $a$ is a \\textbf{substring} of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nA string $a$ is a \\textbf{subsequence} of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.\n\nPay attention to the difference between the \\textbf{substring} and \\textbf{subsequence}, as they both appear in the problem statement.\n\nYou may wish to read the Wikipedia page about the Longest Common Subsequence problem.",
    "tutorial": "This is a dynamic programming problem. Recall the DP calculating the Longest Common Substring for two strings. What similarities are there in our setup, and what differs? If a substring has a negative score, we can throw it away and start from scratch. Let $DP[i][j]$ be the maximum similarity score if we end the first substring with $A_i$ and the second substring with $B_j$. We will also allow the corresponding most similar string to be empty so that $DP[i][j]$ is always at least $0$. It turns out that the fact we need to search for substrings of our words is not a big problem, because we can think of extending the previous ones. In fact, we have just two possibilities: $A_i$ and $B_j$ are the same letters. In this case, we say that $DP[i][j] = min(DP[i][j], DP[i-1][j-1] + 2)$ as the new letter will increase the LCS by $1$, but both of the strings increase by one in length, so the total gain is $4-1-1=2$. $A_i$ and $B_j$ are the same letters. In this case, we say that $DP[i][j] = min(DP[i][j], DP[i-1][j-1] + 2)$ as the new letter will increase the LCS by $1$, but both of the strings increase by one in length, so the total gain is $4-1-1=2$. In every case, we can refer to $DP[i][j-1]$ or $DP[i][j-1]$ to extend one of the previous substrings, but not the LCS, so: DP[i][j] = max(DP[i-1][j], DP[i][j-1]) - 1. In every case, we can refer to $DP[i][j-1]$ or $DP[i][j-1]$ to extend one of the previous substrings, but not the LCS, so: DP[i][j] = max(DP[i-1][j], DP[i][j-1]) - 1. An inquisitive reader may wonder why it doesn't hurt to always apply case $2$ in calculations, so clearing the doubts, it's important to informally notice that we never get a greater $LCS$ this way so wrong calculations only lead to the worse score, and that our code will always find a sequence of transitions which finds the true $LCS$ as well. Implementing the formulas gives a really short $O(n\\cdot m)$ solution.",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1446",
    "index": "C",
    "title": "Xor Tree",
    "statement": "For a given sequence of \\textbf{distinct} non-negative integers $(b_1, b_2, \\dots, b_k)$ we determine if it is \\textbf{good} in the following way:\n\n- Consider a graph on $k$ nodes, with numbers from $b_1$ to $b_k$ written on them.\n- For every $i$ from $1$ to $k$: find such $j$ ($1 \\le j \\le k$, $j\\neq i$), for which $(b_i \\oplus b_j)$ \\textbf{is the smallest} among all such $j$, where $\\oplus$ denotes the operation of bitwise XOR (https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Next, draw an \\textbf{undirected} edge between vertices with numbers $b_i$ and $b_j$ in this graph.\n- We say that the sequence is \\textbf{good} if and only if the resulting graph forms a \\textbf{tree} (is connected and doesn't have any simple cycles).\n\nIt is possible that for some numbers $b_i$ and $b_j$, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.\n\nYou can find an example below (the picture corresponding to the first test case).\n\nSequence $(0, 1, 5, 2, 6)$ \\textbf{is not} good as we \\textbf{cannot} reach $1$ from $5$.\n\nHowever, sequence $(0, 1, 5, 2)$ \\textbf{is} good.\n\nYou are given a sequence $(a_1, a_2, \\dots, a_n)$ of \\textbf{distinct} non-negative integers. You would like to remove some of the elements (possibly none) to make the \\textbf{remaining} sequence good. What is the minimum possible number of removals required to achieve this goal?\n\nIt can be shown that for any sequence, we can remove some number of elements, leaving at least $2$, so that the remaining sequence is good.",
    "tutorial": "Is it possible that the graph formed has a cycle? How to evaluate whether a sequence is good? Since we have $n$ edges and two of them must coincide (the pair of numbers with the smallest xor), we will have at most $n-1$ edges in the graph. Thus, we only need to check if the resulting graph is connected. How to do it? Let's look at the most significant bit, and group the numbers into two sets $S_0$ and $S_1$, depending on the value of the bit. What can we say about sizes of $S_0$ and $S_1$ in a good sequence? It is easy to see that if $2\\leq|S_0|$ and $2\\leq|S_1$| then the whole sequence isn't good, as for any number in $S_i$ the smallest xor will be formed by another number in $S_i$. So there won't be any connections between the numbers forming the two sets. Thus, one of the sets must have no more than one element. If that set contains no elements, then the solution can obviously be calculated recursively. If it instead had one element, then as long as we make the other sequence good, it will be connected to something - and thus the whole graph. Let $F(S)$ be the maximum possible number of values we can take from $S$ so that they form a good sequence. Divide the numbers into $S_0$ and $S_1$ as above. If $S_0$ or $S_1$ is empty, strip the most significant bit and solve the problem recursively. Otherwise, the result is $1 + max(F(S_0), F(S_1))$. Straightforward recursive calculation of this formula gives the runtime of $(n\\cdot 30)$, as all numbers are smaller than $2^{30}$.",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "divide and conquer",
      "dp",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1446",
    "index": "D1",
    "title": "Frequency Problem (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.}\n\nYou are given an array $[a_1, a_2, \\dots, a_n]$.\n\nYour goal is to find the length of the longest subarray of this array such that the most frequent value in it is \\textbf{not} unique. In other words, you are looking for a subarray such that if the most frequent value occurs $f$ times in this subarray, then at least $2$ different values should occur exactly $f$ times.\n\nAn array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "What can you say about the values which are the most frequent ones in the optimal solution? Let $D$ be the most frequent value in the whole sequence. If $D$ is not unique, we output $n$. Otherwise, we can prove that one of the most frequent values in an optimal solution is $D$. We'll prove this by contradiction. Consider an optimal interval $[a, b]$ in which $D$ is not in the set of most frequent values. Let's think of the process of expanding the interval to $[a-1, b]$, $[a-2, b]$, ..., $[1, b]$, $[1, b+1]$, ..., $[1 ,n]$. Since $D$ is most frequent in the entire sequence, at some point in this process it will appear the same number of times as at least one of the other most frequent values. The corresponding interval will also satisfy the task's conditions, hence $[a, b]$ cannot be an optimal interval if $D$ does not appear most frequently. For each value $V$ we can solve the task when $(D, V)$ are the most-frequent values independently, ignoring other values. Now we would like to solve the following subproblem: find the longest interval of sum 0 where elements in the array are either $1$ ($V$), $-1$ ($D$) or $0$ (other values). The solution's complexity should be proportional to the frequency of $V$ in order to obtain an efficient solution for the entire task. You might be worried that we can't simply ignore the other values, since they may end up being more frequent than ($D$, $V$) in the interval that we've found. This might be true, but can only be an underestimation of the optimal interval's length. A similar expanding argument to the proof above shows that: we never overestimate the result for the values of ($D$, $V$) which form the optimal interval we find exactly the right interval value. For the easy version, it's sufficient to consider all pairs ($D$, $V$) in linear time, by using the standard algorithm which computes the longest interval with sum $0$. Thus, we get a solution with complexity $O(100\\cdot n$).",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1446",
    "index": "D2",
    "title": "Frequency Problem (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.}\n\nYou are given an array $[a_1, a_2, \\dots, a_n]$.\n\nYour goal is to find the length of the longest subarray of this array such that the most frequent value in it is \\textbf{not} unique. In other words, you are looking for a subarray such that if the most frequent value occurs $f$ times in this subarray, then at least $2$ different values should occur exactly $f$ times.\n\nAn array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "A bit of thinking may lead you to the observation that solving the task in $O(n log n)$ or even $O(n log^2 n)$ isn't pleasant. The constraints are low enough to allow an $O(n \\sqrt n)$ solution, how about giving it a try? If an element $V$ appears more than $\\sqrt n$ times, we can simply brute-force this pair with partial sums $(D,V)$ in $O(n)$. For the other elements, for all the appearances of $V$ we'll consider only at most $|V|+1$ neighboring occurrences of $D$ to search for the optimal interval. We can generalize the brute-force solution to work for this case too, by writing a function that solves just for a vector of interesting positions. Don't forget to take into account extending intervals with zeroes as well. With proper preprocessing, this gives a solution in $O(|V|^2)$ per value $V$. Therefore, total runtime is bounded by $O(n \\sqrt n)$.",
    "tags": [
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1446",
    "index": "E",
    "title": "Long Recovery",
    "statement": "A patient has been infected with an unknown disease. His body can be seen as an infinite grid of triangular cells which looks as follows:\n\nTwo cells are neighboring if they share a side. Therefore, each cell ($x$, $y$) has exactly three neighbors:\n\n- ($x+1$, $y$)\n- ($x-1$, $y$)\n- ($x+1$, $y-1$) if $x$ is even and ($x-1$, $y+1$) otherwise.\n\nInitially some cells are infected, all the others are healthy. The process of recovery begins. Each second, for \\textbf{exactly one} cell (even though there might be multiple cells that could change its state) one of the following happens:\n\n- A healthy cell with at least $2$ infected neighbors also becomes infected.\n- An infected cell with at least $2$ healthy neighbors also becomes healthy.\n\nIf no such cell exists, the process of recovery stops. Patient is considered recovered if the process of recovery has stopped and all the cells are healthy.\n\nWe're interested in a \\textbf{worst-case} scenario: is it possible that the patient never recovers, or if it's not possible, what is the maximum possible duration of the recovery process?",
    "tutorial": "We're interested in the longest possible recovery path, so let's imagine choosing the longest sequence of operations ourselves. How long can this process last? Let $P$ be the number of pairs of neighboring cells with different state. Consider what happens to $P$ after an operation where we change the state of a cell $c$. It can be seen that $P$ decreases by 1 if $c$ had a neighbor with the same state as $c$, and $P$ decreases by 3 if all the neighbors of $c$ had a different state. Let's call the first kind of operation cheap and the other expensive. We now know that the process cannot last forever. When is it possible that the patient never recovers? If at some point there is a cycle of infected cells, then none of them can ever become healthy. Conversely, if there is no cycle of infected cells, and not all cells are healthy, then it is possible to make some infected cell healthy. If $A$ is the initial set of infected cells, let $\\overline A$ be the set of cells which can eventually be infected. By the above, we should output SICK if and only if $\\overline A$ contains a cycle. We can compute $\\overline A$ using a BFS. No cell with coordinates outside of $[0, 500) x [0, 500)$ will ever become infected, so we can safely make the BFS linear in the number of cells in this region. Let's assume that $\\overline A$ contains no cycle. We want to determine the minimum possible number of expensive operations used during the process of making all the cells healthy. We can consider each connected component of $\\overline A$ separately and add the results, so let's suppose $\\overline A$ is connected. The very last operation must be expensive, since it changes the state of an infected cell with three healthy neighbors. There is one other case where we need an expensive operation: if there's no way to make a cheap operation at the very beginning. In fact, this can happen only if $A$ consists of three cells arranged in a 'triforce'. It turns out that we never need any other expensive operations. So, assuming $\\overline A$ contains no cycle, we can compute the longest possible recovery period as follows. Compute the number $P$ of pairs of neighboring cells with different states. Subtract twice the number of connected components of $\\overline A$. Subtract twice the number of connected components of $\\overline A$ for which the corresponding cells in $A$ are just three cells arranged in a triforce. Note that the observation that the bad beginning component is only a triforce is actually not necessary to code a working solution (one can just check if there's a cheap move at the beginning, just remember that we're inspecting components of $\\overline A$), but it will help us to prove the solution formally. Let's now prove that we never need any other expensive operations than the ones described. Suppose $A$ is a set of at least 2 infected cells, such that (i) $\\overline A$ is cycle-free, (ii) $\\overline A$ is connected, and (iii) $A$ is not a triforce. We claim that there is a some cheap operation, such that the resulting set $A'$ of infected cells still satisfies (i), (ii) and (iii). We will always have (i), since $\\overline{A'} \\subseteq \\overline A$, so we just need to worry about (ii) and (iii), i.e. we need to ensure that $\\overline{A'}$ is connected and that $A'$ is not a triforce. We need to consider a few different cases. Suppose there is a cheap infection operation. Then just perform it. The resulting set $A'$ will have $\\overline{A'} = \\overline A$ still connected, and $A'$ will not be a triforce since it has adjacent infected cells. Suppose there is a cheap infection operation. Then just perform it. The resulting set $A'$ will have $\\overline{A'} = \\overline A$ still connected, and $A'$ will not be a triforce since it has adjacent infected cells. Suppose there is no cheap infection operation, but there is a cheap operation turning a cell $c$ from infected to healthy. Consider what happens if we perform it. Since there is no cheap infection operation, any cell in $\\overline A \\setminus A$ must have three neighbors in $A$. So it has at least two neighbors in $A \\setminus {c}$. So it lies in $\\overline{A \\setminus {c}}$. So $\\overline{A\\setminus{c}} \\supseteq \\overline A \\setminus{c}$. We claim that (ii) is satisfied, i.e. $\\overline{A\\setminus{c}}$ is connected. If $c$ is a leaf in $\\overline A$, this is clear, since removing a leaf from a tree does not disconnect it. If $c$ is not a leaf in $\\overline A$, then it has at least two neighbors in $\\overline{A\\setminus{c}}$, so $\\overline{A\\setminus{c}} = \\overline A$ is again connected. So the only possible issue is with (iii), i.e. $A \\setminus {c}$ might be a triforce. In this case, $A$ must be a triforce with an extra cell added, and we should just have chosen another $c$. Suppose there is no cheap infection operation, but there is a cheap operation turning a cell $c$ from infected to healthy. Consider what happens if we perform it. Since there is no cheap infection operation, any cell in $\\overline A \\setminus A$ must have three neighbors in $A$. So it has at least two neighbors in $A \\setminus {c}$. So it lies in $\\overline{A \\setminus {c}}$. So $\\overline{A\\setminus{c}} \\supseteq \\overline A \\setminus{c}$. We claim that (ii) is satisfied, i.e. $\\overline{A\\setminus{c}}$ is connected. If $c$ is a leaf in $\\overline A$, this is clear, since removing a leaf from a tree does not disconnect it. If $c$ is not a leaf in $\\overline A$, then it has at least two neighbors in $\\overline{A\\setminus{c}}$, so $\\overline{A\\setminus{c}} = \\overline A$ is again connected. So the only possible issue is with (iii), i.e. $A \\setminus {c}$ might be a triforce. In this case, $A$ must be a triforce with an extra cell added, and we should just have chosen another $c$. Suppose there is no cheap operation. This means that no elements of $A$ can be adjacent (since a tree with more than one vertex has a leaf). Moreover, any element of $\\overline A \\setminus A$ is surrounded by elements of $A$. Because $A$ has at least 2 cells and $\\overline A$ is connected, we must somewhere have three cells in $A$ arranged in a triforce. See the picture below. The green cells are not in $A$ since no elements of $A$ are adjacent, and the red cells are not in $A$ since $\\overline A$ is cycle-free. So $A$ cannot have any cells other than these $3$, since $\\overline A$ is connected. Suppose there is no cheap operation. This means that no elements of $A$ can be adjacent (since a tree with more than one vertex has a leaf). Moreover, any element of $\\overline A \\setminus A$ is surrounded by elements of $A$. Because $A$ has at least 2 cells and $\\overline A$ is connected, we must somewhere have three cells in $A$ arranged in a triforce. See the picture below. The green cells are not in $A$ since no elements of $A$ are adjacent, and the red cells are not in $A$ since $\\overline A$ is cycle-free. So $A$ cannot have any cells other than these $3$, since $\\overline A$ is connected. This covers all cases, finishing the proof.",
    "tags": [
      "constructive algorithms",
      "dfs and similar"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1446",
    "index": "F",
    "title": "Line Distance",
    "statement": "You are given an integer $k$ and $n$ distinct points with integer coordinates on the Euclidean plane, the $i$-th point has coordinates $(x_i, y_i)$.\n\nConsider a list of all the $\\frac{n(n - 1)}{2}$ pairs of points $((x_i, y_i), (x_j, y_j))$ ($1 \\le i < j \\le n$). For every such pair, write out the distance from the line through these two points to the origin $(0, 0)$.\n\nYour goal is to calculate the $k$-th smallest number among these distances.",
    "tutorial": "Binary search is your friend. To determine if the answer is bigger or smaller than $r$, we need to count the number of pairs of points $A$, $B$ such that $d(O, AB) > r$. We need to reformulate the condition $d(O, AB) > r$ to make the counting easier. Draw a circle of radius $r$ centered on $O$, and consider two points $A$, $B$ strictly outside the circle. Note that $d(O, AB) > r$ if and only if $AB$ does not intersect this circle. Now draw the tangents from $A$, $B$ to the circle. Let the corresponding points on the circle be $A_1, A_2, B_1, B_2$. Observation: the line segments $A_1 A_2, B_1 B_2$ intersect if and only if $AB$ does not intersect the circle. Moreover, if we pick polar arguments $a_1, a_2, b_1, b_2 \\in [0, 2\\pi)$, for the points in the circle, such that $a_1 < a_2$ and $b_1 < b_2$, then the line segments intersect if the intervals $[a_1, a_2], [b_1, b_2]$ overlap. We don't need to worry too much about precision errors, because if $r$ is close to the real answer, then it doesn't matter what our calculations return. (To compute $a_1$, note that $\\cos \\angle AOA_1 = r / \\left| OA \\right|$. So we get $a_1, a_2$ be adding / subtracting $\\cos^{-1} \\frac r {\\left|OA\\right|}$ from the argument of $A$.) We can prove the observation by considering three different cases, shown in pictures. One circle segment contains the other, and the line $AB$ intersects the circle outside the segment $AB$. The circle segments are disjoint, and the line segment $AB$ intersects the circle. The circle segments partially intersect, and the line $AB$ does not intersect the circle. Now we have computed some intervals and want to find the number of pairs of intervals which partially overlap. To do this, first sort the endpoints of the intervals. Do some coordinate compression on the left endpoints. Build a Fenwick tree on the compressed coordinates. Sweep through the endpoints. Whenever you see a left endpoint, add it to the tree. Whenever you see a right endpoint, remove it from the tree, query the tree for the number of points greater than the corresponding left endpoint, and add the result to the answer.",
    "tags": [
      "binary search",
      "data structures",
      "geometry"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1447",
    "index": "A",
    "title": "Add Candies",
    "statement": "There are $n$ bags with candies, initially the $i$-th bag contains $i$ candies. You want all the bags to contain an equal amount of candies in the end.\n\nTo achieve this, you will:\n\n- Choose $m$ such that $1 \\le m \\le 1000$\n- Perform $m$ operations. In the $j$-th operation, you will pick one bag and add $j$ candies to all bags apart from the chosen one.\n\nYour goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies.\n\n- It can be proved that for the given constraints such a sequence always exists.\n- You \\textbf{don't} have to minimize $m$.\n- If there are several valid sequences, you can output \\textbf{any}.",
    "tutorial": "We're only interested in differences between the elements. Is there another way to express the operation? The operation in the $i$-th turn is equivalent to selecting one element and subtracting $i$ from it. The sequence $1$, $2$, ..., $n$ satisfies task's constraints. After the additions all positions will contain $\\frac{n\\cdot(n+1)}{2}$ candies.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1447",
    "index": "B",
    "title": "Numbers Box",
    "statement": "You are given a rectangular grid with $n$ rows and $m$ columns. The cell located on the $i$-th row from the top and the $j$-th column from the left has a value $a_{ij}$ written in it.\n\nYou can perform the following operation any number of times (possibly zero):\n\n- Choose any two adjacent cells and multiply the values in them by $-1$. Two cells are called adjacent if they share a side.\n\nNote that you can use a cell more than once in different operations.\n\nYou are interested in $X$, the \\textbf{sum} of all the numbers in the grid.\n\nWhat is the maximum $X$ you can achieve with these operations?",
    "tutorial": "We want to minimize the number of negative numbers as much as we can by applying the operations. What is the minimum possible number of those negatives? Let $X$ be the number of non-zero numbers in the grid, and let's see what happens in different scenarios. both cells have negative numbers, then $X$ goes down by $2$. both cells have positive numbers, then $X$ goes up by $2$. one cell has a positive number while the other one has a negative number, then $X$ stays the same. It is important to notice that we can apply this operation not only for the two neighboring cells, but for any two - to achieve this effect we apply this operation on any path between the cells consecutively. The parity of $X$ never changes. So, for even $X$ the answer is the sum of the absolute value of all numbers, $S$. Otherwise, one element will not be positive in the end -- so it's best to choose the one with minimum absolute value, $V$, and subtract $2\\cdot V$ from the sum. The existence of zeroes doesn't really change anything, both formulas output the same value in such a case. This gives us a solution in $O(N\\cdot M)$",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1450",
    "index": "A",
    "title": "Avoid Trygub",
    "statement": "A string $b$ is a subsequence of a string $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) characters. For example, \"xy\" is a subsequence of \"xzyw\" and \"xy\", but not \"yx\".\n\nYou are given a string $a$. Your task is to reorder the characters of $a$ so that \"trygub\" is not a subsequence of the resulting string.\n\nIn other words, you should find a string $b$ which is a permutation of symbols of the string $a$ and \"trygub\" is not a subsequence of $b$.\n\nWe have a truly marvelous proof that any string can be arranged not to contain \"trygub\" as a subsequence, but this problem statement is too short to contain it.",
    "tutorial": "The string \"trygub\" is not sorted alphabetically, and a subsequence of a sorted string is necessarily sorted. So, if we sort the input string, it will be a solution. Complexity is $O(n)$ with counting sort.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int te;\n    cin >> te;\n    while(te--) {\n        int n; string s;\n        cin >> n >> s;\n        sort(s.begin(), s.end());\n        cout << s << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1450",
    "index": "B",
    "title": "Balls of Steel",
    "statement": "You have $n$ \\textbf{distinct} points $(x_1, y_1),\\ldots,(x_n,y_n)$ on the plane and a non-negative integer parameter $k$. Each point is a microscopic steel ball and $k$ is the attract power of a ball when it's charged. The attract power is the same for all balls.\n\nIn one operation, you can select a ball $i$ to charge it. Once charged, \\textbf{all} balls with Manhattan distance at most $k$ from ball $i$ move to the position of ball $i$. Many balls may have the same coordinate after an operation.\n\nMore formally, for all balls $j$ such that $|x_i - x_j| + |y_i - y_j| \\le k$, we assign $x_j:=x_i$ and $y_j:=y_i$.\n\n\\begin{center}\nAn example of an operation. After charging the ball in the center, two other balls move to its position. On the right side, the red dot in the center is the common position of those balls.\n\\end{center}\n\nYour task is to find the minimum number of operations to move all balls to the same position, or report that this is impossible.",
    "tutorial": "We claim the answer is always $-1$ or $1$. In fact, suppose in the first operation of a solution we select a point $p$. If we aren't done, there will at least one point with distance more than $k$ from $p$. However, there will be no point within distance $k$ of $p$, no matter how we perform future operations. So it is impossible for $p$ to merge with a new point, and a solution with more than $1$ operation will be impossible. To see if the answer is $1$, we should check if there is some point $p$ within distance $k$ from all other points. Otherwise, the answer is $-1$. Complexity is $O(n^2)$ to compute pairwise distances.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n\tios_base::sync_with_stdio(0), cin.tie(0);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<pair<int, int>> a(n);\n\t\tfor (auto &i : a)\n\t\t\tcin >> i.first >> i.second;\n\t\tint ans = -1;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint mx = 0;\n\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\tmx = max(mx, abs(a[i].first - a[j].first) + abs(a[i].second - a[j].second));\n\t\t\t}\n\t\t\tif (mx <= k) ans = 1;\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}",
    "tags": [
      "brute force",
      "geometry",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1450",
    "index": "C1",
    "title": "Errich-Tac-Toe (Easy Version)",
    "statement": "\\textbf{The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.}\n\nErrichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces.\n\nIn a Tic-Tac-Toe grid, there are $n$ rows and $n$ columns. Each cell of the grid is either empty or contains a token. There are two types of tokens: X and O. If there exist three tokens of the same type consecutive in a row or column, it is a winning configuration. Otherwise, it is a draw configuration.\n\n\\begin{center}\nThe patterns in the first row are winning configurations. The patterns in the second row are draw configurations.\n\\end{center}\n\nIn an operation, you can change an X to an O, or an O to an X. Let $k$ denote the total number of tokens in the grid. Your task is to make the grid a \\textbf{draw} in at most $\\lfloor \\frac{k}{3}\\rfloor$ (rounding down) operations.\n\nYou are \\textbf{not required} to minimize the number of operations.",
    "tutorial": "For each cell $(i,j)$, let's associate it with the color $(i+j)\\bmod 3$. Every three consecutive cells contains one of each color. So, if we choose one color and flip all tokens with that color, it will be a solution. We need only prove that there is a color associated with at most one third of the tokens. Let there be $x_i$ tokens in cells of diagonal number $i$, for $i=0,1,2$. Then we have $k=x_0+x_1+x_2$. Therefore, $\\min\\{x_0,x_1,x_2\\}\\le \\lfloor \\frac{k}{3}\\rfloor$. Here's the coloring on an example. There are $3$ X's on red, $4$ on blue, and $5$ on green. Red has the fewest, so we flip those.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 305;\nint n;\nstring s[N];\n \nvoid solve() {\n    cin >> n;\n    // cnt[color] = occurrences of X on that color cell.\n    int cnt[3] = {0, 0, 0};\n    for(int i = 0; i < n; i++) {\n        cin >> s[i];\n        for(int j = 0; j < n; j++) {\n            if(s[i][j] == 'X') {\n                cnt[(i + j) % 3]++;\n            }\n        }\n    }\n    // val = best color\n    int val = min_element(cnt, cnt + 3) - cnt;\n    for(int i = 0; i < n; i++) {\n        for(int j = 0; j < n; j++) {\n            // flip tokens whose color is the best val\n            if(s[i][j] == 'X' && (i + j) % 3 == val) {\n                s[i][j] = 'O';\n            }\n        }\n        cout << s[i] << '\\n';\n    }\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int te;\n    cin >> te;\n    while(te--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1450",
    "index": "C2",
    "title": "Errich-Tac-Toe (Hard Version)",
    "statement": "\\textbf{The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.}\n\nErrichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces.\n\nIn a Tic-Tac-Toe grid, there are $n$ rows and $n$ columns. Each cell of the grid is either empty or contains a token. There are two types of tokens: X and O. If there exist three tokens of the same type consecutive in a row or column, it is a winning configuration. Otherwise, it is a draw configuration.\n\n\\begin{center}\nThe patterns in the first row are winning configurations. The patterns in the second row are draw configurations.\n\\end{center}\n\nIn an operation, you can change an X to an O, or an O to an X. Let $k$ denote the total number of tokens in the grid. Your task is to make the grid a \\textbf{draw} in at most $\\lfloor \\frac{k}{3}\\rfloor$ (rounding down) operations.\n\nYou are \\textbf{not required} to minimize the number of operations.",
    "tutorial": "If for every three consecutive tokens in the grid, we make sure there is an X and there is an O, we are done. For each cell $(i,j)$, let's associate it with the color $(i+j)\\bmod 3$. Since every three consecutive cells contains one of each color, if we make all of one color X and all of a different color O, it would be a solution. It remains to prove that one such way makes at most $\\lfloor \\frac{k}{3}\\rfloor$ operations. For each token on the grid, it is associated with a color ($0$, $1$, or $2$) and a type (X or O). Therefore each token falls into one of $6$ categories. So we can make a table for how many tokens fall in each category. $\\begin{array}{c|c|c|c} &0&1&2\\\\\\hline \\text{X}&x_0&x_1&x_2\\\\\\hline \\text{O}&o_0&o_1&o_2\\\\ \\end{array}$ Firstly, $k=x_0+x_1+x_2+o_0+o_1+o_2$. Let $a_{ij}$ denote the number of operations we make if we flip all X's in cells with color $i$ and flip all O's in cells with color $j$. Then $a_{ij}=x_i+o_j$. Now, we have $a_{01}+a_{02}+a_{10}+a_{12}+a_{20}+a_{21}=2k$. Finally, $\\min\\{a_{01},a_{02},a_{10},a_{12},a_{20},a_{21}\\}\\le \\lfloor 2k/6\\rfloor=\\lfloor \\frac{k}{3}\\rfloor$. Here's the coloring in an example. We flip all green X's and blue O's.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 305;\nint te, n;\nstring s[N];\n \nvoid solve() {\n    cin >> n;\n    // Let X = 0, O = 1. Let cnt[r][b] = the number of tokens b in diagonals with label r.\n    int cnt[3][2] = {{0, 0}, {0, 0}, {0, 0}};\n    int k = 0;\n    for(int i = 0; i < n; i++) {\n        cin >> s[i];\n        for(int j = 0; j < n; j++) {\n            char c = s[i][j];\n            int val = (i + j) % 3;\n            if(c == 'X') {\n                cnt[val][0]++;\n                k++;\n            }\n            else if(c == 'O') {\n                cnt[val][1]++;\n                k++;\n            }\n        }\n    }\n    // Choose one diagonal label d to become all O's, and another diagonal label d2 to become all X's.\n    for(int d = 0; d < 3; d++) {\n        for(int d2 = 0; d2 < 3; d2++) {\n            if(d == d2) continue;\n            if(cnt[d][0] + cnt[d2][1] <= k / 3) {\n                for(int i = 0; i < n; i++) {\n                    for(int j = 0; j < n; j++) {\n                        if((i + j) % 3 == d && s[i][j] == 'X') {\n                            s[i][j] = 'O';\n                        }else if((i + j) % 3 == d2 && s[i][j] == 'O') {\n                            s[i][j] = 'X';\n                        }\n                    }\n                    cout << s[i] << '\\n';\n                }\n                return;\n            }\n        }\n    }\n    assert(false);\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> te;\n    while(te--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1450",
    "index": "D",
    "title": "Rating Compression",
    "statement": "On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers $a$ of length $n$. You are now updating the infrastructure, so you've created a program to compress these graphs.\n\nThe program works as follows. Given an integer parameter $k$, the program takes the minimum of each contiguous subarray of length $k$ in $a$.\n\nMore formally, for an array $a$ of length $n$ and an integer $k$, define the $k$-compression array of $a$ as an array $b$ of length $n-k+1$, such that $$b_j =\\min_{j\\le i\\le j+k-1}a_i$$\n\nFor example, the $3$-compression array of $[1, 3, 4, 5, 2]$ is $[\\min\\{1, 3, 4\\}, \\min\\{3, 4, 5\\}, \\min\\{4, 5, 2\\}]=[1, 3, 2].$\n\nA permutation of length $m$ is an array consisting of $m$ distinct integers from $1$ to $m$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($m=3$ but there is $4$ in the array).\n\nA $k$-compression array will make CodeCook users happy if it will be a permutation. Given an array $a$, determine for all $1\\leq k\\leq n$ if CodeCook users will be happy after a $k$-compression of this array or not.",
    "tutorial": "For $k=1$, we simply need to check that the array is a permutation. If $k=n$, we simply need to check that the array has minimum $1$. For $1<k<n$, we know the $k$-compression should contain exactly one occurrence of $1$. But $1$ is the minimum possible element, so it should occur in only one length $k$ subarray. Therefore, $1$ should only occur at one of the extremes: index $1$ or index $n$. Without loss of generality, suppose it occurs at index $n$. Then we require that the $k$-compression of $a[1,\\ldots,n-1]$ is a permutation of the numbers $\\{2,3,\\ldots,n-k+1\\}$, and we can solve iteratively. This gives us the following algorithm. We maintain an interval $[l,r]$. Initially $l=1$ and $r=n$. Now, we iterate $i=1,\\ldots,n$. For each $i$, we make sure that either $a_l=i$ or $a_r=i$, increment $l$ or decrement $r$ accordingly. Then check that $\\min\\limits_{j=l}^r a_j=i+1$. If $i$ is the first index that our checks fail, then the answer is $0$ for $2\\le k\\le n-i+1$ and the answer is $1$ for $n-i+1< k\\le n$. Checking the minimum element each iteration can be done with data structures like a sparse table or segment tree. It is also sufficient to maintain a $count$ array of the elements, for a complexity of $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int mxN = 300001;\nint arr[mxN]; // input array\nint cnt[mxN]; // cnt[x] = number of occurrences of x in the array\nbool ans[mxN]; // the final answer\nint n;\n \nvoid solve() {\n    cin>>n;\n    for(int i = 0; i <= n; ++i) {\n        cnt[i] = 0;\n        ans[i] = 0;\n    }\n    for(int i = 0; i < n; ++i) {\n        cin>>arr[i];\n        arr[i]--; // switch to 0-indexing\n        cnt[arr[i]]++;\n    }\n    int tp = -1;\n    while(cnt[tp+1]==1) {\n        tp++;\n    }\n    // each number from 0..n-1 has exactly one occurrence -> permutation\n    ans[0] = tp==n-1;\n    int l = 0; int r = n-1;\n    \n    // special case, min = 0\n    ans[n-1] = cnt[0] > 0;\n    \n    // shrink the interval as long as our checks pass\n    for(int i = n-1; i > 0; --i) {\n        if(!ans[n-1]) break;\n        ans[i] = true;\n        int nxt = n-i-1;\n        if(--cnt[nxt] == 0 && (arr[l]==nxt || arr[r]==nxt) && cnt[nxt+1]) {\n            if(arr[l]==nxt)l++;\n            if(arr[r]==nxt)r--;\n            continue;\n        }\n        break;\n    }\n    \n    for(int i = 0; i < n; ++i) {\n        cout<<ans[i];\n    }\n    cout<<\"\\n\";\n}\nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    int T;\n    cin>>T;\n    while(T--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1450",
    "index": "E",
    "title": "Capitalism",
    "statement": "A society can be represented by a connected, undirected graph of $n$ vertices and $m$ edges. The vertices represent people, and an edge $(i,j)$ represents a friendship between people $i$ and $j$.\n\nIn society, the $i$-th person has an income $a_i$. A person $i$ is envious of person $j$ if $a_j=a_i+1$. That is if person $j$ has exactly $1$ more unit of income than person $i$.\n\nThe society is called \\textbf{capitalist} if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.\n\nThe \\textbf{income inequality} of society is defined as $\\max\\limits_{1 \\leq i \\leq n} a_i - \\min\\limits_{1 \\leq i \\leq n} a_i$.\n\nYou only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.",
    "tutorial": "Firstly, each edge connects a person with even income and a person with odd income. So if the graph is not bipartite, then a solution does not exist. Consider a friendship between people $u$ and $v$, where we don't know the direction. Since $|a_u-a_v|=1$, we know that $a_u-a_v\\le 1$ and $a_v-a_u\\le 1$. Consider a directed friendship $(u\\to v)$. Since $a_u+1=a_v$, we know that $a_v-a_u\\le 1$ and $a_u-a_v\\le -1$. For each friendship, let's add two directed edges between them. If it's undirected, we add one from $u\\to v$ of weight $1$ and one from $v\\to u$ of weight $1$. If it's directed, we add one from $u\\to v$ of weight $1$, and one from $v\\to u$ of weight $-1$. The way we added these edges ensures that if $u$ and $v$ are any two vertices and there is a path of distance $d$ from $u$ to $v$, then $a_v-a_u\\le d$. Note that if a negative cycle exists in our graph, then the inequalities give a contradiction. Otherwise if an answer exists, some vertex $u$ will have minimum $a_u$ and another vertex $v$ will have maximum $a_v$, and $a_v-a_u\\le \\mathrm{dist}(u\\to v)$. Therefore, the answer cannot be greater than the diameter: $\\max_{u,v}\\mathrm{dist}(u\\to v)$. If we find a construction with this answer, then this proves optimality. Let our construction be as follows. First, choose two vertices $u$ and $v$ such that $\\mathrm{dist}(u\\to v)$ is maximized. Let's assign $a_i=\\mathrm{dist}(u\\to i)$. The property of shortest paths tell us that all the desired inequalities hold for $a_i$. Then we know all directed friendships are correct: $a_v-a_u=1$. For all undirected friendships, we know $|a_v-a_u|\\le 1$. Since the graph is bipartite, it cannot hold that $a_u=a_v$, therefore $|a_v-a_u|=1$, so all requirements hold and the income inequality is maximized. For the implementation, we need to check the graph is bipartite, check if negative cycles exist, and find all-pairs shortest paths. For this, we can simply do Floyd-Warshall in $O(n^3)$ time.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 205, M = 2005;\nint n, m, u[M], v[M], b[M];\nint dist[N][N];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> n >> m;\n    for(int i = 1; i <= n; i++) {\n        for(int j = 1; j <= n; j++) {\n            if(i != j) dist[i][j] = INT_MAX;\n        }\n    }\n    for(int i = 0; i < m; i++) {\n        cin >> u[i] >> v[i] >> b[i];\n        // build directed graph\n        dist[u[i]][v[i]] = 1;\n        dist[v[i]][u[i]] = (b[i] == 0 ? 1 : -1);\n    }\n    // Floyd-Warshall, detecting negative cycles if integer underflow\n    for(int k = 1; k <= n; k++) {\n        for(int i = 1; i <= n; i++) {\n            for(int j = 1; j <= n; j++) {\n                if(dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j]) {\n                    dist[i][j] = dist[i][k] + dist[k][j];\n                    if(dist[i][j] < -1e9) {\n                        // integer underflow -> negative cycle\n                        cout << \"NO\\n\";\n                        return 0;\n                    }\n                }\n            }\n        }\n    }\n    // (max dist, u)\n    pair<int, int> best = {-1, 1};\n    for(int i = 1; i <= n; i++) {\n        if(dist[i][i] < 0) {\n            // negative cycle\n            cout << \"NO\\n\";\n            return 0;\n        }\n        for(int j = 1; j <= n; j++) {\n            best = max(best, {dist[i][j], i});\n        }\n    }\n    // check it is a valid answer. This handles bipartite check automatically.\n    int s = best.second;\n    for(int i = 0; i < m; i++) {\n        if(dist[s][u[i]] == dist[s][v[i]]) {\n            // non-bipartite\n            cout << \"NO\\n\";\n            return 0;\n        }\n    }\n    cout << \"YES\\n\" << best.first << '\\n';\n    for(int i = 1; i <= n; i++) {\n        cout << dist[s][i] << ' ';\n    }\n    cout << '\\n';\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1450",
    "index": "F",
    "title": "The Struggling Contestant",
    "statement": "To help those contestants who struggle a lot in contests, the headquarters of Codeforces are planning to introduce Division 5. In this new division, the tags of all problems will be announced prior to the round to help the contestants.\n\nThe contest consists of $n$ problems, where the tag of the $i$-th problem is denoted by an integer $a_i$.\n\nYou want to AK (solve all problems). To do that, you must solve the problems in some order. To make the contest funnier, you created extra limitations on yourself. You do not want to solve two problems consecutively with the same tag since it is boring. Also, you are afraid of big jumps in difficulties while solving them, so you want to minimize the number of times that you solve two problems consecutively that are not adjacent in the contest order.\n\nFormally, your solve order can be described by a permutation $p$ of length $n$. The \\textbf{cost} of a permutation is defined as the number of indices $i$ ($1\\le i<n$) where $|p_{i+1}-p_i|>1$. You have the requirement that $a_{p_i}\\ne a_{p_{i+1}}$ for all $1\\le i< n$.\n\nYou want to know the minimum possible cost of permutation that satisfies the requirement. If no permutations meet this requirement, you should report about it.",
    "tutorial": "Suppose $p$ is a permutation that satisfies the condition. Imagine we add a divider between adjacent indices that are not adjacent in $p$. If $k$ is the number of \"jumps\" in $p$, then we have split the array $a$ into $k+1$ consecutive segments. The permutation will scan these segments in some order, and each segment can be scanned in forward or reversed order. We can visualize the problem like we \"cut\" the array in $k$ places, then reorder and reverse the segments so that no two adjacent tags are equal. Obviously, for all $i$ such that $a_i=a_{i+1}$ we need to cut between $i$ and $i+1$. Now, we only need to think about the endpoints of these segments, and we need a condition for when it is possible to avoid connecting equal endpoints. For a tag $x$, define $f(x)$ as the number of times $x$ appears as an endpoint of a segment. Note that if a segment consists of only one tag, we count $x$ twice, as both a left and right endpoint. We claim that a valid reordering of the segments is possible if and only if for all tags $x$, it holds that $f(x) \\le k+2$. Let $x$ be a tag. Let's prove that if a solution exists, then $f(x)\\le k+2$. Consider a reordering of the segments as $[y_1, y_2],[y_3,y_4],\\ldots,[y_{2k+1},y_{2k+2}]$. Here, $y_{2i-1}$ and $y_{2i}$ are the endpoints of the segment that appears $i$-th in the solution order. Since $y_{2i}$ and $y_{2i+1}$ are connected, they cannot both be $x$. It can be that $y_1=x$, and it can be that $y_{2k+2}=x$, but at most half of the remaining endpoints (there are $2k$ of them) can be $x$ due to these connections. So $f(x)\\le k+2$. Let's prove that if $f(x)\\le k+2$ for all tags $x$, then we can construct a solution. We proceed by induction on $k$. If $k=0$, there is only one segment and we are done. Now, suppose $k\\ge 1$. Let $x$ be any tag with maximum $f(x)$. Select one segment with $x$ as an endpoint and another with $y \\ne x$ as an endpoint. (Note that such a pair of segments always exists). Connect the selected $x$ and $y$ together, merging them into one segment. We have reduced the number of segments by $1$, and we have decreased the frequencies of $x$ and $y$ as endpoints by $1$. After making this connection, the condition clearly holds for $x$ and $y$. For all other tags $z$ ($z \\ne x$, $z \\ne y$), it holds before the operation that $f(z) \\le (2k+2)-f(x)\\le (2k+2)-f(z)$ and so $f(z)\\le k+1$. After the operation, $k$ decreases and $f(z)$ is unchanged, so $f(z) \\le k+2$ holds. By induction, a solution exists. To find the solution with the minimum number of cuts, we firstly must cut the array between all adjacent indices of equal tags. If this set of cuts already satisfies the above condition, we are done. Otherwise, there is a tag $x$ such that $f(x) > k+2$ and for all tags $y \\ne x$, $f(y)\\le k+2$. If we add a cut between two consecutive tags such that one of them is $x$, it increases $f(x)$ by one and $k$ by one, so it is useless. If we cut between two consecutive tags that are not $x$, it does not change $f(x)$ and it increases $k$ by one. That is, each such cut brings the condition one step closer to equality. Therefore if a solution exists and $f(x)>k+2$, we require exactly $f(x)-(k+2)$ additional cuts. Let's summarize the solution. If some tag $x$ has more than $\\lceil n/2\\rceil$ occurrences, a solution does not exist. Otherwise, let $k$ be the number of adjacent equal tags, and add the necessary cuts in these positions. Let $x$ be the tag that occurs most frequently as an endpoint in the resulting segments. The answer is $k+\\max\\{0, f(x)-(k+2)\\}$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    vector<int> f(n + 1, 0), ends(n + 1, 0);\n    int cuts = 0;\n    for(int i = 0; i < n; i++) {\n        cin >> a[i];\n        f[a[i]]++;\n        if(i > 0 && a[i] == a[i - 1]) {\n            ends[a[i]]++;\n            ends[a[i - 1]]++;\n            cuts++;\n        }\n    }\n    if(*max_element(f.begin(), f.end()) > (n + 1) / 2) {\n        cout << -1 << '\\n';\n        return;\n    }\n    ends[a[0]]++;\n    ends[a[n - 1]]++;\n    int maxf = *max_element(ends.begin(), ends.end());\n    cout << cuts + max(0, maxf - cuts - 2) << '\\n';\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int te;\n    cin >> te;\n    while(te--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1450",
    "index": "G",
    "title": "Communism",
    "statement": "\\textbf{Please pay attention to the unusual memory limit in this problem.}\n\nIn a parallel universe, Satan is called \"Trygub\". For that reason, the letters of his namesake were deleted from the alphabet in ancient times.\n\nThe government has $n$ workers standing in a row and numbered with integers from $1$ to $n$ from left to right. Their job categories can be represented as a string $s$ of length $n$, where the character $s_i$ represents the job category of the $i$-th worker.\n\nA new law will be approved to increase the equality between the workers. The government decided to make everyone have the same job category by performing the following operation any number of times (possibly zero).\n\nThere is a fixed \\textbf{rational} parameter $k=\\frac ab$ describing how easy it is to convince the public, and it will be used to determine the success of an operation.\n\nIn an operation, the government first selects a job category $x$ with at least one worker at the current moment. Suppose $i_1,\\ldots, i_m$ ($i_1<\\ldots<i_m$) are the positions of all the workers with job category $x$. If $k\\cdot (i_m-i_1+1)\\le m$, the government is able to choose any job category $y$ with at least one worker at the current moment and change the job category of \\textbf{all} workers with job category $x$ to job category $y$.\n\nIf it is possible to make all workers have job category $x$, we say that $x$ is obtainable. Can you tell the government the set of obtainable job categories?",
    "tutorial": "Let $C$ denote the set of distinct characters in $s$. Suppose there is a sequence of operations that transforms every character to $x$ in the end. For an operation where we transform all occurrences of $y$ to $z$, let's add a directed edge $(y\\to z)$. The resulting structure is a directed tree rooted at $x$. This is because every character except $x$ is transformed exactly once. For each character $y$, denote the index of its first occurrence by $l_y$ and its last occurrence by $r_y$. For any non-empty subset $S$ of characters, define $\\mathrm{range}(S)=\\left[\\min\\limits_{y\\in S} l_y, \\max\\limits_{y\\in S} r_y\\right]$. That is, the smallest interval capturing all occurrences of characters belonging to $S$. Also define $\\mathrm{cnt}(S)$ as the number of occurrences of characters in $S$. Given a directed tree structure, we can decide its validity regardless of the order of operations. For a character $y$, let $S_y$ denotes the set of characters in the subtree of $y$. The condition is that for every character $y$, $\\mathrm{cnt}(S_y)\\ge k \\left|\\mathrm{range}(S_y)\\right|.\\tag{1}$ Now, we can devise a bitmask dp. For any subset $M$, let $\\mathrm{dp}(M)$ be true if we can organize the characters of $M$ into a valid tree rooted at a character outside of $M$. Then the final answer will be the set of characters $x$ such that $\\mathrm{dp}(C\\setminus \\{x\\})$ is true. To create the dp transitions, there are $2$ cases. Choose a character $y\\in M$ to be an ancestor of all of $M$. That is, if the condition $(1)$ holds for the set $M=S_y$ and $\\mathrm{dp}(M\\setminus \\{y\\})$ is true, then $\\mathrm{dp}(M)$ is true. The set $M$ should be split into at least two disjoint subtrees. That is, if there is a non-empty, proper subset $S\\subset M$ such that $\\mathrm{dp}(S)$ and $\\mathrm{dp}(M\\setminus S)$ are true, then $\\mathrm{dp}(M)$ is also true. These transitions give rise to an $O(n+3^{|C|})$ solution, since we iterate over all subsets of $M$ in case 2. We still need another observation to optimize this further. The key observation is that we may assume for the transitions of case 2 that $\\mathrm{range}(S)\\cap \\mathrm{range}(M\\setminus S)=\\emptyset$. That is, the sets of characters in sibling subtrees occur on disjoint intervals. To prove that this assumption is justified, we show that a valid tree can be transformed to a valid tree that does satisfy our assumption. Suppose there are two siblings $y$ and $z$ whose subtrees have overlapping ranges. Then if we change $z$'s parent to $y$, we only need to check that the condition $(1)$ still holds for $y$. In fact, $\\mathrm{cnt}(A\\cup \\{y\\}\\cup B\\cup \\{z\\})= \\mathrm{cnt}(A\\cup \\{y\\})+\\mathrm{cnt}(B\\cup\\{z\\})$ $\\ge k \\cdot \\left|\\mathrm{range}(A\\cup \\{y\\})\\right| + k\\cdot \\left|\\mathrm{range}(B\\cup \\{z\\})\\right|\\ge k\\cdot \\left|\\mathrm{range}(A\\cup \\{y\\}\\cup B\\cup \\{z\\})\\right|.$ Of course, after the transformation in the figure, maybe our assumption still does not hold. But observe that if we repeat this process, it will stop in finitely many steps. This is because the sum of depths of all nodes strictly increases with each transformation, and the depth of a node is bounded by $|C|$. Now that the claim is proven, it is not hard to improve our solution to $O(n+|C|2^{|C|})$. If we sort the characters in $C$ by the index of their first occurrence, it is sufficient to try only $|C|-1$ splits according to this order for case 2. That is, if the characters in $M$ are ordered $c_1,\\ldots, c_m$, then we should take $S=\\{c_1,\\ldots,c_i\\}$ for some $i$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n\tios_base::sync_with_stdio(0), cin.tie(0);\n \n\tint n, ka, kb;\n\tstring s;\n\tcin >> n >> ka >> kb >> s;\n \n    // sort characters of string by first occurrence\n\tint p = 0;\n\tvector<int> id(26, -1);\n\tvector<char> mp(26);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint c = s[i] - 'a';\n\t\tif (id[c] == -1) {\n\t\t\tmp[p] = s[i];\n\t\t\tid[c] = p++;\n\t\t}\n\t}\n    // dp arrays for first occurrence, last occurrence, number of occurrences for each bitmask\n\tvector<int> l(1 << p, n), r(1 << p, -1), count(1 << p);\n\tfor (int i = 0; i < n; ++i) {\n\t\tint c = s[i] - 'a';\n\t\tif (l[1 << id[c]] == n) {\n\t\t\tl[1 << id[c]] = i;\n        }\n\t\tr[1 << id[c]] = i;\n\t\t++count[1 << id[c]];\n\t}\n \n    // dp[mask] = true if it's possible for everything in mask to transform to a common character\n\tvector<bool> dp(1 << p);\n\tdp[0] = true;\n\tfor (int m = 0; m < (1 << p); ++m) {\n\t\tfor (int i = 0, m2 = 0; i < p; ++i) {\n\t\t\tif (m >> i & 1) {\n\t\t\t\tm2 |= 1 << i;\n                // try ways to split the mask along the sorted order\n                if(dp[m2] && dp[m ^ m2]) {\n                    dp[m] = true;\n                }\n\t\t\t\tl[m] = min(l[m ^ 1 << i], l[1 << i]);\n\t\t\t\tr[m] = max(r[m ^ 1 << i], r[1 << i]);\n\t\t\t\tcount[m] = count[m ^ 1 << i] + count[1 << i];\n\t\t\t}\n        }\n        // try ways to root at some vertex in the mask\n\t\tfor (int i = 0; i < p; ++i) {\n\t\t\tif((m >> i & 1) && dp[m ^ 1 << i] && kb * count[m] >= (r[m] - l[m] + 1) * ka) {\n                dp[m] = true;\n            }\n        }\n\t}\n \n\tset<char> ans;\n\tfor (int i = 0; i < p; ++i) {\n\t\tif (dp[((1 << p) - 1) ^ (1 << i)]) {\n\t\t\tans.insert(mp[i]);\n        }\n    }\n \n\tcout << ans.size();\n\tfor (auto i : ans) cout << \" \" << i;\n\tcout << \"\\n\";\n}",
    "tags": [
      "bitmasks",
      "dp",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1450",
    "index": "H1",
    "title": "Multithreading (Easy Version)",
    "statement": "\\textbf{The only difference between the two versions of the problem is that there are no updates in the easy version.}\n\nThere are $n$ spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white.\n\nFor any two spools of the same color, you can attach them with a thread of that color in a straight line segment. Define a matching as a way to attach spools together so that each spool is attached to exactly one other spool.\n\nColoring is an assignment of colors (white and black) to the spools. A coloring is called \\textbf{valid} if it has at least one matching. That is if the number of black spools and the number of white spools are both even.\n\nGiven a matching, we can find the number of times some white thread intersects some black thread. We compute the number of pairs of differently colored threads that intersect instead of the number of intersection points, so one intersection point may be counted multiple times if different pairs of threads intersect at the same point. If $c$ is a valid coloring, let $f(c)$ denote the minimum number of such intersections out of all possible matchings.\n\n\\begin{center}\nThe circle above is described by the coloring bwbbbwww. After matching the spools as shown, there is one intersection between differently colored threads. It can be proven that it is the minimum possible, so $f(\\text{bwbbbwww}) = 1$.\n\\end{center}\n\nYou are given a string $s$ representing an \\textbf{unfinished} coloring, with black, white, and uncolored spools. A coloring $c$ is called $s$-reachable if you can achieve it by assigning colors to the uncolored spools of $s$ without changing the others.\n\nA coloring $c$ is chosen uniformly at random among all valid, $s$-reachable colorings. Compute the expected value of $f(c)$. You should find it by modulo $998244353$.\n\nWe can show that the answer can be written in the form $\\frac{p}{q}$ where $p$ and $q$ are relatively prime integers and $q\\not\\equiv 0\\pmod{998244353}$. The answer by modulo $998244353$ is equal to $(p\\cdot q^{-1})$ modulo $998244353$.",
    "tutorial": "Lets first solve for a given coloring, $c$, the value of $f(c)$. Let $B_{odd}$, $B_{even}$ denote the number of black spots on even positions, and odd positions respectively. We notate similarly for $W_{odd}$ and $W_{even}$. Claim: $f(c) = \\frac12 |B_{odd} - B_{even}|$. Proof: Let's show for any coloring where $B_{odd} - B_{even} = 2k$ (the other case $B_{even} - B_{odd} = 2k$ is equivalent) we have $f(c)=k$. Let's show $f(c)\\le k$ with a construction of $k$ intersections. Given the condition, let's show a construction. Suppose that $B_{odd}\\geq 1$ and $B_{even}\\geq 1$. Then there are two adjacent positions of the same color. Connect those positions and continue to solve for the remaining spools. Eventually, there will be $B_{odd} = 2k$ and $W_{even} = 2k$ in an alternating pattern $\\text{bwbw}\\ldots\\text{bwbw}$. It's easy to connect these to form $k$ connections. Let's show $f(c)\\ge k$ by proving any matching has at least $k$ intersections. First, we may assume there are no same-color intersections. If one existed, we could improve the matching, not increasing the number of different-color intersections.Now, since $B_{odd}-B_{even}=2k$, there are at least $k$ black spools on odd positions that are connected to other black spools on odd positions. Each such thread splits the other spools into two sections, each with an odd number of spools. Therefore each of these $k$ threads intersects another thread. Qed. Now, since $B_{odd}-B_{even}=2k$, there are at least $k$ black spools on odd positions that are connected to other black spools on odd positions. Each such thread splits the other spools into two sections, each with an odd number of spools. Therefore each of these $k$ threads intersects another thread. Qed. Now, suppose we have $F$ unfilled positions total. Say $F_{odd}$ are on odd positions and $F_{even}$ are on even positions. Let $x = \\frac{n}{2} - W_{odd} - B_{even}$. Claim: Let $i\\equiv x\\pmod 2$. The number of valid, $s$-reachable colorings $c$ with $f(c)=\\frac12 |x-i|$ is equal to ${F\\choose i}$. Proof: Suppose we have a subset of $i$ unfilled positions. For the elements of the subset, we color even positions black and odd positions white. For elements outside the subset, we color even positions white and odd positions black. Say that $a$ is the number of positions in our subset on even positions. Now, $B_{even}+a$ spools will be black on even positions, and $B_{odd}+F_{odd}-i+a$ will be black on odd positions. Then $f(c)=\\frac12 \\left|(B_{even}+a)-(B_{odd}+F_{odd}-i+a)\\right|$ $=\\frac12 |B_{even}-B_{odd}-F_{odd}+i|=\\frac12 |x-i|.$ It is clear that our mapping is a bijecetion. Qed. Given our claims, we can write the expected value as such: $\\frac{1}{2^F}\\sum_{0\\le i\\le F\\atop i\\equiv x\\pmod 2} |x-i| {{F}\\choose{i}}.$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll MOD = 998244353;\nconst int mxN = 200001;\nll fact[mxN], ifact[mxN];\nll nCr(int n, int r) {\n    if(n==r)return 1;\n    if(r > n || r < 0)return 0;\n    return ((fact[n]*ifact[n-r])%MOD*ifact[r])%MOD;\n}\nll binpow(ll a,ll b) {\n    ll res=1;\n    while(b) {\n        if(b&1)res=(res*a)%MOD;\n        a=(a*a)%MOD;\n        b>>=1;\n        \n    }\n    return res;\n}\nll modInv(ll a) {\n    return binpow(a, MOD-2);\n}\nstring s;\nint n, q;\nint b[2], w[2], f[2];\nll tpow[mxN];\nll tinv[mxN];\nll ans[4]; \nll lft, func;\nvoid print() {\n    ll res = (ans[1]*lft + ans[2]*func)%MOD;\n    res = (ans[0]*func + ans[3]*lft - res + MOD)%MOD;\n    res = (res * tinv[lft])%MOD;\n    cout<<res<<\"\\n\";\n}\nvoid reset() {\n    for(int i = 0; i < 2; ++i) {\n        b[i] = w[i] = f[i] = 0;\n    }\n    ans[0] = ans[1] = ans[2] = ans[3] = 0;\n}\nvoid fix() {\n    int parity = abs(func)&1;\n    for(int i = parity; i <= min(func-2, lft); i+=2) {\n        ans[0] = (ans[0] + nCr(lft, i))%MOD;\n    }\n    for(int i = parity; i <= min(func-2, lft); i+=2) {\n        ans[1] = (ans[1] + nCr(lft-1, i-1))%MOD;\n    }\n    for(int i = func+2; i <= lft; i+=2) {\n        ans[3] = (ans[3] + nCr(lft-1, i-1))%MOD;\n    }\n    for(int i = func+2; i <= lft; i+=2) {\n        ans[2] = (ans[2] + nCr(lft, i))%MOD;\n    }\n}\nint main() {\n    fact[0] = 1;\n    tpow[0] = 1;\n    for(int i = 1; i < mxN; ++i){\n        fact[i] = (fact[i-1]*i)%MOD;\n        tpow[i] = (tpow[i-1]*2)%MOD;\n    }\n    ifact[mxN-1] = modInv(fact[mxN-1]);\n    tinv[mxN-1] = modInv(tpow[mxN-1]);\n    for(int i = mxN-2; i >= 0; --i) {\n        ifact[i] = (ifact[i+1]*(i+1))%MOD;\n        tinv[i] = (tinv[i+1]*2)%MOD;\n    }\n    cin>>n>>q>>s;\n    for(int i = 0; i < n; ++i) {\n        if(s[i]=='w') {\n            w[i&1]++;\n        }else if(s[i]=='b') {\n            b[i&1]++;\n        }else {\n            f[i&1]++;\n        }\n    }\n    lft = f[0] + f[1];\n    func = n/2 - b[1] - w[0];\n    fix();\n    print();\n    for(int i = 0; i < q; ++i) {\n        int a;\n        char c;\n        cin>>a>>c;\n        a--;\n        reset();\n        s[a] = c;\n        for(int i = 0; i < n; ++i) {\n            if(s[i]=='w') {\n                w[i&1]++;\n            }else if(s[i]=='b') {\n                b[i&1]++;\n            }else {\n                f[i&1]++;\n            }\n        }\n        lft = f[0] + f[1];\n        func = n/2 - b[1] - w[0];\n        fix();\n        print();\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "fft",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1450",
    "index": "H2",
    "title": "Multithreading (Hard Version)",
    "statement": "\\textbf{The only difference between the two versions of the problem is that there are no updates in the easy version.}\n\nThere are $n$ spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white.\n\nFor any two spools of the same color, you can attach them with a thread of that color in a straight line segment. Define a matching as a way to attach spools together so that each spool is attached to exactly one other spool.\n\nColoring is an assignment of colors (white and black) to the spools. A coloring is called \\textbf{valid} if it has at least one matching. That is if the number of black spools and the number of white spools are both even.\n\nGiven a matching, we can find the number of times some white thread intersects some black thread. We compute the number of pairs of differently colored threads that intersect instead of the number of intersection points, so one intersection point may be counted multiple times if different pairs of threads intersect at the same point. If $c$ is a valid coloring, let $f(c)$ denote the minimum number of such intersections out of all possible matchings.\n\n\\begin{center}\nThe circle above is described by the coloring bwbbbwww. After matching the spools as shown, there is one intersection between differently colored threads. It can be proven that it is the minimum possible, so $f(\\text{bwbbbwww}) = 1$.\n\\end{center}\n\nYou are given a string $s$ representing an \\textbf{unfinished} coloring, with black, white, and uncolored spools. A coloring $c$ is called $s$-reachable if you can achieve it by assigning colors to the uncolored spools of $s$ without changing the others.\n\nA coloring $c$ is chosen uniformly at random among all valid, $s$-reachable colorings. Compute the expected value of $f(c)$. You should find it by modulo $998244353$.\n\nThere will be $m$ updates to change one character of $s$. After each update, you should again compute the expected value of $f(c)$.\n\nWe can show that each answer can be written in the form $\\frac{p}{q}$ where $p$ and $q$ are relatively prime integers and $q\\not\\equiv 0\\pmod{998244353}$. The answer by modulo $998244353$ is equal to $(p\\cdot q^{-1})$ modulo $998244353$.",
    "tutorial": "Continued from Easy Version tutorial. Recall the answer is $\\frac{1}{2^F}\\sum_{0\\le i\\le F\\atop i\\equiv x\\pmod 2} |x-i| {{F}\\choose{i}}.$ Now we have to maintain this sum over updates. Let's ignore the $2^{F}$, and rewrite the sum as $\\sum_{0\\le i\\le x-2\\atop i\\equiv x\\pmod 2} x{{F}\\choose{i}} - \\sum_{0\\le i\\le x-2\\atop i\\equiv x\\pmod 2} i{{F}\\choose{i}} + \\sum_{x+2\\le i\\le F\\atop i\\equiv x\\pmod 2} i{{F}\\choose{i}} - \\sum_{x+2\\le i\\le F\\atop i\\equiv x\\pmod 2} x{{F}\\choose{i}}.$ We will transform sums of the form $i{{F}\\choose{i}}$ to sums of the form ${F\\choose i}$. We rewrite them with the following identity. $i{{F}\\choose{i}} = F{{F-1}\\choose{i-1}}$ To deal with the $i\\equiv x\\pmod 2$ condition, we use Pascal's rule to rewrite each ${F}\\choose{i}$ as ${{F-1}\\choose{i-1}} + {{F-1}\\choose{i}}$, and each sum becomes a prefix sum or suffix sum of some binomial coefficients with the same upper index. The indices change by $O(1)$ between updates, and we should handle these cases. We can handle changes to the upper index by noting the following equation, again due to Pascal's rule. $\\sum_{i=0}^{k} {{F+1}\\choose{i}} = 2\\sum_{i=0}^{k} {{F}\\choose{i}} - {{F}\\choose{k}}.$ It is easy to handle updates to the lower index by adding and subtracting some binomial coefficients when necessary. Be careful about cases where $F = 1$ since the transformed prefix sum won't consider all possibilities.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll MOD = 998244353;\nconst int mxN = 200001;\nll fact[mxN], ifact[mxN];\nll nCr(int n, int r) {\n    if(r > n || r < 0)return 0;\n    return ((fact[n]*ifact[n-r])%MOD*ifact[r])%MOD;\n}\nll binpow(ll a,ll b) {\n    ll res=1;\n    while(b) {\n        if(b&1)res=(res*a)%MOD;\n        a=(a*a)%MOD;\n        b>>=1;\n        \n    }\n    return res;\n}\nll modInv(ll a) {\n    return binpow(a, MOD-2);\n}\nstring s;\nint n, q;\nint b[2], w[2], f[2];\nll tpow[mxN];\nll tinv[mxN];\nll ans[4]; \nll lft, func;\nvoid print() {\n    ll res = (ans[1]*lft + ans[2]*func)%MOD;\n    res = (ans[0]*func + ans[3]*lft - res + MOD)%MOD;\n    res = (res * tinv[lft])%MOD;\n    cout<<res<<\"\\n\";\n}\nvoid fix() {\n    ans[0] = ans[1] = ans[2] = ans[3] = 0;\n    int parity = abs(func)&1;\n    for(int i = parity; i <= min(func-2, lft); i+=2) {\n        ans[0] = (ans[0] + nCr(lft, i))%MOD;\n    }\n    for(int i = parity; i <= min(func-2, lft); i+=2) {\n        ans[1] = (ans[1] + nCr(lft-1, i-1))%MOD;\n    }\n    for(int i = func+2; i <= lft; i+=2) {\n        ans[3] = (ans[3] + nCr(lft-1, i-1))%MOD;\n    }\n    for(int i = func+2; i <= lft; i+=2) {\n        ans[2] = (ans[2] + nCr(lft, i))%MOD;\n    }\n}\nvoid inc() { // increase the numerator\n    ans[0] = (2*ans[0] - nCr(lft-1, func-2) + MOD)%MOD;\n    ans[1] = (2*ans[1] - nCr(lft-2, func-3) + MOD)%MOD;\n    ans[2] = tpow[lft-1] - ans[2];\n    ans[2] = 2*ans[2] - nCr(lft-1, func);\n    ans[2] = ((tpow[lft] - ans[2])%MOD + MOD)%MOD;\n    ans[3] = tpow[lft-2] - ans[3];\n    ans[3] = 2*ans[3] - nCr(lft-2, func-1);\n    ans[3] = ((tpow[lft-1] - ans[3])%MOD + MOD)%MOD;\n    lft++;\n}\nvoid binc() { //increase denominator\n    ans[0] = (ans[0] + nCr(lft-1, func-1))%MOD;\n    ans[1] = (ans[1] + nCr(lft-2, func-2))%MOD;\n    ans[2] = (ans[2] - nCr(lft-1, func+1) + MOD)%MOD;\n    ans[3] = (ans[3] - nCr(lft-2, func) + MOD)%MOD;\n    func++;\n}\nvoid dec() { //decrease the numerator\n    ans[0] = ((ans[0] + nCr(lft-2, func-2))*tinv[1])%MOD;\n    ans[1] = ((ans[1] + nCr(lft-3, func-3))*tinv[1])%MOD;\n    ans[2] = tpow[lft-1] - ans[2];\n    ans[2] = ((ans[2] + nCr(lft-2, func))*tinv[1])%MOD;\n    ans[2] = (tpow[lft-2] - ans[2] + MOD)%MOD;\n    ans[3] = tpow[lft-2] - ans[3];\n    ans[3] = ((ans[3] + nCr(lft-3, func-1))*tinv[1])%MOD;\n    ans[3] = (tpow[lft-3] - ans[3] + MOD)%MOD;\n    lft--;\n}\nvoid bdec() { //decrease denominator\n    ans[0] = (ans[0] - nCr(lft-1, func-2) + MOD)%MOD;\n    ans[1] = (ans[1] - nCr(lft-2, func-3) + MOD)%MOD;\n    ans[2] = (ans[2] + nCr(lft-1, func))%MOD;\n    ans[3] = (ans[3] + nCr(lft-2, func-1))%MOD;\n    func--;\n}\nint main() {\n    fact[0] = 1;\n    tpow[0] = 1;\n    for(int i = 1; i < mxN; ++i){\n        fact[i] = (fact[i-1]*i)%MOD;\n        tpow[i] = (tpow[i-1]*2)%MOD;\n    }\n    ifact[mxN-1] = modInv(fact[mxN-1]);\n    tinv[mxN-1] = modInv(tpow[mxN-1]);\n    for(int i = mxN-2; i >= 0; --i) {\n        ifact[i] = (ifact[i+1]*(i+1))%MOD;\n        tinv[i] = (tinv[i+1]*2)%MOD;\n    }\n    cin>>n>>q>>s;\n    for(int i = 0; i < n; ++i) {\n        if(s[i]=='w') {\n            w[i&1]++;\n        }else if(s[i]=='b') {\n            b[i&1]++;\n        }else {\n            f[i&1]++;\n        }\n    }\n    lft = f[0] + f[1];\n    func = n/2 - b[1] - w[0];\n    fix();\n    print();\n    for(int i = 0; i < q; ++i) {\n        int a;\n        char c;\n        cin>>a>>c;\n        a--;\n        //uncolor\n        if(s[a]=='w') {\n            inc();\n            if((a&1)^1) binc();\n        }else if(s[a]=='b') {\n            inc();\n            if(a&1) binc();\n        }\n        //recolor\n        if(c=='w') {\n            dec();\n            if((a&1)^1) bdec();\n        }else if(c=='b') {\n            dec();\n            if(a&1) bdec();\n        }\n        s[a] = c;\n        if(lft<=2) fix();\n        print();\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "implementation",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1451",
    "index": "A",
    "title": "Subtract or Divide",
    "statement": "Ridbit starts with an integer $n$.\n\nIn one move, he can perform one of the following operations:\n\n- divide $n$ by one of its \\textbf{proper} divisors, or\n- subtract $1$ from $n$ if $n$ is greater than $1$.\n\nA proper divisor is a divisor of a number, excluding itself. For example, $1$, $2$, $4$, $5$, and $10$ are proper divisors of $20$, but $20$ itself is not.\n\nWhat is the minimum number of moves Ridbit is required to make to reduce $n$ to $1$?",
    "tutorial": "Key Idea: For $n > 3$, the answer is $2$ when $n$ is even and $3$ when $n$ is odd. Cases when $n \\leq 3$ can be handled separately. Solution: Case 1: $n \\leq 3$ For $n = 1, 2, 3$, it can be shown that the minimum number of operations required are $0$, $1$, $2$ respectively. Case 2: $n > 3$ and $n$ is even If $n$ is even and greater than $2$, then $\\frac{n}{2}$ is a proper divisor. So we can divide $n$ by $\\frac{n}{2}$ to make it $2$ and then subtract $1$. This requires $2$ operations. Case 3: $n > 3$ and $n$ is odd In this case, $n$ can be made even by subtracting $1$. From case 2, it can be seen that it will take $2$ more operations. Thus a total of $3$ operations are required. Time complexity: $O(1)$ per case",
    "code": "import java.util.*;\nimport java.util.ArrayList;\npublic class Main {\n    public static void main(String args[])\n    {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        for(int i = 0; i < t; i++)\n        {\n            int n = sc.nextInt();\n            System.out.println(Math.min(2 + (n & 1), n - 1));\n        }\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1451",
    "index": "B",
    "title": "Non-Substring Subsequence",
    "statement": "Hr0d1y has $q$ queries on a binary string $s$ of length $n$. A binary string is a string containing only characters '0' and '1'.\n\nA query is described by a pair of integers $l_i$, $r_i$ $(1 \\leq l_i \\lt r_i \\leq n)$.\n\nFor each query, he has to determine whether there exists a good subsequence in $s$ that is equal to the substring $s[l_i\\ldots r_i]$.\n\n- A substring $s[i\\ldots j]$ of a string $s$ is the string formed by characters $s_i s_{i+1} \\ldots s_j$.\n- String $a$ is said to be a subsequence of string $b$ if $a$ can be obtained from $b$ by deleting some characters without changing the order of the remaining characters.\n- A subsequence is said to be \\textbf{good} if it is not contiguous and has length $\\ge 2$. For example, if $s$ is \"1100110\", then the subsequences $s_1s_2s_4$ (\"{\\textbf{11}0\\textbf{0}110}\") and $s_1s_5s_7$ (\"{\\textbf{1}100\\textbf{1}1\\textbf{0}}\") are good, while $s_1s_2s_3$ (\"{\\textbf{110}0110}\") is not good.\n\nCan you help Hr0d1y answer each query?",
    "tutorial": "Key Idea: In each query, the answer is YES iff the first character of the given substring is not the first occurence of that character or the last character of the given substring is not the last occurrence of that character in the string. Solution: The condition stated above is both necessary and sufficient. Proof that it is necessary: Assume that a non-contiguous subsequence exists when the condition is false. If the first character of the substring is the first occurrence of its kind, then the subsequence cannot start before it. Similarly, if the last character of the substring is the last occurrence of its kind, then the subsequence cannot end after it. In such a case, the only subsequence that is of the same length as the given substring and equal to it, is the substring itself. However, this subsequence is contiguous - which is a contradiction. Thus, it is a necessary condition. Proof that it is sufficient: If the first character of the substring $s[l_i...r_i]$ occurs at some index $j$ $(j < l_i)$, then the subsequence $s_js_{l_i+1}...s_{r_i}$ is good. If the last character of the substring $s[l_i...r_i]$ occurs at some index $j$ $(j > r_i)$, then the subsequence $s_{l_i}...s_{r_i-1}s_j$ is good. Thus it is sufficient. Time complexity: $O(nq)$ or $O(n+q)$ for each case depending on implementation.",
    "code": "import java.io.*;\nimport java.util.*;\npublic class Main {\n    public static void main(String args[]) throws IOException\n    {\n        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); \n        int t = Integer.parseInt(br.readLine());\n        for(int cases = 0; cases < t; cases++)\n        {\n            StringTokenizer st = new StringTokenizer(br.readLine());\n            int n = Integer.parseInt(st.nextToken());\n            int q = Integer.parseInt(st.nextToken());\n            String s = br.readLine();\n            int fi[] = new int[2];\n            int la[] = new int[2];\n            for(int j = 0; j < 2; j++)\n            {\n                fi[j] = 2000000000;\n                la[j] = -1;\n            }\n            for(int i = 0; i < s.length(); i++)\n            {\n                int cur = (s.charAt(i) - '0');\n                fi[cur] = Math.min(fi[cur], i);\n                la[cur] = i;\n            }\n            for(int i = 0; i < q; i++)\n            {\n                st = new StringTokenizer(br.readLine());\n                int l = Integer.parseInt(st.nextToken()) - 1;\n                int r = Integer.parseInt(st.nextToken()) - 1;\n                int curl = (s.charAt(l) - '0');\n                int curr = (s.charAt(r) - '0');\n                if(fi[curl] < l || la[curr] > r)\n                    System.out.println(\"YES\\n\");\n                else\n                    System.out.println(\"NO\\n\");\n            }\n        }\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1451",
    "index": "C",
    "title": "String Equality",
    "statement": "Ashish has two strings $a$ and $b$, each of length $n$, and an integer $k$. The strings only contain lowercase English letters.\n\nHe wants to convert string $a$ into string $b$ by performing some (possibly zero) operations on $a$.\n\nIn one move, he can either\n\n- choose an index $i$ ($1 \\leq i\\leq n-1$) and swap $a_i$ and $a_{i+1}$, or\n- choose an index $i$ ($1 \\leq i \\leq n-k+1$) and if $a_i, a_{i+1}, \\ldots, a_{i+k-1}$ are \\textbf{all equal} to some character $c$ ($c \\neq$ 'z'), replace each one with the next character $(c+1)$, that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on.\n\nNote that he can perform any number of operations, and the operations can only be performed on string $a$.\n\nHelp Ashish determine if it is possible to convert string $a$ into $b$ after performing some (possibly zero) operations on it.",
    "tutorial": "Key Idea: For the answer to be YES, the frequencies of each character of the alphabet must match after performing some sequence of operations. Let $freq_{i, a}$ and $freq_{i, b}$ be the frequencies of the $i$-th character of the alphabet in strings $a$ and $b$ respectively. For each $i$ starting from \"a\", we keep exactly $freq_{i, b}$ of the occurrences and try to to convert the rest into the next character. If at any step, this is not possible, the answer is NO. Solution: Consider operations of the first type. It can be shown that after some finite sequence of swaps, we can reorder the string in any way we like. This is helpful because we do not have to worry about the characters being adjacent when we perform an operation of the second type (we can always reorder the string to allow it). In other words, only frequency of the characters matter. To convert string $a$ into string $b$, we first make the frequencies of each character of the alphabet equal, then reorder the string using operations of the first type. The former can be done as described above. If for any $i$, there are an insufficient number of occurrences ($freq_{i, a} \\lt freq_{i, b}$) or the remaining occurrences cannot all be converted into the next character, i.e. $(freq_{i, a} - freq_{i, b})$ is not a multiple of $k$, the answer is NO. Otherwise, the answer is YES. Time complexity: $O(n)$",
    "code": "import java.util.*;\nimport java.util.ArrayList;\npublic class Main {\n    public static void main(String args[])\n    {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        for(int cases = 0; cases < t; cases++)\n        {\n            int n = sc.nextInt();\n            int k = sc.nextInt();\n            sc.nextLine();\n            String a = sc.nextLine();\n            String b = sc.nextLine();\n            int have[] = new int[27];\n            int need[] = new int[27];\n            for(int i = 0; i < n; i++)\n            {\n                have[a.charAt(i) - 'a']++;\n                need[b.charAt(i) - 'a']++;\n            }\n            boolean bad = false;\n            for(int j = 25; j >= 0; j--)\n            {\n                have[j] += have[j + 1];\n                need[j] += need[j + 1];\n                if(have[j] > need[j] || (need[j] - have[j]) % k != 0)\n                    bad = true;\n            }\n            if(bad)\n                System.out.println(\"No\");\n            else\n                System.out.println(\"Yes\");\n        }\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "hashing",
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1451",
    "index": "D",
    "title": "Circle Game",
    "statement": "Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves \\textbf{first}.\n\nConsider the 2D plane. There is a token which is initially at \\textbf{$(0,0)$}. In one move a player must increase either the $x$ coordinate or the $y$ coordinate of the token by \\textbf{exactly} $k$. In doing so, the player must ensure that the token stays within a (Euclidean) distance $d$ from $(0,0)$.\n\nIn other words, if after a move the coordinates of the token are $(p,q)$, then $p^2 + q^2 \\leq d^2$ must hold.\n\nThe game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win.",
    "tutorial": "Key Idea: Let $z$ be the maximum integer such that the point $(kz, kz)$ is within the circle. If the point $(kz, k(z+1))$ is also within the circle, player 1 wins. Otherwise player 2 wins. Solution: Regardless of what move player 1 makes, player 2 can force the token to be at some point on the line $x = y$ at the end of his turn (if player 1 moves up, player 2 can move right and vice versa). Case 1: $(kz, k(z+1))$ lies outside the circle Player 2 can guarantee his victory in this fashion as player 1 will not have any moves left after reaching the point $(kz, kz)$. Player 2 wins. Case 2: $(kz, k(z+1))$ lies within the circle After player 1 makes his first move, player 2 finds himself in the same situation as player 1 did in the previous case. That is, player 1 can ensure that they reach either $(kz, k(z+1))$ or $(k(z+1), kz)$ in the same way. Points $(k(z+1), k(z+1))$ and $(kz, k(z+2))$ do not lie within the circle as by definition $d^2 \\lt k^2(z+1)^2 + k^2(z+1)^2 \\lt k^2z^2 + k^2(z+2)^2$. Thus player 2 will not have any moves left and player 1 wins.",
    "code": "import java.util.*;\nimport java.util.ArrayList;\npublic class Main {\n    public static boolean is_within(long x, long y, long dsq, long k)\n    {\n        return dsq - k * k * x * x - k * k * y * y >= 0;\n    }\n    public static void main(String args[])\n    {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n        for(int cases = 0; cases < t; cases++)\n        {\n            int d = sc.nextInt();\n            long dsq = ((long) d) * d;\n            int k = sc.nextInt();\n            int cur = 0;\n            while(is_within(cur + 1, cur + 1, dsq, k))\n                cur++;\n            if(is_within(cur + 1, cur, dsq, k))\n                System.out.println(\"Ashish\");\n            else\n                System.out.println(\"Utkarsh\");\n        }\n    }\n}",
    "tags": [
      "games",
      "geometry",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1451",
    "index": "E1",
    "title": "Bitwise Queries (Easy Version)",
    "statement": "\\textbf{The only difference between the easy and hard versions is the constraints on the number of queries.}\n\n\\textbf{This is an interactive problem.}\n\nRidbit has a hidden array $a$ of $n$ integers which he wants Ashish to guess. Note that $n$ is a \\textbf{power of two}. Ashish is allowed to ask three different types of queries. They are of the form\n\n- AND $i$ $j$: ask for the bitwise AND of elements $a_i$ and $a_j$ $(1 \\leq i, j \\le n$, $i \\neq j)$\n- OR $i$ $j$: ask for the bitwise OR of elements $a_i$ and $a_j$ $(1 \\leq i, j \\le n$, $i \\neq j)$\n- XOR $i$ $j$: ask for the bitwise XOR of elements $a_i$ and $a_j$ $(1 \\leq i, j \\le n$, $i \\neq j)$\n\nCan you help Ashish guess the elements of the array?\n\n\\textbf{In this version, each element takes a value in the range $[0, n-1]$ (inclusive) and Ashish can ask no more than $n+2$ queries.}",
    "tutorial": "Key Idea: $a + b = (a \\oplus b) + 2 * (a \\& b)$ Pick and distinct $i, j, k$ and find $a_{i} + a_{j} = x$, $a_{i} + a_{k} = y$ and $a_{j} + a_{k} = z$ by querying their XOR and AND values ($6$ queries). This is a system of linear equation with three equations and three variables and thus us a unique solution. Solving it you get the values of $a_{i}$, $a_{j}$, and $a_{k}$. You can then get the remaining $n - 3$ values using $n - 3$ more queries. This uses a total of $n + 3$ queries. Realize that $a_{j}$ $\\oplus$ $a_{k}$ $=$ ($a_{i}$ $\\oplus$ $a_{j}$) $\\oplus$ ($a_{i}$ $\\oplus$ $a_{k}$) to reduce the number of initial queries from $6$ to $5$, for a total of $n + 2$ queries. Solution: Lets take a look at the properties of the 3 operations we have, specifically what information we can recover from it. AND - lossy in information about bits that are on, cant be used to recover the values OR - lossy in information about bits that are off, cant be used to recover the values XOR - lossless, a $\\oplus$ (a $\\oplus$ b) gives us b again. So clearly xor operations are going to be the core of recovering the values. If we can find one of the values, we can find the remaining $n - 1$ values using xor queries. But how do we get that first value? Lets try to think about this for a operation for which we know how to obtain the individual values - addition. If we had $a + b = x$, $a + c = y$ and $b + c = z$, we could just solve the three linear equations to obtain the answer. So what's the difference between xor and addition anyway? If the $i$-th bit is off in both the numbers, xor and addition both give 0. If the $i$-th bit is on in exactly oneof the numbers, xor and addition will both give $2^{i}$ . But what about if the $i$-th bit is on in the both the numbers? Then addition contributes $2 * 2^{i}$ to the answer while xor contributes 0. Is there some way to recover this value? Well if $i$-th bit is on in the both the numbers, the AND will contribute $2^{i}$ to the answer. So we can realize that $a + b$ can be rewritten as (a $\\oplus$ $b$) + $2 \\times$ (a $\\&$ b). So now if we just choose positions $1$, $2$ and $3$, we can obtain $x = a_{1} + a_{2}$, $y = a_{1} + a_{3}$ and $z = a_{2} + a_{3}$ using $3$ XOR and $3$ AND operations. Furthermore we can realize that $a_{2}$ $\\oplus$ $a_{3}$ is just ($a_{1}$ $\\oplus$ $a_{2}$) $\\oplus$ ($a_{1}$ $\\oplus$ $a_{3}$), so we can save one more operation. Now solving the above simultaneous equations, we get $a_{1}$ = $\\frac{x + y - z}{2}$. Now for $2 \\leq i \\leq n$, $a_{i}$ is just $a_{1}$ $\\oplus$ ($a_{1}$ $\\oplus$ $a_{i}$). We already calculated $a_{1}$ $\\oplus$ $a_{2}$ and $a_{1}$ $\\oplus$ $a_{3}$ for the previous step, and can calculate the remaining xor values in $n - 3$ steps. So in total we use exactly $5 + (n - 3)$ = $n + 2$ queries, which is enough to get AC.",
    "code": "import java.util.Scanner;\n \npublic class Main {\n    public static int queries(String s, Scanner sc)\n    {\n        System.out.println(s);\n        System.out.flush();\n        int x = sc.nextInt();\n        if(x == -1)\n            System.exit(0);\n        return x;\n    }\n    public static void main(String args[])\n    {\n        Scanner sc = new Scanner(System.in);\n        int n = sc.nextInt();\n        int xorvals[] = new int[n + 1];\n        int ans[] = new int[n + 1];\n        for(int i = 2; i <= n; i++)\n            xorvals[i] = queries(\"XOR 1 \" + i, sc);\n        int xor12 = xorvals[2], xor13 = xorvals[3], xor23 = xorvals[2] ^ xorvals[3];\n        int and12, and13, and23;\n        and12 = queries(\"AND 1 2\", sc);\n        and13 = queries(\"AND 1 3\", sc);\n        and23 = queries(\"AND 2 3\", sc);\n        int x = xor12 + 2 * and12;\n        int y = xor13 + 2 * and13;\n        int z = xor23 + 2 * and23;\n        assert((x + y - z) % 2 == 0);\n        ans[1] = (x + y - z) / 2;\n        for(int i = 2; i <= n; i++)\n            ans[i] = (xorvals[i] ^ ans[1]);\n        System.out.print(\"! \");\n        for(int i = 1; i <= n; i++)\n            System.out.print(ans[i] + \" \");\n        System.out.println();\n        System.out.flush();\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1451",
    "index": "E2",
    "title": "Bitwise Queries (Hard Version)",
    "statement": "\\textbf{The only difference between the easy and hard versions is the constraints on the number of queries.}\n\n\\textbf{This is an interactive problem.}\n\nRidbit has a hidden array $a$ of $n$ integers which he wants Ashish to guess. Note that $n$ is a \\textbf{power of two}. Ashish is allowed to ask three different types of queries. They are of the form\n\n- AND $i$ $j$: ask for the bitwise AND of elements $a_i$ and $a_j$ $(1 \\leq i, j \\le n$, $i \\neq j)$\n- OR $i$ $j$: ask for the bitwise OR of elements $a_i$ and $a_j$ $(1 \\leq i, j \\le n$, $i \\neq j)$\n- XOR $i$ $j$: ask for the bitwise XOR of elements $a_i$ and $a_j$ $(1 \\leq i, j \\le n$, $i \\neq j)$\n\nCan you help Ashish guess the elements of the array?\n\n\\textbf{In this version, each element takes a value in the range $[0, n-1]$ (inclusive) and Ashish can ask no more than $n+1$ queries.}",
    "tutorial": "Key Idea: Query the $n - 1$ xor values of the form $(1, i)$, for $2 \\leq i \\leq n$ initially. Since numbers lie in the range $[0, n - 1]$, one of two cases can arise: 1. There exists indices j, k such that $a_{j} = a_{k}$. This can be found as $a_{i}$ $\\oplus$ $a_{j}$ $=$ $a_{i}$ $\\oplus$ $a_{k}$. So we can just use the query $a_{j}$ $\\&$ $a_{k}$ to get the value of $a_{j}$. Now we can find the remaining values using the xor values previous queried in$(n - 1) + 1 = n$ queries. 2. All integers in the range $[0, n - 1]$ are present. There exists (several) pairs $j, k$ such that $a_{j}$ $\\oplus$ $a_{k}$ $=$ $n - 1$. This implies that neither of the numbers have any bits in common and as such $a_{j}$ $\\&$ $a_{k}$ $=$ $0$, allowing us to save one query compared to E1. Thus we need $(n - 1) + 3 - 1 = (n + 1)$ queries. Solution: Now we have to eliminate $1$ more query but we are yet to use the info that all values of a are in the range $[0, n - 1]$. It may be tempting to try to remove a xor query, but it is unlikely this will work, as we would not be able differentiate between two arrays which are equal in $n - 1$ places and differ in the position we didn't check. As such it doesn't seem probable that we can recover the exact value if we don't use $n - 1$ xor operations. Since we'll need them anyway, lets go ahead and find $a_{1}$ $\\oplus$ $a_{i}$ for all $2 \\leq i \\leq n$. Then clearly we have to eliminate $1$ of the $3$ AND queries. Since numbers lie in the range $[0, n - 1]$, one of two cases must arise: At least one value is repeated. Clearly if $a_{1}$ $\\oplus$ $a_{j} = a_{1}$ $\\oplus$ $a_{k}$, then $a_{j} = a_{k}$. So we can use the already queried xor values to check if there exists two such values. Its easy to see that $x$ $\\&$ $x$ is $x$ itself, so we can get the value of $a_{j}$ using the query $a_{j}$ $\\&$ $a_{k}$. Now we can just the xor values to find the remaining values. This needs $(n - 1) + 1 = n$ queries. All integers in the range $[0, n - 1]$ are present. We're trying to find a pair of values $(a_{j}, a_{k})$ for which we can find $a_{j}$ $\\&$ $a_{k}$ without needing to query it. However we don't have any equal pair like the last case. The next easiest value that comes to mind would be $0$. Can we easily select a pair with AND value zero based on just the info we currently have? Well if the $i$-th bit of $a_{j}$ $\\oplus$ $a_{k}$ is on, then it must undoubtedly have been on in either $a_{j}$ or $a_{k}$, not both. But we can't make any such statements about a bit being off, since the bit could be off in both (satisfying the condition), or on in both (doesn't satisfy nonzero AND). So can we choose a pair $(a_{j}, a_{k})$ such that all bits are on? Yes we can, this value will be $n - 1$ since $n$ is a power of $2$ and there will be $\\frac{n}{2}$ pairs which equal it ($(0, n - 1)$, $(1, n - 2)$, $(2, n - 3)$, etc). So we can just find any one pair such that $a_{j}$ $\\oplus$ $a_{k}$ $=$ $n - 1$. Now we know $a_{j}$ $\\&$ $a_{k}$ $=$ $0$ and can reduce the number of required AND queries by $1$. So we will need $(n - 1) + 3 - 1 = (n + 1)$ queries. We're trying to find a pair of values $(a_{j}, a_{k})$ for which we can find $a_{j}$ $\\&$ $a_{k}$ without needing to query it. However we don't have any equal pair like the last case. The next easiest value that comes to mind would be $0$. Can we easily select a pair with AND value zero based on just the info we currently have? Well if the $i$-th bit of $a_{j}$ $\\oplus$ $a_{k}$ is on, then it must undoubtedly have been on in either $a_{j}$ or $a_{k}$, not both. But we can't make any such statements about a bit being off, since the bit could be off in both (satisfying the condition), or on in both (doesn't satisfy nonzero AND). So can we choose a pair $(a_{j}, a_{k})$ such that all bits are on? Yes we can, this value will be $n - 1$ since $n$ is a power of $2$ and there will be $\\frac{n}{2}$ pairs which equal it ($(0, n - 1)$, $(1, n - 2)$, $(2, n - 3)$, etc). So we can just find any one pair such that $a_{j}$ $\\oplus$ $a_{k}$ $=$ $n - 1$. Now we know $a_{j}$ $\\&$ $a_{k}$ $=$ $0$ and can reduce the number of required AND queries by $1$. So we will need $(n - 1) + 3 - 1 = (n + 1)$ queries. It is easy to see that these two cases cover all situations possible and in both cases we can find the answer in at max $(n + 1)$ queries which is enough to get AC.",
    "code": "import java.util.*;\nimport java.util.ArrayList;\npublic class Main {\n    public static int queries(String s, int i, int j, Scanner sc)\n    {\n        System.out.println(s + \" \" + i + \" \" + j);\n        System.out.flush();\n        int x = sc.nextInt();\n        if(x == -1)\n            System.exit(0);\n        return x;\n    }\n    public static void main(String args[])\n    {\n        Scanner sc = new Scanner(System.in);\n        int n = sc.nextInt();\n        ArrayList<Integer> pos[] = new ArrayList[n + 1];\n        for(int i = 0; i <= n; i++)\n            pos[i] = new ArrayList<Integer>();\n        int xorvals[] = new int[n + 1];\n        int ans[] = new int[n + 1];\n        xorvals[1] = 0;\n        pos[0].add(1);\n        for(int i = 2; i <= n; i++)\n        {\n            xorvals[i] = queries(\"XOR\", 1, i, sc);\n            pos[xorvals[i]].add(i);\n        }\n        int a = 1, b = -1, c = -1;\n        int same = -1;\n        for(int i = 0; i < n; i++)\n        if(pos[i].size() > 1)\n            {\n                b = pos[i].get(0);\n                c = pos[i].get(1);\n                same = i;\n            }\n        if(same == -1)\n        {\n            // If a_b ^ a_c == n - 1, then a_b & a_c = 0 \n            for(int i = 2; i <= 3; i++)\n                for(int j = i + 1; j <= n; j++)\n                    if((xorvals[i] ^ xorvals[j]) == n - 1)\n                    {\n                        b = i;\n                        c = j;\n                    }\n            assert(b != -1 && c != -1);\n            int xorab = xorvals[a] ^ xorvals[b], xorac = xorvals[a] ^ xorvals[c], xorbc = xorvals[b] ^ xorvals[c];\n            int andab = queries(\"AND\", a, b, sc);\n            int andac = queries(\"AND\", a, c, sc);\n            int andbc = 0;\n            int x = xorab + 2 * andab;\n            int y = xorac + 2 * andac;\n            int z = xorbc + 2 * andbc;\n            assert((x + y - z) % 2 == 0);\n            ans[a] = (x + y - z) / 2;\n        }\n        else\n        {\n            // if a_1 ^ a_b == a_1 ^ a_c, then a_b = a_c = (a_b & a_c)\n            ans[b] = queries(\"AND\", b, c, sc);\n            ans[1] = xorvals[b] ^ ans[b];\n        }\n        for(int i = 2; i <= n; i++)\n            ans[i] = (xorvals[i] ^ ans[1]);\n        System.out.print(\"! \");\n        for(int i = 1; i <= n; i++)\n            System.out.print(ans[i] + \" \");\n        System.out.println();\n        System.out.flush();\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1451",
    "index": "F",
    "title": "Nullify The Matrix",
    "statement": "Jeel and Ashish play a game on an $n \\times m$ matrix. The rows are numbered $1$ to $n$ from top to bottom and the columns are numbered $1$ to $m$ from left to right. They play turn by turn. Ashish goes \\textbf{first}.\n\nInitially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform \\textbf{all} of the following actions in order.\n\n- Choose a starting cell $(r_1, c_1)$ with \\textbf{non-zero} value.\n- Choose a finishing cell $(r_2, c_2)$ such that $r_1 \\leq r_2$ and $c_1 \\leq c_2$.\n- Decrease the value of the starting cell by some positive non-zero integer.\n- Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:\n\n- a shortest path is one that passes through the least number of cells;\n- all cells on this path \\textbf{excluding} the starting cell, but the finishing cell may be modified;\n- the resulting value of each cell must be a non-negative integer;\n- the cells are modified independently and not necessarily by the same value.\n\nIf the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.\n\nThe game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.\n\nGiven the initial matrix, if both players play optimally, can you predict who will win?",
    "tutorial": "Let's consider diagonals $d$ of the form $r+c$ - the diagonals where the sum of row index $(r)$ and column index $(c)$ is constant. Then xor of a diagonal $d$ will be $xor(d) = a(r_1,c_1)\\oplus a(r_2,c_2)\\oplus...a(r_n,c_n)$, such that $r_1 + c_1 = d$, $r_2 + c_2 = d$, .... $r_n + c_n = d$. $Solution:$ If $\\forall d,\\hspace{0.1cm}xor(d) = 0$ at the start of the game, then Jeel wins. Else, Ashish wins. $Proof:$ Let's define two states $S$ and $S'$: $S$ : $\\forall d,\\hspace{0.1cm}xor(d) = 0$ $S'$ : $\\exists d,\\hspace{0.1cm}xor(d) \\ne 0$ $Lemma\\hspace{0.1cm}1:$ Any move on $S$ converts the matrix to $S'$. $Proof:$ If we are in state $S$, $xor(r1 + c1)=0$. Since, we need to anyhow decrease value of $(r1, c1)$, $xor(r1 + c1)$ will become non-zero. Hence, any move on $S$ converts the matrix to $S'$. $Lemma\\hspace{0.1cm}2:$ There always exists a move on $S'$ to convert it to $S$. $Proof:$ If we are given an $S'$ state, we can convert it into $S$ as follows: Note that the diagonals between $(r1 + c1)$ and $(r2 + c2)$ can be arbitrarily changed to any value. $(r1, c1)$ can only be decreased in value. Let $(r1 + c1)$ be such a diagonal that there is no diagonal $d < r1 + c1$ with $xor(d) != 0$. Also, in order to ensure that we can make $xor(r1 + c1) = 0$ by decreasing, we select such a cell $(r1, c1)$ whose largest set bit is equal to the largest set bit of $xor(r1 + c1)$. In this way, we ensure that diagonal $r1 + c1$ can be made $0$. Now, we need to fix $(r2, c2)$. Let's fix $(r2, c2)$ such that there is no diagonal $d > r2 + c2$, such that $xor(d) != 0$. Since, (r2, c2) can be increased as well as decreased, we can easily make $xor(r2 + c2) = 0$. The diagonals in between can be arbitarily changed, so making them $0$ is trivial. At the end of this move, all diagonals have become $0$. Hence, given a state $S'$, we can always convert it to $S$. Due to $Lemma\\hspace{0.1cm}1$ and $Lemma\\hspace{0.1cm}2$, a person starting on state $S'$ can always stay at $S'$ and can always force the opponent to start on state $S$. Since the state at the end of the game will be $S$, the opponent will always lose. Complexity: $O(n * m)$",
    "code": "import java.util.*;\n \npublic class NullifyTheMatrix {\n    public static void main(String[] args) {\n        Scanner sc = new Scanner(System.in);\n        int t = sc.nextInt();\n \n        for(int x = 0; x < t; ++x) {\n            int n = sc.nextInt();\n            int m = sc.nextInt();\n \n            int mat[][] = new int[n][m];\n            for(int i = 0; i < n; ++i) {\n                for(int j = 0; j < m; ++j)\n                    mat[i][j] = sc.nextInt();\n            }\n \n            int xors[] = new int[n + m - 1];\n            for(int i = 0; i < n; ++i) {\n                for(int j = 0; j < m; ++j)\n                    xors[i + j] ^= mat[i][j];\n            }\n \n            int flag = 0;\n            for(int xor : xors) {\n                flag |= xor != 0 ? 1 : 0;\n            }\n \n            if(flag == 1)\n                System.out.println(\"Ashish\");\n            else\n                System.out.println(\"Jeel\");\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "games"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1452",
    "index": "A",
    "title": "Robot Program",
    "statement": "There is an infinite 2-dimensional grid. The robot stands in cell $(0, 0)$ and wants to reach cell $(x, y)$. Here is a list of possible commands the robot can execute:\n\n- move north from cell $(i, j)$ to $(i, j + 1)$;\n- move east from cell $(i, j)$ to $(i + 1, j)$;\n- move south from cell $(i, j)$ to $(i, j - 1)$;\n- move west from cell $(i, j)$ to $(i - 1, j)$;\n- stay in cell $(i, j)$.\n\nThe robot wants to reach cell $(x, y)$ in as few commands as possible. However, he can't execute the same command two or more times in a row.\n\nWhat is the minimum number of commands required to reach $(x, y)$ from $(0, 0)$?",
    "tutorial": "Obviously, you can always obtain the optimal answer without using west or south moves. So the shortest path consists of $x$ east moves and $y$ north moves. Let's estimate the lower bound of the answer. Take a look at these constructions: \"E?E?E?E?E\" and \"N?N?N?N?N\" (let question mark be any command different from the used one). That's the tightest you can put east or north moves in. So the answer is at least $2 \\cdot max(x, y) - 1$. For $x \\neq y$ you can put them just as in the construction and fill the rest of question marks with a stay in place move. $x = y$ case works differently, though. You can do it only in $x + y$ moves by taking alternating moves. Overall complexity: $O(1)$ per testcase.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n        int ans = max(x, y) * 2 - 1;\n        if(x == y) ans++;\n        cout << ans << endl;\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1452",
    "index": "B",
    "title": "Toy Blocks",
    "statement": "You are asked to watch your nephew who likes to play with toy blocks in a strange way.\n\nHe has $n$ boxes and the $i$-th box has $a_i$ blocks. His game consists of two steps:\n\n- he chooses an arbitrary box $i$;\n- he tries to move \\textbf{all} blocks from the $i$-th box to other boxes.\n\nIf he can make the same number of blocks in each of $n - 1$ other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box $i$ he chooses he won't be sad. What is the minimum number of extra blocks you need to put?",
    "tutorial": "Since nephew emptying the box $i$ he's chosen and wants to make all other $n - 1$ box equal then it means that at least the $sum$ of all array $a$ should be divisible by $(n - 1)$ and the number of blocks in each other box should be at least $\\left\\lceil \\frac{sum}{n - 1} \\right\\rceil$ (ceiling function). On the other side, since nephew chooses $i$ (not you), then he can choose a box which is not a maximum $max$, and since he makes empty the only box $i$, then the final number in each other block should be at least $max$. In total, the resulting number of blocks in each of $n - 1$ other boxes should be at least $k = \\max(\\left\\lceil \\frac{sum}{n - 1} \\right\\rceil, max)$ and we need to add at least $(n - 1) \\cdot k - sum$ elements to the initial array. We can always reach this lower bound if we will put each block in the box with the current minimum number of blocks.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val a = readLine()!!.split(' ').map { it.toLong() }\n\n        val k = maxOf(a.max()!!, (a.sum() + n - 2) / (n - 1))\n        println(k * (n - 1) - a.sum())\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1452",
    "index": "C",
    "title": "Two Brackets",
    "statement": "You are given a string $s$, consisting of brackets of two types: '(', ')', '[' and ']'.\n\nA string is called a regular bracket sequence (RBS) if it's of one of the following types:\n\n- empty string;\n- '(' + RBS + ')';\n- '[' + RBS + ']';\n- RBS + RBS.\n\nwhere plus is a concatenation of two strings.\n\nIn one move you can choose a non-empty subsequence of the string $s$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.\n\nWhat is the maximum number of moves you can perform?",
    "tutorial": "Notice that it's never optimal to erase a subsequence of length greater than $2$ because every RBS of length above $2$ contains an RBS of length $2$ inside and removing it won't break the regular property of the outside one. So the task can be solved for the round and the square brackets independently, the answer will be the sum of both. Let's solve the version for brackets '(' and ')'. In general, you just want to remove consecutive substring \"()\" until there is no more left in the string. That can be done by processing the string from left and right and maintaining a stack of current brackets. If the top bracket in it is '(' and the current bracket is ')', then you can increment the answer and remove that bracket from the stack. Otherwise, you push the current bracket to the stack. Overall complexity: $O(|s|)$ per testcase.",
    "code": "def calc(s, x, y):\n\tbal, cnt = 0, 0\n\tfor c in s:\n\t\tif c == y:\n\t\t\tif bal > 0:\n\t\t\t\tbal -= 1\n\t\t\t\tcnt += 1\n\t\telif c == x:\n\t\t\tbal += 1\n\treturn cnt\n\nfor _ in range(int(input())):\n\ts = input()\n\tprint(calc(s, '(', ')') + calc(s, '[', ']'))",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1452",
    "index": "D",
    "title": "Radio Towers",
    "statement": "There are $n + 2$ towns located on a coordinate line, numbered from $0$ to $n + 1$. The $i$-th town is located at the point $i$.\n\nYou build a radio tower in each of the towns $1, 2, \\dots, n$ with probability $\\frac{1}{2}$ (these events are independent). After that, you want to set the signal power on each tower to some integer from $1$ to $n$ (signal powers are not necessarily the same, but also not necessarily different). The signal from a tower located in a town $i$ with signal power $p$ reaches every city $c$ such that $|c - i| < p$.\n\nAfter building the towers, you want to choose signal powers in such a way that:\n\n- towns $0$ and $n + 1$ don't get any signal from the radio towers;\n- towns $1, 2, \\dots, n$ get signal from exactly one radio tower each.\n\nFor example, if $n = 5$, and you have built the towers in towns $2$, $4$ and $5$, you may set the signal power of the tower in town $2$ to $2$, and the signal power of the towers in towns $4$ and $5$ to $1$. That way, towns $0$ and $n + 1$ don't get the signal from any tower, towns $1$, $2$ and $3$ get the signal from the tower in town $2$, town $4$ gets the signal from the tower in town $4$, and town $5$ gets the signal from the tower in town $5$.\n\nCalculate the probability that, after building the towers, you will have a way to set signal powers to meet all constraints.",
    "tutorial": "The crucial observation is that when the positions of towers are fixed, the way to set their signal powers is unique if it exists. That's because the first tower should have its signal power exactly equal to the required to cover all towns before it, the second tower should have signal power exactly equal to the required to cover all towns before it that weren't covered by the first one, and so on. So let's count the number of ways to cover all towns, and then divide it by $2^n$. Covering all towns can be expressed as splitting $n$ into the sum of several positive odd integers. It can be calculated with dynamic programming with prefix sums, but we can also prove that the number of ways to split $n$ is exactly the $n$-th integer in the Fibonacci sequence as follows (this proof uses mathematical induction): for $n \\le 2$, it's quite obvious; for $n > 2$ and $n \\bmod 2 = 0$, let's iterate on the length of the last segment. We have to sum $F_1 + F_3 + \\dots + F_{n - 1}$; $F_1 + F_3 = 1 + 2 = F_4$; $F_4 + F_5 = F_6$; $F_6 + F_7 = F_8$, and so on, until we get $F_{n - 2} + F_{n - 1} = F_n$; for $n > 2$ and $n \\bmod 2 = 1$, let's iterate on the length of the last segment, and add $1$ to result since we can cover everything with a single segment. So, this is $1 + F_2 + F_4 + F_6 + \\dots + F_{n - 1}$. $1 + F_2 = F_3$, $F_3 + F_4 = F_5$, and so on. So, the answer to the problem is $\\dfrac{F_n}{2^n}$. The last thing we have to consider is that we have to print a fraction modulo $998244353$. Since $998244353$ is a prime, using Fermat little theorem, we can calculate $y^{-1}$ as $y^{998244351} \\bmod 998244353$. Exponentiation must be done with some fast algorithm (for example, binary exponentiation). Note: it's common in problems requiring to calculate something modulo some prime number to have problems with overflow in intermediate calculations or some other issues when we forget to take the result of some expression modulo $998244353$. I recommend using either special addition/multiplication/exponentiation functions that always take the result modulo $998244353$ (an example how to write and use them can be viewed in the model solution), or a special modular integer data structure with overloaded operators that you have to implement by yourself.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int ans = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1)\n            ans = mul(ans, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return ans;\n}\n\nint divide(int x, int y)\n{\n    return mul(x, binpow(y, MOD - 2));\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n    vector<int> fib(n + 1);\n    fib[0] = 0;\n    fib[1] = 1;\n    for(int i = 2; i <= n; i++)\n        fib[i] = add(fib[i - 1], fib[i - 2]);\n    cout << divide(fib[n], binpow(2, n)) << endl;    \n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1452",
    "index": "E",
    "title": "Two Editorials",
    "statement": "Berland regional ICPC contest has just ended. There were $m$ participants numbered from $1$ to $m$, who competed on a problemset of $n$ problems numbered from $1$ to $n$.\n\nNow the editorial is about to take place. There are two problem authors, each of them is going to tell the tutorial to \\textbf{exactly $k$ consecutive tasks} of the problemset. The authors choose the segment of $k$ consecutive tasks for themselves independently of each other. The segments can coincide, intersect or not intersect at all.\n\nThe $i$-th participant is interested in listening to the tutorial of all consecutive tasks from $l_i$ to $r_i$. Each participant always chooses to listen to only the problem author that tells the tutorials to the maximum number of tasks he is interested in. Let this maximum number be $a_i$. No participant can listen to both of the authors, even if their segments don't intersect.\n\nThe authors want to choose the segments of $k$ consecutive tasks for themselves in such a way that the sum of $a_i$ over all participants is maximized.",
    "tutorial": "Consider some participant's segment $[l; r]$ and one of the author's segment $[i; i + k - 1]$. How does the length of intersection change when you move $i$ from left to right? It first increases until the centers of both segments coincide (that's the easiest to notice on the segments of the same length) and then decreases. The increase is totally symmetrical to the decrease. With that idea you can conclude that the author's segment, whose center is the closest to the center of participant's segment, has the larger intersection length. Let's sort the participants' segments by their center. You can see that the first author will be optimal for the prefix of the segments and the second author - for the remaining suffix. So you can just iterate over the length of the prefix and update the answer with all options. Overall complexity: $O(n \\log n + nm)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct seg{\n\tint l, r;\n};\n\nint main() {\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tvector<seg> a(m);\n\tforn(i, m){\n\t\tcin >> a[i].l >> a[i].r;\n\t\t--a[i].l;\n\t}\n\tsort(a.begin(), a.end(), [](const seg &a, const seg &b){\n\t\treturn a.l + a.r < b.l + b.r;\n\t});\n\tvector<int> su(m + 1);\n\tforn(i, n - k + 1){\n\t\tint cur = 0;\n\t\tfor (int j = m - 1; j >= 0; --j){\n\t\t\tcur += max(0, min(i + k, a[j].r) - max(i, a[j].l));\n\t\t\tsu[j] = max(su[j], cur);\n\t\t}\n\t}\n\tint ans = su[0];\n\tforn(i, n - k + 1){\n\t\tint cur = 0;\n\t\tforn(j, m){\n\t\t\tcur += max(0, min(i + k, a[j].r) - max(i, a[j].l));\n\t\t\tans = max(ans, cur + su[j + 1]);\n\t\t}\n\t}\n\tcout << ans << endl;\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1452",
    "index": "F",
    "title": "Divide Powers",
    "statement": "You are given a multiset of powers of two. More precisely, for each $i$ from $0$ to $n$ exclusive you have $cnt_i$ elements equal to $2^i$.\n\nIn one operation, you can choose any one element $2^l > 1$ and divide it into two elements $2^{l - 1}$.\n\nYou should perform $q$ queries. Each query has one of two types:\n\n- \"$1$ $pos$ $val$\" — assign $cnt_{pos} := val$;\n- \"$2$ $x$ $k$\" — calculate the minimum number of operations you need to make at least $k$ elements with value lower or equal to $2^x$.\n\nNote that all queries of the second type don't change the multiset; that is, you just calculate the minimum number of operations, you don't perform them.",
    "tutorial": "Several observations: Generally, we have two types of operations: divide $2^l$ and either $l \\le x$ or $l > x$. If $2^l \\le 2^x$ then in one division we'll get $+1$ element $\\le 2^x$, so we can just keep track of the total possible number of these operations as $small$. If $2^l > 2^x$ then if we decide to split whole $2^l$ to $2^x$-s then we get $+2^{l - x}$ elements $\\le 2^x$ but in $2^{l - x} - 1$ operations, i. e. in one division we'll get $+\\frac{2^{l-x}}{2^{l-x} - 1} > 1$ elements. So it's preferably to fully split $2^l > 2^x$ than $2^l \\le 2^x$. Also, the less $l > x$ - the more profitable each division. As a result, let's act greedy: let's say, we need $k$ more elements $\\le 2^x$. Let's iterate over $2^l > 2^x$ in the increasing order. If $2^{l - x} \\le k$ then let's fully split $2^l$ in $2^x$ in $2^{l - x} - 1$ operations, decrease $k$, increase a counter of operations $cur$ and increase $small$ accordingly. If $2^{l - x} > k$ then the situation becomes complicated. We can either don't touch $2^l$ and try to use preserved operations with small $2^j$ if $small \\ge k$, or split $2^l$ in two $2^{l - 1}$-s. Now we spent one operation and get two $2^{l-1}$. If $2^{l - 1 - x} > k$ then we don't need one of $2^{l - 1}$ and can split further only one $2^{l - 1}$. If $2^{l - 1 - x} \\le k$ then it's optimal to fully split one of $2^{l - 1}$ and proceed further with only one $2^{l - 1}$ and recalculated $k$, $cur$ and $small$. In both cases we can solve optimal splitting of $2^{l - 1}$ recursively in the same manner as $2^l$. Since in each step we lower $l$ then we need to check only $O(n)$ cases per each query. If $2^{l - 1 - x} > k$ then we don't need one of $2^{l - 1}$ and can split further only one $2^{l - 1}$. If $2^{l - 1 - x} \\le k$ then it's optimal to fully split one of $2^{l - 1}$ and proceed further with only one $2^{l - 1}$ and recalculated $k$, $cur$ and $small$. Note, that we can treat situation $1$ ($2^{l - x} \\le k$) in packs for several $2^l$ with equal $l$, so the first part also works in $O(n)$. The resulting complexity is $O(n)$ per query.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nint n, q;\nvector<li> cnt;\n\ninline bool read() {\n\tif(!(cin >> n >> q))\n\t\treturn false;\n\tcnt.assign(n, 0);\n\tfore (i, 0, n)\n\t\tcin >> cnt[i];\n\treturn true;\n}\n\ninline void solve() {\n\tfore (qs, 0, q) {\n\t\tint tp, pos;\n\t\tli val;\n\t\tcin >> tp >> pos >> val;\n\t\tif (tp == 1) {\n\t\t\tcnt[pos] = val;\n\t\t} else {\n\t\t\tli small = 0, cur = 0;\n\t\t\tfore (i, 0, pos + 1) {\n\t\t\t\tsmall += cnt[i] * ((1ll << i) - 1);\n\t\t\t\tval -= cnt[i];\n\t\t\t}\n\t\t\tif (val <= 0) {\n\t\t\t\tcout << 0 << '\\n';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tint id = pos + 1;\n\t\t\twhile (id < n) {\n\t\t\t\tli add = 1ll << (id - pos);\n\t\t\t\tli need = min(val / add, cnt[id]);\n\t\t\t\tcur += need * (add - 1);\n\t\t\t\tval -= need * add;\n\t\t\t\tsmall += need * add * ((1ll << pos) - 1);\n\t\t\t\t\n\t\t\t\tif (need == cnt[id])\n\t\t\t\t\tid++;\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (val <= 0) {\n\t\t\t\tcout << cur << '\\n';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (id >= n) {\n\t\t\t\tcout << (val > small ? -1 : cur + val) << '\\n';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tli ans = INF64;\n\t\t\twhile (id > pos) {\n\t\t\t\tif (small >= val)\n\t\t\t\t\tans = min(ans, cur + val);\n\t\t\t\tcur++;\n\t\t\t\tid--;\n\t\t\t\tli add = 1ll << (id - pos);\n\t\t\t\tif (val >= add) {\n\t\t\t\t\tcur += add - 1;\n\t\t\t\t\tval -= add;\n\t\t\t\t\tsmall += add * ((1ll << pos) - 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(val <= 0);\n\t\t\tcout << min(ans, cur) << endl;\n\t\t}\n\t}\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1452",
    "index": "G",
    "title": "Game On Tree",
    "statement": "Alice and Bob are playing a game. They have a tree consisting of $n$ vertices. Initially, Bob has $k$ chips, the $i$-th chip is located in the vertex $a_i$ (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree.\n\nThe game consists of turns. Each turn, the following events happen (sequentially, exactly in the following order):\n\n- Alice either moves her chip to an adjacent vertex or doesn't move it;\n- for each Bob's chip, he either moves it to an adjacent vertex or doesn't move it. Note that this choice is done independently for each chip.\n\nThe game ends when Alice's chip shares the same vertex with one (or multiple) of Bob's chips. Note that Bob's chips may share the same vertex, even though they are in different vertices at the beginning of the game.\n\nAlice wants to maximize the number of turns, Bob wants to minimize it. If the game ends in the middle of some turn (Alice moves her chip to a vertex that contains one or multiple Bob's chips), this turn is counted.\n\nFor each vertex, calculate the number of turns the game will last if Alice places her chip in that vertex.",
    "tutorial": "This task was inspired by an older edu task and another task proposed by RockyB. Let's learn to solve the problem for at least one starting vertex for Alice. Let this vertex be $v$. In general, Alice's strategy is basically this: run to some vertex $u$ as fast as possible and stay in it until Bob reaches $u$. Hesitation on a way to this vertex won't be optimal. Visiting the same vertex multiple times won't as well. I guess that can be proven more formally by analyzing the set of possible solutions after each move. What properties should vertex $u$ have for Alice to be able to escape to it? There shouldn't be a way for Bob to catch her midway. However, it's not necessary to check any midway intersections. If Bob can catch her anywhere on a path, she can also follow her to the end (by moving the same path) and catch her at the destination. Thus, this vertex $u$ should be further from any Bob's chips than from $v$. So you can precalculate the distance to the closest Bob's chip $d_w$ to each vertex $w$. Just push all chips to a queue and run a bfs. We've learned to solve the problem in $O(n)$ for each vertex $v$. Just iterate over all vertices $u$ and take the maximum of $d_u$ over such of them that have $d_u$ greater than the distance from $v$ to $u$. Now the solution can go two ways. You can stop thinking here and obtain an $O(n \\log^2 n)$ one or think more and get an $O(n \\log n)$. The first one goes like that. Notice that the function $f(v, x)$ if the Alice can make at least $x$ moves from vertex $v$ is monotonous in regard to $x$. So we can binary search the answer. The check query transforms to the following. Consider all vertices with distance less or equal to $x$ from $v$. There should exist at least one vertex $u$ with value $d_u>x$ for the check to return true. So at least the maximum value of them should be greater than $x$. That is basically a centroid exercise. Let each centroid store such an array $val$ that $val_i$ is the maximum value of $d_u$ over all such $u$ that belong to this centroid's subgraph and are no further than $i$ distance from the centroid. That array can be constructed in $O(n \\log n)$ for all centroids in total. You can easily see that the length of this array doesn't exceed the number of vertices in the subgraph of the corresponding centroid that is $O(n \\log n)$ be definition. For the query iterate over all centroids $v$ belongs to and check the value from some cell of each one's $val$ array. For the second solution let's reverse the problem. Consider the vertex $u$ Alice escapes to. If there is a starting vertex $v$ no further than $d_u - 1$ from it, then the answer for $v$ can be updated with $d_u$. So we can update the subgraph of vertices with distance no more than $d_u - 1$ with the maximum of their current answer and $d_u$. The solution will be almost the same centroid. Iterate over all centroids $u$ belongs to and write $d_u$ into the cell $i$ of each one's array $val$, where $i$ is the distance from $u$ to this centroid. Then build an array of prefix maximums over this array. Finally, for each $v$ collect the best answer over all centroids $v$ belongs to. Overall complexity: $O(n \\log^2 n)$ or $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\nconst int LN = 18;\n\nvector<int> g[N];\nvector<int> dist[N];\nint sz[N];\nint par[N];\nbool used[N];\nint max_dist[N];\nvector<int> val[N];\n\nint calc_size(int x, int p = -1)\n{\n    sz[x] = 1;\n    for(auto y : g[x])\n        if(y != p && !used[y])\n            sz[x] += calc_size(y, x);\n    return sz[x];   \n}\n\nint find_centroid(int x, int p, int s)\n{\n    int ans = -1;\n    bool good = true;\n    for(auto y : g[x])\n        if(y != p && !used[y])\n            good &= sz[y] * 2 <= s;\n        else if(y == p && !used[y])\n            good &= (s - sz[x]) * 2 <= s;\n    if(good)\n        ans = x;\n    for(auto y : g[x])\n        if(y != p && !used[y])\n            ans = max(ans, find_centroid(y, x, s));\n    return ans;\n}\n\nvoid calc_dist(int x, int p, int d, int s)\n{\n    dist[x].push_back(d);\n    for(auto y : g[x])\n        if(y != p && !used[y])\n            calc_dist(y, x, d + 1, s);\n    max_dist[s] = max(max_dist[s], d);  \n}\n\nint decomposition(int v)\n{\n    calc_size(v);\n    int c = find_centroid(v, v, sz[v]);\n    used[c] = true;\n    for(auto y : g[c])\n        if(!used[y])\n        {\n            par[decomposition(y)] = c;\n        }\n    used[c] = false;\n    calc_dist(c, c, 0, c); \n    return c;\n}\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n - 1; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        --x;\n        --y;\n        g[x].push_back(y);\n        g[y].push_back(x);\n    }\n    decomposition(0);\n    for(int i = 0; i < n; i++)\n        val[i].resize(max_dist[i] + 1);    \n    int k;\n    scanf(\"%d\", &k);\n    vector<int> d(n, int(1e9));\n    queue<int> q;\n    for(int i = 0; i < k; i++)\n    {\n        int x;\n        scanf(\"%d\", &x);\n        --x;\n        q.push(x);\n        d[x] = 0;\n    }\n    while(!q.empty())\n    {\n        int x = q.front();\n        q.pop();\n        for(auto y : g[x])\n            if(d[y] > d[x] + 1)\n            {\n                q.push(y);\n                d[y] = d[x] + 1;\n            }\n    }\n    for(int i = 0; i < n; i++)\n    {\n        if(d[i] == 0) continue;\n        \n        int curc = i;\n        for(int j = 0; j < dist[i].size(); j++)\n        {\n            int dd = dist[i][j];\n            if(dd > d[i] - 1)\n            {\n                curc = par[curc];\n                continue;\n            }\n            dd = d[i] - 1 - dd;\n            if(dd >= val[curc].size())\n                dd = val[curc].size() - 1; \n            val[curc][dd] = max(val[curc][dd], d[i]);\n            curc = par[curc];\n        }\n    }\n    for(int i = 0; i < n; i++)\n        for(int j = max_dist[i]; j >= 1; j--)\n            val[i][j - 1] = max(val[i][j], val[i][j - 1]);\n    for(int i = 0; i < n; i++)\n    {\n        int ans = 0; \n        int curc = i;\n        for(int j = 0; j < dist[i].size(); j++)\n        {\n            int dd = dist[i][j];\n            ans = max(ans, val[curc][dd]);\n            curc = par[curc];\n        }\n        if(d[i] == 0)\n            ans = 0;\n        printf(\"%d%c\", ans, \" \\n\"[i == n - 1]);\n    }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1453",
    "index": "A",
    "title": "Cancel the Trains",
    "statement": "Gildong's town has a train system that has $100$ trains that travel from the bottom end to the top end and $100$ trains that travel from the left end to the right end. The trains starting from each side are numbered from $1$ to $100$, respectively, and all trains have the same speed. Let's take a look at the picture below.\n\nThe train system can be represented as coordinates on a 2D plane. The $i$-th train starting at the bottom end is initially at $(i,0)$ and will be at $(i,T)$ after $T$ minutes, and the $i$-th train starting at the left end is initially at $(0,i)$ and will be at $(T,i)$ after $T$ minutes. All trains arrive at their destinations after $101$ minutes.\n\nHowever, Gildong found that some trains scheduled to depart at a specific time, simultaneously, are very dangerous. At this time, $n$ trains are scheduled to depart from the bottom end and $m$ trains are scheduled to depart from the left end. If two trains are both at $(x,y)$ at the same time for some $x$ and $y$, they will crash into each other. Therefore, he is asking you to find the \\textbf{minimum} number of trains that should be cancelled to prevent all such crashes.",
    "tutorial": "Let's first determine whether it's possible for two trains that start from $(i,0)$ and $(0,j)$ to crash into each other. For this to happen, there must be a point where $(i,T)=(T,j)$, which means $i=T$ and $j=T$. Therefore, a train that starts from the bottom end can crash into a train that starts from the left end if and only if they have the same train number. We can cancel either one of them to prevent that crash. Since $n$ and $m$ are small, we can brute-force every pair of trains and count the number of pairs of trains that share the same number, and print that value as the answer. The time complexity for this solution is $\\mathcal{O}(nm)$ for each test case. If we want an asymptotically faster solution, we can put all train numbers into a binary search tree structure (such as std::set in C++), and then find duplicate numbers from the trains of the other side by searching for those values. Another similar solution is to sort the former numbers, then perform binary search for the other values. The time complexity for these solutions is $\\mathcal{O}((n+m)\\log(n))$. There is another solution with $\\mathcal{O}(n+m)$ time complexity taking advantage of the fact that the train numbers are small. Let's make an array $X$ of length $101$, and set $X[i] = true$ if and only if there is a train starting from $(i, 0)$. For each train starting from $(0, j)$, we can check if $X[j]$ is $true$, and count the total number of duplicates this way.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int MAX_N = 100;\nconst int MAX_COORD = 100;\n \nvoid solve()\n{\n\tint n, m, i, j;\n\tcin >> n >> m;\n\tbool v[MAX_COORD + 5] = { 0 };\n\tint ans = 0;\n \n\tfor (i = 0; i < n; i++)\n\t{\n\t\tint x;\n\t\tcin >> x;\n\t\tv[x] = true;\n\t}\n\tfor (i = 0; i < m; i++)\n\t{\n\t\tint x;\n\t\tcin >> x;\n\t\tif (v[x])\n\t\t\tans++;\n\t}\n \n\tcout << ans << '\\n';\n}\n \nint main()\n{\n\tint t;\n\tcin >> t;\n \n\twhile (t--)\n\t\tsolve();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1453",
    "index": "B",
    "title": "Suffix Operations",
    "statement": "Gildong has an interesting machine that has an array $a$ with $n$ integers. The machine supports two kinds of operations:\n\n- Increase all elements of a suffix of the array by $1$.\n- Decrease all elements of a suffix of the array by $1$.\n\nA suffix is a subsegment (contiguous elements) of the array that contains $a_n$. In other words, for all $i$ where $a_i$ is included in the subsegment, all $a_j$'s where $i \\lt j \\le n$ must also be included in the subsegment.\n\nGildong wants to make all elements of $a$ equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?\n\nNote that even if you change one of the integers in the array, you should \\textbf{not} count that as one of the operations because Gildong did not perform it.",
    "tutorial": "First, let's find the optimal strategy for Gildong to follow to make all elements of the array equal. It's obvious that there is no need to perform any operation on the suffix starting at $a_1$, since that operation changes all the integers in the array. For $i=2$ to $n$, the only way for $a_i$ to have equal value to $a_{i-1}$ is to perform one of the operations on the suffix starting at $a_i$ $abs(a_i - a_{i-1})$ times. This is because all operations starting at other positions do not change the difference between $a_i$ and $a_{i-1}$. Therefore, the minimum number of operations Gildong has to perform is $\\sum_{i=2}^{n}{abs(a_i - a_{i-1})}$. How should we change one element so that we can minimize this value? Let's take care of some special cases first. The optimal way to change $a_1$ is to make it equal to $a_2$, and then the minimum number of operations Gildong has to perform is decreased by $abs(a_2 - a_1)$. Similarly, the optimal way to change $a_n$ is to make it equal to $a_{n-1}$, and then the minimum number of operations Gildong has to perform is decreased by $abs(a_n - a_{n-1})$. For the rest of the elements, changing $a_i$ affects both $abs(a_i - a_{i-1})$ and $abs(a_{i+1} - a_i)$. Here, we need to observe an important fact: This value is minimized when $a_i$ is between $a_{i-1}$ and $a_{i+1}$, inclusive. Intuitively, if $a_{i-1} < a_i > a_{i+1}$, Gildong has to perform one or more $2$-nd operations on the suffix starting at $a_i$, and then one or more $1$-st operations on the suffix starting at $a_{i+1}$ to compensate for the extra $2$-nd operations. This applies to the scenario where $a_{i-1} > a_i < a_{i+1}$ as well. If $a_i$ is between $a_{i-1}$ and $a_{i+1}$, these additional operations are unnecessary. In fact, the number of operations is decreased from $abs(a_i - a_{i-1}) + abs(a_{i+1} - a_i)$ to $abs(a_{i+1} - a_{i-1})$. Therefore, we can decrease the number of operations needed by: $\\max \\begin{cases} abs(a_2 - a_1)\\\\ abs(a_n - a_{n-1})\\\\ \\max_{i=2..n-1}{abs(a_i - a_{i-1}) + abs(a_{i+1} - a_i) - abs(a_{i+1} - a_{i-1})} \\end{cases}$ The answer is $x-y$ where $x$ is the minimum number of operations Gildong needs to perform on the initial array, and $y$ is the maximum number of operations we can decrease by changing exactly one element. Time complexity: $\\mathcal{O}(n)$.",
    "code": "def solve():\n    n = int(input())\n    a = [0] + list(map(int, input().split()))\n    \n    ans = 0\n    for i in range(2, n + 1):\n        ans += abs(a[i] - a[i - 1])\n        \n    mx = max(abs(a[2] - a[1]), abs(a[n] - a[n - 1]))\n    for i in range(2, n):\n        mx = max(mx, abs(a[i] - a[i - 1]) + abs(a[i + 1] - a[i]) - abs(a[i + 1] - a[i - 1]))\n    print(ans - mx)\n \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1453",
    "index": "C",
    "title": "Triangles",
    "statement": "Gildong has a square board consisting of $n$ rows and $n$ columns of square cells, each consisting of a single digit (from $0$ to $9$). The cell at the $j$-th column of the $i$-th row can be represented as $(i, j)$, and the length of the side of each cell is $1$. Gildong likes big things, so for each digit $d$, he wants to find a triangle such that:\n\n- Each vertex of the triangle is in the center of a cell.\n- The digit of every vertex of the triangle is $d$.\n- At least one side of the triangle is parallel to one of the sides of the board. You may assume that a side of length $0$ is parallel to both sides of the board.\n- The area of the triangle is maximized.\n\nOf course, he can't just be happy with finding these triangles as is. Therefore, for each digit $d$, he's going to change the digit of exactly one cell of the board to $d$, then find such a triangle. He changes it back to its original digit after he is done with each digit. Find the maximum area of the triangle he can make for each digit.\n\nNote that he can put multiple vertices of the triangle on the same cell, and the triangle can be a degenerate triangle; i.e. the area of the triangle can be $0$. Also, note that he is allowed to change the digit of a cell from $d$ to $d$.",
    "tutorial": "Let's consider each $d$ separately. For each cell that has the digit $d$, we'll check the case where this cell is used as a vertex of the end of a horizontal or vertical side (i.e. the base) of the triangle, and change the digit of another cell and use it as the other end of that side. Let's say the position for this cell is $(i, j)$, and we change the cell at $(p, q)$. Then there are two cases: $i=p$: Since we always want to maximize the length of the base, $q$ can be either $1$ or $n$, depending on whether $j-1 > n-j$ or not. The length of the base will be $\\max(j-1, n-j)$. $j=q$: Similarly, $p$ can be either $1$ or $n$, depending on whether $i-1 > n-i$ or not. The length of the base will be $\\max(i-1, n-i)$. In the first case, since the base is horizontal, the area of the triangle will be determined only by the remaining vertex's row component. Therefore, we only need the maximum / minimum row position of $d$. Let's say they are $max\\_row$ and $min\\_row$, respectively. We can easily pre-calculate them in advance. Assuming that $b$ is the length of the base, the maximum area will be $\\cfrac{b \\times \\max(max\\_row-i, i-min\\_row)}{2}$. We can get rid of the $\\cfrac{1}{2}$ part as we will print the area multiplied by $2$. Thankfully, we don't need to check the case where we change a cell that is not used as an end of a base separately, since we can always move it around so that they will eventually be horizontal / vertical to one of the other vertices without changing the area, which becomes a case that we already took care of. The same process can be applied to the second case as well. Summarizing the whole process, for each $d$, the maximum area (multiplied by $2$) is: $\\max_{(i, j)=d} \\begin{cases} \\max(j-1, n-j) \\times \\max(max\\_row-i, i-min\\_row)\\\\ \\max(i-1, n-i) \\times \\max(max\\_column-j, j-min\\_column)) \\end{cases}$ Since we check each cell exactly once, and pre-calculating $max\\_row$, $min\\_row$, $max\\_column$, and $min\\_column$ takes $\\mathcal{O}(n^2)$, the total time complexity is $\\mathcal{O}(n^2)$ for each test case.",
    "code": "import sys\nimport copy\ninput = sys.stdin.readline\n \nMAX_N = 2000\ninf = MAX_N + 9\n \ndef solve(a):\n    global inf\n    \n    mnr = [inf]*10\n    mxr = [0]*10\n    mnc = [inf]*10\n    mxc = [0]*10\n    ans = [0]*10\n \n    for i in range(1, n+1):\n        for j in range(1, n+1):\n            x = a[i][j]\n            mnr[x] = min(mnr[x], i)\n            mxr[x] = max(mxr[x], i)\n            mnc[x] = min(mnc[x], j)\n            mxc[x] = max(mxc[x], j)\n            \n    for i in range(1, n+1):\n        for j in range(1, n+1):\n            x = a[i][j]\n            ans[x] = max(ans[x], max(mxr[x] - i, i - mnr[x]) * max(n - j, j - 1))\n            ans[x] = max(ans[x], max(mxc[x] - j, j - mnc[x]) * max(n - i, i - 1))\n\t    \n    return ans\n \nif __name__ == '__main__':\n    t = int(input())\n    while t:\n        n = int(input())\n        a = [[]]\n        for i in range(1, n+1):\n            s = input()\n            a.append([0])\n            for j in range(0, n):\n                a[i].append(int(s[j]))\n \n        ans = solve(a)\n        for i in range(10):\n            print(ans[i], end=' ')\n        print()\n        t -= 1",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1453",
    "index": "D",
    "title": "Checkpoints",
    "statement": "Gildong is developing a game consisting of $n$ stages numbered from $1$ to $n$. The player starts the game from the $1$-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the $n$-th stage.\n\nThere is at most one checkpoint on each stage, and there is always a checkpoint on the $1$-st stage. At the beginning of the game, only the checkpoint on the $1$-st stage is activated, and all other checkpoints are deactivated. When the player gets to the $i$-th stage that has a checkpoint, that checkpoint is activated.\n\nFor each try of a stage, the player can either beat the stage or fail the stage. If they beat the $i$-th stage, the player is moved to the $i+1$-st stage. If they fail the $i$-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.\n\nFor example, assume that $n = 4$ and the checkpoints are on the $1$-st and $3$-rd stages. The player starts at the $1$-st stage. If they fail on the $1$-st stage, they need to retry the $1$-st stage because the checkpoint on the $1$-st stage is the most recent checkpoint they activated. If the player beats the $1$-st stage, they're moved to the $2$-nd stage. If they fail it, they're sent back to the $1$-st stage again. If they beat both the $1$-st stage and the $2$-nd stage, they get to the $3$-rd stage and the checkpoint on the $3$-rd stage is activated. Now whenever they fail on the $3$-rd stage, or the $4$-th stage after beating the $3$-rd stage, they're sent back to the $3$-rd stage. If they beat both the $3$-rd stage and the $4$-th stage, they win the game.\n\nGildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most $2000$ stages, where the expected number of tries over all stages is exactly $k$, for a player whose probability of beating each stage is exactly $\\cfrac{1}{2}$.",
    "tutorial": "As already explained in the notes (and is quite obvious), the expected number of tries to beat stage $i$ with a checkpoint where stage $i+1$ also has a checkpoint (or is the end of the game) is $2$. What if stage $i+1$ doesn't have a checkpoint and stage $i+2$ has a checkpoint? We can think of it like this. It takes $2$ tries in expectation to get to stage $i+1$, and the player needs to add one more try, trying $3$ times in total. But this also has a probability of $\\cfrac{1}{2}$ to succeed, so the expected number of tries to actually get to stage $i+2$ is multiplied by $2$ - making it $6$ in total. This can be extended indefinitely. Let's say $x_i$ is the expected number of tries to beat $i$ consecutive stages with only one checkpoint at the beginning. If we extend it to $i+1$ consecutive stages, it takes $x_{i+1} = 2 \\cdot (x_i+1)$ tries. If this is not intuitive, we can always use Monte Carlo method to simulate how many tries each takes. The general term for this sequence is $x_i = 2^{i+1} - 2$, and it is introduced in OEIS A000918 with a similar example. As each checkpoint makes the stages after that checkpoint independent of the previous stages, we can just add up appropriate $x_i$'s to make it equal to $k$. Using $x_i$ means we append the stages in $1$ $0$ $0$ $0$ ... form where the number of $0$'s is $i-1$. As every term of the sequence is even, the answer is $-1$ if $k$ is odd. Otherwise, we can show that there always exists an answer for all even $k \\le 10^{18}$. There are two simple strategies to make it with at most $2000$ stages. The first strategy is to greedily take the greatest $x_i \\le y$ where $y$ is the remaining number, then append $x_i$ and subtract it from $y$. This works because either $y$ can be exactly $2 \\cdot x_i$, or we can use $x_i$ once and repeat the process with $y-x_i$. The worst case for this strategy is to use all of $x_{57}$, $x_{56}$, $x_{55}$, ..., $x_1$ and another $x_1$, which sums up to total of $1654$ stages. Another strategy is to use $x_i$ and $x_1$ if bit $i+1$ ($0$-indexed) is $1$. Since there can be at most $58$ $1$-bits, the worst case for this strategy is still far less than $2000$. Time complexity: $\\mathcal{O}(\\log^2{k})$",
    "code": "import java.util.*;\n \npublic class Main {\t\n\tstatic Scanner sc = new Scanner(System.in);\n\tstatic final int MAX_N = 2000;\n\tpublic static void main(String[] args) {\n\t\tint t = sc.nextInt();\n\t\twhile (t-- > 0)\n\t\t\tsolve();\n\t}\n\t\n\tpublic static void solve() {\n\t\tlong k = sc.nextLong();\n\t\tif (k % 2 == 1)\n\t\t{\n\t\t\tSystem.out.println(-1);\n\t\t\treturn;\n\t\t}\n \n\t\tint[] a = new int[MAX_N + 5];\n\t\ta[1] = 1;\n\t\tint cur = 1;\n\t\twhile (k > 0)\n\t\t{\n\t\t\tint c;\n\t\t\tfor (c = 1; (1l << (c + 1)) - 2 <= k; c++);\n\t\t\tcur += c - 1;\n\t\t\ta[cur] = 1;\n\t\t\tk -= (1l << c) - 2;\n\t\t}\n\t\tSystem.out.println(cur - 1);\n\t\tfor (int i = 1; i < cur; i++)\n\t\t\tSystem.out.print(a[i] + (i == cur - 1 ? \"\\n\" : \" \"));\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1453",
    "index": "E",
    "title": "Dog Snacks",
    "statement": "Gildong is playing with his dog, Badugi. They're at a park that has $n$ intersections and $n-1$ bidirectional roads, each $1$ meter in length and connecting two intersections with each other. The intersections are numbered from $1$ to $n$, and for every $a$ and $b$ ($1 \\le a, b \\le n$), it is possible to get to the $b$-th intersection from the $a$-th intersection using some set of roads.\n\nGildong has put one snack at every intersection of the park. Now Gildong will give Badugi a mission to eat all of the snacks. Badugi starts at the $1$-st intersection, and he will move by the following rules:\n\n- Badugi looks for snacks that are as close to him as possible. Here, the distance is the length of the shortest path from Badugi's current location to the intersection with the snack. However, Badugi's sense of smell is limited to $k$ meters, so he can only find snacks that are less than or equal to $k$ meters away from himself. If he cannot find any such snack, he fails the mission.\n- Among all the snacks that Badugi can smell from his current location, he chooses a snack that minimizes the distance he needs to travel from his current intersection. If there are multiple such snacks, Badugi will choose one arbitrarily.\n- He repeats this process until he eats all $n$ snacks. After that, he has to find the $1$-st intersection again which also must be less than or equal to $k$ meters away from the last snack he just ate. If he manages to find it, he completes the mission. Otherwise, he fails the mission.\n\nUnfortunately, Gildong doesn't know the value of $k$. So, he wants you to find the minimum value of $k$ that makes it possible for Badugi to complete his mission, if Badugi moves optimally.",
    "tutorial": "It is obvious that the problem can be modeled as a tree rooted at the $1$-st vertex. Given a large enough $k$, we can see that Badugi will always 'clear out' each subtree and then move back to its parent. This is because if there exists an unvisited child for a vertex, the distance between them is $1$, while any unvisited vertex at the parent's side has distance of at least $2$. Therefore, Badugi's moves will look like a preorder tree traversal. This implies another fact. Let's say the $j$-th vertex is a child of the $i$-th vertex. After visiting the last vertex of a subtree rooted at the $j$-th vertex, Badugi has to move a longer distance when it was the last child of the $i$-th vertex than when the $i$-th vertex has another unvisited child. The only important rule for Badugi is to choose the child that has the shortest 'moving back' distance as the last child he will visit. This distance can be sent back to its parent so that the parent can choose between the candidates. Let's say the minimum among the candidates is $mn$, and the maximum is $mx$. It is optimal to use $mn+1$ as the 'moving back' distance, and the maximum of the 'child-to-child' distances will be $mx+1$. There is one exception for this strategy - the root. Unlike the others, there is no need to move any further after visiting all vertices and then getting back to the root. This means choosing $mx$ as the 'moving back' distance is optimal, because we don't need to add anything to it. Then we can use the sub-maximum of the candidates as the maximum of 'child-to-child' distances. Along these processes we can update the answer whenever we find the maximum of 'child-to-child' distances, along with the last move back to the root. Time complexity: $O(n)$ for each test case, but it's too boring to find the sub-maximum in linear time, so just sort the candidates and it will be $O(n\\log{n})$ for each test case.",
    "code": "import java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.util.ArrayList;\nimport java.util.Collections;\n \npublic class Main {\t\n\tstatic BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n\tstatic BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));\n\t\n\tstatic final int MAX_N = 200000;\n\tstatic final int inf = (int)1e9;\n\t\n\tstatic ArrayList<Integer>[] adj;\n\tstatic int ans;\n\t\n\tpublic static void main(String[] args) throws IOException {\n\t\tint t = Integer.parseInt(br.readLine());\n\t\twhile (t-- > 0)\n\t\t\tbw.write(solve() + \"\\n\");\n\t\tbw.flush();\n\t\tbw.close();\n\t\tbr.close();\n\t}\n\t\n\tpublic static int solve() throws IOException {\n\t\tint n = Integer.parseInt(br.readLine());\n\t\tint i;\n\t\t\n\t\tadj = new ArrayList[n + 1];\n\t\t\n\t\tfor (i = 1; i <= n; i++)\n\t\t\tadj[i] = new ArrayList<Integer>();\n\t\t\n\t\tfor (i = 0; i < n - 1; i++)\n\t\t{\n\t\t\tint u, v;\n\t\t\tString[] s = br.readLine().split(\" \");\n\t\t\tu = Integer.parseInt(s[0]);\n\t\t\tv = Integer.parseInt(s[1]);\n\t\t\tadj[u].add(v);\n\t\t\tadj[v].add(u);\n\t\t}\n\t\t\n\t\tans = 0;\n\t\tdfs(1, 0);\n\t\t\n\t\treturn ans;\n\t}\n\t\n\tpublic static int dfs(int cur, int p) {\n\t\tif (adj[cur].size() == 1 && cur != 1)\n\t\t\treturn 1;\n\t\tArrayList<Integer> v = new ArrayList<Integer>();\n\t\tfor (int x : adj[cur])\n\t\t{\n\t\t\tif (x == p)\n\t\t\t\tcontinue;\n\t\t\tint r = dfs(x, cur);\n\t\t\tv.add(r);\n\t\t}\n\t\tCollections.sort(v);\n\t\tif (v.size() > 1) {\n\t\t\tif (cur == 1)\n\t\t\t\tans = Math.max(ans, Math.max(v.get(v.size() - 1), v.get(v.size() - 2) + 1));\n\t\t\telse\n\t\t\t\tans = Math.max(ans, v.get(v.size() - 1) + 1);\n\t\t}\n\t\tans = Math.max(ans, v.get(0));\n\t\treturn v.get(0) + 1;\n\t}\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1453",
    "index": "F",
    "title": "Even Harder",
    "statement": "Gildong is now developing a puzzle game. The puzzle consists of $n$ platforms numbered from $1$ to $n$. The player plays the game as a character that can stand on each platform and the goal of the game is to move the character from the $1$-st platform to the $n$-th platform.\n\nThe $i$-th platform is labeled with an integer $a_i$ ($0 \\le a_i \\le n-i$). When the character is standing on the $i$-th platform, the player can move the character to any of the $j$-th platforms where $i+1 \\le j \\le i+a_i$. If the character is on the $i$-th platform where $a_i=0$ and $i \\ne n$, the player loses the game.\n\nSince Gildong thinks the current game is not hard enough, he wants to make it even harder. He wants to change some (possibly zero) labels to $0$ so that there remains exactly one way to win. He wants to modify the game as little as possible, so he's asking you to find the \\textbf{minimum} number of platforms that should have their labels changed. Two ways are different if and only if there exists a platform the character gets to in one way but not in the other way.",
    "tutorial": "Since there is at least one way to win initially, every platform is reachable from the start. Note that this condition should still hold after we achieve what Gildong wants. Because of this, if there are multiple $j$'s where $j + a_j \\ge i$, there are at least two ways that can get to the $i$-th platform. Therefore, in order to leave only one way to get to the $i$-th platform, we need to change all $a_j$'s where $j + a_j >= i$ into $0$ except for one of them. We'll call this process cleaning, and the platforms where we set $a_j = 0$ are the cleaned platforms. Let $dp[i][x]$ ($i \\le x$) be the minimum number of platforms that should be cleaned to leave only one way to get to the $i$-th platform, where the only platform $k$ that can directly move to the $i$-th platform (i.e. the predecessor) has a value at most $x - k$. In other words, $dp[i][x]$ only considers all $k$'s where $k \\lt i \\le k + a_k \\le x$, and choose the one that requires minimum number of cleaned platforms so far. We'll determine $dp[i][i..n]$ in increasing order of $i$. Now let $cnt$ be the number of $y$'s where $j \\lt y \\lt i$ and $y + a_y \\ge i$. Initially $cnt$ is $0$. Now for each $j$ from $i - 1$ to $1$ (downwards), if $j + a_j >= i$, minimize $dp[i][j + a_j]$ with $dp[j][i - 1] + cnt$ and then increase $cnt$ by $1$. This means we clean all platforms between $j + 1$ and $i - 1$ to let the $j$-th platform be the predecessor of the $i$-th platform, while it has possibility to reach the $j + a_j$-th platform. Note that all $k$'s where $k \\lt j$ and $k + a_k \\ge i$ are already cleaned when calculating $dp[j][i - 1]$, so we only need to count the cleaned platforms between $j + 1$ and $i - 1$ for $cnt$. Then we can prefix-minimize $dp[i][i..n]$ because the actual meaning of the $dp[i][x]$ is the minimum number of platforms that should be cleaned for the predecessor of the $i$-th platform can reach at most the $x$-th platform; i.e. it should consider all cases where $j + a[j] \\lt x$ as well. After we repeat these processes for all $i$'s, the answer is $dp[n][n]$. Though the explanation is quite complicated, the code turns out to be very short. Time complexity: $\\mathcal{O}(n^2)$.",
    "code": "import sys\ninput = sys.stdin.readline\n \nMAX_N = 3000\ninf = MAX_N\n \ndef solve():\n    global inf\n    \n    n = int(input())\n    a = [0] + list(map(int, input().split()))\n    dp = [[0] * (n + 1) for i in range(n + 1)]\n \n    for i in range(2, n + 1):\n        cnt = 0\n        for j in range(i, n + 1):\n            dp[i][j] = inf\n        for j in range(i - 1, 0, -1):\n            if j + a[j] >= i:\n                dp[i][j + a[j]] = min(dp[i][j + a[j]], dp[j][i - 1 ] + cnt)\n                cnt += 1\n        for j in range(i + 1, n + 1):\n            dp[i][j] = min(dp[i][j], dp[i][j - 1])\n \n    return dp[n][n]\n \nif __name__ == '__main__':\n    t = int(input())\n    while t:\n        print(solve())\n        t -= 1",
    "tags": [
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1454",
    "index": "A",
    "title": "Special Permutation",
    "statement": "You are given one integer $n$ ($n > 1$).\n\nRecall that a permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2, 3, 1, 5, 4]$ is a permutation of length $5$, but $[1, 2, 2]$ is not a permutation ($2$ appears twice in the array) and $[1, 3, 4]$ is also not a permutation ($n = 3$ but there is $4$ in the array).\n\nYour task is to find a permutation $p$ of length $n$ that there is no index $i$ ($1 \\le i \\le n$) such that $p_i = i$ (so, for all $i$ from $1$ to $n$ the condition $p_i \\ne i$ should be satisfied).\n\nYou have to answer $t$ independent test cases.\n\nIf there are several answers, you can print any. It can be proven that the answer exists for each $n > 1$.",
    "tutorial": "There are many possible solutions. One of them is just to print $2, 3, \\ldots, n, 1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcout << (i + 1) % n + 1 << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "probabilities"
    ],
    "rating": 800
  },
  {
    "contest_id": "1454",
    "index": "B",
    "title": "Unique Bid Auction",
    "statement": "There is a game called \"Unique Bid Auction\". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem).\n\nLet's simplify this game a bit. Formally, there are $n$ participants, the $i$-th participant chose the number $a_i$. The winner of the game is such a participant that the number he chose is \\textbf{unique} (i. e. nobody else chose this number except him) and is \\textbf{minimal} (i. e. among all unique values of $a$ the minimum one is the winning one).\n\nYour task is to find the \\textbf{index} of the participant who won the game (or -1 if there is no winner). Indexing is $1$-based, i. e. the participants are numbered from $1$ to $n$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "This is a simple implementation problem. Let's calculate two values for each $i$ from $1$ to $n$: $cnt_i$ - the number of occurrences of $i$ in $a$ and $idx_i$ - any position of $i$ in $a$. Then, let's iterate through $i$ from $1$ to $n$ and, if $cnt_i = 1$, just print $idx_i$ (because if it is the only such element then we found the winner). If we didn't find any such element, we have to print -1.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> cnt(n + 1), idx(n + 1);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\t++cnt[x];\n\t\t\tidx[x] = i + 1;\n\t\t}\n\t\tint ans = -1;\n\t\tfor (int i = 0; i <= n; ++i) {\n\t\t\tif (cnt[i] == 1) {\n\t\t\t\tans = idx[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1454",
    "index": "C",
    "title": "Sequence Transformation",
    "statement": "You are given a sequence $a$, initially consisting of $n$ integers.\n\nYou want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).\n\nTo achieve this, you choose some integer $x$ \\textbf{that occurs at least once in $a$}, and then perform the following operation any number of times (possibly zero): choose some segment $[l, r]$ of the sequence and remove it. But there is one exception: \\textbf{you are not allowed to choose a segment that contains $x$}. More formally, you choose some contiguous subsequence $[a_l, a_{l + 1}, \\dots, a_r]$ such that $a_i \\ne x$ if $l \\le i \\le r$, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the $(r+1)$-th is now $l$-th, the element that was $(r+2)$-th is now $(l+1)$-th, and so on (i. e. the remaining sequence just collapses).\n\nNote that you \\textbf{can not change} $x$ after you chose it.\n\nFor example, suppose $n = 6$, $a = [1, 3, 2, 4, 1, 2]$. Then one of the ways to transform it in two operations is to choose $x = 1$, then:\n\n- choose $l = 2$, $r = 4$, so the resulting sequence is $a = [1, 1, 2]$;\n- choose $l = 3$, $r = 3$, so the resulting sequence is $a = [1, 1]$.\n\nNote that choosing $x$ is not an operation. Also, note that you \\textbf{can not} remove any occurrence of $x$.\n\nYour task is to find the \\textbf{minimum} number of operations required to transform the sequence in a way described above.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, let's remove all consecutive equal elements (just keep one occurrence of each such element). For example, the array $[1, 1, 2, 3, 3, 3, 2]$ becomes $[1, 2, 3, 2]$. Now, the answer for each $a_i$ is almost the number of its occurrences plus one. Why is it so? Because we need to remove all segments of elements between every pair of consecutive occurrences of $a_i$. The number of such segments is the number of occurrences of $a_i$ minus one. There is also a segment before the first occurrence of $a_i$ and a segment after the last occurrence of $a_i$. But the first segment doesn't exist for the first element and the last segment doesn't exist for the last element. So, after removing consecutive elements, let's calculate for each $a_i$ the number of its occurrences plus one, subtract one from the value of the first element and from the value of the last element. Then the answer is the minimum among these values for all $a_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (auto &it : a) cin >> it;\n\t\tvector<int> res(n + 1, 1);\n\t\tn = unique(a.begin(), a.end()) - a.begin();\n\t\ta.resize(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tres[a[i]] += 1;\n\t\t}\n\t\tres[a[0]] -= 1;\n\t\tres[a[n - 1]] -= 1;\n\t\tint ans = 1e9;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tans = min(ans, res[a[i]]);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1454",
    "index": "D",
    "title": "Number into Sequence",
    "statement": "You are given an integer $n$ ($n > 1$).\n\nYour task is to find a sequence of integers $a_1, a_2, \\ldots, a_k$ such that:\n\n- each $a_i$ is strictly greater than $1$;\n- $a_1 \\cdot a_2 \\cdot \\ldots \\cdot a_k = n$ (i. e. the product of this sequence is $n$);\n- $a_{i + 1}$ is divisible by $a_i$ for each $i$ from $1$ to $k-1$;\n- $k$ is the \\textbf{maximum} possible (i. e. the length of this sequence is the \\textbf{maximum} possible).\n\nIf there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer $n > 1$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Consider $n$ in this canonical form ${p_1}^{a_1} \\cdot {p_2}^{a_2} \\cdot \\ldots \\cdot {p_k}^{a_k}$ (just find the prime factorization of $n$). Let $i$ be such an index that $a_i$ is the maximum among all values of $a$. Then the answer length can not exceed $a_i$. This is because if the answer has greater length, then some number doesn't have $p_i$ in its representation (thus, there will be problems with divisibility because we are considering primes). So, let's create the answer of length $a_i$ consisting of $p_i$. Then let's just multiply the last element by all other primes in their degrees. So, we satisfied the divisibility rule and the length of the answer is the maximum possible.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tlong long n;\n\t\tcin >> n;\n\t\n\t\tvector<pair<int, long long>> val;\n\t\tfor (long long i = 2; i * i <= n; ++i) {\n\t\t\tint cnt = 0;\n\t\t\twhile (n % i == 0) {\n\t\t\t\t++cnt;\n\t\t\t\tn /= i;\n\t\t\t}\n\t\t\tif (cnt > 0) {\n\t\t\t\tval.push_back({cnt, i});\n\t\t\t}\n\t\t}\n\t\tif (n > 1) {\n\t\t\tval.push_back({1, n});\n\t\t}\n\t\n\t\tsort(val.rbegin(), val.rend());\n\t\tvector<long long> ans(val[0].first, val[0].second);\n\t\tfor (int i = 1; i < int(val.size()); ++i) {\n\t\t\tfor (int j = 0; j < val[i].first; ++j) {\n\t\t\t\tans.back() *= val[i].second;\n\t\t\t}\n\t\t}\n\t\n\t\tcout << ans.size() << endl;\n\t\tfor (auto it : ans) cout << it << \" \";\n\t\tcout << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1454",
    "index": "E",
    "title": "Number of Simple Paths",
    "statement": "You are given an \\textbf{undirected} graph consisting of $n$ vertices and $n$ edges. It is guaranteed that the given graph is \\textbf{connected} (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.\n\nYour task is to calculate the number of \\textbf{simple paths} of length \\textbf{at least} $1$ in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths $[1, 2, 3]$ and $[3, 2, 1]$ are considered the same.\n\nYou have to answer $t$ independent test cases.\n\nRecall that a path in the graph is a sequence of vertices $v_1, v_2, \\ldots, v_k$ such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A \\textbf{simple path} is such a path that all vertices in it are distinct.",
    "tutorial": "Because our graph is just a tree with an additional edge, consider it as a cycle with trees hanged on cycle vertices. Consider some tree hung on a vertex $v$ on a cycle. There is only one path between each pair of its vertices (including the root which is a vertex $v$). So, if the tree has $cnt_v$ vertices, then $\\frac{cnt_v(cnt_v-1)}{2}$ paths are added to the answer. What about paths that go out of a tree? Let's assume that there are $cnt_v \\cdot (n - cnt_v)$ such paths (yeah, we counted only a half of actual paths from this component but this is fine). When we consider other trees, we will take into account the other half of paths. This information can lead us to the conclusion that the only information we need to know about trees hanged on cycle vertices is the number of vertices in these trees. So, if we know $cnt_v$ for each vertex on a cycle, we can just calculate the answer as $\\sum\\limits_{v \\in cycle} \\frac{cnt_v(cnt_v-1)}{2} + cnt_v \\cdot (n - cnt_v)$. So how to find values $cnt_v$? Of course, there is a simple and straight-forward solution \"just extract and mark all cycle vertices and run dfs from every vertex of a cycle\", but there is another approach without any graph algorithms that works very well for such kind of graphs. Initially, let $cnt_v = 1$ for each $v$ from $1$ to $n$. Let's create a queue containing all leafs of the graph. Let's take the leaf $x$, get its parent $p$, add $cnt_p := cnt_p + cnt_x$ and remove the vertex $x$ with all edges incident to it. After that, if $p$ became a leaf, let's add it to the queue. We can see that after processing all leafs only cycle vertices remain in the graph, and $cnt_v$ is exactly the number of the vertices in a tree (and we can just calculate the answer using the formula above). This approach can be implemented in $O(n \\log n)$ or in $O(n)$, there is almost no difference, but $O(n \\log n)$ one can be written a bit simpler than a linear one.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n#endif\n\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<set<int>> g(n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y;\n\t\t\t--x, --y;\n\t\t\tg[x].insert(y);\n\t\t\tg[y].insert(x);\n\t\t}\n\t\tvector<int> val(n, 1);\n\t\tqueue<int> leafs;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (g[i].size() == 1) {\n\t\t\t\tleafs.push(i);\n\t\t\t}\n\t\t}\n\t\twhile (!leafs.empty()) {\n\t\t\tint v = leafs.front();\n\t\t\tleafs.pop();\n\t\t\tint to = *g[v].begin();\n\t\t\tval[to] += val[v];\n\t\t\tval[v] = 0;\n\t\t\tg[v].clear();\n\t\t\tg[to].erase(v);\n\t\t\tif (g[to].size() == 1) {\n\t\t\t\tleafs.push(to);\n\t\t\t}\n\t\t}\n\t\tlong long ans = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tans += val[i] * 1ll * (val[i] - 1) / 2;\n\t\t\tans += val[i] * 1ll * (n - val[i]);\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1454",
    "index": "F",
    "title": "Array Partition",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nLet $min(l, r)$ be the minimum value among $a_l, a_{l + 1}, \\ldots, a_r$ and $max(l, r)$ be the maximum value among $a_l, a_{l + 1}, \\ldots, a_r$.\n\nYour task is to choose three \\textbf{positive} (greater than $0$) integers $x$, $y$ and $z$ such that:\n\n- $x + y + z = n$;\n- $max(1, x) = min(x + 1, x + y) = max(x + y + 1, n)$.\n\nIn other words, you have to split the array $a$ into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).\n\nAmong all such triples (partitions), you can choose any.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Let's fix the length of the first block (iterate through $i$ from $0$ to $n-3$). Let's also try to maximize the length of the third block using the second pointer. So, initially the length of the first block is $1$ and the maximum in the block is $a_0$ (after that, its length will be $2$ and the maximum will be $max(a_0, a_1)$, and so on). Let's move the left border of the third block $r$ while $a_r \\le a_0$ and the second block have at least one element. After we expanded the third block, consider some cases: if its maximum is less than $a_0$, then we don't need to consider this partition (we expanded the third block as much as we can but didn't find the required maximum). Otherwise, its maximum fits our conditions. Then let's find the minimum in the second block. Let it be $mn$. If $mn < mx$, this partition is also bad. If $mn = mx$, this partition is good, and we can just print it. Otherwise, $mn > mx$, and we need to fix the second block somehow. I claim that we only need to expand it by at most one element. Let's see why is it true. Consider we want to expand it to the right (the other case just uses the same logic). If we expanded our block by one element to the right and the new value in it is less than $mx$, then this partition is bad, and we can not use it (this is also the reason why we are trying to maximize the length of the third block). Otherwise, this value is always $mx$, because the first and the third blocks didn't have values greater than $mx$. There are some cases in the implementation we need to consider carefully: first, we need to find the minimum in the second block fast enough. This can be done if we store it as a multiset (set with repetitions). Second, we can remove the only maximum in the third (or the first) block by expanding the second one. This can be handled easily if we just store all three blocks (not only the second one) as multisets. And the last case is that we sometimes need to move the left border of the third block to the right. This happens when we expand the first block and the second block becomes empty. So, this happens only $O(n)$ times in total. Total time complexity of this solution is $O(n \\log n)$. There is also another solution from Gassa: Let us start solving by asking the following question: in which segments will the maximal values end up? Consider the maximum value $m$ in the whole array. If there are at least three of them, a valid answer is to pick any maximum except the first and the last as the middle segment. For example, \"3 2 3 1 3 2 3\" ($m = 3$) can be partitioned as \"3 2[3]1 3 2 3\" or as \"3 2 3 1[3]2 3\", where the middle segment is marked with square brackets. Otherwise, all $m$ should end up in the middle segment, so that maximums to the left and to the right are less. For example, in \"1 2 3 1 3 2 1\", we have to put both threes into the middle segment. Let us now calculate the minimum value $v$ on the middle segment, considering the numbers between those equal to $m$. For example, in \"1 2[3 1 3]2 1\" the value $v = \\min (3, 1, 3) = 1$. All numbers greater than $v$ should also go into the middle segment, and everything between them, which can result in $v$ decreasing even more. We have to expand the borders of the middle segment until the minimum value is such $v$ that there are only values not greater than $v$ left outside. Continuing with the example, we see that in \"1 2[3 1 3]2 1\", the middle segment should be expanded to \"1[2 3 1 3 2]1\". Conversely, if the maximum $m$ was unique, then $v = m$, and we didn't have to expand the middle segment at this stage. For example, in \"1 2 3 2 1\", the current state is \"1 2[3]2 1\". If the maximums to the left and to the right are exactly $v$, we found an answer. Otherwise, any possible middle segment contains the middle segment that we now got. So we have to expand the middle segment, either to the left or to the right. As a result, the value $v$ may become smaller, which can cause another expansion. What's left is to decide where to expand when we have a choice. We would like to do it greedily. Indeed, consider three values: the minimum on middle segment $v$, the maximum on left segment $u$ and the maximum on right segment $w$. When we expand the middle segment, each of them can only decrease. And if we find an answer, the equation $u = v = w$ will be satisfied. So, as we make the minimum of these three values smaller, we have less and less opportunities to make them equal. Thus we can pick the side of expansion after which the value $\\min (u, v, w)$ is larger, and if these are equal, pick any. For example, in the state \"1 3[5 4 5]2 3 1\", we have $u = 3$, $v = 4$, and $w = 3$. If we expand to the left, we get \"1[3 5 4 5]2 3 1\" where $u = 1$, $v = 3$, and $w = 3$. If we expand to the right, we get \"1 3[5 4 5 2]3 1\" where $u = 3$, $v = 2$, and $w = 3$. Our algorithm will pick expanding to the right, however, there is no valid answer in this example anyway. Implementation: let us precalculate the maximums on all prefixes and all suffixes of the array. Then we can expand the middle segment by one element in $O (1)$, and the total running time is linear.",
    "code": "// Author: Ivan Kazmenko (gassa@mail.ru)\nmodule solution;\nimport std.algorithm;\nimport std.conv;\nimport std.range;\nimport std.stdio;\nimport std.string;\n\nvoid main ()\n{\n\tauto tests = readln.strip.to !(int);\n\tforeach (test; 0..tests)\n\t{\n\t\tauto n = readln.strip.to !(int);\n\t\tauto a = readln.splitter.map !(to !(int)).array;\n\t\tauto x = a.dup;\n\t\tforeach (i; 1..n)\n\t\t{\n\t\t\tx[i] = max (x[i], x[i - 1]);\n\t\t}\n\t\tauto y = a.dup;\n\t\tforeach_reverse (i; 0..n - 1)\n\t\t{\n\t\t\ty[i] = max (y[i], y[i + 1]);\n\t\t}\n\n\t\tauto v = a.maxElement;\n\t\tauto maxPlaces = n.iota.filter !(i => a[i] == v).array;\n\t\tint lo = maxPlaces[$ / 2];\n\t\tint hi = lo + 1;\n\n\t\twhile (true)\n\t\t{\n\t\t\tif (lo == 0 || hi == n)\n\t\t\t{\n\t\t\t\twriteln (\"NO\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (x[lo - 1] == v && y[hi] == v)\n\t\t\t{\n\t\t\t\twriteln (\"YES\");\n\t\t\t\twriteln (lo, \" \", hi - lo, \" \", n - hi);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint u = (lo - 1 == 0) ? int.min :\n\t\t\t    min (x[lo - 2], a[lo - 1]);\n\t\t\tint w = (hi + 1 >= n) ? int.min :\n\t\t\t    min (y[hi + 1], a[hi]);\n\t\t\tif (u > w)\n\t\t\t{\n\t\t\t\tv = min (v, a[lo - 1]);\n\t\t\t\tlo -= 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tv = min (v, a[hi]);\n\t\t\t\thi += 1;\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1455",
    "index": "A",
    "title": "Strange Functions",
    "statement": "Let's define a function $f(x)$ ($x$ is a positive integer) as follows: write all digits of the decimal representation of $x$ backwards, then get rid of the leading zeroes. For example, $f(321) = 123$, $f(120) = 21$, $f(1000000) = 1$, $f(111) = 111$.\n\nLet's define another function $g(x) = \\dfrac{x}{f(f(x))}$ ($x$ is a positive integer as well).\n\nYour task is the following: for the given positive integer $n$, calculate the number of different values of $g(x)$ among all numbers $x$ such that $1 \\le x \\le n$.",
    "tutorial": "Let's analyze which values can the function $g(x)$ have. It can be proven that the value of $g(x)$ is equal to $10^k$, where $k$ is the number of zero-digits at the end of the number $x$, because $f(f(x))$ is the same number as $x$ except for the fact that it doesn't have any trailing zeroes. Okay, now let's analyze when we reach the new value of $g(x)$. $1$ is the first value of $x$ such that $g(x) = 1$, $10$ is the first value of $x$ such that $g(x) = 10$, $100$ is the first value of $x$ such that $g(x) = 100$, and so on. We have to calculate the maximum number that has the form $10^k$ and is not greater than $n$, and the answer is exactly $k + 1$. It can be done with a mathematical solution, but the most simple way to do it is read $n$ as a string instead, and calculate its length.",
    "code": "for i in range(int(input())):\n\tprint(len(input()))",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1455",
    "index": "B",
    "title": "Jumps",
    "statement": "You are standing on the $\\mathit{OX}$-axis at point $0$ and you want to move to an integer point $x > 0$.\n\nYou can make several jumps. Suppose you're currently at point $y$ ($y$ may be negative) and jump for the $k$-th time. You can:\n\n- either jump to the point $y + k$\n- or jump to the point $y - 1$.\n\nWhat is the minimum number of jumps you need to reach the point $x$?",
    "tutorial": "At first, let's jump with $+k$ while $x$ is still greater than the current position. Now we finished in some position $pos = 1 + 2 + \\dots + steps = \\frac{steps (steps + 1)}{2} \\ge x$. Note that $0 \\le pos - x < steps$ otherwise, we wouldn't make the last step. If $pos = x$ then we are lucky to finish right in point $x$. Otherwise, let's look at what happens if we replace one $+k$ with $-1$. Basically, we'll finish in $pos' = pos - (k + 1)$. And since $k \\in [1, steps]$ then $pos' \\in [pos - steps - 1, pos - 2]$. We know that $pos - step < x$ so if $x < pos - 1$ then we can choose the corresponding $k = pos - x - 1$ and replace $+k$ with $-1$ and get straight to the point $x$. But if $x + 1 = pos$ then we need one extra operation $-1$. To calculate $steps$ fast we can note we need at least $steps = \\sqrt{2 \\cdot x} - 1$ since $steps (steps + 1) \\le (steps + 1)^2 \\le 2x$ and then we can increase $steps$ while $steps (steps + 1) < 2x$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tint x; cin >> x;\n\t\t\n\t\tint steps = 0;\n\t\twhile (steps * (steps + 1) < 2 * x)\n\t\t\tsteps++;\n\t\t\n\t\tif (steps * (steps + 1) / 2 == x + 1)\n\t\t\tsteps++;\n\t\tcout << steps << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1455",
    "index": "C",
    "title": "Ping-pong",
    "statement": "Alice and Bob play ping-pong with simplified rules.\n\nDuring the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.\n\nThe one who doesn't make a return loses this play. The winner of the play commences the next play. Alice starts the first play.\n\nAlice has $x$ stamina and Bob has $y$. To hit the ball (while serving or returning) each player spends $1$ stamina, so if they don't have any stamina, they can't return the ball (and lose the play) or can't serve the ball (in this case, the other player serves the ball instead). If both players run out of stamina, the game is over.\n\nSometimes, it's strategically optimal not to return the ball, lose the current play, but save the stamina. On the contrary, when the server commences a play, they have to hit the ball, if they have some stamina left.\n\nBoth Alice and Bob play optimally and want to, firstly, maximize their number of wins and, secondly, minimize the number of wins of their opponent.\n\nCalculate the resulting number of Alice's and Bob's wins.",
    "tutorial": "Let's find an answer for a little different version of the game. Let's say that $f(x, y)$ is the final score if the first player has $x$ stamina and the second has $y$ stamina. The first player can either hit the ball or can give up and lose the play. How to calculate $f(x, y)$? Obviously, $f(0, x) = (0, x)$ and $f(x, 0) = (x, 0)$. Otherwise, the first player can either hit the ball: then the player spent $1$ stamina and now it's to the second player to decide - hit or lose. So basically, we moved to the state $f(y, x - 1)$ and the answer in this case is $\\mathit{rev}(f(y, x - 1))$ where $\\mathit{rev}(a, b) = (b, a)$; or lose the play: then the player doesn't spend any stamina, but the opponent has to serve the ball. He serves the ball, spend $1$ stamina and return to the state, where the first player decides - hit or lose. Formally, the answer in this case is $f(x, y - 1) + (0, 1)$. Looking at $f(0, x) = (0, x)$, $f(x, 0) = (x, 0)$ and one of transitions $f(x, y - 1) + (0, 1)$ we can guess that $f(x, y) = (x, y)$ and prove it by induction: $f(x, y)$ is either $\\mathit{rev}(f(y, x - 1))$ or $f(x, y - 1) + (0, 1)$, but $\\mathit{rev}(f(y, x - 1)) = \\mathit{rev}(y, x - 1) = (x - 1, y)$ and $f(x, y - 1) + (0, 1) = (x, y - 1) + (0, 1) = (x, y)$ and $(x, y)$ is better than $(x - 1, y)$, so $f(x, y) = (x, y)$. The final step is to note that since Alice starts the first play and has to serve ball - the answer is $\\mathit{rev}(f(y, x - 1)) = \\mathit{rev}(y, x - 1) = (x - 1, y)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tint x, y;\n\tcin >> x >> y;\n\tcout << x - 1 << \" \" << y << endl;\t\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) solve();\n}",
    "tags": [
      "constructive algorithms",
      "games",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1455",
    "index": "D",
    "title": "Sequence and Swaps",
    "statement": "You are given a sequence $a$ consisting of $n$ integers $a_1, a_2, \\dots, a_n$, and an integer $x$. Your task is to make the sequence $a$ sorted (it is considered sorted if the condition $a_1 \\le a_2 \\le a_3 \\le \\dots \\le a_n$ holds).\n\nTo make the sequence sorted, you may perform the following operation any number of times you want (possibly zero): choose an integer $i$ such that $1 \\le i \\le n$ and $a_i > x$, and swap the values of $a_i$ and $x$.\n\nFor example, if $a = [0, 2, 3, 5, 4]$, $x = 1$, the following sequence of operations is possible:\n\n- choose $i = 2$ (it is possible since $a_2 > x$), then $a = [0, 1, 3, 5, 4]$, $x = 2$;\n- choose $i = 3$ (it is possible since $a_3 > x$), then $a = [0, 1, 2, 5, 4]$, $x = 3$;\n- choose $i = 4$ (it is possible since $a_4 > x$), then $a = [0, 1, 2, 3, 4]$, $x = 5$.\n\nCalculate the minimum number of operations you have to perform so that $a$ becomes sorted, or report that it is impossible.",
    "tutorial": "The main fact that allows us to solve this problem is that the value of $x$ always increases after swaps, and since the resulting sequence should be sorted, the indices of elements we swap with $x$ also increase. This observation is actually enough for us to implement a dynamic programming solution of the form \"dp_{i, j} is the minimum number of actions we have to perform to reach the following situation: the last integer we swapped with $x$ was $a_i$, and the current value of $a_i$ is $j$\". Depending on your implementation, it works either in $O(n^3)$ or in $O(n^2)$. But there exists a much simpler to code greedy solution: scan the array from left to right until it is sorted, and find the first element such that we can apply the operation to it (and apply that operation to it). Implementing it in $O(n^2)$ or even in $O(n)$ is easy, but proving it is a bit harder. The key fact that is required to prove it is that if we can apply an operation to some position, but don't do it and instead apply this operation to some position to the right of that one, the elements on these two positions are no longer sorted (if we can apply the operation to some position $i$, then $a_i > x$, but if we apply the operation to position $j$ instead, then after it $a_i > a_j$). Since we can't go backward, the resulting array cannot be sorted by any means - that's why we can't skip elements in this greedy solution.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nint n, x;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n >> x))\n\t\treturn false;\n\ta.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> a[i];\n\treturn true;\n}\n\ninline void solve() {\n\tvector<int> sf(n + 1, 0);\n\tsf[n] = sf[n - 1] = 1;\n\tfor (int i = n - 2; i >= 0; i--) {\n\t\tif (a[i] <= a[i + 1])\n\t\t\tsf[i] = sf[i + 1];\n\t}\n\t\n\tint ans = 0;\n\tint uk = 0;\n\twhile (true) {\n\t\tint np = uk;\n\t\twhile (np < n && a[np] <= x)\n\t\t\tnp++;\n\t\tfore (i, uk, np) {\n\t\t\tif (i == 0) continue;\n\t\t\tif (a[i - 1] > a[i]) {\n\t\t\t\tcout << -1 << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (sf[np])\n\t\t\tbreak;\n\t\t\n\t\tassert(a[np] > x);\n\t\tswap(a[np], x);\n\t\tans++;\n\t\tuk = np;\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint t; cin >> t;\n\t\n\twhile(t--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1455",
    "index": "E",
    "title": "Four Points",
    "statement": "You are given four different integer points $p_1$, $p_2$, $p_3$ and $p_4$ on $\\mathit{XY}$ grid.\n\nIn one step you can choose one of the points $p_i$ and move it in one of four directions by one. In other words, if you have chosen point $p_i = (x, y)$ you can move it to $(x, y + 1)$, $(x, y - 1)$, $(x + 1, y)$ or $(x - 1, y)$.\n\nYour goal to move points in such a way that they will form a square with sides parallel to $\\mathit{OX}$ and $\\mathit{OY}$ axes (a square with side $0$ is allowed).\n\nWhat is the minimum number of steps you need to make such a square?",
    "tutorial": "Let's discuss two approaches to this problem. Firstly, let's think that we choose not four destination points but four lines on which sides of the square lie. It's two vertical lines with coordinates $x_1$ and $x_2$ and two horizontal lines $y_1$ and $y_2$ (of course, $|x_1 - x_2| = |y_1 - y_2|$). The first approach is to note that either both $x_1$ and $x_2$ coincide with some $(p_i.x)$-s and $y_1$ coincide with one of $(p_i.y)$ or both $y_1$ and $y_2$ coincide with some $(p_i.y)$-s and $x_1$ coincide with one $(p_i.x)$. $\\underset{(\\text{two cases})}{2} \\cdot \\binom{4}{2} \\cdot 4 \\cdot \\underset{y_2 = y_1 \\pm |x_1 - x_2|}{2} \\cdot 4! \\cdot 4 \\approx 10^4$ The second approach is more clever and faster. Let's assign a role for each point $p_i$ - which vertex of the final square this $p_i$ will be: left-bottom, left-top, right-bottom or right-top. There will be $4!$ such assignments. For simplicity let's say that the left-bottom vertex is $a$, left-top is $b$, right-bottom is $c$ and right-top is $d$. If we rewrite our total distance formulas, we can note that instead of summing the distance between points, we can sum the distance from lines to the points which should lie on it. In other words, we can calculate the answer as $(|a_x - x_1| + |b_x - x_1|) + (|c_x - x_2| + |d_x - x_2|) + \\\\ + (|a_y - y_1| + |c_y - y_1|) + (|b_y - y_2| + |d_y - y_2|).$ Let's look at the left side $x_1$. If $\\min(a_x, b_x) \\le x_1 \\le \\max(a_x, b_x)$ then the total distance is always $\\max(a_x, b_x) - \\min(a_x, b_x)$ and $x_1$ has it's optimal segment of values. Analogically, $x_2$ also has it's optimal segment of values $\\min(c_x, d_x) \\le x_2 \\le \\max(c_x, d_x)$. Since we can choose $x_1$ as any value in its segment and $x_2$ as any value in its segment then the possible distance $|x_1 - x_2|$ (the side of the square) also forms a segment of possible values (let's name it as $[xSeg.l, xSeg.r]$) and can be calculated with pretty easy formula. On the other hand, we can do the same with horizontal sides and compute the segment of optimal side length $[ySeg.l, ySeg.r]$ in the same manner. Now, if $xSeg$ and $ySeg$ intersects then we can choose such side length $k$ that lies in both $xSeg$ and $ySeg$ and optimal for both vertical sides and horizontal sides. Otherwise, without loss of generality, $xSeg.r < ySeg.l$ and if we choose $k = ySeg.l$ we need to pay extra \"fee\" since we out of $xSeg$ - it means that the chosen $k$ is greater than optimal $xSeg.r$, so we need to choose, for example, $x_1$ outside $[\\min(a_x, b_x), \\max(a_x, b_x)]$. And we need to pay $+2$ for each step outside of this segment. In other words, the answer for a fixed permutation is $(\\max(a_x, b_x) - \\min(a_x, b_x)) + (\\max(c_x, d_x) - \\min(c_x, d_x)) + \\\\ + (\\max(a_x, c_x) - \\min(a_x, c_x)) + (\\max(b_x, d_x) - \\min(b_x, d_x)) + \\\\ + 2 \\cdot \\max(0, \\max(xSeg.l, ySeg.l) - \\min(xSeg.r, ySeg.r)).$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<li, li> pt;\n\nconst li INF64 = li(1e18);\n\npt p[4];\n\ninline bool read() {\n\tfore (i, 0, 4) {\n\t\tif(!(cin >> p[i].x >> p[i].y))\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nli len(const pt &a) {\n\tassert(a.y >= a.x);\n\treturn a.y - a.x;\n}\npt getSeg(li a, li b) {\n\treturn { min(a, b), max(a, b) };\n}\npt getOpt(const pt &a, const pt &b) {\n\treturn {\n\t\tmax({ a.x - b.y, b.x - a.y, 0LL }),\n\t\tmax({ b.y - a.x, a.y - b.x, 0LL })\n\t};\n}\n\ninline void solve() {\n\tli ans = INF64;\n\t\n\tvector<int> id = { 0, 1, 2, 3 };\n\tdo {\n\t\tli cur = 0;\n\t\tauto x1 = getSeg(p[id[0]].x, p[id[3]].x);\n\t\tauto x2 = getSeg(p[id[1]].x, p[id[2]].x);\n\t\t\n\t\tcur += len(x1) + len(x2);\n\t\tpt xSeg = getOpt(x1, x2);\n\t\t\n\t\tauto y1 = getSeg(p[id[0]].y, p[id[1]].y);\n\t\tauto y2 = getSeg(p[id[2]].y, p[id[3]].y);\n\t\t\n\t\tcur += len(y1) + len(y2);\n\t\tpt ySeg = getOpt(y1, y2);\n\t\t\n\t\tli is = min(xSeg.y, ySeg.y) - max(xSeg.x, ySeg.x);\n\t\tcur += 2 * max(0LL, -is);\n\t\t\n\t\tans = min(ans, cur);\n\t}\n\twhile (next_permutation(id.begin(), id.end()));\n\t\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint t;\n\tcin >> t;\n\t\n\twhile(t--) {\n\t\tassert(read());\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "flows",
      "geometry",
      "greedy",
      "implementation",
      "math",
      "ternary search"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1455",
    "index": "F",
    "title": "String and Operations",
    "statement": "You are given a string $s$ consisting of $n$ characters. These characters are among the first $k$ lowercase letters of the Latin alphabet. You have to perform $n$ operations with the string.\n\nDuring the $i$-th operation, you take the character that \\textbf{initially occupied} the $i$-th position, and perform \\textbf{one} of the following actions with it:\n\n- swap it with the previous character in the string (if it exists). This operation is represented as L;\n- swap it with the next character in the string (if it exists). This operation is represented as R;\n- cyclically change it to the previous character in the alphabet (b becomes a, c becomes b, and so on; a becomes the $k$-th letter of the Latin alphabet). This operation is represented as D;\n- cyclically change it to the next character in the alphabet (a becomes b, b becomes c, and so on; the $k$-th letter of the Latin alphabet becomes a). This operation is represented as U;\n- do nothing. This operation is represented as 0.\n\nFor example, suppose the initial string is test, $k = 20$, and the sequence of operations is URLD. Then the string is transformed as follows:\n\n- the first operation is U, so we change the underlined letter in {\\underline{t}est} to the next one in the first $20$ Latin letters, which is a. The string is now aest;\n- the second operation is R, so we swap the underlined letter with the next one in the string {a\\underline{e}st}. The string is now aset;\n- the third operation is L, so we swap the underlined letter with the previous one in the string {a\\underline{s}et} (note that this is now the $2$-nd character of the string, but it was initially the $3$-rd one, so the $3$-rd operation is performed to it). The resulting string is saet;\n- the fourth operation is D, so we change the underlined letter in {sae\\underline{t}} to the previous one in the first $20$ Latin letters, which is s. The string is now saes.\n\nThe result of performing the sequence of operations is saes.\n\nGiven the string $s$ and the value of $k$, find the lexicographically smallest string that can be obtained after applying a sequence of operations to $s$.",
    "tutorial": "The crucial observation that we have to make is that the character that initially occupied the position $i$ cannot occupy the positions to the left of $i - 2$: we can shift some character two positions to the left using a combination of operations RL, but we can't go any further. So, the prefix of the first $i$ characters of the resulting string can only be affected by the prefix of the first $i + 2$ characters of the initial string. Let's use the following dynamic programming to solve the problem: let $dp_i$ be the lexicographically minimum string that we can obtain by applying operations to the first $i$ characters (that is, $dp_i$ is the answer to the problem if we consider only $i$ first characters of the original string). The transitions here are a bit tricky. If we apply the operation U or D to the character $i + 1$, then $dp_{i + 1} = dp_i + c'$, where $c'$ is the character we get when we apply the aforementioned operation to that character. L is a bit more complicated: we have to insert the character $s_{i + 1}$ just before the last character of $dp_i$. Modeling that we can apply the operation R is likely the most complex transition in our dynamic programming. First of all, we can't just make an update to $dp_{i + 1}$ or $dp_{i + 2}$, since it leads us to a situation where we can still apply some operations to the prefix we have built. Instead, we have to consider the operation we will be able to do with the character $s_{i + 2}$. Using another operation R is useless since the result is like performing no operations with those two characters at all, so we have to consider two options for operation with the $(i + 2)$-th character - D or U (whichever is better), or L. In the first case, we update $dp_{i + 2}$ by appending the resulting two characters to $dp_i$ (the one that we get when we change $s_{i + 2}$, and the one that initially was $s_{i + 1}$). In the second case, things are a bit trickier, but still not very complicated: the character that was $s_{i + 2}$ moves two positions backward, so it is inserted right before the last character of $dp_i$, and then we append $s_{i + 1}$ to the string we get. So, there are four transitions we have to make: a transition from $dp_i$ to $dp_{i + 1}$ that models the case when we apply U or D to the $(i + 1)$-th character; a transition from $dp_i$ to $dp_{i + 1}$ that models the case when we apply L to the $(i + 1)$-th character; a transition from $dp_i$ to $dp_{i + 2}$ to model the operations RD or RU; a transition from $dp_i$ to $dp_{i + 2}$ to model the operations RL. Overall complexity is $O(n^2)$ but it can be improved to $O(n \\log n)$ with some complicated data structures like persistent segment tree with hashes to compare strings and append characters to them in $O(\\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 505;\n\nint n, k;\nstring s;\nstring dp[N];\n\nvoid solve() {\n\tcin >> n >> k >> s;\n\tfor (int i = 1; i <= n; i++)\n\t\tdp[i] = char('z' + 1);\n\tfor (int i = 0; i < n; i++) {\n\t\tint c = s[i] - 'a';\n\t\tint nc = min({c, (c + 1) % k, (c + k - 1) % k});\n\t\tdp[i + 1] = min(dp[i + 1], dp[i] + char('a' + nc));\n\t\tif (i > 0) {\n\t\t\tdp[i + 1] = min(dp[i + 1], dp[i - 1] + char('a' + nc) + s[i - 1]);\n\t\t\tdp[i + 1] = min(dp[i + 1], dp[i].substr(0, i - 1) + s[i] + dp[i].back());\n\t\t}\n\t\tif (i > 1) {\n\t\t\tdp[i + 1] = min(dp[i + 1], dp[i - 1].substr(0, i - 2) + s[i] + dp[i - 1].back() + s[i - 1]);\n\t\t}\n\t}\n\tcout << dp[n] << endl;\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) solve();\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1455",
    "index": "G",
    "title": "Forbidden Value",
    "statement": "Polycarp is editing a complicated computer program. First, variable $x$ is declared and assigned to $0$. Then there are instructions of two types:\n\n- set $y$ $v$ — assign $x$ a value $y$ or spend $v$ burles to remove that instruction (thus, not reassign $x$);\n- if $y$ $\\dots$ end block — execute instructions inside the if block if the value of $x$ is $y$ and ignore the block otherwise.\n\nif blocks can contain set instructions and other if blocks inside them.\n\nHowever, when the value of $x$ gets assigned to $s$, the computer breaks and immediately catches fire. Polycarp wants to prevent that from happening and spend as few burles as possible.\n\nWhat is the minimum amount of burles he can spend on removing set instructions to never assign $x$ to $s$?",
    "tutorial": "Consider the following dynamic programming. $dp_{ij}$ - the minimum cost to make $x$ have value $j$ after the $i$-th line. The transitions here are pretty easy: on set you just consider two options of skipping or not skipping the instructions and on if you either go to the next line or to the end of the block depending on the value. There are a lot of possible values, so that dp works in $O(n^2)$. First, let's notice that all the values that don't appear in the input won't matter, so you can keep only the existing values in the dp. Next, let's consider the following modification to it. What happens when you enter an if block? It's actually the same dp but the only starting value is not $0$ with cost $0$ as in the beginning of the whole program but some value $y$ with some cost $c$. So let's calculate this dp separately from the outer one and just merge the values together. Notice that if some value doesn't appear inside the if block then its cost can not decrease exiting out of it. Thus, it's enough to calculate the inner dp only for values that appear inside the if block. Okay, the transitions for if became easier. The set transitions are still slow, though. Examine the nature of them. All the values besides the $y$ written on the set instruction increase their cost by $v$. As for the $y$, its cost becomes equal to the cost of the cheapest value before the instruction. Thus, let's maintain the dp in some data structure that allows to add the same integer to all elements and take the minimum of its elements. That can be done with a set and a single integer that stores the current shift that should be applied to all elements. Surely, you'll also need a map to retrieve the current cost of particular values. The final part is fast merging of the if block dp and the outer one. It might not appear obvious but if you do that in a straightforward manner of adding all the costs from if one by one it can become $O(n^2)$ in total. So we can apply small-to-large and swap these dp's based on their sizes. Overall complexity: $O(n \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define x first\n#define y second\n\nusing namespace std;\n\nconst long long INF = 1e18;\n\nstruct op{\n\tstring tp;\n\tint y, v, to;\n};\n\nstruct addmap{\n\tlong long add;\n\tmap<int, long long> val;\n\tmultiset<long long> mn;\n};\n\nvoid reset(addmap &a, int x, long long val){\n\tif (a.val.count(x))\n\t\ta.mn.erase(a.mn.find(a.val[x]));\n\ta.val[x] = val - a.add;\n\ta.mn.insert(val - a.add);\n}\n\nint main() {\n\tint n, s;\n\tscanf(\"%d%d\", &n, &s);\n\tstatic char buf[10];\n\top a;\n\tvector<addmap> st;\n\tst.push_back({});\n\tst.back().val[0] = 0;\n\tst.back().add = 0;\n\tst.back().mn.insert(0);\n\tforn(i, n){\n\t\tscanf(\"%s\", buf);\n\t\ta.tp = buf;\n\t\tif (a.tp == \"set\"){\n\t\t\tscanf(\"%d%d\", &a.y, &a.v);\n\t\t\tassert(!st.back().mn.empty());\n\t\t\tlong long mn = st.back().add + *st.back().mn.begin();\n\t\t\tst.back().add += a.v;\n\t\t\tif (a.y != s) reset(st.back(), a.y, mn);\n\t\t}\n\t\telse if (a.tp == \"if\"){\n\t\t\tscanf(\"%d\", &a.y);\n\t\t\tlong long val = INF;\n\t\t\tif (st.back().val.count(a.y)){\n\t\t\t\tval = st.back().val[a.y] + st.back().add;\n\t\t\t\tst.back().mn.erase(st.back().mn.find(st.back().val[a.y]));\n\t\t\t\tst.back().val.erase(a.y);\n\t\t\t}\n\t\t\tst.push_back({});\n\t\t\treset(st.back(), a.y, val);\n\t\t\tst.back().add = 0;\n\t\t}\n\t\telse{\n\t\t\tif (st[int(st.size()) - 1].val.size() > st[int(st.size()) - 2].val.size())\n\t\t\t\tswap(st[int(st.size()) - 1], st[int(st.size()) - 2]);\n\t\t\taddmap& v = st[int(st.size()) - 2];\n\t\t\tfor (auto it : st.back().val){\n\t\t\t\tif (!v.val.count(it.x) || v.val[it.x] + v.add > it.y + st.back().add){\n\t\t\t\t\tif (v.val.count(it.x))\n\t\t\t\t\t\tv.mn.erase(v.mn.find(v.val[it.x]));\n\t\t\t\t\tv.val[it.x] = it.y + st.back().add - v.add;\n\t\t\t\t\tv.mn.insert(it.y + st.back().add - v.add);\n\t\t\t\t}\n\t\t\t}\n\t\t\tst.pop_back();\n\t\t}\n\t}\n\tprintf(\"%lld\\n\", *st.back().mn.begin() + st.back().add);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1456",
    "index": "E",
    "title": "XOR-ranges",
    "statement": "Given integers $c_{0}, c_{1}, \\ldots, c_{k-1}$ we can define the cost of a number $0 \\le x < 2^{k}$ as $p(x) = \\sum_{i=0}^{k-1} \\left( \\left\\lfloor \\frac{x}{2^{i}} \\right\\rfloor \\bmod 2 \\right) \\cdot c_{i}$. In other words, the cost of number $x$ is the sum of $c_{i}$ over the bits of $x$ which are equal to one.\n\nLet's define the cost of array $a$ of length $n \\ge 2$ with elements from $[0, 2^{k})$ as follows: $cost(a) = \\sum_{i=1}^{n - 1} p(a_{i} \\oplus a_{i+1})$, where $\\oplus$ denotes bitwise exclusive OR operation.\n\nYou have to construct an array of length $n$ with minimal cost, given that each element should belong to the given segment: $l_{i} \\le a_{i} \\le r_{i}$.",
    "tutorial": "First, we will make all segments exclusive for convenience. Assume we have segment $(l, r)$, we gonna analyze the process of forming $x$ from highest bit to lowest bit: Let $hb$ is the highest bit such that $hb$-th bit of $l$ and $r$ are different (Apparently, bits higher than $hb$ of x has to be same with bits of $l$ and $r$). We call $hb$ key bit of the segment. Now we set $hb$-th bit of $x$ off (almost similar if we set on). From now on, we have $x < r$ and continue considering lower bits. If the considered bit is on in $l$, we must set this bit on in $x$, otherwise, we have two choices: Set this bit off in $x$ and consider lower bits. Set this bit on in $x$ and don't need to care about lower bits (Because $x > l$ now). Back to the problem, imagine if we fixed all non-free bits of every element, how should we set other bits in order to minimize the cost? It's quite simple: Consider $i$-th bit, call the pair $(l, r)$ visible if $i$-th bits of $l$ and $r$ are non-free but ones of $A[l+1, l+2, .., r-1]$ are free. For each visible pair such that $i$-th bit of endpoints in this pair are different from each other, we'll add $c_{i}$ to the answer. This thing inspire us to write a dynamic programming function: $dp(i, l, r, state(l), state(r))$ ($state(l)$ is $(f, c)$ with $f$ is how did you set key bit for $l$-th element, and $c$ is where is lowest non-free bit of this element (equal to or lower than $i$), similar to $state(r)$) is minimal cost at $i$-th and higher bits of $A[l..r]$ such that $(l, r)$ is currently visible. We have two types of transition: Make $(l, r)$ really visible by going to $(i+1)$-th bit. Make $(l, r)$ invisible by choosing $md (l < md < r)$ and choosing $state(md)$ such that lowest non-free bit of $md$-th element is $i$. Our answer is just $dp(0, 0, N+1, (0, 0), (0, 0))$",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1458",
    "index": "A",
    "title": "Row GCD",
    "statement": "You are given two positive integer sequences $a_1, \\ldots, a_n$ and $b_1, \\ldots, b_m$. For each $j = 1, \\ldots, m$ find the greatest common divisor of $a_1 + b_j, \\ldots, a_n + b_j$.",
    "tutorial": "From basic properties of GCD we know that $GCD(x, y) = GCD(x - y, y)$. The same applies for multiple arguments: $GCD(x, y, z, \\ldots) = GCD(x - y, y, z, \\ldots)$. Let's use this for $GCD(a_1 + b_j, \\ldots, a_n + b_j)$ and subtract $a_1 + b_j$ from all other arguments: $GCD(a_1 + b_j, \\ldots, a_n + b_j) = GCD(a_1 + b_j, a_2 - a_1, \\ldots, a_n - a_1)$. If we find $G = GCD(a_2 - a_1, \\ldots, a_n - a_1)$, then any answer can be found as $GCD(a_1 + b_j, G)$. Note that we have to assume that GCD of an empty set is $0$, and $GCD(x, 0) = x$ for any $x$, since $0$ is the only number divisible by any other number.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1458",
    "index": "B",
    "title": "Glass Half Spilled",
    "statement": "There are $n$ glasses on the table numbered $1, \\ldots, n$. The glass $i$ can hold up to $a_i$ units of water, and currently contains $b_i$ units of water.\n\nYou would like to choose $k$ glasses and collect as much water in them as possible. To that effect you can pour water from one glass to another as many times as you like. However, because of the glasses' awkward shape (and totally unrelated to your natural clumsiness), each time you try to transfer any amount of water, half of the amount is spilled on the floor.\n\nFormally, suppose a glass $i$ currently contains $c_i$ units of water, and a glass $j$ contains $c_j$ units of water. Suppose you try to transfer $x$ units from glass $i$ to glass $j$ (naturally, $x$ can not exceed $c_i$). Then, $x / 2$ units is spilled on the floor. After the transfer is done, the glass $i$ will contain $c_i - x$ units, and the glass $j$ will contain $\\min(a_j, c_j + x / 2)$ units (excess water that doesn't fit in the glass is also spilled).\n\nEach time you transfer water, you can arbitrarlly choose from which glass $i$ to which glass $j$ to pour, and also the amount $x$ transferred can be any positive real number.\n\nFor each $k = 1, \\ldots, n$, determine the largest possible total amount of water that can be collected in arbitrarily chosen $k$ glasses after transferring water between glasses zero or more times.",
    "tutorial": "Suppose that we want to collect water in a certain set of chosen glasses $S$. Let $A_S$ be the total capacity of chosen glasses, and $B_S$ be the total amount of water currently contained in chosen glasses. Also, let $B$ be the total amount of water in all glasses. Clearly, the optimal way is to directly transfer water from non-chosen glasses to chosen ones. Then, we already secured $B_S$ units, and we can transfer up to $B - B_S$ units, thus the largest possible amount is $B_S + (B - B_S) / 2 = B / 2 + B_S / 2$. But all this water may not fit into the chosen glasses, so the actual amount we collect is $\\min(A_S, B / 2 + B_s / 2)$. To find the optimum answer for each $k$, let's use dynamic programming: define $dp[i][k][A]$ as the largest possible $B_S$ for a subset of $k$ glasses among $1, \\ldots, i$ such that the total capacity in the subset is $A$. We can recalculate this with transition $dp[i][k][A] = \\max(dp[i - 1][k][A], dp[i - 1][k - 1][A - a[i]] + b[i])$. Then, $ans[k] = \\max_A \\min(A, dp[n][k][A] / 2 + B / 2)$. Time complexity is $O(n^3 \\max a_i)$, where $\\max a_i$ is the largest capacity of a glass. We can also get rid of storing the first dimension $i$ by overwriting DP values as $i$ increases, and obtain $O(n^2 \\max a_i)$ memory.",
    "tags": [
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1458",
    "index": "C",
    "title": "Latin Square",
    "statement": "You are given a square matrix of size $n$. Every row and every column of this matrix is a permutation of $1$, $2$, $\\ldots$, $n$. Let $a_{i, j}$ be the element at the intersection of $i$-th row and $j$-th column for every $1 \\leq i, j \\leq n$. Rows are numbered $1, \\ldots, n$ top to bottom, and columns are numbered $1, \\ldots, n$ left to right.\n\nThere are six types of operations:\n\n- R: cyclically shift all columns to the right, formally, set the value of each $a_{i, j}$ to $a_{i, ((j - 2)\\bmod n) + 1}$;\n- L: cyclically shift all columns to the left, formally, set the value of each $a_{i, j}$ to $a_{i, (j\\bmod n) + 1}$;\n- D: cyclically shift all rows down, formally, set the value of each $a_{i, j}$ to $a_{((i - 2)\\bmod n) + 1, j}$;\n- U: cyclically shift all rows up, formally, set the value of each $a_{i, j}$ to $a_{(i\\bmod n) + 1, j}$;\n- I: replace the permutation read left to right in each row with its inverse.\n- C: replace the permutation read top to bottom in each column with its inverse.\n\nInverse of a permutation $p_1$, $p_2$, $\\ldots$, $p_n$ is a permutation $q_1$, $q_2$, $\\ldots$, $q_n$, such that $p_{q_i} = i$ for every $1 \\leq i \\leq n$.One can see that after any sequence of operations every row and every column of the matrix will still be a permutation of $1, 2, \\ldots, n$.\n\nGiven the initial matrix description, you should process $m$ operations and output the final matrix.",
    "tutorial": "For convenience, let's assume that all row and column indices, as well as matrix values, are from $0, \\ldots, n - 1$ instead for $1, \\ldots, n$. If only shift operations were present, we could solve the problem in linear time: just maintain where the top left corner ends up after all the shifts, and then the matrix can be easily reconstructed (if this is not immediately clear to you, take a moment and think how this should be done). For the inverse operations, the approach is going to be similar, but we'll need a different way to look at the matrix. Instead of the matrix, let's think about the set of all triples $(i, j, a[i][j])$. Imagining a set of $n^2$ points in 3D, where $i, j$ are $x$ and $y$ coordinates in the horizontal plance, and $a[i][j]$ is the height $z$ is a good mental picture. Shift operations apply $x \\to (x \\pm 1) \\bmod n$ and $y \\to (y \\pm 1) \\bmod n$ to all points. We can think of this as a translation of the entire 3D space, with some looping at the borders. Instead of the given points, let's keep track of where the point $(0, 0, 0)$ is located after the operations are done; it's just as easy as in two-dimensional version from before. Now let's introduce the inverses. Consider, say, a row inverse operation, and all the points $(i, j, k)$, where $k = a[i][j]$, that have the same row index $i$. As an example, suppose that the top ($0$-th) row of the matrix contains numbers $(2, 1, 3, 0)$. The entries in the row correspond to points $(0, 0, 2)$, $(0, 1, 1)$, $(0, 2, 3)$, $(0, 3, 0)$. The inverse permutation to this row is $(3, 1, 0, 2)$, thus the new set of points should be $(0, 0, 3)$, $(0, 1, 1)$, $(0, 2, 0)$, $(0, 3, 2)$. In general, if there is currently a point $(i, j, k)$ in the set, then after the inverse there must be a point $(i, k, j)$. Thus, the entire operation may be summarized as \"swap the second and third coordinates\". Similarly, the column inverse is \"swap the first and third coordinates\". Again, we think of this transformation applied to the entire 3D space: this can be seen as a mirror reflection with respect to $y = z$ or $x = z$ plane. How does this affect our \"keep track of $(0, 0, 0)$\" approach? It is easy to update its position: just swap respective coordinates. However, we now need to care about how the answer is reconstructed, since, say, the point $(1, 0, 0)$ not necessarily ends up one step to the right of $(0, 0, 0)$. Thus, in addition, let's keep track of how the direction vectors $v_x = (1, 0, 0)$, $v_y = (0, 1, 0)$, $v_z = (0, 0, 1)$ are permuted after all operations. Shifts do not affect them, but inverses swap two of them, depending on which coordinates where swapped. We are almost done, we just need to reconstruct the answer at the end. If we had an initially given point $p = (i, j, k)$, where will it end up? If the origin ends up at a position represented as a vector $v_0 = (x, y, z)$, then $p$ ends up at $p' = v_0 + iv_x + jv_y + kv_z$, where $v_x, v_y, v_z$ are permuted accordingly. Once we have the result $p' = (i', j', k')$, all we need is to put $k'$ into $b[i'][j']$, where $b$ is the answer matrix. This results, once again, in a linear time solution. This explanation could have been much shorter with some linear-algebraic machinery (basically each transformation = multiplication by a certain matrix), but I chose to leave it as elementary ($\\neq$ simple!) as possible.",
    "tags": [
      "math",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1458",
    "index": "D",
    "title": "Flip and Reverse",
    "statement": "You are given a string $s$ of 0's and 1's. You are allowed to perform the following operation:\n\n- choose a non-empty contiguous substring of $s$ that contains an equal number of 0's and 1's;\n- flip all characters in the substring, that is, replace all 0's with 1's, and vice versa;\n- reverse the substring.\n\nFor example, consider $s$ = 00111011, and the following operation:\n\n- Choose the first six characters as the substring to act upon: {\\textbf{001110}11}. Note that the number of 0's and 1's are equal, so this is a legal choice. Choosing substrings 0, 110, or the entire string would not be possible.\n- Flip all characters in the substring: {\\textbf{110001}11}.\n- Reverse the substring: {\\textbf{100011}11}.\n\nFind the lexicographically smallest string that can be obtained from $s$ after zero or more operations.",
    "tutorial": "Let's go over characters of $s$ left to right and keep track of the balance = (the number of $0$'s) - (the number of $1$'s) among the visited characters. We can think about starting at the point $0$, and moving right (from $x$ to $x + 1$) when we see a $0$, and moving left (to $x - 1$) when we see a $1$. Each time we go from $x$ to $x \\pm 1$, let's connect the two points with an edge. We'll keep track of all the edges, even if there are multiple ones connecting the same pair of points. Since our path visits all edges we've created exactly once, it is an Eulerian path in the (multi)graph constructed this way. The start point of the path is $0$, and the finish point is equal to the total balance of the string $s$. Now, let's think about what a transformation does. A valid substring subject to the transformation has an equal number of $0$'s and $1$'s, thus it must correspond to a part of our path which is a round tour from a point $x$ back to itself. Flipping and reversing the substring makes us traverse all the same edges, but in reverse order and in reverse direction. Thus, in terms of graphs and paths, what we're doing is reversing a cycle that occurs in the Eulerian path. Note that the collection of edges is preserved after every operation, in other words, the graph is an invariant of the process. Furthermore, the start and finish of the path also stay the same. The answer (= lex. min. string) thus also corresponds to a certain Eulerian path in the very same graph, but which one? It should be the lex. min. path (where we prefer going right before going left) that is obtainable from the initial one with cycle reverses. However, the important observation is: in this particular graph any Eulerian path is obtainable from any other one with cycle reverses (as long as they start and finish in the same places). There are a few ways to prove this. For example, consider two Eulerian paths, and look at the first point where they diverge: say, one goes $x \\to x + 1$, while the other goes $x \\to x - 1$. But both paths will have to eventually return to $x$ to go in the other direction, thus there is at least one extra edge in each direction $x \\to x + 1$ and $x \\to x - 1$, unvisited before the divergence happened. Let's wait until the first path visits at least two edges between $x$ and $x - 1$, returning back to $x$, and reverse the resulting cycle. With this, the next edge after diverging have changed from $x \\to x + 1$ to $x \\to x - 1$, and now the two paths diverge some time later. We can proceed until both paths are the same. The observation implies that we should simply look for the lex. min. Eulerian path in the entire graph. Let's try to do this greedily: build the path from the beginning, marking edges as used when we traverse them. Take the transition $x \\to x + 1$ whenever there is a unused edge leading there, otherwise settle for $x \\to x - 1$. There is a caveat, though: we can not go $x \\to x + 1$ if this uses the last edge between $x$ and $x + 1$, and additionally we still have to visit $x$ some time later (say, if $x$ has unused edges to $x - 1$). However, with this extra condition in place, the greedy algorithm will always find an Eulerian path, and it's clearly the lex. min. one. This procedure is fairly easy to implement in linear time: reconstruct the graph and do the greedy thing.",
    "tags": [
      "data structures",
      "graphs",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1458",
    "index": "E",
    "title": "Nim Shortcuts",
    "statement": "After your debut mobile game \"Nim\" blew up, you decided to make a sequel called \"Nim 2\". This game will expand on the trusted Nim game formula, adding the much awaited second heap!\n\nIn the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.\n\nTo make the game easier to playtest, you've introduced developer shortcuts. There are $n$ shortcut positions $(x_1, y_1), \\ldots, (x_n, y_n)$. These change the game as follows: suppose that before a player's turn the first and second heap contain $x$ and $y$ stones respectively. If the pair $(x, y)$ is equal to one of the pairs $(x_i, y_i)$, then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are \\textbf{ordered}, that is, $x$ must refer to the size of the first heap, and $y$ must refer to the size of the second heap.\n\nThe game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.",
    "tutorial": "Given the shortcut positions, we can immediately mark some initial positions as winning or losing for the first player. Namely, all shortcut positions are immedilately losing, and any position within one move of a shortcut position is winning (unless it's also a shortcut position). In an example picture below cells $(x, y)$ correspond to different initial positions. Red cells mark shortcut positions, and yellow cells are single move wins. Which of the unmarked positions are losing for the starting player? We can repeatedly apply the usual game-analysing rule: if all positions reachable in one move from a position $(x, y)$ are known to be wins, then position $(x, y)$ loses. We'll consider all candidates subject to this rule in lexicographic order. The first candidate is the position $(0, 0)$. A few situations can happen as we proceed forward: $(x, y)$ is a shortcut position. There's no need to mark it as losing, just go to $(x + 1, y + 1)$, as all positions $(x + 1, y)$, $(x + 2, y)$, $\\ldots$ and $(x, y + 1)$, $(x, y + 2)$, $\\ldots$ are known to be single-move wins to $(x, y)$. $(x, y)$ is a single move win to a shortcut $(x', y)$ with $x' < x$. Then, skip $(x, y)$ and go to the next natural candidate $(x + 1, y)$, since all cells $(x, y + 1)$, $(x, y + 2)$, $\\ldots$ are known to be single-move wins to $(x', y)$. $(x, y)$ is a single move win to a shortcut $(x, y')$ with $y' < y$. Then, skip $(x, y)$ and go to the next natural candidate $(x, y + 1)$, since all cells $(x + 1, y)$, $(x + 2, y)$, $\\ldots$ are known to be single-move wine to $(x, y')$. Neither of the above applies. Then, there can be no losing positions reachable in one move from $(x, y)$: single-move wins are eliminated, and all manually marked positions $(x', y'$) saitsfy $x' < x$, $y' < y$. Thus, per our rule, we mark $(x, y)$ as losing and proceed to $(x + 1, y + 1)$. Here's what happens in the picture above. All candidates considered throughout the process are tinted blue, and all identified losing positions are dark blue. With this procedure we can identify all losing positions $(x, y)$ under $x, y \\leq C$ in roughly $O(C \\log n)$ time ($n$ is the number of shortcuts). This is too slow since coordinates can be up to $10^9$. However, we can speed up consecutive applications of the last case of the above procedure as follows: ... Neither of the above applies. Let $X > x$ and $Y > y$ be the closest $x$-coordinate and $y$-coordinate of a shortcut position respectively ($X$ and $Y$ may correspond to different shortcut positions). Let $\\Delta = \\min(X - x, Y - y)$. Then, mark all positions $(x, y), (x + 1, y + 1), \\ldots, (x + \\Delta - 1, y + \\Delta - 1)$ as losing, and go to $(x + \\Delta, y + \\Delta)$. This is justified since all thusly marked positions don't share any coordinate with a shortcut, thus surely they're all subject to this case of the procedure. Looking up $X$ and $Y$ can be implemented with sets of all $x_i$ and $y_i$, and upper bound calls. Further, instead of marking all cells $(x, y), (x + 1, y + 1), \\ldots, (x + \\Delta - 1, y + \\Delta - 1)$ one by one, let's memorize them as a diagonal segment, described by the initial point $(x, y)$ and length $\\Delta$. We can now observe that the optimized process only takes $O(n)$ steps. Indeed, for each step we can find a shortcut $(x_i, y_i)$ such that either $x \\geq x_i$ or $y \\geq y_i$ is true for the first time. In particular, the number of diagonal segments representing all additional losing positions is $O(n)$. Now, to answer any query $(a, b)$ we have to check if one of the following is true: $(a, b)$ is a shortcut; $(a, b)$ belongs to a diagonal segment. The first condition is easy to check if all shortcuts are stored, say, in a set structure. Diagonal segments can also be stored in a set, and we can find the closest to $(a, b)$ with a lower bound, say, by comparing $x$-coordinates. This results in an $O(n \\log n)$ precomputation, and $O(\\log n)$ per initial position query. (Kudos to Golovanov399 for his neat grid drawing tool)",
    "tags": [
      "data structures",
      "games"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1458",
    "index": "F",
    "title": "Range Diameter Sum",
    "statement": "You are given a tree with $n$ vertices numbered $1, \\ldots, n$. A tree is a connected simple graph without cycles.\n\nLet $\\mathrm{dist}(u, v)$ be the number of edges in the unique simple path connecting vertices $u$ and $v$.\n\nLet $\\mathrm{diam}(l, r) = \\max \\mathrm{dist}(u, v)$ over all pairs $u, v$ such that $l \\leq u, v \\leq r$.\n\nCompute $\\sum_{1 \\leq l \\leq r \\leq n} \\mathrm{diam}(l, r)$.",
    "tutorial": "Please bear with my formal style for this one as my hand-waving skills are too weak to explain this properly. We'll use the \"divide-and-conquer\" strategy. Let us implement a recursive procedure $solve(l, r)$ that will compute the sum $\\sum_{l \\leq i \\leq j \\leq r} diam(i, j)$. It will do so as follows: If $l = r$, then answer is trivially $0$. Otherwise, choose $m = \\lfloor(l + r) / 2 \\rfloor$, and compute the following sum: $\\sum_{i = l}^m \\sum_{j = m + 1}^r diam(i, j)$. The only entries $diam(i, j)$ that are not accounted for satisfy either $l \\leq i \\leq j \\leq m$ or $m + 1 \\leq i \\leq j \\leq r$. Compute their total as $solve(l, m) + solve(m + 1, r)$, and return the total answer. Of course, $\\sum_{i = l}^m \\sum_{j = m + 1}^r diam(i, j)$ is the tricky part. We'll need some preparation to compute it. To make arguments cleaner, let us introduce an extra vertex in the middle of every edge, subdividing it into two. We'll refer to new vertices as extra vertices, and the old vertices as proper vertices. Since all distances are doubled, we will have to divide the answer by two in the end. We will define a circle $C(v, r)$ of radius $r$ centered at a vertex $v$ in the tree as the set of all vertices at distance at most $r$ from the vertex $v$. We also assume that if $r > 0$ there are at least two vertices in $C(v, r)$ exactly at distance $r$ from $v$, otherwise decrease $r$ accordingly. For a set of vertices $S$ we define $Cover(S)$ as a circle of smallest radius containing all vertices of $S$. If we assume that all vertices of $S$ are proper, then $Cover(S)$ is unique. Indeed, after subdividing all distances among $S$ are even, thus in $Cover(S) = (v, r)$ we must have $r = diam(S) / 2$, and $v$ is the unique diameter midpoint. We can see that if $r > 0$, then $S$ has at least two vertices at distance $r$ from the covering circle center $v$, namely, the diameter endpoints. Warning: math ahead. It you're not interested in proofs, only read the premise of Lemma 2. Lemma 1. If a circle $C(v, r)$ contains two proper vertices $a, b$, then it also contains the midpoint $c$ on the path between $a, b$, and further $dist(v, c) \\leq r - dist(a, b) / 2$. Proof. Say, for the vertex $a$ we have $dist(v, a) \\leq dist(v, c) + dist(c, a) = dist(v, c) + dist(a, b) / 2$. This inequality is strict: $dist(v, a) < dist(v, c) + dist(c, a)$ only when $v$ and $a$ are in the same subtree with respect to $c$. If we assume that respective inequalities for $a, b$ are both strict, then both $a, b$ are in the same subtree of $c$, in which case $c$ can not be the midpoint. Otherwise, say, for $a$ we have $r \\geq dist(v, a) = dist(v, c) + dist(c, a) = dist(v, c) + dist(a, b) / 2$, and $dist(v, c) \\leq r - dist(a, b) / 2$ by simple rearrangement. An immediate corollary of this lemma is this: if a circle $C(v, r)$ contains a set of proper vertices $S$, it also contains $Cover(S)$. We apply the lemma to the midpoint of $diam(S)$, which is also the center $v'$ of $Cover(S) = C(v', r')$, to establish $dist(v, v') \\leq r - r'$. Then, for any vertex $w$ of $Cover(S)$ we $dist(v, w) \\leq dist(v, v') + dist(v', w) \\leq r$, thus $w \\in C(v, r)$. Lemma 2. Let $S$, $T$ be two non-empty sets of proper vertices. Then the smallest covering circle $Cover(S \\cup T)$ can be found by only knowing $Cover(S)$ and $Cover(T)$, by the following rule: If $Cover(S) \\subseteq Cover(T)$, then $Cover(S \\cup T) = Cover(T)$. If $Cover(T) \\subseteq Cover(S)$, then $Cover(S \\cup T) = Cover(S)$. Let none of $Cover(S) = (v_S, r_S)$ and $Cover(T) = (v_T, r_T)$ contain the other one. Then, $Cover(S \\cup T) = C(V, R)$ has radius $R$ equal to $(r_S + dist(v_S, v_T) + r_T) / 2$ (which is asserted to be an integer), and its center $V$ is located on the unique path $v_S v_T$ at distance $(r - r_S) / 2$ (which is asserted to be an integer) from $v_S$. Proof. The first two cases are somewhat easy. Say, in the first case $Cover(S \\cup T)$ has to contain $T$, then it must contain $Cover(T)$, and then it contains $Cover(S)$ by default. Now, assume the latter case. Any two vertices $v \\in S$, $u \\in T$ satisfy $dist(v, u) \\leq dist(v, v_S) + dist(v_S, v_T) + dist(v_T, u) \\leq r_S + dist(v_S, v_T) + r_T$, thus $\\max dist(v, u) = 2R \\leq r_S + dist(v_S, v_T) + r_T$. Now, let $ab$ and $cd$ be diameter endpoints of $S$ and $T$ respectively. Here we can even choose, say, $a$ outside of $Cover(T)$, since $S \\not \\subseteq Cover(T)$, similarly choose $c \\not \\in Cover(S)$. We then must have $dist(a, c) = r_S + dist(v_S, v_T) + r_T$, thus $Cover(S \\cup T)$ has radius $R$ at least half of that, and $V$ is the only possible center candidate. When one or both of $Cover(S)$ and $Cover(T)$ has zero radius, the claim can established pretty much directly. Okay, we're out of the woods now! The last lemma allows us to maintain $Cover(S) = C(v, r)$ for any set $S$, and further \"merge\" $Cover(S)$ and $Cover(T)$ to obtain $Cover(S \\cup T)$, since all we need is distances between vertices, and finding a vertex on a $v_S v_T$ at certain distance from $v_S$. We can also efficiently check if $C(v, r)$ contains $C(v', r')$ by verifying $dist(v, v') \\leq r - r'$. All of that can be done with binary lifting and LCA manipulations in $O(\\log n)$ per operation. At last, let's get back to the divide-and-conquer step. Let us find circles $C_1(i) = (v_i, r_i) = Cover(i, \\ldots, m)$, and $C_2(j) = (v_j, r_j) = Cover(m + 1, \\ldots, r)$ for all relevant $i, j$. We have $C_1(m) = C(m, 0)$, and $C_1(i)$ is a merge of $C_1(i + 1)$ and $C(i, 0)$ for any smaller $i$; similar for $C_2(j)$. Now, let's consider the sum $\\sum_{j = m + 1}^r diam(i, j)$ for some $i$. $diam(i, j)$ is equal to twice the radius of the merge of $C_1(i)$ and $C_2(j)$. Consider increasing $j$ from $m + 1$ to $r$. Since $C_2(j) \\subseteq C_2(j + 1)$ for any $j$, we have three interesting ranges for $j$, in order from left to right: $j \\in [m + 1, t_1(i))$: $C_2(j) \\subseteq C_1(i)$; $j \\in [t_1(i), t_2(i))$: $C_1(i)$ and $C_2(j)$ are not contained in each other; $j \\in [t_2(i), r]$: $C_1(i) \\subseteq C_2(j)$. In the first range $diam(i, j) = 2r_i$, and in the third range $diam(i, j) = 2r_j$. If we know the boundaries $t_1(i)$ and $t_2(i)$, then these can be accounted for with prefix sums on $r_j$ (and simple multiplcation for $r_i$). In the second range we have to sum up $r_i + dist(v_i, v_j) + r_j$. Again, summands $r_i$ and $r_j$ are accounted in the same way. Only $\\sum_{j \\in [t_1(i), t_2(i))} dist(v_i, v_j)$ remains. Instead of computing this directly right now, consider how $t_1(i)$ and $t_2(i)$ change as $i$ decreases from $m$ to $l$. We have $C_1(i) \\subseteq C_1(i - 1)$, thus we can conclude that $t_1(i)$ and $t_2(i)$ both do not decrease, and the range $[t_1(i), t_2(i))$ is a \"sliding window\" with both endpoints moving to the right. Boundaries $t_1(i)$ and $t_2(i)$ can thus be maintained with the two-pointers approach, and vertices in the range can be maintained with a queue, where vertices enter from the right and leave from the left. On top of the queue that supports \"push-back\" and \"pop-front\", we'd also like to query \"sum of distances from an arbitrary vertex $v$ to all vertices in the queue\". To this end (and only this), we will have to use centroid decomposition in its most basic form. It's fair to say that the margins of this explanation are already too crowded for a proper explanation of this. In short, we can add/remove vertices and query the distance sum in $O(\\log n)$ time. This concludes the divide-and-conquer step description. With the usual divide-and-conquer time analysis we arrive at an $O(n \\log^2 n)$ solution.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1459",
    "index": "A",
    "title": "Red-Blue Shuffle",
    "statement": "There are $n$ cards numbered $1, \\ldots, n$. The card $i$ has a red digit $r_i$ and a blue digit $b_i$ written on it.\n\nWe arrange all $n$ cards in random order from left to right, with all permutations of $1, \\ldots, n$ having the same probability. We then read all red digits on the cards from left to right, and obtain an integer $R$. In the same way, we read all blue digits and obtain an integer $B$. When reading a number, leading zeros can be ignored. If all digits in a number are zeros, then the number is equal to $0$. Below is an illustration of a possible rearrangement of three cards, and how $R$ and $B$ can be found.\n\nTwo players, Red and Blue, are involved in a bet. Red bets that after the shuffle $R > B$, and Blue bets that $R < B$. If in the end $R = B$, the bet results in a draw, and neither player wins.\n\nDetermine, which of the two players is more likely (has higher probability) to win the bet, or that their chances are equal. Refer to the Note section for a formal discussion of comparing probabilities.",
    "tutorial": "First we can observe that if a card has $r_i = b_i$, then if doesn't affect the comparison between $R$ and $B$ regardless of its position. We can forget about all such cards. Formally, if we erase all such cards after the permutation, then $R$ and $B$ are still compared in the same way, and further all the remaining cards are still permuted equiprobably. Now we only have cards with $r_i > b_i$ (let's call them Red-favourable) and $r_i < b_i$ (call them Blue-favourable). But then, the comparison between $R$ and $B$ will only be decided by whether the first card is Red- or Blue-favourable. Naturally, if, say, there are more Red-favourable cards than Blue-favourable cards, then Red is more likely to win. If there is an equal number of Red- and Blue-favourable cards, then the chances are equal. Thus, for the solution purposes we only need to count indices $i$ with $r_i > b_i$ and those with $r_i < b_i$, and compare these two numbers.",
    "tags": [
      "math",
      "probabilities"
    ],
    "rating": 800
  },
  {
    "contest_id": "1459",
    "index": "B",
    "title": "Move and Turn",
    "statement": "A robot is standing at the origin of the infinite two-dimensional plane. Each second the robot moves exactly $1$ meter in one of the four cardinal directions: north, south, west, and east. For the first step the robot \\textbf{can choose any of the four directions}, but then at the end of every second it \\textbf{has to turn} 90 degrees left or right with respect to the direction it just moved in. For example, if the robot has just moved north or south, the next step it takes has to be either west or east, and vice versa.\n\nThe robot makes \\textbf{exactly} $n$ steps from its starting position according to the rules above. How many different points can the robot arrive to at the end? The final orientation of the robot can be ignored.",
    "tutorial": "We will describe an $O(1)$ formula solution. Some slower solutions were also allowed. First, consider the case when $n$ is even. Regardless of the initial direction, we will make $n / 2$ horizontal (west-east) steps and $n / 2$ vertical (north-south) steps. Further, directions of horizontal and vertical steps may be decided independently. If we have to make, say, $k$ horizontal steps choosing left/right direction every time, there are $k + 1$ possible horizontal positions $x$ we can end up in. Indeed, all possible ways can be grouped as follows: $k$ steps left, $0$ steps right: $x = -k$; $k - 1$ steps left, $1$ step right: $x - -k + 2$; ... $0$ steps left, $k$ steps right: $x = k$. Back in the case of even $n$, since the directions for vertical and horizontal steps can be chosen independently, there are $(n / 2 + 1)^2$ possible combinations of final $x$ and $y$. Let's now say that $n = 2k + 1$ is odd. If we start with a horizontal step, then in total we will be making $k + 1$ horizontal steps and $k$ vertical steps, thus the number of combinations here is $(k + 1) \\times (k + 2)$. A similar argument applies for when we start with a vertical step. Finally, observe that it is impossible to reach the same position starting with both vertical and horizontal step. This is because the parity of, say, the final horizontal position $x$ is the same as the number of horizontal steps, thus it can not be the same after $k$ and $k + 1$ horizontal steps. Thus, in the odd case the answer is $2(k + 1)(k + 2)$, where $k = n / 2$ rounded down.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1461",
    "index": "A",
    "title": "String Generation",
    "statement": "One fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length $n$ to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules:\n\n- the string may only contain characters 'a', 'b', or 'c';\n- the maximum length of a substring of this string that is a palindrome does not exceed $k$.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. For example, strings \"a\", \"bc\", \"abc\" are substrings of a string \"abc\", while strings \"ac\", \"ba\", \"cba\" are not.\n\nA string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, strings \"abccba\", \"abbba\", \"aba\", \"abacaba\", \"a\", and \"bacab\" are palindromes, while strings \"abcbba\", \"abb\", and \"ab\" are not.\n\nNow Joe wants to find any correct string. Help him! It can be proven that the answer always exists under the given constraints.",
    "tutorial": "Let's note that the string like \"abcabcabcabc...\" has only palindromes of length 1, what means it is suitable for us in all cases.",
    "code": "#include <bits/stdc++.h>\n \n#define fi first\n#define se second\n#define m_p make_pair\n#define endl '\\n'\n#define fast_io ios_base::sync_with_stdio(0); cin.tie(0)\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int MAXN = 1123456;\nconst int MAXINT = 2147483098;\nconst ll MAXLL = 9223372036854775258LL;\n \nvoid next(char &x) {\n    if (x <= 'b') x++;\n    else x = 'a';\n}\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    char cur = 'a';\n    for (int i = 0; i < n; ++i) {\n        cout << cur;\n        next(cur);\n    } \n    cout << endl;\n}\n \nint main()\n{\n    fast_io;\n    \n    int t;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n    \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1461",
    "index": "B",
    "title": "Find the Spruce",
    "statement": "Holidays are coming up really soon. Rick realized that it's time to think about buying a traditional spruce tree. But Rick doesn't want real trees to get hurt so he decided to find some in an $n \\times m$ matrix consisting of \"*\" and \".\".\n\nTo find every spruce first let's define what a spruce in the matrix is. A set of matrix cells is called a spruce of height $k$ with origin at point $(x, y)$ if:\n\n- All cells in the set contain an \"*\".\n- For each $1 \\le i \\le k$ all cells with the row number $x+i-1$ and columns in range $[y - i + 1, y + i - 1]$ must be a part of the set. All other cells cannot belong to the set.\n\nExamples of correct and incorrect spruce trees:\n\nNow Rick wants to know how many spruces his $n \\times m$ matrix contains. Help Rick solve this problem.",
    "tutorial": "Let's iterate over the top of the spruce. When we meet the symbol \"*\", we will start iterating over the height of the current spruce. If for the current height $k$ for each $1 \\le i \\le k$ all cells with the row number $x+i-1$ and columns in range $[y - i + 1, y + i - 1]$ are \"*\", then we increase the value of the answer. Otherwise, we stop the increment hight.",
    "code": "def solve():\n\tn, m = map(int, input().split())\n\ta = []\n\tfor i in range(n):\n\t\ta.append(input())\n \n\tdp = []\n\tfor i in range(n):\n\t\tdp.append([])\n\t\tfor j in range(m):\n\t\t\tdp[i].append((1 if a[i][j] == '*' else 0) if j == 0 else dp[i][j - 1] + (1 if a[i][j] == '*' else 0))\n \n\tanswer = 0\n\tfor x in range(n):\n\t\tfor y in range(m):\n\t\t\tif a[x][y] == '.':\n\t\t\t\tcontinue\n \n\t\t\tfor level in range(min(n - x, m - y, y + 1)):\n\t\t\t\tif dp[x + level][y + level] - (0 if y - level - 1 < 0 else dp[x + level][y - level - 1]) != level * 2 + 1:\n\t\t\t\t\tbreak\n \n\t\t\t\tanswer += 1\n \n\tprint(answer)\n \n \ntests = int(input())\n \nwhile (tests > 0):\n\tsolve()\n\ttests = tests - 1\t",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1461",
    "index": "C",
    "title": "Random Events",
    "statement": "Ron is a happy owner of a permutation $a$ of length $n$.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nRon's permutation is subjected to $m$ experiments of the following type: ($r_i$, $p_i$). This means that elements in range $[1, r_i]$ (in other words, the prefix of length $r_i$) have to be sorted in ascending order with the probability of $p_i$. All experiments are performed in the same order in which they are specified in the input data.\n\nAs an example, let's take a look at a permutation $[4, 2, 1, 5, 3]$ and an experiment ($3, 0.6$). After such an experiment with the probability of $60\\%$ the permutation will assume the form $[1, 2, 4, 5, 3]$ and with a $40\\%$ probability it will remain unchanged.\n\nYou have to determine the probability of the permutation becoming completely sorted in ascending order after $m$ experiments.",
    "tutorial": "Let's first define some variable $R$, which will be equal to the last unsorted number (the largest $i$ for which $r_i != i$). Now we can see that we are not interested in experiments with $r_i < R$. To get the answer, we just need to multiply the remaining $(1-p_i)$. This number will indicate the probability that all the remaining experiments failed. Since we need to deduce the probability of success, we can subtract the resulting number from one.",
    "code": "def solve(n, m):\n    a = list(map(int, input().split()))\n    lastCorrectPos = n - 1;\n    while lastCorrectPos >= 0 and a[lastCorrectPos] == lastCorrectPos + 1:\n        lastCorrectPos -= 1\n    \n    ans = 1.0\n    if lastCorrectPos == -1:\n        ans = 0.0\n    \n    \n    for _ in range(m):\n        data = input().split()\n        r = int(data[0]) - 1\n        p = float(data[1])\n        \n        if r >= lastCorrectPos:\n            ans = ans * (1 - p)\n        \n    \n    print(\"{:.6f}\".format(1 - ans))\n \n \nt = int(input())\nfor _ in range(t):\n    data = input().split()\n    solve(int(data[0]), int(data[1]))",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1461",
    "index": "D",
    "title": "Divide and Summarize",
    "statement": "Mike received an array $a$ of length $n$ as a birthday present and decided to test how pretty it is.\n\nAn array would pass the $i$-th prettiness test if there is a way to get an array with a sum of elements totaling $s_i$, using some number (possibly zero) of slicing operations.\n\nAn array slicing operation is conducted in the following way:\n\n- assume $mid = \\lfloor\\frac{max(array) + min(array)}{2}\\rfloor$, where $max$ and $min$ — are functions that find the maximum and the minimum array elements. In other words, $mid$ is the sum of the maximum and the minimum element of $array$ divided by $2$ rounded down.\n- Then the array is split into two parts $\\mathit{left}$ and $right$. The $\\mathit{left}$ array contains all elements which are less than or equal $mid$, and the $right$ array contains all elements which are greater than $mid$. Elements in $\\mathit{left}$ and $right$ keep their relative order from $array$.\n- During the third step we choose which of the $\\mathit{left}$ and $right$ arrays we want to keep. The chosen array replaces the current one and the other is permanently discarded.\n\nYou need to help Mike find out the results of $q$ prettiness tests.\n\nNote that you test the prettiness of the array $a$, so you start each prettiness test with the primordial (initial) array $a$. Thus, the first slice (if required) is always performed on the array $a$.",
    "tutorial": "To begin with, you can notice that the cut operation does not depend on the order of the $a$ array. So we can sort it. Now let's build a tree of transitions from the original array to all its possible states. You can simply prove that the height of this tree does not exceed $log(max)$. Since $max(current_a)-min(current_a)$ after each operation of the section is reduced at least twice. Having understood this, we can write a simple recursive search over the states $(left, right)$. The state will describe a sub-segment of the $a$ array that is the current array. For each state, we can calculate the current amount (on the segment from left to right) and add it to any convenient collection (set/HashSet). Next, to respond to requests, we can simply look at our collected collection.",
    "code": "q = set()\na = []\n \ndef go(l, r):\n\tglobal a, q\n \n\tsum = 0\n\tfor i in range(l, r + 1):\n\t\tsum += a[i]\n\tq.add(sum)\n \n\tmid = (a[l] + a[r]) // 2\n \n\tpos = -1\n\tfor i in range(l, r + 1):\n\t\tif a[i] <= mid:\n\t\t\tpos = i\n\t\telse:\n\t\t\tbreak\n \n\tif pos == -1 or pos == r:\n\t\treturn\n \n\tgo(l, pos)\n\tgo(pos + 1, r)\n \n \ndef solve():\n\tglobal a, q\n\tn, m = map(int, input().split())\n\ta = list(map(int, input().split()))\n \n\tq = set()\n\ta.sort()\n\tgo(0, n - 1)\n \n\tfor _ in range(m):\n\t\tx = int(input())\n \n\t\tif x in q:\n\t\t\tprint('YES')\n\t\telse:\n\t\t\tprint('NO')\n \ntests = int(input())\n \nwhile (tests > 0):\n\tsolve()\n\ttests = tests - 1",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "divide and conquer",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1461",
    "index": "E",
    "title": "Water Level",
    "statement": "In recent years John has very successfully settled at his new job at the office. But John doesn't like to idly sit around while his code is compiling, so he immediately found himself an interesting distraction. The point of his distraction was to maintain a water level in the water cooler used by other zebras.\n\nOriginally the cooler contained exactly $k$ liters of water. John decided that the amount of water must always be at least $l$ liters of water but no more than $r$ liters. John will stay at the office for exactly $t$ days. He knows that each day exactly $x$ liters of water will be used by his colleagues. At the beginning of each day he can add exactly $y$ liters of water to the cooler, but at any point in time the amount of water in the cooler must be in the range $[l, r]$.\n\nNow John wants to find out whether he will be able to maintain the water level at the necessary level for $t$ days. Help him answer this question!",
    "tutorial": "If $y \\le x$, it is quite easy to calculate the answer. Note that at each iteration of the algorithm (except, perhaps, the first), the water level will decrease by x-y liters, and we will have to calculate whether it can decrease t times. Otherwise, lets note, when we use the rise in water level, we change the value of the expression $k$ mod $x$. At each step of the algorithm, we will lower the water level as many times as we can, and then raise the level. Further, we note that if we have already reached the value $k$ mod $x$, then we are in a \"cycle\", and therefore we will be able to maintain the water level. If the water level is out of bounds, then the answer is No.",
    "code": "#include <bits/stdc++.h>\n \n#define fi first\n#define se second\n#define m_p make_pair\n#define endl '\\n'\n#define fast_io ios_base::sync_with_stdio(0); cin.tie(0)\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int MAXN = 1123456;\nconst int MAXINT = 2147483098;\nconst ll MAXLL = 8000000000000000000LL;\nconst long double eps = 1e-9;\n \nmt19937_64 mt_rand(\n        chrono::system_clock::now().time_since_epoch().count()\n);\n \n \nint main()\n{\n    fast_io;\n \n    ll k, l, r, t, x, y;\n    cin >> k >> l >> r >> t >> x >> y;\n    if (k < l || k > r) return cout << \"No\\n\", 0;\n    \n    if (x > y) {\n        if (k + y > r) k -= x, t--;\n        \n        if (k < l) return cout << \"No\\n\", 0;\n        \n        ll canAlive = (k - l) / (x - y);\n        if (canAlive < t) return cout << \"No\\n\", 0;\n        \n        cout << \"Yes\" << endl;\n    }else {\n        vector <bool> was(x, false);\n        while(t > 0) {\n            if (was[k % x]) return cout << \"Yes\" << endl, 0;\n            was[k % x] = true;\n            \n            ll canMove = min(t, (k - l) / x);\n            k -= canMove * x;\n            t -= canMove;\n            if (t == 0) return cout << \"Yes\" << endl, 0;\n            t--;\n            if (k + y <= r) k += y;\n            k -= x;\n            if (k < l || k > r) return cout << \"No\" << endl, 0; \n            \n        }\n        \n        cout << \"Yes\" << endl;\n        \n    }\n \n    return 0;\n}",
    "tags": [
      "brute force",
      "graphs",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1461",
    "index": "F",
    "title": "Mathematical Expression",
    "statement": "Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw $n$ numbers $a_1, a_2, \\ldots, a_n$ without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers in a way that would make the resulting expression's value as large as possible. To find out which symbols were available the teacher has given Barbara a string $s$ which contained that information.\n\nIt's easy to notice that Barbara has to place $n - 1$ symbols between numbers in total. The expression must start with a number and all symbols must be allowed (i.e. included in $s$). Note that multiplication takes precedence over addition or subtraction, addition and subtraction have the same priority and performed from left to right. Help Barbara and create the required expression!",
    "tutorial": "First, let's solve the problem without the multiplication sign. It is always beneficial for us to put a plus or a minus, if there is no plus sign. Now we will solve the problem when there is a sign to multiply. The case when the plus sign is missing is very easy to solve. We put the sign to multiply to the first zero, then we put a minus sign in front of the zero, and after the multiplication signs. Let's consider the case when there is a plus sign and multiply. Note that it is never beneficial for us to use the minus sign. If there are zeros in the expression, then we simply put plus signs between them and the expressions are split into other independent expressions. Now you need to be able to solve an expression that has no zeros. To begin with, we take out all units at the beginning and at the end separately with plus signs. The following solution is now proposed. If the product of numbers is greater than or equal to $10^{16}$, then it is beneficial for us to put the multiplication sign everywhere. Otherwise, we can use dynamic programming, because the number of numbers greater than one is no more than $log_2(10^{16})$. Dynamic programming will be one dimension. $dp_i$ is the most profitable answer if you put signs on the prefix. Let us now stand at $i$ and want to go to $j$, this means that between the numbers at the $i$-th and $j$-th positions there will be a sign to multiply, and after the $j$-th position there will be a sign a plus.",
    "code": "#include <bits/stdc++.h>\n \n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC optimize(\"-O3\")\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"fast-math\")\n#pragma GCC optimize(\"no-stack-protector\")\n \n#define fi first\n#define se second\n#define p_b push_back\n#define pll pair<ll,ll>\n#define pii pair<int,int>\n#define m_p make_pair\n#define all(x) x.begin(),x.end()\n#define sset ordered_set\n#define sqr(x) (x)*(x)\n#define pw(x) (1ll << x)\n#define sz(x) (int)x.size()\n#define fout(x) {cout << x << \"\\n\"; return; }\n \nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\nconst ll N = 2e5 + 5;\nconst ll M = 1e7;\nconst ll MAXN = 1123456;\nconst ll inf = 1e17;\nconst ll mod = 1e9 + 7;\nconst ld eps = 1e-10;\n \nll mul(ll a, ll b){\n    return min(a * b, M);\n}\n \nll dp[61], pr[61];\n \nint main(){\n    ios_base :: sync_with_stdio(0);\n    cin.tie(0);\n \n    int n;\n    cin >> n;\n \n    vector <ll> a(n + 1);\n \n    for(int i = 1; i <= n; i++)cin >> a[i];\n    \n    string s;\n    cin >> s;\n    \n    if (n == 3 && a[1] == 2 && a[2] == 2 && a[3] == 0 && s == \"+-*\") {\n        cout << \"2*2-0\\n\";\n        return 0;\n    }\n    \n    if(sz(s) == 1){\n        cout << a[1];\n        for(int i = 2; i <= n; i++){\n            cout << s[0] << a[i];\n        }\n        cout << \"\\n\";\n        return 0;\n    }\n \n    bool fmul, fplus, fminus;\n    fmul = fplus = fminus = 0;\n    for(auto i : s){\n        if(i == '*')fmul = 1;\n        if(i == '+')fplus = 1;\n        if(i == '-')fminus = 1;\n    }\n \n    if(!fmul){\n        if(fplus){\n            cout << a[1];\n            for(int i = 2; i <= n; i++){\n                cout << '+' << a[i];\n            }\n            cout << \"\\n\";\n            return 0;\n        }else{\n            cout << a[1];\n            for(int i = 2; i <= n; i++){\n                cout << '-' << a[i];\n            }\n            cout << \"\\n\";\n            return 0;\n        }\n    }else{\n        if(!fplus){\n            cout << a[1];\n            for(int i = 2; i <= n; i++){\n                if(a[i] == 0)cout << \"-\";\n                else cout << \"*\";\n                cout << a[i];\n            }\n            cout << \"\\n\";\n            return 0;\n        }else{\n            vector <char> b(n + 1, '+');\n \n \n            int uk = 1;\n \n            while(uk <= n){\n                while(uk <= n && a[uk] == 0)uk++;\n                if(uk == n + 1)break;\n                int le = uk;\n                while(uk <= n && a[uk])uk++;\n                int ri = uk - 1;\n                while(le <= ri && a[le] == 1)le++;\n                while(le <= ri && a[ri] == 1)ri--;\n                if(le > ri)continue;\n                ll mult = 1;\n                for(int i = le; i <= ri; i++)mult = mul(mult, a[i]);\n                if(mult == M){\n                    for(int i = le + 1; i <= ri; i++)b[i] = '*';\n                    continue;\n                }\n                vector < pair <ll, pll> > st;\n                int j = le;\n                while(j <= ri){\n                    int l = j;\n                    ll t = 1;\n                    if(a[l] == 1){\n                        while(j <= ri && a[j] == 1)j++;\n                        t = j - l;\n                    }else{\n                        while(j <= ri && a[j] > 1){\n                            if(j != l)b[j] = '*';\n                            t = mul(t, a[j]);\n                            j++;\n                        }\n                    }\n                    st.p_b({t, {l, j - 1}});\n                }\n                int nn = sz(st);\n                for(int i = 1; i <= nn; i++)dp[i] = -inf;\n \n                for(int i = 1; i <= nn; i++){\n                    if(dp[i] < dp[i - 1] + st[i - 1].fi){\n                        pr[i] = i - 1;\n                        dp[i] = dp[i - 1] + st[i - 1].fi;\n                    }\n                    if(i % 2 == 1){\n                        ll t = 1;\n                        for(int j = i; j <= nn; j++){\n                            if((j - i) % 2 == 0)t *= st[j - 1].fi;\n                            if((j - i) % 2 == 0 && dp[j] < t + dp[i - 1]){\n                                pr[j] = i - 1;\n                                dp[j] = t + dp[i - 1];\n                            }\n                        }\n                    }\n                }\n                int x = nn;\n                while(x){\n                    int l = pr[x] + 1, r = x;\n                    x = pr[x];\n                    if(l < r){\n                        for(int i = st[l - 1].se.fi + 1; i <= st[r - 1].se.se; i++)b[i] = '*';\n                    }\n                }\n            }\n \n            cout << a[1];\n            for(int i = 2; i <= n; i++){\n                cout << b[i] << a[i];\n            }\n            cout << \"\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1462",
    "index": "A",
    "title": "Favorite Sequence",
    "statement": "Polycarp has a favorite sequence $a[1 \\dots n]$ consisting of $n$ integers. He wrote it out on the whiteboard as follows:\n\n- he wrote the number $a_1$ to the left side (at the beginning of the whiteboard);\n- he wrote the number $a_2$ to the right side (at the end of the whiteboard);\n- then as far to the left as possible (but to the right from $a_1$), he wrote the number $a_3$;\n- then as far to the right as possible (but to the left from $a_2$), he wrote the number $a_4$;\n- Polycarp continued to act as well, until he wrote out the entire sequence on the whiteboard.\n\n\\begin{center}\n{\\small The beginning of the result looks like this (of course, if $n \\ge 4$).}\n\\end{center}\n\nFor example, if $n=7$ and $a=[3, 1, 4, 1, 5, 9, 2]$, then Polycarp will write a sequence on the whiteboard $[3, 4, 5, 2, 9, 1, 1]$.\n\nYou saw the sequence written on the whiteboard and now you want to restore Polycarp's favorite sequence.",
    "tutorial": "In this problem, you can implement an algorithm opposite to that given in the condition. Let's maintain two pointers to the left-most and right-most unhandled element. Then, restoring the original array, you: put the left-most unhandled item in the first position put the right-most unhandled item in the second position put the left-most unhandled item in the third position put the right-most unhandled item in the fourth position ...",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> v(n);\n  for (int &e : v) {\n    cin >> e;\n  }\n  int left = 0, right = n - 1;\n  vector<int> ans(n);\n  for (int i = 0; i < n; i++) {\n    if (i % 2 == 0) {\n      ans[i] = v[left++];\n    } else {\n      ans[i] = v[right--];\n    }\n  }\n  for (int i : ans) {\n    cout << i << \" \";\n  }\n  cout << \"\\n\";\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "implementation",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1462",
    "index": "B",
    "title": "Last Year's Substring",
    "statement": "Polycarp has a string $s[1 \\dots n]$ of length $n$ consisting of decimal digits. Polycarp performs the following operation with the string $s$ \\textbf{no more than once} (i.e. he can perform operation $0$ or $1$ time):\n\n- Polycarp selects two numbers $i$ and $j$ ($1 \\leq i \\leq j \\leq n$) and removes characters from the $s$ string at the positions $i, i+1, i+2, \\ldots, j$ (i.e. removes substring $s[i \\dots j]$). More formally, Polycarp turns the string $s$ into the string $s_1 s_2 \\ldots s_{i-1} s_{j+1} s_{j+2} \\ldots s_{n}$.\n\nFor example, the string $s = $\"20192020\" Polycarp can turn into strings:\n\n- \"2020\" (in this case $(i, j)=(3, 6)$ or $(i, j)=(1, 4)$);\n- \"2019220\" (in this case $(i, j)=(6, 6)$);\n- \"020\" (in this case $(i, j)=(1, 5)$);\n- other operations are also possible, only a few of them are listed above.\n\nPolycarp likes the string \"2020\" very much, so he is wondering if it is possible to turn the string $s$ into a string \"2020\" in no more than one operation? Note that you can perform zero operations.",
    "tutorial": "Let's see how the deleted substring $t$ should look so that after deleting it, the string $s$ turns into the string \"2020\". The length of the string $t$ must be $n - 4$. Then we can iterate over all substrings of the string $s$ of length $n - 4$ (there are no more than five such substrings) and look at the string obtained after deleting the substring. That is, we need to check that one of the following character sequence matches the $(2, 0, 2, 0)$: $(s[1], s[2], s[3], s[4])$; $(s[1], s[2], s[3], s[n])$; $(s[1], s[2], s[n - 1], s[n])$; $(s[1], s[n - 2], s[n - 1], s[n])$; $(s[n - 3], s[n - 2], s[n - 1], s[n])$;",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  string s;\n  cin >> s;\n\n  for (int i = 0; i <= 4; i++) {\n    if (s.substr(0, i) + s.substr(n - 4 + i, 4 - i) == \"2020\") {\n      cout << \"YES\" << endl;\n      return;\n    }\n  }\n  cout << \"NO\" << endl;\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1462",
    "index": "C",
    "title": "Unique Number",
    "statement": "You are given a positive number $x$. Find the smallest positive integer number that has the sum of digits equal to $x$ and all digits are \\textbf{distinct} (unique).",
    "tutorial": "First of all, let's understand that the answer to the problem should not contain zeros (leading zeros are useless, while others increase the number, but do not change the sum). It is also clear that the number we found should have the minimum possible length (since the longer the numbers without leading zeros, the larger they are). Numbers of the same length are compared lexicographically, that is, first by the first digit, then by the second, and so on. This means that the digits in the number must go in sorted order (the order of the digits does not affect the sum, but does affect the value). Let's minimize the length of the number first. We need to get the specified sum in as few digits as possible. So we should use as large digits as possible. Then let's start with the number $9$ and add the digits from $8$ to $1$ to the beginning of the number in turn, until the sum of the digits exceeds the specified sum. Obviously, you can't get an answer for fewer digits. Now we minimize the number itself. First, we must minimize the first digit. The first digit is uniquely determined as the difference between the sum of the remaining digits and the required sum. So you need to maximize the sum of all digits except the first one (which has already been done in the previous paragraph). It only remains to correct the first digit and print the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n  int x;\n  cin >> x;\n  vector<int> ans;\n  int sum = 0, last = 9;\n  while (sum < x && last > 0) {\n    ans.push_back(min(x - sum, last));\n    sum += last;\n    last--;\n  }\n  if (sum < x) {\n    cout << -1 << \"\\n\";\n  } else {\n    reverse(ans.begin(), ans.end());\n    for (int i : ans) {\n      cout << i;\n    }\n    cout << \"\\n\";\n  }\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1462",
    "index": "D",
    "title": "Add to Neighbour and Remove",
    "statement": "Polycarp was given an array of $a[1 \\dots n]$ of $n$ integers. He can perform the following operation with the array $a$ no more than $n$ times:\n\n- Polycarp selects the index $i$ and adds the value $a_i$ to \\textbf{one of his choice} of its neighbors. More formally, Polycarp adds the value of $a_i$ to $a_{i-1}$ or to $a_{i+1}$ (if such a neighbor does not exist, then it is impossible to add to it).\n- After adding it, Polycarp removes the $i$-th element from the $a$ array. During this step the length of $a$ is decreased by $1$.\n\nThe two items above together denote one single operation.\n\nFor example, if Polycarp has an array $a = [3, 1, 6, 6, 2]$, then it can perform the following sequence of operations with it:\n\n- Polycarp selects $i = 2$ and adds the value $a_i$ to $(i-1)$-th element: $a = [4, 6, 6, 2]$.\n- Polycarp selects $i = 1$ and adds the value $a_i$ to $(i+1)$-th element: $a = [10, 6, 2]$.\n- Polycarp selects $i = 3$ and adds the value $a_i$ to $(i-1)$-th element: $a = [10, 8]$.\n- Polycarp selects $i = 2$ and adds the value $a_i$ to $(i-1)$-th element: $a = [18]$.\n\nNote that Polycarp could stop performing operations at any time.\n\nPolycarp wondered how many minimum operations he would need to perform to make all the elements of $a$ equal (i.e., he wants all $a_i$ are equal to each other).",
    "tutorial": "Let $k$ - be the number of operations performed by Polycarp. Let's see how to check if $k$ is the answer. Let's denote by $s$ the sum of numbers in the array $a$. Note that after each operation $s$ does not change. Since we know that after $k$ operations all elements must be the same and the sum of the numbers in the array does not change, then each of the remaining elements must be equal to $\\frac{s}{n-k}$. Let's check if it is possible to perform $k$ operations so that at the end all elements are equal to $\\frac{s}{n-k}$. Note that the process described in the condition is equivalent to the following process: Choose a set of $n - k + 1$ indices $i_1, i_2, \\dots, i_{n-k+1}$ ($1 = i_1 < i_2 < \\dots < i_ {n - k} < i_ {n - k + 1} = n + 1$) - partitions; Create a new array $b$ of $n - k$ elements, where $b_j = \\sum\\limits_{t=i_j}^{i_{j+1}-1} b_t$ $b_j = \\sum\\limits_{t=i_j}^{i_{j+1}-1} b_t$ Then, to check if $k$ is the answer, it is necessary to split the $a$ array into $n - k$ subarrays, in which the sum of all elements is equal to $\\frac{s}{n-k}$. Such a check can be implemented greedily in $\\mathcal{O}(n)$. It is enough to go through the array from left to right and take an element into the current subarray until the sum in it exceeds $\\frac{s}{n-k}$. The resulting solution works in $\\mathcal{O}(n \\cdot \\sigma(s))$ or $\\mathcal{O}(n^2)$, where $\\sigma(s)$ is the number of divisors $s$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<ll> a(n);\n  ll sum = 0;\n  for (ll &x : a) {\n    cin >> x;\n    sum += x;\n  }\n\n  for (int i = n; i >= 1; i--) {\n    if (sum % i == 0) {\n      ll needSum = sum / i;\n      ll curSum = 0;\n      bool ok = true;\n      for (int j = 0; j < n; j++) {\n        curSum += a[j];\n        if (curSum > needSum) {\n          ok = false;\n          break;\n        } else if (curSum == needSum) {\n          curSum = 0;\n        }\n      }\n\n      if (ok) {\n        cout << n - i << endl;\n        return;\n      }\n    }\n  }\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1462",
    "index": "E1",
    "title": "Close Tuples (easy version)",
    "statement": "\\textbf{This is the easy version of this problem. The only difference between easy and hard versions is the constraints on $k$ and $m$ (in this version $k=2$ and $m=3$). Also, in this version of the problem, you DON'T NEED to output the answer by modulo.}\n\nYou are given a sequence $a$ of length $n$ consisting of integers from $1$ to $n$. \\textbf{The sequence may contain duplicates (i.e. some elements can be equal)}.\n\nFind the number of tuples of $m = 3$ elements such that the maximum number in the tuple differs from the minimum by no more than $k = 2$. Formally, you need to find the number of triples of indices $i < j < z$ such that\n\n$$\\max(a_i, a_j, a_z) - \\min(a_i, a_j, a_z) \\le 2.$$\n\nFor example, if $n=4$ and $a=[1,2,4,3]$, then there are two such triples ($i=1, j=2, z=4$ and $i=2, j=3, z=4$). If $n=4$ and $a=[1,1,1,1]$, then all four possible triples are suitable.",
    "tutorial": "In the easy version of the problem, you can count how many times each number occurs (the numbers themselves do not exceed $n$). Note that we do not have very many options for which triples of numbers can be included in the answer. Let's iterate over $x$ - the minimum number in the triples. Then there are the following options: [$x$, $x + 1$, $x + 2$]; [$x$, $x + 1$, $x + 1$]; [$x$, $x + 2$, $x + 2$]; [$x$, $x$, $x + 1$]; [$x$, $x$, $x + 2$]; [$x$, $x$, $x$]. In each option, you need to multiply the number of ways to choose one, two or three numbers from all occurrences of this number. This is done using binomial coefficients. Formally, if $cnt[x]$ - is the number of occurrences of the number $x$, then the formulas corresponding to the options in the list above are as follows: $cnt[x] \\cdot cnt[x + 1] \\cdot cnt[x + 2]$; $cnt[x] \\cdot \\frac{cnt[x + 1] \\cdot (cnt[x + 1] - 1)}{2}$; $cnt[x] \\cdot \\frac{cnt[x + 2] \\cdot (cnt[x + 2] - 1)}{2}$; $\\frac{cnt[x] \\cdot (cnt[x] - 1)}{2} \\cdot cnt[x + 1]$; $\\frac{cnt[x] \\cdot (cnt[x] - 1)}{2} \\cdot cnt[x + 2]$; $\\frac{cnt[x] \\cdot (cnt[x] - 1) \\cdot (cnt[x] - 2)}{6}$. If we sum these values over all $x$ from $1$ to $n$, then we get the answer to the problem.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<ll> cnt(n + 1);\n  for (int i = 0; i < n; i++) {\n    int x;\n    cin >> x;\n    cnt[x]++;\n  }\n  ll ans = 0;\n  for (int i = 2; i < n; i++) {\n    ans += cnt[i - 1] * cnt[i] * cnt[i + 1];\n  }\n  for (int i = 1; i < n; i++) {\n    ans += cnt[i] * (cnt[i] - 1) / 2 * cnt[i + 1];\n  }\n  for (int i = 2; i <= n; i++) {\n    ans += cnt[i - 1] * cnt[i] * (cnt[i] - 1) / 2;\n  }\n  for (int i = 2; i < n; i++) {\n    ans += cnt[i - 1] * cnt[i + 1] * (cnt[i + 1] - 1) / 2;\n  }\n  for (int i = 2; i < n; i++) {\n    ans += cnt[i + 1] * cnt[i - 1] * (cnt[i - 1] - 1) / 2;\n  }\n  for (int i = 1; i <= n; i++) {\n    ans += cnt[i] * (cnt[i] - 1) * (cnt[i] - 2) / 6;\n  }\n  cout << ans << \"\\n\";\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1462",
    "index": "E2",
    "title": "Close Tuples (hard version)",
    "statement": "\\textbf{This is the hard version of this problem. The only difference between the easy and hard versions is the constraints on $k$ and $m$. In this version of the problem, you need to output the answer by modulo $10^9+7$.}\n\nYou are given a sequence $a$ of length $n$ consisting of integers from $1$ to $n$. \\textbf{The sequence may contain duplicates (i.e. some elements can be equal)}.\n\nFind the number of tuples of $m$ elements such that the maximum number in the tuple differs from the minimum by no more than $k$. Formally, you need to find the number of tuples of $m$ indices $i_1 < i_2 < \\ldots < i_m$, such that\n\n$$\\max(a_{i_1}, a_{i_2}, \\ldots, a_{i_m}) - \\min(a_{i_1}, a_{i_2}, \\ldots, a_{i_m}) \\le k.$$\n\nFor example, if $n=4$, $m=3$, $k=2$, $a=[1,2,4,3]$, then there are two such triples ($i=1, j=2, z=4$ and $i=2, j=3, z=4$). If $n=4$, $m=2$, $k=1$, $a=[1,1,1,1]$, then all six possible pairs are suitable.\n\n\\textbf{As the result can be very large, you should print the value modulo $10^9 + 7$ (the remainder when divided by $10^9 + 7$)}.",
    "tutorial": "The key idea that allows us to move from the previous version to this one is that the values of the numbers themselves are not important to us. The main idea is to consider all numbers in the interval $[x, x + k]$. Let's also, as in the previous version, iterate over the minimum element $x$ in the tuple. Now let's find the count of numbers $cnt$ that lie in the interval $[x, x + k]$ (this can be done with a binary search, two pointers, or prefix sums using an array of occurrences). Then it remains to add to the answer the number of ways to choose $m - 1$ numbers from $cnt - 1$ (we fixed one of the numbers as the minimum). You have to sum these values over all possible values of $x$ (even the same) because now you are not fixing the value of the minimum element (as in the previous problem), but its index in the sorted array. To calculate binomial coefficients quickly, you can pre-compute all factorial values and all $\\frac{1}{n!}$ values by modulo. If you do not know how to calculate the inverse element by modulo, then you could pre-compute the part of Pascal's triangle in $\\mathcal{O}(nm)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nconst int N = 300500;\nconst int mod = 1000000007;\nll fact[N];\nll invFact[N];\n\nll fast_pow(ll a, ll p) {\n    ll res = 1;\n    while (p) {\n        if (p % 2 == 0) {\n            a = (a * a) % mod;\n            p /= 2;\n        } else {\n            res = (res * a) % mod;\n            p--;\n        }\n    }\n    return res;\n}\n\nll C(int n, int k) {\n    if (k > n) {\n        return 0;\n    }\n    return fact[n] * invFact[k] % mod * invFact[n - k] % mod;\n}\n\nvoid solve() {\n    int n, m, k;\n    cin >> n >> m >> k;\n    vector<ll> v(n);\n    for (ll &e : v) {\n        cin >> e;\n    }\n    sort(v.begin(), v.end());\n    ll ans = 0;\n    for (int i = 0; i < n; i++) {\n        int l = i + 1;\n        int r = upper_bound(v.begin(), v.end(), v[i] + k) - v.begin();\n        ans = (ans + C(r - l, m - 1)) % mod;\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    fact[0] = invFact[0] = 1;\n    for (int i = 1; i < N; i++) {\n        fact[i] = (fact[i - 1] * i) % mod;\n        invFact[i] = fast_pow(fact[i], mod - 2);\n    }\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "implementation",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1462",
    "index": "F",
    "title": "The Treasure of The Segments",
    "statement": "Polycarp found $n$ segments on the street. A segment with the index $i$ is described by two integers $l_i$ and $r_i$ — coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.\n\nPolycarp believes that a set of $k$ segments is good if there is a segment $[l_i, r_i]$ ($1 \\leq i \\leq k$) from the set, such that it intersects every segment from the set (the intersection must be a \\textbf{point or segment}). For example, a set of $3$ segments $[[1, 4], [2, 3], [3, 6]]$ is good, since the segment $[2, 3]$ intersects each segment from the set. Set of $4$ segments $[[1, 2], [2, 3], [3, 5], [4, 5]]$ is not good.\n\nPolycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set?",
    "tutorial": "As we know from the problem statement: Polycarp believes that a set of $k$ segments is good if there is a segment $[l_i, r_i]$ ($1 \\leq i \\leq k$) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). Let's iterate over this segment (which intersects all the others) and construct a good set of the remaining segments, maximum in terms of inclusion. It is easy to understand that this set will include all segments that intersect with ours. We must delete all other segments. Two segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect if $max(l_1, l_2) \\le min(r_1, r_2)$. Then if the segment that we iterate over has coordinates $[L, R]$, then we must remove all such segments $[l, r]$ for which $r < L$ or $R < l$ is satisfied (that is, the segment ends earlier than ours begins, or vice versa). Note that these two conditions cannot be fulfilled simultaneously, since $l \\le r$, and if both conditions are satisfied, then $r < L \\le R < l$. This means that we can count the number of segments suitable for these conditions independently. Each of these conditions is easy to handle. Let's create two arrays - all the left boundaries of the segments and all the right boundaries of the segments. Let's sort both arrays. Now we can count the required quantities using the binary search or prefix sums (but in this case, we need to use the coordinate compression technique). Taking at least the number of deleted segments among all the options, we will get the answer to the problem.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    vector<int> L;\n    vector<int> R;\n    int n;\n    cin >> n;\n    vector<pair<int, int>> v(n);\n    for (auto &[l, r] : v) {\n        cin >> l >> r;\n        L.push_back(l);\n        R.push_back(r);\n    }\n    sort(L.begin(), L.end());\n    sort(R.begin(), R.end());\n    int ans = n - 1;\n    for (auto [l, r] : v) {\n        int left = lower_bound(R.begin(), R.end(), l) - R.begin();\n        int right = max(0, n - (int)(upper_bound(L.begin(), L.end(), r) - L.begin()));\n        ans = min(ans, left + right);\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n\n",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1463",
    "index": "A",
    "title": "Dungeon",
    "statement": "You are playing a new computer game in which you have to fight monsters. In a dungeon you are trying to clear, you met three monsters; the first of them has $a$ health points, the second has $b$ health points, and the third has $c$.\n\nTo kill the monsters, you can use a cannon that, when fired, deals $1$ damage to the selected monster. Every $7$-th (i. e. shots with numbers $7$, $14$, $21$ etc.) cannon shot is enhanced and deals $1$ damage to \\textbf{all} monsters, not just one of them. If some monster's current amount of health points is $0$, it can't be targeted by a regular shot and does not receive damage from an enhanced shot.\n\nYou want to pass the dungeon beautifully, i. e., kill all the monsters with the same enhanced shot (i. e. after some enhanced shot, the health points of each of the monsters should become equal to $0$ \\textbf{for the first time}). Each shot must hit a monster, i. e. each shot deals damage to at least one monster.",
    "tutorial": "Note that for every $7$ shots, we deal a total of $9$ units of damage. Since we want to kill all the monsters with a shot which index is divisible by $7$, let's denote the number of shots as $7k$. In this case, a total of $a+b+c$ units of damage must be dealt, hence $k=\\frac{a+b+c}{9}$ (if the result of the division is not an integer, then there is no answer). Since each monster will receive at least $k$ units of damage (with enhanced shots), the health of each monster must be at least $k$. If the two conditions described above are met, then the remaining shots can always be distributed in the desired way.",
    "code": "for i in range(int(input())):\n\ta, b, c = map(int, input().split())\n\tif (a + b + c) % 9 != 0:\n\t\tprint(\"NO\")\n\telse:\n\t    print(\"YES\" if min(a, b, c) >= (a + b + c) // 9 else \"NO\")",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1463",
    "index": "B",
    "title": "Find The Array",
    "statement": "You are given an array $[a_1, a_2, \\dots, a_n]$ such that $1 \\le a_i \\le 10^9$. Let $S$ be the sum of all elements of the array $a$.\n\nLet's call an array $b$ of $n$ integers \\textbf{beautiful} if:\n\n- $1 \\le b_i \\le 10^9$ for each $i$ from $1$ to $n$;\n- for every pair of adjacent integers from the array $(b_i, b_{i + 1})$, either $b_i$ divides $b_{i + 1}$, or $b_{i + 1}$ divides $b_i$ (or both);\n- $2 \\sum \\limits_{i = 1}^{n} |a_i - b_i| \\le S$.\n\nYour task is to find any beautiful array. It can be shown that at least one beautiful array always exists.",
    "tutorial": "It is enough to consider two possible arrays $b$: ($a_1, 1, a_3, 1, a_5, \\dots$) and ($1, a_2, 1, a_4, 1, \\dots$). It is not difficult to notice that in these arrays, the condition is met that among two neighboring elements, one divides the other. It remains to show that at least one of these two arrays satisfies the condition $2 \\sum \\limits_{i = 1}^{n} |a_i - b_i| \\le S$. Let's consider $S_{odd}$ - the sum of elements at odd positions and $S_{even}$ - the sum of elements at even positions. Since $S=S_{odd}+S_{even}$, at least one of the values of $S_{odd}$ and $S_{even}$ does not exceed $\\frac{S}{2}$ (because otherwise their sum will be strictly greater than $S$). Without losing generality, assume that $S_{odd} \\le \\frac{S}{2}$. Note that for the second variant of the array $b$, the condition $\\sum \\limits_{i = 1}^{n} |a_i - b_i| \\le S_{odd}$ holds, so $2 \\sum \\limits_{i = 1}^{n} |a_i - b_i| \\le S$.",
    "code": "for t in range(int(input())):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\ts = sum(a)\n\tcur = [0, 0]\n\tfor i in range(n):\n\t\tcur[i % 2] += a[i] - 1\n\tfor j in range(2):\n\t\tif 2 * cur[j] > s:\n\t\t\tcontinue\n\t\tfor i in range(n):\n\t\t\tif i % 2 == j:\n\t\t\t\ta[i] = 1\n\t\tbreak\n\tprint(*a)",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1463",
    "index": "C",
    "title": "Busy Robot",
    "statement": "You have a robot that can move along a number line. At time moment $0$ it stands at point $0$.\n\nYou give $n$ commands to the robot: at time $t_i$ seconds you command the robot to go to point $x_i$. Whenever the robot receives a command, it starts moving towards the point $x_i$ with the speed of $1$ unit per second, and he stops when he reaches that point. However, while the robot is moving, it \\textbf{ignores} all the other commands that you give him.\n\nFor example, suppose you give three commands to the robot: at time $1$ move to point $5$, at time $3$ move to point $0$ and at time $6$ move to point $4$. Then the robot stands at $0$ until time $1$, then starts moving towards $5$, ignores the second command, reaches $5$ at time $6$ and immediately starts moving to $4$ to execute the third command. At time $7$ it reaches $4$ and stops there.\n\nYou call the command $i$ successful, if there is a time moment in the range $[t_i, t_{i + 1}]$ (i. e. after you give this command and before you give another one, both bounds inclusive; we consider $t_{n + 1} = +\\infty$) when the robot is at point $x_i$. Count the number of successful commands. Note that it is possible that an ignored command is successful.",
    "tutorial": "The main idea in the problem is not how to solve it but how to code it neatly. I've come up with the following way. Let's store three variables: where is the robot now, what direction does it move ($-1$, $0$ or $1$) and how much time is left until it stops moving. The processing of the commands looks becomes pretty easy. If there is no time left to move then the command is executed, and we tell the robot the direction and the time left for the current command. Then there are two cases: either the robot stops before the next command or after it. However, they can be processed simultaneously. Let $T$ be the minimum of the time left before the robot stops moving and the time before the next command. We sure know that before the next command the robot will visit exactly the segment of positions between the current position and the current position plus direction multiplied by $T$. If the destination for the current command is in this segment, then that command is successful. After the command is processed subtract $T$ from the time left and increase the position by direction multiplied by $T$. Overall complexity: $O(n)$ per testcase.",
    "code": "def inside(l, r, x):\n\treturn min(l, r) <= x <= max(l, r)\n\ndef sg(x):\n\treturn -1 if x < 0 else int(x > 0)\n\nfor _ in range(int(input())):\n\tn = int(input())\n\tqs = []\n\tfor i in range(n):\n\t\tqs.append(list(map(int, input().split())))\n\tqs.append([4*10**9, 0])\n\tans = 0\n\tpos, dr, lft = 0, 0, 0\n\tfor i in range(n):\n\t\tt, x = qs[i]\n\t\ttn = qs[i + 1][0]\n\t\tif lft == 0:\n\t\t\tlft = abs(pos - x)\n\t\t\tdr = sg(x - pos)\n\t\ttmp = min(lft, tn - t)\n\t\tif inside(pos, pos + dr * tmp, x):\n\t\t\tans += 1\n\t\tpos += dr * tmp\n\t\tlft -= tmp\n\tprint(ans)",
    "tags": [
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1463",
    "index": "D",
    "title": "Pairs",
    "statement": "You have $2n$ integers $1, 2, \\dots, 2n$. You have to redistribute these $2n$ elements into $n$ pairs. After that, you choose $x$ pairs and take minimum elements from them, and from the other $n - x$ pairs, you take maximum elements.\n\nYour goal is to obtain the set of numbers $\\{b_1, b_2, \\dots, b_n\\}$ as the result of taking elements from the pairs.\n\nWhat is the number of different $x$-s ($0 \\le x \\le n$) such that it's possible to obtain the set $b$ if for each $x$ you can choose how to distribute numbers into pairs and from which $x$ pairs choose minimum elements?",
    "tutorial": "Let's prove that in the set $b$ $x$ minimum elements will be from $x$ pairs where we'll take minimums and analogically $n - x$ maximums will be from $n - x$ pairs where we'll take maximums. By contradiction, let's look at two pairs $(a, b)$ ($a < b$) and $(c, d)$ ($c < d$), where we will take maximum from $(a, b)$ and minimum from $(c, d)$ and $b < c$, if we swap elements $b$ and $c$ and get pair $(a, c)$, $(b, d)$, the result won't change, but now minimum from pair $(b, d)$ will be less than maximum from $(a, c)$. So we can always make pairs in such a way that the chosen minimum from any pair will be less than the chosen maximum from any other pair. Let's make set $nb$ as all elements which are not in $b$. In the same way, we can prove that $n - x$ minimums of $nb$ are from pairs where we took maximums and $x$ maximums are from pairs where we took minimums. Let's say $b$ and $nb$ are sorted. Now we've proven that for a fixed $x$ we should pair $b_1, b_2, \\dots, b_x$ with $nb_{n - x + 1}, nb_{n - x + 2}, \\dots, nb_{n}$ and $b_{x + 1}, \\dots, b_n$ with $nb_1, \\dots, nb_{n - x}$. It's not hard to prove that it's optimal to pair $(b_1, nb_{n - x + 1})$, $(b_2, nb_{n - x + 2})$, ..., $(b_x, nb_n)$ and in the same way $(nb_1, b_{x + 1})$, $(nb_2, b_{x + 2})$, ..., $(nb_{n - x}, b_n)$. For a fixed $x$ we can just check that constructed pairs are valid. But what happens if we move from $x$ to $x + 1$? If for $1 \\le i \\le n - x$ all $(nb_i, b_{x + i})$ was valid then for $x + 1$ all pairs $(nb_i, b_{x + 1 + i})$ will be valid as well. And on contrary, if at least one pair $(b_i, nb_{n - x + i})$ wasn't valid then for $x + 1$ the pair $(b_i, nb_{n - x - 1 + i})$ won't be valid as well. Due to monotony we can find the maximum valid $x$ just checking only pairs $(b_i, nb_{n - x + i})$ and in the same way we can find maximum $n - x$ (minimum $x$) such that all pairs $(nb_i, b_{x + i})$ are valid. That's why all valid $x$-s form a segment, and we need to find its borders. We can find a maximum $x$ (maximum $n - x$) with either binary search or with two pointers and print the length of the segment. Time complexity is either $O(n)$ or $O(n \\log{n})$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nconst int INF = int(1e9);\n\nint n;\nvector<int> b;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\tb.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> b[i];\n\treturn true;\n}\n\nint getMax(const vector<int> &a, const vector<int> &b) {\n\tint uk = 0;\n\tfore (i, 0, sz(a)) {\n\t\twhile (uk < sz(b) && b[uk] < a[i])\n\t\t\tuk++;\n\t\tif (uk >= sz(b))\n\t\t\treturn i;\n\t\tuk++;\n\t}\n\treturn sz(a);\n}\n\ninline void solve() {\n\tvector<int> nb;\n\tfore (i, 1, 2 * n + 1) {\n\t\tif (!binary_search(b.begin(), b.end(), i))\n\t\t\tnb.push_back(i);\n\t}\n\t\n\tint mxX = getMax(b, nb);\n\tint mnX = n - getMax(nb, b);\n\t\n\tcout << mxX - mnX + 1 << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint t; cin >> t;\n\twhile(t--) {\n\t    read();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1463",
    "index": "E",
    "title": "Plan of Lectures",
    "statement": "Ivan is a programming teacher. During the academic year, he plans to give $n$ lectures on $n$ different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the $1$-st, $2$-nd, ..., $n$-th lecture — formally, he wants to choose some permutation of integers from $1$ to $n$ (let's call this permutation $q$). $q_i$ is the index of the topic Ivan will explain during the $i$-th lecture.\n\nFor each topic (except \\textbf{exactly one}), there exists a prerequisite topic (for the topic $i$, the prerequisite topic is $p_i$). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.\n\nOrdering the topics correctly can help students understand the lectures better. Ivan has $k$ special pairs of topics $(x_i, y_i)$ such that he knows that the students will understand the $y_i$-th topic better if the lecture on it is conducted \\textbf{right after} the lecture on the $x_i$-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every $i \\in [1, k]$, there should exist some $j \\in [1, n - 1]$ such that $q_j = x_i$ and $q_{j + 1} = y_i$.\n\nNow Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.",
    "tutorial": "The prerequisites for each lecture form a rooted tree, so let's forget about the legend and learn how to find such an order of vertices of a tree that all conditions work. Let's introduce some algorithm that produces an ordering of vertices for every possible case. If any valid ordering exists, it should produce a valid one. So we will only have to check if the resulting ordering is fine and output it if it is. If there were no special pairs, the task would be perfectly solvable with an algorithm of topological sorting. Thus, let's come up with a way to modify the graph, so that topsort could still be a solution. We know that the vertices that are in the special pairs should follow each other in the ordering. Look at these special pairs as edges as well. Let's first imagine they are undirected. These edges connect some vertices in the tree into components. Each component should be a segment of vertices in a valid answer. So how about we compress them into one vertex first each, find some answer for a compressed version and decompress them back? Let each of these connected components be a vertex in the new graph. Two components are connected by an edge if there is a edge in the tree between vertices of the corresponding components. Topsort in this graph will tell us the order the components should go. However, we should also find the order the vertices should go inside each component. Let's topsort the graph of all directed special pairs and sort the vertices in that order in every component. We can sort the entire graph instead of sorting each component separately because the components are totally independent. Finally, write down the answer: iterate over the compressed vertices of the first new graph in the order of its topsort, for each one write down all the actual vertices inside it in the order of the topsort of the second new graph. Check if each vertex has its parent earlier than itself in the answer. If all the graphs were topologically sortable and that holds, then the answer exists, and we found it. Otherwise, the answer doesn't exist. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nvector<vector<int>> g, h, ng;\n\nvector<int> rk, p;\n\nint getp(int a){\n\treturn a == p[a] ? a : p[a] = getp(p[a]);\n}\n\nvoid unite(int a, int b){\n\ta = getp(a), b = getp(b);\n\tif (a == b) return;\n\tif (rk[a] < rk[b]) swap(a, b);\n\trk[a] += rk[b];\n\tp[b] = a;\n}\n\nvector<vector<int>> comp;\n\nvector<int> ord;\nvector<int> used;\nbool fl;\n\nvoid ts(int v, const vector<vector<int>> &g){\n\tused[v] = 1;\n\tfor (int u : g[v]){\n\t\tif (used[u] == 0)\n\t\t\tts(u, g);\n\t\telse if (used[u] == 1)\n\t\t\tfl = false;\n\t\tif (!fl) return;\n\t}\n\tord.push_back(v);\n\tused[v] = 2;\n}\n\nbool topsort(const vector<vector<int>> &g){\n\tint n = g.size();\n\tused.assign(n, 0);\n\tord.clear();\n\tfl = true;\n\tforn(i, n) if (!used[i]){\n\t\tts(i, g);\n\t\tif (!fl) return false;\n\t}\n\treverse(ord.begin(), ord.end());\n\treturn true;\n}\n\nvector<int> pos;\n\nbool dfs(int v){\n\tfor (int u : g[v]){\n\t\tif (pos[u] < pos[v])\n\t\t\treturn false;\n\t\tif (!dfs(u))\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tg.resize(n);\n\th.resize(n);\n\tng.resize(n);\n\tint rt = -1;\n\tforn(i, n){\n\t\tint p;\n\t\tscanf(\"%d\", &p);\n\t\t--p;\n\t\tif (p == -1)\n\t\t\trt = i;\n\t\telse\n\t\t\tg[p].push_back(i);\n\t}\n\trk.assign(n, 1);\n\tp.resize(n);\n\tiota(p.begin(), p.end(), 0);\n\tforn(i, m){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\th[v].push_back(u);\n\t\tunite(v, u);\n\t}\n\tif (!topsort(h)){\n\t\tputs(\"0\");\n\t\treturn 0;\n\t}\n\tauto ord1 = ord;\n\tvector<int> pos1(n);\n\tforn(i, n) pos1[ord1[i]] = i;\n\tforn(v, n) for (int u : g[v]) if (getp(v) != getp(u))\n\t\tng[getp(v)].push_back(getp(u));\n\tif (!topsort(ng)){\n\t\tputs(\"0\");\n\t\treturn 0;\n\t}\n\tcomp.resize(n);\n\tforn(i, n) comp[getp(i)].push_back(i);\n\tvector<int> fin;\n\tfor (int it : ord){\n\t\tsort(comp[it].begin(), comp[it].end(), [&](int v, int u){ return pos1[v] < pos1[u]; });\n\t\tfor (int v : comp[it])\n\t\t\tfin.push_back(v);\n\t}\n\tpos.resize(n);\n\tforn(i, n) pos[fin[i]] = i;\n\tif (!dfs(rt)){\n\t\tputs(\"0\");\n\t\treturn 0;\n\t}\n\tfor (int v : fin)\n\t\tprintf(\"%d \", v + 1);\n\tputs(\"\");\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation",
      "sortings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1463",
    "index": "F",
    "title": "Max Correct Set",
    "statement": "Let's call the set of positive integers $S$ \\textbf{correct} if the following two conditions are met:\n\n- $S \\subseteq \\{1, 2, \\dots, n\\}$;\n- if $a \\in S$ and $b \\in S$, then $|a-b| \\neq x$ and $|a-b| \\neq y$.\n\nFor the given values $n$, $x$, and $y$, you have to find the maximum size of the \\textbf{correct} set.",
    "tutorial": "The key idea of the task is to prove that there is an optimal answer where the chosen elements in $S$ has a period equal to $p = x + y$. Let's work with $0, 1, \\dots, n - 1$ instead of $1, 2, \\dots, n$. Firstly, let's prove that if we've chosen correct set $a_1, \\dots, a_k$ in interval $[l, l + p)$ then if we take all $a_i + p$ then set $\\{ a_1, \\dots, a_k, a_1 + p, \\dots a_k + p \\}$ will be corect as well. By contradiction: suppose we have $a_i + p - a_j = x$ ($y$), then $a_i - a_j = x - p = x - x - y = -y$ ($-x$) or $|a_i - a_j| = y$ ($x$) - contradiction. It means that if we take the correct set in interval $[l, l + p)$ we can create a periodic answer by copying this interval several times. Next, let's prove that there is an optimal periodic answer. Let's look at any optimal answer and its indicator vector (binary vector of length $n$ where $id_i = 1$ iff $i$ is in the set). Let $r = n \\bmod p$. Let's split the vector in $2 \\left\\lfloor \\frac{n}{p} \\right\\rfloor + 1$ intervals: $[0, r), [r, p), [p, p + r), [p + r, 2p), \\dots, [n - r, n)$. The $1$-st, $3$-rd, $5$-th... segments have length $r$ and $2$-nd, $4$-th,... segments have length $p - r$. If we choose any two consecutive segments its total length will be equal to $p$ and we can use it to make periodic answer by replacing all length $r$ segments with the chosen one and $p - r$ segments with the other one. We can prove that we can always find such two consecutive segments that the induced answer will be greater or equal to the initial one. If we create vector where $v_i$ is equal to the sum of $id_j$ in the $i$-th segment, then the task is equivalent to finding $v_i$ and $v_{i + 1}$ such that replacing all $v_{i \\pm 2z}$ by $v_i$ and all $v_{i + 1 \\pm 2z}$ by $v_{i + 1}$ won't decrease array $v$ sum. The proof is down below. Now, since the answer is periodical, taking element $c$ ($0 \\le c < p$) is equivalent to taking all elements $d \\equiv c \\bmod p$, so for each $c$ we can calc $val_c$ - the number of integers with the same remainder. And for each $c$ we either take it or not. So we can write $dp[p][2^{\\max(x, y)}]$, where $dp[i][msk]$ is the maximum sum if we processed $i$ elements and last $\\max(x, y)$ elements are described by mask $msk$. We start with $dp[0][0]$ and, when look at the $i$-th element, either take it (if we can) or skip it. Time complexity is $O((x + y) 2^{\\max(x, y)})$. ========== Let's prove that for any array $v_1, v_2, \\dots, v_{2n + 1}$ we can find pair $v_p, v_{p + 1}$ such that replacing all $v_{p \\pm 2z}$ with $v_p$ and all $v_{p + 1 \\pm 2z}$ with $v_{p + 1}$ won't decrease the total sum. Let's define $S_o = \\sum\\limits_{i = 1}^{n + 1}{v_{2i - 1}}$ and $S_e = \\sum\\limits_{i = 1}^{n}{v_{2i}}$. Let's make array $b_1, \\dots, b_{2n + 1}$, where $b_{2i - 1} = (n + 1)v_{2i - 1} - S_o$ and $b_{2i} = n \\cdot v_{2i} - S_e$. The meaning behind $b_i$ is how changes the total sum if we replace corresponding elements by $v_i$. Note, that finding a good pair $v_p, v_{p + 1}$ is equivalent to finding $b_p + b_{p + 1} \\ge 0$. Also, note that $\\sum\\limits_{i = 1}^{n + 1}{b_{2i - 1}} = (n + 1)S_o - (n + 1)S_o = 0$ and analogically, $\\sum\\limits_{i = 1}^{n}{b_{2i}} = n \\cdot S_e - n \\cdot S_e = 0$. Let's prove by contradiction: suppose that for any $i$ $b_i + b_{i + 1} < 0$. Let's look at $\\sum\\limits_{i = 1}^{2n + 1}{b_i} = \\sum\\limits_{i = 1}^{n + 1}{b_{2i - 1}} + \\sum\\limits_{i = 1}^{n}{b_{2i}} = 0$. But from the other side, we know that $b_2 + b_3 < 0$, $b_4 + b_5 < 0$, ..., $b_{2n} + b_{2n + 1} < 0$, so $b_1 > 0$, otherwise $\\sum\\limits_{i = 1}^{2n + 1}{b_i}$ will be negative. In the same way, since $b_1 + b_2 < 0$, $b_4 + b_5 < 0$, ..., $b_{2n} + b_{2n + 1} < 0$, then $b_3 > 0$. Analogically we can prove that each $b_{2i - 1} > 0$, but $\\sum\\limits_{i = 1}^{n + 1}{b_{2i - 1}} = 0$ - contradiction. So, there is always a pair $b_p + b_{p + 1} \\ge 0$, i. e. a pair $v_p, v_{p + 1}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\nconst int N = 22;\n\nint dp[2][1 << N];\nint val[2 * N];\n\nint main() {\n\tint n, x, y;\n\tscanf(\"%d%d%d\", &n, &x, &y);\n\t\n\tint k = x + y;\n\tint m = max(x, y);\n\tint FULL = (1 << m) - 1;\n\t\n\tfor (int i = 0; i < k; ++i)\n\t\tval[i] = n / k + (i < n % k);\n\tfor (int mask = 0; mask < (1 << m); ++mask)\n\t\tdp[0][mask] = -INF;\n\tdp[0][0] = 0;\n\t\n\tfor (int i = 0; i < k; ++i) {\n\t\tfor (int mask = 0; mask < (1 << m); ++mask)\n\t\t\tdp[1][mask] = -INF;\n\t\tfor (int mask = 0; mask < (1 << m); ++mask) {\n\t\t\tif (dp[0][mask] == -INF)\n\t\t\t\tcontinue;\n\t\t\tint nmask = (mask << 1) & FULL;\n\t\t\tdp[1][nmask] = max(dp[1][nmask], dp[0][mask]);\n\t\t\tif (((mask >> (x - 1)) & 1) | ((mask >> (y - 1)) & 1))\n\t\t\t\tcontinue;\n\t\t\tnmask |= 1;\n\t\t\tdp[1][nmask] = max(dp[1][nmask], dp[0][mask] + val[i]);\n\t\t}\n\t\tswap(dp[0], dp[1]);\n\t}\n\t\n\tint ans = 0;\n\tfor (int mask = 0; mask < (1 << m); ++mask) \n\t\tans = max(ans, dp[0][mask]);\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "bitmasks",
      "dp",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1464",
    "index": "F",
    "title": "My Beautiful Madness",
    "statement": "You are given a tree. We will consider simple paths on it. Let's denote path between vertices $a$ and $b$ as $(a, b)$. Let $d$-neighborhood of a path be a set of vertices of the tree located at a distance $\\leq d$ from at least one vertex of the path (for example, $0$-neighborhood of a path is a path itself). Let $P$ be a multiset of the tree paths. Initially, it is empty. You are asked to maintain the following queries:\n\n- $1$ $u$ $v$ — add path $(u, v)$ into $P$ ($1 \\leq u, v \\leq n$).\n- $2$ $u$ $v$ — delete path $(u, v)$ from $P$ ($1 \\leq u, v \\leq n$). Notice that $(u, v)$ equals to $(v, u)$. For example, if $P = \\{(1, 2), (1, 2)\\}$, than after query $2$ $2$ $1$, $P = \\{(1, 2)\\}$.\n- $3$ $d$ — if intersection of all $d$-neighborhoods of paths from $P$ is not empty output \"Yes\", otherwise output \"No\" ($0 \\leq d \\leq n - 1$).",
    "tutorial": "When I write \"a vertex at a distance $d$ up from the given\", I mean such a vertex, if it exists; otherwise the root of the tree. Let's learn how to answer the query of whether the intersection of $d$-neighborhoods of all paths is empty. For a given path poman is a vertex at a distance $d$ up from the LCA of this path. Lemma: if the intersection is non-empty, then the deepest poman vertex is included in it. Proof: let the intersection be non-empty, and the deepest poman vertex (let's call it $v$) is not included in the intersection. The path that spawned $v$ is located along with the neighborhood in $v$'s subtree. $v$ is not included in the intersection, so there is some path whose neighborhood does not contain v. Note that it cannot be in the subtree of $v$, since then its poman vertex would be deeper than $v$; hence it lies outside the subtree $v$ with the neighborhood, hence the intersection of all neighborhoods is empty. Contradiction. This knowledge allows us to check if the intersection is empty by checking if one particular vertex $v$ lies in the intersection (for a query, recognizing $v$ is easy if we maintain a set of LCA of paths from P, ordered by depth). Let $kek$ be a vertex at a distance $d$ above $v$. First, a necessary condition: for each path from $P$, the subtree of $kek$ contains at least one end. Let's implement it like this: when the path $(u, v)$ comes, we do ad[u]++, ad[v]++, ad[LCA(u, v)]--. Now the sum of ad in a subtree of a vertex is the number of ends of different paths in it. Now we know for sure that there is no path that lies strictly outside the $kek$ subtree, that is, all paths for which LCA is outside the subtree of $kek$ pass through $kek$, and hence $v$ lies in their $d$-neighborhood. The only remaining paths to check are those in the $kek$ subtree. The shortest distance from $v$ to such paths is the distance to their $LCA$ (this is not true if the $LCA$ lies on the path $(v, kek)$, but this path itself has length $d$ and we will definitely reach such $LCA$ from $v$). We got the following task about processing queries on a tree: podkek[v]++ podkek[v]-- among the vertices of the given subtree with $podkek[v] > 0$, find the farthest from the given vertex (also contained in this subtree)",
    "code": "#pragma GCC optimize(\"O3\")\n \n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n \nusing namespace std;\n \nconst int LG = 20;\nconst int inf = 1e9 + 228;\n \nstruct Fenwick {\n\tint n;\n\tvector<int> t;\n\tFenwick(int n) : n(n), t(n) {}\n\tvoid upd(int v, int x) {\n\t\tfor (int i = v; i < n; i |= i + 1) {\n\t\t\tt[i] += x;\n\t\t}\n\t}\n\tint get(int v) {\n\t\tint res = 0;\n\t\tfor (int i = v; i >= 0; i = (i & (i + 1)) - 1) {\n\t\t\tres += t[i];\n\t\t}\n\t\treturn res;\n\t}\n\tint get(int l, int r) {\n\t\treturn get(r) - get(l - 1);\n\t}\n};\n \nstruct SegTree {\n\tint n;\n\tvector<int> t;\n\tSegTree(int n) : n(n), t(2 * n, -inf) {}\n\tvoid upd(int v, int x) {\n\t\tt[v += n] = x;\n\t\tfor (v >>= 1; v; v >>= 1) {\n\t\t\tt[v] = max(t[v << 1], t[v << 1 | 1]);\n\t\t}\n\t}\n\tint get(int l, int r) {\n\t\tint ret = -inf;\n\t\tfor (l += n, r += n; l <= r; l = (l + 1) >> 1, r = (r - 1) >> 1) {\n\t\t\tif (l & 1) {\n\t\t\t\tret = max(ret, t[l]);\n\t\t\t}\n\t\t\tif (!(r & 1)) {\n\t\t\t\tret = max(ret, t[r]);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n};\n \nstruct Query {\n\tint type;\n\tint u, v;\n\tint d;\n};\n \nstruct HpItem {\n\tint in_hp_v;\n\tint in_desc_v;\n\tint src_v;\n\tbool operator < (const HpItem& o) const {\n\t\treturn in_hp_v > o.in_hp_v || in_hp_v == o.in_hp_v && in_desc_v > o.in_desc_v || \n\t\t\tin_hp_v == o.in_hp_v && in_desc_v == o.in_desc_v && src_v > o.src_v;\n\t}\n};\n \nint n, q;\nvector<vector<int>> g;\nvector<Query> qs;\nvector<vector<int>> up;\nvector<int> pred;\nvector<int> in;\nvector<int> out;\nint timer;\nvector<int> dep;\nvector<int> sz;\nvector<int> top;\nvector<int> bot;\nvector<vector<HpItem>> hpq;\nvector<SegTree> onBot;\nvector<SegTree> onTop;\nvector<vector<int>> cnt;\n \nvoid dfs_tree(int v, int p) {\n\tif (v > 0) {\n\t\tauto it = g[v].begin();\n\t\twhile (*it != p) {\n\t\t\tit++;\n\t\t}\n\t\tg[v].erase(it);\n\t}\n\tup[v][0] = p;\n\tpred[v] = p - !v;\n\tfor (int i = 1; i < LG; i++) {\n\t\tup[v][i] = up[up[v][i - 1]][i - 1];\n\t}\n\tsz[v] = 1;\n\tfor (int& to : g[v]) {\n\t\tdep[to] = dep[v] + 1;\n\t\tdfs_tree(to, v);\n\t\tsz[v] += sz[to];\n\t\tif (sz[to] > sz[g[v][0]]) {\n\t\t\tswap(to, g[v][0]);\n\t\t}\n\t}\n}\n \nvoid dfs_hld(int v) {\n\tin[v] = timer++;\n\tfor (int to : g[v]) {\n\t\tif (to == g[v][0]) {\n\t\t\ttop[to] = top[v];\n\t\t\tbot[top[v]] = to;\n\t\t}\n\t\telse {\n\t\t\ttop[to] = to;\n\t\t\tbot[to] = to;\n\t\t}\n\t\tdfs_hld(to);\n\t}\n\tout[v] = timer;\n}\n \nbool upper(int u, int v) {\n\treturn (in[u] <= in[v] && out[v] <= out[u]);\n}\n \nint lca(int u, int v) {\n\tif (in[u] > in[v]) {\n\t\tswap(u, v);\n\t}\n\tif (upper(u, v)) {\n\t\treturn u;\n\t}\n\tfor (int i = LG - 1; i >= 0; i--) {\n\t\tif (!upper(up[u][i], v)) {\n\t\t\tu = up[u][i];\n\t\t}\n\t}\n\treturn up[u][0];\n}\n \nint kth(int v, int k) {\n\tfor (int i = LG - 1; i >= 0; i--) {\n\t\tif ((1 << i) <= k) {\n\t\t\tv = up[v][i];\n\t\t\tk -= (1 << i);\n\t\t}\n\t}\n\treturn v;\n}\n \nvoid upd(int u, int dt) {\n\tint v = u;\n\tint desc = -1;\n\twhile (v != -1) {\n\t\tint pos = lower_bound(hpq[top[v]].begin(), hpq[top[v]].end(), HpItem{ in[v], (desc == -1 ? -1 : in[desc]), u }) - hpq[top[v]].begin();\n\t\tbool ex = (cnt[top[v]][pos] > 0);\n\t\tcnt[top[v]][pos] += dt;\n\t\tif (!ex) {\n\t\t\tonBot[top[v]].upd(pos, dep[u]);\n\t\t\tonTop[top[v]].upd(pos, dep[u] - dep[v] + (dep[bot[top[v]]] - dep[v]));\n\t\t}\n\t\telse if (cnt[top[v]][pos] == 0) {\n\t\t\tonBot[top[v]].upd(pos, -inf);\n\t\t\tonTop[top[v]].upd(pos, -inf);\n\t\t}\n\t\tdesc = top[v];\n\t\tv = pred[top[v]];\n\t}\n}\n \nint get(int u, int v) { // lower upper\n\tint ret = -inf;\n\tint roma = u;\n\tint desc = -1;\n\twhile (top[u] != top[v]) {\n\t\tint R = upper_bound(hpq[top[u]].begin(), hpq[top[u]].end(), HpItem{ in[u], (desc == -1 ? -1 : in[desc]), -inf }) - hpq[top[u]].begin(); // [R..\n\t\tint L = upper_bound(hpq[top[u]].begin(), hpq[top[u]].end(), HpItem{ in[u], (desc == -1 ? -1 : in[desc]), inf }) - hpq[top[u]].begin() - 1; // ..L]\n\t\tif (L >= 0) {\n\t\t\tret = max(ret, (onBot[top[u]].get(0, L) - dep[u]) + (dep[roma] - dep[u]));\n\t\t}\n\t\tif (R < onTop[top[u]].n) {\n\t\t\tret = max(ret, (onTop[top[u]].get(R, onTop[top[u]].n - 1) - (dep[bot[top[u]]] - dep[u])) + (dep[roma] - dep[u]));\n\t\t}\n\t\tdesc = top[u];\n\t\tu = pred[top[u]];\n\t}\n\t{\n\t\tint R = upper_bound(hpq[top[u]].begin(), hpq[top[u]].end(), HpItem{ in[u], (desc == -1 ? -1 : in[desc]), -inf }) - hpq[top[u]].begin(); // [R..\n\t\tint L = upper_bound(hpq[top[u]].begin(), hpq[top[u]].end(), HpItem{ in[u], (desc == -1 ? -1 : in[desc]), inf }) - hpq[top[u]].begin() - 1; // ..L]\n\t\tif (L >= 0) {\n\t\t\tret = max(ret, (onBot[top[u]].get(0, L) - dep[u]) + (dep[roma] - dep[u]));\n\t\t}\n\t\tint bound = upper_bound(hpq[top[u]].begin(), hpq[top[u]].end(), HpItem{ in[v], -inf, -inf }) - hpq[top[u]].begin() - 1;\n\t\tif (R <= bound) {\n\t\t\tret = max(ret, (onTop[top[u]].get(R, bound) - (dep[bot[top[u]]] - dep[u])) + (dep[roma] - dep[u]));\n\t\t}\n\t}\n\treturn ret;\n}\n \nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcin >> n >> q;\n\tg.resize(n);\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\t--u; --v;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\tqs.resize(q);\n\tfor (auto& qry : qs) {\n\t\tcin >> qry.type;\n\t\tif (qry.type <= 2) {\n\t\t\tcin >> qry.u >> qry.v;\n\t\t\t--qry.u;\n\t\t\t--qry.v;\n\t\t}\n\t\telse {\n\t\t\tcin >> qry.d;\n\t\t}\n\t}\n\tup.resize(n, vector<int>(LG));\n\tdep.resize(n);\n\tsz.resize(n);\n\tpred.resize(n);\n\tdfs_tree(0, 0);\n\tin.resize(n);\n\tout.resize(n);\n\ttop.resize(n);\n\tbot.resize(n);\n\tdfs_hld(0);\n\thpq.resize(n);\n\tfor (int u = 0; u < n; u++) {\n\t\tint v = u;\n\t\tint desc = -1;\n\t\twhile (v != -1) {\n\t\t\thpq[top[v]].push_back({ in[v], (desc == -1 ? -1 : in[desc]), u });\n\t\t\tdesc = top[v];\n\t\t\tv = pred[top[v]];\n\t\t}\n\t}\n\tcnt.resize(n);\n\tfor (int u = 0; u < n; u++) {\n\t\tsort(hpq[u].begin(), hpq[u].end());\n\t\tonBot.emplace_back(hpq[u].size());\n\t\tonTop.emplace_back(hpq[u].size());\n\t\tcnt[u].resize(hpq[u].size());\n\t}\n\tmultiset<pair<int, int>> setik;\n\tFenwick fen(n);\n\tfor (int i = 0; i < q; i++) {\n\t\tif (qs[i].type == 1) {\n\t\t\tint u = qs[i].u;\n\t\t\tint v = qs[i].v;\n\t\t\tint _lca = lca(u, v);\n\t\t\tsetik.insert({ dep[_lca], _lca });\n\t\t\tfen.upd(in[u], 1);\n\t\t\tfen.upd(in[v], 1);\n\t\t\tfen.upd(in[_lca], -1);\n\t\t\tupd(_lca, 1);\n\t\t}\n\t\telse if (qs[i].type == 2) {\n\t\t\tint u = qs[i].u;\n\t\t\tint v = qs[i].v;\n\t\t\tint _lca = lca(u, v);\n\t\t\tsetik.erase(setik.find({ dep[_lca], _lca }));\n\t\t\tfen.upd(in[u], -1);\n\t\t\tfen.upd(in[v], -1);\n\t\t\tfen.upd(in[_lca], 1);\n\t\t\tupd(_lca, -1);\n\t\t}\n\t\telse {\n\t\t\tint d = qs[i].d;\n\t\t\tint v = setik.rbegin()->second;\n\t\t\tint roma = kth(v, d);\n\t\t\tint u = kth(roma, d);\n\t\t\tif (fen.get(in[u], out[u] - 1) != setik.size()) {\n\t\t\t\tcout << \"No\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcout << (get(roma, u) <= d ? \"Yes\\n\" : \"No\\n\");\n\t\t}\n\t}\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1466",
    "index": "A",
    "title": "Bovine Dilemma",
    "statement": "Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.\n\nThere are $n$ trees growing along the river, where Argus tends Io. For this problem, the river can be viewed as the $OX$ axis of the Cartesian coordinate system, and the $n$ trees as points with the $y$-coordinate equal $0$. There is also another tree growing in the point $(0, 1)$.\n\nArgus will tie a rope around three of the trees, creating a triangular pasture. Its exact shape doesn't matter to Io, but its area is crucial to her. There may be many ways for Argus to arrange the fence, but only the ones which result in different areas of the pasture are interesting for Io. Calculate the number of \\textbf{different} areas that her pasture may have. Note that the pasture must have \\textbf{nonzero} area.",
    "tutorial": "The solution is to iterate over all possible triangles, find their areas, and compute how many of these areas are distinct. So the problem is to calculate the area of a given triangle efficiently. There are many possible ways to do it; I will describe the most straightforward method. Recall the formula for the triangle's area: $area = \\frac{base \\cdot height}{2}$ As we want to count distinct areas we can forget about dividing by $2$ and focus on calculating $base \\cdot height$. Note that all triangles are of form $(x_1, 0)$, $(x_2, 0)$ and $(0, 1)$. Thanks to this, if we pick a side $(x_1, 0)$, $(x_2, 0)$ as a base, then the height is equal to $1$! As a result, $base \\cdot height = |x_1 - x_2|$. Final complexity is $\\mathcal{O}(n^2)$ per test case. Try to solve it for $n, x_i \\leq 10^5$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tint n;\n\tscanf(\"%d\", &n);\n\n\tvector <int> in(n);\n\tfor(auto &p: in)\n\t\tscanf(\"%d\", &p);\n\t\n\tset <int> S;\n\tfor(int i = 0; i < n; ++i)\n\t\tfor(int j = i + 1; j < n; ++j)\n\t\t\tS.insert(in[j] - in[i]);\n\n\tprintf(\"%d\\n\", (int)S.size());\n}\n\nint main() {\n\tint cases;\n\tscanf(\"%d\", &cases);\n\t\n\twhile(cases--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "geometry",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1466",
    "index": "B",
    "title": "Last minute enhancements",
    "statement": "Athenaeus has just finished creating his latest musical composition and will present it tomorrow to the people of Athens. Unfortunately, the melody is rather dull and highly likely won't be met with a warm reception.\n\nHis song consists of $n$ notes, which we will treat as \\textbf{positive integers}. The \\textbf{diversity} of a song is the number of \\textbf{different} notes it contains. As a patron of music, Euterpe watches over composers and guides them throughout the process of creating new melodies. She decided to help Athenaeus by changing his song to make it more diverse.\n\nBeing a minor goddess, she cannot arbitrarily change the song. Instead, for each of the $n$ notes in the song, she can either leave it as it is or \\textbf{increase} it by $1$.\n\nGiven the song as a sequence of integers describing the notes, find out the maximal, achievable diversity.",
    "tutorial": "We describe two solutions. The first focuses on maximal contiguous intervals of values. We notice that for each such interval $[l, r]$ it can either remain unchanged or get increased to $[l, r + 1]$ (other possibilities won't increase the number of different elements; thus, we don't need to consider them). From this observation, we conclude that the result is the number of different elements in the input increased by the number of intervals containing at least one duplicate. The second is based on a simple, greedy approach, where we analyze the elements in nondecreasing order. While analyzing, we keep the set of elements for which we have already decided its value. When we want to add the next element, then we check if it is in the set. If it is, we increase it by $1$; otherwise, we keep it as it is. Can you solve it if we can increase note $x_i$ by any integer in $[0, k_i]$, for given $k_i$?",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tint n;\n\tscanf(\"%d\", &n);\n\n\tset <int> S;\n\tfor(int i = 1; i <= n; ++i) {\n\t\tint v;\n\t\tscanf(\"%d\", &v);\n\n\t\tif(S.count(v))\n\t\t\tv++;\n\t\tS.insert(v);\n\t}\n\t\n\tprintf(\"%d\\n\", (int)S.size());\n}\n\nint main() {\n\tint cases;\n\tscanf(\"%d\", &cases);\n\t\n\twhile(cases--)\n\t\tsolve();\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1466",
    "index": "C",
    "title": "Canine poetry",
    "statement": "After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades.\n\nOrpheus, a famous poet, and musician plans to calm Cerberus with his poetry and safely walk past him. He created a very peculiar poem for Cerberus. It consists only of lowercase English letters.\n\nWe call a poem's substring a palindrome if and only if it reads the same backwards and forwards. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deleting several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.\n\nUnfortunately, Cerberus dislikes palindromes of length greater than $1$. For example in the poem abaa the hound of Hades wouldn't like substrings aba and aa.\n\nOrpheus can only calm Cerberus if the hound likes his poetry. That's why he wants to change his poem so that it does not contain any palindrome substrings of length \\textbf{greater than $1$}.\n\nOrpheus can modify the poem by replacing a letter at any position with any lowercase English letter. He can use this operation arbitrarily many times (possibly zero). Since there can be many palindromes in his poem, he may have to make some corrections. But how many, exactly? Given the poem, determine the minimal number of letters that have to be changed so that the poem does not contain any palindromes of length greater than $1$.",
    "tutorial": "The main observation is that if there exists a palindrome of length larger than $3$, then there exists a palindrome of length $2$ or $3$. This observation allows us to simplify the task to erasing all palindromes of length $2$ or $3$. We can also notice that each character will be replaced at most once. From now on, there are a few possible solutions. The easiest one is to iterate over a word from left to right. When we encounter a palindrome (of length $2$ or $3$) ending on the current position, consisting of unmarked elements, we greedily mark this character as the one we want to replace. The number of marked characters is the answer, as it turns out that we can obtain a valid palindrome-less sequence by replacing only the letters on the marked positions. The complexity is $\\mathcal{O}(n)$. The sketch of proof is as follows: it is sufficient to ensure that each marked character does not coincide with $4$ neighboring characters, so we are still left with $22$ remaining possibilities. We can try different approaches too. One of these is a $dp$-based solution, where the state $dp[i][c_a][c_b]$ denotes the minimal result after analyzing first $i$ elements, where characters $s_i$ and $s_{i - 1}$ are equal to $c_a$ and $c_b$ respectively. This $dp$ can be implemented in $\\mathcal{O}(n \\cdot 26^2)$, which should pass, but is pretty messy to implement, so we want to improve it. We can notice that we are not interested in the last $2$ characters' exact values, but only if these were changed or not (the same observation as in the greedy solution). Thanks to this, our state changes to $dp[i][c_i][c_{i - 1}]$, where $c_i$ encodes whether $i$-th character was changed. This $dp$ can be cleanly implemented in linear time. What if letters can change, and you need the calculate the result after each change?",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1e5 + 7;\n\nint n;\nchar in[N];\nint dp[N][2][2];\n\nvoid solve(){\n\tscanf(\"%s\", in + 1);\n\tn = strlen(in + 1);\n\n\tfor(int ta = 0; ta < 2; ++ta)\n\t\tfor(int tb = 0; tb < 2; ++tb)\n\t\t\tdp[0][ta][tb] = 0;\n\n\tfor(int i = 1; i <= n; ++i)\n\t\tfor(int ta = 0; ta < 2; ++ta)\n\t\t\tfor(int tb = 0; tb < 2; ++tb)\n\t\t\t\tdp[i][ta][tb] = N;\n\t\n\tfor(int i = 1; i <= n; ++i){\n\t\tif(in[i] != in[i - 1]){\n\t\t\tif(in[i] != in[i - 2])\n\t\t\t\tdp[i][0][0] = min(dp[i][0][0], dp[i - 1][0][0]);\n\t\t\tdp[i][0][0] = min(dp[i][0][0], dp[i - 1][0][1]);\n\t\t}\n\t\t\n\t\tif(in[i] != in[i - 2])\n\t\t\tdp[i][0][1] = min(dp[i][0][1], dp[i - 1][1][0]);\n\t\tdp[i][0][1] = min(dp[i][0][1], dp[i - 1][1][1]);\n\t\t\n\t\tdp[i][1][0] = min(dp[i][1][0], min(dp[i - 1][0][0], dp[i - 1][0][1]) + 1);\n\t\tdp[i][1][1] = min(dp[i][1][1], min(dp[i - 1][1][0], dp[i - 1][1][1]) + 1);\n\t}\n\t\n\tint ans = N;\n\tfor(int ta = 0; ta < 2; ++ta)\n\t\tfor(int tb = 0; tb < 2; ++tb)\n\t\t\tans = min(ans, dp[n][ta][tb]);\n\tprintf(\"%d\\n\", ans);\n}\n\nint main(){\n\tint cases;\n\tscanf(\"%d\", &cases);\n\t\n\twhile(cases--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1466",
    "index": "D",
    "title": "13th Labour of Heracles",
    "statement": "You've probably heard about the twelve labors of Heracles, but do you have any idea about the thirteenth? It is commonly assumed it took him a dozen years to complete the twelve feats, so on average, a year to accomplish every one of them. As time flows faster these days, you have minutes rather than months to solve this task. But will you manage?\n\nIn this problem, you are given a tree with $n$ weighted vertices. A tree is a connected graph with $n - 1$ edges.\n\nLet us define its $k$-coloring as an assignment of $k$ colors to the edges so that each edge has exactly one color assigned to it. Note that you don't have to use all $k$ colors.\n\nA subgraph of color $x$ consists of these edges from the original tree, which are assigned color $x$, and only those vertices that are adjacent to at least one such edge. So there are no vertices of degree $0$ in such a subgraph.\n\nThe value of a connected component is the \\textbf{sum} of weights of its vertices. Let us define the value of a subgraph as a \\textbf{maximum} of values of its connected components. We will assume that the value of an empty subgraph equals $0$.\n\nThere is also a value of a $k$-coloring, which equals the \\textbf{sum} of values of subgraphs of all $k$ colors. Given a tree, for each $k$ from $1$ to $n - 1$ calculate the maximal value of a $k$-coloring.",
    "tutorial": "Description of the algorithm For simplicity, I will describe the partition of edges into colors in terms of modifying the graph. After the modifications, each connected component will correspond to edges in the given color (different color for every component). I will add colors to the coloring one by one. Initially, we have only one color and the whole graph (one connected component). We add the next color in the following way: Let vertex $v$ be a vertex with maximum weight among the vertices with degree greater than $1$. Let $u$ be any neighbor of $v$. Add vertex $v'$ to the graph with weight equal to the weight of $v$. Add edge $(u,v')$ and remove the $(u,v)$ edge. This algorithm can be simulated in complexity $\\mathcal{O}(n \\log n)$. We process vertices in the order of nonincreasing weights and add $w_i$ $d_i-1$ times, where $w_i$ is a weight of a vertex and $d_i$ its degree in the initial graph. Proof Note that there exists an optimal solution in which all edges assigned to the same color form a single connected component. From this moment on, I will consider only such colorings. Proof: Consider a color such that edges in that color don't form a single connected component. We can change the color of all of them apart from those in a connected component with a maximal value because they don't contribute to the result. So reassigning them to the same colors as adjacent edges will not decrease the value of the coloring. The result equals the sum over all vertices of products of weight ($w_i$) of a vertex and number of distinct colors of edges incident to it ($c_i$): $\\sum_{v =1}^n w_i \\cdot c_i$ Note that $c_i$ is always between $1$ and the degree of $i$-th vertex. Furthermore, for a coloring using exactly $k$ colors, the following holds: $\\sum_{v =1}^n c_i = n + k-1$ Proof: Consider any coloring $C$, it can be obtained the following way: Initially all edges are in the first color, thus all $c_i = 1$. Until not all colors have been processed: Consider the connected component in the first color. Let me define a leaf edge as an edge incident to a vertex of degree one in the graph containing only edges in the first color. There must exist at least one leaf edge which has color $x \\neq 1$ in the coloring $C$ (a leaf edge currently has the first color, but has to be repainted). Process color $x$: set the color of all edges, which color in $C$ is $x$, to $x$. Only $c_i$ of vertices belonging to both connected components of the fist and $x$-th color have changed (they have increased by 1). Since edges in color $x$ form a single connected component and the same holds for the first color, there is exactly one such vertex. Consider the connected component in the first color. Let me define a leaf edge as an edge incident to a vertex of degree one in the graph containing only edges in the first color. There must exist at least one leaf edge which has color $x \\neq 1$ in the coloring $C$ (a leaf edge currently has the first color, but has to be repainted). Process color $x$: set the color of all edges, which color in $C$ is $x$, to $x$. Only $c_i$ of vertices belonging to both connected components of the fist and $x$-th color have changed (they have increased by 1). Since edges in color $x$ form a single connected component and the same holds for the first color, there is exactly one such vertex. This proves $\\sum_{v =1}^n c_i \\leq n + k-1$, which is enough to see that the algorithm above yields an optimal solution. The inequality $\\sum_{v =1}^n c_i \\geq n + k-1$ stems from the fact, that there are $k$ connected components in a $k$-coloring.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long int LL;\n\nconst int N = 100 * 1000 + 7;\n\nint n;\nint w[N];\nint deg[N];\n\nvoid solve() {\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &w[i]);\n\t\tdeg[i] = 0;\n\t}\n\t\n\tfor(int i = 1; i < n; ++i) {\n\t\tint u, v;\n\t\tscanf(\"%d %d\", &u, &v);\n\t\tdeg[u]++; deg[v]++;\n\t}\n\t\n\tLL ans = 0;\n\tvector <int> to_sort;\n\n\tfor(int i = 1; i <= n; ++i) {\n\t\tfor(int j = 1; j < deg[i]; ++j)\n\t\t\tto_sort.push_back(w[i]);\n\t\tans += w[i];\n\t}\n\t\n\tsort(to_sort.begin(), to_sort.end());\n\treverse(to_sort.begin(), to_sort.end());\n\t\n\tfor(auto &v: to_sort) {\n\t\tprintf(\"%lld \", ans);\n\t\tans += v;\n\t}\n\t\n\tprintf(\"%lld\\n\", ans);\n}\n\nint main() {\n\tint cases;\n\tscanf(\"%d\", &cases);\n\t\n\twhile(cases--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1466",
    "index": "E",
    "title": "Apollo versus Pan",
    "statement": "Only a few know that Pan and Apollo weren't only battling for the title of the GOAT musician. A few millenniums later, they also challenged each other in math (or rather in fast calculations). The task they got to solve is the following:\n\nLet $x_1, x_2, \\ldots, x_n$ be the sequence of $n$ non-negative integers. Find this value: $$\\sum_{i=1}^n \\sum_{j=1}^n \\sum_{k=1}^n (x_i \\, \\& \\, x_j) \\cdot (x_j \\, | \\, x_k)$$\n\nHere $\\&$ denotes the bitwise and, and $|$ denotes the bitwise or.\n\nPan and Apollo could solve this in a few seconds. Can you do it too? For convenience, find the answer modulo $10^9 + 7$.",
    "tutorial": "The formula given in this task looks difficult to calculate, so we can rewrite it: $\\sum_{i=1}^n \\sum_{j=1}^n \\sum_{k=1}^n (x_i \\, \\& \\, x_j) \\cdot (x_j \\, | \\, x_k) = \\sum_{j=1}^n \\sum_{i=1}^n (x_i \\, \\& \\, x_j) \\sum_{k=1}^n (x_j \\, | \\, x_k) = \\sum_{j=1}^n \\left[ \\sum_{i=1}^n (x_i \\, \\& \\, x_j) \\right] \\cdot \\left[ \\sum_{k=1}^n (x_j \\, | \\, x_k) \\right]$ We fix the element $x_j$. Now the task is to calculate two sums $\\sum_i (x_i \\, \\& \\, x_j)$ and $\\sum_k (x_j \\, | \\, x_k)$, and multiply them by each other. Let's define function $f(x, c)$ as the value of $c$-th bit in $x$. For example $f(13, 1) = 0$, because $13 = 11\\underline{0}1_2$, and $f(12, 2) = 1$, because $12 = 1\\underline{1}00_2$. Additionally, define $M$ as the smallest integer such that $\\forall_i \\, x_i < 2^M$. Note that in this task $M \\leq 60$. We can rewrite our sums using function $f$: $\\sum_i (x_i \\, \\& \\, x_j) = \\sum_{c = 0}^{M} 2^c \\sum_i f(x_i, c) \\cdot f(x_j, c) = \\sum_{c = 0}^{M} 2^c f(x_j, c) \\sum_i f(x_i, c)$ $\\sum_k (x_j \\, | \\, x_k) = \\sum_{c = 0}^{M} 2^c \\sum_k 1 - (1 - f(x_j, c)) \\cdot (1 - f(x_k, c)) = \\sum_{c = 0}^{M} 2^c \\left[ n - (1 - f(x_j, c)) \\sum_k (1 - f(x_k, c)) \\right]$ In other words, we just split elements $x_i, x_j, x_k$ into the powers of two. If we memorize the values of $\\sum_i f(x_i, c)$, for each $c \\in \\{0, 1, \\ldots, M \\}$, then we can calculate the desired sums in $\\mathcal{O}(M)$ for fixed $x_j$ using the above equations. So the final solution is to iterate over all elements in the array and fix them as $x_j$, and sum all of the results obtained. Complexity is $\\mathcal{O}(nM) = \\mathcal{O}(n \\log \\max_i(x_i))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long int LL;\n\nconst int N = 500 * 1000 + 7;\nconst int P = 60;\nconst int MX = 1e9 + 7;\n\nint n;\nLL in[N];\nint cnt[P];\n\nvoid solve(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < P; ++i)\n\t\tcnt[i] = 0;\n\t\n\tfor(int i = 1; i <= n; ++i){\n\t\tscanf(\"%lld\", &in[i]);\n\t\tfor(int j = 0; j < P; ++j)\n\t\t\tcnt[j] += in[i] >> j & 1;\n\t}\n\t\n\tint ans = 0;\n\tfor(int i = 1; i <= n; ++i){\n\t\tLL exp_or = 0, exp_and = 0;\n\t\tfor(int j = 0; j < P; ++j){\n\t\t\tif(in[i] >> j & 1){\n\t\t\t\texp_or += (1LL << j) % MX * n;\n\t\t\t\texp_and += (1LL << j) % MX * cnt[j];\n\t\t\t}\n\t\t\telse\n\t\t\t\texp_or += (1LL << j) % MX * cnt[j];\n\t\t}\n\t\t\n\t\texp_and %= MX, exp_or %= MX;\n\t\tans = (ans + 1LL * exp_or * exp_and) % MX;\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}\n\nint main(){\n\tint cases;\n\tscanf(\"%d\", &cases);\n\t\n\twhile(cases--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1466",
    "index": "F",
    "title": "Euclid's nightmare",
    "statement": "You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.\n\nIn his bad dream Euclid has a set $S$ of $n$ $m$-dimensional vectors over the $\\mathbb{Z}_2$ field and can perform vector addition on them. In other words he has vectors with $m$ coordinates, each one equal either $0$ or $1$. Vector addition is defined as follows: let $u+v = w$, then $w_i = (u_i + v_i) \\bmod 2$.\n\nEuclid can sum any subset of $S$ and archive another $m$-dimensional vector over $\\mathbb{Z}_2$. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal $0$.\n\nLet $T$ be the set of all the vectors that can be written as a sum of some vectors from $S$. Now Euclid wonders the size of $T$ and whether he can use only a subset $S'$ of $S$ to obtain all the vectors from $T$. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in $S$ have \\textbf{at most} $2$ coordinates equal $1$.\n\nHelp Euclid and calculate $|T|$, the number of $m$-dimensional vectors over $\\mathbb{Z}_2$ that can be written as a sum of some vectors from $S$. As it can be quite large, calculate it modulo $10^9+7$. You should also find $S'$, the \\textbf{smallest} such subset of $S$, that all vectors in $T$ can be written as a sum of vectors from $S'$. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.\n\nConsider sets $A$ and $B$ such that $|A| = |B|$. Let $a_1, a_2, \\dots a_{|A|}$ and $b_1, b_2, \\dots b_{|B|}$ be increasing arrays of indices elements of $A$ and $B$ correspondingly. $A$ is lexicographically smaller than $B$ iff there exists such $i$ that $a_j = b_j$ for all $j < i$ and $a_i < b_i$.",
    "tutorial": "We start by simplifying the task. Increase the length of all vectors by $1$, i.e., add additional dimension. For the vectors from $S$, the $m+1$-th character will be $1$ in those with exactly one character $1$. This way, all the vectors in $S$ will have $1$s on precisely two positions. When we have some items and some subsets of these items of size exactly $2$, it is intuitive to create a graph on these items. Thus we create a graph where vertices represent dimensions of our space, and edges are vectors given in the input. Consider a sum of a subset of vectors in the input. Notice that each such vector contributes $1$ to the sum at exactly $2$ positions. Thus the resulting vector has an even number of $1$. Moreover, consider any connected component in the constructed graph. Note that our vector needs to have an even number of $1$ in each connected component for the same reason. It turns out that we can represent any vector fulfilling this condition. From these observations, we conclude that all we care about are connected components of the graph. Thus the answer is the MST of this graph, where the value of an edge is its index. The number of achievable vectors is $2^{|S'|}$. Complexity is $\\mathcal{O}((n + m) \\log (n + m))$ or faster depending on the algorithm to find the MST.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long int LL;\n\nconst int N = 5e5 + 7;\nconst int MX = 1e9 + 7;\n\nint n, m;\nint rep[N];\n\nint Find(int a) {\n\tif(rep[a] == a)\n\t\treturn a;\n\treturn rep[a] = Find(rep[a]);\n}\n\nbool Union(int a, int b) {\n\ta = Find(a);\n\tb = Find(b);\n\t\n\trep[a] = b;\n\treturn a != b;\n}\n\nint main() {\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 1; i <= m + 1; ++i)\n\t\trep[i] = i;\n\t\n\tvector <int> ans;\n\tfor(int i = 1; i <= n; ++i) {\n\t\tint k;\n\t\tscanf(\"%d\", &k);\n\t\t\n\t\tint fa, fb = m + 1;\n\t\tscanf(\"%d\", &fa);\n\t\t\n\t\tif(k > 1)\n\t\t\tscanf(\"%d\", &fb);\n\t\t\n\t\tif(Union(fa, fb))\n\t\t\tans.push_back(i);\n\t}\n\t\n\tint res = 1;\n\tfor(int i = 0; i < (int)ans.size(); ++i)\n\t\tres = (res + res) % MX;\n\n\tprintf(\"%d %d\\n\", res, (int)ans.size());\n\tfor(auto v: ans)\n\t\tprintf(\"%d \", v);\n\tputs(\"\");\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1466",
    "index": "G",
    "title": "Song of the Sirens",
    "statement": "\\begin{quote}\nWhoso in ignorance draws near to them and hears the Sirens' voice, he nevermore returns.Homer, Odyssey\n\\end{quote}\n\nIn the times of Jason and the Argonauts, it was well known that sirens use the sound of their songs to lure sailors into their demise. Yet only a few knew that every time sirens call a sailor by his name, his will weakens, making him more vulnerable.\n\nFor the purpose of this problem, both siren songs and names of the sailors will be represented as strings of lowercase English letters. The more times the sailor's name occurs as a contiguous substring of the song, the greater danger he is in.\n\nJason found out that sirens can sing one of the $n+1$ songs, which have the following structure: let $s_i$ ($0 \\leq i \\leq n$) be the $i$-th song and $t$ be a string of length $n$, then for every $i < n$: $s_{i+1} = s_i t_i s_i$. In other words $i+1$-st song is the concatenation of $i$-th song, $i$-th letter ($0$-indexed) of $t$ and the $i$-th song.\n\nFortunately, he also knows $s_0$ and $t$. Jason wonders how many times a sailor's name is mentioned in a particular song. Answer $q$ queries: given the sailor's name ($w$) and the index of a song ($i$) output the number of occurrences of $w$ in $s_i$ as a substring. As this number can be quite large, output its remainder modulo $10^9+7$.",
    "tutorial": "We define $f(n, w)$ as the number of occurrences of $w$ in $s_n$. Moreover, we define $g(n, w), n > 0$ as the number of occurrences of $w$ in $s_n$ which contain character $t_{n - 1}$. With these definitions, we write the formula for $f(n, w)$ with $n > 0$: $f(n, w) = 2 \\cdot f(n - 1, w) + g(n, w) = f(0, w) \\cdot 2^n + \\sum_{k = 1}^n g(k, w) \\cdot 2^{n - k}$ Let $s_k$ be the shortest song, such that $|w| \\leq |s_k|$. Notice that $|s_k| \\leq 2 \\cdot |w| + |s_0|$. We can further reformulate the formula for $f(n, w)$: $f(n, w) = f(k, w) \\cdot 2^{n - k} + \\sum_{i = k + 1}^n g(i, w) \\cdot 2^{n - i}$ The length of $s_k$ is more or less the same as the length of $w$, so we can brute-force all occurrences of $w$ in $s_k$ with, for example, the KMP algorithm. The key observation to calculate the latter part of the formula is that $g(i, w)$ = $g(j, w)$ if $t_{i - 1} = t_{j - 1}$, and $k < i, j$. To prove that we note that $s_i, s_j$ can be represented as: $s_i = a_i \\, s_k \\, t_{i - 1} \\, s_k \\, b_i \\\\ s_j = a_j \\, s_k \\, t_{j - 1} \\, s_k \\, b_j \\\\$ As $|w| \\leq |s_k|$, and we are interested only in occurrences containing the middle character, we can see that for equal $t_{i - 1}$, $t_{j - 1}$, values of $g$ are the same. We calculate the value of the $g$ function for each letter of the alphabet (we can use KMP for this). Using prefix sums we can calculate $\\sum_{i = k + 1}^n g(i, w) \\cdot 2^{n - i}$ in $\\mathcal{O}(|\\Sigma|)$, where $|\\Sigma|$ denotes the length of the alphabet. The whole algorithm works in $\\mathcal{O}(n + q \\cdot (|\\Sigma| + |s_0|) + S)$, where $S$ denotes the total length of all queries. It can be improved to $\\mathcal{O}(n + q + S)$, but it was not needed to get accepted.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXLEN = 1e6 + 7;\nconst int MOD = 1e9 + 7;\n\nint n, q;\nstring s, t;\nvector <string> songs;\n\nvector <int> pw;\nvector <int> sum[26];\n\nvoid read(string &p) {\n\tstatic char input[MAXLEN];\n\tscanf(\"%s\", input);\n\tp = input;\n}\n\nvoid prepare_songs() {\n\tsongs = {s};\n\tfor(auto c: t) {\n\t\tif(songs.back().size() >= MAXLEN)\n\t\t\tbreak;\n\t\t\n\t\tauto p = songs.back();\n\t\tauto nxt = p + string(1, c) + p;\n\t\tsongs.push_back(nxt);\n\t}\n}\n\nvoid prepare_sum() {\n\tfor(int i = 0; i < 26; ++i) {\n\t\tchar c = 'a' + i;\n\t\tsum[i].resize(n + 1, 0);\n\t\t\n\t\tfor(int j = 0; j < n; ++j)\n\t\t\tsum[i][j + 1] = (sum[i][j] * 2 + (t[j] == c)) % MOD;\n\t}\n\t\n\tpw.resize(n + 1, 0);\n\tpw[0] = 1;\n\t\n\tfor(int i = 1; i <= n; ++i)\n\t\tpw[i] = 2LL * pw[i - 1] % MOD;\n}\n\nvoid init() {\n\tscanf(\"%d %d\", &n, &q);\n\tread(s), read(t);\n\n\tprepare_songs();\n\tprepare_sum();\n}\n\nvector <int> kmp(string &in) {\n\tint m = in.size(), cpref = 0;\n\tvector <int> dp(m, 0);\n\t\n\tfor(int i = 1; i < (int)in.size(); ++i) {\n\t\twhile(cpref > 0 && in[cpref] != in[i])\n\t\t\tcpref = dp[cpref - 1];\n\t\t\n\t\tif(in[cpref] == in[i])\n\t\t\t++cpref;\n\t\tdp[i] = cpref;\n\t}\n\t\n\treturn dp;\n}\n\n/* Get all borders based on dp from kmp */\nvector <bool> get(vector <int> &dp, int m) {\n\tvector <bool> ret(m + 1, false);\n\tint cur = dp.back();\n\t\n\twhile(cur) {\n\t\tret[cur] = true;\n\t\tcur = dp[cur - 1];\n\t}\n\t\n\tret[cur] = true;\n\treturn ret;\n}\n\nint answer(int k, string &w) {\n\tint id = 0;\n\twhile(songs[id].size() < w.size())\n\t\t++id;\n\t\n\tif(id > k)\n\t\treturn 0;\n\t\n\tint m = w.size();\n\tstring s_pref = w + '#' + songs[id];\n\tstring s_suf = songs[id] + '#' + w;\n\t\n\tauto dp_pref = kmp(s_pref);\n\tauto dp_suf = kmp(s_suf);\n\t\n\tauto pref = get(dp_pref, m);\n\tauto suf = get(dp_suf, m);\n\t\n\t/* Compute all internal occurences */\n\tint ret = 0;\n\tfor(auto &v: dp_pref)\n\t\tret += (v == m);\n\tret = 1LL * ret * pw[k - id] % MOD;\n\t\n\t/* Compute the remaining occurences */\n\tfor(int i = 0; i < m; ++i) {\n\t\tif(!pref[i] || !suf[m - i - 1])\n\t\t\tcontinue;\n\t\t\n\t\tint c = w[i] - 'a';\n\t\tret = (ret + sum[c][k] - 1LL * sum[c][id] * pw[k - id]) % MOD;\n\t}\n\t\n\tret = (ret + MOD) % MOD;\n\treturn ret;\n}\n\nvoid solve() {\n\twhile(q--) {\n\t\tint k;\n\t\tstring w;\n\t\t\n\t\tscanf(\"%d\", &k);\n\t\tread(w);\n\t\tprintf(\"%d\\n\", answer(k, w));\n\t}\n}\n\nint main() {\n\tinit();\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "hashing",
      "math",
      "string suffix structures",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1466",
    "index": "H",
    "title": "Finding satisfactory solutions",
    "statement": "Getting so far in this contest is not an easy feat. By solving all the previous problems, you have impressed the gods greatly. Thus, they decided to spare you the story for this problem and grant a formal statement instead.\n\nConsider $n$ agents. Each one of them initially has exactly one item, \\textbf{$i$-th agent has the item number $i$}. We are interested in reassignments of these items among the agents. An assignment is valid iff each item is assigned to exactly one agent, and each agent is assigned exactly one item.\n\nEach agent has a preference over the items, which can be described by a permutation $p$ of items sorted from the most to the least desirable. In other words, the agent prefers item $i$ to item $j$ iff $i$ appears earlier in the permutation $p$. A \\textbf{preference profile} is a list of $n$ permutations of length $n$ each, such that $i$-th permutation describes preferences of the $i$-th agent.\n\nIt is possible that some of the agents are not happy with the assignment of items. A set of dissatisfied agents may choose not to cooperate with other agents. In such a case, they would exchange the items they possess initially ($i$-th item belongs to $i$-th agent) only between themselves. Agents from this group don't care about the satisfaction of agents outside of it. However, they need to exchange their items in such a way that will make at least one of them happier, and none of them less happy (in comparison to the given assignment).\n\nFormally, consider a valid assignment of items — $A$. Let $A(i)$ denote the item assigned to $i$-th agent. Also, consider a subset of agents. Let $S$ be the set of their indices. We will say this subset of agents is dissatisfied iff there exists a valid assignment $B(i)$ such that:\n\n- For each $i \\in S$, $B(i) \\in S$.\n- No agent $i \\in S$ prefers $A(i)$ to $B(i)$ (no agent from the $S$ is less happy).\n- At least one agent $i \\in S$ prefers $B(i)$ to $A(i)$ (at least one agent from the $S$ is happier).\n\nAn assignment is optimal if no subset of the agents is dissatisfied. Note that the empty subset cannot be dissatisfied. It can be proven that for each preference profile, there is precisely one optimal assignment.\n\nExample: Consider $3$ agents with the following preference profile:\n\n- $[2, 1, 3]$\n- $[1, 2, 3]$\n- $[1, 3, 2]$\n\nAnd such an assignment:\n\n- First agent gets item $2$\n- Second agent gets item $3$.\n- Third agent gets item $1$.\n\nSee that the set of agents $\\{1, 2\\}$ is dissatisfied, because they can reassign their (initial) items in the following way:\n\n- First agent gets item $2$.\n- Second agent gets item $1$.\n- Third agent gets item $3$.\n\nThis reassignment will make the second agent happier and make no difference to the first agent. As a result, the third agent got an item that is worse for him, but this does not prevent the set $\\{1,2\\}$ from being dissatisfied (he is not in this set).\n\nThe following assignment would be optimal:\n\n- First agent gets item $2$.\n- Second agent gets item $1$.\n- Third agent gets item $3$.\n\nGiven an assignment $A$, calculate the number of distinct preference profiles for which assignment $A$ is optimal. As the answer can be huge, output it modulo $10^9+7$.\n\nTwo preference profiles are different iff they assign different preference permutations to any agent.",
    "tutorial": "We start with presenting the algorithm for finding the unique optimal good assignment. It treats agents as vertices in a graph and works in the following way: For every $i$ from $1$ to $n$ create a vertex (a single vertex will represent both the agent and his good) Until there are agents left, perform a round of an algorithm in the following way: For every agent, create a unidirectional edge from his vertex to the vertex of the good most desired by him that is still unassigned (present in the graph). For every agent lying on a cycle, assign his most desirable, available good to him. Then erase all the vertices lying on these cycles. For every agent, create a unidirectional edge from his vertex to the vertex of the good most desired by him that is still unassigned (present in the graph). For every agent lying on a cycle, assign his most desirable, available good to him. Then erase all the vertices lying on these cycles. So the task is to find the number of preference profiles that will generate the cycles present in the given optimal assignment. Note that cycles of the same length are equivalent. We can find this number by simulation of the above algorithm. To simulate, we use dynamic programming. The state contains: For each cycle length, the number of such cycles left. The number of already processed agents The number of agents processed in the previous round of the algorithm The number of agents processed in the current round of the algorithm The length of the cycle we currently analyze The state's value is the number of ways to assign preferences to all the agents on the already processed cycles. There are two types of transitions: Iterate over the number of cycles of the current length to pick in the current round Finish processing the current round, and start the next round Let $p(n)$ be the maximal product of natural numbers with sum equal to $n$. Then the number of transitions between can be bounded by $\\mathcal{O}( p(n) \\cdot n^3 )$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long int LL;\n\n#define st first\n#define nd second\n#define PII pair <int, int>\n\nconst int N = 60;\nconst int MX = 1e9 + 7;\n\nstruct state {\n\tint sum_picked = 0;\n\tint last_picked = 0, cur_picked = 0;\n\tint iterator = 0;\n\tvector <PII> lengths;\n\t\n\tstate(vector <PII> _lengths) {\n\t\tlengths = _lengths;\n\t}\n\t\n\t/* operators for map comparisons */\n\tbool operator<(const state &s) const {\n\t\tif(lengths != s.lengths)\t\t\treturn lengths < s.lengths;\n\t\tif(last_picked != s.last_picked)\treturn last_picked < s.last_picked;\n\t\tif(cur_picked != s.cur_picked)\t\treturn cur_picked < s.cur_picked;\n\t\treturn iterator < s.iterator;\n\t}\n\t\n\tbool operator==(const state &s) const {\n\t\tif(last_picked != s.last_picked)\treturn false;\n\t\tif(cur_picked != s.cur_picked)\t\treturn false;\n\t\tif(iterator != s.iterator)\t\t\treturn false;\n\t\tif(lengths != s.lengths)\t\t\treturn false;\n\t\treturn true;\n\t}\n};\n\nint n;\nvector <PII> cycles;\nmap <state, int> dp;\n\nint sil[N], rv[N];\nint pre[N][N][N];\n\nint fast(int a, int b) {\n\tint ret = 1;\n\twhile(b) {\n\t\tif(b & 1)\n\t\t\tret = 1LL * ret * a % MX;\n\t\t\n\t\tb >>= 1;\n\t\ta = 1LL * a * a % MX;\n\t}\n\t\n\treturn ret;\n}\n\nint newt(int a, int b) {\n\tif(b < 0 || a < b)\n\t\treturn 0;\n\treturn 1LL * sil[a] * rv[b] % MX * rv[a - b] % MX;\n}\n\nPII get_ways(int a, int b) {\n\tif(a == 0 && b == 0)\n\t\treturn {sil[n - 1], 0};\n\n\tint ret = 0, ret2 = 0;\n\tint c = n - a - 1;\n\t\n\tfor(int t = 1; t + c <= n; ++t) {\n\t\tret = (ret + 1LL * newt(n - t, c) * sil[c] % MX * newt(n - c - 1, b) % MX * sil[b] % MX * sil[a - b]) % MX;\n\t\tret2 = (ret2 + 1LL * newt(n - t, c) * sil[c] % MX * newt(n - t - c, b) % MX * sil[b] % MX * sil[a - b]) % MX;\n\t}\n\n\treturn {ret, ret2};\n}\n\nvoid precalc() {\n\tsil[0] = 1;\n\tfor(int i = 1; i <= n; ++i)\n\t\tsil[i] = 1LL * sil[i - 1] * i % MX;\n\t\n\trv[n] = fast(sil[n], MX - 2);\n\tfor(int i = n; i >= 1; --i)\n\t\trv[i - 1] = 1LL * rv[i] * i % MX;\n\t\n\tfor(int i = 0; i < n; ++i)\n\t\tfor(int j = 0; j <= i; ++j) {\n\t\t\tif(i && j == 0)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tauto [val, val2] = get_ways(i, j);\n\t\t\tpre[i][j][0] = 1;\n\n\t\t\tint res = 1, res2 = 1;\n\t\t\tfor(int k = 1; k <= n; ++k) {\n\t\t\t\tres = 1LL * res * val % MX;\n\t\t\t\tres2 = 1LL * res2 * val2 % MX;\n\t\t\t\tpre[i][j][k] = (res + MX - res2) % MX;\n\t\t\t}\n\t\t}\n}\n\nvoid read() {\n\tscanf(\"%d\", &n);\n\tprecalc();\n\n\tvector <int> input(n);\n\tfor(auto &v: input) {\n\t\tscanf(\"%d\", &v);\n\t\tv--;\n\t}\n\t\n\tvector <bool> vis(n);\n\tvector <int> cycle_lengths;\n\n\tfor(int i = 0; i < n; ++i) {\n\t\tif(vis[i])\n\t\t\tcontinue;\n\t\t\n\t\tint cur = i;\n\t\tint cycle_length = 0;\n\t\t\n\t\twhile(!vis[cur]) {\n\t\t\t++cycle_length;\n\t\t\tvis[cur] = true;\n\t\t\tcur = input[cur];\n\t\t}\n\t\t\n\t\tcycle_lengths.push_back(cycle_length);\n\t}\n\t\n\tsort(cycle_lengths.begin(), cycle_lengths.end());\n\tfor(auto v: cycle_lengths) {\n\t\tif(cycles.size() && cycles.back().st == v)\n\t\t\tcycles.back().nd++;\n\t\telse\n\t\t\tcycles.push_back({v, 1});\n\t}\n}\n\nint solve(state &cur) {\n\tif(cur.sum_picked == n)\n\t\treturn 1;\n\t\n\tif(dp.count(cur))\n\t\treturn dp[cur];\n\t\n\tif(cur.iterator == (int)cur.lengths.size()) {\n\t\tif(cur.cur_picked == 0)\n\t\t\treturn dp[cur] = 0;\n\t\t\n\t\tstate nxt = cur;\n\t\tnxt.sum_picked += nxt.cur_picked;\n\t\tnxt.last_picked = nxt.cur_picked;\n\t\tnxt.cur_picked = 0;\n\t\tnxt.iterator = 0;\n\t\treturn dp[cur] = solve(nxt);\n\t}\n\t\n\tstate nxt = cur;\n\tnxt.iterator++;\n\t\n\tint ret = 0, tmp = 1;\n\tauto [length, count] = cur.lengths[cur.iterator];\n\n\tfor(int i = 0; i <= count; ++i) {\n\t\tnxt.cur_picked = cur.cur_picked + i * length;\n\t\tnxt.lengths[cur.iterator].nd = count - i;\n\t\tret = (ret + 1LL * solve(nxt) * tmp % MX * newt(count, i)) % MX;\n\t\ttmp = 1LL * tmp * pre[cur.sum_picked][cur.last_picked][length] % MX;\n\t}\n\t\n\treturn dp[cur] = ret;\n}\n\nint main() {\n\tread();\n\tstate start = state(cycles);\n\tint ans = solve(start);\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1466",
    "index": "I",
    "title": "The Riddle of the Sphinx",
    "statement": "\\begin{quote}\nWhat walks on four feet in the morning, two in the afternoon, and three at night?\n\\end{quote}\n\nThis is an interactive problem. This problem doesn't support hacks.\n\nSphinx's duty is to guard the city of Thebes by making sure that no unworthy traveler crosses its gates. Only the ones who answer her riddle timely and correctly (or get an acc for short) are allowed to pass. As of those who fail, no one heard of them ever again...\n\nSo you don't have a choice but to solve the riddle. Sphinx has an array $a_1, a_2, \\ldots, a_n$ of \\textbf{nonnegative} integers \\textbf{strictly smaller} than $2^b$ and asked you to find the maximum value among its elements. Of course, she will not show you the array, but she will give you $n$ and $b$. As it is impossible to answer this riddle blindly, you can ask her some questions. For given $i, y$, she'll answer you whether $a_i$ is \\textbf{bigger} than $y$. As sphinxes are not very patient, you can ask at most $3 \\cdot (n + b) $ such questions.\n\nAlthough cunning, sphinxes are honest. Even though the array \\textbf{can change} between your queries, answers to the previously asked questions will remain valid.",
    "tutorial": "First, we start with a slightly suboptimal solution using $5 \\cdot (n + b)$ queries. We investigate the elements in order from $1$ to $n$. While doing so, we will keep the stack with some of these elements. Moreover, we will keep a prefix of the maximum we found till now. We keep the following conditions: The prefix of the maximum will have precisely the same length as the number of the elements on the stack $k$-th element on the stack (counting from the lowest element) will match at exactly $k$ bits with the current prefix. Now, we describe how to add an element while keeping previous conditions. Assume that number of elements on the stack is $m < b$. If the current element is: smaller on the first $m$ bits than the current prefix, then delete it and proceed to the next element equal on the first $m$ bits to the current prefix, then find the value of $m + 1$ bit using the current number and add this element to the top of the stack larger on the first $m$ bits than the current prefix, then remove the last element of the stack and last bit of the prefix and try again to add the current element to the stack Queries on the first $m$ bits can be done by filling the number with $0$s or $1$s on the remaining positions (depending on the type of query). After we finish analyzing the sequence, we have $m$ elements on the stack and prefix of length $m$, a candidate for maximum. Now we want to find out if this is truly the prefix of the maximum, or maybe there is an element with a larger prefix. To do this, we analyze the stack from its top. We take the top element, check if this larger on the first $m$ bits than the maximum, and if not, we remove it and proceed. Otherwise, if it is a $k$-th element on the stack, then we know it matches the current prefix on the first $k$ bits, so we keep only these first $k$ bits of the current prefix. At the very end, we are left with some prefix of the maximum. If this prefix has length $b$, then the task is solved. Otherwise, we find all elements with the same prefix and recursively solve the task for smaller $b$ and $n$. We quickly analyze the outlined solution. In the first phase, we ask at most $3$ queries per element when we add it and precisely one when we remove it. In the second phase, we ask as many queries as the stack's size (we can say that this is the query for removal). In the third phase, we use precisely $n$ queries, so in summary, we use $5 \\cdot n$ queries. It can be proven that if we achieve the prefix of $k < b$ elements, then there are at most $k$ elements with such prefix. Using some potential, we can easily prove that the sum of the number of queries used in the algorithm is at most $5 \\cdot (n + b)$. Unfortunately, this is not enough. We optimize two parts of the solution. It is easy to observe that we can skip the third phase - if we get the prefix of length $k$, only the lowest $k$ elements from the stack can have this prefix. Some of them might be smaller on these bits, but this does not matter, as if we ever query them later, we will receive no as an answer. This is enough to achieve $4 \\cdot (n + b)$ solution. The second optimization is that we do not need elements on the stack to match the appropriate prefix exactly. It is enough to fulfill the following conditions instead: $k$-th element on the stack cannot be larger than the first $k$ bits of the prefix There is an element on the stack, which is at least as large as the current prefix. This observation allows us to drop one query we used previously to determine if an element is smaller than the current prefix. This way, we achieve the demanded number of queries equal to $3 \\cdot (n + b)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define st first\n#define nd second\n\nint n, b;\n\nvoid write(int i, string y){\n\tprintf(\"%d \", i);\n\tfor(auto p: y)\n\t\tprintf(\"%c\", p);\n\tputs(\"\");\n\tfflush(stdout);\n}\n\nbool ask(int i, string y){\n\twrite(i, y);\n\tstring ans;\n\tcin >> ans;\n\treturn ans == \"yes\";\n}\n\nvoid solve(vector <int> cur, string pref){\n\tif(pref.size() == b){\n\t\twrite(0, pref);\n\t\treturn;\n\t}\n\n\tstack <pair <int, string> > S;\n\tS.push({0, pref});\n\t\n\tfor(auto v: cur){\n\t\twhile(S.size() > 1){\n\t\t\tauto prv = S.top().nd;\n\t\t\twhile(prv.size() < b)\n\t\t\t\tprv.push_back('1');\n\n\t\t\tif(!ask(v, prv))\n\t\t\t\tbreak;\n\t\t\tS.pop();\n\t\t}\n\t\t\n\t\tif(S.top().nd.size() == b)\n\t\t\tcontinue;\n\t\t\n\t\tauto prv = S.top().nd;\n\t\tprv.push_back('0');\n\n\t\twhile(prv.size() < b)\n\t\t\tprv.push_back('1');\n\n\t\tif(ask(v, prv)){\n\t\t\tprv = S.top().nd + \"1\";\n\t\t\tS.push({v, prv});\n\t\t}\n\t\telse{\n\t\t\tprv = S.top().nd + \"0\";\n\t\t\tS.push({v, prv});\n\t\t}\n\t}\n\t\n\tvector <int> nxt;\n\tstring ans = S.top().nd;\n\t\n\twhile(S.size() > 1){\n\t\tauto p = S.top();\n\t\tS.pop();\n\t\t\n\t\tstring tmp = ans;\n\t\twhile(tmp.size() < b)\n\t\t\ttmp.push_back('1');\n\t\t\n\t\tif(ask(p.st, tmp)){\n\t\t\tnxt.clear();\n\t\t\tans = p.nd;\n\t\t}\n\t\t\n\t\tnxt.push_back(p.st);\n\t}\n\t\n\tsolve(nxt, ans);\n}\n\nint main(){\n\tscanf(\"%d %d\", &n, &b);\n\tvector <int> all_ids;\n\tfor(int i = 0; i < n; ++i)\n\t\tall_ids.push_back(i + 1);\n\tsolve(all_ids, \"\");\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "interactive"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1467",
    "index": "A",
    "title": "Wizard of Orz",
    "statement": "There are $n$ digital panels placed in a straight line. Each panel can show any digit from $0$ to $9$. Initially, all panels show $0$.\n\nEvery second, the digit shown by each panel increases by $1$. In other words, at the end of every second, a panel that showed $9$ would now show $0$, a panel that showed $0$ would now show $1$, a panel that showed $1$ would now show $2$, and so on.\n\nWhen a panel is paused, the digit displayed on the panel does not change in the subsequent seconds.\n\nYou must pause exactly one of these panels, at any second you wish. Then, the panels adjacent to it get paused one second later, the panels adjacent to those get paused $2$ seconds later, and so on. In other words, if you pause panel $x$, panel $y$ (for all valid $y$) would be paused exactly $|x−y|$ seconds later.\n\nFor example, suppose there are $4$ panels, and the $3$-rd panel is paused when the digit $9$ is on it.\n\n- The panel $1$ pauses $2$ seconds later, so it has the digit $1$;\n- the panel $2$ pauses $1$ second later, so it has the digit $0$;\n- the panel $4$ pauses $1$ second later, so it has the digit $0$.\n\nThe resulting $4$-digit number is $1090$. \\textbf{Note that this example is not optimal for $n = 4$}.\n\nOnce all panels have been paused, you write the digits displayed on them from left to right, to form an $n$ digit number (it can consist of leading zeros). What is the largest possible number you can get? Initially, all panels show $0$.",
    "tutorial": "If there is only one panel, then pause it when digit $9$ appears on it. You cannot do any better than that. Otherwise, it is always optimal to pause the second panel from left, when the digit $8$ appears on it. This would give an answer of the form $98901234567890123456\\dots$. You can verify that this is the largest number that can be achieved.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nint solveTestCase() {\n    int n;\n    cin >> n;\n\n    string s = \"989\";\n    if (n <= 3)\n        return cout << s.substr(0, n) << \"\\n\", 0;\n\n    cout << s;\n    for (int i = 3; i < n; i++)\n        cout << (i - 3) % 10;\n    cout << \"\\n\";\n}\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int t = 1;\n    cin >> t;\n    while (t--)\n        solveTestCase();\n\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1467",
    "index": "B",
    "title": "Hills And Valleys",
    "statement": "You are given a sequence of $n$ integers $a_1$, $a_2$, ..., $a_n$. Let us call an index $j$ ($2 \\le j \\le {{n-1}}$) a hill if $a_j > a_{{j+1}}$ and $a_j > a_{{j-1}}$; and let us call it a valley if $a_j < a_{{j+1}}$ and $a_j < a_{{j-1}}$.\n\nLet us define the intimidation value of a sequence as the sum of the number of hills and the number of valleys in the sequence. You can change \\textbf{exactly one} integer in the sequence to any number that you want, or let the sequence remain unchanged. What is the minimum intimidation value that you can achieve?",
    "tutorial": "Changing the value of $a_i$ affects the hill/valley status of only elements $\\{a_{i-1}, a_i, a_{i+1}\\}$. We claim that it is optimal to change $a_i$ to either $a_{i-1}$ or $a_{i+1}$ for valid $i\\space(1<i<n)$. Let $x$ be a value of $a_i$ such that the number of hills/valleys among elements $\\{a_{i-1},a_i,a_{i+1}\\}$ is minimised. Now, if $x < \\max(a_{i-1}, a_{i+1})$, we can set $x := \\min(a_{i-1}, a_{i+1})$ without changing any non-hill/non-valley element to a hill/valley. Similarly, if $x > \\min(a_{i-1},a_{i+1})$ we can set $x := \\max(a_{i-1},a_{i+1})$. Hence proved. The final solution is as follows. Precompute the number of hills and valleys in the original array. Then, for every valid index $i$, calculate the change in the number of hills/valleys of the elements $\\{a_{i-1},a_i,a_{i+1}\\}$ on setting $a_i := a_{i-1}$ and $a_i := a_{i+1}$ and update the minimum answer accordingly.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nconst int N = 3e5;\nint a[N], n;\n\nint isValley(int i) {\n    return (i > 0 && i < n - 1 && a[i] < a[i - 1] && a[i] < a[i + 1]);\n}\n\nint isHill(int i) {\n    return (i > 0 && i < n - 1 && a[i] > a[i - 1] && a[i] > a[i + 1]);\n}\n\nint solveTestCase() {\n    cin >> n;\n    for (int i = 0; i < n; i++)\n        cin >> a[i];\n\n    int is[n] = {};\n    int s = 0;\n    for (int i = 1; i < n - 1; i++) {\n        if (isHill(i) || isValley(i))\n            is[i] = 1, s++;\n    }\n\n    int ans = s;\n    for (int i = 1; i < n - 1; i++) {\n        int temp = a[i];\n        a[i] = a[i - 1];\n        ans = min(ans, s - is[i - 1] - is[i] - is[i + 1] + isHill(i - 1) + isValley(i - 1) + isHill(i) + isValley(i) + isHill(i + 1) + isValley(i + 1));\n        a[i] = a[i + 1];\n        ans = min(ans, s - is[i - 1] - is[i] - is[i + 1] + isHill(i - 1) + isValley(i - 1) + isHill(i) + isValley(i) + isHill(i + 1) + isValley(i + 1));\n        a[i] = temp;\n    }\n\n    cout << ans << \"\\n\";\n}\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int t = 1;\n    cin >> t;\n    while (t--)\n        solveTestCase();\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1467",
    "index": "C",
    "title": "Three Bags",
    "statement": "You are given \\textbf{three} bags. Each bag contains a non-empty multiset of numbers. You can perform a number of operations on these bags. In one operation, you can choose any two non-empty bags, and choose one number from each of the bags. Let's say that you choose number $a$ from the first bag and number $b$ from the second bag. Then, you remove $b$ from the second bag and replace $a$ with $a-b$ in the first bag. Note that if there are multiple occurrences of these numbers, then you shall only remove/replace exactly one occurrence.\n\nYou have to perform these operations in such a way that you have exactly one number remaining in exactly one of the bags (the other two bags being empty). It can be shown that you can always apply these operations to receive such a configuration in the end. Among all these configurations, find the one which has the maximum number left in the end.",
    "tutorial": "Model the problem as a rooted tree (graph). There are $n_1+n_2+n_3$ nodes, corresponding to the elements from the three bags. Edges between two nodes represent an operation on the two elements and it can be seen that an edge can exist only between nodes of elements from different sets. A directed edge from $b$ to $a$ means that $b$ is removed and $a$ is replaced to $a-b$. All edges are directed towards the root. In the given rooted tree, operations are applied bottom up, that is, an operation is applied on a leaf node and its parent, and the leaf node is removed. The process is continued until only the root node is remaining. It is easy to see that the value of the element at the end of all operations is the sum of elements at even depth minus the sum of elements at odd depth (depth is $0$ indexed). Claim: The constructed rooted tree is valid, if the elements at odd depth are 1. are from at least two different bags, or 2. contain all elements from one bag. Proof: Consider a rooted tree with all elements at odd depth from exactly one bag (say $X$) which doesn't fulfil criteria $2$. No remaining elements from bag $X$ can be connected to the nodes at odd depth, making it impossible to construct a tree. This implies that $1$ must hold. However, if criteria $2$ holds, no elements from bag $X$ remain to be connected, and thus the tree can be constructed. Hence proved. Now, we have to minimise either of the two cases, which is the solution to the problem. For the first case, we can choose the two smallest numbers such that they both appear in different bags to be at odd depth. For the second case, we can choose all numbers from the bag where the sum of the numbers is minimum to be at odd depth.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nconst int N = 3e5;\nvector<vector<int>> a(3, vector<int>());\nvector<int> n(3, 0);\n\nint calc() {\n    int ans = 0, m1 = a[1][0], m2 = a[2][0], s1 = 0, s2 = 0;\n    for (int i : a[0]) ans += i;\n    for (int i = 1; i < n[1]; i++) s1 += a[1][i];\n    for (int i = 1; i < n[2]; i++) s2 += a[2][i];\n\n    ans += max({s2 - m1 + s1 - m2, m2 + s2 - m1 - s1, m1 + s1 - m2 - s2});\n    return ans;\n}\n\nint solveTestCase() {\n    cin >> n[0] >> n[1] >> n[2];\n    a[0].resize(n[0]);\n    a[1].resize(n[1]);\n    a[2].resize(n[2]);\n\n    for (int i = 0; i < 3; i++) {\n        for (int j = 0; j < n[i]; j++)\n            cin >> a[i][j];\n        sort(a[i].begin(), a[i].end());\n    }\n\n    int ans = -1e18;\n    ans = max(ans, calc());\n\n    swap(a[0], a[1]), swap(n[0], n[1]);\n    ans = max(ans, calc());\n\n    swap(a[0], a[2]), swap(n[0], n[2]);\n    ans = max(ans, calc());\n\n    cout << ans;\n}\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int t = 1;\n    //cin >> t;\n    while (t--)\n        solveTestCase();\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1467",
    "index": "D",
    "title": "Sum of Paths",
    "statement": "There are $n$ cells, numbered $1,2,\\dots, n$ from left to right. You have to place a robot at any cell initially. The robot must make \\textbf{exactly} $k$ moves.\n\nIn one move, the robot must move one cell to the left or right, provided that it doesn't move out of bounds. In other words, if the robot was in the cell $i$, it must move to either the cell $i-1$ or the cell $i+1$, as long as it lies between $1$ and $n$ (endpoints inclusive). The cells, in the order they are visited (including the cell the robot is placed), together make a good path.\n\nEach cell $i$ has a value $a_i$ associated with it. Let $c_0, c_1, \\dots, c_k$ be the sequence of cells in a good path in the order they are visited ($c_0$ is the cell robot is initially placed, $c_1$ is the cell where the robot is after its first move, and so on; more formally, $c_i$ is the cell that the robot is at after $i$ moves). Then the value of the path is calculated as $a_{c_0} + a_{c_1} + \\dots + a_{c_k}$.\n\nYour task is to calculate the sum of values over all possible good paths. Since this number can be very large, output it modulo $10^9 + 7$. Two good paths are considered different if the starting cell differs or there exists an integer $i \\in [1, k]$ such that the current cell of the robot after exactly $i$ moves is different in those paths.\n\nYou must process $q$ updates to $a$ and print the updated sum each time. Each update changes the value of exactly one cell. See the input format and the sample input-output for more details.",
    "tutorial": "The main idea of the problem is to calculate the contribution of each cell to the answer. Let $cnt_i$ denote the sum of the number of times cell $i$ appears in all good paths of length $k$. Then the answer is equal to $a_1*cnt_1 + a_2*cnt_2 + \\dots + a_n*cnt_n$. We shall use dynamic programming to calculate these values. Let $dp_{{i,j}}$ denote the number of good paths of length $j$ that end at cell $i$. Then, $dp_{{i,0}} = 1$ for all $i$ such that $1 \\le i \\le n$. Further, for all $i$ such that $1 \\le i \\le n$ and for all $j$ such that $1 \\le j \\le k$, $dp_{{i, j}}$ can be calculated as $dp_{{i,j}} = dp_{{{{i-1}},{{j-1}}}} + dp_{{{{i+1}},{{j-1}}}}$ because we can move to cell $i$ from either cell $i-1$ or cell $i+1$. Handle the cases where $i=1$ and $i=n$ separately to avoid out-of-bounds error. Observe that $dp_{{i,j}}$ is also equal to the number of good paths of length $j$ that start at cell $i$. Let $a_{{i,j}}$ denote the number of times cell $i$ appears after exactly $j$ moves in all valid paths of length $k$. Well $a_{{i,j}} = dp_{{i,j}} * dp_{{i,k-j}}$ because we can split a path of length $k$ into two paths of length $j$ and length $k-j$, with the first path ending at cell $i$ and the second path starting at cell $i$. Since $cnt_i$ denotes the sum of the number of times cell $i$ appears in all good path of length $k$, cell $i$ can appear after exactly $0, 1, 2, \\dots, k$ moves. This means that $cnt_i = \\sum_{{j=0}}^{{k}} a_{{i,j}}$. Extending the solution to account for updates is easy once we have calculated these values.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nconst int N = 5005, mod = 1e9 + 7;\nint dp[N][N], cnt[N], a[N], q, n, k;\n\nvoid pre() {\n    for (int i = 0; i < n; i++)\n        dp[i][0] = 1;\n        \n    for (int j = 1; j < N; j++) {\n        dp[0][j] = dp[1][j - 1];\n        for (int i = 1; i < n - 1; i++)\n            dp[i][j] = (dp[i - 1][j - 1] + dp[i + 1][j - 1]) % mod;\n        dp[n - 1][j] = dp[n - 2][j - 1];\n    }\n    \n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j <= k; j++)\n            cnt[i] += dp[i][j] * dp[i][k - j], cnt[i] %= mod;\n    }\n}\n\nvoid solveTestCase() {\n    int ans = 0;\n    for (int i = 0; i < n; i++)\n        cin >> a[i], ans += a[i] * cnt[i], ans %= mod;\n    \n    while (q--) {\n        int i, x;\n        cin >> i >> x;\n        i--;\n        \n        ans -= (a[i] * cnt[i]) % mod, ans += mod, ans %= mod;\n        \n        a[i] = x;\n        ans += (a[i] * cnt[i]), ans %= mod;\n        cout << ans << \"\\n\";\n    }\n}\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    \n    cin >> n >> k >> q;\n    pre();\n    \n    int t = 1;\n    //cin >> t;\n    while (t--)\n        solveTestCase();\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1467",
    "index": "E",
    "title": "Distinctive Roots in a Tree",
    "statement": "You are given a tree with $n$ vertices. Each vertex $i$ has a value $a_i$ associated with it.\n\nLet us root the tree at some vertex $v$. The vertex $v$ is called a distinctive root if the following holds: in all paths that start at $v$ and end at some other node, all the values encountered are distinct. Two different paths may have values in common but a single path must have all distinct values.\n\nFind the number of distinctive roots in the tree.",
    "tutorial": "Root the tree arbitrarily. Consider any node $v$. Let us remove $v$ from the tree and examine the trees that will be created in the resultant forest. Let's say that a particular tree was attached to $v$ through node $u$. Further, let's say that this tree has some node $x$ satisfying $a_v = a_x$. Then clearly, if any distinctive root exists, it must be in this component, because if it were in any other component, then, when you root the tree at that node, you will get a path from the root containing both $v$ and $x$. Let us add a directed edge from $v$ to $u$, signifying that all distinctive roots must be in this particular component. Once we have repeated this for all nodes, we now have a set of directed edges. All distinctive roots must have each of these edges pointing to it. We can check this for all nodes using the rerooting technique. Link cut tree or difference array works as well. Note: In order to check the number of nodes $x$ which occur in a subtree, do a pre-order traversal of the tree. Create a map which maps a value $b$ to the dfs-in times of all nodes $i$ that satisfy $a_i = b$. Now, two lower-bounds on this shall tell us the number of occurrences in the subtree in logarithmic time. Also, with this information, you can also calculate the number of times $x$ occurs in the tree attached to $v$'s parent.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nconst int N = 5e5;\nvector<int> adj[N];\nint a[N], par[N], n;\n\nmap<int, vector<int>> v, times;\nint euler[N * 2 - 1], tin[N], tout[N], c = 0;\n\nset<pair<int, int>> g;\nint dp[N], ans;\n\nvoid dfs(int v, int p = -1) {\n    par[v] = p;\n    tin[v] = c;\n    euler[c++] = v;\n\n    for (int i : adj[v]) {\n        if (i == p)\n            continue;\n        dfs(i, v);\n        euler[c++] = v;\n    }\n\n    tout[v] = c - 1;\n}\n\nvoid examine(int v) {\n    int sum = 0;\n\n    for (int i : adj[v]) {\n        if (i == par[v])\n            continue;\n\n        int count = upper_bound(times[a[v]].begin(), times[a[v]].end(), tout[i]) - lower_bound(times[a[v]].begin(), times[a[v]].end(), tin[i]);\n        if (count > 0)\n            g.insert({v, i});\n        sum += count;\n    }\n\n    sum = times[a[v]].size() - sum - 1;\n    if (sum)\n        g.insert({v, par[v]});\n}\n\nint setup(int v) {\n    for (int i : adj[v]) {\n        if (i != par[v])\n            dp[v] += setup(i);\n    }\n    return dp[v] + g.count({v, par[v]});\n}\n\nvoid reroot(int v) {\n    if (dp[v] == g.size())\n        ans++;\n\n    for (int i : adj[v]) {\n        if (i == par[v])\n            continue;\n\n        dp[v] -= dp[i];\n        dp[v] -= g.count({i, v});\n        dp[i] += dp[v];\n        dp[i] += g.count({v, i});\n\n        reroot(i);\n\n        dp[i] -= g.count({v, i});\n        dp[i] -= dp[v];\n        dp[v] += g.count({i, v});\n        dp[v] += dp[i];\n    }\n}\n\nint solveTestCase() {\n    cin >> n;\n    for (int i = 0; i < n; i++)\n        cin >> a[i];\n\n    for (int i = 0; i < n - 1; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--, v--;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n\n    dfs(0);\n    for (int i = 0; i < n; i++)\n        v[a[i]].push_back(i);\n\n    for (auto i : v) {\n        if (i.second.size() == 1)\n            continue;\n\n        for (int j : i.second)\n            times[i.first].push_back(tin[j]);\n        sort(times[i.first].begin(), times[i.first].end());\n        for (int j : i.second)\n            examine(j);\n    }\n\n    setup(0);\n    reroot(0);\n\n    cout << ans;\n}\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int t = 1;\n    //cin >> t;\n    while (t--)\n        solveTestCase();\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1468",
    "index": "A",
    "title": "LaIS",
    "statement": "Let's call a sequence $b_1, b_2, b_3 \\dots, b_{k - 1}, b_k$ almost increasing if $$\\min(b_1, b_2) \\le \\min(b_2, b_3) \\le \\dots \\le \\min(b_{k - 1}, b_k).$$ In particular, any sequence with no more than two elements is almost increasing.\n\nYou are given a sequence of integers $a_1, a_2, \\dots, a_n$. Calculate the length of its longest almost increasing subsequence.\n\nYou'll be given $t$ test cases. Solve each test case independently.\n\nReminder: a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.",
    "tutorial": "Let's add $0$ to the beginning of $a$, then we'll increase LaIS by one and so it will always start from $0$. Let's look at any almost increasing subsequence (aIS) and underline elements, which are minimums in at least one consecutive pair, for example, $[\\underline{0}, \\underline{1}, \\underline{2}, 7, \\underline{2}, \\underline{2}, 3]$. Note that underlined elements form increasing subsequence (IS) and there is no more than one element between each consecutive pair. What constraints these elements have? Obviously, $a[pos_{i - 1}] \\le a[pos_i] \\ge a[pos_{i + 1}]$, but we can ease the constraints just to $a[pos_{i - 1}] \\le a[pos_i]$, i. e. we can allow $a[pos_i] < a[pos_{i + 1}]$, since aIS will still be aIS. Now, note that between $pos_{i-1}$ and $pos_{i + 1}$ we can choose any $j$ such that $a[pos_{i - 1}] \\le a[j]$, so we can always choose the first such $j$, moreover we can precalculate such $j$ as $nxt_i$ for each $a_i$. Using stacks or something similar. Now, we can note that each $a_i$ is either minimum in LaIS or $i = nxt_j$ for some other element $a_j$. And we can write the following dynamic programming: let $d[i]$ be the LaIS which finish in $a_i$ and it's the last minimum (we can think that the last element of LaIS is minimum in the imaginary pair). To calculate it, we can iterate $i$ from left to right and store for each value $x$ the length of LaIS with the last minimum (not the last element) equal to $x$ in Segment Tree (ST). So, $d_i$ is equal to \"get maximum over segment $[0, a_i]$ in ST\" plus $1$. And we update ST in two moments: firstly, right now with value $d_i$ in position $a_i$ and secondly, after we meet the element $nxt_i$ with value $d_i + 1$ also in position $a_i$. After we process all $i$ we'll get ST where for each $x$ the length of LaIS with last minimum equal to $x$ will be stored and the answer will be equal just to \"maximum over all tree (segment $[0, n]$)\". In total, we should calculate $nxt_i$ for each $a_i$ (we can do it in linear time using stack) and maintain Segment Tree with two basic operations: range maximum and update in position. The time complexity is $O(n \\log(n))$ and the space complexity is $O(n)$.",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1468",
    "index": "B",
    "title": "Bakery",
    "statement": "Monocarp would like to open a bakery in his local area. But, at first, he should figure out whether he can compete with other shops.\n\nMonocarp plans that the bakery will work for $n$ days. On the $i$-th day, $a_i$ loaves of bread will be baked in the morning before the opening. At the end of the $n$-th day, Monocarp will sell all the remaining bread that wasn't sold earlier with a huge discount.\n\nBecause of how bread is stored, the bakery seller sells the bread in the following order: firstly, he sells the loaves that were baked that morning; secondly, he sells the loaves that were baked the day before and weren't sold yet; then the loaves that were baked two days before and weren't sold yet, and so on. That's why some customers may buy a rather stale bread and will definitely spread negative rumors.\n\nLet's define loaf spoilage as the difference between the day it was baked and the day it was sold. Then the unattractiveness of the bakery will be equal to the maximum spoilage among all loaves of bread baked at the bakery.\n\nSuppose Monocarp's local area has consumer demand equal to $k$, it means that each day $k$ customers will come to the bakery and each of them will ask for one loaf of bread (the loaves are sold according to the aforementioned order). If there is no bread left, then the person just doesn't buy anything. During the last day sale, all the remaining loaves will be sold (and they will still count in the calculation of the unattractiveness).\n\nMonocarp analyzed his competitors' data and came up with $m$ possible consumer demand values $k_1, k_2, \\dots, k_m$, and now he'd like to calculate the unattractiveness of the bakery for each value of demand. Can you help him?",
    "tutorial": "Let's look at all $n$ days with some fixed $k$. Obviously, the seller works like a stack, so let's divide all days into segments in such a way, that the stack is emptied between consecutive segments. We can note that after we've got these segments - the answer is the maximum length among all segments. Why? Because the stalest bread on the bottom of the stack and we can't sell it until we empty the stack. Now, let's set $k = 10^9$ and look at what happens when we gradually lower $k$. With $k=10^9$, we sell all bread that we baked on the same day, so all segments consist of one day $[i, i + 1)$. Now, if we start lowering $k$ then at some moment segments will start to merge (and only merge), since $k$ is not enough to sell all bread in this interval. Since no segment will split up, there will be only $n - 1$ merging. So we can look only at moments $k$ when either several segments merge or when we should answer the query. With what $k$ the segment $[p_1, p_1)$ will start to merge with the next segment $[p_1, p_2)$? The answer is when $(p_2 - p_1) \\cdot k < \\sum\\limits_{p_1 \\le i < p_2}{a_i}$ or $k = \\left\\lfloor \\frac{(\\sum{a_i}) - 1}{p_2 - p_1} \\right\\rfloor$. So, we can for each segment $[p_i, p_{i + 1})$ maintain its value $k_i$ when it will start merging with next segment in set. And if we want to calculate the answer for a given $k$ from the queries, we should merge all segments with $k_i \\ge k$, while updating the current maximum length among all segments. Since merging two segments require two operations with the set then the total time complexity is $O(m + n \\log{n})$.",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1468",
    "index": "C",
    "title": "Berpizza",
    "statement": "Monocarp and Polycarp are working as waiters in Berpizza, a pizzeria located near the center of Bertown. Since they are waiters, their job is to serve the customers, but they choose whom they serve first differently.\n\nAt the start of the working day, there are no customers at the Berpizza. They come there one by one. When a customer comes into the pizzeria, she sits and waits for Monocarp or Polycarp to serve her. Monocarp has been working in Berpizza for just two weeks, so whenever he serves a customer, he simply chooses the one who came to Berpizza first, and serves that customer.\n\nOn the other hand, Polycarp is an experienced waiter at Berpizza, and he knows which customers are going to spend a lot of money at the pizzeria (and which aren't) as soon as he sees them. For each customer, Polycarp estimates the amount of money this customer can spend, and when he serves a customer, he chooses the one that is expected to leave the most money at Berpizza (in case there are several such customers, he chooses the one who came first among them).\n\nObviously, no customer can be served twice, so Monocarp and Polycarp choose which customer to serve only among those who haven't been served yet.\n\nWhen the number of customers gets really high, it becomes difficult for both Monocarp and Polycarp to choose the customer they are going to serve. Your task is to write a program that makes these choices for them. Formally, your program should be able to process three types of queries:\n\n- $1$ $m$ — a customer comes to Berpizza, and Polycarp estimates the amount of money that they will spend as $m$;\n- $2$ — Monocarp serves a customer which came to the pizzeria first;\n- $3$ — Polycarp serves a customer which is expected to spend the largest amount of money at the pizzeria (if there are several such customers, the one that came to the pizzeria first is chosen).\n\nFor each query of types $2$ and $3$, report the number of the customer who was served (the customers are numbered in the order they come to the pizzeria, starting from $1$).",
    "tutorial": "The hardest part of this problem is to efficiently implement the third query, i. e. finding the customer with the greatest value of $m$ and erasing it. Simply iterating on all of them is too slow, since there may be up to $2.5 \\cdot 10^5$ such queries and up to $5 \\cdot 10^5$ customers at the pizzeria. There are several solutions to this issue, I will describe two of them. The first solution is to treat each customer as a pair $(id, m)$, where $id$ is the number of the customer. Then the first query means \"insert a new pair\", the second query - \"remove the pair with minimum $id$\", and the third query - \"remove the pair with maximum $m$\". To maintain them, we can use two balanced binary trees that store these pairs - one will store them sorted by $id$, and the other - sorted by $m$. Then the second query means \"find the leftmost element in the first tree and erase it from both trees\", and the third query means \"find the rightmost element in the second tree and erase it from both trees\". Balanced binary trees can perform these operations in $O(\\log n)$, where $n$ is the size of the tree. Note that in most languages you don't have to write a balanced binary tree from scratch - for example, the containers std::set in C++ and TreeSet in Java already support all of the required operations. The second solution maintains three data structures: a queue for supporting the queries of type $2$, a heap for supporting the queries of type $3$, and an array or set that allows checking whether some customer was already deleted by a query. Finding the customer that came first using a queue or has a maximum value of $m$ using a heap is easy, but deleting some element from queue/heap is much harder (because we have to delete some arbitrary element, not necessarily the element at the head of the queue/heap). Instead, we can do it the other way: when we delete some customer from one of these data structures, we mark it as deleted. And while processing the following queries of type $2$ or $3$, we should check the element in the head of the data structure and, if it is marked as deleted, remove it before processing the query. Note that there can be multiple such elements, so it should be done in a loop. Since each element is deleted at most once, this solution works in $O(n \\log n)$ amortized.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1468",
    "index": "D",
    "title": "Firecrackers",
    "statement": "Consider a long corridor which can be divided into $n$ square cells of size $1 \\times 1$. These cells are numbered from $1$ to $n$ from left to right.\n\nThere are two people in this corridor, a hooligan and a security guard. Initially, the hooligan is in the $a$-th cell, the guard is in the $b$-th cell ($a \\ne b$).\n\n\\begin{center}\n{\\small One of the possible situations. The corridor consists of $7$ cells, the hooligan is in the $3$-rd cell, the guard is in the $6$-th ($n = 7$, $a = 3$, $b = 6$).}\n\\end{center}\n\nThere are $m$ firecrackers in the hooligan's pocket, the $i$-th firecracker explodes in $s_i$ seconds after being lit.\n\nThe following events happen each second (sequentially, \\textbf{exactly in the following order}):\n\n- firstly, the hooligan either moves into an adjacent cell (from the cell $i$, he can move to the cell $(i + 1)$ or to the cell $(i - 1)$, and he cannot leave the corridor) or stays in the cell he is currently. If the hooligan doesn't move, he can light \\textbf{one} of his firecrackers and drop it. The hooligan can't move into the cell where the guard is;\n- secondly, some firecrackers that were already dropped may explode. Formally, if the firecracker $j$ is dropped on the $T$-th second, then it will explode on the $(T + s_j)$-th second (for example, if a firecracker with $s_j = 2$ is dropped on the $4$-th second, it explodes on the $6$-th second);\n- finally, the guard moves one cell closer to the hooligan. If the guard moves to the cell where the hooligan is, the hooligan is caught.\n\nObviously, the hooligan will be caught sooner or later, since the corridor is finite. His goal is to see the maximum number of firecrackers explode before he is caught; that is, he will act in order to maximize the number of firecrackers that explodes before he is caught.\n\nYour task is to calculate the number of such firecrackers, if the hooligan acts optimally.",
    "tutorial": "The first crucial observation that we need is the following one: it is optimal to light and drop some firecrackers, and only then start running away from the guard (that's because running away doesn't actually do anything if none of the firecrackers are lit). The hooligan shouldn't drop more than $|a - b| - 1$ firecrackers, because otherwise he will be caught before starting running away, and the last firecracker he dropped won't go off. Okay, now suppose the hooligan wants to explode exactly $f$ firecrackers. It's obvious that he wants to choose the $f$ firecrackers with minimum $s_i$, but in which order he should drop them? If the $i$-th firecracker he drops goes off in $s_j$ seconds, then it will explode on the $(i + s_j)$-th second. We have to choose an ordering of the firecrackers that minimizes the maximum of $(i + s_j)$ in order to check that the hooligan has enough time to see all the firecrackers he dropped explode. It can be shown that we can drop the firecracker with the maximum $s_j$ first, then the firecracker with the second maximum $s_j$, and so on, and the maximum of $(i + s_j)$ is minimized (obviously, we consider only the firecrackers with $f$ minimum values of $s_i$). This leads us to a solution with a binary search on $f$ in $O(n \\log n)$: we can check that the hooligan can explode at least $f$ firecrackers in $O(n)$ (after sorting the sequence $s$ beforehand), and binary search requires to check it for only $\\log n$ values of $f$.",
    "tags": [
      "binary search",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1468",
    "index": "E",
    "title": "Four Segments",
    "statement": "Monocarp wants to draw four line segments on a sheet of paper. He wants the $i$-th segment to have its length equal to $a_i$ ($1 \\le i \\le 4$). These segments can intersect with each other, and each segment should be either horizontal or vertical.\n\nMonocarp wants to draw the segments in such a way that they enclose a rectangular space, and the area of that rectangular space should be maximum possible.\n\nFor example, if Monocarp wants to draw four segments with lengths $1$, $2$, $3$ and $4$, he can do it the following way:\n\n\\begin{center}\n{\\small Here, Monocarp has drawn segments $AB$ (with length $1$), $CD$ (with length $2$), $BC$ (with length $3$) and $EF$ (with length $4$). He got a rectangle $ABCF$ with area equal to $3$ that is enclosed by the segments.}\n\\end{center}\n\nCalculate the maximum area of a rectangle Monocarp can enclose with four segments.",
    "tutorial": "Suppose the values of $a_1$, $a_2$, $a_3$, $a_4$ are sorted in non-descending order. Then the shorter side of the rectangle cannot be longer than $a_1$, because one of the sides must be formed by a segment of length $a_1$. Similarly, the longer side of the rectangle cannot be longer than $a_3$, because there should be at least two segments with length not less than the length of the longer side. So, the answer cannot be greater than $a_1 \\cdot a_3$. It's easy to construct the rectangle with exactly this area by drawing the following segments: from $(0, 0)$ to $(a_1, 0)$; from $(0, a_3)$ to $(a_2, a_3)$; from $(0, 0)$ to $(0, a_3)$; from $(a_1, 0)$ to $(a_1, a_4)$. So, the solution is to sort the sequence $[a_1, a_2, a_3, a_4]$, and then print $a_1 \\cdot a_3$.",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1468",
    "index": "F",
    "title": "Full Turn",
    "statement": "There are $n$ persons located on a plane. The $i$-th person is located at the point $(x_i, y_i)$ and initially looks at the point $(u_i, v_i)$.\n\nAt the same moment of time, all persons will start to rotate clockwise synchronously with the same angular speed. They will rotate until they do one full $360$-degree turn.\n\nIt is said that persons $A$ and $B$ made eye contact if person $A$ looks in person $B$'s direction at the same moment when person $B$ looks in person $A$'s direction. If there is a person $C$ located between persons $A$ and $B$, that will not obstruct $A$ and $B$ from making eye contact. A person can make eye contact with more than one person at the same time.\n\nCalculate the number of pairs of persons that will make eye contact at least once during the rotation (including the initial moment).",
    "tutorial": "Lets define for person with index $i$ their initial vision vector as vector ($u_i - x_i$, $v_i - y_i$). It is possible to prove that two persons will make eye contact during 360 rotation if and only if their initial vision vectors are collinear and oppositely directed. Note that the position of the persons does not matter, only their vision vectors. E.g. lets assume that person $A$ has initial vision vector ($3$, $-4$) and person $B$ - ($-6$, $8$). These vectors are collinear and oppositely directed, hence person $A$ and $B$ will make eye contact during the rotation. If we try to check separately for each pair of persons if they will make eye contact, that would take too much time. For example for $n=10^5$ that would take $\\approx 5*10^9$ checks. Instead we should use a different approach. First, lets normalize vision vector of each person by dividing its coordinates by GCD of absolute values of the coordinates. Here GCD stands for greatest common divisor. E.g. vector's coordinates ($6$, $-8$) should be divided by $GCD(|6|, |-8|) = GCD(6, 8) = 2$, and the normalized vector will be ($3$, $-4$). There is a special case for vectors, which have zero as one of the coordinates: ($0$, $C$), ($0$, $-C$), ($C$, $0$) and ($-C$, $0$), where $C$ is some positive integer. These should be normalized to vectors ($0$, $1$), ($0$, $-1$), ($1$, $0$) and ($-1$, $0$) respectively. After normalization all collinear and co-directed vectors will have exactly the same coordinates. Lets group such vectors and count the number of vectors in each group. Then it is obvious that each person from group with vector ($x$, $y$) will make eye contact with each person from group with vector ($-x$, $-y$). If the first group has $k$ vectors and the second group has $l$ vectors, in total there will be $k*l$ eye contacts between members of these two groups. And also members of these two groups will not make eye contact with members of any other groups. So fast algorithm should create a map, where key would be group's vector and value - number of persons in the group. Then the algorithm should iterate over groups in the map, for each group find the oppositely directed group, and add to the answer multiplication of these groups' sizes. Note that the maximum possible answer is $(n/2)^2$. That would be $2.5*10^9$ when $n=10^5$, which does not fit into signed int32.",
    "tags": [
      "geometry",
      "hashing",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1468",
    "index": "G",
    "title": "Hobbits",
    "statement": "The hobbits Frodo and Sam are carrying the One Ring to Mordor. In order not to be spotted by orcs, they decided to go through the mountains.\n\nThe mountain relief can be represented as a polyline with $n$ points $(x_i, y_i)$, numbered from $1$ to $n$ ($x_i < x_{i + 1}$ for $1 \\le i \\le n - 1$). Hobbits start their journey at the point $(x_1, y_1)$ and should reach the point $(x_n, y_n)$ to complete their mission.\n\nThe problem is that there is a tower with the Eye of Sauron, which watches them. The tower is located at the point $(x_n, y_n)$ and has the height $H$, so the Eye is located at the point $(x_n, y_n + H)$. In order to complete the mission successfully, the hobbits have to wear cloaks all the time when the Sauron Eye can see them, i. e. when there is a direct line from the Eye to the hobbits which is not intersected by the relief.\n\nThe hobbits are low, so their height can be considered negligibly small, but still positive, so when a direct line from the Sauron Eye to the hobbits only touches the relief, the Eye can see them.\n\n\\begin{center}\n{\\small The Sauron Eye can't see hobbits when they are in the left position, but can see them when they are in the right position.}\n\\end{center}\n\nThe hobbits do not like to wear cloaks, so they wear them only when they can be spotted by the Eye. Your task is to calculate the total distance the hobbits have to walk while wearing cloaks.",
    "tutorial": "Let's start with the general idea of the solution. To solve the problem, we need to iterate over all relief segments and understand, which part the segment is seen by the Eye. A segment point can be hidden from the Eye by several mountains, but it is enough to track only the highest mountain. Generally speaking, the relief segments can be processed in any order, bit it would be more convenient to iterate on them backwards - i.e. in the order from the Eye to the start point. Processing the segments in reversed order will allow to recalculate the highest mountain easier. Let's now discuss implementation details. Formally speaking, there are $n$ relief points $p_i = (x_i, y_i)$ ($1 \\le i \\le n$) and the Eye point $E = (x_n, y_n + H)$. Each relief point defines its own angle $\\alpha_i$, which is measured counter-clockwise between positive direction of the OX axis and the $(E, p_i)$ vector. Now, having two relief points $p_i$ and $p_j$ ($i < j$), it can be said that $p_i$ is hidden from the Eye if $\\alpha_i > \\alpha_j$. When this check is implemented in the solution, to avoid the precision loss, it is recommended to use vector product and analyse its sign to understand the relation of the angles. This check is done in $O(1)$ time. Being able to understand when a point is hidden from the Eye by another point, it is possible to calculate, which part of a segment $(p_i, p_{i + 1})$ is seen by the Eye. First of all let's note, that if the segment left point $p_i$ is hidden by its right point $p_{i + 1}$, then the entire segment is hidden from the Eye. Now, we have the situation when left segment point is not hidden from the Eye by its right point. But the segment or its part can still be hidden by the highest mountain (point $M$), which is a point with minimal angle from all relief points, located to the right of our segment. Here three cases are possible: both $p_{i}$ and $p_{i + 1}$ are hidden by $M$ - in this case the entire segment is hidden and we switch to the next segment; both $p_{i}$ and $p_{i + 1}$ are visible by the Eye (not hidden by the highest mountain $M$) - in this case the entire segment is visible and we should add its length to the answer; left segment point $p_i$ is visible by the Eye, but right segment point $p_{i + 1}$ is hidden by $M$ - in this case we need to find intersection point $I$ of the segment $(p_i, p_{i + 1})$ and the ray $(E, M)$. What is left - add length of $(p_i, I)$ segment to the answer. Now, let's conclude the final algorithm: Iterate over all relief segments from right to left, keeping the highest mountain point $M$. Analyze how left and right points of the current segment are located relatively to each other and point $M$. Recalculate $M$, taking points of the current segments as candidates for the highest mountain.",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1468",
    "index": "H",
    "title": "K and Medians",
    "statement": "Let's denote the median of a sequence $s$ with odd length as the value in the middle of $s$ if we sort $s$ in non-decreasing order. For example, let $s = [1, 2, 5, 7, 2, 3, 12]$. After sorting, we get sequence $[1, 2, 2, \\underline{3}, 5, 7, 12]$, and the median is equal to $3$.\n\nYou have a sequence of $n$ integers $[1, 2, \\dots, n]$ and an \\textbf{odd} integer $k$.\n\nIn one step, you choose any $k$ elements from the sequence and erase all chosen elements \\textbf{except} their median. These elements do not have to go continuously (gaps are allowed between them).\n\nFor example, if you have a sequence $[1, 2, 3, 4, 5, 6, 7]$ (i.e. $n=7$) and $k = 3$, then the following options for the first step are possible:\n\n- choose $[1, \\underline{2}, 3]$; $2$ is their median, so it is not erased, and the resulting sequence is $[2, 4, 5, 6, 7]$;\n- choose $[2, \\underline{4}, 6]$; $4$ is their median, so it is not erased, and the resulting sequence is $[1, 3, 4, 5, 7]$;\n- choose $[1, \\underline{6}, 7]$; $6$ is their median, so it is not erased, and the resulting sequence is $[2, 3, 4, 5, 6]$;\n- and several others.\n\nYou can do zero or more steps. Can you get a sequence $b_1$, $b_2$, ..., $b_m$ after several steps?\n\nYou'll be given $t$ test cases. Solve each test case independently.",
    "tutorial": "Since after each operation we erase exactly $k - 1$ element from $a$ then if $(n - m) \\not\\equiv 0 \\pmod{(k - 1)}$ then the answer is NO. Otherwise, if there is such element $b_{pos}$ such that there are at least $\\frac{k - 1}{2}$ erased elements lower than $b_i$ and at least $\\frac{k - 1}{2}$ erased elements greater that $b_i$, then answer is YES, otherwise NO. Let's prove this criterion in two ways. From the one side, in the last step, we should choose $k$ elements and erase them excepts its median, so the median is exactly that element $b_{pos}$. From the other side, let's prove that if there is such $b_{pos}$ then we can always choose operations to get sequence $b$. Let's make operations in such a way that in the last step we'll erase $b_{pos}$, $d = \\frac{k - 1}{2}$ elements lower $b_{pos}$ and $d$ elements greater $b_{pos}$. Since, it doesn't matter which $d$ elements to take from left and right of $b_{pos}$, we will only consider number of such elements. Let's denote $x$ and $y$ as the initial number of elements from left and right of $b_{pos}$ to erase. We know that $x \\ge d$ and $y \\ge d$. and we want to make both of them equal to $d$. Let $x' = x - d$ and $y' = y - d$. We can think that we have $x'$ free elements to erase from left and $y'$ from the right. While $x' + y' \\ge k$ let's take any $k$ free elements that should be erased and erase $k - 1$ of them. Then we get situation $0 \\le x' < k$, $0 \\le y' < k$ and $x' + y' < k$. Since $(n - m)$ is divisible by $(k - 1)$, then it means that $x' + y' = k - 1$. Let's look at what we can do now. We should take one of \"reserved\" elements to participate in erasing last $x' + y'$ free elements but it shouldn't break the situation with $d$ lower elements, $b_{pos}$ and $d$ greater elements. If $x' \\ge y'$, let's take one extra element which is lower than $b_{pos}$, then after erasing, the remaining median will also be lower than $b_{pos}$. If $x' < y'$, let's take one extra element greater than $b_{pos}$, then the remaining median will also be greater than $b_{pos}$. In the end, we choose $d$ elements lower, $b_{pos}$ and $d$ elements greater. Erase them except its median $b_{pos}$ and get the desired array $b$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1468",
    "index": "I",
    "title": "Plane Tiling",
    "statement": "You are given five integers $n$, $dx_1$, $dy_1$, $dx_2$ and $dy_2$. You have to select $n$ distinct pairs of integers $(x_i, y_i)$ in such a way that, for every possible pair of integers $(x, y)$, there exists exactly one triple of integers $(a, b, i)$ meeting the following constraints:\n\n\\begin{center}\n$ \\begin{cases} x \\, = \\, x_i + a \\cdot dx_1 + b \\cdot dx_2, \\\\ y \\, = \\, y_i + a \\cdot dy_1 + b \\cdot dy_2. \\end{cases} $\n\\end{center}",
    "tutorial": "One of the solutions is to consider an infinite 2 dimensional plane and draw a grid with lines parallel to vectors ($dx_1$, $dy_1$) and ($dx_2$, $dy_2$). By doing so we will get a tiling of the plane with parallelepipeds, one of them will have corners at ($0$, $0$), ($dx_1$, $dy_1$), ($dx_1 + dx_2$, $dy_1 + dy_2$), ($dx_2$, $dy_2$). All the parallelepipeds are same shape and all of them can be represented by translating one of them by vector ($a \\cdot dx_1 + b \\cdot dx_2$, $a \\cdot dy_1 + b \\cdot dy_2$), where $a$ and $b$ are all possible integer pairs. Thus, if we \"rasterize\" one of them, we will get a correct solution. To do so, we can represent the parallelepiped as two triangles and rasterize each of them individually. To rasterize a triangle, we need to select those cells which center is either inside of it, or located on the \"top\" or \"left\" edge of it. A \"top\" edge is an edge that is perfectly horizontal and whose defining vertices are above the third one. A \"left\" edge is an edge that is going up if we go in triangle's clockwise order. This way, no cell is going to be selected twice in case we \"rasterize\" two triangles sharing an edge, and since we are tiling the plane with given parallelepipeds rasterized cells are exactly our solution. If vectors ($dx_1$, $dy_1$) and ($dx_2$, $dy_2$) are either collinear or one of them is zero, the answer is \"NO\". Also there is another solution. First of all we have to calculate $d$ - absolute value of determinant of the matrix formed by the given vectors: $d = |det((dx_1, dy_1), (dx_2, dy_2))| = |dx_1 * dy_2 - dx_2 * dy_1|$ If given value $n$ is not equal to $d$ then there is no solution, in particular if $d=0$ there is no required $n$ pairs of integers. Now let $n$=$d$ and $d_x$ = $gcd(dx_1, dx_2)$, $d_y$ = $gcd(dy_1, dy_2)$. Let's go to the same problem with smaller integers - we divide $dx_1$, $dx_2$ by $d_x$ and divide $dy_1$, $dy_2$ by $d_y$. Also we define $m=n/(d_x \\cdot d_y)$ ($n$=$d$ so it is divisible by $d_x\\cdot d_y$). So firstly we need to find such $m$ points $(x_i, y_i)$ that all values $(x_i + a \\cdot dx_1 + b \\cdot dx_2, y_i + a \\cdot dy_1 + b \\cdot dy_2)$ are different. It is enough for solution, because we still have $m$ equal to the absolute value of the determinant of the new matrix. It turns out that it is easy to find such set of points. In particular we may choose points $(0,0), (0,1), \\cdots, (0, m-1)$, i.e. $x_i=i$, $y_i=0$. Let's prove that such set is correct. Assume that for some non-zero pair $(a, b)$ and for some $j$ we also have one of these points: $x_i$ = $x_j + a \\cdot dx_1 + b \\cdot dx_2$ and $y_i$ = $y_j + a \\cdot dy_1 + b \\cdot dy_2$. Considering $y_i=y_j=0$, we have $a \\cdot dy_1 + b \\cdot dy_2 = 0$. Since $dy_1$ and $dy_2$ are coprime (we have divided it by $d_y$) $a = k \\cdot dy_2$, $b = -k\\cdot dy_1$ for some integer $k$. If we use this for $x$ equation, we will have: $x_i - x_j$ = $k \\cdot dy_2 \\cdot dx_1 - k \\cdot dy_1 \\cdot dx_2$. I.e. $x_i - x_j$ = $k \\cdot (dx_1 \\cdot dy_2 - dx_2 \\cdot dy1)$ = $\\pm k \\cdot m$. Also $-m < x_i - x_j < m$ so this equation has no solution for integer non-zero $k$. Thus this set of points is correct. Finally having such $m$ points we have to create an $n$-points solution for the original problem. Obviously we need to multiply current answer coordinates by $d_x$ and $d_y$. Then for each of these points, for each $0 \\leq r_x < d_x$ and for each $0 \\leq r_y < d_y$ we need to print a new point. So, the answer is $(i \\cdot d_x + r_x, r_y)$ for each $0 \\leq i < m$, $0 \\leq r_x < d_x$, $0 \\leq r_y < d_y$.",
    "tags": [
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1468",
    "index": "J",
    "title": "Road Reform",
    "statement": "There are $n$ cities and $m$ bidirectional roads in Berland. The $i$-th road connects the cities $x_i$ and $y_i$, and has the speed limit $s_i$. The road network allows everyone to get from any city to any other city.\n\nThe Berland Transport Ministry is planning a road reform.\n\nFirst of all, maintaining all $m$ roads is too costly, so $m - (n - 1)$ roads will be demolished in such a way that the remaining $(n - 1)$ roads still allow to get to any city from any other city. Formally, the remaining roads should represent an undirected tree.\n\nSecondly, the speed limits on the remaining roads might be changed. The changes will be done sequentially, each change is either increasing the speed limit on some road by $1$, or decreasing it by $1$. Since changing the speed limit requires a lot of work, the Ministry wants to minimize the number of changes.\n\nThe goal of the Ministry is to have a road network of $(n - 1)$ roads with the maximum speed limit over all roads equal to exactly $k$. They assigned you the task of calculating the minimum number of speed limit changes they have to perform so the road network meets their requirements.\n\nFor example, suppose the initial map of Berland looks like that, and $k = 7$:\n\nThen one of the optimal courses of action is to demolish the roads $1$–$4$ and $3$–$4$, and then decrease the speed limit on the road $2$–$3$ by $1$, so the resulting road network looks like that:",
    "tutorial": "We will consider two cases: the road network without roads having $s_i > k$ is either connected or not. Checking that may be done with the help of DFS, BFS, DSU, or any other graph algorithm/data structure that allows checking if some graph is connected. If the network without roads having $s_i > k$ is not connected, then we have to take several roads with $s_i > k$ into the answer. Since their speed limit is too high, we have to decrease the speed limit on them to $k$. Then the required number of changes is $\\sum \\limits_{i \\in R} \\max(0, s_i - k)$, where $R$ is the set of roads that are added to the answer. To minimize this sum, we can set each road's speed limit to $\\max(0, s_i - k)$ and find the minimum spanning tree of the resulting graph. Unfortunately, this approach doesn't work in the other case - we may build a road network having the maximum speed limit less than $k$, not exactly $k$. We have to choose a road with the current speed limit as close to $k$ as possible, i. e. the one with the minimum value of $|s_i - k|$. After applying $|s_i - k|$ changes to it, we can choose $n - 2$ roads having $s_i \\le k$ to form a spanning tree with the chosen road (it is always possible due to the properties of the spanning tree: if we have a spanning tree and we want to add an edge of the graph to it, we can always find another edge to discard). So, in this case, the answer is $\\min \\limits_{i = 1}^{m} |s_i - k|$.",
    "tags": [
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1468",
    "index": "K",
    "title": "The Robot",
    "statement": "There is a robot on a checkered field that is endless in all directions. Initially, the robot is located in the cell with coordinates $(0, 0)$. He will execute commands which are described by a string of capital Latin letters 'L', 'R', 'D', 'U'. When a command is executed, the robot simply moves in the corresponding direction:\n\n- 'L': one cell to the left (the $x$-coordinate of the current cell decreases by $1$);\n- 'R': one cell to the right (the $x$-coordinate of the current cell is increased by $1$);\n- 'D': one cell down (the $y$-coordinate of the current cell decreases by $1$);\n- 'U': one cell up (the $y$-coordinate of the current cell is increased by $1$).\n\nYour task is to put an obstacle in one cell of the field so that after executing the commands, the robot will return to the original cell of its path $(0, 0)$. Of course, an obstacle cannot be placed in the starting cell $(0, 0)$. It is guaranteed that if the obstacle is not placed, then the robot will not return to the starting cell.\n\nAn obstacle affects the movement of the robot in the following way: if it tries to go in a certain direction, and there is an obstacle, then it simply remains in place (the obstacle also remains, that is, it does not disappear).\n\nFind any such cell of the field (other than $(0, 0)$) that if you put an obstacle there, the robot will return to the cell $(0, 0)$ after the execution of all commands. If there is no solution, then report it.",
    "tutorial": "It is obvious that the cell that can be the answer must belong to the original path of the robot. Thus, there are at most $n$ candidate cells in the answer. In order to make sure that a candidate cell is indeed the answer; it is necessary to simulate the movement of the robot, taking into account this cell as an obstacle. No more than $n$ actions will be spent on one such simulation. Therefore, to check all $n$ candidates, the total number of actions spent is will not exceed $n^2$, which fits into the requirements for the running time (time limit) of a solution.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1468",
    "index": "L",
    "title": "Prime Divisors Selection",
    "statement": "Suppose you have a sequence of $k$ integers $A = [a_1, a_2, \\dots , a_k]$ where each $a_i \\geq 2$. A sequence of \\textbf{prime} integers $P = [p_1, p_2, \\dots, p_k]$ is called suitable for the sequence $A$ if $a_1$ is divisible by $p_1$, $a_2$ is divisible by $p_2$ and so on.\n\nA sequence of \\textbf{prime} integers $P$ is called friendly if there are no unique integers in this sequence.\n\nA sequence $A$ is called ideal, if each sequence $P$ that is suitable for $A$ is friendly as well (i. e. there is no sequence $P$ that is suitable for $A$, but not friendly). For example, the sequence $[2, 4, 16]$ is ideal, while the sequence $[2, 4, 6]$ is not ideal (there exists a sequence $P = [2, 2, 3]$ which is suitable for $A$, but not friendly).\n\nYou are given $n$ different integers $x_1$, $x_2$, ..., $x_n$. You have to choose \\textbf{exactly} $k$ of them in such a way that they form an ideal sequence, or report that it is impossible. Note that no integer can be chosen more than once.",
    "tutorial": "Let's find for each prime integer $p \\leq 10^{9}$ amount of integers $p^{q}$ among the given integers. If there are no more than 1 such integers, this prime $p$ is not interesting for us: if we add one such integer to the answer, we may always select exactly one divisor $p$ in a suitable sequence so it will not be friendly. Otherwise let's call such $p$ important and find a group $X_p$ (with some size $k_i$ > 1) - all integers $p^q$ in the given set. So we have several ($t$) such groups with sizes $k_1$, $k_2$, ... $k_t$. Now there are some different cases. Case 1: required size $k \\leq k_1 + k_2 + \\dots + k_t$. If $k$ is odd and $k_i$=2 for each $i$, we have to find some integer $y$ that has minimum possible different important primes in factorization (and does not have not important primes). If there is no such $y$, obviously, there is no solution. Now let there is $y$ that has $u$ different primes in factorization. If $u \\leq (k-1)/2$ we may take all $u$ groups necessary for this integer $y$ and add some other groups $X_p$ in order to have exactly $k$ numbers in the result (if $u < (k-1)/2$). If $k$ is even and $k_i$ = 2 for each $i$, we may just take any $k/2$ groups by 2 integers. If $k_j$ > 2 for some $j$ it is easy to check that we may always find the ideal sequence. Let's start to add groups with the maximum sizes while it is possible. Now we have total size $k_1 \\leq k$ and $q = k - k_1$ 'empty' space. If $q \\geq 2$, we may just add $q$ integers from the next group. If $q = 1$, we may remove one integer from the greatest group (because its size is at least 3) and add 2 integers from the next group. Case 2: $k$ > $k_1$ + $k_2$ + ... + $k_t$. First of all let's take all the groups $X_p$ to the answer. Now each of the remaining integers is either represented as a product of important primes, or not. If it is represented, then we can add it to the answer and the set will remain ideal. Otherwise if we add such number, we can choose any prime divisor from it that is not important and the set will not be ideal. So, we just have to check whether there are enough integers that are represented as a product of important primes and add any $k$ - $k_1$ - $k_2$ - ... - $k_t$ of them to the answer. If there are not enough such integers, there is no solution. How to find all important primes? We are interested only in groups $X_p = {p^q}$ with sizes at least 2. So each such group either has an integer $p^2$ or an integer $p^q$ with $q \\geq 3$. To find all the numbers in the first case, we may just check for each given integer whether it is $p^2$ for some prime $p$. For the second case we have $p \\leq 10^6$, so we may find all the possible powers for each prime $p \\leq 10^6$.",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1468",
    "index": "M",
    "title": "Similar Sets",
    "statement": "You are given $n$ sets of integers. The $i$-th set contains $k_i$ integers.\n\nTwo sets are called similar if they share at least two common elements, i. e. there exist two integers $x$ and $y$ such that $x \\ne y$, and they both belong to each of the two sets.\n\nYour task is to find two similar sets among the given ones, or report that there is no such pair of sets.",
    "tutorial": "Let's define $D$ = $m^{1/2}$, where $m$ is the total amount of integers. Now let's call a set of integers 'large' if its size is at least $D$ and 'small' otherwise. Firstly let's check whether there is a large set that has two common integers with some other (small or large) set. Let's try to find a similar set for each large set $S$ separately. For each integer $x$ in $S$ we may set flag $w[x]$=1. Now for each other set $T$ with size $k$ we may calculate amount of integers $x$ in $T$ that satisfy condition $w[x]$=1 (i.e. amount of common integers with $S$) using $O(k)$ operations. So, we will use $O(m)$ operations for each large set $S$. Since $D$=$m^{1/2}$ we will have at most $m/D$ = $D$ large sets and will perform $O(D*m) = O(m^{3/2})$ operations. Now we have to check whether there are two similar small sets. For each small set $S$ let's find all pairs of integers $(x, y)$, $x < y$ in this set. If there are two equal pairs in different sets, that sets are similar. To find such pairs we may just create a separate array for each integer $x$ and add all values $y$ to it. It is possible to check whether there are two equal integers in array in $O(k)$ operations, where $k$ is the size of this array. Since the size of each small set is at most $D$ we will have at most $D*k$ pairs for each set of size $k$ and at most $D*m$ pairs in total. So we will perform $O(D*m)$ = $O(m^{3/2})$ operations.",
    "tags": [
      "data structures",
      "graphs",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1469",
    "index": "A",
    "title": "Regular Bracket Sequence",
    "statement": "A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence \"RBS\".\n\nYou are given a sequence $s$ of $n$ characters (, ), and/or ?. \\textbf{There is exactly one character ( and exactly one character )} in this sequence.\n\nYou have to replace every character ? with either ) or ( (different characters ? can be replaced with different brackets). \\textbf{You cannot reorder the characters, remove them, insert other characters, and each ? must be replaced}.\n\nDetermine if it is possible to obtain an RBS after these replacements.",
    "tutorial": "There are two solutions to this problem: casework and greedy. The greedy solution goes as follows: the number of opening brackets in an RBS should be exactly $\\frac{|s|}{2}$, and if there is a closing bracket before an opening bracket, it's optimal to swap them, if possible. So, we should replace the first $\\frac{|s|}{2} - 1$ question marks with opening brackets, other question marks with closing brackets, and if the answer exists, this method will find it. All that's left is to check that the resulting sequence is an RBS. The casework solution goes as follows: first of all, each RBS should have an even length, so if $|s|$ is odd, there is no answer. Furthermore, an RBS always begins with an opening bracket and always ends with a closing bracket, so if the first character is a closing bracket or the last character is an opening bracket, there is no answer. Since there is at most one opening bracket and at most one closing bracket in the original sequence, these three constraints are enough: if the opening bracket is before the closing bracket, then they balance out, and all other characters can be replaced in such a way that they form an RBS of length $|s| - 2$. If the opening bracket is after the closing bracket, then the first and the last characters are question marks (since the first character is not a closing bracket, and the last one is not an opening bracket). We should replace the first character with an opening bracket, the last character with a closing bracket, so we get four characters (two opening and two closing brackets) which balance themselves out. All other question marks can be replaced in such a way that they form an RBS of length $|s| - 4$. So, all we have to check is that $|s|$ is even, the first character is not a closing bracket, and the last character is not an opening bracket.",
    "code": "t = int(input())\nfor i in range(t):\n    s = input()\n    n = len(s)\n    a = [s[i] for i in range(n)]\n    cnt = n // 2 - 1\n    for j in range(n):\n        if a[j] == '?':\n            if cnt > 0:\n                cnt -= 1\n                a[j] = '('\n            else:\n                a[j] = ')'\n    bal = 0\n    minbal = 0\n    for j in range(n):\n        if a[j] == '(':\n            bal += 1\n        else:\n            bal -= 1\n        minbal = min(bal, minbal)\n    print('YES' if bal == 0 and minbal >= 0 else 'NO') ",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1469",
    "index": "B",
    "title": "Red and Blue",
    "statement": "Monocarp had a sequence $a$ consisting of $n + m$ integers $a_1, a_2, \\dots, a_{n + m}$. He painted the elements into two colors, red and blue; $n$ elements were painted red, all other $m$ elements were painted blue.\n\nAfter painting the elements, he has written two sequences $r_1, r_2, \\dots, r_n$ and $b_1, b_2, \\dots, b_m$. The sequence $r$ consisted of all red elements of $a$ \\textbf{in the order they appeared in $a$}; similarly, the sequence $b$ consisted of all blue elements of $a$ \\textbf{in the order they appeared in $a$ as well}.\n\nUnfortunately, the original sequence was lost, and Monocarp only has the sequences $r$ and $b$. He wants to restore the original sequence. In case there are multiple ways to restore it, he wants to choose a way to restore that maximizes the value of\n\n$$f(a) = \\max(0, a_1, (a_1 + a_2), (a_1 + a_2 + a_3), \\dots, (a_1 + a_2 + a_3 + \\dots + a_{n + m}))$$\n\nHelp Monocarp to calculate the maximum possible value of $f(a)$.",
    "tutorial": "Denote $p_i$ as the sum of first $i$ elements of $r$, and $q_j$ as the sum of first $j$ elements of $b$. These values can be calculated in $O(n + m)$ with prefix sums. The first solution is to use dynamic programming. Let $dp_{i, j}$ be the maximum value of $f(a)$ if we placed the first $i$ elements of $r$ and the first $j$ elements of $b$. Transitions can be performed in $O(1)$: we either place an element from $r$ (then we go to $dp_{i + 1, j}$ and update it with $\\max(dp_{i, j}, p_{i + 1} + q_j)$), or place an element from $b$ (then we go to $dp_{i, j + 1}$ and update it with $\\max(dp_{i, j}, p_i + q_{j + 1})$). The answer is stored in $dp_{n, m}$, and this solution works in $O(nm)$. The second solution: observe that the sum of several first elements of $a$ is the sum of several first elements of $r$ and several first elements of $b$. So each prefix sum of $a$ (and the answer itself) is not greater than $\\max_{i = 0}^{n} p_i + \\max_{j = 0}^{m} p_j$. It's easy to show how to obtain exactly this answer: let $k$ be the value of $i$ such that $p_i$ is maximized, and $l$ be the value of $j$ such that $q_j$ is maximized. Let's place the first $k$ elements of $r$, then the first $l$ elements of $b$ (so the current sum is exactly $\\max_{i = 0}^{n} p_i + \\max_{j = 0}^{m} p_j$), and place all of the remaining elements in any possible order. So, the answer is $\\max_{i = 0}^{n} p_i + \\max_{j = 0}^{m} p_j$. This solution works in $O(n + m)$.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ta = [int(x) for x in input().split()]\n\tm = int(input())\n\tb = [int(x) for x in input().split()]\n\tdp = [[-10**9 for j in range(m + 1)] for i in range(n + 1)]\n\tdp[0][0] = 0\n\tans = 0\n\tfor i in range(n + 1):\n\t\tfor j in range(m + 1):\n\t\t\tif i < n:\n\t\t\t\tdp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + a[i])\n\t\t\tif j < m:\n\t\t\t\tdp[i][j + 1] = max(dp[i][j + 1], dp[i][j] + b[j])\n\t\t\tans = max(ans, dp[i][j])\n\tprint(ans)",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1469",
    "index": "C",
    "title": "Building a Fence",
    "statement": "You want to build a fence that will consist of $n$ equal sections. All sections have a width equal to $1$ and height equal to $k$. You will place all sections in one line side by side.\n\nUnfortunately, the ground beneath the fence is not flat. For simplicity, you can think that the ground level under the $i$-th section is equal to $h_i$.\n\nYou should follow several rules to build the fence:\n\n- the consecutive sections should have a common side of length at least $1$;\n- the first and the last sections should stand on the corresponding ground levels;\n- the sections between may be either on the ground level or higher, but not higher than $k - 1$ from the ground level $h_i$ (the height should be an integer);\n\n\\begin{center}\n{\\small One of possible fences (blue color) for the first test case}\n\\end{center}\n\nIs it possible to build a fence that meets all rules?",
    "tutorial": "Let's set sections from left to right. Note that for the $i$-th section all valid heights $x$ (heights for which it's possible to choose heights for all sections $1 \\dots i$ meeting all rules and finishing with the height of $i$ equal to $x$) form a segment. It's not hard to prove by induction. For the first section, the valid segment is $[h_1, h_1]$. The step of induction: if the valid segment for $i - 1$ is $[l_{i - 1}, r_{i - 1}]$ then valid $x_i$-s for $i$ is the segment $[\\max(l_{i - 1} - (k - 1), h_i), \\min(r_{i - 1} + (k - 1), h_i + (k - 1))]$, since for each $x_i$ you can find at least one $x_{i - 1}$ in $[l_{i - 1}, r_{i - 1}]$ which don't break the first rule. If for any $i$ the correct segment is empty or if we can't fulfill the third rule ($h_n \\not\\in [l_{n - 1} - (k - 1), r_{n - 1} + (k - 1)]$) then there is no answer, otherwise at least one answer is always exist. As a result, to solve the problem, you should just maintain the segment of valid $x_i$ (using the formula above) while iterating $i$. Complexity is $O(n)$.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (n, k) = readLine()!!.split(' ').map { it.toInt() }\n        val h = readLine()!!.split(' ').map { it.toInt() }\n\n        var mn = h[0]\n        var mx = h[0]\n        var ok = true\n        for (i in 1 until n) {\n            mn = maxOf(mn - k + 1, h[i])\n            mx = minOf(mx + k - 1, h[i] + k - 1)\n            if (mn > mx) {\n                ok = false\n                break\n            }\n        }\n        if (h[n - 1] !in mn..mx)\n            ok = false\n        println(if (ok) \"YES\" else \"NO\")\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1469",
    "index": "D",
    "title": "Ceil Divisions",
    "statement": "You have an array $a_1, a_2, \\dots, a_n$ where $a_i = i$.\n\nIn one step, you can choose two indices $x$ and $y$ ($x \\neq y$) and set $a_x = \\left\\lceil \\frac{a_x}{a_y} \\right\\rceil$ (ceiling function).\n\nYour goal is to make array $a$ consist of $n - 1$ ones and $1$ two in no more than $n + 5$ steps. Note that you don't have to minimize the number of steps.",
    "tutorial": "There are many different approaches. We will describe a pretty optimal one. Let's solve the problem recursively. Let's say we need to process segment $[1, x]$. If $x = 2$, we don't need to do anything. Otherwise, $x > 2$. Let's find the minimum $y$ such that $y \\ge \\left\\lceil \\frac{x}{y} \\right\\rceil$. The chosen $y$ is convenient because it allows making $x$ equal to $1$ in two divisions (and it's the minimum number of divisions to get rid of $x$). Now we can, firstly, make all $z \\in [y + 1, x)$ equal to $1$ in one step (by division on $x$) and then make $x$ equal to $1$ with two divisions on $y$. As a result, we've spent $x - y + 1$ operations and can solve our task recursively for $[1, y]$. In total, we will spend $n - 2 + \\mathit{\\text{number_of_segments}}$ and since the segments are like $(\\sqrt{x}, x]$, $(\\sqrt{\\sqrt{x}}, \\sqrt{x}]$,... There will be at most $\\log{(\\log{n})}$ segments and $n + 3$ operations are enough for $n \\le 2^{32}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nint n;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\treturn true;\n}\n\nvoid calc(int n, vector<pt> &ans) {\n\tif (n == 2)\n\t\treturn;\n\t\n\tint y = max(1, (int)sqrt(n) - 1);\n\twhile (y < (n + y - 1) / y)\n\t\ty++;\n\t\n\tfore (pos, y + 1, n)\n\t\tans.emplace_back(pos, n);\n\tans.emplace_back(n, y);\n\tans.emplace_back(n, y);\n\t\n\tcalc(y, ans);\n}\n\ninline void solve() {\n\tvector<pt> ans;\n\tcalc(n, ans);\n\t\n\tcout << sz(ans) << endl;\n\tfor(auto p : ans)\n\t\tcout << p.first << \" \" << p.second << '\\n';\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint tc; cin >> tc;\n\twhile(tc--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1469",
    "index": "E",
    "title": "A Bit Similar",
    "statement": "Let's call two strings $a$ and $b$ (both of length $k$) a bit similar if they have the same character in some position, i. e. there exists at least one $i \\in [1, k]$ such that $a_i = b_i$.\n\nYou are given a binary string $s$ of length $n$ (a string of $n$ characters 0 and/or 1) and an integer $k$. Let's denote the string $s[i..j]$ as the substring of $s$ starting from the $i$-th character and ending with the $j$-th character (that is, $s[i..j] = s_i s_{i + 1} s_{i + 2} \\dots s_{j - 1} s_j$).\n\nLet's call a binary string $t$ of length $k$ beautiful if it is a bit similar to all substrings of $s$ having length exactly $k$; that is, it is a bit similar to $s[1..k], s[2..k+1], \\dots, s[n-k+1..n]$.\n\nYour goal is to find the \\textbf{lexicographically} smallest string $t$ that is beautiful, or report that no such string exists. String $x$ is lexicographically less than string $y$ if either $x$ is a prefix of $y$ (and $x \\ne y$), or there exists such $i$ ($1 \\le i \\le \\min(|x|, |y|)$), that $x_i < y_i$, and for any $j$ ($1 \\le j < i$) $x_j = y_j$.",
    "tutorial": "Let's denote $z$ as the number of substrings of $s$ having length exactly $k$ (so, $z = n - k + 1$). The first and crucial observation is that if $2^k > z$, then the answer always exists. Each of $z$ substrings forbids one of the strings from being the answer (a string is forbidden if every each character differs from the corresponding character in one of the substrings); we can forbid at most $z$ strings from being the answer, and the number of possible candidates for the answer is $2^k$. This observation leads us to a more strong fact that actually allows us to find a solution: we can set the first $k - \\lceil \\log_2 (z+1) \\rceil$ characters in the answer to 0; all the remaining characters are enough to find the answer. There are at most $2^{\\lceil\\log_2(z+1)\\rceil}$ possible combinations of the last characters, and this number is not greater than $2n$. Let's iterate on each substring of $s$ of length $k$ and check which combination it forbids by inverting the last $\\lceil \\log_2 (z+1) \\rceil$ characters of the substring. After that, find the minimum unforbidden combination. Note that there may be a case when a substring doesn't actually forbid any combination - if there are zeroes in the first $k - \\lceil \\log_2 (z+1) \\rceil$ characters of the substring, it is a bit similar to the answer no matter which combination we choose. This can be checked by precalculating the closest position of zero to the left/right of each index. The whole solution works in $O(n \\log n)$ per test case - the hardest part is inverting the suffix of each substring we are interested in.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000043;                 \nint q;\nchar buf[N];\nint n, k;\n\nint ceilLog(int x)\n{\n    int y = 0;\n    while((1 << y) < x)\n        y++;\n    return y;\n}\n\nint main()\n{\n    scanf(\"%d\", &q);\n    for(int i = 0; i < q; i++)\n    {\n        scanf(\"%d %d\", &n, &k);\n        scanf(\"%s\", buf);\n        string s = buf;\n        int m = min(k, ceilLog(n - k + 2));\n        vector<int> used(1 << m, 0);\n        vector<int> next0(n, int(1e9));\n        if(s[n - 1] == '0')\n            next0[n - 1] = n - 1;\n        for(int j = n - 2; j >= 0; j--)\n            if(s[j] == '0')\n                next0[j] = j;\n            else\n                next0[j] = next0[j + 1];\n        int d = k - m;\n        for(int j = 0; j < n - k + 1; j++)\n        {\n            if(next0[j] - j < d)\n                continue;\n            int cur = 0;\n            for(int x = j + d; x < j + k; x++)\n                cur = cur * 2 + (s[x] - '0');\n            used[((1 << m) - 1) ^ cur] = 1;    \n        }\n        int ans = -1;\n        for(int j = 0; j < (1 << m); j++)\n            if(used[j] == 0)\n            {\n                ans = j;\n                break;    \n            }\n        if(ans == -1)\n            puts(\"NO\");\n        else\n        {\n            puts(\"YES\");\n            string res(d, '0');\n            string res2;\n            for(int j = 0; j < m; j++)\n            {\n                res2.push_back('0' + (ans % 2));\n                ans /= 2;\n            }\n            reverse(res2.begin(), res2.end());\n            res += res2;\n            puts(res.c_str());\n        }\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "hashing",
      "string suffix structures",
      "strings",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1469",
    "index": "F",
    "title": "Power Sockets",
    "statement": "// We decided to drop the legend about the power sockets but feel free to come up with your own :^)\n\nDefine a chain:\n\n- a chain of length $1$ is a single vertex;\n- a chain of length $x$ is a chain of length $x-1$ with a new vertex connected to the end of it with a single edge.\n\nYou are given $n$ chains of lengths $l_1, l_2, \\dots, l_n$. You plan to build a tree using some of them.\n\n- Each vertex of the tree is either white or black.\n- The tree initially only has a white root vertex.\n- All chains initially consist only of white vertices.\n- You can take one of the chains and connect any of its vertices to any white vertex of the tree with an edge. The chain becomes part of the tree. Both endpoints of this edge become black.\n- Each chain can be used no more than once.\n- Some chains can be left unused.\n\nThe distance between two vertices of the tree is the number of edges on the shortest path between them.\n\nIf there is at least $k$ white vertices in the resulting tree, then the value of the tree is the distance between the root and the $k$-th closest white vertex.\n\nWhat's the minimum value of the tree you can obtain? If there is no way to build a tree with at least $k$ white vertices, then print -1.",
    "tutorial": "At first, let's realize that the tree structure doesn't matter that much. What we actually need is the array $cnt_i$ such that it stores the number of white vertices on depth $i$. Initially, $cnt_0=1$ and all other are zero. If you take a chain and attach it to some vertex on depth $d$, then the number of vertices on depth $d$ decreases by $1$. Also, the added vertices update some other counts. So far, it's extremely unclear what to begin with. Let's start by introducing some greedy ideas. For each $t$ let's find the most optimal tree using exactly $t$ chains and update the answer with each of them. First, it's always optimal to attach a chain with its middle vertex. Just consider the changes in the white vertices counts. Second, for each $t$ it's always optimal to take the longest $t$ chains to use. If not the longest $t$ are used, then you can replace any of them and there will be more white vertices. It would be nice if we were able to just add another chain to the tree for $t-1$ to get the tree for $t$. However, that's not always the case. But we can still attempt it and show that the optimal answer was achieved somewhere in the process. Let's show that it's always optimal to attach a new chain to the closest white vertex. So there are basically two cases: there is not enough white vertices yet and there is enough. What happens if there is not enough vertices, and we pick the closest one to attach a chain to? If there are still not enough vertices, then we'll just continue. Otherwise, we'll have to show that the answer can't get any smaller by rearranging something. Consider what the answer actually is. Build a prefix sum array over $cnt$, then the answer is the shortest prefix such that its prefix sum is greater or equal to $k$. So we put the $t$-th chain to the closest white vertex at depth $d$. It decreases $cnt_d$ by $1$ and increases $cnt_{d+2}$ and further by $1$ or $2$. Every chain we have put to this point was attached to a vertex at depth less or equal to the answer (otherwise, we could've rearranged it and obtain the answer before). The optimal answer can be neither $d$, nor $d+1$ (also because we could've rearranged). Thus, the answer is at least $d+2$ and every single chain we have put was packed as tightly as possible below that depth. The second case works similarly. We could've obtained the optimal answer before $t$. So the answer is below $d+2$ and we can do nothing about that. Or the optimal answer is ahead of us, so putting the chain at $d$ can decrease it as much or stronger as any other choice. Thus, updating the answer on every iteration will give us the optimal result. Now we are done with the greedy, time to implement it. I chose the most straightforward way. We basically have to maintain a data structure that can add on range, get the value of a cell and find the shortest prefix with sum at least $k$. That can be easily done with segtree. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint n, k, nn;\n\nvector<long long> t, ps;\n\nvoid push(int v, int l, int r){\n\tif (l < r - 1){\n\t\tps[v * 2] += ps[v];\n\t\tps[v * 2 + 1] += ps[v];\n\t}\n\tt[v] += ps[v] * (r - l);\n\tps[v] = 0;\n}\n\nvoid upd(int v, int l, int r, int L, int R, int val){\n\tpush(v, l, r);\n\tif (L >= R)\n\t\treturn;\n\tif (l == L && r == R){\n\t\tps[v] = val;\n\t\tpush(v, l, r);\n\t\treturn;\n\t}\n\tint m = (l + r) / 2;\n\tupd(v * 2, l, m, L, min(m, R), val);\n\tupd(v * 2 + 1, m, r, max(m, L), R, val);\n\tt[v] = t[v * 2] + t[v * 2 + 1];\n}\n\nlong long get(int v, int l, int r, int L, int R){\n\tpush(v, l, r);\n\tif (L >= R)\n\t\treturn 0;\n\tif (l == L && r == R)\n\t\treturn t[v];\n\tint m = (l + r) / 2;\n\tlong long res = get(v * 2, l, m, L, min(m, R)) + get(v * 2 + 1, m, r, max(m, L), R);\n\tt[v] = t[v * 2] + t[v * 2 + 1];\n\treturn res;\n}\n\nint trav(int v, int l, int r, int cnt){\n\tpush(v, l, r);\n\tif (l == r - 1)\n\t\treturn l;\n\tint m = (l + r) / 2;\n\tpush(v * 2, l, m);\n\tpush(v * 2 + 1, m, r);\n\tint res = INF;\n\tif (t[v * 2] >= cnt)\n\t\tres = trav(v * 2, l, m, cnt);\n\telse if (t[v * 2 + 1] >= cnt - t[v * 2])\n\t\tres = trav(v * 2 + 1, m, r, cnt - t[v * 2]);\n\tt[v] = t[v * 2] + t[v * 2 + 1];\n\treturn res;\n}\n\nint main() {\n\tscanf(\"%d%d\", &n, &k);\n\tvector<int> a(n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tsort(a.begin(), a.end(), greater<int>());\n\tnn = a[0] + 500;\n\tt.resize(4 * nn);\n\tps.resize(4 * nn);\n\tupd(1, 0, nn, 0, 1, 1);\n\tint fst = 0;\n\tint ans = INF;\n\tforn(i, n){\n\t\twhile (get(1, 0, nn, 0, fst + 1) == 0) ++fst;\n\t\tupd(1, 0, nn, fst, fst + 1, -1);\n\t\tupd(1, 0, nn, fst + 2, fst + 2 + (a[i] - 1) / 2, 1);\n\t\tupd(1, 0, nn, fst + 2, fst + 2 + a[i] / 2, 1);\n\t\tans = min(ans, trav(1, 0, nn, k));\n\t}\n\tprintf(\"%d\\n\", ans == INF ? -1 : ans);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1470",
    "index": "A",
    "title": "Strange Birthday Party",
    "statement": "Petya organized a strange birthday party. He invited $n$ friends and assigned an integer $k_i$ to the $i$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $m$ unique presents available, the $j$-th present costs $c_j$ dollars ($1 \\le c_1 \\le c_2 \\le \\ldots \\le c_m$). It's \\textbf{not} allowed to buy a single present more than once.\n\nFor the $i$-th friend Petya can either buy them a present $j \\le k_i$, which costs $c_j$ dollars, or just give them $c_{k_i}$ dollars directly.\n\nHelp Petya determine the minimum total cost of hosting his party.",
    "tutorial": "Let's note that it is beneficial to give cheaper gifts to people with a larger $k_i$ value. Suppose that in the optimal answer a pair of people $A$ and $B$, such that $k_A \\ge k_B$ get gifts with values $a \\ge b$. Then we can give a gift $b$ to a person $A$ and to a person $B$ give a gift $a$ or $min(a, c_{k_B})$ dollars. If $a \\le c_{k_B}$, than we spend the same amount of money. Otherwise, it's a better answer. So the problem can be solved using greedy algorithm. Let's sort guest in order of descending value $k_i$. Than give each person a cheapest gift, or $c_{k_i}$ dollars, if it better. To determinate a cheapest gift, let's store the index of the last purchased gift. Thus, the final asymptotics is $O(m \\log n)$.",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1470",
    "index": "B",
    "title": "Strange Definition",
    "statement": "Let us call two integers $x$ and $y$ adjacent if $\\frac{lcm(x, y)}{gcd(x, y)}$ is a perfect square. For example, $3$ and $12$ are adjacent, but $6$ and $9$ are not.\n\nHere $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$, and $lcm(x, y)$ denotes the least common multiple (LCM) of integers $x$ and $y$.\n\nYou are given an array $a$ of length $n$. Each second the following happens: each element $a_i$ of the array is \\textbf{replaced} by the product of all elements of the array (including itself), that are adjacent to the current value.\n\nLet $d_i$ be the number of adjacent elements to $a_i$ (including $a_i$ itself). The beauty of the array is defined as $\\max_{1 \\le i \\le n} d_i$.\n\nYou are given $q$ queries: each query is described by an integer $w$, and you have to output the beauty of the array after $w$ seconds.",
    "tutorial": "It is well known that $lcm(x, y)=\\frac{x \\cdot y}{gcd(x, y)}$, and it immediately follows that $\\frac{lcm(x, y)}{gcd(x, y)}$ $=$ $\\frac{x \\cdot y}{gcd(x, y)^2}$, which means that numbers $x$ and $y$ are adjacent if and only if $x \\cdot y$ is a perfect square. Let $alpha_x$ be the maximum possible integer such that $p^{alpha_x}$ divides $x$, and $alpha_y$ be the maximum possible integer such that $p^{alpha_y}$ divides $y$. Then $x \\cdot y$ is perfect square if and only if $\\alpha_x + \\alpha_y$ is even, which means $\\alpha_x \\equiv \\alpha_y$ (mod $2$). Let $x =p_1^{\\alpha1} \\cdot \\ldots \\cdot p_k^{\\alpha_k}$. Let's replace it with $p_1^{\\alpha1\\bmod2} \\cdot \\ldots \\cdot p_k^{\\alpha_k\\bmod2}$. After such a replacement two integers are adjacent if and only if they are equal. Let's replace each element of the array and split the numbers into classes of equal numbers. If the number of integers in a single class is even, after a single operation each element from this class will be transformed to $1$, and if the number of integers is odd, the class of the element will remain unchanged. Since the class of integer 1 always remains unchanged, all integers will keep their classes starting from after the first operation. Since $d_i$ denotes the size of the class, the beauty of the array is defined as the size of the maximal class. If $a$ if the size of the maximal class at the beginning of the process, and $b$ - the total number of elements with a class of even size or with the class equal to 1. Then for a query with $w = 0$ the answer is $a$, for a query with $w > 0$ the answer is $max(a, b)$. This solution can easily be implemented with $O(n\\log{A})$ complexity, where $A$ denotes the maximum number in the array.",
    "tags": [
      "bitmasks",
      "graphs",
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1470",
    "index": "C",
    "title": "Strange Shuffle",
    "statement": "This is an interactive problem.\n\n$n$ people sitting in a circle are trying to shuffle a deck of cards. The players are numbered from $1$ to $n$, so that players $i$ and $i+1$ are neighbours (as well as players $1$ and $n$). Each of them has exactly $k$ cards, where $k$ is \\textbf{even}. The left neighbour of a player $i$ is player $i - 1$, and their right neighbour is player $i + 1$ (except for players $1$ and $n$, who are respective neighbours of each other).\n\nEach turn the following happens: if a player has $x$ cards, they give $\\lfloor x / 2 \\rfloor$ to their neighbour on the left and $\\lceil x / 2 \\rceil$ cards to their neighbour on the right. This happens for all players simultaneously.\n\nHowever, one player $p$ is the impostor and they just give all their cards to their neighbour on the right. You know the number of players $n$ and the number of cards $k$ each player has initially, but $p$ is unknown to you. Your task is to determine the value of $p$, by asking questions like \"how many cards does player $q$ have?\" for an index $q$ of your choice. After each question all players will make exactly one move and give their cards to their neighbours. You need to find the impostor by asking no more than $1000$ questions.",
    "tutorial": "Short version: note that, during the first $\\frac{n}{2}$ iterations the number of people with more than $k$ cards, increases. Let's find at least one such person. To do this, let's wait for $\\sqrt{n}$ iterations. After this there is always a continuous segment of length $\\sqrt{n}$ with elements $>k$. To find it, we can split the array into blocks of size $\\sqrt{n}$, ask one element from each block, and find the desired integer $>k$. Then we can use binary search to find the position $p$. In total we need $2 \\sqrt{n} + \\log{n}$ queries. More detailed version: let's use induction to prove that players that are located from the same distance from the player $p$ always have $2k$ cards in total. It is obviously true initially. After one operation, when the array $a$ is transformed to the array $b$, and let's consider a pair of elements located on the same distance from position $p$: $i$ and $j$. Note that, $b_{i} + b_{j} = (\\lceil \\frac{a_{i - 1}}{2} \\rceil + \\lfloor \\frac{a_{i + 1}}{2} \\rfloor) + (\\lceil\\frac{a_{j - 1}}{2} \\rceil + \\lfloor \\frac{a_{j + 1}}{2} \\rfloor) = (\\lceil\\frac{a_{i - 1}}{2} \\rceil + \\lfloor \\frac{a_{j + 1}}{2} \\rfloor) + (\\lfloor \\frac{a_{i + 1}}{2} \\rfloor + \\lceil\\frac{a_{j - 1}}{2} \\rceil) = k + k = 2k$ (excluding the neighbours of $p$). It proves that the player $p$ will always have $k$ cards. Now let's prove that the number of cards that players $p + 1, p + 2, \\ldots, n, 1, \\ldots p - 1$ have is not increasing. Again, if we consider a single step: $b_{i + 1} = \\lceil \\frac{a_i}{2} \\rceil + \\lfloor \\frac {a_{i + 2}}{2} \\rfloor \\ge \\lceil \\frac{a_{i - 1}}{2} \\rceil + \\lfloor \\frac{a_{i + 1}}{2} \\rfloor = b_{i}$. During the first $\\frac{n}{2}$ iterations, the number of elements that are greater than $k$, is increasing. Before $i$-th iteration we have $a_{p + i - 1} > k, a_{p + i} = k$. After $i$-th iteration $a_{p + i} = \\lceil \\frac{a_{p + i - 1}}{2} \\rceil + \\frac{k}{2} > k$, because $k$ is even. The rest of the solution is described in the <<short>> version of the solution above.",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1470",
    "index": "D",
    "title": "Strange Housing",
    "statement": "Students of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold:\n\n- All passages between two houses will be closed, if there are no teachers in both of them. All other passages will stay open.\n- It should be possible to travel between any two houses using the underground passages that are \\textbf{open}.\n- Teachers should not live in houses, directly connected by a passage.\n\nPlease help the organizers to choose the houses where teachers will live to satisfy the safety requirements or determine that it is impossible.",
    "tutorial": "One can prove that the answer always exists if the graph is connected, and the algorithm proves it. Let us paint all vertices with black and white colors. Let us pick any vertex and paint it black, and let us paint all its neighbours with white. Then let's pick any uncoloured vertex that is connected to a white one, paint it black, and paint all its neighbours white. We continue this process until there are no uncoloured vertices left. We claim that the set of black vertices is the answer. We are never painting two adjacent vertices black, since we colour all their neighbours with white. It is also true that the set of already coloured vertices is always connected if we keep only the edges adjacent to black vertices: it is true initially, and whenever we paint a vertex white, it is connected to a black one directly, and when we paint a vertex black, one of its edges goes to a white one coloured on the previous steps (that is how we pick the vertex to paint it white).",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graph matchings",
      "graphs",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1470",
    "index": "E",
    "title": "Strange Permutation",
    "statement": "Alice had a permutation $p_1, p_2, \\ldots, p_n$. Unfortunately, the permutation looked very boring, so she decided to change it and choose some \\textbf{non-overlapping} subranges of this permutation and reverse them. The cost of reversing a single subrange $[l, r]$ (elements from position $l$ to position $r$, inclusive) is equal to $r - l$, and the cost of the operation is the sum of costs of reversing individual subranges. Alice had an integer $c$ in mind, so she only considered operations that cost no more than $c$.\n\nThen she got really bored, and decided to write down all the permutations that she could possibly obtain by performing exactly one operation on the initial permutation. Of course, Alice is very smart, so she wrote down each obtainable permutation exactly once (no matter in how many ways it can be obtained), and of course the list was sorted lexicographically.\n\nNow Bob would like to ask Alice some questions about her list. Each question is in the following form: what is the $i$-th number in the $j$-th permutation that Alice wrote down? Since Alice is too bored to answer these questions, she asked you to help her out.",
    "tutorial": "Let call the cost of rotation of segment $[L, R]$ value $R - L$ coins. Let's calculate how many ways can we apply to the array of length $len$ with total cost less or equal to $c$. We can fix $len - 1$ bars between neighbouring elements of array. There is a bijection between ways to select $c$ of them and ways to apply some not overlapping rotations with total cost equals $c$. We can see, that the number of ways is equals ${{len-1}\\choose{0}} + \\dots + {{len-1}\\choose{c}} = ways(len, c)$. Now we can check if the answer to the query is $-1$. It is easy to see, that the answer on query depends only on construction of $j$-th permutation from $p$. This construction can be represented as set of rotations of size not larger than $c$. And the number of possible rotations in this set doesn't exceed $m = nc$. If we can answer this query for each suffix of $p$, we can determine $j$-th permutation: $l$ $c$ $k$ What is the leftmost rotation on the suffix of length $len$, if we have $c$ coins and we want to get $k$-th permutation of this suffix. Let's fix any suffix $p_x, p_{x+1}, \\dots, p_n$. We can build a long array consisting of the leftmost rotations in construction of each permutation of this suffix using not more than $c$ coins. It is easy to see that each rotation will appear on some segment of this array. We can determine the length of this segment: if it was the rotation $[l, r]$, than the length of this segment is $ways(n - r, c - r + l)$. Exactly once happends that there is no leftmost rotation. For $x-1$ (suffix $p_{x-1}, p_x, \\dots, p_n$) relative order of this segments won't change because we will add $p_{x-1}$ to the beginning of each permutation. Only $c$ segments will appear (rotations $[x-1, x], [x-1, x+1], \\dots, [x-1, x+c-1]$). We can show that new segment will appear only in the beginning and in the end (because only their first element isn't equal $p_{x-1}$). We can show that query $l$ $c$ $k$ is equivalent to query $n$ $c$ $k'$ because of the structure of this array. In $\\mathcal{O}(m)$ we can build this array using deque. We should do this for each $c$. Let's answer the queries offline using the following algorithm: Iterate in order of decreasing $c$ (let's call a level set of queries with the same $c$). Sort queries in order of increasing $k$. Using two pointers approach we can move all queries to another level and change them to type $n$ $c$ $k'$. If we will remove queries from each level after answering them, memory will be reduced from $\\mathcal{O}(qc + nc)$ to $\\mathcal{O}(q + nc)$. Total work time: $\\mathcal{O}(sort(q) \\cdot c + nc^2)$. It can be optimized to $\\mathcal{O}(sort(q) + q \\cdot log{n} \\cdot log{c} + nc^2)$ using another sort algorithms. Also there is a solution in $\\mathcal{O}(nc^2 + q \\cdot c \\cdot log(nc))$ and $\\mathcal{O}(nc)$ memory with binary search and slower solutions with different data structures.",
    "tags": [
      "binary search",
      "combinatorics",
      "data structures",
      "dp",
      "graphs",
      "implementation",
      "two pointers"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1470",
    "index": "F",
    "title": "Strange Covering",
    "statement": "You are given $n$ points on a plane.\n\nPlease find the minimum sum of areas of two axis-aligned rectangles, such that each point is contained in at least one of these rectangles.\n\nNote that the chosen rectangles can be degenerate. Rectangle contains all the points that lie inside it or on its boundary.",
    "tutorial": "It is clear that there are only 3 structurally different ways to pick two rectangles optimally: Two rectangles do not intersect: In this case one can iterate over all horizontal / vertical lines, separating those rectangles, find the extremal points in both halfplanes, and pick the rectangles with corners in the extremal points. In this case one can iterate over all horizontal / vertical lines, separating those rectangles, find the extremal points in both halfplanes, and pick the rectangles with corners in the extremal points. Rectangles do intersect, forming a <<cross>>: In this case note that for each of the rectangles at least two sides lie on the boundary of the bounding box of all points: To find such rectangles efficiently, one can iterate over the right boundary of the <<vertical>> rectangle. Let $L_d$ - be the lowest $y$ coordinate of a point to the left of left boundary of the <<vertical>> rectangle, $L_u$ - the highest $y$ coordinate of a point to the left of the boundary of the <<vertical>> rectangle, and similarly $R_d$ - the lowest $y$-coordinate of a point to the right of the <<vertical>> rectangle, $R_u$ - the highest $y$-coordinate of a point to the right. We can assume that $R_u \\geq L_u$ (this can be guaranteed by picking a prefix in our data structure that we will find later). On such a prefix where $L_d \\geq R_d$ we need to choose the rightmost bound. What remains is a subrange where $L_d \\leq R_d$ and $L_u \\leq R_u$. If we fix two bounds of a rectangle $L$ and $R$, their total area equals $(R_u - L_d) \\cdot H + (R-L) \\cdot W$, where $W$ is the height of the bounding box, and $H$ - its length. Rewriting $(R_u - L_d) \\cdot H + (R-L) \\cdot W = (R \\cdot W + R_u \\cdot H) - (L \\cdot W + L_d \\cdot H)$ one can see that the optimal $L$ can be chosen with a segment tree. In this case note that for each of the rectangles at least two sides lie on the boundary of the bounding box of all points: To find such rectangles efficiently, one can iterate over the right boundary of the <<vertical>> rectangle. Let $L_d$ - be the lowest $y$ coordinate of a point to the left of left boundary of the <<vertical>> rectangle, $L_u$ - the highest $y$ coordinate of a point to the left of the boundary of the <<vertical>> rectangle, and similarly $R_d$ - the lowest $y$-coordinate of a point to the right of the <<vertical>> rectangle, $R_u$ - the highest $y$-coordinate of a point to the right. We can assume that $R_u \\geq L_u$ (this can be guaranteed by picking a prefix in our data structure that we will find later). On such a prefix where $L_d \\geq R_d$ we need to choose the rightmost bound. What remains is a subrange where $L_d \\leq R_d$ and $L_u \\leq R_u$. If we fix two bounds of a rectangle $L$ and $R$, their total area equals $(R_u - L_d) \\cdot H + (R-L) \\cdot W$, where $W$ is the height of the bounding box, and $H$ - its length. Rewriting $(R_u - L_d) \\cdot H + (R-L) \\cdot W = (R \\cdot W + R_u \\cdot H) - (L \\cdot W + L_d \\cdot H)$ one can see that the optimal $L$ can be chosen with a segment tree. Two rectangles intersect in a such a way so that one of the vertices lies inside or on the boundary of the other one: In this case one of the corners of each rectangle coincides with a corner of the bounding box. Let's call such a corner interesting. If we fix the interesting vertex of one of the rectangles, the remaining rectangle can be uniquely determined. Looking at the formulas, it is clear that once we know the $x$-coordinate of an interesting corner of the rectangles, one can choose the $y$-coordinate of the interesting corner by answering a query in form <<minimize $a \\cdot x+b \\cdot y$>>, where $(a, b)$ - one of the pairs belonging to a fixed precomputed set, and $(x,y)$ is a query. Dividing the expression by $x$ one can get $a+b \\cdot \\frac{y}{x}$ - a standard query that can be solved using convex hull trick. The only piece remaining is to guarantee that the chosen rectangles intersect. To achieve this once we fixed $x$ we only need to consider a continuous segment of $y$s, so we need to find the maximal value of a subrange of linear functions, which can be implemented in offline manner in $O(n \\log n)$ time with a segment tree of convex stacks The overall complexity of this solution is $O(n \\log n)$. In this case one of the corners of each rectangle coincides with a corner of the bounding box. Let's call such a corner interesting. If we fix the interesting vertex of one of the rectangles, the remaining rectangle can be uniquely determined. Looking at the formulas, it is clear that once we know the $x$-coordinate of an interesting corner of the rectangles, one can choose the $y$-coordinate of the interesting corner by answering a query in form <<minimize $a \\cdot x+b \\cdot y$>>, where $(a, b)$ - one of the pairs belonging to a fixed precomputed set, and $(x,y)$ is a query. Dividing the expression by $x$ one can get $a+b \\cdot \\frac{y}{x}$ - a standard query that can be solved using convex hull trick. The only piece remaining is to guarantee that the chosen rectangles intersect. To achieve this once we fixed $x$ we only need to consider a continuous segment of $y$s, so we need to find the maximal value of a subrange of linear functions, which can be implemented in offline manner in $O(n \\log n)$ time with a segment tree of convex stacks The overall complexity of this solution is $O(n \\log n)$.",
    "tags": [
      "divide and conquer"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1471",
    "index": "A",
    "title": "Strange Partition",
    "statement": "You are given an array $a$ of length $n$, and an integer $x$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $[3, 6, 9]$, in a single operation one can replace the last two elements by their sum, yielding an array $[3, 15]$, or replace the first two elements to get an array $[9, 9]$. Note that the size of the array decreases after each operation.\n\nThe beauty of an array $b=[b_1, \\ldots, b_k]$ is defined as $\\sum_{i=1}^k \\left\\lceil \\frac{b_i}{x} \\right\\rceil$, which means that we divide each element by $x$, round it up to the nearest integer, and sum up the resulting values. For example, if $x = 3$, and the array is $[4, 11, 6]$, the beauty of the array is equal to $\\left\\lceil \\frac{4}{3} \\right\\rceil + \\left\\lceil \\frac{11}{3} \\right\\rceil + \\left\\lceil \\frac{6}{3} \\right\\rceil = 2 + 4 + 2 = 8$.\n\nPlease determine the minimum and the maximum beauty you can get by performing some operations on the original array.",
    "tutorial": "Note that, $\\left\\lceil \\frac{a + b}{x} \\right\\rceil \\leq \\left\\lceil \\frac{a}{x} \\right\\rceil + \\left\\lceil \\frac{b}{x} \\right\\rceil$. It means that the maximal sum is attained if we do not apply any operations, and the minimal one is attained if we replace all the element with a single one, equal to the sum of all elements.",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1471",
    "index": "B",
    "title": "Strange List",
    "statement": "You have given an array $a$ of length $n$ and an integer $x$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $q$. If $q$ is divisible by $x$, the robot adds $x$ copies of the integer $\\frac{q}{x}$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $q$ is not divisible by $x$, the robot shuts down.\n\nPlease determine the sum of all values of the array at the end of the process.",
    "tutorial": "Solution 1. Let's represent each element $a_{i}$ as $x^{b_{i}} \\cdot c_{i}$, where $b_{i}$ is the maximal possible. Let's take minimum over all values $b_{i}$, and let's assume it's attained at position $j$. The robot will add each element to the array $b_{j}$ times (element at position $j$ will be the first one, which will stop being divisible by $x$). However, we should not forget about the prefix before position $j$: each of those number is divisible by a higher power of $x$, and this prefix will count towards the total sum. The final answer is $(b_{j} + 1) \\cdot \\sum_{i=1}^{n}a_{i} + \\sum_{i=1}^{j-1}a_{i}$ In this solution we divide each number $a_{i}$ by $x$ to generate the array $b_{1}, b_{2}, \\ldots, b_{n}$, and then it takes $O(n)$ to compute both sums. The final complexity of the solution is $O(n \\log A)$, where $A$ denotes the maximum possible element of the array. Solution 2. Let's maintain the list of pairs $\\{ a_{i}, cnt_{i} \\}$ - it indicates a range of $cnt_{i}$ elements equal to $a_{i}$. Then we can easily implement the operation performed by the robot: if we consider pair $\\{ a, cnt \\}$, we either append the array with a pair $\\{ \\frac{a}{x}, cnt \\cdot x \\}$, or terminate the process. The answer to the problem equals to sum of values $a_{i} \\cdot cnt_{i}$. Each number $a_{i}$ will be copied to the end of the array at most $O(\\log A)$ times, since each time $a_{i}$ is divided by $x$. Since there are $n$ elements in the array initially, the total complexity of this solution is $O(n \\log A)$.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1472",
    "index": "A",
    "title": "Cards for Friends",
    "statement": "For the New Year, Polycarp decided to send postcards to all his $n$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $w \\times h$, which can be cut into pieces.\n\nPolycarp can cut any sheet of paper $w \\times h$ that he has in only two cases:\n\n- If $w$ is even, then he can cut the sheet in half and get two sheets of size $\\frac{w}{2} \\times h$;\n- If $h$ is even, then he can cut the sheet in half and get two sheets of size $w \\times \\frac{h}{2}$;\n\nIf $w$ and $h$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above.\n\nAfter cutting a sheet of paper, the total number of sheets of paper is increased by $1$.\n\nHelp Polycarp to find out if he can cut his sheet of size $w \\times h$ at into $n$ or more pieces, using only the rules described above.",
    "tutorial": "If we cut the sheet in width, we will reduce its width by half, without changing the height. Therefore, the width and height dimensions do not affect each other in any way. Let's calculate the maximum number of sheets that we can get by cutting. Let's say that initially this number is $1$. Let's cut the sheet in width. Then the sheets number will become $2$, but they will be the same. If we can cut the sheet again, it is more profitable to cut all the sheets we have, because this way we will get more new sheets and their size will still be the same. So we can maintain the current number of identical sheets and as long as either the width or height is divided by $2$, divide it, and multiply the number of sheets by two.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n  int w, h, n;\n  cin >> w >> h >> n;\n  int res = 1;\n  while (w % 2 == 0) {\n    w /= 2;\n    res *= 2;\n  }\n  while (h % 2 == 0) {\n    h /= 2;\n    res *= 2;\n  }\n  cout << (res >= n ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1472",
    "index": "B",
    "title": "Fair Division",
    "statement": "Alice and Bob received $n$ candies from their parents. \\textbf{Each candy weighs either 1 gram or 2 grams}. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.\n\nCheck if they can do that.\n\nNote that candies \\textbf{are not allowed to be cut in half}.",
    "tutorial": "If the sum of all the weights is not divisible by two, then it is impossible to divide the candies between two people. If the sum is divisible, then let's count the number of candies with a weight of $1$ and $2$. Now, if we can find a way to collect half the sum with some candies, then these candies can be given to Alice, and all the rest can be given to Bob. Simple solution - let's iterate through how many candies of weight $2$ we will give to Alice, then the remaining weight should be filled by candies of weight $1$. If there are enough of them, then we have found a way of division. In fact, if the sum is even and there are at least two candies with weight $1$ (there can't be one candy), then the answer is always \"YES\" (we can collect the weight as close to half as possible with weight $2$ and then add weight $1$). If there are no candies with weight $1$, then you need to check whether $n$ is even (since all the candies have the same weight, you just need to divide them in half).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  int cnt1 = 0, cnt2 = 0;\n  for (int i = 0; i < n; i++) {\n    int c;\n    cin >> c;\n    if (c == 1) {\n      cnt1++;\n    } else {\n      cnt2++;\n    }\n  }\n  if ((cnt1 + 2 * cnt2) % 2 != 0) {\n    cout << \"NO\\n\";\n  } else {\n    int sum = (cnt1 + 2 * cnt2) / 2;\n    if (sum % 2 == 0 || (sum % 2 == 1 && cnt1 != 0)) {\n      cout << \"YES\\n\";\n    } else {\n      cout << \"NO\\n\";\n    }\n  }\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1472",
    "index": "C",
    "title": "Long Jumps",
    "statement": "Polycarp found under the Christmas tree an array $a$ of $n$ elements and instructions for playing with it:\n\n- At first, choose index $i$ ($1 \\leq i \\leq n$) — starting position in the array. Put the chip at the index $i$ (on the value $a_i$).\n- While $i \\leq n$, add $a_i$ to your score and move the chip $a_i$ positions to the right (i.e. replace $i$ with $i + a_i$).\n- If $i > n$, then Polycarp ends the game.\n\nFor example, if $n = 5$ and $a = [7, 3, 1, 2, 3]$, then the following game options are possible:\n\n- Polycarp chooses $i = 1$. Game process: $i = 1 \\overset{+7}{\\longrightarrow} 8$. The score of the game is: $a_1 = 7$.\n- Polycarp chooses $i = 2$. Game process: $i = 2 \\overset{+3}{\\longrightarrow} 5 \\overset{+3}{\\longrightarrow} 8$. The score of the game is: $a_2 + a_5 = 6$.\n- Polycarp chooses $i = 3$. Game process: $i = 3 \\overset{+1}{\\longrightarrow} 4 \\overset{+2}{\\longrightarrow} 6$. The score of the game is: $a_3 + a_4 = 3$.\n- Polycarp chooses $i = 4$. Game process: $i = 4 \\overset{+2}{\\longrightarrow} 6$. The score of the game is: $a_4 = 2$.\n- Polycarp chooses $i = 5$. Game process: $i = 5 \\overset{+3}{\\longrightarrow} 8$. The score of the game is: $a_5 = 3$.\n\nHelp Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.",
    "tutorial": "Let $score(i)$ be the result of the game if we chose $i$ as the starting position. Let's look at some starting position $j$. After making a move from it, we will get $a[j]$ points and move to the position $j + a[j]$, continuing the same game. This means that by choosing the position $j$, we can assume that we will get a result $a[j]$ more than if we chose the position $j + a[j]$. Formally, $score(j) = score(j + a[j]) + a[j]$. Let's calculate all the results of $score$ and store them in an array. Let's start iterating through the positions from the end, then being in the position $i$ we will know $score(j)$ for all $j > i$. Using the formula above, we can calculate $score(i)$ in one operation. It remains only to choose the maximum of all such values.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  for (int &x : a) {\n    cin >> x;\n  }\n\n  vector<int> dp(n);\n  for (int i = n - 1; i >= 0; i--) {\n    dp[i] = a[i];\n    int j = i + a[i];\n    if (j < n) {\n      dp[i] += dp[j];\n    }\n  }\n  cout << *max_element(dp.begin(), dp.end()) << endl;\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1472",
    "index": "D",
    "title": "Even-Odd Game",
    "statement": "During their New Year holidays, Alice and Bob play the following game using an array $a$ of $n$ integers:\n\n- Players take turns, Alice moves first.\n- Each turn a player chooses any element and removes it from the array.\n- If Alice chooses \\textbf{even value}, then she adds it to her score. If the chosen value is odd, Alice's score does not change.\n- Similarly, if Bob chooses \\textbf{odd value}, then he adds it to his score. If the chosen value is even, then Bob's score does not change.\n\nIf there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared.\n\nFor example, if $n = 4$ and $a = [5, 2, 7, 3]$, then the game could go as follows (there are other options):\n\n- On the first move, Alice chooses $2$ and get two points. Her score is now $2$. The array $a$ is now $[5, 7, 3]$.\n- On the second move, Bob chooses $5$ and get five points. His score is now $5$. The array $a$ is now $[7, 3]$.\n- On the third move, Alice chooses $7$ and get no points. Her score is now $2$. The array $a$ is now $[3]$.\n- On the last move, Bob chooses $3$ and get three points. His score is now $8$. The array $a$ is empty now.\n- Since Bob has more points at the end of the game, he is the winner.\n\nYou want to find out who will win if both players play optimally. \\textbf{Note that there may be duplicate numbers in the array}.",
    "tutorial": "Let's look at an analogy for this game. If Alice takes an even number $x$, she adds $x$ points to the global result, otherwise $0$; If Bob takes an odd number $x$, he adds $-x$ points to the global result, otherwise $0$; Alice wants to maximize the global result and Bob wants to minimize it. Obviously, this game is completely equivalent to the conditional game. Suppose now it's Alice's move. Let's look at some number $x$ in the array. If this number is even, then taking it will add $x$ points, and giving it to Bob will add $0$ points. If this number is odd, then taking it will add $0$ points, and giving it to Bob will add $-x$ points. So taking the number $x$ by $x$ points is more profitable than not taking it (regardless of the parity). To maximize the result, Alice should always take the maximum number in the array. Similar reasoning can be done for Bob. In the task, it was necessary to sort the array and simulate the game.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> v(n);\n  for (int &e : v) {\n    cin >> e;\n  }\n  sort(v.rbegin(), v.rend());\n  ll ans = 0;\n  for (int i = 0; i < n; i++) {\n    if (i % 2 == 0) {\n      if (v[i] % 2 == 0) {\n        ans += v[i];\n      }\n    } else {\n      if (v[i] % 2 == 1) {\n        ans -= v[i];\n      }\n    }\n  }\n  if (ans == 0) {\n    cout << \"Tie\\n\";\n  } else if (ans > 0) {\n    cout << \"Alice\\n\";\n  } else {\n    cout << \"Bob\\n\";\n  }\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "dp",
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1472",
    "index": "E",
    "title": "Correct Placement",
    "statement": "Polycarp has invited $n$ friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side.\n\nEach friend is characterized by two values $h_i$ (their height) and $w_i$ (their width). On the photo the $i$-th friend will occupy a rectangle $h_i \\times w_i$ (if they are standing) or $w_i \\times h_i$ (if they are lying on the side).\n\nThe $j$-th friend can be placed in front of the $i$-th friend on the photo if his rectangle is lower and narrower than the rectangle of the $i$-th friend. Formally, \\textbf{at least one} of the following conditions must be fulfilled:\n\n- $h_j < h_i$ \\textbf{and} $w_j < w_i$ (both friends are standing or both are lying);\n- $w_j < h_i$ \\textbf{and} $h_j < w_i$ (one of the friends is standing and the other is lying).\n\nFor example, if $n = 3$, $h=[3,5,3]$ and $w=[4,4,3]$, then:\n\n- the first friend can be placed in front of the second: $w_1 < h_2$ and $h_1 < w_2$ (one of the them is standing and the other one is lying);\n- the third friend can be placed in front of the second: $h_3 < h_2$ and $w_3 < w_2$ (both friends are standing or both are lying).\n\nIn other cases, the person in the foreground will overlap the person in the background.\n\nHelp Polycarp for each $i$ find any $j$, such that the $j$-th friend can be located in front of the $i$-th friend (i.e. at least one of the conditions above is fulfilled).\n\nPlease note that you do not need to find the arrangement of all people for a group photo. You just need to find for each friend $i$ any other friend $j$ who can be located in front of him. Think about it as you need to solve $n$ separate independent subproblems.",
    "tutorial": "Let's sort all people by their height in descending order. Now let's go through all the people and look for the position of the person in the sorted array, the height of which is strictly less than ours (for example, by binary search). Obviously, only those people who are in the sorted array later than the found person can stand in front of us (all of them have a height strictly less than ours). Among all these people, it is more profitable for us to take a person with minimum width. In order to find such a person quickly, we can find a person with the minimum width for each suffix of the sorted array. To handle a situation where a person is lying down, we need to swap the width and height and repeat the algorithm above.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int, int>;\n\nstruct man {\n  int h, w, id;\n};\n\nbool operator<(const man &a, const man &b) {\n  return tie(a.h, a.w, a.id) < tie(b.h, b.w, b.id);\n}\n\nstruct my_min {\n  pii mn1, mn2;\n};\n\nvector<pair<int, my_min>> createPrefMins(const vector<man>& a) {\n  vector<pair<int, my_min>> prefMin;\n  my_min curMin{pii(INT_MAX, -1), pii(INT_MAX, -1)};\n  for (auto x : a) {\n    if (x.w < curMin.mn1.first) {\n      curMin.mn2 = curMin.mn1;\n      curMin.mn1 = pii(x.w, x.id);\n    } else {\n      curMin.mn2 = min(curMin.mn2, pii(x.w, x.id));\n    }\n    prefMin.emplace_back(x.h, curMin);\n  }\n  return prefMin;\n}\n\nint findAny(const vector<pair<int, my_min>> &mins, int h, int w, int id) {\n  int l = -1, r = (int) mins.size();\n  while (r - l > 1) {\n    int m = (l + r) / 2;\n    if (mins[m].first < h) {\n      l = m;\n    } else {\n      r = m;\n    }\n  }\n  if (l == -1) {\n    return -1;\n  }\n\n  auto mn1 = mins[l].second.mn1;\n  auto mn2 = mins[l].second.mn2;\n  if (mn1.second != id) {\n    return mn1.first < w ? mn1.second + 1 : -1;\n  }\n  return mn2.first < w ? mn2.second + 1 : -1;\n}\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<man> hor, ver;\n  vector<pii> a;\n  for (int i = 0; i < n; i++) {\n    int h, w;\n    cin >> h >> w;\n    hor.push_back({h, w, i});\n    ver.push_back({w, h, i});\n    a.emplace_back(h, w);\n  }\n\n  sort(hor.begin(), hor.end());\n  sort(ver.begin(), ver.end());\n\n  auto horMins = createPrefMins(hor);\n  auto verMins = createPrefMins(ver);\n\n  for (int i = 0; i < n; i++) {\n    auto[h, w] = a[i];\n    int id = findAny(horMins, h, w, i);\n    if (id == -1) {\n      id = findAny(verMins, h, w, i);\n    }\n    cout << id << \" \";\n  }\n  cout << endl;\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1472",
    "index": "F",
    "title": "New Year's Puzzle",
    "statement": "Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.\n\nPolycarp got the following problem: given a grid strip of size $2 \\times n$, some cells of it are blocked. You need to check if it is possible to tile all free cells using the $2 \\times 1$ and $1 \\times 2$ tiles (dominoes).\n\nFor example, if $n = 5$ and the strip looks like this (black cells are blocked):\n\nThen it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).\n\nAnd if $n = 3$ and the strip looks like this:\n\nIt is impossible to tile free cells.\n\nPolycarp easily solved this task and received his New Year's gift. Can you solve it?",
    "tutorial": "If the first column is empty, we can always cover it with a vertical tile: if the next column is also empty, then we will have to put either two vertical or two horizontal tiles, but they are obtained from each other by rotating; if the next column contains at least one blocked cell, then we have no other options but to cover the column with a vertical board. If the first column is fully blocked, then we can just skip it. Remove such columns from the beginning, reducing the problem. Now the first column contains one empty and one blocked cell. Obviously, in place of an empty cell, we will have to place a horizontal tile. If this did not work, then the tiling does not exist. Otherwise there are two cases: if the next column is empty, it will turn into a column with one occupied cell. Then we continue to put horizontal tiles; if the next column contains one blocked cell, then it becomes fully blocked and we return to the first step. It turns out the following greedy algorithm, we sort all columns with at least one cell blocked (there are no more than $m$ such columns) by number. Now, if we see a column with one occupied cell, then the next one must also be with one occupied cell (we skipped the empty columns), but this cell must have a different color in the chess coloring (so that we can tile the space between them with horizontal boards. This check is easy to do after sorting the columns.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n  int n, m;\n  cin >> n >> m;\n  map<int, int> v;\n  for (int i = 0; i < m; i++) {\n    int x, y;\n    cin >> x >> y;\n    v[y] |= (1 << (x - 1));\n  }\n  const int FULL = 3;\n  v[2e9] = FULL;\n  int hasLast = 0, lastColor = 0;\n  for (auto[x, mask] : v) {\n    if (mask != FULL && hasLast) {\n      int color = (x + mask) % 2;\n      if (lastColor == color) {\n        cout << \"NO\\n\";\n        return;\n      } else {\n        hasLast = false;\n      }\n    } else if (mask == FULL && hasLast) {\n        cout << \"NO\\n\";\n        return;\n    } else if (mask != FULL) {\n      lastColor = (x + mask) % 2;\n      hasLast = true;\n    }\n  }\n  cout << \"YES\\n\";\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "graph matchings",
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1472",
    "index": "G",
    "title": "Moving to the Capital",
    "statement": "There are $n$ cities in Berland. The city numbered $1$ is the capital. Some pairs of cities are connected by a \\textbf{one-way} road of length 1.\n\nBefore the trip, Polycarp for each city found out the value of $d_i$ — the shortest distance from the capital (the $1$-st city) to the $i$-th city.\n\nPolycarp begins his journey in the city with number $s$ and, being in the $i$-th city, chooses one of the following actions:\n\n- Travel from the $i$-th city to the $j$-th city if there is a road from the $i$-th city to the $j$-th and $d_i < d_j$;\n- Travel from the $i$-th city to the $j$-th city if there is a road from the $i$-th city to the $j$-th and $d_i \\geq d_j$;\n- Stop traveling.\n\nSince the government of Berland does not want all people to come to the capital, so Polycarp \\textbf{no more than once} can take the second action from the list. in other words, he can perform the second action $0$ or $1$ time during his journey. Polycarp, on the other hand, wants to be as close to the capital as possible.\n\nFor example, if $n = 6$ and the cities are connected, as in the picture above, then Polycarp could have made the following travels (not all possible options):\n\n- $2 \\rightarrow 5 \\rightarrow 1 \\rightarrow 2 \\rightarrow 5$;\n- $3 \\rightarrow 6 \\rightarrow 2$;\n- $1 \\rightarrow 3 \\rightarrow 6 \\rightarrow 2 \\rightarrow 5$.\n\nPolycarp wants for each starting city $i$ to find out how close he can get to the capital. More formally: he wants to find the minimal value of $d_j$ that Polycarp can get from the city $i$ to the city $j$ according to the rules described above.",
    "tutorial": "Find the distances to all vertices and construct a new graph that has only edges that goes from a vertex with a smaller distance to a vertex with a larger distance. Such a graph cannot contain cycles. Next, you need to run a dynamic programming similar to finding bridges in an undirected graph. First, we write the minimum distance from each vertex to the capital using no more than one edge. This distance is either equal to the distance from the capital to the vertex itself, or the distance to the vertex connected to us by one of the remote edges. We can't go through more than one remote edge. The real answer for a vertex $v$ is the minimum of such values in all vertices reachable from $v$ in the new graph. Since the new graph is acyclic, we can calculate the answer using dynamic programming and a depth-first search started from the capital.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<int> calcDist(vector<vector<int>> const &g) {\n  vector<int> dist(g.size(), -1);\n  dist[1] = 0;\n  queue<int> pq;\n  pq.push(1);\n  while (!pq.empty()) {\n    int u = pq.front();\n    pq.pop();\n    for (int v : g[u]) {\n      if (dist[v] == -1) {\n        dist[v] = dist[u] + 1;\n        pq.push(v);\n      }\n    }\n  }\n\n  return dist;\n}\n\nvoid dfs(int u, vector<vector<int>> const &g, vector<int> const &dist, vector<int> &dp, vector<bool> &used) {\n  used[u] = true;\n  dp[u] = dist[u];\n  for (int v : g[u]) {\n    if (!used[v] && dist[u] < dist[v]) {\n      dfs(v, g, dist, dp, used);\n    }\n\n    if (dist[u] < dist[v]) {\n      dp[u] = min(dp[u], dp[v]);\n    } else {\n      dp[u] = min(dp[u], dist[v]);\n    }\n  }\n}\n\nvoid solve() {\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> g(n + 1);\n  for (int i = 0; i < m; i++) {\n    int u, v;\n    cin >> u >> v;\n    g[u].push_back(v);\n  }\n\n  vector<int> dist = calcDist(g);\n  vector<int> dp(n + 1);\n  vector<bool> used(n + 1);\n  dfs(1, g, dist, dp, used);\n  for (int i = 1; i <= n; i++) {\n    cout << dp[i] << \" \";\n  }\n  cout << endl;\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1473",
    "index": "A",
    "title": "Replacing Elements",
    "statement": "You have an array $a_1, a_2, \\dots, a_n$. All $a_i$ are positive integers.\n\nIn one step you can choose three distinct indices $i$, $j$, and $k$ ($i \\neq j$; $i \\neq k$; $j \\neq k$) and assign the sum of $a_j$ and $a_k$ to $a_i$, i. e. make $a_i = a_j + a_k$.\n\nCan you make all $a_i$ lower or equal to $d$ using the operation above any number of times (possibly, zero)?",
    "tutorial": "Let's note that since all $a_i$ are positive, any $a_i + a_j > \\max(a_i, a_j)$. It means that we can't make the first and second minimums lower than they already are: suppose the first and second minimums are $mn_1$ and $mn_2$, if we choose any other element to replace, we can't make it less than $mn_1 + mn_2$ and if we choose to replace $mn_1$ or $mn_2$ we will only make them bigger. As a result, it means that we can choose for each element either not to change it or make it equal to $mn_1 + mn_2$. So, to be able to make all elements $\\le d$ we need just check that either $mn_1 + mn_2 \\le d$ or maximum $a_i \\le d$. We can do it, for example, by sorting our array $a$ in increasing order and checking that either $a_1 + a_2 \\le d$ or $a_n \\le d$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tc;\n  cin >> tc;\n  while (tc--) {\n    int n, d;\n    cin >> n >> d;\n    vector<int> a(n);\n    for (int& x : a) cin >> x;\n    sort(a.begin(), a.end());\n    cout << (a.back() <= d || a[0] + a[1] <= d ? \"YES\" : \"NO\") << endl;\n  }\n}",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1473",
    "index": "B",
    "title": "String LCM",
    "statement": "Let's define a multiplication operation between a string $a$ and a positive integer $x$: $a \\cdot x$ is the string that is a result of writing $x$ copies of $a$ one after another. For example, \"abc\" $\\cdot~2~=$ \"abcabc\", \"a\" $\\cdot~5~=$ \"aaaaa\".\n\nA string $a$ is divisible by another string $b$ if there exists an integer $x$ such that $b \\cdot x = a$. For example, \"abababab\" is divisible by \"ab\", but is not divisible by \"ababab\" or \"aa\".\n\nLCM of two strings $s$ and $t$ (defined as $LCM(s, t)$) is the shortest non-empty string that is divisible by both $s$ and $t$.\n\nYou are given two strings $s$ and $t$. Find $LCM(s, t)$ or report that it does not exist. It can be shown that if $LCM(s, t)$ exists, it is unique.",
    "tutorial": "We should notice that if some string $x$ is a multiple of string $y$, then $|x|$ is a multiple of $|y|$. This fact leads us to the conclusion that $|LCM(s, t)|$ should be a common multiple of $|s|$ and $|t|$. Since we want to minimize the length of the string $LCM(s, t)$, then its length is $LCM(|s|, |t|)$. So we have to check that $\\frac{LCM(|s|, |t|)}{|s|}$ copies of the string $s$ equal to $\\frac{LCM(|s|, |t|)}{|t|}$ copies of the string $t$. If such strings are equal, print them, otherwise, there is no solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  auto mul = [](string s, int k) -> string {\n    string res = \"\";\n    while (k--) res += s;\n    return res;\n  };\n  \n  int tc;\n  cin >> tc;\n  while (tc--) {\n    string s, t;\n    cin >> s >> t;\n    int n = s.length(), m = t.length();\n    int g = __gcd(n, m);\n    if (mul(s, m / g) == mul(t, n / g))\n      cout << mul(s, m / g) << endl;\n    else\n      cout << \"-1\" << endl;\n  }\n}",
    "tags": [
      "brute force",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1473",
    "index": "C",
    "title": "No More Inversions",
    "statement": "You have a sequence $a$ with $n$ elements $1, 2, 3, \\dots, k - 1, k, k - 1, k - 2, \\dots, k - (n - k)$ ($k \\le n < 2k$).\n\nLet's call as inversion in $a$ a pair of indices $i < j$ such that $a[i] > a[j]$.\n\nSuppose, you have some permutation $p$ of size $k$ and you build a sequence $b$ of size $n$ in the following manner: $b[i] = p[a[i]]$.\n\nYour goal is to find such permutation $p$ that the total number of inversions in $b$ doesn't exceed the total number of inversions in $a$, and $b$ is lexicographically maximum.\n\nSmall reminder: the sequence of $k$ integers is called a permutation if it contains all integers from $1$ to $k$ exactly once.\n\nAnother small reminder: a sequence $s$ is lexicographically smaller than another sequence $t$, if either $s$ is a prefix of $t$, or for the first $i$ such that $s_i \\ne t_i$, $s_i < t_i$ holds (in the first position that these sequences are different, $s$ has smaller number than $t$).",
    "tutorial": "At first, let's look at sequence $s$: $s_1, s_2, \\dots, s_{p - 1}, s_{p}, s_{p - 1}, \\dots s_2, s_1$. Let's prove that the number of inversions in $s$ is the same regardless of what $s_i$ are (the only condition is that $s_i$ should be distinct). Let's group all elements $s_i$ by their value - there will be $1$ or $2$ elements in each group. Then we can take any two groups with values $x$ and $y$ and calculate the number of inversions between elements in these groups. It's easy to note that construction will always be like $\\dots x, \\dots, y, \\dots, y, \\dots, x \\dots$ (or $\\dots x, \\dots, y, \\dots, x \\dots$) and regardless of $x > y$ or $x < y$ in both cases there will be exactly two inversions between groups equal to $x$ and to $y$ (or one inversion in the second case). So the total number of inversion will be equal to $2 \\frac{(p - 1)(p - 2)}{2} + (p - 1) = (p - 1)^2$. Now we can split sequences $a$ and $b$ into two parts. Let $m = n - k$, then the first part is elements from segment $[1, k - m - 1]$ and the second is from $[k - m, k + m]$. Note that the second parts both in $a$ and $b$ are exactly the sequence $s$ described above. The total number of inversions is equal to the sum of inversions in the first part, in the second part, and the inversions with elements from both parts. Note that in $a$ the first and the third components are equal to $0$ and the second component is constant, so in $b$ we must also have $0$ inversions in the first part and $0$ inversion between parts. It means that $b$ must start from $1, 2, \\dots, (k - m - 1)$. But since the number of inversions in the second part is constant we can set the remaining elements the way we want. And since we want to build lexicographically maximum $b$, we should make the second part as $k, k - 1, \\dots, (k - m + 1), (k - m), (k - m + 1), \\dots, k$. In the end, optimal $b$ is $1, 2, \\dots, (k - m - 1), k, (k - 1), \\dots, (k - m + 1), (k - m), (k - m + 1), \\dots, k$. The permutation $p$ to make such $b$ is equal to $1, 2, \\dots, (k - m - 1), k, (k - 1), \\dots, (k - m)$.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (n, k) = readLine()!!.split(' ').map { it.toInt() }\n\n        for (i in 1 until (k - (n - k)))\n            print(\"$i \")\n        for (i in k downTo (k - (n - k)))\n            print(\"$i \")\n        println(\"\")\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1473",
    "index": "D",
    "title": "Program",
    "statement": "You are given a program that consists of $n$ instructions. Initially a single variable $x$ is assigned to $0$. Afterwards, the instructions are of two types:\n\n- increase $x$ by $1$;\n- decrease $x$ by $1$.\n\nYou are given $m$ queries of the following format:\n\n- query $l$ $r$ — how many distinct values is $x$ assigned to if all the instructions between the $l$-th one and the $r$-th one inclusive are ignored and the rest are executed without changing the order?",
    "tutorial": "The value of $x$ always changes by $1$, thus, the set of values of $x$ is always some contiguous segment. The length of such segment can be determined by just its minimum and maximum values. So we have to solve two separate tasks for each query: find the minimum and the maximum value $x$ gets assigned to. I'll describe only the minimum one. This task, however, can as well be split into two parts: minimum value on a prefix before $l$ and on a suffix after $r$. The prefix is easy - it doesn't get changed by a query, so it can be precalculated beforehand. Minimum value on a prefix of length $i$ is minimum of a minimum value on a prefix of length $i-1$ and the current value. The suffix minimum is not that trivial. First, in order to precalculate the minimum value on a suffix of length $i$, we have to learn to prepend an instruction to the suffix of length $i+1$. Consider the graph of values of $x$ over time. What happens to it if the initial value of $x$ is not $0$ but $1$, for example? It just gets shifted by $1$ upwards. That move is actually the same as prepending a '+' instruction. So the minimum value for a suffix of length $i$ is a minimum of a minimum value for a suffix of length $i-1$, increased by the current instruction, and $0$ (the start of the graph). So now we have a minimum value on a suffix after $r$. However, it can't be taken into the answer as it is, because it considers the graph for the suffix to be starting from $0$. And that's not the case. The graph for the suffix starts from the value the prefix ends on. So we can shift the answer for the suffix by the value of $x$ after the prefix. The overall minimum value is just the minimum on a prefix and on a suffix, then. Overall complexity: $O(n + m)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tcin.tie(0);\n\tios_base::sync_with_stdio(0);\n\tint t;\n\tcin >> t;\n\tforn(_, t){\n\t\tint n, m;\n\t\tstring s;\n\t\tcin >> n >> m;\n\t\tcin >> s;\n\t\tvector<int> sul(1, 0), sur(1, 0);\n\t\tfor (int i = n - 1; i >= 0; --i){\n\t\t\tint d = s[i] == '+' ? 1 : -1;\n\t\t\tsul.push_back(min(0, sul.back() + d));\n\t\t\tsur.push_back(max(0, sur.back() + d));\n\t\t}\n\t\treverse(sul.begin(), sul.end());\n\t\treverse(sur.begin(), sur.end());\n\t\tvector<int> prl(1, 0), prr(1, 0), pr(1, 0);\n\t\tforn(i, n){\n\t\t\tint d = s[i] == '+' ? 1 : -1;\n\t\t\tpr.push_back(pr.back() + d);\n\t\t\tprl.push_back(min(prl.back(), pr.back()));\n\t\t\tprr.push_back(max(prr.back(), pr.back()));\n\t\t}\n\t\tforn(i, m){\n\t\t\tint l, r;\n\t\t\tcin >> l >> r;\n\t\t\t--l;\n\t\t\tint l1 = prl[l], r1 = prr[l];\n\t\t\tint l2 = sul[r] + pr[l], r2 = sur[r] + pr[l];\n\t\t\tprintf(\"%d\\n\", max(r1, r2) - min(l1, l2) + 1);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1473",
    "index": "E",
    "title": "Minimum Path",
    "statement": "You are given a weighted undirected connected graph consisting of $n$ vertices and $m$ edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.\n\nLet's define the weight of the path consisting of $k$ edges with indices $e_1, e_2, \\dots, e_k$ as $\\sum\\limits_{i=1}^{k}{w_{e_i}} - \\max\\limits_{i=1}^{k}{w_{e_i}} + \\min\\limits_{i=1}^{k}{w_{e_i}}$, where $w_i$ — weight of the $i$-th edge in the graph.\n\nYour task is to find the minimum weight of the path from the $1$-st vertex to the $i$-th vertex for each $i$ ($2 \\le i \\le n$).",
    "tutorial": "Let's consider a problem where you can subtract the weight of any edge (not only the maximum one) that belong to the current path and similarly add the weight of any edge (not only the minimum one) that belong to the current path. To solve that problem we can build a new graph where the node can be represented as the following triple (node from the initial graph, flag that some edge has been subtracted, flag that some edge has been added). Now we can run Dijkstra's algorithm to find the length of the shortest paths in such a graph. We can notice that on the shortest path, the maximum weight edge was subtracted and the minimum weight edge was added. Let's assume that this is not the case, and an edge of non-maximum weight was subtracted from the path, then we can reduce the length of the path by choosing an edge of maximum weight. But this is not possible, because we considered the shortest path. Similarly, it is proved that the added edge was of minimal weight. Using this fact, it is not difficult to notice that by solving the modified problem, we have solved the original one.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\n\nint n, m;\nvector<pair<int, int>> g[N];\nlong long d[N][2][2];\n\nint main() {\n  scanf(\"%d%d\", &n, &m);\n  for (int i = 0; i < m; i++) {\n    int v, u, w;\n    scanf(\"%d%d%d\", &v, &u, &w);\n    --v; --u;\n    g[v].emplace_back(u, w);\n    g[u].emplace_back(v, w);\n  }\n  \n  for (int i = 0; i < n; i++)\n    for (int j = 0; j < 2; j++)\n      for (int k = 0; k < 2; k++)\n        d[i][j][k] = (long long)1e18;\n\n  d[0][0][0] = 0;\n  set<pair<long long, array<int, 3>>> q;\n  q.insert({0, {0, 0, 0}});\n\n  while (!q.empty()) {\n    auto [v, mx, mn] = q.begin()->second;\n    q.erase(q.begin());\n    for (auto [u, w] : g[v]) {\n      for (int i = 0; i <= 1 - mx; i++) {\n        for (int j = 0; j <= 1 - mn; j++) {\n          if (d[u][mx | i][mn | j] > d[v][mx][mn] + (1 - i + j) * w) {\n            auto it = q.find({d[u][mx | i][mn | j], {u, mx | i, mn | j}});\n            if (it != q.end())\n              q.erase(it);\n            d[u][mx | i][mn | j] = d[v][mx][mn] + (1 - i + j) * w;\n            q.insert({d[u][mx | i][mn | j], {u, mx | i, mn | j}});\n          }\n        }\n      }\n    }\n  }\n\n  for (int i = 1; i < n; i++) {\n    printf(\"%lld \", d[i][1][1]);\n  }\n  puts(\"\");\n}",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1473",
    "index": "F",
    "title": "Strange Set",
    "statement": "\\textbf{Note that the memory limit is unusual.}\n\nYou are given an integer $n$ and two sequences $a_1, a_2, \\dots, a_n$ and $b_1, b_2, \\dots, b_n$.\n\nLet's call a set of integers $S$ such that $S \\subseteq \\{1, 2, 3, \\dots, n\\}$ strange, if, for every element $i$ of $S$, the following condition is met: for every $j \\in [1, i - 1]$, if $a_j$ divides $a_i$, then $j$ is also included in $S$. An empty set is always strange.\n\nThe cost of the set $S$ is $\\sum\\limits_{i \\in S} b_i$. You have to calculate the maximum possible cost of a strange set.",
    "tutorial": "We will model the problem as the minimum cut in a flow network. Build a network as follows: create a source node $s$, a sink node $t$, and a vertex for every number from $1$ to $n$. Let's say that we are going to find the minimum $s$-$t$ cut in this network, and the vertices belonging to the same cut part with $s$ represent the numbers that are taken into the answer. Using the edges of the network, we should model these constraints: taking an element $i$ that depends on another element $j$ should force us to take $j$ as well; taking an element $i$ with $b_i > 0$ should add $b_i$ to our score; taking an element $i$ with $b_i < 0$ should subtract $|b_i|$ from our score. Constraint $1$ can be modeled in the following way: for every pair $(i, j)$ such that element $i$ depends on element $j$ ($i > j$ and $a_i \\bmod a_j = 0$), add a directed edge with infinite capacity from $i$ to $j$. That way, if $i$ is taken and $j$ is not, the value of the cut will be infinite because of this edge, and this cut cannot be minimum. Constraint $2$ is modeled in the following way: for every $i$ such that $b_i > 0$, add a directed edge with capacity $b_i$ from $s$ to $i$. That way, if we don't take some element $i$ with $b_i > 0$ into the answer, $b_i$ is added to the value of the cut. And for constraint $3$, for every $i$ such that $b_i < 0$, add a directed edge with capacity $|b_i|$ from $i$ to $t$. That way, if we take some element $i$ with $b_i < 0$, $|b_i|$ is added to the value of the cut. It's now easy to see that the answer is $\\sum\\limits_{i = 1}^{n} \\max(b_i, 0) - mincut$, since it is exactly the sum of elements that were taken (for positive elements, we add them all up and then subtract the ones that don't belong to the answer; for negative ones, we just subtract those which belong to the answer). To find a minimum cut, just run maximum flow in this network. There's one caveat though. If, for example, all $a_i$ are equal (or many $a_i$ are divisible by many other values in $a$), this network can contain $O(n^2)$ edges. To reduce the number of edges, let's see that if for some index $i$ there exist two equal divisors of $a_i$ to the left of it (let's say that these divisors are $j$ and $k$: $j < k < i$; $a_i \\bmod a_j = 0$; $a_j = a_k$), then we only need to add an edge from $i$ to $k$, because taking $k$ also should force taking $j$ into the answer. So, for every divisor of $a_i$, we are interested in only one closest occurrence of this divisor to the left, and we need to add a directed edge only to this occurrence, and ignore all other occurrences. That way, for every vertex $i$, we add at most $D(a_i)$ edges to other vertices (where $D(a_i)$ is the number of divisors of $a_i$). It can be proven that any maximum flow algorithm that relies on augmenting paths will finish after $O(V)$ iterations in this network, so it won't work longer than $O(VE)$, and both $V$ and $E$ are proportional to $n$, so any maximum flow solution will run in $O(n^2)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntemplate<typename T>\nstruct dinic {\n    struct edge {\n        int u, rev;\n        T cap, flow;\n    };\n    \n    int n, s, t;\n    T flow;\n    vector<int> lst;\n    vector<int> d;\n    vector<vector<edge>> g;\n    \n    T scaling_lim;\n    bool scaling;\n    \n    dinic() {}\n    \n    dinic(int n, int s, int t, bool scaling = false) : n(n), s(s), t(t), scaling(scaling) {\n        g.resize(n);\n        d.resize(n);\n        lst.resize(n);\n        flow = 0;\n    }\n\n    void add_edge(int v, int u, T cap, bool directed = true) {\n        g[v].push_back({u, g[u].size(), cap, 0});\n        g[u].push_back({v, int(g[v].size()) - 1, directed ? 0 : cap, 0});\n    }\n\n    T dfs(int v, T flow) {\n        if (v == t)\n            return flow;\n        if (flow == 0)\n            return 0;\n        T result = 0;\n        for (; lst[v] < g[v].size(); ++lst[v]) {\n            edge& e = g[v][lst[v]];\n            if (d[e.u] != d[v] + 1)\n                continue;\n            T add = dfs(e.u, min(flow, e.cap - e.flow));\n            if (add > 0) {\n                result += add;\n                flow -= add;\n                e.flow += add;\n                g[e.u][e.rev].flow -= add;\n            }\n            if (flow == 0)\n                break;\n        }\n        return result;\n    }\n\n    bool bfs() {\n        fill(d.begin(), d.end(), -1);\n        queue<int> q({s});\n        d[s] = 0;\n        while (!q.empty() && d[t] == -1) {\n            int v = q.front(); q.pop();\n            for (auto& e : g[v]) {\n                if (d[e.u] == -1 && e.cap - e.flow >= scaling_lim) {\n                    q.push(e.u);\n                    d[e.u] = d[v] + 1;\n                }\n            }\n        }\n        return d[t] != -1;\n    }\n\n    T calc() {\n        T max_lim = numeric_limits<T>::max() / 2 + 1;\n        for (scaling_lim = scaling ? max_lim : 1; scaling_lim > 0; scaling_lim >>= 1) {\n            while (bfs()) {\n                fill(lst.begin(), lst.end(), 0);\n                T add;\n                while((add = dfs(s, numeric_limits<T>::max())) > 0)\n                flow += add;\n            }\n        }   \n        return flow;\n    }\n    \n    vector<bool> min_cut() {\n        vector<bool> res(n);\n        for(int i = 0; i < n; i++) \n            res[i] = (d[i] != -1);\n        return res;\n    }\n};\n\nint main() {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n);\n    for(int i = 0; i < n; i++)\n        cin >> a[i];\n    for(int i = 0; i < n; i++)\n        cin >> b[i];\n    int s = n;\n    int t = n + 1;\n    dinic<int> d(n + 2, s, t, true);\n    vector<int> last(101, -1);\n    for(int i = 0; i < n; i++){\n        if(b[i] > 0)\n            d.add_edge(s, i, b[i]);\n        if(b[i] < 0)\n            d.add_edge(i, t, -b[i]);\n        for(int k = 1; k <= 100; k++)\n            if(last[k] != -1 && a[i] % k == 0)\n                d.add_edge(i, last[k], int(1e9));\n        last[a[i]] = i;    \n    }   \n    int sum = 0;\n    for(int i = 0; i < n; i++)\n        sum += max(0, b[i]);\n    cout << sum - d.calc() << endl;\n}",
    "tags": [
      "flows",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1473",
    "index": "G",
    "title": "Tiles",
    "statement": "Consider a road consisting of several rows. Each row is divided into several rectangular tiles, and all tiles in the same row are equal. The first row contains exactly one rectangular tile. Look at the picture below which shows how the tiles are arranged.\n\nThe road is constructed as follows:\n\n- the first row consists of $1$ tile;\n- then $a_1$ rows follow; each of these rows contains $1$ tile greater than the previous row;\n- then $b_1$ rows follow; each of these rows contains $1$ tile less than the previous row;\n- then $a_2$ rows follow; each of these rows contains $1$ tile greater than the previous row;\n- then $b_2$ rows follow; each of these rows contains $1$ tile less than the previous row;\n- ...\n- then $a_n$ rows follow; each of these rows contains $1$ tile greater than the previous row;\n- then $b_n$ rows follow; each of these rows contains $1$ tile less than the previous row.\n\n\\begin{center}\nAn example of the road with $n = 2$, $a_1 = 4$, $b_1 = 2$, $a_2 = 2$, $b_2 = 3$. Rows are arranged from left to right.\n\\end{center}\n\nYou start from the only tile in the first row and want to reach the last row (any tile of it). From your current tile, you can move to any tile in the next row which touches your current tile.\n\nCalculate the number of different paths from the first row to the last row. Since it can be large, print it modulo $998244353$.",
    "tutorial": "The group of the rows where the number of rectangular tiles increases $a$ times and then decreases $b$ times can be represented as a rectangular table, with $a+b+1$ diagonals, where the size of the first diagonal is equal to the number of rectangular tiles before the operations are applied (let their number be $m$), and the size of the last diagonal is $m+a-b$. In such a rectangular table, one can move from the cell $(i, j)$ to the cells $(i+1, j)$ and $(i, j+1)$ (if they exist), which lie on the next diagonal (next row in terms of the original problem). It's a well-known fact that the number of different paths from one cell to another is some binomial coefficient. Let's define $ans_{i,j}$ as the number of paths from the $1$-st row to the $j$-th tile in the ($\\sum\\limits_{k=1}^{i} (a_i+b_i)$)-th row (i.e. row after the $i$-th group of operations). Now we want to find the values of $ans_{i}$ using the values of $ans_{i-1}$ (let its size be $m$). Using the fact described in the first paragraphs we know that $ans_{i, j}$ depends on $ans_{i-1, k}$ with some binomial coefficient. In fact $ans_{i, j} = \\sum\\limits_{k=1}^{m} \\binom{a_i+b_i}{b_i-k+j} ans_{i-1,k}$ for $1 \\le j \\le m + a_i - b_i$. But this solution is too slow. To speed up this solution we have to notice that the given formula is a convolution of $ans_{i-1}$ and some binomial coefficients. So we can use NTT to multiply them in $O(n\\log n)$ instead of $O(n^2)$ time.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)\n#define sz(a) int((a).size())\n\ntemplate<const int &MOD>\nstruct _m_int {\n  int val;\n \n  _m_int(int64_t v = 0) {\n    if (v < 0) v = v % MOD + MOD;\n    if (v >= MOD) v %= MOD;\n    val = int(v);\n  }\n \n  _m_int(uint64_t v) {\n    if (v >= MOD) v %= MOD;\n    val = int(v);\n  }\n \n  _m_int(int v) : _m_int(int64_t(v)) {}\n  _m_int(unsigned v) : _m_int(uint64_t(v)) {}\n \n  static int inv_mod(int a, int m = MOD) {\n    int g = m, r = a, x = 0, y = 1;\n \n    while (r != 0) {\n      int q = g / r;\n      g %= r; swap(g, r);\n      x -= q * y; swap(x, y);\n    }\n \n    return x < 0 ? x + m : x;\n  }\n \n  explicit operator int() const { return val; }\n  explicit operator unsigned() const { return val; }\n  explicit operator int64_t() const { return val; }\n  explicit operator uint64_t() const { return val; }\n  explicit operator double() const { return val; }\n  explicit operator long double() const { return val; }\n \n  _m_int& operator+=(const _m_int &other) {\n    val -= MOD - other.val;\n    if (val < 0) val += MOD;\n    return *this;\n  }\n \n  _m_int& operator-=(const _m_int &other) {\n    val -= other.val;\n    if (val < 0) val += MOD;\n    return *this;\n  }\n \n  static unsigned fast_mod(uint64_t x, unsigned m = MOD) {\n#if !defined(_WIN32) || defined(_WIN64)\n    return unsigned(x % m);\n#endif\n    // Optimized mod for Codeforces 32-bit machines.\n    // x must be less than 2^32 * m for this to work, so that x / m fits in an unsigned 32-bit int.\n    unsigned x_high = unsigned(x >> 32), x_low = unsigned(x);\n    unsigned quot, rem;\n    asm(\"divl %4\\n\"\n      : \"=a\" (quot), \"=d\" (rem)\n      : \"d\" (x_high), \"a\" (x_low), \"r\" (m));\n    return rem;\n  }\n \n  _m_int& operator*=(const _m_int &other) {\n    val = fast_mod(uint64_t(val) * other.val);\n    return *this;\n  }\n \n  _m_int& operator/=(const _m_int &other) {\n    return *this *= other.inv();\n  }\n \n  friend _m_int operator+(const _m_int &a, const _m_int &b) { return _m_int(a) += b; }\n  friend _m_int operator-(const _m_int &a, const _m_int &b) { return _m_int(a) -= b; }\n  friend _m_int operator*(const _m_int &a, const _m_int &b) { return _m_int(a) *= b; }\n  friend _m_int operator/(const _m_int &a, const _m_int &b) { return _m_int(a) /= b; }\n \n  _m_int& operator++() {\n    val = val == MOD - 1 ? 0 : val + 1;\n    return *this;\n  }\n \n  _m_int& operator--() {\n    val = val == 0 ? MOD - 1 : val - 1;\n    return *this;\n  }\n \n  _m_int operator++(int) { _m_int before = *this; ++*this; return before; }\n  _m_int operator--(int) { _m_int before = *this; --*this; return before; }\n \n  _m_int operator-() const {\n    return val == 0 ? 0 : MOD - val;\n  }\n \n  friend bool operator==(const _m_int &a, const _m_int &b) { return a.val == b.val; }\n  friend bool operator!=(const _m_int &a, const _m_int &b) { return a.val != b.val; }\n  friend bool operator<(const _m_int &a, const _m_int &b) { return a.val < b.val; }\n  friend bool operator>(const _m_int &a, const _m_int &b) { return a.val > b.val; }\n  friend bool operator<=(const _m_int &a, const _m_int &b) { return a.val <= b.val; }\n  friend bool operator>=(const _m_int &a, const _m_int &b) { return a.val >= b.val; }\n \n  _m_int inv() const {\n    return inv_mod(val);\n  }\n \n  _m_int pow(int64_t p) const {\n    if (p < 0)\n      return inv().pow(-p);\n \n    _m_int a = *this, result = 1;\n \n    while (p > 0) {\n      if (p & 1)\n        result *= a;\n      a *= a;\n      p >>= 1;\n    }\n \n    return result;\n  }\n  \n  friend string to_string(_m_int<MOD> x) {\n    return to_string(x.val);\n  }\n \n  friend ostream& operator<<(ostream &os, const _m_int &m) {\n    return os << m.val;\n  }\n};\n\nextern const int MOD = 998244353;\nusing Mint = _m_int<MOD>;\n\nconst int g = 3;\nconst int LOGN = 15;\n\nvector<Mint> w[LOGN];\nvector<int> rv[LOGN];\n\nvoid prepare() {\n  Mint wb = Mint(g).pow((MOD - 1) / (1 << LOGN));\n  forn(st, LOGN - 1) {\n    w[st].assign(1 << st, 1);\n    Mint bw = wb.pow(1 << (LOGN - st - 1));\n    Mint cw = 1;\n    forn(k, 1 << st) {\n      w[st][k] = cw;\n      cw *= bw;\n    }\n  }\n  forn(st, LOGN) {\n    rv[st].assign(1 << st, 0);\n    if (st == 0) {\n      rv[st][0] = 0;\n      continue;\n    }\n    int h = (1 << (st - 1));\n    forn(k, 1 << st)\n      rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);\n  }\n}\n\nvoid ntt(vector<Mint> &a, bool inv) {\n  int n = sz(a);\n  int ln = __builtin_ctz(n);\n  forn(i, n) {\n    int ni = rv[ln][i];\n    if (i < ni) swap(a[i], a[ni]);\n  }\n  forn(st, ln) {\n    int len = 1 << st;\n    for (int k = 0; k < n; k += (len << 1)) {\n      fore(pos, k, k + len){\n        Mint l = a[pos];\n        Mint r = a[pos + len] * w[st][pos - k];\n        a[pos] = l + r;\n        a[pos + len] = l - r;\n      }\n    }\n  }\n  if (inv) {\n    Mint rn = Mint(n).inv();\n    forn(i, n) a[i] *= rn;\n    reverse(a.begin() + 1, a.end());\n  }\n}\n\nvector<Mint> mul(vector<Mint> a, vector<Mint> b) {\n  int cnt = 1 << (32 - __builtin_clz(sz(a) + sz(b) - 1));\n  a.resize(cnt);\n  b.resize(cnt);\n  ntt(a, false);\n  ntt(b, false);\n  vector<Mint> c(cnt);\n  forn(i, cnt) c[i] = a[i] * b[i];\n  ntt(c, true);\n  return c;\n}\n\nint main() {\n  prepare();\n  \n  vector<Mint> fact(1, 1), ifact(1, 1);\n  auto C = [&](int n, int k) -> Mint {\n    if (k < 0 || k > n) return 0;\n    while (sz(fact) <= n) {\n      fact.push_back(fact.back() * sz(fact));\n      ifact.push_back(fact.back().inv());\n    }\n    return fact[n] * ifact[k] * ifact[n - k];\n  };\n  \n  int n;\n  cin >> n;\n  vector<int> a(n), b(n);\n  forn(i, n) cin >> a[i] >> b[i];\n  \n  vector<Mint> ans(1, 1);\n  forn(i, n) {\n    vector<Mint> Cs;\n    for (int j = b[i] - sz(ans) + 1; j < sz(ans) + a[i]; ++j)\n      Cs.push_back(C(a[i] + b[i], j));\n    auto res = mul(ans, Cs);\n    int cnt = sz(ans);\n    ans.resize(cnt + a[i] - b[i]);\n    forn(j, sz(ans)) ans[j] = res[cnt + j - 1];\n  }\n  \n  cout << accumulate(ans.begin(), ans.end(), Mint(0)) << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1474",
    "index": "A",
    "title": "Puzzle From the Future",
    "statement": "In the $2022$ year, Mike found two binary integers $a$ and $b$ of length $n$ (both of them are written only by digits $0$ and $1$) that can have leading zeroes. In order not to forget them, he wanted to construct integer $d$ in the following way:\n\n- he creates an integer $c$ as a result of bitwise summing of $a$ and $b$ without transferring carry, so $c$ may have one or more $2$-s. For example, the result of bitwise summing of $0110$ and $1101$ is $1211$ or the sum of $011000$ and $011000$ is $022000$;\n- after that Mike replaces equal consecutive digits in $c$ by one digit, thus getting $d$. In the cases above after this operation, $1211$ becomes $121$ and $022000$ becomes $020$ (so, $d$ won't have equal consecutive digits).\n\nUnfortunately, Mike lost integer $a$ before he could calculate $d$ himself. Now, to cheer him up, you want to find \\textbf{any binary} integer $a$ of length $n$ such that $d$ will be \\textbf{maximum possible as integer}.\n\nMaximum possible as integer means that $102 > 21$, $012 < 101$, $021 = 21$ and so on.",
    "tutorial": "Hint $1$: Should we always make first digit of $d$ not equal to $0$? How can we do it? Hint $2$: Try to choose such $a$ that $d$ will have $n$ digits. At first, we can make the first digit of $d$ not equal to $0$ by setting $1$ to the first digit of $a$. Now we say that $d$ doesn't have leading zeroes. In this case, more digits $d$ has - the larger $d$ is. It turns out, we can always construct $d$ of length $n$ if we make each consecutive pair of digits different. In other words, we want to select $a_i$ in order to make $a_{i-1} + b_{i-1} \\neq a_{i} + b_{i}$ for all $i > 1$. Since we want to maximize $a_{i} + b_{i}$, if $a_{i} = 1$ satisfies $a_{i-1} + b_{i-1} \\neq a_i + b_i$ we take $a_{i} = 1$. Otherwise, $a_{i} = 0$ satisfies this condition. Time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    string a;\n    cin >> a;\n    string b = \"1\";\n    for (int i = 1; i < n; i++)\n    {\n        if ('1' + a[i] != b[i - 1] + a[i - 1])\n            b += \"1\";\n        else\n            b += \"0\";\n    }\n    cout << b << \"\\n\";\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1474",
    "index": "B",
    "title": "Different Divisors",
    "statement": "Positive integer $x$ is called divisor of positive integer $y$, if $y$ is divisible by $x$ without remainder. For example, $1$ is a divisor of $7$ and $3$ is not divisor of $8$.\n\nWe gave you an integer $d$ and asked you to find \\textbf{the smallest} positive integer $a$, such that\n\n- $a$ has at least $4$ divisors;\n- difference between any two divisors of $a$ is at least $d$.",
    "tutorial": "Hint $1$: Integer have exactly $4$ divisors, if it is of form $pq$ or $p^3$ for some primes $p$ and $q$. In the first case it have divisors $1$, $p$, $q$, $pq$. In the second case it have divisors $1$, $p$, $p^2$, $p^3$. Hint $2$: Instead of finding integer with at least $4$ divisors, find integer with exactly $4$ divisors. Hint $3$: Let $p$ be the smallest prime factor of $a$. Then, $p \\geq d + 1$. Solution: Suppose, we have integer $a$ with more than $4$ divisors (and satisfies the other condition). If $a$ has at least two different prime factors, we can throw out all other prime factors and get a smaller number with at least $4$ divisors. Otherwise, $a = p^k$ for some $k > 3$. $p^3$ will also have $4$ divisors and it will be smaller than $a$. When we throw out a prime factor, no new divisors will appear, so the difference between any two of them will be at least $d$. Let's find smallest integers of form $p^3$ and $pq$ $(p<q)$ independently. In the first case, $p^3 - p^2 > p^2 - p > p - 1$, because $p \\geq 2$. If we will find the smallest $p \\geq d + 1$ all conditions will be satisfied. In the second case, $1 < p < q < pq$. Let's find the smallest $p \\geq d + 1$ and the smallest $q \\geq d + p$. In this case it is easy to see that $p - 1 \\geq d$ and $q - p \\geq d$. Also, $pq - q = q(p - 1) \\geq qd \\geq d$ since $q \\geq 2$. It is enough to get OK even without checking case $a = p^3$. Also we should prove that there cannot exist $p'$ and $q'$ such that $p'q' < pq$. It is true because $p'$ should be at least $d+1$ and it should be prime, but $p$ is the smallest prime greater than $d$, so $p' \\geq p$. And $q'$ should be at least $p+d$ and we can prove that $q' \\geq q$ in the same way. Time complexity is $\\mathcal{O}(t \\cdot \\mathit{gap} \\cdot \\mathit{primecheck})$, where $\\mathit{gap}$ is difference between primes and $\\mathcal{O}(\\log{a})$ in average and $primecheck$ is complexity of your prime check and usually is $\\mathcal{O}(\\sqrt{a})$. Answer for $d = 10000$ is near to $2 \\cdot 10^8$, so naive solution with factorization of each number shouldn't pass, but it is possible to precompute answers for all values of $d$ by that solution (in this case, you should run solution once for all values of $d$, not once for each value of $d$).",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nvoid solve()\n{\n    int x;\n    cin >> x;\n    vector<int> p;\n    for (int i = x + 1; ; i++)\n    {\n        int t = 1;\n        for (int j = 2; j * j <= i; j++)\n        {\n            if (i % j == 0)\n            {\n                t = 0;\n                break;\n            }\n        }\n        if (t)\n        {\n            p.push_back(i);\n            break;\n        }\n    }\n    for (int i = p.back() + x; ; i++)\n    {\n        int t = 1;\n        for (int j = 2; j * j <= i; j++)\n        {\n            if (i % j == 0)\n            {\n                t = 0;\n                break;\n            }\n        }\n        if (t)\n        {\n            p.push_back(i);\n            break;\n        }\n    }\n    cout << min(1ll * p[0] * p[1], 1ll * p[0] * p[0] * p[0]) << \"\\n\";\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1474",
    "index": "C",
    "title": "Array Destruction",
    "statement": "You found a useless array $a$ of $2n$ positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of $a$.\n\nIt could have been an easy task, but it turned out that you should follow some rules:\n\n- In the beginning, you select any positive integer $x$.\n- Then you do the following operation $n$ times:\n\n- select two elements of array with sum equals $x$;\n- remove them from $a$ and replace $x$ with maximum of that two numbers.\n\nFor example, if initially $a = [3, 5, 1, 2]$, you can select $x = 6$. Then you can select the second and the third elements of $a$ with sum $5 + 1 = 6$ and throw them out. After this operation, $x$ equals $5$ and there are two elements in array: $3$ and $2$. You can throw them out on the next operation.\n\nNote, that you choose $x$ before the start and can't change it as you want between the operations.\n\nDetermine how should you behave to throw out all elements of $a$.",
    "tutorial": "Hint $1$: How does $x$ changes after each operation? Hint $2$: Suppose, that you know $x$. What pairs of elements can you throw out now? Hint $3$: Suppose, that you did some operations. Note, that if you have integer $b$ that is greater or equal to $x$ and $b$ is still in array $a$, you can't remove $b$ from $a$, thus you can't throw out all elements of $a$. Hint $4$: You don't know $x$ only before the first operation and $n \\leq 1000$. Solution: Since all integers are positive, $x = c + d \\rightarrow c, d < x$, thus $x$ decreaces after each operation. Suppose that we have integers $a_i \\leq a_j \\leq a_k$ in our array. If we throw out $a_i + a_j = x$, $x$ becomes equal $a_j \\leq a_k$ and we can't throw out $a_k$ any time later. So, we should throw out the biggest element of array on each operation. If we know $x$ and the biggest element of array, we can easily determine the second element we throw out on this operation. We can try all possibilities of the second element of array we throw out on the first operation. $x$ will become equal the biggest element of initial array. After that we put all other elements in multiset $S$ and just simulate opertations by taking $max$ from $S$ and $x - max$ (if it doesn't exists, we can't throw out all elements) and replacing $x$ with $max$. Total time complexity: $\\mathcal{O}(n^2 \\cdot \\log{n})$. There is also a solution without set, that runs in $\\mathcal{O}(n^2 + maxA)$. Solution with set Solution without set 1474D - Cleaning",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int A = 1e6 + 12;\n \nint cnt[A];\n \nvoid reset(vector<int> a)\n{\n    for (int i = 0; i < a.size(); i++)\n    {\n        cnt[a[i]] = 0;\n    }\n}\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<int> a(2 * n);\n    for (int i = 0; i < 2 * n; i++)\n    {\n        cin >> a[i];\n    }\n    sort(a.begin(), a.end());\n    int t = 0;\n    for (int i = 0; i < 2 * n - 1; i++)\n    {\n        for (int j = 0; j < 2 * n; j++)\n            cnt[a[j]]++;\n        int j = 2 * n - 1;\n        int x = a[i] + a[j];\n        vector<int> rm;\n        for (int op = 0; op < n; op++)\n        {\n            while (j > 0 && cnt[a[j]] == 0)\n                j--;\n            rm.push_back(a[j]);\n            rm.push_back(x - a[j]);\n            cnt[a[j]]--, cnt[x - a[j]]--;\n            if (cnt[a[j]] < 0 || cnt[x - a[j]] < 0)\n            {\n                cnt[a[j]] = 0;\n                cnt[x - a[j]] = 0;\n                break;\n            }\n            x = max(x - a[j], a[j]);\n            if (op + 1 == n)\n                t = 1;\n        }\n        reset(a);\n        if (t)\n        {\n            cout << \"YES\\n\";\n            cout << rm[0] + rm[1] << \"\\n\";\n            for (int i = 0; i < rm.size(); i++)\n            {\n                cout << rm[i] << \" \\n\"[i % 2];\n            }\n            return;\n        }\n    }\n    cout << \"NO\\n\";\n    reset(a);\n}\n \nint main(int argc, char* argv[])\n{\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1474",
    "index": "D",
    "title": "Cleaning",
    "statement": "During cleaning the coast, Alice found $n$ piles of stones. The $i$-th pile has $a_i$ stones.\n\nPiles $i$ and $i + 1$ are neighbouring for all $1 \\leq i \\leq n - 1$. If pile $i$ becomes empty, piles $i - 1$ and $i + 1$ \\textbf{doesn't} become neighbouring.\n\nAlice is too lazy to remove these stones, so she asked you to take this duty. She allowed you to do only the following operation:\n\n- Select two \\textbf{neighboring} piles and, if both of them are not empty, remove one stone from each of them.\n\nAlice understands that sometimes it's impossible to remove all stones with the given operation, so she allowed you to use the following superability:\n\n- Before the start of cleaning, you can select two \\textbf{neighboring} piles and swap them.\n\nDetermine, if it is possible to remove all stones using the superability \\textbf{not more than once}.",
    "tutorial": "Hint $1$: How to solve the promblem if we are not allowed to use a superabilty (in linear time)? Hint $2$: Look at the first pile. There is only one way to remove stone from the first pile. Hint $3$: If you swap $i$-th and $(i + 1)$-th piles of stones, nothing changes in way you remove stones from $1$-st, $2$-nd, $\\ldots$, $(i - 2)$-th piles. Hint $4$: Look at the problem from the both sides: from the beginning of $a$ and from the end of $a$. Solution: We can check, whether we can remove all stones without a supeability using the following algorithm: How can we remove the stones from the $1$-st pile? Only with stones from the second pile! If $a_1 > a_2$, then we can't remove all stones from the $1$-st pile. Now we have $0$ stones in the $1$-st pile and $a_2 - a_1$ stones in the $2$-nd pile. We can apply the idea above and get that we should have $a_2 - a_1$ stones in the $3$-rd pile.... ... In the end we have only $1$ pile. If there are any stones in it, we can't remove all stones. Otherwise, we constructed a solution for removing all stones. Also, we profed that there can be only one way to remove all stones. Now we have to improve this algorithm. Let $p_i$ be a number of stones in the $i$-th pile after cleaning piles $1$, $2$, ..., $i-1$ using this algorithm (and $(i+1)$-th, $(i+2)$-th, ..., $n$-th piles have the initial amount of stones). Now, let $s_i$ be a number of stones in the $i$-th pile, if we removed all stones from the $(i+1)$-th, ..., $n$-th piles (using the same algorithm, but we do operations in reversed order). We compute all $p_i$ and all $s_i$ in $\\mathcal{O}(n)$. Now, if we try to swap $i$-th and $(i+1)$-th piles, we should check, that we can remove stones from four piles: $p_{i-1}$, $a_{i + 1}$, $a_{i}$, $s_{i+2}$. If we can do this for any $i$, answer is YES.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nint check(vector<long long> a)\n{\n    for (int i = 0; i + 1 < a.size(); i++)\n    {\n        if (a[i] > a[i + 1])\n        {\n            return 0;\n        }\n        a[i + 1] -= a[i];\n        a[i] = 0;\n    }\n    if (a.back() == 0)\n        return 1;\n    return 0;\n}\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<long long> a(n);\n    for (int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n    }\n    if (check(a))\n    {\n        cout << \"YES\\n\";\n        return;\n    }\n    if (n == 1)\n    {\n        cout << \"NO\\n\";\n        return;\n    }\n    swap(a[0], a[1]);\n    if (check(a))\n    {\n        cout << \"YES\\n\";\n        return;\n    }\n    swap(a[0], a[1]);\n    swap(a[n - 2], a[n - 1]);\n    if (check(a))\n    {\n        cout << \"YES\\n\";\n        return;\n    }\n    swap(a[n - 2], a[n - 1]);\n    vector<long long> p(n), s(n);\n    vector<long long> b = a;\n    p[0] = b[0];\n    for (int i = 1; i < n; i++)\n    {\n        if (p[i - 1] == -1 || b[i - 1] > b[i])\n        {\n            p[i] = -1;\n        }\n        else\n        {\n            b[i] -= b[i - 1];\n            b[i - 1] = 0;\n            p[i] = b[i];\n        }\n    }\n    b = a;\n    s[n - 1] = b[n - 1];\n    for (int i = n - 2; i >= 0; i--)\n    {\n        if (s[i + 1] == -1 || b[i + 1] > b[i])\n        {\n            s[i] = -1;\n        }\n        else\n        {\n            b[i] -= b[i + 1];\n            b[i + 1] = 0;\n            s[i] = b[i];\n        }\n    }\n    for (int i = 1; i + 2 < n; i++)\n    {\n        vector<long long> c = {p[i - 1], a[i], a[i + 1], s[i + 2]};\n        if (p[i - 1] == -1 || s[i + 2] == -1)\n        {\n            continue;\n        }\n        swap(c[1], c[2]);\n        if (check(c))\n        {\n            cout << \"YES\\n\";\n            return;\n        }\n    }\n    cout << \"NO\\n\";\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1474",
    "index": "E",
    "title": "What Is It?",
    "statement": "Lunar rover finally reached planet X. After landing, he met an obstacle, that contains permutation $p$ of length $n$. Scientists found out, that to overcome an obstacle, the robot should make $p$ an identity permutation (make $p_i = i$ for all $i$).\n\nUnfortunately, scientists can't control the robot. Thus the only way to make $p$ an identity permutation is applying the following operation to $p$ multiple times:\n\n- Select two indices $i$ and $j$ ($i \\neq j$), such that $p_j = i$ and swap the values of $p_i$ and $p_j$. It takes robot $(j - i)^2$ seconds to do this operation.\n\nPositions $i$ and $j$ are selected by the robot (scientists can't control it). He will apply this operation while $p$ isn't an identity permutation. We can show that the robot will make no more than $n$ operations regardless of the choice of $i$ and $j$ on each operation.Scientists asked you to find out the maximum possible time it will take the robot to finish making $p$ an identity permutation (i. e. worst-case scenario), so they can decide whether they should construct a new lunar rover or just rest and wait. They won't believe you without proof, so you should build an example of $p$ and robot's operations that maximizes the answer.\n\nFor a better understanding of the statement, read the sample description.",
    "tutorial": "Hint $1$: How many operations will robot make in the worst case? Hint $2$: How many times can robot spend $(n - 1)^2$ time on $1$ operation? Hint $3$: How many times can robot spend $(n - 2)^2$ time on $1$ operation? It is easyer to think about number of operations with time greater or equal to $(n - 2)^2$. Hint $4$: Instead of operation from the statement we can apply the following operation to $q$ which is initially an identity permutation: Select $i$ such that $q_i = i$ and any $j$ and swap $q_i$ and $q_j$ in $(j - i) ^ 2$ seconds. Then we make $p$ = $q$ and do operations in reversed order. Solution: If we can select $i$ and $j$ for an operation, $p_j \\neq j$. After every operation, there is at least one more element with $p_i = i$, so after $n - 1$ operations at least $n - 1$ elements are on their places. The remaining element can be only on its own place, so we can't do more than $n - 1$ operations. Let's now count number of operations that takes $(n - 1)^2$ time. It is only a swap of $1$-st and $n$-th elements. If we did it, $p_1 = 1$ or $p_n = n$ so we can't use it one more time. Let's generalize it. If we are calculating number of operations that takes $(n - k)^2$ time, let's look at the first $k$ elements and at the last $k$ elements. Any operation that takes greater or equal then $(n - k)^2$ seconds, uses two of this elements. So, after $2k - 1$ operations $2k - 1$ of this elements will be on their places and we can't use one more operation of this type. So, $answer \\leq (n - 1)^2 + (n - 2)^2 + (n - 2)^2 + (n - 3)^2 + \\cdots$. There are $n - 1$ terms, each $(n - k)^2$ appears $2$ times, except $(n - 1)^2$ and last term (depends on parity of $n - 1$). We can construct example, where robot will spend exactly $(n - 1)^2 + (n - 2)^2 + (n - 2)^2 + (n - 3)^2 + \\cdots$ second as follows (using idea from hint $4$): If $n$ is even, $answer = (n - 1)^2 + \\cdots + (n - n / 2)^2 + (n - n / 2)^2$. Let's look at the example with $n = 6$: Set $q = [1, 2, 3, 4, 5, 6]$. Swap $q_1$ and $q_n$ in $25$ seconds, $q = [6, 2, 3, 4, 5, 1]$. Swap $q_1$ and $q_{n-1}$ in $16$ seconds, $q = [5, 2, 3, 4, 6, 1]$. Swap $q_2$ and $q_n$ in $16$ seconds, $q = [5, 1, 3, 4, 6, 2]$. Swap $q_1$ and $q_{n-2}$ in $9$ seconds, $q = [4, 1, 3, 5, 6, 2]$. Swap $q_3$ and $q_n$ in $9$ second, $q = [4, 1, 2, 5, 6, 3]$. In general, we swap $1$-st and $n$-th elements on the first operation and then move elements $2, n-1, 3, n-2, 4, n-3, ...$ to the further end of $q$. Set $q = [1, 2, 3, 4, 5, 6]$. Swap $q_1$ and $q_n$ in $25$ seconds, $q = [6, 2, 3, 4, 5, 1]$. Swap $q_1$ and $q_{n-1}$ in $16$ seconds, $q = [5, 2, 3, 4, 6, 1]$. Swap $q_2$ and $q_n$ in $16$ seconds, $q = [5, 1, 3, 4, 6, 2]$. Swap $q_1$ and $q_{n-2}$ in $9$ seconds, $q = [4, 1, 3, 5, 6, 2]$. Swap $q_3$ and $q_n$ in $9$ second, $q = [4, 1, 2, 5, 6, 3]$. If $n$ is odd, $answer = (n - 1)^2 + \\cdots + (n - \\lceil{n/2}\\rceil)^2$. The only difference from even case is element in the center. For example, if $n = 7$ we will do the following operations: $q = [1, 2, 3, 4, 5, 6, 7]$. Swap $q_1$ and $q_n$. $q = [7, 2, 3, 4, 5, 6, 1]$. Swap $q_1$ and $q_{n - 1}$. $q = [6, 2, 3, 4, 5, 7, 1]$. Swap $q_2$ and $q_n$. $q = [6, 1, 3, 4, 5, 7, 2]$. Swap $q_1$ and $q_{n - 2}$. $q = [5, 1, 3, 4, 6, 7, 2]$. Swap $q_3$ and $q_n$. $q = [5, 1, 2, 4, 6, 7, 3]$. Finally, swap $q_1$ and $q_{\\lceil{n/2}\\rceil}$. $q = [4, 1, 2, 5, 6, 7, 3]$. $q = [1, 2, 3, 4, 5, 6, 7]$. Swap $q_1$ and $q_n$. $q = [7, 2, 3, 4, 5, 6, 1]$. Swap $q_1$ and $q_{n - 1}$. $q = [6, 2, 3, 4, 5, 7, 1]$. Swap $q_2$ and $q_n$. $q = [6, 1, 3, 4, 5, 7, 2]$. Swap $q_1$ and $q_{n - 2}$. $q = [5, 1, 3, 4, 6, 7, 2]$. Swap $q_3$ and $q_n$. $q = [5, 1, 2, 4, 6, 7, 3]$. Finally, swap $q_1$ and $q_{\\lceil{n/2}\\rceil}$. $q = [4, 1, 2, 5, 6, 7, 3]$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n \n    if (n == 1)\n    {\n        cout << 0 << \"\\n\";\n        cout << 1 << \"\\n\";\n        cout << 0 << \"\\n\";\n        return;\n    }\n \n    long long ans = 0;\n    long long cnt = 1, st = n - 1, asz = 0;\n    while (asz < n - 1)\n    {\n        if (cnt == 0)\n        {\n            cnt = 2;\n            st--;\n        }\n        ans += st * st;\n        cnt--;\n        asz++;\n    }\n    cout << ans << \"\\n\";\n \n    vector<int> p;\n    vector<int> opi, opj;\n \n    {\n        p.push_back(n / 2 + 1);\n        for (int i = 1; i < n / 2; i++)\n        {\n            p.push_back(i);\n        }\n        for (int i = n / 2 + 2; i <= n; i++)\n        {\n            p.push_back(i);\n        }\n        p.push_back(n / 2);\n        for (int i = n / 2 + 1; i < n; i++)\n        {\n            opi.push_back(i);\n            opj.push_back(1);\n        }\n        for (int i = n / 2; i > 1; i--)\n        {\n            opi.push_back(i);\n            opj.push_back(n);\n        }\n        if (n != 1)\n        {\n            opi.push_back(1);\n            opj.push_back(n);\n        }\n    }\n \n    for (int i = 0; i < p.size(); i++)\n    {\n        cout << p[i] << \" \";\n    }\n    cout << \"\\n\";\n    cout << opi.size() << \"\\n\";\n    for (int j = 0; j < opi.size(); j++)\n    {\n        cout << opi[j] << \" \" << opj[j] << \"\\n\";\n    }\n    cout << \"\\n\";\n    return;\n \n    long long tm = 0;\n    for (int j = 0; j < opi.size(); j++)\n    {\n        opi[j]--;\n        opj[j]--;\n        assert(p[opj[j]] - 1 == opi[j]);\n        swap(p[opi[j]], p[opj[j]]);\n        tm += 1ll * (opi[j] - opj[j]) * (opi[j] - opj[j]);\n    }\n    //cout << \"True time = \" << tm << \"\\n\";\n    //cout << \"Resulting permutation = \";\n    for (int i = 0; i < n; i++)\n    {\n        ;//cout << p[i] << \" \";\n    }\n    //cout << \"\\n\";\n \n    assert(tm == ans);\n    for (int i = 0; i < n; i++)\n    {\n        assert(p[i] == i + 1);\n    }\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1474",
    "index": "F",
    "title": "1 2 3 4 ...",
    "statement": "Igor had a sequence $d_1, d_2, \\dots, d_n$ of integers. When Igor entered the classroom there was an integer $x$ written on the blackboard.\n\nIgor generated sequence $p$ using the following algorithm:\n\n- initially, $p = [x]$;\n- for each $1 \\leq i \\leq n$ he did the following operation $|d_i|$ times:\n\n- if $d_i \\geq 0$, then he looked at the last element of $p$ (let it be $y$) and appended $y + 1$ to the end of $p$;\n- if $d_i < 0$, then he looked at the last element of $p$ (let it be $y$) and appended $y - 1$ to the end of $p$.\n\nFor example, if $x = 3$, and $d = [1, -1, 2]$, $p$ will be equal $[3, 4, 3, 4, 5]$.\n\nIgor decided to calculate the length of the longest increasing subsequence of $p$ and the number of them.\n\nA sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.\n\nA sequence $a$ is an increasing sequence if each element of $a$ (except the first one) is strictly greater than the previous element.\n\nFor $p = [3, 4, 3, 4, 5]$, the length of longest increasing subsequence is $3$ and there are $3$ of them: $[\\underline{3}, \\underline{4}, 3, 4, \\underline{5}]$, $[\\underline{3}, 4, 3, \\underline{4}, \\underline{5}]$, $[3, 4, \\underline{3}, \\underline{4}, \\underline{5}]$.",
    "tutorial": "Solution describes generalized version of algorigthm, corner cases are described later. It is easy to see that answer doesn't depend on $x$ given in the input, because we can substract $x$ from each element of $p$ and longest incerasing subsequences will remain the same. Let's look at $p$ as a function. If $p_i = x$ and $p_j = y$, for each $z \\in [x, y]$ there exists $k \\in [i, j]$, such that $p_k = z$ (Integer version of intermediate value theorem). Now look at any longest increasing subsequence $L$. If there are integers $x - 1$ and $x + 1$ in it (but there is no $x$), we can find appearence of $x$ in $p$ between them and add it to $L$, thus making a $L$ longer. So, such $x$ shouldn't exist $\\rightarrow$ correct longest increasing sequence contains all integers between $a$ and $b$ for some $a$ and $b$. Let's build array $peaks$ that contains $p_1$, $last(p)$ and all $p_i$ such that $p_{i-1} < p_i > p_{i+1}$ or $p_{i-1} > p_i < p_{i+1}$ in order they appear in $p$. It is easy to see, that $|peaks| \\leq n + 1$. Suppose, that the end of $L$ is not a peak. If it lies on increasing interval, than we can take next element into $L$ and increase $|L|$. If it lies on decreasing interval, we can use previous element of $p$ and using previous facts, find $L'$, $|L'| > |L|$. We can apply the same observations to the beginning of $p$. Thus, any $L$ begins and ends in peaks. Now, we can find $|L|$ in $\\mathcal{O}(n^2)$. Suppose, we fixed that peaks and got $p'$, such that longest increasing subsequence of $p'$ begins and ends in different ends of $p'$ (we will not care about other longest increasing subsequences). Let's look at the slow algorithm for finding the amount of longest increasing subsequences: Let $ways_i$ be number of ways to build a prefix of longest increasing subsequence, that ends in $p'_i$. Set $ways_1 = 1$. For each $i$ in order $[1..|p'|]$, $ways_i = \\sum\\limits_{j < i, p'_{j} + 1 = p'_{i}} ways_j$. This is correct because $p'_{j} + 1 = p'_{i}$ means exactly that the length of longest increasing subsequence ends in $p'_j$ is smaller than the length of longest increasing subsequence ends in $p'_i$ by $1$ (because of previous facts). The answer is $ways_{|p'|}$. The time complexity of this approach is $\\mathcal{O}(|p'|^2)$ Let's change this algorithm a bit by changing order we iterate over $i$. We will iterate in order of increasing $p'_{i}$. Since each value appears in $p'$ $\\mathcal{O}(n)$ times, when calculating values of $ways_i$ for all $i$, such that $p'_i = x$, we will need to check only $\\mathcal{O}(n)$ values of $ways_j$ for $p'_j = x - 1$, and we will never use values of $ways_j$ later, we need only $\\mathcal{O}(n)$ memory and $\\mathcal{O}(|L| \\cdot n^2)$ time. We will store this values in array $w$, where $w_{i, j}$ is a number of ways to end prefix of longest increasing subsequence in value $i$ on the $j$-th increasing/decreasing segment of $p'$. Clearly, $w_{i, j}$ is calculated only from $w_{i - 1, *}$. We can write down transitions between them for each $i$ and see, that we use the same transition for almost all values of $i$ between two \"consecutive by value\" peaks. There are $\\mathcal{O}(n)$ intervals between peaks, and almost all transitions on each of this intervals are the same. We can build matrix $G$ of size $\\mathcal{O}(n)$ and use matrix exponentiation for doing this transitions fast. Complexity for each $p'$ is $\\mathcal{O}(n^4 \\cdot \\log|d_{max}|)$. We should be careful, because it will take $\\mathcal{O}(n^6 * \\log|d_{max}|)$ if we will do it for each $p'$ we find. We should group $p'$-s with the same first element into one group and apply the algorithm above for each of the groups. Note, that there can be many groups, but total size (in segments) of all $p'$-s doesn't exceed $n$. It gives the total time complexity $\\mathcal{O}(n^4 \\cdot \\log|d_{max}|)$. We can further optimize this solution to get time complexity $\\mathcal{O}(n^3 \\cdot \\log|d_{max}|)$. Obiviously, we can through out all from matrix all rows and collumns with zeroes. After this, we can show that the matrix will be of the following form: $1$ $1$ $1$ $1$ $1$ $0$ $0$ $1$ $1$ $1$ $0$ $0$ $1$ $1$ $1$ $0$ $0$ $0$ $0$ $1$ $0$ $0$ $0$ $0$ $1$ It happends because ones on the main diagonal correspond to increasing subsegments (between two peaks), and zeroes correspond to decreasing subsegments. Obiviously, we cannot move backwards, so all elements below main diagonal are zeroes. And since this matrix corresponds to placing $x+1$ after $x$ in longest increasing subsequence, all elements above main diagonal are ones (all subsegments contains both $x$ and $x+1$). Matrix exponentiation of this matrix can be done in $\\mathcal{O}(n^2 \\cdot \\log|d_{max}|)$, because we will care only about distance between $i$-th and $j$-th subsegments and parities of $i$ and $j$. There are many tricky cases in this problem, such as: Handling zeroes and same sign elements in a row while building $peaks$. If all $d_i$ are not positive, longest increasing subsequence will have length $1$ (last element = first element), so it don't have to begin in one of peaks and end in one of peaks. Even though all $d_i$ can be stored in $int$, first answer can be up to $5 \\cdot 10^{10} + 1$. Also, degree in matrix exponentiation can don't fit in $int$. There can be many groups of $p'$-s. Algorithm without compessing $p'$-s in groups can work $\\mathcal{O}(n^6 \\cdot \\log|d_{max}|)$ in the worst case.",
    "code": "#include <bits/stdc++.h>\n \nconst long long MOD = 998244353;\n \nusing namespace std;\n \ntypedef long long ll;\n \nvector<ll> binpow(int len, ll deg)\n{\n    if (deg == 1) return vector<ll>(len, 1);\n    vector<ll> part = binpow(len, deg / 2);\n    vector<ll> whole(len);\n \n    auto D = [&](int i, int j){\n        assert(i <= j);\n        if (i % 2 == 0) return part[j - i];\n        return j - i - 1 >= 0 ? part[j - i - 1] : 0;\n    };\n \n    for (int j = 0; j < len; j++)\n    {\n        for (int i = 0; i <= j; i++)\n        {\n            whole[j] = (whole[j] + D(0, i) * D(i, j)) % MOD;\n        }\n    }\n \n    if (deg % 2 == 1)\n    {\n        vector<ll> whole2(len);\n        for (int j = 0; j < len; j++)\n        {\n            for (int i = 0; i <= j; i++)\n            {\n                whole2[j] = (whole2[j] + (i != j || j % 2 == 0 ? whole[i] : 0)) % MOD;\n            }\n        }\n        return whole2;\n    }\n \n    return whole;\n}\n \nvoid simple_transition(vector<ll> &dp, vector<long long> &L, vector<long long> &R, vector<long long> &fl, long long z)\n{\n    vector<ll> dp2(dp.size());\n    for (int i = 0; i < dp.size(); i++)\n    {\n        for (int j = 0; j < i + (fl[i] == 1); j++)\n        {\n            if (L[i] <= z && z <= R[i] && L[j] <= z - 1 && z - 1 <= R[j])\n            {\n                dp2[i] = (dp2[i] + dp[j]) % MOD;\n            }\n        }\n    }\n    dp = dp2;\n}\n \nlong long calls = 0;\n \nlong long solve(vector<long long> b)\n{\n    calls += b.size() - 1;\n    vector<long long> c = b;\n    sort(c.begin(), c.end());\n    int sz = b.size() - 1;\n    vector<long long> L(sz);\n    vector<long long> R(sz);\n    vector<long long> fl(sz, 1);\n    for (int i = 0; i + 1 < b.size(); i++)\n    {\n        L[i] = b[i];\n        R[i] = b[i + 1];\n \n        if (i != 0)\n        {\n            if (L[i] < R[i]) L[i]++;\n            else L[i]--;\n        }\n \n        if (L[i] > R[i]) swap(L[i], R[i]), fl[i] = -1;\n    }\n    vector<ll> dp(sz);\n    long long fr = c[0], to = c.back();\n    for (int i = 0; i < sz; i++)\n    {\n        if (L[i] <= fr && fr <= R[i])\n        {\n            dp[i] = 1;\n        }\n    }\n    long long lst = fr;\n    for (auto p : c)\n    {\n        long long z = p - 2;\n        if (lst < z)\n        {\n            long long d = z - lst;\n            vector<int> act(sz);\n            for (int i = 0; i < sz; i++)\n            {\n                for (int j = 0; j < i + (fl[i] == 1); j++)\n                {\n                    if (L[i] <= z && z <= R[i] && L[j] <= z && z <= R[j])\n                    {\n                        act[i] = 1;\n                        act[j] = 1;\n                    }\n                }\n            }\n            int cnt = 0;\n            vector<int> link(sz);\n            for (int i = 0; i < sz; i++)\n                if (act[i])\n                    link[i] = cnt++;\n            vector<ll> fast = binpow(cnt, d);\n            vector<ll> dp2(sz);\n            auto D = [&](int i, int j){\n                if (i % 2 == 0) return fast[j - i];\n                return (j - i - 1 >= 0 ? fast[j - i - 1] : 0);\n            };\n            for (int i = 0; i < sz; i++)\n            {\n                for (int j = 0; j <= i; j++)\n                {\n                    dp2[i] = (dp2[i] + dp[j] * D(link[j], link[i])) % MOD;\n                }\n            }\n            dp = dp2;\n            lst = z;\n        }\n        z = p - 1;\n        if (lst < z)\n        {\n            simple_transition(dp, L, R, fl, z);\n            lst = z;\n        }\n        z = p;\n        if (lst < z)\n        {\n            simple_transition(dp, L, R, fl, z);\n            lst = z;\n        }\n        z = p + 1;\n        if (z <= to && lst < z)\n        {\n            simple_transition(dp, L, R, fl, z);\n            lst = z;\n        }\n    }\n    long long res = 0;\n    for (int i = 0; i < sz; i++)\n    {\n        if (L[i] <= to && to <= R[i])\n        {\n            res = (res + dp[i]) % MOD;\n        }\n    }\n    return res;\n}\n \nint sign(long long x)\n{\n    if (x > 0) return 1;\n    if (x < 0) return -1;\n    return 0;\n}\n \nint main()\n{\n    int n = 300;\n    cin >> n;\n    long long x = 0;\n    cin >> x;\n    vector<long long> a;\n    for (int i = 0; i < n; i++)\n    {\n        if (i % 2 == 0) x = 1000000000;\n        else x = -999000000 - i;\n        cin >> x;\n        if (x != 0)\n        {\n            if (a.size() && sign(a.back()) == sign(x))\n            {\n                a[a.size() - 1] += x;\n            }\n            else\n            {\n                a.push_back(x);\n            }\n        }\n    }\n    vector<long long> peaks;\n    peaks.push_back(1);\n    n = a.size();\n    for (int i = 0; i < n; i++)\n    {\n        peaks.push_back(a[i] + peaks.back());\n    }\n    n++;\n    long long max_len = 1;\n    for (int i = 0; i < n; i++)\n    {\n        for (int j = i + 1; j < n; j++)\n        {\n            if (peaks[i] < peaks[j])\n                max_len = max(max_len, peaks[j] - peaks[i] + 1);\n        }\n    }\n \n    if (max_len == 1)\n    {\n        long long ans = 1;\n        cout << 1 << \" \";\n        for (int i = 0; i < a.size(); i++)\n        {\n            ans = (ans + abs(a[i])) % MOD;\n        }\n        cout << ans << endl;\n        return 0;\n    }\n \n    cout << max_len << \" \";\n    long long ans = 0;\n    int i = 0;\n    while (i < n)\n    {\n        int id = -1;\n        for (int j = i + 1; j < n; j++)\n        {\n            if (peaks[j] - peaks[i] + 1 == max_len)\n            {\n                id = j;\n            }\n        }\n        if (id == -1)\n        {\n            i++;\n            continue;\n        }\n        vector<long long> b;\n        for (int k = i; k <= id; k++)\n        {\n            b.push_back(peaks[k]);\n        }\n        i = id;\n        ans = (ans + solve(b)) % MOD;\n    }\n    //cerr << tot << endl;\n    cout << ans << endl;\n    //cout << calls << endl;\n}",
    "tags": [
      "dp",
      "math",
      "matrices"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1475",
    "index": "A",
    "title": "Odd Divisor",
    "statement": "You are given an integer $n$. Check if $n$ has an \\textbf{odd} divisor, greater than one (does there exist such a number $x$ ($x > 1$) that $n$ is divisible by $x$ and $x$ is odd).\n\nFor example, if $n=6$, then there is $x=3$. If $n=4$, then such a number does not exist.",
    "tutorial": "If the number $x$ has an odd divisor, then it has an odd prime divisor. To understand this fact, we can consider what happens when multiplying even and odd numbers: even $*$ even $=$ even; even $*$ odd $=$ even; odd $*$ even $=$ even; odd $*$ odd $=$ odd. There is only one even prime number - $2$. So, if a number has no odd divisors, then it must be a power of two. To check this fact, for example, you can divide $n$ by $2$ as long as it is divisible. If at the end we got $1$, then $n$ - the power of two. Bonus: You can also use the following condition to check: $n \\& (n-1) = 0$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\nvoid solve() {\n  ll n;\n  cin >> n;\n  if (n & (n - 1)) {\n    cout << \"YES\\n\";\n  } else {\n    cout << \"NO\\n\";\n  }\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1475",
    "index": "B",
    "title": "New Year's Number",
    "statement": "Polycarp remembered the $2020$-th year, and he is happy with the arrival of the new $2021$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $n$ as the sum of a certain number of $2020$ and a certain number of $2021$.\n\nFor example, if:\n\n- $n=4041$, then the number $n$ can be represented as the sum $2020 + 2021$;\n- $n=4042$, then the number $n$ can be represented as the sum $2021 + 2021$;\n- $n=8081$, then the number $n$ can be represented as the sum $2020 + 2020 + 2020 + 2021$;\n- $n=8079$, then the number $n$ cannot be represented as the sum of the numbers $2020$ and $2021$.\n\nHelp Polycarp to find out whether the number $n$ can be represented as the sum of a certain number of numbers $2020$ and a certain number of numbers $2021$.",
    "tutorial": "Let $x$ - the number of $2020$, $y$ - the number of $2021$ ($x, y \\geq 0$). Let us write the required decomposition of the number $n$: $n = 2020 \\cdot x + 2021 \\cdot y = 2020 \\cdot (x + y) + y$ $x = \\frac{n - y}{2020} - y$",
    "code": "#include <bits/stdc++.h>\n\n#include <utility>\nusing namespace std;\n\nusing pii = pair<int, int>;\n\nint main() {\n  int test;\n  cin >> test;\n  while (test-- > 0) {\n    int n;\n    cin >> n;\n    int cnt2021 = n % 2020;\n    int cnt2020 = (n - cnt2021) / 2020 - cnt2021;\n    if (cnt2020 >= 0 && 2020 * cnt2020 + 2021 * cnt2021 == n) {\n      cout << \"YES\\n\";\n    } else {\n      cout << \"NO\\n\";\n    }\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1475",
    "index": "C",
    "title": "Ball in Berland",
    "statement": "At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.\n\nEach class must present two couples to the ball. In Vasya's class, $a$ boys and $b$ girls wish to participate. But not all boys and not all girls are ready to dance in pairs.\n\nFormally, you know $k$ possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair.\n\nFor example, if $a=3$, $b=4$, $k=4$ and the couples $(1, 2)$, $(1, 3)$, $(2, 2)$, $(3, 4)$ are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below):\n\n- $(1, 3)$ and $(2, 2)$;\n- $(3, 4)$ and $(1, 3)$;\n\nBut the following combinations are not possible:\n\n- $(1, 3)$ and $(1, 2)$ — the first boy enters two pairs;\n- $(1, 2)$ and $(2, 2)$ — the second girl enters two pairs;\n\nFind the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs.",
    "tutorial": "We can think that it is given a bipartite graph. Boys and girls are the vertices of the graph. If a boy and a girl are ready to dance together, then an edge is drawn between them. In this graph, you need to select two edges that do not intersect at the vertices. Let $deg(x)$ - the number of edges included in the vertex $x$. Iterate over the first edge - ($a, b$). It will block $deg(a)+deg(b)-1$ of other edges (all adjacent to vertex $a$, to vertex $b$, but the edge ($a, b$) will be blocked twice. All non-blocked edges do not intersect with ($a, b$) at the vertices. So you can add $k-deg(a)-deg(b)+1$ to the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\nvoid solve() {\n  int A, B, k;\n  cin >> A >> B >> k;\n  vector<int> a(A), b(B);\n  vector<pair<int, int>> edges(k);\n  for (auto &[x, y] : edges) {\n    cin >> x;\n  }\n  for (auto &[x, y] : edges) {\n    cin >> y;\n  }\n  for (auto &[x, y] : edges) {\n    x--;\n    y--;\n    a[x]++;\n    b[y]++;\n  }\n  ll ans = 0;\n  for (auto &[x, y] : edges) {\n    ans += k - a[x] - b[y] + 1;\n  }\n  cout << ans / 2 << \"\\n\";\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "combinatorics",
      "graphs",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1475",
    "index": "D",
    "title": "Cleaning the Phone",
    "statement": "Polycarp often uses his smartphone. He has already installed $n$ applications on it. Application with number $i$ takes up $a_i$ units of memory.\n\nPolycarp wants to free at least $m$ units of memory (by removing some applications).\n\nOf course, some applications are more important to Polycarp than others. He came up with the following scoring system — he assigned an integer $b_i$ to each application:\n\n- $b_i = 1$ — regular application;\n- $b_i = 2$ — important application.\n\nAccording to this rating system, his phone has $b_1 + b_2 + \\ldots + b_n$ convenience points.\n\nPolycarp believes that if he removes applications with numbers $i_1, i_2, \\ldots, i_k$, then he will free $a_{i_1} + a_{i_2} + \\ldots + a_{i_k}$ units of memory and lose $b_{i_1} + b_{i_2} + \\ldots + b_{i_k}$ convenience points.\n\nFor example, if $n=5$, $m=7$, $a=[5, 3, 2, 1, 4]$, $b=[2, 1, 1, 2, 1]$, then Polycarp can uninstall the following application sets (not all options are listed below):\n\n- applications with numbers $1, 4$ and $5$. In this case, it will free $a_1+a_4+a_5=10$ units of memory and lose $b_1+b_4+b_5=5$ convenience points;\n- applications with numbers $1$ and $3$. In this case, it will free $a_1+a_3=7$ units of memory and lose $b_1+b_3=3$ convenience points.\n- applications with numbers $2$ and $5$. In this case, it will free $a_2+a_5=7$ memory units and lose $b_2+b_5=2$ convenience points.\n\nHelp Polycarp, choose a set of applications, such that if removing them will free at least $m$ units of memory and lose the minimum number of convenience points, or indicate that such a set does not exist.",
    "tutorial": "Let's say we remove $x$ applications with $b_i=1$ and $y$ applications with $b_i=2$. Obviously, among all the applications with $b_i=1$, it was necessary to take $x$ maximum in memory (so we will clear the most memory). Let's split all the applications into two arrays with $b_i=1$ and $b_i=2$ and sort them. Then you need to take a prefix from each array. Let's iterate over which prefix we take from the first array. For it, we can uniquely find the second prefix (we remove applications until the sum exceeds $m$). If we now increase the first prefix by taking a new application, then we don't need to take any applications in the second array. This means that when the first prefix is increased, the second one can only decrease. To solve the problem, you can use the two-pointer method.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\nvoid solve() {\n  int n, m;\n  cin >> n >> m;\n  vector<int> a, b;\n  vector<int> v(n);\n  for (int &e : v) {\n    cin >> e;\n  }\n  for (int &e : v) {\n    int x;\n    cin >> x;\n    if (x == 1) {\n      a.push_back(e);\n    } else {\n      b.push_back(e);\n    }\n  }\n  sort(a.rbegin(), a.rend());\n  sort(b.rbegin(), b.rend());\n  ll curSumA = 0;\n  int r = (int)b.size();\n  ll curSumB = accumulate(b.begin(), b.end(), 0ll);\n  int ans = INT_MAX;\n  for (int l = 0; l <= a.size(); l++) {\n    while (r > 0 && curSumA + curSumB - b[r - 1] >= m) {\n      r--;\n      curSumB -= b[r];\n    }\n    if (curSumB + curSumA >= m) {\n      ans = min(ans, 2 * r + l);\n    }\n    if (l != a.size()) {\n      curSumA += a[l];\n    }\n  }\n  cout << (ans == INT_MAX ? -1 : ans) << \"\\n\";\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "binary search",
      "dp",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1475",
    "index": "E",
    "title": "Advertising Agency",
    "statement": "Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of $n$ different bloggers. Blogger numbered $i$ has $a_i$ followers.\n\nSince Masha has a limited budget, she can only sign a contract with $k$ different bloggers. Of course, Masha wants her ad to be seen by as many people as possible. Therefore, she must hire bloggers with the maximum total number of followers.\n\nHelp her, find the number of ways to select $k$ bloggers so that the total number of their followers is maximum possible. Two ways are considered different if there is at least one blogger in the first way, which is not in the second way. Masha believes that all bloggers have different followers (that is, there is no follower who would follow two different bloggers).\n\nFor example, if $n=4$, $k=3$, $a=[1, 3, 1, 2]$, then Masha has two ways to select $3$ bloggers with the maximum total number of followers:\n\n- conclude contracts with bloggers with numbers $1$, $2$ and $4$. In this case, the number of followers will be equal to $a_1 + a_2 + a_4 = 6$.\n- conclude contracts with bloggers with numbers $2$, $3$ and $4$. In this case, the number of followers will be equal to $a_2 + a_3 + a_4 = 6$.\n\nSince the answer can be quite large, \\textbf{output it modulo $10^9+7$}.",
    "tutorial": "It is obvious that Masha will enter into agreements only with bloggers that have the most subscribers. You can sort all the bloggers and greedily select the prefix. Let $x$ - be the minimum number of subscribers for the hired blogger. Then we must hire all the bloggers who have more subscribers. Let $m$ - the number of bloggers who have more than $x$ subscribers, $cnt[x]$ - the number of bloggers who have exactly $x$ subscribers. Then we should select $k-m$ bloggers from $cnt[x]$. The number of ways to do this is equal to the binomial coefficient of $cnt[x]$ by $k-m$. You could calculate it by searching for the inverse element modulo. Then you could calculate the factorials and use the equality $\\binom n k = \\frac{n!}{k! \\cdot (n-k)!}$. Alternatively, you can use the equation $\\binom n k = \\binom {n-1} {k} + \\binom {n-1} {k-1}$ and calculate it using dynamic programming. This method is better known as the Pascal triangle.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\nint mod = 1e9 + 7;\n\nint fast_pow(int a, int p) {\n  int res = 1;\n  while (p) {\n    if (p % 2 == 0) {\n      a = a * 1ll * a % mod;\n      p /= 2;\n    } else {\n      res = res * 1ll * a % mod;\n      p--;\n    }\n  }\n  return res;\n}\n\nint fact(int n) {\n  int res = 1;\n  for (int i = 1; i <= n; i++) {\n    res = res * 1ll * i % mod;\n  }\n  return res;\n}\n\nint C(int n, int k) {\n  return fact(n) * 1ll * fast_pow(fact(k), mod - 2) % mod * 1ll * fast_pow(fact(n - k), mod - 2) % mod;\n}\n\nvoid solve() {\n  int n, k;\n  cin >> n >> k;\n  vector<int> cnt(n + 1);\n  for (int i = 0; i < n; i++) {\n    int x;\n    cin >> x;\n    cnt[x]++;\n  }\n  for (int i = n; i >= 0; i--) {\n    if (cnt[i] >= k) {\n      cout << C(cnt[i], k) << \"\\n\";\n      return;\n    } else {\n      k -= cnt[i];\n    }\n  }\n  cout << 1;\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "combinatorics",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1475",
    "index": "F",
    "title": "Unusual Matrix",
    "statement": "You are given two binary square matrices $a$ and $b$ of size $n \\times n$. A matrix is called binary if each of its elements is equal to $0$ or $1$. You can do the following operations on the matrix $a$ \\textbf{arbitrary} number of times (0 or more):\n\n- vertical xor. You choose the number $j$ ($1 \\le j \\le n$) and for all $i$ ($1 \\le i \\le n$) do the following: $a_{i, j} := a_{i, j} \\oplus 1$ ($\\oplus$ — is the operation xor (exclusive or)).\n- horizontal xor. You choose the number $i$ ($1 \\le i \\le n$) and for all $j$ ($1 \\le j \\le n$) do the following: $a_{i, j} := a_{i, j} \\oplus 1$.\n\nNote that the elements of the $a$ matrix change after each operation.\n\nFor example, if $n=3$ and the matrix $a$ is: $$ \\begin{pmatrix} 1 & 1 & 0 \\\\ 0 & 0 & 1 \\\\ 1 & 1 & 0 \\end{pmatrix} $$ Then the following sequence of operations shows an example of transformations:\n\n- vertical xor, $j=1$. $$ a= \\begin{pmatrix} 0 & 1 & 0 \\\\ 1 & 0 & 1 \\\\ 0 & 1 & 0 \\end{pmatrix} $$\n- horizontal xor, $i=2$. $$ a= \\begin{pmatrix} 0 & 1 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 1 & 0 \\end{pmatrix} $$\n- vertical xor, $j=2$. $$ a= \\begin{pmatrix} 0 & 0 & 0 \\\\ 0 & 0 & 0 \\\\ 0 & 0 & 0 \\end{pmatrix} $$\n\nCheck if there is a sequence of operations such that the matrix $a$ becomes equal to the matrix $b$.",
    "tutorial": "It is clear that the order of operations does not affect the final result, also it makes no sense to apply the same operation more than once (by the property of the xor operation). Let's construct a sequence of operations that will reduce the matrix $a$ to the matrix $b$ (if the answer exists). Let's try iterate over: will we use the operation \"horizontal xor\". Now, by the each element of the first line ($a_{1,j}$), we can understand whether it is necessary to apply the operation \"vertical xor\" (if $a_{1,j} \\ne b_{1,j}$). Let's apply all necessary operations \"vertical xor\". It remains clear whether it is necessary to apply the operation \"horizontal xor\" for $i$ ($2 \\le i \\le n$). Let's look at each element of the first column ($a_{i,1}$) by it you can understand whether it is necessary to apply the operation \"horizontal xor\" (if $a_{i, 1} \\ne b_{i,1}$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing pii = pair<int, int>;\n\nbool check(vector<vector<int>> a, vector<vector<int>> const &b) {\n  int n = (int) a.size();\n  for (int j = 0; j < n; j++) {\n    if (a[0][j] != b[0][j]) {\n      for (int i = 0; i < n; i++) {\n        a[i][j] ^= 1;\n      }\n    }\n  }\n  for (int i = 0; i < n; i++) {\n    int need_xor = (a[i][0] ^ b[i][0]);\n    for (int j = 1; j < n; j++) {\n      if (need_xor != (a[i][j] ^ b[i][j])) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<vector<int>> a(n, vector<int>(n));\n  vector<vector<int>> b(n, vector<int>(n));\n  for (int i = 0; i < n; i++) {\n    string s;\n    cin >> s;\n    for (int j = 0; j < n; j++) {\n      a[i][j] = s[j] - '0';\n    }\n  }\n  for (int i = 0; i < n; i++) {\n    string s;\n    cin >> s;\n    for (int j = 0; j < n; j++) {\n      b[i][j] = s[j] - '0';\n    }\n  }\n\n  for (int times = 0; times < 2; times++) {\n    if (check(a, b)) {\n      cout << \"YES\\n\";\n      return;\n    }\n    for (int j = 0; j < n; j++) {\n      a[0][j] ^= 1;\n    }\n  }\n  cout << \"NO\\n\";\n}\n\nint main() {\n  int test;\n  cin >> test;\n  while (test-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "2-sat",
      "brute force",
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1475",
    "index": "G",
    "title": "Strange Beauty",
    "statement": "Polycarp found on the street an array $a$ of $n$ elements.\n\nPolycarp invented his criterion for the beauty of an array. He calls an array $a$ beautiful if at least one of the following conditions must be met \\textbf{for each different pair of indices} $i \\ne j$:\n\n- $a_i$ is divisible by $a_j$;\n- or $a_j$ is divisible by $a_i$.\n\nFor example, if:\n\n- $n=5$ and $a=[7, 9, 3, 14, 63]$, then the $a$ array is not beautiful (for $i=4$ and $j=2$, none of the conditions above is met);\n- $n=3$ and $a=[2, 14, 42]$, then the $a$ array is beautiful;\n- $n=4$ and $a=[45, 9, 3, 18]$, then the $a$ array is not beautiful (for $i=1$ and $j=4$ none of the conditions above is met);\n\nUgly arrays upset Polycarp, so he wants to remove some elements from the array $a$ so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array $a$ beautiful.",
    "tutorial": "Let's calculate for each number $x$ how many times it occurs in the array $a$. Let's denote this number as $cnt_x$. Let's use the dynamic programming method. Let $dp(x)$ be equal to the maximum number of numbers not greater than $x$ such that for each pair of them one of the conditions above is satisfied. More formally, if $dp(x) = k$, then there exists numbers $b_1, b_2, \\ldots, b_k$ ($b_i \\leq x$) from the array $a$ such that for all $i \\ne j$ ($1 \\leq i, j \\leq k$) one of the conditions above is satisfied. Then to calculate $dp(x)$ you can use the following formula: $dp(x) = cnt(x) + \\max \\limits_{y = 1, x mod y = 0}^{x-1} dp(y)$ Note that to calculate $dp(x)$ you need to go through the list of divisors of $x$. For this, we use the sieve of Eratosthenes.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = (int) 2e5 + 100;\n\nint dp[N];\nint cnt[N];\n\nvoid solve() {\n  int n;\n  cin >> n;\n  fill(dp, dp + N, 0);\n  fill(cnt, cnt + N, 0);\n  for (int i = 0; i < n; i++) {\n    int x;\n    cin >> x;\n    cnt[x]++;\n  }\n  for (int i = 1; i < N; i++) {\n    dp[i] += cnt[i];\n    for (int j = 2 * i; j < N; j += i) {\n      dp[j] = max(dp[j], dp[i]);\n    }\n  }\n  cout << (n - *max_element(dp, dp + N)) << endl;\n}\n\nint main() {\n  int test;\n  cin >> test;\n  while (test-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "dp",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1476",
    "index": "A",
    "title": "K-divisible Sum",
    "statement": "You are given two integers $n$ and $k$.\n\nYou should create an array of $n$ \\textbf{positive integers} $a_1, a_2, \\dots, a_n$ such that the sum $(a_1 + a_2 + \\dots + a_n)$ is divisible by $k$ and maximum element in $a$ is minimum possible.\n\nWhat is the minimum possible maximum element in $a$?",
    "tutorial": "Let's denote $s$ as the sum of array $a$. From one side, since $s$ should be divisible by $k$ then we can say $s = cf \\cdot k$. From other side, since all $a_i$ are positive, then $s \\ge n$. It's quite obvious that the smaller $s$ - the smaller maximum $a_i$ so we need to find the smallest $cf$ that $cf \\cdot k \\ge n$. Then $cf = \\left\\lceil \\frac{n}{k} \\right\\rceil = \\left\\lfloor \\frac{n + k - 1}{k} \\right\\rfloor$. Now we now that $s = cf \\cdot k$ and we need to represent it as $a_1 + \\dots + a_n$ with maximum $a_i$ minimized. It's easy to prove by contradiction that maximum $a_i \\ge \\left\\lceil \\frac{s}{n} \\right\\rceil$. Moreover we can always construct such array $a$ that its sum is equal to $s$ and the maximum element is equal to $\\left\\lceil \\frac{s}{n} \\right\\rceil$. As a result, the answer is $\\left\\lceil \\frac{s}{n} \\right\\rceil = \\left\\lfloor \\frac{cf \\cdot k + n - 1}{n} \\right\\rfloor$, where $cf = \\left\\lfloor \\frac{n + k - 1}{k} \\right\\rfloor$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t; cin >> t;\n  while(t--) {\n    long long n, k;\n    cin >> n >> k;\n    \n    long long cf = (n + k - 1) / k;\n    k *= cf;\n    \n    cout << (k + n - 1) / n << endl;\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1476",
    "index": "B",
    "title": "Inflation",
    "statement": "You have a statistic of price changes for one product represented as an array of $n$ positive integers $p_0, p_1, \\dots, p_{n - 1}$, where $p_0$ is the initial price of the product and $p_i$ is how the price was increased during the $i$-th month.\n\nUsing these price changes you are asked to calculate the inflation coefficients for each month as the ratio of current price increase $p_i$ to the price at the start of this month $(p_0 + p_1 + \\dots + p_{i - 1})$.\n\nYour boss said you clearly that the inflation coefficients must not exceed $k$ %, so you decided to \\textbf{increase} some values $p_i$ in such a way, that all $p_i$ remain integers and the inflation coefficients for each month don't exceed $k$ %.\n\nYou know, that the bigger changes — the more obvious cheating. That's why you need to minimize the total sum of changes.\n\nWhat's the minimum total sum of changes you need to make all inflation coefficients not more than $k$ %?",
    "tutorial": "Suppose we decided to increase some $p_i$ by $x > 0$. How does it affect all inflation coefficients? Let's the $j$-th inflation coefficient be $cf_j$. We now that $cf_j = \\frac{p_j}{p_0 + \\dots + p_{j - 1}}$. If $j < i$, then $cf_j$ doesn't change. If $j > i$ then it's denominator increases by $x$ and $cf_j$ decreases. If $j = i$ then it's numerator increases and $cf_j$ increases as well. But, if we increase $p_{i - 1}$ instead of $p_i$ then all decreased $cf_j$ will decrease as well and also $cf_i$ will decrease. Finally, if we increase $p_0$ then all $cf_j$ decrease and there is no $cf_j$ that increases - so it's always optimal to increase only $p_0$. Now we need to calculate what is minimum $x$ we should add to $p_0$. There are two ways: we can either binary search this value $x$ knowing that $x = 100 \\cdot 10^9$ is always enough. Then we just need to check that all $cf_j \\le \\frac{k}{100}$ (that is equivalent to checking that $p_j \\cdot 100 \\le k \\cdot (x + p_0 + \\dots + p_{j - 1})$). Or we can note that each $cf_j = \\frac{p_j}{(p_0 + \\dots + p_{j - 1}) + x}$ and we need to make $cf_j \\le \\frac{k}{100}$ or that $100 \\cdot p_j - k \\cdot (p_0 + \\dots + p_{j - 1}) \\le k \\cdot x$ or $x \\ge \\left\\lceil \\frac{100 \\cdot p_j - k \\cdot (p_0 + \\dots + p_{j - 1})}{k} \\right\\rceil$. Since we should fulfill all conditions then we should take $x$ as maximum over all fractions. Since $(p_0 + \\dots + p_{j - 1})$ is just a prefix sum, we can check condition for each $cf_j$ in $O(1)$. It total, the time complexity is either $O(n)$ or $O(n \\log{n})$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\nconst int INF = int(1e9);\n\nint main() {\n  int t; cin >> t;\n  while(t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<int> p(n);\n    for (int i = 0; i < n; i++)\n      cin >> p[i];\n    \n    li x = 0;\n    li pSum = p[0];\n    for (int i = 1; i < n; i++) {\n      x = max(x, (100ll * p[i] - k * pSum + k - 1) / k);\n      pSum += p[i];\n    }\n    cout << x << endl;\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1476",
    "index": "C",
    "title": "Longest Simple Cycle",
    "statement": "You have $n$ chains, the $i$-th chain consists of $c_i$ vertices. Vertices in each chain are numbered independently from $1$ to $c_i$ along the chain. In other words, the $i$-th chain is the undirected graph with $c_i$ vertices and $(c_i - 1)$ edges connecting the $j$-th and the $(j + 1)$-th vertices for each $1 \\le j < c_i$.\n\nNow you decided to unite chains in one graph in the following way:\n\n- the first chain is skipped;\n- the $1$-st vertex of the $i$-th chain is connected by an edge with the $a_i$-th vertex of the $(i - 1)$-th chain;\n- the last ($c_i$-th) vertex of the $i$-th chain is connected by an edge with the $b_i$-th vertex of the $(i - 1)$-th chain.\n\n\\begin{center}\n{\\small Picture of the first test case. Dotted lines are the edges added during uniting process}\n\\end{center}\n\nCalculate the length of the longest simple cycle in the resulting graph.\n\nA simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.",
    "tutorial": "Suppose, we've built the graph and chosen any simple cycle. Due to the nature of the graph, any simple cycle right part is part of one of the chains. So, let's for each chain calculate the longest simple path with its right part on this chain and denote it as $len_i$. Obviously, $len_1 = 0$. Now, let's look at chain $i$. If we go along the cycle in both ways, we will step to vertices $a_i$ and $b_i$ of the previous chain. If $a_i = b_i$ then we closed cycle and it's the only possible cycle, so $len_i = c_i + 1$. Otherwise, we can either go from $a_i$ and $b_i$ and meet each other closing the cycle with part of the $(i - 1)$-th chain between $a_i$-th and $b_i$-th vertices - this part has $|a_i - b_i|$ edges and our cycle will have length $c_i + 1 + |a_i - b_i|$. But if we decide to go in different ways, then we will meet the first and the last vertices of the $(i - 1)$-th chain. After that, we'll go to the $a_{i - 1}$-th and the $b_{i - 1}$-th vertices of $(i - 2)$-th chain and will make almost the same choice. But, instead of recurrently solving the same problem, we can note that, in fact, we took a cycle that ends at the $(i - 1)$-th chain, erased the part between vertices $a_i$ and $b_i$, and merged it with our $i$-th chain part, so the length of this merged cycle will be equal to $c_i + 1 + len_{i - 1} - |a_i - b_i|$. Since we maximize $len_i$ we just choose, what part: $|a_i - b_i|$ or $len_{i - 1} - |a_i - b_i|$ is longer and take it. As a result, we can iterate from left to right, calculate all $len_i$ and print the maximum among them.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef long long li;\n\nint main() {\n  int t;\n  cin >> t;\n\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> c(n), a(n), b(n);\n    for (int i = 0; i < n; i++)\n      cin >> c[i];\n    for (int i = 0; i < n; i++)\n      cin >> a[i];\n    for (int i = 0; i < n; i++)\n      cin >> b[i];\n    \n    li ans = 0;\n    li lstLen = 0;\n    for (int i = 1; i < n; i++) {\n      li curLen = c[i] + 1ll + abs(a[i] - b[i]);\n      if (a[i] != b[i])\n        curLen = max(curLen, c[i] + 1ll + lstLen - abs(a[i] - b[i]));\n      ans = max(ans, curLen);\n      lstLen = curLen;  \n    }\n    cout << ans << endl;\n  }\n  return 0;\n};",
    "tags": [
      "dp",
      "graphs",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1476",
    "index": "D",
    "title": "Journey",
    "statement": "There are $n + 1$ cities, numbered from $0$ to $n$. $n$ roads connect these cities, the $i$-th road connects cities $i - 1$ and $i$ ($i \\in [1, n]$).\n\nEach road has a direction. The directions are given by a string of $n$ characters such that each character is either L or R. If the $i$-th character is L, it means that the $i$-th road initially goes from the city $i$ to the city $i - 1$; otherwise it goes from the city $i - 1$ to the city $i$.\n\nA traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler \\textbf{must} go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city $i$ to the city $i + 1$, it is possible to travel from $i$ to $i + 1$, but not from $i + 1$ to $i$. After the traveler moves to a neighboring city, \\textbf{all} roads change their directions \\textbf{to the opposite ones}. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to.\n\nThe goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city $i$, calculate the maximum number of different cities the traveler can visit during \\textbf{exactly one journey} if they start in the city $i$.",
    "tutorial": "There are two key observations to this problem: after each pair of moves, the directions go back to the original ones; after each move, we can immediately go back (and combining these observations, we can derive that if we go from city $i$ to some other city $j$, we can always go back). One of the solutions we can write using these observations is to build an undirected graph on $2n+2$ vertices. Each vertex represents a pair $(v, k)$, where $v$ is the city we are currently staying in, and $k$ is the number of moves we made, modulo $2$. Since each move is to a neighboring city, each vertex $(v, 0)$ is unreachable from $(v, 1)$, and vice versa. And since we can always go back, and each pair of steps doesn't change the directions, this graph is actually an undirected one. So, we can find the connected components of this graph using DFS/BFS/DSU, and for each city $v$, print the size of the component the vertex $(v, 0)$ belongs to. Another solution is to find the leftmost and the rightmost city reachable from each city. For example, finding the leftmost reachable city can be done with the following dynamic programming: let $dp_i$ be the leftmost city reachable from $i$. Then, if we can't go left from $i$, $dp_i = i$; if we can make only one step to the left from $i$, $dp_i = i - 1$; and if we can make two steps, we can take the answer from the city $i - 2$: $dp_i = dp_{i - 2}$. The same approach can be used to calculate the rightmost reachable city.",
    "code": "t = int(input())\n\nfor _ in range(t):\n    n = int(input())\n    s = input()\n    dpl = [i for i in range(n + 1)]\n    dpr = [i for i in range(n + 1)]\n    for i in range(n + 1):\n        if i == 0 or s[i - 1] == 'R':\n            dpl[i] = i\n        elif i == 1 or s[i - 2] == 'L':\n            dpl[i] = i - 1\n        else:\n            dpl[i] = dpl[i - 2]\n    for i in range(n, -1, -1):\n        if i == n or s[i] == 'L':\n            dpr[i] = i\n        elif i == n - 1 or s[i + 1] == 'R':\n            dpr[i] = i + 1\n        else:\n            dpr[i] = dpr[i + 2]\n    ans = [(dpr[i] - dpl[i]) + 1 for i in range(n + 1)]\n    print(*ans)",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1476",
    "index": "E",
    "title": "Pattern Matching",
    "statement": "You are given $n$ patterns $p_1, p_2, \\dots, p_n$ and $m$ strings $s_1, s_2, \\dots, s_m$. Each pattern $p_i$ consists of $k$ characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string $s_j$ consists of $k$ lowercase Latin letters.\n\nA string $a$ matches a pattern $b$ if for each $i$ from $1$ to $k$ either $b_i$ is a wildcard character or $b_i=a_i$.\n\nYou are asked to rearrange the patterns in such a way that the first pattern the $j$-th string matches is $p[mt_j]$. You are allowed to leave the order of the patterns unchanged.\n\nCan you perform such a rearrangement? If you can, then print any valid order.",
    "tutorial": "Let's write down the indices of the pattern that the $j$-th string matches. If $mt_j$ is not among these, then the answer is NO. Otherwise, all the patterns except $mt_j$ should go in the resulting ordering after $mt_j$. Consider that as a graph. Let's add an edge from $mt_j$ to each of the matches. If you add the edges for all the strings, then the topological ordering of the graph will give you the valid result. If the graph has any cycles in it (you can't topsort it), then there is no answer. To find all the patterns we can use the fact that $k$ is rather small. Consider all the $2^k$ binary masks of length $k$. Each mask can correspond to a set of positions in the string that are replaced with wildcards. Now, if there is a pattern that is exactly equal to the string with the fixed set of positions replaced by wildcards, then that pattern is a match. To search for an exact match, you can either store all patterns in a map beforehand (or in a sorted array) or build a trie of them. The second version is faster by a factor of $\\log n$ but both solutions should pass easily. Overall complexity: $O(nk \\log n + mk \\cdot 2^k \\log n)$ or $O(nk + m \\cdot 2^k)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct pattern{\n  string s;\n  int i;\n};\n\nbool operator <(const pattern &a, const pattern &b){\n  return a.s < b.s;\n}\n\nvector<vector<int>> g;\nvector<int> used, ord;\nbool cyc;\n\nvoid ts(int v){\n  used[v] = 1;\n  for (int u : g[v]){\n    if (used[u] == 0)\n      ts(u);\n    else if (used[u] == 1)\n      cyc = true;\n    if (cyc)\n      return;\n  }\n  used[v] = 2;\n  ord.push_back(v);\n}\n\nstruct node{\n  int nxt[28];\n  int term;\n  node(){\n    memset(nxt, -1, sizeof(nxt));\n    term = -1;\n  }\n};\n\nvector<node> trie;\n\nvoid add(const string &s, int i){\n  int cur = 0;\n  for (char c : s){\n    int x = c - '_';\n    if (trie[cur].nxt[x] == -1){\n      trie[cur].nxt[x] = trie.size();\n      trie.push_back(node());\n    }\n    cur = trie[cur].nxt[x];\n  }\n  trie[cur].term = i;\n}\n\nbool check(int i, int v, const string &s, int mt){\n  if (i == int(s.size())){\n    assert(trie[v].term != -1);\n    if (trie[v].term != mt)\n      g[mt].push_back(trie[v].term);\n    else\n      return true;\n    return false;\n  }\n  bool res = false;\n  if (trie[v].nxt[s[i] - '_'] != -1 && check(i + 1, trie[v].nxt[s[i] - '_'], s, mt))\n    res = true;\n  if (trie[v].nxt[0] != -1 && check(i + 1, trie[v].nxt[0], s, mt))\n    res = true;\n  return res;\n}\n\nint main() {\n  cin.tie(0);\n  ios_base::sync_with_stdio(false);\n  trie = vector<node>(1);\n  int n, m, k;\n  cin >> n >> m >> k;\n  g.assign(n, vector<int>());\n  forn(i, n){\n    string cur;\n    cin >> cur;\n    add(cur, i);\n  }\n  pattern nw;\n  nw.s = string(k, '_');\n  forn(i, m){\n    string cur;\n    int mt;\n    cin >> cur >> mt;\n    if (!check(0, 0, cur, mt - 1)){\n      cout << \"NO\\n\";\n      return 0;\n    }\n  }\n  used.assign(n, 0);\n  cyc = false;\n  ord.clear();\n  forn(i, n) if (!used[i]){\n    ts(i);\n    if (cyc){\n      cout << \"NO\\n\";\n      return 0;\n    }\n  }\n  reverse(ord.begin(), ord.end());\n  cout << \"YES\\n\";\n  forn(i, n)\n    cout << ord[i] + 1 << \" \";\n  cout << \"\\n\";\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "dfs and similar",
      "graphs",
      "hashing",
      "sortings",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1476",
    "index": "F",
    "title": "Lanterns",
    "statement": "There are $n$ lanterns in a row. The lantern $i$ is placed in position $i$ and has power equal to $p_i$.\n\nEach lantern can be directed to illuminate either some lanterns to the left or some lanterns to the right. If the $i$-th lantern is turned to the left, it illuminates all such lanterns $j$ that $j \\in [i - p_i, i - 1]$. Similarly, if it is turned to the right, it illuminates all such lanterns $j$ that $j \\in [i + 1, i + p_i]$.\n\nYour goal is to choose a direction for each lantern so each lantern is illuminated by at least one other lantern, or report that it is impossible.",
    "tutorial": "The main idea of the solution is to calculate the following dynamic programming: $dp_i$ is the maximum prefix we can fully cover with $i$ first lanterns. Let's look at how can we solve it in $O(n^2)$ with this kind of dynamic programming. First of all, let's write it forward. Which transitions from $dp_i$ do we have? iterate on the lantern facing left that will cover the lantern $dp_i + 1$. Let this lantern be $j$. It should cover all lanterns in $[dp_i + 1, j - 1]$, so all lanterns from $[i, j)$ can be turned to the right (and we need a max query to determine the new covered prefix); if $dp_i > i$ (lantern $i$ is already covered), we can just extend the prefix by turning the $i$-th lantern to the right. Note that turning it to the right when it is not covered yet will be modeled by the first transition. It is obviously $O(n^2)$, how can we optimize it? Let's write this dynamic programming backward. The second transition is changed to backward dp easily, what about the first one? Suppose we want to turn some lantern $i$ to the left. Let's iterate on the prefix $j$ that we will \"connect\" to it; for this prefix, $dp_j$ should be at least $i - p_i - 1$, and we update $dp_i$ with the maximum of $i - 1$ (since it is covered by lantern $i$) and the result of max query on $[j + 1, i - 1]$. In fact, we need only one such prefix - the one with the minimum $j$ among those which have $dp_j \\ge i - p_i - 1$. So, we build a minimum segment tree where each pair $(i, dp_i)$ is interpreted as the value of $i$ in position $dp_i$, and with min query on the suffix from $i - p_i - 1$ we find this optimal prefix, from which we should update (and to update, we can use any DS that allows max queries on segment - in my solution, it's another segment tree).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = int(1e9);\n\nstruct segTree\n{\n    int n;\n    bool mx;\n    vector<int> t;\n\n    void fix(int v)\n    {\n        t[v] = (mx ? max(t[v * 2 + 1], t[v * 2 + 2]) : min(t[v * 2 + 1], t[v * 2 + 2]));\n    }\n\n    void build(int v, int l, int r)\n    {\n        if(l == r - 1)\n            t[v] = (mx ? -INF : INF);\n        else\n        {\n            int m = (l + r) / 2;\n            build(v * 2 + 1, l, m);\n            build(v * 2 + 2, m, r);\n            fix(v);\n        }\n    }\n\n    void upd(int v, int l, int r, int pos, int val)\n    {\n        if(l == r - 1)\n            t[v] = (mx ? max(t[v], val) : min(t[v], val));\n        else\n        {\n            int m = (l + r) / 2;\n            if(pos < m)\n                upd(v * 2 + 1, l, m, pos, val);\n            else\n                upd(v * 2 + 2, m, r, pos, val);\n            fix(v);\n        }\n    }\n\n    int get(int v, int l, int r, int L, int R)\n    {\n        if(L >= R)\n            return (mx ? -INF : INF);\n        if(l == L && r == R)\n            return t[v];\n        int m = (l + r) / 2;\n        int lf = get(v * 2 + 1, l, m, L, min(R, m));\n        int rg = get(v * 2 + 2, m, r, max(m, L), R);\n        return (mx ? max(lf, rg) : min(lf, rg));\n    }\n\n    void upd(int pos, int val)\n    {\n        upd(0, 0, n, pos, val);\n    }\n\n    int get(int L, int R)\n    {\n        return get(0, 0, n, L, R);\n    }\n\n    void build()\n    {\n        return build(0, 0, n);\n    }\n\n    segTree() {};\n    segTree(int n, bool mx) : n(n), mx(mx)\n    {\n        t.resize(4 * n);\n    }\n};\n\nint main()\n{\n    int t;\n    scanf(\"%d\", &t);\n    for(int _ = 0; _ < t; _++)\n    {\n        int n;\n        scanf(\"%d\", &n);\n        vector<int> p(n);\n        for(int i = 0; i < n; i++)\n            scanf(\"%d\", &p[i]);\n        vector<int> dp(n + 1, -INF);\n        vector<int> par(n + 1, -2);\n        dp[0] = 0;\n        par[0] = -1;\n        vector<int> lf(n), rg(n);\n        for(int i = 0; i < n; i++)\n        {\n            lf[i] = max(1, i - p[i] + 1);\n            rg[i] = min(n, i + p[i] + 1);\n        }\n        segTree sn(n + 1, false);        \n        segTree sx(n, true);\n        sn.build();\n        sx.build();\n        for(int i = 0; i < n; i++)\n            sx.upd(i, rg[i]);\n        sn.upd(0, 0);\n        for(int i = 1; i <= n; i++)\n        {\n            int j = i - 1;\n            int k = lf[j] - 1;\n            \n            int m = sn.get(k, n + 1);                 \n            if(m != INF)\n            {\n                int nval = max(sx.get(m, i - 1), i - 1);\n                if(nval > dp[i])\n                {\n                    dp[i] = nval;\n                    par[i] = m;\n                }\n            }\n            if(dp[j] >= i && max(dp[j], rg[j]) > dp[i])\n            {\n                dp[i] = max(dp[j], rg[j]);\n                par[i] = -1;\n            }\n            if(dp[j] > dp[i])\n            {\n                dp[i] = dp[j];\n                par[i] = -1;\n            }\n            sn.upd(dp[i], i);                \n        }\n        if(dp[n] != n)\n            puts(\"NO\");\n        else\n        {\n            puts(\"YES\");\n            string ans;\n            int cur = n;\n            while(cur != 0)\n            {\n                if(par[cur] == -1)\n                {\n                    cur--;\n                    ans += \"R\";\n                }\n                else\n                {\n                    int pcur = par[cur];\n                    int diff = cur - pcur;\n                    ans += \"L\";\n                    for(int j = 0; j < diff - 1; j++)\n                        ans += \"R\";\n                    cur = pcur;    \n                }\n            }\n            reverse(ans.begin(), ans.end());\n            puts(ans.c_str());\n        }\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1476",
    "index": "G",
    "title": "Minimum Difference",
    "statement": "You are given an integer array $a$ of size $n$.\n\nYou have to perform $m$ queries. Each query has one of two types:\n\n- \"$1$ $l$ $r$ $k$\" — calculate the minimum value $dif$ such that there are exist $k$ \\textbf{distinct} integers $x_1, x_2, \\dots, x_k$ such that $cnt_i > 0$ (for every $i \\in [1, k]$) and $|cnt_i - cnt_j| \\le dif$ (for every $i \\in [1, k], j \\in [1, k]$), where $cnt_i$ is the number of occurrences of $x_i$ in the subarray $a[l..r]$. If it is impossible to choose $k$ integers, report it;\n- \"$2$ $p$ $x$\" — assign $a_{p} := x$.",
    "tutorial": "Let's consider a problem without queries of the second type. Now we can try to solve the problem using Mo's algorithm. Let's maintain array $cnt_i$ - the number of occurrences of $i$ on the current segment and array $ord$ - array $cnt$ sorted in descending order. Let's take a look at how we should handle adding an element equal to $x$. Surely, we should increase $cnt_x$ by $1$, but now we should erase an element equal to $cnt_x-1$ from the array $ord$ and insert an element $cnt_x$ is such a way that the array is still sorted. Instead, we can increase the leftmost element equal to $cnt_x-1$ by $1$. Similarly, we can handle deleting an element (decrease the rightmost element equal to $cnt_x$ by $1$). In order to quickly find the leftmost (rightmost) element equal to $x$, we can store the left and the right bounds of the array $ord$ where all the numbers are equal to $x$. To answer the query of type $1$, we should find two elements in the $ord$ array at distance $k$ whose absolute difference is minimal. Since the size of the array $ord$ (without zero elements) is $O(n)$, we can't look at the whole array. But using the fact that there are no more than $O(\\sqrt{n})$ different values in the $ord$ array, we can create an auxiliary array of pairs $(value, cnt)$ (the value from the array $ord$ and the number of occurrences of that value). In such an array, we need to find a subarray where the sum of the second elements in the pairs is at least $k$, and the absolute difference between the first elements in the pairs is minimal. That can be solved using standard two pointers method in $O(\\sqrt{n})$. The total complexity of the solution is $O(n\\sqrt{n})$. In fact, we can use Mo's algorithm even with updates. But its complexity is $O(n^{\\frac{5}{3}} + m\\sqrt{n})$. You can read the editorial of the problem 940F on Codeforces or the following blog to learn about processing updates in Mo: https://codeforces.com/blog/entry/72690",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\ntypedef pair<int, int> pt;\n\nconst int N = 100 * 1000 + 13;\nconst int P = 2000;\n\nstruct query {\n  int t, l, r, k, i;\n};\n\nint main() {\n  int n, m;\n  scanf(\"%d%d\", &n, &m);\n  vector<int> a(n);\n  forn(i, n) scanf(\"%d\", &a[i]);\n  \n  vector<query> q;\n  vector<array<int, 3>> upd;\n  \n  forn(i, m) {\n    int tp;\n    scanf(\"%d\", &tp);\n    if (tp == 1) {\n      int l, r, k;\n      scanf(\"%d%d%d\", &l, &r, &k);\n      q.push_back({sz(upd), l - 1, r - 1, k, sz(q)});\n    } else {\n      int p, x;\n      scanf(\"%d%d\", &p, &x); --p;\n      upd.push_back({p, a[p], x});\n      a[p] = x;\n    }\n  }\n  \n  sort(q.begin(), q.end(), [](const query &a, const query &b) {\n    if (a.t / P != b.t / P)\n      return a.t < b.t;\n    if (a.l / P != b.l / P)\n      return a.l < b.l;\n    if ((a.l / P) & 1)\n      return a.r < b.r;\n    return a.r > b.r; \n  });\n  \n  for (int i = sz(upd) - 1; i >= 0; --i)\n    a[upd[i][0]] = upd[i][1];\n  \n  vector<int> cnt(N), ord(N);\n  vector<pt> bounds(N, {N, 0});\n  bounds[0] = {0, N - 1};\n  int L = 0, R = -1, T = 0;\n  \n  auto add = [&](int x) {\n    int c = cnt[x];\n    ++ord[bounds[c].x];\n    bounds[c + 1].y = bounds[c].x;\n    if (bounds[c + 1].x == N)\n      bounds[c + 1].x = bounds[c].x;\n    if (bounds[c].x == bounds[c].y)\n      bounds[c].x = N - 1;\n    ++bounds[c].x;\n    ++cnt[x];\n  };\n  \n  auto rem = [&](int x) {\n    int c = cnt[x];\n    --ord[bounds[c].y];\n    if (bounds[c - 1].x == N)\n      bounds[c - 1].y = bounds[c].y;\n    bounds[c - 1].x = bounds[c].y;\n    if (bounds[c].x == bounds[c].y)\n      bounds[c].x = N;\n    --bounds[c].y;\n    --cnt[x];\n  };\n  \n  auto apply = [&](int i, int fl) {\n    int p = upd[i][0];\n    int x = upd[i][fl + 1];\n    if (L <= p && p <= R) {\n      rem(a[p]);\n      add(x);\n    }\n    a[p] = x;\n  };\n  \n  vector<int> ans(sz(q));\n  \n  for (auto qr : q) {\n    int t = qr.t, l = qr.l, r = qr.r, k = qr.k;\n    while (T < t) apply(T++, 1);\n    while (T > t) apply(--T, 0);\n    while (R < r) add(a[++R]);\n    while (L > l) add(a[--L]);\n    while (R > r) rem(a[R--]);\n    while (L < l) rem(a[L++]);\n    \n    int res = N;\n    for (int i = 0, j = 0, sum = 0; i < N && ord[i] > 0; i = bounds[ord[i]].y + 1) {\n      while (j < N && ord[j] > 0 && sum < k) {\n        sum += bounds[ord[j]].y - bounds[ord[j]].x + 1;\n        j = bounds[ord[j]].y + 1;\n      }\n      if (sum >= k) res = min(res, ord[i] - ord[j - 1]);\n      sum -= bounds[ord[i]].y - bounds[ord[i]].x + 1;\n    }\n    if (res == N) res = -1;\n    ans[qr.i] = res;\n  }\n  \n  for (int x : ans) printf(\"%d\\n\", x);\n}",
    "tags": [
      "data structures",
      "hashing",
      "sortings",
      "two pointers"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1477",
    "index": "A",
    "title": "Nezzar and Board",
    "statement": "$n$ \\textbf{distinct} integers $x_1,x_2,\\ldots,x_n$ are written on the board. Nezzar can perform the following operation multiple times.\n\n- Select two integers $x,y$ (not necessarily distinct) on the board, and write down $2x-y$. Note that you don't remove selected numbers.\n\nNow, Nezzar wonders if it is possible to have his favorite number $k$ on the board after applying above operation multiple times.",
    "tutorial": "Let's first assume that $x_1=0$ (Otherwise, we could subtract $x_1$ for $x_1,x_2,\\ldots,x_n$ and $k$). We will now prove that the answer is \"YES\" if and only if $k$ can be divided by $g=\\gcd(x_2,x_3,\\ldots,x_n)$. One direction is straightforward. Note that any number written on the board should be divisible by $g$, which follows from the fact that $g|x, g|y \\implies g|2x-y$. It only remains to prove that for any $x$ divisible by $g$, we could write down $x$ on the board. We will prove it by induction on $n$. Base case ($n=2$) is obvious. Let $g_0=\\gcd(x_2,x_3,\\ldots,x_{n-1})$. By Bézout's Theorem, there exists integers $s,t$ such that $g_0 s-x_n t = g$. By induction, we could write down $g_0$ on the board, and trivially $x_n t$ can be written on the board. Therefore, we could write down $g$ applying operation recursively.",
    "code": "#include<bits/stdc++.h>\n#define int long long\nusing namespace std;\n \nconst int maxn=200007;\nint t;\nint n,k;\nint x[maxn];\n \nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>t;\n    while (t--){\n        cin>>n>>k;\n        for (int i=0;i<n;++i) cin>>x[i];\n        sort(x,x+n);\n        int g=0;\n        for (int i=1;i<n;++i){\n            g=__gcd(g,x[i]-x[0]);\n        }\n        if ((k-x[0])%g) cout<<\"NO\\n\";\n        else cout<<\"YES\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1477",
    "index": "B",
    "title": "Nezzar and Binary String",
    "statement": "Nezzar has a binary string $s$ of length $n$ that he wants to share with his best friend, Nanako. Nanako will spend $q$ days inspecting the binary string. At the same time, Nezzar wants to change the string $s$ into string $f$ during these $q$ days, because it looks better.\n\nIt is known that Nanako loves consistency so much. On the $i$-th day, Nanako will inspect a segment of string $s$ from position $l_i$ to position $r_i$ inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.\n\nAfter this inspection, at the $i$-th night, Nezzar can secretly change \\textbf{strictly less} than half of the characters in the segment from $l_i$ to $r_i$ inclusive, otherwise the change will be too obvious.\n\nNow Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string $f$ at the end of these $q$ days and nights.",
    "tutorial": "The operations can be described backward: Iterate days in reverse order and start with $f$. In $i$-th day, if there is a strict majority of $0$s or $1$s between $l_i$ and $r_i$, change ALL element inside the range to be the majority. Otherwise, declare that the operation failed. We can see that the \"backward\" operation is deterministic, so we can compute the source string from destination string alone and check if the source string computed equal to $s$. To simulate the operations, We need to support two kind of operations: range query on sum, and range assignment Which can be simulated using e.g. lazy segment tree. Time complexity: $O((q + n) \\log{n})$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n#define rep(i,n) for (int i=0;i<(int)(n);++i)\n#define rep1(i,n) for (int i=1;i<=(int)(n);++i)\n#define range(x) begin(x), end(x)\n#define sz(x) (int)(x).size()\n#define pb push_back\n#define F first\n#define S second\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n \nconst int maxn=200007;\nset<int> seg; // segment: [seg[i],seg[i+1])\nint n,q,t,prv;\nint l[maxn],r[maxn];\nbool val[maxn];\nstring s;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>t;\n    while (t--){\n        cin>>n>>q;\n        cin>>s;\n        rep(i,q) cin>>l[i]>>r[i], l[i]--;\n        reverse(l,l+q), reverse(r,r+q);\n        seg.clear();\n        rep(i,n) seg.insert(i), val[i]=s[i]-'0';\n        seg.insert(n);\n        auto add=[&](int u){\n            if (seg.find(u)==seg.end()){\n                auto ret=*prev(seg.upper_bound(u));\n                val[u]=val[ret];\n                seg.insert(u);\n            }\n        };\n        rep(i,q){\n            add(l[i]), add(r[i]);\n            vi remv;\n            remv.clear();\n            int sum[2];\n            memset(sum,0,sizeof(sum));\n            auto iter=seg.find(l[i]);\n            while (1){\n                if (*iter==r[i]) break;\n                int prev=*iter;\n                iter=next(iter);\n                if (*iter<r[i]) remv.pb(*iter);\n                sum[val[prev]]+=*iter-prev;\n            }\n            if (sum[0]==sum[1]){\n                cout<<\"-\\n\";\n                goto cont;\n            }\n            if (sum[0]<sum[1]) val[l[i]]=1;\n            else val[l[i]]=0;\n            for (auto c:remv) seg.erase(c);\n        }\n        prv=0;\n        for (auto c:seg){\n            if (!c) continue;\n            for (int i=prv;i<c;++i) cout<<val[prv];\n            prv=c;\n        }\n        cout<<\"\\n\";\n        cont:;\n    }\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1477",
    "index": "C",
    "title": "Nezzar and Nice Beatmap",
    "statement": "Nezzar loves the game osu!.\n\nosu! is played on beatmaps, which can be seen as an array consisting of \\textbf{distinct} points on a plane. A beatmap is called nice if for any three consecutive points $A,B,C$ listed in order, the angle between these three points, centered at $B$, is \\textbf{strictly less than} $90$ degrees.\n\n\\begin{center}\n{\\small Points $A,B,C$ on the left have angle less than $90$ degrees, so they can be three consecutive points of a nice beatmap; Points $A',B',C'$ on the right have angle greater or equal to $90$ degrees, so they cannot be three consecutive points of a nice beatmap.}\n\\end{center}\n\nNow Nezzar has a beatmap of $n$ \\textbf{distinct} points $A_1,A_2,\\ldots,A_n$. Nezzar would like to reorder these $n$ points so that the resulting beatmap is nice.\n\nFormally, you are required to find a permutation $p_1,p_2,\\ldots,p_n$ of integers from $1$ to $n$, such that beatmap $A_{p_1},A_{p_2},\\ldots,A_{p_n}$ is nice. If it is impossible, you should determine it.",
    "tutorial": "There are two different approaches to solve this task. Furthest Points Pick an arbitrary point, and in each iteration, select the furthest point from previously chosen point among all available points. Indeed, we can prove the correctness by contradiction. Insertion Sorting Notice that in any triangle (possibly degenerate), there exists at most one obtuse angle or right angle in this triangle. Therefore, we may build our permutation using modified version of insertion sort (it suffices to substitute comparing operator). We believe that time complexity for the latter approach is better than $O(n^2)$. However, we fail to find a proof or counterexample for it. It would be grateful if someone could figure it out and inform us about it!",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int maxn=6007;\n \nint n;\nint x[maxn],y[maxn];\nvector<int> perm;\nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>n;\n    for (int i=0;i<n;++i) cin>>x[i]>>y[i];\n    for (int i=0;i<n;++i){\n        perm.push_back(i);\n        for (int j=i;j>1;--j){\n            if (1ll*(x[perm[j]]-x[perm[j-1]])*(x[perm[j-1]]-x[perm[j-2]])+1ll*(y[perm[j]]-y[perm[j-1]])*(y[perm[j-1]]-y[perm[j-2]])>=0){\n                swap(perm[j],perm[j-1]);\n            }\n            else{\n                break;\n            }\n        }\n    }\n    for (auto c:perm) cout<<c+1<<\" \";\n       \n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1477",
    "index": "D",
    "title": "Nezzar and Hidden Permutations",
    "statement": "Nezzar designs a brand new game \"Hidden Permutations\" and shares it with his best friend, Nanako.\n\nAt the beginning of the game, Nanako and Nezzar both know integers $n$ and $m$. The game goes in the following way:\n\n- Firstly, Nezzar hides two permutations $p_1,p_2,\\ldots,p_n$ and $q_1,q_2,\\ldots,q_n$ of integers from $1$ to $n$, and Nanako secretly selects $m$ unordered pairs $(l_1,r_1),(l_2,r_2),\\ldots,(l_m,r_m)$;\n- After that, Nanako sends his chosen pairs to Nezzar;\n- On receiving those $m$ unordered pairs, Nezzar checks if there exists $1 \\le i \\le m$, such that $(p_{l_i}-p_{r_i})$ and $(q_{l_i}-q_{r_i})$ have different signs. If so, Nezzar instantly loses the game and gets a score of $-1$. Otherwise, the score Nezzar gets is equal to the number of indices $1 \\le i \\le n$ such that $p_i \\neq q_i$.\n\nHowever, Nezzar accidentally knows Nanako's unordered pairs and decides to take advantage of them. Please help Nezzar find out two permutations $p$ and $q$ such that the score is maximized.",
    "tutorial": "We can describe the problem in graph theory terms: We are given a graph $G$ of $n$ vertices and $m$ edge. The $i$-th edge connects vertices $l_i$ and $r_i$. We need to write down two numbers on each vertices, on $i$-th vertex we write $p_i$ and $q_i$ on it, so that: $p$ and $q$ forms a permutation from $1$ to $n$, For each edge $(u,v)$, the relative order between $p_u$ and $p_v$ must be the same as between $q_u$ and $q_v$. We want to maximize the number of vertices $u$, so that $p_u \\neq q_u$. We can observe the following: For any vertex $u$ with degree $n-1$, $p_u = q_u$. Proof: For such vertex $u$, let $p_u = k$. Then, there are exactly $k - 1$ neighbors of $u$ that has its $p$-number smaller than $u$. Similarly, let $q_u = k'$. Then, there are exactly $k' - 1$ neighbors of $u$ that has its $q$-number smaller than $u$. Since the relative order between $u$ and its neighbors must be the same across $p$ and $q$, $k' - 1 = k - 1$, which leads to $k' = k$. We can assign those numbers with any unused number and delete them from the graph. Now we will consider only vertices with degree $< m-1$, where $m$ is the number of remaining vertices. We claim that the maximum number of differing position to be exactly $m$. As all vertices have degree $< m-1$, it is easier to consider the complement graph $G'$, where $(u,v)$ in $G'$ is connected if and only if $(u,v)$ is not connected in $G$. Notice that $G'$ consists of connected components and each vertex has at least one neighbor. We will focus on a single connected component. Let us find any spanning tree of this particular component. If the spanning tree is astar, Let the center of star be $u$ and the other vertices be $v_1, v_2, \\cdots v_k$. Then, the following is a valid assignment: $p_u = 1, q_u = k + 1$ $p_{v_i} = i + 1, q_{v_i} = i$ for $1 \\leq i \\leq k$ Otherwise, we claim that we can decompose any tree into different connected stars with at least two nodes each. If we can do so, we can assign numbers $1, 2, \\cdots k_1$ to first star with $k_1$ nodes, $k_1 + 1, k_1 + 2, \\cdots k_1 + k_2$ to second star with $k_2$ nodes and so on. Notice that the relative order between nodes of different stars never change. The remaining part is to decompose tree into stars. There are a lot of algorithms to do so, one of them would be: If any neighbors of $u$ are unassigned, assign $u$ to be the center of new star component along with all unassigned neighbors of $u$. Otherwise, notice that all neighbors of $u$ is now a non-center member of some star component. Pick up any of $u$'s neighbor, $v$. If the star component of $v$ has at least two non-center nodes, remove $v$ from its original star component and make node $u$ and node $v$ a star component centered at $u$. Otherwise, make $v$ to be the center of its star component and add $u$ to it. We can see that the algorithm produces star components of at least two nodes each, and therefore we can apply the assignment of numbers to each stars individually and concat the results. In the end, all nodes will have their $p$ and $q$ assigned differently. It is possible to find all the needed spanning tree in $O((n + m) \\log n)$ time. Then, it takes $O(n)$ total time to compute answers for all trees. Therefore, time complexity is $O((n + m) \\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int maxn=500007;\n \nstruct info{\n    int idx,val;\n    friend bool operator<(info u,info v){\n        return u.val==v.val?u.idx<v.idx:u.val<v.val;\n    }\n};\n \nstruct stars{\n    int rt;\n    vector<int> leaves;\n};\nset<int> rv; // remained vertices\nset<int> g[maxn]; // original graph\nset<int> t[maxn]; // dfs tree\nset<info> d;\nint deg[maxn];\nint n,m;\nint perm1[maxn],perm2[maxn];\nvector<stars> res;\n \nvoid dfs(int u){\n    rv.erase(u);\n    int crt=0;\n    while (1){\n        auto iter=rv.upper_bound(crt);\n        if (iter==rv.end()) break;\n        int v=*iter;\n        crt=v;\n        if (g[u].find(v)!=g[u].end()) continue;\n        t[u].insert(v), t[v].insert(u);\n        dfs(v);\n    }\n}\n \nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    int tc;\n    cin>>tc;\n    while (tc--){\n        cin>>n>>m;\n        for (int i=1;i<=n;++i) g[i].clear(), t[i].clear();\n        rv.clear(), res.clear(), d.clear();\n        for (int i=1;i<=m;++i){\n            int u,v;\n            cin>>u>>v;\n            g[u].insert(v), g[v].insert(u);\n        }\n        for (int i=1;i<=n;++i) rv.insert(i);\n        while (rv.size()>0){\n            int u=*(rv.begin());\n            dfs(u);       \n        }\n        int rem=n;\n        for (int i=1;i<=n;++i){\n            deg[i]=t[i].size();\n            if (deg[i]){\n                d.insert((info){i,deg[i]});\n            }\n            else{\n                perm1[i]=perm2[i]=rem;\n                rem--;\n            }\n        }\n        while (d.size()){\n            int idx=(*(d.begin())).idx;\n            int f=*(t[idx].begin());\n            vector<int> leaves;\n            leaves.clear();\n            d.erase((info){f,deg[f]});\n            for (auto c:t[f]){\n                d.erase((info){c,deg[c]});\n                if (deg[c]==1) leaves.push_back(c);\n                else deg[c]--, d.insert((info){c,deg[c]}), t[c].erase(f);\n            }\n            res.push_back((stars){f,leaves});\n        }\n        int l=0,r=0;\n        for (auto c:res){\n            perm1[c.rt]=++l;\n            for (auto ls:c.leaves){\n                perm1[ls]=++l;\n                perm2[ls]=++r;\n            }\n           perm2[c.rt]=++r;\n        }\n        for (int i=1;i<=n;++i) cout<<perm1[i]<<\" \";\n        cout<<\"\\n\";\n        for (int i=1;i<=n;++i) cout<<perm2[i]<<\" \";\n        cout<<\"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1477",
    "index": "E",
    "title": "Nezzar and Tournaments",
    "statement": "In the famous Oh-Suit-United tournament, two teams are playing against each other for the grand prize of precious pepper points.\n\nThe first team consists of $n$ players, and the second team consists of $m$ players. Each player has a potential: the potential of the $i$-th player in the first team is $a_i$, and the potential of the $i$-th player in the second team is $b_i$.\n\nIn the tournament, \\textbf{all} players will be on the stage in some order. There will be a scoring device, initially assigned to an integer $k$, which will be used to value the performance of all players.\n\nThe scores for all players will be assigned in the order they appear on the stage. Let the potential of the current player be $x$, and the potential of the previous player be $y$ (\\textbf{$y$ equals $x$ for the first player}). Then, $x-y$ is added to the value in the scoring device, Afterwards, if the value in the scoring device becomes negative, \\textbf{the value will be reset to $0$}. Lastly, the player's score is assigned to the current value on the scoring device. The score of a team is the sum of the scores of all its members.\n\nAs an insane fan of the first team, Nezzar desperately wants the biggest win for the first team. He now wonders what is the maximum difference between scores of the first team and the second team.\n\nFormally, let the score of the first team be $score_f$ and the score of the second team be $score_s$. Nezzar wants to find the maximum value of $score_f - score_s$ over all possible orders of players on the stage.\n\nHowever, situation often changes and there are $q$ events that will happen. There are three types of events:\n\n- $1$ $pos$ $x$ — change $a_{pos}$ to $x$;\n- $2$ $pos$ $x$ — change $b_{pos}$ to $x$;\n- $3$ $x$ — tournament is held with $k = x$ and Nezzar wants you to compute the maximum value of $score_f - score_s$.\n\nCan you help Nezzar to answer the queries of the third type?",
    "tutorial": "Let's firstly consider a simplified problem where the scoring device will not reset to $0$. For any player, his score will be fully determined by his potential as well as the potential of first player when $k$ is fixed. Indeed, similar property still holds in our setting. Observation 1. For any fixed arrangement of players with potentials $c_1,c_2,\\ldots,c_{n+m}$, $score_i=k-c_1+c_i+\\max(0,c_1-k-\\min(c_1,c_2,\\ldots,c_i))$, where $score_i$ is the score of the $i$-th player. Observation 2. If the first player is fixed, it is optimal to place players in second team in descending order of potentials, then place all players in ascending order of potentials. Let $f(t)$ be the difference where $a_x=t$ is selected as the first, and others ordered optimally (and $g(t)$ for sequence $b$ similarly). With some calculation, we may get $f(t) = (n-1) \\max(0,t-k-\\min) - \\sum_{i=1}^m \\max(0,t-k-b_i) + (m-n) t + C$ Suppose that we have an oracle of $f$, we are aiming to find out the maximum value of $f(t)$ over sets of values $\\{a_1,a_2,\\ldots,a_n\\}$. It can be seen that maximum values can only be reached on $O(1)$ inputs (which can be found in $O(\\log n)$ time). For better understanding, you may refer to the following figure. Here is a figure for $n=3$, $m=3$, $k=2$, $\\min=4$, $b_1=6, b_2=8$ and $b_3=10$. It can be seen that in this configuration, function is monotone increasing when $t<10$ and decreasing after. It can be shown that $f$ acts similarly. Therefore, it only remains to calculate $f$ for any given input $t$ efficiently, which can be decomposed to the following queries. minimum value over $a_i$, $b_i$. $\\sum_{1 \\le i \\le m} \\max(0,k-t-b_i)$ for given $k$. All those can be done efficiently via segment tree.",
    "code": "//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx\")\n//#pragma GCC optimize(\"unroll-loops\")\n#include<bits/stdc++.h>\nusing namespace std;\n \n#define rep(i,n) for (int i=0;i<(int)(n);++i)\n#define rep1(i,n) for (int i=1;i<=(int)(n);++i)\n#define range(x) begin(x), end(x)\n#define sz(x) (int)(x).size()\n#define pb push_back\n#define F first\n#define S second\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n \nnamespace internal {\n \n// @param n `0 <= n`\n// @return minimum non-negative `x` s.t. `n <= 2**x`\nint ceil_pow2(int n) {\n    int x = 0;\n    while ((1U << x) < (unsigned int)(n)) x++;\n    return x;\n}\n \n}\n \ntemplate <class S, S (*op)(S, S), S (*e)()> struct segtree {\n  public:\n    segtree() : segtree(0) {}\n    segtree(int n) : segtree(std::vector<S>(n, e())) {}\n    segtree(const std::vector<S>& v) : _n(int(v.size())) {\n        log = internal::ceil_pow2(_n);\n        size = 1 << log;\n        d = std::vector<S>(2 * size, e());\n        for (int i = 0; i < _n; i++) d[size + i] = v[i];\n        for (int i = size - 1; i >= 1; i--) {\n            update(i);\n        }\n    }\n \n    void set(int p, S x) {\n        assert(0 <= p && p < _n);\n        p += size;\n        d[p] = x;\n        for (int i = 1; i <= log; i++) update(p >> i);\n    }\n \n    S get(int p) {\n        assert(0 <= p && p < _n);\n        return d[p + size];\n    }\n \n    S prod(int l, int r) {\n        assert(0 <= l && l <= r && r <= _n);\n        S sml = e(), smr = e();\n        l += size;\n        r += size;\n \n        while (l < r) {\n            if (l & 1) sml = op(sml, d[l++]);\n            if (r & 1) smr = op(d[--r], smr);\n            l >>= 1;\n            r >>= 1;\n        }\n        return op(sml, smr);\n    }\n \n    S all_prod() { return d[1]; }\n \n    template <bool (*f)(S)> int max_right(int l) {\n        return max_right(l, [](S x) { return f(x); });\n    }\n    template <class F> int max_right(int l, F f) {\n        assert(0 <= l && l <= _n);\n        assert(f(e()));\n        if (l == _n) return _n;\n        l += size;\n        S sm = e();\n        do {\n            while (l % 2 == 0) l >>= 1;\n            if (!f(op(sm, d[l]))) {\n                while (l < size) {\n                    l = (2 * l);\n                    if (f(op(sm, d[l]))) {\n                        sm = op(sm, d[l]);\n                        l++;\n                    }\n                }\n                return l - size;\n            }\n            sm = op(sm, d[l]);\n            l++;\n        } while ((l & -l) != l);\n        return _n;\n    }\n \n    template <bool (*f)(S)> int min_left(int r) {\n        return min_left(r, [](S x) { return f(x); });\n    }\n    template <class F> int min_left(int r, F f) {\n        assert(0 <= r && r <= _n);\n        assert(f(e()));\n        if (r == 0) return 0;\n        r += size;\n        S sm = e();\n        do {\n            r--;\n            while (r > 1 && (r % 2)) r >>= 1;\n            if (!f(op(d[r], sm))) {\n                while (r < size) {\n                    r = (2 * r + 1);\n                    if (f(op(d[r], sm))) {\n                        sm = op(d[r], sm);\n                        r--;\n                    }\n                }\n                return r + 1 - size;\n            }\n            sm = op(d[r], sm);\n        } while ((r & -r) != r);\n        return 0;\n    }\n \n  private:\n    int _n, size, log;\n    std::vector<S> d;\n \n    void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }\n};\n \n \nconst int maxn=500007;\nconst int maxm=1000007;\nint n,m,k,q,t;\nll sum;\nint a[maxn],b[maxn];\n \nstruct S{\n    int cnt;\n    ll sum;\n};\n \nS e(){\n    return {0,0};\n}\n \nS op(S l,S r){\n    return {l.cnt+r.cnt,l.sum+r.sum};\n}\n \n \n \nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    segtree<S,op,e> seg_a(maxm),seg_b(maxm);\n    auto fa=[&](int x){\n        if (x>m||x<=0) cerr<<x<<endl;\n        assert(x<=m&&x>0);\n        return seg_a.max_right(0,[&](S l){return l.cnt<x;});\n    };\n    auto fb=[&](int x){\n        assert(x<=n&&x>0);\n        return seg_b.max_right(0,[&](S l){return l.cnt<x;});\n    };\n    auto solve=[&](int start,int coef){\n//        cerr<<\"start coef:\"<<start<<\" \"<<coef<<endl;\n        int mn=min(fa(1),fb(1));\n        if (start<=k+mn) return 1ll*(n-m)*start+sum;\n        auto ret=seg_b.prod(0,start-k);\n//        cerr<<\"ret:\"<<ret.cnt<<\" \"<<ret.sum<<endl;\n        return 1ll*coef*(start-k-mn)+1ll*(n-m)*start+sum+ret.sum-1ll*ret.cnt*(start-k);\n    };\n    cin>>m>>n>>q;\n    rep1(i,m) {cin>>a[i],sum+=a[i]; auto ret=seg_a.get(a[i]); ret.cnt++, ret.sum+=a[i], seg_a.set(a[i],ret);}\n    rep1(i,n) {cin>>b[i],sum-=b[i]; auto ret=seg_b.get(b[i]); ret.cnt++, ret.sum+=b[i], seg_b.set(b[i],ret);}\n    sum+=1ll*(m-n)*k;\n    auto res=[&](){\n        ll ans=-1e15;\n        ans=max(ans,solve(fb(1),m));\n        ans=max(ans,solve(fb(n),m));\n        ans=max(ans,solve(fa(1),m-1));\n        ans=max(ans,solve(fa(m),m-1));\n        int threshold=n>1?fb(n-1):0;\n        if (k+threshold<=1e6){\n            int pos=max(seg_a.prod(0,k+threshold).cnt,1);\n            ans=max(ans,solve(fa(pos),m-1));\n            int nxt_pos=seg_a.max_right(0,[&](S l){return l.cnt<=pos;});\n            if (nxt_pos<maxm) ans=max(ans,solve(nxt_pos,m-1));\n        }\n        cout<<ans<<\"\\n\";\n    };\n    while (q--){\n        int op,idx,x;\n        cin>>op;\n        if (op==1){\n            cin>>idx>>x;\n            auto ret=seg_a.get(a[idx]);\n            ret.cnt--, ret.sum-=a[idx];\n            seg_a.set(a[idx],ret);\n            sum-=a[idx];\n            sum+=x;\n            a[idx]=x;\n            ret=seg_a.get(x);\n            ret.cnt++, ret.sum+=x;\n            seg_a.set(x,ret);\n        } \n        if (op==2){\n            cin>>idx>>x;\n            auto ret=seg_b.get(b[idx]);\n            ret.cnt--, ret.sum-=b[idx];\n            seg_b.set(b[idx],ret);\n            sum+=b[idx];\n            sum-=x;\n            b[idx]=x;\n            ret=seg_b.get(x);\n            ret.cnt++, ret.sum+=x;\n            seg_b.set(x,ret);\n        }\n        if (op==3){\n            cin>>k;\n            sum+=(m-n)*k;\n            res();\n            sum-=(m-n)*k;\n        }\n    }  \n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1477",
    "index": "F",
    "title": "Nezzar and Chocolate Bars",
    "statement": "Nezzar buys his favorite snack — $n$ chocolate bars with lengths $l_1,l_2,\\ldots,l_n$. However, chocolate bars might be too long to store them properly!\n\nIn order to solve this problem, Nezzar designs an interesting process to divide them into small pieces. Firstly, Nezzar puts all his chocolate bars into a black box. Then, he will perform the following operation repeatedly until the maximum length over all chocolate bars does not exceed $k$.\n\n- Nezzar picks a chocolate bar from the box with probability proportional to its length $x$.\n- After step $1$, Nezzar uniformly picks a real number $r \\in (0,x)$ and divides the chosen chocolate bar into two chocolate bars with lengths $r$ and $x-r$.\n- Lastly, he puts those two new chocolate bars into the black box.\n\nNezzar now wonders, what is the expected number of operations he will perform to divide his chocolate bars into small pieces.\n\nIt can be shown that the answer can be represented as $\\frac{P}{Q}$, where $P$ and $Q$ are coprime integers and $Q \\not \\equiv 0$ ($\\bmod 998\\,244\\,353$). Print the value of $P\\cdot Q^{-1} \\mod 998\\,244\\,353$.",
    "tutorial": "Let's firstly solve an easier version where $n=1$. Part 1 ($n = 1$) Let's firstly rephrase the original task and solve it for case $n=1$. - Let $p_k$ the probability of event that $X_{(i)}-X_{(i-1)} \\le K$ for $1 \\le i \\le k$ and $L - X_{(k)} \\le K$. Here, $k$ real numbers $X_1,X_2,\\ldots,X_k$ are chosen uniformly from $(0,L)$, and $X_{(1)},X_{(2)},\\ldots,X_{(k)}$ is the sorted array of $X_0=0,X_1,X_2,\\ldots,X_k$. Then the disire answer would be $\\sum_{k=0}^{+\\infty} (1-p_k)$. To simplify notations, denote $w=\\frac{K}{L}$. We are aiming to calculate $p_n$ from now on. Let $Z_i=X_{(i)}-X_{(i-1)}$,then the pdf(probability density function) of the union distribution of $Z_1,Z_2,\\ldots,Z_n$ is $f(z_1,z_2,\\ldots,z_n)=n! I_{0<z_i<1,\\sum_{i=1}^n z_i < 1}$ Hence, $p_n= n! \\int_{0<z_i<w, 1-w < \\sum_{i=1}^n z_i < 1} 1 dz_1 dz_2 \\ldots dz_n= n! w^n \\int_{0<z_i<1, \\frac{1}{w}-1<\\sum_{i=1}^n z_i<\\frac{1}{w}} 1 dz$ Consider $Y_1,Y_2,\\ldots,Y_n$ i.i.d, where $Y_i$ follows uniform distribution sampling from $(0,1)$,then the integral above is $Pr[\\frac{1}{w}-1<\\sum_{i=1}^n Y_i<\\frac{1}{w}]$. Note that $\\sum_{i=1}^n Y_i$ follows Irwin-Hall distribution whose CDF(cumulative distribution function) is $F(x)={\\frac {1}{n!}}\\sum _{{k=0}}^{{\\lfloor x\\rfloor }}(-1)^{k}{\\binom {n}{k}}(x-k)^{n}$ Thus,$p_n = n!w^n(F(\\frac{1}{w})-F(\\frac{1}{w}-1))$. $p_n=1- \\left(\\sum_{k=0}^x (-1)^k \\binom{n}{k} (1-wk)^n - \\sum_{k=0}^{x-1} (-1)^k \\binom{n}{k}(1-(k+1)w)^n\\right) \\\\ =\\sum_{k=1}^x (-1)^{k-1} \\left(\\binom{n}{k}+\\binom{n}{k-1}\\right)(1-kw)^n$ where$x=\\left[\\frac{1}{w}\\right]$. using identity $\\sum_{n \\ge k}\\binom{n}{k} x^n=x^k(1-x)^{-(k+1)}$ to finish this task. Main version To avoid confusion, we will let $q_{m,j}$ the probability that $m$ operations are performed on line $j$ but there still exists lines produced by line $j$ with length greater or equal to $K$ (which have been calculated in part 1, with notation $p_n$). Recall that $q_{m,j} = \\sum_{k=1}^{\\lfloor \\frac{L_j}{K} \\rfloor} (-1)^{k-1}\\binom{m+1}{k} (1-\\frac{kK}{L_j})^m$. Therefore, probability $p_m$ that one fails to finish the task within $m$ rounds is $1 - \\sum_{j_1+j_2+\\ldots+j_n=m} \\frac{m!}{j_1!j_2!\\ldots j_n!} \\prod_{r=1}^n (1-q_{j_r,r})\\left(\\frac{L_j}{L}\\right)^{j_r}$ Let $Q_j$ be EGF of sequence $((1-q_{m,r} )L_j/L)_{m \\ge 0}$, that is to say the $m$-th coefficient is $[x^m]Q_j = \\frac{1}{m! L}(1-q_{m,r} )L_j.$ Similarly, let $P$ be EGF of sequence $(p_m)_{m \\ge 0}$, one may observe that $P = \\exp(x) - \\prod_{i=1}^n Q_i.$ In the following part, we will calculate $Q_j$. $\\begin{aligned} Q_j &= \\sum_{m \\ge 0} \\frac{1}{m!} \\left(\\frac{L_j}{L} - \\sum_{k=1}^{\\lfloor \\frac{L_j}{K} \\rfloor} (-1)^{k-1} \\binom{m+1}{k} \\left(1-\\frac{kK}{L_j}\\right)^m \\right) x^m\\\\ &= \\exp\\left(\\frac{L_j}{L}x\\right) - \\sum_{k=1}^{\\lfloor \\frac{L_j}{K} \\rfloor} (-1)^{k-1} \\sum_{m \\ge k-1} \\frac{(m+1)}{k!(m+1-k)!} \\left(\\frac{L_j-kK}{L}\\right)^m x^m \\end{aligned}$ Note that $\\sum_{m \\ge k-1} \\frac{m+1}{k!(m+1-k)!} y^m = \\sum_{m \\ge k} \\frac{y^m}{k!(m-k)!} + \\sum_{m \\ge k-1} \\frac{k y^m}{k!(m+1-k)!} = \\frac{y^k}{k!} \\exp(y) + \\frac{y^{k-1}}{(k-1)!} \\exp(y)$. Therefore, $\\begin{aligned} Q_j &= \\exp(\\frac{L_j}{L} x) - \\sum_{k=1}^{\\lfloor \\frac{L_j}{K} \\rfloor} (-1)^{k-1} \\left(\\frac{1}{k!} \\left(\\frac{L_j-kK}{L}\\right)^k x^k + \\frac{1}{(k-1)!} \\left(\\frac{L_j-kK}{L}\\right)^{k-1} x^{k-1} \\right)\\exp\\left(\\frac{(L_j-kK)x}{L}\\right) \\end{aligned}$ Note that with NTT and above equalities, we may calculate coefficient of $P$ in $O(nL \\log nL)$ (Precisely, we will calculate coefficient of $x^{k-j}\\exp{\\left(1-\\frac{K}{L}k x\\right)}$ for each $0 \\le k\\le L$ and $0 \\le j \\le \\min(n,k)$). Lastly, we should notice that if EGF of sequence $a$ is $x^k \\exp(Cx)$, then $a_{k+n} = \\frac{(k+n)!}{n!}C^n$, and its OGF is $k!\\sum_{n \\ge 0}\\binom{n+k}{k}C^n x^{n+k} = k!\\frac{(x/C)^k}{(1-Cx)^{k+1}}$. Hence, we will be able to calculate OGF $P'$ of sequence $p_m$, and answer is exactly $P'(1)$. It should be noticed that our approach will run in $O(nL \\log nL)$ implemented appropriately , where $L=\\sum_{i=1}^n l_i$. However, larger time limit is set to allow suboptimal solution to pass(like $O(nL^2)$ or $O(n^2L \\log L)$).",
    "code": "//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx\")\n//#pragma GCC optimize(\"unroll-loops\")\n#include<bits/stdc++.h>\n#define int long long\nusing namespace std;\n \n#define rep(i,n) for (int i=0;i<(int)(n);++i)\n#define rep1(i,n) for (int i=1;i<=(int)(n);++i)\n#define range(x) begin(x), end(x)\n#define sz(x) (int)(x).size()\n#define pb push_back\n#define F first\n#define S second\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n \nconst ll mod = (119 << 23) + 1, root = 62; // = 998244353\n// For p < 2^30 there is also e.g. 5 << 25, 7 << 26, 479 << 21\n// and 483 << 21 (same root). The last two are > 10^9.\n \nll modpow(ll b, ll e) {\n\tll ans = 1;\n\tfor (; e; b = b * b % mod, e /= 2)\n\t\tif (e & 1) ans = ans * b % mod;\n\treturn ans;\n}\n \ntypedef vector<ll> vl;\nvoid ntt(vl &a) {\n\tint n = sz(a), L = 31 - __builtin_clz(n);\n\tstatic vl rt(2, 1);\n\tfor (static int k = 2, s = 2; k < n; k *= 2, s++) {\n\t\trt.resize(n);\n\t\tll z[] = {1, modpow(root, mod >> s)};\n\t\tfor(int i=k;i<2*k;++i) rt[i] = rt[i / 2] * z[i & 1] % mod;\n\t}\n\tvi rev(n);\n\tfor(int i = 0; i < n; ++i) rev[i] = (rev[i / 2] | (i & 1) << L) / 2;\n\tfor(int i = 0; i < n; ++i) if (i < rev[i]) swap(a[i], a[rev[i]]);\n\tfor (int k = 1; k < n; k *= 2)\n\t\tfor (int i = 0; i < n; i += 2 * k) for(int j = 0; j < k; ++j) {\n\t\t\tll z = rt[j + k] * a[i + j + k] % mod, &ai = a[i + j];\n\t\t\ta[i + j + k] = ai - z + (z > ai ? mod : 0);\n\t\t\tai += (ai + z >= mod ? z - mod : z);\n\t\t}\n}\nvl conv(const vl &a, const vl &b) {\n\tif (a.empty() || b.empty()) return {};\n\tint s = sz(a) + sz(b) - 1, B = 32 - __builtin_clz(s), n = 1 << B;\n\tint inv = modpow(n, mod - 2);\n\tvl L(a), R(b), out(n);\n\tL.resize(n), R.resize(n);\n\tntt(L), ntt(R);\n\tfor (int i = 0; i < n; ++i) out[-i & (n - 1)] = (ll)L[i] * R[i] % mod * inv % mod;\n\tntt(out);\n\treturn {out.begin(), out.begin() + s};\n}\n \nconst int maxn=1007;\n \nint n,k;\nint l[maxn];\n \nstruct polynomial{\n    int n,m;\n    vector<vi> poly;\n    polynomial(vector<vi> &po):poly(po){\n        n = sz(poly) - 1, m = sz(poly[0]) - 1;\n    }\n    vi rsz(int nn,int mm){\n        assert(nn>n&&mm>m);\n        vi ret;\n        ret.resize(nn*mm+1,0);\n        for (int i=0;i<=n;++i){\n            for (int j=0;j<=m;++j){\n                ret[i*mm+j]=poly[i][j];\n                assert(poly[i][j]<mod&&poly[i][j]>=0);\n            }\n        }\n        return ret;\n    }\n    \n    friend polynomial operator*(polynomial l,polynomial r){\n        vector<vi> po;\n        po.clear();\n        po.resize(l.n+r.n+1,vi(l.m+r.m+1,0));\n        auto lpo=l.rsz(l.n+1,l.m+r.m+1),rpo=r.rsz(r.n+1,l.m+r.m+1),res=conv(lpo,rpo);\n//        for (auto c:res) cout<<c<<\" \";\n//        cout<<endl;\n//        cout<<sz(lpo)<<\" \"<<sz(rpo)<<\" \"<<sz(res)<<endl;\n        for (int i=0;i<=l.n+r.n;++i){\n            for (int j=0;j<=l.m+r.m;++j){\n                po[i][j]=res[i*(l.m+r.m+1)+j];\n            }\n        }\n//        cout<<\"hi\"<<endl;\n        return po;\n    }\n};\n \nvector<polynomial> poly;\nint f[5007];\nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>n>>k;\n    f[0]=1;\n    rep1(i,5000) f[i]=f[i-1]*i%mod;\n    int L=0;\n    rep(i,n) cin>>l[i], L+=l[i];\n    rep(i,n){\n        vi res0,res1;\n        res0.clear(), res1.clear();\n        res0.pb(1), res1.pb(0);\n        int sgn=1;\n        rep1(j,l[i]/k){\n            int tmp0,tmp1;\n            sgn=-sgn;\n            if (l[i]==k*j) {\n                tmp0=tmp1=0;\n            }\n            else{\n                tmp0=(modpow((l[i]-k*j)*modpow(L,mod-2)%mod,j)%mod)*modpow(f[j],mod-2)%mod, tmp1=(modpow((l[i]-k*j)*modpow(L,mod-2)%mod,j-1)%mod)*modpow(f[j-1],mod-2)%mod;\n                if (sgn<0) tmp0=(tmp0?mod-tmp0:tmp0), tmp1=(tmp1?mod-tmp1:tmp1);\n            }\n//            cerr<<i<<\" \"<<j<<\":\"<<tmp0<<\" \"<<tmp1<<endl;\n            res0.pb(tmp0), res1.pb(tmp1);\n        }\n        vector<vi> p({res0,res1});\n        polynomial po(p);\n        poly.pb(po);\n    }\n    for (int k=1;k<=n;k<<=1){\n        for (int i=k;i<n;i+=2*k){\n            poly[i-k]=poly[i]*poly[i-k];\n        }\n    }\n    int ans=0;\n    // x^{j-i}exp((1-k*j/L)) -> (j-i)!/((k*j/L)^{j-i+1}) = (j-i)!L^{j-i+1}/(k*j)^{j-i+1}\n    rep(i,poly[0].n+1){\n        rep(j,poly[0].m+1){\n            if (i>j) {assert(poly[0].poly[i][j]==0); continue;}\n            if (j==0) {assert(poly[0].poly[i][j]==1); continue;}\n            if (k*j==L) {assert(poly[0].poly[i][j]==0); continue;}\n            int num=f[j-i]*modpow(L,j-i+1)%mod,den=modpow(k*j,j-i+1)%mod;\n//            cerr<<i<<\",\"<<j<<\":\"<<poly[0].poly[i][j]<<\" \"<<num<<\" \"<<den<<endl;\n            ans=(ans+(num*modpow(den,mod-2)%mod)*poly[0].poly[i][j]%mod)%mod;\n        }\n    }\n    if (ans>0) cout<<mod-ans<<endl;     \n    else cout<<0<<endl;\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "fft",
      "math",
      "probabilities"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1478",
    "index": "A",
    "title": "Nezzar and Colorful Balls",
    "statement": "Nezzar has $n$ balls, numbered with integers $1, 2, \\ldots, n$. Numbers $a_1, a_2, \\ldots, a_n$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $a_i \\leq a_{i+1}$ for all $1 \\leq i < n$.\n\nNezzar wants to color the balls using the minimum number of colors, such that the following holds.\n\n- For any color, numbers on balls will form a \\textbf{strictly increasing sequence} if he keeps balls with this chosen color and discards all other balls.\n\nNote that a sequence with the length at most $1$ is considered as a strictly increasing sequence.\n\nPlease help Nezzar determine the minimum number of colors.",
    "tutorial": "For positions which numbers are the same, they cannot be colored using same color. Let us color the $i$-th occurrence of any number using color $i$. We can see that: We cannot use fewer colors: if there are $k$ occurrence of any number, at least $k$ color is needed. The assignment of color is valid: Since the sequence was non-increasing, for any subsequence it is also non-increasing. As there are no duplicates in colored subsequence, the subsequence is strictly increasing as well. Therefore, we only need to count the number of occurrence of every number and take the maximum of them. Time complexity: $O(n)$ per test case",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n#define rep(i,n) for (int i=0;i<(int)(n);++i)\n#define rep1(i,n) for (int i=1;i<=(int)(n);++i)\n#define range(x) begin(x), end(x)\n#define sz(x) (int)(x).size()\n#define pb push_back\n#define F first\n#define S second\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n \nconst int maxn=200007;\nint t,n;\nint cnt[maxn];\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>t;\n    while (t--){\n        cin>>n;\n        rep1(i,n) cnt[i]=0;\n        rep1(i,n){\n            int u;\n            cin>>u;\n            cnt[u]++;\n        }\n        int mx=0;\n        rep1(i,n) mx=max(mx,cnt[i]);\n        cout<<mx<<\"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1478",
    "index": "B",
    "title": "Nezzar and Lucky Number",
    "statement": "Nezzar's favorite digit among $1,\\ldots,9$ is $d$. He calls a \\textbf{positive} integer lucky if $d$ occurs at least once in its decimal representation.\n\nGiven $q$ integers $a_1,a_2,\\ldots,a_q$, for each $1 \\le i \\le q$ Nezzar would like to know if $a_i$ can be equal to a sum of several (one or more) lucky numbers.",
    "tutorial": "For any given $d$, We can observe the following: $10d$ to $10d + 9$ contains $d$ as one of its digit Let $k = 10d + 9$ be the upper bound of such range For every number $x > k$, we can keep reducing $x$ by $d$, $x$ will eventually fall into the range mentioned above, which contains $d$ as digit. Therefore, for numbers $x > k$, they are always achievable. For $x \\leq k - 10$, as $k <= 109$, we can run a standard knapsack dynamicprogramming solution, where $dp[x]$ indicates if $x$ is achievable. $dp[x]$ is achievable, if and only if one of the following is true: $x = 0$ For some $y < x$, $dp[y]$ is true and $x - y$ contains $d$ as digit Iterating for every $x$, all $dp[x]$ for $x < k$ can be computed with $O(k)$ per state (as we only need to consider $y < k$. Besides dynamic programming solution, brute force solutions with enough optimization should also pass the test cases easily. Time complexity: $O((10d)^2)$ per test case.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int maxn=207;\nint t,d,q;\nbool dp[maxn];\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>t;\n    while (t--){\n        memset(dp,0,sizeof(dp));\n        dp[0]=1;\n        cin>>q>>d;\n        if (!d) d+=10;\n        int mx=d*10;\n        for (int i=0;10*i+d<=mx;++i){\n            for (int j=0;10*i+d+j<=mx;++j){\n                dp[10*i+d+j]|=dp[j];\n            }\n        }\n        while (q--){\n            int u;\n            cin>>u;\n            if (u>=mx||dp[u]) cout<<\"YES\\n\";\n            else cout<<\"NO\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1478",
    "index": "C",
    "title": "Nezzar and Symmetric Array",
    "statement": "Long time ago there was a symmetric array $a_1,a_2,\\ldots,a_{2n}$ consisting of $2n$ \\textbf{distinct integers}. Array $a_1,a_2,\\ldots,a_{2n}$ is called symmetric if for each integer $1 \\le i \\le 2n$, there exists an integer $1 \\le j \\le 2n$ such that $a_i = -a_j$.\n\nFor each integer $1 \\le i \\le 2n$, Nezzar wrote down an integer $d_i$ equal to the sum of absolute differences from $a_i$ to all integers in $a$, i. e. $d_i = \\sum_{j = 1}^{2n} {|a_i - a_j|}$.\n\nNow a million years has passed and Nezzar can barely remember the array $d$ and totally forget $a$. Nezzar wonders if there exists any symmetric array $a$ consisting of $2n$ distinct integers that generates the array $d$.",
    "tutorial": "WLOG, we may assume that $0 < a_1 < a_2 < \\ldots < a_n$, and $a_{i+n}=-a_i$ for each $1 \\le i \\le n$. Let's sort array $d$ firstly. It can be observed that the array $d$ satisfied the following property: $d_{2i-1}=d_{2i}$ for each $1 \\le i \\le n$; $d_{2i} \\neq d_{2i+2}$ for each $1 \\le i < n$. $d_{2i}$ must be generated for index $i$ or $i+n$. More importantly, we have the following relation: $d_{2n}-d_{2n-2}=\\sum_{i=1}^{n} (a_n-a_i)+\\sum_{i=1}^n (a_n+a_i) - \\sum_{i=1}^n|a_{n-1}-a_i| - \\sum_{i=1}^n (a_{n-1}+a_i) = (2n-2)(a_n-a_{n-1})$ And observe that $|a_i-a_n|+|a_i+a_n|=2a_n$ is a constant independent of index $1 \\le i\\le n$. Therefore, we may remove $a_n$ and $-a_n$ by subtracting some constant for $d_i$ for all $1 \\le i \\le 2(n-1)$, indicating that we will calculate $a_{i+1}-a_{i}$ for all $1 \\le i < n$, which can be done in $O(n)$. Lastly, we should determine if there exists an postivie integer $a_1$ which generates $d_1$, which can be done in $O(n)$.",
    "code": "#include<bits/stdc++.h>\n#define int long long\nusing namespace std;\n \nconst int maxn=200007;\nint t;\nint n,a[maxn],b[maxn],d[maxn];\n \nsigned main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cin>>t;\n    while (t--){\n        cin>>n;\n        for (int i=0;i<2*n;++i) cin>>a[i];\n        sort(a,a+2*n,greater<int>());\n        for (int i=0;i<n;++i){\n            if (a[i*2]!=a[i*2+1]){\n                cout<<\"NO\\n\";\n                goto cont;\n            }\n            b[i]=a[i*2];\n        }\n        for (int i=1;i<n;++i){\n            if (b[i-1]==b[i]||(b[i-1]-b[i])%(2*(n-i))){\n                cout<<\"NO\\n\";\n                goto cont;\n            }\n            d[i]=(b[i-1]-b[i])/2/(n-i);\n        }\n        for (int i=1;i<n;++i){\n            b[n-1]-=2*i*d[i];\n        }\n        if (b[n-1]<=0||b[n-1]%(2*n)) cout<<\"NO\\n\";\n        else cout<<\"YES\\n\";\n \n        cont:;\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1479",
    "index": "A",
    "title": "Searching Local Minimum",
    "statement": "\\textbf{This is an interactive problem}.\n\nHomer likes arrays a lot and he wants to play a game with you.\n\nHomer has hidden from you a permutation $a_1, a_2, \\dots, a_n$ of integers $1$ to $n$. You are asked to find any index $k$ ($1 \\leq k \\leq n$) which is a local minimum.\n\nFor an array $a_1, a_2, \\dots, a_n$, an index $i$ ($1 \\leq i \\leq n$) is said to be a local minimum if $a_i < \\min\\{a_{i-1},a_{i+1}\\}$, where $a_0 = a_{n+1} = +\\infty$. An array is said to be a permutation of integers $1$ to $n$, if it contains all integers from $1$ to $n$ exactly once.\n\nInitially, you are only given the value of $n$ without any other information about this permutation.\n\nAt each interactive step, you are allowed to choose any $i$ ($1 \\leq i \\leq n$) and make a query with it. As a response, you will be given the value of $a_i$.\n\nYou are asked to find any index $k$ which is a local minimum \\textbf{after at most $100$ queries}.",
    "tutorial": "We maintain by binary search a range $[l, r]$ which has a local minimum. Moreover, we assume that $a_{l-1} > a_l$ and $a_r < a_{r+1}$. Initially, $[l, r] = [1, n]$. In each iteration, let $m$ be the midpoint of $l$ and $r$. Case 1. If $a_m < a_{m+1}$, then the range becomes $[l, m]$. Case 2. If $a_m > a_{m+1}$, then the range becomes $[m+1, r]$. When $l = r$, we have found a local minimum $a_l$. The number of queries to $a_i$ is at most $2 \\lceil \\log_2 n \\rceil \\leq 34 < 100$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = 100010;\n \nint n;\nint a[MAXN];\n \nint query(int x)\n{\n\tif (1 <= x && x <= n)\n\t{\n\t\tprintf(\"? %d\\n\", x);\n\t\tfflush(stdout);\n\t\tscanf(\"%d\", &a[x]);\n\t}\n}\n \nint main()\n{\n\tscanf(\"%d\", &n);\n\ta[0] = a[n + 1] = n + 1;\n\tint L = 1, R = n;\n\twhile (L < R)\n\t{\n\t\tint m = (L + R) / 2;\n\t\tquery(m);\n\t\tquery(m + 1);\n\t\tif (a[m] < a[m + 1])\n\t\t\tR = m;\n\t\telse\n\t\t\tL = m + 1;\n\t}\n\tprintf(\"! %d\\n\", L);\n\tfflush(stdout);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "interactive",
      "ternary search"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1479",
    "index": "B1",
    "title": "Painting the Array I",
    "statement": "\\textbf{The only difference between the two versions is that this version asks the maximal possible answer.}\n\nHomer likes arrays a lot. Today he is painting an array $a_1, a_2, \\dots, a_n$ with two kinds of colors, \\textbf{white} and \\textbf{black}. A painting assignment for $a_1, a_2, \\dots, a_n$ is described by an array $b_1, b_2, \\dots, b_n$ that $b_i$ indicates the color of $a_i$ ($0$ for white and $1$ for black).\n\nAccording to a painting assignment $b_1, b_2, \\dots, b_n$, the array $a$ is split into two new arrays $a^{(0)}$ and $a^{(1)}$, where $a^{(0)}$ is the sub-sequence of all white elements in $a$ and $a^{(1)}$ is the sub-sequence of all black elements in $a$. For example, if $a = [1,2,3,4,5,6]$ and $b = [0,1,0,1,0,0]$, then $a^{(0)} = [1,3,5,6]$ and $a^{(1)} = [2,4]$.\n\nThe number of segments in an array $c_1, c_2, \\dots, c_k$, denoted $\\mathit{seg}(c)$, is the number of elements if we merge all adjacent elements with the same value in $c$. For example, the number of segments in $[1,1,2,2,3,3,3,2]$ is $4$, because the array will become $[1,2,3,2]$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $0$.\n\nHomer wants to find a painting assignment $b$, according to which the number of segments in both $a^{(0)}$ and $a^{(1)}$, i.e. $\\mathit{seg}(a^{(0)})+\\mathit{seg}(a^{(1)})$, is as \\textbf{large} as possible. Find this number.",
    "tutorial": "Formally, for every sequence $a_1, a_2, \\dots, a_n$, and we assume that $a_1, a_2, \\dots, a_n$ are positive integers, the number of segments in $a$ is defined to be $\\mathit{seg}(a) = \\sum_{i=1}^n [ a_{i-1} \\neq a_{i} ],$ Let's restate the problem as Problem. Given a sequence $a_1, a_2, \\dots, a_n$, divide it into two disjoint subsequences $s$ and $t$ such that $\\mathit{seg}(s)+\\mathit{seg}(t)$ is as large as possible. Solution. We will construct two disjoint subsequences by scanning through the sequence $a_1, a_2, \\dots, a_n$. Initial setting: $s$ and $t$ are two empty sequences, and $a_1, a_2, \\dots, a_n$ remains not scanned. Move on: Suppose the last elements of $s$ and $t$ are $x$ and $y$, respectively, and $x = 0$ (resp. $y = 0$) if $s$ (resp. $t$) is empty. Let $z$ be the current element scanning through $a_1, a_2, \\dots, a_n$. Our greedy strategy is described in two cases: Greedy Strategy I: If $z$ equals to one of $x$ and $y$, then assign $z$ to the opposite subsequence. That is, if $z = x$, then append $z$ after $y$; and if $z = y$, then append $z$ after $x$. In particular, if $z$ equals to both $x$ and $y$, the assignment could be arbitrary. Greedy Strategy II: If $z$ differs from both $x$ and $y$, then append $z$ after the one with the nearest next same value. That is, let $\\mathit{next}(x)$ denote the next position where $x$ appears in $a_1, a_2, \\dots, a_n$ after $z$, then append $z$ after $x$ if $\\mathit{next}(x) < \\mathit{next}(y)$, and after $y$ otherwise. The greedy strategy is intuitive, and with this strategy, an $O(n)$ algorithm is immediately obtained. However, its proof turns out to be complicated. We append its proof for completeness. An Intuitive Proof Consider any optimal assignment $b_1, b_2, \\dots, b_n$, we will show that our strategy is not worse than it. Let $a[l \\dots r] = a_l, a_{l+1}, \\dots, a_r$ be the subarray of $a$. Now suppose we are at some position $p$, where the optimal assignment conflicts with our strategy. We assume that $s = (a[1\\dots p])^{(0)} = s' x$ ends with $x$, and $t = (a[1\\dots p])^{(1)} = t' y$ ends with $y$, and $a_{p+1} = z$. Greedy Strategy I: If $b$ conflicts with Greedy Strategy I, then we must have $x \\neq y$ and without loss of generality, we assume that $x = z$. Greedy Strategy I suggests we append $z$ after $y$ but $b$ suggests we append $z$ after $x$. Suppose $b$ results in the two subarrays $\\begin{aligned} & s'xzs^{\\prime \\prime} \\\\ & t'yt^{\\prime \\prime} \\end{aligned}$, while there is indeed another optimal assignment that agrees with our strategy and results in $\\begin{aligned} & s'xt^{\\prime \\prime} \\\\ & t'yzs^{\\prime \\prime} \\end{aligned}$. Greedy Strategy II: If $b$ conflicts with Greedy Strategy II, then we must have $x$, $y$ and $z$ are distinct and without loss of generality, we assume that the next occurrence of $x$ goes in front of that of $y$. Greedy Strategy II suggests we append $z$ after $x$ but $b$ suggests we append $z$ after $y$. Suppose $b$ results in the two subarrays $\\begin{aligned} & s'xs^{\\prime \\prime} \\\\ & t'yzt^{\\prime \\prime} \\end{aligned}$. Consider two cases. Case 1. If $s^{\\prime \\prime}$ does not start with $y$, then there is another optimal assignment that agrees with our strategy and results in $\\begin{aligned} & s'xzt^{\\prime \\prime} \\\\ & t'ys^{\\prime \\prime} \\end{aligned}$. Case 2. If $s^{\\prime \\prime}$ starts with $y$, i.e. $s^{\\prime \\prime} = y s_1$, then since the first occurrence of $x$ is in front of that of $y$, we have that $x$ must be in $t^{\\prime \\prime}$, and assume that $t^{\\prime \\prime} = t_1 x t_2$. The result of $b$ is restated as $\\begin{aligned} & s'x y s_1 \\\\ & t'yzt_1 x t_2 \\end{aligned}$. We find that there is another optimal assignment that agrees with our strategy and results in $\\begin{aligned} & s'xz t_1 y s_1 \\\\ & t'yx t_2 \\end{aligned}$ (Note that $t_1$ does not contain any $x$ or $y$ in it). A Formal Proof The number of alternations in a sequence $a$ starting with $x$ is defined to be $\\mathit{seg}_x(a) = \\sum_{i=1}^n [ a_{i-1} \\neq a_{i} ],$ Let $f_{x,y}(a)$ denote the maximal possible sum of numbers of alternations in the two disjoint subsequences $s$ and $t$ of $a$, i.e. $f_{x, y}(a) = \\max_{s, t} \\{\\mathit{seg}_x(s)+\\mathit{seg}_y(t)\\},$ Let $\\mathit{next}(x)$ denote the least index $k$ such that $a_k = x$, i.e. $\\mathit{next}(x) = \\min\\{k \\in \\mathbb{N}: a_k = x\\}$. In case no such index $k$ exists, $\\mathit{next}(x)$ is defined to be $\\infty$. In fact, our problem can be solved by DP regardless of the time complexity. Proposition 1 (Dynamic Programming). For $n \\geq 1$ and every $x, y \\in \\mathbb{N}$, $f_{x,y}(a_1, a_2, \\dots, a_n) = \\max \\{ f_{a_1, y} (a_2, \\dots, a_n) + [a_1 \\neq x], f_{x, a_1} (a_2, \\dots, a_n) + [a_1 \\neq y] \\}.$ We can obtain some immediate properties of $f_{x, y}(a)$ by the above DP recurrence. Proposition 2. For every $x, y \\in \\mathbb{N}$, $f_{x,0}(a) \\geq f_{x,y}(a) \\geq f_{x,x}(a)$. Moreover, if $\\mathit{next}(y) = \\infty$, then $f_{x,0}(a) = f_{x,y}(a)$. After some observations, we have Proposition 3. For every $x, y, z \\in \\mathbb{N}$ and sequence $a$, $f_{z,x}(a)+1 \\geq f_{z,y}(a)$. Proof: By induction on the length $n$ of sequence $a$. Basis. It is trivial for the case $n = 0$ since the left hand side is always $1$ and the right hand side is always $0$. Induction. Suppose true for the case $n = k (k \\geq 0)$, i.e. $f_{z,x}(a)+1 \\geq f_{z,y}(a)$ Case 1. $x = y$. It is trivial that $f_{z,x}(a)+1 \\geq f_{z,x}(a)$. Case 2. $z = x \\neq y$. We should prove that $f_{x,x}(a)+1 \\geq f_{x,y}(a)$. By Proposition 1, we need to prove that $\\begin{cases} f_{a_1,x}(a_2,\\dots,a_{k+1})+[a_1 \\neq x]+1 \\geq f_{a_1,y}(a_2,\\dots,a_{k+1})+[a_1 \\neq x], \\\\ f_{a_1,x}(a_2,\\dots,a_{k+1})+[a_1 \\neq x]+1 \\geq f_{x,a_1}(a_2,\\dots,a_{k+1})+[a_1 \\neq y]. \\end{cases}$ $f_{a_1,x}(a_2,\\dots,a_{k+1})+1 \\geq f_{a_1,y}(a_2,\\dots,a_{k+1}),$ Case 3. $x \\neq y = z$. We should prove that $f_{x,y}(a)+1 \\geq f_{x,x}(a)$. By Proposition 1, we only need to prove that $f_{x,a_1}(a_2,\\dots,a_{k+1})+[a_1 \\neq y]+1 \\geq f_{a_1,x}(a_2,\\dots,a_{k+1})+[a_1 \\neq x],$ Case 4. $x \\neq y, z \\neq x$ and $z \\neq y$. By Proposition 1, $f_{z,x}(a)+1 \\geq f_{z,y}(a)$ is equivalent to $\\begin{aligned} & \\max\\{ f_{a_1, x}(a_2,\\dots,a_{k+1})+[a_1 \\neq z], f_{z, a_1}(a_2,\\dots,a_{k+1})+[a_1 \\neq x] \\} + 1 \\\\ & \\quad \\geq \\max\\{ f_{a_1, y}(a_2,\\dots,a_{k+1})+[a_1 \\neq z], f_{z, a_1}(a_2,\\dots,a_{k+1})+[a_1 \\neq y] \\}. \\end{aligned}$ Case 4.1. $a_1 = z$. The left hand side becomes $\\max\\{ f_{z, x}(a_2,\\dots,a_{k+1}), f_{z, z}(a_2,\\dots,a_{k+1})+1 \\} + 1 = f_{z, z}(a_2,\\dots,a_{k+1})+2$ $\\max\\{ f_{z, y}(a_2,\\dots,a_{k+1}), f_{z, z}(a_2,\\dots,a_{k+1})+1 \\} = f_{z, z}(a_2,\\dots,a_{k+1})+1$ Case 4.2. $a_1 = x$. The left hand side becomes $\\max\\{ f_{x, x}(a_2,\\dots,a_{k+1})+1, f_{z, x}(a_2,\\dots,a_{k+1}) \\} + 1 = f_{x,x}(a_2,\\dots,a_{k+1})+2$ $\\max\\{ f_{x, y}(a_2,\\dots,a_{k+1})+1, f_{z, x}(a_2,\\dots,a_{k+1})+1 \\}.$ Case 4.3. $a_1 = y$. The left hand side becomes $\\max\\{ f_{y, x}(a_2,\\dots,a_{k+1})+1, f_{z, y}(a_2,\\dots,a_{k+1})+1 \\} + 1.$ $\\max\\{ f_{y, y}(a_2,\\dots,a_{k+1}), f_{z, y}(a_2,\\dots,a_{k+1})+1 \\} = f_{z, y}(a_2,\\dots,a_{k+1})+1$ Case 4.4. $a_1 \\notin \\{x,y,z\\}$. The left hand side becomes $\\max\\{ f_{a_1, x}(a_2,\\dots,a_{k+1})+1, f_{z, a_1}(a_2,\\dots,a_{k+1})+1 \\} + 1.$ $\\max\\{ f_{a_1, y}(a_2,\\dots,a_{k+1})+1, f_{z, a_1}(a_2,\\dots,a_{k+1})+1 \\}.$ The inequality holds for all cases. Therefore, the inequality holds for $n = k+1$. Conclusion. The inequality holds for every $n \\geq 0$. $\\Box$ Proposition 4. Suppose $a_1, a_2, \\dots, a_n$ is a sequence. For every distinct $x, y, z \\in \\mathbb{N}$, i.e. $x \\neq y, y \\neq z$ and $z \\neq x$, if $\\mathit{next}(x) < \\mathit{next}(y)$, then $f_{z,y}(a) \\geq f_{z,x}(a)$. Proof: By induction on the length $n$ of sequence $a$. Basis. It is trivial for the case $n = 0$ since the both hand sides are $0$. Induction. Suppose true for the case $n = k (k \\geq 0)$, i.e. $f_{z,y}(a) \\geq f_{z,x}(a).$ Case 1. $a_1 = z$. By Proposition 1 and 3, the left hand side becomes $\\max\\{ f_{z, y}(a_2,\\dots,a_{k+1}), f_{z, z}(a_2,\\dots,a_{k+1})+1 \\} = f_{z, z}(a_2,\\dots,a_{k+1})+1,$ $\\max\\{ f_{z, x}(a_2,\\dots,a_{k+1}), f_{z, z}(a_2,\\dots,a_{k+1})+1 \\} = f_{z, z}(a_2,\\dots,a_{k+1})+1$ Case 2. $a_1 = x$. By Proposition 1, the left hand side becomes $\\max\\{ f_{x, y}(a_2,\\dots,a_{k+1})+1, f_{z, x}(a_2,\\dots,a_{k+1})+1 \\},$ $\\max\\{ f_{x, x}(a_2,\\dots,a_{k+1})+1, f_{z, x}(a_2,\\dots,a_{k+1}) \\}.$ $f_{z, x}(a_2,\\dots,a_{k+1}) \\geq f_{x, x}(a_2,\\dots,a_{k+1}),$ Case 3. $a_1 = y$. This is impossible because $\\mathit{next}(x) < \\mathit{next}(y)$, i.e. there is an element of value $x$ in front of the first element of value $y$. Case 4. $a_1 \\notin \\{x,y,z\\}$. The left hand side becomes $\\max\\{ f_{a_1, y}(a_2,\\dots,a_{k+1})+1, f_{a_1, z}(a_2,\\dots,a_{k+1})+1 \\}.$ $\\max\\{ f_{a_1, x}(a_2,\\dots,a_{k+1})+1, f_{a_1, z}(a_2,\\dots,a_{k+1})+1 \\}.$ Case 4.1. If $\\mathit{next}(y) > \\mathit{next}(z)$, then by induction we have $f_{a_1, y}(a_2,\\dots,a_{k+1}) \\geq f_{a_1, z}(a_2,\\dots,a_{k+1}),$ $f_{a_1, y}(a_2,\\dots,a_{k+1}) \\geq f_{a_1, x}(a_2,\\dots,a_{k+1}).$ Case 4.2. If $\\mathit{next}(y) < \\mathit{next}(z)$, then by induction we have $f_{a_1, z}(a_2,\\dots,a_{k+1}) \\geq f_{a_1, y}(a_2,\\dots,a_{k+1}),$ $f_{a_1, z}(a_2,\\dots,a_{k+1}) \\geq f_{a_1, x}(a_2,\\dots,a_{k+1}).$ The inequality holds for all cases. Therefore, the inequality holds for $n = k+1$. Conclusion. The inequality holds for every $n \\geq 0$. Proposition 5 (Greedy Strategy I). Suppose $a_1, a_2, \\dots, a_n$ is a sequence. For every $x, y \\in \\mathbb{N}$, if $a_1 = x$, then $f_{x,y}(a_1,\\dots,a_n) = f_{x,x}(a_2,\\dots,a_n)+1.$ Proof: By Proposition 1, we have $f_{x,y}(a_1,\\dots,a_n) = \\max \\{ f_{x, y} (a_2, \\dots, a_n), f_{x, x} (a_2, \\dots, a_n) + 1 \\}.$ $f_{x,x}(a_2, \\dots, a_n) + 1 \\geq f_{x, y} (a_2, \\dots, a_n).$ Proposition 6 (Greedy Strategy II). Suppose $a_1, a_2, \\dots, a_n$ is a sequence. For every $x, y \\in \\mathbb{N}$ with $x \\neq y$, if $a_1 \\notin \\{x,y\\}$, then $f_{x,y}(a_1,\\dots,a_n) = \\begin{cases} f_{a_1,y}(a_2,\\dots,a_n)+1 & \\mathit{next}(x) < \\mathit{next}(y), \\\\ f_{x,a_1}(a_2,\\dots,a_n)+1 & \\text{otherwise}. \\end{cases}$ $f_{a_1,y}(a_2,\\dots,a_n) \\geq f_{x,a_1}(a_2,\\dots,a_n).$ The same statement holds for $\\mathit{next}(x) > \\mathit{next}(y)$. $\\Box$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = 100010;\n \nint n;\nint a[MAXN];\nint pos[MAXN], nxt[MAXN];\n \nvoid solve()\n{\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\tfor (int i = 0; i <= n; ++i)\n\t\tpos[i] = n + 1;\n\tfor (int i = n; i >= 0; --i)\n\t{\n\t\tnxt[i] = pos[a[i]];\n\t\tpos[a[i]] = i;\n\t}\n\tint x = 0, y = 0; // the last elements of the two subarrays\n\tint res = 0;\n\tfor (int z = 1; z <= n; ++z)\n\t{\n\t\t// Greedy Strategy I\n\t\tif (a[x] == a[z])\n\t\t{\n\t\t\tres += a[y] != a[z];\n\t\t\ty = z;\n\t\t}\n\t\telse if (a[y] == a[z])\n\t\t{\n\t\t\tres += a[x] != a[z];\n\t\t\tx = z;\n\t\t}\n\t\t// Greedy Strategy II\n\t\telse if (nxt[x] < nxt[y])\n\t\t{\n\t\t\tres += a[x] != a[z];\n\t\t\tx = z;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres += a[y] != a[z];\n\t\t\ty = z;\n\t\t}\n\t}\n\tprintf(\"%d\\n\", res);\n}\n \nint main()\n{\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1479",
    "index": "B2",
    "title": "Painting the Array II",
    "statement": "\\textbf{The only difference between the two versions is that this version asks the minimal possible answer.}\n\nHomer likes arrays a lot. Today he is painting an array $a_1, a_2, \\dots, a_n$ with two kinds of colors, \\textbf{white} and \\textbf{black}. A painting assignment for $a_1, a_2, \\dots, a_n$ is described by an array $b_1, b_2, \\dots, b_n$ that $b_i$ indicates the color of $a_i$ ($0$ for white and $1$ for black).\n\nAccording to a painting assignment $b_1, b_2, \\dots, b_n$, the array $a$ is split into two new arrays $a^{(0)}$ and $a^{(1)}$, where $a^{(0)}$ is the sub-sequence of all white elements in $a$ and $a^{(1)}$ is the sub-sequence of all black elements in $a$. For example, if $a = [1,2,3,4,5,6]$ and $b = [0,1,0,1,0,0]$, then $a^{(0)} = [1,3,5,6]$ and $a^{(1)} = [2,4]$.\n\nThe number of segments in an array $c_1, c_2, \\dots, c_k$, denoted $\\mathit{seg}(c)$, is the number of elements if we merge all adjacent elements with the same value in $c$. For example, the number of segments in $[1,1,2,2,3,3,3,2]$ is $4$, because the array will become $[1,2,3,2]$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $0$.\n\nHomer wants to find a painting assignment $b$, according to which the number of segments in both $a^{(0)}$ and $a^{(1)}$, i.e. $\\mathit{seg}(a^{(0)})+\\mathit{seg}(a^{(1)})$, is as \\textbf{small} as possible. Find this number.",
    "tutorial": "There are two approaches from different perspectives. DP Approach The first observation is that merging adjacent elements with the same value will not influence the answer. Therefore, without loss of generality, we may assume that there are no adjacent elements with the same value, i.e. $a_{i} \\neq a_{i+1}$ for every $1 \\leq i < n$. We can solve this problem by a DP approach. Let $f(i)$ denote the minimal possible number of segments for sub-array $a_1, a_2, \\dots, a_i$ over all assignments $b_1, b_2, \\dots, b_i$ with $b_i \\neq b_{i-1}$, where $b_{0} = -1$ for convenience. To obtain the answer, we enumerate the last position $1 \\leq i \\leq n$ such that $b_{i-1} \\neq b_i$, and append all elements $a_{i+1}, a_{i+2}, \\dots, a_n$ to the end of $a_i$, which implies an arrangement with $f(i)+n-i$ segments. The minimal number of segments will be the minimum among $f(i)+n-i$ over all $1 \\leq i \\leq n$. It is straightforward to see that $f(0) = 0$ and $f(1) = 1$. For $2 \\leq i \\leq n$, $f(i)$ can be computed by enumerating every possible position $1 \\leq j < i$ such that $b_{j-1} \\neq b_j = b_{j+1} = \\dots = b_{i-1} \\neq b_i$. That is, $a_j, a_{j+1}, \\dots, a_{i-1}$ are assigned to the same sub-sequence, and $a_{j-1}$ and $a_i$ are assigned to the other sub-sequence. Since no adjacent elements has the same value (by our assumption), there are $(i-j)$ segments in $a_j, a_{j+1}, \\dots, a_{i-1}$ (we note that the first segment, i.e. the segment of $a_j$, is counted in $f(j)$). Moreover, there will be zero or one new segment when concatenating $a_{j-1}$ and $a_{i}$ depending on whether $a_{j-1} = a_i$ or not. Hence, for every $2 \\leq j \\leq n$, we have $f(i) = \\min_{1 \\leq j < i} \\{ f(j) + (i-j-1) + [a_{j-1} \\neq a_i] \\},$ To optimize the DP recurrence, we fix $i$, and let $g(j) = f(j) + (i-j-1) + [a_{j-1} \\neq a_i]$, then $f(i) = \\max_{1\\leq j < i}\\{g(j)\\}$. We can observe that Lemma 1. For $2 \\leq i \\leq n$, we have $f(i) = \\min\\{ g(i-1), g(j^*) \\},$ This lemma is very intuitive, which means we need only to consider two cases: one is to just append $a_i$ after $a_{i-1}$ in the same sub-sequence, and the other is to append $a_i$ after the closest $a_{j}$ with the same value, i.e. $a_i = a_j$, and then assign the elements between them (not inclusive) to the other sub-sequence. With this observation, we immediately obtain an $O(n)$ DP solution. The proof is appended below for completeness. Proof: For every $1 \\leq j < i$, we have $f(i) \\leq g(j) = f(j) + (i-j-1) + [a_{j-1} \\neq a_i] \\leq f(j) + i - j,$ Now we consider $g(j)$ for every $1 \\leq j < i$ in two cases. $a_{j-1} \\neq a_i$. We have $\\begin{aligned} g(j) & = f(j) + (i-j-1) + 1 \\\\ & = f(j)-j+i \\\\ & \\geq f(i-1)-(i-1) + i \\\\ & = f(i-1)+1 \\\\ & \\geq g(i-1).\\end{aligned}$ $\\begin{aligned} g(j) & = f(j) + (i-j-1) + 1 \\\\ & = f(j)-j+i \\\\ & \\geq f(i-1)-(i-1) + i \\\\ & = f(i-1)+1 \\\\ & \\geq g(i-1).\\end{aligned}$ $a_{j-1} = a_i$. Suppose there are two different positions $j_1$ and $j_2$ such that $1 \\leq j_1 < j_2 < i$ and $a_{j_1-1} = a_{j_2-2} = a_i$, then $\\begin{aligned} g(j_1) & = f(j_1) + (i-j_1-1) \\\\ & = f(j_1) -j_1 +i-1 \\\\ & \\geq f(j_2)-j_2+i-1 \\\\ & = g(j_2). \\end{aligned}$ $\\begin{aligned} g(j_1) & = f(j_1) + (i-j_1-1) \\\\ & = f(j_1) -j_1 +i-1 \\\\ & \\geq f(j_2)-j_2+i-1 \\\\ & = g(j_2). \\end{aligned}$ Greedy Approach Consider we have a computer whose cache has only two registers. Let's suppose the array $a$ is a sequence of memory access to the computer. The problem is then converted to a more intuitive one that asks the optimal cache replacement. Suppose the current two registers contains two memory accesses $x$ and $y$, and the current requirement memory access is $z$. The greedy strategy is simple: If $z$ matches one of $x$ and $y$, just do nothing. Otherwise, the register that contains the memory access whose next occurrence is farther than the other will be replaced by $z$. This strategy is know as Bélády's algorithm or farthest-in-the-future cache/page replacement policy (see here for more information). The complexity is $O(n)$ since we only need to preprocess every element's next occurrence. DP:",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = 100010;\n \nint n;\nint a[MAXN];\nint pos[MAXN], nxt[MAXN];\n \nvoid solve()\n{\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\tfor (int i = 0; i <= n; ++i)\n\t\tpos[i] = n + 1;\n\tfor (int i = n; i >= 0; --i)\n\t{\n\t\tnxt[i] = pos[a[i]];\n\t\tpos[a[i]] = i;\n\t}\n\tint x = 0, y = 0; // the last elements of the two subarrays\n\tint res = 0;\n\tfor (int z = 1; z <= n; ++z)\n\t{\n\t\t// if one of the two last elements matches a[z], just append a[z] after it.\n\t\tif (a[x] == a[z])\n\t\t{\n\t\t\tx = z;\n\t\t}\n\t\telse if (a[y] == a[z])\n\t\t{\n\t\t\ty = z;\n\t\t}\n\t\t// otherwise, replace the later one.\n\t\telse if (nxt[x] > nxt[y])\n\t\t{\n\t\t\tres += 1;\n\t\t\tx = z;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres += 1;\n\t\t\ty = z;\n\t\t}\n\t}\n\tprintf(\"%d\\n\", res);\n}\n \nint main()\n{\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1479",
    "index": "C",
    "title": "Continuous City",
    "statement": "Some time ago Homer lived in a beautiful city. There were $n$ blocks numbered from $1$ to $n$ and $m$ directed roads between them. Each road had a positive length, and each road went from the block with the smaller index to the block with the larger index. For every two (different) blocks, there was at most one road between them.\n\nHomer discovered that for some two numbers $L$ and $R$ the city was $(L, R)$-continuous.\n\nThe city is said to be $(L, R)$-continuous, if\n\n- all paths from block $1$ to block $n$ are of length between $L$ and $R$ (inclusive); and\n- for every $L \\leq d \\leq R$, there is \\textbf{exactly one} path from block $1$ to block $n$ whose length is $d$.\n\nA path from block $u$ to block $v$ is a sequence $u = x_0 \\to x_1 \\to x_2 \\to \\dots \\to x_k = v$, where there is a road from block $x_{i-1}$ to block $x_{i}$ for every $1 \\leq i \\leq k$. The length of a path is the sum of lengths over all roads in the path. Two paths $x_0 \\to x_1 \\to \\dots \\to x_k$ and $y_0 \\to y_1 \\to \\dots \\to y_l$ are different, if $k \\neq l$ or $x_i \\neq y_i$ for some $0 \\leq i \\leq \\min\\{k, l\\}$.\n\nAfter moving to another city, Homer only remembers the two special numbers $L$ and $R$ but forgets the numbers $n$ and $m$ of blocks and roads, respectively, and how blocks are connected by roads. However, he believes the number of blocks should be no larger than $32$ (because the city was small).\n\nAs the best friend of Homer, please tell him whether it is possible to find a $(L, R)$-continuous city or not.",
    "tutorial": "The answer is always \"YES\". For convenience, we write $(x, y, z)$ for a directed road from block $x$ to block $y$ of length $z$. Step 1. We can solve the case $L = 1$ and $R = 2^k$ for $k \\geq 0$ inductively. The case for $k = 0$ is trivial, i.e. only one edge $(1, 2, 1)$. Suppose there is a city of $k + 2$ blocks for $L = 1$ and $R = 2^k$ for some $k \\geq 0$, and the induced city from block $1$ to block $x$ is $(1, 2^{x-2})$-continuous for every $2 \\leq x \\leq k + 2$. Let block $k + 3$ be a new block, and add $(1, k+3, 1)$ and $(x, k+3, 2^{x-2})$ for $2 \\leq x \\leq k+2$. We can see that the new city containing block $k + 3$ is $(1, 2^{k+1})$-continuous. Step 2. Suppose $L = 1$ and $R > 1$. Let $R - 1 = \\sum_{i=0}^k R_i 2^i$ be the binary representation of $R - 1$, where $0 \\leq R_i \\leq 1$. Let $G_k$ be the $(1, 2^k)$-continuous city constructed in Step 1. Let block $k + 3$ be a new block. Connect $(1, k+3, 1)$, and then for every $0 \\leq i \\leq k$, if $R_i = 1$, then connect $(i+2, k+3, 1+\\sum_{j=i+1}^k R_j 2^j)$. We can see that the new city containing block $k + 3$ is $(1, R)$-continuous. Step 3. Suppose $1 < L \\leq R$. Consider $H_{R-L+1}$, where $H_R$ denotes the $(1, R)$-continuous city constructed in Step 2 and there are $k$ blocks in $H_{R-L+1}$. Connect $(k, k+1, L-1)$. We can see that the new city containing block $k + 1$ is $(L, R)$-continuous. We note that there is at most $23$ blocks in our constructed city.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvector<tuple<int, int, int>> edges;\n \nvoid addedge(int x, int y, int z)\n{\n\tedges.push_back({ x, y, z });\n}\n \nint solve(int L, int R)\n{\n\tif (L > 1)\n\t{\n\t\tint k = solve(1, R - L + 1);\n\t\taddedge(k, k + 1, L - 1);\n\t\treturn k + 1;\n\t}\n\tif ((R & -R) == R) // if L == 1 and R is a power of 2\n\t{\n\t\tint k = __builtin_ctz(R);\n\t\taddedge(1, 2, 1);\n\t\tfor (int i = 3; i <= k + 2; ++i)\n\t\t{\n\t\t\taddedge(1, i, 1);\n\t\t\tfor (int j = 2; j < i; ++j)\n\t\t\t\taddedge(j, i, 1 << (j - 2));\n\t\t}\n\t\treturn k + 2;\n\t}\n\tint k = 0;\n\twhile (1 << (k + 1) <= R - 1) ++k;\n\tsolve(1, 1 << k);\n\taddedge(1, k + 3, 1);\n\tfor (int i = 0; i <= k; ++i)\n\t\tif ((R - 1) >> i & 1)\n\t\t\taddedge(i + 2, k + 3, 1 + ((R - 1) >> (i + 1) << (i + 1)));\n\treturn k + 3;\n}\n \nint main()\n{\n\tint L, R;\n\tscanf(\"%d%d\", &L, &R);\n\tputs(\"YES\");\n\tint n = solve(L, R);\n\tprintf(\"%d %d\\n\", n, (int)edges.size());\n\tfor (auto [x, y, z] : edges) printf(\"%d %d %d\\n\", x, y, z);\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1479",
    "index": "D",
    "title": "Odd Mineral Resource",
    "statement": "In Homer's country, there are $n$ cities numbered $1$ to $n$ and they form a tree. That is, there are $(n-1)$ undirected roads between these $n$ cities and every two cities can reach each other through these roads.\n\nHomer's country is an industrial country, and each of the $n$ cities in it contains some mineral resource. The mineral resource of city $i$ is labeled $a_i$.\n\nHomer is given the plans of the country in the following $q$ years. The plan of the $i$-th year is described by four parameters $u_i, v_i, l_i$ and $r_i$, and he is asked to find any mineral resource $c_i$ such that the following two conditions hold:\n\n- mineral resource $c_i$ appears an \\textbf{odd} number of times between city $u_i$ and city $v_i$; and\n- $l_i \\leq c_i \\leq r_i$.\n\nAs the best friend of Homer, he asks you for help. For every plan, find any such mineral resource $c_i$, or tell him that there doesn't exist one.",
    "tutorial": "Let $s(u, v, c)$ denote the number of cities between city $u$ and city $v$, whose mineral resource is $c$. We restate the problem that for each query $u, v, l, r$, find an integer $c$ such that $l \\leq c \\leq r$ and $s(u, v, c) \\not\\equiv 0 \\pmod 2$. We give a randomized algorithm with success probability extremely high. For every kind of mineral resources $1 \\leq i \\leq n$, we assign a random variable $X_i$ to it. Those random variables $X_i$ are independent and identically uniformly distributed from $[0, 2^{64}-1]$. For every city $u$, we assign its weight to be $X_{c_u}$. For every query $u, v, l, r$, Let $f(u, v, l, r)$ be the bitwise XOR of all weights of all cities between city $u$ and city $v$, whose mineral resources are in $[l, r]$. We claim that $\\Pr\\left[\\, f(u, v, l, r) = 0 \\mid \\forall c, s(u, v, c) \\equiv 0 \\pmod 2 \\,\\right] = 1$, which means that if a suitable $c$ does not exist then $f(u, v, l, r) = 0$ for certainty, and $\\Pr\\left[\\, f(u, v, l, r) \\neq 0 \\mid \\exists c, s(u, v, c) \\not\\equiv 0 \\pmod 2 \\,\\right] = 1-2^{-64}$, which means that if a suitable $c$ does exist then $f(u, v, l, r) \\neq 0$ with high probability. $\\Pr\\left[\\, \\forall c, s(u, v, c) \\equiv 0 \\pmod 2 \\mid f(u, v, l, r) = 0 \\,\\right] = 1-2^{-64}$, which implies with high probability no suitable mineral resource exists if $f(u, v, l, r) = 0$, and $\\Pr\\left[\\, \\exists c, s(u, v, c) \\not\\equiv 0 \\pmod 2 \\mid f(u, v, l, r) \\neq 0 \\,\\right] = 1$, which implies with certainty at least one suitable mineral resource exists. to report no solution if $f(u, v, l, r) = 0$, and to find a $c$ ($l \\leq c \\leq r$) such that $f(u, v, c, c) \\neq 0$ if $f(u, v, l, r) \\neq 0$. Now consider there are $q$ queries. Let $A_i$ denote the event that the $i$-th query succeeds. The $i$-th query will succeed with probability $\\Pr[A_i] \\geq 1-2^{-64}$ (however, they may not be independent). Then we have $\\begin{aligned} \\Pr\\left[ \\bigwedge_{i=1}^{q} A_i \\right] & = 1 - \\Pr\\left[ \\bigvee_{i=1}^q \\bar A_i \\right] \\\\ & \\geq 1 - \\sum_{i=1}^q \\Pr[\\bar A_i] \\\\ & = 1 - \\sum_{i=1}^q \\left( 1 - \\Pr[A_i] \\right) \\\\ & \\geq 1 - \\sum_{i=1}^q \\left( 1 - \\left( 1 - 2^{-64} \\right) \\right) \\\\ & = 1 - 2^{-64}q, \\end{aligned}$ To this end, we shall compute $f(u, v, l, r)$ and find a $c$ ($l \\leq c \\leq r$) such that $f(u, v, c, c) \\neq 0$. This can be solved by consistent segment trees. Let's root the tree (by any vertex, say vertex $1$). For every vertex $u$, we maintain a (consistent) segment tree that for each interval $[l, r]$ computes $f(1, u, l, r)$. Let $\\mathit{father}(u)$ be the father of vertex $u$, and $\\mathit{lca}(u, v)$ be the least common ancestor of vertex $u$ and vertex $v$. Then $f(u, v, l, r) = f(1, u, l, r) \\oplus f(1, v, l, r) \\oplus f(1, \\mathit{lca}(u, v), l, r) \\oplus f(1, \\mathit{father}(\\mathit{lca}(u, v)), l, r).$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = 300010;\nconst int MAXK = 20;\n \nmt19937_64 rd(chrono::steady_clock::now().time_since_epoch().count());\n \nint n, q;\nint a[MAXN];\nuint64_t h[MAXN];\nvector<int> v[MAXN];\nint pre[MAXN][MAXK];\nint dis[MAXN];\n \nstruct node\n{\n\tnode* Lc, * Rc;\n\tuint64_t val;\n\tnode()\n\t{\n\t\tLc = Rc = nullptr;\n\t\tval = 0;\n\t}\n\tvoid update()\n\t{\n\t\tthis->val = this->Lc->val ^ this->Rc->val;\n\t}\n};\n \nint tot;\nnode nodes[MAXN * 22];\nnode* root[MAXN];\n \nnode* new_node()\n{\n\tnode* it = &nodes[++tot];\n\treturn it;\n}\n \nnode* build(int L, int R)\n{\n\tnode* it = new_node();\n\tif (L < R)\n\t{\n\t\tint m = (L + R) / 2;\n\t\tit->Lc = build(L, m);\n\t\tit->Rc = build(m + 1, R);\n\t\tit->update();\n\t}\n\treturn it;\n}\n \nnode* modify(node* p, int L, int R, int x)\n{\n\tnode* it = new_node();\n\t*it = *p;\n\tif (L == R)\n\t{\n\t\tit->val ^= h[x];\n\t\treturn it;\n\t}\n\tint m = (L + R) / 2;\n\tif (x <= m)\n\t\tit->Lc = modify(p->Lc, L, m, x);\n\telse if (x > m)\n\t\tit->Rc = modify(p->Rc, m + 1, R, x);\n\tit->update();\n\treturn it;\n}\n \nvoid dfs(int x)\n{\n\tdis[x] = dis[pre[x][0]] + 1;\n\troot[x] = modify(root[pre[x][0]], 1, n, a[x]);\n\tfor (auto y : v[x])\n\t{\n\t\tif (y == pre[x][0]) continue;\n\t\tpre[y][0] = x;\n\t\tdfs(y);\n\t}\n}\n \nint getlca(int x, int y)\n{\n\tif (dis[x] < dis[y]) swap(x, y);\n\tfor (int k = MAXK - 1; k >= 0; --k)\n\t\tif (dis[x] - dis[y] >= 1 << k)\n\t\t\tx = pre[x][k];\n\tif (x == y) return x;\n\tfor (int k = MAXK - 1; k >= 0; --k)\n\t\tif (pre[x][k] != pre[y][k])\n\t\t{\n\t\t\tx = pre[x][k];\n\t\t\ty = pre[y][k];\n\t\t}\n\treturn pre[x][0];\n}\n \nint calc(node* a, node* b, node* c, node* d, int L, int R)\n{\n\tif (L == R) return L;\n\tint m = (L + R) / 2;\n\tif (a->Lc->val ^ b->Lc->val ^ c->Lc->val ^ d->Lc->val)\n\t\treturn calc(a->Lc, b->Lc, c->Lc, d->Lc, L, m);\n\telse\n\t\treturn calc(a->Rc, b->Rc, c->Rc, d->Rc, m + 1, R);\n}\n \nint query(node* a, node* b, node* c, node* d, int L, int R, int x, int y)\n{\n\tif (L == x && R == y)\n\t{\n\t\tif (a->val ^ b->val ^ c->val ^ d->val)\n\t\t\treturn calc(a, b, c, d, L, R);\n\t\telse\n\t\t\treturn -1;\n\t}\n\tint m = (L + R) / 2;\n\tif (y <= m)\n\t\treturn query(a->Lc, b->Lc, c->Lc, d->Lc, L, m, x, y);\n\tif (x > m)\n\t\treturn query(a->Rc, b->Rc, c->Rc, d->Rc, m + 1, R, x, y);\n\tint tmp = query(a->Lc, b->Lc, c->Lc, d->Lc, L, m, x, m);\n\tif (tmp != -1) return tmp;\n\treturn query(a->Rc, b->Rc, c->Rc, d->Rc, m + 1, R, m + 1, y);\n}\n \nint main()\n{\n\tscanf(\"%d%d\", &n, &q);\n\tfor (int i = 1; i <= n; ++i) scanf(\"%d\", &a[i]);\n\tfor (int i = 1; i <= n; ++i) h[i] = rd();\n\tfor (int i = 1; i < n; ++i)\n\t{\n\t\tint x, y;\n\t\tscanf(\"%d%d\", &x, &y);\n\t\tv[x].push_back(y);\n\t\tv[y].push_back(x);\n\t}\n\troot[0] = build(1, n);\n \n\tdfs(1);\n\tfor (int k = 1; k < MAXK; ++k)\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t\tpre[i][k] = pre[pre[i][k - 1]][k - 1];\n \n\twhile (q--)\n\t{\n\t\tint x, y, l, r;\n\t\tscanf(\"%d%d%d%d\", &x, &y, &l, &r);\n\t\tint z = getlca(x, y);\n\t\tint res = query(root[x], root[y], root[z], root[pre[z][0]], 1, n, l, r);\n\t\tprintf(\"%d\\n\", res);\n\t}\n \n\treturn 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "data structures",
      "probabilities",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1479",
    "index": "E",
    "title": "School Clubs",
    "statement": "In Homer's school, there are $n$ students who love clubs.\n\nInitially, there are $m$ clubs, and each of the $n$ students is in exactly one club. In other words, there are $a_i$ students in the $i$-th club for $1 \\leq i \\leq m$ and $a_1+a_2+\\dots+a_m = n$.\n\nThe $n$ students are so unfriendly that every day one of them (chosen \\textbf{uniformly at random} from all of the $n$ students) gets angry. The student who gets angry will do one of the following things.\n\n- With probability $\\frac 1 2$, he leaves his current club, then creates a new club himself and joins it. There is only one student (himself) in the new club he creates.\n- With probability $\\frac 1 2$, he does not create new clubs. In this case, he changes his club to a new one (possibly the same club he is in currently) with probability proportional to the number of students in it. Formally, suppose there are $k$ clubs and there are $b_i$ students in the $i$-th club for $1 \\leq i \\leq k$ (before the student gets angry). He leaves his current club, and then joins the $i$-th club with probability $\\frac {b_i} {n}$.\n\nWe note that when a club becomes empty, students will never join it because any student who gets angry will join an empty club with probability $0$ according to the above statement.Homer wonders the expected number of days until every student is in the same club for the first time.\n\nWe can prove that the answer can be represented as a rational number $\\frac p q$ with $\\gcd(p, q) = 1$. Therefore, you are asked to find the value of $pq^{-1} \\bmod 998\\,244\\,353$. It can be shown that $q \\bmod 998\\,244\\,353 \\neq 0$ under the given constraints of the problem.",
    "tutorial": "Section 1. The Expected Value of Stopping Time There may be several ways to deal with the expected value of stopping time. Here, we decide to give an elegant way to derive the expected stopping time inspired by MiFaFaOvO's comment. Here, we are going to introduce the mathematical tool we will use in the following description (see here for a Chinese explanation.) Consider a random process $A_0, A_1, A_2, \\dots$, where $A_i$ is called the $i$-th event of the process, or the event at time $i$. Let random variable $T \\in \\mathbb{N}$ be its stopping time. That is, for every $t \\in \\mathbb{N}$, It can be decided whether $T = t$ as long as $A_0, A_1, \\dots, A_t$ are given. If there is a function $\\phi(\\cdot)$ that maps an event to a real number such that $\\mathbb{E}[\\,\\phi(A_{t+1})-\\phi(A_t) \\mid A_0, A_1, \\dots, A_t \\,] = -1$ for every $t \\in \\mathbb{N}$, and $\\mathbb{E}[\\phi(A_T)]$ depends on some properties of the events and the stopping time, which is usually a constant in practice. $\\mathbb{E}[T] = \\phi(A_0) - \\phi(A_T).$ To begin our journey, we should first describe an event as something (a number, a tuple, a sequence, or a set) in our problem. We find it naturally to use a (multi-)set $A = \\{ a_1, a_2, \\dots, a_m \\}$ to describe it, where $m$ denotes the number of clubs, the $i$-th of which contains $a_i$ students. We see that the explicit order of the clubs does not matter but the number of students in each club. Furthermore, we notice that every club's status is equal, which implies us to define the potential function as the form $\\phi(A) = \\sum_{a \\in A} f(a) = \\sum_{i=1}^m f(a_i),$ $n = \\sum_{a \\in A} a = \\sum_{i=1}^m a_i.$ We first consider the corner case for the value of $f(0)$. Since students will never join an empty club, $A$ and $A \\cup \\{0\\}$ denotes the events with the same property. Therefore, we need $\\phi(A) = \\phi(A \\cup \\{0\\})$, which immediately yields $f(0) = 0$. We now investigate how the potential function behaves from the $t$-th event $A_t = \\{ a_1, a_2, \\dots, a_m \\}$ to the $(t+1)$-th event $A_{t+1}$. We note that the student who gets angry is in the $i$-th club with probability $\\frac {a_i} n$. After that, the angry student will leave and create a new club with probability $\\frac 1 2$. In this case, $A_{t+1} = \\{ a_1, a_2, \\dots, a_{i-1}, a_i-1, a_{i+1}, \\dots, a_m, 1 \\}$, and we have $\\phi(A_{t+1}) = \\phi(A_t)-f(a_i)+f(a_i-1)+f(1),$ $\\phi(A_{t+1}) = \\phi(A_t)-f(a_i)+f(a_i-1)+f(1),$ join the $j$-th club ($j \\neq i$) with probability $\\frac {a_j} {2n}$. In this case, $A_{t+1} = \\{ a_1, a_2, \\dots, a_i-1, a_j +1, \\dots, a_m\\}$, and we have $\\phi(A_{t+1}) = \\phi(A_t)-f(a_i)-f(a_j)+f(a_i-1)+f(a_j+1),$ $\\phi(A_{t+1}) = \\phi(A_t)-f(a_i)-f(a_j)+f(a_i-1)+f(a_j+1),$ stay still in the $i$-th club with probability $\\frac {a_i} {2n}$. In this case, $A_{t+1} = A_t$, and we have $\\phi(A_{t+1}) = \\phi(A_t).$ $\\phi(A_{t+1}) = \\phi(A_t).$ To sum it up, we get that $\\begin{aligned} \\mathbb{E}[\\, \\phi(A_{t+1}) \\mid A_t \\,] = \\sum_{i=1}^m \\frac {a_i} n \\Bigg[ & \\frac 1 2 \\big(\\phi(A_t)-f(a_i)+f(a_i-1)+f(1)\\big) \\\\ &+ \\sum_{j \\neq i} \\frac {a_j} {2n} \\big( \\phi(A_t)-f(a_i)-f(a_j)+f(a_i-1)+f(a_j+1) \\big) + \\frac {a_i} {2n} \\phi(A_t) \\Bigg]. \\end{aligned}$ $f(1) + \\sum_{i=1}^m \\frac {a_i} {n^2} \\left[ (2n - a_i) f(a_i-1) + (n - a_i) f(a_i+1) - (3n - 2a_i) f(a_i) \\right] + 2 = 0.$ There are several possible ways to assign the value of $f(a)$. We choose the most simple one such that $f(1)+2 = 0$, which removes the constant term. Under this assignment, we have $f(1) = -2$. After this, we have to make that $(2n - a) f(a-1) + (n - a) f(a+1) - (3n - 2a) f(a) = 0,$ $(n-a) \\left[ f(a+1)-f(a) \\right] = (2n-a) \\left[ f(a)-f(a-1) \\right].$ We let $g(a) = f(a+1)-f(a)$ for $a \\geq 0$. Therefore, $g(0) = f(1)-f(0) = -2$, and $\\begin{aligned} g(a) & = \\frac {2n-a} {n-a} g(a-1) \\\\ & = \\frac {2n-a} {n-a} \\cdot \\frac {2n-(a-1)} {n-(a-1)} g(a-1) \\\\ & = \\dots \\\\ & = \\frac {2n-1} {n-1} \\cdot \\frac {2n-2} {n-2} \\cdot \\dots \\cdot \\frac {2n-a} {n-a} g(0). \\end{aligned}$ $\\begin{aligned} f(a) & = f(0) + g(0) + g(1) + \\dots + g(a-1) \\\\ & = -2 \\left[ 1 + \\frac {P(1)} {Q(1)} + \\frac {P(2)} {Q(2)} + \\dots + \\frac {P(1)P(2) \\dots P(a-1)} {Q(1)Q(2) \\dots Q(a-1)} \\right], \\end{aligned}$ Section 2. The Trick for the Prefix Sum by Generating Functions For convenience, we denote $S(a) = \\frac {P(1)} {Q(1)} + \\frac {P(2)} {Q(2)} + \\dots + \\frac {P(1)P(2) \\dots P(a)} {Q(1)Q(2) \\dots Q(a)},$ Let $N > a$ be a large enough positive integer. Then we have $\\begin{aligned} S(a) = \\frac 1 {Q(1)Q(2) \\dots Q(N)} \\Big[ & P(1)Q(2)Q(3)\\dots Q(a)Q(a+1) \\dots Q(N) + \\\\ & P(1)P(2)Q(3)\\dots Q(a)Q(a+1) \\dots Q(N) + \\\\ & \\dots + \\\\ & P(1)P(2)P(3)\\dots P(a)Q(a+1) \\dots Q(N) \\Big]. \\end{aligned}$ $\\begin{aligned} R(z) = & P(z+1)Q(z+2)Q(z+3) \\dots Q(z+B) + \\\\ & P(z+1)P(z+2)Q(z+3) \\dots Q(z+B) + \\\\ & \\dots + \\\\ & P(z+1)P(z+2)P(z+3) \\dots P(z+B). \\end{aligned}$ $\\begin{aligned} s(a) = & \\sum_{k=0}^{\\lfloor{a/B}\\rfloor} P(1)\\dots P(kB) R(kB) Q((k+1)B+1) \\dots Q(N) \\\\ & + \\sum_{i=(\\lfloor{a/B}\\rfloor+1)B+1}^a P(1)\\dots P(i) Q(i+1) \\dots Q(N). \\end{aligned}$ $\\sum_{k=0}^{\\lfloor{a/B}\\rfloor} \\mathfrak{P}(k) R(kB) \\mathfrak{Q}(k+1).$ Compute $R(z)$ We deal with $R(z)$ first. We note that $R(z)$ is a polynomial of degree $B$ and we want to compute $R(kB)$ for every $0 \\leq k \\leq N/B$. If we can obtain the values of $R(0), R(1), \\dots, R(B)$, then by Lagrange interpolation, we can recover the polynomial $R(z)$. And then, if we know the exact polynomial $R(z)$, then by multi-point evaluation trick, we can compute the values of $R(kB)$ for every $k \\leq N/B$. The total time complexity would be $O(\\sqrt{N} \\log^2 N)$. We can compute $R(0)$ in $O(B)$ time. And then, we note that $R(z) = \\frac {Q(z+B)} {P(z)} R(z-1) - Q(z+1) \\dots Q(z+B) + P(z+1) \\dots P(z+B).$ Bonus: A \"log\" in the complexity may be eliminated by some trick similar to min_25's blog? Compute $\\mathfrak{P}(k)$ This subproblem is very similar to compute the factorial-like product, which is originally mentioned in min_25's blog. To solve it, we define $f_P(z) = P(z+1)P(z+2) \\dots P(z+B).$ compute $\\mathfrak{Q}(k)$ This subproblem is more tricky if we are able to compute $\\mathfrak{P}(k)$ fast. Similarly, we define $f_Q(z)$ as what we did when computing $\\mathfrak{P}(k)$. Let $\\mathfrak{Q}'(k)$ be the prefix block products of $Q(x)$ as an analog for $\\mathfrak{P}(k)$ and $P(x)$. It can be easily seen that $\\mathfrak{Q}(k) = \\frac {Q(1)Q(2)\\dots Q(N)} {\\mathfrak{Q}'(k)}.$ Having computed all values we need in the previous several sections, we are able to compute the value of a single $f(a)$ in $O(\\sqrt N)$ time. Therefore, the overall complexity is $O(\\sqrt N \\log^2 N + m \\sqrt N)$. Bonus: Saving $\\log n$ in Complexity Moreover, we can save $\\log n$ in complexity with an improved interpolation method for shifting evaluation values. See the paper \"A. Bostan, P. Gaudry, and E. Schost, Linear recurrences with polynomial coefficients and application to integer factorization and Cartier-Manin operator. SIAM Journal of Computing, 36(6): 1777-1806. 2007\". Shifting evaluation values Suppose given are a polynomial $f(x)$ of degree $d$ by a point-value representation $f(0), f(1), \\dots, f(d)$ and a shift $\\delta$. It is asked to compute an alternative point-value representation $f(\\delta), f(\\delta+1), \\dots, f(\\delta+d)$. A straightforward way to solve this problem is to directly make use of Lagrange interpolation and multi-point evaluation, which yields an $O(d \\log^2 d)$ arithmetic complexity algorithm. In fact, we can do it better in $O(d \\log d)$ time. Recall the formula of Lagrange interpolation that given $n$ points $(x_i, y_i)$ where $y_i = f(x_i)$, then the unique polynomial of degree $(n-1)$ is $f(x) = \\sum_{i=1}^n y_{i} \\prod_{j \\neq i} \\frac {x-x_j} {x_i-x_j}.$ $f(x) = \\sum_{i=0}^d f(i) \\prod_{j \\neq i} \\frac {x-j} {i-j}.$ $\\begin{aligned} f(\\delta+k) & = \\sum_{i=0}^d f(i) \\prod_{j \\neq i} \\frac {\\delta+k-j} {i-j} \\\\ & = \\left( \\prod_{j=0}^d (\\delta+k-j) \\right) \\left( \\sum_{i=0}^d \\frac {(-1)^{d-i} f(i)} {i! (d-i)!} \\cdot \\frac {1} {\\delta+k-i} \\right). \\end{aligned}$ $A(x) = \\sum_{i=0}^d \\frac {(-1)^{d-i} f(i)} {i! (d-i)!} x^i,$ $B(x) = \\sum_{i=0}^{2d} \\frac {1} {\\delta+i-d} x^i.$ $f(\\delta+k) = \\left( \\prod_{j=0}^d (\\delta+k-j) \\right) [x^{d+k}] A(x)B(x).$ Therefore, $f(\\delta), f(\\delta+1), \\dots, f(\\delta+d)$ can be computed in $O(d \\log d)$ time. Arithmetic sequence shifting Now we consider a modified version: given a polynomial of degree $d$ by a point-value representation $f(0), f(s), f(2s), \\dots, f(ds)$ and a shift $\\delta$, compute $f(\\delta), f(\\delta+s), f(\\delta+2s), \\dots, f(\\delta+ds)$. The trick is to let $g(x) = f(xs)$, which is also a polynomial of degree $d$. Then the problem becomes: given $g(0), g(1), \\dots, g(s)$ and a shift $\\delta' = \\delta/s$, compute $g(\\delta'), g(\\delta'+1), \\dots, g(\\delta'+d)$. Divide and conquer Let's consider how to compute $R(z)$. For convenience, we denote that $\\begin{aligned} R_B(z) = & P(z+1)Q(z+2)Q(z+3) \\dots Q(z+B) + \\\\ & P(z+1)P(z+2)Q(z+3) \\dots Q(z+B) + \\\\ & \\dots + \\\\ & P(z+1)P(z+2)P(z+3) \\dots P(z+B), \\end{aligned}$ $P_B(z) = P(z+1)P(z+2) \\dots P(z+B),$ $Q_B(z) = Q(z+1)Q(z+2) \\dots Q(z+B),$ $\\begin{matrix} R_B(0), & R_B(s), & \\dots, & R_B(sB), \\\\ P_B(0), & P_B(s), & \\dots, & P_B(sB), \\\\ Q_B(0), & Q_B(s), & \\dots, & Q_B(sB). \\end{matrix}$ To compute these values recurrently, we should notice that $R_{2B}(z) = R_B(z) Q_B(z+B) + P_B(z) R_B(z+B),$ $P_{2B}(z) = P_B(z) P_B(z+B),$ $Q_{2B}(z) = Q_B(z) Q_B(z+B).$ $\\begin{aligned} P_{2B}(0) & = P_B(0) P_B(B), \\\\ P_{2B}(s) & = P_B(s) P_B(s+B), \\\\ \\dots, \\\\ P_{2B}(sB) & = P_B(sB) P_B(sB+B), \\\\ P_{2B}(sB+1) & = P_B(sB+1) P_B(sB+B+1), \\\\ \\dots, \\\\ P_{2B}(2sB) & = P_B(2sB) P_B(2sB+B). \\end{aligned}$ $\\begin{matrix} P_B(0), & P_B(s), & \\dots, & P_B(sB), \\\\ P_B(B), & P_B(B+s), & \\dots, & P_B(B+sB), \\\\ P_B(sB), & P_B(sB+s), & \\dots, & P_B(sB+sB), \\\\ P_B(B+sB), & P_B(B+sB+s), & \\dots, & P_B(B+sB+sB). \\end{matrix}$ $T(d) = T(d/2) + O(d \\log d).$ In our case, $d = O(\\sqrt N)$, then the complexity is reduced to $O(\\sqrt N \\log N + m \\sqrt N)$. Conclusion We use the trick, SQRT decomposition, to split summations into blocks, and then use Lagrange interpolation and multi-point evaluation to compute the value in each block. We obtain an algorithm with complexity $O(\\sqrt N \\log^2 N + m \\sqrt N)$. A more subtle trick to save a $\\log N$ is obtained by the shifting technique, which yields a faster algorithm with complexity $O(\\sqrt N \\log N + m \\sqrt N)$. The constant factor of Lagrange interpolation and multi-point evaluation is very large, so this approach to save a $\\log N$ brings a significant improvement. However, we allow suboptimal solutions that directly use Lagrange interpolation and multi-point evaluation to get AC.",
    "tags": [
      "dp",
      "fft",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1480",
    "index": "A",
    "title": "Yet Another String Game",
    "statement": "Homer has two friends Alice and Bob. Both of them are string fans.\n\nOne day, Alice and Bob decide to play a game on a string $s = s_1 s_2 \\dots s_n$ of length $n$ consisting of lowercase English letters. They move in turns alternatively and \\textbf{Alice makes the first move}.\n\nIn a move, a player \\textbf{must} choose an index $i$ ($1 \\leq i \\leq n$) that has not been chosen before, and change $s_i$ to any other lowercase English letter $c$ that $c \\neq s_i$.\n\nWhen all indices have been chosen, the game ends.\n\nThe goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "After some observations, we can see that the players should always choose the most significant letter to change, because it coordinates the lexicographical order of the final string most. Therefore, Alice will choose all odd indices while Bob will choose all even indices, and then Alice will change all letters she choose to the smallest possible letters while Bob will change all letters he choose to the largest possible letters. That is, Alice will change letters to \"a\" if the original letter is not \"a\" and to \"b\" otherwise; Bob will change letters to \"z\" if the original letter is not \"z\" and to \"y\" otherwise. The time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n\tstring s;\n\tcin >> s;\n\tfor (int i = 0; i < s.size(); ++i)\n\t{\n\t\tif (i % 2 == 0)\n\t\t{\n\t\t\ts[i] = s[i] == 'a' ? 'b' : 'a';\n\t\t}\n\t\telse\n\t\t{\n\t\t\ts[i] = s[i] == 'z' ? 'y' : 'z';\n\t\t}\n\t}\n\tcout << s << endl;\n}\n \nint main()\n{\n\tint tests;\n\tcin >> tests;\n\twhile (tests--) solve();\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1480",
    "index": "B",
    "title": "The Great Hero",
    "statement": "The great hero guards the country where Homer lives. The hero has attack power $A$ and initial health value $B$. There are $n$ monsters in front of the hero. The $i$-th monster has attack power $a_i$ and initial health value $b_i$.\n\nThe hero or a monster is said to be living, if his or its health value is positive (greater than or equal to $1$); and he or it is said to be dead, if his or its health value is non-positive (less than or equal to $0$).\n\nIn order to protect people in the country, the hero will fight with monsters until either the hero is dead or all the monsters are dead.\n\n- In each fight, the hero can select an arbitrary living monster and fight with it. Suppose the $i$-th monster is selected, and the health values of the hero and the $i$-th monster are $x$ and $y$ before the fight, respectively. After the fight, the health values of the hero and the $i$-th monster become $x-a_i$ and $y-A$, respectively.\n\n\\textbf{Note that the hero can fight the same monster more than once.}\n\nFor the safety of the people in the country, please tell them whether the great hero can kill all the monsters (even if the great hero himself is dead after killing the last monster).",
    "tutorial": "The hero needs $\\lceil b_i/A \\rceil$ attacks to kill the $i$-th monster, and he will obtain $\\lceil b_i/A \\rceil a_i$ damage after that. Suppose the $k$-th monster is the last monster killed by the hero. Then the health value of the hero before the last attack is $h_k = B - \\sum_{i=1}^n \\left\\lceil \\frac {b_i} {A} \\right\\rceil a_i + a_k.$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = 100010;\n \nint A, B, n;\nint a[MAXN], b[MAXN];\n \nvoid solve()\n{\n\tscanf(\"%d%d%d\", &A, &B, &n);\n\tfor (int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &a[i]);\n\tfor (int i = 1; i <= n; ++i)\n\t\tscanf(\"%d\", &b[i]);\n\tint64_t damage = 0;\n\tfor (int i = 1; i <= n; ++i)\n\t\tdamage += int64_t(b[i] + A - 1) / A * a[i];\n\tfor (int i = 1; i <= n; ++i)\n\t\tif (B - (damage - a[i]) > 0)\n\t\t{\n\t\t\tputs(\"YES\");\n\t\t\treturn;\n\t\t}\n\tputs(\"NO\");\n}\n \nint main()\n{\n\tint tests;\n\tscanf(\"%d\", &tests);\n\twhile (tests--) solve();\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1481",
    "index": "A",
    "title": "Space Navigation ",
    "statement": "You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.\n\nSpace can be represented as the $XY$ plane. You are starting at point $(0, 0)$, and Planetforces is located in point $(p_x, p_y)$.\n\nThe piloting system of your spaceship follows its list of orders which can be represented as a string $s$. The system reads $s$ from left to right. Suppose you are at point $(x, y)$ and current order is $s_i$:\n\n- if $s_i = \\text{U}$, you move to $(x, y + 1)$;\n- if $s_i = \\text{D}$, you move to $(x, y - 1)$;\n- if $s_i = \\text{R}$, you move to $(x + 1, y)$;\n- if $s_i = \\text{L}$, you move to $(x - 1, y)$.\n\nSince string $s$ could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, \\textbf{you can delete some orders from $s$ but you can't change their positions}.\n\nCan you delete several orders (possibly, zero) from $s$ in such a way, that you'll reach Planetforces after the system processes all orders?",
    "tutorial": "Hint 1: You can think of this problem as 2 independent 1D questions (one is up and down , and the other is left and right) instead of 1 2D question. Hint 2: For each 1D part what is the interval of positions that you can reach and see if the end point is in this interval. Hint 3: The interval of up and down is [-The count of D , The count of U] and the interval of left and right is [-The count of L , The count of R].",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n    int t;cin>>t;\n    while(t--){\n        int x,y;cin>>x>>y;\n        string s;cin>>s;\n        int u=0,d=0,l=0,r=0;\n        for(int i=0;i<s.length();i++){\n            if(s[i]=='U')u++;\n            else if(s[i]=='R')r++;\n            else if(s[i]=='D')d++;\n            else l++;\n        }\n        if(x > 0 && r >= x )x = 0;\n        if(x < 0 && l >= -x )x = 0;\n        if(y > 0 && u >= y )y = 0;\n        if(y < 0 && d >= -y )y = 0;\n        cout<<((!x && !y)?\"YES\":\"NO\")<<endl;\n    }\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1481",
    "index": "B",
    "title": "New Colony",
    "statement": "After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).\n\nYou are given an array $h_1, h_2, \\dots, h_n$, where $h_i$ is the height of the $i$-th mountain, and $k$ — the number of boulders you have.\n\nYou will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is $h_i$):\n\n- if $h_i \\ge h_{i + 1}$, the boulder will roll to the next mountain;\n- if $h_i < h_{i + 1}$, the boulder will stop rolling and increase the mountain height by $1$ ($h_i = h_i + 1$);\n- if the boulder reaches the last mountain it will fall to the waste collection system and disappear.\n\nYou want to find the position of the $k$-th boulder or determine that it will fall into the waste collection system.",
    "tutorial": "The two key observation here is that if one boulder fall into the collection system all later boulders will fall into the collection system too and the number of boulders that will end up at any mountain is too small (Hence it will be at most $(n-1) \\cdot (100 - 1)$). So we can simulate all boulders throwing until one boulder fall into the collection system, this will take at most $O(100 \\cdot n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define all(x) (x).begin(), (x).end()\n#define fast ios::sync_with_stdio(false);cin.tie(0);\ntypedef long long ll;\ntypedef long double ld;\ntypedef unsigned long long ull;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint main(){\n\tfast\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n,k;\n\t\tcin>>n>>k;\n\t\tvector<int> a(n);\n\t\tfor(int i=0;i<n;i++)cin>>a[i];\n\t\tint mx = *max_element(all(a));\n\t\tif(n * mx < k){\n\t\t\tcout << -1 << '\\n';\n\t\t\tcontinue;\n\t\t}\n\t\tint ans = n+1;\n\t\tfor(int b=0;b<k;b++){\n\t\t\tint to = -2;\n\t\t\tfor(int i=0;i<n-1;i++){\n\t\t\t\tif(a[i] < a[i+1]){\n\t\t\t\t\tto = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tans = to + 1;\n\t\t\tif(to == -2)break;\n\t\t\ta[to]++;\n\t\t}\n\t\tcout << ans << '\\n';\n\t}\t\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1481",
    "index": "C",
    "title": "Fence Painting",
    "statement": "You finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence — so plain and boring, that you'd like to repaint it.\n\nYou have a fence consisting of $n$ planks, where the $i$-th plank has the color $a_i$. You want to repaint the fence in such a way that the $i$-th plank has the color $b_i$.\n\nYou've invited $m$ painters for this purpose. The $j$-th painter will arrive at the moment $j$ and will recolor \\textbf{exactly one} plank to color $c_j$. For each painter you can choose which plank to recolor, but you can't turn them down, i. e. each painter has to color exactly one plank.\n\nCan you get the coloring $b$ you want? If it's possible, print for each painter which plank he must paint.",
    "tutorial": "We must first see that the most important painter is the last one (and he will paint plank $x$ where $b_x = c_m$) because of two reasons: when he paints plank $x$ it won't be changed and if some other painter have a color that we don't need we can make him paint plank $x$, which will be repainted later. Now we need to find $x$ where $b_x = c_m$, there are three options: $b_x \\ne a_x$. $b_x = a_x$. There are no $b_x = c_m$ this case is impossible and the answer is \"NO\". If the first two are true we choose $x$ such that $b_x \\ne a_x$, then we greedily distribute all painters $j$ $(1 \\le j < m)$ such that: There is plank $i$ such that $b_i = c_j$ and $b_i \\ne a_i$ then the $j^{th}$ painter will paint plank $i$ (as a result the color of the $i^{th}$ plank will be changed). There is no plank $i$ such that $b_i = c_j$ and $b_i \\ne a_i$ then the $j^{th}$ painter will paint plank $x$. At the end there might be some planks that didn't end up as we want so we make a last liner check on all planks $i$ and check if $b_i = a_i$, the total time is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define mod 1000000007\n#define oo 1000000010\nconst int N = 300010;\n\nint n , m;\n\nint a[N] , b[N] , c[N] , ans[N];\n\nvector< int > g[N];\n\nvoid solve(){\n\tscanf(\"%d%d\",&n,&m);\n\tfor(int i = 1 ;i <= n;i++) g[i].clear();\n\tfor(int i = 0 ;i < n;i++)\n\t\tscanf(\"%d\",&a[i]);\n\tfor(int i = 0 ;i < n;i++){\n\t\tscanf(\"%d\",&b[i]);\n\t\tif(b[i] != a[i])\n\t\t\tg[b[i]].push_back(i);\n\t}\n\tfor(int i = 0; i < m;i++){\n\t\tscanf(\"%d\",&c[i]);\n\t}\n\tint last = -1;\n\tif((int)g[c[m - 1]].size() > 0){\n\t\tlast = g[c[m - 1]].back();\n\t\tg[c[m - 1]].pop_back();\n\t}\n\telse{\n\t\tfor(int i = 0 ;i < n;i++){\n\t\t\tif(b[i] == c[m - 1]){\n\t\t\t\tlast = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif(last == -1){\n\t\tputs(\"NO\");\n\t\treturn;\n\t}\n\tans[m - 1] = last;\n\tfor(int i = 0 ;i < m - 1;i++){\n\t\tif((int)g[c[i]].size() == 0){\n\t\t \tans[i] = last;\n\t\t}\n\t\telse{\n\t\t\tans[i] = g[c[i]].back();\n\t\t\tg[c[i]].pop_back();\n\t\t}\n\t}\n\tfor(int i = 1;i <= n;i++){\n\t\tif((int)g[i].size() > 0){\n\t\t\tputs(\"NO\");\n\t\t\treturn;\n\t\t}\n\t}\n\tputs(\"YES\");\n\tfor(int i = 0 ;i < m;i++){\n\t\tif(i) putchar(' ');\n\t\tprintf(\"%d\",ans[i] + 1);\n\t}\n\tputs(\"\");\n}\n\n\n\nint main(){\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1481",
    "index": "D",
    "title": "AB Graph",
    "statement": "Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem.\n\nYou are given a complete directed graph with $n$ vertices without self-loops. In other words, you have $n$ vertices and each pair of vertices $u$ and $v$ ($u \\neq v$) has both directed edges $(u, v)$ and $(v, u)$.\n\nEvery directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $(u, v)$ and $(v, u)$ may have different labels).\n\nYou are also given an integer $m > 0$. You should find a path of length $m$ such that the string obtained by writing out edges' labels when going along the path is a \\textbf{palindrome}. The length of the path is the number of edges in it.\n\n\\textbf{You can visit the same vertex and the same directed edge any number of times}.",
    "tutorial": "If you can find any two nodes $x$, $y$ such that the edge going from $x$ to $y$ has the same value as the edge going from $y$ to $x$, then the answer is obviously YES. If not, if $m$ is odd you can just choose any two nodes $x$ and $y$ and keep going $y \\xrightarrow{} x \\xrightarrow{} y \\xrightarrow{} x \\xrightarrow{} y \\xrightarrow{} x \\xrightarrow{} y$ until you have a string with length $m$, because any alternating string of odd length is a palindrome. If $m$ is even than you should check if there is two consecutive edges with the same value, that is you need to find three different nodes $x$, $y$ and $z$ such that the edge $x \\xrightarrow{} y$ has the same value as the edge $y \\xrightarrow{} z$. Otherwise any string you can get will be an alternating string and any alternating string with even length is not a palindrome (note that for $(n \\geq 3)$ it is always possible to find these three nodes). After finding nodes $x$ $y$, $z$ a way that guarantees you can generate a palindrome string is: if $\\frac{m}{2}$ is odd just keep moving $x \\xrightarrow{} y \\xrightarrow{} z \\xrightarrow{} y \\xrightarrow{} x \\xrightarrow{} y \\xrightarrow{} z$ until you have a string of length $m$. The string will look like aabbaabb...aabbaa which is palindrome. if $\\frac{m}{2}$ is even then keep moving $y \\xrightarrow{} z \\xrightarrow{} y \\xrightarrow{} x \\xrightarrow{} y \\xrightarrow{} z \\xrightarrow{} y$ until you have a string of length $m$. The string will look like abbaabba...abba which is palindrome. Complexity $O(n^{2} + m)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define mod 998244353\n#define oo 1000000010\nconst int N = 1010;\nint n , m;\nchar grid[N][N];\nint has[N][2];\n\n\nvoid solve(){\n\tscanf(\"%d%d\",&n,&m);\n\tfor(int i = 0 ;i <= n;i++) has[i][0] = has[i][1] = -1;\n\tfor(int i = 0 ;i < n;i++){\n\t\tscanf(\"%s\",grid[i]);\n\t\tfor(int j = 0  ;j < n;j++){\n\t\t\tif(j == i) continue;\n\t\t\thas[i][grid[i][j] - 'a'] = j;\n\t\t}\n\t}\n\tif(m & 1){\n\t\tputs(\"YES\");\n\t\tfor(int i = 0 ;i < m + 1;i++){\n\t\t\tif(i) putchar(' ');\n\t\t\tprintf(\"%d\",(i & 1) + 1);\n\t\t}\n\t\tputs(\"\");\n\t\treturn;\n\t}\n\tfor(int i = 0 ;i < n;i++){\n\t\tfor(int j = i + 1;j < n;j++){\n\t\t\tif(grid[i][j] == grid[j][i]){\n\t\t\t\tputs(\"YES\");\n\t\t\t\tfor(int k = 0 ;k < m + 1;k++){\n\t\t\t\t\tif(k) putchar(' ');\n\t\t\t\t\tprintf(\"%d\",(k & 1 ? i + 1 : j + 1));\n\t\t\t\t}\n\t\t\t\tputs(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i = 0 ;i < n;i++){\n\t\tfor(int j = 0;j < n;j++){\n\t\t    if(i == j) continue;\n\t\t\tif(has[j][grid[i][j] - 'a'] == -1) continue;\n\t\t\tputs(\"YES\");\n\t\t\tint cur = has[j][grid[i][j] - 'a'];\n\t\t\tif((m / 2) % 2 == 1){\n\t\t\t\tfor(int k = 0 ;k < m + 1;k++){\n\t\t\t\t\tif(k) putchar(' ');\n\t\t\t\t\tif(k % 4 == 0)\n\t\t\t\t\t\tprintf(\"%d\",i + 1);\n\t\t\t\t\telse if(k % 4 == 2)\n\t\t\t\t\t\tprintf(\"%d\",cur + 1);\n\t\t\t\t\telse\n\t\t\t\t\t\tprintf(\"%d\",j + 1);\n\t\t\t\t}\n\t\t\t\tputs(\"\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprintf(\"%d\",j + 1);\n\t\t\tfor(int k = 0 ;k < m / 2;k++){\n\t\t\t\tif(k & 1) printf(\" %d\",j + 1); else printf(\" %d\",cur + 1);\n\t\t\t}\n\t\t\tfor(int k = 0 ;k < m / 2;k++){\n\t\t\t\tif(k & 1) printf(\" %d\",j + 1); else printf(\" %d\",i + 1);\n\t\t\t}\n\t\t\tputs(\"\");\n\t\t\treturn;\t\t\t\n\t\t}\n\t}\n\tputs(\"NO\");\n\treturn;\n}\n\nint main(){\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile(t--)\n\t    solve();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1481",
    "index": "E",
    "title": "Sorting Books",
    "statement": "One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first.\n\nThere are $n$ books standing in a row on the shelf, the $i$-th book has color $a_i$.\n\nYou'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.\n\nIn one operation you can take one book from any position on the shelf and move it to the right end of the shelf.\n\nWhat is the minimum number of operations you need to make the shelf beautiful?",
    "tutorial": "Lets try to solve the opposite version of the problem where you want to find the maximum number of books that will stay unmoved, so we will choose number of books that will stay unmoved and then move the rest in a way that will make the shelf beautiful. To do that lets first for each color $c$ find the leftmost and rightmost occurrence $l_c$ and $r_c$ and the frequency of this color $f_c$.Then we will use $dp_i$ which will find for each $i$ the maximum number of books that we can leave unmoved in the suffix $[i,n]$. We will go from right to left and for each index $i$ the $dp$ will work as follow : If $i = l_{a_i}$, we leave all occurrences of color $a_i$ unmoved and move everything in between the first and last occurrence of color $a_i$, so between $l_{a_i}$ and $r_{a_i}$ only books with color $a_i$ will stay unmoved, we can see that this will be only true if we are at the first occurrence of color $a_i$ (when $i = l_{a_i}$ because we want to cover the segment $[l_{a_i} , r_{a_i}]$), as a result $dp_i = f_{a_i} + dp_{r_{a_i} + 1}$. If $i \\ne l_{a_i}$, we can keep all books with color $a_i$ in range $[i,n]$ unmoved and move everything else, as a result $dp_i = cf_{a_i}$ where $cf_{a_i}$ is the number of books with color $a_i$ in range $[i,n]$ (we can update this array as we move) (note that here we move all books even those after $r_{a_i}$). In either cases we can move the book $a_i$ and get $dp_i = dp_{i+1}$. The answer will be $n - dp_1$ and the time is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define all(x) (x).begin(), (x).end()\n#define fast ios::sync_with_stdio(false);cin.tie(0);\ntypedef long long ll;\ntypedef long double ld;\ntypedef unsigned long long ull;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint main(){\n\tfast\n\tint n;\n\tcin>>n;\n\tvector<int> a(n),f(n),cf(n);\n\tvector<pair<int,int>> at(n,{-1,-1});\n\tfor(int i=0;i<n;i++){\n\t\tcin>>a[i];\n\t\ta[i]--;\n\t\tf[a[i]]++;\n\t\tif(at[a[i]].first == -1)at[a[i]] = {i,i};\n\t\tat[a[i]].second = i;\n\t}\n\tvector<int> dp(n+1);\n\n\tfor(int i=n-1;i>=0;i--){\n\t\tdp[i] = dp[i+1];\n\t\tcf[a[i]]++;\n\t\tif(i == at[a[i]].first)dp[i] = max(dp[i] , dp[at[a[i]].second + 1] + f[a[i]]);\n\t\telse dp[i] = max(dp[i] , cf[a[i]]);\n\t}\n\n\tcout << n - dp[0] << '\\n';\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1481",
    "index": "F",
    "title": "AB Tree",
    "statement": "Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd.\n\nThe problem is:\n\nYou are given a connected tree rooted at node $1$.\n\nYou should assign a character a or b to every node in the tree so that the total number of a's is equal to $x$ and the total number of b's is equal to $n - x$.\n\nLet's define a string for each node $v$ of the tree as follows:\n\n- if $v$ is root then the string is just one character assigned to $v$:\n- otherwise, let's take a string defined for the $v$'s parent $p_v$ and add to the end of it a character assigned to $v$.\n\nYou should assign every node a character in a way that \\textbf{minimizes the number of distinct strings} among the strings of all nodes.",
    "tutorial": "let the diameter of the tree (the maximum distance between a root and a leaf) be $d$, then the answer couldn't be less than $d+1$ because you will add strings of all lengths between $1$ and $d+1$. In order to have the answer $d+1$, you need all strings with the same length to be equal, so all nodes on the same level must have the same character. Let's define an array $a$ of size $d+1$, such that $a_i$ = (number of nodes at level $i$). So if the answer is $d+1$ there must exist a subset from $a$ with sum $x$, so we assign character a to all the nodes with a level belongs to that subset, and character b to all other nodes. To check if there is a subset with sum $x$ we can use dynamic programming, the complexity of this solution is $O(x \\cdot (d+1))$, which is in worst case $O(n^{2})$. But since the sum of array $a$ is equal to $n$, the number of unique values in $a$ will be at most $\\sqrt{n}$, so lets have an array of size at most $\\sqrt{n}$ having every value with it's frequency. Now let $dp[i][j]$ be true if it is possible to find a subset with sum $j$ in the suffix $i$. So to check if $dp[i][j]$ is true or not we need to check $dp[i+1][j - val[i]], dp[i+1][j - 2 \\cdot val[i]] ... , dp[i+1][j - freq[i] \\cdot val[i]]$, in another way we need to find a value $k$ such that $dp[i+1][j - k \\cdot val[i]]$ is true and $(k \\leq freq[i])$, so for every $j$ let's find the minimum possible $k$, if $dp[i + 1][j]$ is true then $k_j$ will be equal to $0$, otherwise it is equal to $k_{j - val[i]} + 1$. So this way we can check if the answer is $d+1$ in $O(n \\cdot \\sqrt{n})$. Now if the answer is not $d+1$, then it is $d+2$. To find the answer let's start from level $0$ to level $d$, when you are at level $i$ let the number of remaining nodes be $m$ (the number of nodes with depth greater than or equal to $i$) and you have $y$ remaining a's you can still use. If $a_i$ is not greater than $y$ or not greater than $m-y$, you can assign all nodes on the current level with the same character and move on to the next level. If not then you will have to use the two characters on the current level so you are going to add at least one more string on the answer. If you have two nodes on the same level having the same character but the nodes have different prefixes, then the strings will not be considered equal, so to guarantee not adding more than one string to the answer later on, you should make sure to assign the same character to all non-leaf nodes on the current level. Now if we have $l$ non-leaf nodes then $l$ must be less than or equal to $\\frac{m}{2}$, because every non-leaf node should have at least one more node in it's sub tree, and we know that for any value $y$ ($\\frac{m}{2} \\leq max(y , m - y)$), so it is possible to assign the same character to all non-leaf nodes, after assigning all non-leaf nodes with the same character make sure to finish all the remaining copies of this character on the current level so you guarantee on the next levels all nodes will be the same. This way only one string will be added on the current level so the answer will be $d+2$. Total complexity is $O(n \\cdot \\sqrt{n})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define mod 998244353\n#define oo 1000000010\nconst int N = 100010;\nconst int SQ = 500;\nint n , x , p;\nvector< int > g[N] , cur[N];\n\nchar c[N];\n\nint mx;\n\nvector< pair<int,int> > v , v2;\n\npair< int , char > a , b;\n\nint sz[N];\n\nbool comp(int u,int v){\n\treturn (sz[u] < sz[v]);\n}\n\nint DFS(int node,int d){\n\tmx = max(mx,d);\n\tcur[d].push_back(node);\n\tsz[node] = 1;\n\tfor(int i = 0 ;i < (int)g[node].size();i++)\n\t\tsz[node] += DFS(g[node][i] , d + 1);\t\n\treturn sz[node];\n}\n\nbool dp[SQ][N];\n\nint f[N];\n\nvoid build_path(int i,int j){\n\tif(i == (int)v2.size())\n\t\treturn;\n\twhile(!dp[i + 1][j]){\n\t\tf[v2[i].first]++;\n\t\tj -= v2[i].first;\n\t}\n\tbuild_path(i + 1 , j);\n}\n\nint main(){\n\tscanf(\"%d%d\",&n,&x);\n\ta = make_pair(x , 'a');\n\tb = make_pair(n - x , 'b');\n\tif(a > b) swap(a , b);\n\tfor(int i = 2 ;i <= n;i++){\n\t\tscanf(\"%d\",&p);\n\t\tg[p].push_back(i);\n\t}\n\tDFS(1 , 0);\n\tfor(int i = 0 ;i <= mx;i++)\n\t\tv.push_back(make_pair((int)cur[i].size() , i));\n\tsort(v.begin(),v.end());\n\tfor(int i = 0 ;i < (int)v.size();i++){\n\t\tif(i == 0 || v[i].first != v[i - 1].first)\n\t\t\tv2.push_back(make_pair(v[i].first , 1));\n\t\telse\n\t\t\tv2.back().second++;\n\t}\n\tdp[(int)v2.size()][0] = true;\n\tint val , frq;\n\tfor(int i = (int)v2.size() - 1;i >= 0;i--){\n\t\tval = v2[i].first;\n\t\tfrq = v2[i].second;\n\t\tvector< int > last(val , -1);\n\t\tfor(int j = 0 ;j <= a.first;j++){\n\t\t\tif(dp[i + 1][j] == true)\n\t\t\t\tlast[j % val] = j;\n\t\t\tif(last[j % val] == -1 || ((j - last[j % val]) / val) > frq)\n\t\t\t\tdp[i][j] = false;\n\t\t\telse\n\t\t\t\tdp[i][j] = true;\n\t\t}\n\t}\n\tif(dp[0][a.first]){\n\t\tbuild_path(0 , a.first);\n\t\tfor(int i = 1;i <= n;i++) c[i - 1] = b.second;\n\t\tfor(int i = 0 ;i <= mx;i++){\n\t\t\tif(f[(int)cur[i].size()] == 0) continue;\n\t\t\tf[(int)cur[i].size()]--;\n\t\t\tfor(int j = 0 ;j < (int)cur[i].size();j++)\n\t\t\t\tc[cur[i][j] - 1] = a.second;\n\t\t}\n\t\tprintf(\"%d\\n\",mx + 1);\n\t\tc[n] = '\\0';\n\t\tputs(c);\n\t\treturn 0;\t\n\t}\n\tprintf(\"%d\\n\",mx + 2);\n\tfor(int i = 0 ;i <= mx;i++){\n\t\tsort(cur[i].begin(),cur[i].end(),comp);\n\t\tif(a.first < b.first) swap(a , b);\n\t\twhile((int)cur[i].size() > 0 && a.first > 0){\n\t\t\tc[cur[i].back() - 1] = a.second;\n\t\t\tcur[i].pop_back();\n\t\t\ta.first--;\n\t\t}\n\t\twhile((int)cur[i].size() > 0 && b.first > 0){\n\t\t\tc[cur[i].back() - 1] = b.second;\n\t\t\tcur[i].pop_back();\n\t\t\tb.first--;\n\t\t}\n\t}\n\tc[n] = '\\0';\n\tputs(c);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1482",
    "index": "A",
    "title": "Prison Break",
    "statement": "Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.\n\nThe prison can be represented as a rectangle $a\\times b$ which is divided into $ab$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.\n\nYour task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.",
    "tutorial": "Each broken wall increases the number of connected regions of the plane at most by one. Since in the end every single cell must be in the same region as the outside of the prison, there has to be only one connected region, hence the answer is at least $nm$ (because there were $nm + 1$ connected regions at the beginning). To achieve the answer, one can, for example, break the upper wall in every cell.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1482",
    "index": "B",
    "title": "Restore Modulo",
    "statement": "For the first place at the competition, Alex won many arrays of integers and was assured that these arrays are very expensive. After the award ceremony Alex decided to sell them. There is a rule in arrays pawnshop: you can sell array only if it can be compressed to a generator.\n\nThis generator takes four non-negative numbers $n$, $m$, $c$, $s$. $n$ and $m$ must be positive, $s$ non-negative and for $c$ it must be true that $0 \\leq c < m$. The array $a$ of length $n$ is created according to the following rules:\n\n- $a_1 = s \\bmod m$, here $x \\bmod y$ denotes remainder of the division of $x$ by $y$;\n- $a_i = (a_{i-1} + c) \\bmod m$ for all $i$ such that $1 < i \\le n$.\n\nFor example, if $n = 5$, $m = 7$, $c = 4$, and $s = 10$, then $a = [3, 0, 4, 1, 5]$.\n\nPrice of such an array is the value of $m$ in this generator.\n\nAlex has a question: how much money he can get for each of the arrays. Please, help him to understand for every array whether there exist four numbers $n$, $m$, $c$, $s$ that generate this array. If yes, then maximize $m$.",
    "tutorial": "Handle the case of $c = 0$ separately. For this check whether for every $i$ from $1\\leq i < n$ there holds an equality $arr[i] = arr[i + 1]$ (or in other words, all numbers are the same). If this is true then the modulo can be arbitrarily large. Otherwise, if $arr[i] = arr[i + 1]$ holds for at least one $i$, then $c$ must equal zero, but we already know that it's not the case, so the answer is $-1$. Ok, now $c\\neq 0$ and no two consecutive numbers coincide. Note that $x + c\\pmod{m}$ is either $x + c$ or $x - (m - c)$. So all positive differences (between pairs of consecutive numbers) must be the same, as well as all negative differences. Otherwise the answer is $-1$. If there is no positive difference (or similarly if there is no negative difference) then the modulo can be arbitrarily large. Otherwise the modulo has to equal their sum $c + (m - c) = m$. After we find out $m$ and $c$ it only remains to check if they in fact generate our sequence.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1482",
    "index": "C",
    "title": "Basic Diplomacy",
    "statement": "Aleksey has $n$ friends. He is also on a vacation right now, so he has $m$ days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these $m$ days.\n\nOn each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than $\\left\\lceil\\dfrac{m}{2}\\right\\rceil$ times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone.\n\nHelp him to choose teammates so that nobody is chosen strictly more than $\\left\\lceil\\dfrac{m}{2}\\right\\rceil$ times.",
    "tutorial": "First, for each day we select an arbitrary friend from the list. With this choice, at most one friend will play more than $\\left\\lceil\\dfrac{m}{2}\\right\\rceil$ times. Let's call him $f$. We want to fix schedule such that $f$ will play exactly $\\left\\lceil\\dfrac{m}{2}\\right\\rceil$ times. To do this, we go through all the days and, if $f$ is assigned on a certain day and someone else can play this day, then we assign anyone except $f$ for that day. We will make such replacements while $f$ plays more than $\\left\\lceil\\dfrac{m}{2}\\right\\rceil$ times. There is only one case when this is not possible: if $f$ is the only friend who can play in more than $\\left\\lceil\\dfrac{m}{2}\\right\\rceil$ days.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1482",
    "index": "D",
    "title": "Playlist",
    "statement": "Arkady has a playlist that initially consists of $n$ songs, numerated from $1$ to $n$ in the order they appear in the playlist. Arkady starts listening to the songs in the playlist one by one, starting from song $1$. The playlist is cycled, i. e. after listening to the last song, Arkady will continue listening from the beginning.\n\nEach song has a genre $a_i$, which is a positive integer. Let Arkady finish listening to a song with genre $y$, and the genre of the next-to-last listened song be $x$. If $\\operatorname{gcd}(x, y) = 1$, he deletes the last listened song (with genre $y$) from the playlist. After that he continues listening normally, skipping the deleted songs, and \\textbf{forgetting} about songs he listened to before. In other words, after he deletes a song, he can't delete the next song immediately.\n\nHere $\\operatorname{gcd}(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\nFor example, if the initial songs' genres were $[5, 9, 2, 10, 15]$, then the playlist is converted as follows: [\\textbf{5}, 9, 2, 10, 15] $\\to$ [\\textbf{5}, \\textbf{9}, 2, 10, 15] $\\to$ [5, 2, 10, 15] (because $\\operatorname{gcd}(5, 9) = 1$) $\\to$ [5, \\textbf{2}, 10, 15] $\\to$ [5, \\textbf{2}, \\textbf{10}, 15] $\\to$ [5, 2, \\textbf{10}, \\textbf{15}] $\\to$ [\\textbf{5}, 2, 10, \\textbf{15}] $\\to$ [\\textbf{5}, \\textbf{2}, 10, 15] $\\to$ [5, 10, 15] (because $\\operatorname{gcd}(5, 2) = 1$) $\\to$ [5, \\textbf{10}, 15] $\\to$ [5, \\textbf{10}, \\textbf{15}] $\\to$ ... The bold numbers represent the two last played songs. Note that after a song is deleted, Arkady forgets that he listened to that and the previous songs.\n\nGiven the initial playlist, please determine which songs are eventually deleted and the order these songs are deleted.",
    "tutorial": "Let's call a pair of songs bad if GCD of their genres is $1$. It is easy to check if two songs are bad with Euclid's algorithm in $O(\\log{C})$. There are at most $n$ deletions, so simulation is fine in terms of time limit, but we should be able to find the next deleted song quickly. Let's maintain an ordered set of songs on the playlist, and also another ordered set that stores pairs of bad consecutive songs. It is easy to see that after we delete a song, only constant number of changes is needed to these sets. Let the song being deleted be $b$, while the previous song be $a$, and the next song in the playlist be $c$. It is easy to find $a$ and $c$ using the playlist set. Then we should: remove $b$ from the playlist set; remove $(a, b)$ from the bad pairs set; remove $(b, c)$ from the bad pairs set if this pair is bad; add $(a, c)$ to the bad pairs set if this pair is bad. If we store the sets in some fast enough data structure (e. g. balanced binary tree, standard C++'s set is enough), we have fast running time ($O(n (\\log{n} + \\log{C}))$). It is also possible to solve this problem with double-linked lists or DSU with $O(n \\log{C})$ complexity.",
    "tags": [
      "data structures",
      "dsu",
      "implementation",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1482",
    "index": "E",
    "title": "Skyline Photo",
    "statement": "Alice is visiting New York City. To make the trip fun, Alice will take photos of the city skyline and give the set of photos as a present to Bob. However, she wants to find the set of photos with maximum beauty and she needs your help.\n\nThere are $n$ buildings in the city, the $i$-th of them has positive height $h_i$. All $n$ building heights in the city are different. In addition, each building has a beauty value $b_i$. Note that beauty can be positive or negative, as there are ugly buildings in the city too.\n\nA set of photos consists of one or more photos of the buildings in the skyline. Each photo includes one or more buildings in the skyline that form a contiguous segment of indices. Each building needs to be in \\textbf{exactly one} photo. This means that if a building does not appear in any photo, or if a building appears in more than one photo, the set of pictures is not valid.\n\nThe beauty of a photo is equivalent to the beauty $b_i$ of the shortest building in it. The total beauty of a set of photos is the sum of the beauty of all photos in it. Help Alice to find the maximum beauty a valid set of photos can have.",
    "tutorial": "We can solve this problem with DP. A trivial $O(n^2)$ algorithm would look like this: Define $dp_i$ as the maximum beauty that can be achieved if we have a set of photos of buildings from $1$ to $i$. We can check every possible splitting point $j \\le i$ for the rightmost picture of the set, and keep the biggest answer. $dp_i = max_{j \\le i}(dp_{j - 1} + b_{j..i})$. Now we just need to optimize this solution. Assume we are calculating $dp_i$ First important thing we need to realize is that, if we find the position of the closest smaller number to the left of $i$, on position $j$, and we choose to add it in the rightmost photo with building $i$, then the best solution would be on $dp_j$, because all numbers after $j$ are bigger than $h_j$, so they would not change the beauty of the picture (this is assuming that $i$ and $j$ are on the same photo). Note that we had already calculated the max beauty of $dp_j$, so it is not necessary to go back any further, as we have the best answer stored at $dp_j$ Having this observation, we are just left to check numbers between $j$ and $i$ as possible splitting points for the rightmost picture (the case where building $j$ and building $i$ are in different pictures). But we now know that every height from $j + 1$ to $i - 1$ is bigger than $h_i$ ( this is because $j$ is the closets smaller height), so the answer will just be $dp_{k - 1}$ + $b_i$ for any $k$ between $j + 1$ and $i$. We want to maximize the answer, so we just want to look for the max $dp_k$ value in this range. To do this, we can keep a max segment tree with dp values, and query it in $O(lgn)$ time. After we calculate $dp_i$, we insert it to the segment tree. This gives un an $O(n*lgn)$ solution, enough to solve the problem. For the final implementation, we can iterate from 1 to $n$, keeping a stack with height values, to calculate the closest smaller building for each building. We just pop the stack while the current building is smaller than the top value of the stack, and insert the current building on top of the stack. Actually, by using this trick right, a segment tree is not really necessary. We can calculate the minimum answer for the ranges by updating information as we delete or add numbers in the stack. So it is possible to achieve a linear time solution. However, $O(n*lgn)$ is enough to solve the problem, so this optimization is not necessary.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1482",
    "index": "F",
    "title": "Useful Edges",
    "statement": "You are given a weighted undirected graph on $n$ vertices along with $q$ triples $(u, v, l)$, where in each triple $u$ and $v$ are vertices and $l$ is a positive integer. An edge $e$ is called useful if there is at least one triple $(u, v, l)$ and a path (not necessarily simple) with the following properties:\n\n- $u$ and $v$ are the endpoints of this path,\n- $e$ is one of the edges of this path,\n- the sum of weights of all edges on this path doesn't exceed $l$.\n\nPlease print the number of useful edges in this graph.",
    "tutorial": "Find all distances between vertices via Floyd's algorithm for $O(n^3)$. Consider all triples with fixed endpoint, say, $v$. Let's find all useful edges corresponding to such triples. An edge $(a, b, w)$ is useful, if there is a triple $(v, u_i, l_i)$ with $dist(v, a) + w + dist(b, u_i)\\leq l_i\\Leftrightarrow -l_i + dist(u_i, b)\\leq -w - dist(v, a).$ Note that the right hand side depends only on the fixed vertex $v$ and the edge itself, so we are going to minimize the left hand side over all possible triples. It can be done using Dijkstra in $O(n^2)$ if we initialize the distance to all $u_i$ with $-l_i$. After we are done for all vertices $v$, there only remains to check for each edge whether it has been marked useful for any vertex $v$.",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1482",
    "index": "G",
    "title": "Vabank",
    "statement": "Gustaw is the chief bank manager in a huge bank. He has unlimited access to the database system of the bank, in a few clicks he can move any amount of money from the bank's reserves to his own private account. However, the bank uses some fancy AI fraud detection system that makes stealing more difficult.\n\nGustaw knows that the anti-fraud system just detects any operation that exceeds some fixed limit $M$ euros and these operations are checked manually by a number of clerks. Thus, any fraud operation exceeding this limit is detected, while any smaller operation gets unnoticed.\n\nGustaw doesn't know the limit $M$ and wants to find it out. In one operation, he can choose some integer $X$ and try to move $X$ euros from the bank's reserves to his own account. Then, the following happens.\n\n- If $X \\le M$, the operation is unnoticed and Gustaw's account balance raises by $X$ euros.\n- Otherwise, if $X > M$, the fraud is detected and cancelled. Moreover, Gustaw has to pay $X$ euros from his own account as a fine. If he has less than $X$ euros on the account, he is fired and taken to the police.\n\nInitially Gustaw has $1$ euro on his account. Help him find the exact value of $M$ in no more than $105$ operations without getting him fired.",
    "tutorial": "Our solution consists of two parts. First of all find an upper bound for $M$. To achieve this, we try to query $1$, $2$, $4$, $8$ and so on until we fail. After the first unsuccessful query we will have $0$ euro and know that the answer is on some segment $[2^k, 2^{k+1})$. It takes at most 47 queries. Now one could do something like the following binary search: take the left border of our segment of money, then on each query try the left border and then the middle. If the queries are successful then all good, otherwise we lose $L + \\frac{R - L}{2}$, where $L$ is taken at the beginning of this iteration, and all $\\frac{R - L}{2}$ cannot sum up into something greater than the initial left border we obtained, because initially $R - L = L$, and each time $R - L$ decreases twice. However, this solution requires another $2\\log(10^{14})$ queries, which is too much. Let's divide the segment into two non-equal parts sometimes. Note that if the left side of the partition doesn't exceed half of the segment then that extra $L$ we have is enough to cover all our expenses. Also let's use that we actually get extra $M \\approx \\frac{L + R}{2}$ after successful middle queries. We want our algorithm to look something like the following. Let the current segment equal $[l, r]$. and the current balance is at least $l\\cdot y + (r - l)$ for some integer $y$. Then if $y = 0$ then we query $l$, and if $y > 1$ then we query whatever we want on the segment. It is easy to see that after an unsuccessful query our balance is at least $l \\cdot (y - 1) + (r - l)$ (for new $l$ and $r$), and after a successful query, we will think that our balance is at least $l \\cdot (y + 1) + (r - l)$ (for new $l$ or $r$). The latter is not always the case, we will discuss that later. Now our balance is described by the only integer $y$. Let $dp[x][y]$ equal the maximal $d$ so that it's possible to find the answer on $[l, l + d]$ having $y\\cdot l + d$ money initially. Then $dp[x][y] = dp[x - 1][y - 1] + dp[x - 1][y + 1]$, it is easy to compute and follow in the solution. One can show that $dp[k][0] = \\binom{k}{[k/2]}$. It implies that $k\\leq 49$. This adds up to 97 queries. Now remember that, if we proceed from $(l, r, y)$ to $(m, r, y + 1)$, then our balance was $y\\cdot l + (r - l)$ and became $y\\cdot l + m$, while we need $(y + 1)\\cdot m$ for our estimations. Hence we need some extra cash to cover such \"expenses\". It can be proven that they don't exceed three of initial $L$-s, which gives the total of 100 queries.",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1482",
    "index": "H",
    "title": "Exam",
    "statement": "This year a Chunin Selection Exam is held again in Konoha, and taking part in it are $n$ ninjas named $s_1$, $s_2$, ..., $s_n$. All names are distinct. One of the exam stages consists of fights between the participants. This year the rules determining the ninjas for each fight are the following: ninjas $i$ and $j$ fight against each other if the following conditions are held:\n\n- $i \\neq j$;\n- $s_{j}$ is a substring of $s_{i}$;\n- there is no $k$ except $i$ and $j$ that $s_{j}$ is a substring of $s_{k}$, and $s_{k}$ is a substring of $s_{i}$.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nYour task is to find out how many fights are going to take place this year.",
    "tutorial": "Fix a particular string $s$ and find all edges outgoing from it. For each position $i$ of the string let's find the value of $left_i$ being the starting position of the longest substring which ends at the position $i$ and is one of the strings $s_j$. It's easy to see that such strings are the only ones where the outgoing edges from $s$ can lead to. What remains is to find out which of them need to be excluded. A string needs to be excluded if there is an occurrence of it into $s$ which is entirely covered by an occurrence of another substring. So let $ind_i = \\min\\{left_j\\,\\mid\\,j > i\\}$. Then the strings to be excluded are precisely the strings among $s_j$'s which are suffixes of the substring $[ind_i, i]$ for some $i$. This can be found via the Aho-Corasick structure. Since its suffix links represent a tree, one can find the vertices corresponding to the substrings $[ind_i, i]$ and mark the way to the root in the suffix links tree. After this one can just check if the vertices of $[left_i, i]$ are marked. To mark paths efficiently one can use segment trees or std::set. The overall complexity is $O(n\\log{n})$.",
    "tags": [
      "data structures",
      "string suffix structures",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1485",
    "index": "A",
    "title": "Add and Divide",
    "statement": "You have two positive integers $a$ and $b$.\n\nYou can perform two kinds of operations:\n\n- $a = \\lfloor \\frac{a}{b} \\rfloor$ (replace $a$ with the integer part of the division between $a$ and $b$)\n- $b=b+1$ (increase $b$ by $1$)\n\nFind the minimum number of operations required to make $a=0$.",
    "tutorial": "Suppose that you can use $x$ operations of type $1$ and $y$ operations of type $2$. Try to reorder the operations in such a way that $a$ becomes the minimum possible. You should use operations of type $2$ first, then moves of type $1$. How many operations do you need in the worst case? ($a = 10^9$, $b = 1$) You need at most $30$ operations. Iterate over the number of operations of type $2$. Notice how it is never better to increase $b$ after dividing ($\\lfloor \\frac{a}{b+1} \\rfloor \\le \\lfloor \\frac{a}{b} \\rfloor$). So we can try to increase $b$ to a certain value and then divide $a$ by $b$ until it is $0$. Being careful as not to do this with $b<2$, the number of times we divide is going to be $O(\\log a)$. In particular, if you reach $b \\geq 2$ (this requires at most $1$ move), you need at most $\\lfloor \\log_2(10^9) \\rfloor = 29$ moves to finish. Let $y$ be the number of moves of type $2$; we can try all values of $y$ ($0 \\leq y \\leq 30$) and, for each $y$, check how many moves of type $1$ are necessary. Complexity: $O(\\log^2 a)$. If we notice that it is never convenient to increase $b$ over $6$, we can also achieve a solution with better complexity.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nvoid solve(){\n\tlong long A,B,a,b,res,i,ans;\n\tcin>>A>>B;\n\tif(!A){\n\t\tcout<<0<<endl;\n\t\treturn;\n\t}\n\tres=A+3;\n\tfor(i=(B<2?2-B:0); i<res; ++i){\n\t\tb=B+i;\n\t\ta=A;\n\t\tans=i;\n\t\twhile(a){\n\t\t\ta/=b;\n\t\t\t++ans;\n\t\t}\n\t\tif(ans<res)res=ans;\n\t}\n\tcout<<res<<endl;\n}\n \nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--)solve();\n\treturn 0;\n}\n ",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1485",
    "index": "B",
    "title": "Replace and Keep Sorted",
    "statement": "Given a positive integer $k$, two arrays are called $k$-similar if:\n\n- they are \\textbf{strictly increasing};\n- they have the same length;\n- all their elements are positive integers between $1$ and $k$ (inclusive);\n- they differ in \\textbf{exactly} one position.\n\nYou are given an integer $k$, a \\textbf{strictly increasing} array $a$ and $q$ queries. For each query, you are given two integers $l_i \\leq r_i$. Your task is to find how many arrays $b$ exist, such that $b$ is $k$-similar to array $[a_{l_i},a_{l_i+1}\\ldots,a_{r_i}]$.",
    "tutorial": "You can make a $k$-similar array by assigning $a_i = x$ for some $l \\leq i \\leq r$ and $1 \\leq x \\leq k$. How many $k$-similar arrays can you make if $x$ is already equal to some $a_i$ ($l \\leq i \\leq r$)? How many $k$-similar arrays can you make if either $x < a_l$ or $x > a_r$? How many $k$-similar arrays can you make if none of the previous conditions holds? Let's consider each value $x$ from $1$ to $k$. If $x < a_l$, you can replace $a_l$ with $x$ (and you get $1$ $k$-similar array). There are $a_l-1$ such values of $x$. If $x > a_r$, you can replace $a_r$ with $x$ (and you get $1$ $k$-similar array). There are $k-a_r$ such values of $x$. If $a_l < x < a_r$, and $x \\neq a_i$ for all $i$ in $[l, r]$, you can either replace the rightmost $b_i$ which is less than $x$, or the leftmost $b_i$ which is greater than $x$ (and you get $2$ $k$-similar arrays). There are $(a_r - a_l + 1) - (r - l + 1)$ such values of $x$. If $x = a_i$ for some $i$ in $[l, r]$, no $k$-similar arrays can be made. The total count is $(a_l-1)+(k-a_r)+2((a_r - a_l + 1) - (r - l + 1))$, which simplifies to $k + (a_r - a_l + 1) - 2(r - l + 1)$. Complexity: $O(n + q)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main(){\n\tcin.tie(0);\n\tios_base::sync_with_stdio(NULL);\n\tint N,Q,K;\n\tcin >> N >> Q >> K;\n\tvector<int> v(N);\n\tfor(int &x: v)cin >> x;\n\tint l,r;\n\twhile(Q--){\n\t\tcin >> l >> r;\n\t\tcout << K + v[r-1] - v[l-1] - 2*(r - l) - 1 << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1485",
    "index": "C",
    "title": "Floor and Mod",
    "statement": "A pair of positive integers $(a,b)$ is called \\textbf{special} if $\\lfloor \\frac{a}{b} \\rfloor = a \\bmod b$. Here, $\\lfloor \\frac{a}{b} \\rfloor$ is the result of the integer division between $a$ and $b$, while $a \\bmod b$ is its remainder.\n\nYou are given two integers $x$ and $y$. Find the number of special pairs $(a,b)$ such that $1\\leq a \\leq x$ and $1 \\leq b \\leq y$.",
    "tutorial": "Let $\\lfloor \\frac{a}{b} \\rfloor = a~\\mathrm{mod}~b = k$. Is there an upper bound for $k$? $k \\leq \\sqrt x$. For a fixed $k$, can you count the number of special pairs such that $a \\leq x$ and $b \\leq y$ in $O(1)$? We can notice that, if $\\lfloor \\frac{a}{b} \\rfloor = a~\\mathrm{mod}~b = k$, then $a$ can be written as $kb+k$ ($b > k$). Since $b > k$, we have that $k^2 < kb+k = a \\leq x$. Hence $k \\leq \\sqrt x$. Now let's count special pairs for any fixed $k$ ($1 \\leq k \\leq \\sqrt x$). For each $k$, you have to count the number of $b$ such that $b > k$, $1 \\leq b \\leq y$, $1 \\leq kb+k \\leq x$. The second condition is equivalent to $1 \\leq b \\leq x/k-1$. Therefore, for any fixed $k > 0$, the number of special pairs ($a\\leq x$; $b \\leq y$) is $max(0, min(y,x/k-1) - k)$. The result is the sum of the number of special pairs for each $k$. Complexity: $O(\\sqrt x)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n \nvoid solve(){\n\tll x, y;\n\tcin >> x >> y;\n\tll ans = 0;\n\tfor(ll i = 1; i*i < x; i++)ans+=max(min(y,x/i-1)-i,0LL);\n\tcout << ans << endl;\n\treturn;\n}\n \nint main(){\n\tint T = 1;\n\tcin >> T;\n\twhile(T--){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1485",
    "index": "D",
    "title": "Multiples and Power Differences",
    "statement": "You are given a matrix $a$ consisting of positive integers. It has $n$ rows and $m$ columns.\n\nConstruct a matrix $b$ consisting of positive integers. It should have the same size as $a$, and the following conditions should be met:\n\n- $1 \\le b_{i,j} \\le 10^6$;\n- $b_{i,j}$ is a multiple of $a_{i,j}$;\n- the absolute value of the difference between numbers in any adjacent pair of cells (two cells that share the same side) in $b$ is equal to $k^4$ for some integer $k \\ge 1$ ($k$ is not necessarily the same for all pairs, it is own for each pair).\n\nWe can show that the answer always exists.",
    "tutorial": "Brute force doesn't work (even if you optimize it): there are relatively few solutions. There may be very few possible values of $b_{i,j}$, if $b_{i-1,j}$ is fixed. The problem arises when you have to find a value for a cell with, e.g., $4$ fixed neighbors. Try to find a possible property of the neighbors of $(i, j)$, such that at least a solution for $b_{i,j}$ exists. The least common multiple of all integers from $1$ to $16$ is less than $10^6$. Build a matrix with a checkerboard pattern: let $b_{i, j} = 720720$ if $i + j$ is even, and $720720+a_{i, j}^4$ otherwise. The difference between two adjacent cells is obviously a fourth power of an integer. We choose $720720$ because it is $\\operatorname{lcm}(1, 2, \\dots, 16)$. This ensures that $b_{i, j}$ is a multiple of $a_{i, j}$, because it is either $720720$ itself or the sum of two multiples of $a_{i, j}$. Complexity: $O(nm)$.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint main(){\n\tunsigned h,w,x,y,t;\n\tcin>>h>>w;\n\tfor(y=0; y<h; ++y){\n\t\tfor(x=0; x<w; ++x){\n\t\t\tcin>>t;\n\t\t\tif((x^y)&1)\n\t\t\t\tcout<<\"720720 \";\n\t\t\telse cout<<720720+t*t*t*t<<' ';\n\t\t}\n\t\tcout<<'\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1485",
    "index": "E",
    "title": "Move and Swap",
    "statement": "You are given $n - 1$ integers $a_2, \\dots, a_n$ and a tree with $n$ vertices rooted at vertex $1$. The leaves are all at the same distance $d$ from the root.\n\nRecall that a tree is a connected undirected graph without cycles. The distance between two vertices is the number of edges on the simple path between them. All non-root vertices with degree $1$ are leaves. If vertices $s$ and $f$ are connected by an edge and the distance of $f$ from the root is greater than the distance of $s$ from the root, then $f$ is called a child of $s$.\n\nInitially, there are a red coin and a blue coin on the vertex $1$. Let $r$ be the vertex where the red coin is and let $b$ be the vertex where the blue coin is. You should make $d$ moves. A move consists of three steps:\n\n- Move the red coin to any child of $r$.\n- Move the blue coin to any vertex $b'$ such that $dist(1, b') = dist(1, b) + 1$. Here $dist(x, y)$ indicates the length of the simple path between $x$ and $y$. Note that $b$ and $b'$ are not necessarily connected by an edge.\n- You can optionally swap the two coins (or skip this step).\n\nNote that $r$ and $b$ can be equal at any time, and there is no number written on the root.\n\nAfter each move, you gain $|a_r - a_b|$ points. What's the maximum number of points you can gain after $d$ moves?",
    "tutorial": "What happens if you can't swap coins? Let $dp_i$ be the maximum score that you can reach after $dist(1, i)$ moves if there is a red coin on node $i$ after step $3$. However, after step $2$, the coin on node $i$ may be either red or blue. Try to find transitions for both cases. If you consider only the first case, you solve the problem if there are no swaps. You can greedily check the optimal location for the blue coin: a node $j$ such that $dist(1,i) = dist(1,j)$ and $a_j$ is either minimum or maximum. Instead, if the coin on node $i$ is blue after step $2$, the red coin is on node $j$ and you have to calculate $\\max(dp_{parent_j} + |a_j - a_i|)$ for each $i$ with a fixed $dist(1, i)$. How? Divide the nodes in groups based on the distance from the root. Then, for each $dist(1, i)$ in increasing order, calculate $dp_i$ - the maximum score that you can reach after $dist(1, i)$ moves if there is a red coin on node $i$ after step $3$. You can calculate $dp_i$ if you know $dp_j$ for each $j$ that belongs to the previous group. There are two cases: if after step $2$ the coin on node $i$ is red, the previous position of the red coin is fixed, and the blue coin should reach either the minimum or the maximum $a_j$ among the $j$ that belong to the same group of $i$; if after step $2$ the coin on node $i$ is red, the previous position of the red coin is fixed, and the blue coin should reach either the minimum or the maximum $a_j$ among the $j$ that belong to the same group of $i$; if after step $2$ the coin on node $i$ is blue, there is a red coin on node $j$ ($dist(1, i) = dist(1, j)$), so you have to maximize the score $dp_{parent_j} + |a_j - a_i|$. This can be done efficiently by sorting the $a_i$ in the current group and calculating the answer separately for $a_j \\leq a_i$ and $a_j > a_i$; for each $i$ in the group, the optimal node $j$ either doesn't change or it's the previous node. Alternatively, you can notice that $dp_{parent_j} + |a_j - a_i| = \\max(dp_{parent_j} + a_j - a_i, dp_{parent_j} + a_i - a_j)$, and you can maximize both $dp_{parent_j} + a_j - a_i$ and $dp_{parent_j} + a_i - a_j$ greedily (by choosing the maximum $dp_{parent_j} + a_j$ and $dp_{parent_j} - a_j$, respectively). In this solution, you don't need to sort the $a_i$. if after step $2$ the coin on node $i$ is blue, there is a red coin on node $j$ ($dist(1, i) = dist(1, j)$), so you have to maximize the score $dp_{parent_j} + |a_j - a_i|$. This can be done efficiently by sorting the $a_i$ in the current group and calculating the answer separately for $a_j \\leq a_i$ and $a_j > a_i$; for each $i$ in the group, the optimal node $j$ either doesn't change or it's the previous node. Alternatively, you can notice that $dp_{parent_j} + |a_j - a_i| = \\max(dp_{parent_j} + a_j - a_i, dp_{parent_j} + a_i - a_j)$, and you can maximize both $dp_{parent_j} + a_j - a_i$ and $dp_{parent_j} + a_i - a_j$ greedily (by choosing the maximum $dp_{parent_j} + a_j$ and $dp_{parent_j} - a_j$, respectively). In this solution, you don't need to sort the $a_i$. The answer is $\\max(dp_i)$. Complexity: $O(n)$ or $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define endl \"\\n\"\n#define ll long long\n#define INF (ll)1e18\n \nll i, i1, j, k, k1, t, n, m, res, check1, a[200010], a1, b, d, v, dist[200010], dp[200010], s, s1, s2;\nvector<ll> adj[200010];\nvector<array<ll, 3>> dadj[200010];\nbool visited[200010];\n \nvoid dfs(ll s) {\n    for (auto u : adj[s]) {\n        if (!visited[u]) {\n            visited[u] = true;\n            dist[u] = dist[s] + 1;\n            dadj[dist[u]].push_back({-1, s, u});\n            d = max(d, dist[u]);\n            dfs(u);\n        }\n    }\n}\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    //ifstream cin(\"input.txt\");\n    //ofstream cout(\"output.txt\");\n \n    cin >> t;\n    while (t--) {\n        cin >> n;\n        for (i = 0; i <= n; i++) {\n            adj[i].clear(); dadj[i].clear(); visited[i] = false; dist[i] = 0; dp[i] = 0;\n        }\n        for (i = 2; i <= n; i++) {\n            cin >> v;\n            adj[v - 1].push_back(i - 1);\n            adj[i - 1].push_back(v - 1);\n        }\n \n        for (i = 1; i < n; i++) {\n            cin >> a[i];\n        }\n \n        d = 0;\n        visited[0] = true;\n        dfs(0);\n        dadj[0].push_back({0, -1, 0});\n \n        for (i = 1; i <= d; i++) {\n            for (auto& u : dadj[i]) {\n                u[0] = a[u[2]];\n                // cout << u[0] << ' ' << u[1] << ' ' << u[2] << endl;\n            }\n            // cout << endl;\n            sort(dadj[i].begin(), dadj[i].end());\n            s = dadj[i].size();\n            s1 = dadj[i][0][0];\n            s2 = dadj[i][dadj[i].size() - 1][0];\n            // cout << s1 << ' ' << s2 << endl;\n            for (auto& u : dadj[i]) {\n                a1 = a[u[2]];\n                dp[u[2]] = max({dp[u[2]], dp[u[1]] + a1 - s1, dp[u[1]] + s2 - a1});\n            }\n            k = 0;\n            for (j = 0; j < s; j++) {\n                if (dp[dadj[i][j][1]] - dadj[i][j][0] > dp[dadj[i][k][1]] - dadj[i][k][0]) {\n                    k = j;\n                }\n                dp[dadj[i][j][2]] = max(dp[dadj[i][j][2]], dadj[i][j][0] - dadj[i][k][0] + dp[dadj[i][k][1]]);\n            }\n            k = s - 1;\n            for (j = s - 1; j >= 0; j--) {\n                if (dp[dadj[i][j][1]] + dadj[i][j][0] > dp[dadj[i][k][1]] + dadj[i][k][0]) {\n                    k = j;\n                }\n                dp[dadj[i][j][2]] = max(dp[dadj[i][j][2]], dadj[i][k][0] - dadj[i][j][0] + dp[dadj[i][k][1]]);\n            }\n        }\n \n        res = 0;\n        for (i = 1; i < n; i++) {\n            // cout << dp[i] << ' ';\n            res = max(res, dp[i]);\n        }\n        // cout << endl;\n \n        cout << res << endl;\n    }\n \n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1485",
    "index": "F",
    "title": "Copy or Prefix Sum",
    "statement": "You are given an array of integers $b_1, b_2, \\ldots, b_n$.\n\nAn array $a_1, a_2, \\ldots, a_n$ of integers is \\textbf{hybrid} if for each $i$ ($1 \\leq i \\leq n$) at least one of these conditions is true:\n\n- $b_i = a_i$, or\n- $b_i = \\sum_{j=1}^{i} a_j$.\n\nFind the number of hybrid arrays $a_1, a_2, \\ldots, a_n$. As the result can be very large, you should print the answer modulo $10^9 + 7$.",
    "tutorial": "Why isn't the answer $2^{n-1}$? What would you overcount? Find a dp with time complexity $O(n^2\\log n)$. Let $dp_{i, j}$ be the number of hybrid prefixes of length $i$ and sum $j$. The transitions are $dp_{i, j} \\rightarrow dp_{i+1, j+b_i}$ and $dp_{i,j} \\rightarrow dp_{i+1,b_i}$. Can you optimize it to $O(n\\log n)$? For each $i$, you can choose either $a_i = b_i$ or $a_i = b_i - \\sum_{k=1}^{i-1} a_k$. If $\\sum_{k=1}^{i-1} a_k = 0$, the two options coincide and you have to avoid overcounting them. This leads to an $O(n^2\\log n)$ solution: let $dp_i$ be a map such that $dp_{i, j}$ corresponds to the number of ways to create a hybrid prefix $[1, i]$ with sum $j$. The transitions are $dp_{i, j} \\rightarrow dp_{i+1, j+b_i}$ (if you choose $b_i = a_i$, and $j \\neq 0$), $dp_{i,j} \\rightarrow dp_{i+1,b_i}$ (if you choose $b_i = \\sum_{k=1}^{i} a_k$). Let's try to get rid of the first layer of the dp. It turns out that the operations required are move all $dp_j$ to $dp_{j+b_i}$ calculate the sum of all $dp_j$ in some moment change the value of a $dp_j$ and they can be handled in $O(n\\log n)$ with \"Venice technique\". $dp$ is now a map such that $dp_j$ corresponds to the number of ways to create a hybrid prefix $[1, i]$ such that $\\sum_{k=1}^{i} a_k - b_k = j$. Calculate the dp for all prefixes from left to right. if $b_i = a_i$, you don't need to change any value of the dp; if $b_i = \\sum_{k=1}^{i} a_k$, you have to set $dp_{\\sum_{k=1}^{i} -b_k}$ to the total number of hybrid arrays of length $i-1$. Complexity: $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define nl \"\\n\"\n#define nf endl\n#define ll long long\n#define pb push_back\n#define _ << ' ' <<\n \n#define INF (ll)1e18\n#define mod 1000000007\n#define maxn 200010\n \nll i, i1, j, k, k1, t, n, m, res, flag[10], a, b[maxn], tt;\nmap<ll, ll> mp;\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    cin >> t;\n    while (t--) {\n        cin >> n; mp.clear();\n        for (i = 1; i <= n; i++) {\n            cin >> b[i];\n        }\n \n        mp[0] = 1; tt = 1; k = 0;\n        for (i = 1; i <= n; i++) {\n            a = mp[k]; mp[k] = tt; k -= b[i];\n            tt = (2 * tt - a + mod) % mod;\n        }\n \n        cout << tt << nl;\n    }\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1486",
    "index": "A",
    "title": "Shifting Stacks",
    "statement": "You have $n$ stacks of blocks. The $i$-th stack contains $h_i$ blocks and it's height is the number of blocks in it. In one move you can take a block from the $i$-th stack (if there is at least one block) and put it to the $i + 1$-th stack. Can you make the sequence of heights strictly increasing?\n\nNote that the number of stacks always remains $n$: stacks don't disappear when they have $0$ blocks.",
    "tutorial": "What's the lower bound for the amount of blocks for the answer to be $\\texttt{YES}$? Check the predicate for every prefix. Let's consider the smallest amount of blocks we need to make the first $i$ heights ascending. As heights are non-negative and ascending the heights should look like $0, 1, 2, 3, ..., i - 1$, so the minimum sum is $\\frac{(i - 1) \\cdot i}{2}$. It turns out that this is the only requirement. If it's not the case for every prefix the answer is $\\texttt{NO}$ because we can't make some prefix ascending. Otherwise the answer is $\\texttt{YES}$ because you can move the blocks right till there is at least $i$ blocks in the $i$-th stack and this would make the heights ascending.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    need = 0\n    have = 0\n    ans = True\n    a = [int(i) for i in input().split()]\n    for j in range(n):\n        need += j\n        have += a[j]\n        if have < need:\n            ans = False\n    if ans:\n        print(\"YES\")\n    else:\n        print(\"NO\")",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1486",
    "index": "B",
    "title": "Eastern Exhibition",
    "statement": "You and your friends live in $n$ houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$, where $|x|$ is the absolute value of $x$.",
    "tutorial": "Is problem really two dimensional? How to solve the problem if $y = 0$? At first let's see that the problem is not two dimensional. If we change the $x$ coordinate the sum of distances by $y$ is not changed at all. So we just need to calculate the number of good points on a line with points having coordinates $x$ and then $y$ and multiply the answers. Now to calculate the answer on a line we could use a known fact: point with the smallest summary distance is between left and right median. So now we only need to sort the array and find the elements on positions $\\lfloor\\frac{n + 1}{2} \\rfloor$ and $\\lfloor \\frac{n + 2}{2} \\rfloor$ and return their difference plus one.",
    "code": "t = int(input())\ndef solve(x):\n    x.sort()\n    return x[len(x) // 2] - x[(len(x) - 1) // 2] + 1\nfor i in range(t):\n    n = int(input())\n    x, y = [], []\n    for j in range(n):\n        px, py = map(int, input().split())\n        x.append(px)\n        y.append(py)\n    print(solve(x) * solve(y))",
    "tags": [
      "binary search",
      "geometry",
      "shortest paths",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1486",
    "index": "C1",
    "title": "Guessing the Greatest (easy version)",
    "statement": "\\textbf{The only difference between the easy and the hard version is the limit to the number of queries}.\n\n\\textbf{This is an interactive problem.}\n\nThere is an array $a$ of $n$ \\textbf{different} numbers. In one query you can ask the position of the second maximum element in a subsegment $a[l..r]$. Find the position of the maximum element in the array in no more than \\textbf{40} queries.\n\nA subsegment $a[l..r]$ is all the elements $a_l, a_{l + 1}, ..., a_r$. After asking this subsegment you will be given the position of the second maximum from this subsegment \\textbf{in the whole} array.",
    "tutorial": "Binary search? How to check if the maximum element is in the left or the right part of the array in two queries? Let's solve for some subsegment $[l, r)$ and $mid = (l + r) / 2$. Now let's check if the max element is in $[l, mid)$ or $[mid, r)$. Let's find the second max element in $[l, r)$ and call it $smax$. Now let's think that $smax$ is less than $mid$ (for symmetrical reasons). Now if we ask $[l, mid)$ and second max is still $smax$ it means that maximum element is in $[l, mid)$, otherwise it's in $[mid, r)$. Now we've shrunk the segment by a factor of two. So the resulting number of queries is $2 \\cdot \\lceil log_2 10^5 \\rceil = 34$.",
    "code": "from sys import stdout\n \ndef ask(l, r):\n    if l == r:\n        return -1\n    print('?', l, r)\n    stdout.flush()\n    return int(input())\n \nl = 1\nr = int(input()) + 1\nwhile r - l > 1:\n    mid = (r + l) // 2\n    was = ask(l, r - 1)\n    if was < mid:\n        if ask(l, mid - 1) == was:\n            r = mid\n        else:\n            l = mid\n    else:\n        if ask(mid, r - 1) == was:\n            l = mid\n        else:\n            r = mid\nprint('!', l)\nstdout.flush()",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1486",
    "index": "C2",
    "title": "Guessing the Greatest (hard version)",
    "statement": "\\textbf{The only difference between the easy and the hard version is the limit to the number of queries}.\n\n\\textbf{This is an interactive problem.}\n\nThere is an array $a$ of $n$ \\textbf{different} numbers. In one query you can ask the position of the second maximum element in a subsegment $a[l..r]$. Find the position of the maximum element in the array in no more than \\textbf{20} queries.\n\nA subsegment $a[l..r]$ is all the elements $a_l, a_{l + 1}, ..., a_r$. After asking this subsegment you will be given the position of the second maximum from this subsegment \\textbf{in the whole} array.",
    "tutorial": "Kudos to Aleks5d for proposing a solution to this subproblem. Binary search AGAIN? How to solve the problem if the second maximum element is at position $1$? How to check if the maximum element is to the left or the right of the second maximum in two queries? Let's find second max $smax$. Now let's check if the max element is to the left, or to the right. Just ask $[1, smax]$ and see if the answer is different to $smax$. Now let's suppose that the max element is to the right (for symmetrical reasons). Now we only need to find the smallest $m$ such that the answer to the query $[smax, m]$ is $smax$. The smallest such $m$ is obviously the position of the maximum element. Now we need to use binary search to find such $m$. So the resulting number of queries is $2 + \\lceil log_2 10^5 \\rceil = 19$.",
    "code": "from sys import stdout\n \ndef ask(l, r):\n    if l == r:\n        return -1\n    print('?', l, r)\n    stdout.flush()\n    return int(input())\n \nn = int(input())\nsmax = ask(1, n)\nif smax == 1 or ask(1, smax) != smax:\n    l = smax\n    r = n\n    while r - l > 1:\n        mid = (l + r) // 2\n        if ask(smax, mid) == smax:\n            r = mid\n        else:\n            l = mid\n    print('!', r)\nelse:\n    l = 1\n    r = smax\n    while r - l > 1:\n        mid = (l + r) // 2\n        if ask(mid, smax) == smax:\n            l = mid\n        else:\n            r = mid\n    print('!', l)\nstdout.flush()",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1486",
    "index": "D",
    "title": "Max Median",
    "statement": "You are a given an array $a$ of length $n$. Find a subarray $a[l..r]$ with length at least $k$ with the largest median.\n\nA median in an array of length $n$ is an element which occupies position number $\\lfloor \\frac{n + 1}{2} \\rfloor$ after we sort the elements in non-decreasing order. For example: $median([1, 2, 3, 4]) = 2$, $median([3, 2, 1]) = 2$, $median([2, 1, 2, 1]) = 1$.\n\nSubarray $a[l..r]$ is a contiguous part of the array $a$, i. e. the array $a_l,a_{l+1},\\ldots,a_r$ for some $1 \\leq l \\leq r \\leq n$, its length is $r - l + 1$.",
    "tutorial": "How to solve the problem if all the values are $-1$ and $1$? Binary search ONCE MORE? How to check if the answer is at least $x$? Let's binary search the answer. Now let's check if the answer is at least $x$. Replace all values that are at least $x$ with 1 and values that are less than $x$ with $-1$. Now if for some segment the median is at least $x$ if the sum on this subsegment is positive! Now we only need to check if the array consisting of $-1$ and $1$ has a subsegment of length at least $k$ with positive sum. So let's just calculate prefix sums of this array and for prefix sum at position $i$ choose the minimum prefix sum amongst positions $0, 1, ..., i - k$, which can be done using prefix minimum in linear time. So the resulting complexity is $O(nlogn)$.",
    "code": "n, k = map(int, input().split())\na = [int(i) for i in input().split()]\nl = 1\nr = n + 1\nwhile r - l > 1:\n    mid = (r + l) // 2\n    b = [1 if i >= mid else -1 for i in a]\n    for i in range(1, len(b)):\n        b[i] += b[i - 1]\n    ans = False\n    if b[k - 1] > 0:\n        ans = True\n    mn = 0\n    for i in range(k, len(b)):\n        mn = min(mn, b[i - k])\n        if b[i] - mn > 0:\n            ans = True\n    if ans:\n        l = mid\n    else:\n        r = mid\nprint(l)",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1486",
    "index": "E",
    "title": "Paired Payment",
    "statement": "There are $n$ cities and $m$ bidirectional roads in the country. The roads in the country form an undirected weighted graph. The graph \\textbf{is not guaranteed to be connected}. Each road has it's own parameter $w$. You can travel through the roads, but the government made a new law: you can only go through two roads at a time (go from city $a$ to city $b$ and then from city $b$ to city $c$) and you will have to pay $(w_{ab} + w_{bc})^2$ money to go through those roads. Find out whether it is possible to travel from city $1$ to every other city $t$ and what's the minimum amount of money you need to get from $1$ to $t$.",
    "tutorial": "Did you read that $w$ is at most $50$? How to change the graph for dijkstra algorithm to work with this rule? Add some fake vertices and edges to make things work. Let's think about it this way. For a middle vertex we only care what are the weights of the edges that pass through it. Now for every vertex $v$ let's create some fake vertices $(v, w)$, where $w$ is the weight of the last edge. This would add at most $O(M)$ new vertices. Now for each starting edge $(u, v, w)$ let's make an edge $u \\rightarrow (v, w)$ of weight $0$ and for each vertex $(u, was)$ and edge $(u, v, w)$ let's create an edge $(u, was) \\rightarrow v$ with weight $(was + w)^2$. Now running Dijkstra's algorithm from vertex $1$ will result for correct answers for all vertices (as we've simulated the paired edge situation with fake vertices and edges). Also we wouldn't create more than $O(M \\cdot maxW)$ edges cause if some vertex has degree $t$ we would create no more than $t \\cdot maxW$ edges and sum of all $t$ is $2 \\cdot M$. Carefully implemented this would result in $O(M \\cdot maxW \\cdot logM)$ or $O(M \\cdot maxW + MlogM)$ time and $O(M \\cdot maxW)$ or $O(M)$ memory. All of those were fine.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nsigned main() {\n    ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);\n    int n, m;\n    cin >> n >> m;\n    vector<vector<pair<int, int>>> G(n * 51);\n    auto addedge = [&](int u, int v, int w) {\n        G[u * 51].push_back({v * 51 + w, 0});\n        for (int was = 1; was <= 50; ++was) {\n            G[u * 51 + was].push_back({v * 51, (was + w) * (was + w) });\n        }\n    };\n    for (int i = 0; i < m; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u, --v;\n        addedge(u, v, w);\n        addedge(v, u, w);\n    }\n    set<pair<int, int>> st;\n    int inf = 1e9 + 7;\n    vector<int> d(G.size(), inf);\n    d[0] = 0;\n    st.insert({d[0], 0});\n    while (st.size()) {\n        auto f = *st.begin();\n        st.erase(st.begin());\n        for (auto i : G[f.second]) {\n            if (d[i.first] > d[f.second] + i.second) {\n                st.erase({d[i.first], i.first});\n                d[i.first] = d[f.second] + i.second;\n                st.insert({d[i.first], i.first});\n            }\n        }\n    }\n    for (int i = 0; i < n; ++i) {\n        int ans = d[i * 51];\n        if (ans == inf) cout << \"-1 \";\n        else cout << ans << ' ';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "dp",
      "flows",
      "graphs",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1486",
    "index": "F",
    "title": "Pairs of Paths",
    "statement": "You are given a tree consisting of $n$ vertices, and $m$ simple vertex paths. Your task is to find how many pairs of those paths intersect at exactly one vertex. More formally you have to find the number of pairs $(i, j)$ $(1 \\leq i < j \\leq m)$ such that $path_i$ and $path_j$ have exactly one vertex in common.",
    "tutorial": "Root the tree. After rooting the tree, how does the intersection of two paths look? After rooting the tree, what are the two types of intersection? Let's root the tree at some vertex. Now the intersection vertex is lca for at least one path. If the vertex wasn't lca for both paths it would mean that there are either two edges going up (which is impossible in a rooted tree) or they are going up by the same edge, but this would mean that this vertex parent is also an intersection point, so the paths are intersecting in at least $2$ points, so this is impossible too. Now there are two types of intersections: with the same lca and different lca. Let's count them independently. For each path and it's lca let's find the subtrees that path goes to from lca. This would result in a triplet $(lca, subtree1, subtree2)$ (replace subtree with $-1$ if there is none) with $subtree1 < subtree2$ or both of them are $-1$. Now to count the intersections of the first type let's use inclusion-exclusion principle. Remember all paths that have same lca. Now we need to calculate the number of pairs so that they have different $subtree1$ and $subtree2$ (or $-1$). The formula is going to be $cntpath \\cdot (cntpath - 1) / 2 - \\sum \\left(cnt(subtree1, x) + cnt(x, subtree2) - (cnt(subtree1, subtree2) + 1) \\right) / 2$ (from inclusion-exclusion principle) where cntpath is the number of paths with this lca and $cnt(x, y)$ is the number of paths with triplet $(lca, x, y)$. The situation with $-1$ is pretty similar, left as an exercise to the reader. Finding the number of intersections of second type is a bit easier. We just need to calculate the number of all intersections between a path with fixed lca and a vertical path which crosses this lca (the path is not neccessarily vertical, but it contains both lca and it's parent) and then subtract $cnt(subtree1)$ and $cnt(subtree2)$, where $cnt(x)$ is the number of vertical paths that go into subtree $x$. After that we just have to print out the sum of this two numbers. Counting all the needed functions can be done using some data structure (small-to-large for example) or some subtree dynamic programming. The resulting complexity is $O(Mlog^2M)$ or $O(MlogM)$ or even $O(M)$ if you're strong enough.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define FAST ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define FIXED cout << fixed << setprecision(12)\n#define ll long long\n#define pii pair<int, int>\n#define graph vector<vector<int>>\n#define pb push_back\n#define f first\n#define s second\n#define sz(a) signed((a).size())\n#define all(a) (a).begin(), (a).end()\n \nvoid flush() { cout << flush; }\nvoid flushln() { cout << endl; }\nvoid println() { cout << '\\n'; }\ntemplate<class T> void print(const T &x) { cout << x; }\ntemplate<class T> void read(T &x) { cin >> x; }\ntemplate<class T, class ...U> void read(T &x, U& ... u) { read(x); read(u...); }\ntemplate<class T, class ...U> void print(const T &x, const U& ... u) { print(x); print(u...); }\ntemplate<class T, class ...U> void println(const T &x, const U& ... u) { print(x); println(u...); }\n \ngraph G;\nvector<vector<int>> up;\nvector<int> h;\nint LOG;\n \nvoid orient(int v, int p, int he = 0) {\n    up[0][v] = p;\n    h[v] = he;\n    for (auto i : G[v])\n        if (i != p) {\n            orient(i, v, he + 1);\n        }\n}\n \nint lca(int u, int v) {\n    if (h[u] > h[v]) swap(u, v);\n    int d = h[v] - h[u];\n    for (int l = 0; l < LOG; ++l)\n        if (d >> l & 1)\n            v = up[l][v];\n    if (u == v) {\n        return u;\n    }\n    for (int l = LOG - 1; l >= 0; --l) {\n        if (up[l][u] != up[l][v]) {\n            u = up[l][u];\n            v = up[l][v];\n        }\n    }\n    return up[0][u];\n}\n \nint getup(int v, int dist) {\n    for (int l = 0; l < LOG; ++l)\n        if (dist >> l & 1)\n            v = up[l][v];\n    return v;\n}\n \nvector<pii> paths;\nvector<map<pii, vector<int>>> samelca;\nvector<vector<int>> bylca;\nvector<vector<int>> addvertex;\n \nvector<set<int>> sets;\nvector<int> link;\n \nset<int>& at(int v) {\n    return sets[link[v]];\n}\n \nbool count(const vector<int> &v, int x) {\n    return binary_search(all(v), x);\n}\n \nll ans = 0;\n \ntemplate<class T, class U> U get(map<T, U> &mp, T k) {\n    auto it = mp.find(k);\n    if (it != mp.end()) return it->s;\n    return T();\n}\n \nvoid process(int v, int p = -1) {\n    int bigson = -1;\n    map<int, int> sonvert, sonhere;\n    for (auto i : G[v])\n        if (i != p) {\n            process(i, v);\n            if (bigson == -1 || sz(at(bigson)) < sz(at(i))) {\n                bigson = i;\n            }\n            sonvert[i] = sz(at(i));\n            // number of paths that cross v and i both, but lca is not i\n        }\n    for (auto &p : samelca[v]) {\n        sonvert[p.f.f] -= sz(p.s);\n        sonvert[p.f.s] -= sz(p.s);\n        sonhere[p.f.f] += sz(p.s);\n        sonhere[p.f.s] += sz(p.s);\n    }\n    sonvert.erase(-1);\n    sonhere.erase(-1);\n    if (bigson != -1) {\n        link[v] = link[bigson];\n    }\n    for (auto i : G[v])\n        if (i != bigson) {\n            for (auto path : at(i))\n                at(v).insert(path);\n        }\n    for (auto path : addvertex[v])\n        at(v).insert(path);\n    // at(v) - all paths that cross v\n    // bylca[v] - all paths that have v as lca\n    ll vertical = sz(at(v)) - sz(bylca[v]);\n    ll here = sz(bylca[v]);\n    ans += vertical * here + here * (here - 1) / 2;\n    ll add1 = 0, add2 = 0;\n    for (auto &p : samelca[v]) {\n        add1 += sz(p.s) * (ll)(get(sonvert, p.f.f) + get(sonvert, p.f.s));\n        if (p.f.f >= 0) {\n            add2 += sz(p.s) * (ll)(get(sonhere, p.f.f) + get(sonhere, p.f.s));\n            add2 -= (sz(p.s) * (ll)(sz(p.s) + 1) / 2) * 2;\n        } else if (p.f.s >= 0) {\n            add2 += sz(p.s) * (ll)(get(sonhere, p.f.s));\n            add2 -= sz(p.s);\n        }\n    }\n    ans -= add1 + add2 / 2;\n    for (auto path : bylca[v])\n        at(v).erase(path);\n}\n \nsigned main() {\n    FAST; FIXED;\n    int n;\n    read(n);\n    G = graph(n);\n    for (int i = 1; i < n; ++i) {\n        int u, v;\n        read(u, v);\n        --u, --v;\n        G[u].pb(v);\n        G[v].pb(u);\n    }\n    LOG = ceil(log2(max(2, n)));\n    up = vector<vector<int>>(LOG, vector<int>(n));\n    h = vector<int>(n);\n    orient(0, 0);\n    for (int l = 1; l < LOG; ++l) {\n        for (int i = 0; i < n; ++i)\n            up[l][i] = up[l - 1][up[l - 1][i]];\n    }\n    int m;\n    read(m);\n    auto getsub = [&](int v, int l) {\n        if (v == l) return -1;\n        return getup(v, h[v] - h[l] - 1);\n    };\n    paths.resize(m);\n    samelca.resize(n);\n    bylca.resize(n);\n    addvertex.resize(n);\n    for (int i = 0; i < m; ++i) {\n        int u, v;\n        read(u, v);\n        --u, --v;\n        paths[i] = {u, v};\n        int l = lca(u, v);\n        pii sons;\n        sons.f = getsub(u, l);\n        sons.s = getsub(v, l);\n        if (sons.f > sons.s)\n            swap(sons.f, sons.s);\n        samelca[l][sons].pb(i);\n        bylca[l].pb(i);\n        addvertex[u].pb(i);\n        addvertex[v].pb(i);\n    }\n    sets.resize(n);\n    link.resize(n);\n    iota(all(link), 0);\n    process(0);\n    println(ans);\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1487",
    "index": "A",
    "title": "Arena",
    "statement": "$n$ heroes fight against each other in the Arena. Initially, the $i$-th hero has level $a_i$.\n\nEach minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (\\textbf{it's even possible that it is the same two heroes that were fighting during the last minute}).\n\nWhen two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $1$.\n\nThe winner of the tournament is the first hero that wins in at least $100^{500}$ fights \\textbf{(note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner)}. A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.\n\nCalculate the number of possible winners among $n$ heroes.",
    "tutorial": "If for some hero $i$, no other hero is weaker than $i$, then the $i$-th hero cannot win any fights and is not a possible winner. Otherwise, the hero $i$ is a possible winner - he may fight the weakest hero $100^{500}$ times and be declared the winner. So the solution to the problem is calculating the number of minimum elements in the array $a$, since all other elements denote possible winners of the tournament.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int& x : a) cin >> x;\n    cout << n - count(a.begin(), a.end(), *min_element(a.begin(), a.end())) << endl;\n  }\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1487",
    "index": "B",
    "title": "Cat Cycle",
    "statement": "Suppose you are living with two cats: A and B. There are $n$ napping spots where both cats usually sleep.\n\nYour cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:\n\n- Cat A changes its napping place in order: $n, n - 1, n - 2, \\dots, 3, 2, 1, n, n - 1, \\dots$ In other words, at the first hour it's on the spot $n$ and then goes in decreasing order cyclically;\n- Cat B changes its napping place in order: $1, 2, 3, \\dots, n - 1, n, 1, 2, \\dots$ In other words, at the first hour it's on the spot $1$ and then goes in increasing order cyclically.\n\nThe cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $x$ then the A takes this place and B moves to the next place in its order (if $x < n$ then to $x + 1$, but if $x = n$ then to $1$). Cat B follows his order, so \\textbf{it won't return to the skipped spot $x$ after A frees it, but will move to the spot $x + 2$ and so on}.\n\nCalculate, where cat B will be at hour $k$?",
    "tutorial": "If $n$ is even, then each hour A and B are on the spots with different parity, so they will never meet. Otherwise, let's look closely what happens. At the start, A in $n$ and B in $1$. But since we can form a cycle from spots then it means that $n$ and $1$ in reality are neighbors. After that, A and B (starting from neighboring positions) just go in opposite directions and meet each other in the opposite spot after exactly $\\left\\lfloor \\frac{n}{2} \\right\\rfloor$ steps. After meeting B \"jumps over\" A making $1$ extra step and the situation become practically the same: A and B are neighbors and move in the opposite direction. In other words, each $f = \\left\\lfloor \\frac{n}{2} \\right\\rfloor$ steps B makes one extra step, so the answer (if both $k$ and spots are $0$-indexed) is $(k + (n \\bmod 2) \\cdot \\left\\lfloor \\frac{k}{f} \\right\\rfloor) \\bmod n$",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        var (n, k) = readLine()!!.split(' ').map { it.toInt() }\n        k--\n        val floor = n / 2\n        println((k + (n % 2) * k / floor) % n + 1)\n    }\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1487",
    "index": "C",
    "title": "Minimum Ties",
    "statement": "A big football championship will occur soon! $n$ teams will compete in it, and each pair of teams will play exactly one game against each other.\n\nThere are two possible outcomes of a game:\n\n- the game may result in a tie, then both teams get $1$ point;\n- one team might win in a game, then the winning team gets $3$ points and the losing team gets $0$ points.\n\nThe score of a team is the number of points it gained during all games that it played.\n\nYou are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.\n\nYour task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.",
    "tutorial": "If $n$ is odd, then we can solve the problem without any ties: each team should win exactly $\\lfloor\\frac{n}{2}\\rfloor$ matches and lose the same number of matches. Finding which matches each team wins and which matches each team loses can be done with some graph algorithms (like Eulerian cycles or circulations), or with a simple construction: place all teams in a circle in any order, and let the $i$-th team win against the next $\\lfloor\\frac{n}{2}\\rfloor$ teams after it in the circle, and lose to all other teams. Unfortunately, if $n$ is even, we need to use some ties since the total sum of scores over all teams is exactly $\\frac{3n(n-1)}{2}$ when there are no ties, and this number is not divisible by $n$ when $n$ is even. Each tie reduces the total sum by $1$, and the minimum number of ties to make $\\frac{3n(n-1)}{2} - t$ divisible by $n$ is $t = \\frac{n}{2}$ (since $\\frac{3n(n-1)}{2} \\bmod n = \\frac{n}{2}$). So, if we find an answer with exactly $\\frac{n}{2}$ ties, it is optimal. And it's easy to find one: once again, place all teams in a circle in any order; make the $i$-th team win against $\\frac{n - 2}{2}$ next teams in the circle, lose against $\\frac{n - 2}{2}$ previous teams in the circle, and tie with the opposite team in the circle.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int n;\n        cin >> n;\n        if(n % 2 == 1)\n        {\n            for(int i = 0; i < n; i++)\n                for(int j = i + 1; j < n; j++)\n                    if(j - i <= n / 2)\n                        cout << 1 << \" \";\n                    else\n                        cout << -1 << \" \";\n            cout << endl;\n        }\n        else\n        {\n            for(int i = 0; i < n; i++)\n                for(int j = i + 1; j < n; j++)\n                    if(j - i < n / 2)\n                        cout << 1 << \" \";\n                    else if(j - i == n / 2)\n                        cout << 0 << \" \";\n                    else\n                        cout << -1 << \" \";\n            cout << endl;\n        }\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1487",
    "index": "D",
    "title": "Pythagorean Triples",
    "statement": "A Pythagorean triple is a triple of integer numbers $(a, b, c)$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $a$, $b$ and $c$, respectively. An example of the Pythagorean triple is $(3, 4, 5)$.\n\nVasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $c = a^2 - b$.\n\nObviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $(3, 4, 5)$: $5 = 3^2 - 4$, so, according to Vasya's formula, it is a Pythagorean triple.\n\nWhen Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $(a, b, c)$ with $1 \\le a \\le b \\le c \\le n$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.",
    "tutorial": "We have to find the number of triples ($a, b, c$) such that equations $a^2+b^2=c^2$ and $a^2-b=c$ are satisfied. Let's subtract one equation from another and get that $b^2+b=c^2-c \\implies b(b+1)=c(c-1)$. So we know that $c=b+1$ and after substituting, we get that $a^2=2b+1$. We can see that there is only one correct value of $b$ (and $c$) for every odd value of $a$ (greater than $1$). So we can iterate over the value of $a$ and check that the corresponding value of $c$ doesn't exceed $n$. This solution works in $O(\\sqrt{n})$ because $a \\approx \\sqrt{c} \\le \\sqrt{n}$, but you can also solve it in $O(1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    int ans = 0;\n    for (int i = 3; i * i <= 2 * n - 1; i += 2)\n      ++ans;\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1487",
    "index": "E",
    "title": "Cheap Dinner",
    "statement": "Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.\n\nThere are $n_1$ different types of first courses Ivan can buy (the $i$-th of them costs $a_i$ coins), $n_2$ different types of second courses (the $i$-th of them costs $b_i$ coins), $n_3$ different types of drinks (the $i$-th of them costs $c_i$ coins) and $n_4$ different types of desserts (the $i$-th of them costs $d_i$ coins).\n\nSome dishes don't go well with each other. There are $m_1$ pairs of first courses and second courses that don't go well with each other, $m_2$ pairs of second courses and drinks, and $m_3$ pairs of drinks and desserts that don't go well with each other.\n\nIvan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!",
    "tutorial": "The main solution is dynamic programming: let $dp_i$ for every possible dish $i$ be the minimum cost to assemble a prefix of a dinner ending with the dish $i$ (here, $i$ can be a dish of any type: first course, second course, drink, or dessert). Then, the answer to the problem is the minimum value among all desserts. The number of transitions in this dynamic programming is too big, since, for example, when transitioning from first courses to second courses, we need to check $O(n_1 n_2$) options. To speed this up, we need some sort of data structure built over the values of $dp_i$ for all first courses $i$ that allows to recalculate $dp_j$ for a second course $j$ quickly. There are two main approaches to this: build any version of RMQ over the values of dynamic programming for the first courses. Then, when we want to calculate the answer for some second course $j$, sort all types of first courses which don't go well with it, and make several RMQ queries to find the minimum value over all non-forbidden first courses; store all values of $dp_i$ in a data structure that supports adding an element, deleting an element, and finding the minimum element (this DS should allow duplicate elements as well). When we want to calculate the answer for some second course $j$, remove all values of $dp_i$ corresponding to the first courses that don't go well with it from the data structure, query the minimum in it, and insert the removed elements back. The same approach can be used to advance from second courses to drinks and from drinks to desserts (you can even use the same code in a for-loop with $3$ iterations, so the resulting solution is actually short and simple).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n\nint main()\n{   \n    vector<int> ns(4);\n    for(int i = 0; i < 4; i++)\n        scanf(\"%d\", &ns[i]);\n    vector<vector<int>> cs(4);\n    for(int i = 0; i < 4; i++)\n    {\n        cs[i].resize(ns[i]);\n        for(int j = 0; j < ns[i]; j++)\n            scanf(\"%d\", &cs[i][j]);\n    }\n    vector<vector<vector<int>>> bad(3);\n    for(int i = 0; i < 3; i++)\n    {\n        bad[i].resize(ns[i + 1]);\n        int m;\n        scanf(\"%d\", &m);\n        for(int j = 0; j < m; j++)\n        {\n            int x, y;\n            scanf(\"%d %d\", &x, &y);\n            x--;\n            y--;\n            bad[i][y].push_back(x);\n        }\n    }                   \n    vector<vector<int>> dp(4);\n    dp[0] = cs[0];\n    for(int i = 0; i < 3; i++)\n    {\n        dp[i + 1].resize(ns[i + 1]);                \n        multiset<int> s;\n        for(int j = 0; j < ns[i]; j++)\n            s.insert(dp[i][j]);\n        for(int j = 0; j < ns[i + 1]; j++)\n        {\n            for(auto k : bad[i][j])\n                s.erase(s.find(dp[i][k]));\n            if(s.empty())\n                dp[i + 1][j] = int(4e8 + 43);\n            else\n                dp[i + 1][j] = *s.begin() + cs[i + 1][j];\n            for(auto k : bad[i][j])\n                s.insert(dp[i][k]);       \n        }\n    }\n    int ans = *min_element(dp[3].begin(), dp[3].end());\n    if(ans > int(4e8))\n        ans = -1;\n    cout << ans << endl;\n}",
    "tags": [
      "brute force",
      "data structures",
      "graphs",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1487",
    "index": "F",
    "title": "Ones",
    "statement": "You are given a positive (greater than zero) integer $n$.\n\nYou have to represent $n$ as the sum of integers (possibly negative) consisting only of ones (digits '1'). For example, $24 = 11 + 11 + 1 + 1$ and $102 = 111 - 11 + 1 + 1$.\n\nAmong all possible representations, you have to find the one that uses the minimum number of ones in total.",
    "tutorial": "Let's build the number from the lowest digit to the highest digit with the following dynamic programming: $dp_{i,carry,cp,cn}$ - the minimum number of ones, if $i$ least significant digits are already fixed, the carry to the next digit is $carry$ (can be negative), there are $cp$ positive numbers (of the form $111 \\cdots 111$) of length greater than or equal to $i$ and $cn$ negative numbers of length greater than or equal to $i$. First, consider the transitions when we reduce the values of $cp$ and/or $cn$. Such transitions correspond to the fact that in the optimal answer there were several numbers of length exactly $i$, and they should not be considered further. If the value of $(cp-cn+carry) \\mod 10$ matches the $i$-th least significant digit in $n$, then we can use transition to $(i+1)$-th state with the new value of $carry$ and the number of ones in the answer increased by $cp+cn$. It remains to estimate what the maximum value of $cp$ ($cn$) and $carry$ we need. The value of $cp$ doesn't exceed the total number of numbers that we use in the answer. Using at most $5$ numbers we can decrease the length of $n$ by at least $1$. Thus, the maximum value of $cp$ and $cn$ is at most $5|n|$ (where |n| is the length of the number $n$). For the value of $carry$, the condition $carry \\ge \\frac{carry+cp}{10}$ should be met (similarly for a negative value). Thus, we can assume that the absolute value of $carry$ doesn't exceed $\\frac{5|n|}{9}$. The total complexity of this solution is $O(|n|^4)$, yet with a high constant factor.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int N = 250;\nconst int M = 28;\nconst int INF = 1e9;\n\nint dp[2][M * 2 + 1][N][N];\n\nint main() {\n  string s;\n  cin >> s;\n  reverse(s.begin(), s.end());\n  s += \"0\";\n  \n  forn(carry, M * 2 + 1) forn(cp, N) forn(cn, N) dp[0][carry][cp][cn] = INF;\n  dp[0][M][N - 1][N - 1] = 0;\n  \n  forn(i, sz(s)) {\n    forn(carry, M * 2 + 1) forn(cp, N) forn(cn, N) dp[1][carry][cp][cn] = INF;\n    forn(carry, M * 2 + 1) for (int cp = N - 1; cp >= 0; --cp) for (int cn = N - 1; cn >= 0; --cn) if (dp[0][carry][cp][cn] != INF) {\n      if (cp > 0) dp[0][carry][cp - 1][cn] = min(dp[0][carry][cp - 1][cn], dp[0][carry][cp][cn]);\n      if (cn > 0) dp[0][carry][cp][cn - 1] = min(dp[0][carry][cp][cn - 1], dp[0][carry][cp][cn]);\n      int rcarry = carry - M;\n      int val = rcarry + cp - cn;\n      int digit = val % 10;\n      if (digit < 0) digit += 10;\n      int ncarry = val / 10;\n      if (val < 0 && digit != 0) --ncarry;\n      if (digit == s[i] - '0') dp[1][ncarry + M][cp][cn] = min(dp[1][ncarry + M][cp][cn], dp[0][carry][cp][cn] + cp + cn);\n    }\n    swap(dp[0], dp[1]);\n  }\n  \n  int ans = INF;\n  forn(i, N) forn(j, N) ans = min(ans, dp[0][M][i][j]);\n  cout << ans << endl;\n}\n",
    "tags": [
      "dp",
      "greedy",
      "shortest paths"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1487",
    "index": "G",
    "title": "String Counting",
    "statement": "You have $c_1$ letters 'a', $c_2$ letters 'b', ..., $c_{26}$ letters 'z'. You want to build a beautiful string of length $n$ from them (obviously, you cannot use the $i$-th letter more than $c_i$ times). \\textbf{Each $c_i$ is greater than $\\frac{n}{3}$}.\n\nA string is called beautiful if there are no palindromic contiguous substrings of odd length greater than $1$ in it. For example, the string \"abacaba\" is not beautiful, it has several palindromic substrings of odd length greater than $1$ (for example, \"aca\"). Another example: the string \"abcaa\" is beautiful.\n\nCalculate the number of different strings you can build, and print the answer modulo $998244353$.",
    "tutorial": "Suppose there is no constraint on the number of letters used. Then this problem can be solved with the following dynamic programming: let $dp_{i, j, k}$ be the number of strings of length $i$ ending with characters $j$ and $k$ that don't contain palindromes of odd length greater than $1$ (obviously, each forbidden palindrome contains a subpalindrome of length $3$, so we only need to ensure that there are no palindromes of length $3$). The thing we are going to use in order to ensure that all the constraints on the number of characters are met is inclusion-exclusion. Since each $c_i > \\frac{n}{3}$, at most two characters can violate their constraints in a single string, so we will iterate on some character of the alphabet and subtract the number of strings violating the constraint on this character from the answer, then iterate on a pair of characters and add the number of strings violating the constraints on these two characters to the answer. Okay, how to calculate the number of strings violating the constraint on some fixed character? Let's use dynamic programming $f_{i, j, k, l}$ - the number of strings such that they contain $i$ characters, $j$ of them have the same type that we fixed, the previous-to-last character is $k$ and the last character is $l$. The number of states here seems to be something about $n^2 \\cdot 26^2$, but in fact, $k$ and $l$ can be optimized to have only two different values since we are interested in two types of characters: the ones that coincide with the character we fixed, and the ones that don't. Okay, what about violating the constraints on two characters? The same method can be used here: let $g_{i, j, k, l, m}$ be the number of strings consisting of $i$ characters such that the number of occurrences of the first fixed character is $j$, the number of occurrences of the second fixed character is $k$, the previous-to-last character is $l$ and the last character is $m$. Again, at first it seems that there are up to $n^3 \\cdot 26^2$ states, but $l$ and $m$ can be optimized to have only $3$ different values, so the number of states is actually $n^3 \\cdot 3^2$. It seems that we have to run this dynamic programming for each pair of characters, right? In fact, no, it is the same for every pair of characters, the only difference is which states violate the constraints and which don't. We can run this dp only once, and when we need an answer for the pair of characters $(x, y)$, we can use two-dimensional prefix sums to query the sum over $g_{i, j, k, l, m}$ with $i = n$, $j > c_x$ and $k > c_y$ in $O(1)$. In fact, this dynamic programming can also be used for the first and the second part of the solution (calculating the strings that don't violate any constraints and the strings that violate the constraints on one character), so the hardest part of the solution runs in $O(n^3)$, though with a pretty big constant factor.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 402;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint sub(int x, int y)\n{\n    return add(x, -y);\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint c[26];\nint dp[2][N][N][3][3];\nint sumDp[N][N];\nint p1[N][N];\nint p2[N][N];\nint n;\n\nint main()\n{\n    cin >> n;\n    for(int i = 0; i < 26; i++)\n        cin >> c[i];\n    for(int i = 0; i < 26; i++)\n        for(int j = 0; j < 26; j++)\n            for(int k = 0; k < 26; k++)\n                if(i != k)\n                {                                                                    \n                    multiset<int> s = {i, j, k};\n                    dp[1][s.count(0)][s.count(1)][min(2, j)][min(2, k)]++;\n                }\n    for(int i = 4; i <= n; i++)\n    {\n        for(int j = 0; j < N; j++)\n            for(int k = 0; k < N; k++)\n                for(int x = 0; x < 3; x++)\n                    for(int y = 0; y < 3; y++)\n                    {\n                        dp[0][j][k][x][y] = dp[1][j][k][x][y];\n                        dp[1][j][k][x][y] = 0;\n                    }\n        for(int j = 0; j < N; j++)\n            for(int k = 0; k < N; k++)\n                for(int x = 0; x < 3; x++)\n                    for(int y = 0; y < 3; y++)\n                    {\n                        int cur = dp[0][j][k][x][y];\n                        if(cur == 0) continue;\n                        for(int z = 0; z < 3; z++)\n                        {                      \n                            int& nw = dp[1][j + (z == 0 ? 1 : 0)][k + (z == 1 ? 1 : 0)][y][z];\n                            nw = add(nw, mul(cur, (z == 2 ? 24 : 1) - (z == x ? 1 : 0)));\n                        }\n                    }\n    }\n    for(int i = 0; i < N; i++)\n        for(int j = 0; j < N; j++)\n            for(int k = 0; k < 3; k++)\n                for(int l = 0; l < 3; l++)\n                    sumDp[i][j] = add(sumDp[i][j], dp[1][i][j][k][l]);\n    for(int i = 0; i < N; i++)\n    {\n        p1[i][N - 1] = sumDp[i][N - 1];\n        for(int j = N - 2; j >= 0; j--)\n            p1[i][j] = add(sumDp[i][j], p1[i][j + 1]);\n    }\n    for(int j = 0; j < N; j++)\n    {\n        p2[N - 1][j] = p1[N - 1][j];\n        for(int i = N - 2; i >= 0; i--)\n            p2[i][j] = add(p1[i][j], p2[i + 1][j]);\n    }\n    int ans = p2[0][0]; \n    for(int i = 0; i < 26; i++)\n    {\n        for(int j = 0; j < N; j++)\n            for(int k = c[i] + 1; k < N; k++)\n                ans = sub(ans, sumDp[k][j]);\n    }\n    for(int i = 0; i < 26; i++)\n        for(int j = 0; j < i; j++)\n            ans = add(ans, p2[c[i] + 1][c[j] + 1]);\n    cout << ans << endl;    \n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1490",
    "index": "A",
    "title": "Dense Array",
    "statement": "Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $i$ ($1 \\le i \\le n-1$), this condition must be satisfied: $$\\frac{\\max(a[i], a[i+1])}{\\min(a[i], a[i+1])} \\le 2$$\n\nFor example, the arrays $[1, 2, 3, 4, 3]$, $[1, 1, 1]$ and $[5, 10]$ are dense. And the arrays $[5, 11]$, $[1, 4, 2]$, $[6, 6, 1]$ are \\textbf{not} dense.\n\nYou are given an array $a$ of $n$ integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added.\n\nFor example, if $a=[4,2,10,1]$, then the answer is $5$, and the array itself after inserting elements into it may look like this: $a=[4,2,\\underline{\\textbf{3}},\\underline{\\textbf{5}},10,\\underline{\\textbf{6}},\\underline{\\textbf{4}},\\underline{\\textbf{2}},1]$ (there are other ways to build such $a$).",
    "tutorial": "Note that adding elements between positions $i$ ($1 \\le i \\le n - 1$) and $i + 1$ will not change the ratio of the adjacent elements, except for the ones just added. Therefore, for each pair of adjacent numbers, the problem can be solved independently. Let us solve the problem for a adjacent pair of numbers $a_i$ and $a_{i+1}$ for which the inequality from the statements does not hold. Suppose that $2a_i \\le a_{i+1}$ (if not, we will swap them). Then between $a_i$ and $a_{i+1}$ it requires to insert $\\left\\lceil log_2 \\left(\\frac{a_{i+1}}{a_i}\\right) - 1 \\right\\rceil$ elements of the form: $2a_i, 4a_i, ..., 2^{\\left\\lceil log_2 \\left(\\frac{a_{i+1}}{a_i}\\right) - 1 \\right\\rceil} a_i$ It is better not to use explicit formula, but to use the following cycle:",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  int last;\n  cin >> last;\n  int ans = 0;\n  for (int i = 1; i < n; i++) {\n    int nw;\n    cin >> nw;\n    int a = min(last, nw), b = max(last, nw);\n    while (a * 2 < b) {\n      ans++;\n      a *= 2;\n    }\n    last = nw;\n  }\n  cout << ans << \"\\n\";\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1490",
    "index": "B",
    "title": "Balanced Remainders",
    "statement": "You are given a number $n$ (\\textbf{divisible by $3$}) and an array $a[1 \\dots n]$. In one move, you can increase any of the array elements by one. Formally, you choose the index $i$ ($1 \\le i \\le n$) and \\textbf{replace} $a_i$ with $a_i + 1$. You can choose the same index $i$ multiple times for different moves.\n\nLet's denote by $c_0$, $c_1$ and $c_2$ the number of numbers from the array $a$ that have remainders $0$, $1$ and $2$ when divided by the number $3$, respectively. Let's say that the array $a$ has balanced remainders if $c_0$, $c_1$ and $c_2$ are equal.\n\nFor example, if $n = 6$ and $a = [0, 2, 5, 5, 4, 8]$, then the following sequence of moves is possible:\n\n- initially $c_0 = 1$, $c_1 = 1$ and $c_2 = 4$, these values are not equal to each other. Let's increase $a_3$, now the array $a = [0, 2, 6, 5, 4, 8]$;\n- $c_0 = 2$, $c_1 = 1$ and $c_2 = 3$, these values are not equal. Let's increase $a_6$, now the array $a = [0, 2, 6, 5, 4, 9]$;\n- $c_0 = 3$, $c_1 = 1$ and $c_2 = 2$, these values are not equal. Let's increase $a_1$, now the array $a = [1, 2, 6, 5, 4, 9]$;\n- $c_0 = 2$, $c_1 = 2$ and $c_2 = 2$, these values are equal to each other, which means that the array $a$ has balanced remainders.\n\nFind the minimum number of moves needed to make the array $a$ have balanced remainders.",
    "tutorial": "Note that the numbers in the $a$ array are not important to us, so initially we will calculate the values of $c_0$, $c_1$, $c_2$. Now applying a move for the number $a_i$ is equivalent to: decreasing $c_{a_i\\ mod\\ 3}$ by $1$; and increasing $c_{(a_i + 1)\\ mod\\ 3}$ by $1$; We will perform the following greedy algorithm: while the array $a$ have no balanced remainders, find any $i$ ($0 \\le i \\le 2$) such that $c_i > \\frac{n}{3}$; we apply the move for $c_i$, that is, replace $c_i$ with $c_i-1$, and $c_{(i+1)\\ mod\\ 3}$ with $c_{(i+1)\\ mod\\ 3}+1$. It is easy to prove the correctness of this greedy algorithm by cyclically shifting the values $c_0$, $c_1$, and $c_2$ so that the first element is equal to the maximum of them.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  for (int &x : a) {\n    cin >> x;\n  }\n\n  int res = 0;\n  vector<int> cnt(3);\n  for (int x = 0; x <= 2; x++) {\n      for (int i = 0; i < n; i++) {\n          if (a[i] % 3 == x) {\n              cnt[x]++;\n          }\n      }\n  }\n  \n  while (*min_element(cnt.begin(), cnt.end()) != n / 3) {\n      for (int i = 0; i < 3; i++) {\n          if (cnt[i] > n / 3) {\n              res++;\n              cnt[i]--;\n              cnt[(i + 1) % 3]++;\n          }\n      }\n  }\n  cout << res << endl;\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1490",
    "index": "C",
    "title": "Sum of Cubes",
    "statement": "You are given a positive integer $x$. Check whether the number $x$ is representable as the sum of the cubes of two positive integers.\n\nFormally, you need to check if there are two integers $a$ and $b$ ($1 \\le a, b$) such that $a^3+b^3=x$.\n\nFor example, if $x = 35$, then the numbers $a=2$ and $b=3$ are suitable ($2^3+3^3=8+27=35$). If $x=4$, then no pair of numbers $a$ and $b$ is suitable.",
    "tutorial": "In this problem, we need to find $a$ and $b$ such that $x=a^3+b^3$ and $a \\ge 1, b \\ge 1$. Since $a$ and $b$ are positive, $a^3$ and $b^3$ are also positive. Hence $a^3 \\le a^3 + b^3 \\le x$. Therefore, the number $a$ can be iterated from $1$ to $\\sqrt[3]{x}$. Since in all tests $x \\le 10^{12}$, then $a \\le 10^4$. For each $a$ , you can find $b$ by the formula $b=\\sqrt[3]{x-a^3}$. This is a positive number. It remains to check that $b$ is an integer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing ld = long double;\n\nconst ll N = 1'000'000'000'000L;\n\nunordered_set<ll> cubes;\n\nvoid precalc() {\n  for (ll i = 1; i * i * i <= N; i++) {\n    cubes.insert(i * i * i);\n  }\n}\n\nvoid solve() {\n  ll x;\n  cin >> x;\n  for (ll i = 1; i * i * i <= x; i++) {\n    if (cubes.count(x - i * i * i)) {\n      cout << \"YES\\n\";\n      return;\n    }\n  }\n  cout << \"NO\\n\";\n}\n\nint main() {\n  precalc();\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1490",
    "index": "D",
    "title": "Permutation Transformation",
    "statement": "A permutation — is a sequence of length $n$ integers from $1$ to $n$, in which all the numbers occur exactly once. For example, $[1]$, $[3, 5, 2, 1, 4]$, $[1, 3, 2]$ — permutations, and $[2, 3, 2]$, $[4, 3, 1]$, $[0]$ — no.\n\nPolycarp was recently gifted a permutation $a[1 \\dots n]$ of length $n$. Polycarp likes trees more than permutations, so he wants to transform permutation $a$ into a rooted binary tree. He transforms an array of different integers into a tree as follows:\n\n- the maximum element of the array becomes the root of the tree;\n- all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child;\n- all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child.\n\nFor example, if he builds a tree by permutation $a=[3, 5, 2, 1, 4]$, then the root will be the element $a_2=5$, and the left subtree will be the tree that will be built for the subarray $a[1 \\dots 1] = [3]$, and the right one — for the subarray $a[3 \\dots 5] = [2, 1, 4]$. As a result, the following tree will be built:\n\n\\begin{center}\n{\\small The tree corresponding to the permutation $a=[3, 5, 2, 1, 4]$.}\n\\end{center}\n\nAnother example: let the permutation be $a=[1, 3, 2, 7, 5, 6, 4]$. In this case, the tree looks like this:\n\n\\begin{center}\n{\\small The tree corresponding to the permutation $a=[1, 3, 2, 7, 5, 6, 4]$.}\n\\end{center}\n\nLet us denote by $d_v$ the depth of the vertex $a_v$, that is, the number of edges on the path from the root to the vertex numbered $a_v$. Note that the root depth is zero. Given the permutation $a$, for each vertex, find the value of $d_v$.",
    "tutorial": "We will construct the required tree recursively. Let us describe the state of tree construction by three values $(l, r, d)$, where $[l, r]$ - is the segment of the permutation, and $d$ - is the current depth. Then the following transitions can be described: find the position $m$ of the maximum element on the segment $[l, r]$, that is, $a_m = \\max\\limits_{i=l}^{r} a_i$; the depth of the vertex $a_m$ is equal to $d$; if $l<m$, then make the transition to the state $(l, m-1, d + 1)$; if $m<r$, then make the transition to the state $(m + 1, r, d + 1)$; Then, in order to construct the required tree, it is necessary to take $(1, n, 0)$ as the initial state.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid build(int l, int r, vector<int> const &a, vector<int> &d, int curD = 0) {\n  if (r < l) {\n    return;\n  }\n  if (l == r) {\n    d[l] = curD;\n    return;\n  }\n  int m = l;\n  for (int i = l + 1; i <= r; i++) {\n    if (a[m] < a[i]) {\n      m = i;\n    }\n  }\n  d[m] = curD;\n  build(l, m - 1, a, d, curD + 1);\n  build(m + 1, r, a, d, curD + 1);\n}\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  for (int &x : a) {\n    cin >> x;\n  }\n  vector<int> d(n);\n  build(0, n - 1, a, d);\n  for (int x :d) {\n    cout << x << \" \";\n  }\n  cout << endl;\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1490",
    "index": "E",
    "title": "Accidental Victory",
    "statement": "A championship is held in Berland, in which $n$ players participate. The player with the number $i$ has $a_i$ ($a_i \\ge 1$) tokens.\n\nThe championship consists of $n-1$ games, which are played according to the following rules:\n\n- in each game, two random players with non-zero tokens are selected;\n- the player with more tokens is considered the winner of the game (in case of a tie, the winner is chosen randomly);\n- the winning player takes all of the loser's tokens;\n\nThe last player with non-zero tokens is the winner of the championship.\n\nAll random decisions that are made during the championship are made equally probable and independently.\n\nFor example, if $n=4$, $a = [1, 2, 4, 3]$, then one of the options for the game (there could be other options) is:\n\n- during the first game, the first and fourth players were selected. The fourth player has more tokens, so he takes the first player's tokens. Now $a = [0, 2, 4, 4]$;\n- during the second game, the fourth and third players were selected. They have the same number of tokens, but in a random way, the third player is the winner. Now $a = [0, 2, 8, 0]$;\n- during the third game, the second and third players were selected. The third player has more tokens, so he takes the second player's tokens. Now $a = [0, 0, 10, 0]$;\n- the third player is declared the winner of the championship.\n\nChampionship winners will receive personalized prizes. Therefore, the judges want to know in advance which players have a chance of winning, i.e have a non-zero probability of winning the championship. You have been asked to find all such players.",
    "tutorial": "How can a player be checked if he can win the championship? Obviously, he must participate in all the games (otherwise we will increase the number of tokens of the opponents). So you can sort out all the people and play greedily with the weakest ones. Such a check will work in linear time after sorting, so we got a solution for $\\mathcal{O}(n^2)$. The simplest solution to this problem is - binary search for the answer. We will sort all the players by the number of tokens they have. Let's prove that if player $i$ can win, then player $i+1$ can also win (the numbers are dealt after sorting). If the player $i$ was able to win, then based on the strategy above, he was able to defeat all the players on the prefix $[0 \\ldots i+1]$. The player $i+1$ can also defeat all these players since he has at least as many tokens. Now both players have to defeat all opponents with numbers $[i+2 \\ldots n]$ and the number of chips both players have is equal to the sum of the first $i+1$ numbers in the array. So if the player $i$ has a strategy, then the player $i+1$ can use the same strategy. Hence the answer to the problem is - sorted suffix of the input array. You can find this suffix using binary search and linear time checking. Bonus: this problem also has a fully linear (after sorting) solution.",
    "code": "def win(pos : int, a : list):\n    power = a[pos]\n    for i in range(len(a)):\n        if i == pos:\n            continue\n        if power < a[i]:\n            return False\n        power += a[i]\n    return True\n\nt = int(input())\n\nwhile t > 0:\n    t -= 1\n    n = int(input())\n    a = list(map(int, input().split(' ')))\n    b = a.copy()\n    a.sort()\n\n    l = -1\n    r = n - 1\n    while r - l > 1:\n        m = (l + r) // 2\n        if (win(m, a)):\n            r = m\n        else:\n            l = m\n\n    winIds = []\n    for i in range(n):\n        if b[i] >= a[r]:\n            winIds.append(i + 1)\n\n    print(len(winIds))\n    print(*winIds)",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1490",
    "index": "F",
    "title": "Equalize the Array",
    "statement": "Polycarp was gifted an array $a$ of length $n$. Polycarp considers an array beautiful if there exists a number $C$, such that each number in the array occurs either zero or $C$ times. Polycarp wants to remove some elements from the array $a$ to make it beautiful.\n\nFor example, if $n=6$ and $a = [1, 3, 2, 1, 4, 2]$, then the following options are possible to make the array $a$ array beautiful:\n\n- Polycarp removes elements at positions $2$ and $5$, array $a$ becomes equal to $[1, 2, 1, 2]$;\n- Polycarp removes elements at positions $1$ and $6$, array $a$ becomes equal to $[3, 2, 1, 4]$;\n- Polycarp removes elements at positions $1, 2$ and $6$, array $a$ becomes equal to $[2, 1, 4]$;\n\nHelp Polycarp determine the minimum number of elements to remove from the array $a$ to make it beautiful.",
    "tutorial": "Let's calculate the value of $cnt_x$ - how many times the number $x$ occurs in the array $a$. We will iterate over the value of $C$ and look for the minimum number of moves necessary for each number to appear in the $a$ array either $0$ times, or $C$ times. Note that if there is no such number $y$ that $cnt_y = C$, then such a value of $C$ will not give the minimum answer (because we have removed unnecessary elements). Then, for a specific $C$, the answer is calculated as follows: $\\sum\\limits_{cnt_x<C} cnt_x + \\sum\\limits_{cnt_x \\ge C}(cnt_x - C)$ Since the number of candidates for the value of $C$ is no more than $n$, this method works in $\\mathcal{O}(n^2)$. Then there are two ways to optimize our solution: you can consider only unique values of $C$ (there are no more than $\\mathcal{O}(\\sqrt n)$), and get a solution in $\\mathcal{O}(n \\sqrt n)$; you can sort the values $cnt_x$ and use prefix sums, this solution works for $\\mathcal{O}(n \\log n)$ or for $\\mathcal{O}(n)$ (if you use counting sort).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  map<int, int> cnt;\n  for (int i = 0; i < n; i++) {\n    int x;\n    cin >> x;\n    cnt[x]++;\n  }\n  map<int, int> groupedByCnt;\n  for (auto[x, y] : cnt) {\n    groupedByCnt[y]++;\n  }\n\n  int res = n;\n  int left = 0, right = n, rightCnt = (int) cnt.size();\n  for (auto[x, y] : groupedByCnt) {\n    res = min(res, left + right - rightCnt * x);\n    left += x * y;\n    right -= x * y;\n    rightCnt -= y;\n  }\n  cout << res << endl;\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1490",
    "index": "G",
    "title": "Old Floppy Drive ",
    "statement": "Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with $n$ integers written on it.\n\nPolycarp wrote the numbers from the disk into the $a$ array. It turned out that the drive works according to the following algorithm:\n\n- the drive takes one positive number $x$ as input and puts a pointer to the first element of the $a$ array;\n- after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the $a$ array, the last element is again followed by the first one;\n- as soon as the sum is at least $x$, the drive will shut down.\n\nPolycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you $m$ questions. To answer the $i$-th of them, you need to find how many seconds the drive will work if you give it $x_i$ as input. Please note that in some cases the drive can work infinitely.\n\nFor example, if $n=3, m=3$, $a=[1, -3, 4]$ and $x=[1, 5, 2]$, then the answers to the questions are as follows:\n\n- the answer to the first query is $0$ because the drive initially points to the first item and the initial sum is $1$.\n- the answer to the second query is $6$, the drive will spin the disk completely twice and the amount becomes $1+(-3)+4+1+(-3)+4+1=5$.\n- the answer to the third query is $2$, the amount is $1+(-3)+4=2$.",
    "tutorial": "Let's denote for $S$ the sum of all the elements of the array, and for $pref$ the array of its prefix sums. If the drive runs for $t$ seconds, the sum is $\\left\\lfloor \\frac{t}{s} \\right\\rfloor \\cdot S + pref[t \\bmod n]$. This formula immediately shows that if $\\max\\limits_{i=0}^{n-1} pref[i] < x$ and $S \\le 0$, then the disk will run indefinitely. Otherwise, the answer exists. The disk cannot make less than, $\\left\\lceil \\frac{x - \\max\\limits_{i=0}^{n-1} pref[i]}{S} \\right\\rceil$ full spins, otherwise the required amount simply will not be achived. The disk can't make more spins either, because when it reaches the position of the maximum prefix sum, $x$ will already be achived. So we know how to determine the number of full spins of the disk. Let's make these spins: $x:= x - \\left\\lceil \\frac{x - \\max\\limits_{i=0}^{n-1} pref[i]}{S} \\right\\rceil \\cdot S$ Now we have a new problem, given $x$, find the first position $i$ in the array, such that $pref[i] \\ge x$. This problem can be solved using binary search. If $pref$ is not sorted into the array, that is, there is $j$, such that $pref[j-1] > pref[j]$, then $pref[j]$ can simply be thrown out of the array (the answer will never be reached on it).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n  int n, m;\n  cin >> n >> m;\n  vector<ll> a(n);\n  ll allSum = 0;\n  vector<ll> pref;\n  vector<int> ind;\n  int curInd = 0;\n  for (ll &e : a) {\n    cin >> e;\n    allSum += e;\n    if (pref.empty() || allSum > pref.back()) {\n      pref.push_back(allSum);\n      ind.push_back(curInd);\n    }\n    curInd++;\n  }\n  for (int q = 0; q < m; q++) {\n    ll x;\n    cin >> x;\n    if (pref.back() < x && allSum <= 0) {\n      cout << -1 << \" \";\n      continue;\n    }\n    ll needTimes = 0;\n    if (pref.back() < x) {\n      needTimes = (x - pref.back() + allSum - 1) / allSum;\n    }\n    x -= needTimes * allSum;\n    cout << needTimes * n + ind[lower_bound(pref.begin(), pref.end(), x) - pref.begin()] << \" \";\n  }\n  cout << \"\\n\";\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "binary search",
      "data structures",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1491",
    "index": "A",
    "title": "K-th Largest Value",
    "statement": "You are given an array $a$ consisting of $n$ integers. \\textbf{Initially all elements of $a$ are either $0$ or $1$}. You need to process $q$ queries of two kinds:\n\n- 1 x : Assign to $a_x$ the value $1 - a_x$.\n- 2 k : Print the $k$-th largest value of the array.\n\nAs a reminder, $k$-th largest value of the array $b$ is defined as following:\n\n- Sort the array in the non-increasing order, return $k$-th element from it.\n\nFor example, the second largest element in array $[0, 1, 0, 1]$ is $1$, as after sorting in non-increasing order it becomes $[1, 1, 0, 0]$, and the second element in this array is equal to $1$.",
    "tutorial": "How can we find the largest $k$ such that the $k$-th smallest element of the array is $0$? How can we maintain $k$? Let's define $cnt$ to represent the number of 1s in the array. For the modifications, if $a_i$ is already $1$ now, then we let $cnt \\gets cnt - 1$. Otherwise, let $cnt \\gets cnt + 1$. For the querys, just compare $cnt$ with $k$. If $cnt \\ge k$, the answer will be $1$. Otherwise, the answer will be $0$. The complexity : $O(n + q)$.",
    "code": "n, q = map(int,input().split())\na = list(map(int,input().split()))\nzero = a.count(0)\none = n - zero\nfor _ in range(q):\n    t, x = map(int,input().split())\n    if t == 1:\n        if a[x-1] == 1:\n            zero += 1\n            one -= 1\n            a[x-1] = 0\n        else:\n            zero -= 1\n            one += 1\n            a[x-1] = 1\n    else:\n        if x<=one:\n            print(1)\n        else:\n            print(0)",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1491",
    "index": "B",
    "title": "Minimal Cost",
    "statement": "There is a graph of $n$ rows and $10^6 + 2$ columns, where rows are numbered from $1$ to $n$ and columns from $0$ to $10^6 + 1$:\n\nLet's denote the node in the row $i$ and column $j$ by $(i, j)$.\n\nInitially for each $i$ the $i$-th row has exactly one obstacle — at node $(i, a_i)$. You want to move some obstacles so that you can reach node $(n, 10^6+1)$ from node $(1, 0)$ by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs $u$ or $v$ coins, as below:\n\n- If there is an obstacle in the node $(i, j)$, you can use $u$ coins to move it to $(i-1, j)$ or $(i+1, j)$, if such node exists and if there is no obstacle in that node currently.\n- If there is an obstacle in the node $(i, j)$, you can use $v$ coins to move it to $(i, j-1)$ or $(i, j+1)$, if such node exists and if there is no obstacle in that node currently.\n- Note that you \\textbf{can't move obstacles outside the grid}. For example, you can't move an obstacle from $(1,1)$ to $(0,1)$.\n\nRefer to the picture above for a better understanding.\n\nNow you need to calculate the minimal number of coins you need to spend to be able to reach node $(n, 10^6+1)$ from node $(1, 0)$ by moving through edges of this graph without passing through obstacles.",
    "tutorial": "When is the answer $0$? Or rather, when do you not have to make any moves? What happens if $a[i]$ is same for all $i$? Consider the following situations: $\\forall i \\in [2,n], |a_i - a_{i - 1}| = 0$, then the answer will be $v + \\min(u, v)$. $\\exists i \\in [2,n], |a_i - a_{i - 1}| > 1$, then the answer will be $0$. Otherwise, the answer will be $\\min(u, v)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 1e6 + 5;\nint n, a[N], ans = INT_MAX, u, v, T;\nint main()\n{\n\tios::sync_with_stdio(false);\n\tcin>>T;\n\twhile(T--){\n\t    ans = INT_MAX;\n\t    cin >> n >> u >> v;\n\t    for(int i = 1; i <= n; i++)\n\t\t    cin >> a[i];\n\t    for(int i = 2; i <= n; i++)\n\t    {\n\t\t    if(abs(a[i] - a[i - 1]) >= 2) ans = 0;\n\t    \tif(abs(a[i] - a[i - 1]) == 1) ans = min(ans, min(u, v));\n\t\t    if(a[i] == a[i - 1]) ans = min(ans, v + min(u, v));\n\t    }\n\t    cout << ans << endl;\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1491",
    "index": "C",
    "title": "Pekora and Trampoline",
    "statement": "There is a trampoline park with $n$ trampolines in a line. The $i$-th of which has strength $S_i$.\n\nPekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice.\n\nIf at the moment Pekora jumps on trampoline $i$, the trampoline will launch her to position $i + S_i$, and $S_i$ will become equal to $\\max(S_i-1,1)$. In other words, $S_i$ will decrease by $1$, except of the case $S_i=1$, when $S_i$ will remain equal to $1$.\n\nIf there is no trampoline in position $i + S_i$, then this pass is over. Otherwise, Pekora will continue the pass by jumping from the trampoline at position $i + S_i$ by the same rule as above.\n\n\\textbf{Pekora can't stop jumping during the pass until she lands at the position larger than $n$ (in which there is no trampoline)}. Poor Pekora!\n\nPekora is a naughty rabbit and wants to ruin the trampoline park by reducing all $S_i$ to $1$. What is the minimum number of passes she needs to reduce all $S_i$ to $1$?",
    "tutorial": "Think greedily! By exchange argument, where can Pekora start her pass in an optimal solution? For a series of passes, we can describe it as an array $P$ where $P_i$ is the trampoline Pekora starts at in the $i$-th pass. We claim that the final state of trampolines after performing any permutation of $P$ will be the same. Focus on $2$ adjacent passes. We realize that if we swap those $2$ passes, the jumps done on both these passes are the same. Since swapping any $2$ adjacent passes does not change the final state of trampolines, any permutation of $P$ will not change the final state of trampolines. Now, we can claim that there is an optimal solution with $P$ being non-decreasing. Since Pekora can only move right, we must put Pekora on the first trampoline such that $S_i \\ne 1$. However, we cannot directly simulate putting Pekora on the first trampoline such that $S_i \\ne 1$. This actually uses $O(N^3)$. 5000 4999 4998 4997 ... 2 1 However, we can simulate this in $O(N^2)$ by the following. Instead of simulating passes individually, we will combine them. The main idea is that when Pekora jumps on a trampoline of strength $S_i$, we just add another Pekora on trampoline $S_i+i$ and process it later. So, when we process trampolines from $1$ to $N$, we keep track of how many Pekoras there are on trampoline $i$, which we will denote as $C_i$. Then, we only add extra Pekoras to trampoline $i$ if $S_i>C_i+1$. Now, we have some Pekoras on trampoline $i$ and we need to update other values of $C_i$. If $S_i=4$ and $C_i=6$ for example, we would add $1$ Pekora each trampolines to $i+2,i+3,i+4$ to reduce $S_i$ to 1. Then, the rest of the Pekoras will be moved to trampoline $i+1$. This algorithm runs in $O(N^2)$ as we only need to update $O(N)$ other trampolines at each step. Bonus: solve this problem in $O(N)$. (This was the original constraints but it was later changed since it was too hard for its position.)",
    "code": "TC=int(input())\n\nfor tc in range(TC):\n    n=int(input())\n    arr=list(map(int,input().split()))\n    \n    curr=[0]*(n+5)\n    \n    ans=0\n    \n    for x in range(n):\n        temp=curr[x]\n        \n        if (temp<arr[x]-1):\n            ans+=arr[x]-1-temp\n            temp+=arr[x]-1-temp\n            \n        curr[x+1]+=temp-arr[x]+1\n        for y in range(x+2,min(n,x+arr[x]+1)):\n            curr[y]+=1\n        \n    print(ans)",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1491",
    "index": "D",
    "title": "Zookeeper and The Infinite Zoo",
    "statement": "There is a new attraction in Singapore Zoo: The Infinite Zoo.\n\nThe Infinite Zoo can be represented by a graph with an infinite number of vertices labeled $1,2,3,\\ldots$. There is a directed edge from vertex $u$ to vertex $u+v$ if and only if $u\\&v=v$, where $\\&$ denotes the bitwise AND operation. There are no other edges in the graph.\n\nZookeeper has $q$ queries. In the $i$-th query she will ask you if she can travel from vertex $u_i$ to vertex $v_i$ by going through directed edges.",
    "tutorial": "Since $\\&$ is a bitwise operation, represent the number in binary form! We can convert any $u+v$ move to a series of $u+v'$ moves where $u\\&v'=v'$ and $v'=2^k$. Such a move converts a substring of the binary string of the form $01\\ldots11$ into $10\\ldots00$. Focus on converting $01$ into $10$. Firstly, we can show that the reachability graph is equivalent if we restrict to a directed edge between vertices $u$ and $u+v$ if $u\\&v=v$ and that $v=2^k$ for some $k$. This is because we can add each bit from $v$ from $u$ from the highest bit as adding a bit to a number will not affect lower bits. Now, we observe that such as operation converts a binary string of the form $01\\ldots11$ into $10\\ldots00$ for some substring when we represent $u$ as a binary string. (more significant bits are to the left). Now, we consider $s$ and $t$ as binary strings. If and only if there is a matching from bits in $t$ to a lower bit in $s$ and $t$ > $s$, then $t$ is reachable from $s$. Turning $01\\ldots11$ into $10\\ldots00$ means that we can move a bit ($01$->$10$) or we can squish multiple bits ($0111$->$1000$). Let us show it is necessary. If $s>t$, it is impossible. And if there is no such matching, we are not able to put a position in $t$ as bits cannot move back, or there are not enough bits in $s$ to form $t$ (since the number of bits cannot increase). Let is show it is sufficient. Since $s<t$ ($s=t$ is trivial), the strings have some common prefix and the most significant different bit has $0$ in $s$ and $1$ and $t$. Now, we can shift every bit in s into a position in t and squish the most significant bits. To check if there is a matching, we find the least significant bit ($lsb$) of $t$ and $s$. if $lsb(t) < lsb(s)$ or if $s = 0$, then it is impossible. Else, we remove the $lsb$ from both $t$ and $s$ and repeat. If we're able to remove bits until $t=0$, then it is possible to go from $s$ to $t$.",
    "code": "def lsb(x):\n    return x & (-x)\nQ = int(input())\nfor q in range(Q):\n    a,b = map(int,input().split(\" \"))\n    if a > b:\n        print(\"NO\")\n    else:\n        can = True\n        while b > 0:\n            if lsb(b) < lsb(a) or a == 0:\n                can = False\n                break\n            a -= lsb(a)\n            b -= lsb(b)\n        print(\"YES\" if can else \"NO\")",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1491",
    "index": "E",
    "title": "Fib-tree",
    "statement": "Let $F_k$ denote the $k$-th term of Fibonacci sequence, defined as below:\n\n- $F_0 = F_1 = 1$\n- for any integer $n \\geq 0$, $F_{n+2} = F_{n+1} + F_n$\n\nYou are given a tree with $n$ vertices. Recall that a tree is a connected undirected graph without cycles.\n\nWe call a tree a \\textbf{Fib-tree}, if its number of vertices equals $F_k$ for some $k$, and at least one of the following conditions holds:\n\n- The tree consists of only $1$ vertex;\n- You can divide it into two Fib-trees by removing some edge of the tree.\n\nDetermine whether the given tree is a Fib-tree or not.",
    "tutorial": "The only pair $(j,k)$ that satisfies $F_i=F_j+F_k$ is $(i-1,i-2)$. Firstly, we can discover that we can only cut a tree in the size of $f_{i}$ into one in size of $f_{i-1}$ and one in size of $f_{i-2}$. We want to show that the only solution to $F_i=F_j+F_k$ is $(j,k)=(i-1,i-2)$ for $j \\geq k$. Clearly, $i>j$, otherwise, $F_i<F_j+F_k$. Furthermore, $j>i-2$ as $F_i>2 \\cdot F_{i-2}$. Therefore, we have shown the only solution is $(j,k)=(i-1,i-2)$. However, we will have 2 ways to partition the tree sometimes. But it turns out we can cut any edge! We will prove that if some edge cuts Fib-tree of $F_n$ vertices into trees with sizes $F_{n-1}$ and $F_{n-2}$, we can cut it, and the resulting trees are also Fib-trees. By induction. For $n = 2$ it's obvious. If only edge cuts Fib-tree into trees with sizes $F_{n-1}$ and $F_{n-2}$, we have to cut it. If there are two such edges: suppose that cutting the first edge results in making two Fib-trees. Then in the tree of size $F_{n-1}$ the second edge divides it into trees of sizes $F_{n-2}$ and $F_{n-3}$, so we can cut it as well in the next step. But then we could as well cut the second edge first: we will have one Fib-tree of size $F_{n-2}$, and one tree of size $F_{n-1}$ which is cut into Fib-trees of sizes $F_{n-2}$ and $F_{n-3}$ by the first edge, so it's also a Fib-tree! Because the growth of Fibonacci sequence is approximately $O(\\phi^n)$, we only need to cut our tree $O(\\log_\\phi n)$ times: every time, if we find the splitting edge, we cut it, and recurse to the resulting trees, if at some point there was no splitting edge - tree isn't Fib-tree. Finally, we got an $O(n\\log_\\phi n)$ solution.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 2e5 + 5;\nint n, siz[N];\nvector<int> fib;\nvector<pair<int, bool> > G[N];\nvoid NO() { cout << \"NO\\n\"; exit(0); }\nvoid GetSize(int u, int fa)\n{\n    siz[u] = 1;\n    for(pair<int, bool> e : G[u])\n    {\n        if(e.second) continue;\n        int v = e.first;\n        if(v == fa) continue;\n        GetSize(v, u);\n        siz[u] += siz[v];\n    }\n}\nvoid CutEdge(int u, int fa, int k, int &pu, int &pv, int &kd)\n{\n    for(pair<int, bool> e : G[u])\n    {\n        if(pu) return;\n        if(e.second) continue;\n        int v = e.first;\n        if(v == fa) continue;\n        if(siz[v] == fib[k - 1] || siz[v] == fib[k - 2])\n        {\n            pu = u; pv = v;\n            kd = (siz[v] == fib[k - 1]) ? k - 1 : k - 2;\n            break;\n        }\n        CutEdge(v, u, k, pu, pv, kd);\n    }\n}\nvoid Check(int u, int k)\n{\n//    cout << \"Check \" << u << ' ' << k << endl;\n    if(k <= 1) return;\n    GetSize(u, 0);\n    int pu = 0, pv = 0, kd = 0;\n    CutEdge(u, 0, k, pu, pv, kd);\n//    cout << pu << ' ' << pv << ' ' << kd << endl;\n    if(!pu) NO();\n    for(pair<int, bool> &e : G[pu])\n        if(e.first == pv) e.second = true;\n    for(pair<int, bool> &e : G[pv])\n        if(e.first == pu) e.second = true;\n    Check(pv, kd);\n    Check(pu, (kd == k - 1) ? k - 2 : k - 1);\n}\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin >> n;\n    fib.push_back(1);\n    fib.push_back(1);\n    for(int i = 1; ; i++)\n    {\n        if(fib[i] >= n) break;\n        int new_fib = fib[i] + fib[i - 1];\n        fib.push_back(new_fib);\n    }\n    for(int i = 1; i < n; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        G[u].push_back(make_pair(v, false));\n        G[v].push_back(make_pair(u, false));\n    }\n    if(fib[fib.size() - 1] != n) NO();\n    Check(1, fib.size() - 1);\n    cout << \"YES\\n\";\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "divide and conquer",
      "number theory",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1491",
    "index": "F",
    "title": "Magnets",
    "statement": "This is an interactive problem.\n\nKochiya Sanae is playing with magnets. Realizing that some of those magnets are demagnetized, she is curious to find them out.\n\nThere are $n$ magnets, which can be of the following $3$ types:\n\n- N\n- S\n- - — these magnets are demagnetized.\n\nNote that \\textbf{you don't know} the types of these magnets beforehand.\n\nYou have a machine which can measure the force between the magnets, and you can use it \\textbf{at most} $n+\\lfloor \\log_2n\\rfloor$ times.\n\nYou can put some magnets to the left part of the machine and some to the right part of the machine, and launch the machine. Obviously, you can put one magnet to at most one side (you don't have to put all magnets). You can put the same magnet in different queries.\n\nThen the machine will tell the force these magnets produce. Formally, let $n_1,s_1$ be the number of N and S magnets correspondently on the left and $n_2,s_2$ — on the right. Then the force between them would be $n_1n_2+s_1s_2-n_1s_2-n_2s_1$. Please note that the force is a \\textbf{signed} value.\n\nHowever, when the \\textbf{absolute} value of the force is \\textbf{strictly larger than} $n$, the machine will crash into pieces.\n\nYou need to find \\textbf{all} magnets of type - (all demagnetized ones), \\textbf{without breaking the machine}.\n\n\\textbf{Note that the interactor is not adaptive}. The types of the magnets are fixed before the start of the interaction and do not change with queries.\n\nIt is guaranteed that there are \\textbf{at least} $2$ magnets whose type is not -, and \\textbf{at least} $1$ magnet of type -.",
    "tutorial": "Try to construct a solution that works in $2n$ queries. Try to find the second magnet which is not `-'. The actual query limit is $n-1+\\lceil\\log_2n\\rceil$. It seems this problem needs some random technique, but here is a determinate solution: We just try to find a not demagnetized magnet. You can go through the following method to find one: First put the first magnet in the left. Then ask all the other magnets with the left pile. If we got a non-zero answer, we find a valid magnet; else we just put this magnet in the left. It can be proven later that we will always be able to find a valid magnet. Then use this magnet to try on all other magnets. This process form a solution requiring at most $2n-2$ queries. However, when we look back at this solution we'll realize that there is a huge waste of information in the previous queries. As all the previous answers are $0$, it's easy to prove that the magnet we found is the second one we have selected. Since we know nothing about the right part, we can simply check the magnets in the right one by one. However, you have known that there is only $1$ magnetic magnet in the left, so you can do a binary search to seek for the answer. The maximum number of queries is $n-1+\\lceil\\log_2n\\rceil$, which perfectly matches the limit.",
    "code": "#include<bits/stdc++.h>\nint n;\nstd::vector<int>ans,tmp,hlf;\nint main()\n{\n    int T;\n\tscanf(\"%d\",&T);\n\tfor(;T--;)\n\t{\n\t    ans.clear(),tmp.clear(),hlf.clear();\n    \tscanf(\"%d\",&n);\n    \tregister int i,ii;\n    \tint sec=0;\n    \tfor(i=2;i<=n;i++)\n    \t{\n    \t\tprintf(\"? 1 %d\\n%d\\n\",i-1,i);\n    \t\tfor(ii=1;ii<i;ii++)printf(\"%d \",ii);\n    \t\tputs(\"\"),fflush(stdout);\n    \t\tint f;\n    \t\tscanf(\"%d\",&f);\n    \t\tif(f){sec=i;break;}\n    \t}for(i=sec+1;i<=n;i++)\n    \t{\n    \t\tprintf(\"? 1 1\\n%d\\n%d\\n\",sec,i);\n    \t\tfflush(stdout);\n    \t\tint f;\n    \t\tscanf(\"%d\",&f);\n    \t\tif(!f)ans.push_back(i);\n    \t}for(i=1;i<sec;i++)tmp.push_back(i);\n    \twhile(tmp.size()>1)\n    \t{\n    \t\tint md=tmp.size()>>1;\n    \t\thlf.clear();\n    \t\tfor(i=1;i<=md;i++)\n    \t\t\thlf.push_back(tmp.back()),tmp.pop_back();\n    \t\tprintf(\"? 1 %d\\n%d\\n\",md,sec);\n    \t\tfor(int t:hlf)printf(\"%d \",t);\n    \t\tputs(\"\"),fflush(stdout);\n    \t\tint f;\n    \t\tscanf(\"%d\",&f);\n    \t\tif(f)tmp=hlf;\n    \t}\n    \tfor(i=1;i<sec;i++)if(tmp[0]!=i)ans.push_back(i);\n    \tprintf(\"! %u\",ans.size());\n    \tfor(int t:ans)printf(\" %d\",t);\n    \tputs(\"\"),fflush(stdout);\n\t}\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1491",
    "index": "G",
    "title": "Switch and Flip",
    "statement": "There are $n$ coins labeled from $1$ to $n$. Initially, coin $c_i$ is on position $i$ and is facing upwards (($c_1, c_2, \\dots, c_n)$ is a permutation of numbers from $1$ to $n$). You can do some operations on these coins.\n\nIn one operation, you can do the following:\n\n- Choose $2$ distinct indices $i$ and $j$.\n- Then, swap the coins on positions $i$ and $j$.\n- Then, flip both coins on positions $i$ and $j$. (If they are initially faced up, they will be faced down after the operation and vice versa)\n\nConstruct a sequence of at most $n+1$ operations such that after performing all these operations the coin $i$ will be on position $i$ at the end, \\textbf{facing up}.\n\nNote that you \\textbf{do not need} to minimize the number of operations.",
    "tutorial": "Visualize this problem as graph with directed edges $(i,c_i)$. Solve this problem where there is only $1$ big cycle. What if a cycle has $2$ coins that are upside down? How can we force a cycle into such state? We can visualize the problem as a graph with nodes of $2$ colors (face up - red and face down - blue). Initially, the graph has nodes with all red color and with a directed edge to $c_i$. Firstly, any $2$ cycles with all red nodes can be converted into a single cycle with $2$ blues nodes with $1$ swap. A cycle with $2$ blue nodes is very convenient here as swapping a blue node with a red node it is pointing to will decrease the cycle size and maintain that the cycle still has $2$ blue nodes. We can keep decreasing the cycle size until the cycle has only $2$ blue nodes and solve that in $1$ swap. Thus, solving $2$ cycles which have $X$ nodes in total uses only $X$ swaps. Now, we simply pair the cycles and do this. However, if there is an odd number of cycles, there are $2$ cases: If the cycle does not cover the whole graph, we can solve the remaining cycle and a cycle of size $1$ together. Otherwise, we can force $2$ blue nodes into the cycle with $2$ swaps (does not work for $n = 2$ so be careful). Both cases need $X+1$ moves where $X$ is the size of the remaining cycle. Thus, at most $X+1$ swaps is needed in this algorithm.",
    "code": "from sys import stdin, stdout\n\nn=int(stdin.readline())\n\n#make 1-indexed\narr=[0]+list(map(int,stdin.readline().split()))\n\nvis=[0]*(n+1)\n\nans=[]\n\ndef cswap(i,j):\n    arr[i],arr[j]=-arr[j],-arr[i]\n    ans.append((i,j))\n    \ndef swap_cyc(i,j):\n    cswap(i,j)\n    \n    curr=i\n    while (arr[-arr[curr]]>0):\n        cswap(curr,-arr[curr])\n        \n    curr=-arr[curr]\n    while (arr[-arr[curr]]>0):\n        cswap(curr,-arr[curr])\n        \n    cswap(curr,-arr[curr])\n    \np=-1\nfor i in range(1,n+1):\n    if (vis[i]==1): continue\n    if (arr[i]==i): continue\n    \n    curr=i\n    while (True):\n        vis[curr]=1\n        curr=arr[curr]\n        if (curr==i): break\n        \n    if (p==-1): \n        p=i\n    else:\n        swap_cyc(p,i)\n        p=-1\n\nif (p!=-1):\n    can=False\n    for i in range(1,n+1):\n        if (arr[i]==i):\n            swap_cyc(p,i)\n            can=True\n            break\n        \n    if (can==False):\n        t1,t2=arr[p],arr[arr[p]]\n        cswap(p,t1)\n        swap_cyc(t1,t2)\n            \nprint(len(ans))\n[print(i[0],i[1]) for i in ans]",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1491",
    "index": "H",
    "title": "Yuezheng Ling and Dynamic Tree",
    "statement": "Yuezheng Ling gives Luo Tianyi a tree which has $n$ nodes, rooted at $1$.\n\nLuo Tianyi will tell you that the parent of the $i$-th node is $a_i$ ($1 \\leq a_i<i$ for $2 \\le i \\le n$), and she will ask you to perform $q$ queries of $2$ types:\n\n- She'll give you three integers $l$, $r$ and $x$ ($2 \\le l \\le r \\le n$, $1 \\le x \\le 10^5$). You need to replace $a_i$ with $\\max(a_i-x,1)$ for all $i$ with $l \\leq i \\leq r$.\n- She'll give you two integers $u$, $v$ ($1 \\le u, v \\le n$). You need to find the LCA of nodes $u$ and $v$ (their lowest common ancestor).",
    "tutorial": "The complexity is $\\mathcal O(n\\sqrt{n})$. Divide the nodes into $\\sqrt{n}$ blocks. The $i$-th block will contain the nodes in $[(i-1) \\sqrt{n}+1,i \\sqrt{n}]$. Let's define $f_x$ as an ancestor of $x$ such that $f_x$ is in the same block as $x$ and $a_{f_x}$ is not in the same block as $x$. Notice that for a given block, if all $a_x$ is not in the same block as $x$, then $f_x=x$. So, we do not have to re-compute all values of $f_x$ for a certain block if $\\forall x, x-a_x \\geq \\sqrt n$ in this block. When we update a range, we will update some ranges fully and update at most $2$ ranges partially. Let's show that only $O(n+q)$ re-computations will happen. For a certain block, if it is completely contained in an update, the value of $x-a_x$ will increase by $1$, a single block will be re-computed by at most $O(\\sqrt n)$ of such updates, which will contribute $O(\\sqrt n \\cdot \\sqrt n)=O(n)$ re-computations. For blocks that are partially updated by an update, such things will only happen at most $2q$ times, therefore we have a bound of $O(q)$ re-computations from such updates. Maintaining $f_x$, querying can be easily done in $O(\\sqrt n)$.",
    "code": "#include <bits/stdc++.h>\n#define N 100005\nusing namespace std;\n\ntemplate <typename T>\n\nvoid read(T &a)\n{\n\tT x = 0,f = 1;\n\tchar ch = getchar();\n\twhile (ch < '0' || ch > '9')\n\t{\n\t\tif (ch == '-') f = -1;\n\t\tch = getchar();\n\t}\n\twhile (ch >= '0' && ch <= '9')\n\t{\n\t\tx = (x << 1) + (x << 3) + (ch ^ 48);\n\t\tch = getchar();\n\t}\n\ta = x * f;\n}\n\ntemplate <typename T>\n\nvoid write(T x)\n{\n\tif (x < 0) putchar('-'),x = -x;\n\tif (x < 10) return (void) putchar(x + '0');\n\twrite(x / 10);\n\tputchar(x % 10 + '0');\n}\n\ntemplate <typename T>\n\nvoid writeln(T x)\n{\n\twrite(x);\n\tputchar('\\n');\n}\n\ntemplate <typename T>\n\nvoid writes(T x)\n{\n\twrite(x);\n\tputchar(' ');\n}\n\ntemplate <typename T,typename... Args> \n\nvoid read(T &maxx,Args &... args)\n{\n\tread(maxx);\n\tread(args...);\n}\n\ntemplate <typename T,typename... Args>\n\nvoid writeln(T maxx,Args ... args)\n{\n\twrites(maxx);\n\twrites(args...);\n\tputchar('\\n');\n}\n\nconst int B = 300;\nint n,q,a[N],num,bl[N],vis[N];\nstd::vector<int> v;\n\nstruct Block\n{\n\tint f[B],lazy,flag,cnt,L,R;\n\tvoid update()\n\t{\n\t\tflag = 1;\n\t\tfor (int i = L; i <= R; i++)\n\t\t{\n\t\t\tif (bl[i] != bl[a[i]]) f[i - L] = i;\n\t\t\telse f[i - L] = f[a[i] - L],flag = 0;\n\t\t}\n\t}\n\tvoid update(int l,int r,int x)\n\t{\n\t\tfor (int i = l; i <= r; i++)\n\t\t\ta[i] = i == 1 ? 0 : max(a[i] - x,1);\n\t\tupdate();\n\t}\n\tvoid update(int x)\n\t{\n\t\tif (flag) lazy += x;\n\t\telse update(L,R,x);\n\t}\n}T[(N - 1) / B + 5];\n\nvoid update(int l,int r,int x)\n{\n\tif (bl[l] == bl[r])\n\t{\n\t\tT[bl[l]].update(l,r,x);\n\t\treturn ;\n\t}\n\tT[bl[l]].update(l,T[bl[l]].R,x);\n\tfor (int i = bl[l] + 1; i < bl[r]; i++)\n\t\tT[i].update(x);\n\tT[bl[r]].update(T[bl[r]].L,r,x);\n\t// cout << l << ' ' << r << ' ' << x << endl;\n\t// cout << '0' << ' ';\n\t// for (int i = 2; i <= n; i++)\n\t// \tcout << max(a[i] - T[bl[i]].lazy,1) << ' ';\n\t// cout << endl;\n}\n\nvoid clear()\n{\n\tfor (int i = 0; i < v.size(); i++)\n\t\tvis[v[i]] = 0;\n\tv.clear();\n}\n\nint query(int x,int y)\n{\n\t// cout << '0' << ' ';\n\t// for (int i = 2; i <= n; i++)\n\t// \tcout << max(a[i] - T[bl[i]].lazy,1) << ' ';\n\t// cout << endl;\n\twhile (T[bl[x]].f[x - T[bl[x]].L] != T[bl[y]].f[y - T[bl[y]].L])\n\t{\n\t\tif (bl[x] < bl[y]) swap(x,y);\n\t\t// cout << x << ' ' << T[bl[x]].f[x - T[bl[x]].L] << endl;\n\t\tx = (T[bl[x]].f[x - T[bl[x]].L] == 1) ? 0 : max(a[T[bl[x]].f[x - T[bl[x]].L]] - T[bl[x]].lazy,1);\n\t}\n\tint qaq = (T[bl[x]].f[x - T[bl[x]].L] == 1) ? 0 : max(a[T[bl[x]].f[x - T[bl[x]].L]] - T[bl[x]].lazy,1);\n\twhile (x != qaq)\n\t{\n\t\tassert(x != qaq);\n\t\tvis[x] = 1;\n\t\tv.push_back(x);\n\t\tx = (x == 1) ? 0 : max(a[x] - T[bl[x]].lazy,1);\n\t}\n\twhile (y != qaq)\n\t{\n\t\tif (vis[y]) return clear(),y;\n\t\ty = (y == 1) ? 0 : max(a[y] - T[bl[y]].lazy,1);\n\t}\n}\n\nsigned main()\n{\n\tread(n,q);\n\tfor (int i = 2; i <= n; i++) read(a[i]);\n\tnum = (n - 1) / B + 1;\n\tfor (int i = 1; i <= num; i++)\n\t{\n\t\tT[i].L = (i - 1) * B + 1;\n\t\tT[i].R = min(i * B,n);\n\t\tT[i].cnt = i * B - (i - 1) * B;\n\t\tT[i].flag = T[i].lazy = 0;\n\t\tfor (int j = T[i].L; j <= T[i].R; j++)\n\t\t\tbl[j] = i;\n\t}\n\tfor (int i = 1; i <= num; i++)\n\t\tT[i].update();\n\twhile (q--)\n\t{\n\t\tint opt;\n\t\tread(opt);\n\t\tif (opt == 1)\n\t\t{\n\t\t\tint l,r,x;\n\t\t\tread(l,r,x);\n\t\t\tupdate(l,r,x);\n\t\t}\n\t\tif (opt == 2)\n\t\t{\n\t\t\tint u,v;\n\t\t\tread(u,v);\n\t\t\twriteln(query(u,v));\n\t\t}\n\t}\n\t// cerr << (double) clock() / CLOCKS_PER_SEC << endl;\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1491",
    "index": "I",
    "title": "Ruler Of The Zoo",
    "statement": "After realizing that Zookeeper is just a duck, the animals have overthrown Zookeeper. They now have to decide a new ruler among themselves through a fighting tournament of the following format:\n\nInitially, animal $0$ is king, while everyone else queues up with animal $1$ at the front of the queue and animal $n-1$ at the back. The animal at the front of the queue will challenge the king to a fight, and the animal with greater strength will win the fight. The winner will become king, while the loser joins the back of the queue.\n\nAn animal who \\textbf{wins $3$ times consecutively} will be crowned ruler for the whole zoo. The strength of each animal depends on how many consecutive fights he won. Animal $i$ has strength $A_i$ with $0$ consecutive win, $B_i$ with $1$ consecutive win, and $C_i$ with $2$ consecutive wins. Initially, everyone has $0$ consecutive win.\n\n\\textbf{For all animals, $A_i > B_i$ and $C_i > B_i$}. Also, the values of $A_i$, $B_i$, $C_i$ are \\textbf{distinct} (all $3n$ values are pairwise different).\n\nIn other words, an animal who is not a king has strength $A_i$. A king usually has a strength of $B_i$ or $C_i$. The exception is on the first turn, the first king (animal $0$) has strength $A_i$.\n\nWho is the new ruler, and after how many fights? Or will it end up that animals fight forever with no one ending up as ruler?",
    "tutorial": "As the solution to this problem is very long, the full editorial is split into $4$ parts. If you want to challenge yourself, you can try reading one part at a time and see if you get any inspiration. You can also try to read the specific hints for each part. Convert the queue into a circle. Firstly, let's convert the queue into a circle. In our new problem, $n$ animals stand in a circle. The king fights the animal directly clockwise to it. If the king wins, he and the other person swap places, otherwise nothing happens. The animal that is king will always move 1 space clockwise regardless of what happens. For example, in this scenario, 0 beats 1, so he stays as king. But he then loses to 2. Call animals whose A is smaller than the B of the animal before them RED color and the rest of the animals NONRED color. Work out the inequalities. How do the colors of animals change? Let's give each animal a color. An animal $i$ is RED if $B_{i-1}$ > $A_i$. In other words, and animal is red if and only if the previous animal will beat it as king. The animals that are not red are called NONRED for now. We can assume no two animals are consecutively RED* (*will elaborate more in part 4). Suppose we have 3 animals $XYZ$ in that order, and $Y$ is red while $X$ and $Z$ are non-red. Suppose $X$ becomes king and wins $Y$ but not $Z$. As such, the final arrangement is $YXZ$. The claim here is that $X$ and $Z$ cannot become RED. For $X$, $X$ beats $Y$, We have $B_X > A_Y$, but since $A_X > B_X$ and $A_Y > B_Y$, we get that $B_Y < A_X$. As such, $X$ cannot be RED. For $Z$, we have $C_X < A_Z$ (since X lost to Z) and $B_X < C_X$, we hence have $B_X < A_Z$. As such, $Z$ cannot be RED Finally for $Y$, it is possible that it turns from RED to NONRED. From these we can conclude that RED cannot be created, but can be destroyed. REDs can only be destroyed at most $O(n)$ times. Simulate a lot \"uneventful\" moves at once. Consider NONRED positions to be fixed, and the REDs rotate anti-clockwise about them. After $n-1$ moves, what do you observe? Do many sets of $n-1$ moves at once until a RED is destroyed or when the game ends. How to find when a RED is destroyed or when the game ends event occurs quickly? As such, we have the following conclusions: REDS are never created only destroyed The order of NONREDS will not change unless a RED inserts itself within the sequence REDS will never battle REDS (because of * assumption) Since the number of times REDS can be destroyed is limited, we should exploit that. We define an event as either when a RED is destroyed or when the game ends. Since events can occur at most $O(n)$ times, we just need to find some way to quickly simulate the moves until the next event. Let's visualize the moves like this: instead of the RED and NONRED swapping positions, the NONREDs are fixed in position, and the REDs move around anticlockwise. After $n-1$ moves, every RED moves one space anticlockwise around the belt of NONREDs Then in that case, we just need to check how many sets of $n-1$ moves is needed until the first event occurs. For convenience, let's split NONRED into BLUE and GREEN. If a NONRED beats a red in front of it, and it loses to next animal, then it is BLUE. If it wins one more time (and hence the entire game) it is GREEN. Let's look at the conditions for the events: A RED is destroyed. This occurs when $B_{nr} < A_{r}$ where $nr$ is any BLUE or GREEN The game ends. This occurs when $B_{g} > A_{r}$ where $g$ is any GREEN To find the first how many times the reds need to move anticlockwise, we could maintain a monotonic vector across the belt of NONREDs, and then for each RED, binary search the earliest position where an event occurs. Finally, when we find the number of sets of $n-1$ we need to move backwards, we move everything manually, check if the game ends. Then we recompute the color of all animals, and repeat. If no event occurs, then it will repeat infinitely. The step of finding the number of steps before first event occurs takes $O(nlogn)$ in total. Since REDs can disappear at most $O(n)$ times, then the total time complexity is $O(n^2logn)$. It's worth noting that the constant factor for this algorithm is small as the number of REDs is $0.5n$ and binary search is a very fast log. Hence, it passes quite comfortably (author's solution is under 400ms) even though $n \\leq 6000$. In terms of implementation, we can run the first $2n$ by brute force just to handle some bad corner cases. In particular, it is mostly to handle the assumption \"We can assume no two animals are consecutively RED\". If two animals are consecutively RED, then working out the inequalities will show that the one right before the two REDs should be able to win, and hence the game should end within $2n$ moves.",
    "code": "//雪花飄飄北風嘯嘯\n//天地一片蒼茫\n\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \" is \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define up upper_bound\n\n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nstruct dat{\n\tint a,b,c;\n\tint idx;\n};\n\nint n;\ndat head;\ndeque<dat> dq;\n\ndat state[6005];\ndat trans_belt[6005];\nbool green[6005];\n\nint curr;\nll moves=1;\n\nvoid brute(){\n\trep(x,0,1000000){\n\t\tif ((curr==0?head.a:(curr==1?head.b:head.c))>dq.front().a){\n\t\t\tdq.pub(dq.front());\n\t\t\tdq.pof();\n\t\t\tcurr++;\n\t\t\tif (curr==3){\n\t\t\t\tcout<<head.idx<<\" \"<<moves<<endl;\n\t\t\t\texit(0);\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tdq.pub(head);\n\t\t\thead=dq.front();\n\t\t\tdq.pof();\n\t\t\tcurr=1;\n\t\t}\n\t\t\n\t\tmoves++;\n\t\t\n\t\tif (x>n && curr==1) break;\n\t}\n}\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tcin>>n;\n\t\n\trep(x,0,n){\n\t\tint a,b,c;\n\t\tcin>>a>>b>>c;\n\t\t\n\t\tif (!x) head={a,b,c,x};\n\t\telse dq.pub({a,b,c,x});\n\t}\n\t\n\tcurr=0;\n\tbrute();\n\t\n\t//convert to state\n\tstate[0]=head;\n\trep(x,1,n) state[x]=dq[x-1];\n\t\n\twhile (true){\n\t\t//cout<<\"move: \"<<moves-1<<endl;\n\t\t//rep(x,0,n) cout<<state[x].idx<<\" \"; cout<<endl;\n\t\t\n\t\tvector<ii> stk;\n\t\t\n\t\t//find the first instance where state[z].b<state[x].a\n\t\t//maintain min stack of state[z].b\n\t\t\n\t\t//now, we focus on the belt itself\n\t\t//there is a case where the red does not convert to a anything but the game ends\n\t\t//we need to handle that case carefully!\n\t\t//i think lets just insert it into stack with value -1\n\t\t//then if it appears its easily handled\n\t\t\n\t\tmemset(green,false,sizeof(green));\n\t\t\n\t\tint cnt=0;\n\t\t\n\t\tint pidx=-1;\n\t\trep(x,0,n){\n\t\t\tif (x && state[x-1].b>state[x].a){ //red\n\t\t\t\t\n\t\t\t}\n\t\t\telse{ //not red\n\t\t\t\tif (pidx!=-1 && state[pidx].c>state[x].a){\n\t\t\t\t\tgreen[pidx]=true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tpidx=x;\n\t\t\t}\n\t\t}\n\t\tif (state[pidx].c>state[0].a) green[0]=true;\n\t\t\n\t\trep(x,0,n){\n\t\t\tif (x && state[x-1].b>state[x].a){ //red\n\t\t\t\t\n\t\t\t}\n\t\t\telse{ //not red\n\t\t\t\tint temp=green[x]?-1:state[x].b;\n\t\t\t\t\n\t\t\t\twhile (!stk.empty() && stk.back().fi>temp) stk.pob();\n\t\t\t\tstk.pub(ii(temp,cnt));\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tint best=1e9; //shortest distance until red becomes not red\n\t\tint cnt2=cnt;\n\t\t\n\t\t//cout<<\"non-reds: \"<<cnt<<endl;\n\t\t\n\t\trep(x,0,n){\n\t\t\tif (x && state[x-1].b>state[x].a){ //red\n\t\t\t\tif (stk.front().fi>state[x].a) continue; //it wont become red here\n\t\t\t\t\n\t\t\t\tint lo=0,hi=sz(stk),mi;\n\t\t\t\twhile (hi-lo>1){\n\t\t\t\t\tmi=hi+lo>>1;\n\t\t\t\t\tif (stk[mi].fi<state[x].a) lo=mi;\n\t\t\t\t\telse hi=mi;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//cout<<\"debug: \"<<x<<endl;\n\t\t\t\t//for (auto &it:stk) cout<<it.fi<<\"_\"<<it.se<<\" \"; cout<<endl;\n\t\t\t\t//cout<<state[x].a<<endl;\n\t\t\t\t\n\t\t\t\t//cout<<\"found: \"<<pos[stk[hi]]<<endl;\n\t\t\t\tint dist=cnt2-stk[lo].se;\n\t\t\t\t//cout<<dist<<endl;\n\t\t\t\tif (dist<best){\n\t\t\t\t\tbest=dist;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//cout<<endl;\n\t\t\t\t\n\t\t\t}\n\t\t\telse{ //not red\n\t\t\t\tint temp=green[x]?-1:state[x].b;\n\t\t\t\t\n\t\t\t\twhile (!stk.empty() && stk.back().fi>temp) stk.pob();\n\t\t\t\tstk.pub(ii(temp,cnt2));\n\t\t\t\tcnt2++;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//cout<<\"number in belt: \"<<cnt<<endl;\n\t\t//cout<<\"d: \"<<best<<\" \"<<idx<<endl;\n\t\t\n\t\tif (best==1e9){\n\t\t\tcout<<\"-1 -1\"<<endl;\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t//we simulate best-1 cycles for the reds\n\t\t\n\t\tbest--;\n\t\t\n\t\t//cout<<\"hmm: \"<<endl;\n\t\t//cout<<best<<\" \"<<cnt<<endl;\n\t\tif (best>=0){\n\t\t\tmoves+=best*(n-1);\n\t\t\t\n\t\t\t//cout<<endl;\n\t\t\tcnt2=0;\n\t\t\trep(x,0,n){\n\t\t\t\tif (x && state[x-1].b>state[x].a){ //red\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse{ //not red\n\t\t\t\t\ttrans_belt[cnt2]=state[x];\n\t\t\t\t\tcnt2++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//rep(x,0,cnt2) cout<<trans_belt[x].idx<<\" \"; cout<<endl;\n\t\t\t\n\t\t\trep(x,n,0){\n\t\t\t\tif (x && state[x-1].b>state[x].a){ //red\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse{ //not red\n\t\t\t\t\tcnt2--;\n\t\t\t\t\t//cout<<x<<\" \"<<(cnt2-best+cnt)%cnt<<endl;\n\t\t\t\t\tstate[x]=trans_belt[(cnt2-best+cnt)%cnt];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//cout<<cnt<<endl;\n\t\t//cout<<\"move: \"<<moves-1<<endl;\n\t\t//rep(x,0,n) cout<<state[x].idx<<\" \"; cout<<endl;\n\t\t\n\t\thead=state[0];\n\t\tdq.clear();\n\t\trep(x,1,n) dq.pub(state[x]);\n\t\t\n\t\tcurr=1;\n\t\tbrute();\n\t\t\n\t\t//convert to state\n\t\tstate[0]=head;\n\t\trep(x,1,n) state[x]=dq[x-1];\n\t\t\n\t\t//cout<<\"move: \"<<moves-1<<endl;\n\t\t//rep(x,0,n) cout<<state[x].idx<<\" \"; cout<<endl;\n\t\t//cout<<endl;\n\t\t\n\t\t//break;\n\t}\n}",
    "tags": [
      "brute force",
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1492",
    "index": "A",
    "title": "Three swimmers",
    "statement": "Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.\n\nIt takes the first swimmer exactly $a$ minutes to swim across the entire pool and come back, exactly $b$ minutes for the second swimmer and $c$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $0$, $a$, $2a$, $3a$, ... minutes after the start time, the second one will be at $0$, $b$, $2b$, $3b$, ... minutes, and the third one will be on the left side of the pool after $0$, $c$, $2c$, $3c$, ... minutes.\n\nYou came to the left side of the pool exactly $p$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.",
    "tutorial": "The answer is just $\\min{(\\lceil {p \\over a} \\rceil \\cdot a, \\lceil {p \\over b} \\rceil \\cdot b, \\lceil {p \\over c} \\rceil \\cdot c)} - p$. Complexity: $O(1)$.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1492",
    "index": "B",
    "title": "Card Deck",
    "statement": "You have a deck of $n$ cards, and you'd like to reorder it to a new one.\n\nEach card has a value between $1$ and $n$ equal to $p_i$. All $p_i$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $p_1$ stands for the bottom card, $p_n$ is the top card.\n\nIn each step you pick some integer $k > 0$, take the top $k$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)\n\nLet's define an order of a deck as $\\sum\\limits_{i = 1}^{n}{n^{n - i} \\cdot p_i}$.\n\nGiven the original deck, output the deck with maximum possible order you can make using the operation above.",
    "tutorial": "It's easy to prove that order of a deck differs for different permutations. And more than that order of permutation $a$ is greater than order of permutation $b$ if and only if $a$ is lexicographically greater than $b$. Since we need to build a lexicographic maximum permutation, at each point of time we need to choose such $k$ that $k$-th element from the top of the original deck is the maximum element in this deck. Total complexity is $O(n \\log n)$ or $O(n)$ (depending on the implementation).",
    "tags": [
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1492",
    "index": "C",
    "title": "Maximum width",
    "statement": "Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $s$ of length $n$ and $t$ of length $m$.\n\nA sequence $p_1, p_2, \\ldots, p_m$, where $1 \\leq p_1 < p_2 < \\ldots < p_m \\leq n$, is called beautiful, if $s_{p_i} = t_i$ for all $i$ from $1$ to $m$. The width of a sequence is defined as $\\max\\limits_{1 \\le i < m} \\left(p_{i + 1} - p_i\\right)$.\n\nPlease help your classmate to identify the beautiful sequence with the \\textbf{maximum width}. Your classmate promised you that for the given strings $s$ and $t$ there is at least one beautiful sequence.",
    "tutorial": "For some subsequence of the string $s$, let $p_i$ denote the position of the character $t_i$ in the string $s$. For fixed $i$, we can find a subsequence that maximizes $p_{i + 1} - p_i$. Let $\\textit{left}_{i}$ and $\\textit{right}_{i}$ be the minimum and maximum possible value of $p_i$ among all valid $p$s. Now, it is easy to see that the maximum possible value of $p_{i+1} - p_{i}$ is equal to $\\textit{right}_{i + 1} - \\textit{left}_{i}$. To calculate $\\textit{left}_i$ we just need to find the first element after $\\textit{left}_{i - 1}$ which is equal to $t_i$. This can be done by a simple greedy or dp algorithm. $\\textit{right}_i$ can be found in the same way. So, after finding $\\textit{left}$ and $\\textit{right}$, the answer is $\\max_{i=1}^{i=n-1} \\textit{right}_{i + 1} - \\textit{left}_i$. Complexity: $O(n + m)$.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1492",
    "index": "D",
    "title": "Genius's Gambit",
    "statement": "You are given three integers $a$, $b$, $k$.\n\nFind two binary integers $x$ and $y$ ($x \\ge y$) such that\n\n- both $x$ and $y$ consist of $a$ zeroes and $b$ ones;\n- $x - y$ (also written in binary form) has exactly $k$ ones.\n\nYou are \\textbf{not allowed to use leading zeros for $x$ and $y$}.",
    "tutorial": "This problem has a cute constructive solution. If $a = 0$ or $b = 1$ the answer is trivial. In other cases let's fix $x$ as a number in form $111 \\ldots 1100 \\ldots 000$. Let $y = x$, then we will change only $y$. Let's take the last $1$ digit from the consecutive prefix of ones, then move it $\\min(k, a)$ positions to the right. It is easy to see, that the number of ones in $x - y$ has increased by $\\min(k, a)$. If $k \\leq a$ we already have the answer. If not, let's take the last $1$ digit from the consecutive prefix of ones and move it one position to the right. The number of ones in the answer increased by one and if it is less than $k$, we just repeat this move. With this construction we can easily build an answer for every $k \\leq a + b - 2$ It's not difficult to prove that the answer does not exist when $k > a + b - 2$.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1492",
    "index": "E",
    "title": "Almost Fault-Tolerant Database",
    "statement": "You are storing an integer array of length $m$ in a database. To maintain internal integrity and protect data, the database stores $n$ copies of this array.\n\nUnfortunately, the recent incident may have altered the stored information in every copy in the database.\n\nIt's believed, that the incident altered at most two elements in every copy. You need to recover the original array based on the current state of the database.\n\nIn case there are multiple ways to restore the array, report any. If there is no array that differs from every copy in no more than two positions, report that as well.",
    "tutorial": "Let's look at the first array. Every possible answer (if there is any) should not differ from this array in more than $2$ positions. So we should try to change at most $2$ positions in the first array to find a consistent answer. Let's look at the other arrays. We can ignore each other array that differ with the first array in no more than $2$ positions. In particular, if every array doesn't differ in more than $2$ position, we can just print the first array as an answer. If an array differs in $5$ (or more) positions, then no answer exists. Suppose that we selected an array with $3$ or $4$ diffs. This means that we must change $1$ or $2$ positions (respectively) in the first array to reduce it to $2$ diffs. We have $3$ or $6$ ways to do this (respectively), and can go through all the options. After changing, we should look at all arrays again and make changes in the first array again if required (but no more than in $2$ positions in total) in a recursive backtracking manner. If we don't get an answer, we should go back and try another option. The time complexity is $O(n \\cdot m)$ with a decent constant. Bonus1: If allowed number of diffs is $k$, can you solve problem in $O(k^knm)$ time? Bonus2: If allowed number of diffs is $k$, can you solve problem in $O(nm + k^k \\sqrt{nm})$ time?",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1493",
    "index": "A",
    "title": "Anti-knapsack",
    "statement": "You are given two integers $n$ and $k$. You are asked to choose maximum number of distinct integers from $1$ to $n$ so that there is no subset of chosen numbers with sum equal to $k$.\n\nA subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.",
    "tutorial": "Let's notice that we can take all numbers $k+1, k+2 \\ldots n$, because every one of them is greater than $k$, and sum of any number from $k+1, k+2 \\ldots n$ and any number from $1,2 \\ldots n$ also is greater than $k$. Let's also take numbers from $\\left \\lceil \\frac{k}{2} \\right \\rceil$ to $k - 1$ inclusive. Notice that the sum of any two chosen numbers is already greater than $k$, and no chosen number is equal to $k$, therefore such set is correct. It contains $(n - k) + (k -\\left \\lceil \\frac{k}{2} \\right \\rceil) = n - \\left \\lceil \\frac{k}{2} \\right \\rceil$ numbers. Let's show why such size of a set is the maximal possible. Numbers from $k+1$ to $n$ won't give subsets with sum $k$ with any other numbers, so we can take them to the answer: their amount is $n - k$. The number $k$ can't be taken to the answer, because if we take a subset consisting from that number only, the sum in it will be $k$. Let's consider numbers from $1$ to $k-1$. They can be divided into $\\left \\lfloor \\frac{k}{2} \\right \\rfloor$ pairs, in each of which the sum of numbers will be $k$ ($1$ and $k-1$, $2$ and $k-2$ etc.; if $k$ is even, then the pair with number $\\frac{k}{2}$ will consist of one number). If we took at least $\\left \\lfloor \\frac{k}{2} \\right \\rfloor + 1$ numbers from $1$ to $k-1$, then at least two chosen numbers will be in one pair, and their sum will be equal to $k$, what contradicts with problem condition. It means that we can take not more than $\\left \\lfloor \\frac{k}{2} \\right \\rfloor$ numbers from $1$ to $k-1$. Then the total size of the set will not exceed $(n - k) + \\left \\lfloor \\frac{k}{2} \\right \\rfloor$. As known, $k$ = $\\left \\lfloor \\frac{k}{2} \\right \\rfloor + \\left \\lceil \\frac{k}{2} \\right \\rceil$ (you can prove that fact by considering two cases: when $k$ is even, and when $k$ is odd). Let's replace $k$ in recieved estimation: $n - (\\left \\lfloor \\frac{k}{2} \\right \\rfloor + \\left \\lceil \\frac{k}{2} \\right \\rceil) + \\left \\lfloor \\frac{k}{2} \\right \\rfloor=n - \\left \\lceil \\frac{k}{2} \\right \\rceil$, which is the size of mentioned set, therefore mentioned set is the answer to the problem.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    int t, n, k;\n    cin >> t;\n    while (t--) {\n        cin >> n >> k;\n        cout << n - k + k / 2 << '\\n';\n        for (int i = k + 1; i <= n; ++i) cout << i << \" \";\n        for (int i = (k + 1) / 2; i < k; ++i) cout << i << \" \";\n        cout << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1493",
    "index": "B",
    "title": "Planet Lapituletti",
    "statement": "The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $h$ hours and each hour lasts $m$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $0$ to $h-1$ and minutes are numbered from $0$ to $m-1$.\n\n\\begin{center}\nThat's how the digits are displayed on the clock. Please note that digit $1$ is placed in the \\textbf{middle} of its position.\n\\end{center}\n\nA standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).\n\nThe image of the clocks in the mirror is reflected against a vertical axis.\n\n\\begin{center}\nThe reflection is not a valid time.\n\nThe reflection is a valid time with $h=24$, $m = 60$. However, for example, if $h=10$, $m=60$, then the reflection is not a valid time.\n\\end{center}\n\nAn inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $s$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.\n\nIt can be shown that with any $h$, $m$, $s$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.\n\nYou are asked to solve the problem for several test cases.",
    "tutorial": "In order to solve the problem, you need to look over all the moments of time after the given one and check if the reflected time is correct in that moment of time. If such moment of time does not exist on the current day, the moment $00:00$ of the next day is always correct. For realization you need to notice that digits $0$, $1$, $8$ transform into themselves after reflection, $2$ transforms into $5$, $5$ transforms into $2$, and other digits ($3$, $4$, $6$, $7$, $9$) transform into incorrect digits after reflection.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector < int > go = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1};\nint inf = 1e9 + 7;\n\nint get(int x) {\n    string s = to_string(x);\n    if ((int)s.size() == 1) s = \"0\" + s;\n    string answ = \"\";\n    for (int i = 1; i >= 0; --i) {\n        if (go[s[i] - '0'] == -1) return inf;\n        answ += char(go[s[i] - '0'] + '0');\n    }\n    return stoi(answ);\n}\n\nstring good(int x) {\n    string ans = to_string(x);\n    if (x < 10) {\n        ans = \"0\" + ans;\n    }\n    return ans;\n}\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t, h, m, H, M;\n    cin >> t;\n    string s;\n    while (t--) {\n        cin >> h >> m;\n        cin >> s;\n        H = (s[0] - '0') * 10 + s[1] - '0';\n        M = (s[3] - '0') * 10 + s[4] - '0';\n        while (1) {\n            if (M == m) {\n                H++, M = 0;\n            }\n            if (H == h) {\n                H = 0;\n            }\n            if (get(M) < h && get(H) < m) {\n                cout << good(H) << \":\" << good(M) << '\\n';\n                break;\n            }\n            M++;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1493",
    "index": "C",
    "title": "K-beautiful Strings",
    "statement": "You are given a string $s$ consisting of lowercase English letters and a number $k$. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by $k$. You are asked to find the lexicographically smallest beautiful string of length $n$, which is lexicographically greater or equal to string $s$. If such a string does not exist, output $-1$.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "First of all, let's notice that if the length of the string $n$ is not divisible by $k$, no beautiful string of such length exists. Otherwise the answer to the problem always exists (because the string $zz \\ldots z$ is the greatest string of length $n$ and is beautiful). If the string $s$ is beautiful, then $s$ itself is the answer. Otherwise, let's iterate over all the options of the maximal common prefix of the answer string and $s$, that way we will iterate from $n-1$ to $0$. Let's maintain an array $cnt_i$ - how many times does the $i$-th leter of English alphabet occur in the prefix we have fixed. We can recalculate that array totally in $0(n)$, because when we iterate to the smaller prefix we only need to change one value of $cnt$. Denote the length of common prefix as $pref$. Let's iterate over all possible letters at position $pref+1$ (numeration starts from one) in increasing order. We need to iterate over all letters that are strictly greater than $s_{pref+1}$, because otherwise either the answer will be less than $s$ or the length of common prefix won't be equal to $pref$. Now we need to learn how to check quickly if we can pick any suffix so that we will get a beautiful string. To do that you need to go through the array $cnt$ and to calculate for each letter which miminal number of times we need to write it more in order to get the amount of occurences divisible by $k$. For $i$-th leter it is $(k-cnt_i$ $\\%$ $k)$ $\\%$ $k$. Let $sum$ be the sum of such value over all $i$. If $sum$ isn't greater than the length of the suffix, then what's left is to find the minimal suffix. How to build the minimal suffix: let's denote the length of unknown suffix as $suff$ ($suff=n-pref-1$). We know that $sum \\le suff$. If $sum < suff$, then let's increase the amount of occurences of $a$ on suffix by $suff-sum$. Now we will place all letters $a$, then all letters $b$ and so on to $z$. A detail of realization: we will consider iterated letter at position $pref+1$ in the array $cnt$. We can maintain array $cnt$ on prefix of length $pref+1$ and take into account that $pref+1$-st symbol is the iterated symbol and not the symbol of string $s$. The complexity of solution is $O(n \\cdot C)$, where $C$ is the size of the alphabet ($26$). You can also write a solution in $O(n)$, by maintaining the sum $(k-cnt_i$ $\\%$ $k)$ $\\%$ $k$ in a variable.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint cnt[26];\n\nint get(int x, int k) {\n    return (k - x % k) % k;\n}\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n, k, t;\n    cin >> t;\n    while (t--) {\n        cin >> n >> k;\n        string s;\n        cin >> s;\n        for (int j = 0; j < 26; ++j) cnt[j] = 0;\n        for (auto c : s) cnt[c - 'a']++;\n\n        int sum = 0, flag = 1;\n        for (int i = 0; i < 26; ++i) {\n            sum += get(cnt[i], k);\n        }\n\n        if (sum == 0) {\n            cout << s << '\\n';\n            flag = 0;\n        }\n\n        if (n % k != 0) {\n            cout << -1 << '\\n';\n            continue;\n        }\n\n        for (int i = n - 1; i >= 0 && flag; --i) {\n            sum -= get(cnt[s[i] - 'a'], k);\n            cnt[s[i] - 'a']--;\n            sum += get(cnt[s[i] - 'a'], k);\n            for (int j = s[i] - 'a' + 1; j < 26; ++j) {\n\n                int lst_sum = sum;\n                sum -= get(cnt[j], k);\n                cnt[j]++;\n                sum += get(cnt[j], k);\n\n                if (i + sum + 1 <= n) {\n                    for (int pos = 0; pos < i; ++pos) {\n                        cout << s[pos];\n                    }\n                    cout << char('a' + j);\n\n                    string add = \"\";\n                    for (int w = 0; w < 26; ++w) {\n                        int f = get(cnt[w], k);\n                        while (f) {\n                            f--;\n                            add += char('a' + w);\n                        }\n                    }\n                    while ((int)add.size() + i + 1 < n) {\n                        add += \"a\";\n                    }\n\n                    sort(add.begin(), add.end());\n                    cout << add << '\\n';\n                    flag = 0;\n                    break;\n                }\n\n                cnt[j]--;\n                sum = lst_sum;\n            }\n        }\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1493",
    "index": "D",
    "title": "GCD of an Array",
    "statement": "You are given an array $a$ of length $n$. You are asked to process $q$ queries of the following format: given integers $i$ and $x$, multiply $a_i$ by $x$.\n\nAfter processing each query you need to output the greatest common divisor (GCD) of all elements of the array $a$.\n\nSince the answer can be too large, you are asked to output it modulo $10^9+7$.",
    "tutorial": "Notice that after each query the answer doesn't become smaller and we can solve the problem for each prime divisor independently. For each number let's maintain an amount of occurences for all its prime divisors (you can implement it using $map$). For each prime divisor let's write to its corresponding $multiset$ the amount of times it is met in every of the numbers of the array, at the same time we won't add null values. Initially, $ans=1$. Let's understand the way a prime divisor $p$ is included in the answer. If the size of its $multiset$ is not equal to $n$, then $ans$ won't change, otherwise $ans=(ans \\cdot p^x)$ $\\%$ $mod$, where $x$ is a minimal number of $multiset$. Since $ans$ is not decreasing, then we can avoid calculating it all over again every time and instead recalculate it only for divisors that are being changed (with that, because the minimal number of $multiset$ is not decreasing as well, we can just increase the answer using multiplication). To process the query, we need to find the prime factorization of $x$ (for example, using the Sieve of Eratosthenes) and add the prime divisors to the $map$ for $i$-th element (and correspondingly change the $multiset$ for that divisor). Each query is processed in the complexity of the amount of prime divisors multiplied by the time of $map$ and $multiset$ operation, i.e. $log$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint const maxn = 2e5 + 5, max_val = 2e5 + 5;\nll mod = 1e9 + 7, ans = 1;\nint nxt[max_val], n;\nmultiset <int> cnt[max_val];\nmap <int, int> cnt_divisor[maxn];\n\nvoid add(int i, int x) {\n    while (x != 1) {\n        int div = nxt[x], add = 0;\n        while (nxt[x] == div) add++, x = x / nxt[x];\n\n        int lst = cnt_divisor[i][div];\n        cnt_divisor[i][div] += add;\n        int lst_min = 0;\n        if ((int)cnt[div].size() == n) {\n            lst_min = (*cnt[div].begin());\n        }\n        if (lst != 0) {\n            cnt[div].erase(cnt[div].find(lst));\n        }\n        cnt[div].insert(lst + add);\n        if ((int)cnt[div].size() == n) {\n            for (int j = lst_min + 1; j <= (*cnt[div].begin()); ++j) {\n                ans = ans * (ll)div % mod;\n            }\n        }\n    }\n}\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    int q, l, x;\n    cin >> n >> q;\n\n    for (int i = 2; i < maxn; ++i) {\n        if (nxt[i] == 0) {\n            nxt[i] = i;\n            if (i > 10000) continue;\n            for (int j = i * i; j < maxn; j += i) {\n                if (nxt[j] == 0) nxt[j] = i;\n            }\n        }\n    }\n\n    for (int i = 1; i <= n; ++i) {\n        cin >> x;\n        add(i, x);\n    }\n\n    for (int i = 1; i <= q; ++i) {\n        cin >> l >> x;\n        add(l, x);\n        cout << ans << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "hashing",
      "implementation",
      "math",
      "number theory",
      "sortings",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1493",
    "index": "E",
    "title": "Enormous XOR",
    "statement": "You are given two integers $l$ and $r$ in binary representation. Let $g(x, y)$ be equal to the bitwise XOR of all integers from $x$ to $y$ inclusive (that is $x \\oplus (x+1) \\oplus \\dots \\oplus (y-1) \\oplus y$). Let's define $f(l, r)$ as the maximum of all values of $g(x, y)$ satisfying $l \\le x \\le y \\le r$.\n\nOutput $f(l, r)$.",
    "tutorial": "Let's numerate bits from $0$ to $n-1$ from the least significant bit to the most significant (from the end of the representation). If $n-1$-st bits of numbers $l$ and $r$ differ, then there is a power transition between numbers $l$ and $r$, and the answer to the problem is $11 \\ldots 1$ (the number contains $n$ ones). Otherwise it can be shown that if $0$ bit of the number $r$ is equal to $1$, then the answer is $r$ itself. If $0$ bit of the number $r$ is equal to $0$ and $l <= r - 2$, the answer is $r+1$, otherwise the answer is $r$. Proof. Firstly, if there is a power transition between $l$ and $r$, then we can take a segment [$11 \\ldots 1$; $100 \\ldots 0$] ($n-1$ ones; $1$ and $n - 1$ zero), and get $\\operatorname{xor}$ on it of $n$ ones. It is not hard to show that it will be the maximal possible. Let's prove that for odd $r$ without power transition the answer is $r$. That answer can be reached if we take a segment consisting of one number $r$. Let's prove that the answer if maximal using induction. Base: for segments $[r; r]$, $[r-1;r]$, $r$ is odd, the answer is $r$ (in the first case there is no other segments, in the second case subsegments $[r-1;r-1]$ and $[r-1;r]$ have less $\\operatorname{xor}$-s). Let's take induction step from $[l;r]$ to $[l;r+2]$. The answer on segment $[r+1;r+2]$ is obviously $r+2$, remaining subsegments can be split into three groups: with right bound $r+2$, with right bound $r+1$, and lying inside the segment $[l; r]$, with that all the left bounds of the subsegments are lying inside $[l;r]$. The answer on the segments of third group is $r$ (proved by induction). The segments of the first group contain subsegment $[r+1;r+2]$, which has $\\operatorname{xor}$ equal to $1$, and some segment ending at $r$. Notice that that way we can increase the answer of the segment $[l;r]$ not more by $1$, i.e. the answer for the segments of the first group is not greater than $r+1$. Now let's consider the segments of the second group. Suppose that we could find the segment from that group with $\\operatorname{xor}$ on it greater than $r+2$. Then some bit which was $0$ in $r+2$, became $1$ in that $\\operatorname{xor}$, with that it is not the $0$ bit (since $r+2$ is odd). Let's find the amount of numbers from $r+1$ (inclusively) to the nearest having $1$ in that bit (non-inclusively). It is not hard to show that that amount is odd (from even to zero inclusively). In order to make the bit $1$, we need to take an odd amount of numbers with $1$ in that bit. Since the blocks (among consecutive numbers blocks with $0$ in that bit and blocks with $1$ in that bit) have even length ($2$, $4$, $8$ and so on), we need to take an odd amount of numbers in total to take an odd amount of numbers with $1$ in that bit. Then the whole segment will contain odd $+$ odd $=$ even amount of numbers (the first summand is the amount of numbers from $r$ to the nearest having $1$ in that bit, the second summand is the amount of numbers we will take to make that bit equal to $1$), but then the most significant ($(n-1)$-st) bit will become equal to $0$, therefore we will get $\\operatorname{xor}$ less than $r+2$. It means that among segments of the second group there is no segment with $\\operatorname{xor}$ greater than $r+2$ as well. So, $r+2$ is the answer for $[l; r+2]$. Now let's consider even right bounds. If the length of the segment is less than $2$ ($l > r - 2$), then it is simple to show that the right bound will be the answer. Otherwise $r+1$ is the answer. It can be reached on the segment $[r-2;r]$ and is the maximal possible, because we can increase the right bound of the segment by $1$ (it will become odd), with that the answer surely won't decrease, and the answer on $[l;r+1]$ is proven to be $r+1$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nstring add(string s) {\n    int i = (int)s.size() - 1;\n    while (s[i] == '1') {\n        s[i] = '0';\n        i--;\n    }\n    s[i] = '1';\n    return s;\n}\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n;\n    cin >> n;\n    string l, r;\n    cin >> l >> r;\n    if (l == r) {\n        cout << r << '\\n';\n        return 0;\n    }\n    if (l[0] != r[0]) {\n        for (int i = 1; i <= n; ++i) cout << \"1\";\n        return 0;\n    }\n    if (add(l) == r || r.back() == '1') {\n        cout << r << '\\n';\n        return 0;\n    }\n    cout << add(r) << '\\n';\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "math",
      "strings",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1493",
    "index": "F",
    "title": "Enchanted Matrix",
    "statement": "This is an interactive problem.\n\nThere exists a matrix $a$ of size $n \\times m$ ($n$ rows and $m$ columns), you know only numbers $n$ and $m$. The rows of the matrix are numbered from $1$ to $n$ from top to bottom, and columns of the matrix are numbered from $1$ to $m$ from left to right. The cell on the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$.\n\nYou are asked to find the number of pairs $(r, c)$ ($1 \\le r \\le n$, $1 \\le c \\le m$, $r$ is a divisor of $n$, $c$ is a divisor of $m$) such that if we split the matrix into rectangles of size $r \\times c$ (of height $r$ rows and of width $c$ columns, each cell belongs to exactly one rectangle), all those rectangles are pairwise equal.\n\nYou can use queries of the following type:\n\n- ? $h$ $w$ $i_1$ $j_1$ $i_2$ $j_2$ ($1 \\le h \\le n$, $1 \\le w \\le m$, $1 \\le i_1, i_2 \\le n$, $1 \\le j_1, j_2 \\le m$) — to check if \\textbf{non-overlapping} subrectangles of height $h$ rows and of width $w$ columns of matrix $a$ are equal or not. The upper left corner of the first rectangle is $(i_1, j_1)$. The upper left corner of the second rectangle is $(i_2, j_2)$. Subrectangles overlap, if they have at least one mutual cell. If the subrectangles in your query have incorrect coordinates (for example, they go beyond the boundaries of the matrix) or overlap, your solution will be considered incorrect.\n\nYou can use at most $ 3 \\cdot \\left \\lfloor{ \\log_2{(n+m)} } \\right \\rfloor$ queries. All elements of the matrix $a$ are fixed before the start of your program and do not depend on your queries.",
    "tutorial": "Te problem can be solved in various ways but the main idea is that if we want to check, if the $x$ consecutive blocks are equal to each other, then we can do it using $\\left \\lceil \\log_2 x \\right \\rceil$ queries. Let's suppose we want to check the equality of $x$ blocks, then we will check if the first and second $\\left \\lfloor \\frac {x} {2} \\right \\rfloor$ blocks are equal. If they are not equal, then $x$ blocks are not equal to each other, otherwise we need to check if the last $\\left \\lceil \\frac {x} {2} \\right \\rceil$ blocks are equal. Notice that the problem can be solved independently for rows and columns. Let's solve the problem for $n$ rows and let's find all $r$ such that the matrix can be split into equal rectangles of $r$ rows. If $r$ is the answer, then the numbers that are divisible by $r$ are also the answers. If $r$ is not the answer, then all divisors of $r$ are not the answers. If $r1$ and $r2$ are the answers, then $\\operatorname{gcd}(r1, r2)$ is the answer as well. Let's make a dynamic $dp_r$. If $dp_r = 1$, then the matrix can be divided into $r$ rows, otherwise $dp_r = 0$ and the matrix cannot be divided that way. We will iterate over $r$ in descending order. Let's suppose we want to calculate $dp_r$. Then we know for sure that for every $x$ that are divisors of $n$ and are divisible by $r$, $dp_x=1$ (because otherwise $dp_r=0$ and we don't have to calculate it). Let's find such minimal $x$ and check the equality of $\\frac{x}{r}$ blocks using the idea described in the beginning of the editorial. Let's calculate the sum of $dp_r$ - that is the amount of suitable $r$. Then we will solve the problem similarly for columns and output the product of suitable $r$ and suitable $c$. It is guaranteed that with any initial field the described solution will ask less than $3 \\cdot \\left \\lfloor{ \\log_2{(n+m)} } \\right \\rfloor$ queries. An accurate estimation of number of queries will be shown later. An accurate eastimation of number of queries: let us have the least $r$ such that we can split the matrix into $r$ rows (in order to get equal subrectangles) and all remaining $r$ are divided by it. Using that dynamic we maintain a minimal suitable $r$, and after that we try to decrease it using the algorithm from the editorial. The worst case is when we divide current minimal $r$ by $3$ with $2$ queries. Then we need $2 \\cdot \\log_3 n$ queries, which is equal to $\\log_3 4 \\cdot \\log_2 n$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint const maxn = 1005;\nint dp[maxn];\nvector < vector < int > > T;\n\nint ask(int lx1, int ly1, int rx1, int ry1, int lx2, int ly2, int rx2, int ry2) {\n    cout << \"? \" << rx1 - lx1 + 1 << \" \" << ry1 - ly1 + 1 << \" \" << lx1 << \" \" << ly1\n    << \" \" << lx2 << \" \" << ly2 << endl;\n    int ans;\n    cin >> ans;\n    return ans;\n}\n\nint good(int l, int r) {\n    if (l == r) return 1;\n\n    int cnt = (r - l + 1) / 2;\n    if (ask(T[l][0], T[l][1], T[l + cnt - 1][2], T[l + cnt - 1][3], T[l + cnt][0], T[l + cnt][1], T[l + 2 * cnt - 1][2], T[l + 2 * cnt - 1][3])) {\n        return good(l + cnt, r);\n    }\n    return 0;\n}\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n, m, cntn = 0, cntm = 0;\n    cin >> n >> m;\n\n    for (int i = n; i >= 1; --i) {\n        if (n % i != 0 || dp[i] != 0) continue;\n\n        for (int j = 2 * i; j <= n; j += i) {\n            if (n % j == 0 && j % i == 0) {\n                T = {};\n                for (int k = 1; k <= j / i; ++k) {\n                    T.push_back({(k - 1) * i + 1, 1, k * i, m});\n                }\n                if (good(0, (int)T.size() - 1)) dp[i] = 1;\n                else dp[i] = 2;\n                break;\n            }\n        }\n\n        if (dp[i] == 2) {\n            for (int j = 1; j <= n; ++j) {\n                if (i % j == 0) dp[j] = 2;\n            }\n        }\n        else {\n            dp[i] = 1;\n            for (int j = i; j <= n; ++j) {\n                if (dp[j] == 1) {\n                    int w = __gcd(i, j);\n                    for (int pos = w; pos <= n; pos += w) {\n                        dp[pos] = 1;\n                    }\n                }\n            }\n        }\n    }\n\n    for (int i = 1; i <= n; ++i) {\n        if (n % i == 0) cntn += (dp[i] == 1);\n        dp[i] = 0;\n    }\n\n    for (int i = m; i >= 1; --i) {\n        if (m % i != 0 || dp[i] != 0) continue;\n\n        for (int j = 2 * i; j <= m; j += i) {\n            if (m % j == 0 && j % i == 0) {\n                T = {};\n                for (int k = 1; k <= j / i; ++k) {\n                    T.push_back({1, (k - 1) * i + 1, n, k * i});\n                }\n                if (good(0, (int)T.size() - 1)) dp[i] = 1;\n                else dp[i] = 2;\n                break;\n            }\n        }\n        if (dp[i] == 2) {\n            for (int j = 1; j <= i; ++j) {\n                if (i % j == 0) {\n                    dp[j] = 2;\n                }\n            }\n        }\n        else {\n            dp[i] = 1;\n            for (int j = i; j <= m; ++j) {\n                if (dp[j] == 1) {\n                    int w = __gcd(i, j);\n                    for (int pos = w; pos <= m; pos += w) {\n                        dp[pos] = 1;\n                    }\n                }\n            }\n        }\n    }\n\n    for (int i = 1; i <= m; ++i) {\n        if (m % i == 0) cntm += (dp[i] == 1);\n    }\n    cout << \"! \" << cntn * cntm << endl;\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "interactive",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1494",
    "index": "A",
    "title": "ABC String",
    "statement": "You are given a string $a$, consisting of $n$ characters, $n$ is even. For each $i$ from $1$ to $n$ $a_i$ is one of 'A', 'B' or 'C'.\n\nA bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\"), and \")(\", \"(\" and \")\" are not.\n\nYou want to find a string $b$ that consists of $n$ characters such that:\n\n- $b$ is a regular bracket sequence;\n- if for some $i$ and $j$ ($1 \\le i, j \\le n$) $a_i=a_j$, then $b_i=b_j$.\n\nIn other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.\n\nYour task is to determine if such a string $b$ exists.",
    "tutorial": "There are two key observations. First, a regular bracket sequence always starts with an opening bracket and ends with a closing one. Thus, the first letter of $a$ corresponds to an opening bracket and the last letter corresponds to a closing bracket. If they are the same, then the answer is \"NO\". Second, a regular bracket sequence has exactly $\\frac n 2$ opening and $\\frac n 2$ closing brackets. Thus, we can check if the counts of the remaining letter and the first letter of the string or the remaining letter and the last letter of the string make it $\\frac n 2$ in total. If neither of them do, then the answer is \"NO\". If both do, then that means that there are $0$ occurrences of the remaining letter, so it doesn't matter what bracket it is assigned to. Finally, after the assignment is complete, check if the resulting string is a regular bracket sequence. For that you have to check if on any prefix the number of opening brackets is greater or equal to the number of closing brackets. And also if the total number of opening and closing brackets is the same. Overall complexity: $O(n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool solve() {\n  string s;\n  cin >> s;\n  vector<int> d(3);\n  int x = s[0] - 'A';\n  int y = s.back() - 'A';\n  if (x == y)\n    return false;\n  d[x] = 1; d[y] = -1;\n  if (count(s.begin(), s.end(), 'A' + x) == s.length() / 2)\n    d[3 ^ x ^ y] = -1;\n  else\n    d[3 ^ x ^ y] = 1;\n  int bal = 0;\n  for (char c : s) {\n    bal += d[c - 'A'];\n    if (bal < 0) return false;\n  }\n  return bal == 0;\n}\n\nint main() {\n  int t; cin >> t;\n  while (t--) {\n    cout << (solve() ? \"YES\\n\" : \"NO\\n\");\n  }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1494",
    "index": "B",
    "title": "Berland Crossword",
    "statement": "Berland crossword is a puzzle that is solved on a square grid with $n$ rows and $n$ columns. Initially all the cells are white.\n\nTo solve the puzzle one has to color some cells on the border of the grid black in such a way that:\n\n- exactly $U$ cells in the top row are black;\n- exactly $R$ cells in the rightmost column are black;\n- exactly $D$ cells in the bottom row are black;\n- exactly $L$ cells in the leftmost column are black.\n\nNote that you can color zero cells black and leave every cell white.\n\nYour task is to check if there exists a solution to the given puzzle.",
    "tutorial": "Consider some corner of the picture. If it's colored black, then it contributes to counts to both of the adjacent sides. Otherwise, it contributes to none. All the remaining cells can contribute only to the side they are on. There are $n-2$ of such cells on each side. So let's try all $2^4$ options of coloring the corners. After fixing the colors of the corners, we can calculate the number of cells that have to be colored on each side. That is calculated by taking the initial requirement and subtracting the adjacent colored corners from it. If any of the numbers is below $0$ or above $n-2$ then that corner coloring doesn't work. Otherwise, you can always color the cells in some way. Overall complexity: $O(1)$ per testcase.",
    "code": "for _ in range(int(input())):\n    n, U, R, D, L = map(int, input().split())\n    for mask in range(16):\n        rU, rR, rD, rL = U, R, D, L\n        if mask & 1:\n            rU -= 1\n            rL -= 1\n        if mask & 2:\n            rL -= 1\n            rD -= 1\n        if mask & 4:\n            rD -= 1\n            rR -= 1\n        if mask & 8:\n            rR -= 1\n            rU -= 1\n        if min(rU, rR, rD, rL) >= 0 and max(rU, rR, rD, rL) <= n - 2:\n            print(\"YES\")\n            break\n    else:\n        print(\"NO\")",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1494",
    "index": "C",
    "title": "1D Sokoban",
    "statement": "You are playing a game similar to Sokoban on an infinite number line. The game is discrete, so you only consider integer positions on the line.\n\nYou start on a position $0$. There are $n$ boxes, the $i$-th box is on a position $a_i$. All positions of the boxes are distinct. There are also $m$ special positions, the $j$-th position is $b_j$. All the special positions are also distinct.\n\nIn one move you can go one position to the left or to the right. If there is a box in the direction of your move, then you push the box to the next position in that direction. If the next position is taken by another box, then that box is also pushed to the next position, and so on. \\textbf{You can't go through the boxes}. \\textbf{You can't pull the boxes towards you}.\n\nYou are allowed to perform any number of moves (possibly, zero). Your goal is to place as many boxes on special positions as possible. Note that some boxes can be initially placed on special positions.",
    "tutorial": "Since you can only push boxes, you can't bring boxes from negative positions to positive ones and vice versa. Thus, negative boxes/special positions and positive boxes/special positions are two separate tasks. You can solve them independently with the same algorithm and add up the answers. So, we will only consider the positive boxes/special positions case. Notice that it never makes sense to move left. Thus, the only thing that determines the answer is the maximum position to the right you reach. For a naive algorithm, we could iterate over that position, push all boxes that we have encountered on our way ahead of us and calculate the number of boxes that are on special positions. That works in $O((n + m) \\cdot MAXC)$, where $MAXC$ is maximum coordinate. To improve that solution we can notice that the positions that are the most optimal are actually the ones such that the first box is pushed to some special position. Consider the case the first box isn't on a special position, and there is a special position somewhere to the right of it. There are two types of boxes: the ones that are in the pile you would push if you move right and the remaining suffix. What happens if you move one step to the right? The number of boxes from the suffix on special positions doesn't change. The number of boxes from the pile on special positions doesn't decrease. This number changes depending on if there is a special position immediately to the right of the pile and underneath the first box. Since we considered the case where there is no special position underneath the first box, the number can't decrease. So we managed to improve the solution to $O((n + m) \\cdot m)$. Still slow. Let's now learn to maintain the answer while moving the boxes. Precalculate $su_i$ - the number of boxes from the $i$-th to the last one that are already on special positions. That can be done with two pointers. Now iterate over the special position under the first box in the increasing order. Maintain the size of the pile and the number of special positions under the pile. The first value is just the index of the first box not in a pile. The second value is easier to obtain if you keep the index of the first special position after the pile (or $m$ if there are none). Also achievable with two pointers. The answer is the number of special positions under the pile plus the suffix answer for the boxes after the pile. Take the maximum of all options. The constraints are pretty free, so you could replace two pointers with binary searches if you wanted to. Overall complexity: $O(n + m)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint calc(const vector<int> &a, const vector<int> &b){\n    int n = a.size();\n    int m = b.size();\n    vector<int> su(n + 1);\n    int r = m - 1;\n    for (int i = n - 1; i >= 0; --i){\n        su[i] = su[i + 1];\n        while (r >= 0 && b[r] > a[i]) --r;\n        if (r >= 0 && b[r] == a[i]) ++su[i];\n    }\n    int ans = 0;\n    int j = 0;\n    r = 0;\n    forn(l, m){\n        while (j < n && a[j] <= b[l] + j) ++j;\n        while (r < m && b[r] - b[l] < j) ++r;\n        ans = max(ans, r - l + su[j]);\n    }\n    return ans;\n}\n\nint main() {\n    int t;\n    scanf(\"%d\", &t);\n    forn(_, t){\n        int n, m;\n        scanf(\"%d%d\", &n, &m);\n        vector<int> a(n), b(m);\n        forn(i, n) scanf(\"%d\", &a[i]);\n        forn(i, m) scanf(\"%d\", &b[i]);\n        vector<int> al, bl, ar, br;\n        forn(i, n){\n            if (a[i] < 0) al.push_back(-a[i]);\n            else ar.push_back(a[i]);\n        }\n        forn(i, m){\n            if (b[i] < 0) bl.push_back(-b[i]);\n            else br.push_back(b[i]);\n        }\n        reverse(al.begin(), al.end());\n        reverse(bl.begin(), bl.end());\n        printf(\"%d\\n\", calc(al, bl) + calc(ar, br));\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1494",
    "index": "D",
    "title": "Dogeforces",
    "statement": "The Dogeforces company has $k$ employees. Each employee, except for lower-level employees, has at least $2$ subordinates. Lower-level employees have no subordinates. Each employee, except for the head of the company, has exactly one direct supervisor. The head of the company is a direct or indirect supervisor of all employees. It is known that in Dogeforces, each supervisor receives a salary strictly more than all his subordinates.\n\nThe full structure of the company is a secret, but you know the number of lower-level employees and for each pair of lower-level employees, the salary of their common supervisor is known (if there are several such supervisors, then the supervisor with the minimum salary). You have to restore the structure of the company.",
    "tutorial": "We can solve the problem recursively from the root to the leaves. Let's maintain a list of leaf indices for the current subtree. If the list size is equal to $1$, then we can stop our recursion. Otherwise, we have to find the value of the root of the current subtree and split all leaves between child nodes. The root value is the maximum value of $a_{v,u}$ among all pairs $v, u$ belonging to a subtree (since the current root has at least $2$ child nodes, there is a pair of leaves for which the current root is the least common ancestor). If the value of the least common ancestor of the leaves $v$ and $u$ ($a_{v, u}$) is less than the value of the current root then $v$ and $u$ belong to the same child of the root. Using this fact, we can split all the leaves between the child nodes and then restore the subtrees for them recursively.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n\nconst int N = 505;\n\nint n;\nint a[N][N];\nint c[2 * N];\nvector<pair<int, int>> e;\n\nint calc(vector<int> ls) {\n  if (sz(ls) == 1)\n    return ls[0];\n  \n  int res = -1;\n  for (int u : ls)\n    res = max(res, a[ls[0]][u]);\n  \n  vector<vector<int>> ch;\n  ch.push_back({ls[0]});\n  for (int i = 1; i < sz(ls); ++i) {\n    int v = ls[i];\n    int group = -1;\n    for (int j = 0; j < sz(ch); ++j) {\n      if (a[v][ch[j][0]] != res) {\n        group = j;\n        break;\n      }\n    }\n    if (group == -1) {\n      group = sz(ch);\n      ch.push_back({});\n    }\n    ch[group].push_back(v);\n  }\n  \n  int v = n++;\n  c[v] = res;\n  for (int i = 0; i < sz(ch); ++i) {\n    int u = calc(ch[i]);\n    e.emplace_back(u, v);\n  }\n  return v;\n}\n\nint main() {\n  cin >> n;\n  for (int i = 0; i < n; ++i)\n    for (int j = 0; j < n; ++j)\n      cin >> a[i][j];\n  for (int i = 0; i < n; ++i)\n    c[i] = a[i][i];\n  vector<int> ls(n);\n  iota(ls.begin(), ls.end(), 0);\n  int root = calc(ls);\n  cout << n << '\\n';\n  for (int i = 0; i < n; ++i)\n    cout << c[i] << ' ';\n  cout << '\\n' << root + 1 << '\\n';\n  for (auto it : e)\n    cout << it.first + 1 << ' ' << it.second + 1 << '\\n';\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1494",
    "index": "E",
    "title": "A-Z Graph",
    "statement": "You are given a directed graph consisting of $n$ vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty.\n\nYou should process $m$ queries with it. Each query is one of three types:\n\n- \"$+$ $u$ $v$ $c$\" — add arc from $u$ to $v$ with label $c$. It's guaranteed that there is no arc $(u, v)$ in the graph at this moment;\n- \"$-$ $u$ $v$\" — erase arc from $u$ to $v$. It's guaranteed that the graph contains arc $(u, v)$ at this moment;\n- \"$?$ $k$\" — find the sequence of $k$ vertices $v_1, v_2, \\dots, v_k$ such that there exist both routes $v_1 \\to v_2 \\to \\dots \\to v_k$ and $v_k \\to v_{k - 1} \\to \\dots \\to v_1$ and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times.",
    "tutorial": "At first, if there should be both routes $v_1, v_2, \\dots, v_k$ and $v_k, v_{k - 1}, \\dots, v_1$ then there are both arcs $(v_1, v_2)$ and $(v_2, v_1)$, i. e. there should exist at least one pair $\\{u, v\\}$ that both arcs $(u, v)$ and $(v, u)$ are present in the graph. Now, if $k$ is odd, and we have at least one pair $\\{u, v\\}$ then we can simply create sequence $u, v, u, v, \\dots, v, u$. This sequence is a palindrome so, obviously, both routes generate the same string. If $k$ is even (or $k = 2x$), we can note that in the sequence $v_1, v_2, \\dots, v_{2x}$ there is a middle arc $(v_x, v_{x + 1})$ and it should have the same character as arc $(v_{x + 1}, v_x)$ (since it's a middle arc in reverse route $v_k, \\dots, v_1$), i. e. there should exist at least one pair $\\{u, v\\}$ that both arcs $(u, v)$ and $(v, u)$ are present in the graph and have the same label. Now, if we have at least one such pair $\\{u, v\\}$ then routes $u, v, \\dots, u, v$ and $v, u, \\dots, v, u$ generate the same one-letter strings. Since each arc $(u, v)$ is a part of at most one pair $\\{u, v\\}$, we can just maintain two sets with pairs $\\{u, v\\}$: one for pairs with different labels and the other one for pairs with equal labels. If $k$ is odd, we check that at least one of the sets is not empty. If $k$ is even, we check that the second set is not empty.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef pair<int, int> pt;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int n, m;\n    cin >> n >> m;\n    \n    map<pt, int> allEdges;\n    set<pt> difPairs, eqPairs;\n    \n    fore (q, 0, m) {\n        char tp; cin >> tp;\n        if (tp == '+') {\n            int u, v;\n            char c;\n            cin >> u >> v >> c;\n            \n            if (allEdges.count({v, u})) {\n                if (allEdges[{v, u}] == c)\n                    eqPairs.emplace(min(u, v), max(u, v));\n                else\n                    difPairs.emplace(min(u, v), max(u, v));\n            }\n            allEdges[{u, v}] = c;\n            \n        } else if (tp == '-') {\n            int u, v;\n            cin >> u >> v;\n            if (eqPairs.count({min(u, v), max(u, v)}))\n                eqPairs.erase({min(u, v), max(u, v)});\n            if (difPairs.count({min(u, v), max(u, v)}))\n                difPairs.erase({min(u, v), max(u, v)});\n            \n            allEdges.erase({u, v});\n        } else {\n            int k;\n            cin >> k;\n            \n            bool hasAns = !eqPairs.empty();\n            if (k & 1)\n                hasAns |= !difPairs.empty();\n            cout << (hasAns ? \"YES\" : \"NO\") << '\\n';\n        }\n    }\n    \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs",
      "hashing"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1494",
    "index": "F",
    "title": "Delete The Edges",
    "statement": "You are given an undirected connected graph consisting of $n$ vertices and $m$ edges. Your goal is to destroy all edges of the given graph.\n\nYou may choose any vertex as the starting one and begin walking from it along the edges. When you walk along an edge, you destroy it. Obviously, you cannot walk along an edge if it is destroyed.\n\nYou can perform the \\textbf{mode shift} operation at most once during your walk, and this operation can only be performed when you are at some vertex (you cannot perform it while traversing an edge). After the \\textbf{mode shift}, the edges you go through are deleted in the following way: the first edge after the \\textbf{mode shift} is not destroyed, the second one is destroyed, the third one is not destroyed, the fourth one is destroyed, and so on. You cannot switch back to the original mode, and you don't have to perform this operation if you don't want to.\n\nCan you destroy all the edges of the given graph?",
    "tutorial": "Let's suppose our graph is split into two graphs $G_1$ and $G_2$, the first graph contains the edges we delete before the mode shift, the second graph contains the edges we delete after the mode shift. It's quite obvious that the graph $G_1$ has an eulerian path. The structure of $G_2$ is a bit harder to analyze, but we can prove that it is always a star graph (a vertex and some other vertices connected directly to it), and the center of the star coincides with the last vertex in the eulerian path in $G_1$. To prove that $G_2$ is a star graph, we can consider the second part of the path (after the mode shift) backward: the last edge we traversed was deleted, and the previous-to-last move could have been only along that edge. The third-last and the fourth-last moves should have been along another edge connecting some vertex to the center of the star, and so on. Okay, how do we find a way to split the graph into $G_1$ and $G_2$? Iterate on the center of the star (let it be $c$). For the graph $G_1$ to contain an eulerian path, it should have at most $2$ vertices with an odd degree. Let's construct $G_2$ in such a way that we minimize the number of odd vertices in $G_1$ - for each edge incident to $c$, we either move it to $G_1$ or $G_2$ in such a way that the resulting degree of the other vertex is even. All other edges belong to $G_1$. If there is an eulerian path in $G_1$ that ends in $c$, we are done. Otherwise, we should iterate on some edge adjacent to $c$ and change its status (in order to check if $G_1$ can have an eulerian path after that). We can't \"flip\" two edges because flipping two edges increases the number of odd vertices in $G_1$ at least by $2$ (if it is already $2$ or greater, the eulerian path won't exist, and if it's $0$, then flipping two edges creates two odd vertices, none of which is $c$, so eulerian path can't end in $c$). After flipping each edge, we try to find an eulerian path in $G_1$ once again and flip the edge back. After checking the vertex $c$ as the center of the star, we return all adjacent edges to $G_1$ and move to the next vertex. The whole algorithm requires checking for the existence of the eulerian path $O(n + m)$ times, so it should work in $O((n+m)^2)$ or $O((n+m)^2 \\log n)$ depending on the implementation. Fun fact: initially I wanted to give a harder version of a problem with $n, m \\le 2 \\cdot 10^5$ that would require some sort of dynamic connectivity to check for an eulerian path fast, but when I started coding it, I realized that implementation there was a bit painful, so I've decided to drop the constraints to allow quadratic solutions.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300043;\n\nint n, m;\nset<int> g[N];\nset<int> g2[N];\n\nvector<int> res;\n\nvoid euler(int x)\n{\n    while(!g2[x].empty())\n    {\n        int y = *g2[x].begin();\n        g2[x].erase(y);\n        g2[y].erase(x);\n        euler(y);\n    }\n    res.push_back(x);\n}\n\nbool check(int c)\n{\n    for(int i = 1; i <= n; i++)\n        g2[i] = g[i];\n    res = vector<int>();\n    euler(c);\n    int curm = 0;\n    for(int i = 1; i <= n; i++)\n        curm += g[i].size();\n    for(int i = 1; i <= n; i++)\n        g2[i] = g[i];\n    for(int i = 1; i < res.size(); i++)\n    {\n        int x = res[i - 1];\n        int y = res[i];\n        if(g2[x].count(y) != 1)\n            return false;\n        g2[x].erase(y);\n        g2[y].erase(x);\n    }\n    return curm / 2 + 1 == res.size();    \n}\n\nint main()\n{\n    scanf(\"%d %d\", &n, &m);\n    for(int i = 0; i < m; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        g[x].insert(y);\n        g[y].insert(x);\n    }\n    for(int i = 1; i <= n; i++)\n    {\n        set<int> pr = g[i];\n        set<int> diff;\n        for(auto x : pr)\n            if(g[x].size() % 2 == 1)\n            {\n                g[i].erase(x);\n                g[x].erase(i);\n                diff.insert(x);\n            }\n        if(check(i))\n        {\n            res.push_back(-1);\n            for(auto x : diff)\n            {\n                res.push_back(x);\n                res.push_back(i);\n            }\n            printf(\"%d\\n\", res.size());\n            for(auto x : res) printf(\"%d \", x);\n            puts(\"\");\n            exit(0);\n        }\n        for(auto x : pr)\n        {\n            if(g[i].count(x))\n            {\n                g[i].erase(x);\n                g[x].erase(i);\n                diff.insert(x);\n            }\n            else\n            {\n                g[i].insert(x);\n                g[x].insert(i);\n                diff.erase(x);\n            }\n            if(check(i))\n            {\n                res.push_back(-1);\n                for(auto x : diff)\n                {\n                    res.push_back(x);\n                    res.push_back(i);\n                }\n                printf(\"%d\\n\", res.size());\n                for(auto x : res) printf(\"%d \", x);\n                puts(\"\");\n                exit(0);\n            }\n            if(g[i].count(x))\n            {\n                g[i].erase(x);\n                g[x].erase(i);\n                diff.insert(x);\n            }\n            else\n            {\n                g[i].insert(x);\n                g[x].insert(i);\n                diff.erase(x);\n            }\n        }\n        for(auto x : diff)\n        {\n            g[i].insert(x);\n            g[x].insert(i);\n        }\n    }\n    puts(\"0\");\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1495",
    "index": "A",
    "title": "Diamond Miner",
    "statement": "Diamond Miner is a game that is similar to Gold Miner, but there are $n$ miners instead of $1$ in this game.\n\nThe mining area can be described as a plane. The $n$ miners can be regarded as $n$ points \\textbf{on the y-axis}. There are $n$ diamond mines in the mining area. We can regard them as $n$ points \\textbf{on the x-axis}. For some reason, \\textbf{no miners or diamond mines can be at the origin} (point $(0, 0)$).\n\nEvery miner should mine \\textbf{exactly} one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point $(a,b)$ uses his hook to mine a diamond mine at the point $(c,d)$, he will spend $\\sqrt{(a-c)^2+(b-d)^2}$ energy to mine it (the distance between these points). The miners can't move or help each other.\n\nThe object of this game is to minimize \\textbf{the sum of the energy} that miners spend. Can you find this minimum?",
    "tutorial": "First, you can turn a point $(x,y)$ to $(|x|,|y|)$, while not changing the answer. After this operation, all points can be described as $(0,a)$ or $(b,0)$ ($a,b > 0$). In a triangle, if the length of the edges are $a$, $b$, $c$, it is obvious that $a+b > c$. So, if you connect all match-pairs with a segment and there are two segments intersecting each other, you must be able to change the matching ways to make the answer smaller. For example, if you match $A(a_1,0)$ with $B(0,b_1)$, $C(a_2,0)$ with $D(0,b_2)$, the answer will be $|AB|+|CD|$; if you match $A$ with $D$ and $B$ with $C$, the answer will be $|AD|+|BC| < |AO|+|DO|+|BO|+|CO| = |AB|+|CD|$. So in the best solution, there won't be two segments intersecting each other. Sort all the points on the x-axis and on the y-axis, then match the points in ascending order of $x$ or $y$, you can get the minimum. The time complexity is $O(n \\log n)$ for each test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int maxn = 100005;\nint n,X[maxn],Y[maxn],t1,t2;\nint main(){\n  int T; scanf(\"%d\",&T);\n  for(int i(1);i <= T;++i){\n    scanf(\"%d\",&n); t1 = t2 = 0;\n    for(int i(1);i <= 2*n;++i){\n      int x,y;\n      scanf(\"%d%d\",&x,&y);\n      if(x == 0) Y[++t2] = abs(y);\n      else X[++t1] = abs(x);\n    }\n    sort(X+1,X+1+t1);\n    sort(Y+1,Y+1+t2);\n    double Ans = 0;\n    for(int i(1);i <= n;++i)\n      Ans += sqrt(1.0*X[i]*X[i]+1.0*Y[i]*Y[i]);\n    printf(\"%.15lf\\n\",Ans);\n  }\n  return 0;\n}",
    "tags": [
      "geometry",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1495",
    "index": "B",
    "title": "Let's Go Hiking",
    "statement": "On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper.\n\nA permutation $p$ is written from left to right on the paper. First Qingshan chooses an integer index $x$ ($1\\le x\\le n$) and tells it to Daniel. After that, Daniel chooses another integer index $y$ ($1\\le y\\le n$, $y \\ne x$).\n\nThe game progresses turn by turn and as usual, Qingshan moves first. The rules follow:\n\n- If it is Qingshan's turn, Qingshan must change $x$ to such an index $x'$ that $1\\le x'\\le n$, $|x'-x|=1$, $x'\\ne y$, and $p_{x'}<p_x$ at the same time.\n- If it is Daniel's turn, Daniel must change $y$ to such an index $y'$ that $1\\le y'\\le n$, $|y'-y|=1$, $y'\\ne x$, and $p_{y'}>p_y$ at the same time.\n\nThe person who can't make her or his move loses, and the other wins. You, as Qingshan's fan, are asked to calculate the number of possible $x$ to make Qingshan win in the case both players play optimally.",
    "tutorial": "Let's consider that the $2k+1(k\\ge 0)$-th turn is Qingshan's and the $2k+2(k\\ge 0)$-th turn is Daniel's. If Qingshan chooses $x(1<x\\le n)$ satisfying $x=n$ or $p_x<p_{x+1}$, then Daniel can choose $y=x-1$ to make Qingshan can't move in the first turn. The case that $x=1$ or $p_x<p_{x-1}$ is the same. So Qingshan must choose $x(1<x<n)$ satisfying $p_x>p_{x-1}$ and $p_x>p_{x+1}$ at first. Let $l$ be the length of the longest monotone segments and $c$ be the number of the longest monotone segments. $l\\ge 2$ and $c\\ge 1$ are always true. It is obvious that Qingshan can't win when $c>2$ because wherever Qingshan chooses, Daniel can always find a place that he can move $l-1$ times while Qingshan can move $l-1$ times at most. When $c=1$, Qingshan will also lose. If the only longest monotone segment is $p_s,p_{s+1}\\dots,p_{s+l-1}$ and it's increasing(if it's decreasing, the discussion is almost the same). Qingshan must choose $x=s+l-1$ at first. The discussion follows: If $l\\bmod 2=0$, Daniel can choose $y=s$ at first. After the $l-3$-th turn(Qingshan's turn), $x=s+l-\\frac{l}{2}$ and After the $l-2$-th turn(Daniel's turn), $y=s+\\frac{l}{2}-1$. The next turn is Qingshan's and Qingshan loses. If $l\\bmod 2=1$, Daniel can choose $y=s+1$ at first. Pay attention that Qingshan can't change $x$ to $x+1$ in the first turn because Daniel can move $l-2$ times while Qingshan can move $l-2$ times at most if she change $x$ to $x+1$ in the first turn. After the $l-4$-th turn(Qingshan's turn), $x=s+l-\\frac{l-1}{2}$ and After the $l-3$-th turn(Daniel's turn), $y=s+\\frac{l-1}{2}$. The next turn is Qingshan's and Qingshan loses. When $c=2$ , the only two longest monotone segments must be like $p_{m-l+1}<p_{m-l+2}<\\cdots<p_m>p_{m+1}>\\cdots>p_{m+l-1}$. (Otherwise Qingshan will lose.) In that case Qingshan will lose if $l\\bmod 2=0$ because Daniel can choose $y=m-l+1$ at first and whatever Qingshan's first move is, Qingshan will lose(just like the discussion above). If $l\\bmod 2=1$, Qingshan is the winner. It is not hard to check it in $O(n)$. The overall time complexity is $O(n)$.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#define ch() getchar()\n#define pc(x) putchar(x)\nusing namespace std;\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[65];int cnt=0;\n\tif(x<0)pc('-'),x=-x;\n\tq[++cnt]=x%10,x/=10;\n\twhile(x)\n\t\tq[++cnt]=x%10,x/=10;\n\twhile(cnt)pc(q[cnt--]+'0');\n}\nconst int maxn=100005;\nint p[maxn],d[maxn];\nint main(){\n\tint n;read(n);\n\tfor(int i=1;i<=n;++i)read(p[i]);\n\tfor(int i=2;i<=n;++i)d[i]=(p[i-1]<p[i]);\n\tint MX=0,CNT=0;\n\tfor(int l=2,r=2;l<=n;l=r=r+1){\n\t\tint o=d[l];\n\t\twhile(r+1<=n&&o==d[r+1])++r;\n\t\tint len=r-l+2;\n\t\tif(len>MX)MX=len,CNT=1;\n\t\telse if(len==MX)++CNT;\n\t}\n\tif(CNT!=2||(MX&1)==0)return puts(\"0\"),0;\n\tint ok=false;\n\tfor(int i=3;i<=n&&!ok;++i){\n\t\tif(d[i-1]&&!d[i]){\n\t\t\tint l=i-1,r=i;\n\t\t\twhile(l>2&&d[l-1])--l;\n\t\t\twhile(r<n&&!d[r+1])++r;\n\t\t\tif((i-1)-(l-1)+1==MX&&r-(i-1)+1==MX)\n\t\t\t\tok=true;\n\t\t}\n\t}\n\twrite(ok),pc('\\n');\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1495",
    "index": "C",
    "title": "Garden of the Sun",
    "statement": "There are many sunflowers in the Garden of the Sun.\n\nGarden of the Sun is a rectangular table with $n$ rows and $m$ columns, where the cells of the table are farmlands. All of the cells grow a sunflower on it. Unfortunately, one night, the lightning stroke some (possibly zero) cells, and sunflowers on those cells were burned into ashes. In other words, those cells struck by the lightning became empty. Magically, \\textbf{any two empty cells have no common points} (neither edges nor corners).\n\nNow the owner wants to remove some (possibly zero) sunflowers to reach the following two goals:\n\n- When you are on an empty cell, you can walk to any other empty cell. In other words, those empty cells are connected.\n- There is \\textbf{exactly one} simple path between any two empty cells. In other words, there is no cycle among the empty cells.\n\nYou can walk from an empty cell to another if they share a common edge.\n\nCould you please give the owner a solution that meets all her requirements?\n\nNote that you are not allowed to plant sunflowers. You \\textbf{don't need} to minimize the number of sunflowers you remove. It can be shown that the answer always exists.",
    "tutorial": "When $m$ is the multiple of $3$, it's easy to construct a solution: First, remove all the sunflowers on column $2,5,8,11,\\ldots$. This operation won't form a cycle in the graph. Let's take this as an example: After the operation, the graph turns into: After that, you need to connect these columns to make them connected but without forming a cycle. The green cells are all alternatives. This way of construction also works for $m=3k+2$. But you need to be cautious about the case of $m=3k+1$ because there is an extra column that may not be connected with the left part. Don't forget to connect them. Another approach is to remove column $1,4,7,10,\\ldots$ when $m=3k+1$. So there won't be an extra column. The time complexity is $O(nm)$ for each test case.",
    "code": "#include <bits/stdc++.h>\n \nconst int MX = 1e3 + 23;\n \nint read(){\n\tchar k = getchar(); int x = 0;\n\twhile(k < '0' || k > '9') k = getchar();\n\twhile(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();\n\treturn x;\n}\n \nchar str[MX][MX];\n \nvoid solve(){\n\tint n = read() ,m = read();\n\tfor(int i = 1 ; i <= n ; ++i){\n\t\tscanf(\"%s\" ,str[i] + 1);\n\t}\n\tfor(int i = 1 + (m % 3 == 0) ; i <= m ; ){\n\t\tfor(int j = 1 ; j <= n ; ++j) str[j][i] = 'X';\n\t\ti += 3;\n\t\tif(i > m) break;\n \n\t\tint p = 1;\n\t\tif(n == 1 || (str[2][i - 1] != 'X' && str[2][i - 2] != 'X')) p = 1;\n\t\telse p = 2;\n\t\tstr[p][i - 1] = str[p][i - 2] = 'X';\n\t}\n\tfor(int i = 1 ; i <= n ; ++i) puts(str[i] + 1);\n}\n \nint main(){\n\tint T = read();\n\tfor(int i = 1 ; i <= T ; ++i) solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1495",
    "index": "D",
    "title": "BFS Trees",
    "statement": "We define a spanning tree of a graph to be a BFS tree rooted at vertex $s$ if and only if for every node $t$ the shortest distance between $s$ and $t$ in the graph is equal to the shortest distance between $s$ and $t$ in the spanning tree.\n\nGiven a graph, we define $f(x,y)$ to be the number of spanning trees of that graph that are BFS trees rooted at vertices $x$ and $y$ at the same time.\n\nYou are given an undirected connected graph with $n$ vertices and $m$ edges. Calculate $f(i,j)$ for all $i$, $j$ by modulo $998\\,244\\,353$.",
    "tutorial": "Let's enumerate vertexes $x,y$, and calculate $f(x,y)$ for them. Let $dist(x,y)$ denote the number of the vertexes which lie on the shortest-path between $x$ and $y$ on the graph. It is obvious that the distance between $x$ and $y$ in the tree is equal to $dist(x,y)$. And the vertex $z$ satisfying $dist(x,z)+dist(y,z)-1=dist(x,y)$ must be on the path between $x$ and $y$. So the number of the vertexes $z$ must be equal to $dist(x,y)$ ( including $x$ and $y$ ). Then, let's consider the contributions of other vertexes $i$. In the bfs-trees of both $x$ and $y$, there must be and only be a edge linking $i$ and $j$, which $j$ satisfies $dist(x,i)=dist(x,j)+1\\land dist(y,i)=dist(y,j)+1$. Proof : Let's prove it recursively. All the vertexes linked to the path between $x$ and $y$ satisfy the condition ( There is and only is a edge linking them ). We can call them layer 1. All the vertexes linked to the layer 1 satisfy the condition ( There is and only is a edge linking them ). We can call them layer 2. All the vertexes ... End of proof And the contribution of each vertex is independent, which means that for each vertex $i$ we can choose a vertex $j$ without considering other vertexes. Proof : No matter which $j$ we choose for $i$, the layer of $i$ will not change. So the choice of $i$ won't change the number of choices of others. End of proof So we only need calculate the number of $j$ for every $i$, and multiply them. For every $x,y$, we should enumerate all the edges to calculate $j$ for every $i$. So the complexity is $O(m)$ per $x,y$. The total complexity is $O(n^2m)$.",
    "code": "#pragma GCC optimize(2)\n#include <bits/stdc++.h>\n#define debug(...) fprintf(stderr, __VA_ARGS__)\n#define RI register int\ntypedef long long LL;\n \n#define FILEIO(name) freopen(name\".in\", \"r\", stdin), freopen(name\".out\", \"w\", stdout);\n \nusing namespace std;\n \nnamespace IO {\n  char buf[1000000], *p1 = buf, *p2 = buf;\n  inline char gc() {\n    if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin);\n    return p1 == p2 ? EOF : *(p1++);\n  }\n  template <class T> inline void read(T &n) {\n    n = 0; RI ch = gc(), f;\n    while ((ch < '0' || ch > '9') && ch != '-') ch = gc();\n    f = (ch == '-' ? ch = gc(), -1 : 1);\n    while (ch >= '0' && ch <= '9') n = n * 10 + (ch ^ 48), ch = gc();\n    n *= f;\n  }\n  char Of[105], *O1 = Of, *O2 = Of;\n  template <class T> inline void print(T n, char ch = '\\n') {\n    if (n < 0) putchar('-'), n = -n;\n    if (n == 0) putchar('0');\n    while (n) *(O1++) = (n % 10) ^ 48, n /= 10;\n    while (O1 != O2) putchar(*(--O1));\n    putchar(ch);\n  }\n}\n \nusing IO :: read;\nusing IO :: print;\n \nint const mod = 998244353;\nint const MAXN = 505;\nstruct Edges { int to, next; } e[MAXN << 2];\nint head[MAXN], tot;\nint dis[MAXN][MAXN];\nqueue <int> q;\nint n, m;\nint Ans[MAXN][MAXN];\n \ninline void addedge(int from, int to) {\n  e[++tot] = (Edges){to, head[from]};\n  head[from] = tot;\n  e[++tot] = (Edges){from, head[to]};\n  head[to] = tot;\n}\n \nvoid Getdis(int S, int *dis) {\n  for (RI i = 1; i <= n; ++i) dis[i] = 0;\n  q.push(S); dis[S] = 1;\n  while (!q.empty()) {\n    int t = q.front(); q.pop();\n    for (RI i = head[t]; i; i = e[i].next)\n      if (!dis[e[i].to])\n        dis[e[i].to] = dis[t] + 1, q.push(e[i].to);\n  }\n}\n \nint main() {\n  \n#ifdef LOCAL\n  FILEIO(\"a\");\n#endif\n \n  read(n), read(m);\n  for (RI i = 1, x, y; i <= m; ++i)\n    read(x), read(y), addedge(x, y);\n  for (RI i = 1; i <= n; ++i)\n    Getdis(i, dis[i]);\n  for (RI x = 1; x <= n; ++x)\n    for (RI y = x; y <= n; ++y) {\n      int cnt = 0;\n      for (RI i = 1; i <= n; ++i)\n        if (dis[x][i] + dis[y][i] - 1 == dis[x][y])\n          ++cnt;\n      LL ans = 1;\n      if (cnt > dis[x][y]) ans = 0;\n      for (RI i = 1; i <= n; ++i)\n        if (dis[x][i] + dis[y][i] - 1 != dis[x][y]) {\n          int flag = 0;\n          for (RI j = head[i]; j; j = e[j].next)\n            if (dis[x][e[j].to] == dis[x][i] - 1 && dis[y][e[j].to] == dis[y][i] - 1)\n              ++flag;\n          ans = ans * flag % mod;\n          if (!ans) break;\n        }\n      Ans[x][y] = Ans[y][x] = ans;\n    }\n  for (RI i = 1; i <= n; ++i)\n    for (RI j = 1; j <= n; ++j)\n      printf(\"%d%c\", Ans[i][j], \" \\n\"[j == n]);\n \n  return 0;\n}\n \n// created by Daniel yuan\n/*\n     ________\n    /        \\\n   / /      \\ \\\n  / /        \\ \\\n  \\            /\n   \\  ______  /\n    \\________/\n*/",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "graphs",
      "math",
      "shortest paths",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1495",
    "index": "E",
    "title": "Qingshan and Daniel",
    "statement": "Qingshan and Daniel are going to play a card game. But it will be so boring if only two persons play this. So they will make $n$ robots in total to play this game automatically. Robots made by Qingshan belong to the team $1$, and robots made by Daniel belong to the team $2$. Robot $i$ belongs to team $t_i$. Before the game starts, $a_i$ cards are given for robot $i$.\n\nThe rules for this card game are simple:\n\n- Before the start, the robots are arranged in a circle in the order or their indices. The robots will discard cards in some order, in each step one robot discards a single card. When the game starts, robot $1$ will discard one of its cards. After that, robots will follow the following rules:\n- If robot $i$ discards the card last, the nearest robot whose team is opposite from $i$'s will discard the card next. In another word $j$ will discard a card right after $i$, if and only if among all $j$ that satisfy $t_i\\ne t_j$, $dist(i,j)$ (definition is below) is minimum.\n- The robot who has no cards should quit the game immediately. This robot won't be considered in the next steps.\n- When no robot can discard the card next, the game ends.\n\nWe define the distance from robot $x$ to robot $y$ as $dist(x,y)=(y-x+n)\\bmod n$. It is similar to the oriented distance on the circle.\n\nFor example, when $n=5$, the distance from $1$ to $3$ is $dist(1,3)=(3-1+5)\\bmod 5=2$, the distance from $3$ to $1$ is $dist(3,1)=(1-3+5)\\bmod 5 =3$.\n\nLater, Qingshan finds out that it will take so much time to see how robots play. She wants to know the result as quickly as possible. You, as Qingshan's fan, are asked to calculate an array $[ans_1,ans_2,\\ldots,ans_n]$ — $ans_i$ is equal to the number of cards, that $i$-th robot will discard during the game. You need to hurry!\n\nTo avoid the large size of the input, the team and the number of cards of each robot will be generated in your code with some auxiliary arrays.",
    "tutorial": "We can consider that the robots are standing on a cycle. The game ends up with at least one team having no cards. Let the team having no cards in the end be team $A$ and let the other be team $B$. If two teams both use up their cards, the first robot's team is $A$. For team $A$, we've already known how many cards will its robots discard, because they will discard all their cards. But how to calculate the answer for team $B$? Let's look at the process of the game. Obviously, robots in $A$ and robots in $B$ will discard cards alternatively. In another word, if we write down the team of robots who discard cards in time order, it will form a sequence - $ABABAB\\cdots B$ or $BABABA\\cdots B$. For the second type (starting with $B$), we can just use brute-force to discard the first card and then find the next $A$. So there is only one circumstance: $ABABAB\\cdots B$. Note that in the sequence every $A$ is followed by exactly one $B$. So the length of the sequence is the number of cards of team $A$ multiplying $2$. Currently, we are not able to figure out which robot is exactly represented by a particular $A$ or $B$ in the sequence. Luckily, we don't need to know it. What we care about is only how many cards the robot in team $B$ discards. You can consider every $AB$ is the sequence as a query and change operation - \"In the current game, some robot $i$ in team $A$ will find the first robot $j$ in team $B$ on its right, and change $a_j$ to $a_j-1$\". It's a very important limit \"In the current game\" here because some robot will quit the game halfway according to the statement. But on the contrary, an interesting fact is that the \"important\" limit is not important at all. We can make the query and the change in any order and it won't change the answer! So you just need to iterate the array and maintain a variable $cnt$ - the number of operations that are visited but not performed. If the team of the current robot is $A$, assign $cnt+a_i$ to $cnt$. Otherwise, you can perform $\\min(a_i, cnt)$ operations now, and assign $a_i-\\min(a_i,cnt)$ to $a_i$. Since robots are standing on a cycle, you need to iterate the array $2$ times. So the time complexity is $O(n+m)$.",
    "code": "#include <bits/stdc++.h>\n \n#define debug(...) fprintf(stderr ,__VA_ARGS__)\n#define __FILE(x)\\\n\tfreopen(#x\".in\" ,\"r\" ,stdin);\\\n\tfreopen(#x\".out\" ,\"w\" ,stdout)\n#define LL long long\n \nconst int MX = 5e6 + 23;\nconst LL MOD = 1e9 + 7;\n \nint read(){\n\tchar k = getchar(); int x = 0;\n\twhile(k < '0' || k > '9') k = getchar();\n\twhile(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();\n\treturn x;\n}\n \nint a[MX] ,team[MX] ,org[MX];\nint n ,m;\nLL s[2];\n \nint seed ,base;\nint rnd(){\n\tint ret = seed;\n\tseed = (1LL * seed * base + 233) % MOD;\n\treturn ret;\n}\n \nint main(){\n\tn = read() ,m = read();\n\t\n\tint lastp = 0;\n\tfor(int i = 1 ,p ,k ,b ,w ; i <= m ; ++i){\n\t\tp = read() ,k = read() ,b = read() ,w = read();\n\t\tseed = b ,base = w;\n\t\tfor(int j = lastp ; j < p ; ++j){\n\t\t\tteam[j] = rnd() % 2;\n\t\t\ts[team[j]] += (org[j] = a[j] = rnd() % k + 1);\n\t\t\t// printf(\"team %d a[%d] = %d\\n\" ,team[j] ,j ,a[j]);\n\t\t}\n\t\tlastp = p;\n\t}\n\t\n\tint st = 0; \n\tif(s[team[0]] > s[!team[0]]){\n\t\ts[team[0]]-- ,a[0]--;\n\t\twhile(team[0] == team[st] && st < n) ++st;\n\t}\n\t\n \n\tint cur = st;\n\tLL sum = 0;\n\tif(st != n) while(s[team[st]]){\n\t\tif(team[cur] == team[st]){\n\t\t\tsum += a[cur];\n\t\t\ta[cur] = 0;\n\t\t}\n\t\telse{\n\t\t\tLL d = std::min(1LL * a[cur] ,sum);\n\t\t\ts[team[st]] -= d;\n\t\t\tsum -= d;\n\t\t\ta[cur] -= d;\n\t\t}\n\t\tcur = (cur + 1 == n ? 0 : cur + 1);\n\t}\n\tLL ans = 1;\n\tfor(int i = 0 ; i < n ; ++i){\n\t\tLL qwq = (((org[i] - a[i]) ^ (1LL * (i + 1) * (i + 1))) + 1) % MOD;\n\t\tans = ans * qwq % MOD;\n\t}\n\tprintf(\"%lld\\n\" ,ans);\n\t// for(int i = 0 ; i < n ; ++i) printf(\"%d%c\" ,org[i] - a[i] ,\" \\n\"[i == n - 1]);\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1495",
    "index": "F",
    "title": "Squares",
    "statement": "There are $n$ squares drawn from left to right on the floor. The $i$-th square has three integers $p_i,a_i,b_i$, written on it. The sequence $p_1,p_2,\\dots,p_n$ forms a permutation.\n\nEach round you will start from the leftmost square $1$ and jump to the right. If you are now on the $i$-th square, you can do one of the following two operations:\n\n- Jump to the $i+1$-th square and pay the cost $a_i$. If $i=n$, then you can end the round and pay the cost $a_i$.\n- Jump to the $j$-th square and pay the cost $b_i$, where $j$ is the leftmost square that satisfies $j > i, p_j > p_i$. If there is no such $j$ then you can end the round and pay the cost $b_i$.\n\nThere are $q$ rounds in the game. To make the game more difficult, you need to maintain a square set $S$ (initially it is empty). You \\textbf{must} pass through these squares during the round (other squares can also be passed through). The square set $S$ for the $i$-th round is obtained by adding or removing a square from the square set for the $(i-1)$-th round.\n\nFor each round find the minimum cost you should pay to end it.",
    "tutorial": "If we let the parent of $i(1\\le i\\le n)$ is the rightmost $j$ satisfying $j<i,p_j>p_i$(if that $j$ doesn't exist, the parent of $i$ is $0$), we can get a tree and we can dfs the tree with the order $0,1,2,\\dots,n$. Let's call the parent of $i$ is $\\operatorname{pa}_i$ and the children set of $i$ is $\\operatorname{child}_i$. Here is an example. $n=5$ and the permutation is $2,1,5,3,4$. The graphs we build follow. Let's call the edges with the cost $a_i$ A-type and the edges with the cost $b_i$ B-type. Consider that now you are on the $i$-th square. If you choose a B-type edge(with the cost $b_i$), you will jump over all the squares in $i$'s subtree($i$ is not included), that is to say, you will not pass through them. If you choose an A-type edge, we can think you enter $i$'s subtree and you must pass through all of the $i$'s child. To simplify the problem, we think you choose a node $i$ if and only if you pass through the A-type edge from the $i$-th square. Let's call the chosen set is $S$. It is not hard to find out that the node $i$ can be chosen if and only if all the ancestors of $i$ in the tree are chosen(if not, you even don't have the chance to pass through $i$). And that you pass through the $i$-th square is equivalent to you choosing the parent of $i$. Then the problem is simplified. You purpose is to choose some nodes in the tree ($0$ must be chosen as it is the root) and minimize your cost. Here your cost is $\\sum_{i\\in S}a_i+\\sum_{i\\not\\in S,\\operatorname{pa}_i\\in S}b_i$. If we let $c_i=a_i-b_i+\\sum_{j\\in\\operatorname{child}_i}b_j$, the cost can be considered as $\\sum_{i\\in S}c_i+\\sum_{j\\in\\operatorname{child}_0}b_j$. It is very easy to solve it with binups. The time complexity is $O((n+q)\\log n)$.",
    "code": "#include<set>\n#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#define ch() getchar()\n#define pc(x) putchar(x)\nusing namespace std;\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[65];int cnt=0;\n\tif(x<0)pc('-'),x=-x;\n\tq[++cnt]=x%10,x/=10;\n\twhile(x)\n\t\tq[++cnt]=x%10,x/=10;\n\twhile(cnt)pc(q[cnt--]+'0');\n}\nconst int maxn=200005;\nint p[maxn],st[maxn],tp,pa[maxn][22],dp[maxn];\nlong long a[maxn],b[maxn],val[maxn],dis[maxn];\nint lca(int x,int y){\n\tif(dp[x]<dp[y])x^=y^=x^=y;\n\tfor(int t=dp[x]-dp[y],cn=0;t;t>>=1,++cn)\n\t\tif(t&1)x=pa[x][cn];\n\tif(x==y)return x;\n\tfor(int t=20;t>=0;--t)\n\t\tif(pa[x][t]!=pa[y][t])\n\t\t\tx=pa[x][t],y=pa[y][t];\n\treturn pa[x][0];\n}\nint vis[maxn],cnt[maxn];set<int>s;\nlong long sum;\nlong long dist(int x,int y){\n\treturn dis[x]+dis[y]-2*dis[lca(x,y)];\n}\nset<int>::iterator it;\nvoid ins(int x){\n\tit=s.insert(x).first;int l=*(--it);++it;++it;\n\tint r=((it==s.end())?*s.begin():*it);\n\tsum+=dist(l,x)+dist(x,r)-dist(l,r);\n}\nvoid del(int x){\n\tit=s.find(x);int l=*(--it);++it;++it;\n\tint r=((it==s.end())?*s.begin():*it);\n\tsum-=dist(l,x)+dist(x,r)-dist(l,r);\n\t--it;s.erase(it);\n}\nint main(){\n\tint n,q;read(n),read(q);\n\tfor(int i=1;i<=n;++i){\n\t\tread(p[i]);\n\t\twhile(tp&&p[st[tp]]<p[i])--tp;\n\t\tdp[i]=dp[pa[i][0]=st[tp]]+1;st[++tp]=i;\n\t\tfor(int j=1;(1<<j)<=dp[i];++j)\n\t\t\tpa[i][j]=pa[pa[i][j-1]][j-1];\n\t}\n\tfor(int i=1;i<=n;++i)read(a[i]),val[i]+=a[i];\n\tfor(int i=1;i<=n;++i)read(b[i]),val[i]-=b[i],val[pa[i][0]]+=b[i];\n\tfor(int i=n;i>=1;--i)dis[pa[i][0]]+=min(0ll,dis[i]+=val[i]),dis[i]-=min(0ll,dis[i]);\n\tdis[0]+=val[0];for(int i=1;i<=n;++i)dis[i]+=dis[pa[i][0]];cnt[0]=1;s.insert(0);\n\twhile(q--){\n\t\tint x;read(x);\n\t\tif(vis[x]){\n\t\t\tvis[x]=false;\n\t\t\tif(!(--cnt[pa[x][0]]))\n\t\t\t\tdel(pa[x][0]);\n\t\t}\n\t\telse{\n\t\t\tvis[x]=true;\n\t\t\tif(!(cnt[pa[x][0]]++))\n\t\t\t\tins(pa[x][0]);\n\t\t}\n\t\twrite(sum/2+dis[0]),pc('\\n');\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1496",
    "index": "A",
    "title": "Split it!",
    "statement": "Kawashiro Nitori is a girl who loves competitive programming.\n\nOne day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.\n\nGiven a string $s$ and a parameter $k$, you need to check if there exist $k+1$ non-empty strings $a_1,a_2...,a_{k+1}$, such that $$s=a_1+a_2+\\ldots +a_k+a_{k+1}+R(a_k)+R(a_{k-1})+\\ldots+R(a_{1}).$$\n\nHere $+$ represents concatenation. We define $R(x)$ as a reversed string $x$. For example $R(abcd) = dcba$. Note that in the formula above the part $R(a_{k+1})$ is intentionally skipped.",
    "tutorial": "If $k=0$ or $s[1,k]+s[n-k+1,n]$ is a palindrome, the answer is yes. Otherwise, the answer is no. Note that when $2k=n$, the answer is no, too. The time complexity is $O(n+k)$ for each test case.",
    "code": "#include <bits/stdc++.h>\n \n#define debug(...) fprintf(stderr ,__VA_ARGS__)\n#define __FILE(x)\\\n\tfreopen(#x\".in\" ,\"r\" ,stdin);\\\n\tfreopen(#x\".out\" ,\"w\" ,stdout)\n#define LL long long\n \nconst int MX = 100 + 23;\nconst LL MOD = 998244353;\n \nint read(){\n\tchar k = getchar(); int x = 0;\n\twhile(k < '0' || k > '9') k = getchar();\n\twhile(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();\n\treturn x;\n}\n \nchar s[MX];\nvoid solve(){\n\tint n = read() ,k = read();\n\tscanf(\"%s\" ,s);\n\tint ok = 1;\n\tfor(int i = 0 ; i < k ; ++i)\n\t\tok = ok && s[i] == s[n - i - 1];\n\tputs(ok && k * 2 < n ? \"YES\" : \"NO\");\n}\n \nint main(){\n\tint T = read();\n\tfor(int i = 1 ; i <= T ; ++i){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1496",
    "index": "B",
    "title": "Max and Mex",
    "statement": "You are given a multiset $S$ initially consisting of $n$ distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.\n\nYou will perform the following operation $k$ times:\n\n- Add the element $\\lceil\\frac{a+b}{2}\\rceil$ (rounded up) into $S$, where $a = \\operatorname{mex}(S)$ and $b = \\max(S)$. If this number is already in the set, it is added again.\n\nHere $\\operatorname{max}$ of a multiset denotes the maximum integer in the multiset, and $\\operatorname{mex}$ of a multiset denotes the smallest non-negative integer that is not present in the multiset. For example:\n\n- $\\operatorname{mex}(\\{1,4,0,2\\})=3$;\n- $\\operatorname{mex}(\\{2,5,1\\})=0$.\n\nYour task is to calculate the number of \\textbf{distinct} elements in $S$ after $k$ operations will be done.",
    "tutorial": "Let $a=\\max(S),b=\\operatorname{mex}(S)$. When $k=0$, the answer is $n$. Otherwise if $b>a$, then $b=a+1$ , so $\\lceil\\frac{a+b}{2}\\rceil=b$ . It's not hard to find out that $\\max(S\\cup\\{b\\})=b,\\operatorname{mex}(S\\cup\\{b\\})=b+1$, so the set $S$ always satisfies $\\max(S)+1=\\operatorname{mex}(S)$. So the answer is $n+k$ when $b=a+1$. Otherwise $b<a$. So $b<a \\Rightarrow 2b<a+b\\Rightarrow \\frac{a+b}{2}>b\\Rightarrow\\lceil\\frac{a+b}{2}\\rceil>b$. In that case $\\operatorname{mex}(S)=b$ is always true. So the element we add in all operations is always $\\lceil\\frac{a+b}{2}\\rceil$. Just check whether it is in $S$ at first. The time complexity is $O(n)$ or $O(n \\log n)$ for each test case depending on your implementation.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#define ch() getchar()\n#define pc(x) putchar(x)\nusing namespace std;\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[65];int cnt=0;\n\tif(x<0)pc('-'),x=-x;\n\tq[++cnt]=x%10,x/=10;\n\twhile(x)\n\t\tq[++cnt]=x%10,x/=10;\n\twhile(cnt)pc(q[cnt--]+'0');\n}\nconst int maxn=100005;\nint vis[maxn],a[maxn];\nint main(){\n\tint T;read(T);\n\twhile(T--){\n\t\tint n,k,MEX=0,MAX=0;\n\t\tread(n),read(k);\n\t\tfor(int i=1;i<=n;++i){\n\t\t\tread(a[i]);\n\t\t\tif(a[i]<=n)vis[a[i]]=true;\n\t\t\tMAX=max(MAX,a[i]);\n\t\t}\n\t\twhile(vis[MEX])++MEX;\n\t\tfor(int i=1;i<=n;++i){\n\t\t\tif(a[i]<=n)vis[a[i]]=false;\n\t\t}\n\t\tint MCX=(MEX+1+MAX)/2;\n\t\tif(MCX>MAX)write(n+k);\n\t\telse{\n\t\t\tint ok=false;\n\t\t\tfor(int i=1;i<=n;++i)\n\t\t\t\tok|=(a[i]==MCX);\n\t\t\twrite(n+((k>0)&&!ok));\n\t\t}\n\t\tpc('\\n');\n\t}\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1497",
    "index": "A",
    "title": "Meximization",
    "statement": "You are given an integer $n$ and an array $a_1, a_2, \\ldots, a_n$. You should reorder the elements of the array $a$ in such way that the sum of $\\textbf{MEX}$ on prefixes ($i$-th prefix is $a_1, a_2, \\ldots, a_i$) is maximized.\n\nFormally, you should find an array $b_1, b_2, \\ldots, b_n$, such that the sets of elements of arrays $a$ and $b$ are equal (it is equivalent to array $b$ can be found as an array $a$ with some reordering of its elements) and $\\sum\\limits_{i=1}^{n} \\textbf{MEX}(b_1, b_2, \\ldots, b_i)$ is maximized.\n\n$\\textbf{MEX}$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.\n\nFor example, $\\textbf{MEX}(\\{1, 2, 3\\}) = 0$, $\\textbf{MEX}(\\{0, 1, 2, 4, 5\\}) = 3$.",
    "tutorial": "To maximize the sum of $\\textbf{MEX}$ on prefixes we will use a greedy algorithm. Firstly we put all unique elements in increasing order to get maximal $\\textbf{MEX}$ on each prefix. It is easy to see that replacing any two elements after that makes both $\\textbf{MEX}$ and sum of $\\textbf{MEX}$ less. In the end we put all elements that are not used in any order because $\\textbf{MEX}$ will not change and will still be maximal.",
    "code": "// один манул\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (int i = 0; i < n; ++i) cin >> a[i];\n        sort(a.begin(), a.end());\n        vector<int> b;\n        for (int i = 0; i < n; i++) {\n            if (i == 0 || a[i] != a[i - 1]) {\n                b.emplace_back(a[i]);\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            if (i > 0 && a[i] == a[i - 1]) {\n                b.emplace_back(a[i]);\n            }\n        }\n        for (auto x : b) cout << x << ' ';\n        cout << '\\n';\n    }\n    return 0;\n    cout << \"amogus\";\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1497",
    "index": "B",
    "title": "M-arrays",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$ consisting of $n$ positive integers and a positive integer $m$.\n\nYou should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.\n\nLet's call an array $m$-divisible if for each two adjacent numbers in the array (two numbers on the positions $i$ and $i+1$ are called adjacent for each $i$) their sum is divisible by $m$. An array of one element is $m$-divisible.\n\nFind the smallest number of $m$-divisible arrays that $a_1, a_2, \\ldots, a_n$ is possible to divide into.",
    "tutorial": "Let's take each number modulo $m$. Now let $cnt_x$ be the amount of $x$ in array $a$. If $cnt_0 \\neq 0$, then all $0$ should be put in a single array, answer increases by $1$. For each number $x \\neq 0$ we put it in an array $x, m - x, x, m - x, \\dots$ In this array the amount of $x$ and the amount of $m - x$ should differ not more than by $1$, that's why we need to make $max(0, |cnt_x - cnt_{m-x}| - 1)$ arrays, containing a single number ($x$ or $m - x$) that is more common.",
    "code": "//два манула\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        map<int, int> cnt;\n        while (n--) {\n            int x;\n            cin >> x;\n            cnt[x % m]++;\n        }\n        int ans = 0;\n        for (auto &c : cnt) {\n            if (c.first == 0) ans++;\n            else if (2 * c.first == m) {\n                ans++;\n            } else if (2 * c.first < m || cnt.find(m - c.first) == cnt.end()) {\n                int x = c.second, y = cnt[m - c.first];\n                ans += 1 + max(0, abs(x - y) - 1);\n            }\n        }\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1497",
    "index": "C1",
    "title": "k-LCM (easy version)",
    "statement": "\\textbf{It is the easy version of the problem. The only difference is that in this version $k = 3$.}\n\nYou are given a positive integer $n$. Find $k$ positive integers $a_1, a_2, \\ldots, a_k$, such that:\n\n- $a_1 + a_2 + \\ldots + a_k = n$\n- $LCM(a_1, a_2, \\ldots, a_k) \\le \\frac{n}{2}$\n\nHere $LCM$ is the least common multiple of numbers $a_1, a_2, \\ldots, a_k$.\n\nWe can show that for given constraints the answer always exists.",
    "tutorial": "If $n$ is odd, then the answer is $(1, \\lfloor \\frac{n}{2} \\rfloor, \\lfloor \\frac{n}{2} \\rfloor)$ If $n$ is even, but is not a multiple of $4$, then the answer is $(\\frac{n}{2} - 1, \\frac{n}{2} - 1, 2)$. If $n$ is a multiple of $4$, then the answer is $(\\frac{n}{2}, \\frac{n}{4}, \\frac{n}{4})$.",
    "code": "// три манула\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n, k;\n        cin >> n >> k;\n        if (n % 2) cout << 1 << ' ' << n / 2 << ' ' << n / 2 << '\\n';\n        else if (n % 2 == 0 && n % 4) cout << 2 << ' ' << n / 2 - 1 << ' ' << n / 2  - 1 << '\\n';\n        else cout << n / 2 << ' ' << n / 4 << ' ' << n / 4 << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1497",
    "index": "C2",
    "title": "k-LCM (hard version)",
    "statement": "\\textbf{It is the hard version of the problem. The only difference is that in this version $3 \\le k \\le n$.}\n\nYou are given a positive integer $n$. Find $k$ positive integers $a_1, a_2, \\ldots, a_k$, such that:\n\n- $a_1 + a_2 + \\ldots + a_k = n$\n- $LCM(a_1, a_2, \\ldots, a_k) \\le \\frac{n}{2}$\n\nHere $LCM$ is the least common multiple of numbers $a_1, a_2, \\ldots, a_k$.\n\nWe can show that for given constraints the answer always exists.",
    "tutorial": "In this solution we will reuse the solution for $k = 3$. The answer will be $1, 1, \\ldots, 1$ ($k - 3$ times) and the solution $a, b, c$ of the easy version for $n - k + 3$. $(1 + 1 + \\ldots + 1) + (a + b + c) = (k - 3) + (n - k - 3) = n$. Also $LCM(1, 1, \\ldots, 1, a, b, c) = LCM(a, b, c) \\le \\frac{n - k + 3}{2} \\le \\frac{n}{2}$.",
    "code": "// четыре манула\n#include <bits/stdc++.h>\nusing namespace std;\n\nvector<int> solve3(int n) {\n    if (n % 2 == 1) return {1, n / 2, n / 2};\n    if (n % 4 == 0) return {n / 2, n / 4, n / 4};\n    if (n % 2 == 0) return {2, n / 2 - 1, n / 2 - 1};\n}\n\nint main() {\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n, k;\n        cin >> n >> k;\n        vector<int> added = solve3(n - k + 3);\n        for (int i = 0; i < k; ++i) {\n            cout << (i <3 ? added[i] : 1) << ' '; // <3\n        }\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1497",
    "index": "D",
    "title": "Genius",
    "statement": "\\textbf{Please note the non-standard memory limit.}\n\nThere are $n$ problems numbered with integers from $1$ to $n$. $i$-th problem has the complexity $c_i = 2^i$, tag $tag_i$ and score $s_i$.\n\nAfter solving the problem $i$ it's allowed to solve problem $j$ if and only if $\\text{IQ} < |c_i - c_j|$ and $tag_i \\neq tag_j$. After solving it your $\\text{IQ}$ changes and becomes $\\text{IQ} = |c_i - c_j|$ and you gain $|s_i - s_j|$ points.\n\nAny problem can be the first. You can solve problems in any order and as many times as you want.\n\nInitially your $\\text{IQ} = 0$. Find the maximum number of points that can be earned.",
    "tutorial": "Let's consider a graph where vertexes are problems and there is an edge $\\{i, j\\}$ between vertexes $i$ and $j$ with weight $|c_i - c_j|$. Each edge has a unique weight. Let's prove that. Let's assume that $weight = |2^i - 2^j|$ and $i > j$. Then in binary form $weight$ has its $k$-th bit set true if and only if $j \\le k < i$. Then for each unique pair $\\{i, j\\}$ $weight$ is unique too since the corners of a subsegment with true bits are unique. Let $dp_i$ be the maximal amount of points that may be earned ending with problem $i$. Initially $dp_i = 0$ for each $1 \\le i \\le n$. Let's consider all edges in increasing order (because $\\text{IQ}$ should increase). To do that we can consider $j$ in increasing order from $2$ to $n$ and then $i$ in decreasing order from $j - 1$ to $1$. It is also explained by the binary form of the $weight$. Now let's relax $dp$ values. When we consider an edge $\\{i, j\\}, tag_i \\neq tag_j$ we try to solve problem $i$ after solving $dp_j$ problems ending with $j$, and problem $i$ after solving $dp_i$ problems ending with $i$. It means that $dp_i = max(dp_i, dp_j + p), dp_j = max(dp_j, dp_i + p)$ at the same time, where $p = |s_i - s_j|$. After considering all edges the answer is the maximal value among all $dp$ values.",
    "code": "// пять манулов\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n;\n        cin >> n;\n        vector<long long> s(n), tag(n), dp(n, 0);\n        for (int i = 0; i < n; ++i) cin >> tag[i];\n        for (int i = 0; i < n; ++i) cin >> s[i];\n        for (int j = 1; j < n; ++j) {\n            for (int i = j - 1; i >= 0; --i) {\n                if (tag[i] == tag[j]) continue;\n                long long dpi = dp[i], dpj = dp[j], p = abs(s[i] - s[j]);\n                dp[i] = max(dp[i], dpj + p);\n                dp[j] = max(dp[j], dpi + p);\n            }\n        }\n        cout << *max_element(dp.begin(), dp.end()) << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1497",
    "index": "E1",
    "title": "Square-Free Division (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is that in this version $k = 0$.}\n\nThere is an array $a_1, a_2, \\ldots, a_n$ of $n$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.\n\nMoreover, it is allowed to do at most $k$ such operations before the division: choose a number in the array and change its value to any positive integer. But in this version $k = 0$, so it is not important.\n\nWhat is the minimum number of continuous segments you should use if you will make changes optimally?",
    "tutorial": "For factorization of $x = p_1^{q_1} \\cdot p_2^{q_2} \\cdot \\cdots \\cdot p_k^{q_k}$ let's define $mask(x) = p_1^{q_1 \\bmod 2} \\cdot p_2^{q_2 \\bmod 2} \\cdot \\cdots \\cdot p_m^{q_m \\bmod 2}$. After that it is easy to see that $x \\cdot y$ is a perfect square if and only if $mask(x) = mask(y)$. Now let's say $a_i = mask(a_i)$ for all $1 \\le i \\le n$. The problem we need to solve is: split the array into minimal amount of non-intersecting subsegments so that on each subsegment all numbers are different. Since $k = 0$ we can do that using a greedy idea. If we consider an element that has not been in our current segment, then we add it to the segment. If it's already taken, then we should end our current segment and start a new one.",
    "code": "// шесть манулов\n#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXA = 1e7;\n\nvector<int> primes;\nint mind[MAXA + 1];\n\nint main() {\n\n    for (int i = 2; i <= MAXA; ++i) {\n        if (mind[i] == 0) {\n            primes.emplace_back(i);\n            mind[i] = i;\n        }\n        for (auto &x : primes) {\n            if (x > mind[i] || x * i > MAXA) break;\n            mind[x * i] = x;\n        }\n    }\n    \n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n, k;\n        cin >> n >> k;\n        vector<int> a(n, 1);\n        for (int i = 0; i < n; ++i) {\n            int x;\n            cin >> x;\n            int cnt = 0, last = 0;\n            while (x > 1) {\n                int p = mind[x];\n                if (last == p) {\n                    ++cnt;\n                } else {\n                    if (cnt % 2 == 1) a[i] *= last;\n                    last = p;\n                    cnt = 1;\n                }\n                x /= p;\n            }\n            if (cnt % 2 == 1) a[i] *= last;\n        }\n        \n        int L = 0, ans = 1;\n        map<int, int> last;\n        for (int i = 0; i < n; ++i) {\n            if (last.find(a[i]) != last.end() && last[a[i]] >= L) {\n                ++ans;\n                L = i;\n            }\n            last[a[i]] = i;\n        }\n        cout << ans << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1497",
    "index": "E2",
    "title": "Square-Free Division (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $0 \\leq k \\leq 20$.}\n\nThere is an array $a_1, a_2, \\ldots, a_n$ of $n$ positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.\n\nMoreover, it is allowed to do at most $k$ such operations before the division: choose a number in the array and change its value to any positive integer.\n\nWhat is the minimum number of continuous segments you should use if you will make changes optimally?",
    "tutorial": "Let's use the same definitions as in tutorial of E1. So after making $a_i = mask(a_i)$ for all $1 \\le i \\le n$ we need to split the whole array into minimal amount of contiguous subsegments with all different elements. Also, we can change $k$ elements how we want. Firstly, for each $1 \\le i \\le n$ and $0 \\le j \\le k$ let's find $left_{i,j}$ - such minimal index $l$, so that after making $j$ changes the segment $a_l, a_{l + 1}, \\ldots, a_i$ contains only distinct values. For fixed $j$ if $i$ is increased then $left_{i,j}$ increases, too, that's why for fixed $j$ we can use the two pointers technique. This allows us to calculate $left_{i,j}$ in $O(n \\cdot k)$. Now for each $1 \\le i \\le n$ and $0 \\le j \\le k$ let's calculate $dp_{i,j}$ - the minimal amount of contiguous subsegments that prefix $a_1, a_2, \\ldots, a_i$ is possible to divide into after making $j$ changes. For each $j$ let's consider $0 \\le x \\le j$ - the amount of changes on the last subsegment. Let's say that $l = left_{i,x}$ then $dp_{i,j} = min(dp_{i,j}, dp_{l - 1,j-x} + 1)$. This is done in $O(n \\cdot k^2)$ so the total complexity of the solution after making $a_i = mask(a_i)$ is $O(n \\cdot k^2)$.",
    "code": "// семь манулов\n#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1e9 + 1;\nconst int MAXA = 1e7;\nvector<int> primes;\nint mind[MAXA + 1];\n\nint main() {\n    for (int i = 2; i <= MAXA; ++i) {\n        if (mind[i] == 0) {\n            primes.emplace_back(i);\n            mind[i] = i;\n        }\n        for (auto &x : primes) {\n            if (x > mind[i] || x * i > MAXA) break;\n            mind[x * i] = x;\n        }\n    }\n    vector<int> cnt(MAXA + 1);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, k;\n        cin >> n >> k; // уже k манулов\n        vector<int> a(n, 1);\n        for (int i = 0; i < n; ++i) {\n            int x;\n            cin >> x;\n            int cnt = 0, last = 0;\n            while (x > 1) {\n                int p = mind[x];\n                if (last == p) {\n                    ++cnt;\n                } else {\n                    if (cnt % 2 == 1) a[i] *= last;\n                    last = p;\n                    cnt = 1;\n                }\n                x /= p;\n            }\n            if (cnt % 2 == 1) a[i] *= last;\n        }\n        vector<vector<int>> mnleft(n, vector<int>(k + 1));\n        for (int j = 0; j <= k; j++) {\n            int l = n, now = 0;\n            for (int i = n - 1; i >= 0; i--) {\n                while (l - 1 >= 0 && now + (cnt[a[l - 1]] > 0) <= j) {\n                    l--;\n                    now += (cnt[a[l]] > 0);\n                    cnt[a[l]]++;\n                }\n                mnleft[i][j] = l;\n                if (cnt[a[i]] > 1) now--;\n                cnt[a[i]]--;\n            }\n        }\n        vector<vector<int>> dp(n + 1, vector<int>(k + 1, INF));\n        for (auto &c : dp[0]) c = 0;\n        for (int i = 1; i <= n; i++) {\n            for (int j = 0; j <= k; j++) {\n                if (j > 0) dp[i][j] = dp[i][j - 1];\n                for (int lst = 0; lst <= j; lst++) {\n                    dp[i][j] = min(dp[i][j], dp[mnleft[i - 1][lst]][j - lst] + 1);\n                }\n            }\n        }\n        int ans = INF;\n        for (auto &c : dp.back()) ans = min(ans, c);\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1498",
    "index": "A",
    "title": "GCD Sum",
    "statement": "The $\\text{$gcdSum$}$ of a positive integer is the $gcd$ of that integer with its sum of digits. Formally, $\\text{$gcdSum$}(x) = gcd(x, \\text{ sum of digits of } x)$ for a positive integer $x$. $gcd(a, b)$ denotes the greatest common divisor of $a$ and $b$ — the largest integer $d$ such that both integers $a$ and $b$ are divisible by $d$.\n\nFor example: $\\text{$gcdSum$}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3$.\n\nGiven an integer $n$, find the smallest integer $x \\ge n$ such that $\\text{$gcdSum$}(x) > 1$.",
    "tutorial": "Can you think of the simplest properties that relate a number and its sum of digits? Note that if $X$ is a multiple of 3, then both $X$ as well as the sum of digits of $X$ are a multiple of 3! Can you put this property to use here? If $X$ is a multiple of 3, then $\\texttt{gcd-sum}(X) \\ge 3$. Therefore, we are guaranteed that at least every third number will satisfy the constraints required by our problem $(\\texttt{gcd-sum}(X) > 1)$. Therefore, for the input $n$, we can simply check which one of $n$, $n+1$, and $n+2$ has its gcd-sum $> 1$, and print the lowest of them. Note that you must take long long, as input integers exceed the range of int. Moreover, simply outputting $\\text{ceil}((n / 3) \\times 3)$ is incorrect as some non-multiples of three may also may have gcd-sum $> 1$, for example, 26.",
    "code": "from math import gcd\n\ndef valid(x):\n    return gcd(x, sum([ord(c) - ord('0') for c in str(x)])) != 1\n\nt = int(input())\n\nwhile t > 0:\n    t -= 1\n\n    n = int(input())\n    while not valid(n):\n        n += 1\n\n    print(n)",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1498",
    "index": "B",
    "title": "Box Fitting",
    "statement": "You are given $n$ rectangles, each of height $1$. Each rectangle's width is a power of $2$ (i. e. it can be represented as $2^x$ for some non-negative integer $x$).\n\nYou are also given a two-dimensional box of width $W$. Note that $W$ may or may not be a power of $2$. Moreover, $W$ is at least as large as the width of the largest rectangle.\n\nYou have to find the smallest height of this box, such that it is able to fit all the given rectangles. It is allowed to have some empty space left in this box after fitting all the rectangles.\n\nYou cannot rotate the given rectangles to make them fit into the box. Moreover, any two distinct rectangles must not overlap, i. e., any two distinct rectangles must have zero intersection area.\n\nSee notes for visual explanation of sample input.",
    "tutorial": "There can exist multiple optimal packings for a given set of rectangles. However, all of them can always be rearranged to follow a specific pattern, based on the rectangles' sizes. Can you show that it is always possible to replace a set of consecutive small blocks with a single large block? (of same or larger size) We follow a greedy strategy: Initialize height of box as 1. Initialize current layer size as $W$. Pick the largest available rectangle that can fit into the current layer, and place it there. Repeat until this layer cannot fit any more rectangles. If more rectangles remain, increment height by 1 and now repeat the last three steps. Else, output the current value of height. First count sort the given rectangles based on their widths. There can only be 20 distinct rectangle widths in the range $[1, 10^9]$, so the following works: The solution can be implemented by iterating $N$ times. At each iteration, step through the counts array and take the largest available rectangle that can fit into the current space. If no rectangle was able to fit, increment height by 1 and reset box width to $W$. This has complexity $\\mathcal{O}(n\\log(w_\\text{max}))$. It is also possible to implement the solution with a multiset and upper_bound, for a complexity of $\\mathcal{O}(n\\log(n))$. Store all rectangle sizes in a multiset. At each iteration, find using upper_bound the largest rectangle that can fit into the current space we have, and fit it in. If no rectangle can fit in this space, reset the space to maximum, increment height, and repeat. It is always possible to replace several smaller blocks with a single larger block if it is available. Because all blocks are powers of two, it must so happen that smaller powers of two will sum to a larger power. Therefore, we can always place a larger block first if it can be placed there. This elaborate proof isn't actually required for solving the problem. The intuition in the brief proof is sufficient for solving the problem. This proof is for correctness purpose only. Let's first note a property: if $a_1 + \\ldots + a_n>a_0$, then there exists some $i$ such that $a_1+ \\ldots +a_i=a_0$, when all $a_i$ are powers of 2 AND $a_1$ to $a_n$ is a non-increasing sequence (AND $a_1 <= a_0$, of course). Why is this so? You can take an example and observe this intuitively, this is a common property of powers of two. For example, $4+2+2+1+1>8$, but $4+2+2$ (prefix) $=8$. Formally: if $a_1 =a_0$, this property is trivially true. If $a_1 < a_0$, we can splilt $a_0=2^ka_1$ for some $k$ into $2^k$ parts and - by strong induction - claim this property holds. Let us now compare some optimal solution and our greedy solution. Before comparing, we first sort all blocks in each layer of the optimal solution in decreasing order. This does not affect the final answer but helps in our comparison. This comparison goes from bottom to top, left to right. Let us look at the first point of difference: when the block placed by us ($B_G$) is different from the block placed by the optimal solution ($B_O$). There are three cases. If $B_O > B_G$: this is impossible, as in our greedy solution, we are always placing the largest possible block. We wouldn't place $B_G$ in there if $B_O$ was also possible. If $B_O == B_G$: we have nothing to worry about (this isn't a point of difference) If $B_O < B_G$: let us assume that the optimal solution places several consecutive small blocks, and not just one $B_O$. Since the blocks are in decreasing order, none of them would be bigger than $B_G$. Note that either all of these blocks will sum to less than $B_G$ or a prefix of them will be exactly equal to $B_G$. In either case, we can swap them with one single large block $B_G$ (swapping with a $B_G$ which was placed in some higher layer in the optimal solution) Hence, in the last case, we have shown that any optimal solution (an arrangement of blocks) can be rearranged such that each layer fits the largest possible block first. This is also what is done in our greedy strategy. Therefore, with this proof by rearrangement, we conclude that our greedy strategy gives the same minimum height as that of the optimal answer. There is a binary search method to solve this problem. We binary search for the minimum height required. Given a height $h$ - how to check if it can fit all rectangles? We first preprocess the given array to construct a new array $c_i$ = number of rectangles of width $1 << i$. The size of this array is < 20. We iterate from largest width to smallest width. Let its width is $w_i$. Then, we know that it fits only $W / w_i$ times in one layer. Therefore, with height $h$, the box can only fit in $f_i = h \\times (W / w_i)$. So, we can say that if $f_i < c_i$, then this height is insufficient. Therefore, we now know that for any $i$, if $f_i < c_i$, then the height is insufficient. Do we need more conditions to provably state that the given height is sufficient? Yes! We also need to check if we can fit in the $i$-th block in combination with tthe $i+1$-th block. That is, when checking if the $i$-th block has enough space, we need to account for the space that has already been used by the $i + 1$-th block. So, we need to update $c_i = c_i + 2\\times c_{i+1} + 4\\times c_{i+2} \\ldots$. Therefore, we only need to compute the suffix sum $c_i$ like so and then check the above conditions. Complexity is $\\mathcal{O}(n+\\log(w_{max})\\log(n))$. As we understood in the proof, this solution only works when it's guaranteed that smaller blocks will always exactly sum to any larger block. Therefore, if the blocks are not powers of two, this guarantee does not hold. The following counterexample suffices: As you can see here the smaller blocks are not guaranteed to sum to the larger block (no prefix of $4,3,3$ sums to $6$). Our greedy solution gives minimum height 3, but best possible minimum height is $2$ (first layer: $6,4,3$, second layer: $6,4,3$)",
    "code": "#include <array>\n#include <cassert>\n#include <cmath>\n#include <iostream>\nusing namespace std;\n\n#define PW 20\narray<int, PW> arr;\nint n, w;\n\nbool valid(int height) {\n    for (int pw = 0; pw < PW; pw++) {\n        long long units_i_have = 1ll * height * (w / (1 << pw));\n        if (units_i_have < arr[pw]) return false;\n    }\n\n    return true;\n}\n\nint main() {\n    int t; cin >> t;\n\n    while (t--) {\n        cin >> n >> w;\n\n        for (int i = 0; i < PW; i++) arr[i] = 0;\n\n        for (int _ = 0; _ < n; _++) {\n            int w; cin >> w;\n            arr[log2(w)] += 1;\n        }\n\n        // suffix cumulative count\n        for (int i = PW - 2; i >= 0; i--) arr[i] += 2 * arr[i + 1];\n\n        int beg = 1, end = n, ans = -1;\n        while (beg <= end) {\n            int mid = (beg + end) / 2;\n\n            if (valid(mid)) {\n                end = mid - 1;\n                ans = mid;\n            } else {\n                beg = mid + 1;\n            }\n        }\n\n        assert(ans != -1);\n        cout << ans << endl;\n    }\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1498",
    "index": "C",
    "title": "Planar Reflections",
    "statement": "Gaurang has grown up in a mystical universe. He is faced by $n$ consecutive 2D planes. He shoots a particle of decay age $k$ at the planes.\n\nA particle can pass through a plane directly, however, every plane produces an identical copy of the particle going in the opposite direction with a decay age $k-1$. If a particle has decay age equal to $1$, it will NOT produce a copy.\n\nFor example, if there are two planes and a particle is shot with decay age $3$ (towards the right), the process is as follows: (here, $D(x)$ refers to a single particle with decay age $x$)\n\n- the first plane produces a $D(2)$ to the left and lets $D(3)$ continue on to the right;\n- the second plane produces a $D(2)$ to the left and lets $D(3)$ continue on to the right;\n- the first plane lets $D(2)$ continue on to the left and produces a $D(1)$ to the right;\n- the second plane lets $D(1)$ continue on to the right ($D(1)$ cannot produce any copies).\n\nIn total, the final multiset $S$ of particles is $\\{D(3), D(2), D(2), D(1)\\}$. (See notes for visual explanation of this test case.)\n\nGaurang is unable to cope up with the complexity of this situation when the number of planes is too large. Help Gaurang find the size of the multiset $S$, given $n$ and $k$.\n\nSince the size of the multiset can be very large, you have to output it modulo $10^9+7$.\n\nNote: Particles can go back and forth between the planes without colliding with each other.",
    "tutorial": "We can use dynamic programming to store the state of the simulation at a given time. Therefore, we can simulate the entire situation by reusing the dp states. I will describe the most intuitive solution. Naturally, looking at the constraints as well as at the output that is required, we can store a 3-state dp: dp[n][k][2]. Here, dp[n][k][d] indicates the total number of particles (at the end of the simulation) when one particle of decay age $k$ hits the $n$-th plane in the direction $d$. ($d$ is either $0$ or $1$, and indicates the direction (left/right) in which the particle is going) There can be two directions, $N$ planes and maximum decay age is $K$. So, this dp requires $2\\times1000\\times1000\\times4$ bytes $\\approx 24MB$ which is well within our memory constraints. How to update the DP states? If $k = 1$, the value of dp[n][1][d] for any $n$ or $d$ is obviously $1$ (as no copies are produced). So, let us consider a particle $P$ with $k>1$. This particle $P$ produces a copy $P'$ going in the opposite direction. We can count the number of particles produced by $P'$ as dp[n - 1][k - 1][1 - d], as it hits the previous plane with a smaller decay age and in the opposite direction. Moreover, the particle $P$ itself hits the next plane and continues to produce more stuff. We can calculate its number of particles produced as dp[n + 1][k][d], as it hits the next plane with the same decay age and the same direction! Finally, we can combine these two values to get the value of dp[n][k][d]. We can implement this is easily as a recursive dp with memoization. At each state, we only need to iterate in the correct order (in one case, from right to left, and in the other, from left to right), and update states as required. Look at the implementation for more details. The total complexity of this algorithm is $\\mathcal{O}(nk)$ Obviously, there exist much better solutions which do not use a third state and are much sleaker. However, I wanted to describe the simplest idea required to solve the problem.",
    "code": "mod = int(1e9 + 7)\n\ndef iter_solver(N, K):\n    dp = [[[-1 for _ in range(2)] for __ in range(K + 1)] for ___ in range(N + 1)]\n    for i in range(1, N + 1):\n        dp[i][1][0] = dp[i][1][1] = 1\n\n    for k in range(2, K + 1):\n        # forward dir\n        for n in range(N, 0, -1):\n            ans = 2\n\n            if n < N:\n                ans += dp[n + 1][k][0] - 1\n                ans %= mod\n\n            if n > 1:\n                ans += dp[n - 1][k - 1][1] - 1\n                ans %= mod\n\n            dp[n][k][0] = ans\n\n        # backward dir\n        for n in range(1, N + 1):\n            ans = 2\n\n            if n < N:\n                ans += dp[n + 1][k - 1][0] - 1\n                ans %= mod\n\n            if n > 1:\n                ans += dp[n - 1][k][1] - 1\n                ans %= mod\n\n            dp[n][k][1] = ans\n\n    return dp[1][K][0]\n\nt = int(input())\n\nwhile t > 0:\n    t -= 1\n\n    n, k = list(map(int, input().split()))\n\n    print(iter_solver(n, k))",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1498",
    "index": "D",
    "title": "Bananas in a Microwave",
    "statement": "You have a malfunctioning microwave in which you want to put some bananas. You have $n$ time-steps before the microwave stops working completely. At each time-step, it displays a new operation.\n\nLet $k$ be the number of bananas in the microwave currently. Initially, $k = 0$. In the $i$-th operation, you are given three parameters $t_i$, $x_i$, $y_i$ in the input. Based on the value of $t_i$, you must do one of the following:\n\n\\textbf{Type 1}: ($t_i=1$, $x_i$, $y_i$) — pick an $a_i$, such that $0 \\le a_i \\le y_i$, and perform the following update $a_i$ times: $k:=\\lceil (k + x_i) \\rceil$.\n\n\\textbf{Type 2}: ($t_i=2$, $x_i$, $y_i$) — pick an $a_i$, such that $0 \\le a_i \\le y_i$, and perform the following update $a_i$ times: $k:=\\lceil (k \\cdot x_i) \\rceil$.\n\nNote that \\textbf{$x_i$ can be a fractional value}. See input format for more details. Also, $\\lceil x \\rceil$ is the smallest integer $\\ge x$.\n\nAt the $i$-th time-step, you must apply the $i$-th operation exactly once.\n\nFor each $j$ such that $1 \\le j \\le m$, output the earliest time-step at which you can create \\textbf{exactly} $j$ bananas. If you cannot create \\textbf{exactly} $j$ bananas, output $-1$.",
    "tutorial": "We have a brute force $\\mathcal{O}(N\\cdot M^2)$ solution. At every timestep $t$, for each banana $b_i$ that has already been reached previously, apply this timestep's operation $y_t$ times on $b_i$. For all the $y_t$ bananas reachable from $b_i$, update their minimum reachability time if they hadn't been reached previously. Why is this correct? Simply because we are simulating each possible step of the algorithm exactly as it is described. Therefore, we cannot get an answer that's better or worse than that of the optimal solution. Observe if we can reduce our search space when we visit nodes that have already been visited previously. Let us take an example. We have some timestep $t,x,y = 1,5,10$. If we start visiting from $k=10$, we will visit $k=15,20,\\ldots,55,60$. Let us say that $k=40$ was an already visited state. Do we now need to continue visiting $k=45,\\ldots,60$ or can we stop our search here? We can actually stop our search as soon as we reach a previouly visited node! Why is this so? This is because - within the same iteration - that already visited node will once again start its own search, and will hit all the points that we were going to hit, and some more! For example, let us say we would reach points $a, a\\cdot x, a\\cdot x^2, \\ldots, a\\cdot x^{y-1}$. Now, assume that $a\\cdot x^5$ had been previously reached, then it is better to stop at $a\\cdot x^5$, as this node itself will reach $a\\cdot x^5, a\\cdot x^6, \\ldots, a\\cdot x^{y-2}, a\\cdot x^{y-1},a\\cdot x^{y}, \\ldots, a\\cdot x^{5+y-1}$. Note the latter range includes as a prefix the entire remaining suffix of the former range! Therefore, in this approach, nodes that would have been visited, will eventually be visited, and get assigned the minimum timestamp. We can implement the optimized solution by simply adding an extra if already_visited[k]: break to our inner loop. Yup, really, that's all it takes to solve this question! Complexity analysis: We can show that each node is visited at most twice: an unvisited node is reached atmost once, whereas a visited node is reached atmost twice (once during the main loop and once when searching from the immediately previous visited node) There are $N$ iterations, and in each iteration, each of the $M$ nodes is visited at most twice. Therefore, the total complexity is $\\mathcal{O}(2NM)$. Integer overflows: $x'$ does not fit in integer range Out of bounds access: simulating the $y_t$ steps of the algorithm even when $k$ exceeds $M$ prematurely",
    "code": "import sys\ninput = lambda: sys.stdin.readline().rstrip()\n\nDIV = int(1e5)\n\ndef ceil(x, y):\n    return (x + y - 1) // y\n\nT, M = list(map(int, input().split()))\n\nis_seen = [0 for _ in range(M + 1)]\nis_seen[0] = 1\nanswer = [-1 for _ in range(M + 1)]\nanswer[0] = 0\n\no = 0\n\nfor timestep in range(1, T + 1):\n    t, x, y = list(map(int, input().split()))\n\n    def operation(val):\n        if t == 1:\n            return curr + ceil(x, DIV)\n        else:\n            return ceil(curr * x, DIV)\n\n    k = 0\n\n    setting = []\n\n    while k <= M:\n        if is_seen[k]:\n            curr = k\n\n            i = 0\n            while i < y:\n                i += 1\n\n                o += 1\n\n                curr = operation(curr)\n\n                if curr > M:\n                    break\n                if is_seen[curr]:\n                    break\n\n                setting.append(curr)\n                answer[curr] = timestep\n\n        k += 1\n\n    for idx in setting:\n        is_seen[idx] = 1\n\nsys.stdout.write(\" \".join(map(str, answer[1:])))\n",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1498",
    "index": "E",
    "title": "Two Houses",
    "statement": "\\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.\n\nThere is a city in which Dixit lives. In the city, there are $n$ houses. There is \\textbf{exactly one directed road between every pair of houses.} For example, consider two houses A and B, then there is a directed road either from A to B or from B to A but not both. The number of roads leading to the $i$-th house is $k_i$.\n\nTwo houses A and B are bi-reachable if A is reachable from B \\textbf{and} B is reachable from A. We say that house B is reachable from house A when there is a path from house A to house B.\n\nDixit wants to buy two houses in the city, that is, one for living and one for studying. Of course, he would like to travel from one house to another. So, he wants to find a pair of bi-reachable houses A and B. Among all such pairs, he wants to choose one with the maximum value of $|k_A - k_B|$, where $k_i$ is the number of roads leading to the house $i$. If more than one optimal pair exists, any of them is suitable.\n\nSince Dixit is busy preparing CodeCraft, can you help him find the desired pair of houses, or tell him that no such houses exist?\n\nIn the problem input, you are \\textbf{not} given the direction of each road. You are given — for each house — only the number of incoming roads to that house ($k_i$).\n\nYou are allowed to ask only one type of query from the judge: give two houses A and B, and the judge answers whether B is reachable from A. There is \\textbf{no upper limit on the number of queries}. But, \\textbf{you cannot ask more queries after the judge answers \"Yes\" to any of your queries.} Also, you cannot ask the same query twice.\n\nOnce you have exhausted all your queries (or the judge responds \"Yes\" to any of your queries), your program must output its guess for the two houses and quit.\n\nSee the Interaction section below for more details.",
    "tutorial": "In this problem we have to output two nodes $a$ and $b$ such that there is a path from $a$ to $b$ and $b$ to $a$ and the absolute value of the difference of the indegree $(|k_a - k_b|)$ should be maximum. First of all, let us think of bireachability only i.e how to find two nodes $a$ and $b$ such that they are both reachable from each other? How can we verify this from the judge? Because if we ask $\"? \\ a \\ b\"$ i.e whether there is a path from $a$ to $b$ or not, then if the judge answers \"Yes\", we can't ask further queries. So we have to ask queries for those pairs $(a,b)$ for which we are sure that there is a path from $b$ to $a$. So how to ensure whether there is a path from $b$ to $a$ or not? The answer lies in the fact that the given graph is not an ordinary graph, it is a special one. For every pair of vertices in this graph, there is a directed edge. So this type of graph has some interesting properties which we are going to see now. Image how the compressed SCC of the graph will look like. For every pair of nodes of compressed SCC, there will be an edge, so it will have exactly one source, one sink and there would be only one possible topological sorting of this compressed SCC. Since there is an edge between every pair of nodes, for every pair of nodes in the compresses SCC also, there would be an edge. And we know that if there is an edge between node $a$ to node $b$, then node $a$ comes before node $b$ in the topological sort. So for every pair of nodes of compressed SCC, we know which node would come first in the topological sorting, so it would result in a unique topological sorting. Now we'll see one interesting and important property of this graph. Property: Consider two consecutive strongly connected components in the topological sorting, then all nodes present in the left component will have indegree strictly less than all nodes present in the right component. Here left denotes lower enumeration in the topological sorting. Consider two nodes $u$ and $v$ from the left component and right component respectively. Since the contribution to the indegree from the nodes which don't lie in these two components would be the same for both $u$ and $v$ (because $u$ and $v$ lie in adjacent components), we are ignoring it as we have to just compare their values. If we consider all the edges between the nodes of the left component and the right component, then all of them would be directed from the node in the left component to the node in the right component. So the node $v$ would have minimum indegree of $Size of Left Component$. The node $u$ would have the maximum indegree of $Size of Left Component - 1$. This is because there is no edge directed from the right component to the node $u$ and the maximum indegree will be when all other nodes in the left component have an edge directed towards node $u$. In that case, it would be $Size of Left Component -1$. So the indegree of $u$ is strictly less than the indegree of $v$. Since $u$ and $v$ are arbitrary nodes, it is true for all pairs of nodes. Using the above property we can argue that if indegree of node $a$ is greater than the indegree of node $b$, then node $a$ is reachable from node $b$. Because either node $a$ lies in the same SCC or to the SCC of higher enumeration in topological sorting. In both cases $a$ is reachable from $b$. So we can store all pairs of nodes $(a,b), 1 \\leq a \\leq n, 1 \\leq b \\leq n, a < b$ in an array and sort it according to decreasing order of absolute value of difference of indegrees i.e $|k_a - k_b|$. And if we pick a pair, let it be ($a$,$b$) and $indegree[b] > indegree[a]$, then we are sure that $b$ is reachable from $a$ so we need to check whether $a$ is reachable from $b$ or not, so we ask $\"? \\ b \\ a\"$ and if the judge responds by \"Yes\", then it means both $a$ and $b$ are reachable from each other. Since we were iterating in the decreasing order of $|k_a - k_b|$, we get the optimal answer. If the judge never outputs \"Yes\" in the whole process, then there is no pair of nodes that are reachable from each other. So we will output $\"? \\ 0 \\ 0\"$ Overall Complexity : $O(n^2 \\log_2 n)$",
    "code": "import sys\ninput = lambda: sys.stdin.readline().rstrip()\n\nn = int(input())\n\nindegs = list(map(int, input().split()))\n\npairs = []\nfor i in range(n):\n    for j in range(i + 1, n):\n        if indegs[i] > indegs[j]:\n            pairs.append((indegs[i] - indegs[j], (i, j)))\n        else:\n            pairs.append((indegs[j] - indegs[i], (j, i)))\n\n\npairs = sorted(pairs, reverse=True)\nl = len(pairs)\n\nfor _, nodes in pairs:\n    ni, nj = nodes\n\n    sys.stdout.write(f\"? {ni + 1} {nj + 1}\\n\")\n    sys.stdout.flush()\n\n    s = input()\n    if s == \"Yes\":\n        sys.stdout.write(f\"! {ni + 1} {nj + 1}\\n\")\n        exit(0)\n\nsys.stdout.write(\"! 0 0\\n\")",
    "tags": [
      "brute force",
      "graphs",
      "greedy",
      "interactive",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1498",
    "index": "F",
    "title": "Christmas Game",
    "statement": "Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has $n$ nodes (numbered $1$ to $n$, with some node $r$ as its root). There are $a_i$ presents are hanging from the $i$-th node.\n\nBefore beginning the game, a special integer $k$ is chosen. The game proceeds as follows:\n\n- Alice begins the game, with moves alternating each turn;\n- in any move, the current player may choose some node (for example, $i$) which has depth at least $k$. Then, the player picks some positive number of presents hanging from that node, let's call it $m$ $(1 \\le m \\le a_i)$;\n- the player then places these $m$ presents on the $k$-th ancestor (let's call it $j$) of the $i$-th node (the $k$-th ancestor of vertex $i$ is a vertex $j$ such that $i$ is a descendant of $j$, and the difference between the depth of $j$ and the depth of $i$ is exactly $k$). Now, the number of presents of the $i$-th node $(a_i)$ is decreased by $m$, and, correspondingly, $a_j$ is increased by $m$;\n- Alice and Bob both play optimally. The player unable to make a move loses the game.\n\n\\textbf{For each possible root} of the tree, find who among Alice or Bob wins the game.\n\nNote: The depth of a node $i$ in a tree with root $r$ is defined as the number of edges on the simple path from node $r$ to node $i$. The depth of root $r$ itself is zero.",
    "tutorial": "By the Sprague-Grundy theorem, we know that the current player has a winning strategy if $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n$ (xorsum of sizes of the existing piles) is non-zero. For a proof, read details on CP-algorithms. Let us classify nodes into odd or even depending on their depth relative to the root. Note that even steps do not affect the game state. Let us prove how: Let us say it's Alice's turn. If Alice moves some coins from an even step to an odd step, then Bob can move exactly those same coins from that odd step back to an even step. After this transition, once again it's Alice's move. In fact, we realize that Bob can \"revert\" every even->odd move by Alice. Therefore, if Alice wants to win, she has to play at least one odd->even move. Moves that go from even->odd do not affect the game state at all, as the other player can always play another move that reverts them. Therefore, we can say that any coins present on even steps will not change the game state. Let us now analyze what happens if some coins move from the odd steps to even steps. We know that any coins on even nodes will not contribute to the game state. In fact, we realize that it does not matter whether these coins were present on the even nodes before the game started or whether they came by on the even nodes during the game. Once they are on an even step, they no longer contribute to the game state. Hence, we can conclude that moving a coin from odd step to an even step is as good as taking a coin from the odd step and throwing it away. As we can see, we have effectively reduced the Nim game on tree to a linear nim game where only the odd positioned nodes determine the winning strategy. This is known as the staircase nim. The result is the following: the current player has a winning strategy if xorsum of all values at the odd steps is non-zero. In general $K$, we can extend this idea to: parity of $d' = \\lfloor \\frac d K \\rfloor$ where $d$ is the depth of this node (zero-indexed). All nodes - such that $d'$ is odd for them - will contribute to the final xorsum. Take a moment to digest this. How to calculate these xors? At each node $x$, we store a vector of size $D(n) = 2\\cdot K$ where $D(n)_i$ is the xorsum of all nodes having their depth = $i$ - relative to node $x$ - in the subtree of node $n$. How to propagate these values in a DFS? We know that the nodes at depth i is at depth i + 1 for my child nodes. So, we can simply cycle through them and update the values. Check the implementation for details.",
    "code": "n, k = list(map(int, input().split()))\nk2 = 2 * k\n\ndp = [[0 for _ in range(k2)] for _ in range(n + 1)]\nadj = [[] for _ in range(n + 1)]\n\nfor _ in range(n - 1):\n    _x, _y = list(map(int, input().split()))\n    adj[_x].append(_y)\n    adj[_y].append(_x)\n\na = [0] + list(map(int, input().split()))\n\nwin = [0 for _ in range(n + 1)]\n\nparent = [0 for _ in range(n + 1)]\n\n\ndef dfs(node):\n    global parent\n    global dp\n\n    stack = [node]\n\n    pass_num = [0 for _ in range(n + 1)]\n\n    while stack:\n        node = stack[-1]\n\n        pass_num[node] += 1\n\n        if pass_num[node] == 1:\n            for neigh in adj[node]:\n                if neigh == parent[node]:\n                    continue\n\n                parent[neigh] = node\n                stack.append(neigh)\n\n            continue\n\n        dp[node][0] = a[node]\n        stack.pop()\n\n        for neigh in adj[node]:\n            if neigh == parent[node]:\n                continue\n\n            for rem in range(1, k2):\n                dp[node][rem] ^= dp[neigh][rem - 1]\n\n            dp[node][0] ^= dp[neigh][k2 - 1]\n\n\ndef dfs2(node):\n    global win\n\n    stack = [[node, [0 for __ in range(k2)]]]\n\n    global dp\n\n    while stack:\n        node, prev_xors = stack[-1]\n        stack.pop()\n\n        final_xors = [x ^ y for x, y in zip(prev_xors, dp[node])]\n\n        for neigh in adj[node]:\n            if neigh == parent[node]:\n                continue\n\n            send_xors = [x for x in final_xors]\n            for i in range(1, k2):\n                send_xors[i] ^= dp[neigh][i - 1]\n            send_xors[0] ^= dp[neigh][k2 - 1]\n\n            send_xors = [send_xors[-1]] + send_xors[:-1]\n            stack.append([neigh, send_xors])\n\n        odd_xor = 0\n        for i in range(k, k2):\n            odd_xor ^= final_xors[i]\n\n        win[node] = 1 if odd_xor > 0 else 0\n\n\ndfs(1)\ndfs2(1)\nprint(\" \".join(list(map(str, win[1:]))))",
    "tags": [
      "bitmasks",
      "data structures",
      "dfs and similar",
      "dp",
      "games",
      "math",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1499",
    "index": "A",
    "title": "Domino on Windowsill",
    "statement": "You have a board represented as a grid with $2 \\times n$ cells.\n\nThe first $k_1$ cells on the first row and first $k_2$ cells on the second row are colored in white. All other cells are colored in black.\n\nYou have $w$ white dominoes ($2 \\times 1$ tiles, both cells are colored in white) and $b$ black dominoes ($2 \\times 1$ tiles, both cells are colored in black).\n\nYou can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.\n\nCan you place all $w + b$ dominoes on the board if you can place dominoes both horizontally and vertically?",
    "tutorial": "We can prove that if we have $k_1 + k_2$ white cells on the board then we can place any $w$ white dominoes as long as $2w \\le k_1 + k_2$. The proof is the following: if $k_1 \\ge k_2$ let's place one domino at position $((1, k_1 - 1), (1, k_1))$, otherwise let's place domino at position $((2, k_2 - 1), (2, k_2))$. Then we can solve the placement of $w - 1$ dominoes in $k_1 - 2$ cells in the first row and $k_2$ cells of the second row recursively (or, analogically, $k_1$ and $k_2 - 2$). At the end, either all dominoes are placed or $k_1 < 2$ and $k_2 < 2$. If $k_1 = 0$ or $k_2 = 0$ then, since $2w \\le k_1 + k_2$, then $w = 0$ or we successfully placed all dominoes. If $k_1 = 1$ and $k_2 = 1$ then we, possibly, need to place one domino more - and we can place it vertically. We can prove that we can place any $b$ dominoes as long as $2b \\le (n - k_1) + (n - k_2)$ in the same manner. As a result, all we need to check is that $2w \\le k_1 + k_2$ and $2b \\le (n - k_1) + (n - k_2)$.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (n, k1, k2) = readLine()!!.split(' ').map { it.toInt() }\n        val (w, b) = readLine()!!.split(' ').map { it.toInt() }\n\n        if (k1 + k2 >= 2 * w && (n - k1) + (n - k2) >= 2 * b)\n            println(\"YES\")\n        else\n            println(\"NO\")\n    }\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1499",
    "index": "B",
    "title": "Binary Removals",
    "statement": "You are given a string $s$, consisting only of characters '0' or '1'. Let $|s|$ be the length of $s$.\n\nYou are asked to choose some integer $k$ ($k > 0$) and find a sequence $a$ of length $k$ such that:\n\n- $1 \\le a_1 < a_2 < \\dots < a_k \\le |s|$;\n- $a_{i-1} + 1 < a_i$ for all $i$ from $2$ to $k$.\n\nThe characters at positions $a_1, a_2, \\dots, a_k$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $a$ should not be adjacent.\n\nLet the resulting string be $s'$. $s'$ is called sorted if for all $i$ from $2$ to $|s'|$ $s'_{i-1} \\le s'_i$.\n\nDoes there exist such a sequence $a$ that the resulting string $s'$ is sorted?",
    "tutorial": "There are several different ways to solve this problem. In my opinion, the two easiest solutions are: notice that, in the sorted string, there is a prefix of zeroes and a suffix of ones. It means that we can iterate on the prefix (from which we remove all ones), and remove all zeroes from the suffix we obtain. If we try to remove two adjacent characters, then we cannot use this prefix; if there is a substring 11 before the substring 00 in our string, then from both of the substrings, at least one character remains, so if the first occurrence of 11 is earlier than the last occurrence of 00, there is no answer. Otherwise, the answer always exists.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    string s;\n    cin >> s;\n    int i = s.find(\"11\");\n    int j = s.rfind(\"00\");\n    cout << (i != -1 && j != -1 && i < j ? \"NO\" : \"YES\") << endl;\n  }\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1499",
    "index": "C",
    "title": "Minimum Grid Path",
    "statement": "Let's say you are standing on the $XY$-plane at point $(0, 0)$ and you want to reach point $(n, n)$.\n\nYou can move only in two directions:\n\n- to the right, i. e. horizontally and in the direction that increase your $x$ coordinate,\n- or up, i. e. vertically and in the direction that increase your $y$ coordinate.\n\nIn other words, your path will have the following structure:\n\n- initially, you choose to go to the right or up;\n- then you go some \\textbf{positive integer} distance in the chosen direction (distances can be chosen independently);\n- after that you change your direction (from right to up, or from up to right) and repeat the process.\n\nYou don't like to change your direction too much, so you will make no more than $n - 1$ direction changes.\n\nAs a result, your path will be a polygonal chain from $(0, 0)$ to $(n, n)$, consisting of \\textbf{at most} $n$ line segments where each segment has positive integer length and vertical and horizontal segments alternate.\n\nNot all paths are equal. You have $n$ integers $c_1, c_2, \\dots, c_n$ where $c_i$ is the cost of the $i$-th segment.\n\nUsing these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of $k$ segments ($k \\le n$), then the cost of the path is equal to $\\sum\\limits_{i=1}^{k}{c_i \\cdot length_i}$ (segments are numbered from $1$ to $k$ in the order they are in the path).\n\nFind the path of the minimum cost and print its cost.",
    "tutorial": "Suppose we decided to make exactly $k - 1$ turns or, in other words, our path will consist of exactly $k$ segments. Since we should finish at point $(n, n)$ and vertical and horizontal segments alternates, then it means that $length_1 + length_3 + length_5 + \\dots = n$ and $legth_2 + length_4 + length_6 + \\dots = n$. From the other side we should minimize $\\sum\\limits_{i=1}^{k}{c_i \\cdot length_i}$. But it means that we can minimize $c_1 \\cdot length_1 + c_3 \\cdot length_3 + \\dots$ and $c_2 \\cdot length_2 + c_4 \\cdot length_4 + \\dots$ independently. How to minimize $c_1 \\cdot length_1 + c_3 \\cdot length_3 + \\dots$ if we know that $length_1 + length_3 + length_5 + \\dots = n$ and $length_i \\ge 1$? It's easy to prove that it's optimal to assign all $length_i = 1$ except minimum $c_i$ and assign to this minimum $c_i$ the remaining part $length_i = n - cntOdds + 1$. In other words, to calculate the optimal path consisting of $k$ segments, we need to know the sum of $c_i$ on odd and even positions among $c_1, \\dots, c_k$ and also minimum $c_i$ among odd and even positions. Then we can drive out the answer as a quite easy formula $sumOdd + minOdd \\cdot (n - cntOdd)$ $+$ $sumEven + minEven \\cdot (n - cntEven)$. Finally, we should iterate over all $k$ from $2$ to $n$ and find the minimum answer among all variants. It's easy to recalculate sums and minimums when we make transition form $k$ to $k + 1$. Complexity is $O(n)$.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val c = readLine()!!.split(' ').map { it.toInt() }\n\n        val mn = intArrayOf(1e9.toInt(), 1e9.toInt())\n        val rem = longArrayOf(n.toLong(), n.toLong())\n        var sum = 0L\n        var ans = 1e18.toLong()\n        for (i in c.indices) {\n            mn[i % 2] = minOf(mn[i % 2], c[i])\n            rem[i % 2]--\n            sum += c[i]\n            if (i > 0) {\n                val cur = sum + rem[0] * mn[0] + rem[1] * mn[1]\n                ans = minOf(ans, cur)\n            }\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1499",
    "index": "D",
    "title": "The Number of Pairs",
    "statement": "You are given three positive (greater than zero) integers $c$, $d$ and $x$.\n\nYou have to find the number of pairs of positive integers $(a, b)$ such that equality $c \\cdot lcm(a, b) - d \\cdot gcd(a, b) = x$ holds. Where $lcm(a, b)$ is the least common multiple of $a$ and $b$ and $gcd(a, b)$ is the greatest common divisor of $a$ and $b$.",
    "tutorial": "Let's represent $a$ as $Ag$ and $b$ as $Bg$, where $g=gcd(a,b)$ and $gcd(A,B)=1$. By definition $lcm(a,b) = \\frac{ab}{g}$, so we can represent $lcm(a,b)$ as $\\frac{Ag \\cdot Bg}{g} = ABg$. Now we can rewrite the equation from the statement as follows: $c \\cdot ABg - d \\cdot g = x \\implies g(c \\cdot AB - d) = x$. Since the left-hand side is divisible by $g$, the right-hand side should also be divisible. So we can iterate over $g$ as divisors of $x$. If the right-hand side of $c \\cdot AB = \\frac{x}{g} + d$ is not divisible by $c$ then we can skip such $g$. $AB = \\frac{\\frac{x}{g}+d}{c}$ (let's denote as $k$). If $k$ has some prime divisor $p$ then exactly one of $A$ and $B$ should be divisible by $p$ because $gcd(A,B)=1$ ($A$ and $B$ have no common divisors). So there are $2^{\\textit{the number of prime divisors of k}}$ pairs of $A$ and $B$ for current value of $g$. We can precalculate the minimum prime divisor for each number up to $2 \\cdot 10^7$ (the maximum value of $k$ that you may need) in $O(2 \\cdot 10^7 \\log{\\log{(2 \\cdot 10^7)}})$ using Eratosthenes sieve. Now we can solve the problem in $O(\\sqrt{x}\\log{x})$ for each testcase, but that's not fast enough. To speed up this approach, we can precalculate the number of prime divisors for each number up to $2 \\cdot 10^7$. Let's denote $mind_i$ as the minimum prime divisor of $i$ and $val_i$ as the number of prime divisors of $i$. Then $val_i = val_{i / mind_i}$ plus $1$ if $mind_i \\neq mind_{i / mind_i}$. Now, to solve the problem, we only need to iterate over the divisors of $x$, so the time complexity is $O(\\sqrt{x})$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2e7 + 13;\n\nint main() {\n  vector<int> mind(N, -1), val(N);\n  mind[1] = 1;\n  for (int i = 2; i < N; ++i) if (mind[i] == -1)\n    for (int j = i; j < N; j += i) if (mind[j] == -1)\n      mind[j] = i;\n  for (int i = 2; i < N; ++i) {\n    int j = i / mind[i];\n    val[i] = val[j] + (mind[i] != mind[j]);\n  }\n  int t;\n  scanf(\"%d\", &t);\n  while (t--) {\n    int c, d, x;\n    scanf(\"%d%d%d\", &c, &d, &x);\n    int ans = 0;\n    for (int i = 1; i * i <= x; ++i) {\n      if (x % i != 0) continue;\n      int k1 = x / i + d; \n      if (k1 % c == 0) ans += 1 << val[k1 / c];\n      if (i * i == x) continue;\n      int k2 = i + d;\n      if (k2 % c == 0) ans += 1 << val[k2 / c]; \n    }\n    printf(\"%d\\n\", ans);\n  }\n}",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1499",
    "index": "E",
    "title": "Chaotic Merge",
    "statement": "You are given two strings $x$ and $y$, both consist only of lowercase Latin letters. Let $|s|$ be the length of string $s$.\n\nLet's call a sequence $a$ a merging sequence if it consists of exactly $|x|$ zeros and exactly $|y|$ ones in some order.\n\nA merge $z$ is produced from a sequence $a$ by the following rules:\n\n- if $a_i=0$, then remove a letter from the beginning of $x$ and append it to the end of $z$;\n- if $a_i=1$, then remove a letter from the beginning of $y$ and append it to the end of $z$.\n\nTwo merging sequences $a$ and $b$ are different if there is some position $i$ such that $a_i \\neq b_i$.\n\nLet's call a string $z$ chaotic if for all $i$ from $2$ to $|z|$ $z_{i-1} \\neq z_i$.\n\nLet $s[l,r]$ for some $1 \\le l \\le r \\le |s|$ be a substring of consecutive letters of $s$, starting from position $l$ and ending at position $r$ inclusive.\n\nLet $f(l_1, r_1, l_2, r_2)$ be the number of different merging sequences of $x[l_1,r_1]$ and $y[l_2,r_2]$ that produce chaotic merges. Note that only non-empty substrings of $x$ and $y$ are considered.\n\nCalculate $\\sum \\limits_{1 \\le l_1 \\le r_1 \\le |x| \\\\ 1 \\le l_2 \\le r_2 \\le |y|} f(l_1, r_1, l_2, r_2)$. Output the answer modulo $998\\,244\\,353$.",
    "tutorial": "First, let's try to calculate the number of merging sequences just for some fixed pair of strings $x$ and $y$. Imagine we build a merge letter by letter. So far $i$ letters are in the merge already. For the $(i+1)$-th letter we can pick a letter from either string $x$ or string $y$ (put a $0$ or a $1$ into the merging sequence, respectively). What constraints our choice? Easy to see that it's only the $i$-th letter of the merge. So we can come up with the following dynamic programming. $dp[i][j][c]$ is the number of merging sequences such that $i$ characters from $x$ are taken, $j$ characters from $y$ are taken and the last character of the merge is $c$. $c$ can be either just a letter (a dimension of size $26$) or an indicator of a string the last character was taken from ($0$ for string $x$ and $y$ from string $y$). Since we know how many characters are taken from each string, we can easily decide the last taken character from that indicator. For each transition we can just take a character from either of the strings. The sum of $dp[|x|][|y|][i]$ over all $i$ will be the total number of merging sequences. Now for the substrings. Recall the following definition of a substring: $b$ is a substring of $a$ if you can remove some characters from the beginning of $a$ (possibly, none or all) and some characters from the end of $a$ (possibly, none or all) to get the string $b$. What if we incorporated that definition into our dynamic programming? Let $dp[i][j][c]$ be the number of merging sequences that end exactly before the $i$-th character of $x$, exactly before the $j$-th character of $y$ and the last character is still $c$. How to remove some characters from the beginning? That actually is the same as attempting to start the merge from every state of dp. So, if we are currently in some state $dp[i][j][c]$, then we can act as if we have just taken the $i$-th character of $x$ or the $j$-th character of $y$ as the first character of the merge. How to remove some characters from the end? Since $dp[i][j][c]$ is the number of merging sequences that end exactly there, why not just sum up all the values of dynamic programming into the answer? We will count the sequences that end in all possible positions of both strings. That is almost the answer to the task. The only issue we have is that we forgot the condition that asks us to get a non-empty substring from each string. Well, there are multiple ways to resolve the issue. We can remove bad sequences afterwards: their count is the number of chaotic substrings of $x$ multiplied by all possible empty substrings of $y$ (there are $|y|+1$ of them) plus the same thing for $y$ and $x$. These can be counted with two pointers. Alternatively, we can add an extra dimension or two to the dp to indicate if we have ever taken a character from $x$ and from $y$. So we get $dp[i][j][c][fl_x][fl_y]$ with $fl_x$ and $fl_y$ being binary flags that tell if a character from $x$ and from $y$ was ever taken. That way we can only push the states with both flags set to true to the answer. Overall complexity: $O(|x| \\cdot |y|)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint main() {\n\tstring s, t;\n\tcin >> s >> t;\n\tint n = s.size(), m = t.size();\n\tvector<vector<vector<vector<int>>>> dp(n + 1, vector<vector<vector<int>>>(m + 1, vector<vector<int>>(2, vector<int>(4, 0))));\n\tint ans = 0;\n\tforn(i, n + 1) forn(j, m + 1){\n\t\tif (i < n) dp[i + 1][j][0][1] = add(dp[i + 1][j][0][1], 1);\n\t\tif (j < m) dp[i][j + 1][1][2] = add(dp[i][j + 1][1][2], 1);\n\t\tforn(mask, 4){\n\t\t\tif (0 < i && i < n && s[i - 1] != s[i]) dp[i + 1][j][0][mask | 1] = add(dp[i + 1][j][0][mask | 1], dp[i][j][0][mask]);\n\t\t\tif (0 < j && i < n && t[j - 1] != s[i]) dp[i + 1][j][0][mask | 1] = add(dp[i + 1][j][0][mask | 1], dp[i][j][1][mask]);\n\t\t\tif (0 < i && j < m && s[i - 1] != t[j]) dp[i][j + 1][1][mask | 2] = add(dp[i][j + 1][1][mask | 2], dp[i][j][0][mask]);\n\t\t\tif (0 < j && j < m && t[j - 1] != t[j]) dp[i][j + 1][1][mask | 2] = add(dp[i][j + 1][1][mask | 2], dp[i][j][1][mask]);\n\t\t}\n\t\tans = add(ans, dp[i][j][0][3]);\n\t\tans = add(ans, dp[i][j][1][3]);\n\t}\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1499",
    "index": "F",
    "title": "Diameter Cuts",
    "statement": "You are given an integer $k$ and an undirected tree, consisting of $n$ vertices.\n\nThe length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.\n\nYou are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to $k$.\n\nTwo sets of edges are different if there is an edge such that it appears in only one of the sets.\n\nCount the number of valid sets of edges modulo $998\\,244\\,353$.",
    "tutorial": "The task is obviously solved by dynamic programming, so our first reaction should be to start looking for meaningful states for it. Obviously, one of the states is the vertex which subtree we are processing. We can choose the root for the tree arbitrarily, let it be vertex $1$. What can be the other helpful state? Consider the method to find the diameter of the subtree of vertex $v$. The diameter can be one of the following paths: either the longest path that is completely in some subtree of $v$ or the concatenation of the longest paths that start in vertex $v$ and end in different subtrees. The diameter is the longest path. Thus, the diameter being less than or equal to $k$ means that all paths should have length less than or equal to $k$. If we can guarantee that no path that is completely in some subtree of $v$ have length greater than $k$, then we will only have to worry about not concatenating long paths from different subtrees. Phrase it the other way around: if we never concatenate the paths from the different subtrees in such a way that their total length is greater than $k$, then no diameter will be greater than $k$. Thus, we can attempt to have $dp[v][len]$ - the number of ways to cut some edges in the subtree of $v$ in such a way that there is no path of length greater than $k$ and the longest path starting at vertex $v$ has length $len$. Now for the transitions. For the simplicity, let vertex $v$ have exactly two children. It's not too hard to merge their $dp$'s. Iterate over the length $i$ of the first child, the length $j$ of the second child. If $(i+1)+(j+1) \\le k$, then you can concatenate their longest paths and the longest path for $v$ will be of length $max(i,j)+1$. You can also cut either of the edges from $v$ to the first child or to the second child. The approach is good, however, it's not clear how to make it work on a larger number of children. Also, the complexity sounds pretty bad. Instead of merging children to each other, let's merge each child to the $dp$ of $v$ one by one. $dp[v][len]$ can store the current maximum length over all processed children. When processing a new child, you can choose to cut or not to cut the edge to it. So you can iterate over the current longest path from $v$ and the longest path from that child. So far, the only way to estimate the complexity is to say that each child has to merge its dp to the parent in $O(k^2)$, thus making the algorithm $O(nk^2)$. That's obviously too slow. The trick that makes the solution fast is to iterate not to $k$ but to the height of the subtree of $v$ and the subtree of a child. Surely, that is allowed, since the path just can't grow longer than that value. Consider the even worse option: not the height but the size of the subtree. It's easy to see that the size is always greater or equal than the height. Interpret the merge the following way: enumerate the vertices inside all the subtrees of the processed children and the vertices inside the subtree of the new child. Iterating up to the size of the subtree is the same number of moves as going over the vertices in it. The merge will go over all the pairs of vertices such that the first vertex of the pair is in the first set and the second vertex is in the second set. Thus, each pair of vertices of the tree will be processed exactly once (in lca of these vertices). There are $O(n^2)$ such pairs, thus, such $dp$'s work in $O(n^2)$. Overall complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\nint k;\nvector<vector<int>> g;\nvector<vector<int>> dp;\n\nint dfs(int v, int p = -1){\n\tdp[v][0] = 1;\n\tint h = 0;\n\tfor (int u : g[v]) if (u != p){\n\t\tint nh = dfs(u, v);\n\t\tvector<int> tmp(max(h, nh + 1) + 1);\n\t\tforn(i, h + 1) forn(j, nh + 1){\n\t\t\tif (i + j + 1 <= k)\n\t\t\t\ttmp[max(i, j + 1)] = add(tmp[max(i, j + 1)], mul(dp[v][i], dp[u][j]));\n\t\t\tif (i <= k && j <= k)\n\t\t\t\ttmp[i] = add(tmp[i], mul(dp[v][i], dp[u][j]));\n\t\t}\n\t\th = max(h, nh + 1);\n\t\tforn(i, h + 1){\n\t\t\tdp[v][i] = tmp[i];\n\t\t}\n\t}\n\treturn h;\n}\n\nint main() {\n\tint n;\n\tscanf(\"%d%d\", &n, &k);\n\tg.resize(n);\n\tdp.resize(n, vector<int>(n, 0));\n\tforn(i, n - 1){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\tdfs(0);\n\tint ans = 0;\n\tforn(i, k + 1) ans = add(ans, dp[0][i]);\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1499",
    "index": "G",
    "title": "Graph Coloring",
    "statement": "You are given a bipartite graph consisting of $n_1$ vertices in the first part, $n_2$ vertices in the second part, and $m$ edges, numbered from $1$ to $m$. You have to color each edge into one of two colors, red and blue. You have to minimize the following value: $\\sum \\limits_{v \\in V} |r(v) - b(v)|$, where $V$ is the set of vertices of the graph, $r(v)$ is the number of red edges incident to $v$, and $b(v)$ is the number of blue edges incident to $v$.\n\nSounds classical and easy, right? Well, you have to process $q$ queries of the following format:\n\n- $1$ $v_1$ $v_2$ — add a new edge connecting the vertex $v_1$ of the first part with the vertex $v_2$ of the second part. This edge gets a new index as follows: the first added edge gets the index $m + 1$, the second — $m + 2$, and so on. After adding the edge, you have to print the hash of the current optimal coloring (if there are multiple optimal colorings, print the hash of any of them). \\textbf{Actually, this hash won't be verified, you may print any number as the answer to this query, but you may be asked to produce the coloring having this hash};\n- $2$ — print the optimal coloring of the graph with the same hash you printed while processing the previous query. The query of this type will only be asked after a query of type $1$, and there will be at most $10$ queries of this type. If there are multiple optimal colorings corresponding to this hash, print any of them.\n\nNote that if an edge was red or blue in some coloring, it may change its color in next colorings.\n\nThe hash of the coloring is calculated as follows: let $R$ be the set of indices of red edges, then the hash is $(\\sum \\limits_{i \\in R} 2^i) \\bmod 998244353$.\n\nNote that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.",
    "tutorial": "Let's split all edges of the graph into several paths and cycles (each edge will belong to exactly one path or cycle). Each path and each cycle will be colored in an alternating way: the first edge will be red, the second - blue, the third - red, and so on (or vice versa). Since the graph is bipartite, each cycle can be colored in an alternating way. The main idea of the solution is to add the edges one by one, maintain the structure of cycles and paths, and make sure that for each vertex, at most one path starts/ends in it. If we are able to maintain this invariant, then the value of $|r(v) - b(v)|$ for every vertex will be minimum possible - each cycle going through a vertex covers an even number of edges incident to it (half of them will be red, half of them will be blue); so, if the degree of a vertex is odd, one path will have this vertex as an endpoint, and $|r(v) - b(v)| = 1$; otherwise, it won't be an endpoint of any path, so $|r(v) - b(v)| = 0$. Okay, how do we maintain this structure? Let's add edges one by one (even the original edges of the graph) and rebuild the structure in online mode. For each vertex, we will maintain the indices of the paths that have this vertex as an endpoint. If some vertex has $2$ or more paths as its endpoints, we can choose two of them and link them together. Whenever we add an edge from $x$ to $y$, we just create a new path and check if we can link together some paths that have $x$ or $y$ as their endpoints. How do we link the paths together? If we try to link a path with itself, it means that we try to close a cycle - and when we do it, we just forget about the resulting cycle, its structure won't change in future queries. When we link a path with some other path, we might need to reverse and/or repaint the paths before merging them into one. There are (at least) two possible data structures we can use to do this: either an implicit-key treap that supports reversing and repainting; or a deque with small-to-large merging: whenever we try to link two paths together, we repaint and/or reverse the smaller one. Both of those methods give a solution in $O((m + q) \\log(m + q))$ or $O((m + q) \\log^2(m + q))$, depending on your implementation. The model solution uses deques and small-to-large merging.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 1000043;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint sub(int x, int y)\n{\n    return add(x, -y);\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}                               \n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1)\n            z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nint global_hash = 0;\n\nvoid reverse(deque<pair<int, int>>& d)\n{\n    stack<pair<int, int>> s;\n    while(!d.empty())\n    {\n        s.push(d.back());\n        d.pop_back();\n    }\n    while(!s.empty())\n    {\n        d.push_front(s.top());\n        s.pop();\n    }\n}\n\nvoid safe_push_front(deque<pair<int, int>>& d, int c, int& res)\n{\n    int z = d.front().first ^ 1;\n    res = add(res, mul(binpow(2, c), z));\n    d.push_front(make_pair(z, c));\n}\n\nvoid safe_push_back(deque<pair<int, int>>& d, int c, int& res)\n{\n    int z = d.back().first ^ 1;\n    res = add(res, mul(binpow(2, c), z));\n    d.push_back(make_pair(z, c));\n}\n\ndeque<pair<int, int>> ds[N];\n\nstruct path\n{\n    int s;\n    int t;\n    int d;\n    int c;\n\n    path() {};\n    path(int s, int t, int d, int c) : s(s), t(t), d(d), c(c) {};\n\n    void push_front(int i)\n    {\n        safe_push_front(ds[d], i, c);\n    }\n\n    void push_back(int i)\n    {\n        safe_push_back(ds[d], i, c);\n    }\n\n    void pop_front()\n    {\n        ds[d].pop_front();\n    }\n\n    void pop_back()\n    {\n        ds[d].pop_back();\n    }\n\n    int front()\n    {\n        return ds[d].front().second;\n    }\n\n    int back()\n    {\n        return ds[d].back().second;\n    }\n\n    void reverse()\n    {\n        ::reverse(ds[d]);\n        swap(s, t);\n    }\n\n    int size()\n    {\n        return ds[d].size();\n    }\n};\n\npath link_to_left(path x, path y)\n{\n    path z = x;\n    while(y.size() > 0)\n    {\n        z.push_back(y.front());\n        y.pop_front();\n    }\n    z.t = y.t;\n    return z;\n}\n\npath link_to_right(path x, path y)\n{\n    path z = y;\n    while(x.size() > 0)\n    {\n        z.push_front(x.back());\n        x.pop_back();\n    }\n    z.s = x.s;\n    return z;\n}\n\nint cur = 0;\n\npath make(int x, int y, int i)\n{\n    int cost = i;\n    ds[cur].push_back(make_pair(0, cost));\n    return path(x, y, cur++, 0);    \n}\n\nset<int> paths;\nvector<int> paths_v[N];\npath ps[N];\n\npath merge(path x, path y, int v)\n{\n    if(x.size() > y.size())\n        swap(x, y);\n    if(y.s == v)\n    {\n        if(x.t != v)\n            x.reverse();\n        return link_to_right(x, y);    \n    }\n    else\n    {\n        if(x.s != v)\n            x.reverse();\n        return link_to_left(y, x);\n    }    \n}\n\nint cur2 = 0;       \n\nvoid modify(vector<int>& v, int x, int y)\n{\n    for(int i = 0; i < v.size(); i++)\n        if(v[i] == x)\n            v[i] = y;\n}   \n\nvoid reassign(path p, int x, int y)\n{\n    modify(paths_v[p.s], x, y);\n    modify(paths_v[p.t], x, y);    \n}\n\nvoid merge_paths(int x, int y, int v)\n{\n    if(x == y)\n    {                         \n\n    }\n    else\n    {\n        global_hash = sub(global_hash, ps[x].c);\n        global_hash = sub(global_hash, ps[y].c);\n        ps[cur2++] = merge(ps[x], ps[y], v);\n        paths.erase(x);\n        paths.erase(y);\n        paths.insert(cur2 - 1);\n        reassign(ps[x], x, cur2 - 1);\n        reassign(ps[y], y, cur2 - 1);\n        global_hash = add(global_hash, ps[cur2 - 1].c);   \n    }\n}\n\nvoid relax(int v)\n{\n    while(paths_v[v].size() >= 2)\n    {\n        int x = paths_v[v].back();\n        paths_v[v].pop_back();\n        int y = paths_v[v].back();\n        paths_v[v].pop_back();\n        merge_paths(x, y, v);\n    }\n}\n\nvoid add_edge(int x, int y, int i)\n{\n    //cerr << x << \" \" << y << \" \" << i << endl;\n    int c = cur2;\n    ps[cur2++] = make(x, y, i);\n    paths_v[x].push_back(c);\n    paths_v[y].push_back(c);\n    paths.insert(c);\n    relax(x);\n    relax(y);\n}\n\nvoid print_coloring()\n{\n    vector<int> ans;\n    for(auto x : paths)\n    {\n        for(auto y : ds[ps[x].d])\n        {\n            if(y.first == 1)\n                ans.push_back(y.second);\n        }\n    }\n    printf(\"%d\", int(ans.size()));\n    for(auto x : ans)\n        printf(\" %d\", x);\n    puts(\"\");\n    fflush(stdout);\n}\n\nint e = 0;\n\nvoid process_query()\n{\n    int t;\n    scanf(\"%d\", &t);\n    if(t == 1)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        y += 200001;\n        add_edge(x, y, ++e);\n        printf(\"%d\\n\", global_hash);\n        fflush(stdout);\n    }\n    else\n        print_coloring();\n}\n\nvoid print_info()\n{\n    cerr << \"Paths\\n\";\n    for(auto x : paths)\n        cerr << x << \" start: \" << ps[x].s << \" \" << \" end: \" << ps[x].t << endl;\n    cerr << \"Vertices\\n\";\n    for(int i = 0; i < N; i++)\n        if(!paths_v[i].empty())\n        {\n            cerr << i << \": \";\n            for(auto x : paths_v[i])\n                cerr << x << \" \";\n            cerr << endl;\n        }\n\n}\n        \nint main()\n{\n    int n1, n2, m;\n    scanf(\"%d %d %d\", &n1, &n2, &m);\n    for(int i = 0; i < m; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        y += 200001;\n        add_edge(x, y, ++e);\n    }\n    int q;\n    scanf(\"%d\", &q);\n    for(int i = 0; i < q; i++)\n    {\n        //print_info();\n        process_query();\n    }\n}",
    "tags": [
      "data structures",
      "graphs",
      "interactive"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1500",
    "index": "A",
    "title": "Going Home",
    "statement": "It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array $a$.\n\nSeveral hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four \\textbf{different} indices $x, y, z, w$ such that $a_x + a_y = a_z + a_w$.\n\nHer train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery?",
    "tutorial": "Let's prove that if there're at least four different pairs indices with the common sum ($a_{x_1} + a_{y_1} = a_{x_2} + a_{y_2} = \\ldots = a_{x_4} + a_{y_4}$), then there necessarily will be two pairs such that all four indices in them are unique. Let's analyze some cases: There're four pairs of the form $(x, y_1), (x, y_2), (x, y_3), (x, y_4)$ with sum $S$. Then $a_x + a_{y_1} = a_x + a_{y_2} = a_x + a_{y_3} = a_x + a_{y_4} = S$ from which we can conclude that $a_{y_1} = a_{y_2} = a_{y_3} = a_{y_4}$, and it means that pairs $(y_1, y_2)$ and $(y_3, y_4)$ are suitable as answer. There're three pairs of the form $(x, y_1), (x, y_2), (x, y_3)$ and the fourth pair doesn't contain index $x$. Then whatever the fourth pair $(z, w)$ is, it necessarily doesn't contain index $x$ and at least one of indices $y_1, y_2, y_3$ which means we can take as answer pairs $(z, w)$ and one of three that contain $x$. Other cases are analyzed in the same way. To make sure that answer always exists among such four pairs, we can imagine graph, where vertices are indices, and there is an edge between two vertices if the corresponding pair of indices has sum $S$. If such a graph has at least four edges and the degree of all vertices is at most two (we excluded the larger degrees by examining the previous cases), then there will always be two edges with disjoint ends. How to find answer using this? Let's launch simple $\\mathcal{O}(n^2)$ bruteforce which for every sum will save all found pairs with such sum, and for each pair check if there's another already found pair with the same sum and such indices that all four indices in these two pairs are unique. Let's notice it works in $\\mathcal{O}(min(n^2, n + C)$, because once for some sum we find the fourth pair, we can immediately print the answer. And if the answer is \"NO\", then we've done no more than $\\mathcal{O}(C)$ iterations of bruteforce.",
    "tags": [
      "brute force",
      "hashing",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1500",
    "index": "B",
    "title": "Two chandeliers",
    "statement": "Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red – brown – yellow – red – brown – yellow and so on.\n\nThere are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistake — they bought two different chandeliers.\n\nSince chandeliers are different, some days they will have the same color, but some days — different. Of course, it looks poor and only annoys Vasya. As a result, at the $k$-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers.\n\nYour task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.",
    "tutorial": "A formal statement of the problem: there are two sequences of distinct integers, whose are infinitely cycled. You need to find prefix of minimal length which contains exactly $k$ positions $i$ such that $a_i \\neq b_i$. Let's notice that we can use binary search. So we need to count number of positions $i$ such that $a_i \\neq b_i$ on prefix of length $x$. Because all integers in $a_i$ are distinct (and also in $b_i$), we need to calculate number of non-negative solutions: $\\begin{cases} pos \\equiv x \\pmod{n} \\\\ pos \\equiv y \\pmod{m}\\end{cases}$ If $n$ and $m$ are coprime, the value can be calculated with Chinese remainder theorem. Solution's complexity will be $O((n + m) \\cdot \\log(n + m) \\cdot \\log(k \\cdot (n + m))$. If $n$ and $m$ are not coprime, participant can make transition $(n, m) \\to (\\frac{n}{gcd(n, m)}, \\frac{m}{gcd(n, m)})$, solve new equations, and then make reverse transition. After that, you need to optimize this solution. There are many ways to do this, for example, you can precalculate solutions of all equations. And complexity becomes $O((n + m) \\cdot (\\log(k) + \\log(n + m)))$",
    "tags": [
      "binary search",
      "brute force",
      "chinese remainder theorem",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1500",
    "index": "C",
    "title": "Matrix Sorting",
    "statement": "You are given two tables $A$ and $B$ of size $n \\times m$.\n\nWe define a sorting by column as the following: we choose a column and reorder the rows of the table by the value in this column, from the rows with the smallest value to the rows with the largest. In case there are two or more rows with equal value in this column, their relative order does not change (such sorting algorithms are called stable).\n\nYou can find this behavior of sorting by column in many office software for managing spreadsheets. Petya works in one, and he has a table $A$ opened right now. He wants to perform zero of more sortings by column to transform this table to table $B$.\n\nDetermine if it is possible to do so, and if yes, find a sequence of columns to sort by. Note that you \\textbf{do not need} to minimize the number of sortings.",
    "tutorial": "Let's first learn how to solve with O ($n \\cdot m^2$). Note that each column can be sorted no more than once. Now, let's note that if we could turn matrix A into matrix B, then B has a sorted column. Idea - we will choose the rows that we will sort from the end. To do this, we can support string equivalence classes. Where and why? If two rows are in the same class, then the columns that we applied had the same values. Then, we need to find a column that does not break the sequence between the rows inside each of the classes. Let's iterate through such a column every time. We don't care if we apply someone extra - because of the condition of the possibility of application, it will definitely not spoil. Then just apply the column if we could. Each time, the number of equivalence classes does not decrease, so the number of columns that can be applied does not decrease. If it was not possible to sort after all the applications, it means that some of the classes could not be split correctly, which means that it is impossible to get matrix B from matrix A. Let's learn how to solve it faster than in a cube. Let's not store equivalence classes explicitly. To do this, note that in the final state of B, the equivalence classes are sub-arrays! Then it is enough for us to store for each pair of adjacent rows whether we were able to separate them (swap the lower and upper places) - let's call it $cut$. Also, for each column, we will store the number of still unresolved inversions in it, call it $cnt$. Initially, - is just the number of inversions in the column. Next, it will be the same number of inversions, but only within the classes. How does this solution differ from a cube? We are able to quickly find which column can be applied - this is the column $j$ for which $cnt[j] = 0$. Then we just need to learn how to update the cnt. Let's start a queue (we can say that this is bfs, but in fact we do not use anything other than a queue from bfs), to which we will add only columns $j$ in which $cnt[j] = 0$, apply sorting by column, update cnt and add new columns that have $cnt=0$. $cut$will help us with this. Let's, if we managed to swap the columns (that is, in the current column $v$, $b[i][v] < b[i - 1][v]$), set $cut[i] = 1$ and update all the values of $cnt$ through this row. It is clear that it does not make sense to split rows twice. Since we will apply each column at most once, and the pairs of adjacent rows are $O(n)$, the time complexity is $O (n \\cdot m)$. Do not forget that it is not necessary to divide into exactly $n$ equivalence classes, because a smaller number may be enough. So in the end, check transformations(not difficult, but need to be careful). There is also a solution with time complexity $O(nm log)$, but I think, it is more difficult both in terms of understanding and implementation.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "greedy",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1500",
    "index": "D",
    "title": "Tiles for Bathroom",
    "statement": "Kostya is extremely busy: he is renovating his house! He needs to hand wallpaper, assemble furniture throw away trash.\n\nKostya is buying tiles for bathroom today. He is standing in front of a large square stand with tiles in a shop. The stand is a square of $n \\times n$ cells, each cell of which contains a small tile with color $c_{i,\\,j}$. The shop sells tiles in packs: more specifically, you can only buy a subsquare of the initial square.\n\nA subsquare is any square part of the stand, i. e. any set $S(i_0, j_0, k) = \\{c_{i,\\,j}\\ |\\ i_0 \\le i < i_0 + k, j_0 \\le j < j_0 + k\\}$ with $1 \\le i_0, j_0 \\le n - k + 1$.\n\nKostya still does not know how many tiles he needs, so he considers the subsquares of all possible sizes. He doesn't want his bathroom to be too colorful. Help Kostya to count for each $k \\le n$ the number of subsquares of size $k \\times k$ that have at most $q$ different colors of tiles. Two subsquares are considered different if their location on the stand is different.",
    "tutorial": "Let's denote $ans_{i,\\,j}$ as max \"good\" subsquare side size with left top angle at $(i,\\,j)$ cell. It's obvious that every subsquare with side less than $ans_{i,\\,j}$ is \"good\" too. So we need to find $ans_{i,\\,j}$ and then print answer for k-size side as $\\displaystyle \\sum_{x=k}^{n} |\\{(i,\\,j)\\ |\\ ans_{i,\\,j} = k\\}$. This value can be found with partial sums on count array of $ans_{i,\\,j}$. Now we need to calculate $ans_{i,\\,j}$. Let's notice that $ans_{i,\\,j+1} \\ge ans_{i,\\,j} - 1$, because $(i, j + 1)$-th square is inside of $(i, j)$ square if it's side is longer than 1. So, we can use amortized algorithm of sequential increase square's side. Every time when we can increase $ans_{i,\\,j}$ we will do it, then we will go to calculating $ans_{i,\\,j+1}$. Using linear algorithm to check if new square's size is \"good\", we will get $O(n^3)$ solution, which is not effective enough, but can be optimized. Now let's use small constraints for $q$. For each $(i,\\,j)$ cell we will precalc array $colors_{i,\\,j}$, which will have $(q + 1)$ nearest colors in line $(i',\\,j), i' \\ge i$. For each color, we will keep it's earliest occurrence It can be calculated in $O(n^2 q)$, because $colors_{i,\\,j} = colors_{i,\\,j + 1} \\cup c_{i,\\,j}$. If $c_{i,\\,j}$ exists in $colors_{i,\\,j}$, we must change earliest occurrence. If it isn't, we should delete the most far color, then insert the current one. All values can be keeped with increasing left occurrence in $O(q)$ for each cell. Last step - we can merge $colors_{i,\\,j},\\ \\ldots,\\ colors_{i + m - 1,\\,j}$ in $O(mq)$ - it will be the array of $q + 1$ values corresponding for earliest colors in line of width $m$. Merging two lines is almost like merge of two sorted arrays - it is used to find $q + 1$ minimal left occurrences. Maximal \"good\" width can be found as left occurrence of $(q+1)$-th elementh minus $j$. Now we need to unite some rows in a structure and merge lines for current square, then erase first row and repeat the process. The structure can be realized as queue on two stacks, each of whose is keeping merge value of all lines in itself. The algorithm is almost like queue with minimal value (https://cp-algorithms.com/data_structures/stack_queue_modification.html). That's how we get solution with complexity $O(n^2q)$.",
    "tags": [
      "data structures",
      "sortings",
      "two pointers"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1500",
    "index": "E",
    "title": "Subset Trick",
    "statement": "Vanya invented an interesting trick with a set of integers.\n\nLet an illusionist have a set of positive integers $S$. He names a positive integer $x$. Then an audience volunteer must choose some subset (possibly, empty) of $S$ without disclosing it to the illusionist. The volunteer tells the illusionist the size of the chosen subset. And here comes the trick: the illusionist guesses whether the sum of the subset elements does not exceed $x$. The sum of elements of an empty subset is considered to be $0$.\n\nVanya wants to prepare the trick for a public performance. He prepared some set of \\textbf{distinct} positive integers $S$. Vasya wants the trick to be successful. He calls a positive number $x$ unsuitable, if he can't be sure that the trick would be successful for every subset a viewer can choose.\n\nVanya wants to count the number of unsuitable integers for the chosen set $S$.\n\nVanya plans to try different sets $S$. He wants you to write a program that finds the number of unsuitable integers for the initial set $S$, and after each change to the set $S$. Vanya will make $q$ changes to the set, and each change is one of the following two types:\n\n- add a new integer $a$ to the set $S$, or\n- remove some integer $a$ from the set $S$.",
    "tutorial": "Let $S = \\{a_1, a_2, \\ldots, a_n\\}$, where $a_1 < a_2 < \\ldots < a_n$. Let's calculate the number of good numbers from $0$ to $sum(X) - 1$. To get the answer to our problem we should subtract this value from $sum(S)$. Let's suppose that $0 \\leq x < sum(X)$ is good. It is easy to see that it is equivalent to $a_{n - k + 1} + \\ldots + a_{n} \\leq x < a_{1} + \\ldots + a_{k+1}$ for some $0 \\leq k < n$. So to calculate the required number of good numbers we should find the length of the union of intervals $[a_{n - k + 1} + \\ldots + a_{n}, a_{1} + \\ldots + a_{k+1})$ for all $0 \\leq k < n$. We can note two things: some of these intervals are empty all non-empty intervals does not intersect with each other So the number we want to find is just $\\sum\\limits_{k=0}^{n-1} \\max{(a_{1} + \\ldots + a_{k+1} - a_{n - k + 1} - \\ldots - a_{n}, 0)}$. Let's call $f(k) = a_{1} + \\ldots + a_{k+1} - a_{n - k + 1} - \\ldots - a_{n}$. Let's note two simply things: $f(k) = f(n - 1 - k)$ $f(x) \\geq f(y)$ if $x \\leq y \\leq \\frac{n-1}{2}$ Let's use them. First of all let's find $\\sum\\limits_{k=0}^{\\frac{n-1}{2}} \\max{(f(k), 0)}$. We can simply calculate the sum we need from it because we should just multiply this sum by $2$ and possibly subtract the number from the middle (if $n$ is odd). Let's note that in the sum $\\sum\\limits_{k=0}^{\\frac{n-1}{2}} \\max{(f(k), 0)}$ some first summands are $> 0$, others are equal to $0$ (because $0$ will be bigger in the maximum). Let's find the minimal $l \\leq \\frac{n-1}{2}$, such that $f(l) \\leq 0$ using binary search. After that we should calculate $\\sum\\limits_{k=0}^{l-1} f(k) = \\sum\\limits_{k=0}^{l-1} (a_{1} + \\ldots + a_{k+1} - a_{n - k + 1} - \\ldots - a_{n}) = \\sum\\limits_{i=0}^{l} a_i (l - i) - \\sum\\limits_{i=n-l+1}^{n} a_i (i + l - n)$. So what values we should be able to calculate to solve the problem? The sum of numbers on prefix $\\sum\\limits_{i=0}^{k} a_i$. Using two queries of this type we can calculate $f(k)$. The sum of numbers multiplied by index on prefix $\\sum\\limits_{i=0}^{k} a_i i$. We can calculate the final answer using this query. To answer these queries effectively let's use the segment tree. Initially let's find all numbers that will be in $S$ in some moment (we can do it because we have the list of all queries). We will make a segment tree on this array, where we will write $0$, if there is no such number currently in $S$ and $1$, otherwise. For each segment of these segment tree we will store $3$ values: the number of numbers from this segment, that lie in the current $S$ the sum of numbers from this segment, that lie in the current $S$ the sum of numbers multiplied by index from this segment, that lie in the current $S$ These values can be easily recalculated when an update in the segment tree happens. To calculate two sums required for us we need to make the descent in the segment tree summing the segments on the prefix, where the number of numbers that lie in the current $S$ is equal to $k$. In total, we get the $O((n+q) \\log^2{(n+q)})$ solution, because we make the binary search and use queries to the segment tree inside it.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1500",
    "index": "F",
    "title": "Cupboards Jumps",
    "statement": "In the house where Krosh used to live, he had $n$ cupboards standing in a line, the $i$-th cupboard had the height of $h_i$. Krosh moved recently, but he wasn't able to move the cupboards with him. Now he wants to buy $n$ new cupboards so that they look as similar to old ones as possible.\n\nKrosh does not remember the exact heights of the cupboards, but for every three consecutive cupboards he remembers the height difference between the tallest and the shortest of them. In other words, if the cupboards' heights were $h_1, h_2, \\ldots, h_n$, then Krosh remembers the values $w_i = \\max(h_{i}, h_{i + 1}, h_{i + 2}) - \\min(h_{i}, h_{i + 1}, h_{i + 2})$ for all $1 \\leq i \\leq n - 2$.\n\nKrosh wants to buy such $n$ cupboards that all the values $w_i$ remain the same. Help him determine the required cupboards' heights, or determine that he remembers something incorrectly and there is no suitable sequence of heights.",
    "tutorial": "$-$ Note 1 We can change cupboards' heights with differences between following ones: $d_i = h_{i + 1} - h_{i}$. How to get $w$ using $d$? $w_i = \\max(\\left|{d_i}\\right|, \\left|{d_{i + 1}}\\right|, \\left|{d_i + d_{i + 1}}\\right|)$ $\\quad$ $-$ $O(n C)$ $dp[i][dif]$ - can we choose $i$ differences, with the last equal to $dif$ Can be updated with $O(1)$ checks $\\quad$ $-$ Note 2 If we can get $dif$ difference, then $-dif$ too, because we can invert all differences on prefix and save all conditions. So keep in mind just $dif \\in [0, C]$ $\\quad$ $-$ $O(n^2)$ Let's keep values on each layer we can get as segments. We show that there will be O(n) of them for each layer. Segment $[0; w_i]$ is full able if previous layer has value $w_i$ Each segment $[l, r]$ goes to $[\\max(w_i - r, 0), w_i - l]$ If some segment had $x: x \\leq w_i$, then we should add: $[w_i, w_i]$ Restoring the answer: since we keep all segments for each layer, we can check that previous one contains: $w_i$ $w_i - dif$ anything $\\leq w_i$, if $dif = w_i$ $-$ $O(n)$ Segments don't change much. Each layer change is: inversion + shift + truncation with zero ($[l, r] \\to [\\max(w_i - r, 0), w_i - l]$) check for a corner value ($w_i \\to [0, w_i]$) add corner value ($x \\leq w_i \\to [w_i, w_i]$) After recalculating value of $cf$ and $sh$: let's trunc segments from corners to keep just values in $[0, w_i]$ and add $[w_i, w_i]$(converted) if we need to. Number of truncation will be $O(n)$. Restoring: If $w_i$ was at previous layer - keep it and use If $dif = w_i$, use minimum value from previous layer Otherwise we should definitely use $w_i - dif$",
    "tags": [
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1501",
    "index": "A",
    "title": "Alexey and Train",
    "statement": "Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!\n\nAlexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $0$. Also, let's say that the train will visit $n$ stations numbered from $1$ to $n$ along its way, and that Alexey destination is the station $n$.\n\nAlexey learned from the train schedule $n$ integer pairs $(a_i, b_i)$ where $a_i$ is the expected time of train's arrival at the $i$-th station and $b_i$ is the expected time of departure.\n\nAlso, using all information he has, Alexey was able to calculate $n$ integers $tm_1, tm_2, \\dots, tm_n$ where $tm_i$ is the extra time the train need to travel from the station $i - 1$ to the station $i$. Formally, the train needs exactly $a_i - b_{i-1} + tm_i$ time to travel from station $i - 1$ to station $i$ (if $i = 1$ then $b_0$ is the moment the train leave the terminal, and it's equal to $0$).\n\nThe train leaves the station $i$, if both conditions are met:\n\n- it's on the station for at least $\\left\\lceil \\frac{b_i - a_i}{2} \\right\\rceil$ units of time (division with ceiling);\n- current time $\\ge b_i$.\n\nSince Alexey spent all his energy on prediction of time delays, help him to calculate the time of \\textbf{arrival} at the station $n$.",
    "tutorial": "The solution of this task is to basically implement what was written in the statement. Let $dep_i$ be the moment of train departure from the station $i$ ($dep_0 = 0$ initially). Then train arrives at the current station $i$ at moment $ar_i = dep_{i - 1} + (a_i - b_{i - 1}) + tm_i$ and departure at moment $dep_i = \\max(b_i, ar_i + \\frac{b_i - a_i + 1}{2})$. The answer is $ar_n$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1501",
    "index": "B",
    "title": "Napoleon Cake",
    "statement": "This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.\n\nTo bake a Napoleon cake, one has to bake $n$ dry layers first, and then put them on each other in one stack, adding some cream. Arkady started with an empty plate, and performed the following steps $n$ times:\n\n- place a new cake layer on the top of the stack;\n- after the $i$-th layer is placed, pour $a_i$ units of cream on top of the stack.\n\nWhen $x$ units of cream are poured on the top of the stack, top $x$ layers of the cake get drenched in the cream. If there are less than $x$ layers, all layers get drenched and the rest of the cream is wasted. If $x = 0$, no layer gets drenched.\n\n\\begin{center}\n{\\small The picture represents the first test case of the example.}\n\\end{center}\n\nHelp Arkady determine which layers of the cake eventually get drenched when the process is over, and which don't.",
    "tutorial": "The $i$-th layer is drenched in cream if there is such $j \\ge i$ that $j - a_j < i$. Then we can calculate answers for all layers $i$ in reverse order (from $n$ to $1$) and maintain minimum over all values $j - a_j$ as some variable $mn$. As a result, when we move from $i + 1$ to $i$, we update $mn = \\min(mn, i - a_i)$ and then check that $mn < i$.",
    "tags": [
      "dp",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1503",
    "index": "A",
    "title": "Balance the Bits",
    "statement": "A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.\n\nYou are given a binary string $s$ of length $n$. Construct two balanced bracket sequences $a$ and $b$ of length $n$ such that for all $1\\le i\\le n$:\n\n- if $s_i=1$, then $a_i=b_i$\n- if $s_i=0$, then $a_i\\ne b_i$\n\nIf it is impossible, you should report about it.",
    "tutorial": "Any balanced bracket sequence must begin with '(' and end with ')'. Therefore, $a$ and $b$ must agree in the first and last positions, so we require $s_1=s_n=1$ or a solution doesn't exist. The total number of open brackets in $a$ and $b$ must be $n$, which is even. Each $1$ bit in $s$ creates an even number of open brackets and each $0$ bit creates an odd number of open brackets. Therefore, there must be an even number of $0$ bits, or a solution doesn't exist. Note that the number of $1$ bits also must be even. Assuming these conditions hold, let's construct a solution. Suppose there are $k$ positions where $s_i=1$. We will make the first $\\frac k2$ positions open in both $a$ and $b$, and we will make the last $\\frac k2$ positions closed in both $a$ and $b$. Then, the $0$ bits in $s$ will alternate between which string gets the open bracket.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    string s;\n    cin >> n >> s;\n    int cnt = 0;\n    for(int i = 0; i < n; i++) {\n        cnt += (s[i] == '1');\n    }\n    if(cnt % 2 == 1 || s[0] == '0' || s.back() == '0') {\n        cout << \"NO\\n\";\n        return;\n    }\n    string a, b;\n    int k = 0;\n    bool flip = false;\n    for(int i = 0; i < n; i++) {\n        if(s[i] == '1') {\n            a.push_back(2 * k < cnt ? '(' : ')');\n            b.push_back(a.back());\n            k++;\n        }else {\n            a.push_back(flip ? '(' : ')');\n            b.push_back(flip ? ')' : '(');\n            flip = !flip;\n        }\n    }\n    cout << \"YES\\n\" << a << '\\n' << b << '\\n';\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int te;\n    cin >> te;\n    while(te--) solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1503",
    "index": "B",
    "title": "3-Coloring",
    "statement": "\\textbf{This is an interactive problem.}\n\nAlice and Bob are playing a game. There is $n\\times n$ grid, initially empty. We refer to the cell in row $i$ and column $j$ by $(i, j)$ for $1\\le i, j\\le n$. There is an infinite supply of tokens that come in $3$ colors labelled $1$, $2$, and $3$.\n\nThe game proceeds with turns as follows. Each turn begins with Alice naming one of the three colors, let's call it $a$. Then, Bob chooses a color $b\\ne a$, chooses an empty cell, and places a token of color $b$ on that cell.\n\nWe say that there is a \\textbf{conflict} if there exist two adjacent cells containing tokens of the same color. Two cells are considered adjacent if they share a common edge.\n\nIf at any moment there is a conflict, Alice wins. Otherwise, if $n^2$ turns are completed (so that the grid becomes full) without any conflicts, Bob wins.\n\nWe have a proof that Bob has a winning strategy. Play the game as Bob and win.\n\nThe interactor is \\textbf{adaptive}. That is, Alice's color choices can depend on Bob's previous moves.",
    "tutorial": "Imagine the grid is colored like a checkerboard with black and white squares. Then Bob's strategy is to put tokens $1$ on white squares and tokens $2$ on black squares as long as he is able. If he is unable, this means all squares of one color are filled, and he can start placing tokens $3$ without making an invalid coloring. More specifically, this is his strategy: If Alice chooses $1$: If a black square is free, place a $2$ there. Otherwise, place a $3$ on a white cell. If a black square is free, place a $2$ there. Otherwise, place a $3$ on a white cell. If Alice chooses $2$: If a white square is free, place a $1$ there. Otherwise, place a $3$ on a black cell. If a white square is free, place a $1$ there. Otherwise, place a $3$ on a black cell. If Alice chooses $3$: If a white square is free, place a $1$ there. Otherwise, place a $2$ on a black cell. If a white square is free, place a $1$ there. Otherwise, place a $2$ on a black cell.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int n;\n    cin >> n;\n    vector<pair<int, int>> ve[2];\n    #define BLACK 0\n    #define WHITE 1\n    \n    // color the cells like a checkerboard\n    // ve[COLOR] = {list of unfilled cells of that color}\n    for(int i = 1; i <= n; i++) {\n        for(int j = 1; j <= n; j++) {\n            ve[(i + j) % 2].push_back({i, j});\n        }\n    }\n \n    for(int t = 1; t <= n * n; t++) {\n        int a, b, i, j, col;\n        cin >> a;\n \n        // choose an available checkerboard color and a token color for it\n        if(a == 1) {\n            if(!ve[BLACK].empty()) {\n                col = BLACK;\n                b = 2;\n            }else {\n                col = WHITE;\n                b = 3;\n            }\n        }else if(a == 2) {\n            if(!ve[WHITE].empty()) {\n                col = WHITE;\n                b = 1;\n            }else {\n                col = BLACK;\n                b = 3;\n            }\n        }else { // a == 3\n            if(!ve[WHITE].empty()) {\n                col = WHITE;\n                b = 1;\n            }else {\n                col = BLACK;\n                b = 2;\n            }\n        }\n        tie(i, j) = ve[col].back();\n        ve[col].pop_back();\n        cout << b << ' ' << i << ' ' << j << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "games",
      "interactive"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1503",
    "index": "C",
    "title": "Travelling Salesman Problem",
    "statement": "There are $n$ cities numbered from $1$ to $n$, and city $i$ has beauty $a_i$.\n\nA salesman wants to start at city $1$, visit every city exactly once, and return to city $1$.\n\nFor all $i\\ne j$, a flight from city $i$ to city $j$ costs $\\max(c_i,a_j-a_i)$ dollars, where $c_i$ is the price floor enforced by city $i$. Note that there is no absolute value. Find the minimum total cost for the salesman to complete his trip.",
    "tutorial": "Let's reindex the cities so they are in increasing order of beauty. Note that it doesn't matter which city we call the start: the trip will be a cycle visiting every city exactly once. Let's rewrite the cost of a flight $i\\to j$ as $\\max(c_i, a_j-a_i)=c_i+\\max(0, a_j-a_i-c_i).$ Since we always need to leave each city exactly once, we can ignore the $c_i$ term from all flights and only try to minimize the sum of $\\max(0,a_j-a_i-c_i).$ Note that a flight to a city of smaller beauty is always free in the adjusted cost. So all we need is a path from $a_1$ to $a_n$, and the rest of the trip can be done for free. Also, any valid trip will contain a path from $a_1$ to $a_n$, so the shortest path is optimal. Solution 1 All we have to do is encode the graph without storing all edges explicitly, and we can simply run Dijkstra's algorithm to find the shortest path. Add the following edges: $a_i\\to a_{i-1}$ with weight $0$. $i\\to j$ with weight $0$, where $j$ is the largest index with $a_j-a_i-c_i\\le 0$. The index $j$ can be found with binary search. $i\\to j+1$ with weight $\\max(0, a_{j+1}-a_i-c_i)$ where $j$ is the same as before. Every edge in this new graph corresponds to an edge in the original graph, and every edge in the original graph corresponds to a path in the new graph with at most the same cost. So the distance from $a_1$ to $a_n$ is preserved. Solution 2 A simpler solution is to compute for all $i>1$, the minimum possible cost of the first trip reaching $a_i$ or larger. It's easy to see that any path must have at least this cost, and we can construct a path of this cost since moving to smaller $a_i$ is free. It corresponds to the following summation. $\\sum_{i=2}^n \\max(0, a_i-\\max_{j<i}(a_j+c_j))$ Complexity is $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int n;\n    cin >> n;\n    vector<pair<long long, long long>> ve;\n    long long ans = 0;\n    for(int i = 0; i < n; i++) {\n        long long a, c;\n        cin >> a >> c;\n        ve.push_back({a, c});\n        ans += c;\n    }\n    sort(ve.begin(), ve.end());\n    long long mx = ve[0].first + ve[0].second;\n    for(int i = 1; i < n; i++) {\n        ans += max(0LL, ve[i].first - mx);\n        mx = max(mx, ve[i].first + ve[i].second);\n    }\n    cout << ans << '\\n';\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "shortest paths",
      "sortings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1503",
    "index": "D",
    "title": "Flip the Cards",
    "statement": "There is a deck of $n$ cards. The $i$-th card has a number $a_i$ on the front and a number $b_i$ on the back. Every integer between $1$ and $2n$ appears exactly once on the cards.\n\nA deck is called sorted if the front values are in \\textbf{increasing} order and the back values are in \\textbf{decreasing} order. That is, if $a_i< a_{i+1}$ and $b_i> b_{i+1}$ for all $1\\le i<n$.\n\nTo flip a card $i$ means swapping the values of $a_i$ and $b_i$. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?",
    "tutorial": "Suppose there is a sorted deck where the $i$-th card has $c_i$ on the front and $d_i$ on the back. That is, it looks like this: $c_1< c_2< \\cdots< c_n\\\\ d_1> d_2> \\cdots> d_n$ The values $1,\\ldots, n$ must appear in some prefix of $c_i$ and some suffix of $d_i$. That is, they must all appear on distinct cards. So, if two values between $1$ and $n$ appear on the same card, we should report there is no solution. Now, we know that every card in the input has a value in $[1,n]$ and a value in $[n+1,2n]$. Let $f(k)$ denote the number matched with the value $k$. Let's split the cards into two sets. Set $A$ will be the cards that will end with the smaller number on the front, and $B$ is the set of cards ending with the smaller number on the back. In each set, as the smaller numbers increase, the larger numbers decrease. Therefore, it must be possible to decompose $[f(1),\\ldots,f(n)]$ into two decreasing subsequences, or there is no solution. To decompose an array into two decreasing subsequences, there is a standard greedy approach. Also, note that any decomposition of $[f(1),\\ldots,f(n)]$ into two decreasing sequences corresponds to a solution. In fact, we can put all the cards of one subsequence in $A$ and the rest in $B$, and it will create a sorted deck. But how can we find the decomposition that corresponds to the minimum number of card flips? For every index $i$ such that $\\min\\limits_{j\\le i} f(j)>\\max\\limits_{j>i}f(j)$, let's add a divider between $i$ and $i+1$. This splits the array $[f(1),\\ldots, f(n)]$ into several segments. We can independently choose how to decompose each segment into two subsequences, and combining them is guaranteed to be a valid decomposition for the entire array. Also, there is a unique way to decompose each segment: the only choice is in which one we call the first subsequence. And so, we can independently choose for each segment the choice that requires the smallest number of flips. Complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> ve(n + 1), c(n + 1), suffmax(n + 2), seq0, seq1;\n    bool flag = true;\n    for(int i = 0; i < n; i++) {\n        int a, b;\n        cin >> a >> b;\n        int cost = 0;\n        if(a > b) {\n            cost = 1;\n            swap(a, b);\n        }\n        if(a <= n) {\n            ve[a] = b;\n            c[a] = cost;\n        }else flag = false;\n    }\n    if(!flag) {\n        cout << -1 << '\\n';\n        return;\n    }\n    suffmax[n + 1] = -1;\n    for(int i = n; i >= 1; i--) {\n        suffmax[i] = max(suffmax[i + 1], ve[i]);\n    }\n    int prefmin = INT_MAX;\n    int cost0 = 0, cost1 = 0, ans = 0;\n    for(int i = 1; i <= n; i++) {\n        prefmin = min(prefmin, ve[i]);\n        if(seq0.empty() || ve[seq0.back()] > ve[i]) {\n            seq0.push_back(i);\n            cost0 += c[i];\n        }else if(seq1.empty() || ve[seq1.back()] > ve[i]) {\n            seq1.push_back(i);\n            cost1 += c[i];\n        }else {\n            cout << -1 << '\\n';\n            return;\n        }\n        if(prefmin > suffmax[i + 1]) {\n            int s0 = (int) seq0.size(), s1 = (int) seq1.size();\n            ans += min(cost0 + s1 - cost1, s0 - cost0 + cost1);\n            cost0 = cost1 = 0;\n            seq0.clear();\n            seq1.clear();\n        }\n    }\n    cout << ans << '\\n';\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    solve();\n}",
    "tags": [
      "2-sat",
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1503",
    "index": "E",
    "title": "2-Coloring",
    "statement": "There is a grid with $n$ rows and $m$ columns. Every cell of the grid should be colored either blue or yellow.\n\nA coloring of the grid is called stupid if every row has exactly one segment of blue cells and every column has exactly one segment of yellow cells.\n\nIn other words, every row must have at least one blue cell, and all blue cells in a row must be consecutive. Similarly, every column must have at least one yellow cell, and all yellow cells in a column must be consecutive.\n\n\\begin{center}\nAn example of a stupid coloring.\n\\end{center}\n\n\\begin{center}\nExamples of clever colorings. The first coloring is missing a blue cell in the second row, and the second coloring has two yellow segments in the second column.\n\\end{center}\n\nHow many stupid colorings of the grid are there? Two colorings are considered different if there is some cell that is colored differently.",
    "tutorial": "Before counting, we should understand the structure of a stupid coloring. First, both of the following cannot hold: There exists a path of yellow cells from column $1$ to column $m$. There exists a path of blue cells from row $1$ to row $n$. In fact, if two such paths existed, they must have a cell in common, and it would have to be blue and yellow at the same time. Without loss of generality, suppose statement 1 is false. Consider a yellow cell in the grid. All blue cells in its row must be to its left or right because they lie in one segment. So, each yellow cell either belongs to the connected component $A$ of yellow cells touching the first column or the component $B$ touching the last column. There cannot be a column with one cell in $A$ and another cell in $B$, otherwise the segment would connect the two components. And every column has at least one yellow cell, so there exists a number $c$ ($1\\le c<m$) such that $A$ occupies the first $c$ columns and $B$ occupies the last $m-c$ columns. Let $[l_A, r_A]$ be the segment of yellow cells in column $c$ and $[l_B, r_B]$ be the segment of yellow cells in column $c+1$. Since the segments do not overlap, we either have $r_A<l_B$ or $r_B<l_A$. Without loss of generality, suppose $r_A<l_B$. The cells in $A$ create a monotonically increasing path from $(1,0)$ to $(r_A, c)$, then make a monotonically decreasing path from $(r_A, c-1)$ to $(n,0)$. A similar structure happens for $B$. The number of monotonic paths where we step right $a$ times and up $b$ times is counted by the binomial coefficient ${a+b\\choose a}$. Now, if we fix $r_A$ and $l_B$, we can count the number of stupid colorings with the product of $4$ binomial coefficients. To make this fast enough, we can fix only $r_A$ and use a prefix sum to find the number of ways over all $l_B>r_A$. To generalize from the assumption that $r_A<l_B$, we can multiply the answer by $2$ since it's symmetric. To generalize from the assumption that statement $1$ is false, we can also count the number of ways if $n$ and $m$ are swapped. But we should be careful about double counting the case where both statements 1 and 2 are false. This can be handled without too much trouble by simply requiring $r_A+1<l_B$ for one of the two cases. Complexity is $O(\\max(n, m)^2)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int M = 998244353;\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int n, m;\n    cin >> n >> m;\n    if(n < m) swap(n, m);\n    \n    vector<vector<long long>> choose(n + m, vector<long long>(n));\n    for(int i = 0; i < n + m; i++) {\n        for(int j = 0; j < n; j++) {\n            if(j == 0) choose[i][j] = 1;\n            else if(i == 0) choose[i][j] = 0;\n            else choose[i][j] = (choose[i - 1][j] + choose[i - 1][j - 1]) % M;\n        }\n    }\n    long long ans = 0;\n    for(int r = 1; r < n; r++) {\n        long long F = 0;\n        for(int c = m - 1; c >= 1; c--) {\n            F = (F + choose[n - r + m - c - 1][n - r] * choose[c + n - r - 1][n - r - 1]) % M;\n            ans = (ans + choose[r + c - 1][r] * ((choose[m - c + r - 1][r - 1] * F) % M)) % M;\n        }\n    }\n \n    swap(n, m);\n    for(int r = 1; r < n; r++) {\n        long long F = 0;\n        for(int c = m - 1; c >= 1; c--) {\n            ans = (ans + choose[r + c - 1][r] * ((choose[m - c + r - 1][r - 1] * F) % M)) % M;\n            F = (F + choose[n - r + m - c - 1][n - r] * choose[c + n - r - 1][n - r - 1]) % M;\n        }\n    }\n    ans = (2 * ans) % M;\n    cout << ans << '\\n';\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1503",
    "index": "F",
    "title": "Balance the Cards",
    "statement": "A balanced bracket sequence is defined as an integer sequence that can be built with the following rules:\n\n- The empty sequence is balanced.\n- If $[a_1,\\ldots,a_n]$ and $[b_1,\\ldots, b_m]$ are balanced, then their concatenation $[a_1,\\ldots,a_n,b_1,\\ldots,b_m]$ is balanced.\n- If $x$ is a positive integer and $[a_1,\\ldots,a_n]$ is balanced, then $[x,a_1,\\ldots,a_n,-x]$ is balanced.\n\nThe positive numbers can be imagined as opening brackets and the negative numbers as closing brackets, where matching brackets must have the same type (absolute value). For example, $[1, 2, -2, -1]$ and $[1, 3, -3, 2, -2, -1]$ are balanced, but $[1, 2, -1, -2]$ and $[-1, 1]$ are not balanced.\n\nThere are $2n$ cards. Each card has a number on the front and a number on the back. Each integer $1,-1,2,-2,\\ldots,n,-n$ appears exactly once on the front of some card and exactly once on the back of some (not necessarily the same) card.\n\nYou can reorder the cards however you like. You are \\textbf{not} allowed to flip cards, so numbers cannot move between the front and back. Your task is to order the cards so that the sequences given by the front numbers and the back numbers are both balanced, or report that it is impossible.",
    "tutorial": "Suppose we have a deck of cards where the front and back are both balanced bracket sequences. Let's line the cards up horizontally and draw them as points. For each pair of matching brackets on the front and back, we will connect them with an edge. For matched brackets on the front, we add an edge as a semicircle lying above the points. And for matched brackets on the back, we add a similar edge below the points. Since every point is incident to exactly two edges, this graph decomposes into cycles. Since the edges are non-intersecting, each cycle is a Jordan curve in the plane. Imagine the curve as a track, and a monorail makes one full trip clockwise around the track. Each edge turns the monorail clockwise or counterclockwise by 180 degrees. Since the overall effect must turn the monorail a full 360 degrees clockwise, there are two more clockwise edges than counterclockwise edges in the cycle. If a cycle has $2m$ edges, then there are $m+1$ clockwise edges and $m-1$ counterclockwise edges. Now, in the actual problem we are given a shuffled deck of cards. If there exists a way to reorder them so that the front and back are both balanced, then we know the above property must hold. Even though the cards are shuffled, we still have enough information to construct the edges and distinguish two edges in the same cycle by orientation (clockwise and counterclockwise). If there are $m+1$ edges of one orientation, we should call them the clockwise edges. Otherwise if the number of edges of both orientations are invalid, we should report that no solution exists. Now that we have restricted ourselves to the case where this important condition holds, we should construct a solution. We can do this by solving for all the cycles independently and concatenating them together. Consider a cycle. Let's make a binary string describing the sequence of orientations, where $1$ denotes a clockwise turn and $0$ denotes a counterclockwise turn. Since there are $m+1$ clockwise turns, we can find two adjacent $1$'s in the string. For consistency, let's cyclically shift the string so that it begins and ends with $1$, and we can consider the curve to begin at the leftmost point. Let's see how we can build the curve recursively. First, there is the base case where the string is $11$. Clearly, we can build the curve with two points like this. Base Case: Now, suppose we have constructed a curve corresponding to $1s1$ for some string $s$. We will hide the turns of $s$ in the drawing, and just display it as a blue box. From this, we can build a curve corresponding to the string $10s11$ as shown on the right. This requires us to add two new points and reverse the order of the points in the blue box. Operation 1: Similarly, if we have constructed a curve for $1s1$, we can build the curve for $11s01$. Operation 2: Suppose we have constructed the curves $1s1$ and $1t1$ for two strings $s$ and $t$. The turns of $s$ are displayed as a blue box, and the turns of $t$ are displayed as a green box. Then we can build the curve $1st1$ as shown on the right. We take the last point in the blue box visited by the curve, and replace it with the points in the green box, in the same order. Operation 3: It turns out that the base case and these three operations are enough to build any curve satisfying the required condition. We can do it recursively as follows. If the string is $11$, return the base case. If the string is $10s11$ for some $s$, build the curve $1s1$ and apply operation 1. If the string is $11s01$ for some $s$, build the curve $1s1$ and apply operation 2. Otherwise, there exist non-empty strings $s$ and $t$ so that the string is $1st1$, and $s$ contains the same number of $0$'s and $1$'s (and thus so does $t$). Recursively build the curves $1s1$ and $1t1$, and apply operation 3. How can we apply these operations efficiently? When constructing a curve, we only care about the list of points (ignoring the leftmost one) as they appear from left to right, and which points are visited immediately before and after the leftmost point by the curve. If we store the list in the form of a doubly linked list, the operations of reversing and inserting in the middle can be done in constant time. To build it recursively, we also need an efficient way to find a splitting point in the case of $1st1$. If we just scan from one endpoint maintaining a prefix sum (number of $1$'s minus number of $0$'s), the algorithm will take $O(n^2)$ time overall. Instead, we should scan from both endpoints in parallel, and stop when one of them finds a splitting point. If it splits into lengths $k$ and $m-k$, then the time is given by the recurrence $T(m)=T(k)+T(m-k)+\\min(k,m-k)=O(m\\log m).$ Complexity is $O(n\\log n)$. There is also an $O(n)$ solution. Scan the string $s$ (ignoring the first and last $1$) from left to right, maintaining a stack of linked lists. When the prefix sum (number of $1$'s minus number of $0$'s) increases in absolute value, we push the base case to the stack. When the prefix sum decreases in absolute value, we apply an operation $1$ or $2$ to the curve on the top of the stack, then merge the top two curves with operation $3$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nstruct curve {\n    list<int> a, b;\n    curve() {}\n    curve(int x) {\n        a.push_back(x);\n        b.push_back(x);\n    }\n    curve& operator+=(curve &o) {\n        a.splice(a.end(), o.a);\n        o.b.splice(o.b.end(), b);\n        b.swap(o.b);\n        return *this;\n    }\n    curve& rev() {\n        a.swap(b);\n        return *this;\n    }\n};\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int n;\n    cin >> n;\n    vector<int> openfront(n + 1), closefront(n + 1), openback(n + 1), closeback(n + 1), a(2 * n), b(2 * n);\n    for(int i = 0; i < 2 * n; i++) {\n        cin >> a[i] >> b[i];\n        if(a[i] > 0) openfront[a[i]] = i;\n        else closefront[-a[i]] = i;\n        if(b[i] > 0) openback[b[i]] = i;\n        else closeback[-b[i]] = i;\n    }\n    vector<bool> vis(2 * n, false);\n    vector<int> ans, ve;\n    stack<int> st;\n    stack<curve*> stnode;\n    string s;\n    for(int i = 0; i < 2 * n; i++) {\n        if(!vis[i]) {\n            ve.clear();\n            s.clear();\n            int x = i;\n            int cnt = 0;\n            do {\n                ve.push_back(x);\n                vis[x] = true;\n                if(a[x] > 0) {\n                    cnt++;\n                    s.push_back('1');\n                    x = closefront[a[x]];\n                }else {\n                    s.push_back('0');\n                    x = openfront[-a[x]];\n                }\n                ve.push_back(x);\n                vis[x] = true;\n                if(b[x] > 0) {\n                    s.push_back('0');\n                    x = closeback[b[x]];\n                }else {\n                    cnt++;\n                    s.push_back('1');\n                    x = openback[-b[x]];\n                }\n            }while(x != i);\n            if(cnt == (int) s.length() / 2 - 1) {\n                cnt = s.length() - cnt;\n                for(char &c : s) c = (c == '0' ? '1' : '0');\n            }\n            if(cnt != (int) s.length() / 2 + 1) {\n                cout << \"NO\\n\";\n                return 0;\n            }\n            int idx = 0;\n            while(s[idx] == '0' || s[idx + 1] == '0') idx++;\n            rotate(s.begin(), s.begin() + idx, s.end());\n            rotate(ve.begin(), ve.begin() + idx, ve.end());\n            stnode.push(new curve(0));\n            for(int j = (int) s.length() - 1; j >= 2; j--) {\n                if(st.empty() || s[st.top()] == s[j]) {\n                    st.push(j);\n                    stnode.push(new curve());\n                }else {\n                    curve *x = new curve(j), *y = new curve(st.top()), *z = stnode.top();\n                    st.pop();\n                    stnode.pop();\n                    if(s[j] == '0') {\n                        *x += *y;\n                        *x += z->rev();\n                        *x += *stnode.top();\n                        stnode.pop();\n                        stnode.push(x);\n                    }else {\n                        curve *w = stnode.top();\n                        stnode.pop();\n                        *w += z->rev();\n                        *w += *y;\n                        *w += *x;\n                        stnode.push(w);\n                    }\n                }\n            }\n            assert(st.empty());\n            assert((int) stnode.size() == 1);\n            curve *y = stnode.top();\n            y->a.push_front(1);\n            y->b.push_back(1);\n            if(a[ve[1]] < 0) y->rev();\n            for(int idx : y->a) {\n                ans.push_back(ve[idx]);\n            }\n            stnode.pop();\n        }\n    }\n    cout << \"YES\\n\";\n    for(int i : ans) {\n        cout << a[i] << ' ' << b[i] << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "geometry",
      "graphs",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1504",
    "index": "A",
    "title": " Déjà Vu",
    "statement": "A palindrome is a string that reads the same backward as forward. For example, the strings \"z\", \"aaa\", \"aba\", and \"abccba\" are palindromes, but \"codeforces\" and \"ab\" are not. You hate palindromes because they give you déjà vu.\n\nThere is a string $s$. You \\textbf{must} insert \\textbf{exactly one} character 'a' somewhere in $s$. If it is possible to create a string that is \\textbf{not} a palindrome, you should find one example. Otherwise, you should report that it is impossible.\n\nFor example, suppose $s=$ \"cbabc\". By inserting an 'a', you can create \"acbabc\", \"cababc\", \"cbaabc\", \"cbabac\", or \"cbabca\". However \"cbaabc\" is a palindrome, so you must output one of the other options.",
    "tutorial": "If $s$ is the character 'a' repeated some number of times, there is no solution. Otherwise, I claim either 'a' + $s$ or $s$ + 'a' is a solution (or both). Let's prove it. Assume for contradiction that 'a' + $s$ and $s$ + 'a' are both palindromes. Then the first and last characters of $s$ are 'a'. Then the second and second to last characters of $s$ are 'a'. Repeating this, we see that all characters of $s$ are 'a', but we assumed we are not in this case. Therefore, the claim is true. The solution is simply to check if 'a' + $s$ and $s$ + 'a' are palindromes and output the correct one. Complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nbool palindrome(const string &s) {\n    int n = s.length();\n    for(int i = 0; i < n; i++) {\n        if(s[i] != s[n - i - 1]) return false;\n    }\n    return true;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int te;\n    cin >> te;\n    while(te--) {\n        string s;\n        cin >> s;\n        if(!palindrome(s + 'a')) {\n            cout << \"YES\\n\" << s << 'a' << \"\\n\";\n        }else if(!palindrome('a' + s)) {\n            cout << \"YES\\n\" << 'a' << s << '\\n';\n        }else {\n            cout << \"NO\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1504",
    "index": "B",
    "title": "Flip the Bits",
    "statement": "There is a binary string $a$ of length $n$. In one operation, you can select any prefix of $a$ with an \\textbf{equal} number of $0$ and $1$ symbols. Then all symbols in the prefix are inverted: each $0$ becomes $1$ and each $1$ becomes $0$.\n\nFor example, suppose $a=0111010000$.\n\n- In the first operation, we can select the prefix of length $8$ since it has four $0$'s and four $1$'s: $[01110100]00\\to [10001011]00$.\n- In the second operation, we can select the prefix of length $2$ since it has one $0$ and one $1$: $[10]00101100\\to [01]00101100$.\n- It is illegal to select the prefix of length $4$ for the third operation, because it has three $0$'s and one $1$.\n\nCan you transform the string $a$ into the string $b$ using some finite number of operations (possibly, none)?",
    "tutorial": "Let's call a prefix legal if it contains an equal number of $0$ and $1$ symbols. The key observation is that applying operations never changes which prefixes are legal. In fact, suppose we apply an operation to a prefix of length $i$, and consider a prefix of length $j$. We want to show that if $j$ was legal before, it remains legal. And if it wasn't legal, it won't become legal. If $j<i$, then all bits in the length $j$ prefix are inverted. The numbers of $0$'s and $1$'s swap, so it cannot change whether they are equal, and hence it cannot change whether $j$ is legal. If $j\\ge i$, then $i/2$ of the $0$ symbols become $1$ and $i/2$ of the $1$ symbols become $0$. So the numbers of both symbols do not change, so it cannot change whether $j$ is legal. Using prefix sums, we can determine for each prefix whether it is legal. Consider an index $i$. If $i=n$ and $a_n\\ne b_n$, then we must flip the length $n$ prefix at some point. If $i<n$ and $a_i=b_i$, $a_{i+1}\\ne b_{i+1}$, or $a_i\\ne b_i$, $a_{i+1}=b_{i+1}$, then we must flip the length $i$ prefix at some point. If we flip precisely these prefixes in any order, it will transform $a$ into $b$. So we should simply check that every prefix that must be flipped is legal. Complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    string a, b;\n    cin >> n >> a >> b;\n    a.push_back('0');\n    b.push_back('0');\n    int cnt = 0;\n    for(int i = 0; i < n; i++) {\n        cnt += (a[i] == '1') - (a[i] == '0');\n        if((a[i] == b[i]) != (a[i + 1] == b[i + 1]) && cnt != 0) {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    cout << \"YES\\n\";\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int te;\n    cin >> te;\n    while(te--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1506",
    "index": "A",
    "title": "Strange Table",
    "statement": "Polycarp found a rectangular table consisting of $n$ rows and $m$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm \\textbf{\"by columns\"}:\n\n- cells are numbered starting from one;\n- cells are numbered from left to right by columns, and inside each column from top to bottom;\n- number of each cell is an integer one greater than in the previous cell.\n\nFor example, if $n = 3$ and $m = 5$, the table will be numbered as follows:\n\n$$ \\begin{matrix} 1 & 4 & 7 & 10 & 13 \\\\ 2 & 5 & 8 & 11 & 14 \\\\ 3 & 6 & 9 & 12 & 15 \\\\ \\end{matrix} $$\n\nHowever, Polycarp considers such numbering inconvenient. He likes the numbering \\textbf{\"by rows\"}:\n\n- cells are numbered starting from one;\n- cells are numbered from top to bottom by rows, and inside each row from left to right;\n- number of each cell is an integer one greater than the number of the previous cell.\n\nFor example, if $n = 3$ and $m = 5$, then Polycarp likes the following table numbering: $$ \\begin{matrix} 1 & 2 & 3 & 4 & 5 \\\\ 6 & 7 & 8 & 9 & 10 \\\\ 11 & 12 & 13 & 14 & 15 \\\\ \\end{matrix} $$\n\nPolycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering \\textbf{\"by rows\"}, if in the numbering \\textbf{\"by columns\"} the cell has the number $x$?",
    "tutorial": "To find the cell number in a different numbering, you can find $(r, c)$ coordinates of the cell with the number $x$ in the numbering \"by columns\": $r = ((x-1) \\mod r) + 1$, where $a \\mod b$ is the remainder of dividing the number $a$ by the number $b$; $c = \\left\\lceil \\frac{x}{n} \\right\\rceil$, where $\\left\\lceil \\frac{a}{b} \\right\\rceil$ is the division of the number $a$ to the number $b$ rounded up. Then, the cell number in numbering \"by lines\" will be equal to $(r-1)*m + c$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    ll n, m, x;\n    cin >> n >> m >> x;\n    x--;\n    ll col = x / n;\n    ll row = x % n;\n    cout << row * m + col + 1 << \"\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n    int n;\n    cin >> n;\n    while (n--) {\n        solve();\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1506",
    "index": "B",
    "title": "Partial Replacement",
    "statement": "You are given a number $k$ and a string $s$ of length $n$, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met:\n\n- The first character '*' in the original string should be replaced with 'x';\n- The last character '*' in the original string should be replaced with 'x';\n- The distance between two neighboring replaced characters 'x' must not exceed $k$ (more formally, if you replaced characters at positions $i$ and $j$ ($i < j$) and at positions $[i+1, j-1]$ there is no \"x\" symbol, then $j-i$ must be no more than $k$).\n\nFor example, if $n=7$, $s=$.**.*** and $k=3$, then the following strings will satisfy the conditions above:\n\n- .xx.*xx;\n- .x*.x*x;\n- .xx.xxx.\n\nBut, for example, the following strings will not meet the conditions:\n\n- .**.*xx (the first character '*' should be replaced with 'x');\n- .x*.xx* (the last character '*' should be replaced with 'x');\n- .x*.*xx (the distance between characters at positions $2$ and $6$ is greater than $k=3$).\n\nGiven $n$, $k$, and $s$, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions.",
    "tutorial": "To solve this problem, you can use the dynamic programming method or the greedy algorithm. Let's describe the greedy solution. Until we get to the last character '*' we will do the following: being in position $i$, find the maximum $j$, such that $s_j=$'*' and $j-i \\le k$, and move to position $j$. Since we make the longest move on each turn, we will make the minimum number of substitutions.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n  int n, k;\n  cin >> n >> k;\n  string s;\n  cin >> s;\n  int res = 1;\n  int i = s.find_first_of('*');\n  while (true) {\n    int j = min(n - 1, i + k);\n    for (; i < j && s[j] == '.'; j--) {}\n    if (i == j) {\n      break;\n    }\n    res++;\n    i = j;\n  }\n  cout << res << \"\\n\";\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1506",
    "index": "C",
    "title": "Double-ended Strings",
    "statement": "You are given the strings $a$ and $b$, consisting of lowercase Latin letters. You can do any number of the following operations in any order:\n\n- if $|a| > 0$ (the length of the string $a$ is greater than zero), delete the first character of the string $a$, that is, replace $a$ with $a_2 a_3 \\ldots a_n$;\n- if $|a| > 0$, delete the last character of the string $a$, that is, replace $a$ with $a_1 a_2 \\ldots a_{n-1}$;\n- if $|b| > 0$ (the length of the string $b$ is greater than zero), delete the first character of the string $b$, that is, replace $b$ with $b_2 b_3 \\ldots b_n$;\n- if $|b| > 0$, delete the last character of the string $b$, that is, replace $b$ with $b_1 b_2 \\ldots b_{n-1}$.\n\nNote that after each of the operations, the string $a$ or $b$ may become empty.\n\nFor example, if $a=$\"hello\" and $b=$\"icpc\", then you can apply the following sequence of operations:\n\n- delete the first character of the string $a$ $\\Rightarrow$ $a=$\"ello\" and $b=$\"icpc\";\n- delete the first character of the string $b$ $\\Rightarrow$ $a=$\"ello\" and $b=$\"cpc\";\n- delete the first character of the string $b$ $\\Rightarrow$ $a=$\"ello\" and $b=$\"pc\";\n- delete the last character of the string $a$ $\\Rightarrow$ $a=$\"ell\" and $b=$\"pc\";\n- delete the last character of the string $b$ $\\Rightarrow$ $a=$\"ell\" and $b=$\"p\".\n\nFor the given strings $a$ and $b$, find the minimum number of operations for which you can make the strings $a$ and $b$ equal. Note that empty strings are also equal.",
    "tutorial": "Regarding to the small constraints, in this problem you could iterate over how many characters were removed by each type of operation. If $l$ characters at the beginning and $x$ characters at the end are removed from the string $s$, then the substring $s[l+1, n-x]$ remains, where $n$ - is the length of the string $s$. There is also a fast solution to this problem using dynamic programming.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    string a, b;\n    cin >> a >> b;\n    int n = a.size(), m = b.size();\n    int ans = 0;\n    for (int len = 1; len <= min(n, m); len++) {\n        for (int i = 0; i + len <= n; i++) {\n            for (int j = 0; j + len <= m; j++) {\n                if (a.substr(i, len) == b.substr(j, len)) {\n                    ans = max(ans, len);\n                }\n            }\n        }\n    }\n    cout << a.size() + b.size() - 2 * ans << \"\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n    int n;\n    cin >> n;\n    while (n--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1506",
    "index": "D",
    "title": "Epic Transformation",
    "statement": "You are given an array $a$ of length $n$ consisting of integers. You can apply the following operation, consisting of several steps, on the array $a$ \\textbf{zero} or more times:\n\n- you select two \\textbf{different} numbers in the array $a_i$ and $a_j$;\n- you remove $i$-th and $j$-th elements from the array.\n\nFor example, if $n=6$ and $a=[1, 6, 1, 1, 4, 4]$, then you can perform the following sequence of operations:\n\n- select $i=1, j=5$. The array $a$ becomes equal to $[6, 1, 1, 4]$;\n- select $i=1, j=2$. The array $a$ becomes equal to $[1, 4]$.\n\nWhat can be the minimum size of the array after applying some sequence of operations to it?",
    "tutorial": "Let's replace each character with the number of its occurrences in the string. Then each operation - take two non-zero numbers and subtract one from them. In the end, we will have only one non-zero number left, and we want to minimize it. We can say that we want to minimize the maximum number after applying all the operations, which means we want to minimize the maximum number at each step. We get the following greedy solution - each time we take two characters with maximal occurrences number and delete them.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    priority_queue<pair<int, int>> q;\n    int n;\n    cin >> n;\n    map<int, int> v;\n    for (int i = 0; i < n; i++) {\n        int x;\n        cin >> x;\n        v[x]++;\n    }\n    for (auto [x, y] : v) {\n        q.push({y, x});\n    }\n    int sz = n;\n    while (q.size() >= 2) {\n        auto [cnt1, x1] = q.top();\n        q.pop();\n        auto [cnt2, x2] = q.top();\n        q.pop();\n        cnt1--;\n        cnt2--;\n        sz -= 2;\n        if (cnt1) {\n            q.push({cnt1, x1});\n        }\n        if (cnt2) {\n            q.push({cnt2, x2});\n        }\n    }\n    cout << sz << \"\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n    int n;\n    cin >> n;\n    while (n--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1506",
    "index": "E",
    "title": "Restoring the Permutation",
    "statement": "A permutation is a sequence of $n$ integers from $1$ to $n$, in which all numbers occur exactly once. For example, $[1]$, $[3, 5, 2, 1, 4]$, $[1, 3, 2]$ are permutations, and $[2, 3, 2]$, $[4, 3, 1]$, $[0]$ are not.\n\nPolycarp was presented with a permutation $p$ of numbers from $1$ to $n$. However, when Polycarp came home, he noticed that in his pocket, the permutation $p$ had turned into an array $q$ according to the following rule:\n\n- $q_i = \\max(p_1, p_2, \\ldots, p_i)$.\n\nNow Polycarp wondered what lexicographically minimal and lexicographically maximal permutations could be presented to him.\n\nAn array $a$ of length $n$ is lexicographically smaller than an array $b$ of length $n$ if there is an index $i$ ($1 \\le i \\le n$) such that the first $i-1$ elements of arrays $a$ and $b$ are the same, and the $i$-th element of the array $a$ is less than the $i$-th element of the array $b$. For example, the array $a=[1, 3, 2, 3]$ is lexicographically smaller than the array $b=[1, 3, 4, 2]$.\n\nFor example, if $n=7$ and $p=[3, 2, 4, 1, 7, 5, 6]$, then $q=[3, 3, 4, 4, 7, 7, 7]$ and the following permutations could have been as $p$ initially:\n\n- $[3, 1, 4, 2, 7, 5, 6]$ (lexicographically minimal permutation);\n- $[3, 1, 4, 2, 7, 6, 5]$;\n- $[3, 2, 4, 1, 7, 5, 6]$;\n- $[3, 2, 4, 1, 7, 6, 5]$ (lexicographically maximum permutation).\n\nFor a given array $q$, find the lexicographically minimal and lexicographically maximal permutations that could have been originally presented to Polycarp.",
    "tutorial": "If we want to build a minimal lexicographic permutation, we need to build it from left to right by adding the smallest possible element. If $q[i] = q[i-1]$, so the new number must not be greater than all the previous ones, and if $q[i] > q[i-1]$, then necessarily $a[i] = q[i]$. $q[i] < q[i-1]$ does not happen, since $q[i]$ - is the maximum element among the first $i$ elements. We get a greedy solution if $q[i] > q[i-1]$, then $a[i] = q[i]$, otherwise we put the minimum character that has not yet occurred in the permutation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid placeLeft(vector<int> &q, bool minimize) {\n  set<int> left;\n  for (int i = 1; i <= (int) q.size(); i++) {\n    left.insert(i);\n  }\n  for (int i : q) {\n    if (i != -1) {\n      left.erase(i);\n    }\n  }\n  int lastPlaced = -1;\n  for (int &i : q) {\n    if (i == -1) {\n      set<int>::const_iterator it;\n      if (minimize) {\n        it = left.begin();\n      } else {\n        it = --left.lower_bound(lastPlaced);\n      }\n      i = *it;\n      left.erase(it);\n    } else {\n      lastPlaced = i;\n    }\n  }\n}\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> q(n);\n  for (int i = 0; i < n; i++) {\n    cin >> q[i];\n  }\n\n  vector<int> res1(n, -1), res2(n, -1);\n  for (int i = 0, lastPlaced = -1; i < n; lastPlaced = q[i], i++) {\n    if (lastPlaced != q[i]) {\n      res1[i] = q[i];\n      res2[i] = q[i];\n    }\n  }\n  placeLeft(res1, true);\n  placeLeft(res2, false);\n  for (int x : res1) {\n    cout << x << \" \";\n  }\n  cout << \"\\n\";\n  for (int x : res2) {\n    cout << x << \" \";\n  }\n  cout << \"\\n\";\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1506",
    "index": "F",
    "title": "Triangular Paths",
    "statement": "Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $k$-th layer of the triangle contains $k$ points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers $(r, c)$ ($1 \\le c \\le r$), where $r$ is the number of the layer, and $c$ is the number of the point in the layer. From each point $(r, c)$ there are two \\textbf{directed} edges to the points $(r+1, c)$ and $(r+1, c+1)$, but only one of the edges is activated. If $r + c$ is even, then the edge to the point $(r+1, c)$ is activated, otherwise the edge to the point $(r+1, c+1)$ is activated. Look at the picture for a better understanding.\n\n\\begin{center}\n{\\small Activated edges are colored in black. Non-activated edges are colored in gray.}\n\\end{center}\n\nFrom the point $(r_1, c_1)$ it is possible to reach the point $(r_2, c_2)$, if there is a path between them only from \\textbf{activated} edges. For example, in the picture above, there is a path from $(1, 1)$ to $(3, 2)$, but there is no path from $(2, 1)$ to $(1, 1)$.\n\nInitially, you are at the point $(1, 1)$. For each turn, you can:\n\n- Replace activated edge for point $(r, c)$. That is if the edge to the point $(r+1, c)$ is activated, then \\textbf{instead of it}, the edge to the point $(r+1, c+1)$ becomes activated, otherwise if the edge to the point $(r+1, c+1)$, then \\textbf{instead if it}, the edge to the point $(r+1, c)$ becomes activated. This action increases the cost of the path by $1$;\n- Move from the current point to another by following the activated edge. This action \\textbf{does not increase} the cost of the path.\n\nYou are given a sequence of $n$ points of an infinite triangle $(r_1, c_1), (r_2, c_2), \\ldots, (r_n, c_n)$. Find the minimum cost path from $(1, 1)$, passing through all $n$ points in \\textbf{arbitrary} order.",
    "tutorial": "Since all edges are directed downward, there is only one way to visit all $n$ points is to visit the points in ascending order of the layer number. Let's sort the points in order of increasing layer. It is easy to see that the cost of the entire path is equal to the sum of the cost of paths between adjacent points. Let's learn how to calculate the cost of a path between two points $(r_1, c_1)$ and $(r_2, c_2)$: If $r_1 - c_1 = r_2 - c_2$, then if $(r_1 + c_1)$ is even, then the cost is $r_2-r_1$, otherwise the cost is $0$; Otherwise, move the point $(r_2, c_2)$ to $(r_3, c_3) = (r_2-r_1+1, c_2-c_1+1)$ and find the cost of the path $(1, 1) \\rightarrow (r_3, c_3)$ with different criteria for the activation of the edges; If $(r_1 + c_1)$ is even then the cost is $\\lfloor \\frac{r_3-c_3}{2} \\rfloor$; Otherwise, the cost is $\\lceil \\frac{r_3-c_3}{2} \\rceil$;",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nbool isLeftArrow(int r, int c) {\n  return (r + c) % 2 == 0;\n}\n\nbool isRightArrow(int r, int c) {\n  return (r + c) % 2 == 1;\n}\n\nint calcDist(int r1, int c1, int r2, int c2) {\n  if (r1 - c1 == r2 - c2) {\n    return isRightArrow(r1, c1) ? 0 : r2 - r1;\n  }\n  r2 -= r1 - 1;\n  c2 -= c1 - 1;\n  if (isLeftArrow(r1, c1)) {\n    return (r2 - c2) / 2;\n  } else {\n    return (r2 - c2 + 1) / 2;\n  }\n}\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> r(n);\n  vector<int> c(n);\n  for (int i = 0; i < n; i++) {\n    cin >> r[i];\n  }\n  for (int i = 0; i < n; i++) {\n    cin >> c[i];\n  }\n  vector<pair<int, int>> pts;\n  for (int i = 0; i < n; i++) {\n    pts.emplace_back(r[i], c[i]);\n  }\n  sort(pts.begin(), pts.end());\n  int curR = 1, curC = 1;\n  int res = 0;\n  for (auto[nextR, nextC] : pts) {\n    res += calcDist(curR, curC, nextR, nextC);\n    curR = nextR;\n    curC = nextC;\n  }\n  cout << res << \"\\n\";\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math",
      "shortest paths",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1506",
    "index": "G",
    "title": "Maximize the Remaining String",
    "statement": "You are given a string $s$, consisting of lowercase Latin letters. While there is at least one character in the string $s$ that is \\textbf{repeated at least twice}, you perform the following operation:\n\n- you choose the index $i$ ($1 \\le i \\le |s|$) such that the character at position $i$ occurs \\textbf{at least two} times in the string $s$, and delete the character at position $i$, that is, replace $s$ with $s_1 s_2 \\ldots s_{i-1} s_{i+1} s_{i+2} \\ldots s_n$.\n\nFor example, if $s=$\"codeforces\", then you can apply the following sequence of operations:\n\n- $i=6 \\Rightarrow s=$\"codefrces\";\n- $i=1 \\Rightarrow s=$\"odefrces\";\n- $i=7 \\Rightarrow s=$\"odefrcs\";\n\nGiven a given string $s$, find the lexicographically maximum string that can be obtained after applying a certain sequence of operations after which all characters in the string \\textbf{become unique}.\n\nA string $a$ of length $n$ is lexicographically less than a string $b$ of length $m$, if:\n\n- there is an index $i$ ($1 \\le i \\le \\min(n, m)$) such that the first $i-1$ characters of the strings $a$ and $b$ are the same, and the $i$-th character of the string $a$ is less than $i$-th character of string $b$;\n- \\textbf{or} the first $\\min(n, m)$ characters in the strings $a$ and $b$ are the same and $n < m$.\n\nFor example, the string $a=$\"aezakmi\" is lexicographically less than the string $b=$\"aezus\".",
    "tutorial": "How can you check if you can perform such a sequence of operations on the string $s$ to get the string $t$? Note that each time we delete an arbitrary character that is repeated at least two times, so $t$ must be a subsequence of the string $s$ and have the same character set as the string $s$. We will consequently build the resulting string $t$, adding characters to the end. To check if there is such a sequence of operations that turns the string $s$ into the string $tc?$ (a string that first contains the characters of the string $t$, then the character $c$, and then some unknown characters), it is enough to do the following: Find the minimum index $i$ such that $t$ is included in $s[1..i]$ as a subsequence; Find the minimum index $j$ ($i<j$) such that $s_j = c$; Then the substring $s[j+1..n]$ must contain all characters that are in the string $s$, but which are not in the string $tc$. Let's denote a function that checks the criterion above as $can(t)$. Having received the verification criterion, the following algorithm can be made: Initially $t$ is an empty string; While there is a character in the string $s$ that is not in the string $t$, we will find the maximum character $c$ not contained in $t$, but contained in $s$, for which $can(tc) = true$ and add it to the end of the string $t$. Since at each step we take the maximum symbol for which the criterion is met, the resulting string $t$ will be the lexicographically maximum.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint distinct(string s) {\n  sort(s.begin(), s.end());\n  return unique(s.begin(), s.end()) - s.begin();\n}\n\nstring filter(const string &s, char c) {\n  string t;\n  bool foundFirst = false;\n  for (char a : s) {\n    if (a != c && foundFirst) {\n      t += a;\n    } else if (a == c) {\n      foundFirst = true;\n    }\n  }\n  return t;\n}\n\nvoid solve() {\n  string s;\n  cin >> s;\n  int m = distinct(s);\n  unordered_set<char> used(s.begin(), s.end());\n  string t;\n  while (m > 0) {\n    char maxC = -1;\n    for (char c : used) {\n      if (distinct(filter(s, c)) == m - 1) {\n        maxC = max(maxC, c);\n      }\n    }\n    t += maxC;\n    s = filter(s, maxC);\n    used.erase(maxC);\n    m--;\n  }\n  cout << t << \"\\n\";\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1508",
    "index": "A",
    "title": "Binary Literature",
    "statement": "A bitstring is a string that contains only the characters 0 and 1.\n\nKoyomi Kanou is working hard towards her dream of becoming a writer. To practice, she decided to participate in the Binary Novel Writing Contest. The writing prompt for the contest consists of three bitstrings of length $2n$. A valid novel for the contest is a bitstring of length at most $3n$ that contains \\textbf{at least two} of the three given strings as subsequences.\n\nKoyomi has just received the three prompt strings from the contest organizers. Help her write a valid novel for the contest.\n\nA string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero) characters.",
    "tutorial": "First solution Let's focus on two bitstrings $s$ and $t$. How can we get a short string that has them both as subsequences? Well, suppose both strings have a common subsequence of length $L$. Then we can include this subsequence as part of our string. Then we just place the remaining characters of both sequences in the correct positions between the characters of this common sequence, to make both strings a subsequence of the result. This saves us $L$ characters compared to just concatenating $s$ and $t$ since the characters of the common subsequence only have to included once, i.e. this uses $|s| + |t| - L$ characters. Now, in our problem, all strings have a length of $2n$, so this algorithm will use a total of $4n - L$ characters. This means if we can find two strings that have a common subsequence of length $n$, we can finish the problem. However, the usual algorithm for computing the longest common subsequence works in $\\mathcal{O}(n^2)$, which is unlikely to pass the time limit, so we have to construct this common subsequence more concretely. The observation is that because each character is either $0$ or $1$, one of these characters must appear at least $n$ times. Call such a character frequent. Now since each string has at least one frequent character, two of these frequent characters are equal. Considering these two strings and their frequent character we find a common subsequence of length $n$, equal to either $000\\dots 0$ or $111\\dots 1$. Second solution This solution uses a similar idea, in a way that is a bit easier to implement. Consider three pointers $p_1, p_2, p_3$, pointing to a character in each string, and a string $t$ representing our answer. These pointers will represent the prefixes of each string that we have represented in our answer. Initially, $t$ is empty and $p_1 = p_2 = p_3 = 1$ (here our strings are $1$-indexed). Now we will add characters to $t$ one by one. At each step, consider the three characters pointed at by our three pointers. Since they are either $0$ or $1$, two of them are equal. Add this equal character to $t$, and advance the pointers that match this character by $1$. Continue this algorithm until one of the strings is completely contained in $t$, let's say $s_1$. At this point, suppose $t$ has $k$ characters, and thus the pointers have advanced by at least $2k$, since at least two of them advance on each step. We have exhausted the characters of $s_1$, so we have advanced $p_1$ by $2n$, and the other two pointers have advanced $2k - 2n$, and thus one of them has advanced by at least $k - n$. Now just add the remaining characters of this string to $t$. There are at most $2n - (k - n) = 3n - k$ of them, so in the end $t$ has at most $3n$ characters. This problem was originally suggested as a 2B. It turned out to be too hard and was switched to 2C, before being further switched to 1A because it was still too hard. Some testers still believed this problem to be even harder, but we ended up deciding to have it as 1A with a larger score than usual. Apologies to the testers who had to solve this as if it was the second easiest problem in the contest :^)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nstring mix(string s, string t, char c) {\n    int n = s.size()/2;\n    vector<int> v1 = {-1}, v2 = {-1};\n    for(int i = 0; i < 2 * n; i++) {\n        if(s[i] == c)\n            v1.push_back(i);\n        if(t[i] == c)\n            v2.push_back(i);\n    }\n    string ans;\n    for(int i = 0; i < n; i++) {\n        for(int j = v1[i] + 1; j < v1[i + 1]; j++)\n            ans += s[j];\n        for(int j = v2[i] + 1; j < v2[i + 1]; j++)\n            ans += t[j];\n        ans += c;\n    }\n    for(int j = v1[n] + 1; j < 2 * n; j++)\n        ans += s[j];\n    for(int j = v2[n] + 1; j < 2 * n; j++)\n        ans += t[j];\n    return ans;\n}\n \nvoid solve() {\n    vector<string> s0, s1;\n    int n;\n    cin >> n;\n    for(int i = 0; i < 3; i++) {\n        string s;\n        cin >> s;\n        int cnt_0 = 0;\n        for(auto &c : s) {\n            if(c == '0')\n                cnt_0++;\n        }\n        if(cnt_0 >= n)\n            s0.push_back(s);\n        else\n            s1.push_back(s);\n    }\n    if(s0.size() >= 2)\n        cout << mix(s0[0], s0[1], '0') << '\\n';\n    else\n        cout << mix(s1[0], s1[1], '1') << '\\n';\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while(t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1508",
    "index": "B",
    "title": "Almost Sorted",
    "statement": "Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations.\n\nA permutation $a_1, a_2, \\dots, a_n$ of $1, 2, \\dots, n$ is said to be almost sorted if the condition $a_{i + 1} \\ge a_i - 1$ holds for all $i$ between $1$ and $n - 1$ inclusive.\n\nMaki is considering the list of all almost sorted permutations of $1, 2, \\dots, n$, given in lexicographical order, and he wants to find the $k$-th permutation in this list. Can you help him to find such permutation?\n\nPermutation $p$ is lexicographically smaller than a permutation $q$ if and only if the following holds:\n\n- in the first position where $p$ and $q$ differ, the permutation $p$ has a smaller element than the corresponding element in $q$.",
    "tutorial": "First solution. Let's first analyze the general structure of an almost sorted permutation. We know that when the sequence decreases, it must decrease by exactly $1$. Thus, every decreasing subarray covers some consecutive range of values. Let's split the permutation into decreasing subarrays, each of them as large as possible. For example, we can split the almost sorted permutation $[3, 2, 1, 4, 6, 5, 7]$ as $[3, 2, 1], [4], [6, 5], [7]$. The main claim goes as follows. Claim. Each almost sorted permutation is determined uniquely by the sequence of sizes of its maximal decreasing subarrays. So for instance, in the previous example, the sequence of sizes $3, 1, 2, 1$ uniquely determines the permutation as $[3, 2, 1, 4, 6, 5, 7]$. This is because the last element $a_i$ of a decreasing block must be smaller than the first element $a_{i + 1}$ in the next block. Otherwise we either have $a_{i + 1} = a_i - 1$, in which case we should expand the previous block, or $a_{i + 1} < a_i - 1$, which is contradictory. Now, this is basically enough to get a complete solution. Through some careful counting (which we will go into detail about later) we can show that there are $2^{n - 1}$ almost sorted permutations of size $n$. Now notice that smaller sizes for the first block produce lexicographically smaller permutations (since a permutation whose first block has size $m$ starts with $m$). Moreover, the remaining sequence after deleting the first block is almost sorted. This enables to do a recursive argument to find the permutation, by first choosing the correct size for the first block and then solving recursively for the remaining sequence. This works in $\\mathcal{O}(n \\log k)$. Second solution. But we can do better. Let's mark the positions in the array where a decreasing block ends with $0$, and the other positions as $1$. Notice that the last character is always $0$, so we will ignore it and assign only the other $n - 1$ characters. Thus our example permutation $[3, 2, 1, 4, 6, 5, 7]$ becomes $110010$ since the first, second, and third blocks end at positions $3$, $4$, and $6$. By the first claim, we can recover the permutation from this sequence (which is also the proof of there being $2^{n - 1}$ permutations of size $n$ that we promised earlier!). Now, we can read the assigned sequence as a binary number, for instance, the corresponding number is $110010_2 = 2^5 + 2^4 + 2^1 = 50$ for our trusty example. The point of doing this is the following: Claim 2. The $k$-th almost sorted permutation in lexicographical order is assigned the number $k - 1$. To prove this it's actually enough to check that the number $m + 1$ is assigned to a greater permutation than the number $m$. This can be done by looking at how the permutation changes when we add $1$ to $m$, looking at the binary representation of $m$ from right to left. We leave it to the reader to fill in the details of the proof, but here's a diagram showing the situation graphically (with height representing the values of the permutation). Anyways, once we have proven this claim, we get a simple $\\mathcal{O}(n + \\log k)$ solution by finding the binary representation of $k$ and using it to reconstruct the blocks in $\\mathcal{O}(n)$. This problem's creation has a funny story. Back when we were coming up with problems for Round 668, I (Ari) came up the following relatively simple and standard problem and shared it. The next day, Kuroni saw the problem, but misread it and ended up solving the version that made it into this contest, which we think is a lot cooler! One more fun fact for your consideration: This problem's name in Polygon is \"sorrow\".",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n \nvoid solve() {\n    int n;\n    ll k;\n    cin >> n >> k;\n \n    if(n < 62 && k > 1LL << (n - 1)) {\n        cout << \"-1\\n\";\n        return;\n    }\n \n    string s;\n    for(int i = 0; i < n; i++)\n        s += '0';\n    k--;\n    for(ll b = 0; b < min(60LL, (ll)(n - 1)); b++) {\n        if((k >> b) & 1)\n            s[n - 2 - b] = '1';\n    }\n    int cur = 1, sz = 1;\n    vector<int> ans;\n    for(int i = 0; i < n; i++) {\n        if(s[i] == '0') {\n            for(int j = cur + sz - 1; j >= cur; j--)\n                ans.push_back(j);\n            cur += sz;\n            sz = 1;\n        }\n        else\n            sz++;\n    }\n    for(auto &x : ans)\n        cout << x << \" \";\n    cout << '\\n';\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while(t--)\n        solve();\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1508",
    "index": "C",
    "title": "Complete the MST",
    "statement": "As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows.\n\nYou are given an undirected complete graph with $n$ nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with \\textbf{non-negative weights} so that in the resulting fully-assigned complete graph the XOR sum of all weights would be equal to $0$.\n\nDefine the ugliness of a fully-assigned complete graph the weight of its minimum spanning tree, where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible.\n\nAs a reminder, an undirected complete graph with $n$ nodes contains all edges $(u, v)$ with $1 \\le u < v \\le n$; such a graph has $\\frac{n(n-1)}{2}$ edges.\n\nShe is not sure how to solve this problem, so she asks you to solve it for her.",
    "tutorial": "Call $x$ the XOR sum of the weights of all pre-assigned edges. Lemma. All but one unassigned edges are assigned with $0$, while the remaining unassigned edge is assigned with $x$. Proof. Consider any assignment of unassigned edges. There are two cases on the minimum spanning tree: The MST does not use all unassigned edges: We can assign one unused unassigned edge with $x$, while all other unassigned edges (including all used in the MST) are assigned with $0$. This reduces the weight of the MST. The MST uses all unassigned edges: We can prove that the sum of weights of unassigned edges is at least $x$, and the equality can be achieved with the construction from the lemma. Intuitively, the XOR sum is an \"uncarried\" summation, and the construction from the lemma removes any digit carry. Let's DFS on the unassigned edges. It can happen that the unassigned edges may separate the graph into multiple components, and we might need to use some pre-assigned edges in our MST. I will divide the collection of pre-assigned edges into 3 types: Edges that must be included in the MST: these are edges with smallest weights that connect the components after traversing through unassigned edges. Edges that cannot be included in the MST: these are edges that form cycles with smaller-weighted pre-assigned edges. In other words, these are edges that do not exist in the minimum spanning forest of the pre-assigned edges. Edges that are in neither of the previous types. For the unassigned edges, there are two cases: The unassigned edges form at least a cycle: We can assign any edge on this cycle as $x$, the rest as $0$, then build an MST using the $0$-weighted edges with pre-assigned edges of type 1. The unassigned edges does not form a cycle. Suppose we build the tree using only unassigned edges and edges of type 1. Then any edge of type 3 can replace an unassigned edge in the tree. That is because the edges of type 3 must form a cycle with edges of type 1 and unassigned edges (else it would either be in type 1 or type 2). We can simply replace an unassigned edge in that cycle with this type 3 edge. Therefore, for this case, our solution is to first form the tree with all edges of type 1 and unassigned edge. Then, if the smallest weighted type 3 edge has weight $< x$, we can replace an unassigned edge with this edge; else, we keep the tree. Therefore, for this case, our solution is to first form the tree with all edges of type 1 and unassigned edge. Then, if the smallest weighted type 3 edge has weight $< x$, we can replace an unassigned edge with this edge; else, we keep the tree. If the unassigned edges in the graph don't form a forest, then the answer is simply the weight of the MST where all the unassigned edges have weight $0$. Thus the interesting tests in this problem require these edges to form a forest, which means $m \\ge \\frac{n(n - 1)}{2} - (n - 1)$. This automatically limits the maximum value of $n$ to approximately $2\\sqrt{m}$. Concretely, $n \\le 633$ for all interesting tests in this problem. You can also use this to obtain a solution that runs in $O(m \\sqrt{m})$, which a tester found, and which passes if implemented reasonably.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 200005;\n \nint n, m, u, v, w, lef;\nlong long rem, ans = 0;\nset<int> ava;\nvector<int> adj[N];\nvector<array<int, 3>> ed;\n \nstruct dsu {\n    int par[N];\n \n    void init() {\n        fill(par + 1, par + n + 1, -1);\n    }\n \n    int trace(int u) {\n        return par[u] < 0 ? u : par[u] = trace(par[u]);\n    }\n    \n    bool connect(int u, int v) {\n        if ((u = trace(u)) == (v = trace(v))) {\n            return false;\n        }\n        if (par[u] > par[v]) {\n            swap(u, v);\n        }\n        par[u] += par[v];\n        par[v] = u;\n        return true;\n    }\n} all, ori;\n \nvoid DFS(int u) {\n    ava.erase(u);\n    sort(adj[u].begin(), adj[u].end());\n    for (int v = 0;;) {\n        auto it = ava.lower_bound(v);\n        if (it == ava.end()) {\n            return;\n        }\n        v = *it;\n        if (!binary_search(adj[u].begin(), adj[u].end(), v)) {\n            all.connect(u, v);\n            DFS(v);\n            rem--;\n        }\n        v++;\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> n >> m;\n    rem = 1LL * n * (n - 1) / 2 - m;\n    for (int i = 1; i <= n; i++) {\n        ava.insert(i);\n    }\n    all.init(); ori.init();\n    for (int i = 1; i <= m; i++) {\n        cin >> u >> v >> w;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n        lef ^= w;\n        ed.push_back({w, u, v});\n    }\n    for (int i = 1; i <= n; i++) {\n        if (ava.count(i)) {\n            DFS(i);\n        }\n    }\n    if (rem > 0) {\n        lef = 0;\n    }\n    sort(ed.begin(), ed.end());\n    for (auto [w, u, v] : ed) {\n        if (all.connect(u, v)) {\n            ans += w;\n            ori.connect(u, v);\n        } else if (ori.connect(u, v)) {\n            lef = min(lef, w);\n        }\n    }\n    cout << ans + lef << '\\n';\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1508",
    "index": "D",
    "title": "Swap Pass",
    "statement": "Based on a peculiar incident at basketball practice, Akari came up with the following competitive programming problem!\n\nYou are given $n$ points on the plane, no three of which are collinear. The $i$-th point initially has a label $a_i$, in such a way that the labels $a_1, a_2, \\dots, a_n$ form a permutation of $1, 2, \\dots, n$.\n\nYou are allowed to modify the labels through the following operation:\n\n- Choose two distinct integers $i$ and $j$ between $1$ and $n$.\n- Swap the labels of points $i$ and $j$, and finally\n- Draw the segment between points $i$ and $j$.\n\nA sequence of operations is valid if after applying all of the operations in the sequence in order, the $k$-th point ends up having the label $k$ for all $k$ between $1$ and $n$ inclusive, and the drawn segments don't intersect each other internally. Formally, if two of the segments intersect, then they must do so at a common endpoint of both segments.\n\nIn particular, all drawn segments must be distinct.\n\nFind any valid sequence of operations, or say that none exist.",
    "tutorial": "As it turns out, it is always possible to find the required sequence, no matter the position of the points in the plane and the initial permutation. It turns out that it's pretty hard to analyze even particular positions of the points, and it will be more convenient to start by analyzing particular permutations instead. To this effect, we will begin by doing two things: Ignore every $i$ such that initially $a_i = i$. Since we'll prove that the sequence exists for any configuration anyway, they can't ever matter. Draw an arrow from point $i$ to point $a_i$ for each $i$. This divides the points into a bunch of cycles. Now we can make the following observation: Observation 1. If we have any cycle, we can get all the balls in that cycle to their correct position by choosing any member $i$ in the cycle, and repeatedly swap passing between $i$ and $a_i$, without generating any intersections. This allows us to solve the problem for any position of the points as long as the permutation has a single cycle. However, this will generally not be the case. We can hope to deal with this by making a second observation. Observation 2. If we have any two distinct cycles and any two members $u$ and $v$ in those two cycles, then swap passing between $u$ and $v$ will merge both cycles. By combining both observations we can come up with the following general idea to solve any case: First, perform swaps between distinct cycles until all of the cycles merge into a single one. Then, move all the balls to their correct positions as described in the first observation. Now we just have to figure out how to perform these moves without having intersections between segments. It might be helpful to think about the case when the points are vertices of a convex polygon first since it simplifies the model without sacrificing too much of the geometry. Either way, we will describe only the general case. Consider any point, which we will use as a \"pivot\" for the operations at the end. Now, sort all of the other points by the angle of the segment between them and the pivot point. Call the segments that join two consecutive points in the ordering border segments, and the segments between the pivot and the other points central segments. Now we will just merge all the cycles by using border segments and then move all the balls to their intended position by using central segments, this solves the problem. However, there's one small special case that we might have to deal with depending on how we're thinking about the problem: If the pivot point we chose is on the convex hull of the set of points, then one of the border segments may actually intersect some other segments! Luckily, we can easily prove that this can't happen for more than one of the segments, so our plan still works. There are many different ways to deal with this case. From simplest to most complicated: Always choose the bottom-most and left-most point as a pivot. This makes this potentially troublesome segment predictable, and also allows us to slightly simplify the angular sorting code. Discard the problematic segment by looking at which pair of consecutive points makes a clockwise turn instead of a counter-clockwise turn. Discard the problematic segment by brute-force intersecting each border segment with each central segment. This increases our complexity to $\\mathcal{O}(n^2)$, but this is still fine. Intentionally choose a pivot that is not on the convex hull and do something slightly different if the points are the vertices of a convex polygon. Regardless of how we choose to deal with it, we can now solve the problem with approximately $\\frac{3}{2}n$ operations in the worst case, and a time complexity of either $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n^2)$ depending on how we implement the solution. This problem was originally proposed with the points always being the vertices of a convex polygon. This allows us to do a slightly different solution where we first merge the cycles and choose the pivot afterwards by choosing a point unaffected by the previous swaps. The reason for having $n = 2000$ in this problem rather than a larger $n$ like $10^5$ is because of the validator: it is essential to not have three collinear points in this problem, and I don't know how to check this for large $n$. The small $n$ also makes the checker much easier to write, though it's possible (albeit tricky) to write a checker that works in $O(n \\log n)$. Regarding the number of operations used: The solution described in the editorial uses approximately $\\frac{3}{2}n$ operations in the worst case when the permutation consists of cycles of size $2$. The minimum number of operations is lower bounded by $n - 1$ by combinatorics reasons when the permutation is a single cycle. Moreover, by Euler's formula, we have an upper bound of $3n - 6$ operations for any valid sequence, which goes down to $2n - 3$ when the points are the vertices of a convex polygon. I don't know of a solution that uses $cn$ operations for some $c < 3/2$, nor do I know of a general test case where it can be proven that at least $cn$ operations are needed for some $c > 1$, so I'd be really interested in seeing either.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n \nstruct point {\n    ll x, y;\n    point(ll _x = 0, ll _y = 0) : x(_x), y(_y) {}\n    point operator- (const point &o) const { return point(x - o.x, y - o.y); }\n    int half() { return y < 0 || (y == 0 && x < 0); }\n};\n \nll cross(point p, point q) {\n    return p.x * q.y - p.y * q.x;\n}\n \nbool cmp(point p, point q) {\n    if(p.half() != q.half()) {\n        return p.half() < q.half();\n    }\n    return cross(p, q) > 0;\n}\n \nconst int MAXN = 2005;\npoint ps[MAXN];\nint n, a[MAXN], cyc[MAXN];\nvector<int> in_cyc[MAXN];\nvector<array<int, 2>> ops;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    cin >> n;\n    for(int i = 1; i <= n; i++) {\n        cin >> ps[i].x >> ps[i].y >> a[i];\n    }\n \n    int cur_cyc = 0, piv = 0;\n    for(int i = 1; i <= n; i++) {\n        if(a[i] == i || cyc[i])\n            continue;\n        cur_cyc++;\n        int u = i;\n        do {\n            cyc[u] = cur_cyc;\n            in_cyc[cur_cyc].push_back(u);\n            u = a[u];\n        } while(!cyc[u]);\n        piv = i;\n    }\n \n    vector<int> to_sort;\n    for(int i = 1; i <= n; i++) {\n        if(a[i] == i || i == piv)\n            continue;\n        to_sort.push_back(i);\n    }\n    if(to_sort.empty()) {\n        cout << \"0\\n\";\n        return 0;\n    }\n \n    sort(to_sort.begin(), to_sort.end(), [&](int i, int j){ return cmp(ps[i] - ps[piv], ps[j] - ps[piv]); } );\n    vector<array<int, 2>> pairs;\n    to_sort.push_back(to_sort[0]);\n    \n    for(int i = 0; i + 1 < to_sort.size(); i++) {\n        if(cross(ps[to_sort[i]] - ps[piv], ps[to_sort[i + 1]] - ps[piv]) > 0)\n            pairs.push_back({to_sort[i], to_sort[i + 1]});\n    }\n    for(auto &[i, j] : pairs) {\n        int c1 = cyc[i], c2 = cyc[j];\n        if(c1 != c2) {\n            for(auto &x : in_cyc[c2]) {\n                cyc[x] = c1;\n                in_cyc[c1].push_back(x);\n            }\n            in_cyc[c2].clear();\n            ops.push_back({i, j});\n            swap(a[i], a[j]);\n        }\n    }\n \n    while(a[piv] != piv) {\n        int u = a[piv];\n        ops.push_back({piv, u});\n        swap(a[piv], a[u]);\n    }\n \n    cout << ops.size() << '\\n';\n    for(auto &[i, j] : ops)\n        cout << i << \" \" << j << '\\n';\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1508",
    "index": "E",
    "title": "Tree Calendar",
    "statement": "Yuu Koito and Touko Nanami are newlyweds! On the wedding day, Yuu gifted Touko a directed tree with $n$ nodes and rooted at $1$, and a labeling $a$ which is some DFS order of the tree. Every edge in this tree is directed away from the root.\n\nAfter calling dfs(1) the following algorithm returns $a$ as a DFS order of a tree rooted at $1$ :\n\n\\begin{verbatim}\norder := 0\na := array of length n\nfunction dfs(u):\norder := order + 1\na[u] := order\nfor all v such that there is a directed edge (u -> v):\ndfs(v)\n\\end{verbatim}\n\nNote that there may be different DFS orders for a given tree.\n\nTouko likes the present so much she decided to play with it! On each day following the wedding day, Touko performs this procedure once:\n\n- Among all directed edges $u \\rightarrow v$ such that $a_u < a_v$, select the edge $u' \\rightarrow v'$ with the lexicographically smallest pair $(a_{u'}, a_{v'})$.\n- Swap $a_{u'}$ and $a_{v'}$.\n\nDays have passed since their wedding, and Touko has somehow forgotten which date the wedding was and what was the original labeling $a$! Fearing that Yuu might get angry, Touko decided to ask you to derive these two pieces of information using the current labeling.\n\nBeing her good friend, you need to find the number of days that have passed since the wedding, and the original labeling of the tree. However, there is a chance that Touko might have messed up her procedures, which result in the current labeling being impossible to obtain from some original labeling; in that case, please inform Touko as well.",
    "tutorial": "From the structure, we see that until the end, the process is divided into $n$ phases, where the $i$-th involves phase pushing value $i$ from the root to the smallest-labeled leaf. Also in the following tutorial, I will use post-order and exit order, as well as pre-order and DFS order interchangeably. Lemma 1. After finishing pushing $i$, labels $1$ to $i$ are at the post-order positions, and the remaining labels from $i + 1$ to $n$ form the pre-order of the remaining part of the tree offsetted by $i$. Proof. There's a formal proof, but I think a better way is to show an illustration instead. After pushing $i$, we see that all green labels (label from $1$ to $i$) are at their post-order positions, while all red labels (labels from $i + 1$ to $n$) are connected and form the pre-order of the red subtree, with an offset of $i$. Moreover, this suggests that while pushing $i$, the label of the root is $i + 1$. Lemma 2. On any day, the order of the values of the children of any node stays the same. The proof will be left as an exercise for the reader, but a hint would be that for any node, a prefix of its children will be green nodes (nodes that have been pushed), the rest are red nodes (nodes that haven't been pushed). We can prove that the green nodes are ordered the same, the red nodes are ordered the same, and the green nodes are always less than the red nodes. Lemma 3. Suppose we are pushing/have just finished pushing $i$. Then the number of days that have passed is the sum of heights of all labels from $1$ to $i$. Proof. All labels that have finished being pushed, or are being pushed, have all traversed from the root down to their current position, which means the number of days to push each of these labels is equal to the height of the node containing the label. With the three lemmas, we can finally discuss the algorithm: First, we sort the children of each node by its value. Then we use this order to create the pre-order of the tree, and we can also figure out the current value that is being pushed (it is the value of the root minus 1). Call this value $v$. Knowing the current value being pushed, we first check if the current value is being pushed to the correct destination (i.e. check if the node with label $v$ is an ancestor of the node with post-order $v$). Then, we can \"revert\" the pushing of $v$ by swapping it back up the root, also taking to account the number of days. Finally, we check if values $< v$ are in the post-order positions, and values that are $\\ge v$ form the pre-order shifted by $v - 1$ of the remaining of the tree. Complexity is $O(n \\log n)$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "sortings",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1508",
    "index": "F",
    "title": "Optimal Encoding",
    "statement": "Touko's favorite sequence of numbers is a permutation $a_1, a_2, \\dots, a_n$ of $1, 2, \\dots, n$, and she wants some collection of permutations that are similar to her favorite permutation.\n\nShe has a collection of $q$ intervals of the form $[l_i, r_i]$ with $1 \\le l_i \\le r_i \\le n$. To create permutations that are similar to her favorite permutation, she coined the following definition:\n\n- A permutation $b_1, b_2, \\dots, b_n$ allows an interval $[l', r']$ to holds its shape if for any pair of integers $(x, y)$ such that $l' \\le x < y \\le r'$, we have $b_x < b_y$ if and only if $a_x < a_y$.\n- A permutation $b_1, b_2, \\dots, b_n$ is $k$-similar if $b$ allows all intervals $[l_i, r_i]$ for all $1 \\le i \\le k$ to hold their shapes.\n\nYuu wants to figure out all $k$-similar permutations for Touko, but it turns out this is a very hard task; instead, Yuu will encode the set of all $k$-similar permutations with directed acylic graphs (DAG). Yuu also coined the following definitions for herself:\n\n- A permutation $b_1, b_2, \\dots, b_n$ satisfies a DAG $G'$ if for all edge $u \\to v$ in $G'$, we must have $b_u < b_v$.\n- A $k$-encoding is a DAG $G_k$ on the set of vertices $1, 2, \\dots, n$ such that a permutation $b_1, b_2, \\dots, b_n$ satisfies $G_k$ if and only if $b$ is $k$-similar.\n\nSince Yuu is free today, she wants to figure out the minimum number of edges among all $k$-encodings for each $k$ from $1$ to $q$.",
    "tutorial": "We will first solve the problem for $q$-similar permutations only. Let's transform each of the $q$ ranges into edges on a DAG we call $G$: for all ranges $[l_i, r_i]$, for all pairs of indices $l \\le x, y \\le r$ such that $a_x < a_y$, we add an edge from $x$ to $y$. We can easily see a permutation is $q$-similar iff it satisfies $G$. Now, our task is to remove edges from $G$ such that the number of permutations that satisfy it stays the same. Lemma 1. We can remove an edge $(u, v)$ if and only if there is a path from $u$ to $v$ with length $\\ge 2$. Proof. If there exists a path of length $\\ge 2$ between $(u, v)$, then we can remove the edge $(u, v)$ without having to worry about losing dependency between $u$ and $v$. On the other hand, if there doesn't exist such a path, then the only path connecting $u$ and $v$ is via the edge $(u, v)$ itself; removing that edge removes any dependency between $u$ and $v$. When that is the case, we can easily create a permutation such that $a_v = a_u + 1$, then we simply swap $a_u$ and $a_v$ to gain a permutation that does not satisfy the original DAG. Let's return to our problem. For any element $u$, we consider the edges connecting $u \\to v$ such that $v > u$ a right edge of $u$; we define a left edge of $u$ in a similar manner. Lemma 2. There is at most one right edge of $u$. Proof. Suppose there are two right edges of $u$, namely $u \\to w'$ and $u \\to w$ (suppose $w' < w$). Because of our range construction, there must be a range that covers both $u$ and $w$. This range must covers $w'$ too, therefore there is a path between $w$ and $w'$, therefore we can remove either $u \\to w$ or $u \\to w'$. Therefore, there is at most one right edge $u \\to u_r$. We can actually find this right edge: suppose $[l, r]$ is a range such that $l \\le u \\le r$, and $r$ is as large as possible. Then $u_r$ is the index between $u$ and $r$ such that $a_{u_r} > a_u$ and $a_{u_r}$ is as small as possible. We can prove similar results with the left edge of $u$ (denoted as $u \\to u_l$). However, there will be cases when $u \\to u_r$ is actually not needed (I will call this phenomenon being hidden). What is the condition for $u \\to u_r$ to be hidden? That's when there's a path from $u$ to $u_r$ with length $\\ge 2$! Suppose this path is in the format $u \\to \\dots \\to t \\to u_r$. We can prove that $t < u$: if $t > u$ then that implies $a_t > a_u$ but $a_t < a_{u_r}$, which means the right edge of $u$ is $u \\to t$ instead. Because $t < u$, we can take the range $[l, r]$ such that $l \\le u_r \\le r$, $l$ is as small as possible, and check if there exists an index $t \\in [l, u]$ such that $a_u < a_t < a_w$. That concludes the solution for finding the optimal encoding for $q$-permutations. To recap: Find left and right edges of all $u$. Check if the left/right edges of all $u$ are hidden. If they are, remove them from the answer. Let's return to the original problem. For each range $[l_i, r_i]$, instead of adding an edge for every $l \\le x, y \\le r$ to $G$, let's only add an edge between $x'$ and $y'$ such that $a_{x'}$ and $a_{y'}$ are adjacent values in the range. This doesn't change our answer because of lemma 1. Let's call these edges candidate edges. Surprisingly, all of our previous observations hold, but this time on the set of candidate edges. Namely, At any query, there is at most one right edge $u \\to u_r$, which is one of the candidate edges. The right edge $u \\to u_r$ must satisfy that $u_r > u$, $a_{u_r} < a_u$ and $a_{u_r}$ is the smallest such value in the range $[u, r]$, where $[l, r]$ is the range covering $u$ with the largest $r$. $u \\to u_r$ is hidden if there exists a candidate edge $u \\to t$ such that $t < u$, $a_u < a_t < a_{u_r}$, and $t \\in [l, u]$ where $[l, r]$ is the range covering $u_r$ with the smallest $l$. We call this edge $u \\to t$ the destroyer of the edge $u \\to u_r$. All of the above points holds for the left edge $u \\to u_l$. Let's organize the candidate edges: for any edge $u \\to v$, if $v > u$, label $u \\to v$ as a right candidate edge of $u$, else label $u$ as a left candidate edge of $u$. Let's sort the right candidate edges of $u$ by increasing $u_r$, and sort the left candidate edges of $u$ by decreasing $u_l$. Observation. The values of the right end of the right candidate edges are decreasing, i.e. if the right candidate edges of $u$ are $u \\to u_{r,1}, u \\to u_{r,2}, ..., u \\to u_{r,k}$ such that, $u_{r,1} < u_{r,2} < \\dots < u_{r,k}$, then $a_{u_{r,1}} > a_{u_{r,2}} > \\dots > a_{u_{r,k}}$. Similarly, if we sort the left candidate edges of $u$ by decreasing index, then the values of the left end of these candidate edges are decreasing. Using this observation, we can prove that if the destroyer of $u \\to u_{r_i}$ is $u \\to u_{l_j}$, and the destroyer of $u \\to u_{r_{i + 1}}$ is $u \\to u \\to u_{l, k}$, then $u_{l, j} \\ge u_{l, k}$, or $j \\le k$; we can also prove a similar result with the destroyers of left candidate edges. Therefore, we can use two pointers to figure out the destroyer for each left and right candidate edge of $u$. For each right candidate edge $[u \\to u_{r,i}]$, let's see when this candidate edge is used in the optimal encoding: The candidate edge is first activated when there exists a range covering $[u, u_{r, i}]$. We call this timestamp $t_1$. The candidate edge is hidden when there exists a range covering $[u_{l, j}, u_{r,i}]$, where $u \\to u_{l,j}$ is the destroyer of $u \\to u_{r,i}$. We call this timestamp $t_2$. The candidate edge is deactivated when there exists a range covering $[u, u_{r, i + 1}]$, where $u \\to u_{r, i + 1}$ is the right candidate edge after $u \\to u_{r,i}$. We call this timestamp $t_3$. For each candidate edge, we can find these timestamps using a Fenwick tree. With these three timestamps, we can figure out the range of time where each candidate edge is used (which is $[t_1, \\min(t_2, t_3))$), and modify the answer accordingly. Finally, let's find out how many candidate edges there are: Lemma 3. The number of candidate edges is $O(n \\sqrt{q})$. Proof. Suppose for a range $[l, r]$, we maintain edges $u \\to v$ such that $l \\le u, v \\le r$, and the values $a_u$ and $a_v$ are adjacent in the range $[l, r]$. When we add/subtract one of the ends by 1, i.e. when we consider $[l \\pm 1, r \\pm 1]$, the amount of edges that are modified between $[l, r]$ and $[l \\pm 1, r \\pm 1]$ is $O(1)$ (for example, if we add another element, then we remove at most 1 old edge and add at most 2 new edges; similarly, when removing an element, we remove at most 2 old edges and add at most 1 new edge). Therefore, consider Mo's algorithm on the given collection of ranges $[l_i, r_i]$, each candidate edge must appear during the process of iterating over the ranges, and the number of modification is $O(n \\sqrt{q})$, therefore the number of candidate edges is $O(n \\sqrt{q})$. That concludes the solution to the full problem. To recap: Find all candidate edges. Find the destroyer of all candidate edges. Find the range of timestamps where each candidate edge is used. The complexity is $O(n \\sqrt{q} \\log n)$. Notes. In particular, your set candidate edges does not have to be exactly the edges connecting consecutive values between ranges; these candidate edges only need to satisfy 3 conditions: All edges that are included in some optimal $k$-encoding must be present in the set of candidate edges. The observation is not violated, i.e. if we sort the left/right candidate edges of any node $u$ by the other endpoint, then the value at the other endpoint must be sorted as well. The number of candidate edges must not be too large, at about $O(n \\sqrt{q})$ edges. This is to loosen up the process of generating the candidate edges, since the naive Mo-and-set-of-values approach is incredibly expensive. My edge-generating approach involves using Mo with rollback to only allow deletion of values so I can maintain the sorted values with a linked list, and I also do not delete intermediary edges while iterating one range to another.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing namespace chrono;\n \nconst int N = 25005, Q = 100005, D = 80;\n \nint n, q, a[N], l[Q], r[Q], pos[N], ans[Q];\nset<int> se;\nvector<pair<int, int>> edges;\nvector<int> in, out;\nvector<pair<int, int>> l_edge[N], r_edge[N];\nvector<array<int, 3>> eve[N];\nvector<pair<int, int>> add[N];\nvector<pair<int, int>> cur, fin;\n \nstruct fenwick_tree {\n    int bit[N];\n \n    void init() {\n        fill(bit + 1, bit + n + 1, Q);\n    }\n \n    void update(int u, int v) {\n        for (; u > 0; u -= u & -u) {\n            bit[u] = min(bit[u], v);\n        }\n    }\n    \n    int query(int u) {\n        int ans = Q;\n        for (; u <= n; u += u & -u) {\n            ans = min(ans, bit[u]);\n        }\n        return ans;\n    }\n} bit;\n \nvoid find_all_edges() {\n    auto add_node = [&](int u) {\n        auto it = se.insert(u).first;\n        if (it != se.begin()) {\n            cur.push_back({*prev(it), u});\n        }\n        if (next(it) != se.end()) {\n            cur.push_back({u, *next(it)});\n        }\n    };\n    auto remove_node = [&](int u) {\n        se.erase(u);\n        auto it = se.lower_bound(u);\n        if (it != se.end() && it != se.begin()) {\n            cur.push_back({*prev(it), *it});\n        }\n    };\n    auto flush_pair = [&]() {\n        for (auto [u, v] : cur) {\n            fin.push_back({u, v});\n        }\n        cur.clear();\n    };\n    vector<int> que;\n    for (int i = 1; i <= q; i++) {\n        que.push_back(i);\n    }\n    sort(que.begin(), que.end(), [](const int u, const int v) {\n        return l[u] / D != l[v] / D ? l[u] < l[v] : r[u] < r[v];\n    });\n    int le = 1, ri = 0;\n    for (int ind : que) {\n        int cl = l[ind], cr = r[ind];\n        while (ri < cr) {\n            add_node(a[++ri]);\n        }\n        while (le > cl) {\n            add_node(a[--le]);\n        }\n        while (ri > cr) {\n            remove_node(a[ri--]);\n        }\n        while (le < cl) {\n            remove_node(a[le++]);\n        }\n        flush_pair();\n    }\n    edges = vector<pair<int, int>>(fin.begin(), fin.end());\n    sort(edges.begin(), edges.end());\n    edges.erase(unique(edges.begin(), edges.end()), edges.end());\n    in = vector<int>(edges.size(), Q - 1);\n    out = vector<int>(edges.size(), Q - 1);\n}\n \nvoid build_events() {\n    for (int i = 0; i < edges.size(); i++) {\n        auto [u, v] = edges[i];\n        int iu = pos[u], iv = pos[v];\n        (iv > iu ? r_edge : l_edge)[iu].push_back({iv, i});\n    }\n    for (int i = 1; i <= n; i++) {\n        vector<pair<int, int>> &le = l_edge[i], &re = r_edge[i];\n        reverse(le.begin(), le.end());\n        reverse(re.begin(), re.end());\n        le.push_back({0, -1});\n        re.push_back({n + 1, -1});\n        int pl = 0, pr = 0;\n        while (pl < le.size() - 1 || pr < re.size() - 1) {\n            if (a[le[pl].first] > a[re[pr].first]) {\n                int qi = le[pl].second;\n                int u = i, v = le[pl].first; // (edge u => v, go to left)\n                int t = re[pr].first;\n                int vn = le[pl + 1].first;\n                eve[v].push_back({u, qi, 0});\n                eve[vn].push_back({u, qi, 1});\n                eve[v].push_back({t, qi, 1});\n                pl++;\n            } else {\n                int qi = re[pr].second;\n                int u = i, w = re[pr].first; // (edge u => w, go to right)\n                int t = le[pl].first;\n                int wn = re[pr + 1].first;\n                eve[u].push_back({w, qi, 0});\n                eve[t].push_back({w, qi, 1});\n                eve[u].push_back({wn, qi, 1});\n \n                pr++;\n            }\n        }\n    }\n \n    for (int i = 1; i <= q; i++) {\n        add[l[i]].push_back({r[i], i});\n    }\n}\n \nvoid solve() {\n    bit.init();\n    for (int i = 1; i <= n; i++) {\n        for (auto [r, v] : add[i]) {\n            bit.update(r, v);\n        }\n        for (auto [r, i, t] : eve[i]) {\n            int &upd = (t == 0 ? in[i] : out[i]);\n            upd = min(upd, bit.query(r));\n        }\n    }\n    for (int i = 0; i < edges.size(); i++) {\n        ans[in[i]]++;\n        ans[out[i]]--;\n    }\n    for (int i = 1; i <= q; i++) {\n        ans[i] += ans[i - 1];\n        cout << ans[i] << '\\n';\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cin >> n >> q;\n    for (int i = 1; i <= n; i++) {\n        cin >> a[i];\n        pos[a[i]] = i;\n    }\n    for (int i = 1; i <= q; i++) {\n        cin >> l[i] >> r[i];\n    }\n    find_all_edges();\n    build_events();\n    solve();\n}",
    "tags": [
      "brute force",
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1509",
    "index": "A",
    "title": "Average Height",
    "statement": "Sayaka Saeki is a member of the student council, which has $n$ other members (excluding Sayaka). The $i$-th member has a height of $a_i$ millimeters.\n\nIt's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wants to arrange all the members in a line such that the amount of photogenic consecutive pairs of members is \\textbf{as large as possible}.\n\nA pair of two consecutive members $u$ and $v$ on a line is considered photogenic if their average height is an integer, i.e. $\\frac{a_u + a_v}{2}$ is an integer.\n\nHelp Sayaka arrange the other members to \\textbf{maximize} the number of photogenic consecutive pairs.",
    "tutorial": "For two consecutive members to be non-photogenic, $a_u$ and $a_v$ must have different parity. Therefore, to maximize the number of photogenic pairs, or to minimize the number of non-photogenic pairs, we will order the members so that all members with even height are in front and all members with odd height are at the back.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t, n;\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n        partition(a.begin(), a.end(), [&](const int u) {\n            return u % 2;\n        });\n        for (int i = 0; i < n; i++) {\n            cout << a[i] << \" \\n\"[i == n - 1];\n        }\n    }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1509",
    "index": "B",
    "title": "TMT Document",
    "statement": "The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.\n\nHowever, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length $n$ whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences.\n\nA string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero) characters.",
    "tutorial": "There are many slightly different solutions, all based on some sort of greedy idea. Write $n = 3k$ for convenience. Obviously, the string must have $k$ characters M and $2k$ characters T for the partition to be possible, so we can just discard all other cases. Now, let's consider the first M character in the string. This must be part of some TMT subsequence, so we must choose a T character to its left to work as the first character of this subsequence. Which character should we choose? Well, it seems intuitive to match it with the first T character we find going from left to right - it is certainly not the right character of any sequence, and it seems like a good idea to assign it to the first M character since characters that are further to the right may be too far right to match with this character. Continuing this idea, we come up with the following greedy algorithm: Take the first $k$ T characters and use them as the first characters of the subsequences, matching them with the $k$ M characters from left to right greedily. Similarly, take the last $k$ T characters and match them with each M character from left to right greedily. If either of these steps fails, the partition is impossible. This can be formalized into the following observation, which is both easy to prove and gives a solution that is very easy to implement. Claim. Let $m_1 < m_2 < \\dots < m_k$ be the positions of the M characters and let $t_1 < t_2 < \\dots < t_{2k}$ be the positions of the T characters. Then the partition exists if and only if $t_i < m_i < t_{i + k}$ for $1 \\le i \\le k$. Proof. If the condition holds then we can just choose the $k$ subsequences with indices $(t_i, m_i, t_{i + k})$, so it is sufficient. To see that it's necessary, consider the first $i$ M characters with indices $m_1, m_2, \\dots, m_i$, and consider the left T characters in the subsequence they're in. These are to the left of their corresponding M characters, and in particular they are to the left of the $i$-th M character. Thus there's at least $i$ T characters to the left of the $i$-th M character, meaning $t_i < m_i$. The other inequality is proved similarly. Do yourself a favor and listen to Towa-sama's singing! Here are some links to cool songs.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nbool solve() {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    vector<int> t, m;\n    for(int i = 0; i < n; i++) {\n        if(s[i] == 'T')\n            t.push_back(i);\n        else\n            m.push_back(i);\n    }\n    if(t.size() != 2 * m.size())\n        return false;\n    for(int i = 0; i < m.size(); i++) {\n        if(m[i] < t[i] || m[i] > t[i + m.size()])\n            return false;\n    }\n    return true;\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while(t--) {\n        cout << (solve() ? \"YES\" : \"NO\") << '\\n';\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1509",
    "index": "C",
    "title": "The Sports Festival",
    "statement": "The student council is preparing for the relay race at the sports festival.\n\nThe council consists of $n$ members. They will run one after the other in the race, the speed of member $i$ is $s_i$. The discrepancy $d_i$ of the $i$-th stage is the difference between the maximum and the minimum running speed among the first $i$ members who ran. Formally, if $a_i$ denotes the speed of the $i$-th member who participated in the race, then $d_i = \\max(a_1, a_2, \\dots, a_i) - \\min(a_1, a_2, \\dots, a_i)$.\n\nYou want to minimize the sum of the discrepancies $d_1 + d_2 + \\dots + d_n$. To do this, you are allowed to change the order in which the members run. What is the minimum possible sum that can be achieved?",
    "tutorial": "Assume that the array of speeds is sorted, i.e. $s_1 \\le s_2 \\le \\dots \\le s_n$. The key observation is that the last running can be assumed to be either $s_1$ or $s_n$. This is because if $s_1$ and $s_n$ are both in the prefix of length $i$, then clearly $d_i = s_n - s_1$, which is the maximum possible value of any discrepancy. Similarly $d_{i + 1}, d_{i + 2}, \\dots, d_n$ are all equal to $s_n - s_1$. This moving either $s_1$ or $s_n$ (whichever appears last) to the very end of the array cannot possibly increase the sum of these discrepancies, since they already have the largest possible value. If we repeat the previous observation, we deduce that for each $i$, the prefix of length $i$ in an optimal solution forms a contiguous subarray of the sorted array. Therefore, we may solve the problem through dynamic programming: $dp(l, r)$ represents the minimum possible answer if we solve for the subarray $s[l \\dots r]$. Clearly $dp(x, x) = 0$, and the transition is given by $dp(l, r) = s_r - s_l + \\min(dp(l + 1, r), dp(l, r - 1))$ Which corresponds to placing either the smallest or the largest element at the end of the sequence. The final answer is $dp(1, n)$. This allows us to solve the problem in $O(n^2)$. This problem was originally going to appear in Codeforces Round 668 (Div. 2), but it was removed one day before the contest for balance reasons :P",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n \nconst int MAX = 2e3 + 5;\nll mem[MAX][MAX], a[MAX];\n \nll dp(int l, int r) {\n    if(mem[l][r] != -1)\n        return mem[l][r];\n    if(l == r)\n        return 0;\n    return mem[l][r] = a[r] - a[l] + min(dp(l + 1, r), dp(l, r - 1));\n}\n \nint main() {\n    int n;\n    cin >> n;\n \n    for(int i = 0; i < n; i++)\n        cin >> a[i];\n \n    sort(a, a + n);\n    memset(mem, -1, sizeof mem);\n \n    cout << dp(0, n - 1) << '\\n';\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1511",
    "index": "A",
    "title": "Review Site",
    "statement": "You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote.\n\nHowever, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.\n\n$n$ reviewers enter the site one by one. Each reviewer is one of the following types:\n\n- type $1$: a reviewer has watched the movie, and they like it — they press the upvote button;\n- type $2$: a reviewer has watched the movie, and they dislike it — they press the downvote button;\n- type $3$: a reviewer hasn't watched the movie — they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie.\n\nEach reviewer votes on the movie exactly once.\n\nSince you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one.\n\nWhat is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?",
    "tutorial": "Notice that the answer depends only on the number of the reviewers of the third type who upvote the movie. Optimally we would want every single reviewer of the third type to upvote. We can achieve it with the following construction: send all reviewers of the first type to the first server, all reviewers of the second type to the second server and all reviewers of the third type to the first server. Since there are no downvotes on the first server, all reviewers of the third type will upvote. Thus, the answer is the total number of reviewers of the first and the third type. Overall complexity: $O(n)$ per testcase.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        readLine()!!.toInt()\n        println(readLine()!!.split(' ').count { it != \"2\" })\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1511",
    "index": "B",
    "title": "GCD Length",
    "statement": "You are given three integers $a$, $b$ and $c$.\n\nFind two positive integers $x$ and $y$ ($x > 0$, $y > 0$) such that:\n\n- the decimal representation of $x$ without leading zeroes consists of $a$ digits;\n- the decimal representation of $y$ without leading zeroes consists of $b$ digits;\n- the decimal representation of $gcd(x, y)$ without leading zeroes consists of $c$ digits.\n\n$gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\nOutput $x$ and $y$. If there are multiple answers, output any of them.",
    "tutorial": "The easiest way to force some gcd to be of some fixed length is to use the divisibility rules for $2$, $5$ or $10$: if the number produced by the last $y$ digits $x$ is divisible by $2^y$, then $x$ is also divisible by $2^y$ (same goes for $5^y$ and $10^y$). One of the possible constructions is the following: let $x=1\\underbrace{0..0}_{a-c}\\underbrace{0..0}_{c-1}$ and $y=1\\underbrace{1..1}_{b-c}\\underbrace{0..0}_{c-1}$. Since $10..0$ and $11..1$ are pairwise prime, gcd is $10^{c-1}$. Overall complexity: $O(1)$ per testcase.",
    "code": "for t in range(int(input())):\n\ta, b, c = map(int, input().split())\n\tprint(\"1\" + \"0\" * (a - 1), \"1\" * (b - c + 1) + \"0\" * (c - 1))",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1511",
    "index": "C",
    "title": "Yet Another Card Deck",
    "statement": "You have a card deck of $n$ cards, numbered from top to bottom, i. e. the top card has index $1$ and bottom card — index $n$. Each card has its color: the $i$-th card has color $a_i$.\n\nYou should process $q$ queries. The $j$-th query is described by integer $t_j$. For each query you should:\n\n- find the highest card in the deck with color $t_j$, i. e. the card with minimum index;\n- print the position of the card you found;\n- take the card and place it on top of the deck.",
    "tutorial": "Let's look at one fixed color. When we search a card of such color, we take the card with minimum index and after we place it on the top of the deck it remains the one with minimum index. It means that for each color we take and move the same card - one card for each color. In other words, we need to keep track of only $k$ cards, where $k$ is the number of colors ($k \\le 50$). As a result, if $pos_c$ is the position of a card of color $c$ then we can simulate a query in the following way: for each color $c$ such that $pos_c < pos_{t_j}$ we increase $pos_c$ by one (since the card will move down) and then set $pos_{t_j} = 1$. Complexity is $O(n + qk)$. But, if we look closely, we may note that we don't even need array $pos_c$. We can almost manually find the first card of color $t_j$ and move it to the first position either by series of swaps or, for example, using rotate function (present in C++) and it will work fast. Why? Let's look at one color $c$. For the first time it will cost $O(n)$ operations to search the corresponding card and move it to the position $1$. But after that, at any moment of time, the position of the card won't exceed $k$, since all cards before are pairwise different (due to the nature of queries). So, all next moves the color $c$ costs only $O(k)$ time. As a result, the complexity of such almost naive solution is $O(kn + qk)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int n, q;\n  scanf(\"%d%d\", &n, &q);\n  vector<int> a(n);\n  for (int& x : a) scanf(\"%d\", &x);\n  while (q--) {\n    int x;\n    scanf(\"%d\", &x);\n    int p = find(a.begin(), a.end(), x) - a.begin();\n    printf(\"%d \", p + 1);\n    rotate(a.begin(), a.begin() + p, a.begin() + p + 1);\n  }\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "trees"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1511",
    "index": "D",
    "title": "Min Cost String",
    "statement": "Let's define the cost of a string $s$ as the number of index pairs $i$ and $j$ ($1 \\le i < j < |s|$) such that $s_i = s_j$ and $s_{i+1} = s_{j+1}$.\n\nYou are given two positive integers $n$ and $k$. Among all strings with length $n$ that contain only the first $k$ characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.",
    "tutorial": "Consider all possible strings of length $2$ on the alphabet of size $k$ (there are $k^2$ of them). Let $cnt_i$ be the number of occurrences of the $i$-th of them in the string $s$. The cost of the string $s$ by definition is $\\sum \\limits_{i} \\frac{cnt_i(cnt_i - 1)}{2}$. Now, let's suppose there are two strings $i$ and $j$ such that $cnt_i - cnt_j \\ge 2$. Then, if we somehow reduce the number of occurrences of the string $i$ by $1$ and increase the number of occurrences of the string $j$ by $1$, the cost will decrease. So, in the optimal answer all the strings of length $2$ should appear the same number of times (and if it's impossible, the difference in the number of appearances should not be greater than $1$). Let's suppose that $k^2 = n - 1$, then our goal is to build a string where each string of length $2$ on the alphabet of $k$ characters appears exactly once. The construction of this string can be modeled using Eulerian cycles: build a directed graph with $k$ vertices, where each vertex represents a character, each arc represents a string of length $2$, and for every pair of vertices $(i, j)$, there is an arc from $i$ to $j$ (it's possible that $i = j$!). Then, by finding the Eulerian cycle in this graph (it always exists since the graph is strongly connected and, for each vertex, its in-degree is equal to its out-degree), we find a string of length $k^2 + 1$ such that all its substrings are different (so each string of length $2$ appears there once as a substring). Okay, what about the cases $k^2 > n - 1$ and $k^2 < n - 1$? Since the string we build for the case $k^2 = n - 1$ represents a cycle, we can make it \"cyclical\" and repeat the required number of times, then cut last several characters if it's too big. For example, if $n = 8$, $k = 2$, then the string for $k = 2$ is abbaa (it's not the only one, but we can use it). We can expand this string to abbaabbaa (by repeating the last $k^2$ characters), and delete the last character so its length is $8$. By the way, in this problem, you don't have to implement the algorithm that finds Eulerian cycles. The graph where we want to find the Eulerian cycle has a very special structure, and there are many different constructive ways to find the cycle in it. But if you can't use them, you always can rely on the straightforward solution that explicitly searches for the Eulerian cycle.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, k;\nint cur[26];\nvector<int> path;\n\nvoid dfs(int v) {\n  while (cur[v] < k) {\n    int u = cur[v]++;\n    dfs(u);\n    path.push_back(u);\n  }\n}\n\nint main() {\n  scanf(\"%d%d\", &n, &k);\n  dfs(0);\n  printf(\"a\");\n  for (int i = 0; i < n - 1; ++i)\n    printf(\"%c\", path[i % path.size()] + 'a');\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "greedy",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1511",
    "index": "E",
    "title": "Colorings and Dominoes",
    "statement": "You have a large rectangular board which is divided into $n \\times m$ cells (the board has $n$ rows and $m$ columns). Each cell is either white or black.\n\nYou paint each white cell either red or blue. Obviously, the number of different ways to paint them is $2^w$, where $w$ is the number of white cells.\n\nAfter painting the white cells of the board, you want to place the maximum number of dominoes on it, according to the following rules:\n\n- each domino covers two adjacent cells;\n- each cell is covered by at most one domino;\n- if a domino is placed horizontally (it covers two adjacent cells in one of the rows), it should cover only red cells;\n- if a domino is placed vertically (it covers two adjacent cells in one of the columns), it should cover only blue cells.\n\nLet the value of the board be the maximum number of dominoes you can place. Calculate the sum of values of the board over all $2^w$ possible ways to paint it. Since it can be huge, print it modulo $998\\,244\\,353$.",
    "tutorial": "There are different solutions to this problem involving combinatorics and/or dynamic programming, but, in my opinion, it's a bit easier to look at the problem from the perspective of probability theory. Let's suppose a coloring is already chosen. Then it can be covered with dominoes greedily: red and blue cells are independent from each other, and, for example, red cells can be analyzed as a set of \"strips\" of them of different length. Let's say that we cover each \"strip\" from left to right, so, in each \"strip\", the first domino covers the cells $1$ and $2$, the second domino - the cells $3$ and $4$, and so on. Let's calculate the average value of the coloring, that is, the expected value of the coloring if it is chosen randomly. Let it be $E$, then the answer is $2^w E$. By linearity of expectation, $E$ can be calculated as $\\sum\\limits_{d \\in D} p_d$, where $D$ is the set of all places we can use for a domino, and $p_d$ is the probability that there is a domino in place $d$ in our domino covering (which we construct greedily). Each domino covers two adjacent cells, so we can iterate on pairs of adjacent cells, and for each pair, find the probability that this pair is covered. Let's suppose that we want to cover the cells $(x, y)$ and $(x, y + 1)$ with a domino. Then: both of these cells should be red; the length of the red \"strip\" before these cells should be even (otherwise the cell $(x, y)$ will be paired with the cell $(x, y - 1)$). The only thing we need to know in order to calculate the probability of these two conditions being true is the number of white cells before the cell $(x, y)$ - which can be easily maintained. Knowing the number of white cells before $(x, y)$, we can either use dynamic programming to calculate the required probability, or do the math on several easy examples and try to notice the pattern: if there are $0$ white cells before the current one, the probability of that pair being covered with a domino (let's call it $P_0$) is $\\frac{1}{4}$ (both these cells should be red); if there is $1$ white cell before the current one, the probability of that pair being covered with a domino (let's call it $P_1$) is $\\frac{1}{4} - \\frac{1}{8}$ (the cells $(x, y)$ and $(x, y + 1)$ should be red, but the cell before them should not be red); $P_2$ is $\\frac{1}{4} - \\frac{1}{8} + \\frac{1}{16}$ (either the chosen two cells are red and the cell before them is not red, or all four cells are red); $P_3$ is $\\frac{1}{4} - \\frac{1}{8} + \\frac{1}{16} - \\frac{1}{32}$, and so on. So, knowing the number of white cells before $(x, y)$ and $(x, y + 1)$, we easily calculate the probability of this pair being covered by a domino. By summing up the probabilities over all pairs of adjacent white cells (don't forget the vertical ones!), we get the average (or expected) value of the coloring. All that's left is to multiply it by $2^w$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300043;\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD)\n        x -= MOD;\n    while(x < 0)\n        x += MOD;\n    return x;                         \n}\n\nint sub(int x, int y)\n{\n    return add(x, MOD - y);\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1)\n            z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nint inv(int x)\n{\n    return binpow(x, MOD - 2);   \n}\n\nint divide(int x, int y)\n{\n    return mul(x, inv(y));\n}\n\nstring s[N];\nint p[N];\nint n, m;\nchar buf[N];\n\nint main()\n{\n    scanf(\"%d %d\", &n, &m);\n    for(int i = 0; i < n; i++)\n    {\n        scanf(\"%s\", buf);\n        s[i] = buf;\n    }\n    p[0] = divide(1, 2);\n    for(int i = 1; i < N; i++)\n        if(i % 2 == 1)\n            p[i] = sub(p[i - 1], divide(1, binpow(2, i)));\n        else\n            p[i] = add(p[i - 1], divide(1, binpow(2, i)));\n    int ans = 0;\n    int w = 0;\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < m; j++)\n            if(s[i][j] != '*')\n                w = add(w, 1);\n    for(int i = 0; i < n; i++)\n    {\n        int c = 0;\n        for(int j = 0; j < m; j++)\n        {\n            if(s[i][j] == '*')\n                c = 0;\n            else\n                c++;\n            if(c > 0)\n                ans = add(ans, p[c]);\n        }\n    }\n    for(int j = 0; j < m; j++)\n    {\n        int c = 0;\n        for(int i = 0; i < n; i++)\n        {\n            if(s[i][j] == '*')\n                c = 0;\n            else\n                c++;\n            if(c > 0)\n                ans = add(ans, p[c]);\n        }\n    }\n    ans = mul(ans, binpow(2, w));\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1511",
    "index": "F",
    "title": "Chainword",
    "statement": "A chainword is a special type of crossword. As most of the crosswords do, it has cells that you put the letters in and some sort of hints to what these letters should be.\n\nThe letter cells in a chainword are put in a single row. We will consider chainwords of length $m$ in this task.\n\nA hint to a chainword is a sequence of segments such that the segments don't intersect with each other and cover all $m$ letter cells. Each segment contains a description of the word in the corresponding cells.\n\nThe twist is that there are actually two hints: one sequence is the row above the letter cells and the other sequence is the row below the letter cells. When the sequences are different, they provide a way to resolve the ambiguity in the answers.\n\nYou are provided with a dictionary of $n$ words, each word consists of lowercase Latin letters. All words are pairwise distinct.\n\nAn instance of a chainword is the following triple:\n\n- a string of $m$ lowercase Latin letters;\n- the first hint: a sequence of segments such that the letters that correspond to each segment spell a word from the dictionary;\n- the second hint: another sequence of segments such that the letters that correspond to each segment spell a word from the dictionary.\n\nNote that the sequences of segments don't necessarily have to be distinct.\n\nTwo instances of chainwords are considered different if they have different strings, different first hints \\textbf{or} different second hints.\n\nCount the number of different instances of chainwords. Since the number might be pretty large, output it modulo $998\\,244\\,353$.",
    "tutorial": "Let's use a trie to store the given words. Now let's imagine a procedure that checks if some string of length $m$ can be represented as a concatenation of some of these words. If the words were prefix-independent - no word was a prefix of another word, that task would be solvable with a greedy algorithm. We could iterate over a string and maintain the current vertex of the trie we are in. Append a current letter. If there is no such transition in a trie, it can't be represented. If the vertex we go to is a terminal, jump to the root of the trie. Otherwise, just go to that vertex. However, since the words aren't prefix-independent, we have a terminal on a path to other terminals. Thus, we can't immediately decide if we should jump to the root or just go. Let's handle this with dynamic programming. $dp[i][v]$ - can we put $i$ letters in such a way that the vertex of a trie we are in is $v$. Is building a chainword letter by letter that different from this process? Apparently, it isn't. Consider $dp[i][v][u]$ - how many ways are there to put $i$ letters in a string so that the first hint is in a vertex $v$ and the second hint is in a vertex $u$. For the transition we can try all $26$ letters to put and jump to the corresponding vertices. That obviously, is too slow. The intuition tells us that this dp should be calculated with some kind of matrix exponentiation (since $m \\le 10^9$). That dp can be rewritten as a matrix pretty easily. However, its size is up to $1681 \\times 1681$ (the maximum number of vertices in a trie squared). Some say that there is a way to compute the $m$-th power of such a huge matrix fast enough with Berlekamp-Massey, but I unfortunately am not familiar with it. Thus, we'll have to reduce the size of our matrix. First, notice that the only reachable states $(v, u)$ are such that the word that is written on a path from the root to $v$ is a suffix of a word that is written on a path from the root to $u$ or vice versa. Look at it the other way: if we build a trie on the reversed words, then one of the vertices will be an ancestor of another one. Now it's easy to estimate the number of states as the sum of depths of all vertices. However, since we look at ordered pairs of $(v, u)$, we should more or less double that amount. That should be $241$ states at max. This can probably pass with an optimal enough implementation. We can do better, though. Let's merge the states $(v, u)$ and $(u, v)$ into one state. The intuition is basically that you can swap the hints at will. That makes the pairs unordered: now there are up to $161$ pairs. That surely will work fast enough. The way to generate all the possible states is the following: run a dfs/bfs, starting from $(0, 0)$ that makes all valid transition and record all the states that can be visited. While preparing the tests, I only managed to get up to $102$ states and I would really love to hear an approach to either prove a tighter bound or to generate a test closer to the bound of $161$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int K = 161;\nconst int AL = 26;\n\nstruct node{\n\tint nxt[AL];\n\tbool term;\n\tnode(){\n\t\tmemset(nxt, -1, sizeof(nxt));\n\t\tterm = false;\n\t};\n\tint& operator [](const int x){\n\t\treturn nxt[x];\n\t}\n};\n\nvector<node> trie;\n\nint tot;\n\nvoid add(const string &s){\n\tint cur = 0;\n\tint d = 1;\n\tfor (const char &c : s){\n\t\t++d;\n\t\tif (trie[cur][c - 'a'] == -1){\n\t\t\ttrie[cur][c - 'a'] = trie.size();\n\t\t\ttrie.push_back(node());\n\t\t\ttot += d;\n\t\t}\n\t\tcur = trie[cur][c - 'a'];\n\t}\n\ttrie[cur].term = true;\n}\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\ntypedef array<array<int, K>, K> mat;\n\nmat operator *(const mat &a, const mat &b){\n\tmat c;\n\tforn(i, K) forn(j, K) c[i][j] = 0;\n\tforn(i, K) forn(j, K) forn(k, K)\n\t\tc[i][j] = add(c[i][j], mul(a[i][k], b[k][j]));\n\treturn c;\n}\n\nmat binpow(mat a, long long b){\n\tmat res;\n\tforn(i, K) forn(j, K) res[i][j] = i == j;\n\twhile (b){\n\t\tif (b & 1)\n\t\t\tres = res * a;\n\t\ta = a * a;\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nmap<pair<int, int>, int> num;\nqueue<pair<int, int>> q;\n\nint get(int v, int u){\n\tif (v > u) swap(v, u);\n\tif (!num.count({v, u})){\n\t\tint k = num.size();\n\t\tassert(k < K);\n\t\tnum[{v, u}] = k;\n\t\tq.push({v, u});\n\t}\n\treturn num[{v, u}];\n}\n\nint main() {\n\tint n;\n\tlong long m;\n\tcin >> n >> m;\n\ttrie = vector<node>(1, node());\n\ttot = 1;\n\tforn(i, n){\n\t\tstring s;\n\t\tcin >> s;\n\t\tadd(s);\n\t}\n\tq.push({0, 0});\n\tnum[q.front()] = 0;\n\tmat init;\n\tforn(i, K) forn(j, K) init[i][j] = 0;\n\twhile (!q.empty()){\n\t\tint v = q.front().first;\n\t\tint u = q.front().second;\n\t\tq.pop();\n\t\tint x = get(v, u);\n\t\tforn(c, AL){\n\t\t\tint tov = trie[v][c];\n\t\t\tint tou = trie[u][c];\n\t\t\tif (tov == -1 || tou == -1) continue;\n\t\t\t++init[x][get(tov, tou)];\n\t\t\tif (trie[tov].term) ++init[x][get(0, tou)];\n\t\t\tif (trie[tou].term) ++init[x][get(tov, 0)];\n\t\t\tif (trie[tov].term && trie[tou].term) ++init[x][0];\n\t\t}\n\t}\n\tinit = binpow(init, m);\n\tprintf(\"%d\\n\", init[0][0]);\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "matrices",
      "string suffix structures",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1511",
    "index": "G",
    "title": "Chips on a Board",
    "statement": "Alice and Bob have a rectangular board consisting of $n$ rows and $m$ columns. \\textbf{Each row contains exactly one chip.}\n\nAlice and Bob play the following game. They choose two integers $l$ and $r$ such that $1 \\le l \\le r \\le m$ and cut the board in such a way that only the part of it between column $l$ and column $r$ (inclusive) remains. So, all columns to the left of column $l$ and all columns to the right of column $r$ no longer belong to the board.\n\nAfter cutting the board, they move chips on the remaining part of the board (the part from column $l$ to column $r$). They make alternating moves, and the player which cannot make a move loses the game. The first move is made by Alice, the second — by Bob, the third — by Alice, and so on. During their move, the player must choose one of the chips from the board and move it any positive number of cells to the left (so, if the chip was in column $i$, it can move to any column $j < i$, and the chips in the leftmost column cannot be chosen).\n\nAlice and Bob have $q$ pairs of numbers $L_i$ and $R_i$. For each such pair, they want to determine who will be the winner of the game if $l = L_i$ and $r = R_i$. Note that these games should be considered independently (they don't affect the state of the board for the next games), and both Alice and Bob play optimally.",
    "tutorial": "The model solution is $O(N \\sqrt{N \\log N})$, where $N = \\max(n, m, q)$, but it seems that there are faster ones. I'll explain the model solution nevertheless. It's easy to see (using simple Nim theory) that the answer for a query $i$ is B iff the xor of $c_j - L_i$ for all chips such that $L_i \\le c_j \\le R_i$ is equal to $0$. Let's calculate this xor for every query. This number contains at most $18$ bits, and we will process these bits differently: we will choose some number $K$ and use one solution to calculate $K$ lowest bits, and another solution to compute $18 - K$ highest bits. One idea is common in both solutions: we split each query into two queries - a query $(L_i, R_i)$ can be represented as a combination of two queries $Q(L_i, L_i)$ and $Q(R_i + 1, L_i)$, where $Q(x, y)$ is the xor of all numbers $c_j - y$ such that $c_j \\ge x$. After converting the queries, for every $x \\in [1, m]$, store each query of the form $Q(x, y)$ in some sort of vector (or any other data structure). We will use an approach similar to sweep line: iterate on $x$ and solve the queries for the current $x$. These ideas will be used both for the solution calculating $K$ lowest bits and for the solution calculating $18 - K$ highest bits. How to find $K$ lowest bits in each query? Iterate on $x$ from $m$ to $1$ and maintain the number of occurrences of each number $c_i$ we met so far. Then, at a moment we want to calculate $Q(x, y)$, simply iterate on all of the values of $c_i$ and process each value in $O(1)$ (if the number of occurrences of some value $z$ is odd, update the current answer to the query by xoring the number with $z - y$, otherwise just skip it). And since we are interested only in $K$ lowest bits, for each $c_i$, we need only the remainder $c_i \\mod 2^K$, so the number of different values is $O(2^K)$. Thus, this part of the solution runs in $O(n + m + 2^Kq)$. Okay, what about $18 - K$ highest bits in each query? We can see that, for every number $c_i$, the highest bits of $c_i - x$ don't change too often when we iterate on $x$: there will be about $\\frac{m}{2^K}$ segments where the highest bits of $c_i - x$ have different values. We can build a data structure that allows use to process two queries: xor all numbers on a segment with some value and get the value in some position (Fenwick trees and segment trees can do it). Then, we again iterate on $x$ from $m$ to $1$. When we want to process a number $c_i$, we find the segments where the highest bits of $c_i - x$ have the same value and perform updates on these segments in our data structure. When we process a query of the form $Q(x, y)$, we simply get the value in the position $y$ from our data structure. This part of the solution works in $O(n \\frac{m}{2^K} \\log m + m + q)$. By choosing $K$ optimally, we can combine these two parts into a solution with complexity of $O(N \\sqrt{N \\log N})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\nconst int K = 10;\nconst int Z = 1 << K;\n\nint rem[Z];\nint t[N];\n\nint get(int r)\n{\n    int result = 0;\n    for (; r >= 0; r = (r & (r + 1)) - 1)\n        result ^= t[r];\n    return result;\n}\n\nvoid change(int i, int delta)\n{\n    for (; i < N; i = (i | (i + 1)))\n        t[i] ^= delta;\n}\n\nint get(int l, int r)\n{\n    return get(r) - get(l - 1);\n}\n\nint ans[N];\nint c[N];\nint cnt[N];\nint n, m;\nint ls[N];\nint rs[N];\nvector<int> qs[N];\nvector<int> qs2[N];\n\nint main()\n{\n    scanf(\"%d %d\", &n, &m);\n    for(int i = 0; i < n; i++)\n    {\n        scanf(\"%d\", &c[i]);\n        cnt[c[i]]++;\n    }\n    int q;\n    scanf(\"%d\", &q);\n    for(int i = 0; i < q; i++)\n    {\n        int l, r;\n        scanf(\"%d %d\", &l, &r);\n        ls[i] = l;                                                                         \n        rs[i] = r;\n        qs[l].push_back(i);\n        qs2[r + 1].push_back(i);\n    }\n    for(int i = m; i >= 1; i--)\n    {\n        for(int j = 0; j < cnt[i]; j++)\n        {\n            rem[i % (1 << K)]++;\n            int r = i;\n            while(true)\n            {\n                int l = r - Z + 1;\n                l = max(1, l);\n                if(l > r)\n                    break;\n                int diff = i - l;\n                diff >>= K;\n                change(l, diff);\n                change(r + 1, diff);\n                r -= Z;\n            }\n        }\n        for(auto x : qs[i])\n        {\n            int cur = (get(i)) << K;\n            for(int k = 0; k < Z; k++)\n            {\n                int dist = (k - i) % Z;\n                if(dist < 0)\n                    dist += Z;\n                if(rem[k] & 1)\n                    cur ^= dist;\n            }\n            ans[x] ^= cur;\n        }\n        for(auto x : qs2[i])\n        {\n            int cur = (get(ls[x])) << K;\n            for(int k = 0; k < Z; k++)\n            {\n                int dist = (k - ls[x]) % Z;\n                if(dist < 0)\n                    dist += Z;\n                if(rem[k] & 1)\n                    cur ^= dist;\n            }\n            ans[x] ^= cur;\n        }\n    }\n    for(int i = 0; i < q; i++)\n        if(ans[i] == 0)\n            printf(\"B\");\n        else\n            printf(\"A\");\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "dp",
      "games",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1512",
    "index": "A",
    "title": "Spy Detected!",
    "statement": "You are given an array $a$ consisting of $n$ ($n \\ge 3$) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array $[4, 11, 4, 4]$ all numbers except one are equal to $4$).\n\nPrint the index of the element that does not equal others. The numbers in the array are numbered from one.",
    "tutorial": "To find a number that differs from the rest of the numbers in the array, you need to iterate through the array, maintaining two pairs of numbers $(x_1, c_1)$ and $(x_2, c_2)$, where $x_i$ is a number from the array, $c_i$ is how many times the number $x_i$ occurs in the array. Then, to get an answer, you need to find the position of the $x_i$ that occurs in the array exactly once (i.e. $c_i = 1$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> v(n);\n    for (int &e : v) {\n        cin >> e;\n    }\n    vector<int> a = v;\n    sort(a.begin(), a.end());\n    for (int i = 0; i < n; i++) {\n        if (v[i] != a[1]) {\n            cout << i + 1 << \"\\n\";\n        }\n    }\n}\n\nint main() {\n    int n;\n    cin >> n;\n    while (n--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1512",
    "index": "B",
    "title": "Almost Rectangle",
    "statement": "There is a square field of size $n \\times n$ in which two cells are marked. These cells can be in the same row or column.\n\nYou are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.\n\nFor example, if $n=4$ and a rectangular field looks like this (there are asterisks in the marked cells):\n\n$$ \\begin{matrix} . & . & * & . \\\\ . & . & . & . \\\\ * & . & . & . \\\\ . & . & . & . \\\\ \\end{matrix} $$\n\nThen you can mark two more cells as follows\n\n$$ \\begin{matrix} * & . & * & . \\\\ . & . & . & . \\\\ * & . & * & . \\\\ . & . & . & . \\\\ \\end{matrix} $$\n\nIf there are several possible solutions, then print any of them.",
    "tutorial": "f two asterisks are in the same row, then it is enough to select any other row and place two asterisks in the same columns in it. If two asterisks are in the same column, then you can do the same. If none of the above conditions are met and the asterisks are at positions $(x1, y1)$, $(x2, y2)$, then you can place two more asterisks at positions $(x1, y2)$, $(x2, y1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {    \n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<string> f(n);\n        vector<pair<int,int>> p;\n        forn(i, n) {\n            cin >> f[i];\n            forn(j, n)\n                if (f[i][j] == '*')\n                    p.push_back({i, j});\n        }\n\n        p.push_back(p[0]);\n        p.push_back(p[1]);\n        if (p[0].first == p[1].first) {\n            p[2].first = (p[2].first + 1) % n;\n            p[3].first = (p[3].first + 1) % n;\n        } else if (p[0].second == p[1].second) {\n            p[2].second = (p[2].second + 1) % n;\n            p[3].second = (p[3].second + 1) % n;\n        } else\n            swap(p[2].first, p[3].first);\n\n        f[p[2].first][p[2].second] = '*';\n        f[p[3].first][p[3].second] = '*';\n        forn(i, n)\n            cout << f[i] << endl;\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1512",
    "index": "C",
    "title": "A-B Palindrome",
    "statement": "You are given a string $s$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $s$ by '0' or '1' so that the string becomes a palindrome and has \\textbf{exactly} $a$ characters '0' and \\textbf{exactly} $b$ characters '1'. Note that each of the characters '?' is replaced \\textbf{independently} from the others.\n\nA string $t$ of length $n$ is called a palindrome if the equality $t[i] = t[n-i+1]$ is true for all $i$ ($1 \\le i \\le n$).\n\nFor example, if $s=$\"01?????0\", $a=4$ and $b=4$, then you can replace the characters '?' in the following ways:\n\n- \"01011010\";\n- \"01100110\".\n\nFor the given string $s$ and the numbers $a$ and $b$, replace all the characters with '?' in the string $s$ by '0' or '1' so that the string becomes a palindrome and has \\textbf{exactly} $a$ characters '0' and \\textbf{exactly} $b$ characters '1'.",
    "tutorial": "First, let's find such positions $i$ ($1 \\le i \\le n$) such that $s[i]\\ne$'?' (symbols in symmetric positions are uniquely determined): If $s[n-i+1]=$'?', then $s[n-i+1] = s[i]$; If $s[i] \\ne s[n-i+1]$, then at the end we will not get a palindrome in any way, so the answer is '-1'. Note that after such a replacement, the remaining characters '?' are split into pairs, except maybe the central one. If the center character is '?' then it is necessary to put the character '0' if $a$ is odd, or '1' if $b$ is odd (if neither $a$, nor $b$ is odd, then the answer is '-1'). Now the remaining characters '?' are split into pairs (i.e. if $s[i]=$'?', then $s[n-i+1]=$'?'). This allows the remaining characters '0' and '1' to be replaced greedily: If $s[i]=$'?' and $a>1$, then $s[i]=s[n-i+1]=$'0' and decrease $a$ for $2$; If $s[i]=$'?' and $b>1$, then $s[i]=s[n-i +1]=$'1' and decrease $b$ for $2$; Otherwise the answer is '-1'.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid no() {\n  cout << \"-1\" << endl;\n}\n\nvoid solve() {\n  int a, b;\n  cin >> a >> b;\n  string s;\n  cin >> s;\n  for (int times = 0; times < 2; times++) {\n    for (int i = 0; i < (int) s.size(); i++) {\n      int j = (int) s.size() - i - 1;\n      if (s[i] != '?') {\n        if (s[j] == '?') {\n          s[j] = s[i];\n        } else if (s[i] != s[j]) {\n          no();\n          return;\n        }\n      }\n    }\n    reverse(s.begin(), s.end());\n  }\n  a -= count(s.begin(), s.end(), '0');\n  b -= count(s.begin(), s.end(), '1');\n  int ques = count(s.begin(), s.end(), '?');\n  bool emptyMid = (s.size() % 2 == 1 && s[s.size() / 2] == '?');\n  if (a < 0 || b < 0 || a + b != ques || (emptyMid && a % 2 == 0 && b % 2 == 0)) {\n    no();\n    return;\n  }\n  if (a % 2 == 1 || b % 2 == 1) {\n    int i = s.size() / 2;\n    if (s[i] != '?') {\n      no();\n      return;\n    }\n    s[i] = (a % 2 == 1 ? '0' : '1');\n    if (a % 2 == 1) {\n      a--;\n    } else {\n      b--;\n    }\n  }\n  if (a % 2 == 1 || b % 2 == 1) {\n    no();\n    return;\n  }\n  for (int i = 0; i < (int) s.size(); i++) {\n    if (s[i] == '?') {\n      int j = s.size() - i - 1;\n      if (a > 0) {\n        a -= 2;\n        s[i] = s[j] = '0';\n      } else {\n        b -= 2;\n        s[i] = s[j] = '1';\n      }\n    }\n  }\n  cout << s << endl;\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1512",
    "index": "D",
    "title": "Corrupted Array",
    "statement": "You are given a number $n$ and an array $b_1, b_2, \\ldots, b_{n+2}$, obtained according to the following algorithm:\n\n- some array $a_1, a_2, \\ldots, a_n$ was guessed;\n- array $a$ was written to array $b$, i.e. $b_i = a_i$ ($1 \\le i \\le n$);\n- The $(n+1)$-th element of the array $b$ is the sum of the numbers in the array $a$, i.e. $b_{n+1} = a_1+a_2+\\ldots+a_n$;\n- The $(n+2)$-th element of the array $b$ was written some number $x$ ($1 \\le x \\le 10^9$), i.e. $b_{n+2} = x$; The\n- array $b$ was shuffled.\n\nFor example, the array $b=[2, 3, 7, 12 ,2]$ it could be obtained in the following ways:\n\n- $a=[2, 2, 3]$ and $x=12$;\n- $a=[3, 2, 7]$ and $x=2$.\n\nFor the given array $b$, find any array $a$ that could have been guessed initially.",
    "tutorial": "What is the sum of all the elements in $b$? This is twice the sum of all the elements in $a$ + $x$. Denote by $B$ the sum of all the elements of $b$. Let's iterate over which of the array elements was added as the sum of the elements $a$ (let's denote, for $a$). Then, $x$ = $B-2 \\cdot A$. It remains to check that the element $x$ is present in the array $b$, this can be done using a hash table or a binary search tree.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid no() {\n  cout << \"-1\" << endl;\n}\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> b(n + 2);\n  for (int &x : b) {\n    cin >> x;\n  }\n\n  multiset<int> have(b.begin(), b.end());\n  long long sum = accumulate(b.begin(), b.end(), 0LL);\n  for (int x : b) {\n    have.erase(have.find(x));\n    sum -= x;\n    if (sum % 2 == 0 && sum <= 2'000'000'000 && have.find(sum / 2) != have.end()) {\n      have.erase(have.find(sum / 2));\n      for (int y : have) {\n        cout << y << \" \";\n      }\n      cout << endl;\n      return;\n    }\n    sum += x;\n    have.insert(x);\n  }\n  no();\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1512",
    "index": "E",
    "title": "Permutation by Sum",
    "statement": "A permutation is a sequence of $n$ integers from $1$ to $n$, in which all the numbers occur exactly once. For example, $[1]$, $[3, 5, 2, 1, 4]$, $[1, 3, 2]$ are permutations, and $[2, 3, 2]$, $[4, 3, 1]$, $[0]$ are not.\n\nPolycarp was given four integers $n$, $l$, $r$ ($1 \\le l \\le r \\le n)$ and $s$ ($1 \\le s \\le \\frac{n (n+1)}{2}$) and asked to find a permutation $p$ of numbers from $1$ to $n$ that satisfies the following condition:\n\n- $s = p_l + p_{l+1} + \\ldots + p_r$.\n\nFor example, for $n=5$, $l=3$, $r=5$, and $s=8$, the following permutations are suitable (not all options are listed):\n\n- $p = [3, 4, 5, 2, 1]$;\n- $p = [5, 2, 4, 3, 1]$;\n- $p = [5, 2, 1, 3, 4]$.\n\nBut, for example, there is no permutation suitable for the condition above for $n=4$, $l=1$, $r=1$, and $s=5$.Help Polycarp, for the given $n$, $l$, $r$, and $s$, find a permutation of numbers from $1$ to $n$ that fits the condition above. If there are several suitable permutations, print any of them.",
    "tutorial": "It is easy to show that if we choose $k$ numbers from a permutation of length $n$, then the minimum sum of $k$ numbers is $\\frac{k(k+1)}{2}$, the maximum sum is $\\frac{k(2n+1-k)}{2}$ and any sum between them is achievable (that is, you can choose exactly $k$ numbers from $n$ so that their sum is equal to the desired one). This fact allows us to implement the following greedy solution: Denote for $low(k)=\\sum\\limits_{i=1}^{k} i = \\frac{k(k+1)}{2}$, for $high(n, k)=\\sum\\limits_{i=n-k+1}^{n} i = \\frac{k(2n+1-k)}{2}$ and for $k=r-l+1$; We will consider the numbers $i=n,n-1,\\ldots,1$ and determine whether to put them in the segment $[l, r]$ or not; If $k>0$, $high(i, k) \\ge s$ and $s-i \\ge low(k-1)$, then put the number $i$ in the segment $[l, r]$ , decrease $s$ by $i$, decrease $k$ by $1$; Otherwise, we will not put the number $i$ in the segment $[l, r]$. In the end, if $s=0$, then we have chosen $r-l+1$ a number with the sum of $s$, so the remaining number can be arranged in any order. If at the end $s>0$, then there is no way to select $r-l+1$ a number from $1,2,\\ldots,n$ with the sum of $s$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    int n, l, r, s;\n    cin >> n >> l >> r >> s;\n    l--; r--;\n    for (int first = 1; first + (r - l) <= n; first++) {\n        int sum = 0;\n        for (int i = l; i <= r; i++) {\n            sum += first + (i - l);\n        }\n        if (sum <= s && s - sum <= r - l + 1) {\n            int needAdd = r - (s - sum) + 1;\n            vector<int> ans(n);\n            set<int> non_blocked;\n            for (int i = 1; i <= n; i++) {\n                non_blocked.insert(i);\n            }\n            for (int i = l; i <= r; i++) {\n                ans[i] = first + (i - l);\n                if (i >= needAdd) {\n                    ans[i]++;\n                }\n                non_blocked.erase(ans[i]);\n            }\n            if (ans[r] > n) {\n                continue;\n            }\n            non_blocked.erase(ans[r]);\n            for (int i = 0; i < l; i++) {\n                ans[i] = *non_blocked.begin();\n                non_blocked.erase(non_blocked.begin());\n            }\n            for (int i = r + 1; i < n; i++) {\n                ans[i] = *non_blocked.begin();\n                non_blocked.erase(non_blocked.begin());\n            }\n            for (int i : ans) {\n                cout << i << \" \";\n            }\n            cout << \"\\n\";\n            return;\n        }\n    }\n    cout << \"-1\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n    int n;\n    cin >> n;\n    while (n--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1512",
    "index": "F",
    "title": "Education",
    "statement": "Polycarp is wondering about buying a new computer, which costs $c$ tugriks. To do this, he wants to get a job as a programmer in a big company.\n\nThere are $n$ positions in Polycarp's company, numbered starting from one. An employee in position $i$ earns $a[i]$ tugriks every day. The higher the position number, the more tugriks the employee receives. Initially, Polycarp gets a position with the number $1$ and has $0$ tugriks.\n\nEach day Polycarp can do one of two things:\n\n- If Polycarp is in the position of $x$, then he can earn $a[x]$ tugriks.\n- If Polycarp is in the position of $x$ ($x < n$) and has at least $b[x]$ tugriks, then he can spend $b[x]$ tugriks on an online course and move to the position $x+1$.\n\nFor example, if $n=4$, $c=15$, $a=[1, 3, 10, 11]$, $b=[1, 2, 7]$, then Polycarp can act like this:\n\n- On the first day, Polycarp is in the $1$-st position and earns $1$ tugrik. Now he has $1$ tugrik;\n- On the second day, Polycarp is in the $1$-st position and move to the $2$-nd position. Now he has $0$ tugriks;\n- On the third day, Polycarp is in the $2$-nd position and earns $3$ tugriks. Now he has $3$ tugriks;\n- On the fourth day, Polycarp is in the $2$-nd position and is transferred to the $3$-rd position. Now he has $1$ tugriks;\n- On the fifth day, Polycarp is in the $3$-rd position and earns $10$ tugriks. Now he has $11$ tugriks;\n- On the sixth day, Polycarp is in the $3$-rd position and earns $10$ tugriks. Now he has $21$ tugriks;\n- Six days later, Polycarp can buy himself a new computer.\n\nFind the minimum number of days after which Polycarp will be able to buy himself a new computer.",
    "tutorial": "Since the array $a$ does not decrease, if we want to get the position $x$ at some point, it is best to get it as early as possible, because if we get it earlier, we will earn no less money. Therefore, the solution looks like this - rise to some position and earn money on it for a laptop. Let's go through the number of the position and use simple formulas to calculate the number of days it takes to raise to this position and the number of days it takes to buy a laptop. From all the options, choose the minimum one.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nvoid solve() {\n    int n, c;\n    cin >> n >> c;\n    vector<int> a(n);\n    vector<int> b(n - 1);\n    for (int &e : a) {\n        cin >> e;\n    }\n    for (int &e : b) {\n        cin >> e;\n    }\n    b.push_back(0);\n    ll ans = 1e18;\n    ll cur = 0;\n    ll bal = 0;\n    for (int i = 0; i < n; i++) {\n        ans = min(ans, cur + max(0ll, c - bal + a[i] - 1) / a[i]);\n        ll newDays = max(0ll, b[i] - bal + a[i] - 1) / a[i];\n        cur += newDays + 1;\n        bal += a[i] * newDays - b[i];\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    int n;\n    cin >> n;\n    while (n--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1512",
    "index": "G",
    "title": "Short Task",
    "statement": "Let us denote by $d(n)$ the sum of all divisors of the number $n$, i.e. $d(n) = \\sum\\limits_{k | n} k$.\n\nFor example, $d(1) = 1$, $d(4) = 1+2+4=7$, $d(6) = 1+2+3+6=12$.\n\nFor a given number $c$, find the minimum $n$ such that $d(n) = c$.",
    "tutorial": "Note that $n \\le d(n) \\le {10}^7$ (${10}^7$ is the maximum value of $c$ in the problem), so it is enough for every $n=1..{10}^7$ to calculate the value of $d(n)$. To calculate the value of $d(n)$, you can use the sieve of Eratosthenes and get the solution for $\\mathcal{O}({10}^7 \\log ({10}^7))$. Also, you can use the linear sieve of Eratosthenes to find the minimum divisor for each $n=1..{10}^7$ and use the multiplicativity of the function $d(n)$: $d(a \\cdot b) = d(a) \\cdot d(b)$ if $gcd(a, b)=1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = (int) 1e7 + 100;\n\nlong long s[N];\nint d[N];\nint ans[N];\n\nint main() {\n  fill(d, d + N, -1);\n  d[1] = 1;\n  for (int i = 2; i * i < N; i++) {\n    if (d[i] == -1) {\n      d[i] = i;\n      for (int j = i * i; j < N; j += i) {\n        if (d[j] == -1) {\n          d[j] = i;\n        }\n      }\n    }\n  }\n  s[1] = 1;\n  for (int i = 2; i < N; i++) {\n    if (d[i] == -1) {\n      d[i] = i;\n      s[i] = i + 1;\n    } else {\n      int j = i;\n      s[i] = 1;\n      while (j % d[i] == 0) {\n        j /= d[i];\n        s[i] = s[i] * d[i] + 1;\n      }\n      s[i] *= s[j];\n    }\n  }\n  fill(ans, ans + N, -1);\n  for (int i = N - 1; i > 0; i--) {\n    if (s[i] < N) {\n      ans[s[i]] = i;\n    }\n  }\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    int c;\n    cin >> c;\n    cout << ans[c] << endl;\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1513",
    "index": "A",
    "title": "Array and Peaks",
    "statement": "A sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.\n\nGiven two integers $n$ and $k$, construct a permutation $a$ of numbers from $1$ to $n$ which has \\textbf{exactly} $k$ peaks. An index $i$ of an array $a$ of size $n$ is said to be a peak if $1 < i < n$ and $a_i \\gt a_{i-1}$ and $a_i \\gt a_{i+1}$. If such permutation is not possible, then print $-1$.",
    "tutorial": "There are many ways to solve this problem. The key idea is we try to use the first $k$ largest elements from $n$ to $n-k+1$ to construct the $k$ peaks. So try constructing the array like this: $1, n, 2, n-1, 3, n-2,..., n-k+1, k+1, k+2,..., n-k$. For this answer to be possible $n-k+1 \\gt k+1$ which means $2 \\cdot k \\lt n$. If this is not the case we output $-1$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main()\n{\n     int tests;\n     cin>>tests;\n     while(tests--)\n     {\n         int n,k;\n         cin>>n>>k;\n         vector<int> ans(n+1);\n         int num=n;\n         for(int i=2;i<n;i+=2)\n         {\n              if(k==0)break;\n              ans[i]=num--;\n              k--;\n         }\n         if(k)\n         {\n             cout<<-1<<endl;\n             continue;\n         }\n         int cur=1;\n         for(int i=1;i<=n;i++)\n         {\n             if(!ans[i])\n             ans[i]=cur++;\n         }\n\n         for(int i=1;i<=n;i++)\n         cout<<ans[i]<<\" \";\n         cout<<endl;\n     }\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1513",
    "index": "B",
    "title": "AND Sequences",
    "statement": "A sequence of $n$ non-negative integers ($n \\ge 2$) $a_1, a_2, \\dots, a_n$ is called good if for all $i$ from $1$ to $n-1$ the following condition holds true: $$a_1 \\: \\& \\: a_2 \\: \\& \\: \\dots \\: \\& \\: a_i = a_{i+1} \\: \\& \\: a_{i+2} \\: \\& \\: \\dots \\: \\& \\: a_n,$$ where $\\&$ denotes the bitwise AND operation.\n\nYou are given an array $a$ of size $n$ ($n \\geq 2$). Find the number of permutations $p$ of numbers ranging from $1$ to $n$, for which the sequence $a_{p_1}$, $a_{p_2}$, ... ,$a_{p_n}$ is good. Since this number can be large, output it modulo $10^9+7$.",
    "tutorial": "Consider an arbitrary sequence $b_1,b_2,\\dots,b_n$. First let us define the arrays $AND\\_pref$ and $AND\\_suf$ of length $n$ where $AND\\_pref_i = b_1 \\: \\& \\: b_2 \\: \\& \\: \\dots \\: \\& \\: b_i$ and $AND\\_suf_i = b_{i} \\: \\& \\: b_{i+1} \\: \\& \\: \\dots \\: \\& \\: b_n$ . According to the definition of good sequence: $AND\\_pref_1 = AND\\_suf_2$ which means $b_1 = b_2 \\: \\& \\: b_3 \\: \\& \\: \\dots \\: \\& \\: b_n$ . Now $AND\\_pref_2 \\leq AND\\_pref_1 = AND\\_suf_2 \\leq AND\\_suf_3$. Also according to definition of good sequence, $AND\\_pref_2 = AND\\_suf_3$. This means that $b_1 = AND\\_pref_2 = AND\\_suf_3$. Similarly, for all $i$ from $1$ to $n$, we get $AND\\_pref_i = b_1$ and $AND\\_suf_i = b_1$. Therefore for the sequence to be good, $b_1 = b_n$ and the $b_i$ must be a super mask of $b_1$ for all $i$ from $2$ to $n-1$. Initially, we have an array $a_1,a_2,\\dots,a_n$. Let the minimum value among these elements be $x$. Let the number of elements that have the value of $x$ be $cnt$. In order to rearrange the elements of $a_1,a_2,\\dots,a_n$ to a good sequence, we need to have $cnt \\geq 2$ and the remaining elements need to be a super mask of $x$. If we don't meet this criterion, then the answer is $0$. Else the answer will be $(cnt \\cdot (cnt-1) \\cdot (n-2)!) \\% (10^9+7)$. The time complexity is $O(n)$.",
    "code": "\n#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solveTestCase()\n{\n    int MOD=1e9+7;\n    int n;\n    cin>>n;\n    vector<int> a(n);\n    for(int i=0;i<n;i++)cin>>a[i];\n    \n    int min1=*min_element(a.begin(),a.end());\n    int cnt=0;\n    \n    for(int x:a)\n    {\n        if(min1==x)cnt++;\n        if((min1&x)!=min1)\n        {\n            printf(\"0\\n\");\n            return;\n        }\n    }\n    \n    int fact=1;\n    for(int i=1;i<=n-2;i++)fact=(1LL*fact*i)%MOD;\n    int ans=(1LL * cnt * (cnt-1))%MOD;\n    ans = (1LL * ans * fact) % MOD;\n    printf(\"%d\\n\",ans);\n}\n\nint main()\n{\n    int tests;\n    cin>>tests;\n    while(tests--)\n    solveTestCase();\n    return 0;\n}\n",
    "tags": [
      "bitmasks",
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1513",
    "index": "C",
    "title": "Add One",
    "statement": "You are given an integer $n$. You have to apply $m$ operations to it.\n\nIn a single operation, you \\textbf{must} replace every digit $d$ of the number with the decimal representation of integer $d + 1$. For example, $1912$ becomes $21023$ after applying the operation once.\n\nYou have to find the length of $n$ after applying $m$ operations. Since the answer can be very large, print it modulo $10^9+7$.",
    "tutorial": "We can solve this problem using 1D dp. Let $dp_i$ be defined as the length of the string after applying operation $i$-times to the number $10$. Then, $dp_i =2$, $\\forall$ $i$ in $[0,8]$ $dp_i =3$, if $i=9$ (The final number after applying $9$ operations to the number $10$ is $109$.) (The final number after applying $9$ operations to the number $10$ is $109$.) $dp_i =dp_{i-9}+dp_{i-10}$, Otherwise.(length would be the sum of $i-9$ operations and $i-10$ operations.) (length would be the sum of $i-9$ operations and $i-10$ operations.) Now for each test case, the final answer is: $ans=\\sum_{i=1}^{|s|}\\Bigl( \\bigr(m+(int)(s[i]-'0')<10 \\bigr) ? 1 : dp_{m-10+(int)(s[i]-'0')} \\Bigr)$, where $s$ is $n$ (in form of string). Time Complexity O($m$+$t \\cdot$|$s$|), where |$s$| is the number of digits in $n$.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n\nconst int max_n = 200005, mod = 1000000007;\nint dp[max_n];\n\nsigned main(){\n\n    for(int i=0; i<9; i++)dp[i] = 2;\n    dp[9] = 3;\n    for(int i=10; i<max_n; i++){\n        dp[i] = (dp[i-9] + dp[i-10])%mod;\n    }\n\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int t;\n    cin>>t;\n    while(t--){\n        int n, m;\n        cin>>n>>m;\n        int ans = 0;\n        while(n > 0){\n            int x = n%10;\n            ans += ((m + x < 10) ? 1 : dp[m + x - 10]);\n            ans %= mod;\n            n/=10;\n        }\n        cout<<ans<<\"\\n\";\n    }\n    return 0;\n}\n",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1513",
    "index": "D",
    "title": "GCD and MST",
    "statement": "You are given an array $a$ of $n$ ($n \\geq 2$) positive integers and an integer $p$. Consider an undirected weighted graph of $n$ vertices numbered from $1$ to $n$ for which the edges between the vertices $i$ and $j$ ($i<j$) are added in the following manner:\n\n- If $gcd(a_i, a_{i+1}, a_{i+2}, \\dots, a_{j}) = min(a_i, a_{i+1}, a_{i+2}, \\dots, a_j)$, then there is an edge of weight $min(a_i, a_{i+1}, a_{i+2}, \\dots, a_j)$ between $i$ and $j$.\n- If $i+1=j$, then there is an edge of weight $p$ between $i$ and $j$.\n\nHere $gcd(x, y, \\ldots)$ denotes the greatest common divisor (GCD) of integers $x$, $y$, ....\n\nNote that there could be multiple edges between $i$ and $j$ if both of the above conditions are true, and if both the conditions fail for $i$ and $j$, then there is no edge between these vertices.\n\nThe goal is to find the weight of the minimum spanning tree of this graph.",
    "tutorial": "We will iterate from smallest to largest number like in krushkal's algorithm. By this, we will consider the edges with the smallest weight first. Now, while iterating, we will assume the current value as the gcd we want to get, let's say $g$ and we will go left and then right while going left/right, if $gcd(new\\_element, g) = g$, we will add an edge in the graph between corresponding positions of $new\\_element$ and $g$. Also while adding edge we must keep in mind that we shouldn't create a cycle. If we are forming a cycle, we shouldn't add this edge and stop spanning in that direction. We can use a DSU to check this but in this particular problem, this is not required. We can simply check previously whether there is any edge connected to $new\\_element$. If so, we will add this edge and stop spanning further as any further entry forms a cycle (Think why this is so. Hint: This is because we are adding edges in segments kind of fashion). Also, we need to stop when the current $g$ we are considering is greater than the parameter $p$ since we can connect the currently connected components by edges with weight $p$. Thus the number of edges considered would be $O(N)$, and then the overall complexity of finding $MST$ would be $O(N \\log N)$ due to sorting.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solveTestCase()\n{\n     int n,x;\n     cin>>n>>x;\n     vector<int> a(n);\n     for(int i=0;i<n;i++)cin>>a[i];\n     \n     //tells whether vertices i and i+1 are connected for 0<=i<n-1\n     vector<bool> isConnected(n);\n     vector<pair<int,int>> vals;\n     \n     for(int i=0;i<n;i++)\n     vals.push_back(make_pair(a[i],i));\n\n     sort(vals.begin(),vals.end());\n     long long int ans=0;\n     for(auto p:vals)\n     {\n         int cur_val=p.first;\n         int i=p.second;\n\n         if(cur_val>=x)break;\n         \n         while(i>0)\n         {\n              if(isConnected[i-1])break;\n              if(a[i-1]%cur_val==0)\n              {\n                   isConnected[i-1]=true;\n                   ans+=cur_val;\n                   i--;\n              }\n              else\n              break;\n         }\n         \n         i=p.second;\n         while(i<n-1)\n         {\n             if(isConnected[i])break;\n             if(a[i+1]%cur_val==0)\n             {\n                 isConnected[i]=true;\n                 ans+=cur_val;\n                 i++;\n             }\n             else\n             break;\n         }\n         \n     }\n\n     for(int i=0;i<n-1;i++)\n     {\n         if(!isConnected[i])\n         ans+=x;\n     }\n\n     cout<<ans<<endl;\n}\n\nint main()\n{\n    int T;\n    cin>>T;\n    while(T--)\n    {\n         solveTestCase();\n    }  \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dsu",
      "graphs",
      "greedy",
      "number theory",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1513",
    "index": "E",
    "title": "Cost Equilibrium",
    "statement": "An array is called beautiful if all the elements in the array are equal.\n\nYou can transform an array using the following steps any number of times:\n\n- Choose two indices $i$ and $j$ ($1 \\leq i,j \\leq n$), and an integer $x$ ($1 \\leq x \\leq a_i$). Let $i$ be the source index and $j$ be the sink index.\n- Decrease the $i$-th element by $x$, and increase the $j$-th element by $x$. The resulting values at $i$-th and $j$-th index are $a_i-x$ and $a_j+x$ respectively.\n- The cost of this operation is $x \\cdot |j-i| $.\n- Now the $i$-th index can no longer be the sink and the $j$-th index can no longer be the source.\n\nThe total cost of a transformation is the sum of all the costs in step $3$.For example, array $[0, 2, 3, 3]$ can be transformed into a beautiful array $[2, 2, 2, 2]$ with total cost $1 \\cdot |1-3| + 1 \\cdot |1-4| = 5$.\n\nAn array is called balanced, if it can be transformed into a beautiful array, and the cost of such transformation is \\textbf{uniquely} defined. In other words, the minimum cost of transformation into a beautiful array equals the maximum cost.\n\nYou are given an array $a_1, a_2, \\ldots, a_n$ of length $n$, consisting of non-negative integers. Your task is to find the number of balanced arrays which are permutations of the given array. Two arrays are considered different, if elements at some position differ. Since the answer can be large, output it modulo $10^9 + 7$.",
    "tutorial": "let $S$ = $\\sum_0^{n-1}(a_i)$. The first and foremost condition is that $S\\%n=0$, and the final values in the beautiful array will be equal to $x=S/n$. Since a node cannot operate as both, a source and a sink, therefore: Nodes with $values > x$ can only be the source vertices. Nodes with $values < x$ can only be the sink vertices. Nodes with $values = x$ with not be used as a source or a sink. The given condition, $minimumCost=maximumCost$ condition holds only when at least one of the below condition holds: Number of source vertices are zero or one. Number of sink vertices are zero or one. All the source vertices are before the sink vertices in the permutation. All the source vertices are after the sink vertices in the permutation. $f(i)$ denotes the factorial of $i$. Thus, the answer would be: If the number of source or sink is less than or equal to one, we need to consider all the unique permutations.$Ans = f(n) / (f(x_1)*f(x_2)*...)$ where $x_1, x_2, \\dots$ are frequencies of different values. $Ans = f(n) / (f(x_1)*f(x_2)*...)$ where $x_1, x_2, \\dots$ are frequencies of different values. Else,$Ans = 2 * A * B * C$ $A = ($# ways arranging source nodes$) = f(src) / (f(x_1) * f(x_2) * \\dots)$ where $x_1, x_2, \\dots$ are frequencies of different values in source nodes. $B = ($# ways arranging sink nodes$) = f(snk) / (f(x_1) * f(x_2) * \\dots)$ where $x_1, x_2, \\dots$ are frequencies of different values in sink nodes. $C = ($# ways filling $(n-src-snk)$ identical values in $(src+snk+1)$ places) = $Binomial(n, src + src)$. We have an additional factor of $2$ to cover the two possibilities: all sources before all sinks, and all sources after all sinks. $Ans = 2 * A * B * C$ $A = ($# ways arranging source nodes$) = f(src) / (f(x_1) * f(x_2) * \\dots)$ where $x_1, x_2, \\dots$ are frequencies of different values in source nodes. $B = ($# ways arranging sink nodes$) = f(snk) / (f(x_1) * f(x_2) * \\dots)$ where $x_1, x_2, \\dots$ are frequencies of different values in sink nodes. $C = ($# ways filling $(n-src-snk)$ identical values in $(src+snk+1)$ places) = $Binomial(n, src + src)$. We have an additional factor of $2$ to cover the two possibilities: all sources before all sinks, and all sources after all sinks. The overall complexity of the solution would be $O(n)$.",
    "code": "#include \"bits/stdc++.h\"\n#define ll long long\n#define MOD 1000000007\nll power(ll x,ll y, ll md=MOD){ll res = 1;x%=md;while(y){if(y&1)res = (res*x)%md;x *= x; if(x>=md) x %= md; y >>= 1;}return res;}\n \nusing namespace std;\n\n#define int long long\n\n#define MAX 100005\n\nvector<int> f(MAX);\nvector<int> inv(MAX);\n\nvoid init() {\n\tf[0] = 1;\n\tfor(int i=1;i<MAX;i++) f[i] = (f[i-1]*i)%MOD;\n\tinv[MAX-1] = power(f[MAX-1], MOD-2, MOD);\n\tfor(int i=MAX-2;i>=0;i--) inv[i] = (inv[i+1]*(i+1)) % MOD;\n\n\tfor(int i=0;i<MAX;i++) assert(inv[i]==power(f[i],MOD-2,MOD));\n}\n\nint ncr(int n, int r) {\n\tif(r > n || r < 0) return 0;\n\n\tint ans = f[n];\n\tans *= (inv[r] * inv[n - r]) % MOD;\n\tans %= MOD;\n\n\treturn ans;\n}\n\nint solve(const vector<int> &v) {\n\n\tint n = v.size();\n\tint s = 0;\n\tfor(auto x: v) s += x;\n\n\tif(!(s % n == 0)) return 0;\n\n\tint src = 0;\n\tint snk = 0;\n\n\tmap<int,int> freqSrc, freqSnk;\n\tfor(auto x: v) {\n\t\tif(s / n < x) {\n\t\t\tfreqSrc[x]++;\n\t\t\tsrc ++;\n\t\t}\n\t\tif(s / n > x) {\n\t\t\tfreqSnk[x]++;\n\t\t\tsnk ++;\n\t\t}\n\t}\n\n\tif(src == 0 && snk == 0) return 1;\n\n    if(src == 1 || snk == 1) {\n\t\tint ans = f[n];\n\t\tfor(auto x: freqSnk) {\n\t\t\tans = (ans * inv[x.second]) % MOD;\n\t\t}\n\t\tfor(auto x: freqSrc) {\n\t\t\tans = (ans * inv[x.second]) % MOD;\n\t\t}\n\t\tans *= inv[n - src - snk];\n\t\tans %= MOD;\n\t\treturn ans;\n\t}\n\n\tint ans = (2 * f[src] * f[snk]) % MOD;\n\n\t// Divide by freq of repeating elements\n\tfor(auto x: freqSnk) {\n\t\tans = (ans * inv[x.second]) % MOD;\n\t}\n\tfor(auto x: freqSrc) {\n\t\tans = (ans * inv[x.second]) % MOD;\n\t}\n\n\tint tot = src + snk;\n\tint left = n - tot;\n\n\t// Number of Solution: x_0 + x_1 + x_2 + ... + x_tot = left\n\tans = (ans * ncr(left + tot, tot)) % MOD;\n\treturn ans;\n}\n\nsigned main() {\n    \n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n\n\tinit();\n\n\tint n;\n\tcin>>n;\n\n\tvector<int> v(n);\n\tfor(auto &x: v) cin>>x;\n\n\tcout<<solve(v);\n\t\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1513",
    "index": "F",
    "title": "Swapping Problem",
    "statement": "You are given 2 arrays $a$ and $b$, both of size $n$. You can swap two elements in $b$ at most \\textbf{once} (or leave it as it is), and you are required to minimize the value $$\\sum_{i}|a_{i}-b_{i}|.$$\n\nFind the minimum possible value of this sum.",
    "tutorial": "Let's form 2 sets $X$ and $Y$. $X$ contains those indices $i$ such that $A_i$ < $B_i$ and $Y$ contains those indices $i$ such that $A_i$ > $B_i$. We call a segment $L_i$, $R_i$ as $L_i = min(A_i, B_i)$ and $R_i = max(A_i, Bi_i)$ Let break this Question into a series of observation: Observation 1: The answer will reduce by swapping two indexes $i$ and $j$ in $B$ only if: If an index $i$ belongs to X and $j$ belongs to Y. Segment $i$ and $j$ overlap. Observation 2: Based on previous observation, we are now left with only a few cases. WLOG we can fix $A_i$ and $B_i$, and see where our index $j$ be located. $B_j \\le A_i$ and $A_i \\le A_j \\le B_i$ $B_j \\le A_i$ and $B_i \\le A_j$ $B_j \\ge A_i$ and $A_i \\le A_j \\le B_i$ $B_j \\ge A_i$ and $B_i \\le A_j$ Observation 3: We can see that, in each of the cases our final answer changes by, $final\\_answer = original\\_answer - 2 * overlap(Segment_i, Segment_j)$ So, the algorithm would like this: $final\\_answer = original\\_answer - 2 * max(0, A, B)$ $A = max(min(r_i, prefix\\_Maxima(Y, l_i)) - l_i)$ where $(l_i, r_i)$ is a member of X. $B = max(min(r_i, prefix\\_Maxima(X, l_i)) - l_i)$ where $(l_i, r_i)$ is a member of Y. $prefix\\_Maxima(P,q)$ gives the maximum value of $r$ such that $l <= q$, where $(l, r)$ is a member of $P$. $prefix\\_Maxima$ can be implemented using a map, segment tree, or two-pointer approach. The overall complexity of the solution would be O(n*lg(n))",
    "code": "// created by mtnshh\n \n#include<bits/stdc++.h>\n#include<algorithm>\nusing namespace std;\n\n#define ll long long\n#define ld long double\n \n#define rep(i,a,b) for(ll i=a;i<b;i++)\n#define repb(i,a,b) for(ll i=a;i>=b;i--)\n \n#define pb push_back\n#define all(A)  A.begin(),A.end()\n#define allr(A)    A.rbegin(),A.rend()\n#define ft first\n#define sd second\n \n#define pll pair<ll,ll>\n#define V vector<ll>\n#define S set<ll>\n#define VV vector<V>\n#define Vpll vector<pll>\n \n#define endl \"\\n\"\n \nconst ll logN = 20;\nconst ll M = 1000000007;\nconst ll INF = 1e18;\n#define PI 3.14159265\n \nconst ll N = 100005;\n\nint main(){\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    ll n;\n    cin >> n;\n    \n    ll A[n], B[n];\n    \n    rep(i,0,n)  cin >> A[i];\n    rep(i,0,n)  cin >> B[i];\n\n    Vpll x1, x2, y1, y2;\n\n    ll ans = 0;\n\n    rep(i,0,n){\n\n        ans += abs(A[i]-B[i]);\n\n        if(A[i]<B[i]){\n            x1.pb({A[i], B[i]});\n            x2.pb({B[i], A[i]});\n        }\n        else{\n            y1.pb({A[i], B[i]});\n            y2.pb({B[i], A[i]});\n        }\n    }\n\n    ll fin = ans;\n\n    // \n\n    set<ll> s1;\n\n    sort(all(x1));\n    sort(all(y2));\n\n    ll cur1 = 0;\n\n    for(auto i: x1){\n\n        while(cur1 < y2.size() and y2[cur1].ft <= i.ft){\n            s1.insert(y2[cur1].sd);\n            cur1++;\n        }\n\n        if(s1.size() > 0){\n            ll last = *s1.rbegin();\n            fin = min(fin, ans - 2 * (min(i.sd, last) - i.ft));\n        }\n\n    }\n\n    set<ll> s2;\n\n    sort(all(x1));\n    sort(all(y2));\n\n    ll cur2 = 0;\n\n    for(auto i: y2){\n\n        while(cur2 < x1.size() and x1[cur2].ft <= i.ft){\n            s2.insert(x1[cur2].sd);\n            cur2++;\n        }\n\n        if(s2.size() > 0){\n            ll last = *s2.rbegin();\n            fin = min(fin, ans - 2 * (min(last, i.sd) - i.ft));\n        }\n        \n    }\n\n    cout << fin << endl;\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1514",
    "index": "A",
    "title": "Perfectly Imperfect Array",
    "statement": "Given an array $a$ of length $n$, tell us whether it has a non-empty subsequence such that the product of its elements is \\textbf{not} a perfect square.\n\nA sequence $b$ is a subsequence of an array $a$ if $b$ can be obtained from $a$ by deleting some (possibly zero) elements.",
    "tutorial": "If any element is not a perfect square, the answer is yes. Otherwise, the answer is no, because $a^2*b^2*...=(a*b*...)^2$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define MX 10000\\nbool sq[MX+5];\\nint main()\\n{\\n\\tfor (int i=1;i*i<=MX;i++)\\n\\tsq[i*i]=1;\\n\\tint t;\\n\\tscanf(\\\"%d\\\",&t);\\n\\twhile (t--)\\n\\t{\\n\\t\\tint n;\\n\\t\\tscanf(\\\"%d\\\",&n);\\n\\t\\tbool ok=1;\\n\\t\\twhile (n--)\\n\\t\\t{\\n\\t\\t\\tint a;\\n\\t\\t\\tscanf(\\\"%d\\\",&a);\\n\\t\\t\\tok&=sq[a];\\n\\t\\t}\\n\\t\\tputs(ok? \\\"NO\\\":\\\"YES\\\");\\n\\t}\\n}\\n\"",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1514",
    "index": "B",
    "title": "AND 0, Sum Big",
    "statement": "Baby Badawy's first words were \"AND 0 SUM BIG\", so he decided to solve the following problem. Given two integers $n$ and $k$, count the number of arrays of length $n$ such that:\n\n- all its elements are integers between $0$ and $2^k-1$ (inclusive);\n- the bitwise AND of all its elements is $0$;\n- the sum of its elements is as large as possible.\n\nSince the answer can be very large, print its remainder when divided by $10^9+7$.",
    "tutorial": "Let's start with an array where every single bit in every single element is $1$. It clearly doesn't have bitwise-and equal to $0$, so for each bit, we need to turn it off (make it $0$) in at least one of the elements. However, we can't turn it off in more than one element, since the sum would then decrease for no reason. So for every bit, we should choose exactly one element and turn it off there. Since there are $k$ bits and $n$ elements, the answer is just $n^k$.",
    "code": "\"#include <bits/stdc++.h>\\n\\nusing namespace std;\\n\\nint n,k;\\nconst int MOD=1e9+7;\\n\\nint main()\\n{\\n\\tint t;\\n\\tscanf(\\\"%d\\\",&t);\\n\\twhile(t--)\\n\\t{\\n\\t\\tscanf(\\\"%d %d\\\",&n,&k);\\n\\t\\tlong long ans=1;\\n\\t\\tfor(int i=0;i<k;i++) ans=(ans*n)%MOD;\\n\\t\\tprintf(\\\"%lld\\\\n\\\",ans);\\n\\t}\\n}\"",
    "tags": [
      "bitmasks",
      "combinatorics",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1514",
    "index": "C",
    "title": "Product 1 Modulo N",
    "statement": "Now you get Baby Ehab's first words: \"Given an integer $n$, find the longest subsequence of $[1,2, \\ldots, n-1]$ whose product is $1$ modulo $n$.\" Please solve the problem.\n\nA sequence $b$ is a subsequence of an array $a$ if $b$ can be obtained from $a$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $1$.",
    "tutorial": "So first observe that the subsequence can't contain any element that isn't coprime with $n$. Why? Because then its product won't be coprime with $n$, so when you take it modulo $n$, it can't be $1$. In mathier words, $gcd(prod \\space mod \\space n,n)=gcd(prod,n) \\neq 1$. Now, let's take all elements less than $n$ and coprime with it, and let's look at their product modulo $n$; call it $p$. If $p$ is $1$, you can take all these elements. Otherwise, you should take them all except for $p$. It belongs to them because $p$ is coprime with $n$, since $gcd(p \\space mod \\space n,n)=gcd(p,n)=1$ since all the elements in $p$ are coprime with $n$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nbool ok[100005];\\nint main()\\n{\\n\\tint n;\\n\\tscanf(\\\"%d\\\",&n);\\n\\tlong long prod=1;\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tif (__gcd(n,i)==1)\\n\\t\\t{\\n\\t\\t\\tok[i]=1;\\n\\t\\t\\tprod=(prod*i)%n;\\n\\t\\t}\\n\\t}\\n\\tif (prod!=1)\\n\\tok[prod]=0;\\n\\tprintf(\\\"%d\\\\n\\\",count(ok+1,ok+n,1));\\n\\tfor (int i=1;i<n;i++)\\n\\t{\\n\\t\\tif (ok[i])\\n\\t\\tprintf(\\\"%d \\\",i);\\n\\t}\\n}\\n\"",
    "tags": [
      "greedy",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1514",
    "index": "D",
    "title": "Cut and Stick",
    "statement": "Baby Ehab has a piece of Cut and Stick with an array $a$ of length $n$ written on it. He plans to grab a pair of scissors and do the following to it:\n\n- pick a range $(l, r)$ and cut out every element $a_l$, $a_{l + 1}$, ..., $a_r$ in this range;\n- stick some of the elements together in the same order they were in the array;\n- end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece.\n\nMore formally, he partitions the sequence $a_l$, $a_{l + 1}$, ..., $a_r$ into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length $x$, then no value occurs strictly more than $\\lceil \\frac{x}{2} \\rceil$ times in it.\n\nHe didn't pick a range yet, so he's wondering: for $q$ ranges $(l, r)$, what is the minimum number of pieces he needs to partition the elements $a_l$, $a_{l + 1}$, ..., $a_r$ into so that the partitioning is beautiful.\n\nA sequence $b$ is a subsequence of an array $a$ if $b$ can be obtained from $a$ by deleting some (possibly zero) elements. Note that it does \\textbf{not} have to be contiguous.",
    "tutorial": "Suppose the query-interval has length $m$. Let's call an element super-frequent if it occurs more than $\\lceil\\frac{m}{2}\\rceil$ times in it, with frequency $f$. If there's no super-frequent element, then we can just put all the elements in $1$ subsequence. Otherwise, we need the partitioning. Let's call the rest of the elements (other than the super-frequent one) good elements. One way to partition is to put all the $m-f$ good elements with $m-f+1$ super-frequent elements; then, put every remaining occurrence of the super-frequent element in a subsequence on its own. The number of subsequences we need here is then $1+f-(m-f+1)=2*f-m$. There's no way to improve this, because: for every subsequence we add, the number of occurrences of the super-frequent element minus the number of good elements is at most $1$, so by making it exactly $1$ in each subsequence, we get an optimal construction. Now, the problem boils down to calculating $f$. Note that calculating the most frequent element in general is a well-known slow problem. It's usually solved with MO's algorithm in $O(n\\sqrt{n}log(n))$, maybe with a tricky optimization to $O(n\\sqrt{n})$. However, notice that we only need the most frequent element if it occurs more than $\\lceil\\frac{m}{2}\\rceil$ times. How can we use this fact? We can pick ~$40$ random elements from our range to be candidates for the super-frequent element, then count their occurrences and maximize. If there's a super-frequent element, the probability it's not picked is at most $2^{-40}$, which is incredibly small. To count the number of occurrences of an element in a range, we can carry for each element a vector containing all the positions it occurs in increasing order. Then, upper_bound(r)-lower_bound(l) gives us the number of occurrences in $O(log(n))$. Observe that if a range has a super-frequent element, and we split it into $2$ ranges, then this element must be super-frequent in one of them. Now suppose we create a segment tree where every node $[l;r]$ returns an element in the range, and suppose every node merges the $2$ elements returned by its children as follows: count their occurrences in $[l;r]$ and pick whichever occurs more. In general, that doesn't return the most frequent element. However, if there's a super-frequent element, it must return it! That's because if there's a super-frequent element in $[l;r]$, it must be super-frequent in one of its children, so by induction the segment tree works. The time complexity is $O(nlog^2(n))$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint a[300005],tree[1200005];\\nvector<int> v[300005];\\nint cnt(int l,int r,int c)\\n{\\n\\treturn upper_bound(v[c].begin(),v[c].end(),r)-lower_bound(v[c].begin(),v[c].end(),l);\\n}\\nvoid build(int node,int st,int en)\\n{\\n\\tif (st==en)\\n\\ttree[node]=a[st];\\n\\telse\\n\\t{\\n\\t\\tint mid=(st+en)/2;\\n\\t\\tbuild(2*node,st,mid);\\n\\t\\tbuild(2*node+1,mid+1,en);\\n\\t\\ttree[node]=(cnt(st,en,tree[2*node])>cnt(st,en,tree[2*node+1])? tree[2*node]:tree[2*node+1]);\\n\\t}\\n}\\nint query(int node,int st,int en,int l,int r)\\n{\\n\\tif (en<l || st>r || r<l)\\n\\treturn 0;\\n\\tif (l<=st && en<=r)\\n\\treturn cnt(l,r,tree[node]);\\n\\tint mid=(st+en)/2;\\n\\treturn max(query(2*node,st,mid,l,r),query(2*node+1,mid+1,en,l,r));\\n}\\nint main()\\n{\\n\\tint n,q;\\n\\tscanf(\\\"%d%d\\\",&n,&q);\\n\\tfor (int i=1;i<=n;i++)\\n\\t{\\n\\t\\tscanf(\\\"%d\\\",&a[i]);\\n\\t\\tv[a[i]].push_back(i);\\n\\t}\\n\\tbuild(1,1,n);\\n\\twhile (q--)\\n\\t{\\n\\t\\tint l,r;\\n\\t\\tscanf(\\\"%d%d\\\",&l,&r);\\n\\t\\tprintf(\\\"%d\\\\n\\\",max(1,2*query(1,1,n,l,r)-(r-l+1)));\\n\\t}\\n}\"",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1514",
    "index": "E",
    "title": "Baby Ehab's Hyper Apartment",
    "statement": "This is an interactive problem.\n\nBaby Ehab loves crawling around his apartment. It has $n$ rooms numbered from $0$ to $n-1$. For every pair of rooms, $a$ and $b$, there's either a direct passage from room $a$ to room $b$, or from room $b$ to room $a$, but never both.\n\nBaby Ehab wants to go play with Baby Badawy. He wants to know if he could get to him. However, he doesn't know anything about his apartment except the number of rooms. He can ask the baby sitter two types of questions:\n\n- is the passage between room $a$ and room $b$ directed from $a$ to $b$ or the other way around?\n- does room $x$ have a passage towards any of the rooms $s_1$, $s_2$, ..., $s_k$?\n\nHe can ask at most $9n$ queries of the first type and at most $2n$ queries of the second type.\n\nAfter asking some questions, he wants to know for every pair of rooms $a$ and $b$ whether there's a path from $a$ to $b$ or not. A path from $a$ to $b$ is a sequence of passages that starts from room $a$ and ends at room $b$.",
    "tutorial": "Throughout the editorial, I'll call the first type of queries OneEdge and the second type ManyEdges. The basic idea behind this problem is to find a few edges such that every path that could be traversed in your graph could be traversed using only these edges. With that motivation in mind, let's get started. The first observation is: the graph has a hamiltonian path. To prove this, suppose you split the graph into $2$ halves, each containing some of the nodes. Then, we'll proceed by induction. Suppose each half has a hamiltonian path. I'll describe a way to merge them into one path. First, let's look at the first node in each path and ask about the edge between them. Suppose it's directed from the first to the second one. Then, I'll start my new merged path with the first node, remove it, and repeat. This works because no matter which node follows it, it sends an edge out to it. This is best described by the following picture: We start with the $2$ hamiltonian paths we got by induction, then we query that red edge. We find that it's from the grey node to the white node. We then put our grey node as the start of the path and continue doing that with the rest of the nodes, and we don't care which node will follow it, because the edge is out from the black node either way! If everything falls into place in your mind, you should recognize that this algorithm is merge sort. We just run merge sort on the nodes of the graph, using the comparator OneEdge. That gives you a hamiltonian path in $nlog(n)$ queries. Now that we have a hamiltonian path, every edge that goes forward in it is useless, since you can just walk down the path itself: So let's focus on the edges going backwards. Suppose we iterate through the hamiltonian path from its end to its beginning, looking at the edges going back from the nodes we met. An edge going backwards from the current node is important only if it goes back further than any of the edges we've met so far. That's because we can take a (much less direct) route instead of this edge if it doesn't go so far back: Now with a few more edges we can form all the paths! How do we get these edges? We can use $2$ pointers. Let's iterate through the hamiltonian path from its end to its beginning, carrying a pointer $p$ that tells us how far back the edges we met so far can go. To update $p$, let's ask ManyEdges from the node we're currently at, to the first $p$ nodes in the hamiltonian path. While the answer is $1$, we'll keep decreasing $p$. This algorithm calls ManyEdges $2n$ times, since every time we call it, it either returns $0$ and the node we're at decreases, or it returns $1$ and $p$ decreases.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nbool ManyEdges(int x,vector<int> s)\\n{\\n\\tprintf(\\\"2 %d %d\\\",x,s.size());\\n\\tfor (int i:s)\\n\\tprintf(\\\" %d\\\",i);\\n\\tprintf(\\\"\\\\n\\\");\\n\\tfflush(stdout);\\n\\tint ret;\\n\\tscanf(\\\"%d\\\",&ret);\\n\\tif (ret==-1)\\n\\texit(0);\\n\\treturn ret;\\n}\\nbool OneEdge(int a,int b)\\n{\\n\\tprintf(\\\"1 %d %d\\\\n\\\",a,b);\\n\\tfflush(stdout);\\n\\tint ret;\\n\\tscanf(\\\"%d\\\",&ret);\\n\\tif (ret==-1)\\n\\texit(0);\\n\\treturn ret;\\n}\\nvector<int> getprefix(vector<int> v,int p)\\n{\\n\\tvector<int> ret;\\n\\tfor (int i=0;i<=p;i++)\\n\\tret.push_back(v[i]);\\n\\treturn ret;\\n}\\nvector<vector<int> > getMap(int n)\\n{\\n\\tvector<vector<int> > ret(n,vector<int>(n,1));\\n\\tvector<int> path;\\n\\tfor (int i=0;i<n;i++)\\n\\tpath.push_back(i);\\n\\tstable_sort(path.begin(),path.end(),OneEdge);\\n\\tint p=n-2;\\n\\tfor (int i=n-1;i>=0;i--)\\n\\t{\\n\\t\\tif (p==i)\\n\\t\\t{\\n\\t\\t\\tfor (int j=0;j<=i;j++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tfor (int k=i+1;k<n;k++)\\n\\t\\t\\t\\tret[path[k]][path[j]]=0;\\n\\t\\t\\t}\\n\\t\\t\\tp--;\\n\\t\\t}\\n\\t\\twhile (ManyEdges(path[i],getprefix(path,p)))\\n\\t\\tp--;\\n\\t}\\n\\treturn ret;\\n}\\nint main()\\n{\\n\\tint t;\\n\\tscanf(\\\"%d\\\",&t);\\n\\twhile (t--)\\n\\t{\\n\\t\\tint n;\\n\\t\\tscanf(\\\"%d\\\",&n);\\n\\t\\tauto res=getMap(n);\\n\\t\\tputs(\\\"3\\\");\\n\\t\\tfor (int i=0;i<n;i++)\\n\\t\\t{\\n\\t\\t\\tfor (int j=0;j<n;j++)\\n\\t\\t\\tprintf(\\\"%d\\\",res[i][j]);\\n\\t\\t\\tprintf(\\\"\\\\n\\\");\\n\\t\\t}\\n\\t\\tfflush(stdout);\\n\\t\\tint ok;\\n\\t\\tscanf(\\\"%d\\\",&ok);\\n\\t\\tif (ok==-1)\\n\\t\\texit(0);\\n\\t}\\n}\\n\"",
    "tags": [
      "binary search",
      "graphs",
      "interactive",
      "sortings",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1515",
    "index": "A",
    "title": "Phoenix and Gold",
    "statement": "Phoenix has collected $n$ pieces of gold, and he wants to weigh them together so he can feel rich. The $i$-th piece of gold has weight $w_i$. All weights are \\textbf{distinct}. He will put his $n$ pieces of gold on a weight scale, one piece at a time.\n\nThe scale has an unusual defect: if the total weight on it is \\textbf{exactly} $x$, it will explode. Can he put all $n$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order.\n\nFormally, rearrange the array $w$ so that for each $i$ $(1 \\le i \\le n)$, $\\sum\\limits_{j = 1}^{i}w_j \\ne x$.",
    "tutorial": "Note that if the sum of all the weights is $x$, the scale will always explode and the answer will be NO. Otherwise, we claim there is always an answer. Basically, at each point, we choose an arbitrary gold piece to add to the scale so that it doesn't explode. There is always a valid gold piece to add because the weights are distinct. For example, we can try adding piece $1$, $2$, $\\dots$, $n$, in that order. Suppose we are currently considering the $i$-th piece. If we can add it to the scale without an explosion, we do it. If we can't, then we can just first add piece $i+1$, and then piece $i$ ($w_i \\neq w_{i+1}$ because weights are distinct). $i+1$ must be less than or equal to $n$ because otherwise, the total sum of the weights would be $x$. Time complexity for each test case: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n  int n,x;\n  int w[101];\n  cin>>n>>x;\n  int sum=0;\n  for (int i=0;i<n;i++){\n    cin>>w[i];\n    sum+=w[i];\n  }\n  //if the sum is x, we cannot avoid the explosion\n  if (sum==x){\n    cout<<\"NO\"<<endl;\n    return;\n  }\n  cout<<\"YES\"<<endl;\n  //otherwise, the answer always exists\n  //we will keep adding elements from left to right\n  //if we can't add element i, we add element i+1 first by swapping the two\n  for (int i=0;i<n;i++){\n    if (x==w[i]){\n      //i+1 will always be less than n because otherwise, the total sum would be x\n      swap(w[i],w[i+1]);\n    }\n    cout<<w[i]<<' ';\n    x-=w[i];\n  }\n  cout<<endl;\n  return;\n}\n\nint main(){\n  int T; cin>>T;\n  while (T--)\n    solve();\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1515",
    "index": "B",
    "title": "Phoenix and Puzzle",
    "statement": "Phoenix is playing with a new puzzle, which consists of $n$ identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.\n\n\\begin{center}\n{\\small A puzzle piece}\n\\end{center}\n\nThe goal of the puzzle is to create a \\textbf{square} using the $n$ pieces. He is allowed to rotate and move the pieces around, but none of them can overlap and all $n$ pieces must be used (of course, the square shouldn't contain any holes as well). Can he do it?",
    "tutorial": "If $n$ can be written as $2x$ or $4x$, where $x$ is a square number, then the answer is YES. Otherwise it is NO. To visualize this construction, we start by first building a smaller square using exactly $2$ or $4$ pieces (the drawings are in the sample test explanation). We can just use $x$ of those smaller squares to build a larger square. Let's prove that there are no other answers (although this isn't necessary to solve the problem). Let's define each triangle piece to have a short side of length $1$ and a longer side of length $\\sqrt{2}$. Consider one side of the square, and suppose that it has $a$ triangles on the short side and $b$ triangles on the longer side. The side length will be $a+\\sqrt{2}b$. The area of the square is a rational number because the area of each triangle piece is rational. So, $(a+\\sqrt{2}b)^2$ has to be rational, which means either $a$ is $0$, or $b$ is $0$. If either is $0$, we can use the construction in the previous paragraph. Time complexity for each test case: $O(\\sqrt{n})$ or $O(\\log{n})$ (depends on how you check for square numbers)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nbool isSquare(int x){\n  int y=sqrt(x);\n  return y*y==x;\n}\n\nvoid solve(){\n  int n;\n  cin>>n;\n  if (n%2==0 && isSquare(n/2))\n    cout<<\"YES\"<<endl;\n  else if (n%4==0 && isSquare(n/4))\n    cout<<\"YES\"<<endl;\n  else\n    cout<<\"NO\"<<endl;\n}\n\nint main(){\n  int t; cin>>t;\n  while (t--)\n    solve();\n}",
    "tags": [
      "brute force",
      "geometry",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1515",
    "index": "C",
    "title": "Phoenix and Towers",
    "statement": "Phoenix has $n$ blocks of height $h_1, h_2, \\dots, h_n$, and all $h_i$ don't exceed some value $x$. He plans to stack all $n$ blocks into $m$ separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than $x$.\n\nPlease help Phoenix build $m$ towers that look beautiful. Each tower must have at least one block and all blocks must be used.",
    "tutorial": "Greedily adding blocks to the current shortest tower will always give a valid solution. Let's prove it with contradiction. If the towers weren't beautiful, then some two towers would have a height difference of more than $x$. Since a single block cannot exceed a height of $x$, the difference would be more than one block. This is a contradiction with our solution because we always add to the shortest tower. To implement this, we can use a set-like structure and store pairs of ($h_i$, $i$) for each $i$ ($1 \\le i \\le m)$, where $h_i$ is the current height of the $i$-th tower (initialized to $0$). When adding a block, we remove the first element of the sorted set, update the tower height, and add it back into the set. Time complexity for each test case: $O(n \\log{n})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint N,M,X;\nint H[100001];\n\nvoid solve(){\n  cin>>N>>M>>X;\n  cout<<\"YES\"<<endl;\n  set<pair<int,int>>s; //stores pairs of (height, index)\n  for (int i=1;i<=M;i++)\n    s.insert({0,i});\n  for (int i=0;i<N;i++){\n    cin>>H[i];\n    pair<int,int>p=*s.begin();\n    s.erase(p);\n    cout<<p.second<<' ';\n    s.insert({p.first+H[i],p.second});\n  }\n  cout<<endl;\n}\n\nint main(){\n  int T; cin>>T;\n  while (T--)\n    solve();\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1515",
    "index": "D",
    "title": "Phoenix and Socks",
    "statement": "To satisfy his love of matching socks, Phoenix has brought his $n$ socks ($n$ is even) to the sock store. Each of his socks has a color $c_i$ and is either a left sock or right sock.\n\nPhoenix can pay one dollar to the sock store to either:\n\n- recolor a sock to any color $c'$ $(1 \\le c' \\le n)$\n- turn a left sock into a right sock\n- turn a right sock into a left sock\n\nThe sock store may perform each of these changes any number of times. Note that the color of a left sock doesn't change when it turns into a right sock, and vice versa.\n\nA matching pair of socks is a left and right sock with the same color. What is the minimum cost for Phoenix to make $n/2$ matching pairs? Each sock must be included in exactly one matching pair.",
    "tutorial": "First, let's remove all pairs that are already matching because an optimal solution will never change them. Suppose there remain $l$ left socks and $r$ right socks. Without loss of generality, assume $l \\geq r$. If not, we can just swap all left and right socks. We know that regardless of other operations, we will always need to turn $(l-r)/2$ left socks into right socks. So, if there are any pairs of left socks with the same color, we will first make matching pairs by turning half of them into right socks (while making sure $l$ is always at least $r$). This is optimal because since we need to turn left socks into right socks eventually, we might as well do it in a way that yields matching pairs immediately. After we equalize the number of left socks and right socks, or run out of pairs of left socks with the same color, we can finish by turning any $(l-r)/2$ left socks into right socks and then recoloring all left socks to match a right sock. Note that $l$ and $r$ change throughout this process. Time complexity for each test case: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint N,L,R;\nint C[200001];\nint lcnt[200001],rcnt[200001];\n\nvoid solve(){\n  cin>>N>>L>>R;\n  for (int i=1;i<=N;i++){\n    lcnt[i]=0;\n    rcnt[i]=0;\n  }\n  for (int i=1;i<=N;i++){\n    cin>>C[i];\n    if (i<=L)\n      lcnt[C[i]]++;\n    else\n      rcnt[C[i]]++;\n  }\n  //remove pairs that are already matching\n  for (int i=1;i<=N;i++){\n    int mn=min(lcnt[i],rcnt[i]);\n    lcnt[i]-=mn;\n    rcnt[i]-=mn;\n    L-=mn;\n    R-=mn;\n  }\n  if (L<R){\n    swap(lcnt,rcnt);\n    swap(L,R);\n  }\n  //now, there are at least as many left socks as right socks\n  int ans=0;\n  for (int i=1;i<=N;i++){\n    int extra=L-R; //always even\n    int canDo=lcnt[i]/2;\n    int Do=min(canDo*2,extra);\n    //turn \"Do\"/2 left socks of color i into right socks\n    ans+=Do/2;\n    L-=Do;\n  }\n  //turn extra lefts into rights, then adjust all colors\n  ans+=(L-R)/2+(L+R)/2;\n  cout<<ans<<endl;\n}\nint main()\n{\n  ios_base::sync_with_stdio(0);cin.tie(0);\n  int T; cin>>T;\n  while (T--)\n    solve();\n  return 0;\n}\n",
    "tags": [
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1515",
    "index": "E",
    "title": "Phoenix and Computers",
    "statement": "There are $n$ computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer $i-1$ and computer $i+1$ are both on, computer $i$ $(2 \\le i \\le n-1)$ will turn on automatically if it is not already on. Note that Phoenix cannot manually turn on a computer that already turned on automatically.\n\nIf we only consider the sequence of computers that Phoenix turns on manually, how many ways can he turn on all the computers? Two sequences are distinct if either the set of computers turned on manually is distinct, or the order of computers turned on manually is distinct. Since this number may be large, please print it modulo $M$.",
    "tutorial": "Let's first determine how many ways there are to turn on a segment of $k$ computers without any of them turning on automatically (we manually enable all $k$). We have two methods: Method 1: If we turn on computer $1$ first, then we must turn on $2$, $3$, $\\dots$, $k$ in that order. There are $k-1 \\choose 0$ ways to do this, by stars and bars. If we turn on computer $2$ first, then we must turn on $3$, $4$, $\\dots$, $k$ in that order, with computer $1$ inserted somewhere. There are $k-1 \\choose 1$ ways to do this. If we turn on computer $3$ first, then we must turn on $4$, $5$, $\\dots$, $k$ in that order, with computers $2$ and $1$ inserted somewhere (also in that order). There are $k-1 \\choose 2$ ways to do this. In total, there are $k-1 \\choose 0$ $+$ $k-1 \\choose 1$ $+$ $\\dots$ $+$ $k-1 \\choose k-1$$= 2^{k-1}$ ways. Method 2: We can prove it with induction. For the base case $k=1$, there is $1$ way. Now, if there are $x$ ways for some $k$, we wish to show that there are $2x$ ways for $k+1$. The critical observation is that the last computer in the sequence is either computer $1$ or computer $k+1$. If the last computer is $k+1$, then we have $x$ ways (we simply append $k+1$ to each previous sequence). If the last computer is $1$, then we also have $x$ ways (we append $1$ and increment every computer in the previous sequences). In total, we have $x+x=2x$ ways. Therefore, there are $2^{k-1}$ ways for any $k$. As a result, we can write $dp[len][cnt]$ - the number of ways to turn on a prefix of length $len-1$ computers having manually turned on $cnt$ computers. The last one $len$ (if $len < n$) will be turned on automatically. To transition, iterate the length $k$ of a new segment of manual computers to add and calculate the number of ways with formula ($dp[len+k+1][cnt+k]$ $+=$ $dp[len][cnt]$ $\\cdot$ $cnt + k \\choose k$ $\\cdot$ $2^{k - 1}$). The answer will be $\\sum\\limits_{i = 1}^{n} dp[n+1][i]$. Time Complexity: $O(n^3)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll MOD;\n\nint N;\nll dp[405][405];\n\nll fastexp(ll b, ll exp){\n  if (exp==0)\n    return 1;\n  ll temp=fastexp(b,exp/2);\n  temp=(temp*temp)%MOD;\n  if (exp%2==1)\n    temp*=b;\n  return temp%MOD;\n}\n\nll fact[405],inv[405],choose[405][405],pow2[405];\n\nvoid precompute(){\n  fact[0]=1;\n  inv[0]=1;\n  for (int i=1;i<=N;i++){\n    fact[i]=(fact[i-1]*i)%MOD;\n    inv[i]=fastexp(fact[i],MOD-2);\n  }\n  for (int i=0;i<=N;i++)\n    for (int j=0;j<=i;j++)\n      choose[i][j]=((fact[i]*inv[j])%MOD*inv[i-j])%MOD;\n  for (int i=0;i<=N;i++)\n    pow2[i]=fastexp(2,i);\n}\n\nint main()\n{\n  cin>>N>>MOD;\n  precompute();\n  dp[0][0]=1;\n  for (int i=0;i<N;i++){\n    for (int j=0;j<=i;j++){\n      for (int k=1;i+k<=N;k++){\n\tdp[i+k+1][j+k]+=((dp[i][j]*pow2[k-1])%MOD*choose[j+k][k]);\n\tdp[i+k+1][j+k]%=MOD;\n      }\n    }\n  }\n  ll ans=0;\n  for (int i=0;i<=N;i++)\n    ans=(ans+dp[N+1][i])%MOD;\n  cout<<ans<<endl;\n  return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1515",
    "index": "F",
    "title": "Phoenix and Earthquake",
    "statement": "Phoenix's homeland, the Fire Nation had $n$ cities that were connected by $m$ roads, but the roads were all destroyed by an earthquake. The Fire Nation wishes to repair $n-1$ of these roads so that all the cities are connected again.\n\nThe $i$-th city has $a_i$ tons of asphalt. $x$ tons of asphalt are used up when repairing a road, and to repair a road between $i$ and $j$, cities $i$ and $j$ must have at least $x$ tons of asphalt between them. In other words, if city $i$ had $a_i$ tons of asphalt and city $j$ had $a_j$ tons, there would remain $a_i+a_j-x$ tons after repairing the road between them. Asphalt can be moved between cities if the road between them is already repaired.\n\nPlease determine if it is possible to connect all the cities, and if so, output any sequence of roads to repair.",
    "tutorial": "First, note that cities connected by roads behave as one city with the total amount of asphalt. This means building a road is equivalent to merging two cities and summing their asphalt. If the total asphalt is less than $(n-1)$ $\\cdot$ $x$, then we don't have enough asphalt to repair all the roads. It turns out that if the total asphalt is at least $(n-1)$ $\\cdot$ $x$, it is always possible to repair all the roads. We can prove this by induction on the number of vertices. This is obviously true for $n=1$. Now we just need to show there is always a road that can be repaired, because doing so will reduce the number of vertices by one and the resulting asphalt will be at least $(n-2)$ $\\cdot$ $x$, so the resulting graph can be merged by the inductive hypothesis. If some city has at least $x$ asphalt, we can merge it with any neighbor. Otherwise, all cities have less than $x$ asphalt. It turns out that any two cities $i$ and $j$ must have at least $x$ asphalt between them. To see why, notice that $a_k<x$ for all $1\\le k\\le n$, so if $a_i+a_j<x$, then the total asphalt must be less than $(n-1)$ $\\cdot$ $x$. Thus, one approach is to repeatedly find the city with the most asphalt and merge it with any of its neighbors. This can be implemented with a priority queue and union-find data structure in $O(m+n\\log n)$. There are other approaches as well. For example, since only connectedness of the graph is important, we can discard all edges except for a spanning tree. Pick any leaf. If it can be merged with its parent, do so. Otherwise, it must have less than $x$ asphalt. This means deleting the leaf will leave a connected graph with at least $(n-2)$ $\\cdot$ $x$ asphalt, which can be merged recursively. The leaf is merged last. This can be implemented with a DFS in $O(m+n)$.",
    "code": "// Fix a spanning tree\n// Pick a leaf, either merge it into its parent or postpone it to the end\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n\nconst int MAXV=300005;\nconst int MAXE=300005;\n\nint N,M,X;\nlong long as[MAXV];\n\nint elist[MAXE*2];\nint head[MAXV];\nint prev[MAXE*2];\nint tot=0;\n\nbool vis[MAXV];\n\nint ans[MAXV];\nint front,back;\n\nvoid dfs(int u){\n  vis[u]=true;\n  for(int e=head[u];e!=-1;e=prev[e]){\n    int v=elist[e^1];\n    if(vis[v]) continue;\n    dfs(v);\n    if(as[u]+as[v]>=X){\n      as[u]+=as[v]-X;\n      ans[front++]=e>>1;\n    }else{\n      ans[--back]=e>>1;\n    }\n  }\n}\n\nint main(){\n  scanf(\"%d %d %d\",&N,&M,&X);\n  long long total=0;\n  for(int i=0;i<N;i++){\n    scanf(\"%lld\",&as[i]);\n    total+=as[i];\n  }\n  if(total<1LL*(N-1)*X){\n    printf(\"NO\\n\");\n    return 0;\n  }\n  std::fill(head,head+N,-1);\n  for(int i=0;i<M*2;i++){\n    int U;\n    scanf(\"%d\",&U);\n    U--;\n    prev[i]=head[U];\n    head[U]=i;\n    elist[i]=U;\n  }\n  back=N-1;\n  dfs(0);\n  printf(\"YES\\n\");\n  for(int i=0;i<N-1;i++){\n    printf(\"%d\\n\",ans[i]+1);\n  }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1515",
    "index": "G",
    "title": "Phoenix and Odometers",
    "statement": "In Fire City, there are $n$ intersections and $m$ one-way roads. The $i$-th road goes from intersection $a_i$ to $b_i$ and has length $l_i$ miles.\n\nThere are $q$ cars that may only drive along those roads. The $i$-th car starts at intersection $v_i$ and has an odometer that begins at $s_i$, increments for each mile driven, and resets to $0$ whenever it reaches $t_i$. Phoenix has been tasked to drive cars along some roads (possibly none) and \\textbf{return them to their initial intersection} with the odometer showing $0$.\n\nFor each car, please find if this is possible.\n\nA car may visit the same road or intersection an arbitrary number of times. The odometers don't stop counting the distance after resetting, so odometers may also be reset an arbitrary number of times.",
    "tutorial": "We can solve for each strongly-connected component independently. From now on, we will assume the graph is strongly-connected. Define the length of a walk to be the sum of the weights of its edges, modulo $MOD$, the distance at which the odometer resets. This is different for different queries, but the important thing is some $MOD$ exists. If there is a walk from $a$ to $b$ with length $x$, there is a walk from $b$ to $a$ with length $-x$ (for any $MOD$). To see this, note that since the graph is strongly-connected, there is a path from $b$ to $a$. Let its length be $y$. We can walk from $b$ to $a$ and back $MOD-1$ times and then go to $a$ for a total length of $(MOD)y+(MOD-1) x\\equiv -x$. Note that this works for any $MOD$, even if we don't know what it is yet. We can show that if $a$ is in a cycle of length $x$, then $b$ is in a cycle of length $x$. Suppose a path from $a$ to $b$ has length $y$. We can go from $b$ to $a$, go around the cycle, and go back to $b$ for a total length of $y+x+(-y)=x$. $a$ is in a cycle of length $0$. If $a$ is in a cycle of length $x$, it is in a cycle of $kx$ for any integer $k$. If $a$ is in a cycle of length $x$ and a cycle of length $y$, it is in a cycle of length $x+y$. The set of possible cycle lengths of cycles containing vertex $a$ are exactly the multiples of some number, namely the $\\gcd$ of all possible cycle lengths. So, if we want to determine all possible cycle lengths, we just need to compute this gcd. Fix an arbitrary spanning tree rooted at $r$ and denote the length of the tree path from $r$ to $a$ by $\\phi(a)$. If there is an edge of length $l$ from $a$ to $b$, then $r$ is in a cycle of length $\\phi(a)+l-\\phi(b)$. This cycle can be constructed by taking the walk along tree edges from $r$ to $a$, across the edge from $a$ to $b$, then backwards along tree edges from $b$ to $a$. Thus, we can make any cycles whose length is a multiple of $G=\\gcd\\{\\phi(a)+l-\\phi(b):(a,b,l)\\in E\\}$. It turns out these are the only possible lengths. If a walk from $a$ to $b$ has length $x$, then $x\\equiv \\phi(b)-\\phi(a)\\pmod G$. This can be proved by induction on the number of edges in the walk. Now that we know which cycle lengths are possible, we can answer the queries. An odometer can be reset if and only if $S$ plus some multiple of $T$ is a multiple of $G$. An odometer can be reset if and only if $S$ is a multiple of $\\gcd(T,G)$. For implementation, the easiest way to get a spanning tree is by DFS. This can be done while computing strongly-connected components.",
    "code": "#include <cstdio>\n#include <vector>\n#include <cassert>\n#include <algorithm>\n#include <cmath>\n\nusing ll = long long;\n\nstd::vector<std::pair<int,int> > fwd[200005];\nstd::vector<std::pair<int,int> > rev[200005];\n\nint vis[200005];\nint cc[200005];\nll offset[200005];\nint ncc;\nll loop[200005];\nstd::vector<int> ord;\n\nll gcd(ll a,ll b){\n  return b?gcd(b,a%b):a;\n}\n\nvoid dfs_fwd(int x){\n  vis[x]=1;\n  for(auto e:fwd[x]){\n    int y=e.first;\n    if(vis[y]!=1){\n      dfs_fwd(y);\n    }\n  }\n  ord.push_back(x);\n}\n\nvoid dfs_rev(int x){\n  vis[x]=2;\n  for(auto e:rev[x]){\n    int y=e.first,l=e.second;\n    if(vis[y]!=2){\n      cc[y]=cc[x];\n      offset[y]=offset[x]+l;\n      dfs_rev(y);\n    }else if(cc[y]==cc[x]){\n      loop[cc[x]]=gcd(loop[cc[x]],std::llabs(offset[x]+l-offset[y]));\n    }\n  }\n}\n\nint main(){\n  int N,M;\n  scanf(\"%d %d\",&N,&M);\n  for(int i=0;i<M;i++){\n    int A,B,L;\n    scanf(\"%d %d %d\",&A,&B,&L);\n    A--,B--;\n    fwd[A].push_back({B,L});\n    rev[B].push_back({A,L});\n  }\n  for(int i=0;i<N;i++){\n    if(vis[i]!=1){\n      dfs_fwd(i);\n    }\n  }\n  std::reverse(ord.begin(),ord.end());\n  for(int i:ord){\n    if(vis[i]!=2){\n      cc[i]=ncc++;\n      offset[i]=0;\n      dfs_rev(i);\n    }\n  }\n  int Q;\n  scanf(\"%d\",&Q);\n  for(int i=0;i<Q;i++){\n    int V,S,T;\n    scanf(\"%d %d %d\",&V,&S,&T);\n    V--;\n    assert(0<=S&&S<T);\n    if(S%gcd(loop[cc[V]],T)==0){\n      printf(\"YES\\n\");\n    }else{\n      printf(\"NO\\n\");\n    }\n  }\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1515",
    "index": "H",
    "title": "Phoenix and Bits",
    "statement": "Phoenix loves playing with bits — specifically, by using the bitwise operations AND, OR, and XOR. He has $n$ integers $a_1, a_2, \\dots, a_n$, and will perform $q$ of the following queries:\n\n- replace all numbers $a_i$ where $l \\le a_i \\le r$ with $a_i$ AND $x$;\n- replace all numbers $a_i$ where $l \\le a_i \\le r$ with $a_i$ OR $x$;\n- replace all numbers $a_i$ where $l \\le a_i \\le r$ with $a_i$ XOR $x$;\n- output how many \\textbf{distinct} integers $a_i$ where $l \\le a_i \\le r$.\n\nFor each query, Phoenix is given $l$, $r$, and $x$. Note that he is considering the values of the numbers, not their indices.",
    "tutorial": "We store the binary representation of all the numbers in a trie. To perform operations on a range, we split the trie to extract the range, perform the operation, and merge everything back. AND $x$ is equivalent to the sequence XOR $2^{20}-1$, OR $x\\oplus(2^{20}-1)$, XOR $2^{20}-1$. XOR does not affect the number of numbers in a subtrie, so we can just lazily propagate it. This leaves just OR operations. Suppose we want to set the $k$th bit in a subtrie. If all numbers in it have the $k$th bit set, we do nothing; if no numbers in it have the $k$th bit set, we lazily XOR that bit. Thus, we can handle OR operations recursively, merging the children if the bit to be set is at the current level, and stopping when all bits to be set satisfy one of those two conditions. We can detect these conditions by storing, in every trie node, a mask of bits that are set in some leaf and a mask of bits not set in some leaf. This approach can be shown to be $O((n+q)\\log^2C)$ by amortized analysis. Intuitively, the expensive OR operations will make the bits in a subtrie more similar. Define $\\Phi_k$ to be the number of trie nodes that have some leaf with the $k$th bit set and some leaf with the $k$th bit not set. Define $\\Phi_*$ to be $1+\\log C$ times the total number of trie nodes. Define the total potential to be the $\\sum_{k=0}^{\\log C-1}\\Phi_k+\\Phi_*$. This is always nonnegative and at most $O(n\\log^2 C)$. Split operations create at most $\\log C$ nodes, each adding at most $O(\\log C)$ to the potential, so its amortized time complexity is $O(\\log^2 C)$. Merge operations where one side is empty take $O(1)$. Recursive merge operations combine the two roots, the decrease in $\\Phi_*$ paying for the possible increase in $\\Phi_k$ at the root. (As usual, the recursive calls are not included in the cost as they are paid for by their own potential decrease). An OR operation only recurses when there is some $k$ such that the subtrie has both a leaf with the $k$th bit set and a leaf with the $k$ bit not set. After the operation, all leaves will have the $k$th bit set. Thus, the recursion is paid for by the decrease in $\\Phi_k$ at the root.",
    "code": "#include <cstdio>\n#include <cassert>\n#include <utility>\n#include <functional>\n\n//numbers up to 2^MAXLOGX-1\nconst int MAXLOGX=20;\n\ntemplate<int k>\nstruct Trie{\n  Trie<k-1>* chd[2];\n  int cnt;\n  int lazy;\n  int has[2];\n  int get_cnt(){\n    assert(this!=NULL);\n    return cnt;\n  }\n  int get_has(int d){\n    assert(this!=NULL);\n    push();\n    assert(has[d]<(1<<(k+1)));\n    return has[d];\n  }\n  Trie(Trie<k-1>* l,Trie<k-1>* r):chd{l,r},cnt(0),lazy(0),has{0,0}{\n    if(l){\n      cnt+=l->get_cnt();\n      has[0]|=l->get_has(0)|(1<<k);\n      has[1]|=l->get_has(1);\n    }\n    if(r){\n      cnt+=r->get_cnt();\n      has[0]|=r->get_has(0);\n      has[1]|=r->get_has(1)|(1<<k);\n    }\n    assert(has[0]<(1<<(k+1)));\n    assert(has[1]<(1<<(k+1)));\n  }\n  void push(){\n    assert(lazy<(1<<(k+1)));\n    if(!lazy) return;\n    //handle kth bit\n    if(lazy&(1<<k)){\n      std::swap(chd[0],chd[1]);\n      if((has[0]^has[1])&(1<<k)){\n\thas[0]^=(1<<k);\n\thas[1]^=(1<<k);\n      }\n      lazy^=(1<<k);\n    }\n    //handle rest of bits\n    int flip=(has[0]^has[1])&lazy;\n    has[0]^=flip;\n    has[1]^=flip;\n    if(chd[0]) chd[0]->lazy^=lazy;\n    if(chd[1]) chd[1]->lazy^=lazy;\n    lazy=0;\n    assert(has[0]<(1<<(k+1)));\n    assert(has[1]<(1<<(k+1)));\n  }\n};\n\ntemplate<>\nstruct Trie<-1>{\n  int lazy;\n  Trie():lazy(0){\n  }\n  int get_cnt(){\n    assert(this!=NULL);\n    return 1;\n  }\n  int get_has(int d){\n    assert(this!=NULL);\n    return 0;\n  }\n};\n\ntemplate<int k>\nTrie<k>* create(int x){\n  if(x&(1<<k)){\n    return new Trie<k>(NULL,create<k-1>(x));\n  }else{\n    return new Trie<k>(create<k-1>(x),NULL);\n  }\n}\ntemplate<>\nTrie<-1>* create(int x){\n  return new Trie<-1>();\n}\n\ntemplate<int k>\nstd::pair<Trie<k-1>*,Trie<k-1>*> destruct(Trie<k>* a){\n  assert(a!=NULL);\n  a->push();\n  auto res=std::make_pair(a->chd[0],a->chd[1]);\n  delete a;\n  return res;\n}\n\ntemplate<int k>\nTrie<k>* join(Trie<k-1>* l,Trie<k-1>* r){\n  if(l==NULL&&r==NULL) return NULL;\n  return new Trie<k>(l,r);\n}\n\ntemplate<int k>\nTrie<k>* merge(Trie<k>* a,Trie<k>* b){\n  if(!a) return b;\n  if(!b) return a;\n  auto aa=destruct(a);\n  auto bb=destruct(b);\n  Trie<k-1>* l=merge<k-1>(aa.first,bb.first);\n  Trie<k-1>* r=merge<k-1>(aa.second,bb.second);\n  return join<k>(l,r);\n}\n\ntemplate<>\nTrie<-1>* merge<-1>(Trie<-1>* a,Trie<-1>* b){\n  if(!a) return b;\n  if(!b) return a;\n  delete b;\n  return a;\n}\n\ntemplate<int k>\n//<thres and >=thres\nstd::pair<Trie<k>*,Trie<k>*> split(Trie<k>* a,int thres){\n  if(a==NULL){\n    return {NULL,NULL};\n  }\n  if(thres<=0) return {NULL,a};\n  if(thres>=(1<<(k+1))) return {a,NULL};\n  assert(k>=0);\n  auto aa=destruct(a);\n  if(thres<(1<<k)){\n    Trie<k-1>* l,*r;\n    std::tie(l,r)=split<k-1>(aa.first,thres);\n    return std::make_pair(join<k>(l,NULL),join<k>(r,aa.second));\n  }else if(thres>(1<<k)){\n    Trie<k-1>* l,*r;\n    std::tie(l,r)=split<k-1>(aa.second,thres-(1<<k));\n    return std::make_pair(join<k>(aa.first,l),join<k>(NULL,r));\n  }else{\n    return std::make_pair(join<k>(aa.first,NULL),join<k>(NULL,aa.second));\n  }\n}\n\ntemplate<>\nstd::pair<Trie<-1>*,Trie<-1>*> split<-1>(Trie<-1>* a,int thres){\n  assert(0);\n}\n\ntemplate<int k>\nTrie<k>* update(Trie<k>* a,int val){\n  if(a==NULL) return NULL;\n  a->push();\n  assert(val<(1<<(k+1)));\n  if((val&a->has[0]&a->has[1])==0){\n    a->lazy^=(val&a->has[0]);\n    return a;\n  }\n  Trie<k-1>* l,*r;\n  std::tie(l,r)=destruct(a);\n  l=update<k-1>(l,val&~(1<<k));\n  r=update<k-1>(r,val&~(1<<k));\n  if(val&(1<<k)){\n    return join<k>(NULL,merge<k-1>(l,r));\n  }else{\n    return join<k>(l,r);\n  }\n}\n\ntemplate<>\nTrie<-1>* update<-1>(Trie<-1>* a,int val){\n  return a;\n}\n\nint main(){\n  Trie<MAXLOGX-1>* root=NULL;\n  int N,Q;\n  scanf(\"%d %d\",&N,&Q);\n  for(int i=0;i<N;i++){\n    int A;\n    scanf(\"%d\",&A);\n    root=merge(root,create<MAXLOGX-1>(A));\n  }\n  for(int i=0;i<Q;i++){\n    int T,L,R;\n    scanf(\"%d %d %d\",&T,&L,&R);\n    Trie<MAXLOGX-1>* left,*right;\n    std::tie(left,root)=split(root,L);\n    std::tie(root,right)=split(root,R+1);\n    if(T==4){\n      printf(\"%d\\n\",root?root->cnt:0);\n    }else{\n      int X;\n      scanf(\"%d\",&X);\n      if(root!=NULL){\n\tif(T==1){\n\t  root->lazy^=((1<<MAXLOGX)-1);\n\t  root=update(root,X^((1<<MAXLOGX)-1));\n\t  root->lazy^=((1<<MAXLOGX)-1);\n\t}else if(T==2){\n\t  root=update(root,X);\n\t}else if(T==3){\n\t  assert(X<(1<<MAXLOGX));\n\t  root->lazy^=X;\n\t}\n      }\n    }\n    root=merge(root,left);\n    root=merge(root,right);\n  }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "sortings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1515",
    "index": "I",
    "title": "Phoenix and Diamonds",
    "statement": "Phoenix wonders what it is like to rob diamonds from a jewelry store!\n\nThere are $n$ types of diamonds. The $i$-th type has weight $w_i$ and value $v_i$. The store initially has $a_i$ diamonds of the $i$-th type.\n\nEach day, for $q$ days, one of the following will happen:\n\n- A new shipment of $k_i$ diamonds of type $d_i$ arrive.\n- The store sells $k_i$ diamonds of type $d_i$.\n- Phoenix wonders what will happen if he robs the store using a bag that can fit diamonds with total weight not exceeding $c_i$. If he greedily takes diamonds of the largest value that fit, how much value would be taken? If there are multiple diamonds with the largest value, he will take the one with minimum weight. If, of the diamonds with the largest value, there are multiple with the same minimum weight, he will take any of them.\n\nOf course, since Phoenix is a law-abiding citizen, this is all a thought experiment and he never actually robs any diamonds from the store. This means that queries of type $3$ do not affect the diamonds in the store.",
    "tutorial": "Suppose the largest weight of an item is less than $2^k$. Call an item heavy if its weight is in the range $[2^{k-1},2^k)$ and light if its weight is in the range $(0,2^{k-1})$. Sort the items in decreasing order by value. As the thief moves left to right, his remaining capacity is nonincreasing. Consider the point where it drops below $2^{k-1}$. Before this point, he takes all light items. After this point, he takes no heavy items. The latter can be solved recursively by querying the same data structure only on light items, starting at the appropriate point. The former is a bit trickier. The thief will take every item until his capacity drops below $2^k$. This point can be found by binary searching on a segment tree of sums. After this point, he can only take at most one more heavy item. To find this item (if it exists), we can binary search on a segment tree storing range minimums of prefix sum of light items plus weight of heavy item. The first item that is small enough will be taken, if it exists. Either way, we've located all heavy items that will be taken and can recursively handle the light items. To handle updates, reserve space for all items offline and change their multiplicity as needed. When an item is updated, we can modify all segment trees that it participates in. This solution is $O((n+q)\\log{n}\\log{C})$.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <functional>\n#include <utility>\n#include <numeric>\n#include <cassert>\n\nusing ll=long long;\n\nconst ll INF=1e18+7;\n\nstruct Diamond{\n  int w,v,t;\n  ll a;\n}diamonds[200005];\nint index[200005];\nint N;\n\nstruct Node{\n  ll sum_w[31];//sum of weights of all diamonds with weight <2^k\n  ll sum_v[31];//sum of values of all diamonds with weight <2^k\n  ll one_w[31];//sum of weights of light+first heavy when restricted to <2^k\n  ll one_v[31];//sum of values of light+first heavy when restricted to <2^k\n}st[800005];\n\nvoid rebuild(int w,int L,int R,int a,int b){\n  if(a>=R||b<=L) return;\n  if(R-L==1){\n    for(int k=1;k<=30;k++){\n      st[w].sum_w[k]=diamonds[L].a*diamonds[L].w*(diamonds[L].w<(1<<k));\n      st[w].sum_v[k]=diamonds[L].a*diamonds[L].v*(diamonds[L].w<(1<<k));\n      st[w].one_w[k]=INF;//query capacity never exceed INF\n      st[w].one_v[k]=INF;\n      if(diamonds[L].w>=(1<<(k-1))&&diamonds[L].w<(1<<k)&&diamonds[L].a>0){\n\tst[w].one_w[k]=diamonds[L].w;\n\tst[w].one_v[k]=diamonds[L].v;\n      }\n    }\n  }else{\n    int M=(L+R)/2;\n    rebuild(w*2+1,L,M,a,b);\n    rebuild(w*2+2,M,R,a,b);\n    for(int k=1;k<=30;k++){\n      st[w].sum_w[k]=st[w*2+1].sum_w[k]+st[w*2+2].sum_w[k];\n      st[w].sum_v[k]=st[w*2+1].sum_v[k]+st[w*2+2].sum_v[k];\n      if(st[w*2+1].one_w[k]<st[w*2+1].sum_w[k-1]+st[w*2+2].one_w[k]){\n\tst[w].one_w[k]=st[w*2+1].one_w[k];\n\tst[w].one_v[k]=st[w*2+1].one_v[k];\n      }else{\n\tst[w].one_w[k]=st[w*2+1].sum_w[k-1]+st[w*2+2].one_w[k];\n\tst[w].one_v[k]=st[w*2+1].sum_v[k-1]+st[w*2+2].one_v[k];\n      }\n    }\n  }\n}\n\n//only consider weights <2^k\n//take maximal prefix possible\nvoid query_all(int w,int L,int R,int& i,int k,ll& cap,ll& value){\n  assert(i>=L&&i<=R);\n  assert(R-L>0);\n  if(i==R) return;\n  if(i==L&&st[w].sum_w[k]<=cap){\n    cap-=st[w].sum_w[k];\n    value+=st[w].sum_v[k];\n    i=R;\n  }else if(R-L>1){\n    int M=(L+R)/2;\n    if(i<M){\n      query_all(w*2+1,L,M,i,k,cap,value);\n    }\n    if(i>=M){\n      query_all(w*2+2,M,R,i,k,cap,value);\n    }\n  }\n}\n\nstd::array<ll,2> query_one_range_simpl(int w,int L,int R,int a,int b,int k){\n  if(a>=R||b<=L) return {INF,0};\n  if(a<=L&&b>=R){\n    return {st[w].one_w[k],st[w].sum_w[k-1]};\n  }else{\n    int M=(L+R)/2;\n    std::array<ll,2> lsum,rsum;\n    lsum=query_one_range_simpl(w*2+1,L,M,a,b,k);\n    rsum=query_one_range_simpl(w*2+2,M,R,a,b,k);\n    if(lsum[0]<lsum[1]+rsum[0]){\n      return {lsum[0],lsum[1]+rsum[1]};\n    }else{\n      return {lsum[1]+rsum[0],lsum[1]+rsum[1]};\n    }\n  }\n}\n\nstd::array<ll,4> query_one_range(int w,int L,int R,int a,int b,int k){\n  if(a>=R||b<=L) return {INF,INF,0,0};\n  if(a<=L&&b>=R){\n    return {st[w].one_w[k],st[w].one_v[k],st[w].sum_w[k-1],st[w].sum_v[k-1]};\n  }else{\n    int M=(L+R)/2;\n    std::array<ll,4> lsum,rsum;\n    lsum=query_one_range(w*2+1,L,M,a,b,k);\n    rsum=query_one_range(w*2+2,M,R,a,b,k);\n    if(lsum[0]<lsum[2]+rsum[0]){\n      return {lsum[0],lsum[1],lsum[2]+rsum[2],lsum[3]+rsum[3]};\n    }else{\n      return {lsum[2]+rsum[0],lsum[3]+rsum[1],lsum[2]+rsum[2],lsum[3]+rsum[3]};\n    }\n  }\n}\n\n//returns min j such that one_w[i..j) <= cap, or -1 if none exist\n//reduce cap by weight of light in [max(i,L),R)\nint query_one_range_search_(int w,int L,int R,int& i,int k,ll& cap){\n  assert(i>=L&&i<=R);\n  assert(R-L>0);\n  if(i==R) return -1;\n  if(i==L&&st[w].one_w[k]>cap){\n    cap-=st[w].sum_w[k-1];\n    i=R;\n    return -1;\n  }else if(R-L==1){\n    assert(i==L);\n    assert(st[w].one_w[k]<=cap);\n    cap-=st[w].sum_w[k-1];\n    i=R;\n    return R;\n  }else{\n    int M=(L+R)/2;\n    int res=-1;\n    if(i<M){\n      res=query_one_range_search_(w*2+1,L,M,i,k,cap);\n    }\n    if(res!=-1) return res;\n    if(i>=M){\n      res=query_one_range_search_(w*2+2,M,R,i,k,cap);\n    }\n    return res;\n  }\n}\n\nint query_one_range_search(int i,int k,ll cap){\n  //note this copy of cap will be modified\n  return query_one_range_search_(0,0,N,i,k,cap);\n}\n\nvoid query_one(int& L,int k,ll& cap,ll& value){\n  int high=query_one_range_search(L,k,cap);\n  //v[high]<=cap\n  if(high!=-1){\n    auto v=query_one_range(0,0,N,L,high,k);\n    L=high;\n    cap-=v[0];\n    value+=v[1];\n  }\n}\n\nll query(ll cap){\n  ll value=0;\n  int i=0;\n  for(int k=30;k>0;k--){\n    query_all(0,0,N,i,k,cap,value);\n    if(i==N) break;\n    ll take=std::min(diamonds[i].a,cap/diamonds[i].w);\n    cap-=take*diamonds[i].w;\n    value+=take*diamonds[i].v;\n    i++;\n    query_one(i,k,cap,value);\n  }\n  return value;\n}\n\nint main(){\n  int Q;\n  scanf(\"%d %d\",&N,&Q);\n  for(int i=0;i<N;i++){\n    scanf(\"%lld %d %d\",&diamonds[i].a,&diamonds[i].w,&diamonds[i].v);\n    diamonds[i].t=i;\n  }\n  std::sort(diamonds,diamonds+N,[](Diamond x,Diamond y){\n      return (x.v!=y.v)?(x.v>y.v):(x.w<y.w);\n    });\n  for(int i=0;i<N;i++){\n    index[diamonds[i].t]=i;\n  }\n  rebuild(0,0,N,0,N);\n  for(int i=0;i<Q;i++){\n    int T;\n    scanf(\"%d\",&T);\n    if(T==1){\n      int K,D;\n      scanf(\"%d %d\",&K,&D);\n      D--;\n      diamonds[index[D]].a+=K;\n      rebuild(0,0,N,index[D],index[D]+1);\n    }else if(T==2){\n      int K,D;\n      scanf(\"%d %d\",&K,&D);\n      D--;\n      diamonds[index[D]].a-=K;\n      assert(diamonds[index[D]].a>=0);\n      rebuild(0,0,N,index[D],index[D]+1);\n    }else{\n      ll C;\n      scanf(\"%lld\",&C);\n      printf(\"%lld\\n\",query(C));\n    }\n  }\n}",
    "tags": [
      "binary search",
      "data structures",
      "sortings"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1516",
    "index": "A",
    "title": "Tit for Tat",
    "statement": "Given an array $a$ of length $n$, you can do at most $k$ operations of the following type on it:\n\n- choose $2$ different elements in the array, add $1$ to the first, and subtract $1$ from the second. However, all the elements of $a$ have to remain non-negative after this operation.\n\nWhat is lexicographically the smallest array you can obtain?\n\nAn array $x$ is lexicographically smaller than an array $y$ if there exists an index $i$ such that $x_i<y_i$, and $x_j=y_j$ for all $1 \\le j < i$. Less formally, at the first index $i$ in which they differ, $x_i<y_i$.",
    "tutorial": "The general approach to minimizing an array lexicographically is to try to make the first element as small as possible, then the second element, and so on. So greedily, in each operation, we'll pick the first non-zero element and subtract $1$ from it, and we'll add that $1$ to the very last element. You can make the implementation faster by doing as many operations as you can on the first non-zero element simultaneously, but it's not necessary.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint a[105];\\nint main()\\n{\\n\\tint t;\\n\\tscanf(\\\"%d\\\",&t);\\n\\twhile (t--)\\n\\t{\\n\\t\\tint n,k;\\n\\t\\tscanf(\\\"%d%d\\\",&n,&k);\\n\\t\\tfor (int i=0;i<n;i++)\\n\\t\\tscanf(\\\"%d\\\",&a[i]);\\n\\t\\tfor (int i=0;i<n-1;i++)\\n\\t\\t{\\n\\t\\t\\tif (a[i]<k)\\n\\t\\t\\t{\\n\\t\\t\\t\\tk-=a[i];\\n\\t\\t\\t\\ta[n-1]+=a[i];\\n\\t\\t\\t\\ta[i]=0;\\n\\t\\t\\t}\\n\\t\\t\\telse\\n\\t\\t\\t{\\n\\t\\t\\t\\ta[i]-=k;\\n\\t\\t\\t\\ta[n-1]+=k;\\n\\t\\t\\t\\tk=0;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor (int i=0;i<n;i++)\\n\\t\\tprintf(\\\"%d \\\",a[i]);\\n\\t\\tprintf(\\\"\\\\n\\\");\\n\\t}\\n}\\n\"",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1516",
    "index": "B",
    "title": "AGAGA XOOORRR",
    "statement": "Baby Ehab is known for his love for a certain operation. He has an array $a$ of length $n$, and he decided to keep doing the following operation on it:\n\n- he picks $2$ adjacent elements; he then removes them and places a single integer in their place: their bitwise XOR. Note that the length of the array decreases by one.\n\nNow he asks you if he can make all elements of the array equal. Since babies like to make your life harder, he requires that you leave at least $2$ elements remaining.",
    "tutorial": "So let's try to understand what the final array looks like in terms of the initial array. The best way to see this is to look at the process backwards. Basically, start with the final array, and keep replacing an element with the $2$ elements that xor-ed down to it, until you get the initial array. You'll see that the first element turns into a prefix, the second element turns into a subarray that follows this prefix, and so on. Hence, the whole process of moving from the initial to the final array is like we divide the array into pieces, and then replace each piece with its xor, and we want these xors to be equal. A nice observation is: we need at most $3$ pieces. That's because if we have $4$ or more pieces, we can take $3$ pieces and merge them into one. Its xor will be the same, but the total piece count will decrease by $2$. Now, checking if you can divide it into $2$ or $3$ pieces is a simple task that can be done by bruteforce. You can iterate over the positions you'll split the array, and then check the xors are equal using a prefix-xor array or any other method you prefer. Additional idea: for $2$ pieces, you don't even need bruteforce. It's sufficient to check the xor of the whole array is $0$. Hint to see this: write the bruteforce.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint pre[2005];\\nint main()\\n{\\n\\tint t;\\n\\tscanf(\\\"%d\\\",&t);\\n\\twhile (t--)\\n\\t{\\n\\t\\tint n;\\n\\t\\tscanf(\\\"%d\\\",&n);\\n\\t\\tfor (int i=1;i<=n;i++)\\n\\t\\t{\\n\\t\\t\\tint a;\\n\\t\\t\\tscanf(\\\"%d\\\",&a);\\n\\t\\t\\tpre[i]=(pre[i-1]^a);\\n\\t\\t}\\n\\t\\tbool yes=!pre[n];\\n\\t\\tfor (int i=1;i<=n;i++)\\n\\t\\t{\\n\\t\\t\\tfor (int j=i+1;j<n;j++)\\n\\t\\t\\tyes|=(pre[i]==(pre[j]^pre[i]) && pre[i]==(pre[n]^pre[j]));\\n\\t\\t}\\n\\t\\tputs(yes? \\\"YES\\\":\\\"NO\\\");\\n\\t}\\n}\\n\"",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1516",
    "index": "C",
    "title": "Baby Ehab Partitions Again",
    "statement": "Baby Ehab was toying around with arrays. He has an array $a$ of length $n$. He defines an array to be good if there's no way to partition it into $2$ subsequences such that the sum of the elements in the first is equal to the sum of the elements in the second. Now he wants to remove the minimum number of elements in $a$ so that it becomes a good array. Can you help him?\n\nA sequence $b$ is a subsequence of an array $a$ if $b$ can be obtained from $a$ by deleting some (possibly zero or all) elements. A partitioning of an array is a way to divide it into $2$ subsequences such that every element belongs to exactly one subsequence, so you must use all the elements, and you can't share any elements.",
    "tutorial": "First of all, let's check if the array is already good. This can be done with knapsack dp. If it is, the answer is $0$. If it isn't, I claim you can always remove one element to make it good, and here's how to find it: Since the array can be partitioned, its sum is even. So if we remove an odd element, it will be odd, and there will be no way to partition it. If there's no odd element, then all elements are even. But then, you can divide all the elements by $2$ without changing the answer. Why? Because a partitioning in the new array after dividing everything by $2$ is a partitioning in the original array and vice versa. We just re-scaled everything. So, while all the elements are even, you can keep dividing by $2$, until one of the elements becomes odd. Remove it and you're done. If you want the solution in one sentence, remove the element with the smallest possible least significant bit. Alternatively, for a very similar reasoning, you can start by dividing the whole array by its $gcd$ and remove any odd element (which must exist because the $gcd$ is $1$,) but I think this doesn't give as much insight ;)",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint n;\\nbool bad(vector<int> v)\\n{\\n\\tint s=0;\\n\\tfor (int i:v)\\n\\ts+=i;\\n\\tif (s%2)\\n\\treturn 0;\\n\\tbitset<200005> b;\\n\\tb[0]=1;\\n\\tfor (int i:v)\\n\\tb|=(b<<i);\\n\\treturn b[s/2];\\n}\\nint main()\\n{\\n\\tscanf(\\\"%d\\\",&n);\\n\\tvector<int> v(n);\\n\\tfor (int i=0;i<n;i++)\\n\\tscanf(\\\"%d\\\",&v[i]);\\n\\tif (bad(v))\\n\\t{\\n\\t\\tpair<int,int> mn(20,0);\\n\\t\\tfor (int i=0;i<n;i++)\\n\\t\\tmn=min(mn,make_pair(__builtin_ctz(v[i]),i+1));\\n\\t\\tprintf(\\\"1\\\\n%d\\\",mn.second);\\n\\t}\\n\\telse\\n\\tprintf(\\\"0\\\");\\n}\"",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1516",
    "index": "D",
    "title": "Cut",
    "statement": "This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array $a$ of length $n$ written on it, and then he does the following:\n\n- he picks a range $(l, r)$ and cuts the subsegment $a_l, a_{l + 1}, \\ldots, a_r$ out, removing the rest of the array.\n- he then cuts this range into multiple subranges.\n- to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their least common multiple (LCM).\n\nFormally, he partitions the elements of $a_l, a_{l + 1}, \\ldots, a_r$ into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for $q$ independent ranges $(l, r)$, tell Baby Ehab the minimum number of subarrays he needs.",
    "tutorial": "Let's understand what \"product=LCM\" means. Let's look at any prime $p$. Then, the product operation adds up its exponent in all the numbers, while the LCM operation takes the maximum exponent. Hence, the only way they're equal is if every prime divides at most one number in the range. Another way to think about it is that every pair of numbers is coprime. Now, we have the following greedy algorithm: suppose we start at index $l$; we'll keep extending our first subrange while the condition (every pair of numbers is coprime) is satisfied. We clearly don't gain anything by stopping when we can extend, since every new element just comes with new restrictions. Once we're unable to extend our subrange, we'll start a new subrange, until we reach index $r$. Now, for every index $l$, let's define $go_l$ to be the first index that will make the condition break when we add it to the subrange. Then, our algorithm is equivalent to starting with an index $cur=l$, then replacing $cur$ with $go_{cur}$ until we exceed index $r$. The number of steps it takes is our answer. We now have $2$ subproblems to solve: To calculate $go_l$, let's iterate over $a$ from the end to the beginning. While at index $l$, let's iterate over the prime divisors of $a_l$. Then, for each prime, let's get the next element this prime divides. We can store that in an array that we update as we go. If we take the minimum across these occurrences, we'll get the next number that isn't coprime to $l$. Let's set $go_l$ to that number. However, what if $2$ other elements, that don't include $l$, are the ones who aren't coprime? A clever way to get around this is to minimize $go_l$ with $go_{l+1}$, since $go_{l+1}$ covers all the elements coming after $l$. This is a pretty standard problem solvable with the binary lifting technique. The idea is to perform many jumps at a time, instead of $1$. Let's calculate $dp[i][l]$: the index we'll end up at if we keep replacing $l$ with $go_l$ $2^i$ times. Clearly, $dp[i][l]=dp[i-1][dp[i-1][l]]$ since $2^{i-1}+2^{i-1}=2^i$. Now, to calculate how many steps it takes from index $l$ to index $r$, let's iterate over the numbers from $log(n)$ to $0$. Let the current be $i$. If $dp[i][l]$ is less than or equal to $r$, we can jump $2^i$ steps at once, so we'll make $l$ equal to $dp[i][l]$ and add $2^i$ to the answer. At the end, we'll make one more jump.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define MX 100000\\nvector<int> p[100005];\\nint a[100005],nex[100005],dp[20][100005];\\nint main()\\n{\\n    int n,q;\\n\\tscanf(\\\"%d%d\\\",&n,&q);\\n\\tfor (int i=1;i<=n;i++)\\n\\tscanf(\\\"%d\\\",&a[i]);\\n\\tfor (int i=2;i<=MX;i++)\\n\\t{\\n\\t\\tif (p[i].empty())\\n\\t\\t{\\n\\t\\t    nex[i]=n+1;\\n\\t\\t\\tfor (int j=i;j<=MX;j+=i)\\n\\t\\t\\tp[j].push_back(i);\\n\\t\\t}\\n\\t}\\n\\tdp[0][n+1]=n+1;\\n\\tfor (int i=n;i>0;i--)\\n\\t{\\n\\t\\tdp[0][i]=dp[0][i+1];\\n\\t\\tfor (int j:p[a[i]])\\n\\t\\t{\\n\\t\\t\\tdp[0][i]=min(dp[0][i],nex[j]);\\n\\t\\t\\tnex[j]=i;\\n\\t\\t}\\n\\t}\\n\\tfor (int i=1;i<20;i++)\\n\\t{\\n\\t\\tfor (int j=1;j<=n+1;j++)\\n\\t\\tdp[i][j]=dp[i-1][dp[i-1][j]];\\n\\t}\\n\\twhile (q--)\\n\\t{\\n\\t\\tint l,r,ans=0;\\n\\t\\tscanf(\\\"%d%d\\\",&l,&r);\\n\\t\\tfor (int i=19;i>=0;i--)\\n\\t\\t{\\n\\t\\t\\tif (dp[i][l]<=r)\\n\\t\\t\\t{\\n\\t\\t\\t\\tans+=(1<<i);\\n\\t\\t\\t\\tl=dp[i][l];\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tprintf(\\\"%d\\\\n\\\",ans+1);\\n\\t}\\n}\\n\"",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "graphs",
      "number theory",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1516",
    "index": "E",
    "title": "Baby Ehab Plays with Permutations",
    "statement": "This time around, Baby Ehab will play with permutations. He has $n$ cubes arranged in a row, with numbers from $1$ to $n$ written on them. He'll make \\textbf{exactly} $j$ operations. In each operation, he'll pick up $2$ cubes and switch their positions.\n\nHe's wondering: how many different sequences of cubes can I have at the end? Since Baby Ehab is a turbulent person, he doesn't know how many operations he'll make, so he wants the answer for every possible $j$ between $1$ and $k$.",
    "tutorial": "Let's think about the problem backwards. Let's try to count the number of permutations which need exactly $j$ swaps to be sorted. To do this, I first need to refresh your mind (or maybe introduce you) to a greedy algorithm that does the minimum number of swaps to sort a permutation. Look at the last mismatch in the permutation, let it be at index $i$ and $p_i=v$. We'll look at where $v$ is at in the permutation, and swap index $i$ with that index so that $v$ is in the correct position. Basically, we look at the last mismatch and correct it immediately. We can build a slow $dp$ on this greedy algorithm: let $dp[n][j]$ denote the number of permutations of length $n$ which need $j$ swaps to be sorted. If element $n$ is in position $n$, we can just ignore it and focus on the first $n-1$ elements, so that moves us to $dp[n-1][j]$. If it isn't, then we'll swap the element at position $n$ with wherever $n$ is at so that $n$ becomes in the right position, by the greedy algorithm. There are $n-1$ positions index $n$ can be at, and after the swap, you can have an arbitrary permutation of length $n-1$ that needs to be sorted; that gives us $n-1$ ways to go to $dp[n-1][j-1]$. Combining, we get that $dp[n][j]=dp[n-1][j]+(n-1)*dp[n-1][j-1]$. Next, notice that you don't have to do the minimum number of swaps in the original problem. You can swap $2$ indices and swap them back. Also, it's well-known that you can either get to a permutation with an even number of swaps or an odd number, but never both (see this problem.) So now, after you calculate your $dp$, the number of permutations you can get to after $j$ swaps is $dp[n][j]+dp[n][j-2]+dp[n][j-4]+...$. Now, let's solve for $n \\le 10^9$. Notice that after $k$ swaps, only $2k$ indices can move from their place, which is pretty small. That gives you a pretty intuitive idea: let's fix a length $i$ and then a subset of length $i$ that will move around. The number of ways to pick this subset is $\\binom{n}{i}$, and the number of ways to permute it so that we need $j$ swaps is $dp[i][j]$. So we should just multiply them together and sum up, right? Wrong. The problem is that double counting will happen. For example, look at the sorted permutation. This way, you count it for every single subset when $j=0$, but you should only count it once. A really nice solution is: force every element in your subset to move from its position. How does this solve the double counting? Suppose $2$ different subsets give you the same permutation; then, there must be an index in one and not in the other. But how can they give you the same permutation if that index moves in one and doesn't move in the other? So to mend our solution, we need to create $newdp[n][j]$ denoting the number of permutations of length $n$ which need $j$ swaps to be sorted, and every single element moves from its position (there's no $p_i=i$.) How do we calculate it? One way is to do inclusion-exclusion on the $dp$ we already have! Suppose I start with all permutations which need $j$ swaps. Then, I fix one index, and I try to subtract the number of permutations which need $j$ swaps to be sorted after that index is fixed. There are $n$ ways to choose the index, and $dp[n-1][j]$ permutations, so we subtract $n*dp[n-1][j]$. But now permutations with $2$ fixed points are excluded twice, so we'll include them, and so on and so forth. In general, we'll fix $f$ indices in the permutation. There are $\\binom{n}{f}$ ways to pick them, and then there are $dp[n-f][j]$ ways to pick the rest so that we need $j$ swaps. Hence: $newdp[n][j]=\\sum\\limits_{f=0}^{n} (-1)^f*\\binom{n}{f}*dp[n-f][j]$. Phew! If you have no idea what the hell I was talking about in the inclusion-exclusion part, try this problem first. Let $[l;r]$ denote the set of the integers between $l$ and $r$ (inclusive.) Let's try to calculate $dp[2n]$ from $dp[n]$. To do that, we need to understand our $dp$ a bit further. Recall that $dp[n][j]=dp[n-1][j]+(n-1)*dp[n-1][j-1]$. Let's think about what happens as you go down the recurrence. When you're at index $n$, either you skip it and move to $n-1$, or you multiply by $n-1$. But you do that exactly $j$ times, since $j$ decreases every time you do it. So, this $dp$ basically iterates over every subset of $[0;n-1]$ of size $j$, takes its product, and sums up! $dp[n][j]=\\sum\\limits_{s \\subset [0;n-1],|s|=j} s_1*s_2 \\ldots *s_j$ Now, let's use this new understanding to try and calculate $dp[2n]$ from $dp[n]$. suppose I pick a subset of $[0;2n-1]$. Then, a part of it will be in $[0;n-1]$ and a part will be in $[n;2n-1]$. I'll call the first part small and the second part big. So, to account for every subset of length $j$, take every subset of length $j_2$ of the big elements, multiply it by a subset of length $j-j_2$ of the small elements, and sum up. This is just normal polynomial multiplication! Let $big[n][j]$ denote the sum of the products of the subsets of length $j$ of the big elements. That is: $big[n][j]=\\sum\\limits_{s \\subset [n;2n-1],|s|=j} s_1*s_2 \\ldots *s_j$ Then, the polynomial multiplication between $dp[n]$ and $big[n]$ gives $dp[2n]$! How do we calculate $big$ though? Notice that every big element is a small element plus $n$. So we can instead pick a subset of the small elements and add $n$ to each element in it. This transforms the formula to: $big[n][j]=\\sum\\limits_{s \\subset [0;n-1],|s|=j} (s_1+n)*(s_2+n) \\ldots *(s_j+n)$ Let's expand this summand. What will every term in the expansion look like? Well, it will be a subset of length $l$ from our subset of length $j$, multiplied by $n^{j-l}$. Now, let's think about this backwards. Instead of picking a subset of length $j$ and then picking a subset of length $l$ from it, let's pick the subset of length $l$ first, and then see the number of ways to expand it into a subset of length $j$. Well, there are $n-l$ elements left, and you should pick $j-l$ elements from them, so there are $\\binom{n-l}{j-l}$ ways to expand. That gives use: $big[n][j]=\\sum\\limits_{l=0}^{j} \\binom{n-l}{j-l}*n^{j-l}* \\sum\\limits_{s \\subset [0;n-1],|s|=l} s_1*s_2 \\ldots *s_l$ But the interior sum is just $dp[l]$! Hurray! So we can finally calculate $big[n][j]$ to be: $big[n][j]=\\sum\\limits_{l=0}^{j} \\binom{n-l}{j-l}*n^{j-l}*dp[l]$ And then polynomial multiplication with $dp[n]$ itself would give $dp[2n]$. Since you can move to $dp[n+1]$ and to $dp[2n]$, you can reach any $n$ you want in $O(log(n))$ iterations using its binary representation.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define MX 200\\n#define mod 1000000007\\nlong long inv[MX+5];\\nlong long ncr(int n,int r)\\n{\\n\\tlong long ret=1;\\n\\tfor (int i=n-r+1;i<=n;i++)\\n\\tret=(ret*i)%mod;\\n\\tfor (int i=1;i<=r;i++)\\n\\tret=(ret*inv[i])%mod;\\n\\treturn ret;\\n}\\nint main()\\n{\\n\\tinv[1]=1;\\n\\tfor (int i=2;i<=MX;i++)\\n\\tinv[i]=inv[mod%i]*(mod-mod/i)%mod;\\n\\tint n,k;\\n\\tscanf(\\\"%d%d\\\",&n,&k);\\n\\tvector<long long> dp(k+1,0);\\n\\tdp[0]=1;\\n\\tint curn=1;\\n\\tfor (int i=30-__builtin_clz(n);i>=0;i--)\\n\\t{\\n\\t\\tvector<long long> big(k+1,0),pw(k+1),tmp(k+1,0);\\n\\t\\tpw[0]=1;\\n\\t\\tfor (int j=1;j<=k;j++)\\n\\t\\tpw[j]=(curn*pw[j-1])%mod;\\n\\t\\tfor (int j=0;j<=min(k,curn);j++)\\n\\t\\t{\\n\\t\\t\\tfor (int l=0;l<=j;l++)\\n\\t\\t\\tbig[j]=(big[j]+ncr(curn-l,j-l)*dp[l]%mod*pw[j-l])%mod;\\n\\t\\t}\\n\\t\\tfor (int js=0;js<=k;js++)\\n\\t\\t{\\n\\t\\t\\tfor (int jb=0;jb<=k;jb++)\\n\\t\\t\\t{\\n\\t\\t\\t\\tif (js+jb<=k)\\n\\t\\t\\t\\ttmp[js+jb]=(tmp[js+jb]+dp[js]*big[jb])%mod;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tdp=tmp;\\n\\t\\tcurn*=2;\\n\\t\\tif (n&(1<<i))\\n\\t\\t{\\n\\t\\t\\tvector<long long> tmp(k+1);\\n\\t\\t\\ttmp[0]=1;\\n\\t\\t\\tfor (int j=1;j<=k;j++)\\n\\t\\t\\ttmp[j]=(dp[j]+curn*dp[j-1])%mod;\\n\\t\\t\\tdp=tmp;\\n\\t\\t\\tcurn++;\\n\\t\\t}\\n\\t}\\n\\tint ans[]={1,0};\\n\\tfor (int j=1;j<=k;j++)\\n\\t{\\n\\t\\tans[j%2]=(ans[j%2]+dp[j])%mod;\\n\\t\\tprintf(\\\"%d \\\",ans[j%2]);\\n\\t}\\n\\tprintf(\\\"\\\\n\\\");\\n}\\n\"",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1517",
    "index": "A",
    "title": "Sum of 2050",
    "statement": "A number is called 2050-number if it is $2050$, $20500$, ..., ($2050 \\cdot 10^k$ for integer $k \\ge 0$).\n\nGiven a number $n$, you are asked to represent $n$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.",
    "tutorial": "First, we need to check whether $n$ is the multiple of $2050$. If $n$ is not the multiple of $2050$, the answer is always $-1$. Then we can divide $n$ by $2050$, the problem now is how to represent $n$ as the sum of powers of $10$. So the answer is the sum of its digits in decimal representation.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1517",
    "index": "B",
    "title": "Morning Jogging",
    "statement": "The 2050 volunteers are organizing the \"Run! Chase the Rising Sun\" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.\n\nThere are $n+1$ checkpoints on the trail. They are numbered by $0$, $1$, ..., $n$. A runner must start at checkpoint $0$ and finish at checkpoint $n$. No checkpoint is skippable — he must run from checkpoint $0$ to checkpoint $1$, then from checkpoint $1$ to checkpoint $2$ and so on. Look at the picture in notes section for clarification.\n\nBetween any two adjacent checkpoints, there are $m$ different paths to choose. For any $1\\le i\\le n$, to run from checkpoint $i-1$ to checkpoint $i$, a runner can choose exactly one from the $m$ possible paths. The length of the $j$-th path between checkpoint $i-1$ and $i$ is $b_{i,j}$ for any $1\\le j\\le m$ and $1\\le i\\le n$.\n\nTo test the trail, we have $m$ runners. Each runner must run from the checkpoint $0$ to the checkpoint $n$ once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by \\textbf{exactly one} runner. If a runner chooses the path of length $l_i$ between checkpoint $i-1$ and $i$ ($1\\le i\\le n$), his tiredness is $$\\min_{i=1}^n l_i,$$ i. e. the minimum length of the paths he takes.\n\nPlease arrange the paths of the $m$ runners to minimize the sum of tiredness of them.",
    "tutorial": "The minimum sum is the sum of $m$ smallest of all $nm$ numbers. To construct the answer, we can just mark these $m$ smallest numbers and put them in $m$ different columns. A possible way is that for each row, you can sort all numbers from small to large, and rotate the marked number in this row to unmarked columns. For example, 1???? ?23?? ???45",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1517",
    "index": "C",
    "title": "Fillomino 2",
    "statement": "Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:\n\nConsider an $n$ by $n$ chessboard. Its rows are numbered from $1$ to $n$ from the top to the bottom. Its columns are numbered from $1$ to $n$ from the left to the right. A cell on an intersection of $x$-th row and $y$-th column is denoted $(x, y)$. The main diagonal of the chessboard is cells $(x, x)$ for all $1 \\le x \\le n$.\n\nA permutation of $\\{1, 2, 3, \\dots, n\\}$ is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly $1+2+ \\ldots +n$ such cells) into $n$ connected regions satisfying the following constraints:\n\n- Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.\n- The $x$-th region should contain cell on the main diagonal with number $x$ for all $1\\le x\\le n$.\n- The number of cells that belong to the $x$-th region should be equal to $x$ for all $1\\le x\\le n$.\n- Each cell under and on the main diagonal should belong to exactly one region.",
    "tutorial": "The answer is unique and always exists. There are two ways to construct the answer. Construction 1: Start with the main diagonal. There is one cell $(x, x)$ with number $1$ on it. That cell must form a region by itself. For each cell $(y, y)$ on the main diagonal that is above $(x, x)$, the cell $(y+1, y)$ belongs to the same region as $(y, y)$. We write the number on $(y, y)$ minus $1$ on the cell $(y+1, y)$ and make $(y+1, y)$ belong to the same region as $(y, y)$. For each cell $(y, y)$ on the main diagonal that is below $(x, x)$, the cell $(y, y-1)$ belongs to the same region as $(y, y)$. We write the number on $(y, y)$ minus $1$ on the cell $(y, y-1)$ and make $(y, y - 1)$ belong to the same region as $(y, y)$. Then a permutation of $1, \\ldots, n-1$ are written on the cells $(2, 1), (3, 2), \\ldots, (n, n-1)$. We can continue this process on this subdiagonal. Then a oermutation of $1, 2, \\ldots, n-2$ will be written on the cells $(3, 1), (4, 2), \\ldots, (n, n-2)$. Repeat until all cells have numbers written on them. Note that the numbers written on the cells are not the output. Put $x$ for the region with size $x$ after constructing the regions. This construction proves that the solution always exists and is unique. Construction 2: Construct the region for $(1, 1), (2, 2), \\ldots, (n, n)$ in order. When starting at $(i, i)$, we walk from $(i, i)$ for $x$ steps, where $x$ is the number written on $(i, i)$. For each step, if the cell to the left of your current cell is empty, we go to that cell and write $x$ on it. Otherwise we go down and write $x$ there. We can prove that the second construction produces exactly the same answer as the first construction. They only differ in their orders of processing. The regions are always paths.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1517",
    "index": "D",
    "title": "Explorer Space",
    "statement": "You are wandering in the explorer space of the 2050 Conference.\n\nThe explorer space can be viewed as an undirected weighted grid graph with size $n\\times m$. The set of vertices is $\\{(i, j)|1\\le i\\le n, 1\\le j\\le m\\}$. Two vertices $(i_1,j_1)$ and $(i_2, j_2)$ are connected by an edge if and only if $|i_1-i_2|+|j_1-j_2|=1$.\n\nAt each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing $x$ exhibits, your boredness increases by $x$.\n\nFor each starting vertex $(i, j)$, please answer the following question: What is the minimum possible boredness if you walk from $(i, j)$ and go back to it after exactly $k$ steps?\n\nYou can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex $(i, j)$ after $k$ steps, you can visit $(i, j)$ (or not) freely.",
    "tutorial": "Since the graph is bipartite, when $k$ is odd, it is impossible to go back to the vertex after $k$ steps. Since the graph is undirected, we can always find a path with length $k/2$, walk along this path and return. We can use dynamic programming to compute the shortest path from $u$ with length $k$. $dp_{u,k} = \\min_{(u, v) \\in E} \\{dp_{v,k-1} + w_{u,v}\\}$. The time complexity is $O(nmk)$.",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1517",
    "index": "E",
    "title": "Group Photo",
    "statement": "In the 2050 Conference, some people from the competitive programming community meet together and are going to take a photo. The $n$ people form a line. They are numbered from $1$ to $n$ from left to right. Each of them either holds a cardboard with the letter 'C' or a cardboard with the letter 'P'.\n\nLet $C=\\{c_1,c_2,\\dots,c_m\\}$ $(c_1<c_2<\\ldots <c_m)$ be the set of people who hold cardboards of 'C'. Let $P=\\{p_1,p_2,\\dots,p_k\\}$ $(p_1<p_2<\\ldots <p_k)$ be the set of people who hold cardboards of 'P'. The photo is good if and only if it satisfies the following constraints:\n\n- $C\\cup P=\\{1,2,\\dots,n\\}$\n- $C\\cap P =\\emptyset $.\n- $c_i-c_{i-1}\\leq c_{i+1}-c_i(1< i <m)$.\n- $p_i-p_{i-1}\\geq p_{i+1}-p_i(1< i <k)$.\n\nGiven an array $a_1,\\ldots, a_n$, please find the number of good photos satisfying the following condition: $$\\sum\\limits_{x\\in C} a_x < \\sum\\limits_{y\\in P} a_y.$$\n\nThe answer can be large, so output it modulo $998\\,244\\,353$. Two photos are different if and only if there exists at least one person who holds a cardboard of 'C' in one photo but holds a cardboard of 'P' in the other.",
    "tutorial": "There can't be two $i$'s such that $c_i-c_{i-1}>2$, or $p_i-p_{i-1}$ won't be non-increasing. And there can't be two $i$'s such that $p_i-p_{i-1}>2$, or $c_i-c_{i-1}$ won't be non-decreasing. So for any $2\\leq i<m$, $c_i-c_{i-1}\\leq 2$, and for any $2\\leq i<k$, $p_i-p_{i-1}\\leq 2$. Then we can find out that there are only two possible patterns: PP...PCC...C or (C/P)CC...CPCPC...PCPP...P(C/P). You can calculate the first pattern in $O(n)$ and calculate the second pattern in $O(n)$ or $O(nlogn)$ with two-pointers or divide-and-conquer.",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1517",
    "index": "F",
    "title": "Reunion",
    "statement": "It is reported that the 2050 Conference will be held in Yunqi Town in Hangzhou from April 23 to 25, including theme forums, morning jogging, camping and so on.\n\nThe relationship between the $n$ volunteers of the 2050 Conference can be represented by a tree (a connected undirected graph with $n$ vertices and $n-1$ edges). The $n$ vertices of the tree corresponds to the $n$ volunteers and are numbered by $1,2,\\ldots, n$.\n\nWe define the distance between two volunteers $i$ and $j$, \\textrm{dis}$(i,j)$ as the number of edges on the shortest path from vertex $i$ to vertex $j$ on the tree. \\textrm{dis}$(i,j)=0$ whenever $i=j$.\n\nSome of the volunteers can attend the on-site reunion while others cannot. If for some volunteer $x$ and nonnegative integer $r$, all volunteers whose distance to $x$ is no more than $r$ can attend the on-site reunion, a forum with radius $r$ can take place. The level of the on-site reunion is defined as the maximum possible radius of any forum that can take place.\n\nAssume that each volunteer can attend the on-site reunion with probability $\\frac{1}{2}$ and these events are independent. Output the expected level of the on-site reunion. When no volunteer can attend, the level is defined as $-1$. When all volunteers can attend, the level is defined as $n$.",
    "tutorial": "Let $B(u,r) = \\{v | \\mathrm{dis}(u,v) \\leq r \\}$. And a vertex is colored black iff the volunteer is not attend. First, we enumerate $r$ and count the number of ways that the answer is no larger than $r$. That is equivalent to for all black vertices $u$, the union of $B(u,r)$ will cover all vertices. So a typical tree dp is to consider for a subtree, the depth of the deepest uncovered vertex, and how long it can extend (the most shallow black vertex whose neighbor can extend out from this subtree). Here is an observation that if there is an uncovered vertex in the subtree, how long it can extend doesn't matter. The reason is this vertex needs to be covered by the vertex ($v$) from other subtrees, and $v$ can extend further than one in this subtree. So if there is an uncovered vertex in the subtree, we only care about the depth of the deepest uncovered one. Otherwise, we care about the depth of the most shallow black vertex. The state of this subtree is $O(size_a)$ (actually is $O(dep_a)$). Time complexity for each $r$ is $O(n^2)$, and overall complexity is $O(n^3)$. It is possible to optimize it to $O(n^2 \\log n)$ further.",
    "tags": [
      "combinatorics",
      "dp",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1517",
    "index": "G",
    "title": "Starry Night Camping",
    "statement": "At the foot of Liyushan Mountain, $n$ tents will be carefully arranged to provide accommodation for those who are willing to experience the joy of approaching nature, the tranquility of the night, and the bright starry sky.\n\nThe $i$-th tent is located at the point of $(x_i, y_i)$ and has a weight of $w_i$. A tent is important if and only if both $x_i$ and $y_i$ are even. You need to remove some tents such that for each remaining important tent $(x, y)$, there do not exist $3$ other tents $(x'_1, y'_1)$, $(x'_2, y'_2)$ and $(x'_3, y'_3)$ such that both conditions are true:\n\n- $|x'_j-x|, |y'_j - y|\\leq 1$ for all $j \\in \\{1, 2, 3\\}$, and\n- these four tents form a parallelogram (or a rectangle) and one of its sides is \\textbf{parallel to the $x$-axis}.\n\nPlease maximize the sum of the weights of the tents that are \\textbf{not} removed. Print the maximum value.",
    "tutorial": "We can label all the integer points in the plane as follow: ...2323... ...1010... ...2323... ...1010... Where all the good points are labeled with 1. If we draw an edge between every adjacent points, all the forbidden patterns form all paths of length 4 with label 0-1-2-3. So we transform the problem to another problem: delete some points with smallest sum of value such that the remaining points doesn't contain a 0-1-2-3 path. It can be solved with a simple min-cut algorithm.",
    "tags": [
      "constructive algorithms",
      "flows",
      "graphs"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1517",
    "index": "H",
    "title": "Fly Around the World",
    "statement": "After hearing the story of Dr. Zhang, Wowo decides to plan his own flight around the world.\n\nHe already chose $n$ checkpoints in the world map. Due to the landform and the clouds, he cannot fly too high or too low. Formally, let $b_i$ be the height of Wowo's aircraft at checkpoint $i$, $x_i^-\\le b_i\\le x_i^+$ should be satisfied for all integers $i$ between $1$ and $n$, where $x_i^-$ and $x_i^+$ are given integers.\n\nThe angle of Wowo's aircraft is also limited. For example, it cannot make a $90$-degree climb. Formally, $y_i^-\\le b_i-b_{i-1}\\le y_i^+$ should be satisfied for all integers $i$ between $2$ and $n$, where $y_i^-$ and $y_i^+$ are given integers.\n\nThe final limitation is the speed of angling up or angling down. An aircraft should change its angle slowly for safety concerns. Formally, $z_i^- \\le (b_i - b_{i-1}) - (b_{i-1} - b_{i-2}) \\le z_i^+$ should be satisfied for all integers $i$ between $3$ and $n$, where $z_i^-$ and $z_i^+$ are given integers.\n\nTaking all these into consideration, Wowo finds that the heights at checkpoints are too hard for him to choose. Please help Wowo decide whether there exists a sequence of \\textbf{real} numbers $b_1, \\ldots, b_n$ satisfying all the contraints above.",
    "tutorial": "Consider the DP idea: dp[i][x][y] represests whether there exists a sequence $b_1, \\ldots, b_i$ satisfying all the constraints. (Constraints about $b_{i+1}, b_{i+2}, \\ldots$ are ignored.) Then $R(i)=\\{(x, y) | dp[i][x][y] = true\\}$ is a region on the plane. We will prove that it is convex and then show that we can efficiently transform $R(i)$ to $R(i+1)$. Initially, we can construct $R(2)$. In $R(2)$, $x$ represents $b_2$ and $y$ represents $b_2-b_1$. The constraints are $x_1^-\\le b_1=x-y \\le x_1^+$, $x_2^-\\le b_2=x\\le x_2^+$, $y_2^-\\le y=b_2-b_1\\le y_2^+$. $R(2)$ is the intersection of these half planes (so it is convex.) Calculate $R(i+1)$ by $R(i)$: We should take the new constraints $x_{i+1}^- \\le b_{i+1} \\le x_{i+1}^+$, $y_{i+1}^- \\le b_{i+1}-b_i \\le y_{i+1}^+$, $z_{i+1}^- \\le b_{i+1}-b_i-(b_i-b_{i-1}) \\le z_{i+1}^+$ into account. Let's consider the last constraint first and ignore the first two for now. If $(b_{i+1}-b_i)-(b_i-b_{i-1})=z$, point $(x, y)$ in $R(i)$ (represents $b_i=x, b_{i-1}=x-y$ since $y=b_i-b_{i-1}$) will become $(b_{i+1}, b_{i+1}-b_i)=(b_{i}+(b_i-b_{i-1}) + ((b_{i+1}-b_i)-(b_i-b_{i-1})), (b_i-b_{i-1}) + ((b_{i+1}-b_i)-(b_i-b_{i-1})))=(x+y+z, y+z)$ in $R(i+1)$ (since $(b_{i+1}-b_i)-(b_i-b_{i-1})=z$). Thus, to transform $R(i)$ to $R(i+1)$, we simply apply the $x\\leftarrow x+y$ tranformation and then move the region by the vector $(z, z)$. $x\\leftarrow x+y$ is a linear transformation. We call the new region $R(i)(z)$. Now we know that $z$ is between $z_{i+1}^-$ and $z_{i+1}^+$. So we should take the union of all $R(i)(z)$ for $z\\in[z_{i+1}^-,z_{i+1}^+]$. Finally, we add the first two constraints about $x$ and $y$ back. These constraints correspond to cutting the region by vertical or horizontal half planes. The answer is yes if and only if $R(n)$ is nonempty. By the process above, we can prove (inductively) that the region $R(i)$ is always convex. For each $i$, we only add vertical and horizontal half planes. These half planes will cut some original edges of the convex polygon and add some new vertical or horizontal edges to it. The transformation $x\\leftarrow x+y$ will change an edge with slope $1/k$ into an edge with slope $1/(k+1)$ (vertical edges becomes edges with slope $1/1$). So we can also prove inductively that for any $i$, all the edges of $R(i)$ have slope $0, \\infty$ or $1/k$ for some integer $k\\le n$. These edges can be written as $Ax+By+C=0$ for integral $A, B$ and $C$. We now know that for any $i$, the region $R(i)$ is always convex and all edges have slope $0, \\infty$ or $1/k$ for some integer $k\\le n$. Next we describe how to implement the process described above efficiently. We maintain two deques for the vertices on the upper and lower hull of the polygon. Vertical edges are included in the upper hull if they have minimum $x$ coordinate (and lower hull if they have maximum $x$ coordinate.) To cut the polygon by vertical or horizontal half planes, we simply pop some vertices at the end of the deques. (And possibly add some new vertices at the front or back of the deques.) To apply the transformation $x\\leftarrow x+y$, we apply it to all vertices of the convex polygon. Since we apply the same operation to all vertices, this can be done by tags in constant time (like the tags in segment trees). We will explain the precision issues later. Finally, to take the union of all $R(i)(z)$, we move the upper hull by $(z_{i+1}^+, z_{i+1}^+)$ and the lower hull by $(z_{i+1}^-, z_{i+1}^-)$. (These are again transformations applied to all vertices in each deque. We use tags as well.) The new upper hull and new lower hull are not necessarily connected. If they are not, we connect their first and last vertices. The time complexity is $O(n)$ assuming each arithmetic operation costs constant time.",
    "tags": [
      "dp",
      "geometry"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1519",
    "index": "A",
    "title": "Red and Blue Beans",
    "statement": "You have $r$ red and $b$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:\n\n- has at least one red bean (or the number of red beans $r_i \\ge 1$);\n- has at least one blue bean (or the number of blue beans $b_i \\ge 1$);\n- the number of red and blue beans should differ in no more than $d$ (or $|r_i - b_i| \\le d$)\n\nCan you distribute all beans?",
    "tutorial": "Without loss of generality, let's say $r \\le b$ (otherwise, we can swap them). Note that you can't use more than $r$ packets (at least one red bean in each packet), so $b$ can't exceed $r \\cdot (d + 1)$ (at most $d + 1$ blue beans in each packet). So, if $b > r \\cdot (d + 1)$ then asnwer is NO. Otherwise, we can form exactly $r$ packets.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (r, b, d) = readLine()!!.split(' ').map { it.toInt() }\n        println(if (minOf(r, b) * (d + 1).toLong() >= maxOf(r, b)) \"YES\" else \"NO\")\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1519",
    "index": "B",
    "title": "The Cake Is a Lie",
    "statement": "There is a $n \\times m$ grid. You are standing at cell $(1, 1)$ and your goal is to finish at cell $(n, m)$.\n\nYou can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $(x, y)$. You can:\n\n- move right to the cell $(x, y + 1)$ — it costs $x$ burles;\n- move down to the cell $(x + 1, y)$ — it costs $y$ burles.\n\nCan you reach cell $(n, m)$ spending \\textbf{exactly} $k$ burles?",
    "tutorial": "Note that whichever path you choose, the total cost will be the same. If you know that the cost is the same, then it's not hard to calculate it. It's equal to $n \\cdot m - 1$. So the task is to check: is $k$ equal to $n \\cdot m - 1$ or not. The constant cost may be proved by induction on $n + m$: for $n = m = 1$ cost is $1 \\cdot 1 - 1 = 0$. For a fixed $(n, m)$, there are only two last steps you can make: either from $(n, m - 1)$ with cost $n$: the total cost is $n \\cdot (m - 1) - 1 + n$ $=$ $n \\cdot m - 1$ or from $(n - 1, m)$ with cost $m$: the total cost is $(n - 1) \\cdot m - 1 + m$ $=$ $n \\cdot m - 1$. So, whichever path you choose, the total cost is the same.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (n, m, k) = readLine()!!.split(' ').map { it.toInt() }\n        println(if (n * m - 1 == k) \"YES\" else \"NO\")\n    }\n}",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1519",
    "index": "C",
    "title": "Berland Regional",
    "statement": "Polycarp is an organizer of a Berland ICPC regional event. There are $n$ universities in Berland numbered from $1$ to $n$. Polycarp knows all competitive programmers in the region. There are $n$ students: the $i$-th student is enrolled at a university $u_i$ and has a programming skill $s_i$.\n\nPolycarp has to decide on the rules now. In particular, the number of members in the team.\n\nPolycarp knows that if he chooses the size of the team to be some integer $k$, each university will send their $k$ strongest (with the highest programming skill $s$) students in the first team, the next $k$ strongest students in the second team and so on. If there are fewer than $k$ students left, then the team can't be formed. Note that there might be universities that send zero teams.\n\nThe strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is $0$.\n\nHelp Polycarp to find the strength of the region for each choice of $k$ from $1$ to $n$.",
    "tutorial": "There are two important observations to make. The first one is that you can calculate the answers for each university independently of each other and sum them up to obtain the true answer. The second one is that if there are $x$ students in an university, then that university can only contribute to answers for $k$ from $1$ to $x$. So if we learn to calculate the contribution of the $i$-th university for some fixed $k$ in $O(1)$, then we will be able to iterate over all possible $k$ for each university and get the solution in $O(\\sum \\limits_{i=1}^{n} x_i) = O(n)$, where $x_i$ is the number of students in the $i$-th university. To achieve it, you have to gather the sum of the maximum number of students that can form full teams of size $k$. That must be the highest number less than or equal to $x_i$ that is divisible by $k$, so $\\lfloor \\frac{x_i}{k} \\rfloor \\cdot k$. Sort the students of each university, precalculate partial sums, and now you are free to add the prefix sum of that number of students to the answer for $k$. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n    int t;\n    scanf(\"%d\", &t);\n    forn(_, t){\n        int n;\n        scanf(\"%d\", &n);\n        vector<int> s(n), u(n);\n        forn(i, n){\n            scanf(\"%d\", &s[i]);\n            --s[i];\n        }\n        forn(i, n){\n            scanf(\"%d\", &u[i]);\n        }\n        vector<vector<int>> bst(n);\n        forn(i, n) bst[s[i]].push_back(u[i]);\n        forn(i, n) sort(bst[i].begin(), bst[i].end(), greater<int>());\n        vector<vector<long long>> pr(n, vector<long long>(1, 0));\n        forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);\n        vector<long long> ans(n);\n        forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)\n            ans[k - 1] += pr[i][bst[i].size() / k * k];\n        forn(i, n)\n            printf(\"%lld \", ans[i]);\n        puts(\"\");\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "number theory",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1519",
    "index": "D",
    "title": "Maximum Sum of Products",
    "statement": "You are given two integer arrays $a$ and $b$ of length $n$.\n\nYou can reverse \\textbf{at most one} subarray (continuous subsegment) of the array $a$.\n\nYour task is to reverse such a subarray that the sum $\\sum\\limits_{i=1}^n a_i \\cdot b_i$ is \\textbf{maximized}.",
    "tutorial": "The naive approach is to iterate over $l$ and $r$, reverse the subsegment of the array $[l, r]$ and calculate the answer. But this solution is too slow and works in $O(n^3)$. Instead, we can iterate over the center of the reversed segment and its length. If the current segment is $[l, r]$, and we want to go to $[l - 1, r + 1]$, then the answer for the subsegment will increase by $a_{l-1}* b_{r + 1} + a_{r + 1} * b_{l-1}$. It remains to add the answer for $[1, l)$ and $(r, n]$, but without reversion, this is easy to do if you pre-calculate the prefix sums of the values $a_i * b_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing li = long long;\n\nint main() {\n  int n;\n  cin >> n;\n  vector<li> a(n), b(n);\n  for (auto& x : a) cin >> x;\n  for (auto& x : b) cin >> x;\n  vector<li> pr(n + 1, 0);\n  for (int i = 0; i < n; ++i)\n    pr[i + 1] = pr[i] + a[i] * b[i];\n  li ans = pr[n];\n  for (int c = 0; c < n; ++c) {\n    li cur = a[c] * b[c];\n    for (int l = c - 1, r = c + 1; l >= 0 && r < n; --l, ++r) {\n      cur += a[l] * b[r];\n      cur += a[r] * b[l];\n      ans = max(ans, cur + pr[l] + (pr[n] - pr[r + 1]));\n    }\n    cur = 0;\n    for (int l = c, r = c + 1; l >= 0 && r < n; --l, ++r) {\n      cur += a[l] * b[r];\n      cur += a[r] * b[l];\n      ans = max(ans, cur + pr[l] + (pr[n] - pr[r + 1]));\n    }\n  }\n  cout << ans << endl;\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1519",
    "index": "E",
    "title": "Off by One",
    "statement": "There are $n$ points on an infinite plane. The $i$-th point has coordinates $(x_i, y_i)$ such that $x_i > 0$ and $y_i > 0$. The coordinates are not necessarily integer.\n\nIn one move you perform the following operations:\n\n- choose two points $a$ and $b$ ($a \\neq b$);\n- move point $a$ from $(x_a, y_a)$ to either $(x_a + 1, y_a)$ or $(x_a, y_a + 1)$;\n- move point $b$ from $(x_b, y_b)$ to either $(x_b + 1, y_b)$ or $(x_b, y_b + 1)$;\n- remove points $a$ and $b$.\n\n\\textbf{However, the move can only be performed if there exists a line that passes through the new coordinates of $a$, new coordinates of $b$ and $(0, 0)$.}\n\nOtherwise, the move can't be performed and the points stay at their original coordinates $(x_a, y_a)$ and $(x_b, y_b)$, respectively.\n\nThe numeration of points \\textbf{does not change} after some points are removed. Once the points are removed, they can't be chosen in any later moves. Note that you have to move both points during the move, you can't leave them at their original coordinates.\n\nWhat is the maximum number of moves you can perform? What are these moves?\n\nIf there are multiple answers, you can print any of them.",
    "tutorial": "At first the problem sounds like some sort of matching. However, it seems like you first want to match each point with either of its moves and then some pairs of points to each other. That doesn't sound viable but since the matchings are often connected with graphs, the graph idea might come handy. Let's first consider a pair of matched points. What does it actually mean that there exists a line through their new coordinates and $(0, 0)$? It's the same as: the angles of a line through the new coordinates of $a$ and $(0, 0)$ and a line through the new coordinates of $b$ and $(0, 0)$ are the same. Angles are the same means that their tangents are the same (and vice versa since we only consider the first quadrant of the plane). So we can conclude that $\\frac{y}{x+1}$ or $\\frac{y+1}{x}$ of the first point should be equal to any of these of the second point. Now consider the following graph. Various values of tangents of the lines are the nodes. Each point produces an edge between their $\\frac{y}{x+1}$ and $\\frac{y+1}{x}$. What are the matched pairs of points in this graph? It's such a pair of edges that they share at least one endpoint. Building a graph is the slowest part of the solution since you have to use some data structure (or at least a sort and a binary search). $O(n)$ is possible with some sort of hashmap but $O(n \\log n)$ should be perfectly fine as well. So we reduced the problem to a more well-known one: given an arbitrary undirected graph, find the maximum number of pairs of edges such that each pair shares at least one endpoint and each edge is included in no more than one pair. The upper bound on the answer is the following. Let $m_i$ be the number of edges in the $i$-th connected component. Best case we can make $\\lfloor \\frac{m_i}{2} \\rfloor$ pairs from it. Let's come up with an algorithm to achieve this bound. Consider a dfs tree of a component. It's known that a dfs tree of an undirected graph contains no cross edges. So if we direct all the edges of a dfs tree downwards (convert all back edges to forward edges), each edge will connect some vertex to its descendant. Imagine we came up with a dfs such that $dfs(v)$ matches all the edges that have their upper node in the subtree of $v$ to each other (except one edge in case there is an odd number of them). $dfs(root)$ will solve the task exactly then. How should that dfs work exactly? What if there were no forward edges at all? That case is easy since all edges are tree edges. We'll try to maintain an invariant that the only unmatched edge is an edge that has $v$ as one of its endpoints. If $v$ is a leaf, then there's nothing to match. Otherwise, we go into some child $u$. If it can't match all its edges, then match its remaining edge to an edge $(v, u)$. If it can then remember that we have an edge $(v, u)$ unmatched so far. Go into another child $w$. Same, match our edge with its edge if it has one unmatched. However, if $(v, w)$ turned out to get unmatched and $(v, u)$ turned out to be unmatched, then you can match them to each other. This way you will be left with at most one unmatched edge after you process all the children, and that edge has its endpoint at $v$. Add the forward edges back. Did anything change? Look at the forward edge that has its upper vertex the lowest. We can see that it points to a vertex $u$ that has its subtree fully matches. So why don't we treat this forward edge the same as an edge to a leaf? Forget that $u$ has some subtree of its own and just believe that you can't match the edge $(v, u)$ so far. Proceed the same as the easy case. Since we mark exactly which edges you pair up with which, it's trivial to retrieve the answer. Overall complexity: $O(n)/O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define x first\n#define y second\n\nusing namespace std;\n\nstruct point{\n    int a, b, c, d;\n};\n\ntypedef pair<long long, long long> frac;\ntypedef pair<int, int> pt;\n\nint n;\nvector<point> a;\nmap<frac, int> sv;\n\nfrac norm(long long x, long long y){\n    long long g = __gcd(x, y);\n    return {x / g, y / g};\n}\n\nvector<vector<pt>> g;\nvector<int> used;\nvector<pt> ans;\n\nint dfs(int v){\n    used[v] = 1;\n    int cur = -1;\n    for (auto it : g[v]){\n        int u = it.x;\n        int i = it.y;\n        if (used[u] == 1) continue;\n        int nw = i;\n        if (!used[u]){\n            int tmp = dfs(u);\n            if (tmp != -1){\n                ans.push_back({nw, tmp});\n                nw = -1;\n            }\n        }\n        if (nw != -1){\n            if (cur != -1){\n                ans.push_back({cur, nw});\n                cur = -1;\n            }\n            else{\n                cur = nw;\n            }\n        }\n    }\n    used[v] = 2;\n    return cur;\n}\n\nint main() {\n    scanf(\"%d\", &n);\n    a.resize(n);\n    forn(i, n) scanf(\"%d%d%d%d\", &a[i].a, &a[i].b, &a[i].c, &a[i].d);\n    g.resize(2 * n);\n    forn(i, n){\n        frac f1 = norm((a[i].a + a[i].b) * 1ll * a[i].d, a[i].b * 1ll * a[i].c);\n        frac f2 = norm(a[i].a * 1ll * a[i].d, a[i].b * 1ll * (a[i].c + a[i].d));\n        if (!sv.count(f1)){\n            int k = sv.size();\n            sv[f1] = k;\n        }\n        if (!sv.count(f2)){\n            int k = sv.size();\n            sv[f2] = k;\n        }\n        g[sv[f1]].push_back({sv[f2], i});\n        g[sv[f2]].push_back({sv[f1], i});\n    }\n    used.resize(sv.size());\n    forn(i, sv.size()) if (!used[i])\n        dfs(i);\n    printf(\"%d\\n\", int(ans.size()));\n    for (auto it : ans) printf(\"%d %d\\n\", it.x + 1, it.y + 1);\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "geometry",
      "graphs",
      "sortings",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1519",
    "index": "F",
    "title": "Chests and Keys",
    "statement": "Alice and Bob play a game. Alice has got $n$ treasure chests (the $i$-th of which contains $a_i$ coins) and $m$ keys (the $j$-th of which she can sell Bob for $b_j$ coins).\n\nFirstly, Alice puts some locks on the chests. There are $m$ types of locks, the locks of the $j$-th type can only be opened with the $j$-th key. To put a lock of type $j$ on the $i$-th chest, Alice has to pay $c_{i,j}$ dollars. Alice can put any number of different types of locks on each chest (possibly, zero).\n\nThen, Bob buys some of the keys from Alice (possibly none, possibly all of them) and opens each chest he can (he can open a chest if he has the keys for all of the locks on this chest). Bob's profit is the difference between the total number of coins in the opened chests and the total number of coins he spends buying keys from Alice. If Bob's profit is \\textbf{strictly positive} (greater than zero), he wins the game. Otherwise, Alice wins the game.\n\nAlice wants to put some locks on some chests so no matter which keys Bob buys, she always wins (Bob cannot get positive profit). Of course, she wants to spend the minimum possible number of dollars on buying the locks. Help her to determine whether she can win the game at all, and if she can, how many dollars she has to spend on the locks.",
    "tutorial": "Firstly, let's try to find some naive solution for this problem. Let's iterate on the subset of locks Alice puts on the chests. After choosing the subset of locks, how to check whether Bob can gain positive profit? We can iterate on the subset of keys he can buy as well, but in fact, this problem has a polynomial solution. Construct a flow network as follows: each chest and each key represents a vertex; there are $n$ arcs from the source to the vertices representing the chests (each having capacity $a_i$), $m$ arcs from the vertices representing the keys to the sink (each having capacity $b_j$), and for each chosen lock, an arc from the respective chest-vertex to the respective key-vertex with infinite capacity. If we find the minimum cut from the source to the sink, then Bob's profit is $(\\sum_{i = 1}^{n} a_i) - mincut$. The reasoning behind this solution is the following one: if Bob takes all the chests and all the keys belonging to the first part of the cut, his profit is equal to the total cost of all chests he has taken, minus the total cost of all keys he has taken, minus infinity if he takes a chest he can't open. And the value of the cut is equal to the total cost of chests he doesn't take, plus the total cost of keys he takes, plus infinity if he can't open some chest he takes (since the arc from this chest-vertex to one of the key-vertices belongs to the cut). So, Bob's profit is $(\\sum_{i = 1}^{n} a_i) - cut$, and by minimizing the cut value, we maximize his profit. A minimum cut can be easily found using any maxflow algorithm. Unfortunately, even iterating through all subsets of locks is too slow. To improve this solution, we should look at the minimum cut and its usage a bit more in detail. Notice that Bob can always take no keys and open no chests to get a profit of zero, so Alice's goal is to ensure that it is the best Bob's option. If Bob takes no chests and no keys, it means that the cut divides the network into two parts: the source and all other vertices. And, in terms of flows, it means that the maximum flow in this network should saturate all arcs going from the source (I highlighted it because it is the key idea of the solution). Here the constraints on $a_i$, $n$ and $m$ come in handy. We can use a dynamic programming with the flow over all arcs going from the source as one of the states. One of the ways to implement it is to have $(f_1, f_2, \\dots, f_n, i, j, r)$ as the state, where $f_1$ through $f_n$ are the values of the flow going from the arcs from the source, $i$ is the current vertex in the left part we consider, $j$ is the current vertex in the right part we consider, and $r$ is the flow we already pushed through the arc connecting vertex $j$ of the right part to the sink (and the value we store for this state is the minimum cost Alice has pay to reach this state). There are two basic types of transitions in this dynamic programming: we either skip the arc from $i$ to $j$, or pick it and transfer some flow through it; and no matter what we've chosen, we move to the next vertex of the left part (or to $1$ and increase $j$ by $1$ if we are already considering the $n$-th vertex of the left part). The constraints were loose enough to implement this dp basically in any form (there was no need to compress the states into single integers, for example, which was what the most participants of the round did).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 6;\nconst int M = 400;\nconst int INF = int(1e9);\n\nint a[N];\nint b[N];\nint c[N][N];\nint n, m;\n\nstruct state\n{\n    vector<int> need;\n    int v2;\n    int v1;\n    int rem;\n    state() {};\n    state(vector<int> need, int v1, int v2, int rem) : need(need), v1(v1), v2(v2), rem(rem) {};\n};\n\nint get_code(const vector<int>& v)\n{\n    int ans = 0;\n    for(int i = 0; i < v.size(); i++)\n        ans = ans * 5 + v[i];\n    return ans;\n}\n\nint get_code(const state& s)\n{\n    int code = get_code(s.need);\n    code = code * 6 + s.v2;\n    code = code * 6 + s.v1;\n    code = code * 5 + s.rem;\n    return code; \n}\n\nvector<int> get_vector(int code, int n)\n{\n    vector<int> res(n);\n    for(int i = n - 1; i >= 0; i--)\n    {\n        res[i] = code % 5;\n        code /= 5;\n    }\n    return res;\n}\n\nstate get_state(int code)\n{\n    int rem = code % 5;\n    code /= 5;\n    int v1 = code % 6;\n    code /= 6;\n    int v2 = code % 6;\n    code /= 6;\n    vector<int> need = get_vector(code, n);\n    return state(need, v1, v2, rem);\n}\n\nconst int Z = 40 * int(1e6);\nint dp[Z];\n\nint main()\n{\n    cin >> n >> m;\n    for(int i = 0; i < n; i++)\n        cin >> a[i];\n    for(int i = 0; i < m; i++)\n        cin >> b[i];\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < m; j++)\n            cin >> c[i][j];\n    for(int i = 0; i < Z; i++)\n        dp[i] = INF;\n    state start(vector<int>(n, 0), 0, 0, 0);\n    int ans = INF;\n    dp[get_code(start)] = 0;\n    for(int i = 0; i < Z; i++)\n    {\n        if(dp[i] == INF) continue;\n        state s = get_state(i);\n        for(int f = 0; f <= 4; f++)\n        {\n            if(s.need[s.v1] + f > a[s.v1] || s.rem + f > b[s.v2])\n                continue;\n            int add = (f == 0 ? 0 : c[s.v1][s.v2]);\n            state nw = s;\n            nw.need[s.v1] += f;\n            nw.rem += f;\n            if(s.v1 == n - 1)\n            {\n                nw.v1 = 0;\n                nw.v2 = s.v2 + 1;\n                nw.rem = 0;\n            }\n            else\n            {\n                nw.v1 = s.v1 + 1;\n            }\n            if(nw.need == vector<int>(a, a + n))\n                ans = min(ans, dp[i] + add);\n            if(nw.v2 < m)\n            {\n                int code = get_code(nw);\n                dp[code] = min(dp[code], dp[i] + add);\n            }\n        }\n    }\n    if(ans == INF) ans = -1;\n    cout << ans << endl;\n\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp",
      "flows"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1520",
    "index": "A",
    "title": "Do Not Be Distracted!",
    "statement": "Polycarp has $26$ tasks. Each task is designated by a capital letter of the Latin alphabet.\n\nThe teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.\n\nPolycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.\n\nFor example, if Polycarp solved tasks in the following order: \"DDBBCCCBBEZ\", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: \"BAB\", \"AABBCCDDEEBZZ\" and \"AAAAZAAAAA\".\n\nIf Polycarp solved the tasks as follows: \"FFGZZZY\", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: \"BA\", \"AFFFCC\" and \"YYYYY\".\n\nHelp Polycarp find out if his teacher might be suspicious.",
    "tutorial": "The simplest solution - go through the problem, because of which the teacher might have suspicions. Now you can find the first day when Polycarp solved this problem and the last such day. Between these two days, all problems should be the same. If this is not the case, the answer is \"NO\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    for (char c = 'A'; c <= 'Z'; c++) {\n        int first = n;\n        int last = -1;\n        for (int i = 0; i < n; i++) {\n            if (s[i] == c) {\n                first = min(first, i);\n                last = max(last, i);\n            }\n        }\n        for (int i = first; i <= last; i++) {\n            if (s[i] != c) {\n                cout << \"NO\\n\";\n                return;\n            }\n        }\n    }\n    cout << \"YES\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1520",
    "index": "B",
    "title": "Ordinary Numbers",
    "statement": "Let's call a positive integer $n$ ordinary if in the decimal notation all its digits are the same. For example, $1$, $2$ and $99$ are ordinary numbers, but $719$ and $2021$ are not ordinary numbers.\n\nFor a given number $n$, find the number of ordinary numbers among the numbers from $1$ to $n$.",
    "tutorial": "Note that every ordinary number can be represented as $d \\cdot (10^0 + 10^1 + \\ldots + 10^k)$. Therefore, to count all ordinary numbers among the numbers from $1$ to $n$, it is enough to count the number of $(d, k)$ pairs such that $d \\cdot (10^0 + 10^1 + \\ldots + 10^k) \\le n$. In the given constraints, it is enough to iterate over $d$ from $1$ to $9$ and $k$ from $0$ to $8$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  int res = 0;\n  for (ll pw = 1; pw <= n; pw = pw * 10 + 1) {\n    for (int d = 1; d <= 9;  d++) {\n      if (pw * d <= n) {\n        res++;\n      }\n    }\n  }\n  cout << res << endl;\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1520",
    "index": "C",
    "title": "Not Adjacent Matrix",
    "statement": "We will consider the numbers $a$ and $b$ as adjacent if they differ by exactly one, that is, $|a-b|=1$.\n\nWe will consider cells of a square matrix $n \\times n$ as adjacent if they have a common side, that is, for cell $(r, c)$ cells $(r, c-1)$, $(r, c+1)$, $(r-1, c)$ and $(r+1, c)$ are adjacent to it.\n\nFor a given number $n$, construct a square matrix $n \\times n$ such that:\n\n- Each integer from $1$ to $n^2$ occurs in this matrix exactly once;\n- If $(r_1, c_1)$ and $(r_2, c_2)$ are adjacent cells, then the numbers written in them \\textbf{must not be adjacent}.",
    "tutorial": "Note that $n = 2$ is the only case where there is no answer. For other cases, consider the following construction: Let's say that the cell $(i, j)$ is white if $i + j$ is an even number, otherwise, we will say that the cell $(i, j)$ is black; Let's arrange the cells so that all white cells are first, and if the colors are equal, the cells will be compared lexicographically. Arrange numbers from $1$ to $n^2$ in ordered cells. For example, for $n=3$, the following matrix will be constructed: $\\begin{pmatrix} 1 & 6 & 2\\\\ 7 & 3 & 8\\\\ 4 & 9 & 5\\\\ \\end{pmatrix}$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  if (n == 1) {\n    cout << \"1\" << endl;\n    return;\n  } else if (n == 2) {\n    cout << \"-1\" << endl;\n    return;\n  }\n  vector<vector<int>> a(n, vector<int>(n));\n  a[0][0] = 1;\n  a[n - 1][n - 1] = n * n;\n  int x = n * n - 1;\n  for (int i = 1; i + 1 < n; i++) {\n    for (int j = i; j >= 0; j--, x--) {\n      a[i - j][j] = x;\n    }\n  }\n  x = 2;\n  for (int j = n - 2; j > 0; j--) {\n    for (int i = 0; i < n - j; i++, x++) {\n      a[n - i - 1][j + i] = x;\n    }\n  }\n  for (int i = n - 1; i >= 0; i--, x++) {\n    a[i][n - i - 1] = x;\n  }\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      cout << a[i][j] << \" \";\n    }\n    cout << endl;\n  }\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1520",
    "index": "D",
    "title": "Same Differences",
    "statement": "You are given an array $a$ of $n$ integers. Count the number of pairs of indices $(i, j)$ such that $i < j$ and $a_j - a_i = j - i$.",
    "tutorial": "Let's rewrite the original equality a bit: $a_j - a_i = j - i,$ $a_j - j = a_i - i$ Let's replace each $a_i$ with $b_i = a_i - i$. Then the answer is the number of pairs $(i, j)$ such that $i < j$ and $b_i = b_j$. To calculate this value you can use map or sorting.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  map<int, int> a;\n  long long res = 0;\n  for (int i = 0; i < n; i++) {\n    int x;\n    cin >> x;\n    x -= i;\n    res += a[x];\n    a[x]++;\n  }\n  cout << res << endl;\n}\n\nint main() {\n  int tests;\n  cin >> tests;\n  while (tests-- > 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "data structures",
      "hashing",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1520",
    "index": "E",
    "title": "Arranging The Sheep",
    "statement": "You are playing the game \"Arranging The Sheep\". The goal of this game is to make the sheep line up. The level in the game is described by a string of length $n$, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square \\textbf{exists and is empty}. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.\n\nFor example, if $n=6$ and the level is described by the string \"**.*..\", then the following game scenario is possible:\n\n- the sheep at the $4$ position moves to the right, the state of the level: \"**..*.\";\n- the sheep at the $2$ position moves to the right, the state of the level: \"*.*.*.\";\n- the sheep at the $1$ position moves to the right, the state of the level: \".**.*.\";\n- the sheep at the $3$ position moves to the right, the state of the level: \".*.**.\";\n- the sheep at the $2$ position moves to the right, the state of the level: \"..***.\";\n- the sheep are lined up and the game ends.\n\nFor a given level, determine the minimum number of moves you need to make to complete the level.",
    "tutorial": "Let's denote by $k$ the number of sheep in the string, and by $x_1, x_2, \\ldots, x_k$ ($1 \\le x_1 < x_2 < \\ldots < x_k \\le n$) their positions in the string. Note that in the optimal solution the sheep with the number $m = \\lceil\\frac{n}{2}\\rceil$ will not make moves. This can be proved by considering the optimal solution in which the sheep with the number $m$ makes at least one move and come to the conclusion that this solution is not optimal. Consider sheep with numbers from $i=1$ to $n$. Then the final position of the $i$-th sheep will be $x_m - m + i$, and the answer will be $\\sum\\limits_{i=1}^{k} |x_i - (x_m - m + i)|$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tint cnt = 0;\n\tfor(auto x : s)\n\t\tcnt += (x == '*' ? 1 : 0);\n\tint pos = -1;\n\tint cur = -1;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t \tif(s[i] == '*')\n\t \t{\n\t \t    cur++;\n\t \t    if(cur == cnt / 2)\n\t \t    \tpos = i;\n\t \t}\t\n\t}\n\tlong long ans = 0;\n\tcur = pos - cnt / 2;\n\tfor(int i = 0; i < n; i++)\n\t\tif(s[i] == '*')\n\t\t{\n\t\t \tans += abs(cur - i);\n\t\t \tcur++;\n\t\t}\n\tcout << ans << endl;\n}\n \nint main()\n{\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tint tc = 1;\n\tcin >> tc;\n\tfor(int i = 0; i < tc; i++)\n\t{\n\t \tsolve();\n\t}\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1520",
    "index": "F1",
    "title": "Guess the K-th Zero (Easy version)",
    "statement": "\\textbf{This is an interactive problem.}\n\n\\textbf{This is an easy version of the problem. The difference from the hard version is that in the easy version $t=1$ and the number of queries is limited to $20$.}\n\nPolycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the $k$-th zero from the left $t$ times.\n\nPolycarp can make no more than $20$ requests of the following type:\n\n- ? $l$ $r$ — find out the sum of all elements in positions from $l$ to $r$ ($1 \\le l \\le r \\le n$) inclusive.\n\nIn this (easy version) of the problem, this paragraph doesn't really make sense since $t=1$ always. To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the $k$-th zero was $x$, then after Polycarp guesses this position, the $x$-th element of the array will be replaced from $0$ to $1$. Of course, this feature affects something only for $t>1$.\n\nHelp Polycarp win the game.",
    "tutorial": "This problem can be solved by binary search. Let's maintain a segment that is guaranteed to contain the $k$-th zero and gradually narrow it down. Let the current segment be - $[l, r]$ and we want to find $k$-th zero on it. Let's make a query on the half of the segment $[l, m]$, where $m = \\frac{l+r}{2}$. If there are at least $k$ zeros on the left half of the segment, then we go to the left segment and look for the $k$-th zero. If there is only $x < k$ zeros on the left half, then we go to the right segment and look for $(k-x)$-th zero. We will spend $\\log{n}$ queries, which is within the limits.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nvoid calc(int l, int r, int k) {\n    if (l == r) {\n        cout << \"! \" << l << endl;\n        return;\n    }\n    int m = (l + r) / 2;\n    cout << \"? \" << l << \" \" << m << endl;\n    int sum;\n    cin >> sum;\n    if ((m - l + 1) - sum >= k) {\n        calc(l, m, k);\n    } else {\n        calc(m + 1, r, k - (m - l + 1) + sum);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, t, k;\n    cin >> n >> t >> k;\n    calc(1, n, k);\n}",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1520",
    "index": "F2",
    "title": "Guess the K-th Zero (Hard version)",
    "statement": "\\textbf{This is an interactive problem.}\n\n\\textbf{This is a hard version of the problem. The difference from the easy version is that in the hard version $1 \\le t \\le \\min(n, 10^4)$ and the total number of queries is limited to $6 \\cdot 10^4$.}\n\nPolycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the $k$-th zero from the left $t$ times.\n\nPolycarp can make no more than $6 \\cdot 10^4$ requests totally of the following type:\n\n- ? $l$ $r$ — find out the sum of all elements in positions from $l$ to $r$ ($1 \\le l \\le r \\le n$) inclusive.\n\nTo make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the $k$-th zero was $x$, then after Polycarp guesses this position, the $x$-th element of the array will be replaced from $0$ to $1$.\n\nHelp Polycarp win the game.",
    "tutorial": "In this problem, you can apply the same solution as in the previous one, but you need to remember the responses to the requests and not make the same requests several times. Why does it work? Imagine a binary tree with a segment at each vertex, and its children - the left and right half of the segment. We will leave only those vertexes for which we made requests. It remains to show that there are no more than $6 \\cdot 10^4$ such vertices. First - the height of the tree is not more than $18$. Let's understand what the maximum number of vertices can be in the tree. We will consider each level separately. If the level number $x$ is less than $\\log{t} \\le 14$, then we can spend no more than $x$ of vertices (since there are simply no more vertices). If the level number is from $15$ to $18$, then we can spend no more than $t$ vertices, so each request uses only one vertex per level. By limiting the number of vertices in this way, we get that there are no more than $2^14 - 1 + 4 \\cdot 10^4 = 56383$, which fits into the constraints.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nmap<pair<int,int>, int> cache;\n\nvoid dec(int pos, int L, int R) {\n    cache[{L, R}]--;\n\n    if (L != R) {\n        int M = (L + R) / 2;\n        if (pos <= M)\n            dec(pos, L, M);\n        else\n            dec(pos, M + 1, R);\n    }\n}\n\nint main() {\n    int n, cases;\n    cin >> n >> cases;\n    forn(case_, cases) {\n        int k;\n        cin >> k;\n        int L = 0, R = n - 1;\n        while (L != R) {\n            int M = (L + R) / 2;\n            \n            pair<int,int> range = make_pair(L, M);\n            if (cache.count(range) == 0) {\n                cout << \"? \" << range.first + 1 << \" \" << range.second + 1 << endl;\n                cin >> cache[range];\n                cache[range] = range.second - range.first + 1 - cache[range];\n            }\n\n            int value = cache[range];\n            if (k <= value)\n                R = M;\n            else {\n                k -= value;\n                L = M + 1;\n            }\n        }\n\n        cout << \"! \" << L + 1 << endl;\n        dec(L, 0, n - 1);\n    }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "interactive"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1520",
    "index": "G",
    "title": "To Go Or Not To Go?",
    "statement": "Dima overslept the alarm clock, which was supposed to raise him to school.\n\nDima wonders if he will have time to come to the first lesson. To do this, he needs to know the \\textbf{minimum time} it will take him to get from home to school.\n\nThe city where Dima lives is a rectangular field of $n \\times m$ size. Each cell $(i, j)$ on this field is denoted by one number $a_{ij}$:\n\n- The number $-1$ means that the passage through the cell is prohibited;\n- The number $0$ means that the cell is free and Dima can walk though it.\n- The number $x$ ($1 \\le x \\le 10^9$) means that the cell contains a portal with a cost of $x$. A cell with a portal is also considered free.\n\nFrom any portal, Dima can go to any other portal, while the time of moving from the portal $(i, j)$ to the portal $(x, y)$ corresponds to the sum of their costs $a_{ij} + a_{xy}$.\n\nIn addition to moving between portals, Dima can also move between unoccupied cells adjacent to one side in time $w$. In particular, he can enter a cell with a portal and not use it.\n\nInitially, Dima is in the upper-left cell $(1, 1)$, and the school is in the lower right cell $(n, m)$.",
    "tutorial": "There is no point in using two transitions between portals, because if you want to go from portal $A$ to portal $B$, and then from portal $C$ to portal $D$, then you can immediately go from portal $A$ to portal $D$ for less. Then there are two possible paths. First - do not use portals. Here it is enough to find the shortest path between two points. The second - use a single transition. Let's choose a portal from which we should teleport. Obviously, this is a portal with a minimum distance to it and the cost of the transition. Similarly, the portal in which we should teleport is selected.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nconst int MAX_N = 2010;\n\nint dd[4][2] = {\n        {1, 0},\n        {0, 1},\n        {-1, 0},\n        {0, -1}\n};\n\nvoid bfs(int sx, int sy, vector<vector<int>> &d, vector<vector<int>> &a) {\n    int n = d.size();\n    int m = d[0].size();\n    queue<pair<int, int>> q;\n    q.push({sx, sy});\n    d[sx][sy] = 1;\n    while (!q.empty()) {\n        auto [x, y] = q.front();\n        q.pop();\n        for (auto [dx, dy] : dd) {\n            int tx = x + dx;\n            int ty = y + dy;\n            if (tx >= 0 && ty >= 0 && tx < n && ty < m && d[tx][ty] == 0 && a[tx][ty] != -1) {\n                d[tx][ty] = d[x][y] + 1;\n                q.push({tx, ty});\n            }\n        }\n    }\n    for (auto &e : d) {\n        for (auto &i : e) {\n            i--;\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, m, w;\n    cin >> n >> m >> w;\n    vector<vector<int>> a(n, vector<int>(m));\n    vector<vector<int>> d1(n, vector<int>(m));\n    vector<vector<int>> d2(n, vector<int>(m));\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            cin >> a[i][j];\n        }\n    }\n    bfs(0, 0, d1, a);\n    bfs(n - 1, m - 1, d2, a);\n    ll bestFinish = 1e18;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            if (d2[i][j] != -1 && a[i][j] >= 1) {\n                bestFinish = min(bestFinish, a[i][j] + w * 1ll * d2[i][j]);\n            }\n        }\n    }\n    ll ans = w * 1ll * d1[n - 1][m - 1];\n    if (d1[n - 1][m - 1] == -1) {\n        ans = 1e18;\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            if (d1[i][j] != -1 && a[i][j] >= 1 && bestFinish != 1e18) {\n                ans = min(ans, w * 1ll * d1[i][j] + a[i][j] + bestFinish);\n            }\n        }\n    }\n    if (ans == 1e18) {\n        cout << -1;\n    } else {\n        cout << ans;\n    }\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1521",
    "index": "A",
    "title": "Nastia and Nearly Good Numbers",
    "statement": "Nastia has $2$ positive integers $A$ and $B$. She defines that:\n\n- The integer is good if it is divisible by $A \\cdot B$;\n- Otherwise, the integer is nearly good, if it is divisible by $A$.\n\nFor example, if $A = 6$ and $B = 4$, the integers $24$ and $72$ are good, the integers $6$, $660$ and $12$ are nearly good, the integers $16$, $7$ are neither good nor nearly good.\n\nFind $3$ \\textbf{different} positive integers $x$, $y$, and $z$ such that \\textbf{exactly one} of them is good and the \\textbf{other} $2$ are nearly good, and $x + y = z$.",
    "tutorial": "There are $2$ cases: if $B = 1$, then the answer doesn't exist. Here we cannot get the nearly good numbers at all. Otherwise, we can construct the answer as $A + A \\cdot B = A \\cdot (B + 1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n\n    int q;\n    cin >> q;\n\n    while (q--) {\n        int a, b; cin >> a >> b;\n        if (b == 1) {\n            cout << \"NO\" << endl;\n        } else {\n            cout << \"YES\" << endl;\n            cout << a << ' ' << a * (long long)b << ' ' << a * (long long)(b + 1) << endl;\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1521",
    "index": "B",
    "title": "Nastia and a Good Array",
    "statement": "Nastia has received an array of $n$ positive integers as a gift.\n\nShe calls such an array $a$ good that for all $i$ ($2 \\le i \\le n$) takes place $gcd(a_{i - 1}, a_{i}) = 1$, where $gcd(u, v)$ denotes the greatest common divisor (GCD) of integers $u$ and $v$.\n\nYou can perform the operation: select two \\textbf{different} indices $i, j$ ($1 \\le i, j \\le n$, $i \\neq j$) and two integers $x, y$ ($1 \\le x, y \\le 2 \\cdot 10^9$) so that $\\min{(a_i, a_j)} = \\min{(x, y)}$. Then change $a_i$ to $x$ and $a_j$ to $y$.\n\nThe girl asks you to make the array good using \\textbf{at most} $n$ operations.\n\nIt can be proven that this is always possible.",
    "tutorial": "There are many ways to solve the problem. Here is one of them: We will use the fact that $gcd(i, i + 1) = 1$ for any integer $i \\ge 1$. Let's find the minimum element $x$ of the array $a$ that is located in the position $pos$. Then for all integer $i$ ($1 \\le i \\le n$) perform the following operation: $(pos,\\ i,\\ x,\\ x + abs(pos - i))$. That's how we replace $a_i$ to $x + abs(pos - i)$. The main condition: $\\min{(a_i, a_j)} = \\min{(x, y)}$ is satisfied because $a_{pos}$ always equals to $x$ and this value always less than any other element in the array $a$. Consider the structure of the array $a$ after performing the operations describing above. Let's define $l = x + pos - i$ and $r = x + i - pos$. These are the leftmost and the rightmost elements in the array $a$, respectively. The array $a$ looks like $[l,\\ l - 1\\ \\ldots\\ x + 1,\\ x,\\ x + 1\\ \\ldots\\ r - 1,\\ r]$. Thus, we obtain an absolute difference, equal to one, between all pairs of adjacent elements.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n\n    int q;\n    cin >> q;\n\n    while (q--) {\n        int n; cin >> n;\n        int x = 1e9 + 7, pos = -1;\n        for (int i = 0; i < n; ++i) {\n            int a; cin >> a;\n            if (a < x) x = a, pos = i;\n        }\n        cout << n - 1 << endl;\n        for (int i = 0; i < n; ++i) {\n            if (i == pos) continue;\n            cout << pos + 1 << ' ' << i + 1 << ' ' << x << ' ' << x + abs(i - pos) << \"\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1521",
    "index": "C",
    "title": "Nastia and a Hidden Permutation",
    "statement": "\\textbf{This is an interactive problem!}\n\nNastia has a hidden permutation $p$ of length $n$ consisting of integers from $1$ to $n$. You, for some reason, want to figure out the permutation. To do that, you can give her an integer $t$ ($1 \\le t \\le 2$), two \\textbf{different} indices $i$ and $j$ ($1 \\le i, j \\le n$, $i \\neq j$), and an integer $x$ ($1 \\le x \\le n - 1$).\n\nDepending on $t$, she will answer:\n\n- $t = 1$: $\\max{(\\min{(x, p_i)}, \\min{(x + 1, p_j)})}$;\n- $t = 2$: $\\min{(\\max{(x, p_i)}, \\max{(x + 1, p_j)})}$.\n\nYou can ask Nastia \\textbf{at most} $\\lfloor \\frac {3 \\cdot n} { 2} \\rfloor + 30$ times. It is guaranteed that she will \\textbf{not} change her permutation depending on your queries. Can you guess the permutation?",
    "tutorial": "Solution $1$: Let's fix $2$ indices $i$ and $j$ $(1 \\le i, j \\le n,$ $i \\neq j)$. Then restore $p_{i}$ and $p_{j}$. Let's assume we know the maximum element among $p_i$ and $p_j$: $mx = \\max(p_i, p_j)$. Now we can figure out where exactly the maximum is by asking the following query: $val = \\max{(\\min{(mx - 1, p_i)}, \\min{(mx, p_j)})}$. There are $2$ cases: $val = mx - 1$: it means $p_j \\lt mx$, otherwise $val = \\min{(mx, p_j)} = mx$. $val = mx$: it means $p_j = mx$, because $\\min{(mx - 1, p_i)} \\lt mx$. If we know where the maximum is located we easily can find the remaining element: if $p_i = mx$, then $p_j = \\min{(\\max{(1, p_j)}, \\max{(2, p_i)})}$. if $p_j = mx$, then $p_i = \\min{(\\max{(1, p_i)}, \\max{(2, p_j)})}$. We can solve the problem if we know the $mx$. Let's find it: $mx = \\max{(\\min{(n - 1, p_i)}, \\min{(n, p_j)})}$ Take a look on the case when $mx = n - 1$. Here we cannot be sure that $mx = max(p_i, p_j)$. It's possible only if $p_i = n$. Thus if $mx = n - 1$ we spend an extra query to be sure that $p_i \\neq n$. We will ask: $val = \\max{(\\min{(n - 1, p_j)}, \\min{(n, p_i)})}$ So, if $val = n$, then the value $p_i$ equlas to $n$, otherwise the value $mx = n - 1$ equals to the real maximum among $p_i$ and $p_j$. As a result, we can restore any $2$ elements of the permutation. Let's split our permutation into $\\lfloor \\frac {n} {2} \\rfloor$ pairs and restore them independently of each other. The total queries we perform is $\\lfloor \\frac {3 \\cdot n} { 2} \\rfloor + 2$. We spend $3$ operations to restore each of the pair of elements. And no more than $2$ extra queries to be sure that $mx$ is correct. Solution $2$: Let's find the maximum of the permutation and then restore the element $p_i$ $(1 \\le i \\le n)$ of the permutation by query: $p_i = \\min{(\\max{(1, p_i)}, \\max{(2, mx})}$. To find the maximum element let's split the permutation into $\\lfloor \\frac {n} {2} \\rfloor$ pairs and perform the following operation to each of them: $mx = \\max{(\\min{(n - 1, p_i)}, \\min{(n, p_j)})}$. if $mx = n$, then $j$ is the position with a maximum element. if $mx = n - 1$, then need to make sure that $p_i \\neq n$. Let's make the same extra query as we do in the Solution 1. Note that if you don't find the maximum element among the $\\lfloor \\frac {n} {2} \\rfloor$, then it's in the remaining element when $n$ is odd. The total queries we perform is n + $\\lfloor \\frac {n} { 2} \\rfloor + 1$. We ask $\\lfloor \\frac {n} { 2} \\rfloor + 2$ queries to find the maximum of the permutation and $n - 1$ quiries to restore the remaining elements.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nint ask(int t, int i, int j, int x) {\n    cout << \"? \" << t << ' ' << i + 1 << ' ' << j + 1 << ' ' << x << endl;\n    int val; cin >> val;\n    if (val == -1) exit(0);\n    return val;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n\n    int q;\n    cin >> q;\n\n    while (q--) {\n        int n; cin >> n;\n        vector<int> p(n, -1);\n        for (int i = 1; i < n; i += 2) {\n            int pos1 = i - 1, pos2 = i;\n            int val = ask(1, pos1, pos2, n - 1);\n            if (val == n - 1) {\n                val = ask(1, pos2, pos1, n - 1);\n                if (val == n) {\n                    p[pos1] = val;\n                    p[pos2] = ask(2, pos2, pos1, 1);\n                    continue;\n                }\n            }\n            int get = ask(1, pos1, pos2, val - 1);\n            if (get == val) {\n                p[pos2] = val;\n                p[pos1] = ask(2, pos1, pos2, 1);\n            }\n            if (get == val - 1) {\n                p[pos1] = val;\n                p[pos2] = ask(2, pos2, pos1, 1);\n            }\n        }\n        if (p.back() == -1) {\n            vector<bool> us(n + 1);\n            for (int i = 0; i < n - 1; ++i) {\n                us[p[i]] = true;\n            }\n            for (int i = 1; i <= n; ++i) {\n                if (!us[i]) {\n                    assert(p[p.size() - 1] == -1);\n                    p[p.size() - 1] = i;\n                }\n            }\n        }\n        cout << \"! \";\n        for (int i = 0; i < n; ++i) {\n            cout << p[i] << ' ';\n        } cout << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1521",
    "index": "D",
    "title": "Nastia Plays with a Tree",
    "statement": "Nastia has an unweighted tree with $n$ vertices and wants to play with it!\n\nThe girl will perform the following operation with her tree, as long as she needs:\n\n- Remove any existing edge.\n- Add an edge between any pair of vertices.\n\nWhat is the \\textbf{minimum} number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than $2$.",
    "tutorial": "Let's define the variable $x$ as a minimum number of operations that we need to get bamboo from a tree. Let's remove $x$ edges first and then add $x$ new ones to the graph. Consider the structure of the graph after removing $x$ edges. This is a forest with a $x + 1$ connected components. Easy to notice each of the $x + 1$ connected components in the getting forest of trees must be a bamboo to get the bamboo after adding new $x$ edges. The red edges are removed. Thus, we can get the bamboo from the forest of bamboo after removing $x$ edges by $x$ times adding the conjunction between leaves that are in the different components of connectivity of the forest. The green edges are added. So, the task is to find the minimum number of the removing edges needs to get the forest of bamboos. Here works the following greedy: Let's define any vertice of the tree as a root. We will solve the problem for each of the subtrees $v$ $(1 \\le v \\le n)$. First, solve the problem for all child vertices of $v$. Then define the value $c_v$ as the number of the children and the value $p_v$ as the ancestor for vertex $v$. There are $3$ cases: If $c_v <= 1$, then we don't remove anything. If $c_v = 2$, then we remove the edge $(p_v, v)$ if $p_v$ exists. If $c_v > 2$, then we remove the edge $(p_v, v)$ if $p_v$ exists and any $c - 2$ existing edges from $v$ to one of the children vertex. Take a look at the picture: The root of the tree is vertex $1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1e5 + 7;\n\nstruct edge {\n    int v, u;\n};\n\nvector<pair<edge, edge>> operations;\n\nint dp[N], answer = 0;\n\nbool isDeleted[N];\n\nvector<pair<int, int>> g[N];\n\nvoid dfs(int v, int p = -1) {\n    int sz = (int)g[v].size() - (p != -1);\n    for (auto to : g[v]) {\n        if (to.first == p) continue;\n        dfs(to.first, v);\n        if (dp[to.first]) {\n            --sz; ++answer;\n            isDeleted[to.second] = true;\n        }\n    }\n    if (sz >= 2) {\n        dp[v] = true;\n        for (auto to : g[v]) {\n            if (to.first == p) continue;\n            if (sz <= 2) break;\n            if (!dp[to.first]) {\n                --sz; ++answer;\n                isDeleted[to.second] = true;\n            }\n        }\n    }\n}\n\nvector<pair<int, int>> bamboos;\n\nbool used[N];\n\nvector<int> leaves;\n\nvoid dfs2(int v, int root) {\n    used[v] = true;\n    int numberOfChildren = 0;\n    for (auto to : g[v]) {\n        if (used[to.first] || isDeleted[to.second]) continue;\n        ++numberOfChildren; dfs2(to.first, root);\n    }\n    if (v == root && numberOfChildren == 1) {\n        leaves.push_back(v);\n    } else if (!numberOfChildren) {\n        leaves.push_back(v);\n    }\n}\n\nvoid clear(int n) {\n    answer = 0;\n    for (int i = 0; i < n; ++i) {\n        dp[i] = 0;\n        g[i].clear();\n        used[i] = isDeleted[i] = false;\n    }\n    bamboos.clear();\n    operations.clear();\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n\n    int q;\n    cin >> q;\n\n    while (q--) {\n        int n; cin >> n;\n\n        for (int i = 0; i < n - 1; ++i) {\n            int a, b; cin >> a >> b;\n            --a; --b;\n            g[a].push_back({b, i});\n            g[b].push_back({a, i});\n        }\n\n        dfs(0);\n        for (int i = 0; i < n; ++i) {\n            if (!used[i]) {\n                dfs2(i, i);\n                assert((int)leaves.size() <= 2);\n                if ((int)leaves.size() == 2) {\n                    bamboos.push_back({leaves[0], leaves[1]});\n                }\n                if ((int)leaves.size() == 1) {\n                    bamboos.push_back({leaves.back(), leaves.back()});\n                }\n                leaves.clear();\n            }\n        }\n\n        vector<edge> deletedEdges, addedEdges;\n        for (int v = 0; v < n; ++v) {\n            for (auto to : g[v]) {\n                if (isDeleted[to.second]) {\n                    if (v < to.first) {\n                        deletedEdges.push_back({v, to.first});\n                    }\n                }\n            }\n        }\n        for (int i = 1; i < (int)bamboos.size(); ++i) {\n            addedEdges.push_back({bamboos[i - 1].second, bamboos[i].first});\n        }\n\n        assert(answer == (int)deletedEdges.size());\n        assert((int)deletedEdges.size() == (int)addedEdges.size());\n\n        for (int i = 0; i < answer; ++i) {\n            operations.push_back({deletedEdges[i], addedEdges[i]});\n        }\n\n        assert(answer == (int)operations.size());\n\n        cout << answer << endl;\n        for (pair<edge, edge> to : operations) {\n            cout << to.first.v + 1 << ' ' << to.first.u + 1 << ' ';\n            cout << to.second.v + 1 << ' ' << to.second.u + 1 << endl;\n        }\n\n        clear(n);\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1521",
    "index": "E",
    "title": "Nastia and a Beautiful Matrix",
    "statement": "You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?\n\nLet $a_i$ be how many numbers $i$ ($1 \\le i \\le k$) you have.\n\nAn $n \\times n$ matrix is called beautiful if it contains \\textbf{all} the numbers you have, and for \\textbf{each} $2 \\times 2$ submatrix of the original matrix is satisfied:\n\n- The number of occupied cells doesn't exceed $3$;\n- The numbers on each diagonal are distinct.\n\nMake a beautiful matrix of \\textbf{minimum} size.",
    "tutorial": "Let's fix $n$ and will check whether we build a beautiful matrix or not. Let's define the variable $mx$ as a maximum element among all elements from the array $a$. In other words, the amount of the most frequently occurring number we have. Also, define the variable $sum$ as an amount of numbers we have. We can single out the $2$ criteria. These are $sum \\le n ^ 2 - \\lfloor \\frac {n} {2} \\rfloor ^ 2$ and $mx \\le n \\cdot \\lceil \\frac {n} {2} \\rceil$. It can be proved by spitting the matrix into disjoint matrices $2 \\times 2$. Let's construct the structure of the matrix and provide the algorithm of arrangement, that if the previous $2$ conditions are satisfied, then we always can create the beautiful matrix of $n$ size. Take a look at the picture: There are $4$ types of cells. White cells are empty, blue ones can consist of any number. Let's fill yellow and red cells in a way that they don't have any common number. We will do it greedily: Let's fill red cells at first. Let's take numbers $x$, which is the most frequently occurring, and just try to fill red cells using only it. If all numbers $x$ are fully fit there, then we just take a new $x$ and continue filling cells. If there are elements of color $x$ that cannot be placed there then we put all such remaining elements in blue cells. It is always possible to do because the number of blue cells and yellow cells together is $n \\cdot \\lceil \\frac {n} {2} \\rceil$, that is the upper bound of the value $mx$. In this way, we filled red cells and some blue cells. The other elements, which haven't been placed yet, can be placed randomly because they won't match(by diagonal) due to the way of filling red cells.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr); cout.tie(nullptr);\n\n    int q;\n    cin >> q;\n\n    while (q--) {\n        int m, k; cin >> m >> k;\n\n        pair<int, int> a[k];\n        for (int i = 0; i < k; ++i) {\n            cin >> a[i].first, a[i].second = i + 1;\n        } sort(a, a + k, greater<pair<int, int>>());\n\n        int mx = a[0].first;\n        for (int n = 1; n <= m; ++n) {\n            // mx <= n * ceil(n / 2)\n            if (mx > n * (long long)((n + 1) / 2)) continue;\n            // m <= n ^ 2 - floor(n / 2) ^ 2\n            if (m > n * (long long)n - (n / 2) * (long long)(n / 2)) continue;\n\n            // answer = n\n            vector<pair<int, int>> x, y, z;\n            for (int i = 0; i < n; ++i) {\n                for (int j = 0; j < n; ++j) {\n                    if ((i + j) % 2 == 1) {\n                        if (i % 2 == 0) x.push_back({i, j});\n                        else y.push_back({i, j});\n                    } else {\n                        if (i % 2 == 0) z.push_back({i, j});\n                    }\n                }\n            }\n\n            int ans[n][n];\n            for (int i = 0; i < n; ++i) {\n                for (int j = 0; j < n; ++j) {\n                    ans[i][j] = 0;\n                }\n            }\n\n            for (int i = 0; i < k; ++i) {\n                vector<pair<int, int>> &cur = (x.empty() ? y : x);\n                while (a[i].first && !cur.empty()) {\n                    pair<int, int> pos = cur.back();\n                    ans[pos.first][pos.second] = a[i].second;\n                    cur.pop_back(); --a[i].first;\n                }\n                while(a[i].first--) {\n                    assert((int)z.size() > 0);\n                    pair<int, int> pos = z.back();\n                    ans[pos.first][pos.second] = a[i].second;\n                    z.pop_back();\n                }\n            }\n\n            // print answer\n            cout << n << endl;\n            for (int i = 0; i < n; ++i) {\n                for (int j = 0; j < n; ++j) {\n                    cout << ans[i][j] << ' ';\n                } cout << endl;\n            }\n\n            break;\n        }\n    }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1523",
    "index": "A",
    "title": "Game of Life",
    "statement": "William really likes the cellular automaton called \"Game of Life\" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $n$ cells, with each cell either being alive or dead.\n\nEvolution of the array in William's cellular automaton occurs iteratively in the following way:\n\n- If the element is dead and it has \\textbf{exactly} $1$ alive neighbor \\textbf{in the current state of the array}, then on the next iteration it will become alive. For an element at index $i$ the neighbors would be elements with indices $i - 1$ and $i + 1$. If there is no element at that index, it is considered to be a dead neighbor.\n- William is a humane person so all alive elements stay alive.\n\nCheck the note section for examples of the evolution.\n\nYou are given some initial state of all elements and you need to help William find the state of the array after $m$ iterations of evolution.",
    "tutorial": "Notice that evolution will go on for no more than $n$ iterations, since on each iteration at least one new living cell will appear, and if it doesn't this would mean that we remain in the same state as on the previous step and the simulation is over. Knowing this we can write a simple simulation of the process described in the problem statement, which would process each iteration in $O(n)$. Final complexity: $O(n^2)$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1523",
    "index": "B",
    "title": "Lord of the Values",
    "statement": "While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from $a_1, a_2, \\ldots, a_n$ to $-a_1, -a_2, \\ldots, -a_n$. For some unknown reason, the number of service variables is always an even number.\n\nWilliam understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed $5\\,000$ and after every operation no variable can have an absolute value greater than $10^{18}$. William can perform actions of two types for two chosen variables with indices $i$ and $j$, where $i < j$:\n\n- Perform assignment $a_i = a_i + a_j$\n- Perform assignment $a_j = a_j - a_i$\n\nWilliam wants you to develop a strategy that will get all the internal variables to the desired values.",
    "tutorial": "Notice that for transforming any pair of numbers $(a, b)$ into a pair $(-a, -b)$ a sequence of operations such as $(1, 2, 1, 2, 1, 2)$ can be performed. Since $n$ is even we can apply this sequence of operations for all pairs of numbers $(a_{i \\cdot 2 - 1}, a_{i \\cdot 2})$ for all $i$ from $1$ to $\\frac{n}{2}$. Final complexity: $O(n)$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1523",
    "index": "C",
    "title": "Compression and Expansion",
    "statement": "William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.\n\nA valid nested list is any list which can be created from a list with one item \"1\" by applying some operations. Each operation inserts a new item into the list, \\textbf{on a new line}, just after one of existing items $a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\,\\cdots\\, \\,.\\,a_k$ and can be one of two types:\n\n- Add an item $a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\cdots \\,.\\, a_k \\,.\\, 1$ (starting a list of a deeper level), or\n- Add an item $a_1 \\,.\\, a_2 \\,.\\, a_3 \\,.\\, \\cdots \\,.\\, (a_k + 1)$ (continuing the current level).\n\nOperation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the \"Notes\" section.When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the \"Ctrl-S\" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.\n\nWilliam wants you to help him restore a fitting original nested list.",
    "tutorial": "Let's maintain the current depth of the list in a stack. Initially the stack is empty. For each new $a_i$ there are two options: $a_i=1$. In this case we just add the given number to the end of the stack and it will point to a new subitem in the list. $a_i > 1$. In this case we need to find the subitem, the last number of which will be one less than $a_i$. To do this we will remove the last elements from a stack until we find this number. After this at the end of each iteration we will print the resulting stack as a new item in the list. Note that due to outputting the whole list the complexity will be quadratic. Final complexity: $O(n^2)$.",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1523",
    "index": "D",
    "title": "Love-Hate",
    "statement": "William is hosting a party for $n$ of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others.\n\nFor each William's friend $i$ it is known whether he likes currency $j$. There are $m$ currencies in total. It is also known that a trader may not like more than $p$ currencies.\n\nBecause friends need to have some common topic for discussions they need to find the largest by cardinality (possibly empty) subset of currencies, such that there are at least $\\lceil \\frac{n}{2} \\rceil$ friends (rounded up) who like each currency in this subset.",
    "tutorial": "Notice that the final answer will be a submask of one of $\\lceil \\frac{n}{2} \\rceil$ friends. Knowing this, random generation may be used to pick a random mask. If we check a randomly-generated index 50 times then the probability of not hitting a single index of a friend from the required group is $(\\frac{1}{2})^{50}$. This probability is 1125899906 times smaller than the probability of the contestant being hit by a falling meteorite, i.e. insignificant. Now that we have some basis mask $mask$ we can calculate the maximal answer for it. To do this let's \"compress\" each mask for each friend to a size no larger than $p$ by only keeping those true bits which are also true in $mask$. Now for each mask $s$ of length $p$ we can calculate $cnd_{s}$ which is the number of friends that like this mask. For each mask $cnt_{s}$ is the sum of all $cnt_{msk}$ such that s is a submask of $msk$. We can brute force all submasks in $O(3^p)$ by using an algorithm found $\\href{https://cp-algorithms.com/algebra/all-submasks.html}{here}$. Now all we have to do is to pick the $best$ mask for which $\\lceil \\frac{n}{2} \\rceil \\le cnt_{best}$ and which has the largest number of true bits in its uncompressed state. Final complexity: $O(iters \\cdot p \\cdot (2^p + n))$ or $O(iters \\cdot (3^p + n \\cdot p))$, depending on the implementation.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1523",
    "index": "E",
    "title": "Crypto Lights",
    "statement": "To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of $n$ lights arranged in a row. The device functions in the following way:\n\nInitially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distribution, picks a light that is turned off and turns it on, telling William which cryptocurrency he should invest in. After this iteration if any $k$ consecutive lights contain more than one turned on light, then the device finishes working.\n\nWilliam doesn't like uncertainty, so he wants you to calculate the expected value of the number of lights that are turned on in the device after it finishes working.",
    "tutorial": "Let's consider all states of the device where $p$ lights are turned on, and when at the current moment the algorithm has not yet finished working. We will be checking all values for $p$ from 1 to $n$. Notice that for a state where $p$ lights are turned on the probability of getting to that state is $\\frac{p!}{n \\cdot (n - 1) \\cdot (n - 2) \\dots (n - p - 1)}$. Now for a new value of $p$ we need to calculate the number of fitting states. Without the condition about having a distance of $k$ between the lights this number would be equal to the number of ways to split the lights into $p$ groups, which is $C(n-1, p-1)$. Next we can notice that each group must also contain $k-1$ elements to provide the necessary distance. Then the number of \"free\" cells necessary to select an arrangement of groups will be $n - (k - 1) \\cdot (p - 1)$. Then the final quantity of arrangements will be $C(n - (k - 1) \\cdot (p - 1), p - 1)$. The final sum of these quantities, multiplied by the probability of getting each one will be the answer.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1523",
    "index": "F",
    "title": "Favorite Game",
    "statement": "After William is done with work for the day, he enjoys playing his favorite video game.\n\nThe game happens in a 2D world, starting at turn $0$. William can pick any cell in the game world and spawn in it. Then, each turn, William may remain at his current location or move from the current location (x, y) to one of the following locations: (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1).\n\nTo accelerate movement the game has $n$ fast travel towers. $i$-th tower is located at location ($xa_i, ya_i$). To be able to instantly travel to the tower from any location in the game world it must first be activated. Activation of tower $i$ happens at the moment when the player is in cell ($xa_i, ya_i$) after this the tower remains active throughout the entire game.\n\nWilliam also knows that the game has $m$ quests. $i$-th quest can be completed instantly by being at location ($xb_i, yb_i$) on turn $t_i$.\n\nWilliam wants to find out the maximal number of quests he will be able to complete by optimally traversing the game world.",
    "tutorial": "For convenience we will sort quests by time. Let's make two DP: $F(mask, done_q)$ - minimum amount of time it takes to visit the set of $mask$ towers and complete $done_q$ quests. William is in one of the towers. $G(mask, q)$ - maximum number of quests that William can complete if he visited a set of $mask$ towers, and the last completed quest is quest number $q$. It is assumed that the current time for this state is equal to $t_q$ and William is at the coordinate $(xb_q, yb_q)$. DP transitions will be as follows: Transition describing a visit to the new tower $tower_{new}$, assumed that William was in the tower before: $F(mask, done_q) + distance_{tower}(mask, tower_{new}) \\underset{minimize}{\\rightarrow} F(mask \\cup tower_{new}, done_q)$, $tower_{new} \\notin mask$, where $distance_{tower}(mask, tower_{new})$ - minimum distance among all towers from the set $mask$ to the tower $tower_{new}$. Transition describing a visit to a new quest, assumed that William was in the tower before: $(done_q + 1) \\underset{minimize}{\\rightarrow} G(mask, q)$, only if $F(mask, done_q) + distance_{quest}(mask, q) \\leq t_q$, where $distance_{quest}(mask, q)$ - minimum distance among all towers from the set $mask$ to the quest $q$. Transition describing visiting a new quest immediately after the old one, without visiting new towers: $G(mask, q) + 1 \\underset{minimize}{\\rightarrow} G(mask, q_{new})$, only if $t_q + min(distance(q, q_{new}), distance_{quest}(mask, q_{new})) \\leq t_{q_{new}}$, where $distance(q, q_{new})$ - distance between two quests (without instant travel), $min(distance(q, q_{new}), distance_{quest}(mask, q_{new}))$ - choosing the optimal route: either directly to the quest, or through the tower. Transition describing a visit to a new tower, immediately after William visited quest number $q$: $t_q + min(distance(q, tower_{new}), distance_{tower}(mask, tower_{new}) \\underset{minimize}{\\rightarrow} F(mask \\cup tower_{new}, G(mask, q))$, $tower_{new} \\notin mask$, where $distance(q, tower_{new})$ - distance from quest number $q$ to tower number $tower_{new}$, $distance_{tower}(mask, tower_{new})$ - minimum distance from one of the towers from the set $mask$ to the tower $tower_{new}$. Initial states will be: $G(0, q) = 1$, for each quest $q$ - William can choose any starting coordinate. Therefore, he can choose to start at the coordinate with the quest and wait for it. All other states initialized as $G = -\\infty$. $F(\\{tower\\}, 0) = 0$, for each tower $tower$ - William can choose any starting coordinate. Therefore, he can choose the coordinate of the tower and be in it at time $0$. All other states initialized as $F = \\infty$. Answer: The answer is the maximum value among all $G(mask, q)$. Time complexity: There are $O(2^N \\cdot M)$ states in total. From each state there are $O(N + M)$ transitions. Hence the time complexity is $O(2^N \\cdot M \\cdot (N + M))$.",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1523",
    "index": "G",
    "title": "Try Booking",
    "statement": "William owns a flat in central London. He decided to rent his flat out for the next $n$ days to earn some money.\n\nSince his flat is in the center of the city, he instantly got $m$ offers in the form $(l_i, r_i)$, which means that someone wants to book the flat from day $l_i$ until day $r_i$ inclusive. To avoid spending a lot of time figuring out whether it's profitable for him to accept an offer, William decided to develop an algorithm. The algorithm processes all offers as they arrive and will only accept offer $i$ if the following two conditions are satisfied:\n\n- $r_i - l_i + 1 \\ge x$.\n- None of the days between $l_i$ and $r_i$ are occupied by a previously accepted offer\n\nWilliam isn't sure what value $x$ should have and he asks you for help. For all $x$ from $1$ to $n$ he wants you to calculate the total number of days for which the flat would be occupied if the corresponding value will be assigned to $x$.",
    "tutorial": "Note that if you think of the answer as the number accepted offers for rent, the sum of the answers in the worst case will be no more than $\\frac{n}{n}+\\frac{n}{n - 1}+\\ldots+\\frac{n}{1}$. This value can be estimated in $n \\cdot log (n)$. So for each $i$ we can try to learn how to process only those offers that are actually included in the answer for this $i$. Let's learn how to solve the problem recursively for a fixed $i$ and assume that all segments have a length of at least $i$. The recursion will contain two parameters $l$ and $r$ - a continuous segment of days on which all days are still free. Now, if we learn how to find an offer with a minimum $id$ for the segment $l$ and $r$ such that $l \\le l_{id} \\le r_{id} \\le r$, then we can solve our problem. We will only need to recursively find the answer for $l..l_{id}-1$ and $r_{id}+1..r$. To find the minimum $id$ , you can use a 2D data structure that supports the following queries: Get: Minimum on the prefix matrix (one of the corners of the submatrix lies in the cell $(1, 1)$). The minimum can be found on the prefix matrix because we are dealing with segments for which the condition $l \\le r$is is satisfied. Update: Updates the value in the cell $(x, y)$ by a strictly smaller number than it was there before. In the author's solution such a data structure was a 2D segments tree. We can iterate $i$ from $n$ to $1$ so that we only need to add new segments. Total complexity $O (n \\cdot log (n)^3 + m \\cdot log(n)^2)$.",
    "tags": [
      "data structures",
      "divide and conquer"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1523",
    "index": "H",
    "title": "Hopping Around the Array ",
    "statement": "William really wants to get a pet. Since his childhood he dreamt about getting a pet grasshopper. William is being very responsible about choosing his pet, so he wants to set up a trial for the grasshopper!\n\nThe trial takes place on an array $a$ of length $n$, which defines lengths of hops for each of $n$ cells. A grasshopper can hop around the sells according to the following rule: from a cell with index $i$ it can jump to any cell with indices from $i$ to $i+a_i$ inclusive.\n\nLet's call the $k$-grasshopper value of some array the smallest number of hops it would take a grasshopper to hop from the first cell to the last, but before starting you can select no more than $k$ cells and remove them from the array. When a cell is removed all other cells are renumbered but the values of $a_i$ for each cell remains the same. \\textbf{During this the first and the last cells may not be removed.}\n\nIt is required to process $q$ queries of the following format: you are given three numbers $l$, $r$, $k$. You are required to find the $k$-grasshopper value for an array, which is a subarray of the array $a$ with elements from $l$ to $r$ inclusive.",
    "tutorial": "Let's look into all jumps in the optimal answer except the last one with $k = 0$. Thereafter, from the position $i$ it is most effective to jump at such position $best$ that: $i \\le best \\le i+a_i$ and $a_{best} + best$ is the maximal possible. For each $i$ we can use a segment tree for maximum to find that optimal $best$. Let's also notice that if we want to jump from position $i$ having done $x$ removals of cells which indices are from $i+1$ to $a_i+i$, then we want to end up in a cell $a_i+i+x$, because we can do fewer removals otherwise. These observations are sufficient for us to use the idea of dynamic programming. Let $dp[t][i][k]$ store the maximal pair $(a_j + j, j)$ in which we can end up jumping from position $i$, having performed $2^t$ jumps and removed not greater than $k$ cells. With $t=0$ we can initialize the dynamic with optimal $best$. Now we will iterate over $t$, $i$ and $k$ in increasing order and see how to recalculate the dynamic. Let's iterate over $k1$ - the number of removals for the first $2^{t-1}$ jumps. Then, using the value $dp[t-1][i][k1]$ we know in which position we stopped. Now we need to perform $2^{t-1}$ jumps from that position having done not greater than $k-k1$ removals. Additionally, let's make another dynamic $imax[t][i][k]$ - stores such maximal position of initial array in which we can end up jumping from position $i$, having performed $2^t$ jumps and removed not greater than $k$ cells. Just like for the previous dynamic we can initialize it using $best$, and then similarly recalculate the value of the dynamic, but using two dynamics this time - $imax$ and $dp$. It is noteworthy that both dynamics need it to be supposed that when we start in element $i$ we do not remove it. Let's see how we can answer the query using the calculated dynamics. To begin with, let's consider particular cases. If $l=r$, then the answer is equal to $0$. If $a_l + l + k \\ge r$, then the answer is equal to $1$. Farther on, let's make one more dynamic $now_j$, in which we will maintain three numbers $(cnt, a_i + i, i)$. With that the first number is the number of jumps (we minimize it), two following numbers declare our current position $i$, and we maximize these two numbers as a pair $(a_i + i, i)$. Using that dynamic we wish to end up in the last but one cell of the optimal way, having removed not greater than $j$ cells. Initially, the values of dynamic are equal to $(0, a_l + l, l)$. Let's iterate over $t$ in decreasing order (which is to say, we iterate over the $2^t$ jumps). Let's create a dynamic $go$, which we are going to recalculate on the current step, and then make $now=go$ (in other words, we recalculate the dynamic $now$). Let's iterate over $k1$ - the number of removals during the preceding steps and $k2$ - the number of removals we are going to do on the current step. Using the value $now_{k1}$ we know in which position we stopped, and with dynamic $imax$ we can check if we cannot overjump $r$ (or end up in it) having performed $2^t$ jumps. If we cannot overjump $r$, then we will try to update the value $go_{k1+k2}$, otherwise, it's not profitable to perform the jump and thus let's update $go_{k1}$. As a result, we have the calculated dynamic $now_j$. Let's iterate over it and find $j$-s such that we can jump to $r$ with one jump and take the minimal answer over these $j$-s (don't forget to add $1$, since we jumped to the last by one cell in the dynamic). We calculate the dynamics in $O(n \\cdot k^2 \\cdot log(n))$, answer the query in $O(k^2 \\cdot log(n))$, thus the solution is in $O((n + q) \\cdot k^2 \\cdot log(n))$.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1525",
    "index": "A",
    "title": "Potion-making",
    "statement": "You have an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly $k\\ \\%$ magic essence and $(100 - k)\\ \\%$ water.\n\nIn one step, you can pour either one liter of magic essence or one liter of water into the cauldron. What is the minimum number of steps to brew a potion? You don't care about the total volume of the potion, only about the ratio between magic essence and water in it.\n\nA small reminder: if you pour $e$ liters of essence and $w$ liters of water ($e + w > 0$) into the cauldron, then it contains $\\frac{e}{e + w} \\cdot 100\\ \\%$ (without rounding) magic essence and $\\frac{w}{e + w} \\cdot 100\\ \\%$ water.",
    "tutorial": "Since you need $e$ liters of essence to be exactly $k\\ \\%$ of potion then we can write an equality: $\\frac{e}{e + w} = \\frac{k}{100}$ or $k = x \\cdot e$ and $100 = x \\cdot (e + w)$ for some integer $x$. Since we need to minimize $e + w$ and $x(e + w) = 100$, then we should maximize $x$, but both $k$ and $100$ should be divisible by $x$. In other words, taking $x$ as Greatest Common Divisor of $k$ and $100$ is optimal. As a result $e + w = \\frac{100}{x} = \\frac{100}{\\gcd(k, 100)}$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tint k; cin >> k;\n\t\tcout << 100 / gcd(100, k) << endl;\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1525",
    "index": "B",
    "title": "Permutation Sort",
    "statement": "You are given a permutation $a$ consisting of $n$ numbers $1$, $2$, ..., $n$ (a permutation is an array in which each element from $1$ to $n$ occurs exactly once).\n\nYou can perform the following operation: choose some subarray (contiguous subsegment) of $a$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.\n\nFor example, if $a = [2, 1, 4, 5, 3]$ and we want to apply the operation to the subarray $a[2, 4]$ (the subarray containing all elements from the $2$-nd to the $4$-th), then after the operation, the array can become $a = [2, 5, 1, 4, 3]$ or, for example, $a = [2, 1, 5, 4, 3]$.\n\nYour task is to calculate the minimum number of operations described above to sort the permutation $a$ in ascending order.",
    "tutorial": "To solve the problem, it is enough to consider several cases: if the array is already sorted, the answer is $0$; if $a[1] = 1$ (or $a[n] = n$), then you can sort the array in one operation by selecting the subarray $[1, n-1]$ (or $[2, n]$); if $a[1] = n$ and $a[n] = 1$, you can perform the sequence of operations $[1, n-1]$, $[2, n]$ and $[1, n-1]$ and sort the array on each of them (you can't do it faster since you can't move both $n$ to position $n$ and $1$ to position $1$ in only $2$ operations); otherwise, the array can be sorted in $2$ operations.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  scanf(\"%d\", &t);\n  while (t--) {\n    int n;\n    scanf(\"%d\", &n);\n    vector<int> a(n);\n    for (int &x : a) scanf(\"%d\", &x);\n    int ans = 2;\n    if (is_sorted(a.begin(), a.end()))\n      ans = 0;\n    else if (a[0] == 1 || a[n - 1] == n)\n      ans = 1;\n    else if (a[0] == n && a[n - 1] == 1)\n      ans = 3;\n    printf(\"%d\\n\", ans);\n  }\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1525",
    "index": "C",
    "title": "Robot Collisions",
    "statement": "There are $n$ robots driving along an OX axis. There are also two walls: one is at coordinate $0$ and one is at coordinate $m$.\n\nThe $i$-th robot starts at an integer coordinate $x_i~(0 < x_i < m)$ and moves either left (towards the $0$) or right with the speed of $1$ unit per second. No two robots start at the same coordinate.\n\nWhenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed.\n\nWhenever several robots meet at the same \\textbf{integer} coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens.\n\nFor each robot find out if it ever explodes and print the time of explosion if it happens and $-1$ otherwise.",
    "tutorial": "Notice that the robots that start at even coordinates can never collide with the robots that start at odd coordinates. You can see that if a robot starts at an even coordinate, it'll be at an even coordinate on an even second and at an odd coordinate on an odd second. Thus, we'll solve the even and the odd cases separately. Sort the robots by their starting coordinate. Apparently, that step was an inconvenience for some of you. There is a common trick that can help you to implement that. Create a separate array of integer indices $1, 2, \\dots, n$ and sort them with a comparator that looks up the value by indices provided to tell the order. This gives you the order of elements and doesn't require you to modify the original data in any way. Consider the task without reflections of the wall. Take a look at the first robot. If it goes to the left, then nothing ever happens to it. Otherwise, remember that it goes to the right. Look at the next one. If it goes to the left, then it can collide with the first one if that went to the right. Otherwise, remember that it also goes to the right. Now for the third one. If this one goes to the left, who does it collide with? Obviously, the rightmost alive robot that goes to the right. So the idea is to keep a stack of the alive robots. If a robot goes to the left, then check if the stack is empty. If it isn't, then the top of the stack robot is the one who will collide with it. Pop it from the stack, since it explodes. If a robot goes to the right, simply push it to the stack. The time of the collision is just the distance between the robots divided by $2$. If there are robots left in the stack after every robot is processed, then they all go to the right together, so they never collide. What changes when the reflections are introduced? Almost nothing, actually. Well, now if the stack is empty and a robot goes to the left, then it behaves as a one going to the right. You can reflect the part of the way from its start to the wall. Just say that instead of starting at some $x$ going to the left, it starts at $-x$ going to the right. Since there's no one alive to the left of him initially, that will change nothing. That $-x$ should be used for computing the collision time. However, the final robots in the stack also act differently. First, the top of the stack robots reflects off the wall and collides with the second on the stack one. Then the third and the fourth and so on. So you can pop them in pairs until $0$ or $1$ are left. The coordinate reflection trick can be used here as well. Imagine that the top of the stack starts at $m + (m - x)$ and goes to the left instead of starting in $x$ going to the right. For the same reason it changes nothing. Overall complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct bot{\n\tint x, d;\n};\n\nint main() {\n\tint t;\n\tcin >> t;\n\tforn(_, t){\n\t\tint n, m;\n\t\tscanf(\"%d%d\", &n, &m);\n\t\tvector<bot> a(n);\n\t\tforn(i, n) scanf(\"%d\", &a[i].x);\n\t\tforn(i, n){\n\t\t\tchar c;\n\t\t\tscanf(\" %c\", &c);\n\t\t\ta[i].d = c == 'L' ? -1 : 1;\n\t\t}\n\t\tvector<int> ord(n);\n\t\tiota(ord.begin(), ord.end(), 0);\n\t\tsort(ord.begin(), ord.end(), [&a](int x, int y){\n\t\t\treturn a[x].x < a[y].x;\n\t\t});\n\t\tvector<int> ans(n, -1);\n\t\tvector<vector<int>> par(2);\n\t\tfor (int i : ord){\n\t\t\tint p = a[i].x % 2;\n\t\t\tif (a[i].d == -1){\n\t\t\t\tif (par[p].empty())\n\t\t\t\t\tpar[p].push_back(i);\n\t\t\t\telse{\n\t\t\t\t\tint j = par[p].back();\n\t\t\t\t\tpar[p].pop_back();\n\t\t\t\t\tans[i] = ans[j] = (a[i].x - (a[j].d == 1 ? a[j].x : -a[j].x)) / 2;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tpar[p].push_back(i);\n\t\t\t}\n\t\t}\n\t\tforn(p, 2){\n\t\t\twhile (int(par[p].size()) > 1){\n\t\t\t\tint i = par[p].back();\n\t\t\t\tpar[p].pop_back();\n\t\t\t\tint j = par[p].back();\n\t\t\t\tpar[p].pop_back();\n\t\t\t\tans[i] = ans[j] = (2 * m - a[i].x - (a[j].d == 1 ? a[j].x : -a[j].x)) / 2;\n\t\t\t}\n\t\t}\n\t\tforn(i, n){\n\t\t\tprintf(\"%d \", ans[i]);\n\t\t}\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1525",
    "index": "D",
    "title": "Armchairs",
    "statement": "There are $n$ armchairs, numbered from $1$ to $n$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $\\frac{n}{2}$.\n\nFor some reason, you would like to tell people to move from their armchairs to some other ones. If the $i$-th armchair is occupied by someone and the $j$-th armchair is not, you can tell the person sitting in the $i$-th armchair to move to the $j$-th armchair. The time it takes a person to move from the $i$-th armchair to the $j$-th one is $|i - j|$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.\n\nYou want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?",
    "tutorial": "Let's say that the starting position of people are $x_1, x_2, \\dots, x_k$ (in sorted order) and ending positions of people are $y_1, y_2, \\dots, y_k$ (also in sorted order). It's always optimal to match these starting and ending positions in sorted order: the leftmost starting position is matched with the leftmost ending, the second starting position is matched with the second ending, and so on. To prove it, suppose that position $X_1$ is matched with $Y_2$, position $X_2$ is matched with $Y_1$, $X_1 \\le X_2$ and $Y_1 \\le Y_2$. If both persons go to the left or to the right, it means that either $X_1 \\le X_2 \\le Y_1 \\le Y_2$ or $Y_1 \\le Y_2 \\le X_1 \\le X_2$, so nothing changes if we swap the matched positions. If, instead, the person that goes from $X_1$ to $Y_2$ goes to the right, and the person that goes from $X_2$ to $Y_1$ goes to the left, the segment $[\\max(X_1, Y_1), \\min(X_2, Y_2)]$ belongs to both paths, and swapping the matched pairs removes this segment from both paths (and decreases the total time). So, if the order of starting positions is sorted and the order of ending positions is sorted, these positions should be matched exactly in those order. Using this fact, we can implement the following dynamic programming: let $dp_{i, j}$ be the minimum time if we considered $i$ first positions and picked $j$ of them as the ending ones. Transitions are the following: we either take the current position as the ending one (if it's not a starting one), match it with the $j$-th starting position and go to $dp_{i+1, j+1}$, or we skip the current position and go to $dp_{i+1,j}$. It works in $O(n^2)$ since it has up to $O(n^2)$ states and just up to $2$ transitions from each state.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int INF = int(1e9);\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor(int i = 0; i < n; i++)\n\t\tcin >> a[i];\n\tvector<int> pos;\n\tfor(int i = 0; i < n; i++)\n\t\tif(a[i] == 1)\n\t\t\tpos.push_back(i);\n\tint k = pos.size();\n\tvector<vector<int>> dp(n + 1, vector<int>(k + 1, INF));\n\tdp[0][0] = 0;\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j <= k; j++)\n\t\t{\n\t\t \tif(dp[i][j] == INF) continue;\n\t\t \tdp[i + 1][j] = min(dp[i + 1][j], dp[i][j]);\n\t\t \tif(j < k && a[i] == 0)\n\t\t \t\tdp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + abs(pos[j] - i));\n\t\t}\n\tcout << dp[n][k] << endl;\n}\n",
    "tags": [
      "dp",
      "flows",
      "graph matchings",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1525",
    "index": "E",
    "title": "Assimilation IV",
    "statement": "Monocarp is playing a game \"Assimilation IV\". In this game he manages a great empire: builds cities and conquers new lands.\n\nMonocarp's empire has $n$ cities. In order to conquer new lands he plans to build \\textbf{one Monument in each city}. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.\n\nMonocarp has $m$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $1$ to this city. Next turn, the Monument controls all points at distance at most $2$, the turn after — at distance at most $3$, and so on. Monocarp will build $n$ Monuments in $n$ turns and his empire will conquer all points that are controlled by at least one Monument.\n\nMonocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $m$ of them) he will conquer at the end of turn number $n$. Help him to calculate the expected number of conquered points!",
    "tutorial": "Let $I(j)$ be the indicator function equal to $1$ if the $j$-th point is controlled by any city and $0$ otherwise. Then the expected number of controlled points $ans$ can be written as $E(\\sum\\limits_{j=1}^{m}{I(j)}) = \\sum\\limits_{j=1}^{m}{E(I(j))}$ (by linearity of expected value). The expected value of the indicator function is equal to the probability of this function equal to $1$ ($E(I(j)) = P[I(j) = 1]$). In other words, for each point we need to calculate the probability of this point being controlled by any city. Let's instead calculate the probability of point $j$ not being controlled by any city. Suppose, the distance between point $j$ and some city $i$ is equal to $x$. If we build a Monument in city $i$ at step $< n + 1 - x$ (zero indexed) then the point will be controlled by city $i$. But building the Monument at any step greater or equal than $n + 1 - x$ is fine. Let's for each turn $k \\in [0, n)$ calculate the number of cities that you can build Monument in starting this turn as $cnt[k]$. Our task is to calculate the number of permutations that are consistent with array $cnt$. At first turn, we can choose one of $cnt[0]$ cities, at second turn we have $cnt[0] + cnt[1] - 1$ choices, at third step - $cnt[0] + cnt[1] + cnt[2] - 2$ choices, and so on. Using this idea, it's not hard to calculate the number of good permutations and then the initial probablity $P[I(j) = 1]$ $\\equiv$ $1 - \\text{good_permutations} \\cdot (n!)^{-1} \\pmod{998244353}$. The expected value $ans \\equiv \\sum\\limits_{j=1}^{m}{P[I(j) = 1]} \\pmod{998244353}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int MOD = 998244353;\n\nint norm(int a) {\n\twhile (a >= MOD)\n\t\ta -= MOD;\n\twhile (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\nint mul(int a, int b) {\n\treturn int(a * 1ll * b % MOD);\n}\nint binPow(int a, int k) {\n\tint ans = 1;\n\twhile (k > 0) {\n\t\tif (k & 1)\n\t\t\tans = mul(ans, a);\n\t\ta = mul(a, a);\n\t\tk >>= 1;\n\t}\n\treturn ans;\n}\nint inv(int a) {\n\treturn binPow(a, MOD - 2);\n}\n\nvector< vector<int> > d;\nint n, m;\n\ninline bool read() {\n\tif(!(cin >> n >> m))\n\t\treturn false;\n\td.resize(n, vector<int>(m));\n\tfore (i, 0, n) fore (j, 0, m)\n\t\tcin >> d[i][j];\n\treturn true;\n}\n\ninline void solve() {\n\tint invFact = 1;\n\tfore (i, 1, n + 1)\n\t\tinvFact = mul(invFact, i);\n\tinvFact = inv(invFact);\n\t\n\tint E = 0;\n\tfore (j, 0, m) {\n\t\tvector<int> cnt(n + 1, 0);\n\t\tfore (i, 0, n)\n\t\t\tcnt[n + 1 - d[i][j]]++;\n\t\t\n\t\tvector<int> d(n + 1, 0);\n\t\td[0] = 1;\n\t\tint rem = 0;\n\t\tfore (i, 0, n) {\n\t\t\trem += cnt[i];\n\t\t\td[i + 1] = norm(d[i + 1] + mul(d[i], rem));\n\t\t\trem = max(0, rem - 1);\n\t\t}\n//\t\tcerr << d[n] << \" - \" << norm(1 - mul(d[n], invFact)) << endl;\n\t\tE = norm(E + 1 - mul(d[n], invFact));\n\t}\n\tcout << E << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1525",
    "index": "F",
    "title": "Goblins And Gnomes",
    "statement": "Monocarp plays a computer game called \"Goblins and Gnomes\". In this game, he manages a large underground city of gnomes and defends it from hordes of goblins.\n\nThe city consists of $n$ halls and $m$ one-directional tunnels connecting them. The structure of tunnels has the following property: if a goblin leaves any hall, he cannot return to that hall.\n\nThe city will be attacked by $k$ waves of goblins; during the $i$-th wave, $i$ goblins attack the city. Monocarp's goal is to pass all $k$ waves.\n\nThe $i$-th wave goes as follows: firstly, $i$ goblins appear in some halls of the city and pillage them; \\textbf{at most one goblin appears in each hall}. Then, goblins start moving along the tunnels, pillaging all the halls in their path.\n\nGoblins are very greedy and cunning, so they choose their paths so that no two goblins pass through the same hall. Among all possible attack plans, they choose a plan which allows them to \\textbf{pillage the maximum number of halls}. After goblins are done pillaging, they leave the city.\n\nIf all halls are pillaged during the wave — Monocarp loses the game. Otherwise, the city is restored. If some hall is pillaged during a wave, goblins are still interested in pillaging it during the next waves.\n\nBefore each wave, Monocarp can spend some time preparing to it. Monocarp doesn't have any strict time limits on his preparations (he decides when to call each wave by himself), but the longer he prepares for a wave, the fewer points he gets for passing it. If Monocarp prepares for the $i$-th wave for $t_i$ minutes, then he gets $\\max(0, x_i - t_i \\cdot y_i)$ points for passing it (obviously, if he doesn't lose in the process).\n\nWhile preparing for a wave, Monocarp can block tunnels. He can spend one minute to \\textbf{either block all tunnels leading from some hall or block all tunnels leading to some hall}. If Monocarp blocks a tunnel while preparing for a wave, it stays blocked during the next waves as well.\n\nHelp Monocarp to defend against all $k$ waves of goblins and get the maximum possible amount of points!",
    "tutorial": "First of all, let's try to solve the following problem: given a DAG, cover its vertices with the minimum number of vertex-disjoint paths. Solving this problem allows us to calculate the number of goblins that can pillage all of the halls when the tunnel network is fixed. This problem is a fairly classical one; since the number of vertices in each path is greater than the number of arcs in it exactly by $1$, we should take the maximum possible number of arcs into our paths. So we can reduce this problem to bipartite maximum matching - build a bipartite graph where each part consists of $n$ vertices, and for every directed arc $(x, y)$ in the original graph, connect the vertex $x$ of the left part to the vertex $y$ in the right part of the bipartite graph. The maximum matching in this graph allows us to pick the maximum number of arcs into the paths of the original problem (the matching ensures that each vertex has at most one chosen ingoing arc and at most one chosen outgoing arc, so the paths are vertex-disjoint). Okay, now we at least can check if the goblin wave can pillage all of the halls. Let's say that the minimum number of goblins required to pillage the original city is $c$. Obviously, in order to pass the $c$-th wave and waves after it, we have to increase this number. In one minute, Monocarp can block all of the tunnels leading to some hall or out of some hall - and in terms of our reduction to the bipartite matching problem, it means that we remove all edges connected to some vertex of the bipartite graph. Obviously, in one minute, we can increase $c$ by at most $1$, since $c$ is equal to the difference between $n$ and the maximum matching size. It turns out that it's always possible to choose a vertex that belongs to all maximum matchings in the bipartite graph (note that it doesn't work in non-bipartite graphs, but in our problem, it doesn't matter). For the proof of this fact, you can check the last paragraph of the editorial. So, each minute Monocarp prepares for a wave, he increases the maximum number of goblins he can repel by $1$. Now the solution splits into two much easier parts. The first part is finding a sequence in which Monocarp blocks the tunnels, so that each his action reduces the size of the maximum matching by $1$. Since the constraints are small, even a naive approach in $O(n^5)$ - always iterate on the vertex we try to remove from the graph and check that removing it is possible by running Kuhn's algorithm - is fast enough. The second part is to choose when Monocarp calls waves of goblins and when he prepares for them - this can be easily done with dynamic programming: let $dp_{i,j}$ be the maximum Monocarp's score if he has already passed $i$ waves, and the current size of the maximum matching is $j$. The most naive implementation of this dynamic programming runs in $O(n^3)$, so the whole solution works in $O(n^5)$. We can improve it to $O(n^3)$, though it is not needed under these constraints. Instead of finding the vertices to remove from the bipartite graph one-by-one, let's find all of them at once in $O(n^3)$. Recall that the size of maximum matching in a bipartite graph is equal to the size of its minimum vertex cover, and the minimum vertex cover can be reconstructed after finding the maximum matching. If we remove a vertex from the minimum vertex cover, the size of the minimum vertex cover of the remaining graph is reduced by $1$, so the size of the maximum matching is reduced by $1$ as well. It means that we can always choose to remove a vertex from the minimum vertex cover we found. By the way, it also proves that it's always possible to remove a vertex from a bipartite graph so the size of the maximum matching decreases by $1$ (obviously, if it's not $0$ already).",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int N = 543;\nconst long long INF = (long long)(1e18);\n\nstruct Matching\n{\n \tint n1, n2;\n \tvector<set<int>> g;\n \tvector<int> mt, used;\n\n \tvoid init()\n \t{\n \t \tmt = vector<int>(n2, -1);\n \t}\n\n \tint kuhn(int x)\n \t{\n \t \tif(used[x] == 1) return 0;\n \t \tused[x] = 1;\n \t \tfor(auto y : g[x])\n \t \t\tif(mt[y] == -1 || kuhn(mt[y]) == 1)\n \t \t\t{\n \t \t\t \tmt[y] = x;\n \t \t\t \treturn 1;\n \t \t\t}\n \t \treturn 0;\n \t}\n\n \tint calc()\n \t{\n \t \tinit();\n \t \tint sum = 0;\n \t \tfor(int i = 0; i < n1; i++)\n \t \t{\n \t \t\tused = vector<int>(n1, 0);\n \t \t\tsum += kuhn(i);\n \t \t}\n \t \treturn sum;\n \t}\n\n \tvoid remove_vertex(int v, bool right)\n \t{\n \t \tif(right)\n \t \t{\n \t \t\tfor(int i = 0; i < n1; i++)\n \t \t\t\tg[i].erase(v);\n \t \t}\n \t \telse\n \t \t\tg[v].clear();\n \t}\n\n \tvoid add_edge(int x, int y)\n \t{\n \t\tg[x].insert(y);\n \t}\n\n \tMatching() {};\n \tMatching(int n1, int n2) : n1(n1), n2(n2)\n \t{\n \t\tg.resize(n1);\n \t};\n};\n\nint n, m, k;\nlong long dp[N][N];\nint p[N][N];\nvector<int> g[N];\nlong long x[N], y[N];\n\nint main()\n{\n\tcin >> n >> m >> k;\n\tfor(int i = 0; i < m; i++)\n\t{\n\t \tint u, v;\n\t \tcin >> u >> v;\n\t \t--u;\n\t \t--v;\n\t \tg[u].push_back(v);\n\t}\n\tfor(int i = 0; i < k; i++)\n\t\tcin >> x[i] >> y[i];\n\n\tMatching mt(n, n);\n\tfor(int i = 0; i < n; i++)\n\t\tfor(auto j : g[i])\n\t\t\tmt.add_edge(i, j);\n\tint cnt = mt.calc();\n\tint cur = cnt;\n\tvector<int> seq;\n\twhile(cur > 0)\n\t{\n\t\tint idx = 0;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t \tMatching mt2 = mt;\n\t\t \tmt2.remove_vertex(i, false);\n\t\t \tif(mt2.calc() < cur)\n\t\t \t\tidx = i + 1;\n\t\t \tmt2 = mt;\n\t\t \tmt2.remove_vertex(i, true);\n\t\t \tif(mt2.calc() < cur)\n\t\t \t\tidx = -(i + 1);\n\t\t}\n\t\tassert(idx != 0);\n\t\tseq.push_back(idx);\n\t\tmt.remove_vertex(abs(idx) - 1, idx < 0);\n\t\tcur--;\n\t}\t\n\treverse(seq.begin(), seq.end());\n\tfor(int i = 0; i <= k; i++)\n\t\tfor(int j = 0; j <= cnt; j++)\n\t\t\tdp[i][j] = -INF;\n\tdp[0][cnt] = 0;\n\tfor(int i = 0; i < k; i++)\n\t\tfor(int j = 0; j <= cnt; j++)\n\t\t{\n\t\t\tif(dp[i][j] == -INF) continue;\n\t\t\tfor(int z = 0; z <= j; z++)\n\t\t\t{\n\t\t\t\tif(i + 1 + z >= n) continue;\n\t\t\t \tint t = j - z;\n\t\t\t \tlong long add = max(0ll, x[i] - t * y[i]);\n\t\t\t \tif(dp[i + 1][z] < dp[i][j] + add)\n\t\t\t \t{\n\t\t\t \t \tdp[i + 1][z] = dp[i][j] + add;\n\t\t\t \t \tp[i + 1][z] = j;\n\t\t\t \t}\n\t\t\t}\n\t\t}\n\tcur = max_element(dp[k], dp[k] + cnt + 1) - dp[k];\n\tvector<int> res;\n\tfor(int i = k; i > 0; i--)\n\t{\n\t\tres.push_back(0);\n\t\tfor(int j = p[i][cur] - 1; j >= cur; j--)\n\t\t\tres.push_back(seq[j]);\n\t\tcur = p[i][cur];\t\n\t}\n\treverse(res.begin(), res.end());\n\tcout << res.size() << endl;\n\tfor(auto x : res) cout << x << \" \";\n\tcout << endl;\n}\n",
    "tags": [
      "brute force",
      "dp",
      "flows",
      "graph matchings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1526",
    "index": "A",
    "title": "Mean Inequality",
    "statement": "You are given an array $a$ of $2n$ \\textbf{distinct} integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its $2$ neighbours.\n\nMore formally, find an array $b$, such that:\n\n- $b$ is a permutation of $a$.\n- For every $i$ from $1$ to $2n$, $b_i \\neq \\frac{b_{i-1}+b_{i+1}}{2}$, where $b_0 = b_{2n}$ and $b_{2n+1} = b_1$.\n\nIt can be proved that under the constraints of this problem, such array $b$ always exists.",
    "tutorial": "Notice that the array size is even length. Usually in such problems, we would split the array into $2$ equal parts. Can you figure out what those $2$ parts are? We sort the array and split it into the big half and the small half. The main idea is that we can split the numbers into the two halves, the big half and small half, we can place the bigger half at the odd positions and the smaller half at the even positions. This works because the smallest big number is larger than the biggest small number. Hence, the mean of any two small numbers is smaller than any big number, and the mean of any two big numbers is bigger than any small number.",
    "code": "[(lambda n: (lambda arr : [print(f'{arr[i]} {arr[i+n]}', end = ' \\n'[i==n-1]) for i in range(n)])(sorted(list(map(int,input().split())))))(int(input())) for _ in range(int(input()))]",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1526",
    "index": "B",
    "title": "I Hate 1111",
    "statement": "You are given an integer $x$. Can you make $x$ by summing up some number of $11, 111, 1111, 11111, \\ldots$? (You can use any number among them any number of times).\n\nFor instance,\n\n- $33=11+11+11$\n- $144=111+11+11+11$",
    "tutorial": "Read the name of the problem ;) $1111=11 \\cdot 101$ All numbers other than $11$ and $111$ are useless. Notice that $1111=11 \\cdot 100+11$ and similarly $11111=111 \\cdot 100 + 11$. This implies that we can construct $1111$ and all bigger numbers using only $11$ and $111$. So it suffices to check whether we can construct $X$ from $11$ and $111$ only. Suppose $X=A \\cdot 11 + B \\cdot 111$, where $A,B \\geq 0$. Suppose $B=C \\cdot 11 + D$, where $D < 11$. Then $X=(A+C \\cdot 111) \\cdot 11 + D \\cdot 111$. So we can just brute force all $11$ value of $D$ to check whether $X$ can be made. Since $\\gcd(11,111)=1$, by the Chicken McNugget Theorem, all numbers greater than $1099$ can be written as a sum of $11$ and $111$. We can use brute force to find the answer to all values less than or equal to $1099$ and answer yes for all other numbers.",
    "code": "[(lambda n : print(\"YES\" if (n >= 111*(n%11)) else \"NO\"))(int(input())) for _ in range(int(input()))]",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1526",
    "index": "C2",
    "title": "Potions (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $n \\leq 200000$. You can make hacks only if both versions of the problem are solved.}\n\nThere are $n$ potions in a line, with potion $1$ on the far left and potion $n$ on the far right. Each potion will increase your health by $a_i$ when drunk. $a_i$ can be negative, meaning that potion will decrease will health.\n\nYou start with $0$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. \\textbf{You must ensure that your health is always non-negative}.\n\nWhat is the largest number of potions you can drink?",
    "tutorial": "Try dp! The dp states are position and number of potions drank. Speedup dp or use greedy for full solution. Let's consider a dynamic programming solution. Let $dp[i][k]$ be the maximum possible health achievable if we consider only the first $i$ potions, and $k$ is the total number of potions taken. The transition is as follows: $dp[i][k] = max(dp[i-1][k-1] + a_i, dp[i-1][k])$ if $dp[i-1][k-1] + a_i \\geq 0$, and just $dp[i-1][k]$ otherwise. The first term represents the case if we take potion $i$ and the second term is when we ignore potion $i$. This runs in $O(n^2)$ and passes the easy version. We iterate through the potions in non-decreasing order and drink the potion if we do not die. For convenience, we define $c_i=a_i+i \\cdot \\epsilon$, where $\\epsilon$ is a very small real number so that we can treat $c_i$ as distinct integers. We will show by exchange argument that our greedy is optimal. Let $S$ be the set of potions that is an optimal solution. Suppose $i<j$ and $c_i<c_j$. If $i \\in S$ and $j \\notin S$, then removing $i$ and adding $j$ into $S$ will still make $S$ a valid solution. Now, suppose that position $i$ is not drunk. We can assume that there are no $k$ ($k<i$) such that $c_k<c_i$ and $k$ is drunk by the previous assertion. Suppose we add $i$ into $S$. If we reach a position $j$ (we possibly die at $j$) where $c_j<c_i$, then we can remove $j$ from $S$ and add $i$ to $S$. Otherwise, our greedy will also not choose $i$, as it was not chosen when we only consider indexes $k$ such that $c_k<c_i$. Notice that we can arbitrarily define the way $\\epsilon$ is added, so basically we can process $a_i$ in any non-increasing fashion. Doing this naively is $O(n^2)$ as well. However, using a range add range max lazy propagation segment tree, we can check if a certain potion can be drunk without dying, and the solution runs in $O(n \\log n)$. We process the potions from left to right. At the same time, we maintain the list of potions we have taken so far. When processing potion $i$, if we can take $i$ without dying, then we take it. Otherwise, if the most negative potion we've taken is more negative than potion $i$, then we can swap out potion $i$ for that potion. To find the most negative potion we've taken, we can maintain the values of all potions in a minimum priority_queue. This runs in $O(nlogn)$ as well To prove that this works, let's consider best solution where we take exactly $k$ potions (best as in max total health). The solution involves taking the $k$ largest values in our priority queue. Then when considering a new potion, we should see whether swapping out the new potion for the $k$th largest potion will improve the answer. Since the priority queue is strictly decreasing, there will be a cutoff $K$, where for $k$ at most $K$, the answer is not affected, and for larger than $K$, we swap out the $k$th largest potion. It turns out this process is equivalent to inserting the new potion's value into the priority_queue. For those positions at most $K$, they are not affected. For the positions larger than $K$, the elements get pushed back one space, meaning that the smallest element is undrinked. This can also be seen as an efficient way to to transition from one layer of the $dp$ table to the next.",
    "code": "import heapq\nH = []\nn=int(input())\nfor i in list(map(int,input().split())):\n    tot = (tot+i if 'tot' in locals() or 'tot' in globals() else i)\n    tot -= ((heapq.heappush(H,i) if tot >= 0 else heapq.heappushpop(H,i)) or 0)\nprint(len(H))",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1526",
    "index": "D",
    "title": "Kill Anton",
    "statement": "After rejecting $10^{100}$ data structure problems, Errorgorn is very angry at Anton and decided to kill him.\n\nAnton's DNA can be represented as a string $a$ which only contains the characters \"ANTON\" (there are only $4$ distinct characters).\n\nErrorgorn can change Anton's DNA into string $b$ which must be a \\textbf{permutation} of $a$. However, Anton's body can defend against this attack. In $1$ second, his body can swap $2$ \\textbf{adjacent} characters of his DNA to transform it back to $a$. Anton's body is smart and will use the minimum number of moves.\n\nTo maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string $B$. Can you help him?",
    "tutorial": "The time it takes for Anton's body to revert the string is related to inversion number. We claim that in the optimal answer all characters of some type will appear consecutively. Consider the character at position $i$ in string $s$. We define $C_i$ as the position in which that character will be in string $t$. For $s=\\texttt{CAGCAA}$ and $t=\\texttt{AAGCAC}$, $C={4,1,3,6,2,5}$. Then the minimum number of moves to transformed $s$ to $t$ is given by the inversion index of $C$. Suppose we find a substring of $s$ where it is $\\texttt{XXAA...AA[A]XX...XX[A]AA...AAXX}$, where characters $\\texttt{X}$ can be either one of $\\texttt{TCG}$. The square brackets are just for clarity of explanation. We will show that it our solution will not be worse if we merge these $2$ contiguous segments of $\\texttt{A}$. Consider transforming the string into $\\texttt{XXAA...AAXX...XX[A][A]AA...AAXX}$ and $\\texttt{XXAA...AA[A][A]XX...XXAA...AAXX}$. Let the difference in the number of moves be $D_1$ and $D_2$ respectively. And let the index of $\\texttt{[A]}$s be $i$ and $j$ respectively. Then $D_1=\\sum\\limits_{k=i+1}^{j-1} \\sigma(C_k-C_i)$ and $D_2=\\sum\\limits_{k=i+1}^{j-1} \\sigma(C_j-C_k)$, where $\\sigma(x)=\\frac{x}{|x|}$, or rather $\\sigma$ is the sign function. I claim that $D_1+D_2 \\geq 0$. Suppose that $D_1+D_2<0$, then there exist $k$ such that $\\sigma(C_k-C_i)+\\sigma(C_j-C_k)<0$ which implies $C_k-C_i<0$ and $C_j-C_k<0$. However, this implies that $C_j<C_i$ which is clearly a contradiction. Since $D_1+D_2 \\geq 0$, either $D_1 \\geq 0$ or $D_2 \\geq 0$. WLOG, $D_1 \\geq 0$. This implies that we turn $s$ into $\\texttt{XXAA...AAXX...XX[A][A]AA...AAXX}$ without decreasing the number of moves to transform $s$ into $t$. Now, consider the rest of the $\\texttt{A}$ on the left segment of $\\texttt{A}$. We can move it too the right also. Recall that $D_1 + D_2 \\geq 0$. In this case, we know that $D_2 \\leq 0$ as it is the cost to move the left $\\texttt{[A]}$ back to its original position. So $D_1 \\geq 0$. Therefore, we have merged $2$ different segments of $A$ without decreasing the number of moves to transform $s$ into $t$. So, we can try all $24$ possible strings and check the number of moves Anton's body needs to transform each string. The time limit is relaxed enough for a $O(n \\log n)$ similar to 1430E - String Reversal. But there is a $O(n)$ solution, the number of moves Anton's body needs to transform each string is given by the number of inversions in the string. But since we know that we only care about strings that have all the same characters appear consecutively, we can just keep a count of the number of inversions for each pair of characters.",
    "code": "import itertools\n\nTC=int(input())\n\nm={\"A\":0,\"N\":1,\"O\":2,\"T\":3}\nst=\"ANOT\"\n\nfor _ in range(TC):\n\ts=input()\n\tarr=[]\n\t\n\tfor ch in s:\n\t\tarr.append(m[ch])\n\t\n\tcnt=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]\n\tcnt1=[0,0,0,0]\n\t\n\tfor i in arr:\n\t\tfor j in range(4):\n\t\t\tcnt[j][i]+=cnt1[j]\n\t\tcnt1[i]+=1\n\t\n\tval=-1\n\tbest=[]\n\t\n\tfor perm in itertools.permutations([0,1,2,3]):\n\t\tcurr=0\n\t\tfor i in range(4):\n\t\t\tfor j in range(i+1,4):\n\t\t\t\tcurr+=cnt[perm[j]][perm[i]]\t\n\t\t\n\t\tif (curr>val):\n\t\t\tval=curr\n\t\t\tbest=perm\n\t\t\t\n\t\n\tfor i in range(4):\n\t\tfor j in range(cnt1[best[i]]): print(st[best[i]],end=\"\")\n\t\n\tprint()",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "math",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1526",
    "index": "E",
    "title": "Oolimry and Suffix Array",
    "statement": "Once upon a time, Oolimry saw a suffix array. He wondered how many strings can produce this suffix array.\n\nMore formally, given a suffix array of length $n$ and having an alphabet size $k$, count the number of strings that produce such a suffix array.\n\nLet $s$ be a string of length $n$. Then the $i$-th suffix of $s$ is the substring $s[i \\ldots n-1]$. A suffix array is the array of integers that represent the starting indexes of all the suffixes of a given string, after the suffixes are sorted in the lexicographic order. For example, the suffix array of oolimry is $[3,2,4,1,0,5,6]$ as the array of sorted suffixes is $[imry,limry,mry,olimry,oolimry,ry,y]$.\n\nA string $x$ is lexicographically smaller than string $y$, if either $x$ is a prefix of $y$ (and $x\\neq y$), or there exists such $i$ that $x_i < y_i$, and for any $1\\leq j < i$ , $x_j = y_j$.",
    "tutorial": "Try to solve the problem of the minimal $K$ needed to make a string with such a suffix array. First, let's consider a simpler problem. Is it possible to make a string with a certain suffix array given an alphabet size $k$. Consider two adjacent suffixes in the suffix array \"xy\" and \"ab\" where $b$ and $y$ are some strings and $x$ and $a$ are some characters i.e. $x$ is the first character of that suffix and similarly for $a$. If $b$ and $y$ don't exist we consider them as \\$, i.e. smaller than everything. Also, \"xy\" comes before \"ab\". Observation: If the position of $b$ is less than the position of $y$ in the suffix array, $x$ must be less than $a$. Otherwise, $x$ must be less than or equal to $a$. This can be easily shown as \"xy\" must be lexicographically smaller than \"ab\". This is sufficient also. Thus we can iterate through the suffix array and check if $pos[arr[i]+1]>pos[arr[i+1]+1]$ where $arr$ is the suffix array and $pos$ is the position of the $i$th element in the suffix array. If this condition holds then the $arr[i]$ th character must be strictly less than the $arr[i+1]$ th character. Thus we can just count how many such pairs exist. If this count is larger than the alphabet size no such string is possible. Otherwise, such string exists. Note that special care must be taken when considering $arr[i]=n-1$ as $pos[n]$ may not be defined ($0$-indexed). After tackling the simpler question we move on to the full question of counting how many such strings are there. If we consider the string as an array and the order of the array as the order of the suffix array meaning that the $i$ th element of this array is the $arr[i]$ th element of the string. We have now transformed the question into \"Given that some elements must be greater than the previous elements while others can be equal. Count how many arrays are there such that the largest element is less than $k$\". Consider the difference array, some elements must be $\\geq 1$ while some can be $\\geq 0$. We add padding to the front and back of the array so as to account for the first value being non-zero and the last element being less than $k$. These two elements are both $\\geq 0$. Let $cnt$ be the number of elements that must be $\\geq 1$ in the difference array. Now, this becomes count how many arrays of $(n-1+2)=(n+1)$ non-negative elements sum to $k-cnt$. This can be solved using stars and bars so the final answer comes out to be $n+1+k-cnt \\choose n$ which can be found easily. Note that we define $\\binom{a}{b}=0$ when $a<b$. Final Complexity $O(n\\log MOD)$ or $O(n)$ depending on how you find the modular inverse. Btw $k$ was chosen to also be $\\leq 2\\times 10^5$ so as to hide the final complexity :)",
    "code": "MOD=998244353\n\nn,k=map(int,input().split())\narr=list(map(int,input().split()))\n\npos=[0]*(n+1)\n\nfor i in range(n):\n\tpos[arr[i]]=i\npos[n]=-1\n\ncnt=0\n\nfor i in range(n-1):\n\tif (pos[arr[i]+1]>pos[arr[i+1]+1]): cnt+=1\n\n#k-cnt+n-1 choose n\nnum,denom=1,1\n\nfor i in range(n):\n\tnum=num*(k-cnt+n-1-i)%MOD\n\tdenom=denom*(i+1)%MOD\n\nprint(num*pow(denom,MOD-2,MOD)%MOD)",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1526",
    "index": "F",
    "title": "Median Queries",
    "statement": "\\textbf{This is an interactive problem.}\n\nThere is a secret permutation $p$ ($1$-indexed) of numbers from $1$ to $n$. More formally, for $1 \\leq i \\leq n$, $1 \\leq p[i] \\leq n$ and for $1 \\leq i < j \\leq n$, $p[i] \\neq p[j]$. \\textbf{It is known that $p[1]<p[2]$}.\n\nIn $1$ query, you give $3$ \\textbf{distinct} integers $a,b,c$ ($1 \\leq a,b,c \\leq n$), and receive the \\textbf{median} of $\\{|p[a]-p[b]|,|p[b]-p[c]|,|p[a]-p[c]|\\}$.\n\nIn this case, the median is the $2$-nd element ($1$-indexed) of the sequence when sorted in non-decreasing order. The median of $\\{4,6,2\\}$ is $4$ and the median of $\\{0,123,33\\}$ is $33$.\n\nCan you find the secret permutation in not more than $2n+420$ queries?\n\n\\textbf{Note: the grader is not adaptive:} the permutation is fixed before any queries are made.",
    "tutorial": "Find elements $1$ and $2$ in $N+420$ queries. Find a pair $(a,b)$ such that $|p[b]-p[a]| \\leq \\frac{n}{3}-c$, where $c$ is some constant. The problem can be broken into $2$ main parts: Finding a pair $(a,b)$ such that $|p[a]-p[b]|$ is roughly less than a third. Finding elements $1$ and $2$ (actually we may find $N$ and $N-1$ but it is the same). Find the rest of the elements A convenient way to think about the queries, is that given $p[a]<p[b]<p[c]$, we will be returned $\\max(p[b]-p[a],p[c]-p[b])$. We will spend the first queries to find a tuple $(a,b,c)$ such that the return value of this query is at most $\\lfloor \\frac{n-4}{6} \\rfloor$. The easiest way to do this is by randomly choosing distinct $a$,$b$,$c$ and querying it. See proof 1 for the random analysis. But there is also a deterministic solution. Choose any $13$ elements from the array, and it is guaranteed that there exists a tuple in those $13$ elements such that the return value of the query is at most $\\lfloor \\frac{n-4}{6} \\rfloor$, see proof 2. To query all tuples in this sub-array of size $13$, it takes $286$ queries, which fits very comfortably under $420$. user14767553 conjectured that a sub-array of size $10$ works, however we are unable to prove it. You can try to hack his solution at 117685511. Among $a$, $b$, and $c$, we choose $a$ and $b$. The important idea here is that the gap between $a$ and $b$ is small, because we have found a tuple $(a,b,c)$ is less than or equal to $\\lfloor \\frac{n-4}{6} \\rfloor$, so $|p[a]-p[b]| \\leq 2 \\cdot \\lfloor \\frac{n-4}{6} \\rfloor \\leq \\lfloor \\frac{n-4}{3} \\rfloor$. Now, we query all tuples $(a,b,x)$ for all $x \\ne a$ and $x \\ne b$. Since the gap between $a$ and $b$ is small, we should be able to identify either $(1,2)$ or $(n,n-1)$. This is because either $p[a]-1 > p[b]-p[a]$ or $n-p[b] > p[b] - p[a]$ (WLOG assuming $p[b] > p[a]$), see proof 3. Therefore, the furthest $x$ will return the largest value when querying for $(a,b,x)$. (If there's ties choose anyone). Suppose we found element $1$, there are at most two possible candidates for element $2$, $y_1$ and $y_2$ (the other possible candidate will be either $n$ or $n-1$). We can use 2 queries to figure out which of them is element $2$. We can query $(1, y_1, a)$ and $(1, y_2, a)$. Whichever produces the smaller value is element $2$, see proof 4. Once we have found elements $1$ and $2$, solving the rest of the problem is simple. Querying $(1,2,x)$ will always return $x-2$. And we can find the rest of the elements in another $n-2$ queries. Do not forgot about the condition that $p[0]<p[1]$! This is a rough asymptotic analysis for large $n$. Observe that if $\\frac n6 < b < \\frac{5n}{6}$ (this happens around $\\frac 23$ of the time) $b-\\frac{n}{6} < a < b$ (around $\\frac 16$ of the time) $b < c < b+\\frac{n}{6}$ (around $\\frac 1 6$ of the time) Around $\\frac{1}{54}$, we will get a return value of less than $\\frac{1}{6}$. Since there are 6 permutations (i.e. relative orderings of a,b,c), there is a probability of roughly $\\frac{1}{9}$ that some permutation of $(a,b,c)$ satisfies the above condition. The probability that we do not find such a tuple after $420$ queries is $(\\frac{8}{9})^{420} \\approx 3.28\\cdot10^{-22}$. To put this into perspective, you have a higher chance of: Flipping heads $70$ times in a row Drawing a royal flush $5$ times in a row Anton not rejecting a data structure problem We will use contradiction. let $d1, d2, \\ldots ...$ refer to the gaps between the elements. If the maximum any two consecutive gaps is at most $\\lfloor \\frac{n-4}{6} \\rfloor$, one of the queries will work. As such, it is necessary that least $6$ of these gaps are at least $\\lfloor \\frac{n-4}{6} \\rfloor$. Then we have $6 \\cdot (\\lfloor \\frac{n-4}{6} \\rfloor+1) +13$ as the smallest possible size of the original array. However, $6 \\cdot (\\lfloor \\frac{n-4}{6} \\rfloor+1) +13 \\geq 6 \\cdot (\\frac{n-9}{6}+1) +13 = n+10$ which is a clear contradiction. We proof this statement by contrapositive. This statement is equivalent to: if $a-1 \\leq b-a$ and $n-b \\leq b-a$, then $b-a > \\lfloor \\frac{n-4}{3} \\rfloor$. Abbreviating $p[a]$ and $p[b]$ to $a$ and $b$ respectively. Using algebra, $a-1 \\leq b-a$ implies $2a -1 \\leq b$ and $n+a \\leq 2b$. Therefore, $n+3a-1 \\leq 3b$. Then, $\\frac{n-1}{3} \\leq b-a$. It is trivial to see that $\\lfloor \\frac{n-4}{3} \\rfloor < \\frac{n-1}{3}$. Therefore, we have shown that $b-a > \\lfloor \\frac{n-4}{3} \\rfloor$. Suppose that $y_1=2$ and $y_2 = n-1$ or $y_2=n$. We can bound $a$ by $y_1 < a < y_2$ We want to show that the query of $(1,y_1,a)$ is smaller than $(1,a,y_2)$. This is equivalent to showing that $\\max(|1-2|,|2-a|) < \\max (|1-a|,|a-y_2|)$. Since $2 < a$, $\\max(|1-2|,|2-a|)=a-2$. Case $1$: $|1-a| \\geq |a-y_2|$ $\\max(|1-a|,|a-y_2|)=a-1$. Therefore, $\\max(|1-2|,|2-a|) = a-2 < a-1 = \\max(|1-a|,|a-y_2|)$. Case $2$: $|a-y_2| > |1-a|$ $\\max(|1-a|,|a-y_2|)=|a-y_2|$. Therefore, $\\max(|1-2|,|2-a|) = a-2 < a-1 = |1-a| < |a-y_2| = \\max(|1-a|,|a-y_2|)$.",
    "code": "import sys, random\n\nprint = sys.stdout.write\ninput = sys.stdin.readline\n\ndef query(a, b, c):\n    print(\"? \" + str(a+1) + \" \" + str(b+1) + \" \" + str(c+1) + \"\\n\")\n    sys.stdout.flush()\n    return int(input())\n\ndef answer():\n    print(\"! \" + \" \".join([str(i) for i in ans]) + \"\\n\")\n    sys.stdout.flush()\n    return int(input())\n\nT = int(input())\ntestVal = 13\n\nrandomQueryOrder = []\nfor i in range(testVal):\n    for j in range(i+1, testVal):\n        for k in range(j+1, testVal):\n            randomQueryOrder.append((i, j, k))\n\nfor caseno in range(T):\n    N = int(input())\n    \n    a = -1\n    b = -1\n\n    ans = [0 for i in range(N)]\n    res = [0 for i in range(N)]\n    order = [i for i in range(N)]\n    \n    minVal = N+5\n    \n    random.shuffle(order)\n    random.shuffle(randomQueryOrder)\n    for ijk in randomQueryOrder:\n        i, j, k = ijk\n        i = order[i]\n        j = order[j]\n        k = order[k]\n        temp = query(i, j, k)\n        \n        if temp <= (N-4)//6:\n            a = i\n            b = j\n            break\n    \n    assert(a != -1 and b != -1)\n\n    ''' Now, the key thing to note is that abs(P[a]-P[b]) is less than (roughly speaking) N/3.\n    Observe that the index c such that query(a, b, c) is maximum must be such that P[c] == 1 or P[c] == N (some steps skipped).\n    But given the condition P[1] < P[2], we can assume either, then flip using P[i] = N+1-P[i] if condition not satisfied.\n    '''\n\n    # Now, we assume P[c] = 1\n    # There always exists another index d such that query(a, b, d) = query(a, b, c)-1 and P[d] = 2\n    # There can be only at most 2 d which satisfy the former, and we can check which is which by comparing query(a, c, d)\n\n    maxVal = -1\n    c = -1\n    for i in range(N):\n        if a == i or b == i:\n            continue\n        \n        res[i] = query(a, b, i)\n        if res[i] > maxVal:\n            maxVal = res[i]\n            c = i\n\n    d2 = []\n    for i in range(N):\n        if a == i or b == i:\n            continue\n        \n        if res[i] == maxVal-1:\n            d2.append(i)\n\n    d = -1\n    if len(d2) == 1:\n        d = d2[0]\n    elif len(d2) == 2:\n        temp1 = query(a, c, d2[0])\n        temp2 = query(a, c, d2[1])\n        if temp1 < temp2:\n            d = d2[0]\n        else:\n            d = d2[1]\n    else:\n        assert(False)\n\n    # After finding indices c and d such P[c] = 1 and P[d] = 2, we can now find the rest of the values\n    ans[c] = 1\n    ans[d] = 2\n    for i in range(N):\n        if i == c or i == d:\n            continue\n        ans[i] = 2 + query(c, d, i)\n\n    # Flip since P[1] < P[2] not satisfied\n    if ans[0] >= ans[1]:\n        for i in range(N):\n            ans[i] = N+1-ans[i]\n\n    result = answer()\n\n    # I dislike getting WA, hence I make my code MLE\n    if result != 1:\n        MLE = [1 for i in range(1<<27)]\n        sys.stdout.write(MLE[0])",
    "tags": [
      "constructive algorithms",
      "interactive",
      "probabilities"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1527",
    "index": "A",
    "title": "And Then There Were K",
    "statement": "Given an integer $n$, find the maximum value of integer $k$ such that the following condition holds:\n\n\\begin{center}\n$n$ & ($n-1$) & ($n-2$) & ($n-3$) & ... ($k$) = $0$\n\\end{center}\n\nwhere & denotes the bitwise AND operation.",
    "tutorial": "Let $T =$ $n$ & ($n-1$) & ($n-2$) & ($n-3$) & ... ($k$) If there is at least one integer from $K$ to $N$ whose bit at the $i_{th}$ index is $0$, then the value of the $i_{th}$ bit in $T$ will also be $0$. We can easily observe that the $msb$ (Highest set bit in $n$) in $N$ will become $0$ for the first time when $K = 2^{msb}- 1$. All the other bits will become zero when $K = 2^{msb}$. Thus the answer is, $K = 2^{msb} - 1$.",
    "code": "#include<bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#define ll          long long\n#define pb          push_back\n#define ppb         pop_back\n#define endl        '\\n'\n#define mii         map<ll,ll>\n#define msi         map<string,ll>\n#define mis         map<ll, string>\n#define rep(i,a,b)    for(ll i=a;i<b;i++)\n#define repr(i,a,b) for(ll i=b-1;i>=a;i--)\n#define trav(a, x)  for(auto& a : x)\n#define pii         pair<ll,ll>\n#define vi          vector<ll>\n#define vii         vector<pair<ll, ll>>\n#define vs          vector<string>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (ll)x.size()\n#define hell        1000000007\n#define lbnd        lower_bound\n#define ubnd        upper_bound\n#define DEBUG       cerr<<\"/n>>>I'm Here<<</n\"<<endl;\n#define display(x) trav(a,x) cout<<a<<\" \";cout<<endl;\n#define what_is(x)  cerr << #x << \" is \" << x << endl;\n#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>\n#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\nusing namespace __gnu_pbds;\nusing namespace std;\n#define PI 3.141592653589793\n#define N  200005\nvoid solve()\n{\n    ll n;\n    cin >> n;\n    ll cnt=0;\n    while(n!=0){\n        cnt++;\n        n=n/2;\n    }\n    cout << (1<<(cnt-1))-1 << endl;\n}\nint main()\n{\n    #ifndef ONLINE_JUDGE\n    freopen (\"input.txt\",\"r\",stdin);\n    #endif\n    ll int TEST=1;\n    cin >> TEST;\n    //init();\n    while(TEST--)\n    {\n        solve();\n    }\n}\n",
    "tags": [
      "bitmasks"
    ],
    "rating": 800
  },
  {
    "contest_id": "1527",
    "index": "B1",
    "title": "Palindrome Game (easy version)",
    "statement": "\\textbf{The only difference between the easy and hard versions is that the given string $s$ in the easy version is initially a palindrome, this condition is not always true for the hard version.}\n\nA palindrome is a string that reads the same left to right and right to left. For example, \"101101\" is a palindrome, while \"0101\" is not.\n\nAlice and Bob are playing a game on a string $s$ \\textbf{(which is initially a palindrome in this version)} of length $n$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.\n\nIn each turn, the player can perform one of the following operations:\n\n- Choose any $i$ ($1 \\le i \\le n$), where $s[i] =$ '0' and change $s[i]$ to '1'. Pay 1 dollar.\n- Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently \\textbf{not} a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.\n\nReversing a string means reordering its letters from the last to the first. For example, \"01001\" becomes \"10010\" after reversing.\n\nThe game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.",
    "tutorial": "If the count of zeros in the string $s$ is even then Bob always win Proof Bob can restrict Alice from performing operation $2$ by making string $s$ palindrome (if Alice changes $s[i]$ to '1' then Bob will change $s[n-i+1]$ to '1'). However, when the last '0' is remaining, Bob will reverse the string, eventually forcing Alice to perform the operation $1$. This way Alice will spend $2$ dollars more than Bob resulting in Bob's win. Proof Alice will change $s[n/2]$ from '0' to '1' and play with the same strategy as Bob did in the above case. This way Bob will spend $1$ dollar more than Alice resulting in Alice's win.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long int\n#define mp(a,b) make_pair(a,b)\n#define vi vector<int>\n#define mii map<int,int>\n#define mpi map<pair<int,int>,int>\n#define vp vector<pair<int,int> >\n#define pb(a) push_back(a)\n#define fr(i,n) for(i=0;i<n;i++)\n#define rep(i,a,n) for(i=a;i<n;i++)\n#define F first\n#define S second\n#define endl \"\\n\"\n#define fast std::ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n#define mod 1000000007\n#define dom 998244353\n#define sl(a) (int)a.length()\n#define sz(a) (int)a.size()\n#define all(a) a.begin(),a.end()\n#define pii pair<int,int> \n#define mini 2000000000000000000\n#define time_taken 1.0 * clock() / CLOCKS_PER_SEC\n//const long double pi = acos(-1);\n//mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());\n//primes for hashing 937, 1013\ntemplate<typename T, typename U> static inline void amin(T &x, U y) \n{ \n    if (y < x) \n        x = y; \n}\ntemplate<typename T, typename U> static inline void amax(T &x, U y) \n{ \n    if (x < y) \n        x = y; \n}\nvoid shikhar7s(int cas)\n{\n    int n,i;\n    cin>>n;\n    string s;\n    cin>>s;\n    int f=1,z=0;\n    fr(i,n)\n    {\n        if(s[i]=='0')\n            z++;\n    }\n    int x=0;\n    fr(i,n/2)\n    {\n        if(s[i]!=s[n-1-i])\n        {\n            f=0;\n            x++;\n        }\n    }\n    if(f)\n    {\n        if(z==1||z%2==0)\n            cout<<\"BOB\"<<endl;\n        else\n            cout<<\"ALICE\"<<endl;\n    }\n    else\n    {\n        if(x==1&&z==2)\n            cout<<\"DRAW\"<<endl;\n        else\n            cout<<\"ALICE\"<<endl;\n    }\n}\nsigned main()\n{\n    fast;\n    //freopen(\"input.txt\", \"rt\", stdin);\n    //freopen(\"output.txt\", \"wt\", stdout);\n    int t=1;\n    cin>>t;\n    int cas=1;\n    while(cas<=t)\n    {\n    //cout<<\"Case #\"<<cas<<\": \";\n    shikhar7s(cas);\n    cas++;\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "games"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1527",
    "index": "B2",
    "title": "Palindrome Game (hard version)",
    "statement": "\\textbf{The only difference between the easy and hard versions is that the given string $s$ in the easy version is initially a palindrome, this condition is not always true for the hard version.}\n\nA palindrome is a string that reads the same left to right and right to left. For example, \"101101\" is a palindrome, while \"0101\" is not.\n\nAlice and Bob are playing a game on a string $s$ of length $n$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.\n\nIn each turn, the player can perform one of the following operations:\n\n- Choose any $i$ ($1 \\le i \\le n$), where $s[i] =$ '0' and change $s[i]$ to '1'. Pay 1 dollar.\n- Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently \\textbf{not} a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.\n\nReversing a string means reordering its letters from the last to the first. For example, \"01001\" becomes \"10010\" after reversing.\n\nThe game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.",
    "tutorial": "Solution 1: The case when $s$ is a palindrome is discussed in B1. Otherwise, Alice will win or the game will end with a draw. Proof If it is optimal for Alice to perform operation $1$ in the first move, she will perform it else she will perform operation $2$ forcing Bob to perform operation $1$ (which is not optimal otherwise Alice would have performed it in the first move). Optimal Strategy for Alice Alice will keep reversing the string till string $s$ is one move short to become a palindrome with an even number of zeros. This time Alice will perform operation $1$ instead of reversing and will make string $s$ a palindrome. Now, string $s$ is a palindrome containing an even number of zeros, with Bob's turn. Here, Alice can take $2$ dollars advantage using the strategy mentioned in B1. This way Bob will spend at least $1$ dollars more than Alice resulting in Alice's win. In some cases like '1100', '1001110' Alice will just keep on reversing the string and Bob has to change all '0' to 1'. Solution 2: As constraints on $n$ were small, the problem can also be solved using dynamic programming. Following parameters of string $s$ is enough define current state of game: $cnt00$ = count of symmetric $00$ pair ($s[i]=$'0' as well as $s[n-i+1]=$'0') $cnt01$ = count of symmetric $01$ or $10$ pair ($s[i]$ is not equal to $s[n-i+1]$) $mid$ = $True$ if mid character exists (length of string is odd) and it is '0' else $False$ $rev$ = $True$ if previous move was operation $2$ else $False$If any player encounters the game state $\\{cnt00,cnt01,mid,rev\\}$, we define $dp_{cnt00,cnt01,mid,rev}$ to be the minimum cost difference he/she can achieve from here. Transition is pretty simple if $rev$ is $False$ and $cnt01>0$: $dp_{cnt00,cnt01,mid,rev} = \\min(dp_{cnt00,cnt01,mid,rev},-dp_{cnt00,cnt01,mid,True} )$ if $cnt00>0$: $dp_{cnt00,cnt01,mid,rev} = \\min(dp_{cnt00,cnt01,mid,rev},1-dp_{cnt00-1,cnt01+1,mid,False})$ if $cnt01>0$: $dp_{cnt00,cnt01,mid,rev} = \\min(dp_{cnt00,cnt01,mid,rev},1-dp_{cnt00,cnt01-1,mid,False})$ if $mid$ is $True$: $dp_{cnt00,cnt01,mid,rev} = \\min(dp_{cnt00,cnt01,mid,rev},1-dp_{cnt00,cnt01,False,False})$ Finally, If $dp_{cnt00,cnt01,mid,rev}<0$, Alice wins If $dp_{cnt00,cnt01,mid,rev}>0$, Bob wins If $dp_{cnt00,cnt01,mid,rev}=0$, Draw We can precompute this dp and answer all test cases in $O(n)$. Overall time complexity - $O(n^{2})$ If any player encounters the game state $\\{cnt00,cnt01,mid,rev\\}$, we define $dp_{cnt00,cnt01,mid,rev}$ to be the minimum cost difference he/she can achieve from here. Transition is pretty simple if $rev$ is $False$ and $cnt01>0$: $dp_{cnt00,cnt01,mid,rev} = \\min(dp_{cnt00,cnt01,mid,rev},-dp_{cnt00,cnt01,mid,True} )$ if $cnt00>0$: $dp_{cnt00,cnt01,mid,rev} = \\min(dp_{cnt00,cnt01,mid,rev},1-dp_{cnt00-1,cnt01+1,mid,False})$ if $cnt01>0$: $dp_{cnt00,cnt01,mid,rev} = \\min(dp_{cnt00,cnt01,mid,rev},1-dp_{cnt00,cnt01-1,mid,False})$ if $mid$ is $True$: $dp_{cnt00,cnt01,mid,rev} = \\min(dp_{cnt00,cnt01,mid,rev},1-dp_{cnt00,cnt01,False,False})$ If $dp_{cnt00,cnt01,mid,rev}<0$, Alice wins If $dp_{cnt00,cnt01,mid,rev}>0$, Bob wins If $dp_{cnt00,cnt01,mid,rev}=0$, Draw",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ndouble pi = acos(-1);\n#define _time_      1.0 * clock() / CLOCKS_PER_SEC\n#define fi          first\n#define se          second\n#define mp          make_pair\n#define pb          push_back\n#define all(a)      a.begin(),a.end()\nmt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n\nint dp[505][505][2][2];\n\nvoid precompute(){\n    for(int i=0;i<=500;i++){\n        for(int j=0;j<=500;j++){\n            for(int k=0;k<2;k++){\n                for(int l=1;l>=0;l--){\n                    dp[i][j][k][l] = 1e9;\n                }\n            }\n        }\n    }\n    dp[0][0][0][0]=0;\n    dp[0][0][0][1]=0;\n    for(int i=0;i<=500;i++){\n        for(int j=0;j<=500;j++){\n            for(int k=0;k<2;k++){\n                for(int l=1;l>=0;l--){\n                    if(l==0 && j>0) dp[i][j][k][l] = min(dp[i][j][k][l],-dp[i][j][k][1]);\n                    if(i>0) dp[i][j][k][l] = min(dp[i][j][k][l],1-dp[i-1][j+1][k][0]);\n                    if(j>0) dp[i][j][k][l] = min(dp[i][j][k][l],1-dp[i][j-1][k][0]);\n                    if(k==1) dp[i][j][k][l] = min(dp[i][j][k][l],1-dp[i][j][0][0]);\n                }\n            }\n        }\n    }\n}\n\nvoid solve(){\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    int cnt00=0,cnt01=0,mid=0;\n    for(int i=0;i<n/2;i++){\n        if(s[i]=='0' && s[i]==s[n-i-1]) cnt00++;\n        if(s[i]!=s[n-i-1]) cnt01++;\n    }\n    if(n%2 && s[n/2]=='0') mid=1;\n    if(dp[cnt00][cnt01][mid][0]<0){\n        cout << \"ALICE\";\n    }else if(dp[cnt00][cnt01][mid][0]>0){\n        cout << \"BOB\";\n    }else{\n        cout << \"DRAW\";\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #ifdef SIEVE\n        sieve();\n    #endif\n    #ifdef NCR\n        init();\n    #endif\n    precompute();\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "games"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1527",
    "index": "C",
    "title": "Sequence Pair Weight",
    "statement": "The weight of a sequence is defined as the number of unordered pairs of indexes $(i,j)$ (here $i \\lt j$) with same value ($a_{i} = a_{j}$). For example, the weight of sequence $a = [1, 1, 2, 2, 1]$ is $4$. The set of unordered pairs of indexes with same value are $(1, 2)$, $(1, 5)$, $(2, 5)$, and $(3, 4)$.\n\nYou are given a sequence $a$ of $n$ integers. Print the sum of the weight of all subsegments of $a$.\n\nA sequence $b$ is a subsegment of a sequence $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "First of all, it can be proved that the maximum possible answer occurs when $n = 10^5$ and all the elements are identical which comes out to be of the order $4 \\cdot 10^{18}$, which fits in the long long integer range, thus preventing overflow. The brute force approach is just to find the weight of each subarray and sum them up but it will definitely not fit into TL. Let $dp_i$ represents the sum of the weights of all subsegments which ends at index $i$. So $answer = \\sum_{i = 1}^{n} dp_i$ Now, $dp_i$ includes: Sum of the weights of all subsegments ending at index $i-1$ which is equal to $dp_{i-1}$. The contribution of $i_{th}$ index for all the subsegments ending at index $i$. This is just the sum of prefix sums of indexes of the element having the same value as that of $a_i$ which has occurred before index $i$. This is because the number of subsegments ending at index $i$ in which any index $j$ ($j < i$ and $a_j = a_i$) has been counted as unordered pair ${j,i}$ is equal to $j$. This can be done by maintaining a map that stores the prefix sum of indexes for a given value till $i$.",
    "code": "t = int(input())\nfor j in range(t):\n    n = int(input())\n    a = list(map(int,input().split()))\n    \n    value = {}\n    fa, ca = 0, 0\n    \n    for i in range(n):\n      if a[i] in value:\n        ca += value[a[i]]\n      else:\n        value[a[i]]=0\n      value[a[i]] += i+1\n      fa += ca\n    \n    print(fa)",
    "tags": [
      "hashing",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1527",
    "index": "D",
    "title": "MEX Tree",
    "statement": "You are given a tree with $n$ nodes, numerated from $0$ to $n-1$. For each $k$ between $0$ and $n$, inclusive, you have to count the number of unordered pairs $(u,v)$, $u \\neq v$, such that the \\textbf{MEX} of all the node labels in the shortest path from $u$ to $v$ (including end points) is $k$.\n\nThe \\textbf{MEX} of a sequence of integers is the smallest non-negative integer that does not belong to the sequence.",
    "tutorial": "This problem can be solved with two pointer approach. We will use the following simple formula to evaluate the number of paths with MEX = i, $ans_i$ = (Number of paths with $MEX \\ge i$) - (Number of paths with $MEX > i$). First we root the tree at node $0$ and calculate the subtree sizes using a basic subtree DP. Now we can easily calculate answer for $0$ by just summing up the $size \\cdot (size-1)/2$ of its children. Since total number of paths are $\\left(\\begin{array}{c}n\\\\ 2\\end{array}\\right)$, the number of paths with $MEX > 0$ are $\\left(\\begin{array}{c}n\\\\ 2\\end{array}\\right) - ans_0$ and we will maintain these paths which are having $MEX > i$ for every $i$ in a variable lets say $P$. Now the main idea is that for the $MEX$ of a path to be equal to $i$ it must contain all nodes from $0...i-1$ and not $i$. It can be seen that if we have current $MEX = i$ in some path then this path can only be extended from both ends as for $MEX > i$ this whole path must be included. So we start with our $2$ pointers initially $l = 0,r = 0$ i.e. both at the root. We will also be maintaining a visited array which will be denoting all those vertices which are lying in our path from $l$ to $r$. Now we loop from $1$ to $n$ and successively calculate their answers. Suppose we need to add some vertex $i$ to the path, then if the current vertex is already in the path i.e. already visited then we can just continue as the variable $P$ will remain same. In the other case, a possible approach is to just recursively move to the parent marking them as visited until we find a previously visited node. Let that node be $U$. Note that we will always break at the root as it is marked visited in the initial step. Now the following two cases arise, The node $U$ is one of the endpoints $l$ or $r$. In this case we can simply calculate the number of paths having $MEX = i$. See the diagram below, we are having $P$ from previous calculations the number of paths having $MEX \\ge i$ and the number of paths with $MEX > i$ (actually those paths which include all nodes from $0$ to $i-1$) can simply be seen as $subtree_i \\cdot subtree_l$ or $subtree_i \\cdot subtree_r$ depending on which two endpoints are there now. It should be noted that we also need to update the subtree sizes as we move up to parent recursively, by subtracting the $subtree_v$ from $subtree_{parent(v)}$. After updating the $l$ and $r$ pointers, the answer for $MEX = i$ is simply $P - subtree_l \\cdot subtree_r$ and finally we update the variable $P = subtree_l \\cdot subtree_r$ denoting for $i + 1$, the number of paths with $MEX \\ge i+1$. The next case is when $U$ is not among the endpoints $l$ and $r$, then in this case $ans_i = P$ and all other remaining i.e $MEX \\ge i+1$ are zero, since we can never find a path which can contain all vertices from $0$ to $i$.",
    "code": "#include<bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#define ll          long long\n#define pb          push_back\n#define ppb         pop_back\n#define endl        '\\n'\n#define mii         map<ll,ll>\n#define msi         map<string,ll>\n#define mis         map<ll, string>\n#define rep(i,a,b)    for(ll i=a;i<b;i++)\n#define repr(i,a,b) for(ll i=b-1;i>=a;i--)\n#define trav(a, x)  for(auto& a : x)\n#define pii         pair<ll,ll>\n#define vi          vector<ll>\n#define vii         vector<pair<ll, ll>>\n#define vs          vector<string>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (ll)x.size()\n#define hell        1000000007\n#define lbnd        lower_bound\n#define ubnd        upper_bound\n#define DEBUG       cerr<<\"/n>>>I'm Here<<</n\"<<endl;\n#define display(x) trav(a,x) cout<<a<<\" \";cout<<endl;\n#define what_is(x)  cerr << #x << \" is \" << x << endl;\n#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>\n#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\nusing namespace __gnu_pbds;\nusing namespace std;\n#define PI 3.141592653589793\n#define N  200005\nll add(ll x,ll y){return (x+y)%hell;}\nll mul(ll x,ll y){return (x*y)%hell;}\nvector <ll> adj[N];\nll subtree[N];\nll min1[N];\nll ans[N];\nll vis[N];\nll le;\nint v;int u;\nll n;\nint prevv;int prevu;\nvoid init(){\n    rep(i,0,n){\n        adj[i].clear();\n        subtree[i]=0;\n        min1[i]=n;\n        ans[i]=0;\n        vis[i]=0;\n    }\n    le=n*(n-1)/2;\n    v=0;u=0;\n    prevv=-1;\n    prevu=-1;\n}\nvoid dfs(int v,int prev=-1){\n    subtree[v]=1;\n    min1[v]=v;\n    for (auto it: adj[v]){\n        if (it==prev) continue;\n        dfs(it,v);\n        subtree[v]+=subtree[it];\n        min1[v]=min(min1[v],min1[it]);\n    }\n}\nvoid find(int val){\n    //cout << v << \" \" << u << \" \" << prevv << \" \" << prevu << \" \" << val << endl;\n    if (v==val or u==val){\n        ll a,b;\n        if (subtree[prevv]>subtree[v] or prevv==-1) a=subtree[v];\n        else a=n-subtree[prevv];\n        if (subtree[prevu]>subtree[u] or prevu==-1) b=subtree[u];\n        else b=n-subtree[prevu];\n        ans[val]=le-a*b;\n        //cout << a << \" \" << b << endl;\n        le=a*b;\n        return;\n    }\n    for (auto it: adj[v]){\n        if (it==prevv) continue;\n        if (min1[it]==val){\n            if (v==u) prevu=it;\n            prevv=v;\n            v=it;\n            vis[it]=1;\n            \n            find(val);\n            return;\n        }  \n    }\n    for (auto it: adj[u]){\n        if (it==prevu) continue;\n        if (min1[it]==val){\n            prevu=u;\n            u=it;\n            vis[it]=1;\n            find(val);\n            return;\n        }  \n    }\n    ans[val]=le;\n    le=0;\n}\nvoid solve()\n{\n    cin >> n;\n    init();\n    rep(i,0,n-1){\n        int x,y;\n        cin >> x >> y;\n        adj[x].pb(y);\n        adj[y].pb(x);\n    }\n    dfs(0);\n    //cout << le << endl;\n    for (auto it: adj[0]) {ans[0]+=(subtree[it]*(subtree[it]-1))/2;}\n    //cout << endl;\n    //cout << ans[0] << endl;\n    le-=ans[0];\n    rep(i,1,n){\n        if (vis[i]==1 or le==0) ans[i]=0;\n        else find(i);\n    }\n    ans[n]=le;\n    rep(i,0,n+1) cout << ans[i] << \" \";\n    cout << endl;\n    return;\n}\nint main()\n{\n    #ifndef ONLINE_JUDGE\n    freopen (\"input.txt\",\"r\",stdin);\n    #endif\n    ll int TEST=1;\n    cin >> TEST;\n    while(TEST--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1527",
    "index": "E",
    "title": "Partition Game",
    "statement": "You are given an array $a$ of $n$ integers. Define the cost of some array $t$ as follows:\n\n$$cost(t) = \\sum_{x \\in set(t) } last(x) - first(x),$$\n\nwhere $set(t)$ is the set of all values in $t$ without repetitions, $first(x)$, and $last(x)$ are the indices of the first and last occurrence of $x$ in $t$, respectively. In other words, we compute the distance between the first and last occurrences for each distinct element and sum them up.\n\nYou need to split the array $a$ into $k$ consecutive segments such that each element of $a$ belongs to exactly one segment and the sum of the cost of individual segments is minimum.",
    "tutorial": "Let's use dynamic programming to solve this problem. Consider $dp[i][j]$ be the answer for prefix $j$ with $i$ subsegments. Transitions are fairly straightforward. Let $c[i][j]$ be the cost of subarray starting at $i^{th}$ index and ending at $j^{th}$ index. $dp[i][j] = \\min\\limits_{k \\lt j}(dp[i-1][k] + c[k+1][j])$ If we calculate it naively, it would result in $O(n^2k)$ solution which would not be enough for given constraints. We need some data structure to maintain $dp[i-1][k] + c[k+1][j]$ for every $k \\lt j$. Consider the example $a = [2,2,3,2,3]$. We can write cost as $(2-1) + (4-2) + (5-3) = 5$. Except for the first occurrence, we just need a sum of $b[k] = k - last[a[k]]$ in the range, where $last[a[k]]$ is the index of the last occurrence of $a[k]$ just before index $k$. We can maintain this in some segment tree. Let's say our segment tree is built for prefix $j$, we can transition to prefix $j+1$ by adding $b[j+1]$ in range $[0,last[a[j+1]]-1]$. This will result in a $O(n \\cdot k log(n))$ solution.",
    "code": "#include<bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#define ll          long long\n#define pb          push_back\n#define ppb         pop_back\n#define endl        '\\n'\n#define mii         map<ll,ll>\n#define msi         map<string,ll>\n#define mis         map<ll, string>\n#define rep(i,a,b)    for(ll i=a;i<b;i++)\n#define repr(i,a,b) for(ll i=b-1;i>=a;i--)\n#define trav(a, x)  for(auto& a : x)\n#define pii         pair<ll,ll>\n#define vi          vector<ll>\n#define vii         vector<pair<ll, ll>>\n#define vs          vector<string>\n#define all(a)      (a).begin(),(a).end()\n#define F           first\n#define S           second\n#define sz(x)       (ll)x.size()\n#define hell        1000000007\n#define lbnd        lower_bound\n#define ubnd        upper_bound\n#define DEBUG       cerr<<\"/n>>>I'm Here<<</n\"<<endl;\n#define display(x) trav(a,x) cout<<a<<\" \";cout<<endl;\n#define what_is(x)  cerr << #x << \" is \" << x << endl;\n#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>\n#define FAST ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\nusing namespace __gnu_pbds;\nusing namespace std;\n#define PI 3.141592653589793\n#define MAXN  35005\nint tree1[4*MAXN];\nint lazy[4*MAXN];\nint s[MAXN];\nvoid build(int node, int start, int end)\n{\n    lazy[node]=0;\n    if(start == end)\n    {\n        // Leaf node will have a single element\n        tree1[node] = s[start];\n        //cout << tree1[node] << \" \";\n    }\n    else\n    {\n        int mid = (start + end) / 2;\n        // Recurse on the left child\n        build(2*node, start, mid);\n        // Recurse on the right child\n        build(2*node+1, mid+1, end);\n        // Internal node will have the sum of both of its children\n        tree1[node] = min(tree1[2*node],tree1[2*node+1]);\n    }\n}\nvoid updateRange(int node, int start, int end, int l, int r, int val)\n{\n    if (l>r) return;\n    if(lazy[node] != 0)\n    { \n        // This node needs to be updated\n        tree1[node] = tree1[node]+lazy[node];    // Update it\n        if(start != end)\n        {\n            lazy[node*2] += lazy[node];                  // Mark child as lazy\n            lazy[node*2+1] += lazy[node];                // Mark child as lazy\n        }\n        lazy[node] = 0;                                  // Reset it\n    }\n    if(start > end or start > r or end < l)              // Current segment is not within range [l, r]\n        return;\n    if(start >= l and end <= r)\n    {\n        // Segment is fully within range\n        tree1[node] = tree1[node]+val;\n        if(start != end)\n        {\n            // Not leaf node\n            lazy[node*2] += val;\n            lazy[node*2+1] += val;\n        }\n        return;\n    }\n    int mid = (start + end) / 2;\n    updateRange(node*2, start, mid, l, r, val);        // Updating left child\n    updateRange(node*2 + 1, mid + 1, end, l, r, val);   // Updating right child\n    tree1[node] = min(tree1[node*2],tree1[node*2+1]);        // Updating root with max value \n}\n\nll queryRange(int node, int start, int end, int l, int r)\n{\n    if(start > end or start > r or end < l)\n        return hell;         // Out of range\n    if(lazy[node] != 0)\n    {\n        // This node needs to be updated\n        tree1[node] = tree1[node]+lazy[node];            // Update it\n        if(start != end)\n        {\n            lazy[node*2] += lazy[node];         // Mark child as lazy\n            lazy[node*2+1] += lazy[node];    // Mark child as lazy\n        }\n        lazy[node] = 0;                 // Reset it\n    }\n    if(start >= l and end <= r)             // Current segment is totally within range [l, r]\n        return tree1[node];\n    int mid = (start + end) / 2;\n    ll p1 = queryRange(node*2, start, mid, l, r);         // Query left child\n    ll p2 = queryRange(node*2 + 1, mid + 1, end, l, r); // Query right child\n    return min(p1,p2);\n}\nvoid solve()\n{\n    ll n,k;\n    cin >> n >> k;\n    int a[n];\n    rep(i,0,n) cin >> a[i];\n    int lastoc[n];\n    map <int,int> m1;\n    rep(i,0,n){\n        if (m1.find(a[i])==m1.end()) lastoc[i]=-1;\n        else lastoc[i]=m1[a[i]];\n        m1[a[i]]=i;\n    }\n    int dp[n][k+1];\n    dp[0][1]=0;\n    rep(i,1,n){\n        dp[i][1]=dp[i-1][1];\n        if (lastoc[i]!=-1) dp[i][1]+=i-lastoc[i];\n    }\n    rep(i,2,k+1){\n        rep(j,0,n) s[j]=dp[j][i-1];\n        build(1,0,n-1);\n        rep(j,0,i-1) dp[j][i]=hell;\n        dp[i-1][i]=0;\n        rep(j,i,n)\n        {\n            int lastj=lastoc[j];\n            if (lastj>0 and (i-2)<(lastj)) {\n                updateRange(1,0,n-1,i-2,lastj-1,j-lastj);\n            } \n            dp[j][i] = queryRange(1,0,n-1,i-2,j-1);\n        }\n    }\n    cout << dp[n-1][k] << endl;\n}\nint main()\n{\n    #ifndef ONLINE_JUDGE\n    freopen (\"input.txt\",\"r\",stdin);\n    #endif\n    ll int TEST=1;\n    //cin >> TEST;\n    //init();\n    while(TEST--)\n    {\n        solve();\n    }\n}\n\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1528",
    "index": "A",
    "title": "Parsa's Humongous Tree",
    "statement": "Parsa has a humongous tree on $n$ vertices.\n\nOn each vertex $v$ he has written two integers $l_v$ and $r_v$.\n\nTo make Parsa's tree look even more majestic, Nima wants to assign a number $a_v$ ($l_v \\le a_v \\le r_v$) to each vertex $v$ such that the beauty of Parsa's tree is maximized.\n\nNima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of $|a_u - a_v|$ over all edges $(u, v)$ of the tree.\n\nSince Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the \\textbf{maximum} possible beauty for Parsa's tree.",
    "tutorial": "The solution is based on the fact that an optimal assignment for $a$ exists such that for each vertex $v$, $a_v \\in {l_v, r_v}$. Proving this fact isn't hard, pick any assignment for $a$. Assume $v$ is a vertex in this assignment such that $a_v \\notin {l_v, r_v}$. Let $p$ be the number of vertices $u$ adjacent to $v$ such that $a_u > a_v$. Let $q$ be the number of vertices $u$ adjacent to $v$ such that $a_u < a_v$. Consider the following cases: $p > q$: In this case we can decrease $a_v$ to $l_v$ and get a better result. $p < q$: In this case we can increase $a_v$ to $r_v$ and get a better result. $p = q$: In this case changing $a_v$ to $l_v$ or $r_v$ will either increase or not change the beauty of the tree. Based on this fact, we can use dynamic programming to find the answer. Define $dp_{v,0}$ as the maximum beauty of $v$'s subtree if $a_v$ is equal to $l_v$. Similarly, define $dp_{v,1}$ as the maximum beauty of $v$'s subtree if $a_v$ is equal to $r_v$. $dp_{v,j}$ is calculated based on $v$'s children, for each of $v$'s children such as $u$, we add $u$'s contribution to $dp_{v,j}$. The transitions are: $dp_{v,0} += max(dp_{u,0} + |l_v - l_u| , dp_{u,1} + |l_v - r_u|)$ $dp_{v,1} += max(dp_{u,0} + |r_v - l_u| , dp_{u,1} + |r_v - r_u|)$ It's clear that the answer is equal to $max(dp_{v,0}, dp_{v,1})$. complexity: $\\mathcal{O}(n)$",
    "code": "// Call my Name and Save me from The Dark\n#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long int ll;\ntypedef pair<int, int> pii;\n \n#define SZ(x)                       (int) x.size()\n#define F                           first\n#define S                           second\n \nconst int N = 2e5 + 10;\nll dp[2][N]; int A[2][N], n; vector<int> adj[N];\n \nvoid DFS(int v, int p = -1) {\n    dp[0][v] = dp[1][v] = 0;\n    for (int u : adj[v]) {\n        if (u == p) continue;\n        DFS(u, v);\n        dp[0][v] += max(abs(A[0][v] - A[1][u]) + dp[1][u], dp[0][u] + abs(A[0][v] - A[0][u]));\n        dp[1][v] += max(abs(A[1][v] - A[1][u]) + dp[1][u], dp[0][u] + abs(A[1][v] - A[0][u]));\n    }\n}\n \nvoid Solve() {\n    scanf(\"%d\", &n);\n    for (int i = 1; i <= n; i++) scanf(\"%d%d\", &A[0][i], &A[1][i]);\n    fill(adj + 1, adj + n + 1, vector<int>());\n    for (int i = 1; i < n; i++) {\n        int u, v; scanf(\"%d%d\", &u, &v);\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    DFS(1);\n    printf(\"%lld\\n\", max(dp[0][1], dp[1][1]));\n}\n \nint main() {\n    int t; scanf(\"%d\", &t);\n    while (t--) Solve();\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1528",
    "index": "B",
    "title": "Kavi on Pairing Duty",
    "statement": "Kavi has $2n$ points lying on the $OX$ axis, $i$-th of which is located at $x = i$.\n\nKavi considers all ways to split these $2n$ points into $n$ pairs. Among those, he is interested in \\textbf{good} pairings, which are defined as follows:\n\nConsider $n$ segments with ends at the points in correspondent pairs. The pairing is called good, if for every $2$ different segments $A$ and $B$ among those, at least one of the following holds:\n\n- One of the segments $A$ and $B$ lies completely inside the other.\n- $A$ and $B$ have the same length.\n\nConsider the following example:\n\n$A$ is a good pairing since the red segment lies completely inside the blue segment.\n\n$B$ is a good pairing since the red and the blue segment have the same length.\n\n$C$ is not a good pairing since none of the red or blue segments lies inside the other, neither do they have the same size.\n\nKavi is interested in the number of good pairings, so he wants you to find it for him. As the result can be large, find this number modulo $998244353$.\n\nTwo pairings are called different, if some two points are in one pair in some pairing and in different pairs in another.",
    "tutorial": "Let $dp_i$ be the number of good pairings of $2i$ points. Clearly, the answer is $dp_n$. Lemma: Denote $x$ as the point matched with the point $1$. Notice that each point $p$ $(x < p \\le 2n)$ belongs to a segment with length equal to $[1 , x]$'s length. Proof: Assume some point $p$ $(x < p \\le 2n)$ is paired with a point $q$ $(q > p)$, since $[p , q]$ doesn't lie inside $[1, x]$ then their size must be the equal for the pairing to be good. To compute $dp_n$, consider the following cases: $x > n$: Similar to lemma mentioned above, it can be proved that each point $p$ $(1 \\le p \\le 2n-x+1)$ is paired with the point $i + x - 1$, the remaining unpaired $x - n - 1$ points form a continuous subarray which lies inside each of the current pairs, thus they can be paired in $dp_{x - n - 1}$ ways. $x \\le n$: In this case, due to the lemma mentioned above all the segments must have the same length, thus their length must be a divisor of $n$, in this case they can be paired in $D(n)$ ways; where $D(n)$ is the number of divisors of $n$. So $dp_n$ = $D(n) + \\sum_{i = 0}^{n-1} {dp_i}$. Note that $dp_0 = dp_1 = 1$. complexity: $\\mathcal{O}(n\\log n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long ll;\ntypedef pair<ll, ll> pll;\ntypedef pair<int, int> pii;\n \n#define X first\n#define Y second\n#define endl '\\n'\n \nconst int N = 1e6 + 10;\nconst int MOD = 998244353;\n \nint n, dp[N], S;\n \nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(nullptr);\n    cin >> n;\n    for (int i = 1; i <= n; i++) {\n        for (int j = i + i; j <= n; j += i) {\n            dp[j]++;\n        }\n    }\n    dp[0] = S = 1;\n    for (int i = 1; i <= n; i++) {\n        dp[i] = (dp[i] + S) % MOD;\n        S = (S + dp[i]) % MOD;\n    }\n    cout << dp[n] << endl;\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1528",
    "index": "C",
    "title": "Trees of Tranquillity",
    "statement": "Soroush and Keshi each have a labeled and rooted tree on $n$ vertices. Both of their trees are rooted from vertex $1$.\n\nSoroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on $n$ vertices.\n\nThey add an edge between vertices $u$ and $v$ in the memorial graph if \\textbf{both} of the following conditions hold:\n\n- One of $u$ or $v$ is the ancestor of the other in Soroush's tree.\n- Neither of $u$ or $v$ is the ancestor of the other in Keshi's tree.\n\nHere vertex $u$ is considered ancestor of vertex $v$, if $u$ lies on the path from $1$ (the root) to the $v$.\n\nPopping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big.\n\nHelp Mashtali by finding the size of the maximum clique in the memorial graph.\n\nAs a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.",
    "tutorial": "Let's start with some observations. Take any clique $C$ in the memorial graph. Notice that the vertices of $C$ are a subset of a path from root to some leaf in Soroush's tree. So it's sufficient to solve the task for every leaf in Soroush's tree, specifically we should consider subsets of the paths starting from the root and ending in a leaf in Soroush's tree. Assume you have a data structure that supports the following operations: Insert a vertex. Erase a vertex. Among the vertices inside it, find the biggest set of vertices $S$ such that none of them is the ancestor of the other in Keshi's tree. To solve the task, start doing DFS from the root of Soroush's tree. Every time you visit a new vertex $v$, add $v$ using the $1$-st operation. Every time you finish doing DFS in a vertex $v$, erase $v$ using the $2$-nd operation. It's easy to see that the vertices in the data structure always form a path from root to some vertex $v$ in Soroush's tree. The answer to the task is the maximum size of $S$ in the $3$-rd operation for every leaf $u$ of Soroush's tree, when adding $u$ has been the last operation in the data structure; In other words $ans = max(ans , x)$ where $x$ is the size of $S$ in the $3$-rd operation whenever you reach a leaf while doing DFS in Soroush's tree. When adding a vertex $v$ to the data structure, if no vertex $u \\in S$ existed such that $u$ was in $v$'s subtree in Keshi's tree, consider the following cases: If no ancestor of $v$ was in $S$, greedily add $v$ to $S$. Otherwise, let that ancestor be $w$, erase $w$ from $S$ and add $v$ instead. On the other hand, if such a vertex $u$ already existed in $S$, we won't add $v$ to $S$ based on the greedy solution mentioned above. Whatever notation used from here onwards refers to Keshi's tree unless stated. Do a DFS on the tree and find the starting time/finishing time for each vertex. It's widely known that vertex $v$ is an ancestor of vertex $u \\iff$ $st_v \\le st_u$ and $ft_v \\ge ft_u$. Observation: for any pair of vertices $u$ and $v$, segments $[st_u , ft_u]$ and $[st_v , ft_v]$ either don't share an element or one of them lies completely inside the other. To construct the aforementioned data structure: Let the set $S$ be a maximal set of the vertices that form a clique in the memorial graph. For each vertex $v$ we store a pair $\\{st_v , v\\}$ in $S$. Now to check whether any vertex $u$ in the subtree of vertex $v$ exists in $S$: Let $p$ be the first pair in $S$ such that the first element in $p \\ge st_v$. If $p$'s second element's finishing time is less than $ft_v$ then $p$'s second element is in $v$'s subtree, otherwise it's not. Now to check whether any ancestor of $v$ is in $S$ or not: Let $p$ be the first pair in $S$ such that $p$'s first element is less than $st_v$, it can be proved that if an ancestor $u$ of $v$ exists in $S$, then $p = \\{st_u , u\\}$, thus we can check if $v$ is in the subtree of $p$'s second element by the aforementioned observation. Doing the erase operation is also possible by keeping a history of the deleted elements from the set $S$. complexity: $\\mathcal{O}(n \\log n)$",
    "code": "#include<bits/stdc++.h>\n#define lc (id * 2)\n#define rc (id * 2 + 1)\n#define md ((s + e) / 2)\n#define dm ((s + e) / 2 + 1)\n#define ln (e - s + 1)\nusing namespace std;\n \ntypedef long long ll;\nconst ll MXN = 3e5 + 10;\nconst ll MXS = MXN * 4;\nll n, timer, ans, Ans;\nll lazy[MXS], seg[MXS];\nll Stm[MXN], Ftm[MXN];\nvector<ll> adj[MXN][2];\nvoid Build(ll id = 1, ll s = 1, ll e = n){\n    lazy[id] = -1, seg[id] = 0;\n    if(ln > 1) Build(lc, s, md), Build(rc, dm, e);\n}\nvoid Shift(ll id, ll s, ll e){\n    if(lazy[id] == -1) return;\n    seg[id] = lazy[id];\n    if(ln > 1) lazy[lc] = lazy[rc] = lazy[id];\n    lazy[id] = -1;\n}\nvoid Upd(ll l, ll r, ll x, ll id = 1, ll s = 1, ll e = n){\n    Shift(id, s, e);\n    if(e < l || s > r) return;\n    if(l <= s && e <= r){\n        lazy[id] = x; Shift(id, s, e);\n        return;\n    }\n    Upd(l, r, x, lc, s, md), Upd(l, r, x, rc, dm, e);\n    seg[id] = max(seg[lc], seg[rc]);\n}\nll Get(ll l, ll r, ll id = 1, ll s = 1, ll e = n){\n    Shift(id, s, e);\n    if(e < l || s > r) return 0;\n    if(l <= s && e <= r) return seg[id];\n    return max(Get(l, r, lc, s, md), Get(l, r, rc, dm, e));\n}\nvoid prep(ll u, ll par, ll f){\n    Stm[u] = ++ timer;\n    for(auto v : adj[u][f]){\n        if(v != par) prep(v, u, f);\n    }\n    Ftm[u] = timer;\n}\nbool Is_Jad(ll j, ll u){\n    return (Stm[j] <= Stm[u] && Ftm[u] <= Ftm[j]);\n}\nvoid DFS(ll u, ll par, ll f){\n    ll j = Get(Stm[u], Ftm[u]);\n    if(!j) Upd(Stm[u], Ftm[u], u), ans ++;\n    else{\n        if(Is_Jad(j, u)){\n            Upd(Stm[j], Ftm[j], 0);\n            Upd(Stm[u], Ftm[u], u);\n        }\n    }\n    Ans = max(Ans, ans);\n    for(auto v : adj[u][f]){\n        if(v != par) DFS(v, u, f);\n    }\n    if(!j) Upd(Stm[u], Ftm[u], 0), ans --;\n    else{\n        if(Is_Jad(j, u)){\n            Upd(Stm[u], Ftm[u], 0);\n            Upd(Stm[j], Ftm[j], j);\n        }\n    }\n}\nvoid solve(){\n    cin >> n, timer = ans = Ans = 0;\n    for(int i = 1; i <= n; i ++) adj[i][0].clear(), adj[i][1].clear();\n    for(int t = 0; t < 2; t ++) for(int u = 2, v; u <= n; u ++){\n        cin >> v, adj[v][t].push_back(u), adj[u][t].push_back(v);\n    }\n    Build(), prep(1, 0, 1);\n    DFS(1, 0, 0);\n    cout << Ans << '\\n';\n}\nint main(){\n    ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);\n    ll q; cin >> q;\n    while(q --) solve();\n    return 0;\n}\n/*!\n    HE'S AN INSTIGATOR,\n    ENEMY ELIMINATOR,\n    AND WHEN HE KNOCKS YOU BETTER\n    YOU BETTER LET HIM IN.\n*/\n//! N.N",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1528",
    "index": "D",
    "title": "It's a bird! No, it's a plane! No, it's AaParsa!",
    "statement": "There are $n$ cities in Shaazzzland, numbered from $0$ to $n-1$. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.\n\nAs the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.\n\nAaParsa has planted $m$ transport cannons in the cities of Shaazzzland. The $i$-th cannon is planted in the city $a_i$ and is initially pointing at city $b_i$.\n\nIt is guaranteed that each of the $n$ cities has \\textbf{at least one} transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $(a_i, b_i)$ are distinct).\n\nAaParsa used very advanced technology to build the cannons, the cannons rotate every second. In other words, if the $i$-th cannon is pointing towards the city $x$ at some second, it will target the city $(x + 1) \\mod n$ at the next second.\n\nAs their name suggests, transport cannons are for transportation, specifically for human transport. If you use the $i$-th cannon to launch yourself towards the city that it's currently pointing at, you'll be airborne for $c_i$ seconds before reaching your target destination.\n\nIf you still don't get it, using the $i$-th cannon at the $s$-th second (using which is only possible if you are currently in the city $a_i$) will shoot you to the city $(b_i + s) \\mod n$ and you'll land in there after $c_i$ seconds (so you'll be there in the $(s + c_i)$-th second). Also note the cannon that you initially launched from will rotate every second but you obviously won't change direction while you are airborne.\n\nAaParsa wants to use the cannons for travelling between Shaazzzland's cities in his grand plan, and he can start travelling at second $0$. For him to fully utilize them, he needs to know the minimum number of seconds required to reach city $u$ from city $v$ using the cannons for every pair of cities $(u, v)$.\n\n\\textbf{Note that AaParsa can stay in a city for as long as he wants}.",
    "tutorial": "Suppose we did normal dijkstra, the only case that might be missed is when we wait in a vertex for some time. To handle the 'waiting' concept, we can add $n$ fake edges, $i$-th of which is from the $i$-th vertex to the $(i+1 \\mod n)$ -th vertex with weight equal to one. Note that unlike the cannons, fake edges do not rotate. It can be proved that doing dijkstra in the new graph is sufficient if we guarantee that the first used edge is not fake. We can map waiting for $x$ seconds and then using an edge to go to $u$ from $v$ to using a cannon and then using $x$ fake edges to go to $u$ from $v$. Also due to the strict time limit you should use the $\\mathcal{O}(n^2)$ variant of dijkstra. complexity: $\\mathcal{O}(n^3)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int maxn = 600 + 5;\n \nint n;\nint dp[maxn];\nbool mark[maxn];\nvector<pair<int,int>> g[maxn];\nint go[maxn];\n \nint dis(int s, int t) {\n\tif (s <= t)\n\t\treturn t - s;\n\treturn n - (s - t);\n}\n \nvoid dijkstra(int src) {\n\tmemset(dp, 63, sizeof dp);\n\tmemset(mark, 0, sizeof mark);\n\tdp[src] = 0;\n\tset<int> S;\n\tfor (int i = 0; i < n; i++)\n\t\tS.insert(i);\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tint v = -1;\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (mark[j])\n\t\t\t\tcontinue;\n\t\t\tif (v == -1 or dp[v] > dp[j])\n\t\t\t\tv = j;\n\t\t}\n\t\tS.erase(v);\n\t\tmark[v] = 1;\n\t\tif (v != src) {\n\t\t\tauto it = S.lower_bound(v);\n\t\t\tif (it == S.end())\n\t\t\t\tit = S.lower_bound(0);\n\t\t\tint nex = *it;\n\t\t\tdp[nex] = min(dp[nex], dp[v] + dis(v, nex));\n\t\t}\n\t\tfor (int i = 2 * n - 1; i >= 0; i--) {\n\t\t\tint v = i % n;\n\t\t\tif (!mark[v])\n\t\t\t\tgo[v] = v;\n\t\t\telse\n\t\t\t\tgo[v] = go[(v + 1) % n];\n\t\t}\n\t\tfor (auto [u, w] : g[v]) {\n\t\t\tint nex = go[(u + dp[v]) % n];\n\t\t\tdp[nex] = min(dp[nex], dp[v] + w + dis((u + dp[v]) % n, nex));\n\t\t}\n\t}\n}\n \nint main() {\n\tios_base::sync_with_stdio(false);\n\tint m;\n\tcin >> n >> m;\n\tfor (int i = 0; i < m; i++) { \n\t\tint v, u, w;\n\t\tcin >> v >> u >> w;\n\t\tg[v].push_back({u, w});\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tdijkstra(i);\n\t\tfor (int j = 0; j < n; j++)\n\t\t\tcout << dp[j] << \" \\n\"[j == n-1];\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "shortest paths"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1528",
    "index": "E",
    "title": "Mashtali and Hagh Trees",
    "statement": "Today is Mashtali's birthday! He received a \\textbf{Hagh} tree from Haj Davood as his birthday present!\n\nA directed tree is called a \\textbf{Hagh} tree iff:\n\n- The length of the longest directed path in it is exactly $n$.\n- Every vertex has \\textbf{at most three edges} attached to it independent of their orientation.\n- Let's call vertices $u$ and $v$ friends if one of them has a directed path to the other. For every pair of vertices $u$ and $v$ that are not friends, there should exist a vertex $w$ that is friends with both $u$ and $v$ (a mutual friend).\n\nAfter opening his gift, Mashtali found out that the labels on the vertices were gone.\n\nImmediately, he asked himself: how many different unlabeled Hagh trees are there? That is, how many possible trees could he have received as his birthday present?\n\nAt the first glance, the number of such trees seemed to be infinite since there was no limit on the number of vertices; but then he solved the problem and proved that \\textbf{there's a finite number of unlabeled Hagh trees!}\n\nAmazed by this fact, he shared the task with you so that you could enjoy solving it as well. Since the answer can be rather large he asked you to find the number of different unlabeled Hagh trees modulo $998244353$.\n\nHere two trees are considered different, if they are not isomorphic: if there is no way to map nodes of one tree to the second tree, so that edges are mapped to edges preserving the orientation.\n\nSome examples for $n = 2$:\n\nDirected trees $D$ and $E$ are Hagh. $C$ is not Hagh because it has a vertex with $4$ edges attached to it. $A$ and $B$ are not Hagh because their longest directed paths are not equal to $n$. Also in $B$ the leftmost and rightmost vertices are not friends neither do they have a mutual friend.",
    "tutorial": "Let $dp_i$ be the answer for all trees such that there exists a root and all edges are directed in the same direction from root and the root has at most $2$ children. We transition: $dp_i = dp_{i-1}+dp_{i-1} \\cdot pdp_{i-2}+\\frac{dp_{i-1} \\cdot (dp_{i-1}+1)}{2}$ where $pdp_i = \\sum_{j = 0}^{i}{dp_j}$. Then let $dp2_i$ be the same as $dp_i$ except the root must have exactly $2$ children. So $dp2_i = dp_i-dp_{i-1}$. The answer for these cases is: $2 \\cdot (dp_n+\\frac{ dp_{n-1} \\cdot pdp_{n-2} \\cdot (pdp_{n-2}+1)}{2}+\\frac{pdp_{n-2} \\cdot dp_{n-1} \\cdot (dp_{n-1}+1)}{2}+ \\frac{dp_{n-1} \\cdot (dp_{n-1}+1) \\cdot (dp_{n-1}+2)}{6})-1$. This is because $dp_n$ holds the answer for at most $2$ children and the other section accounts for the rest. We multiply by $2$ to account for both edges directions, and subtract $1$ because a single path is isomorphic. This obviously doesn't handle all cases, but all other cases can be found in the following form. Let $t_{up,k}$ be a tree where the root has $2$ children and the edges are directed up and the longest path is $k$, and let $t_{down,k}$ be a tree where the root has $2$ children and the edges are directed down and the longest path is $k$. Then all other cases are $t_{up,k}$ which exists on some path of length $l$ to and connects to $t_{down,n-k-l}$. We can count every other case as $\\sum_{i=0}^{n-1}{(dp_{i}-1) \\cdot dp2_{n-1-i}}$ This works because we pretend the path is always length $1$, then if we do $dp_i \\cdot dp2_{n-1-i}$ we handle all cases except for when the $t_{up,k}$ is empty, and that only happens once.",
    "code": "#include <bits/stdc++.h>\n#pragma GCC optimize (\"O2,unroll-loops\")\n//#pragma GCC optimize(\"no-stack-protector,fast-math\")\n \nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<pii, int> piii;\ntypedef pair<ll, ll> pll;\n#define debug(x) cerr<<#x<<'='<<(x)<<endl;\n#define debugp(x) cerr<<#x<<\"= {\"<<(x.first)<<\", \"<<(x.second)<<\"}\"<<endl;\n#define debug2(x, y) cerr<<\"{\"<<#x<<\", \"<<#y<<\"} = {\"<<(x)<<\", \"<<(y)<<\"}\"<<endl;\n#define debugv(v) {cerr<<#v<<\" : \";for (auto x:v) cerr<<x<<' ';cerr<<endl;}\n#define all(x) x.begin(), x.end()\n#define pb push_back\n#define kill(x) return cout<<x<<'\\n', 0;\n \nconst int inf=1000000010;\nconst ll INF=1000000000000001000LL;\nconst int mod=998244353, inv6=166374059;\nconst int MAXN=1000010, LOG=20;\n \nll n, m, k, u, v, x, y, t, a, b, ans;\nll dp[MAXN], ps[MAXN];\nll pd[MAXN], sp[MAXN];\n \nll C3(ll x){\n\treturn x*(x-1)%mod*(x-2)%mod*inv6%mod;\n}\nll C2(ll x){\n\treturn x*(x-1)/2%mod;\n}\n \nint main(){\n\tios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\t//freopen(\"input.txt\", \"r\", stdin);\n\t//freopen(\"output.txt\", \"w\", stdout);\n\tcin>>n;\n\tdp[0]=ps[0]=1;\n\tpd[0]=sp[0]=1;\n\tfor (int i=1; i<=n; i++){\n\t\tps[i]=(1 + ps[i-1] + ps[i-1]*(ps[i-1]+1)/2)%mod;\n\t\tdp[i]=ps[i]-ps[i-1];\n\t\tpd[i]=dp[i]-dp[i-1];\n\t\tsp[i]=(sp[i-1]+pd[i])%mod;\n\t}\n\tfor (int i=0; i<n; i++) ans=(ans + pd[i]*sp[n-1-i])%mod;\n\t\n\tans=(ans + 2*C3(ps[n-1]+2))%mod;\n\tif (n>=2) ans=(ans - 2*C3(ps[n-2]+2))%mod;\n\t\n\tans=(ans + 2*C2(ps[n-1]+1))%mod;\n\tif (n>=2) ans=(ans - 2*C2(ps[n-2]+1))%mod;\n\t\n\tif (ans<0) ans+=mod;\n\tcout<<ans<<\"\\n\";\n\t\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1528",
    "index": "F",
    "title": "AmShZ Farm",
    "statement": "To AmShZ, all arrays are equal, but some arrays are \\textbf{more-equal} than others. Specifically, the arrays consisting of $n$ elements from $1$ to $n$ that can be turned into permutations of numbers from $1$ to $n$ by adding a non-negative integer to each element.\n\nMashtali \\sout{who wants to appear in every problem statement} thinks that an array $b$ consisting of $k$ elements is compatible with a \\textbf{more-equal} array $a$ consisting of $n$ elements if for each $1 \\le i \\le k$ we have $1 \\le b_i \\le n$ and also $a_{b_1} = a_{b_2} = \\ldots = a_{b_k}$.\n\nFind the number of pairs of arrays $a$ and $b$ such that $a$ is a more-equal array consisting of $n$ elements and $b$ is an array compatible with $a$ consisting of $k$ elements modulo $998244353$.\n\nNote that the elements of $b$ are \\textbf{not necessarily distinct}, same holds for $a$.",
    "tutorial": "Consider the following problem: $n$ cars want to enter a parking lot one by one. The parking lot has $n$ slots numbered $1, 2 , \\ldots , n$, the $i$-th of the $n$ cars wants to park in the $a_i$-th slot. When the $i$-th car drives in, it will park in the first empty slot $s$ such that $s \\ge a_i$. An array $a$ is Good if all of the cars are parked in some slot after the end of the procedure. Good arrays can be mapped to more-equal arrays, because it can be proved that in any sorted Good array $a_i \\le i$, same goes for the more-equal arrays. Now let's modify the above problem a bit, consider a circular parking lot with $n + 1$ free slots. $n$ cars want to park in it, $i$-th of which wants to park in the $a_i$-th slot $(1 \\le a_i \\le n + 1)$. When the $i$-th car drives in, it will park in the first empty slot $s$ such that $s$ is the first empty slot after (including) $a_i$ in the clockwise direction. It's obvious that one slot will be empty after the end of the procedure, let's call this slot $x$. Arrays in which $x = n+1$ can also be mapped to more-equal arrays, let them be good arrays. let the other arrays be called bad arrays (arrays in which $x \\neq n+1$). Every good can mapped to $n$ bad arrays, just add $x$ $(1 \\le x \\le n)$ to all of elements of $a$, formally speaking for each $i$ $(1 \\le i \\le n)$, $a_i = ((a_i + x )\\mod_{n + 1} + 1)$. This can also be viewed as a circular shift of the elements/final positions. Note that the number of arrays compatible with $a$ stays the same in this proccess. Thus the number of bad arrays is equal to $\\frac{n}{n+1}$ of all the possible $(n + 1)^n$ arrays. We know that $a_{b_1} = a_{b_2} = \\ldots = a_{b_k}$, assume $a_{b_1} = x$, let's fix $x$ $(1 \\le x \\le n+1)$, let $CNT$ be the number of occurrences of $x$ in $a$. The number of compatible arrays $b$ such that $a_{b_j} = x$ $(1 \\le j \\le k)$ is equal to $CNT^k$. So the number of pairs of arrays $a$ and $b$ where $b$ is a compatible array with the more-equal array $a$ is equal to $\\sum_{CNT = 0}^{n}{{n}\\choose{CNT}} \\cdot n^{n-CNT} \\cdot CNT^k$. There are $n+1$ ways to choose $x$, also we had to divide the result by $n + 1$ because we were previously counting bad arrays as well, so we can simplify both of this terms with each other. The sum $\\sum_{CNT = 0}^{n}{{n}\\choose{CNT}} \\cdot n^{n-CNT} \\cdot CNT^k$ mentioned above is equal to $\\sum_{i = 1}^{k}{S(k , i) \\cdot i! \\cdot {{n}\\choose{i}} \\cdot (n+1)^{(n-i)}}$, where $S$ refers to Stirling numbers of the second kind. All of $S(k , i)$ can be found in $\\mathcal{O}(k\\log k)$ using FFT. So overall we can solve the task in $\\mathcal{O}(k\\log k)$.",
    "code": "# include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long                                        ll;\ntypedef long double                                      ld;\ntypedef pair <int, int>                                  pii;\ntypedef pair <pii, int>                                  ppi;\ntypedef pair <int, pii>                                  pip;\ntypedef pair <pii, pii>                                  ppp;\ntypedef pair <ll, ll>                                    pll;\n \n# define A                                               first\n# define B                                               second\n# define endl                                            '\\n'\n# define sep                                             ' '\n# define all(x)                                          x.begin(), x.end()\n# define kill(x)                                         return cout << x << endl, 0\n# define SZ(x)                                           int(x.size())\n# define lc                                              id << 1\n# define rc                                              id << 1 | 1\n# define InTheNameOfGod                                  ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);\n \nll power(ll a, ll b, ll md) {return (!b ? 1 : (b & 1 ? a * power(a * a % md, b / 2, md) % md : power(a * a % md, b / 2, md) % md));}\n \nconst int xn = 3e5 + 10;\nconst int xm = 18;\nconst int sq = 320;\nconst int inf = 1e9 + 10;\nconst ll INF = 1e18 + 10;\nconst int mod = 998244353;\nconst int base = 257;\n \nint n, k, C[xn], ans, A[xn], B[xn], rev[xn];\nint fact[xn], ifact[xn];\n \nvoid NTT(int *A, bool inv){\n\tint n = (1 << xm);\n\tfor (int i = 0; i < (1 << xm); ++ i)\n\t\tif (rev[i] < i)\n\t\t\tswap(A[i], A[rev[i]]);\n\tfor (int ln = 1; ln < n; ln <<= 1){\n\t\tint w = power(3, mod / 2 / ln, mod);\n\t\tif (inv)\n\t\t\tw = power(w, mod - 2, mod);\n\t\tfor (int i = 0; i < n; i += ln + ln){\n\t\t\tint wn = 1;\n\t\t\tfor (int j = i; j < i + ln; ++ j){\n\t\t\t\tint x = A[j], y = 1ll * A[j + ln] * wn % mod;\n\t\t\t\tA[j] = (x + y) % mod;\n\t\t\t\tA[j + ln] = (x - y + mod) % mod;\n\t\t\t\twn = 1ll * wn * w % mod;\n\t\t\t}\n\t\t}\n\t}\n\tif (inv){\n\t\tint invn = power(1 << xm, mod - 2, mod);\n\t\tfor (int i = 0; i < n; ++ i)\n\t\t\tA[i] = 1ll * A[i] * invn % mod;\n\t}\n}\n \nint main(){\n\tInTheNameOfGod;\n\t\n\tcin >> n >> k;\n\tC[0] = fact[0] = 1;\n\tfor (int i = 1; i < xn; ++ i){\n\t\tC[i] = 1ll * C[i - 1] * (n - i + 1) % mod * power(i, mod - 2, mod) % mod;\n\t\tfact[i] = 1ll * fact[i - 1] * i % mod;\n\t}\n\tifact[xn - 1] = power(fact[xn - 1], mod - 2, mod);\n\tfor (int i = xn - 2; i >= 0; -- i)\n\t\tifact[i] = 1ll * ifact[i + 1] * (i + 1) % mod;\n\tfor (int i = 1; i < (1 << xm); ++ i)\n\t\trev[i] = (rev[i >> 1] >> 1) | ((i & 1) << (xm - 1));\n\tfor (int i = 0; i <= k; ++ i){\n\t\tA[i] = 1ll * power(i, k, mod) * ifact[i] % mod;\n\t\tB[i] = ifact[i];\n\t\tif (i % 2)\n\t\t\tB[i] = (mod - B[i]) % mod;\n\t}\n\tNTT(A, 0), NTT(B, 0);\n\tfor (int i = 0; i < xn; ++ i)\n\t\tA[i] = 1ll * A[i] * B[i] % mod;\n\tNTT(A, 1);\n\tfor (int i = 1; i <= k; ++ i)\n\t\tans = (ans + 1LL * A[i] * C[i] % mod * power(n + 1, n - i, mod) % mod * fact[i] % mod) % mod;\n\tcout << ans << endl;\n \n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "fft",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1529",
    "index": "A",
    "title": "Eshag Loves Big Arrays",
    "statement": "Eshag has an array $a$ consisting of $n$ integers.\n\nEshag can perform the following operation any number of times: choose some subsequence of $a$ and delete every element from it which is \\textbf{strictly} larger than $AVG$, where $AVG$ is the average of the numbers in the chosen subsequence.\n\nFor example, if $a = [1 , 4 , 3 , 2 , 4]$ and Eshag applies the operation to the subsequence containing $a_1$, $a_2$, $a_4$ and $a_5$, then he will delete those of these $4$ elements which are larger than $\\frac{a_1+a_2+a_4+a_5}{4} = \\frac{11}{4}$, so after the operation, the array $a$ will become $a = [1 , 3 , 2]$.\n\nYour task is to find the \\textbf{maximum} number of elements Eshag can delete from the array $a$ by applying the operation described above some number (maybe, zero) times.\n\nA sequence $b$ is a subsequence of an array $c$ if $b$ can be obtained from $c$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "We state that every element except for the elements with the smallest value can be deleted. Proof: denote $MN$ as the minimum element (s) of the array $a$, in each operation pick $MN$ and some other element, say $X$, which is bigger than $MN$, since $AVG = \\frac{X + MN}{2} < X$, then $X$ will be deleted. Doing this for every $X > MN$ will result in the deletion of every element except for the elements with the smallest value. So the answer to the problem is $n - cntMN$, where $cntMN$ is the number of times $MN$ appeared in $a$. complexity: $\\mathcal{O}(n)$",
    "code": "// khodaya khodet komak kon\n# include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long                                        ll;\ntypedef long double                                      ld;\ntypedef pair <int, int>                                  pii;\ntypedef pair <pii, int>                                  ppi;\ntypedef pair <int, pii>                                  pip;\ntypedef pair <pii, pii>                                  ppp;\ntypedef pair <ll, ll>                                    pll;\n \n# define A                                               first\n# define B                                               second\n# define endl                                            '\\n'\n# define sep                                             ' '\n# define all(x)                                          x.begin(), x.end()\n# define kill(x)                                         return cout << x << endl, 0\n# define SZ(x)                                           int(x.size())\n# define lc                                              id << 1\n# define rc                                              id << 1 | 1\n \nll power(ll a, ll b, ll md) {return (!b ? 1 : (b & 1 ? a * power(a * a % md, b / 2, md) % md : power(a * a % md, b / 2, md) % md));}\n \nconst int xn = 1e2 + 10;\nconst int sq = 320;\nconst int inf = 1e9 + 10;\nconst ll INF = 1e18 + 10;\nconst int mod = 1e9 + 7;//998244353;\nconst int base = 257;\n \nint qq, n, a[xn], mn, ans;\n \nint main(){\n\tios::sync_with_stdio(0);cin.tie(0); cout.tie(0);\n\tcin >> qq;\n\twhile (qq --){\n\t\tcin >> n, mn = inf, ans = 0;\n\t\tfor (int i = 1; i <= n; ++ i)\n\t\t\tcin >> a[i], mn = min(mn, a[i]);\n\t\tfor (int i = 1; i <= n; ++ i)\n\t\t\tans += a[i] != mn;\n\t\tcout << ans << endl;\n\t}\n \n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1529",
    "index": "B",
    "title": "Sifid and Strange Subsequences",
    "statement": "A sequence $(b_1, b_2, \\ldots, b_k)$ is called \\textbf{strange}, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $(i, j)$ with $1 \\le i<j \\le k$, we have $|a_i-a_j|\\geq MAX$, where $MAX$ is the largest element of the sequence. In particular, any sequence of length at most $1$ is strange.\n\nFor example, the sequences $(-2021, -1, -1, -1)$ and $(-1, 0, 1)$ are strange, but $(3, 0, 1)$ is not, because $|0 - 1| < 3$.\n\nSifid has an array $a$ of $n$ integers. Sifid likes everything big, so among all the strange subsequences of $a$, he wants to find the length of the \\textbf{longest} one. Can you help him?\n\nA sequence $c$ is a subsequence of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "It's easy to prove that a strange subsequence can't contain more than one positive element. So it's optimal to pick all of the non-positive elements, now we can pick at most one positive element. Assume $x$ is the minimum positive element in the array. We can pick $x$ if no two elements in the already picked set such as $a$ and $b$ exist in a way that $|a - b| < x$. To check this, we just have to sort the already picked elements and see the difference between adjacent pairs. complexity: $\\mathcal{O}(n\\log n)$",
    "code": "// khodaya khodet komak kon\n// Nightcall - London Grammer\n# include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long                                        ll;\ntypedef long double                                      ld;\ntypedef pair <int, int>                                  pii;\ntypedef pair <pii, int>                                  ppi;\ntypedef pair <int, pii>                                  pip;\ntypedef pair <pii, pii>                                  ppp;\ntypedef pair <ll, ll>                                    pll;\n \n# define A                                               first\n# define B                                               second\n# define endl                                            '\\n'\n# define sep                                             ' '\n# define all(x)                                          x.begin(), x.end()\n# define kill(x)                                         return cout << x << endl, 0\n# define SZ(x)                                           int(x.size())\n# define lc                                              id << 1\n# define rc                                              id << 1 | 1\n \nll power(ll a, ll b, ll md) {return (!b ? 1 : (b & 1 ? a * power(a * a % md, b / 2, md) % md : power(a * a % md, b / 2, md) % md));}\n \nconst int xn = 1e5 + 10;\nconst int xm = - 20 + 10;\nconst int sq = 320;\nconst int inf = 1e9 + 10;\nconst ll INF = 1e18 + 10;\nconst int mod = 1e9 + 7;//998244353;\nconst int base = 257;\n \nint qq, n, a[xn], ans, mn;\nbool flag;\n \nint main(){\n\tios::sync_with_stdio(0);cin.tie(0); cout.tie(0);\n \n\tcin >> qq;\n\twhile (qq --){\n\t\tcin >> n, ans = 0;\n\t\tfor (int i = 1; i <= n; ++ i)\n\t\t\tcin >> a[i], ans += (a[i] <= 0);\n\t\tsort(a + 1, a + n + 1), mn = inf;\n\t\tfor (int i = 1; i <= n; ++ i)\n\t\t\tif (a[i] > 0)\n\t\t\t\tmn = min(mn, a[i]);\n\t\tflag = (mn < inf);\n\t\tfor (int i = 2; i <= n; ++ i)\n\t\t\tif (a[i] <= 0)\n\t\t\t\tflag &= (a[i] - a[i - 1] >= mn);\n\t\tif (flag)\n\t\t\tcout << ans + 1 << endl;\n\t\telse\n\t\t\tcout << ans << endl;\n\t}\n \n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1530",
    "index": "A",
    "title": "Binary Decimal",
    "statement": "Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $0$ or $1$. For example, $1\\,010\\,111$ is a binary decimal, while $10\\,201$ and $787\\,788$ are not.\n\nGiven a number $n$, you are asked to represent $n$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.",
    "tutorial": "Let $d$ be the largest decimal digit of $n$. Note that we need at least $d$ binary decimals to represent $n$ as a sum. Indeed, if we only use $k < d$ binary decimals, no digit of the sum will ever exceed $k$. However, we need at least one digit equal to $d$. At the same time, it is easy to construct an answer with exactly $d$ terms. Start with all terms equal to $0$, and consider each digit separately. Let the $i$-th digit of $n$ be $a_i$. Pick any $a_i$ terms out of the $d$ terms we have, and add $1$ to their $i$-th digits. Therefore, the answer is $d$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1530",
    "index": "B",
    "title": "Putting Plates",
    "statement": "To celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.\n\nThe table can be represented as a rectangle with height $h$ and width $w$, divided into $h \\times w$ cells. Let $(i, j)$ denote the cell in the $i$-th row and the $j$-th column of the rectangle ($1 \\le i \\le h$; $1 \\le j \\le w$).\n\nInto each cell of the table you can either put a plate or keep it empty.\n\nAs each guest has to be seated next to their plate, you can only put plates on the edge of the table — into the first or the last row of the rectangle, or into the first or the last column. Formally, for each cell $(i, j)$ you put a plate into, at least one of the following conditions must be satisfied: $i = 1$, $i = h$, $j = 1$, $j = w$.\n\nTo make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if cell $(i, j)$ contains a plate, you can't put plates into cells $(i - 1, j)$, $(i, j - 1)$, $(i + 1, j)$, $(i, j + 1)$, $(i - 1, j - 1)$, $(i - 1, j + 1)$, $(i + 1, j - 1)$, $(i + 1, j + 1)$.\n\nPut as many plates on the table as possible without violating the rules above.",
    "tutorial": "There are many ways to solve this problem and even more ways to get it accepted. Let's consider a provable solution that minimizes the amount of casework. We'll call a valid solution optimal if it has the largest possible number of plates. Claim. There exists an optimal solution that contains a plate in every corner of the table. Proof. Consider any optimal solution, and consider all four corners one-by-one in any order. If a corner contains a plate, do nothing. If a corner doesn't contain a plate, but either of its neighbors does, move the plate from the neighbor to the corner. Note that we'll still obtain a valid optimal solution. If neither a corner nor any of its neighbors contain a plate, we can put a plate into the corner, increasing the number of plates and contradicting the optimality of our solution. Thus, this case is impossible. After considering all four corners, we'll obtain an optimal solution with a plate in every corner of the table, as desired. $\\blacksquare$ Once we put a plate in every corner, four sides of the table don't interact anymore, and we can solve the problem on each side independently. Putting as many plates as possible on one side is easy: just leave one empty cell between neighboring plates, and maybe leave two empty cells at the end if the length of the side is even.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1530",
    "index": "C",
    "title": "Pursuit",
    "statement": "You and your friend Ilya are participating in an individual programming contest consisting of multiple stages. A contestant can get between $0$ and $100$ points, inclusive, for each stage, independently of other contestants.\n\nPoints received by contestants in different stages are used for forming overall contest results. Suppose that $k$ stages of the contest are completed. For each contestant, $k - \\lfloor \\frac{k}{4} \\rfloor$ stages with the highest scores are selected, and these scores are added up. This sum is the overall result of the contestant. (Here $\\lfloor t \\rfloor$ denotes rounding $t$ down.)\n\nFor example, suppose $9$ stages are completed, and your scores are $50, 30, 50, 50, 100, 10, 30, 100, 50$. First, $7$ stages with the highest scores are chosen — for example, all stages except for the $2$-nd and the $6$-th can be chosen. Then your overall result is equal to $50 + 50 + 50 + 100 + 30 + 100 + 50 = 430$.\n\nAs of now, $n$ stages are completed, and you know the points you and Ilya got for these stages. However, it is unknown how many more stages will be held. You wonder what the smallest number of additional stages is, after which your result might become greater than or equal to Ilya's result, at least in theory. Find this number!",
    "tutorial": "The first thing to notice is that since we're chasing Ilya and we want to reach his score as soon as possible, it only makes sense to add $100$'s to our scores and $0$'s to his. We can also notice that the answer never exceeds $n$. No matter how bad a stage is for us in terms of points, adding a single stage where we score $100$ and Ilya scores $0$ \"compensates\" it. In particular, in the worst case, when all $a_i = 0$ and all $b_i = 100$, the answer is exactly $n$. However, if we just add the $100/0$ stages one-by-one and calculate the overall results from scratch every time, our solution will have $O(n^2)$ complexity and that's too much. There are many ways to optimize the solution. One of them is to transform the given $a$ and $b$ arrays into arrays of length $101$, containing the count of each score (since we are not interested in the order of the scores). Let $m = 100$ be the maximum achievable score in a stage. Using the transformed arrays, we can calculate the overall scores in $O(m)$ instead of $O(n)$, to lower the final complexity to $O(mn)$. Alternatively, notice that when we add $100$ to our scores, it just adds $100$ to our overall score except for the case when the total number of completed stages becomes divisible by $4$, when we also need to subtract the score of the worst currently included stage from the sum. We can similarly handle adding $0$ to Ilya's scores. If we sort all our and Ilya's scores at the beginning and maintain a pointer to the current worst included stage in both scoresheets, we can add a new $100/0$ stage and recalculate the totals in $O(1)$. Finally, we can also notice that whenever adding $k$ stages works for us, adding $k+1$ stages will work too. Thus, we can use binary search on $k$. We can easily check a single value of $k$ in $O(n)$ or $O(n \\log n)$, resulting in $O(n \\log n)$ or $O(n \\log^2 n)$ time complexity.",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1530",
    "index": "D",
    "title": "Secret Santa",
    "statement": "Every December, VK traditionally holds an event for its employees named \"Secret Santa\". Here's how it happens.\n\n$n$ employees numbered from $1$ to $n$ take part in the event. Each employee $i$ is assigned a different employee $b_i$, to which employee $i$ has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all $b_i$ must be distinct integers between $1$ and $n$, and for any $i$, $b_i \\ne i$ must hold.\n\nThe assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee $i$ has said that they wish to make a gift to employee $a_i$.\n\nFind a valid assignment $b$ that maximizes the number of fulfilled wishes of the employees.",
    "tutorial": "Let $m$ be the number of different values among $a_i$ (that is, the number of distinct employees someone wishes to make a gift to). It's easy to see that the answer, $k$, can not exceed $m$: each employee mentioned in $a_i$ allows us to fulfill at most one wish. It turns out that $k$ can always be equal to $m$, and here's how. We can visualize the problem in terms of graphs. We are given a functional graph $G$ (for each $i$, there is an edge from $i$ to $a_i$), and we need to find a directed graph that consists of cycles of length at least $2$ and shares as many edges with $G$ as possible. For each vertex in $G$ that has at least one incoming edge, keep any of these edges and remove the others. Now every vertex has outdegree at most $1$ and indegree at most $1$. Hence, our graph becomes a collection of paths and cycles (isolated vertices are considered to be paths of length $0$). Let the paths be $P_1, P_2, \\ldots, P_t$. For each $i = 1 \\ldots t$, create an edge from the end of path $P_i$ to the beginning of path $P_{i \\bmod t + 1}$. That is, we are forming a single loop out of all the paths. This will always work except for one case: if the new loop we are forming has length $1$. It means that we have a single isolated vertex $v$, and all other vertices form valid cycles. If we ever arrive at this case, we can pick the initial edge going from $v$ to $a_v$, return it to the graph, and remove the other edge going from some vertex $u$ into $a_v$ that we kept. This will break the cycle containing vertex $a_v$ without changing the number of edges shared with the initial graph. Finally, add an edge from $u$ to $v$ closing the cycle, and that will give us a correct answer. Alternatively, to not ever arrive at the bad case, we can use the knowledge of our future selves at the earlier stage of choosing the edges to keep and remove, and prioritize keeping edges going from vertices with indegree $0$. Finally, randomized solutions are also possible. For example, we can select the edges to keep at random, write down the sets of vertices with indegree $0$ and vertices with outdegree $0$, shuffle both sets, and try to create an edge from the $i$-th vertex of one set to the $i$-th vertex of the other one. If we fail, and that can only happen when we try to create an edge from a vertex to self, we just start the process from scratch. With an argument similar to counting derangements, it can be shown that the expected number of iterations until we find a correct answer is constant.",
    "tags": [
      "constructive algorithms",
      "flows",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1530",
    "index": "E",
    "title": "Minimax",
    "statement": "Prefix function of string $t = t_1 t_2 \\ldots t_n$ and position $i$ in it is defined as the length $k$ of the longest proper (not equal to the whole substring) prefix of substring $t_1 t_2 \\ldots t_i$ which is also a suffix of the same substring.\n\nFor example, for string $t = $ abacaba the values of the prefix function in positions $1, 2, \\ldots, 7$ are equal to $[0, 0, 1, 0, 1, 2, 3]$.\n\nLet $f(t)$ be equal to the maximum value of the prefix function of string $t$ over all its positions. For example, $f($abacaba$) = 3$.\n\nYou are given a string $s$. Reorder its characters arbitrarily to get a string $t$ (the number of occurrences of any character in strings $s$ and $t$ must be equal). The value of $f(t)$ must be minimized. Out of all options to minimize $f(t)$, choose the one where string $t$ is the lexicographically smallest.",
    "tutorial": "This problem required careful case analysis. First of all, if all characters of $s$ are the same, there is nothing to reorder: $t = s$, and $f(t) = |t| - 1$. Second, if the first character of $t$ appears somewhere else in the string, $f(t) \\ge 1$. Otherwise, $f(t) = 0$. Thus, if some character has only one occurrence in $s$, choose the smallest such character and put it at the front of $t$, followed by all the remaining characters of $s$ in alphabetical order. That's the lexicographically smallest way to obtain $f(t) = 0$. Otherwise, if all characters have at least two occurrences in $s$, we can always reach $f(t) = 1$. The easiest way to construct such $t$ is to choose any character, put one of its occurrences at the front of $t$, put the remaining occurrences at the back of $t$, and put the rest of the characters in-between ordered arbitrarily. However, we have to minimize $t$ lexicographically. First, we have to put the smallest character of $s$ at the front of $t$, say, a. Then, let's try to follow it with the same character. In this case, $t$ starts with aa, and we can't have another occurrence of aa anywhere in $t$, as we aim at $f(t) = 1$, which means that at most half of the letters (approximately) can be equal to a. The exact condition of whether we can start with aa is: the number of occurrences of a in $s$ must not exceed $\\frac{|s|}{2} + 1$. If this is the case, the lexicographically smallest $t$ we can form will look like aabababacacadddeeefffff. If $t$ starts with a, but can not start with aa, let's find the second smallest character in $s$, say, b, and start $t$ with ab. Now we are not allowed to have ab anywhere else in $t$. There are two (final) cases: if $s$ doesn't have any other characters except a and b, we have to put all the remaining b's in front of all a's. The smallest $t$ will look like abbbbbbbaaaaaaaaaaaaa. otherwise, find the third smallest character in $s$, say, c. We can now afford putting all a's after the ab prefix if we follow these a's with c. The smallest $t$ will look like abaaaaaaaaaaacbbbcddd. It's possible to consider less cases if you implement a function that checks if a prefix of $t$ can be finished with the remaining characters of $s$ to obtain $f(t) = 1$. Then $t$ can be formed character-by-character from left to right. This approach still requires care, though.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1530",
    "index": "F",
    "title": "Bingo",
    "statement": "Getting ready for VK Fest 2021, you prepared a table with $n$ rows and $n$ columns, and filled each cell of this table with some event related with the festival that could either happen or not: for example, whether you will win a prize on the festival, or whether it will rain.\n\nForecasting algorithms used in VK have already estimated the probability for each event to happen. Event in row $i$ and column $j$ will happen with probability $a_{i, j} \\cdot 10^{-4}$. All of the events are mutually independent.\n\nLet's call the table winning if there exists a line such that all $n$ events on it happen. The line could be any horizontal line (cells $(i, 1), (i, 2), \\ldots, (i, n)$ for some $i$), any vertical line (cells $(1, j), (2, j), \\ldots, (n, j)$ for some $j$), the main diagonal (cells $(1, 1), (2, 2), \\ldots, (n, n)$), or the antidiagonal (cells $(1, n), (2, n - 1), \\ldots, (n, 1)$).\n\nFind the probability of your table to be winning, and output it modulo $31\\,607$ (see Output section).",
    "tutorial": "Let $l_1, l_2, \\ldots, l_{2n+2}$ denote the $2n+2$ possible lines that can be formed. Let $L_i$ denote the event that line $l_i$ is formed, and $\\overline{L_i}$ denote the event that line $l_i$ is not formed (i.e., $P(L_i) + P(\\overline{L_i}) = 1$). Let's find the probability that our table is not winning. It is equal to $P(\\overline{L_1} \\cap \\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}})$. Note that the following two statements are true: $P(\\overline{L_1} \\cap \\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}}) + P(L_1 \\cap \\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}}) = P(\\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}})$; $P(L_1 \\cap \\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}}) = P(\\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}} | L_1) \\cdot P(L_1)$. The first one follows from the law of total probability, and the second one follows from the definition of conditional probability. These two statements combined allow us to use the following formula: $P(\\overline{L_1} \\cap \\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}}) = P(\\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}}) - P(\\overline{L_2} \\cap \\ldots \\cap \\overline{L_{2n+2}} | L_1) \\cdot P(L_1)$. We can apply this formula recursively. Specifically, we can make a function $f(i, S)$, where $S = \\{s_1, s_2, \\ldots, s_k\\}$ is a subset of $\\{1, 2, \\ldots, i-1\\}$, which calculates $P(\\overline{L_i} \\cap \\overline{L_{i+1}} \\cap \\ldots \\cap \\overline{L_{2n+2}} | L_{s_1} \\cap \\ldots \\cap L_{s_k})$. For $i = 2n+3$, $f(i, S) = 1$, and for $i \\le 2n+2$ we can generalize the formula above as follows: $f(i, S) = f(i + 1, S) - f(i + 1, S \\cup \\{i\\}) \\cdot P(L_i | L_{s_1} \\cap \\ldots \\cap L_{s_k})$. Here, $P(L_i | L_{s_1} \\cap \\ldots \\cap L_{s_k})$ is the probability that line $l_i$ is formed given that lines $l_{s_1}, \\ldots, l_{s_k}$ are formed. This is equal to the product of probabilities of all cells belonging to $l_i$ which do not belong to any of $l_{s_1}, \\ldots, l_{s_k}$. The answer to the problem, i.e. the probability that our table is winning, is $1 - f(1, \\{\\})$. This allows us to implement an $O(2^{2n} \\cdot n)$ solution, which is too slow. In fact, this solution is equivalent to applying inclusion-exclusion principle. To optimize this solution, note that once it becomes easy to calculate $f(i, S)$, we don't have to make any more recursive calls. Why would it become easy to calculate $f(i, S)$ though? Let's order the lines in such a way that $l_{n+3}, l_{n+4}, \\ldots, l_{2n+2}$ are the horizontal lines of the table. Consider a call of the form $f(n + 3, S)$. This call is basically asking: \"what is the probability that none of lines $l_{n+3}, l_{n+4}, \\ldots, l_{2n+2}$ are formed, given that lines $l_{s_1}, \\ldots, L_{s_k}$ are formed?\". Note that the horizontal lines are independent, and we can actually answer this question in $O(n^2)$. Specifically, for any horizontal line, the probability that it is not formed is $1$ minus the product of probabilities of all its cells not belonging to any of $l_{s_1}, \\ldots, l_{s_k}$. The overall value of $f(n + 3, S)$ is the product of probabilities for individual horizontal lines. This way, we have built an $O(2^n \\cdot n^2)$ solution. This might be fast enough depending on your implementation, but there are at least two ways to optimize it to $O(2^n \\cdot n)$: The first way is to maintain the products of probabilities of untouched cells for horizontal lines on the fly. For simplicity, assume that $l_1$ and $l_2$ are the diagonal lines. For each $i = 3, 4, \\ldots, n+2$, after we process (vertical) line $l_i$, we can update the products for all horizontal lines with the cells of $l_i$ (in $O(n)$), make a recursive call, and roll back the updates (in $O(n)$ again). Once we get to $i = n + 3$, instead of going through every cell of the table in $O(n^2)$, we can just multiply $n$ horizontal line products in $O(n)$. The second way is to define $g(i, mask)$ ($1 \\le i \\le n$; $mask$ is a bitmask of size $n$) to be the product of $a_{i, j}$ over all $j$ belonging to $mask$. All values of $g$ can be calculated in $O(2^n \\cdot n)$ using dynamic programming: $g(i, 0) = 1$, and $g(i, mask) = g(i, mask \\oplus 2^j) \\cdot a_{i, j}$, where $j$ is any bit set in $mask$. When we arrive at a $f(n + 3, S)$ call, for each of the $n$ horizontal lines, instead of going through its cells, we can construct the mask of cells the values in which we want to multiply, and use the corresponding value of $g$ in $O(1)$.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1530",
    "index": "G",
    "title": "What a Reversal",
    "statement": "You have two strings $a$ and $b$ of equal length $n$ consisting of characters 0 and 1, and an integer $k$.\n\nYou need to make strings $a$ and $b$ equal.\n\nIn one step, you can choose any substring of $a$ containing exactly $k$ characters 1 (and arbitrary number of characters 0) and reverse it. Formally, if $a = a_1 a_2 \\ldots a_n$, you can choose any integers $l$ and $r$ ($1 \\le l \\le r \\le n$) such that there are exactly $k$ ones among characters $a_l, a_{l+1}, \\ldots, a_r$, and set $a$ to $a_1 a_2 \\ldots a_{l-1} a_r a_{r-1} \\ldots a_l a_{r+1} a_{r+2} \\ldots a_n$.\n\nFind a way to make $a$ equal to $b$ using at most $4n$ reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.",
    "tutorial": "First of all, the number of 1's in $a$ and $b$ must match. Let $c$ be the number of 1's in $a$. If $k = 0$ or $k > c$, we can not do a meaningful reversal, so we just check if $a = b$. If $k = c$, we can not change the contents of $a$ between the leftmost and the rightmost 1's, we can only reverse it and shift with regard to the outside 0's. It's easy to check whether $a$ can become equal to $b$ then, and at most $2$ steps are required if so. Otherwise, suppose $0 < k < c$. Since our operations are reversible, we'll apply a usual trick: we'll transform both strings into some canonical representations in at most $2n$ steps each. If $a$'s and $b$'s canonical representations don't match, we'll prove that there is no solution. Otherwise, we can transform $a$ into $b$ in at most $4n$ steps: transform $a$ into the canonical representation, and then perform the steps transforming $b$ into the canonical representation, but in reverse order. What representation is canonical is for us to determine later. We'll focus on one string now. Let's write down the lengths of blocks of consecutive 0's in the string. Formally, let $p_0, p_1, p_2, \\ldots, p_c$ be the sequence consisting of the number of 0's: before the first 1, between the first and the second 1's, $\\ldots$, after the last 1. Note that some $p_i$ might be equal to $0$. What does a single reversal do to the sequence of blocks? $k+1$ consecutive blocks get reversed, and additionally, the 0's in the leftmost and the rightmost block of these $k+1$ blocks can be redistributed arbitrarily. It turns out that we don't need more than $k+2$ blocks to achieve our goal (we'll see that later), so let's start with the following. Let $p_i$ be the rightmost block such that $p_i > 0$. If $i \\le k+1$, stop. Otherwise, perform two reversals of blocks $p_{i-k}, p_{i-k+1}, \\ldots, p_i$, moving all the 0's from $p_i$ to $p_{i-k}$ in the process, effectively making $p_i$ zero, and repeat. After this process, only $p_0, p_1, \\ldots, p_{k+1}$ can still be non-zero. Now, consider what happens if we reverse $p_0, p_1, \\ldots, p_k$, and then reverse $p_1, p_2, \\ldots, p_{k+1}$ without changing any values: sequence $p_0, p_1, \\ldots, p_{k+1}$ will change to $p_k, p_{k+1}, p_0, p_1, \\ldots, p_{k-1}$, that is, will cyclically shift by two positions to the right. Suppose we repeat this pair of reversals $k+1$ times. The $k$-th ($0$-indexed) position initially contains $p_k$, after the first pair it will contain $p_{k-2}$, then $p_{k-4}$ and so on. Assume that $k$ is odd. Then every block will reach the $k$-th position at some point! Now, during the first reversal in the pair, let's move all 0's from the $k$-th block to the $0$-th block, and keep the second reversal in the pair as is, without changing the values. Then, after $k+1$ pairs of reversals, all the 0's will move to the $0$-th block, that is, all $p_1, p_2, \\ldots, p_{k+1}$ will become zero. We can for sure call this representation - with all of $p_1, p_2, \\ldots, p_c$ zeroed out, and $p_0$ equal to the number of 0's in the original string - canonical. It follows that if the number of 1's in $a$ and $b$ is equal to $c$, $k < c$ and $k$ is odd, a solution always exists. Let's move on to the case when $k$ is even. In this case, since a pair of reversals makes a cyclic shift by $2$, only even-numbered blocks will appear at the $k$-th position. However, notice that this is not a coincidence: when $k$ is even, whatever reversal we perform, even-numbered blocks only interact with even-numbered blocks, and odd-numbered blocks interact with odd-numbered blocks. In particular, the sum of $p_0, p_2, p_4, \\ldots$ can never change, and the sum of $p_1, p_3, p_5, \\ldots$ can never change either. Thus, when $k$ is even, let's call the following representation canonical: $p_0$ contains the sum of all initial values of $p_0, p_2, p_4, \\ldots$; $p_{k+1}$ contains the sum of all initial values of $p_1, p_3, p_5, \\ldots$; and all the other $p_i$'s are zeros. We can reach this representation in a similar way to the odd $k$ case, using pairs of reversals. Note that similar to the $k$-th position which contains blocks $p_k, p_{k-2}, p_{k-4}, \\ldots$ during the process, the $1$-st position contains blocks $p_1, p_{k+1}, p_{k-1}, p_{k-3}, \\ldots$ during the process. During the first reversal in each pair, as in the previous case, we'll move all the 0's from the $k$-th block to the $0$-th block. During the second reversal in each pair, we'll move all the 0's from the $1$-st block to the $k+1$-th block. After $k+1$ pairs of reversals (actually just $\\frac{k}{2}$ pairs are enough), we'll zero out all the values except for $p_0$ and $p_{k+1}$. All in all, we have found a way to reach the canonical representation in $2c \\le 2n$ steps, as desired.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1530",
    "index": "H",
    "title": "Turing's Award",
    "statement": "Alan Turing is standing on a tape divided into cells that is infinite in both directions.\n\nCells are numbered with consecutive integers from left to right. Alan is initially standing in cell $0$. Every cell $x$ has cell $x - 1$ on the left and cell $x + 1$ on the right.\n\nEach cell can either contain an integer or be empty. Initially all cells are empty.\n\nAlan is given a permutation $a_1, a_2, \\ldots, a_n$ of integers from $1$ to $n$ that was chosen \\textbf{uniformly at random} among all permutations of length $n$.\n\nAt time $1$, integer $a_1$ is written down into cell $0$ where Alan is located.\n\nAt each time $i$ from $2$ to $n$ inclusive, the following happens. First, Alan decides whether to stay in the same cell he's currently in, move to the neighboring cell on the left, or move to the neighboring cell on the right. After that, integer $a_i$ is written down into the cell where Alan is located. If that cell already contained some integer, the old integer is overwritten and irrelevant from that moment on.\n\nOnce $a_n$ is written down into some cell at time $n$, sequence $b$ of all integers contained in the cells from left to right is formed. Empty cells are ignored.\n\nTuring's award is equal to the length of the longest increasing subsequence of sequence $b$.\n\nHelp Alan and determine the largest possible value of his award if he acts optimally.",
    "tutorial": "Let's look at Alan's moves in reverse. The process can be reformulated as follows. Initially, $a_n$ is written down into the cell where Alan is located. Then, for each $i$ from $n-1$ down to $1$, first Alan decides whether to stay or move to a neighboring cell, and then $a_i$ is written down into Alan's cell only if the cell is empty. This way, it's easier to reason about the process since numbers never get overwritten. The state at any moment can be described by the current sequence $b$ and Alan's position inside this sequence. The only way we can change $b$ is by appending a number to either end. Suppose we have decided which elements of the permutation appear in the final sequence $b$, and for each element, whether it gets appended to the front or to the back. Let's call these elements useful. As a special case, $a_n$ is always useful. Two things to notice here: We don't care about intermediate Alan's positions, as long as he has enough time to move between consecutive useful elements. For example, suppose $a_i$ gets appended to the front of $b$ (the other case is symmetrical), and there are exactly $k$ useful elements among $a_i, a_{i+1}, \\ldots, a_n$. Let $a_j$ be the \"next\" useful element, that is, $j < i$ and there are no useful elements between $a_j$ and $a_i$. If $a_j$ should be appended to the front of $b$, Alan can just stay in the same cell for elements $a_{i-1}, a_{i-2}, \\ldots, a_{j+1}$, and then move to the left to append $a_j$. Here, Alan is always in time. If $a_j$ should be appended to the back of $b$, Alan has to move to the other end of $b$, and he needs to make $k$ steps to the right. This is possible if and only if $i - j \\ge k$. If $a_j$ should be appended to the front of $b$, Alan can just stay in the same cell for elements $a_{i-1}, a_{i-2}, \\ldots, a_{j+1}$, and then move to the left to append $a_j$. Here, Alan is always in time. If $a_j$ should be appended to the back of $b$, Alan has to move to the other end of $b$, and he needs to make $k$ steps to the right. This is possible if and only if $i - j \\ge k$. Consider a useful element that neither belongs to the LIS (longest increasing subsequence) of $b$, nor is $a_n$. We can always change this element's status to \"not useful\", and it won't harm us in any way. Thus, we can assume that all of the useful elements, except for maybe $a_n$, belong to the LIS. Let's casework on whether $a_n$ belongs to the LIS. From now on, we will assume that $a_n$ does belong to the LIS. However, the other case differs just slightly. Armed with the above observations, we can solve the problem using dynamic programming: $f_L(k, i)$: suppose $a_i$ is a useful element that gets appended to the front, and there are $k$ useful elements among $a_i, a_{i+1}, \\ldots, a_n$. Then $f_L(k, i)$ is the smallest possible value of the element at the back of the LIS. $f_R(k, i)$: suppose $a_i$ is a useful element that gets appended to the back, and there are $k$ useful elements among $a_i, a_{i+1}, \\ldots, a_n$. Then $f_R(k, i)$ is the largest possible value of the element at the front of the LIS. Note that some DP states might be unreachable: in this case, we set $f_L(\\ldots)$ to $+\\infty$ and $f_R(\\ldots)$ to $-\\infty$. Consider transitions from $f_L(k, i)$ (transitions from $f_R(k, i)$ are similar): For any $j < i$ such that $a_j < a_i$, we can set $f_L(k + 1, j)$ to $f_L(k, i)$. For any $j \\le i - k$ such that $a_j > f_L(k, i)$, we can set $f_R(k + 1, j)$ to $a_i$. Thus, we can transition from $f(k, \\ldots)$ to $f(k + 1, \\ldots)$ in $O(n^2)$ time. We can optimize it to $O(n \\log n)$ if we sweep through the permutation in reverse order ($i = n, n - 1, \\ldots, 1$) and maintain a segment tree for minimum/maximum indexed with element values. The answer to the problem is the largest $k$ such that $f_L(k, i)$ or $f_R(k, i)$ is a reachable state for some $i$. The complexity of our solution is thus $O(kn \\log n)$. Finally, note that the part of $b$ to the left of $a_n$ forms an increasing subsequence of $a$, and the part of $b$ to the right of $a_n$ forms a decreasing subsequence of $a$. It is well-known that the expected length of the longest increasing/decreasing subsequence in a random permutation is $O(\\sqrt{n})$. Therefore, our solution works in $O(n^{1.5} \\log n)$ on average.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1534",
    "index": "A",
    "title": "Colour the Flag",
    "statement": "Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).\n\nYou are given an $n \\times m$ grid of \"R\", \"W\", and \".\" characters. \"R\" is red, \"W\" is white and \".\" is blank. The neighbours of a cell are those that share an edge with it (those that only share a corner do not count).\n\nYour job is to colour the blank cells red or white so that every red cell only has white neighbours (and no red ones) and every white cell only has red neighbours (and no white ones). You are not allowed to recolour already coloured cells.",
    "tutorial": "Observe that there are only two valid grids, one where the top left cell is \"R\" and one where it's \"W\". We can just test those two grids and see if they conform with the requirements. Time complexity: $\\mathcal{O}(nm)$",
    "code": "#include <bits/stdc++.h>\n#define all(x) (x).begin(), (x).end()\n \n#ifdef LOCAL\ntemplate<typename T> void pr(T a){std::cerr<<a<<std::endl;}\ntemplate<typename T, typename... Args> void pr(T a, Args... args){std::cerr<<a<<' ',pr(args...);}\n#else\ntemplate<typename... Args> void pr(Args... args){}\n#endif\n \nusing namespace std;\nconst int MM = 55;\n \nint t, n, m;\nstring s[MM];\nchar cc[] = {'R', 'W'};\n \nint main(){\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tcin.exceptions(cin.failbit);\n\t\n\tcin>>t;\n\twhile(t--){\n\t\tcin>>n>>m;\n\t\tvector<int> r(2), w(2);\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tcin>>s[i];\n\t\t\tfor(int j = 0; j < m; j++){\n\t\t\t\tif(s[i][j] == 'R')\n\t\t\t\t\tr[i+j&1] = 1;\n\t\t\t\telse if(s[i][j] == 'W')\n\t\t\t\t\tw[i+j&1] = 1;\n\t\t\t}\n\t\t}\n\t\tint v = r[1] or w[0];\n\t\tint vv = r[0] or w[1];\n\t\tif(v and vv){\n\t\t\tcout<<\"NO\\n\";\n\t\t\tcontinue;\n\t\t}\n \n\t\tcout<<\"YES\\n\";\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tfor(int j = 0; j < m; j++){\n\t\t\t\tchar c = cc[i+j+v&1];\n\t\t\t\tcout<<c;\n\t\t\t\tif(s[i][j] != '.')\n\t\t\t\t\tassert(s[i][j] == c);\n\t\t\t}\n\t\t\tcout<<'\\n';\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1534",
    "index": "B",
    "title": "Histogram Ugliness",
    "statement": "Little Dormi received a histogram with $n$ bars of height $a_1, a_2, \\ldots, a_n$ for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.\n\nTo modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times:\n\n- Select an index $i$ ($1 \\le i \\le n$) where $a_i>0$, and assign $a_i := a_i-1$.\n\nLittle Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.\n\nHowever, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.\n\nConsider the following example where the histogram has $4$ columns of heights $4,8,9,6$:\n\nThe blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is $4+4+1+3+6 = 18$, so if Little Dormi does not modify the histogram at all, the ugliness would be $18$.\n\nHowever, Little Dormi can apply the operation once on column $2$ and twice on column $3$, resulting in a histogram with heights $4,7,7,6$:\n\nNow, as the total vertical length of the outline (red lines) is $4+3+1+6=14$, the ugliness is $14+3=17$ dollars. It can be proven that this is optimal.",
    "tutorial": "It's only optimal to decrease a column $i$ if $a_i > a_{i+1}$ and $a_i > a_{i-1}$, as that would reduce the vertical length of the outline by $2$ while only costing $1$ operation. Additionally, observe that decreasing a column will never affect whether it is optimal to decrease any other column, so we can treat the operations as independent. Thus, our algorithm is as follows: while it is optimal to decrease a column, do it. Once this is no longer the case, calculate the final value of the histogram. This can be sped up to $\\mathcal{O}(n)$ with some arithmetic and the observation above.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\nusing ll = long long;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\ntemplate<typename T>\nint sz(const T &a){return int(a.size());}\nconst int MN=4e5+2;\nll arr[MN];\nint main(){\n    cin.tie(NULL);\n    ios_base::sync_with_stdio(false);\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        arr[n+1]=0;\n        for(int i=1;i<=n;i++)cin>>arr[i];\n        ll ans=0;\n        for(int i=1;i<=n;i++){\n            ll should=min(arr[i],max(arr[i-1],arr[i+1]));\n            ans+=arr[i]-should+abs(should-arr[i-1]);\n            arr[i]=should;\n        }\n        printf(\"%lli\\n\",ans+arr[n]);\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1534",
    "index": "C",
    "title": "Little Alawn's Puzzle",
    "statement": "When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a $2 \\times n$ grid where each row is a permutation of the numbers $1,2,3,\\ldots,n$.\n\nThe goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial \\textbf{solved} configuration only by swapping numbers in a column.\n\nUnfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo $10^9+7$.",
    "tutorial": "Define the \"direction\" of a column as the orientation of its numbers. Swapping the numbers in a column will flip its direction. Let's create a simple, undirected graph where the nodes are the $n$ columns on the puzzle and we draw one edge connecting it to the $2$ other columns that share a number with it. Notice that the degree of every node in this graph is $2$, so the graph must be made of some number of disjoint simple cycles. Now consider any component in the graph. If we fix the direction of any of the columns in the component, that will fix the direction of the columns adjacent to it, and so on until the direction of every column in the component has been fixed (also note that as the component is a simple cycle, we will never get a contradiction). As there are $2$ possible directions for any column, there are thus $2$ ways to direct the columns in this component. Lastly, notice that the columns in each component are independent, so the answer is simply $2^k$, where $k$ is the number of components in our graph. Time Complexity: $\\mathcal{O}(n)$ with DFS",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\nusing ll = long long;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\ntemplate<typename T>\nint sz(const T &a){return int(a.size());}\nconst int MN=4e5+1;\nconst ll mod=1e9+7;\nbool gone[MN];\nvector<int> adj[MN];\nint arr[MN][2];\nvoid dfs(int loc){\n    gone[loc]=true;\n    for(auto x:adj[loc])if(!gone[x])dfs(x);\n}\nint main(){\n    cin.tie(NULL);\n    ios_base::sync_with_stdio(false);\n    int t;\n    cin>>t;\n    while(t--) {\n        int n;\n        cin >> n;\n        for (int i = 1; i <= n; i++)cin >> arr[i][0],adj[i]=vector<int>(),gone[i]=false;\n        for (int i = 1; i <= n; i++)cin >> arr[i][1];\n        for (int i = 1; i <= n; i++) {\n            adj[arr[i][0]].push_back(arr[i][1]), adj[arr[i][1]].push_back(arr[i][0]);\n        }\n        ll ans = 1;\n        for (int i = 1; i <= n; i++) {\n            if (!gone[i]) {\n                ans = ans * ll(2) % mod;\n                dfs(i);\n            }\n        }\n        printf(\"%lli\\n\", ans);\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "dsu",
      "graphs",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1534",
    "index": "D",
    "title": "Lost Tree",
    "statement": "This is an interactive problem.\n\nLittle Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of $n$ nodes! The nodes of the tree are numbered from $1$ to $n$.\n\nThe game master only allows him to ask one type of question:\n\n- Little Dormi picks a node $r$ ($1 \\le r \\le n$), and the game master will reply with an array $d_1, d_2, \\ldots, d_n$, where $d_i$ is the length of the shortest path from node $r$ to $i$, for all $1 \\le i \\le n$.\n\nAdditionally, to \\sout{make the game unfair} challenge Little Dormi the game master will allow at most $\\lceil\\frac{n}{2}\\rceil$ questions, where $\\lceil x \\rceil$ denotes the smallest integer greater than or equal to $x$.\n\nFaced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy!\n\nNote that the game master creates the tree before the game starts, and does not change it during the game.",
    "tutorial": "If we had $n$ queries, solving this problem would be easy as we could just query every single node and add edges when $d_i=1$. However, notice that as long as we make a query for at least $1$ endpoint of every edge, we will be able to find all the edges using this method. Observe that a tree is bipartite, so we would be able to achieve a bound of $\\lceil \\frac{n}{2} \\rceil$ as long as we only query the smaller bipartite set. To figure out which set is smaller, we can just query any node and look at which nodes have odd depth and which ones have even depth. Lastly, be careful with your queries so that your worst-case bound is $\\lceil \\frac{n}{2} \\rceil$ rather than $\\lfloor \\frac{n}{2} \\rfloor + 1$. One way to do this is to not include the initial node you query in either bipartite set (so you are effectively working with $n-1$ nodes rather than $n$). Time complexity: $\\mathcal{O}(n^2)$",
    "code": "#include \"bits/stdc++.h\"\n#include <random>\nusing namespace std;\n \n// Defines\n#define fs first\n#define sn second\n#define pb push_back\n#define eb emplace_back\n#define mpr make_pair\n#define mtp make_tuple\n#define all(x) (x).begin(), (x).end()\n// Basic type definitions\nusing ll = long long; using ull = unsigned long long; using ld = long double;\nusing pii = pair<int, int>; using pll = pair<long long, long long>;\n#ifdef __GNUG__\n// PBDS order statistic tree\n#include <ext/pb_ds/assoc_container.hpp> // Common file \n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds; \ntemplate <typename T, class comp = less<T>> using os_tree = tree<T, null_type, comp, rb_tree_tag, tree_order_statistics_node_update>;\ntemplate <typename K, typename V, class comp = less<K>> using treemap = tree<K, V, comp, rb_tree_tag, tree_order_statistics_node_update>;\n// HashSet\n#include <ext/pb_ds/assoc_container.hpp>\ntemplate <typename T, class Hash> using hashset = gp_hash_table<T, null_type, Hash>;\ntemplate <typename K, typename V, class Hash> using hashmap = gp_hash_table<K, V, Hash>;\nconst ll RANDOM = chrono::high_resolution_clock::now().time_since_epoch().count();\nstruct chash { ll operator()(ll x) const { return x ^ RANDOM; } };\n#endif\n// More utilities\nint SZ(string &v) { return v.length(); }\ntemplate <typename C> int SZ(C &v) { return v.size(); }\ntemplate <typename C> void UNIQUE(vector<C> &v) { sort(v.begin(), v.end()); v.resize(unique(v.begin(), v.end()) - v.begin()); }\ntemplate <typename T, typename U> void maxa(T &a, U b) { a = max(a, b); }\ntemplate <typename T, typename U> void mina(T &a, U b) { a = min(a, b); }\nconst ll INF = 0x3f3f3f3f, LLINF = 0x3f3f3f3f3f3f3f3f;\n \nconst int MN = 2001;\nint N,\n    dis[MN];\nmt19937 mt(69696969);\nvector<pii> edges;\n \nvoid read(int r) {\n    cout << ('?') << ' ' << (r) << '\\n'; cout.flush();\n    for (auto i = 1; i <= N; i++)\n        cin >> dis[i];\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n \n    cin >> N;\n \n    read(1);\n    vector<int> s[2];\n    for (auto i = 2; i <= N; i++)\n        s[dis[i] & 1].pb(i);\n    if (s[0].size() > s[1].size()) swap(s[0], s[1]);\n \n    for (auto i = 1; i <= N; i++)\n        if (dis[i] == 1)\n            edges.eb(1, i);\n    for (auto x : s[0]) {\n        read(x);\n        for (auto i = 1; i <= N; i++) {\n            if (dis[i] == 1) {\n                int a = x, b = i;\n                if (a > b) swap(a, b);\n                edges.eb(a, b);\n            }\n        }\n    }\n    UNIQUE(edges);\n    shuffle(all(edges), mt);\n    uniform_int_distribution<int> dis(0, 1);\n    for (auto &[a, b] : edges)\n        if (dis(mt))\n            swap(a, b);\n    cout << ('!') << '\\n';\n    for (auto &[a, b] : edges)\n        cout << (a) << ' ' << (b) << '\\n';\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1534",
    "index": "E",
    "title": "Lost Array",
    "statement": "This is an interactive problem.\n\nNote: the XOR-sum of an array $a_1, a_2, \\ldots, a_n$ ($1 \\le a_i \\le 10^9$) is defined as $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n$, where $\\oplus$ denotes the bitwise XOR operation.\n\nLittle Dormi received an array of $n$ integers $a_1, a_2, \\ldots, a_n$ for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.\n\nThe XOR machine is currently configured with a query size of $k$ (which you cannot change), and allows you to perform the following type of query: by giving the machine $k$ \\textbf{distinct} indices $x_1, x_2, \\ldots, x_k$, it will output $a_{x_1} \\oplus a_{x_2} \\oplus \\ldots \\oplus a_{x_k}$.\n\nAs Little Dormi's older brother, you would like to help him recover the \\textbf{XOR-sum} of his array $a_1, a_2, \\ldots, a_n$ by querying the XOR machine.\n\nLittle Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the \\textbf{minimum} number of times to find the XOR-sum of his array. Formally, let $d$ be the minimum number of queries needed to find the XOR-sum of any array of length $n$ with a query size of $k$. Your program will be accepted if you find the correct XOR-sum in at most $d$ queries.\n\nLastly, you also noticed that with certain configurations of the machine $k$ and values of $n$, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.\n\nThe array $a_1, a_2, \\ldots, a_n$ is fixed before you start querying the XOR machine and does not change with the queries.",
    "tutorial": "\"tl;dr it's pure BFS\" The only information we can obtain from a query is the XOR sum of the subset we queried. We can also try and obtain some frequency information about the bits (whether the number of bits at position $i$ is odd for every bit $i$), but trying to combine frequency information is ultimately analogous to just combining the XOR sums of different subsets. Additionally, trying to combine XOR sums with other operations such as OR and AND will cause us to lose the information about the XOR sum of the combined subsets, and are thus not useful. Thus, the only way to find the answer is to repeated query different subsets until their XOR sum includes every element in the array. To find the minimum number of queries, we can run a BFS to find the shortest number of queries to go from the XOR sum of $0$ numbers to the XOR sum of all of them. Observe that only the number of values currently present in the XOR sum matters, as we can query the XOR sum of any subset of numbers in the array as long as it has size $k$. In our graph, we can transition from the XOR sum of a subset of size $i$ by picking $j$ ($0 \\le j \\le k$) selected numbers and $k-j$ unselected numbers. This changes the size of our subset by $k-2j$. Time Complexity: $\\mathcal{O}(nk)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nconst ll INF = 0x3f3f3f3f;\n \nconst int MN = 2001;\nint N, K,\n    dis[MN], par[MN];\n \nint main() {\n    cin >> N >> K;\n \n    // BFS\n    memset(dis, 0x3f, sizeof dis);\n    queue<int> q;\n    dis[0] = 0; par[0] = -1; q.push(0);\n    while (!q.empty()) {\n        int c = q.front(); q.pop(); // c -> num selected\n        for (auto i = 0; i <= K; i++) { // num unselected we add\n            if (i <= N-c && K-i <= c) {\n                int to = c + i-(K-i);\n                if (dis[to] == INF) {\n                    dis[to] = dis[c]+1;\n                    par[to] = c;\n                    q.push(to);\n                }\n            }\n        }\n    }\n \n    if (dis[N] == INF) cout << \"-1\\n\";\n    else {\n        vector<int> sel, nosel(N);\n        iota(nosel.begin(), nosel.end(), 1);\n \n        // get ans\n        vector<int> path;\n        for (auto c = N; c != -1; c = par[c])\n            path.push_back(c);\n        reverse(path.begin(), path.end());\n \n        // for (auto x : path) printf(\"path=%d\\n\", x);\n        // printf(\"\\n\"); fflush(stdout);\n \n        int sz = path.size(), ans = 0;\n        for (auto i = 0; i < sz-1; i++) {\n            // a-(K-a) = d\n            // a-K+a=d\n            // 2a-K=d\n            // 2a=d+K\n            // a=(d+K)/2\n            int a = path[i], b = path[i+1], d = b-a, nsel = (d+K)/2, nnosel = K-nsel; assert((d+K) % 2 == 0);\n            vector<int> cnosel, csel;\n            for (auto j = 0; j < nsel; j++) {\n                csel.push_back(nosel.back());\n                nosel.pop_back();\n            }\n            for (auto j = 0; j < nnosel; j++) {\n                cnosel.push_back(sel.back());\n                sel.pop_back();\n            }\n            \n            // make query\n            cout << \"? \";\n            for (auto x : csel) cout << x << ' ';\n            for (auto x : cnosel) cout << x << ' ';\n            cout << '\\n'; cout.flush();\n            // update nosel,sel\n            nosel.insert(nosel.end(), cnosel.begin(), cnosel.end());\n            sel.insert(sel.end(), csel.begin(), csel.end());\n \n            int res; cin >> res;\n            ans ^= res;\n        }\n        assert(nosel.empty());\n \n        cout << \"! \" << ans << '\\n'; cout.flush();\n    }\n}",
    "tags": [
      "graphs",
      "greedy",
      "interactive",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1534",
    "index": "F1",
    "title": "Falling Sand (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is the constraints on $a_i$. You can make hacks only if all versions of the problem are solved.}\n\nLittle Dormi has recently received a puzzle from his friend and needs your help to solve it.\n\nThe puzzle consists of an upright board with $n$ rows and $m$ columns of cells, some empty and some filled with blocks of sand, and $m$ non-negative integers $a_1,a_2,\\ldots,a_m$ ($0 \\leq a_i \\leq n$). In this version of the problem, $a_i$ will be \\textbf{equal to} the number of blocks of sand in column $i$.\n\nWhen a cell filled with a block of sand is disturbed, the block of sand will fall from its cell to the sand counter at the bottom of the column (each column has a sand counter). While a block of sand is falling, other blocks of sand that are adjacent at any point to the falling block of sand will also be disturbed and start to fall. Specifically, a block of sand disturbed at a cell $(i,j)$ will pass through all cells below and including the cell $(i,j)$ within the column, disturbing all adjacent cells along the way. Here, the cells adjacent to a cell $(i,j)$ are defined as $(i-1,j)$, $(i,j-1)$, $(i+1,j)$, and $(i,j+1)$ (if they are within the grid). Note that the newly falling blocks can disturb other blocks.\n\nIn one operation you are able to disturb any piece of sand. The puzzle is solved when there are \\textbf{at least} $a_i$ blocks of sand counted in the $i$-th sand counter for each column from $1$ to $m$.\n\nYou are now tasked with finding the minimum amount of operations in order to solve the puzzle. Note that Little Dormi will never give you a puzzle that is impossible to solve.",
    "tutorial": "Let's model the grid as a directed graph. Take every block of sand in the puzzle as a node. Now add an edge from a node $A$ to a node $B$ if: $B$ is the first block of sand below $A$. $B$ is the first block of sand next to or below $A$ and on the first column to the left of $A$. $B$ is the first block of sand next to or below $A$ and on the first column to the right of $A$. $B$ is on the cell directly above $A$. Within this graph, the nodes which are reachable from a node $A$ are identical to the set of blocks of sand which will be disturbed as a result of $A$ being disturbed. The question is then converted to, given a directed graph, what is the size of the smallest set of nodes such that all nodes within the graph are reachable from this set. To solve this, we can compress all strongly connected components in the graph (using Tarjan's Algorithm or Kosaraju's Algorithm), leaving us with a directed acyclic graph. From here, it can be observed that all nodes which have an in-degree of $0$ need to be disturbed manually, as no other nodes can disturb them. Moreover, as the graph is acyclic, it can also be proven that all nodes which have an in-degree greater than $0$ are reachable from a node that has an in-degree of $0$. As such, it is minimal and sufficient to disturb all nodes which have an in-degree of $0$. Proof: Take any node $X$ that does not have an in-degree of $0$. Take a node $Y$ that has an edge connecting it to $X$. This node must exist as $X$ has a positive in-degree. Now all nodes that can reach $Y$ can also reach $X$. Thus, we just need to prove that $Y$ is reachable from a node with in-degree $0$ to prove that $X$ is reachable from a node with in-degree $0$. Repeat this process on the node $Y$, taking it as the new $X$. Continue to do this until $X$ has an in-degree of $0$. This process must end and find such an $X$ because there are only a finite number of nodes in the graph, and any repeated node within this process would indicate that there is a cycle in the graph. However as the graph is acyclic, this can not happen. Once we have found this $X$, we can say that $X$ is reachable from a node with an in-degree of $0$ as it itself is a node within in-degree $0$. We can then follow the graph to prove that the first $X$ is reachable from a node with in-degree $0$. Thus, the answer is the number of nodes with in-degree $0$ in the compressed graph. Final Complexity: $\\mathcal{O}(nm)$ or $\\mathcal{O}(nm \\cdot \\log(nm))$ depending on implementation.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\nusing ll = long long;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\ntemplate<typename T>\nint sz(const T &a){return int(a.size());}\nconst int MN=4e5+1;\nvector<vector<char>> arr;\nvector<vector<int>> ind;\nint am[MN];\nvector<int> adj[MN];\nint nodecnt=0;\nint id[MN],low[MN];\nbool inst[MN];\nvector<int> st;\nint et;\nint in[MN];\nvector<vector<int>> comps;\nint indeg[MN];\nvoid dfs(int loc){\n    id[loc]=low[loc]=et++;\n    inst[loc]=true,st.push_back(loc);\n    for(auto x:adj[loc]){\n        if(!id[x])dfs(x),low[loc]=min(low[loc],low[x]);\n        else if(inst[x])low[loc]=min(low[loc],id[x]);\n    }\n    if(id[loc]==low[loc]){\n        comps.push_back({});\n        while(1){\n            int cur=st.back();\n            st.pop_back();\n            in[cur]=sz(comps)-1;\n            inst[cur]=false;\n            comps.back().push_back(cur);\n            if(cur==loc)break;\n        }\n    }\n}\nint main(){\n    cin.tie(NULL);\n    ios_base::sync_with_stdio(false);\n    int n,m;\n    cin>>n>>m;\n    arr.resize(n+1,vector<char>(m+1));\n    ind.resize(n+1,vector<int>(m+1));\n    for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)cin>>arr[i][j];\n    for(int i=1;i<=m;i++)cin>>am[i];\n    for(int i=1;i<=n;i++){\n        for(int j=1;j<=m;j++){\n            if(arr[i][j]=='#'){\n                ind[i][j]=++nodecnt;\n            }\n        }\n    }\n    for(int i=1;i<=n;i++){\n        for(int j=1;j<=m;j++){\n            if(arr[i][j]=='#'){\n                if(i-1>=1&&arr[i-1][j]=='#')adj[ind[i][j]].push_back(ind[i-1][j]);\n                for(int k=i+1;k<=n;k++){\n                    if(arr[k][j]=='#'){\n                        adj[ind[i][j]].push_back(ind[k][j]);\n                        break;\n                    }\n                }\n                bool leftdone=false,rightdone=false;\n                for(int k=i;k<=n&&(!leftdone||!rightdone)&&(arr[k][j]!='#'||k==i);k++){\n                    if(j-1>=1&&!leftdone&&arr[k][j-1]=='#'){\n                        adj[ind[i][j]].push_back(ind[k][j-1]),leftdone=true;\n                    }\n                    if(j+1<=m&&!rightdone&&arr[k][j+1]=='#'){\n                        adj[ind[i][j]].push_back(ind[k][j+1]),rightdone=true;\n                    }\n                }\n            }\n        }\n    }\n    et=1;\n    comps.push_back({});\n    for(int i=1;i<=nodecnt;i++)if(!id[i])dfs(i);\n    for(int i=1;i<sz(comps);i++){\n        for(auto x:comps[i])for(auto y:adj[x])if(in[y]!=i)indeg[in[y]]++;\n    }\n    int ans=0;\n    for(int i=1;i<sz(comps);i++){\n        if(indeg[i]==0)ans++;\n    }\n    printf(\"%d\\n\",ans);\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1534",
    "index": "F2",
    "title": "Falling Sand (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is the constraints on $a_i$. You can make hacks only if all versions of the problem are solved.}\n\nLittle Dormi has recently received a puzzle from his friend and needs your help to solve it.\n\nThe puzzle consists of an upright board with $n$ rows and $m$ columns of cells, some empty and some filled with blocks of sand, and $m$ non-negative integers $a_1,a_2,\\ldots,a_m$ ($0 \\leq a_i \\leq n$). In this version of the problem, $a_i$ will always be \\textbf{not greater than} the number of blocks of sand in column $i$.\n\nWhen a cell filled with a block of sand is disturbed, the block of sand will fall from its cell to the sand counter at the bottom of the column (each column has a sand counter). While a block of sand is falling, other blocks of sand that are adjacent at any point to the falling block of sand will also be disturbed and start to fall. Specifically, a block of sand disturbed at a cell $(i,j)$ will pass through all cells below and including the cell $(i,j)$ within the column, disturbing all adjacent cells along the way. Here, the cells adjacent to a cell $(i,j)$ are defined as $(i-1,j)$, $(i,j-1)$, $(i+1,j)$, and $(i,j+1)$ (if they are within the grid). Note that the newly falling blocks can disturb other blocks.\n\nIn one operation you are able to disturb any piece of sand. The puzzle is solved when there are \\textbf{at least} $a_i$ blocks of sand counted in the $i$-th sand counter for each column from $1$ to $m$.\n\nYou are now tasked with finding the minimum amount of operations in order to solve the puzzle. Note that Little Dormi will never give you a puzzle that is impossible to solve.",
    "tutorial": "Note: If you have not already read the editorial for $F1$, please do so, as this editorial continues on from where that editorial left off. Where $F2$ differs from $F1$ is that not all blocks of sand have to fall, instead only some subset of them within each column need to fall. Let's go back to the Directed Acyclic Graph constructed in $F1$. Instead of all nodes being required to be reachable, we only need the nodes which are the first $a_i$ blocks of sand within each column (counting from the bottom) to be reachable. Let's denote the set which contains the nodes which have to be reachable as $S$. We can then observe that $S$ can be reduced down to just the $a_i^\\texttt{th}$ block of sand within each column as all blocks of sand below will be distributed when it is disturbed. Let us call the nodes that are left in this set \"special nodes\". From here, observe that any special node $X$ that is reachable from another special node $Y$ can be removed from $S$ as a disturbance of the node $Y$ will also guarantee that $X$ will be disturbed. Now remove all such nodes from $S$. Note that these nodes can be found with BFS or DFS. Now I claim that all nodes within the graph will reach some subarray of $S$ when $S$ is sorted by column index (if a node represents multiple nodes within the puzzle, take the left-most column). Let us call this sorted array of $S$ as $A$. Proof: Imagine a node $X$ that does not reach an exact subsegment of $A$. This means that it must reach some node $i$ on the puzzle and then another node $j$ such that they are both in $A$ and none of the special nodes on the columns between them are reachable. Let's denote a random special node that is not reachable as $Z$. As you can only go directly from one column to the next, $X$ must reach some set of nodes on the columns between $i$ and $j$. Denote the reachable node which is in the same column as $Z$ as $K$. If $K$ is above $Z$ in the column, $Z$ is reachable from $K$, and thus reachable from $X$. Thus, $K$ must be below $Z$. However, this means that $K$ is reachable from $Z$. As $K$ is used to reach either $i$ or $j$ depending on which side $X$ is on (WLOG, assume its $j$), $j$ must also be reachable from $Z$. But since $Z$ is a special node, $j$ can not be part of the set $S$ and array $A$. This creates a contradiction, proving that $X$ must reach an exact subsegment of $A$. Now run a dp on the directed acyclic graph and find the minimum and maximum index of $A$ that is reachable from every node. The question is then converted to, given some intervals, what is the minimal amount of intervals that will be able to cover the entire range of $A$. This question is well known and can be solved in many ways. One of the simplest methods is a greedy approach. Loop from left to right on $A$, maintaining the rightmost index of an interval that starts before or at the current index and also maintain the furthest right that any taken interval reaches. As soon as you reach an index that is not within the range of taken intervals, take the interval with the rightmost index and add one to the answer. The final answer is then the value after the loop has completed. Final Complexity: $\\mathcal{O}(nm)$ or $\\mathcal{O}(nm \\cdot \\log(nm))$ depending on implementation.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\nusing ll = long long;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\ntemplate<typename T>\nint sz(const T &a){return int(a.size());}\nconst int MN=4e5+1;\nvector<vector<char>> arr;\nvector<vector<int>> ind;\nint am[MN];\nvector<int> adj[MN];\nint nodecnt=0;\nint id[MN],low[MN];\nbool inst[MN];\nvector<int> st;\nint et;\nint in[MN];\nvector<vector<int>> comps;\nvector<int> nadj[MN];\nint marked[MN];\nint leftspec[MN];\nint trans[MN];\npii dp[MN];\nvoid dfs(int loc){\n    id[loc]=low[loc]=et++;\n    inst[loc]=true,st.push_back(loc);\n    for(auto x:adj[loc]){\n        if(!id[x])dfs(x),low[loc]=min(low[loc],low[x]);\n        else if(inst[x])low[loc]=min(low[loc],id[x]);\n    }\n    if(id[loc]==low[loc]){\n        comps.push_back({});\n        while(1){\n            int cur=st.back();\n            st.pop_back();\n            in[cur]=sz(comps)-1;\n            inst[cur]=false;\n            comps.back().push_back(cur);\n            if(cur==loc)break;\n        }\n    }\n}\nvoid mark(int loc){\n    for(auto x:nadj[loc]){\n        if(!marked[x]) {\n            marked[x] = true;\n            mark(x);\n        }\n    }\n}\npii solve(int loc){\n    if(dp[loc].first)return dp[loc];\n    dp[loc]={INT_MAX,INT_MIN};\n    for(auto x:nadj[loc]){\n        if(!marked[x]){\n            pii te=solve(x);\n            dp[loc]={min(dp[loc].first,te.first),max(dp[loc].second,te.second)};\n        }\n    }\n    return dp[loc];\n}\nint main(){\n    cin.tie(NULL);\n    ios_base::sync_with_stdio(false);\n    int n,m;\n    cin>>n>>m;\n    arr.resize(n+1,vector<char>(m+1));\n    ind.resize(n+1,vector<int>(m+1));\n    for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)cin>>arr[i][j];\n    for(int i=1;i<=m;i++)cin>>am[i];\n    for(int i=1;i<=n;i++){\n        for(int j=1;j<=m;j++){\n            if(arr[i][j]=='#'){\n                ind[i][j]=++nodecnt;\n            }\n        }\n    }\n    for(int i=1;i<=n;i++){\n        for(int j=1;j<=m;j++){\n            if(arr[i][j]=='#'){\n                if(i-1>=1&&arr[i-1][j]=='#')adj[ind[i][j]].push_back(ind[i-1][j]);\n                for(int k=i+1;k<=n;k++){\n                    if(arr[k][j]=='#'){\n                        adj[ind[i][j]].push_back(ind[k][j]);\n                        break;\n                    }\n                }\n                bool leftdone=false,rightdone=false;\n                for(int k=i;k<=n&&(!leftdone||!rightdone)&&(arr[k][j]!='#'||k==i);k++){\n                    if(j-1>=1&&!leftdone&&arr[k][j-1]=='#'){\n                        adj[ind[i][j]].push_back(ind[k][j-1]),leftdone=true;\n                    }\n                    if(j+1<=m&&!rightdone&&arr[k][j+1]=='#'){\n                        adj[ind[i][j]].push_back(ind[k][j+1]),rightdone=true;\n                    }\n                }\n            }\n        }\n    }\n    et=1;\n    comps.push_back({});\n    for(int i=1;i<=nodecnt;i++)if(!id[i])dfs(i);\n    for(int i=1;i<sz(comps);i++){\n        leftspec[i]=INT_MAX;\n        for(auto x:comps[i])for(auto y:adj[x])if(in[y]!=i)nadj[i].push_back(in[y]);\n        sort(nadj[i].begin(),nadj[i].end()),nadj[i].erase(unique(nadj[i].begin(),nadj[i].end()),nadj[i].end());\n    }\n    vector<int> spec;\n    for(int i=1;i<=m;i++){\n        for(int j=n;j>=1;j--){\n            if(arr[j][i]=='#'){\n                am[i]--;\n                if(am[i]==0)spec.push_back(in[ind[j][i]]),leftspec[in[ind[j][i]]]=min(leftspec[in[ind[j][i]]],i);\n            }\n        }\n    }\n    sort(spec.begin(),spec.end()),spec.erase(unique(spec.begin(),spec.end()),spec.end());\n    for(auto x:spec)if(!marked[x])mark(x);\n    vector<int> compress;\n    for(auto x:spec)if(!marked[x])compress.push_back(leftspec[x]);\n    sort(compress.begin(),compress.end());\n    for(auto x:spec)if(!marked[x])dp[x].first=dp[x].second=lower_bound(compress.begin(),compress.end(),leftspec[x])-compress.begin()+1;\n    for(int i=1;i<sz(comps);i++){\n        if(!marked[i]){\n            pii te=solve(i);\n            if(te.first!=INT_MAX){\n                trans[te.first]=max(trans[te.first],te.second);\n            }\n        }\n    }\n    for(int i=2;i<=sz(compress);i++)trans[i]=max(trans[i-1],trans[i]);\n    int cur=1,ans=0;\n    while(cur<=sz(compress))ans++,cur=trans[cur]+1;\n    printf(\"%d\\n\",ans);\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1534",
    "index": "G",
    "title": "A New Beginning",
    "statement": "Annie has gotten bored of winning every coding contest and farming unlimited rating. Today, she is going to farm potatoes instead.\n\nAnnie's garden is an infinite 2D plane. She has $n$ potatoes to plant, and the $i$-th potato must be planted at $(x_i,y_i)$. Starting at the point $(0, 0)$, Annie begins walking, in one step she can travel one unit \\textbf{right} or \\textbf{up} (increasing her $x$ or $y$ coordinate by $1$ respectively). At any point $(X,Y)$ during her walk she can plant some potatoes at arbitrary points using her potato gun, consuming $\\max(|X-x|,|Y-y|)$ units of energy in order to plant a potato at $(x,y)$. Find the minimum total energy required to plant every potato.\n\nNote that Annie may plant any number of potatoes from any point.",
    "tutorial": "Observe that for any point $(x,y)$ and some path $A$, the minimum distance from $A$ to $(x,y)$ will occur on the intersection of $A$ and the antidiagonal of $(x,y)$. Here the antidiagonal is defined as a line $y=-x+c$. Proof: Assume $(a,b)$ is the intersection of $A$ and the antidiagonal of $(x,y)$. If $(a,b) = (x,y)$, this distance is obviously minimal as it is equal to 0. Now consider the case where $(a,b) \\neq (x,y)$. As a result of $(a,b)$ being on the antidiagonal, two properties will be true: $|x-a| = |y-b|$. Either $a > x$ and $b < y$ or $a < x$ and $b > y$. When you move forward on the path, increasing $b$ will only make $|y-b|$ larger. Thus, no matter how you change $a$, $\\max(|x-a|,|y-b|)$ will always increase or stay the same. When you move backward on the path, decreasing $a$ will only make $|x-a|$ larger. Thus, no matter how you change $b$, $\\max(|x-a|,|y-b|)$ will always increase or stay the same. Thus, the shortest distance will always occur at $(a,b)$. Now we rotate the grid $45$ degrees clockwise so that the antidiagonals are now vertical lines on the new grid. Your movements on the grid now go from $(x,y)$ to $(x+1,y+1)$ or $(x+1,y-1)$. Furthermore, it is now optimal to plant a potato when you are on the same x coordinate as the potato. When you are at $(x,a)$, planting a potato at $(x,b)$ costs $\\frac{|a-b|}{2}$. From here we can observe a slow dp. Define $dp[x][y]$ as the minimum cost of any path that goes from $(0,0)$ to $(x,y)$ and plant all potatoes $(a,b)$ such that $a \\leq x$. Note: this function is only defined for when $x$ and $y$ have the same parity. This is as a point $(x,y)$ in the old grid translates to $(x+y,x-y)$ in the new grid and $x+y$ has the same parity as $x-y$. For speed, we also only calculate $dp[x][y]$ when there is a potato with a x-coordinate of $x$. The transition is then established as $dp[x][y] = (\\min{dp[a][b]} \\forall y-(x-a) \\leq b \\leq y+(x-a)) + (\\sum{\\frac{|y-z|}{2}} \\forall potatoes (x,z))$, where $a$ is the last x-coordinate containing a potato. This runs in $\\mathcal{O}(n \\cdot 10^9)$. This dp can then be optimized using slope trick. If you are not familiar with slope trick, we recommend learning it first at Slope trick explained and [Tutorial] Slope Trick. Instead of maintaining a $2$ dimensional array, we can maintain functions $f_x$ where $f_x(y) = dp[x][y]$. To transition from $f_i$ to $f_j$, we first set $f_i(a) = \\min{f_i(b)} \\forall a-(j-i) \\leq b \\leq a+(j-i)$. This can be done by maintaining the center/minimum of the slope trick function and then offsetting all values in the left priority queue by $-(j-i)$ and offsetting all values in the right priority queue by $j-i$. Finally, we have to add the costs of the potatoes. Each of the potatoes $(x,y)$ is just a function $g$ such that $g(a) = \\frac{|y-a|}{2}$. These functions can then be added onto $f_i$ finishing the conversion to $f_j$. The final answer is then the minimum of the last function. Final Complexity: $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/priority_queue.hpp>\nusing namespace std; using namespace __gnu_pbds;\n#define foru(i,a,b) for(int i=(a);i<(b);i++)\n#define ford(i,a,b) for(int i=(a);i>=(b);i--)\n#define fori(a,b) foru(i,a,b)\n#define forj(a,b) foru(j,a,b)\n#define fork(a,b) foru(k,a,b)\n#define seto(x,i) memset(x,i,sizeof x)\n#define pf first\n#define ps second\n#define pb push_back\n#define eb emplace_back\n#define em emplace\n#define mp make_pair\n#define mt make_tuple\n#define popcount __builtin_popcount\n#define popcountll __builtin_popcountll\n#define clz __builtin_clz\n#define clzll __builtin_clzll\n#define ctz __builtin_ctz\n#define ctzll __builtin_ctzll\n#define P2(x) (1LL<<(x))\n#define sz(x) (int)x.size()\n#define all(x) begin(x),end(x)\ntypedef int64_t ll;  typedef uint64_t ull; typedef int8_t byte; typedef long double lld;\ntypedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef pair<lld,lld> pdd;\ntemplate<class T1,class T2> using ordered_map=tree<T1,T2,less<T1>,rb_tree_tag,tree_order_statistics_node_update>; template<class T1> using ordered_set=ordered_map<T1,null_type>;\ntemplate<class T> using minpq=std::priority_queue<T,vector<T>,greater<T>>; template<class T> using maxpq=std::priority_queue<T,vector<T>,less<T>>;\ntemplate<class T> using minpairingheap=__gnu_pbds::priority_queue<T,greater<T>,pairing_heap_tag>; template<class T>using maxpairingheap=__gnu_pbds::priority_queue<T,less<T>,pairing_heap_tag>;\nconst int inf=0x3f3f3f3f,MOD=1e9+7; const ll INF=0x3f3f3f3f3f3f3f3f; const lld PI=acos((lld)-1);\nconst ll SEED=443214^chrono::duration_cast<chrono::nanoseconds>(chrono::high_resolution_clock::now().time_since_epoch()).count();\nmt19937 randgen(SEED); int randint(int a, int b){return uniform_int_distribution<int>(a,b)(randgen);} ll randll(ll a, ll b){return uniform_int_distribution<ll>(a,b)(randgen);}\nll gcd(ll a, ll b){return b?gcd(b,a%b):a;}\nll fpow(ll a,ll b,ll M=MOD){ll ret=1;for(;b;b>>=1){if(b&1) ret=ret*a%M;a=a*a%M;}return ret;}\ntemplate<class T1,class T2>constexpr const auto _min(const T1&x,const T2&y){return x<y?x:y;} template<class T,class...Ts>constexpr auto _min(const T&x,const Ts&...xs){return _min(x,_min(xs...));}\ntemplate<class T1,class T2>constexpr const auto _max(const T1&x,const T2&y){return x>y?x:y;} template<class T,class...Ts>constexpr auto _max(const T&x,const Ts&...xs){return _max(x,_max(xs...));}\n#define min(...) _min(__VA_ARGS__)\n#define max(...) _max(__VA_ARGS__)\ntemplate<class T1,class T2>constexpr bool ckmin(T1&x,const T2&y){return x>y?x=y,1:0;} template<class T,class...Ts>constexpr bool ckmin(T&x,const Ts&...xs){return ckmin(x,min(xs...));}\ntemplate<class T1,class T2>constexpr bool ckmax(T1&x,const T2&y){return x<y?x=y,1:0;} template<class T,class...Ts>constexpr bool ckmax(T&x,const Ts&...xs){return ckmax(x,max(xs...));}\nstruct chash{\n    static ll splitmix64(ll x){x+=0x9e3779b97f4a7c15; x=(x^(x>>30))*0xbf58476d1ce4e5b9; x=(x^(x>>27))*0x94d049bb133111eb; return x^(x>>31);}\n    template<class T> size_t operator()(const T &x) const{return splitmix64(hash<T>()(x)+SEED);}\n    template<class T1,class T2> size_t operator()(const pair<T1,T2>&x)const{return 31*operator()(x.first)+operator()(x.second);}};\nvoid fIn(string s){freopen(s.c_str(),\"r\",stdin);} void fOut(string s){freopen(s.c_str(),\"w\",stdout);} void fIO(string s){fIn(s+\".in\"); fOut(s+\".out\");}\nstring to_string(char c){return string(1,c);} string to_string(char* s){return (string)s;} string to_string(string s){return s;}\ntemplate<class T> string to_string(complex<T> c){stringstream ss; ss<<c; return ss.str();} template<class T1,class T2> string to_string(pair<T1,T2> p){return \"(\"+to_string(p.pf)+\",\"+to_string(p.ps)+\")\";}\ntemplate<size_t SZ> string to_string(bitset<SZ> b){string ret=\"\"; fori(0,SZ) ret+=char('0'+b[i]); return ret;}\ntemplate<class T> string to_string(T v){string ret=\"{\"; for(const auto& x:v) ret+=to_string(x)+\",\"; return ret+\"}\";}\nvoid DBG(){cerr<<\"]\"<<endl;} template<class T,class... Ts> void DBG(T x,Ts... xs){cerr<<to_string(x); if(sizeof...(xs)) cerr<<\", \"; DBG(xs...);}\n#ifdef LOCAL_PROJECT\n    #define dbg(...) cerr<<\"Line(\"<< __LINE__<<\") -> [\"<<#__VA_ARGS__<<\"]: [\", DBG(__VA_ARGS__)\n#else\n    #define dbg(...) 0\n#endif\n#define nl \"\\n\"\n \nconst int N=800010,M=1e1; //8e5\nll T,n,x,y,a,b,c,d,ans;\nstring ff;\n \nint main(){\n    cin.tie(0)->sync_with_stdio(0);\n    T=1;\n    foru(cnt,1,T+1){\n        vector<pll> p;\n        maxpq<ll> pa;\n        minpq<ll> pb;\n        n=x=y=a=b=ans=0;\n        cin>>n;\n        fori(0,n){\n            cin>>x>>y;\n            p.eb(x+y,x-y);\n        }\n        sort(all(p)); pa.em(0); pb.em(0);\n        for(auto [y,x]:p){\n            ans+=max(pa.top()-y-x,x-pb.top()-y,0);\n            if(!sz(pa)||pb.top()+y>x){\n                pa.em(x+y); pa.em(x+y); pb.em(pa.top()-2*y); pa.pop();\n            }\n            else{\n                pb.em(x-y); pb.em(x-y); pa.em(pb.top()+2*y); pb.pop();\n            }\n        }\n        ans/=2;\n        cout<<ans<<nl;\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "geometry",
      "sortings"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1534",
    "index": "H",
    "title": "Lost Nodes",
    "statement": "This is an interactive problem.\n\nAs he qualified for IOI this year, Little Ericyi was given a gift from all his friends: a tree of $n$ nodes!\n\nOn the flight to IOI Little Ericyi was very bored, so he decided to play a game with Little Yvonne with his new tree. First, Little Yvonne selects two (not necessarily different) nodes $a$ and $b$ on the tree (without telling Ericyi), and then gives him a hint $f$ (which is some node on the path from $a$ to $b$).\n\nThen, Little Ericyi is able to ask the following question repeatedly:\n\n- If I rooted the tree at node $r$ (Ericyi gets to choose $r$), what would be the Lowest Common Ancestor of $a$ and $b$?\n\nLittle Ericyi's goal is to find the nodes $a$ and $b$, and report them to Little Yvonne.\n\nHowever, Little Yvonne thought this game was too easy, so before he gives the hint $f$ to Little Ericyi, he also wants him to first find the maximum number of queries required to determine $a$ and $b$ over all possibilities of $a$, $b$, and $f$ assuming Little Ericyi plays optimally. Little Ericyi defines an optimal strategy as one that makes the minimum number of queries. Of course, once Little Ericyi replies with the maximum number of queries, Little Yvonne will only let him use that many queries in the game.\n\nThe tree, $a$, $b$, and $f$ are all fixed before the start of the game and do not change as queries are made.",
    "tutorial": "Finding the theoretical maximum For now, let's only look at finding $k$ for fixed $f$. We will expand for all $f$ later. We know that $f$ is on the path from $a$ to $b$. Let us root the tree at $f$. Thus, we know that the path will pass through the root, and that there are exactly $2$ non-negative length chains beginning at the root. With that in mind, let's take a look at what a question \"? r really does. What happens if $r$ is on the path from $a$ to $b$? In this case, we obtain $r$ as the answer. What happens if $r$ is not on the path from $a$ to $b$? In this case, we obtain the closest node to $r$ on the path from $a$ to $b$. Let's try to find one endpoint of one of these chains first. Consider the following dynamic programming structure: Let $dp[u]$ denote the minimum number of questions required to \"solve\" the subtree rooted at $u$. By \"solve\", we mean to determine if the endpoint of a chain is in the subtree or not, and if it is in the subtree, the exact node. The base case is pretty obvious. For a leaf node, it will take exactly $1$ question to solve a leaf node. If the endpoint of the chain does indeed end at the leaf node, then a question will return the leaf node. Otherwise it'll return an ancestor of the leaf. Let's move on to a non-base case at a node $x$. Let's call the most \"expensive\" child of $x$ as the child $c$ with the largest $dp[c]$ (i.e. takes the most number of questions to \"solve\"). For now, assume we know that an endpoint exists in the subtree rooted at $x$, and is not $x$. Thus, we will need to iterate through each child to determine in which child's subtree the endpoint exists. We will need to use one question per child. However, note that not all of these questions count towards our question count. There are two cases: In the current child we are exploring, the endpoint does exist there. In this case, the question we used does not count towards our question count. We can use a question from the child's question count. This may seem a bit strange, but if we query correctly, then in the same time we check if the endpoint exists in the child's subtree, we also process the most \"expensive\" child of the child and determine if the endpoint exist in that child of the child's subtree. In the current child we are exploring, the endpoint doesn't exist there. In this case, the question we used must count towards our question count. We could consider this a \"wasted\" question as we didn't learn anything new about where the endpoint is, just that it's not in this child. Now, in which order should be explore the children? We can greedy this. Recall that any \"wasted\" questions count towards our question count. Thus, for more \"expensive\" children, we want to have wasted less questions when we get to the child, as in the case the endpoint does exist there, we would need even more questions (adding the \"wasted\" questions to $dp[c]$ where $c$ is the child). This gives us the following idea: To determine if the $i^\\text{th}$ ($0$-indexed) child $c$ of $x$ contains the endpoint, we would need to waste $i$ questions. If the endpoint does exist in $c$, we would need to use a total of $dp[c] + i$ questions to \"solve\" the subtree rooted at $x$. Since we are trying to find the worst case, we want to order the children of $x$ such as to minimize the maximum of all $dp[c] + i$. The optimal ordering is the non-increasing order of $dp[c]$. The transition is thus: $dp[x] = \\max\\{dp[c_i] + i\\} \\,\\, \\forall \\,\\, 0 \\le i < |c|$, where the $dp$ values are sorted in non-increasing order, and $c$ are the children of $x$. Now wait! We haven't handled the case where the endpoint doesn't exist in $x$ or the case where the endpoint is $x$ yet! Turns out, both of these cases are already handled for us. We only need to be a bit careful when we actually perform the interaction later on. If the endpoint doesn't exist in $x$, we would have already realized when one of the questions to a child of $x$ returns an ancestor of $x$. This question count won't be lost though. It will simply be counted towards a \"wasted\" question for one of the ancestors of $x$. If the endpoint is $x$, then all of the questions to a child of $x$ will return $x$ (not a ancestor of $x$). Thus, we will know that the endpoint is $x$ with exactly $|c|$ wasted questions. Notice, however, that $|c| \\le dp[x]$ by the nature of the transition. Thus, this case will never be our worst case, so we can ignore it for the dynamic programming. We now have the dynamic programming complete, but notice that it's only for the endpoint of one chain. At our root $f$, there are two chains with two endpoints. Thus, our final answer won't be simply taking $dp[f]$. It will require a bit more computation. For now, assume that both endpoints are not $f$ (i.e. both chains have positive length). Following a similar analysis as the dynamic programming transition, we have that for any child that does not contain either chain endpoint, we would need to \"waste\" a question. Once again, the optimal ordering is to process in non-increasing order. However, adding $i$ to the $i^\\text{th}$ child is no longer correct. Consider the following observations: When processing a child that doesn't contain a chain, that child only takes one question to determine that both chains are not in that child. For the first child that we know contains a chain, we don't \"waste\" a question. This question is included in that child's question count. With observation $1$, we are basically figuring out the first chain's endpoint for free. There are no wasted questions, as all wasted questions will be counted for the second chain. With observation $2$, we have that adding $i$ wasted questions is no longer correct. We only waste $i - 1$ questions for the $i^\\text{th}$ child, as one of the processed children contains the first chain (and thus doesn't waste a question). Thus, for the root, our formula is: $ans = \\max\\{dp[c_j] + dp[c_i] + i - 1\\} \\,\\, \\forall \\,\\, 0 \\le j < i < |c|$, where the $dp$ values are sorted in non-increasing order, and $c$ is the children of $f$. Note that this formula has an $\\mathcal{O}(n^2)$ worst case for a star graph, so we will need to optimize it. Our optimized formula is: $ans = dp[c_0] + \\max\\{dp[c_i] + i - 1\\} \\,\\, \\forall \\,\\, 1 \\le i < |c|$, where the $dp$ values are sorted in non-increasing order, and $c$ is the children of $f$. Once again, with a similar analysis as what was done for the $dp$ computation, the case that one (or both) chains have a zero length will never be the worst case, and so we can ignore it for the dynamic programming. However, the case must still be handled during interaction. Recall that the above was for a fixed $f$. To find the maximum for all $f$, we can perform a tree walk. When transitioning from one root to an adjacent root, use a prefix and suffix max array to compute $\\max{dp[c_i] + i}$, ignoring the $c_i$ that is the new root. Both max arrays should store $dp[c_i] + i$, not $dp[c_i]$. Remember to subtract $1$ from the suffix array values, as there is one less wasted question. ------------------ Interacting If you understood the initial dynamic programming computation for determining the theoretical maximum, the interaction should be relatively straightforward, and so we will leave it as an exercise for the reader. Be careful when handling the special cases that were ignored during the dynamic programming. ------------------ The final time complexity is $\\mathcal{O}(n \\log n)$ and memory complexity is $\\mathcal{O}(n)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\nusing ll = long long;\nusing pii = pair<int,int>;\nusing pll = pair<ll,ll>;\ntemplate<typename T>\nint sz(const T &a){return int(a.size());}\nconst int MN=1e5+1;\nvector<int> adj[MN];\nint dp[MN],depth[MN];\nvoid dfs(int loc, int parent){\n    vector<int> children;\n    depth[loc]=depth[parent]+1;\n    for(auto x:adj[loc]){\n        if(x!=parent){\n            dfs(x,loc);\n            children.push_back(dp[x]);\n        }\n    }\n    sort(children.begin(),children.end(),greater<>());\n    dp[loc]=1;\n    if(parent) {\n        for (int i = 0; i < sz(children); i++) {\n            dp[loc] = max(dp[loc], children[i] + i);\n        }\n    }\n    else{\n        dp[loc]=0;\n        for (int i = 1; i < sz(children); i++) {\n            dp[loc] = max(dp[loc], children[i] + i - 1);\n        }\n        if(sz(children))dp[loc]+=children.front();\n    }\n}\nint ans=0;\nvoid walkdfs(int loc, int parent, int parentdp){\n    vector<pii> children;\n    if(parentdp!=-1)children.push_back({parentdp,parent});\n    for(auto x:adj[loc])if(x!=parent)children.push_back({dp[x],x});\n    sort(children.begin(),children.end(),greater<>());\n    int nodeans=0;\n    for (int i = 1; i < sz(children); i++) {\n        nodeans = max(nodeans, children[i].first + i - 1);\n    }\n    if(sz(children))nodeans+=children.front().first;\n    ans=max(ans,nodeans);\n    vector<int> pre,suf(sz(children));\n    for(int i=0;i<sz(children);i++){\n        pre.push_back(max(sz(pre)?pre.back():0,children[i].first+i));\n    }\n    for(int i=sz(children)-1;i>=0;i--){\n        suf[i]=max((i==sz(children)-1?0:suf[i+1]+1),children[i].first);\n    }\n    for(int i=0;i<sz(children);i++){\n        if(children[i].second!=parent){\n            walkdfs(children[i].second,loc,max((i-1>=0?pre[i-1]:1),(i+1<sz(suf)?suf[i+1]+i:1)));\n        }\n    }\n}\nint query(int a){\n    int ret;\n    printf(\"? %d\\n\",a);\n    fflush(stdout);\n    cin>>ret;\n    if(ret==-1)exit(0);\n    return ret;\n}\nint simulate(int loc, int parent){\n    vector<int> children;\n    for(auto x:adj[loc]){\n        if(x!=parent){\n            children.push_back(x);\n        }\n    }\n    if(sz(children)==0&&parent)return query(loc);\n    sort(children.begin(),children.end(),[&](const auto &lhs, const auto &rhs){\n        return dp[lhs]>dp[rhs];\n    });\n    if(parent){\n        for (int i = 0; i < sz(children); i++) {\n            int te=simulate(children[i],loc);\n            if(depth[te]!=depth[loc])return te;\n        }\n        return loc;\n    }\n    else{\n        vector<int> nodes;\n        for (int i = 0; i < sz(children); i++) {\n            int te=simulate(children[i],loc);\n            if(depth[te]!=depth[loc]){\n                nodes.push_back(te);\n                if(sz(nodes)==2)break;\n            }\n        }\n        while(sz(nodes)<2)nodes.push_back(loc);\n        printf(\"! %d %d\\n\",nodes[0],nodes[1]);\n        fflush(stdout);\n    }\n    return -1;\n}\nint main(){\n    cin.tie(NULL);\n    ios_base::sync_with_stdio(false);\n    int n,a,b;\n    cin>>n;\n    for(int i=1;i<n;i++){\n        cin>>a>>b;\n        adj[a].push_back(b);\n        adj[b].push_back(a);\n    }\n    dfs(1,0);\n    walkdfs(1,0,-1);\n    printf(\"%d\\n\",ans);\n    fflush(stdout);\n    cin>>a;\n    dfs(a,0);\n    simulate(a,0);\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "graphs",
      "interactive",
      "sortings",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1535",
    "index": "A",
    "title": "Fair Playoff",
    "statement": "Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament.\n\nIt is known that in a match between two players, the one whose skill is greater will win. The skill of the $i$-th player is equal to $s_i$ and all skill levels are pairwise different (i. e. there are no two identical values in the array $s$).\n\nThe tournament is called \\textbf{fair} if the two players with the highest skills meet in the finals.\n\nDetermine whether the given tournament is \\textbf{fair}.",
    "tutorial": "It is easier to determine the case when the players with the maximum skills will not meet in the finals. It means that they met in the semifinals, and in the other semifinals, both players are weaker. It's easy to check this case with the following formula: $\\min(s_1, s_2) > \\max(s_3, s_4)$ or $\\max(s_1, s_2) < \\min(s_3, s_4)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    vector<int> s(4);\n    for (int& x : s) cin >> x;\n    if (min(s[0], s[1]) > max(s[2], s[3]) || max(s[0], s[1]) < min(s[2], s[3]))\n      cout << \"NO\\n\";\n    else\n      cout << \"YES\\n\";\n  }\n}\n",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1535",
    "index": "B",
    "title": "Array Reodering",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nLet's call a pair of indices $i$, $j$ \\textbf{good} if $1 \\le i < j \\le n$ and $\\gcd(a_i, 2a_j) > 1$ (where $\\gcd(x, y)$ is the greatest common divisor of $x$ and $y$).\n\nFind the maximum number of \\textbf{good} index pairs if you can reorder the array $a$ in an arbitrary way.",
    "tutorial": "If the value of $a_i$ is even, then $\\gcd(a_i, 2a_j)$ at least $2$, regardless of the value of $a_j$. Therefore, we can put all the even values before the odd ones (it does not matter in what order). Now it remains to arrange the odd values. In fact, their order is not important, because $\\gcd(a_i, 2a_j) = \\gcd(a_i, a_j)$ (for odd $a_i$ and $a_j$). This means that each pair will be considered exactly $1$ time, regardless of the order of the odd elements.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n    sort(a.begin(), a.end(), [](int x, int y) {\n      return x % 2 < y % 2;\n    });\n    int ans = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = i + 1; j < n; ++j) {\n        ans += __gcd(a[i], a[j] * 2) > 1;\n      }\n    }\n    cout << ans << endl;\n  }\n}\n",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1535",
    "index": "C",
    "title": "Unstable String",
    "statement": "You are given a string $s$ consisting of the characters 0, 1, and ?.\n\nLet's call a string \\textbf{unstable} if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).\n\nLet's call a string \\textbf{beautiful} if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes \\textbf{unstable}.\n\nFor example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.\n\nCalculate the number of beautiful contiguous substrings of the string $s$.",
    "tutorial": "Let's find a simple condition when the string is not beautiful. A string is not beautiful if there are two characters 0 (or two characters 1) at an odd distance, or 0 and 1 at an even distance (because in this case, the string cannot be made unstable). Iterate over the right border of the substring $r$. Let $l$ be the maximum index such that the substring $s[l, r]$ is not beautiful (or $0$ if the substring $s[1, r]$ is beautiful). Then we have to add $r - l$ to the answer (since any substring of a beautiful string is also beautiful). Denote $lst_{c, p}$ as the last occurrence of $c$ ($0$ or $1$) at the position of parity $p$. Let $s_r = 0$, $p$ is the parity of $r$, then $l = \\max(lst_{0, p \\oplus 1}, lst_{1, p})$, i. e. find the nearest character that breaks a beautiful substring (0 at an odd distance or 1 at an even distance) The case for $s_r = 1$ is similar. If $s_r = ?$, then we can choose what this character will be. Obviously, we need to choose the option with the smaller value of $l$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    string s;\n    cin >> s;\n    vector<vector<int>> lst(2, vector<int>(2, -1));\n    long long ans = 0;\n    for (int i = 0; i < int(s.size()); ++i) {\n      int j = i - 1;\n      int p = i & 1;\n      if (s[i] != '1') j = min(j, max(lst[0][p ^ 1], lst[1][p]));\n      if (s[i] != '0') j = min(j, max(lst[0][p], lst[1][p ^ 1]));\n      ans += i - j;\n      if (s[i] != '?') lst[s[i] - '0'][p] = i;\n    }\n    cout << ans << '\\n';\n  }\n}\n",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "implementation",
      "strings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1535",
    "index": "D",
    "title": "Playoff Tournament",
    "statement": "$2^k$ teams participate in a playoff tournament. The tournament consists of $2^k - 1$ games. They are held as follows: first of all, the teams are split into pairs: team $1$ plays against team $2$, team $3$ plays against team $4$ (exactly in this order), and so on (so, $2^{k-1}$ games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only $2^{k-1}$ teams remain. If only one team remains, it is declared the champion; otherwise, $2^{k-2}$ games are played: in the first one of them, the winner of the game \"$1$ vs $2$\" plays against the winner of the game \"$3$ vs $4$\", then the winner of the game \"$5$ vs $6$\" plays against the winner of the game \"$7$ vs $8$\", and so on. This process repeats until only one team remains.\n\nFor example, this picture describes the chronological order of games with $k = 3$:\n\nLet the string $s$ consisting of $2^k - 1$ characters describe the results of the games in chronological order as follows:\n\n- if $s_i$ is 0, then the team with lower index wins the $i$-th game;\n- if $s_i$ is 1, then the team with greater index wins the $i$-th game;\n- if $s_i$ is ?, then the result of the $i$-th game is unknown (any team could win this game).\n\nLet $f(s)$ be the number of possible winners of the tournament described by the string $s$. A team $i$ is a possible winner of the tournament if it is possible to replace every ? with either 1 or 0 in such a way that team $i$ is the champion.\n\nYou are given the initial state of the string $s$. You have to process $q$ queries of the following form:\n\n- $p$ $c$ — replace $s_p$ with character $c$, and print $f(s)$ as the result of the query.",
    "tutorial": "Denote $cnt_i$ as the number of teams that can be winners in the $i$-th game. The answer to the problem is $cnt_{2^k-1}$. If the $i$-th game is played between the winners of games $x$ and $y$ ($x < y$), then: $cnt_i = cnt_x$ if $s_i = 0$; $cnt_i = cnt_y$ if $s_i = 1$; $cnt_i = cnt_x + cnt_y$ if $s_i = ?$. So we can calculate all values of $cnt$ for the initial string. Note that the result of no more than $k$ other games depends on the result of any game. So, if we change $s_p$, it will change no more than $k$ values of $cnt$, and we can recalculate all of them. For convenience, you can renumerate the games so that the playoff looks like a segment tree, i. e. the final has the number $0$, the semifinals have numbers $1$ and $2$, etc.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL); \n  \n  int k;\n  cin >> k;\n  string s;\n  cin >> s;\n  reverse(s.begin(), s.end());\n  \n  int n = 1 << k;\n  vector<int> cnt(2 * n, 1);\n  \n  auto upd = [&](int i) {\n    return cnt[i] = (s[i] != '0' ? cnt[i * 2 + 1] : 0) + (s[i] != '1' ? cnt[i * 2 + 2] : 0);\n  };\n  \n  for (int i = n - 2; i >= 0; i--) {\n    upd(i);\n  }\n  \n  int q;\n  cin >> q;\n  while (q--) {\n    int p;\n    char c;\n    cin >> p >> c;\n    p = n - p - 1;\n    s[p] = c;\n    while (p) {\n      upd(p);\n      p = (p - 1) / 2;\n    }\n    cout << upd(0) << '\\n';\n  }\n}\n",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "implementation",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1535",
    "index": "E",
    "title": "Gold Transfer",
    "statement": "You are given a rooted tree. Each vertex contains $a_i$ tons of gold, which costs $c_i$ per one ton. Initially, the tree consists only a root numbered $0$ with $a_0$ tons of gold and price $c_0$ per ton.\n\nThere are $q$ queries. Each query has one of two types:\n\n- Add vertex $i$ (where $i$ is an index of query) as a son to some vertex $p_i$; vertex $i$ will have $a_i$ tons of gold with $c_i$ per ton. It's guaranteed that $c_i > c_{p_i}$.\n- For a given vertex $v_i$ consider the simple path from $v_i$ to the root. We need to purchase $w_i$ tons of gold from vertices on this path, spending the minimum amount of money. If there isn't enough gold on the path, \\textbf{we buy all we can}.\n\nIf we buy $x$ tons of gold in some vertex $v$ the remaining amount of gold in it decreases by $x$ (of course, we can't buy more gold that vertex has at the moment). For each query of the second type, calculate the resulting amount of gold we bought and the amount of money we should spend.\n\nNote that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query, so don't forget to flush output after printing answers. You can use functions like fflush(stdout) in C++ and BufferedWriter.flush in Java or similar after each writing in your program. In standard (if you don't tweak I/O), endl flushes cout in C++ and System.out.println in Java (or println in Kotlin) makes automatic flush as well.",
    "tutorial": "Note, that $c_i > c_{p_i}$ for each vertex $i$. So if we consider a path from some vertex $v$ to $0$, the closer you are to $0$, the cheaper the cost. In other words, it's always optimal to choose the highest vertex on the path with $a_i > 0$. Suppose we can find such vertex $u$ for a given $v$. How many times we will repeat this search operation? If we need to buy $w$ tons and $u$ has $a_u$ tons, then it's optimal to buy $mn = \\min(w, a_u)$ tons in $u$. After we buy $mn$ tons, either $w$ becomes $0$ or $a_u$ becomes $0$. Since for each vertex $u$, $a_u$ can become equal to zero at most once, and since after $w$ is zero we stop buying, then there will be $O(q)$ searches in total. The next question is how to find $u$ efficiently for a given $v$? Consider the path from $0$ to some vertex $v$. Since we prefer to buy from higher vertices, all empty vertices on this path will form some prefix of it (possibly, empty prefix). So we can make some sort of binary search to find the first non-empty vertex $u$. But instead of binary search we will use binary lifting technique. If we know for each $k$ ($0 \\le k < 20$) which vertex $p[k][v]$ on the path from $v$ to $0$ on distance $2^k$ from $v$ then we can efficiently jump up the path. Let's firstly jump at distance $2^{19}$: if $a[p[19][v]] = 0$ then we jump too high - let's not jump. But if $a[p[19][v]] > 0$ then we can safely jump (or $v = p[19][v]$). Now we know that we don't need a second $2^{19}$ jump, so we try $2^{18}$ jump and so on. In other words, using binary lifting we can find the highest vertex $u$ with $a_u > 0$ in $O(\\log(q))$ steps. Also, we can calculate array $p[k][v]$ for vertex $v$ right after we add vertex $v$ to the tree, since $p[0][v] = p_i$ and $p[k][v] = p[k - 1][p[k - 1][v]]$. The resulting complexity is $O(q \\log(q))$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tout << \"[\";\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \", \";\n\t\tout << v[i];\n\t}\n\treturn out << \"]\";\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nconst int LOG = 20;\n\nint q;\nvector<int> a, c;\nvector<int> p[LOG];\n\nint main() {\n\tcin >> q;\n\ta.resize(q + 1);\n\tc.resize(q + 1);\n\t\n\tfore (lg, 0, LOG)\n\t\tp[lg].resize(q + 1);\n\n\tfore (lg, 0, LOG)\n\t\tp[lg][0] = 0;\n\tcin >> a[0] >> c[0];\n\t\n\tfore (id, 1, q + 1) {\n\t\tint tp; cin >> tp;\n\t\tif (tp == 1) {\n\t\t\tint pr; cin >> pr;\n\t\t\tcin >> a[id] >> c[id];\n\t\t\t\n\t\t\tp[0][id] = pr;\n\t\t\tfore (lg, 1, LOG)\n\t\t\t\tp[lg][id] = p[lg - 1][p[lg - 1][id]];\n\t\t} \n\t\telse {\n\t\t\tint v, w;\n\t\t\tcin >> v >> w;\n\t\t\t\n\t\t\tint ansR = 0;\n\t\t\tli ansS = 0;\n\t\t\t\n\t\t\twhile (w > 0 && a[v] > 0) {\n\t\t\t\tint u = v;\n\t\t\t\tfor (int lg = LOG - 1; lg >= 0; lg--) {\n\t\t\t\t\tif (a[p[lg][u]] > 0)\n\t\t\t\t\t\tu = p[lg][u];\n\t\t\t\t}\n\t\t\t\tint mn = min(a[u], w);\n\t\t\t\ta[u] -= mn;\n\t\t\t\tw -= mn;\n\t\t\t\t\n\t\t\t\tansR += mn;\n\t\t\t\tansS += mn * 1ll * c[u];\n\t\t\t}\n\t\t\tcout << ansR << \" \" << ansS << endl;\n\t\t}\n\t}\n\t\t\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "interactive",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1535",
    "index": "F",
    "title": "String Distance",
    "statement": "Suppose you are given two strings $a$ and $b$. You can apply the following operation any number of times: choose any \\textbf{contiguous} substring of $a$ or $b$, and sort the characters in it in non-descending order. Let $f(a, b)$ the minimum number of operations you have to apply in order to make them equal (or $f(a, b) = 1337$ if it is impossible to make $a$ and $b$ equal using these operations).\n\nFor example:\n\n- $f(\\text{ab}, \\text{ab}) = 0$;\n- $f(\\text{ba}, \\text{ab}) = 1$ (in one operation, we can sort the whole first string);\n- $f(\\text{ebcda}, \\text{ecdba}) = 1$ (in one operation, we can sort the substring of the second string starting from the $2$-nd character and ending with the $4$-th character);\n- $f(\\text{a}, \\text{b}) = 1337$.\n\nYou are given $n$ strings $s_1, s_2, \\dots, s_k$ having equal length. Calculate $\\sum \\limits_{i = 1}^{n} \\sum\\limits_{j = i + 1}^{n} f(s_i, s_j)$.",
    "tutorial": "Disclaimer: the model solution is very complicated compared to most participants' solutions. Feel free to discuss your approaches in the comments! First of all, it's easy to determine when two strings cannot be made equal using these operations: it's when their multisets of characters differ. So, we divide the strings into different equivalence classes, and for any pair of strings from different classes, the answer is $1337$. For any pair of strings from the same class, the answer is either $1$ or $2$, since $2$ operations are always enough to make the strings from the same equivalence class equal (we just sort both of them). Okay, now, for each class, we have to calculate the number of pairs of strings with the distance equal to $1$. Okay, suppose you have two strings $s_1$ and $s_2$, and you want to make them equal using one operation. Suppose that $s_1 < s_2$ lexicographically. Since applying an operation can't result in getting a lexicographically larger string, we should apply the operation on the string $s_2$, not $s_1$. Suppose we choose a substring $[l, r]$ of the string $s_2$ and sort it. All characters to the left of position $l$ and to the right of position $r$ are untouched, and all characters in $[l, r]$ are ordered in non-descending order; so, in order to transform $s_2$ into $s_1$, we should choose a subsegment $[l, r]$ such that all characters outside this segment are the same in both strings, and the substring $[l, r]$ of $s_1$ is sorted. So, the best way to choose a subsegment $[l, r]$ is to compute the longest common prefix of $s_1$ and $s_2$, the longest common suffix of $s_1$ and $s_2$, and try sorting everything in the middle in $s_2$. This gives us a solution in $O(n^2)$: for a pair of strings, we can check that one of them can be transformed into the other in $O(1)$. To do so, we need to build some data structure allowing to query longest common prefixes/suffixes in $O(1)$ (a trie with $O(1)$ LCA or precalculating LCP and building a sparse table of them can do the trick); furthermore, we want to be able to check if some subsegment of some string is sorted in $O(1)$ (but precalculating them is quite easy). So, we have a solution that works if the strings are long (in the model solution, this approach is used on classes having not more than $12000$ strings). The second approach can be used on classes having many strings. If the number of strings is big, it means that they are short, so we can do the following thing: for each string, iterate on the subsegment we will sort and check if the resulting string exists. The model solution uses some very complicated data structures to implement this, but I believe that it's quite easy to get this approach working using string hashes. The only dangerous thing in the second solution you have to consider is that choosing different substrings to sort may result in getting the same resulting string. One good way to deal with this is to ignore some substrings if sorting them doesn't change the leftmost or the rightmost character in the substring; for example, if we sort the substring acb in the string zacb, the character in the beginning of this substring is unchanged, so we can get the same result by sorting cb. So, we consider sorting the substring only if it changes both the first and the last characters of the substring. Okay, so we have two approaches: one works well with a small number of long strings, and the other works well with a big number of short strings. We can choose which of them to run depending on the size of the equivalence class we are considering, and this idea gives us a working solution.",
    "code": "#include<bits/stdc++.h>   \nusing namespace std;\n\nconst int LN = 20;\nconst int K = 12000;\n\nint pw2[1 << LN];\n\nvector<int> sorted_segments(const string& s)\n{\n \tint n = int(s.size()) - 1;\n \tvector<int> res(n);\n \tfor(int i = 0; i < n; i++)\n \t\tif(s[i] <= s[i + 1])\n \t\t\tres[i] = 0;\n \t\telse\n \t\t\tres[i] = 1;\n \treturn res;\n}\n\nvector<int> prefix_sum(const vector<int>& s)\n{\n \tint n = s.size();\n \tvector<int> p(n + 1);\n \tfor(int i = 0; i < n; i++)\n \t\tp[i + 1] = p[i] + s[i];\n \treturn p;\n}\n\nint naiveLCP(const string& s, const string& t)\n{\n \tint ans = 0;\n \tint n = s.size();\n \tint m = t.size();\n \twhile(ans < n && ans < m && s[ans] == t[ans])\n \t\tans++;\n \treturn ans;\n}\n\nvector<vector<int>> build_table(const vector<int>& a)\n{\n\tint n = a.size();\n\tvector<vector<int>> table(LN, vector<int>(n));\n\tfor(int i = 0; i < n; i++)\n\t\ttable[0][i] = a[i];\n\tfor(int i = 1; i < LN; i++)\n\t\tfor(int j = 0; j < n; j++)\n\t\t\tif(j + (1 << (i - 1)) < n)\n\t\t\t\ttable[i][j] = min(table[i - 1][j], table[i - 1][j + (1 << (i - 1))]);\n\t\t\telse\n\t\t\t\ttable[i][j] = table[i - 1][j];\n\treturn table; \t\n}\n\nstruct LCP\n{\n \tvector<int> idx;\n \tvector<vector<int>> table;\n\n \tint query_inner(int x, int y)\n \t{\n \t \tif(x > y) swap(x, y);\n \t \tint len = y - x;\n \t \tint d = pw2[len];\n \t \treturn min(table[d][x], table[d][y - (1 << d)]);\n \t}\n\n \tint query(int x, int y)\n \t{\n \t \treturn query_inner(idx[x], idx[y]);\n \t}\n\n \tLCP() {};\n \tLCP(vector<string> s) \n \t{\n \t\tint n = s.size();\n\t\tvector<pair<string, int>> t;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t \tt.push_back(make_pair(s[i], i));\n\t   \t}\n\t   \tsort(t.begin(), t.end());\n\t   \tidx.resize(n);\n\t   \tfor(int i = 0; i < n; i++)\n\t   \t{\n\t   \t\tidx[t[i].second] = i;\n\t   \t}\n\t   \tvector<int> LCPs;\n\t   \tfor(int i = 0; i < n - 1; i++)\n\t   \t\tLCPs.push_back(naiveLCP(t[i].first, t[i + 1].first));\n\t   \ttable = build_table(LCPs);\t\t\n \t};\n};\n\nconst int T = int(2e7);\n\nmap<char, int> nxt[T];\nint cur = 1;\nint root = 0;\nint cnt[T];\n\nvoid clear_trie()\n{\n \troot = cur++;\n}\n\nint go(int x, char c)\n{\n \tif(!nxt[x].count(c))\n \t\tnxt[x][c] = cur++;\n \treturn nxt[x][c];\n}\n\nvoid add(int v, const string& s, int l, int r, int n, bool sw, const vector<int>& ps)\n{\n\tif(sw && l + r < n - 1 && ps[n - r - 1] == ps[l])\n\t{\n\t\tcnt[v]++;\n\t}\n\tif(sw)\n\t{\n\t\tif(l + r < n - 1)\n\t\t\tadd(go(v, s[n - r - 1]), s, l, r + 1, n, sw, ps);\n \t}\n \telse\n \t{\n \t\tadd(go(v, '$'), s, l, r, n, true, ps);\n \t\tif(l < n - 1)\n \t\t\tadd(go(v, s[l]), s, l + 1, r, n, sw, ps);\n \t}\n}\n\nint calc(int v, const string& s, int l, int r, int n, bool sw, const vector<vector<int>>& good)\n{\n\tint ans = 0;\n\tif(sw && l + r < n - 1 && good[l][r])\n\t{\n\t\tans = cnt[v];\n\t}\n\tif(sw)\n\t{\n\t\tif(l + r < n)\n\t\t\tans += calc(go(v, s[n - r - 1]), s, l, r + 1, n, sw, good);\n\t}\n\telse\n\t{\n\t \tans += calc(go(v, '$'), s, l, r, n, true, good);\n\t \tif(l < n)\n\t \t\tans += calc(go(v, s[l]), s, l + 1, r, n, sw, good);\t\n\t}\n\treturn ans;\n}\n\nlong long solve_short(vector<string> s, int n)\n{\n\tlong long ans = 0;\n \tclear_trie();\n \tsort(s.begin(), s.end());\n \tfor(int i = 0; i < n; i++)\n \t{\n \t \tstring cur = s[i];\n \t \tint len = cur.size();\n \t \tvector<vector<int>> good(len + 1, vector<int>(len + 1));\n \t \tfor(int l = 0; l < len; l++)\n \t \t{\n \t \t \tset<char> q;\n \t \t \tfor(int r = l; r < len; r++)\n \t \t \t{\n \t \t \t \tq.insert(cur[r]);\n \t \t \t \tif(cur[l] != *q.begin() && cur[r] != *q.rbegin())\n \t \t \t \t{\n \t \t \t \t\tgood[l][len - r - 1] = 1;\n \t \t \t \t}\n \t \t \t}\n \t \t}\n \t \tvector<int> p = prefix_sum(sorted_segments(cur));\n \t \tadd(root, cur, 0, 0, len, false, p);\n \t \tans += calc(root, cur, 0, 0, len, false, good);\n \t}\n \tans = n * 1ll * (n - 1) - ans;\n \treturn ans;\n}\n\nlong long solve_long(vector<string> s, int n)\n{                     \n\tint len = s[0].size();\n \tsort(s.begin(), s.end());\n \tvector<string> t = s;\n \tfor(int i = 0; i < n; i++)\n \t\treverse(t[i].begin(), t[i].end());\n \tLCP ls(s);\n \tLCP lt(t);\n \tlong long ans = 0;\n \tfor(int i = 0; i < n; i++)\n \t{\n \t \tvector<int> aux = prefix_sum(sorted_segments(s[i]));\n \t \tfor(int j = i + 1; j < n; j++)\n \t \t{\n \t \t \tint lf = ls.query(i, j);\n \t \t \tint rg = lt.query(i, j);\n \t \t \tif(aux[len - rg - 1] - aux[lf] == 0)\n \t \t \t\tans++;\n \t \t \telse\n \t \t \t\tans += 2;\n \t \t}\n\t}\n\treturn ans;\n}\n\nlong long solve_class(vector<string> s, int n)\n{                       \n\tif(n <= K)\n\t\treturn solve_long(s, n);\n\telse\n\t\treturn solve_short(s, n); \t\n}\n\nvector<int> get_class(string s)\n{\n\tvector<int> c(26);\n\tfor(auto x : s) c[x - 'a']++;\n\treturn c;\n}\n\nint main()\n{\n\tpw2[1] = 0;\n\tfor(int i = 2; i < (1 << LN); i++)\n\t\tpw2[i] = pw2[i >> 1] + 1;\n\tint n;\n\tcin >> n;\n\tvector<string> s(n);\n\tfor(int i = 0; i < n; i++)   \n\t\tcin >> s[i];         \n\tlong long ans = 0;\n\tmap<vector<int>, vector<string>> classes;\n\tfor(int i = 0; i < n; i++)\n\t\tclasses[get_class(s[i])].push_back(s[i]);\n\tint cnt = 0;\n\tfor(auto x : classes)\n\t{                       \n\t \tans += solve_class(x.second, x.second.size());\n\t \tans += cnt * 1337ll * x.second.size();\n\t \tcnt += x.second.size();\n\t}\n\tcout << ans << endl;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "hashing",
      "implementation",
      "strings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1536",
    "index": "A",
    "title": "Omkar and Bad Story",
    "statement": "Omkar has received a message from Anton saying \"Your story for problem A is confusing. Just make a formal statement.\" Because of this, Omkar gives you an array $a = [a_1, a_2, \\ldots, a_n]$ of $n$ distinct integers. An array $b = [b_1, b_2, \\ldots, b_k]$ is called \\textbf{nice} if for any two distinct elements $b_i, b_j$ of $b$, $|b_i-b_j|$ appears in $b$ at least once. In addition, all elements in $b$ must be distinct. Can you add several (maybe, $0$) integers to $a$ to create a \\textbf{nice} array $b$ \\textbf{of size at most $300$}? If $a$ is already \\textbf{nice}, you don't have to add any elements.\n\nFor example, array $[3, 6, 9]$ is \\textbf{nice}, as $|6-3|=|9-6| = 3$, which appears in the array, and $|9-3| = 6$, which appears in the array, while array $[4, 2, 0, 6, 9]$ is not \\textbf{nice}, as $|9-4| = 5$ is not present in the array.\n\nFor integers $x$ and $y$, $|x-y| = x-y$ if $x > y$ and $|x-y| = y-x$ otherwise.",
    "tutorial": "Consider what happens when $a$ contains a negative number. We first claim that if any negative number exists in $a$, then no solution exists. Denote $p$ as the smallest number in $a$ and $q$ as another arbitrary number in the array (as $n \\geq 2$, $q$ always exists). Clearly, $|q - p| = q - p > 0$. However, because $p$ is negative, $q - p > q$. As such, adding $q - p$ to the output array would create the pair $(q - p, p)$ with difference $q - 2p > q - p$. We have the same problem as before; thus, it is impossible to create a nice array if there exists a negative number in $a$. After we deal with this case, we now claim that $b = [0, 1, 2, ..., 100]$ is a valid nice array for any $a$ that contains no negative numbers. It is easy to verify that this is a valid nice array. And since in this case, every element of $a$ is nonnegative and distinct, it is always possible to rearrange and add elements to $a$ to obtain $b$.",
    "code": "import Data.List (intercalate)\nimport Control.Monad (replicateM)\n\nmain = do t <- read <$> getLine\n          replicateM t solve\n\nsolve = do getLine\n           xs <- (map read . words) <$> getLine\n           putStrLn (if any (< 0) xs then \"nO\" else (\"yEs\\n101\\n\" ++ intercalate \" \" (map show [0..100])))",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1536",
    "index": "B",
    "title": "Prinzessin der Verurteilung",
    "statement": "I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.\n\nIt is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?\n\nYou are given a string of $n$ lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that \\textbf{doesn't} appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nFind out what the MEX of the string is!",
    "tutorial": "Pigeonhole principle What is the longest the answer can be? Let's brute force check all substrings of length <= 3 and print the lexicographically smallest one that doesn't appear as a substring in the input. We can guarantee that we will come across the answer due to the pigeonhole principle. There are at most $n+n-1+n-2 = 3n-3$ possible substrings of length 3 or shorter in the input. There exist $26+26^2+26^3 = 18278$ total substrings of length 3 or shorter. It is impossible for the input to contain all $18278$ substrings, as $3n-3 < 18278$ for $n \\leq 1000$. Final runtime looks something like $O(18278n)$ or $O(n)$ depending on how you implement substring checking.",
    "code": "import Data.List (intercalate, tails, isPrefixOf, head)\nimport Control.Monad (replicateM)\nimport Data.Maybe (fromJust, listToMaybe, catMaybes)\n\nmain = do t <- read <$> getLine\n          replicateM t solve\n\nsolve = do getLine\n           s <- getLine\n           putStrLn (leastNonSubstring s)\n\nleastNonSubstring s = head $ catMaybes [leastOfLength l | l <- [1..]]\n  where leastOfLength l = helper \"\" l\n        helper prefix 0 | isSubstring prefix s = Nothing\n                        | otherwise            = Just prefix\n        helper prefix l = listToMaybe $ catMaybes [helper (prefix ++ [letter]) (l - 1) | letter <- ['a'..'z']]\n\nisSubstring s t = any id (map (isPrefixOf s) (tails t))",
    "tags": [
      "brute force",
      "constructive algorithms",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1536",
    "index": "C",
    "title": "Diluc and Kaeya",
    "statement": "The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.\n\nThis time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of $n$ characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly $0$) on this string, partitioning it into several contiguous pieces, each with length at least $1$. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.\n\nKaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every \\textbf{prefix} of the given string. Help him to solve this problem!\n\nFor a string we define a ratio as $a:b$ where 'D' appears in it $a$ times, and 'K' appears $b$ times. Note that $a$ or $b$ can equal $0$, but not both. Ratios $a:b$ and $c:d$ are considered equal if and only if $a\\cdot d = b\\cdot c$.\n\nFor example, for the string 'DDD' the ratio will be $3:0$, for 'DKD' — $2:1$, for 'DKK' — $1:2$, and for 'KKKKDD' — $2:4$. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.",
    "tutorial": "Turn into geometry problem Represent every prefix as $(x, y)$ point in cartesian plane where $x$ = frequency of 'D' and $y$ = frequency of 'K'. Draw a polyline connecting these points in order of increasing length of prefix. Draw a line from origin to point. What can we say about intersections of poly-line with this line? For each prefix, label it with a pair $(a, b)$ where $a$ = frequency of 'D' in this prefix and $b$ = frequency of 'K' in this prefix. Divide $a$ and $b$ by $gcd(a, b)$. If we iterate over all prefixes from to left, we can notice that the answer for the prefix equals the # of occurrences of this pair we have seen so far! This can be visualized by drawing a poly-line as mentioned in the hints. As for implementation, you can use a map in C++ or a HashMap in Java to achieve $O(n \\log n)$ or $O(n)$ runtime.",
    "code": "import Data.List (intercalate)\nimport Control.Monad (mapM, replicateM)\nimport Data.Ratio ((%))\nimport Data.Map (empty, findWithDefault, insert)\n\nmain = do t <- read <$> getLine\n          replicateM t solve\n\nsolve = do getLine\n           s <- getLine\n           putStrLn (intercalate \" \" (map show (maxBlocks s)))\n\nmaxBlocks s = helper s empty 0 0\n  where helper \"\" _ _ _ = []\n        helper (c:s) prev d k = x : helper s prev' d' k'\n          where (d', k') | c == 'D' = (d + 1, k)\n                         | c == 'K' = (d, k + 1)\n                r | k' == 0   = 69000000 % 1\n                  | otherwise = d' % k'\n                x = (findWithDefault 0 r prev) + 1\n                prev' = insert r x prev",
    "tags": [
      "data structures",
      "dp",
      "hashing",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1536",
    "index": "D",
    "title": "Omkar and Medians",
    "statement": "Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array $a$ with elements $a_1, a_2, \\ldots, a_{2k-1}$, is the array $b$ with elements $b_1, b_2, \\ldots, b_{k}$ such that $b_i$ is equal to the median of $a_1, a_2, \\ldots, a_{2i-1}$ for all $i$. Omkar has found an array $b$ of size $n$ ($1 \\leq n \\leq 2 \\cdot 10^5$, $-10^9 \\leq b_i \\leq 10^9$). Given this array $b$, Ray wants to test Omkar's claim and see if $b$ actually is an OmkArray of some array $a$. Can you help Ray?\n\nThe median of a set of numbers $a_1, a_2, \\ldots, a_{2i-1}$ is the number $c_{i}$ where $c_{1}, c_{2}, \\ldots, c_{2i-1}$ represents $a_1, a_2, \\ldots, a_{2i-1}$ sorted in nondecreasing order.",
    "tutorial": "For some $k<n$, assume $b_1, b_2, \\cdots, b_{k}$ is the OmkArray of some $a_1, a_2, \\cdots, a_{2k-1}$, and we want to see what values of $a_{2k}, a_{2k+1}$ we can add so that $b_1, b_2, \\cdots, b_{k+1}$ is the OmkArray of $a_1, a_2, \\cdots, a_{2k+1}$. Let $c_1, c_2, \\cdots, c_{2k-1}$ be $a_1, a_2, \\cdots, a_{2k-1}$ sorted in ascending order. If $b_{k+1} \\geq b_k$, note that $b_{k} = c_k$ and there are $k-2$ elements of $a$ $\\geq c_{k+1}$, so no matter how large $a_{2k}, a_{2k+1}$ are there will be at most $k$ elements larger than $c_{k+1}$ in $a_1, a_2, \\cdots, a_{2k+1}$. This gives $b_{k+1} \\leq c_{k+1}$. We can use a similar argument to show $b_{k+1} \\geq c_{k-1}$. Now we want to bound $c_{k+1}$ and $c_{k-1}$. Note that each distinct value among $b_1, b_2, \\cdots, b_k$ must appear at least once in $a_1, a_2, \\cdots, a_{2k-1}$. Therefore, if $i$, $j$ satisfy that $b_i$ is the largest value of $b_i\\leq b_k$ and $i \\neq k$, and $b_j$ is the smallest value of $b_j \\geq b_k$, $j \\neq k$, then we have $c_{k+1} \\leq b_j$, $c_{k-1} \\geq b_i$, and so $b_i \\leq b_{k+1} \\leq b_j$. If no such largest/smallest values exist, then we can assume $b_{k+1}$ is not bounded above/below. Therefore, if $b$ has an OmkArray, it is necessary that for all $i$, there does not exist a $j\\leq i$ such that $b_j$ is between $b_i$ and $b_{i+1}$, exclusive. I claim this is also sufficient. We can construct such an array $a$ using the following algorithm: Let $a_1 = b_1$. Let $a_1 = b_1$. If $b_{i+1}=b_j$ for some $b_j<b_i$ with $j<i$, let $a_{2k-2}, a_{2k-1} = -\\infty$ (we can replace $-\\infty$ with some sufficiently small constant at the end of our array creation process). If $b_{i+1}=b_j$ for some $b_j<b_i$ with $j<i$, let $a_{2k-2}, a_{2k-1} = -\\infty$ (we can replace $-\\infty$ with some sufficiently small constant at the end of our array creation process). Otherwise, if $b_{i+1}<b_i$ then let $a_{2k-2} = -\\infty$, $a_{2k-1} = b_{i+1}$. Otherwise, if $b_{i+1}<b_i$ then let $a_{2k-2} = -\\infty$, $a_{2k-1} = b_{i+1}$. If $b_{i+1}=b_j$ for some $b_j>b_i$ with $j<i$, let $a_{2k-2}, a_{2k-1} = \\infty$ (we can replace $\\infty$ with some sufficiently large constant at the end of our array creation process). If $b_{i+1}=b_j$ for some $b_j>b_i$ with $j<i$, let $a_{2k-2}, a_{2k-1} = \\infty$ (we can replace $\\infty$ with some sufficiently large constant at the end of our array creation process). Otherwise, if $b_{i+1}>b_i$ then let $a_{2k-2} = \\infty$, $a_{2k-1} = b_{i+1}$. Otherwise, if $b_{i+1}>b_i$ then let $a_{2k-2} = \\infty$, $a_{2k-1} = b_{i+1}$. Finally, if $b_{i+1} = b_i$, let $a_{2k-2} = -\\infty$, $a_{2k-1} = \\infty$. Finally, if $b_{i+1} = b_i$, let $a_{2k-2} = -\\infty$, $a_{2k-1} = \\infty$. This means that an equivalent condition to having an OmkArray is for all $i$, there does not exist a $j\\leq i$ such that $b_j$ is between $b_i$ and $b_{i+1}$, exclusive. There are multiple ways to check this for an array $b$, but one clean way would be to keep some TreeSet $s$, and check if $b_{i+1}$ is between \\t{s.ceil($b_i$)} and \\t{s.floor($b_i$)} for all $i$, and then adding $b_{i+1}$ to $s$ if it is not already added.",
    "code": "import Data.List (intercalate)\nimport Data.Set (singleton, lookupLT, lookupGT, insert)\nimport Control.Monad (mapM, replicateM)\n\nmain = do t <- read <$> getLine\n          replicateM t solve\n\nsolve = do getLine\n           xs <- (map read . words) <$> getLine\n           putStrLn (if isOmkArray xs then \"yEs\" else \"nO\")\n\nisOmkArray :: [Int] -> Bool\nisOmkArray (x:xs) = helper xs x (singleton x)\n  where helper [] _ _ = True\n        helper (x:xs) prev allPrev | maybe False (x <) (lookupLT prev allPrev) || maybe False (x >) (lookupGT prev allPrev) = False\n                                   | otherwise                                                                              = helper xs x (insert x allPrev)",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1536",
    "index": "E",
    "title": "Omkar and Forest",
    "statement": "Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an $n$ by $m$ grid ($1 \\leq n, m \\leq 2000$) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions:\n\n- For any two adjacent (sharing a side) cells, the absolute value of the difference of numbers in them is at most $1$.\n- If the number in some cell is strictly larger than $0$, it should be strictly greater than the number in \\textbf{at least one} of the cells adjacent to it.\n\nUnfortunately, Ajit is not fully worthy of Omkar's powers yet. He sees each cell as a \"0\" or a \"#\". If a cell is labeled as \"0\", then the number in it must equal $0$. Otherwise, the number in it can be any nonnegative integer.\n\nDetermine how many different assignments of elements exist such that these special conditions are satisfied. Two assignments are considered different if there exists at least one cell such that the numbers written in it in these assignments are different. Since the answer may be enormous, find the answer modulo $10^9+7$.",
    "tutorial": "Consider forcing some set of '#' positions to be $0$ and the rest to be positive integers. Multisource BFS Imagine picking some subset of '#' and making them $0$. Then there is exactly one way to make all the remaining '#' positive integers. To see why, imagine multisource BFS with all $0$ as the sources. After the BFS, each '#' will be equal to the minimum distance from itself to any $0$ cell. Difference between adjacent cells will be at most $1$. Proof can be shown by contradiction: if two cells with difference $\\geq 2$ existed, then the larger of these cells is not labeled with the shortest distance to a source (since the distance from the smaller cell $+ 1$ will be a better choice). Because of the nature of BFS, we can also ensure the second condition is also satisfied, since the only cells that have no neighbor strictly smaller will be the source cells. This is the only valid assignment because if we make any number larger, there will exist a pair of cells with difference $\\geq 2$. If we try to make any number smaller, there will exist a cell with positive karma that has no strictly smaller neighbor. If we let $k$ equal to the frequency of '#' in the input, then the answer is $2^k$. Keep in mind of the special case where the input is all '#', in which case you have to subtract $1$. This is because a possible arrangement must contain at least one cell with karma of $0$. Obviously the solution runs in $O(nm)$ time.",
    "code": "import Data.List (intercalate)\nimport Control.Monad (replicateM)\n\nmd x = mod x 1000000007\n\nmain = do t <- read <$> getLine\n          replicateM t solve\n\nsolve = do n:m:[] <- (map read . words) <$> getLine\n           free <- (sum . map (sum . map (\\chara -> if chara == '#' then 1 else 0))) <$> replicateM n getLine\n           putStrLn $ show (if free == n * m then pow 2 free - 1 else pow 2 free)\n\npow :: (Integral a) => Integer -> a -> Integer\npow _ 0 = 1\npow x y = md $ x * (pow x (y - 1))",
    "tags": [
      "combinatorics",
      "graphs",
      "math",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1536",
    "index": "F",
    "title": "Omkar and Akmar",
    "statement": "Omkar and Akmar are playing a game on a circular board with $n$ ($2 \\leq n \\leq 10^6$) cells. The cells are numbered from $1$ to $n$ so that for each $i$ ($1 \\leq i \\leq n-1$) cell $i$ is adjacent to cell $i+1$ and cell $1$ is adjacent to cell $n$. Initially, each cell is empty.\n\nOmkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter.\n\nA player loses when it is their turn and there are no more valid moves.\n\nOutput the number of possible distinct games where both players play optimally modulo $10^9+7$. Note that we only consider games where some player has lost and there are no more valid moves.\n\nTwo games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different.\n\nA move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move.",
    "tutorial": "Solve a simpler version of the problem, where you just need to print who would win if both players play optimally. Consider the possible ending states of the board. The 2nd player, Omkar, always wins no matter what either player does. The easiest way to see this is by considering ending states of the board. An ending state with an even number of letters means that the 2nd player wins (because the first player is the next player and there are no more moves), and an ending state with an odd number of letters means that the 1st player wins. An ending state must be in the form ABABA... or BABA..., where there are 0 or 1 empty cells in between each letter and the letters form an alternating pattern. If there is more than 1 empty cell in between two cells, then a player will be able to play a letter, thus it is not a valid ending state. If an ending state has two of the same letters next to each other, then it is not a valid ending state. Either they are next to each other, which is illegal, or there is at least one empty cell in between them, which means that a player can play the other letter in between. Since the ending state must form an alternating pattern, there must be an even number of states. Thus, the 2nd player, Omkar, always wins. Find the implication of the 2nd player always winning on the number of optimal games. Because the 2nd player always wins no matter what, the number of optimal games basically means the total number of possible games. Because of Hint 1 and Hint 2, we want to find the total number of possible games. This can be done by iterating over the number of moves and counting the number of ways to play a game with that number of moves. We want to find the number of games that end in $x$ moves on a board of size $n$. The first step is to calculate the total number of ending states. If $x=n$, the total number of ending states is just $2$ because you can either have ABABA... or BABAB... Otherwise, a game that ends in $x$ moves will consist of $x$ letters, for example A|B|A|B|... where a | is a possible location of a single empty cell (there cannot be multiple empty cells next to each other or else it would not be a valid ending state). There are $x$ possible places where there can be an empty cell, and $n-x$ empty cells, so there are $\\binom x {n-x}$ ways to choose places to put empty cells. Due to the circular nature of the board, you need to account for the case where the first cell on the board is an empty cell (the previous formula only works if the first cell is not empty). If you set the first cell to be empty, there are not $x-1$ possible places to put an empty cell and $n-x-1$ remaining empty cells, so you have to add $\\binom {x-1} {n-x-1}$. Multiply the answer by $2$ to account for starting with an A or B. Finally, multiply by $x!$ to account for all the ways you can reach each ending configuration. Thus, if $x=n$, there are $2 \\cdot x!$ optimal games, otherwise there are $2 \\cdot (\\binom x {n-x} + \\binom {x-1} {n-x-1} ) \\cdot x!$ optimal games. Add up the number of games that end in $x$ moves for all even $x$ from $\\lceil \\frac{n}{2} \\rceil$ to $n$, inclusive. Thus, the solution is $O(n)$.",
    "code": "import Data.List (reverse)\nimport Data.Array (listArray, (!))\n\nchara = 1000000007\nmd x = mod x chara\n\nmain = do n <- read <$> getLine\n          putStrLn $ show (solve n)\n\nsolve n = md $ 2 * (sum (map (\\k -> md (factorials!k * (choose k (n - k) + choose (k - 1) (n - k - 1)))) [0,2..n]))\n  where factorials = listArray (0, n) (reverse (helper n))\n          where helper 0 = 1:[]\n                helper n' = md (n' * f):fs\n                  where fs@(f:_) = helper (n' - 1)\n        invFactorials = listArray (0, n) (helper 0)\n          where helper n' | n' == n   = inv (factorials!n):[]\n                          | otherwise = md ((n' + 1) * f):fs\n                  where fs@(f:_) = helper (n' + 1)\n        choose a b | 0 <= b && b <= a = md $ factorials!a * (md (invFactorials!b * invFactorials!(a - b)))\n                   | otherwise        = 0\n\nmodPow :: (Integral a) => Integer -> a -> Integer\nmodPow _ 0 = 1\nmodPow x y = md $ (if even y then 1 else x) * modPow (md (x * x)) (div y 2)\n\ninv x = modPow x (chara - 2)",
    "tags": [
      "chinese remainder theorem",
      "combinatorics",
      "constructive algorithms",
      "fft",
      "games",
      "geometry",
      "math",
      "meet-in-the-middle",
      "string suffix structures"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1537",
    "index": "A",
    "title": "Arithmetic Array",
    "statement": "An array $b$ of length $k$ is called good if its arithmetic mean is equal to $1$. More formally, if $$\\frac{b_1 + \\cdots + b_k}{k}=1.$$\n\nNote that the value $\\frac{b_1+\\cdots+b_k}{k}$ is not rounded up or down. For example, the array $[1,1,1,2]$ has an arithmetic mean of $1.25$, which is not equal to $1$.\n\nYou are given an integer array $a$ of length $n$. In an operation, you can append a \\textbf{non-negative} integer to the end of the array. What's the minimum number of operations required to make the array good?\n\nWe have a proof that it is always possible with finitely many operations.",
    "tutorial": "To make the arithmetic mean be equal to exactly $1$ the sum needs to be equal to the number of elements in the array. Let's consider $3$ cases for this problem: 1) The sum of the array equals $n$: Here the answer is $0$ since the arithmetic mean of the array is initially $1$. 2) The sum of the array is smaller than $n$: The answer is always $1$ since we can add a single integer $k$ such that $sum + k = n + 1$ is satisfied and more specifically $k = n - sum + 1$. 3) The sum of the array is greater than $n$: If we add any number apart from $0$ will add to the sum more or equal than to the number of elements. The number of $0$'s to add can be found by a loop of adding $0$'s until the number of elements is equal to the sum or by the simple formula of $sum-n$.",
    "code": "#include \"bits/stdc++.h\"\n using namespace std;\n\n int main()\n {\n\t int t;\n\t cin >> t;\n\t while(t--){\n\t\t int n;\n\t\t cin >> n;\n\t\t int sum = 0;\n\t\t for (int i = 0;i < n; i++){\n\t\t\t int a;\n\t\t\t cin >> a;\n\t\t\t sum += a;\n\t\t }\n   if(sum < n)cout << \"1\\n\";\n   else cout << sum - n << \"\\n\";\n\t }\n }",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1537",
    "index": "B",
    "title": "Bad Boy",
    "statement": "Riley is a very bad boy, but at the same time, he is a yo-yo master. So, he decided to use his yo-yo skills to annoy his friend Anton.\n\nAnton's room can be represented as a grid with $n$ rows and $m$ columns. Let $(i, j)$ denote the cell in row $i$ and column $j$. Anton is currently standing at position $(i, j)$ in his room. To annoy Anton, Riley decided to throw exactly \\textbf{two} yo-yos in cells of the room (they can be in the same cell).\n\nBecause Anton doesn't like yo-yos thrown on the floor, he has to pick up both of them and return back to the initial position. The distance travelled by Anton is the shortest path that goes through the positions of both yo-yos and returns back to $(i, j)$ by travelling only to adjacent by side cells. That is, if he is in cell $(x, y)$ then he can travel to the cells $(x + 1, y)$, $(x - 1, y)$, $(x, y + 1)$ and $(x, y - 1)$ in one step (if a cell with those coordinates exists).\n\nRiley is wondering where he should throw these two yo-yos so that the distance travelled by Anton is \\textbf{maximized}. But because he is very busy, he asked you to tell him.",
    "tutorial": "We can notice that the optimal strategy is to put the yoyos in the corners of the board. One solution may be checking the best distance for all pairs of corners. But, if we think a bit more, we can notice that placing the yoyos in opposite corners the distance will always be maximum possible (the distance always being $2 \\cdot (n - 1) + 2 \\cdot (m - 1)$). So, one possible answer is to always place the first yoyo in the top-left cell and the second one in the bottom-right cell. This is always optimal because, for any initial position of Anton, the distance will still be the same ($2 \\cdot (n - 1) + 2 \\cdot (m - 1)$), this being the largest possible distance. The distance can not get larger than that, because if we move one of the yoyos it will get closer to the other yoyo and the distance will decrease by $1$ or won't decrease, but it's impossible for it to increase.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nint main()\n{\n    int t;\n    cin >> t;\n    while(t--){\n        int n, m, i, j;\n        cin >> n >> m >> i >> j;\n\n        cout << 1 << \" \" << 1 << \" \" << n << \" \" << m << \"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1537",
    "index": "C",
    "title": "Challenging Cliffs",
    "statement": "You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $n$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible.\n\nIn addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains $i$ ($1 \\leq i < n$) such that $h_i \\leq h_{i+1}$ where $h_i$ is the height of the $i$-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them.\n\nFrom all the arrangements that minimize $|h_1-h_n|$, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.",
    "tutorial": "We claim that the maximum difficulty is at least $n-2$. Assume the array is sorted. We first need to find the two mountains which go on the ends. To do this, we can iterate through every mountain in the sorted array and check the difference between a mountain and its neighbours in the array. Let $m_k$ and $m_{k+1}$ be the mountains with the smallest height difference. We can achieve at least a difficulty of $n-2$ by arranging the mountains as $m_k, m_{k+2}, m_{k+3} ... m_n, m_1, m_2, ....., m_{k+1}$. To get difficulty $n-1$, we need $m_k$ to be the shortest mountain and $m_{k+1}$ to be the tallest mountain. This will only happen if $n = 2$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nint main()\n{\n    int t;\n    cin >> t;\n    while(t--){\n        int n;\n        cin >> n;\n        vector<int> h(n);\n\n        for (int i = 0;i < n; i++){\n            cin >> h[i];\n        }\n        sort(h.begin(), h.end());\n\n        if(n == 2){\n            cout << h[0] << \" \" << h[1] << \"\\n\";\n            continue;\n        }\n\n        int pos = -1, mn = INT_MAX;\n\n        for (int i = 1;i < n; i++){\n            if(mn > abs(h[i] - h[i - 1])){\n                pos = i;\n                mn = abs(h[i] - h[i - 1]);\n            }\n        }\n        \n        for (int i = pos;i < n; i++){\n            cout << h[i] << \" \";\n        }\n        for(int i = 0;i < pos; i++){\n            cout << h[i] << \" \";\n        }\n\n        cout << \"\\n\";\n\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1537",
    "index": "D",
    "title": "Deleting Divisors",
    "statement": "Alice and Bob are playing a game.\n\nThey start with a positive integer $n$ and take alternating turns doing operations on it. Each turn a player can subtract from $n$ one of its divisors that isn't $1$ or $n$. The player who cannot make a move on his/her turn loses. Alice always moves first.\n\nNote that they subtract a divisor of the \\textbf{current} number in each turn.\n\nYou are asked to find out who will win the game if both players play optimally.",
    "tutorial": "Let's consider $3$ cases for this problem: 1) n is odd 2) n is even, and $n$ is not a power of $2$ 3) n is a power of $2$ If $n$ is odd, the only move is to subtract an odd divisor (since all the divisors are odd). Doing this, we will obtain an even number that is not a power of $2$(case 2). If $D$ is the divisor of $n$, then $n-D$ must also be divisible by $D$, and since $D$ is odd, $n-D$ cannot be a power of $2$. If $n$ is even and is not a power of $2$, it means that $n$ has an odd divisor. By subtracting this odd divisor, we will obtain $n-D$ is odd(case 1). Now let's show that subtracting an odd divisor every move results in a win. Primes are losing since the only move you can make on them is subtracting the entire number, which results in $n = 0$ and a loss. Since every prime is odd or a power of 2, it works to give the other player an odd number because it will either be a prime(the other player loses), or they will make a move and give you another even number that is not a power of 2. You can continue this process because you will never land on a losing number and because the game must end after a finite number of moves, your opponent must always lose. So we proved that odd numbers are losing and even numbers that are not powers of $2$ are winning. What if $n$ is a power of $2$? You can do two things in one move, halve $n$ or make n an even number that is not a power of $2$(we proved that this is a winning position for the other player). The only optimal move is to halve $n$, making it another power of $2$. The players continue like this until one gets $2$, which is a prime number, so it's losing. If $log_2(n)$ is even, Alice wins, otherwise Bob wins.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \nint main()\n{\n    int t;\n    cin >> t;\n \n    while(t--){\n        \n        int n;\n        cin >> n;\n        if(n % 2 == 1){\n            cout << \"Bob\\n\";\n            continue;\n        }\n        int cnt = 0;\n        while(n % 2 == 0){\n            cnt++;\n            n /= 2;\n        }\n \n        if(n > 1){\n            cout << \"Alice\\n\";\n        }else if(cnt % 2 == 0){\n            cout << \"Alice\\n\";\n        }else cout << \"Bob\\n\";\n    }\n}",
    "tags": [
      "games",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1537",
    "index": "E1",
    "title": "Erase and Extend (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.}\n\nYou have a string $s$, and you can do two types of operations on it:\n\n- Delete the last character of the string.\n- Duplicate the string: $s:=s+s$, where $+$ denotes concatenation.\n\nYou can use each operation any number of times (possibly none).\n\nYour task is to find the lexicographically smallest string of length exactly $k$ that can be obtained by doing these operations on string $s$.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a\\ne b$;\n- In the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "We claim that it is optimal to choose a prefix of the string, then duplicate it until we have a length bigger than $k$, then delete the excess elements. Let's relax the requirement so you have a position in the string and each time you either return to the beginning or advance to the next character. The answer will be the first k characters of the lexicographically smallest infinite string. From a given position, the optimal infinite string from it is unique, so you can pick exactly one optimal decision. Now the optimal string is going around some cycle from the start, and we see it also satisfies the original requirement, not just our relaxation We proved that it is optimal to choose a prefix, duplicate it until the length is bigger than k then delete the excess. As the constraints are low, we can iterate through every prefix on the original string and make a string of length $k$ with it. Then we take the minimum of all these strings as the answer. Solution complexity $O(n\\cdot k)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nstring get(string s, int k){\n    while((int)s.size() < k){\n        s = s + s;\n    }\n    while((int)s.size() > k)\n        s.pop_back();\n    return s;\n}\nint main()\n{\n    int n, k;\n    string s;\n    cin >> n >> k;\n    cin >> s;\n\n    string pref = \"\";\n    pref += s[0];\n\n    string mn = get(pref, k);\n\n    for(int i = 1;i < n;i++){\n        if(s[i] > s[0])break;\n        pref += s[i];\n        mn = min(mn, get(pref, k));\n    }\n    cout << mn << \"\\n\";\n}",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "greedy",
      "hashing",
      "implementation",
      "string suffix structures",
      "strings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1537",
    "index": "E2",
    "title": "Erase and Extend (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.}\n\nYou have a string $s$, and you can do two types of operations on it:\n\n- Delete the last character of the string.\n- Duplicate the string: $s:=s+s$, where $+$ denotes concatenation.\n\nYou can use each operation any number of times (possibly none).\n\nYour task is to find the lexicographically smallest string of length exactly $k$ that can be obtained by doing these operations on string $s$.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a\\ne b$;\n- In the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "We know that the final string is some prefix repeated a bunch of times. Incrementally for $i$ from $1$ to $n$ we will keep the longest among the first $i$ prefixes that gives the best answer we've seen so far. So assume the $m-th$ prefix is currently the best and we're considering position $p$. If the $p-th$ character is greater than the corresponding character in $s_{1..m} \\cdot (a lot)$ then the $p-th$ prefix and any further prefixes can't possibly give a smaller answer, so we just print the current one and finish. Otherwise all the characters before the $p-th$ are all less than or equal to the corresponding characters in $s_1..m \\cdot (a lot)$, so if the $p-th$ is smaller than the corresponding we set the $p-th$ prefix as the best. Now the interesting case is if the current character is the same as the corresponding one. Say then that $p = m + t$, by the logic of the previous paragraph we must have $s_{(m + 1)..(m + t)} = s_{1..t}$. If $t = m$ then the new prefix is just the old one twice, so set $p$ as the best prefix now. This ensures that otherwise $t < m$. Denote $A = s_{1..t}$ and $B = s_{(t + 1)..m}$, so the string formed by the current best prefix is $ABABABABA...$ and the new one is $ABAABAABA...$ Now if $AB = BA$ then these strings are in fact the same, so set $m + t$ as the new best prefix. Otherwise we can find the first position where $AB$ and $BA$ differ, and use that to determine whether the new prefix is better. This can be done in $O(1)$ with Z function, thus giving a linear solution for the full problem.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nstring s;\nint n, k;\n\nvector<int> z_func(string &s) {\n    int n = s.size(), L = -1, R = -1;\n    vector<int> z(n);\n    z[0] = n;\n    for(int i = 1; i < n; i++) {\n        if(i <= R)\n            z[i] = min(z[i - L], R - i + 1);\n        while(i + z[i] < n && s[i + z[i]] == s[z[i]])\n            z[i]++;\n        if(i + z[i] - 1 > R) {\n            L = i;\n            R = i + z[i] - 1;\n        }\n    }\n    return z;\n}\n\nvoid finish(int m) {\n    for(int i = 0; i < k; i++)\n        cout << s[i % m];\n    cout << '\\n';\n    exit(0);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    cin >> n >> k >> s;\n    auto z = z_func(s);\n\n    int cur = 1;\n    for(int i = 1; i < n; i++) {\n        if(s[i] > s[i % cur])\n            finish(cur);\n        if(s[i] < s[i % cur]) {\n            cur = i + 1;\n            continue;\n        }\n        int off = i - cur + 1;\n        if(off == cur) {\n            cur = i + 1;\n            continue;\n        }\n        if(z[off] < cur - off) {\n            if(cur + off + z[off] >= k) {\n                cur = i + 1;\n                continue;\n            }\n            if(s[off + z[off]] > s[z[off]])\n                cur = i + 1;\n            continue;\n        }\n        if(z[cur - off] < off) {\n            if(2 * cur + z[cur - off] >= k) {\n                cur = i + 1;\n                continue;\n            }\n            if(s[cur - off + z[cur - off]] < s[z[cur - off]])\n                cur = i + 1;\n            continue;\n        }\n        cur = i + 1;\n    }\n\n    finish(cur);\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "hashing",
      "string suffix structures",
      "strings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1537",
    "index": "F",
    "title": "Figure Fixing",
    "statement": "You have a connected undirected graph made of $n$ nodes and $m$ edges. The $i$-th node has a value $v_i$ and a target value $t_i$.\n\nIn an operation, you can choose an edge $(i, j)$ and add $k$ to both $v_i$ and $v_j$, where $k$ can be any \\textbf{integer}. In particular, $k$ can be negative.\n\nYour task to determine if it is possible that by doing some finite number of operations (possibly zero), you can achieve for every node $i$, $v_i = t_i$.",
    "tutorial": "If the parity of the sum of the initial values doesn't match the parity of the sum of the target values then there is no solution. Because $k$ is an integer and we always add the value $2 \\cdot k$ to the sum of the initial values in each operation it's easy to notice that the parity of the sum of the initial values never changes. Otherwise, let's consider $2$ cases: 2) The graph is bipartite. 3) The graph is not bipartite. If the graph is bipartite, let the nodes be coloured red and blue with the condition that all the neighbors of any red node are blue and all the neighbours of any blue node are red. Let us call $sum1 = \\sum target_i-value_i$ for each blue node and $sum2 = \\sum target_i-value_i$ for each red node. We want to determine if we can make $target_i = value_i$ for each node, which is equivalent to saying $sum1 = 0$ and $sum2 = 0$. We notice that the difference between $sum1$ and $sum2$ is invariant in a bipartite graph because all operations will add to $sum1$ and $sum2$ at the same time. So to make $sum1 = 0$ and $sum2 = 0$ we need $sum1-sum2$ to be equal to $0$ initially. If the graph is not bipartite, then it is always possible because if the graph is not bipartite, it contains two neighboring vertices of the same color, which can be used to add or subtract from their color sum.",
    "code": "#include \"bits/stdc++.h\"\n using namespace std;\n\n const int N = 2e5 + 10;\n vector<long long> adj[N];\n long long s[N], n, m;\n bool bipartite()\n {\n\t bool bip = true;\n\n\t for(long long i = 0;i < n;i++)\n\t\t s[i] = -1;\n\n\t queue<long long> q;\n\n\t for(long long i = 0;i < n;i++){\n\t\t if(s[i] != -1)continue;\n\n\t\t q.push(i);\n\t\t s[i] = 0;\n\n\t\t while(!q.empty()){\n\t\t\t long long v = q.front();\n\t\t\t q.pop();\n\n\t\t\t for(long long u: adj[v]){\n\t\t\t\t if(s[u] == -1){\n\t\t\t\t\t s[u] = s[v] ^ 1;\n\t\t\t\t\t q.push(u);\n\t\t\t\t }else bip &= s[u] != s[v];\n\t\t\t }\n\t\t }\n\t }\n\t return bip;\n }\n\n int main()\n {\n\t ios_base::sync_with_stdio(0);cin.tie(0);\n\t long long T;\n\t cin >> T;\n\t while(T--)\n\t {\n\t\t cin >> n >> m;\n\t\t for(long long i = 0;i < n;i++)\n\t\t\t adj[i].clear();\n\n\t\t vector<long long> v(n), t(n);\n\t\tlong long p1 = 0, p2 = 0;\n\t\t for(long long i = 0;i < n; i++){\n\t\t\t cin >> v[i];\n\t\t\t p1 = (p1 + abs(v[i])) % 2;\n\t\t }\n\t\t for (long long i = 0;i < n; i++){\n\t\t\t cin >> t[i];\n\t\t\t p2 = (p2 + abs(t[i])) % 2;\n\t\t }\n\n\t\t for(long long i = 0;i < m;i++){\n\t\t\t long long a, b;\n\t\t\t cin >> a >> b;\n\t\t\t --a, --b;\n\t\t\t adj[a].push_back(b);\n\t\t\t adj[b].push_back(a);\n\t\t }\n\t\t \n\t\t if(p1 != p2){\n\t\t   cout << \"NO\\n\";\n\t\t   continue;\n\t\t }\n\n\t\t if(bipartite() == false){\n\t\t\t cout << \"YES\\n\";\n\t\t }else{\n\t\t\t vector<long long> c(2, 0);\n\n\t\t\t for(int i = 0;i < n;i++){\n\t\t\t\t c[s[i]] += v[i] - t[i];\n\t\t\t }\n\n\t\t\t if(c[0] == c[1]){\n\t\t\t\t cout << \"YES\\n\";\n\t\t\t }else cout << \"NO\\n\";\n\t\t }\n\t }\n\n }\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1538",
    "index": "A",
    "title": "Stone Game",
    "statement": "Polycarp is playing a new computer game. This game has $n$ stones in a row. The stone on the position $i$ has integer power $a_i$. \\textbf{The powers of all stones are distinct}.\n\nEach turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.\n\nNow, Polycarp wants two achievements. He gets them if he destroys the stone with the \\textbf{least} power and the stone with the \\textbf{greatest} power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.\n\nFor example, if $n = 5$ and $a = [1, 5, 4, 3, 2]$, then Polycarp could make the following moves:\n\n- Destroy the leftmost stone. After this move $a = [5, 4, 3, 2]$;\n- Destroy the rightmost stone. After this move $a = [5, 4, 3]$;\n- Destroy the leftmost stone. After this move $a = [4, 3]$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.\n\nPlease note that in the example above, you can complete the game in two steps. For example:\n\n- Destroy the leftmost stone. After this move $a = [5, 4, 3, 2]$;\n- Destroy the leftmost stone. After this move $a = [4, 3, 2]$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.",
    "tutorial": "If we want to destroy the largest and smallest stone, then there are only four options: Destroy the stones on the left until we destroy the smallest stone. Then destroy the stones on the right, until we destroy the largest stone. Destroy the stones on the right until we destroy the smallest stone. Then destroy the stones on the left, until we destroy the largest stone. Destroy the stones on the left until we destroy both stones. Destroy the stones on the right until we destroy both stones. You need to check all four options and choose the minimum answer. You need to check all four options and choose the minimum answer.",
    "code": "#include <bits/stdc++.h>\n#include \"random\"\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> v(n);\n    for (int &e : v) {\n        cin >> e;\n    }\n    int maxPos = max_element(v.begin(), v.end()) - v.begin();\n    int minPos = min_element(v.begin(), v.end()) - v.begin();\n    cout << min({\n            max(maxPos, minPos) + 1,\n            (n - 1) - min(maxPos, minPos) + 1,\n            (n - 1) - maxPos + minPos + 2,\n            (n - 1) - minPos + maxPos + 2\n    }) << \"\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1538",
    "index": "B",
    "title": "Friends and Candies",
    "statement": "Polycarp has $n$ friends, the $i$-th of his friends has $a_i$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $a_i$ to be the same. To solve this, Polycarp performs the following set of actions exactly \\textbf{once}:\n\n- Polycarp chooses $k$ ($0 \\le k \\le n$) arbitrary friends (let's say he chooses friends with indices $i_1, i_2, \\ldots, i_k$);\n- Polycarp distributes their $a_{i_1} + a_{i_2} + \\ldots + a_{i_k}$ candies among all $n$ friends. During distribution for each of $a_{i_1} + a_{i_2} + \\ldots + a_{i_k}$ candies he chooses new owner. That can be any of $n$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process.\n\nNote that the number $k$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $k$.\n\nFor example, if $n=4$ and $a=[4, 5, 2, 5]$, then Polycarp could make the following distribution of the candies:\n\n- Polycarp chooses $k=2$ friends with indices $i=[2, 4]$ and distributes $a_2 + a_4 = 10$ candies to make $a=[4, 4, 4, 4]$ (two candies go to person $3$).\n\nNote that in this example Polycarp cannot choose $k=1$ friend so that he can redistribute candies so that in the end all $a_i$ are equal.\n\nFor the data $n$ and $a$, determine the \\textbf{minimum} value $k$. With this value $k$, Polycarp should be able to select $k$ friends and redistribute their candies so that everyone will end up with the same number of candies.",
    "tutorial": "Let's denote for $s$ the number of candies all friends have: $s = \\sum\\limits_{i=1}^{n} a_i$. Note that at the end, each friend must have $\\frac{s}{n}$ of candy. If $s$ is not completely divisible by $n$, then there is no answer. How to get the answer if it exists? If the $i$-th friend has more candies than $\\frac{s}{n}$, then he must be chosen by Polycarp (otherwise this friend will have more candies than the others). If the $i$-th friend has no more than $\\frac{s}{n}$, then Polycarp may not choose it. Then, if the answer exists, it is equal to the number of $a_i > \\frac{s}{n}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  int s = 0;\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n    s += a[i];\n  }\n  if (s % n != 0) {\n    cout << \"-1\" << endl;\n    return;\n  }\n  s /= n;\n  int res = 0;\n  for (int i = 0; i < n; i++) {\n    if (s < a[i]) {\n      res++;\n    }\n  }\n  cout << res << endl;\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1538",
    "index": "C",
    "title": "Number of Pairs",
    "statement": "You are given an array $a$ of $n$ integers. Find the number of pairs $(i, j)$ ($1 \\le i < j \\le n$) where the sum of $a_i + a_j$ is greater than or equal to $l$ and less than or equal to $r$ (that is, $l \\le a_i + a_j \\le r$).\n\nFor example, if $n = 3$, $a = [5, 1, 2]$, $l = 4$ and $r = 7$, then two pairs are suitable:\n\n- $i=1$ and $j=2$ ($4 \\le 5 + 1 \\le 7$);\n- $i=1$ and $j=3$ ($4 \\le 5 + 2 \\le 7$).",
    "tutorial": "The problem can be divided into two classic ones: Count the number of pairs $a_i+a_j \\le r$; Count the number of pairs $a_i+a_j \\le l-1$. Let $A$ - be the answer to the first problem, and $B$ - be the answer to the second problem. Then $A-B$ is the answer to the original problem. The new problem can be solved by binary search. Iterate over the first element of the pair. Then you need to count the number of elements such that $a_j \\le r - a_i$. If you sort the array, this value can be calculated by running a single binary search.",
    "code": "#include <bits/stdc++.h>\n#include \"random\"\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nvoid solve() {\n    int n, l, r;\n    cin >> n >> l >> r;\n    vector<int> v(n);\n    for (int &e : v) {\n        cin >> e;\n    }\n    sort(v.begin(), v.end());\n    ll ans = 0;\n    for (int i = 0; i < n; i++) {\n        ans += upper_bound(v.begin(), v.end(), r - v[i]) - v.begin();\n        ans -= lower_bound(v.begin(), v.end(), l - v[i]) - v.begin();\n        if (l <= 2 * v[i] && 2 * v[i] <= r) {\n            ans--;\n        }\n    }\n    cout << ans / 2 << \"\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "math",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1538",
    "index": "D",
    "title": "Another Problem About Dividing Numbers",
    "statement": "You are given two integers $a$ and $b$. In one turn, you can do one of the following operations:\n\n- Take an integer $c$ ($c > 1$ and \\textbf{$a$ should be divisible by $c$}) and replace $a$ with $\\frac{a}{c}$;\n- Take an integer $c$ ($c > 1$ and \\textbf{$b$ should be divisible by $c$}) and replace $b$ with $\\frac{b}{c}$.\n\nYour goal is to make $a$ equal to $b$ using exactly $k$ turns.\n\nFor example, the numbers $a=36$ and $b=48$ can be made equal in $4$ moves:\n\n- $c=6$, divide $b$ by $c$ $\\Rightarrow$ $a=36$, $b=8$;\n- $c=2$, divide $a$ by $c$ $\\Rightarrow$ $a=18$, $b=8$;\n- $c=9$, divide $a$ by $c$ $\\Rightarrow$ $a=2$, $b=8$;\n- $c=4$, divide $b$ by $c$ $\\Rightarrow$ $a=2$, $b=2$.\n\nFor the given numbers $a$ and $b$, determine whether it is possible to make them equal using exactly $k$ turns.",
    "tutorial": "Let's denote for $n$ the maximum number of moves for which the numbers $a$ and $b$ can be made equal. It is easy to understand that the number of moves is maximum when $a=b=1$ and each time we divided $a$ or $b$ by a prime number. That is, $n=$ sum of exponents of prime divisors of $a+$ sum of exponents of prime divisors of $b$. Let's denote by $m$ the minimum number of moves for which the numbers $a$ and $b$ can be made equal. Consider a few cases: If $a=b$, then $m=0$; If $gcd (a, b)=a$ or $gcd (a, b)=b$, then $m=1$; Otherwise, then $m=2$. Then, the answer \"Yes\" is possible in the following cases: $m \\le k \\le n$ and $k=1$ and $m = 1$, or, $m \\le k \\le n$ and $k \\ne 1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nconst int N = 50'000;\n\nbool isPrime[N];\nvector<int> primes;\n\nvoid precalc() {\n  fill(isPrime + 2, isPrime + N, true);\n  for (int i = 2; i * i < N; i++) {\n    for (int j = i * i; j < N; j += i) {\n      isPrime[j] = false;\n    }\n  }\n  for (int i = 2; i < N; i++) {\n    if (isPrime[i]) {\n      primes.push_back(i);\n    }\n  }\n}\n\nint calcPrime(int n) {\n  int res = 0;\n  for (int i : primes) {\n    if (i * i > n) {\n      break;\n    }\n    while (n % i == 0) {\n      n /= i;\n      res++;\n    }\n  }\n  if (n > 1) {\n    res++;\n  }\n  return res;\n}\n\nmap<int, int> decompose(int n) {\n  map<int, int> a;\n  for (int i : primes) {\n    if (i * i > n) {\n      break;\n    }\n    int p = 0;\n    while (n % i == 0) {\n      n /= i;\n      p++;\n    }\n    if (p > 0) {\n      a[i] = p;\n    }\n  }\n  if (n > 1) {\n    a[n] = 1;\n  }\n  return a;\n}\n\nbool check(const map<int, int> &divs,\n           map<int, int>::const_iterator it,\n           map<int, int> &divsA,\n           map<int, int> &divsB,\n           int low,\n           int high,\n           int k) {\n  if (it == divs.end()) {\n    return __builtin_popcount(low) <= k && k <= high;\n  }\n  for (int p = 0; p <= it->second; p++) {\n    int pa = divsA[it->first];\n    int pb = divsB[it->first];\n    int nextLow = low;\n    if (p != pa) {\n      nextLow |= 1;\n    }\n    if (p != pb) {\n      nextLow |= 2;\n    }\n    if (check(divs, next(it), divsA, divsB, nextLow, high + pa + pb - 2 * p, k)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nvoid solve() {\n  int a, b, k;\n  cin >> a >> b >> k;\n  int g = __gcd(a, b);\n  int low = 0;\n  int high = 0;\n  {\n    int t;\n    int ta = 1;\n    while ((t = __gcd(a, g)) != 1) {\n      a /= t;\n      ta *= t;\n    }\n    high += calcPrime(a);\n    if (a != 1) {\n      low |= 1;\n    }\n    a = ta;\n  }\n  {\n    int t;\n    int tb = 1;\n    while ((t = __gcd(b, g)) != 1) {\n      b /= t;\n      tb *= t;\n    }\n    high += calcPrime(b);\n    if (b != 1) {\n      low |= 2;\n    }\n    b = tb;\n  }\n  auto divs = decompose(g);\n  auto divsA = decompose(a);\n  auto divsB = decompose(b);\n  cout << (check(divs, divs.begin(), divsA, divsB, low, high, k) ? \"YES\" : \"NO\") << endl;\n}\n\nint main() {\n  precalc();\n\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1538",
    "index": "E",
    "title": "Funny Substrings",
    "statement": "Polycarp came up with a new programming language. There are only two types of statements in it:\n\n- \"x := s\": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a variable. Between the variable name, the := operator and the string contains exactly one space each.\n- \"x = a + b\": assign the variable named x the concatenation of values of two variables a and b. For example, if the program consists of three statements a := hello, b := world, c = a + b, then the variable c will contain the string helloworld. It is guaranteed that the program is correct and the variables a and b were previously defined. There is exactly one space between the variable names and the = and + operators.\n\nAll variable names and strings only consist of lowercase letters of the English alphabet and do not exceed $5$ characters.\n\nThe result of the program is the number of occurrences of string haha in the string that was written to the variable in the last statement.\n\nPolycarp was very tired while inventing that language. He asks you to implement it. Your task is — for given program statements calculate the number of occurrences of string haha in the last assigned variable.",
    "tutorial": "We can't model this process directly, since the maximum string length reaches $2^{50}$ (look at the second example from the statements). To optimize this process, you can store each row as a set of the following values. Number of occurrences of haha in the string - $cnt$. String length - $length$. The first three characters of the string are - $pref$. The last three characters of the string are - $suff$. Then, to process the second type of request and combine the two strings $a$ and $b$ into the string $c$, you need: $c.length = a.length + b.length$. $c.cnt = a.cnt + b.cnt + count(a.suff + b.pref, haha)$. (New occurrences may be added at the junction of two words) $c. pref = a. pref$ (However, if the string length is less than $6=3+3$, then you need to handle this case carefully with your hands) $c. suff = b. suff$ (Similarly, you need to process small strings separately).",
    "code": "#include <bits/stdc++.h>\n#include \"random\"\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nvector<string> split(const string& s, char p) {\n    vector<string> res(1);\n    for (char c : s) {\n        if (c == p) {\n            res.emplace_back();\n        } else {\n            res.back() += c;\n        }\n    }\n    return res;\n}\n\nstruct Word {\n    ll len;\n    ll cnt;\n    string s;\n};\n\nstring getFirst(string s) {\n    if (s.size() < 3) {\n        return s;\n    }\n    return s.substr(0, 3);\n}\n\nstring getLast(string s) {\n    if (s.size() < 3) {\n        return s;\n    }\n    return s.substr(s.size() - 3, 3);\n}\n\nint count(const string& s, const string& p) {\n    int cnt = 0;\n    for (int i = 0; i + p.size() <= s.size(); i++) {\n        if (s.substr(i, p.size()) == p) {\n            cnt++;\n        }\n    }\n    return cnt;\n}\n\nWord merge(const Word& a, const Word& b) {\n    Word c;\n    c.len = a.len + b.len;\n    c.s = a.s + b.s;\n    c.cnt = a.cnt + b.cnt + count(getLast(a.s) + getFirst(b.s), \"haha\");\n    if (c.s.size() >= 7) {\n        c.s = getFirst(c.s) + \"@\" + getLast(c.s);\n    }\n    return c;\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    map<string, Word> vars;\n    ll ans = 0;\n    for (int i = 0; i < n; i++) {\n        string var;\n        cin >> var;\n        string opr;\n        cin >> opr;\n        if (opr == \"=\") {\n            string a, plus, b;\n            cin >> a >> plus >> b;\n            vars[var] = merge(vars[a], vars[b]);\n        } else {\n            string str;\n            cin >> str;\n            Word word;\n            word.len = str.length();\n            word.cnt = count(str, \"haha\");\n            word.s = str;\n            vars[var] = word;\n        }\n        ans = vars[var].cnt;\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "hashing",
      "implementation",
      "matrices",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1538",
    "index": "F",
    "title": "Interesting Function",
    "statement": "You are given two integers $l$ and $r$, where $l < r$. We will add $1$ to $l$ until the result is equal to $r$. Thus, there will be exactly $r-l$ additions performed. For each such addition, let's look at the number of digits that will be changed after it.\n\nFor example:\n\n- if $l=909$, then adding one will result in $910$ and $2$ digits will be changed;\n- if you add one to $l=9$, the result will be $10$ and $2$ digits will also be changed;\n- if you add one to $l=489999$, the result will be $490000$ and $5$ digits will be changed.\n\nChanged digits always form a suffix of the result written in the decimal system.\n\nOutput the total number of changed digits, if you want to get $r$ from $l$, adding $1$ each time.",
    "tutorial": "For each digit, we will count how many times it has changed. The number of changes for the first digit (the lowest) is calculated using the formula $r-l$. The number of changes for the second digit is calculated by the formula $\\left\\lfloor\\frac{r}{10}\\right\\rfloor-\\left\\lfloor\\frac{l}{10}\\right\\rfloor$. That is, it is equivalent to the number of first-digit changes for numbers from $\\left\\lfloor\\frac{l}{10}\\right\\rfloor$ to $\\left\\lfloor\\frac{r}{10}\\right\\rfloor$. To calculate the number of changes for the remaining digits, you need to apply similar reasoning with dividing the numbers by $10$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nvoid solve () {\n  int L, R;\n  cin >> L >> R;\n\n  int ans = 0;\n  while (L != 0 || R != 0) {\n    ans += R - L;\n    L /= 10;\n    R /= 10;\n  }\n  cout << ans << '\\n';\n}\n\nint main () {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  \n  int testc;\n  cin >> testc;\n\n  for (int i = 0; i < testc; i++) {\n    solve();\n  }\n}",
    "tags": [
      "binary search",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1538",
    "index": "G",
    "title": "Gift Set",
    "statement": "Polycarp has $x$ of red and $y$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $a$ red candies and $b$ blue candies, or $a$ blue candies and $b$ red candies. Any candy can belong to at most one gift set.\n\nHelp Polycarp to find the largest number of gift sets he can create.\n\nFor example, if $x = 10$, $y = 12$, $a = 5$, and $b = 2$, then Polycarp can make three gift sets:\n\n- In the first set there will be $5$ red candies and $2$ blue candies;\n- In the second set there will be $5$ blue candies and $2$ red candies;\n- In the third set will be $5$ blue candies and $2$ red candies.\n\nNote that in this example there is one red candy that Polycarp does not use in any gift set.",
    "tutorial": "In this problem, we can use a binary search for the answer (If we can make $x$ sets, then we can make $y < x$ sets). So, we need to come up with the following test, whether we can make $n$ sets knowing the parameters $x, y, a, b$. Let $a > b$ (otherwise we will swap them). If $a == b$, the answer is $\\lfloor\\frac{min(x, y)}{a}\\rfloor$. Otherwise, let's say we want to make $k$ sets of the first kind. Then we get a system of inequalities $x \\le a \\cdot k + b \\cdot (n - k)$ $y \\le a \\cdot (n - k) + b \\cdot k$ Let's express $k$from here $\\frac{(x - b \\cdot n)}{a - b} \\le k$ $\\frac{(x - a \\cdot n)}{b - a} \\ge k$ $0 \\le k$ $n \\ge k$ We need to check whether these four equations have an intersection in integers. If there is, then the division into $n$ gifts exists.",
    "code": "#include <bits/stdc++.h>\n#include \"random\"\n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing cd = complex<ld>;\n\nvoid solve() {\n    ll x, y, a, b;\n    cin >> x >> y >> a >> b;\n    ll l = 0, r = 1e9 + 100;\n    if (a == b) {\n        cout << min(x, y) / a << \"\\n\";\n        return;\n    }\n    if (a < b) {\n        swap(a, b);\n    }\n    while (r - l > 1) {\n        ll m = (l + r) / 2;\n        ll right = floorl((x - m * b) * 1.0l / (a - b));\n        ll left = ceill((y - m * a) * 1.0l / (b - a));\n        if (max(left, 0ll) <= min(right, m)) {\n            l = m;\n        } else {\n            r = m;\n        }\n    }\n    cout << l << \"\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "ternary search"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1539",
    "index": "A",
    "title": "Contest Start",
    "statement": "There are $n$ people participating in some contest, they start participating in $x$ minutes intervals. That means the first participant starts at time $0$, the second participant starts at time $x$, the third — at time $2 \\cdot x$, and so on.\n\nDuration of contest is $t$ minutes for each participant, so the first participant finishes the contest at time $t$, the second — at time $t + x$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.\n\nDetermine the sum of dissatisfaction of all participants.",
    "tutorial": "Let's find which participants will disturb participant $i$. Those are participants with number between $i + 1$ and $i + min(t / x, n)$. So each of first $max(0, n - t / x)$ participants will get $t / x$ dissatisfaction, and each next participant will get 1 dissatisfaction less, than previous. So the total answer is $max(0, n - t / x) \\cdot t / x + min(n - 1, t / x - 1) \\cdot min(n, t / x) / 2$.",
    "tags": [
      "combinatorics",
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1539",
    "index": "B",
    "title": "Love Song",
    "statement": "Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $q$ questions about this song. Each question is about a subsegment of the song starting from the $l$-th letter to the $r$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $k$ times, where $k$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring \"abbcb\", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c\" three times, so that the resulting string is \"abbbbcccbb\", its length is $10$. Vasya is interested about the length of the resulting string.\n\nHelp Petya find the length of each string obtained by Vasya.",
    "tutorial": "One can notice that letter with number $x$ will add exactly $x$ to the answer. So, all we have to do is calculate the sum of numbers of letters in our substring. This can be done using prefix sums.",
    "tags": [
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1539",
    "index": "C",
    "title": "Stable Groups",
    "statement": "There are $n$ students numerated from $1$ to $n$. The level of the $i$-th student is $a_i$. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than $x$.\n\nFor example, if $x = 4$, then the group with levels $[1, 10, 8, 4, 4]$ is stable (because $4 - 1 \\le x$, $4 - 4 \\le x$, $8 - 4 \\le x$, $10 - 8 \\le x$), while the group with levels $[2, 10, 10, 7]$ is not stable ($7 - 2 = 5 > x$).\n\nApart from the $n$ given students, teachers can invite at most $k$ additional students with \\textbf{arbitrary} levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).\n\nFor example, if there are two students with levels $1$ and $5$; $x = 2$; and $k \\ge 1$, then you can invite a new student with level $3$ and put all the students in one stable group.",
    "tutorial": "Firstly, we will find the amount of groups needed if we don't add any new students. Let's consider the students in the increasing order of their knowledge level. Students are greedily determined to the same group if the difference of their knowledge levels is not greater than $x$. Else we create another group. After that all students will be split into continuous non-intersecting segments - stable groups. Merging two segments with knowledge difference $d$ may be done by adding $\\lceil\\frac{d}{x}\\rceil - 1$ new students. Each such merge decreases the answer by $1$ so we should maximize the amount of merges. To do that we should just consider the merges in increasing order of their costs.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1539",
    "index": "D",
    "title": "PriceFixed",
    "statement": "Lena is the most economical girl in Moscow. So, when her dad asks her to buy some food for a trip to the country, she goes to the best store  — \"PriceFixed\". Here are some rules of that store:\n\n- The store has an infinite number of items of every product.\n- All products have the same price: $2$ rubles per item.\n- For every product $i$ there is a discount for experienced buyers: if you buy $b_i$ items of products (\\textbf{of any type}, not necessarily type $i$), then for all future purchases of the $i$-th product there is a $50\\%$ discount (so you can buy an item of the $i$-th product for $1$ ruble!).\n\nLena needs to buy $n$ products: she must purchase at least $a_i$ items of the $i$-th product. Help Lena to calculate the minimum amount of money she needs to spend if she optimally chooses the order of purchasing. Note that if she wants, she can buy more items of some product than needed.",
    "tutorial": "Let $m$ be the sum of all $a_i$ Important greedy observations: If there is an item which costs 1, then we will not make the answer worse by buying this item. If all prices are 2, then we will not make the answer worse by buying the item with max $b_i$. Therefore we can sort all items by $b_i$ and on each iteration we will only need to consider two items: with max $b_i$ and with min $b_i$ among us all not bought items. Another important observation: We already know how many items with price 2 we should buy to be able to buy something with a discount. This means that we can buy multiple items with full price together. Similarly, we can buy multiple items with a discount at once. This solution can be implemented using a two pointers technique which allows to find the answer in $O(n \\cdot \\log{n})$.",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1539",
    "index": "E",
    "title": "Game with Cards",
    "statement": "The Alice's computer is broken, so she can't play her favorite card game now. To help Alice, Bob wants to answer $n$ her questions.\n\nInitially, Bob holds one card with number $0$ in the left hand and one in the right hand. In the $i$-th question, Alice asks Bob to replace a card in the left or right hand with a card with number $k_i$ (Bob chooses which of two cards he changes, Bob must replace exactly one card).\n\nAfter this action, Alice wants the numbers on the left and right cards to belong to given segments (segments for left and right cards can be different). Formally, let the number on the left card be $x$, and on the right card be $y$. Then after the $i$-th swap the following conditions must be satisfied: $a_{l, i} \\le x \\le b_{l, i}$, and $a_{r, i} \\le y \\le b_{r,i}$.\n\nPlease determine if Bob can answer all requests. If it is possible, find a way to do it.",
    "tutorial": "Let's use dynamic programming to solve the problem. $dp_L[i]$ is equal to 1 if we can correcly answer queries on suffix the way that $i$-th card is taken in left hand and $i+1$-th card is taken in right hand. $dp_R[i]$ is equal to 1 if we can correcly answer queries on suffix the way that $i$-th card is taken in right hand and $i+1$-th card is taken in left hand. Let's consider transitions to count $dp_L$. Let's suppose we have $j$ such that $dp_R[j] = 1$. Then we can tell that $dp_L[i] = 1$, if these 2 conditions hold: We can take all cards with indexes $[i + 1, j]$ in right hand. Card in query $i$ fits constraints on value written on card in left hand in queries with indexes $[i, j]$.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1539",
    "index": "F",
    "title": "Strange Array",
    "statement": "Vasya has an array of $n$ integers $a_1, a_2, \\ldots, a_n$. Vasya thinks that all numbers in his array are strange for some reason. To calculate how strange the $i$-th number is, Vasya created the following algorithm.\n\nHe chooses a subsegment $a_l, a_{l+1}, \\ldots, a_r$, such that $1 \\le l \\le i \\le r \\le n$, sort its elements in increasing order in his head (he can arrange equal elements arbitrary). After that he finds the center of the segment. The center of a segment is the element at position $(l + r) / 2$, if the length of the segment is odd, and at position $(l + r + 1) / 2$ otherwise. Now Vasya finds the element that was at position $i$ before the sorting, and calculates the distance between its current position and the center of the subsegment (the distance between the elements with indices $j$ and $k$ is $|j - k|$).\n\nThe strangeness of the number at position $i$ is the maximum distance among all suitable choices of $l$ and $r$.\n\nVasya wants to calculate the strangeness of each number in his array. Help him to do it.",
    "tutorial": "Note that the distance from the given element to the median element (the center of a sorted segment) can be defined in terms of numbers of elements that are less, equal or bigger than the given element. Let $cnt_L$ be the number of elements that are less, $cnt_M$ - equal (excluding the given) and $cnt_R$ - bigger than the given element. Then the distance may be calculated in the following way: If $a_i$ is bigger than the median element: $ans = \\lfloor \\frac{cnt_L + cnt_M - cnt_R}{2}\\rfloor$ otherwise $ans = \\lfloor \\frac{cnt_R + cnt_M - cnt_L + 1}{2}\\rfloor$ To solve the problem you firstly need to assume that the given element is greater than the median element, then consider the other case and take the maximum of two answers. Hereinafter only the second case is considered (in which the element is not greater than the median one), the first case can be done analogically. Since we need to maximize $cnt_R + cnt_M - cnt_L$, let's do it separately for the elements to the left and to the right of ours. Let's sort the indices so that the corresponding elements go in increasing order. Let array $D = [1, 1 \\ldots, 1]$ (its size is $n$) and $P = [1, 2, \\ldots n]$. We will need operations \"+= on the segment\" and \"min/max on the segment\", so let's build a segment tree for $P$. We will iterate through the indices in the received order and when considering the index $i$ we'll change $D$ and $P$ so that they correspond to the following conditions: For each $1 \\le j \\le n$ if $a_j < a_i$ then $D_j = -1$, else $D_j = 1$ Array $P$ is a prefix sum array for $D$ (changes to $P$ are made via a segment tree) In order to find $\\max(cnt_R + cnt_M - cnt_L)$ among elements to the left of $i$ we need to find $\\min\\limits_{j=1}^{i} P_j$. In order to find $\\max(cnt_R + cnt_M - cnt_L)$ among elements to the right of i will find $\\max \\limits_{j=i}^{n} P_j$. We will find these values using the segment tree for $P$ and consider the next index. Note that for all the changes we will need only $n$ actions, because in array $D$ each element is firstly equal to 1, and then once becomes -1 and never changes again. The described solution's time complexity is $O(n \\cdot \\log(n))$",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1540",
    "index": "A",
    "title": "Great Graphs",
    "statement": "Farmer John has a farm that consists of $n$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.\n\nUnfortunately, Farmer John lost the map of the farm. All he remembers is an array $d$, where $d_i$ is the smallest amount of time it took the cows to reach the $i$-th pasture from pasture $1$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the \\textbf{minimal} cost of a farm that is consistent with his memory.",
    "tutorial": "Note that if there are two nodes $a$ and $b$ and you want to add an edge between them, the value of the edge must be $\\geq d_b - d_a$. Otherwise, the cows could take a path to $b$ that goes through $d_a$ that's strictly less than $d_b$. With this in mind, let's add all edges $(a, b)$ with weight $d_b - d_a$ if and only if $d_b \\leq d_a$. All of these numbers are not positive, which means they can't make our answer worse. They also don't change the shortest paths, from our first observation. Now, let's call the node with the max $d_i$ node $x$. You can add a single edge from node $1$ to node $x$ with cost $d_x$, and now the graph is good. This is because node $x$ is already connected to all other nodes, which means there is always a shortest path to some node $a$ with the right length by going from $1 \\rightarrow x \\rightarrow a$. However, naively looping through all pairs is too slow. Instead, you can sort $d$ and calculate the contribution of each node to the answer. The complexity is $O(n log n)$.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "shortest paths",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1540",
    "index": "B",
    "title": "Tree Array",
    "statement": "You are given a tree consisting of $n$ nodes. You generate an array from the tree by marking nodes one by one.\n\nInitially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.\n\nAfter that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.\n\nIt can be shown that the process marks all nodes in the tree.\n\nThe final array $a$ is the list of the nodes' labels in order of the time each node was marked.\n\nFind the expected number of inversions in the array that is generated by the tree and the aforementioned process.\n\nThe number of inversions in an array $a$ is the number of pairs of indices $(i, j)$ such that $i < j$ and $a_i > a_j$. For example, the array $[4, 1, 3, 2]$ contains $4$ inversions: $(1, 2)$, $(1, 3)$, $(1, 4)$, $(3, 4)$.",
    "tutorial": "Parsing through the problem statement, the process can be seen as choosing a starting node and \"expanding\" the subtree of marked nodes to nodes adjacent to the marked component. Fixing a given root $r$, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by $n$. Find the contribution of the inversion of two nodes $(a, b)$ where $a<b$. The expected contribution for any pair $(a, b)$ is equal to the probability that $b$ appears before $a$ with a given root. Set $l = lca(a, b)$. Note that, until reaching $l$, every possible process still has the same probability of reaching $b$ before $a$ as it did when the first node was chosen. Therefore, we can assume that the process has reached $l$ and calculate the probability from there. Once $l$ is reached, we now note that the probability that the process \"gets closer\" to $b$ is always equal to the probability of getting closer to $a$. The problem can be rephrased as having two stacks of size $dist(l, a)$ and $dist(l, b)$ with an arbitrary $p$ to remove a node from one of the two stack (and $1-2p$ to nothing) and finding the probability that $dist(l, b)$ reaches zero before $dist(l, a)$. However, it turns out that the actual probability $p$ does not matter. We propose a function $F[x][y]$ that defines the probability that a stack of size $y$ becomes $0$ before a stack of size $x$. In fact a function exists and it is defined as $F[x][y] = \\frac{F[x-1][y]+F[x][y-1]}{2}$. Intuitively, this is because the probability of decreasing $x$ or decreasing $y$ is always the same, so the probability of transitioning the state we end up transitioning to is always the same, regardless of $p$. So, the solution is clear. Iterate over and root at all nodes. Then at the given root, iterate over all pairs of node $a < b$ and add $F[dist(l, a)][dist(l, b)]$ to the answer. Finally, divide by $n$. In total, the solution works in $O(N^3 \\log N)$ or $O(N^3)$.",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "graphs",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1540",
    "index": "C2",
    "title": "Converging Array (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $1 \\le q \\le 10^5$. You can make hacks only if both versions of the problem are solved.}\n\nThere is a process that takes place on arrays $a$ and $b$ of length $n$ and length $n-1$ respectively.\n\nThe process is an infinite sequence of operations. Each operation is as follows:\n\n- First, choose a random integer $i$ ($1 \\le i \\le n-1$).\n- Then, simultaneously set $a_i = \\min\\left(a_i, \\frac{a_i+a_{i+1}-b_i}{2}\\right)$ and $a_{i+1} = \\max\\left(a_{i+1}, \\frac{a_i+a_{i+1}+b_i}{2}\\right)$ without any rounding (so values may become non-integer).\n\nSee notes for an example of an operation.It can be proven that array $a$ converges, i. e. for each $i$ there exists a limit $a_i$ converges to. Let function $F(a, b)$ return the value $a_1$ converges to after a process on $a$ and $b$.\n\nYou are given array $b$, but not array $a$. However, you are given a third array $c$. Array $a$ is good if it contains only \\textbf{integers} and satisfies $0 \\leq a_i \\leq c_i$ for $1 \\leq i \\leq n$.\n\nYour task is to count the number of good arrays $a$ where $F(a, b) \\geq x$ for $q$ values of $x$. Since the number of arrays can be very large, print it modulo $10^9+7$.",
    "tutorial": "First, reduce the operations into something more manageable. It turns out operation $i$ sets $a_{i+1}-a_i=\\max(b_i, a_{i+1}-a_i)$ while keeping $a_{i+1}+a_i$ constant. Visually, this is simultaneously moving $a_i$ up and $a_{i+1}$ down until $a_{i+1}-a[i] \\geq b_i$. Define $f$ to be the final converged array. Let's some observations If $a_{i+1}-a_i = b_i$ is ever satisfied throughout the process (if an operation ever moves anything), $f_{i+1}-f_i = b_i$. Equivalently, if $f_{i+1}-f_i > b_i$ then no operation $i$ could have ever been conducted If no operation $i$ has been conducted, then $[1, i]$ is independent of $[i+1, n]$. If $i$ is the first operation that has never been conducted, then $\\sum_{j=1}^i a_j = \\sum_{j=1}^i f_j$ because no sum could have been exchanged between $a_i$ and $a_{i+1}$. Let's assume that we know that $i$ is the first observation that hasn't been conducted. We can then restore $f_1$ because we know that $f_1 + f_1+b_1+f_1+b_1+b_2 \\ldots = a_1+a_2+\\ldots+a_i$. To keep the tutorial clean, we refer to the prefix of prefix summation of $b_i$ as $bp_i$ and the prefix summation of $a_i$ as $ap_i$. Namely, we can solve for $f_1 = \\frac{ap_i - bp_i}{i}$ given that $i$ is the first observation never conducted. It turns out that $f_1 = \\min(\\frac{ap_i - bp_i}{i})$ over all $i$. This can be shown to be a lower bound on $f_1$ because the answer is obviously in this set as there must be some $i$ that is the first operation never conducted. This can also be shown to be an upperbound on the answer by playing the game on each prefix $i$. At each prefix $i$, the term $\\frac{ap_i - bp_i}{i}$ is an upperbound because, if it's not equal to that term, there must be some $f_{i+1}-f_i > b_i$ so $f_1 < \\frac{ap_i - bp_i}{i}$ because $f_1+f_2+\\ldots+f_i$ remains the same. Returning to the actual problem, we need to count arrays $\\min(\\frac{ap_i-bp_i}{i}) \\geq x$. In other words, $ap_i \\geq i \\cdot x + bp_i$ must hold for all $i$. Let's do dynamic programming on $ap_i$. Call $dp[i][ap_i]$ the number of prefixes of length $i$ with current prefix sum of $ap_i$. We can transition to $i+1$ from $i$ using prefix sums on each valid $ap_i$. Define $M = max(a_i)$. The current complexity is $O(Q M N^2)$ The final step is noticing that there are only $O(M)$ valid integer positions that end up being important for $f_1$. Intuitively, this is because in nearly all cases every operation $i$ ends up being used. To rigorously prove, let's find an upperbound on relevant $x$. If $M\\cdot n < x\\cdot n + bp_i$ then there are $0$ valid arrays. Because $x\\cdot n + bp_i$ is concave and negative on the decreasing portion (i.e. the function goes down immediately into negative if it ever becomes negative, otherwise strictly increases), we can draw the inequality $0 \\geq x\\cdot n + bp_i$, otherwise every array ends up being good. Reducing the inequalities, we can realize that there is exactly $M$ different possible solutions. So, we can precalculate in $O(M^2N^2)$ and answer in $O(1)$.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1540",
    "index": "D",
    "title": "Inverse Inversions",
    "statement": "You were playing with permutation $p$ of length $n$, but you lost it in Blair, Alabama!\n\nLuckily, you remember some information about the permutation. More specifically, you remember an array $b$ of length $n$, where $b_i$ is the number of indices $j$ such that $j < i$ and $p_j > p_i$.\n\nYou have the array $b$, and you want to find the permutation $p$. However, your memory isn't perfect, and you constantly change the values of $b$ as you learn more. For the next $q$ seconds, one of the following things happen:\n\n- $1$ $i$ $x$ — you realize that $b_i$ is equal to $x$;\n- $2$ $i$ — you need to find the value of $p_i$. If there's more than one answer, print any. It can be proven that there's always at least one possible answer under the constraints of the problem.\n\nAnswer the queries, so you can remember the array!",
    "tutorial": "We'll assume the arrays and the final permutation are 0-indexed from this point forward (you can shift values accordingly at the end). Let's start with calculating the final array, without any updates. Let $c_i$ be the number of indices $j$ such that $p_j < p_i$ and $i < j$. It is easy to see that $c_i = i - b_i$. Now imagine sweeping from left to right, maintaining the array $a$. Let's say you're currently at index $i$, and you have a list of all indices $\\leq i$, where the location of some index $j$ is the value of $a_j$. You know that $i$ must be the $c_i$-th out of those (after inserting it into the list) as the $c_i$ smallest values must be before it. This means that you can insert index $i$ at the $c_i-th$ position in the list, and you need to find the final location of index $i$ in each query. Now, let's support $O(1)$ updates and $O(n)$ queries. The first thing to note is that you don't need the entire array $a$ in each query, you just need to query some specific element. Assume you're querying the $i$-th element of the array. Let's repeat the algorithm mentioned above except instead of storing the lists, you only store the location of the $i$-th element for each query. Now, you keep some variable $loc$ which stores the location of the $i$-th element in the list. It is initialized to $c_i$, as it is first inserted to the $c_i$-th position. Now you sweep through all indices $j$ where $j > i$, and check if $loc$ is changed by the insert. This is only true if $loc \\geq a[j]$. This allows for $O(1)$ updates but $O(n)$ queries, which is still too slow. To speed this up, let's use sqrt-decomp. Divide the array into multiple blocks. For each block, let's store an array $next$ where $next_{loc}$ represents the final value of the variable $loc$ if it passes through the block. If we have this array, you can loop over all of the blocks and \"jump\" over them using the next array, querying in $O(n/B)$ time, where $B$ is the size of the block. But how do you calculate and update the $next$ array? Initially, you can calculate the next array in $O(n \\cdot B)$, by going to each index and naively tracking its position. Updating it is harder. One observation to make is that for each index inside a block, there is some value such that if $loc \\geq x$ it will be changed by the index, otherwise it will not. You can find all of those values for a single block using a binary indexed tree: sweep from left to right, query for the the smallest update $loc$ using a lower bound on the BIT, and increment a suffix. Then, you can increment all of those suffixes in the next array using another BIT, which would lead to $O(n \\sqrt{n} + q \\sqrt{n} \\log{n})$, as queries are $O((n/B)\\log{n})$ and updates are $O(B \\log{n})$, which will probably be too slow. To make this faster, note that the suffix that each element is responsible changes by at most one for all non-updated elements. This means that you can update the next array in $O(1)$ for these elements. However, the updated element's suffix might change by $O(n)$. To account for this, you can use another square root decomposition on the next array, which allows for $O(\\sqrt{n})$ range updates, $O(1)$ point updates, and $O(1)$ point queries. This means that updates will remain $O(B \\log{n})$, but queries will become $O(1)$, so the final complexity is $O(q \\sqrt{n \\log{n}})$ with the right blocksize, which is definitely fast enough (the model solution runs in $2$ seconds). If you know of any faster solutions ($O(n\\sqrt{n})$ or even $O(n \\cdot \\log^k{})$ let us know down in the comments).",
    "tags": [
      "binary search",
      "brute force",
      "data structures"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1540",
    "index": "E",
    "title": "Tasty Dishes",
    "statement": "\\textbf{Note that the memory limit is unusual.}\n\nThere are $n$ chefs numbered $1, 2, \\ldots, n$ that must prepare dishes for a king. Chef $i$ has skill $i$ and initially has a dish of tastiness $a_i$ where $|a_i| \\leq i$. Each chef has a list of other chefs that he is allowed to copy from. To stop chefs from learning bad habits, the king makes sure that chef $i$ can only copy from chefs of larger skill.\n\nThere are a sequence of days that pass during which the chefs can work on their dish. During each day, there are two stages during which a chef can change the tastiness of their dish.\n\n- At the beginning of each day, each chef can choose to work (or not work) on their own dish, thereby multiplying the tastiness of their dish of their skill ($a_i := i \\cdot a_i$) (or doing nothing).\n- After all chefs (who wanted) worked on their own dishes, each start observing the other chefs. In particular, for each chef $j$ on chef $i$'s list, chef $i$ can choose to copy (or not copy) $j$'s dish, thereby adding the tastiness of the $j$'s dish to $i$'s dish ($a_i := a_i + a_j$) (or doing nothing). It can be assumed that all copying occurs simultaneously. Namely, if chef $i$ chooses to copy from chef $j$ he will copy the tastiness of chef $j$'s dish at the end of stage $1$.\n\nAll chefs work to maximize the tastiness of their own dish in order to please the king.\n\nFinally, you are given $q$ queries. Each query is one of two types.\n\n- $1$ $k$ $l$ $r$ — find the sum of tastiness $a_l, a_{l+1}, \\ldots, a_{r}$ after the $k$-th day. Because this value can be large, find it modulo $10^9 + 7$.\n- $2$ $i$ $x$ — the king adds $x$ tastiness to the $i$-th chef's dish before the $1$-st day begins ($a_i := a_i + x$). Note that, because the king wants to see tastier dishes, he only adds positive tastiness ($x > 0$).\n\nNote that queries of type $1$ are independent of each all other queries. Specifically, each query of type $1$ is a scenario and does not change the initial tastiness $a_i$ of any dish for future queries. Note that queries of type $2$ are cumulative and only change the initial tastiness $a_i$ of a dish. See notes for an example of queries.",
    "tutorial": "All operations are conducted under a modulo, it can be proven that each operation we conduct is valid within the modulo. Key Idea 1 It's optimal to perform each operation if the number being added/multiplied is strictly positive. Specifically, it's optimal to do $a_i := i\\cdot a_i$ and $a_i := a_i+a+j$ iif $a_i > 0$ and $a_j > 0$ respectively. Key Idea 2 A chef's dish $i$ becomes positive after the $d$'th day where $d$ is the closest distance of chef $i$ from a positive element. We call this value $d_i$ for the $i$'th chef. Initial observations, there are only $O(N^2)$ pairs of $(i, d_i)$ where $d_i$ is not infinite (never reaches positive value and thus never changes). Key Idea 3 We refer to a vector of length $n$ with $n-1$ zeros and a single $1$ at the $i$'th index as $\\vec{e}_i$. If we assume that all chefs are currently positive then every chef takes every opportunity copy and the transition matrix $T$ is well defined and obvious. We can represent the final array at time $k$ as $a = T^k \\sum_{d_i \\leq k} T^{-d_i} \\vec{e}_i a_i$ + $\\sum_{d_i>k} \\vec{e}_i a_i$. This immediately offers a $O(QN^2+N^4)$ potential solution with very good constant. Because $T$ is diagonal, its inverse can with respect to a vector $\\vec{v}$ be calculated in $O(N^2)$. So, we can precalculate $T^-k \\vec{e}_i$ for all valid numbers in $O(N^2)$. In fact, this ends up being $N^4/12$ total operations if optimized. We can then answer each query in $O(N^2)$ by simply iterating over each chef and finding it's contribution to the answer. Multiplying a matrix $O(N^2)$ will be explained later. With some special hacks, it may even be possible to get this to pass. Key Idea 4 An arbitrary matrix $T$ has eigenvalues $\\lambda_i$ and their paired eigenvectors $\\vec{v}_i$. Ignoring how we find eigenvectors and eigenvalues, the point of the two is that they are pairs such that $T \\vec{v}_i = \\vec{v}_i \\lambda_i$. Notably, given a eigenvector and its respective eigenvalue, we can calculate $T^k \\cdot \\vec{v}_i$ in $O(N \\log k)$. In our case, the transition matrix $T$ is a diagonal matrix. A basic result in linear algebra is that the eigenvalues of a diagonal matrix is exactly the numbers on it's diagonal. In our case, this means that $\\lambda_i = i$ for $1 \\le i \\le n$. Finding the eigenvectors is left as an exercise to the reader. We henceforth denote the eigenvector paired with the $i$'th eigenvalue as $\\vec{v}_i$. Key Idea 5 Decompose $\\vec{e}_i$ into a linear combination of eigenvectors. This can be precalculated in $O(N^3)$. Let's denote another vector $\\vec{c}_i$ as this linear combination i.e. $\\vec{c}_i$ satisfies $\\vec{e}_i = \\sum \\vec{v}_i \\vec{c}_{i, j}$. In fact, this is almost all we need. Let's return to to $a = T^k \\sum_{d_i \\leq k} T^{-d_i} \\vec{e}_i a_i$ (the second part can be trivially calculated). We can calculate almost \"separately\" for each eigenvector $j$. In fact, the contribution of the $j$'th eigenvector from the $i$'th chef after the $k$'th day is $\\lambda_j^k c_{i, j} a_i \\lambda_j^{-d_i}$. Let's store $c_{i,j}a_i \\lambda_j^-{d_i}$ in a segment tree/BIT on $d_i$. We can extract in $O(N \\log N)$ total or $O(\\log N)$ for a single eigenvector then find the total contribution by multiplying by $\\lambda_j^k$ and using prefix sums on the eigenvector to extract the relevant range $[l, r]$. We can also process $O(N log N)$ per update if $d_i$ stays constant trivially. This is more than enough to pass, but a further optimization is that the array $d$ only changes at most $O(N)$ time (whenever a new element becomes positive). So, we can simply rebuild our segment tree/BIT in $O(N)$ to reach $O(N^3)$ complexity. Final complexity: $O(N^3 + QN\\log N)$. It's also worth noting that several nonoptimal solutions can pass. We attempted to cut off any solutions that explicitly use matrix multiplication. However, solutions with complexity such as $O(QN^2)$ can pass in 64 bit C++ if only additions are used. The only way we found to do only additions was by making the same eigenvector reduction, so we were not too worried. It seems impossible to fail such solutions while maintaining a reasonable TL.",
    "tags": [
      "math",
      "matrices"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1541",
    "index": "A",
    "title": "Pretty Permutations",
    "statement": "There are $n$ cats in a line, labeled from $1$ to $n$, with the $i$-th cat at position $i$. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.\n\nFor example, if there are $3$ cats, this is a valid reordering: $[3, 1, 2]$. No cat is in its original position. The total distance the cats move is $1 + 1 + 2 = 4$ as cat $1$ moves one place to the right, cat $2$ moves one place to the right, and cat $3$ moves two places to the left.",
    "tutorial": "There are two cases: if $n$ is even, print: $[2, 1, 4, 3, 6, 5 \\ldots n, n-1]$ Formally, you swap every other pair of adjacent elements. This is optimal because the total distance is $n$, which has to be minimal since the distance of one cat must be $\\geq 1$. if $n$ is odd, first print $[3, 1, 2]$ then solve the even case for the remaining elements. This is optimal because the distance is $n+1$, which has to be minimal since a distance of $n$ is not achievable.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1541",
    "index": "B",
    "title": "Pleasant Pairs",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$ consisting of $n$ \\textbf{distinct} integers. Count the number of pairs of indices $(i, j)$ such that $i < j$ and $a_i \\cdot a_j = i + j$.",
    "tutorial": "Loop over all values of $a_i$ and $a_j$. Because $i + j \\leq 2 \\cdot n$, we only care about pairs $(a_i, a_j)$ if $a_i \\cdot a_j \\leq 2 \\cdot n$. The number of such pairs is $O(n log n)$, so you can brute force all pairs. The reason the total number of pairs is $O(n log n)$ is because if the first element of the pair is $x$, there are only $\\frac{2 \\cdot n}{x}$ possible values of $y$. $\\frac{2 \\cdot n}{1} + \\frac{2 \\cdot n}{2} + \\frac{2 \\cdot n}{3} + \\ldots \\frac{2 \\cdot n}{n} = 2 \\cdot n (\\frac{1}{1} + \\frac{1}{2} + \\frac{1}{3} \\ldots \\frac{1}{n}) = O(n log n)$ by the harmonic series. Thus the solution runs in $O(n log n)$ time total.",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1542",
    "index": "A",
    "title": "Odd Set",
    "statement": "You are given a multiset (i. e. a set that can contain multiple equal integers) containing $2n$ integers. Determine if you can split it into exactly $n$ pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is \\textbf{odd} (i. e. when divided by $2$, the remainder is $1$).",
    "tutorial": "The answer is 'yes' if and only if there are exactly $n$ odd numbers.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main() {\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n,cnt[2]={0};\n\t\tcin>>n;\n\t\tfor(int i=1,x;i<=n*2;i++)cin>>x,cnt[x%2]++;\n\t\tif(cnt[0]==n)puts(\"Yes\");\n\t\telse puts(\"No\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1542",
    "index": "B",
    "title": "Plus and Multiply",
    "statement": "There is an infinite set generated as follows:\n\n- $1$ is in this set.\n- If $x$ is in this set, $x \\cdot a$ and $x+b$ both are in this set.\n\nFor example, when $a=3$ and $b=6$, the five smallest elements of the set are:\n\n- $1$,\n- $3$ ($1$ is in this set, so $1\\cdot a=3$ is in this set),\n- $7$ ($1$ is in this set, so $1+b=7$ is in this set),\n- $9$ ($3$ is in this set, so $3\\cdot a=9$ is in this set),\n- $13$ ($7$ is in this set, so $7+b=13$ is in this set).\n\nGiven positive integers $a$, $b$, $n$, determine if $n$ is in this set.",
    "tutorial": "First check specially if $b=1$. Let's consider when $n$ is in $S$. The answer is when the smallest number $m$ in $S$ that $n\\ \\mathrm{mod}\\ b=m\\ \\mathrm{mod}\\ b$ is less than $n$. It's easy to see that a new case of $x\\ \\mathrm{mod}\\ b$ can only appear when you use $\\times a$ to generate a new element. So the smallest number $m$ in S that $m\\ \\mathrm{mod}\\ b=k$ must be a power of $a$. Find all powers of a that is smaller than $n$. If there is one $m=a^k$ that $n\\ \\mathrm{mod}\\ b=m\\ \\mathrm{mod}\\ b$, the answer is yes. Otherwise it's no. Time complexity is $O(\\log n)$.",
    "code": "t=(int)(input())\nfor i in range(t):\n    w=input().split()\n    n=(int)(w[0])\n    a=(int)(w[1])\n    b=(int)(w[2])\n    if a==1 :\n    \tif (n-1)%b==0 :\n    \t\tprint(\"Yes\")\n    \telse :\n    \t\tprint(\"No\")\n    \t\n    else :\n    \tt=1\n    \tflag=0\n    \twhile t<=n :\n    \t\tif t%b==n%b:\n    \t\t\tflag=1\n    \t\t\tbreak\n    \t\tt=t*a\n    \tif flag==1:\n    \t\tprint(\"Yes\")\n    \telse :\n    \t\tprint(\"No\")",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1542",
    "index": "C",
    "title": "Strange Function",
    "statement": "Let $f(i)$ denote the minimum positive integer $x$ such that $x$ is \\textbf{not} a divisor of $i$.\n\nCompute $\\sum_{i=1}^n f(i)$ modulo $10^9+7$. In other words, compute $f(1)+f(2)+\\dots+f(n)$ modulo $10^9+7$.",
    "tutorial": "Enumerate the value of $f(i)$. Since $f(n)=i$ means $lcm(1,2,...,i-1)\\le n$, $f(n)$ will not be too big (less than $100$). The number of $k$s such that $f(k)=i$ is $\\lfloor n/lcm(1,2,...,i-1)\\rfloor -\\lfloor n/lcm(1,2,...,i)\\rfloor$. ($k$ should be divisible by $1\\sim i-1$ but not $i$) So the answer is $\\sum_{i>1} i(\\lfloor n/lcm(1,2,...,i-1)\\rfloor -\\lfloor n/lcm(1,2,...,i)\\rfloor )$. We can also write the answer in another form, which is equivalent to the previous form: $\\sum_{i\\ge 1} \\lfloor n/lcm(1,2,...,i)\\rfloor +n$",
    "code": "#include<bits/stdc++.h>\n#define int long long\n#define re register\nusing namespace std;\nint t,n;\nconst int M=1e9+7;\ninline int gcd(re int x,re int y){\n\treturn y?gcd(y,x%y):x;\n}\ninline int LCM(re int x,re int y){\n\treturn x/gcd(x,y)*y;\n}\nsigned main(){\n\tscanf(\"%lld\",&t);\n\twhile(t--){\n\t\tscanf(\"%lld\",&n);\n\t\tre int G=1,ans=0;\n\t\tfor(re int i=1;G<=n;++i){\n\t\t\tG=LCM(G,i);\n\t\t\tif(G>n)break;\n\t\t\tans+=n/G;\n\t\t}\n\t\tprintf(\"%lld\n\",(ans+n)%M);\n\t}\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1542",
    "index": "D",
    "title": "Priority Queue",
    "statement": "You are given a sequence $A$, where its elements are either in the form + x or -, where $x$ is an integer.\n\nFor such a sequence $S$ where its elements are either in the form + x or -, define $f(S)$ as follows:\n\n- iterate through $S$'s elements from the first one to the last one, and maintain a multiset $T$ as you iterate through it.\n- for each element, if it's in the form + x, add $x$ to $T$; otherwise, erase the smallest element from $T$ (if $T$ is empty, do nothing).\n- after iterating through all $S$'s elements, compute the sum of all elements in $T$. $f(S)$ is defined as the sum.\n\nThe sequence $b$ is a subsequence of the sequence $a$ if $b$ can be derived from $a$ by removing zero or more elements without changing the order of the remaining elements. For all $A$'s subsequences $B$, compute the sum of $f(B)$, modulo $998\\,244\\,353$.",
    "tutorial": "For each $x$, count how many $B$s make the final set contain $x$. Let's say we have picked the $x$ in the $I$-th operation, call it $X$. Then, the subsequence we choose must satisfy the following conditions: It must contain the $i$-th operation (otherwise $X$ won't be added). Let $s$ denote the number of numbers less than $X$ in the current $T$. Whenever we meet a - element in $S$ after the $i$-th operation, $s$ should be greater than $0$. With those conditions, we can come up with the following dp. Let $f(i,j)$ denote the number of subsequences of $a[1...i]$, that if we maintain $T$ with the subsequence, $s$ will become $j$. Then we have the following transitions: $f(i-1,j)\\to f(i,j)$ (when we don't include the $i$-th element is $S$, here $i\\ne I$) $f(i-1,j)\\to f(i,\\max(j-1,0))$ (here, $i<I$, and the $i$-th element of $A$ is -, so the number of numbers in $T$ less than $x$ decreases by one. If there is no such number, $s$ remains $0$) $f(i-1,j)\\to f(i,j-1)$ (here, $i>I$, and and the $i$-th element of $A$ is -, so the number of numbers in $T$ less than $x$ decreases by one.) $f(i-1,j)\\to f(i,j)$ (here, the $i$-th element of $A$ is + and its $x$ is greater than $X$) $f(i-1,j)\\to f(i,j+1)$ (here, the $i$-th element of $A$ is + and its $x$ is less than $x$ or [equal to $x$ but $i>I$] ) [this is to deal with same elements] Then we add $ans$ by $X\\times \\sum_{i\\ge 0} f(n,i)$. The time complexity is $O(n^3)$.",
    "code": "mod=998244353\nn=(int)(input())\na=[0 for i in range(n+1)]\nfor i in range(1,n+1):\n\tm=input().split()\n\tif m[0]==\"+\":\n\t\ta[i]=(int)(m[1])\n\t\nans=0\nfor t in range(1,n+1):\n\tif a[t]==0:\n\t\tcontinue\n\tf=[[0 for i in range(n+2)] for j in range(n+2)]\n\tf[0][0]=1\n\tfor i in range(1,n+1):\n\t\tfor j in range(0,i+1):\n\t\t\tif a[i]==0:\n\t\t\t\tif ((i<=t) or (j>0)):\n\t\t\t\t\tf[i][max(j-1,0)]=(f[i][max(j-1,0)]+f[i-1][j])%mod\n\t\t\telse :\n\t\t\t\tif ((a[i]<a[t]) or ((a[i]==a[t]) and (i<t))):\n\t\t\t\t\tf[i][j+1]=(f[i][j+1]+f[i-1][j])%mod\n\t\t\t\telse :\n\t\t\t\t\tf[i][j]=(f[i][j]+f[i-1][j])%mod\n\t\t\t\n\t\t\tif (i!=t) :\n\t\t\t\tf[i][j]=(f[i][j]+f[i-1][j])%mod\n\t\t\t\t\n\t\t\t\n\t\t\n\t\n\tfor i in range(0,n+1):\n\t\tans=(ans+f[n][i]*a[t])%mod\n\t\n \nprint(ans)",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math",
      "ternary search"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1542",
    "index": "E1",
    "title": "Abnormal Permutation Pairs (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the easy version and the hard version is the constraints on $n$. You can only make hacks if both versions are solved.}\n\nA permutation of $1, 2, \\ldots, n$ is a sequence of $n$ integers, where each integer from $1$ to $n$ appears exactly once. For example, $[2,3,1,4]$ is a permutation of $1, 2, 3, 4$, but $[1,4,2,2]$ isn't because $2$ appears twice in it.\n\nRecall that the number of inversions in a permutation $a_1, a_2, \\ldots, a_n$ is the number of pairs of indices $(i, j)$ such that $i < j$ and $a_i > a_j$.\n\nLet $p$ and $q$ be two permutations of $1, 2, \\ldots, n$. Find the number of permutation pairs $(p,q)$ that satisfy the following conditions:\n\n- $p$ is lexicographically smaller than $q$.\n- the number of inversions in $p$ is greater than the number of inversions in $q$.\n\nPrint the number of such pairs modulo $mod$. Note that $mod$ may not be a prime.",
    "tutorial": "Let's first calculate the number of permutation pair $(p,q)$s (with length $i$) that $p_1<q_1$ but $inv(p)>inv(q)$ ($inv(p)$ is the number of inversions in $p$). Call it $t_i$. Let's enumerate $p_1=j$ and $q_1=k$, then $inv(p[2...i])-inv(q[2...i])>k-j$. ($inv(p)=inv(p[2...i])+j-1,inv(q)=inv(q[2...i])+k-1$, with $inv(p)>inv(q)$ we get the following.) Precalculate $f(i,j)$: the number of permutation $p$s of length $i$ such that $inv(p)=j$. Let $s(i,j)$ be $\\sum_{k\\le j}f(i,k)$, then: $t_i=\\sum_{1\\le j\\le i}\\sum_{j<k\\le i} \\sum_{w} f(i-1,w)s(i-1,w-(k-j)-1)$$f$ and $s$ can be calculated in $O(n^4)$ or $O(n^3)$ in the following way: if you insert $i$ into a permutation of length $i-1$ after the $i-1-p$-th element $(0\\le p\\le i-1)$, it will bring $p$ inversions into the permutation. So $f(i,j)=\\sum_{j-i+1\\le k\\le j} f(i-1,k)$. After calculating $t$, calculating the answer it easy. Let $ans_i$ be the answer for $n=i$, then $ans_i=i\\times ans_{i-1}+t_i$Consider if $p_1=q_1$. If so, there are $i$ choices of $p_1$, and $ans_{i-1}$ choices of the following $n-1$ numbers. Otherwise, there are $t_i$ choices. Total complexity is $O(n^5)$, but it can be optimized to $O(n^4)$ if you consider the difference between $j-k$ only, and can be optimized to $O(n^3\\log n)$ using FFT with arbitary mod (which we hope can't pass E2!).",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nint n,mod,f[55][2005]={1},s[55][2005]={1},ans[55];\nint main(){\n\tcin>>n>>mod;\n\tfor(int i=1;i<=n*(n-1)/2;i++)s[0][i]=1;\n\tfor(int i=1;i<=n;i++){\n\t\tfor(int j=0;j<=n*(n-1)/2;j++){\n\t\t\tif(j-i>=0)f[i][j]=(s[i-1][j]-s[i-1][j-i]+mod)%mod;\n\t\t\telse f[i][j]=s[i-1][j];\n\t\t\ts[i][j]=((j?s[i][j-1]:0)+f[i][j])%mod;\n\t\t}\n\t}\n\tfor(int i=1;i<=n;i++){\n\t\tfor(int j=1;j<=i;j++){\n\t\t\tfor(int k=j+1;k<=i;k++){\n\t\t\t\tfor(int o=0;o<=(i-1)*(i-2)/2;o++){\n\t\t\t\t\tint t=o-(k-j)-1;\n\t\t\t\t\tif(t<0)continue;\n\t\t\t\t\tans[i]=(ans[i]+1ll*f[i-1][o]*s[i-1][t]%mod)%mod;\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t}\n\tfor(int i=2;i<=n;i++)ans[i]=(ans[i]+1ll*i*ans[i-1])%mod;\n\tcout<<ans[n];\n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1542",
    "index": "E2",
    "title": "Abnormal Permutation Pairs (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the easy version and the hard version is the constraints on $n$. You can only make hacks if both versions are solved.}\n\nA permutation of $1, 2, \\ldots, n$ is a sequence of $n$ integers, where each integer from $1$ to $n$ appears exactly once. For example, $[2,3,1,4]$ is a permutation of $1, 2, 3, 4$, but $[1,4,2,2]$ isn't because $2$ appears twice in it.\n\nRecall that the number of inversions in a permutation $a_1, a_2, \\ldots, a_n$ is the number of pairs of indices $(i, j)$ such that $i < j$ and $a_i > a_j$.\n\nLet $p$ and $q$ be two permutations of $1, 2, \\ldots, n$. Find the number of permutation pairs $(p,q)$ that satisfy the following conditions:\n\n- $p$ is lexicographically smaller than $q$.\n- the number of inversions in $p$ is greater than the number of inversions in $q$.\n\nPrint the number of such pairs modulo $mod$. Note that $mod$ may not be a prime.",
    "tutorial": "We recommend you to read E1's editorial first. Let's directly count the number of permutation pairs $(p,q)$ of length $n$ with $inv(p)-inv(q)=k$, instead of counting it indirectly from \"the number of permutation $p$s of length $i$ such that $inv(p)=j$.\". Call this number $f(n,k)$. We have an $n^4$ transition: $f(n,k)=\\sum_{|i|<n} f(n-1,k-i)\\times (n-|i|)$ (Consider where to insert $n$ in the first and second permutation. If the two places are indices $(I,J)$, then the delta of $inv(p)$ is $n-I$, the other is $n-J$, so the delta of difference is $J-I$. In $[1,n]$ there are $n-|J-I|$ pairs of integers with difference $J-I$.) Let's speed it up. When $f(n,k)$ moves to $f(n,k+1)$, it looks like this: ($n=4$, as an example) $f(n-1,k-3)\\times 1+f(n-1,k-2)\\times 2+f(n-1,k-1)\\times 3+f(n-1,k)\\times 4+f(n-1,k+1)\\times 3+f(n-1,k+2)\\times 2+f(n-1,k+3)\\times 1$ $f(n-1,k-2)\\times 1+f(n-1,k-1)\\times 2+f(n-1,k)\\times 3+f(n-1,k+1)\\times 4+f(n-1,k+2)\\times 3+f(n-1,k+3)\\times 2+f(n-1,k+4)\\times 1$ So with prefix sums $s$ ($s(i,j)=\\sum_{k\\le j} f(i,k)$) we can write $f(n,k+1)=f(n,k)-(s(n-1,k)-s(n-1,k-n))+(s(n-1,k+n)-s(n-1,k))$. Note that the second indice of the array might be negative, so we should shift it by $130000$. The memory complexity is $O(n^3)$, so we should only keep two layers of transition to optimize it to $O(n^2)$ (If implemented well, $O(n^3)$ memory solutions can also pass.)",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int B=130000;\nint n,mod,w[2][2*B+5],s[2][2*B+5],ans[505];\nint main(){\n\tcin>>n>>mod;\n\tw[0][B]=s[0][B]=1;\n\tfor(int i=B;i<=2*B;i++)s[0][i]=1;\n\tfor(int i=1;i<=n;i++){\n\t\tint curs=1,I=i&1,J=I^1;\n\t\tmemset(w[I],0,sizeof(w[I])),memset(s[I],0,sizeof(s[I]));\n\t\tfor(int u=i*(i-1)/2,j=-u+B;j<=u+B;j++){\n\t\t\tw[I][j]=curs;\n\t\t\tcurs=(0ll+curs-s[J][j]+s[J][j-i]+s[J][j+i]-s[J][j]+2ll*mod)%mod;\n\t\t}\n\t\tfor(int j=B-i*(i-1)/2,v=(i+2)*(i+1)/2+B;j<=v;j++)s[I][j]=(s[I][j-1]+w[I][j])%mod;\n\t\tfor(int j=1;j<i;j++)ans[i]=(ans[i]+1ll*(s[J][(i+1)*i/2+B]-s[J][j+B]+mod)%mod*(i-j))%mod;\n\t}\n\tfor(int i=2;i<=n;i++)ans[i]=(ans[i]+1ll*i*ans[i-1])%mod;\n\tcout<<ans[n];\n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1543",
    "index": "A",
    "title": "Exciting Bets",
    "statement": "Welcome to Rockport City!\n\nIt is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet $a$ dollars and Ronnie has bet $b$ dollars. But the fans seem to be disappointed. The excitement of the fans is given by $gcd(a,b)$, where $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$. To make the race more exciting, you can perform two types of operations:\n\n- Increase both $a$ and $b$ by $1$.\n- Decrease both $a$ and $b$ by $1$. This operation can only be performed if both $a$ and $b$ are greater than $0$.\n\nIn one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it.\n\nNote that $gcd(x,0)=x$ for any $x \\ge 0$.",
    "tutorial": "$GCD(a,b)=GCD(a-b,b)$ if $a>b$ $a-b$ does not change by applying any operation. However, $b$ can be changed arbitrarily. If $a=b$, the fans can get an infinite amount of excitement, and we can achieve this by applying the first operation infinite times. Otherwise, the maximum excitement the fans can get is $g=\\lvert a-b\\rvert$ and the minimum number of moves required to achieve it is $min(a\\bmod g,g-a\\bmod g)$. Without loss of generality, assume $a>b$ otherwise we can swap $a$ and $b$. We know that $GCD(a,b) = GCD(a-b,b)$. Notice that no matter how many times we apply any operation, the value of $a-b$ does not change. We can arbitrarily change the value of $b$ to a multiple of $a-b$ by applying the operations. In this way, we can achieve a $GCD$ equal to $a-b$. Now, since $GCD(x,y)\\leq min(x,y)$ for any positive $x$ and $y$, $GCD(a-b,b)$ can never exceed $a-b$. So, we cannot achieve a higher GCD by any means. To achieve the required $GCD$, we need to make $b$ a multiple of $g=a-b$ using as few operations as possible. There are two ways to do so $-$ decrease $b$ to the largest multiple of $g$ less than or equal to $b$ or increase $b$ to the smallest multiple of $g$ greater than $b$. The number of operations required to do so are $b\\bmod g$ and $g-b\\bmod g$ respectively. We will obviously choose the minimum of the two. Also notice that $a\\bmod g=b\\bmod g$ since $a=b+g$. So, it doesn't matter if we use either $a$ or $b$ to determine the minimum number of operations. $\\mathcal{O}(1)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        long long a,b;\n        cin >> a >> b;\n        if(a==b)\n            cout << 0 << \" \" << 0 << '\\n';\n        else\n        {\n            long long g = abs(a-b);\n            long long m = min(a%g,g-a%g);\n            cout << g << \" \" << m << '\\n';\n        }\n    }\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1543",
    "index": "B",
    "title": "Customising the Track",
    "statement": "Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $n$ sub-tracks. You are given an array $a$ where $a_i$ represents the number of traffic cars in the $i$-th sub-track. You define the inconvenience of the track as $\\sum\\limits_{i=1}^{n} \\sum\\limits_{j=i+1}^{n} \\lvert a_i-a_j\\rvert$, where $|x|$ is the absolute value of $x$.\n\nYou can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.\n\nFind the minimum inconvenience you can achieve.",
    "tutorial": "In the optimal arrangement, the number of cars will be distributed as evenly as possible. In the optimal arrangement, the number of traffic cars will be distributed as evenly as possible, i.e., $\\lvert a_i-a_j\\rvert\\leq 1$ for each valid $(i,j)$. Let's sort the array in non-decreasing order. Let $a_1=p$, $a_n=q$, $p\\leq q-2$, $x$ elements of the array be equal to $p$, $y$ elements of the array be equal to $q$, $\\displaystyle\\sum\\limits_{i=x+1}^{n-y}\\sum\\limits_{j=i+1}^{n-y} a_j-a_i=r$ and $\\displaystyle\\sum\\limits_{i=x+1}^{n-y} a_i=s$. The inconvenience of the track will be equal to $S_1=r+x\\cdot[s-(n-x-y)\\cdot p]+y\\cdot[(n-x-y)\\cdot q-s]+[xy\\cdot(q-p)]$ Suppose we increase $a_1$ by $1$ and decrease $a_n$ by $1$. Then, the number of occurrences of $p$ and $q$ will reduce by $1$, two new elements $p+1$ and $q-1$ will be formed, and $r$ and $s$ will remain unchanged. In such a case, the new inconvenience of the track will be $S_2=r+(x-1)\\cdot[s-(n-x-y)\\cdot p]$ $+(y-1)\\cdot[(n-x-y)\\cdot q-s]$ $+[(x-1)\\cdot(y-1)\\cdot(q-p)]$ $+[s-(n-x-y)\\cdot(p+1)]$ $+[(n-x-y)\\cdot(q-1)-s]$ $+[(y-1)\\cdot(q-p-1)]$ $+[(x-1)\\cdot(q-p-1)]$ $+(x-1)+(y-1)+(q-p-2)$ Change in inconvenience, $\\Delta = S_1-S_2 = [s-(n-x-y)\\cdot p]+[(n-x-y)\\cdot q-s]+[(x+y-1)\\cdot(q-p)]$ $-[s-(n-x-y)\\cdot(p+1)]$ $-[(n-x-y)\\cdot (q-1)-s]$ $-[(y-1)\\cdot(q-p-1)]$ $-[(x-1)\\cdot(q-p-1)]$ $-(x-1)-(y-1)-(q-p-2)$ $=2\\cdot(n-x-y)+(x+y-1)\\cdot(q-p)-(x+y-2)\\cdot(q-p-1)-(x-1)-(y-1)-(q-p-2)$ $=2\\cdot(n-x-y)+(q-p)+(x+y-1)-1-(x-1)-(y-1)-(q-p-2)$ $=2\\cdot(n-x-y+1) > 0$ as $x+y\\leq n$. So, it follows that if $p\\leq q-2$. it is always beneficial to move a traffic car from the sub-track with the highest number of traffic cars to the sub-track with the lowest number of traffic cars. If $p=q-1$, applying this operation won't change the inconvenience as this will only swap the last and the first element of the array leaving everything else unchanged. If $p=q$, all the elements of the array are already equal, meaning that we have $0$ inconvenience which is the minimum possible. So, there is no point in applying any operation. Now that we have constructed the optimal arrangement of traffic cars, let's find out the value of minimum inconvenience of this optimal arrangement. Finding it naively in $\\mathcal{O}(n^2)$ will time out. Notice that in the optimal arrangement we will have some (say $x$) elements equal to some number $p+1$ and the other $(n-x)$ elements equal to $p$. Let the sum of all elements in $a$ be $sum$. Then, $x=sum\\bmod n$ and $p=\\bigg\\lfloor\\dfrac{sum}{n}\\bigg\\rfloor$. For each pair $(p,p+1)$, we will get an absolute difference of $1$ and for all other pairs, we will get an absolute difference of $0$. Number of such pairs with difference $1$ is equal to $x\\cdot(n-x)$. So, the minimum inconvenience we can achieve is equal to $x\\cdot(n-x)$. That's all we need to find out! $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int n;\n        cin >> n;\n        int a[n];\n        long long s=0;\n        for(int i=0;i<n;i++)\n        {\n            cin >> a[i];\n            s+=a[i];\n        }\n        long long k = s%n;\n        long long ans = k*(n-k);\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "combinatorics",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1543",
    "index": "C",
    "title": "Need for Pink Slips",
    "statement": "After defeating a Blacklist Rival, you get a chance to draw $1$ reward slip out of $x$ hidden valid slips. Initially, $x=3$ and these hidden valid slips are Cash Slip, Impound Strike Release Marker and Pink Slip of Rival's Car. Initially, the probability of drawing these in a random guess are $c$, $m$, and $p$, respectively. There is also a volatility factor $v$. You can play any number of Rival Races as long as you don't draw a Pink Slip. Assume that you win each race and get a chance to draw a reward slip. In each draw, you draw one of the $x$ valid items with their respective probabilities. Suppose you draw a particular item and its probability of drawing before the draw was $a$. Then,\n\n- If the item was a Pink Slip, the quest is over, and you will not play any more races.\n- Otherwise,\n\n- If $a\\leq v$, the probability of the item drawn becomes $0$ and the item is no longer a valid item for all the further draws, reducing $x$ by $1$. Moreover, the reduced probability $a$ is distributed equally among the other remaining valid items.\n- If $a > v$, the probability of the item drawn reduces by $v$ and the reduced probability is distributed equally among the other valid items.\n\nFor example,\n\n- If $(c,m,p)=(0.2,0.1,0.7)$ and $v=0.1$, after drawing Cash, the new probabilities will be $(0.1,0.15,0.75)$.\n- If $(c,m,p)=(0.1,0.2,0.7)$ and $v=0.2$, after drawing Cash, the new probabilities will be $(Invalid,0.25,0.75)$.\n- If $(c,m,p)=(0.2,Invalid,0.8)$ and $v=0.1$, after drawing Cash, the new probabilities will be $(0.1,Invalid,0.9)$.\n- If $(c,m,p)=(0.1,Invalid,0.9)$ and $v=0.2$, after drawing Cash, the new probabilities will be $(Invalid,Invalid,1.0)$.\n\nYou need the cars of Rivals. So, you need to find the expected number of races that you must play in order to draw a pink slip.",
    "tutorial": "Did you notice that $v\\geq 0.1$? The probability of drawing a pink slip can never decrease. What would be the complexity of a bruteforce solution? Make sure to account for precision errors while comparing floating point numbers. Bruteforce over all the possible drawing sequences until we are sure to get a pink slip, i.e., until the probability of drawing a pink slip becomes $1$. Whenever we draw a reward other than a pink slip, If $a\\leq v$, one of the rewards becomes invalid, reducing $x$ by $1$ and this can happen at most $2$ times during the whole process. Else, the probability of drawing a pink slip increases by $\\dfrac{v}{2}$. Notice that the probability of drawing a pink slip can never decrease. Now, since $v\\geq 0.1$, each time we make a draw of the second type, the probability of drawing a pink slip increases by at least $0.05$. It will reach $1$ after just $20$ such draws. So, there will be at most $d=22$ draws before we are sure to get a pink slip. Simulating the whole process will take $\\mathcal{O}(2^d)$ time which is sufficient in our case. What's left is just implementing the bruteforce solution taking care of precision errors while dealing with floating point numbers, especially while comparing $a$ with $v$ as this can completely change things up, keeping an item valid when it should become invalid. It follows that an error approximation of 1e-6 or smaller is sufficient while comparing any two values because all the numbers in the input have at most $4$ decimal places. Another alternative is to convert floating point numbers given in the input to integers using a scaling factor of $10^6$. $\\mathcal{O}\\big(2^{\\frac{2}{v}}\\big)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst long double eps = 1e-9;\nconst long double scale = 1e+6;\n\nlong double expectedRaces(int c,int m,int p,int v)\n{\n    long double ans = p/scale;\n    if(c>0)\n    {\n        if(c>v)\n        {\n            if(m>0)\n                ans += (c/scale)*(1+expectedRaces(c-v,m+v/2,p+v/2,v));\n            else\n                ans += (c/scale)*(1+expectedRaces(c-v,0,p+v,v));\n        }\n        else\n        {\n            if(m>0)\n                ans += (c/scale)*(1+expectedRaces(0,m+c/2,p+c/2,v));\n            else\n                ans += (c/scale)*(1+expectedRaces(0,0,p+c,v));\n        }\n    }\n    if(m>0)\n    {\n        if(m>v)\n        {\n            if(c>0)\n                ans += (m/scale)*(1+expectedRaces(c+v/2,m-v,p+v/2,v));\n            else\n                ans += (m/scale)*(1+expectedRaces(0,m-v,p+v,v));\n        }\n        else\n        {\n            if(c>0)\n                ans += (m/scale)*(1+expectedRaces(c+m/2,0,p+m/2,v));\n            else\n                ans += (m/scale)*(1+expectedRaces(0,0,p+m,v));\n        }\n    }\n    return ans;\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        long double cd,md,pd,vd;\n        cin >> cd >> md >> pd >> vd;\n        int c = round(cd*scale);\n        int m = round(md*scale);\n        int p = round(pd*scale);\n        int v = round(vd*scale);\n        long double ans = expectedRaces(c,m,p,v);\n        cout << setprecision(12) << fixed << ans << '\\n';\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "implementation",
      "math",
      "probabilities"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1543",
    "index": "D1",
    "title": "RPD and Rap Sheet (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is that here $k=2$. You can make hacks only if both the versions of the problem are solved.}\n\nThis is an interactive problem.\n\nEvery decimal number has a base $k$ equivalent. The individual digits of a base $k$ number are called $k$-its. Let's define the $k$-itwise XOR of two $k$-its $a$ and $b$ as $(a + b)\\bmod k$.\n\nThe $k$-itwise XOR of two base $k$ numbers is equal to the new number formed by taking the $k$-itwise XOR of their corresponding $k$-its. The $k$-itwise XOR of two decimal numbers $a$ and $b$ is denoted by $a\\oplus_{k} b$ and is equal to the decimal representation of the $k$-itwise XOR of the base $k$ representations of $a$ and $b$. All further numbers used in the statement below are in decimal unless specified. When $k = 2$ (it is always true in this version), the $k$-itwise XOR is the same as the bitwise XOR.\n\nYou have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between $0$ and $n-1$ inclusive. So, you have decided to guess it. Luckily, you can try at most $n$ times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was $x$, and you guess a different number $y$, then the system changes the password to a number $z$ such that $x\\oplus_{k} z=y$. Guess the password and break into the system.",
    "tutorial": "In this version, $x\\oplus z=y$ or in other words, $z=x\\oplus y$ where $\\oplus$ is the Bitwise XOR operator. The number of queries allowed is equal to the number of possible initial passwords. The grader provides us no information other than whether our guess was correct or not. So, we need to find a way to ask queries such that the $x$-th query will give the correct answer if the original password was $(x-1)$. Try to ask queries in such a way that the $i$-th query reverses the effect of the $(i-1)$-th query and simultaneously checks if the initial password was $(i-1)$. Try to use the self-inverse property of Bitwise XOR, i.e., $a\\oplus a=0$. In this version of the problem, $k=2$. So, the $k$-itwise XOR is the same as Bitwise XOR. In case of incorrect guess, the system changes password to $z$ such that $x\\oplus z=y$. Taking XOR with $x$ on both sides, $x\\oplus x\\oplus z=x\\oplus y\\implies z=x\\oplus y$ because we know that $x\\oplus x = 0$. Since the original password is less than $n$ and we have $n$ queries, we need to find a way to make queries such that if the original password was $(x-1)$, then the $x$-th query will be equal to the current password. There are many different approaches. I will describe two of them. Let $q_i$ denote the $i$-th query. Then, $q_1=0$. $q_i=(i-1)\\oplus (i-2)$ for $2\\leq i\\leq n$. Let's see why this works. Claim - If the original password was $x$, after $i$ queries, the current password will be $x\\oplus (i-1)$. Let's prove this by induction. Base Condition - After $1$-st query, the password becomes $x\\oplus 0=x\\oplus(1-1)$. Induction Hypothesis - Let the password after $i$-th query be $x\\oplus (i-1)$. Inductive step - The $(i+1)$-th query will be $i\\oplus(i-1)$. If this is not equal to the current password, the password will change to $(x\\oplus(i-1))\\oplus(i\\oplus(i-1))$ $=x\\oplus(i-1)\\oplus i\\oplus(i-1)$ $=x\\oplus i$ $=x\\oplus((i+1)-1)$. Hence, proved by induction. Now notice that after $x$ queries, the password will become $x\\oplus(x-1)$. And our $(x+1)$-th query will be $x\\oplus(x-1)$ which is the same as the current password. So, the problem will be solved after $(x+1)$ queries. Since $0\\leq x < n$, the problem will be solved in at most $n$ queries. Again, let $q_i$ denote the $i$-th query. Then, $q_i=(i-1)\\oplus q_1 \\oplus q_2 \\oplus \\ldots \\oplus q_{i-2} \\oplus q_{i-1}$ Let's see why this works. Claim - If the original password was $x$, after $i$ queries, the current password will be $x \\oplus q_1 \\oplus q_2 \\oplus \\ldots \\oplus q_{i-1} \\oplus q_{i}$. Let's prove this by induction. Base Condition - The first query is $0$. After $1$-st query, the password becomes $x\\oplus 0=x\\oplus q_1$. Induction Hypothesis - Let the password after $i$-th query be $x \\oplus q_1 \\oplus q_2 \\oplus \\ldots \\oplus q_{i-1} \\oplus q_{i}$. Inductive step - The $(i+1)$-th query will be $q_{i+1}$. So, the password after $(i+1)$-th query will be $(x \\oplus q_1 \\oplus q_2 \\oplus \\ldots \\oplus q_{i-1} \\oplus q_{i})\\oplus q_{i+1}$ $= x \\oplus q_1 \\oplus q_2 \\oplus \\ldots \\oplus q_{i-1} \\oplus q_{i}\\oplus q_{i+1}$. Hence, proved by induction. Now notice that after $x$ queries, the password will become $x \\oplus q_1 \\oplus q_2 \\oplus \\ldots \\oplus q_{x-1} \\oplus q_{x}$. And our $(x+1)$-th query will be $x \\oplus q_1 \\oplus q_2 \\oplus \\ldots \\oplus q_{x-1} \\oplus q_{x}$ which is the same as the current password. So, the problem will be solved after $(x+1)$ queries. Since $0\\leq x < n$, the problem will be solved in at most $n$ queries. But we are not done yet. We can't afford to calculate the value of each query naively in $\\mathcal{O}(n)$ because this will time out. To handle this, we need to maintain a prefix XOR whose value will be $p=q_1\\oplus q_2\\oplus \\ldots \\oplus q_{i-1} \\oplus q_i$ after $i$ queries. For the $(i+1)$-th query, find $q_{i+1}=p\\oplus i$ and update $p=p\\oplus q_{i+1}$. $\\mathcal{O}(n)$ or $\\mathcal{O}(n\\cdot \\log_{2} n)$ depending upon the implementation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    int t=1;\n    cin >> t;\n    while(t--)\n    {\n        int n,k;\n        cin >> n >> k;\n        int p=0;\n        for(int i=0;i<n;i++)\n        {\n            int q=p^i;\n            cout << q << endl;\n            p=p^q;\n            int v;\n            cin >> v;\n            if(v==1)\n                break;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1543",
    "index": "D2",
    "title": "RPD and Rap Sheet (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that here $2\\leq k\\leq 100$. You can make hacks only if both the versions of the problem are solved.}\n\n\\textbf{This is an interactive problem!}\n\nEvery decimal number has a base $k$ equivalent. The individual digits of a base $k$ number are called $k$-its. Let's define the $k$-itwise XOR of two $k$-its $a$ and $b$ as $(a + b)\\bmod k$.\n\nThe $k$-itwise XOR of two base $k$ numbers is equal to the new number formed by taking the $k$-itwise XOR of their corresponding $k$-its. The $k$-itwise XOR of two decimal numbers $a$ and $b$ is denoted by $a\\oplus_{k} b$ and is equal to the decimal representation of the $k$-itwise XOR of the base $k$ representations of $a$ and $b$. All further numbers used in the statement below are in decimal unless specified.\n\nYou have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between $0$ and $n-1$ inclusive. So, you have decided to guess it. Luckily, you can try at most $n$ times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was $x$, and you guess a different number $y$, then the system changes the password to a number $z$ such that $x\\oplus_{k} z=y$. Guess the password and break into the system.",
    "tutorial": "The generalised $k$-itwise XOR does not satisfy the Self-Inverse property. So, the solution for the Easy Version won't work here. Any property which is satisfied by $k$-its will also be satisfied by base $k$ numbers since a base $k$ number is nothing but a concatenation of $k$-its. So, try to prove properties for $k$-its as they are easier to work with. Let $x_j$ denote the $j$-th $k$-it of $x$. Then, $x_j\\oplus_k z_j=y_j$ $\\forall$ valid $j$. Simplifying this, $x_j\\oplus_k z_j=y_j$ $\\implies$ $(x_j+z_j)\\bmod k=y_j$ $\\implies$ $z_j=(y_j-x_j)\\bmod k$ $\\implies$ $z_j=(y_j\\ominus_k x_j)$ where $a\\ominus_k b$ operation is defined as $a\\ominus_k b=(a-b)\\bmod k$. See Hints 2, 3 and 4 of the Easy Version. Try to generalise the solutions for easy version by exploring properties of $\\oplus_k$ and $\\ominus_k$ operators. Note - It is strongly recommended to read the proofs also to completely understand why the solutions work. The solutions described for the easy version won't work here because the general $k$-itwise operation does not satisfy self-inverse property, i.e., $a\\oplus_k a\\neq 0$. In this whole solution, we will work in base $k$ only and we will convert the numbers to decimal only for I/O purpose. Notice that any property which is satisfied by $k$-its will also be satisfied by base $k$ numbers since a base $k$ number is nothing but a concatenation of $k$-its. When we make an incorrect guess, the system changes the password to $z$ such that $x\\oplus_k z=y$. Let's denote the $j$-th $k$-it of $x$ by $x_j$. Expanding this according to the definition of $k$-itwise XOR, for all individual $k$-its $(x_j+z_j)\\bmod k=y_j$ $\\implies z_j=(y_j-x_j)\\bmod k$. So, let's define another $k$-itwise operation $a\\ominus_k b$ $= (a-b)\\bmod k$. Then, $z=y\\ominus_k x$. Now, let's extend the solutions of the Easy Version for this version. Before moving to the solution, let's see some properties of the $\\ominus_k$ operation over $k$-its. Property 1 - $(a\\ominus_k b)\\ominus_k(a\\ominus_k c)=c\\ominus_k b$ $(a\\ominus_k b)\\ominus_k(a\\ominus_k c)$ $= ((a-b)\\bmod k - (a-c)\\bmod k)\\bmod k$ $=(a-b-a+c)\\bmod k$ $=(c-b)\\bmod k$ $= c\\ominus_k b$ Property 2 - $(b\\ominus_k a)\\ominus_k(c\\ominus_k a)=b\\ominus_k c$ $(b\\ominus_k a)\\ominus_k(c\\ominus_k a)$ $= ((b-a)\\bmod k - (c-a)\\bmod k)\\bmod k$ $=(b-a-c+a)\\bmod k$ $=(b-c)\\bmod k$ $= b\\ominus_k c$ Solution - Let $q_i$ denote the $i$-th query. Then, $q_1=0$, $q_i=(i-2)\\ominus_k (i-1)$ if $i$ is even and $q_i=(i-1)\\ominus_k (i-2)$ if $i$ is odd. Let's see why this works. Claim - If the original password was $x$, after $i$ queries, the password becomes $x\\ominus_k (i-1)$ if $i$ is even and $(i-1)\\ominus_k x$ if $i$ is odd. Let's prove this by induction. Base Case - $q_1=0$. So, after $1$-st query, the password becomes $0\\ominus_k x = (1-1)\\ominus_k x$. Case 1 - $i$ is even Induction hypothesis - Let the current password after $i$ queries be $x\\ominus_k (i-1)$. Inductive step - $(i+1)$ is odd. So, the $(i+1)$-th query is $i\\ominus_k (i-1)$. The new password will be $(i\\ominus_k (i-1))\\ominus_k(x\\ominus_k (i-1))$ $= i\\ominus_k x$ by Property 2. Case 2 - $i$ is odd Induction hypothesis - Let the current password after $i$ queries be $(i-1)\\ominus_k x$. Inductive step - $(i+1)$ is even. So, the $(i+1)$-th query is $(i-1)\\ominus_k i$. The new password will be $((i-1)\\ominus_k i)\\ominus_k((i-1)\\ominus_k x)$ $= x\\ominus_k i$ by Property 1. Hence, proved by induction. Now notice that after $x$ queries, the password will become $x\\ominus_k (x-1)$ if $x$ is even or $(x-1)\\ominus_k x$ if $x$ is odd which will be equal to the $(x+1)$-th query. Hence, the problem will be solved after exactly $(x+1)$ queries. Since $0\\leq x < n$, the problem will be solved after at most $n$ queries. Again, let's denote the $i$-th query by $q_i$. Then, $q_i=q_{i-1}\\ominus_k\\bigg[q_{i-2}\\ominus_k\\Big[q_{i-3}\\ominus_k\\ldots\\ominus_k\\big[q_2\\ominus_k[q_1\\ominus_k(i-1)]\\big]\\ldots\\Big]\\bigg]$ Let's see why this works. Claim - If the original password was $x$, after $i$ queries, the password will be $q_{i}\\ominus_k\\bigg[q_{i-1}\\ominus_k\\Big[q_{i-2}\\ominus_k\\ldots\\ominus_k\\big[q_2\\ominus_k[q_1\\ominus_k x]\\big]\\ldots\\Big]\\bigg]$ Let's prove this by induction. Base Case - After the $1$-st query which is $0$, the password will be $0\\ominus_k x = q_1\\ominus_k x$. Induction hypothesis - Let the password after $i$ queries be $q_{i}\\ominus_k\\bigg[q_{i-1}\\ominus_k\\Big[q_{i-2}\\ominus_k\\ldots\\ominus_k\\big[q_2\\ominus_k[q_1\\ominus_k x]\\big]\\ldots\\Big]\\bigg]$ Inductive Step - The $(i+1)$-th query is $q_{i+1}$. After $(i+1)$ queries, the password will becomes $q_{i+1}\\ominus_k\\Bigg[q_{i}\\ominus_k\\bigg[q_{i-1}\\ominus_k\\Big[q_{i-2}\\ominus_k\\ldots\\ominus_k\\big[q_2\\ominus_k[q_1\\ominus_k x]\\big]\\ldots\\Big]\\bigg]\\Bigg]$ Hence, proved by induction. Now notice that after $x$ queries, the password will become $q_{x}\\ominus_k\\bigg[q_{x-1}\\ominus_k\\Big[q_{x-2}\\ominus_k\\ldots\\ominus_k\\big[q_2\\ominus_k[q_1\\ominus_k x]\\big]\\ldots\\Big]\\bigg]$ which will be equal to the $(x+1)$-th query. Hence, the problem will be solved after exactly $(x+1)$ queries. Since $0\\leq x < n$, the problem will be solved after at most $n$ queries. But we are not done yet. This solution is $\\mathcal{O}(n^2)$ which will time out. The solution for this isn't as simple as what we did for the Easy version because the $\\ominus_k$ operation is neither associative nor commutative. So, it's time to explore some more properties of these operations. Property 3 - $a\\ominus_k(b\\ominus_k c) = (a\\ominus_k b)\\oplus_k c$ $a\\ominus_k(b\\ominus_k c)$ $= (a-(b-c)\\bmod k)\\bmod k$ $= (a-b+c)\\bmod k$ $= ((a-b)\\bmod k+c)\\bmod k$ $= (a\\ominus_k b)\\oplus_k c$ Property 4 - $a\\ominus_k(b\\oplus_k c) = (a\\ominus_k b)\\ominus_k c$ $a\\ominus_k(b\\oplus_k c)$ $= (a-(b+c)\\bmod k)\\bmod k$ $= (a-b-c)\\bmod k$ $= ((a-b)\\bmod k-c)\\bmod k$ $= (a\\ominus_k b)\\ominus_k c$ Now, let's try to simplify our queries. $q_1=0$ $q_2=q_1\\ominus_k 1$ $q_3=q_2\\ominus_k [q_1\\ominus_k 2]=[q_2\\ominus_k q_1]\\oplus_k 2$ (by Property 3) $q_4=q_3\\ominus_k \\big[q_2\\ominus_k [q_1\\ominus_k 3]\\big]=q_3\\ominus_k \\big[[q_2\\ominus_k q_1]\\oplus_k 3\\big]=\\big[q_3\\ominus_k[q_2\\ominus_k q_1]\\big]\\ominus_k 3$ (by Property 4) $\\ldots$ See the pattern? You can generalize the $i$-th query as - $q_i=q_{i-1}\\ominus_k\\Big[q_{i-2}\\ominus_k\\big[q_{i-3}\\ominus_k\\ldots\\ominus_k[q_2\\ominus_k q_1]\\ldots\\big]\\Big]\\oplus_k (i-1)$ if $i$ is odd $q_i=q_{i-1}\\ominus_k\\Big[q_{i-2}\\ominus_k\\big[q_{i-3}\\ominus_k\\ldots\\ominus_k[q_2\\ominus_k q_1]\\ldots\\big]\\Big]\\ominus_k (i-1)$ if $i$ is even So, we will maintain a prefix Negative XOR whose value after $i$ queries will be $p=q_{i}\\ominus_k\\Big[q_{i-1}\\ominus_k\\big[q_{i-2}\\ominus_k\\ldots\\ominus_k[q_2\\ominus_k q_1]\\ldots\\big]\\Big]$ Then, $q_{i+1}=p\\ominus_k i$ if $i$ is odd $q_{i+1}=p\\oplus_k i$ if $i$ is even Then update $p=q_{i+1}\\ominus_k p$ Both the operations $\\ominus_k$ and $\\oplus_k$ can be implemented naively by converting the decimal numbers to base $k$, finding the $k$-itwise XOR of the base $k$ numbers and finally converting it back to decimal. The time complexity for each of these operations will be $\\mathcal{O}(\\log_k n)$. At any stage, the maximum number that we could be dealing with will be non-negative and will not exceed $n\\times k$ as the $k$-itwise operations do not add extra $k$-its. This fits well within the limits of $y$ which is $2\\cdot 10^7$. The total time complexity of the solution will be $\\mathcal{O}(n\\log_k n)$. This part may be interesting for hackers and those who would like to understand what goes in the background checkers and interactors which determine the correctness of their solutions. You must have noticed a large number of submissions failing on Test 1 itself. If you check the checker logs of those solutions, you will find that they fail on many different test cases although the test itself has 1 or 2 test cases. This is because the grader is also adaptive apart from the Rap Sheet System being adaptive. The initial password is not fixed and the grader checks if the solution will give correct answer or not for all possible initial passwords in just a single run! Here is how this is implemented. The grader maintains a set which initially contains all possible initial passwords. Whenever you ask a query, the grader finds out which initial password will give correct answer for this query. This is found using the generalised expression of queries derived in the Method 2 solution. Take some time to convince yourself that this initial password will be unique. It then removes this initial password from the set if it still exists. After that, if the set is empty, the grader returns 1 (meaning that there is no other password for which the solution can give Wrong Answer), otherwise 0 (obviously after checking the constraints on $y$). In this way, only a solution which gives correct answers for all possible initial passwords for a particular $n$ and $k$ defined in the input will manage to pass. Sometimes, checkers and adaptive interactors are more difficult to write than the solution itself! This was one such case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint knxor(int x,int y,int k)\n{\n    int z=0;\n    int p=1;\n    while(x>0 || y>0)\n    {\n        int a=x%k;\n        x=x/k;\n        int b=y%k;\n        y=y/k;\n        int c=(a-b+k)%k;\n        z=z+p*c;\n        p=p*k;\n    }\n    return z;\n}\n\nint kxor(int x,int y,int k)\n{\n    int z=0;\n    int p=1;\n    while(x>0 || y>0)\n    {\n        int a=x%k;\n        x=x/k;\n        int b=y%k;\n        y=y/k;\n        int c=(a+b)%k;\n        z=z+p*c;\n        p=p*k;\n    }\n    return z;\n}\n\nint main()\n{\n    int t=1;\n    cin >> t;\n    while(t--)\n    {\n        int n,k;\n        cin >> n >> k;\n        int p=0;\n        for(int i=0;i<n;i++)\n        {\n            if(i==0)\n                cout << 0 << endl;\n            else if(i%2==0)\n            {\n                int q = kxor(p,i,k);\n                cout << q << endl;\n                p=knxor(q,p,k);\n            }\n            else\n            {\n                int q = knxor(p,i,k);\n                cout << q << endl;\n                p=knxor(q,p,k);\n            }\n            int v;\n            cin >> v;\n            if(v==1)\n                break;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1543",
    "index": "E",
    "title": "The Final Pursuit",
    "statement": "Finally, you have defeated Razor and now, you are the Most Wanted street racer. Sergeant Cross has sent the full police force after you in a deadly pursuit. Fortunately, you have found a hiding spot but you fear that Cross and his force will eventually find you. To increase your chances of survival, you want to tune and repaint your BMW M3 GTR.\n\nThe car can be imagined as a permuted $n$-dimensional hypercube. A simple $n$-dimensional hypercube is an undirected unweighted graph built recursively as follows:\n\n- Take two simple $(n-1)$-dimensional hypercubes one having vertices numbered from $0$ to $2^{n-1}-1$ and the other having vertices numbered from $2^{n-1}$ to $2^{n}-1$. A simple $0$-dimensional Hypercube is just a single vertex.\n- Add an edge between the vertices $i$ and $i+2^{n-1}$ for each $0\\leq i < 2^{n-1}$.\n\nA permuted $n$-dimensional hypercube is formed by permuting the vertex numbers of a simple $n$-dimensional hypercube in any arbitrary manner.\n\nExamples of a simple and permuted $3$-dimensional hypercubes are given below:\n\nNote that a permuted $n$-dimensional hypercube has the following properties:\n\n- There are exactly $2^n$ vertices.\n- There are exactly $n\\cdot 2^{n-1}$ edges.\n- Each vertex is connected to exactly $n$ other vertices.\n- There are no self-loops or duplicate edges.\n\nLet's denote the permutation used to generate the permuted $n$-dimensional hypercube, representing your car, from a simple $n$-dimensional hypercube by $P$. Before messing up the functionalities of the car, you want to find this permutation so that you can restore the car if anything goes wrong. But the job isn't done yet.\n\nYou have $n$ different colours numbered from $0$ to $n-1$. You want to colour the vertices of this permuted $n$-dimensional hypercube in such a way that for each and every vertex $u$ satisfying $0\\leq u < 2^n$ and for each and every colour $c$ satisfying $0\\leq c < n$, there is at least one vertex $v$ adjacent to $u$ having a colour $c$. In other words, from each and every vertex, it must be possible to reach a vertex of any colour by just moving to an adjacent vertex.\n\nGiven the permuted $n$-dimensional hypercube, find any valid permutation $P$ and colouring.",
    "tutorial": "In a simple $n$-Dimensional Hypercube, two vertices are connected if and only if they differ by exactly $1$ bit in their binary representation. The $n$-Dimensional Hypercubes are highly symmetric and all vertices are equivalent. If we select a particular vertex, then all directions in which the edges connected to it goes are also equivalent. For any two vertices $a$ and $b$ separated at a distance of exactly $2$, there are exactly $2$ vertices connected to both $a$ and $b$. Any permuted $n$-Dimensional Hypercube is isomorphic to the simple $n$-Dimensional Hypercube. So, its structure is same as the simple $n$-Dimensional Hypercube. You can find the permutation greedily Before moving to the solution, notice a very important property of simple $n$-Dimensional Hypercubes - Two vertices $a$ and $b$ are connected if and only if $a$ and $b$ differ by exactly one bit in their binary representations. The permutation can be found using the following greedy algorithm - First, assign any arbitrary vertex as $p_0$. This is obvious since all vertices are equivalent. Then, in the simple $n$-Dimensional Hypercube, all powers of $2$ must be connected to the vertex $0$. Moreover, these vertices are added only when we are adding another dimension to the cube. Since all directions are also equivalent, it does not matter in which direction we add a new dimension. So, we can assign all the $n$ vertices connected to $p_0$ in the permuted $n$-Dimensional Hypercube as $p_1$, $p_2$, $p_4$, $p_8$, $\\ldots$, $p_{2^{n-1}}$ in any arbitrary order. Now, we will find $p_u$ for the remaining vertices in increasing order of $u$. In order to find $p_u$, first find a set $S$ of vertices $v$ such that $v < u$ and $v$ is connected to $u$ in the simple $n$-Dimensional Hypercube. Then find any vertex $w$ connected to all the vertices $p_v$ such that $v\\in S$ in the permuted $n$-Dimensional Hypercube and assign $p_u=w$. I claim that we can never make a wrong choice because we will never have a choice! There will only be one such vertex $w$ for any $u$. Let's prove it. Consider two vertices $v_1$ and $v_2$ in the set $S$. These vertices will differ by exactly $2$ bits in their binary representation. Let the bits in which they differ be $b_x$ and $b_y$. Then, they will have the form $v_1=\\ldots b_x\\ldots b_y\\ldots$ and $v_2=\\ldots b^{'}_{x}\\ldots b^{'}_{y}\\ldots$ where $\\ldots$ represent the same bits. Now, only two vertices $u_1=\\ldots b_{x}\\ldots b^{'}_{y}\\ldots$ and $u_2=\\ldots b^{'}_{x}\\ldots b_{y}\\ldots$ can be connected to both $v_1$ and $v_2$. Since a permuted $n$-Dimensional Hypercube is isomorphic to a simple $n$-Dimensional Hypercube, there will only be two vertices connected to both $p_{v_1}$ and $p_{v_2}$ in the permuted $n$-Dimensional Hypercube also. If we iterate over $u$ in increasing order, then $b_x\\neq b_y$, otherwise one of $v_1$ or $v_2$ will be greater than $u$ which is a contradiction. So, the only vertices connected to both $v_1$ and $v_2$ will have the forms $u_1=\\ldots 0\\ldots 0\\ldots$ and $u_2=\\ldots 1\\ldots 1\\ldots$. Now since $u_1<v_1$ and $u_1<v_2$, $p_{u_1}$ has already been calculated and so, one of the vertex connected to both $p_{v_1}$ and $p_{v_2}$ in the permuted $n$-Dimensional Hypercube has already been used. So, we are left with only one choice for such a vertex $w$. Let's call the vertex connected to a given vertex and which is in the opposite constituent smaller hypercube the image of the given vertex. Lemma - if there is an edge $(a, b)$ in the $n$-Dimensional hypercube where vertices $a$ and $b$ lie in different constituent $(n-1)$-Dimensional Hypercubes (in other words, $a$ and $b$ are images of each other), then for all vertices $q$ adjacent to $a$, the image of $q$ is adjacent to $b$. This lemma can be proved by using the fact that two vertex are connected if and only if they differ by exactly $1$ bit. Select any two vertices $a$ and $b$. They form a starting point: we treat them as two vertices in opposite constituents (by symmetry, we can prove that any pairs can be treated as such). Now let us perform multisource BFS with $a$ and $b$ as source nodes. Due to the lemma, the nodes which are discovered from $a$ first lie in the component of $a$, and those which are discovered from $b$ first lie in the component of $b$ (it is easy again to prove it using induction on depth of already discovered vertices). So we have separated these two constituent smaller dimension hypercubes. Lets call a recursive function on any one of them: this recursive function returns a permutation which transforms the permutated hypercube to the simple hypercube. Now, we find for each vertex, in the constituent hypercube whose permutation we just found, its image. Then we can find the permutation for the other constituent by just adding $2^{n-1}$ to the corresponding image. Hence we perform the merging process of recursion. The time complexity of this approach is $\\mathcal{O}(n\\cdot 2^{n})$ Instead of colouring the permuted $n$-Dimensional Hypercube, try to colour the simple $n$-Dimensional Hypercube and map these colours to the permuted one in the end using the permutation found in Part 1. The number of vertices of each colour will be equal. Try to colour a simple $4$-Dimensional Hypercube. This is not a graph problem, rather a constructive problem. The way in which vertices are connected in a simple $n$-Dimensional Hypercube suggests something related to Bitwise XOR. Let's try to colour the simple $n$-Dimensional Hypercube instead of the permuted one. We can map the colours to the permuted one in the end using the permutation found in Part 1. I claim that if $n$ is not a power of $2$, then no colouring exists. A simple explanation is that the graph is symmetric and also the colours. So, it is natural that the number of vertices of each colour must be equal meaning $2^n$ must be divisible by $n$ or in other words, $n$ must be a power of $2$ itself. But if symmetry doesn't satisfy you, I have a formal proof too. According to the condition, every vertex must be connected to at least one vertex of every colour or equivalently, exactly one vertex of every colour since there are $n$ colours and $n$ neighbours of each vertex. So, if we consider the set of neighbours of any vertex, every colour will appear exactly once in that set. If we consider the multi-set of neighbours of all vertices, every colour will appear $2^n$ times in that set. But every vertex has been counted $n$ times in this multi-set because a particular vertex is the neighbour of $n$ other vertices. So, if we consider the set of all vertices, every colour will appear $\\frac{2^n}{n}$ times in that set. Obviously, this number must be a whole number. So, $2^n$ must be divisible by $n$ or in other words, $n$ must itself be a power of $2$ for a colouring to exist. Otherwise, it doesn't exist. To show that a colouring exists if $n$ is a power of $2$, we will construct a colouring. Construction - This is the most interesting and difficult part of the whole problem. The following construction works - Consider a vertex $u$. Let its binary representation be $b_{n-1}b_{n-2}\\ldots b_2 b_1 b_0$. Then the colour of this vertex will be $\\bigoplus\\limits_{i=0}^{n-1} i\\cdot b_i$. Let's show why this works. $\\bigoplus\\limits_{i=0}^{n-1} i\\cdot b_i$ will always lie between $0$ and $n-1$ inclusive because $n$ is a power of $2$. If we are at a vertex $u$ with a colour $c_1$ and we want to reach a vertex of colour $c_2$, we can reach the vertex $v=u\\oplus(1\\ll (c_1\\oplus c_2))$. This is a vertex adjacent to $u$ since it differs from it by exactly $1$ bit and this is the $(c_1\\oplus c_2)$-th bit. Notice that the colour of this vertex $v$ will be $c_1\\oplus (c_1\\oplus c_2) = c_2$. $(c_1\\oplus c_2)$ will always lie between $0$ and $n-1$ because $n$ is a power of $2$. So, $v$ will always be a valid vertex number. You can see that many of these facts break when $n$ is not a power of $2$. So, this colouring will not work in such cases. Finally, after colouring the simple hypercube, we need to restore the vertex numbers of the permuted hypercube. This can be simply done by replacing all vertices $u$ with $p_u$ using the permutation we found in Part 1. Well, that's enough of theoretical stuff. For those who like visualising things, here is a 4-D Hypercube and its colouring - Finding the permutation takes $\\mathcal{O}(n\\cdot\\log_2 n\\cdot 2^n)$ time if implemented using set or $\\mathcal{O}(n^2\\cdot 2^n)$ time if implemented using vector. Constructing the colouring for the simple $n$-Dimensional Hypercube takes $\\mathcal{O}(n\\cdot 2^n)$ time. Restoring colours for the permuted $n$-Dimensional Hypercube takes $\\mathcal{O}(2^n)$ time. So, the overall time complexity is $\\mathcal{O}(n\\cdot\\log_2 n\\cdot 2^n)$ or $\\mathcal{O}(n^2\\cdot 2^n)$ depending upon implementation.",
    "code": "#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <set>\n#include <utility>\n#include <queue>\n#include <map>\n#include <assert.h>\n#include <stack>\n#include <string>\n#include <ctime>\n#include <chrono>\n#include <random>\nusing namespace std;\n \nconst int MAX=65536;\nint power[21]={0};\nvector<int> adj[MAX+1];\nbool xtra[MAX+1];\nbool in[MAX+1];\nvector<int> f(vector<int> s)\n//given a set of vertices [graph], returns the permutation that was applied to the simple hypercube to get this graph\n{\n\t/*\n\tcout << \"set\\n\";\n\tfor (auto it : s)\n\t{\n\t\tcout << it << \" \";\n\t}\n\tcout << '\\n';\n\t*/\n\tif ((int)s.size()==2)\n\t{\n\t\tvector<int> p(2);\n\t\tp[0]=s[0];\n\t\tp[1]=s[1];\n\t\treturn p;\n\t}\n\tfor (auto i: s) in[i]=true;\n\tint v1=s[0];\n\tint v2=-1;\n \n\tfor (auto i: adj[v1])\n\t{\n\t\tif (in[i])\n\t\t{\n\t\t\tv2=i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tassert(v2!=-1);\n\t//cout << \"v1= \" << v1 << \" v2 = \" << v2 << '\\n';\n\tvector<int> component;\n\t//multisource BFS from (v1, v2)\n\t{\n\t\tqueue<int> q;\n\t\tq.push(v1);\n\t\tq.push(v2);\n\t\tmap<int, bool> vis;\n\t\tvis[v1]=true;\n\t\tvis[v2]=true;\n\t\tmap<int, bool> cmp;\n\t\tcmp[v1]=true;\n\t\tcomponent.push_back(v1);\n\t\twhile (!q.empty())\n\t\t{\n\t\t\tauto u=q.front();\n\t\t\tq.pop();\n\t\t\tfor (auto i: adj[u])\n\t\t\t{\n\t\t\t\tif ((!vis[i])&&in[i])\n\t\t\t\t{\n\t\t\t\t\tvis[i]=true;\n\t\t\t\t\tq.push(i);\n\t\t\t\t\tcmp[i]=cmp[u];\n\t\t\t\t\tif (cmp[i]) component.push_back(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor (auto i: s) in[i]=false;\n\tfor (auto i: component) in[i]=true;\n\tvector<int> p1=f(component);\n\tfor (auto i: s) in[i]=true;\n\tfor (auto i: component) xtra[i]=true;\n\t\n\tvector<int> p((int)s.size());\n\t\n\tint z=component.size();\n\tassert(2*z==(int)s.size());\n\t\n\tfor (int i=0; i<z; i++) p[i]=p1[i];\n\t\n\tfor (int i=0; i<z; i++)\n\t{\n\t\t//i+z\n\t\tint g=-1;\n\t\tfor (auto i: adj[p[i]])\n\t\t{\n\t\t\tif (in[i]&&(!xtra[i]))\n\t\t\t{\n\t\t\t\tg=i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tassert(g!=-1);\n\t\tp[z+i]=g;\n\t}\n\tfor (auto i: component) xtra[i]=false;\n\tfor (auto i: s) in[i]=false;\n\treturn p;\n}\n \nvector<int> colorit(int n)\n{\n\tvector<int> ret(n);\n\tfor (int i=0; i<n; i++)\n\t{\n\t\tint res=0;\n\t\tfor (int z=0; z<20; z++) res^=z*((power[z]&i)!=0);\n\t\tret[i]=res;\n\t}\n\treturn ret;\n}\n \nvoid solve()\n{\n\tint n;\n\tcin>>n;\n\tfor (int i = 0; i < power[n]; i++) adj[i].clear();\n\tfor (int j = 0; j < n * power[n - 1]; j++)\n\t{\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tadj[u].push_back(v);\n\t\tadj[v].push_back(u);\n\t}\n\tvector<int> p;\n\t\n\t{\n\t\tvector<int> s;\n\t\tfor (int i=0; i<power[n]; i++) s.push_back(i);\n\t\tp=f(s);\n\t}\n\t\n\tfor (int i=0; i<power[n]; i++) cout<<p[i]<<' ';\n\tcout<<'\\n';\n\t\n\tif (power[n]%n)\n\t{\n\t\tcout<<-1<<'\\n';\n\t\treturn;\n\t}\n\tvector<int> col=colorit(power[n]);\n\tvector<int> out(power[n]);\n\tfor (int i=0; i<power[n]; i++)\n\t{\n\t\tout[p[i]]=col[i];\n\t}\n\tfor (int i=0; i<power[n]; i++) cout<<out[i]<<' ';\n\tcout<<'\\n';\n\treturn;\n}\n \nsigned main()\n{\n\tios::sync_with_stdio(0);\n\tcin.tie(NULL); cout.tie(NULL);\n\tint t;\n\tcin >> t;\n\t//t=1;\n\t\n\tpower[0]=1;\n\tfor (int j=1; j<=20; j++) power[j]=power[j-1]*2;\n\t\n\twhile (t--)\n\t{\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "divide and conquer",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1545",
    "index": "A",
    "title": "AquaMoon and Strange Sort",
    "statement": "AquaMoon has $n$ friends. They stand in a row from left to right, and the $i$-th friend from the left wears a T-shirt with a number $a_i$ written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is \\textbf{right}.\n\nAquaMoon can make some operations on friends. On each operation, AquaMoon can choose two \\textbf{adjacent} friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.\n\nAquaMoon hopes that after some operations, the numbers written on the T-shirt of $n$ friends in the row, read from left to right, become \\textbf{non-decreasing}. Also she wants, that all friends will have a direction of \\textbf{right} at the end. Please find if it is possible.",
    "tutorial": "It's easy to see that each number needs to move an even distance. For the same number, count how many of them are in the odd position and even position. Sort the array and count again. The given array named A, the sorted array named B. For every number, if the number of its occurrence in the odd position in A is different from its occurrence in the odd position in B, or the number of its occurrence in the even position in A is different from its occurrence in the even position in B, then the answer is NO. Otherwise the answer is YES.",
    "code": "#include <bits/stdc++.h>\nstd::vector<int> a;\nint cnt[100001][2];\nint main() {\n  int n, T, flag;\n  scanf(\"%d\", &T);\n  while(T--){\n\tscanf(\"%d\", &n), a.resize(n), flag = 0;\n    for (int i = 0; i < n; ++i)\n      scanf(\"%d\", &a[i]), ++cnt[a[i]][i % 2];\n    std::sort(a.begin(), a.end());\n    for (int i = 0; i < n; ++i)\n      --cnt[a[i]][i % 2];\n    for (int i = 0; i < n; ++i)\n      if (cnt[a[i]][0] != 0 || cnt[a[i]][1] != 0) {\n        puts(\"NO\"), flag = 1;\n\t\tbreak;\n      }\n    if (flag == 0) puts(\"YES\");\n\ta.clear();\n\tfor (int i = 0; i < n; ++i)\n      cnt[a[i]][0] = cnt[a[i]][1] = 0;\n  }\n  return 0;\n}",
    "tags": [
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1545",
    "index": "B",
    "title": "AquaMoon and Chess",
    "statement": "Cirno gave AquaMoon a chessboard of size $1 \\times n$. Its cells are numbered with integers from $1$ to $n$ from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied.\n\nIn each operation, AquaMoon can choose a cell $i$ with a pawn, and do \\textbf{either} of the following (if possible):\n\n- Move pawn from it to the $(i+2)$-th cell, if $i+2 \\leq n$ and the $(i+1)$-th cell is occupied and the $(i+2)$-th cell is unoccupied.\n- Move pawn from it to the $(i-2)$-th cell, if $i-2 \\geq 1$ and the $(i-1)$-th cell is occupied and the $(i-2)$-th cell is unoccupied.\n\nYou are given an initial state of the chessboard. AquaMoon wants to count the number of states reachable from the initial state with some sequence of operations. But she is not good at programming. Can you help her? As the answer can be large find it modulo $998\\,244\\,353$.",
    "tutorial": "We enumerate $i$ from $1$ to $n$. If position $i-1$ and $i$ both contain a chess and $i-1$ is not in other groups, then we divide them into one group. We can change the operation a little: Each time we can swap the two consecutive $1$ and the element to their left or right. It's easy to see this operation equals to the initial one. So that means we can take out the groups (two consecutive $1$) and insert them to any position of the chessboard. So let the number of groups be $m$, the number of zeros be $n$, it's easy to find that the answer is $\\binom{n+m}{m}$(Since inserting one group to the left of some $1$ or to the right of it are the same).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n\nconst int MAXN = 100010;\nconst int MOD = 998244353;\nchar str[MAXN];\nlong long F[MAXN], rF[MAXN];\nlong long inv(long long a, long long m) {\n\tif (a == 1) return 1;\n\treturn inv(m%a, m) * (m - m/a) % m;\n}\nint main() {\n\tint T;\n\tint n;\n\tF[0] = rF[0] = 1;\n\tfor (int i = 1; i < MAXN; i++) {\n\t\tF[i] = F[i-1] * i % MOD;\n\t\trF[i] = rF[i-1] * inv(i, MOD) % MOD;\n\t}\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tscanf(\"%d\", &n);\n\t\tscanf(\"%s\", str);\n\t\tint cg = 0;\n\t\tint c0 = 0;\n\t\tint c1 = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (str[i] == '0') {\n\t\t\t\tc0++;\n\t\t\t} else if (i+1 < n && str[i+1] == '1') {\n\t\t\t\tcg++;\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tc1++;\n\t\t\t}\n\t\t}\n\t\tlong long ans = F[cg + c0] * rF[c0] % MOD * rF[cg] % MOD;\n\t\tprintf(\"%d\\n\", (int) ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1545",
    "index": "C",
    "title": "AquaMoon and Permutations",
    "statement": "Cirno has prepared $n$ arrays of length $n$ each. Each array is a permutation of $n$ integers from $1$ to $n$. These arrays are special: for all $1 \\leq i \\leq n$, if we take the $i$-th element of each array and form another array of length $n$ with these elements, the resultant array is also a permutation of $n$ integers from $1$ to $n$. In the other words, if you put these $n$ arrays under each other to form a matrix with $n$ rows and $n$ columns, this matrix is a Latin square.\n\nAfterwards, Cirno added additional $n$ arrays, each array is a permutation of $n$ integers from $1$ to $n$. For all $1 \\leq i \\leq n$, there exists \\textbf{at least one} position $1 \\leq k \\leq n$, such that for the $i$-th array and the $(n + i)$-th array, the $k$-th element of both arrays is the same. Notice that the arrays indexed from $n + 1$ to $2n$ \\textbf{don't have to} form a Latin square.\n\nAlso, Cirno made sure that for all $2n$ arrays, no two arrays are completely equal, i. e. for all pair of indices $1 \\leq i < j \\leq 2n$, there exists \\textbf{at least one} position $1 \\leq k \\leq n$, such that the $k$-th elements of the $i$-th and $j$-th array are \\textbf{different}.\n\nFinally, Cirno arbitrarily changed the order of $2n$ arrays.\n\nAquaMoon calls a subset of all $2n$ arrays of size $n$ \\textbf{good} if these arrays from a Latin square.\n\nAquaMoon wants to know how many good subsets exist. Because this number may be particularly large, find it modulo $998\\,244\\,353$. Also, she wants to find any good subset. Can you help her?",
    "tutorial": "Among all the arrays not be chosen, if an array have a number which appears exactly once at its column, that the array must belong to the $n$ original arrays. So, we can choose the array and delete all arrays have at least one same bit with it. If there not exists such an array discribed above, according to the Pigeonhole Principle, all numbers of the unchosen arrays must appear exactly twice on their columns. It means either the original arrays or the additional arrays can form a correct latin square. So, it's correct to choose any one of the unchosen array and delete all arrays have at least one same bit with it. Meanwhile, we need to multiply the number of solutions by 2. We need to repeat the above operations, until we have chosen $n$ arrays.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int maxn=500;\nconst long long mod=998244353;\ntypedef pair<int,int> pii;\nint n,x,y,s,t;\nint a[maxn*2+5][maxn+5],b[maxn+5][maxn+5],f[maxn+5];\nvector <pii> v;\nvector <int> c[maxn+5][maxn+5];\nint main()\n{\n    int T;\n    scanf(\"%d\",&T);\n    while (T--)\n    {\n        scanf(\"%d\",&n);\n        for (int i=1;i<=n;i++)\n        {\n            for (int j=1;j<=n;j++)\n            {\n                b[i][j]=0;\n                c[i][j].clear();\n            }\n        }\n        for (int i=1;i<=n*2;i++)\n        {\n            f[i]=0;\n            for (int j=1;j<=n;j++)\n            {\n                scanf(\"%d\",&a[i][j]);\n                b[j][a[i][j]]++;\n                c[j][a[i][j]].push_back(i);\n            }\n        }\n        int top=0,tail=0;\n        int cnt=0,idx=1;\n        long long ans=1;\n        v.clear();\n        for (int i=1;i<=n;i++)\n        {\n            for (int j=1;j<=n;j++)\n            {\n                if (b[i][j]==1)\n                {\n                    tail++;\n                    v.push_back(pii(i,j));\n                }\n            }\n        }\n        while (cnt<n)\n        {\n            if (top<tail)\n            {\n                x=v[top].first;\n                y=v[top].second;\n                if (b[x][y]!=1)\n                {\n                    top++;\n                    continue;\n                }\n                for (int i=0;i<c[x][y].size();i++)\n                {\n                    if (f[c[x][y][i]]==0)\n                    {\n                        t=c[x][y][i];\n                        break;\n                    }\n                }\n            }\n            else\n            {\n                while (f[idx]!=0)\n                {\n                    idx++;\n                }\n                t=idx;\n                ans=ans*2%mod;\n            }\n            f[t]=1;\n            cnt++;\n            for (int i=1;i<=n;i++)\n            {\n                b[i][a[t][i]]=0;\n            }\n            for (int i=1;i<=n;i++)\n            {\n                for (int j=0;j<c[i][a[t][i]].size();j++)\n                {\n                    s=c[i][a[t][i]][j];\n                    if (f[s]==0)\n                    {\n                        f[s]=2;\n                        for (int k=1;k<=n;k++)\n                        {\n                            b[k][a[s][k]]--;\n                            if (b[k][a[s][k]]==1)\n                            {\n                                tail++;\n                                v.push_back(pii(k,a[s][k]));\n                            }\n                        }\n                    }\n                }\n            }\n            top++;\n        }\n        s=0;\n        printf(\"%lld\\n\",ans);\n        for (int i=1;i<=n*2;i++)\n        {\n            if (f[i]==1)\n            {\n                s++;\n                if (s<n) printf(\"%d \",i); else printf(\"%d\\n\",i);\n            }\n        }\n    }\n}",
    "tags": [
      "2-sat",
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "graph matchings",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1545",
    "index": "D",
    "title": "AquaMoon and Wrong Coordinate",
    "statement": "Cirno gives AquaMoon a problem. There are $m$ people numbered from $0$ to $m - 1$. They are standing on a coordinate axis in points with positive integer coordinates. They are facing right (i.e. in the direction of the coordinate increase). At this moment everyone will start running with the constant speed in the direction of coordinate increasing. The initial coordinate of the $i$-th person on the line is $x_i$, and the speed of the $i$-th person is $v_i$. So the coordinate of the $i$-th person at the moment $t$ will be $x_i + t \\cdot v_i$.\n\nCirno captured the coordinates of $m$ people in $k$ consecutive integer moments from $0$ to $k - 1$. In every moment, the coordinates of $m$ people were recorded in \\textbf{arbitrary order}.\n\nTo make the problem more funny, Cirno modified one coordinate at the moment $y$ ($0 < y < k-1$) to a \\textbf{different} integer.\n\nAquaMoon wants to find the moment $y$ and the original coordinate $p$ before the modification. Actually, she is not a programmer at all. So she wasn't able to solve it. Can you help her?",
    "tutorial": "Let's denote for $sum[t]$ the sum of all coordinates at the moment $t$, and for $sum2[t]$ the sum of all squared coordinates at the moment $t$. If there is no error, the sum of the coordinates of all moments will be an arithmetic series, and the difference is $\\sum_{i=1}^m v_i$. It's easy to find the moment that contains the modified coordinate. Assuming that the moment that contains the modified coordinate is found, first use three consecutive moments without the modified coordinate. Suppose it is $t$, $t + 1$, $t + 2$. Sum of squared coordinates of moment $t$ is $sum2[t] = \\sum_{i=1}^m (x_i + t * v_i)^2$. Sum of squared coordinates of moment $t+1$ is $sum2[t+1] = \\sum_{i=1}^m (x_i + (t+1) * v_i)^2$. Sum of squared coordinates of moment $t+2$ is $sum2[t+2] = \\sum_{i=1}^n (x_i + (t+2) * v_i)^2$. We could easy to get $sum2[t] + sum2[t+2] - 2 \\times sum2[t+1] = 2 \\times \\sum_{i=1}^m v_i^2$. In this way, we can know the value of $2 \\times \\sum_{i=1}^m v_i^2$. Then we can enumerate which integer was modified at the moment $y$. We could try to update the integer back to the original coordinate, so that it can meet both $sum[y-1] + sum[y+1] = 2 \\times sum[y]$ and $sum2[y-1] + sum2[y+1] - 2 \\times sum2[y] = 2 \\times \\sum_{i=1}^m v_i^2$. It would be easy to get the original coordinate.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint n,m,i,j,k,ans1,ans2;\nlong long a[1010][1010];\nlong long c[1010],x,y,s,t,temp;\n \nint main()\n{\n    scanf(\"%d%d\",&n,&m);\n    for (i=0;i<m;i++)\n    {\n        for (j=1;j<=n;j++)\n        {\n            scanf(\"%lld\",&a[i][j]);\n            c[i]+=a[i][j];\n        }\n    }\n    x=(c[m-1]-c[0])/(m-1);\n    for (i=1;i<m;i++)\n    {\n        if ((c[i]-c[0])!=x*i)\n        {\n            ans1=i;\n            y=c[i]-c[0]-x*i;\n            break;\n        }\n    }\n    for (i=1;i<m-1;i++)\n    {\n        if (i-1!=ans1&&i!=ans1&&i+1!=ans1)\n        {\n            x=0;\n            for (j=1;j<=n;j++)\n            {\n                x+=a[i-1][j]*a[i-1][j]+a[i+1][j]*a[i+1][j]-a[i][j]*a[i][j]*2;\n            }\n            break;\n        }\n    }\n    i=ans1;\n    t=s=0;\n    for (j=1;j<=n;j++)\n    {\n        s+=a[i-1][j]*a[i-1][j]+a[i+1][j]*a[i+1][j];\n        t+=a[i][j]*a[i][j]*2;\n    }\n    s-=x;\n    for (j=1;j<=n;j++)\n    {\n        temp=t-a[i][j]*a[i][j]*2+(a[i][j]-y)*(a[i][j]-y)*2;\n        if (temp==s)\n        {\n            ans2=a[i][j]-y;\n            break;\n        }\n    }\n    cout<<ans1<<' '<<ans2<<endl;\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1545",
    "index": "E2",
    "title": "AquaMoon and Time Stop (hard version)",
    "statement": "\\textbf{Note that the differences between easy and hard versions are the constraints on $n$ and the time limit. You can make hacks only if both versions are solved.}\n\nAquaMoon knew through foresight that some ghosts wanted to curse tourists on a pedestrian street. But unfortunately, this time, these ghosts were hiding in a barrier, and she couldn't enter this barrier in a short time and destroy them. Therefore, all that can be done is to save any unfortunate person on the street from the ghosts.\n\nThe pedestrian street can be represented as a one-dimensional coordinate system. There is one person hanging out on the pedestrian street. At the time $0$ he is at coordinate $x$, moving with a speed of $1$ unit per second. In particular, at time $i$ the person will be at coordinate $x+i$.\n\nThe ghosts are going to cast $n$ curses on the street. The $i$-th curse will last from time $tl_i-1+10^{-18}$ to time $tr_i+1-10^{-18}$ (exclusively) and will kill people with coordinates from $l_i-1+10^{-18}$ to $r_i+1-10^{-18}$ (exclusively). Formally that means, that the person, whose coordinate is between $(l_i-1+10^{-18},r_i+1-10^{-18})$ in the time range $(tl_i-1+10^{-18},tr_i+1-10^{-18})$ will die.\n\nTo save the person on the street, AquaMoon can stop time at any moment $t$, and then move the person from his current coordinate $x$ to any coordinate $y$ ($t$, $x$ and $y$ are not necessarily integers). The movement costs AquaMoon $|x-y|$ energy. The movement is continuous, so if there exists some cursed area between points $x$ and $y$ at time $t$, the person will \\textbf{die too}.\n\nAquaMoon wants to know what is the minimum amount of energy she needs to spend in order to save the person on the street from all $n$ curses. But she is not good at programming. As her friend, can you help her?",
    "tutorial": "We scan through the time, each time. We need to get minimum answer for all positions of this certain time. We can use some data structure to maintain it. In detail, we use balance tree to maintain every segments which are not covered for some time $t$. We can see that after some time, the answer of every position of the segment is shifted. A new arithmetic sequence is added to the left, and the rightmost part is erased. We use lazy tags to maintain them(We update the segment only when we need to use the answer of it). When a segment is banned, then we just erase it. When a segment is added, we need to consider the answer of at most two neighboring segment. There are two conditions: 1. We use two of the neighboring segment to get the answer of the new-added segment. We need to merge the two segments and insert two arithmetic sequences between them. 2. We use only one of the neighboring segment to get the answer of the new-added segment, and this one will even influence the other. We just use brute force to erase some arithmetic sequences of the influenced segment at the end. For each segment, we use a balance tree to maintain the arithmetic sequences in it. Since each time we will only add segments of a constant number, so the time complexity is $O(nlogn)$. (The easy version is for solution without too many data structures)",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N=2000005,E=1000001;\nstruct str{\n\tint l;\n\tlong long x;\n\tint d;\n\tlong long las(){return x+(l-1)*d;}\n}a[N];\nint ch[N][2],fa[N],h[N],tot,hc,ls[N],siz[N],i;\nstruct seg{\n\tint l,r,x;\n\tbool operator <(const seg &a)const\n\t{\n\t\treturn a.r>r;\n\t}\n};\nset<seg> p;\nvoid pushup(int i)\n{\n\tsiz[i]=siz[ch[i][0]]+siz[ch[i][1]]+a[i].l;\n}\nvoid rotate(int x)\n{\n    int y=fa[x];bool d=(ch[y][0]==x);\n    ch[y][!d]=ch[x][d];\n    if(ch[x][d]!=0)fa[ch[x][d]]=y;\n    fa[x]=fa[y];if(fa[y])ch[fa[y]][ch[fa[y]][1]==y]=x;\n    ch[x][d]=y;fa[y]=x;pushup(y);\n}\nvoid splay(int i,int x,int t=0)\n{\n\tfor(int y=fa[x];y!=t;rotate(x),y=fa[x])\n\t\tif(fa[y]!=t&&(ch[fa[y]][0]==y)==(ch[y][0]==x))\n\t\t\trotate(y);\n\tpushup(x);\n\th[i]=x;\n}\nvoid Findmx(int x)\n{\n\tint i=h[x];\n\twhile(ch[i][1])\n\t\ti=ch[i][1];\n\tsplay(x,i);\n}\nvoid Findmn(int x)\n{\n\tint i=h[x];\n\twhile(ch[i][0])\n\t\ti=ch[i][0];\n\tsplay(x,i);\n}\nvoid MMerge(int x,int y)\n{\n\tif(h[y]==0||h[x]==0)\n\t{\n\t\th[x]=h[y]=max(h[x],h[y]);\n\t\treturn;\n\t}\n\tint i=h[y];\n\tfor(;ch[i][0];i=ch[i][0]);\n\tch[i][0]=h[x];\n\tfa[h[x]]=i;\n\tsplay(y,h[x]);\n}\nint Merge(int x,int y)\n{\n\tFindmx(x),Findmn(y);\n\tif(abs(a[h[x]].las()-a[h[y]].x)<=1)\n\t{\n\t\tMMerge(x,y);\n\t\treturn x;\n\t}\n\tif(a[h[x]].las()>a[h[y]].x)\n\t{\n\t\tlong long la=a[h[y]].x;\n\t\twhile(h[x]&&abs(a[h[x]].las()-la)>1)\n\t\t{\n\t\t\tif(a[h[x]].d==-1)\n\t\t\t\tla+=a[h[x]].l;\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(la+a[h[x]].l<a[h[x]].x)\n\t\t\t\t\tla+=a[h[x]].l;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tint li=(a[h[x]].l-a[h[x]].x+la+2)/2;\n\t\t\t\t\tla+=a[h[x]].l-li;\n\t\t\t\t\ta[h[x]].l=li;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\th[x]=ch[h[x]][0];\n\t\t\tfa[h[x]]=0;\n\t\t\tFindmx(x);\n\t\t}\n\t\th[++hc]=++tot;\n\t\ta[tot]={(int)(la-a[h[y]].x),la,-1};\n\t\tpushup(tot);\n\t\tls[hc]=ls[x];\n\t\tMMerge(x,hc);\n\t\tMMerge(hc,y);\n\t}\n\telse\n\t{\n\t\tlong long la=a[h[x]].las();\n\t\twhile(h[y]&&abs(a[h[y]].x-la)>1)\n\t\t{\n\t\t\tif(a[h[y]].d==1)\n\t\t\t\tla+=a[h[y]].l;\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(a[h[y]].las()>la+a[h[y]].l)\n\t\t\t\t\tla+=a[h[y]].l;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tint li=(a[h[y]].x-la)/2;\n\t\t\t\t\ta[h[y]].x-=li;\n\t\t\t\t\ta[h[y]].l-=li;\n\t\t\t\t\tla+=li;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\th[y]=ch[h[y]][1];\n\t\t\tfa[h[y]]=0;\n\t\t\tFindmn(y);\n\t\t}\n\t\th[++hc]=++tot;\n\t\ta[tot]={(int)(la-a[h[x]].las()),a[h[x]].las()+1,1};\n\t\tpushup(tot);\n\t\tls[hc]=ls[x];\n\t\tMMerge(x,hc);\n\t\tMMerge(hc,y);\n\t}\n\treturn hc;\n}\nvoid Find(int n,int x,int w)\n{\n\tif(w<siz[ch[x][0]])\n\t\tFind(n,ch[x][0],w);\n\telse\n\t\tif(siz[ch[x][0]]+a[x].l>w)\n\t\t{\n\t\t\tif(siz[ch[x][0]]==w)\n\t\t\t{\n\t\t\t\tsplay(n,x,0);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tint tmp=ch[x][1];\n\t\t\tch[x][1]=++tot;\n\t\t\tch[tot][1]=tmp;\n\t\t\tif(tmp)\n\t\t\t\tfa[tmp]=tot;\n\t\t\tfa[tot]=x;\n\t\t\ta[tot].l=a[x].l-(w-siz[ch[x][0]]);\n\t\t\ta[x].l=w-siz[ch[x][0]];\n\t\t\ta[tot].x=a[x].x+a[x].d*a[x].l;\n\t\t\ta[tot].d=a[x].d;\n\t\t\tsplay(n,tot,0);\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t\tFind(n,ch[x][1],w-a[x].l-siz[ch[x][0]]);\n}\nvoid Update(int l,int x)\n{\n\tif(l==ls[x])\n\t\treturn;\n\tint ti=l-ls[x];\n\tls[x]=l;\n\tFindmn(x);\n\tlong long w=a[h[x]].x;\n\th[++hc]=++tot;\n\ta[tot]={ti,w+ti,-1};\n\tpushup(tot);\n\tMMerge(hc,x);\n\twhile(1)\n\t{\n\t\tFindmx(x);\n\t\tif(ti<a[h[x]].l)\n\t\t{\n\t\t\ta[h[x]].l-=ti;\n\t\t\tbreak;\n\t\t}\n\t\tti-=a[h[x]].l;\n\t\th[x]=ch[h[x]][0];\n\t\tfa[h[x]]=0;\n\t}\n}\nvoid Add(int ti,int l,int r)\n{\n\th[++hc]=++tot;\n\ta[tot]={r-l+1,1<<30,1};\n\tpushup(tot);\n\tseg t={l,r,hc};\n\tls[hc]=ti;\n\tauto it=p.lower_bound(t);\n\tif(it!=p.end()&&it->l==r+1)\n\t{\n\t\tUpdate(ti,it->x);\n\t\tt.x=Merge(t.x,it->x);\n\t\tt.r=it->r;\n\t\tp.erase(it);\n\t}\n\tit=p.lower_bound(t);\n\tif(it!=p.begin())\n\t{\n\t\t--it;\n\t\tif(it->r==l-1)\n\t\t{\n\t\t\tUpdate(ti,it->x);\n\t\t\tt.x=Merge(it->x,t.x);\n\t\t\tt.l=it->l;\n\t\t\tp.erase(it);\n\t\t}\n\t}\n\tp.insert(t);\n}\nvoid Del(int ti,int l,int r)\n{\n\tseg t=*p.lower_bound({l,r,0});\n\tp.erase(t);\n\tUpdate(ti,t.x);\n\tFind(t.x,h[t.x],l-t.l);\n\tint u=ch[h[t.x]][0];\n\tfa[u]=ch[h[t.x]][0]=0;\n\tpushup(h[t.x]);\n\tint v=0;\n\tif(siz[h[t.x]]!=r-l+1)\n\t{\n\t\tFind(t.x,h[t.x],r-l+1);\n\t\tv=ch[h[t.x]][0];\n\t\tfa[v]=ch[h[t.x]][0]=0;\n\t\tv=h[t.x];\n\t}\n\tif(l!=t.l)\n\t{\n\t\th[++hc]=u;\n\t\tls[hc]=ti;\n\t\tp.insert({t.l,l-1,hc});\n\t}\n\tif(r!=t.r)\n\t{\n\t\th[++hc]=v;\n\t\tls[hc]=ti;\n\t\tp.insert({r+1,t.r,hc});\n\t}\n}\nint n,l,r,x,y,u,v,tree[N*4],lazy[N*4];\nlong long as=1<<30;\nstruct node{\n\tint l,r;\n};\nvector<node> ad[E+5],de[E+5];\nvoid modify(int i,int l,int r,int ll,int rr,int x)\n{\n\tif(l>=ll&&r<=rr)\n\t{\n\t\tlazy[i]+=x;\n\t\ttree[i]+=x;\n\t\treturn;\n\t}\n\tint mid=l+r>>1;\n\tif(mid>=ll)\n\t\tmodify(i<<1,l,mid,ll,rr,x);\n\tif(mid<rr)\n\t\tmodify(i<<1|1,mid+1,r,ll,rr,x);\n\ttree[i]=max(tree[i<<1],tree[i<<1|1])+lazy[i];\n}\nint Query(int i,int l,int r,int ll,int rr)\n{\n\tif(l>=ll&&r<=rr)\n\t\treturn tree[i];\n\tint mid=l+r>>1,s=0;\n\tif(mid>=ll)\n\t\ts=max(s,Query(i<<1,l,mid,ll,rr));\n\tif(mid<rr)\n\t\ts=max(s,Query(i<<1|1,mid+1,r,ll,rr));\n\treturn s+lazy[i];\n}\nint Findmx(int i,int l,int r,int ll,int s)\n{\n\tif(s+tree[i]==0)\n\t\treturn -1;\n\tif(l==r)\n\t\treturn l-1;\n\tint mid=l+r>>1;\n\ts+=lazy[i];\n\tif(l>=ll)\n\t{\n\t\tint y=Findmx(i<<1,l,mid,ll,s);\n\t\tif(y!=-1)\n\t\t\treturn y;\n\t\telse\n\t\t\treturn Findmx(i<<1|1,mid+1,r,ll,s);\n\t}\n\tif(mid>=ll)\n\t{\n\t\tint y=Findmx(i<<1,l,mid,ll,s);\n\t\tif(y!=-1)\n\t\t\treturn y;\n\t}\n\treturn Findmx(i<<1|1,mid+1,r,ll,s);\n}\nint Findmn(int i,int l,int r,int rr,int s)\n{\n\tif(s+tree[i]==0)\n\t\treturn -1;\n\tif(l==r)\n\t\treturn l+1;\n\tint mid=l+r>>1;\n\ts+=lazy[i];\n\tif(r<=rr)\n\t{\n\t\tint y=Findmn(i<<1|1,mid+1,r,rr,s);\n\t\tif(y!=-1)\n\t\t\treturn y;\n\t\telse\n\t\t\treturn Findmn(i<<1,l,mid,rr,s);\n\t}\n\tif(mid<rr)\n\t{\n\t\tint y=Findmn(i<<1|1,mid+1,r,rr,s);\n\t\tif(y!=-1)\n\t\t\treturn y;\n\t}\n\treturn Findmn(i<<1,l,mid,rr,s);\n}\nvoid dfs(int i)\n{\n\tif(!i)\n\t\treturn;\n\tas=min({as,a[i].x,a[i].las()});\n\tdfs(ch[i][0]);\n\tdfs(ch[i][1]);\n}\nint main()\n{\n\tscanf(\"%d\",&n);\n\tscanf(\"%d\",&x);\n\tfor(i=1;i<=n;++i)\n\t{\n\t\tscanf(\"%d %d %d %d\",&l,&r,&u,&v);\n\t\t--l,++r;\n\t\tde[l].push_back({u,v});\n\t\tad[r].push_back({u,v});\n\t}\n\tp.insert({0,E*2+5,++hc});\n\th[hc]=++tot;\n\ta[tot]={E*2+5-x+1,0,1};\n\tch[tot][0]=2;\n\tfa[++tot]=1;\n\ta[tot]={x,x,-1};\n\tpushup(2);\n\tpushup(1);\n\tfor(i=0;i<=E+1;++i)\n\t{\n\t\tfor(auto it:ad[i])\n\t\t{\n\t\t\tmodify(1,0,E,it.l,it.r,-1);\n\t\t\tauto ii=p.lower_bound({it.l,it.r,0});\n\t\t\tint nr=ii->l-1;\n\t\t\t--ii;\n\t\t\tint nl=ii->r+1;\n\t\t\tif(nl>nr)\n\t\t\t\tcontinue;\n\t\t\tint y=Findmx(1,0,E,nl,0);\n\t\t\tif(y>=nr||y==-1)\n\t\t\t\tAdd(i,nl,nr);\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(y>=nl)\n\t\t\t\t\tAdd(i,nl,y);\n\t\t\t\tint y=Findmn(1,0,E,nr,0);\n\t\t\t\tif(y<=nr)\n\t\t\t\t\tAdd(i,y,nr);\n\t\t\t}\n\t\t}\n\t\tfor(auto it:de[i])\n\t\t{\n\t\t\tmodify(1,0,E,it.l,it.r,1);\n\t\t\twhile(1)\n\t\t\t{\n\t\t\t\tauto y=p.lower_bound({0,it.l,0});\n\t\t\t\tif(y!=p.end())\n\t\t\t\t{\n\t\t\t\t\tif(min(it.r,y->r)>=max(it.l,y->l))\n\t\t\t\t\t\tDel(i,max(it.l,y->l),min(it.r,y->r));\n\t\t\t\t\telse\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tdfs(h[p.begin()->x]);\n\tcout<<as;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1545",
    "index": "F",
    "title": "AquaMoon and Potatoes",
    "statement": "AquaMoon has three integer arrays $a$, $b$, $c$ of length $n$, where $1 \\leq a_i, b_i, c_i \\leq n$ for all $i$.\n\nIn order to accelerate her potato farming, she organizes her farm in a manner based on these three arrays. She is now going to complete $m$ operations to count how many potatoes she can get. Each operation will have one of the two types:\n\n- AquaMoon reorganizes their farm and makes the $k$-th element of the array $a$ equal to $x$. In other words, perform the assignment $a_k := x$.\n- Given a positive integer $r$, AquaMoon receives a potato for each triplet $(i,j,k)$, such that $1\\le i<j<k\\le r$, and $b_{a_i}=a_j=c_{a_k}$. Count the number of such triplets.\n\nAs AquaMoon is busy finding the library, help her complete all of their operations.",
    "tutorial": "We seek a solution of roughly square root time complexity; the small constraint of $m$ hints at a solution in $O(m\\sqrt n)$. This immediately rules out solutions based on square root decomposition on sequences, because of the overhead incurred with initializing such structures. Instead of directly solving the problem, let us solve the following - equivalent - task: How can we solve $O(\\sqrt n)$ queries in $O(n)$ time? If we only consider $O(\\sqrt n)$ queries, then there are at most $O(\\sqrt n)$ positions that are modified throughout these queries. Call these positions \"dynamic points\", and the others \"static points\". A note concerning notation: The following editorial was written when $X$ and $Y$ were permutations, and as such it uses $X^{-1}_i$ to denote the value $j$ such that $X_j=i$. It was later found that the solution can be easily modified to accomodate for $X$ and $Y$ that were not permutations. You can regard $X^{-1}_i$ as the set of $j$ such that $X_j=i$. In the following, we often count the number of dynamic or static elements in a prefix that equals a certain value. The number of elements in a multiset that equal $X^{-1}_i$ is the same as the number of elements in said multiset that satisfy $X_j=i$. In implementation, we can maintain the multiset $\\{X_j:j\\in\\dots\\}$ instead of the original multiset. Call a triplet \"good\" if it satisfies $1\\le i<j< k\\le r$, and $X_{a_i}=a_j=Y_{a_k}$. Hence, for each query, the good triplets fall under 8 categories, in roughly increasing order of difficulty: $i,j,k$ are all static. We can calculate for each $r$ in $O(n)$, through DP or the like, the number of good triplets in $[1,r]$ where $i,j,k$ are all static: we simply ignore the dynamic points. This is $O(n)$ preprocessing and $O(1)$ for each query. We can calculate for each $r$ in $O(n)$, through DP or the like, the number of good triplets in $[1,r]$ where $i,j,k$ are all static: we simply ignore the dynamic points. This is $O(n)$ preprocessing and $O(1)$ for each query. $i,j,k$ are all dynamic. Similarly to 1, for each query, we do a brute force DP over all dynamic $i,j,k$ before $r$. This is $O(\\sqrt n)$ for each query. Similarly to 1, for each query, we do a brute force DP over all dynamic $i,j,k$ before $r$. This is $O(\\sqrt n)$ for each query. $i,j$ are dynamic, $k$ is static. We iterate over all dynamic $j$, moving forward, and keep track of the amount of $X^{-1}_{a_j}$ currently seen. Then, for each $j$, we know the number of dynamic $i$ that can precede it through what we tracked; what remains is to count the number of static $a_k=Y^{-1}_{a_j}$ in $[j+1,r]$ in $O(1)$. We offline all $O(n)$ intervals that we need to count in these $O(\\sqrt n)$ queries and then re-process their contribution at the end of the block. We iterate over all dynamic $j$, moving forward, and keep track of the amount of $X^{-1}_{a_j}$ currently seen. Then, for each $j$, we know the number of dynamic $i$ that can precede it through what we tracked; what remains is to count the number of static $a_k=Y^{-1}_{a_j}$ in $[j+1,r]$ in $O(1)$. We offline all $O(n)$ intervals that we need to count in these $O(\\sqrt n)$ queries and then re-process their contribution at the end of the block. $j,k$ are dynamic, $i$ is static. This is virtually the same as 3; we just iterate in reverse and we count the number of static $a_i=X^{-1}_{a_j}$ in $[1,j-1]$. This is virtually the same as 3; we just iterate in reverse and we count the number of static $a_i=X^{-1}_{a_j}$ in $[1,j-1]$. $j$ is dynamic, $i,k$ are static. Using the same data structure as 3 and 4, we multiply the number of $a_i=X^{-1}_{a_j}$ in $[1,j-1]$ with the number of static $a_k=Y^{-1}_{a_j}$ in $[j+1,r]$. Using the same data structure as 3 and 4, we multiply the number of $a_i=X^{-1}_{a_j}$ in $[1,j-1]$ with the number of static $a_k=Y^{-1}_{a_j}$ in $[j+1,r]$. $i,k$ are dynamic, $j$ is static. We iterate over all dynamic $k$. The number of good $i,j,k$ in this situation equals the number of $i,j$ where $1\\le i,j<k$, $a_i=X^{-1}_{Y_{a_k}}$, and $a_j=Y_{a_k}$, minus the number of $i,j$ where $1\\le j\\le i<k$, $a_i=X^{-1}_{Y_{a_k}}$, and $a_j=Y_{a_k}$. For the former, notice that $i,j$ are independent. As we iterate forwards through all dynamic $k$, we keep track of all dynamic values we have seen so far, and multiply the number of dynamic occurrences of $X^{-1}_{Y_{a_k}}$ with the number of static occurrences of $Y_{a_k}$ in $[1,k-1]$. As usual, to solve for static occurrences we offline them. For the latter, observe, that when $a_i=s$ we must have $a_j=X_s$ in a good triplet. Hence during the iteration over $a$, for each dynamic $i$ we count the number of static $j$ before or on it such that $a_j=X_{a_i}$. We obtain this count for each dynamic $i$ and then, for each $k$, sum the count over all $a_i=X^{-1}_{Y_{a_k}}$. We iterate over all dynamic $k$. The number of good $i,j,k$ in this situation equals the number of $i,j$ where $1\\le i,j<k$, $a_i=X^{-1}_{Y_{a_k}}$, and $a_j=Y_{a_k}$, minus the number of $i,j$ where $1\\le j\\le i<k$, $a_i=X^{-1}_{Y_{a_k}}$, and $a_j=Y_{a_k}$. For the former, notice that $i,j$ are independent. As we iterate forwards through all dynamic $k$, we keep track of all dynamic values we have seen so far, and multiply the number of dynamic occurrences of $X^{-1}_{Y_{a_k}}$ with the number of static occurrences of $Y_{a_k}$ in $[1,k-1]$. As usual, to solve for static occurrences we offline them. For the latter, observe, that when $a_i=s$ we must have $a_j=X_s$ in a good triplet. Hence during the iteration over $a$, for each dynamic $i$ we count the number of static $j$ before or on it such that $a_j=X_{a_i}$. We obtain this count for each dynamic $i$ and then, for each $k$, sum the count over all $a_i=X^{-1}_{Y_{a_k}}$. $k$ is dynamic, $i,j$ are static. We iterate over all dynamic $k$; we seek the number of static $i,j$ in $[1,k-1]$ such that $a_j=X_{a_i}$, $i<j$, and $a_j=Y_{a_k}$. We offline all $O(n)$ dynamic $k$ that we need to count in these $O(\\sqrt n)$ queries. Then, we iterate forwards through $a$ in a manner similar to part 1, keeping track of the number of $i$ that can bind to each $j$, and a sum over all current $j$ where $a_j$ equals some value, answering offlined questions on the way. We iterate over all dynamic $k$; we seek the number of static $i,j$ in $[1,k-1]$ such that $a_j=X_{a_i}$, $i<j$, and $a_j=Y_{a_k}$. We offline all $O(n)$ dynamic $k$ that we need to count in these $O(\\sqrt n)$ queries. Then, we iterate forwards through $a$ in a manner similar to part 1, keeping track of the number of $i$ that can bind to each $j$, and a sum over all current $j$ where $a_j$ equals some value, answering offlined questions on the way. $i$ is dynamic, $j,k$ are static. We iterate over all dynamic $i$; we seek the number of static $j,k$ in $[i+1,r]$ such that $a_j=Y_{a_k}$, $j<k$, and $a_j=X_{a_i}$. We offline all $O(n)$ intervals that we need to count in these $O(\\sqrt n)$ queries. Notice that the number of $j,k$ in an interval $[i+1,r]$ equals the number of $j,k$ where $j$ is in $[i+1,r]$ minus the number of $j,k$ where $j$ is in $[i+1,r]$ and $k$ is in $[r+1,n]$. We calculate the former iterating backwards through $a$ to count the number of $k$ that can bind to each $j$, and then use a sum similar to part 3. For the latter, we observe, that $j$ and $k$ are independent since we have fixed both the value of $a_j=X_{a_i}$ and $a_k=Y^{-1}_{X_{a_i}}$, so we simply multiply the possible $j$ in $[i+1,r]$ with the possible $k$ in $[r+1,n]$. We iterate over all dynamic $i$; we seek the number of static $j,k$ in $[i+1,r]$ such that $a_j=Y_{a_k}$, $j<k$, and $a_j=X_{a_i}$. We offline all $O(n)$ intervals that we need to count in these $O(\\sqrt n)$ queries. Notice that the number of $j,k$ in an interval $[i+1,r]$ equals the number of $j,k$ where $j$ is in $[i+1,r]$ minus the number of $j,k$ where $j$ is in $[i+1,r]$ and $k$ is in $[r+1,n]$. We calculate the former iterating backwards through $a$ to count the number of $k$ that can bind to each $j$, and then use a sum similar to part 3. For the latter, we observe, that $j$ and $k$ are independent since we have fixed both the value of $a_j=X_{a_i}$ and $a_k=Y^{-1}_{X_{a_i}}$, so we simply multiply the possible $j$ in $[i+1,r]$ with the possible $k$ in $[r+1,n]$. As such, we have solved $O(\\sqrt n)$ queries in $O(n)$, and have solved the problem in $O(n+m\\sqrt n)$. We can prove that this problem is more difficult than calculating matrix multiplication of two matrices with size $\\sqrt n\\times \\sqrt n$, when ignoring poly-logarithmic factors. We construct a special arrangement of array: for $a_i=2,5,8,\\dots$, the corresponding $b_{a_i}=1,4,7,\\dots$, the corresponding $c_{a_i}=3,6,9,\\dots$. For other $a_i$, $b_{a_i}=c_{a_i}=n$. We make sure that no $n$ exists in the array $a$. Array $a$ is separated into three parts from left to right. The first part consists of $1,4,7,\\dots$, each appears exactly one time. The second part consists of $2,5,8,\\dots$, each may exist multiple times. The third part consists of $3,6,9,\\dots$, each may exist multiple times. Let $f_{k}$ be the number of triplets $(i,j,k)$ that $b_{a_i}=a_j=c_{a_k}$. For each $a_k$, there is exactly one $a_i$ and it appears exactly one time. Hence, $f_{k}$ is equal to the number of corresponding $a_j$. We only modify elements of $a$ in the second part. If we regard $k,a_k$ that $k$ is in the third part of array as a point in 2D space, let $x_k=k,y_k=a_k$, then inserting a corresponding $a_j$ into the second part means a ranged plus operation for any point that $y=a_k$. A query operation with value $r$ reports the sum of all point $i$ that $x_i\\le r$. Because of our constructed array, only triplets where $k$ is in the third part can contribute to the answer. So we used an algorithm that can solve this problem to solve the two-dimensional $x=A$ add, $y=B$ sum problem, which is equivalent to $x<A$ add, $y<B$ sum when ignoring poly-logarithmic factors. This problem is further equivalent to the famous range inverse query problem, which was proven more difficult than calculating matrix multiplication of two matrices with size $\\sqrt n\\times \\sqrt n$. As currently the best matrix multiplication algorithm is $O(n^{2.373})$, seeking a $\\tilde{O}(n)$ solution is not realistic, so the $O(n+m\\sqrt n)$ solution described above is enough for competitive programming. P.S. There is an easter egg in the problem statement, find it :)",
    "code": "// (insert magical incantation)\n// (insert offerings for the Gods of codeforces judging servers)\n//LXLORZ!!!!//rejudg\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define MAXN 200005\n#define SQRTN 210\n\nnamespace io {\nconst int __SIZE = (1 << 21) + 1;\nchar ibuf[__SIZE], *iS, *iT, obuf[__SIZE], *oS = obuf, *oT = oS + __SIZE - 1,\n                                           __c, qu[55];\nint __f, qr, _eof;\n#define Gc()                                                                   \\\n  (iS == iT ? (iT = (iS = ibuf) + fread(ibuf, 1, __SIZE, stdin),               \\\n               (iS == iT ? EOF : *iS++))                                       \\\n            : *iS++)\ninline void flush() { fwrite(obuf, 1, oS - obuf, stdout), oS = obuf; }\ninline void gc(char &x) { x = Gc(); }\ninline void pc(char x) {\n  *oS++ = x;\n  if (oS == oT)\n    flush();\n}\ninline void pstr(const char *s) {\n  int __len = strlen(s);\n  for (__f = 0; __f < __len; ++__f)\n    pc(s[__f]);\n}\ninline void gstr(char *s) {\n  for (__c = Gc(); __c < 32 || __c > 126 || __c == ' ';)\n    __c = Gc();\n  for (; __c > 31 && __c < 127 && __c != ' '; ++s, __c = Gc())\n    *s = __c;\n  *s = 0;\n}\ntemplate <class I> inline bool gi(I &x) {\n  _eof = 0;\n  for (__f = 1, __c = Gc(); (__c < '0' || __c > '9') && !_eof; __c = Gc()) {\n    if (__c == '-')\n      __f = -1;\n    _eof |= __c == EOF;\n  }\n  for (x = 0; __c <= '9' && __c >= '0' && !_eof; __c = Gc())\n    x = x * 10 + (__c & 15), _eof |= __c == EOF;\n  x *= __f;\n  return !_eof;\n}\ntemplate <class I> inline void print(I x) {\n  if (!x)\n    pc('0');\n  if (x < 0)\n    pc('-'), x = -x;\n  while (x)\n    qu[++qr] = x % 10 + '0', x /= 10;\n  while (qr)\n    pc(qu[qr--]);\n}\nstruct Flusher_ {\n  ~Flusher_() { flush(); }\n} io_flusher_;\n} // namespace io\nusing io::gc;\nusing io::gi;\nusing io::gstr;\nusing io::pc;\nusing io::print;\nusing io::pstr;\n\n#define all(a) a.begin(), a.end()\n#define fi first\n#define se second\n#define pb push_back\n#define mp make_pair\n\nusing ll = long long;\nusing pii = pair<int, int>;\n\nint n;\nint a[MAXN], X[MAXN], Y[MAXN];\n\nint Xa[MAXN], Ya[MAXN];\n\nint dyn[SQRTN + 5];\nbool dynp[MAXN];\n\nint ps1[MAXN];\nll ps2[MAXN];\n\nll ps_7j[MAXN];\n\nint fake_a[MAXN], fake_Xa[MAXN], fake_Ya[MAXN];\n\n// TODO: replace with linked list\n\nstruct offl {\n  int val, id, nxt;\n} detecpool[(SQRTN * SQRTN * 11) / 2 + 5];\n\nint detec[MAXN];\n// int detec7[MAXN];\nint detec8f[MAXN];\nint detecX[MAXN], detecY[MAXN];\n\nint dryans[(SQRTN * SQRTN * 3) / 2 + 5];\nint dryansX[(SQRTN * SQRTN) / 2 + 5];\nint dryansY[(SQRTN * SQRTN * 4) / 2 + 5];\nll dryans_7[(SQRTN * SQRTN) / 2 + 5];\nll dryans_8_former[(SQRTN * SQRTN * 2) / 2 + 5];\nll ijk_static[MAXN];\n\nvoid dryrun(vector<pii> ops) {\n  copy(a, a + n, fake_a);\n  copy(Xa, Xa + n, fake_Xa);\n  copy(Ya, Ya + n, fake_Ya);\n  memset(detec, -1, sizeof detec);\n  memset(detecX, -1, sizeof detecX);\n  memset(detecY, -1, sizeof detecY);\n  // memset(detec7, -1, sizeof detec7);\n  memset(detec8f, -1, sizeof detec8f);\n  int pooln = 0;\n  auto push_back = [&](int *ve, int pos, int va, int id) {\n    detecpool[pooln] = {va, id, ve[pos]};\n    ve[pos] = pooln;\n    pooln++;\n  };\n  int dryid = 0, dryidX = 0, dryidY = 0, dryid7 = 0, dryid8f = 0;\n  for (auto [opn, r] : ops) {\n    if (opn != -1) {\n      assert(dynp[opn]);\n      a[opn] = r;\n      Xa[opn] = X[r];\n      Ya[opn] = Y[r];\n    } else {\n      int mxdyn = 0;\n      for (int i = 0; dyn[i] <= r; i++)\n        mxdyn++;\n      for (int _j = 0; _j < mxdyn; _j++) {\n        int j = dyn[_j];\n        int pfx_xai_km1 = 0;\n        if (j != 0) {\n          // int pfx_ixaj_jm1 = dryans[dryid++];\n          // int pfx_iyaj_r = dryans[dryid++];\n          // int pfx_iyaj_j = dryans[dryid++];\n          push_back(detecX, j - 1, a[j], dryidX++);\n          push_back(detecY, r, a[j], dryidY++);\n          push_back(detecY, j, a[j], dryidY++);\n\n          int k = dyn[_j];\n          // pfx_xai_km1 = dryans[dryid++];\n          // int pfx_yak_km1 = dryans[dryid++];\n          push_back(detec, k - 1, Xa[k], dryid++);\n          push_back(detec, k - 1, Ya[k], dryid++);\n\n          // ll pfx_yak_km1 = dryans_7[dryid7++];\n          // push_back(detec7, k - 1, Ya[k], dryid7++);\n        }\n        int i = j;\n        if (i != r) {\n          // ll sfx_xai_ip1 = dryans_8_former[dryid8f++];\n          // ll sfx_xai_rp1 = dryans_8_former[dryid8f++];\n          // int pfx_xai_r = dryans[dryid++];\n          // int pfx_xai_i = pfx_xai_km1;\n          // int pfx_iyxai_n = dryans[dryid++];\n          // int pfx_iyxai_r = dryans[dryid++];\n          push_back(detec8f, i + 1, Xa[i], dryid8f++);\n          push_back(detec8f, r + 1, Xa[i], dryid8f++);\n          push_back(detec, r, Xa[i], dryid++);\n          push_back(detecY, n, Xa[i], dryidY++);\n          push_back(detecY, r, Xa[i], dryidY++);\n        }\n      }\n    }\n  }\n  for (int i = 0; i <= n; i++) {\n    if (i != n && !dynp[i]) {\n      ps1[a[i]]++;\n    }\n    for (int pid = detec[i]; pid != -1; pid = detecpool[pid].nxt)\n      dryans[detecpool[pid].id] = ps1[detecpool[pid].val];\n  }\n  memset(ps1, 0, n * (sizeof(int)));\n  ll cpsm = 0;\n  for (int i = 0; i <= n; i++) {\n    if (i != n && !dynp[i]) {\n      cpsm += ps_7j[Ya[i]];\n      ps_7j[a[i]] += ps1[a[i]];\n      ps1[Xa[i]]++;\n    }\n    ijk_static[i] = cpsm;\n    for (int pid = detecX[i]; pid != -1; pid = detecpool[pid].nxt) {\n      dryansX[detecpool[pid].id] = ps1[detecpool[pid].val];\n      dryans_7[detecpool[pid].id] = ps_7j[Y[detecpool[pid].val]];\n    }\n  }\n  memset(ps1, 0, n * (sizeof(int)));\n  for (int i = 0; i <= n; i++) {\n    if (i != n && !dynp[i]) {\n      ps1[Ya[i]]++;\n    }\n    for (int pid = detecY[i]; pid != -1; pid = detecpool[pid].nxt)\n      dryansY[detecpool[pid].id] = ps1[detecpool[pid].val];\n  }\n  memset(ps1, 0, n * (sizeof(int)));\n  memset(ps_7j, 0, n * (sizeof(ll)));\n\n  for (int i = n; i >= 0; i--) {\n    if (i != n && !dynp[i]) {\n      ps2[a[i]] += ps1[a[i]];\n      ps1[Ya[i]]++;\n    }\n    for (int pid = detec8f[i]; pid != -1; pid = detecpool[pid].nxt)\n      dryans_8_former[detecpool[pid].id] = ps2[detecpool[pid].val];\n  }\n  memset(ps1, 0, n * (sizeof(int)));\n  memset(ps2, 0, n * (sizeof(ll)));\n  copy(fake_a, fake_a + n, a);\n  copy(fake_Xa, fake_Xa + n, Xa);\n  copy(fake_Ya, fake_Ya + n, Ya);\n}\n\nint PfxGud3[MAXN], SfxGud4[MAXN];\n\nvoid process(vector<pii> ops) {\n  set<int> mdfd;\n  for (auto [xx, b] : ops)\n    if (xx != -1)\n      mdfd.insert(xx);\n  int dync = 0;\n  memset(dyn, 1, sizeof dyn);\n  for (int i : mdfd)\n    dyn[dync++] = i;\n  memset(dynp, 0, sizeof dynp);\n  for (int i = 0; i < dync; i++)\n    dynp[dyn[i]] = 1;\n  dryrun(ops);\n  int dryid = 0, dryidX = 0, dryidY = 0, dryid6l = 0, dryid7 = 0, dryid8f = 0;\n  for (auto [opn, r] : ops) {\n    if (opn != -1) {\n      a[opn] = r;\n      Xa[opn] = X[r];\n      Ya[opn] = Y[r];\n    } else {\n      int mxdyn = 0;\n      for (int i = 0; dyn[i] <= r; i++)\n        mxdyn++;\n      ll P1 = ijk_static[r], P2 = 0, P3 = 0, P4 = 0, P5 = 0, P6 = 0, P7 = 0,\n         P8 = 0;\n      for (int _i = 0; _i < mxdyn; _i++) {\n        int i = dyn[_i];\n        PfxGud3[i] = ps1[a[i]];\n        P2 += ps2[Ya[i]];\n        ps2[a[i]] += ps1[a[i]];\n        ps1[Xa[i]]++;\n      }\n      for (int _i = 0; _i < mxdyn; _i++) {\n        int i = dyn[_i];\n        ps2[a[i]] = 0;\n        ps1[Xa[i]] = 0;\n      }\n      for (int _i = mxdyn - 1; _i >= 0; _i--) {\n        int i = dyn[_i];\n        SfxGud4[i] = ps1[a[i]];\n        ps1[Ya[i]]++;\n      }\n      for (int _i = 0; _i < mxdyn; _i++) {\n        int i = dyn[_i];\n        ps1[Ya[i]] = 0;\n      }\n      for (int _j = 0; _j < mxdyn; _j++) {\n        int j = dyn[_j];\n        int pfx_xai_km1 = 0;\n        if (j != 0) {\n          int pfx_ixaj_jm1 = dryansX[dryidX++];\n          int pfx_iyaj_r = dryansY[dryidY++];\n          int pfx_iyaj_j = dryansY[dryidY++];\n          P3 += PfxGud3[j] * (pfx_iyaj_r - pfx_iyaj_j);\n          P4 += pfx_ixaj_jm1 * SfxGud4[j];\n          P5 += 1ll * pfx_ixaj_jm1 * (pfx_iyaj_r - pfx_iyaj_j);\n\n          int k = dyn[_j];\n          pfx_xai_km1 = dryans[dryid++];\n          int pfx_yak_km1 = dryans[dryid++];\n          int pfxDyn_ixyak = ps1[Ya[k]];\n          ll pfxDyn_BAD_ixyak = ps2[Ya[k]];\n          ps1[Xa[k]]++;\n          ps2[Xa[k]] += pfx_xai_km1;\n          P6 += 1ll * pfx_yak_km1 * pfxDyn_ixyak - pfxDyn_BAD_ixyak;\n\n          P7 += dryans_7[dryid7++];\n        } else {\n          ps1[Xa[j]]++;\n        }\n        int i = j;\n        if (i != r) {\n          ll sfx_xai_ip1 = dryans_8_former[dryid8f++];\n          ll sfx_xai_rp1 = dryans_8_former[dryid8f++];\n          int pfx_xai_r = dryans[dryid++];\n          int pfx_xai_i = pfx_xai_km1;\n          int pfx_iyxai_n = dryansY[dryidY++];\n          int pfx_iyxai_r = dryansY[dryidY++];\n          P8 += (sfx_xai_ip1 - sfx_xai_rp1) -\n                1ll * (pfx_xai_r - pfx_xai_i) * (pfx_iyxai_n - pfx_iyxai_r);\n        }\n      }\n      for (int _i = 0; _i < mxdyn; _i++) {\n        int i = dyn[_i];\n        ps2[Xa[i]] = 0;\n        ps1[Xa[i]] = 0;\n      }\n      print(P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8);\n      pc('\\n');\n    }\n  }\n}\n\nsigned main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(0);\n  int m;\n  gi(n), gi(m);\n  for (int i = 0; i < n; i++) {\n    gi(a[i]);\n    a[i]--;\n  }\n  for (int i = 0; i < n; i++) {\n    gi(X[i]);\n    X[i]--;\n  }\n  for (int i = 0; i < n; i++) {\n    gi(Y[i]);\n    Y[i]--;\n  }\n  for (int i = 0; i < n; i++) {\n    Xa[i] = X[a[i]];\n    Ya[i] = Y[a[i]];\n  }\n  vector<pii> opq;\n  for (int qx = 0; qx < m; qx++) {\n    int op, v;\n    gi(op);\n    gi(v);\n    if (op == 1) {\n      int r;\n      gi(r);\n      opq.push_back({v - 1, r - 1});\n    } else {\n      opq.push_back({-1, v - 1});\n    }\n    if (opq.size() == SQRTN) {\n      process(opq);\n      opq.clear();\n    }\n  }\n  process(opq);\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1546",
    "index": "A",
    "title": "AquaMoon and Two Arrays",
    "statement": "AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays $a$ and $b$, both consist of $n$ non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero):\n\n- She chooses two indices $i$ and $j$ ($1 \\le i, j \\le n$), then decreases the $i$-th element of array $a$ by $1$, and increases the $j$-th element of array $a$ by $1$. The resulting values at $i$-th and $j$-th index of array $a$ are $a_i - 1$ and $a_j + 1$, respectively. Each element of array $a$ \\textbf{must be non-negative after each operation}. If $i = j$ this operation doesn't change the array $a$.\n\nAquaMoon wants to make some operations to make arrays $a$ and $b$ equal. Two arrays $a$ and $b$ are considered equal if and only if $a_i = b_i$ for all $1 \\leq i \\leq n$.\n\nHelp AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays $a$ and $b$ equal.\n\nPlease note, that you \\textbf{don't have to minimize} the number of operations.",
    "tutorial": "First, if the sum of elements in $a$ is not equal to the sum of elements in $b$, then the solution does not exist. Each time find a position $i$ satisfying $a_i>b_i$, and find such a $j$ satisfying $a_j<b_j$. Then let $a_i-1$, $a_j+1$, until the two arrays become the same.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define O(x) cout<<#x<<\" \"<<(x)<<\"\\n\"\ninline int read(){\n\tint x=0,f=1,c=getchar();\n\twhile(!isdigit(c)){if(c=='-')f=-1;c=getchar();}\n\twhile(isdigit(c)){x=(x<<1)+(x<<3)+(c^48);c=getchar();}\n\treturn f==1?x:-x;\n}\nconst int N=104;\nint n,sum,a[N];\nvector<pair<int,int> >ans;\ninline void solve(){\n\tn=read();\n\tsum=0;\n\tans.clear();\n\tfor(int i=1;i<=n;i++)a[i]=read();\n\tfor(int i=1;i<=n;i++){\n\t\ta[i]-=read();\n\t\tsum+=a[i];\n\t}\n\tif(sum){puts(\"-1\");return;}\n\tfor(int i=1;i<=n;i++){\n\t\tfor(int j=1;j<=a[i];j++){\n\t\t\tfor(int k=1;k<=n;k++)if(a[k]<0){\n\t\t\t\tans.push_back(make_pair(i,k));\n\t\t\t\t++a[k];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcout<<ans.size()<<\"\\n\";\n\tfor(auto v:ans)cout<<v.first<<\" \"<<v.second<<\"\\n\";\n}\nint main(){\n\tfor(int T=read();T--;)solve(); \n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1546",
    "index": "B",
    "title": "AquaMoon and Stolen String",
    "statement": "AquaMoon had $n$ strings of length $m$ each. $n$ is an \\textbf{odd} number.\n\nWhen AquaMoon was gone, Cirno tried to pair these $n$ strings together. After making $\\frac{n-1}{2}$ pairs, she found out that there was exactly one string without the pair!\n\nIn her rage, she disrupted each pair of strings. For each pair, she selected some positions (at least $1$ and at most $m$) and swapped the letters in the two strings of this pair at the selected positions.\n\nFor example, if $m = 6$ and two strings \"abcdef\" and \"xyzklm\" are in one pair and Cirno selected positions $2$, $3$ and $6$ she will swap 'b' with 'y', 'c' with 'z' and 'f' with 'm'. The resulting strings will be \"ayzdem\" and \"xbcklf\".\n\nCirno then stole away the string without pair and shuffled all remaining strings in arbitrary order.\n\nAquaMoon found the remaining $n-1$ strings in complete disarray. Also, she remembers the initial $n$ strings. She wants to know which string was stolen, but she is not good at programming. Can you help her?",
    "tutorial": "We can find that for each letter of the answer must appear an odd number of times in its column(Since for other strings, they appear twice in total. The operation does not change the number of the occurrence of some certain letter in one column). So we can consider each position individually. There is always exactly one letter that occurs an odd number of times. So just take them out and they are the letters of the stolen string.",
    "code": "#include <cstdio>\nconst int Maxn=1000000;\nchar s[Maxn+5];\nchar ans[Maxn+5];\nint n,m;\nvoid solve(){\n    scanf(\"%d%d\",&n,&m);\n    n=(n<<1)-1;\n    for(int i=1;i<=m;i++){\n        ans[i]=0;\n    }\n    for(int i=1;i<=n;i++){\n        scanf(\"%s\",s+1);\n        for(int j=1;j<=m;j++){\n            ans[j]^=s[j];\n        }\n    }\n    for(int i=1;i<=m;i++){\n        putchar(ans[i]);\n    }\n    putchar('\\n');\n}\nint main(){\n    int T;\n    scanf(\"%d\",&T);\n    while(T--){\n        solve();\n    }\n\treturn 0;\n}",
    "tags": [
      "interactive",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1547",
    "index": "A",
    "title": "Shortest Path with Obstacle",
    "statement": "There are three cells on an infinite 2-dimensional grid, labeled $A$, $B$, and $F$. Find the length of the shortest path from $A$ to $B$ if:\n\n- in one move you can go to any of the four adjacent cells sharing a side;\n- visiting the cell $F$ is forbidden (it is an obstacle).",
    "tutorial": "Let's suppose that the forbidden cell does not affect the shortest path. In that case, the answer would be $|x_A - x_B| + |y_A - y_B|$. The forbidden cell blocks the shortest path if and only if it belongs to every shortest path. In other words, if there is only one shortest path and the forbidden cell belongs to it. So, the answer differs from $|x_A - x_B| + |y_A - y_B|$ if and only if $A$ and $B$ are in one row or column and $F$ is between them. In that case, the answer is $|x_A - x_B| + |y_A - y_B| + 2$ (i.e. greater by $2$). In order to check that point $R$ lays between $P$ and $Q$ on a straight line, just check $\\min(P, Q) < R < \\max(P, Q)$. So, the correct solution looks like this:",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        vector<int> a(2), b(2), f(2);\n        cin >> a[0] >> a[1];\n        cin >> b[0] >> b[1];\n        cin >> f[0] >> f[1];\n        int ans = abs(a[0] - b[0]) + abs(a[1] - b[1]);\n        if ((a[0] == b[0] && a[0] == f[0] && min(a[1], b[1]) < f[1] && f[1] < max(a[1], b[1]))\n                || (a[1] == b[1] && a[1] == f[1] && min(a[0], b[0]) < f[0] && f[0] < max(a[0], b[0])))\n            ans += 2;\n        cout << ans << endl;\n    }\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1547",
    "index": "B",
    "title": "Alphabetical Strings",
    "statement": "A string $s$ of length $n$ ($1 \\le n \\le 26$) is called alphabetical if it can be obtained using the following algorithm:\n\n- first, write an empty string to $s$ (i.e. perform the assignment $s$ := \"\");\n- then perform the next step $n$ times;\n- at the $i$-th step take $i$-th lowercase letter of the Latin alphabet and write it either to the left of the string $s$ or to the right of the string $s$ (i.e. perform the assignment $s$ := $c+s$ or $s$ := $s+c$, where $c$ is the $i$-th letter of the Latin alphabet).\n\nIn other words, iterate over the $n$ first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string $s$ or append a letter to the right of the string $s$. Strings that can be obtained in that way are alphabetical.\n\nFor example, the following strings are alphabetical: \"a\", \"ba\", \"ab\", \"bac\" and \"ihfcbadeg\". The following strings \\textbf{are not} alphabetical: \"z\", \"aa\", \"ca\", \"acb\", \"xyz\" and \"ddcba\".\n\nFrom the given string, determine if it is alphabetical.",
    "tutorial": "For a start, let's find the position of the letter 'a' in string $s$. If this position does not exist, then the answer would be 'NO'. Suppose that this position exists and equals $\\text{pos}_a$. Let's create two pointers $L$ and $R$. Initially $L := \\text{pos}_a,~R := L$. We will try to build string $s$ using the algorithm from the statement. Suppose that we have built substring $s[L..R]$ in $i$ iterations. Consider the next letter of the Latin alphabet $c_i$. Let's look at cases: find position $pos$ of the letter $c_i$ in $s$ (if it does not exist then 'NO'); if $pos = L - 1$ then make an assignment $L := L - 1$ and process the next letter $c_i$; if $pos = R + 1$ then make an assignment $R := R + 1$ and process the next letter $c_i$; otherwise string $s$ is not alphabetical and the answer is 'NO'.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        string s;\n        cin >> s;\n        size_t L = s.find('a');\n        if (L == string::npos) {\n            cout << \"NO\" << endl;\n            continue;\n        }\n        size_t n = s.length(), R = L;\n        bool yes = true;\n        for (size_t i = 1; i < n; i++) {\n            size_t pos = s.find(char('a' + i));\n            if (pos == string::npos || (pos != L - 1 && pos != R + 1)) {\n                yes = false;\n                break;\n            } else {\n                L = min(L, pos);\n                R = max(R, pos);\n            }\n        }\n        cout << (yes ? \"YES\" : \"NO\") << endl;\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1547",
    "index": "C",
    "title": "Pair Programming",
    "statement": "Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.\n\nIt's known that they have worked together on the same file for $n + m$ minutes. Every minute exactly one of them made one change to the file. Before they started, there were already $k$ lines written in the file.\n\nEvery minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.\n\nMonocarp worked in total for $n$ minutes and performed the sequence of actions $[a_1, a_2, \\dots, a_n]$. If $a_i = 0$, then he adds a new line to the end of the file. If $a_i > 0$, then he changes the line with the number $a_i$. Monocarp performed actions strictly in this order: $a_1$, then $a_2$, ..., $a_n$.\n\nPolycarp worked in total for $m$ minutes and performed the sequence of actions $[b_1, b_2, \\dots, b_m]$. If $b_j = 0$, then he adds a new line to the end of the file. If $b_j > 0$, then he changes the line with the number $b_j$. Polycarp performed actions strictly in this order: $b_1$, then $b_2$, ..., $b_m$.\n\nRestore their common sequence of actions of length $n + m$ such that all actions would be correct — there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence $[a_1, a_2, \\dots, a_n]$ and Polycarp's — subsequence $[b_1, b_2, \\dots, b_m]$. They can replace each other at the computer any number of times.\n\nLet's look at an example. Suppose $k = 3$. Monocarp first changed the line with the number $2$ and then added a new line (thus, $n = 2, \\: a = [2, 0]$). Polycarp first added a new line and then changed the line with the number $5$ (thus, $m = 2, \\: b = [0, 5]$).\n\nSince the initial length of the file was $3$, in order for Polycarp to change line number $5$ two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be $[0, 2, 0, 5]$ and $[2, 0, 0, 5]$. Changes $[0, 0, 5, 2]$ (wrong order of actions) and $[0, 5, 2, 0]$ (line $5$ cannot be edited yet) are not correct.",
    "tutorial": "The solution is that if we can do something, let's do it. It doesn't make sense not to act, because neither adding a new row nor modifying an existing one can prevent the existing row from being changed in the future. Therefore, we will iterate over the actions and eagerly act Monocarp or Polycarp. Let's create two pointers $i$ and $j$ in arrays $a$ and $b$ - index of possible action of Monocarp and Polycarp and $c$ - the current length of the file. Suppose that $a_i = 0$ or $b_j = 0$ on current iteration. Then we take the appropriate zero element and increase $c$ by one. We can do that because appending a new line cannot make a new answer prefix incorrect if the previous prefix was correct. Suppose that $a_i \\ne 0$ and $b_j \\ne 0$. If $a_i > c$ and $b_j > c$ then there is no answer because we can potentially do only two actions and both make the answer incorrect. If one number is greater than $c$ and the other is less than or equals then we take the one that less than or equals $c$. If one of the sequences $a$ or $b$ ends then only one potential action needs to be checked at each iteration.",
    "code": "#include <iostream>\n#include <vector>\n\ntypedef std::vector<int> vi;\n\nint main() {\n    int t;\n    std::cin >> t;\n    while (t--) {\n        int k, n, m;\n        std::cin >> k >> n >> m;\n\n        vi a(n), b(m);\n        for (int i = 0; i < n; i++)\n            std::cin >> a[i];\n        for (int i = 0; i < m; i++)\n            std::cin >> b[i];\n\n        int pos1 = 0, pos2 = 0;\n        vi res;\n        bool ok = true;\n        while (pos1 != n || pos2 != m) {\n            if (pos1 != n && a[pos1] == 0) {\n                res.push_back(0);\n                k++;\n                pos1++;\n            } else if (pos2 != m && b[pos2] == 0) {\n                res.push_back(0);\n                k++;\n                pos2++;\n            } else if (pos1 != n && a[pos1] <= k) {\n                res.push_back(a[pos1++]);\n            } else if (pos2 != m && b[pos2] <= k) {\n                res.push_back(b[pos2++]);\n            } else {\n                std::cout << -1 << '\\n';\n                ok = false;\n                break;\n            }\n        }\n\n        if (ok) {\n            for (int cur : res)\n                std::cout << cur << ' ';\n            std::cout << std::endl;\n        }\n    }\n\n    return 0;\n}",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1547",
    "index": "D",
    "title": "Co-growing Sequence",
    "statement": "A sequence of non-negative integers $a_1, a_2, \\dots, a_n$ is called growing if for all $i$ from $1$ to $n - 1$ all ones (of binary representation) in $a_i$ are in the places of ones (of binary representation) in $a_{i + 1}$ (in other words, $a_i \\:\\&\\: a_{i + 1} = a_i$, where $\\&$ denotes bitwise AND). If $n = 1$ then the sequence is considered growing as well.\n\nFor example, the following four sequences are growing:\n\n- $[2, 3, 15, 175]$ — in binary it's $[10_2, 11_2, 1111_2, 10101111_2]$;\n- $[5]$ — in binary it's $[101_2]$;\n- $[1, 3, 7, 15]$ — in binary it's $[1_2, 11_2, 111_2, 1111_2]$;\n- $[0, 0, 0]$ — in binary it's $[0_2, 0_2, 0_2]$.\n\nThe following three sequences are non-growing:\n\n- $[3, 4, 5]$ — in binary it's $[11_2, 100_2, 101_2]$;\n- $[5, 4, 3]$ — in binary it's $[101_2, 100_2, 011_2]$;\n- $[1, 2, 4, 8]$ — in binary it's $[0001_2, 0010_2, 0100_2, 1000_2]$.\n\nConsider two sequences of non-negative integers $x_1, x_2, \\dots, x_n$ and $y_1, y_2, \\dots, y_n$. Let's call this pair of sequences co-growing if the sequence $x_1 \\oplus y_1, x_2 \\oplus y_2, \\dots, x_n \\oplus y_n$ is growing where $\\oplus$ denotes bitwise XOR.\n\nYou are given a sequence of integers $x_1, x_2, \\dots, x_n$. Find the lexicographically minimal sequence $y_1, y_2, \\dots, y_n$ such that sequences $x_i$ and $y_i$ are co-growing.\n\nThe sequence $a_1, a_2, \\dots, a_n$ is lexicographically smaller than the sequence $b_1, b_2, \\dots, b_n$ if there exists $1 \\le k \\le n$ such that $a_i = b_i$ for any $1 \\le i < k$ but $a_k < b_k$.",
    "tutorial": "In order to build lexicographically minimal co-growing with $x_i$ sequence, it is enough to build its elements iteratively, beginning from $y_1$ and minimizing the $i$-th element assuming that $y_1, \\ldots, y_{i - 1}$ have already been found. Assign $y_1 = 0$. According to the statement, all elements of the sequence are non-negative, so $y_1$ cannot be less than zero. It turns out that $y_i = 0$ is the minimal possible first element. The existence of an answer with $y_1 = 0$ follows from the construction algorithm described below. Let's use mathematical induction and construct $y_i$ under the assumption that all the previous elements of the sequence have already been constructed. In order to satisfy the condition for the growth of the final sequence, the number $x_i \\oplus y_i$ must contain one bits at all places (but not necessarily limited to them), on which there are one bits in the number $x_{i - 1} \\oplus y_{i - 1}$. Let's denote $x_{i - 1} \\oplus y_{i - 1}$ for $t$ and find out what bits can be in $y_i$ to satisfy this condition: If in $t$ stands $0$ bit then independently from $x_i$ in $y_i$ at the same spot we can place any bit because there is no limit on the corresponding bit in $x_i \\oplus y_i$; If in $t$ stands $1$ bit and in $x_i$ - $0$ then the corresponding bit in $y_i$ should be equal $1$, so that in $x_i \\oplus y_i$ the corresponding bit also equals one; If in $t$ and in $x_i$ stands $1$ bit then in $y_1$ should be $0$ bit at the corresponding place for the same reasons. The bit transformation described above can be given by the expression $y_i = \\left(t\\,|\\,x_i\\right) \\oplus x_i$. Indeed, this expression gives us bit 'one' at the fixed position if and only if at that place in $t$ stands $1$ bit and in $x_i$ stands $0$ bit. For the full solution, it remains only to apply this formula in a loop from $2$ to $n$.",
    "code": "def f(x, y):\n    return x & ~y\n\nt = int(input())\nfor tt in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n\n    ans = [0] * n\n    for i in range(1, n):\n        ans[i] = f(ans[i - 1] ^ a[i - 1], a[i])\n    print(\" \".join(map(str, ans)))",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1547",
    "index": "E",
    "title": "Air Conditioners",
    "statement": "On a strip of land of length $n$ there are $k$ air conditioners: the $i$-th air conditioner is placed in cell $a_i$ ($1 \\le a_i \\le n$). Two or more air conditioners cannot be placed in the same cell (i.e. all $a_i$ are distinct).\n\nEach air conditioner is characterized by one parameter: temperature. The $i$-th air conditioner is set to the temperature $t_i$.\n\n\\begin{center}\n{\\small Example of strip of length $n=6$, where $k=2$, $a=[2,5]$ and $t=[14,16]$.}\n\\end{center}\n\nFor each cell $i$ ($1 \\le i \\le n$) find it's temperature, that can be calculated by the formula $$\\min_{1 \\le j \\le k}(t_j + |a_j - i|),$$\n\nwhere $|a_j - i|$ denotes absolute value of the difference $a_j - i$.\n\nIn other words, the temperature in cell $i$ is equal to the minimum among the temperatures of air conditioners, increased by the distance from it to the cell $i$.\n\nLet's look at an example. Consider that $n=6, k=2$, the first air conditioner is placed in cell $a_1=2$ and is set to the temperature $t_1=14$ and the second air conditioner is placed in cell $a_2=5$ and is set to the temperature $t_2=16$. In that case temperatures in cells are:\n\n- temperature in cell $1$ is: $\\min(14 + |2 - 1|, 16 + |5 - 1|)=\\min(14 + 1, 16 + 4)=\\min(15, 20)=15$;\n- temperature in cell $2$ is: $\\min(14 + |2 - 2|, 16 + |5 - 2|)=\\min(14 + 0, 16 + 3)=\\min(14, 19)=14$;\n- temperature in cell $3$ is: $\\min(14 + |2 - 3|, 16 + |5 - 3|)=\\min(14 + 1, 16 + 2)=\\min(15, 18)=15$;\n- temperature in cell $4$ is: $\\min(14 + |2 - 4|, 16 + |5 - 4|)=\\min(14 + 2, 16 + 1)=\\min(16, 17)=16$;\n- temperature in cell $5$ is: $\\min(14 + |2 - 5|, 16 + |5 - 5|)=\\min(14 + 3, 16 + 0)=\\min(17, 16)=16$;\n- temperature in cell $6$ is: $\\min(14 + |2 - 6|, 16 + |5 - 6|)=\\min(14 + 4, 16 + 1)=\\min(18, 17)=17$.\n\nFor each cell from $1$ to $n$ find the temperature in it.",
    "tutorial": "Let's calculate two arrays $L$ and $R$, where: $L_i$ is the temperature in cell $i$ if we take only air conditioners with numbers less than or equal to $i$; $R_i$ is the temperature in cell $i$ if we take only air conditioners with numbers greater than or equal to $i$; Let's show how to calculate array $L$. We will calculate values from left to right using DP and next formula: $L_i = \\min(L_{i+1}+1, c_i)$, where $c_i$ is the temperature of air conditioner in cell $i$ (or infinity if there is no air conditioner in this cell). Indeed, the value of $L_i$ is either determined by the air conditioner in this cell (i.e. equals $c_i$) or by some air conditioner to the left, but this means that we should take the answer from the previous cell and increase it by $1$. The full code for calculating $L$ looks like this: In exactly the same way (but from right to left) we will calculate $R$: The answer for cell $i$ is $\\min(L[i], R[i])$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n, k;\n        cin >> n >> k;\n        vector<int> a(k);\n        forn(i, k)\n            cin >> a[i];\n        vector<int> t(k);\n        forn(i, k)\n            cin >> t[i];\n        vector<long long> c(n, INT_MAX);\n        forn(i, k)\n            c[a[i] - 1] = t[i];\n\n        long long p;\n\n        vector<long long> L(n, INT_MAX);\n        p = INT_MAX;\n        forn(i, n) {\n            p = min(p + 1, c[i]);\n            L[i] = p;\n        }\n\n        vector<long long> R(n, INT_MAX);\n        p = INT_MAX;\n        for (int i = n - 1; i >= 0; i--) {\n            p = min(p + 1, c[i]);\n            R[i] = p;\n        }\n\n        forn(i, n)  \n            cout << min(L[i], R[i]) << \" \";\n        cout << endl;\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "shortest paths",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1547",
    "index": "F",
    "title": "Array Stabilization (GCD version)",
    "statement": "You are given an array of positive integers $a = [a_0, a_1, \\dots, a_{n - 1}]$ ($n \\ge 2$).\n\nIn one step, the array $a$ is replaced with another array of length $n$, in which each element is the greatest common divisor (GCD) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the $(n - 1)$-th element is the $0$-th element).\n\nFormally speaking, a new array $b = [b_0, b_1, \\dots, b_{n - 1}]$ is being built from array $a = [a_0, a_1, \\dots, a_{n - 1}]$ such that $b_i$ $= \\gcd(a_i, a_{(i + 1) \\mod n})$, where $\\gcd(x, y)$ is the greatest common divisor of $x$ and $y$, and $x \\mod y$ is the remainder of $x$ dividing by $y$. In one step the array $b$ is built and then the array $a$ is replaced with $b$ (that is, the assignment $a$ := $b$ is taking place).\n\nFor example, if $a = [16, 24, 10, 5]$ then $b = [\\gcd(16, 24)$, $\\gcd(24, 10)$, $\\gcd(10, 5)$, $\\gcd(5, 16)]$ $= [8, 2, 5, 1]$. Thus, after one step the array $a = [16, 24, 10, 5]$ will be equal to $[8, 2, 5, 1]$.\n\nFor a given array $a$, find the minimum number of steps after which all values $a_i$ become equal (that is, $a_0 = a_1 = \\dots = a_{n - 1}$). If the original array $a$ consists of identical elements then consider the number of steps is equal to $0$.",
    "tutorial": "First, note that the array stabilizes if and only if it consists of equal elements, and the number the array $a$ will be consisted of is $T = \\gcd(a_1, \\ldots, a_n)$. Indeed, at the $i$-th step a number equal to $\\gcd(a_j, \\ldots, a_{(j + i) \\mod n})$ will be written at the $j$-th position in the array. This is easy to prove by induction: if at the previous step the adjacent elements in the array were equal to $\\gcd$ of the numbers on adjacent segments of length $i - 1$ in the original array, then their greatest common divisor will be the greatest common divisor of the union of these two segments (GCD is an idempotent operation). Thus, the algorithm will stop in no more than $n$ steps, since after $n$ steps all numbers will be equal exactly to $T$. If we divide all the numbers $a_i$ by $T$ before starting the algorithm, then the number of steps won't change, but the array will stabilize at the number $1$. Since the numbers in the array after the $k$-th step will be exactly equal to $\\gcd$ of all segments of length $k + 1$ of the original array $a$, it follows that the number of steps after which all values become the same is exactly equal to the length of the maximum segment of the original array on which $\\gcd > 1$. There are several ways to find the length of such a segment. For example, you can use range GCD query and binary search. The following method is based on the factorization of numbers, in other words, on their decomposition into prime factors. Factorization in this problem could be done using both the sieve of Eratosthenes or factoring each number independently in $\\mathcal{O}(\\sqrt{a_i})$. After all the numbers have been factorized, iterate over each $i$ and each prime $p$ in its factorization. In linear time we can go left and right from $i$, finding the maximum segment of numbers that contain the same factor $p$. Then we can update the answer with the length of this segment and move onto the next prime in the factorization of $a_i$ or go to $i + 1$, if all primes have already been iterated through. Note that if a segment of numbers divisible by $p$ contains indices from $l$ to $r$, then we iterate through it $r - l + 1$ times. In order to avoid reiteration on each segment, we remove $p$ from the factorizations of all numbers on the segment after considering only one. The resulting solution works in $\\mathcal{O}\\left(n \\cdot \\mathtt{MAX\\_P}\\right)$, where $\\mathtt{MAX\\_P}$ - the maximum number of different primes in factoriztion of $a_i$. Considering that $a_i \\leq 10^6$, $\\mathtt{MAX\\_P} = 8$, so the solution fits into the time limit.",
    "code": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nconst unsigned int MAX_A = 1'000'000;\nvector<unsigned int> sieve(MAX_A + 1);\nvector<unsigned int> prime;\n\nunsigned int gcd(unsigned int a, unsigned int b) {\n    return b == 0 ? a : gcd(b, a % b);\n}\n\nunsigned int solve() {\n\n    unsigned int n;\n    cin >> n;\n    vector<unsigned int> a(n);\n    for (unsigned int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n\n    unsigned int common = a[0];\n    vector<set<unsigned int>> facts(n);\n    for (unsigned int i = 1; i < n; i++) {\n        common = gcd(common, a[i]);\n    }\n    for (unsigned int i = 0; i < n; i++) {\n        unsigned int t = a[i] / common;\n        while (t != 1) {\n            facts[i].insert(sieve[t]);\n            t /= sieve[t];\n        }\n    }\n\n    unsigned int answer = 0;\n    for (unsigned int i = 0; i < n; i++) {\n        for (unsigned int p : facts[i]) {\n            int l = (i + n - 1) % n, r = i;\n            unsigned int cnt = 0;\n            while (facts[l].count(p) > 0) {\n                facts[l].erase(p);\n                l--; cnt++;\n                if (l < 0) {\n                    l = n - 1;\n                }\n            }\n            while (facts[r].count(p) > 0) {\n                if (r != i) {\n                    facts[r].erase(p);\n                }\n                ++r %= n; cnt++;\n            }\n            answer = max(answer, cnt);\n        }\n        facts[i].clear();\n    }\n\n    return answer;\n\n}\n\nint main() {\n\n    sieve[1] = 1;\n    for (unsigned int i = 2; i <= MAX_A; i++) {\n        if (sieve[i] == 0) {\n            sieve[i] = i;\n            prime.push_back(i);\n        }\n        for (unsigned int j = 0; j < prime.size() && prime[j] <= sieve[i] && i * prime[j] <= MAX_A; j++) {\n            sieve[i * prime[j]] = prime[j];\n        }\n    }\n\n    unsigned int t;\n    cin >> t;\n    for (unsigned int i = 0; i < t; i++) {\n        cout << solve() << '\\n';\n    }\n\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "divide and conquer",
      "number theory",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1547",
    "index": "G",
    "title": "How Many Paths?",
    "statement": "You are given a directed graph $G$ which can contain loops (edges from a vertex to itself). Multi-edges are absent in $G$ which means that for all ordered pairs $(u, v)$ exists at most one edge from $u$ to $v$. Vertices are numbered from $1$ to $n$.\n\nA path from $u$ to $v$ is a sequence of edges such that:\n\n- vertex $u$ is the start of the first edge in the path;\n- vertex $v$ is the end of the last edge in the path;\n- for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on.\n\nWe will assume that the empty sequence of edges is a path from $u$ to $u$.\n\nFor each vertex $v$ output one of four values:\n\n- $0$, if there are no paths from $1$ to $v$;\n- $1$, if there is only one path from $1$ to $v$;\n- $2$, if there is more than one path from $1$ to $v$ and the number of paths is finite;\n- $-1$, if the number of paths from $1$ to $v$ is infinite.\n\nLet's look at the example shown in the figure.\n\nThen:\n\n- the answer for vertex $1$ is $1$: there is only one path from $1$ to $1$ (path with length $0$);\n- the answer for vertex $2$ is $0$: there are no paths from $1$ to $2$;\n- the answer for vertex $3$ is $1$: there is only one path from $1$ to $3$ (it is the edge $(1, 3)$);\n- the answer for vertex $4$ is $2$: there are more than one paths from $1$ to $4$ and the number of paths are finite (two paths: $[(1, 3), (3, 4)]$ and $[(1, 4)]$);\n- the answer for vertex $5$ is $-1$: the number of paths from $1$ to $5$ is infinite (the loop can be used in a path many times);\n- the answer for vertex $6$ is $-1$: the number of paths from $1$ to $6$ is infinite (the loop can be used in a path many times).",
    "tutorial": "The first motivation for solving this problem is to write a lot of standard code like \"find strongly connected components\", do some DP over the condensed graph (the graph of strongly connected components), and so on. In fact, this problem can be solved much more elegantly with less code if you have a little better understanding of how depth-first search works. Consider a usual depth-first search on a digraph that is started from the vertex $1$. This will be a normal depth-first search, which will paint vertices using three colors: white (the vertex has not yet been found by the search), gray (the vertex is processing by DFS), and black (the vertex has already been processed by the DFS completely, that is, completely bypassed its subtree of the depth-first search tree). Here's the pseudocode: The following statements are true: there is a cycle in the digraph reachable from $s$ if and only if the root call dfs(s) visits in the line if color [v] == WHITE when color[v] == GRAY; moreover, for each reachable cycle from $s$ there is at least one vertex that will execute the previous item (then the vertex $v$ belongs to the cycle); if the root call dfs(s) visits in the line if color[v] == WHITE, when color [v] == BLACK, then there is more than one path (the opposite is not true). It is clear that there are infinite paths from $s$ to $u$ if and only if there is a vertex $v$ on some path from $s$ to $u$ such that $v$ is in a cycle. Thus, we mark all such vertices $v$ for which color[v] == GRAY at the moment of execution of the line if color [v] == WHITE. The fact is true: All vertices reachable from those noted in the previous phrase are those and only those vertices that an infinite number of paths lead to them. A similar fact is also true for finding vertices to which at least two paths (but a finite number) lead. Let's mark all such vertices $v$ for which color[v] == BLACK at the moment of execution of the line if color [v] == WHITE. The fact is true: Let's find all reachable vertices from those marked in the previous phrase. Let's discard those up to which we have already determined that the number of paths is infinite. The remaining reachable vertices are those and only those to which there are at least two paths (and their finite number). So the solution looks like this: let's make a depth-first search from the root, mark during it those vertices that were gray when trying to go to them (group A) and were black when trying to go to them (group B); mark the vertices reachable from the group A (let's call them AA); mark the vertices reachable from the group B (let's call them BB); the answer for the vertex is: $0$ if it is not reachable from $s$ (this determines the first DFS); $-1$, if it is from AA; $2$ if it is from BB (but not from AA); $1$, if it is not from AA and not from BB. $0$ if it is not reachable from $s$ (this determines the first DFS); $-1$, if it is from AA; $2$ if it is from BB (but not from AA); $1$, if it is not from AA and not from BB. In the author's solution, only one dfs function was used with an additional boolean parameter to determine its mode.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint n;\nvector<vector<int>> g;\nset<int> s[2];\n\nvoid dfs(int u, vector<int>& color, bool use_s) {\n    color[u] = 1;\n    for (int v: g[u])\n        if (color[v] == 0)\n            dfs(v, color, use_s);\n        else if (use_s)\n            s[color[v] - 1].insert(v);\n    color[u] = 2;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int m;\n        cin >> n >> m;\n        g = vector<vector<int>>(n);\n        forn(i, 2)\n            s[i] = set<int>();\n        forn(i, m) {\n            int x, y;\n            cin >> x >> y;\n            x--, y--;\n            g[x].push_back(y);\n        }\n        vector<int> color = vector<int>(n);\n        dfs(0, color, true);\n        vector<vector<int>> c(2, vector<int>(n));\n        forn(i, 2)\n            for (auto u: s[i])\n                dfs(u, c[i], false);\n        forn(i, n) {\n            int ans = 0;\n            if (color[i] != 0) {\n                ans = 1;\n                if (c[0][i])\n                    ans = -1;\n                else if (c[1][i])\n                    ans = 2;\n            }\n            cout << ans << \" \";\n        }\n        cout << endl;\n    }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1548",
    "index": "A",
    "title": "Web of Lies",
    "statement": "\\begin{quote}\nWhen you play the game of thrones, you win, or you die. There is no middle ground.\n\\hfill Cersei Lannister, A Game of Thrones by George R. R. Martin\n\\end{quote}\n\nThere are $n$ nobles, numbered from $1$ to $n$. Noble $i$ has a power of $i$. There are also $m$ \"friendships\". A friendship between nobles $a$ and $b$ is always mutual.\n\nA noble is defined to be vulnerable if both of the following conditions are satisfied:\n\n- the noble has at least one friend, and\n- \\textbf{all} of that noble's friends have a higher power.\n\nYou will have to process the following three types of queries.\n\n- Add a friendship between nobles $u$ and $v$.\n- Remove a friendship between nobles $u$ and $v$.\n- Calculate the answer to the following process.\n\nThe process: all vulnerable nobles are simultaneously killed, and all their friendships end. Then, it is possible that new nobles become vulnerable. The process repeats itself until no nobles are vulnerable. It can be proven that the process will end in finite time. After the process is complete, you need to calculate the number of remaining nobles.\n\nNote that the results of the process are \\textbf{not} carried over between queries, that is, every process starts with all nobles being alive!",
    "tutorial": "For various graphs, try and simulate the process. Determine a rule to figure out whether a noble survives or not. When you add or remove a single edge, how much can the answer change by? Try and recalculate the answer in $\\mathcal{O}(1)$. Due to the queries, actually simulating the process each time will be too expensive. Proof that the Process will End: Assume after round $x$, $x_i$ nobles are killed. If $x_i=0$, then the state of the graph doesn't change, so the process will have ended. If $x_i > 0$, then the number of nobles decreases. Thus, the maximum number of rounds the process can last is $N$, so it must end. $\\textbf{Lemma 1:}$ At the end of the process, no two nobles will still be friends. Proof by Contradiction: Assume that nobles $u$ and $v$ (assume WLOG that $u < v$) are still friends and the process is over. In order for $u$ to avoid being killed, there must be a noble $w$ weaker than $u$ that is also a friend of $u$. The same logic then applies to $w$, and we have an infinite descent argument. There are only a finite number of nobles weaker than $u$, so there will be a contradiction. $\\textbf{Lemma 2:}$ If all of a noble's friends are weaker than it, that noble cannot be killed. Direct Proof: Since none of the noble's friends are stronger than it, it is impossible for $\\textit{all}$ of them to be stronger at any point in the process. $\\textbf{Final Idea:}$ By combining Lemmas 1 and 2, we can prove that if ALL of a noble's friends are weaker than it, that noble survives, otherwise it will die. This leads to the solution. Maintain in an array the number of nobles weaker than noble $i$. Since the updates guarantee that the edge being removed/added does/doesn't exist respectively, we only need to keep track of the number of edges of each noble. Essentially, a noble survives if and only if weaker[i]==edges[i]. After linear precomputation, updates and queries take constant time. The time complexity is $\\mathcal{O}(N+M+Q)$.",
    "code": "//Written by m371 (Runtime: 202ms)\n\n#include <bits/stdc++.h>\nusing namespace std;\nconst int N=200050;\nint cnt[N],ans;\nint main(){\n    int n,m;scanf(\"%i %i\",&n,&m);\n    for(int i=1;i<=m;i++){\n        int u,v;scanf(\"%i %i\",&u,&v);\n        if(u>v)swap(u,v);\n        cnt[u]++;\n        if(cnt[u]==1)ans++;\n    }\n    int q;scanf(\"%i\",&q);\n    while(q--){\n        int t;scanf(\"%i\",&t);\n        if(t==1){\n            int u,v;scanf(\"%i %i\",&u,&v);\n            if(u>v)swap(u,v);\n            cnt[u]++;\n            if(cnt[u]==1)ans++;\n        }else if(t==2){\n            int u,v;scanf(\"%i %i\",&u,&v);\n            if(u>v)swap(u,v);\n            cnt[u]--;\n            if(cnt[u]==0)ans--;\n        }else printf(\"%i\n\",n-ans);\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "graphs",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1548",
    "index": "B",
    "title": "Integers Have Friends",
    "statement": "British mathematician John Littlewood once said about Indian mathematician Srinivasa Ramanujan that \"every positive integer was one of his personal friends.\"\n\nIt turns out that positive integers can also be friends with each other! You are given an array $a$ of distinct positive integers.\n\nDefine a \\textbf{subarray} $a_i, a_{i+1}, \\ldots, a_j$ to be a friend group if and only if there exists an integer $m \\ge 2$ such that $a_i \\bmod m = a_{i+1} \\bmod m = \\ldots = a_j \\bmod m$, where $x \\bmod y$ denotes the remainder when $x$ is divided by $y$.\n\nYour friend Gregor wants to know the size of the largest friend group in $a$.",
    "tutorial": "Let's say the subarray $A_i \\dots A_j$ is all congruent to $n\\mod{m}$. What does that imply about the subarray? What does the previous hint imply about the difference array generated by $D[i]=A[i+1]-A[i]$? GCD The key observation is to construct the difference array $D$ of size $N-1$, where $D[i]=abs(A[i+1]-A[i])$. If a given subarray is a friend group, then every difference is a multiple of some $m$. Since every element of $A$ is distinct, the case when $D[i]=0$ can be ignored. We can now convert this into a GCD (greatest common divisor) problem. It follows that $A[i\\dots j]$ is a friend group if and only if $\\gcd{(D[i\\dots j-1])} > 1$. Indeed, the value $m$ that we want is equal to this GCD. To solve the problem, we can use a sparse table or a segment tree to find the largest possible subarray beginning at $i$, and then max over all subarray answers to get the final answer. The time complexity is $\\mathcal{O}(N\\log{N}\\log{10^{18}})$. The first log is for the sparse table, the second is for computing GCDs. Note that the de facto time complexity may be closer to $\\mathcal{O}(N\\log{N}+N\\log{10^{18}})$, due to the insights from this blog post.",
    "code": "//Written by emorgan5289 (Runtime: 218ms)\n\n#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nconst int inf = 1e9+10;\nconst ll inf_ll = 1e18+10;\n#define all(x) (x).begin(), (x).end()\n#define pb push_back\n#define cmax(x, y) (x = max(x, y))\n#define cmin(x, y) (x = min(x, y))\n \ntemplate<typename it, typename bin_op>\nstruct sparse_table {\n \n    using T = typename remove_reference<decltype(*declval<it>())>::type;\n    vector<vector<T>> t; bin_op f;\n \n    sparse_table(it first, it last, bin_op op) : t(1), f(op) {\n        int n = distance(first, last);\n        t.assign(32-__builtin_clz(n), vector<T>(n));\n        t[0].assign(first, last);\n        for (int i = 1; i < t.size(); i++)\n            for (int j = 0; j < n-(1<<i)+1; j++)\n                t[i][j] = f(t[i-1][j], t[i-1][j+(1<<(i-1))]);\n    }\n \n    // returns f(a[l..r]) in O(1) time\n    T query(int l, int r) {\n        int h = floor(log2(r-l+1));\n        return f(t[h][l], t[h][r-(1<<h)+1]);\n    }\n};\n \nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int t; cin >> t;\n    while (t--) {\n        ll n; cin >> n;\n        vector<ll> a(n), d(n-1);\n        for (int i = 0; i < n; i++)\n            cin >> a[i];\n        for (int i = 0; i < n-1; i++)\n            d[i] = abs(a[i+1]-a[i]);\n        sparse_table g(all(d), [](ll x, ll y){\n            return __gcd(x, y);\n        });\n        int j = 0, ans = 1;\n        for (int i = 0; i < n-1; i++) {\n            while (j <= i && g.query(j, i) == 1) j++;\n            cmax(ans, i-j+2);\n        }\n        cout << ans << \"\n\";\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1548",
    "index": "C",
    "title": "The Three Little Pigs",
    "statement": "Three little pigs from all over the world are meeting for a convention! Every minute, a triple of 3 new pigs arrives on the convention floor. After the $n$-th minute, the convention ends.\n\nThe big bad wolf has learned about this convention, and he has an attack plan. At some minute in the convention, he will arrive and eat exactly $x$ pigs. Then he will get away.\n\nThe wolf wants Gregor to help him figure out the number of possible attack plans that involve eating exactly $x$ pigs for various values of $x$ ($1 \\le x \\le 3n$). Two attack plans are considered different, if they occur at different times or if the sets of little pigs to eat are different.\n\nNote that all queries are independent, that is, the wolf does not eat the little pigs, he only makes plans!",
    "tutorial": "Convert the word problem into a combinatorics equation. Write the equation for some $x$. Write the equation for $x+1$. How can we easily transition from the first to the second equation? For a given $x$, we want to calculate every third term in the sequence $\\binom{i}{x}$ for $i \\in [1,3N]$. Think about how computing the entire summation $\\sum_{i=1}^{3N}{\\binom{i}{x}}$ will help. For a given $x$, we want to compute $\\sum_{i=1}^{N}{\\binom{3i}{x}}$, which can be solved with a combinatorial dynamic programming. Define the array dp[x][m] (dimensions: $N+1\\times 3$), which computes the sum $\\sum_{i=0}^{N-1}{\\binom{3i+m}{x}}$. Under this definition, $ans[x]=dp[x][0]+\\binom{3N}{x}$, where ans is what we want to find. Under the definition of the dp, we can make the following mathematical observations. $dp[x][0]+dp[x][1]+dp[x][2]=\\sum_{i=0}^{3N-1}{\\binom{i}{x}}$, since term $i$ belongs to the array with $m=i\\mod{3}$. This summation can be condensed with the Hockey Stick Identity into $\\binom{3N}{x+1}$. By repeated uses of Pascal's Identity, we get equations (2) and (3), giving us a system of 3 equations with 3 new unknowns, which can easily be solved. $\\sum_{m=0}^{2}{dp[x][m]}=\\binom{3N}{x+1}$. $dp[x][1] = dp[x][0]+dp[x-1][0]$ $dp[x][2] = dp[x][1]+dp[x-1][1]$ The base case is that $dp[0][0]=dp[0][1]=dp[0][2]=N$. Each query can now be answered trivially. The time complexity is $\\mathcal{O}(N+Q)$ with combinatorial precomputation. Convert the word problem into a combinatorics equation. How will the Binomial Theorem be helpful? Try and construct a polynomial $P(k)$ such as the coefficient $k^x$ in that polynomial represents the number of attack plans if the wolf wants to eat $x$ pigs. Notice that $P(k)$ is a geometric series, so FFT is unnecessary. Define the polynomial $P(k)=(1+k)^3+(1+k)^6+\\cdot + (1+k)^{3N}$. The coefficient of $k^x$ in $P(k)$ is, by the Binomial theorem on each term of the polynomial, equal to $\\binom{3}{x}+\\binom{6}{x}+\\dots + \\binom{3N}{x}$. This is equal to ans[x] from the previous solution. The only thing left to do is quickly calculate $P(k)$. Due to the tight time limit, calculating the polynomial using FFT in $\\mathcal{O}{(N\\log{N})}$ is probably too slow. Instead, we notice that $P(k)$ is a geometric series. Using the geometric series formula, we get that $P(k)=\\frac{(1+k)^{3N+3}-(1+k)^3}{(1+k)^3-1}$. The numerator and denominator of this fraction can be expanded in linear time. Then all we have to do is a polynomial long division. Once we have $P(k)$, we can answer all the queries trivially. The time complexity is $\\mathcal{O}(N)$ with combinatorial precomputation.",
    "code": "//Written by Agnimandur (Runtime: 218ms)\n\n#include <bits/stdc++.h>\n \n#define ll long long\n#define sz(x) ((int) (x).size())\n#define all(x) (x).begin(), (x).end()\n#define vi vector<int>\n#define vl vector<long long>\n#define REP(i,a) for (int i = 0; i < (a); i++)\n#define add push_back\nusing namespace std;\n \nconst ll MOD = 1000000007LL;\n \n \n \nint ni() {\n    int x; cin >> x;\n    return x;\n}\n \nstruct Combo {\n    vl facs;\n    vl invfacs;\n    int N;\n \n    Combo(int N) {\n        this->N=N;\n        facs.assign(N+1,0);\n        invfacs.assign(N+1,0);\n        facs[0] = 1;\n        for (int i = 1; i <= N; i++) {\n            facs[i] = (facs[i-1]*i)%MOD;\n        }\n        invfacs[N] = power(facs[N],MOD-2);\n        for (int i = N-1; i >= 0; i--) {\n            invfacs[i] = (invfacs[i+1]*(i+1))%MOD;\n        }\n    }\n \n    ll choose(int n, int k) {\n        if (n<0||k<0||n<k) return 0LL;\n        ll denInv = (invfacs[k]*invfacs[n-k])%MOD;\n        ll ans = (facs[n]*denInv)%MOD;\n        return ans;\n    }\n \n    ll power(ll x, ll y) {\n        ll ans = 1;\n        x %= MOD;\n        while (y > 0) {\n            if (y%2==1) ans = (ans*x)%MOD;\n            y /= 2;\n            x = (x*x)%MOD;\n        }\n        return ans;\n    }\n};\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n \n    int N = ni();\n    Combo c(3*N);\n    ll DIV3 = c.power(3,MOD-2);\n \n    const int M = 1000000;\n    ll dp[3*M+1][3];\n    REP(i,3) dp[0][i] = N;\n \n    for (int x = 1; x < 3*N; x++) {\n        //solve the system of equations\n        dp[x][0] = ((c.choose(3*N,x+1)-2*dp[x-1][0]-dp[x-1][1]+3*MOD)*DIV3)%MOD;\n        dp[x][1] = (dp[x][0]+dp[x-1][0])%MOD;\n        dp[x][2] = (dp[x][1]+dp[x-1][1])%MOD;\n    }\n    \n    int Q = ni();\n    REP(q,Q) {\n        int x = ni();\n        if (x==3*N)\n            cout << \"1\n\";\n        else\n            cout << (dp[x][0]+c.choose(3*N,x))%MOD << '\n';\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1548",
    "index": "D1",
    "title": "Gregor and the Odd Cows (Easy)",
    "statement": "{This is the easy version of the problem. The only difference from the hard version is that in this version all coordinates are \\textbf{even}.}\n\nThere are $n$ fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line.\n\nThere are an infinite number of cows on the plane, one at every point with integer coordinates.\n\nGregor is a member of the Illuminati, and wants to build a triangular fence, connecting $3$ distinct existing fence posts. A cow \\textbf{strictly} inside the fence is said to be enclosed. If there are an \\textbf{odd} number of enclosed cows and the area of the fence is an \\textbf{integer}, the fence is said to be interesting.\n\nFind the number of interesting fences.",
    "tutorial": "\"Enclosed cows\" are just interior points. It's clear that Pick's Theorem will be useful. Manipulate Pick's Theorem into a modular equation. The number of boundary points between $(x_1,y_1)$ and $(x_2,y_2)$ is $\\gcd{(x_1-x_2,y_1-y_2)}$. Working with relevant formulas, find a simple condition between two points, such that they can be treated as equivalent. Every set of 3 fenceposts forms a lattice triangle We want to find the number of such lattice triangles that have an odd number of interior points. Since all the coordinates are even, the area is automatically even as well. By Pick's Theorem, $area=I+\\frac{B}{2}-1$, so $2\\cdot area=2I+B-2$. $I$ is the number of interior points, and $B$ is the number of boundary points, for an arbitrary triangle formed by 3 fenceposts. Let $A=2\\cdot area$, so $A=2I+B-2$. Since $I$ is odd, taking both sides modulo 4 we get that $A \\equiv B\\mod{4}$. Since the area is an even integer, $A$ is a multiple of 4, so we get that $A\\equiv B\\equiv 0\\mod{4}$. Let's define the $\\textbf{boundary count}$ of a segment to be the number of lattice points on it, minus 1. It can be proven that the boundary count of the segment connecting $(x_1,y_1)$ and $(x_2,y_2)$ is $\\gcd{(|x_2-x_1|,|y_2-y_1|)}$. In this problem, we only care about what the boundary count is modulo 4. Since all the coordinates are even, the GCD is guaranteed to be even, so the boundary count is either 0 or 2 mod 4. For the segment connecting $(x_1,y_1)$ and $(x_2,y_2)$ call its boundary count $b$. $b\\equiv 0\\mod{4}$ IFF $x_1\\equiv x_2 \\mod{4}$ AND $y_1\\equiv y_2 \\mod{4}$. $b\\equiv 2\\mod{4}$ in all other situations. $\\textbf{Key Idea:}$ Turn fence post $(x,y)$ into $(x\\mod{4},y\\mod{4})$. Writing the area of a triangle via the shoelace formula, it becomes obvious that the area mod 4 won't change when the coordinates are modded by 4. Additionally, by our work above, $B$ (the sum of the boundary counts for the 3 sides of the triangle) is entirely dependent on the coordinates mod 4. Let cnt[x][y] be an array counting the number of points that fall into each category based on the key idea above. Since all coordinates are even, only 4 elements in the $cnt$ array will be nonzero. We can fix each point of the triangle into one of the categories, quickly calculuate $A$ and $B$, and solve the problem. Be careful not to overcount triangles. The time complexity is $\\mathcal{O}(N)$, with a small constant for the counting.",
    "code": "//Written by Agnimandur (Runtime: 31ms)\n\n#include <bits/stdc++.h>\n#define ll long long\n#define REP(i,a) for (int i = 0; i < (a); i++)\nusing namespace std;\n\nint ni() {\n    int x; cin >> x;\n    return x;\n}\n \nll choose(ll n, ll k) {\n    if (n<k) return 0LL;\n    \n    if (k==2)\n        return n*(n-1)/2;\n    else\n        return n*(n-1)*(n-2)/6;\n}\n \n// number of boundary points between two points, mod 4\nint boundary(int x1, int y1, int x2, int y2) {\n    if (x1==x2&&y1==y2)\n        return 0;\n    else\n        return 2;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n \n    int N = ni();\n \n    ll cnt[2][2] = {{0,0},{0,0}};\n\n    REP(i,N) {\n        int x = ni();\n        int y = ni();\n        cnt[(x%4)/2][(y%4)/2] += 1;\n    }\n \n    ll ans = 0;\n    for (int s1 = 0; s1 < 4; s1++) {\n        for (int s2 = s1; s2 < 4; s2++) {\n            for (int s3 = s2; s3 < 4; s3++) {\n                int x1 = s1/2;\n                int y1 = s1%2;\n                int x2 = s2/2;\n                int y2 = s2%2;\n                int x3 = s3/2;\n                int y3 = s3%2;\n                int b1 = boundary(x1,y1,x2,y2);\n                int b2 = boundary(x1,y1,x3,y3);\n                int b3 = boundary(x2,y2,x3,y3);\n                int B = (b1+b2+b3)%4;\n \n                if (B==0) {\n                    if (s1==s2&&s2==s3) {\n                        ans += choose(cnt[x1][y1],3);\n                    } else if (s1==s2) {\n                        ans += choose(cnt[x1][y1],2)*cnt[x3][y3];\n                    } else if (s2==s3) {\n                        ans += choose(cnt[x2][y2],2)*cnt[x1][y1];\n                    } else {\n                        ans += cnt[x1][y1]*cnt[x2][y2]*cnt[x3][y3];\n                    }\n                }\n            }\n        }\n    }\n    cout << ans << '\n';\n}",
    "tags": [
      "bitmasks",
      "geometry",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1548",
    "index": "D2",
    "title": "Gregor and the Odd Cows (Hard)",
    "statement": "{This is the hard version of the problem. The only difference from the easy version is that in this version the coordinates can be \\textbf{both} odd and even.}\n\nThere are $n$ fence-posts at distinct coordinates on a plane. It is guaranteed that no three fence posts lie on the same line.\n\nThere are an infinite number of cows on the plane, one at every point with integer coordinates.\n\nGregor is a member of the Illuminati, and wants to build a triangular fence, connecting $3$ distinct existing fence posts. A cow \\textbf{strictly} inside the fence is said to be enclosed. If there are an \\textbf{odd} number of enclosed cows and the area of the fence is an \\textbf{integer}, the fence is said to be interesting.\n\nFind the number of interesting fences.",
    "tutorial": "Solve the easy version of the problem. Taking each coordinate modulo 4 no longer works. This is because if $\\Delta{x}$ or $\\Delta{y}$ are odd, there's no way to predict whether the boundary count (see editorial of the easy version) is 1 or 3 mod 4. By playing with Pick's Theorem, you should find that $B$ (the total number of boundary points) has to be even. Let $b_1$, $b_2$, and $b_3$ be the boundary count of the three sides of a lattice triangle. Lets count the answer. Fix a point. Fix the boundary count mod 4 of the two sides adjacent to that point. Fix more things. In Hint 4, we fixed a point. It's critical that you fix the boundary count of the side opposite that point to be even. First read (and understand!) the editorial for the easy version of the problem. Definition: The $\\textbf{modularity}$ of a point (x,y) is (x%4,y%4). Definition: The $\\textbf{boundary count}$ of a segment is the number of lattice points on that segment, minus 1. Lets precompute the array cnt[i][x][y][b] (dimensions $N\\times 4\\times 4\\times 4$), which equals the number of other points respective to points[i] with modularity $(x,y)$ and with a boundary count mod 4 equal to $b$. This precomputation can be done in $\\mathcal{O}(N^2 \\log{10^7})$ time, by iterating over every pair of points. The boundary count of the segment $(x_1,y_1)$ to $(x_2,y_2)$ is $\\gcd{(|x_2-x_1|,|y_2-y_1|)}$. Consider the number of boundary points on the three sides of a triangle, and call them $b_1,b_2,b_3$. Clearly, $B=b_1+b_2+b_3$. The key idea is that since $B$ is even, wlog we can assume that $b_3$ is even, and that $b_1 \\equiv b_2 \\mod{2}$. The other key idea is that it is easy to figure out if the boundary count is congruent to 0 or 2 mod 4 based on the modularities of the coordinates alone, but it's impossible if the boundary count is odd. Let's fix a point, and count the number of triangles that involve this point. Let's also iterate over all the relevant modularities of the other two points in the triangle, which range from $(0,0)$ up to $(3,3)$. Let's also make sure that there are an even number of boundary points on the side opposite the fixed point, which we know almost nothing about. It can be shown that $b_3 \\equiv 0\\mod{4}$ IFF $(x_1,y_1)=(x_2,y_2)$, and that $b_3 \\equiv 2\\mod{4}$ IFF $x_1,x_2$ have the same parity, and $y_1,y_2$ have the same parity, and the previous case doesn't apply. Finally, make sure that the parity of the boundary count of the two sides next to the fixed point are the same. Using the precomputed array $cnt$ and the formula for $b_3$, we can quickly find $B$ in this case. Using the Shoelace Formula, we can quickly find what $A$ is modulo 4. If $A$ is even and equal to $B$, then we know that $I$ must be odd (in the easy version of the problem, we found that $A \\equiv B \\mod{4}$ IFF $I$ is odd), so all triangles in this class are interesting. Thus, we add to the answer a number roughly equal to $cnt[i][x_1][y_1][b_1]\\cdot cnt[i][x_2][y_2][b_2]$ (it could be lower due to the potential overcount, if two points fall into the same bucket of the array). Lastly, be sure not to overcount triangles! In my code, I count each of the EEE triangles ($b_1,b_2,b_3$ all even) 3 times, and the OOE triangles once. The time complexity is $\\mathcal{O}(N^2 \\log{10^7})$ (the main part of the solution is approximately $\\mathcal{O}(512N)$). Implementation Note: The bottleneck of the algorithm is computing the GCDs. The simplest optimization that is sufficient for AC is to only calculate $\\frac{N^2}{2}$ GCDs instead of all $N^2$ (since the GCD is commutative). Java requires additional optimizations, such as precomputing small GCDs.",
    "code": "//Written by Agnimandur (Runtime: 2886ms)\n\n#include <bits/stdc++.h>\n \n#define ll long long\n#define sz(x) ((int) (x).size())\n#define all(x) (x).begin(), (x).end()\n#define vi vector<int>\n#define vl vector<long long>\n#define pii pair<int, int>\n#define pll pair<ll,ll>\n#define REP(i,a) for (int i = 0; i < (a); i++)\n#define add push_back\nusing namespace std;\n \nint ni() {\n    int x; cin >> x;\n    return x;\n}\n \nll nl() {\n    ll x; cin >> x;\n    return x;\n}\n \ndouble nd() {\n    double x; cin >> x;\n    return x;\n}\n \nstring next() {\n    string x; cin >> x;\n    return x;\n}\n \n \nll area(ll x1, ll y1, ll x2, ll y2, ll x3, ll y3) {\n    return abs(x1*y2+x2*y3+x3*y1-x2*y1-x3*y2-x1*y3)&3;\n}\n \nll boundary(ll x1, ll y1, ll x2, ll y2) {\n    return __gcd(abs(x1-x2),abs(y1-y2))&3;\n}\n \n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n \n    int N = ni();\n \n    vector<pll> nums;\n    vector<pii> mods;\n    REP(i,N) {\n        ll x = nl();\n        ll y = nl();\n        nums.add({x,y});\n        mods.add({(int)(x&3),(int)(y&3)});\n    }\n \n    const int MAX_N = 6000;\n \n    int cnt[MAX_N][4][4][4] = {0};\n    for (int i = 0; i < N; i++) {\n        for (int j = i+1; j < N; j++) {\n            int b = (int)boundary(nums[i].first,nums[i].second,nums[j].first,nums[j].second);\n            cnt[i][mods[j].first][mods[j].second][b] += 1;\n            cnt[j][mods[i].first][mods[i].second][b] += 1;\n        }\n    }\n \n    ll eee = 0;\n    ll ooe = 0;\n    for (int i = 0; i < N; i++) {\n        for (int b1 = 0; b1 < 4; b1++) {\n            for (int b2 = b1; b2 < 4; b2 += 2) {\n                for (int s1 = 0; s1 < 16; s1++) {\n                    int firsts2 = (b1<b2) ? 0 : s1;\n                    for (int s2 = firsts2; s2 < 16; s2++) {\n                        int x1 = s1/4;\n                        int y1 = s1%4;\n                        int x2 = s2/4;\n                        int y2 = s2%4;\n                        if (x1%2 != x2%2 || y1%2 != y2%2) continue;\n \n                        int b3;\n                        int triangles;\n                        if (x1==x2 && y1==y2) {\n                            b3 = 0;\n                            if (b1==b2)\n                                triangles = cnt[i][x1][y1][b1]*(cnt[i][x1][y1][b2]-1)/2;\n                            else\n                                triangles = cnt[i][x1][y1][b1]*cnt[i][x1][y1][b2];\n                        } else {\n                            b3 = 2;\n                            triangles = cnt[i][x1][y1][b1]*cnt[i][x2][y2][b2];\n                        }\n                        int B = (b1+b2+b3)%4;\n                        if (area(nums[i].first,nums[i].second,x1,y1,x2,y2) == B) {\n                            if (b1%2==0&&b2%2==0)\n                                eee += triangles;\n                            else\n                                ooe += triangles;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    ll ans = eee/3+ooe;\n    cout << ans << '\n';\n}",
    "tags": [
      "brute force",
      "geometry",
      "math",
      "number theory"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1548",
    "index": "E",
    "title": "Gregor and the Two Painters",
    "statement": "Two painters, Amin and Benj, are repainting Gregor's living room ceiling! The ceiling can be modeled as an $n \\times m$ grid.\n\nFor each $i$ between $1$ and $n$, inclusive, painter Amin applies $a_i$ layers of paint to the entire $i$-th row. For each $j$ between $1$ and $m$, inclusive, painter Benj applies $b_j$ layers of paint to the entire $j$-th column. Therefore, the cell $(i,j)$ ends up with $a_i+b_j$ layers of paint.\n\nGregor considers the cell $(i,j)$ to be badly painted if $a_i+b_j \\le x$. Define a badly painted region to be a \\textbf{maximal} connected component of badly painted cells, i. e. a connected component of badly painted cells such that all adjacent to the component cells are not badly painted. Two cells are considered adjacent if they share a side.\n\nGregor is appalled by the state of the finished ceiling, and wants to know the number of badly painted regions.",
    "tutorial": "For simplicity let's assume that all $a_i$ are distinct (and similarly, all $b_j$). If this is not the case, we may break ties arbitrarily. Say that two badly painted cells are directly reachable from each other if they are in the same row or column and all cells in between them are also badly painted. Also, define the value of the cell at $(i,j)$ to be $a_i+b_j$. Call a badly painted cell a $\\textbf{representative}$ if no cell directly reachable from it has a smaller value than it. $\\textbf{Claim:}$ Every connected component of badly painted cells contains exactly one representative. $\\textbf{Proof:}$ Clearly every connected component contains at least one representative; consider the cell(s) with the minimum value contained within it. To show that every connected component contains \\textit{exactly} one representative, suppose that we are given a representative $(i,j)$ that is directly reachable from $(i',j)$ for all $i_l\\le i'\\le i_r$ and $(i,j')$ for all $j_l\\le j'\\le j_r$, where $a_i=\\min_{i_l\\le i'\\le i_r}(a_{i'})$ and $b_j=\\min_{j_l\\le j'\\le j_r}(b_{j'})$. Then the connected component containing $(i,j)$ is completely contained within the rectangle $[i_l,i_r]\\times [j_l,j_r]$, and $(i,j)$ is the unique cell with the minimum value within that rectangle. This implies that a representative is always the unique cell with the minimum value within its connected component. It remains to count the number of representatives. For each $i$, let $lo_i$ be the maximum index less than $hi_i$ such that $a_{lo_i}<a_i$ and $hi_i$ be the minimum index greater than $i$ such that $a_{hi_i}<a_i$. Then define $na_i$ to be $\\min(\\max_{i'\\in [lo_i,i]}a_{i'},\\max_{i'\\in [i,hi_i]}a_{i'})$. Any path from a cell in row $i$ to a cell in the same column with lower value must pass through a row with value at least $na_i$. Define $nb_j$ for each $j$ similarly. It can be shown that $(i,j)$ is a representative if and only if the following conditions hold: $a_i+b_j\\le X$ $na_i+b_j>X$ $a_i+nb_j>X$ Computing $na$ and $nb$ can be done in $\\mathcal{O}(N\\log N+M\\log M)$ with any data structure supporting range min/max queries (e.g. sparse tables), or in $O(N+M)$ with a stack. It remains to count the number of pairs $(i,j)$ that satisfy these conditions given $a$, $na$, $b$, and $nb$. First initialize two binary indexed trees $T_a$ and $T_b$. Then sort the pairs $(na_i-a_i,a_i),(nb_j-b_j,b_j)$ in decreasing order. Now for every pair in the order, if it is of the form $(na_i-a_i,a_i)$, then add to the answer the number of elements of $T_b$ that are in the range $(X-na_i,X-a_i]$, and add $a_i$ to $T_a$. The reasoning for the case $(nb_j-b_j,b_j)$ is similar (query $T_a$, update $T_b$). The time complexity is $\\mathcal{O}(N\\log{N}+M\\log{M})$ for sorting the pairs and working with the two BITs.",
    "code": "//Written by Benq (Runtime: 187ms)\n\n#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nusing db = long double; // or double, if TL is tight\nusing str = string; // yay python!\n \nusing pi = pair<int,int>;\nusing pl = pair<ll,ll>;\nusing pd = pair<db,db>;\n \nusing vi = vector<int>;\nusing vb = vector<bool>;\nusing vl = vector<ll>;\nusing vd = vector<db>; \nusing vs = vector<str>;\nusing vpi = vector<pi>;\nusing vpl = vector<pl>; \nusing vpd = vector<pd>;\n \n#define tcT template<class T\n#define tcTU tcT, class U\n// ^ lol this makes everything look weird but I'll try it\ntcT> using V = vector<T>; \ntcT, size_t SZ> using AR = array<T,SZ>; \ntcT> using PR = pair<T,T>;\n \n// pairs\n#define mp make_pair\n#define f first\n#define s second\n \n// vectors\n// oops size(x), rbegin(x), rend(x) need C++17\n#define sz(x) int((x).size())\n#define bg(x) begin(x)\n#define all(x) bg(x), end(x)\n#define rall(x) x.rbegin(), x.rend() \n#define sor(x) sort(all(x)) \n#define rsz resize\n#define ins insert \n#define ft front()\n#define bk back()\n#define pb push_back\n#define eb emplace_back \n#define pf push_front\n#define rtn return\n \n#define lb lower_bound\n#define ub upper_bound \ntcT> int lwb(V<T>& a, const T& b) { return int(lb(all(a),b)-bg(a)); }\n \n// loops\n#define FOR(i,a,b) for (int i = (a); i < (b); ++i)\n#define F0R(i,a) FOR(i,0,a)\n#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)\n#define R0F(i,a) ROF(i,0,a)\n#define rep(a) F0R(_,a)\n#define each(a,x) for (auto& a: x)\n \nconst int MOD = 1e9+7; // 998244353;\nconst int MX = 2e5+5;\nconst ll INF = 1e18; // not too close to LLONG_MAX\nconst db PI = acos((db)-1);\nconst int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1}; // for every grid problem!!\nmt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count()); \ntemplate<class T> using pqg = priority_queue<T,vector<T>,greater<T>>;\n \n// bitwise ops\n// also see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html\nconstexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set\nconstexpr int bits(int x) { // assert(x >= 0); // make C++11 compatible until USACO updates ...\n\treturn x == 0 ? 0 : 31-__builtin_clz(x); } // floor(log2(x)) \nconstexpr int p2(int x) { return 1<<x; }\nconstexpr int msk2(int x) { return p2(x)-1; }\n \nll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up\nll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down\n \ntcT> bool ckmin(T& a, const T& b) {\n\treturn b < a ? a = b, 1 : 0; } // set a = min(a,b)\ntcT> bool ckmax(T& a, const T& b) {\n\treturn a < b ? a = b, 1 : 0; }\n \ntcTU> T fstTrue(T lo, T hi, U f) {\n\thi ++; assert(lo <= hi); // assuming f is increasing\n\twhile (lo < hi) { // find first index such that f is true \n\t\tT mid = lo+(hi-lo)/2;\n\t\tf(mid) ? hi = mid : lo = mid+1; \n\t} \n\treturn lo;\n}\ntcTU> T lstTrue(T lo, T hi, U f) {\n\tlo --; assert(lo <= hi); // assuming f is decreasing\n\twhile (lo < hi) { // find first index such that f is true \n\t\tT mid = lo+(hi-lo+1)/2;\n\t\tf(mid) ? lo = mid : hi = mid-1;\n\t} \n\treturn lo;\n}\ntcT> void remDup(vector<T>& v) { // sort and remove duplicates\n\tsort(all(v)); v.erase(unique(all(v)),end(v)); }\ntcTU> void erase(T& t, const U& u) { // don't erase\n\tauto it = t.find(u); assert(it != end(t));\n\tt.erase(it); } // element that doesn't exist from (multi)set\n \n#define tcTUU tcT, class ...U\n \ninline namespace Helpers {\n\t//////////// is_iterable\n\t// https://stackoverflow.com/questions/13830158/check-if-a-variable-type-is-iterable\n\t// this gets used only when we can call begin() and end() on that type\n\ttcT, class = void> struct is_iterable : false_type {};\n\ttcT> struct is_iterable<T, void_t<decltype(begin(declval<T>())),\n\t                                  decltype(end(declval<T>()))\n\t                                 >\n\t                       > : true_type {};\n\ttcT> constexpr bool is_iterable_v = is_iterable<T>::value;\n \n\t//////////// is_readable\n\ttcT, class = void> struct is_readable : false_type {};\n\ttcT> struct is_readable<T,\n\t        typename std::enable_if_t<\n\t            is_same_v<decltype(cin >> declval<T&>()), istream&>\n\t        >\n\t    > : true_type {};\n\ttcT> constexpr bool is_readable_v = is_readable<T>::value;\n \n\t//////////// is_printable\n\t// // https://nafe.es/posts/2020-02-29-is-printable/\n\ttcT, class = void> struct is_printable : false_type {};\n\ttcT> struct is_printable<T,\n\t        typename std::enable_if_t<\n\t            is_same_v<decltype(cout << declval<T>()), ostream&>\n\t        >\n\t    > : true_type {};\n\ttcT> constexpr bool is_printable_v = is_printable<T>::value;\n}\n \ninline namespace Input {\n\ttcT> constexpr bool needs_input_v = !is_readable_v<T> && is_iterable_v<T>;\n\ttcTUU> void re(T& t, U&... u);\n\ttcTU> void re(pair<T,U>& p); // pairs\n \n\t// re: read\n\ttcT> typename enable_if<is_readable_v<T>,void>::type re(T& x) { cin >> x; } // default\n\ttcT> void re(complex<T>& c) { T a,b; re(a,b); c = {a,b}; } // complex\n\ttcT> typename enable_if<needs_input_v<T>,void>::type re(T& i); // ex. vectors, arrays\n\ttcTU> void re(pair<T,U>& p) { re(p.f,p.s); }\n\ttcT> typename enable_if<needs_input_v<T>,void>::type re(T& i) {\n\t\teach(x,i) re(x); }\n\ttcTUU> void re(T& t, U&... u) { re(t); re(u...); } // read multiple\n \n\t// rv: resize and read vectors\n\tvoid rv(size_t) {}\n\ttcTUU> void rv(size_t N, V<T>& t, U&... u);\n\ttemplate<class...U> void rv(size_t, size_t N2, U&... u);\n\ttcTUU> void rv(size_t N, V<T>& t, U&... u) {\n\t\tt.rsz(N); re(t);\n\t\trv(N,u...); }\n\ttemplate<class...U> void rv(size_t, size_t N2, U&... u) {\n\t\trv(N2,u...); }\n \n\t// dumb shortcuts to read in ints\n\tvoid decrement() {} // subtract one from each\n\ttcTUU> void decrement(T& t, U&... u) { --t; decrement(u...); }\n\t#define ints(...) int __VA_ARGS__; re(__VA_ARGS__);\n\t#define int1(...) ints(__VA_ARGS__); decrement(__VA_ARGS__);\n}\n \ninline namespace ToString {\n\ttcT> constexpr bool needs_output_v = !is_printable_v<T> && is_iterable_v<T>;\n \n\t// ts: string representation to print\n\ttcT> typename enable_if<is_printable_v<T>,str>::type ts(T v) {\n\t\tstringstream ss; ss << fixed << setprecision(15) << v;\n\t\treturn ss.str(); } // default\n\ttcT> str bit_vec(T t) { // bit vector to string\n\t\tstr res = \"{\"; F0R(i,sz(t)) res += ts(t[i]);\n\t\tres += \"}\"; return res; }\n\tstr ts(V<bool> v) { return bit_vec(v); }\n\ttemplate<size_t SZ> str ts(bitset<SZ> b) { return bit_vec(b); } // bit vector\n\ttcTU> str ts(pair<T,U> p); // pairs\n\ttcT> typename enable_if<needs_output_v<T>,str>::type ts(T v); // vectors, arrays\n\ttcTU> str ts(pair<T,U> p) { return \"(\"+ts(p.f)+\", \"+ts(p.s)+\")\"; }\n\ttcT> typename enable_if<is_iterable_v<T>,str>::type ts_sep(T v, str sep) {\n\t\t// convert container to string w/ separator sep\n\t\tbool fst = 1; str res = \"\";\n\t\tfor (const auto& x: v) {\n\t\t\tif (!fst) res += sep;\n\t\t\tfst = 0; res += ts(x);\n\t\t}\n\t\treturn res;\n\t}\n\ttcT> typename enable_if<needs_output_v<T>,str>::type ts(T v) {\n\t\treturn \"{\"+ts_sep(v,\", \")+\"}\"; }\n \n\t// for nested DS\n\ttemplate<int, class T> typename enable_if<!needs_output_v<T>,vs>::type \n\t  ts_lev(const T& v) { return {ts(v)}; }\n\ttemplate<int lev, class T> typename enable_if<needs_output_v<T>,vs>::type \n\t  ts_lev(const T& v) {\n\t\tif (lev == 0 || !sz(v)) return {ts(v)};\n\t\tvs res;\n\t\tfor (const auto& t: v) {\n\t\t\tif (sz(res)) res.bk += \",\";\n\t\t\tvs tmp = ts_lev<lev-1>(t);\n\t\t\tres.ins(end(res),all(tmp));\n\t\t}\n\t\tF0R(i,sz(res)) {\n\t\t\tstr bef = \" \"; if (i == 0) bef = \"{\";\n\t\t\tres[i] = bef+res[i];\n\t\t}\n\t\tres.bk += \"}\";\n\t\treturn res;\n\t}\n}\n \ninline namespace Output {\n\ttemplate<class T> void pr_sep(ostream& os, str, const T& t) { os << ts(t); }\n\ttemplate<class T, class... U> void pr_sep(ostream& os, str sep, const T& t, const U&... u) {\n\t\tpr_sep(os,sep,t); os << sep; pr_sep(os,sep,u...); }\n\t// print w/ no spaces\n\ttemplate<class ...T> void pr(const T&... t) { pr_sep(cout,\"\",t...); } \n\t// print w/ spaces, end with newline\n\tvoid ps() { cout << \"\n\"; }\n\ttemplate<class ...T> void ps(const T&... t) { pr_sep(cout,\" \",t...); ps(); } \n\t// debug to cerr\n\ttemplate<class ...T> void dbg_out(const T&... t) {\n\t\tpr_sep(cerr,\" | \",t...); cerr << endl; }\n\tvoid loc_info(int line, str names) {\n\t\tcerr << \"Line(\" << line << \") -> [\" << names << \"]: \"; }\n\ttemplate<int lev, class T> void dbgl_out(const T& t) {\n\t\tcerr << \"\n\n\" << ts_sep(ts_lev<lev>(t),\"\n\") << \"\n\" << endl; }\n\t#ifdef LOCAL\n\t\t#define dbg(...) loc_info(__LINE__,#__VA_ARGS__), dbg_out(__VA_ARGS__)\n\t\t#define dbgl(lev,x) loc_info(__LINE__,#x), dbgl_out<lev>(x)\n\t#else // don't actually submit with this\n\t\t#define dbg(...) 0\n\t\t#define dbgl(lev,x) 0\n\t#endif\n}\n \ninline namespace FileIO {\n\tvoid setIn(str s)  { freopen(s.c_str(),\"r\",stdin); }\n\tvoid setOut(str s) { freopen(s.c_str(),\"w\",stdout); }\n\tvoid setIO(str s = \"\") {\n\t\tcin.tie(0)->sync_with_stdio(0); // unsync C / C++ I/O streams\n\t\t// cin.exceptions(cin.failbit);\n\t\t// throws exception when do smth illegal\n\t\t// ex. try to read letter into int\n\t\tif (sz(s)) setIn(s+\".in\"), setOut(s+\".out\"); // for old USACO\n\t}\n}\n/**\n * Description: range sum queries and point updates for $$$D$$$ dimensions\n * Source: https://codeforces.com/blog/entry/64914\n * Verification: SPOJ matsum\n * Usage: \texttt{BIT<int,10,10>} gives 2D BIT\n * Time: O((\\log N)^D)\n */\n \ntemplate <class T, int ...Ns> struct BIT {\n\tT val = 0; void upd(T v) { val += v; }\n\tT query() { return val; }\n};\ntemplate <class T, int N, int... Ns> struct BIT<T, N, Ns...> {\n\tBIT<T,Ns...> bit[N+1];\n\ttemplate<typename... Args> void upd(int pos, Args... args) { assert(pos > 0);\n\t\tfor (; pos<=N; pos+=pos&-pos) bit[pos].upd(args...); }\n\ttemplate<typename... Args> T sum(int r, Args... args) {\n\t\tT res=0; for (;r;r-=r&-r) res += bit[r].query(args...); \n\t\treturn res; }\n\ttemplate<typename... Args> T query(int l, int r, Args... \n\t\targs) { \n\t\tl = max(l,1); r = max(r,0);\n\t\treturn sum(r,args...)-sum(l-1,args...); }\n}; \n \n/**\n * Description: 1D range minimum query. Can also do queries \n \t* for any associative operation in $$$O(1)$$$ with D\\&C\n * Source: KACTL\n * Verification: \n\t* https://cses.fi/problemset/stats/1647/\n\t* http://wcipeg.com/problem/ioi1223\n\t* https://pastebin.com/ChpniVZL\n * Memory: O(N\\log N)\n * Time: O(1)\n */\n \ntemplate<class T> struct RMQ { // floor(log_2(x))\n\tint level(int x) { return 31-__builtin_clz(x); } \n\tvector<T> v; vector<vi> jmp;\n\tint comb(int a, int b) { // index of min\n\t\treturn v[a]==v[b]?min(a,b):(v[a]>v[b]?a:b); } \n\tvoid init(const vector<T>& _v) {\n\t\tv = _v; jmp = {vi(sz(v))}; iota(all(jmp[0]),0);\n\t\tfor (int j = 1; 1<<j <= sz(v); ++j) {\n\t\t\tjmp.pb(vi(sz(v)-(1<<j)+1));\n\t\t\tF0R(i,sz(jmp[j])) jmp[j][i] = comb(jmp[j-1][i],\n\t\t\t\t\t\t\t\t\tjmp[j-1][i+(1<<(j-1))]);\n\t\t}\n\t}\n\tint index(int l, int r) { // get index of min element\n\t\tassert(l <= r);\n\t\tint d = level(r-l+1);\n\t\treturn comb(jmp[d][l],jmp[d][r-(1<<d)+1]); }\n\tT query(int l, int r) { return v[index(l,r)]; }\n};\n \nBIT<int,MX> B[2];\n \nvi getNeed(vpi v) {\n\tvi need(sz(v),MOD);\n\tRMQ<pi> RA; RA.init(v);\n\t{\n\t\tvi st;\n\t\tF0R(i,sz(v)) {\n\t\t\twhile (sz(st) && v[st.bk] > v[i]) st.pop_back();\n\t\t\tif (sz(st)) ckmin(need[i],RA.query(st.bk,i).f);\n\t\t\tst.pb(i);\n\t\t}\n\t}\n\t{\n\t\tvi st;\n\t\tR0F(i,sz(v)) {\n\t\t\twhile (sz(st) && v[st.bk] > v[i]) st.pop_back();\n\t\t\tif (sz(st)) ckmin(need[i],RA.query(i,st.bk).f);\n\t\t\tst.pb(i);\n\t\t}\n\t}\n\treturn need;\n}\n \nint main() {\n\tsetIO(); \n\tint N,M,X; re(N,M,X);\n\tvpi a(N), b(M);\n\tF0R(i,N) {\n\t\tre(a[i].f), a[i].s = i;\n\t}\n\tF0R(i,M) re(b[i].f), b[i].s = i;\n\t// dbg(\"READ\");\n\tvi na = getNeed(a), nb = getNeed(b);\n\tdbg(na);\n\tdbg(nb);\n\tV<AR<int,3>> ival;\n\tF0R(i,N) ival.pb({na[i]-a[i].f,a[i].f,0});\n\tF0R(i,M) ival.pb({nb[i]-b[i].f,b[i].f,1});\n\tsort(rall(ival));\n\tll ans = 0;\n\teach(t,ival) {\n\t\t// dbg(t);\n\t\tans += B[t[2]^1].query(X-t[0]-t[1]+1,X-t[1]);\n\t\tB[t[2]].upd(t[1],1);\n\t}\n\tps(ans);\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1549",
    "index": "A",
    "title": "Gregor and Cryptography",
    "statement": "Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them.\n\nGregor's favorite \\textbf{prime} number is $P$. Gregor wants to find two bases of $P$. Formally, Gregor is looking for two integers $a$ and $b$ which satisfy both of the following properties.\n\n- $P \\bmod a = P \\bmod b$, where $x \\bmod y$ denotes the remainder when $x$ is divided by $y$, and\n- $2 \\le a < b \\le P$.\n\nHelp Gregor find two bases of his favorite prime number!",
    "tutorial": "Fix $a$ into a convenient constant. Since $P \\ge 5$ and is also a prime number, we know that $P-1$ is an even composite number. A even composite number is guaranteed to have at least 2 unique divisors greater than 1. Let two of these divisors be $a$ and $b$. It is guaranteed that $P\\mod{a} = P\\mod{b} = 1$, and thus this selection is valid. For example, we can simply pick $a=2$ and $b=P-1$, and we will get a correct solution. The time complexity is $\\mathcal{O}(Q)$.",
    "code": "//Written by penguinhacker (Runtime: 15ms)\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tint t;\n\tcin >> t;\n\twhile(t--) {\n\t\tint p;\n\t\tcin >> p;\n\t\tcout << \"2 \" << p-1 << \"\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1549",
    "index": "B",
    "title": "Gregor and the Pawn Game",
    "statement": "There is a chessboard of size $n$ by $n$. The square in the $i$-th row from top and $j$-th column from the left is labelled $(i,j)$.\n\nCurrently, Gregor has some pawns in the $n$-th row. There are also enemy pawns in the $1$-st row. On one turn, Gregor moves one of \\textbf{his} pawns. A pawn can move one square up (from $(i,j)$ to $(i-1,j)$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $(i,j)$ to either $(i-1,j-1)$ or $(i-1,j+1)$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.\n\nGregor wants to know what is the maximum number of his pawns that can reach row $1$?\n\nNote that only Gregor takes turns in this game, and \\textbf{the enemy pawns never move}. Also, when Gregor's pawn reaches row $1$, it is stuck and cannot make any further moves.",
    "tutorial": "There a very limited number of squares where each of Gregor's pawns could end up. Identify a greedy strategy to maximize the answer. The key insight is that due to the fact that there is only one row of enemy pawns, and those pawns never move, there are only $3$ possible columns where one of Gregor's pawns can end up in. We can solve this problem greedily, going from column $1$ to column $N$. At the current column $j$, if Gregor has a pawn in this column, then we greedily consider 3 cases. If there is an uncaptured enemy pawn in column $j-1$, mark that pawn as captured and increment the answer. Column $j-1$ will never be looked at again, so this decision is optimal. If there is no pawn in column $j$, just move Gregor's pawn forward, and increment the answer. If there is an uncaptured enemy pawn in column $j+1$, mark that pawn as captured and increment the answer. Otherwise, this pawn will not reach the first row. This greedy solution is guaranteed to produce the maximum possible answer. The time complexity is $\\mathcal{O}(N)$. Write the problem as a graph problem. Valid captures or valid forward moves represent edges in the graph. We have two sets: Gregor's pawns, and destination squares. We also have some edges between these two sets. Maximum Matching. Each of Gregor's pawns can end up in one of 3 possible squares. If Gregor has a pawn in column $i$, it can end up in column $i-1$ or $i+1$ if there is an enemy pawn in those columns. Furthermore, it can remain in column $i$ if there is no enemy pawn in that column. Let's build a graph $G$, where each edge connects one of Gregor's pawns to a valid destination cell. Since every edge goes from a cell in the bottom row to a cell in the top row, $G$ is clearly bipartite. It's now clear that moving as many pawns to the end is equivalent to finding a maximum matching in $G$. The time complexity is $\\mathcal{O}(N\\sqrt{N})$ using the HKK algorithm for maximum matching. ($G$ has at most $2N$ vertices, and $6N$ edges)",
    "code": "//Written by arvindr9 (Runtime: 31ms)\n\n#include <bits/stdc++.h>\nusing namespace std;\n \nint t;\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        string st, tt;\n        cin >> st >> tt;\n        int ans = 0;\n        vector<bool> taken(n);\n        for (int j = 0; j < n; j++) {\n            if (tt[j] == '1') {\n                for (int i = j - 1; i <= j + 1; i++) {\n                    if (i >= 0 and i < n) {\n                        if (!taken[i]) {\n                            if ((st[i] == '1' and i != j) or (st[i] == '0' and i == j)) {\n                                taken[i] = 1;\n                                ans++;\n                                break;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        cout << ans << \"\n\";\n    }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "flows",
      "graph matchings",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1550",
    "index": "A",
    "title": "Find The Array",
    "statement": "Let's call an array $a$ consisting of $n$ positive (greater than $0$) integers beautiful if the following condition is held for every $i$ from $1$ to $n$: either $a_i = 1$, or at least one of the numbers $a_i - 1$ and $a_i - 2$ exists in the array as well.\n\nFor example:\n\n- the array $[5, 3, 1]$ is beautiful: for $a_1$, the number $a_1 - 2 = 3$ exists in the array; for $a_2$, the number $a_2 - 2 = 1$ exists in the array; for $a_3$, the condition $a_3 = 1$ holds;\n- the array $[1, 2, 2, 2, 2]$ is beautiful: for $a_1$, the condition $a_1 = 1$ holds; for every other number $a_i$, the number $a_i - 1 = 1$ exists in the array;\n- the array $[1, 4]$ is not beautiful: for $a_2$, neither $a_2 - 2 = 2$ nor $a_2 - 1 = 3$ exists in the array, and $a_2 \\ne 1$;\n- the array $[2]$ is not beautiful: for $a_1$, neither $a_1 - 1 = 1$ nor $a_1 - 2 = 0$ exists in the array, and $a_1 \\ne 1$;\n- the array $[2, 1, 3]$ is beautiful: for $a_1$, the number $a_1 - 1 = 1$ exists in the array; for $a_2$, the condition $a_2 = 1$ holds; for $a_3$, the number $a_3 - 2 = 1$ exists in the array.\n\nYou are given a positive integer $s$. Find the minimum possible size of a beautiful array with the sum of elements equal to $s$.",
    "tutorial": "The maximum sum we can construct with $n$ elements is $1 + 3 + 5 + 7 + \\dots + 2n-1 = n^2$, so we need at least $\\lceil\\sqrt{s}\\rceil$ elements to construct the sum equal to $s$. Let's show how to express $s$ with exactly $\\lceil\\sqrt{s}\\rceil$ elements. Let $\\lceil\\sqrt{s}\\rceil = d$. By taking $1 + 3 + 5 + 7 + \\dots + 2d-3$, we achieve a sum of $(d-1)^2$ using $d - 1$ elements. $s - (d-1)^2$ is not less than $1$ and not greater than $2d-1$ (since $\\sqrt{(d-1)^2} = d-1$, and $\\sqrt{(d-1)^2 + 2d} > d$). Thus, we can just add $s - (d-1)^2$ to our array, and the sum becomes exactly $s$. So, the solution is to find the minimum $n$ such that $n^2 \\ge s$.",
    "code": "def maxSum(x):\n\treturn x ** 2\n\ndef getAns(x):\n\tres = 1\n\twhile maxSum(res) < x:\n\t\tres += 1\n\treturn res\n\ndef main():\n\tt = int(input())\n\tfor i in range(t):\n\t\tprint(getAns(int(input())))\n\nmain()",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1550",
    "index": "B",
    "title": "Maximum Cost Deletion",
    "statement": "You are given a string $s$ of length $n$ consisting only of the characters 0 and 1.\n\nYou perform the following operation until the string becomes empty: choose some \\textbf{consecutive} substring of \\textbf{equal} characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string {1\\textbf{111}10}, you will get the string 110. When you delete a substring of length $l$, you get $a \\cdot l + b$ points.\n\nYour task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.",
    "tutorial": "Let $l_1, l_2, \\dots, l_k$ be the length of the substring deleted at the $i$-th step. Then the number of points will be equal to $\\sum\\limits_{i=1}^{k} (a \\cdot l_i + b)$ or $a\\sum\\limits_{i=1}^{k}l_i + bk$. The sum of all $l_i$ is equal to $n$ (because in the end we deleted the entire string), so the final formula has the form $an + bk$. Obviously, for $b \\ge 0$, you should delete the characters one by one so that $k=n$. Now $b < 0$ and you have to delete the string in the minimum number of operations. Let the string $s$ consist of $m$ blocks of zeros and ones, then $\\lfloor\\frac{m}{2}\\rfloor + 1$ is the minimum number of operations for which the entire string can be deleted. As long as the number of blocks is more than $2$, we will delete the second block, the number of blocks will decrease by $2$ after each such operation (the block that we delete will disappear, and the first and third blocks will merge into one).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, a, b;\n    string s;\n    cin >> n >> a >> b >> s;\n    int m = unique(s.begin(), s.end()) - s.begin();\n    cout << n * a + max(n * b, (m / 2 + 1) * b) << '\\n'; \n  }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1550",
    "index": "C",
    "title": "Manhattan Subarrays",
    "statement": "Suppose you have two points $p = (x_p, y_p)$ and $q = (x_q, y_q)$. Let's denote the Manhattan distance between them as $d(p, q) = |x_p - x_q| + |y_p - y_q|$.\n\nLet's say that three points $p$, $q$, $r$ form a bad triple if $d(p, r) = d(p, q) + d(q, r)$.\n\nLet's say that an array $b_1, b_2, \\dots, b_m$ is good if it is impossible to choose three \\textbf{distinct} indices $i$, $j$, $k$ such that the points $(b_i, i)$, $(b_j, j)$ and $(b_k, k)$ form a bad triple.\n\nYou are given an array $a_1, a_2, \\dots, a_n$. Calculate the number of good subarrays of $a$. A subarray of the array $a$ is the array $a_l, a_{l + 1}, \\dots, a_r$ for some $1 \\le l \\le r \\le n$.\n\nNote that, according to the definition, subarrays of length $1$ and $2$ are good.",
    "tutorial": "Let's figure out criteria for the bad triple $p$, $q$, $r$. It's not hard to prove that the triple is bad, iff point $q$ lies inside the bounding box of points $p$ and $r$. In other words, if $\\min(x_p, x_r) \\le x_q \\le \\max(x_p, x_r)$ and $\\min(y_p, y_r) \\le y_q \\le \\max(y_p, y_r)$. Now, looking at points $p = (a_i, i)$, $q = (a_j, j)$ and $r = (a_k, k)$ we can see that the bad situation may arise only if $i < j < k$ - so we can check only ordered triples. Looking closely at inequality $\\min(a_i, a_k) \\le a_j \\le \\max(a_i, a_k)$ we can note that there are two situations where $(i, j, k)$ forms a bad triple: when either $a_i \\le a_j \\le a_k$ or $a_i \\ge a_j \\ge a_k$. In other words, subarray is bad if and only if it contains either non-decreasing subsequence of length $3$ or non-increasing subsequence of length $3$. The final observation is that any sequence of length at least $5$ contains either non-decreasing or non-increasing subsequence of length $3$. It's not hard to prove it, either brute-forcing all possible variants (of relative orders) on paper, or searching/remembering the theorem that says it. As a result you need to check only subarrays of length at most $4$ whichever the way you want. The complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<li, li> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nint n;\nvector<li> a;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> a[i];\n\treturn true;\n}\n\nli d(const pt &a, const pt &b) {\n\treturn abs(a.x - b.x) + abs(a.y - b.y);\n}\n\ninline void solve() {\n\tli ans = 0;\n\tfore (i, 0, n) {\n\t\tfore (j, i, n) {\n\t\t\tif (i + 2 <= j) {\n\t\t\t\tbool ok = true;\n\t\t\t\tfore (i1, i, j) fore (i2, i1 + 1, j) {\n\t\t\t\t\tif (d(pt(a[i1], i1), pt(a[j], j)) == d(pt(a[i1], i1), pt(a[i2], i2)) + d(pt(a[i2], i2), pt(a[j], j)))\n\t\t\t\t\t\tok = false;\n\t\t\t\t}\n\t\t\t\tif (!ok)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tans++;\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\n\tint t; cin >> t;\n\t\n\twhile(t--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "geometry",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1550",
    "index": "D",
    "title": "Excellent Arrays",
    "statement": "Let's call an integer array $a_1, a_2, \\dots, a_n$ good if $a_i \\neq i$ for each $i$.\n\nLet $F(a)$ be the number of pairs $(i, j)$ ($1 \\le i < j \\le n$) such that $a_i + a_j = i + j$.\n\nLet's say that an array $a_1, a_2, \\dots, a_n$ is excellent if:\n\n- $a$ is good;\n- $l \\le a_i \\le r$ for each $i$;\n- $F(a)$ is the maximum possible among all good arrays of size $n$.\n\nGiven $n$, $l$ and $r$, calculate the number of excellent arrays modulo $10^9 + 7$.",
    "tutorial": "Firstly, let's learn the structure of good array $a$ with maximum $F(a)$. Suppose, $a_i = i + k_i$, then $a_i + a_j = i + j$ $\\Leftrightarrow$ $k_i = -k_j$. In other words, we can group $a_i$ by $|k_i|$ and pairs will appear only inside each group. It's easy to prove that if the group has size $m$ then it's optimal to split it in half: one with $+k_i$ and other with $-k_i$. Then the number of pairs inside the group will be equal to $\\left\\lfloor \\frac{m}{2} \\right\\rfloor \\cdot \\left\\lceil \\frac{m}{2} \\right\\rceil$. It's also not hard to prove that in this case it's optimal to place all elements inside one group. In other words, it's optimal to make a half of all elements as $a_i = i + k$ and the other half as $a_i = i - k$ for some integer $k > 0$. Then $F(a) = \\left\\lfloor \\frac{n}{2} \\right\\rfloor \\cdot \\left\\lceil \\frac{n}{2} \\right\\rceil$. To achieve maximum $F(a)$ the excellent array should also have this structure. Let $\\mathit{half} = \\left\\lfloor \\frac{n}{2} \\right\\rfloor$. For a fixed $k$ if $n$ is even then we should choose exactly $\\mathit{half}$ positions $i$ to set as $a_i = i + k$, but if $n$ is odd, we can choose either $\\mathit{half}$ or $\\mathit{half} + 1$ positions. Let's analyze what happens with different $k$. Obviously, $k \\ge 1$. While $k \\le \\min(1 - l, r - n)$ both $i + k$ and $i - k$ are in the segment $[l, r]$ for any $i$. In this case we can choose any $a_i$ as $i + k$, so there are exactly $\\binom{n}{\\mathit{half}}$ ways for even $n$ and $\\binom{n}{\\mathit{half}} + \\binom{n}{\\mathit{half} + 1}$ ways for odd $n$. When $k > \\min(1 - l, r - n)$ then for $i \\in [1, \\mathit{lf})$ (where $\\mathit{lf} = \\max(1, l + k)$) there is only one choice - to set $a_i = i + k$. Analogically, for $i \\in (\\mathit{rg}, n]$ (where $\\mathit{rg} = \\min(n, r - k)$) there is only choice to set $a_i = i - k$. What remains is $\\mathit{rg} - \\mathit{lf} + 1$ elements without restrictions, so there are $\\binom{\\mathit{rg} - \\mathit{lf} + 1}{\\mathit{half} - (\\mathit{lf} - 1)}$ ways to choose for even $n$ or $\\binom{\\mathit{rg} - \\mathit{lf} + 1}{\\mathit{half} - (\\mathit{lf} - 1)} + \\binom{\\mathit{rg} - \\mathit{lf} + 1}{\\mathit{half} + 1 - (\\mathit{lf} - 1)}$ ways for odd $n$. Note that it's convenient to say that $\\binom{n}{k} = 0$ if $k < 0$ or $n < k$, so we don't need extra checks. Lastly, note that we can process all $k \\in [1, \\min(1 - l, r - n)]$ with one formula and there are only $O(n)$ of $k > \\min(1 - l, r - n)$ with non-zero number of ways to choose, so we can iterate over all such $k$ straightforwardly. The total complexity is $O(n \\log{\\mathit{MOD}})$ because of precomputation of factorials and inverse factorials to calculate $\\binom{n}{k}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nconst int MOD = int(1e9) + 7;\n\nint norm(int a) {\n\twhile (a >= MOD)\n\t\ta -= MOD;\n\twhile (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\nint mul(int a, int b) {\n\treturn int(a * 1ll * b % MOD);\n}\nint binPow(int a, int k) {\n\tint ans = 1;\n\twhile (k > 0) {\n\t\tif (k & 1)\n\t\t\tans = mul(ans, a);\n\t\ta = mul(a, a);\n\t\tk >>= 1;\n\t}\n\treturn ans;\n}\n\nconst int N = 200 * 1000 + 55;\nint f[N], inf[N];\n\nvoid precalc() {\n\tf[0] = inf[0] = 1;\n\tfore (i, 1, N) {\n\t\tf[i] = mul(f[i - 1], i);\n\t\tinf[i] = binPow(f[i], MOD - 2);\n\t}\n}\n\nint C(int n, int k) {\n\tif (k < 0 || n < k)\n\t\treturn 0;\n\treturn mul(f[n], mul(inf[n - k], inf[k]));\n}\n\nint n, l, r;\n\ninline bool read() {\n\tif(!(cin >> n >> l >> r))\n\t\treturn false;\n\treturn true;\n}\n\ninline void solve() {\n\tint half = n / 2;\n\tint st = min(1 - l, r - n);\n\t\n\tint ans = mul(st, C(n, half));\n\tif (n & 1)\n\t\tans = norm(ans + mul(st, C(n, half + 1)));\n\t\n\tfor (int k = st + 1; ; k++) {\n\t\tint lf = max(1, l + k);\n\t\tint rg = min(n, r - k);\n\t\t\n\t\tif (rg + 1 - lf < 0)\n\t\t\tbreak;\n\t\t\n\t\tans = norm(ans + C(rg + 1 - lf, half - (lf - 1)));\n\t\tif (n & 1)\n\t\t\tans = norm(ans + C(rg + 1 - lf, half + 1 - (lf - 1)));\n\t}\n\t\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tprecalc();\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "constructive algorithms",
      "implementation",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1550",
    "index": "E",
    "title": "Stringforces",
    "statement": "You are given a string $s$ of length $n$. Each character is either one of the first $k$ lowercase Latin letters or a question mark.\n\nYou are asked to replace every question mark with one of the first $k$ lowercase Latin letters in such a way that the following value is maximized.\n\nLet $f_i$ be the maximum length substring of string $s$, which consists entirely of the $i$-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the $i$-th letter doesn't appear in a string, then $f_i$ is equal to $0$.\n\nThe value of a string $s$ is the minimum value among $f_i$ for all $i$ from $1$ to $k$.\n\nWhat is the maximum value the string can have?",
    "tutorial": "Notice that if there are substrings of length $x$ for each letter, then there are also substrings of length $x-1$. Thus, the function on the answer is monotonous, so the binary search is applicable. Let's have some answer $x$ fixed by binary search. We have to place $k$ blocks of letters of length $x$ somewhere in a string. If we fix an order these blocks go into the string, then the greedy algorithm for placing them works. Put each block after the previous one but as far to the left as possible (the correctness can be proven by showing that picking not the furthest to the left position can't be more optimal). If there exists such an order that all blocks fit, then the answer is greater than or equal to $x$. The common transition is to move from iterating over permutations to dynamic programming over submasks. Let $dp[mask]$ be the smallest prefix of the string, such that all blocks of letters from the mask fit into this prefix. The transitions are the same: pick a new block and place it as early after that prefix as possible. So far the solution works pretty slow, since for each of $2^k$ masks we have to find the earliest possible position for a block. Let's use some precalculations to perform the transitions in $O(1)$. Notice that the transition doesn't depend on a mask, only on a length of the previous prefix. Thus, for every prefix and every letter, we can save the closest position for a block. Let $pos[i][j]$ be the closest position for a prefix of length $i$ and the $j$-th letter. $pos[i][j]$ is at least equal to $pos[i + 1][j]$. However, if the block can be placed at the $i$-th position, then it should be updated. That can happen if the closest occurrence of any letter except $j$ is not smaller than $j + x$. Thus, we can also maintain the closest occurrence of every letter. With some smart iterations, we can do the precalculations in $O(nk)$. The dynamic programming works in $O(2^k \\cdot k)$ then. Overall complexity: $O((nk + 2^k \\cdot k) \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n, k;\nstring s;\n\nbool check(int d){\n\tvector<int> lst(k, n);\n\tvector<vector<int>> pos(n + 1, vector<int>(k, n + 1));\n\tfor (int i = n - 1; i >= 0; --i){\n\t\tif (s[i] != '?'){\n\t\t\tlst[s[i] - 'a'] = i;\n\t\t}\n\t\tint cur = n;\n\t\tforn(j, k){\n\t\t\tpos[i][j] = (i + d <= cur ? i + d : pos[i + 1][j]);\n\t\t\tcur = min(cur, lst[j]);\n\t\t}\n\t\tcur = n;\n\t\tfor (int j = k - 1; j >= 0; --j){\n\t\t\tif (i + d > cur) pos[i][j] = pos[i + 1][j];\n\t\t\tcur = min(cur, lst[j]);\n\t\t}\n\t}\n\tvector<int> dp(1 << k, n + 1);\n\tdp[0] = 0;\n\tforn(mask, 1 << k) if (dp[mask] < n + 1){\n\t\tforn(i, k) if (!((mask >> i) & 1))\n\t\t\tdp[mask | (1 << i)] = min(dp[mask | (1 << i)], pos[dp[mask]][i]);\n\t}\n\treturn dp[(1 << k) - 1] <= n;\n}\n\nint main() {\n\tcin >> n >> k;\n\tcin >> s;\n\tint l = 1, r = n;\n\tint res = 0;\n\twhile (l <= r){\n\t\tint m = (l + r) / 2;\n\t\tif (check(m)){\n\t\t\tres = m;\n\t\t\tl = m + 1;\n\t\t}\n\t\telse{\n\t\t\tr = m - 1;\n\t\t}\n\t}\n\tcout << res << endl;\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "dp",
      "strings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1550",
    "index": "F",
    "title": "Jumping Around",
    "statement": "There is an infinite pond that can be represented with a number line. There are $n$ rocks in the pond, numbered from $1$ to $n$. The $i$-th rock is located at an integer coordinate $a_i$. The coordinates of the rocks are pairwise distinct. The rocks are numbered in the increasing order of the coordinate, so $a_1 < a_2 < \\dots < a_n$.\n\nA robot frog sits on the rock number $s$. The frog is programmable. It has a base jumping distance parameter $d$. There also is a setting for the jumping distance range. If the jumping distance range is set to some integer $k$, then the frog can jump from some rock to any rock at a distance from $d - k$ to $d + k$ inclusive in any direction. The distance between two rocks is an absolute difference between their coordinates.\n\nYou are assigned a task to implement a feature for the frog. Given two integers $i$ and $k$ determine if the frog can reach a rock number $i$ from a rock number $s$ performing a sequence of jumps with the jumping distance range set to $k$. The sequence can be arbitrarily long or empty.\n\nYou will be given $q$ testcases for that feature, the $j$-th testcase consists of two integers $i$ and $k$. Print \"Yes\" if the $i$-th rock is reachable and \"No\" otherwise.\n\nYou can output \"YES\" and \"NO\" in any case (for example, strings \"yEs\", \"yes\", \"Yes\" and 'YES\"' will be recognized as a positive answer).",
    "tutorial": "Notice that increasing $k$ only increases the range of the jump distances in both directions. So every rock that was reachable with some $k$, will be reachable with $k+1$ as well. Thus, let's try to find the smallest possible value of $k$ to reach each rock. Let's imagine this problem as a graph one and consider the following algorithm. For every pair of rocks, make an edge of weight equal to the smallest $k$ required to jump from one to another. For some rocks $v$ and $u$ that is $w = |d - |a_v - a_u||$. How to check the reachability with these edges? Well, if the jump range value is $k$, then there should exist of path by edges of weight no more than $k$. So we can start with an empty graph, first add the edges of the smallest weight, then the second smallest, and so on. The first time a pair of vertices becomes reachable from each other is the minimum such weight. An experienced reader can notice the resemblance with the Kruskal algorithm for finding the minimum spanning tree. After the spanning tree is constructed, the minimum $k$ is the maximum value on a path between the vertices. The issue is that Kruskal requires $O(n^2 \\log n^2)$ to construct an MST for a complete graph. Prim can make it $O(n^2)$, which is still too much. Thus, the solution is to resort to Boruvka. On each iteration of Boruvka we have to find the smallest weight edge from each component to some other one. We can solve it the following way. Maintain a sorted set of rocks coordinates. The smallest weight edges are the ones that are the closest to $d$ distance from each rock. So we could query a lower_bound of $a_i - d$ and $a_i + d$ on each rock $i$ to find them. Don't forget to look at the both sides of the lower_bound result. However, the issue is that we can bump into the rocks from the same component. Thus, let's process components one by one. When processing a component, first remove all its vertices from the set. Then query the edges for each vertex. Then add the vertices back. This way, only the edges to other components will be considered. That makes it an $O(n \\log^2 n)$ construction, with one log from the number of Boruvka iterations and another $n \\log n$ from finding the edges. That should pass if coded carefully enough, and that is basically the intended solution. Still, there exists a $O(n \\log n)$ construction. That will require a $O(n)$ algorithm for finding the edges. So there are four possible edges for each rock $i$: the closest to $a_i - d$ from the left, from the right and the same for $a_i + d$. Let's consider only the first case, the rest will be similar. The coordinates are sorted beforehand, and we are processing the rocks from left to right. We can maintain a pointer to the latest encountered rock to the left of $a_i - d$. The issue with it being from the same component is still there. Let's go around it by also storing the second latest encountered rock such that it's from the different component from the actual latest one. This can be updated in the same manner one calculates the second maximum of the array. Now you just have to do that for all four cases. This two pointers approach makes it $O(n)$ for each iteration, thus making the construction $O(n \\log n)$. Since the queries ask for a path from some fixed vertex $s$ to a certain vertex $i$, it's the same as calculating the maximum edge on a path from the root of the tree to each vertex. Can be done with a simple dfs. The only thing left is to check if the minimum possible $k$ is less than or equal to the one provided in the query. Overall complexity: $O(n \\log^2 n + q)$ or $O(n \\log n + q)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nstruct edge2{\n\tint u, w;\n};\n\nvector<vector<edge2>> g;\n\nstruct edge3{\n\tint v, u, w;\n\tedge3(){}\n\tedge3(int v, int u, int w) : v(v), u(u), w(w) {\n\t\tif (v > u) swap(v, u);\n\t}\n};\n\nbool operator <(const edge3 &a, const edge3 &b){\n\tif (a.w != b.w)\n\t\treturn a.w < b.w;\n\tif (a.v != b.v)\n\t\treturn a.v < b.v;\n\treturn a.u < b.u;\n}\n\nvector<int> p, rk;\n\nint getp(int a){\n\treturn a == p[a] ? a : p[a] = getp(p[a]);\n}\n\nbool unite(int a, int b){\n\ta = getp(a), b = getp(b);\n\tif (a == b) return false;\n\tif (rk[a] < rk[b]) swap(a, b);\n\trk[a] += rk[b];\n\tp[b] = a;\n\treturn true;\n}\n\nvector<int> mn;\n\nvoid dfs(int v, int p, int d){\n\tmn[v] = d;\n\tfor (auto e : g[v]) if (e.u != p)\n\t\tdfs(e.u, v, max(d, e.w));\n}\n\nint main() {\n\tint n, q, s, d;\n\tscanf(\"%d%d%d%d\", &n, &q, &s, &d);\n\t--s;\n\tvector<int> a(n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tp.resize(n);\n\trk.resize(n);\n\tforn(i, n) rk[i] = 1, p[i] = i;\n\tg.resize(n);\n\tint cnt = n;\n\tint iter = 0;\n\twhile (cnt > 1){\n\t\t++iter;\n\t\tvector<edge3> es(n, edge3(-1, -1, INF));\n\t\tint j, mn1, mn2;\n\t\tj = 0, mn1 = -1, mn2 = -1;\n\t\tforn(i, n) getp(i);\n\t\tforn(i, n){\n\t\t\twhile (j < n && a[i] - a[j] > d){\n\t\t\t\tif (mn1 == -1 || p[mn1] == p[j])\n\t\t\t\t\tmn1 = j;\n\t\t\t\telse{\n\t\t\t\t\tmn2 = mn1;\n\t\t\t\t\tmn1 = j;\n\t\t\t\t}\n\t\t\t\t++j;\n\t\t\t}\n\t\t\tif (mn1 != -1 && p[mn1] != p[i]){\n\t\t\t\tes[p[i]] = min(es[p[i]], edge3(mn1, i, abs(abs(a[i] - a[mn1]) - d)));\n\t\t\t}\n\t\t\tif (mn2 != -1 && p[mn2] != p[i]){\n\t\t\t\tes[p[i]] = min(es[p[i]], edge3(mn2, i, abs(abs(a[i] - a[mn2]) - d)));\n\t\t\t}\n\t\t}\n\t\tj = 0, mn1 = -1, mn2 = -1;\n\t\tforn(i, n){\n\t\t\twhile (j < n && a[j] - a[i] <= d){\n\t\t\t\tif (mn1 == -1 || p[mn1] == p[j])\n\t\t\t\t\tmn1 = j;\n\t\t\t\telse{\n\t\t\t\t\tmn2 = mn1;\n\t\t\t\t\tmn1 = j;\n\t\t\t\t}\n\t\t\t\t++j;\n\t\t\t}\n\t\t\tif (mn1 != -1 && p[mn1] != p[i]){\n\t\t\t\tes[p[i]] = min(es[p[i]], edge3(mn1, i, abs(abs(a[i] - a[mn1]) - d)));\n\t\t\t}\n\t\t\tif (mn2 != -1 && p[mn2] != p[i]){\n\t\t\t\tes[p[i]] = min(es[p[i]], edge3(mn2, i, abs(abs(a[i] - a[mn2]) - d)));\n\t\t\t}\n\t\t}\n\t\tj = n - 1, mn1 = -1, mn2 = -1;\n\t\tfor (int i = n - 1; i >= 0; --i){\n\t\t\twhile (j >= 0 && a[j] - a[i] > d){\n\t\t\t\tif (mn1 == -1 || p[mn1] == p[j])\n\t\t\t\t\tmn1 = j;\n\t\t\t\telse{\n\t\t\t\t\tmn2 = mn1;\n\t\t\t\t\tmn1 = j;\n\t\t\t\t}\n\t\t\t\t--j;\n\t\t\t}\n\t\t\tif (mn1 != -1 && p[mn1] != p[i]){\n\t\t\t\tes[p[i]] = min(es[p[i]], edge3(mn1, i, abs(abs(a[i] - a[mn1]) - d)));\n\t\t\t}\n\t\t\tif (mn2 != -1 && p[mn2] != p[i]){\n\t\t\t\tes[p[i]] = min(es[p[i]], edge3(mn2, i, abs(abs(a[i] - a[mn2]) - d)));\n\t\t\t}\n\t\t}\n\t\tj = n - 1, mn1 = -1, mn2 = -1;\n\t\tfor (int i = n - 1; i >= 0; --i){\n\t\t\twhile (j >= 0 && a[i] - a[j] <= d){\n\t\t\t\tif (mn1 == -1 || p[mn1] == p[j])\n\t\t\t\t\tmn1 = j;\n\t\t\t\telse{\n\t\t\t\t\tmn2 = mn1;\n\t\t\t\t\tmn1 = j;\n\t\t\t\t}\n\t\t\t\t--j;\n\t\t\t}\n\t\t\tif (mn1 != -1 && p[mn1] != p[i]){\n\t\t\t\tes[p[i]] = min(es[p[i]], edge3(mn1, i, abs(abs(a[i] - a[mn1]) - d)));\n\t\t\t}\n\t\t\tif (mn2 != -1 && p[mn2] != p[i]){\n\t\t\t\tes[p[i]] = min(es[p[i]], edge3(mn2, i, abs(abs(a[i] - a[mn2]) - d)));\n\t\t\t}\n\t\t}\n\t\tfor (auto e : es) if (e.v != -1){\n\t\t\tif (unite(e.v, e.u)){\n\t\t\t\t--cnt;\n\t\t\t\tg[e.v].push_back({e.u, e.w});\n\t\t\t\tg[e.u].push_back({e.v, e.w});\n\t\t\t}\n\t\t}\n\t}\n\tmn.resize(n);\n\tdfs(s, -1, 0);\n\tforn(_, q){\n\t\tint i, k;\n\t\tscanf(\"%d%d\", &i, &k);\n\t\t--i;\n\t\tputs(mn[i] <= k ? \"Yes\" : \"No\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dp",
      "dsu",
      "graphs",
      "shortest paths"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1551",
    "index": "A",
    "title": "Polycarp and Coins",
    "statement": "Polycarp must pay \\textbf{exactly} $n$ burles at the checkout. He has coins of two nominal values: $1$ burle and $2$ burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other.\n\nThus, Polycarp wants to minimize the difference between the count of coins of $1$ burle and $2$ burles being used. Help him by determining two non-negative integer values $c_1$ and $c_2$ which are the number of coins of $1$ burle and $2$ burles, respectively, so that the total value of that number of coins is \\textbf{exactly} $n$ (i. e. $c_1 + 2 \\cdot c_2 = n$), and the absolute value of the difference between $c_1$ and $c_2$ is as little as possible (i. e. you must minimize $|c_1-c_2|$).",
    "tutorial": "Let's initialize variables $c_1$ and $c_2$ by the same value of $\\lfloor{\\frac{n}{3}}\\rfloor$. Then we need to gather additionally the remainder of dividing $n$ by $3$. If the remainder is equal to $0$, we don't need to gather anything else because the variables $c_1$ and $c_2$ have been already set to the correct answer: $|c_1 - c_2| = 0$ because $c_1 = c_2$ and no absolute value can be less than $0$. Otherwise, $|c_1 - c_2| \\neq 0$ because $c_1 = c_2$ and $n = c_1 + 2 \\times c_2 = 3 \\times c_1$ in this case, but that's impossible if $n$ isn't divisible by 3. If the remainder is equal to $1$, then we need to gather additionally $1$ burle using one coin of $1$ burle so let's increase $c_1$ by $1$. In this case, $c_1 = c_2 + 1$, hence $|c_1 - c_2| = 1$, this value cannot be less than $1$, as it was proved above. If the remainder is equal to $2$, then we need to gather additionally $2$ burles using one coin of $2$ burles so let's increase $c_2$ by $1$. In this case, $c_2 = c_1 + 1$, hence $|c_1 - c_2| = 1$, this value cannot be less than $1$. There are no other remainders of dividing by $3$ so these cases cover the whole solution.",
    "code": "for i in range(0, int(input())):\n    n = int(input())\n    c1 = n // 3;\n    c2 = c1;\n    if n % 3 == 1:\n        c1 += 1\n    elif n % 3 == 2:\n        c2 += 1\n    print(c1, c2)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1551",
    "index": "B1",
    "title": "Wonderful Coloring - 1",
    "statement": "This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1.\n\nPaul and Mary have a favorite string $s$ which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met:\n\n- each letter of the string is either painted in exactly one color (red or green) or isn't painted;\n- each two letters which are painted in the same color are different;\n- the number of letters painted in red is equal to the number of letters painted in green;\n- the number of painted letters of this coloring is \\textbf{maximum} among all colorings of the string which meet the first three conditions.\n\nE. g. consider a string $s$ equal to \"kzaaa\". One of the wonderful colorings of the string is shown in the figure.\n\n\\begin{center}\n{\\small The example of a wonderful coloring of the string \"kzaaa\".}\n\\end{center}\n\nPaul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find $k$ — the number of red (or green, these numbers are equal) letters in a wonderful coloring.",
    "tutorial": "Let's calculate the number of letters which occur exactly once in the string and letters that occur more than once - $c_1$ and $c_2$, respectively. If a letter occurs more than once, one of its occurrences may be painted in red and another one may be painted in green. We cannot paint all other occurrences because there will be two equal letters painted in one color, but this is unacceptable by the statement. So there are no more than $c_2$ occurrences of letters that occur more than once to be painted in red. Let's select $c_2$ such occurrences and paint them. We need to paint additionally the letters which occur exactly once by meeting the same conditions as we meet painting the whole string. There's no way to paint these letters and not meet the first two conditions. So we must select the maximal count of the letters so that we will be able to paint some set of remaining letters in green so that the number of red letters will be equal to the number of green letters. This number is equal to $\\lfloor \\frac{c_1}{2} \\rfloor$. So the final answer is equal to $c_2 + \\lfloor \\frac{c_1}{2} \\rfloor$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int L = 26;\nint cnt[L];\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t{\n\t\tstring s;\n\t\tcin >> s;\n\t\tmemset(cnt, 0, sizeof(cnt));\n\t\tfor (auto c : s) cnt[c - 'a']++;\n\t\tint cnt1 = 0;\n\t\tint cnt2 = 0;\n\t\tfor (int i = 0; i < L; i++)\n\t\t\tif (cnt[i] == 1)\n\t\t\t\tcnt1++;\n\t\t\telse if (cnt[i] > 0)\n\t\t\t\tcnt2++;\n\t\tcout << (cnt2 + cnt1 / 2) << endl;\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1551",
    "index": "B2",
    "title": "Wonderful Coloring - 2",
    "statement": "This problem is an extension of the problem \"Wonderful Coloring - 1\". It has quite many differences, so you should read this statement completely.\n\nRecently, Paul and Mary have found a new favorite sequence of integers $a_1, a_2, \\dots, a_n$. They want to paint it using pieces of chalk of $k$ colors. The coloring of a sequence is called wonderful if the following conditions are met:\n\n- each element of the sequence is either painted in one of $k$ colors or isn't painted;\n- each two elements which are painted in the same color are different (i. e. there's no two equal values painted in the same color);\n- let's calculate for each of $k$ colors the number of elements painted in the color — all calculated numbers must be equal;\n- the total number of painted elements of the sequence is the \\textbf{maximum} among all colorings of the sequence which meet the first three conditions.\n\nE. g. consider a sequence $a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$ and $k=3$. One of the wonderful colorings of the sequence is shown in the figure.\n\n\\begin{center}\n{\\small The example of a wonderful coloring of the sequence $a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$ and $k=3$. Note that one of the elements isn't painted.}\n\\end{center}\n\nHelp Paul and Mary to find a wonderful coloring of a given sequence $a$.",
    "tutorial": "Since we must use exactly $k$ colors, each element that occurs in the sequence may have no more than $k$ painted occurrences. Let's select for each element $x$ $min(k, cnt_x)$ its occurrences where $cnt_x$ is the number of all its occurrences in the sequence. Let $b_1, b_2, \\dots, b_m$ be a sequence of all elements that occur in the sequence $a$, but in the sequence $b$ they will occur only once. Let's create a $1$-indexed array $p$ in which we will add sequentially indices of the selected occurrences of $b_1$ in the sequence $a$, then the selected occurrences of $b_2$, and so on till $b_m$. Currently, $p$ is a set of occurrences, which wonderful coloring is a wonderful coloring of the whole sequence $a$ because if we want to paint an occurrence outside $p$, we can do it only by selecting an occurrence of the same element in $p$ which we will not paint so that no more than $k$ occurrences will be painted. We must use exactly $k$ colors and paint for each color an equal number of occurrences, hence if we want to paint all occurrences from $p$, we must remove from it the minimum number of occurrences so that the size of the array $p$ will be divided by $k$ (i. e. remove the number of occurrences equal to the remainder of dividing the size of $p$ by $k$). We can remove any occurrences, for example, let's delete it from the suffix of $p$. Currently, we can paint all occurrences from $p$ using the following rule: the occurrence $p_i$ we must paint in the color with a number $((i - 1) \\% k) + 1$ where $\\%$ takes the remainder of dividing the left operand by the right operand. So all occurrences from $p$ will be painted and all $k$ colors will be used. Since all occurrences of one element belong to one subsegment of $p$ and their number isn't greater than $k$, they will be painted in different colors. It may be so that the array $p$ before painting will be empty. In this case, the wonderful coloring of $a$ doesn't contain any painted element.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 200 * 1000 + 13;\n\nint ans[MAX_N];\nmap<int, vector<int>> indices;\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t{\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tindices.clear();\n\t\tmemset(ans, 0, n * sizeof(ans[0]));\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\tif (indices[x].size() < k)\n\t\t\t\tindices[x].push_back(i);\n\t\t}\n\t\tint m = 0;\n\t\tfor (auto e : indices) m += e.second.size();\n\t\tm -= m % k;\n\t\tint color = 0;\n\t\tfor (auto e : indices)\n\t\t\tfor (auto i : e.second)\n\t\t\t{\n\t\t\t\tans[i] = ++color;\n\t\t\t\tcolor %= k;\n\t\t\t\tif (--m == 0) goto _output;\n\t\t\t}\n\t_output:\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tcout << ans[i] << ' ';\n\t\tcout << '\\n';\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1551",
    "index": "C",
    "title": "Interesting Story",
    "statement": "Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'!\n\nTo compose a story, Stephen wrote out $n$ words consisting of the first $5$ lowercase letters of the Latin alphabet. He wants to select the \\textbf{maximum} number of \\textbf{words} to make an \\textbf{interesting} story.\n\nLet a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together.\n\nFor example, the story consisting of three words \"bac\", \"aaada\", \"e\" is interesting (the letter 'a' occurs $5$ times, all other letters occur $4$ times in total). But the story consisting of two words \"aba\", \"abcde\" is not (no such letter that it occurs more than all other letters in total).\n\nYou are given a sequence of $n$ words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output $0$.",
    "tutorial": "Let $f(s, c)$ be the number of the occurrences of the letter $c$ in the word $s$ minus the number of the occurrences of all other letters in total. Since for each two words $s_1$ and $s_2$ the number of the occurrences of a letter in the word $s_1 + s_2$ is the sum of the numbers of its occurrences in $s_1$ and $s_2$, the equality $f(s_1 + s_2, c) = f(s_1, c) + f(s_2, c)$ is true ($s_1 + s_2$ means the concatenation of $s_1$ and $s_2$). Consider a sequence of words $s_1, s_2, \\ldots, s_n$. A story consisting of words $s_{i_1}, s_{i_2}, \\ldots, s_{i_m}$ is interesting if and only if there's a letter $c$ such that $f(s_{i_1} + s_{i_2} + \\ldots + s_{i_m}, c) > 0$ - it exactly means that there's a letter which occurs more times than all other in total. So we are interested in searching for a letter $c$ such that exists a positive integer $m$ - a maximal number of words $s_{i_1}, s_{i_2}, \\ldots, s_{i_m}$ such that $\\sum\\limits_{j = 1}^{m} f(s_{i_j}, c) = f(s_{i_1} + s_{i_2} + \\ldots + s_{i_m}, c) > 0$. Suppose we have a set of words that form an interesting story and where $c$ is the letter having more occurrences than all other letters in total. Suppose we can add to it one of few words. We had better add a word $s$ such that $f(s, c)$ is maximal to be able to add more words in the future. So the problem has the following solution: for each letter $c$ of the Latin alphabet and for each word $s_i$ let's calculate $f(s, c)$. Then let's iterate over all letters $c$, take a sequence $f(s_1, c), f(s_2, c), \\ldots, f(s_n, c)$ and sort it in descending order. Let's initialize an interesting story by a set of a single word corresponding to the first element of the sequence. If there's no word $s$ such that $f(s, c) \\le 0$, then there's no non-empty interesting story containing some words of the given set. Otherwise, let's take the next elements of the sequence sequentially until the sum of $f(s, c)$ over all taken words $s$ is greater than zero. Let's select a letter such that the corresponding taken set is maximal over all letters. Finally, we should print the set's size. The solution consists of two phases: the calculation of all $f(s, c)$ (works in $O(L \\times \\sum\\limits_{i = 1}^{n} |s_i|)$ where $L$ is the alphabet's size, $|s|$ is the lengths of a string $s$) and building a maximal interesting story for each letter $c$ (sorting and a greedy algorithm - $O(L \\times n \\times \\log n)$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 2 * 100 * 1000 + 13;\nconst int L = 26;\n\nvector<int> balance[L];\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t{\n\t\tint n;\n\t\tcin >> n;\n\t\tfor (int i = 0; i < L; i++)\n\t\t\tbalance[i].clear();\n\t\tfor (int i = 1; i <= n; i++)\n\t\t{\n\t\t\tstring s;\n\t\t\tcin >> s;\n\t\t\tint initBalance = -(int)s.length();\n\t\t\tfor (int j = 0; j < L; j++)\n\t\t\t\tbalance[j].push_back(initBalance);\n\t\t\tfor (auto c : s)\n\t\t\t\tbalance[c - 'a'].back() += 2;\n\t\t}\n\t\tint bestCount = 0;\n\t\tint bestLetter = 0;\n\t\tfor (int i = 0; i < L; i++)\n\t\t{\n\t\t\tauto& b = balance[i];\n\t\t\tsort(b.begin(), b.end());\n\t\t\treverse(b.begin(), b.end());\n\t\t\tif (b[0] <= 0) continue;\n\t\t\tint sumBalance = b[0];\n\t\t\tint j = 1;\n\t\t\tfor (; j < n && sumBalance > 0; j++)\n\t\t\t\tsumBalance += b[j];\n\t\t\tif (sumBalance <= 0) j--;\n\t\t\tif (j > bestCount)\n\t\t\t{\n\t\t\t\tbestCount = j;\n\t\t\t\tbestLetter = i;\n\t\t\t}\n\t\t}\n\n\t\tcout << bestCount << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1551",
    "index": "D2",
    "title": "Domino (hard version)",
    "statement": "The only difference between this problem and D1 is that you don't have to provide the way to construct the answer in D1, but you have to do it in this problem.\n\nThere's a table of $n \\times m$ cells ($n$ rows and $m$ columns). The value of $n \\cdot m$ is even.\n\nA domino is a figure that consists of two cells having a common side. It may be horizontal (one of the cells is to the right of the other) or vertical (one of the cells is above the other).\n\nYou need to place $\\frac{nm}{2}$ dominoes on the table so that exactly $k$ of them are horizontal and all the other dominoes are vertical. The dominoes cannot overlap and must fill the whole table.",
    "tutorial": "Suppose $n$ and $m$ are even. A necessary and sufficient condition of existence of the answer is that $k$ is even. Let's prove the sufficient condition. If the count of the horizontal dominoes is even, then we can combine them and vertical dominoes to blocks of size $2 \\times 2$ (the number of the vertical dominoes is even, too, if $k$ is even). If $n$ and $m$ are even, we can fill the table with these blocks. The description of the locations of the dominoes may be printed as follows: consider the table is a chessboard where a cell is a block of two dominoes. Consider the leftmost topmost cell of the board is black. If a cell of the board is black, let's mark one of the dominoes of the block with the letter \"a\" and the other one with the letter \"b\". If a cell of the board is white, let's mark one of the dominoes of the block with the letter \"c\" and the other one with the letter \"d\". There will be no situation that some two cells of the table are marked with one letter but belong to different dominoes. Let's prove the necessary condition. The number of cells in a column ($n$) is even, so the number of cells that belong to vertical dominoes is even because cells of each vertical domino may be either belong to the column or not belong at the same time. So the number of cells that belong to horizontal dominoes is even. Let's cross out all cells that belong to vertical dominoes and let's find the leftmost column having cells that haven't been crossed out. It's the leftmost column with such cells so the pairwise cells of the non-crossed out cells belong to the column to the right of the found one. The number of such cells in the right column is equal to the number of found cells so it's even and the number of found horizontal dominoes is even, too. Let's cross out the found cells and the pairwise cells. The number of non-crossed out cells in the right column will be even. The number of crossed-out horizontal dominoes will be even, too. Let's repeat this procedure until all the dominoes will be crossed out. In every step, we have crossed out the even number of horizontal dominoes, hence the total count of horizontal dominoes is even. Suppose $n$ is odd, hence $m$ is even. In this case, every column contains an odd number of cells, whereas the number of cells that belong to vertical dominoes is even. So the number of cells that belong to horizontal dominoes is odd. Consider the leftmost column and find a cell of it that belongs to a horizontal domino (it must be found because the number of such cells is odd so it isn't equal to $0$). Let's find the pairwise cell and cross out both cells. Currently, the two columns will have an even number of non-crossed-out cells. Let's repeat the procedure until all columns will have even non-crossed-out cells. We will cross out $m$ cells and $\\frac{m}{2}$ dominoes. So the necessary condition is that the number of horizontal dominoes ($k$) is at least $\\frac{m}{2}$. Let's extend the necessary condition with the following condition: the value of $k - \\frac{m}{2}$ is even. Consider the table that we've become after the previous procedure where each column has exactly one crossed-out cell. Let's start the procedure we've done in the case of even both $n$ and $m$. The procedure can be started on our table because each column of the table has an even number of non-crossed-out cells. As a result of the procedure, we will cross out an even count of horizontal dominoes, so the value of $k - \\frac{m}{2}$ is even. Let's build an answer if the conditions $k \\ge \\frac{m}{2}$ and $k - \\frac{m}{2}$ is even are met. Let's place in the topmost row $\\frac{m}{2}$ horizontal dominoes and mark their cells as follows: the first domino will be marked with \"x\", the second one - with \"y\", the third one - with \"x\", and so on. As the result, the region of $n - 1$ rows and $m$ columns will be unfilled. Both values are even, and the value of $k - \\frac{m}{2}$ is even, too. So let's fill the region as if it's a separate table having even numbers of rows and columns. As it was proved above, it's possible to do. The set of letters used for the region and set of the letters used for the topmost row don't have common elements, so there will be no cells that are marked with one letter but belong to different dominoes. The case of odd $m$ (hence, $n$ is even) is similar to the previous one - let's transpose the table (it will have $m$ rows and $n$ columns), swap the values of $k$ and $\\frac{nm}{2} - k$, solve the case above and transpose the table back to have $n$ rows and $m$ columns.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nchar field[128][128];\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t{\n\t\tint n, m, kh;\n\t\tcin >> n >> m >> kh;\n\t\tint kv = n * m / 2 - kh;\n\t\tif (n & 1)\n\t\t{\n\t\t\tkh -= m / 2;\n\t\t\tif (kh < 0)\n\t\t\t{\n\t\t\t\tcout << \"NO\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < m / 2; i++)\n\t\t\t\tfield[n - 1][i * 2] = field[n - 1][i * 2 + 1] = ((i & 1) ? 'x' : 'y');\n\t\t}\n\t\telse if (m & 1)\n\t\t{\n\t\t\tkv -= n / 2;\n\t\t\tif (kv < 0)\n\t\t\t{\n\t\t\t\tcout << \"NO\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < n / 2; i++)\n\t\t\t\tfield[i * 2][m - 1] = field[i * 2 + 1][m - 1] = ((i & 1) ? 'x' : 'y');\n\t\t}\n\t\tif ((kh & 1) || (kv & 1))\n\t\t{\n\t\t\tcout << \"NO\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tfor(int i = 0; i < n / 2; i++)\n\t\t\tfor (int j = 0; j < m / 2; j++)\n\t\t\t{\n\t\t\t\tif (kh)\n\t\t\t\t{\n\t\t\t\t\tkh -= 2;\n\t\t\t\t\tfield[2 * i][2 * j] = field[2 * i][2 * j + 1] = (((i + j) & 1) ? 'a' : 'b');\n\t\t\t\t\tfield[2 * i + 1][2 * j] = field[2 * i + 1][2 * j + 1] = (((i + j) & 1) ? 'c' : 'd');\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfield[2 * i][2 * j] = field[2 * i + 1][2 * j] = (((i + j) & 1) ? 'a' : 'b');\n\t\t\t\t\tfield[2 * i][2 * j + 1] = field[2 * i + 1][2 * j + 1] = (((i + j) & 1) ? 'c' : 'd');\n\t\t\t\t}\n\t\t\t}\n\n\t\tcout << \"YES\\n\";\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tfield[i][m] = 0;\n\t\t\tcout << field[i] << '\\n';\n\t\t}\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1551",
    "index": "E",
    "title": "Fixed Points",
    "statement": "Consider a sequence of integers $a_1, a_2, \\ldots, a_n$. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by $1$ position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length decreases by $1$. The indices of the elements after the move are recalculated.\n\nE. g. let the sequence be $a=[3, 2, 2, 1, 5]$. Let's select the element $a_3=2$ in a move. Then after the move the sequence will be equal to $a=[3, 2, 1, 5]$, so the $3$-rd element of the new sequence will be $a_3=1$ and the $4$-th element will be $a_4=5$.\n\nYou are given a sequence $a_1, a_2, \\ldots, a_n$ and a number $k$. You need to find the minimum number of moves you have to make so that in the resulting sequence there will be \\textbf{at least} $k$ elements that are equal to their indices, i. e. the resulting sequence $b_1, b_2, \\ldots, b_m$ will contain at least $k$ indices $i$ such that $b_i = i$.",
    "tutorial": "Let's use the concept of dynamic programming. Let's create an array $dp$ ($0$-indexed) with size of $(n + 1) \\times (n + 1)$. $dp[i][j]$ will contain the maximal number of the elements equal to their indices if we have considered the first $i$ elements of the sequence $a$ and have not deleted $j$ elements. Let's fill the array with zeroes, then we will increase the elements of the array for different $i$ and $j$. Let's start the $for$-loop with parameter $i$ from $0$ to $n - 1$ and the internal one with parameter $j$ from $0$ to $i$. Consider an element $a_{i + 1}$. We can delete or not delete it. If we delete this element, the number of the elements equal to their indices will not be increased and the number of the non-deleted element will not be increased, too. It means that the answer for $dp[i + 1][j]$ may be updated with $dp[i][j]$. Since we are interested in a maximum answer, we rewrite $dp[i + 1][j]$ only if $dp[i][j]$ is greater than $dp[i + 1][j]$. Suppose we don't delete this element. We haven't deleted previously $j$ elements so $a_{i + 1}$ will have the index $(j + 1)$ and there will be $j + 1$ non-deleted elements if we consider $i + 1$ elements so we must update $dp[i + 1][j + 1]$. If $a_{i + 1} = j + 1$ (i. e. an element equal to its index is found), let's update $dp[i + 1][j + 1]$ with $dp[i][j] + 1$. Otherwise, we should update it with $dp[i][j]$. Remember that update may be done only if we rewrite the less value with the greater value. Let's build the answer as follows. We need to minimize the number of deleted elements (maximize the number of non-deleted elements) so that the number of the elements equal to their indices is at least $k$. Consider only the elements of $dp$ having the first index $i = n$. Let's start a $for$-loop in the descending order of $j$. If $dp[n][j] \\ge k$, $j$ is the maximum number of elements that we will not delete, so the answer is $n - j$. If we will not find $j$ such that $dp[n][j] \\ge k$, there's no desired sequence of moves so the answer is $-1$. The algorithm works in $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 6000;\n\nint dp[MAX_N][MAX_N];\nint a[MAX_N];\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t{\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tfor (int i = 1; i <= n; i++) cin >> a[i];\n\t\tfor (int i = 0; i <= n; i++)\n\t\t\tfor (int j = 0; j <= i; j++)\n\t\t\t\tdp[i][j] = 0;\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tfor (int j = 0; j <= i; j++)\n\t\t\t{\n\t\t\t\tdp[i + 1][j] = max(dp[i + 1][j], dp[i][j]);\n\t\t\t\tdp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + ((a[i + 1] == j + 1) ? 1 : 0));\n\t\t\t}\n\t\tint ans = -1;\n\t\tfor(int i = n; i >= 0; i--)\n\t\t\tif (dp[n][i] >= k)\n\t\t\t{\n\t\t\t\tans = n - i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcout << ans << '\\n';\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "dp"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1551",
    "index": "F",
    "title": "Equidistant Vertices",
    "statement": "A tree is an undirected connected graph without cycles.\n\nYou are given a tree of $n$ vertices. Find the number of ways to choose exactly $k$ vertices in this tree (i. e. a $k$-element subset of vertices) so that all pairwise distances between the selected vertices are equal (in other words, there exists an integer $c$ such that for all $u, v$ ($u \\ne v$, $u, v$ are in selected vertices) $d_{u,v}=c$, where $d_{u,v}$ is the distance from $u$ to $v$).\n\nSince the answer may be very large, you need to output it modulo $10^9 + 7$.",
    "tutorial": "If $k = 2$, any set of two vertices may be taken so the answer is $\\frac{n(n - 1)}{2}$ modulo $10^9 + 7$. Suppose $k \\ge 3$. Consider three vertices $A$, $B$, $C$ such that $d_{A, B} = d_{A,C} = d_{B,C}$. If this equality is true, there's a vertex $Q$ that belongs to all three paths, otherwise, either one of the vertices belongs to the path between two others or there is more than one simple path (i. e. path having distinct edges) between any of the vertices so the graph isn't a tree. Hence, the following equalities are true: $d_{A,B} = d_{A,Q} + d_{B,Q},$ $d_{A,C} = d_{A,Q} + d_{C,Q},$ $d_{B,C} = d_{B,Q} + d_{C,Q}.$ Then $d_{A,Q} + d_{B,Q} = d_{A,Q} + d_{C,Q},$ $d_{A,Q} + d_{B,Q} = d_{B,Q} + d_{C,Q},$ $d_{A,Q} + d_{C,Q} = d_{B,Q} + d_{C,Q},$ hence, $d_{A,Q} = d_{B,Q} = d_{C,Q}$. Suppose $k > 3$. Let's select vertices $A$, $B$, $C$, $D$ that is a correct desired set of four vertices, for the triple of paths $AB$, $AC$, $BC$ let's select a common vertex $Q$ and for the triple $BC$, $CD$, $BD$ - $Q'$. Because $d_{B,Q} = d_{C,Q},$ $d_{B,Q'} = d_{C,Q'}$ $Q$ is the same vertex as $Q'$. The same procedure we can do for all other pairs of triples of vertices. The situation will not be another if we add a new vertex in the set if the set will still meet the problem's conditions. So if $k \\ge 3$, a vertex $Q$ exists such that all vertices of the set are equidistant from it. Note that for each set only one such $Q$ exists. Let's iterate over all vertices taking them as $Q$ and \"hang\" the tree by $Q$. The set of $k$ vertices equidistant from $Q$ meets the problem's condition if and only if the vertices of the set are placed in different subtrees of vertices adjacent to $Q$ (in other words, the paths from them to $Q$ must intersect only in $Q$). Let's calculate the number of desired sets for a given $Q$ and a layer of equidistant vertices. Let $L_Q$ be the number of vertices adjacent to $Q$ (and it's the number of subtrees, too). Let's create an array $cnt$ ($1$-indexed) of size $L_Q$ so that the $i$-th element will contain the number of the vertices of the layer in the $i$-th subtree. For the layer of vertices adjacent to $Q$, this array will be filled with $1$. For the other layers, we can update the array as follows: let's mark $Q$ and vertices adjacent to $Q$ as used, then for every vertex of the current layer let's decrease $cnt[i]$ by $1$ if $i$ is the index of the subtree of the vertex, then let's increase $cnt[i]$ by the number of the vertices adjacent to the current one but not used. Then let's mark the vertices as used. After the iteration, the array $cnt$ will correspond to the new layer. Using the array, let's calculate the number of the desired sets of $k$ vertices using the concept of dynamic programming. Let's create an array $dp$ ($0$-indexed) of size $(L_Q + 1) \\times (k + 1)$. $dp[i][j]$ will contain a number of found sets of $j$ vertices if only $i$ subtrees have been considered. Let's fill the array with $0$ except $dp[0][0] = 1$. Let's start a $for$-loop with parameter $i$ from $0$ to $L_Q - 1$ and the internal one with parameter $j$ from $0$ to $k$. In every step, we can either take a vertex from $(i + 1)$-th subtree or take nothing. If we take a vertex from the subtree (it's possible only if $j < k$), then we have $cnt[i + 1] \\cdot dp[i][j]$ ways to select $j + 1$ vertices considering $i + 1$ subtrees so that the last vertex belongs to the $(i + 1)$-th subtree. This value we must add to $dp[i + 1][j + 1]$ that must contain all ways to select $j + 1$ vertices from $i + 1$ subtrees. If we ignore the subtree, the number of ways to select $j$ vertices from $i + 1$ subtrees ignoring the $(i + 1)$-th subtree is $dp[i][j]$. It must be added to the number of ways to select $j$ vertices from $i + 1$ subtrees - $dp[i + 1][j]$. The answer for the current $Q$ and the current layer of equidistant vertices is $dp[L_Q][k]$. The answer for the whole tree is the sum of the answers for all $Q$ and for all layers of equidistant vertices. Remember that all arithmetical operations must be done modulo $10^9 + 7$. The number of possible central vertices is $n$. For every central vertex and every layer we perform two actions: recalculate the array $cnt$ and calculate the number of the corresponding sets using the concept of dynamic programming. The recalculation of $cnt$ works in $O(L_Qk)$, it's just BFS starting from $Q$ so for every central vertex it works in O(n). The dynamic programming for the current $Q$ and the current layer works in $O(L_Qk)$, for the current $Q$ and all layers - in $O(nL_Qk)$. The summary time corresponding to the current $Q$ is $O(nL_Qk)$. The total algorithm work time is $\\sum\\limits_{Q = 1}^{n} O(nL_QK) = O(nk\\sum\\limits_{Q = 1}^{n} L_Q)$. The sum of all $L_Q$ is a total number of the adjacent vertices to all vertices, it's just a double number of edges - $2(n - 1)$. So the total work time is $O(n^2k)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 128;\n\ntypedef long long ll;\nconst ll mod = 1000 * 1000 * 1000 + 7;\n\nll add(ll x, ll y) { return (x + y) % mod; }\nll mul(ll x, ll y) { return x * y % mod; }\n\nvector<int> g[MAX_N];\nbool used[MAX_N];\nint cnt[MAX_N];\nll dp[MAX_N][MAX_N];\n\nll rundp(int m, int k)\n{\n\tfor (int i = 0; i <= m; i++)\n\t\tfor (int j = 0; j <= k; j++)\n\t\t\tdp[i][j] = 0;\n\tdp[0][0] = 1;\n\tfor (int i = 0; i < m; i++)\n\t\tfor (int j = 0; j <= k; j++)\n\t\t{\n\t\t\tdp[i + 1][j] = add(dp[i + 1][j], dp[i][j]);\n\t\t\tdp[i + 1][j + 1] = add(dp[i + 1][j + 1], mul(dp[i][j], cnt[i]));\n\t\t}\n\treturn dp[m][k];\n}\n\nvoid solve()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tfor (int i = 0; i < n; i++)\n\t\tg[i].clear();\n\tfor (int i = 1; i < n; i++)\n\t{\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tg[--a].push_back(--b);\n\t\tg[b].push_back(a);\n\t}\n\tif (k == 2)\n\t{\n\t\tcout << n * (n - 1LL) / 2 % mod << '\\n';\n\t\treturn;\n\t}\n\tll ans = 0;\n\tfor (int center = 0; center < n; center++)\n\t{\n\t\tmemset(used, 0, n);\n\t\tused[center] = true;\n\n\t\tvector<pair<int, int>> layer;\n\t\tint m = g[center].size();\n\t\tfor (int i = 0; i < m; i++)\n\t\t{\n\t\t\tint y = g[center][i];\n\t\t\tlayer.emplace_back(y, i);\n\t\t\tcnt[i] = 1;\n\t\t\tused[y] = true;\n\t\t}\n\t\twhile (!layer.empty())\n\t\t{\n\t\t\tans = add(ans, rundp(m, k));\n\t\t\tvector<pair<int, int>> newlayer;\n\t\t\tfor (auto p : layer)\n\t\t\t{\n\t\t\t\tcnt[p.second]--;\n\t\t\t\tfor (auto y : g[p.first])\n\t\t\t\t\tif (!used[y])\n\t\t\t\t\t{\n\t\t\t\t\t\tnewlayer.emplace_back(y, p.second);\n\t\t\t\t\t\tused[y] = true;\n\t\t\t\t\t\tcnt[p.second]++;\n\t\t\t\t\t}\n\t\t\t}\n\t\t\tlayer = newlayer;\n\t\t}\n\t}\n\tcout << ans << '\\n';\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile (t--) solve();\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "combinatorics",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1552",
    "index": "A",
    "title": "Subsequence Permutation",
    "statement": "A string $s$ of length $n$, consisting of lowercase letters of the English alphabet, is given.\n\nYou must choose some number $k$ between $0$ and $n$. Then, you select $k$ characters of $s$ and permute them however you want. In this process, the positions of the other $n-k$ characters remain unchanged. You have to perform this operation exactly once.\n\nFor example, if $s=\"andrea\"$, you can choose the $k=4$ characters $\"a_d_ea\"$ and permute them into $\"d_e_aa\"$ so that after the operation the string becomes $\"dneraa\"$.\n\nDetermine the minimum $k$ so that it is possible to sort $s$ alphabetically (that is, after the operation its characters appear in alphabetical order).",
    "tutorial": "Let $\\texttt{sort}(s)$ be $s$ sorted alphabetically. The answer to the problem is the number $m$ of mismatches between $s$ and $\\texttt{sort}(s)$ (i.e., the positions with different characters in the two strings). Choosing $k=m$ characters is sufficient. Let us choose the mismatched characters between $s$ and $\\texttt{sort}(s)$, and permute them so that they are sorted alphabetically. It is not hard to prove that the resulting string will coincide with $\\texttt{sort}(s)$. Choosing strictly less than $m$ characters is not sufficient. If $k < m$, by the Pigeonhole Principle at least one of the mismatched characters will be left out, and thus it will prevent the final string from being ordered alphabetically. Complexity: $O(n\\log n)$.",
    "code": "#include <iostream>\n#include <string>\n#include <algorithm>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    string s;\n    cin >> n >> s;\n \n    string s_ord = s;\n    sort(s_ord.begin(), s_ord.end());\n \n    int ans = 0;\n    for (int i = 0; i < n; i++)\n        ans += (s[i] != s_ord[i]);\n \n    cout << ans << \"\\n\";\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    for (int i = 1; i <= t; i++)\n        solve();\n \n    return 0;\n}",
    "tags": [
      "sortings",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1552",
    "index": "B",
    "title": "Running for Gold",
    "statement": "The Olympic Games have just started and Federico is eager to watch the marathon race.\n\nThere will be $n$ athletes, numbered from $1$ to $n$, competing in the marathon, and all of them have taken part in $5$ important marathons, numbered from $1$ to $5$, in the past. For each $1\\le i\\le n$ and $1\\le j\\le 5$, Federico remembers that athlete $i$ ranked $r_{i,j}$-th in marathon $j$ (e.g., $r_{2,4}=3$ means that athlete $2$ was third in marathon $4$).\n\nFederico considers athlete $x$ superior to athlete $y$ if athlete $x$ ranked better than athlete $y$ in at least $3$ past marathons, i.e., $r_{x,j}<r_{y,j}$ for at least $3$ distinct values of $j$.\n\nFederico believes that an athlete is likely to get the gold medal at the Olympics if he is superior to all other athletes.\n\nFind any athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes), or determine that there is no such athlete.",
    "tutorial": "Solution 1 First of all, observe that athlete $i$ is superior to athlete $j$ if and only if athlete $j$ is not superior to athlete $i$. The issue is, of course, that we cannot iterate over all pairs of athletes as there are $\\binom{n}{2} = O(n^2)$ pairs, which is too much to fit in the time limit. Notice that there can be at most one athlete who is likely to get the gold medal (if there were $2$, one would not be superior to the other which is a contradiction). Let us describe the algorithm. We iterate over the athletes from $1$ to $n$, keeping a possible winner $w$. When we process $i$, we check whether $w$ is superior to $i$. In that case, clearly $i$ is not the one who is likely to get the gold medal and we do nothing. On the other hand, if $i$ is superior to $w$, we deduce that $w$ cannot be the athlete who is likely to get the gold medal. In this case, we assign $w:=i$ and we proceed. Notice that, when we have finished processing athletes, if there is an athlete superior to everyone else it is for sure $w$. Finally, we check whether $w$ is superior to everyone else or not. Complexity: $O(n)$. Solution 2 Let us describe a randomized solution which seems very naive but can actually be proven to have a good complexity (still, the proof is much harder than an optimistic guess). There are many other possible randomized approach which can be proven to have a correct complexity with a similar proof. For each athlete $i$ check whether he is superior to all other athletes, iterating over other athletes in a random order, and stop as soon as you find an athlete who is superior to $i$. Let us show that the described algorithm has complexity $O(n\\log n)$. Consider an athlete $i$ who is superior to exactly $n-1-k$ other athletes. Let us compute the expected amount of other athletes the algorithm processes when deciding if athlete $i$ is likely to get a medal. If $k = 0$, the algorithm iterates over all other $n - 1 = O(n)$ athletes. If $k \\ge 1$, the expected number of other athletes the algorithm iterates over is $O\\Big(\\frac{n}{k}\\Big)$. To prove this, one shall observe that if we take $k$ random distinct elements out of $\\{1, \\, 2, \\, \\dots, \\, n\\}$ the expected value of the smallest one is $O\\Big(\\frac{n}{k}\\Big)$. So, the overall complexity of the algorithm is: $O\\left(q_0 \\cdot n + \\sum_{k = 1}^{n - 1} q_k \\frac{n}{k}\\right) = O\\left(n \\left(q_0 + \\sum_{k = 1}^{n - 1}\\frac{q_k}{k}\\right)\\right),$ If we let $s_k = q_0 + q_1 + \\cdots + q_k$, we can also estimate the complexity with $O\\left(n \\left(s_0 + \\sum_{k = 1}^{n - 1}\\frac{s_k - s_{k-1}}{k}\\right)\\right) = O\\left(n\\left(\\sum_{k = 1}^{n - 2}\\frac{s_k}{k(k + 1)} + \\frac{s_{n - 1}}{n - 1}\\right)\\right).$ It remains to estimate $s_k$ and the following lemma does exactly this. Lemma. For each $k \\ge 0$, there are at most $2k + 1$ athletes which are superior to at least $n - 1 - k$ athletes. Proof. Assume that there are $m$ athletes who are superior to at least $n - 1 - k$ other athletes. Consider the complete directed graph on these $m$ athletes so that the edge $i \\to j$ is present if and only if athlete $i$ is superior to athlete $j$. Each vertex has out-degree $\\ge m - 1 - k$ and therefore the number of edges is at least $m(m - 1 - k)$. On the other hand, the number of edges is clearly $\\binom{m}{2}$ and therefore we obtain $m(m - 1 - k) \\le \\frac{m(m - 1)}2 \\implies m \\le 2k+1$ The lemma tells us that $s_k \\le 2k + 1$ and therefore the complexity is estimated by $O\\left(n\\left(\\sum_{k = 1}^{n - 2} \\frac{2k + 1}{k(k + 1)} + \\frac{2n - 1}{n - 1}\\right)\\right) = O\\left(2n\\sum_{k = 1}^{n - 2} \\frac{1}{k}\\right) = O(n\\log n).$ Complexity: $O(n\\log n)$, randomized.",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \n// Returns the time elapsed in nanoseconds from 1 January 1970, at 00:00:00.\nLL get_time() {\n    return chrono::duration_cast<chrono::nanoseconds>(\n        chrono::steady_clock::now().time_since_epoch())\n        .count();\n}\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \nconst int M = 5;\n \nstruct Rank {\n    int r[M];\n};\n \nbool operator<(const Rank& A, const Rank& B) {\n    int cnt = 0;\n    for (int i = 0; i < M; i++) cnt += A.r[i] < B.r[i];\n    return cnt >= 3;\n}\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    vector<Rank> ath(n);\n    for (int i = 0; i < n; i++) for (int j = 0; j < M; j++) cin >> ath[i].r[j];\n    vector<int> ord(n);\n    for (int i = 0; i < n; i++) ord[i] = i;\n    random_shuffle(ord.begin(), ord.end());\n \n    for (int i = 0; i < n; i++) {\n        bool works = true;\n        for (int j = 0; j < n and works; j++) {\n            if (i != j) works &= ath[ord[i]] < ath[ord[j]];\n        }\n        if (works) {\n            cout << ord[i]+1 << \"\\n\";\n            return;\n        }\n    }\n    cout << -1 << \"\\n\";\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n    srand(time(NULL));\n    \n    int t;\n    cin >> t;\n \n    for (int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "combinatorics",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1552",
    "index": "C",
    "title": "Maximize the Intersections",
    "statement": "On a circle lie $2n$ distinct points, with the following property: however you choose $3$ chords that connect $3$ disjoint pairs of points, no point strictly inside the circle belongs to all $3$ chords. The points are numbered $1, \\, 2, \\, \\dots, \\, 2n$ in clockwise order.\n\nInitially, $k$ chords connect $k$ pairs of points, in such a way that all the $2k$ endpoints of these chords are distinct.\n\nYou want to draw $n - k$ additional chords that connect the remaining $2(n - k)$ points (each point must be an endpoint of exactly one chord).\n\nIn the end, let $x$ be the total number of intersections among all $n$ chords. Compute the maximum value that $x$ can attain if you choose the $n - k$ chords optimally.\n\nNote that the exact position of the $2n$ points is not relevant, as long as the property stated in the first paragraph holds.",
    "tutorial": "Let us forget about the original labeling of the points. Relabel the $2(n - k)$ \"free\" points $1, \\, 2, \\, \\dots, \\, 2(n - k)$ in clockwise order, starting from an arbitrary point. Also, in the following, we will color black the original $k$ chords, and red the additional $n - k$ chords. For $1 \\le i \\le n - k$, connect point $i$ to point $i + n - k$ with a red chord. We shall prove that this configuration - which we will henceforth refer to as the star configuration - is the only one that achieves the maximum number of intersections. The proof will be divided into two parts. First part: we show that, if there are two red chords that do not intersect, it is possible to increase the number of intersections. Second part: we show that there is exactly one configuration in which all pairs of red chords intersect, namely the star configuration. First part. Suppose that, after drawing $n - k$ red chords, there is a pair of red chords that do not intersect. Let these chords connect points $a$-$b$ and $c$-$d$ respectively. Without loss of generality, assume that the chords $a$-$d$ and $b$-$c$ intersect. We show that, by replacing chords $a$-$b$ and $c$-$d$ with $a$-$d$ and $b$-$c$, the overall number of intersections increases. Consider any other chord (either black or red) that intersected exactly one of $a$-$b$ and $c$-$d$. It is easy to see that, in the new configuration, that chord intersects exactly one of $a$-$d$ and $b$-$c$, as exemplified in the following picture: Now consider any other chord (either black or red) that intersected both $a$-$b$ and $c$-$d$. Again, one can see that, in the new configuration, that chord intersects both $a$-$d$ and $b$-$c$: Second part. Consider a configuration that is not the star configuration. Then, there is at least one chord $a$-$b$ ($a < b$) such that $b \\ne a + n - k$. Without loss of generality, suppose $a = 1$. Now, exactly one of the two sets of points $\\{2, \\, \\dots, \\, b - 1\\}$ and $\\{b + 1, \\, \\dots, \\, 2(n - k)\\}$ must contain at least $n - k$ points. By the Pigeonhole Principle, there must be a chord whose endpoints are both contained in this set, and one can see that such a chord does not intersect $a$-$b$. Thus we have shown that the star configuration is the only one in which all pairs of chords intersect, which implies (from the first part) that it is the only one that maximizes the number of intersections. Producing the $n - k$ chords of the star configuration is trivial. It remains to count the number of intersections, which can be done naively in $O(n^2)$ (for each pair of chords, check if they intersect). Bonus: Find an $O(n\\log n)$ algorithm to count the number of intersections. Complexity: $O(n^2)$.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nbool intersect(pair<int, int> c, pair<int, int> d) {\n    if (c.first > d.first) swap(c, d);\n    return c.second > d.first and c.second < d.second;\n}\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n \n    vector<pair<int, int>> chords;\n    vector<bool> used(2 * n + 1, false);\n    for (int i = 1; i <= k; i++) {\n        int x, y;\n        cin >> x >> y;\n        if (x > y) swap(x, y);\n        chords.push_back(make_pair(x, y));\n        used[x] = used[y] = true;\n    }\n \n    vector<int> unused;\n    for (int i = 1; i <= 2 * n; i++)\n        if (!used[i]) unused.push_back(i);\n \n    for (int i = 0; i < n - k; i++)\n        chords.push_back(make_pair(unused[i], unused[i + n - k]));\n \n    int ans = 0;\n    for (int i = 0; i < n; i++)\n        for (int j = i + 1; j < n; j++)\n            ans += intersect(chords[i], chords[j]);\n \n    cout << ans << endl;\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    for (int i = 1; i <= t; i++)\n        solve();\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "geometry",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1552",
    "index": "D",
    "title": "Array Differentiation",
    "statement": "You are given a sequence of $n$ integers $a_1, \\, a_2, \\, \\dots, \\, a_n$.\n\nDoes there exist a sequence of $n$ integers $b_1, \\, b_2, \\, \\dots, \\, b_n$ such that the following property holds?\n\n- For each $1 \\le i \\le n$, there exist two (not necessarily distinct) indices $j$ and $k$ ($1 \\le j, \\, k \\le n$) such that $a_i = b_j - b_k$.",
    "tutorial": "Suppose that a solution $b_1, \\, \\dots, \\, b_n$ exists. For each $1 \\le i \\le n$, let $j_i, \\, k_i$ be the indices such that $a_i = b_{j_i} - b_{k_i}$. Consider the directed graph on vertices $1, \\, \\dots, \\, n$, with the $n$ edges $j_i \\rightarrow k_i$. If we ignore, for a moment, the orientations, we are left with an undirected graph with $n$ vertices and $n$ edges, which must contain a cycle (possibly a loop). Let $m$ be the length of one such cycle, and let $v_1, \\, \\dots, v_m$ be its vertices. Now, of course $(b_{v_1} - b_{v_2}) + (b_{v_2} - b_{v_3}) + \\cdots + (b_{v_m} - b_{v_1}) = 0$, since all the terms cancel out. Notice that, for each $i$, there exists $1 \\le t_i \\le n$ such that (indices are taken modulo $m$, so that $v_{m + 1} = v_1$) $b_{v_i} - b_{v_{i + 1}} = \\begin{cases} a_{t_i} & \\text{if there is an edge } v_i \\rightarrow v_{i + 1}, \\\\ -a_{t_i} & \\text{if there is an edge } v_i \\leftarrow v_{i + 1}. \\end{cases}$ Thus, there must be a nonempty subset $\\{t_1, \\, \\dots, \\, t_m\\} \\subseteq \\{1, \\, \\dots, \\, n\\}$ and a choice of signs $s_1, \\, \\dots, \\, s_m$ ($s_i \\in \\{+1, \\, -1\\}$) such that $\\tag{$\\star$} s_1a_{t_1} + \\cdots + s_ma_{t_m} = 0.$ Let us show that this condition is also sufficient for the existence of a valid sequence $b_1, \\, \\dots, \\, b_n$. Suppose there exist $m$, $t_1, \\, \\dots, \\, t_m$ and $s_1, \\, \\dots, \\, s_m$ so that $(\\star)$ holds. We construct $b_1, \\, \\dots, \\, b_n$ as follows. Set $b_{t_1} = 0$. Then, inductively, for each $1 \\le i < m$ set $b_{t_{i + 1}} = b_{t_i} - s_ia_{t_i}$. Finally, for $i \\not\\in \\{t_1, \\, \\dots, \\, t_m\\}$, set $b_i = a_i$. It is easy to check that this construction works. The algorithm that iterates over all $3^n - 1$ choices of the subset and the signs (for each $i$ we decide whether $a_i$ is included in the subset and if it is included, whether its sign is positive or negative) and checks if for one of them $(\\star)$ holds, is sufficient to solve the problem under the given constraints. Alternatively, one may treat the problem as a knapsack instance (the weights are $a_i$, but can be chosen with arbitrary sign, and we shall understand whether we can fill precisely a knapsack with $0$ capacity). With this approach, the complexity is $O(n^2\\max|a_i|)$. Bonus: Solve the problem with complexity $O(n3^{\\frac{n}{2}})$. Complexity: $O(n3^n)$.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    vector<int> a(n + 1);\n    for (int i = 1; i <= n; i++) cin >> a[i];\n \n    int three2n = 1;\n    for (int i = 1; i <= n; i++)\n        three2n *= 3;\n \n    for (int k = 1; k < three2n; k++) {\n        int k_cp = k;\n        int sum = 0;\n        for (int i = 1; i <= n; i++) {\n            int s = k_cp % 3;\n            k_cp /= 3;\n            if (s == 2) s = -1;\n            sum += s * a[i];\n        }\n        if (sum == 0) {\n            cout << \"YES\" << endl;\n            return;\n        }\n    }\n \n    cout << \"NO\" << endl;\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    for (int i = 1; i <= t; i++)\n        solve();\n \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1552",
    "index": "E",
    "title": "Colors and Intervals",
    "statement": "The numbers $1, \\, 2, \\, \\dots, \\, n \\cdot k$ are colored with $n$ colors. These colors are indexed by $1, \\, 2, \\, \\dots, \\, n$. For each $1 \\le i \\le n$, there are exactly $k$ numbers colored with color $i$.\n\nLet $[a, \\, b]$ denote the interval of integers between $a$ and $b$ inclusive, that is, the set $\\{a, \\, a + 1, \\, \\dots, \\, b\\}$. You must choose $n$ intervals $[a_1, \\, b_1], \\, [a_2, \\, b_2], \\, \\dots, [a_n, \\, b_n]$ such that:\n\n- for each $1 \\le i \\le n$, it holds $1 \\le a_i < b_i \\le n \\cdot k$;\n- for each $1 \\le i \\le n$, the numbers $a_i$ and $b_i$ are colored with color $i$;\n- each number $1 \\le x \\le n \\cdot k$ belongs to at most $\\left\\lceil \\frac{n}{k - 1} \\right\\rceil$ intervals.\n\nOne can show that such a family of intervals always exists under the given constraints.",
    "tutorial": "Solution 1 We describe the algorithm and later we explain why the construction works. Let $x_{i, j}$ ($1 \\le i \\le n$, $1 \\le j \\le k$) denote the position of the $j$-th occurrence of color $i$ (from the left). First, sort the colors according to $x_{i, 2}$. Take the first $\\left\\lceil \\frac{n}{k - 1} \\right\\rceil$ colors, and to each of them assign the interval $[x_{i, 1}, \\, x_{i, 2}]$. Then, sort the remaining colors according to $x_{i, 3}$, take the first $\\left\\lceil \\frac{n}{k - 1} \\right\\rceil$ and to each of them assign the interval $[x_{i, 2}, \\, x_{i, 3}]$. More generally, in the $t$-th step: sort the remaining colors according to $x_{i, t + 1}$; take the first $\\left\\lceil \\frac{n}{k - 1} \\right\\rceil$ (possibly less in the last step) of these colors; assign to each color $i$ the interval $[x_{i, t}, \\, x_{i, t + 1}]$. Let us show that this choice of intervals works. It is straightforward to see that the first two properties hold. It remains to check the third property. We prove that two intervals selected in different steps are disjoint. Since in each step we select at most $\\left\\lceil \\frac{n}{k - 1} \\right\\rceil$ intervals, this is sufficient to conclude. Consider two colors $i, \\, j$ selected in two different steps $s < t$ respectively. Then, we have $x_{i, s + 1} < x_{j, s + 1} \\le x_{j, t}$ and thus $[x_{i, s}, \\, x_{i, s + 1}] \\cap [x_{j, t}, \\, x_{j, t + 1}] = \\varnothing$, which is exactly what we wanted to prove. Complexity: $O(nk)$. Solution 2 A greedy approach is also possible. Let $x_{i, j}$ be defined as in Solution 1. Consider all intervals of the form $[x_{i, j}, \\, x_{i, j + 1}]$ and sort them increasingly according to their right endpoint. We now iterate over these intervals, and for each of them, we decide to select it if both these conditions are met (which are equivalent to \"selecting the interval does not violate any requirement\"): no interval of the same color has been chosen yet; among the numbers spanned by the interval, no one is contained in (at least) $\\left\\lceil \\frac{n}{k - 1} \\right\\rceil$ already selected intervals. Let us prove that this algorithm works (i.e., it selects exactly one interval for each color). Suppose, by contradiction, that, for some color $i$, no interval of that color gets chosen. This means that, for each $1 \\le j \\le k - 1$, there exist $\\left\\lceil \\frac{n}{k - 1} \\right\\rceil$ selected intervals that intersect interval $[x_{i, j}, \\, x_{i, j + 1}]$. We can say more: the rightmost endpoints of these intervals must belong to $[x_{i, j}, \\, x_{i, j + 1}]$; indeed, if it weren't the case for at least one interval $[a, \\, b]$, the interval $[x_{i, j}, \\, x_{i, j + 1}]$ would come before $[a, \\, b]$ in the ordering, so it would actually have been selected. Since all these intervals must be distinct, they are $(k - 1)\\left\\lceil \\frac{n}{k - 1} \\right\\rceil \\ge n$. Yet this contradicts the fact that they must be at most $n - 1$, one for each color other than $i$. Complexity: $O(n^2k)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n \nusing namespace std;\n \nstruct Interval {\n    int a, b;\n    int color;\n    Interval(int _a, int _b, int _color):\n        a(_a), b(_b), color(_color) {}\n    bool operator <(const Interval other) {\n        return b < other.b;\n    }\n};\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    int r = (n + k - 2) / (k - 1);\n \n    vector<int> c(n * k + 1);\n    for (int i = 1; i <= n * k; i++)\n        cin >> c[i];\n \n    vector<vector<int>> x(n + 1);\n    for (int i = 1; i <= n * k; i++)\n        x[c[i]].push_back(i);\n \n    vector<Interval> candidates;\n    for (int i = 1; i <= n; i++)\n        for (int j = 0; j < k - 1; j++)\n            candidates.push_back(Interval(x[i][j], x[i][j + 1], i));\n    sort(candidates.begin(), candidates.end());\n \n    vector<pair<int, int>> intervals(n + 1);\n    vector<bool> taken(n + 1, false);\n    vector<int> weights(n * k + 1, 0);\n    for (Interval I : candidates) {\n        if (taken[I.color]) continue;\n        int max_w = 0;\n        for (int i = I.a; i <= I.b; i++)\n            max_w = max(max_w, weights[i]);\n        if (max_w < r) {\n            taken[I.color] = true;\n            for (int i = I.a; i <= I.b; i++) ++weights[i];\n            intervals[I.color] = make_pair(I.a, I.b);\n        }\n    }\n \n    for (int i = 1; i <= n; i++)\n        cout << intervals[i].first << \" \" << intervals[i].second << endl;\n}\n \nint main() {\n    solve();\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1552",
    "index": "F",
    "title": "Telepanting",
    "statement": "An ant moves on the real line with constant speed of $1$ unit per second. It starts at $0$ and always moves to the right (so its position increases by $1$ each second).\n\nThere are $n$ portals, the $i$-th of which is located at position $x_i$ and teleports to position $y_i < x_i$. Each portal can be either active or inactive. The initial state of the $i$-th portal is determined by $s_i$: if $s_i=0$ then the $i$-th portal is initially inactive, if $s_i=1$ then the $i$-th portal is initially active. When the ant travels through a portal (i.e., when its position coincides with the position of a portal):\n\n- if the portal is inactive, it becomes active (in this case the path of the ant is not affected);\n- if the portal is active, it becomes inactive and the ant is instantly teleported to the position $y_i$, where it keeps on moving as normal.\n\nHow long (from the instant it starts moving) does it take for the ant to reach the position $x_n + 1$? It can be shown that this happens in a finite amount of time. Since the answer may be very large, compute it modulo $998\\,244\\,353$.",
    "tutorial": "Solution 1 The key insight is realizing that, if at some point the ant is located at position $x$, then all the portals with $x_i < x$ are active. One can prove this by induction on the time $t$. Indeed, when $t = 0$, $x = 0$ and there are no portals with $x_i < x$. Now suppose this is true at time $t$, and let $x$ be the position of the ant at that time. There are three possible scenarios to consider. If there is no portal at position $x$, then the statement is trivially true at time $t + 1$. If there is an inactive portal at position $x$, then that portal will become active and the position of the ant at time $t + 1$ will be $x + 1$, so all the portals with $x_i < x + 1$ will be active. If there is an active portal at position $x$, the ant will be teleported to some position $y < x$, and thus at time $t + 1$ it will be at position $y + 1 \\le x$. Since all the portals with $x_i < x$ were active in the first place, and $y + 1 \\le x$, all the portals with $x_i < y + 1$ will be active as well. Let $q_i$ be the time the ant needs to go from the position $x_i$ to the position $x_i$ again assuming that all the portals $1, \\, 2, \\, \\dots, \\, i$ are active. In order to find a formula for $q_i$, let us describe the movement of the ant when it starts from position $x_i$ and the portals $1, 2, \\dots, i$ are active. The ant gets instantly teleported to $y_i$. The ant walks from $y_i$ to $x_{j_i}$, where $j_i \\le i$ is the smallest index so that $y_i < x_{j_i}$. The ant walks for $q_{j_i}$ seconds and it ends up in $x_{j_i}$ with the portal inactive. The ant walks from $x_{j_i}$ to $x_{j_i+1}$. The ant walks for $q_{j_i+1}$ seconds and it ends up in $x_{j_i+1}$ with the portal inactive. $\\cdots$ The ant walks for $q_{i-1}$ seconds and it ends up in $x_{i-1}$ with the portal inactive. The ant walks from $x_{i-1}$ to $x_i$. Adding up the contributions of the steps described above, we obtain the following recurrence for $q_i$: $q_i = (x_i - y_i) + q_{j_i} + q_{j_i + 1} + \\cdots + q_{i - 1}.$ Let $A$ be the set of portals that are initially active. The answer to the problem is given by the formula (which can be proven analyzing the movement of the ant as we have done to prove the recurrence relation for $q_i$) $x_n + 1 + \\sum_{i \\in A} q_i.$ Using a binary search to identify $j_i$ and keeping the prefix sums of $q_1, \\, q_2, \\, \\dots, \\, q_n$, one can implement the described solution in $O(n\\log n)$. Complexity: $O(n\\log n)$. Solution 2 Let $z_i$ be the index of the teleporter reached immediately after using teleporter $i$ (it can be computed by binary search). Let $\\text{dp}_{i, 0}$ be the number of times $x_i$ is reached. Let $\\text{dp}_{i, 1}$ be the number of times the teleporter $i$ is used. Then, the answer is easy to calculate: each time the teleporter $i$ is active you spend $x_{z_i} - y_i$ time, and each time the teleporter $i$ is inactive you spend $x_{i + 1} - x_i$ time. Summing up all the contributions, the answer turns out to be $\\sum_{i = i}^n \\: [\\text{dp}_{i, 1}(x_{z_i} - y_i) + (\\text{dp}_{i, 0} - \\text{dp}_{i, 1})(x_{i + 1} - x_i)],$ Now we find recurrences for $\\text{dp}_{i, 0}$ and $\\text{dp}_{i, 1}$. The crucial observation is that $\\text{dp}_{i, 0}$ has the same parity of $s_i \\oplus 1$, where $\\oplus$ denotes bitwise XOR. Thus, it is not hard to see that, for $1 \\le i \\le n$, $\\begin{align*} \\text{dp}_{i + 1, 0} = \\sum_{z_j = i + 1} \\text{dp}_{j, 1} + \\frac{\\text{dp}_{i, 0} + (s_i \\oplus 1)}{2} \\implies \\text{dp}_{i, 0} & = 2\\left(\\text{dp}_{i + 1, 0} - \\sum_{z_j = i + 1} \\text{dp}_{j, 1}\\right) - (s_i \\oplus 1), \\\\ \\text{dp}_{i, 1} & = \\frac{\\text{dp}_{i, 0} - (s_i \\oplus 1)}{2}. \\end{align*}$ It now suffices to iterate over the indices $i$ in decreasing order. Complexity: $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define nl \"\\n\"\n#define nf endl\n#define ll long long\n#define pb push_back\n#define _ << ' ' <<\n \n#define INF (ll)1e18\n#define mod 1996488706\n#define hmod 998244353\n#define maxn 200010\n \nll i, i1, j, k, k1, t, n, m, res, flag[10], a, b;\nll x[maxn], y[maxn], s[maxn], dp[maxn][2], c[maxn];\nvector<array<ll, 2>> v;\nvector<ll> adj[maxn];\n \nvoid fx(ll &x, ll p) {\n    if ((x + p) % 2) x = (x + hmod) % mod;\n}\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    #if !ONLINE_JUDGE && !EVAL\n        ifstream cin(\"input.txt\");\n        ofstream cout(\"output.txt\");\n    #endif\n \n    cin >> n;\n    for (i = 1; i <= n; i++) {\n        cin >> x[i] >> y[i] >> s[i];\n        v.pb({x[i], i});\n    }\n    x[n + 1] = x[n] + 1;\n \n    for (i = 1; i <= n; i++) {\n        array<ll, 2> o = {y[i], -INF};\n        auto it = lower_bound(v.begin(), v.end(), o);\n        c[i] = (*it)[0] - y[i]; y[i] = (*it)[1];\n        adj[y[i]].pb(i);\n    }\n \n    dp[n][0] = s[n] + 1; dp[n][1] = s[n];\n    for (i = n - 1; i >= 1; i--) {\n        dp[i][0] = (2 * dp[i + 1][0]) % mod;\n        for (auto u : adj[i + 1]) dp[i][0] = (dp[i][0] - 2 * dp[u][1] + 2 * (ll)mod) % mod;\n        dp[i][0] = (dp[i][0] - (s[i] ^ 1) + mod) % mod;\n        fx(dp[i][0], s[i] ^ 1);\n        dp[i][1] = dp[i][0] / 2;\n    }\n \n    /* for (i = 1; i <= n; i++) {\n        cout << x[i + 1] - x[i] _ c[i] _ dp[i][0] _ dp[i][1] << nl;\n    } */\n \n    res = x[1] % mod;\n    for (i = 1; i <= n; i++) {\n        res += (dp[i][1] * c[i]); res %= mod;\n        res += ((dp[i][0] - dp[i][1] + mod) * (x[i + 1] - x[i])) % mod;\n    }\n \n    res %= hmod;\n    cout << res << nl;\n \n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1552",
    "index": "G",
    "title": "A Serious Referee",
    "statement": "Andrea has come up with what he believes to be a novel sorting algorithm for arrays of length $n$. The algorithm works as follows.\n\nInitially there is an array of $n$ integers $a_1,\\, a_2,\\, \\dots,\\, a_n$. Then, $k$ steps are executed.\n\nFor each $1\\le i\\le k$, during the $i$-th step the subsequence of the array $a$ with indexes $j_{i,1}< j_{i,2}< \\dots< j_{i, q_i}$ is sorted, without changing the values with the remaining indexes. So, the subsequence $a_{j_{i,1}},\\, a_{j_{i,2}},\\, \\dots,\\, a_{j_{i,q_i}}$ is sorted and all other elements of $a$ are left untouched.\n\nAndrea, being eager to share his discovery with the academic community, sent a short paper describing his algorithm to the journal \"Annals of Sorting Algorithms\" and you are the referee of the paper (that is, the person who must judge the correctness of the paper). You must decide whether Andrea's algorithm is correct, that is, if it sorts any array $a$ of $n$ integers.",
    "tutorial": "Let us say that an array of $n$ integers is good if it is sorted by Andrea's algorithm, and bad otherwise. First of all, we state and prove the following intuitive fact (which is well-known for sorting networks): Lemma. (Zero-One Principle) All arrays $a$ with values in $\\{0, \\, 1\\}$ are good if and only if all arrays are good. Proof. The \"if\" part is trivial. To prove the converse, consider an array $a$ made up of arbitrary integers (for simplicity, we assume that they are distinct). Fix some $1 \\le s \\le n$ and construct the array $b$ such that $b_i = 0$ if $a_i$ is among the $s$ smallest elements of $a$, and $b_i = 1$ otherwise. Since we know that $b$ is good, it follows that Andrea's algorithm applied on $a$ will produce an array in which the $s$ smallest elements occupy the first $s$ positions. Since this is true for every $s \\in \\{1, \\, 2, \\, \\dots, \\, n\\}$, we deduce that $a$ is good. If $n = 1$, then the answer is always ACCEPTED. From now on, we assume $n \\ge 2$. Let $S_i = \\{j_{i,1}, \\, \\dots, \\, j_{i,q_i}\\}$ be the set of indices considered in the $i$-th step. Let $T_i = S_1 \\cup S_2 \\cup \\cdots \\cup S_i$. Given a function $f: T_i \\to \\{0, \\, 1\\}$, we say that it is $i$-achievable if there is an initial array $a_1, \\, a_2, \\, \\dots, \\, a_n \\in \\{0, \\, 1\\}$ so that, after $i$ steps, $a_j = f(j)$ holds for each $j \\in T_i$. Applying the Zero-One Principle, one can show that the answer to the problem is ACCEPTED if and only if $T_k = \\{1, \\, 2, \\, \\dots, \\, n\\}$ and all the $k$-achievable functions are nondecreasing (there are $n + 1$ nondecreasing functions, which are those like $(0,0,\\dots,0,1,\\dots,1,1)$). The idea, then, is to compute, for each $i = 1, \\, 2, \\, \\dots, \\, k$, the set of $i$-achievable functions. Let $f: T_i \\to \\{0, \\, 1\\}$ be an $i$-achievable function. Notice that, for each $g: S_{i+1} \\setminus T_i \\to \\{0, \\, 1\\}$, we can find an initial configuration such that after $i$ steps it coincides with $f$ on $T_i$ and with $g$ on $S_{i + 1} \\setminus T_i$. In particular, we can choose arbitrarily how many times the function $g$ takes the value $1$. The crucial observation is that if we know $f$ and we know how many times the function $g$ takes the value $1$, then we know unambiguously what happens on $T_{i + 1}$ after $i + 1$ steps: on $T_{i + 1} \\setminus S_{i + 1}$ the values are exactly the values of $f$, on $S_{i + 1}$ the values are nondecreasing and thus only the number of ones is necessary to determine them. Thus, given an $i$-achievable function, we can construct the $(i + 1)$-achievable functions it can evolve into and there are exactly $|S_{i + 1} \\setminus T_i| + 1$ of them. Let $d_i = |S_i \\setminus T_{i - 1}|$. The complexity of the described algorithm is $O(n \\cdot (d_1 + 1)(d_2 + 1) \\cdots (d_k + 1))$. Since $(d_1 + 1) + (d_2 + 1) + \\cdots + (d_k + 1) \\le n + k$, we have (by the AM-GM inequality): $(d_1 + 1)(d_2 + 1) \\cdots (d_k + 1) \\le \\left(\\frac{n + k}{k}\\right)^k.$ Here are three observations which reduce hugely the execution time (the first one is already sufficient to fit into the time-limit comfortably): It is possible to encode the $i$-achievable functions as bitmasks and all the steps of the solutions can be performed as bitwise operations. Let us show that if $T_{k - 1} \\ne \\{1, \\, 2, \\, \\dots, \\, n\\}$ and $S_k \\ne \\{1, \\, 2, \\, \\dots, \\, n\\}$, then the answer is REJECTED. Let $x \\not\\in T_{k - 1}$ and $y \\not\\in S_k$. If $x = y$, then $x \\not\\in T_k$ and we already know that the answer is REJECTED. Otherwise, let $a$ be a permutation of $1, \\, 2, \\, \\dots, \\, n$ with $a_x = y$. After $k - 1$ steps it still holds $a_x = y$ and after $k$ steps $y \\in \\{a_j: j \\in S_k\\}$ which implies that $a_y \\ne y$ and therefore the array is not sorted by the algorithm. With this observation (together with the above described usage of bitmasks), the complexity of the algorithm becomes $O\\left(\\left(\\frac{n + k - 1}{k - 1}\\right)^{k - 1}\\right)$. To save a lot of memory (and, since memory allocation is expensive, also execution time), one can implement the algorithm in a recursive fashion. Complexity: $O\\left(n\\left(\\frac{n + k}{k}\\right)^k\\right)$.",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \n// Returns the time elapsed in nanoseconds from 1 January 1970, at 00:00:00.\nLL get_time() {\n    return chrono::duration_cast<chrono::nanoseconds>(\n        chrono::steady_clock::now().time_since_epoch())\n        .count();\n}\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \nconst int MAXN = 40;\nconst int MAXK = 10;\n \nint n, k;\nLL active[MAXK+1];\nLL bb[MAXK];\nLL pref[MAXK][MAXN+1];\nLL q[MAXK];\nint inactive[MAXK];\n \nbool recur(LL S, int it) {\n    if (it == k-1) {\n        int ones = __builtin_popcountll(S);\n        int zeros = n-ones;\n        LL sortedS = ((1ll<<ones)-1)<<zeros;\n        LL diff = S ^ sortedS;\n        return (diff & bb[it]) == diff;\n    }\n    int min_ones = __builtin_popcountll(S & bb[it]);\n    S |= bb[it];\n    for (int ones = min_ones; ones <= min_ones + inactive[it]; ones++) {\n        if (recur(S & pref[it][ones], it+1) == false) return false;\n    }\n    return true;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n    \n    cin >> n;\n \n    if (n == 1) {\n        cout << \"ACCEPTED\\n\";\n        return 0;\n    }\n    \n    cin >> k;\n    for (int it = 0; it < k; it++) {\n        cin >> q[it];\n        pref[it][q[it]] = (1ll<<n)-1;\n        for (int i = 0; i < q[it]; i++) {\n            int x;\n            cin >> x;\n            x--;\n            bb[it] |= 1ll<<x;\n            pref[it][q[it]-(i+1)] = ~bb[it];\n        }\n        inactive[it] = __builtin_popcountll(bb[it]&(~active[it]));\n        active[it+1] = active[it] | bb[it];\n    }\n \n    if (q[k-1] == n) {\n        cout << \"ACCEPTED\\n\";\n        return 0;\n    }\n \n    if (active[k-1] != (1ll<<n)-1) {\n        cout << \"REJECTED\\n\";\n        return 0;\n    }\n \n    if (!recur(0, 0)) cout << \"REJECTED\\n\";\n    else cout << \"ACCEPTED\\n\";\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1552",
    "index": "H",
    "title": "Guess the Perimeter",
    "statement": "Let us call a point of the plane admissible if its coordinates are positive integers less than or equal to $200$.\n\nThere is an invisible rectangle such that:\n\n- its vertices are all admissible;\n- its sides are parallel to the coordinate axes;\n- its area is strictly positive.\n\nYour task is to guess the perimeter of this rectangle.In order to guess it, you may ask at most $4$ queries.\n\nIn each query, you choose a nonempty subset of the admissible points and you are told how many of the chosen points are inside or on the boundary of the invisible rectangle.",
    "tutorial": "Let $b$ and $h$ be the lengths of base and height of the rectangle. We will solve a harder problem, that is, finding the explicit values of $b$ and $h$. For a positive integer $d$, define $S(d)$ as the set of admissible points $(x, \\, y)$ with $d \\mid x$, and define $f(d)$ as the answer to the query with subset $S(d)$. Then $f(1) = (b + 1)(h + 1)$. Lemma 1. We have $d\\cdot f(d) = f(1)$ if and only if $d \\mid b + 1$. Proof. Consider the set $\\{d, \\, 2d, \\, 3d, \\, \\dots\\}$ of all positive multiples of $d$, and let $n$ be the number of such multiples that are the $x$-coordinate of at least one point of the rectangle. Then $f(d) = n(h + 1)$. We notice that $n = \\frac{b + 1}{d} \\iff d \\mid b + 1$ (indeed, the \"if\" statement is trivial, since $n$ must be integer; the converse is true because we can split the base in $\\frac{b + 1}{d}$ segments, and each segment contains exactly one point whose $x$-coordinate is a multiple of $d$). On the other hand, $df(d) = f(1) \\iff dn(h + 1) = (b + 1)(h + 1) \\iff n = \\frac{b + 1}{d}$. This completes the proof. Lemma 2. Let $p = 2^k$ be the highest power of $2$ which divides $b + 1$. Then $\\left\\lvert 2f(2p) - \\frac{f(1)}{p} \\right\\rvert = h + 1$. Proof. Let $n = \\frac{f(p)}{h + 1}$ be as in the previous Lemma, and let $n' = \\frac{f(2p)}{h + 1}$. Then it is easy to see that $n' = \\frac{n \\pm 1}{2}$, which means that $2f(2p) = 2n'(h + 1) = (n \\pm 1)(h + 1)$. But, since $p \\mid b + 1$, $n(h + 1) = \\frac{b + 1}{p}(h + 1) = \\frac{f(1)}{p}$. Finally, $\\left\\lvert 2f(2p) - \\frac{f(1)}{p} \\right\\rvert = \\left\\lvert n(h + 1) \\pm (h + 1) - \\frac{f(1)}{p} \\right\\rvert = \\left\\lvert \\frac{f(1)}{p} \\pm (h + 1) - \\frac{f(1)}{p} \\right\\rvert = h + 1.$ Now it suffices to ask for $f(1)$ (one query), and then binary-search the value of $p$ from the set $\\{1, \\, 2, \\, 2^2, \\, \\dots, \\, 2^7\\}$, which takes $3$ queries. Note that, when we find $p$, we have already computed $f(2p)$ (except when $p = 2^7$, but in this case $f(2p) = 0$), so no further query is required.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nvector<pair<int, int>> get_S(int d) {\n    vector<pair<int, int>> S;\n    for (int i = d; i <= 200; i += d)\n        for (int j = 1; j <= 200; j++)\n            S.push_back(make_pair(i, j));\n    return S;\n}\n \nint query(int d) {\n    vector<pair<int, int>> S = get_S(d);\n    cout << \"? \" << S.size() << endl;\n    for (auto [x, y] : S) cout << x << \" \" << y << \" \";\n    cout << endl;\n    cout.flush();\n    int ans;\n    cin >> ans;\n    return ans;\n}\n \nint main() {\n    vector<int> f(9, 0);\n    f[0] = query(1);\n \n    int l = 1, r = 8;\n    while (l < r) {\n        int m = (l + r) / 2;\n        int d = (1 << m);\n        f[m] = query(d);\n        if (d * f[m] == f[0]) l = m + 1;\n        else r = m;\n    }\n \n    int k = l - 1;\n    int h = abs(2 * f[k + 1] - f[0] / (1 << k));\n    int b = f[0] / h;\n    cout << \"! \" << 2 * (b + h - 2) << endl;\n    cout.flush();\n \n    return 0;\n}",
    "tags": [
      "binary search",
      "interactive",
      "number theory"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1552",
    "index": "I",
    "title": "Organizing a Music Festival",
    "statement": "You are the organizer of the famous \"Zurich Music Festival\". There will be $n$ singers who will perform at the festival, identified by the integers $1$, $2$, $\\dots$, $n$. You must choose in which order they are going to perform on stage.\n\nYou have $m$ friends and each of them has a set of favourite singers. More precisely, for each $1\\le i\\le m$, the $i$-th friend likes singers $s_{i,1}, \\, s_{i, 2}, \\, \\dots, \\,s_{i, q_i}$.\n\nA friend of yours is happy if the singers he likes perform consecutively (in an arbitrary order). An ordering of the singers is valid if it makes all your friends happy.\n\nCompute the number of valid orderings modulo $998\\,244\\,353$.",
    "tutorial": "Let $S_i := \\{s_{i,1}, \\, s_{i,2}, \\, \\dots, \\, s_{i, q_i}\\}$. Consider the graph on the subsets $S_1, \\, S_2, \\, \\dots, \\, S_k$ such that $S_i$ is adjacent to $S_j$ if and only if $S_i \\cap S_j \\ne \\varnothing, \\, S_i, \\, S_j$. Without loss of generality we can assume that the sets $S_1, \\, S_2, \\, \\dots, \\, S_m$ are distinct. Consider a connected component $\\mathcal C$ in such a graph (that is, $\\mathcal C$ is a family of subsets). Let $P(\\mathcal C) := \\bigcup_{S\\in\\mathcal C} S$ be the union of all sets in $\\mathcal C$. For each $x \\in P(\\mathcal C)$, let $\\mathcal C_x := \\{S \\in \\mathcal C: x \\in S\\}$. Notice that $\\mathcal C_x = \\mathcal C_y$ if and only if the elements $x, \\, y$ belongs to exactly the same set in $\\mathcal C$. Consider the equivalence relationship on $P(\\mathcal C)$ induced by the function $x \\mapsto \\mathcal C_x$ (i.e., $x \\equiv y \\iff \\mathcal C_x = \\mathcal C_y$). Lemma. If $|\\mathcal C| \\ge 2$, there is either $0$ or exactly $2$ (one is the reversal of the other) ways to order the equivalence classes so that any subset $T \\in \\mathcal C$ is the union of a contiguous (in the ordering) interval of equivalence classes. Proof. This can be proven by induction on the number of sets in $\\mathcal C$. If $|\\mathcal C| = 2$, assume $\\mathcal C = \\{S_1, \\, S_2\\}$. The possible values of $\\mathcal C_x$ are $\\{S_1\\}$, $\\{S_2\\}$, $\\{S_1, \\, S_2\\}$. For sure the equivalence class corresponding to $\\{S_1, \\, S_2\\}$ is nonempty and, without loss of generality, we may also assume that the equivalence class corresponding to $\\{S_1\\}$ is nonempty. Then the valid orderings are exactly $\\{S_1\\}\\ - \\ \\{S_1, \\, S_2\\}\\ - \\ \\{S_2\\}$ and its reversal. Now, assume that $|\\mathcal C| \\ge 3$. Take $S \\in \\mathcal C$ so that $\\mathcal C' := \\mathcal C \\setminus \\{S\\}$ is still connected. Notice that the equivalence classes induced by $\\mathcal C'$ may be less refined than those induced by $\\mathcal C$ (moreover, the elements in $S \\setminus P(\\mathcal C')$ are not even considered). If already there is no good ordering of the equivalence classes induced by $\\mathcal C'$, then the same holds for the equivalence classes induced by $\\mathcal C$. Otherwise, by induction, we may assume that there is a unique (up to reversal) ordering of the equivalence classes induced by $\\mathcal C'$. Let $Z_1, \\, Z_2, \\, \\dots, \\, Z_k$ be the equivalence classes induced by $\\mathcal C'$ on $P(\\mathcal C')$ in the correct order. What changes when we consider also the set $S$? Each $Z_i$ splits into two (possibly empty) equivalence classes $Z_i' := Z_i \\cap S$ and $Z_i' ' := Z_i \\setminus S$. Moreover, we have to take care of the (possibly empty) new equivalence class $Z_0 := S \\setminus P(\\mathcal C')$. Consider the set of indices $I$ so that $i \\in I$ if and only if both sets $Z_i \\cap S$ and $Z_i \\setminus S$ are nonempty. Let us consider various cases: If $I=\\varnothing$, then there is a valid ordering if and only if the set $\\{1 \\le i \\le k: Z_i \\cap S \\ne \\varnothing\\}$ is a prefix or a suffix of $\\{1,2,\\dots,k\\}$ or it is a contiguous interval and $Z_0=\\varnothing$. If $|I| \\ge 3$, then there is no good ordering. If $|I| = 2$, assume that $I= \\{l, \\, r\\}$ and $l < r$. Then there is a valid ordering if and only if the set $\\{1 \\le i \\le k: Z_i \\cap S \\ne \\varnothing\\}$ coincides with $[l, \\, r]$ and $Z_0 = \\varnothing$. In such case, the unique valid ordering (up to reversal) is given by: $Z_1, \\, Z_2, \\, \\dots, \\, Z_{l - 1}, \\, Z_l' ', \\, Z_l', \\, Z_{l + 1}, \\, \\dots, \\, Z_{r - 1}, \\, Z_r', \\, Z_r' ', \\, Z_{r+1}, \\, \\dots, \\, Z_n.$ $Z_1, \\, Z_2, \\, \\dots, \\, Z_{l - 1}, \\, Z_l' ', \\, Z_l', \\, Z_{l + 1}, \\, \\dots, \\, Z_{r - 1}, \\, Z_r', \\, Z_r' ', \\, Z_{r+1}, \\, \\dots, \\, Z_n.$ If $|I| = 1$, assume that $I = \\{t\\}$. Then there is a valid ordering if and only if the set $\\{1 \\le i \\le k: Z_i \\cap S \\ne \\varnothing\\}$ coincides with $[1, \\, t]$ or $[t, \\, k]$; or if such set is $\\{t\\}$ and also $Z_0$ is empty. In the first case (the other cases are analogous), the unique valid ordering (up to reversal) is given by: $Z_0, \\, Z_1, \\, Z_2, \\, \\dots, \\, Z_{t - 1}, \\, Z_t', \\, Z_t' ', \\, Z_{t + 1}, \\, \\dots, \\, Z_k.$ $Z_0, \\, Z_1, \\, Z_2, \\, \\dots, \\, Z_{t - 1}, \\, Z_t', \\, Z_t' ', \\, Z_{t + 1}, \\, \\dots, \\, Z_k.$ The lemma teaches us how to handle a single component (of course, one has to compute also the number of possible orderings of each equivalence class, which is just the factorial of its size). What about the interaction between components? It is not hard to check that if $\\mathcal C, \\, \\mathcal D$ are two distinct connected components then either $P(\\mathcal C) \\cap P(\\mathcal D) = \\varnothing$ or $P(\\mathcal C) \\subseteq P(\\mathcal D)$ or $P(\\mathcal D) \\subseteq P(\\mathcal C)$. Moreover, if $P(\\mathcal C) = P(\\mathcal D)$ then either $\\mathcal C$ or $\\mathcal D$ contains only one subset. Let us consider the forest on the connected components such that $\\mathcal C$ is an ancestor of $\\mathcal D$ if and only if $P(\\mathcal D) \\subseteq P(\\mathcal C)$ (if $P(\\mathcal C) = P(\\mathcal D)$ then we require additionally that $\\mathcal C$ contains only one subset). It is not hard to check that this ancestorship is induced by a forest. By adding (if necessary) to the initial family the subset $S_{k + 1} = \\{1, \\, 2, \\, \\dots, \\, n\\}$, we may assume that this forest is a tree. The number of valid permutations is given by the product of the contributions of each connected component $\\mathcal C$. The contribution of a connected component $\\mathcal C$ is the product of the contributions of the equivalence classes of $P(\\mathcal C)$ (and, if there is more than one equivalence class, a factor $2$). Given an equivalence class $E$ of $P(\\mathcal C)$, its contribution is the factorial of $|P(\\mathcal C)| - \\sum_{\\substack{\\mathcal D \\in \\text{sons}(\\mathcal C) \\\\ P(\\mathcal D)\\subseteq E}} \\big(|P(\\mathcal D)|-1\\big).$ Complexity: $O\\left(\\frac{k^2n}{64}\\right)$ (using bitsets to store the subsets and implementing everything naively).",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef unsigned long long ULL;\n#define SZ(x) ((int)((x).size()))\n \n// Returns the time elapsed in nanoseconds from 1 January 1970, at 00:00:00.\nLL get_time() {\n    return chrono::duration_cast<chrono::nanoseconds>(\n        chrono::steady_clock::now().time_since_epoch())\n        .count();\n}\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \n \nconst LL mod = 998244353;\nconst int MAXN = 100;\nconst int MAXM = 100;\ntypedef bitset<MAXN> Subset;\n \nint N;\nbool visited[MAXM];\nvector<int> aa[MAXM];\nint M;\nSubset S[MAXM];\nbool dfs(int v, vector<Subset>& E) {\n    visited[v] = true;\n    \n    string intersection_type(E.size(), '-');\n    Subset A = S[v];\n    for (int i = 0; i < SZ(E); i++) {\n        Subset inter = A & E[i];\n        if (inter.none()) intersection_type[i] = '0';\n        else if (inter != E[i]) intersection_type[i] = '1';\n        else intersection_type[i] = '2';\n        A = A & ~inter;\n    }\n    \n    bool is_prefix = regex_match(intersection_type, regex(\"2*1?0*\"));\n    bool is_suffix = regex_match(intersection_type, regex(\"0*1?2*\"));\n    bool is_interval = regex_match(intersection_type, regex(\"0*1?2*1?0*\"));\n \n    if (!is_interval) return false;\n    if (!is_prefix and !is_suffix and A.any()) return false;\n \n    if (!is_suffix and A.any()) {\n        reverse(E.begin(), E.end());\n        reverse(intersection_type.begin(), intersection_type.end());\n    }\n    \n    if (A.any()) {\n        E.push_back(A);\n        intersection_type += '2';\n    }\n \n    for (int i = SZ(E)-1; i >= 0; i--) {\n        if (intersection_type[i] == '1') {\n            Subset e1 = S[v] & E[i];\n            Subset e2 = E[i] & ~S[v];\n            E.erase(E.begin() + i);\n            if (i >= 1 and intersection_type[i-1] != '0') {\n                E.insert(E.begin() + i, e2);\n                E.insert(E.begin() + i, e1);\n            } else if (i < SZ(intersection_type)-1 and intersection_type[i+1] != '0') {\n                E.insert(E.begin() + i, e1);\n                E.insert(E.begin() + i, e2);\n            } else assert(0);\n        }\n    }\n    \n    for (int a: aa[v]) {\n        if (visited[a]) continue;\n        if (!dfs(a, E)) return false;\n    }\n    return true;\n}\n \nLL solve() {\n    for (int i = 0; i < M; i++) aa[i].clear(), visited[i] = false;\n    \n    for (int i = 0; i < M; i++) {\n        for (int j = i+1; j < M; j++) {\n            Subset inter = S[i]&S[j];\n            if (inter.any() and inter != S[i] and inter != S[j]) {\n                aa[i].push_back(j);\n                aa[j].push_back(i);\n            }\n        }\n    }\n    typedef pair<Subset, vector<Subset>> psvs;\n    vector<psvs> equiv;\n    for (int i = 0; i < M; i++) {\n        if (visited[i]) continue;\n        vector<Subset> E;\n        if (!dfs(i, E)) return 0;\n        Subset PP;\n        for (auto e: E) PP |= e;\n        equiv.push_back({PP, E});\n    }\n    Subset full_set;\n    for (int i = 0; i < N; i++) full_set[i] = 1;\n    equiv.emplace_back(full_set, vector<Subset>{full_set});\n \n    sort(equiv.begin(), equiv.end(), [&](const psvs& A, const psvs& B) {\n        if (A.first.count() != B.first.count()) return A.first.count() > B.first.count();\n        return A.second.size() < B.second.size();\n    });\n \n    LL res = 1;\n    for (int i = 0; i < SZ(equiv); i++) {\n        if (equiv[i].second.size() >= 2) res *= 2;\n        for (Subset A: equiv[i].second) {\n            int cnt = A.count();\n            for (int j = i+1; j < SZ(equiv); j++) {\n                Subset P = equiv[j].first;\n                if ((P & A) == P) {\n                    cnt -= P.count() - 1;\n                    A &= ~P;\n                }\n            }\n            for (int m = 1; m <= cnt; m++) res = res * m % mod;\n        }\n    }\n    return res;\n}\n \n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); // Remove in problems with online queries!\n    \n    cin >> N >> M;\n    for (int i = 0; i < M; i++) {\n        int q;\n        cin >> q;\n        for (int j = 0; j < q; j++) {\n            int s;\n            cin >> s;\n            S[i][s-1] = 1;\n        }\n    }\n \n    cout << solve() << \"\\n\";\n}",
    "tags": [
      "dfs and similar",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1553",
    "index": "A",
    "title": "Digits Sum",
    "statement": "Let's define $S(x)$ to be the sum of digits of number $x$ written in decimal system. For example, $S(5) = 5$, $S(10) = 1$, $S(322) = 7$.\n\nWe will call an integer $x$ \\textbf{interesting} if $S(x + 1) < S(x)$. In each test you will be given one integer $n$. Your task is to calculate the number of integers $x$ such that $1 \\le x \\le n$ and $x$ is interesting.",
    "tutorial": "Let's think: what properties do all interesting numbers have? Well, if a number $x$ does not end with $9$, we can say for sure that $f(x+1) = f(x) + 1$, because the last digit will get increased. What if the number ends with $9$? Then the last digit will become $0$, so, no matter what happens to other digits, we can say that $f(x+1)$ will surely be less than $f(x)$. So the problem asks us to count all numbers $1 \\le x \\le n$ with the last digit equal to $9$. It is not hard to see that the answer is equal to $\\lfloor \\frac{n + 1}{10} \\rfloor$. This concludes the solution, as we are now able to answer all testcases in $O(1)$, resulting in total $O(t)$ runtime.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nint main() {\n    //freopen(\"input.txt\", \"r\", stdin);\n    ios_base::sync_with_stdio(false);\n    int tst;\n    cin >> tst;\n    while (tst--) {\n        int n;\n        cin >> n;\n        cout << (n + 1) / 10 << '\\n';\n    }\n}\n",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1553",
    "index": "B",
    "title": "Reverse String",
    "statement": "You have a string $s$ and a chip, which you can place onto any character of this string.\n\nAfter placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $i$, you move it to the position $i + 1$. Of course, moving the chip to the right is impossible if it is already in the last position.\n\nAfter moving the chip to the right, you move it to the left several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $i$, you move it to the position $i - 1$. Of course, moving the chip to the left is impossible if it is already in the first position.\n\nWhen you place a chip or move it, you write down the character where the chip ends up after your action. For example, if $s$ is abcdef, you place the chip onto the $3$-rd character, move it to the right $2$ times and then move it to the left $3$ times, you write down the string cdedcb.\n\nYou are given two strings $s$ and $t$. Your task is to determine whether it's possible to perform the described operations with $s$ so that you write down the string $t$ as a result.",
    "tutorial": "Let's iterate over starting positions, the number of times we go to the right and the number of times we go to the left. After that we can check that resulting string is equal to the needed one. This solution works in $O(n^4)$, since there are $O(n^3)$ possible combinations of starting position, number of moves to the right and left and each check can take up to $O(n)$ time. To optimize this solution we can notice that if we know number of moves to the right then we can recover number of moves to the left(because we know the length of needed string). So, we have $O(n^2)$ possible combinations, that's why this solution works in $O(n^3)$, which is enough to pass tests. Can you solve this problem in $O(n^2)$ time? Maybe even faster?",
    "code": "q = int(input())\nfor i in range(q):\n\ts = input()\n\tt = input()\n\tn = len(s)\n\tm = len(t)\n\tans = False\n\tfor i in range(n):\n\t\tfor j in range(0, n - i):\n\t\t\tk = m - 1 - j\n\t\t\tif i + j < k:\n\t\t\t\tcontinue                                 \n\t\t\tl1 = i\n\t\t\tr = i + j\n\t\t\tl2 = r - k                                \n\t\t\tif s[l1:r+1] + s[l2:r][::-1] == t:\n\t\t\t\tans = True\t\n\tprint('YES' if ans else 'NO')",
    "tags": [
      "brute force",
      "dp",
      "hashing",
      "implementation",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1553",
    "index": "C",
    "title": "Penalty",
    "statement": "Consider a simplified penalty phase at the end of a football match.\n\nA penalty phase consists of at most $10$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (\\textbf{note that it goes against the usual football rules}). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $7$-th kick the first team has scored $1$ goal, and the second team has scored $3$ goals, the penalty phase ends — the first team cannot reach $3$ goals.\n\nYou know which player will be taking each kick, so you have your predictions for each of the $10$ kicks. These predictions are represented by a string $s$ consisting of $10$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way:\n\n- if $s_i$ is 1, then the $i$-th kick will definitely score a goal;\n- if $s_i$ is 0, then the $i$-th kick definitely won't score a goal;\n- if $s_i$ is ?, then the $i$-th kick could go either way.\n\nBased on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that \\textbf{the referee doesn't take into account any predictions when deciding to stop the penalty phase} — you may know that some kick will/won't be scored, but the referee doesn't.",
    "tutorial": "After you have fixed the values of ? you can easily find the number of kicks needed to decide the winners in constant time. If you iterate over all possible values of ? you can get solution which works in $O(2^10 \\cdot check)$ for one testcase, which is enough to pass. The other possible solution is to notice that it's optimal to change ? of one team to 1 and to 0 for other. So you only have two candidates to check.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tstring s;\n\t\tcin >> s;\n\t\tint ans = 9;\n\t\t\n\t\t{\n\t\t\tint cnt0 = 0, cnt1 = 0;\n\t\t\tfor (int i = 0; i < 10; ++i) {\n\t\t\t\tif (i % 2 == 0) cnt0 += s[i] != '0';\n\t\t\t\telse cnt1 += s[i] == '1'; \n\t\t\t\tif (cnt0 > cnt1 + (10 - i) / 2) ans = min(ans, i);\n\t\t\t\tif (cnt1 > cnt0 + (9 - i) / 2) ans = min(ans, i);\n\t\t\t}\n\t\t}\n\t\t\n\t\t{\n\t\t\tint cnt0 = 0, cnt1 = 0;\n\t\t\tfor (int i = 0; i < 10; ++i) {\n\t\t\t\tif (i % 2 == 0) cnt0 += s[i] == '1';\n\t\t\t\telse cnt1 += s[i] != '0'; \n\t\t\t\tif (cnt0 > cnt1 + (10 - i) / 2) ans = min(ans, i);\n\t\t\t\tif (cnt1 > cnt0 + (9 - i) / 2) ans = min(ans, i);\n\t\t\t}\n\t\t}\n\t\t\n\t\tcout << ans + 1 << '\\n';\n\t}\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1553",
    "index": "D",
    "title": "Backspace",
    "statement": "You are given two strings $s$ and $t$, both consisting of lowercase English letters. You are going to type the string $s$ character by character, from the first character to the last one.\n\nWhen typing a character, instead of pressing the button corresponding to it, you can press the \"Backspace\" button. It deletes the last character you have typed among those that aren't deleted yet (or does nothing if there are no characters in the current string). For example, if $s$ is \"abcbd\" and you press Backspace instead of typing the first and the fourth characters, you will get the string \"bd\" (the first press of Backspace deletes no character, and the second press deletes the character 'c'). Another example, if $s$ is \"abcaa\" and you press Backspace instead of the last two letters, then the resulting text is \"a\".\n\nYour task is to determine whether you can obtain the string $t$, if you type the string $s$ and press \"Backspace\" instead of typing several (maybe zero) characters of $s$.",
    "tutorial": "The main idea of the problem is that backspace results in losing $2$ characters, the one we intended to type (which we replace with a backspace) and the character that the backspace will remove. In general, the idea is to compare every letter $s_i$ with $t_j$ starting from right to left, if they match we will move to compare $s_{i-1}$ with $t_{j-1}$ in the next step, else if they don't match we will delete $s_{i}$ and $s_{i-1}$, then compare $s_{i-2}$ with $t_j$ in the next step and so on. If we successfully matched all characters in $t$ we will print $YES$, $NO$ otherwise.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\n#include <chrono>\n#include <random>\n#include <bitset>\nusing namespace std;\n\n#ifdef LOCAL\n\t#define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr);\n#else\n\t#define eprintf(...) 42\n#endif\n\nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\nll myRand(ll B) {\n\treturn (ull)rng() % B;\n}\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n\nclock_t startTime;\ndouble getCurrentTime() {\n\treturn (double)(clock() - startTime) / CLOCKS_PER_SEC;\n}\n\nconst int N = 200200;\nint n, m;\nchar s[N], t[N];\n\nbool solve() {\n\tscanf(\"%s %s\", s, t);\n\tn = strlen(s);\n\tm = strlen(t);\n\tif (n < m) return false;\n\tint p = (n - m) & 1;\n\tint q = 0;\n\tint k = 0;\n\tfor (int i = p; i < n; i++) {\n\t\tif (k == 1) {\n\t\t\tk = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (q < m && s[i] == t[q]) {\n\t\t\tq++;\n\t\t} else {\n\t\t\tk++;\n\t\t}\n\t}\n\treturn q == m;\n}\n\nint main()\n{\n\tstartTime = clock();\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n\n\tint T;\n\tscanf(\"%d\", &T);\n\twhile(T--) {\n\t\tif (solve())\n\t\t\tprintf(\"YES\\n\");\n\t\telse\n\t\t\tprintf(\"NO\\n\");\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "greedy",
      "strings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1553",
    "index": "E",
    "title": "Permutation Shift",
    "statement": "An identity permutation of length $n$ is an array $[1, 2, 3, \\dots, n]$.\n\nWe performed the following operations to an identity permutation of length $n$:\n\n- firstly, we cyclically shifted it to the right by $k$ positions, where $k$ is unknown to you (the only thing you know is that $0 \\le k \\le n - 1$). When an array is cyclically shifted to the right by $k$ positions, the resulting array is formed by taking $k$ last elements of the original array (without changing their relative order), and then appending $n - k$ first elements to the right of them (without changing relative order of the first $n - k$ elements as well). For example, if we cyclically shift the identity permutation of length $6$ by $2$ positions, we get the array $[5, 6, 1, 2, 3, 4]$;\n- secondly, we performed the following operation \\textbf{at most} $m$ times: pick any two elements of the array and swap them.\n\nYou are given the values of $n$ and $m$, and the resulting array. Your task is to find all possible values of $k$ in the cyclic shift operation.",
    "tutorial": "Let's decrease all numbers by $1$ and start the numeration from $0$, because cyclic shifts are very easy to describe this way. Let's observe for $n = 4$: $k = 0$. $p = [0, 1, 2, 3]$. So, $p_i = i$. $k = 1$. $p = [3, 0, 1, 2]$. So, $p_i = (i-1) \\bmod n$. ... Continuing this process, we verify that indeed, $p_i = (i-k) \\bmod n$. Very simple! Now suppose we have some value $0 \\le k \\le n - 1$ and we want to check if it is possible to obtain $p$ from $k$-th cyclic shift by doing at most $m$ swaps. For this, we can calculate the minimum number of swaps and check it is not more than $m$. So, how to calculate the minimum number of swaps needed to transform a permutation $a$ to another permutation $b$? This is actually a well-known problem. The idea is, we build a graph with undirected edges $(a_i, b_i)$. The minimum number of swaps will be equal to $n - c$, where $c$ is equal to the number of connected components in the resulting graph. Nice, now we can check if some $k$ is good in $O(n)$ time. But we can't check all of them, right? Here comes the crucial observation: Suppose you get a permutation $a$ after a cyclic shift. Then you make at most $m$ swaps and obtain $b$. This means at most $2 \\cdot m$ numbers will be out of order! That is, there will be at least $n - 2 \\cdot m$ indices $i$ such that $a_i = b_i$. So can we calculate the number $cnt_k$ - the count of integers in position for each cyclic shift $k$? Yes, we can! For an arbitrary $i$, there is exactly one $k$ such that $p_i = (i-k) \\bmod n$. But wait, it means there are in total only $n$ good positions because $\\sum cnt_i = n$! And we check only those $k$ for which it is true that $cnt_k \\ge n - 2 \\cdot m$. Remember that weird constraint $m \\le \\frac{n}{3}$? Well, turns out there are at most $\\frac{n}{n - \\frac{2n}{3}} = 3$ different $k$ to consider! So we know we check at most $3$ different values and we know how to check in $O(n)$ time. That concludes the solution. The time and space complexities are $O(n)$.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std; \n\nint cycle_count(vector<int> q, int n)\n{\n \tfor(int i = 0; i < n; i++)\n \t\tq[i]--;\n \tvector<int> used(n);\n \tint ans = 0;\n \tfor(int i = 0; i < n; i++)\n \t{\n \t\tif(used[i] == 1) continue;\n \t\tint j = i;\n \t\twhile(used[j] == 0)\n \t\t{\n \t\t \tused[j] = 1;\n \t\t \tj = q[j];\n \t\t}\n \t\tans++;\n \t}\n \treturn ans;\n}\n\nbool check(int n, int m, int k, vector<int> p)\n{\n \tvector<int> q;\n \tfor(int i = k; i < n; i++)\n \t\tq.push_back(p[i]);\n \tfor(int i = 0; i < k; i++)\n \t\tq.push_back(p[i]);\n \treturn n - cycle_count(q, n) <= m;\n}\n\nvoid solve()\n{\n \tint n, m;\n \tscanf(\"%d %d\", &n, &m);\n \tvector<int> p(n);\n \tfor(int i = 0; i < n; i++)\n \t\tscanf(\"%d\", &p[i]);\n \tvector<int> cnt(n);\n \tfor(int i = 0; i < n; i++)\n \t{\n \t \tint offset = i + 1 - p[i];\n \t \tif(offset < 0)\n \t \t\toffset += n;\n \t \tcnt[offset]++;\n \t}\n \tvector<int> ans;\n \tfor(int i = 0; i < n; i++)\n \t\tif(cnt[i] + 2 * m >= n && check(n, m, i, p))\n \t\t\tans.push_back(i);\n \tprintf(\"%d\", ans.size());\n \tfor(auto x : ans) printf(\" %d\", x);\n \tputs(\"\");\n \t\t\t\n}\n\nint main()\n{\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tsolve(); \t\n\t}\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1553",
    "index": "F",
    "title": "Pairwise Modulo",
    "statement": "You have an array $a$ consisting of $n$ distinct positive integers, numbered from $1$ to $n$. Define $p_k$ as $$p_k = \\sum_{1 \\le i, j \\le k} a_i \\bmod a_j,$$ where $x \\bmod y$ denotes the remainder when $x$ is divided by $y$. You have to find and print $p_1, p_2, \\ldots, p_n$.",
    "tutorial": "First of all, we have to get rid of the mod operation. The following formula helps very much: $x \\bmod y = x - y \\cdot \\lfloor \\frac{x}{y} \\rfloor$. Since the sum is hard to deal with, we will divide it into two separate sums $s_k$ and $t_k$ defined as: $s_k = \\sum_{1 \\le i, j \\le k, i > j} (a_i \\bmod a_j),$ $t_k = \\sum_{1 \\le i, j \\le k, i < j} (a_i \\bmod a_j).$ How to calculate $s_k$? Well, we know that $s_k = s_{k-1} + \\sum_{i=1}^{k-1} (a_k \\bmod a_i) = s_{k-1} + \\sum_{i=1}^{k-1} (a_k - a_i \\cdot \\lfloor \\frac{a_k}{a_i} \\rfloor)$. Take $a_k$ out of the sum and you get $s_k = s_{k-1} + a_k \\cdot (k-1) - \\sum_{i=1}^{k-1} (a_i \\cdot \\lfloor \\frac{a_k}{a_i} \\rfloor)$. So, it is still not clear how to calculate it fast. Let's turn things around. Fix some arbitrary $a_i$ and try to calculate its contribution to all $s_k$ where $k > i$. For all $a_k$ in range $[a_i, 2 \\cdot a_i)$ the contribution is $-a_i$. For all $a_k$ in range $[2 \\cdot a_i, 3 \\cdot a_i)$ the contribution is $-2 \\cdot a_i$. ... For all $a_k$ in range $[d \\cdot a_i, (d+1) \\cdot a_i)$ the contribution is $-d \\cdot a_i$. This means we can just brute force all reasonable $d$ and perform updates of the kind: add $x$ to all numbers in range $[l, r]$ which is clearly possible using segment tree or Fenwick tree which allows range updates and point queries. The only question is: how fast is this? Denote $M$ as $3 \\cdot 10^5$. Remember the constraint that all $a_i$ are distinct? It means in the worst-case scenario we will have $\\frac{M}{1} + \\ldots + \\frac{M}{n} = M \\cdot (\\frac{1}{1} + \\ldots + \\frac{1}{n})$ updates. The summation inside the brackets is known as a Harmonic number which is bounded by $O(\\log n)$. So we have $O(M \\log n)$ updates. Each update takes $O(\\log M)$ time, thus the overall time to calculate $s_k$ is $O(M \\log M \\log n)$. Not bad. Will we be able to calculate $t_k$ with the same efficiency though? Well, the only difference between $s_k$ and $t_k$ is the order of indices, so the solution should be almost the same, right? Exactly. But this time, instead of having range updates and point queries, we will have to deal with point updates and range queries. Let's get into details. $t_k = t_{k-1} + \\sum_{i=1}^{k-1} (a_i \\bmod a_k) = t_{k-1} + \\sum_{i=1}^{k-1} (a_i - a_k \\cdot \\lfloor \\frac{a_i}{a_k} \\rfloor)$. Separate $a_i$ and you get $t_k = t_{k-1} + \\sum_{i=1}^{k-1}a_i - \\sum_{i=1}^{k-1} (a_k \\cdot \\lfloor \\frac{a_i}{a_k} \\rfloor)$. Almost the same thing. This time, we will go over all multiples of $a_k$: All $a_i$ in range $[a_k, 2 \\cdot a_k)$ contribute $-a_k$. All $a_i$ in range $[2 \\cdot a_k, 3 \\cdot a_k)$ contribute $-2 \\cdot a_k$. ... All $a_i$ in range $[d \\cdot a_k, (d+1) \\cdot a_k)$ contribute $-d \\cdot a_k$. It should be crystal clear by now that we are dealing with point updates and range queries here. The time complexity is the same. So, in total we get $O(M \\log M \\log n)$ time complexity and $O(n + M)$ space complexity. Be careful with segment trees, though. Using the classical recursive segment tree with pushes will probably result in a big constant and time out. Just remember that we are not dealing with advanced stuff there, so there is no need for pushes.",
    "code": "// chrono::system_clock::now().time_since_epoch().count()\n#include <bits/stdc++.h>\n\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define sz(x) (int)(x).size()\n#define rep(i, a, b) for (int i = (a); i < (b); ++i)\n#define debug(x) cerr << #x << \" = \" << x << endl\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef vector<int> vi;\n\nconst int M = (int)3e5;\n\nnamespace A {\n    ll t[M * 4];\n\n    void update(int l, int r, ll x, int v = 1, int tl = 1, int tr = M) {\n        if (l > r || tl > r || tr < l) {\n            return;\n        }\n\n        if (l <= tl && tr <= r) {\n            t[v] += x;\n            return;\n        }\n\n        int mid = (tl + tr) >> 1;\n        int c1 = (v << 1), c2 = (c1 | 1);\n\n        update(l, r, x, c1, tl, mid);\n        update(l, r, x, c2, mid + 1, tr);\n    }\n\n    ll get(int p, int v = 1, int tl = 1, int tr = M) {\n        if (tl == tr) {\n            return t[v];\n        }\n\n        int mid = (tl + tr) >> 1;\n        int c1 = (v << 1), c2 = (c1 | 1);\n\n        if (p <= mid) {\n            return t[v] + get(p, c1, tl, mid);\n        }\n        else {\n            return t[v] + get(p, c2, mid + 1, tr);\n        }\n    }\n}\n\nnamespace B {\n    ll t[M * 4];\n\n    void update(int p, ll x, int v = 1, int tl = 1, int tr = M) {\n        if (tl == tr) {\n            t[v] += x;\n            return;\n        }\n\n        int mid = (tl + tr) >> 1;\n        int c1 = (v << 1), c2 = (c1 | 1);\n\n        if (p <= mid) {\n            update(p, x, c1, tl, mid);\n        }\n        else {\n            update(p, x, c2, mid + 1, tr);\n        }\n\n        t[v] = t[c1] + t[c2];\n    }\n\n    ll get(int l, int r, int v = 1, int tl = 1, int tr = M) {\n        if (l > r || tl > r || tr < l) {\n            return 0ll;\n        }\n\n        if (l <= tl && tr <= r) {\n            return t[v];\n        }\n\n        int mid = (tl + tr) >> 1;\n        int c1 = (v << 1), c2 = (c1 | 1);\n\n        return get(l, r, c1, tl, mid) + get(l, r, c2, mid + 1, tr);\n    }\n}\n\nint n;\n\nvoid solve() {\n    cin >> n;\n    ll pref = 0, ans = 0;\n\n    rep (i, 1, n + 1) {\n        int x;\n        cin >> x;\n        ans += x * (i - 1ll);\n        ans += A::get(x);\n        ans += pref;\n        pref += x;\n        \n        for (int j = x; j <= M; j += x) {\n            int l = j, r = min(M, j + x - 1);\n            ans -= x * B::get(l, r) * (j / x);\n            A::update(l, r, -x * (j / x));\n        }\n\n        B::update(x, 1);\n        cout << ans << \" \\n\"[i == n];\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    int tt = 1;\n\n    for (int i = 1; i <= tt; ++i) {\n        solve();\n    }\n\n    return 0;\n}",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1553",
    "index": "G",
    "title": "Common Divisor Graph",
    "statement": "Consider a sequence of distinct integers $a_1, \\ldots, a_n$, each representing one node of a graph. There is an edge between two nodes if the two values are not coprime, i. e. they have a common divisor greater than $1$.\n\nThere are $q$ queries, in each query, you want to get from one given node $a_s$ to another $a_t$. In order to achieve that, you can choose an existing value $a_i$ and create new value $a_{n+1} = a_i \\cdot (1 + a_i)$, with edges to all values that are not coprime with $a_{n+1}$. Also, $n$ gets increased by $1$. You can repeat that operation multiple times, possibly making the sequence much longer and getting huge or repeated values. What's the minimum possible number of newly created nodes so that $a_t$ is reachable from $a_s$?\n\nQueries are independent. In each query, you start with the initial sequence $a$ given in the input.",
    "tutorial": "tl;dr - Find initial CCs. Then for every $a_i$, find prime divisors of $a_i+1$ and draw new edges of cost 1 between each pair of those primes, and between $a_i$ and those primes. Part 1, notation and observations Two numbers are not coprime iff they have a common prime divisor. Let $P(x)$ denote distinct prime divisors of $x$. For example $P(100) = \\{2, 5\\}$. You can run prime sieve to find $P(x)$ for all $x \\in [2, 10^6 + 1]$. Useful interpretation: Creating $a_i \\cdot (a_i + 1)$ is like creating $(a_i + 1)$ and drawing an extra edge between $a_i$ and $(a_i + 1)$. Observation: answer doesn't exceed two because you can move between even values. If the starting node isn't even, use one operation to create $a_s + 1$. If the target node isn't even, use one operation to create $a_t + 1$. Now you can move between them. So we just need to check if answer is 0 or 1. Part 2, checking if answer is 0 Let's find CCs (connected components) of the initial graph. Creates a node for each prime, even if it's not in the input. For each $a_i$, connect it to all values from $P(a_i)$. Use DFS or DSU to find CCs. Given a query, check if two nodes belong to the same CC. If so, the answer is 0. Part 3, checking if answer is 1. Let's say that $a_s$ and $a_t$ belong to two different CC, denoted cc1 and cc2. The answer is 1 in three cases: we spend one operation on a node from cc1, or a node from cc2, or a node from a completely different CC. The last case is needed e.g. for input $n = 3$, $a = (3, 7, 20)$. You need to replicate $20$ into $21$ in order to make $3$ and $7$ reachable from one another. For every $a_i$, let's consider replicating it into $a_i + 1$. Let's draw new edges of cost 1 between CC of $a_i$ and all CCs of values $P(a_i + 1)$. In the drawing, gray areas are initial CCs. Green edges have cost 1. For example, 9 can create 10, so we connect the whole CC with (9, 21, 27, 33) with the whole CC of prime 5, which contains the input value (25). You can't get from 169 to 9 with cost though. That would be possible if 25 replicated into 26 would be connected to both (9, 21, 27, 33) and to (169). To consider such cases, we need to draw green edges between all pairs of $P(a_i + 1)$ too. For example, if $a_i = 9$, then $P(a_i + 1) = \\{2, 5\\}$ so we draw green edges 2-5, 2-3, 3-5. Given a query, check if there is a green edge between the two CCs. If so, the answer is 1. - (should be in spoiler tags) A note about the worst case and preparing tests. One type of max tests is created by choosing $n$ values $x \\leq 10^6$ with most distinct prime divisors of $x + 1$. With few exceptions, that means four or five primes, e.g. $2 \\cdot 3 \\cdot 5 \\cdot 7 \\cdot 11 = 2310$, and on average $5 \\cdot 4 / 2 = 10$ edges of cost 1. It could happen though that choosing such values yields a small number of CCs and thus the solution is actually faster. What if there are some other tests that will make the intended solution significantly slower? In particular, only one CC would mean no edges at all. To check that, we run the intended solution and modified the code of \"edges of cost 1\" part to pretend that all numbers $a_i$ are coprime. That requires around 1'700'000 inserts to a set and takes less than 1 second. It's much faster if you use vector and then sort it. This \"pretend\" part couldn't be used in the testset but it was needed to see that the intended solution can for sure solve any test within TL.",
    "code": "// gcd, AC, O((N+Q) * log^2), by Errichto\n#include <bits/stdc++.h>\nusing namespace std;\n#define sim template < class c\n#define ris return * this\n#define dor > debug & operator <<\n#define eni(x) sim > typename \\\n  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {\nsim > struct rge { c b, e; };\nsim > rge<c> range(c i, c j) { return rge<c>{i, j}; }\nsim > auto dud(c* x) -> decltype(cerr << *x, 0);\nsim > char dud(...);\nstruct debug {\n#ifdef LOCAL\n~debug() { cerr << endl; }\neni(!=) cerr << boolalpha << i; ris; }\neni(==) ris << range(begin(i), end(i)); }\nsim, class b dor(pair < b, c > d) {\n  ris << \"(\" << d.first << \", \" << d.second << \")\";\n}\nsim dor(rge<c> d) {\n  *this << \"[\";\n  for (auto it = d.b; it != d.e; ++it)\n\t*this << \", \" + 2 * (it == d.b) << *it;\n  ris << \"]\";\n}\n#else\nsim dor(const c&) { ris; }\n#endif\n};\n#define imie(...) \" [\" << #__VA_ARGS__ \": \" << (__VA_ARGS__) << \"] \"\n// debug & operator << (debug & dd, P p) { dd << \"(\" << p.x << \", \" << p.y << \")\"; return dd; }\n\nstruct DSU {\n\tvector<int> parent;\n\tDSU(int m) {\n\t\tparent.resize(m + 1);\n\t\tfor(int i = 0; i <= m; ++i) {\n\t\t\tparent[i] = i;\n\t\t}\n\t}\n\tint find(int a) {\n\t\tif(a == parent[a]) {\n\t\t\treturn a;\n\t\t}\n\t\treturn parent[a] = find(parent[a]);\n\t}\n\tvoid uni(int a, int b) {\n\t\tparent[find(a)] = find(b);\n\t}\n};\n\nint main() {\n\t// 1) read input\n\tint n, q;\n\tscanf(\"%d%d\", &n, &q);\n\tvector<int> a(n);\n\tfor(int i = 0; i < n; ++i) {\n\t\tscanf(\"%d\", &a[i]);\n\t}\n\tint m = *max_element(a.begin(), a.end());\n\t// 2) prime sieve\n\tvector<vector<int>> prime_divisors(m + 2);\n\tfor(int p = 2; p <= m + 1; ++p) {\n\t\tif(prime_divisors[p].empty()) {\n\t\t\tfor(int j = p; j <= m + 1; j += p) {\n\t\t\t\tprime_divisors[j].push_back(p);\n\t\t\t}\n\t\t}\n\t}\n\t// 3) DSU, find initial connected components\n\tDSU dsu(m + 2);\n\tfor(int x : a) {\n\t\tfor(int p : prime_divisors[x]) {\n\t\t\tdsu.uni(x, p);\n\t\t}\n\t}\n\t// 4) DSU, find edges of cost 1\n\tset<pair<int,int>> edges;\n\tfor(int x : a) {\n\t\tvector<int> nodes = prime_divisors[x+1];\n\t\tnodes.push_back(x);\n\t\tfor(int& node : nodes) {\n\t\t\tnode = dsu.find(node);\n\t\t}\n\t\tfor(int i = 0; i < (int) nodes.size(); ++i) {\n\t\t\tfor(int j = i + 1; j < (int) nodes.size(); ++j) {\n\t\t\t\tint one = nodes[i];\n\t\t\t\tint two = nodes[j];\n\t\t\t\tif(one != two) {\n\t\t\t\t\tif(one > two) {\n\t\t\t\t\t\tswap(one, two);\n\t\t\t\t\t}\n\t\t\t\t\tedges.insert({one, two});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdebug() << imie(edges);\n\tcerr << imie(edges.size()) << endl;\n\t// 5) answer queries\n\twhile(q--) {\n\t\tint s, t;\n\t\tscanf(\"%d%d\", &s, &t);\n\t\t--s;\n\t\t--t;\n\t\ts = dsu.find(a[s]);\n\t\tt = dsu.find(a[t]);\n\t\tif(s == t) {\n\t\t\tputs(\"0\");\n\t\t}\n\t\telse if(edges.count({min(s, t), max(s, t)})) {\n\t\t\tputs(\"1\");\n\t\t}\n\t\telse {\n\t\t\tputs(\"2\");\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dsu",
      "graphs",
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1553",
    "index": "H",
    "title": "XOR and Distance",
    "statement": "You are given an array $a$ consisting of $n$ distinct elements and an integer $k$. Each element in the array is a non-negative integer not exceeding $2^k-1$.\n\nLet's define the XOR distance for a number $x$ as the value of\n\n$$f(x) = \\min\\limits_{i = 1}^{n} \\min\\limits_{j = i + 1}^{n} |(a_i \\oplus x) - (a_j \\oplus x)|,$$\n\nwhere $\\oplus$ denotes the bitwise XOR operation.\n\nFor every integer $x$ from $0$ to $2^k-1$, you have to calculate $f(x)$.",
    "tutorial": "There are two main approaches to this problem, both of them utilize the same data structure - a trie. But not the usual trie. We will build a trie with each node storing the following four values. Let the interval represented by a node be $[L, R)$, then the values are: $minval$ - minimum existing value in the segment relative to $L$, so, for example, if $L = 4$ and the minimum number in the segment is $5$, then $minval = 1$; $maxval$ - maximum existing value in the segment. Relative to $L$ as well; $ans$ - the minimum distance between two existing values in the subtree; $len$ - the size of the segment represented by the node. We build this structure for $x = 0$, so we just add all the values of the original array into the trie. What happens to this structure when we flip some bit $x$? Let's say that the bit $k-1$ is flipped. It means that we have to swap the left child and the right child of the root of the trie. If we flip the bit $k-2$, we need to swap the neighboring nodes in this trie on depth $2$, and so on. When we flip the $k-i$-th bit, it means that we have to rebuild the first $i + 1$ layers of the trie, which have $2^{i+1} - 1$ nodes. So we need to iterate through all possible values of $x$ while rebuilding the data structure in some way that our rebuilds are not too costly. One of the ways to do it is to use Gray code. If we iterate on $x$ using a variation of Gray code where we start from most significant bits instead of the least significant bits, the bit $k-1$ will be swapped $2^{k-1}$ times (and the total rebuild time for these swaps will be $2^{k-1} \\cdot 3 < 2^{k+1}$), the bit $k-2$ will be swapped $2^{k-2}$ times (and the total rebuild time for these swaps will be $2^{k-2} \\cdot 7 < 2^{k+1}$), and so on. So, the total rebuild time for the whole process will be $O(2^k \\cdot k)$. Brief description of the second approach: for each node, we can store multiple versions of that node. A version of a node is another node which represents the same subtree having all of the numbers XOR'ed by some number $x$. We can see that if we try to XOR all numbers of a node representing a segment of size $4$ by, for example, $8$, nothing changes, and if we try to XOR all numbers by, for example, $11$, the result for this subtree will be the same as if we XOR it by $3$. So, for a subtree of size $m$, we store $m$ versions of it, so the whole structure contains $2^k \\cdot k$ versions of nodes.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = int(1e9);\nconst int K = 20;\n\nstruct node\n{\n \tint max_val, min_val, ans, len;\n \t\n \tnode(const node& left, const node& right)\n \t{\n \t\tlen = left.len + right.len;\n \t\tmax_val = max(left.max_val, right.max_val + left.len);\n \t\tmin_val = min(left.min_val, right.min_val + left.len);\n \t \tans = min(min(left.ans, right.ans), min(INF, right.min_val - left.max_val + left.len));\n \t}\n\n \tnode(int x)\n \t{\n \t \tans = INF;\n \t \tlen = 1;\n \t \tif(x == 1)\n \t \t \tmax_val = min_val = 0;\n \t \telse\n \t \t{\n \t \t \tmax_val = -INF;\n \t \t \tmin_val = INF;\n \t \t}\n \t}\n\n \tnode() {};\n};\n\nint cnt[1 << K];\nvector<node> tree[2 << K];\t\n\nvoid build(int v, int l, int r)\n{\n\ttree[v].resize(r - l);\n \tif(l == r - 1)\n \t{\n \t\ttree[v][0] = node(cnt[l]);\t\n \t}\n \telse\n \t{\n \t \tint m = (l + r) / 2;\n \t \tbuild(v * 2 + 1, l, m);\n \t \tbuild(v * 2 + 2, m, r);\n \t \tfor(int i = 0; i < m - l; i++)\n \t \t{\n \t \t\ttree[v][i] = node(tree[v * 2 + 1][i], tree[v * 2 + 2][i]);\n \t \t\ttree[v][i + (m - l)] = node(tree[v * 2 + 2][i], tree[v * 2 + 1][i]); \t\n \t \t}\n \t}\n}\n\nint main()\n{            \n\tint n, k;\n\tscanf(\"%d %d\", &n, &k);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint x;\n\t \tscanf(\"%d\", &x);\n\t \tcnt[x]++;\n\t}\n\tint m = 1 << k;\n\tbuild(0, 0, m);\n\tfor(int i = 0; i < m; i++)\n\t\tprintf(\"%d \", tree[0][i].ans);\n\tputs(\"\");\n}",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1553",
    "index": "I",
    "title": "Stairs",
    "statement": "For a permutation $p$ of numbers $1$ through $n$, we define a stair array $a$ as follows: $a_i$ is length of the longest segment of permutation which contains position $i$ and is made of consecutive values in sorted order: $[x, x+1, \\ldots, y-1, y]$ or $[y, y-1, \\ldots, x+1, x]$ for some $x \\leq y$. For example, for permutation $p = [4, 1, 2, 3, 7, 6, 5]$ we have $a = [1, 3, 3, 3, 3, 3, 3]$.\n\nYou are given the stair array $a$. Your task is to calculate the number of permutations which have stair array equal to $a$. Since the number can be big, compute it modulo $998\\,244\\,353$. Note that this number can be equal to zero.",
    "tutorial": "First of all, we need to transform the stair array into some other structure. Let's show that for each number, there is only one longest stair covering it, and these longest stairs are disjoint. Suppose that some number $x$ belongs to two different ascending stairs. We can easily expand these stairs to the left and to the right and find the longest ascending stair covering the number. So, it means that the longest ascending stair covering a number is unique. The same for descending stairs. Now suppose that some number $x$ belongs to an ascending stair of length $\\ge 2$ and a descending stair of length $\\ge 2$. It is impossible because it would mean that we have consecutive values $[x-1, x, x-1]$ or $[x+1, x, x+1]$ in the permutation, but since it is a permutation, all values should be distinct. So, the longest stair covering each number is unique. Let's split the stair array into this sequence of longest stairs. The first element of the stair array belongs to some stair. If $a_1 = k$, then the first $k$ elements form a stair. Let's check that all these $k$ elements are equal to $k$ and split them into a stair of length $k$, then continue the same algorithm from $a_{k+1}$. Okay, now we have an array of the lengths of the longest stairs. Each stair represents some segment of numbers, and all stairs can be enumerated by the index of their value segment. So, it looks like the number of permutations that yeild this array of longest stairs is $s! 2^{s'}$, where $s$ is the number of stairs and $s'$ is the number of stairs having length $\\ge 2$. The reasoning behind this formula is that each stair gets assigned an index corresponding to the index of its value segment in the sorted order, and for stairs of length $\\ge 2$, we can choose whether they are ascending or descending. Is that formula right? Unfortunately, no. The fact that we have the array of longest stairs means that we need to ensure that no pair of adjacent stairs merge. And there's no easy way to change this formula, unfortunately. Let's use inclusion-exclusion to eliminate all \"bad\" permutations. We have $s-1$ constraints that shouldn't be violated: stairs $1$ and $2$ shouldn't merge; stairs $2$ and $3$ shouldn't merge; ...; stairs $s-1$ and $s$ shouldn't merge. For every $i$ from $0$ to $s-1$, we can calculate the number of ways to choose $i$ constraints to be violated and a permutation that violates these constrains (and maybe some others), like in the usual inclusion-exclusion formula applications. These values can be calculated with the following dynamic programming: $dp_{n,k,t}$ is the number of ways to choose this set of $k$ violated constraints and a permutation for $n$ first stairs, and $t$ represents the type of the last stair (ascending/descending or having size $1$). What are the transitions in this dynamic programming? When placing a new stair, we may choose either to explicitly violate the constraint on merging it with the previous one (so, we transition to a state $dp_{n+1,k+1,t'}$ and maybe multiply/divide the value by $2$ if we are merging two size-$1$ stairs or merging two stairs with different types). Or we can choose to just make an entirely new stair, choosing one of $n-k+1$ values for it (since we already have $n-k$ stairs), choosing its type if its length is $\\ge 2$, and transitioning to $dp_{n+1,k,t'}$. The main drawback of this solution is that it's $O(n^2)$. Let's find a way to optimize it. Let's calculate this dynamic programming in a divide-and-conquer fashion. Let's say that for some segment $[l, r]$ of stairs, we will calculate a three-dimensional array $dp_{tl,tr,i}$ - the number of ways to violate $i$ constraints in this segment so that the leftmost stair in this segment has type $tl$, and the rightmost stair in this segment has type $tr$. Suppose we want to merge these two segments. We either merge the leftmost stair of the right segment with the rightmost stair of the left segment, or don't. Let's analyze the case when we don't merge them. Let's analyze the value of $dp_{tl, tr, i}$ in the resulting array. Suppose we violate $k$ constraints in the left segment, this leaves us to violate $i-k$ constraints in the right segment. So, the value of $dp_{tl,tr,i}$ in the resulting merged structure will be the sum of $dp_{tl,?,k}$ from the left segment multiplied by $dp_{?,tr,i-k}$ from the right segment (where $?$ can represent any type). And if we treat the values from the left and the right segment as polynomials (where value of $dp_{tl,?,k}$ or $dp_{?,tr,k}$ is the coefficient for $x^k$), merging them is exactly polynomial multiplication! So we can use FFT so speed up the merging. If we want to merge two segments while explicitly violating the constraint that the rightmost stair in the left segment and the leftmost stair in the right segment shouldn't be merged into one, it can be done with polynomial multiplication as well, but you also have to multiply the result by some coefficient that arises from merging those two stairs (if both of them had size $1$, then we multiply the result by $2$ since we can choose whether the resulting stair is ascending or descending; and if both of them had size $\\ge 1$, we divide the result by $2$ since we cannot merge an ascending stair with a descending one). So, this optimization allows us to merge two segments of length $n$ in time $O(n \\log n)$, and as the usual FFT + D&C combination, this results in a complexity of $O(n \\log^2 n)$, though with a fairly large constant factor.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define sz(a) ((int)((a).size()))\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\ntemplate<const int &MOD>\nstruct _m_int {\n\tint val;\n \n\t_m_int(int64_t v = 0) {\n\t\tif (v < 0) v = v % MOD + MOD;\n\t\tif (v >= MOD) v %= MOD;\n\t\tval = int(v);\n\t}\n \n\t_m_int(uint64_t v) {\n\t\tif (v >= MOD) v %= MOD;\n\t\tval = int(v);\n\t}\n \n\t_m_int(int v) : _m_int(int64_t(v)) {}\n\t_m_int(unsigned v) : _m_int(uint64_t(v)) {}\n \n\tstatic int inv_mod(int a, int m = MOD) {\n\t\tint g = m, r = a, x = 0, y = 1;\n \n\t\twhile (r != 0) {\n\t\t\tint q = g / r;\n\t\t\tg %= r; swap(g, r);\n\t\t\tx -= q * y; swap(x, y);\n\t\t}\n \n\t\treturn x < 0 ? x + m : x;\n\t}\n \n\texplicit operator int() const { return val; }\n\texplicit operator unsigned() const { return val; }\n\texplicit operator int64_t() const { return val; }\n\texplicit operator uint64_t() const { return val; }\n\texplicit operator double() const { return val; }\n\texplicit operator long double() const { return val; }\n \n\t_m_int& operator+=(const _m_int &other) {\n\t\tval -= MOD - other.val;\n\t\tif (val < 0) val += MOD;\n\t\treturn *this;\n\t}\n \n\t_m_int& operator-=(const _m_int &other) {\n\t\tval -= other.val;\n\t\tif (val < 0) val += MOD;\n\t\treturn *this;\n\t}\n \n\tstatic unsigned fast_mod(uint64_t x, unsigned m = MOD) {\n#if !defined(_WIN32) || defined(_WIN64)\n\t\treturn unsigned(x % m);\n#endif\n\t\t// Optimized mod for Codeforces 32-bit machines.\n\t\t// x must be less than 2^32 * m for this to work, so that x / m fits in an unsigned 32-bit int.\n\t\tunsigned x_high = unsigned(x >> 32), x_low = unsigned(x);\n\t\tunsigned quot, rem;\n\t\tasm(\"divl %4\\n\"\n\t\t\t: \"=a\" (quot), \"=d\" (rem)\n\t\t\t: \"d\" (x_high), \"a\" (x_low), \"r\" (m));\n\t\treturn rem;\n\t}\n \n\t_m_int& operator*=(const _m_int &other) {\n\t\tval = fast_mod(uint64_t(val) * other.val);\n\t\treturn *this;\n\t}\n \n\t_m_int& operator/=(const _m_int &other) {\n\t\treturn *this *= other.inv();\n\t}\n \n\tfriend _m_int operator+(const _m_int &a, const _m_int &b) { return _m_int(a) += b; }\n\tfriend _m_int operator-(const _m_int &a, const _m_int &b) { return _m_int(a) -= b; }\n\tfriend _m_int operator*(const _m_int &a, const _m_int &b) { return _m_int(a) *= b; }\n\tfriend _m_int operator/(const _m_int &a, const _m_int &b) { return _m_int(a) /= b; }\n \n\t_m_int& operator++() {\n\t\tval = val == MOD - 1 ? 0 : val + 1;\n\t\treturn *this;\n\t}\n \n\t_m_int& operator--() {\n\t\tval = val == 0 ? MOD - 1 : val - 1;\n\t\treturn *this;\n\t}\n \n\t_m_int operator++(int) { _m_int before = *this; ++*this; return before; }\n\t_m_int operator--(int) { _m_int before = *this; --*this; return before; }\n \n\t_m_int operator-() const {\n\t\treturn val == 0 ? 0 : MOD - val;\n\t}\n \n\tfriend bool operator==(const _m_int &a, const _m_int &b) { return a.val == b.val; }\n\tfriend bool operator!=(const _m_int &a, const _m_int &b) { return a.val != b.val; }\n\tfriend bool operator<(const _m_int &a, const _m_int &b) { return a.val < b.val; }\n\tfriend bool operator>(const _m_int &a, const _m_int &b) { return a.val > b.val; }\n\tfriend bool operator<=(const _m_int &a, const _m_int &b) { return a.val <= b.val; }\n\tfriend bool operator>=(const _m_int &a, const _m_int &b) { return a.val >= b.val; }\n \n\t_m_int inv() const {\n\t\treturn inv_mod(val);\n\t}\n \n\t_m_int pow(int64_t p) const {\n\t\tif (p < 0)\n\t\t\treturn inv().pow(-p);\n \n\t\t_m_int a = *this, result = 1;\n \n\t\twhile (p > 0) {\n\t\t\tif (p & 1)\n\t\t\t\tresult *= a;\n\t\t\ta *= a;\n\t\t\tp >>= 1;\n\t\t}\n \n\t\treturn result;\n\t}\n \n\tfriend ostream& operator<<(ostream &os, const _m_int &m) {\n\t\treturn os << m.val;\n\t}\n};\n \nextern const int MOD = 998244353;\nusing Mint = _m_int<MOD>;\n\nconst int LOGN = 19;\nconst int N = (1 << LOGN);\nconst int T = 2;          \nMint g = 3;\n\nvector<Mint> w[LOGN];\nvector<int> rv[LOGN];\n\nvoid precalc() {\n\tMint wb = Mint(g).pow((MOD - 1) / (1 << LOGN));\n\tforn(st, LOGN - 1) {\n\t\tw[st].assign(1 << st, 1);\n\t\tMint bw = wb.pow(1 << (LOGN - st - 1));\n\t\tMint cw = 1;\n\t\tforn(k, 1 << st) {\n\t\t\tw[st][k] = cw;\n\t\t\tcw *= bw;\n\t\t}\n\t}\n\tforn(st, LOGN) {\n\t\trv[st].assign(1 << st, 0);\n\t\tif (st == 0) {\n\t\t\trv[st][0] = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tint h = (1 << (st - 1));\n\t\tforn(k, 1 << st)\n\t\t\trv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);\n\t}\n}\n\nvoid ntt(vector<Mint> &a, bool inv) {\n\tint n = sz(a);\n\tint ln = __builtin_ctz(n);\n\tforn(i, n) {\n\t\tint ni = rv[ln][i];\n\t\tif (i < ni) swap(a[i], a[ni]);\n\t}\n\tforn(st, ln) {\n\t\tint len = 1 << st;\n\t\tfor (int k = 0; k < n; k += (len << 1)) {\n\t\t\tfore(pos, k, k + len){\n\t\t\t\tMint l = a[pos];\n\t\t\t\tMint r = a[pos + len] * w[st][pos - k];\n\t\t\t\ta[pos] = l + r;\n\t\t\t\ta[pos + len] = l - r;\n\t\t\t}\n\t\t}\n\t}\n\tif (inv) {\n\t\tMint rn = Mint(n).inv();\n\t\tforn(i, n) a[i] *= rn;\n\t\treverse(a.begin() + 1, a.end());\n\t}\n}\n\nvector<Mint> mul(vector<Mint> a, vector<Mint> b) {\n\tint cnt = 1 << (32 - __builtin_clz(sz(a) + sz(b) - 1));\n\ta.resize(cnt);\n\tb.resize(cnt);\n\tntt(a, false);\n\tntt(b, false);\n\tvector<Mint> c(cnt);\n\tforn(i, cnt) c[i] = a[i] * b[i];\n\tntt(c, true);\n\twhile(c.size() > 1 && c.back() == 0)\n\t\tc.pop_back();\n\treturn c;\n}\n\nstruct dp\n{\n \tvector<Mint> val[T][T];\n \tbool is_unit;\n\n \tdp() {};\n \tdp(int len)\n \t{\n \t\tis_unit = len == 1;\n \t\tfor(int j = 0; j < T; j++)\n \t\t\tfor(int k = 0; k < T; k++)\n \t\t\t\tval[j][k] = {0};\n \t\tif(len == 1)\n \t\t\tval[0][0][0] = 1;\n \t\telse\n \t\t\tval[1][1][0] = 2;\n \t}\n\n \tdp(const dp& a, const dp& b)\n \t{\n \t\tis_unit = false;\n \t\tfor(int l1 = 0; l1 < T; l1++)\n \t\t\tfor(int r1 = 0; r1 < T; r1++)\n \t\t\t\tfor(int l2 = 0; l2 < T; l2++)\n \t\t\t\t\tfor(int r2 = 0; r2 < T; r2++)\n \t\t\t\t\t{\n \t\t\t\t\t \tvector<Mint> cur = mul(a.val[l1][r1], b.val[l2][r2]);\n \t\t\t\t\t \tif(val[l1][r2].size() < cur.size())\n \t\t\t\t\t \t\tval[l1][r2].resize(cur.size());\n \t\t\t\t\t \tfor(int i = 0; i < cur.size(); i++)\n \t\t\t\t\t\t\tval[l1][r2][i] += cur[i];\n \t\t\t\t\t \tMint merge_coeff = 2;\n \t\t\t\t\t \tif(r1 == 1)\n \t\t\t\t\t \t\tmerge_coeff /= 2;\n \t\t\t\t\t \tif(l2 == 1)\n \t\t\t\t\t \t\tmerge_coeff /= 2;\n \t\t\t\t\t \tcur.insert(cur.begin(), 0);\n \t\t\t\t\t \tfor(int i = 0; i < cur.size(); i++)\n \t\t\t\t\t \t\tcur[i] *= merge_coeff;\n \t\t\t\t\t \tint L1 = l1;\n \t\t\t\t\t \tint R2 = r2;\n \t\t\t\t\t \tif(a.is_unit)\n \t\t\t\t\t \t\tL1 = 1;\n \t\t\t\t\t \tif(b.is_unit)\n \t\t\t\t\t \t\tR2 = 1;\n \t\t\t\t\t \tif(val[L1][R2].size() < cur.size())\n \t\t\t\t\t \t\tval[L1][R2].resize(cur.size());\n \t\t\t\t\t \tfor(int i = 0; i < cur.size(); i++)\n \t\t\t\t\t \t{\n \t\t\t\t\t \t\tval[L1][R2][i] += cur[i];\n \t\t\t\t\t\t}\n \t\t\t\t \t}\n \t}\n};\n\nostream& operator<<(ostream& out, const dp& a)\n{\n \tfor(int i = 0; i < T; i++)\n \t\tfor(int j = 0; j < T; j++)\n \t\t{\n \t\t \tout << \"[\" << i << \"][\" << j << \"]\";\n \t\t \tfor(auto x : a.val[i][j])\n \t\t \t\tout << \" \" << x;\n \t\t \tout << endl;\n \t\t}\n \treturn out;\n}\n\nint a[N];\nint len[N];\nMint fact[N];\nint n;\nint s;\n\ndp build(int l, int r)\n{\n \tif(l == r - 1)\n \t{\n \t\tdp res(len[l]);   \n \t\t//cerr << l << \" \" << r << endl;\n \t \t//cerr << res;\n \t \treturn res;\n \t}                     \n \telse\n \t{\n \t\tint m = (l + r) / 2;\n \t\tdp res(build(l, m), build(m, r));\n \t\t//cerr << l << \" \" << r << endl;\n \t\t//cerr << res;\n \t\treturn res;                         \n \t}\n}\n\nint main()\n{\n\tprecalc();\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; i++)\n\t \tscanf(\"%d\", &a[i]);\n\tint cur = 0;\n\twhile(cur != n)\n\t{\n\t \tif(cur + a[cur] > n)\n\t \t{\n         \tcout << 0 << endl;\n         \treturn 0;\n        }\n        for(int l = cur; l < cur + a[cur]; l++)\n        \tif(a[l] != a[cur])\n        \t{\n        \t \tcout << 0 << endl;\n        \t \treturn 0;\n        \t}\n        len[s++] = a[cur];\n        cur += a[cur];\n\t}\n\t\n\tfact[0] = 1;\n\tfor(int i = 1; i <= s; i++)\n\t\tfact[i] = i * fact[i - 1];\n\n\tdp res = build(0, s);\n\n\tMint ans = 0;\n\tfor(int i = 0; i < s; i++)            \n\t\tfor(int j = 0; j < T; j++)\n\t\t\tfor(int k = 0; k < T; k++)\n\t\t\t\tif(res.val[j][k].size() > i)\n\t\t\t\t\tans += fact[s - i] * res.val[j][k][i] * (i % 2 == 0 ? 1 : MOD - 1);\n\tcout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1554",
    "index": "A",
    "title": "Cherry",
    "statement": "You are given $n$ integers $a_1, a_2, \\ldots, a_n$. Find the maximum value of $max(a_l, a_{l + 1}, \\ldots, a_r) \\cdot min(a_l, a_{l + 1}, \\ldots, a_r)$ over all pairs $(l, r)$ of integers for which $1 \\le l < r \\le n$.",
    "tutorial": "Do we really need to check all the subarrays? Consider a subarray $(a_i, a_{i + 1}, \\ldots, a_{j})$. If we add a new element $a_{j + 1}$, when will the new subarray $(a_i, a_{i + 1}, \\ldots, a_{j}, a_{j + 1})$ give a better result? Pause and think. The minimum of the new subarray can't get better(the minimum of a smaller subarray $\\ge$ the minimum of a larger subarray). So only when $a_{j + 1}$ is greater than the previous maximum, then it will give a better result. But in that case, do we really need to check the whole subarray to get that result? Can we get the same or a better result from a smaller subarray? Think. Here the maximum is $a_{j + 1}$. So if the minimum is not $a_i$, then the subarray $(a_{i + 1}, a_{i + 2}, \\ldots, a_{j + 1})$ will give the same result. Otherwise, the minimum of $(a_{i + 1}, a_{i + 2}, \\ldots, a_{j + 1})$ will not be smaller which implies that $(a_{i + 1}, a_{i + 2}, \\ldots, a_{j + 1})$ will give a better result! So if we add a new element, we don't have to check the whole subarray, checking $(a_i, a_{i + 1}, \\ldots, a_{j})$ and $(a_{i + 1}, a_{i + 2}, \\ldots, a_{j + 1})$ is enough. What good this observation just brought to this world? Think. Yes, we don't have to check subarrays with length $> 2$, because according to the observation, $(a_1, a_2, a_3)$ won't give a better result than $(a_1, a_2)$ and $(a_2, a_3)$. And subarrays with length $4$ won't give a better result than subarrays with length $3$ and subarrays with length $3$ won't give a better result than subarrays with length $2$. You got the idea, right? Another thing to notice here is that the product of maximum and minimum of two integers is just the product of two integers. So the answer to the problem is the maximum of the products of adjacent elements in $a$. Time Complexity: $\\mathcal{O}(n)$",
    "code": "import sys\ninput = sys.stdin.buffer.readline\nt = int(input())\nfor _ in range(t):\n  n = int(input())\n  a = list(map(int, input().split()))\n  ans = 0\n  for i in range(n - 1):\n    ans = max(ans, a[i] * a[i + 1])\n  print(ans)",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1554",
    "index": "B",
    "title": "Cobb",
    "statement": "You are given $n$ integers $a_1, a_2, \\ldots, a_n$ and an integer $k$. Find the maximum value of $i \\cdot j - k \\cdot (a_i | a_j)$ over all pairs $(i, j)$ of integers with $1 \\le i < j \\le n$. Here, $|$ is the bitwise OR operator.",
    "tutorial": "Let $f(i, j) = i \\cdot j - k \\cdot (a_i | a_j)$ for $i < j$. Do we really need to check all pairs? The value of $k$ is small, which is suspicious. There must be something revolving around it. What can that be? In the equation, $i \\cdot j$ can be $\\mathcal{O}(n^2)$, but $k \\cdot (a_i | a_j)$ is $\\mathcal{O}(n \\cdot 100)$. That means the value of $f(i, j)$ must be larger for bigger $i, j$. Can you deduce something from this? What is the smallest $i$ which can contribute to the result($f(i, j): i < j$ is the maximum)? Pause and think. Hint: try to maximize $f(i, j)$ and minimize the heaviest pair, that is, $f(n - 1, n)$, and compare them. Let's find it. What is the maximum possible value of a pair containing $i$?. It's when $i$ pairs with $n$ and $a_i = a_n = 0$. So, $f(i, n) = i \\cdot n - k \\cdot 0 = i \\cdot n$. What is the minimum possible value of the heaviest pair $f(n - 1, n)$? It's when $a_{n - 1} | a_n$ is maximum. And, since $0 \\le a_i \\le n$, the maximum possible of value any $a_i | a_j$ is $\\le 2n$. So $f(n - 1, n) = (n - 1) \\cdot n - k \\cdot 2n = n^2 - 2kn - n$. For $i$ to contribute to the result, $f(i, n)$ must be $\\gt f(n - 1, n)$. And, when $f(i, n) \\gt f(n - 1, n)$, then $i \\cdot n \\gt n^2 - 2kn - n$, or $i \\gt n - 2k -1$. So any of $f(i, j)$ such that $i < n - 2k$ won't generate a value greater than $f(n - 1, n)$!. This indicates us that we just have to check the pairs $f(i, j)$ such that $i, j \\ge n - 2k$. And, there are only $\\mathcal{O}(k^2)$ such pairs, so we can brute-force. We have also allowed $\\mathcal{O}(n \\cdot k)$ solutions to pass i.e. brute-forcing over all pairs such that $1 \\le i \\le n$ and $n - 2k \\le j \\le n$. Time Complexity: $\\mathcal{O}(k^2)$",
    "code": "import sys\ninput = sys.stdin.buffer.readline\nt = int(input())\nfor _ in range(t):\n  n, k = map(int, input().split())\n  a = list(map(int, input().split()))\n  l = max(0, n - 2 * k - 1)\n  ans = -1e12\n  for i in range(l, n):\n    for j in range(i + 1, n):\n      ans = max(ans, (i + 1) * (j + 1) - k * (a[i] | a[j]))\n  print(ans)",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1554",
    "index": "C",
    "title": "Mikasa",
    "statement": "You are given two integers $n$ and $m$. Find the $\\operatorname{MEX}$ of the sequence $n \\oplus 0, n \\oplus 1, \\ldots, n \\oplus m$. Here, $\\oplus$ is the bitwise XOR operator.\n\n$\\operatorname{MEX}$ of the sequence of non-negative integers is the smallest non-negative integer that doesn't appear in this sequence. For example, $\\operatorname{MEX}(0, 1, 2, 4) = 3$, and $\\operatorname{MEX}(1, 2021) = 0$.",
    "tutorial": "How can we check if $k$ is present in the sequence $n\\oplus 0,n\\oplus 1,...,n\\oplus m$ ? Think. If $k$ is present in the sequence, then there must be some $x$ such that $0 \\le x \\le m$ and $n\\oplus x = k$, right? Did you know that $n\\oplus k = x$ is equivalent to $n\\oplus x = k$ ? So we can just check if $n\\oplus k \\le m$ or not! Pretty simple! So the modified problem is to find the smallest non-negative integer $k$ such that $n\\oplus k \\ge m+1$. Can you solve it now? Think using bits. Let $p = m+1$ and $t_i$ be the $i$-th bit of $t$. We will find the smallest $k$ such that $n\\oplus k \\ge p$. Let's build $k$ greedily from the highest bit to the lowest bit. Let's say we will find the $i$-th bit of $k$ and the higher bits have already been generated. Obviously, we will try to make this bit off if possible. When will it be impossible? Think. If $n_i = p_i$, we can set $k_i = 0$ as $n_i \\oplus 0 = n_i \\ge p_i$. If $n_i = 1$ and $p_i = 0$, we can break here by setting the remaining bits of $k$ off as no matter what the remaining bits of $n$ are, $n \\oplus k$ will always be greater than $p$. Finally, if $n_i = 0$ and $p_i = 1$, we must set $k_i = 1$, as we have no other options. Check my solution for more clarity. Time Complexity: $\\mathcal{O}(log(n))$ per test case.",
    "code": "import sys\ninput = sys.stdin.buffer.readline\nt = int(input())\nfor _ in range(t):\n  n, m = map(int, input().split())\n  m += 1\n  ans = 0\n  for k in range(30, -1, -1):\n    if (n >= m): break\n    if ((n >> k & 1) == (m >> k & 1)): continue\n    if (m >> k & 1):\n      ans |= 1 << k\n      n |= 1 << k\n  print(ans)",
    "tags": [
      "binary search",
      "bitmasks",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1554",
    "index": "D",
    "title": "Diane",
    "statement": "You are given an integer $n$. Find any string $s$ of length $n$ consisting only of English lowercase letters such that each non-empty substring of $s$ occurs in $s$ an \\textbf{odd} number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.",
    "tutorial": "Consider the strings of type \"$aa \\ldots a$\". Which substring occurs in which parity? Observe. Play with them. Consider the string \"$aa \\ldots a$\" ($k$ times '$a$'). WLOG Let $k$ be an odd integer. In this string \"$a$\" occurs $k$ times, \"$aa$\" occurs $k - 1$ times and so on. So \"$a$\", \"$aa$\", \"$aaa$\", $\\ldots$ occurs odd, even, odd, even, $\\ldots$ times, respectively. Now let's look at the string \"$aa \\ldots a$\" ($k - 1$ times '$a$'). In this string, \"$a$\", \"$aa$\", \"$aaa$\", $\\ldots$ occurs even, odd, even, odd, $\\ldots$ times, respectively. What can be done now? Did you know that odd $+$ even $=$ odd? Pause and think. Let's merge both strings! If we merge them with \"$b$\" in-between i.e. \"$\\underbrace{aaa \\ldots aaa}_\\text{k times} b \\underbrace{aaa\\ldots aa}_\\text{k - 1 times}$\", then each substring will occur an odd number of times. Thats because each of \"$a$\", \"$aa$\", \"$aaa$\", $\\ldots$ occurs odd $+$ even $=$ odd times, and each newly created substring occurs exactly once. What will happen if we set $k = \\left \\lfloor{\\frac{n}{2}}\\right \\rfloor$? So here is the solution to the problem: \"$\\underbrace{aaa \\ldots aaa}_\\text{k times} + b | bc + \\underbrace{aaa\\ldots aa}_\\text{k- 1 times}$\", where $k = \\left \\lfloor{\\frac{n}{2}}\\right \\rfloor$ and \"$b$\" when $n$ is even and \"$bc$\" when $n$ is odd. For example, if $n = 6$, answer is \"$aaabaa$\" and if $n = 7$, answer is \"$aaabcaa$\". Time Complexity: $\\mathcal{O}(n)$ If you are wondering(as you always do) about the checker: Write a suffix automata and check if every node occurs an odd number of times.",
    "code": "#include<bits/stdc++.h>\n#include \"testlib.h\"\nusing namespace std;\n\n// len -> largest string length of the corresponding endpos-equivalent class\n// link -> longest suffix that is another endpos-equivalent class.\n// firstpos -> 1 indexed end position of the first occurrence of the largest string of that node\n// minlen(v) -> smallest string of node v = len(link(v)) + 1\n// terminal nodes -> store the suffixes\nstruct SuffixAutomaton {\n  struct node {\n    int len, link, firstpos;\n    map<char, int> nxt;\n  };\n  int sz, last;\n  vector<node> t;\n  vector<int> terminal;\n  vector<int> dp;\n  vector<vector<int>> g;\n  SuffixAutomaton() {}\n  SuffixAutomaton(int n) {\n    t.resize(2 * n); terminal.resize(2 * n, 0);\n    dp.resize(2 * n, -1); sz = 1; last = 0;\n    g.resize(2 * n);\n    t[0].len = 0; t[0].link = -1; t[0].firstpos = 0;\n  }\n  void extend(char c) {\n    int p = last;\n    int cur = sz++;\n    t[cur].len = t[last].len + 1;\n    t[cur].firstpos = t[cur].len;\n    p = last;\n    while (p != -1 && !t[p].nxt.count(c)) {\n      t[p].nxt[c] = cur;\n      p = t[p].link;\n    }\n    if (p == -1) t[cur].link = 0;\n    else {\n      int q = t[p].nxt[c];\n      if (t[p].len + 1 == t[q].len) t[cur].link = q;\n      else {\n        int clone = sz++;\n        t[clone] = t[q];\n        t[clone].len = t[p].len + 1;\n        while (p != -1 && t[p].nxt[c] == q) {\n          t[p].nxt[c] = clone;\n          p = t[p].link;\n        }\n        t[q].link = t[cur].link = clone;\n      }\n    }\n    last = cur;\n  }\n  void build_tree() {\n    for (int i = 1; i < sz; i++) g[t[i].link].push_back(i);\n  }\n  void build(string &s) {\n    for (auto x: s) {\n      extend(x);\n      terminal[last] = 1;\n    }\n    build_tree();\n  }\n  int cnt(int i) { // number of times i-th node occurs in the string\n    if (dp[i] != -1) return dp[i];\n    int ret = terminal[i];\n    for (auto &x: g[i]) ret += cnt(x);\n    return dp[i] = ret;\n  }\n};\npair<int, int> ok(string s) {\n  int n = s.size();\n  SuffixAutomaton sa(n);\n  sa.build(s);\n  for (int i = 1; i < sa.sz; i++) {\n    if (sa.cnt(i) % 2 == 0) {\n      return {sa.t[i].firstpos - sa.t[i].len, sa.t[i].firstpos - 1};\n    }\n  }\n  return {-1, -1};\n}\nint main(int argc, char* argv[]) {\n  registerTestlibCmd(argc, argv);\n  int t = inf.readInt();\n  inf.readEoln();\n  for (int test = 1; test <= t; test++) {\n    setTestCase(test);\n    int n = inf.readInt();\n    inf.readEoln();\n    string s = ouf.readToken();\n    if (s.size() != n) {\n      quitf(_wa, \"the length of s should be exactly %d\", n);\n    }\n    for (int i = 0; i < n; i++) {\n      if (!(s[i] >= 'a' and s[i] <= 'z')) {\n        quitf(_wa, \"s contains %c which is not an English lowercase character\", s[i]);\n      }\n    }\n    auto p = ok(s);\n    if (p.first != -1) {\n      quitf(_wa, \"the substring s[%d, %d] (0-indexed) occurs even number of times in s :\\\"(\", p.first, p.second);\n    }\n  }\n  quitf(_ok, \"you are the best problem solver ever UwU\");\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1554",
    "index": "E",
    "title": "You",
    "statement": "You are given a tree with $n$ nodes. As a reminder, a tree is a connected undirected graph without cycles.\n\nLet $a_1, a_2, \\ldots, a_n$ be a sequence of integers. Perform the following operation \\textbf{exactly} $n$ times:\n\n- Select an \\textbf{unerased} node $u$. Assign $a_u :=$ number of \\textbf{unerased} nodes adjacent to $u$. Then, erase the node $u$ along with all edges that have it as an endpoint.\n\nFor each integer $k$ from $1$ to $n$, find the number, modulo $998\\,244\\,353$, of different sequences $a_1, a_2, \\ldots, a_n$ that satisfy the following conditions:\n\n- it is possible to obtain $a$ by performing the aforementioned operations \\textbf{exactly} $n$ times in some order.\n- $\\operatorname{gcd}(a_1, a_2, \\ldots, a_n) = k$. Here, $\\operatorname{gcd}$ means the greatest common divisor of the elements in $a$.",
    "tutorial": "Let's find which sequences of $a$ are possible to obtain by performing the mentioned operations exactly $n$ times in some order. (Critical) Observation 1: Consider all $a_i = 0$ initially. For each edge $(u, v)$, either increase $a_u$ by $1$ (assign $(u, v)$ to $u$) or increase $a_v$ by $1$ ((assign $(u, v)$ to $v$). The final sequences are the only possible sequences that $a$ can possibly be. You can observe it by noticing that when we select a node and delete it, the existing edges adjacent to the node gets assigned to it. Notice that, the final sequences are unique. So there are $2^{n - 1}$ distinct sequences possible. That's because there are $n - 1$ edges and for each edge $(u, v)$ we have $2$ options - either assign it to $u$ or $v$. Now for each $k$ from $1$ to $n$, we have to find the number of sequences which has gcd equals to $k$. Instead, let's find the number of sequences such that each of its values is divisible by $k$. Let it be $f_k$. For $k = 1$, all sequences are valid. So $f_1 = 2^{n - 1}$. Assume $k > 1$. Let's construct a sequence $a$ such that each $a_i$ is divisible by $k$. First, root the tree at node $1$. We will build the array in a bottom-up manner. Let $g_u$ be the set of childs of $u$ and $p_u$ be the parent of $u$. Assume that we have set the values for each $v \\in g_u$. Now we will set the value of $a_u$. For each edge $(u, v)$ such that $v \\in g_u$, if we have assigned this edge to $v$, then do nothing, otherwise we must assign it to $u$ i.e increase $a_u$ by $1$. After we are done with all the edges, if $a_u$ is divisible by $k$, then we can't assign the edge $(p_u, u)$ to $u$ because $a_u$ will be increased by $1$ and as $a_u$ is divisible by $k$, $(a_u + 1)$ will not be divisible by $k$ because $k > 1$. if $a_u$ is not divisible by $k$, then we must assign the edge $(p_u, u)$ to $u$ and thus increasing $a_u$ by $1$. If now $a_u$ is divisible by $k$, then we are done, otherwise we can't make $a_u$ divisible by $k$. So we terminate here. If we can successfully set the values of $a_i$ for each $i$ from $1$ to $n$, then $f_k$ will be non-zero. Observation 2: $f_k$ for $k > 1$ is either $0$ or $1$. We can say this by observing the building process of $a_i$ that has been discussed already. So for each $k$ from $1$ to $n$, we can find the value of $f_k$ in $\\mathcal{O}(n)$ by performing a simple dfs. So all $f_k$ can be found in $\\mathcal{O}(n^2)$. Observation 3: If $k$ doesn't divide $n - 1$, then $f_k = 0$. Proof: Notice that $\\sum\\limits_{i = 1}^{n}{a_i} = n - 1$. So for any integer $k$, if each $a_i$ is divisible $k$, then $k$ must divide $n - 1$. Similarly, if $k$ doesn't divide $n - 1$, then each $a_i$ will not be divisible by $k$ and $f_k$ will be $0$. So we only have to perform a dfs when $k$ divides $n - 1$. So all $f_k$ can be found in $\\mathcal{O}(n \\cdot \\sigma_0 (n - 1))$ where $\\sigma_0(x)$ is the number of divisors of $x$. Let $h_k$ be the number of sequences which has gcd equals to $k$. We can notice that $h_k = f_k - \\sum\\limits_{i = 2}^{\\left \\lfloor{\\frac{n}{k}}\\right \\rfloor}{h_{i \\cdot k}}$. So we can find $h_k$ for each $k$ from $1$ to $n$ in $\\mathcal{O}(n \\cdot log(n))$. Time Complexity: $\\mathcal{O}(n \\cdot \\sigma_0 (n - 1) + n \\cdot log(n))$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1e5 + 9, mod = 998244353;\n\nvector<int> g[N];\nint dp[N], d, ok, ans[N];\nvoid dfs(int u, int p = 0) {\n  if (!ok) return;\n  for (auto v: g[u]) {\n    if (v ^ p) {\n      dfs(v, u);\n    }\n  }\n  if (dp[u] % d != 0) {\n    if (p) {\n      dp[u]++;\n    }\n    if (dp[u] % d != 0) {\n      ok = 0;\n      return;\n    }\n  }\n  else {\n    dp[p]++;\n  }\n}\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t; cin >> t;\n  while (t--) {\n    int n; cin >> n;\n    for (int i = 1; i < n; i++) {\n      int u, v; cin >> u >> v;\n      g[u].push_back(v);\n      g[v].push_back(u);\n    }\n    for (int i = 1; i <= n; i++) {\n      ans[i] = 0;\n    }\n    ans[1] = 1;\n    for (int k = 1; k <= n - 1; k++) {\n      ans[1] = (ans[1] + ans[1]) % mod;\n    }\n    for (d = 2; d <= n - 1; d++) {\n      if ((n - 1) % d == 0) {\n        ok = 1;\n        dfs(1);\n        ans[d] = ok;\n        for (int i = 0; i <= n; i++) {\n          dp[i] = 0;\n        }\n      }\n    }\n    for (int i = n; i >= 1; i--) {\n      for (int j = i + i; j <= n; j += i) {\n        ans[i] = (ans[i] - ans[j] + mod) % mod;\n      }\n    }\n    for (int i = 1; i <= n; i++) {\n      if (i > 1) cout << ' ';\n      cout << ans[i];\n    }\n    cout << '\\n';\n    for (int i = 1; i <= n; i++) {\n      g[i].clear();\n    }\n  }\n  return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1555",
    "index": "A",
    "title": "PizzaForces",
    "statement": "PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of $6$ slices, medium ones consist of $8$ slices, and large pizzas consist of $10$ slices each. Baking them takes $15$, $20$ and $25$ minutes, respectively.\n\nPetya's birthday is today, and $n$ of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order.\n\nYour task is to determine the minimum number of minutes that is needed to make pizzas containing at least $n$ slices in total. For example:\n\n- if $12$ friends come to Petya's birthday, he has to order pizzas containing at least $12$ slices in total. He can order two small pizzas, containing exactly $12$ slices, and the time to bake them is $30$ minutes;\n- if $15$ friends come to Petya's birthday, he has to order pizzas containing at least $15$ slices in total. He can order a small pizza and a large pizza, containing $16$ slices, and the time to bake them is $40$ minutes;\n- if $300$ friends come to Petya's birthday, he has to order pizzas containing at least $300$ slices in total. He can order $15$ small pizzas, $10$ medium pizzas and $13$ large pizzas, in total they contain $15 \\cdot 6 + 10 \\cdot 8 + 13 \\cdot 10 = 300$ slices, and the total time to bake them is $15 \\cdot 15 + 10 \\cdot 20 + 13 \\cdot 25 = 750$ minutes;\n- if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is $15$ minutes.",
    "tutorial": "Note that the \"speed\" of cooking $1$ slice of pizza is the same for all sizes - $1$ slice of pizza for $2.5$ minutes. If $n$ is odd, then we will increase it by $1$ (since the pizza is cooked only with an even number of pieces). Now the value of $n$ is always even. If $n < 6$, then for such $n$ the answer is equal to the answer for $n=6$, so we can say that $n = \\max(n, 6)$. While $n \\ge 12$ we can order a small pizza. Eventually the value of $n$ will be equal to $6$, $8$ or $10$. This means that for any $n$ there will be a set of pizzas with exactly $n$ slices. Then the answer is $n * 2.5$ (in the solution, it is better to use the formula $n / 2 * 5$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    long long n;\n    cin >> n;\n    cout << max(6LL, n + 1) / 2 * 5 << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1555",
    "index": "B",
    "title": "Two Tables",
    "statement": "You have an axis-aligned rectangle room with width $W$ and height $H$, so the lower left corner is in point $(0, 0)$ and the upper right corner is in $(W, H)$.\n\nThere is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $(x_1, y_1)$, and the upper right corner in $(x_2, y_2)$.\n\nYou want to place another rectangular table in this room with width $w$ and height $h$ with the width of the table parallel to the width of the room.\n\nThe problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).\n\nYou \\textbf{can't rotate} any of the tables, but you can move the first table inside the room.\n\n\\begin{center}\n{\\small Example of how you may move the first table.}\n\\end{center}\n\nWhat is the minimum distance you should move the first table to free enough space for the second one?",
    "tutorial": "Firstly, let's notice the next property: if two axis-aligned rectangles don't intersect, then we can draw a vertical or horizontal line between them. In other words, either $\\max(x_1, x_2) \\le \\min(x_3, x_4)$ or $\\max(x_3, x_4) \\le \\min(x_1, x_2)$ if $x_1$ and $x_2$ are coordinates of the one rectangle and $x_3$ and $x_4$ of the other one (analogically, for $y$ coordinates). Now, suppose you want to move the first table by $(dx, dy)$. Note that if in result they will be divided by vertical line then we can set $dy = 0$ - they still will be divided, but the total distance will decrease. Analogically, if divided by horizontal line, we can set $dx = 0$. In other words, it's always optimal to move the table either horizontally or vertically. Let's look at the case of horizontal move: at first, we need to check that both tables can fit in the room, or their total width $w + (x_2 - x_1) \\le W$. If yes, then we calculate the movement distance $dx$ as follows: if we move the table right then there should be at least $w$ to the left of it, or $w \\le x_1 + dx$ $\\Leftrightarrow$ $dx \\ge w - x_1$. Since we want to minimize $dx$ then we take $dx = \\max(0, w - x_1)$. If we want to move the table left, then there should be at least $w$ to the right, or $x_2 - dx \\le W - w$ $\\Leftrightarrow$ $dx \\ge x_2 - (W - w)$, minimizing $dx$ means taking $dx = \\max(0, x_2 - (W - w))$. So, the result is $\\min(\\max(0, w - x_1), \\max(0, x_2 - (W - w)))$. The vertical case can be handled in the same manner, if $h + (y_2 - y_1) \\le H$ then the result is $\\min(\\max(0, h - y_1), \\max(0, y_2 - (H - h)))$. The answer is the minimum among all possible variants, or $-1$ if both cases are impossible.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\n\nint W, H;\nint x1, y1, x2, y2;\nint w, h;\n\ninline bool read() {\n\tif(!(cin >> W >> H))\n\t\treturn false;\n\tcin >> x1 >> y1 >> x2 >> y2;\n\tcin >> w >> h;\n\treturn true;\n}\n\ninline void solve() {\n\tint ans = INF;\n\tif (x2 - x1 + w <= W) {\n\t\tans = min(ans, max(0, w - x1));\n\t\tans = min(ans, max(0, x2 - (W - w)));\n\t}\n\tif (y2 - y1 + h <= H) {\n\t\tans = min(ans, max(0, h - y1));\n\t\tans = min(ans, max(0, y2 - (H - h)));\n\t}\n\tif (ans == INF)\n\t\tcout << -1 << endl;\n\telse\n\t\tcout << double(ans) << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\t\n\tcout << fixed << setprecision(9);\n\tint t; cin >> t;\n\twhile(t--) {\n\t\t(read());\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1555",
    "index": "C",
    "title": "Coin Rows",
    "statement": "Alice and Bob are playing a game on a matrix, consisting of $2$ rows and $m$ columns. The cell in the $i$-th row in the $j$-th column contains $a_{i, j}$ coins in it.\n\nInitially, both Alice and Bob are standing in a cell $(1, 1)$. They are going to perform a sequence of moves to reach a cell $(2, m)$.\n\nThe possible moves are:\n\n- Move right — from some cell $(x, y)$ to $(x, y + 1)$;\n- Move down — from some cell $(x, y)$ to $(x + 1, y)$.\n\nFirst, Alice makes \\textbf{all her moves} until she reaches $(2, m)$. She collects the coins in all cells she visit (including the starting cell).\n\nWhen Alice finishes, Bob starts his journey. He also performs the moves to reach $(2, m)$ and collects the coins in all cells that he visited, \\textbf{but Alice didn't}.\n\nThe score of the game is the total number of coins Bob collects.\n\nAlice wants to minimize the score. Bob wants to maximize the score. What will the score of the game be if both players play optimally?",
    "tutorial": "First, observe that each of the players has only $m$ options for their path - which column to go down in. Let's consider a Bob's response to a strategy chosen by Alice. The easiest way to approach that is to look at the picture of the Alice's path. The path clearly separates the field into two independent pieces - suffix of the first row and the prefix of the second row. Bob can't grab the coins from both of them at once. However, he can grab either of them fully. So the optimal path for him will be one of these two options. You can precalculate some prefix sums and become able to get the Bob's score given the Alice's path. Alice has $m$ possibly paths, so you can iterate over them and choose the minimum answer. However, prefix sums are not required, since you can quickly recalculate both needed sums while iterating over the Alice's column to go down in. Overall complexity: $O(m)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int INF = 2e9 + 10;\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\tforn(_, t){\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tvector<vector<int>> a(2, vector<int>(n));\n\t\tforn(i, 2) forn(j, n)\n\t\t\tscanf(\"%d\", &a[i][j]);\n\t\tint ans = INF;\n\t\tint sum1 = 0, sum2 = 0;\n\t\tforn(i, n) sum1 += a[0][i];\n\t\tforn(i, n){\n\t\t\tsum1 -= a[0][i];\n\t\t\tans = min(ans, max(sum1, sum2));\n\t\t\tsum2 += a[1][i];\n\t\t}\n\t\tprintf(\"%d\\n\", ans);\n\t}\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1555",
    "index": "D",
    "title": "Say No to Palindromes",
    "statement": "Let's call the string \\textbf{beautiful} if it does not contain a substring of length at least $2$, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.\n\nLet's define \\textbf{cost} of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first $3$ letters of the Latin alphabet (in lowercase).\n\nYou are given a string $s$ of length $n$, each character of the string is one of the first $3$ letters of the Latin alphabet (in lowercase).\n\nYou have to answer $m$ queries — calculate the cost of the substring of the string $s$ from $l_i$-th to $r_i$-th position, inclusive.",
    "tutorial": "Note that in the beautiful string $s_i \\neq s_{i-1}$ (because it is a palindrome of length $2$) and $s_i \\neq s_{i-2}$ (because it is a palindrome of length $3$). This means $s_i = s_{i-3}$, i.e. a beautiful string has the form abcabcabc..., up to the permutation of the letters a, b and c. For each permutation of the letters a, b and c, we will construct a string $t$, of the form abcabcabc... of length $n$. Let's define an array $a$ of length $n$ as follows: $a_i = 0$ if $s_i = t_i$ (i.e. the character at the $i$-th position does not need to be changed) and $a_i = 1$ otherwise. Let's build an array $pr$ of prefix sums of the array $a$. Now you can process a query of the number of positions that need to be replaced for the current line $t$ in $O(1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL); \n  int n, m;\n  cin >> n >> m;\n  string s;\n  cin >> s;\n  vector<vector<int>> pr(6, vector<int>(n + 1));\n  string t = \"abc\";\n  int cur = 0;\n  do {\n    for (int i = 0; i < n; ++i)\n      pr[cur][i + 1] = pr[cur][i] + (s[i] != t[i % 3]);\n    ++cur;\n  } while (next_permutation(t.begin(), t.end()));\n  while (m--) {\n    int l, r;\n    cin >> l >> r;\n    int ans = n;\n    for (int i = 0; i < 6; ++i)\n      ans = min(ans, pr[i][r] - pr[i][l - 1]);\n    cout << ans << \"\\n\";\n  }\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1555",
    "index": "E",
    "title": "Boring Segments",
    "statement": "You are given $n$ segments on a number line, numbered from $1$ to $n$. The $i$-th segments covers all integer points from $l_i$ to $r_i$ and has a value $w_i$.\n\nYou are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a selected segment that covers both of them. A subset is good if it's possible to reach point $m$ starting from point $1$ in arbitrary number of moves.\n\nThe cost of the subset is the difference between the maximum and the minimum values of segments in it. Find the minimum cost of a good subset.\n\nIn every test there exists at least one good subset.",
    "tutorial": "Take a look at the condition for a good subset. The major implication it makes is that every point (even non-integer) of the segment $[1; m]$ should be covered by at least one segment. If some point isn't, then there is no way to jump across the gap it produces. At the same time, this condition is enough to have a path, since for every half-integer point ($0.5$, $1.5$ and so on) there exists a segment that covers it. So you can take that segment to go from $1$ to $2$, then from $2$ to $3$ and so on. Thus, we are asked to select a subset of segments that covers the entire segment $[1; m]$ in its union. The main prerequisite to the following solution is knowing the way to maintain the union of segments. For now, I can tell you that there is a data structure that allows you to add a segment, remove a segment and query the length of the current union. Let's continue with making some observations on the cost function. If you fix the minimum and the maximum value, you are free to select all segments that have their value in-between. That allows us to transition from selecting a subset of segment to an interval, if you sort the segments by their weight. If you fix only minimum, then the required maximum should be as small as possible. However, if some value suffices as a maximum, then any value greater than it also suffices (since it only adds extra segments to the subset). This makes the function on the maximum monotonous. So the binary search applicable. You could iterate over the minimum and binary search the maximum. However, it's not too clear how to make a check function. You would need to find a union of some interval of segments quickly. I don't really know a way to do that, so let's try something different. Instead, let's forget about binary search and try to reach a two pointers solution. Let $f(x)$ be the smallest possible maximum, given the fixed minimum is $x$. We want $f(x + 1)$ to be greater than or equal than $f(x)$ for two pointers to be applicable. That condition indeed holds. Imagine if $f(x + 1)$ is smaller than $f(x)$. So there exists some optimal subset for $x + 1$. Add all segments with weight $x$ to that subset. That brings the minimum to $x$. However, it doesn't change the maximum, so $f(x)$ is at least equal to $f(x + 1)$, what contradicts the assumption. Finally, the solution comes up to the following. Iterate over the minimum value $x$, while maintaining $f(x)$. When going from $x$ to $x + 1$, keep increasing the value of $f$ until the union of the segments is exactly $m$. Going from $x$ to $x+1$ and increasing the value of $f$ is actually removing some segments and adding some segments to the data structure. The data structure that helps us with that is a segment tree. The $i$-th leaf of the tree holds the number of segments that cover the interval $(i; i + 1)$. Add/remove segment makes it add/subtract on a range. The union is full if the there are no intervals that are covered by zero segments. Thus, let's store the minimum of the subtree in every intermediate node. If the minimum on the tree is above zero, then the current subset is good. Instead of applying two pointers on the values of the segments, let's apply them on the sorted segments themselves. That makes moving the pointer exactly one update to the segtree. Overall complexity: $O(n \\log n + n \\log m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nvector<int> t, ps;\n\nvoid push(int v){\n\tif (v * 2 + 1 < int(ps.size())){\n\t\tps[v * 2] += ps[v];\n\t\tps[v * 2 + 1] += ps[v];\n\t}\n\tt[v] += ps[v];\n\tps[v] = 0;\n}\n\nvoid upd(int v, int l, int r, int L, int R, int val){\n\tpush(v);\n\tif (L >= R)\n\t\treturn;\n\tif (l == L && r == R){\n\t\tps[v] += val;\n\t\tpush(v);\n\t\treturn;\n\t}\n\tint m = (l + r) / 2;\n\tupd(v * 2, l, m, L, min(m, R), val);\n\tupd(v * 2 + 1, m, r, max(m, L), R, val);\n\tt[v] = min(t[v * 2], t[v * 2 + 1]);\n}\n\nint get(){\n\treturn t[1] + ps[1];\n}\n\nstruct seg{\n\tint l, r, w;\n};\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tvector<seg> a(n);\n\tforn(i, n){\n\t\tscanf(\"%d%d%d\", &a[i].l, &a[i].r, &a[i].w);\n\t\t--a[i].l, --a[i].r;\n\t}\n\t--m;\n\tsort(a.begin(), a.end(), [](const seg &a, const seg &b){\n\t\treturn a.w < b.w;\n\t});\n\tt.resize(4 * m);\n\tps.resize(4 * m);\n\tint ans = INF;\n\tint j = 0;\n\tforn(i, n){\n\t\twhile (j < n && get() == 0){\n\t\t\tupd(1, 0, m, a[j].l, a[j].r, 1);\n\t\t\t++j;\n\t\t}\n\t\tif (get() == 0){\n\t\t\tbreak;\n\t\t}\n\t\tans = min(ans, a[j - 1].w - a[i].w);\n\t\tupd(1, 0, m, a[i].l, a[i].r, -1);\n\t}\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}\n",
    "tags": [
      "data structures",
      "sortings",
      "trees",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1555",
    "index": "F",
    "title": "Good Graph",
    "statement": "You have an undirected graph consisting of $n$ vertices with weighted edges.\n\nA simple cycle is a cycle of the graph without repeated vertices. Let the weight of the cycle be the XOR of weights of edges it consists of.\n\nLet's say the graph is good if all its simple cycles have weight $1$. A graph is bad if it's not good.\n\nInitially, the graph is empty. Then $q$ queries follow. Each query has the next type:\n\n- $u$ $v$ $x$ — add edge between vertices $u$ and $v$ of weight $x$ if it doesn't make the graph bad.\n\nFor each query print, was the edge added or not.",
    "tutorial": "Firstly, let's prove that a good graph has one important property: any two of its simple cycles intersect by at most one vertex, i. e. there is no edge that belongs to more than one simple cycle (cactus definition, yeah). Let's prove it by showing that if two simple cycles of weight $k > 0$ intersects (by edges) then they will induce a simple cycle of weight $\\neq k$. There are two cases: if cycles intersect by a single path, then we can create a new cycle by merging parts of cycles excluding the intersecting path - it will be simple and will have weight $k \\oplus k = 0 \\neq k$; if cycles intersect by more than one path, we can do the next transformation: suppose the common paths are $u_1 - v_1$, $u_2 - v_2$, $\\dots$, and they are ordered in the way how they lie on the first cycle. Let's create a third cycle using two paths from $v_1$ to $u_2$: from the first cycle and from the second cycle. It's easy to see that the third cycle is simple, and more over it has only one common path with the second cycle. So, it's either the third cycle has weight not equal to $k$ or the case $1$. Okay, let's analyze the edges we try to add. Let's divide all edges in two types: tree edges and all other edges (we will name them cycle edges). Let's name an edge as a tree edge if it connects two different components at a moment when we are trying to add it in the graph. It's obvious that we will add all tree edges in the graph, since they can't make it bad (since they don't induce new cycles). But there is a more interesting observation: when we try to add a cycle edge $(u, v)$, it should induce an only one simple cycle where all other edges are tree edges and these tree edges can't be used in any other cycle. It induces at least one \"all-tree-edge\" cycle, since $u$ and $v$ are already connected. It can't induce more than one \"all-tree-edge\" cycle, since it contradicts with tree edge definition, and if it induces a cycle with some other cycle edge, then we can replace that cycle edge with its own tree-edge path: our cycle will become \"all-tree-edge\" cycle, but it will use already used tree edges. In other words, it's enough to consider only one \"all-tree-edge\" cycle induced by any cycle edge. The final trick is to calculate the answer in two steps: at the first step, we will find only tree edges (using DSU) that will form a spanning forest in our graph. The second step is for each cycle edge $(u, v)$ to calculate the $\\operatorname{XOR}$ $X$ on a path between $u$ and $v$ in our spanning forest, check that $X \\oplus \\text{edge_weight} = 1$ and check that none of edges on the path from $u$ to $v$ are used in other cycle. Calculating $X$ is easy: if we precalculate for each vertex $v$ the $\\operatorname{XOR}$ on path from $v$ to root $\\mathit{xr}[v]$ then $X = \\mathit{xr}[u] \\oplus \\mathit{xr}[v]$. Checking that none of the edges are used on the path from $u$ to $v$ is a bit tricky: if we mark an edge by adding $1$ to it, then we should be able to take a sum on path and add on path. There are structures that are capable of it (like HLD and other), but let's look closely. Note that we mark each tree edge at most once, so we can manually add $1$ to each edge, and only asking sum on path should be fast. In other words, we need a data structure (DS) that can add value at edge and take the sum on path - and such DS is a Fenwick tree (BIT) built on Euler tour of tree: it can add value at edge and ask a sum on path from $v$ to root. So we need to find LCA as well, since sum of path $(u, v)$ is equal to $sum(u) + sum(v) - 2 \\cdot sum(LCA(u, v))$. As a result, complexity is $O((n + m) \\log(n))$ with quite a low constant from LCA and BIT.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \" \";\n\t\tout << v[i];\n\t}\n\treturn out;\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nint n, q;\nvector< array<int, 3> > es;\n\ninline bool read() {\n\tif(!(cin >> n >> q))\n\t\treturn false;\n\tes.resize(q);\n\tfore (i, 0, q) {\n\t\tcin >> es[i][0] >> es[i][1] >> es[i][2];\n\t\tes[i][0]--;\n\t\tes[i][1]--;\n\t}\n\treturn true;\n}\n\nvector< vector<pt> > g;\n\nconst int LOG = 19;\nvector<int> up[LOG];\nvector<int> tin, tout;\nvector<int> xr;\nint T = 0;\n\nvoid dfs(int v, int p, int curXor) {\n\ttin[v] = T++;\n\txr[v] = curXor;\n\tup[0][v] = p;\n\tfore (pw, 1, LOG)\n\t\tup[pw][v] = up[pw - 1][up[pw - 1][v]];\n\t\n\tfor (auto [to, w] : g[v]) {\n\t\tif (to == p)\n\t\t\tcontinue;\n\t\tdfs(to, v, curXor ^ w);\n\t}\n\ttout[v] = T;\n}\n\nvoid buildLCA() {\n\tfore (pw, 0, LOG)\n\t\tup[pw].resize(n);\n\ttin.assign(n, -1);\n\ttout.assign(n, -1);\n\txr.assign(n, 0);\n\t\n\tT = 0;\n\tfore (v, 0, n) {\n\t\tif (tin[v] != -1)\n\t\t\tcontinue;\n\t\tdfs(v, v, 0);\n\t}\n}\n\nint isPar(int p, int v) {\n\treturn tin[p] <= tin[v] && tout[v] <= tout[p];\n}\n\nint lca(int u, int v) {\n\tif (isPar(u, v)) return u;\n\tif (isPar(v, u)) return v;\n\t\n\tfor (int pw = LOG - 1; pw >= 0; pw--) {\n\t\tif (!isPar(up[pw][v], u))\n\t\t\tv = up[pw][v];\n\t}\n\treturn up[0][v];\n}\n\nvector<int> par, rk;\n\nvoid init(int n) {\n\tpar.assign(n, 0);\n\tiota(par.begin(), par.end(), 0);\n\trk.assign(n, 1);\n}\n\nint top(int v) {\n\tif (par[v] != v)\n\t\treturn par[v] = top(par[v]);\n\treturn v;\n}\n\nbool unite(int u, int v) {\n\tu = top(u);\n\tv = top(v);\n\tif (u == v)\n\t\treturn false;\n\tif (rk[u] < rk[v])\n\t\tswap(u, v);\n\tpar[v] = u;\n\trk[u] += rk[v];\n\treturn true;\n}\n\nvector<int> F;\nvoid inc(int pos, int val) {\n\tfor(; pos < sz(F); pos |= pos + 1)\n\t\tF[pos] += val;\n}\nint sum(int pos) {\n\tint ans = 0;\n\tfor(; pos >= 0; pos = (pos & (pos + 1)) - 1)\n\t\tans += F[pos];\n\treturn ans;\n}\n\nvoid addOnPath(int v, int l) {\n\twhile (v != l) {\n\t\tinc(tin[v], 1);\n\t\tinc(tout[v], -1);\n\t\tv = up[0][v];\n\t}\n}\n\ninline void solve() {\n\tinit(n);\n\tg.resize(n);\n\t\n\tvector<int> ans(q, -1);\n\tfore (i, 0, q) {\n\t\tint u = es[i][0];\n\t\tint v = es[i][1];\n\t\tint x = es[i][2];\n\t\t\n\t\tif (unite(u, v)) {\n\t\t\tans[i] = 1;\n\t\t\tg[u].emplace_back(v, x);\n\t\t\tg[v].emplace_back(u, x);\n\t\t}\n\t}\n\t\n\tbuildLCA();\n\tF.assign(2 * n + 5, 0);\n\t\n\tfore (i, 0, q) {\n\t\tif (ans[i] != -1)\n\t\t\tcontinue;\n\t\t\n\t\tans[i] = 0;\n\t\tint u = es[i][0];\n\t\tint v = es[i][1];\n\t\tint x = es[i][2];\n\t\t\n\t\tint xorPath = xr[u] ^ xr[v];\n\t\tif ((xorPath ^ x) != 1)\n\t\t\tcontinue;\n\t\t\n\t\tint l = lca(u, v);\n\t\tint usedOnPath = sum(tin[u]) + sum(tin[v]) - 2 * sum(tin[l]);\n\t\tif (usedOnPath > 0)\n\t\t\tcontinue;\n\t\t\n\t\tans[i] = 1;\n\t\taddOnPath(u, l);\n\t\taddOnPath(v, l);\n\t}\n\t\n\tfor (int res : ans)\n\t\tcout << (res ? \"YES\" : \"NO\") << '\\n';\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1556",
    "index": "A",
    "title": "A Variety of Operations",
    "statement": "William has two numbers $a$ and $b$ initially both equal to \\textbf{zero}. William mastered performing three different operations with them quickly. Before performing each operation some positive integer $k$ is picked, which is then used to perform one of the following operations: (note, that for each operation you can choose a \\textbf{new} positive integer $k$)\n\n- add number $k$ to both $a$ and $b$, or\n- add number $k$ to $a$ and subtract $k$ from $b$, or\n- add number $k$ to $b$ and subtract $k$ from $a$.\n\nNote that after performing operations, numbers $a$ and $b$ may become negative as well.\n\nWilliam wants to find out the minimal number of operations he would have to perform to make $a$ equal to his favorite number $c$ and $b$ equal to his second favorite number $d$.",
    "tutorial": "Note, that after any of the operations, the parity of the expression $a - b$ does not change, so if the initial difference of the pair $c - d$ is odd, then it is impossible to get this pair. Now, note that if we can get a $(c, d)$ pair, then it can be obtained in no more than $2$ operations. To do this, consider three cases: $c = d = 0$ - in this case answer is $0$, because initial pair is $(0, 0)$. $c = d$ - in this case answer is $1$. For this, it is enough for us to use the operation of the first type with $k = c = d$. $c \\neq d$ - in this case answer is $2$. For this we can use the operations of the first type with $k = \\frac{c + d}{2}$. After that, it is enough for us to use either an operation of the second type with $k = c - \\frac{|c - d|}{2}$ if $c > d$, or an operation of the third type with $k = d - \\frac{|c - d|}{2}$ otherwise.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1556",
    "index": "B",
    "title": "Take Your Places!",
    "statement": "William has an array of $n$ integers $a_1, a_2, \\dots, a_n$. In one move he can swap two neighboring items. Two items $a_i$ and $a_j$ are considered neighboring if the condition $|i - j| = 1$ is satisfied.\n\nWilliam wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.",
    "tutorial": "Note that if the condition $|odd - even| > 1$ is satisfied, where $odd$ is the number of odd numbers, and $even$ is the number of even numbers, then it is impossible to get the required array. Now, note that it is enough to consider two cases and choose the minimum answer from these cases: The first element will be an odd number. The first element will be an even number. Now we will describe the general solution. Suppose we are now at position $i$ and we must put an element with parity $cur$ on it. Then, we need to find the first element with opposite parity $a_j$, where $i \\le j$. After we have done this, it is enough to swap $a_i$ and $a_j$ and add $j - i$ to the answer. To quickly search for a suitable element, it is enough to use two pointers, which will point to the current available even and odd numbers.",
    "tags": [
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1556",
    "index": "C",
    "title": "Compressed Bracket Sequence",
    "statement": "William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $c_1, c_2, \\dots, c_n$ where $c_i$ is the number of consecutive brackets \"(\" if $i$ is an odd number or the number of consecutive brackets \")\" if $i$ is an even number.\n\nFor example for a bracket sequence \"((())()))\" a corresponding sequence of numbers is $[3, 2, 1, 3]$.\n\nYou need to find the total number of continuous subsequences (subsegments) $[l, r]$ ($l \\le r$) of the original bracket sequence, which are regular bracket sequences.\n\nA bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters \"+\" and \"1\" into this sequence. For example, sequences \"(())()\", \"()\" and \"(()(()))\" are regular, while \")(\", \"(()\" and \"(()))(\" are not.",
    "tutorial": "Let's examine a compressed sequence and fix two indexes $l < r, l$ % $2 = 0, r$ % $2 = 1$. Note that it makes no sense to examine other indexes because the correct bracket sequence always begins with the opening bracket and ends with the closing one. Next, we can calculate the minimum bracket balance on the segment from $l + 1$ to $r - 1$. The minimum bracket balance is the minimum number of opening brackets that we must put before the sequence of brackets in order for it to be regular, provided that we can put any number of closing brackets at the end. Let's denote this number as $minBalance$, and denote the sum of $-c_{l + 1} + c_{l + 2} - c_{l + 2} + \\dots$ as $balance$. The next observation is that if we fix the number of opening brackets taken from $c_l$, then we can count the number of brackets that we should take from $c_r$. Using these observations we can calculate the answer for $l..r$ using the following formula: $min(c_l, c_r-balance) - max(1, minBalance) + 1$. Note that this problem could also be solved in $O(n)$, but this was not required.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1556",
    "index": "D",
    "title": "Take a Guess",
    "statement": "\\textbf{This is an interactive task}\n\nWilliam has a certain sequence of integers $a_1, a_2, \\dots, a_n$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $2 \\cdot n$ of the following questions:\n\n- What is the result of a bitwise AND of two items with indices $i$ and $j$ ($i \\neq j$)\n- What is the result of a bitwise OR of two items with indices $i$ and $j$ ($i \\neq j$)\n\nYou can ask William these questions and you need to find the $k$-th smallest number of the sequence.\n\nFormally the $k$-th smallest number is equal to the number at the $k$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $[5, 3, 3, 10, 1]$ $4$th smallest number is equal to $5$, and $2$nd and $3$rd are $3$.",
    "tutorial": "To solve this problem, we can use the fact that $a+b=(a$ or $b) + (a$ and $b)$. Then we can determine the first $3$ numbers in $6$ operations using the sums $a_{01} = a_0 + a_1$, $a_{12} = a_1 + a_2$ and $a_{02} = a_0 + a_2$. Using the formula $a_1 = \\frac{a_{01}+a_{12}-a_{02}}{2}$, $a_0 = a_{01} - a_1$ and $a_2 = a_{12} - a_1$. Knowing one of the numbers, it is quite simple to find all the other numbers using the same principle by using $2 \\cdot n$ operations. Then we just need to sort the resulting array and output the k-th element.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1556",
    "index": "E",
    "title": "Equilibrium",
    "statement": "William has two arrays $a$ and $b$, each consisting of $n$ items.\n\nFor some segments $l..r$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $i$ from $l$ to $r$ holds $a_i = b_i$.\n\nTo perform a balancing operation an even number of indices must be selected, such that $l \\le pos_1 < pos_2 < \\dots < pos_k \\le r$. Next the items of \\textbf{array a} at positions $pos_1, pos_3, pos_5, \\dots$ get incremented by one and the items of \\textbf{array b} at positions $pos_2, pos_4, pos_6, \\dots$ get incremented by one.\n\nWilliam wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.",
    "tutorial": "The first step to solving this problem is to create some array $C$, where $c_i = a_i - b_i$. Then we can select some elements from this array C and do operations $+1, -1, +1, -1 \\dots$ for these elements for the corresponding elements. And the challenge is to make this array consist of zeros. It is argued that this can always be done if the following conditions are met: 1. no prefix with positive-sum and no suffix with negative 2. the sum of all elements is zero Let us prove the sufficiency of these conditions: we can find the smallest prefix with a negative sum and the smallest suffix with a positive one, do the operation with one $+1$ and one $-1$, and reduce the sum of the absolute values of the elements. Assertion: the minimum number of operations is the maximum modulus of the sum on the subsegment. This is a lower estimate, since on any segment, the sum changes by at most 1. Let us prove the upper bound by presenting a constructive solution. Let now the array of differences $c_1, c_2, \\dots, c_n$, and the maximum modulus of the sum is $M$. Let's do the following: find the first negative number, there is $+1$, the first positive number after it, there is $-1$, and so on. Statement: the last operation will be $-1$, because otherwise, our last nonzero number is negative, which means it is a negative prefix. We can reformulate greed as follows: throw out all zeros, put $+1$ in the first element for each negative segment, and $-1$ for each positive one in the first element. Let us prove that on any subsegment with the sum $M$, it has decreased in absolute value. Without loss of generality, consider the segment $[l, r]$ with a positive-sum [the prefix corresponds to the suffix]. Consider again the array obtained by throwing out zeros. It is clear that our segment $[l, r]$ did not cut any segment of negative/positive ones, otherwise, it has no maximum sum. It is also clear that the first and last segments in $[l, r]$ are positive, so we have bet $-1$ more than $+1$.",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1556",
    "index": "F",
    "title": "Sports Betting",
    "statement": "William is not only interested in trading but also in betting on sports matches. $n$ teams participate in each match. Each team is characterized by strength $a_i$. Each two teams $i < j$ play with each other exactly once. Team $i$ wins with probability $\\frac{a_i}{a_i + a_j}$ and team $j$ wins with probability $\\frac{a_j}{a_i + a_j}$.\n\nThe team is called a winner if it directly or indirectly defeated all other teams. Team $a$ defeated (directly or indirectly) team $b$ if there is a sequence of teams $c_1$, $c_2$, ... $c_k$ such that $c_1 = a$, $c_k = b$ and team $c_i$ defeated team $c_{i + 1}$ for all $i$ from $1$ to $k - 1$. Note that it is possible that team $a$ defeated team $b$ and in the same time team $b$ defeated team $a$.\n\nWilliam wants you to find the expected value of the number of winners.",
    "tutorial": "Let $ALL$ be all teams, and $F(winners)$ be the probability that a set of $winners$ teams are winners, and the rest of $ALL \\setminus winners$ teams are not. Then the answer will be the following value: $\\sum_{winners \\neq \\varnothing, winners \\subseteq ALL} F(winners) \\cdot |winners|$ Let's define extra value: $P(winners)$ - the probability that all teams from the set $winners$ are reachable from each other, that is, they form a cycle. Then $F$ is calculated as follows: $F(winners) = P(winners) \\cdot G(winners, ALL \\setminus winners)$. This is explained as follows: the probability that the set $winners$ will be the set of winners is equal to the probability that the set $winners$ forms a cycle and there is no edge from the set $ALL \\setminus winners$ to $winners$. Where $G(X, Y)$ denotes the probability that all teams from the set $X$ defeat all teams from the set $Y$ directly. More formally speaking, the probability that for every $x$ in $X$, and for every $y$ in $Y$, there is an edge from $x$ to $y$. It remains to learn how to count $P(winners)$. It is easy to see that this can be done using the inclusion-exclusion principle: $P(winners) = 1 - \\sum_{sub \\subset winners, sub \\neq winners} P(sub) \\cdot G(sub, winners \\setminus sub)$ The formula is explained as follows: we need to know the probability that all teams from the set $winners$ are reachable to each other, initially we set this probability equal to $1$, then subtract all options when only some subset $sub$ of the set $winners$ is reachable to itself. $G(X, Y)$ is calculated as follows: $G(X, Y) = \\prod_{x \\in X, y \\in Y} \\frac{a_x}{a_x + a_y}$ Writing these formulas into the code in the simplest way, you can get a solution with asymptotics $O(3^{N} \\cdot N^2)$. Since here $O(3^N)$ pairs $(winners, sub)$ exist, where $winners$ is the set of winners and $sub$ is its subset in the inclusion-exclusion formula. Also, for each such pair, you will have to calculate the value of $G(sub, winners \\setminus sub)$ in $O(N^2)$. But it is possible to calculate $G(X, Y)$ faster. For example, you can notice that $G(X, Y) = \\prod_ {x \\in X} H(x, Y)$, where $H(x, Y)$ is the probability that the command $x$ defeated all teams from the set $Y$ directly. $H$ can be pre-calculated in advance for $O(2^N \\cdot N)$, which will allow us to calculate $G(X, Y)$ in $O(N)$ instead of $O(N^2)$. In a similar way, you can learn how to calculate $G(X, Y)$ in $O(1)$, if you pre-calculate the following four values: $G_{left, left}(X, Y)$, $G_{left, right}(X, Y)$, $G_{right, left}(X, Y)$, $G_{right, right}(X, Y)$. Where $left, right$ is an arbitrary division of teams into two equal (or almost equal) sets, so that $||left| - |right|| \\leq 1$ is satisfied. Where $G_{side_{from}, side_{to}}(X, Y) = G(X, Y)$, only for subsets such that $X \\subseteq side_{from}, Y \\subseteq side_{to}$. As a result: $G(X, Y) = \\prod_{side_{from} \\in \\{ left, right \\} } \\prod_{side_{to} \\in \\{ left, right \\} } G_{side_{from}, side_{to}}(X \\cap side_{from}, Y \\cap side_{to})$ Each of $G_{side_{from}, side_{to}}$ can be pre-calculated in $O(2^N \\cdot N)$. Final asymptotics $O(3^N)$.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "graphs",
      "math",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1556",
    "index": "G",
    "title": "Gates to Another World",
    "statement": "As mentioned previously William really likes playing video games. In one of his favorite games, the player character is in a universe where every planet is designated by a binary number from $0$ to $2^n - 1$. On each planet, there are gates that allow the player to move from planet $i$ to planet $j$ if the binary representations of $i$ and $j$ differ in exactly one bit.\n\nWilliam wants to test you and see how you can handle processing the following queries in this game universe:\n\n- Destroy planets with numbers from $l$ to $r$ inclusively. These planets cannot be moved to anymore.\n- Figure out if it is possible to reach planet $b$ from planet $a$ using some number of planetary gates. It is guaranteed that the planets $a$ and $b$ are not destroyed.",
    "tutorial": "Let's change the formulation of the problem: we will execute queries in reverse order, and assign a lifetime to each segment of blocked vertices. Lifetime - until what moment the segment is blocked. Note, if we look through the requests in reverse order, then for each segment it is possible to determine the moment of time after which the vertices from this segment cease to be blocked. Thus, the problem looks like this: given a graph that is an $n$-dimensional hypercube (each vertex has $n$ edges to adjacent vertices that differ from it by only one coordinate), and there are $m$ blocked vertex segments $[l_i \\dots r_i]$ that live up to the time $t_i$. Consider the following fact: If we take an $n$-dimensional hypercube and sequences of vertices $0, 1, \\dots, 2^{n-1} - 1$ and $2^{n-1}, 2^{n-1} + 1, \\dots, 2^{n} - 1$, then the numbers in the corresponding positions from these two sequences are neighbours to each other, since they differ only in the most significant bit, that is, in the $2^{n-1}$ bit. For a better understanding, let's depict this for $n = 4$: $0000 - 1000$ $0001 - 1001$ $0010 - 1010$ $0011 - 1011$ $0100 - 1100$ $0101 - 1101$ $0110 - 1110$ $0111 - 1111$ Here $a - b$ denotes that $a$ is a neighbour of $b$, and $a$ is present in the first sequence, and $b$ in the second. For simplicity, we will only prohibit movement between a blocked vertex and an unblocked one. Let's learn how to get a \"compressed\" graph, each vertex of which would represent a connected subset of the vertices of the hypercube. Also, this set, which represents a vertex, is a set of consecutive vertices, that is, it is a segment. On each edge of this graph is written the time - when this edge begins to exist. Time makes sense, since an edge can be drawn between a vertex that represents a set of blocked vertices and a vertex that represents a set of unblocked vertices. And the time on this edge there will be a moment in time when the set of vertices is unblocked. Recall that now we are solving a problem in which the vertices are blocked until a certain moment in time. The answer to the reachability request is the reachability request for a given \"compressed\" graph. It is only necessary to correctly determine the reachability of which two vertices of the \"compressed\" graph we are interested in. Let's learn how to recursively build a given compressed graph. Input data for the construction of this graph are: $n$ - the dimension of the hypercube, $S = \\{ (l_i, r_i) \\}$ - the set of blocked vertices. If there are no segments worth blocking, then the compressed graph is one vertex, which is responsible for the connected set $\\{0, 1, 2, \\dots, 2^{n} - 1 \\}$ of hypercube vertices. If there is one segment $(l_i, r_i) = (0, 2^{n} - 1)$, then the compressed graph is one vertex representing all vertices, and they are all blocked. Otherwise, we can divide the hypercube into two parts: by the most significant bit. That is, into two hypercubes of dimensions $2^{n-1}$. And each segment $l_i, r_i$ can go further, as input, either into two hypercubes, or into one of them. Having received compressed graphs from each of the two hypercubes, we can match the adjacent vertices of these hypercubes, as illustrated above. It is not difficult to combine two such graphs, since each vertex of the graph describes the set of vertices of the hypercube, and this set is a segment, therefore, if we have the vertices of the first and second graphs, $V_1$ and $V_2$, respectively, in ascending order of the segments for which they answer, then it is possible to combine these two graphs in $O(|V_1| + |V_2|)$ time, and create no more than $O(|V_1| + |V_2|)$ edges and obtain a new graph of size $|V_1| + |V_2|$. In total, the resulting graph will have a size of $n \\times m$, and the final asymptotics will be $O(n^2 \\times m \\times ACK)$, where $ACK$ is the cost of the operation in the DSU. The DSU is needed to pass queries in reverse order and connect the edges at the right times when the edges begin to exist. The asymptotics is as follows, since each vertex of the graph may go through all $n$ layers of recursion (as you may have noticed, the solution procedure resembles divide and conquer) and at the same time create a new edge in each layer. And the graph has such a size, since each blocked segment in this procedure can be split into $n$ segments. For a better understanding, see the author's solution.",
    "tags": [
      "bitmasks",
      "data structures",
      "dsu",
      "two pointers"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1556",
    "index": "H",
    "title": "DIY Tree",
    "statement": "William really likes puzzle kits. For one of his birthdays, his friends gifted him a complete undirected edge-weighted graph consisting of $n$ vertices.\n\nHe wants to build a spanning tree of this graph, such that for the first $k$ vertices the following condition is satisfied: the degree of a vertex with index $i$ does not exceed $d_i$. Vertices from $k + 1$ to $n$ may have any degree.\n\nWilliam wants you to find the minimum weight of a spanning tree that satisfies all the conditions.\n\nA spanning tree is a subset of edges of a graph that forms a tree on all $n$ vertices of the graph. The weight of a spanning tree is defined as the sum of weights of all the edges included in a spanning tree.",
    "tutorial": "Let's call the first $k$ vertices special. First of all, let's note that the number of different forests on $5$ vertices is at most $300$. It means that we can try all of them, one by one, as the set of all edges of the answer with both endpoints being the special vertices. Let $T$ be the set of chosen edges with both endpoints being the special vertices. With fixed $T$, only edges with zero or one endpoint at special vertices are left. From now on, we will only consider subsets of these edges. We will introduce two matroids: Matroid $A$ is defined as follows: A set of edges $E$ is independent for matroid $A$, if the set $E \\cup T$ has no cycles. $A$ is a matroid, because: Deleting edges produces no cycles, so if $F$ is a superset of $E$ and $F$ is independent, then $E$ is also independent. If $|F| > |E|$, $F$ is independent and $E$ is independent, then from the graphic matroid there should be an edge in $T \\cup F$ that connects connected components in $T \\cup E$. This edge can't be from $T$, so there is an element $x \\in F$, s. t. $E \\cup \\{x\\}$ is also independent. A set of edges $E$ is independent for matroid $A$, if the set $E \\cup T$ has no cycles. $A$ is a matroid, because: Deleting edges produces no cycles, so if $F$ is a superset of $E$ and $F$ is independent, then $E$ is also independent. If $|F| > |E|$, $F$ is independent and $E$ is independent, then from the graphic matroid there should be an edge in $T \\cup F$ that connects connected components in $T \\cup E$. This edge can't be from $T$, so there is an element $x \\in F$, s. t. $E \\cup \\{x\\}$ is also independent. Matroid $B$ is defined as follows. A set of edges $E$ is independent for matroid $B$, if in the set $E \\cup T$ degrees of vertices $[1,2,\\ldots,k]$ don't exceed $[d_1,d_2,\\ldots,d_k]$, respectively. $B$ is a matroid, because: Deleting edges decreases degrees, so if $F$ is a superset of $E$ and $F$ is independent, then $E$ is also independent. If $|F| > |E|$, $F$ is independent and $E$ is independent, then one of the following statements is true. Either there is an edge with zero endpoints at special vertices in $F \\setminus E$, and we can add it to $E$ preserving independence. Or there is some vertex $v \\in \\{1,2,\\ldots,k\\}$ that has larger degree in $F$ than in $E$, and we can take one of adjacent edges that are present in $F \\setminus E$ and add it to $E$. Thus, there is an element $x \\in F$, s. t. $E \\cup \\{x\\}$ is also independent. Let's find the minimum weight base $E$ in the intersection of matroids $A$ and $B$. If it has enough edges, we can relax the answer with the total weight of edges in $E \\cup T$. Also note that we are only interested in edges from $\\{1, \\ldots, k\\} \\times \\{k+1,\\ldots,n\\}$ and in the MST of edges from $\\{k+1,\\ldots,n\\}$, so we only have $O(nk)$ edges we need to consider. Total complexity is $O(\\mathrm{exp}(k) \\cdot \\mathrm{poly}(n)))$, and it will easily fit into TL if your solution is efficient enough. A set of edges $E$ is independent for matroid $B$, if in the set $E \\cup T$ degrees of vertices $[1,2,\\ldots,k]$ don't exceed $[d_1,d_2,\\ldots,d_k]$, respectively. $B$ is a matroid, because: Deleting edges decreases degrees, so if $F$ is a superset of $E$ and $F$ is independent, then $E$ is also independent. If $|F| > |E|$, $F$ is independent and $E$ is independent, then one of the following statements is true. Either there is an edge with zero endpoints at special vertices in $F \\setminus E$, and we can add it to $E$ preserving independence. Or there is some vertex $v \\in \\{1,2,\\ldots,k\\}$ that has larger degree in $F$ than in $E$, and we can take one of adjacent edges that are present in $F \\setminus E$ and add it to $E$. Thus, there is an element $x \\in F$, s. t. $E \\cup \\{x\\}$ is also independent. Let's find the minimum weight base $E$ in the intersection of matroids $A$ and $B$. If it has enough edges, we can relax the answer with the total weight of edges in $E \\cup T$. Also note that we are only interested in edges from $\\{1, \\ldots, k\\} \\times \\{k+1,\\ldots,n\\}$ and in the MST of edges from $\\{k+1,\\ldots,n\\}$, so we only have $O(nk)$ edges we need to consider. Total complexity is $O(\\mathrm{exp}(k) \\cdot \\mathrm{poly}(n)))$, and it will easily fit into TL if your solution is efficient enough.",
    "tags": [
      "graphs",
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1557",
    "index": "A",
    "title": "Ezzat and Two Subsequences",
    "statement": "Ezzat has an array of $n$ integers \\textbf{(maybe negative)}. He wants to split it into two \\textbf{non-empty} subsequences $a$ and $b$, such that every element from the array belongs to exactly one subsequence, and the value of $f(a) + f(b)$ is the maximum possible value, where $f(x)$ is the average of the subsequence $x$.\n\nA sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) elements.\n\nThe average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.\n\nFor example, the average of $[1,5,6]$ is $(1+5+6)/3 = 12/3 = 4$, so $f([1,5,6]) = 4$.",
    "tutorial": "The average of a group of numbers always has a value between the minimum and maximum numbers in that group. Since the average of a group of numbers always has a value between the minimum and maximum numbers in that group, it can be proved that the best approach to obtain the maximum sum of averages of two subsequences is to put the maximum number alone into one subsequence, and the rest of the numbers into the other subsequence. A proof by contradiction follows. Assume a sorted array, so $a_1 \\le a_2 \\le \\ldots \\le a_n$. Assume that there exists a bigger answer if you take the two greatest numbers (instead of only one) in one subsequence. Therefore, we need to prove that: $\\sum_{i=1}^{n-1} a_i / (n - 1) + a_n < \\sum_{i=1}^{n-2} a_i / (n - 2) + (a_{n-1} + a_n) / 2$ By simplifying the inequality: $a_n < 2 / (n - 1) \\cdot \\sum_{i=1}^{n-2} a_i / (n - 2) + (n - 3) / (n - 1) \\cdot a_{n-1}$ Assume $avg_1 = \\sum_{i=1}^{n-2} a_i / (n - 2)$, so $a_1 \\le avg_1 \\le a_{n-2}$ as stated at the beginning of the tutorial. The inequality becomes: $a_n < (2 \\cdot avg_1 + (n - 3) \\cdot a_{n-1}) / (n - 1)$ The right-hand side of the inequality is also an average $avg_2$, such that $avg_1 \\le avg_2 \\le a_{n-1}$ (which can be further simplified to $a_1 \\le avg_2 \\le a_{n-1}$). This means that $a_n$ is strictly less than $avg_2$. In other words, it states that $a_n$ is strictly less than a certain number between $a_1$ and $a_{n-1}$. This is a contradiction as we stated at the beginning of the proof that the array is sorted ($a_n \\ge a_{n-1} \\ge \\ldots \\ge a_1$). Summing things up, taking at least one number along with the maximum number will never yield a greater answer.",
    "code": "#define  _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\nusing namespace std;\nvoid run() {\n\tios::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n#ifndef ONLINE_JUDGE\n\tfreopen(\"input.txt\", \"r\", stdin);\n#else\n#endif\n}\n \nint main() {\n\trun();\n\tcout << fixed << setprecision(10);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> v(n);\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tcin >> v[i];\n\t\tint mx = v[0];\n\t\tlong long sum = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (v[i] > mx)\n\t\t\t\tmx = v[i];\n\t\t\tsum += v[i];\n\t\t}\n\t\tcout << 1.0 * (sum - mx) / (n - 1) + mx << endl;\n\t}\n}",
    "tags": [
      "brute force",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1557",
    "index": "B",
    "title": "Moamen and k-subarrays",
    "statement": "Moamen has an array of $n$ \\textbf{distinct} integers. He wants to sort that array in non-decreasing order by doing the following operations in order \\textbf{exactly once}:\n\n- Split the array into exactly $k$ non-empty subarrays such that each element belongs to exactly one subarray.\n- Reorder these subarrays arbitrary.\n- Merge the subarrays in their new order.\n\nA sequence $a$ is a subarray of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\nCan you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?",
    "tutorial": "You can ignore the $k$ given in the input, try to find the minimum $k$ you need to sort the array (let call it $mnK$). If $mnK$ $\\le$ $k$ then you can split some subarrays to make it equal $k$, so the answer is will be \"YES\". otherwise, the answer will be \"NO\". You need to split the array into the minimum number of subarrays such that each subarray is sorted. This problem can be solved for \\textbf{at least} $k$ subarrays as it is easy to just add extra subarrays (if needed) to achieve \\textbf{exactly} $k$ subarrays. To solve this problem, you need to know what are the numbers that can be grouped into the same subarray. This can be done by maintaining the sorted array along with the non-sorted array. As the numbers are distinct, we can iterate over the non-sorted array, and just add each element $a_i$ to the subarray ending in $a_{i - 1}$ IFF they follow each other in the sorted array, or start a new subarray if they do not follow each other. For example, if the (non-sorted) array is $[$ $2$, $3$, $-1$, $1$], the sorted array will be $[$ $-1$, $1$, $2$, $3$ $]$. If we iterate over the non-sorted array, we will add $2$ to a new subarray, then we will add $3$ to the same subarray as they follow each other in the sorted array. After that, we will start a new subarray at $-1$ as $-1$ and $3$ do not follow each other in the sorted array. Finally, we will add $1$ to the subarray containing $-1$. It should end up like this: { $[$ $2$, $3$ $]$, $[$ $-1$, $1$ $]$ }. Using this approach, you can get the smallest number of subarrays needed. If it is strictly greater than the given $k$, the answer is ''NO''. Otherwise, it is ''YES''.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define endl \"\\n\"\nvoid run() {\n\tios::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n#ifndef ONLINE_JUDGE\n\tfreopen(\"input.txt\", \"r\", stdin);\n#else\n#endif\n}\n \n \nint main() {\n\trun();\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<pair<int, int>> v(n);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> v[i].first;\n\t\t\tv[i].second = i;\n\t\t}\n\t\tsort(v.begin(), v.end());\n\t\tint ans = 1;\n\t\tfor (int i = 1; i < n; i++)\n\t\t\tif (v[i - 1].second + 1 != v[i].second)\n\t\t\t\tans++;\n\t\tcout << (ans <= k ? \"YES\" : \"NO\") << endl;\n\t}\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1557",
    "index": "C",
    "title": "Moamen and XOR",
    "statement": "Moamen and Ezzat are playing a game. They create an array $a$ of $n$ non-negative integers where every element is less than $2^k$.\n\nMoamen wins if $a_1 \\,\\&\\, a_2 \\,\\&\\, a_3 \\,\\&\\, \\ldots \\,\\&\\, a_n \\ge a_1 \\oplus a_2 \\oplus a_3 \\oplus \\ldots \\oplus a_n$.\n\nHere $\\&$ denotes the bitwise AND operation, and $\\oplus$ denotes the bitwise XOR operation.\n\nPlease calculate the number of winning for Moamen arrays $a$.\n\nAs the result may be very large, print the value modulo $1\\,000\\,000\\,007$ ($10^9 + 7$).",
    "tutorial": "We don't care about the values in the array to know it's valid or not, we just need to know for every bit how many numbers have this bit on or off. Try to build the array from the most significant bit ($k-1$) to the least significant bit $0$ using dynamic programming. Can you optimize dynamic programming code with some combinatorics? From now on, I will use $And$ to describe the result of the bitwise AND operation over all the elements in the array, and $Xor$ to describe the result of the bitwise XOR operation over all the elements in the array. Let's call the array is valid if the value of $And$ $\\ge$ $Xor$. We don't care about the values in the array. We just need to know, for every bit, the number of indices at which this bit is on or off. So let's build the array from the most significant bit ($k-1$) to the least significant bit ($0$) using dynamic programming and combinatorics optimization. Define an array $dp$ where $dp_{i, equal}$ $=$ the number of ways to build the array from the $i$-th bit to $0$-th bit. $equal$ is $true$ if $And$ $=$ $Xor$ in the previous bits, and $false$ if $And$ $>$ $Xor$ ($And$ $<$ $Xor$ is not a valid state). Our base case is $dp_{-1,0}$ $=$ $1$, and $dp_{-1,1}$ $=$ $1$. If $equal$ is $false$ at any moment, then you can choose any subset of indices to contain $1$ in the $i$-th bit. Therefore, $dp_{i,0}$ $=$ $2^n$ $\\cdot$ $dp_{i-1,0}$. If $equal$ is $false$ at any moment, then you can choose any subset of indices to contain $1$ in the $i$-th bit. Therefore, $dp_{i,0}$ $=$ $2^n$ $\\cdot$ $dp_{i-1,0}$. Now if $n$ is odd there are $2$ possible choices: You can make $i$-th bit $=$ $1$ in an even number of indices, then $And_i$ will be $0$ and $Xor_i$ will be $0$ too. You can make $i$-th bit $=$ $1$ in all indices, then $And_i$ will be $1$ and $Xor_i$ will be $1$ too. You Don't have any other valid choices. So $dp_{i,1}$ $=$ $dp_{i-1,1}$ $\\cdot$ ({number of ways to choose number of indices from $n$} $+$ $1$). ($+1$ for the second choice). Now if $n$ is odd there are $2$ possible choices: You can make $i$-th bit $=$ $1$ in an even number of indices, then $And_i$ will be $0$ and $Xor_i$ will be $0$ too. You can make $i$-th bit $=$ $1$ in all indices, then $And_i$ will be $1$ and $Xor_i$ will be $1$ too. You Don't have any other valid choices. So $dp_{i,1}$ $=$ $dp_{i-1,1}$ $\\cdot$ ({number of ways to choose number of indices from $n$} $+$ $1$). ($+1$ for the second choice). If $n$ is even there are $2$ possible choices: You can make $i$-th bit $=$ $1$ in an even number (less than $n$) of indices, then $And_i$ will be $0$ and $Xor_i$ will be $0$ also. You can make $i$-th bit $=$ $1$ in all indices, then $And_i$ will be $1$ and $Xor_i$ will be $0$. and now $equal$ will be $false$. You Don't have any other valid choices. So $dp_{i,1}$ $=$ $dp_{i-1,1}$ $\\cdot$ (number of ways to choose number of indices from $n$ ) + $dp_{i-1,0}$. If $n$ is even there are $2$ possible choices: You can make $i$-th bit $=$ $1$ in an even number (less than $n$) of indices, then $And_i$ will be $0$ and $Xor_i$ will be $0$ also. You can make $i$-th bit $=$ $1$ in all indices, then $And_i$ will be $1$ and $Xor_i$ will be $0$. and now $equal$ will be $false$. You Don't have any other valid choices. So $dp_{i,1}$ $=$ $dp_{i-1,1}$ $\\cdot$ (number of ways to choose number of indices from $n$ ) + $dp_{i-1,0}$. We can precalculate the factorial, to get $nCr$ in $\\mathcal{O}(1)$, and then calculate the number of ways to choose an even number from $n$ before starting the $dp$. The total complexity will be $\\mathcal{O}(k + n)$.",
    "code": "#define  _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\n#include <unordered_map>\n#include <unordered_set>\nusing namespace std;\n#define endl \"\\n\"\n#define ll long long\nvoid run() {\n\tios::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n#ifndef ONLINE_JUDGE\n\tfreopen(\"input.txt\", \"r\", stdin);\n#else\n#endif\n}\n \nconst int N = 2e5 + 1;\nconst int MOD = 1e9 + 7;\nll fact[N], inv[N], invfact[N];\nvoid factInverse() {\n\tfact[0] = inv[1] = fact[1] = invfact[0] = invfact[1] = 1;\n\tfor (long long i = 2; i < N; i++) {\n\t\tfact[i] = (fact[i - 1] * i) % MOD;\n\t\tinv[i] = MOD - (inv[MOD % i] * (MOD / i) % MOD);\n\t\tinvfact[i] = (inv[i] * invfact[i - 1]) % MOD;\n\t}\n}\n \nint add(int a, int b) {\n\tif ((a += b) >= MOD)\n\t\ta -= MOD;\n\telse if (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n \nll mul(int x, int y) {\n\treturn (1LL * x * y) % MOD;\n}\n \nll nCr(int n, int r) {\n\tif (r > n)\n\t\treturn 0;\n\treturn mul(mul(fact[n], invfact[r]), invfact[n - r]);\n}\n \nint mem[N][2], vis[N][2], test_id;\nint cntEven, _2pwn, n;\nint dp(int i, bool equal) {\n\tif (i < 0)\n\t\treturn 1;\n\tint& rt = mem[i][equal];\n\tif (vis[i][equal] == test_id)\n\t\treturn rt;\n\tvis[i][equal] = test_id;\n\tif (equal == false)\n\t\treturn rt = mul(_2pwn, dp(i - 1, 0));\n\tif (n & 1)\n\t\treturn rt = mul(dp(i - 1, 1), add(cntEven, 1));\n\treturn rt = add(mul(dp(i - 1, 1), cntEven), dp(i - 1, 0));\n}\n \nint main() {\n\trun();\n\tfactInverse();\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\ttest_id++;\n\t\tint k;\n\t\tcin >> n >> k;\n\t\tcntEven = 0;\n\t\tfor (int i = 0; i < n; i += 2)\n\t\t\tcntEven = add(cntEven, nCr(n, i));\n\t\t_2pwn = 1;\n\t\tfor (int i = 0; i < n; i++)\n\t\t\t_2pwn = mul(_2pwn, 2);\n\t\tcout << dp(k - 1, 1) << endl;\n\t}\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math",
      "matrices"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1557",
    "index": "D",
    "title": "Ezzat and Grid",
    "statement": "Moamen was drawing a grid of $n$ rows and $10^9$ columns containing only digits $0$ and $1$. Ezzat noticed what Moamen was drawing and became interested in the minimum number of rows one needs to remove to make the grid beautiful.\n\nA grid is beautiful if and only if for every two consecutive rows there is at least one column containing $1$ in these two rows.\n\nEzzat will give you the number of rows $n$, and $m$ segments of the grid that contain digits $1$. Every segment is represented with three integers $i$, $l$, and $r$, where $i$ represents the row number, and $l$ and $r$ represent the first and the last column of the segment in that row.\n\nFor example, if $n = 3$, $m = 6$, and the segments are $(1,1,1)$, $(1,7,8)$, $(2,7,7)$, $(2,15,15)$, $(3,1,1)$, $(3,15,15)$, then the grid is:\n\nYour task is to tell Ezzat the minimum number of rows that should be removed to make the grid beautiful.",
    "tutorial": "Try to count the maximum number of rows that makes a beautiful grid, and remove the others. Can you get some dynamic programming formula, and then optimize it with some ranges data structures? We can use dynamic programming to get the maximum number of rows that make a beautiful grid. Define the 2d array, $dp$, where $dp_{i,j}$ $=$ maximum number of rows (from row $1$ to row $i$) that make a beautiful grid, and has $1$ in column $j$ at the last row I have in the biggest beautiful grid. the last row in the biggest beautiful grid is the not necessary to be $i$ Form the definition: $dp_{0,j}$ $=$ $0$. $dp_{0,j}$ $=$ $0$. $dp_{i,j}$ $=$ $1$ $+$ $\\max_{k \\in C_i}$ {$dp_{i-1,k}$} if $grid_{i,j}$ $=$ $1$. $dp_{i,j}$ $=$ $1$ $+$ $\\max_{k \\in C_i}$ {$dp_{i-1,k}$} if $grid_{i,j}$ $=$ $1$. Otherwise, if $grid_{i,j}$ $\\neq$ $1$, then $dp_{i,j}$ $=$ $dp_{i-1,j}$ . Otherwise, if $grid_{i,j}$ $\\neq$ $1$, then $dp_{i,j}$ $=$ $dp_{i-1,j}$ . where $C_i$ is that set of columns that contain $1$ in row $i$. As you know, the set $C_i$ contains the intervals, so we just search in some intervals for the maximum, or update some intervals in the previous layer in $dp$. We can do it faster using Segment tree. So the algorithm will be as follows: Define an array $prev$, where $prev_i$ $=$ the previous row of $i$ in which maximum beautiful grid end with $i$-th row. We will use it to get the rows that will not be removed. Define an array $prev$, where $prev_i$ $=$ the previous row of $i$ in which maximum beautiful grid end with $i$-th row. We will use it to get the rows that will not be removed. Build a segment tree of pairs ($value$, $index$) initially with { $0$ , $-1$ }. Build a segment tree of pairs ($value$, $index$) initially with { $0$ , $-1$ }. Then for each $i$ from $1$ to $n$: Get the maximum value in all the ranges $[l_j,r_j]$ that contains $1$ at the $i$-th row. Let's call it $mx$. Store $prev_{i}$ $=$ $mx.index$. Update all the ranges $[l_j,r_j]$ of this row like this: $seg_j$ $=$ $max($ $seg_j$ $,$ { $mx.value$ $+$ $1$ $,$ $i$ }). Finally, get the rows that have the maximum value using the $prev$ array, and remove the others. Then for each $i$ from $1$ to $n$: Get the maximum value in all the ranges $[l_j,r_j]$ that contains $1$ at the $i$-th row. Let's call it $mx$. Store $prev_{i}$ $=$ $mx.index$. Update all the ranges $[l_j,r_j]$ of this row like this: $seg_j$ $=$ $max($ $seg_j$ $,$ { $mx.value$ $+$ $1$ $,$ $i$ }). Finally, get the rows that have the maximum value using the $prev$ array, and remove the others. The total complexity will be $\\mathcal{O}(n + m\\log{}10^9)$ or $\\mathcal{O}(n + m\\log{}m)$ if you make a coordinate compression to the values.",
    "code": "#define  _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\n#include <unordered_map>\n#include <unordered_set>\nusing namespace std;\n#define endl \"\\n\"\n#define ll long long\n#define sz(s) (int)(s.size())\n#define INF 0x3f3f3f3f3f3f3f3fLL\n#define all(v) v.begin(),v.end()\n#define watch(x) cout<<(#x)<<\" = \"<<x<<endl\nconst int dr[]{ -1, -1, 0, 1, 1, 1, 0, -1 };\nconst int dc[]{ 0, 1, 1, 1, 0, -1, -1, -1 };\n#if __cplusplus >= 201402L\ntemplate<typename T>\nvector<T> create(size_t n) {\n\treturn vector<T>(n);\n}\ntemplate<typename T, typename ... Args>\nauto create(size_t n, Args ... args) {\n\treturn vector<decltype(create<T>(args...))>(n, create<T>(args...));\n}\n#endif\nvoid run() {\n\tios::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n#ifndef ONLINE_JUDGE\n\tfreopen(\"input.txt\", \"r\", stdin);\n#else\n#endif\n}\n \n \nconst pair<int, int> NIL = { 0,-1 };\nstruct segment_tree {\n#define LEFT (idx<<1)\n#define RIGHT (idx<<1|1)\n#define MID (start+end>>1)\n\tint n;\n\tvector<pair<int, int>> tree, lazy;\n\tsegment_tree(int n) :n(n) {\n\t\ttree = lazy = vector<pair<int, int>>(n << 2, NIL);\n\t}\n\tvoid push_down(int idx, int start, int end) {\n\t\tif (lazy[idx] == NIL)\n\t\t\treturn;\n\t\ttree[idx] = max(tree[idx], lazy[idx]);\n\t\tif (start != end) {\n\t\t\tlazy[LEFT] = max(lazy[LEFT], lazy[idx]);\n\t\t\tlazy[RIGHT] = max(lazy[RIGHT], lazy[idx]);\n\t\t}\n\t\tlazy[idx] = NIL;\n\t}\n\tvoid update(int idx, int start, int end, int l, int r, pair<int, int> p) {\n\t\tpush_down(idx, start, end);\n\t\tif (r < start || end < l)\n\t\t\treturn;\n\t\tif (l <= start && end <= r) {\n\t\t\tlazy[idx] = max(lazy[idx], p);\n\t\t\tpush_down(idx, start, end);\n\t\t\treturn;\n\t\t}\n\t\tupdate(LEFT, start, MID, l, r, p);\n\t\tupdate(RIGHT, MID + 1, end, l, r, p);\n\t\ttree[idx] = max(tree[LEFT], tree[RIGHT]);\n\t}\n\tpair<int, int> query(int idx, int start, int end, int l, int r) {\n\t\tpush_down(idx, start, end);\n\t\tif (r < start || end < l)\n\t\t\treturn NIL;\n\t\tif (l <= start && end <= r)\n\t\t\treturn tree[idx];\n\t\treturn max(query(LEFT, start, MID, l, r),\n\t\t\tquery(RIGHT, MID + 1, end, l, r));\n\t}\n\tvoid update(int l, int r,pair<int,int> p) {\n\t\tupdate(1, 1, n, l, r, p);\n\t}\n\tpair<int, int> query(int l, int r) {\n\t\treturn query(1, 1, n, l, r);\n\t}\n};\nint main() {\n\trun();\n\tint n, m;\n\tcin >> n >> m;\n\tvector<vector<pair<int, int>>> v(n);\n\tvector<int> id;\n\twhile (m--) {\n\t\tint i, l, r;\n\t\tcin >> i >> l >> r;\n\t\tid.push_back(l);\n\t\tid.push_back(r);\n\t\tv[i - 1].push_back({ l,r });\n\t}\n\tsort(all(id));\n\tid.erase(unique(all(id)), id.end());\n\tfor (int i = 0; i < n; i++)\n\t\tfor (auto& it : v[i]) {\n\t\t\tit.first = upper_bound(all(id), it.first) - id.begin();\n\t\t\tit.second = upper_bound(all(id), it.second) - id.begin();\n\t\t}\n\tsegment_tree seg(id.size());\n\tvector<int> prv(n, -1);\n\tfor (int i = 0; i < n; i++) {\n\t\tpair<int, int> mx = NIL;\n\t\tfor (auto& it : v[i])\n\t\t\tmx = max(mx, seg.query(it.first, it.second));\n \n\t\tprv[i] = mx.second;\n\t\tmx.first++;\n\t\tmx.second = i;\n\t\tfor (auto& it : v[i])\n\t\t\tseg.update(it.first, it.second, mx);\n\t}\n\tpair<int, int> p = seg.query(1, id.size());\n\tvector<bool> vis(n);\n\tint cur = p.second;\n\twhile (cur != -1) {\n\t\tvis[cur] = true;\n\t\tcur = prv[cur];\n\t}\n \n\tcout << n - p.first << endl;\n\tfor (int i = 0; i < n; i++)\n\t\tif (!vis[i])\n\t\t\tcout << i + 1 << ' ';\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1557",
    "index": "E",
    "title": "Assiut Chess",
    "statement": "This is an interactive problem.\n\nICPC Assiut Community decided to hold a unique chess contest, and you were chosen to control a queen and hunt down the hidden king, while a member of ICPC Assiut Community controls this king.\n\nYou compete on an $8\\times8$ chessboard, the rows are numerated from top to bottom, and the columns are numerated left to right, and the cell in row $x$ and column $y$ is denoted as $(x, y)$.\n\nIn one turn you can move the queen to any of the squares on the same horizontal line, vertical line, or any of the diagonals. For example, if the queen was on square ($4$, $5$), you can move to ($q_1$, $5$), ($4$, $q_1$), ($q_1$, $9-q_1$), or ($q_2$, $q_2+1$) where ($1 \\le q_1 \\le 8$, $q_1 \\ne 4$, $1 \\le q_2 \\le 7$, $q_2 \\ne 4$). Note that the queen \\textbf{cannot} stay on its current cell.\n\nIn one turn, the king can move \"Right\", \"Left\", \"Up\", \"Down\", \"Down-Right\", \"Down-Left\", \"Up-Left\", or \"Up-Right\" such that he doesn't get out of the board. The king \\textbf{cannot} move into a cell that is on the same row, column or diagonal with the queen (including the position of the queen itself). For example, if the king was on square ($4$, $5$), he can move to ($4+k_1$, $5+k_2$) where ($-1 \\le k_1,k_2 \\le 1$, $(k_1, k_2) \\ne (0, 0)$).\n\nAt the start of the game, you should place the queen at any location on the board, and this is done once per game. After that the king is secretly placed at any cell different from the queen's location. You do not know the position of the king. Then, the king and the queen take turns with the king moving first. The king moves to one of the possible directions (\"Right\", \"Down\", \"Up-Left\", etc.), and you are only given the direction it moves to. After that, you should move your queen by declaring the square to which your queen will move. The game follows like this until you win the game or run out of moves.\n\nYou win if the king has no valid moves. You lose if after $130$ moves of the queen the king still has valid moves.",
    "tutorial": "Try to force the king to move into one of the corners down. If you put the queen in a row $x$, move the queen to the left of the row, then start swiping the row right, one square at a time. If you've visited all $8$ squares on the row and the king never made a vertical move, it means $|$ current king row $-$ current queen row $|$ $\\ge 2$ (if the king were on row ($x + 1$\\$x-1$), he would've been forced to move $1$ square (down\\up) at some point). This is one of many possible solutions. We need to force the king to move into one of the four corners (bottom right or bottom left corner in this solution) to ensure that the king will be trapped (cannot move anymore). Place the queen on the top row. After the king makes a $1$ move, he should be below the queen's row. Suppose the queen is on the row $x$ with the king below it (row $x$ $+$ $i$ where $i$ > $0$). If $i$ $=$ $1$, we cannot move down to the next row as the king may move up and we will not be able to trap it. Otherwise, we can move down by one unit. To ensure that the king is not on the next row, scan the current row, $x$, by moving the queen from the leftmost column to the rightmost column one square at a time. Therefore, you can move the queen as follows: During the scan, if you have visited all $8$ squares of the current row and the king never made a vertical or diagonal move, it means that $i \\ge 2$ and you can go down by one row. It is now guaranteed that the king is still below the queen. During the scan, if you have visited all $8$ squares of the current row and the king never made a vertical or diagonal move, it means that $i \\ge 2$ and you can go down by one row. It is now guaranteed that the king is still below the queen. If the king were on row $x$ $+$ $1$, he would have been forced to move $1$ square down at some point. If he ever goes down, move the queen down by one row. If the king were on row $x$ $+$ $1$, he would have been forced to move $1$ square down at some point. If he ever goes down, move the queen down by one row. If the king moves up, start scanning the row again. This can only happen a limited number of times without the king moving into a check. If the king moves up, start scanning the row again. This can only happen a limited number of times without the king moving into a check. In total, the queen needs to apply step $2$ up to $8$ times. At each row, step $1$ needs to be applied, so it takes $8$ moves. Step $1$ also needs to be applied every time step $3$ is applied, which can happen at most $8$ times. In total, that is $8$ $\\cdot$ $(8$ $+$ $8)$ $=$ $128$ moves.",
    "code": "#define  _CRT_SECURE_NO_WARNINGS\n#include <bits/stdc++.h>\n#include <unordered_map>\n#include <unordered_set>\nusing namespace std;\n//#define endl \"\\n\"\n#define ll long long\n#define sz(s) (int)(s.size())\n#define INF 0x3f3f3f3f3f3f3f3fLL\n#define all(v) v.begin(),v.end()\n#define watch(x) cout<<(#x)<<\" = \"<<x<<endl\nconst int dr[]{ -1, -1, 0, 1, 1, 1, 0, -1 };\nconst int dc[]{ 0, 1, 1, 1, 0, -1, -1, -1 };\n#if __cplusplus >= 201402L\ntemplate<typename T>\nvector<T> create(size_t n) {\n\treturn vector<T>(n);\n}\ntemplate<typename T, typename ... Args>\nauto create(size_t n, Args ... args) {\n\treturn vector<decltype(create<T>(args...))>(n, create<T>(args...));\n}\n#endif\nvoid run() {\n\tios::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n#ifndef ONLINE_JUDGE\n\t//freopen(\"input.txt\", \"r\", stdin);\n#else\n#endif\n}\n \nconst int N = 8, LIMIT_QUERIES = 130 + 1;\nint curY = 0, cnt = 0;\nstring Move(int x, int y) {\n\tassert(++cnt <= LIMIT_QUERIES);\n\tcout << x << ' ' << y << endl;\n\tcurY = y;\n\tstring s;\n\tcin >> s;\n\treturn s;\n}\n \nbool scanRow(int row) {\n\tstring s;\n\tif (curY == 8) {\n\t\tfor (int y = 7; y > 0; y--) {\n\t\t\ts = Move(row, y);\n\t\t\tif (s == \"Done\")\n\t\t\t\treturn true;\n\t\t\tif (s.find(\"Up\") != string::npos)\n\t\t\t\treturn scanRow(row);\n\t\t\tif (s.find(\"Down\") != string::npos)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn false;\n\t}\n\tfor (int y = (curY == 1 ? 2 : 1); y <= N; y++) {\n\t\ts = Move(row, y);\n\t\tif (s == \"Done\")\n\t\t\treturn true;\n\t\tif (s.find(\"Up\") != string::npos)\n\t\t\treturn scanRow(row);\n\t\tif (s.find(\"Down\") != string::npos)\n\t\t\treturn false;\n\t}\n\treturn false;\n}\n \nbool solve() {\n\tcurY = 1, cnt = 0;\n\tstring s;\n\tfor (int row = 1; row <= N; row++) {\n\t\ts = Move(row, curY);\n\t\tif (s == \"Done\")\n\t\t\treturn true;\n\t\tif (scanRow(row))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n \nint main() {\n\trun();\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tbool b = solve();\n\t\tassert(b);\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1558",
    "index": "A",
    "title": "Charmed by the Game",
    "statement": "Alice and Borys are playing tennis.\n\nA tennis match consists of games. In each game, one of the players is serving and the other one is receiving.\n\nPlayers serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa.\n\nEach game ends with a victory of one of the players. If a game is won by the serving player, it's said that this player holds serve. If a game is won by the receiving player, it's said that this player breaks serve.\n\nIt is known that Alice won $a$ games and Borys won $b$ games during the match. It is unknown who served first and who won which games.\n\nFind all values of $k$ such that exactly $k$ breaks could happen during the match between Alice and Borys in total.",
    "tutorial": "First of all, we don't know who served first, but there are only two options, so let's just try both and unite the sets of $k$'s we get. Assume that Alice served first. Exactly $a+b$ games were played. If $a+b$ is even, both players served exactly $\\frac{a+b}{2}$ times, and if $a+b$ is odd, Alice served one more time than Borys. The simplest way to consider both cases is to say that Alice served $p = \\lceil \\frac{a+b}{2} \\rceil$ times, and Borys served $q = \\lfloor \\frac{a+b}{2} \\rfloor$ times ($\\lceil t \\rceil$ denotes rounding up, and $\\lfloor t \\rfloor$ denotes rounding down). Let $x$ be the number of times Borys broke Alice's serve ($0 \\le x \\le p$), and let $y$ be the number of times Alice broke Borys' serve ($0 \\le y \\le q$). In this case, the number of games Alice won is $a = (p - x) + y$, and the number of games Borys won is $b = x + (q - y)$. We know neither $x$ nor $y$, but let's loop over $x = 0 \\ldots p$. From $a = (p - x) + y$, we can calculate $y = a - (p - x)$. If $0 \\le y \\le q$, the values of $x$ and $y$ represent a valid scenario of the match with exactly $x + y$ breaks in total. The case when Borys served first is handled similarly. Analyzing the formulas further, we can find a \"closed-form\" solution: Let $d = \\lfloor \\frac{\\lvert a-b \\rvert}{2} \\rfloor$. If $a + b$ is even, all possible values of $k$ are $d, d + 2, d + 4, \\ldots, a + b - d$. If $a + b$ is odd, all possible values of $k$ are $d, d + 1, d + 2, \\ldots, a + b - d$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1558",
    "index": "B",
    "title": "Up the Strip",
    "statement": "\\textbf{Note that the memory limit in this problem is lower than in others.}\n\nYou have a vertical strip with $n$ cells, numbered consecutively from $1$ to $n$ from top to bottom.\n\nYou also have a token that is initially placed in cell $n$. You will move the token up until it arrives at cell $1$.\n\nLet the token be in cell $x > 1$ at some moment. One shift of the token can have either of the following kinds:\n\n- Subtraction: you choose an integer $y$ between $1$ and $x-1$, inclusive, and move the token from cell $x$ to cell $x - y$.\n- Floored division: you choose an integer $z$ between $2$ and $x$, inclusive, and move the token from cell $x$ to cell $\\lfloor \\frac{x}{z} \\rfloor$ ($x$ divided by $z$ rounded down).\n\nFind the number of ways to move the token from cell $n$ to cell $1$ using one or more shifts, and print it modulo $m$. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered \\textbf{distinct} (check example explanation for a better understanding).",
    "tutorial": "This problem was inspired by Blogewoosh #4 a long time ago (Blogewoosh #8 when?). Pretty clearly, we are facing a dynamic programming problem. Let $f(x)$ be the number of ways to move from cell $x$ to cell $1$. Then, $f(1) = 1$, $f(x) = \\sum \\limits_{y=1}^{x-1} f(x-y) + \\sum \\limits_{z=2}^{x} f(\\lfloor \\frac{x}{z} \\rfloor)$, and $f(n)$ is the answer to the problem. However, a straightforward implementation has $O(n^2)$ time complexity and is too slow. Let's look at the main formula for $f(x)$ again: $f(x) = \\sum \\limits_{y=1}^{x-1} f(x-y) + \\sum \\limits_{z=2}^{x} f(\\lfloor \\frac{x}{z} \\rfloor)$. The first sum, $\\sum \\limits_{y=1}^{x-1} f(x-y)$, is easy to optimize: just maintain the sum of $f_1 \\ldots f_{x-1}$ and recalculate it by adding $f(x)$. This takes just $O(1)$ time per cell. For the second sum, $\\sum \\limits_{z=2}^{x} f(\\lfloor \\frac{x}{z} \\rfloor)$, note that $\\lfloor \\frac{x}{z} \\rfloor$ can take at most $O(\\sqrt{x})$ different values over $z \\in [2; x]$. We can handle this sum as follows: Find the sum over all $z < \\sqrt{x}$ directly. We only need to consider $z \\ge \\sqrt{x}$ now. For any such value, $\\lfloor \\frac{x}{z} \\rfloor \\le \\sqrt{x}$. Let's loop over a cell $c \\le \\sqrt{x}$, for how many different values of $z$ it's true that $c = \\lfloor \\frac{x}{z} \\rfloor$? By definition of the floor function, $c \\le \\frac{x}{z} < c+1$. Solving this inequality, we get $z \\in [\\lfloor \\frac{x}{c+1} \\rfloor + 1; \\lfloor \\frac{x}{c} \\rfloor]$. The length of this segment gives us the coefficient of $f(c)$ in the sum. This gives us an $O(n \\sqrt{n})$ solution which is enough for the subtask in Division 2. To get a faster solution, let $S(x)$ denote the multiset of cells where we can go to from cell $x$ (this multiset contains $2x-2$ values). How is $S(x+1)$ different from $S(x)$? $S(x+1)$ contains an extra occurrence of $x$ because we can subtract $1$ from $x+1$. $S(x+1)$ contains an extra occurrence of $1$ because we can divide $x+1$ by $x+1$. For each $i > 1$ that is a divisor of $x+1$, $S(x+1)$ contains an occurrence of $i$ that replaces an occurrence of $i-1$. We don't need to maintain $S(x)$ itself, but we can maintain the sum of $f(i)$ over all $i \\in S(x)$ and recalculate this sum as we go from $x$ to $x+1$. The total number of changes to $S$ is limited by the total number of divisors of all numbers from $1$ to $n$, that is, $\\frac{n}{1} + \\frac{n}{2} + \\ldots + \\frac{n}{n} = O(n \\log n)$. However, if implemented directly, we need to quickly find the divisors of each $x$, and we can only afford $O(n)$ memory due to the memory limit. We can achieve that by preparing a sieve of Eratosthenes, factorizing $x$ and generating all its divisors. A better way is do it the reverse way: once we find $f(c)$ for some $c$, let's traverse $x = 2c, 3c, \\ldots$ and add $f(c) - f(c-1)$ to $f(x)$. This way the time complexity stays $O(n \\log n)$ and the memory complexity is $O(n)$.",
    "tags": [
      "brute force",
      "dp",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1558",
    "index": "C",
    "title": "Bottom-Tier Reversals",
    "statement": "You have a permutation: an array $a = [a_1, a_2, \\ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd.\n\nYou need to sort the permutation in increasing order.\n\nIn one step, you can choose any prefix of the permutation with an odd length and reverse it. Formally, if $a = [a_1, a_2, \\ldots, a_n]$, you can choose any odd integer $p$ between $1$ and $n$, inclusive, and set $a$ to $[a_p, a_{p-1}, \\ldots, a_1, a_{p+1}, a_{p+2}, \\ldots, a_n]$.\n\nFind a way to sort $a$ using no more than $\\frac{5n}{2}$ reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.",
    "tutorial": "First of all, consider what happens when we reverse a prefix of odd length $p$. Elements $a_{p+1}$ to $a_n$ don't move at all, and for each $i$ from $1$ to $p$, $a_i$ moves to $a_{p-i+1}$. Note that $i$ and $p-i+1$ have the same parity: therefore, no element can ever change the parity of its position. In the final sorted permutation, we need to have $a_i = i$ for all $i$: that is, the parity of each element's position must match the parity of its value. This leads to the following necessary condition: for each $i \\in [1, n]$, $a_i \\bmod 2 = i \\bmod 2$. If for any $i$ this doesn't hold, the permutation can not be sorted. It turns out this condition is also sufficient. Let's devise a procedure to sort a permutation of odd length $n$. If $a_n = n$ and $a_{n - 1} = n - 1$, we don't have to touch $a_{n-1}$ and $a_n$ ever again, and we can proceed to sorting a permutation of length $n-2$. Can we actually move $n$ and $n-1$ to their final positions with a simple sequence of steps? Indeed we can. Here is one way to do this in exactly $5$ steps: Let $a_x = n$ (note that $x$ is odd). Reverse a prefix of length $x$ to move $n$ to position $1$. Let $a_y = n-1$ (note that $y$ is even). Reverse a prefix of length $y-1$ to move $n$ to position $y-1$. Reverse a prefix of length $y+1$ to move $n-1$ to position $2$ and $n$ to position $3$. Reverse a prefix of length $3$ to move $n$ to position $1$ ($n-1$ stays at position $2$). Reverse a prefix of length $n$ to move $n$ to position $n$ and $n-1$ to position $n-1$, as desired. We can use this procedure $\\frac{n-1}{2}$ times to first move $n$ and $n-1$ to their final positions, then $n-2$ and $n-3$, and so on. This solution requires exactly $\\frac{5(n-1)}{2}$ steps.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1558",
    "index": "D",
    "title": "Top-Notch Insertions",
    "statement": "Consider the insertion sort algorithm used to sort an integer sequence $[a_1, a_2, \\ldots, a_n]$ of length $n$ in non-decreasing order.\n\nFor each $i$ in order from $2$ to $n$, do the following. If $a_i \\ge a_{i-1}$, do nothing and move on to the next value of $i$. Otherwise, find the smallest $j$ such that $a_i < a_j$, shift the elements on positions from $j$ to $i-1$ by one position to the right, and write down the initial value of $a_i$ to position $j$. In this case we'll say that we performed an insertion of an element from position $i$ to position $j$.\n\nIt can be noticed that after processing any $i$, the prefix of the sequence $[a_1, a_2, \\ldots, a_i]$ is sorted in non-decreasing order, therefore, the algorithm indeed sorts any sequence.\n\nFor example, sorting $[4, 5, 3, 1, 3]$ proceeds as follows:\n\n- $i = 2$: $a_2 \\ge a_1$, do nothing;\n- $i = 3$: $j = 1$, insert from position $3$ to position $1$: $[3, 4, 5, 1, 3]$;\n- $i = 4$: $j = 1$, insert from position $4$ to position $1$: $[1, 3, 4, 5, 3]$;\n- $i = 5$: $j = 3$, insert from position $5$ to position $3$: $[1, 3, 3, 4, 5]$.\n\nYou are given an integer $n$ and a list of $m$ integer pairs $(x_i, y_i)$. We are interested in sequences such that if you sort them using the above algorithm, exactly $m$ insertions will be performed: first from position $x_1$ to position $y_1$, then from position $x_2$ to position $y_2$, ..., finally, from position $x_m$ to position $y_m$.\n\nHow many sequences of length $n$ consisting of (not necessarily distinct) integers between $1$ and $n$, inclusive, satisfy the above condition? Print this number modulo $998\\,244\\,353$.",
    "tutorial": "First of all, note that the sequence of insertions uniquely determines where each element goes. For example, for $n = 5$ and a sequence of insertions $(3, 1), (4, 1), (5, 3)$, the initial sequence $[a_1, a_2, a_3, a_4, a_5]$ is always transformed into $[a_4, a_3, a_5, a_1, a_2]$, no matter what $a_i$ are. Thus, instead of counting the initial sequences, we might count the final sequences instead. Let the final sequence be $[b_1, b_2, \\ldots, b_n]$. From its sortedness, we know that $b_i \\le b_{i+1}$ for every $i \\in [1; n-1]$. Consider a single iteration $i$ of the sorting algorithm. If $a_i \\ge a_{i-1}$, no insertion occurs. This actually doesn't give us any extra information: we know that $a_i$ is placed later than $a_{i-1}$ in the final sequence anyway. What happens though if $a_i$ is inserted into position $j$? We know that $a_i < a_j$ and also, since $j$ is the smallest index with such property, $a_i \\ge a_{j-1}$. Again, a non-strict inequality doesn't give us anything. However, knowing that $a_i < a_j$ is actually important. It turns out that we are interested in elements $a_i$ such that we have ever inserted an element right before $a_i$ during sorting. For every such element, we know that the previous element in the sorted order is strictly smaller. All other pairs of neighboring elements can either be equal, or the earlier one can be smaller. All in all, let $c$ be the number of indices $i \\in [1; n-1]$ such that $b_i < b_{i+1}$ (for all the other values of $i$, $b_i \\le b_{i+1}$). How many different sequences $b$ with integers from $1$ to $n$ satisfy this? This number can be shown to be equal to $\\binom{2n-1-c}{n}$. (The proof can go as follows: for each $i$ such that $b_i \\le b_{i+1}$, increase each of $b_{i+1}, b_{i+2}, \\ldots, b_n$ by $1$. Now for every $i$ we have $b_i < b_{i+1}$, and the maximum possible value of an element increased to $n + (n-1-c)$. Thus, we have built a bijection from the sequences we are searching for to the sequences of $n$ distinct numbers between $1$ and $n + (n-1-c)$. The number of the latter sequences is clearly $\\binom{2n-1-c}{n}$.) How to find $c$? It can be done by going through the insertions and maintaining a balanced binary search tree of your choice. However, implementation becomes simpler if we process the insertions in reverse order. Let's maintain a set $S$ of positions in the final sorted order that are not yet filled in. Initially, the set contains all integers from $1$ to $n$. For each insertion $(x_i, y_i)$ (in reverse order), let $p$ be the $y_i$-th smallest element of $S$, and let $q$ be the $(y_i+1)$-th smallest element of $S$. Since we insert $p$ before $q$, mark position $q$ as \"a position such that we have ever inserted an element right before it\" (which is important for calculating $c$). Then, erase $p$ from the set. As a data structure that can handle finding the $k$-th smallest element, we can use a balanced binary search tree, a segment tree, or binary search over Fenwick tree (in C++ we can also use a built-in policy-based data structure). Finally, to solve each test case in $O(m \\log n)$ and not $O(n \\log n)$, we can have a single data structure instance for solving all test cases, and roll back any changes we apply while solving each test case.",
    "tags": [
      "combinatorics",
      "data structures"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1558",
    "index": "E",
    "title": "Down Below",
    "statement": "In a certain video game, the player controls a hero characterized by a single integer value: power.\n\nOn the current level, the hero got into a system of $n$ caves numbered from $1$ to $n$, and $m$ tunnels between them. Each tunnel connects two distinct caves. Any two caves are connected with at most one tunnel. Any cave can be reached from any other cave by moving via tunnels.\n\nThe hero starts the level in cave $1$, and every other cave contains a monster.\n\nThe hero can move between caves via tunnels. If the hero leaves a cave and enters a tunnel, he must finish his movement and arrive at the opposite end of the tunnel.\n\nThe hero can use each tunnel to move in both directions. However, the hero \\textbf{can not} use the same tunnel \\textbf{twice in a row}. Formally, if the hero has just moved from cave $i$ to cave $j$ via a tunnel, he can not head back to cave $i$ immediately after, but he can head to any other cave connected to cave $j$ with a tunnel.\n\nIt is known that at least two tunnels come out of every cave, thus, the hero will never find himself in a dead end even considering the above requirement.\n\nTo pass the level, the hero must beat the monsters in all the caves. When the hero enters a cave for the first time, he will have to fight the monster in it. The hero can beat the monster in cave $i$ if and only if the hero's power is strictly greater than $a_i$. In case of beating the monster, the hero's power increases by $b_i$. If the hero can't beat the monster he's fighting, the game ends and the player loses.\n\nAfter the hero beats the monster in cave $i$, all subsequent visits to cave $i$ won't have any consequences: the cave won't have any monsters, and the hero's power won't change either.\n\nFind the smallest possible power the hero must start the level with to be able to beat all the monsters and pass the level.",
    "tutorial": "Let's find the smallest possible initial power with binary search. Suppose the initial power is $p$. The main idea behind the solution is to maintain a set of caves where we have beaten all the monsters, and try to extend the set by finding \"augmenting\" paths. However, we can not just go in an arbitrary unvisited cave and pretend we add it to the set: since we are not allowed to turn back, it might happen that we can not move forward anymore because we don't have enough power. It's important that we must be able to reach any cave inside the set only going through caves belonging to the set itself. Initially, the set contains just cave $1$. What can an augmenting path look like? The path can start somewhere inside the set, go out of the set, follow a simple route visiting some new caves (and beating monsters inside them), and go back to a cave belonging to the set. For example, if caves $1$ and $2$ belong to the set, the route can look like $1 \\rightarrow 3 \\rightarrow 4 \\rightarrow 5 \\rightarrow 2$, and we can add caves $3$, $4$, and $5$ to the set. Alternatively, instead of going back to a cave from the set, the path might go into a cave belonging to the route. For example, if caves $1$ and $2$ belong to the set, the route can look like $1 \\rightarrow 3 \\rightarrow 4 \\rightarrow 5 \\rightarrow 6 \\rightarrow 4$, and we can add caves $3$, $4$, $5$, and $6$ to the set. How do we find any augmenting path satisfying us? It turns out that we can use the following property. Suppose we have a path $v \\rightarrow u_1 \\rightarrow u_2 \\rightarrow \\ldots \\rightarrow u_k \\rightarrow x$ (where $v$ is the only cave belonging to the set) that we can follow and beat all the monsters in the caves we visit. Suppose that we have another such path $v' \\rightarrow u'_1 \\rightarrow u'_2 \\rightarrow \\ldots \\rightarrow u'_{k'} \\rightarrow x$. Suppose that following the former path, we arrive at $x$ with the same or higher power than following the latter path. In this case, notice that $v \\rightarrow u_1 \\rightarrow u_2 \\rightarrow \\ldots \\rightarrow u_k \\rightarrow x \\rightarrow u'_{k'} \\rightarrow \\ldots \\rightarrow u'_1 \\rightarrow v'$ Thus, we can simply use BFS or DFS to find all reachable caves. Once we find a path leading back into the set, or we find two different paths leading into the same unvisited cave, we can build an augmenting path, extend the set, and start over, until the set contains all caves (in which case we can try to decrease the initial power level $p$) or until we can not find any augmenting path (in which case we must increase $p$). At each binary search iteration, we can have at most $n$ augmenting paths and we find each of them in $O(m)$. Thus, the time complexity of the solution is $O(nm \\log{a_{max}})$.",
    "tags": [
      "binary search",
      "dfs and similar",
      "graphs",
      "greedy",
      "meet-in-the-middle",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1558",
    "index": "F",
    "title": "Strange Sort",
    "statement": "You have a permutation: an array $a = [a_1, a_2, \\ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd.\n\nConsider the following algorithm of sorting the permutation in increasing order.\n\nA helper procedure of the algorithm, $f(i)$, takes a single argument $i$ ($1 \\le i \\le n-1$) and does the following. If $a_i > a_{i+1}$, the values of $a_i$ and $a_{i+1}$ are exchanged. Otherwise, the permutation doesn't change.\n\nThe algorithm consists of iterations, numbered with consecutive integers starting with $1$. On the $i$-th iteration, the algorithm does the following:\n\n- if $i$ is odd, call $f(1), f(3), \\ldots, f(n - 2)$;\n- if $i$ is even, call $f(2), f(4), \\ldots, f(n - 1)$.\n\nIt can be proven that after a finite number of iterations the permutation will be sorted in increasing order.\n\nAfter how many iterations will this happen for the first time?",
    "tutorial": "Let's draw a wall of $n$ towers of cubes, with the $i$-th tower having height $a_i$. For example, for $a = [4, 5, 7, 1, 3, 2, 6]$ the picture will look as follows ($1$ stands for a cube): Note that applying $f(i)$ to the permutation (swapping $a_i$ and $a_{i+1}$ if $a_i > a_{i+1}$) is equivalent to applying $f(i)$ to each row of the above matrix independently (swapping cells $i$ and $i+1$ if the $i$-th cell is $1$ and the $i+1$-th cell is $0$). Also note that in the final state, when the permutation is $[1, 2, \\ldots, n]$, each row of the matrix is sorted in non-descending order too ($0$'s go before $1$'s), and vice versa - if each row is sorted, the permutation is sorted as well. Thus, it's enough to find the number of iterations required to sort each row of the matrix, and the maximum of these numbers is the answer for the given permutation. The rows of the matrix are $b_i = [a_i \\ge x]$ for $x = 1, 2, \\ldots, n$. How to solve the problem for a sequence of $0$'s and $1$'s? We can assume that the instances of $0$'s don't change their relative order, and the same for $1$'s. Let the positions of zeros in the initial sequence be $1 \\le p_1 < p_2 < \\ldots < p_m \\le n$. The $i$-th zero from the left is moving towards position $i$ in the sorted sequence. Let $s(i)$ be the number of steps it takes the $i$-th zero from the left to get to its final position $i$. If the $i$-th zero is already in position $i$, then $s(i) = 0$. Otherwise, if $i > 1$, note that $s(i) \\ge s(i - 1) + 1$, because the $i$-th zero can only get to position $i$ after the $(i-1)$-th zero gets to position $i-1$. Moreover, let there be $k_i$ ones to the left of the $i$-th zero in the initial sequence. Then $s(i) \\ge k_i + (p_i \\bmod 2)$, because the $0$ has to swap with every $1$ to the left of it, and also the first iteration is useless if $p_i$ is odd. It turns out that $s(i) = \\max(s(i - 1) + 1, k_i + (p_i \\bmod 2))$ - the $i$-th zero either gets stuck into the $(i-1)$-th zero (and then $s_i = s(i - 1) + 1$), or consistently swaps with $1$'s on each iteration except for maybe the first (in which case $s_i = k_i + (p_i \\bmod 2)$). We are interested in $s(m)$. Let the number of $0$'s at the start of the initial sequence be $t$. It can be seen that $s(m) = \\max \\limits_{i=t+1}^m (k_i + (p_i \\bmod 2) + (m - i))$, and this is exactly the number of iterations required. Recall that we need to find the number of iterations for $n$ different binary sequences. However, these binary sequences are very similar to each other. Let's maintain the values of $(k_i + (p_i \\bmod 2) + (m - i))$ for all zeros in a segment tree (and, say, $-\\infty$ for positions containing ones). Start with the sequence $b_i = [a_i \\ge x]$ for $x = 1$ - that is, a sequence of all ones. As we increase $x$ by one, a single $1$ in $b$ gets replaced with $0$. We can handle these changes using a segment tree with \"range add\" and \"range max\". The time complexity of the solution is $O(n \\log n)$. (Another equivalent formula is: $s(m) = \\max \\limits_{i=l}^r c_1([b_1, b_2, \\ldots, b_i]) + c_0([b_{i+1}, \\ldots, b_n]) + (i \\bmod 2) - 1$. Here $c_x(seq)$ is the number of $x$'s in $seq$; $l$ is the smallest position such that $c_1([b_1, b_2, \\ldots, b_l]) > 0$; and $r$ is the largest position such that $c_0([b_{r+1}, \\ldots, b_n]) > 0$. This formula can also be proven using induction. In short, consider this formula applied to the number of remaining iterations - the difference is that instead of $(i \\bmod 2)$, we sometimes have $1 - (i \\bmod 2)$, depending on the parity of the current iteration number. Consider all positions $i$ where the value is maximized. Then it can be shown that after one iteration the value for all such positions decreases by $1$: if the parity is incorrect, after one iteration the parity becomes correct; otherwise, observe that $b_i = 1$ and $b_{i+1} = 0$, which get swapped in the next iteration. Moreover, the value for all other positions has the same parity, increases by at most $1$, and thus doesn't become too big either.)",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1559",
    "index": "A",
    "title": "Mocha and Math",
    "statement": "Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.\n\nThis day, Mocha got a sequence $a$ of length $n$. In each operation, she can select an arbitrary interval $[l, r]$ and for all values $i$ ($0\\leq i \\leq r-l$), replace $a_{l+i}$ with $a_{l+i} \\,\\&\\, a_{r-i}$ at the same time, where $\\&$ denotes the bitwise AND operation. This operation can be performed \\textbf{any number of times}.\n\nFor example, if $n=5$, the array is $[a_1,a_2,a_3,a_4,a_5]$, and Mocha selects the interval $[2,5]$, then the new array is $[a_1,a_2\\,\\&\\, a_5, a_3\\,\\&\\, a_4, a_4\\,\\&\\, a_3, a_5\\,\\&\\, a_2]$.\n\nNow Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?",
    "tutorial": "We assume the answer is $x$. In its binary representation, one bit will be $1$ only if in all the $a_i$'s binary representation,this bit is $1$. Otherwise, we can use one operation to make this bit in $x$ become 0, which is a smaller answer. So we can set $x=a_1$ initially. Then we iterate over the sequence and make $x=x\\& a_{i}$, the $x$ is the anwser finally.",
    "code": "#include<bits/stdc++.h>\n#define inf 0x3f3f3f3f\n#define maxm 100005\n#define maxn 2005\n#define PII pair<int, int>\n#define fi first\n#define se second\ntypedef long long ll;\ntypedef unsigned long long ull;\nusing namespace std;\nconst double pi = acos(-1);\nconst int mod = 998244353;\nconst double eps = 1e-10;\nconst int N =1e2+10;\nint n;\nint a[N];\nint main() {\n    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n    //int a,b,c;\n    int t;\n    cin>>t;\n    while(t--){\n    cin>>n;\n    for(int i=1;i<=n;i++)cin>>a[i];\n    int res=a[1];\n    for(int i=2;i<=n;i++)res&=a[i];\n    cout<<res<<endl;\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1559",
    "index": "B",
    "title": "Mocha and Red and Blue",
    "statement": "As their story unravels, a timeless tale is told once again...\n\nShirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to solve, so she wants you to solve them and tell her the answers. The puzzles are described as follow.\n\nThere are $n$ squares arranged in a row, and each of them can be painted either red or blue.\n\nAmong these squares, some of them have been painted already, and the others are blank. You can decide which color to paint on each blank square.\n\nSome pairs of adjacent squares may have the same color, which is imperfect. We define the imperfectness as the number of pairs of adjacent squares that share the same color.\n\nFor example, the imperfectness of \"BRRRBBR\" is $3$, with \"BB\" occurred once and \"RR\" occurred twice.\n\nYour goal is to minimize the imperfectness and print out the colors of the squares after painting.",
    "tutorial": "For a longest period of \"?\", it is optimized to paint either \"RBRB...\" or \"BRBR...\", so the imperfectness it made is only related to the colors of both sides of it. Choose the one with the lower imperfectness for each longest period of \"?\" in $O(n)$ is acceptable. More elegantly, if the square on the left or on the right of a \"?\" is painted, simply paint \"?\" with the different color from it. This can be proved to reach the minimum imperfectness by considering the parity.",
    "code": "#include <cstdio>\nusing namespace std;\nconst int N=105;\nint t,n,cnt;\nchar s[N];\nint main()\n{\n\tscanf(\"%d\",&t);\n\twhile (t--)\n\t{\n\t\tcnt=0;\n\t\tscanf(\"%d\",&n);\n\t\tscanf(\"%s\",s+1);\n\t\tfor (int i=1;i<=n;i++)\n\t\t\tcnt+=(s[i]!='?');\n\t\tif (!cnt)\n\t\t\ts[1]='R';\n\t\tfor (int i=2;i<=n;i++)\n\t\t\tif (s[i]=='?'&&s[i-1]!='?')\n\t\t\t\ts[i]=s[i-1]^('B'^'R');\n\t\tfor (int i=n-1;i;i--)\n\t\t\tif (s[i]=='?'&&s[i+1]!='?')\n\t\t\t\ts[i]=s[i+1]^('B'^'R');\n\t\tprintf(\"%s\\n\",s+1);\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1559",
    "index": "C",
    "title": "Mocha and Hiking",
    "statement": "The city where Mocha lives in is called Zhijiang. There are $n+1$ villages and $2n-1$ directed roads in this city.\n\nThere are two kinds of roads:\n\n- $n-1$ roads are from village $i$ to village $i+1$, for all $1\\leq i \\leq n-1$.\n- $n$ roads can be described by a sequence $a_1,\\ldots,a_n$. If $a_i=0$, the $i$-th of these roads goes from village $i$ to village $n+1$, otherwise it goes from village $n+1$ to village $i$, for all $1\\leq i\\leq n$.\n\nMocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village \\textbf{exactly once}. They can start and finish at any villages. Can you help them to draw up a plan?",
    "tutorial": "If $a_1=1$, then the path $\\Big[(n+1) \\to 1 \\to 2 \\to \\cdots \\to n\\Big]$ is valid. If $a_n=0$, then the path $\\Big[1 \\to 2 \\to \\cdots \\to n \\to (n+1) \\Big]$ is valid. Otherwise, since $a_1=0 \\land a_n=1$, there must exists an integer $i$ ($1 \\le i < n$) where $a_i=0 \\land a_{i+1}=1$, then the path $\\Big[1 \\to 2 \\to \\cdots \\to i \\to (n+1) \\to (i+1) \\to (i+2) \\to \\cdots n\\Big]$ is valid. This is a step to prove that there always exists an Hamiltonian path in a tournament graph.",
    "code": "#include <bits/stdc++.h>\n#define maxn 100086\n\nusing namespace std;\n\nint t, n;\nint a[maxn];\n\nvoid solve(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 1;i <= n;i++) scanf(\"%d\", &a[i]);\n\tif(a[1]){\n\t\tprintf(\"%d \", n + 1);\n\t\tfor(int i = 1;i <= n;i++) printf(\"%d \", i);\n\t\treturn;\n\t}\n\tfor(int i = 1;i < n;i++){\n\t\tif(!a[i] && a[i + 1]){\n\t\t\tfor(int j = 1;j <= i;j++) printf(\"%d \", j);\n\t\t\tprintf(\"%d \", n + 1);\n\t\t\tfor(int j = i + 1;j <= n;j++) printf(\"%d \", j);\n\t\t\treturn;\n\t\t}\n\t}\n\tfor(int i = 1;i <= n;i++) printf(\"%d \", i);\n\tprintf(\"%d \", n + 1);\n}\n\nint main(){\n    scanf(\"%d\", &t);\n    while(t--) solve(), puts(\"\");\n}\n",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1559",
    "index": "D1",
    "title": "Mocha and Diana (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.}\n\nA forest is an undirected graph without cycles (not necessarily connected).\n\nMocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $1$ to $n$, and they would like to add edges to their forests such that:\n\n- After adding edges, both of their graphs are still forests.\n- They add the same edges. That is, if an edge $(u, v)$ is added to Mocha's forest, then an edge $(u, v)$ is added to Diana's forest, and vice versa.\n\nMocha and Diana want to know the maximum number of edges they can add, and which edges to add.",
    "tutorial": "In the final situation, if one forest has more than one tree, we choose two trees from it, such as tree $A$ and tree $B$. Then we consider node $a$ in $A$ and node $b$ in $B$, they must be connected in another forest. We can easily find node $b$ is connected with all the nodes in $A$ and node $a$ is connected with all the nodes in $B$. So nodes in $A$ and $B$ are in the same tree in another forest. If we consider other trees, we can get the same conclusion. Hence nodes in another forest form only one tree. So we can enumerate every pair $(i, j)$ and check if this edge can be added. When the edge can be added, we can just add it. This can be done in the complexity of $O(n^2)$.",
    "code": "#include<bits/stdc++.h>\n#define maxn 2005\n#define fi first\n#define se second\n#define PII pair<int, int>\n\nusing namespace std;\n\ntypedef long long ll;\nconst ll mod = 10007; \n\ninline ll read(){\n    ll x = 0, f = 1;char ch = getchar();\n    while(ch > '9' || ch < '0'){if(ch == '-') f = -1;ch = getchar();}\n    while(ch >= '0' && ch <= '9'){x = x * 10 + ch -'0';ch = getchar();}\n    return x * f;\n}\n\nint n, m1, m2, f[2][maxn];\n\nint getf(int id, int x){return x == f[id][x] ? x : f[id][x] = getf(id, f[id][x]);}\n\nvector<PII> ans;\n\nint main() {\n\tn = read(), m1 = read(), m2 = read();\n\t\n\tfor(int i = 1; i <= n; i++)\n\t\tf[0][i] = f[1][i] = i;\n\t\n\tfor(int i = 1; i <= m1; i++){\n\t\tint u = read(), v = read();\n\t\tint fu = getf(0, u), fv = getf(0, v);\n\t\tf[0][fu] = fv;\n\t}\n\t\n\tfor(int i = 1; i <= m2; i++){\n\t\tint u = read(), v = read();\n\t\tint fu = getf(1, u), fv = getf(1, v);\n\t\tf[1][fu] = fv;\n\t}\n\t\n\tfor(int i = 1; i <= n; i++){\n\t\tfor(int j = i + 1; j <= n; j++){\n\t\t\tif(getf(0, i) != getf(0, j) && getf(1, i) != getf(1, j)){\n\t\t\t\tans.push_back({i, j});\n\t\t\t\tf[0][getf(0, i)] = getf(0, j);\n\t\t\t\tf[1][getf(1, i)] = getf(1, j); \n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintf(\"%d\\n\", ans.size());\n\tfor(auto i: ans) printf(\"%d %d\\n\", i.fi, i.se);\n\treturn 0;\n}\n\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dsu",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1559",
    "index": "D2",
    "title": "Mocha and Diana (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.}\n\nA forest is an undirected graph without cycles (not necessarily connected).\n\nMocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $1$ to $n$, and they would like to add edges to their forests such that:\n\n- After adding edges, both of their graphs are still forests.\n- They add the same edges. That is, if an edge $(u, v)$ is added to Mocha's forest, then an edge $(u, v)$ is added to Diana's forest, and vice versa.\n\nMocha and Diana want to know the maximum number of edges they can add, and which edges to add.",
    "tutorial": "To have a clearer understanding, let's visualize the problem with a grid where each row is a component in the left forest and each column is a component in the right forest. For example, the cell (i,j) contains vertexes which belongs to $i^{th}$ component in the left forest and $j^{th}$ component in the right tree. (Some cells may be empty.) An operation corresponds to finding two filled cells in different rows and different columns, merging the two rows, and merging the two columns. Now we need to make operation rapidly. For each row, we maintain a set of the different columns with filled cells in this row. Symmetrically, for each column we maintain a set of the different rows with filled cells in this column. To merge two rows, we insert the elements of the smaller set into the larger set. The smaller set is now useless, and we delete it from every column in the set and insert the larger one. Since the data structure is symmetric, merging two columns is similar. Without loss of generality, assume there are fewer rows than columns. If there is a row whose set has more than 1 element, we can pick it and any other row, and find an operation we can make. Otherwise if all rows are singletons, then we know the sets are all disjoint because there are more columns than rows. So we can pick any two sets and make an operation, and then there's a set with more than 1 element. Maintaining which rows have sets with size more than 1 is not hard. For each operation, we need to output the corresponding vertex in the original two forest. Firstly, choose a vertex as the representative of each cell, because all vertexes in a cell can be seen as equivalent. Then, when merging two rows or columns, we just insert the representative vertexes at the same time. There can be at most $2n$ merge operations and the total complexity of them will be $O(n\\log^2 n)$. This is because an element moves to a new row/column $O(\\log n)$ times and each move is $O(\\log n)$ time (using STL set in cpp). Overall, it's $O(n\\log^2n)$time and $O(n\\log n)$ space.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define N 100010\nint fa1[N],fa2[N];\nset<pair<int,int> > rows;\nset<int> row[N],col[N];\nset<int>::iterator it;\nmap<int,int> mp[N];\npair<int,int> Ans[N];\nint getfa(int *fa,int x){\n\tif (x==fa[x]){\n\t\treturn x;\n\t}\n\treturn fa[x]=getfa(fa,fa[x]);\n}\nvoid Merge_row(int x,int y){\n\tfor (it=row[y].begin();it!=row[y].end();it++){\n\t\tmp[x][*it]=mp[y][*it];\n\t\trow[x].insert(*it);\n\t\tcol[*it].erase(y);\n\t\tcol[*it].insert(x);\n\t}\n}\nvoid Merge_col(int x,int y){\n\tfor (it=col[y].begin();it!=col[y].end();it++){\n\t\tmp[*it][x]=mp[*it][y];\n\t\tcol[x].insert(*it);\n\t\trow[*it].erase(y);\n\t\trow[*it].insert(x);\n\t}\n}\nint main(){\n\tint n,m1,m2,h=0,i;\n\tscanf(\"%d%d%d\",&n,&m1,&m2);\n\tfor (i=1;i<=n;i++){\n\t\tfa1[i]=fa2[i]=i;\n\t}\n\tfor (i=1;i<=m1;i++){\n\t\tint x,y;\n\t\tscanf(\"%d%d\",&x,&y);\n\t\tint p=getfa(fa1,x),q=getfa(fa1,y);\n\t\tfa1[p]=q;\n\t}\n\tfor (i=1;i<=m2;i++){\n\t\tint x,y;\n\t\tscanf(\"%d%d\",&x,&y);\n\t\tint p=getfa(fa2,x),q=getfa(fa2,y);\n\t\tfa2[p]=q;\n\t}\n\tif (m1<m2){\n\t\tswap(fa1,fa2);\n\t}\n\t\n\tfor (i=1;i<=n;i++){\n\t\tint p1=getfa(fa1,i),p2=getfa(fa2,i);\n\t\tmp[p1][p2]=i;\n\t\trow[p1].insert(p2);\n\t\tcol[p2].insert(p1);\n\t}\n\tfor (i=1;i<=n;i++){\n\t\tif (getfa(fa1,i)==i){\n\t\t\trows.insert(make_pair(-row[i].size(),i));\n\t\t}\n\t}\n\t\n\twhile (rows.size()>1){\n\t\tint x=rows.begin()->second;\n\t\trows.erase(rows.begin());\n\t\tint y=rows.begin()->second;\n\t\trows.erase(rows.begin());\n\t\tif (row[x].size()<row[y].size()){\n\t\t\tswap(x,y);\n\t\t}\n\t\tit=row[x].begin();\n\t\tint a=*it,b=*row[y].begin();\n\t\tif (a==b){\n\t\t\ta=*++it;\n\t\t}\n\t\tAns[++h]=make_pair(mp[x][a],mp[y][b]);\n\t\tif (col[a].size()<col[b].size()){\n\t\t\tswap(a,b);\n\t\t}\n\t\tMerge_row(x,y);\n\t\tMerge_col(a,b);\n\t\trows.insert(make_pair(-row[x].size(),x));\n\t}\n\t\n\tprintf(\"%d\\n\",h);\n\tfor (i=1;i<=h;i++){\n\t\tprintf(\"%d %d\\n\",Ans[i].first,Ans[i].second);\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "trees",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1559",
    "index": "E",
    "title": "Mocha and Stars",
    "statement": "Mocha wants to be an astrologer. There are $n$ stars which can be seen in Zhijiang, and the brightness of the $i$-th star is $a_i$.\n\nMocha considers that these $n$ stars form a constellation, and she uses $(a_1,a_2,\\ldots,a_n)$ to show its state. A state is called mathematical if all of the following three conditions are satisfied:\n\n- For all $i$ ($1\\le i\\le n$), $a_i$ is an integer in the range $[l_i, r_i]$.\n- $\\sum \\limits _{i=1} ^ n a_i \\le m$.\n- $\\gcd(a_1,a_2,\\ldots,a_n)=1$.\n\nHere, $\\gcd(a_1,a_2,\\ldots,a_n)$ denotes the greatest common divisor (GCD) of integers $a_1,a_2,\\ldots,a_n$.\n\nMocha is wondering how many different mathematical states of this constellation exist. Because the answer may be large, you must find it modulo $998\\,244\\,353$.\n\nTwo states $(a_1,a_2,\\ldots,a_n)$ and $(b_1,b_2,\\ldots,b_n)$ are considered different if there exists $i$ ($1\\le i\\le n$) such that $a_i \\ne b_i$.",
    "tutorial": "We firstly ignore the constraint of $\\gcd$, let $f([l_1,l_2,\\ldots,l_n],[r_1,r_2,\\ldots,r_n],M)$ be the number of integers $(a_1,a_2,\\cdots,a_n)$ satisfy the following two conditions: For all $i$ ($1\\le i\\le n$), $a_i$ is an integer in the range $[l_i, r_i]$. $\\sum \\limits _{i=1} ^ n a_i \\le m$. We can compute it in $O(nM)$ by Knapsack DP optimized by prefix-sums. Then we consider about the constraint of $\\gcd$, let $\\mu(n)$ be Mobius function, and $g(a_1,a_2,\\ldots,a_n)$ be $1$ if $(a_1,a_2,\\cdots,a_n)$ satisfies the two conditions we mentioned about (without the constraint of $\\gcd$), otherwise it will be $0$. The answer we want is: $\\begin{aligned} &\\sum_{a_1=l_1}^{r_1}\\sum_{a_2=l_2}^{r_2}\\cdots\\sum_{a_n=l_n}^{r_n}[\\gcd(a_1,a_2,\\ldots,a_n)=1]g(a_1,a_2,\\ldots,a_n) \\newline =&\\sum_{a_1=l_1}^{r_1}\\sum_{a_2=l_2}^{r_2}\\cdots\\sum_{a_n=l_n}^{r_n}g(a_1,a_2,\\ldots,a_n)\\sum_{d \\mid \\gcd(a_1,a_2,\\ldots,a_n)}\\mu(d) \\newline =&\\sum_{a_1=l_1}^{r_1}\\sum_{a_2=l_2}^{r_2}\\cdots\\sum_{a_n=l_n}^{r_n}g(a_1,a_2,\\ldots,a_n)\\sum_{d\\mid a_1,d\\mid a_2,\\ldots,d \\mid a_n}\\mu(d) \\newline =&\\sum_{d=1}^M\\mu(d)\\sum_{a_1=\\lceil\\frac{l_1}{d}\\rceil}^{\\lfloor\\frac{r_1}{d}\\rfloor}\\sum_{a_2=\\lceil\\frac{l_2}{d}\\rceil}^{\\lfloor\\frac{r_2}{d}\\rfloor}\\cdots\\sum_{a_n=\\lceil\\frac{l_n}{d}\\rceil}^{\\lfloor\\frac{r_n}{d}\\rfloor}g(a_1d,a_2d,\\ldots,a_nd) \\newline \\end{aligned}$ $\\begin{aligned} \\sum_{d=1}^M\\mu(d)f\\left(\\left\\lceil\\dfrac{l_1}{d}\\right\\rceil,\\left\\lceil\\dfrac{l_2}{d}\\right\\rceil,\\ldots,\\left\\lceil\\dfrac{l_n}{d}\\right\\rceil,\\left\\lfloor\\dfrac{r_1}{d}\\right\\rfloor,\\left\\lfloor\\dfrac{r_2}{d}\\right\\rfloor,\\ldots,\\left\\lfloor\\dfrac{r_n}{d}\\right\\rfloor,\\left\\lfloor\\dfrac{M}{d}\\right\\rfloor\\right) \\end{aligned}$",
    "code": "#include <bits/stdc++.h>\n#define maxn 100086\n\nusing namespace std;\n\nconst int p = 998244353;\n\nint n, m;\nint l[maxn], r[maxn];\nint f[maxn], sum[maxn];\n\nint cal(int d){\n\tint M = m / d;\n\tf[0] = 1;\n\tfor(int i = 1;i <= M;i++) f[i] = 0;\n\tfor(int i = 1;i <= n;i++){\n\t\tint L = (l[i] + d - 1) / d, R = r[i] / d;\n\t\tif(L > R) return 0;\n\t\tfor(int j = 0;j <= M;j++) sum[j] = (f[j] + (j ? sum[j - 1] : 0)) % p;\n\t\tfor(int j = 0;j <= M;j++){\n\t\t\tf[j] = ((j - L >= 0 ? sum[j - L] : 0) + p - (j - R - 1 >= 0 ? sum[j - R - 1] : 0)) % p;\n\t\t}\n\t}\n\tint ans = 0;\n\tfor(int i = 1;i <= M;i++) ans = (ans + f[i]) % p;\n\treturn ans;\n}\n\nint prm[maxn], cnt, mu[maxn];\nbool tag[maxn];\n\nint main(){\n\tscanf(\"%d%d\", &n, &m);\n\tfor(int i = 1;i <= n;i++) scanf(\"%d%d\", &l[i], &r[i]);\n\tmu[1] = 1;\n\tfor(int i = 2;i <= m;i++){\n\t\tif(!tag[i]) prm[++cnt] = i, mu[i] = p - 1;\n\t\tfor(int j = 1;j <= cnt && prm[j] * i <= m;j++){\n\t\t\ttag[i * prm[j]] = true;\n\t\t\tif(i % prm[j]) mu[i * prm[j]] = (p - mu[i]) % p;\n\t\t\telse break;\n\t\t} \n\t}\n\tint ans = 0;\n\tfor(int i = 1;i <= m;i++) ans = (ans + 1ll * mu[i] * cal(i)) % p;\n\tprintf(\"%d\", ans);\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1560",
    "index": "A",
    "title": "Dislike of Threes",
    "statement": "Polycarp doesn't like integers that are divisible by $3$ or end with the digit $3$ in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too.\n\nPolycarp starts to write out the positive (greater than $0$) integers which he likes: $1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \\dots$. Output the $k$-th element of this sequence (the elements are numbered from $1$).",
    "tutorial": "The solution is simple: let's create an integer variable (initially set to $0$) that will contain the number of considered liked integers. Let's iterate over all positive integers starting with $1$. Let's increase the variable only when the considered number is liked. If the variable is equal to $k$, let's stop the iteration and output the last considered number. Since the answer for $k = 1000$ is $x = 1666$, the count of considered numbers is at most $1666$ so the solution will work on the specified limitations fast enough.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tint k;\n\t\tcin >> k;\n\n\t\tfor (int i = 1; ; i++)\n\t\t{\n\t\t\tif (i % 3 == 0 || i % 10 == 3)\n\t\t\t\tcontinue;\n\t\t\tif (--k == 0)\n\t\t\t{\n\t\t\t\tcout << i << '\\n';\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1560",
    "index": "B",
    "title": "Who's Opposite?",
    "statement": "Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $1$. Each person is looking through the circle's center at the opposite person.\n\n\\begin{center}\n{\\small A sample of a circle of $6$ persons. The orange arrows indicate who is looking at whom.}\n\\end{center}\n\nYou don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $a$ is looking at the person with the number $b$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $c$? If, for the specified $a$, $b$, and $c$, no such circle exists, output -1.",
    "tutorial": "The person with the number $a$ looks at the person with the number $b$ so the count of people standing to the left of $a$ between $a$ and $b$ is equal to the count of people standing to the right of $a$ between $a$ and $b$. Therefore, both counts are equal to $\\frac{n - 2}{2}$, hence $n$ must be a solution of the equation $\\frac{n - 2}{2} = |a - b| - 1$. The only solution of the equation is $n = 2 \\cdot |a - b|$. Let's check that in the circle of $n$ people can occur the numbers $a$, $b$ and $c$, i. e. let's check that $1 \\le a, b, c \\le n$. If it's false, there's no solution (output $-1$). Since the person with the number $d$ looks at the person with the number $c$, the condition $\\frac{n - 2}{2} = |c - d| - 1$ must be met. Let's solve the equation for $d$. There are two solutions: $d_1 = c + \\frac{n}{2}$; $d_2 = c - \\frac{n}{2}$. We can output any of $d_i$ such that $1 \\le d_i \\le n$. It's easy to prove that exactly one of the solutions meets the condition.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tll a, b, c;\n\t\tcin >> a >> b >> c;\n\n\t\tll n = 2 * abs(a - b);\n\t\tif (a > n || b > n || c > n)\n\t\t\tcout << -1 << '\\n';\n\t\telse\n\t\t{\n\t\t\tll d = n / 2 + c;\n\t\t\twhile (d > n) d -= n;\n\t\t\tcout << d << '\\n';\n\t\t}\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1560",
    "index": "C",
    "title": "Infinity Table",
    "statement": "Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $1$, starting from the topmost one. The columns are numbered from $1$, starting from the leftmost one.\n\nInitially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $1$ and so on to the table as follows.\n\n\\begin{center}\n{\\small The figure shows the placement of the numbers from $1$ to $10$. The following actions are denoted by the arrows.}\n\\end{center}\n\nThe leftmost topmost cell of the table is filled with the number $1$. Then he writes in the table all positive integers beginning from $2$ sequentially using the following algorithm.\n\nFirst, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).\n\nAfter that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.\n\nA friend of Polycarp has a favorite number $k$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $k$.",
    "tutorial": "Let's call a set of cells being filled from the topmost row to the leftmost column a layer. E. g. the $1$-st layer consists of the single number $1$, the $2$-nd layer consists of the numbers $2$, $3$ and $4$, the $3$-rd layer consists of the numbers $5$, $6$, $7$, $8$ and $9$, etc. The number of cells in layers forms an arithmetic progression. The first layer consists of $a_1 = 1$ cells, the $i$-th layer consists of $a_i = a_{i-1} + 2$ cells. The minimum number in the $i$-th layer $x_i$ is equal to the sum of sizes of all layers from the $1$-st to the $(i - 1)$-th plus $1$. Suppose that $k$ belongs to the $i$-th layer. Consider the value of $m = k - x_i + 1$. Polycarp fills exactly $i$ cells on the $i$-th layer before he starts filling the cells from the right to the left (i. e. while he goes down). Therefore, if $m \\le i$, the number $k$ belongs to the $m$-th row and the $i$-th column. Otherwise, the number belongs to the $i$-th row and the $(i - (m - i))$-th column. Consider a way to find the coordinates of a given number $k$. Let's iterate by the layer number $i$ to which given the number belongs calculating the values of $a_i$ and $x_i$ (going to the next layer, let's calculate the next layer parameters as follows: $x_{i + 1} := x_i + a_i$; $a_{i + 1} := a_i + 2$). The iteration must be stopped if the layer number $i$ is such that $x_i \\le k < x_{i + 1}$. Using the values of $i$ and $x_i$, we can calculate the given number's coordinates in the described way in $O(1)$. The total time of calculating the coodrinates for one given $k$ is $O(i_k)$ where $i_k$ is the number of the layer to which the given $k$ belongs. Let's represent the value of $x_i$ as $x_i = f(i)$: $x_i = 1 + \\sum\\limits_{j = 1}^{i - 1} a_j = 1 + \\sum\\limits_{j = 1}^{i - 1} (2j - 1) = 1 + \\frac{1 + 2(i - 1) - 1}{2} \\cdot (i - 1) = 1 + (i - 1)^2$. $1 + (i_k - 1)^2 = x_{i_k} \\le k < x_{i_k + 1} = 1 + i_k^2$, hence $i_k \\approx \\sqrt(k)$. Therefore, the coordinates of one number $k$ may be calculated in $O(\\sqrt{k})$. At the same time, as it follows from the formulas, the layer number $i_k$ can be calculated as follows: $i_k = \\lceil \\sqrt{k} \\rceil$ (the square root of $k$ rounded up). To avoid accuracy problems, you can calculate the value using a loop.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tint k;\n\t\tcin >> k;\n\n\t\tint a = 1;\n\t\tint x = 1;\n\t\tint i = 1;\n\n\t\twhile (k >= x + a)\n\t\t{\n\t\t\tx += a;\n\t\t\ta += 2;\n\t\t\ti += 1;\n\t\t}\n\n\t\tint m = k - x + 1;\n\t\tif (m <= i)\n\t\t\tcout << m << ' ' << i << '\\n';\n\t\telse\n\t\t\tcout << i << ' ' << (i - (m - i)) << '\\n';\n\t}\n}\n\n",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1560",
    "index": "D",
    "title": "Make a Power of Two",
    "statement": "You are given an integer $n$. In $1$ move, you can do one of the following actions:\n\n- erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is \"empty\");\n- add one digit \\textbf{to the right}.\n\nThe actions may be performed in any order any number of times.\n\nNote that if, after deleting some digit from a number, it will contain leading zeroes, they will \\textbf{not} be deleted. E.g. if you delete from the number $301$ the digit $3$, the result is the number $01$ (not $1$).\n\nYou need to perform the \\textbf{minimum} number of actions to make the number any power of $2$ (i.e. there's an integer $k$ ($k \\ge 0$) such that the resulting number is equal to $2^k$). \\textbf{The resulting number must not have leading zeroes}.\n\nE.g. consider $n=1052$. The answer is equal to $2$. First, let's add to the right one digit $4$ (the result will be $10524$). Then let's erase the digit $5$, so the result will be $1024$ which is a power of $2$.\n\nE.g. consider $n=8888$. The answer is equal to $3$. Let's erase any of the digits $8$ three times. The result will be $8$ which is a power of $2$.",
    "tutorial": "Suppose we must turn $n$ into some specific number $x$. In this case, we can use the following greedy algorithm. Consider the string forms - $s_n$ and $s_x$ - of the numbers $n$ and $x$, respectively. Let's make a pointer $p_n$ pointing at the first character of the string $s_n$ and a pointer $p_x$ pointing at the first character of the string $s_x$. Let's initialize a variable $taken = 0$ in which we will store a number of selected characters. Until any of the pointers points at the place that is out of the corresponding string, let's do the following procedure: if the characters to which the pointers point are equal, we will take the character (increase $taken$ by $1$) and move both pointers $1$ character to the right, otherwise, the only action we must perform is to move $s_n$ $1$ character to the right. The variable $taken$ will contain after the whole process the length of the longest subsequence of $s_n$ equal to a prefix of $s_x$, i. e. the maximum number of original characters of $s_n$ that we will not erase. We must add to the resulting string all remaining characters of $s_x$ to turn it into $s_x$. Therefore, we must erase $|s_n| - taken$ digits and add $|s_x| - taken$ digits so the answer for this subproblem is $ans(n, x) = |s_n| + |s_x| - 2 \\cdot taken$ where $|s|$ means the length of a string $s$. Suppose we have a set $X$ of powers of two such that it's enough to consider to get the problem's answer. The problem can be solved as follows: for each $x \\in X$ let's calculate the answer for the subproblem described above and select the value of $\\min\\limits_{x \\in X} ans(n,x)$ as the answer. What set of powers of two we can take? Suppose the number $n$ consists of no more than $9$ digits. The answer for each $n$ consisting of $d$ digits doesn't exceed $d + 1$, hence we can get this value by turning the number into $1$ in $d + 1$ move adding $1$ to the right of the number, and erasing all other $d$ digits. Suppose there's a number $x$ such that $ans(n, x) \\le d$. So it consists of no more than $2 \\cdot d$ digits - this value can be reached as follows: we must not erase any digit and add $d$ digits. Therefore, if $d \\le 9$, each number $x$ such that $ans(n, x) \\le d$ consists of no more than $18$ digits, hence $x < 10^{18}$. Suppose $n$ consists of more than $9$ digits. Then $n = 10^9$ because $n \\le 10^9$ according to the input format. The answer for the number doesn't exceed $9$ - we can get this answer if we erase all $0$ from the number to turn it into $1$. Suppose there's a number $x$ such that $ans(n, x) \\le 8$. This number can consist of no more than $18$ digits ($10$ digits of $n$ plus $8$ digits), hence $x < 10^{18}$. Therefore, it's enough to consider all powers of two that are less than $10^{18}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst ll P2LIM = (ll)2e18;\n\nint solve(string s, string t)\n{\n\tint tp = 0;\n\tint sp = 0;\n\tint taken = 0;\n\n\twhile (sp < s.length() && tp < t.length())\n\t{\n\t\tif(s[sp] == t[tp])\n\t\t{\n\t\t\ttaken++;\n\t\t\ttp++;\n\t\t}\n\t\tsp++;\n\t}\n\n\treturn (int)s.length() - taken + (int)t.length() - taken;\n}\n\nvector<string> ts;\n\nint main()\n{\n\tfor (ll p2 = 1; p2 <= P2LIM; p2 *= 2)\n\t\tts.push_back(to_string(p2));\n\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tstring n;\n\t\tcin >> n;\n\n\t\tint ans = n.length() + 1;\n\t\tfor (auto p2 : ts)\n\t\t\tans = min(ans, solve(n, p2));\n\t\tcout << ans << '\\n';\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1560",
    "index": "E",
    "title": "Polycarp and String Transformation",
    "statement": "Polycarp has a string $s$. Polycarp performs the following actions until the string $s$ is empty ($t$ is initially an empty string):\n\n- he adds to the right to the string $t$ the string $s$, i.e. he does $t = t + s$, where $t + s$ is a concatenation of the strings $t$ and $s$;\n- he selects an arbitrary letter of $s$ and removes from $s$ all its occurrences (\\textbf{the selected letter must occur in the string $s$ at the moment of performing this action}).\n\nPolycarp performs this sequence of actions \\textbf{strictly} in this order.\n\nNote that after Polycarp finishes the actions, the string $s$ will be empty and the string $t$ will be equal to some value (that is undefined and depends on the order of removing).\n\nE.g. consider $s$=\"abacaba\" so the actions may be performed as follows:\n\n- $t$=\"abacaba\", the letter 'b' is selected, then $s$=\"aacaa\";\n- $t$=\"abacabaaacaa\", the letter 'a' is selected, then $s$=\"c\";\n- $t$=\"abacabaaacaac\", the letter 'c' is selected, then $s$=\"\" (the empty string).\n\nYou need to restore the initial value of the string $s$ using only the final value of $t$ and find the order of removing letters from $s$.",
    "tutorial": "Suppose it's given a string $t$ for which the answer exists. Consider the last non-empty value of $s$. Only $1$ letter occurs in the value and the letter is the last removed letter. At the same time, the value of $s$ is a suffix of $t$ so the last character of $t$ is the last removed letter. Consider the second-last non-empty value of $s$. It contains exactly $2$ distinct letters so that one of them is the last removed letter and the other is the second-last removed letter. The concatenation of the second-last and the last values of $s$ is a suffix of $t$ consisting only of the letters. Therefore, the letter which occurrence is the last of the occurrences of all letters except the last removed one is the second-last removed letter. Considering so other values, we are proving that the order of removing the letters is the order the last occurrences of the letters occur in the string $t$. Suppose $k$ is the number of the step in which some letter was removed, $c_k$ is the number of occurrences of the letter in the initial value of $s$. The letter occurs in exactly $k$ different values of $s$. In each of them, the letter occurs exactly $c_k$ times. So the letter occurs in $t$ exactly $d_k = k \\cdot c_k$ times. Therefore, using the number of the step ($k$) in which the letter was removed and the number of the letter's occurrences in $t$ ($d_k$), let's calculate the number of the letter's occurrences in the string $s$: $c_k = \\frac{d_k}{k}$. If $d_k$ isn't completely divisible by $k$, there's no solution. The sum of all $c_k$ of all letters occurring in $t$ is the length of the initial value of $s$. Since the initial value is a prefix of $t$, the possible answer is the prefix of $t$ having the length equal to the sum of all $c_k$. Before outputting the prefix, check that you can get from the supposed value of the string $s$ the string $t$. Checking it, you may use the algorithm from the statement. If the resulting string is equal to $t$, the answer is correct and must be outputted, otherwise, there's no solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint cntsrc[26]; // don't forget to memset it but not cnt\nint* cnt = cntsrc - 'a'; // so cnt['a'] = cntsrc[0] and so on\n\npair<string, string> decrypt(string s)\n{\n\tstring order;\n\treverse(s.begin(), s.end());\n\tfor (auto c : s)\n\t{\n\t\tif (!cnt[c])\n\t\t\torder.push_back(c);\n\t\tcnt[c]++;\n\t}\n\n\tint m = order.length();\n\tint originalLength = 0;\n\tfor (int i = 0; i < m; i++)\n\t\toriginalLength += cnt[order[i]] / (m - i);\n\n\treverse(order.begin(), order.end());\n\treturn { string(s.rbegin(), s.rbegin() + originalLength), order };\n}\n\nstring encrypt(pair<string, string> p)\n{\n\tstring result = p.first;\n\n\tfor (auto c : p.second)\n\t{\n\t\tstring temp;\n\t\tfor (auto d : p.first)\n\t\t\tif (d != c)\n\t\t\t{\n\t\t\t\ttemp.push_back(d);\n\t\t\t\tresult.push_back(d);\n\t\t\t}\n\t\tp.first = temp;\n\t}\n\n\treturn result;\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tmemset(cntsrc, 0, sizeof(cntsrc));\n\t\tstring s;\n\t\tcin >> s;\n\n\t\tauto ans = decrypt(s);\n\t\tauto check = encrypt(ans);\n\n\t\tif (check == s)\n\t\t\tcout << ans.first << ' ' << ans.second << '\\n';\n\t\telse\n\t\t\tcout << \"-1\\n\";\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1560",
    "index": "F1",
    "title": "Nearest Beautiful Number (easy version)",
    "statement": "It is a simplified version of problem F2. The difference between them is the constraints (F1: $k \\le 2$, F2: $k \\le 10$).\n\nYou are given an integer $n$. Find the minimum integer $x$ such that $x \\ge n$ and the number $x$ is $k$-beautiful.\n\nA number is called $k$-beautiful if its decimal representation having no leading zeroes contains no more than $k$ different digits. E.g. if $k = 2$, the numbers $3434443$, $55550$, $777$ and $21$ are $k$-beautiful whereas the numbers $120$, $445435$ and $998244353$ are not.",
    "tutorial": "Suppose the number $n$ contains $m$ digits. The desired number $x$ isn't greater than the number consisting of $m$ digits $9$. This number is $1$-beautiful whereas any $1$-beautiful number is at the same time $k$-beautiful, so $x$ contains at most $m$ digits. At the same time, $x \\ge n$ so $x$ contains at least $m$ digits. Therefore, the desired number contains exactly $m$ digits. Suppose $k = 1$. There are exactly $9$ $k$-beautiful numbers containing exactly $m$ digits. To get the answer fast, it's possible to consider all these numbers. Suppose $k = 2$. If $n$ is already $k$-beautiful, let's output it. Otherwise, let's initialize the answer by the value as if $k = 1$. Let's iterate two digits $a$ and $b$ such that $a < b$. Let's search for the answer by considering the strings consisting only of digits $a$ and $b$. Let's iterate a prefix of $n$ starting from the empty one so that the prefix will be the prefix of $x$. This prefix must contain only the digits $a$ and $b$. Consider the leftmost digit that doesn't belong to the prefix. Let's try to increase it. If the digit is less than $a$, a possible answer is a number such that it has the considered prefix and all other digits are equal to $a$. Let's update the answer by this number (i.e. if the found number is less than the best previously found answer, let's set the answer to the found number). If the considered digit is at least $a$ and is less than $b$, let's update the answer by the number such that it has the considered prefix, the digit $b$ follows the prefix, and all other digits are equal to $a$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring solve1(string n)\n{\n\tstring res(n.length(), '9');\n\tfor (char c = '8'; c >= '0'; c--)\n\t{\n\t\tstring t(n.length(), c);\n\t\tif (t >= n)\n\t\t\tres = t;\n\t}\n\n\treturn res;\n}\n\nstring solve2(string n)\n{\n\tstring res = solve1(n);\n\n\tfor(char a = '0'; a <= '9'; a++)\n\t\tfor (char b = a + 1; b <= '9'; b++)\n\t\t{\n\t\t\tbool n_ok = true;\n\t\t\tfor (int i = 0; i < n.length(); i++)\n\t\t\t{\n\t\t\t\tif (n[i] < b)\n\t\t\t\t{\n\t\t\t\t\tstring t = n;\n\t\t\t\t\tif (t[i] < a) t[i] = a;\n\t\t\t\t\telse t[i] = b;\n\t\t\t\t\tfor (int j = i + 1; j < n.length(); j++)\n\t\t\t\t\t\tt[j] = a;\n\t\t\t\t\tif (res > t)\n\t\t\t\t\t\tres = t;\n\t\t\t\t}\n\n\t\t\t\tif(n[i] != a && n[i] != b)\n\t\t\t\t{\n\t\t\t\t\tn_ok = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (n_ok) return n;\n\t\t}\n\n\treturn res;\n}\n\nstring solve()\n{\n\tstring n;\n\tint k;\n\tcin >> n >> k;\n\n\tif (k == 1) return solve1(n);\n\telse return solve2(n);\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t\tcout << solve() << '\\n';\n\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1560",
    "index": "F2",
    "title": "Nearest Beautiful Number (hard version)",
    "statement": "It is a complicated version of problem F1. The difference between them is the constraints (F1: $k \\le 2$, F2: $k \\le 10$).\n\nYou are given an integer $n$. Find the minimum integer $x$ such that $x \\ge n$ and the number $x$ is $k$-beautiful.\n\nA number is called $k$-beautiful if its decimal representation having no leading zeroes contains no more than $k$ different digits. E.g. if $k = 2$, the numbers $3434443$, $55550$, $777$ and $21$ are $k$-beautiful whereas the numbers $120$, $445435$ and $998244353$ are not.",
    "tutorial": "Suppose the number $n$ contains $m$ digits and its decimal representation is $d_1d_2 \\dots d_m$. The desired number $x$ isn't greater than the number consisting of $m$ digits $9$. This number is $1$-beautiful whereas any $1$-beautiful number is at the same time $k$-beautiful, so $x$ contains at most $m$ digits. At the same time, $x \\ge n$ so $x$ contains at least $m$ digits. Therefore, the desired number contains exactly $m$ digits. Since we search for the minimum $x$, we need to minimize first of all the first digit, only then the second digit, etc. Therefore, we need to find a prefix of the decimal representation of $n$ such that is a prefix of the decimal representation of $x$. Let's do it greedily. Short solution, works in $O(m^2)$ Let's find the maximum prefix of $n$ such that contains no more than $k$ distinct numbers. Suppose the prefix has the length $p$. If $p = m$, then $n$ is already $k$-beautiful, let's output it. Otherwise, let's increase the prefix like a number by $1$, e.g. if $n = 1294$ and $p = 3$, then we increase $129$ by $1$, the resulting prefix is $130$. All other digits ($d_{p + 2}, d_{p + 3}, \\dots, d_m$), let's set to zeroes (e.g. if $n = 1294$ and $p = 3$, then $n$ will be turned into $1300$). The answer for the old $n$ is the answer for the new $n$. To get the answer for the new $n$, let's start the described procedure once again preparing the new $n$. Long solution, works in $O(mk)$ Let's find the maximum prefix of $n$ such that contains no more than $k$ distinct numbers. It's possible to do using a $map$ in which for each digit (the key) the number of its occurrences in the prefix is stored. For an empty prefix, the $map$ is empty. If we increase the prefix length by $1$, we need to check that $map$ contains no more than $k$ keys and add a new key with the value $1$ or increase the value of an existing key. If the length of the found prefix is equal to the length of the whole decimal representation, the given number is already $k$-beautiful so the answer is $n$. Otherwise, the found prefix may not be a prefix of the desired number. Let's change the digits of the decimal representation of $n$ to turn it into the desired number $x$. Let's start the following procedure: suppose we consider a prefix with the length equal to $p$. First, let's find out, is it possible to increase the first element out of the prefix (i. e. $d_{p + 1}$). We need to do it because if we consider the length $p$, then the prefix with the length $p + 1$ cannot be unchanged so the element $d_{p + 1}$ must be changed whereas it cannot be decreased because, in this case, we will get the number which is less than $n$. If we can increase the element $d_{p + 1}$ so that the prefix with the length $p + 1$ has at most $k$ distinct digits, the only thing that is remained to do is to fill the remaining digits $d_{p + 2}, d_{p + 3}, \\dots d_m$ somehow greedily and output the result. If we cannot increase the element $d_{p + 1}$, let's decrease the length of the considered prefix $p$ by $1$ updating the $map$ (let's decrease the value corresponding to the key $d_{p}$ by $1$, then, if it's equal to $0$, we remove the key $d_{p}$ from the $map$). Consider, how and under what conditions we can change $d_{p + 1}$ and the following digits: If $d_{p + 1} = 9$, it's impossible. Suppose the considered prefix contains less than $k$ distinct digits (the number of the keys in the $map$ is less than $k$). In this case, we can replace the digit $d_{p + 1}$ with the value $d_{p + 1} + 1$ so the prefix with the length $p + 1$ will not contain more than $k$ distinct elements because the prefix with the length $p$ doesn't contain more than $k - 1$ distinct elements. If the prefix with the length $p + 1$ still contains less than $k$ distinct numbers, let's replace the remaining digits ($d_{p + 2}$, $d_{p + 3}$, etc) with $0$. Otherwise, we can replace them with the minimum digit that occurs in the prefix with the length $p + 1$ (it may be $0$). Suppose the considered prefix contains exactly $k$ distinct digits. So let's find the minimum digit that occurs in the prefix with the length $p$ and is greater than $d_{p + 1}$. If such digit exists, let's replace $d_{p + 1}$ with it, and all following digits with the minimum digit that occurs in the prefix with the length $p + 1$. Otherwise, the element $d_{p + 1}$ cannot be increased. The converted by the procedure $n$ is the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstring solveFillingSuffix(string& n, char d, int from)\n{\n\tfor (int i = from; i < n.length(); i++)\n\t\tn[i] = d;\n\treturn n;\n}\n\nvoid decAt(map<char, int>& d, char c)\n{\n\tif (d.count(c))\n\t{\n\t\td[c]--;\n\t\tif (d[c] == 0) d.erase(c);\n\t}\n}\n\nstring solve()\n{\n\tstring n;\n\tint k;\n\tcin >> n >> k;\n\n\tmap<char, int> d;\n\tint pref = 0;\n\n\twhile (pref < n.length())\n\t{\n\t\tif (d.count(n[pref]))\n\t\t{\n\t\t\td[n[pref++]]++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (d.size() == k) break;\n\t\td[n[pref++]]++;\n\t}\n\n\tif (pref == n.length())\n\t\treturn n;\n\n\twhile (true)\n\t{\n\t\tif (n[pref] == '9')\n\t\t{\n\t\t\tdecAt(d, n[--pref]);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (d.size() < k)\n\t\t{\n\t\t\td[++n[pref]]++;\n\t\t\treturn solveFillingSuffix(n, d.size() < k ? '0' : d.begin()->first, pref + 1);\n\t\t}\n\n\t\tauto it = d.upper_bound(n[pref]);\n\t\tif (it == d.end())\n\t\t{\n\t\t\tdecAt(d, n[--pref]);\n\t\t\tcontinue;\n\t\t}\n\n\t\tn[pref] = it->first;\n\t\treturn solveFillingSuffix(n, d.begin()->first, pref + 1);\n\t}\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t\tcout << solve() << '\\n';\n\t\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1561",
    "index": "A",
    "title": "Simply Strange Sort",
    "statement": "You have a permutation: an array $a = [a_1, a_2, \\ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd.\n\nConsider the following algorithm of sorting the permutation in increasing order.\n\nA helper procedure of the algorithm, $f(i)$, takes a single argument $i$ ($1 \\le i \\le n-1$) and does the following. If $a_i > a_{i+1}$, the values of $a_i$ and $a_{i+1}$ are exchanged. Otherwise, the permutation doesn't change.\n\nThe algorithm consists of iterations, numbered with consecutive integers starting with $1$. On the $i$-th iteration, the algorithm does the following:\n\n- if $i$ is odd, call $f(1), f(3), \\ldots, f(n - 2)$;\n- if $i$ is even, call $f(2), f(4), \\ldots, f(n - 1)$.\n\nIt can be proven that after a finite number of iterations the permutation will be sorted in increasing order.\n\nAfter how many iterations will this happen for the first time?",
    "tutorial": "The described sorting algorithm is similar to Odd-even sort. In this problem, it's enough to carefully implement the process described in the problem statement. Here is one sample implementation in C++: To estimate the complexity of this solution, we need to know the maximum number of iterations required to sort a permutation of length $n$. It turns out that this number is equal to exactly $n$, thus the complexity of the algorithm is $O(n^2)$. This is intuitive because the algorithm looks similar to bubble sort that requires $n$ iterations too, or you can directly check that sorting $[n, n-1, \\ldots, 1]$ requires $n$ iterations and reason that \"more sorted\" sequences can't require more iterations than \"less sorted\" sequences, and $[n, n-1, \\ldots, 1]$ is naturally the \"least sorted\" sequence of them all. For a formal proof see e.g. the linked Wikipedia page. The proof also follows from the editorial of problem F in Div. 1. If you have a simpler proof, please share in comments!",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt–) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n      cin >> a[i];\n    }\n    int ans = 0;\n    while (!is_sorted(a.begin(), a.end())) {\n      for (int i = ans % 2; i + 1 < n; i += 2) {\n        if (a[i] > a[i + 1]) {\n          swap(a[i], a[i + 1]);\n        }\n      }\n      ans += 1;\n    }\n    cout << ans << endl;\n  }\n  return 0;\n}\n",
    "tags": [
      "brute force",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1561",
    "index": "C",
    "title": "Deep Down Below",
    "statement": "In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.\n\nOn the current level, the hero is facing $n$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $i$, he will have to fight $k_i$ monsters in a row: first a monster with armor $a_{i, 1}$, then a monster with armor $a_{i, 2}$ and so on, finally, a monster with armor $a_{i, k_i}$.\n\nThe hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.\n\nEach time the hero beats a monster, the hero's power increases by $1$.\n\nFind the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.",
    "tutorial": "Consider a single cave $i$. Suppose that the hero enters the cave with power $x$. To beat the first monster, $x$ has to be greater than $a_{i, 1}$. After that, the hero's power will increase to $x+1$, and to beat the second monster, $x+1$ has to be greater than $a_{i, 2}$. Continuing this reasoning, we can write down $k_i$ inequalities: $x > a_{i, 1}$; $x + 1 > a_{i, 2}$; $x + 2 > a_{i, 3}$; ... $x + (k_i - 1) > a_{i, k_i}$. Let $b_i = \\max(a_{i, 1}, a_{i, 2} - 1, a_{i, 3} - 2, \\ldots, a_{i, k_i} - (k_i - 1))$. The system of inequalities above is equivalent to a single inequality: $x > b_i$. Thus, the hero can enter cave $i$ with power $x$ if and only if $x > b_i$, and the hero's power will increase by $k_i$. Armed with this knowledge, can we determine the best order to visit the caves for the hero? It turns out it's always best to enter the caves in non-decreasing order of $b_i$. Indeed, if the hero can enter cave $i$, he should always do that because entering a cave never makes things worse. If the hero enters a cave with greater $b$ right before a cave with smaller $b$, he might enter these caves in reverse order as well. Let's sort the caves accordingly and assume $b_1 \\le b_2 \\le \\ldots \\le b_n$. What is the smallest power the hero can start the level with? We can use the same reasoning that we used for a single cave. Suppose the hero starts the level with power $x$. To enter the first cave, $x$ has to be greater than $b_1$. After that, the hero's power will increase to $x+k_1$, and to enter the second cave, $x+k_1$ has to be greater than $b_2$. Continuing this reasoning, we can write down $n$ inequalities: $x > b_1$; $x + k_1 > b_2$; $x + k_1 + k_2 > b_3$; ... $x + \\sum \\limits_{i=1}^{n-1} k_i > b_n$. Let $p = \\max(b_1, b_2 - k_1, b_3 - (k_1 + k_2), \\ldots, b_n - \\sum \\limits_{i=1}^{n-1} k_i)$. The system of inequalities above is equivalent to a single inequality: $x > p$. Thus, the answer to the problem is $p + 1$. Alternatively, instead of solving the inequalities, one can use binary search on $x$.",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1562",
    "index": "A",
    "title": "The Miracle and the Sleeper",
    "statement": "You are given two integers $l$ and $r$, $l\\le r$. Find the largest possible value of $a \\bmod b$ over all pairs $(a, b)$ of integers for which $r\\ge a \\ge b \\ge l$.\n\nAs a reminder, $a \\bmod b$ is a remainder we get when dividing $a$ by $b$. For example, $26 \\bmod 8 = 2$.",
    "tutorial": "It's not hard to see that if $l \\le \\lfloor \\frac{r}{2} \\rfloor + 1$, then $r \\bmod (\\lfloor \\frac{r}{2} \\rfloor + 1) = \\lfloor \\frac{r-1}{2} \\rfloor$. It can be shown that the maximal possible answer. At the same time, let the segment not contain number $\\lfloor \\frac{r}{2} \\rfloor + 1$, that is, $l > \\lfloor \\frac{r}{2} \\rfloor + 1$. Then we can show that the maximal answer is $r \\bmod l = r-l$. Asymptotics: $O(1)$ per test case.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint l, r;\n\nvoid solve() {\n    if (r < l * 2) {\n        cout << r - l << endl;\n    }\n    else {\n        cout << (r - 1) / 2 << endl;\n    }\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        cin >> l >> r;\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1562",
    "index": "B",
    "title": "Scenes From a Memory",
    "statement": "During the hypnosis session, Nicholas suddenly remembered a positive integer $n$, which \\textbf{doesn't contain zeros in decimal notation}.\n\nSoon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes \\textbf{not prime}, that is, either composite or equal to one?\n\nFor some numbers doing so is impossible: for example, for number $53$ it's impossible to delete some of its digits to obtain a not prime integer. However, \\textbf{for all $n$ in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number}.\n\nNote that you cannot remove all the digits from the number.\n\nA prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. $1$ is neither a prime nor a composite number.",
    "tutorial": "Let's show that if a number has three digits, you can always remove at least one from it to get a number that is not prime. This can be proved by a simple brute-force search of all numbers with three digits, but we'll try to do it without a brute-force search. In fact, if a number contains the digits '1', '4', '6', '8' or '9', then that one digit is the answer, because $1$, $4$, $6$, $8$ and $9$ are not prime numbers. Now let's see what happens if the number doesn't have those digits. Then, if the number has two identical digits, we have found an answer of size two - the number of two identical digits ($22$, $33$, $55$, or $77$) is divisible by $11$. Also, if the digits $2$ or $5$ are not at the beginning of the number, we again have found an answer of size two - the number of two digits ending in $2$ or $5$ is not prime. If none of the above cases worked, then we find that a three-digit number has one of the following values: $237$, $273$, $537$, $573$. It is not difficult to see that these numbers have two digits, which form a number, that is divisible by three. Thus, the maximum answer is two, that is, you can leave no more than two digits in the number. You can find these digits by considering the above cases, or you can just try. It can be shown that such a brute-force solution will work for $O(k)$. Asymptotics: $O(k)$ per test case. Try to prove that the author's solution works for $O(k)$ for one test case. Finding an answer consisting of one digit works in $O(k)$. Now let's see how long the loop takes to complete. Indeed, it is easy to see that once the pairs of indexes $(0,1)$, $(0,2)$, and $(1,2)$ are considered, an answer will always be found. This is so because in any number of three digits you can find an answer consisting of two digits (this was proved earlier). So this is equivalent to removing all but the first three digits, and then solving the problem for them (assuming that the length of the optimal answer is two). Try to think of a way to search index pairs and a test such that this search works for $O(k^2)$ per test case. Let's take the string \\t{3737 \\ldots 37} as a string. We will search pairs of indices in the following way: first we will search all pairs of indices with different parities, and then all pairs of indices with the same parity. It is easy to see that such a search will work for $O(k^2)$ for one test case, because all pairs of indices with different parity will give numbers $37$ and $73$, which are prime, and there are $O(k^2)$ such pairs.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint n;\n\nstring s;\n\nbool prime[100];\n\nvoid solve() {\n    for (int i = 0; i < n; i++) {\n        if (s[i] == '1' || s[i] == '4' || s[i] == '6' || s[i] == '8' || s[i] == '9') {\n            cout << 1 << endl;\n            cout << s[i] << endl;\n            return;\n        }\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = i + 1; j < n; j++) {\n            if (!prime[(s[i] - '0') * 10 + (s[j] - '0')]) {\n                cout << 2 << endl;\n                cout << s[i] << s[j] << endl;\n                return;\n            }\n        }\n    }\n    exit(42);\n}\n\nint main() {\n    for (int i = 2; i < 100; i++) {\n        prime[i] = true;\n        for (int j = 2; j * j <= i; j++) {\n            if (i % j == 0) {\n                prime[i] = false;\n            }\n        }\n    }\n    int t;\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        cin >> s;\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1562",
    "index": "C",
    "title": "Rings",
    "statement": "\\begin{quote}\n{{\\small Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents —there was a pile of different rings: gold and silver...\"How am I to tell which is the One?!\" the mage howled.\n\n\"Throw them one by one into the Cracks of Doom and watch when Mordor falls!\"}}\n\\end{quote}\n\nSomewhere in a parallel Middle-earth, when Saruman caught Frodo, he only found $n$ rings. And the $i$-th ring was either gold or silver. For convenience Saruman wrote down a binary string $s$ of $n$ characters, where the $i$-th character was 0 if the $i$-th ring was gold, and 1 if it was silver.\n\nSaruman has a magic function $f$, which takes a binary string and returns a number obtained by converting the string into a binary number and then converting the binary number into a decimal number. For example, $f(001010) = 10, f(111) = 7, f(11011101) = 221$.\n\nSaruman, however, thinks that the order of the rings plays some important role. He wants to find $2$ pairs of integers $(l_1, r_1), (l_2, r_2)$, such that:\n\n- $1 \\le l_1 \\le n$, $1 \\le r_1 \\le n$, $r_1-l_1+1\\ge \\lfloor \\frac{n}{2} \\rfloor$\n- $1 \\le l_2 \\le n$, $1 \\le r_2 \\le n$, $r_2-l_2+1\\ge \\lfloor \\frac{n}{2} \\rfloor$\n- Pairs $(l_1, r_1)$ and $(l_2, r_2)$ are distinct. That is, at least one of $l_1 \\neq l_2$ and $r_1 \\neq r_2$ must hold.\n- Let $t$ be the substring $s[l_1:r_1]$ of $s$, and $w$ be the substring $s[l_2:r_2]$ of $s$. Then \\textbf{there exists non-negative integer $k$, such that $f(t) = f(w) \\cdot k$.}\n\nHere substring $s[l:r]$ denotes $s_ls_{l+1}\\ldots s_{r-1}s_r$, and $\\lfloor x \\rfloor$ denotes rounding the number down to the nearest integer.\n\nHelp Saruman solve this problem! It is guaranteed that under the constraints of the problem at least one solution exists.",
    "tutorial": "Let us first consider the boundary case. Let a string (hereafter we will assume that the string length $n$) consists of only ones. Then we can output the numbers $1$ $n-1$ $2$ $n$ as the answer, since there will be the same substrings. Now let's figure out what to do in the other case. Let's call the substring [$1$ ... $\\lfloor\\frac{n}{2}\\rfloor$] the left half of the string, and the substring [$\\lfloor\\frac{n}{2}\\rfloor+1$ ... $n$] the right half of the string. Then there are two cases: There is $0$ in the left half of the row, and its position is $k$. Then we can take the numbers $k$ $n$ $k+1$ $n$ as the answer, since they are the same numbers, just the second number has an extra leading zero. There is $0$ in the right half of the row, and its position is $k$. Then you can take the numbers $1$ $k$ $1$ $k-1$ as the answer, since the second number - is the first number multiplied by two (multiplying by two in binary is equivalent to adding one zero to the right). Asymptotics: $O(n)$ per test case. Think about how the problem would be solved if any other number system was chosen, given all the previous conditions (the string consists of the digits $0$ and $1$, the string contains at least one one). The solution would not change in any way. In fact, in a number system with base $k$, adding a zero to the left side does not change the number (multiplication by $1$), but adding a zero to the right side increases the number $k$ times (multiplication by $k$). Think about how the problem would be solved if the condition sounded like this: \\textit{it is necessary that $f(t)$ is divisible by $f(w)$. There are at least one one in the array. Zero is divisible by all numbers, but no number is divisible by zero. Zero is not divisible by zero.} In fact, the problem gets a little more complicated. For example, consider this test: \\t{111000000}. In this case, we could not output $4$ $9$ $5$ $9$ because zero is not divisible by zero. We will perform the old solution, but check that we are not trying to divide zero by zero (if we divide something by zero, we will swap the numbers). And if the answer is not found, then either the whole left half of the string consists of zeros, or the whole right half. Let the leftmost unit have position $p1$, and the rightmost unit ~--- position $p2$. Then in the first case you can output $1$ $p2$ $2$ $p2$, and in the second case~--- $p1$ $n$ $p1$ $n-1$. It is not hard to see that such a solution will always find the answer. In fact, we can solve the problem even simpler: when we meet zero in the left half, we additionally check whether there is at least one one among the characters on the right. If there is, we print the answer, otherwise we move on. Similarly, when we encounter zero in the right half, we additionally check if there is at least one one among the characters on the left. We can show that this solution will also always find the answer. It is interesting that we have solved \\textbf{a stronger version of the problem}, since the solution we obtained works correctly for the old problem as well.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        bool solved = false;\n        for (int i = 0; i < n; i++) {\n            if (s[i] == '0') {\n                solved = true;\n                if (i >= n / 2) {\n                    cout << 1 << \" \" << i + 1 << \" \" << 1 << \" \" << i << endl;\n                    break;\n                } else {\n                    cout << i + 2 << \" \" << n << \" \" << i + 1 << \" \" << n << endl;\n                    break;\n                }\n            }\n        }\n        if (!solved) {\n            cout << 1 << \" \" << n - 1 << \" \" << 2 << \" \" << n << endl;\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1562",
    "index": "D1",
    "title": "Two Hundred Twenty One (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.}\n\nStitch likes experimenting with different machines with his friend Sparky. Today they built another machine.\n\nThe main element of this machine are $n$ rods arranged along one straight line and numbered from $1$ to $n$ inclusive. Each of these rods must carry an electric charge quantitatively equal to either $1$ or $-1$ (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero.\n\nMore formally, the rods can be represented as an array of $n$ numbers characterizing the charge: either $1$ or $-1$. Then the condition must hold: $a_1 - a_2 + a_3 - a_4 + \\ldots = 0$, or $\\sum\\limits_{i=1}^n (-1)^{i-1} \\cdot a_i = 0$.\n\nSparky charged all $n$ rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has $q$ questions. In the $i$th question Sparky asks: if the machine consisted only of rods with numbers $l_i$ to $r_i$ inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all.\n\nIf the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods.\n\nHelp your friends and answer all of Sparky's questions!",
    "tutorial": "Let's prove everything for a particular segment of length $n$. And at the end, we'll show how to quickly solve the problem for many segments. Let $n$ - the length of the segment, and let $a$ - the array corresponding to the segment ($a_i = 1$ if \"+\" is at the $i$th position in the segment, and $a_i = -1$ if \"-\" is at the $i$th position in the segment). Introduce a new array $b$, with $b_i$ being equal to the signed sum on the whole array if the $i$-th element was removed from it. Then: The parity of the length of the segment and the parity of the number of elements to be removed from it are the same. It is not difficult to show that $|b_i - b_{i+1}| = 0$ if $a_i = a_{i+1}$, or $|b_i - b_{i+1}| = 2$ otherwise. Proof of this fact: Let $a_i = a_{i+1}$. Then it is easy to see that when $a_i$ is removed, the segment will look exactly the same as when $a_{i+1}$ is removed. So $|b_i - b_{i+1}| = 0$. Now let $a_i \\neq a_{i+1}$. Denote by $f(l,r)$ the sign-variable sum on the interval $l$ to $r$, taking into account the sign (i.e. if $l$ is odd, the first number is taken with the plus sign, otherwise with the minus sign). Then it is easy to see that $b_i = f(1,i-1) \\pm a_{i+1} \\mp f(i+2,n)$, and $b_{i+1} = f(1,i) \\mp f(i+2,n)$. Hence, if we consider the two cases ($a_{i+1} = 1$ and $a_{i+1} = -1$), we see that $|b_i - b_{i+1}| = 2$. If $n$ is odd, then there exists such $k$ that $b_k = 0$. Let us prove this: If $b_1 = 0$ or $b_n = 0$, then the statement is proved. Now let $b_1 < 0$ and $b_n > 0$. Then, since the neighboring values in the array $b$ differ by no more than $2$, and all elements are even, then there is bound to be zero between the first and last element. The case $b_1 > 0, b_n < 0$ is proved similarly. If $n > 1$, then there cannot be such a case that $b_1 > 0$ and $b_n >0$, and there cannot be such a case that $b_1 < 0$ and $b_n < 0$. In fact, let the sign-variable sum of the whole segment be $s$. Then $b_1 = -s \\pm 1$ and $b_n = s \\pm 1$. Since $b_1$ and $b_n$ are even numbers, therefore either at least one of them is zero, or they are of different signs. Thus the final result is: if the sign-variable sum is already zero, output zero; otherwise, if the segment is of odd length, output $1$; otherwise, output $2$. To quickly determine the sign-variable sum, we use the prefix-sum. Asymptotics: $O(n + q)$ per test case.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint a[1000000 + 5], p[1000000 + 5];\n\nint get_sum(int l, int r) {\n    if (l > r) {\n        return 0;\n    }\n    return (l % 2 == 1) ? p[r] - p[l - 1] : p[l - 1] - p[r];\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin>>t;\n    while (t--) {\n        int n, q;\n        cin >> n >> q;\n        string ss;\n        cin >> ss;\n        for (int i = 1; i <= n; i++) {\n            a[i] = (ss[i - 1] == '+' ? 1 : -1);\n        }\n        p[0] = 0;\n        for (int i = 1; i <= n; i++) {\n            p[i] = p[i - 1] + (i % 2 == 1 ? a[i] : -a[i]);\n        }\n        for (int o = 0; o < q; o++) {\n            int l, r;\n            cin >> l >> r;\n            if (get_sum(l, r) == 0) {\n                cout << \"0\\n\";\n                continue;\n            }\n            if ((r - l + 1) % 2 == 0) {\n                cout << \"2\\n\";\n            }\n            else {\n                cout << \"1\\n\";\n            }\n        }\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1562",
    "index": "D2",
    "title": "Two Hundred Twenty One (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that the hard version does require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.}\n\nStitch likes experimenting with different machines with his friend Sparky. Today they built another machine.\n\nThe main element of this machine are $n$ rods arranged along one straight line and numbered from $1$ to $n$ inclusive. Each of these rods must carry an electric charge quantitatively equal to either $1$ or $-1$ (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero.\n\nMore formally, the rods can be represented as an array of $n$ numbers characterizing the charge: either $1$ or $-1$. Then the condition must hold: $a_1 - a_2 + a_3 - a_4 + \\ldots = 0$, or $\\sum\\limits_{i=1}^n (-1)^{i-1} \\cdot a_i = 0$.\n\nSparky charged all $n$ rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has $q$ questions. In the $i$th question Sparky asks: if the machine consisted only of rods with numbers $l_i$ to $r_i$ inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? \\textbf{Also Sparky wants to know the numbers of these rods}. Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all.\n\nIf the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods.\n\nHelp your friends and answer all of Sparky's questions!",
    "tutorial": "We will use the facts already obtained, given in the solution of problem D1. To quickly check the value of the sign-variable sum on the segment with deletion of one element, slightly modify the prefix-sum. We will not concentrate on this in detail; you can see how to make it in the solution. Now let's see how to search for a matching element inside an odd-length segment. We will do this with a binary search. Suppose initially $l = 1$, $r = n$, and we know that the numbers $b_1$ and $b_n$ are different signs, or one of them is zero. Now consider the following algorithm: Find $m$ equal to $\\lfloor\\frac{l+r}{2}\\rfloor$. If $b_l = 0$, or $b_m = 0$, or $b_r = 0$, then the answer is found. Otherwise, either the numbers $b_l$ and $b_m$ have different signs, or the numbers $b_m$ and $b_r$ have different signs. In the first case, assign $r$ to $m$, in the second case, assign $l$ to $m$. This algorithm will stop sooner or later and produce an answer, since we know that the matching item exactly exists. This can be shown using the fact that $|b_i - b_{i+1}| \\le 2$, and all $b_i$ are even. So finally we have the following solution: if the sign-variable sum is already zero, output zero; otherwise, if the segment is of odd length, search for a suitable element by the above algorithm; otherwise, take, for example, the left boundary of the segment as the first element to remove, and search for the second element using the above algorithm on the segment without a left element. Asymptotics: $O(n + q \\cdot log(n))$ per test case. Is there a solution with asymptotics $O(n + q)$ for a single test case?",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint a[1000000 + 5], p[1000000 + 5];\n\nint get_sum(int l, int r) {\n    if (l > r) {\n        return 0;\n    }\n    return (l % 2 == 1) ? p[r] - p[l - 1] : p[l - 1] - p[r];\n}\n\nint check_elimination(int l, int r, int m) {\n    return ((m - l + 1) % 2 == 1)\n    ? get_sum(l, m - 1) + get_sum(m + 1, r)\n    : get_sum(l, m - 1) - get_sum(m + 1, r);\n}\n\nint get_sign(int m) {\n    return m > 0 ? 1 : -1;\n}\n\nint calculate_odd_segment(int l, int r) {\n    if (l == r) {\n        return l;\n    }\n    int pos = 0;\n    int lb = l;\n    int rb = r;\n    while (lb < rb) {\n        int mb = (lb + rb) / 2;\n        int lq = check_elimination(l,r,lb);\n        int mq = check_elimination(l,r,mb);\n        int rq = check_elimination(l,r,rb);\n        if (lq == 0) {\n            pos = lb;\n            break;\n        }\n        if (mq == 0) {\n            pos = mb;\n            break;\n        }\n        if (rq == 0) {\n            pos = rb;\n            break;\n        }\n        if (get_sign(lq) == get_sign(mq)) {\n            lb = mb;\n        } else {\n            rb = mb;\n        }\n    }\n    return pos;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin>>t;\n    while (t--) {\n        int n, q;\n        cin >> n >> q;\n        string ss;\n        cin >> ss;\n        for (int i = 1; i <= n; i++) {\n            a[i] = (ss[i - 1] == '+' ? 1 : -1);\n        }\n        p[0] = 0;\n        for (int i = 1; i <= n; i++) {\n            p[i] = p[i - 1] + (i % 2 == 1 ? a[i] : -a[i]);\n        }\n        for (int o = 0; o < q; o++) {\n            int l, r;\n            cin >> l >> r;\n            if (get_sum(l, r) == 0) {\n                cout << \"0\\n\";\n                continue;\n            }\n            bool even = false;\n            if ((r - l + 1) % 2 == 0) {\n                even = true;\n                l++;\n            }\n            int pos = calculate_odd_segment(l, r);\n            if (even) {\n                cout << \"2\\n\" << l - 1 << \" \"<< pos << '\\n';\n            } else {\n                cout << \"1\\n\" << pos << '\\n';\n            }\n        }\n    }\n}",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1562",
    "index": "E",
    "title": "Rescue Niwen!",
    "statement": "\\begin{quote}\n{{\\small Morning desert sun horizonRise above the sands of time...}}\n\\hfill {\\small Fates Warning, \"Exodus\"}\n\\end{quote}\n\nAfter crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light did not want to open!\n\nOri was taken aback, but the Voice of the Forest explained to him that the cunning Gorleks had decided to add protection to the repository.\n\nThe Gorleks were very fond of the \"string expansion\" operation. They were also very fond of increasing subsequences.\n\nSuppose a string $s_1s_2s_3 \\ldots s_n$ is given. Then its \"expansion\" is defined as the sequence of strings $s_1$, $s_1 s_2$, ..., $s_1 s_2 \\ldots s_n$, $s_2$, $s_2 s_3$, ..., $s_2 s_3 \\ldots s_n$, $s_3$, $s_3 s_4$, ..., $s_{n-1} s_n$, $s_n$. For example, the \"expansion\" the string 'abcd' will be the following sequence of strings: 'a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'.\n\nTo open the ancient repository, Ori must find the size of the largest increasing subsequence of the \"expansion\" of the string $s$. Here, strings are compared lexicographically.\n\nHelp Ori with this task!\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "The constraints on the problem were chosen so that solutions slower than $O(n^2 \\cdot log(n))$ would not get AC, or would get with difficulty. The solution could be, for example, to sort all substrings by assigning numbers to them, and then find the largest increasing subsequence in the resulting array. Let us describe the solution for $O(n^2)$. The most important thing required for the solution is to understand what the largest increasing subsequence should look like. Let $s$ - a string, and $n$ - the length of the string $s$. It can be shown that if the largest increasing subsequence has a substring [$l$ ... $r$], then it also has a substring [$l$ ... $n$]. I will not give a formal proof, I will only give the key idea. Let the increasing subsequence first have the string [$l_1$ ... $r_1$], and then the substring [$l_2$ ... $r_2$], with $r_1 \\neq n$. It can be understood that if suffixes [$l_1$ ... $n$] and [$l_2$ ... $n$] have some common prefix, and it has already been included in the largest increasing subsequence, then we can <<drop>> the prefixes of the suffix [$l_1$ . . $n$], and instead of them write exactly the same suffix prefixes of [$l_2$ ... $n$], and the size of the increasing subsequence will not change, and the condition above will be satisfied. If, however, the suffixes [$l_1$ ... $n$] and [$l_2$ ... $n$] have no common prefix, then we could take the suffix itself [$l_2$ ... $n$] together with its prefixes, and the answer would only improve. Thus, the largest increasing subsequence looks like this: first comes some substring [$l_1$ ... $r_1$], followed by a substring [$l_1$ ... $r_1 + 1$], and so on, ending with the suffix [$l_1$ ... $n$]. After that comes some substring [$l_2$ ... $r_2$], followed by a substring [$l_2$ ... $r_2 + 1$], and so on, ending with the suffix [$l_2$ ... $n$], and so on. Moreover, knowing which suffixes are included in this subsequence, we can establish all other substrings. Indeed, let the suffixes [$l_1$ ... $n$] and [$l_2$ ... $n$] be included in the sequence, and $l_1$ < $l_2$. Then it is not difficult to see that the suffix prefixes [$l_2$ ... $n$] can be typed greedily, namely, to take all substring [$l_2$ ... $k$] such that they are larger than the suffix [$l_1$ ... $n$]. Note that if the substring [$l_2$ ... $m$] is larger than the suffix [$l_1$ ... $n$], then the substring [$l_2$ ... $m+1$] is also larger than the suffix [$l_1$ ... $n$]. And so, we can use the following algorithm to find out $r_2$, that is, to find out which suffix prefix [$l_2$ ... $n$] to start typing the subsequence. Let $d_{l_1,l_2}$ - be the size of the largest common prefix of suffixes [$l_1$ ... $n$] and [$l_2$ ... $n$]. Then it is easy to see that if the suffix [$l_2$ ... $n$] is larger than the suffix [$l_1$ ... $n$], then the appropriate $r_2$ is $d_{l_1,l_2} + l_2$, which means that you must start typing all substrings, starting from the one that differs from the largest common prefix of the two suffixes. So now we are left with two problems. The first is - you have to learn to quickly recognize the greatest common prefix of the two suffixes. The second is - to write a DP that would allow you to recognize the answer. Let's see how to solve the first problem. You can use different string algorties, such as a suffix array. Or we can write a simple DP that calculates an array $d$ of the largest common prefixes over $O(n^2)$. The transitions in this DP and its implementation can be seen in the author's solution code (lines 37-48). Now about the DP that calculates the answer. Let us use the facts above and do the following. Let $dp_i$ denote the size of the answer if the last substring in it is the suffix [$i$ ... $n$]. Let $dp_1 = n$, and then $dp_i = n - i + 1$. Now let's do the following. We will go through $i$ from $2$ to $n$, doing the following simple steps: for each $j$ from $1$ to $i-1$ ($j$ denotes the previous suffix in the answer) we will check how many substring of the suffix [$i$ ... $n$] we can take: if the suffix [$i$ ... $n$] is larger than the suffix [$j$ ... $n$], we calculate this number with the above described algorithm, using the $d$ array of largest common prefixes. Otherwise, we will not update, because the suffix [$i$ ... $n$] is less than or equal to the suffix [$j$ ... $n$], we cannot take it in response. It is not difficult to guess that the answer is maximal in all $dp_i$. Thus, the problem is solved using two uncomplicated dynamics. Asymptotics: $O(n^2)$ per test case. As far as I know, using trie, you can sort all substrings of a given string in $O(n^2)$. Also, as far as I know, in C++ programming language std::lower_bound works so fast that in an array of size $1.25 \\cdot 10^7$ the same number of std::lower_bound operations is done in a little less than a second. It is also known that std::lower_bound can be used to write a search for the largest increasing subsequence in an array. The question is: can we use this to write a $O(n^2 \\cdot log(n))$ solution that passes the tests?",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint16_t lcp[10000 + 5][10000 + 5];\n\nint dp[10000 + 5];\n\nbool is_greater(const string& s, int x, int y) {\n    if (lcp[x][y] == static_cast<int>(s.size()) - x) {\n        return false;\n    }\n    return s[x + lcp[x][y]] > s[y + lcp[x][y]];\n}\n\nint get_score(const string& s, int x, int y) {\n    if (is_greater(s, x, y)) {\n        return dp[y] + static_cast<int>(s.size()) - x - lcp[x][y];\n    }\n    return 0;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        if (s.size() != n) return 42;\n        for (int i = 0; i <= n; i++) {\n            for (int j = 0; j <= n; j++) {\n                lcp[i][j] = 0;\n            }\n        }\n        for (int i = n - 1; i >= 0; i--) {\n            for (int j = n - 1; j >= 0; j--) {\n                if (i == j) {\n                    lcp[i][j] = n - i;\n                } else\n                if (s[i] != s[j]) {\n                    lcp[i][j] = 0;\n                } else {\n                    lcp[i][j] = lcp[i + 1][j + 1] + 1;\n                }\n            }\n        }\n        int ans = n;\n        dp[0] = n;\n        for (int i = 1; i < n; i++) {\n            dp[i] = n - i;\n            for (int j = 0; j < i; j++) {\n                dp[i] = max (dp[i], get_score(s, i, j));\n            }\n            ans = max(ans, dp[i]);\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "string suffix structures",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1562",
    "index": "F",
    "title": "Tubular Bells",
    "statement": "Do you know what tubular bells are? They are a musical instrument made up of cylindrical metal tubes. In an orchestra, tubular bells are used to mimic the ringing of bells.\n\nMike has tubular bells, too! They consist of $n$ tubes, and each of the tubes has a length that can be expressed by a integer from $l$ to $r$ inclusive. It is clear that the lengths of all the tubes are different (it makes no sense to make the same tubes). It is also known that $r-l+1 = n$.\n\nFormally, we can say that Mike's tubular bells are described by a permutation $a$ of length $n$ that contains all numbers from $l$ to $r$ inclusive, with $a_i$ denoting the length of the $i$-th tube.\n\nYou are offered an interesting task: to guess what Mike's instrument looks like. Simply, you must guess the permutation.\n\nMike won't tell you $l$ or $r$. He will only tell you $n$, and will allow you to ask no more than $n + 5000$ queries.\n\nIn each query, you name two positive integers $x$, $y$ such that $1 \\le x, y \\le n, x \\neq y$. In response to this query, the program written by Mike will give you $\\mathrm{lcm}(a_x, a_y)$, where $\\mathrm{lcm}(c,d)$ denotes the least common multiple of $c$ and $d$.\n\nSolve Mike's problem!",
    "tutorial": "As I know, there are simpler solutions to this problem, but I will describe my solution. We can assume the whole array is randomly permutated, because we can make queries by renumbering it. We also pre-calculate all prime numbers smaller than $200000$. Let us denote something: $n$ - the number of numbers in the array, $a$ - the array itself, $l$ - the smallest value in the array, $r$ - the largest value in the array. So let's look at three cases: $n < 100$. We use the following simple solution: find out the lcm of all pairs of numbers. The greatest of these values will give us the pair of numbers $r-1$ and $r$. It is easy to find out which number $r$ is: all pairs of lcms of this number with others will be divisible by $r$. Now exclude $r$ from the array, and exclude all pairwise lcms with it. The highest value will give us a pair $r-1$ and $r-2$. Repeat this algorithm until all numbers are found. $100 \\le n < 10000$. Solve for $\\lceil\\frac{3n}{2}\\rceil$ queries. We ask for lcms of pairs of numbers: the first with the second, the third with the fourth, etc. Now we will look for the maximal prime multiplier in each such lcm. We will do it by using pre-calculated prime numbers. Since the array is randomly permutated, this will work in a reasonable amount of time. When we will find a pair of numbers with the greatest prime number, we easily find out which of these two numbers is the greatest prime: ask the lcm of one of the numbers in the pair with any other number and check if that lcm contains that greatest prime number. Finding the largest prime number, we easily find out the remaining array: $a_i = lcm(a_i, p) / p$, where $p$ -that prime number. $10000 \\le n \\le 100000$. Let $c$ = $500$. This number is chosen so that $c^2 > 200000$. We will search the array for any prime number that is greater than $c$. Do the following: randomly ask pairs of numbers until we find one that has only two prime numbers in the factorization of the lcm, and both of these prime numbers are greater than $c$. Let it be $p_1$ and $p_2$. Then one of the numbers in the pair - $p_1$ and the other - $p_2$. To find out which number is which, let's ask the lcm of one of them with some numbers chosen at random, and check what all those lcms are divisible by. If they are all divisible by $p_1$, then the chosen number is $p_1$, otherwise it is $p_2$. The chance of us guessing wrong is extremely small, because it requires that all the chosen numbers are divisible by $p_2$, and the chance of that is negligible.We have found a prime number greater than $c$. Let it be $p$. Now we can find out all the numbers that are not divisible by $p$ and greater than $c$. To do this, we ask all the NOCs of the number $p$ and the other numbers. And now, if $lcm(p, a_i) / p > c$, then $a_i = lcm(p, a_i) / p$. This is because if $a_i$ is divisible by $p$, then $lcm(p, a_i) / p = a_i / p \\le c$. If $a_i$ is not divisible by $p$, then by dividing the lcm by $p$ we will find $a_i$, since the number $p$ is prime. Find the largest prime among the found numbers, and use it to find the remaining numbers as described above. Since we only need to find all numbers divisible by $p$ and all numbers not exceeding $c$, such queries will be no more than $100000 / 500 + 500 = 700$. We have found a prime number greater than $c$. Let it be $p$. Now we can find out all the numbers that are not divisible by $p$ and greater than $c$. To do this, we ask all the NOCs of the number $p$ and the other numbers. And now, if $lcm(p, a_i) / p > c$, then $a_i = lcm(p, a_i) / p$. This is because if $a_i$ is divisible by $p$, then $lcm(p, a_i) / p = a_i / p \\le c$. If $a_i$ is not divisible by $p$, then by dividing the lcm by $p$ we will find $a_i$, since the number $p$ is prime. Find the largest prime among the found numbers, and use it to find the remaining numbers as described above. Since we only need to find all numbers divisible by $p$ and all numbers not exceeding $c$, such queries will be no more than $100000 / 500 + 500 = 700$.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <ctime>\n#include <random>\n\nusing namespace std;\n\n#define int long long\n\nmt19937 rnd(time(NULL));\n\nint swnmb[1000000+5];\n\nint swnmbr[1000000+5];\n\nint b[1000000+5];\n\nbool p[1000000+5];\n\nvector<int> primes;\n\nint get_lcm(int x, int y)\n{\n    cout<<\"? \"<<swnmb[x]<<\" \"<<swnmb[y]<<endl;\n    int u;\n    cin>>u;\n    return u;\n}\n\nint max_fact(int d)\n{\n    for (int j=(int)primes.size()-1; j>=0; j--)\n    {\n        if (d%primes[j]==0) return primes[j];\n    }\n}\n\nvector<int> fact(int d)\n{\n    vector<int> ans;\n    for (auto j:primes)\n    {\n        if (d==1) break;\n        while (d%j==0)\n        {\n            ans.push_back(j);\n            d/=j;\n        }\n    }\n    return ans;\n}\n\nbool is_prime(int d)\n{\n    for (int j=0; j<(int)primes.size(); j++)\n    {\n        if (primes[j]>500) return true;\n        if (d%primes[j]==0) return false;\n    }\n    return true;\n}\n\nint paired_get_lcm[100+5][100+5];\n\nvoid solve_quadric(int n)\n{\n    for (int i=1; i<=n; i++) {\n        for (int j=i+1; j<=n; j++) {\n            paired_get_lcm[i][j]=get_lcm(i,j);\n            paired_get_lcm[j][i]=paired_get_lcm[i][j];\n        }\n    }\n    int m1=0;\n    int m2=0;\n    int mx=0;\n    for (int i=1; i<=n; i++) {\n        for (int j=i+1; j<=n; j++) {\n            if (paired_get_lcm[i][j]>mx)\n            {\n                mx=paired_get_lcm[i][j];\n                m1=i;\n                m2=j;\n            }\n        }\n    }\n    int u=0;\n    for (int i=1; i<=200000; i++)\n    {\n        if (mx==i*(i+1))\n        {\n            u=i+1;\n            break;\n        }\n    }\n    for (int i=1; i<=n; i++)\n    {\n        if (i==m1||i==m2) continue;\n        if (paired_get_lcm[m1][i]%u!=0)\n        {\n            swap(m1,m2);\n            break;\n        }\n    }\n    b[m1]=u;\n    int pos=m2;\n    for (int v=u-1; v>u-n-1; v--)\n    {\n        int m0=0;\n        int mx=0;\n        for (int j=1; j<=n; j++) {\n            if (b[j]!=0) continue;\n            if (pos==j) continue;\n            if (paired_get_lcm[pos][j]>mx)\n            {\n                mx=paired_get_lcm[pos][j];\n                m0=j;\n            }\n        }\n        b[pos]=v;\n        pos=m0;\n    }\n    b[pos]=u-n+1;\n}\n\nvoid solve_pair(int n)\n{\n    int maxnum=0;\n    int maxpos=0;\n    int notmaxpos=0;\n    for (int i=1; i<=n; i+=2)\n    {\n        int u;\n        if (i!=n) u=get_lcm(i,i+1);\n        else u=get_lcm(i-1,i);\n        int w=max_fact(u);\n        if (w>maxnum)\n        {\n            maxnum=w;\n            maxpos=min(i+1,n);\n        } else {\n            notmaxpos=i;\n        }\n    }\n    int cur=get_lcm(notmaxpos,maxpos);\n    if (cur%maxnum!=0) {\n        maxpos--;\n    }\n    b[maxpos]=maxnum;\n    for (int i=1; i<=n; i++)\n    {\n        if (i==maxpos) continue;\n        int u=get_lcm(i,maxpos)/maxnum;\n        b[i]=u;\n    }\n}\n\nvoid print_ans(int n)\n{\n    cout<<\"! \";\n    for (int i=1; i<=n; i++) {\n        cout<<b[swnmbr[i]];\n        if (i!=n) cout<<\" \";\n    }\n    cout<<endl;\n}\n\nint32_t main()\n{\n    for (int i=2; i<=200000; i++)\n    {\n        if (p[i]) continue;\n        for (int j=i*i; j<=200000; j+=i)\n        {\n            p[j]=true;\n        }\n        primes.push_back(i);\n    }\n    int t;\n    cin>>t;\n    while (t--)\n    {\n        int n;\n        cin>>n;\n        for (int i=1; i<=n; i++) {\n            swnmb[i]=0;\n            swnmbr[i]=0;\n            b[i]=0;\n        }\n        for (int i=1; i<=n; i++) {\n            swnmb[i]=i;\n        }\n        for (int i=1; i<=n*5; i++) {\n            swap(swnmb[rnd()%n+1], swnmb[rnd()%n+1]);\n        }\n        for (int i=1; i<=n; i++) {\n            swnmbr[swnmb[i]]=i;\n        }\n        if (n<100) {\n            solve_quadric(n);\n            print_ans(n);\n            continue;\n        }\n        if (n<10000) {\n            solve_pair(n);\n            print_ans(n);\n            continue;\n        }\n        int t1=0;\n        int t2=0;\n        int pos1=0;\n        int pos2=0;\n        for (int i=1; i<=4000; i++)\n        {\n            int i1=rnd()%n+1;\n            int i2=rnd()%n+1;\n            while (i1 == i2) {\n                i2=rnd()%n+1;\n            }\n            vector<int> f=fact(get_lcm(i1,i2));\n            if (f.size()==2&&f[0]>500&&f[1]>500)\n            {\n                bool first1=true;\n                bool first2=true;\n                for (int j=0; j<100; j++)\n                {\n                    int t=rnd()%n+1;\n                    while (t==i1||t==i2)\n                    {\n                        t=rnd()%n+1;\n                    }\n                    if (get_lcm(i1,t)%f[0]!=0)\n                    {\n                        first1=false;\n                        break;\n                    }\n                }\n                for (int j=0; j<100; j++)\n                {\n                    int t=rnd()%n+1;\n                    while (t==i1||t==i2)\n                    {\n                        t=rnd()%n+1;\n                    }\n                    if (get_lcm(i1,t)%f[1]!=0)\n                    {\n                        first2=false;\n                        break;\n                    }\n                }\n                if (first1&&first2)\n                {\n                    bool second1=true;\n                    for (int j=0; j<100; j++)\n                    {\n                        int t=rnd()%n+1;\n                        while (t==i1||t==i2)\n                        {\n                            t=rnd()%n+1;\n                        }\n                        if (get_lcm(i2,t)%f[1]!=0)\n                        {\n                            second1=false;\n                            break;\n                        }\n                    }\n                    if (second1)\n                    {\n                        t2=f[0]*f[1];\n                        t1=f[0];\n                    }\n                    else\n                    {\n                        t2=f[0]*f[1];\n                        t1=f[1];\n                    }\n                    pos1=i2;\n                    pos2=i1;\n                }\n                else\n                {\n                    if (!first1)\n                    {\n                        t1=f[1];\n                        t2=f[0];\n                    }\n                    else\n                    {\n                        t1=f[0];\n                        t2=f[1];\n                    }\n                    pos1=i1;\n                    pos2=i2;\n                }\n                b[pos1]=t1;\n                b[pos2]=t2;\n                int posf=0;\n                int maxf=0;\n                for (int j=1; j<=n; j++)\n                {\n                    if (j==i1||j==i2) continue;\n                    int u=get_lcm(pos1,j);\n                    if (u/t1>500)\n                    {\n                        b[j]=u/t1;\n                        if (is_prime(b[j]))\n                        {\n                            if (b[j]>maxf)\n                            {\n                                maxf=b[j];\n                                posf=j;\n                            }\n                        }\n                    }\n                }\n                for (int j=1; j<=n; j++)\n                {\n                    if (b[j]!=0) continue;\n                    b[j]=get_lcm(posf,j)/b[posf];\n                }\n                break;\n            }\n        }\n        print_ans(n);\n    }\n}",
    "tags": [
      "interactive",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1566",
    "index": "A",
    "title": "Median Maximization",
    "statement": "You are given two positive integers $n$ and $s$. Find the maximum possible median of an array of $n$ \\textbf{non-negative} integers (not necessarily distinct), such that the sum of its elements is equal to $s$.\n\nA \\textbf{median} of an array of integers of length $m$ is the number standing on the $\\lceil {\\frac{m}{2}} \\rceil$-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from $1$. For example, a median of the array $[20,40,20,50,50,30]$ is the $\\lceil \\frac{m}{2} \\rceil$-th element of $[20,20,30,40,50,50]$, so it is $30$. There exist other definitions of the median, but in this problem we use the described definition.",
    "tutorial": "Which numbers smaller than the median should be taken? Which numbers bigger than the median should be taken? Greedy algorithm. Let's consider the array of $n$ elements in non-decreasing order. We can make numbers before the median equal to zero, after that we have $m = \\lfloor {\\frac{n}{2}} \\rfloor + 1$ numbers, which sum should be $n$ and the minimal of them (i.e. median value) should be maximized. To do so, it is enough to make all these numbers equal $\\lfloor {\\frac{s}{m}} \\rfloor$, and then add what's left to the last number ($s \\bmod m$). It's easy to see that such array matches all the conditions and it is impossible to make median greater. If it's possible to make the median element $m > 1$ then you can make it $m - 1$. It is possible to make the median element any number from $0$ to some $M$. We can use the binary search for the answer. Let's run a binary search for the answer. This will work because if the answer $M$ then we can decrease the median element by $d$ and add $d$ to the max element, so we can get any median element from $1$ to $M$, but we can't get more than $M$. In the binary search we will use the greedy technique. All numbers less than the median can be $0$ and all numbers from the median should be at least $M$. So there are $m = \\lfloor {\\frac{n}{2}} \\rfloor + 1$ numbers and each of them should be at least $M$ and we find the $M$ using the binary search. Number $M$ is reachable if $M \\cdot m \\leq s$ because we can add $s - M \\cdot m$ to the maximal number and the median will be $M$. Otherwise, the median element can not be $M$.",
    "code": "t = int(input())\nfor test in range(t):\n    n, s = map(int, input().split())\n    L = 0\n    R = 10**10\n    while R - L > 1:\n        M = (L + R) // 2\n        m = n // 2 + 1\n        if m * M <= s:\n            L = M\n        else:\n            R = M\n    print(L)\n",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1566",
    "index": "B",
    "title": "MIN-MEX Cut",
    "statement": "A binary string is a string that consists of characters $0$ and $1$.\n\nLet $\\operatorname{MEX}$ of a binary string be the smallest digit among $0$, $1$, or $2$ that does not occur in the string. For example, $\\operatorname{MEX}$ of $001011$ is $2$, because $0$ and $1$ occur in the string at least once, $\\operatorname{MEX}$ of $1111$ is $0$, because $0$ and $2$ do not occur in the string and $0 < 2$.\n\nA binary string $s$ is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nWhat is the \\textbf{minimal} sum of $\\operatorname{MEX}$ of all substrings pieces can be?",
    "tutorial": "The answer is never greater than $2$. If a string consists only of $1$, then the answer is $0$. If all zeroes are consequent, then the answer is $1$. The answer is never greater than $2$, because $\\text{MEX}$ of the whole string is not greater than $2$. The answer is $0$ only if there are no zeroes in the string. Now we need to understand, when the answer is $1$ or when it is $2$. The sum of $\\text{MEX}$ is $1$ only if all zeroes create a single segment without ones. Then we can cut this segment out, its $\\text{MEX}$ is $1$, everything else is ones, their total $\\text{MEX}$ is $0$. If the zeroes do not create a single segment without ones, the there are two such zeroes that there is a $1$ between them. Then either these zeroes are in a single segment with the $1$, so total $\\text{MEX}$ is not less than $2$ or these zeroes are in different segments and the answer is still not less then $2$.",
    "code": "t = int(input())\nfor test in range(t):\n    s = input()\n    zeroes = s.count('0')\n    if zeroes == 0:\n        print(0)\n        continue\n\n    first = s.find('0')\n    last = s.rfind('0')\n    if last - first + 1 == zeroes:\n        print(1)\n    else:\n        print(2)\n",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1566",
    "index": "C",
    "title": "MAX-MEX Cut",
    "statement": "A binary string is a string that consists of characters $0$ and $1$. A bi-table is a table that has exactly two rows of equal length, each being a binary string.\n\nLet $\\operatorname{MEX}$ of a bi-table be the smallest digit among $0$, $1$, or $2$ that does not occur in the bi-table. For example, $\\operatorname{MEX}$ for $\\begin{bmatrix} 0011\\\\ 1010 \\end{bmatrix}$ is $2$, because $0$ and $1$ occur in the bi-table at least once. $\\operatorname{MEX}$ for $\\begin{bmatrix} 111\\\\ 111 \\end{bmatrix}$ is $0$, because $0$ and $2$ do not occur in the bi-table, and $0 < 2$.\n\nYou are given a bi-table with $n$ columns. You should cut it into any number of bi-tables (each consisting of consecutive columns) so that each column is in exactly one bi-table. It is possible to cut the bi-table into a single bi-table — the whole bi-table.\n\nWhat is the \\textbf{maximal} sum of $\\operatorname{MEX}$ of all resulting bi-tables can be?",
    "tutorial": "You can cut out the columns with both $0$ and $1$. Now in each column there are only $0$ or only $1$. We only need to solve the problem for a string because the columns can be replaced by one digit (they consist of equal elements). Let's be greedy, to each zero we will \"join\" not more than one $1$. Let's solve the same problem but for a string: It's needed to cut a binary string into segments so that each its element is in exactly one segment and the sum of $\\text{MEX}$ for all segments is maximal. Initially we will say that the string is cut into segments of length 1. Then the answer is the number of zeroes in the string. After that the answer is increased every time we merge a segment of $0$ with a segment of $1$. Each such merge increases the answer by $1$. Let's make the merges greedily, maximizing the number of merges. Let's consider the first zero. If the previous element is a $1$, let's merge them and consider the next zero. Else, if the next element is a $1$, let's merge them and consider the next zero. Else, the next element is a zero and we should consider it instead of the current zero the same way. By doing so we get the answer as the number of zeroes + the number of merges. Now let's solve the initial problem. We can cut out the columns that contain both $0$ and $1$, because their $\\text{MEX}$ is already maximized and the answer will not become worse. Now we solve the problem for all remaining bi-tables independently. Each their column consists either only of $0$ or only of $1$ so both rows are equal. We will solve the problem for one row of each remaining bi-table as mentioned before and then sum up the values to get the answer. This problem could be solved in many ways using the dp. We will consider these solutions in short. Let's say that $dp_i$ - is the answer for a prefix until $i$. Then there are different approaches: We can calculate the dp values, iterating through all possible $\\operatorname{MEX}$ values on the last segment. For example, if we want to make $\\operatorname{MEX}$ equal $2$ on the last segment, then we need to find the closest $0$ and the closest $1$ to position $i$. Let it be $last_0$ and $last_1$. Then we should recalc the dp like this $dp_i = \\max(dp_i, dp_{j-1} + 2)$, where $j = \\min(last_0, last_1)$, because we take the shortest segment ending in $i$ which has both $0$ and $1$ and after that we add the answer for this segment and for prefix that ends in $j-1$. Another possible solution with dp is based on the fact that we should not take any segments with length more than $x$, where $x$ is some small number. We can just take some random big enough $x$ and not prove anything. There exists a solution which does not consider segments with length bigger than $5$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint mex(string s){\n  int fl=0;\n  for(auto &nx : s){\n    if(nx=='0'){fl|=1;}\n    else if(nx=='1'){fl|=2;}\n  }\n  if(fl==3){return 2;}\n  if(fl==1){return 1;}\n  return 0;\n}\n \nint main(){\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int t;\n  cin >> t;\n  while(t>0){\n    t--;\n    int n;\n    string s1,s2;\n    cin >> n >> s1 >> s2;\n    vector<int> dp(n+1,0);\n    for(int i=0;i<n;i++){\n      string s;\n      for(int j=0;j<5;j++){\n        if(i+j>=n){break;}\n        s.push_back(s1[i+j]);\n        s.push_back(s2[i+j]);\n        dp[i+j+1]=max(dp[i+j+1],dp[i]+mex(s));\n      }\n    }\n    cout << dp[n] << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1566",
    "index": "D2",
    "title": "Seating Arrangements (hard version) ",
    "statement": "\\textbf{It is the hard version of the problem. The only difference is that in this version $1 \\le n \\le 300$.}\n\nIn the cinema seats can be represented as the table with $n$ rows and $m$ columns. The rows are numbered with integers from $1$ to $n$. The seats in each row are numbered with consecutive integers from left to right: in the $k$-th row from $m (k - 1) + 1$ to $m k$ for all rows $1 \\le k \\le n$.\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||c||c|}\n\\hline\n$1$ & $2$ & $\\cdots$ & $m - 1$ & $m$ \\\n\\hline\n\\hline\n$m + 1$ & $m + 2$ & $\\cdots$ & $2 m - 1$ & $2 m$ \\\n\\hline\n\\hline\n$2m + 1$ & $2m + 2$ & $\\cdots$ & $3 m - 1$ & $3 m$ \\\n\\hline\n\\hline\n$\\vdots$ & $\\vdots$ & $\\ddots$ & $\\vdots$ & $\\vdots$ \\\n\\hline\n\\hline\n$m (n - 1) + 1$ & $m (n - 1) + 2$ & $\\cdots$ & $n m - 1$ & $n m$ \\\n\\hline\n\\end{tabular}\n\n{\\small The table with seats indices}\n\\end{center}\n\nThere are $nm$ people who want to go to the cinema to watch a new film. They are numbered with integers from $1$ to $nm$. You should give exactly one seat to each person.\n\nIt is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $i$-th person has the level of sight $a_i$. Let's define $s_i$ as the seat index, that will be given to $i$-th person. You want to give better places for people with lower sight levels, so for any two people $i$, $j$ such that $a_i < a_j$ it should be satisfied that $s_i < s_j$.\n\nAfter you will give seats to all people they will start coming to their seats. In the order from $1$ to $nm$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The \\textbf{inconvenience} of the person is equal to the number of occupied seats he or she will go through.\n\nLet's consider an example: $m = 5$, the person has the seat $4$ in the first row, the seats $1$, $3$, $5$ in the first row are already occupied, the seats $2$ and $4$ are free. The inconvenience of this person will be $2$, because he will go through occupied seats $1$ and $3$.\n\nFind the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).",
    "tutorial": "Each person can be seated on some subsegment of places with people with the same level of sight. If $n=1$ we should seat people on the maximal possible place. The places available for some person may be a subsegment of a row or a suffix of a row + some full rows + a prefix of a row. Let's consider all seats in increasing order of their indices. For each seat we can consider the level of sight of a person that takes that seat. The considered sequence is non-decreasing. This means that people with the same level of sight should take consequent seats and for each level of sight $x$ we can determine which seats will be taken by people with level of sight $x$. Now we should find out how do people with level of sight $x$ sit in the cinema. For that $x$ we know that people with that level of sight should take places with indices from $l$ to $r$. Let's seat people with the same level of sight greedily. If all places from $l$ to $r$ are in the same row, then we should seat people in decreasing order of seat indices. Otherwise, these seats form a suffix of some row (maybe empty), some full rows (maybe zero), a prefix of some row (maybe empty). Firstly we need to seat people on the suffix in decreasing order of seat indices. This is not worse than other seatings, because the seats before that suffix may be taken in future and total inconvenience will increase. Seats on the prefix should be taken last of all in decreasing order of seat indices. This is not worse than other seatings, because if some people sit on that prefix then they will bother people on the right, increasing the total inconvenience. Full rows should be taken in decreasing order of seat indices, this does not increase the total inconvenience at all. So we should start by seating poeple on the suffix, then we should cover full rows and finally we should cover the prefix. In each case places should be taken in decreasing order of seat indices. The constraints for $m$ are low, so each time we want to seat someone we can consider all places in the row and find how many people increase our inconvenience.",
    "code": "#include <bits/stdc++.h>\n#define long long long int\nusing namespace std;\n \n// @author: pashka\n \nvoid solve_test() {\n    int n, m;\n    cin >> n >> m;\n    vector<pair<int, int>> a(n * m);\n    for (int i = 0; i < n * m; i++) {\n        cin >> a[i].first;\n        a[i].second = i;\n    }\n    sort(a.begin(), a.end());\n    for (int i = 0; i < n * m; i++) {\n        a[i].second = -a[i].second;\n    }\n    int res = 0;\n    for (int i = 0; i < n; i++) {\n        sort(a.begin() + (m * i), a.begin() + (m * i + m));\n        for (int j = 0; j < m; j++) {\n            for (int k = 0; k < j; k++) {\n                if (a[i * m + k].second > a[i * m + j].second) res++;\n            }\n        }\n    }\n    cout <<res << \"\\n\";\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n \n    int n;\n    cin >> n;\n    for (int i = 0; i < n; i++) {\n        solve_test();\n    }\n \n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1566",
    "index": "E",
    "title": "Buds Re-hanging",
    "statement": "A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $v$ (different from root) is the previous to $v$ vertex on the shortest path from the root to the vertex $v$. Children of the vertex $v$ are all vertices for which $v$ is the parent.\n\nA vertex is a leaf if it has no children. We call a vertex a \\textbf{bud}, if the following three conditions are satisfied:\n\n- it is not a root,\n- it has at least one child, and\n- all its children are leaves.\n\nYou are given a rooted tree with $n$ vertices. The vertex $1$ is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.\n\nWhat is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?",
    "tutorial": "Re-hanging a bud to a leaf decreases the total amount of leaves by $1$. Buds can be re-hanged that way so in the end there is only a root, buds that are connected to the root and leaves connected to the root or to the buds. Now the answer depends only on the total amount of vertices, on the amount of buds and on the fact whether there is a leaf connected to the root or not. If we re-hang a bud from its parent to the root, the amount of leaves either doesn't change (if the parent has other children), or increases by $1$. By doing that we don't make the answer worse, because if there are leaves except for bud's leaves, then we can re-hang the bud to some leaf, decreasing the amount of leaves by $1$. So let's re-hang all buds to the root, until there are no free buds left. Now we will assume that all buds are hung to the root, and their amount is $k$. The answer is either $n - 2 \\cdot k$ if there is no leaf, hung to the root, or $n - 2 \\cdot k - 1$ if there is a leaf, hung to the root. Why is it so? Initially, there are $n - k - 1$ leaves (total amount of nodes - the amount of buds - root). If there is a leaf, hung to the root, then we can hang a bud to it, then hang a bud to the previous bud's leaf, and keep doing so until we use all $k$ buds. Then there are $k$ re-hangs, each of them decreases the answer by $1$. So the final answer is $n - k - 1 - k = n - 2 \\cdot k - 1$. If there is no leaves hung to the root, then we can hang a bud to another bud's leaf, then a bud to the previous bud's leaf, and so on until we use $k - 1$ buds. The final answer in this case is $n - k - 1 - (k - 1) = n - 2 \\cdot k$. It is not possible to make the answer less, because each re-hang decreases the answer by \\le 1 and each re-hang we make decreases it exactly by 1 and we use all re-hangs.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<vector<int>> g;\nvector<int> type; // -1  -- default, 0 -- root, 1 -- leaf, 2 -- bud\n\nvoid dfs(int v, int p) {\n    bool leaves = false;\n    for (auto to : g[v]) {\n        if (to == p) continue;\n        dfs(to, v);\n        if (type[to] == 1) leaves = true;\n    }\n    if (v != p) {\n        if (!leaves) type[v] = 1;\n        else type[v] = 2;\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cout.tie(0);\n    cin.tie(0);\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n;\n        cin >> n;\n        g.assign(n, vector<int>());\n        type.assign(n, -1);\n        for (int i = 0; i < n - 1; ++i) {\n            int x, y;\n            cin >> x >> y;\n            --x; --y;\n            g[x].emplace_back(y);\n            g[y].emplace_back(x);\n        }\n        type[0] = 0;\n        dfs(0, 0);\n        bool root_leaf = false;\n        for (auto v : g[0]) {\n            if (type[v] == 1) {\n                root_leaf = true;\n            }\n        }\n        int k = 0;\n        for (int i = 0; i < n; ++i) {\n            k += (type[i] == 2);\n        }\n        cout << n - 2 * k - root_leaf << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1566",
    "index": "F",
    "title": "Points Movement",
    "statement": "There are $n$ points and $m$ segments on the coordinate line. The initial coordinate of the $i$-th point is $a_i$. The endpoints of the $j$-th segment are $l_j$ and $r_j$ — left and right endpoints, respectively.\n\nYou can move the points. In one move you can move any point from its current coordinate $x$ to the coordinate $x - 1$ or the coordinate $x + 1$. The cost of this move is $1$.\n\nYou should move the points in such a way that each segment is visited by at least one point. A point visits the segment $[l, r]$ if there is a moment when its coordinate was on the segment $[l, r]$ (including endpoints).\n\nYou should find the minimal possible total cost of all moves such that all segments are visited.",
    "tutorial": "If a segment already contains a point then it can be thrown out of the consideration. If there is a segment that contains some segment, we can save only the smaller one. If you already know which segments will be visited by some point, how you should calculate the answer for this point? For some segment, which points should visit it? Firstly, if a point has initially visited some segment, then we can throw it out of consideration. It means that all segments that cover at least one point can be thrown out. This can be done using the binary search for each segment separately. Secondly, if a segment $A$ is contained in a segment $B$ (i.e. $l_B \\le l_A \\le r_A \\le r_B$), then a point that visited $A$ will visit $B$, too. It means that we should save only those segments that do not contain any other segments. This can be done using a Fenwick tree. Initially, all values in the tree are zeroes. We will consider the segments in decreasing order of $l$. Let's assume we are considering segment $i$. If there is an already considered segment $j$ $(r_j \\le r_i)$, then segment $j$ is in segment $i$. It is so because $l_i \\le l_j$ because of the considering order, so $l_i \\le l_j \\le r_j \\le r_i$. To find the amount of such $j$ it is enough to find the amount of $1$ on a prefix until $r_i$ in the Fenwick tree. Now when we considered the segment $i$ we set $1$ in the Fenwick tree on position $r_i$. After that there are only segments that do not contain any other segments and they are not initially visited by any point. We will consider only these segments. Let's say that a segment is assigned to a point if that point visits this segment. Let's find out how to calculate the answer for one point if we already know the set of segments that are assigned to it. Let's consider the segments that are on the left to the point and say that the maximal distance from the point to these segments is $a$. In the same way let $b$ be the maximal distance from the point to the segments on the right. Then the answer for the point is $2\\cdot min(a, b)+max(a, b)$. Now if a segment is between two neighbouring points, then it should be assigned to one of these points. (If a segment is to the left from the leftmost point or to the right from the rightmost point then it should be assigned to the leftmost point or to the rightmost point respectively). Now let's consider the segments between two neighbouring points. These segments are ordered by the left ends and by the right ends at the same time. Some prefix of these segments should be assigned to the left point, other segments (suffix) should be assigned to the right point. Now let's solve the problem using the dynamic programming. Let $dp[i][j]$ be the answer if we assigned the segments for first $i$ points and there are $j$ segments assigned to the $i$-th point that are to the right from it. There is a linear amount of dp states. Let's learn to calculate the dp. We will consider the dp states in increasing order of $i$ and, after that, $j$. Let $b$ be the distance from $i$-th point to $j$ segment after it. Then $dp[i][j]=\\displaystyle\\min_{0 \\le k \\le x} \\Big(dp[i-1][k]+2\\cdot min(b, a_{i, k})+max(b, a_{i, k})\\Big)$, where $a_{i, k}$ - is the distance from $i$-th point to $(k+1)$-th segment after $(i-1)$-th point and $x$ is the amount of segments between points $i$ and $(i+1)$. But this is a quadratic dp. Now we can find out that for some prefix of segments after $(i-1)$-th point $a_{i, k}$ is greater than $b$ and for some suffix it is less than $b$. The length of that prefix may be found using the binary search or two pointers. For $k$ on that prefix the dp will be $dp[i-1][k] + x_i - r_{k+1}+2\\cdot b$, and for $k$ on the suffix - $dp[i-1][k] + 2\\cdot(x_i - r_{k+1})+b$. In these formulas everything except $b$ depends on $i$ and $k$. It means that we can calculate dp quickly using prefix and suffix minimums. The answer is $dp[n][x]$, where $x$ is the amount of segments to the right of the rightmost point.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define pb emplace_back\n#define all(x) (x).begin(), (x).end()\n#define fi first\n#define se second\n#define pii pair<int, int>\n#define ll long long \n\nconst long long INFLL = 1e18;\nconst int INF = 1e9 + 1;\n\nstruct segment_tree {\n    vector<int> t;\n\n    segment_tree(int n) {\n        t.assign(4 * n, INF);\n    }\n\n    void mod(int v, int vl, int vr, int id, int val) {\n        if (vr - vl == 1) {\n            t[v] = min(t[v], val);\n            return;\n        }\n        int vm = (vl + vr) / 2;\n        if (id < vm) mod(2 * v + 1, vl, vm, id, val);\n        else mod(2 * v + 2, vm, vr, id, val);\n        t[v] = min(t[v], val);\n    }\n\n    int get(int v, int vl, int vr, int l, int r) {\n        if (vl >= l && vr <= r) return t[v];\n        if (r <= vl || l >= vr) return INF;\n        int vm = (vl + vr) / 2;\n        return min(get(2 * v + 1, vl, vm, l, r), get(2 * v + 2, vm, vr, l, r));\n    }\n};\n\nbool cmp(const pii &a, const pii &b) {\n    return a.se - a.fi < b.se - b.fi;\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        vector<ll> a(n);\n        for (auto &c : a) cin >> c;\n        sort(all(a));\n        vector<pii> seg1(m);\n        vector<int> dl;\n        for (auto &c : seg1) {\n            cin >> c.fi >> c.se;\n            dl.pb(c.fi);\n        }\n        sort(all(dl));\n        dl.resize(unique(all(dl)) - dl.begin());\n        sort(all(seg1), cmp);\n        map<int, int> ma;\n        for (int i = 0; i < (int)dl.size(); i++) ma[dl[i]] = i;\n        segment_tree tr((int)dl.size());\n        vector<pii> seg;\n        for (auto &c : seg1) {\n            int id = lower_bound(all(a), c.fi) - a.begin();\n            if (id < (int)a.size() && a[id] <= c.se) continue;\n            if (tr.get(0, 0, dl.size(), ma[c.fi], dl.size()) <= c.se) continue;\n            tr.mod(0, 0, dl.size(), ma[c.fi], c.se);\n            seg.pb(c.fi, c.se);\n        }\n        m = seg.size();\n        sort(all(seg));\n        vector<vector<pii>> g(n + 1);\n        int L = -1, R = m;\n        while (R - L > 1) {\n            int M = (L + R) / 2;\n            if (seg[M].se < a[0]) L = M;\n            else R = M;\n        }\n        for (int i = 0; i <= L; i++) g[0].pb(seg[i]);\n        for (int i = 0; i < n; i++) {\n            int RIGHT = INF;\n            if (i + 1 < n) RIGHT = a[i + 1];\n            int id = upper_bound(all(seg), make_pair((int)a[i], (int)a[i])) - seg.begin();\n            if (id == m) continue;\n            int L = id - 1, R = m;\n            while (R - L > 1) {\n                int M = (L + R) / 2;\n                if (seg[M].se < RIGHT) L = M;\n                else R = M;\n            }\n            for (int j = id; j <= L; j++) g[i + 1].pb(seg[j]);\n        }\n        vector<vector<ll>> dp(n), pr(n), suff(n);\n        for (int i = 0; i < n; i++) {\n            dp[i].resize(g[i + 1].size() + 1, INFLL);\n            pr[i].resize(g[i + 1].size() + 1, INFLL);\n            suff[i].resize(g[i + 1].size() + 1, INFLL);\n        }\n        for (int j = 0; j <= (int)g[1].size(); j++) {\n            ll x = 0;\n            if (g[0].size()) x = a[0] - g[0][0].se;\n            ll y = 0;\n            if (j) y = g[1][j - 1].fi - a[0];\n            dp[0][j] = 2 * min(x, y) + max(x, y);\n        }\n        for (int i = 1; i < n; i++) {\n            for (int j = 0; j <= (int)g[i].size(); j++) {\n                if (j > 0) pr[i - 1][j] = pr[i - 1][j - 1];\n                pr[i - 1][j] = min(pr[i - 1][j], dp[i - 1][j] - (j == (int)g[i].size() ? a[i] : g[i][j].se));\n            }\n            for (int j = (int)g[i].size(); j >= 0; j--) {\n                if (j + 1 <= (int)g[i].size()) suff[i - 1][j] = suff[i - 1][j + 1];\n                suff[i - 1][j] = min(suff[i - 1][j], dp[i - 1][j] - 2 * (j == (int)g[i].size() ? a[i] : g[i][j].se));\n            }\n            int L = (int)g[i].size();\n            for (int j = 0; j <= (int)g[i + 1].size(); j++) {\n                ll y = 0;\n                if (j) y = g[i + 1][j - 1].fi - a[i];\n                while (L > 0 && a[i] - g[i][L - 1].se <= y) L--;\n                if (L > 0) dp[i][j] = min(dp[i][j], 2 * y + a[i] + pr[i - 1][L - 1]);\n                dp[i][j] = min(dp[i][j], y + 2 * a[i] + suff[i - 1][L]);\n            }\n        }\n        cout << dp[n - 1].back() << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1566",
    "index": "G",
    "title": "Four Vertices",
    "statement": "You are given an undirected weighted graph, consisting of $n$ vertices and $m$ edges.\n\nSome queries happen with this graph:\n\n- Delete an existing edge from the graph.\n- Add a non-existing edge to the graph.\n\nAt the beginning and after each query, you should find four \\textbf{different} vertices $a$, $b$, $c$, $d$ such that there exists a path between $a$ and $b$, there exists a path between $c$ and $d$, and the sum of lengths of two shortest paths from $a$ to $b$ and from $c$ to $d$ is minimal. The answer to the query is the sum of the lengths of these two shortest paths. The length of the path is equal to the sum of weights of edges in this path.",
    "tutorial": "The answer always consists either of three edges with common end or of two edges that don't have any common ends. To find the answer of the second type you can leave in the graph only those edges that are in the list of three smallest edges for both ends. Let's consider those cases when the minimal edge is in the answer or not in the answer. Observation: the answer always consists either of three edges that have one common end or of two edges that do not have any common ends. To find the answer of the first type it is enough to maintain three minimal edges for each vertex. To find the answer of the second type we will use this observation: we can leave in the graph only those edges that are in the set of three minimal edges for each their end. Let's prove that. Let's assume that the answer consists of two edges $(a, b)$ and $(c, d)$ and there are at least three edges $(a, a_1)$, $(a, a_2)$, $(a, a_3)$ less than $(a, b)$. Then the edge $(a, b)$ can be swapped by one of these edges because at least one of te integers $a_1$, $a_2$, $a_3$ is not equal to $c$ and $d$. Then we will maintain the set of all these edges. Now let's consider two cases. Let $(a, b)$ be the minimal edge. If it is in the answer then we need to find the minimal edge, that does not have any common vertices with $(a, b)$. In this case there are at most $6$ ``bad'' edges because the degrees of each vertex in the graph that consists only of remaining edges do not exceed $3$. It means that we have to consider $O(1)$ variants. If $(a, b)$ is not in the answer, then there are two edges in the answer that have vertices $a$ and $b$ as one of their ends. But there are at most $9$ such pairs of edges, so we have to consider only $O(1)$ variants. So the final answer is the minimum of answers of both types.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) (int) (a).size()\n\nconst int N = 1e5;\nvector<pair<int, int>> g[N];\nmap<pair<int, int>, int> cost;\nset<pair<int, int>> a[N], b[N];\nmultiset<long long> dp;\nset<pair<int, pair<int, int>>> dp2;\n\nvoid solve() {\n    auto minr = *dp2.begin();\n    long long ans = 1e18;\n    if (sz(dp)) {\n        ans = min(ans, *dp.begin());\n    }\n    int v = minr.second.first, u = minr.second.second;\n    auto it = dp2.begin();\n    for (int i = 0; i < 6 && it != dp2.end(); i++, it = next(it)) {\n        auto res = *it;\n        int v2 = res.second.first, u2 = res.second.second;\n        if (v2 != v && v2 != u && u2 != v && u2 != u) {\n            ans = min(ans, (long long) res.first + minr.first);\n        }\n    }\n    for (auto [w, v2] : a[v]) {\n        for (auto [w2, u2] : a[u]) {\n            if (v2 != u2 && v2 != u && u2 != v) {\n                ans = min(ans, (long long) w + w2);\n            }\n        }\n    }\n    cout << ans << '\\n';\n}\n\nvoid del(int v) {\n    if (sz(a[v]) >= 3) {\n        long long res = 0;\n        for (auto [w, to] : a[v]) {\n            res += w;\n        }\n        dp.erase(dp.find(res));\n    }\n    for (auto [w, to] : a[v]) {\n        if (dp2.find({w, {min(v, to), max(v, to)}}) != dp2.end()) {\n            dp2.erase({w, {min(v, to), max(v, to)}});   \n        }\n    }\n}\n\nvoid upd(int v) {\n    if (sz(a[v]) >= 3) {\n        long long res = 0;\n        for (auto [w, to] : a[v]) {\n            res += w;\n        }\n        dp.insert(res);\n    }\n    for (auto [w, to] : a[v]) {\n        if (a[to].find({w, v}) != a[to].end()) {\n            dp2.insert({w, {min(v, to), max(v, to)}});  \n        } \n    }\n}\n\nvoid relax(int v) {\n    while (sz(a[v]) && sz(b[v])) {\n        auto A = *a[v].rbegin(), B = *b[v].begin();\n        if (A.first <= B.first) break;\n        a[v].erase(A);\n        b[v].erase(B);\n        a[v].insert(B);\n        b[v].insert(A);\n    }\n    while (sz(a[v]) < 3 && sz(b[v])) {\n        auto B = *b[v].begin();\n        b[v].erase(B);\n        a[v].insert(B);\n    }\n}\n\nvoid erase(int v, int u, int w) {\n    del(v);\n    del(u);\n    if (a[v].find({w, u}) != a[v].end()) {\n        a[v].erase({w, u});\n    }\n    else {\n        b[v].erase({w, u});\n    }\n    if (a[u].find({w, v}) != a[u].end()) {\n        a[u].erase({w, v});\n    }\n    else {\n        b[u].erase({w, v});\n    }\n    relax(v);\n    relax(u);\n    upd(v);\n    upd(u);\n}\n\nvoid add(int v, int u, int w) {\n    del(v);\n    del(u);\n    b[v].insert({w, u});\n    b[u].insert({w, v});\n    relax(v);\n    relax(u);\n    upd(v);\n    upd(u);\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n, m;\n    cin >> n >> m;\n    for (int i = 0; i < m; i++) {\n        int x, y, w;\n        cin >> x >> y >> w;\n        x--, y--;\n        if (x > y) swap(x, y);\n        cost[{x, y}] = w;\n        g[x].push_back({w, y});\n        g[y].push_back({w, x});\n    }\n    for (int i = 0; i < n; i++) {\n        sort(g[i].begin(), g[i].end());\n        for (int j = 0; j < sz(g[i]); j++) {\n            if (j <= 2) {\n                a[i].insert(g[i][j]);\n            }\n            else {\n                b[i].insert(g[i][j]);\n            }\n        }\n        if (sz(a[i]) >= 3) {\n            long long res = 0;\n            for (auto [w, to] : a[i]) {\n                res += w;\n            }\n            dp.insert(res);\n        }\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < sz(g[i]); j++) {\n            int v = g[i][j].second;\n            if (j <= 2) {\n                if (a[v].find({g[i][j].first, i}) != a[v].end()) {\n                    dp2.insert({g[i][j].first, {min(i, v), max(i, v)}});\n                }\n            }\n        }\n    }\n    int q;\n    cin >> q;\n    solve();\n    while (q--) {\n        int t, v, u;\n        cin >> t >> v >> u;\n        v--, u--;\n        if (v > u) swap(v, u);\n        if (t == 0) {\n            int w = cost[{v, u}];\n            erase(v, u, w);\n        }\n        else {\n            int w;\n            cin >> w;\n            cost[{v, u}] = w;\n            add(v, u, w);\n        }\n        solve();\n    }\n}\n",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1566",
    "index": "H",
    "title": "Xor-quiz",
    "statement": "\\textbf{This is an interactive problem.}\n\nYou are given two integers $c$ and $n$. The jury has a \\textbf{randomly generated} set $A$ of distinct positive integers not greater than $c$ (it is generated from all such possible sets with equal probability). The size of $A$ is equal to $n$.\n\nYour task is to guess the set $A$. In order to guess it, you can ask at most $\\lceil 0.65 \\cdot c \\rceil$ queries.\n\nIn each query, you choose a single integer $1 \\le x \\le c$. As the answer to this query you will be given the bitwise xor sum of all $y$, such that $y \\in A$ and $gcd(x, y) = 1$ (i.e. $x$ and $y$ are coprime). If there is no such $y$ this xor sum is equal to $0$.\n\nYou can ask all queries at the beginning and you will receive the answers to all your queries. After that, you won't have the possibility to ask queries.\n\nYou should find any set $A'$, such that $|A'| = n$ and $A'$ and $A$ have the same answers for all $c$ possible queries.",
    "tutorial": "Numbers with the same set of prime divisors may be considered as the same numbers. The amount of distinct sets of prime divisors which multiplication does not exceed $C$ for such constraints does not exceed $\\lceil 0.65 \\cdot C \\rceil$. How you should find the $xor$ of all numbers that have the same set of prime divisors? If you know the $xor$ of all numbers with the same set of prime divisors you can recover these numbers randomly. Let $f(x)$ be the multiplication of all prime divisors of $x$. Then let's make queries for all such $y$ that there is at least one such $x$, $1 \\le x \\le C$ and $f(x) = y$. For such constraints there will be at most $\\lceil 0.65 \\cdot C \\rceil$ queries. Let's group all numbers by $f(x)$. All numbers in one group in any query will be considered together. Let $ans(x)$ be the answer for the query with number $x$ and $g(x)$ be the $xor$ of all number that are not coprime with $x$. Then $g(x)=ans(x) \\oplus ans(1)$. Now let's find out how to calculate the $xor$ of all such $x$ that $f(x)$ is divisible by an arbitrary $y$. Let's take $xor$ of all $g(k)$ where $k$ is a divisor of $y$ greater than $1$. Let's prove that by doing that we will get the needed value. If $f(x)$ is divisible by $y$ then such $x$ will be considered $2^l - 1$ times, where $l$ is the amount of prime divisors of $y$. It means that $x$ will be contained in the final value. Now let's prove that there will be no unintended $x$ values. Let $f(x)$ be not divisible by $y$. It means that there is suche prime $p$ that $y$ is divisible by $p$ and $x$ is not divisible by $p$. Then for each divisor $a$ of $y$ that is divisible by $p$ we will assign $b=a/p$. Then such $x$ will be considered either for both $a$ and $b$ or for none of them. It means that it will be considered an even amount of times. Now to find the $xor$ of all numbers with an arbitrary $f(x)$ we need to consider all $x$ from $C$ to $1$ and make $f(x) = f(x) \\oplus f(2x) \\oplus f(3x) \\oplus \\ldots$. Now we only need to find $n$ distinct numbers from $1$ to $C$ such that $xor$ of numbers in each group is equal to a specific number. For each group of numbers with given $f(x)$ we will start the Gaussian elimination. Let $k$ be the size of a group and after the Gaussian elimination there are $b$ non-zero numbers. Then if $b=k$ there is a single way to obtain the needed $xor$. Else there are $2^{k-b}$ ways to obtain the needed $xor$. Now let's take some random sets of numbers with the needed $xor$ and calculate dp on these numbers to get take exactly $n$ numbers. If there are several ways we can choose any of them.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define pb emplace_back\n#define all(x) (x).begin(), (x).end()\n#define fi first\n#define se second\n#define pii pair<int, int>\n#define ll long long \n#define ld long double\n\nconst long long INFLL = 1e18;\nconst int INF = 1e9 + 1;\nconst int MAXC = 1e6;\nmt19937 gen(time(0));\n\nvector<int> e(MAXC + 5);\n\nvoid precalc() {\n    vector<int> p;\n    for (int i = 2; i <= MAXC; i++) {\n        if (e[i] == 0) {\n            e[i] = i;\n            p.pb(i);\n        }\n        for (int j = 0; j < (int)p.size() && p[j] * i <= MAXC && p[j] <= e[i]; j++) {\n            e[p[j] * i] = p[j];\n        }\n    }\n}\n\nint f(int x) {\n    int ans = 1;\n    vector<int> p;\n    while (x > 1) {\n        p.pb(e[x]);\n        x /= e[x];\n    }\n    for (int i = 0; i < (int)p.size(); i++) {\n        if (i + 1 == (int)p.size() || p[i + 1] != p[i]) ans *= p[i];\n    }\n    return ans;\n}\n\nvoid gauss(int need, vector<int> &lst, vector<int> &ans, vector<vector<int>> &sz, vector<vector<vector<int>>> &v) {\n    int n = lst.size();\n    vector<bitset<20>> a(n);\n    for (int i = 0; i < n; i++) a[i] = lst[i];\n    bitset<20> b = need;\n    vector<bitset<260>> l(n);\n    for (int i = 0; i < n; i++) l[i][i] = 1;\n    int i = 0;\n    vector<int> col(20, -1);\n    int bas_sz = 0;\n    for (int j = 0; j < 20 && i < n; j++) {\n        int i1 = i;\n        while (i1 < n && a[i1][j] == 0) i1++;\n        if (i1 == n) continue;\n        swap(a[i], a[i1]);\n        swap(l[i], l[i1]);\n        bas_sz++;\n        col[j] = i;\n        for (int i2 = i + 1; i2 < n; i2++) {\n            if (a[i2][j]) {\n                a[i2] ^= a[i];\n                l[i2] ^= l[i];\n            }\n        }\n        i++;\n    }\n    bitset<20> res;\n    bitset<260> path;\n    for (int j = 0; j < 20; j++) {\n        if (res[j] != b[j] && col[j] == -1) {\n            exit(0);\n        }\n        if (res[j] == b[j]) continue;\n        res ^= a[col[j]];\n        path ^= l[col[j]];\n    }\n    if (a.back().count() != 0) {\n        for (int i = 0; i < n; i++) {\n            if (path[i]) ans.pb(lst[i]);\n        }\n        return;\n    } \n    vector<int> diff_sz(300);\n    sz.pb();\n    v.pb();\n    for (int it = 0; it < 100; it++) {\n        bitset<260> now = path;\n        for (int i = 0; i < n - bas_sz; i++) {\n            if (gen() % 2) now ^= l[bas_sz + i];\n        }\n        int now_sz = now.count();\n        if (diff_sz[now_sz]) continue;\n        v.back().pb();\n        for (int i = 0; i < n; i++) {\n            if (now[i]) v.back().back().pb(lst[i]);\n        }\n        diff_sz[now_sz] = 1;\n        sz.back().pb(now_sz);\n    }\n}\n\nvector<int> mem(2 * MAXC + 5, -1);\n\nint query(int x) {\n    return mem[x];\n}\n\nvoid solve(int n, int c) {\n    vector<int> calc(c + 1);\n    vector<vector<int>> total(c + 1);\n    for (int x = 1; x <= c; x++) total[f(x)].pb(x);\n    vector<int> need;\n    for (int x = 1; x <= c; x++) {\n        if (total[x].size()) need.pb(x);\n    }\n    cout << need.size() << \" \";\n    for (auto &c : need) cout << c << \" \";\n    cout << endl;\n    for (auto &c : need) {\n        int x;\n        cin >> x;\n        mem[c] = x;\n    }\n    int total_xor = query(1);\n    for (int x = 1; x <= c; x++) {\n        if (total[x].empty()) continue;\n        for (int y = x; y <= c; y += x) calc[y] ^= (query(x) ^ total_xor);\n    }\n    calc[1] = total_xor;\n    for (int x = c; x >= 1; x--) {\n        if (total[x].empty()) continue;\n        for (int y = 2 * x; y <= c; y += x) {\n            if (total[y].size()) calc[x] ^= calc[y];\n        }\n    }\n    vector<int> ans;\n    vector<vector<int>> sz;\n    vector<vector<vector<int>>> v;\n    for (int x = 1; x <= c; x++) {\n        if (total[x].empty()) continue;\n        gauss(calc[x], total[x], ans, sz, v);\n    }\n    vector<bitset<40000>> bag(sz.size() + 1);\n    bag[0][0] = 1;\n    for (int i = 1; i <= (int)sz.size(); i++) {\n        for (auto &x : sz[i - 1]) {\n            bag[i] |= (bag[i - 1] << x);\n        }\n    }\n    int now = n - ans.size();\n    for (int i = (int)sz.size(); i >= 1; i--) {\n        for (int j = 0; j < (int)sz[i - 1].size(); j++) {\n            int x = sz[i - 1][j];\n            if (now - x >= 0 && bag[i - 1][now - x]) {\n                now -= x;\n                for (auto &y : v[i - 1][j]) ans.pb(y);\n                break;\n            }\n        }\n    }\n    sort(all(ans));\n    for (auto &c : ans) cout << c << \" \";\n    cout << endl;\n}\n\nint main() {\n    precalc();\n    int c, n;\n    cin >> c >> n;\n    solve(n, c);\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1567",
    "index": "A",
    "title": "Domino Disaster",
    "statement": "Alice has a grid with $2$ rows and $n$ columns. She fully covers the grid using $n$ dominoes of size $1 \\times 2$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.\n\nNow, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!",
    "tutorial": "If there is a vertical domino (either U or D) in the current slot, then the corresponding domino half in the other row must be a D or a U, respectively. Otherwise, we can just fill the rest of the row with copies of LR. Time complexity: $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    string s, res;\n    cin >> s;\n    for (int i = 0; i < n; i++) {\n        if (s[i] == 'U') {res += 'D';}\n        else if (s[i] == 'D') {res += 'U';}\n        else {res += \"LR\"; i++;}\n    }\n    cout << res;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve(); cout << endl;}\n    //solve();\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1567",
    "index": "B",
    "title": "MEXor Mixup",
    "statement": "Alice gave Bob two integers $a$ and $b$ ($a > 0$ and $b \\ge 0$). Being a curious boy, Bob wrote down an array of \\textbf{non-negative} integers with $\\operatorname{MEX}$ value of all elements equal to $a$ and $\\operatorname{XOR}$ value of all elements equal to $b$.\n\nWhat is the shortest possible length of the array Bob wrote?\n\nRecall that the $\\operatorname{MEX}$ (Minimum EXcluded) of an array is the minimum non-negative integer that does \\textbf{not} belong to the array and the $\\operatorname{XOR}$ of an array is the bitwise XOR of all the elements of the array.",
    "tutorial": "First consider the MEX condition: the shortest array with MEX $a$ is the array $[0, 1, \\dots, a - 1]$, which has length $a$. Now we'll consider the XOR condition. Let the XOR of the array $[0, 1, \\dots, a - 1]$ be $x$. We have three cases. Case 1: $x = b$. Then we don't need to add any elements to the array, so the answer is $a$. Case 2: $x \\neq b$ and $x \\oplus b \\neq a$. Then we can add the element $x \\oplus b$ to the array since $x \\oplus b \\neq a$, so the MEX will still be $a$. The XOR of the array will then be $x \\oplus x \\oplus b = b$. The answer is $a + 1$. Case 3: $x \\neq b$ and $x \\oplus b = a$. Then we cannot add the element $x \\oplus b$ to the end of the array. We can just add $x \\oplus b \\oplus 1$ and $1$, so the XOR of the array will be $x \\oplus x \\oplus b \\oplus 1 \\oplus 1 = b$. The answer is $a + 2$. Time complexity: $\\mathcal{O}(n)$ precomputation and $\\mathcal{O}(1)$ per test case if you precalculate the XOR of the numbers from $0$ to $n-1$, or $\\mathcal{O}(1)$ if you use the well-known formula for it.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 100007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n    int a, b;\n    cin >> a >> b;\n    int pXor;\n    if (a % 4 == 1) {pXor = a - 1;}\n    else if (a % 4 == 2) {pXor = 1;}\n    else if (a % 4 == 3) {pXor = a;}\n    else {pXor = 0;}\n \n    if (pXor == b) {cout << a << '\\n';}\n    else if ((pXor ^ b) != a) {cout << a + 1 << '\\n';}\n    else {cout << a + 2 << '\\n';}\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    //solve();\n}",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1567",
    "index": "C",
    "title": "Carrying Conundrum",
    "statement": "Alice has just learned addition. However, she hasn't learned the concept of \"carrying\" fully — instead of carrying to the next column, she carries to the column two columns to the left.\n\nFor example, the \\textbf{regular} way to evaluate the sum $2039 + 2976$ would be as shown:\n\nHowever, Alice evaluates it as shown:\n\nIn particular, this is what she does:\n\n- add $9$ and $6$ to make $15$, and carry the $1$ to the column two columns to the left, i. e. to the column \"$0$ $9$\";\n- add $3$ and $7$ to make $10$ and carry the $1$ to the column two columns to the left, i. e. to the column \"$2$ $2$\";\n- add $1$, $0$, and $9$ to make $10$ and carry the $1$ to the column two columns to the left, i. e. to the column above the plus sign;\n- add $1$, $2$ and $2$ to make $5$;\n- add $1$ to make $1$.\n\nThus, she ends up with the incorrect result of $15005$.Alice comes up to Bob and says that she has added two numbers to get a result of $n$. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $n$. Note that pairs $(a, b)$ and $(b, a)$ are considered different if $a \\ne b$.",
    "tutorial": "Note that in every other column, the addition Alice performs is correct. Therefore, we can take our number, split it into alternating digits, and then find the answer. For example, consider $n = 12345$. We split it into alternating digits: $1\\underline{2}3\\underline{4}5 \\to 135, 24$. Now the problem is equivalent to find the number of pairs of numbers which add to $135$ multiplied by the number of pairs of numbers which add to $24$. It's clear each pair works: for example, $45 + 90 = 135$ and $\\underline{9} + \\underline{15} = \\underline{24}$, so $4\\underline{9}5 + \\underline{1}9\\underline{5}0$ will be equal to $12345$ according to Alice. Now, how many ways are there to find a pair of non-negative integers whose sum is $n$? There are clearly $n+1$ ways: $n+0,(n-1)+1,(n-2)+2,\\dots,0+n$. Therefore, suppose we split $n$ into two numbers $a$ and $b$. Then the answer will be $(a+1)(b+1)$, but we should subtract $2$ because those correspond to either the first or second number in the sum being $0$. As a result, the answer is $(a+1)(b+1)-2$. Time complexity: $\\mathcal{O}(\\log_{10}n) = \\mathcal{O}(\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint dp[10][2][2];\n \nvoid solve()\n{\n    string s;\n    cin>>s;\n    int n=s.size();\n    for (int i=0;i<10;++i)\n        for (int j=0;j<2;++j)\n            for (int k=0;k<2;++k)\n                dp[i][j][k]=0;\n    dp[n][0][0]=1;\n    for (int i=n-1;i>=0;--i)\n        for (int j=0;j<10;++j)\n            for (int k=0;k<10;++k)\n                for (int l=0;l<2;++l)\n                    for (int m=0;m<2;++m)\n                        if ((j+k+l)%10==s[i]-'0')\n                            dp[i][m][(j+k+l)/10]+=dp[i+1][l][m];\n    cout<<dp[0][0][0]-2<<\"\\n\";\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int t;\n    cin>>t;\n    while (t--)\n        solve();\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1567",
    "index": "D",
    "title": "Expression Evaluation Error",
    "statement": "On the board, Bob wrote $n$ positive integers in base $10$ with sum $s$ (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-$11$ integers and adds them up (in base $11$).\n\nWhat numbers should Bob write on the board, so Alice's sum is as large as possible?",
    "tutorial": "Let's greedily construct the largest possible sum for Alice, digit by digit. That is, the leftmost position should have the largest value possible, then the second-leftmost position, and so on. The maximum value of the leftmost digit of Alice's sum is clearly equal to the leftmost digit of the number $s$, since it cannot be larger. Similarly, the maximum possible value for the second-leftmost digit in Alice's sum cannot be larger than the corresponding digit in $s$, and so on. In general, Alice's sum cannot be larger than the number $s$ when interpreted as a base-11 number. So how can we maintain the sum of $s$ when we express it as a sum of $n$ numbers? The idea is to split $s$ into a sum of powers of $10$. For example, if $s=25$, and Bob writes down $[10, 10, 1, 1, 1, 1, 1]$. Then Alice will not have any carries, and so the answer will just be $s$ interpreted as a base-11 number. But what if we need to write down more numbers than the sum of the digits of $s$? Then, we're forced to split a power ten into units. When we split a power of $10$, it can be seen that we should split the smallest power of $10$ that isn't $1$ (call it $10^k$) as $10^{k-1}$ and $9 \\cdot 10^{k-1}$. We can check all powers of $10$, and it can be shown that this is the best way to split. For example, if $s=21$ and $n=4$, then we do the following process: $[21]$ to $[20, 1]$ to $[10, 10, 1]$ to $[10, 9, 1, 1]$. If $s=110$ and $n=3$, we do the following process: $[110]$ to $[100, 10]$ to $[100, 9, 1]$. Note that, in this last case, splitting $10=9+1$ is better than splitting $100=90+10$, since the sum of $100_{11} + 9_{11} + 1_{11} = 10A_{11}$, and $90_{11} + 10_{11} + 1_{11} = A1_{11}$. Time complexity: $\\mathcal{O}(n^2 \\log_{10}(s))$ if you lazily iterate over all currently split numbers, or $\\mathcal{O}(n \\log{n} \\log_{10}(s))$ if you use a priority queue.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nlong long split(long long n) {\n\tlong long pow10 = 1;\n\twhile (pow10 <= n) {\n\t\tif (pow10 == n) {return pow10 / 10;}\n\t\tpow10 *= 10;\n\t}\n\treturn pow10 / 10;\n}\n \nbool isPow10(long long n) {\n\tlong long pow10 = 1;\n\twhile (pow10 <= n) {\n\t\tif (pow10 == n) {return true;}\n\t\tpow10 *= 10;\n\t}\n\treturn false;\n}\n \nvoid solve() {\n\tlong long s;\n\tint n;\n\tcin >> s >> n;\n\tvector<long long> curr;\n\tcurr.push_back(s);\n\tfor (int mv = 0; mv < n - 1; mv++) {\n\t\tlong long x = -1;\n\t\tfor (int i = 0; i < curr.size(); i++) {\n\t\t\tif (!isPow10(curr[i])) {\n\t\t\t\tx = curr[i]; \n\t\t\t\tcurr.erase(curr.begin() + i); \n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (x == -1) {\n\t\t\tlong long mn = 1000000000007ll;\n\t\t\tfor (int i = 0; i < curr.size(); i++) {\n\t\t\t\tif (curr[i] != 1) {\n\t\t\t\t\tmn = min(mn, curr[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < curr.size(); i++) {\n\t\t\t\tif (curr[i] == mn) {\n\t\t\t\t\tx = curr[i]; \n\t\t\t\t\tcurr.erase(curr.begin() + i); \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcurr.push_back(split(x));\n\t\tcurr.push_back(x - split(x));\n\t}\n\tfor (auto i : curr) {\n\t\tcout << i << ' ';\n\t}\n\tcout << endl;\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1567",
    "index": "E",
    "title": "Non-Decreasing Dilemma",
    "statement": "Alice has recently received an array $a_1, a_2, \\dots, a_n$ for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too!\n\nHowever, soon Bob became curious, and as any sane friend would do, asked Alice to perform $q$ operations of two types on her array:\n\n- $1$ $x$ $y$: update the element $a_x$ to $y$ (set $a_x = y$).\n- $2$ $l$ $r$: calculate how many non-decreasing subarrays exist within the subarray $[a_l, a_{l+1}, \\dots, a_r]$. More formally, count the number of pairs of integers $(p,q)$ such that $l \\le p \\le q \\le r$ and $a_p \\le a_{p+1} \\le \\dots \\le a_{q-1} \\le a_q$.\n\nHelp Alice answer Bob's queries!",
    "tutorial": "Note that if there exists a non-decreasing array of length $x$, then it contains $\\frac{x(x+1)}{2}$ non-decreasing subarrays. Therefore, we can break our solution down to counting the lengths of the non-decreasing \"chains\" within the queried subarray. We can solve this problem using a data structure called a segment tree. On each node of this segment tree, we shall maintain four pieces of information: $\\cdot$ the length of the longest non-decreasing prefix. $\\cdot$ the length of the longest non-decreasing suffix. $\\cdot$ a boolean flag denoting if the entire segment is non-decreasing. $\\cdot$ the total number of nondecreasing subarrays not part of the longest prefix or suffix. I won't explain the merging process here (you can examine the implementation below), but it is not too complex. Using this, we can traverse the segment tree, from the left of our queried range to the right, while maintaining the number of non-decreasing subarrays in the prefix of the range and the length of the outgoing non-decreasing suffix to get our answer. Time complexity: $\\mathcal{O}(q\\log n)$.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\n \nconst int N = 2e5+5;\nint a[N], k;\nll seg[N*4][4], ans;\n \n/**\n \nNotes:\n \n0: The total number of non-decreasing subarrays in this segment which are are not subarrays of the longest prefix/suffix of non-decreasing subarrays.\n1: Length of longest non-decreasing prefix of this segment.\n2: Length of longest non-decreasing suffix of this segment.\n3: Denotes if this entire segment is nondecreasing (0/1).\n \n**/ \n \nll f(int x)\n{\n    return (1LL*x*(x+1))/2;\n}\n \nvoid calc(int i, int l, int r)\n{\n    int m=l+(r-l)/2;\n    if (seg[i*2+1][3]&&seg[i*2+2][3])\n    {\n        if (a[m]>a[m+1])\n        {\n            seg[i][0]=0;\n            seg[i][1]=(r-l)/2+1;\n            seg[i][2]=r-l-(r-l)/2;\n            seg[i][3]=0;\n        }\n        else\n        {\n            seg[i][0]=0;\n            seg[i][1]=0;\n            seg[i][2]=0;\n            seg[i][3]=1;\n        }\n    }\n    else if (seg[i*2+1][3])\n    {\n        if (a[m]>a[m+1])\n        {\n            seg[i][0]=seg[i*2+2][0]+f(seg[i*2+2][1]);\n            seg[i][1]=(r-l)/2+1;\n            seg[i][2]=seg[i*2+2][2];\n            seg[i][3]=0;\n        }\n        else\n        {\n            seg[i][0]=seg[i*2+2][0];\n            seg[i][1]=(r-l)/2+1+seg[i*2+2][1];\n            seg[i][2]=seg[i*2+2][2];\n            seg[i][3]=0;\n        }\n    }\n    else if (seg[i*2+2][3])\n    {\n        if (a[m]>a[m+1])\n        {\n            seg[i][0]=seg[i*2+1][0]+f(seg[i*2+1][2]);\n            seg[i][1]=seg[i*2+1][1];\n            seg[i][2]=r-l-(r-l)/2;\n            seg[i][3]=0;\n        }\n        else\n        {\n            seg[i][0]=seg[i*2+1][0];\n            seg[i][1]=seg[i*2+1][1];\n            seg[i][2]=r-l-(r-l)/2+seg[i*2+1][2];\n            seg[i][3]=0;\n        }\n    }\n    else\n    {\n        if (a[m]>a[m+1])\n        {\n            seg[i][0]=seg[i*2+1][0]+seg[i*2+2][0]+f(seg[i*2+1][2])+f(seg[i*2+2][1]);\n            seg[i][1]=seg[i*2+1][1];\n            seg[i][2]=seg[i*2+2][2];\n            seg[i][3]=0;\n        }\n        else\n        {\n            seg[i][0]=seg[i*2+1][0]+seg[i*2+2][0]+f(seg[i*2+1][2]+seg[i*2+2][1]);\n            seg[i][1]=seg[i*2+1][1];\n            seg[i][2]=seg[i*2+2][2];\n            seg[i][3]=0;\n        }\n    }\n}\n \nvoid build(int i, int l, int r)\n{\n    if (l==r)\n    {\n        cin>>a[l];\n        seg[i][3]=1;\n        return;\n    }\n    build(i*2+1,l,l+(r-l)/2);\n    build(i*2+2,l+(r-l)/2+1,r);\n    calc(i,l,r);\n}\n \nvoid update(int i, int l, int r, int x, int y)\n{\n    if (l==r)\n    {\n        a[x]=y;\n        return;\n    }\n    if (x<=l+(r-l)/2)\n        update(i*2+1,l,l+(r-l)/2,x,y);\n    else\n        update(i*2+2,l+(r-l)/2+1,r,x,y);\n    calc(i,l,r);\n}\n \nvoid query(int i, int l, int r, int qL, int qR)\n{\n    if (r<qL||qR<l)\n        return;\n    if (qL<=l&&r<=qR)\n    {\n        if (seg[i][3])\n        {\n            if (a[l-1]>a[l])\n            {\n                ans+=f(k);\n                k=r-l+1;\n            }\n            else\n                k+=r-l+1;\n        }\n        else\n        {\n            if (a[l-1]>a[l])\n                ans+=seg[i][0]+f(k)+f(seg[i][1]);\n            else\n                ans+=seg[i][0]+f(k+seg[i][1]);\n            k=seg[i][2];\n        }\n        return;\n    }\n    query(i*2+1,l,l+(r-l)/2,qL,qR);\n    query(i*2+2,l+(r-l)/2+1,r,qL,qR);\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int n,q,t,l,r;\n    cin>>n>>q;\n    build(0,1,n);\n    while (q--)\n    {\n        cin>>t>>l>>r;\n        if (t==1)\n            update(0,1,n,l,r);\n        else\n        {\n            ans=k=0;\n            query(0,1,n,l,r);\n            cout<<ans+f(k)<<\"\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1567",
    "index": "F",
    "title": "One-Four Overload",
    "statement": "Alice has an empty grid with $n$ rows and $m$ columns. Some of the cells are marked, and \\textbf{no marked cells are adjacent to the edge of the grid}. (Two squares are adjacent if they share a side.)\n\nAlice wants to fill each cell with a number such that the following statements are true:\n\n- every unmarked cell contains either the number $1$ or $4$;\n- every marked cell contains the sum of the numbers in all \\textbf{unmarked} cells adjacent to it (if a marked cell is not adjacent to any unmarked cell, this sum is $0$);\n- every marked cell contains a multiple of $5$.\n\nAlice couldn't figure it out, so she asks Bob to help her. Help Bob find any such grid, or state that no such grid exists.",
    "tutorial": "Let's look at the numbers in the grid modulo $5$. $1$ and $4$ are $1$ and $-1$ modulo $5$, and by definition each marked cell must be $0$ modulo $5$. This means that each marked cell must have an even number of unmarked neighbors, and there must be an equal number of $1$s and $4$s among those neighbors. In other words, the problem is about two-coloring a grid so each marked square has the same number of red and blue neighbors. If each cell is adjacent to 2 or 4 unmarked cells, then they will form a graph whose faces are two-colorable (the proof of this is below), which will satisfy all conditions, since all cells adjacent to 2 unmarked cells will be adjacent to two cells on opposite faces. However, the tricky case is to deal with cells with 0 unmarked neighbors. The idea is to put a \"mask\" on top of the grid, which will also allow the cells with no unmarked neighbors to satisfy the condition while not interfering with already placed cells. That is, in the coloring terminology above, we will two color the grid, and then flip some cells according to the \"mask\" such that all cells with 2 or 4 unmarked neighbors still satisfy the condition, and all cells with 0 unmarked neighbors now satisfy the condition. We claim that we should flip all cells in all even-numbered columns; that is, the mask should contain columns alternately colored red and blue. Let's prove this works. There are four types of marked cells: a marked cell with no marked neighbors: all four neighbors are in same connected component, so none of them will be \"flipped\" with respect to the rest, and they will work: they will be the numbers $1,4,1,4$ by the mask. For this to hold true, when we make connected components, we need to DFS/BFS diagonally as well. a marked cell with only marked neighors: nothing to check. a marked cell with marked neighbors in the shape of an L tromino: again, these unmarked cells must be part of same connected component, so they will work: they will be the numbers $1$ and $4$ by the mask. For this to hold true, when we make connected components, we need to DFS/BFS diagonally as well. a marked cell with marked neighbors in the shape of an I tromino: then the cell on one side is necessarily in a different connected component than the other, so one will be flipped by the two-coloring, and they will be the right parities. It suffices to show that the graph formed by edges between connected components of unmarked cells is bipartite. Consider instead the graph formed by the marked cells, with an edge between orthogonally adjacent cells. Consider each connected component of this graph individually. By the condition all vertices have degree 0, 2, or 4, but none can have degree 0 because the graph is connected. Now by a theorem of Euler this graph must have a Eulerian cycle. Now we have a more general claim: the face-vertex dual of a Eulerian graph is bipartite. Suppose otherwise. Then the dual has some odd cycle. This means that some face of the dual must be bounded by an odd number of edges, since you can never \"split\" an odd cycle into only even ones. Also, the dual is planar, because our original graph is obviously planar (we are given an explicit planar embedding of it!). Now some face of the dual has an odd number of edges. This means that in the dual graph of the dual, some vertex has odd degree. But the dual graph of the dual is the original graph. So the original graph is both Eulerian and has odd degree, which is absurd. Finally, even though there are many connected components, it is clear that they do not interact: just set the infinite outside face to be one color, and the rest of the faces will be colored automatically. Therefore this graph is bipartite, so we can two-color as desired, and we are done. Time complexity: $\\mathcal{O}(mn)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 507;\n \nchar grid[MAX][MAX] = {};\nbool vis[MAX][MAX] = {};\nint val[MAX][MAX] = {}, res[MAX][MAX] = {}, color[MAX * MAX] = {};\nset<int> graph[MAX * MAX] = {};\nint ind = 0;\n \nvoid dfs(int x, int y) {\n    vis[x][y] = true;\n    vector<pair<int, int> > v;\n    for (int i = -1; i <= 1; i++) {\n        for (int j = -1; j <= 1; j++) {\n        \tv.emplace_back(x + i, y + j);\n        }\n    }\n    for (auto p : v) {\n        if (!vis[p.first][p.second] && grid[p.first][p.second] == '.') {\n            val[p.first][p.second] = ind;\n            dfs(p.first, p.second);\n        }\n    }\n}\n \nint flip(int x) {\n    return (x == 1 ? 4 : 1);\n}\n \nvoid solve() {\n\t// take input\n    int n, m;\n    cin >> n >> m;\n    for (int i = 0; i <= n + 1; i++) {\n        for (int j = 0; j <= m + 1; j++) {\n            if (i == 0 || j == 0 || i == n + 1 || j == m + 1) {grid[i][j] = '!';}\n            else {cin >> grid[i][j];}\n        }\n    }\n    // check that all marked cells have proper degree\n    for (int i = 2; i <= n - 1; i++) {\n        for (int j = 2; j <= m - 1; j++) {\n            int cnt = (grid[i - 1][j] == '.') + (grid[i + 1][j] == '.') + (grid[i][j - 1] == '.') + (grid[i][j + 1] == '.');\n            if (grid[i][j] == 'X' && cnt % 2 == 1) {cout << \"NO\" << endl; return;}\n        }\n    }\n    // find connected components\n    for (int i = 1; i <= n; i++) {\n        for (int j = 1; j <= m; j++) {\n            if (grid[i][j] == '.' && !vis[i][j]) {\n                ind++;\n                val[i][j] = ind;\n                dfs(i, j);\n            }\n        }\n    }\n    // build graph of connected components\n    for (int i = 1; i <= n; i++) {\n    \tfor (int j = 1; j <= m; j++) {\n    \t\tif (grid[i][j] == 'X') {\n    \t\t\tbool horz = (grid[i][j - 1] == '.' && grid[i][j + 1] == '.');\n    \t\t\tbool vert = (grid[i - 1][j] == '.' && grid[i + 1][j] == '.');\n    \t\t\tif (horz && (val[i][j - 1] != val[i][j + 1])) {\n    \t\t\t\tgraph[val[i][j - 1]].insert(val[i][j + 1]);\n    \t\t\t\tgraph[val[i][j + 1]].insert(val[i][j - 1]);\n    \t\t\t}\n    \t\t\tif (vert && (val[i - 1][j] != val[i + 1][j])) {\n    \t\t\t\tgraph[val[i - 1][j]].insert(val[i + 1][j]);\n    \t\t\t\tgraph[val[i + 1][j]].insert(val[i - 1][j]);\n    \t\t\t}\n    \t\t\t\n    \t\t}\n    \t}\n    }\n    // make bipartite coloring of graph\n    queue<int> q;\n    for (int i = 1; i <= ind; i++) {\n    \tif (color[i] == 0) {\n    \t\tq.push(i);\n    \t\tcolor[i] = 1;\n    \t\twhile (!q.empty()) {\n    \t\t\tint v = q.front();\n    \t\t\tq.pop();\n    \t\t\tfor (int u : graph[v]) {\n    \t\t\t\tif (color[u] == 0) {color[u] = (color[v] ^ 3); q.push(u);}\n    \t\t\t\telse if (color[u] == color[v]) {cout << \"NO\" << endl; return;}\n    \t\t\t}\n    \t\t}\n    \t}\n    }\n    // flip each cell appropriately, column by column\n    for (int j = 1; j <= m; j++) {\n        int curr = (j % 2 ? 4 : 1);\n        res[1][j] = curr;\n        int prev = color[val[1][j]];\n        for (int i = 2; i <= n; i++) {\n            if (grid[i][j] == '.') {\n                if (color[val[i][j]] != prev) {curr = flip(curr);}\n                res[i][j] = curr;\n                prev = color[val[i][j]];\n            }\n        }\n    }\n    // find values of marked cells\n    for (int i = 1; i <= n; i++) {\n        for (int j = 1; j <= m; j++) {\n            if (grid[i][j] == 'X') {\n                if (grid[i - 1][j] == '.') {res[i][j] += res[i - 1][j];}\n                if (grid[i + 1][j] == '.') {res[i][j] += res[i + 1][j];}\n                if (grid[i][j - 1] == '.') {res[i][j] += res[i][j - 1];}\n                if (grid[i][j + 1] == '.') {res[i][j] += res[i][j + 1];}\n            }\n        }\n    }\n    // output the answer\n    cout << \"YES\" << endl;\n    for (int i = 1; i <= n; i++) {\n        for (int j = 1; j <= m; j++) {\n            cout << res[i][j] << ' ';\n        }\n        cout << endl;\n    }\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n}",
    "tags": [
      "2-sat",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1569",
    "index": "A",
    "title": "Balanced Substring",
    "statement": "You are given a string $s$, consisting of $n$ letters, each letter is either 'a' or 'b'. The letters in the string are numbered from $1$ to $n$.\n\n$s[l; r]$ is a continuous substring of letters from index $l$ to $r$ of the string inclusive.\n\nA string is called balanced if the number of letters 'a' in it is equal to the number of letters 'b'. For example, strings \"baba\" and \"aabbab\" are balanced and strings \"aaab\" and \"b\" are not.\n\nFind any non-empty balanced substring $s[l; r]$ of string $s$. Print its $l$ and $r$ ($1 \\le l \\le r \\le n$). If there is no such substring, then print $-1$ $-1$.",
    "tutorial": "Any non-empty balanced string contains at least one letter 'a' and at least one letter 'b'. That implies that there's an 'a' adjacent to a 'b' somewhere in that string. Both strings \"ab\" and \"ba\" are balanced. Thus, any balanced string contains a balanced substring of length $2$. So the solution is to check all $n-1$ pairs of adjacent letters. If there exists a pair of different ones, print it. Overall complexity: $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ts = input()\n\tfor i in range(n - 1):\n\t\tif s[i] != s[i + 1]:\n\t\t\tprint(i + 1, i + 2)\n\t\t\tbreak\n\telse:\n\t\tprint(-1, -1)",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1569",
    "index": "B",
    "title": "Chess Tournament",
    "statement": "A chess tournament will be held soon, where $n$ chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players.\n\nEach of the players has their own expectations about the tournament, they can be one of two types:\n\n- a player wants not to lose any game (i. e. finish the tournament with \\textbf{zero losses});\n- a player wants to win at least one game.\n\nYou have to determine if there exists an outcome for all the matches such that all the players meet their expectations. If there are several possible outcomes, print any of them. If there are none, report that it's impossible.",
    "tutorial": "Since the chess players of the first type should not lose a single game, each game between two chess players of the first type should end in a draw (so that none of them gets defeated). And a game between a chess player of the first type and the second type should end either with a victory of the first or a draw. Therefore, for convenience, we will say that all games with a chess player of the first type end in a draw. Now there are only games between chess players of the second type left. If there are only $1$ or $2$ such players, then there is no answer. Otherwise, we can choose the following method: the $i$-th chess player of the second type wins against the $i+1$-th chess player of the second type, and the last one wins against the first; all remaining games are drawn.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL); \n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    string s;\n    cin >> n >> s;\n    vector<int> id;\n    for (int i = 0; i < n; ++i) if (s[i] == '2')\n      id.push_back(i);\n    int k = id.size();\n    if (k == 1 || k == 2) {\n      cout << \"NO\\n\";\n      continue;\n    }\n    vector<string> t(n, string(n, '='));\n    for (int i = 0; i < n; ++i) t[i][i] = 'X';\n    for (int i = 0; i < k; ++i) {\n      int x = id[i], y = id[(i + 1) % k];\n      t[x][y] = '+';\n      t[y][x] = '-';\n    }\n    cout << \"YES\\n\";\n    for (int i = 0; i < n; ++i) cout << t[i] << '\\n';\n  }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1569",
    "index": "C",
    "title": "Jury Meeting",
    "statement": "$n$ people gathered to hold a jury meeting of the upcoming competition, the $i$-th member of the jury came up with $a_i$ tasks, which they want to share with each other.\n\nFirst, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation $p$ of numbers from $1$ to $n$ (an array of size $n$ where each integer from $1$ to $n$ occurs exactly once).\n\nThen the discussion goes as follows:\n\n- If a jury member $p_1$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.\n- If a jury member $p_2$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.\n- ...\n- If a jury member $p_n$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped.\n- If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends.\n\nA permutation $p$ is nice if none of the jury members tell two or more of their own tasks in a row.\n\nCount the number of nice permutations. The answer may be really large, so print it modulo $998\\,244\\,353$.",
    "tutorial": "Note that if there are at least two members with the maximum value of $a_i$, then any permutation is nice. Now let's consider the case when there is only one maximum. Let's find out when the permutation is nice. Let $x$ be the index of the jury member with the maximum number of tasks. Then, during the $a_x$-th discussion round, they will be the only one who will tell their task, because the other members of the jury have already told all their tasks. So during the $(a_x-1)$-th discussion round, there should be a jury member who tells a task after the $x$-th jury member. Let $k$ be the number of elements in the array $a$ equal to $a_x-1$. Then, if at least one of these $k$ jury members goes after the jury member $x$ in the permutation, then the permutation is nice. Using this, we will count the number of bad permutations. Let's fix the elements in the permutation that are not equal to $a_x$ or $a_x-1$, there are $n-k-1$ of them, then the number of ways is $A_n^{n-k-1} = \\frac{n!}{(k+1)!}$. It remains to place $k+1$ elements so that the maximum is in the last position among them, there are $k!$ such ways. The total number of bad permutations is $\\frac{n!k!}{(k+1)!}=\\frac{n!}{k + 1}$. So the answer is $n! - \\frac{n!}{k + 1}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL); \n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n    int mx = *max_element(a.begin(), a.end());\n    int cmx = count(a.begin(), a.end(), mx);\n    int k = count(a.begin(), a.end(), mx - 1);\n    int ans = 1, sub = 1;\n    for (long long i = 1; i <= n; ++i) {\n      ans = ans * i % MOD;\n      if (i != k + 1) sub = sub * i % MOD;\n    }\n    if (cmx == 1) ans = (ans - sub + MOD) % MOD;\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1569",
    "index": "D",
    "title": "Inconvenient Pairs",
    "statement": "There is a city that can be represented as a square grid with corner points in $(0, 0)$ and $(10^6, 10^6)$.\n\nThe city has $n$ vertical and $m$ horizontal streets that goes across the whole city, i. e. the $i$-th vertical streets goes from $(x_i, 0)$ to $(x_i, 10^6)$ and the $j$-th horizontal street goes from $(0, y_j)$ to $(10^6, y_j)$.\n\nAll streets are bidirectional. Borders of the city are streets as well.\n\nThere are $k$ persons staying on the streets: the $p$-th person at point $(x_p, y_p)$ (so either $x_p$ equal to some $x_i$ or $y_p$ equal to some $y_j$, or both).\n\nLet's say that a pair of persons form an inconvenient pair if the shortest path from one person to another going only by streets is strictly greater than the Manhattan distance between them.\n\nCalculate the number of inconvenient pairs of persons (pairs $(x, y)$ and $(y, x)$ are the same pair).\n\nLet's recall that Manhattan distance between points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$.",
    "tutorial": "Firstly, let's look at some point $(x_i, y_i)$. Let's find closest to it vertical and horizontal lines. We will name the closest vertical lines from left and right as $lx$ and $rx$ (and $ly$ and $ry$ as closest horizontal lines). So, $lx \\le x \\le rx$ and $ly \\le y \\le ry$ (we can also note that either $lx = rx$ or $ly = ry$). Now, let's note that if for some other point $j$ $(x_j, y_j)$ either $lx < x_j < rx$ or $ly < y_j < ry$ then to reach $j$ from $i$ we must go reach either $lx$ or $rx$ (or, $ly$ or $ry$), so the shortest distance will be strictly greater than the Manhattan distance. If neither $lx < x_j < rx$ nor $ly < y_j < ry$, then we can show that it's always possible to find the shortest path equal to the Manhattan distance. As a result, for each point $(x_i, y_i)$ we should find the number of points $(x_j, y_j)$ such that $j < i$ and $lx < x_j < rx$ or $ly < y_j < ry$. The exception here is when $j$ lies on the same line as $i$, so we should not count such points. We can note that since either $lx = rx$ or $ly = ry$ there is no such point $j$ that $lx < x_j < rx$ and $ly < y_j < ry$ simultaneously, so we can calculate the pairs by $x$ and $y$ coordinates independently. Let's focus on $y$ coordinates (to calculate for $x$ coordinates, we can just swap all coordinates). Let's sort all points by $x$ coordinate. To get rid of the case when points $i$ and $j$ lies on the same vertical street, we can group them by $x$ coordinate and process by group (since we sorted by $x$, groups are just segments). There are no problems with the case when points lie on the same horizontal street, since then $ly = ry$ and there are no other $y_j$ with $ly < y_j < ry$. If we store for each horizontal line $y_j$ the number of point inside the interval $(y_i, y_{i + 1})$ then, when we need for point $i$ calculate the number of points $j$ with $j < i$ and $ly < y_j < ry$, we can just ask for value assigned to $ly$, because $ly$ and $ry$ are consecutive elements in the array $y$. So, we go through each group two times: first collecting answer, then updating values in appropriate $ly$-s. Note, that we can calculate $ly$ and $ry$ with binary search (using built-in functions). The resulting complexity is $O(n + m + k (\\log{k} + \\log{n} + \\log{m}))$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \" \";\n\t\tout << v[i];\n\t}\n\treturn out;\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nint n, m, k;\nvector<int> x, y;\nvector<pt> ps;\n\ninline bool read() {\n\tif(!(cin >> n >> m >> k))\n\t\treturn false;\n\tx.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> x[i];\n\ty.resize(m);\n\tfore (i, 0, m)\n\t\tcin >> y[i];\n\tps.resize(k);\n\tfore (i, 0, k)\n\t\tcin >> ps[i].x >> ps[i].y;\n\t\n\treturn true;\n}\n\ninline void solve() {\n\tli ans = 0;\n\t\n\tfore (_i, 0, 2) {\n\t\tvector<int> cntY(m, 0);\n\t\tsort(all(ps));\n\t\t\n\t\tvector<pt> bord(k);\n\t\t\n\t\tint u = 0;\n\t\twhile (u < k) {\n\t\t\tint v = u;\n\t\t\twhile (v < k && ps[v].x == ps[u].x)\n\t\t\t\tv++;\n\t\t\t\n\t\t\tfore (i, u, v) {\n\t\t\t\tint r = int(lower_bound(all(y), ps[i].y) - y.begin());\n\t\t\t\tint l = r;\n\t\t\t\tif (y[l] > ps[i].y)\n\t\t\t\t\tl--;\n\t\t\t\tassert(y[l] <= ps[i].y && ps[i].y <= y[r]);\n\t\t\t\t\n\t\t\t\tbord[i] = {l, r};\n\t\t\t}\n\t\t\t\n\t\t\tfore (i, u, v) if (bord[i].x < bord[i].y)\n\t\t\t\tans += cntY[bord[i].x];\n\t\t\t\n\t\t\tfore (i, u, v) if (bord[i].x < bord[i].y)\n\t\t\t\tcntY[bord[i].x]++;\n\t\t\t\n\t\t\tu = v;\n\t\t}\n\t\t\n\t\t\n\t\tfore (i, 0, k)\n\t\t\tswap(ps[i].x, ps[i].y);\n\t\tswap(x, y);\n\t\tswap(n, m);\n\t}\n\t\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1569",
    "index": "E",
    "title": "Playoff Restoration",
    "statement": "$2^k$ teams participate in a playoff tournament. The tournament consists of $2^k - 1$ games. They are held as follows: first of all, the teams are split into pairs: team $1$ plays against team $2$, team $3$ plays against team $4$ (exactly in this order), and so on (so, $2^{k-1}$ games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only $2^{k-1}$ teams remain. If only one team remains, it is declared the champion; otherwise, $2^{k-2}$ games are played: in the first one of them, the winner of the game \"$1$ vs $2$\" plays against the winner of the game \"$3$ vs $4$\", then the winner of the game \"$5$ vs $6$\" plays against the winner of the game \"$7$ vs $8$\", and so on. This process repeats until only one team remains.\n\nAfter the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular:\n\n- the winner of the tournament gets place $1$;\n- the team eliminated in the finals gets place $2$;\n- both teams eliminated in the semifinals get place $3$;\n- all teams eliminated in the quarterfinals get place $5$;\n- all teams eliminated in the 1/8 finals get place $9$, and so on.\n\nFor example, this picture describes one of the possible ways the tournament can go with $k = 3$, and the resulting places of the teams:\n\nAfter a tournament which was conducted by the aforementioned rules ended, its results were encoded in the following way. Let $p_i$ be the place of the $i$-th team in the tournament. The hash value of the tournament $h$ is calculated as $h = (\\sum \\limits_{i=1}^{2^k} i \\cdot A^{p_i}) \\bmod 998244353$, where $A$ is some given integer.\n\nUnfortunately, due to a system crash, almost all tournament-related data was lost. The only pieces of data that remain are the values of $k$, $A$ and $h$. You are asked to restore the resulting placing of the teams in the tournament, if it is possible at all.",
    "tutorial": "There are exactly $2^k-1$ games in the tournament, each game has only two possible outcomes. So it's possible to bruteforce all $2^k-1$ possible ways the tournament could go if $k$ is not large. In fact, this solution is fast enough when $k < 5$, so if we somehow can handle the case $k = 5$, we will have a working solution. To handle $k = 5$, let's divide the teams into two groups: teams from $1$ to $16$ and teams from $17$ to $32$. There will be exactly $15$ matches in each group, and the winners of these two groups will play in the finals. The number of possible ways the games in a group can go is just $2^{15}$, so let's try to bruteforce all possible results in each group and somehow \"merge\" them into the results of the whole tournament. The main idea is to rewrite $h$ as $(h_1 + h_2) \\bmod 998244353$, where $h_1 = (\\sum \\limits_{i=1}^{16} i \\cdot A^{p_i}) \\bmod 998244353$, and $h_2 = (\\sum \\limits_{i=17}^{32} i \\cdot A^{p_i}) \\bmod 998244353$, find all possible values for $h_1$ and $h_2$, and choose a pair of values that yields exactly the given value of $h$. We will handle two separate cases: the winner of the first group wins the whole tournament, or the winner of the second group wins the whole tournament. Suppose we are handling the first case (the second is symmetrical). By choosing the results of matches in the first group, we determine the places of the teams from the first group in the whole tournament: the winner of the first group gets place $1$, the team eliminated in the last match of the first group gets place $3$, and so on. It means that by choosing one of the $2^{15}$ possible results in the first group, we can calculate $h_1$. Let's bruteforce these $2^{15}$ combinations of results in the first group and store them in some data structure that allows to check whether some value of $h_1$ is achievable (in the model solution, it's a std::map which maps reachable values of $h_1$ to combinations of results that yield these values). Then, by choosing the results of matches in the second group, we can calculate $h_2$; so the remaining part of the solution is to bruteforce all $2^{15}$ possible results in the second group, calculate $h_2$ for them, and check that $h_1$ such that $(h_1 + h_2) \\bmod 998244353 = h$ can be achieved by choosing the results in the first group. Don't forget to also handle the case when the team which wins in the first group loses in the finals (it is almost the same, but the winner in the first group gets place $2$ and the winner in the second group gets place $1$). The technique I've described here (instead of bruteforcing all possible variants, split the thing we try to bruteforce into two parts, bruteforce them separatedly, and then try to \"merge\" the parts) is called meet-in-the-middle and can be used to solve a large variety of problems.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n \tx += y;\n \twhile(x >= MOD) x -= MOD;\n \twhile(x < 0) x += MOD;\n \treturn x;\n}\n\nint mul(int x, int y)\n{\n \treturn (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n \tint z = 1;\n \twhile(y)\n \t{\n \t \tif(y & 1) z = mul(z, x);\n \t \tx = mul(x, x);\n \t \ty >>= 1;\n \t}\n \treturn z;\n}\n\nvector<int> evaluate(int n, int choice_mask)\n{\n \tint cur_place = n / 2 + 1;\n \tint cur_bit = n - 2;\n \tvector<int> p(n);\n \tvector<int> c(n);\n \tfor(int i = 0; i < n; i++)\n \t\tc[i] = i;\n \twhile(c.size() != 1)\n \t{\n \t\tvector<int> nc;\n \t \tfor(int i = 0; i < c.size(); i += 2)\n \t \t{\n \t \t \tif(choice_mask & (1 << cur_bit))\n \t \t \t{\n \t \t \t\tp[c[i]] = cur_place;\n \t \t \t\tnc.push_back(c[i + 1]);\n \t \t \t}\n \t \t \telse\n \t \t \t{\n \t \t \t\tp[c[i + 1]] = cur_place;\n \t \t \t\tnc.push_back(c[i]);\n \t \t \t}\n \t \t \tcur_bit--;\n \t \t}\n \t \tc = nc;\n \t \tcur_place /= 2;\n  \t\tcur_place++;\n\t}\n\tp[c[0]] = 1;\n\treturn p;\n}\n\nvector<int> adjust(int n, vector<int> p, bool winning)\n{\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(p[i] == 1)\n\t\t{\n\t\t \tif(!winning) p[i]++;\t\n\t\t}\n\t\telse\n\t\t \tp[i] = p[i] * 2 - 1;\n\t}\n\treturn p;\n}\t\n\nint get_hash(int n, vector<int> p, int A, bool partial = false, bool winning = false, int shift = 0)\n{\n\tif(partial)\n\t\tp = adjust(n, p, winning);\n \tint res = 0;\n \tfor(int i = 0; i < n; i++)\n \t\tres = add(res, mul(add(i + 1, shift), binpow(A, p[i])));\n \treturn res;\n}\n\nint main()\n{\n \tint k, A, h;\n \tcin >> k >> A >> h;\n \tif(k <= 4)\n \t{\n \t\tfor(int i = 0; i < (1 << ((1 << k) - 1)); i++)\n \t\t{             \n \t\t\tvector<int> p = evaluate(1 << k, i);\n \t\t\tif(get_hash(1 << k, p, A) == h)\n \t\t\t{\n \t\t \t\tfor(auto x : p) cout << x << \" \";\n \t\t \t\tcout << endl;\n \t\t \t\treturn 0;\n \t\t\t}\n \t\t}\n \t}\n \telse\n \t{\n \t\tint mask_left = -1;\n \t\tint mask_right = -1;\n \t\tbool left_win = false;\n \t\tfor(int c = 0; c < 2; c++)\n \t\t{\n \t\t \tmap<int, int> left_map;\n \t\t \tfor(int i = 0; i < (1 << 16); i++)\n \t\t \t{\n \t\t \t \tvector<int> p = evaluate(16, i);\n \t\t \t \tint left_hash = get_hash(16, p, A, true, c == 0, 0);\n \t\t \t \tleft_map[left_hash] = i;\t\n \t\t \t}\n \t\t \tfor(int i = 0; i < (1 << 16); i++)\n \t\t \t{\n \t\t \t \tvector<int> p = evaluate(16, i);\n \t\t \t \tint right_hash = get_hash(16, p, A, true, c == 1, 16);\n \t\t \t \tint left_hash = add(h, MOD - right_hash);\n \t\t \t \tif(left_map.count(left_hash))\n \t\t \t \t{\n \t\t \t \t \tmask_left = left_map[left_hash];\n \t\t \t \t \tmask_right = i;\n \t\t \t \t \tleft_win = (c == 0);\n \t\t \t \t}\n \t\t \t}\n \t \t}\n \t \tif(mask_left != -1)\n \t\t{\n \t \t\tvector<int> ans_left = evaluate(16, mask_left);\n \t \t\tvector<int> ans_right = evaluate(16, mask_right);\n \t \t\tans_left = adjust(16, ans_left, left_win);\n \t \t\tans_right = adjust(16, ans_right, !left_win);\n \t \t\tfor(auto x : ans_left)\n \t \t\t\tcout << x << \" \";\n \t   \t\tfor(auto x : ans_right)\n \t   \t\t\tcout << x << \" \";\n \t   \t\treturn 0;\n \t\t}        \n \t}\n \tcout << -1 << endl;\n \treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "brute force",
      "hashing",
      "implementation",
      "meet-in-the-middle"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1569",
    "index": "F",
    "title": "Palindromic Hamiltonian Path",
    "statement": "You are given a simple undirected graph with $n$ vertices, $n$ is even. You are going to write a letter on each vertex. Each letter should be one of the first $k$ letters of the Latin alphabet.\n\nA path in the graph is called Hamiltonian if it visits each vertex exactly once. A string is called palindromic if it reads the same from left to right and from right to left. A path in the graph is called palindromic if the letters on the vertices in it spell a palindromic string without changing the order.\n\nA string of length $n$ is good if:\n\n- each letter is one of the first $k$ lowercase Latin letters;\n- if you write the $i$-th letter of the string on the $i$-th vertex of the graph, there will exist a palindromic Hamiltonian path in the graph.\n\nNote that the path doesn't necesserily go through the vertices in order $1, 2, \\dots, n$.\n\nCount the number of good strings.",
    "tutorial": "Let's start with making some implications from the low constraints. What's the upper estimate on the number of answers? $12^{12}$. Too high, let's think of a better one. Using some combinatorics, we can normalize the answers in such a way that there are at most $12$-th Bell's number of them. The method basically defines the components of equal letters. Given a string, we write down the letters in it in the order they appear for the first time in the string and rename the first of them to 'a', the second one to 'b' and so on. Only $4 \\cdot 10^6$ possible answers already. Hmm, but we should also have an even amount of each letter. That is the absolute lowest estimate, and it's equal to about $2 \\cdot 10^6$. What does it exactly mean for a string to be good? There exists a path such that: there's a pair of equal letters that occupy the $1$-st and the $n$-th vertex in the path, a pair on the $2$-nd and $(n-1)$-th and so on. So for each of $2 \\cdot 10^6$ possible answers, we want to determine if there's a way to split the groups of equal letters into pairs of equal letters such that there exists a path through these pairs. Such a path would mean building a palindrome from inside out. A quick estimation on a number of splittings into pairs. The first letter can be matched against $11$ other letters, the first among the unmatched ones - against $9$ other letters and so on. Thus, it's equal to $11 \\cdot 9 \\cdot ... \\cdot 1 = 10395$. For each splitting into pairs, we can determine if there exists a path. That is a straightforward dynamic programming similar to a usual hamiltonian path search. It stores a mask of visited pairs and the last visited pair. For a transition, you want to either go from the first vertex of one pair to the first vertex of another one and from the second to the second, or the other way around. That would take $2^6 \\cdot 6^2$ for each splitting. The only thing left is to propagate the results from the splitting into pairs to splitting into even sized components of equal letters. A splitting into pairs is a splitting into components of size $2$. Let that be a base case for the dp. For every splitting into components, find a component of size at least $4$ (we still have to split it into pairs) and separate it into a component of size $2$ (a pair) and the rest of the component. Moreover, a pair can always be chosen in such a way that one of its elements is the first element of the component. So there are $2 \\cdot 10^6$ states and at most $11$ transitions from each of them. Maybe there's a more convenient way to store the states, but the one I found to be fast enough is hashing the state into a base-$6$ integer (since there are no more than $6$ components, numbered $0$ through $5$) and storing it in a map/hashmap.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nvector<vector<char>> g;\nmap<long long, bool> dp;\n\nvoid brute(int n, vector<int> &p){\n\tint x = find(p.begin(), p.end(), -1) - p.begin();\n\tif (x == int(p.size())){\n\t\tvector<vector<char>> dp2(1 << n, vector<char>(n));\n\t\tvector<int> pos1(n), pos2(n);\n\t\tforn(i, p.size()){\n\t\t\tpos1[p[i]] = pos2[p[i]];\n\t\t\tpos2[p[i]] = i;\n\t\t}\n\t\tforn(i, n) if (g[pos1[i]][pos2[i]]) dp2[1 << i][i] = true;\n\t\tforn(mask, 1 << n) forn(i, n) if (dp2[mask][i]){\n\t\t\tforn(j, n) if (!((mask >> j) & 1)){\n\t\t\t\tdp2[mask | (1 << j)][j] |= (g[pos1[i]][pos1[j]] && g[pos2[i]][pos2[j]]);\n\t\t\t\tdp2[mask | (1 << j)][j] |= (g[pos1[i]][pos2[j]] && g[pos2[i]][pos1[j]]);\n\t\t\t}\n\t\t}\n\t\tforn(i, n) if (dp2[(1 << n) - 1][i]){\n\t\t\tlong long num = 0;\n\t\t\tfor (int x : p) num = num * 6 + x;\n\t\t\tdp[num] = true;\n\t\t\tbreak;\n\t\t}\n\t\treturn;\n\t}\n\tfor (int y = x + 1; y < int(p.size()); ++y) if (p[y] == -1){\n\t\tp[x] = p[y] = n;\n\t\tbrute(n + 1, p);\n\t\tp[x] = p[y] = -1;\n\t}\n}\n\nbool dfs(vector<int> p){\n\tvector<int> used(int(p.size()), -1);\n\tint cnt = 0;\n\tforn(i, p.size()) if (used[p[i]] == -1)\n\t\tused[p[i]] = cnt++;\n\tlong long num = 0;\n\tfor (int& x : p){\n\t\tx = used[x];\n\t\tnum = num * 6 + x;\n\t}\n\tif (dp.count(num)) return dp[num];\n\tbool res = false;\n\tvector<int> cur(cnt);\n\tforn(i, p.size()) ++cur[p[i]];\n\tforn(i, p.size()) if (cur[p[i]] > 2){\n\t\tint x = p[i];\n\t\tfor (int j = i + 1; j < int(p.size()); ++j) if (p[j] == p[i]){\n\t\t\tp[i] = p[j] = cnt;\n\t\t\tif (dfs(p)){\n\t\t\t\tres = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tp[i] = p[j] = x;\n\t\t}\n\t\tbreak;\n\t}\n\treturn dp[num] = res;\n}\n\nvoid brute2(int n, vector<int> &p){\n\tint x = find(p.begin(), p.end(), -1) - p.begin();\n\tif (x == int(p.size())){\n\t\tdfs(p);\n\t\treturn;\n\t}\n\tforn(i, n + 1){\n\t\tfor (int y = x + 1; y < int(p.size()); ++y) if (p[y] == -1){\n\t\t\tp[x] = p[y] = i;\n\t\t\tbrute2(max(n, i + 1), p);\n\t\t\tp[x] = p[y] = -1;\n\t\t}\n\t}\n}\n\nint main() {\n\tint n, m, k;\n\tscanf(\"%d%d%d\", &n, &m, &k);\n\tg.resize(n, vector<char>(n));\n\tforn(_, m){\n\t\tint v, u;\n\t\tscanf(\"%d%d\", &v, &u);\n\t\t--v, --u;\n\t\tg[v][u] = g[u][v] = 1;\n\t}\n\tvector<int> cur(n, -1);\n\tbrute(0, cur);\n\tbrute2(0, cur);\n\tvector<long long> fact(k + 1);\n\tfact[0] = 1;\n\tfor (int i = 1; i <= k; ++i) fact[i] = fact[i - 1] * i;\n\tlong long ans = 0;\n\tfor (auto it : dp) if (it.second){\n\t\tlong long num = it.first;\n\t\tlong long mx = 1;\n\t\twhile (num){\n\t\t\tmx = max(mx, num % 6 + 1);\n\t\t\tnum /= 6;\n\t\t}\n\t\tif (mx <= k){\n\t\t\tans += fact[k] / fact[k - mx];\n\t\t}\n\t}\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "graphs",
      "hashing"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1572",
    "index": "A",
    "title": "Book",
    "statement": "You are given a book with $n$ chapters.\n\nEach chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.\n\nCurrently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.\n\nDetermine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.",
    "tutorial": "There are two main solutions in this task. The first solution simulates the process of reading the book. Let $r_i$ be the number of chapters that need to be understood in order to understand $i$-th chapter. We will keep this array updated during the simulation. Now we will simulate the process by keeping a set of chapters that are ready to be understood. Suppose we have just understood chapter $x$. We will update array $r$ by iterating over all chapters that require $x$ to be understood. If some chapter becomes ready to be understood, we will insert it to the set. Then, we will lowerbound on our set to the next chapter that can be understood and when we hit the end, the answer increases by one and we come back to the beginning. The entire process runs in $O(n \\log n)$. The second solution is more graph based. We will construct a graph, where there is a directed edge from $a$ to $b$ if chapter $b$ is needed to understand chapter $a$. This edge has weight $0$ if $a > b$ and $1$ otherwise. The answer is the length of the longest weighted path in this graph incremented by $1$. If there exists a cycle we should output $-1$. If the graph is a DAG, we can use toposort and a simple DP to calculate the answer. This solution works in $O(n)$",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "graphs",
      "implementation",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1572",
    "index": "B",
    "title": "Xor of 3",
    "statement": "You are given a sequence $a$ of length $n$ consisting of $0$s and $1$s.\n\nYou can perform the following operation on this sequence:\n\n- Pick an index $i$ from $1$ to $n-2$ (inclusive).\n- Change all of $a_{i}$, $a_{i+1}$, $a_{i+2}$ to $a_{i} \\oplus a_{i+1} \\oplus a_{i+2}$ simultaneously, where $\\oplus$ denotes the bitwise XOR operation\n\nFind a sequence of \\textbf{at most} $n$ operations that changes all elements of $a$ to $0$s or report that it's impossible.We can prove that if there exists a sequence of operations of any length that changes all elements of $a$ to $0$s, then there is also such a sequence of length not greater than $n$.",
    "tutorial": "If the xor of all numbers in the array equals $1$ it is impossible to make everything equal to $0$, since the parity of all numbers doesn't change after an operation. From now on we will assume that the xor of all numbers equals $0$. Lets consider the case when $n$ is odd. We can perform operations on positions $1, 3, ... n-4, n-2$. After this for every even $i$, $a_{i-1} = a_i$. Additionally, $a_n = a_{n-1} = a_{n-2} = 0$. Second one is true since the xor of all numbers equals $0$. Now we can perform operations on positions $n-4, n-6, ... 3, 1$. This will make the array equal to $0$. In the case of even $n$ we will find a prefix of odd length and even xor of numbers and call the above solution on it and its respective suffix. If there is no such prefix, the solution doesn't exist. Here is a proof of it. Assume that every prefix of odd length has an odd xor. This means that $a_1 = a_n = 1$ and for every even $i < n$, $a_i = a_{i+1}$. Consider an operation on an even position $i$ (odd is analogous). We know that $a_i = a_{i+1}$ so after this operation $a_i$ and $a_{i+1}$ will be set to $a_{i+2}$. This means that after every operation for every even $i < n$, $a_i = a_{i+1}$ still holds. Thus we will never be able to make $a_1$ equal to $0$ since performing an operation on it won't change it. Summing up, we perform no more than $n$ operations and our solution runs in $O(n)$",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1572",
    "index": "C",
    "title": "Paint",
    "statement": "You are given a $1$ by $n$ pixel image. The $i$-th pixel of the image has color $a_i$. For each color, the number of pixels of that color is \\textbf{at most} $20$.\n\nYou can perform the following operation, which works like the bucket tool in paint programs, on this image:\n\n- pick a color — an integer from $1$ to $n$;\n- choose a pixel in the image;\n- for all pixels connected to the selected pixel, change their colors to the selected color (two pixels of the same color are considered connected if all the pixels between them have the same color as those two pixels).\n\nCompute the minimum number of operations needed to make all the pixels in the image have the same color.",
    "tutorial": "Firstly, we can notice that when we modify a segment of the form $[a, b, a]$ and change it to $[a, a, a]$ by performing the operation on the second element, as opposed to performing the operation first on the third element and then on the second element (like so $[a, b, a] \\to [a, b, b] \\to [a, a, a]$) we avoid using one unnecessary operation. In our solution we will try to maximize the number of operations that we didn't have to perform. Let $dp[i][j]$ be the maximum number of operations that we can avoid on the interval from $i$ to $j$, while making all of its elements have the same color. Then the answer to the problem will be $n-1-dp[1][n]$. For $i \\ge j$ we have $dp[i][j] = 0$ and for $i < j$ $dp[i][j]$ will be the maximum of $dp[i + 1][j]$ and $\\max(1 + dp[i + 1][k - 1] + dp[k][j])$ over $i< k\\le j$ such that $a[i]=a[k]$. It's because we can either not save any operations on the $i$-th element and just take the answer from the interval $[i + 1, j]$ or we can save one operation while coloring the segment from $i$ to $k$ and take the answer from segments $[i+1, k-1]$ and $[k, j]$. Because each color occurs in $a$ at most $20$ times, we can calculate this $dp$ in $O(20n^2)$ which is also our final time complexity.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1572",
    "index": "D",
    "title": "Bridge Club",
    "statement": "There are currently $n$ hot topics numbered from $0$ to $n-1$ at your local bridge club and $2^n$ players numbered from $0$ to $2^n-1$. Each player holds a different set of views on those $n$ topics, more specifically, the $i$-th player holds a positive view on the $j$-th topic if $i\\ \\&\\ 2^j > 0$, and a negative view otherwise. Here $\\&$ denotes the bitwise AND operation.\n\nYou are going to organize a bridge tournament capable of accommodating at most $k$ pairs of players (bridge is played in teams of two people). You can select teams arbitrarily while each player is in at most one team, but there is one catch: two players cannot be in the same pair if they disagree on $2$ or more of those $n$ topics, as they would argue too much during the play.\n\nYou know that the $i$-th player will pay you $a_i$ dollars if they play in this tournament. Compute the maximum amount of money that you can earn if you pair the players in your club optimally.",
    "tutorial": "Let's make a graph in which the vertices are the players and there is an edge of weight $a_i + a_j$ between the $i$-th and the $j$-th player if they can play together. We can notice that the problem can then be solved by finding a matching of size at most $k$ with the biggest sum of weights in this graph. To solve this problem efficiently we can make the following observations: 1. The graph is bipartite. This stands from the fact that if two players disagree at exactly $1$ topic then the numbers of positive views that they hold have different parities. 2. We can limit ourselves to considering only the $(2n-1)(k-1) + 1$ edges with the biggest weights. We can prove this with a proof by contradiction. Firstly, we can notice that if we use a particular edge in the matching then we prohibit ourselves from using at most $2(n-1)$ other edges with each of the matched vertices being incident to exactly $n-1$ of those edges, because each vertex has degree $n$ in this graph. Now we can see that if we were to use an edge that's not one of those $(2n-1)(k-1)+1$ best ones, then we can just replace it with one of those best ones, because we know that at least one of them will not be prohibited. Combining those two observations we are left with a bipartite graph with $O(nk)$ edges and $O(nk)$ vertices in which we can find a matching with maximum cost and size at most $k$ with for example one of the standard min cost max flow algorithms (we can look for a matching of size $k$ because all edges have non-negative weights). The only problem that's left for us to solve is efficiently selecting those best edges. Because there are $O(n2^n)$ edges in total we cannot use a standard sorting algorithm as that would run in $O(n^2 2^n)$. Instead we can for example use the quick select algorithm which solves this problem in $O(n2^n)$. Our final time complexity is then $O(n2^n + nk^2\\log(kn))$.",
    "tags": [
      "flows",
      "graph matchings",
      "graphs",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1572",
    "index": "E",
    "title": "Polygon",
    "statement": "You are given a strictly convex polygon with $n$ vertices.\n\nYou will make $k$ cuts that meet the following conditions:\n\n- each cut is a segment that connects two different nonadjacent vertices;\n- two cuts can intersect only at vertices of the polygon.\n\nYour task is to maximize the area of the smallest region that will be formed by the polygon and those $k$ cuts.",
    "tutorial": "We are going to binary search the answer. Lets say that we want to check whether we can obtain $k+1$ regions with area of at least $w$. From now on a correct cut means a cut that will cut off a region with area of a least $w$. Lets consider some interval of vertices $(i, j)$. We will cut it off virtually using a cut from $i$ to $j$. We would like to know how many correct regions we can obtain by performing cuts only in this interval. The area next to the virtual cut is considered a leftover. Given two sets of correct cuts in this interval it's always optimal to choose the one with more cuts and if they have the same amount of cuts, the one with the bigger leftover. This observation leads us to a dynamic programming solution. Let $dp_{i, j}$ be a pair $(r_{i, j}, l_{i, j})$ where $r_{i, j}$ means the biggest amount of regions and $l_{i, j}$ the biggest leftover we can obtain by performing cuts in the interval $(i, j)$. To calculate this $dp$ we will iterate over all vertices $k$ such that $i < k < j$ and consider vertex $k$ as one of the vertices that are included in the leftover region. This is a simple transition from states $dp_{i, k}$ and $dp_{k, j}$. After we calculate our $dp$ state we can safely cut this interval off if $l_{i, j} \\ge w$. Iff $r_{1, n} \\ge k + 1$ the answer equals at least $w$. This solution runs in $O(n^3 \\log(10^{16}))$.",
    "tags": [
      "binary search",
      "dp",
      "geometry"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1572",
    "index": "F",
    "title": "Stations",
    "statement": "There are $n$ cities in a row numbered from $1$ to $n$.\n\nThe cities will be building broadcasting stations. The station in the $i$-th city has height $h_i$ and range $w_i$. It can broadcast information to city $j$ if the following constraints are met:\n\n- $i \\le j \\le w_i$, and\n- for each $k$ such that $i < k \\le j$, the following condition holds: $h_k < h_i$.\n\nIn other words, the station in city $i$ can broadcast information to city $j$ if $j \\ge i$, $j$ is in the range of $i$-th station, and $i$ is strictly highest on the range from $i$ to $j$ (including city $j$).At the beginning, for every city $i$, $h_i = 0$ and $w_i = i$.\n\nThen $q$ events will take place. During $i$-th event one of the following will happen:\n\n- City $c_i$ will rebuild its station so that its height will be strictly highest among all stations and $w_{c_i}$ will be set to $g_i$.\n- Let $b_j$ be the number of stations that can broadcast information to city $j$. Print the sum of $b_j$ over all $j$ satisfying $l_i \\le j \\le r_i$.\n\nYour task is to react to all events and print answers to all queries.",
    "tutorial": "We will maintain the array $b$ on a range add/sum segment tree. Queries are done then in $O(\\log n)$ per query. Now lets focus on the station rebuilds. Lets maintain an array $w$, which means how far a station can broadcast information including the fact that some stations might block the signal. When a station is rebuild in city $c_i$ we need to perform a $min$ operation on interval $(1, c_i - 1)$ with value $c_i-1$. Next we have to set $w_{c_i}$ to $g_i$. These are all changes to array $w$ that happen during a single rebuild. Now we want to keep array $b$ up to date. We need to know what has been changed and a list of changes to array $w$ is all we need. When setting $w_{c_i}$ to $g_i$ we can add $1$ on interval $(c_i, g_i)$. This is fast enough to do with a single operation on array $b$, since we do this once for every rebuild. Lets say that $w_j$ was decreased as a result of the $min$ operation. To update array $b$ accordingly we should subtract 1 on interval $(c_i, w_j)$. Sadly, performing a subtraction on $b$ for every value in array $w$ that has changed during the $min$ operation one by one is too slow and we can't afford it. Thankfully, we can speed this up. First, we will think how to keep array $w$ updated. We can use segment tree beats to perform the $min$ operation. Recall that during the $min$ operation we get to know what elements and how many times have changed. This is traditionally used to update the sum over interval information. Now we are going to use it in a different way. Lets say that value $r$ was decreased $p$ times in a node where we perform a tag. To keep array $b$ updated we only need subrtact $p$ from interval $(c_i, r)$. Lets think about the complexity now. Segment tree beats with $min$ and $set$ $point$ operations run in amortized $O((n+q) \\log n)$ meaning that we will perform at most this many changes on array $b$. This leads us to our total time complexity of $O((n+q) \\log^2 n)$.",
    "tags": [
      "data structures"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1573",
    "index": "A",
    "title": "Countdown",
    "statement": "You are given a digital clock with $n$ digits. Each digit shows an integer from $0$ to $9$, so the whole clock shows an integer from $0$ to $10^n-1$. The clock will show leading zeroes if the number is smaller than $10^{n-1}$.\n\nYou want the clock to show $0$ with as few operations as possible. In an operation, you can do one of the following:\n\n- decrease the number on the clock by $1$, or\n- swap two digits (you can choose which digits to swap, and they don't have to be adjacent).\n\nYour task is to determine the minimum number of operations needed to make the clock show $0$.",
    "tutorial": "Let $s$ be the sum of all digits. In one operation we can decrease $s$ by at most $1$ and we are finished iff $s = 0$. This leads us to a conclusion that it is always unoptimal to decrease the number on the clock, when the least significant digit shows $0$, since it will cost us at least $9$ more operations. Using this observation, the following strategy turns out to be optimal: if the least significant digit is positive, decrease the number by $1$ if the least significant digit equals $0$, swap it with some positive digit Let $p$ be the number of digits that are positive and aren't the least significant digit. Our answer will be $s + p$. This can be computed in $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1573",
    "index": "B",
    "title": "Swaps",
    "statement": "You are given two arrays $a$ and $b$ of length $n$. Array $a$ contains each \\textbf{odd} integer from $1$ to $2n$ in an arbitrary order, and array $b$ contains each \\textbf{even} integer from $1$ to $2n$ in an arbitrary order.\n\nYou can perform the following operation on those arrays:\n\n- choose one of the two arrays\n- pick an index $i$ from $1$ to $n-1$\n- swap the $i$-th and the $(i+1)$-th elements of the chosen array\n\nCompute the minimum number of operations needed to make array $a$ lexicographically smaller than array $b$.For two different arrays $x$ and $y$ of the same length $n$, we say that $x$ is lexicographically smaller than $y$ if in the first position where $x$ and $y$ differ, the array $x$ has a smaller element than the corresponding element in $y$.",
    "tutorial": "Since the array $a$ has odd numbers and array $b$ has even numbers, then they will differ at the first position no matter how we perform the operations. It follows that in order to make the first array lexicographically smaller than the second one we need to make the first element of $a$ smaller than the first element of $b$. To move the $i$-th element of an array to the first position we can perform the operation on elements $i - 1$, $i - 2$, ..., $2$, $1$, which is optimal. The answer is then the minimum of $i + j - 2$ over all $a_i$, $b_j$ such that $a_i < b_j$. Now we will think how to calculate this effectively. Let $p_i$ be the position of number $i$ in its respective sequence ($a$ for odd and $b$ for even). We will go through the numbers from biggest to smallest. Let $l$ be the position of the leftmost number in sequence $b$ that was already considered. If $i$ is even we will set $l$ to $min(l, p_i)$. If $i$ is odd we will set $answer$ to $min(answer, p_i + l)$. Our total time complexity is then $O(n)$.",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1574",
    "index": "A",
    "title": "Regular Bracket Sequences",
    "statement": "A bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\"), and \")(\", \"(\" and \")\" are not.\n\nYou are given an integer $n$. Your goal is to construct and print \\textbf{exactly $n$} different regular bracket sequences of length $2n$.",
    "tutorial": "There are many ways to solve this problem. The model solution does the following thing: start with the sequence ()()()()...; merge the first $4$ characters into one sequence to get (())()()...; merge the first $6$ characters into one sequence to get ((()))()...; and so on.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    for j in range(n):\n        print(\"()\" * j + \"(\" * (n - j) + \")\" * (n - j))",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1574",
    "index": "B",
    "title": "Combinatorics Homework",
    "statement": "You are given four integer values $a$, $b$, $c$ and $m$.\n\nCheck if there exists a string that contains:\n\n- $a$ letters 'A';\n- $b$ letters 'B';\n- $c$ letters 'C';\n- no other letters;\n- exactly $m$ pairs of adjacent equal letters (exactly $m$ such positions $i$ that the $i$-th letter is equal to the $(i+1)$-th one).",
    "tutorial": "Let's start with a simple assumption. For some fixed values $a, b, c$, the values of $m$ that the answers exist for, make up a range. So there's the smallest possible number of adjacent equal pairs one can construct and the largest one - everything in-between exists as well. The largest number is simple - put all A's, then all B's, then all C's. So this value is $(a - 1) + (b - 1) + (c - 1)$. The smallest number is trickier. Let's instead investigate when it's equal to $0$. WLOG, assume $a \\le b \\le c$. Imagine the following construction. There are $c$ letters C which separate blocks of letters A and B. There are $c-1$ ($c+1$ if you consider the ones to the sides of all letters C, but we want the smallest value, so we shouldn't consider them) such blocks, thus it's possible that each block contains no more than one letter A and no more than one letter B. So letters A and B will never produce adjacent pairs. If there are empty blocks, then there are adjacent letters C. So the condition to still have no empty blocks is to have at least $c-1$ letters A and B in total. If $c - 1 > a + b$, then any extra letter C can only be put adjacent to another letter C, thus producing an extra pair (at least one extra pair, but since we are examining the lower bound, we can always do exactly one). That means that the lower bound is $c - 1 - (a + b)$. Now for the proof of the fact that every value in-between is also achievable. Since we have a construction for $m = 0$, let's try modifying it. Let's reduce the test to $m = 0$ the following way. While $m > 0$, decrease the count of the letter that appears the most by $1$ and decrease $m$ by $1$. Now build the string for $m = 0$ with the reduced values. After that put the letters back, placing them next to the last occurrence of the same letter (there is at least one occurrence of each letter, the proof is trivial). That increases $m$ by $1$ and the count of this letter by $1$. Thus, we'll return to the initial test. Overall complexity: $O(1)$ per testcase.",
    "code": "for _ in range(int(input())):\n\ta, b, c, m = map(int, input().split())\n\ta, b, c = sorted([a, b, c])\n\tprint(\"YES\" if c - (a + b + 1) <= m <= a + b + c - 3 else \"NO\")",
    "tags": [
      "combinatorics",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1574",
    "index": "C",
    "title": "Slay the Dragon",
    "statement": "Recently, Petya learned about a new game \"Slay the Dragon\". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of $n$ heroes, the strength of the $i$-th hero is equal to $a_i$.\n\nAccording to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to $x$, then you have to send a hero with a strength of at least $x$ to kill it. If the dragon's attack power is $y$, then the total strength of the heroes defending the castle should be at least $y$.\n\nThe player can increase the strength of any hero by $1$ for one gold coin. This operation can be done any number of times.\n\nThere are $m$ dragons in the game, the $i$-th of them has defense equal to $x_i$ and attack power equal to $y_i$. Petya was wondering what is the minimum number of coins he needs to spend to defeat the $i$-th dragon.\n\nNote that the task is solved \\textbf{independently for each dragon} (improvements are not saved).",
    "tutorial": "It is enough to consider two cases: whether we will increase the strength of the hero who will kill the dragon or not. If you do not increase the hero's strength, then you have to choose such $i$ that $a_i \\ge x$. Obviously, among such $i$, you have to choose with the minimum value $a_i$, because the strength of defending heroes is equal to $\\sum\\limits_{j=1}^n a_j - a_i$. It remains to increase the total strength of the remaining heroes to $y$. So the required number of coins is equal to $\\max(0, y - (\\sum\\limits_{j=1}^n a_j - a_i))$. If you increase the hero's strength, then you have to choose the maximum value of $a_i$, which is less than $x$. In this case, the required number of coins is $x - a_i$ to increase the strength of the hero who will kill the dragon, plus $\\max(0, y - (\\sum\\limits_{j=1}^n a_j - a_i))$ to increase the strength of the defending heroes. To find the heroes with strength as close to $x$ as possible, you can use binary search (don't forget to sort the heroes beforehand).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing li = long long;\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL); \n  int n;\n  cin >> n;\n  vector<li> a(n);\n  for (auto &x : a) cin >> x;\n  sort(a.begin(), a.end());\n  li sum = accumulate(a.begin(), a.end(), 0LL);\n  int m;\n  cin >> m;\n  while (m--) {\n    li x, y;\n    cin >> x >> y;\n    int i = lower_bound(a.begin(), a.end(), x) - a.begin();\n    li ans = 2e18;\n    if (i > 0) ans = min(ans, (x - a[i - 1]) + max(0LL, y - sum + a[i - 1]));\n    if (i < n) ans = min(ans, max(0LL, y - sum + a[i]));\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "ternary search"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1574",
    "index": "D",
    "title": "The Strongest Build",
    "statement": "Ivan is playing yet another roguelike computer game. He controls a single hero in the game. The hero has $n$ equipment slots. There is a list of $c_i$ items for the $i$-th slot, the $j$-th of them increases the hero strength by $a_{i,j}$. The items for each slot are pairwise distinct and are listed in the increasing order of their strength increase. So, $a_{i,1} < a_{i,2} < \\dots < a_{i,c_i}$.\n\nFor each slot Ivan chooses exactly one item. Let the chosen item for the $i$-th slot be the $b_i$-th item in the corresponding list. The sequence of choices $[b_1, b_2, \\dots, b_n]$ is called a build.\n\nThe strength of a build is the sum of the strength increases of the items in it. Some builds are banned from the game. There is a list of $m$ pairwise distinct banned builds. It's guaranteed that there's at least one build that's not banned.\n\nWhat is the build with the maximum strength that is not banned from the game? If there are multiple builds with maximum strength, print any of them.",
    "tutorial": "Consider the bruteforce solution. You start with a build that contains the most powerful item for each slot. In one move, you swap an item in some slot for the one that is the previous one by power. If a build is not banned, update the answer with its total power (banned builds can be stored in a set, maybe hashset if you hash carefully enough). Notice that if you reach some unbanned build in this bruteforce, it never makes sense to go further. The answer is already updated with this one, and all the lower ones have smaller power. If you code that bruteforce in a smart way (or just add memorization), you won't visit any build twice. How many states will you visit, though? Since you can only proceed if you are standing in a banned build, you will check around $m + mn$ builds. You can code it like that and get accepted. However, there's another way that's easier to code, in my opinion. The optimal answer can be one of only two types. Either it contains the last item of each slot. Or it's some banned build with one item swapped with the previous one. It's easy to see from the solution above. So you can check the first type, then iterate over the banned build and try swapping each slot in it, checking if the resulting build is banned or not. Overall complexity: $O(mn)$ or $O(mn \\log m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n;\nvector<vector<int>> a;\nint m;\nvector<vector<int>> b;\n\nint main() {\n\tscanf(\"%d\", &n);\n\ta.resize(n);\n\tforn(i, n){\n\t\tint c;\n\t\tscanf(\"%d\", &c);\n\t\ta[i].resize(c);\n\t\tforn(j, c) scanf(\"%d\", &a[i][j]);\n\t}\n\tscanf(\"%d\", &m);\n\tb.resize(m);\n\tforn(i, m){\n\t\tb[i].resize(n);\n\t\tforn(j, n){\n\t\t\tscanf(\"%d\", &b[i][j]);\n\t\t\t--b[i][j];\n\t\t}\n\t}\n\tsort(b.begin(), b.end());\n\tvector<int> ult(n);\n\tforn(i, n) ult[i] = int(a[i].size()) - 1;\n\tif (!binary_search(b.begin(), b.end(), ult)){\n\t\tforn(i, n) printf(\"%d \", ult[i] + 1);\n\t\tputs(\"\");\n\t\treturn 0;\n\t}\n\tint mx = 0;\n\tvector<int> ans(n, -1);\n\tforn(i, m){\n\t\tvector<int> tmp = b[i];\n\t\tint sum = 0;\n\t\tforn(j, n) sum += a[j][tmp[j]];\n\t\tforn(j, n) if (tmp[j] != 0){\n\t\t\t--tmp[j];\n\t\t\tif (!binary_search(b.begin(), b.end(), tmp) && sum - a[j][tmp[j] + 1] + a[j][tmp[j]] > mx){\n\t\t\t\tmx = sum - a[j][tmp[j] + 1] + a[j][tmp[j]];\n\t\t\t\tans = tmp;\n\t\t\t}\n\t\t\t++tmp[j];\n\t\t}\n\t}\n\tforn(i, n){\n\t\tprintf(\"%d \", ans[i] + 1);\n\t}\n\tputs(\"\");\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "hashing",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1574",
    "index": "E",
    "title": "Coloring",
    "statement": "A matrix of size $n \\times m$, such that each cell of it contains either $0$ or $1$, is considered beautiful if the sum in every contiguous submatrix of size $2 \\times 2$ is exactly $2$, i. e. every \"square\" of size $2 \\times 2$ contains exactly two $1$'s and exactly two $0$'s.\n\nYou are given a matrix of size $n \\times m$. Initially each cell of this matrix is empty. Let's denote the cell on the intersection of the $x$-th row and the $y$-th column as $(x, y)$. You have to process the queries of three types:\n\n- $x$ $y$ $-1$ — clear the cell $(x, y)$, if there was a number in it;\n- $x$ $y$ $0$ — write the number $0$ in the cell $(x, y)$, \\textbf{overwriting the number that was there previously (if any)};\n- $x$ $y$ $1$ — write the number $1$ in the cell $(x, y)$, \\textbf{overwriting the number that was there previously (if any)}.\n\nAfter each query, print the number of ways to fill the empty cells of the matrix so that the resulting matrix is beautiful. Since the answers can be large, print them modulo $998244353$.",
    "tutorial": "For best understanding we replace the matrix with $0$ and $1$ with the matrix with black and white cells. At first let's consider matrix if there are two adjacent horizontal cell with same color (for example cells $(5, 5)$ and $(5, 6)$ are black). Then the cells $(4, 5)$, $(4, 6)$, $(6, 5)$ and $6, 6$ must have the opposite color (white); the cells $(3, 5)$, $(3, 6)$, $(7, 5)$ and $7, 6$ must have the same color (black) and so on. So, two adjacent horizontal cells generate the vertical strip of width two. Reciprocally two adjacent vertical cells generate the horizontal strip of width two. And if simultaneously there are horizontal strip and vertical strip then the answer is $0$ (because they contradict each other). If there are two cells of same color in the same row with even number of cells between them (for example $(2, 2)$ and $(2, 7)$ with four cells between them) then there is the vertical strip (because there are always two adjacent cells with same color between them). The same is correct for horizontal strips. Now let's consider how the matrix look if there are the vertical strip. It look like a chess board of size $n \\times m$, but colors of some verticals are inverted. The same is correct if there are the horizontal strips. How we can quickly understand that there are two cells of same color in the same row with even number of cells between them? For this mentally color the matrix in a checkerboard pattern. And then one of this cells has the same color witch cells in chessboard, and the other has the opposite color witch cells in chessboard. For calculating the answer we have maintain to the following values: The color of each colored cell; The row and columns containing the cells of same color with even number of cells between them; And the number of row and columns containing at least one colored cell (for calculating the number of beautiful matrix).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int N = 1'000'009;\n\nint sum (int a, int b) {\n    int res = a + b;\n    if (res < 0) res += MOD;\n    if (res >= MOD) res -= MOD;\n    return res;\n}\n\nint n, m, k;\nmap <pair <int, int>, char> c;\nint cntr[N][2], cntc[N][2];\nint cntx[2];\nset <int> badr, badc;\nset<int> ur, uc;\nint p2[N];\n\nvoid upd2(int pos, int col, int add, int cnt[N][2], set <int> &bad, set<int> &u) {\n    cnt[pos][col] += add;\n    assert(cnt[pos][col] >= 0);\n    \n    if (cnt[pos][0] > 0 && cnt[pos][1] > 0){\n        if (!bad.count(pos))\n            bad.insert(pos);\n    } else {\n        if (bad.count(pos))\n            bad.erase(pos);\n    }\n    \n    if (cnt[pos][0] > 0 || cnt[pos][1] > 0){\n        if (!u.count(pos))\n            u.insert(pos);\n    } else {\n        if (u.count(pos))\n            u.erase(pos);\n    }\n}\n\nvoid upd(int x, int y, int t) {\n    int col = (x & 1) ^ (y & 1);\n    if (c.count({x, y})) {\n        int ncol = col ^ c[{x, y}];\n        --cntx[ncol];\n        upd2(x, ncol, -1, cntr, badr, ur);\n        upd2(y, ncol, -1, cntc, badc, uc);\n        c.erase({x, y});\n    }\n    \n    if (t == -1)\n        return;\n        \n    int ncol = col ^ t;\n    ++cntx[ncol];\n    upd2(x, ncol, 1, cntr, badr, ur);\n    upd2(y, ncol, 1, cntc, badc, uc);\n    c[{x, y}] = t;\n}\n\nint main(){\n    p2[0] = 1;\n    for (int i = 1; i < N; ++i)\n        p2[i] = sum(p2[i - 1], p2[i - 1]);\n        \n    scanf(\"%d%d%d\", &n, &m, &k);\n    for (int i = 0; i < k; ++i) {\n        int x, y, t;\n        scanf(\"%d %d %d\", &x, &y, &t);\n        --x, --y;\n        upd(x, y, t);\n        \n        int res = 0;\n        if(badr.size() > 0 && badc.size() > 0) {\n            res = 0;\n        } else if (badr.size() > 0) {\n            assert(m - uc.size() >= 0);\n            res = p2[m - uc.size()];\n        } else if (badc.size() > 0) {\n            assert(n - ur.size() >= 0);\n            res = p2[n - ur.size()];\n        } else {\n            if (ur.size() == 0 && uc.size() == 0)\n                res = sum(sum(p2[n], p2[m]), -2);\n            else {\n                assert(m - uc.size() >= 0);\n                res = sum(res, p2[m - uc.size()]);\n                assert(n - ur.size() >= 0);\n                res = sum(res, p2[n - ur.size()]);\n                if (cntx[0] == 0 || cntx[1] == 0) {\n                    assert(cntx[0] != 0 || cntx[1] != 0);\n                    res = sum(res, -1);\n                }\n            }\n        }\n        \n        printf(\"%d\\n\", res);\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1574",
    "index": "F",
    "title": "Occurrences",
    "statement": "A subarray of array $a$ from index $l$ to the index $r$ is the array $[a_l, a_{l+1}, \\dots, a_{r}]$. The number of occurrences of the array $b$ in the array $a$ is the number of subarrays of $a$ such that they are equal to $b$.\n\nYou are given $n$ arrays $A_1, A_2, \\dots, A_n$; the elements of these arrays are integers from $1$ to $k$. You have to build an array $a$ consisting of $m$ integers from $1$ to $k$ in such a way that, for \\textbf{every} given subarray $A_i$, the number of occurrences of $A_i$ in the array $a$ is \\textbf{not less} than the number of occurrences of each non-empty subarray of $A_i$ in $a$. Note that if $A_i$ doesn't occur in $a$, and no subarray of $A_i$ occurs in $a$, this condition is still met for $A_i$.\n\nYour task is to calculate the number of different arrays $a$ you can build, and print it modulo $998244353$.",
    "tutorial": "What does the condition \"the number of occurrences of $A_i$ in the array $a$ is not less than the number of occurrences of each non-empty subarray of $A_i$ in $a$\" mean? First, if $A_i$ contains two (or more) equal elements, then any occurrence of $A_i$ introduces at least two occurrences of that element; so any element in $A_i$ is forbidden (it should not appear in the resulting array). Now let's consider an array $A_i$ such that every its element is unique. Every element of $A_i$ should be a part of an occurrence of $A_i$ in the array $a$. Let's rephrase this condition as follows: for each occurrence of $A_{i,j}$ in $a$, the next element in $a$ is $A_{i,j+1}$, and vice versa: for each occurrence of $A_{i,j+1}$ in $a$, the previous element in $a$ is $A_{i,j}$. Let's build a directed graph on $k$ vertices, where an arc from vertex $x$ to vertex $y$ means that each occurrence of $x$ should be followed by $y$, and each occurrence of $y$ should be preceded by $x$ (i. e. $x$ is followed by $y$ in some array $A_i$). Let's consider the weakly connected components in this graph. If we have at least one occurrence of some element from a component in $a$, it means that all other elements from this component occur in $a$ as well. Some integers from $1$ and $k$ are \"bad\" in a sense that we cannot uniquely determine which element should follow/precede them (in terms of graph theory, it means that the in-degree or out-degree of a vertex is at least $2$). Since by picking one element from a component, we will have to use all elements from a component, it means that if a component contains at least one \"bad\" element, the whole component will be \"bad\" - we cannot use any element from it. If a component is a cycle, no vertex has in-degree or out-degree greater than $1$, but the component is still \"bad\" since, if we include at least one element from $a$, we cannot finish the cycle - the array $a$ is not infinite, but the cycle is. Okay, the only \"good\" components are chains. When we use an element from a chain in $a$, all elements from this chain will be used in exactly the same order that they were in the chain; so, $a$ should consist of some chains linked together (chains may repeat, and some chains may be absent from $a$). We can write a solution with dynamic programming: let $dp_i$ be the number of ways to construct an array of length $i$ using these chains. The transitions are as follows: $dp_i = \\sum\\limits_{j=1}^{c} dp_{i - len_j}$, where $c$ is the number of chains, and $len_j$ is the length of the $j$-th chain. The number of chains is up to $k$, and the number of states in dynamic programming is $m + 1$, so the solution works in $O(mk)$, which is too slow. We can improve it with the following two facts: all chains of the same length are indistinguishable; there are $O(\\sqrt{k})$ different lengths of chains. So, instead of iterating on the chains themselves in dynamic programming, we will iterate on the lengths of the chains (considering only lengths having at least one chain), and process all chains of the same length as one by introducing a multiplier in our dynamic programming: $dp_i = \\sum \\limits_{j=1}^{k} dp_{i - j} \\cdot cnt_j$, where $cnt_j$ is the number of chains of length $j$. That way, our dynamic programming will work in $O(m \\sqrt{k})$ if we skip the values of $j$ with $cnt_j = 0$.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n \tx += y;\n \twhile(x >= MOD) x -= MOD;\n \twhile(x < 0) x += MOD;\n \treturn x;\n}\n\nint mul(int x, int y)\n{\n \treturn (x * 1ll * y) % MOD;\n}\n\nint main()\n{\n\tint n, m, k;\n\tscanf(\"%d %d %d\", &n, &m, &k);\n\tvector<vector<int>> A(n);\n\tvector<int> bad_num(k);\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint c;\n\t\tscanf(\"%d\", &c);\n\t\tA[i].resize(c);\n\t\tfor(int j = 0; j < c; j++)\n\t\t{\n\t\t\tscanf(\"%d\", &A[i][j]); \t\n\t\t\tA[i][j]--;\n\t\t}\n\t}\n\n\tfor(int i = 0; i < n; i++)\n\t{\n\t \tif(set<int>(A[i].begin(), A[i].end()).size() != A[i].size())\n\t \t{\n\t \t \tfor(auto x : A[i])\n\t \t \t\tbad_num[x] = 1;\n\t \t}\n\t}\n\tvector<vector<int>> nxt(k);\n\tvector<vector<int>> prv(k);\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j + 1 < A[i].size(); j++)\n\t\t{\n\t\t \tnxt[A[i][j]].push_back(A[i][j + 1]);\n\t\t \tprv[A[i][j + 1]].push_back(A[i][j]);\n\t\t}\n\n\tfor(int i = 0; i < k; i++)\n\t{\n\t    sort(nxt[i].begin(), nxt[i].end());\n\t    sort(prv[i].begin(), prv[i].end());\n\t \tnxt[i].erase(unique(nxt[i].begin(), nxt[i].end()), nxt[i].end());\n\t \tprv[i].erase(unique(prv[i].begin(), prv[i].end()), prv[i].end());\n\t}\n\n\tvector<int> used(k, 0);\n\tvector<int> cnt(k + 1, 0);\n\tfor(int i = 0; i < k; i++)\n\t{\n\t\tif(used[i]) continue;\n\t \tqueue<int> q;\n\t \tvector<int> comp;\n\t \tq.push(i);\n\t \tused[i] = 1;\n\t \twhile(!q.empty())\n\t \t{\n\t \t\tint z = q.front();\n\t \t\tq.pop();\n\t \t\tcomp.push_back(z);\n\t \t \tfor(auto x : nxt[z])\n\t \t \t\tif(!used[x])\n\t \t \t\t{\n\t \t \t\t \tused[x] = 1;\n\t \t \t\t \tq.push(x);\n\t \t \t\t}\n\t \t \tfor(auto x : prv[z])\n\t \t \t\tif(!used[x])\n\t \t \t\t{\n\t \t \t\t \tused[x] = 1;\n\t \t \t\t \tq.push(x);\n\t \t \t\t}\n\t \t}\n\t \tbool bad = false;\n\t \tint cnt_beg = 0;\n\t \tfor(auto x : comp)\n\t \t{\n\t \t \tif(prv[x].empty())\n\t \t \t\tcnt_beg++;\n\t \t \tif(prv[x].size() > 1 || nxt[x].size() > 1 || bad_num[x])\n\t \t \t\tbad = true;\n\t \t}\n\t \tbad |= (cnt_beg == 0);\n\t \tif(!bad)\n\t \t\tcnt[comp.size()]++;\n\t}\n\tvector<int> nonzero;\n\tfor(int i = 1; i <= k; i++)\n\t\tif(cnt[i] > 0)\n\t\t\tnonzero.push_back(i);\n\tvector<int> dp(m + 1, 0);\n\tdp[0] = 1;\n\tfor(int i = 1; i <= m; i++)\n\t\tfor(auto x : nonzero)\n\t\t \tif(x <= i)\n\t\t \t\tdp[i] = add(dp[i], mul(cnt[x], dp[i - x]));\n\n\tprintf(\"%d\\n\", dp[m]);\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "dsu",
      "fft",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1575",
    "index": "A",
    "title": "Another Sorting Problem",
    "statement": "Andi and Budi were given an assignment to tidy up their bookshelf of $n$ books. Each book is represented by the book title — a string $s_i$ numbered from $1$ to $n$, each with length $m$. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending.\n\nSettling their fight, they decided to combine their idea and sort it asc-desc-endingly, where \\textbf{the odd-indexed characters will be compared ascendingly}, and \\textbf{the even-indexed characters will be compared descendingly}.\n\nA string $a$ occurs before a string $b$ in asc-desc-ending order if and only if in the first position where $a$ and $b$ differ, the following holds:\n\n- if it is an odd position, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$;\n- if it is an even position, the string $a$ has a letter that appears later in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Observe that the even-indexed character of the string can be transformed from A-Z to Z-A. E.g. for the first example: AA  \\rightarrow  AZ AB  \\rightarrow  AY BB  \\rightarrow  BY BA  \\rightarrow  BZ AZ  \\rightarrow  AA Now, you can use any known algorithms to sort the string as usual. You can sort it in linear time with trie, or std::sort in $O(nm \\log n)$ time. Time Complexity : $O(nm)$ or $O(nm \\log n)$",
    "tags": [
      "data structures",
      "sortings",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1575",
    "index": "B",
    "title": "Building an Amusement Park",
    "statement": "Mr. Chanek lives in a city represented as a plane. He wants to build an amusement park in the shape of a circle of radius $r$. The circle must \\textbf{touch} the origin (point $(0, 0)$).\n\nThere are $n$ bird habitats that can be a photo spot for the tourists in the park. The $i$-th bird habitat is at point $p_i = (x_i, y_i)$.\n\nFind the minimum radius $r$ of a park with \\textbf{at least} $k$ bird habitats inside.\n\nA point is considered to be inside the park if and only if the distance between $p_i$ and the center of the park is less than or equal to the radius of the park. Note that the center and the radius of the park do not need to be integers.\n\n\\textbf{In this problem, it is guaranteed that the given input always has a solution with $r \\leq 2 \\cdot 10^5$}.",
    "tutorial": "We can binary search the answer $r$ in this case. Here, bird's habitats are referred as points. First of all, define a function $c(x)$ as the maximum number of points that can be covered with a circle of radius $x$ through the origin. Define the park as a circle with radius $x$ and $\\theta$, in a polar coordinate representation. Observe that each points have a radial/angle segment of which the point $p_i$ will be inside the circle if and only if $\\theta$ belongs to the radial segment of $[L_{p_{i}}, R_{p_{i}}]$, where $-\\pi < L_{p_{i}}, R_{p_{i}} \\leq \\pi$. E.g for $x = 4$, Observe the $L_{p_{3}}$ for the $p_3 = (1, 5)$. The green radial segment $e$ represents the $[L_{p_{3}}, R_{p_{3}}]$. Now, to find the two end points $B_i$ and $C_i$ of the arc for each point $p_i$. Because the triangle that is made by those 3 points are an isosceles triangle, simply find the angle where the distance of $p_i$ and $B_i$ equals to $x$, that is $\\Delta = \\cos^{-1}\\dfrac{||p_i||}{2r}$. Now the segment can be found by calculating the angle of $\\tan^{-1}p_i \\pm \\Delta$. Do a radial sweep to find the maximum number of points. Time complexity is $O(n \\log n \\cdot \\log(\\text{MAX_R} \\cdot \\epsilon^{-1}))$. We can optimize the binary search part further, since we only need $\\log(\\epsilon^{-1})$ most significant digits. We can binary search the position of the first non-zero digit in $O(\\log\\log(\\text{MAX_R}))$, then use a normal binary search with $O(\\log(\\epsilon^{-1}))$ steps. In practice, this improves the time by around a factor of 2. Time complexity: $O(n \\log n \\cdot \\log(\\text{MAX_R} \\cdot \\epsilon^{-1}))$ or $O(n \\log n \\cdot \\log(\\log(\\text{MAX_R}) \\cdot \\epsilon^{-1}))$.",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1575",
    "index": "C",
    "title": "Cyclic Sum",
    "statement": "Denote a cyclic sequence of size $n$ as an array $s$ such that $s_n$ is adjacent to $s_1$. The segment $s[r, l]$ where $l < r$ is the concatenation of $s[r, n]$ and $s[1, l]$.\n\nYou are given an array $a$ consisting of $n$ integers. Define $b$ as the cyclic sequence obtained from concatenating $m$ copies of $a$. Note that $b$ has size $n \\cdot m$.\n\nYou are given an integer $k$ where $k = 1$ or $k$ is a prime number. Find the number of different segments in $b$ where the sum of elements in the segment is divisible by $k$.\n\n\\textbf{Two segments are considered different if the set of indices of the segments are different}. For example, when $n = 3$ and $m = 2$, the set of indices for segment $s[2, 5]$ is $\\{2, 3, 4, 5\\}$, and for segment $s[5, 2]$ is $\\{5, 6, 1, 2\\}$. In particular, the segments $s[1, 6], s[2,1], \\ldots, s[6, 5]$ are considered as the same segment.\n\nOutput the answer modulo $10^9 + 7$.",
    "tutorial": "Let a valid segment $[l, r]$ be a segment in $b$ where the sum of elements in the segment is divisible by $k$. We can try to solve a simpler problem: find the number of valid segments such that the right endpoint ends at $1$. That is, the valid segments $[l, 1]$ ($1 \\leq l \\leq n \\cdot m$). Let $prefix(p) = \\sum_{i=1}^{p} {b[i]}$ and $cnt$ be an array where the $cnt[i]$ denote the number of $p$ ($1 \\leq p \\leq n \\cdot m$) such that $i \\equiv prefix(p) \\mod k$. Notice that the number of valid segment $[l, 1]$ is $cnt[prefix(n \\cdot m) + b[1]]$. Furthermore, the number of valid segments $[l, 1 + x \\cdot n]$ ($0 \\leq x \\leq m-1$) is the same as the number of valid segment $[l, 1]$. Thus, we only need to calculate the number of valid segments for $[l, r]$ with $1 \\leq l \\leq n \\cdot m$ and $1 \\leq r \\leq n$, then multiply the final result by $m$. First we need to find the array $cnt$. Let $sum = prefix(n)$. When $sum \\equiv 0 \\mod k$, we can find $cnt$ in a straightforward manner. Now assume $sum \\not\\equiv 0 \\mod k$. For a fixed $i$, let's try to find the contribution of $prefix(i + x \\cdot n)$ for all $0 \\leq x \\leq m-1$ to $cnt$ at once. Observe that if one make a directed graph with $(i, \\ (i + sum) \\bmod k)$ for $0 \\leq i < k$ as the edges, one will get a cycle of length $k$ (since $k$ is prime) as the result. To find the contribution of $prefix(i + x \\cdot n)$, we can do a range add operation on this cycle. This can be done with offline prefix sums (prefix difference) in $O(k)$ total. Now that we have the array $cnt$, we can find the number of valid segments that ends at $1$ easily. To find valid segment that ends at index $2$, we can modify $cnt$ by adding $prefix(n \\cdot m) + b[1]$ to the counter and removing $b[1]$. We do this for all $1 \\leq r \\leq n$. This solution is also applicable for arbitary $k$, albeit multiple cycles will be generated and must be handled separatedly. Time complexity: $O(n + k)$",
    "tags": [
      "data structures",
      "fft",
      "number theory"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1575",
    "index": "D",
    "title": "Divisible by Twenty-Five",
    "statement": "Mr. Chanek has an integer represented by a string $s$. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit.\n\nMr. Chanek wants to count the number of possible integer $s$, where $s$ is divisible by $25$. Of course, $s$ must not contain any leading zero. He can replace the character _ with any digit. He can also replace the character X with any digit, but it must be the same for every character X.\n\nAs a note, a leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, 0025 has two leading zeroes. An exception is the integer zero, (0 has no leading zero, but 0000 has three leading zeroes).",
    "tutorial": "There are no dirty tricks to solve this problem. Brute force all possible number between $i \\in [10^{|s| - 1}, 10^{|s|} - 1]$, with step $i := i + 25$. You might want to handle when $|s| = 1$, because $0$ is a valid $s$, if possible. For easier implementation, you can use the std::to_string(s) in C++. It is also possible to solve it in $O(|s|)$ by case analysis. Time complexity: $O(\\frac{1}{25} \\cdot |s| \\cdot 10^{|s|})$ or $O(|s|)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define sz(x) (int)(x).size()\ntypedef long long LL;\nLL expo(LL a, LL b){\n  // a %= MOD; // USE THIS WHEN N IS REALLY BIG!\n  LL ret = 1;\n  while(b > 0){\n    if(b&1) ret = (ret*a);\n    a = (a*a); b >>= 1;\n  }\n  return ret;\n}\n\nint main(){\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  string s; cin >> s;\n  int low = expo(10, sz(s) - 1);\n  int high = expo(10, sz(s)) - 1;\n  if(low == 1) low--;\n  while(low%25) low++;\n  int ans = 0;\n  for(;low <= high;low += 25){\n    string current = to_string(low);\n    char xval = '-';\n    bool can = 1;\n    for(int i = 0;i < sz(s);i++){\n      if(s[i] == '_') continue;\n      if(s[i] == 'X'){\n        if(xval != '-' && xval != current[i]){\n          can = 0;\n          break;\n        }\n        xval = current[i];\n      }else if(s[i] != current[i]){\n        can = 0;\n        break;\n      }\n    }\n    ans += can;\n  }\n  cout << ans << endl;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1575",
    "index": "E",
    "title": "Eye-Pleasing City Park Tour",
    "statement": "There is a city park represented as a tree with $n$ attractions as its vertices and $n - 1$ rails as its edges. The $i$-th attraction has happiness value $a_i$.\n\nEach rail has a color. It is either black if $t_i = 0$, or white if $t_i = 1$. Black trains only operate on a black rail track, and white trains only operate on a white rail track. If you are previously on a black train and want to ride a white train, or you are previously on a white train and want to ride a black train, you need to use $1$ ticket.\n\nThe path of a tour must be a simple path — it must not visit an attraction more than once. You do not need a ticket the first time you board a train. You only have $k$ tickets, meaning \\textbf{you can only switch train types at most $k$ times}. In particular, you do not need a ticket to go through a path consisting of one rail color.\n\nDefine $f(u, v)$ as the sum of happiness values of the attractions in the tour $(u, v)$, which is a simple path that starts at the $u$-th attraction and ends at the $v$-th attraction. Find the sum of $f(u,v)$ for all valid tours $(u, v)$ ($1 \\leq u \\leq v \\leq n$) that does not need more than $k$ tickets, modulo $10^9 + 7$.",
    "tutorial": "We can use centroid decomposition to solve this problem. Suppose we find the centroid $cen$ of the tree, and root the tree at $cen$. We consider each subtree of the children of $cen$ as different groups of vertices. We want to find the sum of $f(u,v)$ for all valid tours, such that $u$ and $v$ are from different groups. We can solve this with basic inclusion-exclusion. We count the sum of $f(u,v)$ where the path $u \\to cen \\to v$ uses less than $k$ tickets, without caring which group $u,v$ belongs to. Then, we can subtract it by only considering $u \\to cen \\to v$ where $u,v$ belongs from the same group. Define $cost(u)$ as the number of tickets you need to go from $u$ to $cen$. For a fixed set of vertices $S$, you can count $f(u,v)$ where $cost(u) + cost(v) + z \\leq k$ with prefix sums. Note that $z$ depends on whether the last edge of the path from $u \\to cen$ and $v \\to cen$ has different colors. We can do all of these in $O(|S|)$. We use the solution above while setting $S$ as the set of all vertices in $cen$'s subtree, or the set of vertices with the same group. Because the depth of a centroid tree is $O(\\log n)$, the overall complexity of the solution is $O(n \\log n)$.",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1575",
    "index": "F",
    "title": "Finding Expected Value",
    "statement": "Mr. Chanek opened a letter from his fellow, who is currently studying at Singanesia. Here is what it says.\n\nDefine an array $b$ ($0 \\leq b_i < k$) with $n$ integers. While there exists a pair $(i, j)$ such that $b_i \\ne b_j$, do the following operation:\n\n- Randomly pick a number $i$ satisfying $0 \\leq i < n$. Note that each number $i$ has a probability of $\\frac{1}{n}$ to be picked.\n- Randomly Pick a number $j$ satisfying $0 \\leq j < k$.\n- Change the value of $b_i$ to $j$. It is possible for $b_i$ to be changed to the same value.\n\nDenote $f(b)$ as the expected number of operations done to $b$ until all elements of $b$ are equal.\n\nYou are given two integers $n$ and $k$, and an array $a$ ($-1 \\leq a_i < k$) of $n$ integers.\n\nFor every index $i$ with $a_i = -1$, replace $a_i$ with a random number $j$ satisfying $0 \\leq j < k$. Let $c$ be the number of occurrences of $-1$ in $a$. There are $k^c$ possibilites of $a$ after the replacement, each with equal probability of being the final array.\n\nFind the expected value of $f(a)$ modulo $10^9 + 7$.\n\nFormally, let $M = 10^9 + 7$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.\n\nAfter reading the letter, Mr. Chanek gave the task to you. Solve it for the sake of their friendship!",
    "tutorial": "We can use this trick, which is also explained below. Suppose $a_i \\neq -1$ for now. We want to find a function $F(a)$ such that $\\mathbb{E}(F_{t + 1} - F_t | F_t) = -1$, where $F_t$ is the value of $F(a)$ at time $t$. If we can find such a function, then the expected stopping time is equal to $F(a_0) - F(a_T)$, where $a_0$ is the initial array before doing any operation, and $a_T$ is the final array where we don't do any more operation (that is, all elements of $a_T$ are equal). Suppose $occ(x)$ is the number of occurrences of $x$ in the current array, for some $0 \\leq x < k$. It turns out we can find such $F$ satisfying $F = \\sum_{x = 0}^{k - 1} f(occ(x))$ for some function $f$. We now try to find $f$. Suppose we currently have $a_t$, and we want to find the expected value of $F(a_{t + 1})$. There are two cases to consider: $\\forall x, occ_{t + 1}(x) = occ_t(x)$ if $a_i$ doesn't change when doing the operation. This happens with probability $\\frac{1}{k} \\cdot \\frac{occ_t(x)}{n}$ for each $x$. Otherwise, there exist some $x, y$ ($x \\neq y$) such that $occ_{t + 1}(x) = occ_t(x) - 1$ and $occ_{t + 1}(y) = occ_t(y) + 1$. This happens if initially $a_i = x$, then by doing the operation we change it to $y$. This happens with probability $\\frac{1}{k} \\cdot \\frac{occ_t(x)}{n}$ for each $x,y$. Thus, $\\begin{split} & \\mathbb{E}(F_{t + 1} - F_t | F_t) = -1\\\\ \\implies & \\sum_{i = 0}^{k - 1} f(occ_{t + 1}(i)) - \\sum_{i = 0}^{k - 1}f(occ_t(x)) = -1\\\\ \\implies & \\sum_{i = 0}^{k - 1} f(occ_{t + 1}(i)) = \\sum_{i = 0}^{k - 1}f(occ_t(i)) - 1\\\\ \\implies & \\frac{1}{k}\\sum_{i = 0}^{k - 1}f(occ_t(i)) + \\sum_{x = 0}^{k - 1}\\sum_{y = 0}^{k - 1}[x \\neq y]\\frac{occ_t(x)}{nk}\\Big( \\sum_{i = 0}^{k - 1}f(occ_t(i)) - f(occ_t(x)) - \\\\ & f(occ_t(y)) + f(occ_t(x) - 1) + f(occ_t(y) + 1)\\Big) = \\sum_{i = 0}^{k - 1}f(occ_t(i)) - 1\\\\ \\implies & \\sum_{x = 0}^{k - 1}\\sum_{y = 0}^{k - 1}[x \\neq y]\\frac{occ_t(x)}{nk}\\Big( - f(occ_t(x)) - f(occ_t(y)) + f(occ_t(x) - 1) + f(occ_t(y) + 1)\\Big) = - 1\\\\ \\implies & \\sum_{x = 0}^{k - 1}\\frac{(k - 1)occ_t(x)}{nk} \\Big(f(occ_t(x) - 1) - f(occ_t(x))\\Big) + \\frac{n - occ_t(x)}{nk}\\Big( f(occ_t(x) + 1) - f(occ_t(x)) \\Big) = - 1\\\\ \\implies & \\sum_{x = 0}^{k - 1}\\frac{(k - 1)occ_t(x)}{nk} \\Big(f(occ_t(x) - 1) - f(occ_t(x))\\Big) + \\frac{n - occ_t(x)}{nk}\\Big( f(occ_t(x) + 1) - f(occ_t(x)) \\Big) + \\frac{occ_t(x)}{n} = 0\\\\ \\end{split}$ Suppose $a = occ_t(x)$. If we can find $f$ such that $\\frac{(k - 1)a}{nk} \\Big(f(a - 1) - f(a)\\Big) + \\frac{n - a}{nk}\\Big( f(a + 1) - f(a) \\Big) + \\frac{a}{n} = 0$ then $f$ satisfies $F$. $\\frac{(k - 1)a}{nk} \\Big(f(a - 1) - f(a)\\Big) + \\frac{n - a}{nk}\\Big( f(a + 1) - f(a) \\Big) + \\frac{a}{n} = 0\\\\ (k - 1)a \\Big(f(a - 1) - f(a)\\Big) + (n - a)\\Big( f(a + 1) - f(a) \\Big) + ak = 0\\\\ (k - 1)af(a - 1) - (k - 1)af(a) + (n - a)f(a + 1) - (n - a)f(a) + ak = 0\\\\ f(a + 1) = \\frac{1}{a - n}\\Big( (k - 1)af(a - 1) + (2a - ak - n)f(a) + ak \\Big)$ So we can set $f$ to any function that satisfies the recursive formula above, and then derive $F$. To handle $a_i = -1$, note that $F$ depends only on the occurrence of each value $x$ ($0 \\leq x < k$), and each of them is independent. Therefore, we can count the contribution for each $x$ towards all possible final arrays separately. This is easy to do in $O(n)$. Moreoever, there is only $O(\\sqrt{n})$ values of $occ(x)$ in the initial array (before changing $a_i = -1$), and each $x$ with the same occurrences contribute the same amount. Therefore, we can solve the problem in $O(n \\sqrt{n})$.",
    "tags": [
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1575",
    "index": "G",
    "title": "GCD Festival",
    "statement": "Mr. Chanek has an array $a$ of $n$ integers. The prettiness value of $a$ is denoted as:\n\n$$\\sum_{i=1}^{n} {\\sum_{j=1}^{n} {\\gcd(a_i, a_j) \\cdot \\gcd(i, j)}}$$\n\nwhere $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\nIn other words, the prettiness value of an array $a$ is the total sum of $\\gcd(a_i, a_j) \\cdot \\gcd(i, j)$ for all pairs $(i, j)$.\n\nHelp Mr. Chanek find the prettiness value of $a$, and output the result modulo $10^9 + 7$!",
    "tutorial": "Define: $d(n)$ as the set of all divisors of $n$; $\\phi(x)$ as the euler totient function of $x$; and $d(a, b)$ as the set of all divisors of both $a$ and $b$; or equivalently, $d(\\gcd(a, b))$. Observe that $\\sum_{x \\in d(n)}\\phi(x) = n$. This implies $\\sum_{x \\in d(a, b)}\\phi(x) = \\gcd(a,b)$ $\\sum_{i = 1}^n \\sum_{j = 1}^n \\gcd(i, j) \\cdot \\gcd(a_i, a_j)\\\\ \\sum_{i = 1}^n \\sum_{j = 1}^n \\left(\\left(\\sum_{x \\in d(i,j)} \\phi(x)\\right) \\cdot \\gcd(a_i, a_j))\\right)\\\\ \\sum_{x=1}^n \\phi(x) \\sum_{i = 1}^{\\lfloor \\frac{n}{x} \\rfloor} \\sum_{j = 1}^{\\lfloor \\frac{n}{x} \\rfloor} \\gcd(a_{ix}, a_{jx})\\\\ \\sum_{x=1}^n \\phi(x) \\sum_{i = 1}^{\\lfloor \\frac{n}{x} \\rfloor} \\sum_{j = 1}^{\\lfloor \\frac{n}{x} \\rfloor} \\sum_{y \\in d(a_{ix}, a_{jx})} \\phi(y)\\\\ \\sum_{x=1}^n \\phi(x) \\sum_{y} \\phi(y) \\left(\\sum_{i = 1}^{\\lfloor \\frac{n}{x} \\rfloor} [a_{ix} \\bmod y = 0] \\right)^2$ If we only iterate $y$ where $y$ is a divisor of one of $a_{ix}$, we can compute the above summation in $O(n \\log n \\max_{i=1}^n(|d(a_i)|))$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1575",
    "index": "H",
    "title": "Holiday Wall Ornaments",
    "statement": "The Winter holiday will be here soon. Mr. Chanek wants to decorate his house's wall with ornaments. The wall can be represented as a binary string $a$ of length $n$. His favorite nephew has another binary string $b$ of length $m$ ($m \\leq n$).\n\nMr. Chanek's nephew loves the non-negative integer $k$. His nephew wants exactly $k$ occurrences of $b$ as substrings in $a$.\n\nHowever, Mr. Chanek does not know the value of $k$. So, for each $k$ ($0 \\leq k \\leq n - m + 1$), find the minimum number of elements in $a$ that have to be changed such that there are exactly $k$ occurrences of $b$ in $a$.\n\nA string $s$ occurs exactly $k$ times in $t$ if there are exactly $k$ different pairs $(p,q)$ such that we can obtain $s$ by deleting $p$ characters from the beginning and $q$ characters from the end of $t$.",
    "tutorial": "Do a dynamic programming with three states: Position in $s$ Position in $t$ How many matches left. define the dynamic programming of $dp[a][b][rem]$ as the minimum cost of having the string $p = s[1..a]$, $rem$ matches left, and the longest prefix match between $s$ and $t$ is at $b$. The answer will be at $dp[n][c][0]$ for any arbitrary $c$. The transition can first be precomputed with brute force in $O(n^3)$ or with Aho-Corasick. Time complexity: $O(n^3)$ Space complexity: $O(n^2)$",
    "tags": [
      "dp",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1575",
    "index": "I",
    "title": "Illusions of the Desert",
    "statement": "Chanek Jones is back, helping his long-lost relative Indiana Jones, to find a secret treasure in a maze buried below a desert full of illusions.\n\nThe map of the labyrinth forms a tree with $n$ rooms numbered from $1$ to $n$ and $n - 1$ tunnels connecting them such that it is possible to travel between each pair of rooms through several tunnels.\n\nThe $i$-th room ($1 \\leq i \\leq n$) has $a_i$ illusion rate. To go from the $x$-th room to the $y$-th room, there must exist a tunnel between $x$ and $y$, and it takes $\\max(|a_x + a_y|, |a_x - a_y|)$ energy. $|z|$ denotes the absolute value of $z$.\n\nTo prevent grave robbers, the maze can change the illusion rate of any room in it. Chanek and Indiana would ask $q$ queries.\n\nThere are two types of queries to be done:\n\n- $1\\ u\\ c$ — The illusion rate of the $x$-th room is changed to $c$ ($1 \\leq u \\leq n$, $0 \\leq |c| \\leq 10^9$).\n- $2\\ u\\ v$ — Chanek and Indiana ask you the minimum sum of energy needed to take the secret treasure at room $v$ if they are initially at room $u$ ($1 \\leq u, v \\leq n$).\n\nHelp them, so you can get a portion of the treasure!",
    "tutorial": "Note that $\\max(|a_x + a_y|, |a_x - a_y|) = |a_x| + |a_y|$. Now the problem can be reduced to updating a vertex's value and querying the sum of values of vertices in a path. This can be done in several ways. One can use euler tour tree flattening method, as described in Euler Tour Magic by brdy blog, or use heavy-light decomposition. Time complexity : $O((q + n) \\log^2 n)$ or $O((q + n) \\log n)$",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1575",
    "index": "J",
    "title": "Jeopardy of Dropped Balls",
    "statement": "Mr. Chanek has a new game called Dropping Balls. Initially, Mr. Chanek has a grid $a$ of size $n \\times m$\n\nEach cell $(x,y)$ contains an integer $a_{x,y}$ denoting the direction of how the ball will move.\n\n- $a_{x,y}=1$ — the ball will move to the right (the next cell is $(x, y + 1)$);\n- $a_{x,y}=2$ — the ball will move to the bottom (the next cell is $(x + 1, y)$);\n- $a_{x,y}=3$ — the ball will move to the left (the next cell is $(x, y - 1)$).\n\nEvery time a ball leaves a cell $(x,y)$, the integer $a_{x,y}$ will change to $2$. Mr. Chanek will drop $k$ balls sequentially, each starting from the first row, and on the $c_1, c_2, \\dots, c_k$-th ($1 \\leq c_i \\leq m$) columns.\n\nDetermine in which column each ball will end up in (\\textbf{position of the ball after leaving the grid}).",
    "tutorial": "Naively simulating the ball's path is enough, and runs in $O(nm + nk)$. Note that if we visit a non-$2$ cell, then the path length of the current ball is increased by $1$, and then the cell turns into $2$. So the total length of all paths can be increased by at most $O(nm)$ times. In addition, each ball needs at least $O(n)$ moves to travel, so we get $O(nm + nk)$. We can improve this further. You can speed up each drops by storing consecutive $2$-cell segments in the downwards direction for each column. Using a Disjoint-Set Union data structure, for each cell $a_{x,y} = 2$, join it with its bottom cell if $a_{x + 1, y} = 2$. Time complexity: $O(k + rc\\cdot\\alpha(rc))$",
    "tags": [
      "binary search",
      "brute force",
      "dsu",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1575",
    "index": "K",
    "title": "Knitting Batik",
    "statement": "Mr. Chanek wants to knit a batik, a traditional cloth from Indonesia. The cloth forms a grid $a$ with size $n \\times m$. There are $k$ colors, and each cell in the grid can be one of the $k$ colors.\n\n\\textbf{Define} a sub-rectangle as an ordered pair of two cells $((x_1, y_1), (x_2, y_2))$, denoting the top-left cell and bottom-right cell (inclusively) of a sub-rectangle in $a$. Two sub-rectangles $((x_1, y_1), (x_2, y_2))$ and $((x_3, y_3), (x_4, y_4))$ have the same pattern if and only if the following holds:\n\n- they have the same width ($x_2 - x_1 = x_4 - x_3$);\n- they have the same height ($y_2 - y_1 = y_4 - y_3$);\n- for every pair $(i, j)$ where $0 \\leq i \\leq x_2 - x_1$ and $0 \\leq j \\leq y_2 - y_1$, the color of cells $(x_1 + i, y_1 + j)$ and $(x_3 + i, y_3 + j)$ are equal.\n\nCount the number of possible batik color combinations, such that the subrectangles $((a_x, a_y),(a_x + r - 1, a_y + c - 1))$ and $((b_x, b_y),(b_x + r - 1, b_y + c - 1))$ have the same pattern.\n\nOutput the answer modulo $10^9 + 7$.",
    "tutorial": "October the 2nd is the National Batik Day of Indonesia Observe that only some several non-intersecting part of $nm - rc$ that is independent in the grid. Simple casework shows that the answer is $k^{nm}$ if $a = b$, and $k^{nm - rc}$ otherwise. Time complexity: $O(\\log nm)$",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1575",
    "index": "L",
    "title": "Longest Array Deconstruction",
    "statement": "Mr. Chanek gives you a sequence $a$ indexed from $1$ to $n$. Define $f(a)$ as the number of indices where $a_i = i$.\n\nYou can pick an element from the current sequence and remove it, then concatenate the remaining elements together. For example, if you remove the $3$-rd element from the sequence $[4, 2, 3, 1]$, the resulting sequence will be $[4, 2, 1]$.\n\nYou want to remove some elements from $a$ in order to maximize $f(a)$, using zero or more operations. Find the largest possible $f(a)$.",
    "tutorial": "Define $a'$ as the array we get after removing some elements in $a$ and valid element as $a'_i$ that satisfy $a'_i = i$. We can try to find combination of indices ${c_1, c_2, \\dots c_m}$ such that $a_{c_i} = a'_{p_i} = p_i$ for a certain set ${p_1, p_2, \\dots p_m}$. In other words, we want to find all indices ${c_1, c_2, \\dots c_m}$ such that $a_{c_i}$ will be a valid element in the $a'$. Observe that each element in $c$ and every pair $i$ and $j$ ($i < j$) must satisfy: 1. $c_i < c_j$ 2. $a_{c_i} < a_{c_j}$ 3. $c_i - a_{c_i} \\leq c_j - a_{c_j}$, the element you need to remove to adjust $a_{c_i}$ to it's location is smaller than $a_{c_j}$. Therefore, we can convert each index into $(c_i, a_{c_i}, c_i - a_{c_i})$ and find the longest sequence of those tuples that satisfy the conditions. This is sufficient with divide and conquer in $O(n\\log n\\log n)$. But the solution can be improved further. Notice that if $(2) \\land (3) \\implies (1)$. Hence we can solve problem by finding the longest sequence of pairs ($a_{c_i}, c_i - a_{c_i}$) with any standard LIS algorithm. Time complexity: $O(n\\log n)$",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1575",
    "index": "M",
    "title": "Managing Telephone Poles",
    "statement": "Mr. Chanek's city can be represented as a plane. He wants to build a housing complex in the city.\n\nThere are some telephone poles on the plane, which is represented by a grid $a$ of size $(n + 1) \\times (m + 1)$. There is a telephone pole at $(x, y)$ if $a_{x, y} = 1$.\n\nFor each point $(x, y)$, define $S(x, y)$ as the square of the Euclidean distance between the nearest pole and $(x, y)$. Formally, the square of the Euclidean distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is $(x_2 - x_1)^2 + (y_2 - y_1)^2$.\n\nTo optimize the building plan, the project supervisor asks you the sum of all $S(x, y)$ for each $0 \\leq x \\leq n$ and $0 \\leq y \\leq m$. Help him by finding the value of $\\sum_{x=0}^{n} {\\sum_{y=0}^{m} {S(x, y)}}$.",
    "tutorial": "Interestingly, if you generate the Voronoi Diagram and transcribe it to a grid, then the same connected area in the Voronoi Diagram is not necessarily in the same 8-connected component in the grid. This is why most Dijkstra solutions will get WA. We can use convex hull trick to solve this problem. Suppose that we only need to calculate $\\sum_{x = 0}^{m} {S(x, y)}$ for a certain $y$. For a fixed $y$ axis and a pole located in point $(x_i, y_i)$, define $f(x) = (x - x_i)^2 + (y - y_i)^2 = - 2xx_i + x^2 - x_i^2 + (y - y_i)^2$, which is the euclidean distance of point $(x, y)$ and pole $(x_i, y_i)$. Notice that, for a fixed pole $i$ and axis $y$, $f(x)$ is a line equation, thus we can maintain it with convex hull trick. Additionally, for a certain $y$, there are only $m$ poles that we need to consider. More specifically, pole $(x_i, y_i)$ is called considerable if there is no other pole $(x_j, y_j)$ such that $x_i = x_j$ and $|y_i - y| < |y_j - y|$. Hence we can find the $\\sum_{x = 0}^{m} {S(x, y)}$ for a certain $y$ in $O(m)$ or $O(m \\log m)$. Calculating $\\sum_{x = 0}^{m} {S(x, y)}$ for all $y$ will result in $O(nm)$ or $O(nm \\log m)$ time complexity.",
    "tags": [
      "data structures",
      "geometry"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1579",
    "index": "A",
    "title": "Casimir's String Solitaire",
    "statement": "Casimir has a string $s$ which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions:\n\n- he can either erase exactly one letter 'A' \\textbf{and} exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent);\n- or he can erase exactly one letter 'B' \\textbf{and} exactly one letter 'C' from arbitrary places in the string (these letters don't have to be adjacent).\n\nTherefore, each turn the length of the string is decreased exactly by $2$. All turns are independent so for each turn, Casimir can choose any of two possible actions.\n\nFor example, with $s$ $=$ \"ABCABC\" he can obtain a string $s$ $=$ \"ACBC\" in one turn (by erasing the first occurrence of 'B' and the second occurrence of 'A'). There are also many other options for a turn aside from this particular example.\n\nFor a given string $s$ determine whether there is a sequence of actions leading to an empty string. In other words, Casimir's goal is to erase all letters from the string. Is there a way to do this?",
    "tutorial": "Note that no matter which action is chosen, after this action is performed exactly one letter 'B' is erased from the string exactly two letters in total are erased from the string Let's denote the length of the string $s$ by $n$. If $n$ is odd, then described turns can not erase all the characters from the strings, because if he is deleting two letters on each turn, the length will always remain odd. For example, if the original length of the string is $5$, then after one turn it will be equal to $3$, and after two moves it will be equal to $1$ in which case the next turn is impossible. Thus, if the length of the row is odd, the answer is NO. If $n$ is even, it will take exactly $\\frac{n}{2}$ steps to erase all characters from the string. Since each action removes exactly one letter 'B' from the string, the string can become empty only if there are exactly $\\frac{n}{2}$ letters 'B'. Let us show that this condition is sufficient, that is, if a string has exactly half of the letters equal to 'B', then there always exists a sequence of actions leading to an empty string. Indeed, if a string of length $n$ has exactly $\\frac{n}{2}$ letters 'B', exactly $x$ letters 'A' and exactly $y$ letters 'C', then $x + y = n - \\frac{n}{2} = \\frac{n}{2}$. Then Casimir can make $x$ moves of the first type, each time removing the first occurrence of 'B' and the first occurrence of 'A', and $y$ moves of the second type, each time removing the first occurrence of 'B' and the first occurrence of 'C'. After $x + y = \\frac{n}{2}$ such moves, the string will become empty. Thus, checking that the number of letters 'B' in the string is exactly half of its length was enough to solve the problem.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        string s;\n        cin >> s;\n        cout << (count(s.begin(), s.end(), 'B') * 2 == s.size() ?\n                 \"YES\\n\" : \"NO\\n\");\n    }\n}",
    "tags": [
      "math",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1579",
    "index": "B",
    "title": "Shifting Sort",
    "statement": "The new generation external memory contains an array of integers $a[1 \\ldots n] = [a_1, a_2, \\ldots, a_n]$.\n\nThis type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same place.\n\nTechnically, each cyclic shift consists of two consecutive actions:\n\n- You may select arbitrary indices $l$ and $r$ ($1 \\le l < r \\le n$) as the boundaries of the segment.\n- Then you replace the segment $a[l \\ldots r]$ with it's cyclic shift to the \\textbf{left} by an arbitrary offset $d$. The concept of a cyclic shift can be also explained by following relations: the sequence $[1, 4, 1, 3]$ is a cyclic shift of the sequence $[3, 1, 4, 1]$ to the left by the offset $1$ and the sequence $[4, 1, 3, 1]$ is a cyclic shift of the sequence $[3, 1, 4, 1]$ to the left by the offset $2$.\n\nFor example, if $a = [1, \\textcolor{blue}{3, 2, 8}, 5]$, then choosing $l = 2$, $r = 4$ and $d = 2$ yields a segment $a[2 \\ldots 4] = [3, 2, 8]$. This segment is then shifted by the offset $d = 2$ to the \\textbf{left}, and you get a segment $[8, 3, 2]$ which then takes the place of of the original elements of the segment. In the end you get $a = [1, \\textcolor{blue}{8, 3, 2}, 5]$.\n\nSort the given array $a$ using no more than $n$ cyclic shifts of any of its segments. Note that you don't need to minimize the number of cyclic shifts. Any method that requires $n$ or less cyclic shifts will be accepted.",
    "tutorial": "In this problem, it was enough to implement an analogue of standard selection sort or insertion sort. Here is an example of a solution based on selection sort. Let's find the minimum element in the array by simply iterating over it. Let's denote its index in the array by $p_1$. If we apply a shift \"$1$ $p_1$ $(p_1 - 1)$\" to it, the following happens: $a \\rightarrow [\\color{blue}{a_\\color{red}{p_1}, a_1, a_2, \\ldots, a_{p_1 - 1}}, a_{p_1 + 1}, \\ldots, a_n]$ Let us perform a similar shift for the second-largest element of the array, putting it in second place, for the third-largest element of the array, putting it in third place, and so on. More formally, let's describe the $i$-th iteration as follows: At the beginning of the $i$-th iteration, the first $i - 1$ elements of the array are its $i - 1$ minimal elements, already in their correct places in sorted order. During the $i$-th iteration, the $i$-th largest element of the array is placed in the $i$-th place in the array. Since the first $i - 1$ minimal elements are already in their places, the $i$-th largest element of the array is simply the smallest element among $[a_i, a_{i + 1}, \\ldots, a_n]$. Let's find it by iterating over these elements and denote its index in the array $a$ by $p_i$. Make a shift \"$i$ $p_i$ $(p_i - i)$\". The first $i - 1$ elements will not change, and the element from the $p_i$-th place in the array will move to the $i$-th: $a \\rightarrow [a_1, \\ldots, a_{i - 1}, \\color{blue}{a_\\color{red}{p_i}, a_i, a_{i + 1}, \\ldots, a_{p_i - 1}}, a_{p_i + 1}, \\ldots, a_n]$ It is worth noting that the output format forbids shifting segments with $l = r$. Regarding this case, we should check the equality $i = p_i$ separately. If these two indexes coincide, then the $i$-th element is already in its place, and no shift should be done on this iteration. $a \\rightarrow [a_1, \\ldots, a_{i - 1}, \\color{blue}{a_\\color{red}{p_i}, a_i, a_{i + 1}, \\ldots, a_{p_i - 1}}, a_{p_i + 1}, \\ldots, a_n]$ It is worth noting that the output format forbids shifting segments with $l = r$. Regarding this case, we should check the equality $i = p_i$ separately. If these two indexes coincide, then the $i$-th element is already in its place, and no shift should be done on this iteration. Let us repeat this algorithm for $i = 2$, $i = 3$, ..., $i = n - 1$. At each iteration, the new element will be shifted into its place in sorted order, and each iteration performs no more than one shift operation. Thus, in strictly less than $n$ shifts, the array will be completely sorted. The time complexity is $\\mathcal{O}\\left(t \\cdot n^2\\right)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        vector<pii> actions;\n        for (int i = 0; i < n; i++)\n            cin >> a[i];\n\n        for (int i = 0; i < n - 1; i++) {\n            int min_pos = i;\n            for (int j = i + 1; j < n; j++)\n                if (a[j] < a[min_pos])\n                    min_pos = j;\n\n            if (min_pos > i) {\n                actions.push_back({i, min_pos});\n                int opt = a[min_pos];\n                for (int j = min_pos; j > i; j--)\n                    a[j] = a[j - 1];\n                a[i] = opt;\n            }\n        }\n\n        cout << actions.size() << '\\n';\n        for (auto &lr: actions) {\n            cout << lr.first + 1 << ' ' << lr.second + 1 << ' ' << lr.second - lr.first << '\\n';\n        }\n    }\n\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1579",
    "index": "C",
    "title": "Ticks",
    "statement": "Casimir has a rectangular piece of paper with a checkered field of size $n \\times m$. Initially, all cells of the field are white.\n\nLet us denote the cell with coordinates $i$ vertically and $j$ horizontally by $(i, j)$. The upper left cell will be referred to as $(1, 1)$ and the lower right cell as $(n, m)$.\n\nCasimir draws ticks of different sizes on the field. A tick of size $d$ ($d > 0$) with its center in cell $(i, j)$ is drawn as follows:\n\n- First, the center cell $(i, j)$ is painted black.\n- Then exactly $d$ cells on the top-left diagonally to the center and exactly $d$ cells on the top-right diagonally to the center are also painted black.\n- That is all the cells with coordinates $(i - h, j \\pm h)$ for all $h$ between $0$ and $d$ are painted. In particular, a tick consists of $2d + 1$ black cells.\n\nAn already painted cell will remain black if painted again. Below you can find an example of the $4 \\times 9$ box, with two ticks of sizes $2$ and $3$.\n\nYou are given a description of a checkered field of size $n \\times m$. Casimir claims that this field came about after he drew some (possibly $0$) ticks on it. The ticks could be of different sizes, but the size of each tick is at least $k$ (that is, $d \\ge k$ for all the ticks).\n\nDetermine whether this field can indeed be obtained by drawing some (possibly none) ticks of sizes $d \\ge k$ or not.",
    "tutorial": "For each painted cell, we will determine whether it can be part of some tick of the allowed size. If some of the cells cannot be a part of any tick, the answer is obviously NO. Otherwise, let's match each colored cell with an arbitrary valid (entirely contained in the field under consideration and of size $\\ge k$) tick containing it. Let's draw all such ticks, then the following holds: no empty (white) cell of the field will be painted, since only ticks that do not contradict the field in question have been considered; every colored cell of the field will be covered by at least one drawn tick (at least the one we matched it with). In order to check that all painted cells are parts of some ticks, let's go through all possible ticks of size $d \\ge k$ and for each tick mark all the cells included in it. If there is at least one unmarked painted cell in the end, it can't be a part of any valid tick, and the answer is NO. To consider all possible ticks, we can iterate through all their possible center cells, that is, all the painted cells. Since smaller ticks are subsets of larger ticks with the same center cell it is sufficient to find the maximal size tick that can be constructed from that center cell. So for each painted cell we aim to find the maximal possible size of a tick with its center in this very cell. Let us now consider a painted cell $(i, j)$ as a possible center of some tick. By the definition of a tick, this cell can be a center of a tick of size $d$ if for all $h$ from $0$ to $d$ both cells $(i - h, j - h)$ and $(i - h, j + h)$ exist (are not out of bounds) and are painted. Let's iterate through $h$ from $1$ to $i$, and stop when the described condition is no longer satisfied. The largest $h$ for which the condition is still satisfied gives us $d_{i, j}$ - the maximum possible size of a tick with its center in $(i, j)$. Now if $d_{i, j} \\ge k$, then such a tick is valid, and all the cells included in it should be marked. Otherwise, it could not have been drawn, and none of its cells should be marked. After a complete check of all possible ticks in a given field, either there will be no unchecked painted cells and then the answer is YES, or at least one painted cell is not covered by any valid checkbox and then the answer is NO. The time complexity is $\\mathcal{O}\\left(t \\cdot n^2 m\\right)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m, k;\n        cin >> n >> m >> k;\n        vector<vector<int>> status(n, vector<int>(m, 0));\n        for (int i = 0; i < n; i++) {\n            string s;\n            cin >> s;\n            for (int j = 0; j < m; j++)\n                if (s[j] == '*')\n                    status[i][j] = 1;\n        }\n        for (int i = n - 1; i > -1; i--) {\n            for (int j = 0; j < m; j++) {\n                if (status[i][j] == 0)\n                    continue;\n                int len = 0;\n                while (j > len && j + len + 1 < m && i > len) {\n                    if (status[i - len - 1][j - len - 1] == 0 || status[i - len - 1][j + len + 1] == 0)\n                        break;\n                    len++;\n                }\n                if (len >= k) {\n                    for (int d = 0; d <= len; d++) {\n                        status[i - d][j - d] = 2;\n                        status[i - d][j + d] = 2;\n                    }\n                }\n            }\n        }\n        bool ok = true;\n        for (int i = 0; i < n; i++)\n            for (int j = 0; j < m; j++)\n                if (status[i][j] == 1)\n                    ok = false;\n\n        cout << (ok ? \"YES\" : \"NO\") << '\\n';\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1579",
    "index": "D",
    "title": "Productive Meeting",
    "statement": "An important meeting is to be held and there are exactly $n$ people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.\n\nEach person has limited sociability. The sociability of the $i$-th person is a non-negative integer $a_i$. This means that after exactly $a_i$ talks this person leaves the meeting (and does not talk to anyone else anymore). If $a_i = 0$, the $i$-th person leaves the meeting immediately after it starts.\n\nA meeting is considered most productive if the maximum possible number of talks took place during it.\n\nYou are given an array of sociability $a$, determine which people should talk to each other so that the total number of talks is as large as possible.",
    "tutorial": "For the first conversation let's choose two people $i$ and $j$ with maximal values of sociability. Note that after this conversation takes place, we move on to a similar problem, but in which $a_i$ and $a_j$ are decreased by $1$. After decreasing $a_i$ and $a_j$ by $1$, we repeat the choice of the two people with the maximum values of sociability. Let us repeat such iterations while at least two people with positive sociability parameters remain. Let us prove that this solution leads to the optimal answer. Let's denote the sum $\\sum\\limits_{i = 1}^n a_i$ by $S$ and consider two fundamentally different cases: The maximal element $a$ is greater than or equal to the sum of all remaining elements. That is, there exists $i$ such that $a_i \\ge \\sum\\limits_{i \\neq j} a_j = S - a_i$. In this case, note that the $i$-th person can not possibly have more than $S - a_i$ conversations, because by that point all other people already reached their sociability limits and left the meeting. Thus, if $a_i \\ge S - a_i$, the answer cannot be more than $(S - a_i) + \\sum\\limits_{j \\neq i} a_j = 2 \\cdot (S - a_i)$. Note that this estimation is accurate since an example exists in which $i$-th person talks to all other people as many times as possible (that is, $a_j$ times with $j$-th person for all $j$). And the algorithm described above will just choose the $i$th person as one of the participants of a conversation every time, because for every conversation both $a_i$ and $\\sum\\limits_{j \\neq i} a_j$ decrease by exactly $1$, so the inequality holds and it follows that $\\forall k \\neq i:\\, a_i \\ge \\sum\\limits_{j \\neq i} a_j \\ge a_k\\text{.}$ Thus, if $a_i \\ge S - a_i$, the answer cannot be more than $(S - a_i) + \\sum\\limits_{j \\neq i} a_j = 2 \\cdot (S - a_i)$. Note that this estimation is accurate since an example exists in which $i$-th person talks to all other people as many times as possible (that is, $a_j$ times with $j$-th person for all $j$). And the algorithm described above will just choose the $i$th person as one of the participants of a conversation every time, because for every conversation both $a_i$ and $\\sum\\limits_{j \\neq i} a_j$ decrease by exactly $1$, so the inequality holds and it follows that $\\forall k \\neq i:\\, a_i \\ge \\sum\\limits_{j \\neq i} a_j \\ge a_k\\text{.}$ Otherwise, we can prove that the maximum number of conversations is always $\\left\\lfloor\\frac{S}{2}\\right\\rfloor$. Obviously, it is impossible to get more than this number, since each conversation requires exactly two units of sociability (one from two people), while a larger answer would mean that $S = \\sum\\limits_{i = 1}^n a_i \\ge 2 \\cdot \\left(\\left\\lfloor\\frac{S}{2}\\right\\rfloor + 1\\right) > S\\text{,}$ which is obviously wrong. Let us prove that this answer is achieved by the described algorithm. Let's look at the last conversation held. If there are at least two more people left in the meeting after it, we can hold another conversation, which means there is a more optimal answer. If there are zero people left in the meeting, then an estimate of $\\frac{S}{2}$ of conversations has been achieved. And if there is one person with a remaining sociability $= 1$, then an estimate of $\\frac{S - 1}{2}$ of conversations has been achieved. If there is exactly one remaining person $i$ with a sociability residual $> 1$, then we can guarantee that this person has participated in all previous conversations. Indeed, let's look at the last conversation - it was held between two people with the maximum parameters of the remaining sociability. But the $i$-th person has at least $2$ sociability remaining, so it couldn't have been the other two people with residuals of $1$ who left right after that. Thus, analyzing all conversations in reverse order, we can prove that at any time $a_i > \\sum\\limits_{j \\neq i} a_j$, which means that it is in fact the case considered above. $S = \\sum\\limits_{i = 1}^n a_i \\ge 2 \\cdot \\left(\\left\\lfloor\\frac{S}{2}\\right\\rfloor + 1\\right) > S\\text{,}$ Let us prove that this answer is achieved by the described algorithm. Let's look at the last conversation held. If there are at least two more people left in the meeting after it, we can hold another conversation, which means there is a more optimal answer. If there are zero people left in the meeting, then an estimate of $\\frac{S}{2}$ of conversations has been achieved. And if there is one person with a remaining sociability $= 1$, then an estimate of $\\frac{S - 1}{2}$ of conversations has been achieved. If there is exactly one remaining person $i$ with a sociability residual $> 1$, then we can guarantee that this person has participated in all previous conversations. Indeed, let's look at the last conversation - it was held between two people with the maximum parameters of the remaining sociability. But the $i$-th person has at least $2$ sociability remaining, so it couldn't have been the other two people with residuals of $1$ who left right after that. Thus, analyzing all conversations in reverse order, we can prove that at any time $a_i > \\sum\\limits_{j \\neq i} a_j$, which means that it is in fact the case considered above. We have proven that the described greedy algorithm works. This algorithm can be implemented by using any balanced search tree, such as std::set. By storing pairs of elements $(a_i, i)$ in it, we could for $\\mathcal{O}(\\log n)$ each time choose the next two people to talk to and update the sociability values. The time complexity is $\\mathcal{O}(S \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        auto cmp = [](pii const &x, pii const &y) {\n            return x > y;\n        };\n        set<pii, decltype(cmp)> a(cmp);\n        vector<pii> answer;\n        for (int i = 0; i < n; i++) {\n            int ai;\n            cin >> ai;\n            if (ai > 0)\n                a.emplace(ai, i + 1);\n        }\n        while (a.size() > 1) {\n            auto p1 = *a.begin();\n            a.erase(a.begin());\n            auto p2 = *a.begin();\n            a.erase(a.begin());\n            answer.emplace_back(p1.second, p2.second);\n            if (p1.first > 1) a.emplace(p1.first - 1, p1.second);\n            if (p2.first > 1) a.emplace(p2.first - 1, p2.second);\n        }\n        cout << answer.size() << '\\n';\n        for (auto &p : answer) {\n            cout << p.first << ' ' << p.second << '\\n';\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1579",
    "index": "E1",
    "title": "Permutation Minimization by Deque",
    "statement": "In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.\n\nA permutation $p$ of size $n$ is given. A permutation of size $n$ is an array of size $n$ in which each integer from $1$ to $n$ occurs exactly once. For example, $[1, 4, 3, 2]$ and $[4, 2, 1, 3]$ are correct permutations while $[1, 2, 4]$ and $[1, 2, 2]$ are not.\n\nLet us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $[1, 5, 2]$ currently in the deque, adding an element $4$ to the beginning will produce the sequence $[\\textcolor{red}{4}, 1, 5, 2]$, and adding same element to the end will produce $[1, 5, 2, \\textcolor{red}{4}]$.\n\nThe elements of the permutation are sequentially added to the initially empty deque, starting with $p_1$ and finishing with $p_n$. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.\n\nFor example, if we consider a permutation $p = [3, 1, 2, 4]$, one of the possible sequences of actions looks like this:\n\n\\begin{tabular}{lll}\n$\\quad$ 1. & add $3$ to the end of the deque: & deque has a sequence $[\\textcolor{red}{3}]$ in it; \\\n$\\quad$ 2. & add $1$ to the beginning of the deque: & deque has a sequence $[\\textcolor{red}{1}, 3]$ in it; \\\n$\\quad$ 3. & add $2$ to the end of the deque: & deque has a sequence $[1, 3, \\textcolor{red}{2}]$ in it; \\\n$\\quad$ 4. & add $4$ to the end of the deque: & deque has a sequence $[1, 3, 2, \\textcolor{red}{4}]$ in it; \\\n\\end{tabular}\n\nFind the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed.\n\nA sequence $[x_1, x_2, \\ldots, x_n]$ is lexicographically smaller than the sequence $[y_1, y_2, \\ldots, y_n]$ if there exists such $i \\leq n$ that $x_1 = y_1$, $x_2 = y_2$, $\\ldots$, $x_{i - 1} = y_{i - 1}$ and $x_i < y_i$. In other words, if the sequences $x$ and $y$ have some (possibly empty) matching prefix, and the next element of the sequence $x$ is strictly smaller than the corresponding element of the sequence $y$. For example, the sequence $[1, 3, 2, 4]$ is smaller than the sequence $[1, 3, 4, 2]$ because after the two matching elements $[1, 3]$ in the start the first sequence has an element $2$ which is smaller than the corresponding element $4$ in the second sequence.",
    "tutorial": "We'll process the permutation elements one by one. For the first element, it doesn't matter which side of the deque we add it to, the result of its addition will be the same - there will be a sequence of one element (equal to the first permutation element) in the deque. Now let's consider adding the $i$-th element of a permutation to the deque. First $i = 2$ will be considered, then $i = 3$, and so on up to $i = n$. Let us describe the general algorithm for choosing the side of the deque for each step. Note that if the elements $[d_1, \\ldots, d_{i - 1}]$ are now in the deque, then all final permutations that can be obtained in the deque from the current state can be broken down into pairs of the form $[\\ldots, \\color{red}{a_i}, \\color{blue}{d_1, \\ldots, d_{i - 1}}, \\ldots]\\,$ $[\\ldots, \\color{blue}{d_1, \\ldots, d_{i - 1}}, \\color{red}{a_i}, \\ldots]\\text{,}$ Note that when $a_i < d_1$ the first permutation will always be lexicographically smaller than the second one, and vice versa. Therefore, regardless of the following choices, if $a_i < d_1$ then the second permutation will never be minimal, and if $a_i > d_1$ then the first permutation will never be minimal. This means that we can make a choice about the side of the deque to add the $i$-th element to based only on its relation to $d_1$: if $a_i < d_1$, then $a_i$ is added to the beginning of the deque, otherwise - to the end. The time complexity is $\\mathcal{O}(n)$. Alternative solutions, which also fit in the time limit, involved finding a lexicographically minimal increasing sequence in the reversed original permutation and could be implemented either with $\\mathcal{O}(n \\log n)$ time complexity or with $\\mathcal{O}(n)$ time complexity if the permutation's definition was taken into consideration.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, a;\n        cin >> n;\n        deque<int> d;\n        for (int i = 0; i < n; i++) {\n            cin >> a;\n            if (d.empty() || a < d[0])\n                d.push_front(a);\n            else\n                d.push_back(a);\n        }\n        for (int x : d)\n            cout << x << ' ';\n        cout << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1579",
    "index": "E2",
    "title": "Array Optimization by Deque",
    "statement": "In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.\n\nYou are given an integer array $a[1 \\ldots n] = [a_1, a_2, \\ldots, a_n]$.\n\nLet us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $[3, 4, 4]$ currently in the deque, adding an element $1$ to the beginning will produce the sequence $[\\textcolor{red}{1}, 3, 4, 4]$, and adding the same element to the end will produce $[3, 4, 4, \\textcolor{red}{1}]$.\n\nThe elements of the array are sequentially added to the initially empty deque, starting with $a_1$ and finishing with $a_n$. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.\n\nFor example, if we consider an array $a = [3, 7, 5, 5]$, one of the possible sequences of actions looks like this:\n\n\\begin{tabular}{lll}\n$\\quad$ 1. & add $3$ to the beginning of the deque: & deque has a sequence $[\\textcolor{red}{3}]$ in it; \\\n$\\quad$ 2. & add $7$ to the end of the deque: & deque has a sequence $[3, \\textcolor{red}{7}]$ in it; \\\n$\\quad$ 3. & add $5$ to the end of the deque: & deque has a sequence $[3, 7, \\textcolor{red}{5}]$ in it; \\\n$\\quad$ 4. & add $5$ to the beginning of the deque: & deque has a sequence $[\\textcolor{red}{5}, 3, 7, 5]$ in it; \\\n\\end{tabular}\n\nFind the minimal possible number of inversions in the deque after the whole array is processed.\n\nAn inversion in sequence $d$ is a pair of indices $(i, j)$ such that $i < j$ and $d_i > d_j$. For example, the array $d = [5, 3, 7, 5]$ has exactly two inversions — $(1, 2)$ and $(3, 4)$, since $d_1 = 5 > 3 = d_2$ and $d_3 = 7 > 5 = d_4$.",
    "tutorial": "Let's process the array elements one by one. For the first element, it doesn't matter which side of the deque we add it to, the result of its addition will be the same - there will be a sequence of one element (equal to the first array element) in the deque. Now let's consider adding the $i$th element of an array into the deck. First $i = 2$ will be considered, then $i = 3$, and so on up to $i = n$. Let us describe the general algorithm for choosing the side of the dec for each step. Note that if the elements $[d_1, \\ldots, d_{i - 1}]$ now lie in the deck, then all final sequences that can be obtained in the deck from the current state can be broken down into pairs of the form $[\\ldots, \\color{red}{a_i}, \\color{blue}{d_1, \\ldots, d_{i - 1}}, \\ldots]\\,$ $[\\ldots, \\color{blue}{d_1, \\ldots, d_{i - 1}}, \\color{red}{a_i}, \\ldots]\\text{,}$ Note that since the prefix and suffix hidden behind the dots completely coincide in the two sequences under consideration, as well as the set of numbers in the central part coincides, the numbers of inversions also coincide: inside the prefix and inside the suffix; between elements of the prefix and elements of the suffix; between elements of the prefix or suffix and elements of the central part. The difference between the number of inversions in the first and second sequence consists only of the difference between the number of inversions in their central part. So, we can determine at the stage of adding $a_i$ to the deque, which direction of its addition is guaranteed not to lead to the optimal answer and choose the opposite one. If $a_i$ is added to the beginning of the deque, the number of inversions in the central part will increase by the number of elements in the deque strictly smaller than $a_i$, and if we add it to the end of the deque, it will increase by the number of elements in the deque strictly larger than $a_i$. Let us make a choice such that the number of inversions increases by the minimum of these two values. To quickly find the number of elements smaller or larger than $a_i$, we will store all already processed array elements in a structure that supports the element order search operation, such as __gnu_pbds::tree. Besides using this structure specifically, you can write any balanced binary search tree (such as a Cartesian tree); sort all numbers in the input array and compress them to values $[1, n]$, preserving the \"$\\le$\" relation, then build a segment tree on them, storing in the node $[l, r)$ the number of array numbers already processed by the deque with values between $l$ and $r$. Requests to update and get an order in such structures take $\\mathcal{O}(\\log n)$ time, and the construction takes at worst $\\mathcal{O}(n \\log n)$, so the time complexity of the algorithm is $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n\nusing namespace std;\nusing namespace __gnu_pbds;\n\ntypedef pair<int, int> node;\ntypedef tree<node, null_type, less<node>,\n            rb_tree_tag, tree_order_statistics_node_update> ordered_set;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        ordered_set s;\n        long long cnt = 0;\n        for (int i = 0; i < n; i++) {\n            int a;\n            cin >> a;\n            int less = s.order_of_key(node(a, 0)),\n                    greater = i - s.order_of_key(node(a, n));\n            cnt += min(less, greater);\n            s.insert(node(a, i));\n        }\n        cout << cnt << '\\n';\n    }\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1579",
    "index": "F",
    "title": "Array Stabilization (AND version)",
    "statement": "You are given an array $a[0 \\ldots n - 1] = [a_0, a_1, \\ldots, a_{n - 1}]$ of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one.\n\nIn one step, the array $a$ is replaced by another array of length $n$ according to the following rules:\n\n- First, a new array $a^{\\rightarrow d}$ is defined as a cyclic shift of the array $a$ to the right by $d$ cells. The elements of this array can be defined as $a^{\\rightarrow d}_i = a_{(i + n - d) \\bmod n}$, where $(i + n - d) \\bmod n$ is the remainder of integer division of $i + n - d$ by $n$. It means that the whole array $a^{\\rightarrow d}$ can be represented as a sequence $$a^{\\rightarrow d} = [a_{n - d}, a_{n - d + 1}, \\ldots, a_{n - 1}, a_0, a_1, \\ldots, a_{n - d - 1}]$$\n- Then each element of the array $a_i$ is replaced by $a_i \\,\\&\\, a^{\\rightarrow d}_i$, where $\\&$ is a logical \"AND\" operator.\n\nFor example, if $a = [0, 0, 1, 1]$ and $d = 1$, then $a^{\\rightarrow d} = [1, 0, 0, 1]$ and the value of $a$ after the first step will be $[0 \\,\\&\\, 1, 0 \\,\\&\\, 0, 1 \\,\\&\\, 0, 1 \\,\\&\\, 1]$, that is $[0, 0, 0, 1]$.\n\nThe process ends when the array stops changing. For a given array $a$, determine whether it will consist of only zeros at the end of the process. If yes, also find the number of steps the process will take before it finishes.",
    "tutorial": "We'll consider an arbitrary index of the array $i$ and see what changes happen to $a_i$ during several steps of the described algorithm. Let's denote by $a^k$ the value of the array after $k$ steps of the algorithm and prove by induction that $a^k_i$ is the logical \"AND\" of $k + 1$ elements of the array $a$, starting from $i$ with step $d$ to the left, that is $a^k_i = a_i \\,\\&\\, a_{(i - d) \\bmod n} \\,\\&\\, \\ldots \\,\\&\\, a_{(i - kd) \\bmod n}$ Base of induction: for $k = 0$ the element of the original array $a^0_i$ is $a_i$. For clarity we can also show that the statement is true for $k = 1$: during the first step $a_i$ is replaced by $a_i \\,\\&\\, a_{(i - d) \\bmod n}$ by the definition of cyclic shift by $d$ to the right. For simplicity, we will omit the \"$\\bmod n$\" operation in the following formulas but will keep it in mind implicitly. That is, $a_{i - kd}$ will imply $a_{(i - kd) \\bmod n}$. Induction step: let the above statement be true for $k - 1$, let us prove it for $k$. By the definition of cyclic shift $a^k_i = a^{k-1}_i \\,\\&\\, a^{k-1}_{i - d}$. And by the induction assumption, these two numbers are equal to $a^{k-1}_i = a_i \\,\\&\\, \\ldots \\,\\&\\, a_{i - (k-1)d}$ $a^{k-1}_{i - d} = a_{i - d} \\,\\&\\, \\ldots \\,\\&\\, a_{i - kd}$ $a^k_i = a_i \\,\\&\\, a_{i - d} \\,\\&\\, \\ldots \\,\\&\\, a_{i - kd}\\text{,}$ It follows from this formula that $a_i$ turns to zero after the $k$-th step if and only if $a_i = 1$, $a_{i - d} = 1$, ..., $a_{i - (k-1)d} = 1$, and $a_{i - kd} = 0$. Up to the $k$-th step all elements will be equal to $1$, and so their logical \"AND\" will also be equal to $1$. As soon as $0$ appears in the sequence in question, the logical \"AND\" will also become zero. Thus, we reduced the problem to finding the maximal block of elements equal to $1$ of the pattern $a_i = a_{i - d} = a_{i - 2d} = \\ldots = a_{i - (k-1)d} = 1$. Note that by shifts of $d$ the array splits into $\\mathtt{gcd}(n, d)$ cyclic sequences of this kind, each of length $\\frac{n}{\\mathtt{gcd}(n, d)}$. Let's look at these cyclic sequences independently from each other and iterate over each of them in linear time complexity to find the maximal block of consecutive elements equal to $1$ - this will be the answer to the problem. Remember to check that if at least one of these sequences consists entirely of elements equal to $1$, its elements will never zero out, and the answer in such case is -1. The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, d;\n        cin >> n >> d;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++)\n            cin >> a[i];\n        vector<bool> used(n, false);\n        bool fail = false;\n        int res = 0;\n        for (int i = 0; i < n; i++) {\n            if (used[i])\n                continue;\n            int cur = i, pref = 0, last = 0, iter = 0, ans = 0;\n            do {\n                used[cur] = true;\n                if (a[cur] == 0) {\n                    ans = max(ans, last);\n                    last = 0;\n                } else {\n                    last++;\n                    if (iter == pref) {\n                        pref++;\n                    }\n                }\n                cur = (cur + d) % n;\n                iter++;\n            } while (cur != i);\n            if (iter != pref)\n                ans = max(ans, pref + last);\n            else {\n                fail = true;\n                break;\n            }\n            res = max(res, ans);\n        }\n        if (fail)\n            cout << \"-1\\n\";\n        else\n            cout << res << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "graphs",
      "math",
      "number theory",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1579",
    "index": "G",
    "title": "Minimal Coverage",
    "statement": "You are given $n$ lengths of segments that need to be placed on an infinite axis with coordinates.\n\nThe first segment is placed on the axis so that one of its endpoints lies at the point with coordinate $0$. Let's call this endpoint the \"start\" of the first segment and let's call its \"end\" as that endpoint that is not the start.\n\nThe \"start\" of each following segment must coincide with the \"end\" of the previous one. Thus, if the length of the next segment is $d$ and the \"end\" of the previous one has the coordinate $x$, the segment can be placed either on the coordinates $[x-d, x]$, and then the coordinate of its \"end\" is $x - d$, or on the coordinates $[x, x+d]$, in which case its \"end\" coordinate is $x + d$.\n\nThe total coverage of the axis by these segments is defined as their overall union which is basically the set of points covered by at least one of the segments. It's easy to show that the coverage will also be a segment on the axis. Determine the minimal possible length of the coverage that can be obtained by placing all the segments on the axis without changing their order.",
    "tutorial": "One possible solution involves the method of dynamic programming. As a state of DP we will use the number of already placed segments $i$, and the distance $l$ from the \"end\" of the last segment to the current left boundary of the coverage, and in the DP we will store the minimal possible distance from the \"end\" of the last segment to the current right boundary of the coverage. We can prove that the answer never exceeds $2 \\cdot l_{\\mathtt{max}}$, where $l_\\mathtt{max} = \\max(a)$ is the maximal length of the segments. To do this, let us define a region of length $2 \\cdot l_{\\mathtt{max}}$, specifically the segment $[-l_{\\mathtt{max}}, l_{\\mathtt{max}}]$. If the \"end\" of the last segment has a coordinate $x > 0$, we put the next segment to the left, otherwise, we put it to the right. With this algorithm, none of the \"end\" endpoints of the segments will go beyond the marked boundaries, because to do so, the segment must be placed from the coordinate of one sign beyond the boundary of the opposite sign, and thus must have a length greater than $l_{\\mathtt{max}}$ which contradicts how we defined $l_{\\mathtt{max}}$. Using this fact, we will consider the DP $\\mathtt{dp}_{i, l}$ for $0 \\le i \\le n$ and $0 \\le j \\le 2 \\cdot l_{\\mathtt{max}}$ as the minimum distance between the \"end\" of the $i$-th segment and the right boundary of the axis coverage of the first $i$ segments when the distance to the left boundary of the coverage equals to $l$. The \"end of the $0$-th segment\" here is the \"beginning\" of the first one, that is, the point $0$. The base of DP is $\\mathtt{dp}_{0, 0} = 0$, since when no segments are placed, the coverage boundaries and the current point $0$ are all coincident. Next, we consider the forward dynamic programming relaxation: for every $(i, l)$ there are two cases to consider, the case of the next segment being placed to the left and the case of it being placed to the right (value $r$ below refers to the distance to the right boundary of the coverage and is an alias for $\\mathtt{dp}_{i, l}$): If a segment of length $a_{i + 1}$ is placed to the left side, then the new distance to the left boundary will be equal to $\\max(0, l - a_{i + 1})$, and distance to the right boundary will always be $r + a_{i + 1}$, which gives us the relaxation formula $\\mathtt{dp}_{i + 1, \\max(0, l - a_{i + 1})} \\leftarrow \\mathtt{dp}_{i, l} + a_{i + 1}$ $\\mathtt{dp}_{i + 1, \\max(0, l - a_{i + 1})} \\leftarrow \\mathtt{dp}_{i, l} + a_{i + 1}$ If a segment of length $a_{i + 1}$ is placed to the right side, then the new distance to the right boundary will be equal to $\\max(0, r - a_{i + 1})$, and distance to the left boundary will always be $l + a_{i + 1}$, which gives us the relaxation formula $\\mathtt{dp}_{i + 1, l + a_{i + 1}} \\leftarrow \\max(0, \\mathtt{dp}_{i, l} - a_{i + 1})$ $\\mathtt{dp}_{i + 1, l + a_{i + 1}} \\leftarrow \\max(0, \\mathtt{dp}_{i, l} - a_{i + 1})$ The values in array $\\mathtt{dp}$ can be calculated in ascending order by $i$. Then the answer for the problem can be found as the minimum sum of $l$ and $r$ in the last row of $\\mathtt{dp}$, that is $\\min\\limits_{l} l + \\mathtt{dp}_{i, l}$. The time complexity is $\\mathcal{O}(n \\cdot l_{\\mathtt{max}})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1000000000;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        int maxl = 0;\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n            maxl = max(maxl, a[i]);\n        }\n        vector<vector<int>> dp(n + 1, vector<int>(2 * maxl + 1, INF));\n        dp[0][0] = 0;\n        for (int i = 0; i < n; i++) {\n            for (int left = 0; left <= 2 * maxl; left++) {\n                if (dp[i][left] == INF)\n                    continue;\n                dp[i + 1][max(left - a[i], 0)] = min(dp[i + 1][max(left - a[i], 0)], dp[i][left] + a[i]);\n                if (left + a[i] < dp[i + 1].size()) {\n                    dp[i + 1][left + a[i]] = min(dp[i + 1][left + a[i]], max(dp[i][left] - a[i], 0));\n                }\n            }\n        }\n\n        int ans = 2 * maxl + 1;\n        for (int left = 0; left <= 2 * maxl; left++)\n            ans = min(ans, left + dp[n][left]);\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1580",
    "index": "A",
    "title": "Portal",
    "statement": "CQXYM found a rectangle $A$ of size $n \\times m$. There are $n$ rows and $m$ columns of blocks. Each block of the rectangle is an obsidian block or empty. CQXYM can change an obsidian block to an empty block or an empty block to an obsidian block in one operation.\n\nA rectangle $M$ size of $a \\times b$ is called a portal if and only if it satisfies the following conditions:\n\n- $a \\geq 5,b \\geq 4$.\n- For all $1 < x < a$, blocks $M_{x,1}$ and $M_{x,b}$ are obsidian blocks.\n- For all $1 < x < b$, blocks $M_{1,x}$ and $M_{a,x}$ are obsidian blocks.\n- For all $1<x<a,1<y<b$, block $M_{x,y}$ is an empty block.\n- $M_{1, 1}, M_{1, b}, M_{a, 1}, M_{a, b}$ \\textbf{can be any type}.\n\nNote that the there must be $a$ rows and $b$ columns, not $b$ rows and $a$ columns.\\textbf{Note that corners can be any type}\n\nCQXYM wants to know the minimum number of operations he needs to make at least one sub-rectangle a portal.",
    "tutorial": "We can enumerate the two corner of the submatrix, calculate the answer by precalculating the prefix sums. The time complexity is $O(\\sum n^2m^2)$. When we enumerated the upper edge and the lower edge of the submatrix, we can calculate the answer by prefix sum. Assume the left edge of the submatrix is $l$, and the right edge is $r$. The part of anwer contributed by upper and lower edge are two segments, we can calculate the answer by prefix sums. The middle empty part is a submaxtrix, and we can use prefix sums too. Since we have enumerated the upper edge and lower edge, the left edge part is just about $l$, and the right part is just about $r$. Then we enumerate $l$, the answer of the best $r$ can be calculated by precalculating the suffix miniums. The time complexity is $O(\\sum{n^2m})$, space complexity is $O(nm)$.",
    "code": "#include<stdio.h>\nchar s[402];\nint sum[401][401],f[401];\ninline int GetSum(int lx,int ly,int rx,int ry){\n\treturn sum[rx][ry]-sum[rx][ly-1]-sum[lx-1][ry]+sum[lx-1][ly-1];\n}\ninline void Solve(){\n\tint n,m,i,j,k,ans=999999,cur;\n\tscanf(\"%d%d\",&n,&m);\n\tfor(i=1;i<=n;i++){\n\t\tscanf(\"%s\",s+1);\n\t\tfor(j=1;j<=m;j++){\n\t\t\tsum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+(s[j]=='1');\n\t\t}\n\t}\n\tfor(i=1;i!=n;i++){\n\t\tfor(j=i+4;j<=n;j++){\n\t\t\tfor(k=4;k<=m;k++){\n\t\t\t\tf[k]=GetSum(i+1,1,j-1,k-1)-GetSum(i,1,i,k-1)-GetSum(j,1,j,k-1)-GetSum(i+1,k,j-1,k)+(k<<1)+j-i-3;\n\t\t\t}\n\t\t\tfor(k=m-1;k!=3;k--){\n\t\t\t\tif(f[k+1]<f[k]){\n\t\t\t\t\tf[k]=f[k+1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(k=1;k!=m-2;k++){\n\t\t\t\tcur=f[k+3]-GetSum(i+1,1,j-1,k)+GetSum(i,1,i,k)+GetSum(j,1,j,k)-(k<<1)-GetSum(i+1,k,j-1,k)+j-i-1;\n\t\t\t\tif(cur<ans){\n\t\t\t\t\tans=cur;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"%d\\n\",ans);\n}\nint main(){\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile(t!=0){\n\t\tSolve();\n\t\tt--;\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1580",
    "index": "B",
    "title": "Mathematics Curriculum",
    "statement": "Let $c_1, c_2, \\ldots, c_n$ be a permutation of integers $1, 2, \\ldots, n$. Consider all subsegments of this permutation containing an integer $x$. Given an integer $m$, we call the integer $x$ good if there are exactly $m$ different values of maximum on these subsegments.\n\nCirno is studying mathematics, and the teacher asks her to count the number of permutations of length $n$ with exactly $k$ good numbers.\n\nUnfortunately, Cirno isn't good at mathematics, and she can't answer this question. Therefore, she asks you for help.\n\nSince the answer may be very big, you only need to tell her the number of permutations modulo $p$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nA sequence $a$ is a subsegment of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "Define the dp state $f_{l,s,d}$ as the number of the permutaion length of $l$ with exactly $d$ such numbers that all the subsegments containing them have exactly $s$ different maxima in total. We enumerate the position of the bigest number in the permutaion. We call the position is $a$. The numbers before $a$ and after $a$ are independent. Then we transform the statement $(l,s,d)$ to $(a-1,x,d+1)$ and $(l-a,y,d+1)$. We also have to distribute the numbers to two parts, so the dp transformation is: $f_{l,s,d}=\\sum_{a=1}^{l} \\binom{l-1}{a-1} \\sum_{x=0}^{s}f_{a-1,x,d+1}f_{l-a,s-x-[d=k],d+1}$ In addition, the answer of the problem is $f_{n,m,k}$. Actually, the dp proccess is just like a cartesian tree. The time complexity is $O(n^2m^2k)$, space complexity is $O(nmk)$. However, it's enough to pass the tests.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX_N = 100 + 5;\n\nint n, m, k, P;\nint fac[MAX_N], c[MAX_N][MAX_N], f[MAX_N][MAX_N][MAX_N];\n\nint add(int a, int b) {\n    return a + b < P ? a + b : a + b - P;\n}\n\nvoid dp(int sz, int cnt, int dep) {\n    if (f[dep][sz][cnt] != -1) return ;\n    register int &F = f[dep][sz][cnt] = 0;\n    if (!sz) {\n        F = 1;\n        return ;\n    }\n    if ((m - dep < 7 && (1 << (m - dep)) < cnt) || (cnt && sz < m - dep)) return ;\n    if (dep == m) {\n        F = (cnt == 1 ? fac[sz] : 0);\n        return ;\n    }\n    for (int i = 0; i < sz; i ++) {\n        register int fi = 0;\n        register int *fl = f[dep + 1][i], *fr = f[dep + 1][sz - i - 1];\n        for (int j = max(0, cnt + i + 1 - sz); j <= min(cnt, i); j ++)\n            if (fl[j] && fr[cnt - j]) {\n                dp(i, j, dep + 1);\n                dp(sz - i - 1, cnt - j, dep + 1);\n                fi = (fi + 1ll * fl[j] * fr[cnt - j]) % P;\n            }\n        F = (F + 1ll * fi * c[sz - 1][i]) % P;\n    }\n}\n\nint main() {\n    cin >> n >> m >> k >> P; m --;\n    for (int i = c[0][0] = fac[0] = 1; i <= n; i ++) {\n        c[i][0] = c[i][i] = 1;\n        fac[i] = 1ll * fac[i - 1] * i % P;\n        for (int j = 1; j < i; j ++) c[i][j] = add(c[i - 1][j - 1], c[i - 1][j]);\n    }\n    memset(f, -1, sizeof(f));\n    dp(n, k, 0);\n    cout << f[0][n][k] << endl;\n    return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1580",
    "index": "C",
    "title": "Train Maintenance",
    "statement": "Kawasiro Nitori is excellent in engineering. Thus she has been appointed to help maintain trains.\n\nThere are $n$ models of trains, and Nitori's department will only have at most one train of each model at any moment. In the beginning, there are no trains, at each of the following $m$ days, one train will be added, or one train will be removed. When a train of model $i$ is added at day $t$, it works for $x_i$ days (day $t$ inclusive), then it is in maintenance for $y_i$ days, then in work for $x_i$ days again, and so on until it is removed.\n\nIn order to make management easier, Nitori wants you to help her calculate how many trains are in maintenance in each day.\n\n\\textbf{On a day a train is removed, it is not counted as in maintenance.}",
    "tutorial": "Let's distinguish the trains according to $x_i + y_i$. If $x_i + y_i > \\sqrt{m}$, the total times of maintenance and running don't exceed $\\frac{m}{\\sqrt{m}}=\\sqrt{m}$. So we can find every date that the train of model $i$ begin or end maintenance in $O(\\sqrt{m})$, and we can maintain a differential sequence. We can add 1 to the beginning date and minus 1 to the end date, and the prefix sum of this sequence is the number of trains in maintenance. If $x_i + y_i \\le \\sqrt{m}$, suppose the train of model $i$ is repaired at $s_i$ day. For a date $t$ that the train of model $i$ is in maintenance if and only if $(t-s_i) \\ mod \\ (x_i+y_i) \\geq x_i$. Thus for each $a \\le \\sqrt{m}$, we can use an array of length $a$ to record the date of all trains that satisfy $x_i + y_i = a$ are in maintenance modulo $a$. And for one period of maintenance, the total days aren't exceed $\\sqrt{m}$. So we can maintain $(t - s_i) \\ mod \\ (x_i + y_i)$ in $O(\\sqrt{m})$. Thus the intended time complexity is $O(m\\sqrt{m})$ and the intended memory complexity is $O(n + m)$. Finished reading the statement, you may have thought about this easy solution as followed. Maintain an array to count the trains in maintenance in each day. For add and remove operations, traverse the array and add the contribution to the array. The algorithm works in the time complexity of $O(nm)$. Besides, we can use the difference array to modify a segment in $O(1)$. However, we can optimize this solution. For the trains of $x+y>\\sqrt m$, we can modify every period by brute force because the number of periods is less than $\\sqrt m$. For the trains of $x+y \\leqslant \\sqrt m$, the number of the periods can be large. In this case, we set the blocks, each of them sizes $O(\\sqrt m)$. We can merge the modifies which are completely included in the same block, with the same length of period and the same start position in the block. It's fine to use an array to record this. Number of segments are not completely included in the block is about $O(\\sqrt m)$. The total complexity is $O(m\\sqrt m)$.",
    "code": "#include <bits/stdc++.h>\n\nchar BUF_R[1 << 22], *csy1, *csy2;\n#define GC (csy1 == csy2 && (csy2 = (csy1 = BUF_R) + fread(BUF_R, 1, 1 << 22, stdin), csy1 == csy2) ? EOF : *csy1 ++)\n\ntemplate <typename Ty>\ninline void RI(Ty &t) {\n    char c = GC;\n    for (t = 0; c < 48 || c > 57; c = GC);\n    for (; c > 47 && c < 58; c = GC) t = t * 10 + (c ^ 48);\n}\n\nconst int MAX_N = 200000 + 5;\nconst int MAX_M = 256;\nint n, m, thre, x[MAX_N], y[MAX_N], cnt[MAX_M][MAX_M], s[MAX_N], a[MAX_N], ans;\n\nvoid block_modify(int Tm, int k, int v) {\n    int bl = x[k] + y[k], *c = cnt[bl];\n    int l = (Tm + x[k]) % bl, r = (Tm - 1) % bl;\n    if (l <= r) for (int i = l; i <= r; i ++) c[i] += v;\n    else {\n        for (int i = 0; i <= r; i ++) c[i] += v;\n        for (int i = l; i < bl; i ++) c[i] += v;\n    }\n}\n\nint block_query(int Tm) {\n    register int res = 0;\n    for (int i = 2; i <= thre; i ++) res += cnt[i][Tm % i];\n    return res;\n}\n\nint main() {\n    RI(n); RI(m);\n    thre = std::min((int)(0.5 * sqrt(m)) + 1, 255);\n    for (int i = 1; i <= n; i ++) {RI(x[i]); RI(y[i]);}\n    for (int i = 1; i <= m; i ++) {\n        int opt, k;\n        RI(opt); RI(k);\n        if (opt == 1) {\n            if (thre < x[k] + y[k]) {\n                for (int j = i + x[k]; j <= m; j += x[k] + y[k]) {\n                    a[j] ++;\n                    if (j + y[k] <= m) a[j + y[k]] --;\n                }\n            }else block_modify(i, k, 1);\n            s[k] = i;\n        }else {\n            if (thre < x[k] + y[k]) {\n                for (int j = s[k] + x[k]; j <= m; j += x[k] + y[k]) {\n                    a[j] --;\n                    if (j + y[k] <= m) a[j + y[k]] ++;\n                    if (j < i && j + y[k] >= i) ans --;\n                }\n            }else block_modify(s[k], k, -1);\n        }\n        ans += a[i];\n        printf(\"%d\\n\", ans + block_query(i));\n    }\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1580",
    "index": "D",
    "title": "Subsequence",
    "statement": "Alice has an integer sequence $a$ of length $n$ and \\textbf{all elements are different}. She will choose a subsequence of $a$ of length $m$, and defines the value of a subsequence $a_{b_1},a_{b_2},\\ldots,a_{b_m}$ as $$\\sum_{i = 1}^m (m \\cdot a_{b_i}) - \\sum_{i = 1}^m \\sum_{j = 1}^m f(\\min(b_i, b_j), \\max(b_i, b_j)),$$ where $f(i, j)$ denotes $\\min(a_i, a_{i + 1}, \\ldots, a_j)$.\n\nAlice wants you to help her to maximize the value of the subsequence she choose.\n\nA sequence $s$ is a subsequence of a sequence $t$ if $s$ can be obtained from $t$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "First we can change the way we calculate the value of a subsequence. We can easily see the value of a subsequence $a_{b_1},a_{b_2},\\ldots ,a_{b_m}$ is also $\\sum_{i = 1}^m \\sum_{j = i + 1}^m a_{b_i} + a_{b_j} - 2 \\times f(b_i, b_j)$, which is very similar to the distance of two node on a tree. Thus we can build the cartesian tree of the sequence, and set the weight of a edge between node $i$ and $j$ as $|a_i - a_j|$. Then we can see what we are going to calculate turns into follows : choosing $m$ nodes, maximize the total distance between every two nodes. Thus we can solve this task using dynamic programming with the time complexity $O(n^2)$. From the statement, we'd calculate the sums like $a_i+a_j-Min_{k=i}^j a_k$. When we put this on a cartesian tree, it turns out to be $a_i+a_j-a_{LCA(i,j)}$. Set the weigth of the edge $x \\rightarrow y$ as $a_y-a_x$, $a_i+a_j-a_{LCA(i,j)}$ equals to the distance between node $i,j$ on the tree. Define the dp state $f_{i,j}$ as the maxium answer in the subtree rooted at node $i$, and we choose $j$ of the nodes in the subtree. Enumerate how many nodes we choose in the subtree of left-son of node $i$, number of nodes of right-son, and whether node $i$ is chose. The contribution made by the edge is its weight times the number of nodes are chose. Since a pair of node will contribute time complexity only when we are calculating the dp state of their LCA, the total time complexity is $O(n^2)$.",
    "code": "#include <cstdio>\n#include <algorithm>\n\ntypedef long long ll;\n\nconst int MAX_N = 4000 + 5;\n\nint N, M, a[MAX_N], ls[MAX_N], rs[MAX_N], lw[MAX_N], rw[MAX_N], sz[MAX_N];\nll f[MAX_N][MAX_N];\n\ninline void umax(ll &a, ll b) {\n    a = a < b ? b : a;\n}\n\nvoid dfs(int u) {\n    sz[u] = 1;\n    if (ls[u]) {\n        dfs(ls[u]);\n        for (int i = std::min(M, sz[u]); i >= 0; i --)\n            for (int j = std::min(M, sz[ls[u]]); j >= 0; j --)\n                umax(f[u][i + j], f[u][i] + f[ls[u]][j] + 1ll * j * (M - j) * lw[u]);\n        sz[u] += sz[ls[u]];\n    }\n    if (rs[u]) {\n        dfs(rs[u]);\n        for (int i = std::min(M, sz[u]); i >= 0; i --)\n            for (int j = std::min(M, sz[rs[u]]); j >= 0; j --)\n                umax(f[u][i + j], f[u][i] + f[rs[u]][j] + 1ll * j * (M - j) * rw[u]);\n        sz[u] += sz[rs[u]];\n    }\n}\n\nint main() {\n    scanf(\"%d%d\", &N, &M);\n    static int sta[MAX_N], tp;\n    for (int i = 1; i <= N; i ++) {\n        scanf(\"%d\", a + i);\n        int k = tp;\n        for (; k && a[i] < a[sta[k]]; k --);\n        if (k) {\n            rs[sta[k]] = i;\n            rw[sta[k]] = a[i] - a[sta[k]];\n        }\n        if (k < tp) {\n            ls[i] = sta[k + 1];\n            lw[i] = a[sta[k + 1]] - a[i];\n        }\n        sta[++ k] = i;\n        tp = k;\n    }\n    dfs(sta[1]);\n    printf(\"%lld\\n\", f[sta[1]][M]);\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "divide and conquer",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1580",
    "index": "E",
    "title": "Railway Construction",
    "statement": "Because the railway system in Gensokyo is often congested, as an enthusiastic engineer, Kawasiro Nitori plans to construct more railway to ease the congestion.\n\nThere are $n$ stations numbered from $1$ to $n$ and $m$ two-way railways in Gensokyo. Every two-way railway connects two different stations and has a positive integer length $d$. No two two-way railways connect the same two stations. Besides, it is possible to travel from any station to any other using those railways. Among these $n$ stations, station $1$ is the main station. You can get to any station from any other station using only two-way railways.\n\nBecause of the technological limitation, Nitori can only construct one-way railways, whose length can be arbitrary positive integer. Constructing a one-way railway from station $u$ will costs $w_u$ units of resources, no matter where the railway ends. To ease the congestion, Nitori plans that after construction there are at least two shortest paths from station $1$ to any other station, and these two shortest paths do not pass the same station except station $1$ and the terminal. Besides, Nitori also does not want to change the distance of the shortest path from station $1$ to any other station.\n\nDue to various reasons, sometimes the cost of building a new railway will increase uncontrollably. There will be a total of $q$ occurrences of this kind of incident, and the $i$-th event will add additional amount of $x_i$ to the cost of building a new railway from the station $k_i$.\n\nTo save resources, before all incidents and after each incident, Nitori wants you to help her calculate the minimal cost of railway construction.",
    "tutorial": "For convenience, we first define $dis[u]$ as the length of the shortest path between node 1 and node $u$ and \"distance\" of node $u$ as $dis[u]$, and call node $u$ is \"deeper\" than node $v$ if and only if $dis[u] > dis[v]$. Similarly, we call node $u$ is \"lower\" than node $v$ if and only if $dis[u] < dis[v]$. We will use $u$ -> $v$ to denote a a directed edge staring at node $u$ and ending at node $v$, and use $u$ --> $v$ to denote an arbitrary path staring at node $u$ and ending at node $v$. We call two paths \"intersect\" if and only if they pass through at least 1 same node. First let's focus on several facts. Since all edges' weights are positive, and we have to make sure that the distance of every node does not change, for any node $u$, we can only add edges starting at a node whose distance is strictly less than $dis[u]$. Besides, we can always add edge 1 -> $u$, but we can never add edge $u$ -> 1. Since the distance of every node does not change and the train only pass through the shortest path, if an edge is not on the shortest path at first, however we add edges it won't be on any shortest path. Thus we can first calculate the shortest path and then remove all edges which are not on the shortest path. We can easily see that the new graph is a $DAG$ (Directed Acyclic Graph). And in this graph the topological order is also the ascending order of nodes' distances. In the following part of this tutorial, we will use the new graph instead of the original graph. After we add all edges, every node except node 1 must have at least 2 incoming edges. Then let's prove a lemma: if every node except node 1 exactly has 2 incoming edges, the graph will meet the requirement. We will use mathematical induction method to prove the lemma. For an arbitrary node $u$, we suppose that all nodes whose distance is less than $u$'s has met the requirement, and we only need to prove that node $u$ also meets the requirement. Suppose the start of the 2 incoming edges is separately $s$ and $t$. First, if $s$ or $t$ is node 1, we can simply choose $1$ --> $u$ and $1$ --> $t$ -> $u$ as the two paths and obviously they don't intersect. Thus it meet the requirement. Second, if $s$ and $t$ are not node 1. We choose an arbitrary path $1$ --> $s$ and call it path 0. According to our assumption, we can choose two different paths starting at node 1 and ending at node $t$, and the two paths don't intersect. We call them path 1 and path 2 separately. If path 0 and path 1 (or path 2) doesn't intersect, then we can choose path 0 and path 1 to meet the requirement. Thus we only need to consider the situation that path 0 intersect with both path 1 and path 2. In this case, we first find the lowest and deepest node where path 0 and path 1 or path 2 intersect, and call them $a$ and $b$ separately. If the both are the intersect points of path 0 and path 1, like the case below, we can choose path (1 -> a -> (through path 1, i.e. blue path) b -> s) and path 2. Otherwise, like the case below, we can choose path (1 -> a -> t) and path (1 -> b -> s). Both cases are meet the requirement. Thus we've proved the lemma. So we only need to make sure that every node except node 1 has at least 2 incoming edges. Then we can get the following solution if $w$ is fixed: For every node which has only 1 incoming edge, we record the start point of the incoming edge in an array. Then We scan all nodes in the ascending order of nodes' distances, and maintain the previous minima and second minima of $w$ in an array $val$, adding edges greedy. Note that we only need to maintain the index of $w$ instead of its real value. This solution consumes $O(n)$ to calculate for a fixed $w$, so the total complexity is $O(nq)$. To accelerate the solution, let's try maintaining array $val$ while changing $w$. And we will apply all the changes in reverse order. That is, we only consider the case that $w$ is decreasing. According to the value of $val$, we can separate the sequence into many subsegments, and we can use std::set to maintain those subsegments. For one change in $w_k$, it will affect a particular suffix of $val$, so we can first find the suffix. Then we consecutively change the array $val$ until $w_k$ is greater than current subsegment's second minima. Next we will prove that the solution works in $O((n+q)logn)$. When we change a particular subsegment, we separate the operation into 3 types according to the relationship between $w_k$ and the subsegment's $val$. If $w_k$ is exactly the minima of the subsegment. This kind of operation may be done many times, but we will find that it won't change $val$ at all. So we can do them at a time using segment tree. Thus in one change we will only do it at most 1 time. If $w_k$ is the second minima of the subsegment. Note the fact that every subsegment must has different second minima, so this kind of operation will be also done at most once in one change. If $w_k$ is neither the minima nor the second minima of the subsegment. Note the fact that each time we do it, except the first time, will make the number of subsegments decrease by 1. Thus this kind of operation will be done no more than $n+q$ times. Using std::set and segment tree, all of these operations could be done in $O(logn)$ at a time. Thus the total complexity is $O((n+q)logn)$. In conclusion, we can solve this task in $O(mlogm + (n+q)logn)$.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <queue>\n#include <set>\n\nusing std::set;\n\ntypedef long long ll;\n\nchar BUF_R[1 << 22], *csy1, *csy2;\n#define GC (csy1 == csy2 && (csy2 = (csy1 = BUF_R) + fread(BUF_R, 1, 1 << 22, stdin), csy1 == csy2) ? EOF : *csy1 ++)\n\ntemplate <class T>\ninline void RI(T &t) {\n\tchar c = GC;\n\tfor (t = 0; c < 48 || c > 57; c = GC);\n\tfor (; c > 47 && c < 58; c = GC) t = t * 10 + (c ^ 48);\n}\n\nconst int MAX_N = 200000 + 5;\nconst int MAX_M = 600000 + 5;\nconst int INF32 = 0x7fffffff;\nconst ll INF64 = 0x3fffffffffffffffll;\n\nint N, M, Q, ques[MAX_N][2];\nstruct Edge{\n    int y, prev, len;\n}e[MAX_M];\nint elast[MAX_N], ecnt = 1;\nstd::priority_queue < std::pair <ll, int> > pq;\nll dis[MAX_N], w[MAX_N];\nunsigned long long res[MAX_N], ans;\nint cnt[MAX_N], fa[MAX_N], a[MAX_N], t;\nint rt[MAX_N], pos[MAX_N], sum[MAX_N], endpos[MAX_N];\nstruct Node{\n    int f, s;\n    \n    Node (int a = 0, int b = 0) : f(a), s(b) {}\n    \n    inline bool operator == (const Node &comp) const {return f == comp.f && s == comp.s;}\n    \n    inline void swap() {\n        int t = f;\n        f = s;\n        s = t;\n    }\n}minv, val[MAX_N];\nset <int> s;\n\nnamespace SGT{\n    const int MAX_M = 10000000;\n    \n    int tot;\n    struct SegmentNode{\n        int sum, ls, rs;\n    }node[MAX_M];\n    \n    void segment_modify(int &i, int l, int r, int x) {\n        i = i ? i : ++ tot;\n        node[i].sum ++;\n        if (l == r) return ;\n        int mid = (l + r) >> 1;\n        mid < x ? segment_modify(node[i].rs, mid + 1, r, x) : segment_modify(node[i].ls, l, mid, x);\n    }\n    \n    int segment_query(int i, int l, int r, int ql, int qr) {\n        if (!i) return 0;\n        if (l < ql || r > qr) {\n            int mid = (l + r) >> 1, res = 0;\n            if (mid >= ql) res = segment_query(node[i].ls, l, mid, ql, qr);\n            if (mid < qr) res += segment_query(node[i].rs, mid + 1, r, ql, qr);\n            return res;\n        }else return node[i].sum;\n    }\n}\n\nint count_illegal(int idx, int l, int r) {\n    if (r < l || idx == 1) return 0;\n    return SGT::segment_query(rt[idx], 1, N, l, r);\n}\n\nint count_legal(int idx, int l, int r) {\n    if (r < l) return 0;\n    return sum[r] - sum[l - 1] - count_illegal(idx, l, r);\n}\n\nvoid Build(int x, int y, int z) {\n    ecnt ++;\n    e[ecnt].y = y;\n    e[ecnt].len = z;\n    e[ecnt].prev = elast[x];\n    elast[x] = ecnt;\n}\n\nint main() {\n    RI(N); RI(M); RI(Q);\n    for (int i = 1; i <= N; i ++) {\n        RI(w[i]);\n        pos[i] = N + 1;\n        dis[i] = INF64;\n    }\n    for (int i = 1; i <= M; i ++) {\n        int x, y, z;\n        RI(x); RI(y); RI(z);\n        Build(x, y, z);\n        Build(y, x, z);\n    }\n    for (int i = 1; i <= Q; i ++) {\n        RI(ques[i][0]); RI(ques[i][1]);\n        w[ques[i][0]] += ques[i][1];\n    }\n    \n    dis[1] = 0;\n    pq.push(std::make_pair(0, 1));\n    while (!pq.empty()) {\n        int u = pq.top().second;\n        ll d = -pq.top().first;\n        pq.pop();\n        if (dis[u] != d) continue;\n        a[++ t] = u;\n        for (int i = elast[u]; i; i = e[i].prev) {\n            int v = e[i].y;\n            if (d + e[i].len < dis[v]) {\n                dis[v] = d + e[i].len;\n                pq.push(std::make_pair(-dis[v], v));\n            }\n        }\n    }\n    for (int i = 2; i <= ecnt; i ++) {\n        int u = e[i ^ 1].y, v = e[i].y;\n        if (dis[u] + e[i].len == dis[v]) {\n            cnt[v] ++; fa[v] = u;\n        }\n    }\n    \n    ans = 0;\n    s.insert(1);\n    pos[1] = 1;\n    minv.f = 1;\n    minv.s = N + 1;\n    val[1] = minv;\n    w[N + 1] = INF64;\n    for (int i = 2, j = 2; i <= N; i ++) {\n        int u = a[i];\n\t\tfor (; dis[a[j]] < dis[u]; j ++) {\n\t\t    int v = a[j];\n\t\t    pos[v] = i;\n    \t\tif (w[v] < w[minv.f]) {\n    \t\t    s.insert(i);\n    \t\t    endpos[minv.f] = i;\n    \t\t    minv.s = minv.f;\n    \t\t    minv.f = v;\n    \t\t    val[i] = minv;\n    \t\t}else if (w[v] < w[minv.s]) {\n    \t\t    s.insert(i);\n    \t\t    minv.s = v;\n    \t\t    val[i] = minv;\n    \t\t}\n    \t}\n    \tsum[i] = sum[i - 1];\n        if (cnt[u] < 2) {\n            sum[i] ++;\n            if (fa[u] > 1) SGT::segment_modify(rt[fa[u]], 1, N, i);\n\t\t    ans += w[(minv.f == 1 || minv.f != fa[u]) ? minv.f : minv.s];\n\t\t}\n    }\n    endpos[minv.f] = N + 1;\n    s.insert(N + 1);\n    res[Q] = ans;\n    \n    for (int i = Q; i > 0; i --) {\n        int k = ques[i][0], x = ques[i][1];\n        w[k] -= x;\n        if (pos[k] > N) {\n            res[i - 1] = ans;\n            continue;\n        }\n        set <int>::iterator it = -- s.upper_bound(pos[k]), lst;\n        minv = Node();\n        int response = 0, p = pos[k];\n        if (k == val[*it].f) response = 1;\n        else if (k == val[*it].s) response = 2;\n        while (response >= 0 && *it <= N) {\n            lst = it ++;\n            if (response == 0) {\n                if (w[val[*lst].s] <= w[k]) break;\n                if (w[k] < w[val[*lst].f]) {\n                    if (!minv.f) endpos[val[*lst].f] = p;\n                    int c = count_illegal(val[*lst].f, p, (*it) - 1), tot = sum[(*it) - 1] - sum[p - 1];\n                    ans -= 1ull * c * w[val[*lst].s] + 1ll * (tot - c) * w[val[*lst].f];\n                    if (p != *lst) val[p] = val[*lst];\n                    val[p].s = val[p].f;\n                    val[p].f = k;\n                    c = count_illegal(k, p, (*it) - 1);\n                    ans += 1ull * c * w[val[p].s] + 1ll * (tot - c) * w[k];\n                    if (p != *lst) {\n                        s.insert(p);\n                        minv = val[p];\n                    }else if (minv == val[p]) s.erase(lst);\n                    else minv = val[p];\n                    endpos[k] = p = *it;\n                }else {\n                    ans += 1ull * count_illegal(val[*lst].f, p, (*it) - 1) * (w[k] - w[val[*lst].s]);\n                    if (p != *lst) val[p] = val[*lst];\n                    val[p].s = k;\n                    if (p != *lst) {\n                        s.insert(p);\n                        minv = val[p];\n                    }else if (minv == val[p]) s.erase(lst);\n                    else minv = val[p];\n                    p = *it;\n                }\n            }else if (response == 1) {\n                it = s.lower_bound(endpos[k]);\n                ans -= 1ull * count_legal(k, p, (*it) - 1) * x;\n                p = *it; lst = it; lst --;\n                minv = val[*lst];\n                response = val[p].s == k ? 2 : 0;\n            }else {\n                if (w[val[*lst].f] <= w[k]) {\n                    ans -= 1ull * count_illegal(val[*lst].f, p, (*it) - 1) * x;\n                    minv = val[*lst]; p = *it;\n                }else {\n                    endpos[val[*lst].f] = p;\n                    int c = count_illegal(val[*lst].f, p, (*it) - 1), tot = sum[(*it) - 1] - sum[p - 1];\n                    ans -= 1ull * c * (w[val[*lst].s] + x) + 1ull * (tot - c) * w[val[*lst].f];\n                    if (p != *lst) val[p] = val[*lst];\n                    val[p].swap();\n                    c = count_illegal(val[p].f, p, (*it) - 1);\n                    ans += 1ull * c * w[val[p].s] + 1ull * (tot - c) * w[val[p].f];\n                    if (p != *lst) {\n                        s.insert(p);\n                        minv = val[p];\n                    }else if (minv == val[p]) s.erase(lst);\n                    else minv = val[p];\n                    endpos[k] = p = *it;\n                }\n                response = 0;\n            }\n        }\n        res[i - 1] = ans;\n    }\n    \n    for (int i = 0; i <= Q; i ++) printf(\"%llu\\n\", res[i]);\n    \n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "graphs",
      "shortest paths"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1580",
    "index": "F",
    "title": "Problems for Codeforces",
    "statement": "XYMXYM and CQXYM will prepare $n$ problems for Codeforces. The difficulty of the problem $i$ will be an integer $a_i$, where $a_i \\geq 0$. The difficulty of the problems must satisfy $a_i+a_{i+1}<m$ ($1 \\leq i < n$), and $a_1+a_n<m$, where $m$ is a fixed integer. XYMXYM wants to know how many plans of the difficulty of the problems there are modulo $998\\,244\\,353$.\n\nTwo plans of difficulty $a$ and $b$ are different only if there is an integer $i$ ($1 \\leq i \\leq n$) satisfying $a_i \\neq b_i$.",
    "tutorial": "If two numbers $a,b$ satisfying $a+b<m$, there can only be one number not less than $\\lceil \\frac{m}{2} \\rceil$. Consider that cut the cycle to a sequence at the first position $p$ satisfying $\\max(a_p,a_{p+1})<\\lceil \\frac{m}{2} \\rceil$. When we minus all the numbers that are not less than $\\lceil \\frac{m}{2} \\rceil$ by $\\lceil \\frac{m}{2} \\rceil$, we can get a sub-problem. However, If $n$ is an even number, we may not find such a position $p$, but we can still get a sub-problem easily. For this problem on a sequence, we can divide the sequence into many segments, and each of them can not be cut by us anymore. There may be only $1$ segment, and the first, last element of the segment are not less than $\\lceil \\frac{m}{2} \\rceil$. There may be many segments, the length of the first one and last one are even, and the rest of them are odd. To solve the problem, we define the GF A,B. A is the GF of the length of the segments are odd situation, and B is the even one. If $m$ is odd, the segment with only a number $[\\frac{m}{2}]$ exists, and the GF of number of the sequence should be: $B^2(\\sum_{i=0} (A+x)^i)+A=\\frac{B^2}{1-x-A}+A$ Otherwise, it is: $B^2(\\sum_{i=0} A^i)+A=\\frac{B^2}{1-A}+A$. To solve this problem, use NTT and polynomial inversion algorithm is just ok. Each time we transform a problem with limit $m$ to $\\frac{m}{2}$, so the time complexity is $O(n \\log n \\log m)$. UPD: Chinese editorial can be found here.",
    "code": "#include<stdio.h>\n#include<memory.h>\n#define mod 998244353\n\nunsigned long long tmp[131073],invn;\nint a_[131072];\n\ninline int ksm(unsigned long long a,int b){int ans=1;while(b)(b&1)&&(ans=a*ans%mod),a=a*a%mod,b>>=1;return ans;}\nvoid init(int n){\n\tfor(int i=1;i<n;i++)a_[i]=i&1?a_[i^1]|n>>1:a_[i>>1]>>1;\n\tfor(int i=tmp[0]=1,j=ksm(3,(mod-1)/n);i<=n;i++)tmp[i]=tmp[i-1]*j%mod;\n\tinvn=ksm(n,mod-2);\n}\nvoid ntt(int a[],int n,bool typ){\n\tint p;\n\tfor(int i=1;i<n;i++)if(a_[i]<i)p=a[i],a[i]=a[a_[i]],a[a_[i]]=p;\n\tif(typ)for(int i=1,d=n>>1;d;i<<=1,d>>=1)for(int j=0;j<n;j+=i<<1)for(int k=0;k<i;k++)\n\t\tp=tmp[n-d*k]*a[i+j+k]%mod,(a[i+j+k]=a[j+k]+mod-p)>=mod&&(a[i+j+k]-=mod),(a[j+k]+=p)>=mod&&(a[j+k]-=mod);\n\telse for(int i=1,d=n>>1;d;i<<=1,d>>=1)for(int j=0;j<n;j+=i<<1)for(int k=0;k<i;k++)\n\t\tp=tmp[d*k]*a[i+j+k]%mod,(a[i+j+k]=a[j+k]+mod-p)>=mod&&(a[i+j+k]-=mod),(a[j+k]+=p)>=mod&&(a[j+k]-=mod);\n\tif(typ)for(int i=0;i<n;i++)a[i]=invn*a[i]%mod;\n}\nvoid getinv(int n,int a[],int b[]){\n\tstatic int tmp[131072];\n\tmemset(b,0,sizeof(int)*(n<<1));\n\tb[0]=ksm(a[0],mod-2);\n\tfor(int i=1;i<n;i<<=1){\n\t\tinit(i<<2);\n\t\tmemset(tmp,0,sizeof(int)*(i<<2));\n\t\tmemcpy(tmp,a,sizeof(int)*(i<<1));\n\t\tntt(tmp,i<<2,0);\n\t\tntt(b,i<<2,0);\n\t\tfor(int j=0;j<i<<2;j++)b[j]=(1ull*(mod-tmp[j])*b[j]%mod+2)*b[j]%mod;\n\t\tntt(b,i<<2,1);\n\t\tmemset(b+(i<<1),0,sizeof(int)*(i<<1));\n\t}\n}\n\nint n,m,a[131072],b[131072],d0[131072],d1[131072],len,ans;\n\nvoid work(int v){\n\tif(v==1){\n\t\tfor(int i=0;i<len;i++)a[i]=1;\n\t\tans=1;\n\t\treturn;\n\t}\n\twork(v>>1);\n\tmemset(d0,0,sizeof(int)*(len<<1));\n\tmemset(d1,0,sizeof(int)*(len<<1));\n\tfor(int i=0;i<len;i++)(i&1?d1:d0)[i]=a[i];\n\tif(v&1)++d1[1]==mod&&(d1[1]=0);\n\tmemset(a,0,sizeof(int)*(len<<1));\n\tfor(int i=0;i<len;i++)a[i]=d1[i]?mod-d1[i]:0;\n\t++a[0]==mod&&(a[0]=0);\n\tgetinv(len,a,b);\n\tif(v==m||!(n&1)){\n\t\tint Ans=0;\n\t\tfor(int i=1;i<=n;i+=2)\n\t\t\tAns=(1ull*d1[i]*b[n-i]%mod*i+Ans)%mod;\n\t\tif(!(n&1))ans=(2ull*ans+Ans)%mod;\n\t\telse ans=Ans;\n\t\tif(v==m)return;\n\t}\n\tinit(len<<1);\n\tntt(d0,len<<1,0);\n\tfor(int i=0;i<len<<1;i++)d0[i]=1ull*d0[i]*d0[i]%mod;\n\tntt(d0,len<<1,1);\n\tmemset(d0+len,0,sizeof(int)*len);\n\tntt(d0,len<<1,0);\n\tntt(b,len<<1,0);\n\tfor(int i=0;i<len<<1;i++)a[i]=1ull*d0[i]*b[i]%mod;\n\tntt(a,len<<1,1);\n\tfor(int i=1;i<len;i+=2)(a[i]+=d1[i])>=mod&&(a[i]-=mod);\n\tif(v&1)a[1]?a[1]--:a[1]=mod-1;\n}\n\nint main(){\n\tscanf(\"%d%d\",&n,&m);\n\tlen=n<<1;\n\twhile(len^len&-len)len^=len&-len;\n\twork(m);\n\tprintf(\"%d\\n\",ans);\n}",
    "tags": [
      "combinatorics",
      "fft",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1581",
    "index": "A",
    "title": "CQXYM Count Permutations",
    "statement": "CQXYM is counting permutations length of $2n$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nA permutation $p$(length of $2n$) will be counted only if the number of $i$ satisfying $p_i<p_{i+1}$ is no less than $n$. For example:\n\n- Permutation $[1, 2, 3, 4]$ will count, because the number of such $i$ that $p_i<p_{i+1}$ equals $3$ ($i = 1$, $i = 2$, $i = 3$).\n- Permutation $[3, 2, 1, 4]$ won't count, because the number of such $i$ that $p_i<p_{i+1}$ equals $1$ ($i = 3$).\n\nCQXYM wants you to help him to count the number of such permutations modulo $1000000007$ ($10^9+7$).\n\nIn addition, modulo operation is to get the remainder. For example:\n\n- $7 \\mod 3=1$, because $7 = 3 \\cdot 2 + 1$,\n- $15 \\mod 4=3$, because $15 = 4 \\cdot 3 + 3$.",
    "tutorial": "Assume a permutation $p$, and $\\sum_{i=2}^{2n}[p_{i-1}<p_i]=k$. Assume a permutaion $q$, satisfying $\\forall 1 \\leqslant i \\leqslant 2n, q_i=2n-p_i$. We can know that $\\forall 2 \\leqslant i \\leqslant 2n,[p_{i-1}<p_i]+[q_{i-1}<q_i]=1$. Thus,$\\sum_{i=2}^{2n}[q_{i-1}<q_i]=2n-1-k$, and either $p$ should be counted or $q$ should be counted. All in all, the half of all the permutaions would be counted in the answer. Thus, the answer is $\\frac{1}{2}(2n)!$. The time complexity is $O(\\sum n)$. If you precalulate the factors, then the complexity will be $O(t+n)$.",
    "code": "#include<stdio.h>\nint f[100001];\nint main(){\n\tf[1]=1;\n\tfor(register int i=2;i!=100001;i++){\n\t\tf[i]=((i<<1)-1ll)*f[i-1]%1000000007*(i<<1)%1000000007;\n\t}\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor(register int i=n;i!=0;i--){\n\t\tscanf(\"%d\",&n);\n\t\tprintf(\"%d\\n\",f[n]);\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1581",
    "index": "B",
    "title": "Diameter of Graph",
    "statement": "CQXYM wants to create a connected undirected graph with $n$ nodes and $m$ edges, and the diameter of the graph must be strictly less than $k-1$. Also, CQXYM doesn't want a graph that contains self-loops or multiple edges (i.e. each edge connects two different vertices and between each pair of vertices there is at most one edge).\n\nThe diameter of a graph is the maximum distance between any two nodes.\n\nThe distance between two nodes is the minimum number of the edges on the path which endpoints are the two nodes.\n\nCQXYM wonders whether it is possible to create such a graph.",
    "tutorial": "If $m < n-1$, the graph can't be connected, so the answer should be No. If $m > \\frac{n(n-1)}{2}$, the graph must contaion multiedges, so the answer should be No. If $m=\\frac{n(n-1)}{2}$, the graph must be a complete graph. The diameter of the graph is $1$. If $k>2$ the answer is YES, otherwise the answer is NO. If $n=1$, the graph has only one node, and its diameter is $0$. If $k>1$ the answer is YES, otherwise the answer is NO. If $m=n-1$, the graph must be a tree, the diameter of the tree is at least $2$ when it comes to each node has an edge with node $1$. If $m>n-1 \\wedge m<\\frac{n(n-1)}{2}$, we can add edges on the current tree and the diameter wouldn't be more than $2$. Since the graph is not complete graph, the diameter is more than $1$, the diameter is just $2$. If $k>3$ the answer is YES, otherwise the answer is NO. The time complexity is $O(t)$.",
    "code": "#include<stdio.h>\ninline void Solve(){\n\tint n,m,k;\n\tscanf(\"%d%d%d\",&n,&m,&k);\n\tif((n-1ll)*n>>1<m||m<n-1){\n\t\tputs(\"NO\");\n\t\treturn;\n\t}\n\tif(n==1){\n\t\tif(k>1){\n\t\t\tputs(\"YES\");\n\t\t}else{\n\t\t\tputs(\"NO\");\n\t\t}\n\t}else if(m<(n-1ll)*n>>1){\n\t\tif(k>3){\n\t\t\tputs(\"YES\");\n\t\t}else{\n\t\t\tputs(\"NO\");\n\t\t}\n\t}else if(k>2){\n\t\tputs(\"YES\");\n\t}else{\n\t\tputs(\"NO\");\n\t}\n}\nint main(){\n\tint t;\n\tscanf(\"%d\",&t);\n\tfor(register int i=0;i!=t;i++){\n\t\tSolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1582",
    "index": "A",
    "title": "Luntik and Concerts",
    "statement": "Luntik has decided to try singing. He has $a$ one-minute songs, $b$ two-minute songs and $c$ three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.\n\nHe wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.\n\nPlease help Luntik and find the minimal possible difference in minutes between the concerts durations.",
    "tutorial": "Let $S$ be the sum of durations of all songs, that is $S = a + 2 \\cdot b + 3 \\cdot c$. Let's notice that since $a, b, c \\ge 1$, it is possible to make a concert of any duration from $0$ to $S$ (indeed, if we just execute a greedy algorithm and take three-minute songs while possible, then take two-minute songs, and then one-minute ones, we can get any duration we need). Now, the answer is the remainder of $S$ modulo $2$, because if $S$ is even, then it's possible to from the first concert with duration $\\frac{S}{2}$, and the second one will be left with duration $S-\\frac{S}{2}=\\frac{S}{2}$, and the difference between the durations will be $0$. If $S$ is odd, then the smallest possible difference is equal to $1$, let's form the first concert with duration $\\left \\lfloor{\\frac{S}{2}}\\right \\rfloor$, and the second one is left with duration $\\left \\lceil{\\frac{S}{2}}\\right \\rceil$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t, a, b, c;\n    cin >> t;\n    while (t--) {\n        cin >> a >> b >> c;\n        cout << (a + c) % 2 << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1582",
    "index": "B",
    "title": "Luntik and Subsequences",
    "statement": "Luntik came out for a morning stroll and found an array $a$ of length $n$. He calculated the sum $s$ of the elements of the array ($s= \\sum_{i=1}^{n} a_i$). Luntik calls a subsequence of the array $a$ nearly full if the sum of the numbers in that subsequence is equal to $s-1$.\n\nLuntik really wants to know the number of nearly full subsequences of the array $a$. But he needs to come home so he asks you to solve that problem!\n\nA sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "It can be noticed that all subsequences with sum $s-1$ appear if we erase some $0$-es from the array and also erase exactly one $1$. We can independently calculate the number of ways to erase some $0$-es from the array (that way the sum will remain the same), then calculate the number of ways to erase exactly one $1$ from the array (that way the sum will become equal to $s-1$), and then multiply these two numbers. Therefore, the answer is equal to $2^{c_0} \\cdot c_1$, where $c_0$ is the number of $0$-es in the array, and $c_1$ is the number of $1$-s.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t, n, x;\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        int cnt0 = 0, cnt1 = 0;\n        for (int i = 1; i <= n; ++i) {\n            cin >> x;\n            if (x == 0) cnt0++;\n            if (x == 1) cnt1++;\n        }\n        cout << (1ll << cnt0) * (ll)cnt1 << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1582",
    "index": "C",
    "title": "Grandma Capa Knits a Scarf",
    "statement": "Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $s$ of length $n$.\n\nGrandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $s$.\n\nShe also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $s$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the \\textbf{one} letter she chose.\n\nA string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.",
    "tutorial": "Let's iterate over the letter that we will erase from the string (from 'a' to 'z'), and for each letter independently find the minimal number of erased symbols required to make the string a palindrome. Let's say we are currently considering a letter $c$. Let's use the two pointers method: we will maintain two pointers $l$, $r$, initially $l$ points at the beginning of the string, and $r$ points at the end of the string. Now we will form a palindrome: each time we will compare $s_l$ and $s_r$, if they are equal, then we can add both of them to the palindrome at corresponding positions and iterate to symbols $l+1$ and $r-1$. If $s_l \\neq s_r$, then we need to erase one of these symbols (otherwise, we won't get a palindrome), if $s_l=c$, let's erase it (we'll add to the number of erased symbols $1$ and iterate to $l+1$-th symbol), similarly, if $s_r=c$, we'll add to the number of the erased symbols $1$ and iterate to $r-1$-th symbol. And the last case, if $s_l \\neq c$ and $s_r \\neq c$, then it's impossible to get a palindrome from $s$ by erasing only letters equal to $c$. The asymptotic behaviour of this solution is $O(|C| \\cdot n)$, where $|C|$ is the size of the alphabet, i.e. $26$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t, n;\n    cin >> t;\n    while (t--) {\n        string s;\n        cin >> n >> s;\n        int ans = n + 1;\n        for (int c = 0; c < 26; ++c) {\n            int l = 0, r = n - 1, cnt = 0;\n            while (l <= r) {\n                if (s[l] == s[r]) {\n                    l++, r--;\n                }\n                else if (s[l] == char('a' + c)) {\n                    cnt++, l++;\n                }\n                else if (s[r] == char('a' + c)) {\n                    cnt++, r--;\n                }\n                else {\n                    cnt = n + 1;\n                    break;\n                }\n            }\n            ans = min(ans, cnt);\n        }\n        if (ans == n + 1) ans = -1;\n        cout << ans << '\\n';\n    }\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "strings",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1582",
    "index": "D",
    "title": "Vupsen, Pupsen and 0",
    "statement": "Vupsen and Pupsen were gifted an integer array. Since Vupsen doesn't like the number $0$, he threw away all numbers equal to $0$ from the array. As a result, he got an array $a$ of length $n$.\n\nPupsen, on the contrary, likes the number $0$ and he got upset when he saw the array without zeroes. To cheer Pupsen up, Vupsen decided to come up with another array $b$ of length $n$ such that $\\sum_{i=1}^{n}a_i \\cdot b_i=0$. Since Vupsen doesn't like number $0$, \\textbf{the array $b$ must not contain numbers equal to $0$}. Also, the numbers in that array must not be huge, so \\textbf{the sum of their absolute values cannot exceed $10^9$}. Please help Vupsen to find any such array $b$!",
    "tutorial": "Let's consider two cases: when $n$ is even, and when $n$ is odd. If $n$ is even, let's split all numbers into pairs: let $a_1$ and $a_2$ be in one pair, $a_3$ and $a_4$ in one pair as well and so on. In the pair $a_i$, $a_{i+1}$, let $b_i=a_{i+1}$ and $b_{i+1}=-a_i$, then the sum $a_i \\cdot b_i + a_{i+1} \\cdot b_{i+1}$ in every pair will be equal to $0$ ($a_i \\cdot a_{i+1} + a_{i+1} \\cdot (-a_i)=0$), so the overall sum $a_1 \\cdot b_1 + a_2 \\cdot b_2 + \\ldots + a_n \\cdot b_n$ will be equal to $0$ as well. Notice that the sum of the $|b_i|$ is equal to the sum of $|a_i|$, therefore the sum $|b_1| + |b_2| + \\ldots + |b_n|$ does not exceed $MAXA \\cdot MAXN = 10^9$. If $n$ is odd, then let's cut off the last $3$ numbers and calculate $b$ for the array $a_1, a_2, \\ldots, a_{n-3}$ the way we did it for even $n$ ($n-3$ is even since $n$ is odd). Then for the last $3$ numbers $a_{n-2}, a_{n-1}, a_n$ let's find two numbers with sum not equal to $0$ (by the Dirichlet principle, there will always exist two numbers out of three not equal to $0$, which are both positive or both negative, and the sum of those two numbers cannot be equal to $0$), let them be $a_i$, $a_j$, and the third one $a_k$. Then let $b_i=-a_k$, $b_j=-a_k$, $b_k=(a_i+a_j)$, the sum of $a_i \\cdot b_i + a_j \\cdot b_j + a_k \\cdot b_k = 0$, and numbers of $b$ are not equal to $0$. The sum $|b_1| + |b_2| + \\ldots + |b_{n-3}|$ does not exceed $MAXA \\cdot (MAXN - 1 - 3)$ (since $MAXN$ is even, and we consider a case with odd $n$) and the sum $b_{n-2}+b_{n-1}+b_n$ does not exceed $MAXA + MAXA + 2 \\cdot MAXA = 4 \\cdot MAXA$, so the overall sum of $|b_i|$ does not exceed $MAXA \\cdot MAXN = 10^9$.",
    "code": "ttt = int(input())\nfor t in range(ttt):\n\tn = int(input())\n\ta = [int(x) for x in input().split()]\n\tstart = 0\n\tif n % 2 == 1:\n\t\tif (a[0] + a[1] != 0):\n\t\t\tprint(-a[2], -a[2], a[0] + a[1], end = \" \")\n\t\telif (a[1] + a[2] != 0):\n\t\t\tprint(a[2] + a[1], -a[0], -a[0], end = \" \")\n\t\telse:\n\t\t\tprint(-a[1], a[0] + a[2], -a[1], end = \" \")\n\t\tstart = 3\n\twhile start < n:\n\t\tprint(-a[s + 1], a[s], end = \" \")\n\t\tstart += 2\n\tprint()",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1582",
    "index": "E",
    "title": "Pchelyonok and Segments",
    "statement": "Pchelyonok decided to give Mila a gift. Pchelenok has already bought an array $a$ of length $n$, but gifting an array is too common. Instead of that, he decided to gift Mila the segments of that array!\n\nPchelyonok wants his gift to be beautiful, so he decided to choose $k$ non-overlapping segments of the array $[l_1,r_1]$, $[l_2,r_2]$, $\\ldots$ $[l_k,r_k]$ such that:\n\n- the length of the first segment $[l_1,r_1]$ is $k$, the length of the second segment $[l_2,r_2]$ is $k-1$, $\\ldots$, the length of the $k$-th segment $[l_k,r_k]$ is $1$\n- for each $i<j$, the $i$-th segment occurs in the array earlier than the $j$-th (i.e. $r_i<l_j$)\n- the sums in these segments are strictly increasing (i.e. let $sum(l \\ldots r) = \\sum\\limits_{i=l}^{r} a_i$ — the sum of numbers in the segment $[l,r]$ of the array, then $sum(l_1 \\ldots r_1) < sum(l_2 \\ldots r_2) < \\ldots < sum(l_k \\ldots r_k)$).\n\nPchelenok also wants his gift to be as beautiful as possible, so he asks you to find the maximal value of $k$ such that he can give Mila a gift!",
    "tutorial": "Let's notice that $k$ can be the answer, only if the sum of lengths of the segments does not exceed the number of elements in the array, that is $\\frac{k \\cdot (k + 1)}{2} \\le n$. From this inequation we can get that $k$ is less than $\\sqrt{2n}$, and when $n$ hits its maximal value, it does not exceed $447$. Let $dp_{i,j}$ be the maximal sum on the segment of length $j$, with that we have already considered all elements on the suffix $i$ (that is, elements with indices $i, i + 1, \\ldots, n$) and have already chosen segments with lengths $j, j - 1, \\ldots, 1$, in which the sums increase. Let's learn to recalculate the values of dynamics. We can either not include the $i$-th element in the segment of length $j$, then we need refer to the value of dynamics $dp_{i+1,j}$, or include the $i$-th element, and then we are interested in the value of dynamics $dp_{i+j,j-1}$ - if it's greater than the sum on the segment $i, i + 1, \\ldots, i + j - 1$, then we can take $j$ segments with lengths from $j$ to $1$ on the suffix $i$, answ otherwise we cannot take such segments on the suffix $i$. We need to take the maximum among these two cases in order to maximize the sum. To calculate the sum on a segment you can use prefix sums. Asymptotic behavior of this solution - $O(n \\cdot \\sqrt{n})$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nint const maxn = 1e5 + 5, maxk = 450;\nint a[maxn], dp[maxn][maxk];\nint inf = 1e9 + 7;\nll pref[maxn];\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t, n;\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        for (int i = 1; i <= n; ++i) {\n            cin >> a[i];\n            pref[i] = pref[i - 1] + a[i];\n        }\n        int k = 0;\n        while (k * (k + 1) / 2 <= n) k++;\n        for (int j = 0; j < k; ++j) {\n            dp[n + 1][j] = -inf;\n        }\n        dp[n + 1][0] = inf;\n        for (int i = n; i >= 1; --i) {\n            for (int j = 0; j < k; ++j) {\n                dp[i][j] = dp[i + 1][j];\n                if (j && i + j - 1 <= n && pref[i + j - 1] - pref[i - 1] < dp[i + j][j - 1]) {\n                    dp[i][j] = max(dp[i][j], (int)(pref[i + j - 1] - pref[i - 1]));\n                }\n            }\n        }\n        int ans = 0;\n        for (int j = 0; j < k; ++j) {\n            if (dp[1][j] > 0) ans = j;\n        }\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1582",
    "index": "F2",
    "title": "Korney Korneevich and XOR (hard version)",
    "statement": "\\textbf{This is a harder version of the problem with bigger constraints.}\n\nKorney Korneevich dag up an array $a$ of length $n$. Korney Korneevich has recently read about the operation bitwise XOR, so he wished to experiment with it. For this purpose, he decided to find all integers $x \\ge 0$ such that there exists an \\textbf{increasing} subsequence of the array $a$, in which the bitwise XOR of numbers is equal to $x$.\n\nIt didn't take a long time for Korney Korneevich to find all such $x$, and he wants to check his result. That's why he asked you to solve this problem!\n\nA sequence $s$ is a subsequence of a sequence $b$ if $s$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.\n\nA sequence $s_1, s_2, \\ldots , s_m$ is called increasing if $s_1 < s_2 < \\ldots < s_m$.",
    "tutorial": "Let's iterate over all numbers of the array and for each number $t$ maintain a list $g_t$ of all numbers $y$, such that it's possible to choose an increasing subsequence on the current prefix, in which $xor$ of numbers is equal to $y$, and the last number of that increasing subsequence is less than $t$. Let us currently consider the element $a_i$. Then let's consider elements of $g_{a_i}$ - there will be all values of $xor$-s of the subsequences to which we can append the element $a_i$. If $g_{a_i}$ contains a value $f$, then it's possible to get a value $f \\oplus a_i$, then let's add the value $f \\oplus a_i$ to all lists $g$ from $a_i + 1$ to the maximal value of $a$ (if the value that is being added is already in some $g$-s, it's unnecessary to add it there again). Let's perform some optimizations for this solution. Let's stop considering the values $g_t$ that have already been considered. That is, if we have already considered $g_t$ at some iteration, then let's erase it, but remember that we never need to add the values of $xor$, that are being erased. That optimization is sufficient to get the asymptotic behaviour $O((max\\_a)^3)$, where $max\\_a$ is the greatest one among all numbers of the array $a$ (for every number $t$ and its possible value of $xor$ $f$ we will pass over the value $t \\oplus f$ to all states $t + 1, \\ldots, max\\_a$; the amount of different $t$ is $O(max\\_a)$, the amount of $f$ is $O(max\\_a)$ as well, and the passing of the value each time is performed in $O(max\\_a)$). Let's notice that when we pass some value of $xor$ equal to $f$ to elements $t + 1, \\ldots, max\\_a$, and find the element $r$, in which that value of $xor$ has already been, then the value $f$ is already in all elements greater than $r$, and that's why we don't have to add the value $f$ any further. Using this optimization we can finally get a solution in $O(max\\_a^2)$, since for every value of $xor$ (the amount of them is $O(max\\_a)$), we perform $O(max\\_a)$ operations. In total (considering all optimizations), the asymptotic behaviour of the solution is $O(n + (max\\_a)^2)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint const max_value = (1 << 13);\nvector < int > g[max_value];\nint ans[max_value], r[max_value];\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n, x;\n    cin >> n;\n    ans[0] = 1;\n    for (int i = 0; i < max_value; ++i) {\n        g[i].push_back(0);\n    }\n    for (int i = 0; i < max_value; ++i) {\n        r[i] = max_value;\n    }\n    for (int i = 1; i <= n; ++i) {\n        cin >> x;\n        for (auto key : g[x]) {\n            int to = (key^x);\n            ans[to] = 1;\n            while (r[to] > x) {\n                r[to]--;\n                if (r[to] != x) g[r[to]].push_back(to);\n            }\n        }\n        g[x] = {};\n    }\n    int k = 0;\n    for (int i = 0; i < max_value; ++i) {\n        k += ans[i];\n    }\n    cout << k << '\\n';\n    for (int i = 0; i < max_value; ++i) {\n        if (ans[i]) cout << i << \" \";\n    }\n    cout << '\\n';\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1582",
    "index": "G",
    "title": "Kuzya and Homework",
    "statement": "Kuzya started going to school. He was given math homework in which he was given an array $a$ of length $n$ and an array of symbols $b$ of length $n$, consisting of symbols '*' and '/'.\n\nLet's denote a path of calculations for a segment $[l; r]$ ($1 \\le l \\le r \\le n$) in the following way:\n\n- Let $x=1$ initially. For every $i$ from $l$ to $r$ we will consequently do the following: if $b_i=$ '*', $x=x*a_i$, and if $b_i=$ '/', then $x=\\frac{x}{a_i}$. Let's call a path of calculations for the segment $[l; r]$ a list of all $x$ that we got during the calculations (the number of them is exactly $r - l + 1$).\n\nFor example, let $a=[7,$ $12,$ $3,$ $5,$ $4,$ $10,$ $9]$, $b=[/,$ $*,$ $/,$ $/,$ $/,$ $*,$ $*]$, $l=2$, $r=6$, then the path of calculations for that segment is $[12,$ $4,$ $0.8,$ $0.2,$ $2]$.\n\nLet's call a segment $[l;r]$ simple if the path of calculations for it contains \\textbf{only integer numbers}.\n\nKuzya needs to find the number of simple segments $[l;r]$ ($1 \\le l \\le r \\le n$). Since he obviously has no time and no interest to do the calculations for each option, he asked you to write a program to get to find that number!",
    "tutorial": "Notice that the segment is simple, if for any prime number we will get a bracket sequence, which has the minimal balance greater of equal to $0$. The bracket sequence is formed the following way: we will iterate over the segment and add an opening bracket if we multiply by that number, and a closing bracket, if we divide by that number. Let's consider the elements of the array $a$ and calculate the array $nxt_i$, wich contains the greatest left bound, such that we can do the $i$-th operations in integer numbers with every $l \\le nxt_i$. To calculate such bounds, for each prime number let's maintain all indices of its occurences in the numbers of $a$ in a stack (if the prime numbers occurs in a number several times, we need to store the index several times). If the $i$-th operation is the operation of multiplying, then $nxt_i$ is equal to $i$, and for all prime divisors of the number $a_i$ we need to add the index $i$, and if it's the operation of division,then for all prime divisors of $a_i$ we need to delete indices (in the same amount as the prime divisor occurs in $a_i$) and save the smallest erased index in $nxt_i$. If for any prime divisor we had to erase an index from an empty stack, then we got a non-integer result, so $nxt_i=-1$. Now that we know the values of the array $nxt$, we need to calculate the number of segments $1 \\le l \\le r \\le n$, such that $l \\le min(l, r)$, where $min(l, r)$ is the minimal value of $nxt_i$ on segment $l, r$. We can do that using segment tree on minimum in $O(n \\log_2 n)$ (iterate over the left bound and traversing the tree from the root find the greatest right bound for current left one) or using linear algorithms with a stack (to do that, let's iterate over all left bounds in decreasing order and maintain a stack on minimum on the array $nxt$).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nint const maxn = 1e6 + 5;\nint a[maxn];\nint prime[maxn];\nint L[maxn];\nvector < int > pos[maxn];\n\ninline void add(int x, int l) {\n    L[l] = l;\n    while (x > 1) {\n        pos[prime[x]].push_back(l);\n        x /= prime[x];\n    }\n}\n\ninline void del(int x, int l) {\n    if (x == 1) {\n        L[l] = l;\n        return;\n    }\n    L[l] = l;\n    while (x > 1) {\n        if ((int)pos[prime[x]].size() == 0) {\n            L[l] = 0;\n            return;\n        }\n        L[l] = min(L[l], pos[prime[x]].back());\n        pos[prime[x]].pop_back();\n        x /= prime[x];\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    int n;\n    cin >> n;\n    for (int i = 1; i <= n; ++i) cin >> a[i];\n\n    for (int i = 2; i < maxn; ++i) {\n        if (prime[i] == 0) {\n            prime[i] = i;\n            if (i > 1000) continue;\n            for (int j = i * i; j < maxn; j += i) {\n                prime[j] = i;\n            }\n        }\n    }\n\n    char type;\n    for (int i = 1; i <= n; ++i) {\n        cin >> type;\n        if (type == '*') add(a[i], i);\n        else del(a[i], i);\n    }\n\n    ll answer = 0;\n    vector < pair < int, int > > f_min;\n    for (int i = n; i >= 1; --i) {\n        int cnt = 1;\n        while ((int)f_min.size() > 0 && f_min.back().first >= L[i]) {\n            cnt += f_min.back().second;\n            f_min.pop_back();\n        }\n        f_min.push_back({L[i], cnt});\n        if (L[i] == i) answer += (ll)cnt;\n    }\n    cout << answer << '\\n';\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1583",
    "index": "A",
    "title": "Windblume Ode",
    "statement": "A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.\n\nYou have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $n$ ($n \\ge 3$) positive \\textbf{distinct} integers (i.e. different, no duplicates are allowed).\n\nFind the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $x$ is called composite if there exists a positive integer $y$ such that $1 < y < x$ and $x$ is divisible by $y$.\n\nIf there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.",
    "tutorial": "Let $s$ be equal to the sum of array $a$. If $s$ is composite then $a$ is the largest composite subset of itself. Otherwise, since $n \\geq 3$, $s$ must be a prime number greater than $2$, meaning $s$ must be odd. Now notice that because all elements of $a$ are distinct, if we remove any one number from $a$, the remaining sum must be strictly greater than $2$. This leads us to the following solution: if $s$ is prime, removing any odd number from $a$ will give a composite subset of size $n-1$. This is because that since $s$ is assumed to be odd, an odd number must exist in $a$, and the difference of two odd numbers is always even. Since we claim that this difference is at least $4$, the new sum will always be composite.",
    "code": "//make sure to make new file!\nimport java.io.*;\nimport java.util.*;\n \npublic class OmkarAndHeavenlyTreeSolution{\n   \n   public static void main(String[] args)throws IOException{\n      BufferedReader f = new BufferedReader(new InputStreamReader(System.in));\n      PrintWriter out = new PrintWriter(System.out);\n      \n      int t = Integer.parseInt(f.readLine());\n      \n      for(int q = 1; q <= t; q++){\n      \n         StringTokenizer st = new StringTokenizer(f.readLine());\n      \n         int n = Integer.parseInt(st.nextToken());\n         int m = Integer.parseInt(st.nextToken());\n      \n         HashSet<Integer> hset = new HashSet<Integer>();\n         for(int k = 0; k < m; k++){\n            st = new StringTokenizer(f.readLine());\n         \n            int a = Integer.parseInt(st.nextToken());\n            int b = Integer.parseInt(st.nextToken());\n            int c = Integer.parseInt(st.nextToken());\n         \n            hset.add(b);\n         }\n      \n         int middle = -1;\n         for(int k = 1; k <= n; k++){\n            if(!hset.contains(k)){\n               middle = k;\n               break;\n            }\n         }\n      \n         for(int k = 1; k <= n; k++){\n            if(k == middle) \n               continue;\n            out.println(k + \" \" + middle);\n         }\n      \n      }\n      \n      \n      \n      \n      \n      \n      \n      \n      out.close();\n   }\n   \n      \n}\n ",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1583",
    "index": "B",
    "title": "Omkar and Heavenly Tree",
    "statement": "Lord Omkar would like to have a tree with $n$ nodes ($3 \\le n \\le 10^5$) and has asked his disciples to construct the tree. However, Lord Omkar has created $m$ ($\\mathbf{1 \\le m < n}$) restrictions to ensure that the tree will be as heavenly as possible.\n\nA tree with $n$ nodes is an connected undirected graph with $n$ nodes and $n-1$ edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once.\n\nHere is an example of a tree:\n\nA restriction consists of $3$ pairwise distinct integers, $a$, $b$, and $c$ ($1 \\le a,b,c \\le n$). It signifies that node $b$ cannot lie on the simple path between node $a$ and node $c$.\n\nCan you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints.",
    "tutorial": "Because the number of restrictions is less than $n$, there is guaranteed to be at least one value from $1$ to $n$ that is not a value of $b$ for any of the restrictions. Find a value that is not $b$ for all of the restrictions and construct a tree that is a \"star\" with that value in the middle. An easy way to do this is to make an edge from that value to every other number from $1$ to $n$.",
    "code": "//Praise our lord and saviour qlf9\n//DecimalFormat f = new DecimalFormat(\"##.00\");\n \nimport java.util.*;\nimport java.io.*;\nimport java.math.*;\nimport java.text.*;\npublic class CCorrect{\npublic static void main(String[] omkar) throws Exception\n{\n   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n   StringTokenizer st = new StringTokenizer(in.readLine());\n   StringBuilder sb = new StringBuilder();\n   int n = Integer.parseInt(st.nextToken());\n   int m = Integer.parseInt(st.nextToken());\n   int[][] grid = new int[n][m];\n   String s;\n   char cc;\n   for(int i = 0; i < n; i++)\n   {\n      s = in.readLine();\n      for(int j = 0; j < m; j++)\n      {\n         if(s.charAt(j) == 'X')\n         {\n            grid[i][j] = 1;\n         }\n         else\n         {\n            grid[i][j] = 0;\n         }\n      }\n   }\n   int[] numBad = new int[m+1]; \n   int total = 0;\n   for(int j = 0; j < m-1; j++)\n   {\n      for(int i = 1; i< n; i++)\n      {\n         if(grid[i][j] == 1 && grid[i-1][j+1] == 1)\n         {\n            total++;\n         }\n      }\n      numBad[j+1] = total;\n   } \n   numBad[m] = total;\n   int q = Integer.parseInt(in.readLine());\n   int a, b;\n   for(int i = 0; i < q; i++)\n   {\n      st = new StringTokenizer(in.readLine());\n      a = Integer.parseInt(st.nextToken())-1;\n      b = Integer.parseInt(st.nextToken())-1;\n      if(numBad[b]-numBad[a] == 0)\n      {\n         sb.append(\"yes\\n\");\n      }\n      else\n      {\n         sb.append(\"no\\n\");\n      }\n   }\n   System.out.println(sb);\n        }\n}",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1583",
    "index": "C",
    "title": "Omkar and Determination",
    "statement": "The problem statement looms below, filling you with determination.\n\nConsider a grid in which some cells are empty and some cells are filled. Call a cell in this grid \\textbf{exitable} if, starting at that cell, you can exit the grid by moving up and left through only empty cells. This includes the cell itself, so all filled in cells are not exitable. Note that you can exit the grid from any leftmost empty cell (cell in the first column) by going left, and from any topmost empty cell (cell in the first row) by going up.\n\nLet's call a grid \\textbf{determinable} if, given only which cells are exitable, we can exactly determine which cells are filled in and which aren't.\n\nYou are given a grid $a$ of dimensions $n \\times m$ , i. e. a grid with $n$ rows and $m$ columns. You need to answer $q$ queries ($1 \\leq q \\leq 2 \\cdot 10^5$). Each query gives two integers $x_1, x_2$ ($1 \\leq x_1 \\leq x_2 \\leq m$) and asks whether the subgrid of $a$ consisting of the columns $x_1, x_1 + 1, \\ldots, x_2 - 1, x_2$ is determinable.",
    "tutorial": "First notice that in a determinable grid, for any cell, it can't be that both the cell above it and the cell to its left are filled. If that were the case, then the cell wouldn't be exitable regardless of whether it was filled or not, and so we couldn't determine whether it was filled. Now notice that in any grid with the above property, namely that from each cell you can move either up or to the left into an empty cell (or both), every empty cell must be exitable - just keep moving either up or to the left, whichever is possible, until you exit the grid. It follows that for any grid satisfying that property, given only which cells are exitable, starting from the outermost cells you will be able to determine that the nonexitable cells are filled, which implies that the next cells satisfy the property, which further implies that the nonexitable ones there are filled, and so on. This allows you to determine the entire grid (since the exitable cells are obviously empty). Therefore, a grid being determinable is equivalent to all of its cells having an empty cell immediately above and/or to the left of it. You can check this for arbitrary subgrids by precomputing two dimensional prefix sums of the cells that violate this property, then checking whether the sum for a given subgrid is $0$. This solution is $O(nm + q)$. The actual problem only asked for subgrids that contained every row, which allows for a somewhat simpler implementation.",
    "code": "/*\n“I just don't have any patience for people who would rather hurt others instead of facing their own reality.”\n    – Mikoto Misaka.\n */\nimport static java.lang.Math.*;\nimport static java.lang.System.out;\nimport java.util.*;\nimport java.io.*;\nimport java.math.*;\n \npublic class MeaningOfMikotoMisaka\n{\n    public static void main(String hi[]) throws Exception\n    {\n        BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));\n        StringTokenizer st = new StringTokenizer(infile.readLine());\n        int N = Integer.parseInt(st.nextToken());\n        //find p[N-1]\n        int[] res = new int[N];\n        res[N-1] = N;\n        for(int v=1; v < N; v++)\n        {\n            int[] temp = new int[N];\n            Arrays.fill(temp, v+1);\n            temp[N-1] = 1;\n            if(query(temp, infile) == 0)\n            {\n                res[N-1] = v;\n                break;\n            }\n        }\n        //find all p[i] < p[N-1]\n        for(int increase=1; increase < res[N-1]; increase++)\n        {\n            int[] temp = new int[N];\n            Arrays.fill(temp, increase+1);\n            temp[N-1] = 1;\n            int loc = query(temp, infile)-1;\n            res[loc] = res[N-1]-increase;\n        }\n        //find all p[i] > p[N-1]\n        for(int decrease=1; decrease <= N-res[N-1]; decrease++)\n        {\n            int[] temp = new int[N];\n            Arrays.fill(temp, 1);\n            temp[N-1] += decrease;\n            int loc = query(temp, infile)-1;\n            res[loc] = res[N-1]+decrease;\n        }\n        StringBuilder sb = new StringBuilder(\"! \");\n        for(int x: res)\n            sb.append(x+\" \");\n        System.out.println(sb);\n    }\n    public static int query(int[] arr, BufferedReader infile) throws Exception\n    {\n        StringBuilder owo = new StringBuilder(\"? \");\n        for(int i=0; i < arr.length; i++)\n            owo.append(arr[i]+\" \");\n        System.out.println(owo);\n        return Integer.parseInt(infile.readLine());\n    }\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1583",
    "index": "D",
    "title": "Omkar and the Meaning of Life",
    "statement": "It turns out that the meaning of life is a permutation $p_1, p_2, \\ldots, p_n$ of the integers $1, 2, \\ldots, n$ ($2 \\leq n \\leq 100$). Omkar, having created all life, knows this permutation, and will allow you to figure it out using some queries.\n\nA query consists of an array $a_1, a_2, \\ldots, a_n$ of integers between $1$ and $n$. $a$ is \\textbf{not} required to be a permutation. Omkar will first compute the pairwise sum of $a$ and $p$, meaning that he will compute an array $s$ where $s_j = p_j + a_j$ for all $j = 1, 2, \\ldots, n$. Then, he will find the smallest index $k$ such that $s_k$ occurs more than once in $s$, and answer with $k$. If there is no such index $k$, then he will answer with $0$.\n\nYou can perform at most $2n$ queries. Figure out the meaning of life $p$.",
    "tutorial": "Solution 1 We will determine for each $j$, the index $\\text{next}_j$ such that $p_{\\text{next}_j} = p_j + 1$. For each index $j$, perform a query with all $1$s except that $a_j = 2$. If the result $k$ exists, then we should set $\\text{next}_k = j$. Also, for each index $j$, perform a query with all $2$s except that $a_j = 1$. If the result $k$ exists, then we should set $\\text{next}_j = k$. For each $j$ such that $p_j \\neq n$, either $\\text{next}_j > j$, in which case the first set of queries will find $\\text{next}_j$, or $\\text{next}_j < j$, in which case the second set of queries will find $\\text{next}_j$. Therefore we will fully determine the array $\\text{next}$. To compute $p$, note that the index $j$ such that $p_j = 1$ will not appear in the array $\\text{next}$. Therefore, find this $j$, and set $p_j = 1$. Then set $j$ to $\\text{next}_j$, and set $p_j = 2$, and so on. The total number of queries used is $2n$, which is exactly the limit. Solution 2 We will first determine $q_j = p_j - p_n$ for all $j$. For each value of $x$ from $-(n - 1)$ to $n - 1$ (these are the only possible values of $p_j - p_n$), if $x$ is nonnegative, then make a query where all of $a + 1$ is $x$ except that $a_n = 1$; otherwise, make a query where all of $a$ is $1$ except that $a_n = 1 - x$. If the result $k$ exists, then $q_k = x$. Note that there is at most one $k$ such that $q_k = x$ for each $x$, so we will fully determine $q$ this way (obviously we need to manually set $q_n = 0$). $p_n$ is then equal to the number of $j$ such that $q_j \\leq 0$. Using this, we can determine the rest of $p$ as $p_j = q_j + p_n$. The total number of queries used is $2n - 1$, which is $1$ below the limit. Bonus question: Optimize this solution to use $n$ queries.",
    "code": "//stan hu tao\n//come to K-expo!!!\n//watch me get carried in nct ridin\nimport static java.lang.Math.max;\nimport static java.lang.Math.min;\nimport static java.lang.Math.abs;\nimport static java.lang.System.out;\nimport java.util.*;\nimport java.io.*;\nimport java.math.*;\n \npublic class MomentOfBloomModel\n{\n    static ArrayDeque<Integer>[] edges;\n    static ArrayDeque<Integer>[] tree;\n    public static void main(String hi[]) throws Exception\n    {\n        BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));\n        StringTokenizer st = new StringTokenizer(infile.readLine());\n        int N = Integer.parseInt(st.nextToken());\n        int M = Integer.parseInt(st.nextToken());\n        //FOR SAMPLE CASE HIDING ONLY\n        ArrayList<Integer> input = new ArrayList<Integer>();\n        input.add(N);  input.add(M);\n        edges = new ArrayDeque[N+1];\n        for(int i=1; i <= N; i++)\n            edges[i] = new ArrayDeque<Integer>();\n        for(int i=0; i < M; i++)\n        {\n            st = new StringTokenizer(infile.readLine());\n            int a = Integer.parseInt(st.nextToken());\n            int b = Integer.parseInt(st.nextToken());\n            edges[a].add(b);    edges[b].add(a);\n            \n            input.add(a);   input.add(b);\n        }\n        int[] parity = new int[N+1];\n        int Q = Integer.parseInt(infile.readLine());\n        input.add(Q);\n        int[] queries = new int[2*Q];\n        for(int i=1; i < 2*Q; i+=2)\n        {\n            st = new StringTokenizer(infile.readLine());\n            int a = Integer.parseInt(st.nextToken());\n            int b = Integer.parseInt(st.nextToken());\n            queries[i-1] = a;\n            queries[i] = b;\n            parity[a] ^= 1;\n            parity[b] ^= 1;\n            input.add(a);   input.add(b);\n        }\n        int countExtra = 0;\n        for(int x: parity)\n            countExtra+=x;\n        if(countExtra > 0)\n        {\n            System.out.println(\"NO\");\n            System.out.println(countExtra/2);\n            return;\n        }\n        //get dfs tree\n        tree = new ArrayDeque[N+1];\n        for(int i=1; i <= N; i++)\n            tree[i] = new ArrayDeque<Integer>();\n        seen = new boolean[N+1];\n        dfs(1, 0);\n        System.out.println(\"YES\");\n        StringBuilder sb = new StringBuilder();\n        for(int qq=1; qq < 2*Q; qq+=2)\n        {\n            int a = queries[qq-1];\n            int b = queries[qq];\n            //is this too slow? probably not\n            int[] parents = new int[N+1];\n            ArrayDeque<Integer> q = new ArrayDeque<Integer>();\n            q.add(a);   parents[a] = -1;\n            bfs:while(q.size() > 0)\n            {\n                int curr = q.poll();\n                for(int next: tree[curr])\n                    if(parents[next] == 0)\n                    {\n                        parents[next] = curr;\n                        if(next == b)\n                            break bfs;\n                        q.add(next);\n                    }\n            }\n            ArrayList<Integer> path = new ArrayList<Integer>();\n            int curr = b;\n            while(curr != a)\n            {\n                path.add(curr);\n                curr = parents[curr];\n            }\n            path.add(a);\n            Collections.reverse(path);\n            sb.append(path.size()+\"\\n\");\n            for(int x: path)\n                sb.append(x+\" \");\n            sb.append(\"\\n\");\n        }\n        System.out.print(sb);\n    }\n    static boolean[] seen;\n    public static void dfs(int curr, int par)\n    {\n        seen[curr] = true;\n        for(int next: edges[curr])\n            if(!seen[next])\n            {\n                tree[curr].add(next);\n                tree[next].add(curr);\n                dfs(next, curr);\n            }\n    }\n}\n ",
    "tags": [
      "constructive algorithms",
      "greedy",
      "interactive"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1583",
    "index": "E",
    "title": "Moment of Bloom",
    "statement": "She does her utmost to flawlessly carry out a person's last rites and preserve the world's balance of yin and yang.\n\nHu Tao, being the little prankster she is, has tried to scare you with this graph problem! You are given a connected undirected graph of $n$ nodes with $m$ edges. You also have $q$ queries. Each query consists of two nodes $a$ and $b$.\n\nInitially, all edges in the graph have a weight of $0$. For each query, you must choose a simple path starting from $a$ and ending at $b$. Then you add $1$ to every edge along this path. Determine if it's possible, after processing all $q$ queries, for all edges in this graph to have an even weight. If so, output the choice of paths for each query.\n\nIf it is not possible, determine the smallest number of extra queries you could add to make it possible. It can be shown that this number will not exceed $10^{18}$ under the given constraints.\n\nA simple path is defined as any path that does not visit a node more than once.\n\nAn edge is said to have an even weight if its value is divisible by $2$.",
    "tutorial": "Let $f_v$ be the number of times $v$ appears in the $q$ queries. If $f_v$ is odd for any $1 \\leq v \\leq n$, then there does not exist an assignment of paths that will force all even edge weights. To see why, notice that one query will correspond to exactly one edge adjacent to $v$. If an odd number of paths are adjacent to $v$, this implies that at least one edge adjacent to $v$ will have an odd degree. It turns out that this is the only condition that we need to check. In other words, if $f_v$ is even for all $v$, then there will exist an assignment of paths that will force all edge weights to be even. Let's assume all $f_v$ is even. We can find a solution by doing the following: take any spanning tree of the graph and assign each query to be the path from $a$ to $b$ in this tree. An intuitive way of thinking about this is the following. Consider the case if the spanning tree is a line. Then each query becomes a range and we're checking if all points in this range are covered an even number of times. For all points to be covered an even number of times, every point should occur an even number of times in the queries. To generalize this to a tree, when the first path $a_1$ to $b_1$ is incremented, in order to make these values even again, we will need later paths to also overlap the segment from $a_1$ to $b_1$. One way this can be done is if we use two paths $a_1$ to $c$ and $c$ to $b_1$. Notice that even if a new segment that makes the $a_1$ to $b_1$ path even makes some other edges odd, the later queries will always fix these edges.",
    "code": "//stan hu tao\n//come to K-expo!!!\n//watch me get carried in nct ridin\nimport static java.lang.Math.max;\nimport static java.lang.Math.min;\nimport static java.lang.Math.abs;\nimport static java.lang.System.out;\nimport java.util.*;\nimport java.io.*;\nimport java.math.*;\n \npublic class DefenderModel\n{\n    public static void main(String hi[]) throws Exception\n    {\n        BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));\n        StringTokenizer st = new StringTokenizer(infile.readLine());\n        int N = Integer.parseInt(st.nextToken());\n        int K = Integer.parseInt(st.nextToken());\n        int colors = 1;\n        int curr = K;\n        while(curr < N)\n        {\n            curr *= K;\n            colors++;\n        }\n        System.out.println(colors);\n         ArrayList<Integer>[] values = new ArrayList[N];\n         for(int v=0; v < N; v++)\n         {\n            values[v] = new ArrayList<Integer>();\n            int temp = v;\n            while(temp > 0)\n            {\n                values[v].add(temp%K);\n                temp /= K;\n            }\n            if(v == 0)\n                values[v].add(0);\n         }\n         StringBuilder sb = new StringBuilder();\n         for(int a=0; a < N; a++)\n            for(int b=a+1; b < N; b++)\n            {\n                if(values[a].size() < values[b].size())\n                {\n                    int choice = values[b].size();\n                    sb.append(choice+\" \");\n                }\n                else\n                {\n                    int choice = values[a].size()-1;\n                    while(values[a].get(choice) == values[b].get(choice))\n                        choice--;\n                    choice++;\n                    sb.append(choice+\" \");\n                }\n            }\n         System.out.println(sb);\n    }\n}\n ",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graph matchings",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1583",
    "index": "F",
    "title": "Defender of Childhood Dreams",
    "statement": "Even if you just leave them be, they will fall to pieces all by themselves. So, someone has to protect them, right?\n\nYou find yourself playing with Teucer again in the city of Liyue. As you take the eccentric little kid around, you notice something interesting about the structure of the city.\n\nLiyue can be represented as a directed graph containing $n$ nodes. Nodes are labeled from $1$ to $n$. There is a directed edge from node $a$ to node $b$ if and only if $a < b$.\n\nA path between nodes $a$ and $b$ is defined as a sequence of edges such that you can start at $a$, travel along all of these edges in the corresponding direction, and end at $b$. The length of a path is defined by the number of edges. A rainbow path of length $x$ is defined as a path in the graph such that there exists at least 2 distinct colors among the set of $x$ edges.\n\nTeucer's favorite number is $k$. You are curious about the following scenario: If you were to label each edge with a color, what is the minimum number of colors needed to ensure that all paths of length $k$ or longer are rainbow paths?\n\nTeucer wants to surprise his older brother with a map of Liyue. He also wants to know a valid coloring of edges that uses the minimum number of colors. Please help him with this task!",
    "tutorial": "The minimum number of colors that you need is $\\lceil \\log_k n \\rceil$. To achieve this, you can divide the nodes into $k$ contiguous subsegments of equal size (or as close as possible). Any edge between nodes in different subsegments, you color with $1$ for example. Then you recursively solve those subsegments excluding the color that you used. Any path of the same color is between same size subsegments inside a single bigger subsegment (or the whole array). Since there would be only $k$ such subsegments, the path could only have length at most $k - 1$. The highest recursion depth is $\\lceil \\log_k n \\rceil$, so this is the number of colors used as desired. We will now prove that $\\lceil \\log_k n \\rceil$ colors are necessary. We will do this by equivalently proving that if you have a valid coloring using $c$ colors, then $n$ is at most $k^c$. This, in turn, we will prove by induction on $c$. The base case is $c = 0$. If you have no colors, then you can't color any edges, so $n$ must be at most $1 = k^0$. For the inductive step, we assume that any valid coloring using at most $c - 1$ colors can have at most $k^{c - 1}$ nodes, and we desire to show that any valid coloring using at most $c$ colors can have at most $k^c$ nodes. To do this, we will choose an arbitrary color, then partition all our nodes into at most $k$ groups such that inside each group, there are no edges of that color. It follows that each group is colored using at most $c - 1$ colors and so can have at most $k^{c - 1}$ nodes, so overall we can have at most $k \\cdot k^{c - 1} = k^c$ nodes. The partition is defined as follows: we will partition the nodes into the sets $s_0, s_1, \\ldots, s_{k - 1}$ where $s_j$ contains all nodes $a$ such that the length of the longest path ending in $a$ using only edges of our chosen color is exactly $j$. This length is at most $k - 1$ since our coloring can't have paths of length $k$ of a single color. Furthermore, there can't be edges of our chosen color inside a set $s_j$, because otherwise the endpoint of such an edge would be the end of the longest path to the start point of the edge plus the edge itself, which would be of length $j + 1$. Therefore, any valid coloring using $c$ colors can have at most $c^k$ nodes, and so we must use at least $\\lceil \\log_k n \\rceil$ colors in our construction, which we have already seen how to do.",
    "code": "//khodaya khodet komak kon\n# include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long                                        ll;\ntypedef long double                                      ld;\ntypedef pair <int, int>                                  pii;\ntypedef pair <pii, int>                                  ppi;\ntypedef pair <int, pii>                                  pip;\ntypedef pair <pii, pii>                                  ppp;\ntypedef pair <ll, ll>                                    pll;\n \n# define A                                               first\n# define B                                               second\n# define endl                                            '\\n'\n# define sep                                             ' '\n# define all(x)                                          x.begin(), x.end()\n# define kill(x)                                         return cout << x << endl, 0\n# define SZ(x)                                           int(x.size())\n# define lc                                              id << 1\n# define rc                                              id << 1 | 1\n# define fast_io                                         ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);\n \nll power(ll a, ll b, ll md) {return (!b ? 1 : (b & 1 ? a * power(a * a % md, b / 2, md) % md : power(a * a % md, b / 2, md) % md));}\n \nconst int xn = 4e5 + 10;\nconst int xm = - 20 + 10;\nconst int sq = 320;\nconst int inf = 1e9 + 10;\nconst ll INF = 1e18 + 10;\nconst ld eps = 1e-15;\nconst int mod = 1e9 + 7;//998244353;\nconst int base = 257;\n \nint n, dp[xn], ans, fen[xn], q, seg[xn << 2], pd[xn], b[xn];\npii a[xn];\nvector <pii> Q[xn];\nbool flag[xn];\n \nvoid mofen(int pos, int val = 1){\n\tfor (pos += 5; pos < xn; pos += pos & - pos)\n\t\tfen[pos] = (fen[pos] + val) % mod;\n}\nint gefen(int pos){\n\tint res = 0;\n\tfor (pos += 5; pos > 0; pos -= pos & - pos)\n\t\tres = (res + fen[pos]) % mod;\n\treturn res;\n}\nvoid modify(int id, int l, int r, int pos, int val){\n\tseg[id] = max(seg[id], val);\n\tif (r - l == 1)\n\t\treturn;\n\tint mid = l + r >> 1;\n\tif (pos < mid)\n\t\tmodify(lc, l, mid, pos, val);\n\telse\n\t\tmodify(rc, mid, r, pos, val);\n}\nint get(int id, int l, int r, int ql, int qr){\n\tif (qr <= l || r <= ql || qr <= ql)\n\t\treturn 0;\n\tif (ql <= l && r <= qr)\n\t\treturn seg[id];\n\tint mid = l + r >> 1;\n\treturn max(get(lc, l, mid, ql, qr), get(rc, mid, r, ql, qr));\n}\n \nint main(){\n\tfast_io;\n \n\tcin >> n;\n\tfor (int i = 1; i <= n; ++ i){\n\t\tint l, r;\n\t\tcin >> l >> r;\n\t\ta[r] = {l, i};\n\t}\n\tcin >> q;\n\twhile (q --){\n\t\tint x;\n\t\tcin >> x;\n\t\tflag[x] = true;\n\t}\n\tfor (int i = 1; i <= n + n; ++ i){\n\t\tif (!a[i].A)\n\t\t\tcontinue;\n\t\tdp[i] = (gefen(i) - gefen(a[i].A) + mod + 1) % mod;\n\t\tmofen(a[i].A, dp[i]);\n\t\tif (!flag[a[i].B])\n\t\t\tcontinue;\n\t\tint mx = get(1, 0, xn, a[i].A, i);\n\t\tb[i] = mx;\n\t\tQ[mx].push_back({a[i].A, i});\n\t\tmodify(1, 0, xn, a[i].A, i);\n\t}\n\tint mx = get(1, 0, xn, 0, xn);\n\tQ[mx].push_back({0, n + n + 1});\n\tfill(fen, fen + xn, 0);\n\tfor (int i = 1; i <= n + n; ++ i){\n\t\tfor (pii x : Q[i])\n\t\t\tpd[x.B] = (gefen(i) - gefen(x.A) + mod) % mod;\n\t\tif (a[i].A)\n\t\t\tmofen(a[i].A, dp[i]);\n\t}\n\tfor (int i = 1; i <= n + n; ++ i)\n\t\tif (flag[a[i].B])\n\t\t\tpd[i] = (pd[i] + pd[b[i]] + 1) % mod;\n\tcout << (pd[n + n + 1] + pd[mx]) % mod << endl;\n \n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "divide and conquer"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1583",
    "index": "G",
    "title": "Omkar and Time Travel",
    "statement": "El Psy Kongroo.\n\nOmkar is watching Steins;Gate.\n\nIn Steins;Gate, Okabe Rintarou needs to complete $n$ tasks ($1 \\leq n \\leq 2 \\cdot 10^5$). Unfortunately, he doesn't know when he needs to complete the tasks.\n\nInitially, the time is $0$. Time travel will now happen according to the following rules:\n\n- For each $k = 1, 2, \\ldots, n$, Okabe will realize at time $b_k$ that he was supposed to complete the $k$-th task at time $a_k$ ($a_k < b_k$).\n- When he realizes this, if $k$-th task was already completed at time $a_k$, Okabe keeps the usual flow of time. Otherwise, he time travels to time $a_k$ then immediately completes the task.\n- If Okabe time travels to time $a_k$, all tasks completed after this time will become incomplete again. That is, for every $j$, if $a_j>a_k$, the $j$-th task will become incomplete, if it was complete (if it was incomplete, nothing will change).\n- Okabe has bad memory, so he can time travel to time $a_k$ \\textbf{only immediately after} getting to time $b_k$ and learning that he was supposed to complete the $k$-th task at time $a_k$. That is, even if Okabe already had to perform $k$-th task before, he wouldn't remember it before stumbling on the info about this task at time $b_k$ again.\n\nPlease refer to the notes for an example of time travelling.\n\nThere is a certain set $s$ of tasks such that the first moment that all of the tasks in $s$ are simultaneously completed (regardless of whether any other tasks are currently completed), a funny scene will take place. Omkar loves this scene and wants to know how many times Okabe will time travel before this scene takes place. Find this number modulo $10^9 + 7$. It can be proven that eventually all $n$ tasks will be completed and so the answer always exists.",
    "tutorial": "Each time travel that Okabe performs creates a new set of completed tasks. We will take this as given, but it can be proven using ideas from the rest of the proof. It thus suffices to count the number of distinct sets of task that come before the first one that contains $s$ as a subset. We should first figure out what kinds of sets will ever appear as a set of completed tasks at all; we will call these sets valid. We will represent tasks below as intervals $[a_k, b_k]$. First note that clearly not all sets are valid. If you have the intervals $[1, 2]$ and $[3, 4]$, clearly the set $\\{[3, 4]\\}$ is not a valid set. You can actually see that the same is true for the intervals $[1, 3]$ and $[2, 4]$ ($\\{[2, 4]\\}$ is not a valid set) by working through Okabe's activities. This generalizes in a very important way: if there are two intervals $[a, b]$ and $[c, d]$ with $a < c$ and $b < d$, then any valid set that contains $[c, d]$ must also contain $[a, b]$. This is because if $d$ is reached to complete the task $[c, d]$, then $b$ will already have been reached to complete the task $[a, b]$ (since $b < d$), and any time travel that undoes $[a, b]$ must also undo $[c, d]$ (since $a < c$). The above property is actually equivalent to being a valid set; we have already seen that it is necessary, and from the next part of the tutorial we will have way to prove that it is sufficient, but you should have some intuition for why this is true. In order to solve the problem, we want to think about how to determine, given two valid sets, which one Okabe will encounter first. First, for any two valid sets, consider their last interval (i. e. interval with greatest value of $b$). If these are different, then the one with largest interval having greater $b$ will come later. This is because for any valid set, the largest value of $b$ in any interval in that set is equal to the largest value of $b$ that Okabe has ever encountered. You can see this by noticing that the only way to undo a task is to perform a task with greater value of $b$; any task with smaller $b$ is either contained inside the first task, in which case it won't undo it, or also has a smaller value of $a$, in which case by the above property of valid sets it must already be completed. Since the maximum value of $b$ that Okabe has ever encountered will only get larger as his activities continue, it follows that the valid set with larger maximum value of $b$ must occur later. We can further see that for any two valid sets where the interval with largest $b$ is equal, we can discard that interval and consider the next largest interval from both valid sets. This gives us an ordering of the valid sets. We can prove that the aformentioned property is sufficient for being a valid set by showing that at any valid set, the next valid set encountered is the immediately next one in the ordering. The details are left to the reader. In order to use this to finally solve the problem, it is useful to represent valid sets in a different way. Specifically, we can represent a valid set $v$ as the set $u$ of intervals that aren't implied to be in $v$ by any other element of $v$. By thinking about the above property, you can see that $u$ is actually a set of recursively containing intervals; i. e. it contains an interval, then another interval inside that one, then another interval inside that one, etc. We will consider the above representation to be ordered, so that the last interval is the one that contains all the others, and the first interval is the one inside of all the others. We can now solve the problem. For the given set $s$, first determine its above representation; this can be done easily using sorting, discarding any redundant interval. The valid sets, also in their above representation, that come before $s$ are thus the ones that, excluding their common suffix with $s$, have a last interval whose $b$ is smaller than the $b$ for the last interval in $s$ excluding the common suffix. We can therefore solve this as follows. We will count the number of above sets for each possible common suffix. For each suffix, let the last interval in $s$ not included in the suffix be $x$, and let the first interval in the suffix be $y$. The amount of sets for this suffix is equal to the amount of recursively containing sets that have a largest interval that is contained in $y$ whose value of $b$ is less than the value of $b$ for $x$. We can compute this follows. We will maintain a range sum query data structure such as binary index tree. The data structure will have at each $a$, the number of recursively containing subsets whose largest interval is the one with that $a$ (once that interval has been processed). We will process the intervals in increasing order of $b$. For each interval $x$, to put it into the data structure, we can simply perform a range query of literally the interval $x$, and add $1$ to the result. That will be equal to the number of recursively containing sets with $x$ as the largest interval, so we simply insert that into the data structure at the value of $a$ of $x$. Before putting $x$ into the data structure, if it is in the representation of $s$, then we can find the answer for the suffix of $s$ that contains all intervals to the right of $x$ as follows. Since the intervals currently in the data structure are precisely the ones with value of $b$ less than $x$, the answer for that suffix is simply the range query of $y$ where $y$ is the immediately next interval after $x$ in $s$. We therefore perform this range query then add it to our answer. Note that all of this computation doesn't count $s$ itself, but it does count the empty set which doesn't need to be counted, so our answer is correct. The runtime of this solution is $O(n\\lg n)$.",
    "code": "//\n// Created by Danny Mittal on 4/11/21.\n//\n \n#define ll int\n \n#define MAXN 200000\n#define LGMAXN 18\n \n#include <iostream>\n#include <vector>\n#include <algorithm>\n \nusing namespace std;\n \nstruct edge {\n    int from;\n    int to;\n    ll capacity;\n    ll toll;\n};\n \nbool compareEdges(edge e, edge f) {\n    return f.capacity < e.capacity;\n}\n \nstruct query {\n    int from;\n    ll vehicles;\n    int index;\n};\n \nbool compareQueries(query query1, query query2) {\n    return query2.vehicles < query1.vehicles;\n}\n \nll enjoyment[MAXN + 1];\nvector<edge> adj[MAXN + 1];\nedge edges[MAXN - 1];\nquery queries[MAXN];\n \nint parent[LGMAXN][MAXN + 1];\nll maxToll[LGMAXN][MAXN + 1];\nint depth[MAXN + 1];\n \nvoid dfs(int a) {\n    for (edge e : adj[a]) {\n        if (e.to != parent[0][a]) {\n            parent[0][e.to] = a;\n            maxToll[0][e.to] = e.toll;\n            for (int d = 1; d < LGMAXN; d++) {\n                parent[d][e.to] = parent[d - 1][parent[d - 1][e.to]];\n                maxToll[d][e.to] = max(maxToll[d - 1][e.to], maxToll[d - 1][parent[d - 1][e.to]]);\n            }\n            depth[e.to] = depth[a] + 1;\n            dfs(e.to);\n        }\n    }\n}\n \nll maxTollOnPath(int a, int b) {\n    if (depth[b] < depth[a]) {\n        swap(a, b);\n    }\n    ll res = 0;\n    for (int d = LGMAXN - 1; d >= 0; d--) {\n        if (depth[b] - depth[a] >= 1 << d) {\n            res = max(res, maxToll[d][b]);\n            b = parent[d][b];\n        }\n    }\n    if (a == b) {\n        return res;\n    }\n    for (int d = LGMAXN - 1; d >= 0; d--) {\n        if (parent[d][b] != parent[d][a]) {\n            res = max(res, max(maxToll[d][a], maxToll[d][b]));\n            a = parent[d][a];\n            b = parent[d][b];\n        }\n    }\n    res = max(res, max(maxToll[0][a], maxToll[0][b]));\n    return res;\n}\n \nint dsu[MAXN + 1];\nll maxTollInside[MAXN + 1];\n \nint find(int u) {\n    if (dsu[dsu[u]] != dsu[u]) {\n        dsu[u] = find(dsu[u]);\n    }\n    return dsu[u];\n}\n \nll answerEnjoyment[MAXN];\nll answerToll[MAXN];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n, q;\n    cin >> n >> q;\n    for (int a = 1; a <= n; a++) {\n        cin >> enjoyment[a];\n        dsu[a] = a;\n        maxTollInside[a] = 0;\n    }\n    for (int j = 0; j < n - 1; j++) {\n        int a, b;\n        ll c, t;\n        cin >> a >> b >> c >> t;\n        edges[j] = {a, b, c, t};\n        adj[a].push_back({a, b, c, t});\n        adj[b].push_back({b, a, c, t});\n    }\n    dfs(1);\n    for (int j = 0; j < q; j++) {\n        ll v;\n        int x;\n        cin >> v >> x;\n        queries[j] = {x, v, j};\n    }\n    sort(edges, edges + n - 1, compareEdges);\n    sort(queries, queries + q, compareQueries);\n    int k = 0;\n    for (int h = 0; h < q; h++) {\n        int x = queries[h].from;\n        ll v = queries[h].vehicles;\n        int j = queries[h].index;\n        while (k < n - 1 && edges[k].capacity >= v) {\n            int u = find(edges[k].from);\n            int w = find(edges[k].to);\n            if (enjoyment[u] > enjoyment[w]) {\n                dsu[w] = u;\n            } else if (enjoyment[w] > enjoyment[u]) {\n                dsu[u] = w;\n            } else {\n                dsu[w] = u;\n                maxTollInside[u] = max(max(maxTollInside[u], maxTollInside[w]), maxTollOnPath(u, w));\n            }\n            k++;\n        }\n        int u = find(x);\n        answerEnjoyment[j] = enjoyment[u];\n        answerToll[j] =  max(maxTollInside[u], maxTollOnPath(x, u));\n    }\n    for (int j = 0; j < q; j++) {\n        cout << answerEnjoyment[j] << ' ' << answerToll[j] << '\\n';\n    }\n    cout << flush;\n    return 0;\n}",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1583",
    "index": "H",
    "title": "Omkar and Tours",
    "statement": "Omkar is hosting tours of his country, Omkarland! There are $n$ cities in Omkarland, and, rather curiously, there are exactly $n-1$ bidirectional roads connecting the cities to each other. It is guaranteed that you can reach any city from any other city through the road network.\n\nEvery city has an enjoyment value $e$. Each road has a capacity $c$, denoting the maximum number of vehicles that can be on it, and an associated toll $t$. However, the toll system in Omkarland has an interesting quirk: if a vehicle travels on multiple roads on a single journey, they pay only the highest toll of any single road on which they traveled. (In other words, they pay $\\max t$ over all the roads on which they traveled.) If a vehicle traverses no roads, they pay $0$ toll.\n\nOmkar has decided to host $q$ tour groups. Each tour group consists of $v$ vehicles starting at city $x$. (Keep in mind that a tour group with $v$ vehicles can travel only on roads with capacity $\\geq v$.) Being the tour organizer, Omkar wants his groups to have as much fun as they possibly can, but also must reimburse his groups for the tolls that they have to pay. Thus, for each tour group, Omkar wants to know two things: first, what is the enjoyment value of the city $y$ with maximum enjoyment value that the tour group can reach from their starting city, and second, how much per vehicle will Omkar have to pay to reimburse the entire group for their trip from $x$ to $y$? (This trip from $x$ to $y$ will always be on the shortest path from $x$ to $y$.)\n\nIn the case that there are multiple reachable cities with the maximum enjoyment value, Omkar will let his tour group choose which one they want to go to. Therefore, to prepare for all possible scenarios, he wants to know the amount of money per vehicle that he needs to guarantee that he can reimburse the group regardless of which city they choose.",
    "tutorial": "First, note that we can process all the queries offline. We can sort the queries by the number of vehicles in the tour group and process them in decreasing order. Now, consider solving a version of the problem with distinct enjoyment values. Then, there will always be exactly one reachable city with the maximum enjoyment value. To solve this, we can maintain a DSU that stores, for each connected component, the maximum enjoyment value and the index of the node with the maximum enjoyment value, which we denote as $enj[u], mxi[u]$ for a connected component $u$. When merging two connected components $u$, $v$, we simply take $enj[u] = \\max(enj[u], enj[v]), mxi[u] = \\text{arg}\\max(mxi[u], mxi[v])$. Now, consider processing a query with starting node $a$ and number of vehicles $x$, we denote its \"connected component\" $u$ as the connected component of $a$ in the graph that contains only edges with capacity $\\geq x$. Finding the maximum enjoyment value that can be reached from $a$ is simple; we can just output $enj[u]$. To compute the second value, because there is only one node with the maximum enjoyment value ($mxi[u]$), we can find the maximum edge on the path from $a$ to $mxi[u]$ using binary lifting. (Denote this as $\\text{maxEdge}(a, mxi[u])$.) We now consider the original problem, with non-distinct enjoyment values. However, here we make the key observation: for each query, the maximum toll edge always lies on either all the paths from node $a$ to any node with maximum enjoyment value, or on a path between two nodes with maximum enjoyment value. To show this, $\\ell$ be the node with maximum enjoyment value whose path to $a$ contains the maximum toll edge, and let $m$ be an arbitrary node with maximum value. The path from $\\ell$ to $a$ is completely contained in the union of the path from $m$ to $a$ and the path from $\\ell$ to $m$. Therefore, the maximum toll edge lies on at least one of these path as desired. Using this observation, we can modify our DSU to handle the general case. First, we now let $mxi[u]$ to be the index of any maximum enjoyment value node in $u$. We also add a new variable, $tol[u]$, which denotes the maximum toll cost among all paths between nodes of maximum enjoyment value in connected component $u$. Now, when merging components $u$ and $v$, if $enj[u]$ is not equal to $enj[v]$, then we can simply take all the above values from the component with a larger $enj$. However, if $enj[u] = enj[v]$, we will only need to update $tol[u]$. To do this, we need to consider edges that could possibly connect the two components along with ones within the components, so we let $tol[u] = max(tol[u], tol[v], \\text{maxEdge}(mxi[u], mxi[v]))$. Again, maxEdge can be computed using binary lifting. Now, to process the queries, we will make use of our observation. For a query with starting node $a$ and connected component $u$, the maximum enjoyment value is again $enj[u]$. However, the second value can now be more easily computed by $\\max(\\text{maxEdge}(a, mxi[u]), tol[u])$. As the preprocessing necessary for binary lifting takes $O(n \\log n)$ time, and all the queries can be answered in $O((n + q) \\log n)$ time, the overall complexity is $O((n + q) \\log n)$, which is fast enough.",
    "code": "#ifdef DEBUG\n#define _GLIBCXX_DEBUG\n#endif\n//#pragma GCC optimize(\"O3\")\n#include <bits/stdc++.h>\n \nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\nint n;\nconst int maxN = 2005;\nint a[maxN][maxN];\nint b[maxN][maxN];\nvector<pair<int,int>> by[maxN];\nconst int dx[3] = {-1, 0, 0};\nconst int dy[3] = {0, -1, 1};\nint his_val[maxN];\nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    //freopen(\"input.txt\", \"r\", stdin);\n    cin >> n;\n    if (n % 2 == 1) {\n        cout << \"NONE\";\n        return 0;\n    }\n    for (int j = 0; j < n; j++) {\n        a[0][j] = j / 2;\n        b[0][j] = 0;\n    }\n    for (int i = 0; i + 1 < n; i++) {\n        for (int j = 0; j < n; j++) {\n            int xr = 0;\n            int c = 0;\n            vector<int> vals;\n            vals.emplace_back(a[i][j]);\n            for (int z = 0; z < 3; z++) {\n                int ni = i + dx[z];\n                int nj = j + dy[z];\n                if (ni < 0 || ni >= n) continue;\n                if (nj < 0 || nj >= n) continue;\n                vals.emplace_back(a[ni][nj]);\n            }\n            int cnt = 0;\n            int he = -1;\n            sort(vals.begin(), vals.end());\n            vals.erase(unique(vals.begin(), vals.end()), vals.end());\n            for (int& t : vals) {\n                int pp = 0;\n                for (int z = 0; z < 3; z++) {\n                    int ni = i + dx[z];\n                    int nj = j + dy[z];\n                    if (ni < 0 || ni >= n) continue;\n                    if (nj < 0 || nj >= n) continue;\n                    if (a[ni][nj] == t) pp ^= 1;\n                    if (a[i][j] == t) pp ^= 1;\n                }\n                if (pp && t != a[i][j]) {\n                    cnt++;\n                    he = t;\n                }\n            }\n            assert(cnt == 0 || cnt == 1);\n            if (cnt == 0) a[i + 1][j] = a[i][j];\n            else a[i + 1][j] = he;\n            int pp = 0;\n            for (int z = 0; z < 3; z++) {\n                int ni = i + dx[z];\n                int nj = j + dy[z];\n                if (ni < 0 || ni >= n) continue;\n                if (nj < 0 || nj >= n) continue;\n                pp ^= b[ni][nj];\n                pp ^= b[i][j];\n                pp ^= 1;\n            }\n            b[i + 1][j] = (pp ^ 1) ^ b[i][j];\n        }\n    }\n    memset(his_val, -1, sizeof his_val);\n    bool ok = true;\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            char c;\n            cin >> c;\n            if (c == '.') continue;\n            int d = 0;\n            if (c == 'S') d = 0;\n            else d = 1;\n            d ^= b[i][j];\n            if (his_val[a[i][j]] == -1) his_val[a[i][j]] = d;\n            if (his_val[a[i][j]] != d) ok = false;\n        }\n    }\n    if (!ok) {\n        cout << \"NONE\\n\";\n        return 0;\n    }\n    bool hs = false;\n    for (int z = 0; z < n / 2; z++) {\n        if (his_val[z] == -1) hs = true;\n    }\n    if (hs) {\n        cout << \"MULTIPLE\\n\";\n        return 0;\n    }\n    cout << \"UNIQUE\\n\";\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            int d = his_val[a[i][j]] ^ b[i][j];\n            if (d == 0) cout << \"S\";\n            else cout << \"G\";\n        }\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "sortings",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1584",
    "index": "A",
    "title": "Mathematical Addition",
    "statement": "Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form:\n\n- You are given two positive integers $u$ and $v$, find any pair of integers (\\textbf{not necessarily positive}) $x$, $y$, such that: $$\\frac{x}{u} + \\frac{y}{v} = \\frac{x + y}{u + v}.$$\n- The solution $x = 0$, $y = 0$ is forbidden, so you should find any solution with $(x, y) \\neq (0, 0)$.\n\nPlease help Ivan to solve some equations of this form.",
    "tutorial": "We have the equation: $\\frac{x}{u} + \\frac{y}{v} =\\frac{x +y}{u+ v}.$ Let's multiply the left and right parts by $u*v*(u + v)$. Received: $x * v * (u + v) + y * u * (u + v) = (x + y) * u * v$. After opening the brackets and simplifying, we have: $x *v^2 + y*u^2 = 0$. One of the solutions to this equation is $x = -u^2$, $y = v^2$",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1584",
    "index": "B",
    "title": "Coloring Rectangles",
    "statement": "David was given a \\textbf{red} checkered rectangle of size $n \\times m$. But he doesn't like it. So David cuts the original or any other rectangle piece obtained during the cutting into two new pieces along the grid lines. He can do this operation as many times as he wants.\n\nAs a result, he will get a set of rectangles. Rectangles $1 \\times 1$ are \\textbf{forbidden}.\n\nDavid also knows how to paint the cells \\textbf{blue}. He wants each rectangle from the resulting set of pieces to be colored such that any pair of adjacent cells by side (from the same piece) have different colors.\n\nWhat is the minimum number of cells David will have to paint?",
    "tutorial": "Rectangles after cutting will be painted in a chess coloring. So, if the area is even, then the number of cells of different colors is the same, and if it is odd, then it differs by exactly $1$. Let's find out what part the colored cells occupy in relation to all of them. For an even area, this ratio is always $\\frac{1}{2}$. For odd $\\frac{S - 1}{2 \\cdot S}$. The smaller the odd area, the smaller the ratio. An area equal to $1$ cannot be obtained, so the best ratio is $\\frac{1}{3}$ and is achieved with an area equal to $3$. Then we get the lower estimate for the answer: $answer \\geq n \\cdot m \\cdot \\frac{1}{3}$. Great! We know that the answer is integer, so if we manage to construct such a cut that it is necessary to color exactly such a $cnt$ of cells that$\\frac{n \\cdot m}{3} \\leq cnt < \\frac{n \\cdot m}{3} + 1$, then $cnt$ will be the answer. After all, $cnt$ is the minimum integer value satisfying the estimate. If one of the sides is divisible by $3$, then it is obvious how to cut into $1 \\times 3$ rectangles and get the perfect answer. If the remains of sides $1$ and $1$ or $2$ and $2$, then you can cut into $1 \\times 3$ rectangles and one rectangle with an area of $4$, in which you need to paint over $2$ cells. Then the answer also fits the assessment. If the remains of sides $1$ and $2$, then after cutting into $1 \\times 3$ rectangles, a rectangle will remain $1 \\times 2$, in which you need to paint one cell. The answer also fits the assessment. For all pairs of remains, there is a way to construct an answer satisfying the inequality. Therefore, the answer is $\\lceil \\frac{n \\cdot m}{3} \\rceil$",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1584",
    "index": "C",
    "title": "Two Arrays",
    "statement": "You are given two arrays of integers $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_n$.\n\nLet's define a transformation of the array $a$:\n\n- Choose any non-negative integer $k$ such that $0 \\le k \\le n$.\n- Choose $k$ distinct array indices $1 \\le i_1 < i_2 < \\ldots < i_k \\le n$.\n- Add $1$ to each of $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$, all other elements of array $a$ remain unchanged.\n- Permute the elements of array $a$ in any order.\n\nIs it possible to perform some transformation of the array $a$ \\textbf{exactly once}, so that the resulting array is equal to $b$?",
    "tutorial": "Let's sort the arrays first. Let's check the two smallest elements in the arrays and investigate their behavior. First, obviously, if $a_1 + 1 < b_1$ (as nothing can be matched with $a_1$) or $a_1 > b_1$ (as nothing can be matched with $b_1$) the answer is No. Then, it's possible that $a_1 = b_1 = x$. In this case, we have to have at least one $x$ in the array $a$ at the end. Hence, we can leave $a_1$ untouched, as it already suits to $b_1$. It's also possible that $a_1 + 1 = b_1$. Here we have to increase $a_1$ by $1$. In both cases, the task is reduced to the smallest one. Going to the exact solution from this logic, we just have to sort both arrays and check that for each $1 \\leq i \\leq n$ it's $a_i = b_i$ or $a_i + 1 = b_i$. The complexity of the solution is $O(n log(n))$.",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1584",
    "index": "D",
    "title": "Guess the Permutation",
    "statement": "\\textbf{This is an interactive problem.}\n\nJury initially had a sequence $a$ of length $n$, such that $a_i = i$.\n\nThe jury chose three integers $i$, $j$, $k$, such that $1 \\leq i < j < k \\leq n$, $j - i > 1$. After that, Jury reversed subsegments $[i, j - 1]$ and $[j, k]$ of the sequence $a$.\n\nReversing a subsegment $[l, r]$ of the sequence $a$ means reversing the order of elements $a_l, a_{l+1}, \\ldots, a_r$ in the sequence, i. e. $a_l$ is swapped with $a_r$, $a_{l+1}$ is swapped with $a_{r-1}$, etc.\n\nYou are given the number $n$ and you should find $i$, $j$, $k$ after asking some questions.\n\nIn one question you can choose two integers $l$ and $r$ ($1 \\leq l \\leq r \\leq n$) and ask the number of inversions on the subsegment $[l, r]$ of the sequence $a$. You will be given the number of pairs $(i, j)$ such that $l \\leq i < j \\leq r$, and $a_i > a_j$.\n\nFind the chosen numbers $i$, $j$, $k$ after at most $40$ questions.\n\nThe numbers $i$, $j$, and $k$ are fixed before the start of your program and do not depend on your queries.",
    "tutorial": "Note that the number of inversions on decreasing sequence of length $l$ is $(_2^l)$. As we reversed two non-overlaping subsegments, the number of inversions on each subsegment is equal to sum of number of inversions of parts of reversed subsegments, which are decreasing. First of all, let's find $A := (_2^{k-j+1}) + (_2^{j-i})$ - total number of inversions in sequence. We use 1 question for that. Now let's look on the number of inversions on subsegment [$x$, $n$]. If this number is less than A, then not both reversed subsegments fit entirely, so $i < x$, otherwise $i \\geq x$. Now we can apply binnary search to find $i$. We use $log_2(n)$ questions here. Now let's ask the number of inversions on subsegment [$i+1$, $n$], let's call this number B. We use $1$ question here. From the structure of sequence: $A-B$ = $|\\{x | x > i, a_x < a_i\\}|$ = $|[i+1, j-1]|$ = $j - i - 1$. Now we can find $j - i$, $j$ and $(_2^{j - i})$, due to the definition of A, we find $(_2^{k - j + 1})$. Finaly, we can solve quadratic equation for $k-j+1$ and get $k$. Overall, we used $log_2(n) + 2 \\leq 32$ questions, but we gave you a bit more, in case your solution uses few more questions on some stage.",
    "tags": [
      "binary search",
      "combinatorics",
      "interactive",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1584",
    "index": "E",
    "title": "Game with Stones",
    "statement": "Bob decided to take a break from calculus homework and designed a game for himself.\n\nThe game is played on a sequence of piles of stones, which can be described with a sequence of integers $s_1, \\ldots, s_k$, where $s_i$ is the number of stones in the $i$-th pile. On each turn, Bob picks a pair of non-empty adjacent piles $i$ and $i+1$ and takes one stone from each. If a pile becomes empty, its adjacent piles \\textbf{do not become adjacent}. The game ends when Bob can't make turns anymore. Bob considers himself a winner if at the end all piles are empty.\n\nWe consider a sequence of piles \\textbf{winning} if Bob can start with it and win with some sequence of moves.\n\nYou are given a sequence $a_1, \\ldots, a_n$, count the number of subsegments of $a$ that describe a winning sequence of piles. In other words find the number of segments $[l, r]$ ($1 \\leq l \\leq r \\leq n$), such that the sequence $a_l, a_{l+1}, \\ldots, a_r$ is winning.",
    "tutorial": "This game has greedy strategy: look at first pile, all its stones have to be matched with stones from next pile, because it is its only adjacent pile. If pile is non-empty and there are no next pile, or next pile is smaller than current, Bob loses. Otherwise, Bob makes current pile empty, and remove corresponding number of stones from next pile. Now Bob plays the same game as if had one pile less, we can remove first pile without changing game. Bob wins if at the moment he reduced game to one pile it's already empty. Now let's iteratively define array $c$, where $c_i$ - number of stones left in the $i$-th after removing $1, \\ldots, i - 1$ piles, according to greedy strategy. Let $c_0 = 0$, then $c_i = a_i - c_{i - 1}$. If array contains only positive numbers, then it means that Bob is able to remove piles all the way over. Otherwise, let $t$ be the first moment with $c_t < 0$, this means that Bob was able to remove piles until he meet $t$-th pile and $c_{t-1} > a_t$ happened, so Bob loses. To check that last pile is empty, we need to check if $c_n = 0$. So we have criteria of winning subsequence: $c_i \\geq 0$ for all $i$, $c_n = 0$. Let's expand recursive notation of $c_i$: $c_i = a_i - a_{i - 1} + a_{i - 2} -\\ldots + (-1)^{i-1} \\cdot a_1$. We will solve problem separately for different $l$ - left bound of subsegment. Let's define sequence $a^l := a_l, a_{l+1} \\ldots a_n$, $a_i^l = a_{l + i - 1}$. It has similar array $c^l$. We will find first position of negative number in $c^l$ -$t$ ($c_t^l < 0$). And then count how may zeros are on prefix [$1$, $t-1$]. This will give us number of winning subsegemtns with form $[l, r]$, sum over all $l$ will give us answer for the problem. Note, that $c_i^l = a_i^l - a_{i - 1}^l + \\ldots + (-1)^{i-1} \\cdot a_1^l = a_{l+i-1} - a_{l+i-2} + \\ldots + (-1)^{i-1} \\cdot a_{l} = c_{l+i-1} + (-1)^{i-1} \\cdot c_{l - 1}$. Note, that $c_i^l < 0$ if and only if $c_{l + i - 1} < (-1)^{i - 1} \\cdot c_{l - 1}$. Let's divide problem by parity of indexes. Now to find first position of negative number in $c^l$ we should find first position of \"number less than x\" on suffix of $c$. This can be done many ways, for example, by descending through segment tree (segment tree for each parity). Note, that $c_i^l = 0$, if and only if $c_{l + i - 1} = (-1)^{i - 1} \\cdot c_{l - 1}$. Same division of problem by parity. Now to count number of zeros on subsegment of $c_l$ we should count number of \"equals to x\" on subsegment of $c$. This can be done by storing all positions of each $c_i$ in some container (one for each parity) and binnary search. Overall complexity of the solution : $\\mathcal{O}(n \\cdot log(n))$",
    "tags": [
      "binary search",
      "data structures",
      "games",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1584",
    "index": "F",
    "title": "Strange LCS",
    "statement": "You are given $n$ strings $s_1, s_2, \\ldots, s_n$, each consisting of lowercase and uppercase English letters. In addition, it's guaranteed that each character occurs in each string \\textbf{at most twice}. Find the longest common subsequence of these strings.\n\nA string $t$ is a subsequence of a string $s$ if $t$ can be obtained from $s$ by deletion of several (possibly, zero or all) symbols.",
    "tutorial": "Let's define efinegraph with vertexes ($c$, $msk$), where $chr$ denoting some character, ans $mask$ is $n$-bit mask of occasions ($i$-th bit is set to $1$ if and only if we consider second occasion of $c$ in $i$-th string). Not all $mask$ are possible for some $c$ since there could be less than $2$ occasions. Note: vertex define choise of character and positions of this character in all strings. Note, that graph has $\\mathcal{O}(|\\Sigma| \\cdot 2^n)$ vertices. Let's define strict comparison (<) of vertices:($chr1$, $msk1$) < ($char2$, $msk2$) if and only if positions chosen by first vertex are stricly lefter than ones chosen by second (for all strings). Let's define another comparison ($\\leq$) the same way, but allow some position to be equal. Note: strict comparison is anti-reflexive, both comparison are transitive and this stands ($a$ $\\leq$ $b$ < $c$ $\\Rightarrow$ $a$ < $c$). Graph contains directed edges from one vertex to another, if and only if first is smaller by defined comparison. Note: graph is acyclic, because of transitivity of pair comparison. Note: that for every common subsequence there is unique corresponding path in defined graph and vice versa. So we need to find longest path in this graph. Vertex-length of path will be equal to the length of corresponding subsequence. We want to calculate $dp$($c$, $msk$) - length of longest path starting from this vertex. This $dp$ is easy to calulate on DAG, but number of edges is too big. We want to remove some edges without changing values of $dp$. Note: if removal of edge doesn't change $dp$ of its starting point, when it doesn't change $dp$ at all. Let's look at arbitrary vertex $(c, msk)$, that has at least one outgoing edge and some longest path starting from it (it has at least one edge): [$(c, msk) \\rightarrow (c2, msk2) \\rightarrow \\ldots$]. Suppose there exists mask $MidMsk \\neq msk2$, such that: (c, mask) < ($c2$, $MidMsk$) $\\leq$ ($c2$, $msk2$). By the qualities of defined comparisons, we can change second vertex in longest path to ($c2$, $MidMsk$). Now let's find mask for fixed $c2$ which correspond to choise of leftmost positions righter than positions chosen by ($c$, $msk$). It can be found in $\\mathcal{O}(n)$ time. As we notices earlier, without loss of generality, longest path (with fixed $c2$) goes through this vertex , so we can harmlessly remove all edges going from current vertex to the vertices with character $c2$, but diffrent mask. This can be done for every character. Now graph each vertex has $\\mathcal{O}(|\\Sigma|)$ outgoing edges, so $dp$ can be calculated fast enough. Subsequence itself can be easily found now. Note: there is no need for graph in solution, it's just abstraction for better understanding. Note: we don't have to calculate $dp$ for all vertices, we only need to find $dp(c, 0)$ for all $c$, it can be proven by applying same logic. Overall complexity: $\\mathcal{O}(n \\cdot |\\Sigma|^2 \\cdot 2^n)$",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "greedy",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1584",
    "index": "G",
    "title": "Eligible Segments",
    "statement": "You are given $n$ \\textbf{distinct} points $p_1, p_2, \\ldots, p_n$ on the plane and a positive integer $R$.\n\nFind the number of pairs of indices $(i, j)$ such that $1 \\le i < j \\le n$, and for every possible $k$ ($1 \\le k \\le n$) the distance from the point $p_k$ to the \\textbf{segment} between points $p_i$ and $p_j$ is at most $R$.",
    "tutorial": "The distance from point $P$ to segment $[AB]$ is equal to the maximum of the distance from point $P$ to ray $[AB)$ and the distance from point $P$ to ray $[BA)$. Let's fix a point $P_i$. Now we have to find all points $P_j$ such that distance from every point $P_k (1 \\le k \\le n)$ to the ray $[P_i, P_j)$ is less than $R$. For every point $P_k$ let's build two tangents from point $P_i$ to the circle with the center in the point $P_k$ and radius $R$. These tangents form an angle $A_k$. The distance from the point $P_k (1 \\le k \\le n)$ to the ray $[P_i, P_j)$ is less than $R$ iff the ray $[P_i, P_j)$ lies inside the angle $A_k$. So we can build all these angles $A_k$ and intersect them, after that, we only have to check that the ray $[P_i, P_j)$ lies inside the intersection of all angles for all $1 \\le j \\le n$. Time complexity: $O(n^2)$.",
    "tags": [
      "geometry"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1585",
    "index": "A",
    "title": "Life of a Flower",
    "statement": "Petya has got an interesting flower. Petya is a busy person, so he sometimes forgets to water it. You are given $n$ days from Petya's live and you have to determine what happened with his flower in the end.\n\nThe flower grows as follows:\n\n- If the flower isn't watered for two days in a row, it dies.\n- If the flower is watered in the $i$-th day, it grows by $1$ centimeter.\n- If the flower is watered in the $i$-th and in the $(i-1)$-th day ($i > 1$), then it grows by $5$ centimeters instead of $1$.\n- If the flower is not watered in the $i$-th day, it does not grow.\n\nAt the beginning of the $1$-st day the flower is $1$ centimeter tall. What is its height after $n$ days?",
    "tutorial": "Iterating through array and looking on our element and previous element, there is possible 4 variants: $a_i == 1$ and $a_{i - 1} == 1$ - k += 5 $a_i == 1$ and $a_{i - 1} == 0$ - k += 1 $a_i == 0$ and $a_{i - 1} == 1$ - k += 0 $a_i == 0$ and $a_{i - 1} == 0$ - k = -1, break",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1585",
    "index": "B",
    "title": "Array Eversion",
    "statement": "You are given an array $a$ of length $n$.\n\nLet's define the eversion operation. Let $x = a_n$. Then array $a$ is partitioned into two parts: left and right. The left part contains the elements of $a$ that are not greater than $x$ ($\\le x$). The right part contains the elements of $a$ that are strictly greater than $x$ ($> x$). The order of elements in each part is kept the same as before the operation, i. e. the partition is stable. Then the array is replaced with the concatenation of the left and the right parts.\n\nFor example, if the array $a$ is $[2, 4, 1, 5, 3]$, the eversion goes like this: $[2, 4, 1, 5, 3] \\to [2, 1, 3], [4, 5] \\to [2, 1, 3, 4, 5]$.\n\nWe start with the array $a$ and perform eversions on this array. We can prove that after several eversions the array $a$ stops changing. Output the minimum number $k$ such that the array stops changing after $k$ eversions.",
    "tutorial": "Lemma: If $x$ is max element of the array then eversion doesn't change the array. Proof: In spite of the fact that division is stable, all elements will be passed to the left part. Their order won't be changed. Lemma: The lastest element after eversion is the rightest element of the array which is greater than $x$ and lefter than $x$ in the array. Proof: Look at all elements that are greater than $x$. This is the right part of the division. Due to stable division, the right element that is greater will be new $x$. There're no elements greater than $x$ and righter than $x$ because of eversion definition. Let's build a sequence $x_a, x_{a-1}, \\dots x_0$, where $x_0 = a_n$, $x_{i + 1}$ - the rightest element lefter than $x_i$ and greater than $x_i$. The answer is equals to $a$ because $\\{x_i\\}$ is a sequence of last elements overall eversions. Example: $6\\ 10\\ 4\\ 17\\ 9\\ 2\\ 8\\ 1$ Sequence $\\{x_i\\}$ - is $1, 8, 9, 17$. Answer is $3$.",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1585",
    "index": "C",
    "title": "Minimize Distance",
    "statement": "A total of $n$ depots are located on a number line. Depot $i$ lies at the point $x_i$ for $1 \\le i \\le n$.\n\nYou are a salesman with $n$ bags of goods, attempting to deliver one bag to each of the $n$ depots. You and the $n$ bags are initially at the origin $0$. You can carry up to $k$ bags at a time. You must collect the required number of goods from the origin, deliver them to the respective depots, and then return to the origin to collect your next batch of goods.\n\nCalculate the minimum distance you need to cover to deliver all the bags of goods to the depots. You do \\textbf{not} have to return to the origin after you have delivered all the bags.",
    "tutorial": "This problem can be solved with a greedy approach. First, we note that it makes sense to solve positive points $x^p$ and negative points $x^n$ separately since we would like the minimize the number of times we move across the origin. Second, when we move to the farthest depot to which we haven't delivered a bag yet, we can cover $k-1$ other depots. Thus we can also deliver bags to the $k-1$ next farthest depots from the origin. Thus to solve the positive set, we can just sort the positive points and take the sum of the distance of points starting from the farthest point, jumping k points at each step. Thus we can sort $x^p$ and $x^n$ and find the answer through the following equations: $sum_{pos} = \\sum_{i=0}^{|pos| - ki >= 0} x^p_{|pos| - ki}$ $sum_{neg} = \\sum_{i=0}^{|neg| - ki >= 0} x^n_{|neg| - ki}$ The final answer will be $2(sum_{pos} + sum_{neg})$ minus the maximum distance of a positive or negative depot since we do not have to return to the origin in the end.",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1585",
    "index": "D",
    "title": "Yet Another Sorting Problem",
    "statement": "Petya has an array of integers $a_1, a_2, \\ldots, a_n$. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.\n\nPetya likes to challenge himself, so he wants to sort array using only $3$-cycles. More formally, in one operation he can pick $3$ \\textbf{pairwise distinct} indices $i$, $j$, and $k$ ($1 \\leq i, j, k \\leq n$) and apply $i \\to j \\to k \\to i$ cycle to the array $a$. It simultaneously places $a_i$ on position $j$, $a_j$ on position $k$, and $a_k$ on position $i$, without changing any other element.\n\nFor example, if $a$ is $[10, 50, 20, 30, 40, 60]$ and he chooses $i = 2$, $j = 1$, $k = 5$, then the array becomes $[\\underline{50}, \\underline{40}, 20, 30, \\underline{10}, 60]$.\n\nPetya can apply arbitrary number of $3$-cycles (possibly, zero). You are to determine if Petya can sort his array $a$, i. e. make it non-decreasing.",
    "tutorial": "Set of all $3$-cycles generates a group of even permuations $A_n$. So the answer is \"YES\" if and only if there is an even permutation that sorts array $a$. If all elements of $a$ are distinct, then there is unique sorting permutation that has the same parity as $a$. If there are identic elements in $a$, let's look at arbitrary sorting permutation. If it's odd, then we can add transposition of identic elements to it, after this permutation remains sorting, but becomes even. So in this case, even sorting permutation always exists. Overall, we need to check if all elements of $a$ are distinct. If it's not true, then answer is \"YES\". Otherwise, we need to check that permutation $a$ is even. This can be done in many ways, including some with $\\mathcal{O}(n)$ complexity.",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1585",
    "index": "E",
    "title": "Frequency Queries",
    "statement": "Petya has a rooted tree with an integer written on each vertex. The vertex $1$ is the root. You are to answer some questions about the tree.\n\nA tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node $v$ is the next vertex on the shortest path from $v$ to the root.\n\nEach question is defined by three integers $v$, $l$, and $k$. To get the answer to the question, you need to perform the following steps:\n\n- First, write down the sequence of all integers written on the shortest path from the vertex $v$ to the root (including those written in the $v$ and the root).\n- Count the number of times each integer occurs. Remove all integers with less than $l$ occurrences.\n- Replace the sequence, removing all duplicates and ordering the elements by the number of occurrences in the original list in increasing order. In case of a tie, you can choose the order of these elements arbitrary.\n- The answer to the question is the $k$-th number in the remaining sequence. Note that the answer is not always uniquely determined, because there could be several orderings. Also, it is possible that the length of the sequence on this step is less than $k$, in this case the answer is $-1$.\n\nFor example, if the sequence of integers on the path from $v$ to the root is $[2, 2, 1, 7, 1, 1, 4, 4, 4, 4]$, $l = 2$ and $k = 2$, then the answer is $1$.\n\nPlease answer all questions about the tree.",
    "tutorial": "Let's traverse through the tree with depth-first-search from the root and maintain counting array ($cnt_x$ := \"number of occasions of x in the sequence\"). When dfs enters vertex $v$, it increases $cnt_{a_v}$ by $1$, then it proceeds all queries correspondent to $v$. When dfs leaves the vertex, it decreases $cnt_{a_v}$ by $1$. Let's maintain this quantities: Sorting permuation $p$ of $cnt$, initially - $1, 2, \\ldots, n$. Inverse permuation $p^{-1}$. For each $x \\in \\{0, 1, \\ldots, n\\}$, \"lower_bound\" $lb_x$ in sorted array. More formally, minimal $i$ such that $cnt_{p_i} \\geq x$. When we want to increase $cnt_x$ by $1$: Move $x$ in the end of block of same values in sorted array. So we need to swap ($p^{-1}_i$)-th and $(lb_{cnt_x+1}-1$)-th positions of $p$. Change $p^{-1}$ accrodingly to the change of $p$. Decrease $lb_{cnt_x + 1}$ by $1$. Note: that's the only $lb$ value that after during this operation. Increase $cnt_x$. Operation of decreasing $cnt_x$ by $1$ can be done symmetrically. Note: if answer exists, then one of possible answers is $p_{lb_l + k - 1}$. Total complexity: $\\mathcal{O}(n + q)$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1585",
    "index": "F",
    "title": "Non-equal Neighbours",
    "statement": "You are given an array of $n$ positive integers $a_1, a_2, \\ldots, a_n$. Your task is to calculate the number of arrays of $n$ positive integers $b_1, b_2, \\ldots, b_n$ such that:\n\n- $1 \\le b_i \\le a_i$ for every $i$ ($1 \\le i \\le n$), and\n- $b_i \\neq b_{i+1}$ for every $i$ ($1 \\le i \\le n - 1$).\n\nThe number of such arrays can be very large, so print it modulo $998\\,244\\,353$.",
    "tutorial": "Let's solve the problem using the inclusion-exclusion formula. Let the $i$-th property mean that the elements $b_i$ and $b_{i+1}$ are the same. Then for each $k=1, \\ldots, n - 1$ the array is divided into $n-k$ consecutive segments, where all the numbers in each of the segments are equal. Next, we will use the dynamic programming method $dp[i][j]$ $-$ we have already split the prefix of the array $b$ of length $i$ into a number of segments, where $j$ denotes the parity of the number of segments. We will iterate over the index $i=1, \\ldots, n$. Now for each $j$ ($1\\le j < i$) we have to make an update $dp[i][0] += dp[j - 1][1] \\cdot f(j, i)$, where $f(j, i)$ is the minimum of the numbers in the array $a$ on the segment $[j, i]$. Similar to $dp[i][1] += dp[j - 1][0] *\\cdot f(j, i)$. We get the solution with time complexity $O(n^2)$. To speed it up to $O(n)$, it is enough to maintain a stack of minimums on the prefix and recalculate $dp[i][0/1]$ with it.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1585",
    "index": "G",
    "title": "Poachers",
    "statement": "Alice and Bob are two poachers who cut trees in a forest.\n\nA forest is a set of zero or more trees. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a node $v$ is the next vertex on the shortest path from $v$ to the root. Children of vertex $v$ are all nodes for which $v$ is the parent. A vertex is a leaf if it has no children.\n\nIn this problem we define the depth of vertex as number of vertices on the simple path from this vertex to the root. The rank of a tree is the minimum depth among its leaves.\n\nInitially there is a forest of rooted trees. Alice and Bob play a game on this forest. They play alternating turns with Alice going first. At the beginning of their turn, the player chooses a tree from the forest. Then the player chooses a positive cutting depth, which should \\textbf{not exceed the rank} of the chosen tree. Then the player removes all vertices of that tree whose depth is less that or equal to the cutting depth. All other vertices of the tree form a set of rooted trees with root being the vertex with the smallest depth before the cut. All these trees are included in the game forest and the game continues.\n\nA player loses if the forest is empty at the beginning of his move.\n\nYou are to determine whether Alice wins the game if both players play optimally.",
    "tutorial": "Solution below uses Sprague-Grundy theory. Make sure you understand this concept before reading the editorial. We can note that every position that appears in the game is subtree of one of initial trees or their combinations. This shows that it's sufficient to find grundy-values for all subtrees of initial trees. Dynamic programming on subtrees will be applied here. We will identify subtree by its root. In each node we will store array of grundy-values for each of possible moves in the game on correspondent subtree. Length of this array is numerically equal to the rank of subtree. We will arrange moves in decreasing by cutting depth order. We will also store grundy-value for subtree itself, it's equal to MEX of grundy-values over all moves. DP is recalculated in this way: If node is a leaf it has one move leading to empty game. If node has exactly one child, then we should add grundy-value of child in the end of its array and copy this array in current node. We will recalculate MEX of grundy-values in array explicitely here. We must use the fact that MEX can only increase at this point. Suppose that node has multiple children. We will choose one with the smallest rank (shortest array). Let's imagine here, that we cut all arrays by the length of the shortest, as we cannot make moves with cutting depth greater than rank. In the array of current node we will put array, in each position of which lies XOR of grundy-values in correspondent positions over all arrays of children. We should also add in the end of this array XOR of all grundy-values over all children. We should also calculate MEX of grundy-values in constructed array, we will do it explicitly and starting from $0$, calculated value will be equal to grundy-value of current node. Why this work fast? We will use coin method of amortyzed analysis. We will remain the invariant that on each array that we track lie at least ($3 \\cdot$ LENGTH $-$ MEX) coins: Each time we calculate MEX explicitly we can use one coin, so this operation is completely paid off. In leaf-case we create one array with length $1$ and put $3$ coins on it. In other cases we will track one of arrays of children as array of current node and stop tracking arrays of other children. In there is exactly one child, we extend arrays length by $1$ and put $3$ extra coins on it. Remember, we have already showed that MEX recalculation is paid off. In case of multiple children: let's fix $h$ - length of shortest array of chidlren. We will track this array as array of current. There are ($\\geq 2 \\cdot h$) coins on this array. As all other arrays are not shorter, they also have ($\\geq 2 \\cdot h$) coins each. Let's move $h$ coins from them to the shortest one, now it has ($\\geq 3 \\cdot h$) coins. For each of array (except shortest) we will spend $h$ coins to recalculate grundy-value in the shortest one, we do XOR= operation here. In the moment we extend array by adding XOR of grundy-values over children we put extra $3$ coins on it. Note that we lose track of all arrays used here except the shortest one. Note, that there are enough coins to pay off MEX calculation on the shortest array. The only problem left is that when we are trying to recalculate MEX of some array we have to check if number appears in the array. We can maintain set of all elements of the array, each node should contain set for its array. Number of insert/erase/exist queries to all sets are bounded by $4 \\cdot n$, as we pay off each operation except failed attempt to increase MEX, but this happens ones in each node. Total complexity: $\\mathcal{O}(n \\cdot \\log(n))$.",
    "tags": [
      "dp",
      "games",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1586",
    "index": "I",
    "title": "Omkar and Mosaic",
    "statement": "Omkar is creating a mosaic using colored square tiles, which he places in an $n \\times n$ grid. When the mosaic is complete, each cell in the grid will have either a glaucous or sinoper tile. However, currently he has only placed tiles in some cells.\n\nA completed mosaic will be a \\textbf{mastapeece} if and only if each tile is adjacent to exactly $2$ tiles of the same color ($2$ tiles are adjacent if they share a side.) Omkar wants to fill the rest of the tiles so that the mosaic becomes a \\textbf{mastapeece}. Now he is wondering, is the way to do this unique, and if it is, what is it?",
    "tutorial": "The first main observation to make is that the possible mastapeeces don't just have square \"loops\" of the same color. A counterexample to this is shown below: Instead, observe that, in a mastapeece: a) The two cells adjacent to corner cells must be the same color as the corner. b) Any cell not on the border must be adjacent to two sinoper tiles and two glaucous tiles If we then start at two cells adjacent to some corner and keep applying b) to cells on the long diagonal with the corner, we find that the long diagonals starting at the adjacent cells must be identical and tiled alternately with glaucous and sinoper tiles, like so: From here, it's pretty easy to figure out how to implement the problem. Some examples of what mastapeeces look like are shown below:",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1588",
    "index": "F",
    "title": "Jumping Through the Array",
    "statement": "You are given an array of integers $a$ of size $n$ and a permutation $p$ of size $n$. There are $q$ queries of three types coming to you:\n\n- For given numbers $l$ and $r$, calculate the sum in array $a$ on the segment from $l$ to $r$: $\\sum\\limits_{i=l}^{r} a_i$.\n- You are given two numbers $v$ and $x$. Let's build a directed graph from the permutation $p$: it has $n$ vertices and $n$ edges $i \\to p_i$. Let $C$ be the set of vertices that are reachable from $v$ in this graph. You should add $x$ to all $a_u$ such that $u$ is in $C$.\n- You are given indices $i$ and $j$. You should swap $p_i$ and $p_j$.\n\n\\begin{center}\n{\\small The graph corresponding to the permutation $[2, 3, 1, 5, 4]$.}\n\\end{center}\n\nPlease, process all queries and print answers to queries of type $1$.",
    "tutorial": "Let's call $B = \\lfloor \\sqrt{n} \\rfloor$. Let's divide an array $a$ into consecutive blocks of size $B$. To answer the query we will have to sum $O(B)$ $a_i$ near the segment's bounds and $O(\\frac{n}{B})$ sums on blocks. Let's try to calculate them fast. There are two types of cycles: small: with length $< B$ big: with length $\\geq B$ If there is a second type query for the small cycle it is easy to make it in $O(B)$ time: let's iterate over cycle's elements and add $x$ into its $a_i$ and into its array's block sum. It is harder to deal with big cycles. Let's divide each big cycle into blocks, each having the size in $[B, 2B - 1]$. Initially, it is possible. After each query of type $3$ it is possible to reconstruct this division fast: Let's split two blocks with $i$ and $j$. After that, it is possible to reconstruct the divisions of each new cycle into blocks. After that, we should avoid small blocks (with size $< B$). Let's merge two consecutive blocks if one of them has the size $< B$. After that, if the total block has size $\\geq 2B$ let's split it into two equal blocks. Someone calls this method split-rebuild. So, maintaining this structure we will have at most $\\frac{n}{B}$ cycle blocks at any moment. If there is a second type query for the big cycle let's add $x$ to the cycle blocks for this cycle. To consider these values while answering the first type query let's maintain the last structure: For each cycle block $t$ let's calculate the values $pref_{t,0}, pref_{t,1}, \\ldots, pref_{t,\\lceil \\frac{n}{B} \\rceil}$, where $pref_{t,i}$ is the number of elements from the $t$-th cycle block in the first $i$ array's blocks. Using these values it is easy to consider additions to the cycle blocks in the subsegments sums queries. And the values of $pref$ can be recalculated during the cycle's updates because we make $O(1)$ splits and merges. During each split or merge we should recalculate $pref$ for $O(1)$ rows (and this can be done in $O(\\frac{n}{B})$ for one $t$). Also during each split or merge we should zero additions to blocks in operations just pushing the added value into the elements of the block (their number is smaller than $2B$). The total complexity of the solution is $O(n \\sqrt{n})$.",
    "tags": [
      "binary search",
      "data structures",
      "graphs",
      "two pointers"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1592",
    "index": "A",
    "title": "Gamer Hemose",
    "statement": "One day, Ahmed_Hossam went to Hemose and said \"Let's solve a gym contest!\". Hemose didn't want to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract him. Sadly, Ahmed can't solve it... Could you help him?\n\nThere is an Agent in Valorant, and he has $n$ weapons. The $i$-th weapon has a damage value $a_i$, and the Agent will face an enemy whose health value is $H$.\n\nThe Agent will perform one or more moves until the enemy dies.\n\nIn one move, he will choose a weapon and decrease the enemy's health by its damage value. The enemy will die when his health will become less than or equal to $0$. However, not everything is so easy: \\textbf{the Agent can't choose the same weapon for $2$ times in a row}.\n\nWhat is the minimum number of times that the Agent will need to use the weapons to kill the enemy?",
    "tutorial": "It's always optimal to use two weapons with the highest damage value and switch between them. Let $x$ be the highest damage value of a weapon, and $y$ be the second-highest damage value of a weapon. we will decrease monster health by $x$ in the first move, and by $y$ in the second move and so on. $ans=\\begin{cases} 2 \\cdot \\frac{H}{x+y}, & \\text{if $H$ $mod$ $(x+y)$ $= 0$}\\\\ 2 \\cdot \\lfloor{\\frac{H}{x+y}}\\rfloor + 1, & \\text{if $H$ $mod$ $(x+y)$ $\\leq x$}\\\\ 2 \\cdot \\lfloor{\\frac{H}{x+y}}\\rfloor + 2, & \\text{otherwise}\\\\ \\end{cases}$",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1592",
    "index": "B",
    "title": "Hemose Shopping",
    "statement": "Hemose was shopping with his friends Samez, AhmedZ, AshrafEzz, TheSawan and O_E in Germany. As you know, Hemose and his friends are problem solvers, so they are very clever. Therefore, they will go to all discount markets in Germany.\n\nHemose has an array of $n$ integers. He wants Samez to sort the array in the non-decreasing order. Since it would be a too easy problem for Samez, Hemose allows Samez to use only the following operation:\n\n- Choose indices $i$ and $j$ such that $1 \\le i, j \\le n$, and $\\lvert i - j \\rvert \\geq x$. Then, swap elements $a_i$ and $a_j$.\n\nCan you tell Samez if there's a way to sort the array in the non-decreasing order by using the operation written above some finite number of times (possibly $0$)?",
    "tutorial": "The answer is always \"YES\" If $n \\geq 2*x$ because you can reorder the array as you want. Otherwise, You can swap the first $n-x$ elements and the last $n-x$ elements, so you can reorder them as you want but the rest have to stay in their positions in the sorted array. So if elements in the subarray $[n-x+1, x]$ in the original array are in their same position after sorting the array then the answer is YES, otherwise NO.",
    "tags": [
      "constructive algorithms",
      "dsu",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1592",
    "index": "C",
    "title": "Bakry and Partitioning",
    "statement": "Bakry faced a problem, but since he's lazy to solve it, he asks for your help.\n\nYou are given a tree of $n$ nodes, the $i$-th node has value $a_i$ assigned to it for each $i$ from $1$ to $n$. As a reminder, a tree on $n$ nodes is a connected graph with $n-1$ edges.\n\nYou want to delete \\textbf{at least $1$, but at most $k-1$ edges} from the tree, so that the following condition would hold:\n\n- For every connected component calculate the bitwise XOR of the values of the nodes in it. Then, these values have to be the same for all connected components.\n\nIs it possible to achieve this condition?",
    "tutorial": "The most important observation is: If you can partition the tree into $m$ components such that the xor of every component is $x$, Then you can partition the tree into $m-2$ components by merging any 3 adjacent components into 1 component, and the xor of the new component will equal $x$, since $x$ xor $x$ xor $x$ = $x$. Notice that the answer is always YES if the xor of the array is $0$. Because you can delete any edge in the tree, and the 2 components will have the same xor. Otherwise, We need to partition the tree into 3 components that have the same xor. Let $x$ be the xor of all node values in the tree, then The xor of every component will equal $x$. We need to search for 2 edges to delete from the tree and one of them such that the xor every component equals $x$ and if we found them and $K \\neq 2$ then the answer is \"YES\" otherwise \"NO\". To search on the 2 edges, We will first root the tree on node 1, then we will search on the deepest subtree such that xor value of subtree equals $x$, then erase the edge and search again for the 2nd edge.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1592",
    "index": "D",
    "title": "Hemose in ICPC ?",
    "statement": "\\textbf{This is an interactive problem!}\n\n{In the last regional contest Hemose, ZeyadKhattab and YahiaSherif — members of the team Carpe Diem — did not qualify to ICPC because of some \\sout{un}known reasons. Hemose was very sad and had a bad day after the contest, but ZeyadKhattab is very wise and knows Hemose very well, and does not want to see him sad.}\n\nZeyad knows that Hemose loves tree problems, so he gave him a tree problem with a very special device.\n\nHemose has a weighted tree with $n$ nodes and $n-1$ edges. Unfortunately, Hemose doesn't remember the weights of edges.\n\nLet's define $Dist(u, v)$ for $u\\neq v$ as the greatest common divisor of the weights of all edges on the path from node $u$ to node $v$.\n\nHemose has a special device. Hemose can give the device a set of nodes, and the device will return the largest $Dist$ between any two nodes from the set. More formally, if Hemose gives the device a set $S$ of nodes, the device will return the largest value of $Dist(u, v)$ over all pairs $(u, v)$ with $u$, $v$ $\\in$ $S$ and $u \\neq v$.\n\nHemose can use this Device \\textbf{at most $12$ times}, and wants to find any two distinct nodes $a$, $b$, such that $Dist(a, b)$ is maximum possible. Can you help him?",
    "tutorial": "The maximum gcd of a path equals the maximum weight of an edge in the tree. Let $x$ be the value of the maximum weight of an edge in the tree, We need to find $u$, $v$ such that there's an edge between $u$ and $v$ with weight equals $x$. Let's find $x$ by putting all the $n$ nodes in the same query, Now we need to find $u$, $v$. If we have an array of edges such that for any consecutive subarray: The component of nodes inside the subarray is connected using the edges inside the subarray. Then we can binary search on this array to find the edge with the maximum weight. If we put the edges in the array using the order of Euler tour traversal, the array will satisfy the condition above, and we can solve the problem. Total number of queries is $1 + log(2*(n-1))$.",
    "tags": [
      "binary search",
      "dfs and similar",
      "implementation",
      "interactive",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1592",
    "index": "E",
    "title": "Bored Bakry",
    "statement": "Bakry got bored of solving problems related to xor, so he asked you to solve this problem for him.\n\nYou are given an array $a$ of $n$ integers $[a_1, a_2, \\ldots, a_n]$.\n\nLet's call a subarray $a_{l}, a_{l+1}, a_{l+2}, \\ldots, a_r$ \\textbf{good} if $a_l \\, \\& \\, a_{l+1} \\, \\& \\, a_{l+2} \\, \\ldots \\, \\& \\, a_r > a_l \\oplus a_{l+1} \\oplus a_{l+2} \\ldots \\oplus a_r$, where $\\oplus$ denotes the bitwise XOR operation and $\\&$ denotes the bitwise AND operation.\n\nFind the length of the longest good subarray of $a$, or determine that no such subarray exists.",
    "tutorial": "Let $And(l, r)$ denotes the bitwise and of the elements in subarray $[L, R]$ in the array and $Xor(l, r)$ denotes the bitwise xor of the elements in subarray $[L, R]$ in the array. If subarray $[L, R]$ length is odd then it can't be a good subarray because $And(l, r)$ is a submask of $Xor(l, r)$ since every bit in $And(l, r)$ occurs odd times so it will be set in $Xor(l, r)$. If subarray $[L, r]$ length is even then every bit in $And(l, r)$ will be unset in $Xor(l, r)$ so we only care about the most significant bit in $And(l, r)$. Let's solve for every bit $k$, Let's call bit $m$ important bit if $m > k$. For every $r$ in the array, We need to find the minimum $l$ such that $[l, r]$ is even, $k$ is set in $And(l, r)$ and all the important bits are unset in $Xor(l, r)$. Since we only care about the important bits, We can make a prefix array where $pref_i$ is the prefix xor till the index $i$ considering only the important bits. So for every $r$, we need to find the minimum $l$ that satisfy these conditions: $1$ - $r-l+1$ is even. $2$ - $k$ is set in all elements in subarray $[l, r]$. $3$ - $pref_r$ xor $pref_{l-1}$ $= 0$. which can be solved easily in $O(NlogN)$.",
    "tags": [
      "bitmasks",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1592",
    "index": "F1",
    "title": "Alice and Recoloring 1",
    "statement": "\\textbf{The difference between the versions is in the costs of operations. Solution for one version won't work for another!}\n\nAlice has a grid of size $n \\times m$, \\textbf{initially all its cells are colored white}. The cell on the intersection of $i$-th row and $j$-th column is denoted as $(i, j)$. Alice can do the following operations with this grid:\n\n- Choose any subrectangle containing cell $(1, 1)$, and flip the colors of all its cells. (Flipping means changing its color from white to black or from black to white).\n\n\\textbf{This operation costs $1$ coin.}\n- Choose any subrectangle containing cell $(n, 1)$, and flip the colors of all its cells.\n\n\\textbf{This operation costs $2$ coins.}\n- Choose any subrectangle containing cell $(1, m)$, and flip the colors of all its cells.\n\n\\textbf{This operation costs $4$ coins.}\n- Choose any subrectangle containing cell $(n, m)$, and flip the colors of all its cells.\n\n\\textbf{This operation costs $3$ coins.}\n\n\\textbf{As a reminder, subrectangle is a set of all cells $(x, y)$ with $x_1 \\le x \\le x_2$, $y_1 \\le y \\le y_2$ for some $1 \\le x_1 \\le x_2 \\le n$, $1 \\le y_1 \\le y_2 \\le m$}.\n\nAlice wants to obtain her favorite coloring with these operations. What's the smallest number of coins that she would have to spend? It can be shown that it's always possible to transform the initial grid into any other.",
    "tutorial": "We will transform favorite coloring to the all-white coloring instead. Let's denote W by $0$ and B by $1$. First observation is that it doesn't make sense to do operations of type $2$ and $3$ at all. Indeed, each of them can be replaced with $2$ operations of type $1$: Instead of flipping subrectangle $[x, n]\\times[1, y]$, we can flip subrectangles $[1, n]\\times[1, y]$ and $[1, x-1]\\times[1, y]$, and similarly for $[1, x]\\times[y, n]$. So, from now on we only consider first and last operations. Let's create a grid $a$ of $n$ rows and $m$ columns, where $a[i][j]$ denotes the parity of the sum of numbers in those of cells $(i, j), (i+1, j), (i, j+1), (i+1, j+1)$ of favorite coloring, which are present on the grid. Clearly, all numbers in $a$ are $0$ if and only if current coloring is all $0$, so we will want to just make the grid $a$ all $0$. Let's look at how first and last operations affect the grid $a$. If we flip the subrectangle $[1, x]\\times [1, y]$ with the operation of the first type, in grid $a$ the only value that changes is $a[x][y]$. If we flip the subrectangle $[x, n]\\times [y, m]$, clearly $x, y>1$ (otherwise we could have instead used $2$ operations of the first type). Then, it's easy to see that the only cells that will change are $a[x-1][y-1], a[n][y-1], a[x-1][m], a[n][m]$. So, now we have the following problem: we have a binary grid $n\\times m$. In one operation, we can change some $1$ to $0$, with cost of $1$ coin, or to select some $1 \\le x\\le n-1, 1 \\le y \\le m-1$, and flip the numbers in cells $a[x][y], a[n][y], a[x][m], a[n][m]$ with cost of $3$ coins. What's the smallest cost to make all numbers $0$? Now, it's easy to see that it doesn't make sense to apply second operation more than once, as instead of doing it twice, we can apply the operation of the first type at most $6$ times (as cell $a[n][m]$ will be flipped twice). Moreover, it only makes sense to apply the second operation if there exist such $1 \\le x\\le n-1, 1 \\le y \\le m-1$ for which all cells $a[x][y], a[n][y], a[x][m], a[n][m]$ are $1$. So, the algorithm would be to calculate the grid $a$, to calculate the total number of ones in it $ans$, and substract $1$ from $ans$ if there exists such $1 \\le x\\le n-1, 1 \\le y \\le m-1$ for which all cells $a[x][y], a[n][y], a[x][m], a[n][m]$ are $1$. Complexity $O(nm)$.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1592",
    "index": "F2",
    "title": "Alice and Recoloring 2",
    "statement": "\\textbf{The difference between the versions is in the costs of operations. Solution for one version won't work for another!}\n\nAlice has a grid of size $n \\times m$, \\textbf{initially all its cells are colored white}. The cell on the intersection of $i$-th row and $j$-th column is denoted as $(i, j)$. Alice can do the following operations with this grid:\n\n- Choose any subrectangle containing cell $(1, 1)$, and flip the colors of all its cells. (Flipping means changing its color from white to black or from black to white).\n\n\\textbf{This operation costs $1$ coin.}\n- Choose any subrectangle containing cell $(n, 1)$, and flip the colors of all its cells.\n\n\\textbf{This operation costs $3$ coins.}\n- Choose any subrectangle containing cell $(1, m)$, and flip the colors of all its cells.\n\n\\textbf{This operation costs $4$ coins.}\n- Choose any subrectangle containing cell $(n, m)$, and flip the colors of all its cells.\n\n\\textbf{This operation costs $2$ coins.}\n\n\\textbf{As a reminder, subrectangle is a set of all cells $(x, y)$ with $x_1 \\le x \\le x_2$, $y_1 \\le y \\le y_2$ for some $1 \\le x_1 \\le x_2 \\le n$, $1 \\le y_1 \\le y_2 \\le m$}.\n\nAlice wants to obtain her favorite coloring with these operations. What's the smallest number of coins that she would have to spend? It can be shown that it's always possible to transform the initial grid into any other.",
    "tutorial": "Everything from the editorial of the first part of the problem stays the same, except one thing: now the second operation on the modified grid costs only $2$ coins. Sadly, now it's not true that it's not optimal to use the second operation more than once. Let's denote the second operation on $a$ by $op(x, y)$ (meaning that we invert numbers at $a[x][y], a[n][y], a[x][m], a[n][m]$). New claim is that it's not optimal to make operations which have the same $x$ or the same $y$. Indeed, suppose that we made $op(x, y_1)$ and $op(x, y_2)$. Then cells $a[x][m]$ and $a[n][m]$ haven't changed, so we only flipped $4$ cells with cost of $2\\times 2 = 4$ coins. We could have done this with operations of the first type. Another observation: it doesn't make sense to make $op(x, y)$, unless all the cells $a[x][y], a[x][m], a[n][y]$ are $1$. Indeed, no other operation of this type will affect any of these cells. If some cell here is $0$, and we still make $op(x, y)$ in $2$ coins, then we will have to spend one additional coin on reverting it back to $0$ with the operation of the first type. Instead, you could have just flipped $3$ other cells from $a[x][y], a[x][m], a[n][y], a[n][m]$ with the operations of the first type in the same $3$ coins. How many such operations can we make then? Let's build a bipartite graph, with parts of sizes $n-1$ and $m-1$, and connect node $x$ from the left part with node $y$ from the right part iff $a[x][y] = a[x][m] = a[n][y] = 1$. Find the maximum matching in this graph with your favorite algorithm (for example, in $O(mn\\sqrt{m+n})$ with Hopcroft-Karp), let its size be $K$. Then, for each $0 \\le k \\le K$, we can find the number of ones that will be left in the grid if we make exactly $k$ operations of the second type. Then the answer to the problem is just the minimum of $(ones\\_left+2k)$ over all $k$.",
    "tags": [
      "constructive algorithms",
      "flows",
      "graph matchings",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1593",
    "index": "A",
    "title": "Elections",
    "statement": "The elections in which three candidates participated have recently ended. The first candidate received $a$ votes, the second one received $b$ votes, the third one received $c$ votes. For each candidate, solve the following problem: how many votes should be added to this candidate so that he wins the election (i.e. the number of votes for this candidate was strictly greater than the number of votes for any other candidate)?\n\nPlease note that for each candidate it is necessary to solve this problem \\textbf{independently}, i.e. the added votes for any candidate \\textbf{do not} affect the calculations when getting the answer for the other two candidates.",
    "tutorial": "Let's solve the problem for the first candidate. To win the election, he needs to get at least $1$ more votes than every other candidate. Therefore, the first candidate needs to get at least $\\max(b, c) + 1$ votes. If $a$ is already greater than this value, then you don't need to add any votes, otherwise, you need to add $\\max(b, c) + 1 - a$ votes. So the answer for the first candidate is $\\max(0, \\max(b,c) + 1 - a)$. Similarly, the answer for the second candidate is $\\max(0, \\max(a, c) + 1 - b)$, and, for the third one, the answer is $\\max(0, \\max(a, b) + 1 - c)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint solveSingle(int best, int other1, int other2)\n{\n\treturn max(0, max(other1, other2) + 1 - best);\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tint a, b, c;\n\t\tcin >> a >> b >> c;\n\n\t\tcout << solveSingle(a, b, c) << ' ' << solveSingle(b, a, c) << ' ' << solveSingle(c, a, b) << '\\n';\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1593",
    "index": "B",
    "title": "Make it Divisible by 25",
    "statement": "It is given a positive integer $n$. In $1$ move, one can select any single digit and remove it (i.e. one selects some position in the number and removes the digit located at this position). The operation cannot be performed if only one digit remains. If the resulting number contains leading zeroes, they are automatically removed.\n\nE.g. if one removes from the number $32925$ the $3$-rd digit, the resulting number will be $3225$. If one removes from the number $20099050$ the first digit, the resulting number will be $99050$ (the $2$ zeroes going next to the first digit are automatically removed).\n\nWhat is the minimum number of steps to get a number such that it is divisible by $25$ and \\textbf{positive}? It is guaranteed that, for each $n$ occurring in the input, the answer exists. It is guaranteed that the number $n$ has no leading zeros.",
    "tutorial": "A number is divisible by $25$ if and only if its last two digits represent one of the following strings: \"00\", \"25\", \"50\", \"75\". Let's solve for each string the following subtask: what is the minimum number of characters to be deleted so that the string becomes a suffix of the number. Then, choosing the minimum of the answers for all subtasks, we solve the whole problem. Let's solve the subtask for a string \"X Y\" where 'X' and 'Y' are digits. We can do it using the following algorithm: let's delete the last digit of the number until it is equal to 'Y', then the second to last digit of the number until it is equal to 'X'. If it is not possible, then this subtask has no solution (i.e. its result will not affect the answer).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst string subseqs[] = { \"00\", \"25\", \"50\", \"75\" };\n\nconst int INF = 100;\n\nint solve(string& s, string& t)\n{\n\tint sptr = s.length() - 1;\n\n\tint ans = 0;\n\twhile (sptr >= 0 && s[sptr] != t[1])\n\t{\n\t\tsptr--;\n\t\tans++;\n\t}\n\n\tif (sptr < 0) return INF;\n\n\tsptr--;\n\n\twhile (sptr >= 0 && s[sptr] != t[0])\n\t{\n\t\tsptr--;\n\t\tans++;\n\t}\n\n\treturn sptr < 0 ? INF : ans;\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tstring n;\n\t\tcin >> n;\n\t\t\n\t\tint ans = INF;\n\t\tfor (auto e : subseqs)\n\t\t\tans = min(ans, solve(n, e));\n\n\t\tcout << ans << '\\n';\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1593",
    "index": "C",
    "title": "Save More Mice",
    "statement": "There are one cat, $k$ mice, and one hole on a coordinate line. The cat is located at the point $0$, the hole is located at the point $n$. All mice are located between the cat and the hole: the $i$-th mouse is located at the point $x_i$ ($0 < x_i < n$). At each point, many mice can be located.\n\nIn one second, the following happens. First, \\textbf{exactly one} mouse moves to the right by $1$. If the mouse reaches the hole, it hides (i.e. the mouse will not any more move to any point and will not be eaten by the cat). Then (\\textbf{after that} the mouse has finished its move) the cat moves to the right by $1$. If at the new cat's position, some mice are located, the cat eats them (they will not be able to move after that). The actions are performed until any mouse hasn't been hidden or isn't eaten.\n\nIn other words, the first move is made by a mouse. If the mouse has reached the hole, it's saved. Then the cat makes a move. The cat eats the mice located at the pointed the cat has reached (if the cat has reached the hole, it eats nobody).\n\nEach second, you can select a mouse that will make a move. What is the maximum number of mice that can reach the hole without being eaten?",
    "tutorial": "Let's solve the problem using a linear search. Let $m$ be the number of mice we are trying to save. Then it is more efficient to save $m$ mice such that they are the closest ones to the hole. Let $r_i$ be the distance from the $i$-th mouse to the hole ($r_i = n - x_i$). Denote $R := \\sum\\limits_{i = 1}^m r_i$. Let's prove that these mice will be saved if and only if $R < n$. The necessary condition. Suppose we can save the mice and $R \\ge n$. Since only one mouse can be moved in one second, the following will happen: $m - 1$ of mice will already be saved and one mouse will have to be saved. When it's been $q$ seconds, then the distance from the cat to the hole will be equal to $n - q$, and the distance from the mouse to the hole will be equal to $R - q$ (since all other mice are already in the hole, their distances to the hole are equal to $0$, so the sum of the distances from all mice to the hole at the current time is exactly equal to the distance to the hole from one remaining mouse). Since $R - q \\ge n - q$, the distance from the mouse to the hole is greater than or equal to the distance from the cat to the hole. But this cannot be, because both the mice and the cat move only to the right, and all mice met by the cat are eaten. So, $R < n$. Sufficient condition. Suppose $R < n$. If $R = 0$, then all the mice are already in the hole, i.e. they are saved. Suppose $R > 0$. Let's move any mouse, then the cat. Suppose the cat ate at least one of the mice. This mouse is definitely not the one that was moved. Then the distance from it to the eaten mouse was equal to $1$, i.e. the distance from it to the hole was equal to the distance from the eaten mouse to the hole plus $1$. The distance from the moved mouse to the hole was at least $1$. So, $R \\ge r_s + r_m$, where $r_s = n - 1$ is the distance from the eaten mouse to the hole, $r_m \\ge 1$ is the distance from the moved mouse to the hole. So, $R \\ge n - 1 + 1 = n$, but it's false. Therefore, none of the mice will be eaten on the first move. Then the distance from the cat to the hole will be equal to $n - 1$, the total distance from the mice to the hole will be equal to $R - 1$. $R - 1 < n - 1$, i.e. now we have to solve a similar problem for smaller $R$ and $n$. So $R$ will be gradually decreased to $0$, while no mouse will be eaten. So, if $R < n$, all the mice will be saved. Thus, to solve the problem, we need to find the maximum $m$ such that the sum of the distances from the $m$ nearest mice to the hole is less than $n$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tint n, k;\n\t\tcin >> n >> k;\n\n\t\tvector<int> x(k);\n\t\tfor (int i = 0; i < k; i++) cin >> x[i];\n\t\tsort(x.rbegin(), x.rend());\n\n\t\tint cnt = 0;\n\t\tlong long sum = 0;\n\n\t\twhile (cnt < x.size() && sum + n - x[cnt] < n)\n\t\t{\n\t\t\tsum += n - x[cnt++];\n\t\t}\n\n\t\tcout << cnt << '\\n';\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1593",
    "index": "D1",
    "title": "All are Same",
    "statement": "This problem is a simplified version of D2, but it has significant differences, so read the whole statement.\n\nPolycarp has an array of $n$ ($n$ is even) integers $a_1, a_2, \\dots, a_n$. Polycarp conceived of a positive integer $k$. After that, Polycarp began performing the following operations on the array: take an index $i$ ($1 \\le i \\le n$) and reduce the number $a_i$ by $k$.\n\nAfter Polycarp performed some (possibly zero) number of such operations, it turned out that \\textbf{all} numbers in the array became the same. Find the maximum $k$ at which such a situation is possible, or print $-1$ if such a number can be arbitrarily large.",
    "tutorial": "$k$ can be arbitrarily large if and only if all numbers in the array are the same. In this case, we can choose any number $k$ and subtract it from all the numbers, for example, exactly once. Suppose we fix some $k$. Let $q_i$ be the number of subtractions of the number $k$ from the number $a_i$. In this case, all numbers will be equal if and only if, for any two numbers $a_i$ and $a_j$ from the array, $a_i - k \\cdot q_i = a_j - k\\cdot q_j$. Let $q_{i_0}$ be the minimum of $q_i$. Then all numbers in the array become the same if for each index $i$ we subtract from $a_i$ $k$ not $q_i$, but $q_i - q_{i_0}$ times. Then we will never subtract $k$ from the element $a_{i_0}$. This means that there is always an element in the array from which we can never subtract $k$. This element is the minimum on the array. Then from $a_i$ we will subtract $k$ exactly $\\frac{a_i - a_{i_0}}{k}$ times. Thus, with the current $k$, it is possible to make all elements equal if and only if for all elements $a_i$ the value $a_i - a_{i_0}$ (where $a_{i_0}$ is the minimum on the array) is divisible by $k$. So, the maximum $k$ is the greatest common divisor of all values of $a_i - a_{i_0}$, $i = \\overline{1, n}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tint n;\n\t\tcin >> n;\n\n\t\tvector<int> a(n);\n\t\tfor (int i = 0; i < n; i++) cin >> a[i];\n\n\t\tbool inf = true;\n\t\tint minval = a[0];\n\n\t\tfor (int i = 1; i < n; i++)\n\t\t{\n\t\t\tif (a[i] != a[0])\n\t\t\t{\n\t\t\t\tinf = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tminval = min(minval, a[i]);\n\t\t}\n\n\t\tif (inf)\n\t\t{\n\t\t\tcout << \"-1\\n\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tsort(a.begin(), a.end());\n\n\t\tint ans = 0;\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tans = gcd(ans, a[i] - minval);\n\t\tcout << ans << '\\n';\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1593",
    "index": "D2",
    "title": "Half of Same",
    "statement": "This problem is a complicated version of D1, but it has significant differences, so read the whole statement.\n\nPolycarp has an array of $n$ ($n$ is even) integers $a_1, a_2, \\dots, a_n$. Polycarp conceived of a positive integer $k$. After that, Polycarp began performing the following operations on the array: take an index $i$ ($1 \\le i \\le n$) and reduce the number $a_i$ by $k$.\n\nAfter Polycarp performed some (possibly zero) number of such operations, it turned out that \\textbf{at least half} of the numbers in the array became the same. Find the maximum $k$ at which such a situation is possible, or print $-1$ if such a number can be arbitrarily large.",
    "tutorial": "$k$ can be arbitrarily large if and only if at least half of the numbers in the array are the same. In this case, we can choose any number $k$ and subtract it from all numbers, for example, exactly once. Let's iterate over the element $a_{i_0}$, it will be the minimum among the numbers that we want to make the same. Let's calculate the number of numbers in the array that are equal to this element. If this number is at least $\\frac{n}{2}$, then the answer is -1. Otherwise, we will iterate over numbers $a_i$ which are strictly greater than the selected minimum, and, for each number, we will iterate over the divisors of the number $a_i - a_{i_0}$. For each of the found divisors, let's calculate the number of $a_i$ for which this divisor was found. Among all such divisors for which the sum of the found number and the number of numbers equal to $a_{i_0}$ is greater than or equal to $\\frac{n}{2}$, we will choose the maximum one. The greatest found divisor will be the desired $k$. This solution works in $O(n^2\\times\\sqrt{A})$ (where $A$ is the absolute value of the maximum on the array).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nset<int> divs(int n) {  \n    set<int> d;\n    for (int dd = 1; dd * dd <= n; dd++)\n        if (n % dd == 0) {\n            d.insert(n / dd);\n            d.insert(dd);\n        }\n    return d;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        forn(i, n)\n            cin >> a[i];\n        int k = -1;\n\n        forn(i, n) {\n            int minv = a[i];\n            int same = 0;\n            vector<int> d;\n            forn(j, n) {\n                if (a[j] == minv)\n                    same++;\n                else if (a[j] > minv)\n                    d.push_back(a[j] - minv);\n            }\n            if (same >= n / 2) {\n                k = INT_MAX;\n                continue;\n            }\n            map<int,int> div_counts;\n            for (int di: d)\n                for (int dd: divs(di))\n                    div_counts[dd]++;\n            for (auto p: div_counts)\n                if (p.second >= n / 2 - same)\n                    k = max(k, p.first);\n        }\n\n        cout << (k == INT_MAX ? -1 : k) << endl;\n    }\n}\n",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1593",
    "index": "E",
    "title": "Gardener and Tree",
    "statement": "A tree is an undirected connected graph in which there are no cycles. This problem is about non-rooted trees. A leaf of a tree is a vertex that is connected to \\textbf{at most one} vertex.\n\nThe gardener Vitaly grew a tree from $n$ vertices. He decided to trim the tree. To do this, he performs a number of operations. In one operation, he removes \\textbf{all} leaves of the tree.\n\n\\begin{center}\n{\\small Example of a tree.}\n\\end{center}\n\nFor example, consider the tree shown in the figure above. The figure below shows the result of applying exactly one operation to the tree.\n\n\\begin{center}\n{\\small The result of applying the operation \"remove all leaves\" to the tree.}\n\\end{center}\n\nNote the special cases of the operation:\n\n- applying an operation to an empty tree (of $0$ vertices) does not change it;\n- applying an operation to a tree of one vertex removes this vertex (this vertex is treated as a leaf);\n- applying an operation to a tree of two vertices removes both vertices (both vertices are treated as leaves).\n\nVitaly applied $k$ operations sequentially to the tree. How many vertices remain?",
    "tutorial": "Let's create two arrays of length $n$. The element of the array $layer$ will contain the operation number at which the vertex which is the index of the array will be deleted. The $rem$ array will contain the number of neighbors of a given vertex at a certain time. This array must be initialized with the number of neighbors in the original tree. Initially, we will suppose that the gardener performs an infinite number of operations, and we will simply calculate for each vertex the number of the operation on which it will be deleted. Let's create a queue $q$, which will store the order of deleting vertices. The queue will contain only those vertices whose neighbors, except, maybe, one, have been removed (i.e. $rem[v] \\le 1$). Let's add all leaves of the original tree to it, for each of them let's store the value $1$ in the array $layer$ (because all original leaves will be removed during the first operation). Next, we will take sequentially one vertex from the queue and update the data about its neighbors. Consider the neighbors. Since we are deleting the current vertex, we need to update $rem$ of its neighbors. If the neighbor's $rem$ is equal to $1$, then it's already in the queue and it doesn't need to be considered right now. Otherwise, we will decrease the neighbor's $rem$ by $1$. If it becomes equal to $1$, then the neighbor must be added to the queue. The number of the operation during which the neighbor will be deleted is equal to the number of the operation during which the current vertex will be deleted plus $1$. After we calculate the numbers of operations for all vertices, we need to select among them those that will not be deleted during operations with numbers $1, 2, \\dots, k$. Thus, the answer is the number of vertices $v$ such that $layer[v] > k$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tint n, k;\n\t\tcin >> n >> k;\n\n\t\tvector<vector<int>> g(n, vector<int>());\n\t\tvector<int> rem(n, 0);\n\t\tvector<int> layer(n, 0);\n\n\t\tfor (int i = 1; i < n; i++)\n\t\t{\n\t\t\tint x, y;\n\t\t\tcin >> x >> y;\n\t\t\tx--;\n\t\t\ty--;\n\t\t\tg[x].push_back(y);\n\t\t\tg[y].push_back(x);\n\t\t\trem[x]++;\n\t\t\trem[y]++;\n\t\t}\n\n\t\tqueue<int> q;\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tif (rem[i] == 1)\n\t\t\t{\n\t\t\t\tq.push(i);\n\t\t\t\tlayer[i] = 1;\n\t\t\t}\n\n\t\twhile (!q.empty())\n\t\t{\n\t\t\tint u = q.front();\n\t\t\tq.pop();\n\n\t\t\tfor (int v : g[u])\n\t\t\t{\n\t\t\t\tif (rem[v] != 1)\n\t\t\t\t{\n\t\t\t\t\trem[v]--;\n\t\t\t\t\tif (rem[v] == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tlayer[v] = layer[u] + 1;\n\t\t\t\t\t\tq.push(v);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint ans = 0;\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tif (layer[i] > k)\n\t\t\t\tans++;\n\n\t\tcout << ans << '\\n';\n\t}\n\n\treturn 0;\n}\n\n",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1593",
    "index": "F",
    "title": "Red-Black Number",
    "statement": "It is given a non-negative integer $x$, the decimal representation of which contains $n$ digits. You need to color \\textbf{each} its digit in red or black, so that the number formed by the red digits is divisible by $A$, and the number formed by the black digits is divisible by $B$.\n\n\\textbf{At least one} digit must be colored in each of two colors. Consider, the count of digits colored in red is $r$ and the count of digits colored in black is $b$. Among all possible colorings of the given number $x$, you need to output any such that the value of $|r - b|$ is \\textbf{the minimum possible}.\n\nNote that the number $x$ and the numbers formed by digits of each color, \\textbf{may contain leading zeros}.\n\n\\begin{center}\n{\\small Example of painting a number for $A = 3$ and $B = 13$}\n\\end{center}\n\nThe figure above shows an example of painting the number $x = 02165$ of $n = 5$ digits for $A = 3$ and $B = 13$. The red digits form the number $015$, which is divisible by $3$, and the black ones — $26$, which is divisible by $13$. Note that the absolute value of the difference between the counts of red and black digits is $1$, it is impossible to achieve a smaller value.",
    "tutorial": "The number $x$ is divisible by the number $y$ if and only if $x \\equiv 0$ modulo $y$. To solve this problem, let's use the concept of dynamic programming. There will be four states: the number of considered digits of the number $x$, the number of such considered digits that we have colored red, the remainder from dividing the red number by $A$ and the black one by $B$. The value corresponding to the state will be described by three parameters: the possibility of a situation described by the states, the color of the last digit, and the parent state. Let's assume that the number that contains $0$ digits is equal to $0$. Initially, let's mark the state in which $0$ digits are considered, of which $0$ are red digits, and both remainders are equal to $0$, as possible. Next, let's iterate over all states in the following order: first by the number of considered digits, then by the number of considered red digits, then by the remainder of the division by $A$ and by $B$. From the current state, if it is possible (i.e. the corresponding mark is set), you can make two transitions to new states. At the first transition, we paint the last digit in red, at the second one in black. We need also to store the current state in the new states as the previous one. A solution exists if and only if some state in which exactly $n$ digits are considered, of which at least $1$ and at most $n - 1$ red digits, and the remainders are equal to $0$, is marked as possible. Let's find such a state. Using the stored information about the color of the last digit and the previous state, we can restore the colors of all digits of the number $x$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX_N = 64;\n\nbool dp[MAX_N][MAX_N][MAX_N][MAX_N]; // (taken, red, mod A, mod B) -> may be\npair<bool, int> sert[MAX_N][MAX_N][MAX_N][MAX_N]; // the same -> (true (red) | false(black), prev red/black)\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\n\twhile (t--)\n\t{\n\t\tint n, a, b;\n\t\tstring x;\n\t\tcin >> n >> a >> b >> x;\n\n\t\tfor (int i = 0; i <= n; i++)\n\t\t\tfor (int j = 0; j <= n; j++)\n\t\t\t\tfor (int k = 0; k < a; k++)\n\t\t\t\t\tfor (int l = 0; l < b; l++)\n\t\t\t\t\t\tdp[i][j][k][l] = false;\n\n\t\tdp[0][0][0][0] = true;\n\n\t\tfor(int taken = 0; taken < n; taken++)\n\t\t\tfor(int red = 0; red <= taken; red++)\n\t\t\t\tfor(int remA = 0; remA < a; remA++)\n\t\t\t\t\tfor(int remB = 0; remB < b; remB++)\n\t\t\t\t\t\tif (dp[taken][red][remA][remB])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// red transition\n\t\t\t\t\t\t\tdp[taken + 1][red + 1][(remA * 10 + (x[taken] - '0')) % a][remB] = true;\n\t\t\t\t\t\t\tsert[taken + 1][red + 1][(remA * 10 + (x[taken] - '0')) % a][remB] = { true, remA };\n\n\t\t\t\t\t\t\t// black transition\n\t\t\t\t\t\t\tdp[taken + 1][red][remA][(remB * 10 + (x[taken] - '0')) % b] = true;\n\t\t\t\t\t\t\tsert[taken + 1][red][remA][(remB * 10 + (x[taken] - '0')) % b] = { false, remB };\n\t\t\t\t\t\t}\n\n\t\tint bestRed = 0;\n\n\t\tfor (int red = 1; red < n; red++)\n\t\t\tif (dp[n][red][0][0] && abs(red - (n - red)) < abs(bestRed - (n - bestRed)))\n\t\t\t\tbestRed = red;\n\n\t\tif (bestRed == 0)\n\t\t{\n\t\t\tcout << \"-1\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint taken = n;\n\t\t\tint red = bestRed;\n\t\t\tint remA = 0;\n\t\t\tint remB = 0;\n\t\t\tstring ans = \"\";\n\t\t\t\n\t\t\twhile (taken > 0)\n\t\t\t{\n\t\t\t\tauto way = sert[taken][red][remA][remB];\n\t\t\t\tif (way.first)\n\t\t\t\t{\n\t\t\t\t\tred--;\n\t\t\t\t\tremA = way.second;\n\t\t\t\t\tans.push_back('R');\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tremB = way.second;\n\t\t\t\t\tans.push_back('B');\n\t\t\t\t}\n\t\t\t\ttaken--;\n\t\t\t}\n\n\t\t\treverse(ans.begin(), ans.end());\n\t\t\tcout << ans << '\\n';\n\t\t}\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "implementation",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1593",
    "index": "G",
    "title": "Changing Brackets",
    "statement": "A sequence of round and square brackets is given. You can change the sequence by performing the following operations:\n\n- change the direction of a bracket from opening to closing and vice versa without changing the form of the bracket: i.e. you can change '(' to ')' and ')' to '('; you can change '[' to ']' and ']' to '['. The operation costs $0$ burles.\n- change any \\textbf{square} bracket to \\textbf{round} bracket having the same direction: i.e. you can change '[' to '(' but \\textbf{not} from '(' to '['; similarly, you can change ']' to ')' but \\textbf{not} from ')' to ']'. The operation costs $1$ burle.\n\nThe operations can be performed in any order any number of times.\n\nYou are given a string $s$ of the length $n$ and $q$ queries of the type \"l r\" where $1 \\le l < r \\le n$. For every substring $s[l \\dots r]$, find the minimum cost to pay to make it a correct bracket sequence. It is guaranteed that the substring $s[l \\dots r]$ has an even length.\n\nThe queries must be processed independently, i.e. the changes made in the string for the answer to a question $i$ don't affect the queries $j$ ($j > i$). In other words, for every query, the substring $s[l \\dots r]$ is given from the initially given string $s$.\n\nA correct bracket sequence is a sequence that can be built according the following rules:\n\n- an empty sequence is a correct bracket sequence;\n- if \"s\" is a correct bracket sequence, the sequences \"(s)\" and \"[s]\" are correct bracket sequences.\n- if \"s\" and \"t\" are correct bracket sequences, the sequence \"st\" (the concatenation of the sequences) is a correct bracket sequence.\n\nE.g. the sequences \"\", \"(()[])\", \"[()()]()\" and \"(())()\" are correct bracket sequences whereas \"(\", \"[(])\" and \")))\" are not.",
    "tutorial": "Consider a substring $t = s[l \\dots r]$. Let's call square brackets located in odd positions in the substring odd brackets, and square brackets located in even positions even brackets. Let $cnt_{odd}$ be the number of odd brackets, $cnt_{even}$ be the number of even brackets, $cnt_{all} = cnt_{odd} + cnt_{even}$ be the number of all square brackets. Let's prove that the string $t$ can be turned into a correct bracket sequence for $0$ burles if and only if $cnt_{odd} = cnt_{even}$. Let's prove the necessary condition. Suppose the initial substring has been turned into a correct bracket sequence. Since we have paid $0$ burles, there's no bracket which form has been changed. Therefore, $cnt_{odd}$ for the new sequence is the same as $cnt_{odd}$ for the initial sequence, the similar situation happens with $cnt_{even}$. Let's say that two square brackets form a pair if the left one is an opening bracket and the right one is a closing bracket and the substring between them is a correct bracket sequence. A pair can be formed only by one odd bracket and one even bracket because between them is placed an even number of brackets (since it's a correct bracket sequence) so the difference between their indices is odd. In a correct bracket sequence, each square bracket has a pairwise bracket. Therefore, a correct bracket sequence contains $\\frac{cnt_{all}}{2}$ pairs of brackets so $cnt_{odd} = cnt_{even} = \\frac{cnt_{all}}{2}$. Let's prove the sufficient condition. Suppose the initial substring contains equal numbers of odd and even brackets. Let's prove by induction that the substring may be turned into a correct bracket sequence for $0$ burles. Suppose $cnt_{odd} = cnt_{even} = 0$. So the initial substring contains only round brackets. Let's make the first $\\frac{r - l + 1}{2}$ brackets opening and the other brackets closing. The resulting sequence is a correct bracket sequence whereas we haven't changed the form of any bracket so the cost is equal to $0$. A correct bracket sequence has two important properties: after deleting its substring being a correct bracket sequence, the resulting string is a correct bracket sequence; after inserting at any place any correct bracket sequence, the resulting string is a correct bracket sequence. These properties can be applied to an incorrect bracket sequence, too: after deleting a substring being a correct bracket subsequence from an incorrect bracket sequence or inserting a correct bracket sequence into an incorrect one, the resulting sequence is an incorrect bracket sequence. Consider a substring $t$ such that $cnt_{odd} = cnt_{even} > 0$. Suppose we have proved before that each substring $t$ having $cnt_{odd} = cnt_{even}$ decreased by $1$ can be turned into a correct bracket sequence for $0$ burles. Let's find two square brackets such that one of them is odd and another one is even and there are no square brackets between them. There's an even number of round brackets between them that can be turned into a correct bracket sequence for $0$ burles. Let's make the left found bracket opening and the right one closing. Then the substring starting at the left found bracket and ending at the right found bracket is a correct bracket sequence. Let's remove it from $t$. The resulting string contains $cnt_{odd} - 1$ odd brackets and $cnt_{even} - 1$ even brackets so, by the assumption of induction, it can be turned into a correct bracket sequence for $0$ burles. Let's do it and then insert the removed string into its place. Since we insert a correct bracket sequence into a correct bracket sequence, the resulting string is a correct bracket sequence. Actually, the operations of inserting and removing are not allowed, they have been used for clarity, the string can be turned into a correct bracket sequence without these operations as follows: let's turn the substring we have removed into a correct bracket sequence (as it was described above), then change the other brackets of the string the same way as it was done with the string that was the result after removing. The resulting string is a correct bracket sequence. Therefore, the illegal operations of inserting and removing are not necessary, all other operations cost $0$ burles so the substring $t$ can be turned into a correct bracket sequence for $0$ burles. Therefore, to turn a substring into a correct bracket sequence, we need to get a sequence such that $cnt_{odd} = cnt_{even}$. Suppose, initiallly, $cnt_{odd} > cnt_{even}$. Let's pay $cnt_{odd} - cnt_{even}$ burles to replace $cnt_{odd} - cnt_{even}$ odd brackets with round brackets. If $cnt_{odd} < cnt_{even}$, let's replace $cnt_{even} - cnt_{odd}$ even brackets with round brackets. Anyway, we must pay $|cnt_{odd} - cnt_{even}|$ burles. We cannot pay less than this value because for a correct bracket sequence, $cnt_{odd} = cnt_{even}$. But there's no need to pay more than this value, because, if we turn the initial substring into a sequence with $cnt_{odd} = cnt_{even}$, we can turn it into a correct bracket sequence for free. Therfore, the answer for a given question is $|cnt_{odd} - cnt_{even}|$. Since we must answer the queries fast, let's use a concept of prefix sums. If the given string $s$ contains $n$ brackets, let's create arrays $psumOdd$ and $psumEven$ with the length $n + 1$. $psumOdd[i]$ will contain the number of odd brackets on the prefix of the string $s$ with the length $i$, $psumEven[i]$ - the same value for even brackets. Let's initialize $psumOdd[0] = psumEven[0] = 0$ and then iterate $i$ from $1$ to $n$. Let's initialize $psumOdd[i] = psumOdd[i - 1]$ and $psumEven[i] = psumEven[i - 1]$. If the $i$-th bracket is round, then the current values are correct. Otherwise, let's find out what bracket is it. If $i$ is odd, the bracket is odd so we must increase $psumOdd[i]$ by $1$. If $i$ is even, the bracket is even so we must increase $psumEven[i]$ by $1$. To get the answer for a current $l$ and $r$, let's calculate $cnt_{odd}$ and $cnt_{even}$. $cnt_{odd}$ is a number of odd brackets that belong to the prefix with the length $r$ but not to the prefix with the length $l - 1$ so $cnt_{odd} = psumOdd[r] - psumOdd[l - 1]$. Similarly, $cnt_{even} = psumEven[r] - psumEven[l - 1]$. The remaining thing is to output $|cnt_{odd} - cnt_{even}|$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX_N = 1'000'000;\n\nint psumOdd[MAX_N + 1];\nint psumEven[MAX_N + 1];\n\nvoid solve()\n{\n\tstring s;\n\tint q;\n\tcin >> s >> q;\n\tint n = s.length();\n\n\tpsumOdd[0] = psumEven[0] = 0;\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tpsumOdd[i + 1] = psumOdd[i];\n\t\tpsumEven[i + 1] = psumEven[i];\n\n\t\tif (s[i] == '[' || s[i] == ']')\n\t\t{\n\t\t\tif (i & 1)\n\t\t\t\tpsumOdd[i + 1]++;\n\t\t\telse\n\t\t\t\tpsumEven[i + 1]++;\n\t\t}\n\t}\n\n\twhile (q--)\n\t{\n\t\tint l, r;\n\t\tcin >> l >> r;\n\t\tl--;\n\t\tint odd = psumOdd[r] - psumOdd[l];\n\t\tint even = psumEven[r] - psumEven[l];\n\t\tcout << abs(odd - even) << '\\n';\n\t}\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1594",
    "index": "A",
    "title": "Consecutive Sum Riddle",
    "statement": "Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).\n\nYou are given an integer $n$. You need to find two integers $l$ and $r$ such that $-10^{18} \\le l < r \\le 10^{18}$ and $l + (l + 1) + \\ldots + (r - 1) + r = n$.",
    "tutorial": "You can take $(-n + 1) + (-n + 2) + \\ldots + (n - 1) + n$, so the sum will be $n$. Thus, $l = -n + 1$ and $r = n$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nint main(void){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--){\n        ll n;\n        cin>>n;\n        cout<<-n+1<<\" \"<<n<<endl;\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1594",
    "index": "B",
    "title": "Special Numbers",
    "statement": "Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.\n\nLet's call a positive number special if it can be written as a sum of \\textbf{different} non-negative powers of $n$. For example, for $n = 4$ number $17$ is special, because it can be written as $4^0 + 4^2 = 1 + 16 = 17$, but $9$ is not.\n\nTheofanis asks you to help him find the $k$-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo $10^9+7$.",
    "tutorial": "The problem is the same as finding the $k$-th number that in base $n$ has only zeros and ones. So you can write $k$ in binary system and instead of powers of $2$ add powers of $n$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll INF = 1e9+7;\nconst ll MOD = 998244353;\ntypedef pair<ll,ll> ii;\n#define iii pair<ll,ii>\n#define f(i,a,b) for(ll i = a;i < b;i++)\n#define pb push_back\n#define vll vector<ll>\n#define F first\n#define S second\n#define all(x) (x).begin(), (x).end()\nint main(void){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--){\n        ll n,k;\n        cin>>n>>k;\n        ll p = 1;\n        ll ans = 0;\n        f(j,0,31){\n            if(k & (1<<j)){\n                ans = (ans + p) % INF;\n            }\n            p *= n;\n            p %= INF;\n        }\n        cout<<ans<<\"\\n\";\n    }\n}",
    "tags": [
      "bitmasks",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1594",
    "index": "C",
    "title": "Make Them Equal",
    "statement": "Theofanis has a string $s_1 s_2 \\dots s_n$ and a character $c$. He wants to make all characters of the string equal to $c$ using the minimum number of operations.\n\nIn one operation he can choose a number $x$ ($1 \\le x \\le n$) and \\textbf{for every position $i$}, where $i$ is \\textbf{not} divisible by $x$, replace $s_i$ with $c$.\n\nFind the minimum number of operations required to make all the characters equal to $c$ and the $x$-s that he should use in his operations.",
    "tutorial": "If the whole string is equal to $c$ then you don't need to make any operations. In order to find if it is possible with exactly $1$ operation, we can pass through every $x$ and count all the letters $c$ that are divisible by $x$. This takes $O(|s| log |s|)$ time complexity. If for some $x$ all its multiples are $c$ then the answer is $1$ operation with that $x$. If all the above conditions don't hold you can always make $2$ operations and make all the elements equal. One possible way is with $x = |s|$ and $x = |s|-1$. After the first operation only the last element of $s$ is not $c$ thus if we use $x = |s|-1$ since $gcd(|s|,|s|-1) = 1$ then $|s|$ is not divisible by $|s|-1$ and it will become equal to $c$. Time complexity: $O(|s| log |s|)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll INF = 1e9+7;\nconst ll MOD = 998244353;\ntypedef pair<ll,ll> ii;\n#define iii pair<ll,ii>\n#define f(i,a,b) for(int i = a;i < b;i++)\n#define pb push_back\n#define vll vector<ll>\n#define F first\n#define S second\n#define all(x) (x).begin(), (x).end()\nint main(void){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--){\n        ll n;\n        cin>>n;\n        char c;\n        cin>>c;\n        string s;\n        cin>>s;\n        vector<int>ans;\n        bool ok = true;\n        for(auto x:s){\n            if(x != c){\n                ok = false;\n            }\n        }\n        if(!ok){\n            f(i,1,n+1){\n                ok = true;\n                f(j,i,n+1){\n                    ok &= (s[j-1] == c);\n                    j += i-1;\n                }\n                if(ok){\n                    ans.pb(i);\n                    break;\n                }\n            }\n            if(!ok){\n                ans.pb(n);\n                ans.pb(n-1);\n            }\n        }\n        cout<<ans.size()<<\"\\n\";\n        for(auto x:ans){\n            cout<<x<<\" \";\n        }\n        cout<<\"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1594",
    "index": "D",
    "title": "The Number of Imposters",
    "statement": "Theofanis started playing the new online game called \"Among them\". However, he always plays with Cypriot players, and they all have the same name: \"Andreas\" (the most common name in Cyprus).\n\nIn each game, Theofanis plays with $n$ other players. Since they all have the same name, they are numbered from $1$ to $n$.\n\nThe players write $m$ comments in the chat. A comment has the structure of \"$i$ $j$ $c$\" where $i$ and $j$ are two distinct integers and $c$ is a string ($1 \\le i, j \\le n$; $i \\neq j$; $c$ is either imposter or crewmate). The comment means that player $i$ said that player $j$ has the role $c$.\n\nAn imposter always lies, and a crewmate always tells the truth.\n\nHelp Theofanis find the maximum possible number of imposters among all the other Cypriot players, or determine that the comments contradict each other (see the notes for further explanation).\n\nNote that each player has exactly \\textbf{one} role: either imposter or crewmate.",
    "tutorial": "If person $A$ said in a comment that person $B$ is a $crewmate$ then $A$ and $B$ belong to the same team (either imposters or crewmates). If person $A$ said in a comment that person $B$ is an $imposter$ then $A$ and $B$ belong to different teams. Solution $1$: You can build a graph and check if all its components are bipartite. If person $A$ said that $B$ is an imposter then we add an edge from $A$ to $B$. If person $A$ said that $B$ is a crewmate then we add an edge from $A$ to a fake node and from the same fake node to $B$. For each component, we check if it's bipartite and take the maximum from the two colours. If a component is not bipartite then the answer is $-1$. Solution $2$: We can build the graph in the other way: If $A$ and $B$ are in the same team then we add edge with weight $0$, otherwise with weight $1$. Then you can use dfs and colour the nodes either $0$ or $1$ maintaining the property that $u \\oplus v = w(u, v)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll INF = 1e9+7;\nconst ll MOD = 998244353;\ntypedef pair<ll,ll> ii;\n#define iii pair<ll,ii>\n#define f(i,a,b) for(int i = a;i < b;i++)\n#define pb push_back\n#define vll vector<ll>\n#define F first\n#define S second\n#define all(x) (x).begin(), (x).end()\nvector<vector<ii> >adj;\nint c[2];\nint colour[200005];\nbool ok;\nvoid dfs(int idx){\n    c[colour[idx]]++;\n    for(auto x:adj[idx]){\n        if(colour[x.F] == -1){\n            colour[x.F] = colour[idx] ^ x.S;\n            dfs(x.F);\n        }\n        else if(colour[x.F] != (colour[idx] ^ x.S)){\n            ///impossible\n            ok = false;\n        }\n    }\n}\nint main(void){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--){\n        int n,m;\n        cin>>n>>m;\n        adj.assign(n+5,vector<ii>());\n        f(i,0,n+5){\n            colour[i] = -1;\n        }\n        f(i,0,m){\n            int a,b;\n            string c;\n            cin>>a>>b>>c;\n            if(c == \"crewmate\"){\n                ///same team\n                adj[a].pb(ii(b,0));\n                adj[b].pb(ii(a,0));\n            }\n            else{\n                ///different team\n                adj[a].pb(ii(b,1));\n                adj[b].pb(ii(a,1));\n            }\n        }\n        int ans = 0;\n        ok = true;\n        f(i,1,n+1){\n            if(colour[i] == -1){\n                colour[i] = 0;\n                c[0] = c[1] = 0;\n                dfs(i);\n                ans += max(c[0],c[1]);\n            }\n        }\n        if(!ok){\n            ans = -1;\n        }\n        cout<<ans<<\"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "dsu",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1594",
    "index": "E1",
    "title": "Rubik's Cube Coloring (easy version)",
    "statement": "\\textbf{It is the easy version of the problem. The difference is that in this version, there are no nodes with already chosen colors.}\n\nTheofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?\n\nYou have a perfect binary tree of $2^k - 1$ nodes — a binary tree where all vertices $i$ from $1$ to $2^{k - 1} - 1$ have exactly two children: vertices $2i$ and $2i + 1$. Vertices from $2^{k - 1}$ to $2^k - 1$ don't have any children. You want to color its vertices with the $6$ Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).\n\nLet's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube.\n\n\\begin{center}\n\\begin{tabular}{cc}\n& \\\n\\end{tabular}\n\n{\\small A picture of Rubik's cube and its 2D map.}\n\\end{center}\n\nMore formally:\n\n- a white node can \\textbf{not} be neighboring with white and yellow nodes;\n- a yellow node can \\textbf{not} be neighboring with white and yellow nodes;\n- a green node can \\textbf{not} be neighboring with green and blue nodes;\n- a blue node can \\textbf{not} be neighboring with green and blue nodes;\n- a red node can \\textbf{not} be neighboring with red and orange nodes;\n- an orange node can \\textbf{not} be neighboring with red and orange nodes;\n\nYou want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.\n\nThe answer may be too large, so output the answer modulo $10^9+7$.",
    "tutorial": "You have $6$ choices for the first node and $4$ for each other node. Thus, the answer is $6 \\cdot 4 ^{2 ^ k - 2}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll INF = 1e9+7;\nconst ll MOD = 998244353;\ntypedef pair<ll,ll> ii;\n#define iii pair<ii,ll>\n#define f(i,a,b) for(ll i = a;i < b;i++)\n#define pb push_back\n#define vll vector<ll>\n#define F first\n#define S second\n#define all(x) (x).begin(), (x).end()\nll power(ll a,ll b,ll mod){\n    if(b == 0){\n        return 1;\n    }\n    ll ans = power(a,b/2,mod);\n    ans *= ans;\n    ans %= mod;\n    if(b % 2){\n        ans *= a;\n    }\n    return ans % mod;\n}\nint main(void){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    ll k;\n    cin>>k;\n    ll othernodes = (1LL<<k) - 2;\n    ll ans = power(4,othernodes,INF);\n    ans *= 6;\n    ans %= INF;\n    cout<<ans<<\"\\n\";\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1594",
    "index": "E2",
    "title": "Rubik's Cube Coloring (hard version)",
    "statement": "\\textbf{It is the hard version of the problem. The difference is that in this version, there are nodes with already chosen colors.}\n\nTheofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?\n\nYou have a perfect binary tree of $2^k - 1$ nodes — a binary tree where all vertices $i$ from $1$ to $2^{k - 1} - 1$ have exactly two children: vertices $2i$ and $2i + 1$. Vertices from $2^{k - 1}$ to $2^k - 1$ don't have any children. You want to color its vertices with the $6$ Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).\n\nLet's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube.\n\n\\begin{center}\n\\begin{tabular}{cc}\n& \\\n\\end{tabular}\n\n{\\small A picture of Rubik's cube and its 2D map.}\n\\end{center}\n\nMore formally:\n\n- a white node can \\textbf{not} be neighboring with white and yellow nodes;\n- a yellow node can \\textbf{not} be neighboring with white and yellow nodes;\n- a green node can \\textbf{not} be neighboring with green and blue nodes;\n- a blue node can \\textbf{not} be neighboring with green and blue nodes;\n- a red node can \\textbf{not} be neighboring with red and orange nodes;\n- an orange node can \\textbf{not} be neighboring with red and orange nodes;\n\nHowever, there are $n$ special nodes in the tree, colors of which are already chosen.\n\nYou want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.\n\nThe answer may be too large, so output the answer modulo $10^9+7$.",
    "tutorial": "Let's define a node as marked if it has a predefined node in its subtree. There is always at least $1$ marked node since all predefined nodes are definitely marked. You can see that marked nodes form a path for the root to any predefined node. Thus there are at most $n \\cdot k$ marked nodes and we can run a standard $dp[i][j]$ on them (node $i$ is colored with $j$). Depending on the implementation the $dp$ can have time complexity $O(n \\cdot k \\cdot 6 \\cdot 4)$ or $O(n \\cdot k \\cdot log(n \\cdot k) \\cdot 6 \\cdot 4)$ if you use map. You multiply the result with $4^{m}$ where $m$ is the number of unmarked nodes. This holds because if their parent has a fixed color they always have $4$ choices and so on.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll INF = 1e9+7;\nconst ll MOD = 998244353;\ntypedef pair<ll,ll> ii;\n#define iii pair<ii,ll>\n#define f(i,a,b) for(ll i = a;i < b;i++)\n#define pb push_back\n#define vll vector<ll>\n#define F first\n#define S second\n#define all(x) (x).begin(), (x).end()\nll dp[(60 * 10000) + 5][6];\nvll color[6];\nvector<vector<int> >adj;\nmap<ll,int>label;\nll c[(60 * 10000) + 5];\nll solve(int i,int j){\n    if(c[i] != -1 && c[i] != j){\n        return 0;\n    }\n    if(dp[i][j] != -1){\n        return dp[i][j];\n    }\n    ll ans = 0;\n    ll sum[2] = {0};\n    for(auto x:color[j]){\n        f(j,0,adj[i].size()){\n            sum[j] += solve(adj[i][j],x);\n            sum[j] %= INF;\n        }\n    }\n    if(adj[i].empty()){\n        sum[0] = sum[1] = 1;\n    }\n    if((ll)adj[i].size() == 1){\n        sum[1] = 1;\n    }\n    ans = (sum[0] * sum[1]) % INF;\n    return dp[i][j] = ans;\n}\nll power(ll a,ll b,ll mod){\n    if(b == 0){\n        return 1;\n    }\n    ll ans = power(a,b/2,mod);\n    ans *= ans;\n    ans %= mod;\n    if(b % 2){\n        ans *= a;\n    }\n    return ans % mod;\n}\nint main(void){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    color[0] = {1,2,4,5};\n    color[1] = {0,2,3,5};\n    color[2] = {0,1,3,4};\n    color[3] = {1,2,4,5};\n    color[4] = {0,2,3,5};\n    color[5] = {0,1,3,4};\n    map<string,ll>mp;\n    mp[\"white\"] = 0;\n    mp[\"blue\"] = 1;\n    mp[\"red\"] = 2;\n    mp[\"yellow\"] = 3;\n    mp[\"green\"] = 4;\n    mp[\"orange\"] = 5;\n    memset(dp,-1,sizeof dp);\n    memset(c,-1,sizeof c);\n    ll k;\n    cin>>k;\n    ll n;\n    cin>>n;\n    ll posoi = (1LL<<k) - 1;\n    int lab = 0;\n    map<ll,int>ar;\n    f(i,0,n){\n        ll x;\n        cin>>x;\n        string s;\n        cin>>s;\n        ar[x] = mp[s];\n        ll cur = x;\n        while(cur >= 1 && !label.count(cur)){\n            label[cur] = lab;\n            lab++;\n            posoi--;\n            cur /= 2;\n        }\n    }\n    adj.assign(lab + 5,vector<int>());\n    for(auto x:label){\n        if(ar.count(x.F)){\n            c[x.S] = ar[x.F];\n        }\n        if(label.count(x.F * 2)){\n            adj[x.S].pb(label[x.F * 2]);\n        }\n        if(label.count(x.F * 2 + 1)){\n            adj[x.S].pb(label[x.F * 2 + 1]);\n        }\n    }\n    ll ans = power(4,posoi,INF);\n    ll sum = 0;\n    f(j,0,6){\n        sum += solve(label[1],j);\n        sum %= INF;\n    }\n    ans *= sum;\n    ans %= INF;\n    cout<<ans<<\"\\n\";\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1594",
    "index": "F",
    "title": "Ideal Farm",
    "statement": "Theofanis decided to visit his uncle's farm. There are $s$ animals and $n$ animal pens on the farm. For utility purpose, animal pens are constructed in one row.\n\nUncle told Theofanis that a farm is lucky if you can distribute all animals in all pens in such a way that there are no empty pens and there is at least one continuous segment of pens that has exactly $k$ animals in total.\n\nMoreover, a farm is ideal if it's lucky for any distribution without empty pens.\n\nNeither Theofanis nor his uncle knows if their farm is ideal or not. Can you help them to figure it out?",
    "tutorial": "The problem is the same as: We have an array $a$ of length $n$ where every element of it is a positive integer and the sum of the whole array is $s$. If no matter how we construct the array $a$, we can find a non-zero length subarray which has sum equal to $k$ print \"YES\" else print \"NO\". If $s = k$ then the answer is obviously \"YES\" and if $s < k$ then the answer is obviously \"NO\". Let $pre[i] = \\sum_{j=1}^{j<=i} a[j]$ ($1$ - indexed) All the elements of array pre are different as all $a[i]$ are positive integers. Let $b[i] = pre[i] + k$ but we also have $b[0] = k$. Again all the elements of $b$ are different because all $a[i]$ are positive integers. Array $pre$ has size $n$ and array $b$ has size $n + 1$. If and only if an element from $pre$ is equal to an element from $b$ then it means that $pre[i] = pre[j] + k$ or $pre[i] = k$. If it is the second case then obviously there is a subarray with sum equal to $k$. If it's the first case then $pre[i] - pre[j] = k$ so the subarray $[j+1, i]$ has sum $k$. But when do we have an equation in these two arrays? There are $n + (n + 1) = 2n + 1$ elements and they can be values from $1$ to $s+k$. If the maximum number of distinct elements that we can take is less than $2n + 1$ the answer is \"YES\" else the answer is \"NO\". Let $m$ be the maximum number of elements that we can take. We go through the last k elements ($[s-k+1,s]$) and we count the number of elements that have the same modulo $k$. For each element in this range, if there are odd elements that have the same modulo, we can't take all of them because for every element $x$ that we add in $pre$ that we also add $x+k$ to $b$. Thus one element would have a $x+k$ out of range. Therefore we count all the elements that have odd elements with the same modulo $k$ and subtract them from $s+k$ to find $m$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll INF = 1e9+7;\nll MOD = 998244353;\ntypedef pair<ll,ll> ii;\n#define iii pair<ii,ll>\n#define f(i,a,b) for(int i = a;i < b;i++)\n#define pb push_back\n#define vll vector<ll>\n#define F first\n#define S second\n#define all(x) (x).begin(), (x).end()\nint main(void){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--){\n        ll n,k,s;\n        cin>>s>>n>>k;\n        if(s == k){\n            cout<<\"YES\\n\";\n        }\n        else if(k > s){\n            cout<<\"NO\\n\";\n        }\n        else{\n            ll posa = s+k;\n            ll l = s-k+1,r = s;\n            ll siz = r - l + 1;\n            ll a = 0,b = 0;\n            ll num = (s / k) * k;\n            b = r - num + 1;\n            a = siz - b;\n            if((s / k) % 2 == 1){\n                posa -= b;\n            }\n            else{\n                posa -= a;\n            }\n            if((2 * n + 1) > posa){\n                cout<<\"YES\\n\";\n            }\n            else{\n                cout<<\"NO\\n\";\n            }\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1598",
    "index": "A",
    "title": "Computer Game",
    "statement": "Monocarp is playing a computer game. Now he wants to complete the first level of this game.\n\nA level is a rectangular grid of $2$ rows and $n$ columns. Monocarp controls a character, which starts in cell $(1, 1)$ — at the intersection of the $1$-st row and the $1$-st column.\n\nMonocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $(x_1, y_1)$ to cell $(x_2, y_2)$ in one step if $|x_1 - x_2| \\le 1$ and $|y_1 - y_2| \\le 1$. Obviously, it is prohibited to go outside the grid.\n\nThere are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.\n\nTo complete a level, Monocarp's character should reach cell $(2, n)$ — at the intersection of row $2$ and column $n$.\n\nHelp Monocarp determine if it is possible to complete the level.",
    "tutorial": "At first glance, it seems like a graph problem. And indeed, this problem can be solved by explicitly building a graph considering cells as the vertices and checking that there is a safe path from start to finish via DFS/BFS/DSU/any other graph algorithm or data structure you know. But there's a much simpler solution. Since there are only two rows in a matrix, it's possible to move from any cell in the column $i$ to any cell in column $i + 1$ (if they are both safe, of course). It means that as long as there is at least one safe cell in each column, it is possible to reach any column of the matrix (and the cell $(2, n)$ as well). It's easy to see that if this condition is not met, there exists a column with two unsafe cells - and this also means that this column and columns to the right of it are unreachable. So, the problem is reduced to checking if there is a column without any unsafe cells. To implement this, you can read both rows of the matrix as strings (let these strings be $s_1$ and $s_2$) and check that there is a position $i$ such that both $s_1[i]$ and $s_2[i]$ are equal to 1.",
    "code": "def solve():\n\tn = int(input())\n\ts1 = input()\n\ts2 = input()\n\tbad = False\n\tfor i in range(n):\n\t\tbad |= s1[i] == '1' and s2[i] == '1'\n\tif bad:\n\t\tprint('NO')\n\telse:\n\t\tprint('YES')\n\nt = int(input())\nfor i in range(t):\n\tsolve()",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1598",
    "index": "B",
    "title": "Groups",
    "statement": "$n$ students attended the first meeting of the Berland SU programming course ($n$ is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must be different. Furthermore, both groups should contain the same number of students.\n\nEach student has filled a survey in which they told which days of the week are convenient for them to attend a lesson, and which are not.\n\nYour task is to determine if it is possible to choose two different week days to schedule the lessons for the group (the first group will attend the lesson on the first chosen day, the second group will attend the lesson on the second chosen day), and divide the students into two groups, so the groups have equal sizes, and for each student, the chosen lesson day for their group is convenient.",
    "tutorial": "Since there are only five days, we can iterate over the two of them that will be the answer. Now we have fixed a pair of days $a$ and $b$ and want to check if it can be the answer. All students can be divided into four groups: marked neither of days $a$ and $b$, marked only day $a$, marked only day $b$ and marked both days. Obviously, if the first group is non-empty, days $a$ and $b$ can't be the answer. Let's call the number of students, who only marked day $a$, $\\mathit{cnt}_a$ and the number of students, who only marked day $b$, $\\mathit{cnt}_b$. If either of $\\mathit{cnt}_a$ or $\\mathit{cnt}_b$ exceed $\\frac{n}{2}$, then days $a$ and $b$ can't be the answer as well. Otherwise, we can always choose $\\frac{n}{2} - \\mathit{cnt}_a$ students from the ones who marked both days and send them to day $a$. The rest of the students can go to day $b$.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    a = [[] for i in range(n)]\n    for j in range(n):\n        a[j] = list(map(int, input().split()))\n    ans = False\n    for j in range(5):\n        for k in range(5):\n            if k != j:\n                cnt1 = 0\n                cnt2 = 0\n                cntno = 0\n                for z in range(n):\n                    if a[z][j] == 1:\n                        cnt1 += 1\n                    if a[z][k] == 1:\n                        cnt2 += 1\n                    if a[z][j] == 0 and a[z][k] == 0:\n                        cntno += 1\n                if cnt1 >= n // 2 and cnt2 >= n // 2 and cntno == 0:\n                    ans = True\n    if ans:\n        print('YES')\n    else:\n        print('NO')",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1598",
    "index": "C",
    "title": "Delete Two Elements",
    "statement": "Monocarp has got an array $a$ consisting of $n$ integers. Let's denote $k$ as the mathematic mean of these elements (note that it's possible that $k$ is not an integer).\n\nThe mathematic mean of an array of $n$ elements is the sum of elements divided by the number of these elements (i. e. sum divided by $n$).\n\nMonocarp wants to delete exactly two elements from $a$ so that the mathematic mean of the remaining $(n - 2)$ elements is still equal to $k$.\n\nYour task is to calculate the number of pairs of positions $[i, j]$ ($i < j$) such that if the elements on these positions are deleted, the mathematic mean of $(n - 2)$ remaining elements is equal to $k$ (that is, it is equal to the mathematic mean of $n$ elements of the original array $a$).",
    "tutorial": "First of all, instead of the mathematic mean, let's consider the sum of elements. If the mathematic mean is $k$, then the sum of elements of the array is $k \\cdot n$. Let's denote the sum of elements in the original array as $s$. Note $s$ is always an integer. If we remove two elements from the array, the resulting sum of elements should become $k \\cdot (n - 2) = \\frac{s \\cdot (n - 2)}{n}$. So, the sum of the elements we remove should be exactly $\\frac{2s}{n}$. If $\\frac{2s}{n}$ is not an integer, the answer is $0$ (to check that, you can simply compare $(2s) \\bmod n$ with $0$). Otherwise, we have to find the number of pairs $(i, j)$ such that $i < j$ and $a_i + a_j = \\frac{2s}{n}$. This is a well-known problem. To solve it, you can calculate the number of occurrences of each element and store it in some associative data structure (for example, map in C++). Let $cnt_x$ be the number of occurrences of element $x$. Then, you should iterate on the element $a_i$ you want to remove and check how many elements match it, that is, how many elements give exactly $\\frac{2s}{n}$ if you add $a_i$ to them. The number of these elements is just $cnt_{\\frac{2s}{n} - a_i}$. Let's sum up all these values for every element in the array. Unfortunately, this sum is not the answer yet. We need to take care of two things: if for some index $i$, $2 \\cdot a_i = \\frac{2s}{n}$, then $a_i$ matches itself, so you have to subtract the number of such elements from the answer; every pair of elements is counted twice: the first time when we consider the first element of the pair, and the second time - when we consider the second element of the pair. So, don't forget to divide the answer by $2$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  scanf(\"%d\", &t);\n  while (t--) {\n    int n;\n    scanf(\"%d\", &n);\n    vector<int> a(n);\n    map<int, int> cnt;\n    for (auto &x : a) {\n      scanf(\"%d\", &x);\n      cnt[x] += 1;\n    }\n    long long sum = accumulate(a.begin(), a.end(), 0LL);\n    if ((2 * sum) % n != 0) {\n      puts(\"0\");\n      continue;\n    }\n    long long need = (2 * sum) / n;\n    long long ans = 0;\n    for (int i = 0; i < n; ++i) {\n      int a1 = a[i];\n      int a2 = need - a1;\n      if (cnt.count(a2)) ans += cnt[a2];\n      if (a1 == a2) ans -= 1;\n    }\n    printf(\"%lld\\n\", ans / 2);\n  }\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1598",
    "index": "D",
    "title": "Training Session",
    "statement": "Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.\n\nMonocarp has $n$ problems that none of his students have seen yet. The $i$-th problem has a topic $a_i$ (an integer from $1$ to $n$) and a difficulty $b_i$ (an integer from $1$ to $n$). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time.\n\nMonocarp decided to select exactly $3$ problems from $n$ problems for the problemset. The problems should satisfy \\textbf{at least one} of two conditions (possibly, both):\n\n- the topics of all three selected problems are different;\n- the difficulties of all three selected problems are different.\n\nYour task is to determine the number of ways to select three problems for the problemset.",
    "tutorial": "There are many different ways to solve this problem, but, in my opinion, the easiest one is to count all possible triples and subtract the number of bad triples. The first part is easy - the number of ways to choose $3$ elements out of $n$ is just $\\frac{n \\cdot (n - 1) \\cdot (n - 2)}{6}$. The second part is a bit tricky. What does it mean that the conditions in the statements are not fulfilled? There is a pair of problems with equal difficulty, and there is a pair of problems with the same topic. Since all problems in the input are different, it means that every bad triple has the following form: $[(x_a, y_a), (x_b, y_a), (x_a, y_b)]$ - i. e. there exists a problem such that it shares the difficulty with one of the other two problems, and the topic with the remaining problem of the triple. This observation allows us to calculate the number of bad triples as follows: we will iterate on the \"central\" problem (the one that shares the topic with the second problem and the difficulty with the third problem). If we pick $(x_a, y_a)$ as the \"central\" problem, we need to choose the other two. Counting ways to choose the other problems is easy if we precalculate the number of problems for each topic/difficulty: let $cntT_x$ be the number of problems with topic $x$, and $cntD_y$ be the number of problems with difficulty $y$; then, if we pick the problem $(x, y)$ as the \"central one\", there are $cntT_x - 1$ ways to choose a problem that shares the topic with it, and $cntD_y - 1$ ways to choose a problem that has the same difficulty - so, we have to subtract $(cntT_x - 1)(cntD_y - 1)$ from the answer for every problem $(x, y)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL); \n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n), ca(n + 1), cb(n + 1);\n    for (int i = 0; i < n; ++i) {\n      cin >> a[i] >> b[i];\n      ca[a[i]]++; cb[b[i]]++;\n    }\n    long long ans = n * 1LL * (n - 1) * (n - 2) / 6;\n    for (int i = 0; i < n; ++i) \n      ans -= (ca[a[i]] - 1) * 1LL * (cb[b[i]] - 1);\n    cout << ans << '\\n';\n  }\n} ",
    "tags": [
      "combinatorics",
      "data structures",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1598",
    "index": "E",
    "title": "Staircases",
    "statement": "You are given a matrix, consisting of $n$ rows and $m$ columns. The rows are numbered top to bottom, the columns are numbered left to right.\n\nEach cell of the matrix can be either free or locked.\n\nLet's call a path in the matrix a staircase if it:\n\n- starts and ends in the free cell;\n- visits only free cells;\n- has one of the two following structures:\n\n- the second cell is $1$ to the right from the first one, the third cell is $1$ to the bottom from the second one, the fourth cell is $1$ to the right from the third one, and so on;\n- the second cell is $1$ to the bottom from the first one, the third cell is $1$ to the right from the second one, the fourth cell is $1$ to the bottom from the third one, and so on.\n\nIn particular, a path, consisting of a single cell, is considered to be a staircase.\n\nHere are some examples of staircases:\n\nInitially all the cells of the matrix are \\textbf{free}.\n\nYou have to process $q$ queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free.\n\nPrint the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.",
    "tutorial": "The solution consist of two main parts: calculate the initial number of staircases and recalculate the number of staircases on query. The constraints were pretty loose, so we'll do the first part in $O(nm)$ and the second part in $O(n + m)$ per query. However, it's worth mentioning that faster is possible. The first part can surely be done in $O(n + m)$ and can probably be done in $O(1)$. The second part can be done in $O(\\log n)$ per query. It's important to notice is that the only staircase that satisfy the requirements for both types is the staircase that consists of a single cell. Thus, staircases of both types can be calculated almost separately. Let's define \"base\" staircases as the staircases that can't be prolonged further in any direction. There are $O(n + m)$ of them on the grid. If a staircase consists of at least two cells, it's a part of exactly one base staircase. At the same time, every segment of a base staircase is a valid staircase by itself. Thus, the main idea of calculating the initial answer is the following. Isolate each base staircase and determine its length $\\mathit{len}$ (possibly, in $O(n + m)$). Add $\\binom{len-1}{2}$ (the number of segments of length at least $2$) to the answer. Add extra $nm$ one cell staircases afterwards. If you draw the base staircases on the grid, you can easily determine their starting cell. The base staircases, that start by going one cell to the right, start from the first row. The base staircases, that start by going one cell to the bottom, start from the first column. Notice that both types can start from cell $(1, 1)$. The updates can be handled the following way. The answer always changes by the number of staircases that pass through cell $(x, y)$ (if you ignore its state). If the cell becomes free, then these staircases are added to the answer. Otherwise, they are subtracted from it. That can be calculated for two cases as well. Go first down, then right, as far as possible. Let it be $cnt_1$ steps. Go first left, then up, as far as possible. Let it be $cnt_2$ steps. Then $cnt_1 \\cdot cnt_2$ staircases are added to the answer. Then change the order of steps in both directions to calculate the other type of staircases. Beware of one cell staircases again. To achieve $O(n + m)$ for precalc, you can calculate the length of each base staircase with a formula. To achieve $O(\\log n)$ per query, you can first enumerate cells in each base staircase separately, then maintain the set of segments of adjacent free cells in it.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint n, m, q;\n\tscanf(\"%d%d%d\", &n, &m, &q);\n\tvector<vector<int>> a(n, vector<int>(m, 1));\n\tlong long ans = 0;\n\tforn(x, n) forn(y, m){\n\t\tif (x == 0){\n\t\t\tfor (int k = 1;; ++k){\n\t\t\t\tint nx = x + k / 2;\n\t\t\t\tint ny = y + (k + 1) / 2;\n\t\t\t\tif (nx == n || ny == m) break;\n\t\t\t\tans += k;\n\t\t\t}\n\t\t}\n\t\tif (y == 0){\n\t\t\tfor (int k = 1;; ++k){\n\t\t\t\tint nx = x + (k + 1) / 2;\n\t\t\t\tint ny = y + k / 2;\n\t\t\t\tif (nx == n || ny == m) break;\n\t\t\t\tans += k;\n\t\t\t}\n\t\t}\n\t}\n\tans += n * m;\n\tforn(i, q){\n\t\tint x, y;\n\t\tscanf(\"%d%d\", &x, &y);\n\t\t--x, --y;\n\t\tforn(c, 2){\n\t\t\tint l = 1, r = 1;\n\t\t\twhile (true){\n\t\t\t\tint nx = x + (l + c) / 2;\n\t\t\t\tint ny = y + (l + !c) / 2;\n\t\t\t\tif (nx == n || ny == m || a[nx][ny] == 0) break;\n\t\t\t\t++l;\n\t\t\t}\n\t\t\twhile (true){\n\t\t\t\tint nx = x - (r + !c) / 2;\n\t\t\t\tint ny = y - (r + c) / 2;\n\t\t\t\tif (nx < 0 || ny < 0 || a[nx][ny] == 0) break;\n\t\t\t\t++r;\n\t\t\t}\n\t\t\tif (a[x][y] == 0){\n\t\t\t\tans += l * r;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tans -= l * r;\n\t\t\t}\n\t\t}\n\t\tans += a[x][y];\n\t\ta[x][y] ^= 1;\n\t\tans -= a[x][y];\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "data structures",
      "dfs and similar",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1598",
    "index": "F",
    "title": "RBS",
    "statement": "A bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example:\n\n- bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\");\n- bracket sequences \")(\", \"(\" and \")\" are not.\n\nLet's denote the concatenation of two strings $x$ and $y$ as $x+y$. For example, \"()()\" $+$ \")(\" $=$ \"()())(\".\n\nYou are given $n$ bracket sequences $s_1, s_2, \\dots, s_n$. You can rearrange them in any order (you can rearrange only the strings themselves, but not the characters in them).\n\nYour task is to rearrange the strings in such a way that the string $s_1 + s_2 + \\dots + s_n$ has as many non-empty prefixes that are RBS as possible.",
    "tutorial": "The constraint $n \\le 20$ is a clear hint that we need some exponential solution. Of course, we cannot try all $n!$ permutations. Let's instead try to design a solution with bitmask dynamic programming. A string is an RBS if its balance (the difference between the number of opening and closing brackets) is $0$, and the balance of its each prefix is non-negative. So, let's introduce the following dynamic programming: $dp_{m,b,f}$ is the greatest number of RBS-prefixes of a string if we considered a mask $m$ of strings $s_i$, the current balance of the prefix is $b$, and $f$ is a flag that denotes whether there already has been a prefix with negative balance. We can already get rid of one of the states: the current balance is uniquely determined by the mask $m$. So, this dynamic programming will have $O(2^{n+1})$ states. To perform transitions, we need to find a way to recalculate the value of $f$ and the answer if we append a new string at the end of the current one. Unfortunately, it's too slow to simply simulate the process. Instead, for every string $s_i$, let's precalculate the value $go(s_i, f, x)$ - how does the flag and the answer change, if the current flag is $f$, and the current balance is $x$. The resulting flag will be true in one of the following two cases: it is already true; the string we append creates a new prefix with non-positive balance. The second case can be checked as follows: let's precalculate the minimum balance of a prefix of $s_i$; let it be $c$. If $x + c < 0$, the flag will be true. Calculating how the answer changes is a bit trickier. If the current flag is already true, the answer doesn't change. But if it is false, the answer will increase by the number of new RBS-prefixes. If the balance before adding the string $s_i$ is $b$, then we get a new RBS-prefix for every prefix of $s_i$ such that: its balance is exactly $(-b)$ (to compensate the balance we already have); there is no prefix with balance $(-b-1)$ in $s_i$ before this prefix. To quickly get the number of prefixes meeting these constraints, we can create a data structure that stores the following information: for every balance $j$, store a sorted vector of positions in $s_i$ with balance equal to $j$. Then, to calculate the number of prefixes meeting the constraints, we can find the first position in $s_i$ with balance equal to $(-b-1)$ by looking at the beginning of the vector for $(-b-1)$, and then get the number of elements less than this one from the vector for balance $(-b)$ by binary search. These optimizations yield a solution in $O(2^n \\log A + A \\log A)$, although it's possible to improve to $O(2^n + A \\log A)$ if you precalculate each value of $go(s_i, f, x)$ for every string $s_i$.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int INF = int(1e9);\n\nconst int N = 20;\nconst int M = (1 << N);\n\nstruct BracketSeqn\n{\n \tint balance;\n \tint lowestBalance;\n \tvector<int> queryAns;\n\n \tpair<int, bool> go(int x, bool f)\n \t{\n     \tif(f)\n     \t\treturn make_pair(0, true);\n       \telse\n       \t\treturn make_pair(x < queryAns.size() ? queryAns[x] : 0, x + lowestBalance < 0);\n    }\n\n\tBracketSeqn() {};\n\tBracketSeqn(string s)\n\t{\n\t\tvector<int> bal;\n\t\tint cur = 0;\n\t\tint n = s.size();\n\t\tfor(auto x : s)\n\t\t{\n\t\t \tif(x == '(')\n\t\t \t\tcur++;\n\t\t \telse\t\n\t\t \t\tcur--;\n\t\t \tbal.push_back(cur);\t\n\t\t}\n\t\tbalance = bal.back();\n\t\tlowestBalance = min(0, *min_element(bal.begin(), bal.end()));\n\t\tvector<vector<int>> negPos(-lowestBalance + 1);\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t \tif(bal[i] > 0) continue;\n\t\t \tnegPos[-bal[i]].push_back(i);\n\t\t}\n\t\tqueryAns.resize(-lowestBalance + 1);\n\t\tfor(int i = 0; i < queryAns.size(); i++)\n\t\t{\n\t\t \tint lastPos = int(1e9);\n\t\t \tif(i != -lowestBalance)\n\t\t \t\tlastPos = negPos[i + 1][0];\n\t\t \tqueryAns[i] = lower_bound(negPos[i].begin(), negPos[i].end(), lastPos) - negPos[i].begin();\n\t\t}\n\t};\n};\n\nint dp[M][2];\nchar buf[M];\nint total_bal[M];\n\nint main()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<BracketSeqn> bs;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t \tscanf(\"%s\", buf);\n\t \tstring s = buf;\n\t \tbs.push_back(BracketSeqn(s));\n\t}\n\tfor(int i = 0; i < (1 << n); i++)               \n\t \tfor(int j = 0; j < n; j++)\n\t \t\tif(i & (1 << j))\n\t \t\t\ttotal_bal[i] += bs[j].balance;\n\tfor(int i = 0; i < (1 << n); i++)\n\t\tfor(int j = 0; j < 2; j++)\n\t\t\tdp[i][j] = -int(1e9);\n\tdp[0][0] = 0;\n\tfor(int i = 0; i < (1 << n); i++)\n\t\tfor(int f = 0; f < 2; f++)\n\t\t{\n\t\t \tif(dp[i][f] < 0) continue;\n\t\t \tfor(int k = 0; k < n; k++)\n\t\t \t{\n\t\t \t \tif(i & (1 << k)) continue;\n\t\t \t \tpair<int, bool> res = bs[k].go(total_bal[i], f);\n\t\t \t \tdp[i ^ (1 << k)][res.second] = max(dp[i ^ (1 << k)][res.second], dp[i][f] + res.first);\n\t\t \t}\n\t\t}\n\tprintf(\"%d\\n\", max(dp[(1 << n) - 1][0], dp[(1 << n) - 1][1]));\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1598",
    "index": "G",
    "title": "The Sum of Good Numbers",
    "statement": "Let's call a positive integer good if there is no digit 0 in its decimal representation.\n\nFor an array of a good numbers $a$, one found out that the sum of some two neighboring elements is equal to $x$ (i.e. $x = a_i + a_{i + 1}$ for some $i$). $x$ had turned out to be a good number as well.\n\nThen the elements of the array $a$ were written out one after another without separators into one string $s$. For example, if $a = [12, 5, 6, 133]$, then $s = 1256133$.\n\nYou are given a string $s$ and a number $x$. Your task is to determine the positions in the string that correspond to the adjacent elements of the array that have sum $x$. If there are several possible answers, you can print any of them.",
    "tutorial": "Let's denote $a$ as the largest of the terms of the sum, and $b$ is the smaller one. Consider $2$ cases: $|a| =|x| - 1$ or $|a|=|x|$. If $|a| =|x| - 1$, then $|b| =|x| - 1$. So we need to find two consecutive substrings of length $|x| - 1$ such that if we convert these substrings into integers, their sum is equal to $x$. If $|a| = |x|$, let $\\mathit{lcp}$ be the largest common prefix of $a$ and $x$ if we consider them as strings. Then $|b| = |x| - \\mathit{lcp}$ or $|b| =|x| - \\mathit{lcp} - 1$. So it is necessary to check only these two cases, and whether $b$ goes before or after $a$ (in the string $s$). Thus, we have reduced the number of variants where the substrings for $a$ and $b$ are located to $O(n)$. It remains to consider how to quickly check whether the selected substrings are suitable. To do this, you can use hashes (preferably with several random modules).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int MOD[] = { 597804841, 618557587, 998244353 };\nconst int N = 500 * 1000 + 13;\nconst int K = 3;\n\nusing hs = array<int, K>;\n\nint add(int x, int y, int mod) {\n  x += y;\n  if (x >= mod) x -= mod;\n  if (x < 0) x += mod;\n  return x;\n}\n\nint mul(int x, int y, int mod) {\n  return x * 1LL * y % mod;\n}\n\nhs get(const int& x) {\n  hs c;\n  forn(i, K) c[i] = x;\n  return c;\n}\n\nhs operator +(const hs& a, const hs& b) { \n  hs c;\n  forn(i, K) c[i] = add(a[i], b[i], MOD[i]);\n  return c;\n}\n\nhs operator -(const hs& a, const hs& b) {\n  hs c;\n  forn(i, K) c[i] = add(a[i], -b[i], MOD[i]);\n  return c; \n}\n\nhs operator *(const hs& a, const hs& b) {\n  hs c;\n  forn(i, K) c[i] = mul(a[i], b[i], MOD[i]);\n  return c; \n}\n\nint n, m;\nstring s, sx;\nhs sum[N], pw[N];\n\nhs get(int l, int r) {\n  return sum[r] - sum[l] * pw[r - l];\n}\n\nvector<int> zfunction(const string& s) {\n  int n = s.size();\n  vector<int> z(n);\n  int l = 0, r = 0;\n  for (int i = 1; i < n; ++i) {\n    if (i <= r) z[i] = min(z[i - l], r - i + 1);\n    while (i + z[i] < n && s[z[i]] == s[i + z[i]])\n      ++z[i];\n    if (i + z[i] - 1 > r) {\n      l = i;\n      r = i + z[i] - 1;\n    }\n  }\n  return z;\n}\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL); \n  \n  cin >> s >> sx;\n  n = s.size();\n  m = sx.size();\n  \n  pw[0] = get(1);\n  forn(i, N - 1) pw[i + 1] = pw[i] * get(10); \n  sum[0] = get(0);\n  forn(i, n) sum[i + 1] = sum[i] * get(10) + get(s[i] - '0'); \n  hs x = get(0);\n  forn(i, m) x = x * get(10) + get(sx[i] - '0');\n  \n  if (m > 1) for (int i = 0; i + 2 * (m - 1) <= n; ++i) {\n    if (get(i, i + m - 1) + get(i + m - 1, i + 2 * (m - 1)) == x) {\n      cout << i + 1 << ' ' << i + m - 1 << '\\n';\n      cout << i + m << ' ' << i + 2 * (m - 1) << '\\n';\n      return 0;\n    }\n  }\n  \n  auto z = zfunction(sx + \"#\" + s);\n  \n  for (int i = 0; i + m <= n; ++i) {\n    int lcp = z[m + i + 1];\n    for (int len = m - lcp - 1; len <= m - lcp; ++len) {\n      if (len < 1) continue;\n      if (i + m + len <= n && get(i, i + m) + get(i + m, i + m + len) == x) {\n        cout << i + 1 << ' ' << i + m << '\\n';\n        cout << i + m + 1 << ' ' << i + m + len << '\\n';\n        return 0;\n      }\n      if (i >= len && get(i - len, i) + get(i, i + m) == x) {\n        cout << i - len + 1 << ' ' << i << '\\n';\n        cout << i + 1 << ' ' << i + m << '\\n';\n        return 0;\n      }\n    }\n  }\n  \n  assert(false);\n}",
    "tags": [
      "hashing",
      "math",
      "string suffix structures",
      "strings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1601",
    "index": "A",
    "title": "Array Elimination",
    "statement": "You are given array $a_1, a_2, \\ldots, a_n$, consisting of non-negative integers.\n\nLet's define operation of \"elimination\" with integer parameter $k$ ($1 \\leq k \\leq n$) as follows:\n\n- Choose $k$ distinct array indices $1 \\leq i_1 < i_2 < \\ldots < i_k \\le n$.\n- Calculate $x = a_{i_1} ~ \\& ~ a_{i_2} ~ \\& ~ \\ldots ~ \\& ~ a_{i_k}$, where $\\&$ denotes the bitwise AND operation (notes section contains formal definition).\n- Subtract $x$ from each of $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$; all other elements remain untouched.\n\nFind all possible values of $k$, such that it's possible to make all elements of array $a$ equal to $0$ using a finite number of elimination operations with parameter $k$. It can be proven that exists at least one possible $k$ for any array $a$.\n\nNote that you \\textbf{firstly choose $k$ and only after that perform elimination operations with value $k$ you've chosen initially}.",
    "tutorial": "Let's note, that in one destruction for any bit $i$ ($0 \\leq i < 30$) we either change all $k$-th non-zero bits into zero bits, or nothing changes. So, the number of $i$-th non-zero bits in the array either decreases by $k$ or doesn't change. In the end, all these numbers will be equal to $0$. So, to be able to destruct the array, the number of $i$-th non-zero bits in the array should be divisible by $k$ for all bits $i$. Let's prove, that it is enough to destruct the array. Let's make operations with non-zero AND, while we can make them. In the end, there is at least one non-zero element, if we have not destructed the array. So, there is at least one bit $i$, for which the number of $i$-th non-zero bits in the array is non-zero, so this number is at least $k$ (because it is divisible by $k$). So we can select $k$ numbers with $i$-th non-zero bit to the next operation and make the new destruction, which is impossible. So the resulting solution is: for each bit $i$ ($0 \\leq i < 30$) let's find the number of array's elements with non-zero $i$-th bit. Let's find all common divisors $k$ ($1 \\leq k \\leq n$) of these numbers. Time complexity is $O(n \\log{C})$, where $C = 10^9$ - upper limit on all numbers in the array.",
    "tags": [
      "bitmasks",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1601",
    "index": "B",
    "title": "Frog Traveler",
    "statement": "Frog Gorf is traveling through Swamp kingdom. Unfortunately, after a poor jump, he fell into a well of $n$ meters depth. Now Gorf is on the bottom of the well and has a long way up.\n\nThe surface of the well's walls vary in quality: somewhere they are slippery, but somewhere have convenient ledges. In other words, if Gorf is on $x$ meters below ground level, then in one jump he can go up on any integer distance from $0$ to $a_x$ meters inclusive. (Note that Gorf can't jump down, only up).\n\nUnfortunately, Gorf has to take a break after each jump (including jump on $0$ meters). And after jumping up to position $x$ meters below ground level, he'll slip exactly $b_x$ meters down while resting.\n\nCalculate the minimum number of jumps Gorf needs to reach ground level.",
    "tutorial": "Let's denote sequence of moves $i \\Rightarrow i - a_i \\dashrightarrow i - a_i + b_{i-a_i}$ as jump. We will use $dp_i$ - minimal number of moves needed to travel from $i$ to $0$. It can be calculated $dp_i = 1 + \\min (dp_j + b_j)$, with $i - a_i \\le j \\le i$. We expected calculations to use bfs-style order. So, if there is a jump to $0$, $dp$ is $1$. If there is no jump to $0$, but there is a jump to position with $dp=1$, then $dp$ is $2$, and so on. What happens, when we know all dp's with values from $0$ to $d$? We'll take position $v$ ($dp_v = d$) and all $u$ with condition $u + b_u = v$. Then all $j$ that has $j - a_j \\le u \\le j$ we know for sure $dp_j = d + 1$. For every $i$ we will save in minimum segment tree value $i - a_i$. So, all $j$'s are just elements from a suffix with value not greater than $u$. We can iterate through all $j$'s, because every of them is used only once - right after we know $dp_j$, we can use any neutral value (infinity in our case). Time complexity is $O(n \\log n)$ Bonus. Try to solve it in linear time :)",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1601",
    "index": "C",
    "title": "Optimal Insertion",
    "statement": "You are given two arrays of integers $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_m$.\n\nYou need to insert all elements of $b$ into $a$ in an arbitrary way. As a result you will get an array $c_1, c_2, \\ldots, c_{n+m}$ of size $n + m$.\n\nNote that you are not allowed to change the order of elements in $a$, while you can insert elements of $b$ at arbitrary positions. They can be inserted at the beginning, between any elements of $a$, or at the end. Moreover, elements of $b$ can appear in the resulting array in any order.\n\nWhat is the minimum possible number of inversions in the resulting array $c$? Recall that an inversion is a pair of indices $(i, j)$ such that $i < j$ and $c_i > c_j$.",
    "tutorial": "Let's sort array $b$. Let's define $p_i$ as the index of the array $a$, before which we should insert $b_i$. If $b_i$ should be inserted at the end of the array $a$, let's make $p_i = n + 1$. Let's note, that all inserted elements should go in the sorted order in the optimal answer. If it is false and there exists $p_i > p_j$ for $i < j$, let's swap $b_i$ and $b_j$ in the answer. The number of inversions will decrease, a contradiction. So $p_1 \\leq p_2 \\leq \\ldots \\leq p_m$. If we will find their values we will be able to restore an array after inserting elements. Let's use \"Divide and conquer\" to find them. Let's write a recursive function $solve(l_i, r_i, l_p, r_p)$, that will find $p_i$ for all $l_i \\leq i < r_i$, if it is known, that $p_i \\in [l_p, r_p]$ for all such $i$. To find all values of $p$ we should call the function $solve(1, m + 1, 1, n + 1)$. Realization of $solve(l_i, r_i, l_p, r_p)$: If $l_i \\geq r_i$, we shouldn't do anything. Let $mid = \\lfloor \\frac{l_i + r_i}{2} \\rfloor$. Let's find $p_{mid}$. The number of inversions with $b_{mid}$ will be (the number of $a_i > b_{mid}$ for $i < p_{mid}$) + (the number of $a_i < b_{mid}$ for $i \\geq p_{mid}$). This sum differs by a constant from: (the number of $a_i > b_{mid}$ for $l_p \\leq i < p_{mid}$) + (the number of $a_i < b_{mid}$ for $p_{mid} \\leq i < r_p$). For this sum it is simple to find the minimal optimal $p_{mid}$ in $O(r_p - l_p)$. Let's make two recursive calls of $solve(l_i, mid - 1, l_p, p_{mid})$, $solve(mid + 1, r_i, p_{mid}, r_p)$, that will find all remaining values of $p$. The complexity of this function will be $O((n+m)\\log{m})$, because there will be $O(\\log{m})$ levels of recursion and we will make $O(n+m)$ operations on each of them. In the end, using the values $p_i$ we will restore the array and find the number of inversions in it. Total complexity: $O((n+m)\\log{(n+m)})$. Also, there exist other correct solutions with the same complexity, using segment tree.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1601",
    "index": "D",
    "title": "Difficult Mountain",
    "statement": "A group of $n$ alpinists has just reached the foot of the mountain. The initial difficulty of climbing this mountain can be described as an integer $d$.\n\nEach alpinist can be described by two integers $s$ and $a$, where $s$ is his skill of climbing mountains and $a$ is his neatness.\n\nAn alpinist of skill level $s$ is able to climb a mountain of difficulty $p$ only if $p \\leq s$. As an alpinist climbs a mountain, they affect the path and thus may change mountain difficulty. Specifically, if an alpinist of neatness $a$ climbs a mountain of difficulty $p$ the difficulty of this mountain becomes $\\max(p, a)$.\n\nAlpinists will climb the mountain one by one. And before the start, they wonder, what is the maximum number of alpinists who will be able to climb the mountain if they choose the right order. As you are the only person in the group who does programming, you are to answer the question.\n\nNote that after the order is chosen, each alpinist who can climb the mountain, must climb the mountain at that time.",
    "tutorial": "First, discard all $i$ such that $s_i < d$ Instead of climbers, we will consider pairs $(s_i, a_i)$, and also say that the set of pairs is correct if there is a permutation $p_1 \\ldots p_n$ such that for every $i : \\max (d, a_ {p_1}, \\ldots a_ {p_ {i-1}}) \\le s_ {p_i}$, which means that there is an order in which all climbers can climb. We will call a pair of indices $i, j$ incompatible if $i \\neq j$ and $s_j < a_i$ and $s_i <a_j$. - this means that the $i$-th climber cannot climb after the $j$-th and vice versa. Note that if the set does not have an incompatible pair of indices, then it is correct. The suitable order for pairs $(s_i, a_i)$ can be reached by sorting them in increasing order of pairs ${min (s_i, a_i), \\max (s_i, a_i)}$. After sorting either $i$-th climber can go after $(i - 1)$-th or the pair $(i - 1), i$ is incompatible. $\\quad$ Let's solve the problem with an additional restriction first, namely: for each $i : s_i < a_i$, In this case, you can use the following greedy solution: Let $D = d$, find among the pairs $(s_i, a_i)$ such that $D \\le s_i$, and among such pairs - the pair with the smallest $a_i$ - it will be the next in our order. Replace $D$ by $a_i$, increase the answer by 1 and repeat the algorithm. If the pair with $D \\le s_i$ does not exist, terminate the algorithm. The correctness of such an algorithm is proved by induction. To effectively implement this solution, let's sort all the pairs $(s_i, a_i)$ in increasing order of $a_i$ Let's go through the indices $i$ from 1 to $n$ $\\quad$ If $D \\le s_i$, then add 1 to the answer and replace $D$ with $a_i$. $\\quad$ Let's get back to the main problem: Consider a pair of indices $i, j$ such that $s_i < a_j \\le s_j < a_i$ Such a pair of indices is incompatible, and if the optimal answer contains $i$, then it can be replaced with $j$ and the sequence will not break. $\\quad$ $s_i < s_j \\Rightarrow$ for any value of $D$ that matches $i$ it matches $j$. $\\quad$ $a_j < a_i \\Rightarrow$ for any $D: max (D, a_j) \\le max (D, a_i)$ Therefore, for any such pair $i, j$, the $i$-th can be excluded from the set of climbers and the answer will not worsen. $\\quad$ To effectively remove all such $(s_i, a_i)$ pairs, we use the two-pointer method: Let's take out all such pairs that $a_i \\le s_i$ into the $b$ array. Let the remaining pairs be in the $c$ array. Let's sort the array $b$ in increasing order of $a_i$ and the array $c$ in increasing order of $s_i$. Let's create an ordered set $M$, which can store the pairs $(s_i, a_i)$ in decreasing order of $a_i$. Let's create a pointer $j = 0$. Let's go through the elements of the $b$ array with index i. $\\quad$ For this item: $\\quad$ While $c_ {j} .s < b_ {i} .a$ we will add $c_j$ to the set $M$ $\\quad$ Now while $b_ {i} .s < M_ {1} .a$ we will delete the first element M. Among the elements of the $b$ array, the $M$ set and the remaining elements in the $c$ array, there are no more required pairs. Note that among the remaining pairs $(s_i, a_i)$, any pair of indices $i, j$ such that $a_i \\le s_i$ or $a_j \\le s_j$ is not incompatible. Now, if we find the maximum correct subset of the pairs $(s_i, a_i)$, such that $s_i < a_i$ and combine it with the set of pairs $(s_i, a_i)$, such that $a_i \\le s_i$, we get the correct set, moreover, for obvious reasons - it has maximum size. Therefore, we will get the answer to the problem.",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1601",
    "index": "E",
    "title": "Phys Ed Online",
    "statement": "Students of one unknown college don't have PE courses. That's why $q$ of them decided to visit a gym nearby by themselves. The gym is open for $n$ days and has a ticket system. At the $i$-th day, the cost of one ticket is equal to $a_i$. You are free to buy more than one ticket per day.\n\nYou can activate a ticket purchased at day $i$ either at day $i$ or any day later. Each activated ticket is valid only for $k$ days. In other words, if you activate ticket at day $t$, it will be valid only at days $t, t + 1, \\dots, t + k - 1$.\n\nYou know that the $j$-th student wants to visit the gym at each day from $l_j$ to $r_j$ inclusive. Each student will use the following strategy of visiting the gym at any day $i$ ($l_j \\le i \\le r_j$):\n\n- person comes to a desk selling tickets placed near the entrance and buy several tickets with cost $a_i$ apiece (possibly, zero tickets);\n- if the person has at least one activated and still valid ticket, they just go in. Otherwise, they activate one of tickets purchased today or earlier and go in.\n\nNote that each student will visit gym only starting $l_j$, so each student has to buy at least one ticket at day $l_j$.\n\nHelp students to calculate the minimum amount of money they have to spend in order to go to the gym.",
    "tutorial": "Observe that we need to buy a subscription at day one, then we need to buy the cheapest subscricption among first $k + 1$ days, $...$, then the cheapest among the first $tk + 1$ days. Let's denote $b_i$ as a minimum on a segment $[i - k, i - k + 1, ..., i]$, $b_i$ can be calculated in a linear time using monotonic queue. So the answer for query is $a_l + b_{l + k} + \\textrm{min}(b_{l + k}, b_{l + 2k}) + ... + \\textrm{min}(b_{l + k}, b_{l + 2k} + ... + b_{l + tk})$, where $l + tk \\leq r$. Observe that such a sum is independent of the remainder of the division of $l$ by $k$, so we can solve an easier problem instead: we are given with an array $c$, and we need to calculate a sum of prefix minimums on a segment. To solve this, let's calculate an array $nxt_i$ - the minimum position $nxt_i > i$ such that $c_{nxt_i} < c_i$. Let $dp_i$ be a sum of minimums on prefixes of $i$-th suffix. Observe that $dp_i = dp_{nxt_i} + c_i \\cdot (nxt_i - i)$. To calculate a sum of prefix minimums on the segment $[l, r]$, find a position $p$, such that $a_p$ is a minimum on the segment $[l, r]$, then the answer is $dp_l - dp_p + (r - p + 1) \\cdot c_p$. So we have a solution in $\\mathcal{O}(n + q\\alpha^{-1}(n))$, where $\\alpha^{-1}$ is the inverse Ackermann function, if we use a Tarjan's algorithm for offline rmq. It was enough to use any logarithmic data structure to solve a problem.",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1601",
    "index": "F",
    "title": "Two Sorts",
    "statement": "Integers from $1$ to $n$ (inclusive) were sorted lexicographically (considering integers as strings). As a result, array $a_1, a_2, \\dots, a_n$ was obtained.\n\nCalculate value of $(\\sum_{i = 1}^n ((i - a_i) \\mod 998244353)) \\mod 10^9 + 7$.\n\n$x \\mod y$ here means the remainder after division $x$ by $y$. This remainder is always non-negative and doesn't exceed $y - 1$. For example, $5 \\mod 3 = 2$, $(-1) \\mod 6 = 5$.",
    "tutorial": "Suppose $b$ is an inverse permutation of $a$, that is $a_{b_{i}} = b_{a_i} = i$, that is $b_i$ is an index of $i$ in the lexicographical sorting. Rewrite desired sum replacing $i \\to b_i$: $\\sum_{i=1 \\ldots n} ((i - a_i) \\bmod p) = \\sum_{i=1 \\ldots n} ((b_i - a_{b_i}) \\bmod p) = \\sum_{i=1 \\ldots n} ((b_i - i) \\bmod p)$. First, we need to understand how to calculate $b_i$'s. Observe that $b_i$ equals $1$ plus number of integers $x$ ($1 \\le x \\le n$) so that $x <_{lex} i$. These integers are of two possible kinds: own prefixes of $i$ (the number of such $x$ depends only on the length of $i$) and integers $x$ having a common prefix with $i$ of some length $t$ and a smaller digit $c$ in $(t+1)$-th index. If we fix values of $t$, $c$, length of $x$, we have a \"mask\" of the following kind: \"123???\", and we are interested in the number of $x$ matching this mask. This number almost always depends on the number of \"?\" with minor exceptions concerning $n$. E. g. consider $n = 123456$ for the example above. So in the desired sum, we group summands by the following markers of $i$ (brute force the value of these markers): Length of $i$, Position of first digit different in $i$ and $n$ (cases, where $i$ is an own prefix of $n$, shall be considered separately). The value of this digit. So we know description of $i$ of the following kind: $i = \\overline{c_1 c_2 \\ldots c_k x_1 \\ldots x_l}$, where $c_j$ are fixed, and $x_1, \\ldots, x_l$ are arbitrary integer variables in $[0, 9]$. Observe that both $b_i$ and $i$ are linear combination of variables $x_j$ and $1$, so $b_i - i$ is also a linear combination of them. The only issue is computing $b_i - i$ modulo $p$. To do summing over all $x_1, \\ldots, x_l$ we use the meet-in-the-middle method: bruteforce separately the values for the first half and the second half, and then match one with another. If $n \\le 10^L$, the solution works in $\\mathcal{O}(10^{\\frac{L}{2}} \\operatorname{poly}(L))$, or $\\mathcal{O}(\\sqrt{n}\\, \\operatorname{poly}(\\log n))$.",
    "tags": [
      "binary search",
      "dfs and similar",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1602",
    "index": "A",
    "title": "Two Subsequences",
    "statement": "You are given a string $s$. You need to find two non-empty strings $a$ and $b$ such that the following conditions are satisfied:\n\n- Strings $a$ and $b$ are both \\textbf{subsequences} of $s$.\n- For each index $i$, character $s_i$ of string $s$ must belong to \\textbf{exactly one} of strings $a$ or $b$.\n- String $a$ is lexicographically minimum possible; string $b$ may be any possible string.\n\nGiven string $s$, print any valid $a$ and $b$.\n\n\\textbf{Reminder:}\n\nA string $a$ ($b$) is a subsequence of a string $s$ if $a$ ($b$) can be obtained from $s$ by deletion of several (possibly, zero) elements. For example, \"dores\", \"cf\", and \"for\" are subsequences of \"codeforces\", while \"decor\" and \"fork\" are not.\n\nA string $x$ is lexicographically smaller than a string $y$ if and only if one of the following holds:\n\n- $x$ is a prefix of $y$, but $x \\ne y$;\n- in the first position where $x$ and $y$ differ, the string $x$ has a letter that appears earlier in the alphabet than the corresponding letter in $y$.",
    "tutorial": "Note that taking $a$ as minimum character in $s$ is always optimal ($a$ starts with minimum possible character and is prefix of any other longer string). In such case, $b$ is just all characters from $s$ except character from $a$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1602",
    "index": "B",
    "title": "Divine Array",
    "statement": "Black is gifted with a Divine array $a$ consisting of $n$ ($1 \\le n \\le 2000$) integers. Each position in $a$ has an initial value. After shouting a curse over the array, it becomes angry and starts an unstoppable transformation.\n\nThe transformation consists of infinite steps. Array $a$ changes at the $i$-th step in the following way: for every position $j$, $a_j$ becomes equal to the number of occurrences of $a_j$ in $a$ before starting this step.\n\nHere is an example to help you understand the process better:\n\n\\begin{center}\n\\begin{tabular}{cc}\nInitial array: & $2$ $1$ $1$ $4$ $3$ $1$ $2$ \\\nAfter the $1$-st step: & $2$ $3$ $3$ $1$ $1$ $3$ $2$ \\\nAfter the $2$-nd step: & $2$ $3$ $3$ $2$ $2$ $3$ $2$ \\\nAfter the $3$-rd step: & $4$ $3$ $3$ $4$ $4$ $3$ $4$ \\\n... & ... \\\n\\end{tabular}\n\\end{center}\n\nIn the initial array, we had two $2$-s, three $1$-s, only one $4$ and only one $3$, so after the first step, each element became equal to the number of its occurrences in the initial array: all twos changed to $2$, all ones changed to $3$, four changed to $1$ and three changed to $1$.\n\nThe transformation steps continue \\textbf{forever}.\n\nYou have to process $q$ queries: in each query, Black is curious to know the value of $a_x$ after the $k$-th step of transformation.",
    "tutorial": "It can be shown that after at most $n$ steps of transformation, array $a$ becomes repetitive. There is even a better lower bound: it can be shown that after at most $\\log(n)$ steps $a$ becomes repetitive, so we use either of these two facts to simulate the process and answer the queries.",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1603",
    "index": "A",
    "title": "Di-visible Confusion",
    "statement": "YouKn0wWho has an integer sequence $a_1, a_2, \\ldots, a_n$. He will perform the following operation until the sequence becomes empty: select an index $i$ such that $1 \\le i \\le |a|$ and $a_i$ is \\textbf{not} divisible by $(i + 1)$, and erase this element from the sequence. Here $|a|$ is the length of sequence $a$ at the moment of operation. Note that the sequence $a$ changes and the next operation is performed on this changed sequence.\n\nFor example, if $a=[3,5,4,5]$, then he can select $i = 2$, because $a_2 = 5$ is not divisible by $i+1 = 3$. After this operation the sequence is $[3,4,5]$.\n\nHelp YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation.",
    "tutorial": "Notice that we can erase $a_i$ at positions from $1$ to $i$. So for each $i$, there should be at least one integer from $2$ to $i + 1$ such that $a_i$ is not divisible by that integer. If it is not satisfied for some integer $i$, then there is no solution for sure. Otherwise, it turns out that a solution always exists. Why? We can prove it by induction. Let's say it is possible to erase the prefix containing $n - 1$ elements. As $a_n$ can be erased at some position from $1$ to $n$(let's say $k$), then while erasing the prefix of $n - 1$ elements, when the prefix contains $k - 1$ elements, then $a_n$ is at the $k$-th position, so we can erase it at that position and erase the rest of the sequence accordingly. So we just have to check for all integers $i$ from $1$ to $n$, if $a_i$ is not divisible by at least one integer from $2$ to $i + 1$. Notice that if $a_i$ is divisible by all integers from $2$ to $i + 1$, then it means that $a_i$ is divisible by $\\operatorname{LCM}(2, 3, \\ldots, (i+1))$. But when $i = 22$, $\\operatorname{LCM}(2, 3, \\ldots, 23) \\gt 10^9 \\gt a_i$. So for $i \\ge 22$, there will always be an integer from $2$ to $i + 1$ which doesn't divide $a_i$. So we don't have to check for them. For $i \\lt 22$, use bruteforce. Complexity: $\\mathcal{O}(n + 21^2)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t; cin >> t;\n  while (t--) {\n    int n; cin >> n;\n    bool ok = true;\n    for (int i = 1; i <= n; i++) {\n      int x; cin >> x;\n      bool found = false;\n      for (int j = i + 1; j >= 2; j--) { // this loop will run not more than 22 times, in practice its much lower than that\n        if (x % j) {\n          found = true;\n          break;\n        }\n      }\n      ok &= found;\n    }\n    if (ok) {\n      cout << \"YES\\n\";\n    }\n    else {\n      cout << \"NO\\n\";\n    }\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1603",
    "index": "B",
    "title": "Moderate Modular Mode",
    "statement": "YouKn0wWho has two \\textbf{even} integers $x$ and $y$. Help him to find an integer $n$ such that $1 \\le n \\le 2 \\cdot 10^{18}$ and $n \\bmod x = y \\bmod n$. Here, $a \\bmod b$ denotes the remainder of $a$ after division by $b$. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.",
    "tutorial": "If $x \\gt y$, then $x + y$ works, as $(x + y) \\bmod x = y \\bmod x = y$ and $y \\bmod (x + y) = y$. The challenge arrives when $x \\le y$. The later part of the editorial assumes that $x \\le y$. Claim $1$: $n$ can't be less than $x$. Proof: Assume that for some $n \\lt x$, $n \\bmod x = y \\bmod n$ is satisfied. Then $n \\bmod x = n$ but $y \\bmod n \\lt n$. So $n \\bmod x$ can't be equal to $y \\bmod n$ which is a contradiction. Claim $2$: $n$ can't be greater than $y$. Proof: Assume that for some $n \\gt y$, $n \\bmod x = y \\bmod n$ is satisfied. Then $n \\bmod x \\lt x$ but $y \\bmod n = y \\ge x$. So $n \\bmod x$ can't be equal to $y \\bmod n$ which is a contradiction. So $n$ should be in between $x$ and $y$. But what is the exact value of $n$? Let's solve this intuitively. Consider a line on the $X$ axis. Imagine you are at position $0$. You will start jumping from $0$ to $y$ with a step of length $x$. So there will be a position from where if you jump one more time it will exceed $y$. This position is $p = y - y \\bmod x$. From this position let's go to $y$ in exactly $2$ steps! Notice that $y - p$ is guaranteed to be even as $x$ and $y$ both are even. So we need to jump with a length of $\\frac{y - p}{2}$ and we will jump to the position $t = p + \\frac{y - p}{2}$. And voila! $t$ is our desired $n$ because $t \\bmod x = \\frac{y - p}{2}$ and $y \\bmod t = (y - p) - \\frac{y - p}{2} = \\frac{y - p}{2}$. To be precise, $n = t = y - \\frac{y \\bmod x}{2}$. Here is a cute illustration for you:",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t; cin >> t;\n  while (t--) {\n    int x, y; cin >> x >> y;\n    if (x <= y) {\n      cout << y - y % x / 2 << '\\n';\n    }\n    else {\n      cout << x + y << '\\n';\n    }\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1603",
    "index": "C",
    "title": "Extreme Extension",
    "statement": "For an array $b$ of $n$ integers, the extreme value of this array is the minimum number of times (possibly, zero) the following operation has to be performed to make $b$ \\textbf{non-decreasing}:\n\n- Select an index $i$ such that $1 \\le i \\le |b|$, where $|b|$ is the current length of $b$.\n- Replace $b_i$ with two elements $x$ and $y$ such that $x$ and $y$ both are \\textbf{positive} integers and $x + y = b_i$.\n- This way, the array $b$ changes and the next operation is performed on this modified array.\n\nFor example, if $b = [2, 4, 3]$ and index $2$ gets selected, then the possible arrays after this operation are $[2, \\underline{1}, \\underline{3}, 3]$, $[2, \\underline{2}, \\underline{2}, 3]$, or $[2, \\underline{3}, \\underline{1}, 3]$. And consequently, for this array, this single operation is enough to make it non-decreasing: $[2, 4, 3] \\rightarrow [2, \\underline{2}, \\underline{2}, 3]$.\n\nIt's easy to see that every array of positive integers can be made non-decreasing this way.\n\nYouKn0wWho has an array $a$ of $n$ integers. Help him find the sum of extreme values of all nonempty subarrays of $a$ modulo $998\\,244\\,353$. If a subarray appears in $a$ multiple times, its extreme value should be counted the number of times it appears.\n\nAn array $d$ is a subarray of an array $c$ if $d$ can be obtained from $c$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "Let's find out how to calculate the extreme value of an array $a$ of $n$ integers. It turns out that a greedy solution exists! Consider the rightmost index $i$ such that $a_i \\gt a_{i + 1}$. So we must split $a_i$ into new (let's say $k$) elements $1 \\le b_1 \\le b_2 \\le \\ldots \\le b_k \\le a_{i+1}$ such that $b_1 + b_2 + \\ldots + b_k = a_i$ . Notice that $k \\ge \\left\\lceil \\frac{a_i}{a_{i+1}} \\right\\rceil$ because $b_k \\le a_{i+1}$. But it is always optimal to make $b_1$ as large as possible. It is not hard to see that the smaller the $k$, the bigger the $b_1$ we can achieve. So let's set $k = \\left\\lceil \\frac{a_i}{a_{i+1}} \\right\\rceil$. Now, notice that $b_1 \\le \\left\\lfloor \\frac{a_i}{k} \\right\\rfloor$. So let's set $b_1 = \\left\\lfloor \\frac{a_i}{k} \\right\\rfloor = \\left\\lfloor \\frac{a_i}{\\left\\lceil \\frac{a_i}{a_{i+1}} \\right\\rceil} \\right\\rfloor$. So we have performed $k - 1 = \\left\\lceil \\frac{a_i}{a_{i+1}} \\right\\rceil - 1$ operations and will solve the problem analogously for the previous indices after replacing $a_i$ by $[b_1, b_2, \\ldots, b_k]$. To sum it all up, we can calculate the extreme value in the following procedure: Iterator from $i = n - 1$ to $1$. Add $\\left\\lceil \\frac{a_i}{a_{i+1}} \\right\\rceil - 1$ to the answer. Set $a_i = \\left\\lfloor \\frac{a_i}{\\left\\lceil \\frac{a_i}{a_{i+1}} \\right\\rceil} \\right\\rfloor$. Pretty elegant! Let's call it elegant procedure from now on. So we can calculate the extreme value of an array of $n$ integers in $\\mathcal{O}{(n)}$. To solve it for all subarrays in $\\mathcal{O}{(n^2)}$, we need to fix a prefix and solve each suffix of this prefix in a total of $\\mathcal{O}{(n)}$ operations. We can do that easily because the procedure to calculate the extreme values starts from the end, so we can sum up the contributions on the run. How to solve the problem faster? Think dp. Let $dp(i, x)$ be the count of subarrays $a[i;j]$ such that $i \\le j$ and after the elegant procedure $x$ becomes the first element of the final version of that subarray. We only care about the $x$s for which $dp(i, x)$ is non-zero. How many different $x$ is possible? Well, it can be up to $10^5$, right? Wrong! Let's go back to our elegant procedure once again. For the time being, let's say for all $x = 1$ to $10^5$, $dp(i + 1, x)$ is non-zero. So for each $x$, we will add $dp(i + 1, x)$ to $dp(i, \\left\\lfloor \\frac{a_i}{\\left\\lceil \\frac{a_i}{x} \\right\\rceil} \\right\\rfloor)$. But there can be at most $2 \\sqrt{m}$ distinct values in the sequence $\\left\\lfloor \\frac{m}{1} \\right\\rfloor, \\left\\lfloor \\frac{m}{2} \\right\\rfloor, \\ldots, \\left\\lfloor \\frac{m}{m} \\right\\rfloor$. Check this for a proof. So there can be $\\mathcal{O}{(\\sqrt{10^5})}$ distinct $x$s for which $dp(i, x)$ is non-zero. So we can solve this dp in $\\mathcal{O}{(n \\cdot \\sqrt{10^5}})$. To optimize the space-complexity we can observe that we only need the dp values of $i + 1$. So we can use only two arrays to maintain everything. Check my solution for more clarity. To get the final answer, we will use the contribution technique. To be precise, for each $(i + 1, x)$ we will add $i \\cdot dp(i + 1, x) \\cdot (\\left\\lceil \\frac{a_i}{a_{i+1}} \\right\\rceil - 1)$ to our answer and its not hard to see this. Here, $i \\cdot dp(i + 1, x)$ is the number of arrays where the $i$-th element will be set to $x$ in the elegant procedure and $\\left\\lceil \\frac{a_i}{a_{i+1}} \\right\\rceil - 1$ is the number of operations that will be performed for the same. Overall time complexity will be $\\mathcal{O}{(n \\cdot \\sqrt{10^5}})$ and space complexity will be $\\mathcal{O}(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int N = 1e5 + 9, mod = 998244353;\nvector<int> v[2];\nint dp[2][N];\nint a[N];\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t; cin >> t;\n  while (t--) {\n    int n; cin >> n;\n    for (int i = 1; i <= n; i++) {\n      cin >> a[i];\n    }\n    long long ans = 0;\n    for (int i = n; i >= 1; i--) {\n      int k = i & 1;\n      v[k].push_back(a[i]);\n      dp[k][a[i]] = 1;\n      int last = a[i];\n      for (auto x: v[k ^ 1]) {\n        int y = dp[k ^ 1][x];\n        int split = (a[i] + x - 1) / x;\n        int st = a[i] / split;\n        ans += 1LL * (split - 1) * y * i;\n        dp[k][st] += y;\n        if (last != st) {\n          v[k].push_back(st), last = st;\n        }\n      }\n      for (auto x: v[k ^ 1]) dp[k ^ 1][x] = 0;\n      v[k ^ 1].clear();\n      ans %= mod;\n    }\n    cout << ans << '\\n';\n    for (auto x: v[0]) dp[0][x] = 0;\n    for (auto x: v[1]) dp[1][x] = 0;\n    v[0].clear(); v[1].clear();\n  }\n  return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1603",
    "index": "D",
    "title": "Artistic Partition",
    "statement": "For two positive integers $l$ and $r$ ($l \\le r$) let $c(l, r)$ denote the number of integer pairs $(i, j)$ such that $l \\le i \\le j \\le r$ and $\\operatorname{gcd}(i, j) \\ge l$. Here, $\\operatorname{gcd}(i, j)$ is the greatest common divisor (GCD) of integers $i$ and $j$.\n\nYouKn0wWho has two integers $n$ and $k$ where $1 \\le k \\le n$. Let $f(n, k)$ denote the minimum of $\\sum\\limits_{i=1}^{k}{c(x_i+1,x_{i+1})}$ over all integer sequences $0=x_1 \\lt x_2 \\lt \\ldots \\lt x_{k} \\lt x_{k+1}=n$.\n\nHelp YouKn0wWho find $f(n, k)$.",
    "tutorial": "For now, let $c(l, r)$ denote the number of integer pairs $(i, j)$ such that $l \\le i \\lt j \\le r$ (instead of $i \\le j$) and $\\operatorname{gcd}(i, j) \\ge l$. So we can add $n$ to $f(n, k)$ in the end. We can construct a straightforward dp where $f(n, k) = \\min\\limits_{i = 1}^{n}{(f(i - 1, k - 1)+c(i, n))}$. As a straightforward implementation of $c(l, r)$ takes $\\mathcal{O}(n^2 \\log_2 n)$ time, the total complexity of finding $f(n, k)$ will be $\\mathcal{O}(n^5 \\log_2 n)$ which is quite shameful. Let's see how to do better. Tiny Observation: $c(x, 2 \\cdot x - 1) = 0$. It's easy to see why it holds. Cute Observation: $f(n, k) = 0$ when $k \\gt \\log_2 n$. Proof: Let $L = \\log_2 n$. Following the tiny observation, we can split the numbers as $[1, 1], [2, 3], [4, 7], \\ldots, [2^{L - 1}, 2^L - 1], [2^L, n]$ without spending a single penny. Now we can solve $f(n, k)$ in $\\mathcal{O}(n^4 \\log_2^2 n)$ which is still shameful. So we just have to find $f(n, k)$ for $1 \\le n \\le 10^5$ and $1 \\le k \\le 17$. Let's optimize the calculation for $c(l, r)$ . $c(l, r) = \\sum\\limits_{i=l}^{r}\\sum\\limits_{j=i+1}^{r}{[\\gcd(i, j) \\ge l]}$ $=\\sum\\limits_{k=l}^{r}\\sum\\limits_{i=l}^{r}\\sum\\limits_{j=i+1}^{r}{[\\gcd(i, j) = k]}$ $=\\sum\\limits_{k=l}^{r}\\sum\\limits_{i=l, k | i}^{r}\\sum\\limits_{j=i+1, k | j}^{r}{[\\gcd(i, j) = k]}$ $=\\sum\\limits_{k=l}^{r}\\sum\\limits_{i=1}^{\\left\\lfloor \\frac{r}{k} \\right\\rfloor}\\sum\\limits_{j=i+1}^{\\left\\lfloor \\frac{r}{k} \\right\\rfloor}{[\\gcd(i \\cdot k, j \\cdot k) = k]}$ $=\\sum\\limits_{k=l}^{r}\\sum\\limits_{i=1}^{\\left\\lfloor \\frac{r}{k} \\right\\rfloor}\\sum\\limits_{j=i+1}^{\\left\\lfloor \\frac{r}{k} \\right\\rfloor}{[\\gcd(i, j) = 1]}$ $=\\sum\\limits_{k=l}^{r}\\sum\\limits_{i=1}^{\\left\\lfloor \\frac{r}{k} \\right\\rfloor}{\\phi(i)}$ $=\\sum\\limits_{k=l}^{r}{p(\\left\\lfloor \\frac{r}{k} \\right\\rfloor)}$ But notice that there can be at most $2 \\sqrt{m}$ distinct values in the sequence $\\left\\lfloor \\frac{m}{1} \\right\\rfloor, \\left\\lfloor \\frac{m}{2} \\right\\rfloor, \\ldots, \\left\\lfloor \\frac{m}{m} \\right\\rfloor$. Check this for a proof. So we can calculate $c(l, r)$ in $\\mathcal{O}(\\sqrt{n})$ which improves our solution to $\\mathcal{O}(n^2 \\sqrt{n})$. But notice that as $c(l, r) =\\sum\\limits_{k=l}^{r}{p(\\left\\lfloor \\frac{r}{k} \\right\\rfloor)}$ we can precalculate the suffix sums for each $r=1$ to $n$ over all distinct values of $\\left\\lfloor \\frac{r}{k} \\right\\rfloor$ and then calculate $c(l, r)$ in $\\mathcal{O}(1)$. This preprocessing will take $\\mathcal{O}(n \\sqrt{n})$ time and $\\mathcal{O}(n \\sqrt{n})$ memory. That means we can solve our problem $\\mathcal{O}(n^2 + n\\sqrt{n})$ which is promising. Critical Observation: $c(l, r)$ satisfies quadrangle inequality, that is $c(i,k)+c(j,l)\\le c(i,l)+c(j,k)$ for $i\\le j \\le k \\le l$. Proof: Let $f(i, j, r) =\\sum\\limits_{k=i}^{j}{p(\\left\\lfloor \\frac{r}{k} \\right\\rfloor)}$. Here, $c(i, l) + c(j, k)= f(i, l, l) + f(j, k, k)$ $= (f(i, j - 1, l) + f(j, l, l)) + (f(i, k, k) - f(i, j - 1, k))$ $=f(i, j - 1, l) + c(j, l) + c(i, k) - f(i, j - 1, k)$ $= c(i, k) + c(j, l) + f(i, j - 1, l) - f(i, j - 1, k)$ You can learn more about quadrangle inequality and how it is useful from here. Read it because I won't describe why it helps us here. This suggests that we can solve this problem using Divide and Conquer DP or 1D1D DP which will optimize our $\\mathcal{O}(n^2)$ part to $\\mathcal{O}(n \\log_2^2 n)$. To solve for multiple queries we can just precalculate $f(n, k)$ for $1 \\le n \\le 10^5$ and $1 \\le k \\le 17$. Overall complexity: $\\mathcal{O}(n \\log_2^2 n + n\\sqrt{n})$ where $n = 10^5$. This problem can also be solved using Divide and Conquer DP and by calculating $c(l, r)$ in $\\mathcal{O}(\\sqrt{r-l})$ in each level which runs pretty fast in practice (for $n = 5 \\cdot 10^5$, it takes less than 3s) but I don't have a rigorous upper bound on the time complexity. Check out my solution for more clarity.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int N = 1e5 + 9;\nconst long long inf = 1e12;\nusing ll = long long;\nint phi[N];\nvoid totient() {\n  for (int i = 1; i < N; i++) phi[i] = i;\n  for (int i = 2; i < N; i++) {\n    if (phi[i] == i) {\n      for (int j = i; j < N; j += i) phi[j] -= phi[j] / i;\n    }\n  }\n}\nll a[N];\nll c(int l, int r) {\n  if (l > r) return inf;\n  ll ans = 0;\n  for (int i = l, last; i <= r; i = last + 1) {\n    last = r / (r / i);\n    int x = 0;\n    if (i >= l) x = last - i + 1;\n    else if (last >= l) x = last - l + 1;\n    ans += a[r / i] * x;\n  }\n  return ans;\n}\nll dp[N][17];\nvoid yo(int i, int l, int r, int optl, int optr) {\n  if(l > r) return;\n  int mid = (l + r) / 2;\n  dp[mid][i] = inf;\n  int opt = optl;\n  ll cost = c(min(mid, optr) + 1, mid);\n  for(int k = min(mid, optr); k >= optl ; k--) {\n    ll cc = dp[k][i - 1] + cost;\n    if (cc <= dp[mid][i]) {\n      dp[mid][i] = cc;\n      opt = k;\n    }\n    if (k <= mid) {\n      if (cost == inf) cost = a[mid / k];\n      else cost += a[mid / k];\n    }\n  }\n  yo(i, l, mid - 1, optl, opt);\n  yo(i, mid + 1, r, opt, optr);\n}\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  totient();\n  for (int i = 1; i < N; i++) {\n    a[i] = a[i - 1] + phi[i];\n  }\n  int n = 100000;\n  dp[0][0] = 0;\n  for (int i = 1; i <= n; i++) {\n    dp[i][0] = inf;\n  }\n  for(int i = 1; i <= n; i++) dp[i][1] = 1LL * i * (i + 1) / 2;\n  for(int i = 2; i <= 16; i++) yo(i, 1, n, 1, n);\n  int q; cin >> q;\n  while (q--) {\n    int n, k; cin >> n >> k;\n    if (k >= 20 or (1 << k) > n) {\n      cout << n << '\\n';\n    }\n    else {\n      cout << dp[n][k] << '\\n';\n    }\n  }\n  return 0;\n}",
    "tags": [
      "divide and conquer",
      "dp",
      "number theory"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1603",
    "index": "E",
    "title": "A Perfect Problem",
    "statement": "A sequence of integers $b_1, b_2, \\ldots, b_m$ is called good if $max(b_1, b_2, \\ldots, b_m) \\cdot min(b_1, b_2, \\ldots, b_m) \\ge b_1 + b_2 + \\ldots + b_m$.\n\nA sequence of integers $a_1, a_2, \\ldots, a_n$ is called perfect if every non-empty subsequence of $a$ is good.\n\nYouKn0wWho has two integers $n$ and $M$, $M$ is prime. Help him find the number, modulo $M$, of perfect sequences $a_1, a_2, \\ldots, a_n$ such that $1 \\le a_i \\le n + 1$ for each integer $i$ from $1$ to $n$.\n\nA sequence $d$ is a subsequence of a sequence $c$ if $d$ can be obtained from $c$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "Let's go deeper into the properties of perfect sequences. Observation $1$: If a sorted sequence $a_1, a_2, \\ldots, a_n$ is perfect then all its permutations are also perfect. Actually, it's very easy to see that as the order doesn't matter. So we will work on the sorted version of the sequence. Observation $2$: The sorted sequence $a_1, a_2, \\ldots, a_n$ is perfect iff all its subarrays are good. Proof: Let's fix the $\\min$ and $\\max$ of a subsequence. As $\\min \\cdot \\max$ is fixed, the worst case happens when we insert as many elements as possible in this subsequence which are in between $\\min$ and $\\max$ as we are comparing $\\min \\cdot \\max$ with the sum, and the worst case is a subarray of this sorted sequence! Now we will go one step further. Observation $3$: The sorted sequence $a_1, a_2, \\ldots, a_n$ is perfect iff all its prefixes are good. Proof: The condition essentially means that $a_1 \\cdot a_i \\ge a_1 + a_2 + \\ldots +a_i$ for all $1 \\le i \\le n$. Imagine that its true. Now we will prove that the sequence is perfect. Consider a subarray $[i; j]$. $a_i \\cdot a_j \\ge a_1 \\cdot a_j$ $\\ge a_1 + a_2 + \\ldots + a_j$ $\\ge a_i + a_{i+1} + \\ldots +a_j$. That means all subarrays are good. And following observation $2$, it indicates that the sequence is perfect. And it is necessary that all the prefixes should be good because they are subarrays after all which proves the iff condition. Now let's exploit the fact that all $a_i$ are $\\le n+1$. Let's remind again that we are considering the sorted sequences for now. Observation $4$: $a_k \\ge k$ is required for any $k$. Proof: If $a_k < k$, $a_1 + a_2 + \\ldots + a_k \\ge a_1 + a_1 + \\ldots + a_1 \\ge a_1 \\cdot k \\gt a_1 \\cdot a_k$ (as $k \\gt a_k$) which violates the good condition. Observation $5$: If $a_k = k$, then all $a_i = k$ for $i \\le k$. Proof: $a_1 \\cdot a_k = a_1 \\cdot k \\ge a_1 + a_2 + \\ldots + a_k$. This means $(a_1 - a_1) + (a_2 - a_1) + \\ldots + (a_k - a_1) \\le 0$. But as all $a_i \\ge a_1$, this can only happen when all $a_i = a_1$. But as $a_k = k$, consequently, all $a_i$ should be $k$. So $a_n$ can be either $n$ or $n+1$. If $a_n=n$ then according to observation $5$ there is only one such sequence. From now on, let's consider $a_n = n + 1$. So $a_1 \\cdot (n + 1) \\ge a_1 + a_2 + \\ldots a_n$. But this formulation is a bit hard to work on. So now we will make a move which I would like to call a programmer move. That is, the equation is equivalent to $(a_1 - a_1) + (a_2 - a_1) + \\ldots + (a_n - a_1) \\le a_1$. Following observation $3$, its necessary that $a_1 \\cdot a_i \\ge a_1 + a_2 + \\ldots + a_i$ for all $i$. Observation $6$: if $a_n=n+1$ and $a_i \\ge i+1$, then the prefix $a_1, a_2, \\ldots, a_i$ is automatically good if the whole sorted sequence $a_1, a_2, \\ldots, a_n$ is good. Proof: If the whole sequence is good then, $(a_1 - a_1) + (a_2 - a_1) + \\ldots + (a_n - a_1) \\le a_1$. Now, $(a_1 - a_1) + (a_2 - a_1) + \\ldots + (a_i - a_1) \\le (a_1 - a_1) + (a_2 - a_1) + \\ldots + (a_n - a_1) \\le a_1$. So, $a_1+a_2+\\ldots+a_i \\le a_1 \\cdot (i+1) \\le a_1 \\cdot a_i$ So the prefix is good! Let's recap that $a_i \\ge i$ is required(observation $4$), if $a_i \\ge i + 1$, then $a_1, a_2, \\ldots, a_i$ is automatically good (observation $6$) and $a_i = i$ is only possible when $i = a_1$(observation $5$). So the necessary and sufficient conditions for the sorted sequence $a$ to be perfect assuming $a_n = n + 1$ are - For $i \\le a_1$, $a_1 \\le a_i \\le n + 1$ For $i \\gt a_1$, $i + 1 \\le a_i \\le n + 1$ $(a_1 - a_1) + (a_2 - a_1) + \\ldots + (a_n - a_1) \\le a_1$ Notice that we need the answer considering all such sequences, not only sorted sequences, but it is not hard to track that using basic combinatorics. So let's fix the smallest number $a_1$ and subtract $a_1$ from everything. So we need to count the number of sequences $b_1, b_2, \\ldots, b_n$ such that - $0 \\le b_i \\le n + 1 - a_1$ $b_1 + b_2 + \\ldots b_n \\le a_1$ There is at least $1$ number $\\ge n+1-a_1$, at least $2$ numbers $\\ge n-a_1$, $\\ldots$, at least $n - a_1$ numbers $\\ge 2$ (this condition is basically the intuition of when $i \\le a_1$, $a_1 \\le a_i \\le n + 1$ and when $i \\gt a_1$, $i + 1 \\le a_i \\le n + 1$). Let's formulate a dp in top-down manner. We will choose $b_i$ going from $n+1-a_1$ to $0$. Let $\\operatorname{dp}(i, sum, k) =$ number of sequences when we already chose $i$ elements, the total sum of the selected elements $= sum$ and we will select $k$ now. So if we choose $cnt$ numbers of $k$, then the transition is something like $\\operatorname{dp}(i, sum, k)$ += $\\frac{\\operatorname{dp}(i + cnt, sum + cnt \\cdot k, k - 1)}{cnt!}$. And at the base case, when $i=n$, return $n!$. The factorial terms are easy to make sense of because we are considering all perfect sequences, not only sorted ones. Check my solution for more clarity. This dp will take $\\mathcal{O}(n^4 \\cdot \\log_2 n)$ for each $a_1$ ($\\log_2 n$ term is for harmonic series sum as $cnt \\le \\frac{a_1}{k}$) yielding a total of $\\mathcal{O}(n^5 \\cdot \\log_2 n)$. Observation $7$: If $a_1 \\lt n - 2 \\cdot \\sqrt{n}$, then no perfect sequences are possible. Proof: Assume that $a_1 \\lt n - 2 \\cdot \\sqrt{n}$, or $n - a_1 \\gt 2 \\cdot \\sqrt{n}$, or $n - a_1 \\gt 2 \\cdot \\sqrt{n}$. But because of the condition $3$, there will be at least at least $1$ number $\\ge n - 2 \\cdot \\sqrt{n} + 2$, at least $2$ numbers $\\ge n - 2 \\cdot \\sqrt{n} + 1$, $\\ldots$, at least $n - 2 \\cdot \\sqrt{n} + 1$ numbers $\\ge 2$. But that clearly means that $b_1 + b_2 + \\ldots b_n \\gt n + 1 \\gt a_1$ which is a contradiction. So we need to traverse $\\mathcal{O}(\\sqrt{n})$ $a_1$s which also means in the dp $k$ is also $\\mathcal{O}(\\sqrt{n})$. So the total time complexity will be $\\mathcal{O}(n^3 \\sqrt{n} \\log_2 n)$ or faster but with very low constant that it will work instantly! Phew, such a long editorial. I need to take a break and explore the world sometimes...",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int N = 205;\nint mod;\n \nint power(long long n, long long k) {\n  int ans = 1 % mod; n %= mod; if (n < 0) n += mod;\n  while (k) {\n    if (k & 1) ans = (long long) ans * n % mod;\n    n = (long long) n * n % mod;\n    k >>= 1;\n  }\n  return ans;\n}\nint dp[N][N][40], fac[N], ifac[N];\nint vis[N][N][40];\nint n, a1;\n/*\nnumber of solutions to the equation b1 + b2 + ... bn <= a1\ns.t. 0<=bi<=n+1-a1 \nand there is at least 1 number >= n + 1 - a1, \nat least 2 numbers >= (n - a1), ..., at least (n - a1) numbers >= 2\n*/\nint yo(int i, int sum, int k) { // k <= 2 * sqrt(n)\n  if (i == n) return fac[n];\n  if (k == 0) return 1LL * fac[n] * ifac[n - i] % mod;\n  if (vis[i][sum][k] == a1) return dp[i][sum][k];\n  vis[i][sum][k] = a1;\n  int &ans = dp[i][sum][k];\n  ans = 0;\n  int r = (a1 - sum) / k;\n  for (int cnt = r; cnt >= 0; cnt--) {\n    if (k > 1 and i + cnt < n - a1 + 1 - k + 1) continue;\n    ans += 1LL * yo(i + cnt, sum + cnt * k, k - 1) * ifac[cnt] % mod;\n    ans %= mod;\n  }\n  return ans;\n}\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  cin >> n >> mod;\n  fac[0] = 1;\n  ifac[0] = 1;\n  for (int i = 1; i < N; i++) {\n    fac[i] = 1LL * fac[i - 1] * i % mod;\n    ifac[i] = power(fac[i], mod - 2);\n  }\n  int ans = 0;\n  int lim = 2 * sqrt(n) + 1;\n  for (a1 = max(1, n - lim); a1 <= n; a1++) {\n    ans += yo(0, 0, n + 1 - a1);\n    ans %= mod;\n  }\n  ans %= mod;\n  cout << ans << '\\n';\n  return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1603",
    "index": "F",
    "title": "October 18, 2017",
    "statement": "It was October 18, 2017. Shohag, a melancholic soul, made a strong determination that he will pursue Competitive Programming seriously, by heart, because he found it fascinating. Fast forward to 4 years, he is happy that he took this road. He is now creating a contest on Codeforces. He found an astounding problem but has no idea how to solve this. Help him to solve the final problem of the round.\n\nYou are given three integers $n$, $k$ and $x$. Find the number, modulo $998\\,244\\,353$, of integer sequences $a_1, a_2, \\ldots, a_n$ such that the following conditions are satisfied:\n\n- $0 \\le a_i \\lt 2^k$ for each integer $i$ from $1$ to $n$.\n- There is no non-empty subsequence in $a$ such that the bitwise XOR of the elements of the subsequence is $x$.\n\nA sequence $b$ is a subsequence of a sequence $c$ if $b$ can be obtained from $c$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "When $x = 0$, we need to count the number of sequences $(a_1, a_2, \\ldots, a_n)$, such that the $a_i$s are linearly independent. Clearly, for $n>k$ there are no such sequences, and for $n \\le k$, the answer is $(2^k-1)\\cdot(2^k-2)\\cdot \\ldots \\cdot (2^k - 2^{n-1})$, as $a_i$ can be any element not generated by the elements $a_1, a_2, \\ldots, a_{i-1}$, and they generate exactly $2^{i-1}$ elements. Now, let's deal with the case $x>0$. It's easy to see that the exact value of $x$ doesn't matter here, it's easy to construct a bijection between such sequences for this problem and such sequences for the case $x = 1$, by change of basis from the one which has $x$ as the first element to one which has $1$ as the first element. So from now on $x = 1$. We will show that the answer for given $n, k$ is $(2^k)^n \\cdot 2^{k-1} - (2^{k-1})^n \\cdot (2^{k-1}-1)\\cdot 2^{k-2} + (2^{k-2})^n \\cdot (2^{k-1}-1)(2^{k-2}-1)\\cdot 2^{k-3} \\ldots$ More generally, it's $\\sum_{i = 0}^{k}((-1)^i \\cdot (2^{k-i})^n \\cdot \\prod_{j = 0}^{i-1} (2^{k-j-1}-1) 2^{k-i-1} )$ This is easy to calculate in $O(k + \\log{n})$, by calculating prefix products $P_i = \\prod_{j = 0}^{i-1} (2^{k-j-1}-1)$ in $O(k)$, and finding $2^n$ in $O(\\log{n})$ and its powers in $O(k)$. Now, let's prove the formula. It's possible to prove the formula by some inclusion-exclusion arguments, but here we will present a bit more combinatorial approach. Let's just look at $(2^{k-i})^n \\cdot \\prod_{j = 0}^{i-1} (2^{k-j-1}-1) 2^{k-i-1}$ and find some combinatorial interpretation for it. Let's consider a linear space of dimension $t$ (with $2^t$ elements), containing $1$. Consider all its subspaces of dimension $t-1$. Firstly, how many of them are there? Exactly $2^t-1$, each corresponding to the only nonzero element of the orthogonal complement of the subspace. It's easy to see that exactly $2^{t-1}-1$ of them will contain $1$, and other $2^{t-1}$ won't. Then, there is a natural representation of the number $\\prod_{j = 0}^{i-1} (2^{k-j-1}-1) 2^{k-i-1}$ - it's the number of sequences of spaces $(S_0, S_1, S_2, \\ldots, S_{i-1}, S_i)$, where: $S_0$ is the whole space of our problem, of dimension $k$, $S_0$ is the whole space of our problem, of dimension $k$, For $j$ from $1$ to $i-1$, $S_j$ is a subspace of $S_{j-1}$ of dimension $k-j$, containing $1$. For $j$ from $1$ to $i-1$, $S_j$ is a subspace of $S_{j-1}$ of dimension $k-j$, containing $1$. $S_i$ is a subspace of $S_{i-1}$ of dimension $k-i$, not containing $1$. $S_i$ is a subspace of $S_{i-1}$ of dimension $k-i$, not containing $1$. Then, $(2^{k-i})^n \\cdot \\prod_{j = 0}^{i-1} (2^{k-j-1}-1) 2^{k-i-1}$ is the number of sequences $(S_0, S_1, S_2, \\ldots, S_{i-1}, S_i, a)$, where sets $S$ are described as above, and all elements of $a$ lie in $S_i$ (as there are $2^{k-i}$ ways to choose each of them). This starts to resemble what we need... As in such structure, space generated by $a$ won't be able to contain $1$, and it's exactly the kind of arrays we are interested in. So, we want to show that the actual number of arrays from the statement is equal to the number of tuples $(S_0, S_1, S_2, \\ldots, S_{i-1}, S_i, a)$, where the tuple is counted with a plus sign for even $i$ and with a minus sign for odd $i$. It's enough to prove that each array $a$ will be counted exactly once this way (meaning that it will be in tuples taken with plus one more time than in tuples taken with a minus). Fine, let's consider an array $a$ such that subspace spanned by it doesn't contain $1$ and look at the sequences of sets $(S_0, S_1, S_2, \\ldots, S_{i-1}, S_i)$ such that $a$ is contained in $S_i$. If the subspace generated by $a$ is $T$, we just need all spaces to contain $T$. If size of $T$ is $t$, there is a bijection between such sequences and sequences $(S_0, S_1, S_2, \\ldots, S_{i-1}, S_i)$, where $S_0$ is the space orthogonal to subspace $T$, of dimension $k-t$, $S_0$ is the space orthogonal to subspace $T$, of dimension $k-t$, For $j$ from $1$ to $i-1$, $S_j$ is a subspace of $S_{j-1}$ of dimension $k-t-j$, containing $1$. For $j$ from $1$ to $i-1$, $S_j$ is a subspace of $S_{j-1}$ of dimension $k-t-j$, containing $1$. $S_i$ is a subspace of $S_{i-1}$ of dimension $k-t-i$, not containing $1$. $S_i$ is a subspace of $S_{i-1}$ of dimension $k-t-i$, not containing $1$. But the number of such sequences for a fixed $i$ is precisely $\\prod_{j = 0}^{i-1} (2^{k-t-j-1}-1) \\cdot 2^{k-t-i-1}$! So, we need to show that the sum of this (with correspondent signs) over $i$ from $0$ to $n-t$ is $1$. Let's replace $n-t$ by $n$, we need to show that $\\sum_{i = 0}^k ((-1)^i \\cdot 2^{k-i-1} \\cdot \\prod_{j = 0}^{i-1}(2^{k-j-1}-1) ) = 1$ This is easy to prove by induction, as after moving $2^{k-1}$ to the right side it's equivalent to $\\sum_{i = 1}^k ((-1)^i \\cdot 2^{k-i-1} \\cdot \\prod_{j = 0}^{i-1}(2^{k-j-1}-1) ) = (1 - 2^{k-1})$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int N = 1e7 + 9, mod = 998244353;\ntemplate <const int32_t MOD>\nstruct modint {\n  int32_t value;\n  modint() = default;\n  modint(int32_t value_) : value(value_) {}\n  inline modint<MOD> operator + (modint<MOD> other) const { int32_t c = this->value + other.value; return modint<MOD>(c >= MOD ? c - MOD : c); }\n  inline modint<MOD> operator - (modint<MOD> other) const { int32_t c = this->value - other.value; return modint<MOD>(c <    0 ? c + MOD : c); }\n  inline modint<MOD> operator * (modint<MOD> other) const { int32_t c = (int64_t)this->value * other.value % MOD; return modint<MOD>(c < 0 ? c + MOD : c); }\n  inline modint<MOD> & operator += (modint<MOD> other) { this->value += other.value; if (this->value >= MOD) this->value -= MOD; return *this; }\n  inline modint<MOD> & operator -= (modint<MOD> other) { this->value -= other.value; if (this->value <    0) this->value += MOD; return *this; }\n  inline modint<MOD> & operator *= (modint<MOD> other) { this->value = (int64_t)this->value * other.value % MOD; if (this->value < 0) this->value += MOD; return *this; }\n  inline modint<MOD> operator - () const { return modint<MOD>(this->value ? MOD - this->value : 0); }\n  modint<MOD> pow(uint64_t k) const { modint<MOD> x = *this, y = 1; for (; k; k >>= 1) { if (k & 1) y *= x; x *= x; } return y; }\n  modint<MOD> inv() const { return pow(MOD - 2); }  // MOD must be a prime\n  inline modint<MOD> operator /  (modint<MOD> other) const { return *this *  other.inv(); }\n  inline modint<MOD> operator /= (modint<MOD> other)       { return *this *= other.inv(); }\n  inline bool operator == (modint<MOD> other) const { return value == other.value; }\n  inline bool operator != (modint<MOD> other) const { return value != other.value; }\n  inline bool operator < (modint<MOD> other) const { return value < other.value; }\n  inline bool operator > (modint<MOD> other) const { return value > other.value; }\n};\ntemplate <int32_t MOD> modint<MOD> operator * (int64_t value, modint<MOD> n) { return modint<MOD>(value) * n; }\ntemplate <int32_t MOD> modint<MOD> operator * (int32_t value, modint<MOD> n) { return modint<MOD>(value % MOD) * n; }\ntemplate <int32_t MOD> istream & operator >> (istream & in, modint<MOD> &n) { return in >> n.value; }\ntemplate <int32_t MOD> ostream & operator << (ostream & out, modint<MOD> n) { return out << n.value; }\n \nusing mint = modint<mod>;\n \nmint pw[N];\nmint genius(int n, int k) {\n  if (k == 0) return 1;\n  vector<mint> c(k, 0), d(k + 1, 0);\n  d[k] = 1;\n  for (int i = k - 1; i >= 0; i--) {\n    c[i] = pw[i] * d[i + 1];\n    d[i] = (pw[i] - 1) * d[i + 1];\n  }\n  mint ans = 0, pwn = mint(2).pow(n), cur = 1;\n  for (int i = 0; i < k; i++) {\n    ans += ((k - 1 - i) & 1 ? mod - 1 : 1) * c[i] * cur;\n    cur *= pwn;\n  }\n  return ans;\n}\nmint f(int n, int k) {\n  if (k == 0 or n > k) return 0;\n  mint ans = 1;\n  for (int i = 0; i < n; i++) {\n    ans *= pw[k] - pw[i];\n  }\n  return ans;\n}\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  pw[0] = 1;\n  for (int i = 1; i < N; i++) {\n    pw[i] = pw[i - 1] * 2;\n  }\n  int t; cin >> t;\n  while (t--) {\n    int n, k, x; cin >> n >> k >> x;\n    if (x) {\n      cout << genius(n, k) << '\\n';\n    }\n    else {\n      cout << f(n, k) << '\\n';\n    }\n  }\n  return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1604",
    "index": "A",
    "title": "Era",
    "statement": "Shohag has an integer sequence $a_1, a_2, \\ldots, a_n$. He can perform the following operation any number of times (possibly, zero):\n\n- Select any positive integer $k$ (it can be different in different operations).\n- Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert $k$ into the sequence at this position.\n- This way, the sequence $a$ changes, and the next operation is performed on this changed sequence.\n\nFor example, if $a=[3,3,4]$ and he selects $k = 2$, then after the operation he can obtain one of the sequences $[\\underline{2},3,3,4]$, $[3,\\underline{2},3,4]$, $[3,3,\\underline{2},4]$, or $[3,3,4,\\underline{2}]$.\n\nShohag wants this sequence to satisfy the following condition: for each $1 \\le i \\le |a|$, $a_i \\le i$. Here, $|a|$ denotes the size of $a$.\n\nHelp him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.",
    "tutorial": "If $a_i \\gt i$ for some position $i$, then we need to insert at least $a_i - i$ new small elements before this position. Let $m = max(0, \\max\\limits_{i = 1}^{n}{(a_i - i)})$. So we need at least $m$ operations. But its not hard to see that $m$ operations are enough. For example, you can insert $m$ $1$s at the beginning of the sequence. This way, all elements will be shifted by $m$ positions, and consequently, will satisfy that $a_i \\le i$ for each valid $i$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint main() {\n  int t; cin >> t;\n  while (t--) {\n    int n; cin >> n;\n    int ans = 0;\n    for (int i = 1; i <= n; i++) {\n      int k; cin >> k;\n      ans = max(ans, k - i);\n    }\n    cout << ans << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1604",
    "index": "B",
    "title": "XOR Specia-LIS-t",
    "statement": "YouKn0wWho has an integer sequence $a_1, a_2, \\ldots a_n$. Now he will split the sequence $a$ into one or more consecutive subarrays so that each element of $a$ belongs to exactly one subarray. Let $k$ be the number of resulting subarrays, and $h_1, h_2, \\ldots, h_k$ be the lengths of the longest increasing subsequences of corresponding subarrays.\n\nFor example, if we split $[2, 5, 3, 1, 4, 3, 2, 2, 5, 1]$ into $[2, 5, 3, 1, 4]$, $[3, 2, 2, 5]$, $[1]$, then $h = [3, 2, 1]$.\n\nYouKn0wWho wonders if it is possible to split the sequence $a$ in such a way that the bitwise XOR of $h_1, h_2, \\ldots, h_k$ is equal to $0$. You have to tell whether it is possible.\n\nThe longest increasing subsequence (LIS) of a sequence $b_1, b_2, \\ldots, b_m$ is the longest sequence of valid indices $i_1, i_2, \\ldots, i_k$ such that $i_1 \\lt i_2 \\lt \\ldots \\lt i_k$ and $b_{i_1} \\lt b_{i_2} \\lt \\ldots \\lt b_{i_k}$. For example, the LIS of $[2, 5, 3, 3, 5]$ is $[2, 3, 5]$, which has length $3$.\n\nAn array $c$ is a subarray of an array $b$ if $c$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "What happens if we split the sequence into subarrays of length $1$?. Yes, if $n$ is even, the bitwise XOR will be $0$ as there will be an even number of $1$s. If $n$ is odd we can't do the same. But what if there is an index $i$ such that $a_i \\ge a_{i + 1}$? What if we use these two indices as a single subarray as it has LIS of length $1$ and take other indices as single subarrays? Yeah, again, there will be an even number of $1$s which will yield a bitwise XOR of $0$. What we are left with are strictly increasing sequences of odd lengths. Notice that any subarray of length $l$ has LIS of length $l$ here. So we need to find a sequence $b_1, b_2, \\ldots, b_k$ such that $b_1 + b_2 + \\ldots + b_k = n$ and $b_1 \\oplus b_2 \\oplus \\ldots \\oplus b_k = 0$ where $n$ is odd. Is it possible to find such a sequence? Pause and think. Hint: think about the last bit of each $b_i$. If XOR is $0$, then there will be an even number of $b_i$s such that its last bit is $1$. But then the sum will be even. But here the sum $n$ is odd, which produces a contradiction. So in the last case, it is not possible to find such a split.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t; cin >> t;\n  while (t--) {\n    int n; cin >> n;\n    vector<int> a(n + 1);\n    bool inc = true;\n    for (int i = 1; i <= n; i++) {\n      cin >> a[i];\n      inc &= a[i] > a[i - 1];\n    }\n    if (n % 2 == 0 or !inc) {\n      cout << \"YES\\n\";\n    }\n    else {\n      cout << \"NO\\n\";\n    }\n  }\n  return 0;\n}",
    "tags": [],
    "rating": 1100
  },
  {
    "contest_id": "1605",
    "index": "A",
    "title": "A.M. Deviation",
    "statement": "A number $a_2$ is said to be the arithmetic mean of two numbers $a_1$ and $a_3$, if the following condition holds: $a_1 + a_3 = 2\\cdot a_2$.\n\nWe define an arithmetic mean deviation of three numbers $a_1$, $a_2$ and $a_3$ as follows: $d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \\cdot a_2|$.\n\nArithmetic means a lot to Jeevan. He has three numbers $a_1$, $a_2$ and $a_3$ and he wants to minimize the arithmetic mean deviation $d(a_1, a_2, a_3)$. To do so, he can perform the following operation any number of times (possibly zero):\n\n- Choose $i, j$ from $\\{1, 2, 3\\}$ such that $i \\ne j$ and increment $a_i$ by $1$ and decrement $a_j$ by $1$\n\nHelp Jeevan find out the minimum value of $d(a_1, a_2, a_3)$ that can be obtained after applying the operation any number of times.",
    "tutorial": "$\\rightarrow$ Applying the operation on $a_1$ and $a_3$ (irrespective of which element is incremented and which one is decremented) does not change the value of $a_1 + a_3 - 2 \\cdot a_2$. $\\rightarrow$ Incrementing $a_1$ (or $a_3$) by $1$ and decrementing $a_2$ by $1$ causes the value of $a_1 + a_3 - 2 \\cdot a_2$ to increase by $3$. $\\rightarrow$ Decrementing $a_1$ (or $a_3$) by $1$ and incrementing $a_2$ by $1$ causes the value of $a_1 + a_3 - 2 \\cdot a_2$ to decrease by $3$. This effectively means that we can add or subtract any multiple of $3$ by performing some number of operations. Also, the value of $a_1 + a_3 - 2 \\cdot a_2$ will never change modulo $3$. Thus, If $\\, \\, a_1 + a_3 - 2 \\cdot a_2 \\equiv 0$ $\\mod 3$, then the minimum value of $d(a_1, a_2, a_3) = |0| = 0$ If $\\, \\, a_1 + a_3 - 2 \\cdot a_2 \\equiv 1$ $\\mod 3$, then the minimum value of $d(a_1, a_2, a_3) = |1| = 1$ If $\\, \\, a_1 + a_3 - 2 \\cdot a_2 \\equiv 2$ $\\mod 3$, then the minimum value of $d(a_1, a_2, a_3) = |2-3| = |-1| = 1$ In simpler words, if $a_1 + a_3 - 2 \\cdot a_2$ is divisible by $3$ the answer is $0$, otherwise it is $1$. Time Complexity: $\\mathcal{O}(1)$",
    "code": "t=int(input())\nfor i in range(t):\n    a,b,c=[int(x) for x in input().split()]\n    print(0 if ((a+b+c)%3 == 0) else 1)",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1605",
    "index": "B",
    "title": "Reverse Sort",
    "statement": "Ashish has a binary string $s$ of length $n$ that he wants to sort in non-decreasing order.\n\nHe can perform the following operation:\n\n- Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $k$ such that $1 \\leq k \\leq n$ and any sequence of $k$ indices $1 \\le i_1 \\lt i_2 \\lt \\ldots \\lt i_k \\le n$ such that $s_{i_1} \\ge s_{i_2} \\ge \\ldots \\ge s_{i_k}$.\n- Reverse this subsequence in-place. Formally, swap $s_{i_1}$ with $s_{i_k}$, swap $s_{i_2}$ with $s_{i_{k-1}}$, $\\ldots$ and swap $s_{i_{\\lfloor k/2 \\rfloor}}$ with $s_{i_{\\lceil k/2 \\rceil + 1}}$ (Here $\\lfloor x \\rfloor$ denotes the largest integer not exceeding $x$, and $\\lceil x \\rceil$ denotes the smallest integer not less than $x$)\n\nFind the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most $n$ operations.",
    "tutorial": "Any binary string $s$ can be sorted in at most $1$ operation! Let the number of $0$s in $s$ be $cnt_0$ and the number of $1$s in $s$ be $cnt_1$. The first $cnt_0$ positions of the final sorted string will be $0$ and the remaining $cnt_1$ positions will be $1$ (since it is sorted in non-decreasing order). Key observation: For every $1$ that is in the first $cnt_0$ positions of $s$, there is a $0$ that is in the last $cnt_1$ positions of $s$ (Why?). If the string is not already sorted, in one operation pick the subsequence consisting of all $1$s among the first $cnt_0$ positions of $s$ as well as all $0$s among the last $cnt_1$ positions of $s$. It can be shown that this will correctly sort the string since the number of such $0$s and $1$s are equal. Time complexity: $\\mathcal{O}(n)$",
    "code": "q = int(input())\nfor tc in range(q):\n    n = int(input())\n    s = input()\n    t = ''.join(sorted(s))\n    ans = []\n    for i in range(len(s)):\n        if s[i] != t[i]: \n            ans.append(i)\n    val = 1 if len(ans) > 0 else 0\n    print(val)\n    if val > 0:\n        print(len(ans), end = \" \")\n    for elem in range(len(ans)):\n        print(ans[elem] + 1, end = \" \")\n    print()",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1605",
    "index": "C",
    "title": "Dominant Character",
    "statement": "Ashish has a string $s$ of length $n$ containing only characters 'a', 'b' and 'c'.\n\nHe wants to find the length of the smallest substring, which satisfies the following conditions:\n\n- Length of the substring is \\textbf{at least} $2$\n- 'a' occurs strictly more times in this substring than 'b'\n- 'a' occurs strictly more times in this substring than 'c'\n\nAshish is busy planning his next Codeforces round. Help him solve the problem.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.",
    "tutorial": "Tl;dr: The following are all the possible minimal substrings (there aren't that many) which satisfy the given conditions: \"aa\", \"aba\", \"aca\", \"abca\", \"acba\", \"abbacca\", \"accabba\". Any other string that satisfies the condition contains at least one of these as a substring, and hence is not the optimal substring for the answer. Claim: If a substring exists which satisfies the given conditions, then the length of the shortest such substring is at most $7$. Otherwise the solution does not exist. Proof: Let us consider that the solution exists. We will try to prove this by breaking this into the following cases: Case 1: There exist two such \"a\" whose distance is less than or equal to $2$, where distance is the absolute difference of their indices. In this case where there are two such \"a\" whose distance is less than $2$, then either these two \"a\" are present consecutive or there is only one single letter between these two \"a\". All these minimal substrings are \"aa\", \"aba\" and \"aca\"which satisfies all the given conditions. Hence we can say that the shortest length of such substring that satisfies the given conditions is at most $3$ in this case. Case 2: There exists no two such \"a\" whose distance is less than or equal to $2$. In this case all the consecutive occurrences of \"a\" are present at a distance at least $3$. Then in order for the number of \"a\" to be bigger than that of \"b\" and \"c\" the string must look like \"a??a??a??a??a\". Let us define \"??\" as a block. Now if there is any block consisting of different characters $i.e$ \"bc\" or \"cb\" then the substring \"a??a\" will satisfy all the given conditions and hence the minimal length will be $4$. Notice that there must be at least one block of \"bb\" and atleast one block of \"cc\", otherwise \"a\" will not be in a majority. Hence, there must exist 2 consecutive blocks equal to \"bb\" and \"cc\" or \"cc\" and \"bb\" in the string (otherwise all blocks would be of the same character). Hence we can pick the substring \"abbacca\" or \"accabba\" which satisfies the given conditions. The minimal length is, therefore, $7$ in this case. Therefore we can say that the shortest length of such substring that satisfies the given conditions is at most $7$ in this case. Thus, it suffices to only check all substrings of length up to $7$ and find the smallest among them that satisfies the given conditions (or report that it does not exist). Time Complexity: $\\mathcal{O}(7 \\cdot n)$",
    "code": "fun main(args: Array<String>) {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val s = readLine()!!\n        var ans = 8;\n        for(i in 0..n-1) {\n            val cnt = IntArray(3) {0}\n            for(j in i..Math.min(i + 6, n - 1)) {\n                cnt[s[j] - 'a']++;\n                if(j > i && cnt[0] > Math.max(cnt[1], cnt[2]))\n                    ans = Math.min(ans, j - i + 1);\n            }\n        }\n        if(ans > 7)\n            ans = -1;\n        println(ans)\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1605",
    "index": "D",
    "title": "Treelabeling",
    "statement": "Eikooc and Sushi play a game.\n\nThe game is played on a tree having $n$ nodes numbered $1$ to $n$. Recall that a tree having $n$ nodes is an undirected, connected graph with $n-1$ edges.\n\nThey take turns alternately moving a token on the tree. \\textbf{Eikooc makes the first move, placing the token} on any node of her choice. Sushi makes the next move, followed by Eikooc, followed by Sushi, and so on. In each turn after the first, a player must move the token to a node $u$ such that\n\n- $u$ is adjacent to the node $v$ the token is currently on\n- $u$ has not been visited before\n- $u \\oplus v \\leq min(u, v)$\n\nHere $x \\oplus y$ denotes the bitwise XOR operation on integers $x$ and $y$.\n\nBoth the players play optimally. The player who is unable to make a move loses.\n\nThe following are examples which demonstrate the rules of the game.\n\n\\begin{center}\n\\begin{tabular}{ll}\nSuppose Eikooc starts the game by placing the token at node $4$. Sushi then moves the token to node $6$, which is unvisited and adjacent to $4$. It also holds that $6 \\oplus 4 = 2 \\leq min(6, 4)$. In the next turn, Eikooc moves the token to node $5$, which is unvisited and adjacent to $6$. It holds that $5 \\oplus 6 = 3 \\leq min(5, 6)$. Sushi has no more moves to play, so she loses. & Suppose Eikooc starts the game by placing the token at node $3$. Sushi moves the token to node $2$, which is unvisited and adjacent to $3$. It also holds that $3 \\oplus 2 = 1 \\leq min(3, 2)$. Eikooc cannot move the token to node $6$ since $6 \\oplus 2 = 4 \\nleq min(6, 2)$. Since Eikooc has no moves to play, she loses. \\\n\\end{tabular}\n\\end{center}\n\nBefore the game begins, Eikooc decides to sneakily relabel the nodes of the tree in her favour. Formally, a relabeling is a permutation $p$ of length $n$ (sequence of $n$ integers wherein each integer from $1$ to $n$ occurs exactly once) where $p_i$ denotes the new numbering of node $i$.\n\nShe wants to maximize the number of nodes she can choose in the first turn which will guarantee her a win. Help Eikooc find any relabeling which will help her do so.",
    "tutorial": "If the most significant bits (MSBs) of two integers $x$ and $y$ are the same, say $\\mathrm{MSB}_x = \\mathrm{MSB}_y = b$, then the $b$-th bit will be unset in $x \\oplus y$. Since $min(x, y)$ will have this bit set, it will be greater than $x \\oplus y$. Thus, if $\\mathrm{MSB}_x = \\mathrm{MSB}_y$ then $x \\oplus y \\leq min(x, y)$. If a node in the tree is adjacent only to nodes whose MSB differs from its MSB, then the player who plays this node will win. It turns out that not only is it always possible to make it such that no two nodes sharing an edge have the same MSB, it is also necessary to do so in order to maximize the number of winnning starting nodes for Eikooc. Consequently, starting at any node will guarantee a win for her. Why is it necessary if it is always possible? $\\\\$ Assume there exists at least two nodes in the tree that are adjacent to each other, having the same MSB. We prove that there will be at least one losing node for Eikooc to start on, which is suboptimal. $\\\\$ Consider a connected component of nodes in the tree of size at least two, all having the same MSB. Since this connected component also forms a tree, it must have at least one leaf node. Any node in the component which is adjacent to at least one of these leaf nodes will be losing for Eikooc (since Sushi can just move the token to a leaf node and Eikooc will have no moves to play). How do you construct it and is it always possible to do so (if so, why)? $\\\\$ We aim to relabel the nodes of the tree in such a way that for every node $v$ in the tree and all nodes $u$ adjacent to it, $\\mathrm{MSB}_v \\neq \\mathrm{MSB}_u$. $\\\\$ Think bipartite. In the bipartite colouring of a tree, no two adjacent nodes have the same colour. If we are able to relabel the nodes in such a way that all nodes with the same MSB belong to the same colour, we are done. $\\\\$ Key observation: There are $2^i$ occurrences of integers from $1$ to $n$ with the $i$-th bit as MSB (0-indexed) for each $i$ from $0$ to $\\mathrm{MSB}_n - 1$, and all such groups of integers are disjoint (since each integer has exactly one MSB). $\\\\$ Let the number of white and black nodes be $w$ and $b$ respectively and WLOG let $w \\leq b$ (we can swap the colours otherwise). Since all nodes are coloured either white or black, $w + b = n$. Under these constraints, it is then easy to show that $w \\leq \\frac{n}{2}$. Consequently, $\\mathrm{MSB}_w \\lt \\mathrm{MSB}_n$. Since $\\mathrm{MSB}_w \\lt \\mathrm{MSB}_n$, $w$ can possibly only have those bits set which lie in the range $[0, \\mathrm{MSB}_n - 1]$. Can you connect the dots? $\\\\$ Consider the binary representation of $w$. We can assign all integers from $1$ to $n$ having the $i$-th bit as MSB to a white node if the $i$-th bit is set in $w$, and assign all the remaining integers to black nodes. In doing so, no two nodes having the same MSB will belong to different colours. This ensures that no such pair is adjacent. This is also guaranteed to always be possible since the binary representation of $w$ only spans the first $\\mathrm{MSB}_n - 1$ bits and we also have access to groups of sizes comprising all powers of two upto $\\mathrm{MSB}_n - 1$. Time complexity: $\\mathcal{O}(n)$",
    "code": "fun dfs(x: Int, p: Int, curcol: Int, adj: Array<MutableList<Int>>, col: Array<Int>) {\n    col[x] = curcol\n    adj[x]\n        .filter { it != p }\n        .forEach { dfs(it, x, curcol xor 1, adj, col) }\n}\n \nfun main(args: Array<String>) {\n    val t = readLine()!!.toInt()\n    repeat(t) {\n        val n = readLine()!!.toInt()\n        val adj = Array(n) { mutableListOf<Int>() }\n        repeat(n - 1) {\n            val (u, v) = readLine()!!.split(\" \").map { it.toInt() }\n            adj[u - 1].add(v - 1);\n            adj[v - 1].add(u - 1);\n        }\n        val col = Array<Int>(n) {0}\n        dfs(0, -1, 0, adj, col)\n        var s = Array(2) { mutableListOf<Int>() }\n        (0..n-1).forEach { s[col[it]].add(it) }\n        if(s[0].size < s[1].size)\n            s[0] = s[1].also { s[1] = s[0] }\n        val highestBit = Array(20) { mutableListOf<Int>() }\n        (1..n).forEach { highestBit[it.takeHighestOneBit().countTrailingZeroBits()].add(it - 1) }\n        val ans = Array<Int>(n) {-1}\n        (19 downTo 0).forEach { currentBit ->\n            val largerSet = if(s[0].size >= s[1].size) 0 else 1\n            highestBit[currentBit].forEach { it ->\n                ans[it] = s[largerSet].last()\n                s[largerSet].removeLast()\n            }\n        }\n        val pos = Array<Int>(n) {-1}\n        (0..n-1).forEach { pos[ans[it]] = it };\n        (0..n-1).forEach { print (\"${pos[it] + 1} \") }\n        println()\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "games",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1605",
    "index": "E",
    "title": "Array Equalizer",
    "statement": "Jeevan has two arrays $a$ and $b$ of size $n$. He is fond of performing weird operations on arrays. This time, he comes up with two types of operations:\n\n- Choose any $i$ ($1 \\le i \\le n$) and increment $a_j$ by $1$ for every $j$ which is a multiple of $i$ and $1 \\le j \\le n$.\n- Choose any $i$ ($1 \\le i \\le n$) and decrement $a_j$ by $1$ for every $j$ which is a multiple of $i$ and $1 \\le j \\le n$.\n\nHe wants to convert array $a$ into an array $b$ using the minimum total number of operations. However, Jeevan seems to have forgotten the value of $b_1$. So he makes some guesses. He will ask you $q$ questions corresponding to his $q$ guesses, the $i$-th of which is of the form:\n\n- If $b_1 = x_i$, what is the minimum number of operations required to convert $a$ to $b$?\n\nHelp him by answering each question.",
    "tutorial": "Firstly let's observe that only the differences $b_i - a_i$ matter, and not the individual values of $a_i$ and $b_i$. So let us create two more arrays $A$ and $B$ where initially $A_i = 0$ and $B_i = b_i - a_i$ for all $i$. The problem reduces to making $A$ equal to $B$. Let's have a few definitions for ease of explanation. We define operation \"add\" $k$ to $i$ as: perform the increment operation at $i$ (and multiples of $i$), $k$ times, if $k > 0$, otherwise perform the decrement operation at $i$ (and multiples of $i$), $k$ times. In both cases, the number of operations performed is $|k|$. Let's first solve the problem for only one value of $B_1$. We notice that problem can be solved using a simple greedy approach. We iterate over the elements from left to right. Let the index of the current element be $u$. Initial arrays: -123456$\\cdots$$A$$0$$0$$0$$0$$0$$0$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add------$\\cdots$ -123456$\\cdots$$A$$0$$0$$0$$0$$0$$0$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add------$\\cdots$ At $u = 1$: Applying the operation at $i = 1$ alone can change the value of $A_1$. Thereby we \"add\" $B_1$ at $i = 1$ to make $A_1 = B_1$. The remaining array also gets modified accordingly. Resulting arrays: -123456$\\cdots$$A$$B_1$$B_1$$B_1$$B_1$$B_1$$B_1$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$B_1$-----$\\cdots$ -123456$\\cdots$$A$$B_1$$B_1$$B_1$$B_1$$B_1$$B_1$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$B_1$-----$\\cdots$ At $u = 2$: Applying the operation at $i = 1$ and $i = 2$ only can change the value of $A_2$. But since we have already made $A_1 = B_1$, we will only apply operations at $i = 2$. We \"add\" $B_2 - B_1$ at $i = 2$. Resulting arrays: -123456$\\cdots$$A$$B_1$$B_2$$B_1$$B_2$$B_1$$B_2$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$B_1$$B_2 - B_1$----$\\cdots$ -123456$\\cdots$$A$$B_1$$B_2$$B_1$$B_2$$B_1$$B_2$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$B_1$$B_2 - B_1$----$\\cdots$ At $u = 3$: Applying the operation at $i = 1$ and $i = 3$ only can change the value of $A_3$. But since we have already made $A_1 = B_1$, we will only apply operations at $i = 3$. We \"add\" $B_3 - B_1$ at $i = 3$. Resulting arrays: -123456$\\cdots$$A$$B_1$$B_2$$B_3$$B_2$$B_1$$B_3 + B_2 - B_1$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$B_1$$B_2 - B_1$$B_3 - B_1$---$\\cdots$ -123456$\\cdots$$A$$B_1$$B_2$$B_3$$B_2$$B_1$$B_3 + B_2 - B_1$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$B_1$$B_2 - B_1$$B_3 - B_1$---$\\cdots$ At $u = 4$: Applying the operation at $i = 1$, $i = 2$ and $i = 4$ only can change the value of $A_4$. But since we have already made $A_1 = B_1$ and $A_2$ = B_2, we will only apply operations at $i = 4$. We \"add\" $B_4 - B_2$ at $i = 4$. Resulting arrays: -123456$\\cdots$$A$$B_1$$B_2$$B_3$$B_2$$B_1$$B_3 + B_2 - B_1$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$B_1$$B_2 - B_1$$B_3 - B_1$$B_4 - B_2$--$\\cdots$ -123456$\\cdots$$A$$B_1$$B_2$$B_3$$B_2$$B_1$$B_3 + B_2 - B_1$$\\cdots$$B$$B_1$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$B_1$$B_2 - B_1$$B_3 - B_1$$B_4 - B_2$--$\\cdots$ So we iterate from left to right and at every index $u$, we \"add\" $(B_u -$ current value of $A_u)$ at $i = u$. The final answer will be summation of absolute value of these values (i.e. the values written in the \"add\" row). However, in the original problem, we have to solve the problem for multiple values of $B_1$. So let us assume the value of $B_1$ to be equal to some variable, say $x$. Let us try to use the same approach with the variable $x$. Initial arrays: -123456$\\cdots$$A$$0$$0$$0$$0$$0$$0$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add------$\\cdots$ -123456$\\cdots$$A$$0$$0$$0$$0$$0$$0$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add------$\\cdots$ At $u = 1$: We \"add\" $x$ at $i = 1$. Resulting arrays: -123456$\\cdots$$A$$x$$x$$x$$x$$x$$x$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$x$-----$\\cdots$ -123456$\\cdots$$A$$x$$x$$x$$x$$x$$x$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$x$-----$\\cdots$ At $u = 2$: We \"add\" $B_2 - x$ at $i = 2$. Resulting arrays: -123456$\\cdots$$A$$x$$B_2$$x$$B_2$$x$$B_2$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$x$$B_2 - x$----$\\cdots$ -123456$\\cdots$$A$$x$$B_2$$x$$B_2$$x$$B_2$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$x$$B_2 - x$----$\\cdots$ At $u = 3$: We \"add\" $B_3 - x$ at $i = 3$. Resulting arrays: -123456$\\cdots$$A$$x$$B_2$$B_3$$B_2$$x$$B_3 + B_2 - x$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$x$$B_2 - x$$B_3 - x$---$\\cdots$ -123456$\\cdots$$A$$x$$B_2$$B_3$$B_2$$x$$B_3 + B_2 - x$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$x$$B_2 - x$$B_3 - x$---$\\cdots$ At $u = 4$: We \"add\" $B_4 - B_2$ at $i = 4$. Resulting arrays: -123456$\\cdots$$A$$x$$B_2$$B_3$$B_4$$x$$B_3 + B_2 - x$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$x$$B_2 - x$$B_3 - x$$B_4 - B_2$--$\\cdots$ -123456$\\cdots$$A$$x$$B_2$$B_3$$B_4$$x$$B_3 + B_2 - x$$\\cdots$$B$$x$$B_2$$B_3$$B_4$$B_5$$B_6$$\\cdots$add$x$$B_2 - x$$B_3 - x$$B_4 - B_2$--$\\cdots$ Every cell in the \"add\" row here will be of the form: $c \\cdot x + d$. The final answer will be the summation of absolute values of these values written in the \"add\" row. Also we know, $|c \\cdot x + d| = \\begin{cases} c \\cdot x + d & x \\ge -\\frac{d}{c} \\\\ -(c \\cdot x + d) & x \\lt -\\frac{d}{c} \\end{cases}$ Note that the above equalities hold only when $c \\gt 0$. So if $c$ is negative in any term, then we can multiply the entire term with $-1$ to make it positive since $|c \\cdot x + d| = |- c \\cdot x - d|$. Now, we can store the values of $-\\frac{d}{c}$ for each index in sorted order. And for each query, we can find out, using binary search, which of the absolute value terms will have a positive sign and which of those will have a negative sign. So we can finally calculate the answer using prefix and suffix sums. Bonus: It turns out that the value of coefficient of $x$ in the \"add\" value for the $u$-th index is $c_u = \\mu(u)$ where $\\mu$ is the mobious function. So $-1 \\le c_u \\le 1$. Time Complexity: $\\mathcal{O}(n \\log n + q \\log n)$ $\\cdots$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define IOS ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define int long long\n#define endl \"\\n\"\n#define sz(w) (int)(w.size())\nusing pii = pair<int, int>;\n \nconst double EPS = 1e-9;\nconst long long INF = 1e18;\n \nconst int N = 2e5+5; \n \nint n, m, a[N], b[N], c[N], add[N], mob[N];\n \nvoid mobius() \n{\n    mob[1] = 1;\n    for(int i = 2; i < N; i++)\n    {\n        mob[i]--;\n        for(int j = i + i; j < N; j += i) \n        {\n          mob[j] -= mob[i];\n        }\n    }\n}\n \nint32_t main()\n{\n    IOS;\n    mobius();\n    cin >> n;\n    for(int i = 1; i <= n; i++)\n        cin >> a[i];\n    for(int i = 1; i <= n; i++)\n        cin >> b[i];\n    for(int i = 1; i <= n; i++)\n        c[i] = b[i] - a[i];\n    c[1] = 0;\n    vector<int> z;\n    for(int i = 1; i <= n; i++)\n    {\n        int d = c[i];\n        for(int j = i; j <= n; j += i)\n        {\n            c[j] -= d;\n        }\n        add[i] = d;\n    }\n    int ans = 0;\n    for(int i = 1; i <= n; i++)\n    {\n        if(mob[i] == 0)\n            ans += abs(add[i]);\n        else if(mob[i] == -1)\n            z.push_back(-add[i]);\n        else \n            z.push_back(add[i]);\n    }\n    sort(z.begin(), z.end());\n    vector<int> pref = z;\n    for(int i = 1; i < sz(z); i++)\n        pref[i] = pref[i-1] + z[i];\n    auto sum = [&pref](int l, int r)\n    {\n        if(r < 0) return 0LL;\n        int res = pref[r];\n        if(l-1 >= 0)\n            res -= pref[l-1];\n        return res;\n    };\n    int q; cin >> q;\n    while(q--)\n    {\n        int x; cin >> x;\n        x -= a[1];\n        int lo = 0, hi = sz(z)-1;\n        while(lo <= hi)\n        {\n            int mid = (lo+hi)/2;\n            if(z[mid] <= -x)\n                lo = mid+1;\n            else\n                hi = mid-1;\n        }\n        swap(lo, hi);\n        int res = sum(hi, sz(z)-1) + (sz(z)-hi) * x;\n        res -= (sum(0, lo) + (lo+1)*x);\n        cout << ans+res << endl;\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "math",
      "number theory",
      "sortings",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1605",
    "index": "F",
    "title": "PalindORme",
    "statement": "An integer array $a$ of length $n$ is said to be a PalindORme if ($a_{1}$ $|$ $a_{2} $ $|$ $ \\ldots $ $|$ $ a_{i}) = (a_{{n - i + 1}} $ $|$ $ \\ldots $ $|$ $ a_{{n - 1}} $ $|$ $ a_{n}) $ \\textbf{for all} $ 1 \\leq i \\leq n$, where $|$ denotes the bitwise OR operation.\n\nAn integer array $a$ of length $n$ is considered to be good if its elements can be rearranged to form a PalindORme. Formally, array $a$ is good if there exists a permutation $p_1, p_2, \\ldots p_n$ (an array where each integer from $1$ to $n$ appears exactly once) for which $a_{p_1}, a_{p_2}, \\ldots a_{p_n}$ is a PalindORme.\n\nFind the number of good arrays of length $n$, consisting only of integers in the range $[0, 2^{k} - 1]$, and print it modulo some prime $m$.\n\nTwo arrays $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_n$ are considered to be different if there exists any $i$ $(1 \\leq i \\leq n)$ such that $a_i \\ne b_i$.",
    "tutorial": "$\\textbf{Solution Outline:}$ For any bad array, there is $\\textbf{exactly one}$ maximum even length good subsequence (possibly the empty subsequence). It can be proven that there exists at most one element in the bad array that doesn't belong to this subsequence, but is a submask of its OR. If such an element exists, we add it to the subsequence. After performing this step if needed, we have a good subsequence of this bad array such that all other elements of this array have one or more bits active which aren't present anywhere in this subsequence. We will call this the \"best\" subsequence from now on. Clearly a bad array also has $\\textbf{exactly one}$ best subsequence. By noting that the best subsequence is still a good array (place the extra element in the middle of the PalindORme of even length), we can use dp to count the number of bad arrays of length $n$ with exactly $k$ bits on in total using its best subsequence of length $n' \\lt n$ with exactly $k' \\lt k$ bits on in total in $O(n ^ 4)$. $\\textbf{Full Editorial:}$ Let $S$ be the multiset of elements of the initial array $a_1, a_2, \\ldots, a_n$. We want to check if we can construct a PalindORme from these elements. Out of the $n$ conditions of the form $b_{1}$ $|$ $b_{2}$ $|$ $\\ldots$ $|$ $b_{i} = b_{{n - i + 1}}$ $|$ $\\ldots$ $|$ $b_{{n - 1}}$ $|$ $b_{n}$, it intuitively makes sense to tackle them in increasing order of $i$, so we will try to do that. For $i = 1$, we want to find two elements $x, y$ in $S$ such that $x = y$. We place these elements as $b_1$ and $b_n$ and erase them from $S$. For $i = 2$, we want to find two elements $x, y$ in $S$ such that $b_1$ $|$ $x$ $=$ $b_1$ $|$ $y$. We place these elements as $b_2$ and $b_{n - 1}$ and erase them from $S$. Generalizing, for any $i$, we want to find two elements $x, y$ in $S$ such that $b_{1}$ $|$ $b_{2}$ $|$ $\\ldots$ $|$ $b_{i - 1}$ $|$ $x$ $=$ $b_{1}$ $|$ $b_{2}$ $|$ $\\ldots$ $|$ $b_{i - 1}$ $|$ $y$. We place these elements as $b_i$ and $b_{n + 1 - i}$ and erase them from $S$. But what if there exists multiple pairs $(x_1, y_1), (x_2, y_2), \\ldots (x_k, y_k)$ that satisfy the property in a given step, which do we take? It is optimal to take any of them. Clearly if $mask$ $|$ $x_j$ = $mask$ $|$ $y_j$, then $mask$ $|$ $z$ $|$ $x_j$ = $mask$ $|$ $z$ $|$ $y_j$ is also true for any $z$. So regardless of which of these pairs we take, all other pairs will remain good in future steps. So we obtain the following simple algorithm to check if a PalindORme is good: This algorithm is equivalent to placing elements at positions $i$ and $(n + 1 - i)$ of the PalindORme in the $i$-th iteration of the loop. Taking any two elements is optimal since a pair that satisfies the property for $mask$ will also clearly satisfy it for $mask$ $|$ $x$. Let us consider the multiset $S$ corresponding to the elements of a bad array: This algorithm will fail to find any such pair of elements after some number of steps. The pairs which have been selected till this point will constitute a good array (possibly of length 0). For the given bad array, the number of pairs taken as well as the bits on in the mask will always be the same when the algorithm fails regardless of the two elements selected in each step. Since we cannot add any two more elements to this good array, this is the longest even length good subsequence of the bad array. Due to the previous point, we can also see that it is the only good subsequence of this length. There can exist at most one element among the remaining elements not in the subsequence which is a submask of $mask$, otherwise there would exist a pair such that $mask$ $|$ $x$ $=$ $mask$ $|$ $y$ $=$ $mask$. If such an element exists, we can add it to the subsequence. The best subsequence still remains a good array since we can place this element in the center position of resulting PalindORme. After performing this step if needed, we have a good subsequence of this bad array such that all elements of this array not in the subsequence have one or more bits active which aren't on in $mask$ and therefore not present in the subsequence. We will call this the \"best\" subsequence from now on. Clearly a bad array also has $\\textbf{exactly one}$ best subsequence (possibly of length 0). So every bad array of length $n$ with $k$ bits on in total can be mapped to a best subsequence (which is a good array) with length $n' \\lt n$ with $k' \\lt k$ bits on in total. The remaining $n - n'$ elements will then need to be chosen such that they have the remaining $k - k'$ bits on in total while possessing distinct values when OR'd with $mask$. So we obtain a dp to count the number of bad arrays $-$ $cnt\\_bad_{\\text{length}, \\text{bits on in total}}$, where $cnt\\_bad_{i, j} = \\sum\\limits_{i' = 0}^{i - 1} \\sum\\limits_{j' = 0}^{j - 1} f(i, j, i', j')\\cdot(cnt\\_good_{i', j'})$. Here $f(i, j, i', j')$ is the number of bad arrays of length $i$ with exactly $j$ bits on in total, that have a good array of length $i' \\lt i$ with exactly $j' \\lt j$ bits on in total as their best subsequence. Since the total number of arrays of length $x$ with exactly $y$ bits on in total can be easily calculated using some basic combinatorial formulas and inclusion exclusion, we can rewrite this as: $cnt\\_bad_{i, j}$ $=$ $\\sum\\limits_{i' = 0}^{i - 1} \\sum\\limits_{j' = 0}^{j - 1} f(i, j, i', j')\\cdot(cnt\\_total_{i', j'} - cnt\\_bad_{i', j'})$ giving us a dp with $O(n ^ 2)$ states and $O(n ^ 4)$ transitions. $f(i, j, i', j')$ is made of the following components: The number of ways of placing the best subsequence in the bad array. Since there are no values in common between the best subsequence and the remaining values of the array, the answer is just $n \\choose n'$. Since there are no values in common between the best subsequence and the remaining values of the array, the answer is just $n \\choose n'$. The number of ways of choosing which $j'$ of the $j$ bits were from the good array. All ways are possible, so it is just $j \\choose j'$ All ways are possible, so it is just $j \\choose j'$ The number of different arrays of length $i - i'$ with the remaining $j - j'$ bits set in total such that each element has one or more of the $j - j'$ bits set and all elements have distinct values when OR'd with $mask$, i.e, the remaining $j$ bits. We can observe that the second can be broken into the product of two easier parts: The number of different arrays of $i - i'$ distinct positive numbers with exactly $j - j'$ bits set in total. We can first find the number of ways of permuting $i - i'$ positive numbers with $\\textbf{up to}$ $k$ bits set in total as $^{2^k - 1} P_{i - i'}$. Then we just need to perform simple inclusion-exclusion to get the answer for exactly $k$ bits set in total. The number of ways of setting the remaining $j'$ bits for these numbers. Since $mask$ is effectively the OR of all elements in the good array, all the $j'$ bits are already set in $mask$. So any setting of these $j'$ bits for these numbers doesn't doesn't affect the values when OR'd with $mask$. So the number of ways is just $2^{(i - i')\\cdot(j')}$. We can observe that the second can be broken into the product of two easier parts: The number of different arrays of $i - i'$ distinct positive numbers with exactly $j - j'$ bits set in total. We can first find the number of ways of permuting $i - i'$ positive numbers with $\\textbf{up to}$ $k$ bits set in total as $^{2^k - 1} P_{i - i'}$. Then we just need to perform simple inclusion-exclusion to get the answer for exactly $k$ bits set in total. The number of ways of setting the remaining $j'$ bits for these numbers. Since $mask$ is effectively the OR of all elements in the good array, all the $j'$ bits are already set in $mask$. So any setting of these $j'$ bits for these numbers doesn't doesn't affect the values when OR'd with $mask$. So the number of ways is just $2^{(i - i')\\cdot(j')}$. The number of different arrays of $i - i'$ distinct positive numbers with exactly $j - j'$ bits set in total. We can first find the number of ways of permuting $i - i'$ positive numbers with $\\textbf{up to}$ $k$ bits set in total as $^{2^k - 1} P_{i - i'}$. Then we just need to perform simple inclusion-exclusion to get the answer for exactly $k$ bits set in total. The number of ways of setting the remaining $j'$ bits for these numbers. Since $mask$ is effectively the OR of all elements in the good array, all the $j'$ bits are already set in $mask$. So any setting of these $j'$ bits for these numbers doesn't doesn't affect the values when OR'd with $mask$. So the number of ways is just $2^{(i - i')\\cdot(j')}$. Since these three components are independent of each other, $f(i, j, i', j')$ is just the product of them. However, as you may have observed, the \"bad\" arrays counted by this dp doesn't line up with the actual definition of bad arrays in one case - When a \"bad\" array has an even length best subsequence and a single remaining element with one or more bits that aren't set in this subsequence. This is clearly a good array but is counted as bad by our dp. (Example: good array [1, 1] combined with remaining element array [2] resulting in [1, 2, 1] (or [1, 1, 2] / [2, 1, 1]) which is clearly a good array but is counted as bad by our dp.) This is however necessary since this is the only type of good array that is never the best subsequence of any bad array. Counting it as a good array in our dp would lead to overcounting when it was used as a best subsequence. But then how do we then recover the correct number of actual bad arrays of length $n$ with exactly $j$ bits set? We can notice that this case occurs for best subsequences of length $i - 1$ when $i$ is odd. So when counting the number of bad arrays of length $n$ we can just skip best subsequences of length $n - 1$ if $n$ is odd. Since $n$ is the largest array size we are concerned with, good arrays of size $n$ will never be a best subsequence of a larger bad array and as such won't lead to overcounting. As a final note, remember that we have the number of bad arrays for $n$ with $\\textbf{exactly}$ $j$ bits set while we need the number of bad arrays with $\\textbf {up to}$ $j$ bits set. This can be easily obtained by multiplying the answer for a given $j$ with the number of ways of choosing $j$ of the $k$ bits and summing these values up for each $j$. In short, we want $\\sum_{j = 0}^{k} {k \\choose j} \\cdot cnt\\_good_{n, j}$. Time Complexity: $\\mathcal{O}(n ^ 4)$ $\\cdots$",
    "code": "fun mod_expo(base: Int, pow: Int, MOD: Int): Long {\n    if(pow == 0) {\n        return 1;\n    }\n    var res = mod_expo(base, pow / 2, MOD)\n    res = (res * res) % MOD\n    if(pow % 2 == 1) {\n        res = (res * base) % MOD;\n    }\n    return res;\n}\n \nfun mod_inv(base: Int, MOD: Int): Long {\n    return mod_expo(base, MOD - 2, MOD)\n}\n \nfun fast_nCr(n: Int, r: Int, fact: Array<Long>, invfact: Array<Long>, MOD: Int): Long {\n    val num = fact[n];\n    val denom = (invfact[r] * invfact[n - r]) % MOD;\n    return (num * denom) % MOD;\n}\n \nfun slow_nPr(n: Int, r: Int, MOD: Int): Long {\n    var res = 1L;\n    for(i in 1..r) {\n        res *= (n - i + 1 + MOD) % MOD;\n        res %= MOD;\n    }\n    return res;\n}\n \nfun main(args: Array<String>) {\n    val (n, k, MOD) = readLine()!!.split(\" \").map { it.toInt() }\n    val fact = Array<Long>(Math.max(n, k) + 1) { 1L }\n    val invfact = Array<Long>(Math.max(n, k) + 1) { 1L }\n    for(i in 1..Math.max(n, k)) {\n        fact[i] = (fact[i - 1] * i) % MOD\n        invfact[i] = mod_inv(fact[i].toInt(), MOD)\n    }\n    val pow2 = Array<Long>(n * k + 1) { 1 }\n    for(i in 1..n*k) {\n        pow2[i] = (pow2[i - 1] * 2) % MOD;\n    }\n    val cntDistinctPositive = Array(n + 1) { Array<Long>(k + 1) { 0L } }\n    val cntTotal = Array(n + 1) { Array<Long>(k + 1) { 0L } }\n    val cntBad = Array(n + 1) { Array<Long>(k + 1) { 0L } }\n    for(i in 0..n) {\n        for(j in 0..k) {\n            cntDistinctPositive[i][j] = slow_nPr((mod_expo(2, j, MOD).toInt() - 1 + MOD) % MOD, i, MOD)\n            cntTotal[i][j] = pow2[i * j]\n            for(l in 0..j-1) {\n                cntDistinctPositive[i][j] += (MOD - ((fast_nCr(j, l, fact, invfact, MOD) * cntDistinctPositive[i][l])) % MOD)\n                cntDistinctPositive[i][j] = cntDistinctPositive[i][j] % MOD\n                cntTotal[i][j] += (MOD - ((fast_nCr(j, l, fact, invfact, MOD) * cntTotal[i][l])) % MOD);\n                cntTotal[i][j] = cntTotal[i][j] % MOD\n            }\n        }\n    }\n    cntTotal[0][0] = 1\n    for(i in 1..n) {\n        for(j in 0..k) {\n            cntBad[i][j] = 0\n             for(a in 0..i-1) {\n                for(b in 0..j-1) {\n                    if(i == n && n % 2 == 1 && a == i - 1) {\n                        continue;\n                    }\n                    var curBad = (cntTotal[a][b] - cntBad[a][b] + MOD) % MOD\n                    curBad *= (cntDistinctPositive[i - a][j - b])\n                    curBad = curBad % MOD\n                    curBad *= fast_nCr(i, a, fact, invfact, MOD)\n                    curBad = curBad % MOD\n                    curBad *= fast_nCr(j, b, fact, invfact, MOD)\n                    curBad = curBad % MOD\n                    curBad *= pow2[(i - a) * b]\n                    curBad = curBad % MOD\n                    cntBad[i][j] += curBad\n                    cntBad[i][j] = cntBad[i][j] % MOD\n                }\n            }\n        }\n    }\n    var ans = 0L\n    for(j in 0..k) {\n        val cntGood = (cntTotal[n][j] - cntBad[n][j] + MOD) % MOD\n        ans += (fast_nCr(k, j, fact, invfact, MOD) * cntGood) % MOD\n    }\n    println(ans % MOD)\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1606",
    "index": "A",
    "title": "AB Balance",
    "statement": "You are given a string $s$ of length $n$ consisting of characters a and/or b.\n\nLet $\\operatorname{AB}(s)$ be the number of occurrences of string ab in $s$ as a \\textbf{substring}. Analogically, $\\operatorname{BA}(s)$ is the number of occurrences of ba in $s$ as a \\textbf{substring}.\n\nIn one step, you can choose any index $i$ and replace $s_i$ with character a or b.\n\nWhat is the minimum number of steps you need to make to achieve $\\operatorname{AB}(s) = \\operatorname{BA}(s)$?\n\n\\textbf{Reminder:}\n\nThe number of occurrences of string $d$ in $s$ as substring is the number of indices $i$ ($1 \\le i \\le |s| - |d| + 1$) such that substring $s_i s_{i + 1} \\dots s_{i + |d| - 1}$ is equal to $d$. For example, $\\operatorname{AB}($aabbbabaa$) = 2$ since there are two indices $i$: $i = 2$ where {a\\underline{ab}bbabaa} and $i = 6$ where {aabbb\\underline{ab}aa}.",
    "tutorial": "Let's look at the first and the last characters of $s$. Note that if $s_1 = s_n$ (where $n = |s|$), then $\\operatorname{AB}(s)$ is always equal to $\\operatorname{BA}(s)$. It can be proved, for example, by induction: if $s$ consists of equal characters then $\\operatorname{AB}(s) = \\operatorname{BA}(s) = 0$; if $s$ has a structure like abb...ba (or baa...ab) then $\\operatorname{AB}(s) = \\operatorname{BA}(s) = 1$. Otherwise, there is at least one character $s_i$ in the middle that equal to $s_1$ and $s_n$. So we can split string $s$ in $s[1..i]$ and $s[i..n]$. Both these string has $\\operatorname{AB} = \\operatorname{BA}$ (by induction), so our string $s$ also has $\\operatorname{AB}(s) = \\operatorname{BA}(s)$. As a result, if $s_1 = s_n$ then the answer is $0$, and we print the string untouched. Otherwise, we replace either $s_1$ or $s_n$ and get the desired string. (It also can be proved that if $s_1 \\neq s_n$ then $\\operatorname{AB}(s) \\neq \\operatorname{BA}(s)$)",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val s = readLine()!!\n        println(s.last() + s.substring(1))\n    }\n}",
    "tags": [
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1606",
    "index": "B",
    "title": "Update Files",
    "statement": "Berland State University has received a new update for the operating system. Initially it is installed only on the $1$-st computer.\n\nUpdate files should be copied to all $n$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.\n\nYour task is to find the minimum number of hours required to copy the update files to all $n$ computers if there are only $k$ patch cables in Berland State University.",
    "tutorial": "Let $cur$ be the current number of computers with the update already installed (initially it is $1$). Then, in $1$ hour, we can increase $cur$ by $\\min(cur, k)$. From here we can see that the value of $cur$ will double for the first few hours, and then, when it becomes greater than $k$, it will begin to increase by exactly $k$. The process when the number of computers doubles can be modeled using a loop, because the number of doublings does not exceed $\\log{n}$. And after that, we have to increase the answer by $\\left\\lceil {\\frac{n - cur}{k}} \\right\\rceil$ to take the number of additions of $k$ into account. Note that computing $\\left\\lceil {\\frac{n - cur}{k}} \\right\\rceil$ should be done without using fractional data types; to calculate $\\left\\lceil {\\frac{x}{y}} \\right\\rceil$ in integers, you should divide $x + y - 1$ by $y$ using integer division (this will work provided that both $x$ and $y$ are non-negative, and $y \\ne 0$). If you use real numbers, this may cause precision issues.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing li = long long;\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL); \n  int t;\n  cin >> t;\n  while (t--) {\n    li n, k;\n    cin >> n >> k;\n    li ans = 0, cur = 1;\n    while (cur < k) {\n      cur *= 2;\n      ++ans;\n    }\n    if (cur < n) ans += (n - cur + k - 1) / k;\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1606",
    "index": "C",
    "title": "Banknotes",
    "statement": "In Berland, $n$ different types of banknotes are used. Banknotes of the $i$-th type have denomination $10^{a_i}$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $1$.\n\nLet's denote $f(s)$ as the minimum number of banknotes required to represent exactly $s$ burles. For example, if the denominations of banknotes used in Berland are $1$, $10$ and $100$, then $f(59) = 14$: $9$ banknotes with denomination of $1$ burle and $5$ banknotes with denomination of $10$ burles can be used to represent exactly $9 \\cdot 1 + 5 \\cdot 10 = 59$ burles, and there's no way to do it with fewer banknotes.\n\nFor a given integer $k$, find the minimum positive number of burles $s$ that cannot be represented with $k$ or fewer banknotes (that is, $f(s) > k$).",
    "tutorial": "First of all, let's find out how to calculate $f(s)$. This can be done greedily, let's iterate from the higher denominations to the lower ones, the number of banknotes of $i$-th type is equal to $\\left\\lfloor {\\frac{s}{10^{a_i}}} \\right\\rfloor$ (the value of $s$ here changes to reflect that we have already taken some banknotes; that is, we subtract $\\left\\lfloor {\\frac{s}{10^{a_i}}} \\right\\rfloor \\cdot 10^{a_i}$ from $s$ each time, which is the same as taking $s$ modulo $10^{a_i}$). We can see that after we process the $i$-th type of banknotes, the condition $s < 10^{a_i}$ holds, which means that the number of banknotes of $i$-th type does not exceed $\\frac{10^{a_{i + 1}}}{10^{a_i}} - 1$ (except in the case of $i = n$). Now we can find the minimum number $s$ such that $f(s) > k$. Let $\\mathit{lft}$ be the number of banknotes that still remains to take, initially equal to $k+1$ (because we want $f(s)$ to be at least $k + 1$). Let's iterate from the lower denominations to the highest ones, the number of banknotes of $i$-th type we take should be equal to $\\min(\\mathit{lft}, \\frac{10^{a_{i + 1}}}{10^{a_i}} - 1)$ - the minimum of how many we need to take and how many we are allowed to take, so as not to break the minimality of the function $f$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    k += 1;\n    vector<int> a(n);\n    for (int& x : a) {\n      cin >> x;\n      int cur = 1;\n      while (x--) cur *= 10;\n      x = cur;\n    }\n    long long res = 0;\n    for (int i = 0; i < n; i++) {\n      int cnt = k;\n      if (i + 1 < n) cnt = min(cnt, a[i + 1] / a[i] - 1);\n      res += a[i] * 1LL * cnt;\n      k -= cnt;\n    }\n    cout << res << '\\n';\n  }\n} ",
    "tags": [
      "greedy",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1606",
    "index": "D",
    "title": "Red-Blue Matrix",
    "statement": "You are given a matrix, consisting of $n$ rows and $m$ columns. The $j$-th cell of the $i$-th row contains an integer $a_{ij}$.\n\nFirst, you have to color each row of the matrix either red or blue in such a way that \\textbf{at least one row is colored red} and \\textbf{at least one row is colored blue}.\n\nThen, you have to choose an integer $k$ ($1 \\le k < m$) and cut the colored matrix in such a way that the first $k$ columns become a separate matrix (the left matrix) and the last $m-k$ columns become a separate matrix (the right matrix).\n\nThe coloring and the cut are called perfect if two properties hold:\n\n- every red cell in the left matrix contains an integer greater than every blue cell in the left matrix;\n- every blue cell in the right matrix contains an integer greater than every red cell in the right matrix.\n\nFind any perfect coloring and cut, or report that there are none.",
    "tutorial": "Imagine you fixed some cut and then colored one row red. Which rows can now be colored red or blue so that the condition on the left matrix is satisfied? If the row has at least one number greater or equal than the numbers in the red row, then the row must be red. Otherwise, it can be either red or blue. However, imagine a weaker condition. Let's look only at the first cell in each row. Sort the rows by the first cell in them. Similarly, if a row is colored red, all the rows that are further in the sorted order should also be red, because they already have a greater or equal number in them. It implies that after you sort the rows, the only possible colorings are: color some prefix of the rows in blue and the remaining suffix in red. So there are $n$ possible colorings and $m$ possible cuts. If we learn to check if they are perfect in $O(1)$, we can get the solution in $O(nm)$. Turns out, the condition \"all numbers in the submatrix should be greater than all numbers in the other submatrix\" is the same as \"the minimum in the first submatrix should be greater than the maximum in the second submatrix\". Thus, you can first precalculate prefix and suffix minimums and maximums and check a coloring and a cut in $O(1)$. Overall complexity: $O(n \\log n + nm)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint main() {\n\tint tc;\n\tscanf(\"%d\", &tc);\n\twhile (tc--){\n\t\tint n, m;\n\t\tscanf(\"%d%d\", &n, &m);\n\t\tvector<vector<int>> a(n, vector<int>(m));\n\t\tforn(i, n) forn(j, m) scanf(\"%d\", &a[i][j]);\n\t\tvector<int> ord(n);\n\t\tiota(ord.begin(), ord.end(), 0);\n\t\tsort(ord.begin(), ord.end(), [&a](int x, int y){ return a[x][0] > a[y][0]; });\n\t\tvector<vector<int>> mxl(n, vector<int>(m, -INF));\n\t\tvector<vector<int>> mnr(n, vector<int>(m, INF));\n\t\tfor (int i = n - 1; i >= 0; --i) forn(j, m){\n\t\t\tmxl[i][j] = a[ord[i]][j];\n\t\t\tif (i < n - 1) mxl[i][j] = max(mxl[i][j], mxl[i + 1][j]);\n\t\t\tif (j > 0) mxl[i][j] = max(mxl[i][j], mxl[i][j - 1]);\n\t\t}\n\t\tfor (int i = n - 1; i >= 0; --i) for (int j = m - 1; j >= 0; --j){\n\t\t\tmnr[i][j] = a[ord[i]][j];\n\t\t\tif (i < n - 1) mnr[i][j] = min(mnr[i][j], mnr[i + 1][j]);\n\t\t\tif (j < m - 1) mnr[i][j] = min(mnr[i][j], mnr[i][j + 1]);\n\t\t}\n\t\tvector<int> mnl(m, INF), mxr(m, -INF);\n\t\tpair<int, int> ans(-1, -1);\n\t\tforn(i, n - 1){\n\t\t\tforn(j, m){\n\t\t\t\tmnl[j] = min(mnl[j], a[ord[i]][j]);\n\t\t\t\tif (j > 0) mnl[j] = min(mnl[j], mnl[j - 1]);\n\t\t\t}\n\t\t\tfor (int j = m - 1; j >= 0; --j){\n\t\t\t\tmxr[j] = max(mxr[j], a[ord[i]][j]);\n\t\t\t\tif (j < m - 1) mxr[j] = max(mxr[j], mxr[j + 1]);\n\t\t\t}\n\t\t\tforn(j, m - 1) if (mnl[j] > mxl[i + 1][j] && mxr[j + 1] < mnr[i + 1][j + 1]){\n\t\t\t\tans = {i, j};\n\t\t\t}\n\t\t}\n\t\tif (ans.first == -1){\n\t\t\tputs(\"NO\");\n\t\t\tcontinue;\n\t\t}\n\t\tputs(\"YES\");\n\t\tstring res(n, '.');\n\t\tforn(i, n) res[ord[i]] = i <= ans.first ? 'R' : 'B';\n\t\tprintf(\"%s %d\\n\", res.c_str(), ans.second + 1);\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1606",
    "index": "E",
    "title": "Arena",
    "statement": "There are $n$ heroes fighting in the arena. Initially, the $i$-th hero has $a_i$ health points.\n\nThe fight in the arena takes place in several rounds. At the beginning of each round, each alive hero deals $1$ damage to all other heroes. Hits of all heroes occur simultaneously. Heroes whose health is less than $1$ at the end of the round are considered killed.\n\nIf exactly $1$ hero remains alive after a certain round, then he is declared the winner. Otherwise, there is no winner.\n\nYour task is to calculate the number of ways to choose the initial health points for each hero $a_i$, where $1 \\le a_i \\le x$, so that there is no winner of the fight. The number of ways can be very large, so print it modulo $998244353$. Two ways are considered different if at least one hero has a different amount of health. For example, $[1, 2, 1]$ and $[2, 1, 1]$ are different.",
    "tutorial": "Let's calculate the following dynamic programming $dp_{i, j}$ - the number of ways to choose the initial health if there are $i$ heroes still alive, and they already received $j$ damage. Let's iterate over $k$ - the number of heroes that will survive after the next round. Then we have to make a transition to the state $dp_{k, nj}$, where $nj = \\min(x, j + i - 1)$ (the minimum of the maximum allowed health and $j$ plus the damage done in this round). It remains to understand with what coefficient we should make this transition in dynamic programming. This coefficient is equal to $\\binom{i}{i - k} \\cdot (nj - j)^{i - k}$ - the number of ways to choose which of the $i$ living heroes will die in this round multiplied by the number of ways to choose health for these $i - k$ heroes (because their health is greater than $j$ so that they are still alive at the moment, but not more than $nj$ so that they are guaranteed to die in this round). Of course, we don't make any transitions from the states $dp_{i,j}$ where $i < 2$, since they represent the fights that have already finished. The answer is the sum of all $dp_{0, j}$ for every $j \\in [0, x]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 505;\nconst int MOD = 998244353;\n\nint n, x;\nint c[N][N], dp[N][N];\n\nint add(int x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n  return x;\n}\n\nint mul(int x, int y) {\n  return x * 1ll * y % MOD;\n}\n\nint main() {\n  cin >> n >> x;\n  for (int i = 0; i <= n; ++i) {\n    c[i][0] = c[i][i] = 1;\n    for (int j = 1; j < i; ++j) \n      c[i][j] = add(c[i - 1][j], c[i - 1][j - 1]);\n  }\n  dp[n][0] = 1;\n  for (int i = n; i > 1; i--) {\n    for (int j = 0; j < x; ++j) {\n      if (!dp[i][j]) continue;\n      int pw = 1, nj = min(x, j + i - 1);\n      for (int k = i; k >= 0; k--) {\n        dp[k][nj] = add(dp[k][nj], mul(dp[i][j], mul(c[i][k], pw)));\n        pw = mul(pw, nj - j);\n      }\n    }\n  }\n  int ans = 0;\n  for (int i = 0; i <= x; ++i)\n    ans = add(ans, dp[0][i]);\n  cout << ans << endl;\n} ",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1606",
    "index": "F",
    "title": "Tree Queries",
    "statement": "You are given a tree consisting of $n$ vertices. Recall that a tree is an undirected connected acyclic graph. The given tree is rooted at the vertex $1$.\n\nYou have to process $q$ queries. In each query, you are given a vertex of the tree $v$ and an integer $k$.\n\nTo process a query, you may delete any vertices from the tree in any order, except for the root and the vertex $v$. When a vertex is deleted, its children become the children of its parent. You have to process a query in such a way that maximizes the value of $c(v) - m \\cdot k$ (where $c(v)$ is the resulting number of children of the vertex $v$, and $m$ is the number of vertices you have deleted). Print the maximum possible value you can obtain.\n\nThe queries are independent: the changes you make to the tree while processing a query don't affect the tree in other queries.",
    "tutorial": "A naive solution to this problem would be to implement a recursive function which answers each query: let $f(v, k)$ be the answer to the query \"$v$ $k$\", we can calculate it as $\\sum\\limits_{u \\in children(v)} \\max(1, f(u, k) - k)$, since for each child $u$ of vertex $v$, we either delete it and change the score by $f(u, k) - k$, or choose to let it remain, and this increases the score by $1$. Unfortunately, it is too slow. Let's try to optimize it. First of all, $f(v, k-1) \\ge f(v, k)$ since if we choose the exact same subset of vertices to delete for the query \"$v$ $k-1$\" as we've chosen for the query \"$v$ $k$\", our score won't decrease. Using this fact, we can show that if it's optimal to remove some vertex in the query \"$v$ $k$\", it's also optimal to remove a vertex in the query \"$v$ $k-1$\" because it's optimal to remove vertex $u$ if $f(u, k) - k > 1$, and if this condition holds for some value of $k$, then it holds for each smaller value of $k$. Let $opt(u)$ be the maximum value of $k$ when it's optimal to remove the vertex $u$. We will calculate these values for all vertices of the tree using an event processing method: we'll process the values of $k$ from $200000$ to $0$ and use a set or a priority queue to store events of the form \"at the value $i$, vertex $u$ becomes optimal to delete\". This set/priority queue should sort the events in descending order of the value of $k$, and in case of ties, in descending order of depths of the vertices (to make sure that vertices with the same value of $opt(u)$ are processed from bottom to up). Let's analyze the implementation of this process more in detail. For each vertex, we will store two values - the number of vertices we should remove from its subtree, and the number of children this vertex will optimally have. Using these two values, we can easily calculate the value of $opt$ for a vertex. When a vertex is \"removed\" (that is, the event corresponding to this vertex is processed), these values for this vertex should be added to its current parent (we can use DSU to find the current parent easily, for example; and don't forget that the number of vertices we have to remove for this new parent also increases by $1$); then we recalculate the value of $opt$ for the current parent and change the event corresponding to this current parent (note that the value of $opt$ for the current parent shouldn't be greater than the value of $opt$ for the vertex we've deleted). Okay, this allows us to calculate when it's optimal to delete each vertex. But how do we answer queries? One of the ways to do this is to process queries in the same event processing algorithm (and for every value of $k$, we first \"remove\" the vertices $u$ with $opt(u) = k$, then process the queries). There is an issue that when we remove a vertex, it can affect the answer not only for its current parent, but also for the vertices that could be its parents, but are already deleted; to handle this, instead of adding the values of the deleted vertex only to the values of its current parent, we perform an addition on the whole path from the vertex to the current parent (excluding the vertex itself). This path addition can be performed with a Fenwick or Segment tree over the Eulerian tour of the tree, and this yields a compexity of $O(n \\log n)$, though with a high constant factor.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nstruct Vertex\n{\n \tint cost;\n \tint depth;\n \tint idx;\n \tVertex() {};\n \tVertex(int cost, int depth, int idx) : cost(cost), depth(depth), idx(idx) {};\n};\n\nbool operator <(const Vertex& a, const Vertex& b)\n{\n \tif(a.cost != b.cost)\n \t\treturn a.cost > b.cost;\n \tif(a.depth != b.depth)\n \t\treturn a.depth > b.depth;\n \treturn a.idx < b.idx;\n}\n\nstruct DSU\n{\n\tint n;\n \tvector<int> p;\n \tvector<int> top;\n\n \tint get(int x)\n \t{\n \t\tif(p[x] == x)\n \t\t\treturn x;\n \t\treturn p[x] = get(p[x]); \t\n \t}\n\n \tint get_top(int x)\n \t{\n \t \treturn top[get(x)];\n \t}\n\n \tvoid merge(int x, int par)\n \t{\n \t \tp[x] = par;\n \t}\n\n \tDSU(int k = 0)\n \t{\n \t \tn = k;\n \t \tp.resize(n);\n \t \tiota(p.begin(), p.end(), 0);\n \t \ttop = p;\n \t};\n};\n\nconst int N = 200043;\n\nint n;\nvector<int> g[N];\nint p[N], d[N], tin[N], tout[N];\nint qv[N];\nint qk[N];\nint T = 0;\n\nvoid dfs(int v = 0, int par = -1)\n{\n \ttin[v] = T++;\n \tp[v] = par;\n \tif(par == -1)\n \t\td[v] = 0;\n \telse\n \t\td[v] = d[par] + 1;\n \tfor(auto x : g[v])\n \t\tif(x != par)\n \t\t\tdfs(x, v);\n \ttout[v] = T;\n}\n\npair<long long, long long> tree[4 * N];\n\npair<long long, long long> operator+(const pair<long long, long long>& a, const pair<long long, long long>& b)\n{\n \treturn make_pair(a.first + b.first, a.second + b.second);\n}\n\npair<long long, long long> get(int v, int l, int r, int L, int R)\n{\n \tif(L >= R) return {0, 0};\n \tif(l == L && r == R) return tree[v];\n \tint m = (l + r) / 2;\n \treturn get(v * 2 + 1, l, m, L, min(R, m)) + get(v * 2 + 2, m, r, max(m, L), R);\n}\n\nvoid add(int v, int l, int r, int pos, pair<long long, long long> val)\n{\n \tif(l == r - 1)\n \t\ttree[v] = tree[v] + val;\n \telse\n \t{\n \t \tint m = (l + r) / 2;\n \t \tif(pos < m) add(v * 2 + 1, l, m, pos, val);\n \t \telse add(v * 2 + 2, m, r, pos, val);\n \t \ttree[v] = tree[v] + val;\n \t}                                                                  \n}\n\npair<long long, long long> get_vertex_value(int v)\n{\n \treturn get(0, 0, n, tin[v], tout[v]);\n}\n\nvoid add_on_path(int x, int y, pair<long long, long long> val)\n{\n \t// x is a descendant of y\n \tadd(0, 0, n, tin[x], val);\n \tif(p[y] != -1)\n \t\tadd(0, 0, n, tin[p[y]], make_pair(-val.first, -val.second));\n}\n\nint calculate_cost(int v, int correction)\n{\n\t//cerr << v << \" \" << correction << endl;\n \tpair<long long, long long> res = get_vertex_value(v);\n \t// first - (second + 1) * k <= 0\n \tlong long k = (res.first + res.second) / (res.second + 1) - 1;\n \tif(correction < k) return correction;\n \treturn k;\n}\n\nint main()\n{\n\tscanf(\"%d\", &n);\n\tfor(int i = 1; i < n; i++)\n\t{\n\t \tint x, y;\n\t \tscanf(\"%d %d\", &x, &y);\n\t \t--x;\n\t \t--y;\n\t \tg[x].push_back(y);\n\t \tg[y].push_back(x);\n\t}\n\tint q;\n\tscanf(\"%d\", &q);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t \tscanf(\"%d %d\", &qv[i], &qk[i]);\n\t \t--qv[i];\n\t}                   \n\n\tdfs();\n\tDSU dsu(n);\n                        \n\tvector<long long> ans(q);\n\tset<Vertex> pq;\n\tvector<Vertex> curv(n);\n\tfor(int i = 0; i < n; i++)\n\t{                     \n\t \tint count_children = g[i].size();\n\t \tif(i != 0) count_children--;               \n\t \tadd_on_path(i, i, make_pair((long long)(count_children), 0ll)); \n\t \tif(i != 0)\n\t \t{\n\t \t\tcurv[i] = Vertex(calculate_cost(i, 200000), d[i], i);\n\t\t\tpq.insert(curv[i]);                                   \n\t \t}\n                          \n\t}\n                        \n\tfor(int i = 0; i < q; i++)\n\t\tpq.insert(Vertex(qk[i], -1, i));\n\n\twhile(!pq.empty())\n\t{\n\t\tVertex z = *pq.begin();\n\t\tpq.erase(pq.begin());\n\t\tif(z.depth == -1)\n\t\t{\n\t\t \tauto res = get_vertex_value(qv[z.idx]);\n\t\t \tans[z.idx] = res.first - res.second * z.cost;\n\t    }\n\t    else\n\t    {\n\t     \tint v = z.idx;\n\t     \tint pv = p[v];\n\t     \tint newtop = dsu.get_top(pv);\n\t     \tpair<long long, long long> val = get_vertex_value(v);\n\t     \tval.second++;\n\t     \tval.first--;\n\t     \tif(newtop != 0)\n\t     \t\tpq.erase(curv[newtop]);\n\t     \tadd_on_path(pv, newtop, val);\n\t     \tif(newtop != 0)\n\t     \t\tcurv[newtop].cost = calculate_cost(newtop, z.cost);\n\t     \tif(newtop != 0)\n\t     \t\tpq.insert(curv[newtop]);\n\t     \tdsu.merge(v, pv);\n\t    }\n\t}\t\n\n\tfor(int i = 0; i < q; i++)\n\t\tprintf(\"%lld\\n\", ans[i]);\n}",
    "tags": [
      "brute force",
      "dp",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1607",
    "index": "A",
    "title": "Linear Keyboard",
    "statement": "You are given a keyboard that consists of $26$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.\n\nYou have to type the word $s$ on this keyboard. It also consists only of lowercase Latin letters.\n\nTo type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.\n\nMoving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.\n\nFor example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $8$, $5$, $12$ and $15$, respectively. Therefore, it will take $|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$ units of time to type the word \"hello\".\n\nDetermine how long it will take to print the word $s$.",
    "tutorial": "Since it does not take time to place your hand over the first letter, you need to calculate the sum of the distances between the keyboard keys corresponding to each pair of adjacent letters of the word, that is $\\sum\\limits_{i=2}^n |\\mathtt{pos}(s_i) - \\mathtt{pos}(s_{i-1})|$ In order to calculate this sum, let's just iterate through the word $s$ with the for loop and find the differences between the positions of $s_i$ and $s_{i-1}$ on the keyboard. To find the position of a character on the keyboard, you could either use the built-in strings functions (such as str.index in Python or string::find in C++) or precalculate each letter's position on the keyboard into a separate array using another loop over a keyboard.",
    "code": "t = int(input())\nfor _ in range(t):\n    k, s = input(), input()\n    res = 0\n    for i in range(1, len(s)):\n        res += abs(k.index(s[i]) - k.index(s[i - 1]))\n    print(res)",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1607",
    "index": "B",
    "title": "Odd Grasshopper",
    "statement": "The grasshopper is located on the numeric axis at the point with coordinate $x_0$.\n\nHaving nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $x$ with a distance $d$ to the left moves the grasshopper to a point with a coordinate $x - d$, while jumping to the right moves him to a point with a coordinate $x + d$.\n\nThe grasshopper is very fond of positive integers, so for each integer $i$ starting with $1$ the following holds: exactly $i$ minutes after the start he makes a jump with a distance of exactly $i$. So, in the first minutes he jumps by $1$, then by $2$, and so on.\n\nThe direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an \\textbf{even} coordinate, the grasshopper jumps to the \\textbf{left}, \\textbf{otherwise} he jumps to the \\textbf{right}.\n\nFor example, if after $18$ consecutive jumps he arrives at the point with a coordinate $7$, he will jump by a distance of $19$ to the right, since $7$ is an odd number, and will end up at a point $7 + 19 = 26$. Since $26$ is an even number, the next jump the grasshopper will make to the left by a distance of $20$, and it will move him to the point $26 - 20 = 6$.\n\nFind exactly which point the grasshopper will be at after exactly $n$ jumps.",
    "tutorial": "Consider the first four actions that the grasshopper will perform, starting at a point with coordinate $0$: coordinate $0$ is even, jumping left to $1$ leads to $-1$ coordinate $-1$ is odd, jumping right to $2$ leads to $2$ coordinate $1$ is odd, jumping right to $3$ leads to $4$ coordinate $4$ is even, jumping left to $4$ leads to $0$ If you look closely at the next four jumps, they follow the same pattern: jump to the left, two jumps to the right, jump to the left. In general, making jumps with numbers $4k + 1 \\ldots 4k + 4$, the grasshopper will start from coordinate $0$ and move as $0 \\underset{\\ ^{-(4k+1)}}{\\longrightarrow} -(4k + 1) \\underset{\\ ^{+(4k+2)}}{\\longrightarrow} 1 \\underset{\\ ^{+(4k+3)}}{\\longrightarrow} 4k + 4 \\underset{\\ ^{-(4k+4)}}{\\longrightarrow} 0$ Thus, if $x_0$ were always zero, the answer would be $-n$ if $n \\equiv 1 \\bmod 4$ $1$ if $n \\equiv 2 \\bmod 4$ $n + 1$ if $n \\equiv 3 \\bmod 4$ $0$ if $n$ is divisible by $4$ Let's find an answer for the cases when $x_0 \\neq 0$. But if $x_0$ is even, then all steps will follow the same directions, and the answer will be $x_0 + D$, where $D$ is the answer for the same $n$ and starting point $0$ (described above). And if $x_0$ is odd, then all steps will have opposite directions, and the answer will be $x_0 - D$.",
    "code": "t = int(input())\nmaps = [\n    lambda x: 0,\n    lambda x: x,\n    lambda x: -1,\n    lambda x: -x - 1\n]\n\nfor _ in range(t):\n    x0, n = map(int, input().split())\n    d = maps[n % 4](n)\n    print(x0 - d if x0 % 2 == 0 else x0 + d)",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1607",
    "index": "C",
    "title": "Minimum Extraction",
    "statement": "Yelisey has an array $a$ of $n$ integers.\n\nIf $a$ has length strictly greater than $1$, then Yelisei can apply an operation called minimum extraction to it:\n\n- First, Yelisei finds the minimal number $m$ in the array. If there are several identical minima, Yelisey can choose any of them.\n- Then the selected minimal element is removed from the array. After that, $m$ is subtracted from each remaining element.\n\nThus, after each operation, the length of the array is reduced by $1$.\n\nFor example, if $a = [1, 6, -4, -2, -4]$, then the minimum element in it is $a_3 = -4$, which means that after this operation the array will be equal to $a=[1 {- (-4)}, 6 {- (-4)}, -2 {- (-4)}, -4 {- (-4)}] = [5, 10, 2, 0]$.\n\nSince Yelisey likes big numbers, he wants the numbers in the array $a$ to be as big as possible.\n\nFormally speaking, he wants to make the \\textbf{minimum} of the numbers in array $a$ to be \\textbf{maximal possible} (i.e. he want to maximize a minimum). To do this, Yelisey can apply the minimum extraction operation to the array as many times as he wants (possibly, zero). Note that the operation cannot be applied to an array of length $1$.\n\nHelp him find what maximal value can the minimal element of the array have after applying several (possibly, zero) minimum extraction operations to the array.",
    "tutorial": "Note that the order of numbers in the array does not affect anything. If you swap two elements in the original array, the set of elements at each step will not change in any way. Let's sort the original array $a$ and denote it by $a^0$. We denote by $a^i$ the state of array $a^0$ after applying $i$ operations of minimum extraction. The minimum element in $a^0$ is $a^0_1$, so the elements of array $a^1$ will be equal to $a^1_i = a^0_{i+1} - a^0_1$, and therefore the minimum of them will be $a^0_2 - a^0_1$. Constructing an array $a^2$, we can notice that its elements are equal to $a^2_i = a^1_{i+1} - a^1_1$. We know that the elements of $a^1$ are the difference between corresponding elements of the array $a^0$ and $a^0_1$, so $a^2_i = a^1_{i+1} - a^1_1 = (a^0_{i+2} - a^0_1) - (a^0_2 - a^0_1) = a^0_{i+2} - a^0_2$ Thus, the elements of the array $a^2$ are the differences between elements of $a^0$ starting with third and $a^0_2$, the minimum of which is $a^0_3 - a^0_2$. It is not difficult to show in a similar way (for example by induction) that the elements of $a^c$ are equal to $a^c_i = a^0_{i+c} - a^0_c$, the minimum of which is $a^0_{c+1} - a^0_c$. So the \"candidates\" for the answer are simply differences of adjacent elements of the array $a^0$. Indeed, if we look at $a^0 = [1, 4, 6, 12, 13]$, it will undergo changes as follows: $[\\color{blue}{1}, 4, 6, 12, 15] \\to [\\color{blue}{3}, 5, 11, 14] \\to [\\color{blue}{2}, 8, 11] \\to [\\color{blue}{6}, 9] \\to [\\color{blue}{3}]$. You can notice that the minimum elements starting with after the first operation are exactly $4 - 1$, $6 - 4$, $12 - 6$ and $15 - 12$, respectively. Thus, to solve the problem, it was sufficient to sort the array in ascending order, then take the maximum of the original first element and the differences of all adjacent elements $\\max\\left(a^0_1, \\max\\limits_{i=2}^n \\left(a^0_i - a^0_{i-1}\\right) \\right)$",
    "code": "t = int(input())\n\nfor _ in range(t):\n    n = int(input())\n    a = sorted(list(map(int, input().split())))\n    res = a[0]\n    for i in range(n - 1):\n        res = max(res, a[i + 1] - a[i])\n    print(res)",
    "tags": [
      "brute force",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1607",
    "index": "D",
    "title": "Blue-Red Permutation",
    "statement": "You are given an array of integers $a$ of length $n$. The elements of the array can be either different or the same.\n\nEach element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step:\n\n- either you can select any blue element and decrease its value by $1$;\n- or you can select any red element and increase its value by $1$.\n\nSituations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.\n\nDetermine whether it is possible to make $0$ or more steps such that the resulting array is a permutation of numbers from $1$ to $n$?\n\nIn other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $a$ contains in some order all numbers from $1$ to $n$ (inclusive), each exactly once.",
    "tutorial": "Note the following fact: if a number $x$ in a permutation was obtained from a blue number and a number $y$ in a permutation was obtained from a red number, and $x > y$, then by decreasing the blue number and increasing the red number exactly $x - y$ times each, we will obtain the same permutation in which the two numbers have swapped places. Thus, if a permutation can be obtained at all, some permutation can be obtained by making all the red numbers equal to $n, n - 1, \\ldots, n - k + 1$, and the blue ones equal to $1, 2, \\ldots, n - k$, where $k$ is the total count of red numbers. Now consider separately two red numbers $a_i$ and $a_j$ such that $a_i > a_j$. If $x$ is produced by increasing $a_i$ and $y$ is produced by increasing $a_j$, and in the same time $x < y$ then $y > x \\geqslant a_i > a_j$, and the following is also true: $x > a_j$ and $y > a_i$. So we just showed that if an answer exists, it also exists if greater numbers are produced by greater values from the input. The same holds for the blue numbers. Let us sort all elements $a_i$ by the key $(c_i, a_i)$, where $c_i$ the color of $i$-th element (and blue comes before red). It remains to check that for any $t$ from $1$ to $n$ we can get the number $t$ from the $t$-th element of the obtained sorted array. To do this, we iterate through it and check that either $c_t = \\,$'B' and $a_t \\geqslant t$ so it can be reduced to $t$, or, symmetrically, $c_t = \\,$'R' and $a_t \\leqslant t$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        forn(i, n)\n            cin >> a[i];\n\n        string c;\n        cin >> c;\n\n        vector<int> l, r;\n        forn(i, n)\n            (c[i] == 'B' ? l : r).push_back(a[i]);\n        sort(l.begin(), l.end());\n        sort(r.begin(), r.end(), greater<int>());\n\n        bool ok = true;\n        forn(i, l.size())\n            if (l[i] < i + 1)\n                ok = false;\n        forn(i, r.size())\n            if (r[i] > n - i)\n                ok = false;\n\n        cout << (ok ? \"YES\" : \"NO\") << '\\n';\n    }\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1607",
    "index": "E",
    "title": "Robot on the Board 1",
    "statement": "The robot is located on a checkered rectangular board of size $n \\times m$ ($n$ rows, $m$ columns). The rows in the board are numbered from $1$ to $n$ from top to bottom, and the columns — from $1$ to $m$ from left to right.\n\nThe robot is able to move from the current cell to one of the four cells adjacent by side.\n\nThe sequence of commands $s$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.\n\nThe robot can start its movement in \\textbf{any} cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $s$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is \\textbf{not considered} successfully executed.\n\nThe robot's task is to execute as many commands as possible without falling off the board. For example, on board $3 \\times 3$, if the robot starts a sequence of actions $s=$\"RRDLUU\" (\"right\", \"right\", \"down\", \"left\", \"up\", \"up\") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $(2, 1)$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $(1, 2)$ (first row, second column).\n\n\\begin{center}\n{\\small The robot starts from cell $(2, 1)$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $(1, 2)$ (first row, second column).}\n\\end{center}\n\nDetermine the cell from which the robot should start its movement in order to execute as many commands as possible.",
    "tutorial": "Let's look at the answer $(r, c)$. Let's see how many commands the robot can execute. Since the robot breaks as soon as goes outside the field, if any command causes it to break, it either leads to its total shift relative to $(r, c)$ of exactly $c$ to the left or exactly $m - c + 1$ to the right, or, similarly, of exactly $r$ up or exactly $n - r + 1$ down. Denote by $d[\\leftrightarrow]$ and $d[\\updownarrow]$ the sum of the maximum positive (right, down) and maximum negative (left, up) shifts in the corresponding direction. By adding up the above constraints, we get the fact that the robot will not fall off the board only if $d[\\leftrightarrow] \\leqslant (c - 1) + ((m - c + 1) - 1) = m - 1$ and $d[\\updownarrow] \\leqslant (r - 1) + ((n - r + 1) - 1) = n - 1$. Note that the reverse is also true: if both these conditions are satisfied, then starting from the point $(\\max[\\leftarrow] + 1, \\max[\\uparrow] + 1)$ where $\\max[\\mathtt{dir}]$ is the maximum shift along the direction $\\mathtt{dir}$, the robot will not pass any of the board's edges. Thus, it is sufficient to find the number of commands which, when executed, hold the following invariant: $d[\\leftrightarrow] \\leqslant m - 1 \\land d[\\updownarrow] \\leqslant n - 1$ The horizontal shift can be calculated as the difference between the number of letters 'R' and the number of letters 'L' encountered. Similarly, the vertical shift - as the difference of the numbers of 'D' and 'U'. Let's iterate over the sequence of commands, maintaining relevant values of $\\max[\\mathtt{dir}]$ for all $\\mathtt{dir} \\in [\\leftarrow, \\rightarrow, \\uparrow, \\downarrow]$. After executing each command, if the robot goes farther in some direction than ever before, we update the corresponding $\\max$. Either we reach the end of $s$, or we meet a command after which either $d[\\leftrightarrow] = \\max[\\leftarrow] + \\max[\\rightarrow]$ becomes equal to $m$, or $d[\\updownarrow] = \\max[\\uparrow] + \\max[\\downarrow]$ becomes equal to $n$ and the robot breaks, so the previous command was the last one successfully executed. The possible answer is $(\\max[\\leftarrow] + 1, \\max[\\uparrow] + 1)$, where the $\\max$ values are calculated one command before the robot broke.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        string s;\n        cin >> s;\n\n        int bx = 0, by = 0;\n        int min_bx = 0, max_bx = 0, min_by = 0, max_by = 0;\n        for (char c: s) {\n            if      (c == 'L') min_by = min(min_by, --by);\n            else if (c == 'R') max_by = max(max_by, ++by);\n            else if (c == 'U') min_bx = min(min_bx, --bx);\n            else               max_bx = max(max_bx, ++bx);\n\n            if (max_bx - min_bx >= n) {\n                if (bx == min_bx) min_bx++;\n                break;\n            }\n            if (max_by - min_by >= m) {\n                if (by == min_by) min_by++;\n                break;\n            }\n        }\n\n        cout << 1 - min_bx << ' ' << 1 - min_by << '\\n';\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1607",
    "index": "F",
    "title": "Robot on the Board 2",
    "statement": "The robot is located on a checkered rectangular board of size $n \\times m$ ($n$ rows, $m$ columns). The rows in the board are numbered from $1$ to $n$ from top to bottom, and the columns — from $1$ to $m$ from left to right.\n\nThe robot is able to move from the current cell to one of the four cells adjacent by side.\n\nEach cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cell — left, right, down or up, respectively.\n\nThe robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move.\n\n- If the robot moves beyond the edge of the board, it falls and breaks.\n- If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore).\n\nRobot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops.\n\nDetermine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board).",
    "tutorial": "Let's start moving from an arbitrary cell of the table, for example, from $(1, 1)$. Movement from each cell is specified by the direction given in that cell, so you can run a loop with a stopping condition \"exit from the board border or get to the already visited cell\". Create a separate array $d[r][c]$ - how many commands the robot will execute, starting the movement from the cell $(r, c)$; we will also use it to check whether the cell has already been visited or not (not visited if $d[r][c]$ is not yet positive). Finishing the movement from $(1, 1)$ let's consider two cases. Either we have gone beyond the boundary of the array, then we can say for sure that for the $i$-th cell from the end of the sequence $(r_i, c_i)$ the answer is $d[r_i][c_i] = i$. Or we came to the already visited cell, let it be the $t$-th from the end in our path. Then at the end of the path, there is a cycle of length $t$: starting the movement at any cell of this cycle, the robot will walk exactly $t$ steps until it arrives at the already visited cell. Thus, for $i \\leqslant t$ distance will be equal to $d[r_i][c_i] = t$, and for all others it will be, as in the first case, $d[r_i][c_i] = i$. Let us run the same algorithm from the next cell, which we have not yet considered. There will be three cases of robot stopping the execution of the commands: the first two repeat those already considered above, and the third case is that the robot will come to the cell $(r_0, c_0)$ already visited on some of the previous iterations of our algorithm. In this case we know that starting from $(r_0, c_0)$, the robot will make exactly $d[r_0][c_0]$ steps, so for the $i$-th cell from the end on the current path $d[r_i][c_i] = d[r_0][c_0] + i$ will hold. The first two cases are handled completely in the same way as described above. Each of the cases is eventually reduced to another iteration over the cells visited in the current path. Let's visit all the cells in reverse and mark all values of $d$. Such algorithm is enough to repeat until each cell is processed, after which for each cell of the table its $d$ will be known and we'll only have to choose the maximal value of $d[r][c]$ among all $(r, c)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector<int> vi;\ntypedef pair<int, int> pii;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        vector<string> dir(n);\n        for (int i = 0; i < n; i++)\n            cin >> dir[i];\n\n        vector<vi> res(n, vi(m, 0));\n        int opt = 0, optr = 0, optc = 0;\n        for (int r = 0; r < n; r++) {\n            for (int c = 0; c < m; c++) {\n                if (res[r][c] > 0)\n                    continue;\n\n                int nr = r, nc = c;\n                int depth = 0;\n                vector<pii> path;\n                auto ok = [&n, &m](int row, int col) {\n                    return row > -1 && row < n && col > -1 && col < m;\n                };\n\n                do {\n                    res[nr][nc] = --depth;\n                    path.emplace_back(nr, nc);\n                    if (dir[nr][nc] == 'L')\n                        nc--;\n                    else if (dir[nr][nc] == 'R')\n                        nc++;\n                    else if (dir[nr][nc] == 'U')\n                        nr--;\n                    else\n                        nr++;\n                } while (ok(nr, nc) && res[nr][nc] == 0);\n\n                int start = 1;\n                if (ok(nr, nc)) {\n                    if (res[nr][nc] < 0) {\n                        int cycle = res[nr][nc] - depth + 1;\n                        for (int i = 0; i < cycle; i++) {\n                            auto p = path.back();\n                            path.pop_back();\n                            res[p.first][p.second] = cycle;\n                        }\n                    }\n                    start = res[nr][nc] + 1;\n                }\n                while (!path.empty()) {\n                    auto p = path.back();\n                    path.pop_back();\n                    res[p.first][p.second] = start++;\n                }\n\n                if (res[r][c] > opt) {\n                    opt = res[r][c];\n                    optr = r;\n                    optc = c;\n                }\n            }\n        }\n\n        cout << optr + 1 << ' ' << optc + 1 << ' ' << opt << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1607",
    "index": "G",
    "title": "Banquet Preparations 1",
    "statement": "A known chef has prepared $n$ dishes: the $i$-th dish consists of $a_i$ grams of fish and $b_i$ grams of meat.\n\nThe banquet organizers estimate the balance of $n$ dishes as follows. The balance is equal to the absolute value of the difference between the total mass of fish and the total mass of meat.\n\nTechnically, the balance equals to $\\left|\\sum\\limits_{i=1}^n a_i - \\sum\\limits_{i=1}^n b_i\\right|$. The smaller the balance, the better.\n\nIn order to improve the balance, a taster was invited. He will eat \\textbf{exactly} $m$ grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he should eat exactly $m$ grams of each dish in total.\n\nDetermine how much of what type of food the taster should eat from each dish so that the value of the balance is as minimal as possible. If there are several correct answers, you may choose any of them.",
    "tutorial": "Let's find how much meat and fish a taster can eat at most. Note that a taster can eat no more than $\\min(a_i, m)$ of fish from the $i$-th dish (since he can't eat more than $m$ or more than there is at all). Similarly, he can eat no more than $\\min(b_i, m)$ of meat. Let's sum the obtained values over all $i$ and denote the resulting sums by $A$ and $B$ -the maximum total amount of fish and meat that can be eaten. Let's denote by balance* $T$ the value $\\sum\\limits_{i=1}^n a_i - \\sum\\limits_{i=1}^n b_i$, that is the balance without module. If the taster eats as much fish as possible, he will eat $A$ of fish and $nm - A$ of meat, and change the balance* by $-A + (nm - A) = nm - 2A$. Similarly, if he eats the maximum amount of meat, the balance* will change by $2B - nm$. Note that the taster can achieve any balance* between $2B - nm$ and $nm - 2A$ of the same oddity as both of these numbers. To do this, just take the way of eating the maximum fish and substitute eating a gram of fish for a gram of meat several times. Thus, the final balance $T_\\mathtt{res}$ can be found as $\\min |x|$ over all $x$ between $T + (2B - nm)$ and $T + (nm - 2A)$ with same oddity. To do this, just check the boundaries of the resulting segment - if they have the same sign, then it's the boundary with the smallest absolute value, otherwise we can take one of the numbers $-1$, $0$, $1$ present in said set (depending on the parity of $nm$). All that remains is to find how much of what type to eat from each dish. Having obtained the answer in the previous paragraph (the final balance), we can reconstruct how much fish and how much meat the taster has to eat to achieve it. The expected amount of fish to be eaten can be found as $e_A = \\frac{T + nm - T_\\mathtt{res}}{2}$. Note that the taster must eat $\\max(m - b_i, 0)$ of fish from the $i$-th dish, since if meat $b_i < m$, then at least $m - b_i$ of fish is guaranteed to be eaten. Let's break down $e_A$ into the sum of $nm - B$ (how much total fish will have to be eaten anyway) and the remaining value $g_A = e_A - (nm - B)$. Let's go through all the dishes and collect the first summand as just the sum of $\\max(m - b_i, 0)$ over all $i$, and the second summand with greedy algorithm, each time giving the taster as much fish beyond what he must eat anyway until the sum of such \"additions\" reaches $g_A$. And knowing for each dish how much fish will be eaten from it, the amount of meat eaten can be calculated by subtracting the fish eaten from $m$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef pair<int, int> pii;\ntypedef long long ll;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        vector<pii> dishes(n);\n        ll balance = 0;\n        ll max_a = 0, max_b = 0;\n        ll total_eat = static_cast<long long>(n) * m;\n\n        for (int i = 0; i < n; i++) {\n            cin >> dishes[i].first >> dishes[i].second;\n            balance += dishes[i].first - dishes[i].second;\n            max_a += min(m, dishes[i].first);\n            max_b += min(m, dishes[i].second);\n        }\n        ll max_delta = 2 * max_a - total_eat, min_delta = total_eat - 2 * max_b;\n        ll min_a = total_eat - max_b;\n\n        ll eat_a;\n        if (balance < 0) {\n            eat_a = min_a;\n            if (balance - min_delta >= 0)\n                eat_a = min(max_a, (total_eat + balance + 1) / 2);\n        } else {\n            eat_a = max_a;\n            if (balance - max_delta <= 0)\n                eat_a = min(max_a, (total_eat + balance + 1) / 2);\n        }\n        ll ans = abs(balance - 2 * eat_a + total_eat);\n\n        cout << ans << '\\n';\n        ll rest_a = eat_a - min_a;\n        for (int i = 0; i < n; i++) {\n            ll cur_a = 0;\n            if (dishes[i].second < m)\n                cur_a += m - dishes[i].second;\n            ll add = min(rest_a, min(m - cur_a, dishes[i].first - cur_a));\n            cur_a += add;\n            rest_a -= add;\n            cout << cur_a << ' ' << m - cur_a << '\\n';\n        }\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1607",
    "index": "H",
    "title": "Banquet Preparations 2",
    "statement": "The chef has cooked $n$ dishes yet again: the $i$-th dish consists of $a_i$ grams of fish and $b_i$ grams of meat.\n\nBanquet organizers consider two dishes $i$ and $j$ equal if $a_i=a_j$ and $b_i=b_j$ at the same time.\n\nThe banquet organizers estimate the variety of $n$ dishes as follows. The variety of a set of dishes is equal to the number of different dishes in it. The \\textbf{less} variety is, the \\textbf{better}.\n\nIn order to reduce the variety, a taster was invited. He will eat \\textbf{exactly} $m_i$ grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he will eat exactly $m_i$ grams of the $i$-th dish in total.\n\nDetermine how much of what type of food the taster should eat from each dish so that the value of variety is the minimum possible. If there are several correct answers, you may output any of them.",
    "tutorial": "Note that dishes can become equal if and only if they have equal values of $a_i + b_i - m_i$, that is, how much fish and meat remain in them in total after \"tasting\". Let's calculate this value for each dish and group all the dishes with equal calculated values. The minimum amount of fish that can remain in the $i$-th dish is $a_i^\\mathtt{min} = \\max(0, a_i - m_i)$ in case where the maximum possible mass of fish is eaten. Similarly, the maximum amount of fish that can remain is $a_i^\\mathtt{max} = a_i + \\min(0, b_i - m_i)$ in case where the maximum possible mass of meat is eaten. Consider one of the groups $g$ in which there are all the dishes with equal values $G = a_i + b_i - m_i$. We sill assign each dish a corresponding segment on the coordinate line between $a_i^{\\mathtt{min}}$ and $a_i^{\\mathtt{max}}$. This segment specifies all possible values of the remaining mass of fish in the dish; any value on it is achievable by replacing eating some mass of fish with the same mass of meat. And since $G$ is common, the same amount of remaining fish will imply the same amount of remaining meat, thus, equality. Let us solve the problem for each group independently. Within a group, the problem is reduced to choosing as few points as possible that \"cover\" all the segments described in the last paragraph (that is, that there should be a point inside each segment). Each selected point will correspond to the resulting dish, and it being inside a segment will mean that such a resulting dish can be obtained from the corresponding starting one. Such a problem is solved as follows: we choose a segment with the minimal right end; because it must contain at least one chosen point we'll greedily choose it equal to its right end; there's no point in choosing a point to the left from it, since it will not cover more segments than the right end of the segment in question; we'll mark all segments containing this point as covered, and repeat the algorithm for the next unprocessed segment with the minimal right end. For this algorithm, it is sufficient to sort the segments by their right ends within each group and iterate through the segments, greedily selecting points in the manner described above. The set of points obtained at the end will be the answer, and its size and the information about the point selected within each segment should be printed in the output. If for a dish $(a_i, b_i, m_i)$ a point $x$ is chosen inside its corresponding segment, then there should be exactly $x$ of fish left in it, that is, you should output the numbers $a_i - x$ and $m_i - (a_i - x)$ in the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nstruct seg {\n    int a, b, m;\n    int index;\n};\n\nint n, ans;\nvector<seg> segments;\nmap<int, vector<seg>> diags;\n\nvoid erase(multiset<pair<pair<int,int>, int>>& lr, int l, int r, int index) {\n    pair<pair<int,int>,int> plr = make_pair(make_pair(l, r), index);\n    auto i = lr.find(plr);\n    assert(i != lr.end());\n    lr.erase(i);\n}\n\nvoid erase(multiset<pair<pair<int,int>, int>>& lr, multiset<pair<pair<int,int>, int>>& rl, int l, int r, int index) {\n    erase(lr, l, r, index);\n    erase(rl, r, l, index);\n}\n\nmap<int, pair<int,int>> dd;\n\nvoid setup_dd(int index, int value) {\n    assert(dd.count(index) == 0);\n    int x = segments[index].a - value;\n    int y = segments[index].m - x;\n    assert(segments[index].a - x >= 0);\n    assert(segments[index].b - y >= 0);\n    assert(x + y == segments[index].m);\n    dd[index] = make_pair(x, y);\n}\n\nint solve(vector<seg> s) {\n    int n = s.size();\n    multiset<pair<pair<int,int>, int>> lr;\n    multiset<pair<pair<int,int>, int>> rl;\n    forn(i, n) {\n        int min_d = max(s[i].m - s[i].b, 0);\n        int max_d = min(s[i].a, s[i].m);\n        lr.insert(make_pair(make_pair(s[i].a - max_d, s[i].a - min_d), s[i].index));\n        rl.insert(make_pair(make_pair(s[i].a - min_d, s[i].a - max_d), s[i].index));\n    }\n\n    int result = 0;\n    while (!rl.empty()) {\n        result++;\n        auto min_r_iterator = rl.begin();\n        int r = min_r_iterator->first.first;\n        int l = min_r_iterator->first.second;\n        int index = min_r_iterator->second;\n        erase(lr, rl, l, r, index);\n        setup_dd(index, r);\n\n        while (!lr.empty()) {\n            auto min_l_iterator = lr.begin();\n            int ll = min_l_iterator->first.first;\n            int rr = min_l_iterator->first.second;\n            int ii = min_l_iterator->second;\n            if (ll <= r) {\n                erase(lr, rl, ll, rr, ii);\n                setup_dd(ii, r);\n            } else\n                break;\n        }\n    }\n\n    return result;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        cin >> n;\n        diags.clear();\n        dd.clear();\n        segments = vector<seg>(n);\n        forn(i, n) {\n            seg s;\n            s.index = i;\n            cin >> s.a >> s.b >> s.m;\n            diags[s.a + s.b - s.m].push_back(s);\n            segments[i] = s;\n        }\n        int sum = 0;\n        for (auto p: diags)\n            sum += solve(p.second);\n        cout << sum << '\\n';\n        forn(i, n)\n            cout << dd[i].first << \" \" << dd[i].second << '\\n';\n    }\n}",
    "tags": [
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1608",
    "index": "A",
    "title": "Find Array",
    "statement": "Given $n$, find any array $a_1, a_2, \\ldots, a_n$ of integers such that all of the following conditions hold:\n\n- $1 \\le a_i \\le 10^9$ for every $i$ from $1$ to $n$.\n- $a_1 < a_2 < \\ldots <a_n$\n- For every $i$ from $2$ to $n$, $a_i$ isn't divisible by $a_{i-1}$\n\nIt can be shown that such an array always exists under the constraints of the problem.",
    "tutorial": "Notice that $x$ is never divisible by $x-1$ for $x \\geq 3$, so we can output $2, 3, \\dots, n, n+1$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1608",
    "index": "B",
    "title": "Build the Permutation",
    "statement": "You are given three integers $n, a, b$. Determine if there exists a permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$, such that:\n\n- There are exactly $a$ integers $i$ with $2 \\le i \\le n-1$ such that $p_{i-1} < p_i > p_{i+1}$ (in other words, there are exactly $a$ local maximums).\n- There are exactly $b$ integers $i$ with $2 \\le i \\le n-1$ such that $p_{i-1} > p_i < p_{i+1}$ (in other words, there are exactly $b$ local minimums).\n\nIf such permutations exist, find any such permutation.",
    "tutorial": "First, answer does not exists if $a+b+2 > n$. Second, answer exists if and only if $|a-b| \\leq 1$. It happens because between every two consecutive local maximums must be exactly one local minimum. And vice versa, between two consecutive minimums must be exactly one maximum. First case gives $b \\geq a-1$, second - $a \\geq b-1$, both in total gives $a-1 \\leq b \\leq a+1$. Lets build answer considering $a \\geq b$. Otherwise we can build inverse answer: swap $a$ and $b$, and perform replace $p_i = n - p_i + 1$. Lets take $a+b+2$ biggest numbers (i. e. from $n$ downto $n-a-b-1$) and put them consequentially, such numbers on first position and on each second position from first are less then other numbers. It gives that every number, except first and last, are local maximum or local minimum. Rest of the numbers needed to be placed before this sequence in increasing order.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1608",
    "index": "C",
    "title": "Game Master",
    "statement": "$n$ players are playing a game.\n\nThere are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map.\n\nYou are the game master and want to organize a tournament. There will be a total of $n-1$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament.\n\nIn the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.",
    "tutorial": "Let's look at the fights in the reversed order. If player $x$ is the winner, then he won against some player $y$ in the last fight. In $(n-2)$-th fight either $x$ or $y$ won against some player $z$, and so on. We always expand the set by adding a player that can lose against at least one player in the set, so if we can start from $x$ and end up with the set of all players, $x$ can win the tournament. If we construct a directed graph where we add an edge from player $u$ to player $v$ if and only if $u$ can win against $v$ in a fight, the problem is equivalent to finding the set of nodes from which we can reach all the other nodes. To reduce the number of edges to $2n-2$, we can sort players descending by $a_i$ and by $b_i$ and add only edges from $i$-th to $(i+1)$-th player in these orders. Notice that $x$ can win the tournament if and only if there is a path from $x$ to the player with maximum $a_i$. To find the set of such nodes, we can run DFS from the player with maximum $a_i$ on the graph with each edge reversed, or do two pointers technique on arrays of players sorted by $a_i$ and $b_i$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1608",
    "index": "D",
    "title": "Dominoes",
    "statement": "You are given $n$ dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.\n\nThe coloring is said to be \\textbf{valid} if and only if it is possible to rearrange the dominoes in some order such that for each $1 \\le i \\le n$ the color of the right cell of the $i$-th domino is different from the color of the left cell of the $((i \\bmod n)+1)$-st domino.\n\nNote that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.\n\nCount the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).\n\nAs this number can be very big, output it modulo $998\\,244\\,353$.",
    "tutorial": "If domino coloring is valid we can split cells into $n$ pairs of cells with opposite colors, so there is exactly $n$ cells of each color. Let $C_B$ and $C_W$ be the number of black and the number of white cells in the input, respectively. If $C_B > n$ or $C_W > n$, then the answer is $0$. Otherwise, the number of colorings with exactly $n$ cells of each color is $\\binom{2n - C_W - C_B}{n - C_W}$. Unfortunately, some of these colorings are invalid, so we need to subtract them. If there is at least one completely white or completely black domino we can first rearrange them and easily insert multicolored dominoes in between. If all the dominoes are colored in WB or BW the coloring is valid if and only if all dominoes are colored in the same pattern. We have to subtract the number of colorings where each domino is multicolored and they are not all colored in the same pattern. This can be easily done by finding the number of ways to color each domino in WB or BW, multiplying these numbers and possibly subtracting the cases when all the dominoes are colored in the same pattern.",
    "tags": [
      "combinatorics",
      "fft",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1608",
    "index": "E",
    "title": "The Cells on the Paper",
    "statement": "On an endless checkered sheet of paper, $n$ cells are chosen and colored in three colors, where $n$ is divisible by $3$. It turns out that there are exactly $\\frac{n}{3}$ marked cells of each of three colors!\n\nFind the largest such $k$ that it's possible to choose $\\frac{k}{3}$ cells of each color, remove all other marked cells, and then select three rectangles with sides parallel to the grid lines so that the following conditions hold:\n\n- No two rectangles can intersect (but they can share a part of the boundary). In other words, the area of intersection of any two of these rectangles must be $0$.\n- The $i$-th rectangle contains all the chosen cells of the $i$-th color and no chosen cells of other colors, for $i = 1, 2, 3$.",
    "tutorial": "Rectangles in optimal answer always arranged in one of the following ways: horizontally from left to right; divided by <<T>>: first rectangle is upper than second and third, and the second is to the left of the third; rotations of previous ways. Lets consider all four rotations and find best answer for arrangements 1 and 2. Additionally, fix the order of colors, they will be $3!=6$. Arrangement 1 can be found by binary search on $k$. Greedily take $k$ leftmost points of first color and $k$ rightmost points of third. Check if rectangles does not cross and it is enough points of seconds color between rectangles. Arrangement 2 is binary search on $k$ too. Take $k$ uppermost points of first color, in remaining area take $k$ leftmost points of second color, check if is enough points of third color in remaining area. Considering the constant factor, in total solution works in $O(36nlogn)$. Bonus. Task can be solved in $O(36n + nlogn)$. In first, sort all points once by $x$ and once by $y$. Arrangement 1 can be solved by two pointers in $O(n)$. For arrangement 2 let first (upper) rectangle be empty, and all points be divided into two noncrossed rectangles in such way that difference between sizes is minimal possible. Now lets move bottom of first rectangle and remove points of second and third colors from their rectangles keeping difference as minimum as possible. It can be achieved with linked list in $O(n)$.",
    "tags": [
      "binary search",
      "implementation",
      "sortings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1608",
    "index": "F",
    "title": "MEX counting",
    "statement": "For an array $c$ of nonnegative integers, $MEX(c)$ denotes the smallest nonnegative integer that doesn't appear in it. For example, $MEX([0, 1, 3]) = 2$, $MEX([42]) = 0$.\n\nYou are given integers $n, k$, and an array $[b_1, b_2, \\ldots, b_n]$.\n\nFind the number of arrays $[a_1, a_2, \\ldots, a_n]$, for which the following conditions hold:\n\n- $0 \\le a_i \\le n$ for each $i$ for each $i$ from $1$ to $n$.\n- $|MEX([a_1, a_2, \\ldots, a_i]) - b_i| \\le k$ for each $i$ from $1$ to $n$.\n\nAs this number can be very big, output it modulo $998\\,244\\,353$.",
    "tutorial": "Let's count $dp[pos][mex][big]$ - the number of ways to assign first $pos$ elements in a way that: $|MEX([a_1, a_2, \\ldots, a_i]) - b_i| \\le k$ for each $i$ from $1$ to $pos$. $|MEX([a_1, a_2, \\ldots, a_i]) - b_i| \\le k$ for each $i$ from $1$ to $pos$. $MEX([a_1, a_2, \\ldots, a_{pos}]) = mex$ $MEX([a_1, a_2, \\ldots, a_{pos}]) = mex$ There are exactly $big$ distinct elements among $a_1, a_2, \\ldots, a_{pos}$, which are bigger then $mex$. Let's call them large. There are exactly $big$ distinct elements among $a_1, a_2, \\ldots, a_{pos}$, which are bigger then $mex$. Let's call them large. We don't care about the exact values of large elements, we care only about their positions and who of them is equal to who. For example, arrays $[3, 3, 4, 0, 1], [4, 4, 5, 0, 1], [5, 5, 3, 0, 1]$ would all be equivalent. We care about the exact values of all other elements. We don't care about the exact values of large elements, we care only about their positions and who of them is equal to who. For example, arrays $[3, 3, 4, 0, 1], [4, 4, 5, 0, 1], [5, 5, 3, 0, 1]$ would all be equivalent. We care about the exact values of all other elements. We only need to consider at most $2k+1$ possible values of $mex$ for each $pos$. Now, let's learn how to transition from $pos$ to $pos+1$. Let's say that now we are at state $(pos, mex, big)$. Where can we transition after assigning $a_{pos+1}$? There are two cases. $MEX$ doesn't change.It happens when $a_{pos+1} \\neq mex$. Then, if $a_{pos+1}$ is among those $big$ large elements or is less than $mex$, the number of large elements won't change. Otherwise, the number of large elements increases by $1$ (but we don't care about its value other than it being bigger than $mex$). So, we need to add $(mex + big)dp[pos][mex][big]$ to $dp[pos][mex][big]$, and $dp[pos][mex][big]$ to $dp[pos][mex][big+1]$. It happens when $a_{pos+1} \\neq mex$. Then, if $a_{pos+1}$ is among those $big$ large elements or is less than $mex$, the number of large elements won't change. Otherwise, the number of large elements increases by $1$ (but we don't care about its value other than it being bigger than $mex$). So, we need to add $(mex + big)dp[pos][mex][big]$ to $dp[pos][mex][big]$, and $dp[pos][mex][big]$ to $dp[pos][mex][big+1]$. $MEX$ becomes $mex_1 > mex$.It happens only when $a_{pos+1} = mex$, and all numbers from $mex+1$ to $mex_1-1$ appear among those $big$ large elements. There are $\\frac{big!}{(big-(mex_1-mex-1))!}$ ways to choose their positions there, and all of them will stop being large, so there will be only $big - (mex_1 - mex - 1)$ elements remaining. So, we have to add $\\frac{big!}{(big-(mex_1-mex-1))!}\\cdot dp[pos][mex][big]$ to $dp[pos+1][mex_1][big-(mex_1-mex-1)]$ for all valid $pos, mex, big, mex_1$. It happens only when $a_{pos+1} = mex$, and all numbers from $mex+1$ to $mex_1-1$ appear among those $big$ large elements. There are $\\frac{big!}{(big-(mex_1-mex-1))!}$ ways to choose their positions there, and all of them will stop being large, so there will be only $big - (mex_1 - mex - 1)$ elements remaining. So, we have to add $\\frac{big!}{(big-(mex_1-mex-1))!}\\cdot dp[pos][mex][big]$ to $dp[pos+1][mex_1][big-(mex_1-mex-1)]$ for all valid $pos, mex, big, mex_1$. This already gives $O(n^2k^2)$ solution, as we have $n$ iterations and $O(nk^2)$ transitions on each of them. However, this TLEs. So, let's try to optimize our transitions. We will process cases when $MEX$ doesn't change as before, as it's only $O(nk)$ transitions. So consider only transitions where $MEX$ changes. Note that $mex + big$ increases exactly by one in such transitions. Also note that we have to multiply by $big!$ when number of large elements previously was $big$ and divide by $(big - (mex_1 - mex - 1))!$ when the number of large elements now becomes $big - (mex_1 - mex - 1)$. Then let's only consider states with $mex + big =$ some fixed $T$ for now, then we have transitions of sort $(mex, T-mex) \\to (mex_1, T+1-mex_1)$ with coefficients $\\frac{(T-mex)!}{(T+1-mex_1)!}$. So, to find what we have to add to $dp[pos+1][mex_1][T+1-mex_1]$, we have to find sum of $dp[pos][mex][T-mex]\\cdot (T-mex)!$ over all valid $mex<mex_1$, and to divide this sum by $(T+1-mex_1)!$. This is easy to do with prefix sums. So, the final complexity is $O(n^2k)$.",
    "tags": [
      "combinatorics",
      "dp",
      "implementation"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1608",
    "index": "G",
    "title": "Alphabetic Tree",
    "statement": "You are given $m$ strings and a tree on $n$ nodes. Each edge has some letter written on it.\n\nYou have to answer $q$ queries. Each query is described by $4$ integers $u$, $v$, $l$ and $r$. The answer to the query is the total number of occurrences of $str(u,v)$ in strings with indices from $l$ to $r$. $str(u,v)$ is defined as the string that is made by concatenating letters written on the edges on the shortest path from $u$ to $v$ (in order that they are traversed).",
    "tutorial": "Let's concatenate the $m$ input strings, separated by some character not in the input, into a string $S$, and build the suffix array over it. If we could lexicographically compare $str(u, v)$ to some suffix of $S$, we could use binary search to find the left and right boundary of suffixes that start with $str(u, v)$ in the suffix array. Knowing how to find the longest common prefix of a path in the tree and a suffix of $S$ would help us in comparing them, since we would know the first position where these string differ. Letters on the tree are still unrelated to the letters in concatenated string, so let's append them to $S$ in some helpful way. Let's split the tree into chains using heavy-light decomposition and append the chains and reversed chains to the string $S$. This way every path in the tree can be split into $O(logn)$ parts which are substrings of $S$. Let's build LCP array of $S$ from it's suffix array, and then sparse table over the LCP array, to be able to answer queries for longest common prefix of two suffixes of $S$ in $O(1)$. With such queries we can get longest common prefix of a path and a suffix of $S$ in $O(logn)$ by querying LCP for $O(logn)$ parts of the path and corresponding suffixes of $S$. Now we know how to find the range of suffixes which have $str(u, v)$ as a prefix. Out of these suffixes we have to count only these for which first position belongs to a string with index in the set $\\{l, l+1, \\dots, r \\}$. We can do the counting offline, sweeping through strings from the first to the last and maintaining binary indexed tree over suffix array. In iteration $i$ we store $1$ for suffixes of strings with indices $1, 2, \\dots, i$, and $0$ for the rest. A query can be solved by taking the difference of sums on suffix array range in iteration $r$ and in iteration $l-1$. Building suffix array can be done in $O(nlog^2n)$, $O(nlogn)$ or $O(n)$ depending on the chosen algorithm, LCP array can be constructed from the suffix array in $O(n)$ using Kasai's algorithm, while the sparse table construction works in $O(nlogn)$ and uses $O(nlogn)$ memory. Searching for the ranges can be done in $O(qlog^2n)$ as described above, and the last offline sweeping part takes $O((n+q)logn)$ time. The overall time complexity is $O((n+q)log^2n)$, with $O(nlogn)$ memory.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "hashing",
      "string suffix structures",
      "strings",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1609",
    "index": "A",
    "title": "Divide and Multiply",
    "statement": "William has array of $n$ numbers $a_1, a_2, \\dots, a_n$. He can perform the following sequence of operations \\textbf{any number of times}:\n\n- Pick any two items from array $a_i$ and $a_j$, where $a_i$ must be a multiple of $2$\n- $a_i = \\frac{a_i}{2}$\n- $a_j = a_j \\cdot 2$\n\nHelp William find the maximal sum of array elements, which he can get by performing the sequence of operations described above.",
    "tutorial": "First we divide all numbers by $2$, while they're divisible and calculate $k$, the number of successful divisions. Next we notice that to maximize the sum we need to multiply $2^k$ by the largest number remaining in the array after the described operations.",
    "code": "def solve():\n\tn = int(input())\n\ta = list(map(int, input().split(' ')))\n \n\ttemp = 1\n\tfor i in range(n):\n\t\twhile (a[i] % 2 == 0):\n\t\t\ta[i] //= 2\n\t\t\ttemp *= 2\n \n\ta.sort()\n\ta[-1] *= temp\n \n\tprint(sum(a))\n \n \nt = int(input())\n \nfor i in range(t):\n\tsolve()",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1609",
    "index": "B",
    "title": "William the Vigilant",
    "statement": "Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is the correct formal description of the homework assignment:\n\nYou are given a string $s$ of length $n$ only consisting of characters \"a\", \"b\" and \"c\". There are $q$ queries of format ($pos, c$), meaning replacing the element of string $s$ at position $pos$ with character $c$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string \"abc\" as a \\textbf{substring}. A valid replacement of a character is replacing it with \"a\", \"b\" or \"c\".\n\nA string $x$ is a substring of a string $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.",
    "tutorial": "Notice that the answer to this problem is the number of substrings \"abc\" Before starting to process queries let's count the number of substrings \"abc\" in the initial string. Next, notice that changing a character on position $pos$ can only remove one substring \"abc\" and add only one substring \"abc\". To check if either of those changes occurred we only need to look at characters no more than two positions away from $pos$ and see if substring \"abc\" appeared (or disappeared) there.",
    "code": "def solve():\n\tn, m = map(int, input().split(' '))\n\ta = list(input())\n \n\tnum = 0\n\tfor i in range(n - 2):\n\t\tif (''.join(a[i:i + 3]) == 'abc'):\n\t\t\tnum += 1\n \n\tfor i in range(m):\n\t\tindex, ch = input().split(' ')\n\t\tindex = int(index) - 1\n \n\t\tfor j in range(max(0, index - 2), index + 1):\n\t\t\tif (''.join(a[j:j + 3]) == 'abc'):\n\t\t\t\tnum -= 1\n \n\t\ta[index] = ch\n \n\t\tfor j in range(max(0, index - 2), index + 1):\n\t\t\tif (''.join(a[j:j + 3]) == 'abc'):\n\t\t\t\tnum += 1\n \n\t\tprint(num)\n \nsolve()",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1609",
    "index": "C",
    "title": "Complex Market Analysis",
    "statement": "While performing complex market analysis William encountered the following problem:\n\nFor a given array $a$ of size $n$ and a natural number $e$, calculate the number of pairs of natural numbers $(i, k)$ which satisfy the following conditions:\n\n- $1 \\le i, k$\n- $i + e \\cdot k \\le n$.\n- Product $a_i \\cdot a_{i + e} \\cdot a_{i + 2 \\cdot e} \\cdot \\ldots \\cdot a_{i + k \\cdot e} $ is a prime number.\n\nA prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.",
    "tutorial": "Note that the product of $n$ natural numbers is a prime number if, and only if, $n - 1$ of these numbers equal to one and one number is prime. Next, let's group all of our numbers into groups which are ones. It's important that these groups are separated by a prime numbers. If the current number is neither a one nor a prime, it means we stop building a group for the current index. Let's say we now have $p$ of these groups, then for each $i < p$ we must add product $p_i \\cdot p_{i + 1}$, where $p_i$ is the number of ones in group $i$. Also a group of ones doesn't necessarily have to be connected to the subsequent group of ones, so to get the answer we must take into the account their product with the next prime (if there is one) and the previous prime (if there is one) for this group.",
    "code": "// #pragma GCC target(\"sse,sse2,sse3,ssse3,sse4\")\n// #pragma GCC optimize(\"Ofast\")\n// #pragma GCC optimize(\"unroll-loops\")\n \n#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <ctime>\n#include <cmath>\n#include <map>\n#include <assert.h>\n#include <fstream>\n#include <cstdlib>\n#include <random>\n#include <iomanip>\n#include <queue>\n#include <bitset>\n \nusing namespace std;\n \n#define sqr(a) ((a)*(a))\n#define all(a) (a).begin(), (a).end()\n#define fast_io ios_base::sync_with_stdio(false); cin.tie(nullptr)\n#define endl '\\n'\n \nconst int MOD = int(1e9) + 7;\nconst int MAXN = 1123456;\n \nbool used[MAXN], prime[MAXN];\n \nlong long mainSolve(int n, int k, const vector<int>& isOne, const vector<int>& isPrime) {\n    vector <int> ones;\n    vector <bool> chained(n + 1, false);\n \n    long long res = 0;\n    for (int i = 1; i <= n; ++i) if (!chained[i]){\n        ones.clear();\n        int currentOnes = 0;\n        for (int j = i; j <= n; j += k){\n            if ((!isOne[j] && !isPrime[j]) || chained[j]) {\n                break;\n            }\n            chained[j] = true;\n            if (isOne[j]) {\n                currentOnes++;\n            } else {\n                ones.push_back(currentOnes);\n                currentOnes = 0;\n            }\n        }\n \n        if (ones.size() == 0) continue;\n        ones.push_back(currentOnes);\n        for (int j = 0; j < ones.size(); ++j) {\n            res += ones[j];\n            if (j > 0 && j < ones.size() - 1) {\n                res += ones[j];\n            }\n \n            if (j < ones.size() - 1) {\n                res += (long long)(ones[j]) * (long long)(ones[j + 1]);\n            }\n        }\n    }\n \n    return res;\n}\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    vector <int> isOne(n + 1, 0), isPrime(n + 1, 0);\n \n    for (int i = 1; i <= n; ++i) {\n        int a;\n        cin >> a;\n        if (a == 1) {\n            isOne[i] = 1;\n        } else if (prime[a]) {\n            isPrime[i] = 1;\n        }\n    }\n \n    cout << mainSolve(n, k, isOne, isPrime) << endl;\n \n}\n \n \nvoid precalc() {\n    for (int i = 2; i < MAXN; ++i) if (!used[i]){\n        prime[i] = true;\n        for (int j = i; j < MAXN; j += i) {\n            used[j] = true;\n        }\n    }\n}\n \nint main() {\n    // freopen(\"input.txt\", \"r\", stdin);\n    srand(time(0));\n    fast_io;\n    precalc();\n \n    int tests = 1;\n    cin >> tests;\n    while (tests--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "dp",
      "implementation",
      "number theory",
      "schedules",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1609",
    "index": "D",
    "title": "Social Network",
    "statement": "William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.\n\nThe conference has $n$ participants, who are initially unfamiliar with each other. William can introduce any two people, $a$ and $b$, who were not familiar before, to each other.\n\nWilliam has $d$ conditions, $i$'th of which requires person $x_i$ to have a connection to person $y_i$. Formally, two people $x$ and $y$ have a connection if there is such a chain $p_1=x, p_2, p_3, \\dots, p_k=y$ for which for all $i$ from $1$ to $k - 1$ it's true that two people with numbers $p_i$ and $p_{i + 1}$ know each other.\n\nFor every $i$ ($1 \\le i \\le d$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $1$ and up to and including $i$ and performed \\textbf{exactly} $i$ introductions. The conditions are being checked after William performed $i$ introductions. The answer for each $i$ must be calculated independently. It means that when you compute an answer for $i$, you should assume that no two people have been introduced to each other yet.",
    "tutorial": "Note that the conditions form a collection of disjoint sets. Consider two situations: The next condition connects two previously unconnected sets: then we will simply unite. The next condition connects two previously connected sets: this case allows us to \"postpone\" an edge to use it as we like. The second observation is that inside a set, the most advantageous construction for us has the shape of a star (a star is a graph, wherefrom one vertex there is an edge to all the others in this set). It remains not to forget about the deferred ribs. We can use them to connect some sets. The most profitable solution would be to connect sets with maximum sizes. The constraints of the problem make it possible to do this by a simple traversal over the sets in the order of sorting by the number of vertices in them. Note that it was possible to solve the problem for more complex constraints using a tree of segments or two set<>, but this was not required in this problem.",
    "code": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <ctime>\n#include <cmath>\n#include <map>\n#include <assert.h>\n#include <fstream>\n#include <cstdlib>\n#include <random>\n#include <iomanip>\n#include <queue>\n#include <bitset>\n \nusing namespace std;\n \n#define sqr(a) ((a)*(a))\n#define all(a) (a).begin(), (a).end()\n \nstruct DSU {\n\tvector<int> to;\n\tvector<int> val;\n\tint safeEdges = 0;\n\tmultiset<int> topVals;\n\tmultiset<int> tempVals;\t\n \n\tDSU(int n) {\n\t\tto.resize(n);\n\t\tval.resize(n, 1);\n \n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tto[i] = i;\n\t\t\ttempVals.insert(val[i]);\n\t\t}\n\t}\n \n\tint f(int v) {\n\t\tif (v == to[v])\n\t\t\treturn v;\n \n\t\treturn to[v] = f(to[v]);\n\t}\n \n\tbool check(multiset<int>& st, int val) {\n\t\tauto it = st.lower_bound(val);\n\t\tif (it == st.end())\n\t\t\treturn false;\n\t\treturn (*it == val);\n\t}\n \n\tvoid merge(int x, int y) {\n\t\tx = f(x);\n\t\ty = f(y);\n \n\t\tif (x == y) {\n\t\t\t++safeEdges;\n\t\t\treturn;\n\t\t}\n \n\t\tif (check(tempVals, val[x]))\n\t\t\ttempVals.erase(tempVals.lower_bound(val[x]));\n\t\telse {\n\t\t\tsum -= val[x];\n\t\t\ttopVals.erase(topVals.lower_bound(val[x]));\n\t\t}\n\t\tif (check(tempVals, val[y]))\n\t\t\ttempVals.erase(tempVals.lower_bound(val[y]));\n\t\telse {\n\t\t\tsum -= val[y];\n\t\t\ttopVals.erase(topVals.lower_bound(val[y]));\n\t\t}\n \n\t\tto[y] = x;\n\t\tval[x] = val[x] + val[y];\n \n\t\ttempVals.insert(val[x]);\n\t}\n \n\tlong long sum = 0;\n \n\tint getAnswer() {\n\t\twhile (tempVals.size() && topVals.size() < safeEdges + 1) {\n\t\t\tsum += (*--tempVals.end());\n\t\t\ttopVals.insert(*--tempVals.end());\n\t\t\ttempVals.erase(--tempVals.end());\n\t\t}\n \n\t\twhile (tempVals.size() && (*topVals.begin()) < (*--tempVals.end())) {\n\t\t\tsum -= *topVals.begin();\n \n\t\t\tint temp = *topVals.begin();\n\t\t\ttopVals.erase(topVals.begin());\n\t\t\ttempVals.insert(temp);\n \n\t\t\tsum += *--tempVals.end();\n\t\t\ttopVals.insert(*--tempVals.end());\n \n\t\t\ttempVals.erase(*--tempVals.end());\n\t\t}\n \n\t\treturn sum - 1;\n\t}\n} ;\n \nvoid solve() {\n\tint n, m;\n\tcin >> n >> m;\n \n\tDSU dsu(n);\n \n\tfor (int i = 0; i < m; ++i) {\n\t\tint x, y;\n\t\tcin >> x >> y;\n\t\t--x; --y;\n \n\t\tdsu.merge(x, y);\n \n\t\tcout << dsu.getAnswer() << \"\\n\";\n\t}\n}\n \nint main() {\n    int numTests = 1;\n \n    while (numTests--) {\n        solve();\n    }\n}",
    "tags": [
      "dsu",
      "graphs",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1609",
    "index": "E",
    "title": "William The Oblivious ",
    "statement": "Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:\n\nYou are given a string $s$ of length $n$ only consisting of characters \"a\", \"b\" and \"c\". There are $q$ queries of format ($pos, c$), meaning replacing the element of string $s$ at position $pos$ with character $c$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string \"abc\" as a \\textbf{subsequence}. A valid replacement of a character is replacing it with \"a\", \"b\" or \"c\".\n\nA string $x$ is said to be a subsequence of string $y$ if $x$ can be obtained from $y$ by deleting some characters without changing the ordering of the remaining characters.",
    "tutorial": "To solve this problem we will use a segment tree. Let's maintain the following informaton for each segment: $dp_{node, mask}$ stores the minimal number of characters that have to be replaced to make the string only contain subsequences equal to $mask$. Next let's define what $mask$ is. Let the first bit of the mask correspond to subsequence $a$, the second bit correspond to subsequence $b$, the third bit correspond to subsequence $c$, the fourth bit correspond to subsequence $ab$, the fifth bit correspond to subsequence $bc$. Then $mask$ contains those subsequences, which have a number corresponding to the number of 1 bits in them. Let's define the value $merge(leftMask, rightMask)$ as a resulting mask which contains the subsequences from both masks and the subsequences that are created as a result of their merge. Then for a new node $node$ and for all masks $mask$ we can define $dp_{node, mask}$ as the minimal among all values $dp_{leftChild, leftMask} + dp_{rightChild, rightMask}$, where $leftChild$ and $rightChild$ are the left and right child nodes of the $node$ in the segment tree and $leftMask$ and $rightMask$ are masks for which $merge(leftMask, rightMask) = mask$. The final answer is the minimal among all $dp_{1, mask}$.",
    "code": "// #pragma GCC target(\"sse,sse2,sse3,ssse3,sse4\")\n// #pragma GCC optimize(\"Ofast\")\n// #pragma GCC optimize(\"unroll-loops\")\n \n#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <ctime>\n#include <cmath>\n#include <map>\n#include <assert.h>\n#include <fstream>\n#include <cstdlib>\n#include <random>\n#include <iomanip>\n#include <queue>\n#include <bitset>\n#include <unordered_map>\n#include <chrono>\n \n#define fi first\n#define se second\n#define m_p make_pair\n#define fast_io ios_base::sync_with_stdio(0); cin.tie(0)\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int inf = int(1e9);\n \nint masksMerge[40][40];\nvector <string> bits = {\"a\", \"b\", \"c\", \"ab\", \"bc\"};\n \nbool contains(const string& s, const string& sub) {\n    int pos = 0;\n    for (int i = 0; i < s.size(); ++i) {\n        if (pos < sub.size() && s[i] == sub[pos]) pos++;\n    }\n    return pos >= sub.size();\n}\n \nint totalMask(const vector<string>& firstMask, const vector<string>& secondMask) {\n    int msk = 0;\n    for (const auto& f : firstMask) {\n        for (const auto& s : secondMask) {\n            string merged = f + s;\n            if (contains(merged, \"abc\")) {\n                return -1;\n            }\n \n            for (int bit = 0; bit < 5; ++bit) {\n                if (contains(merged, bits[bit])) {\n                    msk |= (1 << bit);\n                }\n            }\n        }\n    }\n    return msk;\n}\n \nvoid precalc() {\n    for (int msk1 = 0; msk1 < 32; ++msk1) {\n        for (int msk2 = 0; msk2 < 32; ++msk2) {\n            vector<string> firstMask, secondMask;\n            for (int i = 0; i < 5; ++i) {\n                if (msk1 & (1 << i)) firstMask.push_back(bits[i]);\n                if (msk2 & (1 << i)) secondMask.push_back(bits[i]);\n            }\n            firstMask.push_back(\"\");\n            secondMask.push_back(\"\");\n            int msk = totalMask(firstMask, secondMask);\n            masksMerge[msk1][msk2] = msk;\n \n        }\n    }\n}\n \nstruct Node {\n    vector <int> dp;\n \n    Node() {\n        dp.resize(40, inf);\n    }\n};\n \nstruct Tree {\nprivate:\n    int n;\n    vector<Node> nodes;\n \n    void merge(int v) {\n        for (int i = 0; i < 32; ++i) nodes[v].dp[i] = inf;\n \n        for (int msk1 = 0; msk1 < 32; ++msk1) {\n            if (nodes[v * 2].dp[msk1] == inf) continue;\n            for (int msk2 = 0; msk2 < 32; ++msk2) {\n                int newMask = masksMerge[msk1][msk2];\n                if (newMask != -1) {\n                    nodes[v].dp[newMask] = min(nodes[v].dp[newMask], nodes[v * 2].dp[msk1] + nodes[v * 2 + 1].dp[msk2]);\n                }\n            }\n        }\n    }\n \n    void build(int v, int tl, int tr, const string& s) {\n        if (tl == tr) {\n            int mskPos = int(s[tl - 1] - 'a');\n            nodes[v].dp[(1 << mskPos)] = 0;\n            nodes[v].dp[0] = 1;\n            return;\n        }\n        int tm = (tl + tr) / 2;\n        build(v * 2, tl, tm, s);\n        build(v * 2 + 1, tm + 1, tr, s);\n        merge(v);\n    }\n \n    void modify(int v, int tl, int tr, int pos, char val) {\n        if (tl == tr) {\n            for (int i = 0; i < 33; ++i) nodes[v].dp[i] = inf;\n            int mskPos = int(val - 'a');\n            nodes[v].dp[(1 << mskPos)] = 0;\n            nodes[v].dp[0] = 1;\n            return;\n        }\n \n        int tm = (tl + tr) / 2;\n        if (pos <= tm) modify(v * 2, tl, tm, pos, val);\n        else modify(v * 2 + 1, tm + 1, tr, pos, val);\n        merge(v);\n    }\n \npublic:\n    Tree(const string& s) {\n        n = int(s.size());\n        nodes.resize(4 * n);\n        build(1, 1, n, s);\n    }\n \n    void update(int pos, char x) {\n        modify(1, 1, n, pos, x);\n    }\n \n    int get() {\n        int ans = inf;\n        for (int i = 0; i < 32; ++i) {\n            ans = min(ans, nodes[1].dp[i]);\n        }\n        return ans;\n    }\n \n};\n \nvoid solve() {\n    int n, q;\n    cin >> n >> q;\n    string s;\n    cin >> s;\n    Tree tree(s);\n \n    while (q--) {\n        int pos;\n        char x;\n        cin >> pos >> x;\n        tree.update(pos, x);\n        cout << tree.get() << '\\n';\n    }\n}\n \nint main()\n{\n    fast_io;\n    precalc();\n    int t = 1;\n    while(t--) {\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "dp",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1609",
    "index": "F",
    "title": "Interesting Sections",
    "statement": "William has an array of non-negative numbers $a_1, a_2, \\dots, a_n$. He wants you to find out how many segments $l \\le r$ pass the check. The check is performed in the following manner:\n\n- The minimum and maximum numbers are found on the segment of the array starting at $l$ and ending at $r$.\n- The check is considered to be passed if the binary representation of the minimum and maximum numbers have the same number of bits equal to 1.",
    "tutorial": "We will use Divide & Conquer algorithm. Let $f(l, r)$ be the answer to the problem on the subsegment $l\\ldots r$. Let's notice, that if $l = r$, then $f(l, r) = 1$, otherwise $f(l, r) = f(l, m) + f(m + 1, r) + f'(l, r)$, where $m = \\frac{r + l}{2}$ and $f'(l, r)$ equals to the number of subsegments passing the check, which have left bound ranged from $l$ to $m$ (inclusively) and right bound ranged from $m+1$ to $r$ (inclusively). Let's see how to calculate $f'(l, r)$. Let $max(l, r)$ be equal to maximum on the subsegment $l \\ldots r$ and $min(l, r)$ be equal to minimum on the subsegment $l \\ldots r$. Let's suppose that the maximal value of the chosen segment is in the left half (the case when the maximal value is in the right half is similar to this one). Now, let's iterate over the left bound $L$ of the segment, maintaining a maximal value of numbers in the left half (in other words, a maximal value on the segment $L\\ldots m$). If we iterate over possible $L$-s in descending order, it is possible to maintain a pointer at all possible right bounds in the right half (notice that we want to maintain the greatest $R\\_{max}$ such that $max(m + 1, R\\_{max}) \\le max(L, m)$). Now that we know the maximum, we know the number of bits equal to $1$ that binary representations of maximum and minimum contain. It's only left to find the number of right bounds $R'$ such that: $m + 1 \\le R' \\le R\\_{max}$ $min(L, R')$ has the same number of bits equal to $1$ as $max(L, m)$. For every prefix of the right half let's calculate the minimum on it, in other words, $min(m + 1, pref)$, for every $pref$ such that $m + 1 \\le pref \\le r$. Notice that we can maintain an array $cnt_x$, which for every $x$ stores the number of right bounds, for which the binary representation of prefix minimum has exactly $x$ bits equal to $1$. The only case left unconsidered is when the minimum is in the left half. Let's notice that if we iterate over $L$-s in descending order, we don't increase the minimum in the left half, which means that we can create a pointer for it in the right half, maintaining such minimal $R\\_{min}$, that $min(m + 1, R\\_{min}) \\le min(L, m)$. It turns out that $R\\_{min} - (m + 1)$ segments have maximum and minimum in the left half, and we know how to find those segments, and we just need to check if the binary representations of maximum and minimum of such segments have equal numbers of bits equal to $1$. In all other cases we want to calculate the number of right bounds on the segment $R\\_{min}\\ldots R\\_{max}$, for which the prefix minimum has the same number of bits equal to $1$ as $max(L, m)$. It can be done if we maintain the array $cnt_x$ for the subsegment $R\\_{min} \\ldots R\\_{max}$. If we initially calculate the number of bits equal to $1$ for every number, then we will get a solution in $O(n \\cdot \\log n + n \\cdot \\log max\\_a)$. 1609G - A Stroll Around the Matrix",
    "tags": [
      "data structures",
      "divide and conquer",
      "meet-in-the-middle",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1609",
    "index": "G",
    "title": "A Stroll Around the Matrix",
    "statement": "William has two arrays of numbers $a_1, a_2, \\dots, a_n$ and $b_1, b_2, \\dots, b_m$. The arrays satisfy the conditions of being convex. Formally an array $c$ of length $k$ is considered convex if $c_i - c_{i - 1} < c_{i + 1} - c_i$ for all $i$ from $2$ to $k - 1$ and $c_1 < c_2$.\n\nThroughout William's life he observed $q$ changes of two types happening to the arrays:\n\n- Add the arithmetic progression $d, d \\cdot 2, d \\cdot 3, \\dots, d \\cdot k$ to the suffix of the array $a$ of length $k$. The array after the change looks like this: $[a_1, a_2, \\dots, a_{n - k}, a_{n - k + 1} + d, a_{n - k + 2} + d \\cdot 2, \\dots, a_n + d \\cdot k]$.\n- The same operation, but for array $b$.\n\nAfter each change a matrix $d$ is created from arrays $a$ and $b$, of size $n \\times m$, where $d_{i, j}=a_i + b_j$. William wants to get from cell ($1, 1$) to cell ($n, m$) of this matrix. From cell ($x, y$) he can only move to cells ($x + 1, y$) and ($x, y + 1$). The length of a path is calculated as the sum of numbers in cells visited by William, including the first and the last cells.\n\nAfter each change William wants you to help find out the minimal length of the path he could take.",
    "tutorial": "Let's try to solve the problem without asking for changes. Note that in the matrix constructed in this way for the move from (i, j) it is always profitable to go to the cell with the smallest number. This can be seen more clearly in the matrix of the first test case: This allows you to solve the problem with complexity $O(n + m)$, but this is not enough for a complete solution. Let's introduce two new arrays of the difference between the adjacent elements of the arrays $da_i = a_{i + 1} - a_i$ and $db_i = b_{i + 1} - b_i$. Note that our greedy decision turns right out of the cell $(i, j)$, when $da_i > db_j$. For clarity, below is an illustration of the turns: Each time such a turn to the right in the cell $(i, j)$ decreases our total sum by $(da_i - db_j) + (da_{i + 1} - db_j) + \\dots + (da_{n - 1} - db_j) = (\\sum_{t=i}^{n - 1} da_t) - db_j \\cdot (n - i)$. Which is actually equivalent to the sum of $da_i - db_j$ for all $da_i > db_j$. Such a sum can be considered by recognizing for each $i$ by a binary search the last $db_j$ for which the expression $da_i> db_j$ is true. This allows us to solve the problem in $O(n \\cdot log(m))$ using the prefix sums of the $db$ array. Now let's get back to change requests. Because the size of the $da$ array is small enough, then we can change the values of its elements by a simple. To store the $db$ array, you will need to use a segment tree supporting the following operations: - Adding a number at the suffix (since we are working with an array $db$, not $b$, then all elements will change by one number equal to the step of the arithmetic progression). - Sum of array numbers on array prefix so far $element_i < X$. ($da_i$ will act as $X$).",
    "tags": [
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1609",
    "index": "H",
    "title": "Pushing Robots",
    "statement": "There're $n$ robots placed on a number line. Initially, $i$-th of them occupies unit segment $[x_i, x_i + 1]$. Each robot has a program, consisting of $k$ instructions numbered from $1$ to $k$. The robot performs instructions in a cycle. Each instruction is described by an integer number. Let's denote the number corresponding to the $j$-th instruction of the $i$-th robot as $f_{i, j}$.\n\nInitial placement of robots corresponds to the moment of time $0$. During one second from moment of time $t$ ($0 \\le t$) until $t + 1$ the following process occurs:\n\n- Each robot performs $(t \\bmod k + 1)$-th instruction from its list of instructions. Robot number $i$ takes number $F = f_{i, (t \\bmod k + 1)}$. If this number is negative (less than zero), the robot is trying to move to the left with force $|F|$. If the number is positive (more than zero), the robot is trying to move to the right with force $F$. Otherwise, the robot does nothing.\n- Let's imaginary divide robots into groups of consecutive, using the following algorithm:\n\n- Initially, each robot belongs to its own group.\n- Let's sum up numbers corresponding to the instructions of the robots from one group. Note that we are summing numbers without taking them by absolute value. Denote this sum as $S$. We say that the whole group moves together, and does it with force $S$ by the same rules as a single robot. That is if $S$ is negative, the group is trying to move to the left with force $|S|$. If $S$ is positive, the group is trying to move to the right with force $S$. Otherwise, the group does nothing.\n- If one group is trying to move, and in the direction of movement touches another group, let's unite them. One group is touching another if their outermost robots occupy adjacent unit segments.\n- Continue this process until groups stop uniting.\n\n- Each robot moves by $1$ in the direction of movement of its group or stays in place if its group isn't moving. But there's one exception.\n- The exception is if there're two groups of robots, divided by exactly one unit segment, such that the left group is trying to move to the right and the right group is trying to move to the left. Let's denote sum in the left group as $S_l$ and sum in the right group as $S_r$. If $|S_l| \\le |S_r|$ only the right group will move. Otherwise, only the left group will move.\n- Note that robots from one group don't glue together. They may separate in the future. The division into groups is imaginary and is needed only to understand how robots will move during one second $[t, t + 1]$.\n\nAn illustration of the process happening during one second:\n\nRectangles represent robots. Numbers inside rectangles correspond to instructions of robots. The final division into groups is marked with arcs. Below are the positions of the robots after moving. Only the left of the two rightmost groups moved. That's because these two groups tried to move towards each other, and were separated by exactly one unit segment.\n\nLook at the examples for a better understanding of the process.\n\nYou need to answer several questions. What is the position of $a_i$-th robot at the moment of time $t_i$?",
    "tutorial": "First of all, it should be noted, that one iteration of the described algorithm of robots' movements can be implemented in $O(n)$ time. For example, using stack. Let's consider moments of time that are multiple of $k$. And segments of time between such two consecutive moments of time. Consider two adjacent robots. It can be proved that if these two robots touched each other during a segment of time $[k \\cdot t, k \\cdot (t + 1)]$ ($1 < t$), then they will touch each other during any succeeding segment of time $[k \\cdot t', k \\cdot (t' + 1)]$ ($t < t'$). One thing that may change in the future is that the left robot will be blocked from moving to the left, or the right robot will be blocked from moving to the right. Robots just will become closer to each other after such a change. It's also possible that the left robot will be blocked from moving to the right, or the right robot from moving to the left. But then they are touching. Similarly, if after $k$ seconds distance between two robots decreases, then it will continue decreasing until they touch during some segment of time. And if two robots touch during a segment of time, then the distance between them after this segment of time will be less than or equal to the distance between them before this segment. Let's simulate the first $k$ seconds, and then another $k$ seconds. Let's look at pairs of adjacent robots. If the distance between two robots increased or didn't change, skip this pair. If the distance between two robots decreased. If the distance is $\\le k \\cdot 2 + 1$, then robots may touch during the next segment. So, let's simulate the next $k$ seconds again. Otherwise, let distance be $d$ and it decreased by $s$ during the last segment of time. Then, during the next $\\lfloor\\frac{d - k \\cdot 2 - 1}{s}\\rfloor$ segments of time it will continue decreasing with the same speed ($s$ units per $k$ seconds). So we can skip these segments of time, and simulate the next after them. If the distance is $\\le k \\cdot 2 + 1$, then robots may touch during the next segment. So, let's simulate the next $k$ seconds again. Otherwise, let distance be $d$ and it decreased by $s$ during the last segment of time. Then, during the next $\\lfloor\\frac{d - k \\cdot 2 - 1}{s}\\rfloor$ segments of time it will continue decreasing with the same speed ($s$ units per $k$ seconds). So we can skip these segments of time, and simulate the next after them. Let's choose the minimum segment of time that should be simulated. Let's skip all till this segment of time, and simulate it. Then again choose the minimum segment of time till which we can skip simulation. It can be proved that there will be simulated $O(n \\cdot k)$ segments of time overall. This is due to the fact that there're no more than $O(k)$ decreases of the distance between two adjacent robots, after which we will do the simulation. In order to answer questions, let's also simulate segments of time that contain moments of time of questions. Total time complexity is $O(n \\cdot k \\cdot (n \\cdot k + q))$.",
    "tags": [],
    "rating": 3500
  },
  {
    "contest_id": "1610",
    "index": "A",
    "title": "Anti Light's Cell Guessing",
    "statement": "You are playing a game on a $n \\times m$ grid, in which the computer has selected some cell $(x, y)$ of the grid, and you have to determine which one.\n\nTo do so, you will choose some $k$ and some $k$ cells $(x_1, y_1),\\, (x_2, y_2), \\ldots, (x_k, y_k)$, and give them to the computer. In response, you will get $k$ numbers $b_1,\\, b_2, \\ldots b_k$, where $b_i$ is the manhattan distance from $(x_i, y_i)$ to the hidden cell $(x, y)$ (so you know which distance corresponds to which of $k$ input cells).\n\nAfter receiving these $b_1,\\, b_2, \\ldots, b_k$, you have to be able to determine the hidden cell. What is the smallest $k$ for which is it possible to always guess the hidden cell correctly, no matter what cell computer chooses?\n\nAs a reminder, the manhattan distance between cells $(a_1, b_1)$ and $(a_2, b_2)$ is equal to $|a_1-a_2|+|b_1-b_2|$.",
    "tutorial": "$\\mathcal Complete\\;\\mathcal Solution$: $\\textbf{I encourage you to read the Hints and Assumptions before reading this.}$ Let's say the answer is $ans$. If $n == 1$ and $m == 1$, then there's only one cell, so we don't need any more information, and the hidden cell is that single cell. So for this scenario $ans = 0$. If exactly one of $n$ or $m$ equals $1$, then it's trivial that the answer is greater than $0$. Also if we choose the cell $(1, 1)$, we can find the hidden cell. So for this case $ans = 1$. Now assume $2 \\le n$ and $2 \\le m$, if you choose $(1, 1)$ and $(n, 1)$ then let's say the distance from $(1, 1)$ to the hidden cell is $b_1$ and the distance from $(n, 1)$ to the hidden cell is $b_2$. Then if the hidden cell is $(i, j)$ then $b_1 = i-1 + j-1$ and $b_2 = n-i + j-1$ so $b_1+b_2 = n-1 + 2j-2$ so we can find $j$. After finding $j$ we can find $i$ using $b_1 = i-1+j-1$. So the answer is at most $2$. Now we proof $2 \\le ans$, trivially $0 < ans$, but why $ans \\ne 1$?. Assume someone chose a cell $(i, j)$ and they could distinguish all the $n \\cdot m$ possible hidden cells. It's easy to see that at least $3$ of the $4$ cells $(i, j-1)$, $(i+1, j)$, $(i-1, j)$ and $(i, j+1)$ exist in the table, but their distance from $(i, j)$ is $1$ for all $4$ of them, so we can't distinguish them, so $ans = 2$. Time complexity: $\\mathcal{O}(1)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie();\n    cout.tie();\n    \n    int t;\n    cin >> t;\n    while(t--){\n        int n, m;\n        cin >> n >> m;\n        if(n == 1 && m == 1){\n            cout << \"0\\n\";\n        }\n        else if(min(n, m) == 1){\n            cout << \"1\\n\";\n        }\n        else cout << \"2\\n\";\n    }\n}\n",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1610",
    "index": "B",
    "title": "Kalindrome Array",
    "statement": "An array $[b_1, b_2, \\ldots, b_m]$ is a palindrome, if $b_i = b_{m+1-i}$ for each $i$ from $1$ to $m$. Empty array is also a palindrome.\n\nAn array is called \\textbf{kalindrome}, if the following condition holds:\n\n- It's possible to select some integer $x$ and delete some of the elements of the array equal to $x$, so that the remaining array (after gluing together the remaining parts) is a palindrome.\n\nNote that you don't have to delete all elements equal to $x$, and you don't have to delete at least one element equal to $x$.\n\nFor example :\n\n- $[1, 2, 1]$ is kalindrome because you can simply not delete a single element.\n- $[3, 1, 2, 3, 1]$ is kalindrome because you can choose $x = 3$ and delete both elements equal to $3$, obtaining array $[1, 2, 1]$, which is a palindrome.\n- $[1, 2, 3]$ is not kalindrome.\n\nYou are given an array $[a_1, a_2, \\ldots, a_n]$. Determine if $a$ is kalindrome or not.",
    "tutorial": "If the array is already a palindrome the answer is Yes. Otherwise, let's find the minimum $i$ that $a_i \\neq a_{n + 1 - i}$. We can prove that we have to remove either $a_i$ or $a_{n + 1 - i}$ in order the make the array palindrome. Imagine it's possible to make the array palindrome by removing all appearances of $x$. $x \\neq a_i, a_{n + 1 - i}$ The number of appearances of $x$ before $i$ is equal to the number of appearances of $x$ after $n + 1 - i$. So in order to make the array palindrome, $a_i$ must be equal to $a_{n + 1 - i}$. So we just have to check if the array will be palindrome after removing all appearances of $a_i$ or after removing all appearances of $a_{n + 1 - i}$. Time complexity: $\\mathcal{O}(n)$",
    "code": "//khodaya khodet komak kon\n# include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long                                        ll;\ntypedef long double                                      ld;\ntypedef pair <int, int>                                  pii;\ntypedef pair <pii, int>                                  ppi;\ntypedef pair <int, pii>                                  pip;\ntypedef pair <pii, pii>                                  ppp;\ntypedef pair <ll, ll>                                    pll;\n \n# define A                                               first\n# define B                                               second\n# define endl                                            '\\n'\n# define sep                                             ' '\n# define all(x)                                          x.begin(), x.end()\n# define kill(x)                                         return cout << x << endl, 0\n# define SZ(x)                                           int(x.size())\n# define lc                                              id << 1\n# define rc                                              id << 1 | 1\n# define fast_io                                         ios::sync_with_stdio(0);cin.tie(0); cout.tie(0);\n \nll power(ll a, ll b, ll md) {return (!b ? 1 : (b & 1 ? a * power(a * a % md, b / 2, md) % md : power(a * a % md, b / 2, md) % md));}\n \nconst int xn = 2e5 + 10;\nconst int xm = - 20 + 10;\nconst int sq = 320;\nconst int inf = 1e9 + 10;\nconst ll INF = 1e18 + 10;\nconst ld eps = 1e-15;\nconst int mod = 998244353;\nconst int base = 257;\n \nint qq, n, m, a[xn], b[xn];\nbool ans;\n \nvoid check(int x){\n\tm = 0;\n\tfor (int i = 1; i <= n; ++ i)\n\t\tif (a[i] != x)\n\t\t\tb[++ m] = a[i];\n\tfor (int i = 1; i <= m; ++ i)\n\t\tif (b[i] != b[m + 1 - i])\n\t\t\treturn;\n\tans = true;\n}\n \nint main(){\n\tfast_io;\n \n\tcin >> qq;\n\twhile (qq --){\n\t\tcin >> n, ans = true;\n\t\tfor (int i = 1; i <= n; ++ i)\n\t\t\tcin >> a[i];\n\t\tfor (int i = 1; i <= n; ++ i){\n\t\t\tif (a[i] != a[n + 1 - i]){\n\t\t\t\tans = false;\n\t\t\t\tcheck(a[i]);\n\t\t\t\tcheck(a[n + 1 - i]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (ans)\n\t\t\tcout << \"YES\" << endl;\n\t\telse\n\t\t\tcout << \"NO\" << endl;\n\t}\n \n\treturn 0;\n}\n",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1610",
    "index": "C",
    "title": "Keshi Is Throwing a Party",
    "statement": "Keshi is throwing a party and he wants everybody in the party to be happy.\n\nHe has $n$ friends. His $i$-th friend has $i$ dollars.\n\nIf you invite the $i$-th friend to the party, he will be happy only if at most $a_i$ people in the party are strictly richer than him and at most $b_i$ people are strictly poorer than him.\n\nKeshi wants to invite as many people as possible. Find the maximum number of people he can invite to the party so that every invited person would be happy.",
    "tutorial": "Take a look at this greedy approach. Let $p_i$ be the $i$-th poorest invited person.($p_i < p_{i + 1}$) Find the poorest person $v$ that $x - 1 - a_v \\le 0 \\le b_v$. We will invite this person so $p_1 = v$. For each $2 \\le i \\le x$ find the poorest person $v$ that $v > p_{i - 1}$ and $x - 1 - a_v \\le i - 1 \\le b_v$ this means that person $v$ can be the $i$-th poorest invited person. Imagine we fail to find $x$ people but there is a way to do so. The solution chooses $s_1, s_2, \\ldots, s_x$. for each $i$ we chose the minimum $p_i$ possible, therefor $p_i \\le s_i$. But if our algorithm fails there must exist an index $i$ that $p_i > s_i$. So our algorithm is correct. Time complexity: $\\mathcal{O}(n\\log n)$",
    "code": "//In the name of God\n#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef int ll;\ntypedef pair<ll, ll> pll;\n \nconst ll maxn = 2e5 + 100;\nconst ll mod = 1e9 + 7;\nconst ll inf = 1e9;\n \n#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n#define file_io freopen(\"input.txt\", \"r+\", stdin);freopen(\"output.txt\", \"w+\", stdout);\n#define pb push_back\n#define Mp make_pair\n#define F first\n#define S second\n#define Sz(x) ll((x).size())\n#define all(x) (x).begin(), (x).end()\n \nll q, n, a[maxn], b[maxn];\n \nbool ok(ll x){\n\tll c = 0;\n\tfor(ll i = 0; i < n; i++){\n\t\tif(x - 1 - a[i] <= c && c <= b[i]) c++;\n\t}\n\treturn c >= x;\n}\n \nint main(){\n    fast_io;\n    \n    cin >> q;\n    while(q--){\n        cin >> n;\n        for(ll i = 0; i < n; i++){\n        \tcin >> a[i] >> b[i];\n    \t}\n    \tll l = -1, r = n + 1, mid;\n    \twhile(r - l > 1){\n    \t\tmid = (l + r) >> 1;\n    \t\tif(ok(mid)) l = mid;\n    \t\telse r = mid;\n    \t}\n    \tcout << l << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1610",
    "index": "D",
    "title": "Not Quite Lee",
    "statement": "Lee couldn't sleep lately, because he had nightmares. In one of his nightmares (which was about an unbalanced global round), he decided to fight back and propose a problem below (which you should solve) to balance the round, hopefully setting him free from the nightmares.\n\nA non-empty array $b_1, b_2, \\ldots, b_m$ is called \\textbf{good}, if there exist $m$ integer sequences which satisfy the following properties:\n\n- The $i$-th sequence consists of $b_i$ consecutive integers (for example if $b_i = 3$ then the $i$-th sequence can be $(-1, 0, 1)$ or $(-5, -4, -3)$ but not $(0, -1, 1)$ or $(1, 2, 3, 4)$).\n- Assuming the sum of integers in the $i$-th sequence is $sum_i$, we want $sum_1 + sum_2 + \\ldots + sum_m$ to be equal to $0$.\n\nYou are given an array $a_1, a_2, \\ldots, a_n$. It has $2^n - 1$ nonempty subsequences. Find how many of them are \\textbf{good}.\n\nAs this number can be very large, output it modulo $10^9 + 7$.\n\nAn array $c$ is a subsequence of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "$\\mathcal Complete\\;\\mathcal Solution$: $\\textbf{I encourage you to read the Hints and Assumptions before reading this.}$ Assume we have an array $c$ of length $k$, need to know if it's good or not. We can choose an initial sequence $t_i$ for all $1 \\le i \\le k$, then slide them (in other words, choose an index $i$ and increase or decrease all the elements in the $i$-th sequence, keep doing this as many times as you need) that way we can reach any other possible set of sequences that satisfy the first property, so it doesn't matter what we choose as initial sequences, because from any set of $k$ sequences that satisfy the first property, we can reach any other such set of $k$ sequences. After that, if $\\displaystyle \\sum_{i = 1}^k sum_i = s$, we want to find such $x_i$-s that $\\displaystyle \\sum_{i=1}^kx_ic_i = -su$ so after sliding $i$-th sequence $|x_i|$ times to the right(or left if $x_i$ is negative) for all $i$, we will have a set of sequences that satisfy both the properties. Now to do that, one can prove if $\\displaystyle gcd(c_1, c_2, \\ldots, c_k) = g$, then if $g$ divides $s$, the array is good, otherwise it's not (I won't prove it because it's quite well-known and easy). If we choose the initial sequences such that the $i$-th sequence starts from $0$ and ends with $c_i-1$, then $\\displaystyle s = \\sum_{i=1}^k \\frac{c_i(c_i-1)}2$. Now we want $g$ to divide $s$. If $g$ is odd, then it will always divide $s$ because it divides $\\frac{c_i}2$. From now on we assume $g$ to be even. One can prove that if $2^l$ divides $g$ and $0 < l$ is maximum such integer, then $\\frac g{2^l}$ (which is odd) divides all $\\frac{c_i}2$, so $s$ is divisible by $\\frac g{2^l}$. So we should only check if $2^l$ also divides $s$ or not. If $2^{l+1}$ divides some $c_i$, then $2^l$ divides $\\frac{c_i(c_i-1)}2$ for that $i$ as well. Also if $2^{l+1}$ doesn't divide $c_i$, we knew that $2^l$ divides $c_i$ (because $2^l$ divides $g$ and $g$ divides $c_i$) so $2^{l-1}$ divides $\\frac{c_i}2$ but $2^l$ doesn't, also $c_i-1$ is odd. So $\\frac{c_i(c_i-1)}2$ has a reminder equal to $2^{l-1}$ modulo $2^l$. All the other terms $\\frac{c_i(c_i-1)}2$ were divisible by $2^l$ except these, so if the number of such $c_i$-s is even, then their reminders sum up to $0$ modulo $2^l$ then $c$ is good, and not otherwise. To solve the actual problem, we can fix $l$, maximum power of 2 that divides $g$, now we only care about how many $c_i$-s are divisible by $2^l$ (let's say $x$ such $c_i$-s, also if $x < 2$ then we should skip this $l$ because we need at least $2$ such $c_i$-s to have an array with that $l$), and how many are divisible by $2^{l+1}$ (let's say $y$ such $c_i$-s). Now there are $2^x$ possible subsequences such that $2^l$ divides $g$ (including the empty subsequence), but some of them may have an odd number of $c_i$-s not divisible by $2^{l+1}$, it's easy to see that half of them have an even number of such $c_i$-s, still, for $2^y$ of them, $2^{l+1}$ divides $g$ as well (which is not what we want. Also includes the empty subsequence). So we have $2^{x-1}-2^y$ subsequences with that $l$ (doesn't include the empty subsequence). Then we sum up this for all possible $l$, also don't forget to count $l=0$ separately (i.e. $g$ is odd). Time complexity: $\\mathcal{O}(nlog(10^9))$",
    "code": "//In The Name of God\n//I usually forget about the previous line...\n\n#include <bits/stdc++.h>\n\n#define IOS ios::sync_with_stdio(0), cin.tie(), cout.tie();\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int maxBt = 30;\nconst int mod = 1e9+7;\n\nint cnt[maxBt];\n\nint slv(){\n    int n;\n    cin >> n;\n\n    int a[n];\n    for(int i = 0; i < n; i++){\n        cin >> a[i];\n    }\n\n    int to[n+1]; //powers of 2\n\n    to[0] = 1;\n    for(int i = 1; i <= n; i++){\n        to[i] = to[i-1]*2 % mod;\n    }\n\n    for(int i = 0; i < n; i++){\n        int x = 0;\n        for(int k = 0; k < maxBt; k++){\n            if(a[i] & 1)break;\n            a[i] >>= 1;\n            x++;\n        }\n        cnt[x]++;\n    }\n\n    int ans = to[n] - to[n-cnt[0]] + mod;\n    if(ans >= mod)ans -= mod;\n\n    int y = n-cnt[0];\n\n    for(int l = 1; l < maxBt; l++){\n        int x = y;\n        y -= cnt[l];\n        if(x-y < 2)continue;\n        int delta = to[x-1]-to[y]+mod;\n        if(delta >= mod)delta -= mod;\n        ans += delta;\n        if(ans >= mod)ans -= mod;\n    }\n\n    return ans;\n}\n\n\nsigned main(){\n    IOS\n\n    cout << slv() << '\\n';\n\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1610",
    "index": "E",
    "title": "AmShZ and G.O.A.T.",
    "statement": "Let's call an array of $k$ integers $c_1, c_2, \\ldots, c_k$ \\textbf{terrible}, if the following condition holds:\n\n- Let $AVG$ be the $\\frac{c_1 + c_2 + \\ldots + c_k}{k}$(the average of all the elements of the array, it doesn't have to be integer). Then the number of elements of the array which are bigger than $AVG$ should be \\textbf{strictly} larger than the number of elements of the array which are smaller than $AVG$. Note that elements equal to $AVG$ don't count.\n\nFor example $c = \\{1, 4, 4, 5, 6\\}$ is \\textbf{terrible} because $AVG = 4.0$ and $5$-th and $4$-th elements are greater than $AVG$ and $1$-st element is smaller than $AVG$.\n\nLet's call an array of $m$ integers $b_1, b_2, \\ldots, b_m$ \\textbf{bad}, if at least one of its non-empty subsequences is terrible, and \\textbf{good} otherwise.\n\nYou are given an array of $n$ integers $a_1, a_2, \\ldots, a_n$. Find the minimum number of elements that you have to delete from it to obtain a \\textbf{good} array.\n\nAn array is a subsequence of another array if it can be obtained from it by deletion of several (possibly, zero or all) elements.",
    "tutorial": "We build the longest good subsequence starting with $a_s$ greedily step by step. In each step we add the smallest possible element to the subsequence. If the last element is $a_k$, we have to find the minimum $i$ that $i > k$ and $a_i \\ge 2 \\cdot a_k - a_s$. (using lower_bound) Assume $b_1 \\neq b_2$, then $k < \\log(a_n))$. Because for each $i$, $b_{i + 1} \\ge 2 \\cdot b_i - b_1$ then $b_{i + 1} - b_1 \\ge 2 \\cdot b_i - 2 \\cdot b_1$ then $b_{i + 1} - b_1 \\ge 2 \\cdot (b_i - b_1)$. And for cases that $b_1 = b_2$, $+ cnt_i$. ($cnt_i$ being the number of occurrences of element $i$) So for each $i$ that $a_i \\neq a_{i - 1}$ we do the above greedy approach. We don't need to do it for indices that $a_i = a_{i - 1}$ since adding $a_{i - 1}$ to the longest subsequence starting from $a_i$ doesn't make it bad. Time complexity is $\\log(n) \\cdot \\displaystyle\\sum_{a_i \\neq a_{i - 1}}{cnt_i + \\log(a_n)} \\le \\log(n) \\cdot \\left( n \\cdot \\log(a_n) + \\displaystyle\\sum_{a_i \\neq a_{i - 1}}{cnt_i} \\right) \\le \\log(n) \\cdot (n \\cdot \\log(a_n) + n)$. The overall time complexity will be $\\mathcal{O}(n \\cdot \\log n \\cdot \\log a_n)$",
    "code": "//khodaya khodet komak kon\n# include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int xn = 2e5 + 10;\n\nint qq, n, a[xn], ans, res, ptr;\n \nint main(){\n\tios::sync_with_stdio(0);cin.tie(0); cout.tie(0);\n\n\tcin >> qq;\n\twhile (qq --){\n\t\tcin >> n, ans = 0;\n\t\tfor (int i = 1; i <= n; ++ i)\n\t\t\tcin >> a[i];\n\t\tfor (int i = 1; i <= n; ++ i){\n\t\t\tif (a[i] == a[i - 1])\n\t\t\t\tcontinue;\n\t\t\tres = 0, ptr = i;\n\t\t\twhile (ptr <= n)\n\t\t\t\tptr = lower_bound(a + ptr + 1, a + n + 1, 2 * a[ptr] - a[i]) - a, ++ res;\n\t\t\tans = max(ans, res);\n\t\t}\n\t\tcout << n - ans << \"\\n\";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1610",
    "index": "F",
    "title": "Mashtali: a Space Oddysey",
    "statement": "Lee was planning to get closer to Mashtali's heart to proceed with his evil plan(which we're not aware of, yet), so he decided to beautify Mashtali's graph. But he made several rules for himself. And also he was too busy with his plans that he didn't have time for such minor tasks, so he asked you for help.\n\nMashtali's graph is an \\textbf{undirected} weighted graph with $n$ vertices and $m$ edges with weights equal to either $1$ or $2$. Lee wants to direct the edges of Mashtali's graph so that it will be as beautiful as possible.\n\nLee thinks that the beauty of a directed weighted graph is equal to the number of its Oddysey vertices. A vertex $v$ is an Oddysey vertex if $|d^+(v) - d^-(v)| = 1$, where $d^+(v)$ is the sum of weights of the outgoing from $v$ edges, and $d^-(v)$ is the sum of the weights of the incoming to $v$ edges.\n\nFind the largest possible beauty of a graph that Lee can achieve by directing the edges of Mashtali's graph. In addition, find any way to achieve it.\n\nNote that you have to orient each edge.",
    "tutorial": "If there is a vertex $v$ connected to its neighbors $x$ and $y$ with same edge weights, we delete these edges and add a new edge between $x$ and $y$. So the number of edges decreases by 1. Now we solve the problem for our new graph recurrently. Then we check whether the assigned direction is from $x$ to $y$ or from $y$ to $x$. In the first case, we should delete this edge and add a directional edge from $x$ to $v$ and from $v$ to $y$. Otherwise, after deleting the edge we add a directional edge from $y$ to $v$ and from $v$ to $x$. After these changes, for every $v$, $d^+(v) - d^-(v)$ will not change. However if there is no such vertex, the graph contains some paths and cycles in which the weight of each path and cycle is 1 or 2 every other one. So we can direct edges of each cycle to produce a directed cycle and do the same thing for edges of each path in order to make a directed path. By doing this, every $v$ with odd $c_v$ will become Oddysey.",
    "code": "#include <bits/stdc++.h>\n#pragma GCC optimize (\"O2,unroll-loops\")\n \nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\n#define all(x) x.begin(), x.end()\n#define pb push_back\n#define SZ(x) ((int)x.size())\n#define kill(x) return cout<<x<<'\\n', 0;\n \nconst int inf=1000000010;\nconst ll INF=100000000000000100LL;\nconst int mod=1000000007;\nconst int MAXN=300010, LOG=19;\n \nint n, m, mm, k, u, v, x, y, t, a, b;\nint U[MAXN], V[MAXN], W[MAXN], ans[MAXN];\nint deg[MAXN], parr[MAXN][3], mark[MAXN];\nvector<int> G[MAXN][3], E[MAXN];\nvector<pii> G2[MAXN];\n \ninline void orient(int i, int u){\n\tif (u==U[i]){\n\t\tans[i]=1;\n\t\tdeg[U[i]]-=W[i];\n\t\tdeg[V[i]]+=W[i];\n\t}\n\telse{\n\t\tans[i]=2;\n\t\tdeg[U[i]]+=W[i];\n\t\tdeg[V[i]]-=W[i];\n\t}\n}\n \nvoid MergePath(int i, int w){\n\tmm++;\n\tint v=i;\n\twhile (1){\n\t\twhile (SZ(G[v][w]) && mark[G[v][w].back()]) G[v][w].pop_back();\n\t\tif (G[v][w].empty()) break ;\n\t\tint i=G[v][w].back();\n\t\tassert(!mark[i]);\n\t\tmark[i]=1;\n\t\tE[mm].pb(i);\n\t\tint u=(U[i]^V[i]^v);\n\t\tparr[u][w]^=1;\n\t\tparr[v][w]^=1;\n\t\tv=u;\n\t}\n\tif (E[mm].empty()){\n\t\tmm--;\n\t\treturn ;\n\t}\n\tG2[i].pb({v, mm});\n\tG2[v].pb({i, -mm});\n}\nvoid dfs(int v){\n\twhile (SZ(G2[v]) && mark[abs(G2[v].back().second)]) G2[v].pop_back();\n\tif (G2[v].empty()) return ;\n\tint u=G2[v].back().first, id=G2[v].back().second;\n\tif (id<0){\n\t\tid*=-1;\n\t\treverse(all(E[id]));\n\t}\n\tmark[id]=1;\n\tfor (int i:E[id]){\n\t\torient(i, v);\n\t\tv^=V[i]^U[i];\n\t}\n\tassert(v==u);\n\tdfs(u);\n}\n \nint main(){\n\tios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\tcin>>n>>m;\n\tfor (int i=0; i<m; i++){\n\t\tcin>>U[i]>>V[i]>>W[i];\n\t\tparr[U[i]][W[i]]^=1;\n\t\tparr[V[i]][W[i]]^=1;\n\t\tG[U[i]][W[i]].pb(i);\n\t\tG[V[i]][W[i]].pb(i);\n\t}\n\tint sum=0;\n\tfor (int i=1; i<=n; i++) sum+=parr[i][1];\n\tfor (int i=1; i<=n; i++) for (int w:{1, 2}) if (parr[i][w]) MergePath(i, w);\n\tfor (int i=1; i<=n; i++) for (int w:{1, 2}) MergePath(i, w);\n \n\tfor (int i=0; i<m; i++){\n\t\tassert(mark[i]);\n\t\tmark[i]=0;\n\t}\n\tfor (int i=1; i<=n; i++) if (SZ(G2[i])&1) dfs(i);\n\tfor (int i=1; i<=n; i++) dfs(i);\n \n\tcout<<sum<<\"\\n\";\n\tfor (int i=0; i<m; i++) cout<<ans[i]; cout<<\"\\n\";\n \n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1610",
    "index": "G",
    "title": "AmShZ Wins a Bet",
    "statement": "Right before the UEFA Euro 2020, AmShZ and Safar placed bets on who'd be the champion, AmShZ betting on Italy, and Safar betting on France.\n\nOf course, AmShZ won. Hence, Safar gave him a bracket sequence $S$. Note that a bracket sequence is a string made of '(' and ')' characters.\n\nAmShZ can perform the following operation any number of times:\n\n- First, he cuts his string $S$ into three (possibly empty) contiguous substrings $A, B$ and $C$. Then, he glues them back by using a '(' and a ')' characters, resulting in a new string $S$ = $A$ + \"(\" + $B$ + \")\" + $C$.For example, if $S$ = \"))((\" and AmShZ cuts it into $A$ = \"\", $B$ = \"))\", and $C$ = \"((\", He will obtain $S$ = \"()))((\" as a new string.\n\nAfter performing some (possibly none) operations, AmShZ gives his string to Keshi and asks him to find the initial string. Of course, Keshi might be able to come up with more than one possible initial string. Keshi is interested in finding the lexicographically smallest possible initial string.\n\nYour task is to help Keshi in achieving his goal.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Idea: AmShZ, Keshi, Preparation: AmShZ, Keshi, alireza_kaviani, AliShahali1382 We can prove that there exists a way to achieve the lexicographically minimum by removing some balanced substrings. (A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters \"+\" and \"1\".) We will remove some pairs of indices. If there is a pair that we don't remove all the characters between them, by using that character instead of one the initial ones the answer either stays the same or becomes lexicographically smaller. Because if the character in between is \"(\", changing the pair is like moving a \"(\" closer to the front of the outcome which will make it smaller. And if it's \")\", changing the pair is like moving a \")\" farther from the front of the outcome which will make it smaller. For each $i$ find the shortest non-empty balanced substring that starts in index $i$. Let the length of this substring be $l$. Set $nxt_i$ as $i + l$, or $i$ if no such substring exists. For each $i$ we either keep the $i$-th character or remove every character in $[i, nxt_i)$ interval. Imagine we somehow store the answer for each suffix. Then $ans_i = \\min(s_i + ans_{i + 1}, ans_{nxt_i})$. $\\textbf{Read the Hints and Assumptions before reading this.}$",
    "code": "//In the name of God\n#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long ll;\ntypedef pair<ll, ll> pll;\n \nconst ll maxn = 3e5 + 100;\nconst ll lg = 20;\nconst ll mod = 1e9 + 7;\nconst ll inf = 1e18;\n \n#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n#define file_io freopen(\"input.txt\", \"r+\", stdin);freopen(\"output.txt\", \"w+\", stdout);\n#define pb push_back\n#define Mp make_pair\n#define F first\n#define S second\n#define Sz(x) ll((x).size())\n#define all(x) (x).begin(), (x).end()\n \nll n, par[maxn][lg], h[maxn][lg], ls[maxn + maxn], ps[maxn], nxt[maxn], a[maxn], d[maxn], p[maxn];\nstring s;\n \nll check(ll v, ll u){\n\tfor(ll i = lg; i--;){\n\t\tif(d[v] < (1 << i) || d[u] < (1 << i)) continue;\n\t\tif(h[v][i] == h[u][i]){\n\t\t\tv = par[v][i];\n\t\t\tu = par[u][i];\n\t\t}\n\t}\n\tif(d[v] == 0) return 1;\n\treturn (h[v][0] < h[u][0]);\n}\n \nint main(){\n\tfast_io;\n\tp[0] = 1;\n\tfor(ll i = 1; i < maxn; i++){\n\t\tp[i] = p[i - 1] * 2 % mod;\n\t}\n    \n\tcin >> s;\n\tn = Sz(s);\n\ts = ' ' + s;\n\tfor(ll i = 1; i <= n; i++){\n\t\tps[i] = ps[i - 1] + (s[i] == '(' ? 1 : -1);\n\t}\n\tfor(ll i = n + 1; i > 0; i--){\n\t\tnxt[i] = i;\n\t\tif(s[i] == '(' && ls[ps[i - 1] + maxn]){\n\t\t\tnxt[i] = ls[ps[i - 1] + maxn];\n\t\t}\n\t\tls[ps[i - 1] + maxn] = i;\n\t}\n\ta[n + 1] = n + 1;\n\tfor(ll i = n; i > 0; i--){\n\t\tpar[i][0] = a[i + 1];\n\t\th[i][0] = (s[i] == '(' ? 0 : 1);\n\t\td[i] = d[par[i][0]] + 1;\n\t\tfor(ll j = 1; j < lg; j++){\n\t\t\tif(d[i] < (1 << j)) break;\n\t\t\tpar[i][j] = par[par[i][j - 1]][j - 1];\n\t\t\th[i][j] = (h[i][j - 1] * p[(1 << (j - 1))] + h[par[i][j - 1]][j - 1]) % mod;\n\t\t}\n\t\ta[i] = i;\n\t\tif(check(a[nxt[i]], i)){\n\t\t\ta[i] = a[nxt[i]];\n\t\t}\n\t}\n\tll v = a[1];\n\twhile(v != n + 1){\n\t\tcout << (h[v][0] ? ')' : '(');\n\t\tv = par[v][0];\n\t}\n\tcout << \"\\n\";\n \n    return 0;\n}\n",
    "tags": [
      "data structures",
      "greedy",
      "hashing"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1610",
    "index": "H",
    "title": "Squid Game",
    "statement": "After watching the new \\sout{over-rated} series Squid Game, Mashtali and Soroush decided to hold their own Squid Games! Soroush agreed to be the host and will provide money for the winner's prize, and Mashtali became the Front Man!\n\n$m$ players registered to play in the games to win the great prize, but when Mashtali found out how huge the winner's prize is going to be, he decided to \\sout{kill} eliminate all the players so he could take the money for himself!\n\nHere is how evil Mashtali is going to eliminate players:\n\nThere is an unrooted tree with $n$ vertices. Every player has $2$ special vertices $x_i$ and $y_i$.\n\nIn one operation, Mashtali can choose any vertex $v$ of the tree. Then, for each remaining player $i$ he finds a vertex $w$ on the simple path from $x_i$ to $y_i$, which is the closest to $v$. If $w\\ne x_i$ and $w\\ne y_i$, player $i$ will be eliminated.\n\nNow Mashtali wondered: \"What is the minimum number of operations I should perform so that I can remove every player from the game and take the money for myself?\"\n\nSince he was only thinking about the money, he couldn't solve the problem by himself and asked for your help!",
    "tutorial": "A player gets eliminated iff $(x_i, y_i)$ is a cross-edge while rooting the tree from where Mashtali sits. we say a vertex is marked if Mashtali choses it in a move. Lets solve the problem in polynomial time. First, lets fix one of the marked vertices and root the tree from it. Then all cross-edges are already covered and we have a set of back-edges to cover. Then, we can use this greedy approach: At each step, take the lowest uncovered back-edge and mark the second highest vertex in its path.(the highest one is either $x_i$ or $y_i$ which is not allowed) You can prove its correct using the fact that there is no lower back-edges, so if we mark a higher vertex all vertices that were marked before, are marked now. So far the complexity is smth like $O(n^3)$. But we can use fenwick-tree to check whether an edge is covered or not. Which leads to a $O(n^2 \\cdot log(n))$ solution. Now, let's forget about fixing one of the moves! let's just make the tree rooted at $1$, ignore all cross-edges, and do the previous solution. Finally, check if there is an uncovered cross-edge. If so, just put a token on $1$. Now, why is that correct? if all cross-edges are covered, everything is ok. So we just need to show we need more marked vertices if a cross-edge is uncovered. If that happens, it means all our tokens are either in subtree of $x_i$ or in subtree of $y_i$. Since we put our tokens at highest possible nodes, there is no vertex that would mark the cross-edge and a back-edge with it. So, we need to mark at least one more vertex and the root, suffice. time complexity: $O(n \\cdot log(n))$",
    "code": "#include <bits/stdc++.h>\n#pragma GCC optimize (\"O2,unroll-loops\")\n \nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<pii, int> piii;\ntypedef pair<ll, ll> pll;\n#define debug(x) cerr<<#x<<'='<<(x)<<endl;\n#define debugp(x) cerr<<#x<<\"= {\"<<(x.first)<<\", \"<<(x.second)<<\"}\"<<endl;\n#define debug2(x, y) cerr<<\"{\"<<#x<<\", \"<<#y<<\"} = {\"<<(x)<<\", \"<<(y)<<\"}\"<<endl;\n#define debugv(v) {cerr<<#v<<\" : \";for (auto x:v) cerr<<x<<' ';cerr<<endl;}\n#define all(x) x.begin(), x.end()\n#define pb push_back\n#define SZ(x) ((int)x.size())\n#define kill(x) return cout<<x<<'\\n', 0;\n \nconst int inf=1000000010;\nconst ll INF=100000000000000100LL;\nconst int mod=1000000007;\nconst int MAXN=300010, LOG=19;\n \nint n, m, k, u, v, x, y, t, a, b, ans;\nint par[LOG][MAXN], h[MAXN], P[MAXN];\nint stt[MAXN], fnt[MAXN], timer=1;\nint fen[MAXN];\nvector<int> G[MAXN], vec[MAXN], out;\n \nint GetPar(int v, int k){\n\tfor (int i=0; k; i++) if (k&(1<<i)){\n\t\tk^=(1<<i);\n\t\tv=par[i][v];\n\t}\n\treturn v;\n}\ninline void add(int pos, int val){\n\tfor (; pos<MAXN; pos+=pos&-pos) fen[pos]+=val;\n}\ninline int get(int pos){\n\tint res=0;\n\tfor (; pos; pos-=pos&-pos) res+=fen[pos];\n\treturn res;\n}\ninline int get2(int v){ return get(fnt[v]-1)-get(stt[v]-1);}\nvoid dfs(int node){\n\tstt[node]=timer++;\n\tfor (int v:G[node]) dfs(v);\n\tfnt[node]=timer;\n}\n \nint main(){\n\tios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\tcin>>n>>m;\n\tfor (int i=2; i<=n; i++){\n\t\tcin>>par[0][i];\n\t\tG[par[0][i]].pb(i);\n\t\th[i]=h[par[0][i]]+1;\n\t\tfor (int j=1; j<LOG; j++)\n\t\t\tpar[j][i]=par[j-1][par[j-1][i]];\n\t}\n\tdfs(1);\n\twhile (m--){\n\t\tcin>>x>>y;\n\t\tif (h[x]>h[y]) swap(x, y);\n\t\tif (par[0][y]==x) kill(-1)\n\t\tvec[x].pb(y);\n\t}\n\tiota(P+1, P+n+1, 1);\n\tsort(P+1, P+n+1, [](int i, int j){ return h[i]>h[j];});\n\tvector<pii> crossE;\n\tfor (int i=1; i<=n; i++){\n\t\tint x=P[i];\n\t\tfor (int y:vec[x]){\n\t\t\tif (h[x]==h[y]){\n\t\t\t\tcrossE.pb({x, y});\n\t\t\t\tcontinue ;\n\t\t\t}\n\t\t\tint yy=GetPar(y, h[y]-h[x]-1);\n\t\t\tif (par[0][yy]!=x){\n\t\t\t\tcrossE.pb({x, y});\n\t\t\t\tcontinue ;\n\t\t\t}\n\t\t\tif (get2(yy)-get2(y)) continue ;\n\t\t\tans++;\n\t\t\tout.pb(yy);\n\t\t\tadd(stt[yy], +1);\n\t\t}\n\t}\n\tfor (pii p:crossE){\n\t\tint x=p.first, y=p.second;\n\t\tif (get2(x)+get2(y)<ans) continue ;\n\t\tout.pb(1);\n\t\tans++;\n\t\tbreak ;\n\t}\n\tcout<<ans<<\"\\n\";\n \n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1611",
    "index": "A",
    "title": "Make Even",
    "statement": "Polycarp has an integer $n$ that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times:\n\n- Reverse the prefix of length $l$ (in other words, $l$ leftmost digits) of $n$. So, the leftmost digit is swapped with the $l$-th digit from the left, the second digit from the left swapped with ($l-1$)-th left, etc. For example, if $n=123456789$ and $l=5$, then the new value of $n$ will be $543216789$.\n\nNote that for different operations, the values of $l$ can be different. The number $l$ can be equal to the length of the number $n$ — in this case, the whole number $n$ is reversed.\n\nPolycarp loves even numbers. Therefore, he wants to make his number even. At the same time, Polycarp is very impatient. He wants to do as few operations as possible.\n\nHelp Polycarp. Determine the minimum number of operations he needs to perform with the number $n$ to make it even or determine that this is impossible.\n\nYou need to answer $t$ independent test cases.",
    "tutorial": "If the number is already even, then nothing needs to be done, so the answer in this case is 0. Now let's recall the divisibility by $2$: a number is divisible by $2$ if and only if its last digit is divisible by $2$. It follows that if there are no even digits in our number, then the answer is -1. Let's take a look at our operation. What is going on? The first digit always changes with the digit numbered $l$. In particular, when we reverse the entire number, the first digit is swapped with the last. Note that no other digit, except for the first one at the current moment, can't be the last. Therefore, you can do this: if the first digit of a number is divisible by $2$, then we reverse the whole number. The first digit will become the last, and the number will become even. Therefore, you only need to do one operation. Now, what if the first digit of a number is odd? In this case, we can find the first even digit in the number (let it be at position $x$), and reverse the prefix of length $x$ (in one operation). Now the first digit of our number has become even, and we can use the previous case (one more operation). Thus, we will do only 2 operations.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    while(t--) {\n        string n;\n        cin >> n;\n        if((n.back() - '0') % 2 == 0) {\n            cout << \"0\\n\";\n            continue;\n        }\n        if((n[0] - '0') % 2 == 0) {\n            cout << \"1\\n\";\n            continue;\n        }\n        int count_2 = count(n.begin(), n.end(), '2');\n        int count_4 = count(n.begin(), n.end(), '4');\n        int count_6 = count(n.begin(), n.end(), '6');\n        int count_8 = count(n.begin(), n.end(), '8');\n        if(count_2 > 0 || count_4 > 0 || count_6 > 0 || count_8 > 0) {\n            cout << \"2\\n\";\n            continue;\n        }\n        cout << \"-1\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1611",
    "index": "B",
    "title": "Team Composition: Programmers and Mathematicians",
    "statement": "The All-Berland Team Programming Contest will take place very soon. This year, teams of four are allowed to participate.\n\nThere are $a$ programmers and $b$ mathematicians at Berland State University. How many maximum teams can be made if:\n\n- each team must consist of exactly $4$ students,\n- teams of $4$ mathematicians or $4$ programmers are unlikely to perform well, so the decision was made not to compose such teams.\n\nThus, each team must have at least one programmer \\textbf{and} at least one mathematician.\n\nPrint the required maximum number of teams. Each person can be a member of no more than one team.",
    "tutorial": "If necessary, change the values of $a$ and $b$ so that $a \\le b$ is always true. Consider two cases. 1. Let $a \\le \\frac{a + b}{4}$. Then: $4a \\le a + b$, $3a \\le b$. This means that the set $b$ is at least $3$ times larger than $a$, and we can form $a$ teams of the form $(1, 3)$, where one participant will be a programmer and three will be mathematicians. 2. Let $\\frac{a + b}{4} \\le a$. Then assume that $b = a + d$. Let's substitute this value into the inequality: $\\frac{2a + d}{4} \\le a$, $2a + d \\le 4a$ $d \\le 2a$, $\\frac{d}{2} \\le a$ Then we compose $\\frac{d}{2}$ commands of the form $(1, 3)$. Since making such a command decreases the value of $d$ by 2. The new value $a' = a - \\frac{d}{2}$, $b' = a' + d - 2 * (\\frac{d}{2})$. The condition $a' \\le b'$ still holds. Then make $\\frac{a'}{2}$ commands of the form $(2, 2)$. The total number of commands is $\\frac{a'}{2} + \\frac{d}{2} = \\frac{2*a' + 2*d}{4} = \\frac{2*a - d + 2*d}{4} = \\frac{a + (a+d)}{4} = \\frac{a+b}{4}$. That's what we wanted to get.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nusing ll = long long;\n \nvoid solve() {\n    ll a, b;\n    cin >> a >> b;\n    cout << min(min(a, b), (a + b) / 4) << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1611",
    "index": "C",
    "title": "Polycarp Recovers the Permutation",
    "statement": "Polycarp wrote on a whiteboard an array $p$ of length $n$, which is a permutation of numbers from $1$ to $n$. In other words, in $p$ each number from $1$ to $n$ occurs exactly once.\n\nHe also prepared a resulting array $a$, which is initially empty (that is, it has a length of $0$).\n\nAfter that, he did exactly $n$ steps. Each step looked like this:\n\n- Look at the leftmost and rightmost elements of $p$, and pick the smaller of the two.\n- If you picked the leftmost element of $p$, append it to the left of $a$; otherwise, if you picked the rightmost element of $p$, append it to the right of $a$.\n- The picked element is erased from $p$.\n\nNote that on the last step, $p$ has a length of $1$ and its minimum element is both leftmost and rightmost. In this case, Polycarp can choose what role the minimum element plays. In other words, this element can be added to $a$ both on the left and on the right (at the discretion of Polycarp).\n\nLet's look at an example. Let $n=4$, $p=[3, 1, 4, 2]$. Initially $a=[]$. Then:\n\n- During the first step, the minimum is on the right (with a value of $2$), so after this step, $p=[3,1,4]$ and $a=[2]$ (he added the value $2$ to the right).\n- During the second step, the minimum is on the left (with a value of $3$), so after this step, $p=[1,4]$ and $a=[3,2]$ (he added the value $3$ to the left).\n- During the third step, the minimum is on the left (with a value of $1$), so after this step, $p=[4]$ and $a=[1,3,2]$ (he added the value $1$ to the left).\n- During the fourth step, the minimum is both left and right (this value is $4$). Let's say Polycarp chose the right option. After this step, $p=[]$ and $a=[1,3,2,4]$ (he added the value $4$ to the right).\n\nThus, a possible value of $a$ after $n$ steps could be $a=[1,3,2,4]$.\n\nYou are given the final value of the resulting array $a$. Find \\textbf{any} possible initial value for $p$ that can result the given $a$, or determine that there is no solution.",
    "tutorial": "The maximum element is always added last, so if it is not in the first or last position, then there is no answer. Let us prove that if the permutation has its maximum element in the first or last position, then after $n$ actions we can get an expanded permutation. Indeed, the maximum element will be added last at the desired end, and all the others will be added in reverse order. Then, if the answer exists, it is sufficient to simply unfold the permutation.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        forn(i, n)\n            cin >> a[i];\n        if (a[0] != n && a[n - 1] != n)\n            cout << -1 << endl;\n        else {\n            for (int i = n - 1; i >= 0; i--)\n                cout << a[i] << \" \";\n            cout << endl;\n        }\n    }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1611",
    "index": "D",
    "title": "Weights Assignment For Tree Edges",
    "statement": "You are given a rooted tree consisting of $n$ vertices. Vertices are numbered from $1$ to $n$. Any vertex can be the root of a tree.\n\nA tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.\n\nThe tree is specified by an array of ancestors $b$ containing $n$ numbers: $b_i$ is an ancestor of the vertex with the number $i$. The ancestor of a vertex $u$ is a vertex that is the next vertex on a simple path from $u$ to the root. For example, on the simple path from $5$ to $3$ (the root), the next vertex would be $1$, so the ancestor of $5$ is $1$.\n\nThe root has no ancestor, so for it, the value of $b_i$ is $i$ (the root is the only vertex for which $b_i=i$).\n\nFor example, if $n=5$ and $b=[3, 1, 3, 3, 1]$, then the tree looks like this.\n\n\\begin{center}\n{\\small An example of a rooted tree for $n=5$, the root of the tree is a vertex number $3$.}\n\\end{center}\n\nYou are given an array $p$ — a permutation of the vertices of the tree. If it is possible, assign any \\textbf{positive} integer weights on the edges, so that the vertices sorted by distance from the root would form the given permutation $p$.\n\nIn other words, for a given permutation of vertices $p$, it is necessary to choose such edge weights so that the condition $dist[p_i]<dist[p_{i+1}]$ is true for each $i$ from $1$ to $n-1$. $dist[u]$ is a sum of the weights of the edges on the path from the root to $u$. In particular, $dist[u]=0$ if the vertex $u$ is the root of the tree.\n\nFor example, assume that $p=[3, 1, 2, 5, 4]$. In this case, the following edge weights satisfy this permutation:\n\n- the edge ($3, 4$) has a weight of $102$;\n- the edge ($3, 1$) has weight of $1$;\n- the edge ($1, 2$) has a weight of $10$;\n- the edge ($1, 5$) has a weight of $100$.\n\nThe array of distances from the root looks like: $dist=[1,11,0,102,101]$. The vertices sorted by increasing the distance from the root form the given permutation $p$.\n\nPrint the required edge weights or determine that there is no suitable way to assign weights. If there are several solutions, then print any of them.",
    "tutorial": "Consider the cases when it is impossible to form a given permutation $p$: 1. The first vertex in the permutation is not the root of the tree. For root $u$ it is true that $dist[u]=0$. For any other vertex $i$ the value of $dist[i]$ will be positive, since there is at least one edge of positive weight on the path to it. 2. The distance to the child is less than to the parent. In a rooted tree there is exactly one path from the root to any vertex $i$, and it goes through its parent $b_i$, so it must always be true $dist[b[i]] < dist[i]$. Let us start filling the array $dist$, where $dist[p[1]] = 0$. Consider a vertex $p[i]$, ($2 \\le p[i] \\le n$). The vertex whose distance at the current time is maximal is $p[i - 1]$. Then $dist[p[i]]$ is at least $dist[p[i - 1]] + 1$. We assign a value to $dist[i]$, remembering to check that $dist[b[i]]$ has already been counted. After counting all $dist[i]$ values, we can output the lengths of the edges: $w[i] = dist[i] - dist[b[i]]$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int> b(n + 1), p(n + 1), dist(n + 1, -1);\n \n    for(int i = 1; i <= n; i++)\n        cin >> b[i];\n    for(int i = 1; i <= n; i++)\n        cin >> p[i];\n \n    if (b[p[1]] != p[1]){\n        cout << -1 << '\\n';\n        return;\n    }\n \n    dist[p[1]] = 0;\n    for(int i = 2; i <= n; i++){\n        if(dist[b[p[i]]] == -1){\n            cout << -1 << '\\n';\n            return;\n        }\n        dist[p[i]] = dist[p[i - 1]] + 1;\n    }\n \n    for(int i = 1; i <= n; i++) {\n        cout << dist[i] - dist[b[i]] << ' ';\n    }\n    cout << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while(t-- > 0) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1611",
    "index": "E1",
    "title": "Escape The Maze (easy version)",
    "statement": "The only difference with E2 is the question of the problem..\n\nVlad built a maze out of $n$ rooms and $n-1$ bidirectional corridors. From any room $u$ any other room $v$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.\n\nVlad invited $k$ friends to play a game with them.\n\nVlad starts the game in the room $1$ and wins if he reaches a room other than $1$, into which exactly one corridor leads.\n\nFriends are placed in the maze: the friend with number $i$ is in the room $x_i$, and no two friends are in the same room (that is, $x_i \\neq x_j$ for all $i \\neq j$). Friends win if one of them meets Vlad in any room or corridor before he wins.\n\nFor one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time.\n\nFriends know the plan of a maze and intend to win. Vlad is a bit afraid of their ardor. Determine if he can guarantee victory (i.e. can he win in any way friends play).\n\nIn other words, determine if there is such a sequence of Vlad's moves that lets Vlad win in any way friends play.",
    "tutorial": "First, we need to understand when it is not possible to get to some exit $e$. Let's fix a friend who is at the vertex $f$ and try to understand if he can interfere with us. The paths from $1$ to $e$ and from $f$ to $e$ have a common part, let it start at the vertex $v$. Then, if the path from $f$ to $v$ is not more than from $1$ to $v$, it can prevent us from reaching this exit by blocking the vertex $v$. Since the path from $v$ to $e$ is common, the previous condition is equivalent to the condition that the path from $f$ to $e$ is not greater than from $1$ to $e$. Note that if there is more than one such vertex $e$, then $f$ can overlap each of them, simply by going as close to the root as possible. Thus, Vlad can win if there is such a leaf (which, by condition, exits) for which the distance to the root is less than the distance to any of the friends. By running a breadth-first search at the same time from each vertex with a friend, we can find the shortest distance to any friend from each vertex and by running from the root - the distance to the root. Now let's just go through all the leaves and check if there is one among them that the distance to the root is less. We can also run from the vertices with friends and from the root at the same time, assigning them different colors, then the color will correspond to what is closer: the root or some friend. this solution is attached to the tutorial. There is also another solution, which is a simplified version of the one we will use in E2.",
    "code": "//\n// Created by Vlad on 16.11.2021.\n//\n \n#include <bits/stdc++.h>\n \n#define int long long\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n \ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(143);\n \nconst int inf = 1e10;\nconst int M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-4;\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    vector<int> color(n, -1);\n    deque<int> q;\n    for(int i = 0; i < k; ++i){\n        int x;\n        cin >> x;\n        color[--x] = 0;\n        q.push_back(x);\n    }\n    color[0] = 1;\n    q.push_back(0);\n    vector<vector<int>> g(n);\n    for(int i = 0; i < n - 1; ++i){\n        int u, v;\n        cin >> u >> v;\n        g[--u].push_back(--v);\n        g[v].push_back(u);\n    }\n    while(!q.empty()){\n        int v = q.front();\n        q.pop_front();\n        for(int u: g[v]){\n            if(color[u] == -1){\n                color[u] = color[v];\n                q.push_back(u);\n            }\n        }\n    }\n    for(int v = 1; v < n; ++v){\n        if(g[v].size() == 1 && color[v] == 1){\n            cout << \"YES\";\n            return;\n        }\n    }\n    cout << \"NO\";\n}\n \nbool multi = true;\n \nsigned main() {\n    int t = 1;\n    if (multi) {\n        cin >> t;\n    }\n    for (; t != 0; --t) {\n        solve();\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "greedy",
      "shortest paths",
      "trees",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1611",
    "index": "E2",
    "title": "Escape The Maze (hard version)",
    "statement": "The only difference with E1 is the question of the problem.\n\nVlad built a maze out of $n$ rooms and $n-1$ bidirectional corridors. From any room $u$ any other room $v$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.\n\nVlad invited $k$ friends to play a game with them.\n\nVlad starts the game in the room $1$ and wins if he reaches a room other than $1$, into which exactly one corridor leads. Friends are placed in the maze: the friend with number $i$ is in the room $x_i$, and no two friends are in the same room (that is, $x_i \\neq x_j$ for all $i \\neq j$). Friends win if one of them meets Vlad in any room or corridor before he wins.\n\nFor one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time.\n\nFriends know the plan of a maze and intend to win. They don't want to waste too much energy. They ask you to determine if they can win and if they can, what \\textbf{minimum} number of friends must remain in the maze so that they can always catch Vlad.\n\nIn other words, you need to determine the size of the minimum (by the number of elements) subset of friends who can catch Vlad or say that such a subset does not exist.",
    "tutorial": "Let's learn how to find an answer for the subtree rooted in vertex $v$. At first, it is obvious from E1 tutorial that if the nearest to $v$ vertex with a friend from this subtree is no further from it than the root of the entire tree from $v$, then the answer for the entire subtree is $1$ since a friend can come to $v$ and catch Vlad in it not allowing him to go to any leaf of this subtree. Else we will find the answer leaning on its children. If a solution does not exist for at least one child, then it does not exist for the entire subtree, because after reaching $v$ Vlad will be able to go to such child and reach any exit. Otherwise, the answer for $v$ is the sum of the answers of its children, since we need to beat it in each subtree to win, and for each subtree, we have found the minimum answer.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n \n/*#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"no-stack-protector\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native\")\n#pragma GCC optimize(\"fast-math\")\n*/\ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(143);\n \nconst int inf = 1e10;\nconst int M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-4;\n \nvector<vector<int>> sl;\nvector<int> nearest;\n \nint count(int v, int dist, int p = -1){\n    bool children = true;\n    int s = 0;\n    for(int u: sl[v]){\n        if(u == p) continue;\n        int c = count(u, dist + 1, v);\n        if(c < 0) children = false;\n        nearest[v] = min(nearest[v], nearest[u] + 1);\n        s += c;\n    }\n    if(nearest[v] <= dist) return 1;\n    if(s == 0 || !children) return -1;\n    return s;\n}\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    sl.assign(n, vector<int>(0));\n    nearest.assign(n, n);\n    for(int i = 0; i < k; ++i){\n        int x;\n        cin >> x;\n        --x;\n        nearest[x] = 0;\n    }\n    for(int i = 1; i  < n; ++i){\n        int u, v;\n        cin >> u >> v;\n        --u, --v;\n        sl[u].emplace_back(v);\n        sl[v].emplace_back(u);\n    }\n    cout << count(0, 0);\n}\n \nbool multi = true;\n \nsigned main() {\n    //freopen(\"in.txt\", \"r\", stdin);\n    //freopen(\"in.txt\", \"w\", stdout);\n    /*ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);*/\n    int t = 1;\n    if (multi) {\n        cin >> t;\n    }\n    for (; t != 0; --t) {\n        solve();\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "shortest paths",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1611",
    "index": "F",
    "title": "ATM and Students",
    "statement": "Polycarp started working at a bank. He was assigned to monitor the ATM. The ATM initially contains $s$ rubles.\n\nA queue of $n$ students lined up to him. Each student wants to either withdraw a certain amount of money or deposit it into an account. If $a_i$ is positive, then the student credits that amount of money via ATM. Otherwise, the student withdraws $|a_i|$ rubles.\n\nIn the beginning, the ATM is turned off and an arbitrary number of students are not served. At some point, Polycarp turns on the ATM, which has an initial amount of $s$ rubles. Then, the remaining students start queueing at the ATM. If at some point in time there is less money in the ATM than the student wants to withdraw, then the student is not served and Polycarp turns off the ATM and does not turn it on anymore.\n\nMore formally, the students that are served are forming a \\textbf{contiguous subsequence}.\n\nPolycarp wants the ATM to serve the \\textbf{maximum} number of students. Help him in this matter. Print the numbers of the first and last student, or determine that he will not be able to serve anyone.\n\nIn other words, find such a longest continuous segment of students that, starting with the sum of $s$ at the ATM, all these students will be served. ATM serves students consistently (i.e. one after another in the order of the queue).",
    "tutorial": "At first glance, this is a standard problem for ST (Segment Tree). Let's solve the problem in that way. First, we find the prefix sums of the $a$ array and store them in $p$. Let's build an ST on the prefix array and store the min in it. For each index $l$ $(1 \\le l \\le n)$, we'll make a query in ST and will find such a minimum index $r$ ($l \\le r$) that the sum on the subsegment $[l, r]$ of the array $a$ and $s$ will be negative, in other words $s + (p [r] -p [l-1]) \\lt 0$ or $s - p [l-1] \\lt -p [r]$, the sum of s is obtained and the subsegment $[l, r)$ of the array $a$ will be non-negative, in other words, $s + (p [r-1] - p [l-1]) \\ge 0$. Accordingly, the correct response to the request will be $l$ and $r-1$. Of all such pairs of indices $l$ and $r-1$, we take such that the distance between them is maximal. If for all pairs $l == r$, then the answer is $-1$. The hardest part here is the querys. Actually, here's a query that returns $r-1$ for index $l$ or $-1$ if $l == r$: Btw, after each request for $l$ do not forget to change in ST the element that corresponds to $p[l]$ to MAX_INT, so that it does not interfere with us. Time complexity is $O(n \\cdot log(n))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nvector<ll> t, a;\nll s, tl;\n\nconst ll MAX = 1'000'000'000'000'000LL;\n\nvoid build(int v, int l, int r) {\n\tif (l == r)\n\t\tt[v] = a[l];\n\telse {\n\t\tint m = (l + r) / 2;\n\t\tbuild (v * 2, l, m);\n\t\tbuild (v * 2 + 1, m + 1, r);\n\t\tt[v] = min(t[v * 2], t[v * 2 + 1]);\n\t}\n}\n\nvoid update(int v, int l, int r) {\n\tif (l == r)\n\t\tt[v] = MAX;\n\telse {\n\t\tint m = (l + r) / 2;\n\t\tif (tl <= m)\n\t\t\tupdate(v * 2, l, m);\n\t\telse\n\t\t\tupdate(v * 2 + 1, m + 1, r);\n\t\tt[v] = min(t[v * 2], t[v * 2 + 1]);\n\t}\n}\n\nint lower_bound_s(int v, int l, int r) {\n\tif (r < tl || (l == r && s < -t[v])) {\n\t\treturn -1;\n\t}\n    if (l == r || -t[v] <= s) {\n        return r;\n    }\n\tint m = (l + r) / 2;\n\n\tif (m < tl) {\n        return lower_bound_s(2 * v + 1, m + 1, r);\n\t}\n\tif (s < -t[2 * v]) {\n        return lower_bound_s(2 * v, l, m);\n\t}\n\tint res = lower_bound_s(2 * v + 1, m + 1, r);\n\treturn (res == -1) ? m : res;\n}\n\n\nint main() {\n    int tests;\n    cin >> tests;\n    forn(tt, tests) {\n        int n;\n        cin >> n >> s;\n        t = vector<ll>(4 * n);\n        a = vector<ll>(n);\n        forn(i, n) {\n            cin >> a[i];\n        }\n        for (int i = 1; i < n; ++i) {\n            a[i] += a[i - 1];\n        }\n        build(1, 0, n - 1);\n        int first = -1, second = -2;\n        for (tl = 0; tl < n; ++tl) {\n            int v = lower_bound_s(1, 0, n - 1);\n            if (v != -1 && v - tl > second - first) {\n                first = tl + 1;\n                second = v + 1;\n            }\n            s -= a[tl];\n            if (tl != 0) s += a[tl - 1];\n            update(1, 0, n - 1);\n        }\n        if (first == -1) {\n            cout << -1;\n        } else {\n            cout << first << \" \" << second;\n        }\n        cout << endl;\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1611",
    "index": "G",
    "title": "Robot and Candies",
    "statement": "Polycarp has a rectangular field of $n \\times m$ cells (the size of the $n \\cdot m$ field does not exceed $10^6$ cells, $m \\ge 2$), in each cell of which there can be candy. There are $n$ rows and $m$ columns in the field.\n\nLet's denote a cell with coordinates $x$ vertically and $y$ horizontally by $(x, y)$. Then the top-left cell will be denoted as $(1, 1)$, and the bottom-right cell will be denoted as $(n, m)$.\n\nIf there is candy in the cell, then the cell is marked with the symbol '1', otherwise — with the symbol '0'.\n\nPolycarp made a Robot that can collect candy. The Robot can move from $(x, y)$ either to $(x+1, y+1)$, or to $(x+1, y-1)$. If the Robot is in a cell that contains candy, it takes it.\n\nWhile there is at least one candy on the field, the following procedure is executed:\n\n- Polycarp puts the Robot in an arbitrary cell on the \\textbf{topmost row} of the field. He himself chooses in which cell to place the Robot. It is allowed to put the Robot in the same cell multiple times.\n- The Robot moves across the field and collects candies. He controls the Robot.\n- When the Robot leaves the field, Polycarp takes it. If there are still candies left, Polycarp repeats the procedure.\n\nFind the \\textbf{minimum} number of times Polycarp needs to put the Robot on the topmost row of the field in order to collect all the candies. It is guaranteed that Polycarp can always collect all the candies.",
    "tutorial": "Note first that we can solve the two subtasks independently if we consider the coloring as on a chessboard, since at any move of the robot the parity of $x + y$ does not change. Now replace the moves $(x+1, y-1)$, $(x+1, y+1)$ with moves $(x+1, y)$, $(x+1, y+1)$ respectively. This can be done because we simply shifted the rows by some value, with the Robot walking on the same cells it walked on in the original board. Let's look at the even numbered (gray) cells: Changed field Then we'll go through the columns from left to right, keeping the minimum(by size) set of cells the Robot should be in. Then the transition to the next column will be as follows. Go through the cells from bottom to top, which contain the candy. For each cell, find the closest cell of our set (find the Robot) that is above the current cell. Then we change the square from the set to the current square. If there is no robot for the square in the array, then we need to increase the answer by $1$ and add the robot to our current square (you can think of it as adding the robot to the very top square in the column and getting all the candies that were above). In the picture, the red circles indicate the cells where we will put the robot as needed. The pink cells mean that this cell is contained in the set. The final asymptotic depends on the implementation (you can use a set as data structure, or you can use a vector with two pointers): $O(n*m*log(n))$ and $O(n*m)$, respectively.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n \nconst int N = 1e6 + 50;\nstring a[N];\n \nint n,m;\nint ans;\n \nvoid solve(int sum0) {\n    vector<int> v;\n    for (int sum = sum0, ad = 0, pref = 0; sum < n + m; sum += 2, ad++) {\n        vector<int> cur;\n        int li = max(0, sum - m + 1), ri = min(n - 1, sum);\n        if (li > ri) continue;\n \n        for (int i = li; i <= ri; i++) {\n            int j = sum - i;\n \n            if (a[i][j] == '1')\n                cur.emplace_back(i);\n        }\n \n        while (pref != sz(v) && v[pref] + ad > ri) {\n            pref++;\n        }\n        for (int i = pref; i < sz(v); i++) {\n            int new_val = v[i];\n            while (!cur.empty() && cur.back() - ad >= v[i]) {\n                new_val = max(new_val, cur.back() - ad);\n                cur.pop_back();\n            }\n            v[i] = new_val;\n        }\n        if (!cur.empty()) {\n            v.emplace_back(cur.back() - ad);\n            ans++;\n        }\n    }\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    forn(tt, t) {\n        cin >> n >> m;\n \n        forn(i, n) {\n            string s; \n            cin >> a[i];\n        }\n \n        ans = 0;\n        solve(0);\n        solve(1);\n        \n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "data structures",
      "graph matchings",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1612",
    "index": "A",
    "title": "Distance",
    "statement": "Let's denote the Manhattan distance between two points $p_1$ (with coordinates $(x_1, y_1)$) and $p_2$ (with coordinates $(x_2, y_2)$) as $d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|$. For example, the distance between two points with coordinates $(1, 3)$ and $(4, 2)$ is $|1 - 4| + |3 - 2| = 4$.\n\nYou are given two points, $A$ and $B$. The point $A$ has coordinates $(0, 0)$, the point $B$ has coordinates $(x, y)$.\n\nYour goal is to find a point $C$ such that:\n\n- both coordinates of $C$ are non-negative integers;\n- $d(A, C) = \\dfrac{d(A, B)}{2}$ (without any rounding);\n- $d(B, C) = \\dfrac{d(A, B)}{2}$ (without any rounding).\n\nFind any point $C$ that meets these constraints, or report that no such point exists.",
    "tutorial": "There is a solution in $O(1)$, but in fact, a solution that checks all points with $x$-coordinate from $0$ to $50$ and $y$-coordinate from $0$ to $50$ is fast enough. There's no need to check any other points, since $d(A, C) + d(B, C) = d(A, B)$ implies that point $C$ is on one of the shortest paths between $A$ and $B$.",
    "code": "t = int(input())\nfor i in range(t):\n    x, y = map(int, input().split())\n    xc = -1\n    yc = -1\n    for j in range(0, 51):\n        for k in range(0, 51):\n            if 2 * (j + k) == x + y and 2 * (abs(x - j) + abs(y - k)) == x + y:\n                xc, yc = j, k\n    print(xc, yc)",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1612",
    "index": "B",
    "title": "Special Permutation",
    "statement": "A permutation of length $n$ is an array $p=[p_1,p_2,\\dots, p_n]$ which contains every integer from $1$ to $n$ (inclusive) exactly once. For example, $p=[4, 2, 6, 5, 3, 1]$ is a permutation of length $6$.\n\nYou are given three integers $n$, $a$ and $b$, where $n$ is an even number. Print any permutation of length $n$ that the minimum among \\textbf{all its elements of the left half} equals $a$ and the maximum among \\textbf{all its elements of the right half} equals $b$. Print -1 if no such permutation exists.",
    "tutorial": "There are many different constructions that give the correct answer, if it exists. In my opinion, one of the most elegant is the following one. $a$ should always be present in the left half, and $b$ should be present in the right half, but the exact order of elements in each half doesn't matter. So, it will never be wrong to put $a$ in the first position, and $b$ in the second position. As for the remaining elements, we want elements of the left half to be as big as possible (since they shouldn't be less than $a$), and elements of the right half - as small as possible (since they shouldn't be greater than $b$). Let's put the elements $n$, $n - 1$, $n - 2$, ..., $1$ (excluding $a$ and $b$) on positions $2$, $3$, $4$, ..., $n-1$, respectively, so the elements in the left half are as big as possible, and the elements in the right half are as small as possible. After constructing a permutation according to these rules, we should check if it meets the constraints (and print it if it does).",
    "code": "t = int(input())\nfor i in range(t):\n    n, a, b = map(int, input().split())\n    p = [a]\n    for j in range(n, 0, -1):\n        if j != a and j != b:\n            p.append(j)\n    p.append(b)\n    if(len(p) == n and min(p[0:n//2]) == a and max(p[n//2:n]) == b):\n        print(*p)\n    else:\n        print(-1)",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1612",
    "index": "C",
    "title": "Chat Ban",
    "statement": "You are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something.\n\nMore precisely, you want to spam the emote triangle of size $k$. It consists of $2k-1$ messages. The first message consists of one emote, the second one — of two emotes, ..., the $k$-th one — of $k$ emotes, the $k+1$-th one — of $k-1$ emotes, ..., and the last one — of one emote.\n\nFor example, the emote triangle for $k=3$ consists of $5$ messages:\n\nOf course, most of the channels have auto moderation. Auto moderator of the current chat will ban you right after you spam at least $x$ emotes in succession (you can assume you are the only user in the chat). Now you are interested — how many messages will you write before getting banned? Or maybe you will not get banned at all (i.e. will write all $2k-1$ messages and complete your emote triangle successfully)? Note that if you get banned as a result of writing a message, this message is also counted.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "This is a pretty obvious binary search problem. If we get banned after $y$ messages, we also get banned after $y+1$, $y+2$ and so on messages (and vice versa, if we don't get banned after $y$ messages, we also don't get banned after $y-1$, $y-2$ and so on messages). For simplicity, let's split the problem into two parts: when we check if we're getting banned after $y$ messages, let's handle cases $y < k$ and $y \\ge k$ separately. Recall that the sum of the arithmetic progression consisting of integers $1$, $2$, ..., $y$ is $\\frac{y(y+1)}{2}$. Let it be $cnt(y)$. The first case is pretty simple: the number of emotes we send with $y$ messages when $y < k$ is $\\frac{y(y+1)}{2}$ which is $cnt(y)$. So we only need to check if $cnt(y) \\ge x$. The second case is a bit harder but still can be done using arithmetic progression formulas. Firstly, we send all messages for $y \\le k$ (the number of such messages is $cnt(k)$). Then, we need to add $(k - 1) + (k - 2) + \\ldots + (y - k)$ messages. This number equals to $cnt(k - 1) - cnt(2k - 1 - y)$ (i.e. we send all messages from $k-1$ to $1$ and subtract messages from $1$ to $2k - 1 - y$ from this amount). The final condition is $cnt(k) + cnt(k - 1) - cnt(2k - 1 - y) \\ge x$. Time complexity: $O(\\log{k})$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long get(int x) {\n    return x * 1ll * (x + 1) / 2;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int t;\n    cin >> t;\n    while (t--) {\n        int k;\n        long long x;\n        cin >> k >> x;\n        long long l = 1, r = 2 * k - 1;\n        long long res = 2 * k - 1;\n        bool over = false;\n        while (l <= r) {\n            int mid = (l + r) >> 1;\n            if (mid >= k) {\n                over = (get(k) + get(k - 1) - get(2 * k - 1 - mid) >= x);\n            } else {\n                over = (get(mid) >= x);\n            }\n            if (over) {\n                res = mid;\n                r = mid - 1;\n            } else {\n                l = mid + 1;\n            }\n        }\n        cout << res << endl;\n    }\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1612",
    "index": "D",
    "title": "X-Magic Pair",
    "statement": "You are given a pair of integers $(a, b)$ and an integer $x$.\n\nYou can change the pair in two different ways:\n\n- set (assign) $a := |a - b|$;\n- set (assign) $b := |a - b|$,\n\nwhere $|a - b|$ is the absolute difference between $a$ and $b$.The pair $(a, b)$ is called $x$-magic if $x$ is obtainable either as $a$ or as $b$ using only the given operations (i.e. the pair $(a, b)$ is $x$-magic if $a = x$ or $b = x$ after some number of operations applied). You can apply the operations any number of times (even zero).\n\nYour task is to find out if the pair $(a, b)$ is $x$-magic or not.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "This problem has a GCD-based solution. Firstly, lets' try to solve it naively. Always suppose that $a > b$. If this is not true, let's swap $a$ and $b$. Firstly, if $b > a - b$, let's do $b := a - b$. Okay, now let's subtract $b$ from $a$ until $b \\ge a - b$ again and repeat this algorithm till $a = 0$ or $b = 0$. If, after some step, we get $a = x$ or $b = x$, we are done, and the answer is YES. If $a = 0$ or $b = 0$, and we didn't get $x$ then the answer is NO. Okay, we can see that we always subtract the minimum possible $b$ from $a$ and trying to maintain this condition. It can be proven that this algorithm yields all possible integers that are obtainable by any sequence of the operations from the problem statement (either in $a$ or in $b$). Now we have to speed up this solution somehow. Obviously, most operations are redundant for us in this particular problem. The first thing is that we can skip all operations till $b$ becomes greater than $a - b$. The number of such operations is $\\lfloor\\frac{a - b}{2b}\\rfloor$. And the second thing is that we can skip all operations till we get $x$ in $a$. The number of such operations is $\\lfloor\\frac{a-x}{b}\\rfloor$. For simplicity, this part can be also written as $\\lfloor\\frac{a-x}{2b}\\rfloor$. This doesn't affect the time complexity much, but the formula for the final number of operations we can skip will be simpler. This number equals $cnt = max(1, \\lfloor\\frac{a-max(b, x)}{2b}\\rfloor)$ (in fact, we take the minimum between two values written above, because we don't want to skip any of these two cases). So, we can transform the pair $(a, b)$ to the pair $(a - b * cnt, b)$ and continue this algorithm. There are also simpler approaches using the same idea but in a cooler way. Time complexity: $O(\\log{a})$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool get(long long a, long long b, long long x) {\n    if (a == x || b == x) return true;\n    if (a < b) swap(a, b);\n    if (b > a - b) b = a - b;\n    if (x > max(a, b) || a == 0 || b == 0) return false;\n    long long cnt = max(1ll, (a - max(x, b)) / (2 * b));\n    return get(a - b * cnt, b, x);\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int t;\n    cin >> t;\n    while (t--) {\n        long long a, b, x;\n        cin >> a >> b >> x;\n        if (get(a, b, x)) {\n            cout << \"YES\" << endl;\n        } else {\n            cout << \"NO\" << endl;\n        }\n    }\n    \n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1612",
    "index": "E",
    "title": "Messages",
    "statement": "Monocarp is a tutor of a group of $n$ students. He communicates with them using a conference in a popular messenger.\n\nToday was a busy day for Monocarp — he was asked to forward a lot of posts and announcements to his group, that's why he had to write a very large number of messages in the conference. Monocarp knows the students in the group he is tutoring quite well, so he understands which message should each student read: Monocarp wants the student $i$ to read the message $m_i$.\n\nOf course, no one's going to read all the messages in the conference. That's why Monocarp decided to pin some of them. Monocarp can pin any number of messages, and if he wants anyone to read some message, he should pin it — otherwise \\textbf{it will definitely be skipped by everyone}.\n\nUnfortunately, even if a message is pinned, some students may skip it anyway. For each student $i$, Monocarp knows that they will read at most $k_i$ messages. Suppose Monocarp pins $t$ messages; if $t \\le k_i$, then the $i$-th student will read all the pinned messages; but if $t > k_i$, the $i$-th student will choose exactly $k_i$ random pinned messages (all possible subsets of pinned messages of size $k_i$ are equiprobable) and read only the chosen messages.\n\nMonocarp wants to maximize the expected number of students that read their respective messages (i.e. the number of such indices $i$ that student $i$ reads the message $m_i$). Help him to choose how many (and which) messages should he pin!",
    "tutorial": "First of all, let's rewrite the answer using expectation linearity. The expected number of students who read their respective messages is equal to $F_1 + F_2 + \\dots + F_n$, where $F_i$ is a random value which is $1$ if the $i$-th student reads the message $m_i$, and $0$ if the $i$-th student doesn't do it. Let's analyze the expected value of $F_i$. Suppose Monocarp pins the messages $c_1, c_2, \\dots, c_t$. There are three cases: if $m_i \\notin [c_1, c_2, \\dots, c_t]$, then the $i$-th student won't read the message $m_i$, so $F_i = 0$; if $m_i \\in [c_1, c_2, \\dots, c_t]$ and $t \\le k_i$, then the $i$-th student will definitely read the message $m_i$, so $F_i = 1$; if $m_i \\in [c_1, c_2, \\dots, c_t]$ and $t > k_i$, then $F_i = \\frac{k_i}{t}$. If we iterate on the number of messages we pin $t$, we can calculate the sum of $F_i$ for each message (considering that we pin it), sort all of the messages and pick $t$ best of them. So, we have a solution working in $O(n^2 \\log n)$. The only thing we need to improve this solution sufficiently is the fact that we don't have to consider the case $t > 20$. Since every $k_i$ is not greater than $20$, the sum of $F_i$ for a message in the case $t = 20$ is the same as this sum of $F_i$ in the case $t = 21$, but multiplied by the coefficient $\\frac{20}{21}$ - and we pick $21$ best values, their sum multiplied by $\\frac{20}{21}$ is not greater than the sum of $20$ best values. The same holds for $t = 22$ and greater.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int N = 200043;\nconst int K = 20;\nvector<int> idx[N];\nint m[N], k[N];\n\nbool frac_greater(pair<int, int> a, pair<int, int> b)\n{\n    return a.first * b.second > a.second * b.first;\n}\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++)\n    {\n        scanf(\"%d %d\", &m[i], &k[i]);\n        idx[m[i]].push_back(i);\n    }\n\n    vector<int> cert;\n    pair<int, int> ans = {0, 1};\n    for(int i = 1; i <= K; i++)\n    {\n        vector<int> score(N);\n        for(int j = 0; j < n; j++)\n            score[m[j]] += min(i, k[j]);\n        vector<pair<int, int>> aux;\n        for(int j = 0; j < N; j++)\n            aux.push_back(make_pair(score[j], j));\n        sort(aux.rbegin(), aux.rend());\n        pair<int, int> cur_ans = {0, i};\n        vector<int> cur_cert;\n        for(int j = 0; j < i; j++)\n        {\n            cur_ans.first += aux[j].first;\n            cur_cert.push_back(aux[j].second);\n        }\n        if(frac_greater(cur_ans, ans))\n        {\n            ans = cur_ans;\n            cert = cur_cert;\n        }\n    }\n    cout << cert.size() << endl;\n    shuffle(cert.begin(), cert.end(), mt19937(time(NULL)));\n    for(auto x : cert) cout << x << \" \";\n    cout << endl;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "probabilities",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1612",
    "index": "F",
    "title": "Armor and Weapons",
    "statement": "Monocarp plays a computer game. There are $n$ different sets of armor and $m$ different weapons in this game. If a character equips the $i$-th set of armor and wields the $j$-th weapon, their power is usually equal to $i + j$; but some combinations of armor and weapons synergize well. Formally, there is a list of $q$ ordered pairs, and if the pair $(i, j)$ belongs to this list, the power of the character equipped with the $i$-th set of armor and wielding the $j$-th weapon is not $i + j$, but $i + j + 1$.\n\nInitially, Monocarp's character has got only the $1$-st armor set and the $1$-st weapon. Monocarp can obtain a new weapon or a new set of armor in one hour. If he wants to obtain the $k$-th armor set or the $k$-th weapon, he must possess a combination of an armor set and a weapon that gets his power to $k$ \\textbf{or greater}. Of course, after Monocarp obtains a weapon or an armor set, he can use it to obtain new armor sets or weapons, but he can go with any of the older armor sets and/or weapons as well.\n\nMonocarp wants to obtain the $n$-th armor set \\textbf{and} the $m$-th weapon. What is the minimum number of hours he has to spend on it?",
    "tutorial": "Among two armor sets, one with the greater index is always better. The same can be said about two different weapons. So, it is always optimal to use and obtain the best possible weapon or armor. This observation allows us to model this problem with dynamic programming or shortest paths: let $dp_{x,y}$ be the minimum time in which Monocarp can obtain the armor $x$ and the weapon $y$; and in each transition, we either get the best weapon we can or the best armor we can. Similarly, we can build a graph where the vertices represent these pairs $(x, y)$, and the edges represent getting the best possible weapon/armor, and find the shortest path from $(1, 1)$ to $(n, m)$ using BFS. Unfortunately, it is $O(nm)$. But we can modify the BFS in the following fashion: let's analyze each layer of BFS (a layer is a set of vertices with the same distance from the origin). In each layer, there might be some redundant vertices: if two vertices $(x, y)$ and $(x', y')$ belong to the same layer, $x' \\le x$ and $y' \\le y$, then the vertex $(x', y')$ is redundant. If we filter each layer, removing all redundant vertices from it and continuing BFS only from non-redundant ones, the solution will be fast enough. To prove it, let's analyze the constraints on the answer. Suppose $n \\ge m$. The answer can be bounded as $O(\\log m + \\frac{n}{m})$, since we can reach the pair $(m, m)$ in $O(\\log m)$ steps using something similar to Fibonacci sequence building, and then go from $(m, m)$ to $(n, m)$ in $\\frac{n}{m}$ steps. And the number of non-redundant states on each layer is not greater than $m$ (because, of two states with the same weapon or the same armor set, at least one is redundant). So, if we don't continue BFS from redundant vertices, it will visit at most $O(m \\cdot (\\log m + \\frac{n}{m})) = O(m \\log m + n)$ vertices. There might be another logarithm in the asymptotic complexity of the solution, if you use something like a set to store all combinations that synergize well, but this implementation is still fast enough.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\n\n#define x first\n#define y second\n\ntypedef pair<int, int> comb;\n\ncomb norm(const comb& a)\n{\n    return make_pair(min(a.x, n), min(a.y, m));\n}\n\nbool good(const comb& a)\n{\n    return a.x == n || a.y == m;\n}\n\nbool comp(const comb& a, const comb& b)\n{\n    if(a.x != b.x)\n        return a.x > b.x;\n    return a.y > b.y;\n}\n\nint main()\n{\n    scanf(\"%d %d\", &n, &m);\n    int v;\n    scanf(\"%d\", &v);\n    set<comb> s;\n    for(int i = 0; i < v; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        s.insert(make_pair(x, y));\n    }\n    int steps = 0;\n    vector<comb> cur;\n    cur.push_back(make_pair(1, 1));\n    while(true)\n    {\n        if(cur[0] == make_pair(n, m))\n            break;\n        vector<comb> ncur;\n        for(auto x : cur)\n        {\n            int sum = x.x + x.y;\n            if(s.count(x))\n                sum++;\n            comb z = x;\n            z.x = sum;\n            ncur.push_back(norm(z));\n            z = x;\n            z.y = sum;\n            ncur.push_back(norm(z));\n        }\n        sort(ncur.begin(), ncur.end(), comp);\n        int mx = 0;\n        vector<comb> ncur2;\n        for(auto x : ncur)\n        {\n            if(x.y <= mx) continue;\n            mx = max(mx, x.y);\n            ncur2.push_back(x);\n        }\n        cur = ncur2;\n        steps++;\n    }\n    printf(\"%d\\n\", steps);\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "shortest paths"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1612",
    "index": "G",
    "title": "Max Sum Array",
    "statement": "You are given an array $c = [c_1, c_2, \\dots, c_m]$. An array $a = [a_1, a_2, \\dots, a_n]$ is constructed in such a way that it consists of integers $1, 2, \\dots, m$, and for each $i \\in [1,m]$, there are exactly $c_i$ occurrences of integer $i$ in $a$. So, the number of elements in $a$ is exactly $\\sum\\limits_{i=1}^{m} c_i$.\n\nLet's define for such array $a$ the value $f(a)$ as $$f(a) = \\sum_{\\substack{1 \\le i < j \\le n\\\\ a_i = a_j}}{j - i}.$$\n\nIn other words, $f(a)$ is the total sum of distances between all pairs of equal elements.\n\nYour task is to calculate the maximum possible value of $f(a)$ and the number of arrays yielding the maximum possible value of $f(a)$. Two arrays are considered different, if elements at some position differ.",
    "tutorial": "Firstly, let's prove that at first and last positions of $a$ the most frequent elements should be placed (but not necessary the same). WLOG, let's prove that $c_{a_1} \\ge c_{a_i}$ for any $i > 1$. By contradiction, let's $p$ be the smallest index such that $c_{a_1} < c_{a_p}$. What happens if we swap them? Since $p$ is the first such index then there are no $a_i = a_p$ for $i < p$, so \"contribution\" of $a_p$ will increase by exactly $inc = (c_{a_p} - 1) \\cdot (p - 1)$. From the other side, contribution of $a_1$ consists of two parts: pairs with elements from $(p, n]$ and from $(1, p)$. For all elements from $(p, n]$ decrease will be equal to $dec_1 = c_{a_1}[p + 1, n] \\cdot (p - 1)$ and from elements in $(1, p)$ $dec_2 \\le c_{a_1}[2, p - 1] \\cdot (p - 1)$. So, the total decrease $dec$ after moving $a_1$ to position $p$ equal to $dec = dec_1 + dec_2 \\le (c_{a_1} - 1) \\cdot (p - 1)$. The total difference in such case is equal to $inc - dec \\ge (p - 1) \\cdot (c_{a_p} - c_{a_1}) > 0$. So, our placement is not optimal - contradiction. Let's suggest that there is exactly one $e$ with maximum $c_{e}$. According to what we proved earlier, both $a_1$ and $a_n$ must be equal to $e$. Contribution of the first and last elements will be equal to: $(n - 1)$ for pair $(1, n)$ and for each element $i$ ($1 < i < n$) with $a_i = e$ we add $(i - 1) + (n - i) = (n - 1)$ for pairs $(1, i)$ and $(i, n)$. So, the total contribution of $a_1 = a_n = e$ is equal to $(n - 1) \\cdot (c_e - 1)$. Note that this contribution is independent of positions of other $e$ in the array $a$, so that's why we can cut first and last elements of $a$ and solve the task recursively. Unfortunately, in the initial task we may have several $e_1, e_2, \\dots, e_k$ with maximum $c_{e_i}$. But we in the similar manner can prove that the first (and last) $k$ elements $a_1, \\dots, a_k$ should be some permutation of $e_1, \\dots e_k$. Now, let's prove that any permutation of first and last $k$ elements is optimal. Suppose, positions of $e_i$ are $l_i$ ($1 \\le l_i \\le k$) and $r_i$ ($n - k + 1 \\le r_i \\le n$). Then the contribution of $e_i$ is equal to $(c_{e_i} - 1) \\cdot (r_i - l_i)$. The total contribution of all $e_i$ is $\\sum\\limits_{i=1}^{k}{(c_{e_i} - 1) \\cdot (r_i - l_i)}$ $=$ $(c_{e_1} - 1) (\\sum\\limits_{i=1}^{k}r_i - \\sum\\limits_{i=1}^{k}{l_i})$ $=$ $(c_{e_1} - 1)((n - k)k + \\frac{k(k + 1)}{2} - \\frac{k(k+1)}{2}) = (c_{e_1} - 1) k (n - k)$. This contribution doesn't depend on chosen $l_i$ and $r_i$, so any permutation of first $k$ elements and any permutation of last $k$ elements give optimal answer. As a result, the algorithm is following: Find all maximums $e_1, \\dots, e_k$ in $c$. If $c_{e_1} = 1$ then any permutation of remaining elements has $f(a) = 0$ (there are $k!$ such permutations). Otherwise, add $(c_{e_1} - 1) k (n - k)$ to the total balance, and multiply the number of variants by $(k!)^2$. Cut prefix and suffix by making $c_{e_i} = c_{e_i} - 2$ for each $e_i$ (obviously, $n = n - 2k$) and repeat the whole process. We can implement the algorithm fast if we keep the number of $c_i$ equal to each $val$ from $0$ to $C$ ($C \\le 10^6$). So the total complexity is $O(n + C)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n    return out << \"(\" << p.x << \" \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n    fore(i, 0, sz(v)) {\n        if(i) out << \" \";\n        out << v[i];\n    }\n    return out;\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nconst int MOD = int(1e9) + 7;\n\nint norm(int a) {\n    while (a >= MOD)\n        a -= MOD;\n    while (a < 0)\n        a += MOD;\n    return a;\n}\nint mul(int a, int b) {\n    return int(a * 1ll * b % MOD);\n}\n\nconst int MX = int(1e6) + 55;\nint n;\nli total;\nint cnt[MX];\n\ninline bool read() {\n    if(!(cin >> n))\n        return false;\n    total = 0;\n    fore (i, 0, n) {\n        int k; cin >> k;\n        cnt[k]++;\n        total += k;\n    }\n    return true;\n}\n\nint fact[MX];\n\ninline void solve() {\n    fact[0] = 1;\n    fore (i, 1, MX)\n        fact[i] = mul(fact[i - 1], i);\n    \n    int ansSum = 0;\n    int ansCnt = 1;\n    \n    for (int lvl = MX - 1; lvl > 1; lvl--) {\n        ansCnt = mul(ansCnt, mul(fact[cnt[lvl]], fact[cnt[lvl]]));\n        \n        //each color gives (lvl - 1) * (r_i - l_i)\n        // or (lvl - 1) * (sum r_i - sum l_i)\n        // l_i is permutation of [0,..., cnt[lvl]), so sum l_i = (cnt[lvl] - 1) * cnt[lvl] / 2\n        // r_i is permutation of [total - cnt[lvl],..., total), so sum = cnt[lvl] * (total - cnt[lvl]) + (cnt[lvl] - 1) * cnt[lvl] / 2\n        \n        ansSum = norm(ansSum + mul(mul(lvl - 1, cnt[lvl]), (total - cnt[lvl]) % MOD));\n        \n        total -= 2 * cnt[lvl];\n        cnt[lvl - 2] += cnt[lvl];\n    }\n    \n    ansCnt = mul(ansCnt, fact[cnt[1]]);\n    \n    cout << ansSum << \" \" << ansCnt << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1613",
    "index": "A",
    "title": "Long Comparison",
    "statement": "Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer $x$ with $p$ zeros appended to its end.\n\nNow Monocarp asks you to compare these two numbers. Can you help him?",
    "tutorial": "First, let's say that appending the number with $p$ zeros is the same as multiplying it by $10^p$. The given numbers are so large that they can't fit into any reasonable integer type. Even if you use a language with unlimited length integers (python, for example) or store the numbers in strings, you should still face the time limit issue. So let's learn to shrink the numbers a bit. Note that the result of the comparison of two numbers doesn't change if you divide both numbers by the same positive number. So we can keep dividing both numbers by $10$ until one of them is not divisible anymore. Let's also ignore the trailing zeros in $x_1$ and $x_2$ and leave them as is. If the first number is appended with $p_1$ zeros and the second numbers is appended with $p_2$ zeros, we can subtract $min(p_1, p_2)$ from both values, effectively dividing both numbers by $10^{min(p_1, p_2)}$. This way, one of the numbers becomes short enough to fit into an integer type (because it has $p=0$ and $x$ is only up to $10^6$). The other number might still be large enough. However, if it's really large, we can instantly say that it's larger than another one. Say, if its $p$ is at least $7$. This number it at least $10^7$ and the other number is at most $10^6$. Otherwise, we can calculate this number as well and compare the values normally. Overall complexity: $O(1)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main(){\n\tint t;\n\tcin >> t;\n\twhile (t--){\n\t\tlong long x1, x2;\n\t\tint p1, p2;\n\t\tcin >> x1 >> p1 >> x2 >> p2;\n\t\tint mn = min(p1, p2);\n\t\tp1 -= mn;\n\t\tp2 -= mn;\n\t\tif (p1 >= 7)\n\t\t\tcout << \">\" << endl;\n\t\telse if (p2 >= 7)\n\t\t\tcout << \"<\" << endl;\n\t\telse{\n\t\t\tfor (int i = 0; i < p1; ++i) x1 *= 10;\n\t\t\tfor (int i = 0; i < p2; ++i) x2 *= 10;\n\t\t\tif (x1 < x2)\n\t\t\t\tcout << \"<\" << endl;\n\t\t\telse if (x1 > x2)\n\t\t\t\tcout << \">\" << endl;\n\t\t\telse\n\t\t\t\tcout << \"=\" << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1613",
    "index": "B",
    "title": "Absent Remainder",
    "statement": "You are given a sequence $a_1, a_2, \\dots, a_n$ consisting of $n$ pairwise distinct positive integers.\n\nFind $\\left\\lfloor \\frac n 2 \\right\\rfloor$ different pairs of integers $x$ and $y$ such that:\n\n- $x \\neq y$;\n- $x$ and $y$ appear in $a$;\n- $x~mod~y$ doesn't appear in $a$.\n\nNote that some $x$ or $y$ can belong to multiple pairs.\n\n$\\lfloor x \\rfloor$ denotes the floor function — the largest integer less than or equal to $x$. $x~mod~y$ denotes the remainder from dividing $x$ by $y$.\n\nIf there are multiple solutions, print any of them. It can be shown that at least one solution always exists.",
    "tutorial": "There is one important observation: $x~mod~y<y$. Thus, you can obtain at least $n-1$ pair by choosing $y$ as the minimum number in the sequence and $x$ as anything else. $n-1 \\ge \\left\\lfloor \\frac n 2 \\right\\rfloor$ for any positive $n$. Overall complexity: $O(n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n    int mn = *min_element(a.begin(), a.end());\n    for (int i = 0, k = 0; k < n / 2; ++i) if (a[i] != mn) {\n      cout << a[i] << ' ' << mn << '\\n';\n      k += 1;\n    }\n  }\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1613",
    "index": "C",
    "title": "Poisoned Dagger",
    "statement": "Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $100^{500}$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $i$-th attack is performed at the beginning of the $a_i$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $1$ damage during each of the next $k$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).\n\nFor example, suppose $k = 4$, and Monocarp stabs the dragon during the seconds $2$, $4$ and $10$. Then the poison effect is applied at the start of the $2$-nd second and deals $1$ damage during the $2$-nd and $3$-rd seconds; then, at the beginning of the $4$-th second, the poison effect is reapplied, so it deals exactly $1$ damage during the seconds $4$, $5$, $6$ and $7$; then, during the $10$-th second, the poison effect is applied again, and it deals $1$ damage during the seconds $10$, $11$, $12$ and $13$. In total, the dragon receives $10$ damage.\n\nMonocarp knows that the dragon has $h$ hit points, and if he deals at least $h$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $k$ (the number of seconds the poison effect lasts) that is enough to deal at least $h$ damage to the dragon.",
    "tutorial": "Let's find out the total damage for a fixed value of $k$. Since the effect of the poison from the $i$-th attack deals damage $\\min(k, a_{i+1} - a_i)$ seconds for $i < n$ and $k$ seconds for $i = n$, then the total damage is $k +\\sum\\limits_{i=1}^{n-1}{\\min(k, a_{i+1} - a_i)}$. We can see that the higher the value of $k$, the greater the total sum. So we can do a binary search on $k$ and find the minimum value when the sum is greater than or equal to $h$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing li = long long;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    li h;\n    cin >> n >> h;\n    vector<li> a(n);\n    for (li &x : a) cin >> x;\n    li l = 1, r = 1e18;\n    while (l <= r) {\n      li m = (l + r) / 2;\n      li sum = m;\n      for (int i = 0; i < n - 1; ++i) \n        sum += min(m, a[i + 1] - a[i]);\n      if (sum < h) l = m + 1;\n      else r = m - 1;\n    }\n    cout << r + 1 << '\\n';\n  }\n}",
    "tags": [
      "binary search"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1613",
    "index": "D",
    "title": "MEX Sequences",
    "statement": "Let's call a sequence of integers $x_1, x_2, \\dots, x_k$ MEX-correct if for all $i$ ($1 \\le i \\le k$) $|x_i - \\operatorname{MEX}(x_1, x_2, \\dots, x_i)| \\le 1$ holds. Where $\\operatorname{MEX}(x_1, \\dots, x_k)$ is the minimum non-negative integer that doesn't belong to the set $x_1, \\dots, x_k$. For example, $\\operatorname{MEX}(1, 0, 1, 3) = 2$ and $\\operatorname{MEX}(2, 1, 5) = 0$.\n\nYou are given an array $a$ consisting of $n$ non-negative integers. Calculate the number of non-empty MEX-correct subsequences of a given array. The number of subsequences can be very large, so print it modulo $998244353$.\n\nNote: a subsequence of an array $a$ is a sequence $[a_{i_1}, a_{i_2}, \\dots, a_{i_m}]$ meeting the constraints $1 \\le i_1 < i_2 < \\dots < i_m \\le n$. If two different ways to choose the sequence of indices $[i_1, i_2, \\dots, i_m]$ yield the same subsequence, the resulting subsequence should be counted twice (i. e. two subsequences are different if their sequences of indices $[i_1, i_2, \\dots, i_m]$ are not the same).",
    "tutorial": "Let's understand what MEX-correct sequences look like. It turns out there are only two types: $[\\underline{0, \\dots, 0}, \\underline{1, \\dots, 1}, \\dots, \\underline{x-1, \\dots, x-1}, \\underline{x, \\dots, x}]$ and $[\\underline{0, \\dots, 0}, \\underline{1, \\dots, 1}, \\dots, \\underline{x-1, \\dots, x-1}, \\underline{x+1, \\dots, x+1}, \\underline{x-1, \\dots, x-1}, \\underline{x+1, \\dots}]$. For example, the sequences $[0, 0, 1, 1, 1, 2, 3, 3]$ and the empty sequence are MEX-correct sequences of the first type, and $[1, 1, 1, 1]$ and $[0, 0, 1, 2, 4, 4, 2, 4, 2, 2]$ of the second one. Let's calculate the dynamic programming $\\mathrm{dp1}_{i, j}$ - the number of MEX-correct subsequences of the first type on the prefix of length $i$ with $\\operatorname{MEX}$ equal to $j$ and similarly $\\mathrm{dp2}_{i, j}$ - the number of MEX-correct subsequences of the second type on the prefix of length $i$ with $\\operatorname{MEX}$ equal to $j$. Let's look at the transitions in these dps, and show that there are no other MEX-correct sequences at the same time. Let the current state be $\\mathrm{dp1}_{i, j}$, and we are trying to add an element equal to $x$: if $x < j - 1$, then such an element cannot be added; if $x = j - 1$, then the value of $\\operatorname{MEX}$ will not change and the sequence is still of the first type, which means we have a transition to $\\mathrm{dp1}_{i + 1, j}$; if $x = j$, then the value of $\\operatorname{MEX}$ will increase by $1$, but it will still be of the first type, which means we have a transition to $\\mathrm{dp1}_{i + 1, j + 1}$ if $x = j + 1$, then the value of $\\operatorname{MEX}$ will not change, but the sequence will become of the second type, which means we have a transition to $\\mathrm{dp2}_{i + 1, j}$; if $x > j + 1$, then such an element cannot be added. Let the current state be $\\mathrm{dp2}_{i, j}$, and we are trying to add an element equal to $x$: if $x < j - 1$, then such an element cannot be added; if $x = j - 1$, then the value of $\\operatorname{MEX}$ will not change and the sequence is still of the second type, which means we have a transition to $\\mathrm{dp2}_{i + 1, j}$; if $x = j$, then such an element cannot be added, because $\\operatorname{MEX}$ will increase by $2$, which means the absolute difference between $\\operatorname{MEX}$ and $x$ is greater than $1$; if $x = j + 1$, then the value of $\\operatorname{MEX}$ will not change and the sequence is still of the second type, which means we have a transition to $\\mathrm{dp2}_{i + 1, j}$; if $x > j + 1$, then such an element cannot be added. Thus, we considered all possible transitions (adding a new element to the already MEX-correct sequences) and made sure that there are only two types. While the solution itself works in $O(n)$ time (because each element $x$ has $O(1)$ possible transitions in the dps), it uses $O(n^2)$ memory, which does not allow us to write that solution as is. However, note that $\\mathrm{dp1}_i$ and $\\mathrm{dp1}_{i + 1}$ (similarly for $\\mathrm{dp2}$) differ in only a few positions (in those that the element $a_i$ allowed us to make), which means we can store only one-dimensional arrays, $\\mathrm{dp1}_j$ and $\\mathrm{dp2}_j$. Thus, the final complexity of the solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n  return x;\n}\n\nint main() {\n  int t;\n  scanf(\"%d\", &t);\n  while (t--) {\n    int n;\n    scanf(\"%d\", &n);\n    vector<int> dp1(n + 2), dp2(n + 2);\n    dp1[0] = 1;\n    while (n--) {\n      int x;\n      scanf(\"%d\", &x);\n      dp1[x + 1] = add(dp1[x + 1], dp1[x + 1]);\n      dp1[x + 1] = add(dp1[x + 1], dp1[x]);\n      if (x > 0) dp2[x - 1] = add(dp2[x - 1], dp2[x - 1]);\n      if (x > 0) dp2[x - 1] = add(dp2[x - 1], dp1[x - 1]);\n      dp2[x + 1] = add(dp2[x + 1], dp2[x + 1]);\n    }\n    int ans = 0;\n    for (int x : dp1) ans = add(ans, x);\n    for (int x : dp2) ans = add(ans, x);\n    printf(\"%d\\n\", add(ans, MOD - 1));\n  }\n} \n",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1613",
    "index": "E",
    "title": "Crazy Robot",
    "statement": "There is a grid, consisting of $n$ rows and $m$ columns. Each cell of the grid is either free or blocked. One of the free cells contains a lab. All the cells beyond the borders of the grid are also blocked.\n\nA crazy robot has escaped from this lab. It is currently in some free cell of the grid. You can send one of the following commands to the robot: \"move right\", \"move down\", \"move left\" or \"move up\". Each command means moving to a neighbouring cell in the corresponding direction.\n\nHowever, as the robot is crazy, it will do anything except following the command. Upon receiving a command, it will choose a direction such that it differs from the one in command and the cell in that direction is not blocked. If there is such a direction, then it will move to a neighbouring cell in that direction. Otherwise, it will do nothing.\n\nWe want to get the robot to the lab to get it fixed. For each free cell, determine if the robot can be forced to reach the lab starting in this cell. That is, after each step of the robot a command can be sent to a robot such that no matter what different directions the robot chooses, it will end up in a lab.",
    "tutorial": "One way to think about this problem is in game theory terms. Imagine a following game. Two players alternate moves. The first players chooses a direction. The second player chooses a different direction and moves a robot there. The game ends when the robot reaches the lab, and the first player wins. Otherwise, it's a draw. What's the outcome of the game if both players play optimally (as in the first player tries to win, the second player tries to draw)? Does it sound easier? Well, it sure does if you ever dealt with solving games on arbitrary graphs. You can skim through this article if that's unfamiliar to you. The state of the game is a pair $(\\mathit{cell}, \\mathit{direction})$. If a direction is not chosen (denote it with $-1$), it's the first player's move. Otherwise, it's the second player's move. You can even implement it as is. Or you can adjust a part of this algorithm for this particular problem. Initially, all the states are drawing, only the state $(\\mathit{lab}, -1)$ is winning. What we basically need is a way to determine if a state is winning or not. From game theory, we can tell that the state is winning if there's a transition from it to a losing state. The state is losing if all the transitions from it lead to winning states. So $(\\mathit{cell}, -1)$ is winning if any of $(\\mathit{cell}, \\mathit{direction} \\neq -1)$ are losing. Promote that one step further. The state is winning if there exists such a direction that all neighbouring free cells except in this direction are winning states. Rephrase it. The state is winning if it has at least one winning state neighbour and no more than one non-winning state neighbour. Let's store the number of non-winning neighbouring states for each cell. Initially, it's the number of neighbouring free cells. If some state becomes marked as winning, decrease the value for each of its neighbours by $1$. If some state's value reaches $0$ or $1$ after this operation, mark it as winning. Since what this does is basically a traversal of a grid, this can be done with a DFS/BFS, starting from the lab. Overall complexity: $O(nm)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct cell{\n\tint x, y;\n};\n\nint dx[] = {-1, 0, 1, 0};\nint dy[] = {0, 1, 0, -1};\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--){\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tvector<string> s(n);\n\t\tint lx = -1, ly = -1;\n\t\tforn(i, n){\n\t\t\tcin >> s[i];\n\t\t\tforn(j, m) if (s[i][j] == 'L'){\n\t\t\t\tlx = i;\n\t\t\t\tly = j;\n\t\t\t}\n\t\t}\n\t\tauto in = [&](int x, int y){\n\t\t\treturn 0 <= x && x < n && 0 <= y && y < m;\n\t\t};\n\t\tvector<vector<int>> d(n, vector<int>(m, 0));\n\t\tforn(x, n) forn(y, m) if (s[x][y] == '.'){\n\t\t\tforn(i, 4){\n\t\t\t\tint nx = x + dx[i];\n\t\t\t\tint ny = y + dy[i];\n\t\t\t\td[x][y] += in(nx, ny) && s[nx][ny] != '#';\n\t\t\t}\n\t\t}\n\t\tqueue<cell> q;\n\t\tvector<vector<char>> used(n, vector<char>(m, 0));\n\t\tq.push({lx, ly});\n\t\tused[lx][ly] = true;\n\t\twhile (!q.empty()){\n\t\t\tint x = q.front().x;\n\t\t\tint y = q.front().y;\n\t\t\tq.pop();\n\t\t\tforn(i, 4){\n\t\t\t\tint nx = x + dx[i];\n\t\t\t\tint ny = y + dy[i];\n\t\t\t\tif (!in(nx, ny) || s[nx][ny] == '#' || used[nx][ny]) continue;\n\t\t\t\t--d[nx][ny];\n\t\t\t\tif (d[nx][ny] <= 1){\n\t\t\t\t\tused[nx][ny] = true;\n\t\t\t\t\tq.push({nx, ny});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tforn(i, n){\n\t\t\tforn(j, m) if (s[i][j] == '.' && used[i][j])\n\t\t\t\ts[i][j] = '+';\n\t\t\tcout << s[i] << \"\\n\";\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1613",
    "index": "F",
    "title": "Tree Coloring",
    "statement": "You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is the vertex $1$.\n\nYou have to color all vertices of the tree into $n$ colors (also numbered from $1$ to $n$) so that there is exactly one vertex for each color. Let $c_i$ be the color of vertex $i$, and $p_i$ be the parent of vertex $i$ in the rooted tree. The coloring is considered beautiful if there is no vertex $k$ ($k > 1$) such that $c_k = c_{p_k} - 1$, i. e. no vertex such that its color is less than the color of its parent by \\textbf{exactly $1$}.\n\nCalculate the number of beautiful colorings, and print it modulo $998244353$.",
    "tutorial": "When a problem asks us to calculate the number of combinatorial objects that meet some constraints, we can sometimes use inclusion-exclusion formula. Let's try to apply it in this problem. We could use $n-1$ constraints that should not be violated. The $i$-th constraint is formulated as follows: $c_i \\ne c_{p_i} - 1$ (there will be a constraint of this type for each $i \\in [2, n]$). Suppose we violated $k$ of these constraints (and have chosen which $k$ constraints to violate), then the number of colorings that meet these violations is $(n-k)!$ (for $k$ vertices, the colors on them depend on some other independent vertices, so we can assign only colors for independent vertices). So, the answer can be calculated as follows: $\\sum\\limits_{k=0}^{n-1} (-1)^k f(k) (n-k)!$ where $f(k)$ is the number of ways to choose $k$ constraints to violate. One initial guess how to calculate $f(k)$ is that $f(k) = {{n-1}\\choose{k}}$, as it would be calculated in other, more usual inclusion-exclusion problems. Unfortunately, in this problem, the constraints we violate are not independent. For example, if a vertex has several sons, we can violate the constraint only on at most one edge leading from a vertex to its son simultaneously, we cannot violate two or more such constraints. Let's take care of this issue as follows: we can write a dynamic programming of the form $dp_{i, j}$ is the number of ways to process $i$ first vertices of the tree and choose exactly $j$ edges leading from these nodes to their sons so that no vertex has more than one edge leading to its sons chosen. Then, $dp_{n, k}$ is exactly the number of ways to choose $k$ edges in the tree so that no vertex has more than one chosen edge leading to its sons, and that will be equal to $f(k)$. We can calculate this dynamic programming in a knapsack fashion in $O(n^2)$, but it is too slow. Instead, let's optimize this knapsack DP with FFT: for each vertex $i$, introduce a polynomial $1 + d_i \\cdot x$, where $d_i$ is the number of children of the vertex $i$. Coefficients of this polynomial for the first vertex are the values of $dp_{1,k}$; coefficients of the product of this polynomial with the polynomial for the second vertex are the values of $dp_{2,k}$, and so on; to obtain the values of $dp_{n,k}$, we have to multiply all these polynomials, and using FFT + divide-and-conquer, we can do it in $O(n \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n#define fore(i, l, r) for (int i = int(l); i < int(r); ++i)\n#define sz(a) int((a).size())\n\nconst int MOD = 998244353;\n\nstruct Mint\n{\n  int val;\n\n  bool operator==(const Mint& other)\n  {\n    return val == other.val;\n  }\n\n  Mint operator+(const Mint& other)\n  {\n    int res = val + other.val;\n    while(res >= MOD) res -= MOD;\n    while(res < 0) res += MOD;\n    return Mint(res);\n  }\n\n  Mint operator-(const Mint& other)\n  {\n    int res = val - other.val;\n    while(res >= MOD) res -= MOD;\n    while(res < 0) res += MOD;\n    return Mint(res);  \n  }\n\n  Mint operator*(const Mint& other)\n  {\n    return Mint((val * 1ll * other.val) % MOD);\n  }\n\n  Mint pow(int y)\n  {\n    Mint z(1);\n    Mint x(val);\n    while(y > 0)\n    {\n      if(y % 2 == 1) z = z * x;\n      x = x * x;\n      y /= 2;\n    }\n    return z;\n  }\n\n  Mint operator/(const Mint& other)\n  {\n    return Mint(val) * Mint(other.val).pow(MOD - 2);\n  }\n\n  Mint() {\n      val = 0;\n  };\n  Mint(int x)\n  {\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    val = x;\n  };\n};\n\nostream& operator<<(ostream& out, const Mint& x)\n{\n  return out << x.val;\n}\n\nconst int g = 3;\nconst int LOGN = 19;\n\nvector<Mint> w[LOGN];\nvector<int> rv[LOGN];\n\nvoid prepare() {\n  Mint wb = Mint(g).pow((MOD - 1) / (1 << LOGN));\n  forn(st, LOGN - 1) {\n    w[st].assign(1 << st, 1);\n    Mint bw = wb.pow(1 << (LOGN - st - 1));\n    Mint cw = 1;\n    forn(k, 1 << st) {\n      w[st][k] = cw;\n      cw = cw * bw;\n    }\n  }\n  forn(st, LOGN) {\n    rv[st].assign(1 << st, 0);\n    if (st == 0) {\n      rv[st][0] = 0;\n      continue;\n    }\n    int h = (1 << (st - 1));\n    forn(k, 1 << st)\n      rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);\n  }\n}\n\nvoid ntt(vector<Mint> &a, bool inv) {\n  int n = sz(a);\n  int ln = __builtin_ctz(n);\n  forn(i, n) {\n    int ni = rv[ln][i];\n    if (i < ni) swap(a[i], a[ni]);\n  }\n  forn(st, ln) {\n    int len = 1 << st;\n    for (int k = 0; k < n; k += (len << 1)) {\n      fore(pos, k, k + len){\n        Mint l = a[pos];\n        Mint r = a[pos + len] * w[st][pos - k];\n        a[pos] = l + r;\n        a[pos + len] = l - r;\n      }\n    }\n  }\n  if (inv) {\n    Mint rn = Mint(n).pow(MOD - 2);\n    forn(i, n) a[i] = a[i] * rn;\n    reverse(a.begin() + 1, a.end());\n  }\n}\n\nvector<Mint> mul(vector<Mint> a, vector<Mint> b) {\n  int cnt = 1 << (32 - __builtin_clz(sz(a) + sz(b) - 1));\n  a.resize(cnt);\n  b.resize(cnt);\n  ntt(a, false);\n  ntt(b, false);\n  vector<Mint> c(cnt);\n  forn(i, cnt) c[i] = a[i] * b[i];\n  ntt(c, true);\n  return c;\n}\n\nvector<Mint> norm(vector<Mint> a)\n{\n  while(a.size() > 1 && a.back() == Mint(0))\n    a.pop_back();\n  return a;\n}\n\nconst int N = 250043;\nvector<int> G[N];\nint d[N];\n\nMint fact[N * 2];\nMint rev[N * 2];\n\nvoid dfs(int x, int p)\n{\n  if(p != x) d[p]++;\n  for(auto y : G[x]) if(y != p) dfs(y, x);\n}\n\nMint C(int n, int k)\n{\n  return fact[n] * rev[k] * rev[n - k];\n}\n\nint main()\n{\n  prepare();\n  fact[0] = Mint(1);\n  for(int i = 1; i < N * 2; i++) fact[i] = fact[i - 1] * i;\n  for(int i = 0; i < N * 2; i++) rev[i] = Mint(1) / fact[i];\n  int n;\n  scanf(\"%d\", &n);\n  for(int i = 0; i < n - 1; i++)\n  {\n    int x, y;\n    scanf(\"%d %d\", &x, &y);\n    --x;\n    --y;\n    G[x].push_back(y);\n    G[y].push_back(x);  \n  }\n  dfs(0, 0);\n  vector<vector<Mint>> cur;\n  for(int i = 0; i < n; i++)\n    if(d[i] > 0)\n      cur.push_back(vector<Mint>({Mint(1), Mint(d[i])}));\n  while(cur.size() > 1)\n  {\n    vector<vector<Mint>> ncur;\n    for(int i = 0; i + 1 < cur.size(); i += 2)\n      ncur.push_back(norm(mul(cur[i], cur[i + 1])));\n    if(cur.size() % 2 == 1) ncur.push_back(cur.back());\n    cur = ncur;  \n  }\n  Mint ans = 0;\n  for(int i = 0; i < cur[0].size(); i++)\n  {\n    if(i % 2 == 0) ans = ans + cur[0][i] * fact[n - i];\n    else ans = ans - cur[0][i] * fact[n - i];\n  }\n  cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "fft"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1614",
    "index": "A",
    "title": "Divan and a Store",
    "statement": "Businessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well.\n\nThe store he came to has $n$ different chocolate bars, and the price of the $i$-th chocolate bar is $a_i$ dollars. Divan considers a chocolate bar too expensive if it costs strictly more than $r$ dollars. Similarly, he considers a bar of chocolate to be too cheap if it costs strictly less than $l$ dollars. Divan will not buy too cheap or too expensive bars.\n\nDivan is not going to spend all his money on chocolate bars, so he will spend at most $k$ dollars on chocolates.\n\nPlease determine the maximum number of chocolate bars Divan can buy.",
    "tutorial": "To solve this problem, let's use the following greedy algorithm. Let's sort the prices of chocolate bars in increasing order, after which we will go from left to right and take chocolates that have a price not less than $l$, but not more than $r$ until we run out of money. The number of chocolate bars that we took will be the answer to the problem. The resulting asymptotics in time: $\\mathcal{O}(n\\log{}n)$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1614",
    "index": "B",
    "title": "Divan and a New Project ",
    "statement": "The company \"Divan's Sofas\" is planning to build $n + 1$ different buildings on a coordinate line so that:\n\n- the coordinate of each building is an integer number;\n- no two buildings stand at the same point.\n\nLet $x_i$ be the coordinate of the $i$-th building. To get from the building $i$ to the building $j$, Divan spends $|x_i - x_j|$ minutes, where $|y|$ is the absolute value of $y$.\n\nAll buildings that Divan is going to build can be numbered from $0$ to $n$. The businessman will live in the building $0$, the new headquarters of \"Divan's Sofas\". In the first ten years after construction Divan will visit the $i$-th building $a_i$ times, each time spending $2 \\cdot |x_0-x_i|$ minutes for walking.\n\nDivan asks you to choose the coordinates for all $n + 1$ buildings so that over the next ten years the businessman will spend as little time for walking as possible.",
    "tutorial": "Obviously, the more often we have to go to the $i$ building, the closer it should be to the main office. This implies a greedy algorithm. Let's put the main office at $0$ and sort the rest by $a_i$. Then we put the most visited building at a point with a coordinate of $1$, the second at $-1$, the third at $2$, etc. The resulting asymptotics in time is $\\mathcal{O}(n\\log{}n)$.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1614",
    "index": "C",
    "title": "Divan and bitwise operations",
    "statement": "Once Divan analyzed a sequence $a_1, a_2, \\ldots, a_n$ consisting of $n$ non-negative integers as follows. He considered each non-empty subsequence of the sequence $a$, computed the bitwise XOR of its elements and added up all the XORs, obtaining the coziness of the sequence $a$.\n\nA sequence $c$ is a subsequence of a sequence $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements. For example, $[1, \\, 2, \\, 3, \\, 4]$, $[2, \\, 4]$, and $[2]$ are subsequences of $[1, \\, 2, \\, 3, \\, 4]$, but $[4, \\, 3]$ and $[0]$ are not.\n\nDivan was very proud of his analysis, but now he lost the sequence $a$, and also the coziness value! However, Divan remembers the value of bitwise OR on $m$ contiguous subsegments of the sequence $a$. It turns out that each element of the original sequence is contained in \\textbf{at least one} of these $m$ segments.\n\nDivan asks you to help find the coziness of the sequence $a$ using the information he remembers. If several coziness values are possible, print any.\n\nAs the result can be very large, print the value modulo $10^9 + 7$.",
    "tutorial": "Let's count for each bit how many times it will be included in the answer. Let us now consider the $i$-th bit. Note that if no number contains the included $i$-th bit, then such a bit will never be included in the answer. Otherwise, each of the subsequences contains $i$-th bit even or odd number of times. If a bit enters an even number of times, then we should not count such a subsequence, because the bitwise exclusive OR for this bit will be zero. If the bit enters an odd number of times, then we must count such a subsequence, because the bitwise exclusive OR for this bit will be equal to one. It is stated that the number of subsequences in which the $i$-th bit enters an odd number of times is equal to $2^{n - 1}$. Let's prove it. Divide the numbers into two sets $A$ and $B$. In the set $A$ there will be numbers whose $i$th bit is off, in the set $B$ there will be numbers whose $i$-th bit is on. Note that the numbers from the set $A$ do not affect the answer in any way, because $x\\; XOR\\; 0 = 1$. Thus, whichever subset of $A$ we take, the $i$-th bit will not change its parity. There will be $2^{|A|}$ in total of such subsets. Let $k = 1$ if $|B|$ is even, or $k = 0$ if $|B|$ is odd. In order for the $i$-th bit to enter the subsequence an odd number of times, you need to take an odd number of elements from the set $B$. This number is equal to $C_{|B|}^{1} \\, + \\, C_{|B|}^{3} \\, + \\dots \\, + \\, C_{|B|}^{|B| - k} = 2^{|B| - 1}$. Thus, the $i$-th bit is included in exactly $2^{|A|}\\cdot 2^{|B|- 1}= 2^{n - 1}$ subsequences, which was required to be proved. Then the solution to this problem turns out to be very simple: let $x$ be equal to the bitwise OR of all elements of the sequence (or, the same thing, bitwise OR of all given segments), then the answer will be equal to $x\\cdot 2^{n - 1}$ modulo $10^9 + 7$. The resulting asymptotics in time: $\\mathcal{O}(n)$.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1614",
    "index": "D1",
    "title": "Divan and Kostomuksha (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is maximum value of $a_i$.}\n\nOnce in Kostomuksha Divan found an array $a$ consisting of positive integers. Now he wants to reorder the elements of $a$ to maximize the value of the following function: $$\\sum_{i=1}^n \\operatorname{gcd}(a_1, \\, a_2, \\, \\dots, \\, a_i),$$ where $\\operatorname{gcd}(x_1, x_2, \\ldots, x_k)$ denotes the greatest common divisor of integers $x_1, x_2, \\ldots, x_k$, and $\\operatorname{gcd}(x) = x$ for any integer $x$.\n\nReordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order.\n\nOf course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you.",
    "tutorial": "Let's solve the dynamic programming problem. Let $dp_i$ be the maximum answer for all arrays, the last element of which is divisible by $i$. Let's calculate the dynamics from $C$ to $1$, where $C$ is the maximum value of $a_i$. Initially, $dp_i = cnt_i \\cdot i$, where $cnt_i$ is the amount of $a_i = i$. How do we recalculate our dynamic programming? $dp_i = max(dp_i, dp_j + i \\cdot (cnt_i - cnt_j))$, for all $j$ such that $j$ $mod$ $i = 0$ (i.e. $j$ is divisible by $i$). In this dynamic, we iterate over the past change of our $gcd$ on the prefix, and greedily add all possible elements. The resulting asymptotics in time is $\\mathcal{O}(C\\log{}C)$.",
    "tags": [
      "dp",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1614",
    "index": "D2",
    "title": "Divan and Kostomuksha (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is maximum value of $a_i$.}\n\nOnce in Kostomuksha Divan found an array $a$ consisting of positive integers. Now he wants to reorder the elements of $a$ to maximize the value of the following function: $$\\sum_{i=1}^n \\operatorname{gcd}(a_1, \\, a_2, \\, \\dots, \\, a_i),$$ where $\\operatorname{gcd}(x_1, x_2, \\ldots, x_k)$ denotes the greatest common divisor of integers $x_1, x_2, \\ldots, x_k$, and $\\operatorname{gcd}(x) = x$ for any integer $x$.\n\nReordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order.\n\nOf course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you.",
    "tutorial": "To solve $D2$, we can notice that to recalculate the dynamics, we can iterate over all such $j$ that differ from $i$ by multiplying exactly $1$ prime number. Also, to speed up the solution, we can use the linear sieve of Eratosthenes to find primes and factorization. The resulting asymptotics in time: $\\mathcal{O}(C\\log{}\\log{}C)$.",
    "tags": [
      "dp",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1614",
    "index": "E",
    "title": "Divan and a Cottage",
    "statement": "Divan's new cottage is finally complete! However, after a thorough inspection, it turned out that the workers had installed the insulation incorrectly, and now the temperature in the house directly depends on the temperature outside. More precisely, if the temperature in the house is $P$ in the morning, and the street temperature is $T$, then by the next morning the temperature in the house changes according to the following rule:\n\n- $P_{new} = P + 1$, if $P < T$,\n- $P_{new} = P - 1$, if $P > T$,\n- $P_{new} = P$, if $P = T$.\n\nHere $P_{new}$ is the temperature in the house next morning.Divan is a very busy businessman, so sometimes he is not at home for long periods and does not know what the temperature is there now, so he hired you to find it. You will work for $n$ days. In the beginning of the $i$-th day, the temperature outside $T_i$ is first given to you. After that, on the $i$-th day, you will receive $k_i$ queries. Each query asks the following: \"if the temperature in the house was $x_i$ at the morning of the \\textbf{first} day, what would be the temperature in the house next morning (after day $i$)?\"\n\nPlease answer all the businessman's queries.",
    "tutorial": "Let $ans_{temp}$ the current answer for temperature $temp$. Before all days, $ans_{temp}$ is considered equal to $temp$. In order to respond to a request with a temperature of $x$, we will just need to output the value of $ans_x$. But how to maintain $ans$? With the help of an implicit tree of segments, at the vertices of which the minimum and maximum will be stored, as well as the variable $add$, which will contain the value that needs to be added to the current vertex (that is, such a variable that is needed to perform lazy operations on the segment tree). At the beginning of the next day you get the temperature $T$. Now we need to change the current answer for some $temp$. We need to find such $ans_{temp}$ that $ans_{temp} <T$ and add $+1$ to them, and then find such $ans_{temp}$ that $ans_{temp} > T$ and add $-1$ to them. All this is not difficult to do, just starting from the root of the segment tree and stopping at the moments when: the maximum of the current vertex is less than $T$ - here we add $+1$; the minimum of the current vertex is greater than $T$ - here we add $-1$; the minimum of the vertex is equal to the maximum of the vertex (and, therefore, the $T$ itself) - here we do not add anything. The resulting asymptotics in time: $\\mathcal{O}(n\\log{}T)$.",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1615",
    "index": "A",
    "title": "Closing The Gap",
    "statement": "There are $n$ block towers in a row, where tower $i$ has a height of $a_i$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation:\n\n- Choose two indices $i$ and $j$ ($1 \\leq i, j \\leq n$; $i \\neq j$), and move a block from tower $i$ to tower $j$. This essentially decreases $a_i$ by $1$ and increases $a_j$ by $1$.\n\nYou think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $\\max(a)-\\min(a)$.\n\nWhat's the minimum possible ugliness you can achieve, after any number of days?",
    "tutorial": "If $\\max(a) - \\min(a)$ is strictly greater than $1$, you can apply the operation on the max and the min respectively, which brings them both closer to each other. In other words, it either decreases $\\max(a) - \\min(a)$ or leaves it the same. This implies that the answer is always $\\leq 1$. Now what remains is determining whether the answer is $0$ or $1$. The answer can only be $0$ if the sum of the array is divisible by $n$, as the sum of the array can't change after an operation, and if it's not divisible by $n$ you can't make every element equal. This means that the answer is $0$ if the sum is divisible by $n$, and $1$ otherwise.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1615",
    "index": "B",
    "title": "And It's Non-Zero",
    "statement": "You are given an array consisting of all integers from $[l, r]$ inclusive. For example, if $l = 2$ and $r = 5$, the array would be $[2, 3, 4, 5]$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero?\n\nA bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.",
    "tutorial": "Let's solve the complement problem: find the largest subsequence of the array such that their bitwise AND is non-zero. Let $x$ be the bitwise and of the optimal subsequence. Since $x \\neq 0$, at least one bit must be set in $x$. Let's iterate over that bit, call it $b$, and in each iteration, calculate the largest subsequence whose bitwise and has that bit set. For the $b$-th bit to be set in the final answer, every element in the chosen subsequence must have that bit set. Since choosing every element with the $b$-th bit on is a valid subsequence, this implies that the answer for the $b$-th bit is the number of elements that have the $b$-th bit set. Thus, the answer to the final problem is $n - \\max\\limits_{1 \\leq b \\leq 30} cnt_{b}$, where $cnt_b$ is the number of elements who have the $b$-th bit set. Note: it doesn't matter if the final answer contains more than one set bit, it's still covered in at least one of the cases, and the bitwise and will still be non-zero. All that remains is counting the number of elements in the range $[l \\ldots r]$ with the $b$-th bit set, for all $b$. This can be done with precomputation, by creating $b$ prefix sum arrays before answering any of the test cases, where the $i$-th element of the $b$-th array is the number of integers $\\leq i$ that have the $b$-th bit on. After this, you can use the prefix sum technique to answer queries, as $cnt_b = a_{b, r} - a_{b, l}$, if $a_b$ is the $b$-th array. Challenge: solve the problem with $1 \\leq l \\leq r \\leq 10^9$.",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1615",
    "index": "C",
    "title": "Menorah",
    "statement": "There are $n$ candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string $s$, where the $i$-th candle is lit if and only if $s_i=1$.\n\nInitially, the candle lights are described by a string $a$. In an operation, you select a candle that is \\textbf{currently lit}. By doing so, the candle you selected will remain lit, and every other candle will change (if it was lit, it will become unlit and if it was unlit, it will become lit).\n\nYou would like to make the candles look the same as string $b$. Your task is to determine if it is possible, and if it is, find the minimum number of operations required.",
    "tutorial": "First, let's define the \"type\" of a candle $i$ to be the string $a_ib_i$. For example, if a candle is currently unlit and must be lit in the end, its type is $01$. It's useful to think about the number of candles of each type because the position of a candle is irrelevant in this problem. Now, let's consider what happens when we do two operations consecutively. All candles except the ones we select will flip twice, so let's focus on what happens to the candles we select. If we select the same candle twice, nothing changes. And if we select two different candles, it's equivalent to swapping a $1$ and a $0$ in the string. Since we have a really nice description of two consecutive operations, any sequence of an even number of operations is just a sequence of swaps. So it's possible in an even number of operations as long as the number of $1$'s in both strings is the same, and the minimum number of operations will be the number of positions where the strings differ. Now, what about an odd number of operations? Well, it's the same as performing one operation and then reducing it to the case of an even number of operations. There are two types of candles we can select on the first operation: type $10$ and type $11$. Simply try both options if they're present, and find the minimum number of operations after it's reduced to the even case. Finally, there are some strings where it's possible to do in either an even or an odd number of operations, so in those cases we have to take the minimum of both options. The total complexity is $O(n)$. Bonus: Can you prove that in the case of an odd number of operations, it is never necessary to select a candle of type $10$?",
    "tags": [
      "brute force",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1615",
    "index": "D",
    "title": "X(or)-mas Tree",
    "statement": "'Twas the night before Christmas, and Santa's frantically setting up his new Christmas tree! There are $n$ nodes in the tree, connected by $n-1$ edges. On each edge of the tree, there's a set of Christmas lights, which can be represented by an integer in binary representation.\n\nHe has $m$ elves come over and admire his tree. Each elf is assigned two nodes, $a$ and $b$, and that elf looks at all lights on the simple path between the two nodes. After this, the elf's favorite number becomes the bitwise XOR of the values of the lights on the edges in that path.\n\nHowever, the North Pole has been recovering from a nasty bout of flu. Because of this, Santa forgot some of the configurations of lights he had put on the tree, and he has already left the North Pole! Fortunately, the elves came to the rescue, and each one told Santa what pair of nodes he was assigned $(a_i, b_i)$, as well as \\textbf{the parity} of the number of set bits in his favorite number. In other words, he remembers whether the number of $1$'s when his favorite number is written in binary is \\textbf{odd or even}.\n\nHelp Santa determine if it's possible that the memories are consistent, and if it is, remember what his tree looked like, and maybe you'll go down in history!",
    "tutorial": "Let $\\text{count}(x)$ be the number of $1$-bits in an integer $x$. Notice that $\\text{count}(x \\oplus y)\\mod 2$ = $\\text{count}(x) \\mod 2 \\oplus \\text{count}(y) \\mod 2$. This means that you can replace each integer $x$ on the tree with $\\text{count}(x) \\mod 2$. Note that you can pretend the initial given edges are also just elves who traveled over the path consisting solely of that edge. After this transformation, each of the edge weights is either $0$ or $1$, and you're given a set of paths and you are told the XOR of each path. Root the tree at node $1$. Let $r_i$ be the XOR of the values on the edges from node $i$ to the root ($r_1 = 0$). Notice that the XOR of a path $(a, b)$ is $r_a \\oplus r_b$. From this, each constraint of the form $(a, b, c)$ telling you that the XOR of the path $(a, b)$ has to equal $c$ is equivalent to $r_a \\oplus r_b = c$. This problem can be solved using a variant of bipartite coloring, where you create a graph and add a bidirectional edge between $(a, b)$ with weight $c$ for each of those constraints. You run dfs through each of the individual connected components. Within a component, choosing the value of a single node uniquely determines the rest. During the dfs, if you're at a node $a$ and are considering traversing the edge $(a, b, c)$, you know that $r_b = r_a \\oplus c$, so you can determine $r_b$ from $r_a$. The final value of an edge between $a$ and $p$ (the parent of $a$) is $r_a \\oplus r_p$.",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1615",
    "index": "E",
    "title": "Purple Crayon",
    "statement": "Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game.\n\nThe game works as follows: there is a tree of size $n$, rooted at node $1$, where each node is initially white. Red and Blue get \\textbf{one turn each}. Red goes first.\n\nIn Red's turn, he can do the following operation \\textbf{any number of times}:\n\n- Pick any subtree of the rooted tree, and color every node in the subtree red.\n\nHowever, to make the game fair, Red is only allowed to color $k$ nodes of the tree. In other words, after Red's turn, at most $k$ of the nodes can be colored red.Then, it's Blue's turn. Blue can do the following operation \\textbf{any number of times}:\n\n- Pick any subtree of the rooted tree, and color every node in the subtree blue. However, he's not allowed to choose a subtree that contains a node already colored red, as that would make the node purple and no one likes purple crayon.\n\nNote: there's no restriction on the number of nodes Blue can color, as long as he doesn't color a node that Red has already colored.After the two turns, the score of the game is determined as follows: let $w$ be the number of white nodes, $r$ be the number of red nodes, and $b$ be the number of blue nodes. The score of the game is $w \\cdot (r - b)$.\n\nRed wants to maximize this score, and Blue wants to minimize it. If both players play optimally, what will the final score of the game be?",
    "tutorial": "After expanding the expression given in the statement (by replacing $w$ with $n - r - b$), it reduces to $r \\cdot (n - r) - b \\cdot (n - b)$. This means that in Blue's turn, his only goal is to maximize $b \\cdot (n - b)$. To maximize the value of that function, it's optimal to pick the value of $b$ that is closest to $\\lfloor \\frac{n}{2} \\rfloor$. One thing to note is that if it's possible for Blue to color exactly $x$ nodes, for some number $x$, it is possible for Blue to color exactly $x-1$ nodes as well. This is because, given some subtree that he has colored, he can also choose to color every node in the subtree except the root. This would reduce the number of Blue nodes by exactly $1$. By repeating this process, one can show that if Blue can color exactly $x$ nodes, Blue can also color $y$ nodes if $y \\leq x$. What this implies is that if you know the number of nodes that Red colors, Red's optimal strategy would be to minimize the maximum number of nodes that Blue can color (as it reduces the possible choices that Blue has). If Red chooses node $x$, it means that Blue can't choose any ancestors (or descendants) of node $x$. This transforms the problem into the following: For all $i \\leq k$, perform the following operation exactly $i$ times: choose a node $v$ and mark all of the nodes on the path to the root. For each $i$, calculate the maximum number of nodes that are marked at least once at the end of this process by optimally choosing $v$ at each step. The set of optimally chosen $v$ (for a given $i$) can be found using the following greedy algorithm: Sort all nodes in decreasing order of depth. Then, go through the nodes in order, let the current node be $v$. Go to the root marking nodes until you reach one that has already been marked. Let the number of marked nodes be $c_v$. Finally, sort all nodes in decreasing order of $c_v$. Choose the first $i$ nodes from this list. Proof that the greedy produces the correct answer: We must prove that the greedy algorithm always chooses a subset of nodes that maximizes the number of marked nodes at the end of the process. We can imagine that instead of coloring nodes, we can delete them from the tree to get a forest of rooted trees. Let's prove that there is an optimal solution where the deepest leaf in a forest (say $v$) is chosen. Consider a configuration in which $v$ is not chosen. Let $u$ be the node that maximizes the depth of LCA($u$, $v$) that is present in the configuration. You can replace the node $u$ with $v$ in the configuration, and the answer won't decrease (as the depth of $v$ is greater than the depth of $u$). Since the relative order of depths in a tree in the forest at any point is the same as the relative order of depths of its vertices in the original tree, choosing the deepest node in a tree in the forest is equivalent to choosing the vertex in that tree, which has the max depth in the original tree. Note that the process can be simulated in amortized linear time (not including the sorting), as each node will be colored at most once. All that's left is to iterate over all values of $i$, and take the maximum value that Red can get.",
    "tags": [
      "data structures",
      "dfs and similar",
      "games",
      "graphs",
      "greedy",
      "math",
      "sortings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1615",
    "index": "F",
    "title": "LEGOndary Grandmaster",
    "statement": "After getting bored by playing with crayons, you decided to switch to Legos! Today, you're working with a long strip, with height $1$ and length $n$, some positions of which are occupied by $1$ by $1$ Lego pieces.\n\nIn one second, you can either remove two adjacent Lego pieces from the strip (if both are present), or add two Lego pieces to adjacent positions (if both are absent). You can only add or remove Lego's at two adjacent positions at the same time, as otherwise your chubby fingers run into precision issues.\n\nYou want to know exactly how much time you'll spend playing with Legos. You value efficiency, so given some starting state and some ending state, you'll always spend the least number of seconds to transform the starting state into the ending state. If it's impossible to transform the starting state into the ending state, you just skip it (so you spend $0$ seconds).\n\nThe issue is that, for some positions, you don't remember whether there were Legos there or not (in either the starting state, the ending state, or both). Over all pairs of (starting state, ending state) that are consistent with your memory, find the total amount of time it will take to transform the starting state to the ending state. Print this value modulo $1\\,000\\,000\\,007$ ($10^9 + 7$).",
    "tutorial": "First, let's consider a fixed pair of strings $s$ and $t$, and find a simple way to calculate the amount of time it takes. Key observation: Flip every bit at an even position in both strings $s$ and $t$. Now, the operation is equivalent to swapping two adjacent bits of $s$. This is because the operation is equivalent to flipping two adjacent bits and swapping them. Flipping bits on an even position takes care of the first part of the operation (as any operation includes one bit at an even and one bit at an odd position), so the problem reduces to simple swapping. Now, for a fixed pair of strings, you want to find the minimum number of swaps to transform one into the other. Obviously, the answer is $0$ if the number of 1's in both strings is different. Now, let the number of 1's in each string be $k$, and the position of the $i$-th 1 from the left in $s$ be $x_i$, and the $i$-th 1 from the left in $t$ be $y_i$. The answer for a fixed pair of strings is $\\sum\\limits_{i = 1}^k|x_i - y_i|$, as the $i$-th 1 in $s$ will always be matched with the $i$-th 1 in $t$. This expression can be transformed into a more convenient one. Let $a_i$ be the number of 1's in $s$ in the prefix ending at $i$, and $b_i$ the number of 1's in $t$ in the prefix ending at $i$. The previous expression is equivalent to $\\sum\\limits_{i = 1}^n|a_i - b_i|$. This is because the $i$-th index contributes $1$ to each 1 in the previous expression if and only if a $1$ needs to \"cross\" the $i$-th index when moving to it's corresponding location in $t$. Exactly $|a_i - b_i|$ 1's will cross over the index, so the answer is the sum over all of the values. Now going back to the original problem, apply the initial transformation on the strings $s$ and $t$, where for each even index, you change 0 to 1, 1 to 0, and keep ? the same. Let $p_{i, j}$ be the number of ways, if you only consider indices $\\leq i$, to replace the ?'s with 0's and 1's so that $a_i - b_i = j$. $s_{i, j}$ is defined similarly, except you only consider indices $\\geq i$. Both of these have $\\mathcal{O}(n^2)$ states and $\\mathcal{O}(1)$ transitions. The final answer is $\\sum\\limits_{i=1}^{n-1} \\sum\\limits_{j=-n}^n |\\ j \\cdot p_{i, j} \\cdot s_{i+1, -j} \\ |$.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1615",
    "index": "G",
    "title": "Maximum Adjacent Pairs",
    "statement": "You are given an array $a$ consisting of $n$ non-negative integers.\n\nYou have to replace each $0$ in $a$ with an integer from $1$ to $n$ (different elements equal to $0$ can be replaced by different integers).\n\nThe value of the array you obtain is the number of integers $k$ from $1$ to $n$ such that the following condition holds: there exist a pair of adjacent elements equal to $k$ (i. e. there exists some $i \\in [1, n - 1]$ such that $a_i = a_{i + 1} = k$). If there are multiple such pairs for some integer $k$, this integer is counted in the value only once.\n\nYour task is to obtain the array with the maximum possible value.",
    "tutorial": "Let's consider each segment of zeroes in our sequence. Each of these segments has either odd or even length. If a segment has length $2m + 1$ (it is odd), then it can be used to create $m$ pairs of neighboring elements, and an additional pair for either the number right before the segment, or for the number right after the segment. If a segment has length $2m$ (it is even), then it can be used either to create $m$ pairs of neighboring elements, or $m-1$ pairs of any integers and two additional pairs for the elements that are on the borders of the segment. It's never optimal to match only one of the zeroes in an even segment with the element on the border, because we could just use the segment to create $m$ pairs instead. Let's build an undirected graph which initially has $m = \\max\\limits_{i=1}^{n} a_i$ vertices (one for each integer from $1$ to $m$). Let's add the following edges and vertices to it: For each integer already having a pair of adjacent elements, add an auxiliary vertex and connect it with the vertex representing the integer. For each $0$-segment of even length, add an edge between vertices representing elements on the borders of this segment (we need at most one of these for each pair of elements on the border). For each $0$-segment of odd length, add an auxiliary vertex and connect it with vertices representing elements on the borders of this segment (we need at most two of these for each pair of elements on the border). Let's find the maximum matching in this graph using some maximum matching algorithm (for example, Edmonds' blossom algorithm). Let the size of the maximum matching be $M$. It can be shown that the sum of $M$ and all values $\\lfloor \\frac{len}{2} \\rfloor$ over all $0$-segments (where $len$ is the length of the segment) is equal to the maximum number of integers that can have a pair of neighboring elements: for each segment of even length, the edge representing it will either be in the matching (and the segment will create $\\frac{len}{2} + 1$ pairs), or the edge won't belong to the matching (and the segment will create $\\frac{len}{2}$ pairs). For each odd $0$-segment, we either match its vertex with a number on its border (so this segment creates $\\frac{len - 1}{2} + 1$ pairs), or won't match its vertex (so this segment creates $\\frac{len - 1}{2}$ pairs). The numbers already having a pair of neighboring elements will be processed by the vertices connected only to them, so they get $+1$ to the size of the matching \"for free\" and can't be matched with anything else (or will be matched, but won't add $+1$ for free). The maximum matching can enforce the constraint that each number is counted in the answer only once. How fast will this solution work? Unfortunately, it can be too slow. The resulting graph can have up to $O(n)$ edges and up to $600^2$ vertices, so the standard implementation of Edmonds is not sufficient. But there are many different heuristics you can use in this problem to speed up the solution. We used the following one: Split all vertices into two \"parts\", the first part will contain the vertices representing the numbers, and the second part will contain all of the other vertices. The edges can connect only vertices from the first part and the vertices from different parts, and there are only up to $600$ vertices in the first part. Let's ignore the edges between the vertices in the first part and find the maximum matching in this graph using Kuhn's algorithm. Then, we claim that if we find the maximum general matching starting from this bipartite matching and improving it, the augmenting paths cannot both start and end in the vertices of the second part (since the number of matched vertices in the second part cannot exceed the maximum bipartite matching). Then we can search for augmenting paths only starting in vertices of the first part in Edmonds (so we need only $600$ phases of Edmonds). Furthermore, we can speed up each phase of Edmonds as follows: if the current size of the matching is $M$, then we'll visit no more than $2M+2$ vertices while searching for an augmenting path; and if we contract each blossom in linear time of its size, each phase will work in $O(M^2)$, where $M$ is the current size of the matching (and it cannot me greater than $600$).",
    "tags": [
      "constructive algorithms",
      "graph matchings"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1615",
    "index": "H",
    "title": "Reindeer Games",
    "statement": "There are $n$ reindeer at the North Pole, all battling for the highest spot on the \"Top Reindeer\" leaderboard on the front page of CodeNorses (a popular competitive reindeer gaming website). Interestingly, the \"Top Reindeer\" title is just a measure of upvotes and has nothing to do with their skill level in the reindeer games, but they still give it the utmost importance.\n\nCurrently, the $i$-th reindeer has a score of $a_i$. You would like to influence the leaderboard with some operations. In an operation, you can choose a reindeer, and either increase or decrease his score by $1$ unit. Negative scores are allowed.\n\nYou have $m$ requirements for the resulting scores. Each requirement is given by an ordered pair $(u, v)$, meaning that after all operations, the score of reindeer $u$ must be less than or equal to the score of reindeer $v$.\n\nYour task is to perform the minimum number of operations so that all requirements will be satisfied.",
    "tutorial": "Let's try to find a nice lower bound for the answer. Let's denote a requirement of two nodes $u$ and $v$ by a directed edge $u\\to v$. We can observe that if there are two nodes $u$ and $v$ such that there's a requirement $u\\to v$ (or a path of requirements from $u$ to $v$), then we will need to do at least $a_u-a_v$ operations on these two nodes. So, if we can create a list of pairs $(u_1,v_1),\\ldots, (u_k,v_k)$ with all distinct nodes such that there is a path from $u_i$ to $v_i$ for all $i$, then a lower bound of the answer is $\\sum\\limits_{i=1}^k (a_{u_i}-a_{v_i})$ Our strategy will be to find the largest possible lower bound of this form, and then construct a solution with exactly that cost (which is therefore the optimal cost). To find an optimal set of pairs, we can set it up as a flow problem. Every directed edge $u\\to v$ of the original graph will have infinite capacity and a cost of $a_u-a_v$. In addition, we will create two new nodes $s$ and $t$. For each node $u$, add an edge $s\\to u$ with capacity $1$ and cost $0$, and add an edge $u\\to t$ with capacity $1$ and cost $0$. Compute the maximum cost flow from $s$ to $t$ (the amount of flow doesn't need to be maximized). If there is any node $u$ such that $s\\to u$ and $u\\to t$ both have flow, make them both have $0$ flow, and this won't change the cost. The flow can be decomposed into paths with distinct endpoints in the original graph. The endpoints are distinct because each node $u$ cannot have flow on both edges $s\\to u$ and $u\\to t$. And the cost of a path beginning in $u$ and ending in $v$ will be $a_u-a_v$ (intermediate nodes of the path cancel out when computing the cost). It's also easy to see that any set of pairs has a corresponding flow in the graph with the same cost. So, this flow gives us a way to compute a set of pairs with the maximum lower bound, just like we want. Now, how do we construct the operations to perform? First, take the edges of the residual flow graph that are not at full capacity. Using only these edges, compute the longest path from $s$ to every node in the graph (where length of a path is the sum of edge costs). Let's say the longest path from $s$ to $u$ is $d_u$. Let's show that $b_u:=a_u+d_u$ satisfies all requirements. Every requirement $u\\to v$ is present in the residual graph because it has infinite capacity. So we have that $d_u+(a_u-a_v)\\le d_v$, otherwise we could find a longer path from $s$ to $v$. By moving $a_v$ to the right side of this inequality, we get $a_u+d_u\\le a_v+d_v$, In other words, $b_u\\le b_v$, meaning this requirement is satisfied. Let's show that the total number of operations $\\sum_u|b_u-a_u|$ does not exceed the cost of the flow. It's sufficient to show that for each node $u$ that isn't in one of the pairs, we have $b_u=a_u$, and for each pair $(u_i, v_i)$ we have that $a_{v_i}\\le b_{v_i}=b_{u_i}\\le a_{u_i}$. For the first part, suppose a node $u$ is unpaired. If $d_u>0$, then there is a path from $s$ to $u$ with positive cost, and there is an edge from $u$ to $t$ of $0$ cost because it's unpaired, so we've found an augmenting path in the flow graph that will increase the cost. This contradicts the fact that we found the maximum cost flow. On the other hand, if $d_u<0$, this contradicts the definition of $d_u$ since there's an edge $s\\to u$ of cost $0$ which makes a longer path. Therefore, $d_u=0$ and $b_u=a_u+d_u=a_u$, as desired. For the second part, consider a pair $(u_i,v_i)$. There is a path in the residual graph from $v_i$ to $u_i$, so we have $d_{v_i}+(a_{v_i}-a_{u_i})\\le d_{u_i}$. In other words, $b_{v_i}\\le b_{u_i}$. But we already had that $b_{u_i}\\le b_{v_i}$ because all requirements are satisfied, therefore $b_{u_i}=b_{v_i}$. It's impossible to have $d_{v_i}<0$ because there's a longer path with the direct edge $s\\to v_i$ which is present in the residual graph. It's impossible to have $d_{u_i}>0$ because it would mean the edge $u_i\\to t$ creates an augmenting path with positive cost. Therefore, $a_{v_i}\\le a_{v_i}+d_{v_i}=b_{v_i}=b_{u_i}=a_{u_i}+d_{u_i}\\le a_{u_i}$, as desired. In summary, the solution is to build a flow graph, compute the maximum cost flow (which is equivalent to minimum cost flow with all costs negated), and compute the distance values $d_u$ to construct the solution. The flow can be computed with the potential method in $O(nm\\log n)$ time.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "flows",
      "graphs",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1616",
    "index": "A",
    "title": "Integer Diversity",
    "statement": "You are given $n$ integers $a_1, a_2, \\ldots, a_n$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i. e. change $x \\to (-x)$). What is the maximum number of different values in the array you can achieve?",
    "tutorial": "At first, let's replace $a_i$ with $|a_i|$. Let $f(x)$ denote the number of vaues in the array equal to $x$ after the replacement (or, equal to $x$ or $-x$ before). Then, for the zero we can only get $\\min(1, f(0))$ different values. And for any other number $x > 0$, we can get $\\min(2, f(x))$ different numbers in the array. As different absolute values are independent and bounded, to get the answer we just need to evalue the sum $\\min(1, f(0)) + \\min(2, f(1)) + \\ldots + \\min(2, f(100))$. It can be easily done using arrays, maintaning the number of occurences for each $|x|$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1616",
    "index": "B",
    "title": "Mirror in the String",
    "statement": "You have a string $s_1 s_2 \\ldots s_n$ and you stand on the left of the string looking right. You want to choose an index $k$ ($1 \\le k \\le n$) and place a mirror after the $k$-th letter, so that what you see is $s_1 s_2 \\ldots s_k s_k s_{k - 1} \\ldots s_1$. What is the lexicographically smallest string you can see?\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Let's compare $s_1 s_2 \\ldots s_k s_k s_{k - 1} \\ldots s_1$ and $s_1 s_2 \\ldots s_{k+1} s_{k+1} s_{k} \\ldots s_1$. Note that they have a long common prefix $s_1, s_2, \\ldots, s_k$. And the next pair of characters to compare is $s_{k+1}$ and $s_k$. So, unless $s_1 s_2 \\ldots s_k s_k s_{k - 1} \\ldots s_1$ is a prefix of $s_1 s_2 \\ldots s_{k+1} s_{k+1} s_{k} \\ldots s_1$, it is optimal to choose $k+1$ if $s_{k+1} \\leq s_k$. Pushing this idea further, we can see that the answer is either $s_1 s_1$ or $s_1 s_2 \\ldots s_k s_k s_{k - 1} \\ldots s_1$, for the largest $k$ such that $s_k \\leq s_{k-1}$.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1616",
    "index": "C",
    "title": "Representative Edges",
    "statement": "An array $a_1, a_2, \\ldots, a_n$ is good if and only if for every subsegment $1 \\leq l \\leq r \\leq n$, the following holds: $a_l + a_{l + 1} + \\ldots + a_r = \\frac{1}{2}(a_l + a_r) \\cdot (r - l + 1)$.\n\nYou are given an array of integers $a_1, a_2, \\ldots, a_n$. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.",
    "tutorial": "Note that if the array is good $a_{k+2}-a_{k+1}=a_{k+1}-a_k$. In other words, the array form an arithmetic progression. We can either fix an arbitrary element and set all other elements equal to it (giving us the lower bound $n-1$ on the answer). Or, to solve the remaining case, we can fix any two elements that are in the answer, derive the formula for an arbitrary element of the arithmetic progression, and check the number of elements that we have to change.",
    "tags": [
      "brute force",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1616",
    "index": "D",
    "title": "Keep the Average High",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$ and an integer $x$.\n\nYou need to select the maximum number of elements in the array, such that for every subsegment $a_l, a_{l + 1}, \\ldots, a_r$ containing strictly more than one element $(l < r)$, either:\n\n- At least one element on this subsegment is \\textbf{not} selected, or\n- $a_l + a_{l+1} + \\ldots + a_r \\geq x \\cdot (r - l + 1)$.",
    "tutorial": "Note that $a_l + a_{l+1} + \\ldots + a_r \\geq x \\cdot (r - l + 1) \\Rightarrow (a_l - x) + (a_{l+1} - x) + \\ldots + (a_r - x) \\geq 0$. After subtracting $x$ from all elements, the problem is reduced to choosing the maximum number of elements with only non-negative sum contiguous elements. Note that there should be a negative-sum subsegment of length $2$ or $3$, if there is a negative-sum subsegment. It is easy to see as $x < 0, y < 0 \\Rightarrow x + y < 0$. Hence, to solve the original problem we can use a simple DP, storing for the last two elements whether they are in the answer or not.",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1616",
    "index": "E",
    "title": "Lexicographically Small Enough",
    "statement": "You are given two strings $s$ and $t$ of equal length $n$. In one move, you can swap any two adjacent characters of the string $s$.\n\nYou need to find the minimal number of operations you need to make string $s$ lexicographically smaller than string $t$.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Let's iterate over characters one by one and see the minimum number of operations required to make the string smaller with the fixed common prefix. Every time, we need to update the answer with the minimum number of moves required to make our prefix equal to some other prefix (iterating over characters smaller than the current). In general, we can easily see that the optimal strategy is to move characters one by one, every time choosing the closest character. You can use data structures like Binary Indexed Tree to maintain the answer along the way.",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1616",
    "index": "F",
    "title": "Tricolor Triangles",
    "statement": "You are given a simple undirected graph with $n$ vertices and $m$ edges. Edge $i$ is colored in the color $c_i$, which is either $1$, $2$, or $3$, or left uncolored (in this case, $c_i = -1$).\n\nYou need to color all of the uncolored edges in such a way that for any three pairwise adjacent vertices $1 \\leq a < b < c \\leq n$, the colors of the edges $a \\leftrightarrow b$, $b \\leftrightarrow c$, and $a \\leftrightarrow c$ are either pairwise different, or all equal. In case no such coloring exists, you need to determine that.",
    "tutorial": "$c_1, c_2, c_3$ form a valid triangle coloring if and only if $c_1 + c_2 + c_3 = 3k$ for some $k \\in \\mathbb{Z}$ Hence we can solve our problem with the simple Gaussian elemeniation. Complexity depends on your implementation, and you can use bitset to optimize it by $64$ times. Note that the number of triangles is bounded by $m\\sqrt{m}$, and the number of elements in the basis is $m$.",
    "tags": [
      "brute force",
      "graphs",
      "math",
      "matrices"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1616",
    "index": "G",
    "title": "Just Add an Edge",
    "statement": "You are given a directed acyclic graph with $n$ vertices and $m$ edges. For all edges $a \\to b$ in the graph, $a < b$ holds.\n\nYou need to find the number of pairs of vertices $x$, $y$, such that $x > y$ and after adding the edge $x \\to y$ to the graph, it has a Hamiltonian path.",
    "tutorial": "First of all, we have to check whether there is a Hamiltonian path in the original graph. In this case, the number is ${n \\choose 2}$ Otherwise, addition of the edge $a \\to b$ can only add a Hamiltonian path of the form: $(1 \\to \\ldots \\to a - 1) \\to \\ldots \\to b$ $b \\to a$ $a \\to \\ldots \\to (b \\to \\ldots n)$ And these paths should be non-intersecting. Where $(x \\to \\ldots \\to y)$ means the default path $x \\to (x+1) \\to \\ldots \\to y$ Using this observation, it is easy to derive a $DP$ with two states: two last vertices on the chain, and we are only interested in the states where $x,x+1$ are in different chains. $dp_{x,x+1}, dp_{x+1,x}$, we are interested in the number of valid pairs $(a-1,a)$ that you can reach from the valid pair $(b,b+1)$. Pair is valid if there is a hamilton path in the required direction. From here, we can get a solution in $O(nm)$, that could be optimized with bitset to $O(\\frac{nm}{64})$. But to make it linear, let's note that if there is no Hamiltonian path, then there is some edge $y \\to (y+1)$ not present in the graph, and all the paths connecting the pairs oof vertices we are interested in are going through this edge. So instead of maintaining the set of all valid $(a,a+1)$, we can run DFS in two drections from $(y,y+1)$, and calculate the number of required pairs.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1616",
    "index": "H",
    "title": "Keep XOR Low",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$ and an integer $x$.\n\nFind the number of non-empty subsets of indices of this array $1 \\leq b_1 < b_2 < \\ldots < b_k \\leq n$, such that for all pairs $(i, j)$ where $1 \\leq i < j \\leq k$, the inequality $a_{b_i} \\oplus a_{b_j} \\leq x$ is held. Here, $\\oplus$ denotes the bitwise XOR operation. As the answer may be very large, output it modulo $998\\,244\\,353$.",
    "tutorial": "First of all, we should divide all elements into groups by the prefix before the leading bit $i$ of $x$, as elements from different groups will definitely yield invalid answers. In one group, we either choose elements only from the group with the same bit $i$, then we can choose an artbirary subset. Or we need to solve the following problem: You are given two sequences $a,b$ of lengths $n,m$ and the current bit $i$. Choose any subset of $a \\cup b$, such that in each sequence at least one element is chosen, and the bitwise XOR of any pair (ignoring bits above $i$) is at most $x$ To solve this problem, we need to look at the bit $i$ in $x$. If it is set to zero, we need to recursively divide both arrays into $a_0, a_1, b_0, b_1$ according to the bits, and multiply the answers of $(a_0, b_0,i+1)$, and $(a_1, b_1, i+1)$. Otherwise, let's note that $(a_0, b_1)$ and $(a_1, b_0)$ are independent, so we can multiply their answers and also add a bunch of simple combinatorial formulas in case none elements are chosen in one of these pairs. The total complexity is $O(30n)$, as at each layer there are only $n$ elements in total.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "data structures",
      "divide and conquer",
      "dp",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1617",
    "index": "A",
    "title": "Forbidden Subsequence",
    "statement": "You are given strings $S$ and $T$, consisting of lowercase English letters. It is guaranteed that $T$ is a permutation of the string abc.\n\nFind string $S'$, the \\textbf{lexicographically smallest} permutation of $S$ such that $T$ is \\textbf{not} a subsequence of $S'$.\n\nString $a$ is a permutation of string $b$ if the number of occurrences of each distinct character is the same in both strings.\n\nA string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "When is the lexicographically smallest permutation of $S$ (i.e. the sorted string) not the answer? If there are no occurrences of a, b or c in $S$, sort $S$ and output it. Else, if $T \\ne$ abc, sort $S$ and output it. Else, output all a, then all c, then all b, then the rest of the string sorted. Originally, the author and two testers' solutions are all wrong, but we didn't notice until the third tester submitted the real correct solution.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define all(x) x.begin(), x.end()\nint main() {\n    int T;\n    cin >> T;\n    while(T--) {\n        string s, t;\n        cin >> s >> t;\n        sort(all(s));\n        vector<int> cnt(26, 0);\n        for(auto x: s)cnt[x - 'a']++;\n        if(t != \"abc\" || !cnt[0] || !cnt[1] || !cnt[2])cout << s << \"\\n\";\n        else{\n            while(cnt[0]--)cout<<\"a\";\n            while(cnt[2]--)cout<<\"c\";\n            while(cnt[1]--)cout<<\"b\";\n            for(int i = 3;i < 26; ++i){\n                while(cnt[i]--)cout<<char('a' + i);\n            }\n            cout << \"\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1617",
    "index": "B",
    "title": "GCD Problem",
    "statement": "Given a positive integer $n$. Find three \\textbf{distinct} positive integers $a$, $b$, $c$ such that $a + b + c = n$ and $\\operatorname{gcd}(a, b) = c$, where $\\operatorname{gcd}(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.",
    "tutorial": "There must exist a solution for $c=1$ under the given constraints. Key observation: there always exists a solution with $c = 1$ under the given constraints. We set $n \\ge 10$ because there is no solution when $1 \\le n \\le 5$ or $n = 7$. Solution 1: Brute force from $a = 2, 3, 4, \\dots$ and calculate the value of $b$ ($b = n - a - 1$), then check whether $gcd(a, b) = 1$. It works, because you will find a prime number $p \\le 29$ such that $n-1$ does not divide $p$. Solution 2: Randomly choose $a$ and calculate $b$ ($b = n - a - 1$). Repeating that for enough times will eventually get you a pair of ($a, b$) such that $gcd(a, b) = 1$. Solution 3: Constructive solution. When $n \\equiv 0 \\pmod 2$, output ($n-3, 2, 1$). When $n \\equiv 0 \\pmod 2$, output ($n-3, 2, 1$). When $n \\equiv 1 \\pmod 4$, output ($\\left \\lfloor \\frac{n}{2} \\right \\rfloor -1, \\left \\lfloor \\frac{n}{2} \\right \\rfloor +1, 1$). When $n \\equiv 1 \\pmod 4$, output ($\\left \\lfloor \\frac{n}{2} \\right \\rfloor -1, \\left \\lfloor \\frac{n}{2} \\right \\rfloor +1, 1$). When $n \\equiv 3 \\pmod 4$, output ($\\left \\lfloor \\frac{n}{2} \\right \\rfloor -2, \\left \\lfloor \\frac{n}{2} \\right \\rfloor +2, 1$). When $n \\equiv 3 \\pmod 4$, output ($\\left \\lfloor \\frac{n}{2} \\right \\rfloor -2, \\left \\lfloor \\frac{n}{2} \\right \\rfloor +2, 1$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve(){\n\tint n;\n\tcin>>n;\n\tif (n%2==0) cout<<\"2 \"<<(n-1)-2<<\" 1\\n\";\n\telse {\n\t\tint cur=(n-1)/2;\n\t\tif (cur%2==0) cout<<cur-1<<\" \"<<cur+1<<\" \"<<1<<endl;\n\t\telse cout<<cur-2<<\" \"<<cur+2<<\" \"<<1<<endl;\n\t}\n}\nsigned main(){\n\tint t;\n\tcin>>t;\n\twhile (t--) solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1617",
    "index": "C",
    "title": "Paprika and Permutation",
    "statement": "Paprika loves permutations. She has an array $a_1, a_2, \\dots, a_n$. She wants to make the array a \\textbf{permutation} of integers $1$ to $n$.\n\nIn order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers $i$ ($1 \\le i \\le n$) and $x$ ($x > 0$), then perform $a_i := a_i \\bmod x$ (that is, replace $a_i$ by the remainder of $a_i$ divided by $x$). In different operations, the chosen $i$ and $x$ \\textbf{can be different}.\n\nDetermine the minimum number of operations needed to make the array a permutation of integers $1$ to $n$. If it is impossible, output $-1$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "For any two positive integers $x$, $y$ that satisfy $x \\ge y$, what is the maximum value of $x \\bmod y$? Consider the following input: $n = 4$, $a = [3, 3, 10, 10]$. Sometimes, we don't need to do anything to some $a_i$. When do we have to make operations, and when do we not have to? Key observation: $x \\bmod y < \\frac{x}{2}$ if $x \\ge y$, and $x \\bmod y = x$ if $x < y$. Notice that the bigger the $x$, the bigger the range of values that can be obtained after one $\\bmod$ operation. So, intuitively, we want to assign smaller $a_i$ to smaller numbers in the resulting permutation. However, if $a_i$ satisfies $1 \\le a_i \\le n$, we can just leave it there and use it in the resulting permutation (if multiple $a_i$ satisfy $1 \\le a_i \\le n$ and have the same value, just choose one). Let's suppose in the optimal solution, we change $x$ to $y$ and change $z$ to $x$ for some $z > x > y$ ($x$, $y$, $z$ are values, not indices). Then changing $x$ to $x$ (i.e. doing nothing) and changing $z$ to $y$ uses $1$ less operation. And, if it is possible to change $z$ to $x$, then it must be possible to change $z$ to $y$. However, if it is not possible to change $z$ to $x$, it might still be possible to change $z$ to $y$. Therefore, the solution is as follows: Sort the array. For each element $i$ in the sorted array: If $1 \\le a_i \\le n$ and it is the first occurrence of element with value $a_i$, leave it there. If $1 \\le a_i \\le n$ and it is the first occurrence of element with value $a_i$, leave it there. Else, let the current least unassigned value in the resulting permutation be $m$, if $m < \\frac{a_i}{2}$, we can assign the current element to value $m$ and add the number of operations by $1$. Else, output $-1$ directly. Else, let the current least unassigned value in the resulting permutation be $m$, if $m < \\frac{a_i}{2}$, we can assign the current element to value $m$ and add the number of operations by $1$. Else, output $-1$ directly. The solution works in $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while(t>0){\n        t--;\n        int n;\n        cin >> n;\n        set<int> st;\n        for(int i=1;i<=n;i++){st.insert(i);}\n        vector<int> rem;\n        for(int i=0;i<n;i++){\n            int v;\n            cin >> v;\n            if(st.find(v)!=st.end()){st.erase(v);}\n            else{rem.push_back(v);}\n        }\n        sort(rem.begin(),rem.end());\n        reverse(rem.begin(),rem.end());\n        int pt=0;\n        bool err=false;\n        for(auto &nx : rem){\n            auto it=st.end();\n            it--;\n            int ctg=(*it);\n            if(ctg>(nx-1)/2){err=true;break;}\n            st.erase(it);\n        }\n        if(err){cout << \"-1\\n\";}\n        else{cout << rem.size() << '\\n';}\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1617",
    "index": "D1",
    "title": "Too Many Impostors (easy version)",
    "statement": "This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions.\n\nThere are $n$ players labelled from $1$ to $n$. \\textbf{It is guaranteed that $n$ is a multiple of $3$.}\n\nAmong them, there are $k$ impostors and $n-k$ crewmates. The number of impostors, $k$, is not given to you. \\textbf{It is guaranteed that $\\frac{n}{3} < k < \\frac{2n}{3}$.}\n\nIn each question, you can choose three distinct integers $a$, $b$, $c$ ($1 \\le a, b, c \\le n$) and ask: \"Among the players labelled $a$, $b$ and $c$, are there more impostors or more crewmates?\" You will be given the integer $0$ if there are more impostors than crewmates, and $1$ otherwise.\n\nFind the number of impostors $k$ and the indices of players that are impostors after asking at most $2n$ questions.\n\nThe jury is \\textbf{adaptive}, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.",
    "tutorial": "The weird constraint, $\\frac{n}{3} < k < \\frac{2n}{3}$, is crucial. If you know the index of one crewmate and one impostor, how to find the roles of other $n-2$ players in exactly $n-2$ queries? Query players ($1, 2, 3$), ($2, 3, 4$), $\\dots$, ($n-1, n, 1$), ($n, 1, 2$). After that, you can surely find out the index of one crewmate and one impostor. Try to find out how. Key observation: if result of query ($a, b, c$) $\\ne$ result of query ($b, c, d$), since $b$ and $c$ are common, players $a$ and $d$ have different roles. Additionally, if result of query ($a, b, c$) = $1$ then player $a$ is a crewmate (and player $d$ is an impostor), vice versa. The first step is to query players ($1, 2, 3$), ($2, 3, 4$), $\\dots$, ($n-1, n, 1$), ($n, 1, 2$). If the results of any two adjacent queries (or queries ($1, 2, 3$) and ($n, 1, 2$)) are different, we instantly know the roles of the two players that are only included in one query - one is a crewmate, one is an impostor. Since the number of impostors $k$ and crewmates $n-k$ satisfy $k > \\frac{n}{3}$ and $n - k > \\frac{n}{3}$, there must be one pair of adjacent queries that are different. After we know one crewmate and one impostor (let's call them $a$, $d$), we can query these two players with each one of the rest of the players. If a query ($a, d, x$) ($1 \\le x \\le n$, $x \\ne a$ and $x \\ne d$) returns $0$, player $x$ is an impostor, else player $x$ is a crewmate. In total, $2n-2$ queries are used.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    int N; \n    cin >> N;\n    int res[N];\n    for(int i=0; i<N; i++) {\n        cout << \"? \" << i + 1 << \" \" << (i+1) % N + 1 << \" \" << (i+2) % N + 1 << endl;\n        cin >> res[i];\n    }\n    vector<int> imp;\n    for(int i=0; i<N; i++) {\n        if(res[i] != res[(i+1) % N]) {\n            if(res[i] == 0) imp.push_back(i + 1);\n            else imp.push_back((i+3) % N + 1);\n            for(int j=0; j<N; j++) {\n                if(j != i && j != (i+3) % N) {\n                    cout << \"? \" << i + 1 << \" \" << (i+3) % N + 1 << \" \" << j + 1 << endl;\n                    int r;\n                    cin >> r;\n                    if(r == 0) imp.push_back(j + 1);\n                }\n            }\n            break;\n        }\n    }\n    cout << \"! \" << imp.size();\n    for(int x : imp) cout << \" \" << x;\n    cout << endl;\n}\nint main() {\n    int T;\n    cin >> T;\n    for(int i=1; i<=T; i++) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "interactive"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1617",
    "index": "D2",
    "title": "Too Many Impostors (hard version)",
    "statement": "This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions.\n\nThere are $n$ players labelled from $1$ to $n$. \\textbf{It is guaranteed that $n$ is a multiple of $3$.}\n\nAmong them, there are $k$ impostors and $n-k$ crewmates. The number of impostors, $k$, is not given to you. \\textbf{It is guaranteed that $\\frac{n}{3} < k < \\frac{2n}{3}$.}\n\nIn each question, you can choose three distinct integers $a$, $b$, $c$ ($1 \\le a, b, c \\le n$) and ask: \"Among the players labelled $a$, $b$ and $c$, are there more impostors or more crewmates?\" You will be given the integer $0$ if there are more impostors than crewmates, and $1$ otherwise.\n\nFind the number of impostors $k$ and the indices of players that are impostors after asking at most $n+6$ questions.\n\nThe jury is \\textbf{adaptive}, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.",
    "tutorial": "Aim to find an impostor and a crewmate's index in $\\frac{n}{3} + c$ queries, with $c$ being a small constant. Consider splitting the $n$ players into groups of $3$ (and query each group) in order to reach the goal in Hint 1. What is special about the results of the $\\frac{n}{3}$ queries? Firstly query ($1, 2, 3$), ($4, 5, 6$), $\\dots$, ($n-2, n-1, n$). Due to the constraint $\\frac{n}{3} < k < \\frac{2n}{3}$, among the results of these $\\frac{n}{3}$ queries, there must be at least one $0$ and one $1$. Now, let's call a tuple ($a, b, c$) that returns $0$ a $0$-majority tuple, and vice versa. From the easy version, notice that finding one crewmate and one impostor is very helpful in determining the roles of the remaining players. Let's make use of the above observation, and pick one adjacent $0$-majority tuple and $1$-majority tuple. Let's say we picked ($i, i+1, i+2$) and ($i+3, i+4, i+5$). Then, we query ($i+1, i+2, i+3$) and ($i+2, i+3, i+4$). Among the four queries ($i, i+1, i+2$), ($i+1, i+2, i+3$), ($i+2, i+3, i+4$), ($i+3, i+4, i+5$), there must be a pair of adjacent queries with different results. From the easy version, we can directly find the index of an impostor and a crewmate. In all the above cases, we end up knowing an impostor and a crewmate using $\\frac{n}{3} + 2$ queries, including the first step. You have the index of an impostor and a crewmate now, and around $\\frac{2n}{3}$ queries left. Consider using at most $2$ queries to find out roles of each player in each group of $3$ from Step 1, which should add up to $\\frac{2n}{3}$ queries. Make use of the information you know about each group (whether it is $0$-majority or $1$-majority). Assume a tuple (group of $3$) is $0$-majority. There are $4$ possibilities of roles of the $3$ players in the tuple, which are: impostor, impostor, impostor impostor, impostor, impostor crewmate, impostor, impostor (and its permutations) crewmate, impostor, impostor (and its permutations) In each query, reduce half of the possibilities. It remains to figure out how we can find the roles of the remaining players using $\\frac{2n}{3}$ queries. For each tuple ($i, i+1, i+2$) queried in the first step, let's assume the tuple is $0$-majority (because the other case can be solved similarly). Then, there are only four possibilities: All players $i$, $i+1$, $i+2$ are impostors. All players $i$, $i+1$, $i+2$ are impostors. Player $i$ is a crewmate, players $i+1$, $i+2$ are impostors. Player $i$ is a crewmate, players $i+1$, $i+2$ are impostors. Player $i+1$ is a crewmate, players $i$, $i+2$ are impostors. Player $i+1$ is a crewmate, players $i$, $i+2$ are impostors. Player $i+2$ is a crewmate, players $i$, $i+1$ are impostors. Player $i+2$ is a crewmate, players $i$, $i+1$ are impostors. Earlier, we found the index of a crewmate and an impostor, let the index of the crewmate be $a$ and the impostor be $b$. If the tuple ($i, i+1, a$) is $1$-majority, either player $i$ or player $i+1$ is a crewmate. So, we reduced the number of possibilities to $2$. To check which player is the crewmate, query it with $a$ and $b$ like we did in the easy version. Else, either there are no crewmates or player $i+2$ is a crewmate. So, we reduced the number of possibilities to $2$. To check the role of player $i+2$, query it with $a$ and $b$ like we did in the easy version. In both cases, we use $2$ queries for each initial tuple ($i, i+1, i+2$). So, we used $n + 2$ queries in total, but we gave you a bit more, in case you used some more queries to find a crewmate and an impostor. There is one corner case we should handle: if the tuple ($i, i+1, i+2$) contains $a$ or $b$, we can just naively query for each unknown role in the tuple, since we won't use more than $2$ queries anyway.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint query(int a, int b, int c) {\n    cout << \"? \" << a << ' ' << b << ' ' << c << endl;\n    int r; cin >> r;\n    return r;\n}\nvoid solve(int tc) {\n    int n; cin >> n;\n    int a[n+1], role[n+1];\n    for(int i=1; i+2<=n; i+=3) a[i] = query(i, i+1, i+2);\n    int imp, crew;\n    for(int i=1; i<=n; i++) role[i] = -1;\n    for(int i=1; i+5<=n; i+=3) {\n        if(a[i] != a[i+3]) {\n            a[i+1] = query(i+1, i+2, i+3), a[i+2] = query(i+2, i+3, i+4);\n            for(int j=i; j<i+3; j++) {\n                if(a[j] != a[j+1]) {\n                    if(a[j] == 0) {\n                        imp = j, crew = j+3;\n                        role[j] = 0, role[j+3] = 1;\n                    }\n                    else {\n                        imp = j+3, crew = j;\n                        role[j+3] = 0, role[j] = 1;\n                    }\n                }\n            }\n            break;\n        }\n    }\n    for(int i=1; i+2<=n; i+=3) {\n        if(i == imp || i+1 == imp || i+2 == imp || i == crew || i+1 == crew || i+2 == crew) {\n            for(int j=i; j<i+3; j++) {\n                if(role[j] == -1) {\n                    role[j] = query(imp, crew, j);\n                }\n            }\n        }\n        else if(a[i] == 0) {\n            if(query(i, i+1, crew) == 1) {\n                if(query(i, imp, crew) == 0) role[i] = 0, role[i+1] = 1;\n                else role[i] = 1, role[i+1] = 0;\n                role[i+2] = 0; \n            }\n            else {\n                role[i] = role[i+1] = 0;\n                role[i+2] = query(i+2, imp, crew);\n            }\n        }\n        else {\n            if(query(i, i+1, imp) == 0) {\n                if(query(i, imp, crew) == 0) role[i] = 0, role[i+1] = 1;\n                else role[i] = 1, role[i+1] = 0;\n                role[i+2] = 1; \n            }\n            else {\n                role[i] = role[i+1] = 1;\n                role[i+2] = query(i+2, imp, crew);\n            }\n        }\n    }\n    cout << \"! \";\n    queue<int> q;\n    for(int i=1; i<=n; i++) if(role[i] == 0) q.push(i);\n    cout << q.size();\n    while(q.size()) {\n        cout << \" \" << q.front();\n        q.pop();\n    }\n    cout << endl;\n}\nint main() {\n    int T; cin >> T;\n    for(int i=1; i<=T; i++) solve(i);\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "interactive",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1617",
    "index": "E",
    "title": "Christmas Chocolates",
    "statement": "Christmas is coming, Icy has just received a box of chocolates from her grandparents! The box contains $n$ chocolates. The $i$-th chocolate has a non-negative integer type $a_i$.\n\nIcy believes that good things come in pairs. Unfortunately, all types of chocolates are distinct (all $a_i$ are \\textbf{distinct}). Icy wants to make at least one pair of chocolates the same type.\n\nAs a result, she asks her grandparents to perform some chocolate exchanges. \\textbf{Before performing any chocolate exchanges}, Icy chooses two chocolates with indices $x$ and $y$ ($1 \\le x, y \\le n$, $x \\ne y$).\n\nIn a chocolate exchange, Icy's grandparents choose a non-negative integer $k$, such that $2^k \\ge a_x$, and change the type of the chocolate $x$ from $a_x$ to $2^k - a_x$ (that is, perform $a_x := 2^k - a_x$).\n\nThe chocolate exchanges will be stopped only when $a_x = a_y$. \\textbf{Note that other pairs of equal chocolate types do not stop the procedure.}\n\nIcy's grandparents are smart, so they would choose the sequence of chocolate exchanges that \\textbf{minimizes} the number of exchanges needed. Since Icy likes causing trouble, she wants to \\textbf{maximize} the minimum number of exchanges needed by choosing $x$ and $y$ appropriately. She wonders what is the optimal pair $(x, y)$ such that the minimum number of exchanges needed is maximized across all possible choices of $(x, y)$.\n\nSince Icy is not good at math, she hopes that you can help her solve the problem.",
    "tutorial": "Translate the problem into a graph problem. What feature of the graph is it asking about? Draw out the graph, for $a_i \\le 10$. What special property does the graph have? Any specific algorithm to solve the problem (in Hint 1)? In graph terms, the problem is as follows: in a graph with infinite nodes, two nodes $x$ and $y$ are connected if $x + y = 2^k$ for some $k \\ge 0$. Among $n$ special nodes, find the pair of nodes ($i, j$) with maximum shortest distance. Here comes the key observation: For any $i \\ge 1$, there exists only one $j$ ($0 \\le j < i$) such that $i + j = 2^k$ for some $k \\ge 0$. The proof is as follows: let's say that $0 \\le j_1, j_2 < i$, $j_1 \\ge j_2$, $i + j_1 = 2^{k_1}$, $i + j_2 = 2^{k_2}$. Then, $j_1 - j_2 = 2^{k_2} \\cdot (2^{k_1-k_2} - 1)$. So, $j_1 \\equiv j_2 \\pmod {2^{k_2}}$. Since $i \\le 2^{k_2}$, $j_1 = j_2$. Then, we realize we can build a graph as follows: add an edge between $x$ and $y$ ($x, y \\ge 0$) if $x + y = 2^k$ for some $k \\ge 0$. Because of the first key observation, the graph must be a tree. We can root the tree at node $0$. Our problem is equivalent to finding the pair of nodes which have maximum distance in a tree, which can be solved using the diameter of tree algorithm. We can't build the entire tree as it has $10^9 + 1$ nodes. Try to notice something about the depth of the tree, then think of how this could help us solve the problem (by building the tree, or otherwise). Since $0 \\le a_i \\le 10^9$, it is impossible to build the entire tree. A final observation is that: Consider any node $v$ with degree $\\ge 2$ in the tree, then $v > p_v$ and $p_v > p_{p_v}$, therefore $v + p_v > p_v + p_{p_v}$ ($p_x$ denotes the parent of node $x$ in the tree). Hence the depth of the tree is $\\lceil \\log(max(a_i)) \\rceil = 30$, since there are only $\\lceil \\log(max(a_i)) \\rceil$ possible $k$ ($0 \\le k < 30$) for the sum of two nodes connected by an edge. So, there are two ways to do it: the first way is to build parts of the tree: only the $n$ given nodes and the ancestors of the $n$ nodes. There will be at most $O(n \\log max(a_i))$ nodes, which should fit into the memory limit. The second way is to not build the tree at all, and calculate the LCA (Lowest Common Ancestor) of two nodes to find their distance. Since the depth of the tree is $30$, LCA of two nodes can be computed by simply checking every ancestor of both nodes. In both ways, the time complexity is $O(n \\log max(a_i))$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint f(int x){\n    for(int i=0;;i++){\n        if((1<<i)>=x){\n            return (1<<i)-x;\n        }\n    }\n}\n\nusing pi=pair<int,int>;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int n;\n    cin >> n;\n    map<int,pair<pi,pi>> mp;\n    priority_queue<int> pq;\n    for(int i=0;i<n;i++){\n        int v;\n        cin >> v;\n        pq.push(v);\n        mp[v].first=make_pair(0,i+1);\n    }\n    while(!pq.empty()){\n        int od=pq.top();pq.pop();\n        if((!pq.empty()) && od==pq.top()){continue;}\n        if(od!=1){\n            int nx=f(od);\n            pq.push(nx);\n            pi send=mp[od].first;\n            send.first++;\n            if(mp[nx].first<send){\n                mp[nx].second=mp[nx].first;\n                mp[nx].first=send;\n            }\n            else if(mp[nx].second<send){mp[nx].second=send;}\n        }\n    }\n    int ra=0,rb=0,rc=-1;\n    for(auto &nx : mp){\n        pair<pi,pi> tg=nx.second;\n        if(tg.first.second==0 || tg.second.second==0){continue;}\n        if(rc<tg.first.first+tg.second.first){\n            rc=tg.first.first+tg.second.first;\n            ra=tg.first.second;\n            rb=tg.second.second;\n        }\n    }\n    cout << ra << ' ' << rb << ' ' << rc << '\\n';\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "graphs",
      "implementation",
      "math",
      "number theory",
      "shortest paths",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1618",
    "index": "A",
    "title": "Polycarp and Sums of Subsequences",
    "statement": "Polycarp had an array $a$ of $3$ \\textbf{positive} integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $b$ of $7$ integers.\n\nFor example, if $a = \\{1, 4, 3\\}$, then Polycarp wrote out $1$, $4$, $3$, $1 + 4 = 5$, $1 + 3 = 4$, $4 + 3 = 7$, $1 + 4 + 3 = 8$. After sorting, he got an array $b = \\{1, 3, 4, 4, 5, 7, 8\\}.$\n\nUnfortunately, Polycarp lost the array $a$. He only has the array $b$ left. Help him to restore the array $a$.",
    "tutorial": "The order of elements in $a$ doesn't matter. If there is at least one correct array $a$, then we can sort it and get the answer in which $a_1 \\le a_2 \\le a_3$. Therefore, we can always find a sorted array. Suppose that $a_1 \\le a_2 \\le a_3$. Then $b_1 = a_1$, $b_2 = a_2$, $b_7 = a_1 + a_2 + a_3$. We can find $a_3$ as $b_7 - a_1 - a_2$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        vector <int> b(7);\n\n        for(int i = 0; i < 7; i++)\n            cin >> b[i];\n\n        cout << b[0] << ' ' << b[1] << ' ' << b[6] - b[0] - b[1] << endl;\n    }\n}",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1618",
    "index": "B",
    "title": "Missing Bigram",
    "statement": "Polycarp has come up with a new game to play with you. He calls it \"A missing bigram\".\n\nA bigram of a word is a sequence of two adjacent letters in it.\n\nFor example, word \"abbaaba\" contains bigrams \"ab\", \"bb\", \"ba\", \"aa\", \"ab\" and \"ba\".\n\nThe game goes as follows. First, Polycarp comes up with a word, consisting only of lowercase letters 'a' and 'b'. Then, he writes down all its bigrams on a whiteboard \\textbf{in the same order as they appear in the word}. After that, he wipes one of them off the whiteboard.\n\nFinally, Polycarp invites you to guess what the word that he has come up with was.\n\nYour goal is to find any word such that it's possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.\n\nThe tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.",
    "tutorial": "Consider a full sequence of bigrams for some word. The first bigram consists of letters $1$ and $2$ of the word. The second bigram consists of letters $2$ and $3$. The $i$-th bigram consists of letters $i$ and $i+1$. After one bigram is removed, there becomes two adjacent bigrams such that one consists of letters $i$ and $i+1$ and the other consists of letters $i+2$ and $i+3$. Thus, we can find the position of the removed bigram by looking for a pair of adjacent bigrams such that the second letter of the first one differs from the first letter of the second one. If there is no such pair, then the sequence of bigrams represents a valid word of length $n-1$. We can append it with any bigram that starts with the second letter of the last bigram to make it a valid word of length $n$. If there exists such a pair, then all letters of the word can be recovered. We can find the position of the removed bigram, determine the letters it consisted of and insert it into the sequence. After that, we have a full sequence of bigrams and we can restore the word from it. Overall complexity: $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ts = input().split()\n\tfor i in range(n - 3):\n\t\tif s[i][1] != s[i + 1][0]:\n\t\t\ts.insert(i + 1, s[i][1] + s[i + 1][0])\n\t\t\tbreak\n\telse:\n\t\ts.append(s[-1][1] + 'a')\n\tprint(s[0][0], end=\"\")\n\tfor i in range(n - 1):\n\t\tprint(s[i][1], end=\"\")\n\tprint()",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1618",
    "index": "C",
    "title": "Paint the Array",
    "statement": "You are given an array $a$ consisting of $n$ positive integers. You have to choose a positive integer $d$ and paint all elements into two colors. All elements which are divisible by $d$ will be painted red, and all other elements will be painted blue.\n\nThe coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of $d$ which yields a beautiful coloring, or report that it is impossible.",
    "tutorial": "What does it mean that no pair of adjacent elements should have the same color? It means that either all elements on odd positions are blue and all elements on even positions are red, or vice versa. So, we need to check these two cases. Let's try to solve a case when we have to find a number $d$ such that $a_1, a_3, \\dots$ are divisible by $d$, and $a_2, a_4, \\dots$ are not. What does it mean that $d$ divides all of the numbers $a_1, a_3, \\dots$? It means that $d$ divides the $gcd(a_1, a_3, \\dots)$, where $gcd$ represents the greatest common divisor. Let's calculate this $gcd$ using Euclidean algorithm or some built-in functions in $O(n + \\log A)$. Okay, now we need to check all divisors of the $gcd(a_1, a_3, \\dots)$ and find if any of them does not divide $a_2, a_4, \\dots$. So, we have to factorize $gcd$ and generate all of its divisors... or do we? In fact, if $gcd(a_1, a_3, \\dots)$ divides any of the numbers $a_2, a_4, \\dots$, then every divisor of $gcd$ also divides that number. So, the only two numbers we have to check as canditates for the answer are $gcd(a_1, a_3, \\dots)$ and $gcd(a_2, a_4, \\dots)$.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<long long> a(n);\n    for(int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n    }\n    vector<long long> g(a.begin(), a.begin() + 2);\n    for(int i = 0; i < n; i++)\n    {\n        g[i % 2] = __gcd(g[i % 2], a[i]);\n    }  \n    vector<bool> good(2, true);\n    for(int i = 0; i < n; i++)\n    {\n        good[i % 2] = good[i % 2] && (a[i] % g[(i % 2) ^ 1] > 0);\n    }   \n    long long ans = 0;\n    for(int i = 0; i < 2; i++)\n        if(good[i])\n            ans = max(ans, g[i ^ 1]);\n    cout << ans << endl;\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        solve();\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1618",
    "index": "D",
    "title": "Array and Operations",
    "statement": "You are given an array $a$ of $n$ integers, and another integer $k$ such that $2k \\le n$.\n\nYou have to perform \\textbf{exactly} $k$ operations with this array. In one operation, you have to choose two elements of the array (let them be $a_i$ and $a_j$; they can be equal or different, but \\textbf{their positions in the array must not be the same}), remove them from the array, and add $\\lfloor \\frac{a_i}{a_j} \\rfloor$ to your score, where $\\lfloor \\frac{x}{y} \\rfloor$ is the maximum integer not exceeding $\\frac{x}{y}$.\n\nInitially, your score is $0$. After you perform exactly $k$ operations, you add all the remaining elements of the array to the score.\n\nCalculate the minimum possible score you can get.",
    "tutorial": "It's kinda obvious that we have to choose the $k$ greatest elements of the array as the denominators in the operations: suppose we haven't chosen one of them, but have chosen a lesser element as a denominator; if we swap them, the total score won't decrease. It is a bit harder to prove that the numerators of the fractions should be the next $k$ greatest elements (the elements on positions from $n - 2k + 1$ to $n - k$ in sorted order). It can be proved as follows: each fraction we will get in such a way rounds down to either $1$ or to $0$, and if we choose a lesser element as a numerator, we can decrease a fraction from $1$ to $0$, but we'll increase the sum of elements that remain in the array, so this is not optimal. All that's left is to pair the numerators and denominators. A fraction with numerator equal to denominator rounds down to $1$, any other fraction will round down to $0$, so our goal is to minimize the number of fractions having the numerator equal to the denominator. It can be done by pairing the numbers into fractions in the following way: $\\frac{a_{n-2k+1}}{a_{n-k+1}}$, $\\frac{a_{n-2k+2}}{a_{n-k+2}}$, ..., $\\frac{a_{n-k}}{a_n}$ (assuming $a$ is sorted). So, the solution of the problem is the following: sort the array $a$, then calculate $\\sum \\limits_{i=1}^{n-2k} a_i + \\sum\\limits_{i=1}^{k} \\lfloor \\dfrac{a_{n-2k+i}}{a_{n-k+i}} \\rfloor$.",
    "code": "def solve():\n    n, k = map(int, input().split())\n    a = list(map(int, input().split()))\n\n    a = sorted(a)\n    cost = sum(a[0:n-2*k]) + sum(map(lambda x: a[x+n-2*k] // a[x+n-k], range(0, k)))\n    print(cost)\n    \nt = int(input())\nfor i in range(t):\n    solve()",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1618",
    "index": "E",
    "title": "Singers' Tour",
    "statement": "$n$ towns are arranged in a circle sequentially. The towns are numbered from $1$ to $n$ in clockwise order. In the $i$-th town, there lives a singer with a repertoire of $a_i$ minutes for each $i \\in [1, n]$.\n\nEach singer visited all $n$ towns in clockwise order, starting with the town he lives in, and gave exactly one concert in each town. In addition, in each town, the $i$-th singer got inspired and came up with a song that lasts $a_i$ minutes. The song was added to his repertoire so that he could perform it in the rest of the cities.\n\nHence, for the $i$-th singer, the concert in the $i$-th town will last $a_i$ minutes, in the $(i + 1)$-th town the concert will last $2 \\cdot a_i$ minutes, ..., in the $((i + k) \\bmod n + 1)$-th town the duration of the concert will be $(k + 2) \\cdot a_i$, ..., in the town $((i + n - 2) \\bmod n + 1)$ — $n \\cdot a_i$ minutes.\n\nYou are given an array of $b$ integer numbers, where $b_i$ is the total duration of concerts in the $i$-th town. Reconstruct any correct sequence of \\textbf{positive} integers $a$ or say that it is impossible.",
    "tutorial": "First, $b_i = a_i + 2 \\cdot a_{i - 1} + \\dots + i \\cdot a_1 + (i + 1) \\cdot a_n + \\dots n \\cdot a_{i + 1}$. Consider the sum $b_1 + b_2 + \\cdots + b_n$. If we substitute the formula of $b_i$ then for every $i = 1, 2, \\dots, n$ the coefficient at $a_i$ will be equal to $\\frac{n \\cdot (n + 1)}{2}$, so we can find the sum $S$ of all $a_i$: $S = a_1 + a_2 + \\dots + a_n$ is equal to $\\frac{2 \\cdot (b_1 + b_2 + \\dots + b_n)}{n \\cdot (n + 1)}$. If the sum of $b_i$ isn't divisible by $\\frac{n \\cdot (n + 1)}{2}$, then the answer is NO. Now let's consider the difference between two neighboring towns: $b_i - b_{(i + n - 2) \\mod n + 1} = a_{i - 1} + a_{i - 2} + \\dots + a_{i \\mod n + 1} - (n - 1) \\cdot a_i = S - a_i - (n - 1) \\cdot a_i = S - n \\cdot a_i$, so $a_i = \\frac{S - b_i + b_{(i + n - 2) \\mod n + 1}}{n}$. If the value of $a_i$ we found isn't a positive integer, then the answer if NO. Otherwise, we can find a single value of $a_i$ for every $i = 1, 2, \\dots n$. It's easy to see that these values are correct. Overall complexity: $O(n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing li = long long;\n\nconst int N = 50013;\n\nint b[N];\nint a[N];\n\nvoid solve() {\n    \n    int n;\n    cin >> n;\n\n    li sumb = 0;\n    for(int i = 0; i < n; i++) {\n        cin >> b[i];\n        sumb += b[i];\n    }\n\n    li d = n * 1ll * (n + 1) / 2;\n\n    if(sumb % d != 0) {\n        cout << \"NO\" << endl;\n        return;\n    }\n\n    li suma = sumb / d;\n\n    for(int i = n - 1; i >= 0; i--) {\n        li res = (b[i] - b[(i + 1) % n] + suma);\n        if(res % n != 0 || res <= 0) {\n            cout << \"NO\" << endl;\n            return;\n        }\n\n        a[(i + 1) % n] = res / n;\n    }\n\n    cout << \"YES\" << endl;\n    for(int i = 0; i < n; i++)\n        cout << a[i] << ' ';\n    cout << endl;\n}\n\nint main()\n{\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1618",
    "index": "F",
    "title": "Reverse",
    "statement": "You are given two positive integers $x$ and $y$. You can perform the following operation with $x$: write it in its binary form without leading zeros, add $0$ or $1$ to the right of it, reverse the binary form and turn it into a decimal number which is assigned as the new value of $x$.\n\nFor example:\n\n- $34$ can be turned into $81$ via one operation: the binary form of $34$ is $100010$, if you add $1$, reverse it and remove leading zeros, you will get $1010001$, which is the binary form of $81$.\n- $34$ can be turned into $17$ via one operation: the binary form of $34$ is $100010$, if you add $0$, reverse it and remove leading zeros, you will get $10001$, which is the binary form of $17$.\n- $81$ can be turned into $69$ via one operation: the binary form of $81$ is $1010001$, if you add $0$, reverse it and remove leading zeros, you will get $1000101$, which is the binary form of $69$.\n- $34$ can be turned into $69$ via two operations: first you turn $34$ into $81$ and then $81$ into $69$.\n\nYour task is to find out whether $x$ can be turned into $y$ after a certain number of operations (possibly zero).",
    "tutorial": "There are two main approaches to this problem. Approach $1$. Let's analyze how the binary representation of $x$ changes after the operation. If there are no zeroes at the end of it, appending $0$ just reverses the binary representation; if there are any trailing zeroes, we remove them and reverse the binary representation. If we append $1$, we just reverse the binary representation and add $1$ at the beginning. No matter which action we choose on the first step, the resulting binary representation will have $1$ at its beginning and $1$ at its end, so no bits can be removed from it (no zero from the resulting binary representation can become leading). It means that every number we can obtain from $x$ will have the following form: several ones (maybe none), then $s$, then several ones (again, maybe none), where $s$ is one of the following four strings: the binary representation of $x$ after appending $1$ in the first operation; the binary representation of $x$ after appending $0$ in the first operation; one of the aforementioned representations, but reversed. We can check that $y$ meets one of these four templates, but since we only considered the case when we apply at least one operation, we also have to verify if $x = y$. Approach $2$. Run something like implicit BFS or DFS to generate all possible values you can obtain, pruning when the length of the binary representation we get becomes too large (say, greater than $100$). Why does this work fast? As we have shown in our first approach, the numbers we can get from $x$ have a very specific form, and if we limit their lengths to $100$, we will consider only about $400$ different numbers. Note that if you try this approach, you have to store the obtained numbers in some associative data structure (I use a set of strings in my solution).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nstring go(string t)\n{\n    while(t.back() == '0') t.pop_back();\n    reverse(t.begin(), t.end());\n    return t;\n}\n\nstring to_bin(long long x)\n{\n    if(x == 0)\n        return \"\";\n    else\n    {\n        string s = to_bin(x / 2);\n        s.push_back(char('0' + x % 2));\n        return s;\n    }\n}\n\nint main()\n{\n    long long x, y;\n    cin >> x >> y;\n    set<string> used;\n    queue<string> q;\n    q.push(to_bin(x));\n    used.insert(to_bin(x));\n    while(!q.empty())\n    {\n        string k = q.front();\n        q.pop();\n        if(k.size() > 100) continue;\n        for(int i = 0; i < 2; i++)\n        {\n            string k2 = go(k + string(1, char('0' + i)));\n            if(!used.count(k2))\n            {\n                used.insert(k2);\n                q.push(k2);\n            }\n        }\n    }\n    if(used.count(to_bin(y)))\n        cout << \"YES\\n\";\n    else\n        cout << \"NO\\n\";\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1618",
    "index": "G",
    "title": "Trader Problem",
    "statement": "Monocarp plays a computer game (yet again!). This game has a unique trading mechanics.\n\nTo trade with a character, Monocarp has to choose one of the items he possesses and trade it for some item the other character possesses. Each item has an integer price. If Monocarp's chosen item has price $x$, then he can trade it for any item \\textbf{(exactly one item)} with price not greater than $x+k$.\n\nMonocarp initially has $n$ items, the price of the $i$-th item he has is $a_i$. The character Monocarp is trading with has $m$ items, the price of the $i$-th item they have is $b_i$. Monocarp can trade with this character as many times as he wants (possibly even zero times), each time exchanging one of his items with one of the other character's items according to the aforementioned constraints. Note that if Monocarp gets some item during an exchange, he can trade it for another item (since now the item belongs to him), and vice versa: if Monocarp trades one of his items for another item, he can get his item back by trading something for it.\n\nYou have to answer $q$ queries. Each query consists of one integer, which is the value of $k$, and asks you to calculate the maximum possible total cost of items Monocarp can have after some sequence of trades, assuming that he can trade an item of cost $x$ for an item of cost not greater than $x+k$ during each trade. Note that the queries are independent: the trades do not actually occur, Monocarp only wants to calculate the maximum total cost he can get.",
    "tutorial": "Suppose we have fixed the value of $k$, so we can trade an item with price $i$ for an item with price $j$ if $j \\in [0, i + k]$. We can see that it's never optimal to trade an item with higher price for an item with lower price, and we could just simulate the trading process as follows: try to find an item owned by Polycarp and a more expensive item owned by the other character which can be traded, repeat until we cannot find any suitable pair. Unfortunately, it is too slow. Instead, let's try to analyze: for a given value of $k$, how to verify that an item of price $x$ can be traded for an item of price $y$ (maybe not right away, but with intermediate trades)? You can build a graph of $n + m$ vertices representing items, where two vertices representing items with prices $x$ and $y$ are connected by an edge if and only if $|x - y| \\le k$. Then, the edges of the graph represent possible trades, and the paths in the graph represent sequences of trades. So, one item can be traded for another item (possibly with intermediate trades) if the vertices representing the items belong to the same component. For a fixed value of $k$, we can build this graph, find all of its components, calculate the number of Monocarp's items in each component and add this number of most expensive vertices from the component to the answer. There are two problems though. The first one is that the graph may have up to $O((n + m)^2)$ edges. But if we sort all items according to their prices, we are only interested in edges between vertices which represent adjacent items in sorted order, so the size of the graph is decreased to $O(n + m)$. Another problem is that there are multiple queries for different values of $k$. To handle it, we can sort the values of $k$ in ascending order and go in sorted order while maintaining the graph for the current value of $k$. A data structure like DSU or a method like small-to-large merging can be helpful to update the components as they merge. The last trick: to quickly recalculate the number of items Monocarp has in a component and the sum of most expensive several items, you can build two prefix sum arrays - one over the array storing the costs of the items, and another one over the array which stores values $1$ or $0$ depending on who owns the respective item (the items should still be considered in sorted order). Since each component is a segment of costs of items, prefix sums allow us to calculate the required values in $O(1)$. By the way, knowing that each component is a segment, we can get rid of the graph and the structure that stores it altogether and just maintain a set of segments of items representing the components.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nlong long get(const vector<int>& pcnt, const vector<long long>& psum, pair<int, int> seg)\n{\n    int L = seg.first;\n    int R = seg.second;\n    int cnt = pcnt[R] - pcnt[L];\n    return psum[R] - psum[R - cnt];\n}\n\nint main()\n{\n    int n, m, q;\n    scanf(\"%d %d %d\", &n, &m, &q);\n    vector<int> a(n), b(m);\n    for(int i = 0; i < n; i++)\n    {\n        scanf(\"%d\", &a[i]);\n    }\n    for(int i = 0; i < m; i++)\n    {\n        scanf(\"%d\", &b[i]);\n    }\n    vector<int> pcnt = {0};\n    vector<long long> psum = {0ll};\n    vector<pair<int, int>> order;\n    for(int i = 0; i < n; i++) order.push_back(make_pair(a[i], 1));\n    for(int i = 0; i < m; i++) order.push_back(make_pair(b[i], 0));\n    sort(order.begin(), order.end());\n    int z = n + m;\n    for(int i = 0; i < z; i++)\n    {\n        pcnt.push_back(pcnt.back() + order[i].second);\n        psum.push_back(psum.back() + order[i].first);\n    }\n    long long cur = 0;\n    for(int i = 0; i < n; i++)\n        cur += a[i];\n    set<pair<int, int>> segs;\n    for(int i = 0; i < z; i++)\n        segs.insert(make_pair(i, i + 1));\n    map<int, vector<int>> events;\n    for(int i = 0; i < z - 1; i++)\n        events[order[i + 1].first - order[i].first].push_back(i);\n    vector<pair<int, long long>> ans = {{0, cur}};\n    for(auto x : events)\n    {\n        int cost = x.first;\n        vector<int> changes = x.second;\n        for(auto i : changes)\n        {\n            auto itr = segs.upper_bound(make_pair(i, int(1e9)));\n            auto itl = prev(itr);\n            pair<int, int> pl = *itl;\n            pair<int, int> pr = *itr;\n            cur -= get(pcnt, psum, pl);\n            cur -= get(pcnt, psum, pr);\n            pair<int, int> p = make_pair(pl.first, pr.second);\n            cur += get(pcnt, psum, p);\n            segs.erase(pl);\n            segs.erase(pr);\n            segs.insert(p);\n        }\n        ans.push_back(make_pair(cost, cur));\n    }              \n    for(int i = 0; i < q; i++)\n    {\n        int k;\n        scanf(\"%d\", &k);\n        int pos = upper_bound(ans.begin(), ans.end(), make_pair(k + 1, -1ll)) - ans.begin() - 1;\n        printf(\"%lld\\n\", ans[pos].second);\n    }\n}",
    "tags": [
      "data structures",
      "dsu",
      "greedy",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1619",
    "index": "A",
    "title": "Square String?",
    "statement": "A string is called square if it is some string written twice in a row. For example, the strings \"aa\", \"abcabc\", \"abab\" and \"baabaa\" are square. But the strings \"aaa\", \"abaaab\" and \"abcdabc\" are not square.\n\nFor a given string $s$ determine if it is square.",
    "tutorial": "If the length of the given string $s$ is odd, then the answer is NO, since adding two strings cannot do that. Otherwise, let $n$ be the length of the string. Let's go through the first half of the string, comparing whether its first and $\\frac{n}{2} + 1$ characters are equal, its second and $\\frac{n}{2} + 2$ characters are equal, and so on. If the characters in any pair are not equal, the answer is NO, otherwise - YES.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        string s;\n        cin >> s;\n        bool ok = true;\n        if (s.length() % 2 == 0) {\n            forn(i, s.length() / 2)\n                if (s[i] != s[i + s.length() / 2])\n                    ok = false;\n        } else\n            ok = false;\n        cout << (ok ? \"YES\" : \"NO\") << endl;\n    }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1619",
    "index": "B",
    "title": "Squares and Cubes",
    "statement": "Polycarp likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: $1$, $4$, $8$, $9$, ....\n\nFor a given number $n$, count the number of integers from $1$ to $n$ that Polycarp likes. In other words, find the number of such $x$ that $x$ is a square of a positive integer number or a cube of a positive integer number (or both a square and a cube simultaneously).",
    "tutorial": "We'll search for positive integers not larger than $n$, and add their squares or cubes to the set if they don't exceed $n$. If $n = 10^9$, the maximum number Polycarp will like is $31622^2 = 999950884$, so the running time will be within the time limit. The answer to the problem is the length of the resulting set.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        set<int> a;\n        for (int i = 1; i * i <= n; i++)\n            a.insert(i * i);\n        for (int i = 1; i * i * i <= n; i++)\n            a.insert(i * i * i);\n        cout << a.size() << endl;\n    }\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1619",
    "index": "C",
    "title": "Wrong Addition",
    "statement": "Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers $a$ and $b$ using the following algorithm:\n\n- If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length.\n- The numbers are processed from right to left (that is, from the least significant digits to the most significant).\n- In the first step, she adds the last digit of $a$ to the last digit of $b$ and writes their sum in the answer.\n- At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the \\textbf{left} side of the answer.\n\nFor example, the numbers $a = 17236$ and $b = 3465$ Tanya adds up as follows:\n\n$$ \\large{ \\begin{array}{r} + \\begin{array}{r} 17236\\\\ 03465\\\\ \\end{array} \\\\ \\hline \\begin{array}{r} 1106911 \\end{array} \\end{array}} $$\n\n- calculates the sum of $6 + 5 = 11$ and writes $11$ in the answer.\n- calculates the sum of $3 + 6 = 9$ and writes the result to the left side of the answer to get $911$.\n- calculates the sum of $2 + 4 = 6$ and writes the result to the left side of the answer to get $6911$.\n- calculates the sum of $7 + 3 = 10$, and writes the result to the left side of the answer to get $106911$.\n- calculates the sum of $1 + 0 = 1$ and writes the result to the left side of the answer and get $1106911$.\n\nAs a result, she gets $1106911$.\n\nYou are given two positive integers $a$ and $s$. Find the number $b$ such that by adding $a$ and $b$ as described above, Tanya will get $s$. Or determine that no suitable $b$ exists.",
    "tutorial": "Let's compute the answer to the array $b$, where $b_ k$ is the digit at the $k$ position in the number we are looking for. Let $i$ be the position of the last digit in number $a$, $j$ be the position of the last digit in number $s$. Then denote $x = a_i$, $y = s_j$, and consider the cases: if $x \\le y$, then the sum of $a_i + b_i$ was exactly $s_i$, then $b_i = y - x$. if $x \\gt y$, then the sum $a_i + b_i$ was greater than $9$ and we need to look at the next digit of the number $s$. If there isn't one, we can't get the answer - we'll output -1. Otherwise we recalculate $y = 10 \\cdot s_{j - 1} + s_j$ and reduce $j$ by one. if now $y \\ge 10$ and $y \\le 18$, then $b_i = y - x$. Otherwise, we deduce -1, since we cannot get more than $9 + 9 = 18$ when adding two digits, and the cases where $a_i + b_i \\lt 10$ have already been considered before.",
    "code": "#include<bits/stdc++.h>\n#define len(s) (int)s.size()\nusing namespace std;\nusing ll = long long;\n \nvoid solve(){\n    ll a, s;\n    cin >> a >> s;\n    vector<int>b;\n    while(s){\n        int x = a % 10;\n        int y = s % 10;\n        if(x <= y) b.emplace_back(y - x);\n        else{\n            s /= 10;\n            y += 10 * (s % 10);\n            if(x < y && y >= 10 && y <= 19) b.emplace_back(y - x);\n            else{\n                cout << -1 << '\\n';\n                return;\n            }\n        }\n        a /= 10;\n        s /= 10;\n    }\n    if(a) cout << -1 << '\\n';\n    else{\n        while (b.back() == 0) b.pop_back();\n        for(int i = len(b) - 1; i >= 0; i--) cout << b[i];\n        cout << '\\n';\n    }\n}\n \nint main(){\n    ios_base ::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int t;\n    cin >> t;\n    while (t){\n        solve();\n        t--;\n    }\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1619",
    "index": "D",
    "title": "New Year's Problem",
    "statement": "Vlad has $n$ friends, for each of whom he wants to buy one gift for the New Year.\n\nThere are $m$ shops in the city, in each of which he can buy a gift for any of his friends. If the $j$-th friend ($1 \\le j \\le n$) receives a gift bought in the shop with the number $i$ ($1 \\le i \\le m$), then the friend receives $p_{ij}$ units of joy. The rectangular table $p_{ij}$ is given in the input.\n\nVlad has time to visit at most $n-1$ shops (where $n$ is the number of \\textbf{friends}). He chooses which shops he will visit and for which friends he will buy gifts in each of them.\n\nLet the $j$-th friend receive $a_j$ units of joy from Vlad's gift. Let's find the value $\\alpha=\\min\\{a_1, a_2, \\dots, a_n\\}$. Vlad's goal is to buy gifts so that the value of $\\alpha$ is as large as possible. In other words, Vlad wants to maximize the minimum of the joys of his friends.\n\nFor example, let $m = 2$, $n = 2$. Let the joy from the gifts that we can buy in the first shop: $p_{11} = 1$, $p_{12}=2$, in the second shop: $p_{21} = 3$, $p_{22}=4$.\n\nThen it is enough for Vlad to go only to the second shop and buy a gift for the first friend, bringing joy $3$, and for the second — bringing joy $4$. In this case, the value $\\alpha$ will be equal to $\\min\\{3, 4\\} = 3$\n\nHelp Vlad choose gifts for his friends so that the value of $\\alpha$ is as high as possible. Please note that each friend must receive one gift. Vlad can visit at most $n-1$ shops (where $n$ is the number of \\textbf{friends}). In the shop, he can buy any number of gifts.",
    "tutorial": "Note that if we cannot get joy $x$, then we cannot get $x+1$, and if we can get at least $x$, then we can get at least $x-1$. These facts allow us to use binary search to find the answer. Now we need to understand how exactly we can recognize whether we can gain joy at least $x$ or not. We can enter at most $n-1$ shops, so we always need to take two gifts from some store, which means there must be a store in which we can find two or more gifts with pleasure at least $x$. Also, each friend should receive a gift, which means that we should be able to buy each gift with pleasure at least $x$. It takes O (nm) to check that both of these conditions are met. The total solution works in O (nm  \\times  log (nm)).",
    "code": "//\n// Created by Vlad on 17.12.2021.\n//\n \n#include <bits/stdc++.h>\n \n#define int long long\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n \n/*#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"no-stack-protector\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native\")\n#pragma GCC optimize(\"fast-math\")\n*/\ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(143);\n \nconst int inf = 1e10;\nconst int M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-4;\n \nint n, m;\nvector<vector<int>> p;\n \nbool check(int x){\n    vector<bool> abl(m);\n    bool pair = false;\n    for(int i = 0; i < n; ++i){\n        int c = 0;\n        for(int j = 0; j < m; ++j){\n            if(p[i][j] >= x){\n                abl[j] = true;\n                c++;\n            }\n        }\n        if(c > 1) pair = true;\n    }\n    if(!pair && m > 1) return false;\n    bool ans = true;\n    for(bool b: abl){\n        ans = ans && b;\n    }\n    return ans;\n}\n \nvoid solve() {\n    cin >> n >> m;\n    p.assign(n, vector<int>(m));\n    for(int i = 0; i < n; ++i){\n        for(int j = 0; j < m; ++j){\n            cin >> p[i][j];\n        }\n    }\n    int l = 1, r = 2;\n    while (check(r)) r *= 2;\n    while (r - l > 1){\n        int mid = (r + l) / 2;\n        if(check(mid)) l = mid;\n        else r = mid;\n    }\n    cout << l;\n}\n \nbool multi = true;\n \nsigned main() {\n    //freopen(\"in.txt\", \"r\", stdin);\n    //freopen(\"in.txt\", \"w\", stdout);\n    int t = 1;\n    if (multi) {\n        cin >> t;\n    }\n    for (; t != 0; --t) {\n        solve();\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1619",
    "index": "E",
    "title": "MEX and Increments",
    "statement": "Dmitry has an array of $n$ non-negative integers $a_1, a_2, \\dots, a_n$.\n\nIn one operation, Dmitry can choose any index $j$ ($1 \\le j \\le n$) and increase the value of the element $a_j$ by $1$. He can choose the same index $j$ multiple times.\n\nFor each $i$ from $0$ to $n$, determine whether Dmitry can make the $\\mathrm{MEX}$ of the array equal to exactly $i$. If it is possible, then determine the minimum number of operations to do it.\n\nThe $\\mathrm{MEX}$ of the array is equal to the minimum non-negative integer that is not in the array. For example, the $\\mathrm{MEX}$ of the array $[3, 1, 0]$ is equal to $2$, and the array $[3, 3, 1, 4]$ is equal to $0$.",
    "tutorial": "First, let's sort the array. Then we will consider its elements in non-decreasing order. To make MEX equal to $0$, you need to increase all zeros. To make MEX at least $n$, you first need to make MEX at least $n - 1$, and then, if the number $n - 1$ is missing in the array, you need to get it. If there are no extra values less than $n - 1$, then this and all subsequent MEX values cannot be obtained. Otherwise, you can use the maximum of the extra array values. To do this, you can use a data structure such as a stack. If an element occurs more than once in the array, put its extra occurrences on the stack.",
    "code": "#include <iostream>\n#include <vector>\n#include <stack>\n#include <algorithm>\n \nusing namespace std;\n \ntypedef long long ll;\nconst int MAX_N = 2e5;\n \nint main() {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        int n;\n        cin >> n;\n        vector<int> a(n), cnt(n + 1);\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n            cnt[a[i]]++;\n        }\n        sort(a.begin(), a.end());\n        stack<int> st;\n        vector<ll> ans(n + 1, -1);\n        ll sum = 0;\n        for (int i = 0; i <= n; ++i) {\n            if (i > 0 && cnt[i - 1] == 0) {\n                if (st.empty()) {\n                    break;\n                }\n                int j = st.top();\n                st.pop();\n                sum += i - j - 1;\n            }\n            ans[i] = sum + cnt[i];\n            while (i > 0 && cnt[i - 1] > 1) {\n                cnt[i - 1]--;\n                st.push(i - 1);\n            }\n        }\n        for (ll x : ans) {\n            cout << x << ' ';\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1619",
    "index": "F",
    "title": "Let's Play the Hat?",
    "statement": "The Hat is a game of speedy explanation/guessing words (similar to Alias). It's fun. Try it! In this problem, we are talking about a variant of the game when the players are sitting at the table and everyone plays individually (i.e. not teams, but individual gamers play).\n\n$n$ people gathered in a room with $m$ tables ($n \\ge 2m$). They want to play the Hat $k$ times. Thus, $k$ games will be played at each table. Each player will play in $k$ games.\n\nTo do this, they are distributed among the tables for each game. During each game, one player plays at exactly one table. A player can play at different tables.\n\nPlayers want to have the most \"fair\" schedule of games. For this reason, they are looking for a schedule (table distribution for each game) such that:\n\n- At any table in each game there are either $\\lfloor\\frac{n}{m}\\rfloor$ people or $\\lceil\\frac{n}{m}\\rceil$ people (that is, either $n/m$ rounded down, or $n/m$ rounded up). Different numbers of people can play different games at the same table.\n- Let's calculate for each player the value $b_i$ — the number of times the $i$-th player played at a table with $\\lceil\\frac{n}{m}\\rceil$ persons ($n/m$ rounded up). Any two values of $b_i$must differ by no more than $1$. In other words, for any two players $i$ and $j$, it must be true $|b_i - b_j| \\le 1$.\n\nFor example, if $n=5$, $m=2$ and $k=2$, then at the request of the first item either two players or three players should play at each table. Consider the following schedules:\n\n- First game: $1, 2, 3$ are played at the first table, and $4, 5$ at the second one. The second game: at the first table they play $5, 1$, and at the second  — $2, 3, 4$. This schedule is \\textbf{not \"fair\"} since $b_2=2$ (the second player played twice at a big table) and $b_5=0$ (the fifth player did not play at a big table).\n- First game: $1, 2, 3$ are played at the first table, and $4, 5$ at the second one. The second game: at the first table they play $4, 5, 2$, and at the second one  — $1, 3$. This schedule is \\textbf{\"fair\"}: $b=[1,2,1,1,1]$ (any two values of $b_i$ differ by no more than $1$).\n\nFind any \"fair\" game schedule for $n$ people if they play on the $m$ tables of $k$ games.",
    "tutorial": "For each game, we want to seat $n$ people at $m$ tables, $n \\mod m$ of them will be big and $B = \\lceil\\frac{n}{m}\\rceil$ will sit at them, and $m - n \\mod m$ will be small. Each round $p = n \\mod m * B$ people will sit at the big tables. Let's put people with numbers $0, 1, 2 \\dots p - 1$ at large tables in the first round (for convenience we index from zero), and the rest for small ones, in the second round we will seat people at large tables with numbers $p \\mod n, (p + 1) \\mod n \\dots (2p - 1) \\mod n$ and so on. We cycle through the players from $1$ to $n$ in blocks of $p$. Since $p <n$, no one person can be ahead of any other by 2 or more large tables.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n, m, k;\n        cin >> n >> m >> k;\n        vector<int> p(n);\n        forn(i, n)\n            p[i] = i;\n        if (tt > 0)\n            cout << endl;\n        forn(round, k) {\n            int index = 0;\n            forn(table, m) {\n                int size = n / m;\n                if (table < n % m)\n                    size++;\n                cout << size;\n                forn(j, size)\n                    cout << \" \" << p[index++] + 1;\n                cout << endl;                        \n            }\n            rotate(p.begin(), p.begin() + (n % m) * ((n + m - 1) / m), p.end());\n        }\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1619",
    "index": "G",
    "title": "Unusual Minesweeper",
    "statement": "Polycarp is very fond of playing the game Minesweeper. Recently he found a similar game and there are such rules.\n\nThere are mines on the field, for each the coordinates of its location are known ($x_i, y_i$). Each mine has a lifetime in seconds, after which it will explode. After the explosion, the mine also detonates all mines vertically and horizontally at a distance of $k$ (two perpendicular lines). As a result, we get an explosion on the field in the form of a \"plus\" symbol ('\\textbf{+}'). Thus, one explosion can cause new explosions, and so on.\n\nAlso, Polycarp can detonate anyone mine every second, starting from zero seconds. After that, a chain reaction of explosions also takes place. Mines explode \\textbf{instantly} and also \\textbf{instantly} detonate other mines according to the rules described above.\n\nPolycarp wants to set a new record and asks you to help him calculate in what minimum number of seconds all mines can be detonated.",
    "tutorial": "Our first task is to separate mines into components. We will store in the hashmap $mapx$ at the $x$ coordinate all the $y$ coordinates where there is a mine. Let's do the same with the $mapy$ hashmap. Thus, going through the available arrays in $mapx$ and $mapy$, we connect adjacent elements into one component, if $|mapx[x][i] - mapx[x][i + 1]| <= k$, also with $mapy$. As a result, we have components, where if you detonate one mine in the $j$'s component, then all the mines belonging to this component will also explode. Further, we find a mine with a minimum timer in each component. Finding the minimum for each component, we store it conditionally in the array $a$. Now we know at what minimum time some component will explode if it is left unaffected. To answer, it remains to find in the sorted array $a$ such a minimum index $i$ $(0 \\le i \\le a.size - 1)$ that $max (a[i], a.size - i - 2)$ is min. And the general asymptotic behavior is $O(n log (n))$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nint k;\n \nmap <int, vector<int>> mx;\nmap <int, vector<int>> my;\nmap <pair<int ,int>, bool> used;\nmap <pair<int, int>, int> time_of;\n \nint dfs(int x, int y) {\n    used[{x, y}] = true;\n    int _min_ = time_of[{x, y}];\n \n    auto i = lower_bound(mx[x].begin(), mx[x].end(), y);\n    auto j = lower_bound(my[y].begin(), my[y].end(), x);\n \n    if (++i != mx[x].end() && !used[{x, *i}] && abs(*i - y) <= k) {\n        _min_ = min(_min_, dfs(x, *i));\n    }\n    --i;\n    if (i != mx[x].begin() && !used[{x, *(--i)}] && abs(*i - y) <= k) {\n        _min_ = min(_min_, dfs(x, *i));\n    }\n \n    if (++j != my[y].end() && !used[{*j, y}] && abs(*j - x) <= k) {\n        _min_ = min(_min_, dfs(*j, y));\n    }\n    --j;\n    if (j != my[y].begin() && !used[{*(--j), y}] && abs(*j - x) <= k) {\n        _min_ = min(_min_, dfs(*j, y));\n    }\n \n    return _min_;\n}\n \nvoid solve() {\n    mx.clear();\n    my.clear();\n    used.clear();\n \n    int n;\n    cin >> n >> k;\n    vector <pair<int, int>> a(n);\n    int x, y, timer;\n \n    for (int i = 0; i < n; ++i) {\n        cin >> x >> y >> timer;\n        a[i] = {x, y};\n        time_of[{x, y}] = timer;\n        mx[x].push_back(y);\n        my[y].push_back(x);\n    }\n    vector<int> res;\n \n    for (auto now: mx) {\n        sort(mx[now.first].begin(), mx[now.first].end());\n    }\n    for (auto now: my) {\n        sort(my[now.first].begin(), my[now.first].end());\n    }\n \n    for (auto now: a) {\n        if (!used[now]) {\n            res.push_back(dfs(now.first, now.second));\n        }\n    }\n    sort(res.begin(), res.end());\n \n    int ans = res.size() - 1;\n    for (int i = 0; i < res.size(); ++i) {\n        ans = min(ans, max((int)res.size() - i - 2, res[i]));\n    }\n    cout << ans << '\\n';\n}\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(nullptr); cout.tie(nullptr);\n    int tests;\n    cin >> tests;\n    forn(tt, tests) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "dsu",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1619",
    "index": "H",
    "title": "Permutation and Queries",
    "statement": "You are given a permutation $p$ of $n$ elements. A permutation of $n$ elements is an array of length $n$ containing each integer from $1$ to $n$ exactly once. For example, $[1, 2, 3]$ and $[4, 3, 5, 1, 2]$ are permutations, but $[1, 2, 4]$ and $[4, 3, 2, 1, 2]$ are not permutations. You should perform $q$ queries.\n\nThere are two types of queries:\n\n- $1$ $x$ $y$ — swap $p_x$ and $p_y$.\n- $2$ $i$ $k$ — print the number that $i$ will become if we assign $i = p_i$ $k$ times.",
    "tutorial": "Let's compute an array $a$ of $n$ integers - answers to all possible second-type queries with $k = Q$, $Q  \\approx  \\sqrt n$. Now, if we have to perform any second-type query, we can split it into at most $n / Q$ queries with $k = Q$ and at most $Q - 1$ queries with $k = 1$. Let's also compute an array $r$ of $n$ integers - reverse permutation. If $p_i = j$, then $r_j = i$. To perform any first-type query, we should recompute $p$, $r$ and $a$. We can swap $p_x$ and $p_y$ in the array $p$ and $r_{p_x}$ and $r_{p_y}$ in the array $r.$ No more than $2 \\cdot Q$ elements will be changed in the array $a$. These are elements with indexes $x, r_x, r_{r_x}, \\dots$($Q$ elements) and $y, r_y, r_{r_y}, \\dots$($Q$ elements). We can recompute $a_x$ and then assign $a_{r_x} = r_{a_x}$ and $x = r_x$ $Q - 1$ times. Similarly for $y$. Time complexity: $O((n+q)\\sqrt n)$.",
    "code": "#include <bits/stdc++.h>\n//#define int long long\n#define ld long double\n#define x first\n#define y second\n#define pb push_back\n \nusing namespace std;\nconst int Q = 100;\n \nint n, q, p[100005], r[100005], a[100005];\n \nint32_t main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n \n    cin >> n >> q;\n \n    for(int i = 0; i < n; i++)\n    {\n        cin >> p[i];\n        p[i]--;\n    }\n \n    for(int i = 0; i < n; i++)\n        r[p[i]] = i;\n \n    for(int i = 0; i < n; i++)\n    {\n        int x = i;\n \n        for(int j = 0; j < Q; j++)\n            x = p[x];\n \n        a[i] = x;\n    }\n \n    while(q--)\n    {\n        int t, x, y;\n        cin >> t >> x >> y;\n \n        if(t == 2)\n        {\n            x--;\n \n            while(y >= Q)\n            {\n                y -= Q;\n                x = a[x];\n            }\n \n            while(y--)\n                x = p[x];\n \n            cout << x + 1 << \"\\n\";\n        }\n        else\n        {\n            x--;\n            y--;\n \n            swap(r[p[x]], r[p[y]]);\n            swap(p[x], p[y]);\n \n            int ax = x;\n \n            for(int i = 0; i < Q; i++)\n                ax = p[ax];\n \n            int x2 = x;\n \n            for(int i = 0; i < Q; i++)\n            {\n                a[x] = ax;\n                x = r[x];\n                ax = r[ax];\n            }\n \n            swap(x, y);\n \n            ax = x;\n \n            for(int i = 0; i < Q; i++)\n                ax = p[ax];\n \n            x2 = x;\n \n            for(int i = 0; i < Q; i++)\n            {\n                a[x] = ax;\n                x = r[x];\n                ax = r[ax];\n            }\n        }\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1620",
    "index": "A",
    "title": "Equal or Not Equal",
    "statement": "You had $n$ positive integers $a_1, a_2, \\dots, a_n$ arranged in a circle. For each pair of neighboring numbers ($a_1$ and $a_2$, $a_2$ and $a_3$, ..., $a_{n - 1}$ and $a_n$, and $a_n$ and $a_1$), you wrote down: are the numbers in the pair equal or not.\n\nUnfortunately, you've lost a piece of paper with the array $a$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $a$ which is consistent with information you have about equality or non-equality of corresponding pairs?",
    "tutorial": "Let's look at a group of E: it's easy to see that each such a group is equal to the same number. Now, let's look at how these groups are distributed on the circle: If there are no N then all $a_i$ are just equal to each other. It's okay. If there is exactly one N then from one side, all of them are still in one group, so they should be equal, but from the other side, one pair should have different values. It's contradiction. If there are more than one N then all numbers are divided in several groups with different values. It's okay. As a result, array $a$ exists as long as the number of N isn't $1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    string s;\n    cin >> s;\n    cout << (count(s.begin(), s.end(), 'N') == 1 ? \"NO\\n\" : \"YES\\n\");\n  }\n} ",
    "tags": [
      "constructive algorithms",
      "dsu",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1620",
    "index": "B",
    "title": "Triangles on a Rectangle",
    "statement": "A rectangle with its opposite corners in $(0, 0)$ and $(w, h)$ and sides parallel to the axes is drawn on a plane.\n\nYou are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.\n\nYour task is to choose three points in such a way that:\n\n- exactly two of them belong to the same side of a rectangle;\n- the area of a triangle formed by them is maximum possible.\n\nPrint the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.",
    "tutorial": "The area of a triangle is equal to its base multiplied by its height divided by $2$. Let the two points that have to be on the same side of a rectangle form its base. To maximize it, let's choose such two points that are the most apart from each other - the first and the last in the list. Then the height will be determined by the distance from that side to the remaining point. Since there are points on all sides, the points on the opposite side are the furthest. Thus, the height is always one of $h$ or $w$, depending on whether we picked the horizontal or the vertical side. So we have to check four options to pick the side and choose the best answer among them.",
    "code": "for _ in range(int(input())):\n  w, h = map(int, input().split())\n  ans = 0\n  for i in range(4):\n    a = [int(x) for x in input().split()][1:]\n    ans = max(ans, (a[-1] - a[0]) * (h if i < 2 else w))\n  print(ans)",
    "tags": [
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1620",
    "index": "C",
    "title": "BA-String",
    "statement": "You are given an integer $k$ and a string $s$ that consists only of characters 'a' (a lowercase Latin letter) and '*' (an asterisk).\n\nEach asterisk should be replaced with several (from $0$ to $k$ inclusive) lowercase Latin letters 'b'. Different asterisk can be replaced with different counts of letter 'b'.\n\nThe result of the replacement is called a BA-string.\n\nTwo strings $a$ and $b$ are different if they either have different lengths or there exists such a position $i$ that $a_i \\neq b_i$.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.\n\nNow consider all different BA-strings and find the $x$-th lexicographically smallest of them.",
    "tutorial": "Find all segments of asterisks in the string. Let there be $t$ of them, and the number of asterisks in them be $c_1, c_2, \\dots, c_t$. That tells us that the $i$-th segment of asterisks can be replaced with at most $c_i \\cdot k$ letters 'b'. Notice that we can compare two strings lexicographically using just the number of letters 'b' that replace each of $t$ segments of asterisks. Let that sequence for some string $a$ be $A_1, A_2, \\dots, A_t$ and that sequence for some string $b$ be $B_1, B_2, \\dots, B_t$. Then $a < b$ if and only if $A < B$. That is, there exists such position $i$ that $A_i < B_i$. The proof is trivial. So we can actually look at the sequence $A_1, A_2, \\dots, A_t$ as some kind of number in a mixed base. The lowest \"digit\" $A_t$ can be of one of $c_t \\cdot k + 1$ values (from $0$ to $c_t \\cdot k$). The second lowest - one of $c_{t-1} \\cdot k + 1$. And so on. Then, comparison of two strings is the same as comparison of these two mixed base numbers. Thus, the task is to convert number $x-1$ to this mixed base. Turns out, it's not that hard. In base $10$, for example, the lowest digit can be determined as the remainder of the number of dividing by $10$. Here it will be the remainder of dividing by $c_t \\cdot k + 1$. After that, divide and floor the number and proceed to the next \"digit\". After $t$ steps are done, the \"digits\" of that mixed base number tell exactly how many letters 'b' should replace each segment of asterisks. Overall complexity: $O(n)$ per testcase to recover the string, $O(nk)$ to print it.",
    "code": "for _ in range(int(input())):\n  n, k, x = map(int, input().split())\n  x -= 1\n  s = input()[::-1]\n  res = []\n  i = 0\n  while i < n:\n    if s[i] == 'a':\n      res.append(s[i])\n    else:\n      j = i\n      while j + 1 < n and s[j + 1] == s[i]:\n        j += 1\n      cur = (j - i + 1) * k + 1\n      res.append('b' * (x % cur))\n      x //= cur\n      i = j\n    i += 1\n  print(''.join(res[::-1]))",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1620",
    "index": "D",
    "title": "Exact Change",
    "statement": "One day, early in the morning, you decided to buy yourself a bag of chips in the nearby store. The store has chips of $n$ different flavors. A bag of the $i$-th flavor costs $a_i$ burles.\n\nThe store may run out of some flavors, so you'll decide which one to buy after arriving there. But there are two major flaws in this plan:\n\n- you have only coins of $1$, $2$ and $3$ burles;\n- since it's morning, the store will ask you to pay in exact change, i. e. if you choose the $i$-th flavor, you'll have to pay exactly $a_i$ burles.\n\nCoins are heavy, so you'd like to take the least possible number of coins in total. That's why you are wondering: what is the minimum total number of coins you should take with you, so you can buy a bag of chips of any flavor in exact change?",
    "tutorial": "Let's define $m = \\max(a_i)$, then it should be obvious that we need at least $r = \\left\\lceil \\frac{m}{3} \\right\\rceil$ coins to buy a bag of chips of cost $m$. Now, it's not hard to prove that $r + 1$ coins is always enough to buy a bag of chips of any cost $c \\le m$. Proof: if $m \\equiv 0 \\pmod 3$, we'll take $r - 1$ coins of value $3$, coin $1$ and coin $2$; if $m \\equiv 2 \\pmod 3$, we'll take $r - 1$ coins $3$ and two coins $1$; if $m \\equiv 1 \\pmod 3$, we'll take $r - 2$ coins $3$, one coin $2$ and two coins $1$. So the question is how to decide, is $r$ coins enough. The solution is to note that there is no need to take more than $3$ coins $1$ and more than $3$ coins $2$, so we can just brute force the number of coins $1$ we'll take $c_1$ and the number of coins $2$ we'll take $c_2$. Then, the number of coins $3$ $c_3 = \\left\\lceil \\frac{m - c_1 - 2 c_2}{3} \\right\\rceil$, and we can check: is it possible to pay exactly $a_i$ using at most $c_1$, $c_2$ and $c_3$ coins respectively. There exists casework solution as well, but it's quite tricky, so brute force is preferable. The main problem for case work is the case $m \\equiv 1 \\pmod 3$, since there are two different ways to take $r$ coins: either $r - 1$ coins $3$ and coin $1$ or $r - 2$ coins $3$ and two coins $2$. In the first way, you can't gather exactly $a_i \\equiv 2 \\pmod 3$ and in the second one, you can gather neither $a_i = m - 1$ nor $a_i = 1$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n  return out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n  fore(i, 0, sz(v)) {\n    if(i) out << \" \";\n    out << v[i];\n  }\n  return out;\n}\n\nint n;\nvector<int> a;\n\ninline bool read() {\n  if(!(cin >> n))\n    return false;\n  a.resize(n);\n  fore (i, 0, n)\n    cin >> a[i];\n  return true;\n}\n\nbool p(int val, int c1, int c2, int c3) {\n  fore (cur1, 0, c1 + 1) fore (cur2, 0, c2 + 1) {\n    if (cur1 + 2 * cur2 > val)\n      continue;\n    if ((val - cur1 - 2 * cur2) % 3 != 0)\n      continue;\n    if ((val - cur1 - 2 * cur2) / 3 <= c3)\n      return true;\n  }\n  return false;\n}\n\nbool possible(int c1, int c2, int c3) {\n  for (int v : a) {\n    if (!p(v, c1, c2, c3))\n      return false;\n  }\n  return true;\n}\n\ninline void solve() {\n  int m = *max_element(a.begin(), a.end());\n  int ans = int(1e9);\n  \n  const int MAG = 3;\n  fore (c1, 0, MAG) fore (c2, 0, MAG) {\n    int c3 = max(0, (m - c1 - 2 * c2 + 2) / 3);\n    assert(c1 + 2 * c2 + 3 * c3 >= m);\n    \n    if (possible(c1, c2, c3))\n      ans = min(ans, c1 + c2 + c3);\n  }\n  cout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n  freopen(\"input.txt\", \"r\", stdin);\n#endif\n  int t; cin >> t;\n  while(t--) {\n    read();\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1620",
    "index": "E",
    "title": "Replace the Numbers",
    "statement": "You have an array of integers (initially empty).\n\nYou have to perform $q$ queries. Each query is of one of two types:\n\n- \"$1$ $x$\" — add the element $x$ to the end of the array;\n- \"$2$ $x$ $y$\" — replace all occurrences of $x$ in the array with $y$.\n\nFind the resulting array after performing all the queries.",
    "tutorial": "Let's solve the problem from the end. Let's maintain the array $p_x$ - what number will $x$ become if we apply to it all the already considered queries of type $2$. If the current query is of the first type, then we simply add $p_x$ to the resulting array. If the current query is of the second type, then we have to change the value of $p_x$. Since all occurrences of $x$ must be replaced with $y$, it is enough to assign $p_x = p_y$. Since we process each query in $O(1)$, the final complexity is $O(n)$. There is also an alternative solution. Let's process queries in the direct order. Let's store all its positions in an array for each number. Then for the first query, it is enough to put the index in the corresponding array of positions. And for a query of the second type, we have to move all the positions of the number $x$ into an array of positions of the number $y$. The naive implementation is obviously too slow, but we can use the small to large method, then the complexity of the solution will be $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 500 * 1000 + 13;\n\nint n, q;\nvector<int> pos[N];\n\nint main() {\n  scanf(\"%d\", &q);\n  while (q--) {\n    int t, x, y;\n    scanf(\"%d\", &t);\n    if (t == 1) {\n      scanf(\"%d\", &x);\n      pos[x].push_back(n++);\n    } else {\n      scanf(\"%d%d\", &x, &y);\n      if (x != y) {\n        if (pos[x].size() > pos[y].size()) pos[x].swap(pos[y]);\n        for (int &i : pos[x]) pos[y].push_back(i);\n        pos[x].clear();\n      }\n    }\n  }\n  vector<int> ans(n);\n  for (int x = 0; x < N; ++x)\n    for (int &i : pos[x]) \n      ans[i] = x;\n  for (int &x : ans) printf(\"%d \", x);\n} ",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dsu",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1620",
    "index": "F",
    "title": "Bipartite Array",
    "statement": "You are given a permutation $p$ consisting of $n$ integers $1, 2, \\dots, n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once).\n\nLet's call an array $a$ bipartite if the following undirected graph is bipartite:\n\n- the graph consists of $n$ vertices;\n- two vertices $i$ and $j$ are connected by an edge if $i < j$ and $a_i > a_j$.\n\nYour task is to find a bipartite array of integers $a$ of size $n$, such that $a_i = p_i$ or $a_i = -p_i$, or report that no such array exists. If there are multiple answers, print any of them.",
    "tutorial": "To begin with, let's understand that an array is bipartite if and only if there is no decreasing subsequence of length $3$ in the array. Now we can write dynamic programming $dp_{i, x, y}$: is there an array $a$ of length $i$ such that $x$ is the maximum last element of a decreasing subsequence of length $1$, and $y$ is the maximum last element of a subsequence of length $2$. Note that $x > y$. Let's consider all possible transitions from the state $(i, x, y)$ if we are trying to put the number $z$ on the $i$-th position, where $z = \\pm p_i$: if $z > x$, then the new state will be $(i +1, z,y)$; if $z > y$, then the new state will be $(i + 1, x, z)$; if $z < y$, then such a transition is not valid, because a decreasing subsequence of length $3$ is formed in the array. With a naive implementation, such dynamic programming works in $O(n^3)$. We can note that for fixed values of $i$ and $x$ ($i$ and $y$) it is enough for us to store only the minimum available value of $y$ ($x$). So, we can write dynamic programming $dp_{i, x}$, which is defined similarly to the above, but now instead of being Boolean, stores the minimum value of $y$ (or infinity if the state is not valid). We have speeded up our solution to $O(n^2)$, but it is still too slow. To speed up the solution even more, we have to look at the transitions in dynamics and notice that for a fixed $i$, either $x$ or $y$ is always equal to $\\pm p_{i - 1}$. So we can rewrite our dynamic programming in the following form - $dp_{i, pos, sign}$. Here, the $pos$ flag says which of the numbers $x$ and $y$ is equal to $\\pm p_{i - 1}$, and the $sign$ flag is responsible for the sign of $p_{i - 1}$, and the minimum value of $y$ or $x$ is stored in the value itself (depending on $pos$). Thus, we got a solution with a linear running time. In fact, this solution can be simplified if we see the following relation: the number we use on position $i$ is not less than $dp_{i, 0, sign}$ and not greater than $dp_{i, 1, sign}$. This allows us to get rid of one of the states in our dynamic programming altogether, so we get an easier solution. This optimization wasn't required to get AC, but the code becomes shorter.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int INF = 1e9;\nconst int N = 1000 * 1000 + 13;\n\nint n;\nint p[N], a[N];\nint dp[N][2], pr[N][2];\n\nvoid solve() {\n  scanf(\"%d\", &n);\n  forn(i, n) scanf(\"%d\", &p[i]);\n  forn(i, n) forn(j, 2) dp[i][j] = INF;\n  dp[0][0] = dp[0][1] = -INF;\n  forn(i, n - 1) forn(j, 2) if (dp[i][j] != INF) {\n    int x = j ? -p[i] : p[i];\n    int y = dp[i][j];\n    if (x < y) swap(x, y);\n    forn(nj, 2) {\n      int z = nj ? -p[i + 1] : p[i + 1];\n      if (z > x) {\n        if (dp[i + 1][nj] > y) {\n          dp[i + 1][nj] = y;\n          pr[i + 1][nj] = j;\n        }\n      } else if (z > y)  {\n        if (dp[i + 1][nj] > x) {\n          dp[i + 1][nj] = x;\n          pr[i + 1][nj] = j;\n        }\n      }\n    }\n  }\n  int j = -1;\n  forn(i, 2) if (dp[n - 1][i] != INF) j = i;\n  if (j == -1) {\n    puts(\"NO\");\n    return;\n  }\n  for (int i = n - 1; i >= 0; i--) {\n    a[i] = j ? -p[i] : p[i];\n    j = pr[i][j];\n  }\n  puts(\"YES\");\n  forn(i, n) printf(\"%d \", a[i]);\n  puts(\"\");\n}\n\nint main() {\n  int t;\n  scanf(\"%d\", &t);\n  while (t--) solve();\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1620",
    "index": "G",
    "title": "Subsequences Galore",
    "statement": "For a sequence of strings $[t_1, t_2, \\dots, t_m]$, let's define the function $f([t_1, t_2, \\dots, t_m])$ as the number of different strings (\\textbf{including the empty string}) that are subsequences of \\textbf{at least one} string $t_i$. $f([]) = 0$ (i. e. the number of such strings for an empty sequence is $0$).\n\nYou are given a sequence of strings $[s_1, s_2, \\dots, s_n]$. Every string in this sequence consists of lowercase Latin letters and is \\textbf{sorted} (i. e., each string begins with several (maybe zero) characters a, then several (maybe zero) characters b, ..., ends with several (maybe zero) characters z).\n\nFor each of $2^n$ subsequences of $[s_1, s_2, \\dots, s_n]$, calculate the value of the function $f$ modulo $998244353$.",
    "tutorial": "For a string $t$, let's define its characteristic mask as the mask of $n$ bits, where $i$-th bit is $1$ if and only if $t$ is a subsequence of $s_i$. Let's suppose we somehow calculate the number of strings for each characteristic mask, and we denote this as $G(x)$ for a mask $x$. How can we use this information to find $f([s_{i_1}, s_{i_2}, \\dots, s_{i_k}])$? Suppose this set of strings is represented by a mask $x$, then the strings which are not included in $f$ are the strings such that their characteristic mask has bitwise AND with $x$ equal to $0$, i. e. these characteristic masks are submasks of $2^n - 1 \\oplus x$. We can use SOS DP to calculate these sums of $G(x)$ over submasks in $O(2^n n)$. The only problem is how to calculate $G(x)$ for every mask. Let's analyze when a string is a subsequence of a sorted string $s_i$. The subsequence should be sorted as well, and the number of occurrences of every character in a subsequence should not exceed the number of occurrences of that character in $s_i$. So, if there are $c_1$ characters a in $s_i$, $c_2$ characters b in $s_i$, and so on, then the number of its subsequences is $\\prod \\limits_{j=1}^{26} (1 + c_j)$. What about subsequences of every string from a set? These conditions on the number of occurrences should apply to every string in the set, so, for each character, we can calculate the minimum number of occurrences of this character in each string of the set, add $1$, and multiply these numbers to get the number of strings that are subsequences of each string in a set. These values can be calculated in $O(2^n (n + A))$ for all $2^n$ subsequences of $[s_1, s_2, \\dots, s_n]$ using recursive approach. Can these numbers be used as $G(x)$? Not so fast. Unfortunately, these values (let's call them $H(x)$) are the numbers of subsequences of the chosen sets of strings, but we have no information about the strings that are not included in the chosen set of strings. To handle it, we can use the following equation: $H(x) = \\sum \\limits_{x \\subseteq y} G(y)$, where $x \\subseteq y$ means that $x$ is a submask of $y$. To transform the values of $H(x)$ into the values of $G(x)$, we can flip all bits in the masks (so $H(x)$ is the sum of $G(y)$ over all submasks of $x$), apply inverse SOS DP (also known as Mobius transformation), and then flip all bits in the masks again. So, we found a way to calculate all values of $G(x)$ in $O(2^n (n + A))$, and we have already discussed what to do with them in the first paragraph of the editorial. The overall complexity of the solution is $O(2^n (n+A))$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 23;\nconst int A = 26;\nconst int S = 20043;\nint n;\nstring inp[N];\nchar buf[S];\nint cnt[N][A];\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint sub(int x, int y)\n{\n    return add(x, -y);\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nvoid flip_all(vector<int>& a)\n{\n    int msk = (1 << n) - 1;\n    for(int i = 0; i < (1 << (n - 1)); i++)\n        swap(a[i], a[i ^ msk]);\n}\n\nint val[S];\nint* where[S];\nint cur = 0;\n\nvoid change(int& x, int y)\n{\n    where[cur] = &x;\n    val[cur] = x;\n    x = y;\n    cur++;\n}\n\nvoid rollback()\n{\n    --cur;\n    (*where[cur]) = val[cur];\n}\n\nvoid zeta_transform(vector<int>& a)\n{\n    for(int i = 0; i < n; i++)\n    {\n        for(int j = 0; j < (1 << n); j++)\n            if((j & (1 << i)) == 0)\n                a[j ^ (1 << i)] = add(a[j ^ (1 << i)], a[j]);\n    }\n}                     \n\nvoid mobius_transform(vector<int>& a)\n{\n    for(int i = n - 1; i >= 0; i--)\n    {\n        for(int j = (1 << n) - 1; j >= 0; j--)\n            if((j & (1 << i)) != 0)\n                a[j] = sub(a[j], a[j ^ (1 << i)]);\n    }\n}\n\nint cur_max[A];\nvector<int> mask_cnt;\n\nvoid rec(int depth, int mask)\n{\n    if(depth == n)\n    {\n        mask_cnt[mask] = 1;\n        for(int i = 0; i < A; i++)\n            mask_cnt[mask] = mul(mask_cnt[mask], cur_max[i] + 1);\n    }\n    else\n    {\n        int state = cur;\n        for(int i = 0; i < A; i++)\n            change(cur_max[i], min(cur_max[i], cnt[depth][i]));\n        rec(depth + 1, mask + (1 << depth));\n        while(state != cur) rollback();\n        rec(depth + 1, mask);\n    }   \n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++)\n    {\n        scanf(\"%s\", buf);\n        inp[i] = buf;\n        for(auto x : inp[i])\n            cnt[i][x - 'a']++;\n    }\n\n    for(int i = 0; i < A; i++)\n        cur_max[i] = S;\n    mask_cnt.resize(1 << n);\n    rec(0, 0);\n    flip_all(mask_cnt);\n    mobius_transform(mask_cnt);\n    flip_all(mask_cnt);\n    int sum = 0;\n    for(int i = 0; i < (1 << n); i++) sum = add(sum, mask_cnt[i]);\n    zeta_transform(mask_cnt);\n    vector<int> res(1 << n);\n    for(int i = 0; i < (1 << n); i++)\n        res[i] = sub(sum, mask_cnt[((1 << n) - 1) ^ i]);\n\n    long long ans = 0;\n\n    for(int i = 0; i < (1 << n); i++)\n    {\n        int c = 0, s = 0;\n        for(int j = 0; j < n; j++)\n        {\n            if(i & (1 << j))\n            {\n                c++;\n                s += j + 1;\n            }   \n        }\n        ans ^= res[i] * 1ll * c * 1ll * s;\n    }\n\n    //for(int i = 0; i < (1 << n); i++) printf(\"%d\\n\", res[i]);\n    printf(\"%lld\\n\", ans);\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1621",
    "index": "A",
    "title": "Stable Arrangement of Rooks",
    "statement": "You have an $n \\times n$ chessboard and $k$ rooks. Rows of this chessboard are numbered by integers from $1$ to $n$ from top to bottom and columns of this chessboard are numbered by integers from $1$ to $n$ from left to right. The cell $(x, y)$ is the cell on the intersection of row $x$ and collumn $y$ for $1 \\leq x \\leq n$ and $1 \\leq y \\leq n$.\n\nThe arrangement of rooks on this board is called good, if no rook is beaten by another rook.\n\nA rook beats all the rooks that shares the same row or collumn with it.\n\nThe \\textbf{good} arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the \\textbf{good} arrangement is stable. Here, adjacent cells are the cells \\textbf{that share a side}.\n\n\\begin{center}\n{\\small Such arrangement of $3$ rooks on the $4 \\times 4$ chessboard is good, but it is not stable: the rook from $(1, 1)$ can be moved to the adjacent cell $(2, 1)$ and rooks on cells $(2, 1)$ and $(2, 4)$ will beat each other.}\n\\end{center}\n\nPlease, find any stable arrangement of $k$ rooks on the $n \\times n$ chessboard or report that there is no such arrangement.",
    "tutorial": "It is easy to see that if there are two rooks in the neighbouring rows we can move one of them to the another of these two rows, so there shouldn't be two rooks in the neighbouring rows in a stable arrangement. Let's split chessboard into $\\lceil \\frac{n}{2} \\rceil$ regions in the following way: region $1$ contains all cells of rows $1$, $2$, region $2$ contains all cells of rows $3$, $4$ and so on. The last region can contain cells of only one row if $n$ is odd. We had shown that there can't be two rooks in one region so if $k > \\lceil \\frac{n}{2} \\rceil = \\lfloor \\frac{n+1}{2} \\rfloor$ there is no stable arrangement. We can always place $k \\leq \\lfloor \\frac{n+1}{2} \\rfloor$ rooks into cells $(1, 1)$, $(3, 3)$, $\\ldots$, $(2k-1, 2k-1)$. Such arrangement is stable because after moving any rook to the neighbouring row it will be in the same collumn and in the even numbered row where there are no other rooks. The same applies for moving rook to the neighbouring collumn. Actually, we can show that condition from the first paragraph combined with the same condition for collumns is sufficient and necessary criterion for stable placement.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        int n, k;\n        cin >> n >> k;\n        if (k > (n + 1) / 2)\n        {\n            cout << \"-1\\n\";\n            continue;\n        }\n        vector<string> s(n, string(n, '.'));\n        for (int i = 0; i < k; i++)\n            s[2 * i][2 * i] = 'R';\n        for (int i = 0; i < n; i++)\n            cout << s[i] << \"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1621",
    "index": "B",
    "title": "Integers Shop",
    "statement": "The integers shop sells $n$ segments. The $i$-th of them contains all integers from $l_i$ to $r_i$ and costs $c_i$ coins.\n\nTomorrow Vasya will go to this shop and will buy some segments there. He will get all integers that appear in at least one of bought segments. The total cost of the purchase is the sum of costs of all segments in it.\n\nAfter shopping, Vasya will get some more integers as a gift. He will get integer $x$ as a gift if and only if all of the following conditions are satisfied:\n\n- Vasya hasn't bought $x$.\n- Vasya has bought integer $l$ that is less than $x$.\n- Vasya has bought integer $r$ that is greater than $x$.\n\nVasya can get integer $x$ as a gift only once so he won't have the same integers after receiving a gift.\n\nFor example, if Vasya buys segment $[2, 4]$ for $20$ coins and segment $[7, 8]$ for $22$ coins, he spends $42$ coins and receives integers $2, 3, 4, 7, 8$ from these segments. He also gets integers $5$ and $6$ as a gift.\n\nDue to the technical issues only the first $s$ segments (that is, segments $[l_1, r_1], [l_2, r_2], \\ldots, [l_s, r_s]$) will be available tomorrow in the shop.\n\nVasya wants to get (to buy or to get as a gift) as many integers as possible. If he can do this in differents ways, he selects the cheapest of them.\n\nFor each $s$ from $1$ to $n$, find how many coins will Vasya spend if only the first $s$ segments will be available.",
    "tutorial": "Let $L$ be the minimum integer Vasya will buy and $R$ be the maximum integer Vasya will buy. Then it is easy to see that he will get all integers between $L$ and $R$ and only them after receiving a gift. Because Vasya wants to maximise the number of integers he will get, he should buy the smallest and the largest integers available in the shop. They can either appear in the same segment or in different segments. It is important to note that if they appear in the same segment, then it is the longest one. Let's add the segments to shop one by one and maintain the following six values: The smallest integer in the shop and the cost of the cheapest segment that contains it. The largest integer in the shop and the cost of the cheapest segment that contains it. The length of the longest segment and the cost of the cheapest of such segments. When we know all this values it is easy to find how many coins Vasya will spend in the shop. Total time complexity of this solution is $\\mathcal{O}(n)$. There are other solutions (for example, solution with sets) that runs in $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint answer(set<vector<int> > &byL, set<vector<int> > &byR, map<pair<int, int>, set<int> > &all)\n{\n    if (byL.size() == 0)\n        return 0;\n    int L = (*byL.begin())[0];\n    int R = (*byR.rbegin())[0];\n    int Lc = (*byL.begin())[1];\n    int Rc = -(*byR.rbegin())[1];\n    if (all[{L, R}].size() != 0)\n    {\n        int x = *all[{L, R}].begin();\n        if (x < Lc + Rc)\n            return x;\n    }\n    return Lc + Rc;\n}\n \nvoid solve()\n{\n    int q;\n    cin >> q;\n    set<vector<int> > byL, byR;\n    map<pair<int, int>, set<int> > all;\n    while (q--)\n    {\n        char t = '+';\n        int l, r, c;\n        cin >> l >> r >> c;\n        if (t == '+')\n        {\n            byL.insert({l, c, r});\n            byR.insert({r, -c, l});\n            all[{l, r}].insert(c);\n        }\n        else\n        {\n            byL.erase({l, c, r});\n            byR.erase({r, -c, l});\n            all[{l, r}].erase(c);\n        }\n        cout << answer(byL, byR, all) << \"\\n\";\n    }\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1621",
    "index": "C",
    "title": "Hidden Permutations",
    "statement": "\\textbf{This is an interactive problem.}\n\nThe jury has a permutation $p$ of length $n$ and wants you to guess it. For this, the jury created another permutation $q$ of length $n$. Initially, $q$ is an identity permutation ($q_i = i$ for all $i$).\n\nYou can ask queries to get $q_i$ for any $i$ you want. After each query, the jury will change $q$ in the following way:\n\n- At first, the jury will create a new permutation $q'$ of length $n$ such that $q'_i = q_{p_i}$ for all $i$.\n- Then the jury will replace permutation $q$ with pemutation $q'$.\n\nYou can make no more than $2n$ queries in order to quess $p$.",
    "tutorial": "At first, let's solve this problem when $p$ is a cycle of length $n$. It can be done by asking for $q_1$ for $n$ times. After this, we will receive $1$, $p_1$, $p_{p_1}$, $p_{p_{p_1}}, \\ldots$ in this order. Since $p$ is a cycle, each $x$ will appear once in this sequence. The next element after $x$ will be $p_x$. When $p$ is not a cycle we can determine the cycle containing the first element of permutation by asking such queries. Actually, we can stop asking queries after receiving $1$, thus determining this cycle in $len+1$ queries, where $len$ is the length of this cycle. We can determine other cycles in the same way. We will ask $n$ queries to determine all elements and one more query for determining each cycle end, that is not more than $2n$ queries.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint ask(int i)\n{\n    cout << \"? \" << i + 1 << endl;\n    int x;\n    cin >> x;\n    return x - 1;\n}\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n \n    vector<int> myp(n, -1);\n    for (int i = 0; i < n; i++)\n    {\n        if (myp[i] == -1)\n        {\n            vector<int> cycle;\n            int answer = ask(i);\n            int x = ask(i);\n            cycle.push_back(x);\n            while (x != answer)\n            {\n                x = ask(i);\n                cycle.push_back(x);\n            }\n            for (int j = 0; j < cycle.size(); j++)\n            {\n                myp[cycle[j]] = cycle[(j + 1) % cycle.size()];\n            }\n        }\n    }\n    cout << \"! \";\n    for (int i = 0; i < myp.size(); i++) cout << myp[i] + 1 << \" \";\n    cout << endl;\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "dfs and similar",
      "interactive",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1621",
    "index": "D",
    "title": "The Winter Hike",
    "statement": "Circular land is an $2n \\times 2n$ grid. Rows of this grid are numbered by integers from $1$ to $2n$ from top to bottom and columns of this grid are numbered by integers from $1$ to $2n$ from left to right. The cell $(x, y)$ is the cell on the intersection of row $x$ and column $y$ for $1 \\leq x \\leq 2n$ and $1 \\leq y \\leq 2n$.\n\nThere are $n^2$ of your friends in the top left corner of the grid. That is, in each cell $(x, y)$ with $1 \\leq x, y \\leq n$ there is exactly one friend. Some of the other cells are covered with snow.\n\nYour friends want to get to the bottom right corner of the grid. For this in each cell $(x, y)$ with $n+1 \\leq x, y \\leq 2n$ there should be exactly one friend. It doesn't matter in what cell each of friends will be.\n\nYou have decided to help your friends to get to the bottom right corner of the grid.\n\nFor this, you can give instructions of the following types:\n\n- You select a row $x$. All friends in this row should move to the next cell in this row. That is, friend from the cell $(x, y)$ with $1 \\leq y < 2n$ will move to the cell $(x, y + 1)$ and friend from the cell $(x, 2n)$ will move to the cell $(x, 1)$.\n- You select a row $x$. All friends in this row should move to the previous cell in this row. That is, friend from the cell $(x, y)$ with $1 < y \\leq 2n$ will move to the cell $(x, y - 1)$ and friend from the cell $(x, 1)$ will move to the cell $(x, 2n)$.\n- You select a column $y$. All friends in this column should move to the next cell in this column. That is, friend from the cell $(x, y)$ with $1 \\leq x < 2n$ will move to the cell $(x + 1, y)$ and friend from the cell $(2n, y)$ will move to the cell $(1, y)$.\n- You select a column $y$. All friends in this column should move to the previous cell in this column. That is, friend from the cell $(x, y)$ with $1 < x \\leq 2n$ will move to the cell $(x - 1, y)$ and friend from the cell $(1, y)$ will move to the cell $(2n, y)$.\n\nNote how friends on the grid border behave in these instructions.\n\n\\begin{center}\n{\\small Example of applying the third operation to the second column. Here, colorful circles denote your friends and blue cells are covered with snow.}\n\\end{center}\n\nYou can give such instructions any number of times. You can give instructions of different types. If after any instruction one of your friends is in the cell covered with snow he becomes ill.\n\nIn order to save your friends you can remove snow from some cells before giving the first instruction:\n\n- You can select the cell $(x, y)$ that is covered with snow now and remove snow from this cell for $c_{x, y}$ coins.\n\nYou can do this operation any number of times.\n\nYou want to spend the minimal number of coins and give some instructions to your friends. After this, all your friends should be in the bottom right corner of the grid and none of them should be ill.\n\nPlease, find how many coins you will spend.",
    "tutorial": "Let's say that if for cell $(i, j)$, $c_{i, j}=0$ then it is covered with snow but the cost of removing snow from this cell is $0$. It is obvious that we should remove all the snow in the bottom right corner of the grid. In the case $n=1$ we should remove the snow from the exactly one of the remaining cells. Now concider only the friends in cells $(1, 1)$, $(1, n)$, $(n, n)$, $(n, 1)$. The first operation that will affect any of them is either operation in the $1$-st or in the $n$-th row or operation in the $1$-st or in the $n$-th column. After any of these operaions one of them will be in one of the following cells: $(2n, 1)$, $(1, 2n)$, $(2n, n)$, $(1, n+1)$, $(n+1, n)$, $(n, n+1)$, $(n+1, 1)$, $(n, 2n)$. So we should remove snow from at least one of these cells. Now we can show that it is actually enough to remove snow from exactly one of these cells. Let's assume that we removed snow from $(n, n+1)$. All other cells are identical. Then you can move your friends from the $n$-th row to the $(n+1)$-th column in $2n$ moves as follows: Move all your friends in the $n$-th row to the next cell of this row. Move all your friends in the $(n+1)$-th column to the next cell of this column. Repeat these two operations $n-1$ more times. After this, your friends will stand in the following cells: Here, gray cells are covered with snow. Each integer denotes one of your friends. Now it is easy to see, how to move friends that initially were in the $(n-1)$-th row to the bottom right corner. By repeation these sequences of operations you can help your friends to finish the trip.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<vector<ll> > a(2 * n, vector<ll>(2 * n));\n    for (int i = 0; i < 2 * n; i++)\n    {\n        for (int j = 0; j < 2 * n; j++)\n        {\n            cin >> a[i][j];\n        }\n    }\n    ll ans = 0;\n    for (int i = n; i < 2 * n; i++)\n    {\n        for (int j = n; j < 2 * n; j++)\n        {\n            ans += a[i][j];\n        }\n    }\n    ll mn = 1e9 + 1;\n    mn = min(mn, a[n][0]);\n    mn = min(mn, a[n][n - 1]);\n    mn = min(mn, a[2 * n - 1][0]);\n    mn = min(mn, a[2 * n - 1][n - 1]);\n    mn = min(mn, a[0][n]);\n    mn = min(mn, a[n - 1][n]);\n    mn = min(mn, a[0][2 * n - 1]);\n    mn = min(mn, a[n - 1][2 * n - 1]);\n    cout << ans + mn << \"\\n\";\n}\n \nsigned main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1621",
    "index": "E",
    "title": "New School",
    "statement": "You have decided to open a new school. You have already found $n$ teachers and $m$ groups of students. The $i$-th group of students consists of $k_i \\geq 2$ students. You know age of each teacher and each student. The ages of teachers are $a_1, a_2, \\ldots, a_n$ and the ages of students of the $i$-th group are $b_{i, 1}, b_{i, 2}, \\ldots, b_{i, k_i}$.\n\nTo start lessons you should assign the teacher to each group of students. Such assignment should satisfy the following requirements:\n\n- To each group exactly one teacher assigned.\n- To each teacher at most $1$ group of students assigned.\n- The average of students' ages in each group doesn't exceed the age of the teacher assigned to this group.\n\nThe average of set $x_1, x_2, \\ldots, x_k$ of $k$ integers is $\\frac{x_1 + x_2 + \\ldots + x_k}{k}$.\n\nRecently you have heard that one of the students will refuse to study in your school. After this, the size of one group will decrease by $1$ while all other groups will remain unchanged.\n\nYou don't know who will refuse to study. For each student determine if you can start lessons in case of his refusal.\n\nNote, that it is \\textbf{not guaranteed} that it is possible to start lessons before any refusal.",
    "tutorial": "Suppose, that you know average ages of each group of studens $avg_1, avg_2, \\ldots, avg_m$. How can we check whether we can start lessons? Let's sort this ages and ages of teachers in the decreasing order. Now we have $avg_1 \\geq avg_2 \\geq \\ldots \\geq avg_m$ and $a_1 \\geq a_2 \\geq \\ldots \\geq a_n$. In all the following solution I will assume that average ages of students and teachers are sorted in the decreasing order. Let's show that we can start lessons if and only if $avg_i \\leq a_i$ for all $1 \\leq i \\leq m$. If $avg_i > a_i$ for some $i$ then the eldest $i$ groups can be assigned only to the $i-1$ eldest teachers, so there is no possible assignment. Otherwise we can assign the $i$-th group to the $i$-th teacher. When one of the students refuse to study, only one value of $avg_i$ changes to the new value $x$. Let's denote the new position of this group in the sorted list as $j$. Then all groups on positions between $i$ and $j$ will move by $1$ towards the initial position of group $i$. This position $j$ can be easily found with binary search. Then we can compare $a_j$ and $x$, $a_k$ with $avg_k$ for groups that haven't move and $a_k$ with $avg_{k \\pm 1}$ for groups that have moved to the neighbouring positions. It can be easy done with prefix sum arrays. We can also show that we can do binary search in each group, but it doesn't decrease time complexity (for example, in case when all groups are small).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint comp(pair<long long, int> a, pair<long long, int> b)\n{\n    if (a.first * b.second < b.first * a.second)\n        return 1;\n    return 0;\n}\n \nvoid solve()\n{\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) cin >> a[i];\n    vector<vector<int> > g(m);\n    for (int i = 0; i < m; i++)\n    {\n        int k;\n        cin >> k;\n        g[i] = vector<int>(k);\n        for (int j = 0; j < k; j++)\n        {\n            cin >> g[i][j];\n        }\n    }\n    vector<pair<pair<long long, int>, int> > avg(m);\n    for (int i = 0; i < m; i++)\n    {\n        avg[i] = {{accumulate(g[i].begin(), g[i].end(), 0LL), g[i].size()}, i};\n    }\n    sort(a.rbegin(), a.rend());\n    sort(avg.rbegin(), avg.rend(), [&](pair<pair<long long, int>, int> A, pair<pair<long long, int>, int> B){\n         return comp(A.first, B.first);\n         });\n    vector<int> pos(m);\n    for (int i = 0; i < m; i++)\n        pos[avg[i].second] = i;\n \n    vector<int> assign_to_next(m);\n    vector<int> assign_to_this(m);\n    vector<int> assign_to_prev(m);\n    for (int i = 0; i < m - 1; i++)\n        assign_to_next[i] = comp({1ll * a[i + 1], 1}, avg[i].first);\n    for (int i = 0; i < m; i++)\n        assign_to_this[i] = comp({1ll * a[i], 1}, avg[i].first);\n    for (int i = 1; i < m; i++)\n        assign_to_prev[i] = comp({1ll * a[i - 1], 1}, avg[i].first);\n    for (int i = 1; i < m; i++)\n        assign_to_next[i] += assign_to_next[i - 1],\n        assign_to_this[i] += assign_to_this[i - 1],\n        assign_to_prev[i] += assign_to_prev[i - 1];\n \n    for (int i = 0; i < m; i++)\n    {\n        int id = pos[i];\n        pair<long long, int> cur = {accumulate(g[i].begin(), g[i].end(), 0LL), g[i].size() - 1};\n        for (int j = 0; j < g[i].size(); j++)\n        {\n            cur.first -= g[i][j];\n            int L = -1, R = m;\n            while (L + 1 < R)\n            {\n                int M = (L + R) / 2;\n                if (!comp(avg[M].first, cur))\n                    L = M;\n                else\n                    R = M;\n            }\n            if (R > id) R--;\n            int tr = 1;\n            if (comp({1ll * a[R], 1}, cur) == 1) tr = 0;\n            if (min(R, id) - 1 >= 0 && assign_to_this[min(R, id) - 1] != 0) tr = 0;\n            if (assign_to_this[max(R, id)] != assign_to_this.back()) tr = 0;\n            if (R < id && (R ? assign_to_next[R - 1] : 0) != assign_to_next[id - 1]) tr = 0;\n            if (R > id && assign_to_prev[R] != assign_to_prev[id]) tr = 0;\n            cout << tr;\n            cur.first += g[i][j];\n        }\n    }\n    cout << \"\\n\";\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1621",
    "index": "F",
    "title": "Strange Instructions",
    "statement": "Dasha has $10^{100}$ coins. Recently, she found a binary string $s$ of length $n$ and some operations that allows to change this string (she can do each operation any number of times):\n\n- Replace substring 00 of $s$ by 0 and receive $a$ coins.\n- Replace substring 11 of $s$ by 1 and receive $b$ coins.\n- Remove 0 from any position in $s$ and \\textbf{pay} $c$ coins.\n\nIt turned out that while doing this operations Dasha should follow the rule:\n\n- It is forbidden to do two operations with the same parity in a row. Operations are numbered by integers $1$-$3$ in the order they are given above.\n\nPlease, calculate what is the maximum profit Dasha can get by doing these operations and following this rule.",
    "tutorial": "From the rule $4$ it follows that the sequence of types of operations looks like $\\ldots$, ($1$ or $3$), $2$, ($1$ or $3$), $2$, ($1$ or $3$), $\\ldots$. One can suppose that operation $1$ is \"better\" than operation $3$ so we can (in optimal solution) do all operations of type $3$ after all operations of type $1$. However it is now always the truth: for example for $s = 00101$ with large $a$ and $b$ and small $c$ it is optimal to do operations of types $3$, $2$ and $1$ in this order to get profit of $a+b-c$ ($00101 \\rightarrow 0011 \\rightarrow 011 \\rightarrow 01$). But it turns out that it is the only case when we should do operation of type $1$ after the operation of the type $3$: we can do no more than one such operation $1$ and we can do it in the end. I will prove it later. Now we know how does the operation sequence look like. Let's now think what zeroes and ones we will remove on each step. Obviously, the only case we should use operation of type $3$ is to remove the last $0$ in the block (block of zeroes or ones is the unextendable substring constisting only of zeroes or ones) otherwise we can use the operation of type $1$. Let's now think that string is a sequence of blocks. Obiviously, all zeroes/ones in one block are indistinguishable. Let's look how does the number of possible operations of type $2$ changes after each operation. It is the number of ones minus the number of blocks of ones. After the operation of type $1$ the blocks structure doesn't changes; after the operation of type $2$ the blocks structure also doesn't change but the number of ones reduces by one; after the operation of type of $3$ the number of ones doesn't change, but two blocks of ones are merged together (if we removed not the first or last block). So, the number of possible operations of type $2$ decreaces by one after the operation of type $2$ and can increase by one after the operation of type $3$. Also we can see that the operation of type $2$ can't affect any block of zeroes in any way. From here it follows that all operations of type $2$ are indistinguishable and we should only care about the amount of possible such operations. Also it follows that using operation $3$ to remove one of the middle blocks is always better than using operation $3$ to remove the block from the side. Also it follows that if we have no possible operation of type $2$ remaining the only way to not stop doing operations it to do operation of type $3$ with one of the middle blocks. However, after it we will do operation of type $2$ and will come back to this situation again. Here, in cases $b < c$ or no operation of type $3$ available we can do operation of type $1$ (if it is possible) and stop. I claim that the case above is the only case when we should do the operation of type $1$ after the operation $3$. Assume it is not. Then we have consecutive operations of types $3$, $2$, $1$, $2$ in this order. Then we had possible operations of type $2$ before the first of these operations and operations of types $1$ and $3$ are applied to the different blocks. Thus we can make the same operations in the order $1$, $2$, $3$, $2$ and don't change the answer (we don't care what block to we apply the type $2$ operation). So there is an optimal sequence of operations without consecutive operations $3$, $2$, $1$, $2$. Well, we know much enough about operations of types $2$ and $3$. Now let's go to the operation of type $1$. When we will start making operations of type $3$? There are two cases: we cannot make any operation of type $1$ or we have no possible operations of type $2$. In the first case we will make all possible operations of type $1$ so it doesn't matter in what order we will do them. In the second case we will never come back to the operations of type $1$ except the last operation, so we should prepare as much blocks of length $1$ as possible. The best way to do this is to remove zeroes from the shortest block except the corner blocks on each operation, and then remove zeroes from the corner blocks. I claim that this is enough to solve the problem. It seems that there are too many cases but all of them are covered by the algorithm below. Let's fix the parity of the first operation type to simplify the implementation, so on each step we will know the parity of the type of operation we should do next. Now the algorithm is (after each operation we should try to update the answer): If we should do the operation of type $2$: If we can do it, we do it. Otherwise, we should terminate. If we can do it, we do it. Otherwise, we should terminate. If we should do the operation of type $1$ or $3$: If there are no possible operations of type $2$: If we can do operation of type $1$, we should try to do it (but don't actually do it) and update the answer. It it the last operation in this case. If we can do operation of type $3$ and remove one of the center blocks, we should do it. Otherwise, we should terminate. If there are possible operations of type $2$: If we can do operation of type $1$ on one of the middle blocks, we should do it on the one of the shortest middle blocks. Otherwise, if we can do operation of type $1$ on one of the corner blocks, we should do it. Otherwise, if we can do operation of type $3$ on one of the middle blocks, we should do it. Otherwise, if we can do operation of type $3$ on one of the corner blocks, we should do it. Otherwise, we should terminate. If there are no possible operations of type $2$: If we can do operation of type $1$, we should try to do it (but don't actually do it) and update the answer. It it the last operation in this case. If we can do operation of type $3$ and remove one of the center blocks, we should do it. Otherwise, we should terminate. If we can do operation of type $1$, we should try to do it (but don't actually do it) and update the answer. It it the last operation in this case. If we can do operation of type $3$ and remove one of the center blocks, we should do it. Otherwise, we should terminate. If there are possible operations of type $2$: If we can do operation of type $1$ on one of the middle blocks, we should do it on the one of the shortest middle blocks. Otherwise, if we can do operation of type $1$ on one of the corner blocks, we should do it. Otherwise, if we can do operation of type $3$ on one of the middle blocks, we should do it. Otherwise, if we can do operation of type $3$ on one of the corner blocks, we should do it. Otherwise, we should terminate. If we can do operation of type $1$ on one of the middle blocks, we should do it on the one of the shortest middle blocks. Otherwise, if we can do operation of type $1$ on one of the corner blocks, we should do it. Otherwise, if we can do operation of type $3$ on one of the middle blocks, we should do it. Otherwise, if we can do operation of type $3$ on one of the corner blocks, we should do it. Otherwise, we should terminate. It covers all the cases and works in $\\mathcal{O}(n)$. Total complexity is $\\mathcal{O}(n \\log n)$ because of sorting.",
    "code": "#include <bits/stdc++.h>\n \ntypedef long long ll;\nconst int INF = 1e9;\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; (i) != (n); (i)++)\n#define all(v) (v).begin(), (v).end()\n#define rall(v) (v).rbegin(), (v).rend()\n \nvoid solver(int turn, ll &ans, ll a, ll b, ll c, vector<int> blocks, ll other0, ll single0, ll P, ll turns1)\n{\n    ll cur = 0;\n    while (1)\n    {\n        if (turn == 1)\n        {\n            if (turns1 > 0)\n            {\n                turns1--;\n                cur += b;\n                ans = max(ans, cur);\n            }\n            else\n            {\n                return;\n            }\n        }\n        else\n        {\n            if (turns1 == 0)\n            {\n                if (other0 > 0 || blocks.size() > 0)\n                {\n                    ans = max(ans, cur + a); /// it is the final move\n                }\n                if (single0 > 0) /// we are forced to remove single zero\n                {\n                    single0--;\n                    cur -= c;\n                    ans = max(ans, cur);\n                    turns1++;\n                }\n            }\n            else\n            {\n                if (blocks.size() > 0)\n                {\n                    blocks[blocks.size() - 1]--;\n                    if (blocks.back() == 1)\n                        blocks.pop_back(), single0++;\n                    cur += a;\n                    ans = max(ans, cur);\n                }\n                else if (other0 > 0)\n                {\n                    other0--;\n                    cur += a;\n                    ans = max(ans, cur);\n                }\n                else if (single0 > 0)\n                {\n                    single0--;\n                    turns1++;\n                    cur -= c;\n                    ans = max(ans, cur);\n                }\n                else if (P > 0)\n                {\n                    P--;\n                    cur -= c;\n                    ans = max(ans, cur);\n                }\n                else\n                {\n                    return;\n                }\n            }\n        }\n        turn ^= 1;\n    }\n}\n \nll solve(int n, string s, ll a, ll b, ll c)\n{\n    if (n == 1)\n    {\n        return 0ll;\n    }\n \n    // +a for \"00\" -> \"0\"\n    // +b for \"11\" -> \"1\"\n    // -c for \"0\"->\"\"\n \n    ll ans = 0;\n \n    ll fir1 = INF, lst1 = -1;\n    forn(i, n) if (s[i] == '1')\n    {\n        lst1 = i;\n    }\n    forn(i, n) if (s[i] == '1')\n    {\n        fir1 = i;\n        break;\n    }\n    if (fir1 == INF)\n    {\n        return a;\n    }\n    vector<int> blocks;\n    ll P = 0;\n    if (s[0] == '0') P++;\n    if (s.back() == '0') P++;\n    ll other0 = max(fir1 - 1, 0ll) + max(n - lst1 - 2, 0ll);\n    ll turns1 = 0;\n    for (int i = 0; i + 1 < n; i++) if (s[i] == s[i + 1] && s[i] == '1')\n        turns1++;\n    ll single0 = 0;\n    for (int i = fir1; i < lst1; )\n    {\n        int j = i + 1;\n        while (s[j] != '1')\n            j++;\n        int len = j - i - 1;\n        if (len == 1) single0++;\n        else if (len > 1) blocks.push_back(len);\n        i = j;\n    }\n    sort(rall(blocks));\n \n    solver(0, ans, a, b, c, blocks, other0, single0, P, turns1);\n    solver(1, ans, a, b, c, blocks, other0, single0, P, turns1);\n \n    return ans;\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n    {\n        int n;\n        cin >> n;\n        ll a, b, c;\n        cin >> a >> b >> c;\n        string s;\n        cin >> s;\n        ll ans3 = solve(n, s, a, b, c);\n        cout << ans3 << \"\\n\";\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1621",
    "index": "G",
    "title": "Weighted Increasing Subsequences",
    "statement": "You are given the sequence of integers $a_1, a_2, \\ldots, a_n$ of length $n$.\n\nThe sequence of indices $i_1 < i_2 < \\ldots < i_k$ of length $k$ denotes the subsequence $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$ of length $k$ of sequence $a$.\n\nThe subsequence $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$ of length $k$ of sequence $a$ is called increasing subsequence if $a_{i_j} < a_{i_{j+1}}$ for each $1 \\leq j < k$.\n\nThe weight of the increasing subsequence $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$ of length $k$ of sequence $a$ is the number of $1 \\leq j \\leq k$, such that exists index $i_k < x \\leq n$ and $a_x > a_{i_j}$.\n\nFor example, if $a = [6, 4, 8, 6, 5]$, then the sequence of indices $i = [2, 4]$ denotes increasing subsequence $[4, 6]$ of sequence $a$. The weight of this increasing subsequence is $1$, because for $j = 1$ exists $x = 5$ and $a_5 = 5 > a_{i_1} = 4$, but for $j = 2$ such $x$ doesn't exist.\n\nFind the sum of weights of all increasing subsequences of $a$ modulo $10^9+7$.",
    "tutorial": "At first, this problem can be easily reduced to the problem about permutations by replacing $a_i$ by pair $(a_i, -i)$. The relative order of such pairs is the same as in the problem, however all of them are different so we can replace them with permutation. Let the weight of increasing subsequence $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$ be $w$. It is obvious that if $a_{i_j}$ affects the weight, then $a_{i_{j-1}}$ also affects the weight ($j > 1$). So, elements $a_{i_1}, a_{i_2}, \\ldots, a_{i_w}$ affects the weight of this subsequence while other don't. As $x$ in the weight defenition it is always correct to select the position of $\\max(a_{i_k + 1}, \\ldots, a_n)$. Let's force to select such $x$ for all increasing subsequences. Then we will know that $a_{i_j} < a_x < a_{i_{j+1}}$ for some $j$ and the weight $w$ is equals to this $j$. Let's determine when $a_i$ affects the weight of increasing sequence $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$. Firstly, $a_i$ should appear in this sequence, that is $a_i = a_{i_j}$ for some $j$. Secondly, $\\max(a_{i_k + 1}, \\ldots, a_n)$ should be greater than $a_i$. We can obtain solution in $\\mathcal{O}(n^2)$ by fixing both $a_i$ and $a_{i_k}$. Let $a_{x_1} < a_{x_2} < \\ldots$ be the sequence of suffix maximums. Note that $x_1 > x_2 > \\ldots$ here. Let $y'$ be the smallest $y$ such that $a_{x_y} > a_i$. Then $a_i$ affects the weight of increasing subsequence $a_{i_1}, a_{i_2}, \\ldots, a_{i_k}$ if and only if $i_k \\neq x_{y'}$. It is true because if subsequence ends in $a_{x_{y'}}$ then there is no suffix maximum on the right of $a_{x_{y'}}$ that is greater then $a_i$. Otherwise, the subsequence ends before $a_{x_{y'}}$ so $a_i$ affects the weight. Let's calculate how many increasing subsequences contains $a_i$. For this we should multiply the number of increasing subsequences that ends in $a_i$ by the number of increasing subsequences that starts in $a_i$. Both this values can by found by standart dynamic programming. Also we should calculate the number of increasing subsequences that starts in $a_i$ and ends in $a_{x_{y'}}$. This can be done by almost the same dynamic programming. We can use binary indexed tree to optimize all calculations to $\\mathcal{O}(n \\log n)$. It is imporant to note that when we calculate the number of increasing subsequences that ends in $a_{x_{y'}}$ we are only interested in the increasing subsequences that begins in $a_{x_{y'-1}} < a_i \\leq a_{x_{y'}}$ so there will be $\\mathcal{O}(n)$ calls to binary indexed tree in total.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 1e9 + 7;\n \nvoid add(int pos, int x, vector<int> &fenw)\n{\n    while (pos < fenw.size())\n    {\n        fenw[pos] += x;\n        fenw[pos] %= MOD;\n        pos |= (pos + 1);\n    }\n}\n \nint get(int pos, vector<int> &fenw)\n{\n    int res = 0;\n    while (pos >= 0)\n    {\n        res = res + fenw[pos];\n        res %= MOD;\n        pos &= (pos + 1);\n        pos--;\n    }\n    return res;\n}\n \nint weight_of_all_subseq(vector<int> seq)\n{\n    vector<int> dp_up(seq.size());\n    vector<int> fenw1(seq.size());\n    for (int i = (int)seq.size() - 1; i >= 0; i--)\n    {\n        dp_up[i] = (1ll + get(seq.size() - 1, fenw1) - get(seq[i], fenw1) + MOD) % MOD;\n        add(seq[i], dp_up[i], fenw1);\n    }\n    vector<int> fenw2(seq.size());\n    vector<int> dp_down(seq.size());\n    for (int i = 0; i < seq.size(); i++)\n    {\n        dp_down[i] = (1ll + get(seq[i], fenw2)) % MOD;\n        add(seq[i], dp_down[i], fenw2);\n    }\n    vector<int> suf_mx;\n    vector<int> is_suf_mx(seq.size());\n    int mx = 0;\n    for (int i = (int)seq.size() - 1; i >= 0; i--)\n    {\n        mx = max(mx, seq[i]);\n        if (seq[i] == mx)\n            suf_mx.push_back(i), is_suf_mx[i] = 1;\n    }\n \n    vector<int> q(seq.size());\n    for (int i = 0; i < seq.size(); i++)\n        q[seq[i]] = i;\n \n    vector<int> dp_up_fix(seq.size());\n    vector<int> fenw3(seq.size());\n    int lst = seq.size() - 1;\n    for (int x = (int)seq.size() - 1; x >= 0; x--)\n    {\n        if (is_suf_mx[q[x]])\n        {\n            dp_up_fix[x] = 1;\n            for (int j = x + 1; j <= lst; j++)\n                add(q[j], (MOD - dp_up_fix[j]) % MOD, fenw3);\n            add(q[x], dp_up_fix[x], fenw3);\n            lst = x;\n            continue;\n        }\n        dp_up_fix[x] = (get(q[lst], fenw3) - get(q[x], fenw3) + MOD) % MOD;\n        add(q[x], dp_up_fix[x], fenw3);\n    }\n \n    int ans = 0;\n    for (int i = (int)seq.size() - 1; i >= 0; i--)\n    {\n        ans = (ans + 1ll * dp_down[i] * (dp_up[i] + MOD - dp_up_fix[seq[i]])) % MOD;\n    }\n    return ans;\n}\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<pair<int, int> > b(n);\n    for (int i = 0; i < n; i++)\n        cin >> b[i].first, b[i].second = -i;\n    vector<int> a(n);\n    sort(b.begin(), b.end());\n    for (int i = 0; i < n; i++)\n        a[-b[i].second] = i;\n    cout << weight_of_all_subseq(a) << \"\\n\";\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1621",
    "index": "H",
    "title": "Trains and Airplanes",
    "statement": "Railway network of one city consists of $n$ stations connected by $n-1$ roads. These stations and roads forms a tree. Station $1$ is a city center. For each road you know the time trains spend to pass this road. You can assume that trains don't spend time on stops. Let's define $dist(v)$ as the time that trains spend to get from the station $v$ to the station $1$.\n\nThis railway network is splitted into zones named by first $k$ capital latin letters. The zone of the $i$-th station is $z_i$. City center is in the zone A. For all other stations it is guaranteed that the first station on the road from this station to the city center is either in the same zone or in the zone with lexicographically smaller name. Any road is completely owned by the zone of the most distant end from the city center.\n\nTourist will arrive at the airport soon and then he will go to the city center. Here's how the trip from station $v$ to station $1$ happends:\n\n- At the moment $0$, tourist enters the train that follows directly from the station $v$ to the station $1$. The trip will last for $dist(v)$ minutes.\n- Tourist can buy tickets for any subset of zones at any moment. Ticket for zone $i$ costs $pass_i$ euro.\n- Every $T$ minutes since the start of the trip (that is, at the moments $T, 2T, \\ldots$) the control system will scan tourist. If at the moment of scan tourist is in the zone $i$ without zone $i$ ticket, he should pay $fine_i$ euro. Formally, the zone of tourist is determined in the following way:\n\n- If tourist is at the station $1$, then he already at the city center so he shouldn't pay fine.\n- If tourist is at the station $u \\neq 1$, then he is in the zone $z_u$.\n- If tourist is moving from the station $x$ to the station $y$ that are directly connected by road, then he is in the zone $z_x$.\n\nNote, that tourist can pay fine multiple times in the same zone.\n\nTourist always selects such way to buy tickets and pay fines that minimizes the total cost of trip. Let $f(v)$ be such cost for station $v$.\n\nUnfortunately, tourist doesn't know the current values of $pass_i$ and $fine_i$ for different zones and he has forgot the location of the airport. He will ask you queries of $3$ types:\n\n- $1$ $i$ $c$ — the cost of \\textbf{ticket} in zone $i$ has changed. Now $pass_i$ is $c$.\n- $2$ $i$ $c$ — the cost of \\textbf{fine} in zone $i$ has changed. Now $fine_i$ is $c$.\n- $3$ $u$ — solve the following problem for current values of $pass$ and $fine$:\n\n- You are given the station $u$. Consider all the stations $v$ that satisfy the following conditions:\n\n- $z_v = z_u$\n- The station $u$ is on the path from the station $v$ to the station $1$.\n\nFind the value of $\\min(f(v))$ over all such stations $v$ with the following assumption: \\textbf{tourist has the ticket for the zone of station} $z_u$.",
    "tutorial": "Let $scans_{v, i}$ be the number of scans in the $i$-th zone if we start from the vertex $v$ and $scans_{v, z_v} = 0$. Note that $scans$ doesn't change during queries. Now our task is to calculate $\\sum_{z \\in zones} \\min (scans_{v, z} \\cdot fine_{z}, pass_{z})$ over some set of vertices $A_i$ described in the $i$-th query. It is important to note that for any two vertices $v_1, v_2 \\in A_i$ and any zone $z$ holds $|scans_{v_1, z} - scans_{v_2, z}| \\leq 1$. From this, we can see that there are no more than $\\mathcal{O}(2^k)$ different values of $scans_v$ for $v \\in A_i$, so we don't need to check all vertices in $A_i$ to find the answer. However, it is still quite a lot. Let $minscans_z$ be the min value of $scans_{v, z}$ for $v \\in A_i$. For some vertices $v$ we will have $minscans_z$ scans in zone $z$ and $minscans_z + 1$ scans for other vertices. Actually, we can look at the moment $t$ we escape the start zone (zone that contains the airport). For each zone $z$ there is a segment$\\bmod T$ such that if $t$ lies in it we will have $minscans_z$ scans in this zone and we will have $minscans_z + 1$ scans otherwise. Let's suppose we are going to do something like sweepline on this segments. There are $\\mathcal{O}(k)$ segments and they can split the$\\bmod T$ circle into at most $\\mathcal{O}(k)$ sections. This is how we get that we actually should check not more that $2k$ vertices in order to find answer for each query. What about the implementation part, we should be able to find where we escape the start zone (let's call this vertex $V$) and the time we spend on the road from any vertex to the vertex $1$. It can be easily done with dfs. Also we should be able to calculate $scans_{V}$. We can do it in $\\mathcal{O}(k)$ by repeatedly going to the next vertex of the path in another zone. While doing this we can also find$\\bmod T$ segments when we should escape the start zone in order to have less scans in each zone: if we start from vertex $V$ and we are in the zone $z$ at the segment of moments $[t_l, t_r]$, then we will have to pay additional fine in zone $z$ if we pass through $V$ at one of moments $[T-t_r, T-t_l] \\pmod T$. Then we will do sweepline algorithm on this segments to find the segments of times we are interested in. The last thing we should be able to do is to determine in which of previouly descibed segments there are vertices in $A_i$. It can be done by computing this segment for each vertex and then merging this values by dfs. During answering the query we can iterate over all previouly descibed segments and update answer in case we have vertex in this segment. In order to reduce time complexity of answering query from $\\mathcal{O}(k^2)$ to $\\mathcal{O}(k)$ we should actually perform such sweepline and maintain current answer and precompute whether we have vertices in this section. It is how we can get $\\mathcal{O}(nk\\log k + qk)$ solution with $\\mathcal{O}(nk)$ memory. We can also do all calculations in place and solve this problem with $\\mathcal{O}(n)$ memory in $\\mathcal{O}(nk\\log k + qk\\log k)$ which is not much slower. It seems that this problem is somehow connected with real life so you can be interested how such descripion of set of vertices in queries was obtained. Assume that tourist already was in this airport. He bought the ticket at the station near the airport but activated it only at the station $u$ in the same zone. At the moment of query he had this ticket and it contained some information about activation.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst long long INF = 1e9 + 5;\n \npair<vector<long long>, vector<pair<int, int> > > get_total_and_changes(int vv, int k, int T, vector<long long> &depth, vector<int> &checkpoint, string &z)\n{\n    //int vv = par;\n    long long enter_time = 0;\n    long long cur_time = 0;\n \n    vector<pair<int, int> > changes;\n    vector<long long> total(k);\n \n    while (vv != 0)\n    {\n        cur_time += depth[vv] - depth[checkpoint[vv]];\n        int L = enter_time % T, R = (cur_time - 1) % T;\n \n        total[z[vv] - 'A'] += (cur_time - 1 + T) / T - (enter_time - 1 + T) / T;\n \n        L = (T - L) % T;\n        R = (T - R) % T;\n        if ((L + 1) % T != R % T)\n        {\n            if (R % T != 0) changes.push_back({R % T, z[vv]});\n            if ((L + 1) % T != 0) changes.push_back({(L + 1) % T, -z[vv]});\n        }\n \n        enter_time = cur_time;\n        vv = checkpoint[vv];\n    }\n \n    sort(changes.begin(), changes.end());\n \n    return {total, changes};\n}\n \nvoid dfs(int v, int par, vector<vector<pair<int, int> > > &g,\n         vector<int> &p, vector<long long> &depth,\n         string &z, vector<int> &checkpoint)\n{\n    checkpoint[v] = checkpoint[par];\n    p[v] = par;\n    if (z[par] != z[v])\n        checkpoint[v] = par;\n \n    for (auto e : g[v]) if (e.first != par)\n    {\n        depth[e.first] = depth[v] + e.second;\n        dfs(e.first, v, g, p, depth, z, checkpoint);\n    }\n}\n \nvoid dfs(int v, int p, vector<vector<pair<int, int> > > &g, string &z, vector<long long> &checkpoint_sectors)\n{\n    for (auto e : g[v]) if (e.first != p)\n    {\n        dfs(e.first, v, g, z, checkpoint_sectors);\n        if (z[e.first] == z[v] && z[v] != 'A')\n        {\n            checkpoint_sectors[v] |= checkpoint_sectors[e.first];\n        }\n    }\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    // read the main input\n    int n;\n    cin >> n;\n    vector<vector<pair<int, int> > > g(n);\n    for (int i = 0; i < n - 1; i++)\n    {\n        int v, u, t;\n        cin >> v >> u >> t;\n        v--, u--;\n        g[v].push_back({u, t});\n        g[u].push_back({v, t});\n    }\n \n    int k;\n    cin >> k;\n    string z;\n    cin >> z;\n \n    vector<int> pass(k), fine(k);\n    for (int i = 0; i < k; i++)\n    {\n        cin >> pass[i];\n    }\n    for (int i = 0; i < k; i++)\n    {\n        cin >> fine[i];\n    }\n \n    int T;\n    cin >> T;\n \n    // work with main data\n    vector<int> p(n);\n    vector<long long> depth(n);\n    vector<int> checkpoint(n);\n    dfs(0, 0, g, p, depth, z, checkpoint);\n \n    vector<long long> checkpoint_sectors(n);\n    for (int i = 0; i < n; i++)\n    {\n        if (z[i] == 'A') continue;\n        int CH = checkpoint[i];\n        int pass = (depth[i] - depth[CH]) % T;\n        vector<pair<int, int> > table_changes = get_total_and_changes(CH, k, T, depth, checkpoint, z).second;\n        for (int j = 0; j < table_changes.size(); j++)\n        {\n            if (table_changes[j].first <= pass)\n                checkpoint_sectors[i]++;\n        }\n        checkpoint_sectors[i] = (1ll << checkpoint_sectors[i]);\n    }\n    dfs(0, 0, g, z, checkpoint_sectors);\n \n    // answer queries\n    int q;\n    cin >> q;\n    while (q--)\n    {\n        int t;\n        cin >> t;\n        if (t == 1)\n        {\n            char z;\n            int c;\n            cin >> z >> c;\n            pass[z - 'A'] = c;\n            continue;\n        }\n        else if (t == 2)\n        {\n            char z;\n            int c;\n            cin >> z >> c;\n            fine[z - 'A'] = c;\n            continue;\n        }\n        int u;\n        cin >> u;\n        u--;\n \n        if (z[u] == 'A')\n        {\n            cout << 0 << \"\\n\";\n            continue;\n        }\n        int CH = checkpoint[u];\n        long long ans = 1e18;\n        pair<vector<long long>, vector<pair<int, int> > > tables = get_total_and_changes(CH, k, T, depth, checkpoint, z);\n        long long cur = 0;\n        for (int i = 0; i < k; i++) cur += min(1ll * pass[i], 1ll * fine[i] * min(tables.first[i], INF));\n        for (int i = 0; i <= tables.second.size(); i++)\n        {\n            if (checkpoint_sectors[u] & (1ll << i)) ans = min(ans, cur);\n            if (i == tables.second.size()) break;\n            int j = tables.second[i].second;\n            if (j > 0)\n            {\n                j -= 'A';\n                cur -= min(1ll * pass[j], 1ll * fine[j] * min(tables.first[j], INF));\n                tables.first[j]++;\n                cur += min(1ll * pass[j], 1ll * fine[j] * min(tables.first[j], INF));\n            }\n            else\n            {\n                j *= -1;\n                j -= 'A';\n                cur -= min(1ll * pass[j], 1ll * fine[j] * min(tables.first[j], INF));\n                tables.first[j]--;\n                cur += min(1ll * pass[j], 1ll * fine[j] * min(tables.first[j], INF));\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1621",
    "index": "I",
    "title": "Two Sequences",
    "statement": "Consider an array of integers $C = [c_1, c_2, \\ldots, c_n]$ of length $n$. Let's build the sequence of arrays $D_0, D_1, D_2, \\ldots, D_{n}$ of length $n+1$ in the following way:\n\n- The first element of this sequence will be equals $C$: $D_0 = C$.\n- For each $1 \\leq i \\leq n$ array $D_i$ will be constructed from $D_{i-1}$ in the following way:\n\n- Let's find the lexicographically smallest subarray of $D_{i-1}$ of length $i$. Then, the first $n-i$ elements of $D_i$ will be equals to the corresponding $n-i$ elements of array $D_{i-1}$ and the last $i$ elements of $D_i$ will be equals to the corresponding elements of the found subarray of length $i$.\n\nArray $x$ is subarray of array $y$, if $x$ can be obtained by deletion of several (possibly, zero or all) elements from the beginning of $y$ and several (possibly, zero or all) elements from the end of $y$.\n\nFor array $C$ let's denote array $D_n$ as $op(C)$.\n\nAlice has an array of integers $A = [a_1, a_2, \\ldots, a_n]$ of length $n$. She will build the sequence of arrays $B_0, B_1, \\ldots, B_n$ of length $n+1$ in the following way:\n\n- The first element of this sequence will be equals $A$: $B_0 = A$.\n- For each $1 \\leq i \\leq n$ array $B_i$ will be equals $op(B_{i-1})$, where $op$ is the transformation described above.\n\nShe will ask you $q$ queries about elements of sequence of arrays $B_0, B_1, \\ldots, B_n$. Each query consists of two integers $i$ and $j$, and the answer to this query is the value of the $j$-th element of array $B_i$.",
    "tutorial": "Let's denote the construction of array $D_i$ from array $D_{i-1}$ as the $i$-th step of transformation $op$. Also let's behave as all steps affect $C$ instead of creating multiple new arrays. The solution consists of $4$ parts: Show that there exists small $m$, such that $B_m = B_{m-1}$. If $n \\leq 10^5$ then $m$ doesn't exceed $7$ ($m = \\mathcal{O}(\\log\\log n)$). Find the lexicographically smallest suffix for each prefix of some array. For subarray $c_l, \\ldots, c_r$ find the smallest $k$ such that the subarray $c_l, \\ldots, c_r$ is a period (without a prefix) of the subarray $c_k, \\ldots, c_r$. Show that on the $(n-r+1)$-th step of transformation the lexicographically smallest subarray starts in $c_l$ or in $c_k$. Find the way to simulate the transformation quite fast. Total time complexity is $\\mathcal{O}(n \\log^2 n \\log\\log n)$. You can try to solve each of the parts independently! Part $1$. Let's concider an array $C$ we are going to apply $op$ to. It is easy to see that $op(C) = C$ if it is non-increasing (because on each step the suffix of length $i$ will be one of the lexicographically smallest subarrays of length $i$). Otherwise let $j$ be the smallest index such that $c_j < c_{j+1}$. Let $x$ be the smallest index such that $c_x = c_j$ (then $c_x = c_{x+1} = \\ldots = c_j$, all element of the subarray of length $j - x + 1$ are equal). The first $n - j - 1$ steps doesn't affect the prefix of length $j + 1$. It is easy to see that the last $x$ steps doesn't change array (the reason is the same as in the paragraph above). Let's understand what happends on the $(n-j)$-th step. We should find the lexicographically smallest subarray that starts on the prefix of length $j+1$. The smallest element on this prefix is $c_j$, thus this subarray will start in one of positions between $x$ and $j$. Since $c_j < c_{j+1}$ the subarray of length $n-j$ that starts in the position $x$ is always one of the lexicographically smallest subarrays. Thus after the $(n-j)$-th step If $x + n - j - 1 \\leq j$, then all elements on positions between $j+1$ and $n$ became equals to $c_x$ (because the selected subarray constists only of elements that are equal $c_x$). It it easy to see that array becomes non-increasing so it won't ever change again. Otherwise elements on positions $j+1, j+2, \\ldots, j+(j-x-1)$ becomes equal $c_x$ and elements on positions $j+(j-x), \\ldots, n$ are equal to old values of $c_x, c_{x+1}, \\ldots, c_{n-(j-x)}$. By the way $c_{j+(j-x)}$ is equal to the old value of $c_x$. It is important that in the second case the length of the subarray of the equal elements becomes $(j-x+1)+(j-x+1)$ and it is followed by the greater element. Now we can apply the same ideas to the steps between the $(n-j+1)$-th and $(n-x)$-th. We see that the length of the subarray filled by the same elements becomes $(j-x+1) + (j-x+1) + (j-x) + (j-x-1) + \\ldots + 1 = \\frac{(j-x+3)(j-x+2)}{2}-1$ or this subarray becomes the suffix and whole array won't change again. In the initial array $A$ the length of this subarray (the subarray of the equal elements starting at position $x$) is at least $1$, so in $B_1$ it is at least $2$, in $B_2$ it is at least $5$, in $B_3$ it is at least $20$, in $B_4$ it is at least $230$, in $B_5$ it is at least $26795$, in $B_6$ this subarray becomes the suffix. After that all arrays will be equal $B_6$ (because $n \\leq 10^5$). The integers above are connected with the sequence A007501. Now we know that we should simulate $op$ only $6$ times to get all answers. In the following solution I will optimize $op$ assuming that time limit is aproximately $1$ sec. It is easy to see how to find $B_6$ in linear time and simulate $op$ only $5$ times. Part $2$. If we had no change queries than the problem is to find the lexicographically smallest substring of length $k$ in the given string for all $k$ between $1$ and $n$. The solution of this problem is building the suffix array and finding the lexicographically smallest suffix of length at least $k$. It is important that change queries change the suffix of the initial array to \"something lexicographically small\". And that on the $i$-th step the required substring starts in one of position on the prefix of length $i-1$. We can guess that we should find the lexicographically smallest suffix of each prefix. I will prove that it is almost enough later. As far as I know it is not the well known problem so I will describe the solution. At first we can build the suffix array of the initial array and sparce table in order to compate subarrays fast and in order to find the first position of difference of subarrays that start at some positions $i$ and $j$. Now let's consider all prefixes of the initial array in the order of increasing of length. We want to understand how does the suffix array of the current array changes when we add the integer to the right end of it. There are some prefix-independent subarrays (that is, subarrays that have the integer that differs them already added), and some segments of prefix-dependent subarrays. It is easy to see that the prefix-independent subarrays won't change their relative order. But prefix-depenent subarrays in one segment can change their relative order. Suppose that you have the sorted sequence of pairwise different arrays $s_1, s_2, \\ldots, s_n$ and each of them is the prefix of the next one. Then appending some integer $c$ to each of them and sorting them again are equivalent to the following operations: Let's split the sequence of arrays into two subsequences $s_{k_1}, s_{k_2}, \\ldots, s_{k_x}$ and $s_{m_1}, s_{m_2}, \\ldots, s_{m_y}$ in the following way: the first of them contains all such arrays $s_i$ that $i < n$ and $s_i + c \\leq s_{i+1}$, the second of them contains all other arrays. The sorted sequence of arrays is equal to $s_{k_1} + c, s_{k_2} + c, \\ldots, s_{k_x} + c, s_{m_y} + c, s_{m_{y-1}} + c, \\ldots, s_{y_1} + c$. Prefix-dependent arrays can appear only in the first part of the sequence. We can use sparce table to find the first position where prefix-dependent subarrays differ. Using the suffix array we can find the final order of these arrays. Since we are interested only in the lexicographically smallest suffix we can maintain only some data about the first segment of prefix-dependent subarrays in the suffix array. Let's call the suffix from the first segment such that its position in the final suffix array is the smallest important suffix. Then the suffixes that can be the lexicographically smallest now differs from the important suffix in come position later. Let's maintain \"the minimal suffix candidates\" as a set of triples (the position of the beginning of this suffix, the position of this suffix in the final suffix array, the position where this suffix differs from the important suffix). Here is the code that finds the minimal suffix of each prefix of the given array: This part of the solution works in $\\mathcal{O}(n \\log^2 n)$ or in $\\mathcal{O}(n \\log n)$. It depends on your implementation of suffix array. Part $3$. For a given $r$ let the position of the beginning of the lexmin suffix of $c_1, c_2, \\ldots, c_r$ be $l$. For a subarray $c_l, \\ldots, c_r$, I want to find the smallest $k$ such that $c_l, \\ldots, c_r$ is a period of $c_k, \\ldots, c_r$ (without a prefix). It can be easily done by binary search or binary lifting in $\\mathcal{O}(n \\log n)$ for all $r$. We use the suffix array and sparce table from the previous part here. Now, let's show that on the $(n-r+1)$-th step the lexicographically smallest subarray starts in one of positions $l$ and $k$ (for this $r$). Let $i = n - r + 1$. Let's assume that the lexmin subarray starts in the position $x$ and $x \\neq l$. If $c_l, \\ldots, c_r$ is not a prefix of $c_x, \\ldots, c_r$ then the subarray that starts at the position $l$ is not larger than the subarray that starts at the position $x$ according to the choice of $l$. By the same reasons $x < l$. Now we know that $c_l, \\ldots, c_r$ is a prefix of $c_x, \\ldots, c_r$. Let $p$ be the smallest positive integer such that $c_{l+p} \\neq c_{x+p}$. Since we assumed that the lexmin subarray starts at the position $x$ then $c_{l+p} > c_{x+p}$. The case $x + p > x + i - 1$ is not interesting because subarrays of length $i$ from positions $l$ and $x$ are equal in this case. If $l + p \\leq r$ then $c_l, \\ldots, c_r$ is not a prefix of $c_x, \\ldots, c_r$. If $x + p \\leq r$ then we are in the following situation: On the first picture the subarray that starts in position $x$ is shown. On the second picture the subarray that starts in position $l$ is show.$S$, $T$ are subarrays ($T$ can be empty), $a$, $b$ are the integers on position $x+p$ and $l+p$. The blue line splits the array into the prefix of the length $r$ and the suffix of the length $n-r$. Then we can show that the subarray that starts in the position $x+(r-l)+1$ is lexicographically smaller than the subarray we selected on the previous step. But it can't be true. On the first picture the subarray that starts in position $x$ is shown. On the second picture the subarray that starts in position $l$ is show.$S$, $T$ are subarrays ($T$ can be empty), $a$, $b$ are the integers on position $x+p$ and $l+p$. The blue line splits the array into the prefix of the length $r$ and the suffix of the length $n-r$. $S$, $T$ are subarrays ($T$ can be empty), $a$, $b$ are the integers on position $x+p$ and $l+p$. The blue line splits the array into the prefix of the length $r$ and the suffix of the length $n-r$. Then we can show that the subarray that starts in the position $x+(r-l)+1$ is lexicographically smaller than the subarray we selected on the previous step. But it can't be true. If $x + p > r$ we can't get such a simple contradiction. But in this case we know that there are some items that appear in both subarrays. I will show that $c_l, \\ldots, c_r$ is a period (without a prefix) of $c_x, \\ldots, c_r$. Consider arrays $c_x, \\ldots, c_{x+p-1}$ and $c_l, \\ldots, c_{l+p-1}$. Let $S$ be the subarray $c_l, \\ldots, c_r$ and $T$ be the subarray $c_{x+(r-l)+1}, \\ldots, c_r$. Then from equalities $c_y = c_{y-(l-x)}$ for $x + (r-l) \\leq y < l+p$ follows that $T$ is a period of the subarray $c_{r + 1}, \\ldots, c_{l+p-1}$. It is easy to see that the length of $T$ in at least the length of $S$ and that $T$ is lexicographically larger than $S$ according to the choise of $l$. But if the prefix of $T$ of length $|S|$ is larger than $S$, then it is incorrect that we have select the subarray that starts with $T$ on the previous step. Thus $S$ is a prefix of $T$. By the same reasons we can show that concatenation of $\\alpha \\leq \\lfloor\\frac{|T|}{|S|}\\rfloor$ copies of $S$ is a prefix $T$. At the same time $S$ is a suffix of $T$. Thus $S$ is a period of $T$. If $|T| \\bmod |S| \\neq 0$ then the suffix of $S$ of length $|T| \\bmod |S|$ is lexicographically smaller than $S$ but is makes a contradiction with the choise of $l$. Thus $S$ is a period of $T$ (without a prefix). Let $S$ be the subarray $c_l, \\ldots, c_r$ and $T$ be the subarray $c_{x+(r-l)+1}, \\ldots, c_r$. Then from equalities $c_y = c_{y-(l-x)}$ for $x + (r-l) \\leq y < l+p$ follows that $T$ is a period of the subarray $c_{r + 1}, \\ldots, c_{l+p-1}$. It is easy to see that the length of $T$ in at least the length of $S$ and that $T$ is lexicographically larger than $S$ according to the choise of $l$. But if the prefix of $T$ of length $|S|$ is larger than $S$, then it is incorrect that we have select the subarray that starts with $T$ on the previous step. Thus $S$ is a prefix of $T$. By the same reasons we can show that concatenation of $\\alpha \\leq \\lfloor\\frac{|T|}{|S|}\\rfloor$ copies of $S$ is a prefix $T$. At the same time $S$ is a suffix of $T$. Thus $S$ is a period of $T$. If $|T| \\bmod |S| \\neq 0$ then the suffix of $S$ of length $|T| \\bmod |S|$ is lexicographically smaller than $S$ but is makes a contradiction with the choise of $l$. Thus $S$ is a period of $T$ (without a prefix). The last thing to show is that $x = k$. Otherwise, $x - (r-l+1) \\geq k$. It is easy to show that the subarray that starts in the position $x-(r-l+1)$ is not larger than the subarray that starts in the position $x$. It follows from the selection of $p$: $c_{l+p}$ makes the first difference between $c_{r+1}, \\ldots, c_{n}$ and infinite concatenation of subarrays $c_l, \\ldots, c_r$. Part $4$. Now we know that we should compare two subarrays that start from some known positions on each step. Let's deal with copying the subarray to the suffix. Let's split an array into two parts. The first of them will consist of the first $n-i+1$ elements on the $i$-th step. The second of them will be the subarray we found on the previous step. Let's store the second part as a queue of subarrays of the initial subarray. If we copy some subarray that doesn't intersect with the suffix, we just put it in the beginning of the queue. Otherwise, we can put the suffix of the current prefix into this queue. We can maintain this queue in the segment tree with hashes. To compare two subarrays we will use the binary search. Total time complexity of this part is $\\mathcal{O}(n \\log^2 n)$. There will be $M = \\mathcal{O}(n \\log n \\log \\log n) \\approx 10^7$ hash comparations in the whole solution. The model solution uses the module near $10^{36}$. I guess that it is possible to create a faster solution or solution without hashes using some ideas from the part $3$.\"prefix of T\" from the picture above is either really small ($0$ or $1$) or huge ($|T| - 1$ or $|T| - 2$)? it is easy to see where the increasing order of lengths of subarrays is used; but is it necessary that these lengths are $1, \\ldots, n$ in parts $2$-$4$ (in other worlds, is it possible to solve the problem that requires to make the given steps of $op$)?",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\ntypedef pair<int, int> pii;\n \n#define all(x) (x).begin(), (x).end()\n#define l first\n#define r second\n \nconst int INF = 1e9 + 1;\nconst int N = 202000;\n \nconst ll MOD1 = 998244391;\nconst ll M1 = 1e6 + 3;\nint deg1[N];\n \nvector<int> lcp(vector<int> &s, vector<int> &sa, vector<int> &pos)\n{\n    int n = s.size();\n    vector<int> L(n);\n    int k = 0;\n    for (int i = 0; i < n; i++)\n    {\n        if (k > 0) k--;\n        if (pos[i] == n - 1)\n            L[n - 1] = -1, k = 0;\n        else\n        {\n            int j = sa[pos[i] + 1];\n            while (max(i + k, j + k) < n && s[i + k] == s[j + k])\n                k++;\n            L[pos[i]] = k;\n        }\n    }\n    return L;\n}\n \n \nint H[N];\nint sp[20][N];\n \nint get(int l, int r)\n{\n    int j = H[r - l + 1];\n    return min(sp[j][l], sp[j][r - (1 << j) + 1]);\n}\n \nvoid buildsa(vector<int> &s, vector<int> &sa, vector<int> &pos)\n{\n    map<int, int> mm;\n    for (int i = 0; i < (int)s.size(); i++)\n        mm[s[i]] = -1;\n    int x = 0;\n    for (int c = 0; c <= s.size(); c++)\n    {\n        if (mm.find(c) != mm.end())\n            mm[c] = x++;\n    }\n    for (int i = 0; i < (int)s.size(); i++)\n    {\n        pos[i] = mm[s[i]];\n    }\n    vector<pair<pii, int> > p(s.size());\n    for (int j = 1; (1 << j) <= 2 * (int)s.size(); j++)\n    {\n        for (int i = 0; i < (int)s.size(); i++)\n        {\n            p[i] = {{pos[i], pos[(i + (1 << j) / 2) % s.size()]}, i};\n        }\n        sort(p.begin(), p.end());\n        int x = 0;\n        pos[p[0].second] = x;\n        for (int i = 1; i < (int)p.size(); i++)\n        {\n            if (p[i].first != p[i - 1].first) x++;\n            pos[p[i].second] = x;\n        }\n    }\n    for (int i = 0; i < (int)s.size(); i++)\n    {\n        sa[pos[i]] = i;\n    }\n}\n \nvector<int> msep(vector<int> &s, vector<int> &sa, vector<int> &pos)\n{\n    vector<int> res(s.size());\n \n    int n = s.size();\n    int ri = 0;\n    int pi = INF;\n \n    set<array<int, 3> > waitlist;\n    set<array<int, 3> > waitlist_sorted;\n \n    auto emplace = [&](int z) { \n        pi = min(pi, z);\n        if (pi != INF && pi < z && get(pi, z - 1) >= ri - sa[z])\n        {\n            waitlist.insert({sa[z] + get(pi, z - 1), z, sa[z]});\n            waitlist_sorted.insert({-sa[z], sa[z] + get(pi, z - 1), z});\n        }\n    };\n \n    while (ri < n)\n    {\n        ri++;\n        while (waitlist.size())\n        {\n            array<int, 3> it = *waitlist.begin();\n            int z = it[1];\n            if (it[0] >= ri) break;\n            waitlist.erase(it);\n            waitlist_sorted.erase({-it[2], it[0], it[1]});\n        }\n        emplace(pos[ri - 1]);\n \n        if (waitlist_sorted.size())\n        {\n            res[ri - 1] = -(*waitlist_sorted.begin())[0];\n        }\n        else\n        {\n            res[ri - 1] = sa[pi];\n        }\n    }\n    return res;\n}\n \ndouble precomputation_time = 0;\n \nvector<int> fast_op(vector<int> s)\n{\n    double st = clock();\n \n    s.push_back(0);\n    vector<int> sa(s.size());\n    vector<int> pos(s.size());\n    buildsa(s, sa, pos);\n    vector<int> L = lcp(s, sa, pos);\n \n    for (int i = 0; i < (int)s.size(); i++) sp[0][i] = L[i];\n    for (int j = 0; j < 20; j++)\n        for (int i = 0; i + (1 << j) - 1 < (int)s.size(); i++)\n            sp[j][i] = get(i, i + (1 << j) - 1);\n \n    s.pop_back();\n \n    auto cmp = [&](int l1, int l2, int len)\n    {\n        if (get(min(pos[l1], pos[l2]), max(pos[l1], pos[l2]) - 1) >= len)\n            return 1;\n        return 0;\n    };\n \n    vector<int> min_suf_each_pref = msep(s, sa, pos);\n    vector<int> kek_suf_each_pref(s.size());\n    for (int i = 0; i < s.size(); i++)\n    {\n        int len = i + 1 - min_suf_each_pref[i];\n        kek_suf_each_pref[i] = min_suf_each_pref[i];\n        int j = 0;\n        for (j = 0; j < 20; j++)\n        {\n            ll nc = kek_suf_each_pref[i] - (1ll << j) * len;\n            if (nc >= 0 && cmp(nc, kek_suf_each_pref[i], (1ll << j) * len))\n                kek_suf_each_pref[i] = nc;\n            else\n                break;\n        }\n        for (; j >= 0; j--)\n        {\n            ll nc = kek_suf_each_pref[i] - (1ll << j) * len;\n            if (nc >= 0 && cmp(nc, kek_suf_each_pref[i], (1ll << j) * len))\n                kek_suf_each_pref[i] = nc;\n        }\n    }\n \n    precomputation_time += 1.0 * (clock() - st) / CLOCKS_PER_SEC;\n \n    deque<pair<int, int> > h;\n \n    struct SegTree{\n        struct Node\n        {\n            int l, r;\n            ll len;\n            ll h1;\n        };\n \n        vector<Node> tree;\n        vector<Node> hashes;\n        int pnt;\n \n        SegTree(vector<int> s)\n        {\n            tree.resize(4 * s.size());\n            hashes.resize(s.size());\n            hashes[0].h1 = s[0];\n            for (int i = 1; i < s.size(); i++)\n            {\n                hashes[i].h1 = (hashes[i - 1].h1 * M1 + s[i]) % MOD1;\n            }\n            pnt = s.size();\n        }\n        Node Get(int l, int r)\n        {\n            Node res;\n            res.l = l;\n            res.r = r;\n            res.len = r - l + 1;\n            res.h1 = (hashes[r].h1 - (l ? hashes[l - 1].h1 : 0) * deg1[r - l + 1]) % MOD1;\n            res.h1 = (res.h1 + MOD1) % MOD1;\n            return res;\n        }\n        Node Merge(Node L, Node R)\n        {\n            if (L.len + R.len < N) L.h1 = (L.h1 * deg1[R.len] + R.h1) % MOD1;\n            L.len += R.len;\n            return L;\n        }\n        void Set(int pos, Node X, int L, int R, int V)\n        {\n            if (L + 1 == R)\n            {\n                tree[V] = X;\n                return;\n            }\n            int M = (L + R) / 2;\n            if (pos < M) Set(pos, X, L, M, 2 * V + 1);\n            else Set(pos, X, M, R, 2 * V + 2);\n            tree[V] = Merge(tree[2 * V + 1], tree[2 * V + 2]);\n        }\n        void push_front(int l, int r)\n        {\n            pnt--;\n            Set(pnt, Get(l, r), 0, tree.size() / 4, 0);\n        }\n        Node Get(int chars, int L, int R, int V)\n        {\n            if (L + 1 == R)\n            {\n                return Get(tree[V].l, tree[V].l + chars - 1);\n            }\n            int M = (L + R) / 2;\n            if (tree[2 * V + 1].len >= chars)\n                return Get(chars, L, M, 2 * V + 1);\n            return Merge(tree[2 * V + 1], Get(chars - tree[2 * V + 1].len, M, R, 2 * V + 2));\n        }\n        Node Get(int chars)\n        {\n            return Get(chars, 0, tree.size() / 4, 0);\n        }\n    };\n \n    SegTree TT(s);\n    for (int i = 1; i <= s.size(); i++)\n    {\n        int pos1 = min_suf_each_pref[s.size() - i];\n        int pos2 = kek_suf_each_pref[s.size() - i];\n        int len = s.size() - i + 1 - pos1;\n \n        if (pos1 == pos2)\n        {\n            int LL = min_suf_each_pref[s.size() - i];\n            int RR = min((int)s.size() - i, min_suf_each_pref[s.size() - i] + i - 1);\n            h.push_front({LL, RR});\n            TT.push_front(LL, RR);\n            continue;\n        }\n        int t2 = -1;\n        int aval = s.size() - i + 1 - pos2 - len;\n \n        aval = min(aval, i);\n        if (TT.Get(aval).h1 != TT.Get(pos2 + len, pos2 + len + aval - 1).h1)\n            t2 = 1;\n \n        int shL = aval, shR = i;\n        while (t2 == -1 && shL + 1 < shR)\n        {\n            int sh = (shL + shR) / 2;\n            int x1 = TT.Get(sh).h1;\n            int x2 = TT.Merge(TT.Get(pos2 + len, s.size() - i), TT.Get(sh - aval)).h1;\n            if (x1 != x2)\n                shR = sh;\n            else\n                shL = sh;\n        }\n \n        if (t2 == -1 && shR < i)\n        {\n            int x1 = TT.Get(shR).h1;\n            int x2 = TT.Merge(TT.Get(pos2 + len, s.size() - i), TT.Get(shR - aval)).h1;\n            if (x1 != x2)\n            {\n                if ((x1 - x2 + MOD1) % MOD1 < MOD1 / 2)\n                {\n                    t2 = 2;\n                }\n                else\n                {\n                    t2 = 1;\n                }\n            }\n        }\n \n        if (t2 == 1)\n        {\n            int LL = min_suf_each_pref[s.size() - i];\n            int RR = min((int)s.size() - i, min_suf_each_pref[s.size() - i] + i - 1);\n            h.push_front({LL, RR});\n            TT.push_front(LL, RR);\n        }\n        else\n        {\n            int LL = kek_suf_each_pref[s.size() - i];\n            int RR = min((int)s.size() - i, kek_suf_each_pref[s.size() - i] + i - 1);\n            h.push_front({LL, RR});\n            TT.push_front(LL, RR);\n        }\n    }\n    vector<int> s2;\n    for (int j = 0; j < h.size(); j++)\n    {\n        for (int k = h[j].l; k <= h[j].r; k++)\n        {\n            s2.push_back(s[k]);\n            if (s2.size() == s.size())\n                break;\n        }\n        if (s2.size() == s.size())\n            break;\n    }\n    return s2;\n}\n \nvector<int> op(vector<int> s)\n{\n    for (int i = 1; i < s.size(); i++)\n    {\n        vector<int> h = {INF};\n        for (int j = 0; j + i <= s.size(); j++)\n        {\n            vector<int> t;\n            for (int k = 0; k < i; k++)\n                t.push_back(s[j + k]);\n            h = min(h, t);\n        }\n        for (int j = 0; j < i; j++)\n        {\n            s[s.size() - i + j] = h[j];\n        }\n    }\n    return s;\n}\n \nsigned main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    \n    deg1[0] = 1;\n    for (int i = 1; i < N; i++)\n        deg1[i] = deg1[i - 1] * M1 % MOD1;\n    for (int i = 3; i < N; i++)\n        H[i] = (((i - 1) & (i - 2)) == 0) + H[i - 1];\n \n    int n;\n    cin >> n;\n    vector<vector<int> > b(7, vector<int>(n));\n    for (int i = 0; i < n; i++) cin >> b[0][i];\n    // b[1] - 2\n    // b[2] - 5\n    // b[3] - 20\n    // b[4] - 230\n    // b[5] - 26795\n    // b[6] - stable\n    for (int i = 1; i < 6; i++) b[i] = fast_op(b[i - 1]);\n    int pos = 0;\n    while (pos + 1 < n && b[0][pos + 1] <= b[0][pos]) pos++;\n    for (int i = 0; i < pos; i++) b[6][i] = b[0][i];\n    for (int i = pos; i < n; i++) b[6][i] = b[0][pos];\n    int q;\n    cin >> q;\n    while (q--)\n    {\n        int i, j;\n        cin >> i >> j;\n        j--;\n        i = min(i, 6);\n        cout << b[i][j] << \"\\n\";\n    }\n    return 0;\n \n}",
    "tags": [
      "data structures",
      "hashing",
      "string suffix structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1622",
    "index": "A",
    "title": "Construct a Rectangle",
    "statement": "There are three sticks with integer lengths $l_1, l_2$ and $l_3$.\n\nYou are asked to break exactly one of them into two pieces in such a way that:\n\n- both pieces have positive (strictly greater than $0$) \\textbf{integer} length;\n- the total length of the pieces is equal to the original length of the stick;\n- it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides.\n\nA square is also considered a rectangle.\n\nDetermine if it's possible to do that.",
    "tutorial": "First, the condition about being able to construct a rectangle is the same as having two pairs of sticks of equal length. Let's fix the stick that we are going to break into two parts. Now there are two cases. The remaining two sticks can be the same. In that case, you can break the chosen stick into equal parts to make the second equal pair of sticks. Note, however, that the stick should have an even length, because otherwise the length of the resulting parts won't be integer. The remaining two sticks can be different. In that case, the chosen stick should have the length equal to their total length, because the only way to make two pairs of equal sticks is to produce the same two sticks as the remaining ones. Overall complexity: $O(1)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    vector<int> l(3);\n    for (int i = 0; i < 3; ++i)\n      cin >> l[i];\n    bool ok = false;\n    for (int i = 0; i < 3; ++i)\n      ok |= l[i] == l[(i + 1) % 3] + l[(i + 2) % 3];\n    for (int i = 0; i < 3; ++i) if (l[i] % 2 == 0)\n      ok |= l[(i + 1) % 3] == l[(i + 2) % 3];\n    cout << (ok ? \"YES\\n\" : \"NO\\n\");\n  }\n} ",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1622",
    "index": "B",
    "title": "Berland Music",
    "statement": "Berland Music is a music streaming service built specifically to support Berland local artist. Its developers are currently working on a song recommendation module.\n\nSo imagine Monocarp got recommended $n$ songs, numbered from $1$ to $n$. The $i$-th song had its predicted rating equal to $p_i$, where $1 \\le p_i \\le n$ and every integer from $1$ to $n$ appears exactly once. In other words, $p$ is a permutation.\n\nAfter listening to each of them, Monocarp pressed either a like or a dislike button. Let his vote sequence be represented with a string $s$, such that $s_i=0$ means that he disliked the $i$-th song, and $s_i=1$ means that he liked it.\n\nNow the service has to re-evaluate the song ratings in such a way that:\n\n- the new ratings $q_1, q_2, \\dots, q_n$ still form a permutation ($1 \\le q_i \\le n$; each integer from $1$ to $n$ appears exactly once);\n- every song that Monocarp liked should have a greater rating than every song that Monocarp disliked (formally, for all $i, j$ such that $s_i=1$ and $s_j=0$, $q_i>q_j$ should hold).\n\nAmong all valid permutations $q$ find the one that has the smallest value of $\\sum\\limits_{i=1}^n |p_i-q_i|$, where $|x|$ is an absolute value of $x$.\n\nPrint the permutation $q_1, q_2, \\dots, q_n$. If there are multiple answers, you can print any of them.",
    "tutorial": "Since we know that every disliked song should have lower rating than every liked song, we actually know which new ratings should belong to disliked songs and which should belong to the liked ones. The disliked songs take ratings from $1$ to the number of zeros in $s$. The liked songs take ratings from the number of zeros in $s$ plus $1$ to $n$. Thus, we have two independent tasks to solve. Let the disliked songs have ratings $d_1, d_2, \\dots, d_k$. Their new ratings should be $1, 2, \\dots, k$. We can show that if we sort the array $d$, then $|d'_1 - 1| + |d'_2 - 2| + \\dots + |d'_k - k|$ will be the lowest possible. The general way to prove it is to show that if the order has any inversions, we can always fix the leftmost of them (swap two adjacent values), and the cost doesn't increase. So the solution can be to sort triples $(s_i, p_i, i)$ and restore $q$ from the order of $i$ in these. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\tp = [int(x) for x in input().split()]\n\ts = input()\n\tl = sorted([[s[i], p[i], i] for i in range(n)])\n\tq = [-1 for i in range(n)]\n\tfor i in range(n):\n\t\tq[l[i][2]] = i + 1\n\tprint(*q)",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1622",
    "index": "C",
    "title": "Set or Decrease",
    "statement": "You are given an integer array $a_1, a_2, \\dots, a_n$ and integer $k$.\n\nIn one step you can\n\n- either choose some index $i$ and decrease $a_i$ by one (make $a_i = a_i - 1$);\n- or choose two indices $i$ and $j$ and set $a_i$ equal to $a_j$ (make $a_i = a_j$).\n\nWhat is the minimum number of steps you need to make the sum of array $\\sum\\limits_{i=1}^{n}{a_i} \\le k$? (You are allowed to make values of array negative).",
    "tutorial": "First, we can prove that the optimal way to perform operations is first, decrease the minimum value several (maybe, zero) times, then take several (maybe, zero) maximums and make them equal to the minimum value. The proof consists of several steps: Prove that first, we make decreases, only then sets: if some $a_i = a_i - 1$ is done after some $a_j = a_k$ then if there were no modification of $a_i$ then you can just move $a_i = a_i - 1$ earlier. Otherwise, there were $a_i = a_k$, and you can replace (... $a_i = a_k$, $a_i = a_i - 1$ ...) with (... $a_k = a_k - 1$, $a_i = a_k$ ...). We demonstrated how to move decrease operations before set operations. if some $a_i = a_i - 1$ is done after some $a_j = a_k$ then if there were no modification of $a_i$ then you can just move $a_i = a_i - 1$ earlier. Otherwise, there were $a_i = a_k$, and you can replace (... $a_i = a_k$, $a_i = a_i - 1$ ...) with (... $a_k = a_k - 1$, $a_i = a_k$ ...). We demonstrated how to move decrease operations before set operations. Prove that it's optimal to decrease only one element $a_i$: instead of decreasing $a_i$ by $x$ and $a_j$ by $y$ (where $a_i \\le a_j$), we can decrease $a_i$ by $x + y$ and replace all $a_k = a_j$ with $a_k = a_i$. instead of decreasing $a_i$ by $x$ and $a_j$ by $y$ (where $a_i \\le a_j$), we can decrease $a_i$ by $x + y$ and replace all $a_k = a_j$ with $a_k = a_i$. It's optimal to decrease the minimum element - it follows from proof of previous step. If we make $y$ set operations, it's optimal to set minimum value to $y$ maximum elements - should be obvious. To use the strategy, we'll firstly sort array $a$ in non-decreasing order. In this case, we'll decrease $a_1$ by $x$ and perform set to $y$ elements $a_{n-y+1}, \\dots, a_n$. The question is: how to minimize value of $x + y$? Note, that $0 \\le y < n$ (since setting the same position multiple times has no sense). Let's iterate over all possible values of $y$ and determine the minimum $x$ needed. The resulting array will consists of $(a_1 - x), a_2, a_3, \\dots, a_{n - y}, (a_1 - x), (a_1 - x), \\dots, (a_1 - x)$. Let's say that $P(i) = a_1 + a_2 + \\dots + a_i$ (and all $P(i)$ can be precomputed beforehand). Then the sum of array will become $(a_1 - x)(y + 1) + P(n - y) - a_1$, and we need $(a_1 - x)(y + 1) + P(n - y) - a_1 \\le k$ $(a_1 - x)(y + 1) \\le k - P(n - y) + a_1$ $a_1 - x \\le \\left\\lfloor \\frac{k - P(n - y) + a_1}{y + 1} \\right\\rfloor$ $x = a_1 - \\left\\lfloor \\frac{k - P(n - y) + a_1}{y + 1} \\right\\rfloor$ Using the formula above, we can for each $y$ ($0 \\le y < n$) calculate minimum $x$ required. But to be accurate, value $k - P(n - y) + a_1$ may be negative, and, usually in programming languages, integer division $\\frac{c}{d}$ for negative $c$ returns $\\left\\lceil \\frac{c}{d} \\right\\rceil$ instead of $\\left\\lfloor \\frac{c}{d} \\right\\rfloor$. There is an alternative solution: note that if $\\sum{a_i} \\le k$, then $a_1 \\le \\frac{k}{n}$. Note that if $a_1 \\ge \\frac{k}{n}$ then resulting value of $a_1 - x$ is in $\\frac{k}{n} - n < a_1 - x \\le \\frac{n}{k}$ and there are at most $n$ possible value for $x$. So, you can iterate over all possible $x$ and for each $x$ calculate minimum required $y$ either with binary search or two pointers.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\ntypedef long long li;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nint n;\nli k;\nvector<int> a;\n\ninline bool read() {\n\tif(!(cin >> n >> k))\n\t\treturn false;\n\ta.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> a[i];\n\treturn true;\n}\n\nli accurateFloor(li a, li b) {\n\tli val = a / b;\n\twhile (val * b > a)\n\t\tval--;\n\treturn val;\n}\n\ninline void solve() {\n\tsort(a.begin(), a.end());\n\tvector<li> pSum(n + 1, 0);\n\tfore (i, 0, n)\n\t\tpSum[i + 1] = pSum[i] + a[i];\n\t\n\tli ans = 1e18;\n\tfore (y, 0, n) {\n\t\t//(a[0] - x)(y + 1) + (pSum[n - y] - a[0]) <= k\n\t\t//a[0] - x <= (k - pSum[n - y] + a[0]) / (y + 1)\n\t\t//x == a[0] - (k - pSum[n - y] + a[0]) / (y + 1)\n\t\t\n\t\tli x = a[0] - accurateFloor(k - pSum[n - y] + a[0], y + 1);\n\t\tans = min(ans, y + max(0LL, x));\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\t\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tread();\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1622",
    "index": "D",
    "title": "Shuffle",
    "statement": "You are given a binary string (i. e. a string consisting of characters 0 and/or 1) $s$ of length $n$. You can perform the following operation with the string $s$ \\textbf{at most once}: choose a substring (a contiguous subsequence) of $s$ having \\textbf{exactly} $k$ characters 1 in it, and shuffle it (reorder the characters in the substring as you wish).\n\nCalculate the number of different strings which can be obtained from $s$ by performing this operation at most once.",
    "tutorial": "We could iterate on the substrings we want to shuffle and try to count the number of ways to reorder their characters, but, unfortunately, there's no easy way to take care of the fact that shuffling different substrings may yield the same result. Instead, we will iterate on the first and the last character that are changed. Let these characters be $i$ and $j$. First of all, let's check that they can belong to the same substring we can shuffle - it is the case if the string contains at least $k$ characters 1, and the substring from the $i$-th character to the $j$-th character contains at most $k$ characters 1. Then, after we've fixed the first and the last characters that are changed, we have to calculate the number of ways to shuffle the characters between them (including them) so that both of these characters are changed. Let's calculate $c_0$ and $c_1$ - the number of characters 0 and 1 respectively in the substring. Then, we need to modify these two values: for example, if the $i$-th character is 0, then since it is the first changed character, it should become 1, so we need to put 1 there and decrease $c_1$ by one. The same for the $j$-th character. Let $c'_0$ and $c'_1$ be the values of $c_0$ and $c_1$ after we take care of the fact that the $i$-th and the $j$-th character are fixed. The remaining characters can be in any order, so the number of ways to arrang them is ${{c'_0 + c'_1}\\choose{c'_0}}$. We can add up these values for all pairs ($i, j$) such that we can shuffle a substring containing these two characters. We won't be counting any string twice because we ensure that $i$ is the first changed character, and $j$ is the last changed character. Don't forget to add $1$ to the answer - the string we didn't count is the original one. This solution works in $O(n^2)$, but the problem is solvable in $O(n)$.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n    int k;\n    cin >> k;\n    string s;\n    cin >> s;\n    vector<int> p(n + 1);\n    for(int i = 0; i < n; i++) p[i + 1] = p[i] + (s[i] - '0');\n    vector<vector<int>> C(n + 1);\n    for(int i = 0; i <= n; i++)\n    {\n        C[i].resize(i + 1);\n        C[i][0] = C[i][i] = 1;\n        for(int j = 1; j < i; j++)\n            C[i][j] = add(C[i - 1][j], C[i - 1][j - 1]);\n    }\n    int ans = 1;\n    for(int i = 0; i < n; i++)\n        for(int j = i + 1; j < n; j++)\n        {\n            int cnt = j + 1 - i;\n            int cnt1 = p[j + 1] - p[i];\n            if(cnt1 > k || p[n] < k) continue;\n            cnt -= 2;\n            if(s[i] == '0') cnt1--;\n            if(s[j] == '0') cnt1--;\n            if(cnt1 <= cnt && cnt1 >= 0 && cnt >= 0)\n                ans = add(ans, C[cnt][cnt1]);\n        }\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1622",
    "index": "E",
    "title": "Math Test",
    "statement": "Petya is a math teacher. $n$ of his students has written a test consisting of $m$ questions. For each student, it is known which questions he has answered correctly and which he has not.\n\nIf the student answers the $j$-th question correctly, he gets $p_j$ points (otherwise, he gets $0$ points). Moreover, the points for the questions are distributed in such a way that the array $p$ is a permutation of numbers from $1$ to $m$.\n\nFor the $i$-th student, Petya knows that he expects to get $x_i$ points for the test. Petya wonders how unexpected the results could be. Petya believes that the surprise value of the results for students is equal to $\\sum\\limits_{i=1}^{n} |x_i - r_i|$, where $r_i$ is the number of points that the $i$-th student has got for the test.\n\nYour task is to help Petya find such a permutation $p$ for which the surprise value of the results is maximum possible. If there are multiple answers, print any of them.",
    "tutorial": "Note that there are only two ways to fix the result of the operation of taking an absolute value in the expression $|x_i - r_i|$: $x_i - r_i$ or $r_i - x_i$. Since the value of $n$ is small enough that we can iterate over all $2^n$ options, and choose the one for which the sum is maximum. For each student, let's fix with which sign their total points will contribute to the answer, then $x_i$ will contribute with the opposite sign. Now, for the question $j$ we can calculate $val_j$ - the coefficient with which $p_j$ will contribute to the answer. It remains to choose such a permutation $p$ that the sum $\\sum\\limits_{j=1}^m p_j val_j$ is the maximum possible. From here we can see that if $val_j < val_i$ (for some $i$ and $j$), then $p_j < p_i$ must holds, otherwise we can swap $p_j$ and $p_i$, and the answer will increase. This means that we can sort all questions in ascending order by the value in the $val$ array, and assign the value $x$ in the array $p$ to the $x$-th question in ascending order. For some of $2^n$ options, the permutations we found may be illegal because it can happen that we consider the case that some $|x_i - r_i|$ evaluates as $(x_i - r_i)$, but in the best permutation we found for that option, it evaluates as $(r_i - x_i)$. We can just ignore it because this will never be the case with the option giving the highest possible surprise value - if this thing happened for some option to choose the signs of $r_i$, then, if we flip the signs for the students such that the conditions on them are not met in the optimal permutation, we'll get a combination of signs that yields a higher surprise value.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nint main() {\n  int t;\n  scanf(\"%d\", &t);\n  while (t--) {\n    int n, m;\n    scanf(\"%d%d\", &n, &m);\n    vector<int> x(n);\n    forn(i, n) scanf(\"%d\", &x[i]);\n    vector<vector<int>> a(n, vector<int>(m));\n    forn(i, n) forn(j, m) scanf(\"%1d\", &a[i][j]);\n    \n    int ans = -1;\n    vector<int> best;\n    forn(mask, 1 << n) {\n      vector<int> val(m);\n      forn(i, n) forn(j, m) if (a[i][j]) val[j] += ((mask >> i) & 1) ? +1 : -1;\n      int res = 0;\n      forn(i, n) res += ((mask >> i) & 1) ? -x[i] : x[i];\n      vector<int> p(m);\n      iota(p.begin(), p.end(), 0);\n      sort(p.begin(), p.end(), [&](int x, int y) { return val[x] < val[y]; });\n      forn(i, m) res += val[p[i]] * (i + 1);\n      if (res > ans) ans = res, best = p;\n    }\n    \n    vector<int> ansPerm(m);\n    forn(i, m) ansPerm[best[i]] = i;\n    forn(i, m) printf(\"%d \", ansPerm[i] + 1);\n    puts(\"\");\n  }\n} ",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1622",
    "index": "F",
    "title": "Quadratic Set",
    "statement": "Let's call a set of positive integers $a_1, a_2, \\dots, a_k$ quadratic if the product of the factorials of its elements is a square of an integer, i. e. $\\prod\\limits_{i=1}^{k} a_i! = m^2$, for some integer $m$.\n\nYou are given a positive integer $n$.\n\nYour task is to find a quadratic subset of a set $1, 2, \\dots, n$ of maximum size. If there are multiple answers, print any of them.",
    "tutorial": "A good start to solve the problem would be to check the answers for small values of $n$. One can see that the answers (the sizes of the maximum subsets) are not much different from $n$ itself, or rather not less than $n-3$. Let's try to prove that this is true for all $n$. Consider $n$ is even. Let $n=2k$, let's see what the product is equal to if we take all the numbers from $1$ to $n$. $\\prod\\limits_{i=1}^{2k} i! = \\prod\\limits_{i=1}^{k} (2i-1)! (2i)! = \\prod\\limits_{i=1}^{k} (2i-1)!^2 2i = (\\prod\\limits_{i=1}^{k} (2i-1)!)^2 \\prod\\limits_{i=1}^{k} 2i = (\\prod\\limits_{i=1}^{k} (2i-1)!)^2 2^k k!$ From here we can see that for even $k$ the answer is at least $n-1$, because we can delete $k!$ and the product of the remaining factorials will be the square of an integer, for odd $k$ the answer is at least $n-2$, because we can delete $2!$ and $k!$. It remains to prove that the answer is at least $n-3$ for odd $n$. This is easy to do, because the answer for $n$ is not less than the answer for $n-1$ minus $1$, because we can delete $n!$ and solve the task with a smaller $n$ value. Moreover, it can be seen from the previous arguments that the answer $3$ can only be for $n \\equiv 3 \\pmod 4$, and we already know that in this case one of the correct answers is to remove the factorials $2, \\frac{n-1}{2}, n$. It remains to learn how to check whether it is possible to remove $1$ or $2$ numbers so that the remaining product of factorials is the square of an integer. To do this, we can use XOR hashes. Let's assign each prime number a random $64$-bit number. For composite numbers, the hash is equal to the XOR of hashes of all its prime divisors from factorization. Thus, if some prime is included in the number an even number of times, it will not affect the value of the hash, which is what we need. The hash of the product of two numbers is equal to the XOR of the hashes of these numbers. Let's denote the hash function as $H$. Using the above, let's calculate $H(i)$ for all $i$ from $1$ to $n$, as well as $H(i!)$ for all $i$ from $1$ to $n$, this is easy to do, because $H(i!) = H((i-1)!) \\oplus H(i)$. We will also store a map $H(i!) \\rightarrow i$. Let's calculate the hash $H(1!2! \\cdots n!)$ and denote it as $fp$. It remains to consider the following cases: if $fp = 0$, then the current product is already the square of an integer; for an answer of size $n-1$, we have to check that there exists such a $i$ that $H(i!) \\oplus fp = 0$. To find such $i$, let's check whether the map contains $fp$; for an answer of size $n-2$, we have to check that there are such $i$ and $j$ that $H(i!) \\oplus H(j!) \\oplus fp = 0$. To do this, iterate over $i$, and then check whether map contains $H(i!) \\oplus fp$; otherwise, the answer is $n-3$, and there is an answer, where all numbers except $2, \\frac{n-1}{2}, n$ are taken.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000 * 1000 + 13;\n\nusing li = unsigned long long;\n\nint pr[N];\nli hs[N], f[N];\nunordered_map<li, int> rf;\n\nint main() {\n  int n;\n  scanf(\"%d\", &n);\n  \n  mt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());\n  iota(pr, pr + N, 0);\n  for (int i = 2; i <= n; ++i) if (pr[i] == i) {\n    for (int j = i; j <= n; j += i) pr[j] = min(pr[j], i);\n    hs[i] = rnd();\n  }\n  for (int i = 2; i <= n; ++i) {\n    f[i] = f[i - 1];\n    int x = i;\n    while (x != 1) {\n      f[i] ^= hs[pr[x]];\n      x /= pr[x];\n    }\n    rf[f[i]] = i;\n  }\n  \n  auto solve = [&] (int n) -> vector<int> {\n    li fp = 0;\n    for (int i = 2; i <= n; ++i) fp ^= f[i];\n    if (fp == 0) return {};\n    if (rf.count(fp)) return {rf[fp]};\n    for (int i = 2; i <= n; ++i) {\n        li x = f[i] ^ fp;\n        if (rf.count(x) && rf[x] != i) return {rf[x], i};\n    }\n    return {2, n / 2, n};\n  };\n  \n  auto ans = solve(n);\n  printf(\"%d\\n\", n - (int)ans.size());\n  for (int i = 1; i <= n; ++i)\n    if (find(ans.begin(), ans.end(), i) == ans.end()) printf(\"%d \", i);\n  puts(\"\");\n} ",
    "tags": [
      "constructive algorithms",
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1623",
    "index": "A",
    "title": "Robot Cleaner",
    "statement": "A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $n$ rows and $m$ columns. The rows of the floor are numbered from $1$ to $n$ from top to bottom, and columns of the floor are numbered from $1$ to $m$ from left to right. The cell on the intersection of the $r$-th row and the $c$-th column is denoted as $(r,c)$. The initial position of the robot is $(r_b, c_b)$.\n\nIn one second, the robot moves by $dr$ rows and $dc$ columns, that is, after one second, the robot moves from the cell $(r, c)$ to $(r + dr, c + dc)$. Initially $dr = 1$, $dc = 1$. If there is a vertical wall (the left or the right walls) in the movement direction, $dc$ is reflected before the movement, so the new value of $dc$ is $-dc$. And if there is a horizontal wall (the upper or lower walls), $dr$ is reflected before the movement, so the new value of $dr$ is $-dr$.\n\nEach second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row \\textbf{or} the same column as its position. There is only one dirty cell at $(r_d, c_d)$. The job of the robot is to clean that dirty cell.\n\n\\begin{center}\nIllustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes.\n\\end{center}\n\nGiven the floor size $n$ and $m$, the robot's initial position $(r_b, c_b)$ and the dirty cell's position $(r_d, c_d)$, find the time for the robot to do its job.",
    "tutorial": "Let's consider the 1-D problem of this problem: there are $n$ cells, lying in a row. The robot is at the $x$-th cell, and the dirty cell is at the $y$-th cell. Each second, the robot cleans the cell at its position. The robot initially moves by 1 cell to the right each second. If there is no cell in the movement direction, its direction will be reflected. What is the minimum time for the robot to clean the dirty cell? There are two cases needed to be considered: If $x \\le y$, then the answer is $y - x$. The robot just goes straight to the dirty cell. Otherwise, if $x > y$, then the robot needs to go to the right endpoint first, and then go back to the dirty cell. Going to the right endpoint takes $n - x$ seconds, and going from that cell to the dirty cell takes $n - y$ seconds. Therefore, the answer for this case is $2 \\cdot n - x - y$. Going back to our original problem, we can solve it by dividing it into two 1-D versions. This is done by projecting the position of the robot and the dirty cell onto the $Ox$ and $Oy$ axis as follows. By doing so, we can see that we can clean the dirty cell, if and only if one of the projections of the robot can reach the dirty cell. Therefore, the answer is the minimum between the answers of the two sub-problems.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    int ntest;\n    cin >> ntest;\n    while (ntest--) {\n        int n, m, rb, cb, rd, cd;\n        cin >> n >> m >> rb >> cb >> rd >> cd;\n        cout << min(\n            rb <= rd ? rd - rb : 2 * n - rb - rd,\n            cb <= cd ? cd - cb : 2 * m - cb - cd\n        ) << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1623",
    "index": "B",
    "title": "Game on Ranges",
    "statement": "Alice and Bob play the following game. Alice has a set $S$ of disjoint ranges of integers, initially containing only one range $[1, n]$. In one turn, Alice picks a range $[l, r]$ from the set $S$ and asks Bob to pick a number in the range. Bob chooses a number $d$ ($l \\le d \\le r$). Then Alice removes $[l, r]$ from $S$ and puts into the set $S$ the range $[l, d - 1]$ (if $l \\le d - 1$) and the range $[d + 1, r]$ (if $d + 1 \\le r$). The game ends when the set $S$ is empty. We can show that the number of turns in each game is exactly $n$.\n\nAfter playing the game, Alice remembers all the ranges $[l, r]$ she picked from the set $S$, but Bob does not remember any of the numbers that he picked. But Bob is smart, and he knows he can find out his numbers $d$ from Alice's ranges, and so he asks you for help with your programming skill.\n\nGiven the list of ranges that Alice has picked ($[l, r]$), for each range, help Bob find the number $d$ that Bob has picked.\n\nWe can show that there is always a unique way for Bob to choose his number for a list of valid ranges picked by Alice.",
    "tutorial": "If the length of a range $[l, r]$ is 1 (that is, $l = r$), then $d = l = r$. Otherwise, if Bob picks a number $d$, then Alice has to put the sets $[l, d - 1]$ and $[d + 1, r]$ (if existed) back to the set. Thus, there will be a moment that Alice picks the range $[l, d - 1]$ (if existed), and another moment to pick the range $[d + 1, r]$ (if existed) as well. Using the above observation, for each range $[l, r]$, we can iterate the number $d$ from $l$ to $r$, check if both range $[l, d - 1]$ (if $d > l$) and $[d + 1, r]$ (if $d < r$) existed in the Alice's picked ranges. Or in other words, check if these ranges are given in the input. For checking, we can either use set data structures supported in most programming languages or simply use a 2-dimensional array for marking the picked ranges. The time complexity is, therefore, $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    \n    int ntest;\n    cin >> ntest;\n    while (ntest--) {\n        int n;\n        cin >> n;\n        vector mark(n + 1, vector<bool>(n + 1));\n        vector<int> l(n), r(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> l[i] >> r[i];\n            mark[l[i]][r[i]] = true;\n        }\n        for (int i = 0; i < n; ++i) {\n            for (int d = l[i]; d <= r[i]; ++d) {\n                if ((d == l[i] or mark[l[i]][d - 1]) and (d == r[i] or mark[d + 1][r[i]])) {\n                    cout << l[i] << ' ' << r[i] << ' ' << d << '\\n';\n                    break;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1623",
    "index": "C",
    "title": "Balanced Stone Heaps",
    "statement": "There are $n$ heaps of stone. The $i$-th heap has $h_i$ stones. You want to change the number of stones in the heap by performing the following process once:\n\n- You go through the heaps from the $3$-rd heap to the $n$-th heap, in this order.\n- Let $i$ be the number of the current heap.\n- You can choose a number $d$ ($0 \\le 3 \\cdot d \\le h_i$), move $d$ stones from the $i$-th heap to the $(i - 1)$-th heap, and $2 \\cdot d$ stones from the $i$-th heap to the $(i - 2)$-th heap.\n- So after that $h_i$ is decreased by $3 \\cdot d$, $h_{i - 1}$ is increased by $d$, and $h_{i - 2}$ is increased by $2 \\cdot d$.\n- You can choose different or same $d$ for different operations. Some heaps may become empty, but they still count as heaps.\n\nWhat is the maximum number of stones in the smallest heap after the process?",
    "tutorial": "The answer can be binary searched. That is, we can find the biggest number $x$, such that we can make all heap having at least $x$ stones. So our job here is to check if we can satisfy the said condition with a number $x$. Let's consider a reversed problem: we go from $1$ to $n - 2$, pick a number $d$ ($0 \\le 3\\cdot d \\le h_i$), move $d$ and $2\\cdot d$ stones from the $i$-th heap to the $i + 1$ heap and $i + 2$-th heap respectively. In this problem, we can greedily move the stones: since $x$ is the minimum required stones, if at some moment, we have $h_i < x$, then we can not satisfy the condition for $x$ anymore. Otherwise, it is always the best to use as many stones as we can, that is, choose $d = \\left \\lfloor \\frac {h_i - x} 3 \\right \\rfloor$, and move $d$ and $2\\cdot d$ stones to the $i + 1$ and $i + 2$ heaps respectively. In the end, if all the heap are not less than $x$, we can conclude that we can make all heaps having not less than $x$ stones with this process. Going back to our original problem, it seems like we can solve it by doing the process in the reversed order, as discussed above. But there is a catch! The number of stones that can be moved must not exceed the number of the stones in the original heap! So, if we call $h_i$ - the original heap size, and $h'_i$ - the current modified heap size, then the number of stones that we should move is $d = \\left \\lfloor \\frac {\\min \\{ h_i, h'_i - x \\}} 3 \\right\\rfloor$ at each step. There is not much to note about this problem.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int maxn = 201010;\nint n;\nint h[maxn];\n \nbool check(int x) {\n    vector<int> cur_h(h, h + n);\n    for (int i = n - 1; i >= 2; --i) {\n        if (cur_h[i] < x) return false;\n        int d = min(h[i], cur_h[i] - x) / 3;\n        cur_h[i - 1] += d;\n        cur_h[i - 2] += 2 * d;\n        // we don't need to fix cur_h[i] since we are not going back\n    }\n    return cur_h[0] >= x and cur_h[1] >= x;\n}\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    \n    int ntest;\n    cin >> ntest;\n    while (ntest--) {\n        cin >> n;\n        for (int i = 0; i < n; ++i) cin >> h[i];\n        int l = 0, r = *max_element(h, h + n);\n        while (l < r) {\n            int mid = l + (r - l + 1) / 2;\n            if (check(mid)) l = mid;\n            else r = mid - 1;\n        }\n        cout << l << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1623",
    "index": "D",
    "title": "Robot Cleaner Revisit",
    "statement": "The statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.\n\nA robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $n$ rows and $m$ columns. The rows of the floor are numbered from $1$ to $n$ from top to bottom, and columns of the floor are numbered from $1$ to $m$ from left to right. The cell on the intersection of the $r$-th row and the $c$-th column is denoted as $(r,c)$. The initial position of the robot is $(r_b, c_b)$.\n\nIn one second, the robot moves by $dr$ rows and $dc$ columns, that is, after one second, the robot moves from the cell $(r, c)$ to $(r + dr, c + dc)$. Initially $dr = 1$, $dc = 1$. If there is a vertical wall (the left or the right walls) in the movement direction, $dc$ is reflected before the movement, so the new value of $dc$ is $-dc$. And if there is a horizontal wall (the upper or lower walls), $dr$ is reflected before the movement, so the new value of $dr$ is $-dr$.\n\nEach second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row \\textbf{or} the same column as its position. There is only one dirty cell at $(r_d, c_d)$. The job of the robot is to clean that dirty cell.\n\nAfter a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability $\\frac p {100}$ only, and not performed with probability $1 - \\frac p {100}$. The cleaning or not cleaning outcomes are independent each second.\n\nGiven the floor size $n$ and $m$, the robot's initial position $(r_b, c_b)$ and the dirty cell's position $(r_d, c_d)$, find the \\textbf{expected time} for the robot to do its job.\n\nIt can be shown that the answer can be expressed as an irreducible fraction $\\frac x y$, where $x$ and $y$ are integers and $y \\not \\equiv 0 \\pmod{10^9 + 7} $. Output the integer equal to $x \\cdot y^{-1} \\bmod (10^9 + 7)$. In other words, output such an integer $a$ that $0 \\le a < 10^9 + 7$ and $a \\cdot y \\equiv x \\pmod {10^9 + 7}$.",
    "tutorial": "In order to see how my solution actually works, let's solve this problem, the math way! You can skip to the \"In general, ...\" part if you don't really care about these concrete examples. First of all, let $\\overline{p}$ be the probability of not cleaning, that is, the probability that the robot will not be able to clean. So $\\overline{p} = 1 - \\frac p {100}$. Let's revisit the first example again. In this example, the robot has 2 states: when it was at position $(1, 1)$, and when it was at $(2, 2)$. Let $x$ be the answer for this problem when the robot started at $(1, 1)$, and $y$ be the answer for this problem when the robot started at $(2, 2)$. Let's consider the first state. If the robot can clean, it spends $0$ seconds to clean the dirty cell. Otherwise, it will spend $1 + y$ seconds. Therefore, we have an equation: $x = \\overline{p} (1 + y)$. Similarly, we also have the an equation: $y = \\overline{p}(1 + x)$, since these two states are symetrical. Subtituding $y = \\overline{p}(1 + x)$ into $x = \\overline{p}(1 + y)$, we have $\\begin{array}{crcl} & x & = & \\overline{p}(1 + \\overline{p}(1 + x)) \\end{array}$ By substituting $\\overline p$ in, we can find the value of $x$. Let's consider the other example. In this example, the robot has 4 states: when it is at $(1, 1)$, when it is at $(2, 2)$ but going to the right, when it is at $(1, 3)$, and when it is at $(2, 2)$ but going to the left. Let the answer for these states be $x_1, x_2, x_3,$ and $x_4$. Similar to the previous example, we can write down the equations: $\\begin{cases} x_1 = 1 + x_2 & \\text{(because at }(1, 1)\\text{ the robot cannot clean the dirty cell)} \\\\ x_2 = \\overline p (1 + x_3) \\\\ x_3 = \\overline p (1 + x_4) \\\\ x_4 = \\overline p (1 + x_1) \\end{cases}$ Substituting these equations back to back, we can have the following equation: $x_1 = 1 + \\overline p \\left( 1 + \\overline p \\left( 1 + \\overline p \\left( 1 + x \\right) \\right) \\right)$ And again, if we substitute $\\overline p$ in, the answer can be found easily. In general, the path that the robot takes will form a cycle, containing the initial position. If we call $x$ the answer to the problem at the initial position, the equation we need to solve will have the following form: $x = a_1 \\left( 1 + a_2 \\left( 1 + a_3 \\left( 1 + \\ldots a_k \\left(1 + x \\right ) \\ldots \\right) \\right) \\right)$ where $k$ is the number of states in the cycle, and $a_i$ is some coefficient. $a_i = \\overline p$ if, at the $i$-th state in the cycle, we have an opportunity to clean the dirty cell, and $1$ otherwise. The equation can easily be solved by expanding the brackets from the innermost to the outermost, by going through the cycle in the reverse order. After the expansion, the equation will be a very simple linear equation with the form $x = u + vx$, and the solution will be $x = \\frac u {1 - v}$. To construct the equation, we can first find the cycle by either DFS or BFS, and go through the cycle in the reverse order for expansion. Or, we can do the reverse simulation, maintaining the coefficient $u$ and $v$ right away. And even better, we can just forget about the cycle and iterate exactly $4(n - 1)(m - 1)$ times (not $4nm$ though), since $4(n - 1)(m - 1)$ will always be the multiple of $k$ - the cycle length. The time complexity of this solution is $O(nm)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing ll = long long;\n \n// I swear that I type this everytime, so this is not count as template :))\n#define defop(type, op) \\\n    inline friend type operator op (type u, const type& v) { return u op ##= v; } \\\n    type& operator op##=(const type& o)\ntemplate<int mod>\nstruct modint {\n    int x;\n    // note that there is no correction, simply for speed\n    modint(int xx = 0): x(xx) {}\n    modint(ll xx): x(int(xx % mod)) {}\n    defop(modint, +) {\n        if ((x += o.x) >= mod) x -= mod;\n        return *this;\n    }\n    defop(modint, -) {\n        if ((x -= o.x) < 0) x += mod;\n        return *this;\n    }\n    defop(modint, * ) { return *this = modint(1ll * x * o.x); }\n    modint pow(ll exp) const {\n        modint ans = 1, base = *this;\n        for (; exp > 0; exp >>= 1, base *= base)\n            if (exp & 1) ans *= base;\n        return ans;\n    }\n    defop(modint, /) { return *this *= o.pow(mod - 2); }\n};\nusing mint = modint<(int)1e9 + 7>;\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    \n    int ntest;\n    cin >> ntest;\n    while (ntest--) {\n        int n, m, rb, cb, rd, cd;\n        mint p;\n        cin >> n >> m >> rb >> cb >> rd >> cd >> p.x;\n        p = 1 - p / 100;  // probability of not cleaning\n        int dr = -1, dc = -1;\n        mint u = 0, v = 1;\n        for (int i = 0; i < 4 * (n - 1) * (m - 1); ++i) {\n            if (!(1 <= rb + dr and rb + dr <= n)) dr = -dr;\n            if (!(1 <= cb + dc and cb + dc <= m)) dc = -dc;\n            rb += dr;\n            cb += dc;\n            u += 1;\n            if (rb == rd or cb == cd) {\n                u *= p;\n                v *= p;\n            }\n        }\n        cout << (u / (1 - v)).x << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "implementation",
      "math",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1623",
    "index": "E",
    "title": "Middle Duplication",
    "statement": "A binary tree of $n$ nodes is given. Nodes of the tree are numbered from $1$ to $n$ and the root is the node $1$. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote $l_u$ and $r_u$ as the left and the right child of the node $u$ respectively, $l_u = 0$ if $u$ does not have the left child, and $r_u = 0$ if the node $u$ does not have the right child.\n\nEach node has a string label, initially is a single character $c_u$. Let's define the string representation of the binary tree as the concatenation of the labels of the nodes in the in-order. Formally, let $f(u)$ be the string representation of the tree rooted at the node $u$. $f(u)$ is defined as follows: $$ f(u) = \\begin{cases} <empty string>, & \\text{if }u = 0; \\\\ f(l_u) + c_u + f(r_u) & \\text{otherwise}, \\end{cases} $$ where $+$ denotes the string concatenation operation.\n\nThis way, the string representation of the tree is $f(1)$.\n\nFor each node, we can duplicate its label \\textbf{at most once}, that is, assign $c_u$ with $c_u + c_u$, but only if $u$ is the root of the tree, or if its parent also has its label duplicated.\n\nYou are given the tree and an integer $k$. What is the lexicographically smallest string representation of the tree, if we can duplicate labels of at most $k$ nodes?\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Firstly, we need to determine if a label should be duplicated at all. For example, in the string \"bac\", the characters 'b' and 'c' should never be duplicated, since duplicating them always make the result worse (\"bbac\" and \"bacc\" are both lexicographically greater than \"bac\"). This is because, next to the character 'b' is 'a', and 'a' is smaller than 'b'. For the case of 'c', after it there is no more characters, thus we should not duplicate it as well. Let's call a node good if duplicating its label will make the result better (lexicographically smaller). To find good nodes, we can find the initial string representation of the tree using DFS. A node is good if the next different character in the string representation must exist and is smaller than the label of the node. After finding the good nodes, let's find the first label that we should duplicate. This label must be from a good label and must lie as close to the start of the string as possible. We can find this label, also by DFS. We still do DFS in the in-order, and the first good node having depth not exceed $k$ will be the first node to have the label duplicated. And by duplicating this node, we must duplicate the labels of its ancestors as well. Note that during the DFS process, if we don't duplicate a node, we should not go to the right sub-tree. Let's call the cost of duplicating a node the number of its ancestors that is not duplicated before. The cost of the first duplicated node is its depth, which can be calculated while doing DFS. The cost of the other nodes can also be maintained while doing DFS as well: if a node is duplicated, the root going to the right sub-tree will have a cost of $1$. So overall we will have the following DFS algorithm on the node $u$: If $u = 0$, then we do nothing. If $cost[u] > k$ , we do nothing. Assign $cost[l[u]] \\gets cost[u] + 1$ and do DFS on $l[u]$. If $l[u]$ has it label duplicated, we duplicate the label of $u$. Otherwise, if $u$ is good, we duplicate the label of $u$ as well, and decrease $k$ by $cost[u]$. If $u$ is duplicated, then assign $cost[r[u]] \\gets 1$, do DFS on $r[u]$. For implementation, we can pass the variable cost together with $u$ to the DFS function, and don't need to declare a global array. The overall time complexity of this solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int maxn = 202020;\nint n, k;\nstring c;\nint l[maxn], r[maxn];\n \nvector<int> in_order;\nvoid build_in_order(int u) {\n    if (u == 0) return ;\n    build_in_order(l[u]);\n    in_order.push_back(u);\n    build_in_order(r[u]);\n}\n \nbool good[maxn];\nbool duplicated[maxn];\n \n// the function try to greedily duplicate the nodes.\n// u: the curernt node\n// cost: distance to the nearest duplicated ancestor.\n// the function will \"destroy\" the value of k\nvoid dfs(int u, int cost = 1) {\n    if (u == 0) return ;\n    if (cost > k) return ;\n    dfs(l[u], cost + 1);\n    if (duplicated[l[u]]) {\n        duplicated[u] = true;\n    } else if (good[u]) {\n        duplicated[u] = true;\n        k -= cost;\n    }\n    if (duplicated[u]) dfs(r[u], 1);\n}\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    cin >> n >> k;\n    cin >> c;\n    c = ' ' + c;\n    for (int i = 1; i <= n; ++i) {\n        cin >> l[i] >> r[i];\n    }\n    build_in_order(1);\n    char last_diff = c[in_order.back()];\n    for (int i = n - 2; i >= 0; --i) {\n        int u = in_order[i];\n        int v = in_order[i + 1];\n        if (c[u] != c[v]) {\n            last_diff = c[v];\n        }\n        if (c[u] < last_diff) {\n            good[u] = true;\n        }\n    }\n    \n    dfs(1);\n    for (auto u: in_order) {\n        cout << c[u];\n        if (duplicated[u]) cout << c[u];\n    }\n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy",
      "strings",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1624",
    "index": "A",
    "title": "Plus One on the Subset",
    "statement": "Polycarp got an array of integers $a[1 \\dots n]$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $a_1=a_2=\\dots=a_n$).\n\n- In one operation, he can take some indices in the array and increase the elements of the array at those indices by $1$.\n\nFor example, let $a=[4,2,1,6,2]$. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by $1$. As a result, in one operation, he can get a new state of the array $a=[5,3,1,7,2]$.\n\nWhat is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become $a_1=a_2=\\dots=a_n$)?",
    "tutorial": "Let's sort the numbers in ascending order. It becomes immediately clear that it is not profitable for us to increase the numbers that are equal to the last number (the maximum of the array). It turns out that every time you need to take such a subset of the array, in which all the numbers, except the maximums. And once for each operation, the numbers in the subset are increased by one, then how many times can the operation be performed on the array? Accordingly $max(a) - min(a)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\n\nvoid solve() {\n    int n;\n    cin >> n;\n    int a[n];\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    int MIN = INT_MAX;\n    int MAX = INT_MIN;\n    for (int i = 0; i < n; ++i) {\n        MIN = min(MIN, a[i]);\n        MAX = max(MAX, a[i]);\n    }\n    cout << MAX - MIN << '\\n';\n}\nint main() {\n    int tests;\n    cin >> tests;\n    forn(tt, tests) {\n        solve();\n    }\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1624",
    "index": "B",
    "title": "Make AP",
    "statement": "Polycarp has $3$ positive integers $a$, $b$ and $c$. He can perform the following operation \\textbf{exactly once}.\n\n- Choose a \\textbf{positive} integer $m$ and multiply \\textbf{exactly one} of the integers $a$, $b$ or $c$ by $m$.\n\nCan Polycarp make it so that after performing the operation, the sequence of three numbers $a$, $b$, $c$ (\\textbf{in this order}) forms an arithmetic progression? Note that you \\textbf{cannot change} the order of $a$, $b$ and $c$.\n\nFormally, a sequence $x_1, x_2, \\dots, x_n$ is called an arithmetic progression (AP) if there exists a number $d$ (called \"common difference\") such that $x_{i+1}=x_i+d$ for all $i$ from $1$ to $n-1$. In this problem, $n=3$.\n\nFor example, the following sequences are AP: $[5, 10, 15]$, $[3, 2, 1]$, $[1, 1, 1]$, and $[13, 10, 7]$. The following sequences are not AP: $[1, 2, 4]$, $[0, 1, 0]$ and $[1, 3, 2]$.\n\nYou need to answer $t$ independent test cases.",
    "tutorial": "Let's iterate over the number that we want to multiply by $m$. How can we check that we can multiply the current number so that an AP is formed? Note that those $2$ numbers that we do not touch should form an AP themselves. For instance, let at the current operation we want somehow multiply the number $c$. Then $a = x_1$, and $b = x_2 = x_1 + d$. Note that $b - a = x_1 + d - x_1 = d$. Thus, we know what $d$ is. Also we know that $c = x_1 + 2 \\cdot d = a + 2 \\cdot d$. Let's check if $a + 2 \\cdot d$ is divisible by $c$. If yes, then we have found the answer, if not, then move on to the next number. We do the same for $a$ and $b$. Be careful with non positive numbers, integer divisions and other edge cases.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solveTest() {\n    int a, b, c;\n    cin >> a >> b >> c;\n\n    int new_a = b - (c - b);\n    if(new_a >= a && new_a % a == 0 && new_a != 0) {\n        cout << \"YES\\n\";\n        return;\n    }\n\n    int new_b = a + (c - a)/2;\n    if(new_b >= b && (c-a)%2 == 0 && new_b % b == 0 && new_b != 0) {\n        cout << \"YES\\n\";\n        return;\n    }\n\n    int new_c = a + 2*(b - a);\n    if(new_c >= c && new_c % c == 0 && new_c != 0) {\n        cout << \"YES\\n\";\n        return;\n    }\n\n    cout << \"NO\\n\";\n    return;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0); cout.tie(0);\n    int tt;\n    cin >> tt;\n    while(tt--)\n        solveTest();\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1624",
    "index": "C",
    "title": "Division by Two and Permutation",
    "statement": "You are given an array $a$ consisting of $n$ positive integers. You can perform operations on it.\n\nIn one operation you can replace any element of the array $a_i$ with $\\lfloor \\frac{a_i}{2} \\rfloor$, that is, by an integer part of dividing $a_i$ by $2$ (rounding down).\n\nSee if you can apply the operation some number of times (possible $0$) to make the array $a$ become a permutation of numbers from $1$ to $n$ —that is, so that it contains all numbers from $1$ to $n$, each exactly once.\n\nFor example, if $a = [1, 8, 25, 2]$, $n = 4$, then the answer is yes. You could do the following:\n\n- Replace $8$ with $\\lfloor \\frac{8}{2} \\rfloor = 4$, then $a = [1, 4, 25, 2]$.\n- Replace $25$ with $\\lfloor \\frac{25}{2} \\rfloor = 12$, then $a = [1, 4, 12, 2]$.\n- Replace $12$ with $\\lfloor \\frac{12}{2} \\rfloor = 6$, then $a = [1, 4, 6, 2]$.\n- Replace $6$ with $\\lfloor \\frac{6}{2} \\rfloor = 3$, then $a = [1, 4, 3, 2]$.",
    "tutorial": "Let's sort the array $a$ in descending order of the values of its elements. Then let's create a logical array $used$, where $used[i]$ will have the value true if we already got element $i$ of the permutation we are looking for, and the value false otherwise. We loop through the elements of the array $a$ and assign $x = a_i$. We'll divide $x$ by $2$ as long as it exceeds $n$ or as long as $used[x]$ is true. If it turns out that $x = 0$, then all the numbers that could be obtained from $a_i$ have already been obtained before. Since each element of the array $a$ must produce a new value from $1$ to $n$, the answer cannot be constructed - output NO. Otherwise, assign $used[x]$ a value of true - this means that the number $x$, which is an element of the permutation, we will get exactly from the original number $a_i$. After processing all elements of the array $a$ we can output YES.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int>a(n), used(n + 1, false);\n    for(auto &i : a) cin >> i;\n    sort(a.begin(), a.end(), [] (int a, int b) {\n        return a > b;\n    });\n    bool ok = true;\n    for(auto &i : a){\n        int x = i;\n        while(x > n or used[x])  x /= 2;\n        if(x > 0) used[x] = true;\n        else ok = false;\n    }\n    cout << (ok ? \"YES\" : \"NO\") << '\\n';\n\n}\n\nint main(){\n    ios_base :: sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "flows",
      "graph matchings",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1624",
    "index": "D",
    "title": "Palindromes Coloring",
    "statement": "You have a string $s$ consisting of lowercase Latin alphabet letters.\n\nYou can color some letters in colors from $1$ to $k$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.\n\nThen you can swap any two symbols painted in the same color as many times as you want.\n\nAfter that, $k$ strings will be created, $i$-th of them will contain all the characters colored in the color $i$, written in the order of their sequence in the string $s$.\n\nYour task is to color the characters of the string so that all the resulting $k$ strings are palindromes, and the length of the shortest of these $k$ strings is as \\textbf{large} as possible.\n\nRead the note for the first test case of the example if you need a clarification.\n\nRecall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.",
    "tutorial": "We will solve the problem greedily. First, we will try to add pairs of identical characters to palindromes. As long as there are at least $k$ pairs, let's add them. After that, it is no longer possible to add a couple of characters, but you can try to add one character in the middle. This can be done if there are at least $k$ characters left. There is no need to paint other characters.",
    "code": "#include <iostream>\n#include <vector>\n#include <stack>\n#include <algorithm>\n\nusing namespace std;\n\ntypedef long long ll;\nconst int MAX_N = 2e5;\n\nint main(int argc, char* argv[]) {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        int n, k;\n        string s;\n        cin >> n >> k >> s;\n        vector<int> cnt(26);\n        for (char c : s) {\n            cnt[c - 'a']++;\n        }\n        int cntPairs = 0, cntOdd = 0;\n        for (int c : cnt) {\n            cntPairs += c / 2;\n            cntOdd += c % 2;\n        }\n        int ans = 2 * (cntPairs / k);\n        cntOdd += 2 * (cntPairs % k);\n        if (cntOdd >= k) {\n            ans++;\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1624",
    "index": "E",
    "title": "Masha-forgetful",
    "statement": "Masha meets a new friend and learns his phone number — $s$. She wants to remember it as soon as possible. The phone number — is a string of length $m$ that consists of digits from $0$ to $9$. The phone number may start with 0.\n\nMasha already knows $n$ phone numbers (all numbers have the same length $m$). It will be easier for her to remember a new number if the $s$ is represented as segments of numbers she already knows. Each such segment must be of length \\textbf{at least $2$}, otherwise there will be too many segments and Masha will get confused.\n\nFor example, Masha needs to remember the number: $s = $ '12345678' and she already knows $n = 4$ numbers: '12340219', '20215601', '56782022', '12300678'. You can represent $s$ as a $3$ segment: '1234' of number one, '56' of number two, and '78' of number three. There are other ways to represent $s$.\n\nMasha asks you for help, she asks you to break the string $s$ into segments of length $2$ or more of the numbers she already knows. If there are several possible answers, print \\textbf{any} of them.",
    "tutorial": "The key idea is that any string of length greater than 3 can be obtained by concatenating strings of length $2$ or $3$. Then when reading the data, remember all occurring substring of length $2$ and $3$. There are at most $10^4$. Now we will count the dynamics on the prefix: $dp[i] = true$ if we can get the prefix of length $i$ of phone $s$ by segments of length $2$ and $3$ of the known phones Masha. Then for the transition we need to look through the lengths $2$ and $3$, then take a substring of the corresponding length and find out whether such a string occurred in the phones known to Masha. Then it will take $O(m)$ or $O(mlogm)$ time to recalculate the dynamics, depending on the implementation. But it will still take more time to read the data, so the final asymptotic will be $O(nm)$ or $O(nmlogm)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n\nconst int N = 1e4;\nmap<string, bool> have;\nmap<string, tuple<int,int,int>> pos;\n\nvoid solve() {\n    int n, m; cin >> n >> m;\n    vector<bool> dp(m+1, false);\n    vector<int> pr(m+1);\n    vector<string> cache;\n    dp[0] = true;\n\n    forn(i, n) {\n        string s; cin >> s;\n        forn(j, m) {\n            string t;\n            t += s[j];\n            for(int k = 1; k <= 2; k++) {\n                if (k + j >= m) break;\n                t += s[j+k];\n\n                if (!have[t]) {\n                    have[t] = true;\n                    pos[t] = make_tuple(j, j+k, i);\n                    cache.push_back(t);\n                }\n            }\n        }\n    }\n\n    string s; cin >> s;\n    forn(i, m) {\n        string t;\n        t += s[i];\n        for (int k = 1; k <= 2; k++) {\n            if (i - k < 0) break;\n            t = s[i-k] + t;\n            if (have[t] && dp[i-k]) {\n                dp[i+1] = true;\n                pr[i+1] = i-k;\n            }\n            if (dp[i+1]) break;\n        }\n    }\n    for (string t : cache) {\n        have[t] = false;\n    }\n\n    if (!dp[m]) {\n        cout << \"-1\\n\";\n        return;\n    }\n    vector<tuple<int,int,int>> ans;\n\n    for (int k = m; k > 0; ) {\n        int p = pr[k];\n        string t = s.substr(p, k - p);\n        ans.emplace_back(pos[t]);\n        k = p;\n    }\n\n    cout << sz(ans) << '\\n';\n    reverse(ans.begin(), ans.end());\n    for (auto [l,r,i] : ans) cout << l+1 << ' ' << r+1 << ' ' << i+1 << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "hashing",
      "implementation",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1624",
    "index": "F",
    "title": "Interacdive Problem",
    "statement": "\\textbf{This problem is interactive.}\n\nWe decided to play a game with you and guess the number $x$ ($1 \\le x < n$), where you know the number $n$.\n\nYou can make queries like this:\n\n- + c: this command assigns $x = x + c$ ($1 \\le c < n$) and then returns you the value $\\lfloor\\frac{x}{n}\\rfloor$ ($x$ divide by $n$ and round down).\n\nYou win if you guess the current number with no more than $10$ queries.",
    "tutorial": "After each query we know the $\\lfloor\\frac{x}{n}\\rfloor$ value, then we need to find $x \\mod n$ to find the current $x$ value. To find it, we will use a binary search. Suppose $x \\mod n$ is in the $[l, r)$ half-interval, in order to understand which half it is in, we will make a query, select the middle $m$ of the half-interval and make a + $n-m$ query. After that, $\\lfloor\\frac{x}{n}\\rfloor$ will either change, which means that $x \\mod n$ was in the $[m, r)$ half-interval, or not, then it was in the $[l, m)$ half-interval. Now you just need to properly shift the half-interval to accommodate the query change.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(143);\n\nconst int inf = 1e10;\nconst int M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-4;\n\nsigned main(){\n    int n;\n    cin >> n;\n    int l = 1, r = n;\n    int div = 0;\n    while(r - l > 1){\n        int mid = (r + l) / 2;\n        cout << \"+ \"<< n - mid << endl;\n        int d;\n        cin >> d;\n        if(d > div)l = mid;\n        else r = mid;\n        l = (l + n - mid) % n;\n        r = (r + n - mid) % n;\n        if(r == 0) r = n;\n        div = d;\n    }\n    cout << \"! \" << div * n + l;\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1624",
    "index": "G",
    "title": "MinOr Tree",
    "statement": "Recently, Vlad has been carried away by spanning trees, so his friends, without hesitation, gave him a connected weighted undirected graph of $n$ vertices and $m$ edges for his birthday.\n\nVlad defined the ority of a spanning tree as the bitwise OR of all its weights, and now he is interested in what is the minimum possible ority that can be achieved by choosing a certain spanning tree. A spanning tree is a connected subgraph of a given graph that does not contain cycles.\n\nIn other words, you want to keep $n-1$ edges so that the graph remains connected and the bitwise OR weights of the edges are as small as possible. You have to find the minimum bitwise OR itself.",
    "tutorial": "We need to minimize the result of the bitwise operation, so for convenience, we represent the answer as a mask. Firstly, let's assume that this mask is composed entirely of ones. Let's go from the most significant bit to the least significant one and try to reduce the answer. To understand whether it is possible to remove the $j$-th bit, remove it and check if the graph, in which all the weights are submasks of the current answer, is connected, for this, you can use depth-first search or a disjoint sets union. If the graph is connected, then the bit can obviously be thrown out, and if not it cannot and must be returned.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(143);\n\nconst int inf = 1e9;\nconst int M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-4;\n\nint n, cur;\nvector<vector<pair<int, int>>> sl;\n\nvoid dfs(int v, vector<bool> &used){\n    used[v] = true;\n    for(auto e: sl[v]){\n        int u = e.x, w = e.y;\n        if(!used[u] && (cur | w) == cur){\n            dfs(u, used);\n        }\n    }\n}\n\nvoid cnt(int pw){\n    if(pw < 0) return;\n    int d = (ll) 1 << pw;\n    cur -= d;\n    vector<bool> used(n);\n    dfs(0, used);\n    for(bool b: used){\n        if(!b) {\n            cur += d;\n            break;\n        }\n    }\n    cnt(pw - 1);\n}\n\nvoid solve() {\n    int m;\n    cin >> n >> m;\n    sl.assign(n, vector<pair<int, int>>(0));\n    for(int i = 0; i < m; ++i){\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u, --v;\n        sl[u].emplace_back(v, w);\n        sl[v].emplace_back(u, w);\n    }\n    cur = 1;\n    int bit = 0;\n    for(; cur < inf; bit++){\n        cur = 2 * cur + 1;\n    }\n    cnt(bit);\n    cout << cur;\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if (multi) {\n        cin >> t;\n    }\n    for (; t != 0; --t) {\n        solve();\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1625",
    "index": "A",
    "title": "Ancient Civilization",
    "statement": "Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.\n\nThey found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly $\\ell$ letters long. So, the scientists decided to write each word of this language as an integer from $0$ to $2^{\\ell} - 1$ inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.\n\nThe same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.\n\nDenote the distance between two words as the amount of positions, in which these words differ. For example, the distance between $1001_2$ and $1100_2$ (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words $x$ and $y$ as $d(x, y)$.\n\nLet the word have $n$ forms, the $i$-th of which is described with an integer $x_i$. All the $x_i$ are not necessarily different, as two various forms of the word can be written the same. Consider some word $y$. Then, closeness of the word $y$ is equal to the sum of distances to each of the word forms, i. e. the sum $d(x_i, y)$ over all $1 \\le i \\le n$.\n\nThe initial form is the word $y$ with minimal possible nearness.\n\nYou need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is \\textbf{not necessarily} equal to any of the $n$ given forms.",
    "tutorial": "Note that the problem can be solved independently for each bit, as the bits don't influence each other. Set the $i$th bit to zero if the numbers in the array contain more zeros than ones in the $i$th bit. Otherwise, set it to one.",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1625",
    "index": "B",
    "title": "Elementary Particles",
    "statement": "Martians are actively engaged in interplanetary trade. Olymp City, the Martian city known for its spaceport, has become a place where goods from all the corners of our Galaxy come. To deliver even more freight from faraway planets, Martians need fast spaceships.\n\nA group of scientists conducts experiments to build a fast engine for the new spaceship. In the current experiment, there are $n$ elementary particles, the $i$-th of them has type $a_i$.\n\nDenote a subsegment of the particle sequence ($a_1, a_2, \\dots, a_n$) as a sequence ($a_l, a_{l+1}, \\dots, a_r$) for some left bound $l$ and right bound $r$ ($1 \\le l \\le r \\le n$). For instance, the sequence $(1\\ 4\\ 2\\ 8\\ 5\\ 7)$ for $l=2$ and $r=4$ has the sequence $(4\\ 2\\ 8)$ as a subsegment. Two subsegments are considered different if at least one bound of those subsegments differs.\n\nNote that the subsegments can be equal as sequences but still considered different. For example, consider the sequence $(1\\ 1\\ 1\\ 1\\ 1)$ and two of its subsegments: one with $l=1$ and $r=3$ and another with $l=2$ and $r=4$. Both subsegments are equal to $(1\\ 1\\ 1)$, but still considered different, as their left and right bounds differ.\n\nThe scientists want to conduct a reaction to get two different subsegments of the same length. Denote this length $k$. The resulting pair of subsegments must be harmonious, i. e. for \\textbf{some} $i$ ($1 \\le i \\le k$) it must be true that the types of particles on the $i$-th position are the same for these two subsegments. For example, the pair $(1\\ 7\\ 3)$ and $(4\\ 7\\ 8)$ is harmonious, as both subsegments have $7$ on the second position. The pair $(1\\ 2\\ 3)$ and $(3\\ 1\\ 2)$ is not harmonious.\n\nThe longer are harmonious subsegments, the more chances for the scientists to design a fast engine. So, they asked you to calculate the maximal possible length of harmonious pair made of different subsegments.",
    "tutorial": "Note the following fact. For each optimal pair of harmonious strings, it's true that the right string ends on the last character. Proof: suppose it's wrong. Then, we can expand the strings to the right by one character, and they will remain harmonious. Now, prove the following statement, that will help us to solve this problem. The statement is as follows: the answer is $n - min(v - u)$ where minimum is over all $u$ and $v$ such that $u < v$ and $a_u = a_v$. Proof: consider two elements $u$ and $v$ such that $u < v$ and $a_u = a_v$. Suppose that they are on the same position in a pair of harmonious substrings. What maximal length these substring may have? From what was proved above, we know that we can expand the strings to the right. Take the first string starting in $u$ and the second string starting with $v$. Then, we get the strings of length $n - v + 1$ after expanding them. Still, it's not enough. So, we will also expand the strings to the left. So, the total length of the strings will become $n - v + u$, which is equal to $n - (v - u)$. The smaller $v - u$, the larger the length. To solve the problem, we need to find a pair of nearest equal elements quickly. We can do the following: store all the positions of each element (i. e. all the positions with $a_i = 1$, with $a_i = 2$ etc.), and then we iterate over $a_i$, go through the pairs of neighboring positions and calculate the minimum.",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1625",
    "index": "C",
    "title": "Road Optimization",
    "statement": "The Government of Mars is not only interested in optimizing space flights, but also wants to improve the road system of the planet.\n\nOne of the most important highways of Mars connects Olymp City and Kstolop, the capital of Cydonia. In this problem, we only consider the way from Kstolop to Olymp City, but not the reverse path (i. e. the path from Olymp City to Kstolop).\n\nThe road from Kstolop to Olymp City is $\\ell$ kilometers long. Each point of the road has a coordinate $x$ ($0 \\le x \\le \\ell$), which is equal to the distance from Kstolop in kilometers. So, Kstolop is located in the point with coordinate $0$, and Olymp City is located in the point with coordinate $\\ell$.\n\nThere are $n$ signs along the road, $i$-th of which sets a speed limit $a_i$. This limit means that the next kilometer must be passed in $a_i$ minutes and is active until you encounter the next along the road. There is a road sign at the start of the road (i. e. in the point with coordinate $0$), which sets the initial speed limit.\n\nIf you know the location of all the signs, it's not hard to calculate how much time it takes to drive from Kstolop to Olymp City. Consider an example:\n\nHere, you need to drive the first three kilometers in five minutes each, then one kilometer in eight minutes, then four kilometers in three minutes each, and finally the last two kilometers must be passed in six minutes each. Total time is $3\\cdot 5 + 1\\cdot 8 + 4\\cdot 3 + 2\\cdot 6 = 47$ minutes.\n\nTo optimize the road traffic, the Government of Mars decided to remove no more than $k$ road signs. It cannot remove the sign at the start of the road, otherwise, there will be no limit at the start. By removing these signs, the Government also wants to make the time needed to drive from Kstolop to Olymp City as small as possible.\n\nThe largest industrial enterprises are located in Cydonia, so it's the priority task to optimize the road traffic from Olymp City. So, the Government of Mars wants you to remove the signs in the way described above.",
    "tutorial": "First you need to understand that this problem must be solved with dynamic programming. Let $dp_{i,j}$ is the minimum time to drive between the two cities, if we consider first $i$ signs and have already removed $j$ signs. We also assume that the $i$th sign is taken. Then, the initial state is: $dp_{0,0} = 0$, $dp_{i,0} = dp_{i-1,0} + b_{i-1} \\cdot (a_i - a_{i-1})$. So, we don't need to drive to the first sign (as it takes $0$ seconds), and if we don't remove any signs, it's easy to calculate the time. Initially, fill $dp_{i,j} = \\infty$ for all $i = 1 \\ldots n, j = 1 \\ldots k$. Then, the answer is $min(dp_{n,j})$ over all $j = 0 \\ldots k$. Consider which transitions can we make. Calculate our DP from bottom to top, so we go from smaller states to larger ones. Consider all the $i = 0 \\ldots n-1$ and all the $j = 0 \\ldots k$ in the loop order, i. e: If we see $dp_{i, j} = \\infty$, then there's no answer and we'll just skip this state. For example, it may mean that $i < j$. Now, iterate over the positions of the next sign we'll put. Call this position $pos$. The transitions are as follows: $dp_{pos, j + pos - i - 1} = \\min(dp_{pos,j + pos - i - 1}, dp_{i, j} + b_i * (a_{pos} - a_i))$. Why such formula? After removing all the signs between $[i+1, pos-1]$ we will stay on the sign $pos$, remove $pos - i - 1$ signs, and the time to go from $i$ to $pos$ will depend on the sign $i$ and the distance between $i$ and $pos$. So, we get the solution in $O(n^3)$. There also exists a solution in $O(n^2\\cdot \\log n)$, which uses Convex Hull Trick. We don't describe it here, as it's not required to solve the problem.",
    "tags": [
      "dp"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1625",
    "index": "D",
    "title": "Binary Spiders",
    "statement": "Binary Spiders are species of spiders that live on Mars. These spiders weave their webs to defend themselves from enemies.\n\nTo weave a web, spiders join in pairs. If the first spider in pair has $x$ legs, and the second spider has $y$ legs, then they weave a web with durability $x \\oplus y$. Here, $\\oplus$ means bitwise XOR.\n\nBinary Spiders live in large groups. You observe a group of $n$ spiders, and the $i$-th spider has $a_i$ legs.\n\nWhen the group is threatened, some of the spiders become defenders. Defenders are chosen in the following way. First, there must be at least two defenders. Second, any pair of defenders must be able to weave a web with durability at least $k$. Third, there must be as much defenders as possible.\n\nScientists have researched the behaviour of Binary Spiders for a long time, and now they have a hypothesis that they can always choose the defenders in an optimal way, satisfying the conditions above. You need to verify this hypothesis on your group of spiders. So, you need to understand how many spiders must become defenders. You are not a Binary Spider, so you decided to use a computer to solve this problem.",
    "tutorial": "To solve the problem, we need the following well-known fact. Suppose we have a set of numbers and we need to find minimal possible $xor$ over all the pairs. It is true that, if we sort the numbers in non-descending order, the answer will be equal to minimal $xor$ over neighboring numbers. We need the minimal $xor$ to be not less than $k$ in this problem. For a quadratic solution, we can just sort the numbers and consider $dp_i$ - largest good subset such that the greatest element in it is equal to $a_i$. Then, $dp_i = max(dp_j + 1)$, where $a_j \\oplus a_i \\ge k$. To make this solution faster, we can use a trie over the bits of numbers. In each vertex of the trie, we store the size of the largest good subset whose greatest element lies in this subtree. When we want to get the answer for $i$, we descend in the tree and get the answer for all the subtrees where we don't go, if the corresponding bit in $k$ is equal to zero. Time complexity is $O(n\\cdot \\log \\max a_i)$.",
    "tags": [
      "bitmasks",
      "data structures",
      "implementation",
      "math",
      "sortings",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1625",
    "index": "E1",
    "title": "Cats on the Upgrade (easy version)",
    "statement": "This is the easy version of the problem. The only difference between the easy and the hard versions are removal queries, they are present only in the hard version.\n\n\"Interplanetary Software, Inc.\" together with \"Robots of Cydonia, Ltd.\" has developed and released robot cats. These electronic pets can meow, catch mice and entertain the owner in various ways.\n\nThe developers from \"Interplanetary Software, Inc.\" have recently decided to release a software update for these robots. After the update, the cats must solve the problems about bracket sequences. One of the problems is described below.\n\nFirst, we need to learn a bit of bracket sequence theory. Consider the strings that contain characters \"(\", \")\" and \".\". Call a string regular bracket sequence (RBS), if it can be transformed to an empty string by one or more operations of removing either single \".\" characters, or a continuous substring \"()\". For instance, the string \"(()(.))\" is an RBS, as it can be transformed to an empty string with the following sequence of removals:\n\n\\begin{center}\n\"{(()(\\underline{.}))}\" $\\rightarrow$ \"{(()\\underline{()})}\" $\\rightarrow$ \"{(\\underline{()})}\" $\\rightarrow$ \"{\\underline{()}}\" $\\rightarrow$ \"\".\n\\end{center}\n\nWe got an empty string, so the initial string was an RBS. At the same time, the string \")(\" is not an RBS, as it is not possible to apply such removal operations to it.\n\nAn RBS is simple if this RBS is not empty, doesn't start with \".\", and doesn't end with \".\".\n\nDenote the substring of the string $s$ as its sequential subsegment. In particular, $s[l\\dots r] = s_ls_{l+1}\\dots s_r$, where $s_i$ is the $i$-th character of the string $s$.\n\nNow, move on to the problem statement itself. You are given a string $s$, initially consisting of characters \"(\" and \")\". You need to answer the queries of the following kind.\n\nGiven two indices, $l$ and $r$ ($1 \\le l < r \\le n$), and it's \\textbf{guaranteed} that the substring $s[l\\dots r]$ is a \\textbf{simple RBS}. You need to find the number of substrings in $s[l\\dots r]$ such that they are simple RBS. In other words, find the number of index pairs $i$, $j$ such that $l \\le i < j \\le r$ and $s[i\\dots j]$ is a simple RBS.\n\nYou are an employee in \"Interplanetary Software, Inc.\" and you were given the task to teach the cats to solve the problem above, after the update.\n\nNote that the \".\" character cannot appear in the string in this version of the problem. It is only needed for the hard version.",
    "tutorial": "First, we need to make the input string an RBS. Consider one of the possible ways to do it. First, we keep the stack of all the opening brackets. We remove the bracket from the stack if we encounter the corresponding closing bracket. If there is an unpaired closing bracket or an opening bracket which is not removed, they must be replaced with a dot. So, the input string becomes an RBS. It's not hard to see that there are no queries that pass through dots we put in this step. Now, build a tree from the brackets. We will do it in the following way. Initially, there is one vertex. Then, if we encounter an opening bracket, we go one level below and create a new vertex, and if we encounter a closing bracket, then we go to the parent. It's now clear that each vertex corresponds to an RBS. The root of the tree corresponds to the entire string, and leaf nodes correspond to empty RBSes. Now, note that we can obtain all the RBSes if we take all the subsegments from the children of vertices. Each subsegment from the children looks like (RBS)(RBS)...(RBS), i. e. it's a concatenation of RBSes that correspond to children, where each one is put into brackets. Now, we can make a simple DP. Indeed, the amount of all RBSes in a vertex is the sum of RBSes of its children plus $\\frac{k \\cdot (k + 1)}{2}$, where $k$ is the number of children. The amount of RBSes on the segment is calculated in a similar way. When we calculate such DP and can carefully find a vertex in the tree, we can answer the queries on the segment. The time complexity is $O(q \\log n)$ or possibly $O(n + q)$ if we manage to find the vertices corresponding to indices fast.",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1625",
    "index": "E2",
    "title": "Cats on the Upgrade (hard version)",
    "statement": "This is the hard version of the problem. The only difference between the easy and the hard versions are removal queries, they are present only in the hard version.\n\n\"Interplanetary Software, Inc.\" together with \"Robots of Cydonia, Ltd.\" has developed and released robot cats. These electronic pets can meow, catch mice and entertain the owner in various ways.\n\nThe developers from \"Interplanetary Software, Inc.\" have recently decided to release a software update for these robots. After the update, the cats must solve the problems about bracket sequences. One of the problems is described below.\n\nFirst, we need to learn a bit of bracket sequence theory. Consider the strings that contain characters \"(\", \")\" and \".\". Call a string regular bracket sequence (RBS), if it can be transformed to an empty string by one or more operations of removing either single \".\" characters, or a continuous substring \"()\". For instance, the string \"(()(.))\" is an RBS, as it can be transformed to an empty string with the following sequence of removals:\n\n\\begin{center}\n\"{(()(\\underline{.}))}\" $\\rightarrow$ \"{(()\\underline{()})}\" $\\rightarrow$ \"{(\\underline{()})}\" $\\rightarrow$ \"{\\underline{()}}\" $\\rightarrow$ \"\".\n\\end{center}\n\nWe got an empty string, so the initial string was an RBS. At the same time, the string \")(\" is not an RBS, as it is not possible to apply such removal operations to it.\n\nAn RBS is simple if this RBS is not empty, doesn't start with \".\", and doesn't end with \".\".\n\nDenote the substring of the string $s$ as its sequential subsegment. In particular, $s[l\\dots r] = s_ls_{l+1}\\dots s_r$, where $s_i$ is the $i$-th character of the string $s$.\n\nNow, move on to the problem statement itself. You are given a string $s$, initially consisting of characters \"(\" and \")\". You need to answer the following queries:\n\n- Given two indices, $l$ and $r$ ($1 \\le l < r \\le n$). It's \\textbf{guaranteed} that the $l$-th character is equal to \"(\", the $r$-th character is equal to \")\", and the characters between them are equal to \".\". Then the $l$-th and the $r$-th characters must be set to \".\".\n- Given two indices, $l$ and $r$ ($1 \\le l < r \\le n$), and it's \\textbf{guaranteed} that the substring $s[l\\dots r]$ is a \\textbf{simple RBS}. You need to find the number of substrings in $s[l\\dots r]$ such that they are simple RBS. In other words, find the number of index pairs $i$, $j$ such that $l \\le i < j \\le r$ and $s[i\\dots j]$ is a simple RBS.\n\nYou are an employee in \"Interplanetary Software, Inc.\" and you were given the task to teach the cats to solve the problem above, after the update.",
    "tutorial": "Now, we need to see how to handle removal queries in this task. Build an SQRT decomposition in the following way. We will rebuild the entire tree after each $\\sqrt{n}$ queries and recalculate the DP. Between the rebuilds, we hold a list of removed leaves. Now look how we can recalculate the answer if some leaves are removed. First suppose that the leaf is not a direct child of the vertex we are interested in. Then the removal of this leaf decreases the answer by $q$, where $q$ is the number of children of this leaf's parent. Why so? The parent of this leaf had the answer as sum of answers in its children plus $\\frac{q \\cdot (q + 1)}{2}$. The answer in the leaf is equal to zero, so the new answer became sum plus $\\frac{q \\cdot (q + 1)}{2}$, thus decreased by $q$. When we build the DP, the modification of answer in a vertex is passed to its parents unchanged. So, the answer decreases by $q$ on the entire path from this leaf to the root. We can easily check if we are affected by this removal. It must be applied only if the removed leaf lies strictly inside our query of the second type. We also need to handle the case where our leaf is a direct child of the vertex we consider, as the removal described above doesn't fully apply to this case. This is an exercise left to the reader. So, we get the solution in $O((n + q) \\cdot \\sqrt{n})$. There is also a solution in $O((n + q) \\log n)$. We consider it very shortly. Let's hold just $\\frac{k \\cdot (k + 1)}{2}$ in each vertex, not the sum over children plus $\\frac{k \\cdot (k + 1)}{2}$, as we did before. Then the answer for each vertex is the sum in the subtree. We can keep a Fenwick tree, as we can calculate sums in the subtree with it, using Eulerian tour over the tree. It's not hard to see that each update must be applied only once to the direct parent.",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1626",
    "index": "A",
    "title": "Equidistant Letters",
    "statement": "You are given a string $s$, consisting of lowercase Latin letters. Every letter appears in it no more than twice.\n\nYour task is to rearrange the letters in the string in such a way that for each pair of letters that appear exactly twice, the distance between the letters in the pair is the same. You are not allowed to add or remove letters.\n\nIt can be shown that the answer always exists. If there are multiple answers, print any of them.",
    "tutorial": "Let's consider a very special case of equal distances. What if all distances were equal to $1$? It implies that if some letter appears exactly twice, both occurrences are placed right next to each other. That construction can be achieved if you sort the string, for example: first right down all letters 'a', then all letters 'b' and so on. If a letter appears multiple times, all its occurrences will be next to each other, just as we wanted. Overall complexity: $O(|s| \\log |s|)$ or $O(|s|)$ per testcase.",
    "code": "for _ in range(int(input())):\n  print(''.join(sorted(input())))",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1626",
    "index": "B",
    "title": "Minor Reduction",
    "statement": "You are given a decimal representation of an integer $x$ without leading zeros.\n\nYou have to perform the following reduction on it \\textbf{exactly once}: take two neighboring digits in $x$ and replace them with their sum without leading zeros (if the sum is $0$, it's represented as a single $0$).\n\nFor example, if $x = 10057$, the possible reductions are:\n\n- choose the first and the second digits $1$ and $0$, replace them with $1+0=1$; the result is $1057$;\n- choose the second and the third digits $0$ and $0$, replace them with $0+0=0$; the result is also $1057$;\n- choose the third and the fourth digits $0$ and $5$, replace them with $0+5=5$; the result is still $1057$;\n- choose the fourth and the fifth digits $5$ and $7$, replace them with $5+7=12$; the result is $10012$.\n\nWhat's the largest number that can be obtained?",
    "tutorial": "Let's think how a reduction changes the length of $x$. There are two cases. If two adjacent letters sum up to $10$ or greater, then the length doesn't change. Otherwise, the length decreases by one. Obviously, if there exists a reduction that doesn't change the length, then it's better to use it. Which among such reduction should you choose? Well, notice that such a reduction always makes the number strictly smaller (easy to see with some case analysis). Thus, the logical conclusion is to leave the longest possible prefix of $x$ untouched. So, the rightmost such reduction will change the number as little as possible. If all reductions decrease the length, then a similar argument can be applied. The sum will be a single digit, but a digit that is greater than or equal to the left one of the adjacent pair. If it was just greater, it's easy to see that the leftmost such reduction will make the number the largest possible. The equal case adds more case analysis on top of the proof, but the conclusion remains the same: the leftmost reduction is the best one. As an implementation note, since all the reductions are of the same type, the leftmost reduction always includes the first and the second digits. Overall complexity: $O(|x|)$ per testcase.",
    "code": "for _ in range(int(input())):\n  x = [ord(c) - ord('0') for c in input()]\n  n = len(x)\n  for i in range(n - 2, -1, -1):\n    if x[i] + x[i + 1] >= 10:\n      x[i + 1] += x[i] - 10\n      x[i] = 1\n      break\n  else:\n    x[1] += x[0]\n    x.pop(0)\n  print(''.join([chr(c + ord('0')) for c in x]))",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1626",
    "index": "C",
    "title": "Monsters And Spells",
    "statement": "Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.\n\nThe level he's currently on contains $n$ monsters. The $i$-th of them appears $k_i$ seconds after the start of the level and has $h_i$ health points. As an additional constraint, $h_i \\le k_i$ for all $1 \\le i \\le n$. All $k_i$ are different.\n\nMonocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: $1, 2, 3, \\dots$ The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is $1$. Otherwise, let the damage at the previous second be $x$. Then he can choose the damage to be either $x + 1$ or $1$. A spell uses mana: casting a spell with damage $x$ uses $x$ mana. Mana doesn't regenerate.\n\nTo kill the $i$-th monster, Monocarp has to cast a spell with damage at least $h_i$ at the exact moment the monster appears, which is $k_i$.\n\nNote that Monocarp can cast the spell even when there is no monster at the current second.\n\nThe mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.\n\nIt can be shown that it's always possible to kill all monsters under the constraints of the problem.",
    "tutorial": "Consider the problem with $n=1$. There is a single monster with some health $h$ that appears at some second $k$. In order to kill it, we have to wind up our spell until it has damage $h$. So we have to use it from second $k - h + 1$ to second $k$. Look at it as a segment $[k - h + 1; k]$ on a timeline. Actually, to avoid handling zero length segments, let's instead say that a segment covers the time from $k - h$ non-inclusive to $k$ inclusive, producing a half-interval $(k - h; k]$. This way, the total mana cost will be $\\frac{\\mathit{len}(\\mathit{len} + 1)}{2}$, where $\\mathit{len}$ is the length of the half-interval. Now $n=2$. There are two time segments. If they don't intersect (segments $(1; 2]$ and $(2; 3]$ don't intersect, since they are half-intervals), then it's always better to wind up the spell for the monsters separately instead of saving the damage. However, if they intersect, then we don't have the choice other than to save the damage from the earlier one to the later one. Otherwise, there won't be enough time to wind up the spell. What that means in a mathematic sense? The answer is the union of two half-intervals. If they don't intersect, they are left as is. Otherwise, they become one half-interval that covers them both. Now add the third monster into the construction. The same argument applies. While there exists a pair of intersecting half-intervals, keep uniting them. The union of all half-intervals can be found in $O(n \\log n)$, but the constraints allowed slower approaches as well.",
    "code": "for _ in range(int(input())):\n  n = int(input())\n  k = list(map(int, input().split()))\n  h = list(map(int, input().split()))\n  st = []\n  for i in range(n):\n    st.append([k[i] - h[i], k[i]])\n  st.sort()\n  l, r = -1, -1\n  ans = 0\n  for it in st:\n    if it[0] >= r:\n      ans += (r - l) * (r - l + 1) // 2\n      l, r = it\n    else:\n      r = max(r, it[1])\n  ans += (r - l) * (r - l + 1) // 2\n  print(ans)",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1626",
    "index": "D",
    "title": "Martial Arts Tournament",
    "statement": "Monocarp is planning to host a martial arts tournament. There will be three divisions based on weight: lightweight, middleweight and heavyweight. The winner of each division will be determined by a single elimination system.\n\nIn particular, that implies that the number of participants in each division should be a power of two. Additionally, each division should have a non-zero amount of participants.\n\n$n$ participants have registered for the tournament so far, the $i$-th of them weighs $a_i$. To split participants into divisions, Monocarp is going to establish two integer weight boundaries $x$ and $y$ ($x < y$).\n\nAll participants who weigh strictly less than $x$ will be considered lightweight. All participants who weigh greater or equal to $y$ will be considered heavyweight. The remaining participants will be considered middleweight.\n\nIt's possible that the distribution doesn't make the number of participants in each division a power of two. It can also lead to empty divisions. To fix the issues, Monocarp can invite an arbitrary number of participants to each division.\n\nNote that Monocarp can't kick out any of the $n$ participants who have already registered for the tournament.\n\nHowever, he wants to invite as little extra participants as possible. Help Monocarp to choose $x$ and $y$ in such a way that the total amount of extra participants required is as small as possible. Output that amount.",
    "tutorial": "Sort the weights, now choosing $x$ and $y$ will split the array into three consecutive segments. Consider a naive solution to the problem. You can iterate over the length of the first segment and the second segment. The third segment will include everyone remaining. Now you have to check if there exist some $x$ and $y$ that produce such segment. $x$ can be equal to the first element of the second segment (since only all elements of the first segment are smaller than it). Similarly, $y$ can be equal to the first element of the third segment. However, if the last element of some segment is equal to the first element of the next segment, no $x$ or $y$ can split the array like that. Otherwise, you can split an array like that. So you can iterate over the lengths, check the correctness and choose the best answer. Now let's optimize it using the condition about powers of two. First, iterate over the size of the middle division (which is a power of two). Then over the length of the first segment (which can be not a power of two). Check if the first segment is valid. So we fixed the length of the first segment and some value which is greater or equal than the length of the second segment. That value isn't necessarily equal to the length of the second segment because the produced segment might be invalid. So there is a greedy idea that the second segment should be as long as possible under the constraint that it doesn't exceed the fixed value. The intuition is the following. Consider the longest possible valid segment. Now take the last element away from it. We will have to invite one more participant to the middle division. And that element will also get added to the third segment, increasing its length. So potentially, you can only increase the required number of participants to invite. This can be implemented in the following fashion. For each position $i$ precalculate $\\mathit{left}_i$ - the closest possible segment border from the left. Iterate over the size of the middle division $\\mathit{mid}$ as a power of two. Iterate over the length of the first segment $\\mathit{len}_1$. Find the closest border to the left of $\\mathit{len}_1 + \\mathit{mid} = \\mathit{left}[\\mathit{len}_1 + \\mathit{mid}]$. Get the lengths of the second and the third segments. Find the closest powers of two to each length and update the answer. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "calc = 1\nnxt = [1, 0]\n\nfor _ in range(int(input())):\n  n = int(input())\n  a = sorted(list(map(int, input().split())))\n  while calc <= n:\n    for i in range(calc):\n      nxt.append(calc - i - 1)\n    calc *= 2\n  left = []\n  for i in range(n + 1):\n    if i == 0 or i == n or a[i] != a[i - 1]:\n      left.append(i)\n    else:\n      left.append(left[-1])\n  mid = 1\n  ans = n + 2\n  while mid <= n:\n    for len1 in range(n + 1):\n      if left[len1] == len1:\n        len2 = left[min(n, len1 + mid)] - len1\n        len3 = n - len1 - len2\n        ans = min(ans, nxt[len1] + (mid - len2) + nxt[len3])\n    mid *= 2\n  print(ans)",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1626",
    "index": "E",
    "title": "Black and White Tree",
    "statement": "You are given a tree consisting of $n$ vertices. Some of the vertices (at least two) are black, all the other vertices are white.\n\nYou place a chip on one of the vertices of the tree, and then perform the following operations:\n\n- let the current vertex where the chip is located is $x$. You choose a black vertex $y$, and then move the chip along the first edge on the simple path from $x$ to $y$.\n\nYou are not allowed to choose the same black vertex $y$ in two operations in a row (i. e., for every two consecutive operations, the chosen black vertex should be different).\n\nYou end your operations when the chip moves to the black vertex (if it is initially placed in a black vertex, you don't perform the operations at all), or when the number of performed operations exceeds $100^{500}$.\n\nFor every vertex $i$, you have to determine if there exists a (possibly empty) sequence of operations that moves the chip to some black vertex, if the chip is initially placed on the vertex $i$.",
    "tutorial": "I think there are some ways to solve this problem with casework, but let's try to come up with an intuitive and easy-to-implement approach. It's always possible to move closer to some black vertex, no matter in which vertex you are currently and which black vertex was used in the previous operation. However, sometimes if you try to move along an edge, you immediately get forced back. Let's analyze when we can move without being forced back. We can move along the edge $x \\rightarrow y$ so that our next action is not moving back if: either $y$ is black (there is no next action); or, if we remove the edge between $x$ and $y$, the number of black vertices in $y$'s component is at least $2$ (we can use one of them to go from $x$ to $y$, and another one to continue our path). Note that the cases $x \\rightarrow y$ and $y \\rightarrow x$ may be different (sometimes it will be possible to move in one direction, and impossible to move in the opposite direction). Let's treat this possible move $x \\rightarrow y$ as an arc in a directed graph. We can find all such arcs if we can answer the queries of the type \"count black vertices in a subtree of some vertex\", and this can be done by rooting the tree and calculating this information for each subtree with DFS. Now, if there is a way from some vertex $i$ to some black vertex along these arcs, the answer for the vertex $i$ is $1$. How can we find all such vertices? Let's transpose the graph (change the direction of each arc to opposite), now we need to find all vertices reachable from black ones - which is easily done with multisource BFS or DFS. The complexity of this solution is $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300043;\n\nvector<int> g[N];\nint cnt[N];\nint c[N];\nvector<int> g2[N];\nint par[N];\nint used[N];\n\nvoid dfs(int x, int p = -1)\n{\n    par[x] = p;\n    for(auto y : g[x])\n        if(y != p)\n        {\n            dfs(y, x);\n            cnt[x] += cnt[y];\n        }\n    cnt[x] += c[x];\n}   \n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++) scanf(\"%d\", &c[i]);\n    for(int i = 1; i < n; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        --x;\n        --y;\n        g[x].push_back(y);\n        g[y].push_back(x);\n    }\n    dfs(0);\n    for(int i = 0; i < n; i++)\n        for(auto j : g[i])\n        {\n            if(i == par[j])\n            {\n                if(c[i] == 1 || cnt[0] - cnt[j] > 1)\n                    g2[i].push_back(j);\n            }\n            else\n            {\n                if(c[i] == 1 || cnt[i] > 1)\n                    g2[i].push_back(j);\n            }\n        }\n    queue<int> q;\n    for(int i = 0; i < n; i++)\n    {\n        if(c[i] == 1)\n        {\n            q.push(i);\n            used[i] = 1;\n        }\n    }\n    while(!q.empty())\n    {\n        int k = q.front();\n        q.pop();\n        for(auto y : g2[k])\n            if(used[y] == 0)\n            {\n                used[y] = 1;\n                q.push(y);\n            }\n    }\n    for(int i = 0; i < n; i++)\n        printf(\"%d \", used[i]);\n    puts(\"\");\n}",
    "tags": [
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1626",
    "index": "F",
    "title": "A Random Code Problem",
    "statement": "You are given an integer array $a_0, a_1, \\dots, a_{n - 1}$, and an integer $k$. You perform the following code with it:\n\n\\begin{verbatim}\nlong long ans = 0; // create a 64-bit signed variable which is initially equal to 0\nfor(int i = 1; i <= k; i++)\n{\nint idx = rnd.next(0, n - 1); // generate a random integer between 0 and n - 1, both inclusive\n// each integer from 0 to n - 1 has the same probability of being chosen\nans += a[idx];\na[idx] -= (a[idx] % i);\n}\n\n\\end{verbatim}\n\nYour task is to calculate the expected value of the variable ans after performing this code.\n\nNote that the input is generated according to special rules (see the input format section).",
    "tutorial": "I think it's easier to approach this problem using combinatorics instead of probability theory methods, so we'll calculate the answer as \"the sum of values of ans over all ways to choose the index on each iteration of the loop\". If a number $a_{idx}$ is chosen on the iteration $i$ of the loop, then it is reduced to the maximum number divisible by $i$ that doesn't exceed the initial value. So, if a number is divisible by all integers from $1$ to $k$, i. e. divisible by $L = LCM(1,2,\\dots,k)$, it won't be changed in the operation. Furthermore, if $\\lfloor \\frac{a_{idx}}{L} \\rfloor = x$, then the value of this element won't become less than $x \\cdot L$. It means that we can interpret each number $a_i$ as $a_i = x \\cdot L + y$, where $x = \\lfloor \\frac{a_{i}}{L} \\rfloor$ and $y = a_i \\bmod L$. The part with $x \\cdot L$ will always be added to the variable ans when this element is chosen, so let's add $k \\cdot n^{k-1} \\cdot x \\cdot L$ to the answer (which is the contribution of $x \\cdot L$ over all ways to choose the indices in the operations), and work with $a_i \\bmod L$ instead of $a_i$. Now all elements of the array are less than $L$. We can use this constraint by writing the following dynamic programming to solve the problem: $dp_{i,j}$ is the number of appearances of the integer $i$ in the array $a$ over all ways to choose the indices for the first $j$ iterations. For $j = 0$, $dp$ is just the number of occurrences of each integer in the array $a$. The transitions from $dp_{i,j}$ are the following ones: if this element is chosen in the operation, then it becomes $i' = i - (i \\bmod (j + 1))$, and we transition to the state $dp_{i',j+1}$; otherwise, the element is unchanged, and we transition to the state $dp_{i,j+1}$, multiplying the current value by $n-1$, which is the number of ways to choose some other element in the operation. How can we use this dynamic programming to get the answer? On the $(j+1)$-th iteration, the number of times we choose the integer $i$ is exactly $dp_{i,j}$, and the number of ways to use the integers in the next operations is $n^{k-j-1}$, so we add $i \\cdot dp_{i,j} \\cdot n^{k-j-1}$ to the answer for every such state $dp_{i,j}$. This solution runs in time $O(n + LCM(1,2,\\dots,k) \\cdot k)$, which may be too slow if not implemented carefully. Fortunately, we have an easy way to optimize it: use $L = LCM(1,2,\\dots,k-1)$ instead of $L = LCM(1,2,\\dots,k)$, which divides $L$ by $17$ in the worst case scenario for our solution. We can do this because even if an integer is changed on the $k$-th operation, we are not interested in this change since this is the last operation.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int MOD = 998244353;\nconst int L = 720720;\n\nint add(int x, int y, int m = MOD)\n{\n    x += y;\n    if(x >= m) x -= m;\n    return x;\n}\n\nint mul(int x, int y, int m = MOD)\n{\n    return (x * 1ll * y) % m;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1) z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nint inv(int x)\n{\n    return binpow(x, MOD - 2);\n}\n\nint divide(int x, int y)\n{\n    return mul(x, inv(y));\n}\n\nint main()\n{\n    int n, a0, x, y, k, M;\n    cin >> n >> a0 >> x >> y >> k >> M;\n    vector<int> arr(n);\n    arr[0] = a0;\n    for(int i = 1; i < n; i++)\n        arr[i] = add(mul(arr[i - 1], x, M), y, M);\n    int ans = 0;\n    int total_ways = binpow(n, k);\n    int coeff = mul(divide(total_ways, n), k);\n    vector<vector<int>> dp(k, vector<int>(L));\n    for(int i = 0; i < n; i++)\n    {\n        int p = arr[i] / L;\n        int q = arr[i] % L;\n        dp[0][q]++;\n        ans = add(ans, mul(p, mul(L, coeff)));\n    }\n    int cur_coeff = divide(total_ways, n);\n    for(int i = 1; i <= k; i++)\n    {\n        for(int j = 0; j < L; j++)\n        {\n            int cur = dp[i - 1][j];\n            if(i < k)\n                dp[i][j] = add(dp[i][j], mul(n - 1, cur));\n            ans = add(ans, mul(j, mul(cur, cur_coeff)));\n            if(i < k)\n                dp[i][j - (j % i)] = add(dp[i][j - (j % i)], cur);\n        }\n        cur_coeff = divide(cur_coeff, n);\n    }\n    cout << ans << endl;        \n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1627",
    "index": "A",
    "title": "Not Shading",
    "statement": "There is a grid with $n$ rows and $m$ columns. Some cells are colored black, and the rest of the cells are colored white.\n\nIn one operation, you can select some \\textbf{black} cell and do \\textbf{exactly one} of the following:\n\n- color all cells in its row black, or\n- color all cells in its column black.\n\nYou are given two integers $r$ and $c$. Find the minimum number of operations required to make the cell in row $r$ and column $c$ black, or determine that it is impossible.",
    "tutorial": "There are several cases to consider: If all the cell are white, then it is impossible to perform any operations, so you cannot make any cell black. The answer is $-1$. If the cell in row $r$ and column $c$ is already black, then we don't need to perform any operations. The answer is $0$. If any of the cells in row $r$ are already black (that is, the cell we need to turn black shares a row with a black cell), then we can take this black cell and make row $r$. The same is true if any of the cells in column $c$ are already black. The answer is $1$. Otherwise, we claim the answer is $2$. Take any black cell and make its row black. This means that every column contains a black cell, so now we can take column $c$ are turn it black. Thus the answer is $2$.",
    "code": "for t in range(int(input())):\n    n, m, r, c = map(int, input().split())\n    a = [list(input()) for i in range(n)]\n    if \"B\" not in str(a):\n        print(-1)\n        continue\n    print(2 - (\"B\" in a[r-1] + list([*zip(*a)][c-1])) - (a[r-1][c-1] == 'B'))",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1627",
    "index": "B",
    "title": "Not Sitting",
    "statement": "Rahul and Tina are looking forward to starting their new year at college. As they enter their new classroom, they observe the seats of students are arranged in a $n \\times m$ grid. The seat in row $r$ and column $c$ is denoted by $(r, c)$, and the distance between two seats $(a,b)$ and $(c,d)$ is $|a-c| + |b-d|$.\n\nAs the class president, Tina has access to \\textbf{exactly} $k$ buckets of pink paint. The following process occurs.\n\n- First, Tina chooses exactly $k$ seats in the classroom to paint with pink paint. One bucket of paint can paint exactly one seat.\n- After Tina has painted $k$ seats in the previous step, Rahul chooses where he sits. He will not choose a seat that has been painted pink due to his hatred of the colour pink.\n- After Rahul has chosen his seat, Tina chooses a seat for herself. She can choose any of the seats, painted or not, other than the one chosen by Rahul.\n\nRahul wants to choose a seat such that he sits as close to Tina as possible. However, Tina wants to sit as far away from Rahul as possible due to some complicated relationship history that we couldn't fit into the statement!\n\nNow, Rahul wonders for $k = 0, 1, \\dots, n \\cdot m - 1$, if Tina has $k$ buckets of paint, how close can Rahul sit to Tina, if both Rahul and Tina are aware of each other's intentions and they both act as strategically as possible? Please help satisfy Rahul's curiosity!",
    "tutorial": "Let's denote Rahul's seat as $(a, b)$ and Tina's seat as $(c, d)$. Notice that the in the distance between their seats, $|a-c| + |b-d|$, $|a-c|$ and $|b-d|$ are independent of each other, i.e. both the $x$-coordinate and $y$-coordinate of Tina's seat are independent. From the answer to the hint above, we can see that the optimal seat for Tina in a $1$-dimensional classroom is one of the edge seats, and combining this with the previous observation means that the optimal seat for Tina is always one of the corner seats. Since Rahul chooses seats optimally, he will know that Tina will choose one of the corner seats, so he will choose a seat such that the maximum distance from it to one of the corner seats is minimised. As Tina also chooses which seats to paint optimally, the best strategy for her is to paint the $k$ seats with minimum maximum distance to one of the corner seats pink. We can implement this by calculating for each seat the maximum distance to one of the corner seats from it, and storing these values in an array. After sorting this array in non-decreasing order, we can simply print the first $n \\cdot m - 1$ values of the array, as the $i$-th value of the array ($0$-indexed) is the optimal answer for $k = i$. This can be implemented in $\\mathcal{O}(nm\\log(nm))$ time per test case.",
    "code": "import sys\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n \nfor t in range(int(input())):\n    n, m = map(int, input().split())\n    print(*sorted(max(x, n-1-x) + max(y, m-1-y) for x in range(n) for y in range(m)))",
    "tags": [
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1627",
    "index": "C",
    "title": "Not Assigning",
    "statement": "You are given a tree of $n$ vertices numbered from $1$ to $n$, with edges numbered from $1$ to $n-1$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.\n\nA prime tree is a tree where the weight of every path consisting of \\textbf{one or two edges} is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.\n\nConsider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $2 \\to 1 \\to 3$ has a weight of $11 + 2 = 13$, which is prime. Similarly, the path of one edge: $4 \\to 3$ has a weight of $5$, which is also prime.\n\nPrint \\textbf{any} valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $-1$. It can be proven that if a valid assignment exists, one exists with weights between $1$ and $10^5$ as well.",
    "tutorial": "Let us first see when a valid assignment does not exist. Claim. If any vertex has 3 or more edges adjacent to it, no valid assignment exists. Proof. Consider a graph where a vertex has edges to three other vertices with weights $x$, $y$ and $z$ respectively. For a valid assignment, $x$, $y$ and $z$ need to be primes themselves. Also, $x+y$, $y+z$ and $x + z$ need to be primes too. Since $x, y, z \\ge 2$ (as $2$ is the smallest prime), thus $x + y, x + z, y + z \\ge 4$, so they must be odd primes. This implies: $x$ and $y$ have opposite parity. $y$ and $z$ have opposite parity. $x$ and $z$ have opposite parity. As all the three conditions cannot hold together, hence we have a contradiction. Proven. So, we have a tree where every vertex has either one or two edges adjacent to it. Such a tree will have exactly two leaf nodes for $n \\ge 2$ and have the following structure, where $V_1$ and $V_n$ are the leaf nodes. $V_1 \\longleftrightarrow V_2 \\longleftrightarrow V_3 \\dots \\longleftrightarrow V_{n-1} \\longleftrightarrow V_n$ Thus, starting a DFS from any leaf node, we can assign weights $2$ and $3$ (or $2$ and the first number of any twin prime pair) alternatingly to form a prime tree, as $2$, $3$ and $2+3 = 5$ are all primes. Expected time complexity: $\\mathcal{O}(n)$",
    "code": "import sys\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n \nfor t in range(int(input())):\n    n = int(input())\n    graph = [[] for __ in range(n + 1)]\n    ans = [-1] * (n - 1)\n    for i in range(n - 1):\n        x, y = map(int, input().split())\n        graph[x] += [(y, i)]\n        graph[y] += [(x, i)]\n    if max(len(graph[i]) for i in range(n + 1)) > 2:\n        print(-1)\n        continue\n    cur, prev = 1, None\n    while len(graph[cur]) != 1: cur += 1\n    for p in range(n - 1):\n        for x, i in graph[cur]:\n            if x != prev:\n                ans[i] = [17, 2][p % 2]\n                cur, prev = x, cur\n                break\n    print(*ans)",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "number theory",
      "trees"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1627",
    "index": "D",
    "title": "Not Adding",
    "statement": "You have an array $a_1, a_2, \\dots, a_n$ consisting of $n$ \\textbf{distinct} integers. You are allowed to perform the following operation on it:\n\n- Choose two elements from the array $a_i$ and $a_j$ ($i \\ne j$) such that $\\gcd(a_i, a_j)$ is not present in the array, and add $\\gcd(a_i, a_j)$ to the end of the array. Here $\\gcd(x, y)$ denotes greatest common divisor (GCD) of integers $x$ and $y$.\n\nNote that the array changes after each operation, and the subsequent operations are performed on the new array.\n\nWhat is the \\textbf{maximum} number of times you can perform the operation on the array?",
    "tutorial": "Note that the $\\gcd$ of two numbers cannot exceed their maximum. Let the maximum element of the array be $A$. So for every number from $1$ to $A$, we try to check whether that element can be included in the array after performing some operations or not. How to check for a particular number $x$? For $x$ to be in the final array, either: It already exists in the initial array. Or, the $\\gcd$ of all multiples of $x$ present in the initial array equals $x$. Proof For $x$ to be added after some operations, there must be some subset of the array which has a $\\gcd$ equal to $x$. We can perform the operations by taking the current gcd and one element from the subset at a time and at the end we will obtain $x$. Note that such a subset can only contain multiples of $x$. So it is enough to check that the $\\gcd$ of all multiples is equal to $x$. Thus, the overall solution takes $\\mathcal{O}(n + A \\log{A})$.",
    "code": "import io, os\nfrom math import gcd\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n \nn = int(input())\na = list(map(int, input().split()))\nMAXN = 1000000\npresent = [False] * (MAXN + 1)\nfor each in a:\n    present[each] = True\nans = 0\nfor i in range(MAXN, 0, -1):\n    if present[i]: continue\n    g = 0\n    for j in range(2*i, MAXN + 1, i):\n        if present[j]:\n            if g == 0: \n                g = j\n            elif gcd(g, j) == i:\n                g = i\n                break\n    if g == i:\n        ans += 1\n        present[i] = True\nprint(ans)",
    "tags": [
      "brute force",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1627",
    "index": "E",
    "title": "Not Escaping",
    "statement": "Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.\n\nThe building consists of $n$ floors, each with $m$ rooms each. Let $(i, j)$ represent the $j$-th room on the $i$-th floor. Additionally, there are $k$ ladders installed. The $i$-th ladder allows Ram to travel from $(a_i, b_i)$ to $(c_i, d_i)$, but \\textbf{not in the other direction}. Ram also gains $h_i$ health points if he uses the ladder $i$. \\textbf{It is guaranteed $a_i < c_i$ for all ladders.}\n\nIf Ram is on the $i$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $(i, j)$ to $(i, k)$, he loses $|j-k| \\cdot x_i$ health points.\n\nRam enters the building at $(1, 1)$ while his helicopter is waiting at $(n, m)$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output \"NO ESCAPE\" if no matter what path Ram takes, he cannot escape the clutches of Raghav.",
    "tutorial": "The building plan of the input consists of $n \\cdot m$ rooms, which in the worst case is $10^{10}$ however, most of these rooms are unimportant to us. We can instead use a much reduced version of the building consisting of at most $2k + 2$ rooms, both endpoints of each ladder, as well as our starting and target rooms. As every ladder connects a lower floor to a higher floor and is one-directional, we can process the rooms floor by floor, from floor $1$ to floor $n$. On each floor, let's sort all the rooms in non-decreasing order. Now, we can use dynamic programming, as well as the compression previously mentioned to calculate the minimum distance to get to all important rooms. First, we calculate the minimum cost to get to each room using a room on the same floor as an intermediate. We can do this by iterating over the rooms on a floor twice, once from left to right, and then once from right to left. Then, for each room on the floor, if it has a ladder going up from it, we can update the $dp$ value of the room where the ladder ends. Our answer is the $dp$ value of the target room. This can be implemented in $\\mathcal{O}(k\\log(k))$ time per test case.",
    "code": "import sys, os, io\nfrom collections import defaultdict\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n \ninf = 5 * 10**16\n \nfor _ in range(int(input())):\n    n, m, k = map(int, input().split())\n    a = list(map(int, input().split()))\n    go_to = defaultdict(list)\n    coords = set()\n    coords.add((1, 1))\n    coords.add((n, m))\n    for i in range(k):\n        p, q, r, s, t = map(int, input().split())\n        go_to[p * m + q] += [[r, s, t]]\n        coords.add((p, q))\n        coords.add((r, s))\n    coords = sorted(list(coords))\n    N, index = len(coords), {}\n    dp, prefix, suffix = [-inf] * N, [-inf] * N, [-inf] * N\n    for i in range(N): index[coords[i]] = i\n    pairs, i = [], 0\n    dp[0] = 0\n    while i < N:\n        j = i\n        while j + 1 < N and coords[j + 1][0] == coords[j][0]:\n            j += 1\n            if coords[j][0] == 1:\n                dp[j] = -a[0] * (coords[j][1] - 1)\n        pairs += [(i, j)]\n        i = j + 1\n    for start, end in pairs:\n        leftVal = rightVal = -inf\n        for i in range(start, end + 1):\n            x, y = coords[i]\n            leftVal = max(leftVal, prefix[i])\n            dp[i] = max(dp[i], leftVal - a[x - 1] * (y - 1))\n        for i in range(end, start - 1, -1):\n            x, y = coords[i]\n            rightVal = max(rightVal, suffix[i])\n            dp[i] = max(dp[i], rightVal - a[x - 1] * (m - y))\n        for i in range(start, end + 1):\n            if dp[i] == -inf: continue\n            x, y = coords[i]\n            for r, s, t in go_to[x * m + y]:\n                j = index[(r, s)]\n                dp[j] = max(dp[j], dp[i] + t)\n                prefix[j] = max(prefix[j], dp[j] + a[r - 1] * (s - 1))\n                suffix[j] = max(suffix[j], dp[j] + a[r - 1] * (m - s))\n    print(-dp[-1] if dp[-1] != -inf else \"NO ESCAPE\")",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "shortest paths",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1627",
    "index": "F",
    "title": "Not Splitting",
    "statement": "There is a $k \\times k$ grid, where $k$ is even. The square in row $r$ and column $c$ is denoted by $(r,c)$. Two squares $(r_1, c_1)$ and $(r_2, c_2)$ are considered adjacent if $\\lvert r_1 - r_2 \\rvert + \\lvert c_1 - c_2 \\rvert = 1$.\n\nAn array of adjacent pairs of squares is called strong if it is possible to cut the grid along grid lines into two connected, congruent pieces so that each pair is part of the \\textbf{same} piece. Two pieces are congruent if one can be matched with the other by translation, rotation, and reflection, or a combination of these.\n\n\\begin{center}\nThe picture above represents the first test case. Arrows indicate pairs of squares, and the thick black line represents the cut.\n\\end{center}\n\nYou are given an array $a$ of $n$ pairs of adjacent squares. Find the size of the largest strong subsequence of $a$. An array $p$ is a subsequence of an array $q$ if $p$ can be obtained from $q$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "Claim. Any cut that splits the square into two congruent parts is rotationally symmetric about the center by $180^{\\circ}$. Proof. It is a special case when the cut is a vertical or horizontal line. Assume otherwise. Then: One piece has a row containing more than $\\frac{k}{2}$, but less than $k$ squares. One piece has a column containing more than $\\frac{k}{2}$, but less than $k$ squares. Both exactly pieces contain two of the corners of the grid. Now consider the isometry of the plane bringing one piece to the other. Then the corners of the grid of one piece must map to the corners of the grid of the other piece, since there has to be a straight edge connecting them with length $k$, which only exists between two corners. There are precisely two such isometries that fit within the bounds of the square: a reflection and a $180^{\\circ}$ rotation, pictured below, respectively. However if one piece has a row containing more than $\\frac{k}{2}$ but less than $k$ squares, then in the first case the number of squares in that row is greater than $k$. The same holds in the case of a vertical reflection. Hence the cut must be rotationally symmetric. Now we can turn the problem into a graph problem. Consider the graph whose vertices are vertices of the grid and whose edges are edges of the grid. We need to minimize the number of pairs of squares that we \"split up\" in our cut. Note that each pair of squares shares an edge. Thus, we want to minimize the number of these edges we pass through. Let's initially weight all edges with $0$, and increase the weight by $1$ for each edge given. Since each cut is rotationally symmetric about the center, we can just consider finding a minimal-weight path from the boundary to the center, and then rotating this path $180^{\\circ}$ to find a valid cut. However, there are three details we need to iron out: The cut may pass through other weighted edges when rotated. We need to find an efficient way to find the shortest path from each boundary point to the center. The cut may be self-intersecting. The second point can be accounted for by noticing that the boundary of the square has all edges of weight $0$, so we can just run single source shortest paths from any single point on the boundary. For the third point, consider some path that intersects itself when rotated. Suppose we build the path edge-by-edge, along with its mirror copy. At some point we will hit the mirror copy. But that means that there is a way with strictly fewer edges to reach the same point: just take the path from this intersection to the start of the mirror copy. See the image below. Instead of taking the long path (in blue/orange), we can take the shorter path (in green/purple). So now all our details are successfully ironed out. We can just run Dijkstra's algorithm from any vertex and find the length of the shortest path, solving the problem in $\\mathcal{O}(n + k^2 \\log k)$.",
    "code": "import io, os\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\nfrom heapq import heappop, heappush\n \nfor _ in range(int(input())):\n    q, n = map(int, input().split())\n    graph = [[[] for j in range(n + 1)] for i in range(n + 1)]\n    for x in range(n + 1):\n        for y in range(n + 1):\n            if x - 1 >= 0: graph[x-1][y] += [[x, y, 0]]\n            if x + 1 < n: graph[x+1][y] += [[x, y, 0]]\n            if y - 1 >= 0: graph[x][y-1] += [[x, y, 0]]\n            if y + 1 < n: graph[x][y+1] += [[x, y, 0]]\n            \n    def update(x1, y1, x2, y2):\n        for i in range(len(graph[x1][y1])):\n            if (graph[x1][y1][i][0], graph[x1][y1][i][1]) == (x2, y2):\n                graph[x1][y1][i][2] += 1\n        for i in range(len(graph[x2][y2])):\n            if (graph[x2][y2][i][0], graph[x2][y2][i][1]) == (x1, y1):\n                graph[x2][y2][i][2] += 1\n    \n    for i in range(q):\n        x1, y1, x2, y2 = map(int, input().split())\n        if x1 == x2:\n            y1, y2 = min(y1, y2), max(y1, y2)\n            update(x1 - 1, y1, x1, y1)\n            update(n - (x1 - 1), n - y1, n - x1, n - y1)\n        else:\n            x1, x2 = min(x1, x2), max(x1, x2)\n            update(x1, y1 - 1, x1, y1)\n            update(n - x1, n - (y1 - 1), n - x1, n - y1)\n    \n    dist = [[float(\"inf\")] * (n + 1) for __ in range(n + 1)]\n    queue = []\n    heappush(queue, (0, n // 2, n // 2))\n    dist[n // 2][n // 2] = 0\n    while queue:\n        length, x, y = heappop(queue)\n        if x == 0 or y == 0:\n            print(q - length)\n            break\n        if dist[x][y] != length:\n            continue\n        for x2, y2, w in graph[x][y]:\n            if dist[x2][y2] > dist[x][y] + w:\n                dist[x2][y2] = dist[x][y] + w\n                heappush(queue, (dist[x2][y2], x2, y2))",
    "tags": [
      "geometry",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1628",
    "index": "A",
    "title": "Meximum Array",
    "statement": "Mihai has just learned about the MEX concept and since he liked it so much, he decided to use it right away.\n\nGiven an array $a$ of $n$ non-negative integers, Mihai wants to create \\textbf{a new array $b$} that is formed in the following way:\n\nWhile $a$ is not empty:\n\n- Choose an integer $k$ ($1 \\leq k \\leq |a|$).\n- Append the MEX of the first $k$ numbers of the array $a$ to the end of array $b$ and erase them from the array $a$, shifting the positions of the remaining numbers in $a$.\n\nBut, since Mihai loves big arrays as much as the MEX concept, he wants the new array $b$ to be the \\textbf{lexicographically maximum}. So, Mihai asks you to tell him what the maximum array $b$ that can be created by constructing the array optimally is.\n\nAn array $x$ is lexicographically greater than an array $y$ if in the first position where $x$ and $y$ differ $x_i > y_i$ or if $|x| > |y|$ and $y$ is a prefix of $x$ (where $|x|$ denotes the size of the array $x$).\n\nThe \\textbf{MEX} of a set of non-negative integers is the minimal non-negative integer such that it is not in the set. For example, \\textbf{MEX}({${1, 2, 3}$}) $= 0$ and \\textbf{MEX}({${0, 1, 2, 4, 5}$}) $= 3$.",
    "tutorial": "The splitting points can be picked greedily. Firstly, find the MEX of all suffixes, this can be easily done in $O(n \\cdot log(n))$ or $O(n)$. Instead of removing elements, we consider that we need to split the array into some number of subarrays. Let $p$ be the index we are currently at and MEX($l, r$) - the MEX of the set formed from the numbers $[a_l, a_{l+1}, ..., a_r]$. Start the process by looking at the first element, so $p = 1$ initially. Then do the following process as long as $p \\leq n$: find the first position $j (p \\leq j \\leq n)$ such that MEX($p, j$) $=$ MEX($p, n$), add this MEX to the array $b$ and do the same process starting from position $j + 1$, so $p = j + 1$. This process always produces the optimal answer because if for each element in $b$ we choose to remove the minimum amount of elements from $a$ to obtain the maximum element $b_i$, so we have more elements in the future to do the same optimal choices. Complexity: $O(n \\cdot log(n))$ or $O(n)$ depending on implementation.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1628",
    "index": "B",
    "title": "Peculiar Movie Preferences",
    "statement": "Mihai plans to watch a movie. He only likes palindromic movies, so he wants to skip some (possibly zero) scenes to make the remaining parts of the movie palindromic.\n\nYou are given a list $s$ of $n$ non-empty strings of length \\textbf{at most $3$}, representing the scenes of Mihai's movie.\n\nA subsequence of $s$ is called awesome if it is non-empty and the concatenation of the strings in the subsequence, in order, is a palindrome.\n\nCan you help Mihai check if there is at least one awesome subsequence of $s$?\n\nA palindrome is a string that reads the same backward as forward, for example strings \"z\", \"aaa\", \"aba\", \"abccba\" are palindromes, but strings \"codeforces\", \"reality\", \"ab\" are not.\n\nA sequence $a$ is a non-empty subsequence of a non-empty sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly zero, but not all) elements.",
    "tutorial": "Because of the low constraints on the lengths of the strings, we can prove that it's enough to pair at most $2$ strings to form a palindrome. <proof only checking pairs is enough> Let's assume there is a awesome subsequence of the form xyz where x and z are single strings from s, and y is anything. If x and z are the same length, they clearly have to be reverses of each other for xyz to be a palindrome, so y is not needed to make it a palindrome. If they are not the same length, one of them is of length 3 and the other is of length 2. Assume x is the string of length 3 and y is the string of length 2. The first two characters of x must be the reverse of z. If x and z are concatenated, the third character of x is in the middle, so it doesn't matter. So in this case too, y is not needed. This proves that if any awesome subsequence exists, there also exists an awesome subsequence of 1 or 2 strings. <proof ends> So, we first check if there exists a palindrome already, if there is, we found a solution! If not, checking for each pair would take too long, but we can do it much more efficiently. We can assume that all strings are of length $2$ or $3$ since if there was a string of length $1$ it would be a palindrome and we would have found the solution earlier. For each string of length $2$ it's enough to check if before it, we have seen a string of the following $2$ forms: its reverse or its reverse with a character appended to it (so a string of length $3$), since the last character of a string of length $3$ would be the middle character of the palindrome obtained after concatenation. For each string of length $3$ it's enough to check if before it, we have seen a string of the following $2$ forms: its reverse or the reverse of the string without considering the first character (so a string of length $2$), since the first character of a string of length $3$ would be the middle character of the palindrome obtained after concatenation. All this can be checked using a frequency matrix, map, set or other data structures.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1628",
    "index": "C",
    "title": "Grid Xor",
    "statement": "Note: The XOR-sum of set $\\{s_1,s_2,\\ldots,s_m\\}$ is defined as $s_1 \\oplus s_2 \\oplus \\ldots \\oplus s_m$, where $\\oplus$ denotes the bitwise XOR operation.\n\nAfter almost winning IOI, Victor bought himself an $n\\times n$ grid containing integers in each cell. \\textbf{$n$ is an even integer.} The integer in the cell in the $i$-th row and $j$-th column is $a_{i,j}$.\n\nSadly, Mihai stole the grid from Victor and told him he would return it with only one condition: Victor has to tell Mihai the XOR-sum of \\textbf{all} the integers in the whole grid.\n\nVictor doesn't remember all the elements of the grid, but he remembers some information about it: For each cell, Victor remembers the XOR-sum of all its neighboring cells.\n\nTwo cells are considered neighbors if they share an edge — in other words, for some integers $1 \\le i, j, k, l \\le n$, the cell in the $i$-th row and $j$-th column is a neighbor of the cell in the $k$-th row and $l$-th column if $|i - k| = 1$ and $j = l$, or if $i = k$ and $|j - l| = 1$.\n\nTo get his grid back, Victor is asking you for your help. Can you use the information Victor remembers to find the XOR-sum of the whole grid?\n\nIt can be proven that the answer is unique.",
    "tutorial": "Let's denote count($i,j$) the amount of times the cell ($i,j$) contributed in queries. We notice that count($i,j$) must be odd for all cells ($i,j$). There are multiple possible solutions for this problem. In the editorial we will describe two of them. <first solution> The following construction satisfies the condition: Iterate Through all rows from row $2$ to n. For each row, traverse all its cells and query cell ($i,j$) if the cell above it if cell ($i-1,j$) was contributed (count($i-1,j$) $= 0$ (mod $2$)) an even amount of times and XOR curent_answer with $a_{ij}$ (curent_answer initially being $0$) Everule gave a proof of correctness of this approach. <first solution> <second solution> Let's try making some pattern that takes all cells exactly once: Something like this would work if the board was a triangle instead of a square. But it turns out we can actually completely cover the square by using 4 copies of such a triangle rotated: <second solution>",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "interactive",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1628",
    "index": "D1",
    "title": "Game on Sum (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference is the constraints on $n$, $m$ and $t$. You can make hacks only if all versions of the problem are solved.}\n\nAlice and Bob are given the numbers $n$, $m$ and $k$, and play a game as follows:\n\nThe game has a score that Alice tries to maximize, and Bob tries to minimize. The score is initially $0$. The game consists of $n$ turns. Each turn, Alice picks a \\textbf{real} number from $0$ to $k$ (inclusive) which Bob either adds to or subtracts from the score of the game. But throughout the game, Bob has to choose to add at least $m$ out of the $n$ turns.\n\nBob gets to know which number Alice picked before deciding whether to add or subtract the number from the score, and Alice gets to know whether Bob added or subtracted the number for the previous turn before picking the number for the current turn (except on the first turn since there was no previous turn).\n\nIf Alice and Bob play optimally, what will the final score of the game be?",
    "tutorial": "What is the answer for $n = 2$, $m = 1$? Let's call the number Alice picks on the first turn $x$. If $x$ is small, Bob can add it, and then Alice will have to pick $0$ on the last turn since Bob will definitely subtract it from the score if it isn't $0$, meaning the score ends up being $x$. If Alice picks a big number, Bob can subtract it. Then Alice will pick the biggest number she can on the last turn, ending up with a score of $k-x$. Since Bob tries to minimize the score of the game, Alice should pick an $x$ such that it maximizes the value of $min(x, k-x)$. $x$ and $k-x$ are both linear (straight line) functions on $x$. The $x$ value that maximizes the minimum of two lines is their intersection. The intersection of the lines $x$ and $k-x$ is at $x = k/2$. So Alice should pick $x = k/2$ in the optimal game where $n = 2$, $m = 1$. To generalize the solution to arbitrary $n$ and $m$, we can use DP. Let $DP[i][j]$ what the score would be if $n = i$, $m = j$. Our base cases will be $DP[i][0] = 0$ since if Bob doesn't have to add anything, Alice has to always pick $0$. $DP[i][i] = i \\cdot k$ since if Bob always has to add, Alice can just pick $k$ every time. When Bob adds to the score, the rest of the game will be the same as a game with $1$ fewer turns and $1$ fewer forced adds, except the game score is offset by Alice's number. When Bob subtracts from the score, the rest of the game will be the same as a game with $1$ fewer turns except the game score is offset by negative Alice's number. Bob will take the minimum of these, so the $DP$ transition will be $DP[i][j] = min(DP[i-1][j-1]+x, DP[i-1][j]-x)$ for $x$ that maximizes this value. This is the same problem as the $n=2$ case resulting in the intersection between lines. The score at this intersection simplifies nicely to $DP[i][j] = (DP[i-1][j-1]+DP[i-1][j])/2$ This $O(n\\cdot m)$ solution is fast enough to pass the easy version of this problem.",
    "tags": [
      "combinatorics",
      "dp",
      "games",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1628",
    "index": "D2",
    "title": "Game on Sum (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference is the constraints on $n$, $m$ and $t$. You can make hacks only if all versions of the problem are solved.}\n\nAlice and Bob are given the numbers $n$, $m$ and $k$, and play a game as follows:\n\nThe game has a score that Alice tries to maximize, and Bob tries to minimize. The score is initially $0$. The game consists of $n$ turns. Each turn, Alice picks a \\textbf{real} number from $0$ to $k$ (inclusive) which Bob either adds to or subtracts from the score of the game. But throughout the game, Bob has to choose to add at least $m$ out of the $n$ turns.\n\nBob gets to know which number Alice picked before deciding whether to add or subtract the number from the score, and Alice gets to know whether Bob added or subtracted the number for the previous turn before picking the number for the current turn (except on the first turn since there was no previous turn).\n\nIf Alice and Bob play optimally, what will the final score of the game be?",
    "tutorial": "We have base cases $DP[i][0] = 0$ $DP[i][i] = k\\cdot i$ And transition $DP[i][j] = (DP[i-1][j-1]+DP[i-1][j])/2$ Check the explanation for the easy version to see why. This $DP$ can be optimized by looking at contributions from the base cases. If we draw the $DP$ states on a grid and ignore the division by $2$ in the transition, we can see that the number of times states $DP[i][i]$ contributes to state $DP[n][m]$ is the number of paths from $(i, j)$ to $(n, m)$ in the grid such that at each step, both $i$ and $j$ increase, or only $j$ increases, except we have to exclude paths that go through other base cases. The number of such paths is $n-i-1 \\choose m-j$. Since the number of steps in all of these paths is the same, we can account for the division by $2$ in each transition by dividing by $2^{n-i}$ in the end. To find the value of $DP[n][m]$ we sum the contribution form every base case $DP[i][i]$ for $1 \\leq i \\leq n$.",
    "tags": [
      "combinatorics",
      "dp",
      "games",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1628",
    "index": "E",
    "title": "Groceries in Meteor Town",
    "statement": "Mihai lives in a town where meteor storms are a common problem. It's annoying, because Mihai has to buy groceries sometimes, and getting hit by meteors isn't fun. Therefore, we ask you to find the most dangerous way to buy groceries so that we can trick him to go there.\n\nThe town has $n$ buildings numbered from $1$ to $n$. Some buildings have roads between them, and there is exactly $1$ simple path from any building to any other building. Each road has a certain meteor danger level. The buildings all have grocery stores, but Mihai only cares about the open ones, of course. Initially, all the grocery stores are closed.\n\nYou are given $q$ queries of three types:\n\n- Given the integers $l$ and $r$, the buildings numbered from $l$ to $r$ open their grocery stores (nothing happens to buildings in the range that already have an open grocery store).\n- Given the integers $l$ and $r$, the buildings numbered from $l$ to $r$ close their grocery stores (nothing happens to buildings in the range that didn't have an open grocery store).\n- Given the integer $x$, find the maximum meteor danger level on the simple path from $x$ to \\textbf{any} open grocery store, or $-1$ if there is no edge on any simple path to an open store.",
    "tutorial": "Consider the edge with the greatest weight. Any path going through that edge will have weight equal to the weight of that edge. If we delete that edge from the tree, a path going through that edge in the original tree has one endpoint in each component that results from the removal of the edge. Consider some query $x$ with some set of open stores. If the component not including $x$ has an open store, then the answer is the deleted edge. If it does not have an open store, then we recursively solve the problem for the component of $x$. Observe that the structure of this is the same as for finding $LCA$ of a set of nodes in a tree. When asking for the $LCA$ of some set, we can pick an in-order traversal, ignore all nodes except the leftmost and rightmost ones, and still get the same $LCA$. The solution outline then looks like this: Create the binary tree that arises from making a node representing the edge with the greatest weight, and then doing the same for the two components resulting from deleting the greatest weight making them left and right subtrees of the above tree. Order the nodes by in-order traversal in this tree. Use a segment tree or another data structure to maintain what is the leftmost and rightmost open store in the in-order traversal. Find the LCA of the leftmost and rightmost open store in the created tree.",
    "tags": [
      "binary search",
      "data structures",
      "dsu",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1628",
    "index": "F",
    "title": "Spaceship Crisis Management",
    "statement": "NASA (Norwegian Astronaut Stuff Association) is developing a new steering system for spaceships. But in its current state, it wouldn't be very safe if the spaceship would end up in a bunch of space junk. To make the steering system safe, they need to answer the following:\n\nGiven the target position $t = (0, 0)$, a set of $n$ pieces of space junk $l$ described by line segments $l_i = ((a_{ix}, a_{iy}), (b_{ix}, b_{iy}))$, and a starting position $s = (s_x, s_y)$, is there a direction such that floating in that direction from the starting position would lead to the target position?\n\nWhen the spaceship hits a piece of space junk, what happens depends on the absolute difference in angle between the floating direction and the line segment, $\\theta$:\n\n- If $\\theta < 45^{\\circ}$, the spaceship slides along the piece of space junk in the direction that minimizes the change in angle, and when the spaceship slides off the end of the space junk, it continues floating in the direction it came in (before hitting the space junk).\n- If $\\theta \\ge 45^{\\circ}$, the spaceship stops, because there is too much friction to slide along the space junk.\n\nYou are only given the set of pieces of space junk once, and the target position is always $(0, 0)$, but there are $q$ queries, each with a starting position $s_j = (s_{jx}, s_{jy})$.\n\nAnswer the above question for each query.",
    "tutorial": "The exit position at a specific segment is always the same, only the exit direction changes depending on which angle the spaceship comes in at. Therefore, if we know the set of directions that are good to hit a segment at, we know if a path that hits the segment is good or not. Note that it's only useful to consider directions that are either the direction from the closest point on some segment to the target, or from some starting position to the target. Let's call these directions relevant directions. Slow solution: We can use DP to determine the set of useful directions for each segment: Sort the segments by distance to the target, and for each segment try shooting a ray in every relevant direction that is within 45 degrees of the direction of the segment itself, and see if it either hits the target or a segment where that direction is good. The comparison with 45 degrees can be done exactly using e.g. properties of the dot product. Then for each starting position query, the same ray shooting can be done. This is $O((n+q)^2 \\cdot n)$ because there are $O(n+q)$ relevant directions, $O(n+q)$ positions from which to shoot rays, and $O(n)$ segments to check intersection with. This is too slow. We found two different ways to optimize this: 1. Since we need to know what a ray hits for many different directions from the same origin, we could do some preprocessing at each origin. A Li-Chao tree traditionally finds the minimum y-value at a certain x-coordinate among a set of line segments. But it doesn't have to contain line segments. It can contain any set of functions such that any pair of them intersect at most once. This includes distance to 2D line segments from a fixed origin as a function of angle. Using this, we can for each origin do $O(n \\cdot log (n+q))$ time precomputation to get $O(log (n+q))$ time per query to a single direction, resulting in the time complexity $O((n+q)^2 \\log (n+q))$ 2. Solution by Maksim1744: If we fix the floating direction, the movement between space junk forms edges in a functional graph. We can use a sweep to build the graph and then for each starting position and determine if it reaches the target in the graph. Doing this for all relevant directions also results in a time a complexity of $O((n+q)^2 \\log (n+q))$",
    "tags": [
      "binary search",
      "data structures",
      "geometry",
      "sortings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1629",
    "index": "A",
    "title": "Download More RAM",
    "statement": "Did you know you can download more RAM? There is a shop with $n$ different pieces of software that increase your RAM. The $i$-th RAM increasing software takes $a_i$ GB of memory to run (\\textbf{temporarily, once the program is done running, you get the RAM back}), and gives you an additional $b_i$ GB of RAM (permanently). \\textbf{Each software can only be used once.} Your PC currently has $k$ GB of RAM.\n\nNote that you can't use a RAM-increasing software if it takes more GB of RAM to use than what you currently have.\n\nSince RAM is the most important thing in the world, you wonder, what is the maximum possible amount of RAM achievable?",
    "tutorial": "Using some software is never bad. It always ends up increasing your RAM if you can use it. And for any possible order to use a set of software in, they all result in the same amount RAM in the end. So we can greedily go through the list, using software if you have enough RAM for it. After going through the list, your RAM may have increased, so maybe some of the software you couldn't use at the start is now usable. Therefore we have to go through the list again (now with the used software removed) until the RAM doesn't increase anymore. This results in time complexity $O(n^2)$, which is fine for these constraints. It turns out we don't actually need to go through the list of software more than once if we sort it by $a$. This results in $O(n \\log n)$ time complexity.",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1629",
    "index": "B",
    "title": "GCD Arrays",
    "statement": "Consider the array $a$ composed of all the integers in the range $[l, r]$. For example, if $l = 3$ and $r = 7$, then $a = [3, 4, 5, 6, 7]$.\n\nGiven $l$, $r$, and $k$, is it possible for $\\gcd(a)$ to be greater than $1$ after doing the following operation at most $k$ times?\n\n- Choose $2$ numbers from $a$.\n- Permanently remove one occurrence of each of them from the array.\n- Insert their product back into $a$.\n\n$\\gcd(b)$ denotes the greatest common divisor (GCD) of the integers in $b$.",
    "tutorial": "For the $GCD$ of the whole array to be greater than $1$, each of the elements must have a common prime factor, so we need to find the prime factor that's the most common in the array and merge the elements that have this prime factor with those who don't, the answer being the size of the array - number of occurrences of the most frequent prime factor. And, because the numbers are consecutive, the most common prime factor is always $2$. So, the minimum number of moves we need to do is the count of odd numbers in the given range, which is $(r - l + 1) - (r / 2 - (l - 1) / 2)$. Now. the answer is \"YES\" when the minimum number of moves we need to do is less than or equal to $k$ and \"NO\" otherwise. The extra cases we should take care of are the ones where $l = r$, in which the answer is always \"YES\", or \"NO' only when $l = r = 1$.",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1630",
    "index": "A",
    "title": "And Matching",
    "statement": "You are given a set of $n$ ($n$ is always a power of $2$) elements containing all integers $0, 1, 2, \\ldots, n-1$ exactly once.\n\nFind $\\frac{n}{2}$ pairs of elements such that:\n\n- Each element in the set is in exactly one pair.\n- The sum over all pairs of the bitwise AND of its elements must be exactly equal to $k$. Formally, if $a_i$ and $b_i$ are the elements of the $i$-th pair, then the following must hold: $$\\sum_{i=1}^{n/2}{a_i \\& b_i} = k,$$ where $\\&$ denotes the bitwise AND operation.\n\nIf there are many solutions, print any of them, if there is no solution, print $-1$ instead.",
    "tutorial": "Try to find a pairing such that $\\sum\\limits_1^{n/2}{a_i\\&{b_i}}=0$ Try to find a pairing for $k>0$ by changing only a few elements from the previous pairing. Let's define $c(x)$, the compliment of $x$, as the number $x$ after changing all bits 0 to 1 and vice versa, for example $c(110010_2) = 001101_2$. It can be shown that $c(x) = x\\oplus{(n-1)}$. Remember that $n-1 = 11...11_2$ since $n$ is a power of $2$. We will separate the problem into three cases. Case $k = 0$: In this case it is possible to pair $x$ with $c(x)$ for $0\\leq{x}<{\\frac{n}{2}}$, getting $\\sum\\limits_{x=0}^{\\frac{n}{2}-1} {x\\&{c(x)}} = 0$. Case $k = 0$: In this case it is possible to pair $x$ with $c(x)$ for $0\\leq{x}<{\\frac{n}{2}}$, getting $\\sum\\limits_{x=0}^{\\frac{n}{2}-1} {x\\&{c(x)}} = 0$. Case $0 < k < n-1$: In this case it is possible to pair each element with its compliment except $0$, $k$, $c(k)$ and $n-1$, and then pair $0$ with $c(k)$ and $k$ with $n-1$, $0\\& c(k) = 0$ and $k\\& (n-1) = k$. Case $0 < k < n-1$: In this case it is possible to pair each element with its compliment except $0$, $k$, $c(k)$ and $n-1$, and then pair $0$ with $c(k)$ and $k$ with $n-1$, $0\\& c(k) = 0$ and $k\\& (n-1) = k$. Case $k = n-1$: There are many constructions that work in this case, if $n=4$ there is no solution, if $n \\geq8$ it is possible to construct the answer in the following way: It is possible to pair $n-1$ with $n-2$, $n-3$ with $1$, $0$ with $2$ and all other elements with their compliments. $(n-1)\\&{(n-2)}=n-2$, for example $1111_2\\&{1110_2}=1110_2$ $(n-3)\\&{1}=1$, for example $1101_2\\&{0001_2}=0001_2$ $0\\&{2}=0$, for example $0000_2\\&{0010_2}=0000_2$ All other elements can be paired with their complements and $x\\&{c(x)}=0$ Note that $(n-2)+1+0+0+ ... +0=n-1$. Case $k = n-1$: There are many constructions that work in this case, if $n=4$ there is no solution, if $n \\geq8$ it is possible to construct the answer in the following way: It is possible to pair $n-1$ with $n-2$, $n-3$ with $1$, $0$ with $2$ and all other elements with their compliments. $(n-1)\\&{(n-2)}=n-2$, for example $1111_2\\&{1110_2}=1110_2$ $(n-3)\\&{1}=1$, for example $1101_2\\&{0001_2}=0001_2$ $0\\&{2}=0$, for example $0000_2\\&{0010_2}=0000_2$ All other elements can be paired with their complements and $x\\&{c(x)}=0$ Note that $(n-2)+1+0+0+ ... +0=n-1$. Each case can be implemented in $O(n)$. Let's define $a$ such that $a_i = i-1$ for $1\\le i \\le \\frac{n}{2}$ and $b$ such that $b_i = c(a_i)$ for $1\\le i \\le \\frac{n}{2}$. For example, for $n = 16$ they are: $a = [0000_2, 0001_2, 0010_2, 0011_2, 0100_2, 0101_2, 0110_2, 0111_2]$ $b = [1111_2, 1110_2, 1101_2, 1100_2, 1011_2, 1010_2, 1001_2, 1000_2]$ All swaps are independent and are applied to the original $a$ and $b$. After swapping two adjacent elements of $b$ (that have not been swapped) the sum will change in $2^x-1$ for some positive integer $x$. Then it is possible to solve the problem by repeatedly swapping the pair that maximizes $\\sum\\limits_{i=1}^{n/2}{ a_i\\&{b_i}}$ after the swap such that $\\sum\\limits_{i=1}^{n/2}{ a_i\\&{b_i}} \\leq k$ is held and none of its elements have been swapped yet. However, this only works for all values of $k$ if $n \\geq 32$, the case $n \\leq 16$ can be handled with brute force. Please read the previous solution. Arrays $a$ and $b$ from it will also be used here. It is possible to start with $a$ and $b$ and repeatedly select and index $x$ randomly and swap $b_x$ with $b_{x+1}$ if $\\sum\\limits_{i=1}^{n/2}{a_i\\&b_i} \\leq k$ holds until $\\sum\\limits_{i=1}^{n/2}{a_i\\&b_i} = k$. We have no proof of this solution but it was stressed against each possible input to the problem and it worked quickly for $n \\geq 16$, the case $n \\leq 8$ can be handled with brute force.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint c(int x,int n){\n    return ( x ^ ( n - 1 ) );\n}\n\nint main(){\n\n    int tc;\n    cin >> tc;\n    while( tc-- ){\n\n        int n, k;\n        cin >> n >> k;\n\n        vector<int> a(n/2), b(n/2);\n\n        if( k == 0 ){\n            for(int i=0; i<n/2; i++){\n                a[i] = i;\n                b[i] = c(i,n);\n            }\n        }\n\n        if( k > 0 && k < n - 1 ){\n            int small_k = min( k , c(k,n) );\n            for(int i=0; i<n/2; i++){\n                if( i != 0 && i != small_k ){\n                    a[i] = i;\n                    b[i] = c(i,n);\n                }\n            }\n\n            a[0] = 0;\n            b[0] = c(k,n);\n\n            a[small_k] = k;\n            b[small_k] = n - 1;\n        }\n\n        if( k == n - 1 ){\n\n            if( n == 4 ){\n                cout << -1 << '\\n';\n                continue;\n            }\n\n            a[0] = n - 2;\n            b[0] = n - 1;\n\n            a[1] = 1;\n            b[1] = n - 3;\n\n            a[2] = 0;\n            b[2] = 2;\n\n            for(int i=3; i<n/2; i++){\n                a[i] = i;\n                b[i] = c(i,n);\n            }\n        }\n\n        for(int i=0; i<n/2; i++){\n            cout << a[i] << ' ' << b[i] << '\\n';\n        }\n    }\n\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1630",
    "index": "B",
    "title": "Range and Partition",
    "statement": "Given an array $a$ of $n$ integers, find a range of values $[x, y]$ ($x \\le y$), and split $a$ into \\textbf{exactly} $k$ ($1 \\le k \\le n$) subarrays in such a way that:\n\n- Each subarray is formed by several continuous elements of $a$, that is, it is equal to $a_l, a_{l+1}, \\ldots, a_r$ for some $l$ and $r$ ($1 \\leq l \\leq r \\leq n$).\n- Each element from $a$ belongs to exactly one subarray.\n- In each subarray the number of elements inside the range $[x, y]$ (inclusive) is \\textbf{strictly greater} than the number of elements outside the range. An element with index $i$ is inside the range $[x, y]$ if and only if $x \\le a_i \\le y$.\n\nPrint any solution that minimizes $y - x$.",
    "tutorial": "Focus on how to solve the problem for a fixed interval $[x,y]$ Think about the numbers inside the interval as $+1$, and the other numbers as $-1$ Try to relate a partition into valid subarrays with an increasing sequence of the prefix sums array Note that if some value $x$ ($x>0$) appears on the prefix sums array, $x-1$ appears before since the absolute value of the elements is $1$ (+1 and -1) Focus on how to solve the problem for a fixed interval $[x,y]$: Let us define an array $b$ such that $b_i = 1$ if $x \\le a_i \\le y$ or $b_i = -1$ otherwise, for all $1\\le i\\le n$. Let's define $psum_i$ as $b_1 + b_2 + ... + b_i$. We need to find a partition on $k$ subarrays with positive sum of $b_i$. The sum of a subarray $[l,r]$ is $b_l+b_{l+1}+...+b_r = psum_r-psum_{l-1}$. Then a subarray is valid if $psum_r > psum_{l-1}$. We need to find an increasing sequence of $psum$ of length $k+1$ starting at $0$ and ending at $n$. Let's define $firstocc_x$ to be the first occurrence of the integer $x$ in $psum$. If $psum_n < k$ there will be no valid sequence, otherwise the sequence $0, firstocc_1, firstocc_2, ..., firstocc_{k-1}, n$ will satisfy all constraints. Note that, since $|psum_i-psum_{i-1}| = 1$, for $i>0$, then $firstocc_v$ exists and $firstocc_v < firstocc_{v+1}$ for $0\\leq v \\leq psum_n$. This solves the problem for a fixed interval. It remains to find the smallest interval $[x,y]$ such that $psum_n \\geq k$. For a given interval $[x,y]$, since $psum_n = b_1 + b_2 + ... + b_n$, $psum_n$ will be equal to the number of elements of $a$ inside the interval minus the number of elements outside. Then for each $x$, it is possible to find the smallest $y$ such that $psum_n \\geq k$ using binary search or two pointers. It is also possible to note that: $psum_n \\geq k$ $\\sum\\limits_{i=1}^n b_i \\geq k$ $\\sum\\limits_{i=1}^n (-1 + 2\\cdot [x\\le a_i\\le y]) \\geq k$ $\\sum\\limits_{i=1}^n [x\\le a_i\\le y] \\geq \\lceil{\\frac{k+n}{2}}\\rceil$ We need to find the smallest interval with at least $\\lceil{\\frac{k+n}{2}}\\rceil$ inside, let $A$ be the array $a$ sorted, the answer is the minimum interval among all intervals $[A_i, A_{i+\\lceil{\\frac{k+n}{2}}\\rceil-1}]$ for $1 \\leq i \\leq n - \\lceil{\\frac{k+n}{2}}\\rceil+1$. Complexity: $O(n\\log{n})$ if solved with the previous formula or binary search, or $O(n)$ is solved with two pointers.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint main() {\n \n    int tc;\n    cin >> tc;\n    while( tc-- ){\n \n        int n, k;\n        cin >> n >> k;\n \n        vector<int> a(n), sorted_a(n);\n        for(int i=0; i<n; i++){\n            cin >> a[i];\n            sorted_a[i] = a[i];\n        }\n \n        sort(sorted_a.begin(),sorted_a.end());\n \n        int req_sum = ( n + k + 1 ) / 2;\n \n        pair<int,pair<int,int>> ans = { n + 1 , { -1 , -1 } };\n \n        for(int i=0; i+req_sum-1<n; i++)\n            ans = min( ans , { sorted_a[i+req_sum-1] - sorted_a[i] , { sorted_a[i] , sorted_a[i+req_sum-1] } } );\n \n        cout << ans.second.first << ' ' << ans.second.second << '\\n';\n \n        int subarrays_found = 0, curr_sum = 0;\n        int last_uncovered = 1;\n \n        for(int i=0; i<n; i++){\n \n            if( a[i] >= ans.second.first && a[i] <= ans.second.second ) curr_sum ++;\n                else curr_sum --;\n \n            if( curr_sum > 0 && subarrays_found + 1 < k ){\n \n                cout << last_uncovered << ' ' << ( i + 1 ) << '\\n';\n                last_uncovered = i + 2;\n \n                subarrays_found ++;\n                curr_sum = 0;\n            }\n        }\n \n        subarrays_found ++;\n        cout << last_uncovered << ' ' << n << '\\n';\n \n    }\n \n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1630",
    "index": "C",
    "title": "Paint the Middle",
    "statement": "You are given $n$ elements numbered from $1$ to $n$, the element $i$ has value $a_i$ and color $c_i$, initially, $c_i = 0$ for all $i$.\n\nThe following operation can be applied:\n\n- Select three elements $i$, $j$ and $k$ ($1 \\leq i < j < k \\leq n$), such that $c_i$, $c_j$ and $c_k$ are all equal to $0$ and $a_i = a_k$, then set $c_j = 1$.\n\nFind the maximum value of $\\sum\\limits_{i=1}^n{c_i}$ that can be obtained after applying the given operation any number of times.",
    "tutorial": "Think about all occurrences of some element, what occurrences are important? Think about the first and last occurrence of each element as a segment. Think about the segments that at least one of its endpoints will end up with $c_i = 0$. For each $x$ such that all the elements $a_1, a_2, ..., a_x$ are different from $a_{x+1}, a_{x+2}, ..., a_n$ it is impossible to apply an operation with some indices from the first part, and some other from the second one. Then it is possible to split the array in subarrays for each $x$ such that the previous condition holds, and sum the answers from all of them. Let's solve the problem independently for one of those subarrays, let's denote its length as $m$, the values of its elements as $a_1, ..., a_m$ and their colors as $c_1, ..., c_m$: For every tuple $(x, y, z)$ such that $1 \\le x < y < z \\le m$ and $a_x = a_y = a_z$ it is possible to apply an operation with indices $x, y$ and $z$. Then only the first and last occurrences of each element are important. For all pairs $(x, y)$ such that $1 \\le x < y \\le m$, $a_x = a_y$, $a_x$ is the first occurrence and $a_y$ the last occurrence of that value, a segment $[x, y]$ will be created. Let's denote the left border of a segment $i$ as $l_i$ and the right border as $r_i$. Let's say that a set of segments $S$ is connected if the union of its segments is the segment $[\\min(l_i, \\forall i\\in{S}), \\max(r_i, \\forall i\\in{S})]$. Instead of maximizing $\\sum\\limits_{i=1}^m{c_i}$, it is possible to focus on minimizing $\\sum\\limits_{i=1}^m{[c_i=0]}$. Lemma 1: If we have a connected set $S$, it is possible to apply some operations to its induced array to end up with at most $|S|+1$ elements with $c_i = 0$. For each segment $x$ in $S$ if there exists a segment $y$ such that $l_y < l_x < r_x < r_y$, it is possible to apply the operation with indices $l_y, l_x, r_y$ and with $l_y, r_x, r_y$. Otherwise, add this segment to a set $T$. Then is possible to repeatedly select the leftmost segment of $T$ that have not been selected yet, and set the color of its right border to $1$, this will be always possible until we select the rightmost segment since $T$ is connected. In the end, all the left borders of the segments of $T$ will have $c_i = 0$, the same holds for the right border of the rightmost segment of $T$, which leads to a total of $|T|+1$ elements with $c_i = 0$, and $|T| \\le |S|$. Let $X$ be a subarray that can be obtained by applying the given operation to the initial subarray any number of times. Let $S(X)$ be the set of segments that includes all segments $i$ such that $c[l_i] = 0$ or $c[r_i] = 0$ (or both), where $c[i]$ is the color of the $i$-th segment of the subarray $X$. Lemma 2: There is always an optimal solution in which $S(X)$ is connected. Suppose $S(X)$ is not connected, if there are only two components of segments $A$ and $B$, there will always be a segment from $A$ to $B$ due to the way the subarray was formed. If $A$ or $B$ have some segment $x$ such that there exists a segment $y$ such that $l_y < l_x < r_x < r_y$ you can erase it by applying the operation with indices $l_y, l_x, r_y$ and with $l_y, r_x, r_y$. Then we can assume that $\\sum\\limits_{i\\in A}{([c[l_i]=0]+[c[r_i]=0])} = |A|+1$ and similarly for $B$. The solution to $A$ before merging is $|A|+1$, the solution to $B$ is $|B|+1$, if we merge $A$ and $B$ with a segment we get a component $C$ of size $|A|+|B|+1$, and its answer will be $|A|+|B|+1+1$ (using \\bf{lemma 1}), the case with more than two components is similar, then we can always merge the components without making the answer worse. Finally, the problem in each subarray can be reduced to find the smallest set (in number of segments), such that the union of its segments is the whole subarray. This can be computed with dp or sweep line. Let $dp[x]$ be the minimum size of a set such that the union of its segments is the segment $[1,x]$. To compute $dp$, process all the segments in increasing order of $r_i$, and compute the value of $dp[r_i] = \\min(dp[l_i+1], dp[l_i+2], ..., dp[r_i-1]) + 1$. Then the solution to the subarray is $dp[m] + 1$, this $dp$ can be computed in $O(m\\log{m})$ with segment tree. It is possible to compute a similar $dp$ to solve the problem for the whole array without splitting the array, the time complexity is $O(n\\log{n})$. It is possible to create an event where a segment starts and an event where a segment ends. Then process the events in order and each time a segment ends, if it is the rightmost segment added, add to the solution the segment with maximum $r_i$ among the segments that $l_i$ is already processed. It is possible to modify the sweep line to solve the problem for the whole array without splitting the array, the time complexity is $O(n)$ or $O(n\\log{n})$ depending on the implementation.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \ntemplate <typename Tnode,typename Tup>\nstruct ST{\n    vector<Tnode> st;\n    int sz;\n \n    ST(int n){\n        sz = n;\n        st.resize(4*n);\n    }\n \n    Tnode merge_(Tnode a, Tnode b){\n        Tnode c;\n        /// Merge a and b into c\n        c = min( a , b );\n        return c;\n    }\n \n    void update_node(int nod,Tup v){\n        /// how v affects to st[nod]\n        st[nod] = v;\n    }\n \n    void build(vector<Tnode> &arr){ build(1,0,sz-1,arr); }\n \n    void build(int nod,int l,int r,vector<Tnode> &arr){\n        if( l == r ){\n            st[nod] = arr[l];\n            return;\n        }\n        int mi = ( l + r ) >> 1;\n            build((nod<<1),l,mi,arr);\n            build((nod<<1)+1,mi+1,r,arr);\n        st[nod] = merge_( st[(nod<<1)] , st[(nod<<1)+1] );\n    }\n \n    void update(int id,Tup v){ update(1,0,sz-1,id,v); }\n \n    void update(int nod,int l,int r,int id,Tup v){\n        if( l == r ){\n            update_node(nod,v);\n            return;\n        }\n        int mi = ( l + r ) >> 1;\n        if( id <= mi ) update((nod<<1),l,mi,id,v);\n            else update((nod<<1)+1,mi+1,r,id,v);\n        st[nod] = merge_( st[(nod<<1)] , st[(nod<<1)+1] );\n    }\n \n    Tnode query(int l,int r){ return query(1,0,sz-1,l,r); }\n \n    Tnode query(int nod,int l,int r,int x,int y){\n \n        if( l >= x && r <= y ) return st[nod];\n \n        int mi = ( l + r ) >> 1;\n \n        if( y <= mi ) return query((nod<<1),l,mi,x,y);\n \n        if( x > mi ) return query((nod<<1)+1,mi+1,r,x,y);\n \n        return merge_( query((nod<<1),l,mi,x,y), query((nod<<1)+1,mi+1,r,x,y) );\n    }\n};\n \nint main(){\n \n    int n;\n    cin >> n;\n \n    vector<int> a(n), fst(n,-1), lst(n,-1);\n    for(int i=0; i<n; i++){\n        cin >> a[i];\n        a[i] --;\n        if( fst[a[i]] == -1 )\n            fst[a[i]] = i;\n        lst[a[i]] = i;\n    }\n \n    vector<pair<int,int>> segments;\n    for(int i=0; i<n; i++)\n        if( fst[i] != -1 )\n            segments.push_back({lst[i]+1,fst[i]+1});\n    sort(segments.begin(),segments.end());\n \n    vector<int> dp(n+1,1000000007);\n    dp[0] = 0;\n \n    ST<int,int> st(n+1);\n    st.build(dp);\n    for( auto i : segments ){\n        dp[i.first] = min( dp[i.first] , dp[i.second-1] + 1 + ( i.first != i.second ) );\n        if( i.second + 1 <= i.first - 1 )\n            dp[i.first] = min( dp[i.first] , st.query(i.second+1,i.first-1) + 1 );\n        st.update(i.first,dp[i.first]);\n    }\n    cout << n - dp[n] << '\\n';\n \n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1630",
    "index": "D",
    "title": "Flipping Range",
    "statement": "You are given an array $a$ of $n$ integers and a set $B$ of $m$ positive integers such that $1 \\leq b_i \\leq \\lfloor \\frac{n}{2} \\rfloor$ for $1\\le i\\le m$, where $b_i$ is the $i$-th element of $B$.\n\nYou can make the following operation on $a$:\n\n- Select some $x$ such that $x$ appears in $B$.\n- Select an interval from array $a$ of size $x$ and multiply by $-1$ every element in the interval. Formally, select $l$ and $r$ such that $1\\leq l\\leq r \\leq n$ and $r-l+1=x$, then assign $a_i:=-a_i$ for every $i$ such that $l\\leq i\\leq r$.\n\nConsider the following example, let $a=[0,6,-2,1,-4,5]$ and $B=\\{1,2\\}$:\n\n- $[0,6,-2,-1,4,5]$ is obtained after choosing size $2$ and $l=4$, $r=5$.\n- $[0,6,2,-1,4,5]$ is obtained after choosing size $1$ and $l=3$, $r=3$.\n\nFind the maximum $\\sum\\limits_{i=1}^n {a_i}$ you can get after applying such operation any number of times (possibly zero).",
    "tutorial": "What is the size of the smallest subarray that it is possible to multiply by $-1$ using some operations? Let $s$ be a string such that $s_i=0$ if that element is multiplied by $-1$ or $s_i=1$ otherwise, what such $s$ are reachable? Think about the parity of the sum of all $s_i$ such that $i\\mod{g}=constant$, where $g$ is the size of the smallest subarray that it is possible to multiply by $-1$ using some operations If we have $x, y \\in B$ (assume $x > y$), since all elements of $B$ are at most $\\lfloor\\frac{n}{2}\\rfloor$, it is possible to multiply all intervals of size $x-y$ by either multiplying an interval of size $x$ that starts at the position of the interval of size $x-y$, and an interval of size $y$ that ends at the same position as the interval $x$, or multiply an interval of size $x$ that ends at the same position as the interval of size $x-y$ and another interval of size $y$ that starts at the same position as the interval of size $x$. For two elements $x, y \\in B$ ($x > y$), it is possible to add $x-y$ to $B$, repeatedly doing this it is possible to get $\\gcd(x, y)$. Let $g = \\gcd(b_1, b_2, ..., b_m : b_i \\in B)$, by applying the previous reduction $g$ is the smallest element that can be obtained, and all other elements will be its multiples, then the problem is reduced to, multiplying intervals of size $g$ by $-1$ any number of times, maximize $\\sum\\limits_{i=1}^n{a_i}$. Let's define the string $s = 000...00$ of size $n$ (0-indexed) such that $s_i = 0$ if the $i$-th element is not multiplied by $-1$ or $s_i = 1$ otherwise. The operation flips all values of $s$ in a substring of size $g$. Let's define $f_x$ as the xor over all values $s_i$ such that $i\\mod g = x$, note that $f_x$ is defined for the values $0 \\le x \\le g-1$. In any operation, all values of $f$ change simultaneously, since they are all $0$ at the beginning only the states of $s$ such that all $f_i$ are equal are reachable. To prove that all states of $s$ with all $f_i$ equal are reachable, let's start with any state of $s$ such that $f = 000...00$ and repeatedly select the rightmost $i$ such that $s_i=1$ and $i\\geq g-1$ and flip the substring that ends in that position, after doing that as many times as possible, $s_i = 0$ for $g-1\\leq i\\leq n-1$. If $s_i=1$ for any $0\\leq i < g$, then $f_i = 1$ which is a contradiction since $f_{g-1} = 0$ and all $f_i$ change simultaneously, then $s = 000...00$. The case with all values of $f$ equal to $1$ is similar. After this, it is possible to solve the problem with $dp$. Let $dp_{i,0}$ be the maximum sum of $a_i, a_{i-g}, a_{i-2\\cdot{g}}, ..., a_{i-k\\cdot{g}}$ such that $i-k\\cdot{g}\\equiv{i}(\\mod{g})$ and $\\bigoplus\\limits_{k\\geq 0, i-k\\cdot g\\geq 0} f_{i-k \\cdot g}=0$ and $dp_{i,1}$ be the same such that $\\bigoplus\\limits_{k\\geq 0, i-k\\cdot g\\geq 0} f_{i-k \\cdot g}=1$. The answer to the problem is $\\max(\\sum\\limits_{i=n-g}^{n-1}{dp_{i,0}}, \\sum\\limits_{i=n-g}^{n-1}{dp_{i,1}} )$ (0-indexed). This $dp$ can be computed in $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    int T;\n    cin >> T;\n\n    while(T--)\n    {\n        int n,m;\n        cin >> n >> m;\n        vector<int> a(n),b(m);\n        for(int i=0;i<n;i++)\n            cin >> a[i];\n\n        int g=0;\n        for(int i=0;i<m;i++)\n        {\n            cin >> b[i];\n            g=__gcd(g,b[i]);\n        }\n\n        vector<vector<ll>> dp(g,vector<ll>(2));\n        for(int i=0;i<g;i++)\n            dp[i][1]=-2e9;\n        for(int i=0;i<n;i++)\n        {\n            int rem=i%g;\n            ll v0=max(dp[rem][0]+a[i],dp[rem][1]-a[i]);\n            ll v1=max(dp[rem][0]-a[i],dp[rem][1]+a[i]);\n            dp[rem][0]=v0;\n            dp[rem][1]=v1;\n        }\n\n        ll sum0=0,sum1=0;\n        for(int i=0;i<g;i++)\n        {\n            sum0+=dp[i][0];\n            sum1+=dp[i][1];\n        }\n\n        cout << max(sum0,sum1) << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1630",
    "index": "E",
    "title": "Expected Components",
    "statement": "Given a cyclic array $a$ of size $n$, where $a_i$ is the value of $a$ in the $i$-th position, \\textbf{there may be repeated values}. Let us define that a permutation of $a$ is equal to another permutation of $a$ if and only if their values are the same for each position $i$ or we can transform them to each other by performing some cyclic rotation. Let us define for a cyclic array $b$ its number of components as the number of connected components in a graph, where the vertices are the positions of $b$ and we add an edge between each pair of adjacent positions of $b$ with equal values (note that in a cyclic array the first and last position are also adjacents).\n\nFind the expected value of components of a permutation of $a$ if we select it equiprobably over the set of all the different permutations of $a$.",
    "tutorial": "Burnside's lemma Think about an easy way to count the number of components in a cyclic array. The number of components in a cyclic array is equal to the number of adjacent positions with different values. The problem can be solved by applying Burnside's lemma. The number of different permutations of the cyclic array $a$ is equal to the sum of number of fixed points for each permutation function divided by the number of permutations functions. Let's focus on two parts. First part (find the number of different permutations of $a$): Let's define a permutation function $F_x(arr)$ as the function that cyclically shifts the array $arr$ by $x$ positions. In this problem for an array of size $n$ we have $n$ possible permutations functions and we would need to find the sum of the number of fixed points for each permutation function. To find the number of fixed points for a permutation function $F_x()$ we have that $arr_i$ must be equal to $arr_{(i+x)\\%n}$, if we add an edge $(i,(i+x)\\%n)$ for each position $i$ then by number theory we would obtain that $gcd(n,x)$ cycles would be formed and each one of size $\\frac{n}{gcd(n,x)}$, then we can note that each position $i$ will belong to the $(i\\%gcd(n,x))$-th cycle, so we can say that the problem can be transformed into counting the number of permutations with repetition in an array of size $gcd(n,x)$. Let us denote $cnt[v]$ as the number of values equal to $v$ in array $a$, when we are processing the function $F_x()$ and we reduce the problem to an array of size $gcd(n,x)$ we should also decrease $cnt[v]$ to $\\frac{cnt[v]}{n/gcd(n,x)}$ since each component is made up of $\\frac{n}{gcd(n,x)}$ values, also we must observe that for solving a problem for an array of size $x$, then $\\frac{n}{x}$ should be a divisor of $gcd(cnt[1],cnt[2],\\ldots,cnt[n])$. Let us denote $cnt_x[v] = \\frac{cnt[v]}{n/gcd(n,x)}$ So to count the number of permutations with repetition for $F_x()$ that can be formed with the frequency array $cnt_x$ we can use the formula $\\frac{n!}{x_1! \\cdot x_2! \\cdot \\ldots \\cdot x_n!}$ Let us denote $G_{all} = gcd(cnt[1],cnt[2],\\ldots,cnt[n])$ Let us denote $fdiv(val)$ as the number of divisors of $val$. Let us denote $tot_{sz}$ as the number of permutations with repetition for an array of size $sz$, from what has been said before we have that $\\frac{n}{sz}$ must be divisible by $G_{all}$ so we only need to calculate the permutations with repetition for $fdiv(G_{all})$ arrays. Now suppose that the number of different values of array $a$ is $k$ then $G_{all}$ must be at most $\\frac{n}{k}$ because the gcd of several numbers is always less than or equal to the smallest of them. Now to calculate the permutations with repetition for a $cnt_x$ we do it in $O(k)$, for that we need to precalculate some factorials and modular inverses before, and since we need to calculate them $fdiv(G_{all})$ times, then we have that in total the complexity would be $O(fdiv(G_{all})\\cdot k)$ but since $G_{all}$ is at most $\\frac{n}{k}$ and $fdiv(\\frac{n}{k})$ is at most $\\frac{n}{k}$, substituting it would be $O(\\frac{n}{k}\\cdot k)$ equal to $O(n)$ So to find the sum of the number of fixed points we need the sum of $tot_{gcd(n,x)}$ for $1 \\le x \\le n$ and $\\frac{n}{gcd(n,x)}$ divides to $G_{all}$, at the end of all we divide the sum of the number of fixed points by $n$ and we would obtain the number of different permutations of $a$. To find the $gcd(n,x)$ for $1 \\le x \\le n$ we do it with the Euclid's algorithm in complexity $O(n\\cdot log)$ so in total the complexity is $O(n\\cdot log)$ Second part (find the expected value of components of different permutations of $a$): Here we will use the Linear Expectation property and we will focus on calculating the contribution of each component separately, the first thing is to realize that the number of components is equal to the number of different adjacent values, so we only need to focus on two adjacent values, except if it is a single component, this would be a special case. If we have $k$ different values we can use each different pair of them that in total would be $k\\cdot(k-1)$ pairs, we can realize that when we put a pair its contribution would be equal to the number of ways to permute the remaining values, which if we are in an array of size $\\frac{n}{x}$ and we use the values $val_1$ and $val_2$ it would be equal to: $tot_{n/x} \\cdot \\frac{1}{(n/x)\\cdot(n/x-1)} \\cdot cnt_x[val_1] \\cdot cnt_x[val_2]$ because we removing a value $val_1$ and another value $val_2$ from the set, so if we have the formula: $\\frac{n!}{x_1! \\cdot x_2! \\cdot \\ldots \\cdot x_n!}$ and $val_1$ and $val_2$ are the first two elements then it would be: $\\frac{(n-2)!}{(x_1-1)! \\cdot (x_2-1)! \\cdot \\ldots \\cdot x_n!}$ which would be equivalent to: $\\frac{n!}{x_1! \\cdot x_2! \\cdot \\ldots \\cdot x_n!} \\cdot \\frac{1}{n \\cdot (n-1)} \\cdot x_1 \\cdot x_2$ Now to calculate the contribution of the $k\\cdot(k-1)$ pairs we can realize that taking common factor $tot_{n/x} \\cdot \\frac{1}{(n/x)\\cdot(n/x-1)}$ in the previous expression it only remains to find the sum of $cnt_x[i]\\cdot cnt_x[j]$ for all $i \\neq j$, this can be found in $O(k)$ easily by keeping the prefix sum and doing some multiplication. Then at the end we multiply by $n$ since there are $n$ possible pairs of adjacent elements in the general array. Let us define $sum_{sz}$ as the contribution of components of the permutations with repetition for an array of size $sz$, then: $sum_{n/x} = tot_{n/x} \\cdot \\frac{1}{(n/x)\\cdot(n/x-1)} \\cdot (sum~of~(cnt_x[i]\\cdot cnt_x[j])~for~i \\neq j) \\cdot n$ Now for each possible permutation with repetition we have by the Burnside's lemma that in the end we divide it by $n$, so we should also divide by $n$ the contribution of each component. Let's define $tot'_x = \\frac{tot_x}{n}$ and $sum'_x = \\frac{sum_x}{n}$ Let's define $tot_{all}$ as the sum of $tot'_{gcd(n,x)}$ for $1 \\le x \\le n$ and $\\frac{n}{gcd(n,x)}$ divide to $G_{all}$. Let's define $sum_{all}$ as the sum of $sum'_{gcd(n,x)}$ for $1 \\le x \\le n$ and $\\frac{n}{gcd(n,x)}$ divide to $G_{all}$. The final answer would be: $res = \\frac{sum_{all}}{tot_{all}}$ The final complexity then is $O(n\\cdot log)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 1e6 + 100;\n\nconst int MOD = 998244353;\n\nlong long fact[MAXN];\n\nlong long F[MAXN];\n\nlong long qpow(long long a, long long b)\n{\n    long long res = 1;\n    while(b)\n    {\n        if(b&1)res = res*a%MOD;\n        a = a*a%MOD;\n        b /= 2;\n    }\n    return res;\n}\n\nlong long inv(long long x)\n{\n    return qpow(x,MOD-2);\n}\n\nint32_t main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    fact[0] = 1;\n\n    for(int i = 1 ; i < MAXN ; i++)\n    {\n        fact[i] = fact[i-1]*i%MOD;\n    }\n\n    int T;\n    cin >> T;\n\n    while(T--)\n    {\n        int N;\n        cin >> N;\n\n        for(int i = 1 ; i <= N ; i++)\n        {\n            F[i] = 0;\n        }\n\n        for(int i = 1 ; i <= N ; i++)\n        {\n            int n;\n            cin >> n;\n            F[n]++;\n        }\n\n        vector<long long> vvv;\n\n        for(int i = 1 ; i <= N ; i++)\n        {\n            if(F[i])vvv.push_back(F[i]);\n        }\n\n        int G = 0;\n\n        for(auto x : vvv)\n        {\n            G = __gcd(G,x);\n        }\n\n        if(G == N)\n        {\n            cout << 1 << '\\n';\n            continue;\n        }\n\n        vector<long long> arr(N+1);\n        vector<long long> arr2(N+1);\n\n        for(int i = 1 ; i <= G ; i++)\n        {\n            if(G%i == 0)\n            {\n                long long tot = inv(fact[N/i-2]), acum = 0, sum = 0;\n\n                for(auto x : vvv)\n                {\n                    tot = tot*fact[x/i]%MOD;\n                    sum = (sum + acum*(x/i)*2)%MOD;\n                    acum = (acum + (x/i))%MOD;\n                }\n\n                tot = inv(tot);\n\n                arr2[i] = tot*(N/i-1)%MOD*(N/i)%MOD;\n\n                tot = tot*sum%MOD*N%MOD;\n\n                arr[i] = tot;\n            }\n        }\n\n        long long res = 0;\n        long long cont = 0;\n\n        for(int i = 1 ; i <= N ; i++)\n        {\n            long long ggg = N/__gcd(N,i);\n\n            if(G%ggg == 0)\n            {\n                res = (res + arr[ggg])%MOD;\n                cont = (cont + arr2[ggg])%MOD;\n            }\n        }\n\n        cout << res*inv(cont)%MOD << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1630",
    "index": "F",
    "title": "Making It Bipartite",
    "statement": "You are given an undirected graph of $n$ vertices indexed from $1$ to $n$, where vertex $i$ has a value $a_i$ assigned to it and all values $a_i$ are \\textbf{different}. There is an edge between two vertices $u$ and $v$ if either $a_u$ divides $a_v$ or $a_v$ divides $a_u$.\n\nFind the minimum number of vertices to remove such that the remaining graph is bipartite, when you remove a vertex you remove all the edges incident to it.",
    "tutorial": "Think about the directed graph where there is an directed edge from $a$ to $b$ if and only if $b|a$ Let us define the above graph as $G$, make a duplicate graph $G'$ from $G$, and then add directed edges $(x', x)$ for each node $x'$ of the graph $G'$. What happens in this graph? Maximum Antichain First of all, let's analyze what happens when there are $3$ vertices $x$, $y$ and $z$ such that $a_x|a_y$, $a_x|a_z$ and $a_y|a_z$, if this happens then the graph cannot be bipartite because there would be a cycle of size $3$, therefore there cannot be such a triple ($x$, $y$, $z$), this condition, besides to being necessary, is sufficient since we can separate the graph into two sets, set $A$: vertices that have edges towards multiples, set $B$: vertices that have edges towards divisors, keep in mind that a vertex cannot exist in two sets at the same time if the condition is fulfilled, now note that there are no edges between elements of the same set because if this happens it would mean that they belong to different sets and it would be a contradiction, then the problem is to find the minimum number of vertices to remove such that in the remaining vertices there is no such triple of numbers ($x$, $y$, $z$). Now instead of minimizing the number of vertices to remove, let's try to maximize the number of vertices that will remain in the graph. Let us define the directed graph $G$ as the graph formed by $n$ vertices, and directed edges ($u$, $v$) such that $a_v|a_u$, now the problem is reduced to finding the maximum number of vertices such that in the graph formed among them, no vertex has ingoing edges and outgoing edges at the same time, formally for each vertex $x$ the following property must be kept $indegree_x = 0$ or $outdegree_x = 0$, in this way we guarantee that there is no triple ($x$, $y$, $z$) such that $a_x|a_y$, $a_x|a_z$ and $a_y|a_z$. Now let's define the graph $G'$ as a copy of the graph $G$. Formally for each directed edge ($u$, $v$) in the graph $G$ there is an directed edge ($u'$, $v'$) in the graph $G'$. On the other hand, let's define the graph $H = G + G'$ and we will also add new directed edges ($u'$, $u$), this graph $H$ is a $DAG$, it is easy to see that the edges always go from a vertex $u$ to a vertex $v$ only if $a_u > a_v$, except for the edges ($u'$, $u$), which in this case $a_{u'} = a_u$, these edges are the ones that connect $G'$ to $G$, but since they always go in one direction pointing towards $G$, the property of $DAG$ is still fulfilled. Now the only thing we have to do is find the largest antichain in the graph $H$, this can be done using the Dilworth's Theorem, modeling the problem as a bipartite matching, we can use some flow algorithm such as Dinic's Algorithm, or Hopcroft Karp's Algorithm, which is specific to find the maximum bipartite matching. First of all we realize that the graph $G$ is a special graph since if there is an indirect path from a vertex $u$ to a vertex $v$ then there is always a direct edge between them, this is true because if we have $3$ vertices $x$, $y$ and $z$ such that $a_x|a_y$ and $a_y|a_z$ then always $a_x|a_z$. With this we can say that two elements are not reachable with each other if and only if there are no edges between them. Now let's say that all the vertices in the graph $G$ are white and all the vertices in the graph $G'$ are black, let us denote $f(x)$ a function such that $f(u') = u$, where the vertex $u$ from the graph $G$ is the projection of the vertex $u'$ from the graph $G'$. Now let's divide the proof into two parts. Lemma 1: Every antichain of $H$ can be transformed into a valid set of vertices such that they form a bipartite graph. Proof of Lemma 1: Let's divide the antichain of $H$ into two sets, white vertices and black vertices, Let us define the set of white vertices as $W$ and the set of all black vertices as $B$, now we will create a set $S$ = {$f(x)$ | $x \\in B$}. It is easy to see that no element in $S$ belongs to $W$ since if this happens it would mean that there is an element $x$ such that $x$ belongs to $B$ and $f(x)$ belongs to $W$ and by the concept of antichain that would not be possible. It is also easy to see that the elements of the set $S$ are an antichain since the set $S$ is a projection of vertices from the set $B$ of the graph $G'$ on $G$. Now we have that there are no edges between the vertices of the set $S$ and there are no edges between the vertices of the set $W$, with this it is proved that the graph is bipartite. Lemma 2: Every valid set of vertices such that they form a bipartite graph can be transformed into an antichain of $H$. Proof of Lemma 2: Let us denote $f^{-1}(x)$ a function such that $f^{-1}(u) = u'$, where vertex $u$ from graph $G$ is the projection of vertex $u'$ from graph $G'$. Let us denote the set $A$ as all vertices that have $indegree$ greater than $0$ and $B$ to all vertices that have $outdegree$ greater than $0$, now we will create a set $C$ = {$f^{-1}(x)$ | $x \\in A$}, It is easy to see that set $B$ is an antichain since if one vertex has an edge to another vertex then some of them would have $indegree$ greater than $0$ and would contradict the definition of set $B$, we can also see that the elements in set $A$ are an antichain since all the elements have $outdegree = 0$ so no vertex point towards any other vertex, with this we can define that all the elements in $C$ are an antichain since they are a projection of vertices of the set $A$ from the graph $G$ on $G'$, Now we want to proof that the union of set $B$ and $C$ is an antichain, this is very simple to see since the vertices of set $B$ belong to $G$ and the vertices of $C$ belong to $G'$, therefore there is no edge from any vertex in $B$ to a vertex in $C$ since there are no edges from $G$ to $G'$. Now it only remains to proof that from set $C$ no vertex of set $B$ can be reached, this is proved taking into account that the vertices reachable from the set $C$ in the graph $G$ are the same that the vertices reachable from the set $A$ in the graph $G$, and as no vertex of $A$ has edges towards $B$, this cannot happen. Therefore the union of the sets $B$ and $C$ is an antichain of $H$. Then we can say that the two problems are equivalent and it is shown that finding the maximum antichain we obtain the largest bipartite graph. The graph $G$ contains $n$ vertices and around $n\\cdot log(n)$ edges (since the numbers $a_x$ are different and the sum of the divisors from $1$ to $n$ is around $n\\cdot log(n)$). The graph $G'$ is a duplicate of $G$ then we would have $n\\cdot log(n)\\cdot2 + n$ edges and $2\\cdot n$ vertices, if we use the Hopcroft Karp algorithm we would obtain a time complexity of $O(n\\cdot log(n)\\cdot sqrt(n))$ and a space complexity of $O(n\\cdot log(n))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstruct HOPCROFT_KARP\n{\n    int n, m;\n    vector<vector<int>> adj;\n    vector<int> mu, mv, level, que;\n\n    HOPCROFT_KARP(int n, int m) : n(n), m(m), adj(n), mu(n, -1), mv(m, -1), level(n), que(n) {}\n\n    void add_edge(int u, int v)\n    {\n        adj[u].push_back(v);\n    }\n\n    void bfs()\n    {\n        int qf = 0, qt = 0;\n        for(int u = 0 ; u < n ; ++u)\n        {\n            if(mu[u] == -1)que[qt++] = u, level[u] = 0;\n            else level[u] = -1;\n        }\n        for( ; qf < qt ; ++qf)\n        {\n            int u = que[qf];\n            for(auto w : adj[u])\n            {\n                int v = mv[w];\n                if(v != -1 && level[v] == -1)\n                    que[qt++] = v, level[v] = level[u] + 1;\n            }\n        }\n    }\n\n    bool dfs(int u)\n    {\n        for(auto w : adj[u])\n        {\n            int v = mv[w];\n            if(v == -1 || (level[v] == level[u] + 1 && dfs(v)))\n                return mu[u] = w, mv[w] = u, true;\n        }\n        return false;\n    }\n\n    int max_matching()\n    {\n        int match = 0;\n        for(int c = 1 ; bfs(), c ; match += c)\n            for(int u = c = 0 ; u < n ; ++u)\n                if(mu[u] == -1)\n                    c += dfs(u);\n        return match;\n    }\n\n    pair<vector<int>, vector<int>> min_vertex_cover()\n    {\n        max_matching();\n        vector<int> L, R, inR(m);\n        for(int u = 0 ; u < n ; ++u)\n        {\n            if(level[u] == -1)L.push_back(u);\n            else if(mu[u] != -1)inR[mu[u]] = true;\n        }\n        for(int v = 0 ; v < m ; ++v)\n            if(inR[v])R.push_back(v);\n        return { L, R };\n    }\n};\n\nconst int MAXN = 5e4 + 100;\n\nint arr[MAXN];\nvector<int> dv[MAXN];\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    for(int i = 1 ; i < MAXN ; i++)\n    {\n        for(int j = i*2 ; j < MAXN ; j+=i)\n        {\n            dv[j].push_back(i);\n        }\n    }\n\n    for(int i = 0 ; i < MAXN ; i++)\n    {\n        arr[i] = -1;\n    }\n\n    int T;\n    cin >> T;\n\n    while(T--)\n    {\n        int N;\n        cin >> N;\n\n        vector<int> vect;\n\n        for(int i = 0 ; i < N ; i++)\n        {\n            int n;\n            cin >> n;\n            vect.push_back(n);\n            arr[n] = i;\n        }\n\n        vector<pair<int,int>> edge;\n\n        for(int i = 0 ; i < N ; i++)\n        {\n            for(auto x : dv[vect[i]])\n            {\n                if(arr[x] != -1)\n                {\n                    edge.push_back({i, arr[x]});\n                }\n            }\n        }\n\n        for(auto x : vect)\n        {\n            arr[x] = -1;\n        }\n\n        HOPCROFT_KARP HK(2*N,2*N);\n\n        for(auto x : edge)\n        {\n            int i = x.first;\n            int j = x.second;\n            HK.add_edge(i,j);\n            HK.add_edge(i+N,j+N);\n        }\n\n        for(int i = 0 ; i < N ; i++)\n        {\n            HK.add_edge(i+N,i);\n        }\n\n        cout << HK.max_matching()-N << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "flows",
      "graph matchings",
      "graphs",
      "number theory"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1631",
    "index": "A",
    "title": "Min Max Swap",
    "statement": "You are given two arrays $a$ and $b$ of $n$ positive integers each. You can apply the following operation to them any number of times:\n\n- Select an index $i$ ($1\\leq i\\leq n$) and swap $a_i$ with $b_i$ (i. e. $a_i$ becomes $b_i$ and vice versa).\n\nFind the \\textbf{minimum} possible value of $\\max(a_1, a_2, \\ldots, a_n) \\cdot \\max(b_1, b_2, \\ldots, b_n)$ you can get after applying such operation any number of times (possibly zero).",
    "tutorial": "Think about how $max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$ will contribute to the answer. The maximum of one array is always $max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$. How should you minimize then? Let $m_1 = \\max(a_1, a_2, ..., a_n, b_1, b_2, ..., b_n)$. The answer will always be $m_1 \\cdot m_2$ where $m_2$ is the maximum of the array that does not contain $m_1$. Since $m_1$ is fixed, the problem can be reduced to minimize $m_2$, that is, minimize the maximum of the array that does not contain the global maximum. WLOG assume that the global maximum will be in the array $b$, we can swap elements at each index $x$ such that $a_x > b_x$, ending with $a_i \\leq b_i$ for all $i$. It can be shown that the maximum of array $a$ is minimized in this way. Time complexity: $O(n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint calc_max(vector<int> a){\n    int res = 0;\n    for( auto i : a )\n        res = max( res , i );\n    return res;\n}\n \nint main(){\n    int tc;\n    cin >> tc;\n    while( tc-- ){\n        int n;\n        cin >> n;\n \n        vector<int> a(n), b(n);\n        for( auto &i : a )\n            cin >> i;\n        for( auto &i : b )\n            cin >> i;\n \n        for(int i=0; i<n; i++)\n            if( a[i] > b[i] )\n                swap( a[i] , b[i] );\n \n        cout << calc_max(a) * calc_max(b) << '\\n';\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1631",
    "index": "B",
    "title": "Fun with Even Subarrays",
    "statement": "You are given an array $a$ of $n$ elements. You can apply the following operation to it any number of times:\n\n- Select some subarray from $a$ of even size $2k$ that begins at position $l$ ($1\\le l \\le l+2\\cdot{k}-1\\le n$, $k \\ge 1$) and for each $i$ between $0$ and $k-1$ (inclusive), assign the value $a_{l+k+i}$ to $a_{l+i}$.\n\nFor example, if $a = [2, 1, 3, 4, 5, 3]$, then choose $l = 1$ and $k = 2$, applying this operation the array will become $a = [3, 4, 3, 4, 5, 3]$.\n\nFind the minimum number of operations (possibly zero) needed to make all the elements of the array equal.",
    "tutorial": "It is not possible to modify $a_n$ using the given operation. Think about the leftmost $x$ such that $a_x \\neq a_n$. For simplicity, let $b_1, b_2, ..., b_n = a_n, a_{n-1}, ..., a_1$ (let $b$ be $a$ reversed). The operation transforms to select a subarray $[l, r]$ of length $2\\cdot{k}$, so $k = \\frac{r-l+1}{2}$, then for all $i$ such that $0 \\leq i < k$, set $b_{l+k+i} = b_{l+i}$. $b_1$ can not be changed with the given operation. That reduces the problem to make all elements equal to $b_1$. Let $x$ be the rightmost index such that for all $1 \\leq i \\leq x$, $b_i = b_1$ holds. The problem will be solved when $x = n$. If an operation is applied with $l + k > x + 1$, $b_{x+1}$ will not change and $x$ will remain the same. The largest range with $l + k \\leq x + 1$ is $[1, 2\\cdot{x}]$, applying an operation to it will lead to $b_{x+1}, b_{x+2}, ..., b_{2\\cdot{x}} = b_1, b_2, ..., b_x$, so $x$ will become at least $2\\cdot{x}$ and there is not any other range that will lead to a bigger value of $x$. If $2\\cdot{x} > n$, it is possible to apply the operation on $[x-(n-x)+1,n]$, after applying it $b_{x+1}, ..., b_n = b_{x-(n-x)+1}, ..., b_x$ and all elements will become equal. The problem can now be solved by repeatedly finding $x$ and applying the operation on $[1, 2\\cdot{x}]$ or on $[x-(n-x)+1,n]$ if $2\\cdot{x} > n$. Since $x$ will become at least $2\\cdot{x}$ in each operation but the last one, the naive implementation will take $O(n\\log{n})$, however, it is easy to implement it in $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    int tc;\n    cin >> tc;\n    while(tc--)\n    {\n        int n;\n        cin >> n;\n\n        vector<int> a(n+1);\n        for(int i=1; i<=n; i++)\n            cin >> a[i];\n\n        vector<int> b = a;\n        reverse(b.begin()+1,b.end());\n\n        int ans = 0, x = 1;\n\n        while( x < n )\n        {\n            if( b[x+1] == b[1] ){\n                x ++;\n                continue;\n            }\n            ans ++;\n            x *= 2;\n        }\n\n        cout << ans << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1632",
    "index": "A",
    "title": "ABC",
    "statement": "Recently, the students of School 179 have developed a unique algorithm, which takes in a binary string $s$ as input. However, they soon found out that if some substring $t$ of $s$ is a palindrome of length greater than 1, the algorithm will work incorrectly. Can the students somehow reorder the characters of $s$ so that the algorithm will work correctly on the string?\n\nA binary string is a string where each character is either 0 or 1.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nA palindrome is a string that reads the same backwards as forwards.",
    "tutorial": "Only a few strings have the answer \"YES\". For $n \\ge 3$, the answer is \"NO\". Let $n \\ge 3$ and the resulting string be $a$. For there to be no palindromes of length greater than $1$, at least all of these inequalities must be true: $a_1 \\neq a_2$, $a_2 \\neq a_3$, and $a_1 \\neq a_3$. Since our string is binary, this is impossible, so the answer is \"NO\". For $n \\le 2$, there are 4 strings that have the answer \"YES\": $0$, $1$, $01$, and $10$; as well as 2 strings that have the answer \"NO\": $00$ and $11$. Time complexity: $O(n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n \nint main() {\n    int t;\n    cin >> t;\n    while(t--) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        if(n > 2 || s == \"11\" || s == \"00\") {\n            cout << \"NO\\n\";\n        } else {\n            cout << \"YES\\n\";\n        }\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1632",
    "index": "B",
    "title": "Roof Construction",
    "statement": "It has finally been decided to build a roof over the football field in School 179. Its construction will require placing $n$ consecutive vertical pillars. Furthermore, the headmaster wants the heights of all the pillars to form a permutation $p$ of integers from $0$ to $n - 1$, where $p_i$ is the height of the $i$-th pillar from the left $(1 \\le i \\le n)$.\n\nAs the chief, you know that the cost of construction of consecutive pillars is equal to \\textbf{the maximum value of the bitwise XOR} of heights of all pairs of adjacent pillars. In other words, the cost of construction is equal to $\\max\\limits_{1 \\le i \\le n - 1}{p_i \\oplus p_{i + 1}}$, where $\\oplus$ denotes the bitwise XOR operation.\n\nFind any sequence of pillar heights $p$ of length $n$ with the smallest construction cost.\n\nIn this problem, a permutation is an array consisting of $n$ distinct integers from $0$ to $n - 1$ in arbitrary order. For example, $[2,3,1,0,4]$ is a permutation, but $[1,0,1]$ is not a permutation ($1$ appears twice in the array) and $[1,0,3]$ is also not a permutation ($n=3$, but $3$ is in the array).",
    "tutorial": "The cost of construction is a power of two. The cost of construction is $2 ^ k$, where $k$ is the highest set bit in $n - 1$. Let $k$ be the highest set bit in $n - 1$. There will always be a pair of adjacent elements where one of them has the $k$-th bit set and the other one doesn't, so the cost is at least $2^k$. A simple construction that reaches it is $2^k - 1$, $2^k - 2$, $\\ldots$, $0$, $2^k$, $2^k + 1$, $\\ldots$, $n - 1$. Time complexity: $O(n)$ Bonus: count the number of permutations with the minimum cost.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n \nint main() {\n    int t;\n    cin >> t;\n    while(t--) {\n        int n;\n        cin >> n;\n        int k = 0;\n        while((1 << (k + 1)) <= n - 1) ++k; \n        for(int i = (1 << k) - 1; i >= 0; i--) {\n            cout << i << ' ';\n        }\n        for(int i = (1 << k); i < n; i++) {\n            cout << i << ' ';\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1632",
    "index": "C",
    "title": "Strange Test",
    "statement": "Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich.\n\nIgor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $a$ and $b$ ($a < b$). After that, the student can apply any of the following operations any number of times:\n\n- $a := a + 1$ (increase $a$ by $1$),\n- $b := b + 1$ (increase $b$ by $1$),\n- $a := a \\ | \\ b$ (replace $a$ with the bitwise OR of $a$ and $b$).\n\nTo get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $a$ and $b$ equal.\n\nIgor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $a$ equal to $b$.",
    "tutorial": "It is optimal to apply the third operation at most once. It is optimal to apply the third operation at most once, because is does not decrease $a$ and always makes $b \\le a$. This means that after we use it, we can only apply the second operation. If we don't apply the third operation, the answer is $b - a$. Suppose we do apply it. Before that, we used the first and second operations some number of times, let the resulting values of $a$ and $b$ be $a'$ and $b'$ respectively $(a \\le a', b \\le b')$. The answer in this case will be $(a' - a) + (b' - b) + ((a' \\ | \\ b') - b') + 1$ $=$ $a' + (a' \\ | \\ b') + (1 - a - b)$. This is equivalent to minimizing $a' + (a' \\ | \\ b')$, since $(1 - a - b)$ is constant. To do that, we can iterate $a'$ from $a$ to $b$. For a fixed $a'$, we have to minimize $a' \\ | \\ b'$, the optimal $b'$ can be constructed like this: Set $b'$ to zero and iterate over bits from highest to lowest. There are 4 cases: If current bit of $a'$ is $0$ and $b$ is $1$, set the current bit of $b'$ to $1$. If current bit of $a'$ is $0$ and $b$ is $0$, set the current bit of $b'$ to $0$. If current bit of $a'$ is $1$ and $b$ is $1$, set the current bit of $b'$ to $1$. If current bit of $a'$ is $1$ and $b$ is $0$, set the current bit of $b'$ to $1$ and stop. This works in $O(\\log b)$ and can also be sped up to $O(1)$ using bit manipulation. Time complexity: $O(b)$ or $O(b \\log b)$ Bonus 1: solve the problem in $O(\\log b)$ or faster. Bonus 2: prove that is optimal to have either $a' = a$ or $b' = b$.",
    "code": "for _ in range(int(input())):\n    a, b = map(int, input().split())\n    ans = b - a\n    for a1 in range(a, b):\n        b1 = 0\n        for i in range(21, -1, -1):\n            if (b >> i) & 1:\n                b1 ^= (1 << i)\n            else:\n                if (a1 >> i) & 1:\n                    b1 ^= (1 << i)\n                    break\n        ans = min(ans, a1 - a - b + (a1 | b1) + 1);\n    print(ans)",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "dp",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1632",
    "index": "D",
    "title": "New Year Concert",
    "statement": "New Year is just around the corner, which means that in School 179, preparations for the concert are in full swing.\n\nThere are $n$ classes in the school, numbered from $1$ to $n$, the $i$-th class has prepared a scene of length $a_i$ minutes.\n\nAs the main one responsible for holding the concert, Idnar knows that if a concert has $k$ scenes of lengths $b_1$, $b_2$, $\\ldots$, $b_k$ minutes, then the audience will get bored if there exist two integers $l$ and $r$ such that $1 \\le l \\le r \\le k$ and $\\gcd(b_l, b_{l + 1}, \\ldots, b_{r - 1}, b_r) = r - l + 1$, where $\\gcd(b_l, b_{l + 1}, \\ldots, b_{r - 1}, b_r)$ is equal to the greatest common divisor (GCD) of the numbers $b_l$, $b_{l + 1}$, $\\ldots$, $b_{r - 1}$, $b_r$.\n\nTo avoid boring the audience, Idnar can ask any number of times (possibly zero) for the $t$-th class ($1 \\le t \\le k$) to make a new scene $d$ minutes in length, where $d$ can be \\textbf{any positive integer}. Thus, after this operation, $b_t$ is equal to $d$. Note that $t$ and $d$ can be different for each operation.\n\nFor a sequence of scene lengths $b_1$, $b_2$, $\\ldots$, $b_{k}$, let $f(b)$ be the minimum number of classes Idnar has to ask to change their scene if he wants to avoid boring the audience.\n\nIdnar hasn't decided which scenes will be allowed for the concert, so he wants to know the value of $f$ for each non-empty prefix of $a$. In other words, Idnar wants to know the values of $f(a_1)$, $f(a_1$,$a_2)$, $\\ldots$, $f(a_1$,$a_2$,$\\ldots$,$a_n)$.",
    "tutorial": "Let's call a segment $[l, r]$ bad if $\\gcd(a_l \\ldots a_r) = r - l + 1$. There at most $n$ bad segments. For a fixed $l$, as $r$ increases, $\\gcd(a_l \\ldots a_r)$ does not increase. Suppose you change $a_i$ into a big prime. How does this affect the bad segments? Read the hints above. Let's find all of the bad segments. For a fixed $l$, let's find the largest $r$ that has $\\gcd(a_l \\ldots a_r) \\ge r - l + 1$. This can be done with binary search and a sparse table / segment tree. If $\\gcd(a_l \\ldots a_r) = r - l + 1$, then the segment $[l, r]$ is bad. If we change $a_i$ into a big prime, no new bad segments will appear. And all bad segments that have $i$ inside of them will disappear. So we have to find the minimum number of points to cover all of them. This is a standard problem, which can be solved greedily: choose the segment with the smallest $r$, delete all segments that have $r$ in them, and repeat. In our case, this is easy to do because our segments are not nested. Time complexity: $O(n \\log n \\log A)$ with a sparse table, where $A$ is the maximum value of $a_i$. Notes: There are many different modifications to the previous solution, some of them use two pointers (since segments are not nested) and some of them update the answer on the fly while searching for the bad segments. Using a segment tree and two pointers you can get the complexity $O(n (\\log n + \\log A))$. You can also use the fact that for a prefix, there at most $O(\\log A)$ different suffix $\\gcd$ values. This leads to another way to find the bad segments.",
    "code": "from math import gcd\n \n \nn = int(input())\na = list(map(int, input().split()))\n \n \nt = [0] * (4 * n)\ndef build(v, tl, tr):\n\tglobal t\n\tif tl == tr - 1:\n\t\tt[v] = a[tl]\n\telse:\n\t\ttm = (tl + tr) // 2\n\t\tbuild(2*v + 1, tl, tm)\n\t\tbuild(2*v + 2, tm, tr)\n\t\tt[v] = gcd(t[2*v + 1], t[2*v + 2])\n \n \ndef query(v, tl, tr, l, r):\n\tif l >= r:\n\t\treturn 0\n\tif tl == l and tr == r:\n\t\treturn t[v]\n\ttm = (tl + tr) // 2\n\tr1 = query(2*v + 1, tl, tm, l, min(tm, r))\n\tr2 = query(2*v + 2, tm, tr, max(l, tm), r)\n\treturn gcd(r1, r2)\n \n \nbuild(0, 0, n)\ncur_l = 0\nans = 0\nres = []\nfor i in range(n):\n\twhile query(0, 0, n, cur_l, i + 1) < i + 1 - cur_l:\n\t\tcur_l += 1\n \n\tif query(0, 0, n, cur_l, i + 1) == i + 1 - cur_l:\n\t\tans += 1\n\t\tcur_l = i + 1\n\tres.append(ans)\n\t\nprint(' '.join(map(str, res)))",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1632",
    "index": "E2",
    "title": "Distance Tree (hard version)",
    "statement": "\\textbf{This version of the problem differs from the previous one only in the constraint on $n$}.\n\nA tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.\n\nYou are given a weighted tree with $n$ vertices, each edge has a weight of $1$. Denote $d(v)$ as the distance between vertex $1$ and vertex $v$.\n\nLet $f(x)$ be the minimum possible value of $\\max\\limits_{1 \\leq v \\leq n} \\ {d(v)}$ if you can temporarily add an edge with weight $x$ between any two vertices $a$ and $b$ $(1 \\le a, b \\le n)$. Note that after this operation, the graph is no longer a tree.\n\nFor each integer $x$ from $1$ to $n$, find $f(x)$.",
    "tutorial": "It is optimal to add edges of type $(1, v)$. Try to check if for a fixed $x$ the answer is at most $ans$. For a fixed $x$ and answer $ans$, find the distance between nodes that have $depth_v > ans$. For each node, find two children with the deepest subtrees. Read the hints above. Let $f_{ans}$ be the maximum distance between two nodes that have $depth_v > ans$. If for some $x$ the answer is at most $ans$, then either $ans \\ge depth$ or $\\lceil \\frac{f_{ans}}{2} \\rceil + x \\le ans$, since we can add an edge $(1, u)$ where $u$ is in the middle of the path connecting the two farthest apart nodes with $depth_v > ans$. Since $f_{ans}$ decreases as $ans$ increases, we can use binary search. Also note that we can use two pointers and increase $ans$ as we increase $x$. How to calculate $f_{ans}$? Let's find for each node its two children with the deepest subtrees. Let $a_v$ and $b_v$ be the depths of their subtrees ($a_v \\ge b_v$). If there are not enough children, set this values to $depth_v$. If $b_v > 0$, do $f_{b_v-1} := \\max(f_{b_v - 1}, a_v + b_v - 2 \\cdot depth_v)$. After this, iterate $i$ from $n - 2$ to $0$ and do $f_i = \\max(f_i, f_{i + 1})$. Time complexity: $O(n)$ or $O(n \\log n)$ with binary search. Note: To solve E1, it is enough to calculate $f_{ans}$ in $O(n)$ or $O(n \\log n)$ for each $ans$. One way to do that is to find the diameter of the resulting tree after repeatedly deleting any leaf that has $depth_v \\le ans$ ($1$ is also considered a leaf).",
    "code": "import sys\nfrom types import GeneratorType\n \ng = []\nd = []\nn = 0\t\n \ninp = list(sys.stdin)\n \n \ndef dfs_from_hell():\n\tst = [[], [0, 0, 0, -1, 0, 0]]\n\twhile len(st) > 1:\n\t\tif len(st[-1]) == 7:\n\t\t\tif st[-1][-1] > st[-1][1]:\n\t\t\t\tst[-1][2] = st[-1][1]\n\t\t\t\tst[-1][1] = st[-1][-1]\n\t\t\telif st[-1][-1] > st[-1][2]:\n\t\t\t\tst[-1][2] = st[-1][-1]\n\t\t\tdel st[-1][-1]\n\t\t\tcontinue\n\t\tif len(g[st[-1][0]]) == st[-1][5]:\n\t\t\ti = min(st[-1][1], st[-1][2]) - 1\n\t\t\tif i >= 0:\n\t\t\t\td[i] = max(d[i], st[-1][1] + st[-1][2] - 2 * st[-1][4] + 1)\n\t\t\tst[-2].append(st[-1][1])\n\t\t\tdel st[-1]\n\t\t\tcontinue\n\t\tif g[st[-1][0]][st[-1][5]] == st[-1][3]:\n\t\t\tst[-1][5] += 1\n\t\t\tcontinue\n\t\tst.append([g[st[-1][0]][st[-1][5]], st[-1][4] + 1, st[-1][4] + 1, st[-1][0], st[-1][4] + 1, 0])\n\t\tst[-2][5] += 1\n\treturn st[0][0]\n \n \nci = 1\ndef solve():\n\tglobal n, g, d, ci\n\tn = int(inp[ci])\n\tci += 1\n\tg = [[] for _ in range(n)]\n\td = [0 for _ in range(n)]\n\t\n\tfor i in range(n - 1):\n\t\ta, b = map(int, inp[ci].split())\n\t\tci += 1\n\t\ta -= 1\n\t\tb -= 1\n\t\tg[a].append(b);\n\t\tg[b].append(a);\n\t\n\tm_ans = dfs_from_hell()\n\tfor i in range(n - 2, -1, -1):\n\t\t d[i] = max(d[i], d[i + 1])\n\t\n\tans = 0\n\tres = []\n\tfor k in range(1, n + 1):\n\t\twhile ans < m_ans and d[ans] // 2 + k > ans:\n\t\t\tans += 1\n\t\tres.append(str(ans))\n\tprint(' '.join(res))\n \n \nfor _ in range(int(inp[0])):\n\tsolve()",
    "tags": [
      "binary search",
      "dfs and similar",
      "shortest paths",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1633",
    "index": "A",
    "title": "Div. 7",
    "statement": "You are given an integer $n$. You have to change the minimum number of digits in it in such a way that the resulting number \\textbf{does not have any leading zeroes} and \\textbf{is divisible by $7$}.\n\nIf there are multiple ways to do it, print any of them. If the given number is already divisible by $7$, leave it unchanged.",
    "tutorial": "A lot of different solutions can be written in this problem. The model solution relies on the fact that every $7$-th integer is divisible by $7$, and it means that there is always a way to change the last digit of $n$ (or leave it unchanged) so that the result is divisible by $7$. So, if $n$ is already divisible by $7$, we just print it, otherwise we change its last digit using some formulas or iteration on its value from $0$ to $9$.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    if n % 7 == 0:\n        print(n)\n    else:\n        ans = -1\n        for j in range(10):\n            if (n - n % 10 + j) % 7 == 0:\n                ans = n - n % 10 + j\n        print(ans)",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "1633",
    "index": "B",
    "title": "Minority",
    "statement": "You are given a string $s$, consisting only of characters '0' and '1'.\n\nYou have to choose a contiguous substring of $s$ and remove all occurrences of the character, which is a strict minority in it, from the substring.\n\nThat is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.\n\nYou have to apply the operation \\textbf{exactly once}. What is the maximum amount of characters that can be removed?",
    "tutorial": "Let's try to estimate the maximum possible answer. Best case, you will be able to remove either all zeros or all ones from the entire string. Whichever has the least occurrences, can be the answer. If the amounts of zeros and ones in the string are different, this bound is actually easy to reach: just choose the substring that is the entire string. If the amounts are the same, the bound is impossible to reach. Choosing the entire string will do nothing, and asking a smaller substring will decrease the answer. The smallest we can decrease the answer by is $1$. If you choose the substring that is the string without the last character, you will decrease one of the amounts by one. That will make the amounts different, and the bound will be reached. Overall complexity: $O(|s|)$ per testcase.",
    "code": "for _ in range(int(input())):\n    s = input()\n    print(min((len(s) - 1) // 2, s.count('0'), s.count('1')))",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1633",
    "index": "C",
    "title": "Kill the Monster",
    "statement": "Monocarp is playing a computer game. In this game, his character fights different monsters.\n\nA fight between a character and a monster goes as follows. Suppose the character initially has health $h_C$ and attack $d_C$; the monster initially has health $h_M$ and attack $d_M$. The fight consists of several steps:\n\n- the character attacks the monster, decreasing the monster's health by $d_C$;\n- the monster attacks the character, decreasing the character's health by $d_M$;\n- the character attacks the monster, decreasing the monster's health by $d_C$;\n- the monster attacks the character, decreasing the character's health by $d_M$;\n- and so on, until the end of the fight.\n\nThe fight ends when someone's health becomes non-positive (i. e. $0$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.\n\nMonocarp's character currently has health equal to $h_C$ and attack equal to $d_C$. He wants to slay a monster with health equal to $h_M$ and attack equal to $d_M$. Before the fight, Monocarp can spend up to $k$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $w$, and each armor upgrade increases the character's health by $a$.\n\nCan Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?",
    "tutorial": "First of all, let's understand how to solve the problem without upgrades. To do this, it is enough to compare two numbers: $\\left\\lceil\\frac{h_M}{d_C}\\right\\rceil$ and $\\left\\lceil\\frac{h_C}{d_M}\\right\\rceil$ - the number of attacks that the character needs to kill the monster and the number of attacks that the monster needs to kill the character, respectively. So, if the first number is not greater than the second number, then the character wins. Note that the number of coins is not very large, which means we can iterate over the number of coins that we will spend on weapon upgrades, and the remaining coins will be spent on armor upgrades. After that, we can use the formula described above to check whether the character will win. The complexity of the solution is $O(k)$.",
    "code": "for _ in range(int(input())):\n    hc, dc = map(int, input().split())\n    hm, dm = map(int, input().split())\n    k, w, a = map(int, input().split())\n    for i in range(k + 1):\n        nhc = hc + i * a\n        ndc = dc + (k - i) * w\n        if (hm + ndc - 1) // ndc <= (nhc + dm - 1) // dm:\n            print(\"YES\")\n            break\n    else:\n        print(\"NO\")",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1633",
    "index": "D",
    "title": "Make Them Equal",
    "statement": "You have an array of integers $a$ of size $n$. Initially, all elements of the array are equal to $1$. You can perform the following operation: choose two integers $i$ ($1 \\le i \\le n$) and $x$ ($x > 0$), and then increase the value of $a_i$ by $\\left\\lfloor\\frac{a_i}{x}\\right\\rfloor$ (i.e. make $a_i = a_i + \\left\\lfloor\\frac{a_i}{x}\\right\\rfloor$).\n\nAfter performing all operations, you will receive $c_i$ coins for all such $i$ that $a_i = b_i$.\n\nYour task is to determine the maximum number of coins that you can receive by performing no more than $k$ operations.",
    "tutorial": "Let's calculate $d_i$ - the minimum number of operations to get the number $i$ from $1$. To do this, it is enough to use BFS or dynamic programming. Edges in the graph (transitions in dynamic programming) have the form $\\left(i, i + \\left\\lfloor\\frac{i}{x}\\right\\rfloor\\right)$ for all $1 \\le x \\le i$. Now the problem itself can be reduced to a knapsack problem: there are $n$ items, $i$-th item weighs $d_{b_i}$ and costs $c_i$, you have to find a set of items with the total weight of no more than $k$ of the maximum cost. This is a standard problem that can be solved in $O(nk)$, but it is too slow (although some participants passed all the tests with such a solution). However, we can notice that the values of $d_i$ should not grow too fast, namely, the maximum value of $d_i$ for $1 \\le i \\le 10^3$ does not exceed $12$. This means that the maximum possible weight is no more than $12n$, and we can limit $k$ to this number (i. e. make $k = \\min(k, 12n)$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1001;\n\nint main() {\n  vector<int> d(N, N);\n  d[1] = 0;\n  for (int i = 1; i < N; ++i) {\n    for (int x = 1; x <= i; ++x) {\n      int j = i + i / x;\n      if (j < N) d[j] = min(d[j], d[i] + 1);\n    }\n  }\n  \n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<int> b(n), c(n);\n    for (int &x : b) cin >> x;\n    for (int &x : c) cin >> x;\n    int sum = 0;\n    for (int x : b) sum += d[x];\n    k = min(k, sum);\n    vector<int> dp(k + 1, 0);\n    for (int i = 0; i < n; ++i) {\n      for (int j = k - d[b[i]]; j >= 0; j--) {\n        dp[j + d[b[i]]] = max(dp[j + d[b[i]]], dp[j] + c[i]);\n      }\n    }\n    cout << *max_element(dp.begin(), dp.end()) << '\\n';\n  }\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1633",
    "index": "E",
    "title": "Spanning Tree Queries",
    "statement": "You are given a connected weighted undirected graph, consisting of $n$ vertices and $m$ edges.\n\nYou are asked $k$ queries about it. Each query consists of a single integer $x$. For each query, you select a spanning tree in the graph. Let the weights of its edges be $w_1, w_2, \\dots, w_{n-1}$. The cost of a spanning tree is $\\sum \\limits_{i=1}^{n-1} |w_i - x|$ (the sum of absolute differences between the weights and $x$). The answer to a query is the lowest cost of a spanning tree.\n\nThe queries are given in a compressed format. The first $p$ $(1 \\le p \\le k)$ queries $q_1, q_2, \\dots, q_p$ are provided explicitly. For queries from $p+1$ to $k$, $q_j = (q_{j-1} \\cdot a + b) \\mod c$.\n\nPrint the xor of answers to all queries.",
    "tutorial": "Consider a naive solution using Kruskal's algorithm for finding MST. Given some $x$, you arrange the edges in the increasing order of $|w_i - x|$ and process them one by one. Look closely at the arrangements. At $x=0$ the edges are sorted by $w_i$. How does the arrangement change when $x$ increases? Well, some edges swap places. Consider a pair of edges with different weights $w_1$ and $w_2$ ($w_1 < w_2$). Edge $1$ will go before edge $2$ in the arrangement as long as $x$ is closer to $w_1$ than $w_2$. So for all $x$ up to $\\frac{w_1 + w_2}{2}$, edge $1$ goes before edge $2$. And for all $x$ from $\\frac{w_1 + w_2}{2}$ onwards, edge $2$ goes before edge $1$. This tells us that every pair of edge with different weights will swap exactly once. So there will be at most $O(m^2)$ swaps. Which is at most $O(m^2)$ different arrangements. Each of them corresponds to some range of $x$'s. We can extract the ranges of $x$'s for all arrangements and calculate MST at the start of each range. We can also find the arrangement that corresponds to some $x$ from a query with a binary search. However, only knowing the weight of the MST at the start of the range is not enough. The weights of edges change later in the range, and we can't predict how. Some edges have their weight increasing, some decreasing. First, let's add more ranges. We want each edge to behave the same way on the entire range: either increase all the way or decrease all the way. If we also add $x=w_i$ for all $i$ into the MST calculation, this will hold. Second, let's store another value for each range: the number of edges that have their weight increasing on it. With that, we can easily recalculate the change in the cost of the spanning tree. The TL should be free enough for you to sort the edges for each MST calculation, resulting in $O(m^2 (m \\log m + n \\log n) + k \\log m)$ solution. You can also optimize the first part to $O(m^3)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct edge{\n\tint v, u, w;\n};\n\nvector<int> pr, rk;\n\nint getp(int a){\n\treturn a == pr[a] ? a : pr[a] = getp(pr[a]);\n}\n\nbool unite(int a, int b){\n\ta = getp(a), b = getp(b);\n\tif (a == b) return false;\n\tif (rk[a] < rk[b]) swap(a, b);\n\trk[a] += rk[b];\n\tpr[b] = a;\n\treturn true;\n}\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tpr.resize(n);\n\trk.resize(n);\n\tvector<edge> es(m);\n\tforn(i, m){\n\t\tscanf(\"%d%d%d\", &es[i].v, &es[i].u, &es[i].w);\n\t\t--es[i].v, --es[i].u;\n\t\tes[i].w *= 2;\n\t}\n\tvector<int> ev(1, 0);\n\tforn(i, m) forn(j, i + 1) ev.push_back((es[i].w + es[j].w) / 2);\n\tsort(ev.begin(), ev.end());\n\tev.resize(unique(ev.begin(), ev.end()) - ev.begin());\n\tvector<long long> base;\n\tvector<int> cnt;\n\tfor (int x : ev){\n\t\tsort(es.begin(), es.end(), [&x](const edge &a, const edge &b){\n\t\t\tint wa = abs(a.w - x);\n\t\t\tint wb = abs(b.w - x);\n\t\t\tif (wa != wb) return wa < wb;\n\t\t\treturn a.w > b.w;\n\t\t});\n\t\tforn(i, n) pr[i] = i, rk[i] = 1;\n\t\tlong long cur_base = 0;\n\t\tint cur_cnt = 0;\n\t\tfor (const auto &e : es) if (unite(e.v, e.u)){\n\t\t\tcur_base += abs(e.w - x);\n\t\t\tcur_cnt += x < e.w;\n\t\t}\n\t\tbase.push_back(cur_base);\n\t\tcnt.push_back(cur_cnt);\n\t}\n\tint p, k, a, b, c;\n\tscanf(\"%d%d%d%d%d\", &p, &k, &a, &b, &c);\n\tint x = 0;\n\tlong long ans = 0;\n\tforn(q, k){\n\t\tif (q < p) scanf(\"%d\", &x);\n\t\telse x = (x * 1ll * a + b) % c;\n\t\tint y = upper_bound(ev.begin(), ev.end(), 2 * x) - ev.begin() - 1;\n\t\tans ^= (base[y] + (n - 1 - 2 * cnt[y]) * 1ll * (2 * x - ev[y])) / 2;\n\t}\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "math",
      "sortings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1633",
    "index": "F",
    "title": "Perfect Matching",
    "statement": "You are given a tree consisting of $n$ vertices (numbered from $1$ to $n$) and $n-1$ edges (numbered from $1$ to $n-1$). Initially, all vertices except vertex $1$ are inactive.\n\nYou have to process queries of three types:\n\n- $1$ $v$ — activate the vertex $v$. It is guaranteed that the vertex $v$ is inactive before this query, and one of its neighbors is active. After activating the vertex, you have to choose a subset of edges of the tree such that each \\textbf{active} vertex is incident to \\textbf{exactly one} chosen edge, and each \\textbf{inactive} vertex is not incident to any of the chosen edges — in other words, this subset should represent a perfect matching on the active part of the tree. If any such subset of edges exists, print the sum of indices of edges in it; otherwise, print $0$.\n- $2$ — queries of this type will be asked only right after a query of type $1$, and there will be \\textbf{at most $10$} such queries. If your answer to the previous query was $0$, simply print $0$; otherwise, print the subset of edges for the previous query as follows: first, print the number of edges in the subset, then print the indices of the chosen edges \\textbf{in ascending order}. The sum of indices should be equal to your answer to the previous query.\n- $3$ — terminate the program.\n\nNote that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.",
    "tutorial": "Let's root the tree at vertex $1$ and try to analyze when a tree contains a perfect matching. If we want to find the maximum matching in a tree, we can use some greedy approaches like \"take a leaf of the tree, match it with its parent and remove both vertices, repeat this process until only isolated vertices remain\". If we are interested in a perfect matching, then this process should eliminate all of the vertices. Let's modify this process a bit by always picking the deepest leaf. If there exists a perfect matching, picking the deepest leaf will ensure that the tree always remains a tree and doesn't fall apart, i. e. there will always be one connected component. It means that when we remove the leaf with its parent, this leaf is the only descendant of its parent. It's easy to see that whenever we remove a pair of vertices in this process, for each remaining vertex, the number of its descendants is either left unchanged or decreased by $2$. It means that if a vertex has an even number of descendants, it will have an even number of descendants until it is removed, and the same for odd number of descendants. Let's call the vertices with even number of descendants (including the vertex itself) even vertices, and all the other vertices - odd vertices. A vertex cannot change its status in the process of building the perfect matching. Each leaf is and odd vertex, and if its parent has only one child, this parent is an even vertex. So, when we remove a pair of vertices, one of them (the child) is odd, and the other of them (the parent) is even. This leads us to another way of building the perfect matching: match each odd vertex with its parent, and make sure that everything is correct. Unfortunately, implementing it is $O(n)$ per query, so we need something faster. We can see that each even vertex has at least one odd child (because if all children of a vertex are even, then the number of its descendants, including the vertex itself is odd). In order to find a perfect matching, we have to make sure that: each even vertex has exactly one odd child; each odd vertex has an even vertex as its parent. All this means is that the number of even vertices should be equal to the number of odd vertices: it cannot be greater since each even vertex has at least one odd child, and if it is smaller, it's impossible to match the vertices. The perfect matching itself consists of edges that connect odd vertices with their parents. Okay, now we need some sort of data structure to maintain the status of each vertex (and the sum of edges that lead to an odd vertex if directed from top to bottom). In our problem, we have to add new leaves to the tree (it happens when a vertex is activated), and this increases the number of descendants for every vertex on the path from the root to this new leaf. So, we need some sort of data structure that supports the operations \"add a new leaf\" and \"flip the status of all vertices on a path\". One of the structures that allow this is the Link/Cut Tree, but we can use the fact that the whole tree is given in advance to build a Heavy-Light Decomposition on it, which is much easier to code. Operations on segments of paths can be done with a lazy segment tree, and each vertex then will be added in $O(\\log^2 n)$.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\ntypedef pair<long long, int> val;\n\n#define x first \n#define y second\n\nconst int N = 200043;\n\nval operator +(const val& a, const val& b)\n{\n    return make_pair(a.x + b.x, a.y + b.y);\n}\n\nval operator -(const val& a, const val& b)\n{\n    return make_pair(a.x - b.x, a.y - b.y);\n}\n\nval T[4 * N];\nval Tfull[4 * N];\nint f[4 * N];\n\nval getVal(int v)\n{\n    if(f[v] == 1)\n        return Tfull[v] - T[v];\n    return T[v];\n}\n\nvoid push(int v)\n{\n    if(f[v] == 1)\n    {\n        f[v] = 0;\n        T[v] = Tfull[v] - T[v];\n        f[v * 2 + 1] ^= 1;\n        f[v * 2 + 2] ^= 1;\n    }   \n}                \n\nvoid upd(int v)\n{\n    Tfull[v] = Tfull[v * 2 + 1] + Tfull[v * 2 + 2];\n    T[v] = getVal(v * 2 + 1) + getVal(v * 2 + 2);\n}\n\nvoid setVal(int v, int l, int r, int pos, val cur)\n{                                                           \n    if(l == r - 1)\n    {\n        f[v] = 0;\n        Tfull[v] = cur;\n        T[v] = cur;\n    }\n    else\n    {\n        push(v);\n        int m = (l + r) / 2;\n        if(pos < m)\n            setVal(v * 2 + 1, l, m, pos, cur);\n        else\n            setVal(v * 2 + 2, m, r, pos, cur);\n        upd(v);\n    }\n}\n\nvoid flipColor(int v, int l, int r, int L, int R)\n{\n    if(L >= R) return;\n    if(l == L && r == R)\n        f[v] ^= 1;\n    else\n    {\n        push(v);\n        int m = (l + r) / 2;\n        flipColor(v * 2 + 1, l, m, L, min(m, R));\n        flipColor(v * 2 + 2, m, r, max(L, m), R);\n        upd(v);\n    }\n}\n\nval getVal(int v, int l, int r, int L, int R)\n{\n    if(L >= R) return make_pair(0ll, 0);\n    if(l == L && r == R) return getVal(v);\n    int m = (l + r) / 2;\n    val ans = make_pair(0ll, 0);\n    push(v);\n    ans = ans + getVal(v * 2 + 1, l, m, L, min(R, m));\n    ans = ans + getVal(v * 2 + 2, m, r, max(L, m), R);\n    upd(v);\n    return ans;\n}\n\nint n;\nvector<int> g[N];\n\nint p[N], siz[N], d[N], nxt[N];\nint tin[N], timer;\nmap<pair<int, int>, int> idx;\nlong long sum;\nint cnt;\nint active[N];\nint active_cnt;\n\nvoid dfs_sz(int v) \n{\n    if (p[v] != -1) \n    {\n        auto it = find(g[v].begin(), g[v].end(), p[v]);\n        if (it != g[v].end())\n            g[v].erase(it);\n    }\n    siz[v] = 1;\n    for (int &u : g[v]) \n    {\n        p[u] = v;\n        d[u] = d[v] + 1;\n        dfs_sz(u);\n        siz[v] += siz[u];\n        if (siz[u] > siz[g[v][0]])\n            swap(u, g[v][0]);\n    }\n}\n\nvoid dfs_hld(int v) \n{\n    tin[v] = timer++;\n    for (int u : g[v]) \n    {\n        nxt[u] = (u == g[v][0] ? nxt[v] : u);\n        dfs_hld(u);\n    }\n}\n\n// [l; r] inclusive\nvoid flipSegment(int l, int r) \n{\n    flipColor(0, 0, n, l, r + 1);        \n}\n\n// [l; r] inclusive\nval get(int l, int r) \n{\n    return getVal(0, 0, n, l, r + 1);   \n}\n\nvoid flipPath(int v, int u) \n{\n    for (; nxt[v] != nxt[u]; u = p[nxt[u]]) \n    {\n        if (d[nxt[v]] > d[nxt[u]]) swap(v, u);\n        flipSegment(tin[nxt[u]], tin[u]);\n    }\n    if (d[v] > d[u]) swap(v, u);\n    flipSegment(tin[v], tin[u]);\n}\n\nval getPath(int v, int u) \n{\n    val res = make_pair(0ll, 0);\n    for (; nxt[v] != nxt[u]; u = p[nxt[u]]) \n    {\n        if (d[nxt[v]] > d[nxt[u]]) swap(v, u);\n        // update res with the result of get()\n        res = res + get(tin[nxt[u]], tin[u]);\n    }\n    if (d[v] > d[u]) swap(v, u);\n    res = res + get(tin[v], tin[u]);\n    return res;\n}\n\nvoid activate_vertex(int x)\n{\n    int id = 0;\n    if(p[x] != -1)\n    {                       \n        id = idx[make_pair(x, p[x])];\n        val v = getPath(0, p[x]);\n        flipPath(0, p[x]);\n        sum -= v.x;\n        cnt -= v.y;\n        v = getPath(0, p[x]);\n        sum += v.x;\n        cnt += v.y;\n    }                   \n    cnt++;\n    sum += id;\n    setVal(0, 0, n, tin[x], make_pair((long long)(id), 1));\n    active[x] = 1;\n    active_cnt++;   \n}          \n\nvoid init_hld(int root = 0) \n{\n    d[root] = 0;\n    nxt[root] = root;\n    p[root] = -1;\n    timer = 0;\n    dfs_sz(root);\n    dfs_hld(root);\n}\n\nint currentSize[N];\n\nint dfsSolution(int x, vector<int>& edges)\n{\n    if(!active[x]) return 0;\n    currentSize[x] = 1;\n    for(auto y : g[x])\n        if(y != p[x])\n            currentSize[x] += dfsSolution(y, edges);\n    if(currentSize[x] % 2 == 1)\n        edges.push_back(idx[make_pair(x, p[x])]);\n    return currentSize[x];   \n}\n\nvoid outputSolution()\n{\n    vector<int> edges;\n    if(cnt * 2 == active_cnt)\n    {\n        dfsSolution(0, edges);\n        sort(edges.begin(), edges.end());\n    }\n    printf(\"%d\", int(edges.size()));\n    for(auto x : edges) printf(\" %d\", x);\n    puts(\"\");\n    fflush(stdout);\n}\n\nvoid processQuery(int v)\n{\n    activate_vertex(v);\n    if(cnt * 2 == active_cnt)\n        printf(\"%lld\\n\", sum);\n    else\n        puts(\"0\");\n    fflush(stdout);\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for(int i = 1; i < n; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        --x;\n        --y;\n        g[x].push_back(y);\n        g[y].push_back(x);\n        idx[make_pair(x, y)] = i;\n        idx[make_pair(y, x)] = i;\n    }   \n    \n    init_hld();         \n    activate_vertex(0); \n    while(true)\n    {\n        int t;\n        scanf(\"%d\", &t);       \n        if(t == 3)\n            break;\n        if(t == 2)\n            outputSolution();\n        if(t == 1)\n        {\n            int v;          \n            scanf(\"%d\", &v);\n            --v;\n            processQuery(v);\n        } \n    }\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "interactive",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1634",
    "index": "A",
    "title": "Reverse and Concatenate",
    "statement": "\\begin{quote}\nReal stupidity beats artificial intelligence every time.\n\\hfill — Terry Pratchett, Hogfather, Discworld\n\\end{quote}\n\nYou are given a string $s$ of length $n$ and a number $k$. Let's denote by $rev(s)$ the reversed string $s$ (i.e. $rev(s) = s_n s_{n-1} ... s_1$). You can apply one of the two kinds of operations to the string:\n\n- replace the string $s$ with $s + rev(s)$\n- replace the string $s$ with $rev(s) + s$\n\nHow many different strings can you get as a result of performing \\textbf{exactly} $k$ operations (possibly of different kinds) on the original string $s$?\n\nIn this statement we denoted the concatenation of strings $s$ and $t$ as $s + t$. In other words, $s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$, where $n$ and $m$ are the lengths of strings $s$ and $t$ respectively.",
    "tutorial": "If $k = 0$, the answer is $1$. Otherwise, consider two cases: The string is a palindrome (that is, $s = rev(s)$). Then $rev(s) + s = s + rev(s) = s + s$, so both operations will replace $s$ by the string $s+s$, which is also a palindrome. Then for any $k$ the answer is $1$. Otherwise $s \\ne rev(s)$. Then after the first operation we get either $s + rev(s)$ (which is a palindrome) or $rev(s) + s$ (also a palindrome). Also note that if we apply the operation to two different palindromes of length $x$ any number of times, they cannot become equal, since they do not have the same prefix of length $x$. So, after the first operation from a non-palindrome 2 different strings will be obtained, and after all following operations 2 unequal strings will be obtained. So the answer is - $2$.",
    "code": "q = int(input())\n\nfor _ in range(q):\n    n, k = map(int, input().split())\n    s = input()\n    if s == s[::-1] or k == 0:\n        print(1)\n    else:\n        print(2)",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1634",
    "index": "B",
    "title": "Fortune Telling",
    "statement": "\\begin{quote}\nHaha, try to solve this, SelectorUnlimited!\n\\hfill — antontrygubO_o\n\\end{quote}\n\nYour friends Alice and Bob practice fortune telling.\n\nFortune telling is performed as follows. There is a well-known array $a$ of $n$ non-negative integers indexed from $1$ to $n$. The tellee starts with some non-negative number $d$ and performs one of the two operations for each $i = 1, 2, \\ldots, n$, \\textbf{in the increasing order of $i$}. The possible operations are:\n\n- replace their current number $d$ with $d + a_i$\n- replace their current number $d$ with $d \\oplus a_i$ (hereinafter $\\oplus$ denotes the bitwise XOR operation)\n\nNotice that the chosen operation may be different for different $i$ and for different tellees.\n\nOne time, Alice decided to start with $d = x$ and Bob started with $d = x + 3$. Each of them performed fortune telling and got a particular number in the end. Notice that the friends chose operations independently of each other, that is, they could apply different operations for the same $i$.\n\nYou learnt that either Alice or Bob ended up with number $y$ in the end, but you don't know whose of the two it was. Given the numbers Alice and Bob started with and $y$, find out who (Alice or Bob) could get the number $y$ after performing the operations. It is guaranteed that on the jury tests, \\textbf{exactly one} of your friends could have actually gotten that number.\n\n\\textbf{Hacks}\n\nYou cannot make hacks in this problem.",
    "tutorial": "Notice that the operations $+$ and $\\oplus$ have the same effect on the parity: it is inverted if the second argument of the operation is odd, and stays the same otherwise. By induction, we conclude that if we apply the operations to some even number and to some odd number, the resulting numbers will also be of different parity. Therefore, we can determine whether the parity of the input is the same as the parity of the output or the opposite: if the sum of $a$ is even, then the parity does not change, otherwise it does. Thus we can find out the parity of the original number from the parity of the result, and this is enough to solve the problem because the numbers $x$ and $x + 3$ have different parity.",
    "code": "def main():\n    n, x, y = map(int, input().split())\n    a = list(map(int, input().split()))\n    if (sum(a) + x + y) % 2 == 0:\n        print('Alice')\n    else:\n        print('Bob')\n\n\nfor _ in range(int(input())):\n    main()",
    "tags": [
      "bitmasks",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1634",
    "index": "C",
    "title": "OKEA",
    "statement": "\\begin{quote}\nPeople worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.\n\\hfill — Pedro Domingos\n\\end{quote}\n\nYou work for a well-known department store that uses leading technologies and employs mechanistic work — that is, robots!\n\nThe department you work in sells $n \\cdot k$ items. The first item costs $1$ dollar, the second item costs $2$ dollars, and so on: $i$-th item costs $i$ dollars. The items are situated on shelves. The items form a rectangular grid: there are $n$ shelves in total, and each shelf contains exactly $k$ items. We will denote by $a_{i,j}$ the price of $j$-th item (counting from the left) on the $i$-th shelf, $1 \\le i \\le n, 1 \\le j \\le k$.\n\nOccasionally robots get curious and ponder on the following question: what is the mean price (arithmetic average) of items $a_{i,l}, a_{i,l+1}, \\ldots, a_{i,r}$ for some shelf $i$ and indices $l \\le r$? Unfortunately, the old robots can only work with whole numbers. If the mean price turns out not to be an integer, they break down.\n\nYou care about robots' welfare. You want to arrange the items in such a way that the robots cannot theoretically break. Formally, you want to choose such a two-dimensional array $a$ that:\n\n- Every number from $1$ to $n \\cdot k$ (inclusively) occurs exactly once.\n- For each $i, l, r$, the mean price of items from $l$ to $r$ on $i$-th shelf is an integer.\n\nFind out if such an arrangement is possible, and if it is, give any example of such arrangement.",
    "tutorial": "If $k = 1$, you can put items on the shelves in any order. Otherwise, there are at least 2 items on each shelf. If there are items of different parity on the shelf, it is obvious that there are two neighboring items of different parity, but then the arithmetic mean of these two items won't be whole, which is against the constraints. Therefore, all items on each shelf are of the same parity. Notice that if the number of shelves $n$ is odd, we cannot arrange the items correctly because the number of shelves with even and odd items must be the same (that is, if $k \\ge 2$). Let us show that for even $n$ there is always an answer. On $i$-th shelf we will place items with prices $i, i + n, i + 2 \\cdot n, \\ldots, i + n \\cdot (k - 1)$. We can use the formula for the sum of an arithmetic progression to compute the sum of prices of a subsegment with coordinates $i, l$ up to $i, r$: $sum = i \\cdot (r - l + 1) + \\frac{n(l - 1) + n(r - 1)}{2} \\cdot (r - l + 1) = \\ = i \\cdot (r - l + 1) + \\frac{n}{2} \\cdot (l + r - 2) \\cdot (r - l + 1) = \\ = (r - l + 1) \\cdot \\left(i + \\frac{n}{2} \\cdot (l + r - 2)\\right)$ The length of the segment ($r - l + 1$) always divides this sum, since $n$ is even. Therefore, this arrangement fits the requirements of the problem.",
    "code": "def solve():\n    n, k = map(int, input().split())\n    if k == 1:\n        print(\"YES\")\n        for i in range(1, n + 1):\n            print(i)\n        return\n\n    if n % 2 == 1:\n        print(\"NO\")\n        return\n\n    print(\"YES\")\n    for i in range(1, n + 1):\n        print(*[i for i in range(i, n * k + 1, n)])\n\n\nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1634",
    "index": "D",
    "title": "Finding Zero",
    "statement": "\\textbf{This is an interactive problem.}\n\nWe picked an array of whole numbers $a_1, a_2, \\ldots, a_n$ ($0 \\le a_i \\le 10^9$) and concealed \\textbf{exactly one} zero in it! Your goal is to find the location of this zero, that is, to find $i$ such that $a_i = 0$.\n\nYou are allowed to make several queries to guess the answer. For each query, you can think up three distinct indices $i, j, k$, and we will tell you the value of $\\max(a_i, a_j, a_k) - \\min(a_i, a_j, a_k)$. In other words, we will tell you the difference between the maximum and the minimum number among $a_i$, $a_j$ and $a_k$.\n\nYou are allowed to make no more than $2 \\cdot n - 2$ queries, and after that you have two tries to guess where the zero is. That is, you have to tell us two numbers $i$ and $j$ and you win if $a_i = 0$ or $a_j = 0$.\n\nCan you guess where we hid the zero?\n\nNote that the array in each test case is fixed beforehand and will not change during the game. In other words, the interactor is not adaptive.",
    "tutorial": "Notice that for any four numbers $a, b, c, d$ we can locate at least two numbers among them that are certainly not zeroes using only four queries as follows. For each of the four numbers, compute it's complement, that is, the difference between the maximum and the minimum of the other three numbers: $\\bar{a} = \\max(b, c, d) - \\min(b, c, d)$ and so on. This takes exactly four queries. Now, consider what happens if one of the four numbers was a zero. For instance, if $a = 0, b \\le c \\le d$, then: $\\bar{a} = d - b$ $\\bar{b} = d$ $\\bar{c} = d$ $\\bar{d} = c$ $d > d - b, d \\ge c$, so the two largest complements ($\\bar{b} = \\bar{c} = d$ in this example) are always complements of non-zeroes. Of course, the order of the values could be different, but the numbers with the two largest complements will always be guaranteed non-zeroes. If there is no zero among these numbers, then we can still run this algorithm because it doesn't matter exactly which numbers it will yield - they are all non-zero anyway. Now let's learn how to solve the problem using this algorithm. Start with a \"pile\" of the first four numbers, apply the algorithm and throw two certain non-zeroes away. Add the next two numbers to the \"pile\" and drop two non-zeroes again. Repeat this until there are two or three numbers left in the \"pile\", depending on the parity of $n$. If there are three elements left, add some number that we have already dropped to the pile again and apply the algorithm the last time. If $n$ is even, we have made $\\frac{n - 2}{2} \\cdot 4 = 2n - 4$ queries. If $n$ is odd, we have made $\\frac{n - 3}{2} \\cdot 4 + 4 = 2n - 2$ queries. The complexity of this solution is $\\mathcal{O}(n)$, and the solution uses no more than $2n - 2$ queries.",
    "code": "#include <bits/stdc++.h>\n \n#define all(x) (x).begin(), (x).end()\n#define len(x) (int) (x).size()\n \nusing namespace std;\n \n \nint get(const vector <int>& x) {\n    cout << \"? \" << x[0] + 1 << \" \" << x[1] + 1 << \" \" << x[2] + 1 << endl;\n    int ans;\n    cin >> ans;\n    return ans;\n}\n \n \nsigned main() {\n    ios_base::sync_with_stdio();\n    cin.tie(nullptr);\n    \n    int t;\n    cin >> t;\n    \n    while(t --> 0) {\n        int n;\n        cin >> n;\n    \n        pair <int, int> possible = {0, 1};\n        for (int i = 2; i < n - 1; i += 2) {\n            vector <pair <int, int>> ch(4);\n            vector <int> now = {possible.first, possible.second, i, i + 1};\n            for (int j = 0; j < 4; j++) {\n                vector <int> x = now;\n                x.erase(x.begin() + j);\n                ch[j] = {get(x), now[j]};\n            }\n            sort(all(ch));\n            possible = {ch[0].second, ch[1].second};\n        }\n        if (n % 2 == 1) {\n            int other = 0;\n            while (possible.first == other || possible.second == other) {\n                other++;\n            }\n            vector <pair <int, int>> ch(4);\n            vector <int> now = {possible.first, possible.second, n - 1, other};\n            for (int j = 0; j < 4; j++) {\n                vector <int> x = now;\n                x.erase(x.begin() + j);\n                ch[j] = {get(x), now[j]};\n            }\n            sort(all(ch));\n            possible = {ch[0].second, ch[1].second};\n        }\n        cout << \"! \" << possible.first + 1 << \" \" << possible.second + 1 << endl;\n    }\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1634",
    "index": "E",
    "title": "Fair Share",
    "statement": "\\begin{quote}\nEven a cat has things it can do that AI cannot.\n\\hfill — Fei-Fei Li\n\\end{quote}\n\nYou are given $m$ arrays of positive integers. Each array is of even length.\n\nYou need to split all these integers into two \\textbf{equal} multisets $L$ and $R$, that is, each element of each array should go into one of two multisets (but not both). Additionally, for each of the $m$ arrays, \\textbf{exactly half} of its elements should go into $L$, and the rest should go into $R$.\n\nGive an example of such a division or determine that no such division exists.",
    "tutorial": "If there is a number that occurs an odd number of times in total, there is no answer. Otherwise, let us construct a bipartite graph as follows. The left part will denote the arrays ($m$ vertices) and the right part will denote the numbers (up to $\\sum n_i$ vertices). Each array vertex is connected to all the numbers contained in the array, counted with multiplicity. That is, a vertex $a$ from the left part is connected to a vertex $b$ from the right part $x$ times, where $x$ is the count of occurrences of the number $b$ in the $a$-th array. Notice that all vertices in both parts are of even degree because the length of each array is even and the number of occurrences of each number is even. Therefore we can find a directed Eulerian circuit of this graph. Then for edges like $a \\rightarrow b$ (going from the left to the right) let us add the number $b$ to $L$, and for edges like $a \\leftarrow b$ (going from the right to the left) add $b$ to $R$. This partitioning will obviously be valid. For each vertex on the left, the indegree equals the outdegree and hence each array is split in half, and for each vertex on the right the same condition holds, so each number occurs in $L$ and $R$ the same number of times and thus $L = R$.",
    "code": "#include <bits/stdc++.h>\n\n#define len(x) (int) (x).size()\n#define all(x) (x).begin(), (x).end()\n#define endl \"\\n\"\n\nusing namespace std;\n\nconst int N = 4e5 + 100, H = 2e5 + 50;\nvector <pair <int, int>> g[N];\nstring ans[N];\nint pos[N];\n\n\nvoid dfs(int v) {\n    if (pos[v] == 0) {\n        ans[v] = string(len(g[v]), 'L');\n    }\n\n    while (pos[v] < len(g[v])) {\n        auto [i, ind] = g[v][pos[v]];\n        if (i == -1) {\n            pos[v]++;\n            continue;\n        }\n        g[i][ind].first = -1, g[v][pos[v]].first = -1;\n        if (v < H) {\n            ans[v][pos[v]] = 'R';\n        }\n        pos[v]++;\n        dfs(i);\n    }\n}\n\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int m;\n    cin >> m;\n    map <int, int> ind, cnt;\n    int fre_ind = 0;\n\n    vector <vector <int>> nums(m);\n    for (int i = 0; i < m; i++) {\n        int n;\n        cin >> n;\n        for (int _ = 0; _ < n; _++) {\n            int x;\n            cin >> x;\n            if (!ind.count(x)) {\n                ind[x] = fre_ind++;\n            }\n            x = ind[x];\n            cnt[x]++;\n            nums[i].push_back(x);\n            g[i].emplace_back(x + H, len(g[x + H]));\n            g[x + H].emplace_back(i, len(g[i]) - 1);\n        }\n    }\n\n    for (auto [num, cn] : cnt) {\n        if (cn % 2 == 1) {\n            cout << \"NO\" << endl;\n            return 0;\n        }\n    }\n\n    for (int i = 0; i < N; i++) {\n        dfs(i);\n    }\n\n    cout << \"YES\" << endl;\n    for (int i = 0; i < m; i++) {\n        cout << ans[i] << endl;\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "graph matchings",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1634",
    "index": "F",
    "title": "Fibonacci Additions",
    "statement": "\\begin{quote}\nOne of my most productive days was throwing away 1,000 lines of code.\n\\hfill — Ken Thompson\n\\end{quote}\n\n\\textbf{Fibonacci addition} is an operation on an array $X$ of integers, parametrized by indices $l$ and $r$. Fibonacci addition increases $X_l$ by $F_1$, increases $X_{l + 1}$ by $F_2$, and so on up to $X_r$ which is increased by $F_{r - l + 1}$.\n\n$F_i$ denotes the $i$-th Fibonacci number ($F_1 = 1$, $F_2 = 1$, $F_{i} = F_{i - 1} + F_{i - 2}$ for $i > 2$), and \\textbf{all operations are performed modulo $MOD$}.\n\nYou are given two arrays $A$ and $B$ of the same length. We will ask you to perform several Fibonacci additions on these arrays with different parameters, and after each operation you have to report whether arrays $A$ and $B$ are equal modulo $MOD$.",
    "tutorial": "Let $C_i = A_i - B_i$. Consider another auxiliary array $D$, where $D_1 = C_1$, $D_2 = C_2 - C_1$, and $D_i = C_i - C_{i - 1} - C_{i - 2}$ for $i > 2$. Notice that arrays $A$ and $B$ are equal if and only if all elements of $D$ are equal to $0$. Let's analyze how Fibonacci addition affects $D$. If Fibonacci addition is performed on array $A$ on a segment from $l$ to $r$, then: $D_l$ will increase by $1$, $D_{r + 1}$ will decrease by $F_{r - l + 2}$, and $D_{r + 2}$ will decrease by $F_{r - l + 1}$. Fibonacci addition on $B$ can be handled in a similar way. Fibonacci numbers modulo $MOD$ can be easily precomputed, and therefore the problem can be solved in linear time.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define len(x) (int) (x).size()\n#define endl \"\\n\"\n#define int long long\n\nusing namespace std;\n\nconst int N = 3e5 + 100;\nint MOD;\nint fib[N];\n\nvector <int> unfib;\nint notzero = 0;\n\nvoid upd(int ind, int delta) {\n  notzero -= (unfib[ind] != 0);\n  unfib[ind] += delta;\n  if (unfib[ind] >= MOD) {\n    unfib[ind] -= MOD;\n  };\n  notzero += (unfib[ind] != 0);\n}\n\n\nsigned main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n\n  int n, q;\n  cin >> n >> q >> MOD;\n\n  fib[0] = fib[1] = 1;\n  for (int i = 2; i < N; i++) {\n    fib[i] = (fib[i - 1] + fib[i - 2]) % MOD;\n  }\n\n  vector <int> delta(n);\n  for (int& i : delta) {\n    cin >> i;\n  }\n  for (int i = 0; i < n; i++) {\n    int x;\n    cin >> x;\n    delta[i] = (delta[i] - x + MOD) % MOD;\n  }\n\n  unfib.resize(n);\n  unfib[0] = delta[0];\n  if (len(unfib) >= 2) {\n    unfib[1] = (delta[1] - delta[0] + MOD) % MOD;\n  }\n  for (int i = 2; i < n; i++) {\n    unfib[i] = ((long long) delta[i] - delta[i - 1] - delta[i - 2] + MOD * 2) % MOD;\n  }\n  for (int i = 0; i < n; i++) {\n    notzero += (unfib[i] != 0);\n  }\n\n  while (q--) {\n    char c;\n    int l, r;\n    cin >> c >> l >> r;\n    if (c == 'A') {\n      upd(l - 1, 1);\n      if (r != n) {\n        upd(r, MOD - fib[r - l + 1]);\n      }\n      if (r < n - 1) {\n        upd(r + 1, MOD - fib[r - l]);\n      }\n    } else {\n      upd(l - 1, MOD - 1);\n      if (r != n) {\n        upd(r, fib[r - l + 1]);\n      }\n      if (r < n - 1) {\n        upd(r + 1, fib[r - l]);\n      }\n    }\n    if (!notzero) {\n      cout << \"YES\" << endl;\n    } else {\n      cout << \"NO\" << endl;\n    }\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "hashing",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1635",
    "index": "A",
    "title": "Min Or Sum",
    "statement": "You are given an array $a$ of size $n$.\n\nYou can perform the following operation on the array:\n\n- Choose two different integers $i, j$ $(1 \\leq i < j \\leq n$), replace $a_i$ with $x$ and $a_j$ with $y$. In order not to break the array, $a_i | a_j = x | y$ must be held, where $|$ denotes the bitwise OR operation. Notice that $x$ and $y$ are non-negative integers.\n\nPlease output the minimum sum of the array you can get after using the operation above any number of times.",
    "tutorial": "The answer is $a_1 | a_2 | \\cdots | a_n$. Here is the proof: Let $m = a_1 | a_2 | \\cdots | a_n$. After an operation, the value $m$ won't change. Since, $a_1 | a_2 | \\cdots | a_n \\leq a_1 + a_2 + \\cdots + a_n$, the sum of the array has a lower bound of $m$. And this sum can be constructed easily: for all $i \\in [1, n - 1]$, set $a_{i+1}$ to $a_i | a_{i+1}$ and $a_i$ to $0$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main () {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        int ans = 0;\n        for (int i = 0, x; i < n; ++i) {\n            cin >> x;\n            ans |= x;\n        }\n        cout << ans << endl;\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1635",
    "index": "B",
    "title": "Avoid Local Maximums",
    "statement": "You are given an array $a$ of size $n$. Each element in this array is an integer between $1$ and $10^9$.\n\nYou can perform several operations to this array. During an operation, you can replace an element in the array with any integer between $1$ and $10^9$.\n\nOutput the minimum number of operations needed such that the resulting array doesn't contain any local maximums, and the resulting array after the operations.\n\nAn element $a_i$ is a local maximum if it is strictly larger than both of its neighbors (that is, $a_i > a_{i - 1}$ and $a_i > a_{i + 1}$). Since $a_1$ and $a_n$ have only one neighbor each, they will never be a local maximum.",
    "tutorial": "Let's check all elements in $a$ from the left. Once we find that $a_i$ is a local maximum, then we should perform an operation to fix it. There are many ways to do this, but the optimal way is to set $a_{i+1}$ to $max(a_{i},a_{i+2})$, because we can avoid $a_i$ and $a_{i+2}$ from being local maximums at the same time. Proof: Let's take all indices of local maximums in the initial array and append them to an empty array $b$ with their corresponding order. For example, if $a=[1,2,1,3,1,1,3,1,4,1,2 ,1]$, we obtain $b=[2,4,7,9,11]$. Then, we devide $b$ into subarrays, such that $b_i$ and $b_{i+1}$ are in the same subarray if and only if $b_{i+1}-b_i=2$. Using the same example above, we will devide $b$ into $[2,4], [7,9,11]$. To finish our proof, we need two important observations. 1. Any operation would cancel at most two local maximums. 2. Any operation won't cancel two local maximums whose indices are in different subarrays of $b$. So for a fixed subarray, we need at least $\\lceil \\frac{length}{2} \\rceil$ operations to cancel all corresponding local maximums, and the lower bound of the answer is the sum of $\\lceil \\frac{length}{2} \\rceil$ for all subarrays. Since the strategy described above could achieve this lower bound, our proof has completed.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main () {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector <int> a(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n        }\n        int ans = 0;\n        for (int i = 1; i + 1 < n; ++i) {\n            if (a[i] > a[i - 1] && a[i] > a[i + 1]) {\n                if (i + 2 < n) {\n                    a[i + 1] = max(a[i], a[i + 2]);\n                } else {\n                    a[i + 1] = a[i];\n                }\n                ans++;\n            }\n        }\n        cout << ans << endl;\n        for (int i = 0; i < n; ++i) {\n            cout << a[i] << \" \\n\"[i == n - 1];\n        }\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1635",
    "index": "C",
    "title": "Differential Sorting",
    "statement": "You are given an array $a$ of $n$ elements.\n\nYour can perform the following operation no more than $n$ times: Select three indices $x,y,z$ $(1 \\leq x < y < z \\leq n)$ and replace $a_x$ with $a_y - a_z$. After the operation, $|a_x|$ need to be less than $10^{18}$.\n\nYour goal is to make the resulting array \\textbf{non-decreasing}. If there are multiple solutions, you can output any. If it is impossible to achieve, you should report it as well.",
    "tutorial": "First of all, if $a_{n-1} > a_n$, then the answer is $-1$ since we can't change the last two elements. If $a_n \\geq 0$, there exists a simple solution: perform the operation $(i, n - 1, n)$ for each $1 \\leq i \\leq n - 2$. Otherwise, the answer exists if and only if the initial array is sorted. Proof: Assume that $a_n < 0$ and we can sort the array after $m > 0$ operations. Consider the last operation we performed ($x_m, y_m, z_m$). Since all elements should be negative after the last operation, so $a_{z_m} < 0$ should hold before the last operation. But $a_{x_m} = a_{y_m} - a_{z_m} > a_{y_m}$ after this, so the array isn't sorted in the end. By contradiction, we have proved that we can't perform any operations as long as $a_n < 0$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main () {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector <int> a(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n        }\n        if (a[n - 2] > a[n - 1]) {\n            cout << -1 << endl;\n        } else {\n            if (a[n - 1] < 0) {\n                if (is_sorted(a.begin(), a.end())) {\n                    cout << 0 << endl;\n                } else {\n                    cout << -1 << endl;\n                }\n            } else {\n                cout << n - 2 << endl;\n                for (int i = 1; i <= n - 2; ++i) {\n                    cout << i << ' ' << n - 1 << ' ' << n << endl;\n                }\n            }\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1635",
    "index": "D",
    "title": "Infinite Set",
    "statement": "You are given an array $a$ consisting of $n$ \\textbf{distinct} positive integers.\n\nLet's consider an infinite integer set $S$ which contains all integers $x$ that satisfy at least one of the following conditions:\n\n- $x = a_i$ for some $1 \\leq i \\leq n$.\n- $x = 2y + 1$ and $y$ is in $S$.\n- $x = 4y$ and $y$ is in $S$.\n\nFor example, if $a = [1,2]$ then the $10$ smallest elements in $S$ will be $\\{1,2,3,4,5,7,8,9,11,12\\}$.\n\nFind the number of elements in $S$ that are strictly smaller than $2^p$. Since this number may be too large, print it modulo $10^9 + 7$.",
    "tutorial": "First of all, let's discuss the problem where $n = 1$ and $a_1 = 1$. For every integer $x$, there is exactly one integer $k$ satisfying $2^k \\leq x < 2^{k + 1}$. Let's define $f(x) = k$. Then, it's quite easy to find out $f(2x + 1) = f(x) + 1$ and $f(4x) = f(x) + 2$. This observation leads to a simple dynamic programming solution: let $dp_i$ be the number of integer $x$ where $x \\in S$ and $f(x) = i$. The base case is $dp_{0} = 1$ and the transition is $dp_i = dp_{i - 1} + dp_{i - 2}$. After computing the $dp$ array, the final answer will be $\\sum\\limits_{i = 0}^{p - 1}dp_i$. For the general version of the problem, in order not to compute the same number two or more times, we need to delete all \"useless\" numbers. A number $a_i$ is called useless if there exists an index $j$ such that $a_j$ can generate $a_i$ after a series of operations (setting $a_j$ to $2 a_j + 1$ or $4 a_j$). After the deletion, we can simply do the same thing above, only changing the transition a little bit: $dp_i = dp_{i - 1} + dp_{i - 2} + g(i)$, where $g(i)$ = number of $j$ satisfying $f(a_j) = i$. The final problem is how to find all the useless numbers. For every integer $x$, there are at most $\\mathcal{O}(logx)$ possible \"parents\" that can generate it. Also, such \"parent\" must be smaller than $x$. So, let's sort the array in increasing order. Maintain all useful numbers in a set, and for each $a_i$, we will check whether its \"parent\" exists or not. Once we confirm that its parent doesn't exist, we will append it to the set of useful numbers. This works in $\\mathcal{O}(nlognlogC)$. Total Complexity: $\\mathcal{O}(nlognlogC + p)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int mod = 1e9 + 7;\n\nint main () {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int n, p;\n    cin >> n >> p;\n    vector <int> a(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    sort(a.begin(), a.end());\n    set <int> useful;\n    for (int i = 0; i < n; ++i) {\n        int x = a[i];\n        bool flag = false;\n        while (x > 0) {\n            if (useful.count(x)) {\n                flag = true;\n            }\n            if (x & 1) {\n                x >>= 1;\n            } else if (x & 3) {\n                break;\n            } else {\n                x >>= 2;\n            }\n        }\n        if (!flag)\n            useful.insert(a[i]);\n    }\n    vector <int> cnt(30, 0), dp(p);\n    for (int x : useful) {\n        cnt[__lg(x)]++;\n    }\n    int ans = 0;\n    for (int i = 0; i < p; ++i) {\n        if (i < 30) {\n            dp[i] = cnt[i];\n        }\n        if (i >= 1) {\n            dp[i] += dp[i - 1];\n            if (dp[i] >= mod) {\n                dp[i] -= mod;\n            }\n        }\n        if (i >= 2) {\n            dp[i] += dp[i - 2];\n            if (dp[i] >= mod) {\n                dp[i] -= mod;\n            }\n        }\n        ans += dp[i];\n        if (ans >= mod) {\n            ans -= mod;\n        }\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "math",
      "matrices",
      "number theory",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1635",
    "index": "E",
    "title": "Cars ",
    "statement": "There are $n$ cars on a coordinate axis $OX$. Each car is located at an integer point initially and no two cars are located at the same point. Also, each car is oriented either left or right, and they can move at any constant positive speed in that direction at any moment.\n\nMore formally, we can describe the $i$-th car with a letter and an integer: its orientation $ori_i$ and its location $x_i$. If $ori_i = L$, then $x_i$ is decreasing at a constant rate with respect to time. Similarly, if $ori_i = R$, then $x_i$ is increasing at a constant rate with respect to time.\n\nWe call two cars \\textbf{irrelevant} if they never end up in the same point regardless of their speed. In other words, they won't share the same coordinate at any moment.\n\nWe call two cars \\textbf{destined} if they always end up in the same point regardless of their speed. In other words, they must share the same coordinate at some moment.\n\nUnfortunately, we lost all information about our cars, but we do remember $m$ relationships. There are two types of relationships:\n\n$1$ $i$ $j$ —$i$-th car and $j$-th car are \\textbf{irrelevant}.\n\n$2$ $i$ $j$ —$i$-th car and $j$-th car are \\textbf{destined}.\n\nRestore the orientations and the locations of the cars satisfying the relationships, or report that it is impossible. If there are multiple solutions, you can output any.\n\nNote that if two cars share the same coordinate, they will intersect, but at the same moment they will continue their movement in their directions.",
    "tutorial": "First of all, let's discuss in what cases will two cars be irrelevant or destined. If two cars are in the same direction, they can either share the same coordinate at some moment or not, depending on their speed. In the picture above, if we set the speed of the blue car to $\\infty$ and the red car to $1$, they won't meet each other. But if we set the speed of the blue car to $1$ and the red car to $\\infty$, they will meet each other. If two cars are irrelevant, they must look something like this: If two cars are destined, they must look something like this: In conclusion, if there is a relationship between car $i$ and car $j$, their direction must be different. So let's build a graph: if there is a relationship between car $i$ and car $j$, we'll add an undirected edge between vertices $(i, j)$. Note that this implies any valid set of relations must form a bipartite graph. After that, let's run dfs or bfs to make a bipartite coloring. If the graph isn't bipartite, the answer is obviously \"NO\". Otherwise we can get information about the cars' direction. The next part is how to know where the cars are located. If car $i$ and car $j$ have a relationship and the orientation of the car $i$ is left, we can know the following restriction: 1. if two cars are irrelevant, $x_i < x_j$ must be held. 2. if two cars are destined, $x_j < x_i$ must be held. Let's build another graph. for every restriction $x_i < x_j$, add a directed edge from $i$ to $j$. After that, if the graph has one or more cycles, the answer is obviously \"NO\". Otherwise, we can do topological sort and the ordering is one possible solution of $x$ in decreasing order. Total Complexity: $\\mathcal{O}(n + m)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 200001;\n\nstruct edge {\n    int type, u, v;\n};\n\nvector <int> adj[N];\nint col[N], topo[N];\n\nvoid dfs(int v) {\n    for (int u : adj[v]) if (col[u] == -1) {\n        col[u] = col[v] ^ 1;\n        dfs(u);\n    }\n}\n\nbool BipartiteColoring(int n) {\n    for (int i = 1; i <= n; ++i)\n        col[i] = -1;\n    for (int i = 1; i <= n; ++i) if (col[i] == -1) {\n        col[i] = 0;\n        dfs(i);\n    }\n    for (int i = 1; i <= n; ++i) for (int j : adj[i]) {\n        if (col[i] == col[j]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool TopologicalSort(int n) {\n    vector <int> in(n + 1, 0);\n    for (int i = 1; i <= n; ++i) for (int j : adj[i]) {\n        in[j]++;\n    }\n    queue <int> q;\n    for (int i = 1; i <= n; ++i) if (in[i] == 0) {\n        q.push(i);\n    }\n    int ord = 0;\n    while (!q.empty()) {\n        int v = q.front(); q.pop();\n        topo[v] = ord++;\n        for (int u : adj[v]) {\n            in[u]--;\n            if (in[u] == 0) {\n                q.push(u);\n            }\n        }\n    }\n    return ord == n;\n}\n\nint main () {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int n, m;\n    cin >> n >> m;\n    vector <edge> a(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> a[i].type >> a[i].u >> a[i].v;\n        adj[a[i].u].push_back(a[i].v);\n        adj[a[i].v].push_back(a[i].u);\n    }\n    if (!BipartiteColoring(n)) {\n        cout << \"NO\" << endl;\n        return 0;\n    }\n    // col = 0 -> orient left, col = 1 -> orient right\n    for (int i = 1; i <= n; ++i) {\n        adj[i].clear();\n    }\n    for (edge e : a) {\n        if (col[e.u] == 1)\n            swap(e.u, e.v);\n        if (e.type == 1) {\n            adj[e.u].push_back(e.v);\n        } else {\n            adj[e.v].push_back(e.u);\n        }\n    }\n    if (!TopologicalSort(n)) {\n        cout << \"NO\" << endl;\n        return 0;\n    }\n    cout << \"YES\" << endl;\n    for (int i = 1; i <= n; ++i) {\n        cout << (col[i] == 0 ? \"L \" : \"R \") << topo[i] << endl;\n    }\n}",
    "tags": [
      "2-sat",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1635",
    "index": "F",
    "title": "Closest Pair ",
    "statement": "There are $n$ weighted points on the $OX$-axis. The coordinate and the weight of the $i$-th point is $x_i$ and $w_i$, respectively. All points have distinct coordinates and positive weights. Also, $x_i < x_{i + 1}$ holds for any $1 \\leq i < n$.\n\nThe weighted distance between $i$-th point and $j$-th point is defined as $|x_i - x_j| \\cdot (w_i + w_j)$, where $|val|$ denotes the absolute value of $val$.\n\nYou should answer $q$ queries, where the $i$-th query asks the following: Find the \\textbf{minimum} weighted distance among all pairs of distinct points among the points in subarray $[l_i,r_i]$.",
    "tutorial": "First of all, let's solve the problem for the whole array. Define $L_i$ as the biggest $j$ satisfying $j < i$ and $w_j \\leq w_i$, and $R_i$ as the smallest $j$ satisfying $j > i$ and $w_j \\leq w_i$. Then, we consider $2n$ pairs of points: $(L_i, i)$ and $(i, R_i)$ for each $1 \\leq i \\leq n$. In conclusion, the closest pair (the pair with the minimum weighted distance) must be among them. Proof: Assume that $(a, b)$ is the closest pair and $a < b$. If $w_a \\leq w_b$ holds, then $a = L_b$ must holds, otherwise $(a, L_b)$ would obviously be a better pair. Similarly, if $w_a > w_b$ holds, then $b = R_a$ must holds, otherwise $(R_a, b)$ would obviously be a better pair. The lemma above also applies to range queries by the exact same proof. So now, we first need to find $L_i$ and $R_i$ for each $1 \\leq i \\leq n$, this could be simply done with a stack. Then, imagine we draw lines between the endpoints of each pair, and the problem could be reduced to: given $2n$ weighted segments, for each query $i$ find the one with the minimum weight that is totally covered by $[l_i, r_i]$. This is actually a classic problem, which could be solved by sweep line trick + any data structure able to maintain prefix-minimum with single point updates, like BIT or segment tree. Total Complexity: $\\mathcal{O}((n+q)\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 300005;\nconst long long INF = 1ll << 62;\n\nvector <int> useful_pair[N];\nvector <pair <int, int>> queries[N];\n\nlong long bit[N];\n\nvoid modify(int p, long long v) {\n    for (int i = p; i > 0; i -= i & (-i)) {\n        bit[i] = min(bit[i], v);\n    }\n}\n\nlong long query(int p) {\n    long long ans = INF;\n    for (int i = p; i < N; i += i & (-i)) {\n        ans = min(ans, bit[i]);\n    }\n    return ans;\n}\n\nint main () {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int n, q;\n    cin >> n >> q;\n    vector <int> x(n), w(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> x[i] >> w[i];\n    }\n    for (int i = 0, l, r; i < q; ++i) {\n        cin >> l >> r, --l;\n        queries[r].emplace_back(l, i);\n    }\n    stack <int> stk;\n    for (int i = 0; i < n; ++i) {\n        while (!stk.empty() && w[stk.top()] > w[i]) {\n            stk.pop();\n        }\n        if (!stk.empty()) {\n            int x = stk.top();\n            useful_pair[i].push_back(x);\n        }\n        stk.push(i);\n    }\n    while (!stk.empty()) {\n        stk.pop();\n    }\n    for (int i = n - 1; ~i; --i) {\n        while (!stk.empty() && w[stk.top()] > w[i]) {\n            stk.pop();\n        }\n        if (!stk.empty()) {\n            int x = stk.top();\n            useful_pair[x].push_back(i);\n        }\n        stk.push(i);\n    }\n    fill(bit, bit + N, INF);\n    vector <long long> ans(q);\n    for (int r = 1; r <= n; ++r) {\n        for (int l : useful_pair[r - 1]) {\n            long long val = 1ll * (x[r - 1] - x[l]) * (w[l] + w[r - 1]);\n            modify(l + 1, val);\n        }\n        for (auto [l, id] : queries[r]) {\n            ans[id] = query(l + 1);\n        }\n    }\n    for (int i = 0; i < q; ++i) {\n        cout << ans[i] << endl;\n    }\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1637",
    "index": "A",
    "title": "Sorting Parts",
    "statement": "You have an array $a$ of length $n$. You can \\textbf{exactly} once select an integer $len$ between $1$ and $n - 1$ inclusively, and then sort in non-decreasing order the prefix of the array of length $len$ and the suffix of the array of length $n - len$ independently.\n\nFor example, if the array is $a = [3, 1, 4, 5, 2]$, and you choose $len = 2$, then after that the array will be equal to $[1, 3, 2, 4, 5]$.\n\nCould it be that after performing this operation, the array will \\textbf{not} be sorted in non-decreasing order?",
    "tutorial": "Consider two cases: The array is already sorted. THe array is not sorted. In the first case, sorting any prefix and any suffix does not change the array. So the array will always remain sorted so the answer is \"NO\". In the second case, there are two elements with indexes $i$ and $j$, such that $i < j$ and $a_i > a_j$. So choose $len$ so that these two elements will be in different parts. For example - $len = i$. Note that after operation $a_i$ will remain to the left of $a_j$, which means the array will not be sorted. So the answer is \"YES\". Then the solution is to check if the array is sorted, which can be done in $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (auto& u : a)\n            cin >> u;\n        if (!is_sorted(a.begin(), a.end()))\n            cout << \"YES\\n\";\n        else\n            cout << \"NO\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1637",
    "index": "B",
    "title": "MEX and Array",
    "statement": "Let there be an array $b_1, b_2, \\ldots, b_k$. Let there be a partition of this array into segments $[l_1; r_1], [l_2; r_2], \\ldots, [l_c; r_c]$, where $l_1 = 1$, $r_c = k$, and for any $2 \\leq i \\leq c$ holds that $r_{i-1} + 1 = l_i$. In other words, each element of the array belongs to exactly one segment.\n\nLet's define the cost of a partition as $$c + \\sum_{i = 1}^{c} \\operatorname{mex}(\\{b_{l_i}, b_{l_i + 1}, \\ldots, b_{r_i}\\}),$$ where $\\operatorname{mex}$ of a set of numbers $S$ is the smallest non-negative integer that does not occur in the set $S$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $b_1, b_2, \\ldots, b_k$ as the \\textbf{maximum} possible cost over all partitions of this array.\n\nYou are given an array $a$ of size $n$. Find the sum of values of all its subsegments.\n\nAn array $x$ is a subsegment of an array $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "We show, that replacing a segment of length $k$ ($k > 1$) with segments of length $1$ does not decrease the cost of the partition. Consider two cases: The segment does not contain $0$. The segment contains $0$. In the first case the contribution of the segment equals to $1$ (because $mex = 0$), but the contribution of $k$ segments of length $1$ equals to $k$. So the cost increased. In the second case the contribution of the segment equals to $1 + mex <= 1 + k$, but the contribution of the segments of length $1$ would be at least $1 + k$, so the cost has not decreased. Then it is possible to replace all segments of length more than $1$ by segments of length $1$ and not decrease the cost. So the value of the array $b_1, b_2, \\ldots, b_k$ equals to $\\sum_{i=1}^{k}{(1 + mex(\\{b_i\\}))}$ = $k$ + (the number of zeros in the array). To calculate the total $value$ of all subsegments, you need to calculate the total length of all subsegments and the contribution of each $0$. The total length of all subsegments equals to $\\frac{n \\cdot (n + 1) \\cdot (n + 2)}{6}$. The contribution of a zero in the position $i$ equals to $i \\cdot (n - i + 1)$. This solution works in $O(n)$, but it could be implemented less efficiently. There is also another solution, which uses dynamic programming: let $dp_{l, r}$ is the value of the array $a_l, a_{l + 1}, \\ldots, a_r$. Then $dp_{l, r} = max(1 + mex(\\{a_l, a_{l + 1}, \\ldots, a_r\\}), \\max_{c = l}^{r - 1} (dp_{l, c} + dp_{c + 1, r}))$. This solution can be implemented in $O(n^3)$ or in $O(n^4)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (auto& u : a)\n            cin >> u;\n \n        int ans = 0;\n        for (int i = 0; i < n; i++) {\n            ans += (i + 1) * (n - i);\n            if (a[i] == 0)\n                ans += (i + 1) * (n - i);\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1637",
    "index": "C",
    "title": "Andrew and Stones",
    "statement": "Andrew has $n$ piles with stones. The $i$-th pile contains $a_i$ stones. He wants to make his table clean so he decided to put every stone either to the $1$-st or the $n$-th pile.\n\nAndrew can perform the following operation any number of times: choose $3$ indices $1 \\le i < j < k \\le n$, such that the $j$-th pile contains at least $2$ stones, then he takes $2$ stones from the pile $j$ and puts one stone into pile $i$ and one stone into pile $k$.\n\nTell Andrew what is the minimum number of operations needed to move all the stones to piles $1$ and $n$, or determine if it's impossible.",
    "tutorial": "Consider $2$ cases when the answer is $-1$ for sure: For all $1 < i < n$: $a_i = 1$. In this case, it's not possible to make any operation and not all stones are in piles $1$ or $n$. $n = 3$ and $a_2$ is odd. Then after any operation this number will remain odd, so it can never become equal to $0$. Later it will become clear why these are the only cases where the answer is $-1$. To show it consider the following algorithm: If all stones are in piles $1$ and $n$ then the algorithm is done. If there is at least one non-zero even element (piles $1$ and $n$ don't count), then subtract $2$ from it, add $1$ to the odd number to the left or to the pile $1$ if there's no such number. Similarly add $1$ to the odd number to the right or to the pile $n$ if there's no such number. Then continue the algorithm. Note that the number of odd elements after it (piles $1$ and $n$ don't count) decreases at least by $1$ (if there was any odd number). Also either a new even number has appeared, or the algorithm will be done. If all remaining non-zero numbers are odd, then there is at least one odd number greater than $1$. So let's subtract $2$ from this element and add ones similar to the $2$-nd case. In this case the number of odd elements decreases at least by $1$. From the notes written in the second and third cases, it follows that the algorithm always puts all stones to the piles $1$ and $n$. Also note that if in the initial array the element in position $i$ ($1 < i < n$) was even, then the algorithm did not add any $1$ to it, so the number of operations with the center in $i$ equals to $\\frac{a_i}{2}$. And if $a_i$ was odd, the algorithm will add $1$ to this element exactly once, so the number of operations with the center in $i$ equals to $\\frac{a_i + 1}{2}$. This algorithm is optimal because for each odd number it's necessary to add at least $1$ to it and the algorithm adds exactly $1$. And from even elements the algorithm can only subtract. It means that the answer to the problem equals to $\\sum_{i=2}^{n-1} \\lceil \\frac{a_i}{2} \\rceil$. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (auto &x : a)\n        cin >> x;\n \n    if (*max_element(a.begin() + 1, a.end() - 1) == 1 || (n == 3 && a[1] % 2 == 1)) {\n        cout << \"-1\\n\";\n        return;\n    }\n \n    long long answer = 0;\n    for (int i = 1; i < n - 1; i++)\n        answer += (a[i] + 1) / 2;\n \n    cout << answer << '\\n';\n}\n \nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    int tests;\n    cin >> tests;\n    while (tests--)\n        solve();\n}\n",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1637",
    "index": "D",
    "title": "Yet Another Minimization Problem",
    "statement": "You are given two arrays $a$ and $b$, both of length $n$.\n\nYou can perform the following operation any number of times (possibly zero): select an index $i$ ($1 \\leq i \\leq n$) and swap $a_i$ and $b_i$.\n\nLet's define the cost of the array $a$ as $\\sum_{i=1}^{n} \\sum_{j=i + 1}^{n} (a_i + a_j)^2$. Similarly, the cost of the array $b$ is $\\sum_{i=1}^{n} \\sum_{j=i + 1}^{n} (b_i + b_j)^2$.\n\nYour task is to minimize the total cost of two arrays.",
    "tutorial": "The $cost$ of the array $a$ equals to $\\sum_{i=1}^{n} \\sum_{j=i + 1}^{n} (a_i + a_j)^2 = \\sum_{i=1}^{n} \\sum_{j=i + 1}^{n} (a_i^2 + a_j^2 + 2a_i a_j)$. Let $s = \\sum_{i=1}^{n} a_i$. Then $cost = (n - 1) \\cdot \\sum_{i=1}^{n} a_i^2 + \\sum_{i=1}^n (a_i \\cdot (s - a_i)) = (n - 1) \\cdot \\sum_{i=1}^{n} a_i^2 + s^2 - \\sum_{i=1}^{n} a_i^2 = (n - 2) \\cdot \\sum_{i=1}^{n} a_i^2 + (\\sum_{i=1}^n a_i)^2$. Then the total cost of two arrays equals to $(n - 2) \\cdot \\sum_{i=1}^{n} (a_i^2 + b_i^2) + (\\sum_{i=1}^n a_i)^2 + (\\sum_{i=1}^n b_i)^2$. The first term is a constant $\\Rightarrow$ we need to minimize $(\\sum_{i=1}^n a_i)^2 + (\\sum_{i=1}^n b_i)^2$. There are two continuations of the solution, but the idea of both is to iterate over all possible sum of the array $a$, then calculate the sum of the array $b$ and update the answer using formula written above: Let $dp_{i, w}$ is true if it's possible to make some operations so that the sum of first $i$ elements in the array $a$ equals to $w$, otherwise $dp_{i, w}$ is false. Then $dp_{1, a_1} = dp_{1, b_1} =$ true. For $i > 1$: $dp_{i, w} = dp_{i-1, w-a_i}$ or $dp_{i-1, w-b_i}$. Then to iterate over all possible sums of the array $a$ you need to consider such $s$, that $dp_{n, s} =$ true. Assume, that we have $n$ items, where $i$-th item has a weight of $|b_i - a_i|$. By solving simple backpack problem let's find all possible sums of weights of these items. And if the sum contains $i$-th item, then we will assume that $a_i \\ge b_i$, otherwise $a_i \\le b_i$. So if the sum of weights of some items equals to $s$, then the sum of the array $a$ equals to $\\sum_{i=1}^n min(a_i, b_i) + s$. So all possible sums of the array $a$ can be received from all possible sums of weights of these items. Both solutions works in $O(n^2 \\cdot maxA)$ where $maxA = 100$, and both solutions can be optimized with std::bitest, speeding up them by $64$ times, but it wasn't necessary.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconstexpr int MAXSUM = 100 * 100 + 10;\n \nint sqr(int x) {\n    return x * x;\n}\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n);\n    for (auto& u : a)\n        cin >> u;\n \n    for (auto& u : b)\n        cin >> u;\n \n    int sumMin = 0, sumMax = 0, sumSq = 0;\n    for (int i = 0; i < n; i++) {\n        if (a[i] > b[i])\n            swap(a[i], b[i]);\n \n        sumSq += sqr(a[i]) + sqr(b[i]);\n        sumMin += a[i];\n        sumMax += b[i];\n    }\n \n    bitset<MAXSUM> dp;\n    dp[0] = 1;\n    for (int i = 0; i < n; i++)\n        dp |= dp << (b[i] - a[i]);\n \n    int ans = sqr(sumMin) + sqr(sumMax);\n    for (int i = 0; i <= sumMax - sumMin; i++)\n        if (dp[i])\n            ans = min(ans, sqr(sumMin + i) + sqr(sumMax - i));\n \n    cout << sumSq * (n - 2) + ans << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}\n",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1637",
    "index": "E",
    "title": "Best Pair",
    "statement": "You are given an array $a$ of length $n$. Let $cnt_x$ be the number of elements from the array which are equal to $x$. Let's also define $f(x, y)$ as $(cnt_x + cnt_y) \\cdot (x + y)$.\n\nAlso you are given $m$ bad pairs $(x_i, y_i)$. Note that if $(x, y)$ is a bad pair, then $(y, x)$ is also bad.\n\nYour task is to find the maximum value of $f(u, v)$ over all pairs $(u, v)$, such that $u \\neq v$, that this pair is not bad, and also that $u$ and $v$ each occur in the array $a$. It is guaranteed that such a pair exists.",
    "tutorial": "Let's fix $x$ and iterate over $cnt_y \\le cnt_x$. Then we need to find maximum $y$ over all elements that occurs exactly $cnt_y$ times, such that $x \\neq y$ and pair $(x, y)$ is not bad. To do that, we will just iterate over all elements that occurs exactly $cnt_y$ times in not increasing order, while pair $(x, y)$ is bad or $x = y$. If we find such $y$ then we will update the answer. To check if the pair is bad, just add all pairs into the set, and check is the pair is in the set. Also you can sort all bad pairs and check it using binary search. Both methods works in $O(\\log{n})$. Iterating over all $x$ and $cnt_y \\le cnt_x$ works in $O(\\sum cnt_x) = O(n)$. And finding maximum $y$ such that $x \\neq y$ and the pair $(x, y)$ is not bad works in $O((n + m) \\log{m})$ summary, because there are $O(n + m)$ checks if the pair is bad or not. So this solution works in $O((n + m) \\log{m} + n \\log{n}).$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n);\n    map<int, int> cnt;\n    for (auto &x : a) {\n        cin >> x;\n        cnt[x]++;\n    }\n \n    vector<pair<int, int>> bad_pairs;\n    bad_pairs.reserve(2 * m);\n    for (int i = 0; i < m; i++) {\n        int x, y;\n        cin >> x >> y;\n        bad_pairs.emplace_back(x, y);\n        bad_pairs.emplace_back(y, x);\n    }\n    sort(bad_pairs.begin(), bad_pairs.end());\n \n    vector<vector<int>> occ(n);\n    for (auto &[x, c] : cnt)\n        occ[c].push_back(x);\n \n    for (auto &v : occ)\n        reverse(v.begin(), v.end());\n \n    long long answer = 0;\n    for (int cnt_x = 1; cnt_x < n; cnt_x++)\n        for (int x : occ[cnt_x])\n            for (int cnt_y = 1; cnt_y <= cnt_x; cnt_y++)\n                for (auto y : occ[cnt_y])\n                    if (x != y && !binary_search(bad_pairs.begin(), bad_pairs.end(), pair<int, int>{x, y})) {\n                        answer = max(answer, 1ll * (cnt_x + cnt_y) * (x + y));\n                        break;\n                    }\n \n    cout << answer << '\\n';\n}\n \nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    int tests;\n    cin >> tests;\n    while (tests--)\n        solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1637",
    "index": "F",
    "title": "Towers",
    "statement": "You are given a tree with $n$ vertices numbered from $1$ to $n$. The height of the $i$-th vertex is $h_i$. You can place any number of towers into vertices, for each tower you can choose which vertex to put it in, as well as choose its efficiency. Setting up a tower with efficiency $e$ costs $e$ coins, where $e > 0$.\n\nIt is considered that a vertex $x$ gets a signal if for some pair of towers at the vertices $u$ and $v$ ($u \\neq v$, but it is allowed that $x = u$ or $x = v$) with efficiencies $e_u$ and $e_v$, respectively, it is satisfied that $\\min(e_u, e_v) \\geq h_x$ and $x$ lies on the path between $u$ and $v$.\n\nFind the minimum number of coins required to set up towers so that you can get a signal at all vertices.",
    "tutorial": "Main solution: Let's consider all leaves. If $v$ is a leaf, then all paths, which cover $v$ should start in $v$. Then let's increase heights of all towers in the leaves by $1$ (it's necessary) and decrease all $h_v$ by $1$. Now we should remove all leaves with $h_v = 0$ (they will be already covered). We will repeat the operation until there are covered leaves. We will continue the algorithm but instead of increasing height in new leaves of the tree we will increase height in deleted vertexes (in its subtree). If at some point we have only 1 vertex left we should increase height in $2$ towers (due to the statement we should use $2$ different towers to cover the vertex). To speed up the solution we will sort vertexes by $h_v$ and we will store current level of current leaves. On each iteration we will add amount of leaves multiplied by change of level. If it is not optimal then let's consider heights of towers in the optimal answer. Let $f(i)$ be amount of vertices in optimal answer with height larger or equal to $i$. It is easy to notice that $f(i) - f(i - 1)$ is at least amount of leaves in the tree on $i$-th iteration. If there is only one vertex left on iteration $i$ then $2 = f(i) - f(i - 1)$. That means that the algorithm is optimal. Alternative solution: Let $root$ be the vertex with the maximum height. Let's root tree at $root$. Now there must be two towers in the subtrees of the children of vertex $root$ of height $h_{root}$ (if there's only one child, then there must be a tower at the vertex $root$ of height $h_{root}$). Now we need to place towers in the subtrees of the children of vertex $root$, such that for for every vertex $v$ the highest tower in the subtree of vertex $v$ (including $v$) must be at least $h_v$. After it's done you need to select two highest towers in the subtrees of two different child of the vertex $root$ and set their height to $h_{root}$. Now we need to optimally place towers in the subtrees so that for every vertex $v$ there must be a tower in the subtree of vertex $v$ of height at least $h_v$. To do that in the subtree of vertex $v$, let's recursively place towers in the subtrees of the children of vertex $v$, and then increase the height of the highest tower in the subtree of $v$ to $h_v$ if it's necessary. If vertex $v$ is a leaf then we need to place a tower of height $h_v$ in the vertex $v$. This solutions can be implemented in $O(n)$. For a better understanding, we recommend you to see the implementation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntypedef long long ll;\n \nint main() {\n  ios_base::sync_with_stdio(false); cin.tie(0);\n  int n;\n  cin >> n;\n  vector<int> h(n);\n  for (int i = 0; i < n; ++i) cin >> h[i];\n  vector<vector<int>> g(n);\n  for (int i = 0; i + 1 < n; ++i) {\n    int u, v;\n    cin >> u >> v;\n    --u, --v;\n    g[u].push_back(v);\n    g[v].push_back(u);\n  }\n  int rt = 0;\n  for (int i = 0; i < n; ++i) {\n    if (h[i] > h[rt]) {\n      rt = i;\n    }\n  }\n  ll ans = 0;\n  function<int(int, int)> dfs = [&](int u, int p) {\n    int mx1 = 0, mx2 = 0;\n    vector<int> have;\n    for (auto v : g[u]) {\n      if (v != p) {\n        int cur = dfs(v, u);\n        if (cur > mx1) swap(cur, mx1);\n        if (cur > mx2) swap(cur, mx2);\n      }\n    }\n    if (p != -1) {\n      int delta = max(0, h[u] - mx1);\n      ans += delta;\n      mx1 += delta;\n    } else {\n      ans += max(0, h[u] - mx1) + max(0, h[u] - mx2);\n    }\n    return mx1;\n  };\n  dfs(rt, -1);\n  cout << ans << '\\n';\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1637",
    "index": "G",
    "title": "Birthday",
    "statement": "Vitaly gave Maxim $n$ numbers $1, 2, \\ldots, n$ for his $16$-th birthday. Maxim was tired of playing board games during the celebration, so he decided to play with these numbers. In one step Maxim can choose two numbers $x$ and $y$ from the numbers he has, throw them away, and add two numbers $x + y$ and $|x - y|$ instead. He wants all his numbers to be equal after several steps and the sum of the numbers to be minimal.\n\nHelp Maxim to find a solution. Maxim's friends don't want to wait long, so the number of steps in the solution should not exceed $20n$. It is guaranteed that under the given constraints, if a solution exists, then there exists a solution that makes all numbers equal, minimizes their sum, and spends no more than $20n$ moves.",
    "tutorial": "The answer is $-1$ only if $n = 2$. It will become clear later. Let all numbers be equal to $val$ after all steps. Consider the moves in reverse order: numbers $x$ and $y$ are obtained from $\\frac{x + y}{2}$ and $\\frac{|x - y|}{2}$. If numbers $x$ and $y$ are multiples of an odd number $p > 1$, then numbers $\\frac{x + y}{2}$ and $\\frac{|x - y|}{2}$ are also multiples of $p$. But after all steps in reverse order, we need to get $1$ $\\Rightarrow$ $val$ can't be a multiple of $p$. It means that $val$ is a power of two. Moreover $val \\ge n$ because the maximum after all steps in direct order can't get smaller. Let's show how to make all numbers equal to the smallest power of two which is at least $n$. First of all, let's transform numbers $1, 2, \\ldots, n$ into the $n$ powers of two (maybe different), but not greater than the answer. Let the function $solve(n)$ do this. It can be implemented as follows: If $n \\le 2$ then all numbers are already a power of two so we can finish the function. if $n$ is a power of two, then call $solve(n - 1)$ and finish the function. Otherwise let's $p$ be the maximum power of two not exceeding $n$. Lets make steps by choosing pairs $(p - 1, p + 1), (p - 2, p + 2), \\ldots, (p - (n - p), p + (n - p))$. After that, there will be numbers that can be divided into $3$ groups: Numbers that have not been changed: $1, 2, \\ldots, p - (n - p) - 1$ and $p$. $p$ is already a power of two. To transform other numbers into the powers of two let's call $solve(p - (n - p) - 1)$. Numbers that have been obtained as $|x - y|$ after some step: $2, 4, \\ldots, 2 \\cdot (n - p)$. To transform them into the powers of two we can take the sequence of steps that does $solve(n - p)$ and multiply all numbers in these steps by $2$. All numers that have been obtained as $x + y$ after some step, are equal to $2p$ and they are already a power of two. Numbers that have not been changed: $1, 2, \\ldots, p - (n - p) - 1$ and $p$. $p$ is already a power of two. To transform other numbers into the powers of two let's call $solve(p - (n - p) - 1)$. Numbers that have been obtained as $|x - y|$ after some step: $2, 4, \\ldots, 2 \\cdot (n - p)$. To transform them into the powers of two we can take the sequence of steps that does $solve(n - p)$ and multiply all numbers in these steps by $2$. All numers that have been obtained as $x + y$ after some step, are equal to $2p$ and they are already a power of two. After this transformation, there are always two equal numbers that are smaller than the answer. Let them be equal to $x$. Let's make a step using them and we will get $0$ and $2x$. From numbers $0$ and $x$ we can get numers $0$ and $2x$: $(0, x) \\rightarrow (x, x) \\rightarrow (0, 2x)$. So let's just use this $0$ to transform all remaining numbers into the answer. After all, let's make a step using $0$ and the answer, so $0$ becomes equal to the answer. It is obvious, that this solution works at most in $O(n \\cdot \\log{n})$. But at such limits it uses at most $7n$ steps.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvector<pair<int, int>> ops;\nvector<int> a;\n \nvoid rec(int n, int coeff) {\n    if (n <= 2) {\n        for (int i = 1; i <= n; i++)\n            a.push_back(i * coeff);\n        return;\n    }\n \n    int p = 1;\n    while (p * 2 <= n) p *= 2;\n \n    if (p == n) {\n        a.push_back(n * coeff);\n        n--, p /= 2;\n    }\n \n    a.push_back(p * coeff);\n    for (int i = p + 1; i <= n; i++) {\n        a.push_back(2 * p * coeff);\n        ops.emplace_back(i * coeff, (2 * p - i) * coeff);\n    }\n \n    rec(2 * p - n - 1, coeff);\n    rec(n - p, coeff * 2);\n}\n \nvoid solve() {\n    int n;\n    cin >> n;\n    if (n == 2) {\n        cout << \"-1\\n\";\n        return;\n    }\n \n    ops.clear();\n    a.clear();\n    rec(n, 1);\n    sort(a.begin(), a.end());\n \n    int answer = 1;\n    while (answer < n)\n        answer *= 2;\n \n    for (int i = 0;; i++)\n        if (a[i] == a[i + 1]) {\n            assert(a[i] != answer);\n            ops.emplace_back(a[i], a[i]);\n            a[i + 1] *= 2;\n            a.erase(a.begin() + i);\n            break;\n        }\n \n    for (auto x : a)\n        while (x != answer) {\n            ops.emplace_back(0, x);\n            ops.emplace_back(x, x);\n            x *= 2;\n        }\n \n    ops.emplace_back(0, answer);\n    cout << ops.size() << '\\n';\n    for (auto &[x, y] : ops)\n        cout << x << ' ' << y << '\\n';\n}\n \nint main() {\n    int tests;\n    cin >> tests;\n    while (tests--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1637",
    "index": "H",
    "title": "Minimize Inversions Number",
    "statement": "You are given a permutation $p$ of length $n$.\n\nYou can choose any subsequence, remove it from the permutation, and insert it at the beginning of the permutation keeping the same order.\n\nFor every $k$ from $0$ to $n$, find the minimal possible number of inversions in the permutation after you choose a subsequence of length exactly $k$.",
    "tutorial": "To simplify the explanation, we will represent a permutation as a set of points $(i, p_i)$. $\\bf{Lemma}$: Let's consider some selected subsequence. Then there always exists such sequence of the same length, so that if we select it instead, the number of inversions won't increase, for which the following condition is satisfied: if the point $i$ is selected, then all points to the right and below point $i$ are also selected. $\\bf{Proof}$: Let assume that it's not right, then there is a pair of points $(i, j)$ such that $i$ is selected and $j$ is not, and j is to the right and below point $i$ (the point is selected if it is in the sequence). Let's call such pair a bad pair. Divide the points into 9 regions by 4 straight lines parallel to the coordinate axes passing through the point $i$ and $j$. No for every point, considering if it is selected or not and considering the region where it is, let's determine by how many it reduces the number of inversions after replacing $i$ with $j$ (i.e. select $j$ instead of $i$). Let's call it a contribution of this point. Also note that after replacing the point $i$ with the point $j$, the inversion formed by these two points disappears. The first integer in each region - the contribution of the point selected there. The second integer - the contribution of unselected one. Note that negative contribution has only selected points, located between the point $i$ and $j$ (on the $Ox$ axis) above the point $i$, and unselected points located between the point $i$ and $j$ below the point $j$. Now let's find any bad pair $(i, j)$ and do the following: If there is a selected point $id$, which has negative contribution, then set $i = id$ and continue the algorithm. Otherwise, if there is a unselected point $id$, which has negative contribution, then set $j = id$ and continue the algorithm. Otherwise, after replacing the point $i$ with the point $j$ the number of inversions will reduce. This algorithm always finds a bad pair such that after replacing $i$ with $j$ the number of inversions will reduce, because each time the value $j - i$ reduces. Q.E.D. Let $d_i$ is a number by which the number of inversions will decrease after moving only the element with index $i$ to the beginning. Then $d_i =$ (the number of points to the left and above i$) - ($the number of points to the left and below i). Then, if sequence $seq$ is selected, then the number of inversions in a new permutation will be equal to $invs - \\sum_{i \\in seq} d_i + seqInvs - (\\frac{|seq| \\cdot (|seq| - 1)}{2} - seqInvs) = invs - \\sum_{i \\in seq} d_i + 2 \\cdot seqInvs - \\frac{|seq| \\cdot (|seq| - 1)}{2}$. Here $invs$ - the number of inversions in the initial permutation, and $seqInvs$ - the number of inversions over all elements in the $seq$. $seqInvs = \\sum_{i \\in seq}$ (the number of selected points to the right and below $i$). Due to the lemma proved above, if the sequence $seq$ is optimal, then if the point $i$ is selected, then $\\Rightarrow$ all points to the right and below $i$ are selected as well, so if $s_i$ is the number of points to the right and below $i$, then $seqInvs = \\sum_{i \\in seq} s_i$. So the number of inversions in the new permutation equals to $invs - \\sum_{i \\in seq} (d_i - 2s_i) - \\frac{|seq| \\cdot (|seq| - 1)}{2}$. Note, that this formula can be incorrect if the sequence is not optimal. In this case point $i$ reduces the number of inversions by $c_i = d_i - 2s_i$. Note that the number of points to the left and below $i$ equals to $p_i - 1 - s_i$, and the number of points to the left and above $i$ equals to $(i - 1) - (p_i - 1 - s_i) = i - p_i + s_i$. So $d_i = (i - p_i + s_i) - (p_i - 1 - s_i) = i - 2p_i + 2s_i + 1$. So $c_i = d_i - 2s_i = i - 2p_i + 1$. Now it's not hard to see, that if the point $j$ is to the left and below the point $i$, then $c_j > c_i$. So if we select $len$ maximum elements by the value of $c_i$, the formula for the number of inversions written above is correct. It means that it is optimal. It can be implemented in $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nstruct binary_index_tree {\n    int n;\n    vector<int> bit;\n \n    binary_index_tree(int n) : n(n), bit(n + 1) {}\n \n    void increase(int pos) {\n        for (pos++; pos <= n; pos += pos & -pos)\n            bit[pos]++;\n    }\n \n    int query(int pref) const {\n        int sum = 0;\n        for (; pref; pref -= pref & -pref)\n            sum += bit[pref];\n \n        return sum;\n    }\n};\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    vector<int> d(n);\n    binary_index_tree bit(n);\n    long long inversions = 0;\n \n    for (int i = 0; i < n; i++) {\n        int p;\n        cin >> p;\n        p--;\n \n        d[i] = i - 2 * p;\n        inversions += i - bit.query(p);\n        bit.increase(p);\n    }\n    sort(d.rbegin(), d.rend());\n \n    cout << inversions;\n    long long sum = 0;\n    for (int i = 0; i < n; i++) {\n        sum += d[i];\n        cout << ' ' << inversions - sum - 1ll * i * (i + 1) / 2;\n    }\n \n    cout << '\\n';\n}\n \nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n \n    int tests;\n    cin >> tests;\n    while (tests--)\n        solve();\n}",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1638",
    "index": "A",
    "title": "Reverse",
    "statement": "You are given a permutation $p_1, p_2, \\ldots, p_n$ of length $n$. You have to choose two integers $l,r$ ($1 \\le l \\le r \\le n$) and reverse the subsegment $[l,r]$ of the permutation. The permutation will become $p_1,p_2, \\dots, p_{l-1},p_r,p_{r-1}, \\dots, p_l,p_{r+1},p_{r+2}, \\dots ,p_n$.\n\nFind the lexicographically smallest permutation that can be obtained by performing \\textbf{exactly} one reverse operation on the initial permutation.\n\nNote that for two distinct permutations of equal length $a$ and $b$, $a$ is lexicographically smaller than $b$ if at the first position they differ, $a$ has the smaller element.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "When is it best for the permutation to remain unchanged? What elements are obviously optimal and should remain as they are? Find the first non-optimal element. What's the best way to fix it? Let $p_i$ be the first element such that $p_i \\neq i$. For the prefix of elements $p_1=1,p_2=2, \\dots ,p_{i-1}=i-1$ we do not need to change anything because it is already the minimum lexicographic, but we would like to have $i$ instead of $p_i$ on that position. The solution is to reverse segment $[i,j]$, where $p_j=i$. Notice that $i<j$ since $p_k=k$ for every $k<i$, so $p_k<p_j=i$ for every $k<i$. Time complexity: $O(n)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1638",
    "index": "B",
    "title": "Odd Swap Sort",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$. You can perform operations on the array. In each operation you can choose an integer $i$ ($1 \\le i < n$), and swap elements $a_i$ and $a_{i+1}$ of the array, if $a_i + a_{i+1}$ is odd.\n\nDetermine whether it can be sorted in non-decreasing order using this operation any number of times.",
    "tutorial": "Replace the condition \"$a_i+a_{i+1}$ is odd\" with something easier to work with. The condition means that we only swap elements of different parity. Now, make some observations. What happens if there are some elements $a_i$ and $a_j$ ($i<j$) of the same parity, such that $a_i>a_j$? If such pair exists, the answer is \"NO\". Now consider the array to be a merge between two increasing arrays (one with odd elements, one with even elements). Try to prove that the answer is always \"YES\" in this case. What does the Bubble Sort algorithm do here? Does it ever do an illegal swap? The condition \"$a_i + a_{i+1}$ is odd\" means that we can only swap elements of different parity. If either the order of even elements or the order of odd elements is not non-decreasing, then it is impossible to sort the sequence. Otherwise, let's prove that it is always possible to sort the sequence. We can for example perform Bubble Sort algorithm. Note that this algorithm only swaps elements $a_i$ and $a_{i+1}$ if $a_i > a_{i+1}$, so it will never swap two elements of the same parity (given our assumption on their order). Time complexity: $O(n)$.",
    "tags": [
      "data structures",
      "math",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1638",
    "index": "C",
    "title": "Inversion Graph",
    "statement": "You are given a permutation $p_1, p_2, \\dots, p_n$. Then, an undirected graph is constructed in the following way: add an edge between vertices $i$, $j$ such that $i < j$ if and only if $p_i > p_j$. Your task is to count the number of connected components in this graph.\n\nTwo vertices $u$ and $v$ belong to the same connected component if and only if there is at least one path along edges connecting $u$ and $v$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "The key idea is to start merging from the beginning using a stack. Assume that the connected components are always segments in the permutation (this solution also proves this by induction). We will iterate the prefix and maintain in our stack the minimum/maximum element of all the segments in order. When we increase the prefix adding the next position $i$, we add $(p_i, p_i)$ to the top of the stack. Then, we merge the top two segments while we are able to. If the top two segments have their minimum/maximum elements $(min_1, max_1)$ and $(min_2, max_2)$, in this order from the top, we will merge them only if $max_2 > min_1$, because this means that an edge exist between the two. When we reach the end, our stack contains all connected components. Note that merging two adjacent intervals forms a new interval, so we have proven by induction that our first assumption is correct. Time complexity: $O(n)$.",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1638",
    "index": "D",
    "title": "Big Brush",
    "statement": "You found a painting on a canvas of size $n \\times m$. The canvas can be represented as a grid with $n$ rows and $m$ columns. Each cell has some color. Cell $(i, j)$ has color $c_{i,j}$.\n\nNear the painting you also found a brush in the shape of a $2 \\times 2$ square, so the canvas was surely painted in the following way: initially, no cell was painted. Then, the following painting operation has been performed some number of times:\n\n- Choose two integers $i$ and $j$ ($1 \\le i < n$, $1 \\le j < m$) and some color $k$ ($1 \\le k \\le nm$).\n- Paint cells $(i, j)$, $(i + 1, j)$, $(i, j + 1)$, $(i + 1, j + 1)$ in color $k$.\n\nAll cells must be painted at least once. A cell can be painted multiple times. In this case, its final color will be the last one.\n\nFind any sequence of at most $nm$ operations that could have led to the painting you found or state that it's impossible.",
    "tutorial": "Let's try to build the solution from the last operation to the first operation. The last operation can be any $2 \\times 2$ square painted in a single color. If there is no such square, it is clearly impossible. Otherwise, this square being the last operation implies that we could previously color its cells in any color, multiple times, without any consequences. We will name these special cells. What happens when we run out of $2 \\times 2$ squares painted in a single color? Well, we can use the special cells described above. The next operation considered can be any $2 \\times 2$ square such that all its non-special cells are painted in the same color. If there is no such square, it is clearly impossible. We now have a correct solution. It consists of at most $nm$ operation because at each step we turn at least one non-special cell into a special one and there are $nm$ cells. We can implement this solution similar to BFS. First, insert all $2 \\times 2$ squares painted in a single color into a queue. Then, at each step take the square in the front of the queue, add it to the solution and make all its non-special cells special. When making a cell special, check all $2 \\times 2$ squares that contain it and if some of them meet the condition after the current step, insert them into the queue. Note that there are at most $9$ such squares. Time complexity: $O(nm)$.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1638",
    "index": "E",
    "title": "Colorful Operations",
    "statement": "You have an array $a_1,a_2, \\dots, a_n$. Each element initially has value $0$ and color $1$. You are also given $q$ queries to perform:\n\n- Color $l$ $r$ $c$: Change the color of elements $a_l,a_{l+1},\\cdots,a_r$ to $c$ ($1 \\le l \\le r \\le n$, $1 \\le c \\le n$).\n- Add $c$ $x$: Add $x$ to values of all elements $a_i$ ($1 \\le i \\le n$) of color $c$ ($1 \\le c \\le n$, $-10^9 \\le x \\le 10^9$).\n- Query $i$: Print $a_i$ ($1 \\le i \\le n$).",
    "tutorial": "In the first part, let's consider that for all update operations $l=r$. The idea is not to update each element in an Add operation and instead, keeping an array $lazy[color]$ which stores for each color the total sum we must add to it (because we didn't do it when we had to). Lets's discuss each operation: Update $l$ $r$ $c$:We will use the notation $l=r=i$. In this operation we change the color of element $i$ from $c'$ to $c$. First, remember that we have the sum $lazy[c']$ that we haven't added to any of the elements of color $c'$ (including $i$), so we better do it now because the color changes: $a[i] := a[i] + lazy[c']$. Now we can change the color to $c$. But wait, what about $lazy[c]$? It says that we will need to add some value to element $i$, but this is obviously false, since now it is up to date. We can compensate by subtracting now $lazy[c]$ from element $i$, repairing the mistake we will do later: $a[i] := a[i] - lazy[c]$. Finally, don't forget to set $color[i] := c$. We will use the notation $l=r=i$. In this operation we change the color of element $i$ from $c'$ to $c$. First, remember that we have the sum $lazy[c']$ that we haven't added to any of the elements of color $c'$ (including $i$), so we better do it now because the color changes: $a[i] := a[i] + lazy[c']$. Now we can change the color to $c$. But wait, what about $lazy[c]$? It says that we will need to add some value to element $i$, but this is obviously false, since now it is up to date. We can compensate by subtracting now $lazy[c]$ from element $i$, repairing the mistake we will do later: $a[i] := a[i] - lazy[c]$. Finally, don't forget to set $color[i] := c$. Add $c$ $x$:This is as simple as it gets: $lazy[c] := lazy[c] + x$. This is as simple as it gets: $lazy[c] := lazy[c] + x$. Query $i$:The query operation is also not very complicated. We print the value $a[i]$ and don't forget about $lazy[color[i]]$: $print(a[i] + lazy[color[i]])$. The query operation is also not very complicated. We print the value $a[i]$ and don't forget about $lazy[color[i]]$: $print(a[i] + lazy[color[i]])$. The time complexity is $O(1)$ per query. Now we get back to the initial problem and remove the restriction $l=r$. Let's keep an array of maximal intervals of elements with the same color. We will name them color intervals. By doing so, we can keep the $lazy$ value for the a whole color interval. When we change the color of all elements in $[l,r]$, there are two kinds of color intervals that interest us in our array: $[l',r'] \\subseteq [l,r]$:In this case the whole interval changes its color. First, we add the $lazy$ values to each interval. Then, after changing the color of all these intervals into the same one, we can merge them all. Now we update the resulting interval similar to how we would update a single element. In this case the whole interval changes its color. First, we add the $lazy$ values to each interval. Then, after changing the color of all these intervals into the same one, we can merge them all. Now we update the resulting interval similar to how we would update a single element. $l \\in [l',r']$ or $r \\in [l',r']$ (or both):These are the two (or one) intervals that contain the endpoints $l$ and $r$. Here we will first split the color interval into two (or three) smaller ones: outside and inside $[l,r]$. Then, we just update the one inside $[l,r]$ as before. These are the two (or one) intervals that contain the endpoints $l$ and $r$. Here we will first split the color interval into two (or three) smaller ones: outside and inside $[l,r]$. Then, we just update the one inside $[l,r]$ as before. Notice that in contrast to the solution for $l=r$, here we have to add some value on a range. We can do this using a data structure such as Fenwick tree or segment tree in $O(log_2{(n)})$. Also, for storing the color intervals we can use a set. This allows insertions and deletions, as well as quickly finding the range of intervals modified in a coloring. The time complexity is a bit tricky to determine because at first it might seem like it is $O(q \\cdot n)$, but if we analyze the effect each update has on the long term, it turns out to be much better. We will further refer to the number of intervals in our array as the potential of the current state. Let's consider that in our update we found $k$ color intervals contained in the update interval, the potential decreases by $k-1$ and then it grows by at most $2$ (because of the two splits). The number of steps our program performs is proportional to the total changes in potential. In one operation, the potential can decrease by a lot, but luckily, it can only grow by $2$. Because the potential is always positive, it decreases in total at most as much as it increases. Thus, the total change in potential is $O(q)$. Although not described here, there exists another solution to this problem using only a segment tree with lazy propagation. In this solution, our data structure stops only on monochrome segments. The time complexity is the same. Time complexity: $O(n+q \\cdot log_2{(n)})$.",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1638",
    "index": "F",
    "title": "Two Posters",
    "statement": "You want to advertise your new business, so you are going to place two posters on a billboard in the city center. The billboard consists of $n$ vertical panels of width $1$ and varying integer heights, held together by a horizontal bar. The $i$-th of the $n$ panels has height $h_i$.\n\nInitially, all panels hang down from the bar (their top edges lie on it), but before placing the two posters, you are allowed to move each panel up by any integer length, as long as it is still connected to the bar (its bottom edge lies below or on it).\n\nAfter the moves are done, you will place two posters: one below the bar and one above it. They are not allowed to go over the bar and they must be positioned completely inside of the panels.\n\nWhat is the maximum total area the two posters can cover together if you make the optimal moves? \\textbf{Note that you can also place a poster of $0$ area. This case is equivalent to placing a single poster.}",
    "tutorial": "There are many ways in which two posters can be positioned, therefore, we split the problem into multiple sub-problems. Consider the following cases. The two posters share no common panel. The two posters share a range of common panels. Here, there are two sub-cases. The second poster does not share all its panels with the first. The second poster shares all its panels with the first. The second poster does not share all its panels with the first. The second poster shares all its panels with the first. Let's find the maximum total area for each of these cases. The answer will be the maximum over them. The important element to analyze in an optimal positioning of the two posters is the bottleneck. This is the panel (or one of them) which is completely covered by the posters and doesn't allow the area to be any larger. The two posters share no common panel.Since the two posters cover disjoint ranges of panels, there is a left poster and a right poster. Thus, we can choose a position somewhere between the two posters and move up to the maximum all panels to the left of this position. So, a correct solution is to consider all possible split positions. For each of them, solve the standard skyline problem for both left and right sides or, for an easier implementation, use a trivial precomputation. Time complexity: $O(n^2)$. Since the two posters cover disjoint ranges of panels, there is a left poster and a right poster. Thus, we can choose a position somewhere between the two posters and move up to the maximum all panels to the left of this position. So, a correct solution is to consider all possible split positions. For each of them, solve the standard skyline problem for both left and right sides or, for an easier implementation, use a trivial precomputation. Time complexity: $O(n^2)$. The two posters share a range of common panels.In the following two subcases we will deal with pairs of posters that share some panels. So, let's make some observations before going any further. Consider the height of the first poster (red) to be $h_1$ and the height of the second poster (blue) to be $h_2$. Now, let's find all panels $i$ such that $h_i < h_l + h_r$. We will color these panels yellow and the rest of them gray. Because of the condition we imposed on the heights of yellow panels, they can't be shared by the two posters. On the other hand, gray panels can. Now we can make one more observation. The range of common panels lies between two yellow panels. Moreover, since we try to maximize the total area and the two heights are fixed, the range of common panels is one of the maximal gray ranges. Now comes the tricky part. We can't iterate over all the maximal gray ranges. There are $O(n)$ such ranges for any $h_1$ and $h_2$. And even worse, the two heights are up to $10^{12}$. The problem is that we are looking from the wrong perspective. Instead of iterating $h_1$ and $h_2$ and then finding the yellow panels, let's consider some possible maximal intersection range and then find all pairs of $h_1$ and $h_2$ influenced by this range. Ok, but there are $O(n^2)$ ranges to consider, right? Well, there are actually only $O(n)$. Please note that the yellow/gray notation only works after fixing some $h_1$ and $h_2$, but we refer to as a maximal intersection range to those ranges that could meet the conditions for some suitable $h_1$ and $h_2$. Let the smallest panel inside a maximal intersection range be its representative (if there are multiple, take the leftmost one). Now consider some panel $i$. For which maximal intesrection ranges is it the representative? Start with the range $[i,i]$ and extend to the left and to the right, while at least one of the bounding panels is larger or equal to $h_i$. We are doing this because we search for maximal intersection ranges, and this means that they are contained between two yellow panels of smaller size. Now we stopped at some range $[x,y]$, where $h_j > h_{x-1}$ and $h_j > h_{y+1}$ for any $j \\in [x,y]$. Can we extend even more? No, we considered panel $i$ to be the representative and thus, the smallest in the range, extending it any further would contradict this. We now have $O(n)$ possible maximal intersection ranges, each having a unique representative. Let the prefix of panels before the range be colored red and the suffix of panels after the range be colored blue. Now, let's look at the two remaining cases and solve them. The second poster does not share all its panels with the first.This means that the first poster covers all gray panels and some of the red ones, and the second poster covers all gray panels and some of the blue ones. Consider the following example. These are all the ways two posters can be positioned in this case. Some of them are marked as useless because they can be transformed into better configurations. How do we tell if a configuration is useful? Well, in a useful configuration, the two posters should meet one of the following two conditions. They touch (the representative panel being a bottleneck) and one of them also has its own bottleneck. If none of them had its own bottleneck, it would be possible to stretch the wider one, while shrinking the other, in order to increase the total area. This way, a bottleneck could be formed in a better configuration. Each of them has its own bottleneck. So, let's sum up. First, we choose a representative panel. Then, we find the range it represents. Next, solve each of the above cases separately. Some prefix/suffix precomputation and two pointers algorithm should be enough. Time complexity: $O(n^2)$. The second poster shares all its panels with the first.This means that the second poster covers all gray panels and the first poster covers all gray panels, some of the red ones and some of the blue ones (here, we will replace blue and red with pink). Consider the following example. This is obviously the simple subcase of the two. We only need to keep track on the left and right pink panels while we gradually decrease the height of the second poster. We will use the two pointers algorithm again. Note that the blue poster should touch the end of the representative panel. You might argue that braking this restriction could result in a larger total area, but don't forget that we will handle those cases using other representative panels and their respective gray ranges. Time complexity: $O(n^2)$. In the following two subcases we will deal with pairs of posters that share some panels. So, let's make some observations before going any further. Consider the height of the first poster (red) to be $h_1$ and the height of the second poster (blue) to be $h_2$. Now, let's find all panels $i$ such that $h_i < h_l + h_r$. We will color these panels yellow and the rest of them gray. Because of the condition we imposed on the heights of yellow panels, they can't be shared by the two posters. On the other hand, gray panels can. Now we can make one more observation. The range of common panels lies between two yellow panels. Moreover, since we try to maximize the total area and the two heights are fixed, the range of common panels is one of the maximal gray ranges. Now comes the tricky part. We can't iterate over all the maximal gray ranges. There are $O(n)$ such ranges for any $h_1$ and $h_2$. And even worse, the two heights are up to $10^{12}$. The problem is that we are looking from the wrong perspective. Instead of iterating $h_1$ and $h_2$ and then finding the yellow panels, let's consider some possible maximal intersection range and then find all pairs of $h_1$ and $h_2$ influenced by this range. Ok, but there are $O(n^2)$ ranges to consider, right? Well, there are actually only $O(n)$. Please note that the yellow/gray notation only works after fixing some $h_1$ and $h_2$, but we refer to as a maximal intersection range to those ranges that could meet the conditions for some suitable $h_1$ and $h_2$. Let the smallest panel inside a maximal intersection range be its representative (if there are multiple, take the leftmost one). Now consider some panel $i$. For which maximal intesrection ranges is it the representative? Start with the range $[i,i]$ and extend to the left and to the right, while at least one of the bounding panels is larger or equal to $h_i$. We are doing this because we search for maximal intersection ranges, and this means that they are contained between two yellow panels of smaller size. Now we stopped at some range $[x,y]$, where $h_j > h_{x-1}$ and $h_j > h_{y+1}$ for any $j \\in [x,y]$. Can we extend even more? No, we considered panel $i$ to be the representative and thus, the smallest in the range, extending it any further would contradict this. We now have $O(n)$ possible maximal intersection ranges, each having a unique representative. Let the prefix of panels before the range be colored red and the suffix of panels after the range be colored blue. Now, let's look at the two remaining cases and solve them. The second poster does not share all its panels with the first.This means that the first poster covers all gray panels and some of the red ones, and the second poster covers all gray panels and some of the blue ones. Consider the following example. These are all the ways two posters can be positioned in this case. Some of them are marked as useless because they can be transformed into better configurations. How do we tell if a configuration is useful? Well, in a useful configuration, the two posters should meet one of the following two conditions. They touch (the representative panel being a bottleneck) and one of them also has its own bottleneck. If none of them had its own bottleneck, it would be possible to stretch the wider one, while shrinking the other, in order to increase the total area. This way, a bottleneck could be formed in a better configuration. Each of them has its own bottleneck. So, let's sum up. First, we choose a representative panel. Then, we find the range it represents. Next, solve each of the above cases separately. Some prefix/suffix precomputation and two pointers algorithm should be enough. Time complexity: $O(n^2)$. This means that the first poster covers all gray panels and some of the red ones, and the second poster covers all gray panels and some of the blue ones. Consider the following example. These are all the ways two posters can be positioned in this case. Some of them are marked as useless because they can be transformed into better configurations. How do we tell if a configuration is useful? Well, in a useful configuration, the two posters should meet one of the following two conditions. They touch (the representative panel being a bottleneck) and one of them also has its own bottleneck. If none of them had its own bottleneck, it would be possible to stretch the wider one, while shrinking the other, in order to increase the total area. This way, a bottleneck could be formed in a better configuration. Each of them has its own bottleneck. So, let's sum up. First, we choose a representative panel. Then, we find the range it represents. Next, solve each of the above cases separately. Some prefix/suffix precomputation and two pointers algorithm should be enough. Time complexity: $O(n^2)$. The second poster shares all its panels with the first.This means that the second poster covers all gray panels and the first poster covers all gray panels, some of the red ones and some of the blue ones (here, we will replace blue and red with pink). Consider the following example. This is obviously the simple subcase of the two. We only need to keep track on the left and right pink panels while we gradually decrease the height of the second poster. We will use the two pointers algorithm again. Note that the blue poster should touch the end of the representative panel. You might argue that braking this restriction could result in a larger total area, but don't forget that we will handle those cases using other representative panels and their respective gray ranges. Time complexity: $O(n^2)$. This means that the second poster covers all gray panels and the first poster covers all gray panels, some of the red ones and some of the blue ones (here, we will replace blue and red with pink). Consider the following example. This is obviously the simple subcase of the two. We only need to keep track on the left and right pink panels while we gradually decrease the height of the second poster. We will use the two pointers algorithm again. Note that the blue poster should touch the end of the representative panel. You might argue that braking this restriction could result in a larger total area, but don't forget that we will handle those cases using other representative panels and their respective gray ranges. Time complexity: $O(n^2)$.",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1641",
    "index": "A",
    "title": "Great Sequence",
    "statement": "A sequence of positive integers is called great for a positive integer $x$, if we can split it into pairs in such a way that in each pair the first number multiplied by $x$ is equal to the second number. More formally, a sequence $a$ of size $n$ is great for a positive integer $x$, if $n$ is even and there exists a permutation $p$ of size $n$, such that for each $i$ ($1 \\le i \\le \\frac{n}{2}$) $a_{p_{2i-1}} \\cdot x = a_{p_{2i}}$.\n\nSam has a sequence $a$ and a positive integer $x$. Help him to make the sequence great: find the minimum possible number of positive integers that should be added to the sequence $a$ to make it great for the number $x$.",
    "tutorial": "Let's look at the minimal integer in our multiset. Since it can be matched with only one integer, we need to create such pair. Thus, we can maintain the current multiset. We need to take the minimal element out of it (and delete it from it), find a pair for it, and delete it from the multiset if such pair exists, or add 1 to the answer if there is no such pair.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n \nusing namespace std;\n \nsigned main() {\n    (*cin.tie(0)).sync_with_stdio(0);\n    int t; cin >> t;\n    while (t--) {\n        int n;\n        int64_t x;\n        cin >> n >> x;\n        vector<int64_t> ar(n);\n        for (auto& it : ar)\n            cin >> it;\n        sort(ar.begin(), ar.end());\n        vector<bool> vis(n);\n        int j = 0, q = 0;\n        int ans = 0;\n        for (int i = 0; i < n; ++i) {\n            if (vis[i])\n                continue;\n            if (ar[i] * x > ar[j]) {\n                while (ar[i] * x >= ar[j] && j < n)\n                    q = ++j;\n                q = --j;\n            }\n            if (i < q && ar[i] * x == ar[q])\n                vis[q--] = 1;\n            else\n                ans++;\n        }\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}\n ",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1641",
    "index": "B",
    "title": "Repetitions Decoding",
    "statement": "Olya has an array of integers $a_1, a_2, \\ldots, a_n$. She wants to split it into tandem repeats. Since it's rarely possible, before that she wants to perform the following operation several (possibly, zero) number of times: insert a pair of equal numbers into an arbitrary position. Help her!\n\nMore formally:\n\n- A tandem repeat is a sequence $x$ of even length $2k$ such that for each $1 \\le i \\le k$ the condition $x_i = x_{i + k}$ is satisfied.\n- An array $a$ could be split into tandem repeats if you can split it into several parts, each being a subsegment of the array, such that each part is a tandem repeat.\n- In one operation you can choose an arbitrary letter $c$ and insert $[c, c]$ to any position in the array (at the beginning, between any two integers, or at the end).\n- You are to perform several operations and split the array into tandem repeats or determine that it is impossible. Please note that you do \\textbf{not} have to minimize the number of operations.",
    "tutorial": "Let's prove that we can turn the array into a concatenation of tandem repeats using the operations given if and only if every letter occurs an even number of times If there is such letter $x$ that it occurs an odd number of times there is no such sequence of operations, since the parity of the number of occurrences if letter $x$ stays the same. If we insert a different letter, the number of occurrences of letter $x$ does not change, if we insert letter $x$, we add 2 occurrences of it. Thus, it will be impossible to split the array into tandem repeats. If we have an array $s_{1}s_{2}...s_{n}$, and we want to reverse its prefix of length $k \\leq n$, we can insert a pair of letters equal to $s_{1}$ after the $k$-th symbol, a pair of letters equal to $s_{2}$ after $(k+1)$-th symbol and etc. $s_1s_2...s_ks_{k+1}...s_n$ $s_1s_2...s_ks_1s_1s_{k+1}...s_n$ $s_1s_2...s_ks_1s_2s_2s_1s_{k+1}...s_n$ $...$ $s_1s_2...s_ks_1s_2...s_ks_k...s_2s_1s_{k+1}...s_n$ It is obvious that the first $2k$ symbols of the array form a tandem repeat. We can add it to our division and cut it out from the array. The array will now have its prefix of length $k$ reversed. Thus, we can move any element to the beginning of the array, so we can simply sort it. Since every element occurs an even number of times, the resulting string will be a concatenation of tandem repeats consisting of the same letters. $\\mathcal{O}(2n^2)$ insertions solution: 147514019 $\\mathcal{O}(n^2)$ insertions solution: 147514028",
    "code": "#define _USE_MATH_DEFINES\n \n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <deque>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <map>\n#include <math.h>\n#include <numeric>\n#include <queue>\n#include <random>\n#include <set>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n \nusing namespace std;\n \nvoid reverse_range(vector<int> &ar, vector<pair<int, int>> &ans,\n                  vector<int> &lens, int &mdf, int l, int r) {\n    for (int i = l; i <= r; ++i)\n        ans.emplace_back(r + 1 + mdf + i - 2 * l, ar[i]);\n    if (r - l + 1 > 0)\n        lens.push_back((r - l + 1) * 2);\n    mdf += (r - l + 1) * 2;\n    reverse(ar.begin() + l, ar.begin() + r + 1);\n}\n \nvoid move_last_to_front(vector<int> &ar, vector<pair<int, int>> &ans,\n                   vector<int> &lens, int &mdf, int l, int r) {\n    reverse_range(ar, ans, lens, mdf, l, r - 1);\n    reverse_range(ar, ans, lens, mdf, l, r);\n}\n \nsigned IlkrasTEQ1Solve(int n, vector<int>& ar) {\n    if (n % 2) {\n        cout << \"-1\\n\";\n        return 0;\n    }\n    int xr = 0;\n    unordered_map<int, int> cnt;\n    for (auto &it : ar) {\n        cnt[it]++;\n    }\n    for (auto &it : cnt)\n        if (it.second % 2) {\n            cout << \"-1\\n\";\n            return 0;\n        }\n    vector<pair<int, int>> ans;\n    vector<int> lens;\n    ans.reserve(n * n * 2);\n    lens.reserve(n * 2);\n    int mdf = 0;\n    for (int i = 0; i < n; i += 2) {\n        int fnd = (int)(find(ar.begin() + i + 1, ar.end(), ar[i]) - ar.begin());\n        move_last_to_front(ar, ans, lens, mdf, i, fnd);\n        lens.push_back(2);\n        mdf += 2;\n    }\n    cout << (int)ans.size() << \"\\n\";\n    for (auto &it : ans)\n        cout << it.first << \" \" << it.second << \"\\n\";\n    cout << (int)lens.size() << \"\\n\";\n    for (auto &it : lens)\n        cout << it << \" \";\n    cout << \"\\n\";\n    return 0;\n}\n \nsigned main() {\n    (*cin.tie(0)).sync_with_stdio(0);\n    int q;\n    cin >> q;\n    while (q--) {\n        int n;\n        cin >> n;\n        vector<int> ar(n);\n        for (auto &it : ar)\n            cin >> it;\n        if (n % 2) {\n            cout << \"-1\\n\";\n            continue;\n        }\n        IlkrasTEQ1Solve(n, ar);\n    }\n    return 0;\n}\n \n ",
    "tags": [
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1641",
    "index": "C",
    "title": "Anonymity Is Important",
    "statement": "In the work of a doctor, it is important to maintain the anonymity of clients and the results of tests. The test results are sent to everyone personally by email, but people are very impatient and they want to know the results right away.\n\nThat's why in the testing lab \"De-vitro\" doctors came up with an experimental way to report the results. Let's assume that $n$ people took the tests in the order of the queue. Then the chief doctor Sam can make several statements, in each telling if there is a sick person among the people in the queue from $l$-th to $r$-th (inclusive), for some values $l$ and $r$.\n\nDuring the process, Sam will check how well this scheme works and will be interested in whether it is possible to find out the test result of $i$-th person from the information he announced. And if it can be done, then is that patient sick or not.\n\nHelp Sam to test his scheme.",
    "tutorial": "If $i$-th person is not ill, the following query exists: $0 \\ l \\ r \\ 0$, such that $l \\le i \\le r$. Otherwise, the person's status is either unknown or they are ill. If $i$-th person is ill, the following query exists:$0 \\ l \\ r \\ 1$, such that $l \\le i \\le r$, and every person $i$ such that $l \\leq j \\leq r$ are not ill. If there is such person $j$ that they are not ill, and $j \\neq i, l \\le j \\le r$. In this case, it is impossible to determine if $i$-th person is ill or not. Let's maintain the indices of the people who might be ill using set. When we get a query $0 \\ l \\ r \\ 0$, we can find the first possible ill person with an index of at least $l$ using lower_bound, after that, we need to delete this person from our set, find the next one and do the same thing until we find the first index greater than $r$. This works in $O(nlogn)$. If a person is not in the set, he is totally healthy. Otherwise, we can use a segment tree to store such index $j$ that there is a query $0 \\ i \\ j \\ 1$ and store it in the $i$-th slot of our segment tree. We can update it when we get a new query. When we understand that the $i$-th person might be ill, we can find the first elements to the left ($l$) and to the right ($r$) of $i$, which might be ill using our set. The $i$-th person is ill when the minimal element on segment $[l + 1; i]$ is $< r$. The solution works in $O(nlogn + qlogn)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define fi first\n#define se second\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define gcd __gcd\n#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define rep(i, n) for (int i=0; i<(n); i++)\n#define rep1(i, n) for (int i=1; i<=(n); i++)\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define endl \"\\n\"\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef unsigned uint;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector<vector<int>> vvi;\ntypedef vector<ll> vll;\ntypedef vector<vector<ll>> vvll;\ntypedef vector<bool> vb;\ntypedef vector<vector<bool>> vvb;\n \nint32_t main() {\n    fastio;\n    int n, q; cin >> n >> q;\n    set<int> active;\n    rep(i, n + 1) active.insert(i);\n    vi m(n, INT_MAX);\n    vi ans(n, -1);\n    while(q--) {\n        int t; cin >> t;\n        if(t == 0) {\n            int l, r, x; cin >> l >> r >> x; --l, --r;\n            if(x == 1) {\n                int v = *active.lower_bound(l);\n                m[v] = min(m[v], r);\n                if(m[v] < *active.upper_bound(v)) ans[v] = 1;\n            }\n            else {\n                int nxt = *active.upper_bound(r);\n                for(auto itr = active.lower_bound(l); *itr <= r;) {\n                    if(nxt != n) m[nxt] = min(m[nxt], m[*itr]);\n                    ans[*itr] = 0;\n                    active.erase(itr);\n                    itr = active.lower_bound(l);\n                }\n                if(nxt != n && m[nxt] < *active.upper_bound(nxt)) ans[nxt] = 1;\n                if(*active.begin() < l) {\n                    int prv = *prev(active.lower_bound(l));\n                    if(m[prv] < *active.upper_bound(prv)) ans[prv] = 1;\n                }\n            }\n        }\n        else {\n            int p; cin >> p; --p;\n            if(ans[p] == -1) cout << \"N/A\\n\";\n            else if(ans[p] == 0) cout << \"NO\\n\";\n            else cout << \"YES\\n\";\n        }\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dsu",
      "greedy",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1641",
    "index": "D",
    "title": "Two Arrays",
    "statement": "Sam changed his school and on the first biology lesson he got a very interesting task about genes.\n\nYou are given $n$ arrays, the $i$-th of them contains $m$ different integers — $a_{i,1}, a_{i,2},\\ldots,a_{i,m}$. Also you are given an array of integers $w$ of length $n$.\n\nFind the minimum value of $w_i + w_j$ among all pairs of integers $(i, j)$ ($1 \\le i, j \\le n$), such that the numbers $a_{i,1}, a_{i,2},\\ldots,a_{i,m}, a_{j,1}, a_{j,2},\\ldots,a_{j,m}$ are distinct.",
    "tutorial": "Let's maintain a set of arrays of length $m$, add new arrays there, delete arrays from this set and understand if the set has a suitable pair for some array. To do this, let's consider a pair of sorted arrays $a$ and $b$ of length $m$. Let's write out all subsets of the array $a$. Then we start a counter $count$, and for each subset of the array $b$ we add one to $count$, if the subset occurs in $a$ and contains an odd number of elements, and subtract one if the subset occurs in $a$ and contains an even number of elements. Note that if $a$ and $b$ have at least one element in common, then $count$ will be equal to $1$, otherwise it will be equal to $0$. Thus, we can maintain a trie that contains all the subsets of each array in the set. Now any request to this trie is trivially done for $2^m$. Now let's sort the arrays by $w$ and use our structure to find the first array that has a suitable pair. We can simply find the pair and maintain 2 pointers, $l$ is equal to the first array in the pair, $r$ is equal to the second array in the pair. Note that now we are only interested in pairs $l_{1}, r_{1}$ such that $l < l_{1} < r_{1} < r$. Therefore, we will move $l$ to the left only. When we moved it once again, we will see if there is a pair for it among $l < i < r$. If so, then we will move $r$ to the left until there is a pair for $l$ among $l < i \\leq r$. After that we can update the answer with $w_{l} + w_{r}$. The solution works in $O(n\\cdot 2^m)$. It is also possible to solve this problem in $O(\\frac{n^2 \\cdot m}{32})$ using std::bitset.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/trie_policy.hpp>\n#include <ext/rope>\n \nusing namespace std;\n \n#define fi first\n#define se second\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define gcd __gcd\n#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define rep(i, n) for (int i=0; i<(n); i++)\n#define rep1(i, n) for (int i=1; i<=(n); i++)\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define endl \"\\n\"\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef unsigned uint;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector<vector<int>> vvi;\ntypedef vector<ll> vll;\ntypedef vector<vector<ll>> vvll;\ntypedef vector<bool> vb;\ntypedef vector<vector<bool>> vvb;\n \nconstexpr int N = 1e5 + 5;\nconstexpr int M = 5;\nconstexpr int T = 1000;\n \n#pragma GCC target(\"popcnt\")\nint a[N][M];\nint elem[N * M];\nvi idx[N * M];\nunique_ptr<bitset<N>> good[N * M];\nbitset<N> state;\nint w[N];\nint ord[N];\nint conv[N];\n \nint32_t main() {\n    fastio;\n    int n, m; cin >> n >> m;\n    int sz = 0;\n    rep(i, n) {\n        rep(j, m) cin >> a[i][j], elem[sz++] = a[i][j];\n        cin >> w[i];\n    }\n    sort(elem, elem + sz);\n    sz = unique(elem, elem + sz) - elem;\n    iota(ord, ord + n, 0);\n    sort(ord, ord + n, [&](int i, int j) {return w[i] < w[j];});\n    rep(i, n) conv[ord[i]] = i;\n    rep(i, n) {\n        sort(a[i], a[i] + m);\n        rep(j, m) {\n            int v = lower_bound(elem, elem + sz, a[i][j]) - elem;\n            a[i][j] = v;\n            if(!j || a[i][j] != a[i][j - 1]) idx[v].pb(conv[i]);\n        }\n    }\n    rep(i, sz) if(idx[i].size() >= T) {\n        good[i] = make_unique<bitset<N>>();\n        good[i] -> set();\n        for(int v: idx[i]) good[i] -> reset(v);\n    }\n    int ans = INT_MAX;\n    rep(i, n) {\n        state.set();\n        state[conv[i]] = 0;\n        rep(j, m) if(!j || a[i][j] != a[i][j - 1]) {\n            int v = a[i][j];\n            if(idx[v].size() < T) for(int x: idx[v]) state[x] = 0;\n            else state &= *good[v];\n        }\n        int id = state._Find_first();\n        if(id >= n) continue;\n        else {\n            id = ord[id];\n            ans = min(ans, w[i] + w[id]);\n        }\n    }\n    cout << (ans == INT_MAX ? -1 : ans) << endl;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "greedy",
      "hashing",
      "math",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1641",
    "index": "E",
    "title": "Special Positions",
    "statement": "You are given an array $a$ of length $n$. Also you are given $m$ distinct positions $p_1, p_2, \\ldots, p_m$ ($1 \\leq p_i \\leq n$).\n\nA \\textbf{non-empty} subset of these positions $T$ is randomly selected with equal probability and the following value is calculated: $$\\sum_{i=1}^{n} (a_i \\cdot \\min_{j \\in T} \\left|i - j\\right|).$$ In other word, for each index of the array, $a_i$ and the distance to the closest chosen position are multiplied, and then these values are summed up.\n\nFind the expected value of this sum.\n\nThis value must be found modulo $998\\,244\\,353$. More formally, let $M = 998\\,244\\,353$. It can be shown that the answer can be represented as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\neq 0$ (mod $M$). Output the integer equal to $p \\cdot q^{-1}$ (mod $M$). In other words, output such integer $x$ that $0 \\leq x < M$ and $x \\cdot q = p$ (mod $M$).",
    "tutorial": "First of all, calculate for each index the total sum of distances among all subsets if the closest selected position is to the left. Let $suf_i = 2^{cnt_i}$, where $cnt_i$ - the number of cpecial positions at $i$ or to the right of $i$ (if $i > n$ then $cnt_i = 0$). Let $special_i = 1$ if position $i$ is special, otherwise $special_i = 0$. It's not hard to see, that the value for the position $pos$ in this case equals to $\\sum_{i = 1}^{pos-1} \\sum_{j + i = 2 * pos} special_i \\cdot suf_i \\cdot (pos - i)$. Then for each $pos$ calculate two values: $\\sum_{i = 1}^{pos-1} \\sum_{j + i = 2 * pos} special_i \\cdot suf_i \\cdot i$ $\\sum_{i = 1}^{pos-1} \\sum_{j + i = 2 * pos} special_i \\cdot suf_i$ Since $j > i$ we can find first value using DNC (the second value we will find similary): we want to consider every $l \\le i < j \\le r$. Then halve this segment: $m = \\frac{l + r}{2}$. Then create two polynomials: The polynomial $P$ of size $m - l + 1$, where $P_i = special_{l + i} \\cdot (l + r)$. The polynomial $Q$ of size $r - m$, where $Q_i = suf_{m + 1 + i}$. By multiplying this two polinomials we can recalculate the values for positions from $l + m + 1$ to $m + r$ and then solve two parts recursively. Thus we can find for each index the total sum of distances among all subsets if the closest selected position is to the left. To find for each index the total sum of distances among all subsets if the closest selected positions is to the right we can do the same stuff but in inverse order. Note, that we need to consider the case where the closest selected position to the left and the closest selected position are at the same distance from $pos$. It can be done by changing $cnt_i$ in one of the cases by the number of special positinos strickly to the right of $i$. It can be implemented in $O(n \\log^2{n})$ using FFT.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconstexpr int MOD = 998244353, ROOT = 3;\n \nint add(int a, int b) {\n    a += b;\n    return a - MOD * (a >= MOD);\n}\n \nint sub(int a, int b) {\n    a -= b;\n    return a + MOD * (a < 0);\n}\n \nint mult(int a, int b) {\n    return 1ll * a * b % MOD;\n}\n \nint power(int a, int b) {\n    int prod = 1;\n    for (; b; b >>= 1, a = mult(a, a))\n        if (b & 1)\n            prod = mult(prod, a);\n \n    return prod;\n}\n \nvoid fft(vector<int> &a) {\n    int n = a.size(), lg = __lg(n);\n    assert((1 << lg) == n);\n \n    for (int i = 0; i < n; i++) {\n        int j = 0;\n        for (int bit = 0; bit < lg; bit++)\n            j ^= (i >> bit & 1) << (lg - bit - 1);\n \n        if (i < j)\n            swap(a[i], a[j]);\n    }\n \n    for (int length = 1; length < n; length <<= 1) {\n        int root = power(ROOT, (MOD - 1) / (length << 1));\n        for (int i = 0; i < n; i += length << 1)\n            for (int j = 0, x = 1; j < length; j++, x = mult(x, root)) {\n                int value = mult(a[i + j + length], x);\n                a[i + j + length] = sub(a[i + j], value);\n                a[i + j] = add(a[i + j], value);\n            }\n    }\n}\n \nvector<int> multiply(vector<int> a, vector<int> b) {\n    int result_size = int(a.size() + b.size()) - 1, n = 1;\n    while (n < result_size)\n        n <<= 1;\n \n    a.resize(n);\n    b.resize(n);\n    fft(a), fft(b);\n \n    for (int i = 0; i < n; i++)\n        a[i] = mult(a[i], b[i]);\n \n    fft(a);\n    reverse(a.begin() + 1, a.end());\n \n    int inv_n = power(n, MOD - 2);\n    for (auto &x : a)\n        x = mult(x, inv_n);\n \n    a.resize(result_size);\n    return a;\n}\n \nvoid solve(int l, int r, const vector<int> &a, const vector<int> &b, vector<int> &c) {\n    if (r - l == 1)\n        return;\n \n    int m = (l + r) >> 1;\n    solve(l, m, a, b, c);\n    solve(m, r, a, b, c);\n \n    auto prod = multiply(vector<int>(a.begin() + l, a.begin() + m),\n                         vector<int>(b.begin() + m, b.begin() + r));\n \n    for (int i = 0; i < int(prod.size()); i++)\n        c[i + l + m] = add(c[i + l + m], prod[i]);\n}\n \nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n \n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n);\n    for (auto &x : a)\n        cin >> x;\n \n    vector<int> positions(m);\n    vector<bool> is_special(n);\n    for (auto &pos : positions) {\n        cin >> pos;\n        pos--;\n        is_special[pos] = true;\n    }\n \n    vector<int> p2(m + 1, 1);\n    for (int i = 1; i <= m; i++)\n        p2[i] = add(p2[i - 1], p2[i - 1]);\n \n    int sum = 0;\n    for (int rot : {0, 1}) {\n        vector<int> first(n), second(n);\n        for (int i = 0; i < m; i++) {\n            first[positions[i]] = p2[i];\n            if (positions[i] - rot >= 0)\n                second[positions[i] - rot] = p2[m - 1 - i];\n        }\n \n        for (int i = n - 2; i >= 0; i--)\n            second[i] = add(second[i], second[i + 1]);\n \n        vector<int> ways(2 * n);\n        solve(0, n, first, second, ways);\n \n        for (int i = 0; i < n; i++)\n            first[i] = mult(first[i], i);\n \n        vector<int> to_sub(2 * n);\n        solve(0, n, first, second, to_sub);\n \n        for (int i = 0; i < n; i++)\n            sum = add(sum, mult(a[i], sub(mult(i, ways[2 * i]), to_sub[2 * i])));\n \n        for (int i = 0, pref = 0, tot = 0; i < n; i++) {\n            sum = add(sum, mult(a[i], sub(mult(i, sub(p2[pref], 1)), tot)));\n \n            if (is_special[i]) {\n                tot = add(tot, mult(i, p2[pref]));\n                pref++;\n            }\n        }\n \n        reverse(a.begin(), a.end());\n        reverse(is_special.begin(), is_special.end());\n        reverse(positions.begin(), positions.end());\n        for (auto &pos : positions)\n            pos = n - 1 - pos;\n    }\n \n    cout << mult(sum, power(sub(p2[m], 1), MOD - 2)) << '\\n';\n}\n ",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "fft",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1641",
    "index": "F",
    "title": "Covering Circle",
    "statement": "Sam started playing with round buckets in the sandbox, while also scattering pebbles. His mom decided to buy him a new bucket, so she needs to solve the following task.\n\nYou are given $n$ distinct points with integer coordinates $A_1, A_2, \\ldots, A_n$. All points were generated from the square $[-10^8, 10^8] \\times [-10^8, 10^8]$ uniformly and independently.\n\nYou are given positive integers $k$, $l$, such that $k \\leq l \\leq n$. You want to select a subsegment $A_i, A_{i+1}, \\ldots, A_{i+l-1}$ of the points array (for some $1 \\leq i \\leq n + 1 - l$), and some circle on the plane, containing $\\geq k$ points of the selected subsegment (inside or on the border).\n\nWhat is the smallest possible radius of that circle?",
    "tutorial": "If the answer is $r$ let's consider $n$ circles $C_1, C_2, \\ldots, C_n$ with centers $A_1, A_2, \\ldots, A_n$ and radius $r$. If a required circle with radius $r$ exists it should be true, that $k$ circles $C_{i_1}, C_{i_2}, \\ldots, C_{i_k}$ has non empty intersection for some $i_1 < i_2 < \\ldots < i_k$ and $i_k - i_1 < l$. For some $1 \\leq h \\leq k$ we can find intersection point of these circles on circle $C_{i_h}$. Let's define $j = i_h$. Let's define $f(j)$ as the minimal possible $r$, such that there exists $k$ circles $C_{i_1}, C_{i_2}, \\ldots, C_{i_k}$ and $i_k - i_1 < l$, such that $j = i_h$ for some $1 \\leq h \\leq k$ and these circles intersect on circle $C_j$. Then the answer to the problem is $\\min_{1 \\leq j \\leq n} f(j)$. Let's make a procedure to check, that $f(j) \\leq x$ for some $x$. To check that let's consider circles $C_{j-l+1}, \\ldots, C_j, \\ldots, C_{j+l-1}$ with centers $A_{j-l+1}, \\ldots, A_j, \\ldots, A_{j+l-1}$ and radius $x$. Each of them intersect with $C_j$ with some arc (circular segment). We can find all these arcs. Let's now make scanline and mantain all indices of arcs covering the current point. With segment tree with lazy propagation we can check if there exists $k - 1$ indices with difference at most $l - 1$. The complexity of this check is $O(s \\log{n})$, where $s$ is the number of arcs. Let's iterate $j$ from $1$ to $n$ and maintain the current answer $r$. Initially let's initialize $r$ with $\\sqrt{2} \\cdot 10^8 \\cdot \\frac{\\sqrt{l-1}}{\\sqrt{k-1}}$ (it's easy to prove that the answer can't be bigger than these constant for any points). Now if we have some $j$ let's firstly check, that $f(j) \\leq r$ (if not - the answer won't be updated), if it is true - let's make a binary search to find a new answer. The only problem is - the number of arcs can be big. Let's note, that $C_i$ makes an arc on $C_j$ if and only if $|A_i A_j| \\leq 2x$. So let's make an infinite grid with step $2r$ and maintain a set of points in each square. Also, we should maintain points from the segment $[j - l + 1, j + l - 1]$. After that, we can only check indices, that are in the same square as the point $A_j$ and in $8$ neighboring squares. It's easy to prove, that if $r \\leq \\sqrt{2} \\cdot 10^8 \\cdot \\frac{\\sqrt{l-1}}{\\sqrt{k-1}}$ the expected number of points in each grid square is $O(k)$. In practice, the average number of points to check is around $4k \\sim 5k$. So we can find these candidate points and then use in procedures to check, that $f(j) \\leq x$, which will work in $O(k \\log{n})$. If $r$ is changed we can reconstruct all grid in $O(l)$. Due to all points are random the expected number of times when $r$ will change is $O(\\log{n})$ (famous Blogewoosh #6 idea). So the complexity of this solution is $O(n k \\log{n} + k \\log{n} \\log{\\varepsilon^{-1}})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\ntypedef double ld;\nmt19937 rnd(228);\n#define TIME (clock() * 1.0 / CLOCKS_PER_SEC)\n \nconst int M = 5e4 + 239;\nconst int X = (int)(1e8) + 239;\nconst int T = (1 << 17) + 239;\nconst ld pi = acos((ld)-1.0);\n \nint n, l, k, bd, x[M], y[M];\nint idx[M], sz_idx;\n \nint divide(int a, int b) {\n    if (a >= 0 || a % b == 0) {\n        return a / b;\n    }\n    return -(abs(a) / b) - 1;\n}\n \nclass Hasher {\npublic:\n    size_t operator()(const pair<int, int>& key) const {\n        return ((ll)(key.first + X) << 30LL) + (ll)key.second;\n    }\n};\n \nstruct helper {\n    int R = 0;\n    int l = 0;\n    int r = 0;\n    unordered_map<pair<int, int>, unordered_set<int>, Hasher> in;\n \n    template <typename P>\n    void upload(int x, int y, P pred) {\n        int xi = divide(x, R);\n        int yi = divide(y, R);\n        for (int dx = -1; dx <= 1; dx++) {\n            for (int dy = -1; dy <= 1; dy++) {\n                auto it = in.find(make_pair(xi + dx, yi + dy));\n                if (it != in.end()) {\n                    for (int i : it->second) {\n                        if (pred(i)) {\n                            idx[sz_idx++] = i;\n                        }\n                    }\n                }\n            }\n        }\n    }\n \n    void add(int i) {\n        int xi = divide(::x[i], R);\n        int yi = divide(::y[i], R);\n        in[make_pair(xi, yi)].insert(i);\n    }\n \n    void del(int i) {\n        int xi = divide(::x[i], R);\n        int yi = divide(::y[i], R);\n        in[make_pair(xi, yi)].erase(i);\n    }\n \n    void remake(ld new_r) {\n        R = ceil(new_r) + 1;\n        in.clear();\n        in.reserve(sz_idx * 2);\n        for (int i = l; i < r; i++) {\n            add(i);\n        }\n    }\n \n    void move_left() {\n        del(l);\n        l++;\n    }\n \n    void move_right() {\n        add(r);\n        r++;\n    }\n};\n \nld dist(int i, int j) {\n    return hypot(x[j] - x[i], y[j] - y[i]);\n}\n \nld angle(int i, int j) {\n    return atan2(y[j] - y[i], x[j] - x[i]);\n}\n \nint tree[T], add[T];\n \nvoid build(int i, int l, int r) {\n    tree[i] = 0;\n    add[i] = 0;\n    if (r - l == 1) {\n        return;\n    }\n    int mid = (l + r) / 2;\n    build(2 * i + 1, l, mid);\n    build(2 * i + 2, mid, r);\n}\n \ninline void push(int i, int l, int r) {\n    tree[i] += add[i];\n    if (r - l > 1) {\n        add[2 * i + 1] += add[i];\n        add[2 * i + 2] += add[i];\n    }\n    add[i] = 0;\n}\n \nvoid upd(int i, int l, int r, int ql, int qr, int x) {\n    push(i, l, r);\n    if (r <= ql || qr <= l) {\n        return;\n    }\n    if (ql <= l && r <= qr) {\n        add[i] += x;\n        push(i, l, r);\n        return;\n    }\n    int mid = (l + r) / 2;\n    upd(2 * i + 1, l, mid, ql, qr, x);\n    upd(2 * i + 2, mid, r, ql, qr, x);\n    tree[i] = max(tree[2 * i + 1], tree[2 * i + 2]);\n}\n \nvoid clear(int i, int l, int r) {\n    push(i, l, r);\n    if (tree[i] == 0) {\n        return;\n    }\n    tree[i] = 0;\n    if (r - l > 1) {\n        int mid = (l + r) / 2;\n        clear(2 * i + 1, l, mid);\n        clear(2 * i + 2, mid, r);\n    }\n}\n \nint s[M], cnt;\nvector<pair<ld, int>> events;\n \nbool check(int p, ld t) {\n    if (sz_idx < k - 1) {\n        return false;\n    }\n    bool ans = false;\n    events.clear();\n    events.reserve(sz_idx * 2);\n    cnt = 0;\n    for (int ii = 0; ii < sz_idx; ii++) {\n        int i = idx[ii];\n        ld d = dist(p, i);\n        if (d > 2 * t) {\n            continue;\n        }\n        ld a = angle(p, i);\n        ld len = acos(min((ld)1.0, d / (2 * t)));\n        ld lg = a - len;\n        ld rg = a + len;\n        if (lg < -pi) {\n            lg += 2 * pi;\n        }\n        if (rg > pi) {\n            rg -= 2 * pi;\n        }\n        events.emplace_back(lg, -1 - i);\n        events.emplace_back(rg, 1 + i);\n        if (lg > rg) {\n            upd(0, 0, bd, max(0, i - l + 1), min(bd, i + 1), 1);\n            s[cnt++] = i;\n            if (tree[0] >= k - 1) {\n                ans = true;\n            }\n        }\n    }\n    if (!ans) {\n        sort(events.begin(), events.end());\n        for (const auto& t : events) {\n            if (t.second < 0) {\n                int i = -t.second - 1;\n                upd(0, 0, bd, max(0, i - l + 1), min(bd, i + 1), 1);\n            } else {\n                int i = t.second - 1;\n                upd(0, 0, bd, max(0, i - l + 1), min(bd, i + 1), -1);\n            }\n            if (tree[0] >= k - 1) {\n                ans = true;\n            }\n        }\n    }\n    for (int i = 0; i < cnt; i++) {\n        upd(0, 0, bd, max(0, s[i] - l + 1), min(bd, s[i] + 1), -1);\n    }\n    return ans;\n}\n \nld func(helper& hl, helper& hr, int p, ld pa) {\n    auto is_good = [&](int i) {\n        return dist(p, i) <= 2 * pa;\n    };\n    sz_idx = 0;\n    hl.upload(x[p], y[p], is_good);\n    hr.upload(x[p], y[p], is_good);\n    if (!check(p, pa)) {\n        return pa;\n    }\n    ld lg = 0;\n    ld rg = pa;\n    for (int i = 0; i < 70; i++) {\n        ld mid = (lg + rg) / 2;\n        if (check(p, mid)) {\n            rg = mid;\n        } else {\n            lg = mid;\n        }\n    }\n    hl.remake(2 * rg);\n    hr.remake(2 * rg);\n    return rg;\n}\n \nvoid solve() {\n    cin >> n >> l >> k;\n    for (int i = 0; i < n; i++) {\n        cin >> x[i] >> y[i];\n    }\n    bd = n - l + 1;\n \n    int s = sqrt((ld)(l - 1) / (k - 1));\n    ld ans = ((1e8 / s) * sqrt(2)) + 1;\n \n    helper hl, hr;\n    hl.remake(2 * ans);\n    hr.remake(2 * ans);\n    for (int i = 0; i < l; i++) {\n        hr.move_right();\n    }\n \n    build(0, 0, bd);\n    for (int i = 0; i < n; i++) {\n        hr.move_left();\n \n        // solve\n        ans = min(ans, func(hl, hr, i, ans));\n \n        if (i + 1 == n) {\n            break;\n        }\n        if (i + l < n) {\n            hr.move_right();\n        }\n        if (i - l + 1 >= 0) {\n            hl.move_left();\n        }\n        hl.move_right();\n    }\n    cout << ans << \"\\n\";\n}\n \nint main() {\n#ifdef ONPC\n    freopen(\"input\", \"r\", stdin);\n#endif\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    cout << fixed << setprecision(20);\n \n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "geometry"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1642",
    "index": "A",
    "title": "Hard Way",
    "statement": "Sam lives in Awesomeburg, its downtown has a triangular shape. Also, the following is true about the triangle:\n\n- its vertices have integer coordinates,\n- the coordinates of vertices are non-negative, and\n- its vertices are not on a single line.\n\nHe calls a point on the downtown's border (that is the border of the triangle) safe if he can reach this point from \\textbf{at least one point} of the line $y = 0$ walking along some \\textbf{straight line}, without crossing the interior of the triangle.\n\n\\begin{center}\n{\\small In the picture the downtown is marked with grey color. The first path is invalid because it does not go along a straight line. The second path is invalid because it intersects with the interior of the downtown. The third and fourth paths are correct.}\n\\end{center}\n\nFind the total length of the unsafe parts of the downtown border. It can be proven that these parts are segments and their number is finite.",
    "tutorial": "If the triangle's side is not parallel with the line $y = 0$, all points on this side are safe because we can intersect it with $y = 0$ and there will be a point from which we can reach any point on this side of our triangle. All points on the side, which is parallel with $y = 0$ line contains are also safe if the third point has a greater $y$: Thus, a point can be unreachable if and only if it is the \"upper\" horizontal side of our triangle, because it is impossible to draw such line which would intersect with $y = 0$ line and would not intersect with the inner part of our triangle:",
    "code": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <cassert>\n#include <map>\n#include <set>\n#include <cmath>\n#include <array>\n \nusing namespace std;\n \nsigned main() {\n    if (1) {\n        ios_base::sync_with_stdio(false);\n        cin.tie(0);\n        cout.tie(0);\n    }\n    int t;\n    cin >> t;\n    while (t--) {\n        int a, b, c, d, e, f, ans = 0;\n        cin >> b >> a >> d >> c >> f >> e;\n        if (a == c && e < a) ans = abs(b - d);\n        else if (c == e && a < c) ans = abs(d - f);\n        else if (a == e && c < a) ans = abs(b - f);\n        cout << ans << \"\\n\";\n    }\n}\n \n ",
    "tags": [
      "geometry"
    ],
    "rating": 800
  },
  {
    "contest_id": "1642",
    "index": "B",
    "title": "Power Walking",
    "statement": "Sam is a kindergartener, and there are $n$ children in his group. He decided to create a team with some of his children to play \"brawl:go 2\".\n\nSam has $n$ power-ups, the $i$-th has type $a_i$. A child's strength is equal to the number of \\textbf{different} types among power-ups he has.\n\nFor a team of size $k$, Sam will distribute all $n$ power-ups to $k$ children in such a way that each of the $k$ children receives at least one power-up, and each power-up is given to someone.\n\nFor each integer $k$ from $1$ to $n$, find the \\textbf{minimum} sum of strengths of a team of $k$ children Sam can get.",
    "tutorial": "It is quite easy to understand that every multiset's power is at least 1. The final answer is at east the number of distict integers in the multiset. It is possible to proof that the answer to the problem for $k$ is equal to $\\max(k, cnt)$, where $cnt$ is the number of distinct integers. $\\textbf{Proof.}$ If the number of distinct interest is equal to $c \\leq k$, is is obvious that we can create $c$ multisets, $i$-th multiset Will only contain integers which are equal to $i$. We can create $k - c$ multisets of size 1. The answer in this case is equal to $k$. If the number of distinct integers is at least $k$, we can divide the integers into groups in such way that for each $x$ all occurrences of $x$ are located in the same multiset. The answer in this case is equal to $cnt$. In the first case the answer is $k$, in the second case - $cnt$. Thus, the answer is equal to $\\max(k, cnt)$.",
    "code": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <cassert>\n#include <map>\n#include <set>\n#include <cmath>\n#include <array>\n \nusing namespace std;\n \nsigned main() {\n    if (1) {\n        ios_base::sync_with_stdio(false);\n        cin.tie(0);\n        cout.tie(0);\n    }\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        map <int, int> d;\n        for (int i = 0; i < n; ++i) {\n            int x;\n            cin >> x;\n            d[x]++;\n        }\n        int cnt = 0;\n        for (auto i : d) {\n            ++cnt;\n        }\n        int cur_cnt = cnt;\n        for (int k = 1; k <= n; ++k) {\n            cout << max(k, cnt) << \"\\n\";\n        }\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1644",
    "index": "A",
    "title": "Doors and Keys",
    "statement": "The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.\n\nIn a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.\n\nEach door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.\n\nThe knight has a map of the hallway. It can be transcribed as a string, consisting of six characters:\n\n- R, G, B — denoting red, green and blue doors, respectively;\n- r, g, b — denoting red, green and blue keys, respectively.\n\nEach of these six characters appears in the string exactly once.\n\nThe knight is standing at the beginning of the hallway — on the left on the map.\n\nGiven a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway.",
    "tutorial": "The necessary and sufficient condition is the following: for each color the key should appear before the door. Necessary is easy to show: if there is a key after a door, this door can't be opened. Sufficient can be shown the following way. If there are no closed doors left, the knight has reached the princess. Otherwise, consider the first door the knight encounters. He has a key for this door, so he opens it. We remove both the key and the door from the string and proceed to the case with one less door. Overall complexity: $O(1)$.",
    "code": "for _ in range(int(input())):\n\ts = input()\n\tfor (d, k) in zip(\"RGB\", \"rgb\"):\n\t\tif s.find(d) < s.find(k):\n\t\t\tprint(\"NO\")\n\t\t\tbreak\n\telse:\n\t\tprint(\"YES\")",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1644",
    "index": "B",
    "title": "Anti-Fibonacci Permutation",
    "statement": "Let's call a permutation $p$ of length $n$ \\textbf{anti-Fibonacci} if the condition $p_{i-2} + p_{i-1} \\ne p_i$ holds for all $i$ ($3 \\le i \\le n$). Recall that the permutation is the array of length $n$ which contains each integer from $1$ to $n$ exactly once.\n\nYour task is for a given number $n$ print $n$ \\textbf{distinct} anti-Fibonacci permutations of length $n$.",
    "tutorial": "Let's consider one of the possible solutions. Let's put the first element in the $x$-th permutation equal to $x$, and sort all the other elements in descending order. Thus, we get permutations of the form: $[1, n, n-1, \\dots, 2]$, $[2, n, n-1, \\dots, 1]$, ..., $[n, n-1, n-2, \\dots, 1]$. In such a construction $p_{i-1} > p_i$ for all $i$ ($3 \\le i \\le n$), and hence $p_{i-2} + p_{i-1} > p_i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\tcout << i;\n\t\t\tfor (int j = n; j > 0; --j) if (i != j)\n\t\t\t\tcout << ' ' << j;\n\t\t\tcout << '\\n';\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1644",
    "index": "C",
    "title": "Increase Subarray Sums",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$, consisting of $n$ integers. You are also given an integer value $x$.\n\nLet $f(k)$ be the maximum sum of a contiguous subarray of $a$ after applying the following operation: add $x$ to the elements on exactly $k$ \\textbf{distinct} positions. An empty subarray should also be considered, it has sum $0$.\n\nNote that the subarray doesn't have to include all of the increased elements.\n\nCalculate the maximum value of $f(k)$ for all $k$ from $0$ to $n$ independently.",
    "tutorial": "Consider the naive solution. Iterate over $k$. Then iterate over the segment that will have the maximum sum. Let its length be $l$. Since $x$ is non-negative, it's always optimal to increase the elements inside the segment. So if $k \\le l$, then the sum of the segment increases by $k \\cdot x$. Otherwise, only the elements inside the segment will affect the sum, thus, it will increase by $l \\cdot x$. That can be written as $min(k, l) \\cdot x$. Notice that we only care about two parameters for each segment. Its length and its sum. Moreover, if there are several segments with the same length, we only care about the one with the greatest sum. Thus, the idea of the solution is the following. For each length, find the segment of this length with the greatest sum. Then calculate $f(k)$ in $O(n)$ by iterating over the length of the segment. Overall complexity: $O(n^2)$ per testcase.",
    "code": "INF = 10**9\n\nfor _ in range(int(input())):\n\tn, x = map(int, input().split())\n\ta = list(map(int, input().split()))\n\tmx = [-INF for i in range(n + 1)]\n\tmx[0] = 0\n\tfor l in range(n):\n\t\ts = 0\n\t\tfor r in range(l, n):\n\t\t\ts += a[r]\n\t\t\tmx[r - l + 1] = max(mx[r - l + 1], s)\n\tans = [0 for i in range(n + 1)]\n\tfor k in range(n + 1):\n\t\tbst = 0\n\t\tfor i in range(n + 1):\n\t\t\tbst = max(bst, mx[i] + min(k, i) * x)\n\t\tans[k] = bst\n\tprint(\" \".join([str(x) for x in ans]))",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1644",
    "index": "D",
    "title": "Cross Coloring",
    "statement": "There is a sheet of paper that can be represented with a grid of size $n \\times m$: $n$ rows and $m$ columns of cells. All cells are colored in white initially.\n\n$q$ operations have been applied to the sheet. The $i$-th of them can be described as follows:\n\n- $x_i$ $y_i$ — choose one of $k$ non-white colors and color the entire row $x_i$ and the entire column $y_i$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation.\n\nThe sheet after applying all $q$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.\n\nHow many different colorings are there? Print the number modulo $998\\,244\\,353$.",
    "tutorial": "Let's take a look at a final coloring. Each cell has some color. There exist cells such that there were no operation in their row and their column. They are left white, and they don't affect the answer. All other cells are colored in one of $k$ colors. For each cell $(x, y)$ there is a query that has been the last one to color this cell (it covered row $x$, column $y$ or both of them). So all cells that have the same query as the last one will have the same color. Since the color for each query is chosen independently, the number of colorings will be $k$ to the power of the number of queries that have at least one cell belong to them. How to determine if a query has at least one cell. This is true unless one of these things happen afterwards: both its row and its column are recolored; all rows are recolored; all columns are recolored. So the solution is to process the queries backwards. Maintain the set of colored rows and colored columns. For each query, check the conditions. If none hold, multiply the answer by $k$. Overall complexity: $O(q \\log (n + m))$ or $O(q)$ per testcase.",
    "code": "from sys import stdin, stdout\n\nMOD = 998244353\n\nux = []\nuy = []\nfor _ in range(int(stdin.readline())):\n\tn, m, k, q = map(int, stdin.readline().split())\n\twhile len(ux) < n:\n\t\tux.append(False)\n\twhile len(uy) < m:\n\t\tuy.append(False)\n\txs = [-1 for i in range(q)]\n\tys = [-1 for i in range(q)]\n\tfor i in range(q):\n\t\tx, y = map(int, stdin.readline().split())\n\t\txs[i] = x - 1\n\t\tys[i] = y - 1\n\tcx = 0\n\tcy = 0\n\tans = 1\n\tfor i in range(q - 1, -1, -1):\n\t\tfl = False\n\t\tif not ux[xs[i]]:\n\t\t\tux[xs[i]] = True\n\t\t\tcx += 1\n\t\t\tfl = True\n\t\tif not uy[ys[i]]:\n\t\t\tuy[ys[i]] = True\n\t\t\tcy += 1\n\t\t\tfl = True\n\t\tif fl:\n\t\t\tans = ans * k % MOD\n\t\tif cx == n or cy == m:\n\t\t\tbreak\n\tfor i in range(q):\n\t\tux[xs[i]] = False\n\t\tuy[ys[i]] = False\n\tstdout.write(str(ans) + \"\\n\")",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1644",
    "index": "E",
    "title": "Expand the Path",
    "statement": "Consider a grid of size $n \\times n$. The rows are numbered top to bottom from $1$ to $n$, the columns are numbered left to right from $1$ to $n$.\n\nThe robot is positioned in a cell $(1, 1)$. It can perform two types of moves:\n\n- D — move one cell down;\n- R — move one cell right.\n\nThe robot is not allowed to move outside the grid.\n\nYou are given a sequence of moves $s$ — the initial path of the robot. This path doesn't lead the robot outside the grid.\n\nYou are allowed to perform an arbitrary number of modifications to it (possibly, zero). With one modification, you can duplicate one move in the sequence. That is, replace a single occurrence of D with DD or a single occurrence of R with RR.\n\nCount the number of cells such that there exists at least one sequence of modifications that the robot visits this cell on the modified path and doesn't move outside the grid.",
    "tutorial": "First, get rid of the corner cases. If the string doesn't contain either of the letters, the answer is $n$. The general solution to the problem is to consider every single way to modify the path, then find the union of them. Well, every single path is too much, let's learn to reduce the number of different sequences of modifications that we have to consider. The main observation is that all cells that the robot can visit are enclosed in the space formed by the following two paths: the first 'R' is duplicated the maximum number of times, then the last 'D' is duplicated the maximum number of times; the first 'D' is duplicated the maximum number of times, then the last 'R' is duplicated the maximum number of times. You can realize that by drawing the visited cells for some large test. To show that more formally, you can consider the visited cells row by row. Let's show that for every two different visited cells in the same row, all cells in-between them can also be visited. In general case, we want to show that we can take the prefix of the path to the left one of these cells and duplicate any 'R' on it to reach the right cell. The suffixes of the paths will remain the same as in the initial path. If there exists an 'R' on the prefix, then we are good. Otherwise, the reason that it doesn't exist is that we duplicated 'D' too many times. Reduce that and there will be 'R' immediately after reaching the cell or earlier. We should also show that the number of 'R's on the path to the left cell won't reach the maximum allowed amount until reaching the right cell. Use the fact that the number of 'D's on both prefixes of the paths is the same. The other non-obvious part is that you can't reach cells outside this space. However, that can also be shown by analyzing each row independently. Finally, about the way to calculate the area of this space. The main idea is to calculate the total number of cells outside this area and subtract it from $n^2$. Notice that non-visited cells form two separate parts: the one above the first path and the one to the left of the second path. These are pretty similar to each other. Moreover, you can calculate them with a same function. If we replace all 'D's in the string with 'R' and vice versa, then these parts swap places. So we can calculate the upper part, swap them and calculate it again. I think the algorithm is best described with a picture. Consider test $n=15$, $s=$ DDDRRDRRDDRRR, for example. First, there are some rows that only have one cell visited. Then the first 'R' in the string appears. Since we duplicate it the maximum amount of times, it produces a long row of visited cells. The remaining part of the part becomes the outline of the area. Note that the row that marks the end of the string, always ends at the last column. Thus, only at most first $|s|$ rows matter. To be exact, the amount of rows that matter is equal to the number of letters 'D' in the string. For each letter 'D', let's calculate the number of non-visited cells in a row it goes down to. I found the most convenient way is to go over the string backwards. We start from the row corresponding to the number of letters 'D' in the string. It has zero non-visited cells. We can maintain the number of non-visited cells in the current row. If we encounter an 'R' in the string, we add $1$ to this number. If we encounter a 'D', we add the number to the answer. We have to stop after the first 'R' in the string. The later (well, earlier, since we are going backwards) part corresponds to the prefix of letters 'D' - the starting column on the picture. Each of these rows have $1$ visited cell, so $n-1$ non-visited. So we can easily calculate this part as well. Overall complexity: $O(|s|)$ per testcase.",
    "code": "def calc(s, n):\n\tld = s.find('R')\n\tres = ld * (n - 1)\n\ty = 0\n\tfor i in range(len(s) - 1, ld - 1, -1):\n\t\tif s[i] == 'D':\n\t\t\tres += y\n\t\telse:\n\t\t\ty += 1\n\treturn res\n\nfor _ in range(int(input())):\n\tn = int(input())\n\ts = input()\n\tif s.count(s[0]) == len(s):\n\t\tprint(n)\n\t\tcontinue\n\tans = n * n\n\tans -= calc(s, n)\n\tans -= calc(''.join(['D' if c == 'R' else 'R' for c in s]), n)\n\tprint(ans)",
    "tags": [
      "brute force",
      "combinatorics",
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1644",
    "index": "F",
    "title": "Basis",
    "statement": "For an array of integers $a$, let's define $|a|$ as the number of elements in it.\n\nLet's denote two functions:\n\n- $F(a, k)$ is a function that takes an array of integers $a$ and a positive integer $k$. The result of this function is the array containing $|a|$ first elements of the array that you get by replacing each element of $a$ with exactly $k$ copies of that element.For example, $F([2, 2, 1, 3, 5, 6, 8], 2)$ is calculated as follows: first, you replace each element of the array with $2$ copies of it, so you obtain $[2, 2, 2, 2, 1, 1, 3, 3, 5, 5, 6, 6, 8, 8]$. Then, you take the first $7$ elements of the array you obtained, so the result of the function is $[2, 2, 2, 2, 1, 1, 3]$.\n- $G(a, x, y)$ is a function that takes an array of integers $a$ and two \\textbf{different} integers $x$ and $y$. The result of this function is the array $a$ with every element equal to $x$ replaced by $y$, and every element equal to $y$ replaced by $x$.For example, $G([1, 1, 2, 3, 5], 3, 1) = [3, 3, 2, 1, 5]$.\n\nAn array $a$ is a \\textbf{parent} of the array $b$ if:\n\n- either there exists a positive integer $k$ such that $F(a, k) = b$;\n- or there exist two different integers $x$ and $y$ such that $G(a, x, y) = b$.\n\nAn array $a$ is an \\textbf{ancestor} of the array $b$ if there exists a finite sequence of arrays $c_0, c_1, \\dots, c_m$ ($m \\ge 0$) such that $c_0$ is $a$, $c_m$ is $b$, and for every $i \\in [1, m]$, $c_{i-1}$ is a parent of $c_i$.\n\nAnd now, the problem itself.\n\nYou are given two integers $n$ and $k$. Your goal is to construct a sequence of arrays $s_1, s_2, \\dots, s_m$ in such a way that:\n\n- every array $s_i$ contains exactly $n$ elements, and all elements are integers from $1$ to $k$;\n- for every array $a$ consisting of exactly $n$ integers from $1$ to $k$, the sequence contains at least one array $s_i$ such that $s_i$ is an ancestor of $a$.\n\nPrint the minimum number of arrays in such sequence.",
    "tutorial": "First of all, since the second operation changes all occurrences of some number $x$ to other number $y$ and vice versa, then, by using it, we can convert an array into another array if there exists a bijection between elements in the first array and elements in the second array. It can also be shown that $F(G(a, x, y), m) = G(F(a, m), x, y)$, so we can consider that if we want to transform an array into another array, then we first apply the function $F$, then the function $G$. Another relation that helps us is that $G(G(a, x, y), x, y) = a$, it means that every time we apply the function $G$, we can easily rollback the changes. Considering that we have already shown that a sequence of transformations can be reordered so that we apply $G$ only after we've made all operations with the function $F$, let's try to \"rollback\" the second part of transformations, i. e. for each array, find some canonical form which can be obtained by using the function $G$. Since applying the second operation several times is equal to applying some bijective function to the array, we can treat each array as a partition of the set $\\{1, 2, \\dots, n\\}$ into several subsets. So, if we are not allowed to perform the first operation, the answer to the problem is equal to $\\sum \\limits_{i=1}^{\\min(n, k)} S(n, i)$, where $S(n, i)$ is the number of ways to partition a set of $n$ objects into $i$ non-empty sets (these are known as Stirling numbers of the second kind). There are many ways to calculate Stirling numbers of the second kind, but in this problem, we will have to use some FFT-related approach which allows getting all Stirling numbers for some value of $n$ in time $O(n \\log n)$. For example, you can use the following relation: $S(n, k) = \\frac{1}{k!} \\sum \\limits_{i = 0}^{k} (-1)^i {{k}\\choose{i}} (k-i)^n$ $S(n, k) = \\sum \\limits_{i=0}^{k} \\frac{(-1)^i \\cdot k! \\cdot (k-i)^n}{k! \\cdot i! \\cdot (k-i)!}$ $S(n, k) = \\sum \\limits_{i=0}^{k} \\frac{(-1)^i}{i!} \\cdot \\frac{(k-i)^n}{(k-i)!}$ If we substitute $p_i = \\frac{(-1)^i}{i!}$ and $q_j = \\frac{j^n}{j!}$, we can see that the sequence of Stirling numbers for some fixed $n$ is just the convolution of sequences $p$ and $q$. For simplicity in the following formulas, let's denote $A_i = \\sum \\limits_{j=1}^{\\min(i, k)} S(i, j)$. We now know that this value can be calculated in $O(i \\log i)$. Okay, now back to the original problem. Unfortunately, we didn't take the operation $F$ into account. Let's analyze it. The result of function $F(a, m)$ consists of several blocks of equal elements, and it's easy to see that the lengths of these blocks (except for maybe the last one) should be divisible by $m$. The opposite is also true - if the lengths of all blocks (except maybe for the last one) are divisible by some integer $m$, then the array can be produced as $F(a, m)$ for some array $a$. What does it mean? If the greatest common divisor of the lengths of the blocks (except for the last one) is not $1$, the array that we consider can be obtained by applying the function $F$ to some other array. Otherwise, it cannot be obtained in such a way. Now, inclusion-exclusion principle comes to the rescue. Let's define $B_i$ as the number of arrays that we consider which have the lengths of all their blocks (except maybe for the last one) divisible by $i$. It's easy to see that $B_i = A_{\\lceil \\frac{n}{i} \\rceil}$ (we can compress every $i$ consecutive elements into one). Then, using inclusion exclusion principle, we can see that the answer is $\\sum \\limits_{i=1}^{n} \\mu(i) B_i = \\sum \\limits_{i=1}^{n} \\mu(i) A_{\\lceil \\frac{n}{i} \\rceil}$ where $\\mu(i)$ is the Mobius function. Using this formula, we can calculate the answer in $O(n \\log^2 n)$. Note 1. This inclusion-exclusion principle handles the arrays according to the GCD of the blocks that they consist of, except for the last one. But what if the array consists only of one block? These arrays can be counted wrongly, so we should exclude them - i. e. use $A_i - S(i, 1)$ instead of just $A_i$ and count the arrays consisting of the same element (if we need any of them in the answer separately). Note 2. Depending on the way you implement this, $n = 1$ or $k = 1$ (or both) may be a corner case.",
    "tags": [
      "combinatorics",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1646",
    "index": "A",
    "title": "Square Counting",
    "statement": "Luis has a sequence of $n+1$ integers $a_1, a_2, \\ldots, a_{n+1}$. For each $i = 1, 2, \\ldots, n+1$ it is guaranteed that $0\\leq a_i < n$, or $a_i=n^2$. He has calculated the sum of all the elements of the sequence, and called this value $s$.\n\nLuis has lost his sequence, but he remembers the values of $n$ and $s$. Can you find the number of elements in the sequence that are equal to $n^2$?\n\nWe can show that the answer is unique under the given constraints.",
    "tutorial": "Let the number of elements in the sequence equal to $n^2$ be $x$ and let the sum of all other numbers be $u$. Then, $s=x\\cdot n^2+u$. If an element of the sequence is not equal to $n^2$, then its value is at most is $n-1$. There are $n+1$ numbers in the sequence, so $u\\leq (n-1)\\times (n+1)=n^2-1$. Thus, $\\displaystyle \\left \\lfloor \\frac{s}{n^2} \\right \\rfloor= \\left \\lfloor \\frac{x\\cdot n^2+u}{n^2} \\right \\rfloor=\\left\\lfloor x+\\frac{u}{n^2} \\right\\rfloor=x$, which is the value we want to find. So, to solve the problem it is enough to compute the value of $\\displaystyle \\left\\lfloor \\frac{s}{n^2} \\right\\rfloor$. Intended complexity: $O(1)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tint t; cin >> t;\n\tfor(int i = 0; i < t; i++){\n\t\tlong long n, s; \n\t\tcin >> n >> s;\n\t\tcout << s / (n * n) << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1646",
    "index": "B",
    "title": "Quality vs Quantity",
    "statement": "$ \\def\\myred#1{\\textcolor{red}{\\underline{\\bf{#1}}}} \\def\\myblue#1{\\textcolor{blue}{\\overline{\\bf{#1}}}} $ $\\def\\RED{\\myred{Red}} \\def\\BLUE{\\myblue{Blue}}$\n\nYou are given a sequence of $n$ non-negative integers $a_1, a_2, \\ldots, a_n$. Initially, all the elements of the sequence are unpainted. You can paint each number $\\RED$ or $\\BLUE$ (but not both), or \\textbf{leave it unpainted}.\n\nFor a color $c$, $\\text{Count}(c)$ is the number of elements in the sequence painted with that color and $\\text{Sum}(c)$ is the sum of the elements in the sequence painted with that color.\n\nFor example, if the given sequence is $[2, 8, 6, 3, 1]$ and it is painted this way: $[\\myblue{2}, 8, \\myred{6}, \\myblue{3}, 1]$ (where $6$ is painted red, $2$ and $3$ are painted blue, $1$ and $8$ are unpainted) then $\\text{Sum}(\\RED)=6$, $\\text{Sum}(\\BLUE)=2+3=5$, $\\text{Count}(\\RED)=1$, and $\\text{Count}(\\BLUE)=2$.\n\nDetermine if it is possible to paint the sequence so that $\\text{Sum}(\\RED) > \\text{Sum}(\\BLUE)$ and $\\text{Count}(\\RED) < \\text{Count}(\\BLUE)$.",
    "tutorial": "$\\def\\myred#1{\\color{red}{\\underline{\\bf{#1}}}} \\def\\myblue#1{\\color{blue}{\\overline{\\bf{#1}}}}$ $\\def\\RED{\\myred{Red}} \\def\\BLUE{\\myblue{Blue}}$ Suppose $\\text{Count}(\\RED)=k$. If a solution exists, then there is one with $\\text{Count}(\\BLUE)=k+1$, because if there are more than $k+1$ numbers painted blue, we can remove some of them until we have exactly $k+1$ numbers, and the sum of these numbers will be smaller. As we want $\\text{Sum}(\\RED) > \\text{Sum}(\\BLUE)$ to hold, the optimal way to paint the numbers is to paint the $k$ largest numbers red, and the $k+1$ smallest numbers blue. So, to solve the problem it is enough to sort the sequence, iterate over the value of $k$ and for each of them compute the sum of the $k$ largest numbers, the sum of the $k+1$ smallest numbers and compare them. This can be done efficiently by computing the sum of every prefix and suffix of the sorted sequence in linear time. This way, we can make a constant number of operations for each $k$. Intended complexity: $\\mathcal{O}(n\\:\\text{log}\\:n)$ It can be proven that (try to prove it!) if some $k$ works, then $k=\\displaystyle \\left \\lfloor \\frac{n-1}{2} \\right \\rfloor$ has to work. This means that there is always an answer using $n$ or $n-1$ elements, depending on parity.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tios::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\tint t; cin >> t;\n\tfor(int test_number = 0; test_number < t; test_number++){\n\t\tint n; cin >> n;\n\t\tvector <long long> a(n);\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tcin >> a[i];\n\t\t}\n\t\tsort(a.begin(), a.end());\n\t\tvector <long long> prefix_sums = {0};\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tprefix_sums.push_back(prefix_sums.back() + a[i]);\n\t\t}\n\t\tvector <long long> suffix_sums = {0};\n\t\tfor(int i = n - 1; i >= 0; i--){\n\t\t\tsuffix_sums.push_back(suffix_sums.back() + a[i]);\n\t\t}\n\t\tbool answer = false;\n\t\tfor(int k = 1; k <= n; k++){\n\t\t\tif(2 * k + 1 <= n){\n\t\t\t\tlong long blue_sum = prefix_sums[k + 1];\n\t\t\t\tlong long red_sum = suffix_sums[k];\n\t\t\t\tif(blue_sum < red_sum){\n\t\t\t\t\tanswer = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(answer) cout << \"YES\\n\";\n\t\telse cout << \"NO\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1646",
    "index": "C",
    "title": "Factorials and Powers of Two",
    "statement": "A number is called powerful if it is a power of two or a factorial. In other words, the number $m$ is powerful if there exists a non-negative integer $d$ such that $m=2^d$ or $m=d!$, where $d!=1\\cdot 2\\cdot \\ldots \\cdot d$ (in particular, $0! = 1$). For example $1$, $4$, and $6$ are powerful numbers, because $1=1!$, $4=2^2$, and $6=3!$ but $7$, $10$, or $18$ are not.\n\nYou are given a positive integer $n$. Find the minimum number $k$ such that $n$ can be represented as the sum of $k$ \\textbf{distinct} powerful numbers, or say that there is no such $k$.",
    "tutorial": "If the problem asked to represent $n$ as a sum of distinct powers of two only (without the factorials), then there is a unique way to do it, using the binary representation of $n$ and the number of terms will be the number of digits equal to $1$ in this binary representation. Let's denote this number by $\\text{ones}(n)$. If we fix the factorials we are going to use in the sum, then the rest of the terms are uniquely determined because of the observation above. Note that $1$ and $2$ will not be considered as factorials in order to avoid repeating terms. So, to solve the problem it is enough to iterate through all possibilities of including or not including each factorial (up to $14!$) and for each of them calculate the number of terms used in the sum. If we used $f$ factorials and their sum is $s$, then the number of terms can be calculated as $f+\\text{ones}(n-s)$. The minimum of all these numbers will be the answer. Intended complexity: $\\mathcal{O}(2^k)$ where $k$ is the biggest positive integer such that $k!\\leq n$ Actually, there is no problem in repeating $1$, $2$, or any other power of two. This is because it can be proven that (try to prove it!) those sums are not optimal.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long MAXAI = 1000000000000ll;\n\nint get_first_bit(long long n){\n\treturn 63 - __builtin_clzll(n);\n}\n\nint get_bit_count(long long n){\n\treturn __builtin_popcountll(n);\n}\n\nint main(){\n\tios::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\tint t; cin >> t;\n\tfor(int test_number = 0; test_number < t; test_number++){\n\t\tlong long n; cin >> n;\n\t\t//Computing factorials <= MAXAI\n\t\tvector<long long> fact;\n\t\tlong long factorial = 6, number = 4;\n\t\twhile(factorial <= MAXAI){\n\t\t\tfact.push_back(factorial);\n\t\t\tfactorial *= number;\n\t\t\tnumber++;\n\t\t}\n\t\t//Computing masks of factorials\n\t\tvector<pair<long long, long long>> fact_sum(1 << fact.size());\n\t\tfact_sum[0] = {0, 0};\n\t\tfor(int mask = 1; mask < (1 << fact.size()); mask++){\n\t\t\tauto first_bit = get_first_bit(mask);\n\t\t\tfact_sum[mask].first = fact_sum[mask ^ (1 << first_bit)].first + fact[first_bit];\n\t\t\tfact_sum[mask].second = get_bit_count(mask);\n\t\t}\n\t\tlong long res = get_bit_count(n);\n\t\tfor(auto i : fact_sum){\n\t\t\tif(i.first <= n){\n\t\t\t\tres = min(res, i.second + get_bit_count(n - i.first));\n\t\t\t}\n\t\t}\n\t\tcout << res << \"\\n\";\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1646",
    "index": "D",
    "title": "Weight the Tree",
    "statement": "You are given a tree of $n$ vertices numbered from $1$ to $n$. A tree is a connected undirected graph without cycles.\n\nFor each $i=1,2, \\ldots, n$, let $w_i$ be the weight of the $i$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.\n\nInitially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree.",
    "tutorial": "If $n=2$, we can assign $w_1=1$ and $w_2=1$ and there is no way to get a better answer because all vertices are good and the sum of weights cannot be smaller because the weights have to be positive. If $n>2$, two vertices sharing an edge cannot be both good. To prove this, we are going to analyze two cases. If the two vertices have distinct weights, then the one with a smaller weight cannot be good, because the one with a larger weight is its neighbor. Otherwise, if both vertices have the same weight, then none of them can have another neighbor, as that would increase the sum of their neighbors by at least $1$. So, the only way this could happen is if $n=2$, but we are assuming that $n>2$. Thus, the set of good vertices must be an independent set. We will see that for each independent set of vertices in the tree, there is an assignment of weights where all the vertices from this set are good. We can assign a weight of $1$ to each vertex that is not in the set, and assign its degree to each vertex in the set. Because all neighbors of a vertex in the set are not in the set, then all of them have a weight of $1$ and this vertex is good. Therefore, the maximum number of good vertices is the same as the maximum size of an independent set in this tree. For a fixed independent set of the maximum size, the construction above leads to a configuration with the minimum sum of weights. This is because all vertices must have a weight of at least $1$, and the vertices in the set must have a weight of at least its degree. So, to solve the problem it is enough to root the tree in an arbitrary vertex and solve a tree dp. Let's call $f(x, b)$ to the pair $(g, s)$, where $g$ is the maximum number of good vertices in the subtree of vertex $x$ assuming that $x$ is good (if $b=1$) or that it is not good (if $b=0$), and $s$ is the minimum sum of weights for that value $g$. The values of $f(x,b)$ can be computed with a dp, using the values of $f$ in the children of node $x$. If $b=1$, then for each child $c$ you must sum $f(c,0)$. If $b=0$, for each child $c$ you can choose the best answer between $f(c,0)$ and $f(c,1)$. The answer to the problem will be the best between $f(\\text{root},0)$ and $f(\\text{root},1)$ To construct the assignment of weights, you can do it recursively considering for each vertex if it has to be good or not, in order to keep the current value of the answer. In case both options (making it good or not) work, you have to choose to not make it good, as you do not know if its father was good or not. Intended complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 400005;\n\nvector<int> g[MAXN];\n\nbool vis[MAXN];\nint pa[MAXN];\n\n//DFS to compute the parent of each node\n//parent of node i is stored at pa[i]\nvoid dfs(int v){\n\tvis[v] = 1;\n\tfor(auto i : g[v]){\n\t\tif(!vis[i]){\n\t\t\tpa[i] = v;\n\t\t\tdfs(i);\n\t\t}\n\t}\n}\n\npair<int, int> dp[MAXN][2];\n\n//Computes the value of function f, using dp\n//the second coordinate of the pair is negated (to take maximums)\npair<int, int> f(int x, int y){\n\tpair<int, int> & res = dp[x][y];\n\tif(res.first >= 0) return res;\n\tres = {y, y ? -((int) g[x].size()) : -1};\n\tfor(auto i : g[x]){\n\t\tif(i != pa[x]){\n\t\t\tpair<int, int> maxi = f(i, 0);\n\t\t\tif(y == 0) maxi = max(maxi, f(i, 1));\n\t\t\tres.first += maxi.first;\n\t\t\tres.second += maxi.second;\n\t\t}\n\t}\n\treturn res;\n}\n\nvector<int> is_good;\n\n//Recursive construction of the answer\n//is_good[i] tells whether vertex i is good or not.\nvoid build(pair<int, int> value, int v){\n\tif(value == f(v, 0)){\n\t\tis_good[v] = 0;\n\t\tfor(auto i : g[v]){\n\t\t\tif(i != pa[v]){\n\t\t\t\tbuild(max(f(i, 0), f(i, 1)), i);\n\t\t\t}\n\t\t}\n\t}else{\n\t\tis_good[v] = 1;\n\t\tfor(auto i : g[v]){\n\t\t\tif(i != pa[v]){\n\t\t\t\tbuild(f(i, 0), i);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(){\n\tios::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\tint n; cin >> n;\n\tfor(int i = 0; i < n - 1; i++){\n\t\tint u, v; \n\t\tcin >> u >> v; u--; v--;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\tif(n == 2){\n\t\tcout<<\"2 2\\n1 1\\n\";\n\t\treturn 0;\n\t}\n\tpa[0] = -1;\n\tdfs(0);\n\tfor(int i = 0; i < n; i++) dp[i][0] = {-1, -1}, dp[i][1] = {-1, -1};\n\tpair<int, int> res = max(f(0, 0), f(0, 1));\n\tcout << res.first << \" \" << -res.second << \"\\n\";\n\tis_good.resize(n);\n\tbuild(res, 0);\n\tfor(int i = 0; i < n; i++){\n\t\tif(is_good[i]) cout << g[i].size() << \" \";\n\t\telse cout << \"1 \";\n\t}\n\tcout << \"\\n\";\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "implementation",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1646",
    "index": "E",
    "title": "Power Board",
    "statement": "You have a rectangular board of size $n\\times m$ ($n$ rows, $m$ columns). The $n$ rows are numbered from $1$ to $n$ from top to bottom, and the $m$ columns are numbered from $1$ to $m$ from left to right.\n\nThe cell at the intersection of row $i$ and column $j$ contains the number $i^j$ ($i$ raised to the power of $j$). For example, if $n=3$ and $m=3$ the board is as follows:\n\nFind the number of distinct integers written on the board.",
    "tutorial": "It is easy to see that the first row only contains the number $1$ and that this number doesn't appear anywhere else on the board. We say that an integer is a perfect power if it can be represented as $x^a$ where $x$ and $a$ are positive integers and $a>1$. For each positive integer $x$ which is not a perfect power, we call $R(x)$ to the set of all numbers which appear in rows $x, x^2, x^3, \\ldots$. Claim: If $x\\neq y$ are not perfect powers, then $R(x)$ and $R(y)$ have no elements in common. Proof: Suppose there is a common element, then there exist positive integers $a,b$ such that $x^a=y^b$. This is the same as $\\displaystyle x=y^{\\frac{b}{a}}$. Because $y$ is not a perfect power, $\\displaystyle \\frac{b}{a}$ has to be a positive integer. If $\\displaystyle \\frac{b}{a}=1$ then $x=y$, which cannot happen. So then $\\displaystyle \\frac{b}{a}>1$, which cannot happen as $x$ is not a perfect power. Thus, this common element cannot exist. Based on the observation above, for each not perfect power $x$ we can compute the size of $R(x)$ independently and then sum the results. For a fixed $x$, let $k$ be the number of rows that start with a power of $x$. Then $R(x)$ contains all numbers of the form $x^{i\\cdot j}$ where $1\\leq i\\leq k$ and $1\\leq j\\leq m$. But, the size of this set is the same as the size of the set containing all numbers of the form $i\\cdot j$ where $1\\leq i\\leq k$ and $1\\leq j\\leq m$. Note that the number of elements in this set does not depend on $x$, it just depends on $k$. Thus, the size of $R(x)$ is uniquely determined by the value of $k$. As $x^k\\leq n$, then we have that $k\\leq \\text{log}(n)$. Then, for each $k=1,2,\\ldots,\\lfloor\\text{log}(n)\\rfloor$ we just need to compute the number of distinct elements of the form $i\\cdot j$ where $1\\leq i\\leq k$ and $1\\leq j\\leq m$. We can do this using an array of length $m \\cdot \\text{log}(n)$, and at the $i$-th step (for $i=1,2,\\ldots,\\lfloor\\text{log}(n)\\rfloor$) we mark the numbers $i,2i,\\ldots, mi$ as visited in the array, and add one to the value we are computing for each number that was not visited before. After the $i$-th step we have computed this value for $k=i$. So, to solve the problem it is enough to compute for each not perfect power $x$, how many rows in the matrix start with a power of $x$ and using the values we calculated in the last paragraph we can know how many distinct numbers are there in $R(x)$. Intended complexity: $\\mathcal{O}(m\\:\\text{log}\\:n + n)$ This solution uses the fact that $m\\le 10^6$, other solutions do not use this, and work for much larger values of $m$ (like $m\\leq 10^{18}$, but taking the answer modulo some big prime number). Try to solve the problem with this new constraint!",
    "code": "#include <bits/stdc++.h>\n#define fore(i,a,b) for(ll i=a,ggdem=b;i<ggdem;++i)\nusing namespace std;\ntypedef long long ll;\n\nconst int MAXM = 1000006;\n\nconst int MAXLOGN = 20;\n\nbool visited_mul[MAXM * MAXLOGN];\n\nint main(){\n\tll n, m; cin >> n >> m;\n\tvector<ll> mul_quan(MAXLOGN);\n\tll current_vis = 0;\n\tfore(i, 1, MAXLOGN){\n\t\tfore(j, 1, m+1){\n\t\t\tif(!visited_mul[i * j]){\n\t\t\t\tvisited_mul[i * j] = 1;\n\t\t\t\tcurrent_vis++;\n\t\t\t}\n\t\t}\n\t\tmul_quan[i] = current_vis;\n\t}\n\tll res=1;\n\tvector<ll> vis(n + 1);\n\tfore(i, 2, n+1){\n\t\tif(vis[i]) continue;\n\t\tll power = i, power_quan = 0;\n\t\twhile(power <= n){\n\t\t\tvis[power] = 1;\n\t\t\tpower_quan++;\n\t\t\tpower *= i;\n\t\t}\n\t\tres += mul_quan[power_quan];\n\t}\n\tcout << res << \"\\n\";\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1646",
    "index": "F",
    "title": "Playing Around the Table",
    "statement": "There are $n$ players, numbered from $1$ to $n$ sitting around a round table. The $(i+1)$-th player sits to the right of the $i$-th player for $1 \\le i < n$, and the $1$-st player sits to the right of the $n$-th player.\n\nThere are $n^2$ cards, each of which has an integer between $1$ and $n$ written on it. For each integer from $1$ to $n$, there are exactly $n$ cards having this number.\n\nInitially, all these cards are distributed among all the players, in such a way that each of them has exactly $n$ cards. In one operation, each player chooses one of his cards and passes it to the player to his right. All these actions are performed \\textbf{simultaneously}.\n\nPlayer $i$ is called solid if all his cards have the integer $i$ written on them. Their objective is to reach a configuration in which everyone is solid. Find a way to do it using at most $(n^2-n)$ operations. You do \\textbf{not} need to minimize the number of operations.",
    "tutorial": "For each player, we say it is diverse if all his cards have different numbers. For each player, we will call a card repeated if this player has two or more cards with that number. Observe that a player is diverse if and only if he has no repeated cards. To construct the answer we are going to divide the process into two parts, each of them using at most $\\displaystyle \\frac{n\\times(n-1)}{2}$ operations. In the first part, we are going to reach a configuration where everyone is diverse. In the second one, we will reach the desired configuration. To do the first part, in each operation we will choose for each player a repeated card to pass. We will repeat this until all players are diverse. If some player is already diverse, he will pass a card with the same number as the card he will receive in that operation. This way, if a player was diverse before the operation, he will still be diverse after the operation. We will prove that the above algorithm ends. If it does not end, at some point some non-diverse player will pass a card he already passed (not a card with the same number, the exact same card). At this point, all other players have at least one card with this number and this player has at least two (because it is non-diverse), but this implies that there are at least $n+1$ cards with this number, which cannot happen. Now, we will prove that this algorithm ends in at most $\\displaystyle\\frac{n\\times(n-1)}{2}$ operations. Consider all cards having the number $c$, and for each of them consider the distance it moved, but when a player is diverse, we will consider his cards as static and that the card he received (or a previous one, if there are multiple diverse players before him) moved more than once in a single operation. For each $x$, such that $1\\leq x\\leq n-1$, consider all cards having the number $c$ that moved a distance of $x$ or more, and look at the one that reaches its final destination first. The first $x$ players that passed this card already had a card with the number $c$ on it, and for each of them, one of these cards will not move anymore (remember that once the player is diverse, his cards are static) and it moved less than $x$, as we are considering the first card. So, there are at most $n-x$ cards that moved a distance of $x$ or more. Thus, the maximum sum of distances of all cards containing the number $c$ is $\\displaystyle 1+2+\\ldots+(n-1)=\\frac{n\\times(n-1)}{2}$ and the maximum sum of distances of all cards is $\\displaystyle \\frac{n^2\\times(n-1)}{2}$. In each operation, the sum of all distances is increased by $n$ so there will be at most $\\displaystyle \\frac{n\\times(n-1)}{2}$ operations in this part. To do the second part, for each $j=1,2,\\ldots,n-1$ (in this order) the $i$-th player will pass a card with the number $((i-j)\\bmod n) + 1$ a total of $j$ times. It is easy to see that after $\\displaystyle 1+2+\\ldots+(n-1)=\\frac{n\\times(n-1)}{2}$ operations, all players are solid. Implementing the first part naively will result in an $\\mathcal{O}(n^4)$ algorithm, which is enough to solve the problem. However, it is possible to divide the complexity by $n$ maintaining a stack of repeated cards for each player. Intended complexity: $\\mathcal{O}(n^3)$ Additionally, competitive__programmer has made video editorials for problems B, C and D.",
    "code": "#include <bits/stdc++.h>\n#define fore(i, a, b) for(int i = a; i < b; ++i)\nusing namespace std;\n \nconst int MAXN = 1010;\n\n//c[i][j] = number of cards player i has, with the number j\nint c[MAXN][MAXN];\n \n//extras[i] is the stack of repeated cards for player i.\nvector<int> extras[MAXN];\n \nint main(){\n\tios::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\tint n; cin >> n;\n\tfore(i, 0, n){\n\t\tfore(j, 0, n){\n\t\t\tint x; cin >> x; x--;\n\t\t\tc[i][x]++;\n\t\t\tif(c[i][x] > 1) extras[i].push_back(x);\n\t\t}\n\t}\n\tvector<vector<int>> res;\n\t//First part\n\twhile(true){\n\t\t//oper will describe the next operation to perform\n\t\tvector<int> oper(n);\n\t\t//s will be the first non-diverse player\n\t\tint s = -1;\n\t\tfore(i, 0, n){\n\t\t\tif(extras[i].size()){\n\t\t\t\ts = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(s == -1) break;\n\t\t//last_card will be the card that the previous player passed\n\t\tint last_card = -1;\n\t\tfore(i, s, s + n){\n\t\t\tint real_i = i % n;\n\t\t\tif(extras[real_i].size()){\n\t\t\t\tlast_card = extras[real_i].back();\n\t\t\t\textras[real_i].pop_back();\n\t\t\t}\n\t\t\toper[real_i] = last_card;\n\t\t}\n\t\tres.push_back(oper);\n\t\tfore(i, 0, n){\n\t\t\tint i_next = (i + 1) % n;\n\t\t\tc[i][oper[i]]--;\n\t\t\tc[i_next][oper[i]]++;\n\t\t}\n\t\tfore(i, 0, n){\n\t\t\tint i_next = (i + 1) % n;\n\t\t\tif(c[i_next][oper[i]] > 1) extras[i_next].push_back(oper[i]);\n\t\t}\n\t}\n\t//Second part\n\tfore(j, 1, n){\n\t\tvector<int> oper;\n\t\tfore(i, 0, n) oper.push_back((i - j + n) % n);\n\t\tfore(i, 0, j) res.push_back(oper);\n\t}\n\tcout << res.size() << \"\\n\";\n\tfor(auto i : res){\n\t\tfor(auto j : i) cout<< j + 1 << \" \";\n\t\tcout << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1647",
    "index": "A",
    "title": "Madoka and Math Dad",
    "statement": "Madoka finally found the administrator password for her computer. Her father is a well-known popularizer of mathematics, so the password is the answer to the following problem.\n\nFind the maximum decimal number without zeroes and with no equal digits in a row, such that the sum of its digits is $n$.\n\nMadoka is too tired of math to solve it herself, so help her to solve this problem!",
    "tutorial": "Since we want to maximize the number we need, we will first find the longest suitable number. Obviously, it is better to use only the numbers $1$ and $2$ for this. Therefore, the answer always looks like $2121\\ldots$ or $1212\\ldots$. The first option is optimal when $n$ has a remainder of $2$ or $0$ modulo $3$, otherwise the second option is optimal. Below is an example of a neat implementation.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    int type;\n    if (n % 3 == 1)\n        type = 1;\n    else\n        type = 2;\n    int sum = 0;\n    while (sum != n) {\n        cout << type;\n        sum += type;\n        type = 3 - type;\n    }\n    cout << '\n';\n}\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1647",
    "index": "B",
    "title": "Madoka and the Elegant Gift",
    "statement": "Madoka's father just reached $1$ million subscribers on Mathub! So the website decided to send him a personalized award — The Mathhub's Bit Button!\n\nThe Bit Button is a rectangular table with $n$ rows and $m$ columns with $0$ or $1$ in each cell. After exploring the table Madoka found out that:\n\n- A subrectangle $A$ is contained in a subrectangle $B$ if there's no cell contained in $A$ but not contained in $B$.\n- Two subrectangles intersect if there is a cell contained in both of them.\n- A subrectangle is called \\textbf{black} if there's no cell with value $0$ inside it.\n- A subrectangle is called \\textbf{nice} if it's \\textbf{black} and it's not contained in another \\textbf{black} subrectangle.\n- The table is called \\textbf{elegant} if there are no two \\textbf{nice} intersecting subrectangles.\n\nFor example, in the first illustration the red subrectangle is nice, but in the second one it's not, because it's contained in the purple subrectangle.\n\nHelp Madoka to determine whether the table is elegant.",
    "tutorial": "Note that the answer to the problem is \"YES\" if and only if the picture is a certain number of disjoint rectangles. Now, in this case, let's look at all squares of size $2\\times 2$, note that there cannot be exactly $3$ filled cells in each of them. It is also clear that if there are $3$ such cells, then there will be two intersecting rectangles. Therefore, you just need to check if there is a $2\\times 2$ square in which there are exactly $3$ colored cells.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> a(n, vector<int> (m));\n    for (int i = 0; i < n; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < m; ++j) {\n            a[i][j] = s[j] - '0';\n        }\n    }\n    for (int i = 0; i < n - 1; ++i) {\n        for (int j = 0; j < m - 1; ++j) {\n            int sum = a[i][j] + a[i][j + 1] + a[i + 1][j] + a[i + 1][j + 1];\n            if (sum == 3) {\n                cout << \"NO\n\";\n                return;\n            }\n        }\n    }\n    cout << \"YES\n\";\n}\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1647",
    "index": "C",
    "title": "Madoka and Childish Pranks",
    "statement": "Madoka as a child was an extremely capricious girl, and one of her favorite pranks was drawing on her wall. According to Madoka's memories, the wall was a table of $n$ rows and $m$ columns, consisting only of zeroes and ones. The coordinate of the cell in the $i$-th row and the $j$-th column ($1 \\le i \\le n$, $1 \\le j \\le m$) is $(i, j)$.\n\nOne day she saw a picture \"Mahou Shoujo Madoka Magica\" and decided to draw it on her wall. Initially, the Madoka's table is a table of size $n \\times m$ filled with zeroes. Then she applies the following operation any number of times:\n\nMadoka selects any rectangular subtable of the table and paints it in a chess coloring (the upper left corner of the subtable always has the color $0$). Note that some cells may be colored several times. In this case, the final color of the cell is equal to the color obtained during the last repainting.\n\n\\begin{center}\n{\\small White color means $0$, black means $1$. So, for example, the table in the first picture is painted in a chess coloring, and the others are not.}\n\\end{center}\n\nFor better understanding of the statement, we recommend you to read the explanation of the first test.\n\nHelp Madoka and find some sequence of no more than $n \\cdot m$ operations that allows you to obtain the picture she wants, or determine that this is impossible.",
    "tutorial": "According to the condition, if the upper left cell is painted black, then we cannot paint it that way. Otherwise it is possible. Let's colour the cells in the following order: $(n,m), (n,m - 1), \\ldots, (n, 1), (n - 1, m), \\ldots (1, 1)$. Let the cell $(i, j)$ be colored black, then if $j > 1$, then just paint the rectangle $(i, j - 1)$, $(i, j)$. Otherwise, if $j = 1$, then we will color the rectangle $(i - 1, j)$. After such an operation, no cells that we painted before will be repainted, since they have one coordinate larger than ours, and the cell itself will be painted black. Thus, we are able to paint the table for a maximum of $n\\cdot m - 1$ operations.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> a(n, vector<int> (m));\n    for (int i = 0; i < n; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < m; ++j)\n            a[i][j] = s[j] - '0';\n    }\n    vector<array<int, 4>> ans;\n    if (a[0][0] == 1) {\n        cout << -1<< '\n';\n        return;\n    }\n    \n    for (int j = m - 1; j >= 0; --j) {\n        for (int i = n - 1; i >= 0; --i) {\n            if (a[i][j]) {\n                if (i != 0) {\n                    ans.push_back({i, j + 1, i + 1, j + 1});\n                } else {\n                    ans.push_back({i + 1, j, i + 1, j + 1});\n                }\n            }\n        }\n    }\n    cout << ans.size() << '\n';\n    for (auto i : ans) {\n        cout << i[0] << ' ' << i[1] << ' ' << i[2] << ' ' << i[3] << '\n';\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1647",
    "index": "D",
    "title": "Madoka and the Best School in Russia",
    "statement": "Madoka is going to enroll in \"TSUNS PTU\". But she stumbled upon a difficult task during the entrance computer science exam:\n\n- A number is called good if it is a multiple of $d$.\n- A number is called beatiful if it is \\textbf{good} and it \\textbf{cannot} be represented as a product of two good numbers.\n\nNotice that a beautiful number must be good.\n\nGiven a good number $x$, determine whether it can be represented in at least two different ways as a product of several (possibly, one) \\textbf{beautiful} numbers. Two ways are different if the sets of numbers used are different.\n\nSolve this problem for Madoka and help her to enroll in the best school in Russia!",
    "tutorial": "Let's solve a more complex problem: calculate the number of partitions into such multipliers. This is easily solved by dynamic programming. Let $dp_{n, d}$ be the number of factorizations, if we have a number left to decompose the number $n$, and before that we divided by the number $d$. Let's go through all such beautiful numbers $i\\geq d$ that divide $n$, then $dp_{n /i, i} += dp_{n, d}$. Note that in this case, we took into account each option exactly once, since we count the divisors in the order of their increase. Let $C$ be the number of divisors of the number $x$, and $V$ be the number of beautiful divisors of the number $x$. Then it works for $O(C\\cdot V)$ or $O(C\\cdot V^2\\cdot log)$ depending on the implementation (since $n$ is always a divisor of the number $x$), but it all comes easily, since $V$ is no more $700$. Let $x = d^a\\cdot b$. Where $b$ is not a multiple of $d$. Then consider a few cases: $a = 1$. Then $a$ is a beautiful number, since any number multiple of $d^2$ can be decomposed into $d\\cdot(a/d)$, each of which is colored, and a number multiple of only $d$, obviously, cannot be decomposed. So in this case there is exactly one option. $b$ is composite, then obviously we can decompose in several ways if $a\\neq 1$. $d$ is simple. If $b$ is prime, then the statement - we have only one option to decompose the number. Since every beautiful multiplier of the form $d\\cdot k$. But since $d$ is simple, there are no other ways to decompose it, except to add a multiplier from $b$, and since $b$ is simple, then all these options will be equal before the permutation. $d$ is composite and is not a power of prime. If $a\\leq 2$, then this case is no different from the past, since we still have to get two beautiful multipliers and they will all just be equal to $d$. Otherwise, let $d = p\\cdot q$, where $gcd(p, q) = 1$. Then we can make the number $p\\cdot q^{b - 1}$ and $p^{b - 1}\\cdot q$. And also $q\\cdot p, q\\cdot p, \\ldots , q\\cdot p$, in this case we have a different number of divisors, so these options will be different, which means we have several options in this case. $d$ is the power of a prime number. Then $d = p^k$. The statement, if $d = p^2$, and $x =p^7$, then it cannot be decomposed in several ways, otherwise, if $a > 2$ and $k >1$, then let's look at the partition of $p^{2k - 1}, p^{k+1}, p^k, \\ldots , p^k$, it is clear that if $k > 2$, then even if $b = p$, then the multiplier of $p^{k+ 2}$ will still be beautiful, so it does not differ from the composite $d$ in last case. Otherwise, if $k = 2$, then if $a = 3$ and $b = p$, then nothing can be added, otherwise we will have the opportunity to choose $3$ of the multiplier $p^k$, and somehow decompose the rest (since in this case $a > 3$, then at least one more multiplier will be) and add $b$ there. And we can decompose these 3 multipliers into $2$ or $3$ multipliers, as written above. Therefore, the only unique case when $d$ is the degree of a prime is $d = p^2, x = p^7$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint prime(int x) {\n    for (int i = 2; i * i <= x; ++i) {\n        if (x % i == 0)\n            return i;\n    }\n    return -1;\n}\n \nvoid solve() {\n    int x, d;\n    cin >> x >> d;\n    int cnt = 0;\n    while (x % d == 0) {\n        ++cnt;\n        x /= d;\n    }\n    if (cnt == 1) {\n        cout << \"NO\n\";\n        return;\n    }\n    if (prime(x) != -1) {\n        cout << \"YES\n\";\n        return;\n    }\n    if (prime(d) != -1 && d == prime(d) * prime(d)) {\n        if (x == prime(d) && cnt == 3) {\n            cout << \"NO\n\";\n            return;\n        }\n    }\n    if (cnt > 2 && prime(d) != -1) {\n        cout << \"YES\n\";\n        return;\n    }\n    cout << \"NO\n\";\n}\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1647",
    "index": "E",
    "title": "Madoka and the Sixth-graders",
    "statement": "After the most stunning success with the fifth-graders, Madoka has been trusted with teaching the sixth-graders.\n\nThere's $n$ single-place desks in her classroom. At the very beginning Madoka decided that the student number $b_i$ ($1 \\le b_i \\le n$) will sit at the desk number $i$. Also there's an infinite line of students with numbers $n + 1, n + 2, n + 3, \\ldots$ waiting at the door with the hope of being able to learn something from the Madoka herself. Pay attention that each student has his \\textbf{unique} number.\n\nAfter each lesson, the following happens in sequence.\n\n- The student sitting at the desk $i$ moves to the desk $p_i$. All students move simultaneously.\n- If there is more than one student at a desk, the student with the lowest number keeps the place, and the others are removed from the class \\textbf{forever}.\n- For all empty desks in ascending order, the student from the lowest number from the outside line occupies the desk.\n\nNote that in the end there is exactly one student at each desk again. It is guaranteed that the numbers $p$ are such that at least one student is removed after each lesson. Check out the explanation to the first example for a better understanding.\n\nAfter several (possibly, zero) lessons the desk $i$ is occupied by student $a_i$. Given the values $a_1, a_2, \\ldots, a_n$ and $p_1, p_2, \\ldots, p_n$, find the lexicographically smallest suitable initial seating permutation $b_1, b_2, \\ldots, b_n$.\n\nThe permutation is an array of $n$ different integers from $1$ up to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not ($2$ occurs twice). $[1,3,4]$ is not a permutation either ($n=3$ but there's $4$ in the array).\n\nFor two different permutations $a$ and $b$ of the same length, $a$ is lexicographically less than $b$ if in the first position where $a$ and $b$ differ, the permutation $a$ has a smaller element than the corresponding element in $b$.",
    "tutorial": "After each lesson, the person's number increases from the maximum number by the number of desks where no one goes. Therefore, it is easy to calculate how much time has passed since the very beginning, let it be the number $k$. Then let's imagine that schoolchildren are not expelled, but at any given time we are simply interested in a student with a minimum number. Obviously, the answer in this case will not change in any way. Let $to_i$ be the desk to which the student will move after $k$ transfers, who originally sat at $i$ desk. This is a standard problem that can be solved using binary lifts or not the most pleasant dfs with cycle allocation and the like. (but we do not recommend you to write the latter), we define the set $V_i$ as the set of all numbers $j$, where $to_j = i$. Let the starting placement of the student be a permutation of $b$, then we will understand that if someone is transferred to the $i$ desk after $k$ operations, then the value in it is the minimum value in $V_i$. And if no one changes seats for it, then a student with the same number will always sit in it, regardless of the initial seating arrangement. After that, it is not difficult to guess the optimal starting seating of schoolchildren. Let $s$ be a lot of schoolchildren for whom we have not yet chosen the desk at which they are sitting. We will iterate over $i$ from $1$ to $n$ in ascending order. Then you need to understand who should sit at the $i$ desk. If we know that there is a desk for which $min(V_i) = i$ must be performed, then we must put a student with the minimum number of $V_i$ at $i$, and we can put the remaining people at any desks with a number greater than $i$, so we will add all the other students to the set $s$. Otherwise, we just need to take a person from $s$ with the minimum number and put him in a place under the number $i$, and then just remove him from the set of $s$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int K = 30;\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n \n    int n;\n    cin >> n;\n    vector<int> cnt(n);\n    vector<vector<int>> up(n, vector<int> (K));\n    for (int i = 0; i < n; ++i) {\n        int a;\n        cin >> a;\n        --a;\n        ++cnt[a];\n        up[i][0] = a;\n    }\n    for (int k = 1; k < K; ++k) {\n        for (int i = 0; i < n; ++i) {\n            up[i][k] = up[up[i][k - 1]][k - 1];\n        }\n    }\n    vector<int> a(n);\n    int cnt_bad = 0;\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n        if (!cnt[i]) {\n            ++cnt_bad;\n        }\n    }\n    int k = (*max_element(a.begin(), a.end()) - n) / cnt_bad;\n    vector<vector<int>> add(n);\n \n    for (int i = 0; i < n; ++i) {\n        int v = i, level = k;\n        for (int j = K - 1; j >= 0; --j) {\n            if (level >= (1 << j)) {\n                level -= (1 << j);\n                v = up[v][j];\n            }\n        }\n        add[a[v] - 1].push_back(i);\n    }\n    set<int> now;\n    vector<int> ans(n);\n    for (int i = 0; i < n; ++i) {\n        if (add[i].size()) {\n            int res = *min_element(add[i].begin(), add[i].end());\n            for (int j : add[i]) {\n                if (j != res) {\n                    now.emplace(j);\n                }\n            }\n            ans[res] = i + 1;\n        } else {\n            ans[*now.begin()] = i + 1;\n            now.erase(*now.begin());\n        }\n    }\n    for (int i : ans)\n        cout << i << ' ';\n    cout << '\n';\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1647",
    "index": "F",
    "title": "Madoka and Laziness",
    "statement": "Madoka has become too lazy to write a legend, so let's go straight to the formal description of the problem.\n\nAn array of integers $a_1, a_2, \\ldots, a_n$ is called a hill if it is not empty and there is an index $i$ in it, for which the following is true: $a_1 < a_2 < \\ldots < a_i > a_{i + 1} > a_{i + 2} > \\ldots > a_n$.\n\nA sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) elements keeping the order of the other elements. For example, for an array $[69, 1000, 228, -7]$ the array $[1000, -7]$ is a subsequence, while $[1]$ and $[-7, 1000]$ are not.\n\nSplitting an array into two subsequences is called good if each element belongs to exactly one subsequence, and also each of these subsequences is a hill.\n\nYou are given an array of \\textbf{distinct} positive integers $a_1, a_2, \\ldots a_n$. It is required to find the number of different pairs of maxima of the first and second subsequences among all good splits. Two pairs that only differ in the order of elements are considered same.",
    "tutorial": "The inflection of the sequence is the maximum number in the subsequence. Then note that in the first subsequence, the inflection will be the maximum number in our array, let its position in the array be $ind$. Then let's say for convenience that the inflection of the second subsequence will be to the right of the maximum element. (then expand the array and run the solution one more time). In this case, we will have $3$ states: both subsequences increase, the first decreases, and the second increases, or both subsequences decrease. Let's solve the first case first: Let $dp1_i$ be the minimum possible maximum element in a subsequence that does not contain an $i$ element. It is considered not difficult. If $dp1_{i - 1} < a_{i}$, then $dp1_{i} = min(dp1_{i}, a_{i - 1})$, since in this case we can add an $i$ element to a subsequence that does not contain an element of $i - 1$. Similarly, if $a_{i - 1} < a_{i}$, then $dp1_{i} = min(dp1_{i}, dp1_{i - 1})$. The third case is considered anologically, but only it needs to be counted from the end. (This array will be $dp3$) Now let's deal with the second case: Let $dp2_{i, 0}$ be the minimum possible last element in the second subsequence if the $i$ element belongs to the first subsequence. And $dp2_{i, 1}$ is the maximum possible last element in the first subsequence if the $i$ element belongs to the second subsequence. There are several options. If $i$ and $i - 1$ lie in the same and different subsequences. And we will count for $i\\leq ind$, since before this section both sub-sequences increase, and this is another calculated case. And then it is not difficult to get the conversion formulas: $dp2_{ind, 0} = dp1_{ind}$, by definition $dp2_{ind, 0}$ If $a_{i - 1} > a_i$, then $dp2_{i, 0} = min(dp2_{i, 0}, dp2_{i - 1, 0})$. If $dp2_{i - 1, 1} > a_i$, then $dp2_{i, 0} = min(dp2_{i, 0}, a_{i - 1})$. If $a_{i - 1} < a_{i}$, then $dp2_{i, 1} = max(dp2_{i, 1}, dp3_{i - 1, 1})$. If $dp2_{i - 1, 0} < a_i$, then $dp2_{i, 1} = max(dp2_{i, 1}, a_{i - 1})$. Now let's understand that the element with the number $i$ can be an inflection of the second subsequence if $i > ind$, as well as $dp2_{i, 1} > dp3_{i}$. That is, we can move from the second state to the third.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int inf = 1e9 + 228;\n \nint solve (int n, vector<int> a) {\n    int ind = max_element(a.begin(), a.end()) - a.begin();\n    vector<int> dp1(n, inf);\n    dp1[0] = -1;\n    for (int i = 1; i <= ind; ++i) {\n        if (a[i] > dp1[i - 1])\n            dp1[i] = min(dp1[i], a[i - 1]);\n        if (a[i] > a[i - 1])\n            dp1[i] = min(dp1[i], dp1[i - 1]);\n    }\n \n    vector<int> dp2(n, inf);\n    dp2[n - 1] = -1;\n    for (int i = n - 2; i >= ind; --i) {\n        if (a[i] > dp2[i + 1])\n            dp2[i] = min(dp2[i], a[i + 1]);\n        if (a[i] > a[i + 1])\n            dp2[i] = min(dp2[i], dp2[i + 1]);\n    }\n \n    vector<array<int, 2>> dp3(n, {inf, -inf});\n    dp3[ind][0] = dp1[ind];\n    int ans = 0;\n    for (int i = ind + 1; i < n; ++i) {\n        if (a[i - 1] > a[i])\n            dp3[i][0] = min(dp3[i][0], dp3[i - 1][0]);\n        if (dp3[i - 1][1] > a[i])\n            dp3[i][0] = min(dp3[i][0], a[i - 1]);\n        \n        if (a[i - 1] < a[i])\n            dp3[i][1] = max(dp3[i][1], dp3[i - 1][1]);\n        if (dp3[i - 1][0] < a[i])\n            dp3[i][1] = max(dp3[i][1], a[i - 1]);\n        \n        if (dp3[i][1] > dp2[i])\n            ++ans;\n    }\n    return ans;\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n \n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i)\n        cin >> a[i];\n    int ans = solve(n, a);\n    reverse(a.begin(), a.end());\n    cout << ans + solve(n, a) << '\n';\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1648",
    "index": "A",
    "title": "Weird Sum",
    "statement": "Egor has a table of size $n \\times m$, with lines numbered from $1$ to $n$ and columns numbered from $1$ to $m$. Each cell has a color that can be presented as an integer from $1$ to $10^5$.\n\nLet us denote the cell that lies in the intersection of the $r$-th row and the $c$-th column as $(r, c)$. We define the \\underline{manhattan distance} between two cells $(r_1, c_1)$ and $(r_2, c_2)$ as the length of a shortest path between them where each consecutive cells in the path must have a common side. The path can go through cells of any color. For example, in the table $3 \\times 4$ the manhattan distance between $(1, 2)$ and $(3, 3)$ is $3$, one of the shortest paths is the following: $(1, 2) \\to (2, 2) \\to (2, 3) \\to (3, 3)$.\n\nEgor decided to calculate the sum of manhattan distances between each pair of cells of the same color. Help him to calculate this sum.",
    "tutorial": "We note that the manhattan distance between cells $(r_1, c_1)$ and $(r_2, c_2)$ is equal to $|r_1-r_2|+|c_1-c_2|$. For each color we will compose a list of all cells $(r_0, c_0), \\ldots, (r_{k-1}, c_{k-1})$ of this color, compute the target sum for this color, and sum up the answers for all colors. The sum is equal: $\\sum_{i=0}^{k-1} \\sum_{j=i+1}^{k-1} |r_i - r_j| + |c_i - c_j| = \\left(\\sum_{i=0}^{k-1} \\sum_{j=i+1}^{k-1} |r_i - r_j|\\right) + \\left(\\sum_{i=0}^{k-1} \\sum_{j=i+1}^{k-1} |c_i - c_j|\\right)$ We will compute the first sum, the second sum is analogous. Let an array $s$ be equal to $r$, but sorted in increasing order. Then: $\\sum_{i=0}^{k-1} \\sum_{j=i+1}^{k-1} |r_i - r_j| = \\sum_{i=0}^{k-1} \\sum_{j=i+1}^{k-1} s_j - s_i = \\left(\\sum_{i=0}^{k-1} \\sum_{j=i+1}^{k-1} s_j\\right) + \\left(\\sum_{i=0}^{k-1} \\sum_{j=i+1}^{k-1} -s_i\\right)$ The value $s_j$ occurs in the first double sum exactly $j$ times, the value $-s_i$ occurs in the second sum exactly $k-1-i$ times. Then, the value is equal to: $\\sum_{j=0}^{k-1} js_j + \\sum_{i=0}^{k-1} -(k-1-i)s_i = \\sum_{i=0}^{k-1} (2i+1-k)s_i$ The last sum can be computed in $O(k)$, the time complexity to sort an array is $O(k \\log k)$. The overall complexity is $O(nm\\log(nm))$. We can also sort arrays of coordinates by adding cells to lists in the right order. This yields an $O(nm)$ solution.",
    "tags": [
      "combinatorics",
      "data structures",
      "geometry",
      "math",
      "matrices",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1648",
    "index": "B",
    "title": "Integral Array",
    "statement": "You are given an array $a$ of $n$ positive integers numbered from $1$ to $n$. Let's call an array integral if for any two, not necessarily different, numbers $x$ and $y$ from this array, $x \\ge y$, the number $\\left \\lfloor \\frac{x}{y} \\right \\rfloor$ ($x$ divided by $y$ with rounding down) is also in this array.\n\nYou are guaranteed that all numbers in $a$ do not exceed $c$. Your task is to check whether this array is integral.",
    "tutorial": "Let's consider $x, y \\in a$ and $r \\notin a$. If $y \\cdot r \\le x < y \\cdot (r + 1)$ then $\\left \\lfloor \\frac{x}{y} \\right \\rfloor = r$, but $r$ is not in $a$, so the answer is \"No\". Let's suggest that $y$ and $r$ are already given. We can check if there exists such $x \\in a$ from the mentioned segment in $O(1)$. It is done by considering array $cnt_x$ - the amount of occurrences of $x$ in $a$, and prefix sums for that array. Now we only need to run this check for each $r$ and $y$. To do that we can iterate through all $r \\notin a$ and $y \\in a$ in increasing order. If $r \\cdot y > c$ then there is definitely no such $x$ so we can consider the next $r$. This optimization speeds up the process and makes the whole solution work in $O(C \\log C)$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1648",
    "index": "C",
    "title": "Tyler and Strings",
    "statement": "While looking at the kitchen fridge, the little boy Tyler noticed magnets with symbols, that can be aligned into a string $s$.\n\nTyler likes strings, and especially those that are lexicographically smaller than another string, $t$. After playing with magnets on the fridge, he is wondering, how many distinct strings can be composed out of letters of string $s$ by rearranging them, so that the resulting string is lexicographically smaller than the string $t$? Tyler is too young, so he can't answer this question. The alphabet Tyler uses is very large, so for your convenience he has already replaced the same letters in $s$ and $t$ to the same integers, keeping that different letters have been replaced to different integers.\n\nWe call a string $x$ lexicographically smaller than a string $y$ if one of the followings conditions is fulfilled:\n\n- There exists such position of symbol $m$ that is presented in both strings, so that before $m$-th symbol the strings are equal, and the $m$-th symbol of string $x$ is smaller than $m$-th symbol of string $y$.\n- String $x$ is the prefix of string $y$ and $x \\neq y$.\n\nBecause the answer can be too large, print it modulo $998\\,244\\,353$.",
    "tutorial": "Let $K$ be the size of the alphabet, that is, the number of the maximum letter that occurs in it. First, let's calculate how many different strings can be composed if we have $c_1$ letters of the $1$th type, $c_2$ letters of the $2$th type, $\\ldots$, $c_K$ letters of the $K$ type. This is the school formula: $P(c_1, c_2, \\ldots, c_K) = \\frac{(c_1 + c_2 + \\ldots + c_K)!}{c_1! \\cdot c_2! \\cdot \\ldots \\cdot c_K!}$ to quickly calculate it for different $c_1, c_2, \\ldots, c_k$ pre-calculate all factorials and their reciprocals modulo $C = 998244353$ in O($n \\cdot \\log{C}$) In order for the string $x$ to be less than the string t, they must have the same prefix. Let's iterate over the length of this matching prefix from $0$ to $\\min(n, m)$. If strings $x$ and $t$ have the same first $i$ characters, then we know exactly how many letters we have left. To support this, let's create an array cnt, at the $i$-th position of which there will be the number of remaining letters of type $i$. Let's iterate over the letter that will appear immediately after the matching prefix. For the resulting string to be less than $t$, this letter must be strictly less than the corresponding letter in $t$, and all subsequent letters can be arranged in any order. Let's calculate the number of rows $x$ considered in this way according to the formula above. The only case where the resulting string $x$ can be lexicographically less than $t$, which we will not count, is when it is a prefix of the string $t$, but has a shorter length. We will separately check whether we can get such a string, and if so, add 1 to the answer. Since at each of at most $\\min(n, m)$ steps we need to go through at most $K$ options for the next letter, and we calculate each option in O($K$) - we get the asymptotics O($\\min (n, m) \\cdot K^2 + n \\cdot \\log{C}$) To speed up the resulting solution, let's create an array $add$, in the $i$-th cell of which we store how many ways it will be possible to arrange the remaining letters if the letter $i$ is put in the current position. In fact $add_i = \\frac{(cnt_1 + cnt_2 + \\ldots + cnt_K - 1)!}{cnt_1! \\cdot cnt_2! \\cdot \\ldots \\cdot (cnt_i - 1)! \\cdot \\ldots \\cdot cnt_K!}$ If we learn how to maintain this array, then at each step we only need to take the sum of the elements at some of its prefix. Let's see how it changes if the next letter in the string $t$ is $i$, i.e. $cnt_i$ should decrease by 1. For all cells $j \\neq i$ $add_j$ is replaced by $add_j \\cdot \\frac{cnt_i}{cnt_1 + cnt_2 + \\ldots + cnt_K - 1}$. To apply modifications to the entire array, let's create a separate variable $modify$, by which we need to multiply the value in the cell to get the value that should be there. For cell $i$, $add_i$ will be replaced by $add_i \\cdot \\frac{cnt_i - 1}{cnt_1 + cnt_2 + \\ldots + cnt_K - 1}$. And taking into account the fact that we applied a modifier to all cells, it is enough to multiply the value of $add_i$ by $\\frac{cnt_i - 1}{cnt_i}$ With this optimization, we now spend only O(K) actions at each step to calculate the prefix sum, and O($\\log(C)$) to calculate what to multiply the array cells by. We get the asymptotics O($\\min(n, m) \\cdot (K + \\log(C))$) To get rid of $K$ asymptotically, note that the only thing we want to do with the $add$ array is take the sum at the prefix and change the value at the point. This can be done in O($log(K)$ using the Fenwick Tree or the Segment Tree. Applying them, we get the final asymptotic O($\\min(n, m) \\cdot (\\log(K) + \\log(C))$). In fact, $\\log(C)$ in the asymptotics can be eliminated by precalculating modulo reciprocals for all numbers from $1$ to $n$ faster than O($n \\cdot \\log(C)$), but in this task was not required.",
    "tags": [
      "combinatorics",
      "data structures",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1648",
    "index": "D",
    "title": "Serious Business",
    "statement": "Dima is taking part in a show organized by his friend Peter. In this show Dima is required to cross a $3 \\times n$ rectangular field. Rows are numbered from $1$ to $3$ and columns are numbered from $1$ to $n$.\n\nThe cell in the intersection of the $i$-th row and the $j$-th column of the field contains an integer $a_{i,j}$. Initially Dima's score equals zero, and whenever Dima reaches a cell in the row $i$ and the column $j$, his score changes by $a_{i,j}$. Note that the score can become negative.\n\nInitially all cells in the first and the third row are marked as available, and all cells in the second row are marked as unavailable. However, Peter offered Dima some help: there are $q$ special offers in the show, the $i$-th special offer allows Dima to mark cells in the second row between $l_i$ and $r_i$ as available, though Dima's score reduces by $k_i$ whenever he accepts a special offer. Dima is allowed to use as many special offers as he wants, and might mark the same cell as available multiple times.\n\nDima starts his journey in the cell $(1, 1)$ and would like to reach the cell $(3, n)$. He can move either down to the next row or right to the next column (meaning he could increase the current row or column by 1), thus making $n + 1$ moves in total, out of which exactly $n - 1$ would be horizontal and $2$ would be vertical.\n\nPeter promised Dima to pay him based on his final score, so the sum of all numbers of all visited cells minus the cost of all special offers used. Please help Dima to maximize his final score.",
    "tutorial": "Let's denote $pref[i][j] := \\sum_{k = 0}^{j - 1} a[i][k]$. Then define $s$ and $t$ as follows: $s[i] = pref[0][i + 1] - pref[1][i]$ $f[i] = pref[1][i + 1] - pref[2][i] + pref[2][n]$ Now we can transform the problem to following: compute $\\max\\limits_{0\\leq i\\leq j < n} s[i] + f[j] - cost(i, j)$ where $cost(i, j)$ is the minimal cost of unlocking segment $[i, j]$. Let's define $dp[i]$ as the maximum profit for going from $(1, 1)$ to $(2, i)$, if the rightmost segment that we have used ends in $i$ (so it's $s[j]$ for some $j$ minus cost of covering segment $[i, j]$, when we know that there's a segment ending at $i$). The calculation of $dp$ is as follows: for all $i$ look through each segment, which ends at $i$, and relax $dp[i]$ with $\\max\\limits_{l - 1\\leq j < i} dp[j] - k$. It can be calculated using segment tree. Now consider the optimal usage of segments. Fix the rightmost segment. The profit for this segment usage should be $dp[i] + f[j] + k$ for some $i, j$ on this segment. So we can bruteforce the rightmost segment in our answer and relax the overall answer with $\\max\\limits_{l\\leq i\\leq j\\leq r} dp[i] + f[j] - k$. Also there's a case where taking only 1 segment is optimal, then we should relax the answer with $\\max\\limits_{l\\leq i\\leq j\\leq r} s[i] + f[j] - k$. We can calculate all of this using segment tree. Overall complexity is $O(q\\, log\\, n)$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "implementation",
      "shortest paths"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1648",
    "index": "E",
    "title": "Air Reform",
    "statement": "Berland is a large country with developed airlines. In total, there are $n$ cities in the country that are historically served by the Berlaflot airline. The airline operates bi-directional flights between $m$ pairs of cities, $i$-th of them connects cities with numbers $a_i$ and $b_i$ and has a price $c_i$ for a flight in both directions.\n\nIt is known that Berlaflot flights can be used to get from any city to any other (possibly with transfers), and the cost of any route that consists of several consequent flights is equal to the cost of the most expensive of them. More formally, the cost of the route from a city $t_1$ to a city $t_k$ with $(k-2)$ transfers using cities $t_2,\\ t_3,\\ t_4,\\ \\ldots,\\ t_{k - 1}$ is equal to the maximum cost of flights from $t_1$ to $t_2$, from $t_2$ to $t_3$, from $t_3$ to $t_4$ and so on until the flight from $t_{k - 1}$ to $t_k$. Of course, all these flights must be operated by Berlaflot.\n\nA new airline, S8 Airlines, has recently started operating in Berland. This airline provides bi-directional flights between all pairs of cities that are not connected by Berlaflot direct flights. Thus, between each pair of cities there is a flight of either Berlaflot or S8 Airlines.\n\nThe cost of S8 Airlines flights is calculated as follows: for each pair of cities $x$ and $y$ that is connected by a S8 Airlines flight, the cost of this flight is equal to the minimum cost of the route between the cities $x$ and $y$ at Berlaflot according to the pricing described earlier.\n\nIt is known that with the help of S8 Airlines flights you can get from any city to any other with possible transfers, and, similarly to Berlaflot, the cost of a route between any two cities that consists of several S8 Airlines flights is equal to the cost of the most expensive flight.\n\nDue to the increased competition with S8 Airlines, Berlaflot decided to introduce an air reform and change the costs of its flights. Namely, for the $i$-th of its flight between the cities $a_i$ and $b_i$, Berlaflot wants to make the cost of this flight equal to the minimum cost of the route between the cities $a_i$ and $b_i$ at S8 Airlines. Help Berlaflot managers calculate new flight costs.",
    "tutorial": "The formal statement of this problem is that we have a weighted graph, for which we build it's complement, where the weight of an edge between $A$ and $B$ equals to minimal maximum on path from $A$ to $B$ in initial graph. The same way we calculate edge weights of initial graph, and we have to output them. We can notice, that the path where maximum wight is minimal goes directly through the minumum spanning tree. That means that in order to get the final edges weights we need to calculate the minimum spanning tree on the graph complement and to get the final weights of initial edges we need to get the maximum on the tree path, which we can do in $O(m \\log n)$ time with binary jumping pointers. In order to build the minimum spanning tree of graph complement, we will do something like Kruskal algorithm. We will sort the edges of initial graph by their weights and store sets of connected vertices by edges of weights less than last added. The same way we will store the sets of connected vertices in graph complement by edges of weights less than last added. These complement components will form subsets of initial components. While adding a new edge, some connected components of initial graph can be merged. That means that some complement components can be merged. We can merge only those complement components, that are subsets of different initial components that became merged after adding an edge. These complement components become merged only if there exists some edge between two vertices of complement components in complement graph. In other words, between some pair of vertices in different complement components there is no edge in initial graph. So when two initial components $S$ and $T$ become merged, we can iterate over all pair of complement components, such that first one is subset of $S$ and second one is subset of $T$. For each two vertices in them we should check that there is an edge between them in initial graph. Only in this case we can not merge these two complement components. For each of this unsuccessful attempt of merging two complement components, we do as much iterations, as there are edges between them in initial graph. So the total number of iterations in unsuccessful merges is $O(m)$. And for successful merges the complement components are merged and a new edge is added to complement minimum spanning tree. So the total number of successful merges is $O(n)$ and the total time if $O(m \\log m)$ for edges sorting and $O(m)$ for complement MST build. After that we can find weights of initial edges in $O(m \\log n)$ time.",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1648",
    "index": "F",
    "title": "Two Avenues",
    "statement": "In order to make the capital of Berland a more attractive place for tourists, the great king came up with the following plan: choose two streets of the city and call them avenues. Certainly, these avenues will be proclaimed extremely important historical places, which should attract tourists from all over the world.\n\nThe capital of Berland can be represented as a graph, the vertices of which are crossroads, and the edges are streets connecting two crossroads. In total, there are $n$ vertices and $m$ edges in the graph, you can move in both directions along any street, you can get from any crossroad to any other by moving only along the streets, each street connects two different crossroads, and no two streets connect the same pair of crossroads.\n\nIn order to reduce the flow of ordinary citizens moving along the great avenues, it was decided to introduce a toll on each avenue in both directions. Now you need to pay $1$ tugrik for one passage along the avenue. You don't have to pay for the rest of the streets.\n\nAnalysts have collected a sample of $k$ citizens, $i$-th of them needs to go to work from the crossroad $a_i$ to the crossroad $b_i$. After two avenues are chosen, each citizen will go to work along the path with minimal cost.\n\nIn order to earn as much money as possible, it was decided to choose two streets as two avenues, so that the total number of tugriks paid by these $k$ citizens is maximized. Help the king: according to the given scheme of the city and a sample of citizens, find out which two streets should be made avenues, and how many tugriks the citizens will pay according to this choice.",
    "tutorial": "Let's consider two edges from the answer $e_1$, $e_2$. At least one of them should lie on dfs tree, otherwise the graph will be connected after removing $e_1$, $e_2$ and the answer will be $0$. Let the answer be $e_1$, $e_2$, where $e_1$ lies on dfs tree. What cases can be for edges $e_1$, $e_2$? The edge $e_2$ should be a bridge of the graph without edge $e_1$ (otherwise $e_2$ can be any). Using this we can highlight possible cases: Both edges $e_1$, $e_2$ are bridges of the graph. The edge $e_1$ is the bridge of the graph, the edge $e_2$ does not matter. The edge $e_1$ lies on dfs tree, the edge $e_2$ is the only outer edge covering the edge $e_1$. Both edges $e_1$, $e_2$ lies on dfs tree, sets of outer edges covering $e_1$, and covering $e_2$ are equal. For each case let's find the maximum answer. For each of $k$ pairs of vertices let's consider the path between vertices in the pair. For each edge $e$ of dfs tree let's calculate three values: $c_e$ - the number of paths, containing the edge $e$. $f_e$ - the number of outer edges, covering the edge $e$. $h_e$ - the hash of all outer edges, covering the edge $e$. For each outer edge let's give random $64$-bit integer, the hash will be equal to the sum of values. In the first case, the answer for two bridges $e_1$, $e_2$ is equal to $c_{e_1} + c_{e_2}$. So we should find two brides with maximum value $c_e$. In the second case, the answer for one bridge $e_1$ is equal to $c_{e_1}$. So we should find the bridge with maximum value $c_e$. In the third case, we consider edges $e_1$, such that $f_{e_1} = 1$. The answer is $c_{e_1}$. So we should find edge $e_1$ of dfs tree, such that $f_{e_1} = 1$ with maximum value $c_{e_1}$. The fourth case is very hard. We consider two edges $e_1$, $e_2$, such that $h_{e_1} = h_{e_2}$. The answer is equal to the number of paths, containing exactly one edge from $e_1$, $e_2$. We can divide each path into two vertical paths, the answer won't change. The plan of the solution will be: let's make a dfs of the dfs tree and maintain the segment tree with operations add on segment, and maximum on segment. The prefix of the segment tree corresponds to edges on the path from the root to the current edge $e_2$. The value in the cell corresponding to the edge $e_1$ is equal to the answer for the pair of edges $e_1$, $e_2$. It is possible to recalculate this segment tree with $O(n + k)$ updates during the dfs tree traversal. The unsolved problem now is how to consider only edges $e_1$, such that $h_{e_1} = h_{e_2}$ in the maximum on segment. Let's call a cluster all edges with equal hash. All edges from one cluster lie on the vertical path. Let's consider the vertical path for each cluster: from the first occurrence of edge from the cluster to the last occurrence of edge from the cluster. Any two paths for two clusters either do not intersect or nested into each other. When making a traversal let's add $-\\infty$ on the segment from the last edge with hash $h_{e_2}$ to the edge $e_2$. This move will exclude edges from the maximum. This won't interfere the values, because all hashes from the segment won't be found later in the traversal (due to the clusters structure). After that, let's find the maximum on the segment from the first edge with hash $h_{e_2}$ to the edge $e_2$. In that maximum all edges with the hash $h_{e_2}$ will participate. The total solution has the complexity $O(m + (n + k) \\log{n})$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1649",
    "index": "A",
    "title": "Game",
    "statement": "You are playing a very popular computer game. The next level consists of $n$ consecutive locations, numbered from $1$ to $n$, each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also, if you become inside a location with water, you will die, so you can only move between locations with land.\n\nYou can jump between adjacent locations for free, as well as \\textbf{no more than} once jump from any location with land $i$ to any location with land $i + x$, spending $x$ coins ($x \\geq 0$).\n\nYour task is to spend the minimum possible number of coins to move from the first location to the last one.\n\nNote that this is always possible since both the first and last locations are the land locations.",
    "tutorial": "It is easy to see that if there are no water locations, the answer is $0$. Otherwise, we should jump from the last accessible from the start land location to the first land location from which the finish is accessible. In order to find these locations, one can use two consecutive while loops, one increasing $l$ from $1$ until $a_{l + 1} = 0$, and the other one decreasing $r$ from $n$ until $a_{r - 1} = 0$. After the loops finish, we know that we should jump from the $l$-th location to the $r$-th at the cost of $r - l$.",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1649",
    "index": "B",
    "title": "Game of Ball Passing",
    "statement": "Daniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session.\n\nThe game involves $n$ players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how many balls were involved during the game. The only thing he knows is the number of passes delivered by each player during all the session.\n\nFind the minimum possible amount of balls that were involved in the game.",
    "tutorial": "If $max(a) \\cdot 2 \\leq sum(a)$, we can always prove that we can only use one ball. For other cases, the number of balls is determined by $2 \\cdot max(a) - sum(a)$.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1650",
    "index": "A",
    "title": "Deletions of Two Adjacent Letters",
    "statement": "The string $s$ is given, the string length is \\textbf{odd} number. The string consists of lowercase letters of the Latin alphabet.\n\nAs long as the string length is greater than $1$, the following operation can be performed on it: select any two adjacent letters in the string $s$ and delete them from the string. For example, from the string \"lemma\" in one operation, you can get any of the four strings: \"mma\", \"lma\", \"lea\" or \"lem\" In particular, in one operation, the length of the string reduces by $2$.\n\nFormally, let the string $s$ have the form $s=s_1s_2 \\dots s_n$ ($n>1$). During one operation, you choose an arbitrary index $i$ ($1 \\le i < n$) and replace $s=s_1s_2 \\dots s_{i-1}s_{i+2} \\dots s_n$.\n\nFor the given string $s$ and the letter $c$, determine whether it is possible to make such a sequence of operations that in the end the equality $s=c$ will be true? In other words, is there such a sequence of operations that the process will end with a string of length $1$, which consists of the letter $c$?",
    "tutorial": "There will be one character left in the end, so we have to delete all the characters going before and after it. That is, delete some prefix and suffix. Since we always delete some substring of length $2$, we can only delete the prefix and suffix of even length, it means the answer is YES in the case when there is an odd position in $s$ with the character $c$ and NO otherwise.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        string s, t;\n        cin >> s >> t;\n        bool yes = false;\n        forn(i, s.length())\n            if (s[i] == t[0] && i % 2 == 0)\n                yes = true;\n        cout << (yes ? \"YES\" : \"NO\") << endl;\n    }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1650",
    "index": "B",
    "title": "DIV + MOD",
    "statement": "Not so long ago, Vlad came up with an interesting function:\n\n- $f_a(x)=\\left\\lfloor\\frac{x}{a}\\right\\rfloor + x \\bmod a$, where $\\left\\lfloor\\frac{x}{a}\\right\\rfloor$ is $\\frac{x}{a}$, rounded \\textbf{down}, $x \\bmod a$ — the remainder of the integer division of $x$ by $a$.\n\nFor example, with $a=3$ and $x=11$, the value $f_3(11) = \\left\\lfloor\\frac{11}{3}\\right\\rfloor + 11 \\bmod 3 = 3 + 2 = 5$.\n\nThe number $a$ is fixed and known to Vlad. Help Vlad find the maximum value of $f_a(x)$ if $x$ can take any integer value from $l$ to $r$ inclusive ($l \\le x \\le r$).",
    "tutorial": "Consider $f_a(r)$. Note that $\\left\\lfloor\\frac{r}{a}\\right\\rfloor$ is maximal over the entire segment from $l$ to $r$, so if there is $x$ in which $f_a$ gives a greater result, then $x \\bmod a > r\\bmod a$. Note that numbers from $r - r \\bmod a$ to $r$ that have an incomplete quotient when divided by $a$ equal to $\\left\\lfloor\\frac{r}{a}\\right\\rfloor$ do not fit this condition (and are guaranteed to have a value $f_a$ less than $f_a(r)$). And the number $x = r - r \\bmod a - 1$: Has the maximum possible remainder $x \\bmod a = a - 1$; Has the maximum possible $\\left\\lfloor\\frac{r}{a}\\right\\rfloor$ among numbers less than $r - r\\bmod a$. So there are two candidates for the answer - these are $r$ and $r - r \\bmod a - 1$. The second candidate is suitable only if it is at least $l$. It remains only to compare the values of $f_a$ and select the maximum.",
    "code": "#include <bits/stdc++.h>\n\n//#define int long long\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"no-stack-protector\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native\")\n#pragma GCC optimize(\"fast-math\")\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(143);\n\nconst ll inf = 1e9;\nconst ll M = 1e9;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-4;\n\nvoid solve() {\n    int l, r, x;\n    cin >> l >> r >> x;\n    int ans = r / x + r % x;\n    int m = r / x * x - 1;\n    if(m >= l)ans = max(ans, m / x + m % x);\n    cout << ans;\n}\n\nbool multi = true;\n\nsigned main() {\n    //freopen(\"in.txt\", \"r\", stdin);\n    //freopen(\"in.txt\", \"w\", stdout);\n    int t = 1;\n    if (multi) {\n        cin >> t;\n    }\n    for (; t != 0; --t) {\n        solve();\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1650",
    "index": "C",
    "title": "Weight of the System of Nested Segments",
    "statement": "On the number line there are $m$ points, $i$-th of which has integer coordinate $x_i$ and integer weight $w_i$. The coordinates of all points are different, and the points are numbered from $1$ to $m$.\n\nA sequence of $n$ segments $[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]$ is called system of nested segments if for each pair $i, j$ ($1 \\le i < j \\le n$) the condition $l_i < l_j < r_j < r_i$ is satisfied. In other words, the second segment is strictly inside the first one, the third segment is strictly inside the second one, and so on.\n\nFor a given number $n$, find a system of nested segments such that:\n\n- both ends of each segment are one of $m$ given points;\n- the sum of the weights $2\\cdot n$ of the points used as ends of the segments is \\textbf{minimal}.\n\nFor example, let $m = 8$. The given points are marked in the picture, their weights are marked in red, their coordinates are marked in blue. Make a system of three nested segments:\n\n- weight of the first segment: $1 + 1 = 2$\n- weight of the second segment: $10 + (-1) = 9$\n- weight of the third segment: $3 + (-2) = 1$\n- sum of the weights of all the segments in the system: $2 + 9 + 1 = 12$\n\n\\begin{center}\n{\\small System of three nested segments}\n\\end{center}",
    "tutorial": "We create a structure that stores for each point its coordinate, weight, and index in the input data. Sort the $points$ array by increasing weight. The sum of weights of the first $2 \\cdot n$ points will be minimal, so we use them to construct a system of $n$ nested segments. We save the weights of the first $2 \\cdot n$ points in the variable $sum$ and remove the remaining $m - 2 \\cdot n$ points from the array. Now sort the points in ascending order of coordinates and form a system of nested segments such that the endpoints of $i$th segment are $points[i]$ and $points[2 \\cdot n - i + 1]$ for $(1 \\le i \\le 2 \\cdot n)$. Thus, the endpoints of the first segment are $points[1]$ and $points[2 \\cdot n]$, the endpoints of the $n$th segment are $points[n]$ and $points[n + 1]$. For each test case we first output $sum$, then - $n$ pairs of numbers $i$, $j$ ($1 \\le i, j \\le m$) - the indices under which the endpoints of the current segment were written in the input data.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nstruct point{\n    int weight, position, id;\n};\n\nvoid solve(){\n    int n, m;\n    cin >> n >> m;\n    vector<point>points(m);\n\n    forn(i, m) {\n        cin >>  points[i].position >> points[i].weight;\n        points[i].id = i + 1;\n    }\n\n    sort(points.begin(), points.end(), [] (point a, point b){\n        return a.weight < b.weight;\n    });\n\n    int sum = 0;\n    forn(i, m){\n        if(i < 2 * n) sum += points[i].weight;\n        else points.pop_back();\n    }\n\n    sort(points.begin(), points.end(), [] (point a, point b){\n        return a.position < b.position;\n    });\n\n    cout << sum << endl;\n    forn(i, n){\n        cout << points[i].id << ' ' << points[2 * n - i - 1].id << endl;\n    }\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "hashing",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1650",
    "index": "D",
    "title": "Twist the Permutation",
    "statement": "Petya got an array $a$ of numbers from $1$ to $n$, where $a[i]=i$.\n\nHe performed $n$ operations sequentially. In the end, he received a new state of the $a$ array.\n\nAt the $i$-th operation, Petya chose the first $i$ elements of the array and cyclically shifted them to the right an arbitrary number of times (elements with indexes $i+1$ and more remain in their places). One cyclic shift to the right is such a transformation that the array $a=[a_1, a_2, \\dots, a_n]$ becomes equal to the array $a = [a_i, a_1, a_2, \\dots, a_{i-2}, a_{i-1}, a_{i+1}, a_{i+2}, \\dots, a_n]$.\n\nFor example, if $a = [5,4,2,1,3]$ and $i=3$ (that is, this is the third operation), then as a result of this operation, he could get any of these three arrays:\n\n- $a = [5,4,2,1,3]$ (makes $0$ cyclic shifts, or any number that is divisible by $3$);\n- $a = [2,5,4,1,3]$ (makes $1$ cyclic shift, or any number that has a remainder of $1$ when divided by $3$);\n- $a = [4,2,5,1,3]$ (makes $2$ cyclic shifts, or any number that has a remainder of $2$ when divided by $3$).\n\nLet's look at an example. Let $n=6$, i.e. initially $a=[1,2,3,4,5,6]$. A possible scenario is described below.\n\n- $i=1$: no matter how many cyclic shifts Petya makes, the array $a$ does not change.\n- $i=2$: let's say Petya decided to make a $1$ cyclic shift, then the array will look like $a = [\\textbf{2}, \\textbf{1}, 3, 4, 5, 6]$.\n- $i=3$: let's say Petya decided to make $1$ cyclic shift, then the array will look like $a = [\\textbf{3}, \\textbf{2}, \\textbf{1}, 4, 5, 6]$.\n- $i=4$: let's say Petya decided to make $2$ cyclic shifts, the original array will look like $a = [\\textbf{1}, \\textbf{4}, \\textbf{3}, \\textbf{2}, 5, 6]$.\n- $i=5$: let's say Petya decided to make $0$ cyclic shifts, then the array won't change.\n- $i=6$: let's say Petya decided to make $4$ cyclic shifts, the array will look like $a = [\\textbf{3}, \\textbf{2}, \\textbf{5}, \\textbf{6}, \\textbf{1}, \\textbf{4}]$.\n\nYou are given a final array state $a$ after all $n$ operations. Determine if there is a way to perform the operation that produces this result. In this case, if an answer exists, print the numbers of cyclical shifts that occurred during each of the $n$ operations.",
    "tutorial": "The first thing to notice - the answer always exists. For $n$ numbers $1\\cdot2\\cdot3 \\dots n = n!$ answer choices, as well as $n!$ permutation combinations. It remains only to restore the answer from this permutation. We will restore by performing reverse operations. On the $i$-th ($i = n,~n - 1, ~\\dots, ~2, ~1$) operation will be selectd the first $i$ elements of the array and rotate them $d[i]$ times to the left ( elements with numbers $i+1$ and more remain in their places). Where $d[i]$ is equal to $0$ if $i = 1$, otherwise $d[i] = (index + 1) \\bmod i$, and $index$ - is the index of the number $i$. Thus, for each $i$ from right to left, performing a left cyclic shift operation, we move the number $i$ at index $i$. As a result, we move $O(n)$ numbers $n$ times. The time complexity $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\n\nvoid solve() {\n    int n;\n    cin >> n;\n    int a[n];\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    int ans[n];\n    for (int i = n; i > 0; --i) {\n        int ind = 0;\n        for (int j = 0; j < i; ++j) {\n            ind = a[j] == i ? j : ind;\n        }\n        int b[i];\n        for (int j = 0; j < i; ++j) {\n            b[(i - 1 - ind + j) % i] = a[j];\n        }\n        for (int j = 0; j < i; ++j) {\n            a[j] = b[j];\n        }\n        ans[i - 1] = i != 1 ? (ind + 1) % i : 0;\n    }\n    for (int i = 0; i < n; ++i) {\n        cout << ans[i] << ' ';\n    }\n    cout << '\\n';\n}\nint main() {\n    int tests;\n    cin >> tests;\n    forn(tt, tests) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1650",
    "index": "E",
    "title": "Rescheduling the Exam",
    "statement": "Now Dmitry has a session, and he has to pass $n$ exams. The session starts on day $1$ and lasts $d$ days. The $i$th exam will take place on the day of $a_i$ ($1 \\le a_i \\le d$), all $a_i$ — are different.\n\n\\begin{center}\n{\\small Sample, where $n=3$, $d=12$, $a=[3,5,9]$. Orange — exam days. Before the first exam Dmitry will rest $2$ days, before the second he will rest $1$ day and before the third he will rest $3$ days.}\n\\end{center}\n\nFor the session schedule, Dmitry considers a special value $\\mu$ — the smallest of the rest times before the exam for all exams. For example, for the image above, $\\mu=1$. In other words, for the schedule, he counts exactly $n$ numbers  — how many days he rests between the exam $i-1$ and $i$ (for $i=0$ between the start of the session and the exam $i$). Then it finds $\\mu$ — the minimum among these $n$ numbers.\n\nDmitry believes that he can improve the schedule of the session. He may ask to change the date of one exam (change one arbitrary value of $a_i$). Help him change the date so that all $a_i$ remain different, and the value of $\\mu$ is as large as possible.\n\nFor example, for the schedule above, it is most advantageous for Dmitry to move the second exam to the very end of the session. The new schedule will take the form:\n\n\\begin{center}\n{\\small Now the rest periods before exams are equal to $[2,2,5]$. So, $\\mu=2$.}\n\\end{center}\n\nDmitry can leave the proposed schedule unchanged (if there is no way to move one exam so that it will lead to an improvement in the situation).",
    "tutorial": "To begin with, we will learn how to find the optimal place for the exam that we want to move. Let's imagine that it is not in the schedule, in this case we have two options: Put the exam at the end of the session so that there are $d - a_n - 1$ days before it. Put it in the middle of the largest break between exams ((let its length be $mx$), so that between it and the nearest one there is $\\left\\lfloor \\frac{mx - 1}{2} \\right\\rfloor$, because this is no worse than putting it in any part of any other break. That is, the answer for such an arrangement is - the minimum of the larger of these options and the minimum break, in schedule without the moved exam. Now note that the minimum break in most variants is the same - minimum in the initial schedule. So in order to reduce $\\mu$, you need to move exactly one of the two exams that form it and you need to check which of the two options is better.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(143);\n\nconst ll inf = 1e9;\nconst ll M = 998'244'353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-4;\n\nint n, d;\n\nint cnt(vector<int> &schedule){\n    int mx = 0, mn = inf;\n    for(int i = 1; i < n; ++i){\n        mx = max(mx, schedule[i] - schedule[i - 1] - 1);\n        mn = min(mn, schedule[i] - schedule[i - 1] - 1);\n    }\n    return min(mn, max(d - schedule.back() - 1, (mx - 1) / 2));\n}\n\nvoid solve(int test_case) {\n    cin >> n >> d;\n    vector<int> a(n + 1);\n    int mn = d, min_pos = 0;\n    for(int i = 1; i <= n; ++i){\n        cin >> a[i];\n        if(a[i] - a[i - 1] - 1 < mn){\n            mn = a[i] - a[i - 1] - 1;\n            min_pos = i;\n        }\n    }\n    vector<int> schedule;\n    for(int i = 0; i <= n; ++i){\n        if(i != min_pos){\n            schedule.push_back(a[i]);\n        }\n    }\n    int ans = cnt(schedule);\n    if(min_pos > 1){\n        schedule[min_pos - 1] = a[min_pos];\n    }\n    ans = max(ans, cnt(schedule));\n    cout << ans;\n}\n\nbool multi = true;\n\nsigned main() {\n    //freopen(\"in.txt\", \"r\", stdin);\n    //freopen(\"in.txt\", \"w\", stdout);\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int t = 1;\n    if (multi) {\n        cin >> t;\n    }\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1650",
    "index": "F",
    "title": "Vitaly and Advanced Useless Algorithms",
    "statement": "Vitaly enrolled in the course Advanced Useless Algorithms. The course consists of $n$ tasks. Vitaly calculated that he has $a_i$ hours to do the task $i$ from the day he enrolled in the course. That is, the deadline before the $i$-th task is $a_i$ hours. The array $a$ is sorted in ascending order, in other words, the job numbers correspond to the order in which the assignments are turned in.\n\nVitaly does everything conscientiously, so he wants to complete \\textbf{each} task by $100$ percent, \\textbf{or more}. Initially, his completion rate for each task is $0$ percent.\n\nVitaly has $m$ training options, each option can be used \\textbf{not more than} once. The $i$th option is characterized by three integers: $e_i, t_i$ and $p_i$. If Vitaly uses the $i$th option, then after $t_i$ hours (from the current moment) he will increase the progress of the task $e_i$ by $p_i$ percent.\n\nFor example, let Vitaly have $3$ of tasks to complete. Let the array $a$ have the form: $a = [5, 7, 8]$. Suppose Vitaly has $5$ of options: $[e_1=1, t_1=1, p_1=30]$, $[e_2=2, t_2=3, p_2=50]$, $[e_3=2, t_3=3, p_3=100]$, $[e_4=1, t_4=1, p_4=80]$, $[e_5=3, t_5=3, p_5=100]$.\n\nThen, if Vitaly prepares in the following way, he will be able to complete everything in time:\n\n- Vitaly chooses the $4$-th option. Then in $1$ hour, he will complete the $1$-st task at $80$ percent. He still has $4$ hours left before the deadline for the $1$-st task.\n- Vitaly chooses the $3$-rd option. Then in $3$ hours, he will complete the $2$-nd task in its entirety. He has another $1$ hour left before the deadline for the $1$-st task and $4$ hours left before the deadline for the $3$-rd task.\n- Vitaly chooses the $1$-st option. Then after $1$ hour, he will complete the $1$-st task for $110$ percent, which means that he will complete the $1$-st task just in time for the deadline.\n- Vitaly chooses the $5$-th option. He will complete the $3$-rd task for $2$ hours, and after another $1$ hour, Vitaly will complete the $3$-rd task in its entirety.\n\nThus, Vitaly has managed to complete the course completely and on time, using the $4$ options.\n\nHelp Vitaly — print the options for Vitaly to complete the tasks in the correct order. Please note: each option can be used \\textbf{not more than} once. If there are several possible answers, it is allowed to output any of them.",
    "tutorial": "Note that it is always advantageous for us to complete the task that has an earlier deadline first. Only then will we proceed to the next task. Then we can solve each problem independently for each exam. Then it remains to score $100$ percent on the task on the available options. This is a typical knapsack problem with an answer recovery.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate<class T> bool ckmin(T &a, T b) {return a > b ? a=b, true : false;}\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n\nstruct option {\n    int t, p, id;\n    option(int _t,int _p, int _id) : t(_t), p(_p), id(_id) {\n    }\n};\n\nconst int INF = INT_MAX >> 1;\n\nvector<int> get_ans(vector<option> &v) {\n    int n = sz(v);\n    vector<vector<int>> dp(101, vector<int>(n+1, INF));\n    dp[0][0] = 0;\n    for (int k = 1; k <= n; k++) {\n        auto [t,p,id] = v[k-1];\n        dp[0][k] = 0;\n        for (int i = 100; i > 0; i--) {\n            int prev = max(0,i - p);\n            dp[i][k] = dp[i][k-1];\n            ckmin(dp[i][k], dp[prev][k-1] + t);\n        }\n    }\n    vector<int> ans;\n    int t = dp[100][n];\n\n    if (t == INF) return {-1};\n    for (int i = 100, k = n; k >= 1; k--) {\n        if (dp[i][k] == dp[i][k-1]) {\n            continue;\n        }\n        ans.emplace_back(v[k-1].id);\n        i = max(0, i - v[k-1].p);\n    }\n\n    reverse(all(ans));\n    ans.emplace_back(t);\n    return ans;\n}\n\nvoid solve(bool flag=true) {\n\n\n    int n,m; cin >> n >> m;\n    vector<int> a(n);\n    forn(i, n) {\n        cin >> a[i];\n    }\n    for (int i = n-1; i > 0; i--) {\n        a[i] -= a[i-1];\n    }\n\n    vector<vector<option>> v(n);\n    forn(j, m) {\n        int e,t,p; cin >> e >> t >> p, e--;\n        v[e].emplace_back(t, p, j+1);\n    }\n    vector<int> ans;\n    forn(i, n) {\n        vector<int> cur = get_ans(v[i]);\n        if (sz(cur) == 1 && cur[0] == -1) {\n            cout << \"-1\\n\";\n            return;\n        }\n        int t = cur.back();\n        if (t > a[i]) {\n            cout << \"-1\\n\";\n            return;\n        }\n        cur.pop_back();\n        if (i+1 < n) a[i+1] += a[i] - t;\n\n        ans.insert(ans.end(), all(cur));\n    }\n\n\n    cout << sz(ans) << '\\n';\n    for (auto e:ans) cout << e << ' ';\n    cout << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1650",
    "index": "G",
    "title": "Counting Shortcuts",
    "statement": "Given an undirected connected graph with $n$ vertices and $m$ edges. The graph contains no loops (edges from a vertex to itself) and multiple edges (i.e. no more than one edge between each pair of vertices). The vertices of the graph are numbered from $1$ to $n$.\n\nFind the number of paths from a vertex $s$ to $t$ whose length differs from the shortest path from $s$ to $t$ by no more than $1$. It is necessary to consider all suitable paths, even if they pass through the same vertex or edge more than once (i.e. they are not simple).\n\n\\begin{center}\n{\\small Graph consisting of $6$ of vertices and $8$ of edges}\n\\end{center}\n\nFor example, let $n = 6$, $m = 8$, $s = 6$ and $t = 1$, and let the graph look like the figure above. Then the length of the shortest path from $s$ to $t$ is $1$. Consider all paths whose length is at most $1 + 1 = 2$.\n\n- $6 \\rightarrow 1$. The length of the path is $1$.\n- $6 \\rightarrow 4 \\rightarrow 1$. Path length is $2$.\n- $6 \\rightarrow 2 \\rightarrow 1$. Path length is $2$.\n- $6 \\rightarrow 5 \\rightarrow 1$. Path length is $2$.\n\nThere is a total of $4$ of matching paths.",
    "tutorial": "Note that in any shortest path, we cannot return to the previous vertex. Since if the current vertex $v$, the previous $u$. The current distance $d_v = d_u + 1$ (the shortest distance to vertex $v$), the shortest distance to vertex $t$ - $d_t$. Then, if we return to the vertex $u$, the shortest distance from it to $t$ is $d_t - d_u = d_t - d_v + 1$. If we add to the current distance, we get: $(d_v + 1) + (d_t - d_v + 1) = d_t + 2$. Thus, we get a path at least $2$ longer than the shortest one. Thus, our answer consists of only simple paths. If the answer consists only of simple paths, then we will simply add vertices to the queue when traversing bfs twice (on the first visit, and on the next visit, when the distance to the vertex is equal to the shortest $+1$). And we will also count the number of ways to get to that vertex. Then we can output the answer as soon as we get to the vertex $t$ the second time for processing. After that we can terminate the loop. The asymptotic will be $O(n + m)$ since we only need bfs.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define eb emplace_back\n#define mt make_tuple\n\nconst int INF = INT_MAX >> 1;\nconst int mod = 1e9 + 7;\n\nvoid csum(int &a,int b) {\n    a = (a + b) % mod;\n}\n\nint s, t;\nvector<int> us;\nvector<int> dist;\nvector<int> dp[2];\nint bfs(vector<vector<int>> &g) {\n    queue<tuple<int,int,int>> q;\n    q.push(mt(s, 0, 0)); //[v, dist, count]\n\n    int ans = 0, mnd = INF;\n    us[s] = 1;\n    dp[0][s] = 1;\n    dist[s] = 0;\n    while(!q.empty()) {\n        auto [v,d, x] = q.front(); q.pop();\n        // cerr << v << ' ' << d << ' ' << dp[x][v] << endl;\n        if (v == t) {\n            if (mnd == INF) {\n                mnd = d;\n            }\n            csum(ans, dp[x][v]);\n        }\n        if (d == mnd + 1) continue;\n        for (int to : g[v]) if(d <= dist[to]) {\n            dist[to] = min(dist[to], d+1);\n            csum(dp[d - dist[to] + 1][to], dp[x][v]);\n            // cerr << \"TO: \" <<  to << ' ' << dist[to] << ' ' << d << endl;\n            if(us[to] == 0 || (us[to] == 1 && dist[to] == d)) q.push(mt(to, d+1, us[to]++));\n        }\n    }\n    return ans;\n}\n\n\nvoid solve() {\n    int n,m; cin >> n >> m;\n    cin >> s >> t;\n    us.resize(n+1);\n    dp[0].resize(n+1);\n    dp[1].resize(n+1);\n    dist.resize(n+1);\n    forn(i, n+1) {\n        us[i] = dp[0][i] = dp[1][i] = 0;\n        dist[i] = INF;\n    }\n\n    vector<vector<int>> g(n+1);\n    forn(i, m) {\n        int a,b; cin >> a >> b;\n        g[a].eb(b);\n        g[b].eb(a);\n    }\n\n    cout << bfs(g) << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1651",
    "index": "A",
    "title": "Playoff",
    "statement": "Consider a playoff tournament where $2^n$ athletes compete. The athletes are numbered from $1$ to $2^n$.\n\nThe tournament is held in $n$ stages. In each stage, the athletes are split into pairs in such a way that each athlete belongs exactly to one pair. In each pair, the athletes compete against each other, and exactly one of them wins. The winner of each pair advances to the next stage, the athlete who was defeated gets eliminated from the tournament.\n\nThe pairs are formed as follows:\n\n- in the first stage, athlete $1$ competes against athlete $2$; $3$ competes against $4$; $5$ competes against $6$, and so on;\n- in the second stage, the winner of the match \"$1$–$2$\" competes against the winner of the match \"$3$–$4$\"; the winner of the match \"$5$–$6$\" competes against the winner of the match \"$7$–$8$\", and so on;\n- the next stages are held according to the same rules.\n\nWhen athletes $x$ and $y$ compete, the winner is decided as follows:\n\n- if $x+y$ is odd, the athlete with the lower index wins (i. e. if $x < y$, then $x$ wins, otherwise $y$ wins);\n- if $x+y$ is even, the athlete with the higher index wins.\n\nThe following picture describes the way the tournament with $n = 3$ goes.\n\nYour task is the following one: given the integer $n$, determine the index of the athlete who wins the tournament.",
    "tutorial": "During the first stage, every player with an even index competes against a player with an odd index, so in each match during the first stage, the player whose index is smaller wins. The pairs are formed in such a way that, in each pair, the player with an odd index has smaller index, so all players with even indices get eliminated, and all players with odd indices advance to the next stage. All of the remaining matches are between players with odd indices, so the winner of each match is the player with the larger index. So, the overall winner of the tournament is the player with the greatest odd index, which is $2^n-1$. Note: in some languages (for example, C++), standard power functions work with floating-point numbers instead of integers, so they will produce the answer as a floating-point number (which may lead to wrong formatting of the output and/or calculation errors). You might have to implement your own power function that works with integers, or compute $2^n$ using a loop.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    print(2 ** n - 1)",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1651",
    "index": "B",
    "title": "Prove Him Wrong",
    "statement": "Recently, your friend discovered one special operation on an integer array $a$:\n\n- Choose two indices $i$ and $j$ ($i \\neq j$);\n- Set $a_i = a_j = |a_i - a_j|$.\n\nAfter playing with this operation for a while, he came to the next conclusion:\n\n- For every array $a$ of $n$ integers, where $1 \\le a_i \\le 10^9$, you can find a pair of indices $(i, j)$ such that the total sum of $a$ will \\textbf{decrease} after performing the operation.\n\nThis statement sounds fishy to you, so you want to find a counterexample for a given integer $n$. Can you find such counterexample and prove him wrong?\n\nIn other words, find an array $a$ consisting of $n$ integers $a_1, a_2, \\dots, a_n$ ($1 \\le a_i \\le 10^9$) such that for all pairs of indices $(i, j)$ performing the operation won't decrease the total sum (it will increase or not change the sum).",
    "tutorial": "Suppose the initial sum of $a$ is equal to $S$. If we perform the operation, the new sum will be equal to $S' = S - (a_i + a_j) + 2 |a_i - a_j|$. We want the sum not to decrease, or $S' \\ge S$. If $a_i \\ge a_j$, we will get: $S' \\ge S,$ $S - (a_i + a_j) + 2 (a_i - a_j) \\ge S,$ $a_i - 3 a_j \\ge 0,$ $a_i \\ge 3 a_j.$ In other words, array $a$ you need (if sorted) will have $a_2 \\ge 3 a_1$, $a_3 \\ge 3 a_2$ and so on. And one of the variants (and, obviously, an optimal one) is just $[1, 3, 9, 27, \\dots, 3^{n - 1}]$. As a result, since $a_i \\le 10^9$, we just need to check: if $3^{n - 1} \\le 10^9$ then we found an answer, otherwise there is no counterexample.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\tif 3**(n-1) > 10**9:\n\t\tprint(\"NO\")\n\telse:\n\t\tprint(\"YES\")\n\t\tprint(*[3**x for x in range(n)])",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1651",
    "index": "C",
    "title": "Fault-tolerant Network",
    "statement": "There is a classroom with two rows of computers. There are $n$ computers in each row and each computer has its own grade. Computers in the first row have grades $a_1, a_2, \\dots, a_n$ and in the second row — $b_1, b_2, \\dots, b_n$.\n\nInitially, all pairs of \\textbf{neighboring} computers in each row are connected by wire (pairs $(i, i + 1)$ for all $1 \\le i < n$), so two rows form two independent computer networks.\n\nYour task is to combine them into one common network by connecting one or more pairs of computers from \\textbf{different} rows. Connecting the $i$-th computer from the first row and the $j$-th computer from the second row costs $|a_i - b_j|$.\n\nYou can connect one computer to several other computers, but you need to provide at least a basic fault tolerance: you need to connect computers in such a way that the network stays connected, despite one of its computers failing. In other words, if one computer is broken (no matter which one), the network won't split into two or more parts.\n\nWhat is the minimum total cost to make a fault-tolerant network?",
    "tutorial": "There is a criterion when the given network becomes fault-tolerant: the network becomes fault-tolerant if and only if each of the corner computers (let's name them $A_1$, $A_n$, $B_1$, and $B_n$) is connected to the other row. From one side: if, WLOG, $A_1$ is not connected to the other row then if $A_2$ is broken - $A_1$ loses connection to the other network (since $A_1$ is connected only with $A_2$). From the other side: suppose, WLOG, $A_i$ is broken, then the row $A$ is falling into at most two parts: $A_1 - \\dots - A_{i - 1}$ and $A_{i + 1} - \\dots - A_n$. But since both $A_1$ and $A_n$ are connected to row $B$ and $B$ is still connected, then the resulting network is still connected. Now the question is: how to connect all corner computers? Because sometimes it's optimal not to connect corners directly. One of the approaches is described below. Let's look at $A_1$. Essentially, there are three ways to connect it to row $B$: to $B_1$, $B_n$, or $\\mathrm{best}_B(A_1)$ (where $\\mathrm{best}_B(A_1)$ is $B_j$ with minimum possible $|a_i - b_j|$). The same applies to $A_n$. So, let's just iterate over all these $3 \\times 3$ variants. For each of these variants, if we didn't cover $B_1$ then we should also add one more connection between $B_1$ and $\\mathrm{best}_A(B_1)$; if we didn't cover $B_n$ then we should also add one more connection between $B_n$ and $\\mathrm{best}_A(B_n)$; As a result, we choose the best variant.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n\ntypedef long long li;\n\nconst int INF = int(1e9);\n\nint n;\nvector<int> a, b;\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> a[i];\n\tb.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> b[i];\n\treturn true;\n}\n\nint bestCandidate(const vector<int> &vals, int cur) {\n\tint bst = INF + 10, pos = -1;\n\tfore (i, 0, n) {\n\t\tif (bst > abs(cur - vals[i])) {\n\t\t\tbst = abs(cur - vals[i]);\n\t\t\tpos = i;\n\t\t}\n\t}\n\treturn pos;\n}\n\ninline void solve() {\n\tli bst = 10ll * INF;\n\t\n\tvector<int> cds1 = {0, bestCandidate(b, a[0]), n - 1};\n\tvector<int> cds2 = {0, bestCandidate(b, a[n - 1]), n - 1};\n\t\n\tfor (int var1 : cds1) {\n\t\tfor (int var2 : cds2) {\n\t\t\tli ans = (li)abs(a[0] - b[var1]) + abs(a[n - 1] - b[var2]);\n\t\t\t\n\t\t\tif (var1 > 0 && var2 > 0)\n\t\t\t\tans += abs(b[0] - a[bestCandidate(a, b[0])]);\n\t\t\tif (var1 < n - 1 && var2 < n - 1)\n\t\t\t\tans += abs(b[n - 1] - a[bestCandidate(a, b[n - 1])]);\n\t\t\t\n\t\t\tbst = min(bst, ans);\n\t\t}\n\t}\n\tcout << bst << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\t\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tread();\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1651",
    "index": "D",
    "title": "Nearest Excluded Points",
    "statement": "You are given $n$ distinct points on a plane. The coordinates of the $i$-th point are $(x_i, y_i)$.\n\nFor each point $i$, find the nearest (in terms of Manhattan distance) point with \\textbf{integer coordinates} that is not among the given $n$ points. If there are multiple such points — you can choose any of them.\n\nThe Manhattan distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$.",
    "tutorial": "Firstly, we can find answers for all points that are adjacent to at least one point not from the set. The distance for such points is obviously $1$ (and this is the smallest possible answer we can get). On the next iteration, we can set answers for all points that are adjacent to points with found answers (because they don't have neighbors not from the set, the distance for them is at least $2$). It doesn't matter which point we will take, so if the point $i$ is adjacent to some point $j$ that have the answer $1$, we can set the answer for the point $i$ as the answer for the point $j$. We can repeat this process until we find answers for all points. In terms of the code, this can be done by breadth first search (BFS). In other words, we set answers for the points that have the distance $1$ and then push these answers to all adjacent points from the set in order of the increasing distance until we find all the answers. Time complexity: $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint dx[] = {0, 0, -1, 1};\nint dy[] = {-1, 1, 0, 0};\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int n;\n    scanf(\"%d\", &n);\n    vector<pair<int, int>> a(n);\n    for (auto &[x, y] : a) scanf(\"%d %d\", &x, &y);\n    \n    set<pair<int, int>> st(a.begin(), a.end());\n    map<pair<int, int>, pair<int, int>> ans;\n    queue<pair<int, int>> q;\n    for (auto [x, y] : a) {\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + dx[i], ny = y + dy[i];\n            if (st.count({nx, ny})) {\n                continue;\n            }\n            ans[{x, y}] = {nx, ny};\n            q.push({x, y});\n            break;\n        }\n    }\n    \n    while (!q.empty()) {\n        int x = q.front().first, y = q.front().second;\n        q.pop();\n        for (int i = 0; i < 4; ++i) {\n            int nx = x + dx[i], ny = y + dy[i];\n            if (!st.count({nx, ny}) || ans.count({nx, ny})) {\n                continue;\n            }\n            ans[{nx, ny}] = ans[{x, y}];\n            q.push({nx, ny});\n        }\n    }\n    \n    for (auto [x, y] : a) {\n        auto it = ans[{x, y}];\n        printf(\"%d %d\\n\", it.first, it.second);\n    }\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1651",
    "index": "E",
    "title": "Sum of Matchings",
    "statement": "Let's denote the size of the maximum matching in a graph $G$ as $\\mathit{MM}(G)$.\n\nYou are given a bipartite graph. The vertices of the first part are numbered from $1$ to $n$, the vertices of the second part are numbered from $n+1$ to $2n$. \\textbf{Each vertex's degree is $2$}.\n\nFor a tuple of four integers $(l, r, L, R)$, where $1 \\le l \\le r \\le n$ and $n+1 \\le L \\le R \\le 2n$, let's define $G'(l, r, L, R)$ as the graph which consists of all vertices of the given graph that are included in the segment $[l, r]$ or in the segment $[L, R]$, and all edges of the given graph such that each of their endpoints belongs to one of these segments. In other words, to obtain $G'(l, r, L, R)$ from the original graph, you have to remove all vertices $i$ such that $i \\notin [l, r]$ and $i \\notin [L, R]$, and all edges incident to these vertices.\n\nCalculate the sum of $\\mathit{MM}(G(l, r, L, R))$ over all tuples of integers $(l, r, L, R)$ having $1 \\le l \\le r \\le n$ and $n+1 \\le L \\le R \\le 2n$.",
    "tutorial": "Instead of counting the edges belonging to the maximum matching, it is easier to count the vertices. So, we will calculate the total number of vertices saturated by the maximum matching over all possible tuples $(l, r, L, R)$, and then divide the answer by $2$. Furthermore, it's easier to calculate the number of unsaturated vertices than the number of saturated vertices, so we can subtract it from the total number of vertices in all graphs we consider and obtain the answer. Let's analyze how to calculate the total number of unsaturated vertices. Each graph $G'(l, r, L, R)$ is a subgraph of the given graph, so it is still bipartite, and the degree of each vertex is still not greater than $2$. A bipartite graph where the degree of each vertex is at most $2$ can be represented as a set of cycles and paths, and the maximum matching over each of these cycles/paths can be considered independently. Each cycle has an even number of vertices (since otherwise the graph would not be bipartite), so we can saturate all vertices on a cycle with the matching. For a path, the number of unsaturated vertices depends on its length: if the number of vertices in a path is even, we can match all vertices on it; otherwise, one vertex will be unsaturated. So the problem reduces to counting paths with odd number of vertices in all possible graphs $G'(l, r, L, R)$. Every path with an odd number of vertices has a center (the vertex which is exactly in the middle of the path). Let's iterate on the center of the path and its length, and calculate the number of times this path occurs in all graphs we consider. Suppose the center of the path is the vertex $x$, and the number of vertices in it is $2k+1$. Then, for this path to exist, two conditions must hold: every vertex $y$ such that the distance from $x$ to $y$ is not greater than $k$ should be present in the graph; every vertex $z$ such that the distance from $x$ to $z$ is exactly $k+1$ should be excluded from the graph. It means that, for each of the two parts of the graph, there are several vertices that should be present in the graph, and zero or two vertices that should be excluded from the graph. It's easy to see that among the vertices we have to include, we are only interested in the minimum one and the maximum one (all vertices between them will be included as well if these two are included). So, we need to implement some kind of function that allows us to calculate the number of segments that cover the minimum and the maximum vertex we need, and don't cover any of the vertices that we have to exclude - this can be easily done in $O(1)$. Note that the segments should be considered independently for both parts of the graph. Overall, for each vertex we have to consider at most $O(n)$ different lengths of odd paths with the center in this vertex. The minimum/maximum indices of vertices in both parts we have to include in the graph can be maintained while we increase the length of the path, so the whole solution works in $O(n^2)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 3043;\n\nvector<int> g[2 * N];\nint n;\nint used[2 * N];\n\nint choose2(int n)\n{\n    return n * (n + 1) / 2;\n}\n\nint count_ways(int L, int R, const vector<int>& forbidden)\n{\n    if(L > R)\n    {\n        int ml = *min_element(forbidden.begin(), forbidden.end());\n        int mr = *max_element(forbidden.begin(), forbidden.end());\n        return choose2(ml) + choose2(mr - ml - 1) + choose2(n - 1 - mr);\n    }\n    int minl = 0;\n    int maxl = L;\n    int minr = R;\n    int maxr = n - 1;\n    for(auto x : forbidden)\n    {\n        if(L <= x && x <= R)\n            return 0;\n        else if(x < L) minl = max(minl, x + 1);\n        else maxr = min(maxr, x - 1);\n    }                            \n    return (maxl - minl + 1) * (maxr - minr + 1);\n}\n\nvector<int> cur;\n\nvoid dfs(int x)\n{\n    if(used[x] == 1) return;\n    used[x] = 1;\n    cur.push_back(x);\n    for(auto y : g[x]) dfs(y);\n}\n\nlong long calc(const vector<int>& cycle)\n{\n    int m = cycle.size();\n    int k = m / 2;\n    long long ans = 0;\n    for(int i = 0; i < m; i++)\n    {\n        int z = cycle[i];\n        if(z >= n) z -= n;\n        ans += choose2(n) * 1ll * (choose2(z) + 0ll + choose2(n - z - 1));\n        int l = n - 1, r = 0, L = n - 1, R = 0;\n        int pl = i, pr = i;\n        for(int j = 0; j < k; j++)\n        {\n            for(auto x : vector<int>({cycle[pl], cycle[pr]}))\n            {\n                if(x < n)\n                {\n                    l = min(l, x);\n                    r = max(r, x);\n                }\n                else\n                {\n                    L = min(L, x - n);\n                    R = max(R, x - n);\n                }\n            }\n            vector<int> f, F;\n            pl--;\n            if(pl < 0) pl += m;\n            pr++;\n            if(pr >= m) pr -= m;\n            for(auto x : vector<int>({cycle[pl], cycle[pr]}))\n            {                     \n                if(x < n) f.push_back(x);\n                else F.push_back(x - n);\n            }\n            long long add = count_ways(l, r, f) * 1ll * count_ways(L, R, F);\n            ans += add;\n        }\n    }\n    return ans;       \n}\n\nint main()\n{\n    cin >> n;\n    for(int i = 0; i < 2 * n; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n        --x;\n        --y;\n        g[x].push_back(y);\n        g[y].push_back(x);\n    }\n    long long ans = n * 1ll * choose2(n) * 1ll * choose2(n) * 2ll;\n    for(int i = 0; i < n; i++)\n    {\n        if(used[i]) continue;\n        dfs(i);\n        vector<int> cycle = cur;\n        ans -= calc(cycle);\n        cur = vector<int>();\n    }\n    cout << ans / 2 << endl;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "dfs and similar",
      "graph matchings",
      "greedy",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1651",
    "index": "F",
    "title": "Tower Defense",
    "statement": "Monocarp is playing a tower defense game. A level in the game can be represented as an OX axis, where each lattice point from $1$ to $n$ contains a tower in it.\n\nThe tower in the $i$-th point has $c_i$ mana capacity and $r_i$ mana regeneration rate. In the beginning, before the $0$-th second, each tower has full mana. If, at the end of some second, the $i$-th tower has $x$ mana, then it becomes $\\mathit{min}(x + r_i, c_i)$ mana for the next second.\n\nThere are $q$ monsters spawning on a level. The $j$-th monster spawns at point $1$ at the beginning of $t_j$-th second, and it has $h_j$ health. Every monster is moving $1$ point per second in the direction of increasing coordinate.\n\nWhen a monster passes the tower, the tower deals $\\mathit{min}(H, M)$ damage to it, where $H$ is the current health of the monster and $M$ is the current mana amount of the tower. This amount gets subtracted from both monster's health and tower's mana.\n\nUnfortunately, sometimes some monsters can pass all $n$ towers and remain alive. Monocarp wants to know what will be the total health of the monsters after they pass all towers.",
    "tutorial": "Let's start thinking about the problem from the easy cases. How to solve the problem fast if all towers have full mana? We can store prefix sums of their capacities and find the first tower that doesn't get drained completely with a binary search. Let's try the opposite. How to solve the problem fast if all towers were drained completely in the previous second? It's the same but the prefix sums are calculated over regeneration rates. What if all towers were drained at the same second, earlier than the previous second, and no tower is fully restored yet? It's also the same but the regeneration rates are multiplied by the time passed since the drain. What if we drop the condition about the towers not being fully restored? How would a data structure that can answer prefix sum queries work? It should store the total mana capacity of all towers that are full. Then mana regeneration rates for all towers that aren't. If these are kept separately, then it's easy to obtain the prefix sum by providing the time passed. This will be total capacity plus total regeneration rate, multiplied by the time passed. How to determine if the tower is fully restored since the drain or not? That's easy. For each tower, we can calculate the number of seconds it takes it to get restored from zero. That is $\\lceil \\frac{c}{r} \\rceil$. Thus, all towers that have this value smaller than the time passed won't get restored. All the rest will. Unfortunately, in the actual problem, not all towers were last drained at the same time. However, it's possible to reduce the problem to that. Store the segments of towers that were drained at same time. There are also towers that weren't drained completely, but they can be stored as segments of length $1$ too. When a monster comes, it drains some prefix of the towers completely and possibly one more tower partially. In terms of segments, it removes some prefix of the them and possibly cuts one. Then it creates a segment that covers the prefix and possibly a segment of length $1$ (with a partially drained tower). So each monster creates $O(1)$ segments and removes no more segments than were created. Thus, if we were to process each creation and removal in some $O(T)$, then the complexity will be $O(qT)$. All towers on each segment have the same time passed since the drain. We want to query the sum on the entire segment. If it is greater than the remaining health of the monster, we want to find the largest prefix of this segment that has a smaller or equal sum than the monster health. Given time passed, let's learn to query the range sum. If we knew the queries beforehand, it would be easy. Initialize a segment tree as if all towers are completely restored. Then make events of two kinds: a tower with restore time $\\lceil \\frac{c}{r} \\rceil$ and a query with time $t$. Sort them in the decreasing order and start processing one by one. When a tower event happens, update a single position in the segment tree from capacity to regeneration rate. When a query event happens, find the sum. Since the queries are not known beforehand, make that segment tree persistent and ask specific versions of it. If a segment of towers was last drained at time $t_{\\mathit{lst}}$, and the query is at time $t$, then you should query the segment tree in version $t - t_{\\mathit{lst}}$. Obviously, you can store not all versions but only ones that have some tower change. Moreover, it's more convenient to make one version responsible for one tower update. Then you can lower_bound the array of sorted $\\lceil \\frac{c}{r} \\rceil$ to find the version you want to ask at. To determine the largest prefix of this segment that has a smaller or equal sum than the monster health, you can either binary search for $O(\\log^2 n)$ or traverse the segment tree for $O(\\log n)$. The time limit might be a little tight for the first approach, but it can still pass. Overall complexity: $O((n + q) \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct node{\n\tnode *l, *r;\n\tlong long sumc, sumr;\n\tnode() : l(NULL), r(NULL), sumc(0), sumr(0) {}\n\tnode(node* l, node* r, long long sumc, long long sumr) : l(l), r(r), sumc(sumc), sumr(sumr) {}\n};\n\nnode* build(int l, int r, vector<int> &c){\n\tif (l == r - 1)\n\t\treturn new node(NULL, NULL, c[l], 0);\n\tint m = (l + r) / 2;\n\tnode* nw = new node();\n\tnw->l = build(l, m, c);\n\tnw->r = build(m, r, c);\n\tnw->sumc = nw->l->sumc + nw->r->sumc;\n\treturn nw;\n}\n\nnode* upd(node* v, int l, int r, int pos, int val){\n\tif (l == r - 1)\n\t\treturn new node(NULL, NULL, 0, val);\n\tint m = (l + r) / 2;\n\tnode* nw = new node(v->l, v->r, 0, 0);\n\tif (pos < m)\n\t\tnw->l = upd(v->l, l, m, pos, val);\n\telse\n\t\tnw->r = upd(v->r, m, r, pos, val);\n\tnw->sumc = nw->l->sumc + nw->r->sumc;\n\tnw->sumr = nw->l->sumr + nw->r->sumr;\n\treturn nw;\n}\n\nlong long getsum(node *v, int mult){\n\treturn v->sumc + v->sumr * mult;\n}\n\nint trav(node *v, int l, int r, int L, int R, long long &lft, int mult){\n\tif (L >= R){\n\t\treturn 0;\n\t}\n\tif (l == L && r == R && lft - getsum(v, mult) >= 0){\n\t\tlft -= getsum(v, mult);\n\t\treturn r - l;\n\t}\n\tif (l == r - 1){\n\t\treturn 0;\n\t}\n\tint m = (l + r) / 2;\n\tint cnt = trav(v->l, l, m, L, min(m, R), lft, mult);\n\tif (cnt == max(0, min(m, R) - L))\n\t\tcnt += trav(v->r, m, r, max(m, L), R, lft, mult);\n\treturn cnt;\n}\n\nstruct seg{\n\tint l, r, lst, cur;\n};\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> c(n), r(n);\n\tforn(i, n) scanf(\"%d%d\", &c[i], &r[i]);\n\t\n\tvector<int> ord(n);\n\tiota(ord.begin(), ord.end(), 0);\n\tsort(ord.begin(), ord.end(), [&](int x, int y){\n\t\treturn c[x] / r[x] > c[y] / r[y];\n\t});\n\tvector<int> vals;\n\tfor (int i : ord) vals.push_back(c[i] / r[i]);\n\t\n\tvector<node*> root(1, build(0, n, c));\n\tfor (int i : ord)\n\t\troot.push_back(upd(root.back(), 0, n, i, r[i]));\n\t\n\tvector<seg> st;\n\tfor (int i = n - 1; i >= 0; --i)\n\t\tst.push_back({i, i + 1, 0, c[i]});\n\t\n\tlong long ans = 0;\n\tint q;\n\tscanf(\"%d\", &q);\n\tforn(_, q){\n\t\tint t;\n\t\tlong long h;\n\t\tscanf(\"%d%lld\", &t, &h);\n\t\twhile (!st.empty()){\n\t\t\tauto it = st.back();\n\t\t\tst.pop_back();\n\t\t\tif (it.r - it.l == 1){\n\t\t\t\tit.cur = min((long long)c[it.l], it.cur + (t - it.lst) * 1ll * r[it.l]);\n\t\t\t\tif (it.cur <= h){\n\t\t\t\t\th -= it.cur;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tst.push_back({it.l, it.r, t, int(it.cur - h)});\n\t\t\t\t\th = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tint mx = vals.rend() - lower_bound(vals.rbegin(), vals.rend(), t - it.lst);\n\t\t\t\tint res = it.l + trav(root[mx], 0, n, it.l, it.r, h, t - it.lst);\n\t\t\t\tassert(res <= it.r);\n\t\t\t\tif (res != it.r){\n\t\t\t\t\tif (it.r - res > 1)\n\t\t\t\t\t\tst.push_back({res + 1, it.r, it.lst, 0});\n\t\t\t\t\tint nw = min((long long)c[res], r[res] * 1ll * (t - it.lst));\n\t\t\t\t\tassert(nw - h > 0);\n\t\t\t\t\tst.push_back({res, res + 1, t, int(nw - h)});\n\t\t\t\t\th = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (h == 0){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (st.empty()){\n\t\t\tst.push_back({0, n, t, 0});\n\t\t}\n\t\telse if (st.back().l != 0){\n\t\t\tst.push_back({0, st.back().l, t, 0});\n\t\t}\n\t\tans += h;\n\t}\n\t\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1654",
    "index": "A",
    "title": "Maximum Cake Tastiness",
    "statement": "There are $n$ pieces of cake on a line. The $i$-th piece of cake has weight $a_i$ ($1 \\leq i \\leq n$).\n\nThe tastiness of the cake is the maximum total weight of two adjacent pieces of cake (i. e., $\\max(a_1+a_2,\\, a_2+a_3,\\, \\ldots,\\, a_{n-1} + a_{n})$).\n\nYou want to maximize the tastiness of the cake. You are allowed to do the following operation at most once (doing more operations would ruin the cake):\n\n- Choose a contiguous subsegment $a[l, r]$ of pieces of cake ($1 \\leq l \\leq r \\leq n$), and reverse it.\n\nThe subsegment $a[l, r]$ of the array $a$ is the sequence $a_l, a_{l+1}, \\dots, a_r$.\n\nIf you reverse it, the array will become $a_1, a_2, \\dots, a_{l-2}, a_{l-1}, \\underline{a_r}, \\underline{a_{r-1}}, \\underline{\\dots}, \\underline{a_{l+1}}, \\underline{a_l}, a_{r+1}, a_{r+2}, \\dots, a_{n-1}, a_n$.\n\nFor example, if the weights are initially $[5, 2, 1, 4, 7, 3]$, you can reverse the subsegment $a[2, 5]$, getting $[5, \\underline{7}, \\underline{4}, \\underline{1}, \\underline{2}, 3]$. The tastiness of the cake is now $5 + 7 = 12$ (while before the operation the tastiness was $4+7=11$).\n\nFind the maximum tastiness of the cake after doing the operation at most once.",
    "tutorial": "Suppose you want to choose pieces of cake $i$, $j$. Can you make them adjacent in $1$ move? The answer is the sum of the $2$ maximum weights. You can always pick the $2$ maximum weights: if they are $a_i$ and $a_j$ ($i < j$), you can flip the subsegment $[i, j-1]$ to make them adjacent. The result can't be larger, because the sum of the weights of any $2$ pieces of cake is never greater than the sum of the $2$ maximum weights. Iterating over all pairs of pieces of cake is enough to get AC, but you can solve the problem in $O(n \\log n)$ by sorting the weights and printing the sum of the last $2$ values, or even in $O(n)$ if you calculate the maximum and the second maximum in linear time. Complexity: $O(t \\cdot n^2)$, $O(t \\cdot n \\log n)$ or $O(t \\cdot n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    int t; cin >> t;\n    while (t--) {\n \n        int n; cin >> n;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++)\n            cin >> a[i];\n \n        int ans = 0;\n        for (int i = 0; i < n; i++)\n            for (int j = i+1; j < n; j++)\n                ans = max(ans, a[i]+a[j]);\n \n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1654",
    "index": "B",
    "title": "Prefix Removals",
    "statement": "You are given a string $s$ consisting of lowercase letters of the English alphabet. You must perform the following algorithm on $s$:\n\n- Let $x$ be the length of the longest prefix of $s$ which occurs somewhere else in $s$ as a contiguous substring (the other occurrence may also intersect the prefix). If $x = 0$, break. Otherwise, remove the first $x$ characters of $s$, and repeat.\n\nA prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".\n\nFor instance, if we perform the algorithm on $s =$ \"abcabdc\",\n\n- Initially, \"ab\" is the longest prefix that also appears somewhere else as a substring in $s$, so $s =$ \"cabdc\" after $1$ operation.\n- Then, \"c\" is the longest prefix that also appears somewhere else as a substring in $s$, so $s =$ \"abdc\" after $2$ operations.\n- Now $x=0$ (because there are no non-empty prefixes of \"abdc\" that also appear somewhere else as a substring in $s$), so the algorithm terminates.\n\nFind the final state of the string after performing the algorithm.",
    "tutorial": "Are there any characters that you can never remove? You can't remove the rightmost occurrence of each letter. Can you remove the other characters? If you can remove $s_1, s_2, \\dots, s_{i-1}$ and $s_i$ is not the rightmost occurrence of a letter, you can also remove $s_i$. Let $a$ be the initial string. For a string $z$, let's define $z(l, r) = z_lz_{l+1} \\dots z_r$, i.e., the substring of $z$ from $l$ to $r$. The final string is $a(k, n)$ for some $k$. In the final string, $x = 0$, so the first character doesn't appear anywhere else in $s$. This means that $a_k\\not=a_{k+1}, a_{k+2}, \\dots, a_n$. In other words, $a_k$ is the rightmost occurrence of a letter in $s$. Can you ever remove $a_i$, if $a_i\\not=a_{i+1}, a_{i+2}, \\dots, a_n$? Notice that you would need to remove $a(l, r)$ ($l \\leq i \\leq r$): this means that there must exist $a(l', r') = a(l, r)$ for some $l' > l$. So, $a_{i+l'-l} = a_i$, and this is a contradiction. Therefore, $k$ is the smallest index such that $a_k\\not=a_{k+1}, a_{k+2}, \\dots, a_n$. You can find $k$ by iterating over the string from right to left and updating the frequency of each letter. Indeed $a_i\\not=a_{i+1}, a_{i+2}, \\dots, a_n$ if and only if the frequency of the letter $a_i$ is $0$ up to now (in the iteration from right to left we are performing). The value of $k$ is the minimum such index $i$. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    int t; cin >> t;\n    while (t--) {\n \n        string s; cin >> s;\n        map<char, int> frequency;\n        for (char c : s)\n            frequency[c]++;\n \n        for (int i = 0; i < s.size(); i++)\n            if (--frequency[s[i]] == 0) {\n                cout << s.substr(i) << \"\\n\";\n                break;\n            }\n    }\n}",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1654",
    "index": "C",
    "title": "Alice and the Cake",
    "statement": "Alice has a cake, and she is going to cut it. She will perform the following operation $n-1$ times: choose a piece of the cake (initially, the cake is all one piece) with weight $w\\ge 2$ and cut it into two smaller pieces of weight $\\lfloor\\frac{w}{2}\\rfloor$ and $\\lceil\\frac{w}{2}\\rceil$ ($\\lfloor x \\rfloor$ and $\\lceil x \\rceil$ denote floor and ceiling functions, respectively).\n\nAfter cutting the cake in $n$ pieces, she will line up these $n$ pieces on a table in an arbitrary order. Let $a_i$ be the weight of the $i$-th piece in the line.\n\nYou are given the array $a$. Determine whether there exists an initial weight and sequence of operations which results in $a$.",
    "tutorial": "Can you find the initial weight which results in $a$? The initial weight is the sum of the final weights. Let's simulate the division, starting from a new cake. How to choose fast which splits to do? If the largest piece is not in $a$, you have to split it. How to find the largest piece efficiently? Keep $a$ and the new cake in two multisets or priority queues. First, let's find the initial weight. When a piece of cake is split, the sum of weights is $\\lfloor\\frac{w}{2}\\rfloor + \\lceil\\frac{w}{2}\\rceil$: if $w$ is even, $\\lfloor\\frac{w}{2}\\rfloor + \\lceil\\frac{w}{2}\\rceil = \\frac{w}{2} + \\frac{w}{2} = w$; if $w$ is odd, $\\lfloor\\frac{w}{2}\\rfloor + \\lceil\\frac{w}{2}\\rceil = \\frac{w-1}{2} + \\frac{w+1}{2} = w$. Therefore, the sum of weights is constant, and the initial weight is the sum of the final weights. Now let's start from a cake $b$ of weight $b_1 = \\sum_{i=1}^n a_i$, split it (into pieces of weight $b_i$) and try to make it equal to $a$. At any moment, it's convenient to consider the largest $b_i$, because you can determine if you can split it or not. More specifically, if $b_i$ is not in $a$, you have to split it; if $b_i = a_j$ for some $j$, you can only match $a_j$ with $b_i$ or with a $b_k$ such that $b_k = a_j = b_i$ (because there doesn't exist any larger $b_k$): that's equivalent to removing $a_j$ and $b_i$ from $a$, $b$, respectively. Notice that, if at any moment the maximum element of $b$ is smaller than the maximum element of $a$, the answer is NO. If can keep $a$ and $b$ in any data structure that supports inserting an integer, asking for the maximum and removing the maximum (e.g., multiset or priority queue), the following algorithm works. While either $a$ or $b$ is not empty, if the maximum element of $b$ is smaller than the maximum element of $a$, print NO and break; if the maximum element of $b$ is equal to the maximum element of $a$, remove it from both $a$ and $b$; if the maximum element $m$ of $b$ is larger than the maximum element of $a$, remove it from $b$ and split the piece of cake (i.e., insert $\\lfloor\\frac{w}{2}\\rfloor$ and $\\lceil\\frac{w}{2}\\rceil$ into $b$). If $a$ or $b$ are both empty at the end, the answer is YES. Complexity: $O(n \\log n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\n \nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int t; cin >> t;\n    while (t--) {\n \n        ll n; cin >> n;\n        vector<ll> a(n);\n        for (int i = 0; i < n; i++)\n            cin >> a[i];\n \n        ll sum = 0;\n        for (int i = 0; i < n; i++)\n            sum += a[i];\n \n        multiset<ll> p = {sum};\n        multiset<ll> q(a.begin(), a.end());\n \n        while (!p.empty()) {\n            ll x = *--p.end();\n            if (x < *--q.end()) break;\n            p.erase(--p.end());\n            if (q.find(x) != q.end())\n                q.erase(q.find(x));\n            else {\n                p.insert(x/2);\n                p.insert((x+1)/2);\n            }\n        }\n \n        cout << (q.empty() ? \"YES\" : \"NO\") << \"\\n\";\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1654",
    "index": "D",
    "title": "Potion Brewing Class",
    "statement": "Alice's potion making professor gave the following assignment to his students: brew a potion using $n$ ingredients, such that the proportion of ingredient $i$ in the final potion is $r_i > 0$ (and $r_1 + r_2 + \\cdots + r_n = 1$).\n\nHe forgot the recipe, and now all he remembers is a set of $n-1$ facts of the form, \"ingredients $i$ and $j$ should have a ratio of $x$ to $y$\" (i.e., if $a_i$ and $a_j$ are the amounts of ingredient $i$ and $j$ in the potion respectively, then it must hold $a_i/a_j = x/y$), where $x$ and $y$ are positive integers. However, it is guaranteed that the set of facts he remembers is sufficient to uniquely determine the original values $r_i$.\n\nHe decided that he will allow the students to pass the class as long as they submit a potion which satisfies all of the $n-1$ requirements (there may be many such satisfactory potions), and contains a positive integer amount of each ingredient.\n\nFind the minimum total amount of ingredients needed to make a potion which passes the class. As the result can be very large, you should print the answer modulo $998\\,244\\,353$.",
    "tutorial": "The $n-1$ facts make a tree. Assume that the amount of ingredient $1$ is $1$. For each $i$, the amount of ingredient $i$ would be $c_i/d_i$ for some integer $c_i, d_i > 0$. How to make an integer amount of each ingredient? The optimal amount of ingredient $1$ is $\\text{lcm}(d_1, d_2, \\dots, d_n)$. Can you find the exponent of each prime $p \\leq n$ in $\\text{lcm}(d_1, d_2, \\dots, d_n)$? If you visit the nodes in DFS order, each edge changes the exponent of $O(\\log n)$ primes. At each moment, keep the factorization of $c_i/d_i$ of the current node, i.e., the exponents of each $p \\leq n$ (they can be negative). For each $p$, also keep the minimum exponent so far. Read the hints. The rest is just implementation. Start a DFS from node $1$. Keep an array $f$ such that $f_p$ is the exponent of $p$ in the amount of ingredients of the current node. Keep also $v_i = c_i/d_i \\,\\, \\text{mod} \\,\\, 998\\,244\\,353$. At the beginning, the amount of ingredients (of node $1$) is $1$, so $f_p = 0$ for each $p$. Whenever you move from node $i$ to node $j$, and $r_i/r_j = x/y$, for each $p^k$ such that $p^k \\mid x$ and $p^{k+1} \\nmid x$, decrease $f_p$ by $k$; for each $p^k$ such that $p^k \\mid y$ and $p^{k+1} \\nmid y$, increase $f_p$ by $k$. Notice that there exist $O(\\log n)$ such values of $p^k$ for each edge, and you can find them by precalculating either the smallest prime factor (with the sieve of Eratosthenes) or the whole factorization of every integer in $[2, n]$. Let $g_p$ be the minimum value of $f_p$ during the DFS. Then, for every $p$, you have to multiply the amount of ingredients of node $1$ by $p^{-g_p}$. The answer is the sum of $v_i$, multiplied by the amount of ingredients of node $1$. Complexity: $O(n \\log n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nconst int inf = 1e9+10;\nconst ll inf_ll = 1e18+10;\n#define all(x) (x).begin(), (x).end()\n#define pb push_back\n#define cmax(x, y) (x = max(x, y))\n#define cmin(x, y) (x = min(x, y))\n \n#ifndef LOCAL\n#define debug(...) 0\n#else\n#include \"../../debug.cpp\"\n#endif\n \ntemplate<ll M>\nstruct modint {\n \n    static ll _pow(ll n, ll k) {\n        ll r = 1;\n        for (; k > 0; k >>= 1, n = (n*n)%M)\n            if (k&1) r = (r*n)%M;\n        return r;\n    }\n \n    ll v; modint(ll n = 0) : v(n%M) { v += (M&(0-(v<0))); }\n    \n    friend string to_string(const modint n) { return to_string(n.v); }\n    friend istream& operator>>(istream& i, modint& n) { return i >> n.v; }\n    friend ostream& operator<<(ostream& o, const modint n) { return o << n.v; }\n    template<typename T> explicit operator T() { return T(v); }\n \n    friend bool operator==(const modint n, const modint m) { return n.v == m.v; }\n    friend bool operator!=(const modint n, const modint m) { return n.v != m.v; }\n    friend bool operator<(const modint n, const modint m) { return n.v < m.v; }\n    friend bool operator<=(const modint n, const modint m) { return n.v <= m.v; }\n    friend bool operator>(const modint n, const modint m) { return n.v > m.v; }\n    friend bool operator>=(const modint n, const modint m) { return n.v >= m.v; }\n \n    modint& operator+=(const modint n) { v += n.v; v -= (M&(0-(v>=M))); return *this; }\n    modint& operator-=(const modint n) { v -= n.v; v += (M&(0-(v<0))); return *this; }\n    modint& operator*=(const modint n) { v = (v*n.v)%M; return *this; }\n    modint& operator/=(const modint n) { v = (v*_pow(n.v, M-2))%M; return *this; }\n    friend modint operator+(const modint n, const modint m) { return modint(n) += m; }\n    friend modint operator-(const modint n, const modint m) { return modint(n) -= m; }\n    friend modint operator*(const modint n, const modint m) { return modint(n) *= m; }\n    friend modint operator/(const modint n, const modint m) { return modint(n) /= m; }\n    modint& operator++() { return *this += 1; }\n    modint& operator--() { return *this -= 1; }\n    modint operator++(int) { modint t = *this; return *this += 1, t; }\n    modint operator--(int) { modint t = *this; return *this -= 1, t; }\n    modint operator+() { return *this; }\n    modint operator-() { return modint(0) -= *this; }\n \n    // O(logk) modular exponentiation\n    modint pow(const ll k) const {\n        return k < 0 ? _pow(v, M-1-(-k%(M-1))) : _pow(v, k);\n    }\n    modint inv() const { return _pow(v, M-2); }\n};\n \nusing mod = modint<998244353>;\nconst int N = 2e5+5; // upper bound on x, y\n \nvector<vector<array<int, 3>>> adj;\nvector<int> d; // d[x] = smallest divisor of x\nvector<vector<int>> factors; // factors[x] = prime factors of x, including duplicates\nvector<int> f, wf; // from editorial\nmod ans = 0;\n \n// compute wf\nvoid dfs1(int i, int k) {\n    for (auto& [j, x, y] : adj[i])\n        if (j != k) {\n            for (int p : factors[y]) f[p]--;\n            for (int p : factors[x]) f[p]++, cmax(wf[p], f[p]);\n            dfs1(j, i);\n            for (int p : factors[y]) f[p]++;\n            for (int p : factors[x]) f[p]--;\n        }\n}\n \n// compute the amount of every ingredient, where p is the amount of ingredient i\nvoid dfs2(int i, int k, mod p) {\n    ans += p;\n    mod tmp = p;\n    for (auto& [j, x, y] : adj[i]) {\n        if (j != k) {\n            p = tmp;\n            for (int q : factors[y]) p *= q;\n            for (int q : factors[x]) p /= q;\n            dfs2(j, i, p);\n        }\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int t; cin >> t;\n \n    d.assign(N, 1);\n    factors.resize(N);\n    for (int i = N-1; i > 1; i--)\n        for (int j = i; j < N; j += i)\n            d[j] = i;\n    for (int i = 1; i < N; i++)\n        for (int x = i; x != 1; x /= d[x])\n            factors[i].pb(d[x]);\n \n    f.assign(N, 0);\n    wf.assign(N, 0);\n \n    while (t--) {\n        int n; cin >> n;\n \n        set<int> distinct_primes;\n \n        adj.assign(n, {});\n        for (int i = 0; i < n-1; i++) {\n            int p, q, x, y; cin >> p >> q >> x >> y;\n            p--, q--;\n            adj[p].pb({q, x, y});\n            adj[q].pb({p, y, x});\n            for (int z : factors[x])\n                distinct_primes.insert(z);\n            for (int z : factors[y])\n                distinct_primes.insert(z);\n        }\n \n        dfs1(0, 0);\n        mod p = 1;\n        for (int x : distinct_primes)\n            for (int i = 0; i < wf[x]; i++)\n                p *= x;\n        ans = 0;\n        dfs2(0, 0, p);\n        cout << ans << \"\\n\";\n \n        for (int x : distinct_primes)\n            f[x] = wf[x] = 0;\n    }\n}",
    "tags": [
      "dfs and similar",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1654",
    "index": "E",
    "title": "Arithmetic Operations",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$.\n\nYou can do the following operation any number of times (possibly zero):\n\n- Choose any index $i$ and set $a_i$ to any integer (positive, negative or $0$).\n\nWhat is the minimum number of operations needed to turn $a$ into an arithmetic progression? The array $a$ is an arithmetic progression if $a_{i+1}-a_i=a_i-a_{i-1}$ for any $2 \\leq i \\leq n-1$.",
    "tutorial": "Consider each element of the array as being a point in the plane $(i, a_i)$. Then all of the elements that don't get affected by an operation lie on a single line in the plane. Find a line that maximizes the number of points on it. Let $m$ be the upper bound on $a_i$. The intended complexity is $O(n \\sqrt m)$. Let $m$ be the upper bound on $a_i$. Let $d$ be the difference between adjacent elements in the final array. Create a piecewise algorithm for the cases where $|d| < \\sqrt m$ and $|d| \\geq \\sqrt m$ As explained in the hints, instead of computing the fewest number of operations, we will compute the largest number of elements that don't have an operation on them, and we will create a piecewise algorithm with final complexity $O(n\\sqrt m)$ , where $m$ is the upper bound on $a_i$. Let $d$ be the common difference between elements in our final sequence. First of all, I will assume that $d \\geq 0$, since solving the problem for negative $d$ is as simple as reversing the array and running the solution again. If $d$ is fixed beforehand, we can solve the problem in $O(n)$ by putting element $i$ into bucket $a_i-d\\cdot i$ and returning $n$ minus the size of the biggest bucket. For $d < \\sqrt m$, we can use the above algorithm to handle all of these $d$ in $O(n \\sqrt m)$ time. We can keep a hashmap from bucket index $\\to$ number of elements in the bucket, or we can just keep an array since the bucket indices have a range of at most $O(n \\sqrt m)$ which is not enough to exceed the memory limit. For $d \\geq \\sqrt m$, we observe that if we have two indices $i, j$ such that $j > i+\\sqrt m$, then at least one of them definitely has to have an operation performed on it, because the difference between them would have to be $a_j-a_i \\geq \\sqrt m \\cdot d > m$ which is not possible. In other words, if we consider the set of elements which are not edited, that set will have gaps between pairs of elements of size at most $\\sqrt m$. So, we can build a graph between indices with an edge $i \\to j$ with label $x$ if $i < j \\leq i+\\sqrt m$ and $\\frac{a_j-a_i}{j-i} = x$. This graph has at most $n\\sqrt m$ edges. Then we just have to find the longest path in the graph where all edges have the same label. You can do this with dynamic programming -- let $dp_{i,d}$ be the length of the longest path ending at index $i$, where all edges have label $d$. For each $i$, we only need to check edges to $j$ where $i - \\sqrt m < j < i$. This means the time complexity is $O(n\\sqrt m)$. To store the values $dp_{i,d}$ sparsely, we can use either a hash map or a rotating buffer (where we only store $dp_{i,d}$ for $i$ in a sliding window of width $\\sqrt m$). Complexity: $O(n \\sqrt m)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;\n \nstruct splitmix64 {\n    size_t operator()(size_t x) const {\n        static const size_t fixed = chrono::steady_clock::now().time_since_epoch().count();\n        x += 0x9e3779b97f4a7c15 + fixed;\n        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;\n        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;\n        return x ^ (x >> 31);\n    }\n};\n \nconst int N = 1e5+5, S = 70;\nint n, a[N];\n \n// for small d case: b[i] = number of elements in bucket i\nint b[N*S];\n \n// for large d case: dp[i][j] = maximum length of a path ending\n// at index i, such that all edges in the path have label j\ngp_hash_table<int, int, splitmix64> dp[N];\n \n// solve under the assumption that d >= 0\nint solve() {\n \n    int ans = 0;\n \n    // d < S\n    for (int d = 0; d < S; d++) {\n        for (int i = 0; i < n; i++)\n            ans = max(ans, ++b[a[i]+(n-i)*d]);\n        for (int i = 0; i < n; i++)\n            b[a[i]+(n-i)*d] = 0;\n    }\n \n    // S <= d < N\n    for (int i = 0; i < n; i++) {\n        for (int j = max(0, i-N/S); j < i; j++) {\n            int d = (a[i]-a[j])/(i-j);\n            int r = (a[i]-a[j])%(i-j);\n            if (r == 0 && d >= S) {\n                dp[i][d] = max(dp[i][d], dp[j][d]+1);\n                ans = max(ans, dp[i][d]+1);\n            }\n        }\n    }\n \n    for (int i = 0; i < n; i++)\n        dp[i].clear();\n \n    return ans;\n}\n \nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    cin >> n;\n    for (int i = 0; i < n; i++)\n        cin >> a[i];\n    int ans = solve();\n    reverse(a, a+n);\n    ans = max(ans, solve());\n    cout << n-ans << \"\\n\";\n}",
    "tags": [
      "brute force",
      "data structures",
      "graphs",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1654",
    "index": "F",
    "title": "Minimal String Xoration",
    "statement": "You are given an integer $n$ and a string $s$ consisting of $2^n$ lowercase letters of the English alphabet. The characters of the string $s$ are $s_0s_1s_2\\cdots s_{2^n-1}$.\n\nA string $t$ of length $2^n$ (whose characters are denoted by $t_0t_1t_2\\cdots t_{2^n-1}$) is a xoration of $s$ if there exists an integer $j$ ($0\\le j \\leq 2^n-1$) such that, for each $0 \\leq i \\leq 2^n-1$, $t_i = s_{i \\oplus j}$ (where $\\oplus$ denotes the operation bitwise XOR).\n\nFind the lexicographically minimal xoration of $s$.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Let $f(s, x)$ be the string $t$ such that $t_i = s_{i\\oplus x}$. The intended solution not only finds the $x$ such that $f(s, x)$ is lexicographically minimized, but produces an array of all $0 \\leq x < 2^n$ sorted according the comparator $f(s, i) < f(s, j)$. The solution is similar to the standard method to construct a suffix array. Let $a_k$ be an array of the integers $0$ through $2^n-1$, sorted according to the lexicographic ordering of the first $2^k$ characters of $f(s, x)$. The answer to the problem is $f(s, a_{n,0})$. Given the array $a_{k-1}$, can you compute $a_k$? Let $f(s, x)$ be the string $t$ such that $t_i = s_{i\\oplus x}$. The solution is inspired by the standard method to construct a suffix array. Let $a_k$ be an array containing the integers $0, 1, 2,\\dots, 2^n-1$, sorted according to the lexicographic ordering of the prefixes of length $2^k$ of the strings $f(s, 0), f(s, 1), \\dots, f(s, 2^n-1)$ (i.e., the prefix of length $2^k$ of $f(s, a_k[i])$ is lexicographically smaller or equal than the prefix of length $2^k$ of $f(s, a_k[i+1])$). We can construct $a_k$ using $a_{k-1}$, and $a_0$ is easy to construct as a base case. In order to construct $a_k$ from $a_{k-1}$, we will first construct an auxiliary array of integers $v$ using $a_{k-1}$, where $v_i < v_j$ iff $f(s, i)_{0..2^{k-1}} < f(s, j)_{0..2^{k-1}}$. Then, we will sort the array $a_k$ according to the comparison of tuples $(v_i, v_{i\\oplus {2^{k-1}}}) < (v_j, v_{j\\oplus {2^{k-1}}})$. Once we have $a_n$, then we just print $f(s, a_{n,0})$. In total, the solution takes $O(2^n n^2)$ time, which can be optimized to $O(2^n n)$ using the fact that tuples of integers in the range $[0, m]$ can be sorted using radix sort in $O(m)$ time. This optimization was not required to get AC.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 18;\nstring s;\nint a[1<<N], v[1<<N], tmp[1<<N];\n \nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int n; cin >> n >> s;\n    assert(s.size() == (1<<n));\n \n    iota(a, a+(1<<n), 0);\n    sort(a, a+(1<<n), [&](int i, int j){ return s[i] < s[j]; });\n    for (int i = 1; i < 1<<n; i++)\n        v[a[i]] = v[a[i-1]] + (s[a[i]] != s[a[i-1]] ? 1 : 0);\n \n    for (int k = 1; k < 1<<n; k <<= 1) {\n        auto cmp = [&](int i, int j){\n            return v[i] == v[j] ? v[i^k] < v[j^k] : v[i] < v[j];\n        };\n        sort(a, a+(1<<n), cmp);\n        for (int i = 1; i < 1<<n; i++)\n            tmp[a[i]] = tmp[a[i-1]] + (cmp(a[i-1], a[i]) ? 1 : 0);\n        copy(tmp, tmp+(1<<n), v);\n    }\n \n    for (int i = 0; i < 1<<n; i++)\n        cout << s[i^a[0]];\n    cout << \"\\n\";\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "divide and conquer",
      "greedy",
      "hashing",
      "sortings",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1654",
    "index": "G",
    "title": "Snowy Mountain",
    "statement": "There are $n$ locations on a snowy mountain range (numbered from $1$ to $n$), connected by $n-1$ trails in the shape of a tree. Each trail has length $1$. Some of the locations are base lodges. The height $h_i$ of each location is equal to the distance to the nearest base lodge (a base lodge has height $0$).\n\nThere is a skier at each location, each skier has initial kinetic energy $0$. Each skier wants to ski along as many trails as possible. Suppose that the skier is skiing along a trail from location $i$ to $j$. Skiers are not allowed to ski uphill (i.e., if $h_i < h_j$). It costs one unit of kinetic energy to ski along flat ground (i.e., if $h_i = h_j$), and a skier gains one unit of kinetic energy by skiing downhill (i.e., if $h_i > h_j$). For each location, compute the length of the longest sequence of trails that the skier starting at that location can ski along without their kinetic energy ever becoming negative. Skiers are allowed to visit the same location or trail multiple times.",
    "tutorial": "Let's say that a vertex is \"flippable\" if it has at least one neighbor of the same height. The optimal strategy for a skier is to ski to a flippable vertex with lowest height, flip back and forth between that vertex and its neighbor until all energy is used, and then ski to a base lodge. Assuming the skier starts at vertex $v$ and chooses vertex $u$ as the flippable vertex to flip back and forth at, this skier will \"waste\" a total of $h_u$ units of kinetic energy for a total path length of $2h_v-h_u$. Note that if no such $u$ exists, then the maximum amount of $h_v$ will be wasted as the skier goes straight to a base lodge. Let $w_v$ be this \"wasted\" amount. Instead of computing the maximum path length for the skier starting at vertex $v$, compute $w_v$. The answer for that vertex is $2h_v-w_v$. Try to solve this seemingly unrelated problem: Let $S$ be the set of flippable vertices. What is the largest possible value of $\\sum\\limits_{v\\in S}h_v$? The largest possible value of $\\sum\\limits_{v\\in S}h_v$ is $O(n)$. Therefore, there are at most $O(\\sqrt n)$ distinct values of $w_v$ across all vertices. Solve for each value of $w_v$ separately. Read the hints. The rest is just implementation. For each set of flippable vertices of the same height, we can calculate the set of starting vertices which are able to reach at least one vertex in that flippable set. To do this, split the graph up into layers of equal height. Let $c_v$ be the minimum required energy to reach a vertex in the flippable set. $c_v$ can be computed via shortests paths, where edges in the same layer have weight $1$ and edges from layer $i$ to $i+1$ have weight $-1$. We can use bfs to relax the costs of vertices in a single layer, and then easily transition to the next layer. We do this for $O(\\sqrt n)$ different starting heights, so the total complexity is $O(n\\sqrt n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define fi first\n#define se second\n#define int long long\nconst ll mod=998244353;\nconst int N=2e5+1;\nint n;\nint d[N];\nqueue<int>q;\n \nvector<int>adj[N];\nint g[N],h[N],z;\nbool use[N];\nvector<int>ans[N];\n \nvector<int>f[N];\nbool vis[N];\nvoid dfs(int id,int p){\n\tvis[id]=true;\n\tfor(auto c:adj[id]){\n\t\tif(c==p || d[c]!=d[id]) continue;\n\t\tdfs(c,id);\n\t\tfor(int i=1; i<=z ;i++){\n\t\t\tans[id][i]=min(ans[id][i],ans[c][i]+1);\n\t\t}\n\t\tans[id][h[d[id]]]=1;\n\t}\n}\nvoid dfs2(int id,int p){\n\tfor(auto c:adj[id]){\n\t\tif(c==p || d[c]!=d[id]) continue;\n\t\tfor(int i=1; i<=z ;i++){\n\t\t\tans[c][i]=min(ans[c][i],ans[id][i]+1);\n\t\t}\n\t\tans[c][h[d[c]]]=1;\n\t\tdfs2(c,id);\n\t}\n}\nmain(){\n\tios::sync_with_stdio(false);cin.tie(0);\n\tcin >> n;\n\tfor(int i=1; i<=n ;i++){\n\t\tint x;cin >> x;\n\t\tif(x==1) q.push(i);\n\t\telse d[i]=1e9;\t\t\n\t}\n\tfor(int i=1; i<n ;i++){\n\t\tint u,v;cin >> u >> v;\n\t\tadj[u].push_back(v);\n\t\tadj[v].push_back(u);\n\t}\n\twhile(!q.empty()){\n\t\tint x=q.front();q.pop();\n\t\tfor(auto c:adj[x]){\n\t\t\tif(d[c]>d[x]+1){\n\t\t\t\td[c]=d[x]+1;\n\t\t\t\tq.push(c);\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=1; i<=n ;i++){\n\t\tf[d[i]].push_back(i);\n\t\tfor(auto c:adj[i]){\n\t\t\tif(d[c]==d[i] && c>i){\n\t\t\t\tuse[d[i]]=true;\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i=0; i<=n ;i++){\n\t\tif(use[i]){\n\t\t\tg[++z]=i;\n\t\t\th[i]=z;\n\t\t}\n\t}/*\n\tfor(int i=1; i<=n ;i++){\n\t\tcout << d[i] << ' ';\n\t}\n\tcout << endl;*/\n\tfor(int i=1; i<=n ;i++){\n\t\tans[i].resize(z+1);\n\t}\n\tfor(int j=0; j<=n ;j++){\n\t\tfor(auto x:f[j]){\n\t\t\tfor(int i=1; i<=z ;i++) ans[x][i]=1e9;\n\t\t\tfor(auto c:adj[x]){\n\t\t\t\tif(d[c]==d[x]-1){\n\t\t\t\t\tfor(int i=1; i<=z ;i++) ans[x][i]=min(ans[x][i],max((ll)0,ans[c][i]-1));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(auto x:f[j]){\n\t\t\tif(!vis[x]){\n\t\t\t\tdfs(x,0);\n\t\t\t\tdfs2(x,0);\n\t\t\t}\n\t\t}\n\t\t/*for(auto x:f[j]){\n\t\t\tcout << x << \": \";\n\t\t\tfor(int i=1; i<=z ;i++) cout << ans[x][i] << ' ';\n\t\t\tcout << '\\n';\n\t\t}*/\n\t}\n\tfor(int i=1; i<=n ;i++){\n\t\tint res=d[i];\n\t\tfor(int j=1; j<=z ;j++){\n\t\t\tif(ans[i][j]==0) res=max(res,d[i]*2-g[j]);\n\t\t}\n\t\tcout << res << ' ';\n\t}\n\tcout << '\\n';\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1654",
    "index": "H",
    "title": "Three Minimums",
    "statement": "Given a list of distinct values, we denote with first minimum, second minimum, and third minimum the three smallest values (in increasing order).\n\nA permutation $p_1, p_2, \\dots, p_n$ is good if the following statement holds for all pairs $(l,r)$ with $1\\le l < l+2 \\le r\\le n$.\n\n- If $\\{p_l, p_r\\}$ are (not necessarily in this order) the first and second minimum of $p_l, p_{l+1}, \\dots, p_r$ then the third minimum of $p_l, p_{l+1},\\dots, p_r$ is either $p_{l+1}$ or $p_{r-1}$.\n\nYou are given an integer $n$ and a string $s$ of length $m$ consisting of characters \"<\" and \">\".\n\nCount the number of good permutations $p_1, p_2,\\dots, p_n$ such that, for all $1\\le i\\le m$,\n\n- $p_i < p_{i+1}$ if $s_i =$ \"<\";\n- $p_i > p_{i+1}$ if $s_i =$ \">\".\n\nAs the result can be very large, you should print it modulo $998\\,244\\,353$.",
    "tutorial": "If $p_1,\\dots, p_n$ is good and $p_i=1$, what can you say about $p_1,p_2,\\dots, p_i$ and $p_i,p_{i+1},\\dots, p_n$? Find a quadratic solution ignoring the constraints given by the string $s$. Find an $O(n^2 + nm)$ solution taking care of the constraints given by the string $s$. Optimize the $O(n^2+nm)$ solution using generating functions. The solution to the ODE $y'(t) = a(t)y(t) + b(t)$ with $y(0)=1$ is given by $\\exp(\\smallint a)\\Big(1+\\int b\\exp(-\\smallint a)\\Big)$ First of all, let us state the following lemma (which is sufficient to solve the problem in $O(n^2)$ if one ignores the constraints given by the string $s$). We omit the proof as it is rather easy compared to the difficulty of the problem as a whole. Lemma: The following statements hold for a permutation $p_1,p_2,\\dots, p_n$. $p$ is good if and only if $p[1:i]$ and $p[i:n]$ are good, where $p_i = 1$. If $p_1=1$, then $p$ is good if and only if $p[1:i]$ and $p[i:n]$ are good, where $p_i = 2$. If $p_1=1$ and $p_n=2$, then $p$ is good if and only if it is bitonic, i.e., $p_1<p_2<p_3<\\cdots<p_i>p_{i+1}>\\cdots p_{n-1}>p_n$, where $p_i=n$. Given $1\\le l < r\\le n$, we say that a permutation $q_1,q_2,\\dots, q_{r-l+1}$ of ${1,2,\\dots, r-l+1}$ is $[l,r]$-consistent if for any $l\\le i \\le \\min(r, m-1)$: $q_{i-l+1} < q_{i-l+2}$ if $s_i = \\texttt{<}$; $q_{i-l+1} > q_{i-l+2}$ if $s_i = \\texttt{>}$. Informally speaking, a permutation is $[l,r]$-consistent if it satisfies the constraints given by $s$ when it is written in the positions $[l, r]$. For $1\\le l<r\\le n$, let $a_{\\ast\\ast}(l, r)$, $a_{1\\ast}(l, r)$, $a_{\\ast 1}(l, r)$, $a_{12}(l, r)$, $a_{21}(l, r)$ be the the number of good permutations which are $[l,r]$-consistent and, respectively, No additional conditions; Start with $1$; End with $1$; Start with $1$ and end with $2$; Start with $2$ and end with $1$. For $1\\le i < n$ and $c\\in{\\texttt{<}, \\texttt{>}}$, let $q(i, c) := [i>m\\text{ or } s_i= c]$. Informally speaking, $q(i, \\texttt{<})$ is $1$ if and only if it can be $p_i<p_{i+1}$ and $q(i, \\texttt{>})$ is $1$ if and only if it can be $p_i > p_{i+1}$. Thanks to the Lemma, one has the following relations: $a_{\\ast\\ast}(l, r) = \\sum_{i=l}^r a_{\\ast1}(l, i) a_{1\\ast}(i, r) \\binom{r-l}{i-l}$. $a_{1\\ast}(l, l) = 1$. For $l < r$, $a_{1\\ast}(l, r) = \\sum_{i=l+1}^r a_{12}(l, i)a_{1\\ast}(i, r)\\binom{r-l-1}{i-l-1}$. Analogous formula for $a_{\\ast 1}$. $a_{12}(l, l) = 0$ and $a_{12}(l, l+1)= q(l, \\texttt{<})$ and $a_{12}(l, l+2)= q(l, \\texttt{<})\\cdot q(l+1, \\texttt{>})$. For $l<l+1<r$, $a_{12}(l, r) = q(l, \\texttt{<})a_{21}(l+1, r) + q(r-1, \\texttt{>})a_{12}(l, r-1)$. Analogous formula for $a_{21}$. The problem asks to compute $a_{\\ast\\ast}(1, n)$. Thanks to the formulas stated above, it is straightforward to implement an $O(n^2)$ solution. Now we will tackle the hard task of optimizing it to $O(nm + n\\log(n))$. In order to compute $a_{\\ast\\ast}(1, n)$, we will compute $a_{\\ast1}(1, k)$ and $a_{1\\ast}(k, n)$ for all $1\\le k\\le n$. We have the recurrence relation (for $k\\ge 2$) $\\tag{1} a_{\\ast1}(1, k) = \\sum_{i=1}^k a_{\\ast1}(1, i) a_{21}(i, k) \\binom{k-2}{i-1}$ Setting $x_{k-1} := a_{\\ast1}(1, k) / (k-1)!$, (1) is equivalent to (for $k\\ge 1$, and also for $k=0$!) $\\tag{2} k\\cdot x_k = \\sum_{i=0}^{k-1} x_i \\frac{a_{21}(i+1, k+1)}{(k-1-i)!}.$ This looks very similar to an identify between generating functions (a derivative on the left, a product on the right); but for the fact that $a_{21}$ depends on two parameters. To overcome this issue let us proceed as follows. Notice that, if we set $b$ to any of the functions $a_{\\ast\\ast}$, $a_{\\ast1}$, $a_{1\\ast}$, $a_{12}$, $a_{21}$, it holds $b(l, r) = b(l+1, r+1)$ whenever $l > m$. Hence, let us define $b_{\\ast\\ast}(k) = a_{\\ast\\ast}(n+1, n+k)$ and analogously $b_{1\\ast}(k)$, $b_{\\ast 1}(k)$, $b_{12}(k)$, $b_{21}(k)$. With these new definitions, (2) becomes (for $k\\ge 0$) $\\tag{3} k\\cdot x_k = \\sum_{i=0}^{k-1} x_i \\frac{b_{21}((k-1-i) + 2)}{(k-1-i)!} + \\sum_{i=0}^{\\min(k-1, m-1)} x_i \\frac{a_{21}(i+1, k+1) - b_{21}(k+1-i)}{(k-1-i)!} .$ Let $u_i:= \\frac{b_{21}(i+2)}{i!}$ and $v_{k-1}:= \\sum_{i=0}^{\\min(k-1, m-1)} x_i \\frac{b_{21}(k+1-i) - a_{21}(i+1, k+1)}{(k-1-i)!}$. So, (3) simplifies to $\\tag{4} k\\cdot x_k = v_{k-1} + \\sum_{i=0}^{k-1} x_i u_{k-1-i} .$ We precompute in $O(nm)$ the values of $a_{12}(l, r)$ and $a_{21}(l, r)$ for $1\\le l\\le m$, $l < r\\le n$. We can also precompute in $O(n)$ the values of $b_{12}(k), b_{21}(k)$ for $1\\le k\\le n$. In $O(m^2)$ we compute also $x_i$ for all $0\\le i\\le m-1$. Thus, in $O(nm)$ we can compute, for all $0\\le k < n$, the values $u_k$. It is now time to start working with generating functions. Let $X(t):= \\sum_{k\\ge 0} x_k t^k$, $U(t):=\\sum_{k\\ge0} u_kt^k$, $V(t):=\\sum_{k\\ge0} v_kt^k$. We know $U(t)$ and $V(t)$ (at least the first $n$ coefficients) and we want to compute $X(t)$. Since $x_0=1$, we know $X(0)=1$. Moreover (4) is equivalent to the ordinary differential equation $X' = V + U\\cdot X$. This ODE is standard and its (unique) solution is given by $X = \\exp(\\smallint U)\\Big(1 + \\int V\\exp(-\\smallint U)\\Big).$ Since the product of generating functions and the exponential of a generating function can be computed in $O(n\\log(n))$, we are able to obtain the values of $x_k$ for all $0\\le k <n$ and thus the values of $a_{\\ast 1}(1,k)$. Now, let us see how to compute $a_{1\\ast}(k, n)$. Since $a_{1\\ast}(k,n) = b_{1\\ast}(n-k+1)$ for all $m<k\\le n$, let us first compute $b_{1\\ast}(k)$ for all $1\\le k\\le n$. By repeating verbatim the reasoning above, we get that the generating function $Y(t):=\\sum_{k\\ge 0} y_k t^k$, where $y_{k-1}:=b_{1\\ast}(k) / (k-1)!$, is given by ($V=0$ in this case) $Y=\\exp(\\int U)$. So, it remains only to compute $a_{1\\ast}(k, n)$ for $1\\le k\\le m$. This can be done naively in $O(nm)$. The overall complexity is $O(nm + n\\log(n))$.",
    "code": "#define _USE_MATH_DEFINES\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef unsigned long long ULL;\ntypedef long long LL;\n#define SZ(x) ((int)((x).size()))\n \ntemplate <typename T1, typename T2>\nstring print_iterable(T1 begin_iter, T2 end_iter, int counter) {\n    bool done_something = false;\n    stringstream res;\n    res << \"[\";\n    for (; begin_iter != end_iter and counter; ++begin_iter) {\n        done_something = true;\n        counter--;\n        res << *begin_iter << \", \";\n    }\n    string str = res.str();\n    if (done_something) {\n        str.pop_back();\n        str.pop_back();\n    }\n    str += \"]\";\n    return str;\n}\n \nvector<int> SortIndex(int size, std::function<bool(int, int)> compare) {\n    vector<int> ord(size);\n    for (int i = 0; i < size; i++) ord[i] = i;\n    sort(ord.begin(), ord.end(), compare);\n    return ord;\n}\n \ntemplate <typename T>\nbool MinPlace(T& a, const T& b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename T>\nbool MaxPlace(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate <typename S, typename T>\nostream& operator <<(ostream& out, const pair<S, T>& p) {\n    out << \"{\" << p.first << \", \" << p.second << \"}\";\n    return out;\n}\n \ntemplate <typename T>\nostream& operator <<(ostream& out, const vector<T>& v) {\n    out << \"[\";\n    for (int i = 0; i < (int)v.size(); i++) {\n        out << v[i];\n        if (i != (int)v.size()-1) out << \", \";\n    }\n    out << \"]\";\n    return out;\n}\n \ntemplate<class TH>\nvoid _dbg(const char* name, TH val){\n    clog << name << \": \" << val << endl;\n}\ntemplate<class TH, class... TA>\nvoid _dbg(const char* names, TH curr_val, TA... vals) {\n    while(*names != ',') clog << *names++;\n    clog << \": \" << curr_val << \", \";\n    _dbg(names+1, vals...);\n}\n \n#if DEBUG && !ONLINE_JUDGE\n    ifstream input_from_file(\"input.txt\");\n    #define cin input_from_file\n \n    #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)\n    #define dbg_arr(x, len) clog << #x << \": \" << print_iterable(x, x+len, -1) << endl;\n#else\n    #define dbg(...)\n    #define dbg_arr(x, len)\n#endif\n \n// Computes the inverse of n modulo m.\n// Precondition: n >= 0, m > 0 and gcd(n, m) == 1.\n// The returned value satisfies 0 <= x < m (Inverse(0, 1) = 0).\n// ACHTUNG: It must hold max(m, n) < 2**31 to avoid integer overflow.\nLL Inverse(LL n, LL m) {\n    n %= m;\n    if (n <= 1) return n; // Handles properly (n = 0, m = 1).\n    return m - ((m * Inverse(m, n) - 1) / n);\n}\n \n// Fast exponentiation modulo mod. Returns x**e modulo mod.\n// Assumptions: 0 <= x < mod\n//              mod < 2**31.\n//              0 <= e < 2**63\nLL pow(LL x, LL e, LL mod) {\n    LL res = 1;\n    for (; e >= 1; e >>= 1) {\n        if (e & 1) res = res * x % mod;\n        x = x * x % mod;\n    }\n    return res;\n}\n \n// Struct that computes x % mod faster than usual, if mod is always the same.\n// It gives a x1.8 speed up over the % operator (with mod ~ 1e9 and x large).\n// It is an implementation of the Barrett reduction, see\n//    https://en.wikipedia.org/wiki/Barrett_reduction .\n// If fast_mod is an instance of the class, then fast_mod(x) will return\n// x % mod. There are no restrictions on the values of mod and x, provided\n// that they fit in an unsigned long long (and mod != 0).\n//\n// ACHTUNG: The integer type __uint128_t must be available.\nstruct FastMod {\n    ULL mod;\n    ULL inv;\n    FastMod(ULL mod) : mod(mod), inv(-1ULL / mod) {}\n    ULL operator()(ULL x) {\n        ULL q = (ULL)((__uint128_t(inv) * x) >> 64);\n        ULL r = x - q * mod;\n        return r - mod * (r >= mod);\n    }\n};\n \n// Class for integers modulo mod.\n// It supports all expected operations: +, -, *, /, pow, ==, < and >.\n// It is as fast as it can be.\n// The modulo mod shall be set through set_mod().\n//\n// Assumptions: mod < (1<<30).\n// ACHTUNG: The integer type __uint128_t must be available.\n//\n// Remark: To handle larger moduli (up to 1<<62), one has to:\n//          1. replace int in the definitions of mod, n.\n//          2. The parameter of fast_mod must be __uint128_t, so it must be\n//             changed in the definition of fast_mod and in the definition of\n//             the operators * and *=.\n//          3. fast_mod must be a naive modulo operation, no barrett reduction.\n//          4. In Inverse, __int128_t shall be used.\nstruct ModularInteger {\n    static int mod;\n    static __uint128_t inv_mod; // Necessary for fast_mod.\n    int n; // 0 <= n < mod at all times\n    static void set_mod(int _mod) {\n        mod = _mod;\n        inv_mod = -1ULL / mod;\n    }\n    ModularInteger(): n(0) {}\n    ModularInteger(LL _n): n(_n % mod) {\n        n += (n<0)*mod;\n    }\n    LL get() const { return n; }\n    static int fast_mod(ULL x) { // Barrett reduction.\n        ULL q = (inv_mod * x) >> 64;\n        int m = x - q * mod;\n        m -= mod * (m >= mod);\n        return m;\n    }\n \n    ModularInteger operator-() const { return n?mod-n:0; }\n};\nint ModularInteger::mod;\n__uint128_t ModularInteger::inv_mod;\n \nModularInteger operator +(const ModularInteger& A, const ModularInteger& B) {\n    ModularInteger C;\n    C.n = A.n + B.n;\n    C.n -= (C.n >= ModularInteger::mod)*ModularInteger::mod;\n    return C;\n}\n \nvoid operator +=(ModularInteger& A, const ModularInteger& B) {\n    A.n += B.n;\n    A.n -= (A.n >= ModularInteger::mod)*ModularInteger::mod;\n}\n \nModularInteger operator -(const ModularInteger& A, const ModularInteger& B) {\n    ModularInteger C;\n    C.n = A.n - B.n;\n    C.n += (C.n < 0)*ModularInteger::mod;\n    return C;\n}\n \nvoid operator -=(ModularInteger& A, const ModularInteger& B) {\n    A.n -= B.n;\n    A.n += (A.n < 0)*ModularInteger::mod;\n}\n \nModularInteger operator *(const ModularInteger& A, const ModularInteger& B) {\n    ModularInteger C;\n    C.n = ModularInteger::fast_mod(((ULL)A.n) * B.n);\n    return C;\n}\n \nvoid operator *=(ModularInteger& A, const ModularInteger& B) {\n    A.n = ModularInteger::fast_mod(((ULL)A.n) * B.n);\n}\n \n// Assumption: gcd(B, mod) = 1.\nModularInteger operator /(const ModularInteger& A, const ModularInteger& B) {\n    return A * Inverse(B.n, ModularInteger::mod);\n}\n \n// Assumption: gcd(B, mod) = 1.\nvoid operator/=(ModularInteger& A, const ModularInteger& B) {\n    A *= Inverse(B.n, ModularInteger::mod);\n}\n \nModularInteger power(ModularInteger A, ULL e) {\n    ModularInteger res = 1;\n    for (; e >= 1; e >>= 1) {\n        if (e & 1) res *= A;\n        A *= A;\n    }\n    return res;\n}\n \nbool operator ==(const ModularInteger& A, const ModularInteger& B) {\n    return A.n == B.n;\n}\nbool operator !=(const ModularInteger& A, const ModularInteger& B) {\n    return A.n != B.n;\n}\nbool operator <(const ModularInteger& A, const ModularInteger& B) {\n    return A.n < B.n;\n}\nbool operator >(const ModularInteger& A, const ModularInteger& B) {\n    return A.n > B.n;\n}\nbool operator <=(const ModularInteger& A, const ModularInteger& B) {\n    return A.n <= B.n;\n}\nbool operator >=(const ModularInteger& A, const ModularInteger& B) {\n    return A.n >= B.n;\n}\n \nostream& operator <<(ostream& out, const ModularInteger& A) {\n    out << A.n;\n    return out;\n}\n \nistream& operator >>(istream& in, ModularInteger& A) {\n  LL a;\n  in >> a;\n  A = ModularInteger(a);\n  return in;\n}\n \ntypedef ModularInteger mint;\n \n// Returns x such that Ord_mod(x) = order.\n// Assumptions:\n//  1. mod is an odd prime < 2**31\n//  2. order | mod-1\n//\n// Complexity: sqrt(lpf(order)) + polylog(order).\n// When this function is used as a building block for the number theoretic\n// transform, order is a power of two and therefore the complexity is\n// polylog(order).\nLL FindElementWithGivenOrder(LL mod, LL order) {\n    assert((mod-1)%order == 0);\n    vector<LL> primes; // primes dividing order\n    LL n = order;\n    for (LL p = 2; p*p <= n; p++) {\n        if (n % p == 0) {\n            primes.push_back(p);\n            while (n % p == 0) n /= p;\n        }\n    }\n    if (n != 1) primes.push_back(n);\n    for (LL x = 2; x < mod; x++) {\n        LL y = pow(x, (mod-1)/order, mod);\n        if (pow(y, order, mod) != 1) continue;\n        bool works = true;\n        for (LL p : primes) {\n            if (pow(y, order/p, mod) == 1) {\n                works = false;\n                break;\n            }\n        }\n        if (works) return y;\n    }\n    assert(0);\n    return -1;\n}\n \n \n// Precomputes the vectors rev and roots as required by the function FFT.\n// It is called internally by FFT when necessary (i.e., when the length of\n// the vector is strictly larger than all previous calls to FFT).\n// Both the arrays rev and roots have length N. Their values satisfy:\n// - rev[i] is the bit-reverse of i.\n// - roots contains the roots of unity. For any k that is a power of two,\n//   and any i < k, roots[k + i] contains the i-th power of the (2k)-root of\n//   unity. Using such an array speeds up (and simplifies) the code.\n//\n// Complexity: O(N)\n//\n// Assumptions:\n//  1. The type T is either complex<double> or ModularInteger.\n//  2. N power of 2\n//  3. If T = ModularInteger, then ModularInteger::mod is prime and\n//     N | mod-1 .\ntemplate <typename T>\nvoid _FFT_Precompute(int N, vector<int>& rev, vector<T>& roots) {\n    static_assert(std::is_same<T, ModularInteger>::value\n                  or std::is_same<T, complex<double>>::value);\n    assert(N > 0 and !(N&(N-1)));\n    rev.resize(N);\n    roots.resize(N);\n    rev[0] = 0;\n    for (int i = 1; i < N; i++) rev[i] = (rev[i>>1]>>1) ^ ((i&1)?(N>>1):0);\n    \n    // The generation of primitive roots is handled differently for complex\n    // numbers and finite fields.\n    if constexpr (std::is_same<T, ModularInteger>::value) {\n        ModularInteger primitive_root =\n            FindElementWithGivenOrder(ModularInteger::mod, N);\n        for (int k = 1; k < N; k<<=1) {\n            // z is a (2k)-primitive root.\n            ModularInteger z = power(primitive_root, N/(2*k)); \n            ModularInteger r = 1;\n            for (int i = 0; i < k; i++) {\n                roots[k+i] = r;\n                r *= z;\n            }\n        }\n    } else {\n        for (int k = 1; k < N; k<<=1) {\n            for (int i = 0; i < k; i++) {\n                double theta = M_PI*i/k;\n                roots[k+i] = cos(theta) + 1i * sin(theta);\n            }\n        }\n    }\n}\n \n// Given a sequence of numbers, computes its discrete Fourier transform in-place.\n// If inverse=true then the inverse of the Fourier transform is computed.\n//\n// More precisely, the resulting array a' satisfies\n//  a'_i = \\sum a_j w^{ij} ,\n// where w is an N-root of unity (N = a.size()).\n//\n// Complexity: O(Nlog(N)) where N = a.size().\n//\n// Assumptions:\n//  1. The type T is either complex<double> or ModularInteger.\n//  2. The length of a is a power of 2.\n//  3. If T = ModularInteger, then ModularInteger::mod is prime and the\n//     length of a divides mod-1 .\ntemplate <typename T>\nvoid FFT(vector<T>& a, bool inverse=false) {\n    static_assert(std::is_same<T, ModularInteger>::value\n                  or std::is_same<T, complex<double>>::value);\n    static vector<int> rev;\n    static vector<T> roots;\n    int N = a.size();\n    assert(N > 0 and !(N&(N-1)));\n    if ((int)rev.size() < N) _FFT_Precompute(N, rev, roots);\n \n    int offset = 0;\n    while ((1<<offset) < (int)rev.size()/N) offset++;\n \n    for (int i = 0; i < N; i++) if (i < (rev[i]>>offset)) {\n        swap(a[i], a[rev[i]>>offset]);\n    }\n    \n    for (int k = 1; k < N; k<<=1) {\n        for (int i = 0; i < N; i+=2*k) {\n            for (int j = 0; j < k; j++) {\n                T x = a[i+j], y = a[i+k+j] * roots[k+j];\n                a[i+j] = x + y;\n                a[i+k+j] = x - y;\n            }\n        }\n    }\n \n    if (inverse) {\n        reverse(a.begin()+1, a.end());\n        T invN = static_cast<T>(1) / static_cast<T>(N);\n        for (auto& val : a) val *= invN;\n    }\n}\n \n \n// Computes the convolution between a and b in O(n log n) where\n// n = a.size() + b.size().\n// It returns a vector c such that\n//   c[k] = \\sum_{i+j = k} a[i] b[j].\n//\n// Assumption: a and b are nonempty.\ntemplate<typename T>\nvector<T> Convolution(vector<T> a, vector<T> b) {\n    const static int small_len = 64;\n    int alen = a.size(), blen = b.size();\n    if (alen == 0 or blen == 0) return {};\n    assert(1 <= alen and 1 <= blen);\n \n    // Naive convolution O(alen * blen).\n    // Used if one of the two vectors is very short.\n    if (alen < small_len or blen < small_len) {\n        vector<T> c(alen + blen-1, 0);\n        for (int i = 0; i < alen; i++) for (int j = 0; j < blen; j++)\n            c[i + j] += a[i] * b[j];\n        return c;\n    }\n    \n    int sz = 1;\n    while (sz < alen + blen - 1) sz *= 2;\n    a.resize(sz, 0);\n    b.resize(sz, 0);\n    FFT(a);\n    FFT(b);\n    for (int i = 0; i < sz; i++) a[i] *= b[i];\n    FFT(a, true);\n    a.resize(alen + blen - 1);\n    return a;\n}\n \n \n// F is a field. Must support operator +, +=, -, -=, *, / as defined by the field.\n// F(0) must return additive identity. F(1) must return multiplicative identity.\ntemplate<typename F>\nstruct Polynomial {\n    vector<F> coef;\n \n    Polynomial() {}\n \n    Polynomial(const vector<F> &_coef) : coef(_coef) {}\n \n    Polynomial(vector<F> &&_coef) : coef(_coef) {}\n \n    size_t size() const {\n        return coef.size();\n    }\n \n    void trim_leading_zeros() {\n        while (!coef.empty() && coef.back() == F(0))\n            coef.pop_back();\n    }\n \n    void resize(size_t new_size) {\n        coef.resize(new_size, F(0));\n    }\n \n    void operator+=(const Polynomial &other) {\n        for (size_t i = 0; i < other.size(); i++)\n            if (i < coef.size())\n                coef[i] += other.coef[i];\n            else\n                coef.push_back(other.coef[i]);\n    }\n \n    Polynomial operator+(const Polynomial &other) const {\n        Polynomial ret = *this;\n        ret += other;\n        return ret;\n    }\n \n    void operator-=(const Polynomial &other) {\n        for (size_t i = 0; i < other.size(); i++)\n            if (i < coef.size())\n                coef[i] -= other.coef[i];\n            else\n                coef.push_back(-other.coef[i]);\n    }\n \n    Polynomial operator-(const Polynomial &other) const {\n        Polynomial<F> ret = *this;\n        ret -= other;\n        return ret;\n    }\n \n    Polynomial operator*(const Polynomial &other) const {\n        return Polynomial(Convolution<F>(this->coef, other.coef));\n    }\n \n    void operator*=(const Polynomial &other) {\n        *this = *this * other;\n    }\n \n    // f(x)g(x) = 1 (mod x^N)\n    Polynomial recip_mod(size_t deg = 0) const {\n        size_t n = deg;\n        if (n == 0)\n            n = size();\n        const int N_RECIP_MOD_NAIVE = 64;\n        if (n <= N_RECIP_MOD_NAIVE) {\n            Polynomial ret;\n            ret.coef.reserve(n);\n            ret.coef.push_back(F(1) / coef[0]);\n            for (size_t i = 1; i < n; i++) {\n                F s(0);\n                for (size_t j = 1; j <= i && j < size(); j++)\n                    s -= coef[j] * ret.coef[i - j];\n                ret.coef.push_back(s * ret.coef[0]);\n            }\n            return ret;\n        }\n        size_t n_low = (n + 1) / 2;\n        Polynomial low_recip;\n        if (size() <= n_low)\n            low_recip = recip_mod(n_low);\n        else {\n            Polynomial low(vector<F>(coef.begin(), coef.begin() + n_low));\n            low_recip = low.recip_mod();\n        }\n        Polynomial ret = low_recip * low_recip;\n        if (size() <= n)\n            ret *= *this;\n        else {\n            Polynomial trunc(vector<F>(coef.begin(), coef.begin() + n));\n            ret *= trunc;\n        }\n        ret.resize(n);\n        for (size_t i = n_low; i < n; i++)\n            ret.coef[i] = -ret.coef[i];\n        return ret;\n    }\n \n    Polynomial rev() const {\n        Polynomial ret = *this;\n        reverse(ret.coef.begin(), ret.coef.end());\n        return ret;\n    }\n \n    Polynomial derivative() const {\n        if (size() <= 1)\n            return Polynomial();\n        Polynomial deriv;\n        deriv.coef.reserve(size() - 1);\n        F multiplier(0);\n        for (size_t i = 1; i < size(); i++) {\n            multiplier += F(1);\n            deriv.coef.push_back(coef[i] * multiplier);\n        }\n        return deriv;\n    }\n \n    Polynomial integral() const {\n        if (size() <= 1)\n            return Polynomial({F(0)});\n        Polynomial integ;\n        integ.coef.reserve(size() + 1);\n        integ.coef.emplace_back(0);\n        F divisor(0);\n        for (size_t i = 0; i < size(); i++) {\n            divisor += F(1);\n            integ.coef.push_back(coef[i] / divisor);\n        }\n        return integ;\n    }\n};\n \nPolynomial<mint> exp(Polynomial<mint> f) {\n    Polynomial<mint> g({1});\n    while (g.size() < f.size()) {\n        size_t next_size = min(g.size() * 2, f.size());\n        vector<mint> f_coef_trunc(f.coef.begin(), f.coef.begin() + next_size);\n        f_coef_trunc[0] += 1;\n        Polynomial<mint> f_trunc(move(f_coef_trunc));\n        Polynomial<mint> log_g = g;\n        log_g.resize(next_size);\n        log_g = log_g.recip_mod() * g.derivative();\n        log_g.resize(next_size - 1);\n        log_g = log_g.integral();\n        g *= f_trunc - log_g;\n        g.resize(next_size);\n    }\n    return g;\n}\n \n \n///////////////////////////////////////////////////////////////////////////\n//////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////\n///////////////////////////////////////////////////////////////////////////\n \n \n \nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    mint::set_mod(998244353);\n \n    int n, m;\n    cin >> n >> m;\n    string s;\n    cin >> s;\n    s = '_' + s;\n    vector<mint> fact(n+1);\n    fact[0] = 1;\n    for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i;\n    vector<mint> ifact(n+1);\n    ifact[n] = mint(1) / fact[n];\n    for (int i = n-1; i >= 0; i--) ifact[i] = ifact[i+1] * (i+1);\n \n    // Definitions of q, a21, b21, a12.\n    // Complexity O(nm).\n    auto q = [&](int p, char c) { return p > m or s[p] == c; };\n    vector<vector<mint>> _a21(m+2, vector<mint>(n+m+2));\n    auto b21 = [&](int k) { return _a21[m+1][m+k]; };\n    auto a21 = [&](int l, int r) { return (l > m) ? b21(r-l+1) : _a21[l][r]; };\n    for (int l = m+1; l >= 0; l--) {\n        _a21[l][l+1] = q(l, '>');\n        _a21[l][l+2] = q(l, '<') and q(l+1, '>');\n        for (int r = l+3; r <= n+m+1; r++)\n            _a21[l][r] = q(l, '<') * a21(l+1, r) + q(r-1, '>') * a21(l, r-1);\n    }\n    auto a12 = [&](int l, int r) { return (l + 1 == r) ? q(l, '<') : a21(l, r); };\n \n    // Definitions of u, x, v.\n    // Complexity O(nm).\n    vector<mint> u(n);\n    for (int i = 0; i < n; i++) u[i] = b21(i+2) * ifact[i];\n \n    vector<mint> x(m);\n    x[0] = 1;\n    for (int k = 1; k < m; k++) {\n        for (int i = 0; i < k; i++) x[k] += x[i] * u[k-1-i];\n        for (int i = 0; i <= min(k-1, m-1); i++) {\n            mint diff = a21(i+1, k+1) - b21(k+1-i);\n            x[k] += diff * x[i] * ifact[k-1-i];\n        }\n        x[k] /= k;\n    }\n \n    vector<mint> v(n);\n    for (int k = 0; k < n; k++) {\n        for (int i = 0; i <= min(k, m-1); i++) {\n            mint diff = a21(i+1, k+2) - b21(k+2-i);\n            v[k] += x[i] * diff * ifact[k-i];\n        }\n    }\n    \n \n    // BEGIN Generating functions\n    // Complexity O(nlog(n)).\n    Polynomial<mint> U(u);\n    Polynomial<mint> V(v);\n \n    Polynomial<mint> Y = exp(U.integral());\n    Polynomial<mint> Y_inv = Y.recip_mod();\n    Polynomial<mint> X = Y + Y * (V*Y_inv).integral();\n    // END Generating functions\n \n    // Computing\n    //   pref[k] = a_{*1}(1, k),\n    //   suff[k] = a_{1*}(k, n).\n    // Complexity O(nm).\n    vector<mint> pref(n+1);\n    vector<mint> suff(n+1);\n \n    for (int k = 1; k <= n; k++) {\n        pref[k] = X.coef[k-1] * fact[k-1];\n        suff[n+1-k] = Y.coef[k-1] * fact[k-1];\n    }\n \n    auto binom = [&](int a, int b) {\n        return fact[a] * ifact[b] * ifact[a-b];\n    };\n    for (int k = m; k >= 1; k--) {\n        suff[k] = 0;\n        for (int i = k+1; i <= n; i++)\n            suff[k] += a12(k, i) * suff[i] * binom(n-k-1, i-k-1);\n    }\n \n    // Computing the result.\n    // Complexity O(n).\n    mint res = 0;\n    for (int i = 1; i <= n; i++) res += pref[i] * suff[i] * binom(n-1, i-1);\n    cout << res << \"\\n\";\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "divide and conquer",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1656",
    "index": "A",
    "title": "Good Pairs",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$ of positive integers. A good pair is a pair of indices $(i, j)$ with $1 \\leq i, j \\leq n$ such that, for all $1 \\leq k \\leq n$, the following equality holds:\n\n$$ |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, $$ where $|x|$ denotes the absolute value of $x$.\n\nFind a good pair. Note that $i$ can be equal to $j$.",
    "tutorial": "By the triangle inequality, for all real numbers $x, y, z$, we have: $|x-y| + |y-z| \\geq |x-z|$ with equality if and only if $\\min(x, z) \\leq y \\leq \\max(x, z)$. Now, take indices $i$ and $j$ such that $a_i$ and $a_j$ are the maximum and minimum values of the array, respectively. Then, for each index $k$, we have $a_i \\geq a_k \\geq a_j$, meaning that $|a_i - a_k| + |a_k - a_j| = a_i - a_k + a_k - a_j = a_i- a_j = |a_i - a_j|$, as we desired.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n\tint t;\n\tcin >> t;\n\twhile(t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tint minv = 1e9+1;\n\t\tint maxv = -1;\n\t\tint mini;\n\t\tint maxi;\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\tint a;\n\t\t\tcin >> a;\n\t\t\tif(a > maxv) {\n\t\t\t\tmaxi = i+1;\n\t\t\t\tmaxv = a;\n\t\t\t}\n\t\t\tif(a < minv) {\n\t\t\t\tmini = i+1;\n\t\t\t\tminv =  a;\n\t\t\t}\n\t\t}\n\t\tcout << mini << \" \" << maxi << endl;\n\t}\n \n}\n",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1656",
    "index": "B",
    "title": "Subtract Operation",
    "statement": "You are given a list of $n$ integers. You can perform the following operation: you choose an element $x$ from the list, erase $x$ from the list, and subtract the value of $x$ from all the remaining elements. Thus, in one operation, the length of the list is decreased by exactly $1$.\n\nGiven an integer $k$ ($k>0$), find if there is some sequence of $n-1$ operations such that, after applying the operations, the only remaining element of the list is equal to $k$.",
    "tutorial": "Note that, after deleting element $a_j$, all numbers in the set are of the form $a_i - a_j$, since the previous substractions are cancelled. Therefore, the final element will be the difference between the last element and the previous element which was erased. So we just need to check if $k$ is the difference of two elements in the set, which can be done by sorting and using the double pointer technique in $O(n \\log n)$ time.",
    "code": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    while(t--) {\n        int n, a;\n    \tcin >> n >> a;\n    \tvector<int> v(n);\n    \tfor(int& x : v) cin >> x;\n    \tbool ans = false;\n    \tif(n == 1) ans = (v[0] == a);\n    \telse {\n    \t\tsort(v.begin(), v.end());\n    \t\tint i = 0;\n    \t\tint j = 1;\n    \t\twhile(j < n and i < n) {\n    \t\t\tif(v[i] + abs(a) == v[j]) {\n    \t\t\t\tans = true;\n    \t\t\t\tbreak;\n    \t\t\t}\n    \t\t\telse if(v[i] + abs(a) < v[j]) ++i;\n    \t\t\telse ++j;\n    \t\t}\n    \t}\n    \tcout << (ans? \"YES\" : \"NO\") << '\\n';   \n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1656",
    "index": "C",
    "title": "Make Equal With Mod",
    "statement": "You are given an array of $n$ non-negative integers $a_1, a_2, \\ldots, a_n$. You can make the following operation: choose an integer $x \\geq 2$ and replace each number of the array by the remainder when dividing that number by $x$, that is, for all $1 \\leq i \\leq n$ set $a_i$ to $a_i \\bmod x$.\n\nDetermine if it is possible to make all the elements of the array equal by applying the operation zero or more times.",
    "tutorial": "Note that, if $1$ is not present in the array, we can always make all elements equal to $0$ by repeatedly applying the operation with $x = \\max(a_i)$ until all elements become $0$, as this operation will set the elements equal to the maximum to $0$, while maintaining the others intact. So the answer is YES. If $1$ is present and there are no two consecutive numbers in the array, we can similarly apply repeatedly the operation with $x = \\max(a_i) - 1$ until all elements become $1$, as this operation will set the elements equal to the maximum to $1$, while maintaining the others intact. So the answer is again YES. If $1$ is present in the array, and there are two consecutive numbers $m, m + 1$ in the array, the answer is NO. Note that if we have a $0$ and a $1$ in the array, we won't be able to make them equal after any number of operations, and so we cannot have any operation with an $x$ that divides one of the $a_i$'s. The rest of operations will cause that $m, m + 1$ remain consecutive (and thus different), meaning that it is impossible to make all the array equal.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \ntypedef vector<int> vi;\n \n \nint main() {\n\tint t;\n\tcin >> t;\n\twhile(t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvi a(n);\n\t\tfor(int i=0; i < n; ++i) cin >> a[i];\n\t\tsort(a.begin(), a.end());\n\t\tbool one = false;\n\t\tbool consec = false;\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\tif(a[i] == 1) one = true;\n\t\t\tif(i < n-1 && a[i]+1 == a[i+1]) consec = true;\n\t\t}\n \n\t\tcout << ((one && consec) ? \"NO\" : \"YES\") << endl;\n\t}\n \n}\n",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1656",
    "index": "D",
    "title": "K-good",
    "statement": "We say that a positive integer $n$ is $k$-good for some positive integer $k$ if $n$ can be expressed as a sum of $k$ positive integers which give $k$ distinct remainders when divided by $k$.\n\nGiven a positive integer $n$, find some $k \\geq 2$ so that $n$ is $k$-good or tell that such a $k$ does not exist.",
    "tutorial": "$n$ is $k$-good if and only if $n \\geq 1 + 2 + \\ldots + k = \\frac{k(k+1)}{2}$. $n \\equiv 1 + 2 + \\ldots + k \\equiv \\frac{k(k+1)}{2} \\pmod{k}$. It is clear that both conditions are necessary, and it turns out they're sufficient too since $\\frac{k(k+1)}{2} + m \\cdot k$ is attainable for any integer $m \\geq 0$ by repeatedly adding $k$ to one of the terms in the sum $1 + 2 + \\ldots + k$. Note that, if $k$ is even, the second condition is $n \\equiv \\frac{k}{2} \\pmod{k}$, which is true if and only if $2n$ is a multiple of $k$ but $n$ is not a multiple of $k$. So all $k$ which divide $2n$ but do not divide $n$ satisfy the second condition, and we want the smallest of them in order to have the best chance of satisfying the first condition. The smallest of such $k$ is $k_1 = 2^{\\nu_2(n)+1}$, i. e. the smallest power of $2$ that does not divide $n$. We can compute $k_1$ in $O(\\log n)$ (or in $O(1)$ with some architecture-specific functions) and check if it satisfies the first condition. If it doesn't, consider $k_2 = \\frac{2n}{k_1}$. Note that $k_2$ is odd, and therefore the second condition is satisfied since $k_2$ is a divisor of $n$. Since $k_1$ did not satisfy the condition, we have $k_1(k_1+1) > 2n \\implies k_2 < k_1+1 \\implies k_2 \\leq k_1-1$ (since $k_2$ is odd), so: $\\frac{k_2(k_2+1)}{2} \\leq \\frac{k_2 \\cdot k_1}{2} = n$ So $k_2$ satisfies the first condition. Note that $k_2$ is only a valid answer if $k_2 \\neq 1$. If $k_2 = 1$, then we have that $n$ is a power of $2$, and in this case there is no answer since all odd candidates of $k$ must be odd divisors of $n$, of which there is only $1$, and the smallest even candidate for $k$ was $k_1 = 2n$, which does not work. So we have to answer $-1$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \n#define endl '\\n'\n \ntypedef long long ll;\n \nint main() {\n    ios::sync_with_stdio(false);\n\tint T;\n\tcin >> T;\n\twhile(T--) {\n\t\tll n;\n\t\tcin >> n;\n\t\tll x = n;\n\t\twhile(x % 2 == 0) x /= 2;\n\t\tif(x == 1) {\n\t\t\tcout << -1 << endl;\n\t\t}\n\t\telse if(x <= 2e9 && (x*(x+1))/2 <= n) {\n\t\t\tcout << x << endl;\n\t\t}\n\t\telse {\n\t\t\tcout << 2*(n/x) << endl;\n\t\t}\n\t}\n}\n",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1656",
    "index": "E",
    "title": "Equal Tree Sums",
    "statement": "You are given an undirected unrooted tree, i.e. a connected undirected graph without cycles.\n\nYou must assign a \\textbf{nonzero} integer weight to each vertex so that the following is satisfied: if any vertex of the tree is removed, then each of the remaining connected components has the same sum of weights in its vertices.",
    "tutorial": "Bicolor the tree, and put $+\\text{deg}(v)$ in vertices of one color and $-\\text{deg}(v)$ in vertices of the other color. Consider removing one vertex $u$. In each subtree, for each edge not incident with $u$, $+1$ will be added for one of the endpoints and $-1$ for the other endpoint, so the total contribution is $0$. For the one edge in each subtree incident with $u$, the contribution will be $+1$ or $-1$ depending on the color of $u$. So the sums of the subtrees will all be equal to $+1$ or $-1$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\n \nvvi al;\nvi ans;\n \nvoid dfs(int u, int p, int c) {\n\tans[u] = ((int)al[u].size())*c;\n\tfor(int v : al[u]) {\n\t\tif(v != p) {\n\t\t\tdfs(v, u, -c);\n\t\t}\n\t}\n}\n \nint main() {\n\tint T;\n\tcin >> T;\n\twhile(T--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tal = vvi(n);\n\t\tfor(int i=0; i < n-1; ++i) {\n\t\t\tint u, v;\n\t\t\tcin >> u >> v;\n\t\t\tu--;\n\t\t\tv--;\n\t\t\tal[u].push_back(v);\n\t\t\tal[v].push_back(u);\n\t\t}\n\t\tans = vi(n);\n\t\tdfs(0, -1, 1);\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\tcout << ans[i];\n\t\t\tif(i < n-1) cout << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "math",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1656",
    "index": "F",
    "title": "Parametric MST",
    "statement": "You are given $n$ integers $a_1, a_2, \\ldots, a_n$. For any real number $t$, consider the complete weighted graph on $n$ vertices $K_n(t)$ with weight of the edge between vertices $i$ and $j$ equal to $w_{ij}(t) = a_i \\cdot a_j + t \\cdot (a_i + a_j)$.\n\nLet $f(t)$ be the cost of the minimum spanning tree of $K_n(t)$. Determine whether $f(t)$ is bounded above and, if so, output the maximum value it attains.",
    "tutorial": "Assume $a_1 \\leq \\ldots \\leq a_n$. We will try to connect each node $u$ to the neighbour $v$ that minimizes the cost function $c(u, v) = a_u a_v + t(a_u + a_v)$. If by doing this we obtain a tree which is connected, it will clearly be an MST. Let $b_i(t) = a_i + t$. We can rewrite $c(u, v)$ as $c(u, v) = b_u(t)b_v(t) - t^2$. So, if we fix $t$ and $u$, this value will be minimized if $v = n$ when $b_u(t) \\leq 0$ or $v = 1$ when $b_u(t) \\geq 0$. We have three cases: If there are positive and negative values of $b_i(t)$, connect all $i$ with $b_i(t) < 0$ to $v = n$, and connect the rest to $v = 1$. We see that we are adding $n - 1$ edges (since we are counting the edge $\\{1, n\\}$ twice), and that the resulting graph is connected since every node is connected to either $1$ or $n$. If all $b_i(t)$ are positive, connect all $u \\neq 1$ to $v = 1$; and if all are negative, connect all $u \\neq n$ to $v = n$. Now it is immediate to see that the MST will only change when some $b_i(t)$ changes its sign, that is, when $t = -a_k$ for some $k$, and that the total cost function will be piecewise affine. Furthermore, updating the total cost at each $t = -a_k$ can be done in $O(1)$ time if we process nodes from $1$ to $n$ and we mantain some cumulative sums. We are left with checking whether the MST total cost function goes to $+\\infty$ when $t \\to \\pm\\infty$, which can be done by computing the slope of the MST total cost function at the limiting values $t = -a_1$ and $t = -a_n$ (which can be computed by adding the slopes of the cost functions of the edges, the construction of which we have previously mentioned).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef vector<ll> vi;\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile(T--) {\n\t\tll n;\n\t\tcin >> n;\n\t\tvi a(n);\n\t\tll tsum = 0;\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\tcin >> a[i];\n\t\t\ttsum += a[i];\n\t\t}\n\t\tsort(a.begin(), a.end());\n\t\tif(a[n-1]*(n-2) + tsum < 0 || a[0]*(n-2) + tsum > 0) {\n\t\t\tcout << \"INF\" << endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tll cslope = a[n-1]*(n-2) + tsum;\n\t\tll cvalue = -(n-1)*a[n-1]*a[n-1];\n\t\t\n\n\t\tll ans = cvalue;\n\t\tfor(ll i=1; i < n; ++i) {\n\t\t\tll d = a[n-i]-a[n-i-1];\n\t\t\tcvalue += cslope*d;\n\t\t\tans = max(cvalue, ans);\n\n\t\t\tcslope += a[0]-a[n-1];\n\n\n\t\t}\n\t\tcout << ans << endl;\n\t}\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "graphs",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1656",
    "index": "G",
    "title": "Cycle Palindrome",
    "statement": "We say that a sequence of $n$ integers $a_1, a_2, \\ldots, a_n$ is a palindrome if for all $1 \\leq i \\leq n$, $a_i = a_{n-i+1}$. You are given a sequence of $n$ integers $a_1, a_2, \\ldots, a_n$ and you have to find, if it exists, a cycle permutation $\\sigma$ so that the sequence $a_{\\sigma(1)}, a_{\\sigma(2)}, \\ldots, a_{\\sigma(n)}$ is a palindrome.\n\nA permutation of $1, 2, \\ldots, n$ is a bijective function from $\\{1, 2, \\ldots, n\\}$ to $\\{1, 2, \\ldots, n\\}$. We say that a permutation $\\sigma$ is a cycle permutation if $1, \\sigma(1), \\sigma^2(1), \\ldots, \\sigma^{n-1}(1)$ are pairwise different numbers. Here $\\sigma^m(1)$ denotes $\\underbrace{\\sigma(\\sigma(\\ldots \\sigma}_{m \\text{ times}}(1) \\ldots))$.",
    "tutorial": "We clearly see that the following two conditions are necessary: Each number must be repeated an even number of time except possibly one of the numbers. (This is necessary to find any permutation that results in a palindrome, not just a cycle). If $n$ is odd, it can not be that the number $a_{(n+1)/2}$ appears only one time. (Otherwise, the permutation would need to have one fixed point). We will see that those two conditions are sufficient. First, let's focus on the $n$ even case. Find any permutation $\\sigma$ so that applying it results in a palindrome. This permutation will have a cycle decomposition. We are going to merge all those cycles in one big cycle. To do so, we will first merge the cycles so that indices $i$ and $n-i+1$ are in the same cycle for all $i$. Note that, since $a_{\\sigma(i)} = a_{\\sigma(n-i+1)}$ we can define a new permutation $\\sigma'$ with $\\sigma'(n-i+1) = \\sigma(i)$ and $\\sigma'(i) = \\sigma(n-i+1)$ and the permutation $\\sigma'$ will still generate a palindrome and $i$ and $n-i+1$ will be in the same cycle. We iterate over all the $i$s and merge all such cycles. Note that we need to keep track efficiently of which indices are in the same cycle, so we should use union-find data structure. Now we have $m$ disjoint cycles which are symmetric, that is $i$ and $n-i+1$ are in the same cycle. If $m = 1$ we've won. Otherwise, let $i_1, \\ldots, i_m$ be indices belonging to each of the cycles and let $\\sigma$ be our current permutation. Note that if we define $\\sigma'(i_j) = \\sigma(n-i_{j+1}+1)$ and $\\sigma'(n-i_j+1) = \\sigma(i_{j+1})$ for $j = 1, \\ldots, m-1$ and $\\sigma'(i_m) = \\sigma(i_1)$, $\\sigma'(n-i_m+1) = \\sigma(n-i_1+1)$, we have another permutation $\\sigma'$ which results in a palindrome and consists of only one cycle, so we're done. There are different ways of handling the case when $n$ is odd, the one that requires least casework for this solution is noticing that in the $n$ odd case we can still merge symmetric cycles with no issues, and that the only thing that could make the last step fail would be to choose some index $i_j$ so that $n-i_j+1 = i_j$. So we have to be careful not to choose $i_j = \\frac{n+1}{2}$, and in particular this means that the cycle that contains the middle element can not be a fixed point. If the second condition is satisfied, this can be achieved easily in the initial permutation we choose. Alternative solution: Notice that the above solution has $O(n \\alpha (n) )$ complexity because of union-find. Actually, a $O(n)$ complexity can be achieved, we describe briefly an alternative solution with that complexity. We focus on the case when $n$ is even. The idea is to start with a permutation whose cycles are already symmetric. In order to do so, we construct a graph whose vertices are the numbers that appear in the sequence and for each $1 \\leq i \\leq \\frac{n}{2}$ we add an edge between $a_i$ and $a_{n-i+1}$. Now note that for each of the connected components of the graph we can obtain a symmetric cycle resulting in a palindrome from an Eulerian tour of the graph.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\n\nvi obtain_p_permutation(const vi& a) {\n\tint n = a.size();\n\tvi pp(n, -1);\n\tvi p(n);\n\tint cp = 0;\n\tvi cnt(n);\n\tfor(int i=0; i < n; ++i) {\n\t\tcnt[a[i]]++;\n\t}\n\tfor(int i=0; i < n; ++i) {\n\t\tif(pp[a[i]] == -1) {\n\t\t\tif(cnt[a[i]] == 1) {\n\t\t\t\tp[i] = n/2;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tp[i] = cp;\n\t\t\t\tpp[a[i]] = n-cp-1;\n\t\t\t\tcp++;\n\t\t\t\tcnt[a[i]]--;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tp[i] = pp[a[i]];\n\t\t\tpp[a[i]] = -1;\n\t\t\tcnt[a[i]]--;\n\t\t}\n\t}\n\treturn p;\n}\n\nvvi find_cycles(vi p, vi& in_cyc) {\n\tint n = p.size();\n\tvi vis = vi(n);\n\tvvi cycles;\n\tfor(int i=0; i < n; ++i) {\n\t\tif(!vis[i]) {\n\t\t\tvi cyc;\n\t\t\tint v = i;\n\t\t\twhile(!vis[v]) {\n\t\t\t\tcyc.push_back(v);\n\t\t\t\tin_cyc[v] = cycles.size();\n\t\t\t\tvis[v] = true;\n\t\t\t\tv = p[v];\n\t\t\t}\n\t\t\tcycles.push_back(cyc);\n\t\t}\n\t}\n\treturn cycles;\n}\n\nint find_set(vi& dsu, int x) {\n\tif(dsu[x] == x) return x;\n\treturn dsu[x] = find_set(dsu, dsu[x]);\n}\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvi a(n);\n\tvi cnt(n);\n\tfor(int i=0; i < n; ++i) {\n\t\tcin >> a[i];\n\t\ta[i]--;\n\t\tcnt[a[i]]++;\n\t}\n\tint odd_i = -1;\n\tfor(int i=0; i < n; ++i) {\n\t\tif(cnt[i]%2 == 1) {\n\t\t\tif(odd_i == -1) {\n\t\t\t\todd_i = i;\n\t\t\t}\n\t\t\telse {\n\t\t\t\todd_i = -2;\n\t\t\t}\n\t\t}\n\t}\n\tif(odd_i == -2) {\n\t\tcout << \"NO\" << endl;\n\t}\n\telse if(odd_i != -1 && (cnt[odd_i] == 1 && odd_i == a[n/2])) {\n\t\tcout << \"NO\" << endl;\n\t}\n\telse {\n\n\t\tvi p = obtain_p_permutation(a);\n\t\tif(odd_i != -1 && p[n/2] == n/2) {\n\t\t\tfor(int i=0; i < n; ++i) {\n\t\t\t\tif(i != n/2 && a[i] == odd_i) {\n\t\t\t\t\tp[n/2] = p[i];\n\t\t\t\t\tp[i] = n/2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvi rp(n);\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\trp[p[i]] = i;\n\t\t}\n\t\tvvi cycles;\n\t\tvi in_cyc(n);\n\t\tcycles = find_cycles(p, in_cyc);\n\n\n\t\tvi dsu(n);\n\t\tfor(int i=0; i < n; ++i) dsu[i] = i;\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\tif(find_set(dsu, in_cyc[i]) != find_set(dsu, in_cyc[n-i-1])) {\n\t\t\t\tdsu[find_set(dsu, in_cyc[i])] = find_set(dsu, in_cyc[n-i-1]);\n\t\t\t\tint j1 = rp[i];\n\t\t\t\tint j2 = rp[n-i-1];\n\t\t\t\tp[j2] = i;\n\t\t\t\trp[i] = j2;\n\t\t\t\tp[j1] = n-i-1;\n\t\t\t\trp[n-i-1] = j1;  \n\t\t\t}\n\t\t}\n\t\tcycles = find_cycles(p, in_cyc);\n\t\tint nc = cycles.size();\n\t\n\n\t\tvi prev_p = vi(p);\n\t\tvi prev_rp = vi(rp);\n\n\t\tfor(int i=0; i < nc-1; ++i) {\n\t\t\tint i0 = cycles[i][0];\n\t\t\tint ip1 = cycles[(i+1)][0];\n\t\t\tp[prev_rp[n-i0-1]] = ip1;\n\t\t\trp[ip1] = prev_rp[n-i0-1]; \n\t\t}\n\t\tp[prev_rp[n-cycles[nc-1][0]-1]] = n-cycles[0][0]-1;\n\t\trp[n-cycles[0][0]-1] = prev_rp[n-cycles[nc-1][0]-1];\n\t\tfor(int i=0; i < nc-1; ++i) {\n\t\t\tint i0 = cycles[i][0];\n\t\t\tint ip1 = cycles[(i+1)][0];\n\t\t\tp[prev_rp[i0]] = n-ip1-1;\n\t\t\trp[n-ip1-1] = prev_rp[i0];\n\t\t}\n\t\tp[prev_rp[cycles[nc-1][0]]] = cycles[0][0];\n\t\trp[cycles[0][0]] = prev_rp[cycles[nc-1][0]];\n\n\t\tcout << \"YES\" << endl;\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\tcout << rp[i]+1 << \" \";\n\t\t}\n\t\tcout << endl;\n\n\t}\n\t\n\n\n}\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile(T--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1656",
    "index": "H",
    "title": "Equal LCM Subsets",
    "statement": "You are given two sets of positive integers $A$ and $B$. You have to find two non-empty subsets $S_A \\subseteq A$, $S_B \\subseteq B$ so that the least common multiple (LCM) of the elements of $S_A$ is equal to the least common multiple (LCM) of the elements of $S_B$.",
    "tutorial": "First, we see how to check if the two entire sets have the same LCM (without subsets). To do this, for each element $a \\in A$ let us compute $f(a, B) = \\gcd(a/\\gcd(a, b_1), \\ldots, a/\\gcd(a, b_n))$ If $f(a, B) > 1$, we can simply delete $a$ from $A$ and solve recursively using the remaining sets (similarly if $f(b, A) > 1$). We need to update the values $f(a, B)$ and $f(b, A)$ efficiently. We can do it using many segment tree (one for each $a \\in A$, and one for each $b \\in B$). The segment tree of $a \\in A$, $ST_a$, will have the elements of $B$ as its leaves, and the node $u$ of $ST_a$, which will include a range $[i, j]$ of elements of $B$ will be $\\gcd(a/\\gcd(a, b_i), \\ldots, a/\\gcd(a, b_j))$, meaning that after removing an element of $B$, we will need to recompute all of the $n$ segment trees in $\\mathcal O(\\log n + U)$ time each (it is $\\mathcal O(\\log n + U)$ and not $\\mathcal O(\\log n \\cdot U)$ by a similar argument to the one used to compute the complexity of computing the gcd of an array of numbers) . Since we have to repeat this for $O(n)$ steps, the total time complexity will be $\\mathcal O(n^2 \\cdot (\\log n + U))$ and the memory complexity is $\\mathcal O(n^2)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \ntypedef __int128 ll; \ntypedef vector<ll> vi;\ntypedef vector<vi> vvi;\n \n \nll read_ll() {\n\tstring s;\n\tcin >> s;\n\tll x = 0;\n\tfor(int i=0; i < (int)s.length(); ++i) {\n\t\tx *= 10;\n\t\tx += ll(s[i]-'0');\n\t}\n\treturn x;\n}\n \nvoid print_ll(ll x) {\n\tvector<int> p;\n\twhile(x > 0) {\n\t\tp.push_back((int)(x%10));\n\t\tx /= 10;\n\t}\n\treverse(p.begin(), p.end());\n\tfor(int y : p) cout << y;\n}\n \ninline ll ctz(ll x) {\n\tlong long a = x&((ll(1)<<ll(63))-ll(1));\n\tlong long b = x>>ll(63);\n\tif(a == 0) return ll(63)+__builtin_ctzll(b);\n\treturn __builtin_ctzll(a);  \n}\n \ninline ll abll(ll x) {\n\treturn x >= 0 ? x : -x;\n}\n \nll gcd(ll a, ll b) {\n\tif(b == 0) return a;\n\tif(a == 0) return b;\n \n\tint az = ctz(a);\n\tint bz = ctz(b);\n\tint shift = min(az, bz);\n\tb >>= bz;\n \n\twhile(a != 0) {\n\t\ta >>= az;\n\t\tll diff = b-a;\n\t\tif(diff) az = ctz(diff);\n\t\tb = min(a, b);\n\t\ta = abll(diff);\n\t}\n\treturn b << shift;\n}\n \nvoid init_st(vi& st, const vi& v) {\n\tint n = v.size();\n\tfor(int i=0; i < n; ++i) {\n\t\tst[n+i] = v[i];\n\t}\n\tfor(int i=n-1; i >= 1; --i) {\n\t\tst[i] = gcd(st[2*i], st[2*i+1]);\n\t}\n}\n\nvoid update_st(vi& st, int i, ll x) {\n\tint n = (int)st.size() / 2;\n\tint pos = n+i;\n\tst[pos] = x;\n\twhile(pos > 1) {\n\t\tpos /= 2;\n\t\tst[pos] = gcd(st[2*pos], st[2*pos+1]);\n\t}\n}\n \nvoid solve(const vi& a, const vi& b, vector<bool>& ai, vector<bool>& bi) {\n\tint n = a.size();\n\tint m = b.size();\n\tvvi st_a = vvi(n, vi(2*m, 0));\n\tvvi st_b = vvi(m, vi(2*n, 0));\n\tfor(int i=0; i < n; ++i) {\n\t\tvi af(m);\n\t\tfor(int j=0; j < m; ++j) {\n\t\t\taf[j] = a[i]/gcd(a[i], b[j]);\n\t\t}\n\t\tinit_st(st_a[i], af);\n\t}\n\tfor(int i=0; i < m; ++i) {\n\t\tvi bf(n);\n\t\tfor(int j=0; j < n; ++j) {\n\t\t\tbf[j] = b[i]/gcd(b[i], a[j]);\n\t\t}\n\t\tinit_st(st_b[i], bf);\n\t}\n\tqueue<int> dq;\n\tfor(int i=0; i < n; ++i) {\n\t\tif(st_a[i][1] > 1) {\n\t\t       \tdq.push(i);\n\t\t\tai[i] = false;\n\t\t}\n\t}\n\tfor(int i=0; i < m; ++i) {\n\t\tif(st_b[i][1] > 1) {\n\t\t       \tdq.push(n+i);\n\t\t\tbi[i] = false;\n\t\t}\n\t}\n\twhile(!dq.empty()) {\n\t\tint idx = dq.front();\n\t\tdq.pop();\n\t\tif(idx < n) {\n\t\t\tint i = idx;\n\t\t\tfor(int j=0; j < m; ++j) {\n\t\t\t\tif(bi[j]) {\n\t\t\t\t\tupdate_st(st_b[j], i, b[j]);\n\t\t\t\t\tif(st_b[j][1] > 1) {\n\t\t\t\t\t\tdq.push(n+j);\n\t\t\t\t\t\tbi[j] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tint i = idx-n;\n\t\t\tfor(int j=0; j < n; ++j) {\n\t\t\t\tif(ai[j]) {\n\t\t\t\t\tupdate_st(st_a[j], i, a[j]);\n\t\t\t\t\tif(st_a[j][1] > 1) { \n\t\t\t\t\t\tdq.push(j);\n\t\t\t\t\t\tai[j] = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\t\n \n}\n \n \n \nint main() {\n\tint T;\n\tcin >> T;\n\twhile(T--) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tvi a(n);\n\t\tvi b(m);\n\t\tfor(int i=0; i < n; ++i) a[i] = read_ll();\n\t\tfor(int i=0; i < m; ++i) b[i] = read_ll();\n\t\tvector<bool> ai(n, true);\n\t\tvector<bool> bi(m, true);\n\t\tsolve(a, b, ai, bi);\n\t\tint as = 0;\n\t\tint bs = 0;\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\tif(ai[i]) as++;\n\t\t}\n\t\tfor(int i=0; i < m; ++i) {\n\t\t\tif(bi[i]) bs++;\n\t\t}\n\t\tif(as == 0 || bs == 0) cout << \"NO\" << endl;\n\t\telse {\n\t\t\tcout << \"YES\" << endl;\n\t\t\tcout << as << \" \" << bs << endl;\n\t\t\tfor(int i=0; i < n; ++i) {\n\t\t\t\tif(ai[i]) {\n\t\t\t\t\tprint_ll(a[i]);\n\t\t\t\t\tcout << \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\tfor(int i=0; i < m; ++i) {\n\t\t\t\tif(bi[i]) {\n\t\t\t\t\tprint_ll(b[i]);\n\t\t\t\t\tcout << \" \";\n\t\t\t\t}\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\t\n \n\t\t}\n\t}\n}\n",
    "tags": [
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1656",
    "index": "I",
    "title": "Neighbour Ordering",
    "statement": "Given an undirected graph $G$, we say that a neighbour ordering is an ordered list of all the neighbours of a vertex for each of the vertices of $G$. Consider a given neighbour ordering of $G$ and three vertices $u$, $v$ and $w$, such that $v$ is a neighbor of $u$ and $w$. We write $u <_{v} w$ if $u$ comes after $w$ in $v$'s neighbor list.\n\nA neighbour ordering is said to be good if, for each simple cycle $v_1, v_2, \\ldots, v_c$ of the graph, one of the following is satisfied:\n\n- $v_1 <_{v_2} v_3, v_2 <_{v_3} v_4, \\ldots, v_{c-2} <_{v_{c-1}} v_c, v_{c-1} <_{v_c} v_1, v_c <_{v_1} v_2$.\n- $v_1 >_{v_2} v_3, v_2 >_{v_3} v_4, \\ldots, v_{c-2} >_{v_{c-1}} v_c, v_{c-1} >_{v_c} v_1, v_c >_{v_1} v_2$.\n\nGiven a graph $G$, determine whether there exists a good neighbour ordering for it and construct one if it does.",
    "tutorial": "First, note that, for each vertex $v$, the relative order between neighbours that belong to different biconnected components (i. e., neighbours $u$ and $w$ so that the edges $vu$ and $vw$ belong to different biconnected components) is irrelevant, since there can not be any (vertex-disjoint) cycle using edges from different biconnected components. Therefore, a good ordering for the entire graph will be possible if and only if a good ordering for each of the biconnected components is possible, and if so the ordering for the entire graph can be obtained from the orderings for each of the components by arbitrarily merging the lists of each component for each vertex (preserving the relative order for the lists of each component). Therefore, from now on we will assume that the graph is biconnected. Also, we assume that the graph has at least 3 vertices to avoid trivialities. Lemma 1: If the graph $G$ has a cycle $\\mathcal{C}$, and there are two vertices $u, v \\in \\mathcal{C}$ not adjacent in the cycle such that there is a path from $u$ to $v$ that passes through a vertex $w \\not\\in \\mathcal{C}$, then the graph $G$ can not have a good ordering. Proof: Assume the graph has a good ordering, and label the vertices of the cycle $v_1, v_2, \\ldots, v_n$ so that $v_i \\leq_{v_{i+1}} v_{i+2}$ and $u = v_1$ and $v = v_j$ with $j \\neq 1, 2, n$. Let the path between $v_j$ and $v_1$ be $v_j, w_1, \\ldots, w_p$, where $w_p = v_1$, $p > 1$, and we can assume that all $w_i$ lie outside the cycle. Considering the cycle $v_1, v_2, \\ldots, v_j, w_1, \\ldots$, we can see that since $v_1 \\leq_{v_2} v_3$, it must happen too that $v_j \\leq_{w_1} w_2$. Now, considering the cycle $w_p, \\ldots, w_1, v_j, v_{j+1}, \\ldots, v_n$, we see that since $v_j \\leq_{v_{j+1}} v_{j+2}$ (with possibly $v_{j+2} = v_1$), we must have $w_2 \\leq_{w_1} v_j$. Since $w_2 \\neq v_j$, we can't have the inequality both ways and we reach a contradiction. $\\square$ Theorem: If the (biconnected) graph $G$ has a good ordering, then it has a hamiltonian cycle. Proof: Assume it doesn't have a hamiltonian cycle. Since it is biconnected with at least 3 vertices, it must have some cycle. Let $v_1, \\ldots, v_c$ be a longest cycle of the graph. Because the cycle does not visit all the vertices of the graph and the graph is connected, there must be some vertex $u$ not in the cycle which is a neighbour of a vertex $v_i$ in the cycle. Because the graph is biconnected, there must be some path $w_1, \\ldots, w_d$ not passing through $v_i$ with $w_1 = u$ and $w_d = v_j$, a vertex in the cycle. We can choose the path so that vertices $w_1, \\ldots, w_{d-1}$ are not in the cycle, since we can just finish the path at the first vertex that is in the cycle. Now we consider two cases: Case 1: $v_i$ and $v_j$ are adjacent in the cycle (i. e. $j = i+1$ or $j = i-1$, where we admit taking indices modulo $c$). Now we can consider the cycle $v_1, \\ldots, v_i, w_1, \\ldots, w_{d-1}, v_j, \\ldots, v_c$, which is strictly longer than the original cycle, but we said it was a longest cycle, contradiction. Case 2: $v_i$ and $v_j$ are not adjacent in the cycle. Assume $i < j$ and consider the cycle $v_1, \\ldots, v_i, w_1, \\ldots, w_{d-1}, v_j, \\ldots, v_c$. We have a path $v_i, v_{i+1}, \\ldots, v_j$ that passes through vertices not in the cycle, so by the first lemma it is not possible to have a good ordering, contradiction. Now, let's see how we can compute this hamiltonian cycle efficiently. The argument we used in the proof already gives a good algorithm: we find a cycle, and repeatedly find paths that go out of the cycle and then return to it. We will either find a path which returns to an adjacent vertex and therefore we can use it to augment the cycle (Case 1) or we will find that it is impossible to have a good ordering and halt (Case 2). However, implementing this directly is in worst case $O(n^2)$. We will find a way to implement this idea in $O(n)$ time, using properties of the DFS tree. Lemma 2: In a DFS tree of a (biconnected) graph $G$ with a good ordering, each vertex can have at most two children. Proof: Suppose that some vertex $u$ has more than two children. Because the graph is biconnected, we have $u$ can not be the root, and that from each of the child subtrees there is a back edge to a proper ancestor of $u$. Let $v_1,v_2, v_3$ be three children of $u$ that have back edges (in their respective subtrees) to three vertices $w_1, w_2, w_3$ with $\\text{depth}(w_1) \\leq \\text{depth}(w_2) \\leq \\text{depth}(w_3)$, where $\\text{depth}$ is the depth in the DFS tree. Consider the cycle $v_1, u, v_2, \\ldots, w_2, \\ldots, w_1, \\ldots$ (goes back to $v_1$) and the path $w_2, \\ldots, w_3, \\ldots, v_3, u$ between $w_2$ and $u$, two non-adjacent vertices in the cycle. This contradicts lemma 1. $\\square$ Lemma 3: In a DFS tree of a (biconnected) graph $G$ with a good ordering, consider a vertex $u$ that is not the root and whose parent $v$ is not the root either with two children $u_1$ and $u_2$, and let $\\text{Low}(u_i)$ be the vertex with least depth that can be reached with a back edge from the subtree of $u_i$. Then there is exactly one $i$ such that $\\text{Low}(u_i) = v$ Proof: Assume that $\\text{Low}(u_1)$ and $\\text{Low}(u_2)$ are both proper ancestors of $v$ (they can not be descendants of $v$ since the graph is biconnected). Then, if we consider the cycle which includes the path $u_1, u, u_2$ and then cycles back using back edges without passing through $v$, we have a contradiction with lemma 1 considering the path from some vertex in the cycle which is a proper ancestor of $v$ to $u$ going down the DFS tree. Therefore, at least one of $\\text{Low}(u_1)$ or $\\text{Low}(u_2)$ is equal to $v$. Now let's see that it can not happen that $\\text{Low}(u_1) = \\text{Low}(u_2) = v$. Assume that it is the case. Since the graph is biconnected, we must have that $\\text{Low}(u) \\neq v$ since it must be a proper ancestor of $v$ (note that here we are using that $v$ is not the root). Therefore, since the two children subtrees don't have back edges to vertices higher than $v$, $u$ must have a back edge to $\\text{Low}(u)$. Consider the cycle $u, u_1, \\ldots, v, \\text{parent(v)}, \\ldots, \\text{Low(u)}$. Now with the path $u, u_2, \\ldots, v$ lemma 1 is violated. $\\square$ Lemma 4: In a DFS tree of a (biconnected) graph $G$ with a good ordering, consider a vertex $u$ that is not the root with parent $v$ and with only one child $u_1$. If $\\text{Low}(u_1) \\neq \\text{Low}(u)$, then $\\text{Low}(u_1) = v$. Proof: Consider the cycle $u, u_1, \\ldots, \\text{Low}(u_1), \\ldots$. If $u_1$ and $\\text{Low}(u_1)$ are not adjacent, the path $u, \\text{Low}(u), \\ldots, \\text{Low}(u_1)$ violates lemma 1. $\\square$ Theorem: In a DFS tree of a (biconnected) graph $G$ with a good ordering, we can partition the front edges into: One path of the form $u_1, \\ldots, u_p$, where $u_{i+1}$ is the parent of $u_i$ for $1 \\leq i < p$, and $u_p$ is the root, and there is a back edge between $u_1$ and $u_p$. Some paths of the form $u_1, \\ldots, u_p$, where $u_{i+1}$ is the parent of $u_i$ for $1 \\leq i < p$, and there is a back edge between $u_1$ and the parent of $u_p$. Proof: Let $u$ be a vertex which is not the root. We say that the representative back edge associated with vertex $u$ is the back edge from $u$'s subtree that goes to $\\text{Low}(u)$: if there are multiple such back edges, we choose the one that has as the other vertex the one that has a highest DFS visitation number. We partition the front edges $(u, \\text{parent}(u))$ into groups with the same representative edge associated with $u$. We have to prove that this partition has the desired properties. Let $u, v$ be vertices with the same representative edge. One vertex must be an ancestor of the other (otherwise their subtrees would be disjoint and they can not have the same back edges), and every vertex in the path going from one to the other in the tree has the same representative edge (if there was some better edge, the higher vertex would have it as a representative). This proves that the groups form paths of the form $u_1, \\ldots, u_p$, where $u_{i+1}$ is the parent of $u_i$ for $1 \\leq i < p$ (note that here $u_1, \\ldots, u_{p-1}$ would be the vertices with the same representative edge but $u_p$ wouldn't; $u_p$ is in the path because the partition is of edges, not vertices, and $(u_{p-1}, \\text{parent}(u_{p-1}))$ is an edge in the group). Now, let's see the other property. It is clear that $u_1$, the vertex with most depth of the path, has the representative edge of the path as one of its back edges. Now consider $u_p$. We have multiple cases: $u_p$ is not the root and it has only one child $u_{p-1}$. Then since it doesn't have the same representative edge necessarily it must have a back edge and $\\text{Low}(u_p) \\neq \\text{Low}(u_{p-1})$. By lemma 4, we must have $\\text{Low}(u_{p-1}) = \\text{parent}(u_{p})$ and the back edge from $u_1$ goes to the parent of $u_p$, as desired. $u_p$ is not the root, its parent is not the root either, and it has two children, one of which is $u_{p-1}$. Then by lemma 3, exactly one of the two children has its Low value equal to the parent of $u_p$. If it were not $u_{p-1}$, then $u_p$ would have the same representative edge as $u_{p-1}$, which is not possible since it is the endpoint of the path. Therefore again we have $\\text{Low}(u_{p-1}) = \\text{parent}(u_{p})$, and the back edge from $u_1$ goes to the parent of $u_p$. $u_p$ is the child of the root and it has two children. Now we must have once again $\\text{Low}(u_{p-1}) = \\text{parent}(u_{p})$ once again because there is no other vertex with least depth than the parent of $u_p$, and the back from $u_1$ goes to the parent of $u_p$. $u_p$ is the root. This happens for only for one path, and clearly there must be a back edge from $u_1$ to $u_p$. This is just what we wanted: doing just one DFS we can get one initial cycle and a series of paths we can use to successively augment our cycle until we have a hamiltonian cycle. One way to implement this is the following: first, we partition the graph into paths as in the previous theorem (we can mantain the representative back edge during the DFS; if a violation of the properties proven in the lemmas is detected, we halt). Then, we begin exploring the initial path (the one that forms a cycle with the root) in a downwards direction that is, first we visit $u_p$, then its child $u_{p-1}$, until we visit $u_1$, which has a edge back to $u_p$. When we visit one vertex, we push it into a vector that will contain the hamiltonian cycle at the end. If at some point we visit a vertex that is the parent of the endpoint of another path, we recursively visit that path and after visiting it we continue with our original path. But when recursively visiting the new path, we traverse it upwards, that is, we start with $u_1$ and go up to the parent of the vertex. If at some point we visit the endpoint of some other path, we again do a recursive visit of that path, this time in downwards direction. This way, we end up visiting all paths in a DFS-like way, and since we alternate between upward and downward traversals we end up having all the vertices of the graph in the vector ordered in a way that they form a hamiltonian cycle. Now that we have found how to compute that hamiltonian cycle in linear time (or halt if we find that some of the necessary conditions for a good ordering are violated), let's see an additional necessary condition for a good ordering. Theorem: In a (biconnected) graph $G$ with a good ordering, for any hamiltonian cycle, then there can not be any pair of edges that \"cross\", that is, if we draw the graph with vertices placed in a circle in the hamiltonian cycle order and with non-cycle edges drawn as chords, no two chords intersect. Proof: Assume that two edges cross. We can label the vertices $v_1, \\ldots, v_n$ so that $v_1, \\ldots, v_n$ forms the hamiltonian cycle in that order, $v_{k} \\leq_{v_{k+1}} v_{k+2}$ and the endpoints of the chords are $v_1, v_i$ and $v_p, v_q$, with $1 < p < i < q \\leq n$. Consider the cycle $v_1, v_2, \\ldots, v_p, v_q, v_{j+1}, \\ldots$. Because of the orientation of the hamiltonian cycle (note that there are at least three consecutive vertices from the hamiltonian cycle in this cycle) we have that $v_{p-1} \\leq_{v_p} v_q$. Similarly for the cycle $v_1, v_i, v_{i+1}, \\ldots, v_n$, we see that $v_1 \\leq_{v_i} v_{i+1}$. But now consider the cycle $v_1, v_i, v_{i+1}, \\ldots, v_q, v_p, v_{p-1}, \\ldots$. Because $v_1 \\leq_{v_i} v_{i+1}$, we must also have $v_{q} \\leq_{v_p} v_{p-1}$, contradiction. $\\square$ Once we have found the hamiltonian cycle, this property can be checked in linear time. And now the properties we have checked are not only necessary but also sufficient: Theorem: A biconnected graph $G$ with a hamiltonian cycle $v_1, \\ldots, v_n$ such that non-cycle edges do not cross admits a good ordering. Proof: We assign an ordering by choosing one orientation of the cycle, and ordering the edges of each vertex by how far is the endpoint of the edge traversing the cycle in that orientation. We have to prove that this is a good ordering. Let $v_{i_1}, v_{i_2}, \\ldots, v_{i_c}$ be any cycle, and label the vertices $v_1, \\ldots, v_n$ so that $i_1 = 1$ and $v_{i_1} \\leq_{v_{i_2}} v_{i_3}$ according to the orientation. If we show that $i_1 < \\ldots < i_c$, we will have shown that the cycle is consistent with the ordering. We already have $i_1 < i_2 < i_3$ by the labelling choice. Note that is $i_{k} < i_{k-1}$ is the first index to break the inequality, then if $1 < i_{k} < i_{k-2}$ the edge between $i_{k-1}$ and $i_k$ crosses some previous edge, and if $i_{k-2} < i_k$, then the cycle from then onwards be contained in the interval between vertices $v_{i_{k-2}}$ and $v_{i_{k-1}}$, which is not possible since vertex $v_1$ lies outside. $\\square$ This ordering can be reconstructed in time $O(m \\log m)$ by applying any standard sorting algorithm to the adjacency lists of the vertices (the comparison function is different for each vertex), and it can be improved to linear time by making an array of pairs consisting on the information of all the adjacency lists (each edge is included two times in the array, one for each end), sorting the array in linear time using counting sort, and then for each of the vertices the sorted adjacency list can be restored by applying one splice operation to the list given in the order in which the array was sorted.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef pair<int, int> ii;\ntypedef vector<ii> vii;\ntypedef vector<vii> vvii;\n\nstruct graph {\n\tint n;\n\tint m;\n\n\tvvi al;\n\tvi morphism;\n\n\tvvi dfs_children;\n\tvi dfs_parent;\n\tvi dfs_num;\n\tvi dfs_low;\n\tint dfs_count;\n\n\tbool is_root_ac = false;\n\n\tbool bad_biccon = false;\n\tvii repr_edge;\n\n\tvoid dt_dfs(int v, int par) {\n\t\tdfs_parent[v] = par;\n\t\tdfs_num[v] = dfs_low[v] = dfs_count++;\n\t\tfor(int u : al[v]) {\n\t\t\tif(u == par) {\n\t\t\t\t//Nothing\n\t\t\t}\n\t\t\telse if(dfs_num[u] == -1) {\n\t\t\t\tdfs_children[v].push_back(u);\n\t\t\t\tdt_dfs(u, v);\n\t\t\t\tdfs_low[v] = min(dfs_low[v], dfs_low[u]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdfs_low[v] = min(dfs_low[v], dfs_num[u]);\n\t\t\t}\n\t\t}\n\t}\n\n\tii min_repr_edge(ii a, ii b) {\n\t\tif(a.first == -1) return b;\n\t\tif(b.first == -1) return a;\n\t\tif(dfs_num[a.second] < dfs_num[b.second]) return a;\n\t\tif(dfs_num[a.second] > dfs_num[b.second]) return b;\n\t\tif(dfs_num[a.first] > dfs_num[b.first]) return a;\n\t\tif(dfs_num[a.first] < dfs_num[b.first]) return b;\n\t\treturn a;\n\t}\n\n\tvoid dt_dfs_hamil(int v) {\n\t\trepr_edge[v] = ii(-1, -1);\n\n\t\tfor(int u : dfs_children[v]) {\n\t\t\tdt_dfs_hamil(u);\n\t\t\trepr_edge[v] = min_repr_edge(repr_edge[v], repr_edge[u]);\n\t\t}\n\n\t\tfor(int u : al[v]) {\n\t\t\tif(u == dfs_parent[v]) {\n\t\t\t\t//Nothing\n\t\t\t}\n\t\t\telse if(dfs_num[u] < dfs_num[v]) {\n\t\t\t\trepr_edge[v] = min_repr_edge(repr_edge[v], ii(v, u));\n\t\t\t}\n\n\t\t}\n\n\t\tif(dfs_parent[v] == -1) {\n\t\t\t//Root case\n\t\t\t\n\t\t\t//Nothing more to check, repr_edge will always be set correctly.\n\t\t}\n\t\telse {\n\t\t\tif(dfs_children[v].size() == 0) {\n\t\t\t\t//Nothing to check\n\t\t\t}\n\t\t\telse if(dfs_children[v].size() == 1) {\n\t\t\t\t//Lemma 4\n\t\t\t\tif(dfs_low[dfs_children[v][0]] != dfs_low[v] && dfs_low[dfs_children[v][0]] != dfs_num[dfs_parent[v]]) {\n\t\t\t\t\tbad_biccon = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(dfs_children[v].size() == 2) {\n\t\t\t\t//Lemma 3\n\t\t\t\tif(dfs_parent[dfs_parent[v]] != -1) {\n\t\t\t\t\tif(!((dfs_low[dfs_children[v][0]] == dfs_num[dfs_parent[v]]) ^ (dfs_low[dfs_children[v][1]] == dfs_num[dfs_parent[v]]))) {\n\t\t\t\t\t\tbad_biccon = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(dfs_low[v] < min(dfs_low[dfs_children[v][0]], dfs_low[dfs_children[v][1]])) {\n\t\t\t\t\tbad_biccon = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbad_biccon = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid dt_dfs_cedges(vvii& cedges, vii& edge_stack, int v, int par) {\n\t\tdfs_parent[v] = par;\n\t\tdfs_num[v] = dfs_low[v] = dfs_count++;\n\t\tfor(int u : al[v]) {\n\t\t\tif(u == par) {\n\t\t\t\t//Nothing\n\t\t\t}\n\t\t\telse if(dfs_num[u] == -1) {\n\t\t\t\tdfs_children[v].push_back(u);\n\t\t\t\tedge_stack.emplace_back(v, u);\n\t\t\t\tdt_dfs_cedges(cedges, edge_stack, u, v);\n\t\t\t\tdfs_low[v] = min(dfs_low[v], dfs_low[u]);\n\n\t\t\t\tif((par == -1 && is_root_ac) || (par != -1 && dfs_low[u] >= dfs_num[v])) {\n\t\t\t\t\tvii comp;\n\t\t\t\t\twhile(edge_stack.back().first != v || edge_stack.back().second != u) {\n\t\t\t\t\t\tcomp.push_back(edge_stack.back());\n\t\t\t\t\t\tedge_stack.pop_back();\n\t\t\t\t\t}\n\t\t\t\t\tcomp.push_back(edge_stack.back());\n\t\t\t\t\tedge_stack.pop_back();\n\t\t\t\t\tcedges.push_back(comp);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdfs_low[v] = min(dfs_low[v], dfs_num[u]);\n\t\t\t\tif(dfs_num[u] < dfs_num[v]) {\n\t\t\t\t\tedge_stack.emplace_back(v, u);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid generate_dfs_tree(int root) {\n\t\tdfs_children = vvi(n, vi());\n\t\tdfs_parent = vi(n);\n\t\tdfs_count = 0;\n\t\tdfs_num = vi(n, -1);\n\t\tdfs_low = vi(n, -1);\n\t\tdt_dfs(root, -1);\n\t}\n\n\tvoid generate_edge_partition(vvii& cedges, vii& edge_stack, int root) {\n\t\tgenerate_dfs_tree(root);\n\t\tis_root_ac = (dfs_children[root].size() > 1);\n\n\t\tdfs_children = vvi(n, vi());\n\t\tdfs_parent = vi(n);\n\t\tdfs_count = 0;\n\t\tdfs_num = vi(n, -1);\n\t\tdfs_low = vi(n, -1);\n\t\tdt_dfs_cedges(cedges, edge_stack, root, -1);\n\t\tif(!edge_stack.empty()) cedges.push_back(edge_stack);\n\t}\n\n\tvoid generate_hamil_dfs_tree(int root) {\n\t\tgenerate_dfs_tree(root);\n\t\trepr_edge = vii(n, ii());\n\t\tdt_dfs_hamil(root);\n\t}\n};\n\nvector<graph> partition_biconnected(graph& g) {\n\tvvii cedges;\n\tvii edge_stack;\n\tg.generate_edge_partition(cedges, edge_stack, 0);\n\tvector<graph> comp;\n\tfor(vii& vec : cedges) {\n\t\tgraph h;\n\t\th.n = 0;\n\t\th.m = vec.size();\n\t\tunordered_map<int, int> rmorph;\n\t\tfor(ii e : vec) {\n\t\t\tif(rmorph.find(e.first) == rmorph.end()) {\n\t\t\t\trmorph[e.first] = h.n++;\n\t\t\t}\n\t\t\tif(rmorph.find(e.second) == rmorph.end()) {\n\t\t\t\trmorph[e.second] = h.n++;\n\t\t\t}\n\t\t}\n\t\th.morphism = vi(h.n);\n\t\th.al = vvi(h.n);\n\t\tfor(ii e : vec) {\n\t\t\tint u = rmorph[e.first];\n\t\t\tint v = rmorph[e.second];\n\t\t\th.morphism[u] = g.morphism[e.first];\n\t\t\th.morphism[v] = g.morphism[e.second];\n\t\t\th.al[u].push_back(v);\n\t\t\th.al[v].push_back(u);\n\t\t}\n\t\tcomp.push_back(h);\n\t}\n\treturn comp;\n}\n\nvoid upwards_path(graph& g, vi& hc, int v, int tar);\n\nvoid downwards_path(graph& g, vi& hc, int v, int tar);\n\nvoid upwards_path(graph& g, vi& hc, int v, int tar) {\n\tif(g.dfs_children[v].size() == 2) {\n\t\tint u1 = g.dfs_children[v][0];\n\t\tint u2 = g.dfs_children[v][1];\n\t\tif(g.repr_edge[u1] == g.repr_edge[v]) swap(u1, u2);\n\t\thc.push_back(v);\n\t\tdownwards_path(g, hc, u1, g.repr_edge[u1].first);\n\t\tif(v != tar) { \n\t\t\tupwards_path(g, hc, g.dfs_parent[v], tar);\n\t\t}\n\t}\n\telse if(g.dfs_children[v].size() == 1) {\n\t\tint u = g.dfs_children[v][0];\n\t\thc.push_back(v);\n\t\tif(g.repr_edge[u] != g.repr_edge[v]) {\n\t\t\tdownwards_path(g, hc, u, g.repr_edge[u].first);\n\t\t}\n\t\tif(v != tar) {\n\t\t\tupwards_path(g, hc, g.dfs_parent[v], tar);\n\t\t}\n\t}\n\telse {\n\t\thc.push_back(v);\n\t\tif(v != tar) {\n\t\t\tupwards_path(g, hc, g.dfs_parent[v], tar);\n\t\t}\n\t}\n}\n\nvoid downwards_path(graph& g, vi& hc, int v, int tar) {\n\tif(g.dfs_children[v].size() == 2) {\n\t\tint u1 = g.dfs_children[v][0];\n\t\tint u2 = g.dfs_children[v][1];\n\t\tif(g.repr_edge[u1] == g.repr_edge[v]) swap(u1, u2);\n\t\tupwards_path(g, hc, g.repr_edge[u1].first, u1);\n\t\thc.push_back(v);\n\t\tdownwards_path(g, hc, u2, tar);\n\t}\n\telse if(g.dfs_children[v].size() == 1) {\n\t\tint u = g.dfs_children[v][0];\n\t\tif(v == tar) {\n\t\t\tupwards_path(g, hc, g.repr_edge[u].first, u);\n\t\t\thc.push_back(v);\n\t\t}\n\t\telse {\n\t\t\thc.push_back(v);\n\t\t\tdownwards_path(g, hc, u, tar);\n\t\t}\n\t}\n\telse {\n\t\thc.push_back(v);\n\t}\n}\n\nvi hamiltonian_cycle(graph& g) {\n\tg.generate_hamil_dfs_tree(0);\n\tif(g.bad_biccon) return vi();\n\tvi hc;\n\tdownwards_path(g, hc, 0, g.repr_edge[0].first);\n\tassert((int)hc.size() == g.n);\n\treturn hc;\n}\n\nint comp_index;\nbool cyclic_comparator(int a, int b) {\n\tif(a < comp_index) a += 1e7;\n\tif(b < comp_index) b += 1e7;\n\treturn a < b;\n}\n\ngraph sort_graph(const graph& g, const vi& hc) {\n\tgraph h;\n\th.n = g.n;\n\th.m = g.m;\n\th.morphism = vi(g.n);\n\th.al = vvi(g.n);\n\tvi rhc(g.n);\n\tfor(int i=0; i < g.n; ++i) {\n\t\th.morphism[i] = g.morphism[hc[i]];\n\t\trhc[hc[i]] = i;\n\t}\n\tfor(int i=0; i < g.n; ++i) {\n\t\tfor(int j : g.al[hc[i]]) {\n\t\t\th.al[i].push_back(rhc[j]);\n\t\t}\n\t\tcomp_index = i;\n\t\t//This is m log m, can be improved\n\t\tsort(h.al[i].begin(), h.al[i].end(), cyclic_comparator);\n\t}\n\treturn h;\n}\n\nbool has_crossing(const graph& g) {\n\tvii bad_stack;\n\tfor(int i=0; i < g.n; ++i) {\n\t\tcomp_index = i;\n\t\twhile(!bad_stack.empty() && i == bad_stack.back().first) bad_stack.pop_back();\n\t\tfor(int j=(int)g.al[i].size()-2; j > 0; --j) {\n\t\t\tint u = g.al[i][j];\n\t\t\tif(!bad_stack.empty() && cyclic_comparator(bad_stack.back().first, u) && cyclic_comparator(u, bad_stack.back().second)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif(u > i && (bad_stack.empty() || u != bad_stack.back().first)) {\n\t\t\t\tbad_stack.emplace_back(u, i);\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid merge_ans(const graph& g, vvi& ans) {\n\tfor(int i=0; i < g.n; ++i) {\n\t\tfor(int j : g.al[i]) {\n\t\t\tans[g.morphism[i]].push_back(g.morphism[j]);\n\t\t}\n\t}\n}\n\nvoid merge_single_edge_ans(const graph& g, vvi& ans) {\n\tint u = g.morphism[0];\n\tint v = g.morphism[1];\n\tans[u].push_back(v);\n\tans[v].push_back(u);\n}\n\nvvi solve(graph& input_graph) {\n\tvvi ans(input_graph.n);\n\tvector<graph> components = partition_biconnected(input_graph);\n\tfor(graph g : components) {\n\t\tif(g.n == 1) {\n\t\t\t//Nothing\n\t\t}\n\t\telse if(g.n == 2) {\n\t\t\tmerge_single_edge_ans(g, ans);\n\t\t}\n\t\telse {\n\t\t\tvi hc = hamiltonian_cycle(g);\n\t\t\tif(hc.empty()) {\n\t\t\t\treturn vvi();\n\t\t\t}\n\t\t\tgraph g2 = sort_graph(g, hc);\n\t\t\tif(has_crossing(g2))  return vvi();\n\t\t\tmerge_ans(g2, ans);\n\t\t}\n\t}\t\n\treturn ans;\n}\n\ngraph read_graph() {\n\tgraph g;\n\tint n, m;\n\tcin >> n >> m;\n\tg.n = n;\n\tg.m = m;\n\tg.al = vvi(n, vi());\n\tg.morphism = vi(n, 0);\n\tfor(int i=0; i < n; ++i) {\n\t\tg.morphism[i] = i;\n\t}\n\tfor(int i=0; i < m; ++i) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tg.al[u].push_back(v);\n\t\tg.al[v].push_back(u);\n\t}\n\treturn g;\n}\n\nvoid print_ans(const vvi& ans) {\n\tint n = ans.size();\n\tif(n == 0) {\n\t\tcout << \"NO\" << endl;\n\t}\n\telse {\n\t\tcout << \"YES\" << endl;\n\t\tfor(int i=0; i < n; ++i) {\n\t\t\tfor(int x : ans[i]) {\n\t\t\t\tcout << x << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t}\n}\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile(T--) {\n\t\tgraph input_graph = read_graph();\n\t\tvvi ans = solve(input_graph);\n\t\tprint_ans(ans);\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1657",
    "index": "A",
    "title": "Integer Moves",
    "statement": "There's a chip in the point $(0, 0)$ of the coordinate plane. In one operation, you can move the chip from some point $(x_1, y_1)$ to some point $(x_2, y_2)$ if the Euclidean distance between these two points is an \\textbf{integer} (i.e. $\\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$ is integer).\n\nYour task is to determine the minimum number of operations required to move the chip from the point $(0, 0)$ to the point $(x, y)$.",
    "tutorial": "Note that the answer does not exceed $2$, because the chip can be moved as follows: $(0, 0) \\rightarrow (x, 0) \\rightarrow (x, y)$. Obviously, in this case, both operation are valid. It remains to check the cases when the answer is $0$ or $1$. The answer is $0$ only if the destination point is $(0, 0)$, and the answer is $1$ if $\\sqrt{x^2+y^2}$ is integer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int x, y;\n    cin >> x >> y;\n    int d = x * x + y * y;\n    int r = 0;\n    while (r * r < d) ++r;\n    int ans = 2;\n    if (r * r == d) ans = 1;\n    if (x == 0 && y == 0) ans = 0; \n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1657",
    "index": "B",
    "title": "XY Sequence",
    "statement": "You are given four integers $n$, $B$, $x$ and $y$. You should build a sequence $a_0, a_1, a_2, \\dots, a_n$ where $a_0 = 0$ and for each $i \\ge 1$ you can choose:\n\n- either $a_i = a_{i - 1} + x$\n- or $a_i = a_{i - 1} - y$.\n\nYour goal is to build such a sequence $a$ that $a_i \\le B$ for all $i$ and $\\sum\\limits_{i=0}^{n}{a_i}$ is maximum possible.",
    "tutorial": "Strategy is quite easy: we go from $a_1$ to $a_n$ and if $a_{i - 1} + x \\le B$ we take this variant (we set $a_i = a_{i - 1} + x$); otherwise we set $a_i = a_{i - 1} - y$. Note that all $a_i$ are in range $[-(x + y), B]$ so there won't be any overflow/underflow. It's also not hard to prove that this strategy maximizes the sum. By contradiction: suppose the optimal answer has some index $i$ where $a_{i - 1} + x \\le B$ but $a_i = a_{i - 1} - y$. Let's find first position $j \\ge i$ where $a_j = a_{j - 1} + x$ and swap operations between $i$ and $j$. As a result, $B \\ge a_i > a_{i + 1} > \\dots > a_{j}$, all $a_i$ from $[i, j - 1]$ were increased while $a_j$ remained the same, i. e. there is no violation of the rules and the total sum increased - contradiction.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (n, B, x, y) = readLine()!!.split(' ').map { it.toInt() }\n        var cur = 0L\n        var ans = 0L\n        for (i in 1..n) {\n            cur += if (cur + x <= B) x else -y\n            ans += cur\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1657",
    "index": "C",
    "title": "Bracket Sequence Deletion",
    "statement": "You are given a bracket sequence consisting of $n$ characters '(' and/or )'. You perform several operations with it.\n\nDuring one operation, you choose the \\textbf{shortest} prefix of this string (some amount of first characters of the string) that is \\textbf{good} and remove it from the string.\n\nThe prefix is considered \\textbf{good} if one of the following two conditions is satisfied:\n\n- this prefix is a regular bracket sequence;\n- this prefix is a palindrome of length \\textbf{at least two}.\n\nA bracket sequence is called regular if it is possible to obtain a correct arithmetic expression by inserting characters '+' and '1' into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not.\n\nThe bracket sequence is called palindrome if it reads the same back and forth. For example, the bracket sequences )), (( and )(() are palindromes, while bracket sequences (), )( and ))( are not palindromes.\n\nYou stop performing the operations when it's not possible to find a \\textbf{good} prefix. Your task is to find the number of operations you will perform on the given string and the number of remaining characters in the string.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Consider the first character of the string. If it is '(', then we can remove the first two characters of the string and continue (because the prefix of length $2$ will be either a palindrome or a regular bracket sequence). If the first character of the string is ')' then this is a bad case. Of course, the regular bracket sequence can't start with '(', so this prefix should be a palindrome. And what is the shortest palindrome we can get with the first character ')'? It is the closing bracket ')', then some (possibly, zero) amount of opening brackets '(', and another one closing bracket. We can see that we can't find a palindrome shorter than this one because we have to find a pair for the first character. So, if the first character of the string is ')', then we just remove anything until the next character ')' inclusive. To not remove any characters explicitly, we can just use pointers instead. And the last thing is to carefully handle cases when we can't do any operations.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        string s;\n        cin >> n >> s;\n        int l = 0;\n        int cnt = 0;\n        while (l + 1 < n) {\n            if (s[l] == '(' || (s[l] == ')' && s[l + 1] == ')')) {\n                l += 2;\n            } else {\n                int r = l + 1;\n                while (r < n && s[r] != ')') {\n                    ++r;\n                }\n                if (r == n) {\n                    break;\n                }\n                l = r + 1;\n            }\n            ++cnt;\n        }\n        cout << cnt << ' ' << n - l << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1657",
    "index": "D",
    "title": "For Gamers. By Gamers.",
    "statement": "Monocarp is playing a strategy game. In the game, he recruits a squad to fight monsters. Before each battle, Monocarp has $C$ coins to spend on his squad.\n\nBefore each battle starts, his squad is empty. Monocarp chooses \\textbf{one type of units} and recruits no more units of that type than he can recruit with $C$ coins.\n\nThere are $n$ types of units. Every unit type has three parameters:\n\n- $c_i$ — the cost of recruiting one unit of the $i$-th type;\n- $d_i$ — the damage that one unit of the $i$-th type deals in a second;\n- $h_i$ — the amount of health of one unit of the $i$-th type.\n\nMonocarp has to face $m$ monsters. Every monster has two parameters:\n\n- $D_j$ — the damage that the $j$-th monster deals in a second;\n- $H_j$ — the amount of health the $j$-th monster has.\n\nMonocarp has to fight only the $j$-th monster during the $j$-th battle. He wants all his recruited units to stay alive. Both Monocarp's squad and the monster attack continuously (not once per second) and at the same time. Thus, Monocarp wins the battle if and only if his squad kills the monster strictly faster than the monster kills one of his units. The time is compared with no rounding.\n\nFor each monster, Monocarp wants to know the minimum amount of coins he has to spend to kill that monster. If this amount is greater than $C$, then report that it's impossible to kill that monster.",
    "tutorial": "Imagine you are fighting the $j$-th monster, and you fixed the type of units $i$ and their amount $x$. What's the win condition? $\\frac{H_j}{d_i \\cdot x} < \\frac{h_i}{D_j}$. Rewrite it as $H_j \\cdot D_j < d_i \\cdot x \\cdot h_i$. Notice how we only care about $d \\cdot h$ for both the units and the monster, but not about $d$ and $h$ on their own. Let's call $d \\cdot h \\cdot x$ and $D \\cdot H$ the power of the squad and the monster. You can see that for each cost $c$ we can only leave one unit type of that price that has the largest value of $d \\cdot h$. Let's call it $\\mathit{bst}_c$. Now let's learn to determine the maximum power we can obtain for cost exactly $c$. We can iterate over the cost $c$ of one unit and the count $x$ of units in the squad. Since $c \\cdot x$ should not exceed $C$, that will take $\\frac{C}{1} + \\frac{C}{2} + \\dots + \\frac{C}{C} = O(C \\log C)$. Propagate $\\mathit{bst}_c$ to be the maximum power for cost exactly $c$. We have the knowledge about cost exactly $c$, but we actually want no more than $c$. Calculate prefix maximums over $\\mathit{bst}$ - that will be the maximum power we can obtain with no more than $c$ coins. For each monster, we just have to find the smallest $c$ such that $\\mathit{bst}_c > D \\cdot H$. Since the array is monotone, we can use binary search. Overall complexity: $O(n + (C + m) \\log C)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nint main(){\n\tint n, C;\n\tscanf(\"%d%d\", &n, &C);\n\tvector<long long> bst(C + 1);\n\tforn(i, n){\n\t\tint c, d, h;\n\t\tscanf(\"%d%d%d\", &c, &d, &h);\n\t\tbst[c] = max(bst[c], d * 1ll * h);\n\t}\n\tfor (int c = 1; c <= C; ++c) for (int xc = c; xc <= C; xc += c)\n\t\tbst[xc] = max(bst[xc], bst[c] * (xc / c));\n\tforn(c, C)\n\t\tbst[c + 1] = max(bst[c + 1], bst[c]);\n\tint m;\n\tscanf(\"%d\", &m);\n\tforn(j, m){\n\t\tint D;\n\t\tlong long H;\n\t\tscanf(\"%d%lld\", &D, &H);\n\t\tint mn = upper_bound(bst.begin(), bst.end(), D * H) - bst.begin();\n\t\tif (mn > C) mn = -1;\n\t\tprintf(\"%d \", mn);\n\t}\n\tputs(\"\");\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1657",
    "index": "E",
    "title": "Star MST",
    "statement": "In this problem, we will consider \\textbf{complete} undirected graphs consisting of $n$ vertices with weighted edges. The weight of each edge is an integer from $1$ to $k$.\n\nAn undirected graph is considered \\textbf{beautiful} if the sum of weights of all edges incident to vertex $1$ is equal to the weight of MST in the graph. MST is the minimum spanning tree — a tree consisting of $n-1$ edges of the graph, which connects all $n$ vertices and has the minimum sum of weights among all such trees; the weight of MST is the sum of weights of all edges in it.\n\nCalculate the number of \\textbf{complete} \\textbf{beautiful} graphs having exactly $n$ vertices and the weights of edges from $1$ to $k$. Since the answer might be large, print it modulo $998244353$.",
    "tutorial": "Let the weight of the edge between the vertex $x$ to the vertex $y$ be $w_{x,y}$. Suppose there exists a pair of vertices $x$ and $y$ (with indices greater than $2$) such that $w_{x,y} < w_{1,x}$ or $w_{x,y} < w_{1,y}$. Then, if we choose the spanning tree with all vertices connected to $1$, it won't be an MST: we can remove either the edge $(1,x)$ or the edge $(1,y)$, add the edge $(x,y)$ instead, and the cost of the spanning tree will decrease. So, we should have $w_{x,y} \\ge \\max(w_{1,x}, w_{1,y})$ for every pair $(x, y)$. It can be shown that this condition is not only necessary, but sufficient as well: if for every pair $(x, y)$ the condition $w_{x,y} \\ge \\max(w_{1,x}, w_{1,y})$ holds, the MST can't have the weight less than $\\sum \\limits_{i=2}^{n} w_{1,i}$. We can prove this by induction (suppose that $w_{1,2} \\le w_{1,3} \\le \\ldots \\le w_{1,n}$ for simplicity): in the spanning tree, there should be at least one edge incident to vertex $n$, and its weight is at least $w_{1,n}$; there should be at least two edges incident to vertices $n$ and $n-1$, and their weights are at least $w_{1,n-1} + w_{1,n}$; ...; there should be at least $n-1$ edges incident to vertices from $2$ to $n$, and their weights are at least $\\sum \\limits_{i=2}^{n} w_{1,i}$. Okay, now let's show how to calculate the number of such graphs. We can run the following dynamic programming: let $dp_{i,j}$ be the number of graphs where we have already connected $i$ vertices to the vertex $1$, and the maximum weight we have used is $j$. We start with $dp_{0,0}$, and for each transition from $dp_{i,j}$, we will iterate on the number of vertices we connect to the vertex $1$ with edges with weight $(j+1)$ (let the number of those vertices be $t$), choose them with a binomial coefficient $\\frac{(n-1-i)!}{t!(n-1-i-t)!}$, and also choose the weights for the edges that connect one of the chosen vertices with one of the vertices already connected to $1$ (since for each of those edges, we know that their weights should be in $[j+1,k]$) - so, we need to multiply the value in transition by $(k-j)^e$, where $e$ is the number of such edges. Implementing this dynamic programming can be done in $O(n^2k)$ or $O(n^2 k \\log n)$, both are sufficient.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int MOD = 998244353;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\nint binpow(int a, int b){\n\tint res = 1;\n\twhile (b){\n\t\tif (b & 1)\n\t\t\tres = mul(res, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nint main(){\n\tint n, k;\n\tscanf(\"%d%d\", &n, &k);\n\t--n;\n\tvector<vector<int>> dp(k + 1, vector<int>(n + 1, 0));\n\tvector<vector<int>> C(n + 1);\n\tforn(i, n + 1){\n\t\tC[i].resize(i + 1);\n\t\tC[i][0] = C[i][i] = 1;\n\t\tfor (int j = 1; j < i; ++j)\n\t\t\tC[i][j] = add(C[i - 1][j], C[i - 1][j - 1]);\n\t}\n\tdp[0][0] = 1;\n\tforn(i, k) forn(t, n + 1) {\n\t\tint pw = binpow(k - i, t * (t - 1) / 2);\n\t\tint step = binpow(k - i, t);\n\t\tforn(j, n - t + 1){\n\t\t\tdp[i + 1][j + t] = add(dp[i + 1][j + t], mul(dp[i][j], mul(C[n - j][t], pw)));\n\t\t\tpw = mul(pw, step);\n\t\t}\n\t}\n\tprintf(\"%d\\n\", dp[k][n]);\n}",
    "tags": [
      "combinatorics",
      "dp",
      "graph matchings",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1657",
    "index": "F",
    "title": "Words on Tree",
    "statement": "You are given a tree consisting of $n$ vertices, and $q$ triples $(x_i, y_i, s_i)$, where $x_i$ and $y_i$ are integers from $1$ to $n$, and $s_i$ is a string \\textbf{with length equal to the number of vertices on the simple path from $x_i$ to $y_i$}.\n\nYou want to write a lowercase Latin letter on each vertex in such a way that, for each of $q$ given triples, at least one of the following conditions holds:\n\n- if you write out the letters on the vertices on the simple path from $x_i$ to $y_i$ in the order they appear on this path, you get the string $s_i$;\n- if you write out the letters on the vertices on the simple path from $y_i$ to $x_i$ in the order they appear on this path, you get the string $s_i$.\n\nFind any possible way to write a letter on each vertex to meet these constraints, or report that it is impossible.",
    "tutorial": "Let's design a naive solution first. For each of the given triples, we have two options: either write the string on the tree in the order from $x_i$ to $y_i$, or in reverse order. Some options conflict with each other. So, we can treat this problem as an instance of 2-SAT: create a variable for each of the given strings, which is true if the string is not reversed, and false if it is reversed; find all conflicting pairs of options and then run the usual algorithm for solving 2-SAT. Unfortunately, the number of conflicting pairs can be up to $O(n^2)$, so we need to improve this solution. Let's introduce a variable for each vertex of the tree which will define the character we write on it. At first, it looks like we can't use these variables in 2-SAT, since the number of possible characters is $26$, not $2$. But if a vertex is covered by at least one path in a triple, then there are only two possible characters we can write in this vertex: either the character which will land on this position if we write the string from $x_i$ to $y_i$, or the character on the opposite position in the string $s_i$. And, obviously, if a vertex is not covered by any triple, we can write any character on it. Okay, now for each vertex $i$, we have two options for a character: $c_{i,1}$ and $c_{i,2}$. Let the variable $p_i$ be true if we write $c_{i,1}$ on vertex $i$, and false if we write $c_{i,2}$. Also, for each triple $j$, let's introduce a variable $w_j$ which is true if the string $s_j$ is written from $x_j$ to $y_j$, and false if it is written in reversed order. If the vertex $i$ is the $k$-th one on the path from $x_j$ to $y_j$, then we should add the following constraints in our 2-SAT: if $s_{j,k} \\ne c_{i,1}$, we need a constraint \"NOT $p_i$ OR NOT $w_j$\"; if $s_{j,k} \\ne c_{i,2}$, we need a constraint \"$p_i$ OR NOT $w_j$\"; if $s_{j,|s_j|-k+1} \\ne c_{i,1}$, we need a constraint \"NOT $p_i$ OR $w_j$\"; if $s_{j,|s_j|-k+1} \\ne c_{i,2}$, we need a constraint \"$p_i$ OR $w_j$\". Thus, we add at most $16 \\cdot 10^5$ constraints in our 2-SAT. The only thing we haven't discussed is how to actually restore each path from $x_j$ to $y_j$; this can be done either with any fast algorithm that finds LCA, or by searching for LCA \"naively\" by ascending from one of those vertices until we arrive at the ancestor of another vertex; this approach will visit at most $\\sum \\limits_{j=1}^{q} |s_j|$ vertices. Overall, this solution runs in $O(n + q + \\sum \\limits_{j=1}^{q} |s_j|)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n \nvector<vector<int>> t;\nvector<int> p, h;\n \nvoid init(int v){\n\tfor (int u : t[v]) if (u != p[v]){\n\t\tp[u] = v;\n\t\th[u] = h[v] + 1;\n\t\tinit(u);\n\t}\n}\n \nvector<int> get_path(int v, int u){\n\tvector<int> l, r;\n\twhile (v != u){\n\t\tif (h[v] > h[u]){\n\t\t\tl.push_back(v);\n\t\t\tv = p[v];\n\t\t}\n\t\telse{\n\t\t\tr.push_back(u);\n\t\t\tu = p[u];\n\t\t}\n\t}\n\tl.push_back(v);\n\twhile (!r.empty()){\n\t\tl.push_back(r.back());\n\t\tr.pop_back();\n\t}\n\treturn l;\n}\n \nvector<vector<int>> g, tg;\n \nvoid add_edge(int v, bool vx, int u, bool vy){\n\t// (val[v] == vx) -> (val[u] == vy)\n\tg[v * 2 + vx].push_back(u * 2 + vy);\n\ttg[u * 2 + vy].push_back(v * 2 + vx);\n\tg[u * 2 + !vy].push_back(v * 2 + !vx);\n\ttg[v * 2 + !vx].push_back(u * 2 + !vy);\n}\n \nvector<int> ord;\nvector<char> used;\n \nvoid ts(int v){\n\tused[v] = true;\n\tfor (int u : g[v]) if (!used[u])\n\t\tts(u);\n\tord.push_back(v);\n}\n \nvector<int> clr;\nint k;\n \nvoid dfs(int v){\n\tclr[v] = k;\n\tfor (int u : tg[v]) if (clr[u] == -1)\n\t\tdfs(u);\n}\n \nint main(){\n\tcin.tie(0);\n\tiostream::sync_with_stdio(false);\n\t\n\tint n, m;\n\tcin >> n >> m;\n\tt.resize(n);\n\tp.resize(n);\n\th.resize(n);\n\tp[0] = -1;\n\tforn(i, n - 1){\n\t\tint v, u;\n\t\tcin >> v >> u;\n\t\t--v, --u;\n\t\tt[v].push_back(u);\n\t\tt[u].push_back(v);\n\t}\n\tinit(0);\n\t\n\tvector<vector<int>> paths(m);\n\tvector<string> s(m);\n\t\n\tvector<pair<char, char>> opts(n, make_pair(-1, -1));\n\tforn(i, m){\n\t\tint v, u;\n\t\tcin >> v >> u >> s[i];\n\t\t--v, --u;\n\t\tpaths[i] = get_path(v, u);\n\t\tint k = s[i].size();\n\t\tassert(int(paths[i].size()) == k);\n\t\tforn(j, k) opts[paths[i][j]] = {s[i][j], s[i][k - j - 1]};\n\t}\n\t\n\tint nm = (n + m) * 2;\n\tg.resize(nm);\n\ttg.resize(nm);\n\tforn(i, m){\n\t\tint k = s[i].size();\n\t\tforn(j, k){\n\t\t\tint v = paths[i][j];\n\t\t\tchar c = s[i][j], rc = s[i][k - j - 1];\n\t\t\tchar d = opts[v].first, rd = opts[v].second;\n\t\t\tif (d != c) add_edge(v, false, n + i, true);\n\t\t\tif (d != rc) add_edge(v, false, n + i, false);\n\t\t\tif (rd != c) add_edge(v, true, n + i, true);\n\t\t\tif (rd != rc) add_edge(v, true, n + i, false);\n\t\t}\n\t}\n\t\n\tused.resize(nm);\n\tforn(i, nm) if (!used[i]) ts(i);\n\tclr.resize(nm, -1);\n\treverse(ord.begin(), ord.end());\n\tfor (int v : ord) if (clr[v] == -1){\n\t\tdfs(v);\n\t\t++k;\n\t}\n\tforn(i, nm) if (clr[i] == clr[i ^ 1]){\n\t\tcout << \"NO\\n\";\n\t\treturn 0;\n\t}\n\t\n\tcout << \"YES\\n\";\n\tfor (int i = 0; i < 2 * n; i += 2){\n\t\tif (opts[i / 2].first == -1)\n\t\t\tcout << 'a';\n\t\telse if (clr[i] > clr[i ^ 1])\n\t\t\tcout << opts[i / 2].first;\n\t\telse\n\t\t\tcout << opts[i / 2].second;\n\t}\n\tcout << \"\\n\";\n}",
    "tags": [
      "2-sat",
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1658",
    "index": "A",
    "title": "Marin and Photoshoot",
    "statement": "Today, Marin is at a cosplay exhibition and is preparing for a group photoshoot!\n\nFor the group picture, the cosplayers form a horizontal line. A group picture is considered beautiful if for every contiguous segment of at least $2$ cosplayers, the number of males does not exceed the number of females (obviously).\n\nCurrently, the line has $n$ cosplayers which can be described by a binary string $s$. The $i$-th cosplayer is male if $s_i = 0$ and female if $s_i = 1$. To ensure that the line is beautiful, you can invite some additional cosplayers (possibly zero) to join the line at any position. You can't remove any cosplayer from the line.\n\nMarin wants to know the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful. She can't do this on her own, so she's asking you for help. Can you help her?",
    "tutorial": "How will you solve this problem if there are just $2$ male cosplayers? Notice the distance between $2$ consecutive male cosplayers. It is easy to see, in a beautiful picture, there must be at least $2$ female cosplayers between $2$ consecutive male cosplayers. It is also the sufficient condition, as if there are $x$ male cosplayers in a subsegment, there are at least $2(x - 1) = 2x - 2 \\geq x$ for all $x \\geq 2$.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = input()\n    s = input()\n    ans = 0\n    cnt = 2\n    for c in s:\n        if c == '1': cnt += 1\n        else:\n            ans += max(2 - cnt, 0)\n            cnt = 0\n    print(ans)\n \n ",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1658",
    "index": "B",
    "title": "Marin and Anti-coprime Permutation",
    "statement": "Marin wants you to count number of permutations that are beautiful. A beautiful permutation of length $n$ is a permutation that has the following property: $$ \\gcd (1 \\cdot p_1, \\, 2 \\cdot p_2, \\, \\dots, \\, n \\cdot p_n) > 1, $$ where $\\gcd$ is the greatest common divisor.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3, 4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Let's $g = \\gcd (1 \\cdot p_1, \\, 2 \\cdot p_2, \\, \\dots, \\, n \\cdot p_n)$. What is the maximum value of $g$? For each value of $g$, can you construct a satisfying permutation? We can prove that $g \\leq 2$. Assuming $g > 2$: If there exists a prime number $p > 2$ that $p \\mid g$, there are $\\left \\lfloor \\dfrac{n}{p} \\right \\rfloor$ numbers divisible by $p$, so we can match at most $2 \\left \\lfloor \\dfrac{n}{3} \\right \\rfloor$ numbers into pairs, which is smaller than $n$. If there exists a prime number $p > 2$ that $p \\mid g$, there are $\\left \\lfloor \\dfrac{n}{p} \\right \\rfloor$ numbers divisible by $p$, so we can match at most $2 \\left \\lfloor \\dfrac{n}{3} \\right \\rfloor$ numbers into pairs, which is smaller than $n$. Otherwise, we can match odd numbers with even positions, and even numbers with odd positions, which leads to $2 \\mid g$. Because $p_2$ is odd, $2 \\cdot p_2$ is not divisible by $2^k$ with $k > 1$. Otherwise, we can match odd numbers with even positions, and even numbers with odd positions, which leads to $2 \\mid g$. Because $p_2$ is odd, $2 \\cdot p_2$ is not divisible by $2^k$ with $k > 1$. Therefore, $g\\leq 2$. Therefore: If $n$ is odd, the answer is $0$ since the number of odd is greater than the number of even. Otherwise, we will match odd with even and vice versa. For odd number in even position, we have $(\\dfrac{n}{2})!$ ways. According to the multiplicative rule, the answer will be $((\\dfrac{n}{2})!)^2$.",
    "code": "MOD = 998244353\nt = int(input())\n\nfor _ in range(t):\n\tn = int(input())\n\tif n & 1:\n\t    print(0)\n\t    continue\n\tans = 1\n\tfor i in range(1, n // 2 + 1):\n\t\tans = ans * i % MOD\n\tans = ans * ans % MOD\n\tprint(ans)",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1658",
    "index": "C",
    "title": "Shinju and the Lost Permutation",
    "statement": "Shinju loves permutations very much! Today, she has borrowed a permutation $p$ from Juju to play with.\n\nThe $i$-th cyclic shift of a permutation $p$ is a transformation on the permutation such that $p = [p_1, p_2, \\ldots, p_n] $ will now become $ p = [p_{n-i+1}, \\ldots, p_n, p_1,p_2, \\ldots, p_{n-i}]$.\n\nLet's define the power of permutation $p$ as the number of distinct elements in the prefix maximums array $b$ of the permutation. The prefix maximums array $b$ is the array of length $n$ such that $b_i = \\max(p_1, p_2, \\ldots, p_i)$. For example, the power of $[1, 2, 5, 4, 6, 3]$ is $4$ since $b=[1,2,5,5,6,6]$ and there are $4$ distinct elements in $b$.\n\nUnfortunately, Shinju has lost the permutation $p$! The only information she remembers is an array $c$, where $c_i$ is the power of the $(i-1)$-th cyclic shift of the permutation $p$. She's also not confident that she remembers it correctly, so she wants to know if her memory is good enough.\n\nGiven the array $c$, determine if there exists a permutation $p$ that is consistent with $c$. You do \\textbf{not} have to construct the permutation $p$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3, 4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "There is exactly one $1$ in array $c$ (in $(i - 1)$-th cyclic shift, $c_i > 1$ if $p_1 \\neq n$, and $c_i = 1$ if $p_1 = n$), so if the number of $1s$ is greater or less than one, the answer is $\\texttt{NO}$. We can rotate the array such that $c_1 = 1$ (initial state) because we don't have to construct the permutation, so if there exists a permutation with $p_1 = n$, the answer is $\\texttt{YES}$. Notice the difference of $c_i$ and $c_{i + 1}$. In the $i$-th cyclic shift, if $p_1 > p_2$ then $c_{i + 1} \\leq c_i$, otherwise $c_{i + 1} - c_i = 1$, so if there exists a position $i$ such that $c_{i + 1} - c_i > 1$, the answer is $\\texttt{NO}$. This is the sufficient condition. It can be shown that, if $c_{i + 1} - c_i \\leq 1$ for all $1 \\leq i < n$, then there exists a permutation that satisfies. Here is a sketch of the construction: https://codeforces.com/blog/entry/101302?#comment-899523",
    "code": "import sys\ninput = sys.stdin.readline\n \nt = int(input())\nfor _ in range (t):\n    n = int(input())\n    a = list(map(int, input().split()))\n \n    if a.count(1) != 1:\n        print(\"NO\")\n        continue\n \n    a.append(a[0])\n    ok = True\n    for i in range (0, n):\n        if a[i + 1] - a[i] > 1:\n            ok = False\n            break\n    \n    if ok: print(\"YES\")\n    else: print(\"NO\")\n",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1658",
    "index": "D1",
    "title": "388535 (Easy Version)",
    "statement": "This is the easy version of the problem. The difference in the constraints between both versions is colored below in red. You can make hacks only if all versions of the problem are solved.\n\nMarin and Gojou are playing hide-and-seek with an array.\n\nGojou initially performs the following steps:\n\n- First, Gojou chooses $2$ integers $l$ and $r$ such that $l \\leq r$.\n- Then, Gojou makes an array $a$ of length $r-l+1$ which is a permutation of the array $[l,l+1,\\ldots,r]$.\n- Finally, Gojou chooses a secret integer $x$ and sets $a_i$ to $a_i \\oplus x$ for all $i$ (where $\\oplus$ denotes the bitwise XOR operation).\n\nMarin is then given the values of $l,r$ and the final array $a$. She needs to find the secret integer $x$ to win. Can you help her?\n\nNote that there may be multiple possible $x$ that Gojou could have chosen. Marin can find any possible $x$ that could have resulted in the final value of $a$.",
    "tutorial": "Let's look at the binary representation of numbers from $0$ to $7$: $000$ $001$ $010$ $011$ $100$ $101$ $110$ $111$ Let us look at the $i$-th bit only (maybe $i=2$), we will get a sequence like $[0,0,1,1,0,0,1,1]$. Notice that the number of zeroes equals the number of ones in a prefix only when the length of the prefix is a multiple of $2^i$. Otherwise, there will be more zeros than ones. So, we will count the number of flipped and unflipped bits for each bit position. If the number of ones is greater than the number of zeros, the $i$-th bit of $x$ must be $1$. If the number of zeros is greater than the number of ones, the $i$-th bit of $x$ must be $0$. If the number of ones is equal to the number of zeros, that $i$-th bit of $x$ can either be $0$ or $1$. However, if the number of ones is equal to the number of zeros, we can assign the $i$-th bit anything we like. The rough sketch of the proof is that if $x$ is inside $a$ then $x\\oplus2^i$ is also inside $a$. 1658D2 - 388535 (Hard Version)",
    "code": "import sys\ninput = sys.stdin.readline\n \nt = int(input())\nfor _ in range (t):\n    l, r = map(int, input().split())\n    a = list(map(int, input().split()))\n    cnt = [[0] * 2 for _ in range (32)]\n \n    for x in a:\n        for i in range (31):\n            cnt[i][x & 1] += 1\n            x >>= 1\n \n    ans = 0\n    for i in range (31):\n        if (cnt[i][0] < cnt[i][1]):\n            ans |= (1 << i)\n    \n    print(ans)\n",
    "tags": [
      "bitmasks",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1658",
    "index": "D2",
    "title": "388535 (Hard Version)",
    "statement": "This is the hard version of the problem. The difference in the constraints between both versions are colored below in red. You can make hacks only if all versions of the problem are solved.\n\nMarin and Gojou are playing hide-and-seek with an array.\n\nGojou initially perform the following steps:\n\n- First, Gojou chooses $2$ integers $l$ and $r$ such that $l \\leq r$.\n- Then, Gojou will make an array $a$ of length $r-l+1$ which is a permutation of the array $[l,l+1,\\ldots,r]$.\n- Finally, Gojou chooses a secret integer $x$ and sets $a_i$ to $a_i \\oplus x$ for all $i$ (where $\\oplus$ denotes the bitwise XOR operation).\n\nMarin is then given the values of $l,r$ and the final array $a$. She needs to find the secret integer $x$ to win. Can you help her?\n\nNote that there may be multiple possible $x$ that Gojou could have chosen. Marin can find any possible $x$ that could have resulted in the final value of $a$.",
    "tutorial": "If $a \\oplus b = 1$, then $(a \\oplus x) \\oplus (b \\oplus x) = 1$. if $l$ is even and $r$ is odd, the last bit of $x$ can be either $0$ or $1$ (we can pair $a_i$ with $a_i \\oplus 1$). There are two solutions to this problem. If $l$ is even and $r$ is odd, we can skip the last bit and divide the range by two, then recursively solve it. Otherwise, we will pair $a_i$ with $a_i \\oplus 1$, and we will left with at most $2$ candidates for $x$ to check. There is also another solution: we can iterate all possibilities of $x$ (by assuming $a_i$ is $l \\oplus x$ for all $1 \\leq i \\leq n$). If $x$ is the hidden number, $l \\leq a_i \\oplus x \\leq r$ for all $1 \\leq i \\leq n$, so the problem reduce to \"count the number of $a_i$ that $l \\leq a_i \\oplus x \\leq r$\", which can be solved with binary trie.",
    "code": "import sys\ninput = sys.stdin.readline\n \ndef solve(l: int, r: int, s: set):\n    if l % 2 == 0 and r % 2 == 1:\n        t = set()\n        for v in s: t.add(v >> 1)\n        return solve(l >> 1, r >> 1, t) << 1\n    else:\n        for v in s:\n            if (v ^ 1) not in s:\n                ok = True\n                ans = v\n                if l % 2 == 0: ans ^= r\n                else: ans ^= l\n                for x in s:\n                    if (x ^ ans) < l or (x ^ ans) > r:\n                        ok = False\n                        break\n                if ok: return ans\n            \n \nt = int(input())\nfor _ in range (t):\n    l, r = map(int, input().split())\n    s = set(map(int, input().split()))\n    print(solve(l, r, s))\n",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1658",
    "index": "E",
    "title": "Gojou and Matrix Game",
    "statement": "Marin feels exhausted after a long day of cosplay, so Gojou invites her to play a game!\n\nMarin and Gojou take turns to place one of their tokens on an $n \\times n$ grid with Marin starting first. There are some restrictions and allowances on where to place tokens:\n\n- Apart from the first move, the token placed by a player must be more than Manhattan distance $k$ away from the previous token placed on the matrix. In other words, if a player places a token at $(x_1, y_1)$, then the token placed \\textbf{by the other player} in the next move must be in a cell $(x_2, y_2)$ satisfying $|x_2 - x_1| + |y_2 - y_1| > k$.\n- Apart from the previous restriction, a token can be placed anywhere on the matrix, \\textbf{including cells where tokens were previously placed by any player}.\n\nWhenever a player places a token on cell $(x, y)$, that player gets $v_{x,\\ y}$ points. All values of $v$ on the grid are \\textbf{distinct}. You still get points from a cell even if tokens were already placed onto the cell. The game finishes when each player makes $10^{100}$ moves.\n\nMarin and Gojou will play $n^2$ games. For each cell of the grid, there will be exactly one game where Marin places a token on that cell on her first move. Please answer for each game, if Marin and Gojou play optimally (after Marin's first move), who will have more points at the end? Or will the game end in a draw (both players have the same points at the end)?",
    "tutorial": "What if a player is forced to play in a cell where they get fewer points than the previous move? Rephrase the problem, then solve it with dynamic programming. Suppose that Marin places a token at $(a,b)$. If Gojou places a token at $(c,d)$ where $V_{c,d}<V_{a,b}$, then Gojou would not have any advantage as Marin can play at $(a,b)$ again. After a very huge number of turns, Marin will have more points than Gojou. Generally, if a player is forced to play in a cell where they get fewer points than the previous move, they would instantly lose. Therefore, we can rephrase the problem as such: Apart from the first move, the token placed by a player must be more than Manhattan distance k away from the previous token placed on the matrix. Apart from the first move, the token placed by a player must be on a cell with more points than the cell with the token placed by the previous player. The player who plays the last token is the winner. This turns out to be a standard dynamic programming. Let $dp[i][j]$ return $1$ if the player who places a token at $(i,j)$ wins. Let $V_{a,b}=n^2$, then we have $dp[a][b]=1$ as a base case. Then we will fill the values of $dp$ in decreasing values of $V_{i,j}$. $dp[i][j]=1$ if for all $(i',j')$ such that $|i-i'|+|j-j'| > k$, we have $dp[i'][j']=0$. Note that by taking the contrapositive, this is equivalent to for all $(i',j')$ such that $dp[i'][j']=1$, we have $|i-i'|+|j-j'| \\leq k$. Let us maintain a set $S$ that stores the pairs $(i',j')$ such that $dp[i'][j']=1$, then our operations are: adding point $(i,j)$ to $S$ given $(i,j)$, check if for all $(i',j')$ in $S$, $|i-i'|+|j-j'| \\leq k$ Notice that $|i-i'|+|j-j'| \\leq k \\Leftrightarrow \\max(|(i+j)-(i'+j')|,|(i-j)-(i'-j')|) \\leq k$. Checking $\\max(|(i+j)-(i'+j')|,|(i-j)-(i'-j')|) \\leq k$ is very simple as we only need to store the minimum and maximum of all $(i+j)$ and $(i-j)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 2e3 + 5;\nbool f[N][N];\nint l, r, u, d, n, k;\nvector<array<int, 5>> v;\n\nbool check(int i, int j) {\n    return (abs(i - u) <= k && abs(i - d) <= k && abs(j - l) <= k && abs(j - r) <= k);\n}\n\nvoid solve(){\n    cin >> n >> k;\n    for (int i = 1; i <= n; ++i) {\n        for (int j = 1; j <= n; ++j) {\n            f[i][j] = false;\n            int x; cin >> x;\n            v.push_back({x, i, j, i + j, j - i});\n        }\n    }\n\n    sort(v.begin(), v.end(), greater<array<int, 5>>());\n    l = v[0][4], r = v[0][4], u = v[0][3], d = v[0][3];\n    for (array<int, 5> cell: v) {\n        if (check(cell[3], cell[4])) {\n            f[cell[1]][cell[2]] = true;\n            l = min(l, cell[4]);\n            r = max(r, cell[4]);\n            u = min(u, cell[3]);\n            d = max(d, cell[3]);\n        }\n    }\n\n    for (int i = 1; i <= n; ++i) {\n        for (int j = 1; j <= n; ++j) {\n            if (f[i][j]) cout << 'M';\n            else cout << 'G';\n        }\n        cout << '\\n';\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    solve();\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "dp",
      "games",
      "hashing",
      "implementation",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1658",
    "index": "F",
    "title": "Juju and Binary String",
    "statement": "The cuteness of a binary string is the number of $1$s divided by the length of the string. For example, the cuteness of $01101$ is $\\frac{3}{5}$.\n\nJuju has a binary string $s$ of length $n$. She wants to choose some non-intersecting subsegments of $s$ such that their concatenation has length $m$ and it has the same cuteness as the string $s$.\n\nMore specifically, she wants to find two arrays $l$ and $r$ of equal length $k$ such that $1 \\leq l_1 \\leq r_1 < l_2 \\leq r_2 < \\ldots < l_k \\leq r_k \\leq n$, and also:\n\n- $\\sum\\limits_{i=1}^k (r_i - l_i + 1) = m$;\n- The cuteness of $s[l_1,r_1]+s[l_2,r_2]+\\ldots+s[l_k,r_k]$ is equal to the cuteness of $s$, where $s[x, y]$ denotes the subsegment $s_x s_{x+1} \\ldots s_y$, and $+$ denotes string concatenation.\n\nJuju does not like splitting the string into many parts, so she also wants to \\textbf{minimize} the value of $k$. Find the minimum value of $k$ such that there exist $l$ and $r$ that satisfy the constraints above or determine that it is impossible to find such $l$ and $r$ for any $k$.",
    "tutorial": "Let $b$ be the number of black balls and $w$ be the number of white balls. The answer will be impossible if $m$ is not a multiple of $\\dfrac{b+w}{gcd(b, w)}$. It is easy to show that the cuteness of $s$ is $\\dfrac{b}{n}$. What is the number of $\\texttt{1}$ in the concatenated string needed so that the answer exists? The cuteness of $s$ is $\\dfrac{b}{n} = \\dfrac{b}{b+w}$ by definition. Now consider $t = s[l_1, r_1] + [l_2, r_2] + \\dots + s[l_k, r_k]$, the cuteness of the concatenated string. The cuteness of $t$ is $\\dfrac{b}{b+w}$, so the number of $\\texttt{1}$ needed is $k = \\dfrac{m \\cdot w}{b + w}$. If $k$ is not an integer then there will be no answer, so $m$ must be a multiple of $\\dfrac{b+w}{gcd(b, w)}$. We don't need more than 2 parts, or to say $k \\leq 2$ is needed in this problem. Let $c_i =$ (the number of $\\texttt{1}$ in $s[i \\dots i + m - 1]$). For convenient, from now let assume the array and string is wrapped around: $s[i] = s[i + n]$ and $c_i = c_{i+n}$. We have $|c_i-c_{i+1}| \\leq 1$ and there exists $c_i = y$ for all $y$ that $min(c_i) \\leq y \\leq max(c_i)$. GM+ smax provides a simple and clean answer here. Let $L = min(c_i)$, $R = max(c_i)$ and we are doing with wrap around arrays for convenient. We want to prove that for any $y$ that $L \\leq y \\leq R$ there will be some $c_i = y$. Let $d_i = max(c_p, c_{p+1}, \\dots, c_i)$ for $p$ is the minimal position that $c_p = L$. Let $f_x$ is the first position $i$ starting $p$ that $d_i = x$, we have $d_{f_x} = c_{f_x}$ [1] Since $L \\leq y \\leq R$ and, we have $L = d_p \\leq d_{p+1} \\leq \\dots \\leq d_{p+n-1} = R$. [2] Since $|c_{i+1} - c_i| \\leq 1$ we can show that. $\\forall p < i < p + n \\rightarrow \\left[\\begin{array}{l} d_i = d_{i-1} \\\\ d_i = d_{i-1} + 1 \\end{array}\\right.$ [3] Since $c_i \\in \\mathbb{N}$, we also have $d_i \\in \\mathbb{N}$ From [1], [2], [3], if there is $d_i = v > L$ then there will be $d_j = v - 1$ for some $j$ that $p + (v - L) \\leq j < i$. $\\Leftrightarrow \\forall v, min(d_i) \\leq v \\leq max(d_i) \\rightarrow \\exists d_{f_i} = v$ $\\Leftrightarrow \\exists d_{f_i} = y$ $\\Leftrightarrow \\exists c_{f_i} = y$ The answer will be impossible if $m$ is not a multiple of $\\dfrac{b+w}{gcd(b, w)}$. Otherwise, it is proved that $k \\leq 2$ is needed. Since we need to select a minimum $k$, let's first check if there is a solution with $k = 1$ If there exist such position $p$ that $1 \\leq p \\leq n - m + 1$ and $s[p, p + m - 1]$ have the same cuteness as $s[1, n]$ then we found an answer. Otherwise there must be an answer with $k = 2$, and it is simple too If there exist such position $p$ that $1 \\leq p < m$ and $s[1, p] \\cup s[n - (m - p) + 1, n]$ have the same cuteness as $s[1, n]$ then we found an answer. Both can be done in linear $O(n)$ with the sliding window technique or prefixsum.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        int n, k; cin >> n >> k;\n        string s; cin >> s;\n        int one = count_if(s.begin(), s.end(), [](char c) { return c == '1'; });\n        if (1LL * one * k % n != 0) {\n            cout << \"-1\\n\";\n        } else {\n            one = 1LL * one * k / n;\n            vector<int> suf(2 * n + 1);\n            for (int i = 1; i <= 2 * n; i++) {\n                suf[i] = suf[i - 1] + (s[(i - 1) % n] == '1');\n                if (i >= k && suf[i] == suf[i - k] + one) {\n                    if (i <= n) {\n                        cout << \"1\\n\";\n                        cout << i - k + 1 << \" \" << i << '\\n';\n                    } else {\n                        cout << \"2\\n\";\n                        cout << 1 << \" \" << i - n << '\\n';\n                        cout << i - k + 1 << \" \" << n << '\\n';\n                    }\n                    break;\n                }\n            }\n        }\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1659",
    "index": "A",
    "title": "Red Versus Blue",
    "statement": "Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $n$ matches.\n\nIn the end, it turned out Team Red won $r$ times and Team Blue won $b$ times. Team Blue was less skilled than Team Red, so $b$ was \\textbf{strictly less} than $r$.\n\nYou missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $n$ where the $i$-th character denotes who won the $i$-th match  — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the \\textbf{maximum} number of times a team \\textbf{won in a row} was \\textbf{as small as possible}. For example, in the series of matches RBBRRRB, Team Red won $3$ times in a row, which is the maximum.\n\nYou must find a string satisfying the above conditions. If there are multiple answers, print any.",
    "tutorial": "We have $b$ B's which divide the string into $b + 1$ regions and we have to place the R's in these regions. By the strong form of the pigeonhole principle, at least one region must have at least $\\lceil\\frac{r}{b + 1}\\rceil$ R's. This gives us a lower bound on the answer. Now, we will construct a string whose answer is exactly equal to the lower bound. We place the B's so that they are not adjacent. Then we equally distribute the R's in the $b + 1$ regions. Let $p = \\lfloor\\frac{r}{b + 1}\\rfloor$ and $q = r\\bmod(b + 1)$. We place $p$ R's in each region and an extra R in any $q$ regions. Hence, our answer for the construction is $\\lceil\\frac{r}{b + 1}\\rceil$, which is equal to the lower bound. Importantly, $r > b$, so none of the B's will be consecutive. Time complexity: $\\mathcal{O}(n)$.",
    "code": "t = int(input())\nfor i in range(t):\n    n, r, b = map(int, input().split())\n    p = r % (b + 1)\n    y = \"\"\n    for j in range(int(r / (b + 1))):\n        y = y + \"R\"\n    ans = \"\"\n    for i in range(b + 1):\n        if i > 0:\n            ans = ans + \"B\"\n        ans = ans + y\n        if p > 0:\n            ans = ans + \"R\"\n            p = p - 1\n    print(ans)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1659",
    "index": "B",
    "title": "Bit Flipping",
    "statement": "You are given a binary string of length $n$. You have \\textbf{exactly} $k$ moves. In one move, you must select a single bit. The state of all bits \\textbf{except} that bit will get flipped ($0$ becomes $1$, $1$ becomes $0$). You need to output the lexicographically largest string that you can get after using \\textbf{all} $k$ moves. Also, output the number of times you will select each bit. If there are multiple ways to do this, you may output any of them.\n\nA binary string $a$ is lexicographically larger than a binary string $b$ of the same length, if and only if the following holds:\n\n- in the first position where $a$ and $b$ differ, the string $a$ contains a $1$, and the string $b$ contains a $0$.",
    "tutorial": "Let's see how many times a given bit will get flipped. Clearly, a bit gets flipped whenever it is not selected in an operation. Therefore, the $i$-th bit gets flipped $k-f_i$ times. We want to select a bit as few times as possible. Now we can handle a few cases. $k$ is even, bit $i$ is $1$ $\\Rightarrow$ $f_i=0$ (even number of flips don't change the bit) $k$ is even, bit $i$ is $0$ $\\Rightarrow$ $f_i=1$ (odd number of flips toggle the bit from $0$ to $1$) $k$ is odd, bit $i$ is $1$ $\\Rightarrow$ $f_i=1$ (even number of flips don't change the bit) $k$ is odd, bit $i$ is $0$ $\\Rightarrow$ $f_i=0$ (odd number of flips toggle the bit from $0$ to $1$) Process the string from left to right until you can't anymore. If you still have some remaining moves at the end, you can just give them all to the last bit. Then you can construct the final string by checking the parity of $k-f_i$. Time complexity: $\\mathcal{O}(n)$",
    "code": "t = int(input())\nfor i in range(t):\n    n, k = map(int, input().split())\n    kc = k\n    s = input()\n    f = [0] * n\n    ans = \"\"\n    for i in range(n):\n        if k == 0:\n            break\n        if kc % 2 == 1 and s[i] == '1':\n            f[i] = f[i] + 1\n            k = k - 1\n        elif kc % 2 == 0 and s[i] == '0':\n            f[i] = f[i] + 1\n            k = k - 1\n    f[n - 1] = f[n - 1] + k\n    for i in range(n):\n        flip = kc - f[i]\n        if flip % 2 == 0:\n            ans = ans + s[i]\n        else:\n            if s[i] == '1':\n                ans = ans + '0'\n            else:\n                ans = ans + '1'\n    print(ans)\n    for i in range(n):\n        print(f[i], end = ' ')\n    print()",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1659",
    "index": "C",
    "title": "Line Empire",
    "statement": "You are an ambitious king who wants to be the Emperor of The Reals. But to do that, you must first become Emperor of The Integers.\n\nConsider a number axis. The capital of your empire is initially at $0$. There are $n$ unconquered kingdoms at positions $0<x_1<x_2<\\ldots<x_n$. You want to conquer all other kingdoms.\n\nThere are two actions available to you:\n\n- You can change the location of your capital (let its current position be $c_1$) to any other \\textbf{conquered} kingdom (let its position be $c_2$) at a cost of $a\\cdot |c_1-c_2|$.\n- From the current capital (let its current position be $c_1$) you can conquer an unconquered kingdom (let its position be $c_2$) at a cost of $b\\cdot |c_1-c_2|$. You \\textbf{cannot} conquer a kingdom if there is an unconquered kingdom between the target and your capital.\n\nNote that you \\textbf{cannot} place the capital at a point without a kingdom. In other words, at any point, your capital can only be at $0$ or one of $x_1,x_2,\\ldots,x_n$. Also note that conquering a kingdom does not change the position of your capital.\n\nFind the minimum total cost to conquer all kingdoms. Your capital can be anywhere at the end.",
    "tutorial": "Clearly, we should always move from left to right. Also, assume $x_0=0$ for simplicity. Let us analyze what our cost would look like. It will be composed of a part due to moving capitals, and a part due to conquering kingdoms. If we shift our capital from $x_i$ to $x_j$, the cost is $a\\cdot(x_j-x_i)$. If we conquer kingdoms from $(i,j]$ with capital $x_i$, the cost is $b\\cdot((x_{i+1}-x_i)+(x_{i+2}-x_i)+\\ldots+(x_j-x_i))$, which can be written as $b\\cdot(p_j-p_i-(j-i)\\cdot x_i)$, where $p_i=x_0+x_1+\\ldots+x_i$. Now, notice that $x_j-x_i$ and $p_j-p_i$ are linear. Also, if we isolate the parts involving $x_j-x_i$, the sum will be like $(x_{j_1}-x_0)+(x_{j_2}-x_{j_1})+\\ldots+(x_{j_f}-x_{j_{f-1}})=x_{j_f}-x_0$. This means we can simply write the final sum of this part as $a\\cdot x_f$, where $x_f$ is the final position of the capital. We can say the same thing about $p_j-p_i$, except that the final kingdom conquered is always $x_n$. So the final sum of this part is always $b\\cdot p_n$ ($x_0=p_0=0$, so they weren't written explicitly). Our final cost, then, looks like $T=a\\cdot x_f+b\\cdot (p_n-C)$, where $C$ is composed of terms like $(j-i)\\cdot x_i$. If we want to minimise $T$, we want to maximise $C$. That is achieved if we always increase $x_i$! Then we can write $C=x_0+x_1+\\ldots+x_{f-1}+\\underbrace{x_f+\\ldots+x_f}_{n-f\\text{ }\\mathrm{times}}=p_f+(n-f-1)\\cdot x_f$ Hence, our final answer is given by $\\min_{f \\in [0,n]}{(a\\cdot x_f+b\\cdot (p_n-p_f-(n-f-1)\\cdot x_f))}$ Time complexity: $\\mathcal{O}(n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing lol=long long int;\n#define endl \"\\n\"\nconst lol inf=1e18+8;\n \nint main()\n{\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\nint _=1;\ncin>>_;\nwhile(_--)\n{\n    int n;\n    lol a,b;\n    cin>>n>>a>>b;\n    vector<lol> x(n+1),p(n+1);\n    x[0]=0;\n    for(int i=1;i<=n;i++)   cin>>x[i];\n    partial_sum(x.begin(),x.end(),p.begin());\n    lol ans=inf;\n    for(int i=0;i<=n;i++)\n    {\n        ans=min(ans,(a+b)*(x[i]-x[0])+b*(p[n]-p[i]-(n-i)*x[i]));\n    }\n    cout<<ans<<endl;\n}\nreturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1659",
    "index": "D",
    "title": "Reverse Sort Sum",
    "statement": "Suppose you had an array $A$ of $n$ elements, each of which is $0$ or $1$.\n\nLet us define a function $f(k,A)$ which returns another array $B$, the result of sorting the first $k$ elements of $A$ in non-decreasing order. For example, $f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$. Note that the first $4$ elements were sorted.\n\nNow consider the arrays $B_1, B_2,\\ldots, B_n$ generated by $f(1,A), f(2,A),\\ldots,f(n,A)$. Let $C$ be the array obtained by taking the element-wise sum of $B_1, B_2,\\ldots, B_n$.\n\nFor example, let $A=[0,1,0,1]$. Then we have $B_1=[0,1,0,1]$, $B_2=[0,1,0,1]$, $B_3=[0,0,1,1]$, $B_4=[0,0,1,1]$. Then $C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$.\n\nYou are given $C$. Determine a binary array $A$ that would give $C$ when processed as above. It is guaranteed that an array $A$ exists for given $C$ in the input.",
    "tutorial": "The first thing to notice is that any $1$ in the initial array $A$, will contribute to the sum of elements of array $C$ exactly $n$ times. That means, if $S=c_1+c_2+...+c_n$, $S$ must be divisible by $n$. Let $k=\\frac{S}{n}$ be the number of $1$s in the initial array $A$. Observation: The $1$s in $B_n$ form a suffix of it. We'll process the array $C$ from right to left. Assume $a_n$ was $1$. Then, it is clear that $c_n=n$. Then, we can place a $1$ there. Now assume $a_n$ was $0$. Then, it is clear that if there were any $1$s in $A$ (in other words, if $k>0$), then $c_n=1$. Otherwise $c_n=0$. If this is the case, we can place a $0$ there and move on. Finally, we must subtract $1$ from each of the last $k$ elements provided $k>0$. Decrement $k$ if a $1$ was placed. In essence, we simulated removing $B_n$ from the elementwise sum. Once we've processed $c_n$, we can forget about it and continue solving the problem assuming there are $n-1$ elements, and so on. The last thing is to handle subtracting $1$ from the last $k$ elements. It is possible to do it using a segment tree/BIT, but that is overkill for this problem. A simpler way is to maintain a left border for the suffix, and keep track of when the border crosses an element (say $t_i$) and when we reach it. Then we can get a simple formula for the value of the element that looks something like $c_i-(t_i-i)$. Time complexity: $\\mathcal{O}(n)$ or $\\mathcal{O}(n\\log{n})$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing lol=long long int;\n#define endl \"\\n\"\n \nint main()\n{\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\nint _=1;\ncin>>_;\nwhile(_--)\n{\n    int n;\n    cin>>n;\n    vector<lol> v(n);\n    for(auto& e:v)  cin>>e;\n    int k=accumulate(v.begin(),v.end(),0ll)/n;\n    vector<int> b(n),ans(n,0);\n    int lf=n-k;\n    for(int i=lf;i<n;i++)   b[i]=n-1;\n    for(int i=n-1;i>=0 && lf<=i;i--)\n    {\n        int cur=v[i]-(b[i]-i);\n        if(cur==i+1)    ans[i]=1;\n        else if(cur==1)\n        {\n            ans[i]=0;\n            lf--;\n            b[lf]=i-1;\n        }\n    }\n    for(auto& e:ans)    cout<<e<<\" \";\n    cout<<endl;\n}\nreturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1659",
    "index": "E",
    "title": "AND-MEX Walk",
    "statement": "There is an undirected, connected graph with $n$ vertices and $m$ weighted edges. A walk from vertex $u$ to vertex $v$ is defined as a sequence of vertices $p_1,p_2,\\ldots,p_k$ (which are not necessarily distinct) starting with $u$ and ending with $v$, such that $p_i$ and $p_{i+1}$ are connected by an edge for $1 \\leq i < k$.\n\nWe define the length of a walk as follows: take the ordered sequence of edges and write down the weights on each of them in an array. Now, write down the bitwise AND of every nonempty prefix of this array. The length of the walk is the MEX of all these values.\n\nMore formally, let us have $[w_1,w_2,\\ldots,w_{k-1}]$ where $w_i$ is the weight of the edge between $p_i$ and $p_{i+1}$. Then the length of the walk is given by $\\mathrm{MEX}(\\{w_1,\\,w_1\\& w_2,\\,\\ldots,\\,w_1\\& w_2\\& \\ldots\\& w_{k-1}\\})$, where $\\&$ denotes the bitwise AND operation.\n\nNow you must process $q$ queries of the form u v. For each query, find the \\textbf{minimum} possible length of a walk from $u$ to $v$.\n\nThe MEX (minimum excluded) of a set is the smallest non-negative integer that does not belong to the set. For instance:\n\n- The MEX of $\\{2,1\\}$ is $0$, because $0$ does not belong to the set.\n- The MEX of $\\{3,1,0\\}$ is $2$, because $0$ and $1$ belong to the set, but $2$ does not.\n- The MEX of $\\{0,3,1,2\\}$ is $4$ because $0$, $1$, $2$ and $3$ belong to the set, but $4$ does not.",
    "tutorial": "Observation: The MEX can only be $0$, $1$, or $2$. Proof: Suppose the MEX is greater than $2$. We know that on using the bitwise AND function, some on bits will turn off and the sequence will be non-increasing. This would imply that we have $2$, $1$ and $0$ in our sequence. However, going from $2$ (10) to $1$ (01) is not possible as an off bit gets turned on. Hence, $2$ and $1$ can't both be in our sequence. Case $1$: MEX is $0$. For MEX to be $0$, there must be a walk from $u$ to $v$ such that the bitwise AND of the weights of all the edges in that walk is non-zero. This implies that there exists some bit which is on in all the edges of that walk. To check this, we can loop over all possible bits, i.e. $i$ goes from $0$ to $29$, and construct a new graph for each bit while only adding the edges which have the $i$-th bit on. We can use DSU on this new graph and form connected components. This can be processed before taking the queries. In a query, we can go through all bits from $0$ to $29$ and if we get $u$ and $v$ in the same component for some bit, then we're done and our answer is $0$. Case $2$: MEX is $1$. If we didn't get the MEX to be $0$, then we know that $0$ is in our sequence. Now, in our walk, if we ever get a node which has an even edge (let's say this is the first even edge so far) and our bitwise AND so far is greater than $1$ (it would also be an odd number since there's no even edges), then including this edge in our walk would guarantee a MEX of $1$ since the even edge has the $0$-th bit off. Taking the bitwise AND with this edge guarantees that the last bit stays off until the end of our walk and we never get $1$ in the sequence. Let us call this node $x$. For a given $u$, if an $x$ exists, then an answer of $1$ is possible. This also shows us that the value of $v$ is not relevant, since after we get the even edge, our MEX is guaranteed to be $1$ and the subsequent weights do not matter. For the bitwise AND of the walk to be an odd number greater than $1$, all edges on the walk from $u$ to $x$ must have the $0$-th bit on and the $i$-th bit on for some $i$ in $[1, 29]$. Similar to the previous case, we now loop $i$ from $1$ to $29$ and make a new graph for each bit while only adding edges which have the $0$-th and the $i$-th bits on, and use DSU to form connected components. Within a component, if any node has an even edge, then every node in that component can be the starting point of a walk to get the answer as $1$. Then, we go through all the nodes. If the current node, say, $y$ has an even edge, then we can mark the parent node of $y$'s component indicating that this component has an even edge. In the queries, we can go through all the $29$ graphs and if the parent of $u$ in a graph has been marked, then we know that it's possible to have the MEX as $1$. If not, the answer must be $2$ since MEX cannot exceed $2$. Time complexity: $\\mathcal{O}(n\\log{w}+(m+q)\\alpha(n)\\log{w})$",
    "code": "#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC target(\"avx,avx2,fma\")\n \n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/trie_policy.hpp>\n#include <ext/rope>\n \nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n \nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n \n#define fi first\n#define se second\n#define pb push_back\n#define eb emplace_back\n#define mp make_pair\n#define gcd __gcd\n#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define rep(i, n) for (int i=0; i<(n); i++)\n#define rep1(i, n) for (int i=1; i<=(n); i++)\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define endl \"\\n\"\n \ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef unsigned uint;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef vector<int> vi;\ntypedef vector<vector<int>> vvi;\ntypedef vector<ll> vll;\ntypedef vector<vector<ll>> vvll;\ntypedef vector<bool> vb;\ntypedef vector<vector<bool>> vvb;\ntemplate<typename T, typename cmp = less<T>>\nusing ordered_set=tree<T, null_type, cmp, rb_tree_tag, tree_order_statistics_node_update>;\ntypedef trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update> pref_trie;\n \nstruct dsu {\n    vi d;\n    dsu(int n) : d(n, -1) {}\n    int find(int x) {return d[x] < 0 ? x : d[x] = find(d[x]);}\n    void join(int x, int y) {\n        x = find(x), y = find(y);\n        if(x == y) return;\n        if(d[x] > d[y]) swap(x, y);\n        d[x] += d[y]; d[y] = x;\n    }\n    bool is_joined(int x, int y) {\n        return find(x) == find(y);\n    }\n};\n \nint32_t main() {\n    fastio;\n    int n, m; cin >> n >> m;\n    vector<tuple<int, int, int>> edges;\n    rep(i, m) {\n        int u, v, w; cin >> u >> v >> w;\n        edges.eb(--u, --v, w);\n    }\n    vector<dsu> zero(30, n), one(30, n);\n    rep(j, 30) {\n        for(auto& [u, v, w]: edges) if(w >> j & 1) {\n            zero[j].join(u, v);\n        }\n    }\n    vb even(n);\n    rep1(j, 29) {\n        for(auto& [u, v, w]: edges) if((w >> j & 1)) {\n            one[j].join(u, v);\n        }\n        vb vis(n);\n        for(auto& [u, v, w]: edges) if(!(w & 1)) {\n            vis[one[j].find(u)] = 1;\n            vis[one[j].find(v)] = 1;\n        }\n        rep(i, n) if(vis[one[j].find(i)]) even[i] = 1;\n    }\n    auto check = [&](int u, int v) -> int {\n        rep(j, 30) if(zero[j].is_joined(u, v)) return 0;\n        if(even[u]) return 1;\n        rep1(j, 29) if(one[j].is_joined(u, v)) return 1;\n        return 2;\n    };\n    int q; cin >> q;\n    while(q--) {\n        int u, v; cin >> u >> v; --u, --v;\n        cout << check(u, v) << endl;\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1659",
    "index": "F",
    "title": "Tree and Permutation Game",
    "statement": "There is a tree of $n$ vertices and a permutation $p$ of size $n$. A token is present on vertex $x$ of the tree.\n\nAlice and Bob are playing a game. Alice is in control of the permutation $p$, and Bob is in control of the token on the tree. In Alice's turn, she \\textbf{must} pick two \\textbf{distinct} \\textbf{numbers} $u$ and $v$ (\\textbf{not} positions; $u \\neq v$), such that the token is neither at vertex $u$ nor vertex $v$ on the tree, and swap their positions in the permutation $p$. In Bob's turn, he \\textbf{must} move the token to an adjacent vertex from the one it is currently on.\n\nAlice wants to sort the permutation in increasing order. Bob wants to prevent that. Alice wins if the permutation is sorted in increasing order at the beginning or end of her turn. Bob wins if he can make the game go on for an infinite number of moves (which means that Alice is never able to get a sorted permutation). Both players play optimally. Alice makes the first move.\n\nGiven the tree, the permutation $p$, and the vertex $x$ on which the token initially is, find the winner of the game.",
    "tutorial": "Let us call all such $i$ that satisfy $p_i \\neq i$ as marked. If $p_i=i$, it is called unmarked. Also, a notation like $XY$ means \"swap $X$ and $Y$ in the permutation\". We are going to show that it is always possible for Alice to win if the diameter of the tree is $\\geq 3$. First of all, it should be obvious that no matter what moves are made, we will eventually end up at a state where we have just $2$ marked vertices and the token is either on one of them or neither of them (with Alice having to move). In the latter case we have a trivial win. Proof: As long as there are $>2$ marked numbers, you can always find a pair of numbers to swap that will unmark one of the numbers. One can imagine this in terms of the cycle decomposition of the permutation. ----- Next, let us show that from the former state, we can also force a state where the two marked vertices are adjacent to each other (with Alice having to move). Proof: If the two marked vertices are already adjacent, we don't need to do anything. Else, let's say we have $A$ and $B$ where $B$ is the vertex with the token on it. Now, consider two cases. If $A$ is at distance $\\geq 3$ from $B$, we can choose any adjacent vertex to $B$. Let it be $C$. Swap $C$ and $A$. Now Bob has the option of moving the token onto $C$ or not. It wouldn't be optimal to move it away from $C$, because then we can force the sequence $BC$ $CA$ and Bob won't be able to cover any vertex with his token. So Bob must move his token onto $C$. Swap $A$ and $B$, which puts $A$ in its right place. Now Bob must move this token onto $B$, so we did it. If $A$ is instead at distance $2$ from $B$, pick the vertex between $B$ and $A$ as $C$, and we can repeat the same analysis as above. ----- Now, let's say we have $A$ and $B$ with $B$ being the vertex with the token on it. Let us show that, if possible, we can always move $A$ over $B$ and $B$ over $A$ (effectively \"jumping\" over the opposite vertex). Proof: For the first one, pick some vertex adjacent to $B$ (not $A$). Let it be $C$. Swap $A$ and $C$. Now Bob has the option of moving to either $C$ or $A$. If he moves to $A$, we can force $BC$ $CA$ and win. If he moves to $C$, we swap $AB$ (putting $A$ in the right place) and Bob has to move his token to $B$. Now we can see that the marked vertex which was $A$, \"jumped\" over $B$ to reach $C$. For the second one, pick some vertex adjacent to $A$ (not $B$). Let it be $C$. Bob must move his token to $A$. Swap $B$ and $C$ (putting $B$ in the right place). Bob must move his token to $C$. Now we can see that the marked vertex with a token which was $B$, \"jumped\" over $A$ to reach $C$. ----- Like this, we can move all over the tree. Now let's move such that both of the marked vertices lie on a diameter of the tree and one of them is at one end of it. Consider a tree with diameter $\\geq 3$. That means we have a line of at least $4$ vertices taking the two marked vertices at one end. Let's consider just the first $4$ vertices, and show that we can always win here. Proof: Say we have a configuration like $A$-$B$-$C$-$D$ where $A$ and $B$ are marked and $A$ has the token on it. If $B$ has the token on it instead, we can use the moving strategy explained before to first move $A$ to $C$ and then $B$ to $D$ and then it is equivalent to the first configuration. Swap $B$ and $D$. Now Bob must move his token to $B$. Swap $A$ and $D$ (putting $A$ in its right place). Now no matter where Bob moves, after his turn no vertex will be covered and we can force $BD$ and win. ----- Therefore, if the diameter of the tree is $\\geq 3$, we always win. If the diameter of the tree is $2$, it is a star graph, and this is a more problematic case. First of all, we must check if the permutation is already sorted, or we can win in the first move. We can only win in the first move if only $1$ swap is required to sort the permutation, and the token is on neither of the numbers we need to swap. If the above is not possible, several cases follow. Let us make the following observation first. If Bob is at the center of the star and the center is a marked vertex, Bob can infinitely stall Alice. Proof: Let's call the center $A$, and suppose we need to swap the number $B$ with it to put it in its right place. $B$ is definitely at a leaf and $1$ vertex away because of the structure of the star graph. So when Bob's turn comes he can simply move the token to where $B$ is and alternate this way between $A$ and $B$, infinitely stalling Alice. Obviously, even if we try swapping $B$ with a different number $C$, we can just move to where $C$ is next until there are just two vertices left, the center and a leaf. So Bob wins. ----- In light of this, it never makes sense to mark the center in our turn if it is unmarked and not covered by the token. So we have $4$ cases to think of now: - Token on center and center is marked vertex: As explained before, Alice loses here. Before discussing the rest of the cases, let us define $d$ as the minimum number of swaps required to sort the permutation and $x$ is $0$ if the token is on the center and $1$ if it is on a leaf. Now I claim that the parity of $d+x$ is invariant. The magnitude of $x$ changes by exactly $1$ every turn and we can say the same about $d$. So considering all possible changes ($-1$,$-1$) ($-1$,$+1$) ($+1$,$-1$) ($+1$,$+1$) we can see the sum of the changes is always $0 \\bmod 2$. Hence proved. Consider the possible end states for the game: (all with $2$ marked vertices and with Alice having to move) Token at center, center marked Token at unmarked leaf, center marked Token at marked leaf, center marked Token at center, center unmarked Token at unmarked leaf, center unmarked Token at marked leaf, center unmarked Observe that end states $2$ and $5$ will never occur if the game lasts longer than $1$ turn because if you go back by $1$ turn, Bob would have a more optimal move. Therefore, in states $2$ and $5$ we can win in the very first move. Further observe that states $1$ and $2$ will never occur if the center was initially unmarked or we could unmark it in the first move. The only other possibility would be us being unable to unmark the center in the first move, which is a losing state. So we only care about states $4$ and $6$ now. Observe that state $4$ is a winning position while state $6$ is a losing position. Also observe that state $4$ has $d+x$ odd but state $6$ has $d+x$ even. Now let us continue with the cases and use these facts. - Token at center and center is unmarked vertex: Check the parity of $d+x$ here. If it is odd, we win, otherwise we lose (follows from the invariance of $d+x$). - Token at leaf and center is marked vertex: If we cannot unmark the center vertex in our very first move, we'll reach a losing position. If we can, check parity of $d+x$. Odd is win, even is lose. When can we not unmark the center vertex? Only if the token is on $p_{center}$. Otherwise it is always possible. - Token at leaf and center is unmarked vertex: Check parity of $d+x$. Odd is win, even is lose. This completes the solution. Time complexity: $\\mathcal{O}(n)$ or $\\mathcal{O}(n\\log{n})$ (depending on whether you use cycles or inversions to find the parity of $d$)",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing lol=long long int;\n#define endl \"\\n\"\n \npair<int,int> dfs(int u,const vector<vector<int>>& g,int p=-1) //returns {node with max dist,max dist}\n{\n    pair<int,int> res{u,0};\n    int mx=0;\n    for(auto v:g[u])\n    {\n        if(v==p)    continue;\n        pair<int,int> cur=dfs(v,g,u);\n        cur.second++;\n        if(mx<cur.second)\n        {\n            res=cur;\n            mx=cur.second;\n        }\n    }\n    return res;\n}\n \nint main()\n{\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\nint _=1;\ncin>>_;\nwhile(_--)\n{\n    int n,x;\n    cin>>n>>x;\n    vector<vector<int>> g(n+1);\n    vector<int> p(n+1),deg(n+1,0);\n    for(int i=1;i<n;i++)\n    {\n        int u,v;\n        cin>>u>>v;\n        g[u].push_back(v);\n        g[v].push_back(u);\n        deg[u]++,deg[v]++;\n    }\n    for(int i=1;i<=n;i++)\n    {\n        cin>>p[i];\n    }\n    //find diameter of tree with 2 DFSes\n    int diam=dfs(dfs(1,g).first,g).second;\n    //if diam>=3, Alice always wins\n    //if diam=1, n=2, have to check if p=[1,2]\n    //otherwise we have a star graph and cases follow\n    if(diam>=3) cout<<\"Alice\";\n    else if(diam==1)    cout<<((p[1]==1)?\"Alice\":\"Bob\");\n    else\n    {\n        //we need to check if we have already won or can win in the first move\n        //this is possible if the permutation is already sorted\n        //or if there are two marked elements and the chip is on neither of them\n        vector<int> marked;\n        for(int i=1;i<=n;i++)\n        {\n            if(p[i]!=i) marked.push_back(i);\n        }\n        if((int)marked.size()==0)\n        {\n            cout<<\"Alice\";\n        }else if((int)marked.size()==2 && (x!=marked[0] && x!=marked[1]))\n        {\n            cout<<\"Alice\";\n        }else\n        {\n            //we haven't won yet and it is not possible to win in one move\n            //cases follow\n            //first find center, it will have deg>1\n            int center;\n            for(int i=1;i<=n;i++)\n            {\n                if(deg[i]>1)\n                {\n                    center=i;\n                    break;\n                }\n            }\n            //is chip on center?\n            bool chiponcenter=(x==center);\n            //is center marked?\n            bool centerismarked=(find(marked.begin(),marked.end(),x)!=marked.end());\n            //list the cycles\n            vector<int> vis(n+1,false);\n            vector<vector<int> > cycles;\n            for(int i=1;i<=n;i++)\n            {\n                if(vis[i])  continue;\n                int j=i;\n                cycles.push_back({j});\n                vis[j]=true;\n                while(!vis[p[j]])\n                {\n                    cycles.back().push_back(p[j]);\n                    vis[p[j]]=true;\n                    j=p[j];\n                }\n            }\n            //min number of swaps\n            int swapcnt=0;\n            for(auto& cycle:cycles) swapcnt+=(int)cycle.size()-1;\n            //parity\n            int parity=(swapcnt+!chiponcenter)%2;\n            //cases\n            if(!centerismarked)    cout<<(parity?\"Alice\":\"Bob\");\n            else if(chiponcenter && centerismarked)  cout<<\"Bob\";\n            else    //chip not on center and center is marked\n            {\n                //need to check if we can unmark center on first move\n                //it is impossible if x is on p[center] (since we need to move p[center] to get center\n                //to the right place, but p[center] is blocked)\n                bool cannotunmarkcenter=(p[center]==x);\n                if(cannotunmarkcenter)  cout<<\"Bob\";\n                else    cout<<(parity?\"Alice\":\"Bob\");\n            }\n        }\n    }\n    cout<<endl;\n}\nreturn 0;\n}",
    "tags": [
      "dfs and similar",
      "games",
      "graphs",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1660",
    "index": "A",
    "title": "Vasya and Coins",
    "statement": "Vasya decided to go to the grocery store. He found in his wallet $a$ coins of $1$ burle and $b$ coins of $2$ burles. He does not yet know the total cost of all goods, so help him find out $s$ ($s > 0$): the \\textbf{minimum} positive integer amount of money he \\textbf{cannot} pay without change or pay at all using only his coins.\n\nFor example, if $a=1$ and $b=1$ (he has one $1$-burle coin and one $2$-burle coin), then:\n\n- he can pay $1$ burle without change, paying with one $1$-burle coin,\n- he can pay $2$ burle without change, paying with one $2$-burle coin,\n- he can pay $3$ burle without change by paying with one $1$-burle coin and one $2$-burle coin,\n- he cannot pay $4$ burle without change (moreover, he cannot pay this amount at all).\n\nSo for $a=1$ and $b=1$ the answer is $s=4$.",
    "tutorial": "If Vasya has $b$ coins of $2$ burles, then he can collect amounts of $2, 4, \\dots, 2 * b$ burls. If Vasya does not have $1$ burles coins, then he cannot collect the amount of $1$ burle. If he has at least one coin in $1$ burl, he can score odd amounts up to $2*b + a$. The following $1$burl coins increase the maximum amount he can make. If Vasya has $a$ coins for $1$ burle, he can make up the amount of $2 * b + a$ burles, and $2 * b + a + 1$ - not anymore.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    for (int it = 0; it < t; ++it) {\n        int a, b;\n        cin >> a >> b;\n        cout << (a == 0 ? 1 : a + 2 * b + 1) << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1660",
    "index": "B",
    "title": "Vlad and Candies",
    "statement": "Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were $n$ types of candies, there are $a_i$ candies of the type $i$ ($1 \\le i \\le n$).\n\nVlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose \\textbf{any} of them). To get the maximum pleasure from eating, Vlad \\textbf{does not want} to eat two candies of the same type in a row.\n\nHelp him figure out if he can eat all the candies without eating two identical candies in a row.",
    "tutorial": "There will be three cases in total, let's consider them on two types of candies: $a_1 = a_2$, then we will eat candies in this order $[1, 2, 1, 2, \\ dots, 1, 2]$ $a_1 = a_2 + 1$, then we will eat a candy of the type $1$, and then we will eat in this order $[2, 1, 2, 1, \\dots, 2, 1]$ (almost as in the case above) $a_1 >= a_2 + 2$, then we will eat a candy of the type $1$, but there will still be more of them than candies of the type $2$ and we will have to eat a candy of the type $1$ again. So the answer is \"NO\". Now we prove that it is enough to check these conditions on two maximums of the array $a$. If the third condition is true, the answer is obvious \"NO\". Otherwise, we will by turns eat candies of the two maximum types until their number is equal to the third maximum, after which we will by turns eat candies of these three types and so on.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    a.sort()\n    if n == 1:\n        if a[0] > 1:\n            print(\"NO\")\n        else:\n            print(\"YES\")\n        continue\n    if a[-2] + 1 < a[-1]:\n        print(\"NO\")\n    else:\n        print(\"YES\")",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1660",
    "index": "C",
    "title": "Get an Even String",
    "statement": "A string $a=a_1a_2\\dots a_n$ is called even if it consists of a concatenation (joining) of strings of length $2$ consisting of the same characters. In other words, a string $a$ is even if two conditions are satisfied \\textbf{at the same time}:\n\n- its length $n$ is even;\n- for all odd $i$ ($1 \\le i \\le n - 1$), $a_i = a_{i+1}$ is satisfied.\n\nFor example, the following strings are even: \"\" (empty string), \"tt\", \"aabb\", \"oooo\", and \"ttrrrroouuuuuuuukk\". The following strings are not even: \"aaa\", \"abab\" and \"abba\".\n\nGiven a string $s$ consisting of lowercase Latin letters. Find the minimum number of characters to remove from the string $s$ to make it even. The deleted characters do not have to be consecutive.",
    "tutorial": "We will act greedily: we will make an array $prev$ consisting of $26$ elements, in which we will mark $prev[i] = true$ if the letter is already encountered in the string, and $prev[i] = false$ otherwise. In the variable $m$ we will store the length of the even string that can be obtained from $s$. We will go through the string by executing the following algorithm: if $prev[i] = false$, mark $prev[i] = true$. if $prev[i] = true$, then we already have a pair of repeating characters to add to an even string - add $2$ to the number $m$ and clear the array $used$. Clearing $prev$ is necessary because both characters that will make up the next pair must be in the $s$ string after the current character. In other words, if the last character in the current pair was $s_t$, then the first character in the new pair can be $s_k$, where $t \\lt k \\lt n$. Then we calculate the answer as $n - m$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint sz = 26;\n \nvoid solve(){\n    string s;\n    cin >> s;\n    int m = 0, n = (int)s.size();\n    vector<bool>prev(sz, false);\n    for(auto &i : s){\n        if(prev[i - 'a']){\n            m += 2;\n            for(int j = 0; j < sz; j++) prev[j] = false;\n        }\n        else prev[i - 'a'] = true;\n    }\n \n    cout << n - m << endl;\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while (t--){\n        solve();\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1660",
    "index": "D",
    "title": "Maximum Product Strikes Back",
    "statement": "You are given an array $a$ consisting of $n$ integers. For each $i$ ($1 \\le i \\le n$) the following inequality is true: $-2 \\le a_i \\le 2$.\n\nYou can remove any number (possibly $0$) of elements from the beginning of the array and any number (possibly $0$) of elements from the end of the array. You are allowed to delete the whole array.\n\nYou need to answer the question: how many elements should be removed from the beginning of the array, and how many elements should be removed from the end of the array, so that the result will be an array whose product (multiplication) of elements is \\textbf{maximal}. If there is more than one way to get an array with the maximum product of elements on it, you are allowed to output \\textbf{any} of them.\n\nThe product of elements of an \\textbf{empty} array (array of length $0$) should be assumed to be $1$.",
    "tutorial": "First, we can always get a product value equal to $1$ if we remove all elements of the array. Then we need to know what maximal positive value of the product we can get. Consequently, the remaining array (after removing the corresponding prefix and suffix) should have no $0$ elements. We can find maxima in all sections between zeros. Now we are left with a set of nonzero numbers. If the value of the product on the current segment is positive, it makes no sense to remove any more elements. Otherwise, the product is negative, then we must remove one negative number from the product (either to the left or to the right). Compare the values of the product on the prefix and suffix to the nearest negative value, and remove either the suffix or the prefix, respectively.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n \n \nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n);\n \n    forn(i, n) \n        cin >> a[i];\n    int ans = 0;\n    int ap = n, as = 0;\n    for(int i = 0, l = -1; i <= n; i++) {\n        if (i == n || a[i] == 0) {\n            int cnt = 0;\n            bool neg = false;\n            int left = -1, right = -1;\n            int cl = 0, cr = 0;\n            for (int j = l+1; j < i; j++) {\n                neg ^= a[j] < 0;\n                if (a[j] < 0) {\n                    right = j;\n                    cr = 0;\n                }\n \n                if (abs(a[j]) == 2) {\n                    cnt++, cr++;\n                    if (left == -1) cl++;\n                }\n \n                if (a[j] < 0 && left == -1) {\n                    left = j;\n                }\n            }\n            if (neg) {\n                if (cnt - cl > cnt - cr) {\n                    right = i;\n                    cnt -= cl;\n                } else {\n                    left = l;\n                    cnt -= cr;\n                }\n            } else {\n                left = l, right = i;\n            }\n            if (ans < cnt) {\n                ans = cnt;\n                ap = left + 1, as = n - right;\n            }\n \n            l = i;\n        }\n    }\n    cout << ap << ' ' << as << endl;\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1660",
    "index": "E",
    "title": "Matrix and Shifts",
    "statement": "You are given a binary matrix $A$ of size $n \\times n$. Rows are numbered from top to bottom from $1$ to $n$, columns are numbered from left to right from $1$ to $n$. The element located at the intersection of row $i$ and column $j$ is called $A_{ij}$. Consider a set of $4$ operations:\n\n- Cyclically shift all rows up. The row with index $i$ will be written in place of the row $i-1$ ($2 \\le i \\le n$), the row with index $1$ will be written in place of the row $n$.\n- Cyclically shift all rows down. The row with index $i$ will be written in place of the row $i+1$ ($1 \\le i \\le n - 1$), the row with index $n$ will be written in place of the row $1$.\n- Cyclically shift all columns to the left. The column with index $j$ will be written in place of the column $j-1$ ($2 \\le j \\le n$), the column with index $1$ will be written in place of the column $n$.\n- Cyclically shift all columns to the right. The column with index $j$ will be written in place of the column $j+1$ ($1 \\le j \\le n - 1$), the column with index $n$ will be written in place of the column $1$.\n\n\\begin{center}\n{\\small The $3 \\times 3$ matrix is shown on the left before the $3$-rd operation is applied to it, on the right — after.}\n\\end{center}\n\nYou can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order.\n\nAfter that, you can perform an arbitrary (possibly zero) number of new xor-operations:\n\n- Select any element $A_{ij}$ and assign it with new value $A_{ij} \\oplus 1$. In other words, the value of $(A_{ij} + 1) \\bmod 2$ will have to be written into element $A_{ij}$.\n\nEach application of this xor-operation costs one burl. Note that the $4$ shift operations — are free. These $4$ operations can only be performed before xor-operations are performed.\n\nOutput the minimum number of burles you would have to pay to make the $A$ matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, $A_{ij} = 1$ if $i = j$ and $A_{ij} = 0$ otherwise).",
    "tutorial": "Count to the variable $sum$ the number of all ones in the matrix. Then consider pairs of diagonals, one of which starts in cell $A[i][0]$, and the other - in cell $A[0][n - i]$ (for $1 \\le i \\le n - 1$). Using cyclic shifts, we can assemble the main diagonal from this pair. Then among all such pairs (and the main diagonal), find the one that contains the maximal number of ones, and store this number in the variable $Max$. The number of zeros on the main diagonal, which should be turned into ones, is equal to $n - Max$. The number of ones to be turned into zeros, because they are not on the main diagonal, is calculated as $sum - Max$. The total answer is calculated as $n - Max + sum - Max = n + sum - 2Max$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n \nconst int INF = INT_MAX >> 1;\n \nvoid solve() {\n    int n; cin >> n;\n    int cnt1 = 0;\n    vector<int> cnt (n, 0);\n    for (int i = 0; i < n; i++) {\n        string s; cin >> s;\n        for (int j = 0, k = (n - i) % n; j < n; j++, k = (k + 1 == n ? 0 : k + 1)) if (s[j] == '1') {\n            cnt1++;\n            cnt[k]++;\n        }\n    }\n    int ans = INF;\n    for (int i = 0; i < sz(cnt); i++) {\n        ans = min(ans, cnt1 - cnt[i] + (n - cnt[i]));\n    }\n    cout << ans << endl;\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1660",
    "index": "F1",
    "title": "Promising String (easy version)",
    "statement": "\\textbf{This is the easy version of Problem F. The only difference between the easy version and the hard version is the constraints.}\n\nWe will call a non-empty string \\textbf{balanced} if it contains the same number of plus and minus signs. For example: strings \"+--+\" and \"++-+--\" are balanced, and strings \"+--\", \"--\" and \"\" are not balanced.\n\nWe will call a string \\textbf{promising} if the string can be made balanced by several (possibly zero) uses of the following operation:\n\n- replace two \\textbf{adjacent} minus signs with one plus sign.\n\nIn particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.\n\nFor example, the string \"-+---\" is promising, because you can replace two adjacent minuses with plus and get a balanced string \"-++-\", or get another balanced string \"-+-+\".\n\nHow many non-empty substrings of the given string $s$ are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string $s$.\n\nRecall that a substring is a sequence of consecutive characters of the string. For example, for string \"+-+\" its substring are: \"+-\", \"-+\", \"+\", \"+-+\" (the string is a substring of itself) and some others. But the following strings are not its substring: \"--\", \"++\", \"-++\".",
    "tutorial": "Note the fact that if the number of minus signs is greater than the number of plus signs by at least $2$, then there is sure to be a pair of standing next to minus signs (according to the Dirichlet principle). When we apply the operation of replacing two adjacent minus signs with a plus sign, the balance (the difference of plus signs and minus signs) increases by $3$. Then we need to find the number of subsections such that the balance on them is a multiple of $3$ and non-positive (then we can apply the operations until the balance is $0$). The balance value on the segment equals the balance value on the right boundary minus the balance value on the left boundary, i.e. we can find $O(1)$ by prefix sums.",
    "code": "tst = int(input())\nfor _ in range(tst):\n    n = int(input())\n    s = input()\n    b = [0 for i in range(n+1)]\n    bal = n\n    b[0] = bal\n    ans = 0\n    for i in range(1,n+1):\n        if s[i-1] == '+':\n            bal += 1\n        else:\n            bal -= 1\n        b[i] = bal\n        for j in range(i):\n            if b[j] >= b[i] and (b[j] - b[i]) % 3 == 0:\n                ans += 1\n    print(ans)",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1660",
    "index": "F2",
    "title": "Promising String (hard version)",
    "statement": "\\textbf{This is the hard version of Problem F. The only difference between the easy version and the hard version is the constraints.}\n\nWe will call a non-empty string \\textbf{balanced} if it contains the same number of plus and minus signs. For example: strings \"+--+\" and \"++-+--\" are balanced, and strings \"+--\", \"--\" and \"\" are not balanced.\n\nWe will call a string \\textbf{promising} if the string can be made balanced by several (possibly zero) uses of the following operation:\n\n- replace two \\textbf{adjacent} minus signs with one plus sign.\n\nIn particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.\n\nFor example, the string \"-+---\" is promising, because you can replace two adjacent minuses with plus and get a balanced string \"-++-\", or get another balanced string \"-+-+\".\n\nHow many non-empty substrings of the given string $s$ are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string $s$.\n\nRecall that a substring is a sequence of consecutive characters of the string. For example, for string \"+-+\" its substring are: \"+-\", \"-+\", \"+\", \"+-+\" (the string is a substring of itself) and some others. But the following strings are not its substring: \"--\", \"++\", \"-++\".",
    "tutorial": "Now we need to quickly find for a given balance value (on the prefix), the number of matching left boundaries. The boundary is suitable if the balance on the boundary is comparable modulo $3$ to the current balance and the current balance is less than the balance on the boundary, since we need the balance on the segment to be non-positive. That is, we need to be able to find a number of numbers for each value of the balance that is not less than ours. This can be done either by data structure, or notice that the balance takes only $2n+1$ different values, then you can find the number of numbers not less on the prefix for $O(1)$.",
    "code": "tst = int(input())\nfor _ in range(tst):\n    n = int(input())\n    s = input()\n    f = [0 for i in range(3)]\n    cur_bal = n\n    cnt_bal = [0 for i in range(2 * n + 1)]\n    cnt_bal[cur_bal] += 1\n    f[cur_bal % 3] += 1\n    ans = 0\n    for i in range(n):\n        #print(f)\n        #print(cur_bal, ans)\n        new_bal = cur_bal\n        if s[i] == '-':\n            new_bal -= 1\n            f[new_bal % 3] += cnt_bal[new_bal]\n            ans += f[new_bal % 3]\n            cnt_bal[new_bal] += 1\n            f[new_bal % 3] += 1\n        else:\n            f[new_bal % 3] -= cnt_bal[new_bal]\n            new_bal += 1\n            ans += f[new_bal % 3]\n            cnt_bal[new_bal] += 1\n            f[new_bal % 3] += 1\n        cur_bal = new_bal\n    print(ans)",
    "tags": [
      "data structures",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1661",
    "index": "A",
    "title": "Array Balancing",
    "statement": "You are given two arrays of length $n$: $a_1, a_2, \\dots, a_n$ and $b_1, b_2, \\dots, b_n$.\n\nYou can perform the following operation any number of times:\n\n- Choose integer index $i$ ($1 \\le i \\le n$);\n- Swap $a_i$ and $b_i$.\n\nWhat is the minimum possible sum $|a_1 - a_2| + |a_2 - a_3| + \\dots + |a_{n-1} - a_n|$ $+$ $|b_1 - b_2| + |b_2 - b_3| + \\dots + |b_{n-1} - b_n|$ (in other words, $\\sum\\limits_{i=1}^{n - 1}{\\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\\right)}$) you can achieve after performing several (possibly, zero) operations?",
    "tutorial": "Let's look at our arrays $a$ and $b$. Note that for any position $p$ such that $|a_{p-1} - a_p| + |b_{p-1} - b_p| > |a_{p-1} - b_p| + |b_{p-1} - a_p|$ we can always \"fix it\" by swapping all positions $i$ from $p$ to $n$. In that case, contribution from all $i < p$ won't change, contribution of pair $(p - 1, p)$ will decrease and contribution from all $i > p$ won't change again, since we swapped all of them. It means that we already can use the following algorithm: while exists such $p$ that $|a_{p-1} - a_p| + |b_{p-1} - b_p| > |a_{p-1} - b_p| + |b_{p-1} - a_p|$ just swap all $i$ from $p$ to $n$. This solution works for $O(n^2)$ per test, that should be enough. But we can optimize our approach by realizing that we can (instead of searching $p$ each time) just go from $2$ to $n$ and fix pairs one by one: if $|a_1 - a_2| + |b_1 - b_2| > |a_1 - b_2| + |b_1 - a_2|$ then swap $a_2$ with $b_2$; next, if $|a_2 - a_3| + |b_2 - b_3| > |a_2 - b_3| + |b_2 - a_3|$ then swap $a_3$ with $b_3$ and so on. In such way, solution works in $O(n)$.",
    "code": "import kotlin.math.abs\n\nfun sum(a1: Int, a2: Int, b1: Int, b2: Int) = abs(a1 - a2) + abs(b1 - b2)\n\nfun main() {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val a = readLine()!!.split(' ').map { it.toInt() }.toIntArray()\n        val b = readLine()!!.split(' ').map { it.toInt() }.toIntArray()\n\n        var sum = 0L\n        for (i in 1 until n) {\n            if (sum(a[i - 1], a[i], b[i - 1], b[i]) > sum(a[i - 1], b[i], b[i - 1], a[i]))\n                a[i] = b[i].also { b[i] = a[i] }\n            sum += sum(a[i - 1], a[i], b[i - 1], b[i])\n        }\n        println(sum)\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1661",
    "index": "B",
    "title": "Getting Zero",
    "statement": "Suppose you have an integer $v$. In one operation, you can:\n\n- either set $v = (v + 1) \\bmod 32768$\n- or set $v = (2 \\cdot v) \\bmod 32768$.\n\nYou are given $n$ integers $a_1, a_2, \\dots, a_n$. What is the minimum number of operations you need to make each $a_i$ equal to $0$?",
    "tutorial": "Note that $32768 = 2^{15}$, so you can make any value equal to $0$ by multiplying it by two $15$ times, since $(v \\cdot 2^{15}) \\bmod 2^{15} = 0$. So, the answer for each value $a_i$ is at most $15$. Now, let's note that there is always an optimal answer that consists of: at first, add one $cntAdd$ times, then multiply by two $cntMul$ times - and $cntAdd + cntMul$ is the minimum answer. In other words, let's just iterate over all $cntAdd \\le 15$ and $cntMul \\le 15$ and check that $(v + cntAdd) \\cdot 2^{cntMul} \\bmod 32768 = 0$. The answer is minimum $cntAdd + cntMul$ among them. To prove that it's optimal to add at first and only then to multiply, note that it's not optimal to add more than once after muptiplying ($v \\rightarrow 2v \\rightarrow 2v + 2$ can be replaced by $v \\rightarrow v + 1 \\rightarrow 2(v + 1)$). So there is at most one $+1$ between two $\\cdot 2$, but it's not optimal to make even one $+1$ since we need to make $v$ divisible by $2^{15}$ and $+1$ break divisibility. There are many other approaches to this task except this one: for example, since $a_i < 32768$ you can write bfs to find the shortest paths from $0$ to all $a_i$.",
    "code": "fun main() {\n    val n = readLine()!!.toInt()\n    val a = readLine()!!.split(' ').map { it.toInt() }.toIntArray()\n\n    for (v in a) {\n        var ans = 20\n        for (cntAdd in 0..15) {\n            for (cntMul in 0..15) {\n                if (((v + cntAdd) shl cntMul) % 32768 == 0)\n                    ans = minOf(ans, cntAdd + cntMul)\n            }\n        }\n        print(\"$ans \")\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1661",
    "index": "C",
    "title": "Water the Trees",
    "statement": "There are $n$ trees in a park, numbered from $1$ to $n$. The initial height of the $i$-th tree is $h_i$.\n\nYou want to water these trees, so they all grow to the \\textbf{same} height.\n\nThe watering process goes as follows. You start watering trees at day $1$. During the $j$-th day you can:\n\n- Choose a tree and water it. If the day is odd (e.g. $1, 3, 5, 7, \\dots$), then the height of the tree increases by $1$. If the day is even (e.g. $2, 4, 6, 8, \\dots$), then the height of the tree increases by $2$.\n- Or skip a day without watering any tree.\n\nNote that you can't water more than one tree in a day.\n\nYour task is to determine the \\textbf{minimum} number of days required to water the trees so they grow to the same height.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "The first observation we need to solve this problem: the required height is either $max$ or $max + 1$, where $max$ is the maximum initial height of some tree. We don't need heights greater than $max + 1$, because, for example, if the height is $max + 2$, we can remove some moves and get the answer for the height $max$. The same thing applies to all heights greater than $max + 1$. Why do we even need the height $max + 1$? In some cases (like $[1, 1, 1, 1, 1, 1, 2]$) the answer for the height $max + 1$ is better than the answer for the height $max$ (in this particular case, it is $9$ vs $11$). Now, we have two ways to solve the problem: either use some gross formulas, or just write a binary search on the answer. I won't consider the solution with formulas (but we have one), so let's assume we use binary search. Let the current answer be $mid$. Then let $cnt_1 = \\lceil\\frac{mid}{2}\\rceil$ be the number of $+1$ operations we can do and $cnt_2 = \\lfloor\\frac{mid}{2}\\rfloor$ be the number of $+2$ operations we can do. We can use $+2$ operations greedily and then just check if the number of $+1$ operations is sufficient to grow up the remaining heights. Time complexity: $O(n \\log{n})$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nint main(){\n    int tc;\n    scanf(\"%d\", &tc);\n    while (tc--) {\n        int n;\n        scanf(\"%d\", &n);\n        vector<int> a(n);\n        forn(i, n) scanf(\"%d\", &a[i]);\n        long long ans = 1e18;\n        int mx = *max_element(a.begin(), a.end());\n        for (int x : {mx, mx + 1}){\n            long long cnt1 = 0, cnt2 = 0;\n            forn(i, n){\n                cnt2 += (x - a[i]) / 2;\n                cnt1 += (x - a[i]) % 2;\n            }\n            long long dif = max(0ll, cnt2 - cnt1 - 1) / 3;\n            cnt1 += dif * 2;\n            cnt2 -= dif;\n            ans = min(ans, max(cnt1 * 2 - 1, cnt2 * 2));\n            if (cnt2 > 0){\n                cnt1 += 2;\n                --cnt2;\n                ans = min(ans, max(cnt1 * 2 - 1, cnt2 * 2));\n            }\n        }\n        printf(\"%lld\\n\", ans);\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1661",
    "index": "D",
    "title": "Progressions Covering",
    "statement": "You are given two arrays: an array $a$ consisting of $n$ zeros and an array $b$ consisting of $n$ integers.\n\nYou can apply the following operation to the array $a$ an arbitrary number of times: choose some subsegment of $a$ of length $k$ and add the arithmetic progression $1, 2, \\ldots, k$ to this subsegment — i. e. add $1$ to the first element of the subsegment, $2$ to the second element, and so on. The chosen subsegment should be inside the borders of the array $a$ (i.e., if the left border of the chosen subsegment is $l$, then the condition $1 \\le l \\le l + k - 1 \\le n$ should be satisfied). Note that the progression added is always $1, 2, \\ldots, k$ but not the $k, k - 1, \\ldots, 1$ or anything else (i.e., the leftmost element of the subsegment always increases by $1$, the second element always increases by $2$ and so on).\n\nYour task is to find the \\textbf{minimum} possible number of operations required to satisfy the condition $a_i \\ge b_i$ for each $i$ from $1$ to $n$. Note that the condition $a_i \\ge b_i$ should be satisfied for all elements at once.",
    "tutorial": "Let's solve the problem greedily. But not from the beginning, because if we solve it from the beginning, we can't be sure what option is more optimal for the next elements (e.g. for the second element it is not clear if we need to add $2$ to it starting our segment from the first position or add $1$ to it starting our segment from the second position). So, let's solve the problem from right to left, then anything becomes clearer. Actually, let's operate with the array $b$ and decrease its elements instead of using some other array. Let's carry some variables: $sum$, $cnt$ and the array $closed$ of length $n$ (along with the answer). The variable $sum$ means the value we need to subtract from the current element from currently existing progressions, $cnt$ is the number of currently existing progressions, and $closed_i$ means the number of progressions that will end at the position $i+1$ (i.e. will not add anything from the position $i$ and further to the left). When we consider the element $i$, firstly let's fix $sum$ (decrease it by $cnt$). Then, let's fix $cnt$ (decrease it by $closed_i$). Then, let's decrease $b_i$ by $sum$, and if it becomes less than or equal to zero, just proceed. Otherwise, the number by which we can decrease the $i$-th element with one progression, equals to $el = min(k, i + 1)$ (zero-indexed). Then the number of progressions we need to satisfy this element is $need = \\lceil\\frac{b_i}{el}\\rceil$. Let's add this number to the answer, increase $sum$ by $el \\cdot need$, increase $cnt$ by $need$, and if $i - el \\ge 0$ then we need to end these progressions somewhere, so let's add $need$ to $closed_{i - el}$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n\n    int n, k;\n    scanf(\"%d %d\", &n, &k);\n    vector<long long> b(n);\n    for (auto &it : b) {\n        scanf(\"%lld\", &it);\n    }\n    \n    vector<long long> closed(n);\n    long long sum = 0, cnt = 0, ans = 0;\n    for (int i = n - 1; i >= 0; --i) {\n        sum -= cnt;\n        cnt -= closed[i];\n        b[i] -= sum;\n        if (b[i] <= 0) {\n            continue;\n        }\n        int el = min(i + 1, k);\n        long long need = (b[i] + el - 1) / el;\n        sum += need * el;\n        cnt += need;\n        ans += need;\n        if (i - el >= 0) {\n            closed[i - el] += need;\n        }\n    }\n    \n    printf(\"%lld\\n\", ans);\n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1661",
    "index": "E",
    "title": "Narrow Components",
    "statement": "You are given a matrix $a$, consisting of $3$ rows and $n$ columns. Each cell of the matrix is either free or taken.\n\nA free cell $y$ is reachable from a free cell $x$ if at least one of these conditions hold:\n\n- $x$ and $y$ share a side;\n- there exists a free cell $z$ such that $z$ is reachable from $x$ and $y$ is reachable from $z$.\n\nA connected component is a set of free cells of the matrix such that all cells in it are reachable from one another, but adding any other free cell to the set violates this rule.\n\nYou are asked $q$ queries about the matrix. Each query is the following:\n\n- $l$ $r$ — count the number of connected components of the matrix, consisting of columns from $l$ to $r$ of the matrix $a$, inclusive.\n\nPrint the answers to all queries.",
    "tutorial": "Consider the naive approach to the problem. Cut off the columns directly and count the connected components. There are two main solutions to this problem: either DFS (or BFS) or DSU. I personally found the DSU method easier to adjust to the full problem. So, to count connected components with DSU, you should do the following. Initialize the structure without edges: every free cell is its own connected component. Then add edges one by one. Each edge connects two cells either vertically or horizontally. When an edge connects different components, they merge, and the number of components decreases by one. Thus, the number of components on a range of columns is the number of free cells on it minus the number of meaningful edges on it (the ones that will merge components if the algorithm is performed only on these columns - the spanning forest edges). Let's try to adjust this algorithm to the full problem. It would be great if we could just calculate the spanning forest of the entire matrix, and then print the number of free cells minus the number of its edges on the segment. Unfortunately, it's not as easy as that. For components that lie fully in the segment, it works. However, if a component is split by a border of a segment, it can both stay connected or fall apart. If we determine its outcome, we can fix the answer. There are probably a lot of ways to adjust for that, but I'll tell you the one I found the neatest to code. Let's add the edges into DSU in the following order. Go column by column left to right. First add all vertical edges in any order, then all horizontal edges to the previous column in any order. If you start this algorithm at the first column, you will be able to answer all queries with $l=1$. Since the algorithm adds columns iteratively, the spanning forest it's building is correct after every column. So the answer for each query is indeed the number of cells minus the number of edges on the range. Let's investigate the difference between starting at the first column and an arbitrary column $l$. Look at the column $l$. If it contains $1$ or $3$ free cells or $2$ that are adjacent, then the cells are always in the same component, regardless of what has been before column $l$. If there are no free cells, nothing to the left matters, too. This tells us that the spanning forest that the first algorithm has built, is correct for any queries that start in this $l$. The only non-trivial case is when only rows $1$ and $3$ of the $l$-th column contain a free cell. Then we can't tell if the algorithm is correct or not, because these two cells can be in the same component already or not. Let's call this a \"101\" column. Imagine you started processing from the leftmost column of the query, left to right to the rightmost column. Our previous observations tell us that once we encounter a column that is not a \"101\", the algorithm onwards will be correct. Until then, we only have some \"101\" columns to deal with. We can add the part from the first non-\"101\" column onwards to the answer (the number of cells minus the number of edges). And then handle the prefix with some easy casework: if the leftmost column is not \"101\", then add nothing; if all columns in the query are \"101\", then the answer is $2$; if the first non-\"101\" column is \"111\", then add nothing (since the \"101\"s get merged into the component of this column); if the first non-\"101\" column is \"000\" or \"010\", then add $2$ components (since neither row $1$ nor row $3$ is merged anywhere); otherwise, add $1$ component. The number of free cells and edges on a segment can be precalculated with some prefix sums. The closest non-\"101\" column can also be precalculated with a linear algorithm. Overall complexity: $O(n \\cdot \\alpha(n) + q)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nint main(){\n    cin.tie(0);\n\tiostream::sync_with_stdio(false);\n\tint n;\n\tcin >> n;\n\tvector<string> s(3);\n\tforn(i, 3) cin >> s[i];\n\tvector<int> pr(n + 1);\n\tforn(i, n){\n\t\tpr[i + 1] += pr[i];\n\t\tforn(j, 3) pr[i + 1] += (s[j][i] == '1');\n\t}\n\t\n\tvector<int> p(3 * n), rk(3 * n, 1);\n\tiota(p.begin(), p.end(), 0);\n\tfunction<int(int)> getp;\n\tgetp = [&](int a) -> int {\n\t\treturn a == p[a] ? a : p[a] = getp(p[a]);\n\t};\n\tauto unite = [&](int a, int b) -> bool {\n\t\ta = getp(a), b = getp(b);\n\t\tif (a == b) return false;\n\t\tif (rk[a] < rk[b]) swap(a, b);\n\t\tp[b] = a;\n\t\trk[a] += rk[b];\n\t\treturn true;\n\t};\n\t\n\tvector<int> prhe(n + 1), prve(n + 1);\n\t\n\tforn(j, n){\n\t\tforn(i, 2) if (s[i][j] == '1' && s[i + 1][j] == '1' && unite(i * n + j, (i + 1) * n + j))\n\t\t\t++prve[j + 1];\n\t\tforn(i, 3) if (j > 0 && s[i][j] == '1' && s[i][j - 1] == '1' && unite(i * n + j, i * n + (j - 1)))\n\t\t\t++prhe[j];\n\t}\n\tforn(i, n) prve[i + 1] += prve[i];\n\tforn(i, n) prhe[i + 1] += prhe[i];\n\t\n\tvector<int> nxt(n + 1, 0);\n\tfor (int i = n - 1; i >= 0; --i)\n\t\tnxt[i] = (s[0][i] == '1' && s[1][i] == '0' && s[2][i] == '1' ? (nxt[i + 1] + 1) : 0);\n\t\n\tint m;\n\tcin >> m;\n\tforn(_, m){\n\t\tint l, r;\n\t\tcin >> l >> r;\n\t\t--l, --r;\n\t\tint non101 = l + nxt[l];\n\t\tif (non101 > r){\n\t\t    cout << \"2\\n\";\n\t\t    continue;\n\t\t}\n\t\tint tot = pr[r + 1] - pr[non101];\n\t\tint in = (prve[r + 1] - prve[non101]) + (prhe[r] - prhe[non101]);\n\t\tint res = tot - in;\n\t\tif (non101 != l){\n\t\t\tif (s[0][non101] == '1' && s[1][non101] == '1' && s[2][non101] == '1');\n\t\t\telse if (s[0][non101] == '0' && s[2][non101] == '0') res += 2;\n\t\t\telse ++res;\n\t\t}\n\t\tcout << res << \"\\n\";\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "dsu",
      "math",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1661",
    "index": "F",
    "title": "Teleporters",
    "statement": "There are $n+1$ teleporters on a straight line, located in points $0$, $a_1$, $a_2$, $a_3$, ..., $a_n$. It's possible to teleport from point $x$ to point $y$ if there are teleporters in \\textbf{both} of those points, and it costs $(x-y)^2$ energy.\n\nYou want to install some additional teleporters so that it is possible to get from the point $0$ to the point $a_n$ (possibly through some other teleporters) spending \\textbf{no more} than $m$ energy in total. Each teleporter you install must be located in an \\textbf{integer point}.\n\nWhat is the minimum number of teleporters you have to install?",
    "tutorial": "Initial $n+1$ portals divide the path from $0$ to $a_n$ into $n$ separate sections. If we place a new portal between two given ones, it only affects the section between these two portals. Let's suppose we want to place $k$ new portals into a section of length $x$. This will divide it into $(k+1)$ sections, and it's quite easy to prove that these sections should be roughly equal in size (to prove it, we can show that if the sizes of two sections differ by more than $1$, the longer one can be shortened and the shorter one can be elongated so the sum of squares of their lengths decreases). So, a section of length $x$ should be divided into $x \\bmod (k+1)$ sections of length $\\lceil \\frac{x}{k+1} \\rceil$ and $(k+1) - x \\bmod (k+1)$ sections of length $\\lfloor \\frac{x}{k+1} \\rfloor$. Let's denote the total energy cost of a section of length $x$ divided by $k$ new portals as $f(x, k)$; since we divide it in roughly equal parts, it's easy to see that $f(x, k) = (x \\bmod (k+1)) \\cdot (\\lceil \\frac{x}{k+1} \\rceil)^2 + ((k+1) - x \\bmod (k+1)) \\cdot (\\lfloor \\frac{x}{k+1} \\rfloor)^2$ The key observation that we need to make now is that $f(x, k) - f(x, k+1) \\ge f(x, k+1) - f(x, k+2)$; i. e. if we add more portals to the same section, the energy cost change from adding a new portal doesn't go up. Unfortunately, we can't give a simple, strict proof of this fact, but we have faith and stress (this would be easy to prove if it was possible to place portals in non-integer points, we could just analyze the derivative, but in integer case, it's way more difficult). Okay, what should we do with the fact that $f(x, k) - f(x, k+1) \\ge f(x, k+1) - f(x, k+2)$ for a section of length $x$? The main idea of the solution is binary search over the value of $f(x, k) - f(x, k+1)$; i. e., we use binary search to find the minimum possible change that a new portal would give us. Let's say that we want to check that using the portals that give the cost change $\\ge c$ is enough; then, for each section, we want to find the number of new portals $k$ such that $f(x, k-1) - f(x, k) \\ge c$, but $f(x, k) - f(x, k+1) < c$; we can use another binary search to do that. For a fixed integer $c$, we can calculate not only the number of new portals that we can add if the cost change for each portal should be at least $c$, but also the total cost of the path after these changes; let's denote $g(c)$ as the total cost of the path if we place new portals until the cost change is less than $c$, and $h(c)$ is the number of portals we will place in that case. We have to find the minimum value of $c$ such that $g(c) \\le m$. Now, it looks like $h(c)$ is the answer, but this solution gives WA on one of the sample tests. The key observation we are missing is that, for the value $c$, we don't have to add all of the portals that change the answer by $c$; we might need only some of them. To calculate the answer, let's compute four values: $g(c+1)$; $h(c+1)$; $g(c)$; $h(c)$. If we place $h(c+1)$ portals and add new portals one by one, until the total cost becomes not greater than $m$, the cost change from each new portal will be equal to $\\frac{g(c+1) - g(c)}{h(c) - h(c+1)}$ (or just $c$ if we consider the fact that we start using the portals which change the cost by $c$). So, we can easily calculate how many more additional portals we need to add if we start from $h(c+1)$ portals and cost $g(c+1)$. The total complexity of our solution is $O(n \\log^2 A)$: we have a binary search over the cost change for each new portal; and for a fixed cost change, to determine the number of portals we place in each section, we run another binary search in every section separately.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nint n;\nvector<int> lens;\n\nlong long sqr(int x)\n{\n    return x * 1ll * x;\n}\n\nlong long eval_split(int len, int k)\n{\n    return sqr(len / k) * (k - len % k) + sqr(len / k + 1) * (len % k);\n}\n\npair<int, long long> eval_segment(int len, long long bound)\n{\n    // only take options with value >= bound\n    if(bound <= 2 || len == 1)\n        return make_pair(len - 1, len);\n    int lf = 0;\n    int rg = len - 1;\n    while(rg - lf > 1)\n    {\n        int mid = (lf + rg) / 2;\n        if(eval_split(len, mid) - eval_split(len, mid + 1) >= bound)\n            lf = mid;\n        else\n            rg = mid;    \n    }\n    return make_pair(lf, eval_split(len, lf + 1));\n}\n\npair<int, long long> eval_full(long long bound)\n{\n    pair<int, long long> ans;\n    for(auto x : lens)\n    {\n        pair<int, long long> cur = eval_segment(x, bound);\n        ans.first += cur.first;\n        ans.second += cur.second;\n    }\n    return ans;\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    int pr = 0;\n    for(int i = 0; i < n; i++)\n    {\n        int x;\n        scanf(\"%d\", &x);\n        lens.push_back(x - pr);\n        pr = x;\n    }\n    long long w;\n    scanf(\"%lld\", &w);\n    long long lf = 0ll;\n    long long rg = (long long)(1e18) + 43;\n    if(eval_full(rg).second <= w)\n    {\n        cout << 0 << endl;\n        return 0;\n    }\n    while(rg - lf > 1)\n    {\n        long long mid = (lf + rg) / 2;\n        pair<int, long long> res = eval_full(mid);\n        if(res.second <= w)\n            lf = mid;\n        else\n            rg = mid;\n    }   \n    pair<int, long long> resL = eval_full(lf);\n    pair<int, long long> resR = eval_full(rg);\n    assert(resL.second <= w && resR.second > w);\n    long long change = (resR.second - resL.second) / (resR.first - resL.first);\n    cout << resL.first + (w - resL.second) / change << endl;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1662",
    "index": "A",
    "title": "Organizing SWERC",
    "statement": "Gianni, SWERC's chief judge, received a huge amount of high quality problems from the judges and now he has to choose a problem set for SWERC.\n\nHe received $n$ problems and he assigned a beauty score and a difficulty to each of them. The $i$-th problem has beauty score equal to $b_i$ and difficulty equal to $d_i$. The beauty and the difficulty are integers between $1$ and $10$.\n\nIf there are no problems with a certain difficulty (the possible difficulties are $1,2,\\dots,10$) then Gianni will ask for more problems to the judges.\n\nOtherwise, for each difficulty between $1$ and $10$, he will put in the problem set one of the most beautiful problems with such difficulty (so the problem set will contain exactly $10$ problems with distinct difficulties). You shall compute the total beauty of the problem set, that is the sum of the beauty scores of the problems chosen by Gianni.",
    "tutorial": "This is the ice breaker problem of the contest. To solve it one shall implement what is described in the statement. One way to implement it is to keep an array $\\texttt{beauty}[1\\dots10]$ (initialized to $0$), so that, for $1\\le \\texttt{diff}\\le 10$, the value $\\texttt{beauty}[\\texttt{diff}]$ corresponds to the maximum beauty of a proposed problem with difficulty equal to $\\texttt{diff}$. One can update the entries of $\\texttt{beauty}$ while processing the input. In the end, if some entries of $\\texttt{beauty}$ are still $0$ then the correct output is $\\texttt{MOREPROBLEMS}$, otherwise it is the sum of the entries $\\texttt{beauty}[1] + \\texttt{beauty}[2] + \\cdots + \\texttt{beauty}[10]$. Notice that the small size of the input allows for less efficient solutions. For instance, one could iterate $10$ times over the problems, once for each difficulty, and find the maximum beauty associated with difficulty $i$ during the $i$-th iteration (this way, array $\\texttt{beauty}$ is not needed).",
    "tags": [
      "brute force",
      "implementation"
    ]
  },
  {
    "contest_id": "1662",
    "index": "B",
    "title": "Toys",
    "statement": "Vittorio has three favorite toys: a teddy bear, an owl, and a raccoon. Each of them has a name.\n\nVittorio takes several sheets of paper and writes a letter on each side of every sheet so that it is possible to spell any of the three names by arranging some of the sheets in a row (sheets can be reordered and flipped as needed). The three names do not have to be spelled at the same time, it is sufficient that it is possible to spell each of them using all the available sheets (and the same sheet can be used to spell different names).\n\nFind the minimum number of sheets required. In addition, produce a list of sheets with minimum cardinality which can be used to spell the three names (if there are multiple answers, print any).",
    "tutorial": "Toys is one of the most challenging problems of the contest, but no particular knowledge of algorithms and data structures is required to solve it. We propose two greedy solutions that start with a common reformulation of the problem statement. The limit to the length of the three names is very permissive ($\\leq 1000$), so there is no need to pay much attention to computational efficiency. Problem reformulation and notations Suppose to have a set of sheets that allows to spell all three names. Once we fix the way all names are spelled, each sheet either contributes to the $i$-th name with a letter $x_i$ or does not contribute to the $i$-th name. In the latter case, we conventionally set $x_i = \\star$. The triplet $(x_1, \\, x_2, \\, x_3)$ consists of three English letters ($\\texttt{A}$-$\\texttt{Z}$) or $\\star$, with the constraint that at most two different English letters can occur (we say that such a triplet is valid). The problem can then be reformulated as follows: find a set of valid triplets $(x_1^1, \\, x_2^1, \\, x_3^1), \\, \\dots,$ $(x_1^m, \\, x_2^m, \\, x_3^m)$ of minimal size $m$ such that, for each $i \\in \\{1, \\, 2, \\, 3\\}$, the letters $x_i^1, \\, \\dots, \\, x_i^m$ are a permutation of the $i$-th name with some extra $\\star$'s. A set of valid triplets satisfying this property (not necessarily of minimal size) will be called an admissible set; if it is also of minimal size, it will be called an optimal admissible set. For instance, in the first sample, the two sheets $\\texttt{AG}$ and $\\texttt{AM}$ can be represented by the triples $(\\texttt{A}, \\, \\texttt{G}, \\, \\texttt{A})$ and $(\\texttt{A}, \\, \\texttt{A}, \\, \\texttt{M})$ to form the three names $\\texttt{AA}$, $\\texttt{GA}$, $\\texttt{MA}$. In the second sample (where the three names are $\\texttt{TEDDY}$, $\\texttt{HEDWIG}$, and $\\texttt{RACCOON}$), the eight sheets of the sample output can be represented by the triplets in the following columns: $\\texttt{T}$$\\star$$\\texttt{Y}$$\\texttt{D}$$\\texttt{D}$$\\texttt{E}$$\\star$$\\star$$\\star$$\\texttt{H}$$\\star$$\\texttt{G}$$\\texttt{D}$$\\texttt{E}$$\\texttt{I}$$\\texttt{W}$$\\texttt{A}$$\\texttt{C}$$\\texttt{C}$$\\star$$\\texttt{O}$$\\texttt{R}$$\\texttt{N}$$\\texttt{O}$ Denote by $f_i(x)$ the number of occurrences of the letter $x$ in the $i$-th name. Let $f(x) =$ $(f_1(x),$ $f_2(x),$ $f_3(x))$. For instance, in the second sample, $f(\\texttt{D}) = (2, \\, 1, \\, 0)$. Denote by $l_1, \\, l_2, \\, l_3$ the lengths of the three names. Comments on the sample inputs/outputs The first sample (where the three input names are $\\texttt{AA}$, $\\texttt{GA}$, $\\texttt{MA}$) is very small but it already shows that one can cleverly construct a solution with only two sheets, by putting the $\\texttt{G}$ and the $\\texttt{M}$ in two different sheets. If we are not careful and put the $\\texttt{G}$ and the $\\texttt{M}$ on the two sides of the same sheet, then we are forced to use a total of three sheets which is sub-optimal. Note that $\\texttt{AA}$, $\\texttt{GA}$, and $\\texttt{MA}$ are indeed among Vittorio's early favorite words. A trivial lower bound to the number of sheets needed is $\\max(l_1, \\, l_2, \\, l_3)$. The second sample ($\\texttt{TEDDY}$, $\\texttt{HEDWIG}$, $\\texttt{RACCOON}$) is a case where $\\max(l_1, \\, l_2, \\, l_3) = 7$ sheets are not enough. To become convinced that this is indeed the case, one can try to construct an admissible set of $7$ triplets having the letters of $\\texttt{RACCOON}$ in the third positions. None of the letters of $\\texttt{RACCOON}$ is reusable in the other two names, so the only way to save some space is to have two $\\texttt{D}$'s on one sheet and two $\\texttt{E}$'s on another sheet (these are the letters in common between $\\texttt{TEDDY}$ and $\\texttt{HEDWIG}$). Since $l_1 + l_2 = 11$, we would still need $9$ sheets. If we try instead to construct $8$ sheets, one of them is not required to spell $\\texttt{RACCOON}$ (so the corresponding triplet has a $\\star$ in the third position) and so it can fit two different letters from $\\texttt{TEDDY}$ and $\\texttt{HEDWIG}$ (for instance, $\\texttt{D}$ and $\\texttt{G}$ in the sample output). At this point, one could guess that the minimal number of sheets is given by the formula $\\max\\left(l_1, \\, l_2, \\, l_3, \\, \\left\\lceil \\frac{1}{2} \\sum_x \\max f(x) \\right\\rceil \\right).$ First solution We start with the following observation. It is relatively simple, but it will turn out to be very useful. Lemma 1. If $f_1(x) \\geq f_2(x) \\geq f_3(x)$ and $f_1(x), \\, f_2(x) > 0$, then there exists an optimal admissible set that includes a triplet of the form $(x, \\, x, \\, y)$ for some $y$. Proof. Suppose to have an optimal admissible set where no triplet has the form $(x, \\, x, \\, y)$. There is at least one triplet $s_1 = (x, \\, y, \\, y')$ where $x$ appears in first position (but not in second) and at least one triplet $s_2 = (z, \\, x, \\, z')$ where $x$ appears in second position (but not in first). If $s_1$ can be chosen so that $y, \\, y' \\neq x$, then we can replace $s_1$ and $s_2$ with the valid triplets $(x, \\, x, \\, z')$, $(z, \\, y, \\, y')$. If $s_2$ can be chosen so that $z, \\, z' \\neq x$, then we can replace $s_1$ and $s_2$ with the valid triplets $(x, \\, x, \\, y')$, $(z, \\, y, \\, z')$. If none of the previous cases occurs, all triplets containing $x$ are of the form $(t, \\, t', \\, x)$. Therefore, $f_3(x) \\geq f_1(x), \\, f_2(x)$. This implies that $f_1(x) = f_2(x) = f_3(x)$, so all triplets containing $x$ are equal to $(x, \\, x, \\, x)$. $\\blacksquare$ We now describe the first and most important step in our solution. As long as the hypothesis of Lemma 1 holds for some letter $x$ with $f_1(x) + f_2(x) + f_3(x) \\geq 3$, replace one occurrence of the letter $x$ in the first and second name with a new letter $x'$ (not appearing in any of the three names and not necessarily belonging to the English alphabet). This operation does not decrease the minimal number of triplets needed: any set that is admissible for the three new names is also admissible for the old names, after replacing $x'$ with $x$. Thanks to Lemma 1, the minimal number of triplets needed remains the same. When the hypothesis of Lemma 1 does not hold anymore (even after reordering the three names), each letter appears either in at most one name (possibly several times) or exactly twice across all three names. For each letter $x$ that appears in only one name (say, $k$ times), replace all occurrences of $x$ with different new letters $x_1, \\, \\dots, \\, x_k$. This does not impact the optimal size of an admissible set, because all occurrences of $x$ necessarily appear in different triplets. After this operation, every letter appears at most once in each name and at most twice across all three names. For instance, the three names of the second sample could become as follows (we create new letters by adding subscripts to standard English letters): $\\texttt{T}_1\\texttt{E}_1\\texttt{D}_1\\texttt{D}_2\\texttt{Y}_1$, $\\texttt{H}_1\\texttt{E}_1\\texttt{D}_1\\texttt{W}_1\\texttt{I}_1\\texttt{G}_1$, $\\texttt{R}_1\\texttt{A}_1\\texttt{C}_1\\texttt{C}_2\\texttt{O}_1\\texttt{O}_2\\texttt{N}_1$. We say that a letter is double if it appears twice across the three names (such as $\\texttt{D}_1$ in the previous example) and single if it appears once (such as $\\texttt{D}_2$). After changing the three names as described above, our greedy solution is as follows. As long as there are a double letter $x$ and a single letter $y$ that appear in different names (assume without loss of generality that $x$ appears in the first two names and $y$ appears in the third), create a valid triplet $(x, \\, x, \\, y)$ and erase the occurrences of $x$ and $y$ from the three names. As long as there are three double letters $x, \\, y, \\, z$ with $f(x) = (1, \\, 1, \\, 0)$, $f(y) = (0, \\, 1, \\, 1)$, and $f(z) = (1, \\, 0, \\, 1)$, create the two valid triplets $(x, \\, x, \\, z)$ and $(z, \\, y, \\, y)$, then erase all occurrences of $x, \\, y, \\, z$ from the three names. As long as there is a double letter $x$ (assume without loss of generality that it appears in the first two names), create a valid triplet $(x, \\, x, \\, \\star)$ and erase the two occurrences of $x$ in the first two names. As long as at least two names are non-empty, take letters $x, \\, y$ from the two longest names (assume without loss of generality that they are the first and the second name), create a valid triplet $(x, \\, y, \\, \\star)$, and erase the occurrences of $x$ and $y$. As long as exactly one of the names is non-empty (assume without loss of generality that it is the first), create a triplet $(x, \\, \\star, \\, \\star)$ using a letter $x$ of the first name and erase $x$ from the first name. The following lemmas show that the solution we have just described leads to an optimal set of triplets. Lemma 2. Suppose that $x$ is a double letter and $y$ is a single letter with $f(x) = (1, \\, 1, \\, 0)$ and $f(y) = (0, \\, 0, \\, 1)$. Then there exists an optimal admissible set that includes the triplet $(x, \\, x, \\, y)$. Proof. An optimal admissible set necessarily contains one triplet of the form $(z, \\, z', \\, y)$ with $z, \\, z' \\neq y$. We can swap $z$ with the only occurrence of $x$ in the first position of some triplet and $z'$ with the only occurrence of $x$ in the second position of some triplet. All triplets remain valid after this operation. $\\blacksquare$ Lemma 3. Suppose that the hypothesis of Lemma 2 does not apply. If $x, \\, y, \\, z$ are double letters with $f(x) = (1, \\, 1, \\, 0)$, $f(y) = (0, \\, 1, \\, 1)$, and $f(z) = (1, \\, 0, \\, 1)$, then there is an optimal admissible set that includes the triplets $(x, \\, x, \\, z)$ and $(z, \\, y, \\, y)$. Proof. An optimal admissible set necessarily contains one triplet of the form $(x, \\, x, \\, z')$. Since there are no single letters (otherwise, the hypothesis of Lemma 2 would hold), $z'$ is a double letter, so the solution also contains a valid triplet $(z', \\, y', \\, y\")$ or $(y', \\, z', \\, y\")$ with $y', \\, y\" \\neq z'$. In the first case, swap the two occurrences of $z'$ with the two occurrences of $z$; then swap $y'$ with one occurrence of $y$ and $y\"$ with the other occurrence of $y$. We obtain the valid triplets $(x, \\, x, \\, z)$ and $(z, \\, y, \\, y)$, as desired. In the second case, we can similarly obtain $(x, \\, x, \\, y)$ and $(z, \\, y, \\, z)$. One additional swap of $y$ and $z$ in the third position leads to $(x, \\, x, \\, z)$ and $(z, \\, y, \\, y)$. $\\blacksquare$ Lemma 4. Suppose that the hypotheses of Lemmas 2 and 3 do not apply. If $x$ is a double letter with $f(x) = (1, \\, 1, \\, 0)$, then there is an optimal admissible set that includes the triplet $(x, \\, x, \\, \\star)$. Proof. Among all optimal admissible sets, choose one which maximizes the number of triplets with two equal letters $\\neq \\star$. The chosen set necessarily includes a triplet of the form $(x, \\, x, \\, y)$ with $y \\neq x$. We are going to prove that $y = \\star$ (using the maximality assumption). Suppose by contradiction that $y \\neq \\star$. Then $y$ is a double letter, otherwise, Lemma 2 would apply. Therefore, the set includes a valid triplet of the form $(y, \\, z, \\, z')$ or $(z, \\, y, \\, z')$, for some $z, \\, z' \\neq y$; without loss of generality, assume that the first case occurs. If $z = z'$ is a double letter, then Lemma 3 applies, which is a contradiction. This means that at least one of $z$ and $z'$ is $\\star$. We can then swap the $y$ and the $z'$ in the third positions, obtaining the valid triplets $(x, \\, x, \\, z')$ and $(y, \\, z, \\, y)$. This increases by $1$ the number of triplets with two equal letters, violating the maximality assumption. $\\blacksquare$ Lemma 5. Suppose that there are single letters only. If the lengths of the three names satisfy $l_1 \\geq l_2 \\geq l_3$ and $l_1, \\, l_2 > 0$, then there is an optimal admissible set that includes a triplet $(x, \\, y, \\, \\star)$ where $x$ is any (single) letter of the first name and $y$ is any (single) letter of the second name. Proof. Suppose by contradiction to have an optimal set with no triplets of the form $(x, \\, y, \\, \\star)$. For $i \\in \\{1, \\, 2, \\, 3\\}$ denote by $t_i$ the number of triplets with one single letter at position $i$ and two $\\star$; for $1 \\leq i < j \\leq 3$, denote by $t_{i,j}$ the number of triplets with single letters at positions $i$ and $j$. At most one of $t_1, \\, t_2, \\, t_3$ is non-zero, otherwise, we could merge two triplets into one, which goes against the optimality assumption. In addition, $t_{1,2} = 0$. By counting the letters occurring in each position of the triplets, we easily get $l_1 = t_1 + t_{1,3}$, $l_2 = t_2 + t_{2,3}$, and $l_3 = t_3 + t_{1,3} + t_{2,3}$. Since at least one of $t_1$ and $t_2$ is zero, we have that $l_3 \\geq \\min(l_1, \\, l_2)$, so $l_2 = l_3$. This forces $t_3 = 0$ and $t_2 = t_{1,3}$. If $t_2 = t_{1,3} > 0$, then there is at least one triplet of the form $(x, \\, \\star, \\, z)$ and one the form $(\\star, \\, y, \\, \\star)$; we can swap $x$ and $\\star$ the first positions to obtain $(x, \\, y, \\, \\star)$ and $(\\star, \\, \\star, \\, z)$, as desired. Otherwise, $t_2 = t_{1,3} = 0$, so $t_1 \\geq t_{2,3} > 0$ and we conclude in a similar way by transforming two triplets of the form $(x, \\, \\star, \\, \\star)$ and $(\\star, \\, y, \\, z)$ into $(x, \\, y, \\, \\star)$ and $(\\star, \\, \\star, \\, z)$. $\\blacksquare$ Second solution The alternative solution we propose does not use the idea of changing the letters. Instead, the key greedy step is the following: as long as one name (say, the first) contains a letter $x$ with $f_1(x) > f_2(x) + f_3(x)$ and the other two names contain a common letter $y$ with $f_1(y) < f_2(y) + f_3(y)$, we create the triplet $(x, \\, y, \\, y)$ and decrease the length of the three names by $1$. The optimality of this step is proved in Lemma 8 below. Once this can no longer be done, we are left with four possible cases (described by Lemma 9 below) and we show how to conclude greedily in each case: one case is in common with the first solution; in the other three cases, there is an admissible set of size $\\max(l_1, \\, l_2, \\, l_3)$ which is clearly optimal (since we need at least one triplet for each letter of the longest name). Lemma 6. Suppose that $f_1(x) > f_2(x) + f_3(x)$ for some English letter $x$. Then any admissible set includes a triplet $(x, \\, y, \\, y')$ with $y, \\, y' \\neq x$, where $y$ and $y'$ can be either English letters or $\\star$. Proof. For all $i \\in \\{1, \\, 2, \\, 3\\}$, any admissible set must have exactly $f_i(x)$ triplets with $x$ in the $i$-th position. Therefore, at least one triplet has $x$ in the first position but not in the second or third position. $\\blacksquare$ Lemma 7. Suppose that $f_1(x) < f_2(x) + f_3(x)$, $f_2(x) > 0$, and $f_3(x) > 0$, for some English letter $x$. Then there is an optimal admissible set that includes a triplet $(y, \\, x, \\, x)$ where $y$ can be either an English letter or $\\star$. Proof. Fix an optimal admissible set. If at least one triplet has $x$ both in the second and third position, then we are done. Otherwise, the inequality $f_1(x) < f_2(x) + f_3(x)$ ensures that at least one triplet $s_1$ has $x$ in the second or third position but not in the first position. Suppose without loss of generality that $s_1 = (z, \\, z', \\, x)$ with $z, \\, z' \\neq x$. Since $f_2(x) > 0$, there exists at least one triplet $s_2$ of the form $(y, \\, x, \\, y')$. We can then replace the triplets $s_1$ and $s_2$ with the following two valid triplets: $(y, \\, x, \\, x)$ and $(z, \\, z', \\, y')$. $\\blacksquare$ Lemma 8. Suppose that $f_1(x) > f_2(x) + f_3(x)$, $f_1(y) < f_2(y) + f_3(y)$, and $f_2(y), \\, f_3(y) > 0$ for some English letters $x, \\, y$. Then there is an optimal admissible set that includes a triplet $(x, \\, y, \\, y)$. Proof. By Lemma 7, there exists an optimal admissible set that includes a triplet $s_1$ of the form $(z, \\, y, \\, y)$. If $z = x$, then we are done. Otherwise, by Lemma 6, the set also includes a triplet $s_2$ of the form $(x, \\, t, \\, t')$ with $t, \\, t' \\neq x$. We can then replace $s_1$ and $s_2$ with the following two valid triplets: $(x, \\, y, \\, y)$ and $(z, \\, t, \\, t')$. $\\blacksquare$ Lemma 9. If the hypothesis of Lemma 8 does not apply, we are in at least one of the following cases: For all letters $x$, the numbers $f_1(x), \\, f_2(x), \\, f_3(x)$ form the sides of a (possibly degenerate) triangle. Up to changing the order of the three names, $f_1(x) \\geq f_2(x) + f_3(x)$ for all letters $x$. One of the names is empty. The three names have disjoint letters. Proof. We say that the first name is beautiful if $f_1(x) > f_2(x) + f_3(x)$ for at least one letter $x$, and we analogously define beauty for the second and third name. If none of the three names is beautiful, then we are in case (1). If exactly one name is beautiful (say, the first one), then $f_1(x) > f_2(x) + f_3(x)$ for some letter $x$; if $f_1(y) < f_2(y) + f_3(y)$ for some $y$, then $f_2(y), \\, f_3(y) > 0$ (otherwise, the second or third name would be beautiful), so Lemma 8 applies, which is a contradiction. Therefore we are in case (2). If exactly two names are beautiful (say, the first and the second name), we are going to prove that the third name is empty, so we are in case (3). Indeed, suppose by contradiction that the third name contains some letter $y$. Then $f_3(y) \\leq f_1(y) + f_2(y)$ because the third name is not beautiful, so at least one other name (say, the second) contains the letter $y$. Since the first name is beautiful and Lemma 8 does not apply, we have $f_1(y) \\geq f_2(y) + f_3(y)$ and in particular, the first name also contains the letter $y$. Similarly, since the second name is beautiful and Lemma 8 does not apply (after swapping the first and second name), we get $f_2(y) \\geq f_1(y) + f_3(y)$. Combining the previous two inequalities, we get $f_1(y) \\geq f_2(y) + f_3(y) \\geq f_1(y) + 2 f_3(y)$, so $f_3(y) = 0$, a contradiction. Finally, if all three names are beautiful, we are going to prove that we are in case (4). Indeed, suppose by contradiction that two names (say, the second and the third) have a letter $y$ in common. Since the first name is beautiful and Lemma 8 does not apply, we have $f_1(y) \\geq f_2(y) + f_3(y)$, so in particular the first name also contains $y$. Since the second name is beautiful and Lemma 8 does not apply, we also have $f_2(y) \\geq f_1(y) + f_3(y)$, which is a contradiction because $f_3(y) > 0$. $\\blacksquare$ If we are in case (2), we easily conclude with $l_1$ additional triplets. If we are in case (3), assuming without loss of generality that the third name is empty, we conclude with additional $\\max(l_1, \\, l_2)$ triplets. Case (4) is handled as in Lemma 5 at the end of the first solution (we are left with single letters only). Only case (1) remains, and we are going to show that in such case we can conclude with $\\max(l_1, \\, l_2, \\, l_3)$ additional triplets. We say that the first and second names are friends if there is a letter $x$ such that $f_1(x), \\, f_2(x) > 0$ and $f_1(x)-1, \\, f_2(x)-1, \\, f_3(x)$ form the sides of a triangle (we say that the letter $x$ proves the friendship between the first and second names). We define the friendship for the other two pairs of names analogously. Iteratively proceed as follows: As long as there is a letter $x$ such that $f_1(x)-1, \\, f_2(x)-1, \\, f_3(x)-1$ form the sides of a triangle, we create a triplet $(x, \\, x, \\, x)$ and erase one occurrence of $x$ from each name. As long as each name is a friend of the other two, then let $x, \\, y, \\, z$ be three letters that prove the friendships. We create two triplets $(x, \\, x, \\, y)$ and $(z, \\, y, \\, z)$, then erase $x$ and $z$ from the first name, $x$ and $y$ from the second name, $y$ and $z$ from the third name. If we are not in case (1) or (2), suppose without loss of generality that the second and third names are not friends. We are going to prove that $f_1(x) \\geq f_2(x) + f_3(x)$ for all letters $x$, so we can conclude as in case (2). If $f_2(x) = 0$, then $f_1(x) = f_3(x)$ (because we are in case (1)), and similarly $f_3(x) = 0$ implies $f_1(x) = f_3(x)$. In both these cases, $f_1(x) \\geq f_2(x) + f_3(x)$. We can therefore assume that $f_2(x), \\, f_3(x) > 0$. Since the second and third names are not friends, we have $f_1(x) > f_2(x) - 1 + f_3(x) - 1$, i.e., $f_1(x) \\geq f_2(x) + f_3(x) - 1$. Since we are not in case (a), we necessarily have $f_1(x) \\geq f_2(x) + f_3(x)$.",
    "tags": [
      "greedy",
      "strings"
    ]
  },
  {
    "contest_id": "1662",
    "index": "C",
    "title": "European Trip",
    "statement": "The map of Europe can be represented by a set of $n$ cities, numbered from $1$ through $n$, which are connected by $m$ bidirectional roads, each of which connects two distinct cities. A trip of length $k$ is a sequence of $k+1$ cities $v_1, v_2, \\ldots, v_{k+1}$ such that there is a road connecting each consecutive pair $v_i$, $v_{i+1}$ of cities, for all $1 \\le i \\le k$. A special trip is a trip that does not use the same road twice in a row, i.e., a sequence of $k+1$ cities $v_1, v_2, \\ldots, v_{k+1}$ such that it forms a trip and $v_i \\neq v_{i + 2}$, for all $1 \\le i \\le k - 1$.\n\nGiven an integer $k$, compute the number of distinct special trips of length $k$ which begin and end in the same city. Since the answer might be large, give the answer modulo $998\\,244\\,353$.",
    "tutorial": "Warm-up problem Let us consider a related simpler problem first. Let $G$ be the graph that represents the cities and roads in the problem statement and let $A$ be its adjacency matrix. Suppose that instead of special trips we wanted to compute the number of distinct trips of length $k$ that begin and end in the same city. We can use an important property of the adjacency matrix $A$. Lemma 1. For any $k \\ge 1$, the $(i, \\, j)$-th entry of the $k$-th power of $A$, $(A^k)_{ij}$ is equal to the number of trips of length $k$ that start at $i$ and end at $j$. Proof. For $k = 1$ this is obvious from the definition of adjacency matrix. Assume the lemma holds for $k \\geq 1$ and consider the matrix $A^{k+1} = A^k A$. By the inductive hypothesis, $(A^k)_{ij}$ is equal to the number of trips of length $k$ that start at $i$ and end at $j$. Now, the number of trips of length $k + 1$ between $i$ and $j$ is equal the number of trips of length $k$ from $i$ to some vertex $l$ adjacent to $j$, but this is given by $A^k A$, so the result follows by induction. $\\blacksquare$ Thus, to compute the number of trips of length $k$ that begin and end in the same city we only need to compute $A^k$ and sum the elements in the diagonal of the matrix (this is called the trace of the matrix). To do so efficiently, we can use the binary exponentiation technique, which is summarized in the following recursive approach. Let $\\displaystyle I = \\begin{bmatrix} 1 & 0 & \\cdots & 0 \\\\ 0 & 1 & \\cdots & 0 \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ 0 & 0 & \\cdots & 1 \\end{bmatrix}$ be the identity matrix. Then: $A^k = \\left\\{ \\begin{matrix} I & \\mathrm{if} \\; k = 0, \\\\ \\left(A^{\\frac{k}{2}}\\right)^2 & \\mathrm{if} \\; k > 0 \\; \\mathrm{and} \\; k \\; \\mathrm{even}, \\\\ \\left(A^{\\frac{k - 1}{2}}\\right)^2 \\cdot A & \\mathrm{if} \\; k > 0 \\; \\mathrm{and} \\; k \\; \\mathrm{odd}. \\end{matrix} \\right.$ Since we half the exponent in each step, this procedure takes $\\mathcal O(\\log k)$ steps. In each step we perform one or two matrix multiplications of two $n \\times n$ square matrices, which takes (with the naive algorithm) $\\mathcal O(n^3)$ time. Overall this algorithm takes $\\mathcal O(n^3 \\log k)$ time to compute the answer. Full problem Let us now turn our attention back to the problem of computing the number of special trips that begin and end in the same city. There is no simple matrix whose powers correspond to special trips, but we can try to reason about how to describe these trips in terms of the adjacency matrix. Let $S^{(k)}$ be an $n \\times n$ matrix whose $(i, \\, j)$ entry is equal to the number of special trips of length $k$ that start in $i$ and end in $j$. Additionally, let $D$ be the degrees matrix, a diagonal matrix where $D_{ii}$ is equal to the degree of vertex $i$ in $G$. Lemma 2. The following equalities hold. $S^{(1)} = A$. $S^{(2)} = A^2 - D$. $S^{(k)} = S^{(k - 1)} \\cdot A - S^{(k - 2)} \\cdot (D - I)$, for $k > 2$. Proof. For $k = 1$ it is clear that the special trips of length $1$ are equivalent to edges in the graph. For $k = 2$, we know that $A^2$ corresponds to trips of length $2$. Special trips cannot use the same edge twice in a row, but $A^2$ ignores this constraint. However, the length 2 trips that use two edges in a row are exactly the trips that start in a vertex $v$, follow one of the $\\deg(v)$ adjacent edges, where $\\deg(v)$ is the degree of $v$, and then follow that same edge back. The number of such trips is given exactly by $D$, so by subtracting this matrix from the total number of trips of length $2$ we get $S^{(2)} = A^2 - D$. Now consider $k \\ge 3$. Note that $S^{(k - 1)} \\cdot A$ is the number of trips of length $k$ that do not use the same road twice in a row, except maybe on the very last step. This is almost what we want, but we need to subtract the number of trips that do not use the same road twice in a row, except on the very last step. Applying a similar reasoning as in the $k = 2$ case, this is equal to the number of special trips of length $k - 2$ that end at some vertex $v$, then follow one of its $\\deg(v)$ adjacent edges, and finally follow that same edge back. However, we do not need to count the edge that preceded getting to $v$, since that would lead to walking the same edge twice in the second to last step. The number of such trips is given by $S^{(k - 2)} \\cdot (D - I)$, where $D - I$ is the \"degree minus one\" diagonal matrix. So the result follows. $\\blacksquare$ We are still not done because it is not obvious how to solve this recurrence efficiently. Note that this is a linear recurrence, so we can use any linear recurrence solving technique. There are several ways of doing this, but let us consider a matrix exponentiation method. Consider the following block matrix: $L = \\begin{bmatrix} A & -(D - I)\\\\ I & 0 \\end{bmatrix}.$ Note that $L$ is a $2n \\times 2n$ matrix. If we multiply it by some column vector we get: $\\begin{bmatrix} A & -(D - I)\\\\ I & 0 \\end{bmatrix} \\begin{bmatrix} S_1\\\\ S_2 \\end{bmatrix} = \\begin{bmatrix} A S_1 - (D - I) S_2 \\\\ S_1 \\end{bmatrix}.$ In particular, this has the exact form of the recurrence in Lemma 2, which means that the product of $L^{k-2}$ by a column vector with entries $S^{(2)}$ and $S^{(1)}$ will result in a column vector with entries $S^{(k)}$ and $S^{(k - 1)}$. To compute $L^{k-2}$ we can use the same binary exponentiation method from the first section, so overall this method takes $\\mathcal O(n^3 \\log k)$ time.",
    "tags": [
      "dp",
      "graphs",
      "math",
      "matrices"
    ]
  },
  {
    "contest_id": "1662",
    "index": "D",
    "title": "Evolution of Weasels",
    "statement": "A wild basilisk just appeared at your doorstep. You are not entirely sure what a basilisk is and you wonder whether it evolved from your favorite animal, the weasel.\n\nHow can you find out whether basilisks evolved from weasels? Certainly, a good first step is to sequence both of their DNAs. Then you can try to check whether there is a sequence of possible mutations from the DNA of the weasel to the DNA of the basilisk.\n\nYour friend Ron is a talented alchemist and has studied DNA sequences in many of his experiments. He has found out that DNA strings consist of the letters A, B and C and that single mutations can only remove or add substrings at any position in the string (a substring is a contiguous sequence of characters). The substrings that can be removed or added by a mutation are AA, BB, CC, ABAB or BCBC. During a sequence of mutations a DNA string may even become empty.\n\nRon has agreed to sequence the DNA of the weasel and the basilisk for you, but finding out whether there is a sequence of possible mutations that leads from one to the other is too difficult for him, so you have to do it on your own.",
    "tutorial": "To solve the problem we need the following observations. Every mutation is reversible. Hence, instead of trying to find a sequence of mutations of the string $u$ to get to the string $v$, we can try to find a sequence of mutations of the string $u$ and a sequence of mutations of the string $v$ such that both of them are the same after the mutations. In all possible mutations, we never change the parity of the occurrence of a character. Thus, if the parity of the occurrences of $\\texttt{A}$, $\\texttt{B}$ and $\\texttt{C}$ is not the same in $u$ and $v$, there does not exist a sequence of mutations to get from $u$ to $v$. For the rest of the solution we assume that the parities are the same in both strings. We can transform the string $\\texttt{AB}$ to the string $\\texttt{BA}$ via the following sequence of moves: start with $\\texttt{A}\\texttt{B}$, then insert $\\texttt{B}\\texttt{B}$ at the back of the string to get $\\texttt{ABBB}$, then insert the string $\\texttt{ABAB}$ in the second to last position to get $\\texttt{ABBABABB}$. Removing the two occurences of $\\texttt{B}\\texttt{B}$ we get the string $\\texttt{A}\\texttt{A}\\texttt{B}\\texttt{A}$ and then removing $\\texttt{A}\\texttt{A}$ we get to $\\texttt{B}\\texttt{A}$. A similar trick can be done to transform the string $\\texttt{BC}$ to the string $\\texttt{CB}$. While this series of steps might seem magical, viewing the problem as a group theoretic problem (see a later section) gives us this observation almost for free. The observation above tells us that we can move the letter $\\texttt{B}$ to any position we want and can essentially ignore it; let $u'$ and $v'$ be the strings we obtain from $u$ and $v$ when removing all occurrences of $\\texttt{B}$. When ignoring the letter $\\texttt{B}$, the strings $\\texttt{ABAB}$ and $\\texttt{BCBC}$ are the same as the strings $\\texttt{AA}$ and $\\texttt{CC}$, thus we now have strings consisting of the letters $\\texttt{A}$ and $\\texttt{C}$ and we can add and remove substrings of the form $\\texttt{AA}$ and $\\texttt{CC}$. This is a much easier problem. We can iteratively remove occurences of $\\texttt{AA}$ or $\\texttt{CC}$ from $u'$ and $v'$ until no removal is possible anymore. If the strings are the same after the removal, a sequence of mutations is possible, otherwise it is not. Optimizing the runtime. If we remove occurrences of $\\texttt{AA}$ and $\\texttt{CC}$ iteratively the runtime of our algorithm is quadratic (in the length of the strings), which is fast enough to pass. There exists a linear time algorithm: Keep a stack of the substring you visited but could not remove (at the beginning, this is empty). Then iterate through your string. If the letter you currently look at is the same as the last letter in your stack, delete the last letter in your stack. If not add the letter to your stack. Viewing the problem as a group theoretic problem This is a different perspective on the problem and might require some knowledge about groups and their presentations to understand. In the language of groups, the problem statement can be reformulated as follows: Do the words $u$ and $v$ represent the same element in the group $G=\\{\\texttt{A},\\texttt{B}, \\texttt{C}\\mid\\texttt{A}^2 = \\texttt{B}^2=\\texttt{C}^2 = \\texttt{ABAB} = \\texttt{BCBC} = 1\\}$? The words $u$ and $v$ represent the same element if and only if $w = uv^{-1}$ represents the identity in $G$. Furthermore $\\texttt{A}$ and $\\texttt{B}$ commute: $\\texttt{A}^2 = 1$ implies that $\\texttt{A} = \\texttt{A}^{-1}$ and the same holds for $\\texttt{B}$ and $\\texttt{C}$. Thus, $1 = \\texttt{A}\\texttt{B}\\texttt{A}\\texttt{B} = \\texttt{A}\\texttt{B}\\texttt{A}^{-1}\\texttt{B}^{-1}$, which directly implies $\\texttt{AB} = \\texttt{B}\\texttt{A}$. Analogously, we get that $\\texttt{BC} = \\texttt{CB}$. Now the only thing left to check is: Does the letter $\\texttt{B}$ occur evenly many times in $w$? After deleting all occurences of $\\texttt{B}$ from $w$, can we get from $w$ to the empty word by deleting $\\texttt{AA}$ or $\\texttt{CC}$? If the answer to one of those questions is no, then $w$ does not represent the identity. If both answers are yes, $w$ does represent the identity. Some background about the problem. The problem of telling whether two words represent the same element in a group is called the word problem, and is a widely studied problem in Mathematics. While it is proven to be unsolvable for some groups, the group $G$ we are dealing with in this problem is a Coxeter group, where the word problem is always solvable using Tits' algorithm.",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ]
  },
  {
    "contest_id": "1662",
    "index": "E",
    "title": "Round Table",
    "statement": "There are $n$ people, numbered from $1$ to $n$, sitting at a round table. Person $i+1$ is sitting to the right of person $i$ (with person $1$ sitting to the right of person $n$).\n\nYou have come up with a better seating arrangement, which is given as a permutation $p_1, p_2, \\dots, p_n$. More specifically, you want to change the seats of the people so that at the end person $p_{i+1}$ is sitting to the right of person $p_i$ (with person $p_1$ sitting to the right of person $p_n$). Notice that for each seating arrangement there are $n$ permutations that describe it (which can be obtained by rotations).\n\nIn order to achieve that, you can swap two people sitting at adjacent places; but there is a catch: for all $1 \\le x \\le n-1$ you cannot swap person $x$ and person $x+1$ (notice that you \\textbf{can} swap person $n$ and person $1$). What is the minimum number of swaps necessary? It can be proven that any arrangement can be achieved.",
    "tutorial": "Main assumption After playing a bit with the second sample test case one can notice that there are many sequences of swaps of the same length that achieve the same result, and as long as we always swap two people such that the person with a larger number is on the left before the swap, then we always achieve the goal in the minimum number of swaps. Let us first construct a solution which relies on this assumption, and then prove that the assumption is correct. We need to find any way to arrive at the given permutation from the initial one such that in each swap the person with a larger number is on the left, and count the number of swaps needed efficiently. Algorithm We will construct our permutation in steps. After the $i$-th step, the people with numbers from $1$ to $i$ will be in the correct circular order, and the people with numbers from $i+1$ to $n$ will be sitting in the order of their numbers directly to the right of person $i$. In the starting arrangement the condition above is already satisfied for $i=2$, since there is just one circular order for two people. To perform the $(i+1)$-th step, we need to do the following: person $i+1$ is currently sitting to the right of person $i$, but they need to be sitting to the right of some other person $j_i$ which is determined as the closest person on the left of person $i+1$ that has a number between $1$ and $i$. Since we cannot move the person $i+1$ to the left, as we cannot swap person $i$ and person $i+1$, the only way to achieve this is by moving person $i+1$ to the right. But we can't do this directly because person $i+2$ is there, so what we are going to do is move the entire block of people from $i+1$ to $n$ to the right. Moving the block of people from $i+1$ to $n$ by one position to the right takes $n-i$ swaps, and we need to do this $d_i$ times where $d_i$ is the circular distance from person $i$ to person $j_i$ when going to the right, and only considering people with numbers from $1$ to $i$. The total number of swaps can therefore be computed as $\\displaystyle f(p)=\\sum_{i=2}^{n-1}d_i(n-i)$. The numbers $d_i$ can be computed using a standard data structure such as a segment tree, a Fenwick tree, or a balanced search tree in $\\mathcal O(n\\log n)$. Proof of the main assumption Now we need to repay our debts and prove the assumption. It suffices to prove the following. Lemma. If a permutation $q$ differs from a permutation $p$ in only one swap of adjacent elements $a$ (on the left) and $b$ (on the right) such that $a>b$, then $f(q)-f(p)=1$, where $f(p)$ is the number of operations used by the above algorithm. Proof. Indeed, almost all terms in $f(p)$ and $f(q)$ sums will be the same. Which terms are going to differ? The quantity $d_{a-1}$ will increase by $1$, since the person $a$ will now need to travel one more step to the right to overtake $b$. Conversely, $d_a$ will decrease by $1$, since the person $a+1$ will now need to travel one less step to the right as they will have already overtaken $b$ earlier. All other values of $d_i$ will stay unchanged. So $f(q)-f(p)=(n-(a-1))-(n-a)=1$. $\\blacksquare$ By applying the lemma in reverse, we can also see that performing a swap where the largest element is on the right will decrease $f(p)$ by $1$. So every swap either increases or decreases $f(p)$ by $1$, and $f(\\mathrm{id})=0$ ($\\mathrm{id}$ stands for the identity permutation), therefore $f(p)$ is indeed the smallest number of swaps needed to reach permutation $p$, and it does not matter in which order we make the swaps as long as we always make swaps where the person with a larger number is on the left. Parting words This problem was inspired by the following paper, where you can learn more about this setup: Abram, Antoine, Nathan Chapelier-Laget, and Christophe Reutenauer. \"An Order on Circular Permutations.\" The Electronic Journal of Combinatorics (2021): P3-31. The paper also mentions that this setup was used for USAMO 2010, Problem 2. We hope that none of the participants have seen the paper or the USAMO problem before. We found it quite remarkable that the answer is $\\mathcal O(n^3)$ in magnitude but the order of swaps does not matter, just like in the non-circular problem without any restrictions on swaps where one would simply count the number of inversions in a permutation. We hope you enjoyed solving this problem, too!",
    "tags": [
      "math"
    ]
  },
  {
    "contest_id": "1662",
    "index": "F",
    "title": "Antennas",
    "statement": "There are $n$ equidistant antennas on a line, numbered from $1$ to $n$. Each antenna has a power rating, the power of the $i$-th antenna is $p_i$.\n\nThe $i$-th and the $j$-th antenna can communicate directly if and only if their distance is at most the minimum of their powers, i.e., $|i-j| \\leq \\min(p_i, p_j)$. Sending a message directly between two such antennas takes $1$ second.\n\nWhat is the minimum amount of time necessary to send a message from antenna $a$ to antenna $b$, possibly using other antennas as relays?",
    "tutorial": "Let's model the problem as an undirected graph, where the vertex $i$ corresponds to the antenna $i$ and vertices $i$ and $j$ are connected with an edge if and only if the corresponding antennas are able to communicate directly, that is $|i - j| \\leq \\min(p_i, \\, p_j)$. In this formulation, the answer to the question posed in the problem statement is simply the shortest distance between $a$ and $b$. To compute the shortest distance, we would like to be able to construct the graph and run a breadth-first search. Unfortunately, we cannot afford to do that, as the number of edges can be in the order of $n^2$. We need a more efficient approach. We examine two options. Improving the BFS The inefficiency of a breadth-first search on a dense graph lies in the fact that the majority of the traversed edges lead to a vertex that has already been visited. Ideally, for every vertex, we would like to process only one of the incoming edges. Should we achieve this property, the running time would be linear in the number of vertices, not in the number of edges. Let's decompose each edge into two directed edges, one in each direction. As soon as we traverse the first edge incoming to a particular vertex, we remove all other edges incoming to this vertex. This idea leads to the desired property of only processing each vertex once, nevertheless on its own it doesn't affect the time complexity as we still generate the full graph. Let's consider for a brief moment how can we generate the graph in the first place. A naive approach is to consider, for a fixed $i$, all $1 \\leq j \\leq n$ and check whether $i$ and $j$ can communicate with each other. However, we can observe that we do not need to test all $j$'s up to $n$ - it is sufficient to only iterate up to $\\min(n, \\, i + p_i)$, because $|i - j| = j - i \\leq p_i$ must hold. Similarly, a tighter lower bound for the iteration is $\\max(1, \\, i - p_i)$ instead of $i$. We can do even better than that. Define $l_j := j - p_j$. For $j \\in(i, \\, i + p_i]$ to be able to communicate with $i$, we just need $l_j \\leq i$. Similarly, for $j \\in [i - p_i, \\, i)$ we need $r_j := j + p_j \\geq i$. To summarise, we need to find all $j \\in [i - p_i, \\, i)$ such that $r_j \\geq i$ and all $j \\in (i, \\, i + p_i]$ such that $l_j \\leq i$. We can do this by storing the values $r_j$ and $l_j$ in two segment trees that return the minimum and maximum on a queried interval, respectively, together with the index where this minimum or maximum is achieved, and querying the appropriate interval as long as the inequality $r_j \\ge i$ or $l_j \\le i$ holds. Now, recall the previous idea - removing all edges incoming to a vertex once we find its distance from $a$. In this implementation, we can achieve this in $\\mathcal O(\\log n)$ time by simply setting the corresponding $l_j$ to $\\infty$ and $r_j$ to $-\\infty$. Using these techniques, we can process a vertex in $\\mathcal O(d\\log n)$, where $d$ is the out-degree of the vertex when we are processing it. Since, for each vertex, we only process at most a single incoming edge, the total running time is $\\mathcal O(n\\log n)$. Iterating on a restricted problem Let us consider a restricted version of the problem. In this version, antenna $i$ is allowed to send a message to $j$ if $|i - j| \\leq \\min(p_i, \\, p_j)$ and $i < j$. In other words, a message can only be sent to an antenna with a strictly larger index, and never in the opposite direction. This problem can be solved by a single sweep, as follows. Maintain a segment tree $S$ of size $n$, that returns the minimum on an interval, and supports single element update. We process the antennas in order of increasing index. When processing an antenna $i$, we do the following operations: Set $S[i] = \\mathrm{dist}[i]$ where $\\mathrm{dist}[i]$ is the length of the shortest known path from $a$ to $i$. Initially $\\mathrm{dist}[a] = 0$, and all other values are initialised to $\\infty$. For all antennas $j$ such that $j + p_j - 1 = i$ (i.e. $j$ is able to reach $i - 1$ but not $i$), set $S[j] = \\infty$. Set $\\mathrm{dist}[i] = 1 + S.\\mathrm{min}(i-p_i, \\, i)$. The purpose of removing an antenna by setting $S[j] = \\infty$ is evident - as the antennas are processed in order of increasing indices, we know that none of the antennas to be processed can communicate with $j$. The complexity of this algorithm is $\\mathcal O(n \\log n)$. Note that it is trivial to modify this algorithm for a version of the problem where all communication goes to antennas with a lower index instead. How does this help to solve our original problem? We can alternate between the two versions - the one that only allows communication towards antennas with larger indices (i.e. to the right), and the one with smaller ones (i.e. to the left). This process is repeated while the array $\\mathrm{dist}$ is changing. Once a fixed state is reached, we have a correct solution. We argue that only $\\mathcal O(\\log n)$ iterations of this outer loop will be performed, in other words there exists a shortest path that \"changes direction\" at most $\\mathcal O(\\log n)$ times. The basic idea of the proof is that when two successive direction changes are performed, the distances between antennas at least doubled, otherwise there would exist a path of a shorter or equal length with fewer direction changes. The details of the proof are left as an exercise to the reader. All things considered, this yields an $\\mathcal O(n\\log^2 n)$ algorithm, which is sufficient given a careful implementation.",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "implementation",
      "shortest paths"
    ]
  },
  {
    "contest_id": "1662",
    "index": "G",
    "title": "Gastronomic Event",
    "statement": "SWERC organizers want to hold a gastronomic event.\n\nThe location of the event is a building with $n$ rooms connected by $n-1$ corridors (each corridor connects two rooms) so that it is possible to go from any room to any other room.\n\nIn each room you have to set up the tasting of a typical Italian dish. You can choose from $n$ typical Italian dishes rated from $1$ to $n$ depending on how good they are ($n$ is the best possible rating). The $n$ dishes have distinct ratings.\n\nYou want to assign the $n$ dishes to the $n$ rooms so that the number of pleasing tours is maximal. A pleasing tour is a nonempty sequence of rooms so that:\n\n- Each room in the sequence is connected to the next one in the sequence by a corridor.\n- The ratings of the dishes in the rooms (in the order given by the sequence) are increasing.\n\nIf you assign the $n$ dishes optimally, what is the maximum number of pleasing tours?",
    "tutorial": "This is a classical problem in which one must find a \"simple\" characterization of what the optimal solution looks like, and then restrict the search for the maximum to the (much smaller, much more regular) family of instances that satisfy the characterization. In our specific case, the first part of this paradigm is by far the most difficult and the one that requires all the important insights, while the second part can be solved through the application of a standard technique. We are going to split the core of the solution in two parts, the first of which deals with the characterization of optimal solutions. Then, in the second, we will explain how to compute the answer efficiently in the restricted search space and we will discuss some improvements and further considerations. Preliminary observations and notation First, however, let us set up the bases. It goes without saying that we are dealing with a graph - actually, a tree - problem. Also, the statement is deceptively straightforward: assign a permutation of $\\{1, \\, \\dots, \\, n\\}$ to the vertices so as to maximize the number of increasing paths. And here comes the first non-trivial (however simple) idea: we are actually going to consider ways to orient the edges of the tree, and find an orientation that maximizes the number of directed paths; we forget about the vertex numeration altogether. After all, an assignment of the numbers $1, \\, \\dots, \\, n$ naturally induces an orientation of the edges, where edge $(u, \\, v)$ points towards $v$ if $u < v$ and towards $u$ otherwise. This begs the question of whether the converse is also true, i.e., does an orientation of the edges \"induce\" a numbering of the vertices? The answer is, in general, no. Nevertheless, we would still be happy if it were true that every orientation is induced by at least one numbering (for this would mean that, in switching to the orientation perspective, we wouldn't be considering forbidden configurations). Luckily, it is, and it follows immediately from the existence of a topological sorting of the vertices of a directed tree (which is, in fact, a DAG): just number the vertices in their topological order! (Incidentally, note that any topological order works, and since it is generally not unique, neither is the numbering.) From now on, we shall call a path any path in the undirected tree, as opposed to directed path which refers to the underlying orientation of the edges (supposing we have fixed one in the context of the sentence). A single vertex is both a path and a directed path. Given an orientation of the tree, we call its value the number of directed paths it produces; therefore, the problem asks to maximize the value of an orientation. We say that a (directed) path has length $\\ell$ if it is made up of $\\ell$ vertices. Finally, we denote $d(u, \\, v)$ the distance between $u$ and $v$ in the undirected tree. Characterizing the optimal solutions The next two results are crucial. Lemma 1. Fix an orientation of the edges. Suppose there exist four distinct vertices $a$, $b$, $c$ and $d$ such that (refer to the figure below for clarity): there are edges $a \\rightarrow b$ and $c \\rightarrow d$; there is a directed path from $c$ to $b$. Proof. Let's see what happens, in terms of value, when we reverse edge $a \\rightarrow b$ and the subtree rooted at $a$. Let: $A$ be the number of directed paths (in the initial orientation) ending at $a$, including the path of length $1$; $B_{\\mathrm{out}}$ be the number of directed paths of length $\\ge 2$ starting at $b$; $B_{\\mathrm{in}}$ be the number of directed paths of length $\\ge 2$ ending at $b$ that do not go through edge $a \\rightarrow b$. $v \\rightarrow \\cdots \\rightarrow b \\leftarrow a \\leftarrow \\cdots \\leftarrow w,$ With similar reasoning and notation, if we invert the edge $c \\rightarrow d$ and the subtree rooted at $d$, the vaue increases (or decreased) by $\\Delta_2 = D(C_{\\mathrm{out}} - C_{\\mathrm{in}})$. Now, since every directed path beginning at $b$ can be extended to the left until we get to $c$ (i.e. we can pre-append the path $c \\rightarrow \\cdots \\rightarrow b$), and since $c \\rightarrow \\cdots \\rightarrow b$ is itself a path beginning at $c$, it holds $C_{\\mathrm{out}} \\ge B_{\\mathrm{out}} + 1$. Likewise, we can prove $B_{\\mathrm{in}} \\ge C_{\\mathrm{in}} + 1$. Thus, $(B_{\\mathrm{in}} - B_{\\mathrm{out}}) + (C_{\\mathrm{out}} - C_{\\mathrm{in}}) \\ge 2$ and without loss of generality $B_{\\mathrm{in}} - B_{\\mathrm{out}} > 0$, which implies, since $A > 0$, that $\\Delta_1 > 0$ as desired. $\\blacksquare$ From Lemma 1 it follows that, in an orientation that yields the optimal solution, every path \"changes direction\" at most once. Formally: given a path $(v_1, \\, v_2, \\, \\dots, \\, v_k)$, there exists at most one index $2 \\le i \\le k - 1$ such that the path $(v_{i - 1}, \\, v_i, \\, v_{i + 1})$ is not directed. This condition is equivalent to a very simple property which opens up the way to an efficient algorithm to find the solution. Lemma 2. Suppose a directed tree satisfies the aforementioned condition. Then, there exists a (not necessarily unique) vertex $v^*$ such that all paths having $v^*$ as an endpoint are also directed paths. Proof. We shall start by fixing an arbitrary vertex $v$ and rooting the tree at $v$. Call a vertex $u \\ne v$ evil if it has a child $w$ such that the path $(v, \\, \\dots, \\, u, \\, w)$ changes direction at $u$. If there are no evil vertices, $v$ is a valid candidate for $v^*$ and we are done. Otherwise, all evil vertices must lie in the same $v$-subtree. Indeed, if $u$ and $u'$ were two evil vertices belonging to different subtrees, and $w$, $w'$ the respective children, the path $(w, \\, u, \\, \\dots, \\, v, \\, \\dots, \\, u', \\, w')$ would change direction at least twice (see figure below, (a)). Moreover, if $u$ is an evil vertex and $r$ is the root of its subtree, the edge $(v, \\, r)$ must point in a different direction than all other edges incident on $v$. To see why, suppose without loss of generality $v \\rightarrow r$ and $v \\rightarrow r' \\ne r$; then the path $(w, \\, u, \\, \\dots, \\, r, \\, v, \\, r')$ changes direction twice (see figure below, (b)). Thanks to the previous observations, if we replace $v$ with $r$ the set of evil vertices decreases or stays the same. If we repeat this argument while there are evil vertices, we will produce a downward path in the tree rooted at $v$, which must stop eventually, at which point the number of evil vertices must vanish. $\\blacksquare$ Thanks to Lemmas 1 and 2 combined, we know that any optimal orientation admits the existence of a vertex $v^*$ satisfying the property of Lemma 2. This makes us finally able to tackle the problem algorithmically. Computing the maximum Call a vertex $v^*$ that satisfies the property of Lemma 2 a crossroad. We are going to iterate over all $n$ vertices and find the maximum value of an orientation where said vertex is a crossroad. Thus, fix a vertex $v^*$ and consider the $\\deg(v^*)$ subtrees the tree gets split into if we erase $v^*$. In an optimal orientation, in each subtree all edges point either \"inwards\" or \"outwards\": let $S$ be the sum of the sizes of subtrees of the first kind, and $T$ be the sum of the sizes of the subtrees of the second kind. Of course, $S + T = n - 1$. Let's calculate the value of such an orientation. There are $n$ directed paths having $v^*$ as an endpoint. The directed paths lying entirely in one subtree are $\\displaystyle \\sum_{v \\ne v^*} d(v^*, \\, v)$. Finally, the paths starting in a subtree of the first kind and ending in a subtree of the second kind contribute with an additional $S \\cdot T$ term. Observe that the first two terms are independent of $S$ and $T$. It is trivial to compute the sizes of the subtrees in $\\mathcal O(\\deg(v^*))$ after preprocessing. Furthermore, the sum of distances can be updated in $\\mathcal O(1)$ when moving from $v^*$ to one of its neighbors. As for the third term, it is clear that it is maximized when $S$ and $T$ are as close as possible to $\\frac{n - 1}{2}$. If one of the subtrees has size $k \\ge \\frac{n}{2}$ (there can only be one of those), the way of doing so is trivial: just orient the edges of the big subtree one way, and all other edges the other way, so that $ST = k(n - 1 - k)$. The matter is more complicated if all subtrees have sizes smaller than $\\frac{n}{2}$. In this case, $v^*$ is a centroid of the tree. Recall that any tree has exactly one or two centroids - and the latter can only occur if $n$ is even. What we are dealing with is an instance of the knapsack problem: we are given positive integers $k_1, \\, \\dots, \\, k_{\\deg(v^*)}$ - the sizes of the subtrees - whose sum is $n - 1$, and we shall find a subset whose sum is as close as possible to $\\frac{n - 1}{2}$. The naive dynamic programming solution runs in $\\mathcal O(n^2)$ at worst (with $\\mathcal O(n)$ space), way too slow for our purposes. We can optimize the runtime, reducing it by a factor $32$, via the use of bitsets. This is still not enough. There is a standard, yet somewhat advanced, trick to speed the algorithm up to $\\mathcal O\\left(\\frac{n\\sqrt{n}}{\\mathrm{sizeof}(\\mathrm{int})}\\right)$. We won't go over it here, but you can find a complete tutorial in this Codeforces blog entry (under Subset Sum Speedup 1), together with a number of other interesting related techniques. Since we only need to run this algorithm at most twice, this final optimization, carefully implemented, does the trick. Finally, let's comment further on the nature of the characterization. So far, we know very little about the crossroad $v^*$, but intuitively it makes sense that it should be \"in the middle\" of the tree in order to yield an optimal solution. Lemma 3. There is an optimal solution where at least one centroid of the tree is a crossroad. Proof. Consider an optimal orientation where a vertex $v^*$, which is not a centroid, is a crossroad. Let $\\tau$ be the subtree of size $\\ge \\frac{n}{2}$. We have already observed that all edges of $\\tau$ must point (WLOG) toward $v^*$, and all other edges away from $v^*$. Now let $v$ be the neighbor of $v^*$ belonging to $\\tau$. If we make $v$ a crossroad, by inverting edge $v \\rightarrow v^*$ and keeping the orientations of all other edges, a simple computation shows that the value of the new configuration has not decreased. We can therefore iterate until we reach a centroid. $\\blacksquare$ Although this result is not necessary to solve the problem, it is relatively easy to guess and prove, and it simplifies the implementation. One can even prove this slightly stronger conclusion: for each centroid, there is an optimal orientation in which it is a crossroad. [It was briefly considered whether to give this problem with $n \\le 10^7$. It turns out that the \"slow\" part of the algorithm is not the optimized knapsack, but rather the tree traversal needed to find the centroid. To fit the new constraint, one must come up with a way to do this without any traversal. Taking a look at the input format might be a good starting point...]",
    "tags": [
      "dp",
      "greedy",
      "trees"
    ]
  },
  {
    "contest_id": "1662",
    "index": "H",
    "title": "Boundary",
    "statement": "Bethany would like to tile her bathroom. The bathroom has width $w$ centimeters and length $l$ centimeters. If Bethany simply used the basic tiles of size $1 \\times 1$ centimeters, she would use $w \\cdot l$ of them.\n\nHowever, she has something different in mind.\n\n- On the interior of the floor she wants to use the $1 \\times 1$ tiles. She needs exactly $(w-2) \\cdot (l-2)$ of these.\n- On the floor boundary she wants to use tiles of size $1 \\times a$ for some positive integer $a$. The tiles can also be rotated by $90$ degrees.\n\nFor which values of $a$ can Bethany tile the bathroom floor as described? Note that $a$ can also be $1$.",
    "tutorial": "First, observe that we can tile any rectangle with tiles of size $1 \\times 1$. From now on, we will consider a fixed $a > 1$. Let's investigate what happens in the corners of the rectangle. Each corner is covered either by a tile that is placed horizontally, or by a tile that is placed vertically. Below is an example of one of $2^4 = 16$ possibilities, with the corner tiles in gray. Once we place those tiles (up to $4$, fewer if the tile length is greater than $\\frac{w}{2}$ or $\\frac{l}{2}$) the positions of the rest are uniquely determined. We can now put four constraints on the value of $a$, one for each side of the rectangle. These constraints are of form $a \\mid w - x$ or $a \\mid l - x$, where $\\mid$ is the \"divides without remainde\" relation, and $x$ is the number of positions on that side that are covered by a tile placed in a perpendicular direction, e.g. a vertical tile on a horizontal side. Clearly, this can only happen in the corners of the rectangle, hence $x$ is between $0$ and $2$ for all sides. In the above figure, the top side yields the constraint $a \\mid w - 0$, the bottom one $a \\mid w - 2$, and both the left and right sides $a \\mid l - 1$. Put together, we have a necessary condition $a \\mid \\gcd(w - 0, \\, w - 2, \\, l - 1, \\, l - 1)$, where $\\gcd$ is the greatest common divisor. Clearly, the condition is also sufficient, i.e. for an $a$ fulfilling this divisibility there is a rectangle tiling. To summarise, we consider all $16$ possibilities for the tile orientations in the corners, find the $\\gcd$ of the constraints using Euclidean algorithm, and then compute its divisiors by a trial division. Finally, we return the sorted set of all the divisors. The total time complexity is $\\mathcal O(\\sqrt {\\min(w, \\, l)})$ per test case, dominated by the trial division. Note that some of the $16$ cases are the same up to mirroring or rotation, and some are clearly impossible. Hence we only need to factor the following values: $\\gcd(w - 1, \\, l - 1)$ $\\gcd(w, \\, l - 2)$ $\\gcd(w - 2, \\, l)$ $\\gcd(w - 1, \\, l - 2, \\, l)$ $\\gcd(w - 2, \\, w, \\, l - 1)$ The last two can only be $1$ or $2$, and if they are both $1$, this implies that one of the first three $\\gcd$s is divisible by $2$. Therefore $a = 2$ is always a solution - we can simply insert it to the solution set, and only compute and factor the first three $\\gcd$s. This does not change the asymptotic time complexity, nevertheless it is a useful optimisation.",
    "tags": [
      "brute force",
      "math"
    ]
  },
  {
    "contest_id": "1662",
    "index": "I",
    "title": "Ice Cream Shop",
    "statement": "On a beach there are $n$ huts in a perfect line, hut $1$ being at the left and hut $i+1$ being $100$ meters to the right of hut $i$, for all $1 \\le i \\le n - 1$. In hut $i$ there are $p_i$ people.\n\nThere are $m$ ice cream sellers, also aligned in a perfect line with all the huts. The $i$-th ice cream seller has their shop $x_i$ meters to the right of the first hut. All ice cream shops are at distinct locations, but they may be at the same location as a hut.\n\nYou want to open a new ice cream shop and you wonder what the best location for your shop is. You can place your ice cream shop anywhere on the beach (not necessarily at an integer distance from the first hut) as long as it is aligned with the huts and the other ice cream shops, even if there is already another ice cream shop or a hut at that location. You know that people would come to your shop only if it is strictly closer to their hut than any other ice cream shop.\n\nIf every person living in the huts wants to buy exactly one ice cream, what is the maximum number of ice creams that you can sell if you place the shop optimally?",
    "tutorial": "Suppose there are ice cream shops located $a$ and $b$ meters to the right of the first hut, such that $a < b$. If we place our ice cream shop in any location in the interval $[a, \\, b]$ it can only be strictly closer to huts located in the interval $(a, \\, b)$, since any hut located at or before $a$ will be closer to the ice cream shop located at $a$ and any hut located at or after $b$ will be closer to the ice cream shop located at $b$. We now present two approaches to solve the problem starting from this observation. First solution Let $a < b$ be the positions of two ice cream shops, and let us further assume that there is no other ice cream shop between $a$ and $b$. Of course, it is never convenient to put the new shop at $a$ or $b$. What happens if we place our new shop at $s \\in (a, \\, b)$? It is easy to see that the only huts whose people will buy ice creams are those in the open interval $\\left(\\frac{a + s}{2}, \\, \\frac{s + b}{2}\\right)$. Notice that this interval has length $\\frac{s + b}{2} - \\frac{a + s}{2} = \\frac{b - a}{2}$, i.e., half the length of $(a, \\, b)$, which is independent of $s$. On the other hand, consider an interval $(l, \\, r)$ such that $a \\le l < r \\le b$ and $r - l = \\frac{b - a}{2}$. If we choose $s = 2l - a$, the interval $\\left(\\frac{a + s}{2}, \\, \\frac{s + b}{2}\\right)$ is exactly $(l, \\, r)$. This means that for every interval $(l, \\, r)$ of length $\\frac{b - a}{2}$ which lies entirely in $(a, \\, b)$, it is possible to achieve a total number of ice creams given by $f(l, \\, r) := \\sum_{100i \\, \\in \\, (l, \\, r)} p_{i + 1}.$ Thus the answer is the maximum of $f(l, \\, r)$, over all intervals such that there exist $a$ and $b$ as above and $r - l \\le \\frac{b - a}{2}$. Also notice that we can restrict our search to the intervals with $l = 100k - \\frac{1}{2}$ for some $0 \\le k \\le n - 1$. We can therefore proceed as follows. Iterate over $k = 0, \\, \\dots, \\, n - 1$. For each $k$, find the greatest $x_j < 100k$. This can be done in amortized constant time - or via binary search - after sorting the $x_j$'s. Compute $f(l, \\, r)$, where $l = 100k - \\frac{1}{2}$ and $r = \\min\\left(x_{j + 1}, \\, l + \\frac{x_{j + 1} - x_j}{2}\\right)$ (assume the $x_j$'s are sorted). This is easy to do having precomputed the prefix sums of $p_1, \\, \\dots, \\, p_n$. Return the maximum of all these values. One must be careful with \"boundary conditions\", that is, values of $k$ such that $100k$ lies to the left or to the right of all ice cream shops. These are best handled by introducing two dummy shops at positions $-\\infty$ and $+\\infty$. The solution has $\\mathcal O(n + m\\log m)$ time complexity and $\\mathcal O(n + m)$ space complexity. Second solution Pick again two ice cream shops at $a < b$, with no other ice cream shops in between, and consider a hut located at $h$ such that $a < h < b$. If we place our shop in $s$ such that $s$ is between $a$ and $h$, then we will always be closer to $h$ than the ice cream shop located at $a$. However, we are only closer than the ice cream shop at $b$ if the distance from $s$ to $h$ is smaller than the distance from $h$ to $b$. Formally this means $h - s < b - h$. If we rearrange this expression, we conclude that we will be closer to $h$ if $s > 2h - b$. Analogously, if we place our shop in $s$ such that $s$ is between $h$ and $b$, we will be closer to $h$ if $s < 2h - a$. Hence, we conclude that if we want to be closer to $h$ then we have to place our shop in the interval $(2h - b, \\, 2h - a)$ (note that this is an open interval since we want to be strictly closer to $h$). Using this idea, we can now compute for every hut $h$ an interval such that if we place our shop in any point in that interval then our shop will be the closest to hut $h$. Let us assume we have all these intervals, how do we determine the optimal solution from this information? Notice that the optimal solution is a point that maximizes the sum of the $p_i$ of all the intervals it is contained in. We can find this maximum sum efficiently using a sweep-line approach. Picture a vertical line that is going to sweep through all of these intervals from left to right. As this line moves we want to keep the sum of the $p_i$ corresponding to the intervals it currently intersects, so we store that value in a counter and whenever the line reaches the starting point of an interval we add its value to the counter, conversely whenever it reaches the endpoint of an interval we subtract its value from the counter. The solution is the maximum value the counter achieves during this process. To implement this efficiently, the only thing we need to observe is that the only relevant \"events\" to this procedure are the start- and endpoints of intervals. So our sweep-line algorithm can be implemented as follows: for every interval $(l_i, \\, r_i)$ corresponding to hut $p_i$ add a point $(l_i, \\, p_i)$ and a point $(r_i, \\, -p_i)$ to a list of points. Sort this list according to the first component. Iterate through the sorted points and store a counter (initially $0$). Whenever we reach a point $(a, \\, b)$ add $b$ to the counter. This requires time $\\mathcal O(n \\log n)$ since we have to sort all of the $2n$ \"event\" points and then iterate through them once. Before doing that, however, we need to compute each hut's interval. To do so we have to determine the closest ice cream shops $a$ and $b$ such that $a < h$ and $b > h$ and then the interval is given by $(2h - b, \\, 2h - a)$. If we sort the $x_i$ locations of all the ice cream shops we can find this using binary search or by iterating through the huts and ice cream shops simultaneously (this is also known as a two pointers technique). The time complexity of the binary search method is $\\mathcal O((m + n) \\log m)$, since we first sort the $x_i$ and then for each hut we perform one binary search. The time complexity of the two pointers method is $\\mathcal O(m \\log m + n)$, since we first sort the $x_i$ and then iterate through all the $n$ huts and $m$ ice cream shops once. Combining all of this we get a solution that runs in $\\mathcal O(m\\log m + n \\log n)$ time.",
    "tags": [
      "brute force",
      "implementation",
      "sortings"
    ]
  },
  {
    "contest_id": "1662",
    "index": "J",
    "title": "Training Camp",
    "statement": "You are organizing a training camp to teach algorithms to young kids. There are $n^2$ kids, organized in an $n$ by $n$ grid. Each kid is between $1$ and $n$ years old (inclusive) and any two kids who are in the same row or in the same column have different ages.\n\nYou want to select exactly $n$ kids for a programming competition, with exactly one kid from each row and one kid from each column. Moreover, kids who are not selected must be either older than both kids selected in their row and column, or younger than both kids selected in their row and column (otherwise they will complain). Notice that it is always possible to select $n$ kids satisfying these requirements (for example by selecting $n$ kids who have the same age).\n\nDuring the training camp, you observed that some kids are good at programming, and the others are not. What is the maximum number of kids good at programming that you can select while satisfying all the requirements?",
    "tutorial": "In this task, you are given the ages of $n^2$ kids as a Latin square $S$ ($n \\times n$ grid such that each row and each column contains all the integers from $1$ to $n$), and you are asked to find a subset containing exactly one kid from each row/column, satisfying a certain \"stability\" constraint, and maximizing the number of kids who are good at programming. Definitions A solution $\\mu \\subseteq \\{1, \\, \\dots, \\, n\\}^2$ is a subset of kids containing exactly one kid from each row/column. For convenience, we will denote $\\mu_i$ the unique $j$ such that $(i, \\, j) \\in \\mu$, and $\\mu^j$ the unique $i$ such that $(i, \\, j) \\in \\mu$. We say that a kid $(i, \\, j)$ is blocking a solution $\\mu$ if the age of $(i, \\, j)$ is between the ages of $(i, \\, \\mu_i)$ and $(\\mu^j, \\, j)$, that is if $(S_{i,j} - S_{i,\\mu_i})(S_{i,j} - S_{\\mu^j,j}) < 0$. We say that a solution is stable if there is no blocking kid. To understand what stability means, we will have a closer look at the second sample. As a first attempt, we can try to draw the graph $G$ containing pairs of kids who cannot belong to the same solution, either because they are on the same row/column (black edges), or because they would create a blocking kid (gray edges). Kids who are good at programming are colored in gray. Stable solutions correspond to maximum (cardinality $n$) independent sets in $G$, which (unfortunalely) are difficult to compute without additional structure, especially because $G$ may contain $\\Theta(n^4)$ edges. Reducing the problem to maximum-weight antichain We came to the conclusion that we need to understand the structure of $G$. For that matter, define the directed acyclic graph $\\vec G$, which has an edge from kid $a$ to kid $b$ iff they are on the same row/column and $a$ is younger that $b$. The graph $\\vec G$ has $\\Theta(n^3)$ edges, and an important observation is that edges of $G$ corresponds to paths of length $\\leq 2$ in $\\vec G$. After looking at length-$2$ paths, we may try to look at longer paths. For that matter, denote $\\vec G^{(k)}$ the $k$-th power of $\\vec G$, that is the graph which contains an edge from kid $a$ to kid $b$ iff $\\vec G$ contains a path of length $\\leq k$ from $a$ to $b$. In particular, $\\vec G^{(2)}$ is an orientation of the graph $G$ defined in the previous section. Lemma 1. For all $k \\geq 2$, the following properties are satisfied. Any independent set of size $n$ in $\\vec G^{(k)}$ is a stable solution. Maximum independent sets of $\\vec G^{(k)}$ have size $n$. Stable solutions are independent sets in $\\vec G^{(k)}$. Proof. To prove (1), observe that $\\vec G \\subseteq \\vec G^{(k)}$ (independent sets contain exactly one kid per row/column) and $\\vec G^{(2)} \\subseteq \\vec G^{(k)}$ (independent sets are stable). To prove (2), observe that a choice of kids having the same age is an independent set, and no set of size $> n$ can be independent (by the pigeonhole principle, some row/column would contain $2$ kids). We prove (3) by induction on $k$. It is true when $k = 2$ by construction. Now choose the smallest $k > 2$ such that there is a path $a_1 \\rightarrow a_2 \\rightarrow \\cdots \\rightarrow a_k$ in $\\vec G$ where $a_1 \\in \\mu$ and $a_k \\in \\mu$ for some stable solution $\\mu$. By minimality of $k$, we may assume (without loss of generality) that $a_1 = (i, \\, j') \\in \\mu$, $a_2 = (i, \\, j) \\notin \\mu$ and $a_3 = (i', \\, j) \\notin \\mu$. Let $a_1' = (\\mu^j, \\, j) \\in \\mu$ be the kid selected in row $j$. By stability of $\\mu$, kid $a_2$ is older than both $a_1$ and $a_1'$, therefore there is an edge $a_1' \\rightarrow a_3$, which contradicts the minimality of $k$. $\\blacksquare$ An antichain of a partially ordered set is a subset of elements such that no pair of elements are comparable (using transitivity). As a corollary of Lemma 1, stable solutions are exactly the maximum antichains of the partial order induced by $\\vec G$. Because antichains are defined using the transitive closure, we can simplify the definition of $\\vec G$ while keeping the same transitive closure, so that there is an edge from kid $a$ to kid $b$ iff they are on the same row/column and $a$ is exactly $1$ year younger than $b$. This new definition of $\\vec G$ has $\\Theta(n^2)$ edges, while keeping the property that stable solutions correspond to maximum antichains. Finally, remember that our goal was to find the \"best\" stable solution in terms of number of kids who are good at programming. Thus, we give each kid a weight between $0$ and $M=1$, and our goal is to find a maximum-weight antichain, under the constraint that it is a maximum-cardinality antichain. We deal with the cardinality constraint by adding a large weight $\\omega > n\\cdot M$ to each kid, which reduces our problem to finding the maximum-weight antichain. Reducing maximum-weight antichain to maximum flow Finally, we are going to reduce the maximum-weight antichain problem to the maximum flow problem. Define a flow graph $\\vec F$, with two special nodes $s$ (source) and $t$ (target), and two copies $v_1\\in V_1$ and $v_2\\in V_2$ of each node $v$ from $\\vec G$. For each node $v$ of weight $w(v)$ in $\\vec G$, add two edges $s \\rightarrow v_1$ and $v_2 \\rightarrow t$ with capacity $w(v)$. For each edge $u \\rightarrow v$ in $\\vec G$, add three edges $u_1 \\rightarrow v_1$, $u_2 \\rightarrow v_2$ and $u_1 \\rightarrow v_2$ with infinite capacity. Using the max-flow min-cut theorem, the maximum $s$-$t$ flow is equal to the minimum $s$-$t$ cut. Our reduction is easier to understand when looking at cuts (see picture below). Recall that a cut is partition $(\\mathcal S, \\, \\mathcal T)$ of the nodes, where $s\\in \\mathcal S$ and $t\\in \\mathcal T$. Given an antichain $A$ in $\\vec G$, denote $X$ the set of vertices before $A$ and $Y$ the set of vertices after $A$. We define $\\mathcal S := \\{s\\} \\cup \\{v_1 : v\\in A\\cup Y\\} \\cup \\{v_2 : v\\in Y\\}$ and $\\mathcal T := \\{t\\} \\cup \\{v_1 : v\\in X\\} \\cup \\{v_2 : v\\in X\\cup A\\}$. The weight of this cut is exactly equal to $\\sum_{v\\notin A} w(v)$. Conversely, let $(\\mathcal S, \\, \\mathcal T)$ be a cut of finite weight. We first show that $\\mathcal S\\cap V_1$ must be downward closed (if $u_1 \\in \\mathcal S$ and $u_1 \\rightarrow v_1$, then $v_1\\in \\mathcal S$) and $\\mathcal T \\cap V_2$ must be upward closed (if $v_2 \\in \\mathcal T$ and $u_2 \\rightarrow v_2$ then $u_2\\in \\mathcal T$). Then, $A := \\{v : v_1\\in \\mathcal S \\: \\mathrm{and} \\: v_2\\in \\mathcal T\\}$ is an antichain, and the cut has weight $\\sum_{v\\notin A} w(v)$. Therefore, computing a maximum weight antichain in $\\vec G$ is equivalent to computing a minimum weight cut in $\\vec F$, which can be done by computing a maximum flow in $\\vec F$. In terms of complexity, $\\vec F$ has $2+n^2$ nodes and $\\Theta(n^2)$ edges, which should make any reasonable flow algorithm (such as Edmonds-Karp or Dinic's algorithm) efficient enough. Dilworth's theorem The reduction from the previous section can be seen as an application of Dilworth's theorem. In the unweighted case, the theorem states that the maximal size of an antichain is equal to the minimum number of paths necessary to cover all elements. Moreover, minimum path cover in a directed acyclic graph can be reduced to maximum cardinality matching in a bipartite graph, which in turn can be reduced to maximum flow. In the weighted case, a generalization of Dilworth's theorem states that the maximal weight of an antichain is equal to the minimum number of paths needed to cover each element as many times as its weight. Then, this weighted path cover problem can be reduced to maximum flow. The resulting flow instance is similar to $\\vec F$, however, there is no edge within sets $V_1$ and $V_2$, and edges from $V_1$ to $V_2$ correspond to the transitive closure of $\\vec G$. This gives a flow instance with $\\Theta(n^4)$ edges, which is too slow for this problem. Observing that we can avoid computing the transitive closure of $\\vec G$ by adding edges within $V_1$ (and $V_2$) yields the solution described in the previous section. Stable matchings In this editorial, we defined the notions of blocking kids and stable solutions. These choices of terms are deliberate, because this task is in fact a (hopefully well) hidden stable marriage problem. Lemma 2. Stable solutions are exactly solution of the stable marriage problem where: rows have preferences over columns: row $i$ ranks column $j$ in $M_{i,j}$-th position; columns have preferences over rows: column $j$ ranks row $i$ in $(n + 1 - M_{i,j})$-th position; a row-column pair is blocking if both prefer each other to their respective partners; a matching is stable if it contains no blocking pair. Proof. The only difference between the task statement and the definition of stability given in Lemma 2 is that a kid $(i, \\, j)$ is blocking iff $M_{\\mu^j,j} < M_{i,j} < M_{i,\\mu_i}$ (type 1) or $M_{i,\\mu_i} < M_{i,j} < M_{\\mu^j,j}$ (type 2), whereas a row-column pair is blocking (in the stable marriage instance) iff $M_{\\mu^j,j} < M_{i,j} < M_{i,\\mu_i}$ (type 1). Interestingly, one can show that if a solution has a type 2 blocking kid, then it also has a type 1 blocking kid (left as an exercise). $\\blacksquare$ In the stable marriage problem, one stable matching is optimal for the rows (kids of age $1$) and one stable matching is optimal for the columns (kids of age $n$). The set of stable matchings has a distributive lattice structure, which can be represented by closed subsets of a directed graph (closely related to $\\vec G$). The problem of finding a maximum-weight stable matching can be reduced to the closure problem, which can itself be reduced to maximum flow. Let us finish this editorial with a few fun facts. In the second sample used in this task, $n$ is a power of $2$, each kid $(i, \\, j)$ has age $1 + (i - 1) \\wedge (j - 1)$, and the number of stable matchings is given by A005154. This family of instance was first proposed by Donald Knuth, who conjectured that it maximizes the number of stable matchings (still open).",
    "tags": [
      "flows",
      "graphs"
    ]
  },
  {
    "contest_id": "1662",
    "index": "K",
    "title": "Pandemic Restrictions",
    "statement": "After a long time living abroad, you have decided to move back to Italy and have to find a place to live, but things are not so easy due to the ongoing global pandemic.\n\nYour three friends Fabio, Flavio and Francesco live at the points with coordinates $(x_1, y_1), (x_2, y_2)$ and $(x_3, y_3)$, respectively. Due to the mobility restrictions in response to the pandemic, meetings are limited to $3$ persons, so you will only be able to meet $2$ of your friends at a time. Moreover, in order to contain the spread of the infection, the authorities have imposed the following additional measure: for each meeting, the sum of the lengths travelled by each of the attendees from their residence place to the place of the meeting must not exceed $r$.\n\nWhat is the minimum value of $r$ (which can be any nonnegative real number) for which there exists a place of residence that allows you to hold the three possible meetings involving you and two of your friends? Note that the chosen place of residence need not have integer coordinates.",
    "tutorial": "Let us start with some definitions that will make the presentation clearer. Given three points $X, Y$ and $Z$ in the plane, let $f(X, \\, Y, \\, Z)$ be the minimum of $\\overline{XP}+\\overline{YP}+\\overline{ZP}$ over all points $P$. It is well known that this minimum actually exists and is achieved at a unique point called the Fermat point of the triangle $XYZ$. For fixed $X$ and $Y$, let $f_{XY}(Z) := f(X, \\, Y, \\, Z)$ and define $g(W) := \\max(f_{AB}(W), \\, f_{AC}(W), \\, f_{BC}(W)),$ For a given parameter $r$, the condition that $Z$ is a valid residence point is equivalent to $g(Z) \\leq r$. Thus, no valid residence point exists if and only if $\\min g > r$, and therefore the minimum value of $r$ that works is equal to the minimum of $g$ over all points of the plane. We claim that $g$ is convex, hence this minimum exists and we can find it efficiently. This relies on the following two observations: The pointwise maximum of a finite set of convex functions is convex. The function $f_{XY}$ is convex. The first observation is a standard fact. For the second observation, let $X, \\, Y$ be two points, $0 \\leq t \\leq 1$, and let $P, \\, Q$ be the respective Fermat points of the triangles $ABX$ and $ABY$. Then, denoting $Z = tX + (1-t)Y$ and $R = tP + (1-t)Q$, we have that $\\overline{AR} = |A - tP - (1-t)Q| \\leq t \\overline{AP} + (1-t)\\overline{AQ},$ $\\overline{BR} = |B - tP - (1-t)Q| \\leq t \\overline{BP} + (1-t)\\overline{BQ},$ $\\overline{ZR} = |t(X-P) + (1-t)(Y-Q)| \\leq t \\overline{XP} + (1-t)\\overline{YQ},$ $f_{AB}(Z) \\leq \\overline{AR}+\\overline{BR}+\\overline{ZR} \\leq t f_{AB}(X) + (1-t) f_{AB}(Y).$ In view of these facts, if we know how to compute $f(X, \\, Y, \\, Z)$ efficiently we can solve the problem with a double ternary search on $g$. There are ways to achieve this in $\\mathcal O(1)$ time by distinguishing two cases: If one of the angles of triangle $XYZ$ is greater than $2 \\pi / 3$, then the corresponding vertex is the Fermat point. Otherwise the Fermat point can be computed using the construction of the Napoleon triangle, or the sum of its distances can be computed more straightforwardly using the following formula: $f(X, \\, Y, \\, Z) = \\sqrt{\\frac{a^2+b^2+c^2+4\\sqrt{3}S}{2}}.$ (Here $a, \\, b, \\, c$ are the sidelengths and $S$ is the area of the triangle.) $f(X, \\, Y, \\, Z) = \\sqrt{\\frac{a^2+b^2+c^2+4\\sqrt{3}S}{2}}.$",
    "tags": [
      "geometry",
      "ternary search"
    ]
  },
  {
    "contest_id": "1662",
    "index": "L",
    "title": "Il Derby della Madonnina",
    "statement": "The derby between Milan and Inter is happening soon, and you have been chosen as the assistant referee for the match, also known as linesman. Your task is to move along the touch-line, namely the side of the field, always looking very carefully at the match to check for offside positions and other offences.\n\nFootball is an extremely serious matter in Italy, and thus it is fundamental that you keep very close track of the ball for as much time as possible. This means that you want to maximise the number of kicks which you monitor closely. You are able to monitor closely a kick if, when it happens, you are in the position along the touch-line with minimum distance from the place where the kick happens.\n\nFortunately, expert analysts have been able to accurately predict all the kicks which will occur during the game. That is, you have been given two lists of integers, $t_1, \\ldots, t_n$ and $a_1, \\ldots, a_n$, indicating that $t_i$ seconds after the beginning of the match the ball will be kicked and you can monitor closely such kick if you are at the position $a_i$ along the touch-line.\n\nAt the beginning of the game you start at position $0$ and the maximum speed at which you can walk along the touch-line is $v$ units per second (i.e., you can change your position by at most $v$ each second). What is the maximum number of kicks that you can monitor closely?",
    "tutorial": "Let $x_i := v t_i - a_i$ and $y_i := v t_i + a_i$ for $i = 1, \\, \\ldots, \\, n$. The main observation to solve this problem is that a sequence of kicks with indices $i_1, \\, \\ldots, \\, i_k$ can be seen (in this order and starting from the first one) if and only if both sequences $x_{i_1}, \\, \\ldots, \\, x_{i_k}$ and $y_{i_1}, \\, \\ldots, \\, y_{i_k}$ are nondecreasing. To see this, observe that $x_i \\leq x_j \\iff v t_i - a_i \\leq v t_j - a_j \\iff a_j - a_i \\leq v(t_j - t_i)$ $y_i \\leq y_j \\iff v t_i + a_i \\leq v t_j + a_j \\iff a_i - a_j \\leq v(t_j - t_i).$ $t_i = \\frac{x_i + y_i}{2 v},$ In order to impose the condition that the events can be reached starting from position $0$ at time $0$, it is enough to remove all points which cannot be reached from the origin, that is, with $|a_i| > v t_i$. We will assume that these events have been eliminated and still denote by $n$ the total number of events. We have thus reduced the problem to finding the longest increasing subsequence of the $y$-values when ordered by increasing $x$-value. More precisely, let $(p_1, \\, \\ldots, \\, p_n)$ be the permutation of $(1, \\, \\ldots, \\, n)$ such that $i < j \\implies x_{p_i} < x_{p_j} \\text{ or } (x_{p_i} = x_{p_j} \\text{ and } y_{p_i} < y_{p_j}).$ There are classical algorithms to solve this efficiently in $\\mathcal O(n \\log n)$ time. For instance, this complexity is achieved by an approach that processes the elements from left to right and uses binary searches to update the value of the smallest possible last element of a length-$k$ increasing subsequence in every prefix for every $k$.",
    "tags": [
      "data structures",
      "dp",
      "math"
    ]
  },
  {
    "contest_id": "1662",
    "index": "N",
    "title": "Drone Photo",
    "statement": "Today, like every year at SWERC, the $n^2$ contestants have gathered outside the venue to take a drone photo. Jennifer, the social media manager for the event, has arranged them into an $n\\times n$ square. Being very good at her job, she knows that the contestant standing on the intersection of the $i$-th row with the $j$-th column is $a_{i,j}$ years old. Coincidentally, she notices that no two contestants have the same age, and that everyone is between $1$ and $n^2$ years old.\n\nJennifer is planning to have some contestants hold a banner with the ICPC logo parallel to the ground, so that it is clearly visible in the aerial picture. Here are the steps that she is going to follow in order to take the perfect SWERC drone photo.\n\n- First of all, Jennifer is going to select four contestants standing on the vertices of an axis-aligned rectangle.\n- Then, she will have the two younger contestants hold one of the poles, while the two older contestants will hold the other pole.\n- Finally, she will unfold the banner, using the poles to support its two ends. Obviously, this can only be done if the two poles are parallel and \\textbf{do not cross}, as shown in the pictures below.\n\nBeing very indecisive, Jennifer would like to try out all possible arrangements for the banner, but she is worried that this may cause the contestants to be late for the competition. How many different ways are there to choose the four contestants holding the poles in order to take a perfect photo? Two choices are considered different if at least one contestant is included in one but not the other.",
    "tutorial": "For each $i = 1, \\, \\ldots, \\, n^2$, let: $s_i$ denote the $i$-year-old contestant; $u_i$ be the number of contestants on the same row as $s_i$ who are (strictly) under $i$ years old; $v_i$ be the number of contestants on the same column as $s_i$ who are (strictly) under $i$ years old. Let $A$ be the answer to the problem, i.e. the number of ways to choose four contestants so that the poles do not cross. We claim that $2A=\\sum_{i=1}^{n^2} \\: [u_i(n - 1 - v_i) + (n - 1 - u_i)v_i].$ Given an axis-aligned rectangle, we say that a contestant $s$ standing on one if its vertices is intermediate if exactly one of the two contestants on vertices adjacent to $s$ is younger than $s$. Rectangles in which the poles don't cross can be characterised by the fact that exactly two of the contestants on their vertices are intermediate (see figure (a) below for an example). On the contrary, rectangles in which the poles do cross have no intermediate contestants (figure (b)). The right-hand side of the equation is the sum over all contestants $s$ of the number of rectangles for which $s$ is intermediate. Therefore, by the previous remark, this summation equals twice the number of rectangles with non-crossing poles, i.e. twice the answer to the problem.",
    "tags": [
      "combinatorics",
      "math",
      "sortings"
    ]
  },
  {
    "contest_id": "1662",
    "index": "O",
    "title": "Circular Maze",
    "statement": "You are given a circular maze such as the ones shown in the figures.\n\nDetermine if it can be solved, i.e., if there is a path which goes from the center to the outside of the maze which does not touch any wall. The maze is described by $n$ walls. Each wall can be either circular or straight.\n\n- Circular walls are described by a radius $r$, the distance from the center, and two angles $\\theta_1, \\theta_2$ describing the beginning and the end of the wall in the clockwise direction. Notice that swapping the two angles changes the wall.\n- Straight walls are described by an angle $\\theta$, the direction of the wall, and two radii $r_1 < r_2$ describing the beginning and the end of the wall.\n\nAngles are measured in degrees; the angle $0$ corresponds to the upward pointing direction; and angles increase clockwise (hence the east direction corresponds to the angle $90$).",
    "tutorial": "In this task, you are given circular mazes described by collections of walls, which can be either circular (constant radius) or straight (constant angle). The goal is to determine if a maze can be solved, that is, if there is a path from the center to the outside which does not cross any wall. Reducing the problem to a grid maze The first remark to be made is that this task can be reformulated into the much simpler problem of finding a path in a grid maze (with the left and right sides of the grid being connected by some portal). The image bellow illustrates the grid obtained from the first input sample, where each row corresponds to a radius (between $1$ and $20$) and each column corresponds to an angle (between $0$ and $360$). A possible path solving the maze is displayed in orange. The first part of the solution consists of building the grid maze, and fill 2D arrays with the walls. Because walls do not overlap, it is sufficient to iterate over each wall (number of operations is in the order of $t \\cdot 20 \\cdot 360 \\leq 10^6$). Observe that with overlapping walls, the naive implementation might be too slow (worst case is $t \\cdot n \\cdot 360 \\geq 10^8$), but one could compute cumulative sums of arrays containing the endpoints of walls. Finally, we build the undirected graph where each cell is connected to the neighbouring cells such that there is no wall in between. Solving the grid maze Now that we have a grid maze, where each cell is connected to up to $4$ neighbours, we need to determine if there is a path between the inside and the outside of the maze. The only remaining detail is to describe how we deal with the inside (below radius $r=1$) and the outside of the maze (above radius $r=20$). Multiple approaches exist: Adding two \"sentinel\" rows of cells to the maze, one at the bottom (inside) and one at the top (outside). Because there are no walls in sentinel rows, it is enough to pick (arbitrarily) one cell from each row and check if there is a path between them. Adding two special cells, one for the inside and one for the outside, connected (when there is no wall) to cells from the bottom and the top row. It is now enough to check if there is a path between these two special cells. Finally, checking if there is a path between two cells can be done with various algorithms computing the connected components of a graph. Depth-first search: the procedure builds the component of a starting cell by exploring (recursively) adjacent cells, making sure it does not explore the same cell twice. Breadth-first search: the procedure builds the component of a starting cell by exploring (iteratively) cells at distance $1$, then $2$, etc. Disjoint-Set Union data structure: starting from a collection of singleton sets (each containing one cell), the data structure can merge sets (containing two neighbouring cells). The resulting collection of sets corresponds to connected components.",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation"
    ]
  },
  {
    "contest_id": "1665",
    "index": "A",
    "title": "GCD vs LCM",
    "statement": "You are given a positive integer $n$. You have to find $4$ \\textbf{positive} integers $a, b, c, d$ such that\n\n- $a + b + c + d = n$, and\n- $\\gcd(a, b) = \\operatorname{lcm}(c, d)$.\n\nIf there are several possible answers you can output any of them. It is possible to show that the answer always exists.\n\nIn this problem $\\gcd(a, b)$ denotes the greatest common divisor of $a$ and $b$, and $\\operatorname{lcm}(c, d)$ denotes the least common multiple of $c$ and $d$.",
    "tutorial": "In this problem it is enough to print $n - 3$, $1$, $1$, $1$. It is easy to see that this answer is correct for any $n \\ge 4$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n;\n        cin >> n;\n        cout << n - 3 << ' ' << 1 << ' ' << 1 << ' ' << 1 << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1665",
    "index": "B",
    "title": "Array Cloning Technique",
    "statement": "You are given an array $a$ of $n$ integers. Initially there is only one copy of the given array.\n\nYou can do operations of two types:\n\n- Choose any array and clone it. After that there is one more copy of the chosen array.\n- Swap two elements from \\textbf{any} two copies (maybe in the same copy) on any positions.\n\nYou need to find the minimal number of operations needed to obtain a copy where all elements are equal.",
    "tutorial": "We will use a greedy technique. Let's find the most common element in the array. Let it be $x$ and let it occur $k$ times in the array. Then let's make a copy where all elements are $x$. To do that we can make a copy of the given array and put all $x$ in one array. Now we will repeat the algorithm for the new array until we get a copy with $n$ numbers $x$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n;\n        cin >> n;\n        map<int, int> q;\n        for (int i = 0; i < n; ++i) {\n            int x;\n            cin >> x;\n            ++q[x];\n        }\n        int am = 0;\n        for (auto &[x, y] : q) {\n            am = max(am, y);\n        }\n        int ans = 0;\n        while (am < n) {\n            int d = min(n - am, am);\n            ans += 1 + d;\n            am += d;\n        }\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1665",
    "index": "C",
    "title": "Tree Infection",
    "statement": "A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $v$ (different from root) is the previous to $v$ vertex on the shortest path from the root to the vertex $v$. Children of the vertex $v$ are all vertices for which $v$ is the parent.\n\nYou are given a rooted tree with $n$ vertices. The vertex $1$ is the root. Initially, all vertices are healthy.\n\nEach second you do \\textbf{two} operations, the spreading operation and, after that, the injection operation:\n\n- Spreading: for \\textbf{each} vertex $v$, if at least one child of $v$ is infected, you can spread the disease by infecting at most one other child of $v$ of your choice.\n- Injection: you can choose any healthy vertex and infect it.\n\nThis process repeats each second until the whole tree is infected. You need to find the minimal number of seconds needed to infect the whole tree.",
    "tutorial": "Firstly, we can see that for any two different vertices, their children are independent. It means that infection can not spread from children of one vertex to children of another. Also it does not matter how the infection spreads among the children of some vertex, so we only need to know the amount of vertices with the same parent. Using this knowledge we can reduce the problem to this one: You are given an array of $k$ positive integers, each integer denotes the amount of healthy vertices with the same parent. Each second you can infect an integer in this array (by injection). Also each second all infected integers decrease by 1 (because of spreading). Let's now use a greedy algorithm. We will sort this array in the decreasing order and infect all integers one by one. These injections are always needed because the integers are independent. After that each second all numbers decrease by 1 and we can choose one number to be decreased once more in the same second. This should be the max number. This problem can be solved by simulating the whole process, because the sum of all integers in the beginning is $n$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint ans;\n\nvoid proc(vector<int>& a) {\n    if (a.empty()) return;\n    int n = a.size();\n    int last = 0;\n    for (int i = 0; i < n; ++i) {\n        if (a[i] == a[0]) {\n            last = i;\n        } else {\n            break;\n        }\n    }\n    --a[last];\n    for (int i = 0; i < n; ++i) --a[i];\n    ++ans;\n    while (!a.empty() && a.back() <= 0) {\n        a.pop_back();\n    }\n    proc(a);\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        ans = 0;\n        for (int i = 1; i < n; ++i) {\n            int x;\n            cin >> x;\n            ++a[--x];\n        }\n        a.emplace_back(1);\n        sort(a.rbegin(), a.rend());\n        while (!a.empty() && a.back() <= 0) a.pop_back();\n        n = a.size();\n        for (int i = 0; i < n; ++i) {\n            a[i] = a[i] - (n - i);\n            ++ans;\n        }\n        sort(a.rbegin(), a.rend());\n        while (!a.empty() && a.back() <= 0) a.pop_back();\n        proc(a);\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1665",
    "index": "D",
    "title": "GCD Guess",
    "statement": "\\textbf{This is an interactive problem.}\n\nThere is a positive integer $1 \\le x \\le 10^9$ that you have to guess.\n\nIn one query you can choose two positive integers $a \\neq b$. As an answer to this query you will get $\\gcd(x + a, x + b)$, where $\\gcd(n, m)$ is the greatest common divisor of the numbers $n$ and $m$.\n\nTo guess one hidden number $x$ you are allowed to make no more than $30$ queries.",
    "tutorial": "Solution 1 Let's iteratively find the remainder of $x \\bmod$ each power of $2$. Initially, we know that $x \\bmod 2^0 = x \\bmod 1 = 0$. If we know that $x \\bmod 2^k = r$, then how do we find $x \\bmod 2^{k + 1}$? To do that let's ask $\\gcd(x + 2^k - r, 2^{k + 1}) = \\gcd(x + 2^k - r, x + 2^k - r + 2^{k + 1})$. If $\\gcd = 2^{k + 1}$, then $x \\bmod 2^{k + 1} = r + 2^{k - 1}$ else $x \\bmod 2^{k + 1} = r$. Using this algorithm we will find $x \\bmod 2^{30}$ which is just $x$. It takes exactly $30$ queries. Solution 2 Let's consider a set of pairwise coprime numbers ${23, 19, 17, 13, 11, 9, 7, 5, 4}$. Their $\\text{lcm} > 10^9$ that's why $x \\bmod \\text{lcm} = x$. Let's find $x \\bmod$ each of these numbers. To do that, for each $1 \\le i \\le 23$ we can ask $\\gcd(x + i, x + \\text{lcm} + i)$ (the query is $(i, \\text{lcm} + i)$). If the $\\gcd$ is a multiple of some number from our set then $x \\bmod$ this number is $-i$. After that we can use the chinese remainder theorem to find $x$ that gives the same remainders for numbers from the set. This solution asks only $23$ queries. Observation 1: It's enough to make only $22$ queries, because if we did not find anything for $1 \\le i \\le 22$ then we can guarantee that $i = 23$ will do. Observation 2: All moduli are small, that's why it is possible to use a simplified CRT (check the implementation).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define nl \"\\n\"\n#define nf endl\n#define ll long long\n#define pb push_back\n#define _ << ' ' <<\n \n#define INF (ll)1e18\n#define mod 998244353\n#define maxn 110\n#define lc 1338557220\n \nll i, i1, j, k, k1, t, n, m, res, flag[10], a, b;\nll x, rs[maxn], p;\nvector<ll> pw = {23, 19, 17, 13, 11, 9, 7, 5, 4};\n \nll ask(ll a, ll b) {\n    cout << \"?\" _ a _ b << nf;\n    ll x; cin >> x; return x;\n}\n \nvoid clm(ll x) {\n    cout << \"!\" _ x << nf;\n}\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    /* #if !ONLINE_JUDGE && !EVAL\n        ifstream cin(\"input.txt\");\n        ofstream cout(\"output.txt\");\n    #endif */\n \n    // kudos for automatic wa\n \n    cin >> t;\n    while (t--) {\n        for (i = 1; i <= 23; i++) {\n            k = ask(x + i, lc + i);\n            for (j = 0; j < 9; j++) {\n                if (k % pw[j] == 0) rs[j] = i % pw[j];\n            }\n        }\n \n        k = 1; p = 1;\n        for (j = 0; j < 9; j++) {\n            // cout << \"p =\" _ p << nf;\n            while (p % pw[j] != rs[j]) p += k;\n            k *= pw[j];\n        }\n \n        clm(lc - p);\n    }\n \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "chinese remainder theorem",
      "constructive algorithms",
      "games",
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1665",
    "index": "E",
    "title": "MinimizOR",
    "statement": "You are given an array $a$ of $n$ non-negative integers, numbered from $1$ to $n$.\n\nLet's define the cost of the array $a$ as $\\displaystyle \\min_{i \\neq j} a_i | a_j$, where $|$ denotes the bitwise OR operation.\n\nThere are $q$ queries. For each query you are given two integers $l$ and $r$ ($l < r$). For each query you should find the cost of the subarray $a_{l}, a_{l + 1}, \\ldots, a_{r}$.",
    "tutorial": "The key idea for the solution is that the answer always lies among no more than 31 minimal numbers. According to this idea, it is possible to build a segment tree for minimum on a segment. After that we only need to find no more than 31 minimums on the segment (each time we find one we change it to $\\infty$) and, finally, we can find all $OR$s pairwise among these 31 numbers. It is also possible to use the Merge Sort Tree and the same idea. Now let's prove the key idea: let's prove by induction that if all numbers are less than $2^k$ then it's enough to consider $k + 1$ minimal numbers. Base case: $k=1$, all numbers are from $0$ to $1$ and the proof is obvious. Inductive step: Let's show that for any $k \\ge 1$ if for $k$ the statement is true then it's true for $k + 1$. If all numbers have 1 in $k$-th bit then the $k$-th bit of the answer is also 1, that's why we only have to minimize the remaining bits. For these bits we can apply the induction hypothesis that $k + 1$ minimal numbers are enough. If at least two numbers have 0 in their $k$-th bit then the $k$-th bit in the answer is also 0. That's why we only consider only numbers with 0 in $k$-th bit and we have to minimize the remaining bits. Again applying the induction hypothesis, $k + 1$ minimal numbers are enough. If there is exactly one number with 0 in $k$-th bit then the $k$-th bit in the answer is 1 and we have to find $k + 1$ minimal numbers over $k$ bits. They are among $k + 2$ minimal numbers over $k + 1$ bits, so $k + 2$ minimal numbers are enough. Problem A Idea: shishyando Polygon: shishyando Idea: shishyando Polygon: shishyando Problem B Idea: shishyando Polygon: shishyando Idea: shishyando Polygon: shishyando Problem C Idea: shishyando Polygon: shishyando Idea: shishyando Polygon: shishyando Problem D Idea: Artyom123 Polygon: shishyando Idea: Artyom123 Polygon: shishyando Problem E Idea: I_love_teraqqq Polygon: shishyando Idea: I_love_teraqqq Polygon: shishyando English translation: shishyando Special thanks: KAN for coordinating the coordinator and double checking everything Another special thanks: NEAR for supporting the Codeforces Community! Yet another special thanks: everyone who participated and tested!",
    "code": "#include <bits/stdc++.h>\n \n#define F first\n#define S second\n#define all(a) a.begin(), a.end()\n \nusing namespace std;\nusing ll = long long;\n \ntemplate<class T> bool ckmin(T &a, T b) { return a > b ? a = b, true : false; }\ntemplate<class T> bool ckmax(T &a, T b) { return a < b ? a = b, true : false; }\n \nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n); for (auto &x : a) cin >> x;\n    vector<unordered_map<int, vector<int>>> cnt(30);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < 30; ++j) {\n            cnt[29-j][a[i]>>j].push_back(i);\n        }\n    }\n    int q; cin >> q;\n    while (q--) {\n        int l, r; cin >> l >> r; l--; r--;\n        int x = 0, pref = 0;\n        vector<int> tmp;\n        for (int j = 0; j < 30; ++j) {\n            pref*=2;\n            vector<int> newtmp;\n            int k = upper_bound(all(cnt[j][pref]), r) - lower_bound(all(cnt[j][pref]), l);\n            int k0 = k;\n            for (auto y : tmp) {\n                if (((y>>(29-j))&1) == 0) k++, newtmp.push_back(y);\n            }\n            if (k0 == 1) {\n                int id = lower_bound(all(cnt[j][pref]), l) - cnt[j][pref].begin();\n                tmp.push_back(a[cnt[j][pref][id]]);\n            }\n            if (k < 2) pref++;\n            else tmp.swap(newtmp);\n        }\n        cout << pref << \"\\n\";\n    }\n}\n \nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int t; cin >> t;\n    while (t--) solve();\n    return 228/1337;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "divide and conquer",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1667",
    "index": "A",
    "title": "Make it Increasing",
    "statement": "You are given an array $a$ consisting of $n$ positive integers, and an array $b$, with length $n$. Initially $b_i=0$ for each $1 \\leq i \\leq n$.\n\nIn one move you can choose an integer $i$ ($1 \\leq i \\leq n$), and add $a_i$ to $b_i$ or subtract $a_i$ from $b_i$. What is the minimum number of moves needed to make $b$ increasing (that is, every element is strictly greater than every element before it)?",
    "tutorial": "If the final array, is $b_1$, $b_2$ ... $b_n$, than the solution is surely unoptimal if there is an $2 \\le i \\le n$, when $b_i>0$, and $b_i-a_i>b_{i-1}$, or $b_1>0$. Because there was one unnecessary move on $b_i$ or on $b_1$. Similarly it is unoptimal, if $b_i<0$ and $b_i+a_i<b_{i+1}$ or $b_n<0$. We can see, that there will be a $0$ in the final array. If we fix the position of the $0$ element, than we can set the other values greadily: find the smallest value for each element, which is bigger than the previous one, and similarly before that element. We can fix each element, and calculate the answer for that in $O(n)$ time. The minimum of these values will be the final answer. So the final complexity is $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nlong long n, a[5005], ans=1e18;\nint main()\n{\n    cin >> n;\n    for (int i=1; i<=n; i++) {\n        cin >> a[i];\n    }\n    for (int pos=1; pos<=n; pos++) {\n        long long prev=0, sum=0;\n        for (int i=pos-1; i>=1; i--) {\n            prev+=a[i]-prev%a[i];\n            sum+=prev/a[i];\n        }\n        prev=0;\n        for (int i=pos+1; i<=n; i++) {\n            prev+=a[i]-prev%a[i];\n            sum+=prev/a[i];\n        }\n        ans=min(ans, sum);\n    }\n    cout << ans << \"\\n\";\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1667",
    "index": "B",
    "title": "Optimal Partition",
    "statement": "You are given an array $a$ consisting of $n$ integers. You should divide $a$ into continuous non-empty subarrays (there are $2^{n-1}$ ways to do that).\n\nLet $s=a_l+a_{l+1}+\\ldots+a_r$. The value of a subarray $a_l, a_{l+1}, \\ldots, a_r$ is:\n\n- $(r-l+1)$ if $s>0$,\n- $0$ if $s=0$,\n- $-(r-l+1)$ if $s<0$.\n\nWhat is the maximum sum of values you can get with a partition?",
    "tutorial": "Let $dp_i$ be the answer for the first $i$ elements, and $v_{(i, j)}$ the value of the subarray $[i, j]$. With prefix sums it is easy to calculate $v_{(i, j)}$ quickly. With this we can get a $n^2$ solution: $dp_i=max(dp_j+v_{(j+1, i)})$ for $j<i$. Lets call a segment winning, drawing, or losing, if the value of it is positive, $0$, or negative respectively. There is an optimal solution if the length of the drawing and losing segments are $1$. (The task is solvable without this observation, but it is harder to implement.) Proof: For a losing segment in the worst case we can get two losing segments with the same total length (the same value). For a drawing segment with length $k$ if $k$ is even than the answer is the same if we split it into two segments with length $k/2$. For odd $k$ if the sum in the first $(k-1)/2$ or last $(k-1)/2$ elements is negative, than it is possible to increase the answer, otherwise one can split the segment into $(k-1)/2$, $1$, and $(k-1)/2$ long segments, and the answer for the new partition can't lessen. So there is an optimal solution when only winning segments might be longer than $1$. It is easy to handle the $1$ long segments. For each $i$ ($1 \\le i \\le n$) we have to find $j$, $0<=j<i$, where $v_{(j+1, i)}>0$, and $dp_j+v_{(j+1, i)}$ is maximal ($dp_0=0$). If we store the prefix sums, and assign a permutation according to the prefix sums, than we can get all the positions $1 \\le j<i$, where $v_{(j+1, i)}>0$. Than $v_{(j+1, i)}=i-j$. So when we calculate $dp_i$, we should update with $dp_i-i$. This way, finding the optimal $j$ for each $i$ is just a prefix maximum. One can solve the problem with Fenwick tree or segment tree. Final complexity is $O(n \\cdot log(n))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nconst int max_n=500005, inf=10000000;\nint t, n, a[max_n], dp[max_n], ord[max_n], fen[max_n];\nlong long pref[max_n];\n\n\n// Fenwick tree with prefix maximum\nint lsb(int a) {\n    return (a & -a);\n}\nvoid add(int pos, int val) {\n    while (pos<=n) {\n        fen[pos]=max(fen[pos], val);\n        pos+=lsb(pos);\n    }\n}\nint ask(int pos) {\n    int val=-inf;\n    while (pos) {\n        val=max(fen[pos], val);\n        pos-=lsb(pos);\n    }\n    return val;\n}\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        vector<pair<long long, int> > v;\n        for (int i=1; i<=n; i++) {\n            cin >> a[i];\n            pref[i]=pref[i-1]+a[i];\n            v.push_back({pref[i], -i});\n        }\n        sort(v.begin(), v.end());\n        for (int i=0; i<n; i++) {\n            ord[-v[i].second]=i+1;\n        }\n        // smaller prefix sum, smaller ord[i]\n        // if j<i they have equal prefix sums, than ord[i]<ord[j], this way we cannot count [j+1, ... i] as a winning segment\n\n\n        for (int i=1; i<=n; i++) {\n            fen[i]=-inf;\n        }\n\n        for (int i=1; i<=n; i++) {\n            dp[i]=(dp[i-1]+(a[i]<0 ? -1 : a[i]>0 ? 1 : 0));\n            // The last segment is 1 long.\n\n            dp[i]=max(dp[i], ask(ord[i])+i);\n            if (pref[i]>0) dp[i]=i;\n            // Segment [1, ... i] is winning, so dp[i]=i;\n\n            add(ord[i], dp[i]-i);\n        }\n        cout << dp[n] << \"\\n\";\n\n        for (int i=0; i<=n; i++) {\n            a[i]=0, dp[i]=0, ord[i]=0, fen[i]=0, pref[i]=0;\n        }\n    }\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1667",
    "index": "C",
    "title": "Half Queen Cover",
    "statement": "You are given a board with $n$ rows and $n$ columns, numbered from $1$ to $n$. The intersection of the $a$-th row and $b$-th column is denoted by $(a, b)$.\n\nA half-queen attacks cells in the same row, same column, and on one diagonal. More formally, a half-queen on $(a, b)$ attacks the cell $(c, d)$ if $a=c$ or $b=d$ or $a-b=c-d$.\n\n\\begin{center}\n{\\small The blue cells are under attack.}\n\\end{center}\n\nWhat is the minimum number of half-queens that can be placed on that board so as to ensure that each square is attacked by at least one half-queen?Construct an optimal solution.",
    "tutorial": "Let's assume that there is a solution for $k$ half-queens. There are at least $n-k$ rows, and columns, which contains no half-queen. If the uncovered rows are $r_1, r_2, ... r_a$, and the columns are $c_1, c_2, ... c_b$, (in increasing order), each diagonal (when the difference is a constant) contains at most one of the following $a+b-1$ squares: $(r_a, c_1), (r_a-1, c_1), ... (r_1, c_1), (r_1, c_2), ... (r_1, c_b)$. So a different half-queen attacks these cells. We know that: $a+b-1 \\le k, n-k \\le a, n-k \\le b$, so $2 \\cdot n \\le 3 \\cdot k+1$. We have a lower bound for $k$. It turns out, that there is a consturction, for this $k$. For $n=3 \\cdot x+2$, $k=2 \\cdot x+1$, and we can place $x+1$ in the top left corner, diagonally, and $x$ half queens in the bottom right corner diagonally. For $n=8$ an optimal construction could be: $(1, 3)$, $(2, 2)$, $(3, 1)$, $(7, 8)$, $(8, 7)$. If $n=3 \\cdot x$, or $n=3 \\cdot x+1$ we can put one or two half-queens, in the bottom right corner, and use the previous construction.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{   \n    int n;\n    cin >> n;\n    cout << n/3+(n+2)/3 << \"\\n\";\n    if (n==1) {\n        cout << 1 << \" \" << 1 << \"\\n\";\n        return 0;\n    }\n    while (n%3!=2) {\n        cout << n << \" \" << n << \"\\n\";\n        n--;\n    }\n    int a=(n+1)/3;\n    for (int i=1; i<=a; i++) {\n        cout << i << \" \" << a+1-i << \"\\n\";\n    }\n    for (int i=1; i<a; i++) {\n        cout << n-a+i+1 << \" \" << n-i+1 << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1667",
    "index": "D",
    "title": "Edge Elimination",
    "statement": "You are given a tree (connected, undirected, acyclic graph) with $n$ vertices. Two edges are adjacent if they share exactly one endpoint. In one move you can remove an arbitrary edge, if that edge is adjacent to an even number of remaining edges.\n\nRemove all of the edges, or determine that it is impossible. If there are multiple solutions, print any.",
    "tutorial": "When an edge is removed, the two neighbouring vertex have the same parity of edges. We say that an edge is odd, if the parity is odd, and the edge is even otherwise. One can see, that a vertex with even degree will have the same amount of odd and even edges. For a vertex with odd degree, there will be one more odd edge. Starting from the leaves, we can decide the parity of each edge (an edge connected to a leaf is odd). If there is a contradiction somewhere than the answer is NO. Otherwise, there is a construction. In each vertex decide the removal order of the outgoing edges. Any order is good, when it always changes parity, and ends with an odd edge. Consider the directed graph with these conditions. One can see, that this graph is acyclic, so there is a topological order of that graph which will satisfy all the conditions. Also, it is possible to solve it recursively.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nconst int c=200005;\nint t, n, up[c];\nbool parity[c], vis[c], no_sol;\nvector<int> edges[c];\nvoid dfs(int a) {\n    vis[a]=true;\n    int cnt[2]={0, 0};\n    for (auto x:edges[a]) {\n        if (!vis[x]) {\n            up[x]=a;\n            dfs(x);\n            cnt[parity[x]]++;\n        }\n    }\n    if (a!=1) {\n        if (parity[a]=(cnt[0]>=cnt[1]));\n        cnt[parity[a]]++;\n    }\n    if (cnt[1]-cnt[0]<0 || cnt[1]-cnt[0]>1) {\n        no_sol=1;\n    }\n}\nvoid solve(int a) {\n    vector<int> p[2];\n    for (auto x:edges[a]) {\n        if (x!=up[a]) {\n            p[parity[x]].push_back(x);\n        } else {\n            p[parity[a]].push_back(a);\n        }\n    }\n    int si=edges[a].size(), id=si%2;\n    for (int i=0; i<si; i++) {\n        int val=p[id].back();\n        if (val==a) {\n            cout << a << \" \" << up[a] << \"\\n\";\n        } else {\n            solve(val);\n        }\n        p[id].pop_back();\n        id=1-id;\n    }\n \n}\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin >> t;\n    for (int test=0; test<t; test++) {\n        cin >> n;\n        for (int i=1; i<n; i++) {\n            int a, b;\n            cin >> a >> b;\n            edges[a].push_back(b), edges[b].push_back(a);\n        }\n        dfs(1);\n        if (no_sol) {\n            cout << \"NO\\n\";\n        } else {\n            cout << \"YES\\n\";\n            solve(1);\n        }\n \n        for (int i=1; i<=n; i++) {\n            parity[i]=0, up[i]=0, vis[i]=0;\n            edges[i].clear();\n        }\n        no_sol=0;\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1667",
    "index": "E",
    "title": "Centroid Probabilities",
    "statement": "Consider every tree (connected undirected acyclic graph) with $n$ vertices (\\textbf{$n$ is odd}, vertices numbered from $1$ to $n$), and for each $2 \\le i \\le n$ the $i$-th vertex is adjacent to exactly one vertex with a smaller index.\n\nFor each $i$ ($1 \\le i \\le n$) calculate the number of trees for which the $i$-th vertex will be the centroid. The answer can be huge, output it modulo $998\\,244\\,353$.\n\nA vertex is called a centroid if its removal splits the tree into subtrees with at most $(n-1)/2$ vertices each.",
    "tutorial": "Let $S=\\frac{n+1}{2}$, $binom_{i, j}=\\frac{i!}{j! \\cdot (i-j)!}$, $dp_i$ the result of some precalculation (see below) and $ans_i$ the final answer for the $i$-th vertex. Root the tree in vertex $1$. It is easy to see that in the possible trees the parent of vertex $2 \\le i \\le n$ is smaller than $i$. The cetroid will be the largest vertex, where the size of its subtree is at least $S$. For each $i$ first calculate: how many times the subtree of vertex $i$ will be at least $S$ ($dp_i$). If $i=1$, then $dp_i=(n-1)!$. If $i>S$ then the $dp_i=0$. Otherwise ($2 \\le i \\le S$) $dp_i = \\sum_{j=S-1}^{n-i} binom_{n-i, j} \\cdot j! \\cdot (n-j-2)! \\cdot (i-1)$ Proof: Let's assume that the size of the subtree is $j+1$. Color the subtree of vertex $i$ except $i$ red. Color every other vertex except the first and the $i$-th one to blue. We have $binom_{n-i, j}$ differnt colorings, because we have to choose $j$ values between $i+1$ and $n$. ($binom_{n-i, j}$) There are $k$ possibilities for the parent of the $k$-th smallest blue or the $k$-th smallest red vertex. ($j! \\cdot (n-j-2)!$) The parent of the $i$-th vertex can be anything. ($i-1$) If we multiply all of these, we get the described formula. Then $ans_i=dp_i-\\sum_{j=i+1}^{n} \\frac{ans_j}{i}$ Proof: if the subtree of $i$ is at least $S$, and the centroid is not $i$, than the centroid is in the subtree of $i$. If $j$ is the centroid, there is exactly $\\frac{1}{i}$ chance, that the path from $j$ to $1$ will cross vertex $i$. So we have to subract $\\frac{ans_j}{i}$ for each $j>i$. This gives us an $O(n^2)$ solution, which is slow because of the two sum formulas. $\\sum_{j=S-1}^{n-i} binom_{n-i, j} \\cdot j! \\cdot (n-j-2)! \\cdot (i-1) = \\sum_{j=S-1}^{n-i} \\frac {(n-i)! \\cdot j! \\cdot (n-j-1)! \\cdot (i-1)}{j! \\cdot (n-i-j)!} = \\sum_{j=S-1}^{n-i} \\frac {(n-i)! \\cdot (n-j-2)! \\cdot (i-1)}{(n-i-j)!}$ $(n-i)! \\cdot (i-1)$ is a constant (for fixed $i$), and the difference between $n-j-2$ and $n-i-j$ is $i-2$, is also a constant for fixed $i$. If we reverse the inv array, then we can calculate $\\sum_{j=S-1}^{n-i} \\frac{(n-j-2)!}{(n-i-j)!}$ in $n \\cdot log(n)$ time for $2 \\le i \\le S$ with ntt. We can do the calculation of $ans_i$ in linear time if we store the suffix sums of the latter values. This gives us the final complexity: $O(n \\cdot log(n))$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n \n \n// ntt - this code is not mine\nconst int _ = 1 << 20 , mod = 998244353 , G = 3;\nint upd(int x) {\n    return x + (x >> 31 & mod);\n}\nint add(int x , int y) {\n    return upd(x + y - mod);\n}\nint sub (int x , int y){\n    return upd(x - y);\n}\nint mul (int a, int b) {\n    return 1ll*a*b%mod;\n}\nint poww(long long a , int b) {\n    int tms = 1;\n    while (b) {\n        if(b & 1) tms = tms * a % mod;\n        a = a * a % mod; b >>= 1;}\n    return tms;\n}\n \nint dir[_] , need , invnd , w[_];\nvoid init(int len){\n\tstatic int L = 1; need = 1;\n\twhile (need < len) need <<= 1;\n\tinvnd = poww(need , mod - 2);\n\tfor (int i = 1 ; i < need ; ++i) dir[i] = (dir[i >> 1] >> 1) | (i & 1 ? need >> 1 : 0);\n\tfor (int &i = L ; i < need ; i <<= 1) {\n        w[i] = 1;\n        int wn = poww(G , mod / i / 2);\n        for(int j = 1 ; j < i ; ++j) w[i + j] = 1ll * w[i + j - 1] * wn % mod;\n    }\n}\n \nvoid dft(vector < int > &arr , int tmod){\n\tarr.resize(need);\n\tfor (int i = 1 ; i < need ; ++i) {\n        if (i < dir[i]) swap(arr[i] , arr[dir[i]]);\n\t}\n\tfor(int i = 1 ; i < need ; i <<= 1) {\n\t\tfor (int j = 0 ; j < need ; j += i << 1) {\n\t\t\tfor (int k = 0 ; k < i ; ++k) {\n\t\t\t\tint x = arr[j + k] , y = 1ll * arr[i + j + k] * w[i + k] % mod;\n\t\t\t\tarr[j + k] = add(x , y); arr[i + j + k] = sub(x , y);\n\t\t\t}\n\t\t}\n\t}\n\tif(tmod == -1) {\n        reverse(arr.begin() + 1 , arr.end());\n        for(auto &t : arr) {\n            t = 1ll * t * invnd % mod;\n        }\n    }\n}\n \nvector<int> multiply(vector<int> const& a, vector<int> const& b) {\n    init(a.size()+b.size());\n    vector<int> fa(a.begin(), a.end()), fb(b.begin(), b.end());\n \n    dft(fa, 1);\n    dft(fb, 1);\n    for (int i = 0; i < need; i++) {\n        fa[i] = 1ll * fa[i] * fb[i] % mod;\n    }\n    dft(fa, -1);\n    return fa;\n}\n \nconst int max_n=200005;\nlong long n, fact[max_n], inv[max_n], dp[max_n], ans[max_n], suf, s;\nvector<int> v1, v2, v3;\nlong long po(long long a, long long b) {\n    long long res=1;\n    while (b) {\n        if (b%2) res=res*a%mod;\n        a=a*a%mod;\n        b/=2;\n    }\n    return res;\n}\n \n \nint main()\n{\n    cin >> n;\n    s=(n+1)/2;\n    fact[0]=1, inv[0]=1;\n    for (int i=1; i<=n; i++) {\n        fact[i]=fact[i-1]*i%mod;\n        inv[i]=po(fact[i], mod-2);\n    }\n \n    for (int i=0; i<s-1; i++) {\n        v1.push_back(fact[i]);\n        v2.push_back(inv[i]);\n    }\n    reverse(v2.begin(), v2.end());\n    v3=multiply(v1, v2);\n \n    dp[1]=fact[n-1];\n    for (int i=2; i<=s; i++) {\n        dp[i]=fact[n-i]*v3[i+s-4]%mod*(i-1)%mod;\n    }\n \n    for (int i=s; i>=1; i--) {\n        ans[i]=(dp[i]-suf*po(i, mod-2)%mod+mod)%mod;\n        suf=(suf+ans[i])%mod;\n    }\n \n    for (int i=1; i<=n; i++) {\n        cout << ans[i] << \" \";\n    }\n    cout << \"\\n\";\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1667",
    "index": "F",
    "title": "Yin Yang",
    "statement": "You are given a rectangular grid with $n$ rows and $m$ columns. $n$ and $m$ are divisible by $4$. Some of the cells are already colored black or white. It is guaranteed that no two colored cells share a corner or an edge.\n\nColor the remaining cells in a way that both the black and the white cells becomes orthogonally connected or determine that it is impossible.\n\nConsider a graph, where the black cells are the nodes. Two nodes are adjacent if the corresponding cells share an edge. If the described graph is connected, the black cells are orthogonally connected. Same for white cells.",
    "tutorial": "Border: cells in the first or last row or first or last column. One can see that on the border both the black and the white part is connected. So there is no solution if there is a BWBW subsequence on the border. Otherwise there is a solution. Solve an easier task first. Assume that there is no colored cell on the border. Then there is a nice construction. Color white all cells in the first column, and in the $4*k+2$-nd and $4*k+3$-rd row, which is not in the last column. One can see that the stripes (2 consequtive white rows) are connected, because no two initially colored cell shares a corner. Also different stripes are connected to each other because of the left column. If there is a white cell in the middle of a black stripe, then it must be orthogonally adjacent to a white stripe. Similarly the black cells will be connected too. If there are colored cells on the border, than it is impossible to do exactly this. But the most of the cells might be the same: the white stripes, and the white column on the left side. In this way, the white part is connected. For the black part, there might be $3$ issues: the border is not connected to the black stripes, there are isolated black cells in the $2$-nd or $n-1$-th row, and different black stripes might be unconnected. All of these issues is solvable locally with changing the color of some cells from white to black and vice versa.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nconst int c=505;\nint t, n, m, fix[c][c], ans[c][c], rotcnt, change, old_cl, new_cl;\nint fix2[c][c], ans2[c][c];\nvoid color_boundary() {\n    for (int cnt=1; cnt<=2; cnt++) {\n        for (int j=2; j<=m; j++) {\n            if (!ans[1][j]) ans[1][j]=ans[1][j-1];\n            if (ans[1][j]!=ans[1][j-1]) change++;\n        }\n        for (int i=2; i<=n; i++) {\n            if (!ans[i][m]) ans[i][m]=ans[i-1][m];\n            if (ans[i][m]!=ans[i-1][m]) change++;\n        }\n        for (int j=m-1; j>=1; j--) {\n            if (!ans[n][j]) ans[n][j]=ans[n][j+1];\n            if (ans[n][j]!=ans[n][j+1]) change++;\n        }\n        for (int i=n-1; i>=1; i--) {\n            if (!ans[i][1]) ans[i][1]=ans[i+1][1];\n            if (ans[i][1]!=ans[i+1][1]) change++;\n        }\n        if (!ans[1][1]) ans[1][1]=1;\n        if (cnt==1) change=0;\n    }\n}\nvoid rotate_90() {\n    rotcnt++;\n    for (int i=1; i<=n; i++) {\n        for (int j=1; j<=m; j++) {\n            ans2[i][j]=ans[i][j], fix2[i][j]=fix[i][j];\n        }\n    }\n    for (int i=1; i<=n; i++) {\n        for (int j=1; j<=m; j++) {\n            ans[j][n+1-i]=ans2[i][j];\n            fix[j][n+1-i]=fix2[i][j];\n        }\n    }\n    swap(n, m);\n}\nvoid good_rotation() {\n    for (int cnt=1; cnt<=4; cnt++) {\n        bool same=1, opposite=0;\n        for (int i=1; i<=n; i++) {\n            if (ans[i][1]!=ans[1][1]) same=0;\n            if (1<i && i<n && ans[1][1]!=ans[i][m]) opposite=1;\n        }\n        if (!same || !opposite) rotate_90();\n    }\n}\nvoid color_the_stripes() {\n    for (int i=2; i<n; i++) {\n        for (int j=2; j<m; j++) {\n            if (!fix[i][j]) {\n                if (i%4==2 || i%4==3) ans[i][j]=old_cl;\n                else ans[i][j]=new_cl;\n            }\n        }\n    }\n}\nvoid avoid_touching() {\n    for (int i=1; i<n; i++) {\n        if (ans[i][m-1]==ans[i+1][m] && ans[i+1][m-1]==ans[i][m] && ans[i][m]!=ans[i+1][m]) {\n            if (!fix[i][m]) ans[i][m]=3-ans[i][m];\n            else ans[i+1][m]=3-ans[i+1][m];\n        }\n    }\n}\nvoid boundary_stripe_connection() {\n    int first=0, last=0;\n    for (int i=1; i<=n; i++) {\n        if (ans[i][m]==new_cl) {\n            if (!first) first=i;\n            last=i;\n        }\n    }\n    if (first==0 || (last>3 && first<n-2)) return;\n    if (last<=3 && fix[4][m-1]==old_cl) {\n        for (int i=3; i<=5; i++) {\n            ans[i][m]=new_cl;\n        }\n        return;\n    }\n    if (first>=n-2 && fix[n-3][m-1]==old_cl) {\n        for (int i=n-4; i<=n-2; i++) {\n            ans[i][m]=new_cl;\n        }\n        return;\n    }\n    int x=(last<=3 ? 2 : n-2);\n    for (int i=x; i<=x+1; i++) {\n        for (int j=m-1; j<=m; j++) {\n            if (!fix[i][j]) ans[i][j]=new_cl;\n        }\n    }\n}\nvoid connect_isolated_point(int x, int y) {\n    if (ans[x-1][y]==new_cl || ans[x+1][y]==new_cl || ans[x][y+1]==new_cl) return;\n    int x1=(x==2 ? 1 : n), x2=(x==2 ? 2 : n-1), x3=(x==2 ? 3 : n-2), x4=(x==2 ? 4 : n-3);\n    if (y<=m-2 && ans[x1][y+2]==new_cl) {\n        ans[x1][y]=new_cl;\n        ans[x1][y+1]=new_cl;\n        return;\n    }\n    if (y<=m-2 && ans[x2][y+2]==new_cl) {\n        ans[x2][y+1]=new_cl;\n        return;\n    }\n    if (fix[x4][y]!=old_cl) {\n        ans[x3][y]=new_cl;\n    } else {\n        int y2=(y+1<m ? y+1 : y-1);\n        ans[x2][y2]=new_cl;\n        ans[x3][y2]=new_cl;\n    }\n}\nvoid bridge_through_the_stripe(int x) {\n    for (int j=2; j<=4; j++) {\n        bool good=1;\n        for (int i=x-1; i<=x+2; i++) {\n            if (fix[i][j]==old_cl) good=0;\n        }\n        if (good) {\n            ans[x][j]=new_cl;\n            ans[x+1][j]=new_cl;\n            return;\n        }\n    }\n    for (int i=x-1; i<=x+2; i++) {\n        if (!fix[i][3]) ans[i][3]=new_cl;\n    }\n    if (fix[x-1][3]) {\n        ans[x-1][2]=old_cl;\n        ans[x][4]=new_cl;\n    }\n    if (fix[x+2][3]) {\n        ans[x+2][2]=old_cl;\n        ans[x+1][4]=new_cl;\n    }\n    if (fix[x][3] || fix[x+1][3]) {\n        ans[x][2]=new_cl;\n        ans[x+1][2]=new_cl;\n    }\n}\nint main()\n{\n    cin >> t;\n    for (int tc=1; tc<=t; tc++) {\n        cin >> n >> m;\n        for (int i=1; i<=n; i++) {\n            for (int j=1; j<=m; j++) {\n                char c;\n                cin >> c;\n                fix[i][j]=(c=='B' ? 1 : c=='W' ? 2 : 0);\n                ans[i][j]=fix[i][j];\n            }\n        }\n        color_boundary();\n        if (change>=4) {\n            cout << \"NO\\n\";\n        } else {\n            good_rotation();\n            old_cl=ans[1][1], new_cl=3-ans[1][1];\n            color_the_stripes();\n            avoid_touching();\n            boundary_stripe_connection();\n            for (int j=2; j<m; j++) {\n                if (fix[2][j]==new_cl) connect_isolated_point(2, j);\n                if (fix[n-1][j]==new_cl) connect_isolated_point(n-1, j);\n            }\n            for (int i=6; i<=n-6; i+=4) {\n                if (ans[1][1]==ans[i][m] || ans[1][1]==ans[i+1][m]) bridge_through_the_stripe(i);\n            }\n            while (rotcnt<4) rotate_90();\n            cout << \"YES\\n\";\n            for (int i=1; i<=n; i++) {\n                for (int j=1; j<=m; j++) {\n                    cout << (ans[i][j]==1 ? \"B\" : \"W\");\n                }\n                cout << \"\\n\";\n            }\n        }\n        rotcnt=0, change=0;\n        for (int i=1; i<=n; i++) {\n            for (int j=1; j<=m; j++) {\n                fix[i][j]=0, ans[i][j]=0;\n                fix[j][i]=0, ans[j][i]=0;\n            }\n        }\n    }\n    return 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1668",
    "index": "A",
    "title": "Direction Change",
    "statement": "You are given a grid with $n$ rows and $m$ columns. Rows and columns are numbered from $1$ to $n$, and from $1$ to $m$. The intersection of the $a$-th row and $b$-th column is denoted by $(a, b)$.\n\nInitially, you are standing in the top left corner $(1, 1)$. Your goal is to reach the bottom right corner $(n, m)$.\n\nYou can move in four directions from $(a, b)$: up to $(a-1, b)$, down to $(a+1, b)$, left to $(a, b-1)$ or right to $(a, b+1)$.\n\nYou cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What is the minimum number of moves to reach $(n, m)$?",
    "tutorial": "The moves are symmetrical, so we can assume that $n \\ge m$. There is no solution if $m=1$ and $n \\ge 3$, because one can only move up and down, but two consecutive down moves is required to reach $(n, 1)$. Otherwise, there is a solution. One should move downwards at least $n-1$ times, and it is forbidden to do that twice in a row, so another $n-2$ move is necessary ($1$ between each pair). So at least $n-1+n-2=2 \\cdot n-3$ moves required. If $n+m$ is even, then one more, because the parity of $a+b$ changes after every move, and the parity is even before the first and after the last move, so the total number of moves should be even. There is a construction for that lower bound: Move alternately down and right. After reaching the $m$-th column, repeat the following sequence of moves: down, left, down, right. With this $4$ move long sequence, one can move down two times. So we will reach $(n-1, m)$, then one more move is required, or we will reach $(n, m)$. If we add all of these moves, we get the formula: if $n+m$ is even then: $2 \\cdot (m-1)+4 \\cdot (n-m)/2=2 \\cdot n-2$,and if $n+m$ is odd then: $2 \\cdot (m-1)+4 \\cdot (n-m-1)/2+1=2 \\cdot n-3$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nint t, n, m;\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin >> t;\n    while (t--) {\n        cin >> n >> m;\n        if (n<m) {\n            swap(n, m);\n        }\n        if (m==1 && n>=3) {\n            cout << -1 << \"\\n\";\n        } else {\n            cout << 2*n-2-(n+m)%2 << \"\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1668",
    "index": "B",
    "title": "Social Distance",
    "statement": "$m$ chairs are arranged in a circle sequentially. The chairs are numbered from $0$ to $m-1$. $n$ people want to sit in these chairs. The $i$-th of them wants at least $a[i]$ empty chairs both on his right and left side.\n\nMore formally, if the $i$-th person sits in the $j$-th chair, then no one else should sit in the following chairs: $(j-a[i]) \\bmod m$, $(j-a[i]+1) \\bmod m$, ... $(j+a[i]-1) \\bmod m$, $(j+a[i]) \\bmod m$.\n\nDecide if it is possible to sit down for all of them, under the given limitations.",
    "tutorial": "If there is no one between the $i$-th and $j$-th person then $max(a_i, a_j)$ free chairs should be between them. So we should find a permutation $p$ of the array $a$, when $max(p_1, p_2)+max(p_2, p_3) ... +max(p_{n-1}, p_n)+max(p_n, p_1)$ is minimal. We can assume that the array is non-decreasing ($a_i \\leq a_{i+1}$). For each $i$ ($1 \\le i<n$) the $i$ largest elements from $a$ ($a_{n-i+1}$ ... $a_n$) will appear in the formula at least $i+1$ times. Every element occurs in two segments, and we only can count $i-1$ segments twice. So we get a lower bound for the number of free chairs: $a_2+a_3+...+a_{n-1}+2 \\cdot a_n$. This lower bound is reachable for the empty chairs if the permutation of $p$ is sorted. Because $max(p_1, p_2)=p_2$, $max(p_2, p_3)=p_3$, ... $max(p_{n-1}, p_n)=p_n$, and $max(p_n, p_1)=p_n$. They also sit on $n$ chairs. If we add all of these, we get that the answer is YES if: $n+ \\sum_{i=1}^{n}(a_i)-min(a_i)+max(a_i) \\le m$. ($a_i$={$a_1, a_2, ... a_n$})",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    int t;\n    cin >> t;\n    while (t--) {\n        long long n, m;\n        cin >> n >> m;\n        long long sum=0, min_val=1e9, max_val=0;\n        for (int i=1; i<=n; i++) {\n            long long x;\n            cin >> x;\n            sum+=x, min_val=min(min_val, x), max_val=max(max_val, x);\n        }\n        cout << (n+sum-min_val+max_val<=m ? \"YES\" : \"NO\") << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1669",
    "index": "A",
    "title": "Division?",
    "statement": "Codeforces separates its users into $4$ divisions by their rating:\n\n- For Division 1: $1900 \\leq \\mathrm{rating}$\n- For Division 2: $1600 \\leq \\mathrm{rating} \\leq 1899$\n- For Division 3: $1400 \\leq \\mathrm{rating} \\leq 1599$\n- For Division 4: $\\mathrm{rating} \\leq 1399$\n\nGiven a $\\mathrm{rating}$, print in which division the $\\mathrm{rating}$ belongs.",
    "tutorial": "For this problem you just need to implement what it asks you. To be able to implement it you need to know about the \"if\" statement.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nint main() {\n    int t; cin >> t;\n    while(t--) {\n        int x; cin >> x;\n        if(x < 1400) cout << \"Division 4\\n\";\n        else if(x < 1600) cout << \"Division 3\\n\";\n        else if(x < 1900) cout << \"Division 2\\n\";\n        else cout << \"Division 1\\n\";\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1669",
    "index": "B",
    "title": "Triple",
    "statement": "Given an array $a$ of $n$ elements, print any value that appears at least three times or print -1 if there is no such value.",
    "tutorial": "Approach 1: Sort the array using an efficient sorting algorithm. For every element check if the next two in the array are equal to it. If you find such an element output it. Time complexity is $\\mathcal{O}(n \\log n)$. Approach 2: Notice that elements have an upper bound of $n$, you can use an auxiliary array to store the count of each value. Go through each value and see if its count is bigger than or equal to $3$. Time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n\nint main() {\n\tint t; cin >> t;\n\twhile(t--) {\n\t    int n; cin >> n;\n    \tvector<int> cnt(n + 1, 0);\n    \tint ans = -1;\n    \tfor(int i = 0; i < n; i++) {\n    \t\tint x; cin >> x;\n    \t\tif(++cnt[x] >= 3) {\n    \t\t\tans = x;\n    \t\t}\n    \t}\n    \tcout << ans << endl;\n\t}\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1669",
    "index": "C",
    "title": "Odd/Even Increments",
    "statement": "Given an array $a=[a_1,a_2,\\dots,a_n]$ of $n$ positive integers, you can do operations of two types on it:\n\n- Add $1$ to \\textbf{every} element with an \\textbf{odd} index. In other words change the array as follows: $a_1 := a_1 +1, a_3 := a_3 + 1, a_5 := a_5+1, \\dots$.\n- Add $1$ to \\textbf{every} element with an \\textbf{even} index. In other words change the array as follows: $a_2 := a_2 +1, a_4 := a_4 + 1, a_6 := a_6+1, \\dots$.\n\nDetermine if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers. In other words, determine if you can make all elements of the array have the same parity after any number of operations.\n\nNote that you can do operations of both types any number of times (even none). Operations of different types can be performed a different number of times.",
    "tutorial": "Note is that after doing two operations of the same type, they are \"cancelled out\" in terms of parity, since we would change the parity of all elements once, then change it back again. So, we know that we will do each operation exactly $0$ or $1$ time. It is possible to check all possible cases just by simulating, or we can notice that all elements on all indices of the same parity must have the same parity and if they do we can always find an answer, by doing just a single type of operation a single time (in case the array doesn't already contain all elements of the same parity). The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \nint main() {\n    int t; cin >> t;\n    while(t--) {\n        int n; cin >> n;\n        vector<int> a(n);\n\n        int even1 = 0, even2 = 0, odd1 = 0, odd2 = 0;\n        for(int i = 0; i < n; ++i) {\n            cin >> a[i];\n            if(i % 2 == 0) {\n                if(a[i] % 2 == 1) odd1 = 1;\n                else even1 = 1; \n            } else {\n                if(a[i] % 2 == 1) odd2 = 1;\n                else even2 = 1;\n            }\n        }\n\n        if(even1 && odd1) {\n            cout << \"NO\\n\";\n        } else if(even2 && odd2) {\n            cout << \"NO\\n\";\n        } else {\n            cout << \"YES\\n\";\n        }\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1669",
    "index": "D",
    "title": "Colorful Stamp",
    "statement": "A row of $n$ cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as $\\textcolor{blue}{B}\\textcolor{red}{R}$ and as $\\textcolor{red}{R}\\textcolor{blue}{B}$.\n\nDuring use, the stamp must completely fit on the given $n$ cells (it cannot be partially outside the cells). The stamp can be applied multiple times to the same cell. Each usage of the stamp recolors both cells that are under the stamp.\n\nFor example, one possible sequence of stamps to make the picture $\\textcolor{blue}{B}\\textcolor{red}{R}\\textcolor{blue}{B}\\textcolor{blue}{B}W$ could be $WWWWW \\to WW\\textcolor{brown}{\\underline{\\color{red}{R}\\textcolor{blue}{B}}}W \\to \\textcolor{brown}{\\underline{\\color{blue}{B}\\textcolor{red}{R}}}\\textcolor{red}{R}\\textcolor{blue}{B}W \\to \\textcolor{blue}{B}\\textcolor{brown}{\\underline{\\color{red}{R}\\textcolor{blue}{B}}}\\textcolor{blue}{B}W$. Here $W$, $\\textcolor{red}{R}$, and $\\textcolor{blue}{B}$ represent a white, red, or blue cell, respectively, and the cells that the stamp is used on are marked with an underline.\n\nGiven a final picture, is it possible to make it using the stamp zero or more times?",
    "tutorial": "First note that parts of the picture separated by $\\texttt{W}$ are independent. That is, any stamps used on one part doesn't have any impact on the other, since a character $\\texttt{W}$ means no stamp has been placed on that cell. So let's split the string by $\\texttt{W}$s (for example, with split() method in Python), and consider the resulting strings containing only $\\texttt{R}$ and $\\texttt{B}$. Call one of these parts $p$. In the final stamp we place on $p$, we must have placed $\\texttt{RB}$, so it should have both the characters $\\texttt{R}$ and $\\texttt{B}$. Therefore, if the string has only $\\texttt{R}$ or only $\\texttt{B}$, the answer is NO. Otherwise, the answer is YES. Let's show it. As we have just shown, we must have $\\texttt{R}$ next to $\\texttt{B}$ for the string to be possible. Consider the way to make $\\texttt{RBRRBBBB}$. The final stamp can be $\\texttt{RBR}\\underline{\\texttt{RB}}\\texttt{BBB}$. For the rest of the cells, we can make them one by one as below. $\\texttt{WWWWWWWW} \\to \\underline{\\texttt{RB}}\\texttt{WWWWWW} \\to \\texttt{R}\\underline{\\texttt{BR}}\\texttt{WWWWW} \\to \\texttt{RB}\\underline{\\texttt{RB}}\\texttt{WWWW}\\text{,}$ $\\texttt{RBRBWWWW} \\to \\texttt{RBRBWW}\\underline{\\texttt{RB}} \\to \\texttt{RBRBW}\\underline{\\texttt{RB}}\\texttt{B} \\to \\texttt{RBRB}\\underline{\\texttt{RB}}\\texttt{BB}\\text{.}$ Finally, we can put the final stamp to make the whole string. $\\texttt{RBRBRBBB} \\to \\texttt{RBR}\\underline{\\texttt{RB}}\\texttt{BBB}\\text{.}$",
    "code": "for i in range(int(input())):\n    n = int(input())\n    l = input().split('W')\n    bad = False\n    for s in l:\n    \tb1 = 'R' in s\n    \tb2 = 'B' in s\n    \tif (b1 ^ b2):\n    \t\tbad = True\n    print(\"NO\" if bad else \"YES\")",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1669",
    "index": "E",
    "title": "2-Letter Strings",
    "statement": "Given $n$ strings, each of length $2$, consisting of lowercase Latin alphabet letters \\textbf{from 'a' to 'k}', output the number of pairs of indices $(i, j)$ such that $i < j$ and the $i$-th string and the $j$-th string differ in exactly one position.\n\nIn other words, count the number of pairs $(i, j)$ ($i < j$) such that the $i$-th string and the $j$-th string have \\textbf{exactly} one position $p$ ($1 \\leq p \\leq 2$) such that ${s_{i}}_{p} \\neq {s_{j}}_{p}$.\n\nThe answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.",
    "tutorial": "One solution is to go through all given strings, generate all strings that differ in exactly one position, and count the number of times these strings occur in the array. A possible way to count them is by using either the map/dictionary data structure or even simpler - a frequency array. Depending on the implementation, you may need to divide the answer by $2$ because of overcounting pairs. The solution runs in $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n)$ depending on the implementation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t; cin >> t;\n    while(t--) {\n        int n; cin >> n;\n\n        vector<vector<int>> cnt(12, vector<int>(12, 0));\n        long long ans = 0;\n        \n        for(int i = 0;i < n; ++i) {\n            string s; cin >> s;\n            for(int j = 0;j < 2; ++j) {\n                for(char c = 'a'; c <= 'k'; ++c) {\n                    if(c == s[j]) continue;\n                    string a = s; a[j] = c;\n                    ans += cnt[a[0] - 'a'][a[1] - 'a'];\n                }\n            }\n            ++cnt[s[0] - 'a'][s[1] - 'a'];\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "data structures",
      "math",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1669",
    "index": "F",
    "title": "Eating Candies",
    "statement": "There are $n$ candies put from left to right on a table. The candies are numbered from left to right. The $i$-th candy has weight $w_i$. Alice and Bob eat candies.\n\nAlice can eat any number of candies from the left (she can't skip candies, she eats them in a row).\n\nBob can eat any number of candies from the right (he can't skip candies, he eats them in a row).\n\nOf course, if Alice ate a candy, Bob can't eat it (and vice versa).\n\nThey want to be fair. Their goal is to eat the same total weight of candies. What is the most number of candies they can eat in total?",
    "tutorial": "We can solve the problem with a two pointers technique. Let $i$ be the left pointer, initially at $1$, and $j$ be the right pointer, initially at $n$. Let's store Alice and Bob's current totals as $a$ and $b$. Let's iterate $i$ from the left to the right. For each $i$, we should do the following. Increase $a$ by $a_i$ (Alice eats the $i$-th candy). Move $j$ leftwards until Bob's total is at least Alice's total, and update $b$ every time we move. If the two pointers have crossed, then both Alice and Bob took the same candy, which is not possible. So we should exit and output the current answer. Otherwise, if $a=b$ after this step, we should update the current answer to be the value that is equal to Alice and Bob. Both $i$ and $j$ move at most $n$ times in total, so the solution runs in $\\mathcal{O}(n)$.",
    "code": "t = int(input())\nfor test in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n    l = 0\n    r = n - 1\n    suml = a[0]\n    sumr = a[n-1]\n    ans = 0\n    while l < r:\n        if suml == sumr:\n            ans = max(ans, l + 1 + n - r)\n\n        if suml <= sumr:\n            l+=1\n            suml+=a[l]\n\n        elif sumr < suml:\n            r-=1\n            sumr+=a[r]\n            \n    print(ans)",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1669",
    "index": "G",
    "title": "Fall Down",
    "statement": "There is a grid with $n$ rows and $m$ columns, and three types of cells:\n\n- An empty cell, denoted with '.'.\n- A stone, denoted with '*'.\n- An obstacle, denoted with the lowercase Latin letter 'o'.\n\nAll stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)\n\nSimulate the process. What does the resulting grid look like?",
    "tutorial": "Note that the columns don't affect each other, so we can solve for each column by itself. For each column, go from the bottom to the top, and keep track of the row of the last obstacle seen; call it $\\mathrm{last}$. Note that initially, $\\mathrm{last}=n+1$, since we treat the floor as the $n+1$th row of obstacles. Whenever we see a new obstacle, we should update $\\mathrm{last}$. Now, if we ever see a stone, we should move it to row $\\mathrm{last} - 1$, since it will be one row above the last obstacle seen (it will fall on top of it). Afterwards, we should also decrease $\\mathrm{last}$ by $1$, because if any future stones fall on top of it, they will land on the row above this stone. This solution works in $\\mathcal{O}(nm)$. We also accepted slower solutions that run in $\\mathcal{O}(n^2m)$ that simulate each stone falling.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n, m;\n\tcin >> n >> m;\n\tchar g[n + 7][m + 7];\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tcin >> g[i][j];\n\t\t}\n\t}\n\tfor (int j = 0; j < m; j++) {\n\t\tint last = n - 1;\n\t\tfor (int i = n - 1; i >= 0; i--) {\n\t\t\tif (g[i][j] == 'o') {last = i - 1;}\n\t\t\telse if (g[i][j] == '*') {swap(g[i][j], g[last][j]); last--;}\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tcout << g[i][j];\n\t\t}\n\t\tcout << '\\n';\n\t}\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "dfs and similar",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1669",
    "index": "H",
    "title": "Maximal AND",
    "statement": "Let $\\mathsf{AND}$ denote the bitwise AND operation, and $\\mathsf{OR}$ denote the bitwise OR operation.\n\nYou are given an array $a$ of length $n$ and a non-negative integer $k$. You can perform \\textbf{at most} $k$ operations on the array of the following type:\n\n- Select an index $i$ ($1 \\leq i \\leq n$) and replace $a_i$ with $a_i$ $\\mathsf{OR}$ $2^j$ where $j$ is any integer between $0$ and $30$ \\textbf{inclusive}. In other words, in an operation you can choose an index $i$ ($1 \\leq i \\leq n$) and set the $j$-th bit of $a_i$ to $1$ ($0 \\leq j \\leq 30$).\n\nOutput the maximum possible value of $a_1$ $\\mathsf{AND}$ $a_2$ $\\mathsf{AND}$ $\\dots$ $\\mathsf{AND}$ $a_n$ after performing \\textbf{at most} $k$ operations.",
    "tutorial": "The optimal strategy is to greedily take the highest bit we have enough operations to set in every array element. To do this, we maintain a count for each bit with the number of elements that have it set already. The cost to set the $i$-th bit will be $n-\\mathrm{count}_i$. We go from the highest bit to the lowest: If we have enough operations left, we set the bit, subtract its cost from the operations and move to the next lower bit. If we don't have enough operations, we move on to the next lower bit and don't modify the operations. The time complexity is $\\mathcal{O}(n \\log a_i)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nint main() {\n    int t; cin >> t;\n    while(t--) {\n        int n, k; cin >> n >> k;\n        vector<int> cnt(31, 0), a(n);\n        for(int i = 0;i < n; ++i) {\n            cin >> a[i];\n            for(int j = 30; j >= 0; --j) {\n                if(a[i] & (1 << j)) ++cnt[j];\n            }\n        }\n        int ans = 0;\n        for(int i = 30; i >= 0; --i) {\n            int need = n - cnt[i];\n            if(need <= k) {\n                k -= need;\n                ans += (1 << i);\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1670",
    "index": "A",
    "title": "Prof. Slim",
    "statement": "{One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were \\sout{happy} sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder one so that he stays at the GUC. After a long argument, they decided to change it into the following problem.}\n\nGiven an array of $n$ integers $a_1,a_2,\\ldots,a_n$, \\textbf{where $a_{i} \\neq 0$}, check if you can make this array sorted by using the following operation any number of times (possibly zero). An array is sorted if its elements are arranged in a non-decreasing order.\n\n- select two indices $i$ and $j$ ($1 \\le i,j \\le n$) such that $a_i$ and $a_j$ have \\textbf{different signs}. In other words, one must be positive and one must be negative.\n- swap the \\textbf{signs} of $a_{i}$ and $a_{j}$. For example if you select $a_i=3$ and $a_j=-2$, then they will change to $a_i=-3$ and $a_j=2$.\n\nProf. Slim saw that the problem is still too easy and isn't worth his time, so he decided to give it to you to solve.",
    "tutorial": "We can notice that to make the array sorted we must move all the negative signs to the beginning of the array. So let's say the number of negative elements is $k$. Then we must check that the first $k$ elements are non-increasing and the remaining elements are non-decreasing. Complexity is $O(n)$.",
    "code": "import java.io.*;\nimport java.util.StringTokenizer;\n \npublic class A {\n    public static void main(String[] args) throws IOException {\n        Scanner sc = new Scanner(System.in);\n        PrintWriter pw = new PrintWriter(System.out);\n        int tc = sc.nextInt();\n        for (int test = 1; test <= tc; test++) {\n            int n = sc.nextInt();\n            int[] arr = new int[n];\n            for (int i = 0; i < n; i++)\n                arr[i] = sc.nextInt();\n            int i = 0, j = 0;\n            while (i < n) {\n                if (arr[i] < 0) {\n                    arr[j++] *= -1;\n                    arr[i] *= -1;\n                }\n                i++;\n            }\n            if (isSorted(arr)) {\n                pw.println(\"YES\");\n            } else\n                pw.println(\"NO\");\n        }\n        pw.flush();\n    }\n \n    private static boolean isSorted(int[] arr) {\n        for (int i = 1; i < arr.length; i++)\n            if (arr[i] < arr[i - 1])\n                return false;\n        return true;\n    }\n \n    static class Scanner {\n        BufferedReader br;\n        StringTokenizer st;\n \n        public Scanner(InputStream s) {\n            br = new BufferedReader(new InputStreamReader(s));\n        }\n \n        public Scanner(FileReader f) {\n            br = new BufferedReader(f);\n        }\n \n        public String next() throws IOException {\n            while (st == null || !st.hasMoreTokens())\n                st = new StringTokenizer(br.readLine());\n            return st.nextToken();\n        }\n \n        public int nextInt() throws IOException {\n            return Integer.parseInt(next());\n        }\n \n        public long nextLong() throws IOException {\n            return Long.parseLong(next());\n        }\n \n        public double nextDouble() throws IOException {\n            return Double.parseDouble(next());\n        }\n \n        public int[] nextIntArr(int n) throws IOException {\n            int[] arr = new int[n];\n            for (int i = 0; i < n; i++) {\n                arr[i] = Integer.parseInt(next());\n            }\n            return arr;\n        }\n \n    }\n}\n",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1670",
    "index": "B",
    "title": "Dorms War",
    "statement": "Hosssam decided to sneak into Hemose's room while he is sleeping and change his laptop's password. He already knows the password, which is a string $s$ of length $n$. He also knows that there are $k$ special letters of the alphabet: $c_1,c_2,\\ldots, c_k$.\n\nHosssam made a program that can do the following.\n\n- The program considers the current password $s$ of some length $m$.\n- Then it finds all positions $i$ ($1\\le i<m$) such that $s_{i+1}$ is one of the $k$ special letters.\n- Then it deletes all of those positions from the password $s$ \\textbf{even if $s_{i}$ is a special character}. If there are no positions to delete, then the program displays an error message which has a very loud sound.\n\nFor example, suppose the string $s$ is \"abcdef\" and the special characters are 'b' and 'd'. If he runs the program once, the positions $1$ and $3$ will be deleted as they come before special characters, so the password becomes \"bdef\". If he runs the program again, it deletes position $1$, and the password becomes \"def\". If he is wise, he won't run it a third time.\n\nHosssam wants to know how many times he can run the program on Hemose's laptop without waking him up from the sound of the error message. Can you help him?",
    "tutorial": "Let's consider the non-special characters as '0' and special characters as '1' since they are indistinguishable. So now the problem is that we have a binary string, where each '1' character removes the character before it each time the program is run. The trivial case is when there is only one '1' character, the answer then is just the number of '0' characters before it. But what if there is more than one '1' character? lets take for example when there are two '1' characters as follows: $00000010001\\to 000001001\\to 0000101\\to 00011\\to 001\\to 01\\to 1$ The observation here is that when the first '1' character from the right reached the second '1', it acts as if it just replaced its place, so we can say that each '1' character replaces another '1' as soon as it reaches it. So we can partition the binary string into small partitions where each partition contains only one '1' character that is the rightmost character in the partition. For example, the string $00010000001011$ can be partitioned into: $(0001),(0000001),(01),(1)$ We first calculate the amount of time each partition requires to remove all the '0' characters before it, which is basically the number of '0' characters before it. Each partition except for the first partition requires one more second to replace the '1' character in the previous partition. So the answer is the maximum time required among all the partitions.",
    "code": "import java.io.*;\nimport java.util.StringTokenizer;\n \npublic class B{\n \n \n    public static void main(String[] args) throws IOException {\n        Scanner sc = new Scanner(System.in);\n        PrintWriter pw = new PrintWriter(System.out);\n        int tests = sc.nextInt();\n        for (int test = 0; test < tests; test++) {\n            int n = sc.nextInt();\n            char[] arr = sc.next().toCharArray();\n            int k = sc.nextInt();\n            boolean[] special = new boolean[26];\n            for (int i = 0; i < k; i++)\n                special[sc.next().charAt(0) - 'a'] = true;\n            int idx = -1;\n            for (int i = 0; i < n; i++)\n                if (special[arr[i] - 'a'])\n                    idx = i;\n            int max=0;\n            for(int i=idx-1;i>=0;i--){\n                int j=i;\n                while (j>0&&!special[arr[j]-'a'])\n                    j--;\n                max=Math.max(max,i+1-j);\n                i=j;\n            }\n            pw.println(max);\n        }\n        pw.flush();\n    }\n \n \n    public static class Scanner {\n        StringTokenizer st;\n        BufferedReader br;\n \n        public Scanner(InputStream s) {\n            br = new BufferedReader(new InputStreamReader(s));\n        }\n \n        public Scanner(String s) throws FileNotFoundException {\n            br = new BufferedReader(new InputStreamReader(new FileInputStream(s)));\n        }\n \n        public String next() throws IOException {\n            while (st == null || !st.hasMoreTokens())\n                st = new StringTokenizer(br.readLine());\n            return st.nextToken();\n        }\n \n        public int nextInt() throws IOException {\n            return Integer.parseInt(next());\n        }\n \n        public long nextLong() throws IOException {\n            return Long.parseLong(next());\n        }\n    }\n}\n",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1670",
    "index": "C",
    "title": "Where is the Pizza?",
    "statement": "While searching for the pizza, baby Hosssam came across two permutations $a$ and $b$ of length $n$.\n\nRecall that a permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nBaby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $n$.\n\nSpecifically, he mixed up the permutations to form a new array $c$ in the following way.\n\n- For each $i$ ($1\\le i\\le n$), he either made $c_i=a_i$ or $c_i=b_i$.\n- The array $c$ is a permutation.\n\nYou know permutations $a$, $b$, and values at some positions in $c$. Please count the number different permutations $c$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $10^9+7$.\n\nIt is guaranteed that there exists at least one permutation $c$ that satisfies all the requirements.",
    "tutorial": "Let's first solve the version where the array $d$ is filled with $0$'s (in other words there is no constrain on the permutation $c$ that needs to be formed). Let's say we have the permutation $[1,2,3,4]$ as $a$ and the permutation $[3,1,2,4]$ as $b$. Suppose that we have chosen the first element of the array $c$ to be the first element of array $a$, this way we can't choose the first element of array $b$. Since we want array $c$ to be a permutation, we will have to get the first element of $b$ from $a$ (which is $3$). If we search for $3$ in array $a$ and add it to array $c$, we wont be able to choose the element of $b$ in the corresponding index (which is $2$), so we again search for $2$ in array $a$ and add it to $c$. This time, the element in $b$ at the corresponding index is $1$, which is already included in the array $c$, so we are not obliged to select another element from array a. We observe that the elements that we were obliged to choose from $a$ along with the initial element we selected $[1,2,3]$ are a permutation of the elements at the corresponding indices of $b$ $[3,1,2]$, and for each group that has a size bigger than one we have $2$ options, either we select the whole group from $a$, or we select the whole group from $b$. So the answer to this version is to just count the number of groups of size bigger than $1$ (let's say the number of groups is $p$) and print $2^p$. Now what if array $d$ is not filled with $0$'s? We just have to make sure that each group we count has $0$'s in all the corresponding indices of the group we are considering, otherwise this group has only one option and we don't count it. This solution can be implemented in many ways, but using DSU to union each group together is the most elegant way to implement it in my opinion.",
    "code": "import java.io.*;\nimport java.util.HashSet;\nimport java.util.StringTokenizer;\n \npublic class C{\n \n    static int mod = (int) 1e9 + 7;\n \n    public static void main(String[] args) throws IOException {\n        Scanner sc = new Scanner(System.in);\n        PrintWriter pw = new PrintWriter(System.out);\n        int tests = sc.nextInt();\n        for (int test = 0; test < tests; test++) {\n            int n = sc.nextInt();\n            int[] first = new int[n];\n            int[] second = new int[n];\n            int[] third=new int[n];\n            for (int i = 0; i < n; i++)\n                first[i] = sc.nextInt() - 1;\n            for (int i = 0; i < n; i++)\n                second[i] = sc.nextInt() - 1;\n            for(int i=0;i<n;i++)\n                third[i]= sc.nextInt()-1;\n            UnionFind uf = new UnionFind(n);\n            for (int i = 0; i < n; i++)\n                uf.unionSet(first[i], second[i]);\n            HashSet<Integer> set = new HashSet<>();\n            for (int i = 0; i < n; i++)\n                set.add(uf.findSet(i));\n            for(int i=0;i<n;i++){\n                if(third[i]==-1)\n                    continue;\n                set.remove(uf.findSet(third[i]));\n            }\n            int pow = 0;\n            for (int x : set)\n                if (uf.sizeOfSet(x) > 1)\n                    pow++;\n            int ans = 1;\n            for (int i = 0; i < pow; i++)\n                ans = (int) ((2L * ans) % mod);\n            pw.println(ans);\n        }\n        pw.flush();\n    }\n    \n    \n    \n     public static class UnionFind {\n        int[] p, rank, setSize;\n        int numSets;\n \n        public UnionFind(int N) {\n            p = new int[numSets = N];\n            rank = new int[N];\n            setSize = new int[N];\n            for (int i = 0; i < N; i++) {\n                p[i] = i;\n                setSize[i] = 1;\n            }\n        }\n \n        public int findSet(int i) {\n            return p[i] == i ? i : (p[i] = findSet(p[i]));\n        }\n \n        public boolean isSameSet(int i, int j) {\n            return findSet(i) == findSet(j);\n        }\n \n        public void unionSet(int i, int j) {\n            if (isSameSet(i, j))\n                return;\n            numSets--;\n            int x = findSet(i), y = findSet(j);\n            if (rank[x] > rank[y]) {\n                p[y] = x;\n                setSize[x] += setSize[y];\n            } else {\n                p[x] = y;\n                setSize[y] += setSize[x];\n                if (rank[x] == rank[y]) rank[y]++;\n            }\n        }\n \n        public int numDisjointSets() {\n            return numSets;\n        }\n \n        public int sizeOfSet(int i) {\n            return setSize[findSet(i)];\n        }\n    }\n \n \n    public static class Scanner {\n        StringTokenizer st;\n        BufferedReader br;\n \n        public Scanner(InputStream s) {\n            br = new BufferedReader(new InputStreamReader(s));\n        }\n \n        public Scanner(String s) throws FileNotFoundException {\n            br = new BufferedReader(new InputStreamReader(new FileInputStream(s)));\n        }\n \n        public String next() throws IOException {\n            while (st == null || !st.hasMoreTokens())\n                st = new StringTokenizer(br.readLine());\n            return st.nextToken();\n        }\n \n        public int nextInt() throws IOException {\n            return Integer.parseInt(next());\n        }\n \n        public long nextLong() throws IOException {\n            return Long.parseLong(next());\n        }\n    }\n}\n",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1670",
    "index": "D",
    "title": "Very Suspicious",
    "statement": "Sehr Sus is an infinite hexagonal grid as pictured below, controlled by MennaFadali, ZerooCool and Hosssam.\n\nThey love equilateral triangles and want to create $n$ equilateral triangles on the grid by adding some straight lines. The triangles must all be empty from the inside (in other words, no straight line or hexagon edge should pass through any of the triangles).\n\nYou are allowed to add straight lines parallel to the edges of the hexagons. Given $n$, what is the minimum number of lines you need to add to create at least $n$ equilateral triangles as described?\n\n\\begin{center}\n{\\small Adding two red lines results in two new yellow equilateral triangles.}\n\\end{center}",
    "tutorial": "We can notice that there are $3$ different slopes in which we can draw a line, and we can also notice that drawing the lines exactly on the edges of the hexagons will result in the creation of $2$ equilateral triangles at each intersection of $2$ lines, so we can say that: Number of equilateral triangles = 2 *( number of intersections at center of some hexagon). Now we only need to find a way to draw the lines such that it maximizes the number of intersections. The best way to do that is to keep the number of lines on all $3$ slopes as close as possible (the proof will be explained at the bottom). One way to do so is to add the lines once at each slope then repeat. Let's say that slopes are numbered $1$, $2$, and $3$, so we will add the lines as follows $1,2,3,1,2,3,$ and so on. The increase in the intersection will be the number of lines in the other two slopes added together. It will be as follows : $+0, +1, +2, +2, +3, +4, +4, +5, +6, +6, +7, +8, \\ldots$ If we separate that into groups of 3 we will get $\\{0,1,2\\},\\{2,3,4\\},\\{4,5,6\\},\\ldots$ The sum of the groups is $3,9,15,21,\\ldots$ To get the sum of the first $X$ groups it will be $3X^2$. So, to get the number of intersections using $N$ lines we will first find the number of complete groups which is $\\lfloor \\frac{N}{3} \\rfloor$ and then loop over the last group to find the total number of intersections. Now that we have a way to find the number of equilateral triangles created by $N$ lines we can find the number of lines needed to get $X$ equilateral triangles by using binary search. The proof that the best way to maximize the number of intersections is to keep the number of lines on all $3$ slopes as close as possible: Imagine a case in which the difference between the lines in two slops is more than $2$ lines, now we can see that if we moved one line from the larger group to the smaller we will obtain more intersections because after moving, the intersections with the $3$-rd line will be the same and will not be affected and the intersection between the slopes will decrease by the size of the smaller group and increased by the size of the larger group minus $1$ so overall the intersections will increase by at least $1$ so that proves that we can't have any difference more than $1$ and the groups must be as close as possible.",
    "code": "import java.util.*;\nimport java.io.*;\n \npublic class D{\n\tpublic static void main(String[] args) throws Exception {\n\t\tint t=sc.nextInt();\n\t\twhile(t-->0) {\n\t\t\tpw.println(sol(sc.nextInt()));\n\t\t}\n\t\tpw.close();\n\t}\n\t\n\tpublic static int sol(int n) {\n\t\tint low=0;\n\t\tint high=(int)1e9;\n\t\tint mid=(low+high)/2;\n\t\twhile(low<=high) {\n\t\t\tif(calc(mid)<n) {\n\t\t\t\tlow=mid+1;\n\t\t\t}else {\n\t\t\t\thigh=mid-1;\n\t\t\t}\n\t\t\tmid=(low+high)/2;\n\t\t}\n\t\treturn low;\n\t}\n\t\n\tpublic static long calc(long n) {\n\t\tn--;\n\t\tlong ans=0;\n\t\tans=(n/3)*(n/3)*3;\n\t\tfor (int i = 0; i <= n % 3; i++)\n\t\t\tans += (n / 3) * 2 + i;\n\t\treturn ans*2;\n\t}\n \n\tstatic class Scanner {\n\t\tStringTokenizer st;\n\t\tBufferedReader br;\n \n\t\tpublic Scanner(InputStream s) {\n\t\t\tbr = new BufferedReader(new InputStreamReader(s));\n\t\t}\n \n\t\tpublic Scanner(FileReader r) {\n\t\t\tbr = new BufferedReader(r);\n\t\t}\n \n\t\tpublic String next() throws IOException {\n\t\t\twhile (st == null || !st.hasMoreTokens())\n\t\t\t\tst = new StringTokenizer(br.readLine());\n\t\t\treturn st.nextToken();\n\t\t}\n \n\t\tpublic int nextInt() throws IOException {\n\t\t\treturn Integer.parseInt(next());\n\t\t}\n \n\t\tpublic long nextLong() throws IOException {\n\t\t\treturn Long.parseLong(next());\n\t\t}\n \n\t\tpublic String nextLine() throws IOException {\n\t\t\treturn br.readLine();\n\t\t}\n \n\t\tpublic double nextDouble() throws IOException {\n\t\t\tString x = next();\n\t\t\tStringBuilder sb = new StringBuilder(\"0\");\n\t\t\tdouble res = 0, f = 1;\n\t\t\tboolean dec = false, neg = false;\n\t\t\tint start = 0;\n\t\t\tif (x.charAt(0) == '-') {\n\t\t\t\tneg = true;\n\t\t\t\tstart++;\n\t\t\t}\n\t\t\tfor (int i = start; i < x.length(); i++)\n\t\t\t\tif (x.charAt(i) == '.') {\n\t\t\t\t\tres = Long.parseLong(sb.toString());\n\t\t\t\t\tsb = new StringBuilder(\"0\");\n\t\t\t\t\tdec = true;\n\t\t\t\t} else {\n\t\t\t\t\tsb.append(x.charAt(i));\n\t\t\t\t\tif (dec)\n\t\t\t\t\t\tf *= 10;\n\t\t\t\t}\n\t\t\tres += Long.parseLong(sb.toString()) / f;\n\t\t\treturn res * (neg ? -1 : 1);\n\t\t}\n \n\t\tpublic long[] nextlongArray(int n) throws IOException {\n\t\t\tlong[] a = new long[n];\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\ta[i] = nextLong();\n\t\t\treturn a;\n\t\t}\n \n\t\tpublic Long[] nextLongArray(int n) throws IOException {\n\t\t\tLong[] a = new Long[n];\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\ta[i] = nextLong();\n\t\t\treturn a;\n\t\t}\n \n\t\tpublic int[] nextIntArray(int n) throws IOException {\n\t\t\tint[] a = new int[n];\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\ta[i] = nextInt();\n\t\t\treturn a;\n\t\t}\n \n\t\tpublic Integer[] nextIntegerArray(int n) throws IOException {\n\t\t\tInteger[] a = new Integer[n];\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\ta[i] = nextInt();\n\t\t\treturn a;\n\t\t}\n \n\t\tpublic boolean ready() throws IOException {\n\t\t\treturn br.ready();\n\t\t}\n \n\t}\n \n\tstatic Scanner sc = new Scanner(System.in);\n\tstatic PrintWriter pw = new PrintWriter(System.out);\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "geometry",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1670",
    "index": "E",
    "title": "Hemose on the Tree",
    "statement": "After the last regional contest, Hemose and his teammates finally qualified to the ICPC World Finals, so for this great achievement and his love of trees, he gave you this problem as the name of his team \"Hemose 3al shagra\" (Hemose on the tree).\n\nYou are given a tree of $n$ vertices where $n$ is a power of $2$. You have to give each node and edge an integer value in the range $[1,2n -1]$ (inclusive), where all the values are distinct.\n\nAfter giving each node and edge a value, you should select some root for the tree such that the maximum cost of any simple path starting from the root and ending at any \\textbf{node or edge} is minimized.\n\nThe cost of the path between two nodes $u$ and $v$ or any node $u$ and edge $e$ is defined as the bitwise XOR of all the node's and edge's values between them, including the endpoints (note that in a tree there is only one simple path between two nodes or between a node and an edge).",
    "tutorial": "Let's look at the minimum maximum value that we can get if we have an array of numbers from $[1,2^{(p+1)}-1]$ and we are trying to get any prefix xor, the answer will be $2^p$ because you can stop at the first integer that will have the bit $p$ so the answer will be $\\geq 2^p$. We can apply the same concept here, for any arrangement we can start at the root and stop at the first node/edge that has the bit $p$ on. Let's try to find a construction that will make our answer always $2^p$. This is one of the valid ways. Select an arbitrary root. Put $2^p$ at the root. Create $2^p-1$ pairs from the remaining numbers of the form $(x,x+2^p)$ where $x < 2^p$ For every node we will do the following: If its parent has the bit $p$ in its value the node will take the value $x$ and the edge to the parent will take $x+2^p$. If its parent doesn't have the bit $p$ in its value the node will take the value $x+2^p$ and the edge to the parent will take $x$. Using this construction you will find that the xor value form the root will alternate between $0$ and $2^p$ and $x$ which is always $\\le 2^p$ . If its parent has the bit $p$ in its value the node will take the value $x$ and the edge to the parent will take $x+2^p$. If its parent doesn't have the bit $p$ in its value the node will take the value $x+2^p$ and the edge to the parent will take $x$. Using this construction you will find that the xor value form the root will alternate between $0$ and $2^p$ and $x$ which is always $\\le 2^p$ .",
    "code": "import java.util.*;\nimport java.io.*;\n \npublic class E{\n    static ArrayList<int[]>[] adj;\n    static int[] nodeval, edgeval;\n    static int count, N;\n \n    public static void main(String[] args) throws IOException {\n        Scanner sc = new Scanner(System.in);\n        PrintWriter pw = new PrintWriter(System.out);\n        int t = sc.nextInt();\n        while(t-->0){\n        \n            int n = sc.nextInt();\n            N = 1 << n;\n            adj = new ArrayList[N];\n            for (int i = 0; i < N; i++)\n                adj[i] = new ArrayList<>();\n    \n            for (int i = 0; i < N - 1; i++) {\n                int u = sc.nextInt() - 1;\n                int v = sc.nextInt() - 1;\n    \n                adj[u].add(new int[]{v, i});\n                adj[v].add(new int[]{u, i});\n            }\n            nodeval = new int[N];\n            edgeval = new int[N];\n            nodeval[0] = N;\n            count =0;\n            dfs(0, -1);\n    \n            pw.println(1);\n            for (int i = 0; i < N; i++)\n                pw.print(nodeval[i] + \" \");\n            pw.println();\n            for (int i = 0; i < N - 1; i++)\n                pw.print(edgeval[i] + \" \");\n            pw.println();    \n        }\n        pw.close();\n \n    }\n \n    private static void dfs(int u, int p) {\n \n        for (int[] nxt : adj[u]) {\n            int v = nxt[0];\n            int idx = nxt[1];\n            if (v == p)\n                continue;\n            count++;\n            edgeval[idx] = count + ((nodeval[u] & N) != 0 ? N : 0);\n            nodeval[v] = count + ((nodeval[u] & N) != 0 ? 0 : N);\n            dfs(v, u);\n        }\n    }\n \n \n    static class Scanner {\n        BufferedReader br;\n        StringTokenizer st;\n \n        public Scanner(InputStream s) {\n            br = new BufferedReader(new InputStreamReader(s));\n        }\n \n        public Scanner(FileReader f) {\n            br = new BufferedReader(f);\n        }\n \n        public String next() throws IOException {\n            while (st == null || !st.hasMoreTokens())\n                st = new StringTokenizer(br.readLine());\n            return st.nextToken();\n        }\n \n        public int nextInt() throws IOException {\n            return Integer.parseInt(next());\n        }\n \n        public long nextLong() throws IOException {\n            return Long.parseLong(next());\n        }\n \n        public double nextDouble() throws IOException {\n            return Double.parseDouble(next());\n        }\n \n        public int[] nextIntArr(int n) throws IOException {\n            int[] arr = new int[n];\n            for (int i = 0; i < n; i++) {\n                arr[i] = Integer.parseInt(next());\n            }\n            return arr;\n        }\n \n    }\n \n}\n",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1670",
    "index": "F",
    "title": "Jee, You See?",
    "statement": "{During their training for the ICPC competitions, team \"Jee You See\" stumbled upon a very basic counting problem. After many \"Wrong answer\" verdicts, they finally decided to give up and \\sout{destroy} turn-off the PC. Now they want your help in up-solving the problem.}\n\nYou are given 4 integers $n$, $l$, $r$, and $z$. Count the number of arrays $a$ of length $n$ containing non-negative integers such that:\n\n- $l\\le a_1+a_2+\\ldots+a_n\\le r$, and\n- $a_1\\oplus a_2 \\oplus \\ldots\\oplus a_n=z$, where $\\oplus$ denotes the bitwise XOR operation.\n\nSince the answer can be large, print it modulo $10^9+7$.",
    "tutorial": "Let's put aside the XOR constraint and only focus on the sum constraint. let $G(X)$ be the number of ways to construct $n$ integers such that their sum is at most $X$. We will construct each bit of the $n$ integers at the same time, we want to guarantee that the contribution of the sum of the bits generated at each position plus the sum of the previous bits wont exceed $X$ we only have to know the difference between the previous bits of $X$ (add 1 if the current bit is on) and the sum of the generated bits. However we know for sure that at each position we can generate at most $n$ bits which will sum to $n$ at most, so for the next position the difference will be the $2$ * (current difference - the sum of the bits at the cur position). we can see that if the current difference has a value $\\geq$ $2n$ we can place any number of bits at the remaining positions. Let's define $dp[m][k]$ as the number of ways to construct the first $m$ bits of the $n$ integers such that their sum doesn't exceed $X$, where $k$ is min between (the difference between the previous bits and $X$) and $2n$. We can have $count$ from 0 to $min(k,n)$ ones placed at the current bit and for each $count$ we have $n \\choose count$ ways to distribute them. Formally $dp[m][k]= \\sum_{count=0}^{\\min(n,k)} {n \\choose count}\\cdot dp[m+1][2(k-count+currentBit)]$ where $currentBit$ is one if the limit have the bit $m$ on. For the XOR constraint we only have to make sure that count is even if the current bit of Z is 0 or odd if the current bit is 1. The answer of the problem will be $G(R)-G(L-1)$.",
    "code": "import java.io.*;\nimport java.util.Arrays;\nimport java.util.StringTokenizer;\n \npublic class F {\n    static final int mod = (int) 1e9 + 7;\n    static int n;\n    static long l, r, z;\n    static long[][] memo;\n    static long[][] memo2;\n \n    public static long nCr(int n, int r) {\n        if (r == 0)\n            return 1;\n        if (n == 0)\n            return 0;\n        if (memo[n][r] != -1)\n            return memo[n][r];\n        return memo[n][r] = (nCr(n - 1, r) + nCr(n - 1, r - 1)) % mod;\n    }\n \n    public static void main(String[] args) throws IOException {\n        Scanner sc = new Scanner(System.in);\n        PrintWriter pw = new PrintWriter(System.out);\n        int tests = 1;\n        memo = new long[1001][1001];\n        for (long[] x : memo)\n            Arrays.fill(x, -1);\n        for (int test = 0; test < tests; test++) {\n            n = sc.nextInt();\n            l = sc.nextLong();\n            r = sc.nextLong();\n            z = sc.nextLong();\n            long ans = (compute(r) - compute(l - 1) + mod) % mod;\n            pw.println(ans);\n        }\n        pw.flush();\n    }\n \n    private static long compute(long val) {\n        memo2 = new long[61][2001];\n        for (long[] x : memo2)\n            Arrays.fill(x, -1);\n        return dp(60, 0, val);\n    }\n \n    private static long dp(int idx, int rem, long val) {\n        if (rem > 2000)\n            rem = 2000;\n        if (rem < 0)\n            return 0;\n        if (idx == -1)\n            return 1;\n        if (memo2[idx][rem] != -1)\n            return memo2[idx][rem];\n        long ans = 0;\n        int currentBitXor = (z & 1L << idx)== 0 ? 0 : 1;\n        for (int i = currentBitXor == 1 ? 1 : 0; i <= n; i += 2) {\n            int currentBitSum = (val & 1L << idx) == 0 ? 0 : 1;\n            int nextRem = 2 * (rem + currentBitSum - i);\n            long toAdd = (nCr(n, i) * dp(idx - 1, nextRem, val)) % mod;\n            ans = (ans + toAdd) % mod;\n        }\n        return memo2[idx][rem] = ans;\n    }\n \n \n    public static class Scanner {\n        StringTokenizer st;\n        BufferedReader br;\n \n        public Scanner(InputStream s) {\n            br = new BufferedReader(new InputStreamReader(s));\n        }\n \n        public Scanner(String s) throws FileNotFoundException {\n            br = new BufferedReader(new InputStreamReader(new FileInputStream(s)));\n        }\n \n        public String next() throws IOException {\n            while (st == null || !st.hasMoreTokens())\n                st = new StringTokenizer(br.readLine());\n            return st.nextToken();\n        }\n \n        public int nextInt() throws IOException {\n            return Integer.parseInt(next());\n        }\n \n        public long nextLong() throws IOException {\n            return Long.parseLong(next());\n        }\n    }\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1671",
    "index": "A",
    "title": "String Building",
    "statement": "You are given a string $s$. You have to determine whether it is possible to build the string $s$ out of strings aa, aaa, bb and/or bbb by concatenating them. You can use the strings aa, aaa, bb and/or bbb any number of times and in any order.\n\nFor example:\n\n- aaaabbb can be built as aa $+$ aa $+$ bbb;\n- bbaaaaabbb can be built as bb $+$ aaa $+$ aa $+$ bbb;\n- aaaaaa can be built as aa $+$ aa $+$ aa;\n- abab cannot be built from aa, aaa, bb and/or bbb.",
    "tutorial": "Every character in strings aa, aaa, bb and bbb has at least one character adjacent to it that is the same. So, if there is an isolated character in our string (a character that has no neighbors equal to it), we cannot build it. It's easy to see that in the other case, we can build the string: we can split it into blocks of consecutive equal characters, and since there are no isolated characters, each block will have at least $2$ characters, so it can be formed from strings of length $2$ and/or $3$ consisting of equal characters. So, the problem is reduced to checking if each character has a neighbor equal to it.",
    "code": "t = int(input())\nfor i in range(t):\n    s = input()\n    ans = True\n    n = len(s)\n    for j in range(n):\n        if (j == 0 or s[j] != s[j - 1]) and (j == n - 1 or s[j] != s[j + 1]):\n            ans = False\n    print('YES' if ans else 'NO')\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1671",
    "index": "B",
    "title": "Consecutive Points Segment",
    "statement": "You are given $n$ points with integer coordinates on a coordinate axis $OX$. The coordinate of the $i$-th point is $x_i$. All points' coordinates are distinct and given in strictly increasing order.\n\nFor each point $i$, you can do the following operation \\textbf{no more than once}: take this point and move it by $1$ to the left or to the right (i..e., you can change its coordinate $x_i$ to $x_i - 1$ or to $x_i + 1$). In other words, for each point, you choose (separately) its new coordinate. For the $i$-th point, it can be either $x_i - 1$, $x_i$ or $x_i + 1$.\n\nYour task is to determine if you can move some points as described above in such a way that the new set of points forms a \\textbf{consecutive segment} of integers, i. e. for some integer $l$ the coordinates of points should be equal to $l, l + 1, \\ldots, l + n - 1$.\n\nNote that the resulting points should have \\textbf{distinct} coordinates.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "We can see that the answer is YES if and only if there are no more than two gaps of length $1$ between the given points. If there is no gap, the answer is obviously YES. If there is only one gap of length $1$, we can just move the left (or the right) part of the set to this gap. When there are two gaps, we can move the part before the first gap to the right and the part after the second gap to the left. Of course, if there is a gap of length at least $3$ (or multiple gaps with the total length $3$), we can't move the points from the left and the right part to satisfy the middle gap. Time complexity: $O(n)$.",
    "code": "for i in range(int(input())):\n    n = int(input())\n    x = list(map(int, input().split()))\n    print('YES' if x[-1] - x[0] - n + 1 <= 2 else 'NO')",
    "tags": [
      "brute force",
      "math",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1671",
    "index": "C",
    "title": "Dolce Vita",
    "statement": "Turbulent times are coming, so you decided to buy sugar in advance. There are $n$ shops around that sell sugar: the $i$-th shop sells one pack of sugar for $a_i$ coins, but only \\textbf{one pack to one customer} each day. So in order to buy several packs, you need to visit several shops.\n\nAnother problem is that prices are increasing each day: during the first day the cost is $a_i$, during the second day cost is $a_i + 1$, during the third day — $a_i + 2$ and so on for each shop $i$.\n\nOn the contrary, your everyday budget is only $x$ coins. In other words, each day you go and buy as many packs as possible with total cost not exceeding $x$. Note that if you don't spend some amount of coins during a day, you can't use these coins during the next days.\n\nEventually, the cost for each pack will exceed $x$, and you won't be able to buy even a single pack. So, how many packs will you be able to buy till that moment in total?",
    "tutorial": "Firstly, note that if we want to buy as many packs as possible, then it's optimal to buy the cheapest packs. In other words, if we sort all packs, we'll always buy a prefix of array $a$. Next, note that each day we buy some number of packs $i \\in [1, n]$, so, instead of iterating through the days, we can iterate through the number of packs $i$ and for each $i$ calculate the number of days we'll buy exactly $i$ packs. Since the prices increasing and at day $k + 1$ the price is $a_i + k$, then exists last day $k_i + 1$ such that as days $1, 2, \\dots, k_i + 1$ we could buy $i$ packs and at days $k_i + 2, k_i + 3, \\dots$ we can't. And we can find $k_i$ as maximum possible integer solution to inequation $(a_1 + k_i) + \\dots + (a_i + k_i) \\le x$ or $k_i = \\left\\lfloor \\frac{x - (a_1 + \\dots + a_i)}{i} \\right\\rfloor$. We can calculate all $k_i$ using prefix sums $a_1 + \\dots + a_i$ in linear time. As a result, we buy $n$ packs in days $(0, k_1 + 1]$; $n \\cdot (k_1 + 1)$ in total; $n - 1$ packs in days $(k_1 + 1, k_2 + 1]$; $(n - 1) \\cdot (k_2 - k_1)$ in total; $n - 2$ packs in days $(k_2 + 1, k_3 + 1]$; $(n - 2) \\cdot (k_3 - k_2)$ in total and so on. The resulting complexity is $O(n \\log{n})$ because of sort.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val (n, x) = readLine()!!.split(' ').map { it.toInt() }\n        val a = readLine()!!.split(' ').map { it.toInt() }.sorted()\n\n        var sum = a.sumOf { it.toLong() }\n        var prevDay = -1L\n        var ans = 0L\n        for (i in n - 1 downTo 0) {\n            val curDay = if (x - sum >= 0) (x - sum) / (i + 1) else -1\n            ans += (i + 1) * (curDay - prevDay)\n            prevDay = curDay\n            sum -= a[i]\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1671",
    "index": "D",
    "title": "Insert a Progression",
    "statement": "You are given a sequence of $n$ integers $a_1, a_2, \\dots, a_n$. You are also given $x$ integers $1, 2, \\dots, x$.\n\nYou are asked to insert each of the extra integers into the sequence $a$. Each integer can be inserted at the beginning of the sequence, at the end of the sequence, or between any elements of the sequence.\n\nThe score of the resulting sequence $a'$ is the sum of absolute differences of adjacent elements in it $\\left(\\sum \\limits_{i=1}^{n+x-1} |a'_i - a'_{i+1}|\\right)$.\n\nWhat is the smallest possible score of the resulting sequence $a'$?",
    "tutorial": "Observe the cost of inserting a single element. Notice that inserting any value between the minimum of the sequence and the maximum of the sequence is free. Why is this true? The argument is similar to the algorithm of finding some $x$ such that $f(x) = 0$ for a continous function $f$ if you know some $x_1$ such that $f(x_1) < 0$ and $x_2$ such that $f(x_2) > 0$. As a more general idea, it's free to insert some value $s$ into a segment $[l; r]$ such that $a_l \\le s$ and $s \\le a_r$ (WLOG assume $a_l \\le a_r$). Let's find the position that is free. If $r - l = 1$, then you can insert $s$ between $a_l$ and $a_r$, since it's free. Otherwise, you can choose an arbitrary position $l < i < r$. $s$ will be either between $a_i$ and $a_l$ or between $a_i$ and $a_r$ (or both of them). Descend into the one that holds to continue the search. Since the lenght decreases, at some point you will reach the segment of length $1$. How does that help? Well, you can insert $1$ somewhere, then insert $x$ somewhere. The rest of insertions will be free. Now it's an algorithmic problem. First, consider all options to insert both $1$ and $x$ between the same pair of elements. Next, assume you insert $1$ somewhere before $x$. Iterate from left to right, maintaning the lowest price to insert $1$. Try to insert $x$ at the current position and $1$ into the cheapest position before it. Then update the lowest price for inserting $1$. After you finish, reverse the sequence and solve the problem again - that will be the same as inserting $x$ before $1$. Overall complexity: $O(n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n    int t;\n    scanf(\"%d\", &t);\n    forn(_, t){\n        int n, x;\n        scanf(\"%d%d\", &n, &x);\n        vector<int> a(n);\n        forn(i, n) scanf(\"%d\", &a[i]);\n        long long ans = 1e18;\n        long long cur = 0;\n        forn(i, n - 1){\n            cur += abs(a[i] - a[i + 1]);\n        }\n        forn(_, 2){\n            long long mn = abs(a[0] - 1);\n            ans = min(ans, cur + abs(a[0] - x) + (x - 1));\n            forn(i, n - 1){\n                ans = min(ans, cur + mn - abs(a[i] - a[i + 1]) + abs(a[i] - x) + abs(a[i + 1] - x));\n                ans = min(ans, cur - abs(a[i] - a[i + 1]) + abs(a[i] - x) + abs(a[i + 1] - 1) + (x - 1));\n                mn = min(mn, 0ll - abs(a[i] - a[i + 1]) + abs(a[i] - 1) + abs(a[i + 1] - 1));\n            }\n            ans = min(ans, cur + mn + abs(a.back() - x));\n            reverse(a.begin(), a.end());\n        }\n        printf(\"%lld\\n\", ans);\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1671",
    "index": "E",
    "title": "Preorder",
    "statement": "You are given a rooted tree of $2^n - 1$ vertices. Every vertex of this tree has either $0$ children, or $2$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.\n\nThe vertices of the tree are numbered in the following order:\n\n- the root has index $1$;\n- if a vertex has index $x$, then its left child has index $2x$, and its right child has index $2x+1$.\n\nEvery vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $x$ as $s_x$.\n\nLet the preorder string of some vertex $x$ be defined in the following way:\n\n- if the vertex $x$ is a leaf, then the preorder string of $x$ be consisting of only one character $s_x$;\n- otherwise, the preorder string of $x$ is $s_x + f(l_x) + f(r_x)$, where $+$ operator defines concatenation of strings, $f(l_x)$ is the preorder string of the left child of $x$, and $f(r_x)$ is the preorder string of the right child of $x$.\n\nThe preorder string of the tree is the preorder string of its root.\n\nNow, for the problem itself...\n\nYou have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree:\n\n- choose any non-leaf vertex $x$, and swap its children (so, the left child becomes the right one, and vice versa).",
    "tutorial": "In terms of preorder strings, the operation \"swap two children of some vertex\" means \"swap two substrings of equal length in some specific location\". This operation can be inverted by applying it an additional time, so for every positive integer $k$, all of the strings of length $2^k-1$ are split into equivalence classes in such a way that two strings from the same class can be transformed into each other, and two strings from different classes cannot. For each vertex, the set of its possible preorder strings is one of these classes. Let's calculate the answer for the problem recursively: let $dp_v$ be the number of preorder strings for the vertex $v$. For a leaf, the number of its preorder strings is $1$. For a vertex $x$ with children $y$ and $z$, one of the two holds: if the equivalence class for vertex $y$ is different from the equivalence class for vertex $z$, then we have to pick a string from the class of vertex $y$, pick a string from the class of vertex $z$, and choose the order in which we take them. So, $dp_x = dp_y \\cdot dp_z + dp_z \\cdot dp_y = 2 \\cdot dp_y \\cdot dp_z$; if the equivalence class for $y$ is the same as the equivalence class for $z$, then swapping $y$ and $z$ doesn't do anything, so we pick a string from the equivalence class of $y$, and then a string from the equivalence class of $z$. So, $dp_x = dp_y \\cdot dp_z = dp_y^2$. The only thing we don't know is how to determine if two vertices represent the same equivalence class. The model solution uses hashing for this, but there's a much simpler method: for each vertex $v$, let $t_v$ be the lexicographically smallest string that can be a preorder string of $v$. If a vertex $x$ has children $y$ and $z$, then $t_x = \\min(t_y + s_x + t_z, t_z + s_x + t_y)$, and we can calculate these strings recursively since the total length is $O(n 2^n)$ - each of $2^n-1$ characters will be present in $O(n)$ strings.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nmt19937 rnd(42);\n\nconst int MOD = 998244353;\nconst int K = 3;\n\nint add(int x, int y, int mod = MOD)\n{\n    x += y;\n    while(x >= mod) x -= mod;\n    while(x < 0) x += mod;\n    return x;\n}   \n\nint sub(int x, int y, int mod = MOD)\n{\n    return add(x, -y, mod);\n}   \n\nint mul(int x, int y, int mod = MOD)\n{\n    return (x * 1ll * y) % mod;\n}\n\nint binpow(int x, int y, int mod = MOD)\n{\n    int z = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1) z = mul(z, x, mod);\n        y /= 2;\n        x = mul(x, x, mod);\n    }   \n    return z;\n}\n\nbool prime(int x)\n{\n    for(int i = 2; i * 1ll * i <= x; i++)\n        if(x % i == 0)\n            return false;\n    return true;    \n}   \n\nint get_base()\n{\n    int x = rnd() % 10000 + 4444;\n    while(!prime(x)) x++;\n    return x;\n}   \n\nint get_modulo()\n{\n    int x = rnd() % int(1e9) + int(1e8);\n    while(!prime(x)) x++;\n    return x;\n}   \n\ntypedef array<int, K> hs;\n\nhs base, modulo;\n\nvoid generate_hs()\n{\n    for(int i = 0; i < K; i++)\n    {\n        base[i] = get_base();\n        modulo[i] = get_modulo();\n    }\n}   \n\nhs operator+(const hs& a, const hs& b)\n{\n    hs c;\n    for(int i = 0; i < K; i++)\n    {\n        c[i] = add(a[i], b[i], modulo[i]);    \n    }\n    return c;\n}\n\nhs operator-(const hs& a, const hs& b)\n{\n    hs c;\n    for(int i = 0; i < K; i++)\n    {\n        c[i] = sub(a[i], b[i], modulo[i]);    \n    }\n    return c;\n}\n\nhs operator*(const hs& a, const hs& b)\n{\n    hs c;\n    for(int i = 0; i < K; i++)\n    {\n        c[i] = mul(a[i], b[i], modulo[i]);    \n    }\n    return c;\n}\n\nhs operator^(const hs& a, const hs& b)\n{\n    hs c; \n    for(int i = 0; i < K; i++)\n    {\n        c[i] = binpow(a[i], b[i], modulo[i]);    \n    }\n    return c;\n}\n\nhs char_hash(char c)\n{\n    hs res;\n    for(int i = 0; i < K; i++)\n        res[i] = c - 'A' + 1;\n    return res;\n}\n\nconst int N = 18;\nconst int V = 1 << N;\nstring s;\nchar buf[V + 43];\nint n;\nint ans[V + 43];\nhs vertex_hash[V + 43];\n\nbool is_leaf(int x)\n{\n    return (x * 2 + 1) >= ((1 << n) - 1);\n}\n\nvoid rec(int x)\n{\n    vertex_hash[x] = char_hash(s[x]);\n    ans[x] = 1;\n    if(is_leaf(x)) \n    {\n        return;\n    }\n    rec(x * 2 + 1);\n    rec(x * 2 + 2);\n    vertex_hash[x] = vertex_hash[x] + (base ^ vertex_hash[2 * x + 1]) + (base ^ vertex_hash[2 * x + 2]);\n    ans[x] = mul(ans[2 * x + 1], ans[2 * x + 2]);\n    if(vertex_hash[2 * x + 1] != vertex_hash[2 * x + 2])\n        ans[x] = mul(ans[x], 2);\n}\n \nint main() \n{\n    generate_hs();\n    scanf(\"%d\", &n);\n    scanf(\"%s\", buf);\n    s = buf;\n    rec(0);\n    cout << ans[0] << endl;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp",
      "dsu",
      "hashing",
      "sortings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1671",
    "index": "F",
    "title": "Permutation Counting",
    "statement": "Calculate the number of permutations $p$ of size $n$ with exactly $k$ inversions (pairs of indices $(i, j)$ such that $i < j$ and $p_i > p_j$) and exactly $x$ indices $i$ such that $p_i > p_{i+1}$.\n\nYep, that's the whole problem. Good luck!",
    "tutorial": "A lot of solutions which were written during the contest use Berlekamp-Messey or some other algorithms related to analyzing linear recurrences, but the model solution is based on other principles. First of all, if the number of inversions is at most $11$, it means that most elements of the permutation will stay at their own places, and those which don't stay at their places can't be too far away from them. Let's denote a block $[l, r]$ in a permutation as a segment of indices $[l, r]$ such that: all elements less than $l$ are to the left of the block; all elements greater than $r$ are to the right of the block; all elements from $[l, r]$ belong to the block. Let's say that a block is non-trivial if it contains at least two elements. Suppose we split a permutation into the maximum number of blocks. Then, for each block, we can see that: if its length is $b$, it has at least $b-1$ inversions (to prove it, you can use the fact that the number of inversions is equal to the number of swaps of adjacent elements required to sort the permutation; and if we cannot split the block into other blocks, it means that we have to swap each pair of adjacent elements in it at least once to sort it) if the block is non-trivial, it has at least one $i$ such that $p_i > p_{i+1}$. From these two facts, we can see that: there will be at most $11$ non-trivial blocks; there will be at most $22$ elements in total belonging to non-trivial blocks; the maximum possible length of a block is $12$. The main idea of the solution is to calculate the following dynamic programming: $dp_{i,j,a,b}$ is the number of ways to split $j$ elements into $i$ non-trivial blocks such that there are exactly $b$ inversions in them and exactly $a$ pairs $p_i > p_{i+1}$. Then, to get the answer for the test case \"$n$ $k$ $x$\", we can iterate on the number of non-trivial blocks and the number of elements in them, and choose the elements belonging to that blocks with a binomial coefficient. The only thing that's left is how to calculate this dynamic programming efficiently. There are a few ways to do it, but the model solution uses a table $cnt_{a,b,c}$ - the number of different non-trivial blocks of length $a$ with $b$ elements $p_i > p_{i+1}$ and $c$ inversions - to handle transitions. This table is not very big, so you can run an exhaustive search for $2$-$3$ minutes to calculate it and then just paste its results into the source code of your program. Note that you have to make sure that you consider only the blocks which cannot be split any further.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nconst int K = 13;\nconst int MOD = 998244353;\n\nint n, k, x;\n\nint cnt[K][K][K];\nint dp[K][2 * K][K][K];\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}   \n\nint sub(int x, int y)\n{\n    return add(x, -y);\n}   \n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1) z = mul(z, x);\n        y /= 2;\n        x = mul(x, x);\n    }   \n    return z;\n}\n\nvoid precalc()\n{\n    cnt[2][1][1] = 1;\n    cnt[3][1][2] = 2;\n    cnt[3][2][3] = 1;\n    cnt[4][1][3] = 3;\n    cnt[4][1][4] = 1;\n    cnt[4][2][3] = 1;\n    cnt[4][2][4] = 4;\n    cnt[4][2][5] = 3;\n    cnt[4][3][6] = 1;\n    cnt[5][1][4] = 4;\n    cnt[5][1][5] = 2;\n    cnt[5][1][6] = 2;\n    cnt[5][2][4] = 4;\n    cnt[5][2][5] = 12;\n    cnt[5][2][6] = 12;\n    cnt[5][2][7] = 9;\n    cnt[5][2][8] = 3;\n    cnt[5][3][5] = 2;\n    cnt[5][3][6] = 4;\n    cnt[5][3][7] = 6;\n    cnt[5][3][8] = 6;\n    cnt[5][3][9] = 4;\n    cnt[5][4][10] = 1;\n    cnt[6][1][5] = 5;\n    cnt[6][1][6] = 3;\n    cnt[6][1][7] = 4;\n    cnt[6][1][8] = 3;\n    cnt[6][1][9] = 1;\n    cnt[6][2][5] = 10;\n    cnt[6][2][6] = 28;\n    cnt[6][2][7] = 35;\n    cnt[6][2][8] = 35;\n    cnt[6][2][9] = 30;\n    cnt[6][2][10] = 17;\n    cnt[6][2][11] = 8;\n    cnt[6][3][5] = 1;\n    cnt[6][3][6] = 13;\n    cnt[6][3][7] = 29;\n    cnt[6][3][8] = 41;\n    cnt[6][3][9] = 44;\n    cnt[6][3][10] = 45;\n    cnt[6][3][11] = 30;\n    cnt[6][4][7] = 1;\n    cnt[6][4][8] = 4;\n    cnt[6][4][9] = 7;\n    cnt[6][4][10] = 7;\n    cnt[6][4][11] = 11;\n    cnt[7][1][6] = 6;\n    cnt[7][1][7] = 4;\n    cnt[7][1][8] = 6;\n    cnt[7][1][9] = 6;\n    cnt[7][1][10] = 6;\n    cnt[7][1][11] = 2;\n    cnt[7][2][6] = 20;\n    cnt[7][2][7] = 55;\n    cnt[7][2][8] = 80;\n    cnt[7][2][9] = 95;\n    cnt[7][2][10] = 101;\n    cnt[7][2][11] = 94;\n    cnt[7][3][6] = 6;\n    cnt[7][3][7] = 50;\n    cnt[7][3][8] = 118;\n    cnt[7][3][9] = 186;\n    cnt[7][3][10] = 230;\n    cnt[7][3][11] = 260;\n    cnt[7][4][7] = 3;\n    cnt[7][4][8] = 18;\n    cnt[7][4][9] = 48;\n    cnt[7][4][10] = 85;\n    cnt[7][4][11] = 113;\n    cnt[7][5][10] = 2;\n    cnt[7][5][11] = 4;\n    cnt[8][1][7] = 7;\n    cnt[8][1][8] = 5;\n    cnt[8][1][9] = 8;\n    cnt[8][1][10] = 9;\n    cnt[8][1][11] = 11;\n    cnt[8][2][7] = 35;\n    cnt[8][2][8] = 96;\n    cnt[8][2][9] = 155;\n    cnt[8][2][10] = 207;\n    cnt[8][2][11] = 250;\n    cnt[8][3][7] = 21;\n    cnt[8][3][8] = 145;\n    cnt[8][3][9] = 358;\n    cnt[8][3][10] = 616;\n    cnt[8][3][11] = 859;\n    cnt[8][4][7] = 1;\n    cnt[8][4][8] = 26;\n    cnt[8][4][9] = 124;\n    cnt[8][4][10] = 313;\n    cnt[8][4][11] = 567;\n    cnt[8][5][9] = 3;\n    cnt[8][5][10] = 16;\n    cnt[8][5][11] = 53;\n    cnt[9][1][8] = 8;\n    cnt[9][1][9] = 6;\n    cnt[9][1][10] = 10;\n    cnt[9][1][11] = 12;\n    cnt[9][2][8] = 56;\n    cnt[9][2][9] = 154;\n    cnt[9][2][10] = 268;\n    cnt[9][2][11] = 389;\n    cnt[9][3][8] = 56;\n    cnt[9][3][9] = 350;\n    cnt[9][3][10] = 898;\n    cnt[9][3][11] = 1654;\n    cnt[9][4][8] = 8;\n    cnt[9][4][9] = 126;\n    cnt[9][4][10] = 552;\n    cnt[9][4][11] = 1404;\n    cnt[9][5][9] = 4;\n    cnt[9][5][10] = 48;\n    cnt[9][5][11] = 204;\n    cnt[9][6][11] = 1;\n    cnt[10][1][9] = 9;\n    cnt[10][1][10] = 7;\n    cnt[10][1][11] = 12;\n    cnt[10][2][9] = 84;\n    cnt[10][2][10] = 232;\n    cnt[10][2][11] = 427;\n    cnt[10][3][9] = 126;\n    cnt[10][3][10] = 742;\n    cnt[10][3][11] = 1967;\n    cnt[10][4][9] = 36;\n    cnt[10][4][10] = 448;\n    cnt[10][4][11] = 1887;\n    cnt[10][5][9] = 1;\n    cnt[10][5][10] = 43;\n    cnt[10][5][11] = 357;\n    cnt[10][6][11] = 6;\n    cnt[11][1][10] = 10;\n    cnt[11][1][11] = 8;\n    cnt[11][2][10] = 120;\n    cnt[11][2][11] = 333;\n    cnt[11][3][10] = 252;\n    cnt[11][3][11] = 1428;\n    cnt[11][4][10] = 120;\n    cnt[11][4][11] = 1302;\n    cnt[11][5][10] = 10;\n    cnt[11][5][11] = 252;\n    cnt[11][6][11] = 5;\n    cnt[12][1][11] = 11;\n    cnt[12][2][11] = 165;\n    cnt[12][3][11] = 462;\n    cnt[12][4][11] = 330;\n    cnt[12][5][11] = 55;\n    cnt[12][6][11] = 1;    \n}\n\nint inv[K];\n\nint C(int n, int k)\n{\n    if(n < 0 || n < k || k < 0) return 0;\n    int res = 1;\n    for(int i = n; i > n - k; i--)\n        res = mul(res, i);\n    for(int i = 1; i <= k; i++)\n        res = mul(res, inv[i]);\n    return res;\n}\n\nvoid prepare()\n{\n    for(int i = 1; i < K; i++)\n        inv[i] = binpow(i, MOD - 2);\n    precalc();\n    dp[0][0][0][0] = 1;\n    for(int i = 0; i < K; i++)\n        for(int j = 0; j < 2 * K; j++)\n            for(int a = 0; a < K - 2; a++)\n                for(int b = 0; b < K - 2; b++)\n                {\n                    if(dp[i][j][a][b] == 0) continue;\n                    for(int add_cnt = 2; add_cnt < K; add_cnt++)\n                        for(int add_desc = 1; add_desc <= K - 2; add_desc++)\n                            for(int add_inv = 1; add_inv <= K - 2; add_inv++)\n                            {\n                                if(j + add_cnt >= 2 * K || a + add_desc > K - 2 || b + add_inv > K - 2) continue;\n                                int& nw = dp[i + 1][j + add_cnt][a + add_desc][b + add_inv];\n                                nw = add(nw, mul(dp[i][j][a][b], cnt[add_cnt][add_desc][add_inv]));    \n                            }\n                }       \n}\n\nvoid solve() \n{\n    scanf(\"%d %d %d\", &n, &k, &x);\n    if(k == 0 && x == 0)\n    {\n        puts(\"1\");\n        return;\n    }\n    int ans = 0;\n    for(int i = 1; i < K; i++)\n        for(int j = 1; j < 2 * K; j++)\n            if(dp[i][j][x][k] != 0)\n            {\n                ans = add(ans, mul(dp[i][j][x][k], C(n - j + i, i)));        \n            }\n    printf(\"%d\\n\", ans);\n}\n\nint main()\n{\n    prepare();\n    int t;\n    scanf(\"%d\", &t);\n    for(int i = 0; i < t; i++)\n        solve();\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1672",
    "index": "A",
    "title": "Log Chopping",
    "statement": "There are $n$ logs, the $i$-th log has a length of $a_i$ meters. Since chopping logs is tiring work, errorgorn and maomao90 have decided to play a game.\n\nerrorgorn and maomao90 will take turns chopping the logs with \\textbf{errorgorn chopping first}. On his turn, the player will pick a log and chop it into $2$ pieces. If the length of the chosen log is $x$, and the lengths of the resulting pieces are $y$ and $z$, then $y$ and $z$ have to be \\textbf{positive integers}, and $x=y+z$ must hold. For example, you can chop a log of length $3$ into logs of lengths $2$ and $1$, but not into logs of lengths $3$ and $0$, $2$ and $2$, or $1.5$ and $1.5$.\n\nThe player who is unable to make a chop will be the loser. Assuming that both errorgorn and maomao90 play optimally, who will be the winner?",
    "tutorial": "No matter what move each player does, the result of the game will always be the same. Count the number of moves. Let us consider the ending state of the game. It turns out that at the ending state, we will only have logs of $1$ meter. Otherwise, players can make a move. Now, at the ending state of the game, we will have $\\sum\\limits_{k=1}^n a_k$ logs. And each move we increase the number of logs by exactly $1$. Since we started with $n$ logs, there has been exactly $(\\sum\\limits_{k=1}^n a_k) - n$ turns. Alternatively, a log of length $a_k$ will be cut $a_k-1$ times, so there will be $\\sum\\limits_{k=1}^n (a_k-1)$ turns. If there were an odd number of turns $\\texttt{errorgorn}$ wins, otherwise $\\texttt{maomao90}$ wins.",
    "code": "// Super Idol的笑容\n//    都没你的甜\n//  八月正午的阳光\n//    都没你耀眼\n//  热爱105°C的你\n// 滴滴清纯的蒸馏水\n\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n\n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nint n;\nint arr[105];\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tint TC;\n\tcin>>TC;\n\twhile (TC--){\n\t\tcin>>n;\n\t\trep(x,0,n) cin>>arr[x];\n\t\t\n\t\tint tot=0;\n\t\trep(x,0,n) tot+=arr[x]-1;\n\t\t\n\t\tif (tot%2==0) cout<<\"maomao90\"<<endl;\n\t\telse cout<<\"errorgorn\"<<endl;\n\t}\n}\n",
    "tags": [
      "games",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1672",
    "index": "B",
    "title": "I love AAAB",
    "statement": "Let's call a string \\textbf{good} if its length is at least $2$ and all of its characters are $A$ except for the last character which is $B$. The good strings are $AB,AAB,AAAB,\\ldots$. Note that $B$ is \\textbf{not} a good string.\n\nYou are given an initially empty string $s_1$.\n\nYou can perform the following operation any number of times:\n\n- Choose any position of $s_1$ and insert some good string in that position.\n\nGiven a string $s_2$, can we turn $s_1$ into $s_2$ after some number of operations?",
    "tutorial": "Pretend that we can only insert $\\texttt{AB}$. What if we replaced $\\texttt{A}$ and $\\texttt{B}$ with $\\texttt{(}$ and $\\texttt{)}$? Claim: The string is obtainable if it ends in $\\texttt{B}$ and every prefix of the string has at least as many $\\texttt{A}$ as $\\texttt{B}$. An alternative way to think about the second condition is to assign $\\texttt{A}$ to have a value of $1$ and $\\texttt{B}$ to have a value of $-1$. Then, we are just saying that each prefix must have a non-negative sum. This is pretty similar to bracket sequences. Now, both conditions are clearly necessary, let us show that they are sufficient too. We will explicitly construct the string (in the reverse direction). While there are more than $1$ occurrences of $\\texttt{B}$ in the string, remove the first occurrence of $\\texttt{AB}$. After doing this process, you will eventually end up with the string $\\texttt{AAA...AAB}$.",
    "code": "// Super Idol的笑容\n//    都没你的甜\n//  八月正午的阳光\n//    都没你耀眼\n//  热爱105°C的你\n// 滴滴清纯的蒸馏水\n\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n\n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tint TC;\n\tcin>>TC;\n\twhile (TC--){\n\t\tstring s;\n\t\tcin>>s;\n\t\t\n\t\tbool ok=(s.back()=='B');\n\t\t\n\t\tint sum=0;\n\t\tfor (auto it:s){\n\t\t\tif (it=='A') sum++;\n\t\t\telse sum--;\n\t\t\tif (sum<0) ok=false;\n\t\t}\n\t\t\n\t\tif (ok) cout<<\"YES\"<<endl;\n\t\telse cout<<\"NO\"<<endl;\n\t}\n}\n",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1672",
    "index": "C",
    "title": "Unequal Array",
    "statement": "You are given an array $a$ of length $n$. We define the \\textbf{equality} of the array as the number of indices $1 \\le i \\le n - 1$ such that $a_i = a_{i + 1}$. We are allowed to do the following operation:\n\n- Select two integers $i$ and $x$ such that $1 \\le i \\le n - 1$ and $1 \\le x \\le 10^9$. Then, set $a_i$ and $a_{i + 1}$ to be equal to $x$.\n\nFind the minimum number of operations needed such that the equality of the array is less than or equal to $1$.",
    "tutorial": "If the array is $a=[1,1,\\ldots,1]$. We will need $0$ moves if $n \\leq 2$ and will need $\\max(n-3,1)$ moves. The only way to reduce the number of $i$ such that $a_i = a_{i+1}$ is when $a_i = a_{i+1}$ and $a_{i+2} = a_{i+3}$, and you apply the operation on $a_{i+1}$ and $a_{i+2}$. Suppose $l$ is the smallest index where $a_l = a_{l+1}$ and r is the largest index where $a_r = a_{r+1}$. If $l=r$ or $l$ and $r$ does not exist, the condition is already satisfied and we can do 0 operations. Otherwise, the answer is $\\max(1, r - l - 1)$. The proof is as follows: Suppose $l+1=r$, then, there are 3 elements that are adjacent to each other. Hence, we can just do one operation with $i=l$ and $x=\\infty$ to make the equality of the array 1. Suppose otherwise, then the array will look something like $[..., X, X, ..., Y, Y, ...]$, with $r - l - 2$ elements between the second $X$ and the first $Y$. Then, we can do operations on $i={l+1, l+2, \\ldots, r-2, r-1}$ to make the equality of the array 1. To see why we need at least $r - l - 1$ operations, observe that each operation will cause $r - l$ to decrease by at most 1. This is because if we do not do an operation on $i \\in \\{l-1,l+1,r-1,r+1\\}$, then both $a_l = a_{l+1}$ and $a_r = a_{r+1}$ will still hold. We see that $r-l$ only decreases when do we an operation on $i \\in {l+1,r-1}$ and it is not too hard to show that it only decreases by $1$ in those cases while $r-l > 2$ Hence, we keep doing the operation until $r - l = 2$, which will only require 1 operation to change both pairs and make the equality 1.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n\ntemplate <class T>\ninline bool mnto(T& a, T b) {return a > b ? a = b, 1 : 0;}\ntemplate <class T>\ninline bool mxto(T& a, T b) {return a < b ? a = b, 1: 0;}\n#define REP(i, s, e) for (int i = s; i < e; i++)\n#define RREP(i, s, e) for (int i = s; i >= e; i--)\ntypedef long long ll;\ntypedef long double ld;\n#define MP make_pair\n#define FI first\n#define SE second\ntypedef pair<int, int> ii;\ntypedef pair<ll, ll> pll;\n#define MT make_tuple\ntypedef tuple<int, int, int> iii;\n#define ALL(_a) _a.begin(), _a.end()\n#define pb push_back\ntypedef vector<int> vi;\ntypedef vector<ll> vll;\ntypedef vector<ii> vii;\n\n#ifndef DEBUG\n#define cerr if (0) cerr\n#endif\n\n#define INF 1000000005\n#define LINF 1000000000000000005ll\n#define MAXN 200005\n\nint t;\nint n;\nint a[MAXN];\n\nint main() {\n#ifndef DEBUG\n    ios::sync_with_stdio(0), cin.tie(0);\n#endif\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        REP (i, 0, n) {\n            cin >> a[i];\n        }\n        int mn = -1, mx = -1;\n        REP (i, 1, n) {\n            if (a[i] == a[i - 1]) {\n                if (mn == -1) {\n                    mn = i;\n                }\n                mx = i;\n            }\n        }\n        if (mn == mx) {\n            cout << 0 << '\\n';\n        } else {\n            cout << max(1, mx - mn - 1) << '\\n';\n        }\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1672",
    "index": "D",
    "title": "Cyclic Rotation",
    "statement": "There is an array $a$ of length $n$. You may perform the following operation any number of times:\n\n- Choose two indices $l$ and $r$ where $1 \\le l < r \\le n$ and $a_l = a_r$. Then, set $a[l \\ldots r] = [a_{l+1}, a_{l+2}, \\ldots, a_r, a_l]$.\n\nYou are also given another array $b$ of length $n$ which is a permutation of $a$. Determine whether it is possible to transform array $a$ into an array $b$ using the above operation some number of times.",
    "tutorial": "The operation of cyclic shift is equivalent to deleting $a_i$ and duplicating $a_j$ where $a_i = a_j$. Reverse the process. We will solve the problem by reversing the steps and transform array $b$ to array $a$. We can do the following operation on $b$: pick index $i<j$ such that $b_j=b_{j+1}$ and remove $b_{j+1}$ and insert it after position $i$. Now, for every consecutive block of identical elements in $b$, we can remove all but one element from it and move it left. If we process from right to left, we can imagine as taking consecutive elemnets in $b$ out and placing in a reserve, and using them to match some elements in $a$ towards the left. Using this idea, we can use the following greedy two-pointer algorithm: Let $i$ and $j$ represent the size of $a$ and $b$ respectively (and hence $a_i$ and $b_j$ will refer to the last elements of $a$ and $b$ respectively). We also have an initially empty multiset $S$, which represents the reserve. We will perform the following operations in this order: While $b_{j-1}=b_j$, add $b_j$ to the multiset $S$ and decrement $j$ If $a_i = b_j$, then decrement both $i$ and $j$ Otherwise, we delete an occurance of $a_i$ in $S$ and decrement $i$. If we cannot find $a_i$ in $S$, it is impossible to transform $b$ to $a$. Let us define an array $c$ where all elements of $c$ is $1$. We can rephrase the problem in the following way: Choose $i<j$ such that $a_i = a_j$ and $c_i>0$. Then update $c_i \\gets c_i-1$ and $c_j \\gets c_j+1$. The final array $b$ is obtained by the following: Let $b$ be initially empty, then iterate $i$ from $1$ to $n$ and add $c_i$ copies of $a_i$ to $b$. As such, we can consider mapping elements of $b$ into elements of $a$. More specifically, consider a mapping $f$ where $f$ is non-decreasing, $b_i=a_{f_i}$ and we increment $c_{f_i}$ by $1$ for all $i$. All that remains is to determine if we can make such a mapping such that $c$ is valid. Notice that if all elements of $a$ are identical, the necessary and sufficient condition for a valid array $c$ is that $c_1+c_2+\\ldots+c_i \\leq i$ for all $i$. This motivates us to construct an array $pa$ where $pa_i$ is the number of indices $j \\leq i$ such that $a_i=a_j$. Analogously, construct $pb$. Then the necessary and sufficient conditions for a mapping $f$ is that $f$ is non-decreasing, $b_i=a_{f_i}$ and $pb_i \\leq pa_{f_i}$. A greedy algorithm to construct $f$, if it exists, is trivial by minimizing $f_i$ for each $i$.",
    "code": "// Super Idol的笑容\n//    都没你的甜\n//  八月正午的阳光\n//    都没你耀眼\n//  热爱105°C的你\n// 滴滴清纯的蒸馏水\n\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n\n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nint n;\nint arr[200005];\nint brr[200005];\nint crr[200005];\nint num[200005];\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tint TC;\n\tcin>>TC;\n\twhile (TC--){\n\t\tcin>>n;\n\t\trep(x,1,n+1) cin>>arr[x];\n\t\trep(x,1,n+1) cin>>brr[x];\n\t\t\n\t\trep(x,1,n+1) num[x]=0;\n\t\trep(x,1,n+1){\n\t\t\tnum[arr[x]]++;\n\t\t\tcrr[x]=num[arr[x]];\n\t\t}\n\t\t\n\t\trep(x,1,n+1) num[x]=0;\n\t\tint idx=1;\n\t\trep(x,1,n+1){\n\t\t\tnum[brr[x]]++;\n\t\t\twhile (idx<=n && (arr[idx]!=brr[x] || crr[idx]<num[brr[x]])) idx++;\n\t\t}\n\t\t\n\t\tif (idx>n) cout<<\"NO\"<<endl;\n\t\telse cout<<\"YES\"<<endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1672",
    "index": "E",
    "title": "notepad.exe",
    "statement": "\\textbf{This is an interactive problem.}\n\nThere are $n$ words in a text editor. The $i$-th word has length $l_i$ ($1 \\leq l_i \\leq 2000$). The array $l$ is hidden and only known by the grader.\n\nThe text editor displays words in lines, splitting each two words in a line with at least one space. Note that a line does not have to end with a space. Let the height of the text editor refer to the number of lines used. For the given \\textbf{width}, the text editor will display words in such a way that the height is minimized.\n\nMore formally, suppose that the text editor has \\textbf{width} $w$. Let $a$ be an array of length $k+1$ where $1=a_1 < a_2 < \\ldots < a_{k+1}=n+1$. $a$ is a \\textbf{valid} array if for all $1 \\leq i \\leq k$, $l_{a_i}+1+l_{a_i+1}+1+\\ldots+1+l_{a_{i+1}-1} \\leq w$. Then the \\textbf{height} of the text editor is the minimum $k$ over all valid arrays.\n\nNote that if $w < \\max(l_i)$, the text editor cannot display all the words properly and will crash, and the height of the text editor will be $0$ instead.\n\nYou can ask $n+30$ queries. In one query, you provide a width $w$. Then, the grader will return the height $h_w$ of the text editor when its width is $w$.\n\nFind the minimum area of the text editor, which is the minimum value of $w \\cdot h_w$ over all $w$ for which $h_w \\neq 0$.\n\nThe lengths are fixed in advance. In other words, \\textbf{the interactor is not adaptive}.",
    "tutorial": "Find the sum of lengths of words. Given a height, how many \"good\" widths are there. The first idea that we have is that we want to be able to find the minimum possible width of the text editor for a specific height. We can do this in $n\\log (n \\cdot 2000)$ queries using binary search for each height. This is clearly not good enough, so let us come up with more observations. First, we can binary search for the minimum possible width for height $1$. This value is $(\\sum_{i=1}^n l_i)+n-1$ which we will denote with $S$. Let us consider what we might want to query for height $h$. Suppose that the words are arranged very nicely such that there are no trailing spaces in each line. Then, the total number of characters will be $S - h +1$. This means that the minimum possible area for height $h$ will be $S-h+1$. We also know that if the area is more than $S$, it will not be useful as the area for $h=1$ is already $S$. Now, we know that the range of possible areas that we are interested in is $[S - h +1, S]$. There is a total of $h$ possible areas that it can take, and an area is only possible if $h \\cdot w = a$, or in other words, the area is divisible by $h$. Among the $h$ consecutive possible values, exactly one of them will be divisible by $h$, hence we can just query that one value of $w$ which can very nicely be found as $\\lfloor \\frac{S}{h} \\rfloor$. The total number of queries used is $n + \\log(n \\cdot 2000)$ where $n$ comes from the single query for each height and the $\\log(n \\cdot 2000)$ comes from the binary search at the start.",
    "code": "// Super Idol的笑容\n//    都没你的甜\n//  八月正午的阳光\n//    都没你耀眼\n//  热爱105°C的你\n// 滴滴清纯的蒸馏水\n\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n\n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n\n\nint n;\n\nint ask(int i){\n\tif (i==0) return 0;\n\tcout<<\"? \"<<i<<endl;\n\tint temp;\n\tcin>>temp;\n\t\n\tif (temp==-1){\n\t\texit(0);\n\t}\n\t\n\treturn temp;\n}\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tcin>>n;\n\t\n\tint lo=-2,hi=5e6,mi;\n\twhile (hi-lo>1){\n\t\tmi=hi+lo>>1;\n\t\t\n\t\tif (ask(mi)==1) hi=mi;\n\t\telse lo=mi;\n\t}\n\t\n\tint ans=1e9;\n\trep(x,1,n+1){\n\t\tint temp=ask(hi/x);\n\t\tif (temp) ans=min(ans,temp*(hi/x));\n\t}\n\t\n\tcout<<\"! \"<<ans<<endl;\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "interactive"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1672",
    "index": "F2",
    "title": "Checker for Array Shuffling",
    "statement": "oolimry has an array $a$ of length $n$ which he really likes. Today, you have changed his array to $b$, a permutation of $a$, to make him sad.\n\nBecause oolimry is only a duck, he can only perform the following operation to restore his array:\n\n- Choose two integers $i,j$ such that $1 \\leq i,j \\leq n$.\n- Swap $b_i$ and $b_j$.\n\nThe \\textbf{sadness} of the array $b$ is the minimum number of operations needed to transform $b$ into $a$.\n\nGiven the arrays $a$ and $b$, where $b$ is a permutation of $a$, determine if $b$ has the maximum sadness over all permutations of $a$.",
    "tutorial": "The number of occurances of the most frequent element is important. Let $X$ be the number of occurances of the most common element. The maximal sadness is $N-X$. For every minimal sequence of swaps, we have duality of maximal number of cycles when considering the graph with edges $a_i \\to b_i$. Let $N$ be the length of $A$ and $B$. We want to prove that an optimal swapping from $B \\to A$ is equivalent to sorting via some cycles. Suppose our swap order is $\\{(l_1,r_1),(l_2,r_2),\\ldots,(l_K,r_K)\\}$. Let's consider a graph $G$ with edges being the swaps. Suppose the number of connected components in $G$ is $CC$, then there is a way to perform the transformation $B \\to A$ using $CC$ cycles since we can view the labels of each connected component of $G$ as a permutation of the original vertices. One cycle of length $X$ uses $X-1$ swaps, so we use $N-CC$ swaps in total. Since $CC \\geq N-K$, we can always change the swap order to swapping cycles while not performing a bigger number of moves. Now we have changed the problem to maximizing the number of cycles we use. Let $cnt_x$ be the number of occurrences of $x$ in $A$. WLOG $cnt_1 \\geq cnt_2 \\geq \\ldots$. Let $s_A(B)$ denote the sadness of $B$ when the original array is $A$. Claim: $\\max(s_A) \\leq N-cnt_1$ Proof: By pigeonhole principle, we know there exist a cycle with $2$ occurrences of the element $1$. Consider a cycle that swaps $i_1 \\to i_2 \\to \\ldots \\to i_K \\to i_1$ where $A_{i_1}=A_{i_z}=1$. Then we can increase the number of connected components while maintaining $B$ by splitting into $2$ cycles $i_1 \\to i_2 \\to \\ldots \\to i_{z-1} \\to i_1$ and $i_z \\to i_2 \\to \\ldots \\to i_N \\to i_z$. Therefore, in an optimal solution, there should not be a cycle that passes through the same value twice. $\\blacksquare$ Therefore, we can assume that all occurrences of $1$ belong to different cycles. Therefore, $\\#cyc \\geq cnt_1$ swaps are used. The number of swaps used is $N-\\#cyc \\leq N-cnt_1$. Therefore, $N-cnt_1$ is a upper bound of $s$. Claim: $s_A(B)<N-cnt_1$ $\\Leftrightarrow$ there exists a cycle $i_1 \\to i_2 \\to \\ldots \\to i_K \\to i_1$ such that all $i_x \\neq 1$. Proof: $(\\Rightarrow)$ There exists a cycle decomposition of the graph that uses at least $cnt_1+1$ cycles. Since a single element of $1$ can only go to a single cycle, there exists a cycle without $1$. $(\\Leftarrow)$ Let's remove this cycle to form an arrays $A'$ and $B'$. Then $s_{A'}(B') \\leq N-K-cnt_1$. Now, we only needed $K-1$ swaps to remove the cycle, so it much be that $s_A(B) \\leq (N-K-cnt_1)+(K-1)=N-cnt_1-1$. $\\blacksquare$ To construction a permutation such that $s(B)=N-cnt_1$, let's construct a graph $G_{cnt}$ based on the number of occurrences of each element in $A$. We draw $cnt_{i+1}$ edges from $(i) \\to (i+1)$ and $cnt_{i}-cnt_{i+1}$ edges from $(i) \\to (1)$. It is obviously impossible to find a cycle that does not contain $1$. Since all edges will be of the form $(i) \\to (i+1)$. Another way to construct this permutation is to assume that $A$ is sorted. Then we perform $cnt_1$ cyclic shifts on $A$ to obtain $B$. Given the graph representation, finding such a cycle $i_1 \\to i_2 \\to \\ldots \\to i_K \\to i_1$ such that all $i_x \\neq 1$ is easy. Let's remove $1$ from the graph then check if the graph is a DAG.",
    "code": "// Super Idol的笑容\n//    都没你的甜\n//  八月正午的阳光\n//    都没你耀眼\n//  热爱105°C的你\n// 滴滴清纯的蒸馏水\n\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n\n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nint n;\nint arr[200005];\nint brr[200005];\n\nvector<int> al[200005];\nbool onstk[200005];\nbool vis[200005];\n\nbool cyc;\nvoid dfs(int i){\n\tonstk[i]=vis[i]=true;\n\t\n\tfor (auto it:al[i]){\n\t\tif (onstk[it]) cyc=true;\n\t\tif (!vis[it]) dfs(it);\n\t}\n\t\n\tonstk[i]=false;\n}\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tint TC;\n\tcin>>TC;\n\twhile (TC--){\n\t\tcin>>n;\n\t\t\n\t\trep(x,1,n+1) al[x].clear();\n\t\trep(x,1,n+1) vis[x]=onstk[x]=false;\n\t\t\n\t\trep(x,1,n+1) cin>>arr[x];\n\t\trep(x,1,n+1) cin>>brr[x];\n\t\t\n\t\trep(x,1,n+1) al[arr[x]].pub(brr[x]);\n\t\t\n\t\tint mx=1;\n\t\trep(x,1,n+1) if (sz(al[x])>sz(al[mx])) mx=x;\n\t\t\n\t\tvis[mx]=true;\n\t\tcyc=false;\n\t\trep(x,1,n+1) if (!vis[x]) dfs(x);\n\t\t\n\t\tif (cyc) cout<<\"WA\"<<endl;\n\t\telse cout<<\"AC\"<<endl;\n\t}\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1672",
    "index": "G",
    "title": "Cross Xor",
    "statement": "There is a grid with $r$ rows and $c$ columns, where the square on the $i$-th row and $j$-th column has an integer $a_{i, j}$ written on it. Initially, all elements are set to $0$. We are allowed to do the following operation:\n\n- Choose indices $1 \\le i \\le r$ and $1 \\le j \\le c$, then replace all values on the same row or column as $(i, j)$ with the value xor $1$. In other words, for all $a_{x, y}$ where $x=i$ or $y=j$ or both, replace $a_{x, y}$ with $a_{x, y}$ xor $1$.\n\nYou want to form grid $b$ by doing the above operations a finite number of times. However, some elements of $b$ are missing and are replaced with '?' instead.\n\nLet $k$ be the number of '?' characters. Among all the $2^k$ ways of filling up the grid $b$ by replacing each '?' with '0' or '1', count the number of grids, that can be formed by doing the above operation a finite number of times, starting from the grid filled with $0$. As this number can be large, output it modulo $998244353$.",
    "tutorial": "We need to consider $4$ cases based on the parity of $r$ and $c$. Let $R_i$ and $C_j$ denote $\\bigotimes\\limits_{j=1}^c a_{i,j}$ and $\\bigotimes\\limits_{i=1}^r a_{i,j}$ respectively, or the xor-sum of the $i$-th row and the xor-sum of the $j$-th column respectively. For some cases, $R$ and $C$ will be constant sequences no matter what sequence of operations we perform. The obvious necessary conditions for $R$ and $C$ are actually sufficient. When at least one of $r$ or $c$ is even, counting the valid grids is easy. When both $r$ and $c$ is odd, consider drawing the bipartite graph where edges are cells with $\\texttt{?}$. Let $R_i$ and $C_j$ denote $\\bigotimes\\limits_{j=1}^c a_{i,j}$ and $\\bigotimes\\limits_{i=1}^r a_{i,j}$ respectively, or the xor-sum of the $i$-th row and the xor-sum of the $j$-th column respectively. We will split the problem into 3 cases. Choose some $(x,y)$ and do an operation on all $(i,j)$ where $i=x$ or $j=y$. The effect of this series of operations is toggling $(x,y)$. All possible grids are reachable. Counting them is easy. If $r$ is odd and $c$ is even, we can treat it as the same case by swapping a few variables. Notice that every operation toggles all elements in $R$. It is neccasary that $R$ all values in R are the same, let us prove that this is sufficient as well. Now suppose $R$ is all 0. If $R$ is all $1$. We can perform the operation on $(1,1)$ and now $R$ is all $0$. If we pick $1 \\leq x \\leq r$ and $1 \\leq y < c$ and perform operations on all $(i,j)$ where $i \\neq x$ and $j=y$ or $j=c$, then it is equivalent to toggling $(x,y)$ and $(x,c)$. We can perform the following new operation: pick $1 \\leq x \\leq r$ and $1 \\leq y < c$ toggle $(x,y)$,$(x,c)$ Since $R$ is all 0, each row has an even number of $1$. If we apply the new operation on all $(x,y)$ where $a_{x,y} = 1$ and $y < c$, then $(x,c)$ will be $0$ in the end. Hence, the whole grid will be $0$. Notice that every operation toggles all elements in $R$ and $C$. It is neccasary that both $R$ are $C$ all having the same values, let us prove that this is sufficient as well. Suppose $R$ is all $0$ and $C$ is all $0$. If $R$ and $C$ are all $1$, we apply the operation on $(1,1)$ to make $R$ and $C$ both all $0$ Notice that if we pick $1 \\leq x_1 < x_2 \\leq r$ and $1 \\leq y_1 < y_2 \\leq c$. Let $S=\\{(x_1,y_1), (x_1,y_2), (x_2,y_1),(x_2,y_2)\\}$. When we perform operations on all cells in $S$, it is equivalent to toggling all cells in $S$. We can perform the following new operation: pick $1 \\leq x < r$ and $1 \\leq y < c$ toggle $(x,y)$,$(x,c)$,$(r,y)$,$(r,c)$ Since $R$ and $C$ is all 0, each row and column has an even number of 1. If we apply the new operation on all $(x,y)$ where $a_{x,y} = 1$ and $x < r$ and $y < c$ , then $(x,c)$ will be $0$ for $0 < x < r$ and $(r,y)$ will be $0$ for $0 < y < c$ in the end. And hence, $a_{r,c} = 0$ too since $R$ and $C$ is all 0. Hence, the whole grid will be $0$. Thanks to dario2994 for writing this. Let $V = Z_2^{nm}$. $V$ is endowed with the natural scalar product, which induces the concept of orthogonality. Let $M$ be the subspace generated by the moves. Let $M^{\\perp}$ be the space orthogonal to $M$. It is a basic result in linear algebra that $(M^{\\perp})^{\\perp} = M$. One can see that $\\{(x1, y1), (x1, y2), (x2, y1), (x2, y2)\\}$ belongs to $M$ (it is a combination of 4 moves). Thus one deduces that if $u \\in M^{\\perp}$ then $u_{x,y} = a_x \\oplus b_y$ for two vectors $a\\in Z_2^r, b \\in Z_2^c$. Given $a, b$; the scalar product between $u$ and the move centered at $(x, y)$ is: $xor(a) \\oplus xor(b) \\oplus (c+1)a_x \\oplus (r+1)b_y$. Assume that $u$ is in $M^{\\perp}$: If $r, c$ are both even, then $a_x$ and $b_y$ must be constant and equal each other. Thus $M^{\\perp}$ is only the $0$ vector. If $r$ is even and $c$ is odd, then $b_y$ is constant. Hence $M^{\\perp}$ is generated by any two rows. If $r$ is odd and $c$ is even, analogous. If $r$ and $c$ are both odd, then the only condition is $xor(a) \\oplus xor(b) = 0$. This is necessary and sufficient for the orthogonality. And it implies that $M^{\\perp}$ is generated by any two rows and any two columns. Since we determined $M^{\\perp}$, we have determined also $M$. Case 1 and 2 are the easy cases while counting case 3 is more involved. All grids are obtainable. Let $\\#?$ denote the number of $\\texttt{?}$s in the grid. Then the answer is $2^{\\#?}$ since all grid are obtainable. If $r$ is odd and $c$ is even, we can treat it as the same case by swapping a few variables. Let us fix whether we want $R=[0,0,\\ldots,0]$ or $R=[1,1,\\ldots,1]$. We will count the number of valid grids for each case. Let $\\#?_i$ denote the number of $\\texttt{?}$s in the $i$-th row. If $\\#?_i>0$, then then number of ways to set the $i$-th row is $2^{\\#?_i-1}$. Otherwise, the number of ways is either $0$ to $1$ depending on the initial value of $R_i$. Let us define a bipartite graph with vertices $r+c$ vertices, labelled $V_{R,i}$ for $1 \\leq i \\leq r$ and $V_{C,j}$ for $1 \\leq j \\leq c$. If $a_{i,j}=\\texttt{?}$, then we will add an (undirected) edge $V_{R,i} \\leftrightarrow V_{C,j}$. Now we assume that each $\\texttt{?}$ is set to $\\texttt{0}$ at first. We will choose a subset of them to turn into $\\texttt{1}$. When we do this on $a_{i,j}$, the value of $R_i$ and $C_j$ will toggle. In terms of the graph, this corresponds to assigning $0$ or $1$ to each edge. When we assign $1$ to the edge connecting $V_{R,i}$ and $V_{C,j}$, then $R_i$ and $C_j$ will toggle. We can consider $R_i$ and $C_j$ to be the weight of the vertices $V_{R,i}$ and $V_{C,j}$ respecitvely. Consider a connected component of this bipartite graph. Choose an arbitrary spanning tree of this connected component. By assinging the weights of the edges in the spanning tree, we can arbitrarily set the weights of all but one vertex. We cannot arbitarily set the weight of all vertices as the xor-sum of the weight of vertices is an invariant. Let us show that we can arbitarily choose the weights of all but one vertex on this connected component using the spanning tree. Let us arbitrarily root the tree. Choose some arbitrary leaf of the tree, if the weight of the leaf is correct, assign the edge connected to that vertex weight $0$. Otherwise, assign it weight $1$. Then remove the leaf and its corresponding edge. Actually, this shows that there is a one-to-one correspondents between the possible weights of the edges and the possible weights of the vertices. For the edges not in the spanning tree we have chosen, we can arbitarily set their weights while we are still able to choose the weights of all but one vertex on this connected component by properly assigning weights of the edges in the spanning tree. Suppose we want this constant value of $R$ and $C$ to be $v$, where $v$ is either $0$ or $1$. Suppose that the connected component has size $n$, has $m$ edges and the xor of all the initial vertex weights is $x$. If $n$ is even: If $x=0$, then there are $2^{m-n+1}$ ways to assign weights to edges. If $x=1$, then there are $0$ ways to assign weights to edges. If $n$ is odd: If $x=v$, then there are $2^{m-n+1}$ ways to assign weights to edges. If $x\\neq v$, then there are $0$ ways to assign weights to edges.",
    "code": "// Super Idol的笑容\n//    都没你的甜\n//  八月正午的阳光\n//    都没你耀眼\n//  热爱105°C的你\n// 滴滴清纯的蒸馏水\n\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n\n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nconst int MOD=998244353;\n\nll qexp(ll b,ll p,int m){\n    ll res=1;\n    while (p){\n        if (p&1) res=(res*b)%m;\n        b=(b*b)%m;\n        p>>=1;\n    }\n    return res;\n}\n\nint n,m;\nchar grid[2005][2005];\n\nint w[4005];\nvector<int> al[4005];\n\nbool vis[4005];\nint ss,par,edges;\n\nvoid dfs(int i){\n\tif (vis[i]) return;\n\tvis[i]=true;\n\t\n\tss++;\n\tpar^=w[i];\n\tedges+=sz(al[i]);\n\t\n\tfor (auto it:al[i]) dfs(it);\n}\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tcin>>n>>m;\n\trep(x,0,n) cin>>grid[x];\n\t\n\tif (n%2>m%2){\n\t    swap(n,m);\n\t\trep(x,0,2005) rep(y,0,2005) if (x<y) swap(grid[x][y],grid[y][x]);\n\t}\n\t\n\t// rep(x,0,n){\n\t\t// rep(y,0,m) cout<<grid[x][y]<<\" \"; cout<<endl;\n\t// }\n\t\n\tif (n%2==0 && m%2==0){\n\t\tint cnt=0;\n\t\trep(x,0,n) rep(y,0,m) if (grid[x][y]=='?') cnt++;\n\t\tcout<<qexp(2,cnt,MOD)<<endl;\n\t}\n\telse if (n%2==0 && m%2==1){\n\t\tint cnt0=1,cnt1=1;\n\t\t\n\t\trep(x,0,n){\n\t\t\tint val=0;\n\t\t\tint cnt=0;\n\t\t\trep(y,0,m){\n\t\t\t\tif (grid[x][y]=='?') cnt++;\n\t\t\t\telse val^=grid[x][y]-'0';\n\t\t\t}\n\t\t\tif (cnt==0){\n\t\t\t\tif (val==0) cnt1=0;\n\t\t\t\telse cnt0=0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcnt0=(cnt0*qexp(2,cnt-1,MOD))%MOD;\n\t\t\t\tcnt1=(cnt1*qexp(2,cnt-1,MOD))%MOD;\n\t\t\t}\n\t\t}\n\t\t\n\t\tcout<<(cnt1+cnt0)%MOD<<endl;\n\t}\n\telse{\n\t\trep(x,0,n) rep(y,0,m){\n\t\t\tif (grid[x][y]!='?'){\n\t\t\t\tw[x]^=grid[x][y]-'0';\n\t\t\t\tw[y+n]^=grid[x][y]-'0';\n\t\t\t}\n\t\t\telse{\n\t\t\t\tal[x].pub(y+n);\n\t\t\t\tal[y+n].pub(x);\n\t\t\t}\n\t\t}\n\t\t\n\t\tint cnt0=1,cnt1=1;\n\t\t\n\t\trep(x,0,n+m) if (!vis[x]){\n\t\t\tss=0,par=0,edges=0;\n\t\t\tdfs(x);\n\t\t\tedges/=2;\n\t\t\tedges-=ss-1; //extra edge\n\t\t\t\n\t\t\tint mul=qexp(2,edges,MOD);\n\t\t\t\n\t\t\tif (ss%2==0){\n\t\t\t\tif (par) mul=0;\n\t\t\t\tcnt0=(cnt0*mul)%MOD;\n\t\t\t\tcnt1=(cnt1*mul)%MOD;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (par==0){\n\t\t\t\t\tcnt0=(cnt0*mul)%MOD;\n\t\t\t\t\tcnt1=0;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcnt0=0;\n\t\t\t\t\tcnt1=(cnt1*mul)%MOD;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tcout<<(cnt0+cnt1)%MOD<<endl;\n\t}\n}\n",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math",
      "matrices"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1672",
    "index": "H",
    "title": "Zigu Zagu",
    "statement": "You have a binary string $a$ of length $n$ consisting only of digits $0$ and $1$.\n\nYou are given $q$ queries. In the $i$-th query, you are given two indices $l$ and $r$ such that $1 \\le l \\le r \\le n$.\n\nLet $s=a[l,r]$. You are allowed to do the following operation on $s$:\n\n- Choose two indices $x$ and $y$ such that $1 \\le x \\le y \\le |s|$. Let $t$ be the substring $t = s[x, y]$. Then for all $1 \\le i \\le |t| - 1$, the condition $t_i \\neq t_{i+1}$ has to hold. Note that $x = y$ is always a valid substring.\n- Delete the substring $s[x, y]$ from $s$.\n\nFor each of the $q$ queries, find the minimum number of operations needed to make $s$ an empty string.\n\nNote that for a string $s$, $s[l,r]$ denotes the subsegment $s_l,s_{l+1},\\ldots,s_r$.",
    "tutorial": "We will always remove a maximal segment, or in other words we will select $l$ and $r$ such that $A_{l-1} = A_l$ and $A_r = A_{r+1}$. Try to find an invariant. We can first split string $A$ into the minimum number of sections of $\\texttt{010101}\\ldots$ and $\\texttt{101010}\\ldots$. Let the number of sections be $K$. Since we can simply delete each section individually, the worst answer that we can get is $K$. Also, there is no reason to only delete part of a segment, so from here on we only assume that we delete maximal segments. Now, we can decompose $A$ based on its $K$ sections and write it as a string $D$. The rules for the decomposition is as follows: $10\\ldots01 \\to x$ $01\\ldots10 \\to x'$ $10\\ldots10 \\to y$ $01\\ldots01 \\to y'$ For example, the string $A=[0101][1][1010]$ becomes $D=y'xy$. Now, let us look at what our operation does on $D$. When we remove a section of even length ($y$ or $y'$) that is not on the endpoint of the string, the left and right sections will get combined. This is because the two ends of an even section are opposite, allowing the left and right sections to merge. Otherwise, it results in no merging. When some sections get combined, the length of string $D$ gets reduced by $2$, while the length of $D$ gets reduced by $1$ otherwise. Clearly, we want to maximize deleting the number of sections of even length that are not on the endpoints of the string. We will call such a move a power move. Let us classify strings that have no power moves. They actually come in $8$ types: $x x \\ldots x$ $y' x x \\ldots x$ $x x \\ldots x y$ $y' x x \\ldots x y$ $x' x' \\ldots x'$ $y x' x' \\ldots x'$ $x' x' \\ldots x' y'$ $y x' x' \\ldots x' y'$ We can prove that for any string not of this form, there will be always be character $y$ or $y'$ that is not on the ends of the string. Suppose that the string contains both $x$ and $x'$, then $xyx'$ or $x'y'x$ must be a substring. Also, the number of $y$ or $y'$s on each side cannot be more than $1$. Note that strings such that $y$ or $yy'$ may fall under multiple types. Furthermore, for string of these types, the number of moves we have to make is equal to the length of the string. Let us define the balance of $x$ as the number of $x$ minus the number of $x'$. We will define the balance of $y$ similarly. When we perform a power move, notice that the balance of the string is unchanged. Indeed, each power move either removes a pair of $x$ and $x'$ or $y$ and $y'$ from the string. With this, we can easily find which type of ending string we will end up with based on the perviously mentioned invariants, except for the cases of differentiating between the string $x x \\ldots x$ and $y' x x \\ldots x y$ (and the case for $x'$). To differentiate between these $2$ cases, we can note that the first character of our string does not change when we perform power moves. And indeed, $x$ and $y'$ have different starting characters. Note that we have to be careful when the balance of $x$ and the balance of $y$ is $0$ in the initial string as for strings such as $yy'$, the final string is not $\\varnothing$ but $yy'$. With this, we can answer queries in $O(1)$ since we can query the balance of $x$, the balance of $y$ and the total length of the decomposed string in $O(1)$. Furthermore, there is a implementation trick here. Notice that if $a_{l-1}\\neq a_l$, then then answer for $s[l-1,r]$ will be equal to the answer for $s[l,r]$. So in implementation, it is easier to \"extend\" $l$ and $r$ to find the balance of $x$ and $y$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n,q;\nstring s;\nint l[200005];\nint r[200005];\nint psum[200005];\nint balance[200005];\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tcin>>n>>q;\n\tcin>>s;\n\t\n\ts=s[0]+s+s[n-1];\n\t\n\tfor (int x=1;x<=n;x++){\n\t\tif (s[x-1]==s[x]) l[x]=x;\n\t\telse l[x]=l[x-1];\n\t}\n\t\n\tfor (int x=n;x>=1;x--){\n\t\tif (s[x]==s[x+1]){\n\t\t\tr[x]=x;\n\t\t\tpsum[x]=1;\n\t\t\tif ((x-l[x])%2==0){\n\t\t\t\tbalance[x]=(s[x]=='1'?1:-1);\n\t\t\t}\n\t\t}\n\t\telse r[x]=r[x+1];\n\t}\n\t\n\tfor (int x=1;x<=n;x++){\n\t\tpsum[x]+=psum[x-1];\n\t\tbalance[x]+=balance[x-1];\n\t}\n\t\n\tint a,b;\n\twhile (q--){\n\t\tcin>>a>>b;\n\t\ta=l[a],b=r[b];\n\t\t\n\t\tint bl=balance[b]-balance[a-1];\n\t\tint sum=psum[b]-psum[a-1];\n\t\t\n\t\tint ans=(sum+abs(bl))/2;\n\t\t\n\t\tif ((sum+abs(bl))%2==1) ans++;\n\t\telse if (abs(bl)==0) ans++;\n\t\telse if (bl>0 ^ s[a]=='1') ans++;\n\t\t\n\t\tcout<<ans<<\"\\n\";\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1672",
    "index": "I",
    "title": "PermutationForces",
    "statement": "You have a permutation $p$ of integers from $1$ to $n$.\n\nYou have a strength of $s$ and will perform the following operation some times:\n\n- Choose an index $i$ such that $1 \\leq i \\leq |p|$ and $|i-p_i| \\leq s$.\n- For all $j$ such that $1 \\leq j \\leq |p|$ and $p_i<p_j$, update $p_j$ to $p_j-1$.\n- Delete the $i$-th element from $p$. Formally, update $p$ to $[p_1,\\ldots,p_{i-1},p_{i+1},\\ldots,p_n]$.\n\nIt can be shown that no matter what $i$ you have chosen, $p$ will be a permutation of integers from $1$ to $|p|$ after all operations.\n\nYou want to be able to transform $p$ into the empty permutation. Find the minimum strength $s$ that will allow you to do so.",
    "tutorial": "When removing an element, consider how the costs of other elements change? When removing an element, consider the elements whose cost increase. What are their properties? Is there a greedy algorithm? Yes there is. How to make it run fast? Use monotonicity to reduce one dimension Let us rephrase the problem. Let $x$ and $y$ be arrays where $x_i=p_i$ and $y_i=i$ initially. For brevity, let $c_i = |x_i - y_i|$. We want to check if we can do the following operation $n$ times on the array: Choose an index $i$ such that and $c_i \\leq s$. For all $j$ where $x_i < x_j$, update $x_j \\gets x_j-1$. For all $j$ where $y_i < y_j$, update $y_j \\gets y_j-1$. Set $x_i \\gets \\infty$ and $y_i \\gets -\\infty$ Let us fix $s$ and solve the problem of checking whether a value of $s$ allows us to transform the permutation into the empty permutation. Let $(x,y,c)$ be the arrays before some arbitrary operation and $(x',y',c')$ be the arrays after that operation. If we only perform moves with $c_i \\leq s$, then $c_j \\leq s$ implies that $c'_j \\leq s$ i.e. if something was removable before, it will be removable later if we only use valid moves. Proof: Note that $x'_j = x_j$ or $x'_j=x_j-1$. The case for $y$ is same. We can see that $c'_j \\leq c_j+1$. So the only case where $c'_j > s$ is when $c_j=s$. Case $1$: $x_j \\leq y_j$ Then it must be that $x'_j=x_j$ and $y'_j=y_j-1$. By the definition of our operation, we have the following inequality: $x_i < x_j \\leq y_j < y_i$. This implies that $c_i>s$, which is a contradiction. Case $2$: $x_j \\geq y_j$ By similar analysis we see that $c_i>s$. $\\blacksquare$ Suppose that we only remove points with $c_i \\leq s$ for some fixed $s$. This greedy algorithm works here - at each step, choose any point $c_i \\leq s$ with and remove it. - if no such point exists, the $s$ does not work Proof: Given any permutation, let any point with $c_a \\leq s$ be $a$. Consider any optimal sequence of moves $[b_1,b_2,\\ldots,b_w,a,\\ldots]$. We can transform to another optimal solution it by moving $a$ to the front. Let the element before $a$ to be $b_w$. We will swap $a$ and $b_w$. $a$ is already removable at the start so it will be removable after removing $b_1,b_2,\\ldots,b_{w-1}$ by lemma $1$. After removing everything before $b_1,b_2,\\ldots,b_{w-1}$, $b_w$ is removable, so it will be removable after removing $a$ by lemma $1$. Hence we can move $a$ to the front of the sequence of moves by repeatedly swaping elemenets. By exchange arguement, the greedy solution of removing any point with $c_a \\leq s$ is an optimal solution. By extension, the following greedy algorithm works: Set $s \\gets 0$. At each step, choose index $i$ with minimal $c_i$ Update $s \\gets \\max(s,c_i)$ Remove point $i$ Let's start with $s=0$ and remove things while we can. If we are at a state that we are stuck, incremenet $s$. When we increment $s$, the moves that we haved done before will still be a valid choice with this new value of $s$. We simply increment $s$ until we can remove the entire permutation which is Now the only difficult part about this is maintaining the array $c_i$ (the cost) for the points we have not removed. Let's define a point as good as follows: If $y < x$, the point is good if there exist no other point $(x',y')$ such that $y < y' \\leq x' < x$. Otherwise, the point is good if there exist no other point $(x',y')$ such that $x < x' \\leq y' < y$. We maintain only the good elements, because only good elements are candidates for the minimum $c_i$. Suppose element is not good and minimal, then the point that causes it to be not good has a strictly smaller cost, an obvious contradiction. Now we will use data structures to maintain $c_i$ of good points. We will split the good points into the left good and right good points which are those of $x_i \\leq y_i$ and $y_i \\leq x_i$ respectively. Notice that if $x_i = y_i$, then it is both left good and right good. We will focus on the left good points. Suppose $i$ and $j$ are both left good with $x_i < x_j$, then $y_i < y_j$. Suppose otherwise, then we have $x_i < x_j \\leq y_j < y_i$, making $i$ not good. As such $x$ and $y$ of the left good points are monotone. To find this monotone chain of left good points, we can maintain a max segment tree which stores max $y$ for all alive $x$. Using binary search on segment tree to find the unique point with $x' > x$ such that $y'$ is minimized. Where $(x,y)$ is a point on the chain, and $(x',y')$ is the next point. We can repeatedly do this to find the entire chain of left good elements We can store a segment tree where $i$ is the key and $c_i$ is the value. If an element is left good, it will always be left good until it is removed. The following two operations are simply range updates on the segment tree since $y_i$ is monotone. - For all $j$ such that $x_j>x_i$, set $x_j \\leftarrow x_j-1$. - For all $j$ such that $y_j<y_i$, set $y_j \\leftarrow y_j-1$. Now, when we remove some left good point, some other points will become left good, and we will need to add them. We do this by starting from the previous element of the left good chain, and then keep repeating the same algo using descend on the segment tree. When we add a new left good point, we need to know the cost at the current point in time. If we consider a point which is initially $(x,y)$, and all other previously removed $(x',y')$, $x$ decreases by 1 per $x' < x$ and $y$ decreases by 1 per $y' < y$. Hence, we can maintain a fenwick tree of the removed point's $x$ and $y$, and using that we can determine the $x$ and $y$ at the time when we add it to the left good chain (and hence to the segment tree). Time Complexity: $O(n \\log n)$ Thanks to dario2994 for pointing this out. Surprisingly quad trees are provably $O(n \\sqrt n)$ here. Take the $k$-th layer of the quad tree. The $n \\cdot n$ grid will be split into $4^k$ squares in the $k$-th layer. Since we are doing half plane covers, our query range will only touch $2^k$ squares. At the same time, the width of those $2^k$ squares is $\\frac{n}{2^k}$. Since each column only has a single element, our query range will also by bounded by $\\frac{n}{2^k}$. The time complexity for a single update is given by $\\sum\\limits_{k=1}^{\\log n} \\min(2^k,\\frac{n}{2^k}) = O(\\sqrt n)$.",
    "code": "// Super Idol的笑容\n//    都没你的甜\n//  八月正午的阳光\n//    都没你耀眼\n//  热爱105°C的你\n// 滴滴清纯的蒸馏水\n\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n\n#define ii pair<int,int>\n#define fi first\n#define se second\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nstruct FEN{\n\tint fen[500005];\n\t\n\tFEN(){\n\t\tmemset(fen,0,sizeof(fen));\n\t}\n\t\n\tvoid upd(int i,int j){\n\t\twhile (i<500005){\n\t\t\tfen[i]+=j;\n\t\t\ti+=i&-i;\n\t\t}\n\t}\n\t\n\tint query(int i){\n\t\tint res=0;\n\t\twhile (i){\n\t\t\tres+=fen[i];\n\t\t\ti-=i&-i;\n\t\t}\n\t\treturn res;\n\t}\n} fval,fidx;\n\nstruct dat{\n\tstruct node{\n\t\tint s,e,m;\n\t\tii val;\n\t\tint lazy=0;\n\t\tnode *l,*r;\n\t\t\n\t\tnode (int _s,int _e){\n\t\t\ts=_s,e=_e,m=s+e>>1;\n\t\t\tval={1e9,s};\n\t\t\t\n\t\t\tif (s!=e){\n\t\t\t\tl=new node(s,m);\n\t\t\t\tr=new node(m+1,e);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid propo(){\n\t\t\tif (lazy){\n\t\t\t\tval.fi+=lazy;\n\t\t\t\tif (s!=e){\n\t\t\t\t\tl->lazy+=lazy;\n\t\t\t\t\tr->lazy+=lazy;\n\t\t\t\t}\n\t\t\t\tlazy=0;\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid update(int i,int j,int k){\n\t\t\tif (s==i && e==j) lazy+=k;\n\t\t\telse{\n\t\t\t\tif (j<=m) l->update(i,j,k);\n\t\t\t\telse if (m<i) r->update(i,j,k);\n\t\t\t\telse l->update(i,m,k),r->update(m+1,j,k);\n\t\t\t\t\n\t\t\t\tl->propo(),r->propo();\n\t\t\t\tval=min(l->val,r->val);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid set(int i,int k){\n\t\t\tpropo();\n\t\t\tif (s==e) val.fi=k;\n\t\t\telse{\n\t\t\t\tif (i<=m) l->set(i,k);\n\t\t\t\telse r->set(i,k);\n\t\t\t\t\n\t\t\t\tl->propo(),r->propo();\n\t\t\t\tval=min(l->val,r->val);\n\t\t\t}\n\t\t}\n\t} *root=new node(0,500005);\n\t\n\tstruct node2{\n\t\tint s,e,m;\n\t\tint val=-1e9;\n\t\tnode2 *l,*r;\n\t\t\n\t\tnode2 (int _s,int _e){\n\t\t\ts=_s,e=_e,m=s+e>>1;\n\t\t\t\n\t\t\tif (s!=e){\n\t\t\t\tl=new node2(s,m);\n\t\t\t\tr=new node2(m+1,e);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid update(int i,int k){\n\t\t\tif (s==e) val=k;\n\t\t\telse{\n\t\t\t\tif (i<=m) l->update(i,k);\n\t\t\t\telse r->update(i,k);\n\t\t\t\tval=max(l->val,r->val);\n\t\t\t}\n\t\t}\n\t\t\n\t\tii query(int i,int key){ //find key<=val where i<=s\n\t\t\tif (e<i || val<key) return {-1,-1};\n\t\t\tif (s==e) return {s,val};\n\t\t\telse{\n\t\t\t\tauto temp=l->query(i,key);\n\t\t\t\tif (temp!=ii(-1,-1)) return temp;\n\t\t\t\telse return r->query(i,key);\n\t\t\t}\n\t\t}\n\t} *root2=new node2(0,500005);\n\t\n\tset<ii> s={ {500005,500005} };\n\t\n\t//root stores the values of each pair\n\t//root2 stores the left endpoint of each pair to add non-overlapping ranges\n\t//s stores the pairs are still alive so its easy to do searches\n\t\n\tdat *d; //we also store the other guy\n\tbool orien; //false for i->arr[i]\n\t\n\tint pp[500005];\n\t\n\tvoid push(int i,int j){\n\t\tpp[j]=i;\n\t\troot2->update(j,i);\n\t}\n\t\n\tvoid add(int i,int j){\n\t\troot2->update(j,-1e9);\n\t\ts.insert({i,j});\n\t\t\n\t\tint val;\n\t\tif (!orien) val=fval.query(j)-fidx.query(i);\n\t\telse val=fidx.query(j)-fval.query(i);\n\t\t\n\t\troot->set(j,val);\n\t}\n\t\n\tvoid del(int j){\n\t\tii curr={-1,-1};\n\t\tint lim=500005;\n\t\t\n\t\tif (j!=-1){\n\t\t\tint i=pp[j];\n\t\t\t\n\t\t\tauto it=d->s.ub({j,1e9});\n\t\t\td->root->update(i,(*it).se-1,-1);\n\t\t\t\n\t\t\tif (!orien) fidx.upd(i,-1),fval.upd(j,-1);\n\t\t\telse fval.upd(i,-1),fidx.upd(j,-1);\n\t\t\t\n\t\t\tit=s.find({i,j});\n\t\t\tif (it!=s.begin()) curr=*prev(it);\n\t\t\tlim=(*next(it)).se;\n\t\t\ts.erase(it);\n\t\t\troot->set(j,1e9);\n\t\t\troot2->update(j,-1e9);\n\t\t}\n\t\t\n\t\twhile (true){\n\t\t\tauto temp=root2->query(curr.se,curr.fi);\n\t\t\tswap(temp.fi,temp.se);\n\t\t\tif (temp==ii(-1,-1) || lim<=temp.se) break;\n\t\t\t\n\t\t\tadd(temp.fi,temp.se);\n\t\t\tcurr=temp;\n\t\t}\n\t}\n} *l=new dat(),*r=new dat();\n\nint n;\n\nint main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\t//cyclic mapping to each other\n\tl->d=r;\n\tr->d=l;\n\t\n\tr->orien=true;\n\t\n\tcin>>n;\n\trep(x,1,n+1){\n\t\tint y;\n\t\tcin>>y;\n\t\t\n\t\tif (x<=y) l->push(x,y);\n\t\telse r->push(y,x);\n\t}\n\t\n\trep(x,1,n+1) fidx.upd(x,1),fval.upd(x,1);\n\tl->del(-1);\n\tr->del(-1);\n\t\n\tint ans=0;\n\t\n\trep(x,0,n){\n\t\tif (l->root->val.fi<=r->root->val.fi){\n\t\t\tans=max(ans,l->root->val.fi);\n\t\t\tl->del(l->root->val.se);\n\t\t}\n\t\telse{\n\t\t\tans=max(ans,r->root->val.fi);\n\t\t\tr->del(r->root->val.se);\n\t\t}\n\t}\n\t\n\tcout<<ans<<endl;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1673",
    "index": "A",
    "title": "Subtle Substring Subtraction",
    "statement": "Alice and Bob are playing a game with strings. There will be $t$ rounds in the game. In each round, there will be a string $s$ consisting of lowercase English letters.\n\nAlice moves first and both the players take alternate turns. \\textbf{Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $s$}.\n\nMore formally, if there was a string $s = s_1s_2 \\ldots s_k$ the player can choose a substring $s_ls_{l+1} \\ldots s_{r-1}s_r$ with length of corresponding parity and remove it. After that the string will become $s = s_1 \\ldots s_{l-1}s_{r+1} \\ldots s_k$.\n\nAfter the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $a$ is $1$, the value of $b$ is $2$, the value of $c$ is $3$, $\\ldots$, and the value of $z$ is $26$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.",
    "tutorial": "Greedy The answer depends on whether the length of $s$ is even or odd and on the first and last characters of $s$ if the length is odd. The problem can be solved greedily. Let $n$ be the length of the given string. If the $n$ is even, it is always optimal for Alice to remove the whole string. If the $n$ is odd, it is always optimal for Alice to remove either $s_1s_2\\ldots s_{n-1}$ or $s_2s_3\\ldots s_n$ based on which gives the higher score and then Bob can remove the remaining character ($s_n$ or $s_1$ respectively). This is optimal because if Alice chooses to remove a substring of even length $2k$ such that $2k < n-1$ then Bob can remove the remaining $n-2k\\geq 3$ characters, one of which will always be either $s_1$ or $s_n$, thus increasing Bob's score and decreasing Alice's score. Prove that - Bob can win if and only if the length of the string is $1$. A draw is impossible.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    int tc;\n    cin >> tc;\n    while(tc--)\n    {\n        string s;\n        cin >> s;\n        int n=s.length(),alice=0;\n        for(int i=0;i<n;i++)\n            alice += s[i]-'a'+1;\n        if(n%2==0)\n            cout << \"Alice \" << alice << '\\n';\n        else\n        {\n            int bob;\n            if(s[0]<=s[n-1])\n                bob = s[0]-'a'+1;\n            else\n                bob = s[n-1]-'a'+1;\n            alice -= bob;\n            if(alice > bob)\n                cout << \"Alice \" << alice-bob << '\\n';\n            else if(alice < bob)\n                cout << \"Bob \" << bob-alice << '\\n';\n            else\n                cout << \"Draw \" << 0 << '\\n';\n        }\n    }\n}",
    "tags": [
      "games",
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1673",
    "index": "B",
    "title": "A Perfectly Balanced String?",
    "statement": "Let's call a string $s$ perfectly balanced if for all possible triplets $(t,u,v)$ such that $t$ is a non-empty substring of $s$ and $u$ and $v$ are characters present in $s$, the difference between the frequencies of $u$ and $v$ in $t$ is not more than $1$.\n\nFor example, the strings \"aba\" and \"abc\" are perfectly balanced but \"abb\" is not because for the triplet (\"bb\",'a','b'), the condition is not satisfied.\n\nYou are given a string $s$ consisting of lowercase English letters only. Your task is to determine whether $s$ is perfectly balanced or not.\n\nA string $b$ is called a substring of another string $a$ if $b$ can be obtained by deleting some characters (possibly $0$) from the start and some characters (possibly $0$) from the end of $a$.",
    "tutorial": "The string is perfectly balanced if it is periodic and the repeating pattern contains all distinct alphabets. Let the number of distinct characters in $s$ be $k$ and length of $s$ be $n$. Then, $s$ will be perfectly balanced if and only if $s_{i}, s_{i+1}, \\ldots, s_{i+k-1}$ are all pairwise distinct for every $i$ in the range $1\\leq i\\leq n-k+1$. If there exists some $i$ in the range $1\\leq i\\leq n-k+1$ for which the characters $s_{i}, s_{i+1}, \\ldots, s_{i+k-1}$ are not pairwise distinct, there will be atleast one character $u$ in the substring $t=s_{i} s_{i+1}\\ldots s_{i+k-1}$ such that $f_t(u)\\geq 2$ and by pigeonhole principle, there will be atleast one character $v$ present in $s$ such that $f_t(v)=0$. So, for the triple $(t,u,v)$, $f_t(u)-f_t(v)\\geq 2$, violating the criteria for the $s$ to be perfectly balanced. Suppose the following condition is met. Let's pick up any substring $t=s_is_{i+1}\\ldots s_j$. Let's divide $t$ into $\\Big\\lceil \\frac{j-i+1}{k}\\Big\\rceil$ blocks each of length $k$ except probably the last block. For each of these blocks, the frequency of all characters is equal to $1$ (because there are $k$ distinct characters in a block as well as in $s$) and for the last block, the frequency of some characters is equal to $1$ wheras the frequency of rest of the characters is equal to $0$. So, the frequency of some characters in $t$ will be equal to $\\Big\\lceil \\frac{j-i+1}{k}\\Big\\rceil$ while that for the other characters will be equal to $\\Big\\lceil \\frac{j-i+1}{k}\\Big\\rceil-1$. If we pick any two characters $u$ and $v$, $\\lvert f_t(u)-f_t(v)\\rvert\\leq 1$ meaning that $s$ is perfectly balanced. Prove that the condition is equivalent to the following two conditions - The first $k$ characters of $s$ are pairwise distinct. For each $i$ in the range $1\\leq i\\leq n-k$, $s_i=s_{i+k}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    int tc;\n    cin >> tc;\n    while(tc--)\n    {\n        string s;\n        cin >> s;\n        int n = s.length();\n        set<char> c;\n        bool ok = true;\n        int k;\n        for(k=0;k<n;k++)\n        {\n            if(c.find(s[k])==c.end())\n                c.insert(s[k]);\n            else\n                break;\n        }\n        for(int i=k;i<n;i++)\n        {\n            if(s[i]!=s[i-k])\n                ok = false;\n        }\n        if(ok)\n            cout << \"YES\\n\";\n        else\n            cout << \"NO\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1673",
    "index": "C",
    "title": "Palindrome Basis",
    "statement": "You are given a positive integer $n$. Let's call some positive integer $a$ without leading zeroes palindromic if it remains the same after reversing the order of its digits. Find the number of distinct ways to express $n$ as a sum of positive palindromic integers. Two ways are considered different if the frequency of at least one palindromic integer is different in them. For example, $5=4+1$ and $5=3+1+1$ are considered different but $5=3+1+1$ and $5=1+3+1$ are considered the same.\n\nFormally, you need to find the number of distinct multisets of positive palindromic integers the sum of which is equal to $n$.\n\nSince the answer can be quite large, print it modulo $10^9+7$.",
    "tutorial": "The number of palindromes less than $4\\cdot 10^4$ is relatively small. The rest of the problem is quite similar to the classical partitions problem. First, we need to observe that the number of palindromes less than $4\\cdot 10^4$ is relatively very small. The number of $5$-digit palindromes are $300$ (enumerate all $3$-digit numbers less than $400$ and append the first two digits in the reverse order). Similarly, the number of $4$-digit, $3$-digit, $2$-digit and $1$-digit palindromes are $90$, $90$, $9$ and $9$ respectively, giving a total of $M=498$ palindromes. Now, the problem can be solved just like the classical partitions problem which can be solved using Dynamic Programming. Let $dp_{k,m} =$ Number of ways to partition the number $k$ using only the first $m$ palindromes. It is not hard to see that $dp_{k,m} = dp_{k,m-1} + dp_{k-p_m,m}$ where $p_m$ denotes the $m^{th}$ palindrome. The first term corresponds to the partitions of $k$ using only the first $m-1$ palindromes and the second term corresponds to those partitions of $k$ in which the $m^{th}$ palindrome has been used atleast once. As base cases, $dp_{k,1}=1$ and $dp_{1,m}=1$. The final answer for any $n$ will be $dp_{n,M}$. The time and space complexity is $\\mathcal{O}(n\\cdot M)$. Try to optimize the space complexity to $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 40004, M = 502;\nconst long long MOD = 1000000007;\nlong long dp[N][M];\n\nint reverse(int n)\n{\n    int r=0;\n    while(n>0)\n    {\n        r=r*10+n%10;\n        n/=10;\n    }\n    return r;\n}\n\nbool palindrome(int n)\n{\n    return (reverse(n)==n); \n}\n\nint main()\n{\n    vector<int> palin;\n    palin.push_back(0);\n    for(int i=1;i<2*N;i++)\n    {\n        if(palindrome(i))\n            palin.push_back(i);\n    }\n    for(int j=1;j<M;j++)\n        dp[0][j]=1;\n    for(int i=1;i<N;i++)\n    {\n        dp[i][0]=0;\n        for(int j=1;j<M;j++)\n        {\n            if(palin[j]<=i)\n                dp[i][j]=(dp[i][j-1]+dp[i-palin[j]][j])%MOD;\n            else\n                dp[i][j]=dp[i][j-1];\n        }\n    }\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int tc;\n    cin >> tc;\n    while(tc--)\n    {\n        int n;\n        cin >> n;\n        cout << dp[n][M-1] << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1673",
    "index": "D",
    "title": "Lost Arithmetic Progression",
    "statement": "Long ago, you thought of two finite arithmetic progressions $A$ and $B$. Then you found out another sequence $C$ containing all elements common to both $A$ and $B$. It is not hard to see that $C$ is also a finite arithmetic progression. After many years, you forgot what $A$ was but remember $B$ and $C$. You are, for some reason, determined to find this lost arithmetic progression. Before you begin this eternal search, you want to know how many different finite arithmetic progressions exist which can be your lost progression $A$.\n\nTwo arithmetic progressions are considered different if they differ in their first term, common difference or number of terms.\n\nIt may be possible that there are infinitely many such progressions, in which case you won't even try to look for them! Print $-1$ in all such cases.\n\nEven if there are finite number of them, the answer might be very large. So, you are only interested to find the answer modulo $10^9+7$.",
    "tutorial": "First check if all elements of $C$ are present in $B$ or not. If not, the answer is $0$. Then check if the answer is infinite or not. It depends on only the first and last elements of $B$ and $C$. If $p$ is the common difference of $A$ then $lcm(p,q)=r$. $p$ must necessarily be a factor of $r$ and $\\mathcal{O}(\\sqrt n)$ works here. If all elements of $C$ are not present in $B$, then the answer is $0$. It is sufficient to check the following $4$ conditions to check if all elements of $C$ are present in $B$ or not - The first term of $B\\leq$ The first term of $C$, i.e., $b\\leq c$. The last term of $B\\geq$ The last term of $C$, i.e., $b+(y-1)q\\geq c+(z-1)r$. The common difference of $C$ must be divisible by the common difference of $B$, i.e., $r\\bmod q=0$. The first term of $C$ must lie in $B$, i.e., $(c-b)\\bmod q=0$. Now suppose the following conditions are satisfied. Let's denote an Arithmetic Progression (AP) with first term $a$, common difference $d$ and $n$ number of terms by $[a,d,n]$. If $b>c-r$ then there are infinite number of progressions which can be $A$ like $[c,r,z]$, $[c-r,r,z+1]$, $[c-2r,r,z+2]$ and so on. Similarly, if $b+(y-1)q<c+zr$, there are infinite number of progressions which can be $A$ like $[c,r,z]$, $[c,r,z+1]$, $[c,r,z+2]$ and so on. Otherwise, there are a finite number of progressions which can be $A$. Let's count them. Let $A$ be the AP $[a,p,x]$ and $l=a+(x-1)p$. It can be seen that $lcm(p,q)=r$, $(c-a)\\bmod p=0$, $a>c-r$ and $l<c+rz$ for any valid $A$. The first two conditions are trivial. The third condition is necessary because if $a\\leq c-r$ then $c-r$ will always be present in both $A$ and $B$ contradicting the fact that $C$ contains all the terms common to $A$ and $B$. Similarly, the fourth condition is also necessary. The only possible values $p$ can take according to the first condition are factors of $r$ which can be enumerated in $\\mathcal{O}(\\sqrt{r})$. The $lcm$ condition can be checked in $\\mathcal{O}(\\log r)$. For a particular value of $p$, there are $\\frac{r}{p}$ possible values of $a$ satisfying conditions 2 and 3 and $\\frac{r}{p}$ possible values of $l$ satisfying conditions 2 and 4. Thus, the answer is $\\displaystyle\\sum_{lcm(p,q)=r}\\Big(\\frac{r}{p}\\Big)^2$. Time complexity: $\\mathcal{O}(t\\,\\sqrt{r}\\,\\log r)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long MOD = 1000000007;\n\nlong long gcd(long long a,long long b)\n{\n    if(b==0)\n        return a;\n    else\n        return gcd(b,a%b);\n}\n\nlong long lcm(long long a,long long b)\n{\n    long long g = gcd(a,b);\n    return (a*b)/g;\n}\n\nint main()\n{\n    int tc;\n    cin >> tc;\n    while(tc--)\n    {\n        long long b,c,q,r,y,z;\n        cin >> b >> q >> y;\n        cin >> c >> r >> z;\n        long long e = b+q*(y-1);\n        long long f = c+r*(z-1);\n        if(c<b || c>e || f<b || f>e || r%q!=0 || (c-b)%q!=0)\n            cout << 0 << '\\n';\n        else if(c-r<b || f+r>e)\n            cout << -1 << '\\n';\n        else\n        {\n            long long ans = 0;\n            for(long long p=1;p*p<=r;p++)\n            {\n                if(r%p==0)\n                {\n                    if(lcm(p,q)==r)\n                    {\n                        long long a = ((r/p)*(r/p))%MOD;\n                        ans = (ans+a)%MOD;\n                    }\n                    if(p*p!=r && lcm(r/p,q)==r)\n                    {\n                        long long a = (p*p)%MOD;\n                        ans = (ans+a)%MOD;\n                    }\n                }\n            }\n            cout << ans << '\\n';\n        }\n    }\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1673",
    "index": "E",
    "title": "Power or XOR?",
    "statement": "The symbol $\\wedge$ is quite ambiguous, especially when used without context. Sometimes it is used to denote a power ($a\\wedge b = a^b$) and sometimes it is used to denote the XOR operation ($a\\wedge b=a\\oplus b$).\n\nYou have an ambiguous expression $E=A_1\\wedge A_2\\wedge A_3\\wedge\\ldots\\wedge A_n$. You can replace each $\\wedge$ symbol with either a $Power$ operation or a $XOR$ operation to get an unambiguous expression $E'$.\n\nThe value of this expression $E'$ is determined according to the following rules:\n\n- All $Power$ operations are performed before any $XOR$ operation. In other words, the $Power$ operation takes precedence over $XOR$ operation. For example, $4\\;XOR\\;6\\;Power\\;2=4\\oplus (6^2)=4\\oplus 36=32$.\n- Consecutive powers are calculated from \\textbf{left to right}. For example, $2\\;Power\\;3 \\;Power\\;4 = (2^3)^4 = 8^4 = 4096$.\n\nYou are given an array $B$ of length $n$ and an integer $k$. The array $A$ is given by $A_i=2^{B_i}$ and the expression $E$ is given by $E=A_1\\wedge A_2\\wedge A_3\\wedge\\ldots\\wedge A_n$. You need to find the XOR of the values of all possible unambiguous expressions $E'$ which can be obtained from $E$ and has at least $k$ $\\wedge$ symbols used as $XOR$ operation. Since the answer can be very large, you need to find it modulo $2^{2^{20}}$. Since this number can also be very large, you need to print its binary representation \\textbf{without leading zeroes}. If the answer is equal to $0$, print $0$.",
    "tutorial": "All numbers in $A$ are powers of $2$ and the modulo is also a power of $2$ and $B_i\\geq 1$. Fix all operators in a particular subsegment as $\\texttt{Power}$ and fix the operators around the segment as $\\texttt{XOR}$. Find the contribution of this segment independent of other segments. Maximum possible length for such a subsegment which can contribute to the answer is $20$. Use Lucas' Theorem or Submasks DP or precomputation in order to count the parity of the number of valid unambiguous expressions in which the subsegment appears as in Hint 2. Let's consider a subsegment $[A_{l}\\wedge A_{l+1}\\wedge A_{l+2}\\wedge\\ldots\\wedge A_r]$. Let all the $\\wedge$ symbols in this segment be replaced by $\\texttt{Power}$ and the $\\wedge$ symbols before $A_l$ and after $A_r$ be replaced by $\\texttt{XOR}$. Then the value of this segment will not be affected by the rest of the expression. Moreover, out of all the expressions in which this segment appears as above, it will contribute the same value to the final answer. Since the final answer is also a $\\texttt{XOR}$, if the segment $[l\\ldots r]$ appears in the above mentioned form in odd number of valid unambiguous expressions, it will contribute $(\\ldots((A_l^{A_{l+1}})^{A_{l+2}}) \\ldots )^ {A_r}$ to the final answer else it will contribute nothing. We can find the contribution of each segment $[l\\ldots r]$ independently for all values of $1\\leq l < r \\leq n$. Now, there are two things we need to find out: How much $(\\ldots((A_l^{A_{l+1}})^{A_{l+2}}) \\ldots )^ {A_r}$ will contribute to the final answer, modulo $MOD = 2^{1048576}$. What is the parity of the count of valid unambiguous expressions, in which the segment $[l...r]$ appears as $... \\oplus (\\ldots((A_l^{A_{l+1}})^{A_{l+2}}) \\ldots )^ {A_r} \\oplus \\ldots$. Part 1: Notice that since all the elements of $A$ are powers of $2$, $S(l,r)=(\\ldots((A_l^{A_{l+1}})^{A_{l+2}}) \\ldots )^ {A_r}$ will also be a power of $2$. It means that $\\texttt{XOR}$-ing it with answer will flip not more than $1$ bit in the answer. The rest of the calculations is pretty straightforward. $S(l,r) = 2^{B_l\\cdot A_{l+1}\\cdot A_{l+2}\\cdot\\ldots\\cdot A_{r}}$ by properties of exponents. So, if it contributes to the answer, it will flip the $B_l\\cdot A_{l+1}\\cdot A_{l+2}\\cdot\\ldots\\cdot A_{r}-$th bit of the answer. Now, note that if $S\\geq 2^{1048576}$, it will have no effect on the answer because $S(l,r) \\bmod 2^{1048576}$ will then be $0$. So, we care only for those $(l,r)$ for which $S(l,r) < 2^{1048576}$. Since $B_i\\geq 1$, $A_i\\geq 2$ and so, $r-l \\leq 20$ because $2^{20} = 1048576$. Thus, it is sufficient to calculate $S(l,r)$ for only $20$ values of $r$ per value of $l$. Part 2: We have used $r-l$ $\\wedge$ operators as $\\texttt{Power}$ and $0$, $1$ or $2$ $\\wedge$ operators as $\\texttt{XOR}$. Let's say that out of the $m$ unused operators, we need to use at least $q$ of them as $\\texttt{XOR}$. Then the number of ways to do this is $\\binom{m}{q}+\\binom{m}{q+1}+\\binom{m}{q+2}+\\ldots+\\binom{m}{m}$. Infact, instead of finding this value, we are only interested in finding whether it is even or odd. So, we need the value of $\\big[\\binom{m}{q}+\\binom{m}{q+1}+\\binom{m}{q+2}+\\ldots+\\binom{m}{m}\\big]\\bmod 2=$ $\\big[\\binom{m-1}{q}+\\binom{m-1}{q-1} + \\binom{m-1}{q+1}+\\binom{m-1}{q} + \\binom{m-1}{q+2}+\\binom{m-1}{q+1} + \\ldots + \\binom{m-1}{m-1}+\\binom{m-1}{m-2} + \\binom{m}{m}\\big] \\bmod 2=$ $\\big[\\binom{m-1}{q-1} + \\binom{m-1}{m-1} + \\binom{m}{m}]\\bmod 2 =$ $\\binom{m-1}{q-1} \\bmod 2$ as $(a + a) \\bmod 2 = 0$ and $\\binom{x}{x} = 1$ by definition. $\\binom{m-1}{q-1} \\bmod 2$ can be found using Lucas' Theorem. It turns out that $\\binom{n}{r}$ is odd if and only if $r$ is a submask of $n$, i.e., $n | r = n$. Note that there are also many other ways to find this value (like Submasks DP or using the fact that $r-l\\leq 20$ for precomputation) but this is the easiest one. Some final notes - We can maintain the final answer as a binary string of length $1048576$. Find the value $X = B_l\\cdot A_{l+1}\\cdot A_{l+2}\\cdot\\ldots\\cdot A_{r}$ and if the required parity is odd and $X < 1048576$, flip the $X-$th bit of the string. We need to be careful while calculating $B_l\\cdot A_{l+1}\\cdot A_{l+2}\\cdot\\ldots\\cdot A_{r}$ since $A_i$ can be as large as $2^{1048575}$. But since we are interested in values that evaluate to something smaller than $1048576$, we will never try to multiply $A_i$ for anything with $B_i > 20$. Calculating the parity of $\\binom{n}{r}$ in $\\mathcal{O}(\\log n)$ may time out. The constraints are strict enough. Total time Complexity - $\\mathcal{O}(n \\log \\log MOD)$ Try to solve the problem if $B_i\\geq 0$ and if powers are calculated from right to left.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1048576;\nlong long b[N];\nchar ans[N];\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int n,k;\n    cin >> n >> k;\n    for(int i=0;i<n;i++)\n    {\n        cin >> b[i];\n    }\n    for(int i=0;i<1048576;i++)\n        ans[i]='0';\n    for(int l=0;l<n;l++)\n    {\n        long long p=1;\n        for(int r=l;r<n;r++)\n        {\n            if(r==l)\n                p*=b[r];\n            else\n            {\n                if(b[r]>=20)\n                    break;\n                else\n                    p*=(1ll<<b[r]);\n            }\n            if(p>=1048576)\n                break;\n            int m = n-r+l-3;\n            int q = k-2;\n            if(l==0)\n            {\n                m++;\n                q++;\n            }\n            if(r==n-1)\n            {\n                m++;\n                q++;\n            }\n            if(m>=q && (m==0 || (q>0 && ((m-1)|(q-1))==(m-1))))\n                ans[p]='1'+'0'-ans[p];\n        }\n    }\n    bool start=false;\n    for(int i=1048575;i>=0;i--)\n    {\n        if(ans[i]=='0' && start)\n            cout << 0;\n        else if(ans[i]=='1')\n        {\n            cout << 1;\n            start=true;\n        }\n    }\n    if(!start)\n        cout << 0;\n    cout << '\\n';\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1673",
    "index": "F",
    "title": "Anti-Theft Road Planning",
    "statement": "This is an interactive problem.\n\nA city has $n^2$ buildings divided into a grid of $n$ rows and $n$ columns. You need to build a road of some length $D(A,B)$ of your choice between each pair of adjacent by side buildings $A$ and $B$. Due to budget limitations and legal restrictions, the length of each road must be a positive integer and \\textbf{the total length of all roads should not exceed $48\\,000$}.\n\nThere is a thief in the city who will start from the topmost, leftmost building (in the first row and the first column) and roam around the city, occasionally stealing artifacts from some of the buildings. He can move from one building to another adjacent building by travelling through the road which connects them.\n\nYou are unable to track down what buildings he visits and what path he follows to reach them. But there is one tracking mechanism in the city. The tracker is capable of storing a single integer $x$ which is initially $0$. Each time the thief travels from a building $A$ to another adjacent building $B$ through a road of length $D(A,B)$, the tracker changes $x$ to $x\\oplus D(A,B)$. Each time the thief steals from a building, the tracker reports the value $x$ stored in it and resets it back to $0$.\n\nIt is known beforehand that the thief will steal in exactly $k$ buildings but you will know the values returned by the tracker only after the thefts actually happen. Your task is to choose the lengths of roads in such a way that no matter what strategy or routes the thief follows, you will be able to exactly tell the location of all the buildings where the thefts occurred from the values returned by the tracker.",
    "tutorial": "The main goal is to assign numbers $A_{i,j}$ from $0$ to $1023$ to all buildings such that all buildings get distinct numbers and assign the road lengths between buildings $B_{x_1,y_1}$ and $B_{x_2,y_2}$ as $A_{x_1,y_1}\\oplus A_{x_2,y_2}$. Among all such assignments, try to find the one which has the least sum of road lengths. $2$-Dimensional Gray Code works For now, lets ignore $n<=32$ and assume $n=32$. Let's try to build the roads in such a way that no matter what path the thief takes to reach building $B_{i,j}$, the tracker will always return a fixed value $A_{i,j}$ such that all $A_{i,j}$ are distinct. Then by knowing the values returned by the tracker, one can easily find which building the theft occurred in. The main problem here is not to choose the lengths of the roads, since by choosing the length of road between buildings $B_{x_1,y_1}$ and $B_{x_2,y_2}$ as $A_{x_1,y_1}\\oplus A_{x_2,y_2}$, one can always achieve this property. But there is a constraint which needs to be satisfied: The total length of all roads must not exceed $48000$. This is, in fact, a tight constraint (model solution uses $47616$) due to which one needs to choose the values of $A_{i,j}$ very efficiently. Consider this problem - Find a permutation of numbers from $0$ to $2^m-1$ such that the sum of XOR of consecutive integers is minimized. The answer to this is Gray Code or Reflected Binary Code. In the standard Gray Code, bit $0$ is flipped $2^{m-1}$ times, bit $1$ is flipped $2^{m-2}$ times, bit $2$ is flipped $2^{m-3}$ times, $\\ldots$, bit $m-1$ is flipped $1$ time. The idea is to use small bits more number of times compared to the larger ones. Our task is to implement this idea in $2$-dimensions. Let's look at the algorithm used to build Gray Code. If we have the Gray Code for $k$ bits, it can be extended to $k+1$ bits by taking a copy of it, reflecting it and appending $1$ to the beginning of the reflected code and $0$ to the beginning of the original one. Here, if we have the Gray Code for $2^k \\times 2^k$ matrix, it can be first extended to a Gray Code for $2^k \\times 2^{k+1}$ matrix and this can further be extended to a Gray Code for $2^{k+1} \\times 2^{k+1}$ matrix. If we build a $2^m \\times 2^m$ matrix using this algorithm, the total length of roads used will be $\\frac{3}{2}\\cdot(4^m)\\cdot(2^m-1)$. In this problem, $m = 5$. So, total length of roads used = $\\frac{3}{2} \\cdot 1024 \\cdot 31 = 47616$. Once this construction is complete, finding the buildings where thefts occurred is elementary since there can now be only one building corresponding to each value returned by the tracker. Now, coming back to the original problem, we can simply take the first $n$ rows and the first $n$ columns from the constructed matrix. The cost won't increase and the properties still hold.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 32;\n\nint maxpower2(int n)\n{\n    int p=1;\n    while(n%2==0)\n    {\n        p*=2;\n        n/=2;\n    }\n    return p;\n}\n\nint main()\n{\n    int n,k;\n    cin >> n >> k;\n    int h[N][N-1];\n    for(int i=0;i<N;i++)\n    {\n        for(int j=1;j<=N-1;j++)\n        {\n            h[i][j-1]=maxpower2(j)*maxpower2(j);\n        }\n    }\n    for(int i=0;i<n;i++)\n    {\n        for(int j=0;j<n-1;j++)\n        {\n            cout << h[i][j] << \" \";\n        }\n        cout << endl;\n    }\n    int v[N-1][N];\n    for(int i=1;i<=N-1;i++)\n    {\n        for(int j=0;j<N;j++)\n        {\n            v[i-1][j]=2*maxpower2(i)*maxpower2(i);\n        }\n    }\n    for(int i=0;i<n-1;i++)\n    {\n        for(int j=0;j<n;j++)\n        {\n            cout << v[i][j] << \" \";\n        }\n        cout << endl;\n    }\n    int b[n][n];\n    b[0][0]=0;\n    for(int j=1;j<n;j++)\n    {\n        b[0][j]=b[0][j-1]^h[0][j-1];\n    }\n    for(int i=1;i<n;i++)\n    {\n        for(int j=0;j<n;j++)\n        {\n            b[i][j]=b[i-1][j]^v[i-1][j];\n        }\n    }\n    map<int,pair<int,int> > m;\n    for(int i=0;i<n;i++)\n    {\n        for(int j=0;j<n;j++)\n        {\n            m[b[i][j]]={i,j};\n        }\n    }\n    int y=0;\n    while(k--)\n    {\n        int x;\n        cin >> x;\n        pair<int,int> ans = m[x^y];\n        cout << ans.first+1 << \" \" << ans.second+1 << endl;\n        y^=x;\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "divide and conquer",
      "greedy",
      "interactive",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1674",
    "index": "A",
    "title": "Number Transformation",
    "statement": "You are given two integers $x$ and $y$. You want to choose two \\textbf{strictly positive} (greater than zero) integers $a$ and $b$, and then apply the following operation to $x$ \\textbf{exactly} $a$ times: replace $x$ with $b \\cdot x$.\n\nYou want to find two positive integers $a$ and $b$ such that $x$ becomes equal to $y$ after this process. If there are multiple possible pairs, you can choose \\textbf{any of them}. If there is no such pair, report it.\n\nFor example:\n\n- if $x = 3$ and $y = 75$, you may choose $a = 2$ and $b = 5$, so that $x$ becomes equal to $3 \\cdot 5 \\cdot 5 = 75$;\n- if $x = 100$ and $y = 100$, you may choose $a = 3$ and $b = 1$, so that $x$ becomes equal to $100 \\cdot 1 \\cdot 1 \\cdot 1 = 100$;\n- if $x = 42$ and $y = 13$, there is no answer since you cannot decrease $x$ with the given operations.",
    "tutorial": "The process in the statement can be rephrased as \"multiply $x$ by $b^a$\". $x \\cdot b^a$ will be divisible by $x$, so if $y$ is not divisible by $x$, there is no answer. Otherwise, $a = 1$ and $b = \\frac{y}{x}$ can be used.",
    "code": "t = int(input())\nfor i in range(t):\n    x, y = map(int, input().split())\n    if y % x != 0:\n        print(0, 0)\n    else:\n        print(1, y // x)",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1674",
    "index": "B",
    "title": "Dictionary",
    "statement": "The Berland language consists of words having \\textbf{exactly two letters}. Moreover, \\textbf{the first letter of a word is different from the second letter}. Any combination of two different Berland letters (which, by the way, are the same as the lowercase letters of Latin alphabet) is a correct word in Berland language.\n\nThe Berland dictionary contains all words of this language. The words are listed in a way they are usually ordered in dictionaries. Formally, word $a$ comes earlier than word $b$ in the dictionary if one of the following conditions hold:\n\n- the first letter of $a$ is less than the first letter of $b$;\n- the first letters of $a$ and $b$ are the same, and the second letter of $a$ is less than the second letter of $b$.\n\nSo, the dictionary looks like that:\n\n- Word $1$: ab\n- Word $2$: ac\n- ...\n- Word $25$: az\n- Word $26$: ba\n- Word $27$: bc\n- ...\n- Word $649$: zx\n- Word $650$: zy\n\nYou are given a word $s$ from the Berland language. Your task is to find its index in the dictionary.",
    "tutorial": "There are many different ways to solve this problem: generate all Berland words with two for-loops and store them in an array, then for each test case, go through the array of words to find the exact word you need; generate all Berland words with two for-loops and store them in a dictionary-like data structure (map in C++, dict in Python, etc), using words as keys and their numbers as values. This allows to search for the index of the given word quickly; for each test case, run two for-loops to iterate over the words, count the number of words we skipped, and stop at the word from the test case; try to invent some formulas that allow counting the number of words before the given one.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() \n{\n    string w = \"aa\";\n    map<string, int> idx;\n    int i = 1;\n    for(w[0] = 'a'; w[0] <= 'z'; w[0]++)\n        for(w[1] = 'a'; w[1] <= 'z'; w[1]++)\n            if(w[0] != w[1])\n                idx[w] = i++;\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        string s;\n        cin >> s;\n        cout << idx[s] << endl;\n    }   \n}\n",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1674",
    "index": "C",
    "title": "Infinite Replacement",
    "statement": "You are given a string $s$, consisting only of Latin letters 'a', and a string $t$, consisting of lowercase Latin letters.\n\nIn one move, you can replace any letter 'a' in the string $s$ with a string $t$. Note that after the replacement string $s$ might contain letters other than 'a'.\n\nYou can perform an arbitrary number of moves (including zero). How many different strings can you obtain? Print the number, or report that it is infinitely large.\n\nTwo strings are considered different if they have different length, or they differ at some index.",
    "tutorial": "Let's consider some cases. If there are letters 'a' in string $t$, then the moves can be performed endlessly. If $t$ itself is equal to \"a\", then the string won't change, so the answer is $1$. Otherwise, the length of $t$ is least $2$, so string $s$ will be increasing in length after each move, and the answer is -1. If there are no letters 'a' in string $t$, then the resulting string is only determined by whichever letters 'a' we chose to replace with $t$. That's because once we replace a letter 'a' with string $t$, we can do nothing with the new letters anymore. We can actually imagine that $t$ is equal to \"b\", and the answer won't change. Now it's easy to see that the answer is equal to the number of strings of length $n$, consisting only of letters 'a' and 'b'. There are two options for each position, and there are $n$ positions, so the answer is $2^n$. Overall complexity: $O(|s| + |t|)$ per testcase.",
    "code": "for _ in range(int(input())):\n    s = input()\n    t = input()\n    if t == \"a\":\n        print(1)\n    elif t.count('a') != 0:\n        print(-1)\n    else:\n        print(2**len(s))\n        ",
    "tags": [
      "combinatorics",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1674",
    "index": "D",
    "title": "A-B-C Sort",
    "statement": "You are given three arrays $a$, $b$ and $c$. Initially, array $a$ consists of $n$ elements, arrays $b$ and $c$ are empty.\n\nYou are performing the following algorithm that consists of two steps:\n\n- Step $1$: while $a$ is not empty, you take the last element from $a$ and move it in the middle of array $b$. If $b$ currently has odd length, you can choose: place the element from $a$ to the left or to the right of the middle element of $b$. As a result, $a$ becomes empty and $b$ consists of $n$ elements.\n- Step $2$: while $b$ is not empty, you take the middle element from $b$ and move it to the end of array $c$. If $b$ currently has even length, you can choose which of two middle elements to take. As a result, $b$ becomes empty and $c$ now consists of $n$ elements.\n\nRefer to the Note section for examples.Can you make array $c$ sorted in non-decreasing order?",
    "tutorial": "Let's look at elements $a_n$ and $a_{n - 1}$. After the first step, they will always move to positions $b_1$ and $b_n$ (it's up to you to choose: $a_n \\to b_1$ and $a_{n-1} \\to b_n$ or vice versa) because all remaining $a_i$ for $i < n - 1$ will be placed between $a_n$ and $a_{n-1}$. After the second step, elements $b_1$ and $b_n$ will always be placed at positions $c_{n-1}$ and $c_n$ (it's also up to you to decide the exact order) because it's easy to see that you first take all $b_i$ for $1 < i < n$ and only after that - $b_1$ and $b_n$. In other words, elements $a_{n-1}$ and $a_n$ are moved to positions $c_{n-1}$ and $c_n$. We can analogically prove that each pair $(a_{n-2i-1}, a_{n-2i})$ is moved to a pair of positions $(c_{n-2i-1}, c_{n-2i})$: you first take all elements $a_j$ for $j > n - 2i$ and place them at positions $[b_1, \\dots, b_i]$ and $[b_{n-i+1}, \\dots, b_n]$; then you move $a_{n-2i}$ and $a_{n-2i-1}$; finally you move all remaining elements from $a$ between $b_{i+1}$ and $b_{n-i}$. Step $2$ just does everything in \"reverse\" order to step $1$. It means that array $c$ is basically array $a$, but you can swap elements in pairs $(a_{n-2i-1}, a_{n-2i})$ for $i \\ge 0$. And to make $a$ ($c$) sorted, we can try to sort each pair and check - is it enough to sort the whole array or not.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val a = readLine()!!.split(' ').map { it.toInt() }.toIntArray()\n        for (i in (n % 2) until n step 2) {\n            if (a[i] > a[i + 1])\n                a[i] = a[i + 1].also { a[i + 1] = a[i] }\n        }\n        var sorted = true\n        for (i in a.indices)\n            if (i > 0 && a[i - 1] > a[i])\n                sorted = false\n        println(if(sorted) \"YES\" else \"NO\")\n    }\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1674",
    "index": "E",
    "title": "Breaking the Wall",
    "statement": "Monocarp plays \"Rage of Empires II: Definitive Edition\" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.\n\nThe wall consists of $n$ sections, aligned in a row. The $i$-th section initially has durability $a_i$. If durability of some section becomes $0$ or less, this section is considered broken.\n\nTo attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $2$ damage to the target section and $1$ damage to adjacent sections. In other words, if the onager shoots at the section $x$, then the durability of the section $x$ decreases by $2$, and the durability of the sections $x - 1$ and $x + 1$ (if they exist) decreases by $1$ each.\n\nMonocarp can shoot at any sections any number of times, \\textbf{he can even shoot at broken sections}.\n\nMonocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!",
    "tutorial": "Let's analyze three cases based on the distance between two sections we are going to break: break two neighboring sections ($i$ and $i+1$); break two sections with another section between them ($i$ and $i+2$); break two sections with more than one section between them. Why exactly these cases? Because the damage from the shots and the possibility to hit both sections with the same shot depends on the distance between them. If there is more than one section between the two we want to break, then any shot hits only one of these sections, so each shot should be aimed at one of those sections, and we break them independently. Let's pick two sections with minimum durability and calculate the number of shots required to break them; if these sections are $i$ and $j$, then the required number of shots is $\\lceil \\frac{a_i}{2} \\rceil + \\lceil \\frac{a_j}{2} \\rceil$. It actually does not matter if the distance between them is less than $3$; if it is so, these sections will be analyzed in one of the other cases. Okay, now let's deal with two sections having exactly one section between them. We can iterate on all combinations of these sections (iterate on $i$ from $1$ to $n-2$ and pick sections $i$ and $i+2$). Let's analyze how can we damage them. If we shoot at the section between them, we deal $1$ damage to both sections; if we shoot at one of those sections, we deal $2$ damage to it and $0$ damage to the other section. So, each shot distributes $2$ damage between these two sections the way we want to distribute it, and the number of shots required to break these two sections is $\\lceil \\frac{a_i + a_{i+2}}{2} \\rceil$. The case when we try to break two adjacent sections is the trickiest one. Let's say that these sections are $i$ and $i+1$, $x = \\max(a_i, a_{i+1})$, and $y = \\min(a_i, a_{i+1})$. If we target one of these sections, we deal $2$ damage to it and $1$ damage to the other section. Let's try to run the following algorithm: shoot at the section with higher durability, until both of them break. It can be slow, but we can see that after the first $x-y$ shots, the durabilities of the sections become equal, and each pair of shots after that deals $3$ damage to both sections. So, we can model the first $x-y$ shots, subtract $2(x-y)$ from $x$ and $(x-y)$ from $y$, and then we'll need $\\lceil \\frac{x+y}{3} \\rceil$ shots. The only case when this doesn't work is if we break both sections before we equalize their durabilities; it means that $2y \\le x$ and we need to do only $\\lceil \\frac{x}{2} \\rceil$ shots.",
    "code": "#include <iostream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n#include <cmath>\n#include <queue>\n#include <string>\n#include <cstring>\n#include <cassert>\n#include <iomanip>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <ctime>\n#include <cmath>\n\n#define forn(i, n) for(int i=0;i<n;++i)\n#define fore(i, l, r) for(int i = int(l); i <= int(r); ++i)\n#define sz(v) int(v.size())\n#define all(v) v.begin(), v.end()\n#define pb push_back\n#define mp make_pair\n#define x first\n#define y1 ________y1\n#define y second\n#define ft first\n#define sc second\n#define pt pair<int, int>\n\ntemplate<typename X> inline X abs(const X& a) { return a < 0? -a: a; }\ntemplate<typename X> inline X sqr(const X& a) { return a * a; }\n\ntypedef long long li;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int INF = 1000 * 1000 * 1000;\nconst ld EPS = 1e-9;\nconst ld PI = acos(-1.0);\n\nconst int N = 200 * 1000 + 13;\n\nint n;\nint a[N];\n\ninline void read() {\n    cin >> n;\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }   \n}\n\ninline void solve() {   \n    int ans = INF;\n    for (int i = 0; i < n - 1; i++) {\n        int cur = 0;\n        int x = a[i], y = a[i + 1];\n        if (x < y) {\n            swap(x, y);\n        }\n        int cnt = min(x - y, (x + 1) / 2);\n        cur += cnt;\n        x -= 2 * cnt;\n        y -= cnt;\n        if (x > 0 && y > 0) {\n            cur += (x + y + 2) / 3;\n        }\n        ans = min(ans, cur);    \n    }\n\n    for (int i = 0; i < n - 2; i++) {\n        int cur = 0;\n        int x = a[i], y = a[i + 2];\n        if (x < y) {\n            swap(x, y);\n        }\n        int cnt = (x - y + 1) / 2;\n        cur += cnt;\n        cur += y;\n        ans = min(ans, cur);\n    }\n    \n    sort(a, a + n);\n    ans = min(ans, (a[0] + 1) / 2 + (a[1] + 1) / 2);\n    cout << ans << endl;\n}\n\nint main () {\n#ifdef fcspartakm\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n#endif\n    srand(time(NULL));\n    cerr << setprecision(10) << fixed;\n    \n    read();\n    solve();\n \n    //cerr << \"TIME: \" << clock() << endl;\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1674",
    "index": "F",
    "title": "Desktop Rearrangement",
    "statement": "Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $n \\times m$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).\n\nThe desktop is called \\textbf{good} if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.\n\nIn one move, you can take one icon and move it to any empty cell in the desktop.\n\nIvan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $q$ queries: what is the \\textbf{minimum} number of moves required to make the desktop \\textbf{good} after adding/removing one icon?\n\nNote that \\textbf{queries are permanent} and change the state of the desktop.",
    "tutorial": "I've seen a lot of data structures solutions for this problem, but author's solution doesn't use them and works in $O(nm + q)$. Firstly, let's change our matrix to a string $s$, because it will be easier to work with a string than with a matrix. The order of characters will be from top to bottom, from left to right (i. e. the outer cycle by columns, and the inner by rows). Then, let's calculate $sum$ - the number of icons on the desktop (the number of '*' in $s$). Then the answer will be, obviously, the number of dots on the prefix of $s$ of size $sum$. Now let's deal with queries. It can be shown that one query changes our answer by no more than $1$. Let $p = ny + x$ be the position of the cell that is being changed in $s$ (zero-indexed). Then, if $p < sum$, there are two cases. If $s_p$ is '.', then we have one more icon on our prefix, so the answer decreases by one (because we filled one empty space in the good desktop). Otherwise, it increases by one (because this icon is outside our prefix). Then let's change the corresponding character by the opposite. After that, we should move our right border ($sum$) accordingly to the new number of icons. Note that this border is exclusive. If $s_p$ becomes '*', then we will increase the variable $sum$. But before that, if $s_{sum}$ is '.', then there should be an icon, and it is not here yet, so the answer increases. Otherwise, our border will decrease. Then, if $s_{sum - 1}$ is '.', then the answer decreases (because there was a place for an icon, and now it is not needed anymore). Time complexity: $O(nm + q)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nstatic char buf[1010];\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int n, m, q;\n    scanf(\"%d %d %d\", &n, &m, &q);\n    vector<string> tmp(n);\n    string s;\n    int sum = 0;\n    for (int i = 0; i < n; ++i) {\n        scanf(\"%s\", buf);\n        tmp[i] = buf;\n        sum += count(tmp[i].begin(), tmp[i].end(), '*');\n    }\n    \n    for (int j = 0; j < m; ++j) {\n        for (int i = 0; i < n; ++i) {\n            s += tmp[i][j];\n        }\n    }\n    int res = count(s.begin(), s.begin() + sum, '.');\n    int pos = sum;\n    for (int i = 0; i < q; ++i) {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        --x, --y;\n        int p = y * n + x;\n        if (p < pos) {\n            if (s[p] == '.') {\n                --res;\n            } else {\n                ++res;\n            }\n        }\n        s[p] = (s[p] == '.' ? '*' : '.');\n        if (s[p] == '*') {\n            if (s[pos] == '.') {\n                ++res;\n            }\n            ++pos;\n        } else {\n            if (s[pos - 1] == '.') {\n                --res;\n            }\n            --pos;\n        }\n        printf(\"%d\\n\", res);\n    }\n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1674",
    "index": "G",
    "title": "Remove Directed Edges",
    "statement": "You are given a directed acyclic graph, consisting of $n$ vertices and $m$ edges. The vertices are numbered from $1$ to $n$. There are no multiple edges and self-loops.\n\nLet $\\mathit{in}_v$ be the number of incoming edges (indegree) and $\\mathit{out}_v$ be the number of outgoing edges (outdegree) of vertex $v$.\n\nYou are asked to remove some edges from the graph. Let the new degrees be $\\mathit{in'}_v$ and $\\mathit{out'}_v$.\n\nYou are only allowed to remove the edges if the following conditions hold for every vertex $v$:\n\n- $\\mathit{in'}_v < \\mathit{in}_v$ or $\\mathit{in'}_v = \\mathit{in}_v = 0$;\n- $\\mathit{out'}_v < \\mathit{out}_v$ or $\\mathit{out'}_v = \\mathit{out}_v = 0$.\n\nLet's call a set of vertices $S$ cute if for each pair of vertices $v$ and $u$ ($v \\neq u$) such that $v \\in S$ and $u \\in S$, there exists a path either from $v$ to $u$ or from $u$ to $v$ over the non-removed edges.\n\nWhat is the maximum possible size of a cute set $S$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $0$?",
    "tutorial": "Let's solve the problem in reverse. Imagine we have already removed some edges, so that the conditions hold. When is some set of vertices considered cute? Since the graph is acyclic, we can topologically sort the vertices in the set. The vertices are reachable from each other, so there exists a path from the $i$-th vertex in the set to the $(i+1)$-st vertex. Thus, there exists a path that goes through all chosen vertices. However, we can make this conclusion even stronger. In the optimal answer, not just the path goes from the $i$-th vertex to the $(i+1)$-st one, but a single edge. That can be shown by contradiction. Let there be some vertices $v$ and $u$ that are adjacent in the chosen cute set. There exists a path between them, but not a single edge. We want to show that this set is not optimal and can be made larger. The vertices on that path don't belong to the set. If they did, they would be between $v$ and $u$ in the set (because of the topological order). We can add them to the set. Every vertex that can reach $v$, can reach them too, and every vertex that can be reached from $u$, can be reached from them. Thus, it will still be a cute set. Now every vertex from $v$ to $u$ has an edge between them and the size of the set is larger. Thus, we showed that the maximum set in the answer is always some path in the graph. So the task is to choose some path, then remove some edges so that this path still exists and the conditions hold. Note that if the conditions hold for some set of remaining edges, then we can remove any edge from it, and the conditions will still be met. Thus, we can only leave this path. Let's look closer into the conditions. What they actually tell is the following. If a vertex has incoming edges, then remove at least one of them. The same for the outgoing edges. Since we are looking for a path, it's enough to leave one outgoing edge for all vertices except the last one and leave one incoming edge for all vertices except the first one. In order to achieve that, every vertex except the last one should have at least two outgoing edges and every vertex except the first one should have at least two incoming edges. We can see that this condition is not only necessary, but sufficient as well. Just remove the outgoing edges which don't go to the next vertex and the incoming edges which don't go from the previous vertex. Now we can wrap this up into the dynamic programming. Initialize the answer with $1$, since you can always remove all edges, and get a set with one vertex. Then let $\\mathit{dp}_v$ be the longest path such that it starts in vertex $v$, all vertices in it have at least two incoming edges and all vertices except maybe the final one have at least two outgoing edges. Initialize the $\\mathit{dp}$ for the vertices that can be the final in the path (have at least two incoming edges) with $1$. Then update $\\mathit{dp}_v$ for all $v$ that can be internal vertices (have at least two outgoing and two incoming edges) with $\\mathit{dp}_u + 1$ for all outgoing edges $(v, u)$. Finally, update the answer from the vertices that can be the first one in the path. For each vertex $v$ that has at least two outgoing edges, take the value of $\\mathit{dp}_u + 1$ for all outgoing edges $(v, u)$. Overall complexity: $O(n + m)$.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nconst int INF = 1e9;\n \nvector<int> in, out;\nvector<vector<int>> g;\nvector<int> dp;\n \nint calc(int v){\n    if (dp[v] != -1) return dp[v];\n    if (in[v] >= 2 && out[v] >= 2){\n        dp[v] = 1;\n        for (int u : g[v])\n            dp[v] = max(dp[v], calc(u) + 1);\n    }\n    else if (in[v] >= 2){\n        dp[v] = 1;\n    }\n    else{\n        dp[v] = -INF;\n    }\n    return dp[v];\n}\n \nint main() {\n    int n, m;\n    scanf(\"%d%d\", &n, &m);\n    g.resize(n);\n    in.resize(n);\n    out.resize(n);\n    forn(i, m){\n        int v, u;\n        scanf(\"%d%d\", &v, &u);\n        --v, --u;\n        g[v].push_back(u);\n        ++in[u];\n        ++out[v];\n    }\n    int ans = 1;\n    dp.resize(n, -1);\n    forn(v, n) if (out[v] >= 2){\n        for (int u : g[v]){\n            ans = max(ans, calc(u) + 1);\n        }\n    }\n    printf(\"%d\\n\", ans);\n    return 0;\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1675",
    "index": "A",
    "title": "Food for Animals",
    "statement": "In the pet store on sale there are:\n\n- $a$ packs of dog food;\n- $b$ packs of cat food;\n- $c$ packs of universal food (such food is suitable for both dogs and cats).\n\nPolycarp has $x$ dogs and $y$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.",
    "tutorial": "Obviously, the best way to buy food for every pet is to buy maximum possible food for dogs and cats, then $max(0, x - a)$ dogs and $max(0, y - b)$ cats will not get food. We will buy universal food for these dogs and cats. Then the answer is YES, if $max(0, x - a) + max(0, y - b) \\le c$, and NO else.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int a, b, c, x, y;\n        cin >> a >> b >> c >> x >> y;\n        int ax = min(a, x);\n        int by = min(b, y);\n        a -= ax;\n        x -= ax;\n        b -= by;\n        y -= by;\n        if (c >= x + y)\n            cout << \"YES\" << endl;\n        else\n            cout << \"NO\" << endl;\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1675",
    "index": "B",
    "title": "Make It Increasing",
    "statement": "Given $n$ integers $a_1, a_2, \\dots, a_n$. You can perform the following operation on them:\n\n- select any element $a_i$ ($1 \\le i \\le n$) and divide it by $2$ (round down). In other words, you can replace any selected element $a_i$ with the value $\\left \\lfloor \\frac{a_i}{2}\\right\\rfloor$ (where $\\left \\lfloor x \\right\\rfloor$ is – round down the real number $x$).\n\nOutput the minimum number of operations that must be done for a sequence of integers to become strictly increasing (that is, for the condition $a_1 \\lt a_2 \\lt \\dots \\lt a_n$ to be satisfied). Or determine that it is impossible to obtain such a sequence. Note that elements \\textbf{cannot} be swapped. The only possible operation is described above.\n\nFor example, let $n = 3$ and a sequence of numbers $[3, 6, 5]$ be given. Then it is enough to perform two operations on it:\n\n- Write the number $\\left \\lfloor \\frac{6}{2}\\right\\rfloor = 3$ instead of the number $a_2=6$ and get the sequence $[3, 3, 5]$;\n- Then replace $a_1=3$ with $\\left \\lfloor \\frac{3}{2}\\right\\rfloor = 1$ and get the sequence $[1, 3, 5]$.\n\nThe resulting sequence is strictly increasing because $1 \\lt 3 \\lt 5$.",
    "tutorial": "We will process the elements of the sequence starting from the end of the sequence. Each element $a_i$ ($1 \\le i \\le n - 1$) will be divided by $2$ until it is less than $a_{i+1}$. If at some point it turns out that $a_{i + 1} = 0$, it is impossible to obtain the desired sequence.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int>a(n);\n    for(auto &i : a) cin >> i;\n    int ans = 0;\n    for(int i = n - 2; i >= 0; i--){\n        while(a[i] >= a[i + 1] && a[i] > 0){\n            a[i] /= 2;\n            ans++;\n        }\n        if(a[i] == a[i+1]){\n            cout << -1 << '\\n';\n            return;\n        }\n    }\n    cout << ans << '\\n';\n}\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1675",
    "index": "C",
    "title": "Detective Task",
    "statement": "Polycarp bought a new expensive painting and decided to show it to his $n$ friends. He hung it in his room. $n$ of his friends entered and exited there one by one. At one moment there was no more than one person in the room. In other words, the first friend entered and left first, then the second, and so on.\n\nIt is known that at the beginning (before visiting friends) a picture hung in the room. At the end (after the $n$-th friend) it turned out that it disappeared. At what exact moment it disappeared — there is no information.\n\nPolycarp asked his friends one by one. He asked each one if there was a picture when he entered the room. Each friend answered one of three:\n\n- no (response encoded with 0);\n- yes (response encoded as 1);\n- can't remember (response is encoded with ?).\n\nEveryone except the thief either doesn't remember or told the \\textbf{truth}. The thief can say anything (any of the three options).\n\nPolycarp cannot understand who the thief is. He asks you to find out the number of those who can be considered a thief according to the answers.",
    "tutorial": "First, let's note that we will have a transition from $1$ to $0$ only once, otherwise it turns out that first the picture disappeared, then it appeared and disappeared back, but we can consider that a friend in the middle, who answered $1$ lied to us, but this is not true, because even before him the picture disappeared. So we need to find this transition. Since we can also meet $?$, we find the index of the leftmost $0$ (in case of absence, we take $n - 1$) and mark it as $r_0$, and the index of rightmost $1$ (in case of absence, we take $0$) and mark as $l_1$. Answer - the number of indices between them (inclusive), because only they could lie. $r_0 - l_1 + 1$ There could not be a thief to the left of $l_1$, since either the friend under the index $l_1$ lied, or the picture was not stolen before $l_1$. There could not be a thief to the right of $r_0$, since either the painting had already been stolen in the presence of $r_0$'s friend, or it was he who lied.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        string s;\n        cin >> s;\n        int n = s.length();\n        vector<bool> a(n + 1);\n        a[0] = true;\n        forn(i, n)\n            a[i + 1] = a[i] && (s[i] == '1' || s[i] == '?');\n        vector<bool> b(n + 1);\n        b[0] = true;\n        for (int i = n - 1; i >= 0; i--)\n            b[n - i] = b[n - i - 1] && (s[i] == '0' || s[i] == '?');\n        int result = 0;\n        forn(i, n)\n            if (a[i] && b[n - i - 1])\n                result++;\n        cout << result << endl;\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1675",
    "index": "D",
    "title": "Vertical Paths",
    "statement": "You are given a rooted tree consisting of $n$ vertices. Vertices are numbered from $1$ to $n$. Any vertex can be the root of a tree.\n\nA tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.\n\nThe tree is specified by an array of parents $p$ containing $n$ numbers: $p_i$ is a parent of the vertex with the index $i$. The parent of a vertex $u$ is a vertex that is the next vertex on the shortest path from $u$ to the root. For example, on the simple path from $5$ to $3$ (the root), the next vertex would be $1$, so the parent of $5$ is $1$.\n\nThe root has no parent, so for it, the value of $p_i$ is $i$ (the root is the only vertex for which $p_i=i$).\n\nFind such a set of paths that:\n\n- each vertex belongs to exactly one path, each path can contain one or more vertices;\n- in each path each next vertex — is a son of the current vertex (that is, paths always lead down — from parent to son);\n- number of paths is \\textbf{minimal}.\n\nFor example, if $n=5$ and $p=[3, 1, 3, 3, 1]$, then the tree can be divided into three paths:\n\n- $3 \\rightarrow 1 \\rightarrow 5$ (path of $3$ vertices),\n- $4$ (path of $1$ vertices).\n- $2$ (path of $1$ vertices).\n\n\\begin{center}\n{\\small Example of splitting a root tree into three paths for $n=5$, the root of the tree — node $3$.}\n\\end{center}",
    "tutorial": "Let's find a set of leaves of a given tree. From each leaf we will climb up the tree until we meet a vertex already visited. Having met such a vertex, start a new path from the next leaf. The sequence of vertices in the found paths must be deduced in reverse order, because the paths must go from bottom to top. It also follows from this solution that the number of paths will always be equal to the number of leaves in the tree.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int>b(n + 1);\n    vector<bool>leaf(n + 1, true);\n    for(int i = 1; i <= n; i++) {\n        cin >> b[i];\n        leaf[b[i]] = false;\n    }\n\n    if(n == 1){\n        cout << \"1\\n1\\n1\\n\\n\";\n        return;\n    }\n\n    vector<int>paths[n + 1];\n    vector<bool>used(n + 1, false);\n    int color = 0;\n\n    for(int i = 1; i <= n; i++){\n        if(!leaf[i]) continue;\n        used[i] = true;\n        paths[color].emplace_back(i);\n\n        int v = i;\n        while (b[v] != v && !used[b[v]]){\n            v = b[v];\n            used[v] = true;\n            paths[color].emplace_back(v);\n        }\n        color++;\n    }\n\n    cout << color << '\\n';\n    for(auto &path : paths){\n        if(path.empty()) continue;\n        cout << (int)path.size() << '\\n';\n        reverse(path.begin(), path.end());\n        for(auto &v: path) cout << v << ' ';\n        cout << '\\n';\n    }\n    cout << '\\n';\n}\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1675",
    "index": "E",
    "title": "Replace With the Previous, Minimize",
    "statement": "You are given a string $s$ of lowercase Latin letters.\n\nThe following operation can be used:\n\n- select one character (from 'a' to 'z') that occurs at least once in the string. And replace all such characters in the string with the previous one in alphabetical order on the loop. For example, replace all 'c' with 'b' or replace all 'a' with 'z'.\n\nAnd you are given the integer $k$ — the maximum number of operations that can be performed. Find the minimum lexicographically possible string that can be obtained by performing no more than $k$ operations.\n\nThe string $a=a_1a_2 \\dots a_n$ is lexicographically smaller than the string $b = b_1b_2 \\dots b_n$ if there exists an index $k$ ($1 \\le k \\le n$) such that $a_1=b_1$, $a_2=b_2$, ..., $a_{k-1}=b_{k-1}$, but $a_k < b_k$.",
    "tutorial": "Greedy idea. To minimize the string, we will go from left to right and maintain a variable $mx$ = maximal character, from which we will reduce everything to 'a'. Initially it is 'a' and we spend $0$ of operations on it. Then, at the next symbol, we can either reduce it to 'a' in no more than $k$ operations, or reduce to 'a' the prefix we have already passed and minimize the next character in the remaining operations.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\ntemplate <class T> bool ckmax(T &a, T b) {return a<b ? a=b, true : false;}\n\n\nvoid solve() {\n    int n,k; cin >> n >> k;\n    string s; cin >> s;\n\n    char mn = 'a';\n    for (int i = 0; i < n; i++) if(s[i] > mn) {\n        if (s[i] - 'a' > k) {\n            k -= mn - 'a';\n            int to = s[i] - k;\n            for (char c = s[i]; c > to; c--) {\n                for (char &e:s) if (e == c) {\n                    e = char(c-1);\n                }\n            }\n            break;\n        } else ckmax(mn, s[i]);\n    }\n    for (char &e:s) if (e <= mn) {\n        e = 'a';\n    }\n    cout << s << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "dsu",
      "greedy",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1675",
    "index": "F",
    "title": "Vlad and Unfinished Business",
    "statement": "Vlad and Nastya live in a city consisting of $n$ houses and $n-1$ road. From each house, you can get to the other by moving only along the roads. That is, the city is a tree.\n\nVlad lives in a house with index $x$, and Nastya lives in a house with index $y$. Vlad decided to visit Nastya. However, he remembered that he had postponed for later $k$ things that he has to do before coming to Nastya. To do the $i$-th thing, he needs to come to the $a_i$-th house, things can be done in any order. In $1$ minute, he can walk from one house to another if they are connected by a road.\n\nVlad does not really like walking, so he is interested what is the minimum number of minutes he has to spend on the road to do all things and then come to Nastya. Houses $a_1, a_2, \\dots, a_k$ he can visit in any order. He can visit any house multiple times (if he wants).",
    "tutorial": "To begin with, we will hang the tree by the vertex $x$. In fact, we want to go from the root to the top of $y$, going off this path to do things and coming back. At one vertex of the path, it is advantageous to get off it in all the necessary directions and follow it further. So we will go $1$ once for each edge leading to $y$ and $2$ times for each edge leading to some of the cases, but not leading to $y$. Let's match each vertex with an edge to its ancestor. If the edge of a vertex leads to $y$, then $y$ is in the subtree of this vertex, similarly with vertices with cases. It is necessary for each vertex to determine whether there is a vertex $y$ in its subtree and whether there is a vertex from the array $a$, this can be done using a depth-first search, then we will calculate the answer according to the rules described above.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n//#define int long long\n#define ll long long\n//#define double long double\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\nconst int MOD = 1e9 + 7;\nconst int maxN = 5e3 + 1;\nconst int INF = 2e9;\nconst int MB = 20;\n\nvector<vector<int>> g;\nvector<bool> todo, good;\n\nvoid dfs(int v, int p = -1) {\n    for (int u : g[v]) {\n        if (u != p) {\n            dfs(u, v);\n            if (todo[u]) {\n                todo[v] = true;\n            }\n            if (good[u]) {\n                good[v] = true;\n            }\n        }\n    }\n}\n\nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    g.clear();\n    g.resize(n);\n    int x, y;\n    cin >> x >> y;\n    --x;\n    --y;\n    todo.resize(n);\n    fill(all(todo), false);\n    good.resize(n);\n    fill(all(good), false);\n    for (int i = 0; i < k; ++i) {\n        int v;\n        cin >> v;\n        --v;\n        todo[v] = true;\n    }\n    good[y] = true;\n    for (int i = 0; i < n - 1; ++i) {\n        int v, u;\n        cin >> v >> u;\n        --v;\n        --u;\n        g[v].push_back(u);\n        g[u].push_back(v);\n    }\n    dfs(x);\n    int ans = 0;\n    for (int i = 0; i < n; ++i) {\n        if (i == x) {\n            continue;\n        }\n        if (good[i]) {\n            ++ans;\n        } else if (todo[i]) {\n            ans += 2;\n        }\n    }\n    cout << ans << '\\n';\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    //    srand(time(0));\n    int t = 1;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1675",
    "index": "G",
    "title": "Sorting Pancakes",
    "statement": "Nastya baked $m$ pancakes and spread them on $n$ dishes. The dishes are in a row and numbered from left to right. She put $a_i$ pancakes on the dish with the index $i$.\n\nSeeing the dishes, Vlad decided to bring order to the stacks and move some pancakes. In one move, he can shift one pancake from any dish to the closest one, that is, select the dish $i$ ($a_i > 0$) and do one of the following:\n\n- if $i > 1$, put the pancake on a dish with the previous index, after this move $a_i = a_i - 1$ and $a_{i - 1} = a_{i - 1} + 1$;\n- if $i < n$, put the pancake on a dish with the following index, after this move $a_i = a_i - 1$ and $a_{i + 1} = a_{i + 1} + 1$.\n\nVlad wants to make the array $a$\\textbf{non-increasing}, after moving as few pancakes as possible. Help him find the minimum number of moves needed for this.\n\nThe array $a=[a_1, a_2,\\dots,a_n]$ is called non-increasing if $a_i \\ge a_{i+1}$ for all $i$ from $1$ to $n-1$.",
    "tutorial": "For convenience, we will calculate the prefix sums on the array $a$, we will also enter the array $b$ containing the indexes of all pancakes and calculate the prefix sums on it. Let's use dynamic programming. Let's define $dp[i][last][sum]$ as the required number of operations to correctly lay out the $i$-th prefix, with the final $a_i = last$, and $\\sum_{j = 1}^i a_j = sum$. Then you can go to $dp[i][last][sum]$ from $dp[i - 1][last + j][sum - last]$ (the previous number must be greater, and the sum is fixed). To $dp[i - 1][last + j][sum - last]$, it will be necessary to add a certain number of actions necessary to get $a_i = last$, let's call it $add$ (all the terrible prefix sums are needed to count it). Since $add$ depends only on $last$ and $sum$, we only need to choose the minimum $dp[i - 1][last + j][sum - last]$, the choice can be optimized by suffix minima. As a result, the solution works for $\\mathcal{O}(n*m^2)$, that's how many states need to be processed.",
    "code": "#include <bits/stdc++.h>\n\n//#define int long long\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(143);\n\nconst ll inf = 1e9 + 7;\nconst ll M = 998'244'353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-4;\n\nvoid solve(int test_case) {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n), pancakes(1);\n    for(int &e: a) cin >> e;\n    for(int i = 0; i < n; ++i){\n        for(int j = 0; j < a[i]; ++j){\n            pancakes.emplace_back(i);\n            int c = pancakes.size();\n            pancakes[c - 1] += pancakes[c - 2];\n        }\n        if(i > 0) a[i] += a[i - 1];\n    }\n    vector<vector<vector<int>>> dp(n, vector<vector<int>>(m + 1, vector<int>(m + 1, inf)));\n    for(int j = 0; j <= m; j++){\n        if(a[0] >= j) dp[0][j][j] = a[0] - j;//moved right\n        else dp[0][j][j] = pancakes[j];//moved from right\n    }\n    for(int j = m - 1; j >= 0; --j){\n        for(int k = j; k <= m; ++k){\n            dp[0][j][k] = min(dp[0][j][k], dp[0][j + 1][k]);\n        }\n    }\n    for(int i = 1; i < n; ++i){\n        for(int j = 0; j <= m; ++j){\n            for(int k = j; k <= m; ++k){\n                int add = 0;\n                if(a[i] >= k) add = a[i] - k;//moved to i + 1\n                else {\n                    int lend = min(j, k - a[i]);\n                    add = pancakes[k] - pancakes[k - lend] - i * (lend);//moved from greater i\n                }\n                dp[i][j][k] = dp[i - 1][j][k - j] + add;\n            }\n        }\n\n        for(int j = m - 1; j >= 0; --j){\n            for(int k = (i + 1) * j; k <= m; ++k){\n                dp[i][j][k] = min(dp[i][j][k], dp[i][j + 1][k]);\n            }\n        }\n    }\n    cout << dp[n-1][0][m];\n}\n\nbool multi = false;\n\nsigned main() {\n    int t = 1;\n    if (multi) {\n        cin >> t;\n    }\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1676",
    "index": "A",
    "title": "Lucky?",
    "statement": "A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.",
    "tutorial": "We need to check if the sum of the first three digits is equal to the sum of the last three digits. This is doable by scanning the input as a string, then comparing the sum of the first three characters with the sum of the last three characters using the if statement and the addition operation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tif(s[0]+s[1]+s[2] == s[3]+s[4]+s[5]) {\n\t\tcout << \"YES\" << endl;\n\t}\n\telse {\n\t\tcout << \"NO\" << endl;\n\t}\n}\n\nint main() {\n\tint t = 1;\n\tcin >> t;\n\twhile (t--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1676",
    "index": "B",
    "title": "Equal Candies",
    "statement": "There are $n$ boxes with different quantities of candies in each of them. The $i$-th box has $a_i$ candies inside.\n\nYou also have $n$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.\n\nWhat's the minimum total number of candies you have to eat to satisfy the requirements?",
    "tutorial": "Because we can only eat candies from boxes. The only way to make all boxes have the same quantity of candies in them would be to make all candies contain a number of candies equal to the minimum quantity of candies a box initially has. So, we should find this minimum number, let's denote it as $m$, and then for each box, there should be eaten $a_i - m$ candies. So the answer would be the sum of $a_i - m$ over all $i$-s ($1 \\leq i \\leq n$).",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nint main() {\n    int t; cin >> t;\n    while(t--) {\n        int n; cin >> n;\n        vector<int> a(n);\n        int mn = INT_MAX, ans = 0;\n        for(int i = 0; i < n; ++i) {\n            cin >> a[i];\n            mn = min(mn, a[i]);\n        }\n        for(int i = 0; i < n; ++i) {\n            ans += a[i] - mn;\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1676",
    "index": "C",
    "title": "Most Similar Words",
    "statement": "You are given $n$ words of \\textbf{equal} length $m$, consisting of lowercase Latin alphabet letters. The $i$-th word is denoted $s_i$.\n\nIn one move you can choose \\textbf{any position in any single word} and change the letter at that position to the previous or next letter in alphabetical order. For example:\n\n- you can change 'e' to 'd' or to 'f';\n- 'a' can only be changed to 'b';\n- 'z' can only be changed to 'y'.\n\nThe difference between two words is the \\textbf{minimum} number of moves required to make them equal. For example, the difference between \"best\" and \"cost\" is $1 + 10 + 0 + 0 = 11$.\n\nFind the minimum difference of $s_i$ and $s_j$ such that $(i < j)$. In other words, find the minimum difference over all possible pairs of the $n$ words.",
    "tutorial": "Firstly, given any pair of strings of length $m$, we should be able to tell the difference between them. It's enough to find the sum of absolute differences between each character from the same position. Now, we should go through all possible pairs and pick the minimum value over all of them using the function we use to calculate the difference.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nint cost(string& a, string& b) {\n    int val = 0;\n    for(int i = 0; i < a.size(); ++i) {\n        val += abs(a[i] - b[i]);\n    }\n    return val;\n}\n\nint main() {\n    int t; cin >> t;\n    while(t--) {\n        int n, m; cin >> n >> m;\n        vector<string> s(n);\n        for(int i = 0; i < n; ++i) {\n            cin >> s[i];\n        }\n        int ans = INT_MAX;\n        for(int i = 0; i < n; ++i) {\n            for(int j = i + 1; j < n; ++j) {\n                ans = min(ans, cost(s[i], s[j]));\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1676",
    "index": "D",
    "title": "X-Sum",
    "statement": "Timur's grandfather gifted him a chessboard to practice his chess skills. This chessboard is a grid $a$ with $n$ rows and $m$ columns with each cell having a \\textbf{non-negative} integer written on it.\n\nTimur's challenge is to place a bishop on the board such that the sum of all cells attacked by the bishop is \\textbf{maximal}. The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. Help him find the maximal sum he can get.",
    "tutorial": "The solution is to check the sum over all diagonals for each cell. For a cell ($i,j$) we can iterate over all elements in all its diagonals. This will be in total $O(max(n, m))$ elements. The complexity will be $O(n \\cdot m \\cdot max(n, m))$. $O(n \\cdot m)$ solutions involving precomputation are also possible but aren't needed.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n\tint n, m;\n\tcin >> n >> m;\n\tint a[n][m];\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j < m; j++)\n\t\t{\n\t\t\tcin >> a[i][j];\n\t\t}\n\t}\n\tint mx = 0;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j < m; j++)\n\t\t{\n\t\t\tint now = 0;\n\t\t\tint ci = i, cj = j;\n\t\t\twhile(ci >= 0 && ci < n && cj >= 0 && cj < m)\n\t\t\t{\n\t\t\t\tnow+=a[ci][cj];\n\t\t\t\tci--;\n\t\t\t\tcj--;\n\t\t\t}\n\t\t\tci = i, cj = j;\n\t\t\twhile(ci >= 0 && ci < n && cj >= 0 && cj < m)\n\t\t\t{\n\t\t\t\tnow+=a[ci][cj];\n\t\t\t\tci++;\n\t\t\t\tcj--;\n\t\t\t}\n\t\t\tci = i, cj = j;\n\t\t\twhile(ci >= 0 && ci < n && cj >= 0 && cj < m)\n\t\t\t{\n\t\t\t\tnow+=a[ci][cj];\n\t\t\t\tci--;\n\t\t\t\tcj++;\n\t\t\t}\n\t\t\tci = i, cj = j;\n\t\t\twhile(ci >= 0 && ci < n && cj >= 0 && cj < m)\n\t\t\t{\n\t\t\t\tnow+=a[ci][cj];\n\t\t\t\tci++;\n\t\t\t\tcj++;\n\t\t\t}\n\t\t\tnow-=a[i][j]*3;\n\t\t\tmx = max(mx, now);\n\t\t}\n\t}\n\tcout << mx << endl;\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tsolve();\n\t}\n}\n",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1676",
    "index": "E",
    "title": "Eating Queries",
    "statement": "Timur has $n$ candies. The $i$-th candy has a quantity of sugar equal to $a_i$. So, by eating the $i$-th candy, Timur consumes a quantity of sugar equal to $a_i$.\n\nTimur will ask you $q$ queries regarding his candies. For the $j$-th query you have to answer what is the \\textbf{minimum} number of candies he needs to eat in order to reach a quantity of sugar \\textbf{greater than or equal to} $x_j$ or print -1 if it's not possible to obtain such a quantity. In other words, you should print the minimum possible $k$ such that after eating $k$ candies, Timur consumes a quantity of sugar of at least $x_j$ or say that no possible $k$ exists.\n\nNote that he can't eat the same candy twice and queries are independent of each other (Timur can use the same candy in different queries).",
    "tutorial": "Let's solve the problem with just one query. Greedily, we should pick the candies with the most sugar first, since there is no benefit to picking a candy with less sugar. So the solution is as follows: sort the candies in descending order, and then find the prefix whose sum is $\\geq x$. This is $\\mathcal{O}(n)$ per query, which is too slow for us. To speed it up, notice that we just need to find a prefix sum at least $x$. So if we compute the prefix sums of the reverse-sorted array, we need to find the first element that is at least $x$. Since all elements of $a$ are positive, the array of prefix sums is increasing. Therefore, you can binary search the first element $\\geq x$. This solves the problem in $\\log n$ per query. Total time complexity: $\\mathcal{O}(q \\log n + n)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nint main() {  \n    int t; cin >> t;\n    while(t--) {\n        int n, q; cin >> n >> q;\n        vector<long long> a(n), p(n);\n        for(int i = 0; i < n; ++i) {\n            cin >> a[i];\n        }\n        sort(a.rbegin(), a.rend());\n        for(int i = 0; i < n; ++i) {\n            p[i] = (i ? p[i - 1] : 0) + a[i];\n        }\n    \n        while(q--) {\n            long long x; cin >> x;\n            int l = 1, r = n, ans = -1;\n            while(l <= r) {\n                int mid = (l + r) / 2;\n                if(p[mid - 1] >= x) {\n                    ans = mid;\n                    r = mid - 1;\n                } else {\n                    l = mid + 1;\n                }\n            }\n            cout << ans << \"\\n\";\n        }\n    }\n}   ",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1676",
    "index": "F",
    "title": "Longest Strike",
    "statement": "Given an array $a$ of length $n$ and an integer $k$, you are tasked to find any two numbers $l$ and $r$ ($l \\leq r$) such that:\n\n- For each $x$ $(l \\leq x \\leq r)$, $x$ appears in $a$ at least $k$ times (i.e. $k$ or more array elements are equal to $x$).\n- The value $r-l$ is maximized.\n\nIf no numbers satisfy the conditions, output -1.\n\nFor example, if $a=[11, 11, 12, 13, 13, 14, 14]$ and $k=2$, then:\n\n- for $l=12$, $r=14$ the first condition fails because $12$ does not appear at least $k=2$ times.\n- for $l=13$, $r=14$ the first condition holds, because $13$ occurs at least $k=2$ times in $a$ and $14$ occurs at least $k=2$ times in $a$.\n- for $l=11$, $r=11$ the first condition holds, because $11$ occurs at least $k=2$ times in $a$.\n\nA pair of $l$ and $r$ for which the first condition holds and $r-l$ is maximal is $l = 13$, $r = 14$.",
    "tutorial": "Let's call a value good if it appears at least $k$ times. For example, if $a=[1,1,2,2,3,4,4,4,5,5,6,6]$ and $k=2$, then good values are $[1,2,4,5,6]$. So we need to find the longest subarray of this array in which all values are consecutive. For example, the subarray $[4,5,6]$ is the answer, because all values are good and the length of the array is longest. There are many ways to do this. For example, we can see when the difference between two elements is more than $1$, and then break the array into parts based on that. For instance, $[1,2,4,5,6] \\to [1,2], [4,5,6]$. You can also iterate from left to right and keep track of the size of the current array. Time complexity: $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tint a[n];\n\tmap<int, int> mp;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tcin >> a[i];\n\t\tmp[a[i]]++;\n\t}\n\tvector<int> c;\n\tfor(auto x : mp)\n\t{\n\t\tif(x.second >= k)\n\t\t{\n\t\t\tc.push_back(x.first);\n\t\t}\n\t}\n\tif(c.size() == 0)\n\t{\n\t\tcout << -1 << endl;\n\t\treturn;\n\t}\n\tsort(c.begin(), c.end());\n\tint mx = 0;\n\tint lans = c[0], rans = c[0];\n\tint l = c[0];\n\tfor(int i = 1; i < c.size(); i++)\n\t{\n\t\tif(c[i]-1 == c[i-1])\n\t\t{\n\t\t\tif(c[i]-l > mx)\n\t\t\t{\n\t\t\t\tlans = l;\n\t\t\t\trans = c[i];\n\t\t\t\tmx = c[i]-l;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tl = c[i];\n\t\t}\n\t}\n\tcout << lans << \" \" << rans << endl;\n}\n\nint main(int argc, char * argv[])\n{\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tsolve();\n\t}\n}\n",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1676",
    "index": "G",
    "title": "White-Black Balanced Subtrees",
    "statement": "You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root is vertex $1$. There is also a string $s$ denoting the color of each vertex: if $s_i = B$, then vertex $i$ is black, and if $s_i = W$, then vertex $i$ is white.\n\nA subtree of the tree is called balanced if the number of white vertices equals the number of black vertices. Count the number of balanced subtrees.\n\nA tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. In this problem, all trees have root $1$.\n\nThe tree is specified by an array of parents $a_2, \\dots, a_n$ containing $n-1$ numbers: $a_i$ is the parent of the vertex with the number $i$ for all $i = 2, \\dots, n$. The parent of a vertex $u$ is a vertex that is the next vertex on a simple path from $u$ to the root.\n\nThe subtree of a vertex $u$ is the set of all vertices that pass through $u$ on a simple path to the root. For example, in the picture below, $7$ is in the subtree of $3$ because the simple path $7 \\to 5 \\to 3 \\to 1$ passes through $3$. Note that a vertex is included in its subtree, and the subtree of the root is the entire tree.\n\n\\begin{center}\nThe picture shows the tree for $n=7$, $a=[1,1,2,3,3,5]$, and $s=WBBWWBW$. The subtree at the vertex $3$ is balanced.\n\\end{center}",
    "tutorial": "Let's run a dynamic programming from the leaves to the root. For each vertex store the values of the number of balanced subtrees, as well as the number of white and black vertices in it. Then from a vertex we can count the total number of white vertices in its subtree as well as the black vertices in its subtree, and update our total if they are equal. Remember to include the color of the vertex itself in these counts. The answer is the answer at the root. Therefore the problem is solved in $\\mathcal{O}(n)$ time.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> child[n + 7];\n\tfor (int i = 2; i <= n; i++) {\n\t\tint x;\n\t\tcin >> x;\n\t\tchild[x].push_back(i);\n\t}\n\tstring s;\n\tcin >> s;\n\tint res = 0;\n\tfunction<int(int)> dp = [&] (int x) {\n\t\tint bal = (s[x - 1] == 'B') ? -1 : 1;\n\t\tif (child[x].empty()) {return bal;}\n\t\tfor (int i : child[x]) {\n\t\t\tbal += dp(i);\n\t\t}\n\t\tif (bal == 0) {res++;}\n\t\treturn bal;\n\t};\n\tdp(1);\n\tcout << res << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1676",
    "index": "H1",
    "title": "Maximum Crossings (Easy Version)",
    "statement": "The only difference between the two versions is that in this version $n \\leq 1000$ and the sum of $n$ over all test cases does not exceed $1000$.\n\nA terminal is a row of $n$ equal segments numbered $1$ to $n$ in order. There are two terminals, one above the other.\n\nYou are given an array $a$ of length $n$. For all $i = 1, 2, \\dots, n$, there should be a straight wire from some point on segment $i$ of the top terminal to some point on segment $a_i$ of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if $n=7$ and $a=[4,1,4,6,7,7,5]$.\n\nA crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.\n\nWhat is the \\textbf{maximum} number of crossings there can be if you place the wires optimally?",
    "tutorial": "Let's look at two wires from $i \\to a_i$ and $j \\to a_j$. If $a_i < a_j$, there can never be any intersection. If $a_i > a_j$, there has to be an intersection. If $a_i = a_j$, it is possible that there is an intersection or not, depending on how we arrange the wires on the bottom terminal. Since we want to maximize the number of intersections, we just need to count the number of pairs $(i,j)$ such that $a_i \\geq a_j$. You can brute force all pairs in $\\mathcal{O}(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tint a[n];\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\tint res = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\tif (a[i] >= a[j]) {res++;}\n\t\t}\n\t}\n\tcout << res << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "brute force"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1676",
    "index": "H2",
    "title": "Maximum Crossings (Hard Version)",
    "statement": "The only difference between the two versions is that in this version $n \\leq 2 \\cdot 10^5$ and the sum of $n$ over all test cases does not exceed $2 \\cdot 10^5$.\n\nA terminal is a row of $n$ equal segments numbered $1$ to $n$ in order. There are two terminals, one above the other.\n\nYou are given an array $a$ of length $n$. For all $i = 1, 2, \\dots, n$, there should be a straight wire from some point on segment $i$ of the top terminal to some point on segment $a_i$ of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if $n=7$ and $a=[4,1,4,6,7,7,5]$.\n\nA crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.\n\nWhat is the \\textbf{maximum} number of crossings there can be if you place the wires optimally?",
    "tutorial": "Read the solution of the easy version. We want to count the number of pairs $(i,j)$ such that $i<j$ and $a_i \\geq a_j$. This is a standard problem, and we can do this we can use a segment tree or BIT, for example. Insert the $a_j$ from $j=1$ to $n$, and then for each $a_j$ count the number of $a_i \\leq a_j$ using a BIT. It is also related to the problem of counting inversions, so you can solve it using a modification of merge sort. Either way, the solution is $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nlong long merge(int a[], int temp[], int left, int mid, int right) {\n   int i, j, k;\n   long long count = 0;\n   i = left;\n   j = mid;\n   k = left;\n   while ((i <= mid - 1) && (j <= right)) {\n      if (a[i] <= a[j]){\n      temp[k++] = a[i++];\n      } else {\n         temp[k++] = a[j++];\n         count += (mid - i);\n      }\n   }\n   while (i <= mid - 1)\n      temp[k++] = a[i++];\n   while (j <= right)\n      temp[k++] = a[j++];\n   for (i=left; i <= right; i++)\n      a[i] = temp[i];\n   return count;\n}\nlong long mergeSort(int a[], int temp[], int left, int right){\n   int mid;\n   long long count = 0;\n   if (right > left) {\n      mid = (right + left)/2;\n      count = mergeSort(a, temp, left, mid);\n      count += mergeSort(a, temp, mid+1, right);\n      count += merge(a, temp, left, mid+1, right);\n   }\n   return count;\n}\nlong long aInversion(int a[], int n) {\n   int temp[n];\n   return mergeSort(a, temp, 0, n - 1);\n}\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tint a[n];\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\tlong long res = aInversion(a, n);\n\tsort(a, a + n);\n\tlong long curr = 1;\n\tfor (int i = 1; i < n; i++) {\n\t    if (a[i] != a[i - 1]) {res += (curr * (curr - 1)) / 2; curr = 1;}\n\t    else {curr++;}\n\t}\n\tres += (curr * (curr - 1)) / 2;\n\tcout << res << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1677",
    "index": "A",
    "title": "Tokitsukaze and Strange Inequality",
    "statement": "Tokitsukaze has a permutation $p$ of length $n$. Recall that a permutation $p$ of length $n$ is a sequence $p_1, p_2, \\ldots, p_n$ consisting of $n$ distinct integers, each of which from $1$ to $n$ ($1 \\leq p_i \\leq n$).\n\nShe wants to know how many different indices tuples $[a,b,c,d]$ ($1 \\leq a < b < c < d \\leq n$) in this permutation satisfy the following two inequalities:\n\n\\begin{center}\n$p_a < p_c$ and $p_b > p_d$.\n\\end{center}\n\nNote that two tuples $[a_1,b_1,c_1,d_1]$ and $[a_2,b_2,c_2,d_2]$ are considered to be different if $a_1 \\ne a_2$ or $b_1 \\ne b_2$ or $c_1 \\ne c_2$ or $d_1 \\ne d_2$.",
    "tutorial": "We can calculate the answer in two steps. The first step, for each $b$, let $f_b$ represents the number of $p_d$ where $p_b > p_d$ in the interval $[b+1,n]$. We can calculate $f$ in $\\mathcal{O}(n^2)$. The second step, calculate the answer. First we enumerate $c$ from $1$ to $n$, and then enumerate $a$ from $1$ to $c-1$. When $p_a < p_c$, add $f_b$ in the interval $[a+1,c-1]$ to the answer. Before enumerating $a$, we can calculate the prefix sum of $f$ first, so we can add the $f_b$ in the interval to the answer in $\\mathcal{O}(1)$. The time complexity of this step is $\\mathcal{O}(n^2)$. However, this will add the result of $d$ in the interval $[a+1,c-1]$ to the answer, which is illegal because $c < d$ is required. So we need to maintain $f$ while enumerating $c$: enumerate $b$ from $1$ to $c-1$, if $p_b > p_c$, $f_b$ minus $1$. $p_c$ is actually regarded as $p_d$, that is, subtract the case where $c$ is equal to $d$, so as to subtract the illegal case. The time complexity of this step is also $\\mathcal{O}(n^2)$. Time complexity:$\\mathcal{O}(n^2)$. By the way, use Fenwick Tree or Segment Tree can also pass, the time complexity is $\\mathcal{O}(n^2 log\\ n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n/************* debug begin *************/\nstring to_string(string s){return '\"'+s+'\"';}\nstring to_string(const char* s){return to_string((string)s);}\nstring to_string(const bool& b){return(b?\"true\":\"false\");}\ntemplate<class T>string to_string(T x){ostringstream sout;sout<<x;return sout.str();}\ntemplate<class A,class B>string to_string(pair<A,B> p){return \"(\"+to_string(p.first)+\", \"+to_string(p.second)+\")\";}\ntemplate<class A>string to_string(const vector<A> v){\n\tint f=1;string res=\"{\";for(const auto x:v){if(!f)res+= \", \";f=0;res+=to_string(x);}res+=\"}\";\n\treturn res;\n}\nvoid debug_out(){puts(\"\");}\ntemplate<class T,class... U>void debug_out(const T& h,const U&... t){cout<<\" \"<<to_string(h);debug_out(t...);}\n#ifdef tokitsukaze \n#define debug(...) cout<<\"[\"<<#__VA_ARGS__<<\"]:\",debug_out(__VA_ARGS__);\n#else\n#define debug(...) 233;\n#endif\n/*************  debug end  *************/\n#define mem(a,b) memset((a),(b),sizeof(a))\n#define MP make_pair\n#define pb push_back\n#define fi first\n#define se second\n#define sz(x) (int)x.size()\n#define all(x) x.begin(),x.end()\n#define sqr(x) (x)*(x)\nusing namespace __gnu_cxx;\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef pair<int,int> PII;\ntypedef pair<ll,ll> PLL;\ntypedef pair<int,ll> PIL;\ntypedef pair<ll,int> PLI;\ntypedef vector<int> VI;\ntypedef vector<ll> VL;\ntypedef vector<PII > VPII;\n/************* define end  *************/\nvoid println(VI x){for(int i=0;i<sz(x);i++) printf(\"%d%c\",x[i],\" \\n\"[i==sz(x)-1]);}\nvoid println(VL x){for(int i=0;i<sz(x);i++) printf(\"%lld%c\",x[i],\" \\n\"[i==sz(x)-1]);}\nvoid println(int *x,int l,int r){for(int i=l;i<=r;i++) printf(\"%d%c\",x[i],\" \\n\"[i==r]);}\nvoid println(ll *x,int l,int r){for(int i=l;i<=r;i++) printf(\"%lld%c\",x[i],\" \\n\"[i==r]);}\n/*************** IO end  ***************/\nvoid go();\nint main(){\n\t#ifdef tokitsukaze\n\t\tfreopen(\"TEST.txt\",\"r\",stdin);\n\t#endif\n\tgo();return 0;\n}\nconst int INF=0x3f3f3f3f;\nconst ll LLINF=0x3f3f3f3f3f3f3f3fLL;\nconst double PI=acos(-1.0);\nconst double eps=1e-6;\nconst int MAX=1e5+10;\nconst ll mod=998244353;\n/*********************************  head  *********************************/\nint a[MAX];\nll f[MAX],bitf[MAX];\nvoid go()\n{\n\tint n,i,j,k,l,T;\n\tll ans;\n\tscanf(\"%d\",&T);\n\twhile(T--)\n\t{\n\t    scanf(\"%d\",&n);\n\t\tfor(i=1;i<=n;i++) scanf(\"%d\",&a[i]);\n\t\tmem(f,0);\n\t\tfor(j=1;j<=n;j++)\n\t\t{\n\t\t\tfor(l=j+1;l<=n;l++)\n\t\t\t{\n\t\t\t\tif(a[j]>a[l]) f[j]++;\n\t\t\t}\n\t\t}\n\t\tans=0;\n\t\tfor(k=1;k<=n;k++)\n\t\t{\n\t\t\tfor(j=1;j<k;j++)\n\t\t\t{\n\t\t\t\tif(a[j]>a[k]) f[j]--;\n\t\t\t}\n\t\t\tbitf[0]=0;\n\t\t\tfor(i=1;i<=k;i++) bitf[i]=bitf[i-1]+f[i];\n\t\t\tfor(i=1;i<k;i++)\n\t\t\t{\n\t\t\t\tif(a[i]<a[k]) ans+=bitf[k-1]-bitf[i];\n\t\t\t}\n\t\t}\n\t\tprintf(\"%lld\\n\",ans);\n\t}\n}\n\n",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1677",
    "index": "B",
    "title": "Tokitsukaze and Meeting",
    "statement": "Tokitsukaze is arranging a meeting. There are $n$ rows and $m$ columns of seats in the meeting hall.\n\nThere are exactly $n \\cdot m$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $1$ to $n\\cdot m$. The students will enter the meeting hall in order. When the $i$-th student enters the meeting hall, he will sit in the $1$-st column of the $1$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $j$-th ($1\\leq j \\leq m-1$) column of the $i$-th row will move to the $(j+1)$-th column of the $i$-th row, and the student sitting in $m$-th column of the $i$-th row will move to the $1$-st column of the $(i+1)$-th row.\n\nFor example, there is a meeting hall with $2$ rows and $2$ columns of seats shown as below:\n\nThere will be $4$ students entering the meeting hall in order, represented as a binary string \"1100\", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows:\n\nDenote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $i$-th student enters the meeting hall, for all $i$.",
    "tutorial": "Obviously, we can calculate the answers of rows and columns separately. For the answers of columns, we can observe that since there are only $n \\cdot m$ students in total, no students will leave, and every time a new student entering the meeting hall, all columns will move one step to the right circularly, so the answer will not decrease. If the $i$-th student is a serious student, for all the previous students with subscript $j$ where $0 < j < i$, and $j \\% m = i \\% m$ are naughty students, the answer in the column will increase by $1$. For the answer of rows, we can transfer it from the answer of $i-m$, which is equivalent to adding a new row to the answer of $i-m$. Suppose the last serious student is the $j$-th student. If $i-j<m$, the answer will increase by $1$, otherwise the answer will be the same as that of when the $i-m$ student enters the meeting hall.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint rownum[1000100];\nint col[1000100];\nint n,m;\nvoid init(){\n\tfor(int i = 0;i <= max(n,m);i++) {\n\t\trownum[i] = col[i] = 0;\n\t}\n}\nvoid solve(){\n\tscanf(\"%d%d\",&n,&m);\n\tinit();\n\tint las = -n*m;\n\tint colnum = 0;\n\tchar tmp;\n\tfor(int i = 0;i < n*m;i++) {\n\t\tscanf(\" %c\",&tmp);\n\t\ttmp -= '0';\n\t\tif(tmp == 1) {\n\t\t\tlas = i;\n\t\t\tif(col[i%m] == 0) {\n\t\t\t\tcol[i%m] = 1;\n\t\t\t\tcolnum++;\n\t\t\t}\n\t\t}\n\t\tif(i - las < m) {\n\t\t\trownum[i%m]++;\n\t\t}\n\t\tif(i!=0) printf(\" \");\n\t\tprintf(\"%d\",rownum[i%m] + colnum);\n\t\t\n\t}\n\tprintf(\"\\n\");\n}\nint main(){\n\tint T;\n\tscanf(\"%d\",&T);\n\twhile(T--) {\n\t\tsolve();\n\t}\n} ",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1677",
    "index": "C",
    "title": "Tokitsukaze and Two Colorful Tapes",
    "statement": "Tokitsukaze has two colorful tapes. There are $n$ distinct colors, numbered $1$ through $n$, and each color appears exactly once on each of the two tapes. Denote the color of the $i$-th position of the first tape as $ca_i$, and the color of the $i$-th position of the second tape as $cb_i$.\n\nNow Tokitsukaze wants to select each color an integer value from $1$ to $n$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $i$-th position of the first tape as $numa_i$, and the number of the $i$-th position of the second tape as $numb_i$.\n\nFor example, for the above picture, assuming that the color red has value $x$ ($1 \\leq x \\leq n$), it appears at the $1$-st position of the first tape and the $3$-rd position of the second tape, so $numa_1=numb_3=x$.\n\nNote that each color $i$ from $1$ to $n$ should have a \\textbf{distinct} value, and the same color which appears in both tapes has the same value.\n\nAfter labeling each color, the beauty of the two tapes is calculated as $$\\sum_{i=1}^{n}|numa_i-numb_i|.$$\n\nPlease help Tokitsukaze to find the highest possible beauty.",
    "tutorial": "First, find the cycle directly, take out all the cycles, and then fill each cycle in the order: maximum, minimum, maximum, minimum $\\ldots$. Note that when you encounter an odd cycle, the last one should be empty and fill in the middle value. For example, in a ternary cycle, if the first and the second position are filled with $1$ and $9$, it can be observed that the contribution of the ternary cycle to the answer remains unchanged no matter which number between $2 \\sim 8$ is filled in the middle. So this situation can be left out first, and finally fill in whatever number is left. The same to the cycles with odd sizes such as self cycles and five membered cycles, because the last number does not provide any contribution. In this way, you can directly construct a solution with the maximum $score$. We notice that if we take out the numbers that has already been filled in each cycle and put them into a new cycled array $h$, in fact, the numbers providing contribution are only at the \"peak\" and \"valley\" points of the array. We define \"peak\" as the point with subscript $i$ where $h_{i}>h_{i-1}$ and $h_{i}>h_{i+1}$, and \"valley\" is the point with subscript $i$ where $h_{i}<h_{i-1}$ and $h_{i}<h_{i+1}$. Obviously, each \"peak\" will provide contribution of $2 \\cdot h_{i}$, each \"valley\" will provide contribution of $-2 \\cdot h_{i}$. For the points which are neither \"peak\"s nor \"valley\"s, they do not provide any contribution. In order to maximize the score, we make the larger number in the permutation \"peak\" and the smaller number \"valley\". There are $\\left \\lfloor \\frac{CircleSize}{2} \\right \\rfloor$ \"peak\"s and \"valley\"s for a circle with a length of $Circlesize$. So the expression of the final answer can be derived from the summation formula of the arithmetic sequence: Let $c=\\sum \\left \\lfloor \\frac{CircleSize}{2} \\right \\rfloor$, $N$ represents the size of the permutation, $score=2c \\cdot (N-c)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAXN = 100005;\nint n,col[2][MAXN],col_to_pos_1[MAXN];\nlong long output;\nbool vis_0[MAXN];\nint T,cnt;\nlong long c;\nvoid dfs(int pos)\n{\n\tif(vis_0[pos])return;\n\tvis_0[pos]=true;\n\t++cnt;\n\tdfs(col_to_pos_1[col[0][pos]]);\n}\nint main(int argc, char const *argv[])\n{\n\tscanf(\"%d\",&T);\n\twhile(T--)\n\t{\n\t\tscanf(\"%d\",&n);\n\t\tfor(int i=1;i<=n;++i)\n\t\t{\n\t\t\tvis_0[i]=false;\n\t\t}\n\t\tfor(int i=1;i<=n;++i)\n\t\t{\n\t\t\tscanf(\"%d\",&col[0][i]);\n\t\t}\n\t\tfor(int i=1;i<=n;++i)\n\t\t{\n\t\t\tscanf(\"%d\",&col[1][i]);\n\t\t\tcol_to_pos_1[col[1][i]]=i;\n\t\t}\n\t\tc=0;\n\t\tfor(int i=1;i<=n;++i)\n\t\t{\n\t\t\tcnt=0;\n\t\t\tdfs(i);\n\t\t\tc+=cnt/2;\n\t\t}\n\t\tprintf(\"%lld\\n\", (c*(n-c))<<1);\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1677",
    "index": "D",
    "title": "Tokitsukaze and Permutations",
    "statement": "Tokitsukaze has a permutation $p$. She performed the following operation to $p$ \\textbf{exactly} $k$ times: in one operation, for each $i$ from $1$ to $n - 1$ in order, if $p_i$ > $p_{i+1}$, swap $p_i$, $p_{i+1}$. After exactly $k$ times of operations, Tokitsukaze got a new sequence $a$, obviously the sequence $a$ is also a permutation.\n\nAfter that, Tokitsukaze wrote down the value sequence $v$ of $a$ on paper. Denote the value sequence $v$ of the permutation $a$ of length $n$ as $v_i=\\sum_{j=1}^{i-1}[a_i < a_j]$, where the value of $[a_i < a_j]$ define as if $a_i < a_j$, the value is $1$, otherwise is $0$ (in other words, $v_i$ is equal to the number of elements greater than $a_i$ that are to the left of position $i$). Then Tokitsukaze went out to work.\n\nThere are three naughty cats in Tokitsukaze's house. When she came home, she found the paper with the value sequence $v$ to be bitten out by the cats, leaving several holes, so that the value of some positions could not be seen clearly. She forgot what the original permutation $p$ was. She wants to know how many different permutations $p$ there are, so that the value sequence $v$ of the new permutation $a$ after \\textbf{exactly} $k$ operations is the same as the $v$ written on the paper (not taking into account the unclear positions).\n\nSince the answer may be too large, print it modulo $998\\,244\\,353$.",
    "tutorial": "Consider finding out the relationship between sequence $v$ and permutation $p$. It can be observed that the permutation $p$ have bijective relationship with sequence $c$. That is to say, sequence $c$ will only correspond to one permutation $p$, as it can be proved: Let $S={1,2,\\ldots,n}$, and find that the last number can be determined through $c_n$, because there is no number after this position. We observe that $p_n$ is the $(c_n+1)$ largest number in $S$, then delete $p_n$ from $S$, we can get $p_{n - 1}$. So repeat the process, we can get the whole permutation. Consider counting $v$, we observe that each bubble sort will first make $v_i=\\max(v_{i}-1,0)$, then the whole $v$ moves left, $v_1$ is directly covered, $v_n$ is set to $0$. Because each valued $v_i$ is preceded by a number larger than the current position, then it will definitely be exchanged and moved forward, $v_i$ minus $1$. For example, if the current $v=[0,0,2,1,1]$, after once bubble sort, $v=[0,1,0,0,0]$. To avoid confusion, the $V$ array below is the $v$ in the input. It's easy to count after knowing the above conclusion. For the position $i(i\\le k)$, it can be observed that after $k$ times of bubble sort , it is directly covered, so just multiply the answer by $\\prod_{i=1}^k i$. For the position $i(k\\lt i \\le n)$, if $V_{i-k}\\ne -1$, then obviously $v_i$ is uniquely determined; If $V_{i-k}=-1$, then $v_i$ has $i$ possible values, multiply the answer by $i$; If $V_{i-k}=0$, then $v_i-k\\le 0$, multiply the answer by $k+1$. Note that for the position $i(i\\ge n-k+1)$, $V_i$ should be $0$ or $-1$, otherwise the answer must be $0$. Complexity:$\\mathcal{O}(n)$.",
    "code": "#include<cstdio>\n#include<iostream>\n#include<cstring>\n#include<algorithm>\n#include<queue>\n#include<map>\n#include<ctime>\n#include<cmath>\n#include<unordered_map> \nusing namespace std;\n#define LL long long\n#define pp pair<int,pair<int,int>>\n#define mp make_pair \n#define fi first\n#define se second.first\n#define th second.second\nnamespace IO{\n\tconst int sz=1<<22;\n\tchar a[sz+5],b[sz+5],*p1=a,*p2=a,*t=b,p[105];\n\tinline char gc(){\n\t\treturn p1==p2?(p2=(p1=a)+fread(a,1,sz,stdin),p1==p2?EOF:*p1++):*p1++;\n\t}\n\ttemplate<class T> void gi(T& x){\n\t\tx=0; int f=1;char c=gc();\n\t\tif(c=='-')f=-1;\n\t\tfor(;c<'0'||c>'9';c=gc())if(c=='-')f=-1;\n\t\tfor(;c>='0'&&c<='9';c=gc())\n\t\t\tx=x*10+(c-'0');\n\t\tx=x*f;\n\t}\n\tinline void flush(){fwrite(b,1,t-b,stdout),t=b; }\n\tinline void pc(char x){*t++=x; if(t-b==sz) flush(); }\n\ttemplate<class T> void pi(T x,char c='\\n'){\n\t\tif(x==0) pc('0'); int t=0;\n\t\tfor(;x;x/=10) p[++t]=x%10+'0';\n\t\tfor(;t;--t) pc(p[t]); pc(c);\n\t}\n\tstruct F{~F(){flush();}}f; \n}\nusing IO::gi;\nusing IO::pi;\nusing IO::pc;\nint t,n,a[1000005],ans,k;\nconst int mod=998244353;\nsigned main(){\n\tsrand(time(0));\n\tgi(t);\n\twhile(t--){\n\t\tgi(n),gi(k);\n\t\tbool f=0;\n\t\tfor(int i=1;i<=n;i++)gi(a[i]),f|=(a[i]>i-1);\n\t\tif(f){\n\t\t\tpi(0,'\\n');\n\t\t\tcontinue;\n\t\t}\n\t\tans=1;\n\t\tfor(int i=1;i<=k;i++)ans=1ll*ans*i%mod;\n\t\tfor(int i=n-k+1;i<=n;i++){\n\t\t\tif(a[i]!=-1&&a[i]){\n\t\t\t\tpi(0,'\\n');\n\t\t\t\tf=1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(f)continue;\n\t\tfor(int i=k+1;i<=n;i++){\n\t\t\tint limit=i-1;\n\t\t\tif(a[i-k]==-1){\n\t\t\t\tans=1ll*ans*i%mod;\n\t\t\t}else{\n\t\t\t\tif(a[i-k]){\n\t\t\t\t\tlimit=a[i-k]+k;\n\t\t\t\t\tif(limit>i-1)f=1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlimit=min(limit,k),ans=1ll*ans*(limit+1)%mod; \n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\tif(f)ans=0;\n\t\tpi(ans,'\\n');\n\t} \n\treturn 0;\n}",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1677",
    "index": "E",
    "title": "Tokitsukaze and Beautiful Subsegments",
    "statement": "Tokitsukaze has a permutation $p$ of length $n$.\n\nLet's call a segment $[l,r]$ beautiful if there exist $i$ and $j$ satisfying $p_i \\cdot p_j = \\max\\{p_l, p_{l+1}, \\ldots, p_r \\}$, where $l \\leq i < j \\leq r$.\n\nNow Tokitsukaze has $q$ queries, in the $i$-th query she wants to know how many beautiful subsegments $[x,y]$ there are in the segment $[l_i,r_i]$ (i. e. $l_i \\leq x \\leq y \\leq r_i$).",
    "tutorial": "Let's sort the queries $[l,r]$ with $r$ in ascending order. Let's move $R$ from $1$ to $n$, and answer queries $[l,r]$ when $r=R$. Use segment tree to solve this problem, each leaf node $[ul,ul]$ in the segment tree maintenance the number that how many intervals $[ul,R]$ are beautiful, then answering queries is to get sum. Use monotone stack to maintain the maximum number. When moving $R$ one step right, the monotone stack will pop some and push one. Let's think about the number $x$ in monotone stack, which means the maximum number of the intervals $[lp,R]$ ($l1 \\le lp \\le l2$) is $x$. If there exist a $ll$ in $[l1,l2]$ which satisfies $a_{ll}*a_R=x$, then before $x$ is poped, intervals $[l,rr]$ are beautiful($l \\in [l1,l2]$,$l \\le ll$ ,$R \\le rr$). So we can assume that $x$ will not be poped when it is pushed in the monotone stack, and do something like difference algorithm in the segment tree, by using the current $R$ as the time stamp. Each node in the segment tree has to maintain $a*R+b$,which like a linear function. So when moving $R$ right step, let's enumerate the factor of $a_R$ to update old intervals in monotone stack, enumerate the multiple of $a_R$ to update the new interval in monotone stack and update the intervals which are poped. Time complexity: $\\mathcal{O}(nlognlogn+qlogn)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N=2e5+5;\ntypedef pair<int,int> pp;\nint n,m,ti,top,a[N],d[N],p[N],bz[N],bo[N];\nlong long ans[1000005];\nvector<pp>q[1000005];\nvector<int>w[N];\nstruct dd\n{\n\tlong long x,y,tg,len;\n}tr[N*4];\nvoid make(int x,int l,int r)\n{\n\ttr[x].len=r-l+1;\n\tif (l==r) return;\n\tint mid=l+r>>1;\n\tmake(x<<1,l,mid),make(x<<1|1,mid+1,r);\n}\nvoid down(int x)\n{\n\tif (tr[x].x==tr[x].len)\n\t{\n\t\ttr[x<<1].x=tr[x<<1].len;\n\t\ttr[x<<1|1].x=tr[x<<1|1].len;\n\t}\n\tif (tr[x].x==0)\n\t{\n\t\ttr[x<<1].x=0;\n\t\ttr[x<<1|1].x=0;\n\t}\n\ttr[x<<1].tg+=tr[x].tg;\n\ttr[x<<1].y+=tr[x].tg*tr[x<<1].len;\n\ttr[x<<1|1].tg+=tr[x].tg;\n\ttr[x<<1|1].y+=tr[x].tg*tr[x<<1|1].len;\n\ttr[x].tg=0;\n}\nvoid up(int x)\n{\n\ttr[x].x=tr[x<<1].x+tr[x<<1|1].x;\n\ttr[x].y=tr[x<<1].y+tr[x<<1|1].y;\n}\nvoid clear(int x,int l,int r,int ll,int rr)\n{\n\tif (l>=ll && r<=rr)\n\t{\n\t\ttr[x].tg+=ti;\n\t\ttr[x].y+=ti*tr[x].len;\n\t\ttr[x].x=0;\n\t\treturn;\n\t}\n\tdown(x);\n\tint mid=l+r>>1;\n\tif (ll<=mid) clear(x<<1,l,mid,ll,rr);\n\tif (rr>mid) clear(x<<1|1,mid+1,r,ll,rr);\n\tup(x);\n}\nvoid add(int x,int l,int r,int ll,int rr)\n{\n\tif (l>=ll && r<=rr)\n\t{\n\t\ttr[x].tg-=ti;\n\t\ttr[x].x=tr[x].len;\n\t\ttr[x].y-=ti*tr[x].len;\n\t\treturn;\n\t}\n\tdown(x);\n\tint mid=l+r>>1;\n\tif (ll<=mid) add(x<<1,l,mid,ll,rr);\n\tif (rr>mid) add(x<<1|1,mid+1,r,ll,rr);\n\tup(x);\n}\nlong long find(int x,int l,int r,int ll,int rr)\n{\n\tif (l>=ll && r<=rr) return tr[x].y+ti*tr[x].x;\n\tdown(x);\n\tint mid=l+r>>1;\n\tlong long ans=0;\n\tif (ll<=mid) ans+=find(x<<1,l,mid,ll,rr);\n\tif (rr>mid) ans+=find(x<<1|1,mid+1,r,ll,rr);\n\treturn ans;\n}\nint main()\n{\n\t//freopen(\"a.in\",\"r\",stdin);\n\t//freopen(\"1.out\",\"w\",stdout);\n\tscanf(\"%d%d\",&n,&m);\n\tfor (int i=1;i<=n;i++) scanf(\"%d\",&a[i]),bz[a[i]]=i;\n\tfor (int i=1;i<=m;i++) \n\t{\n\t\tint l,r;\n\t\tscanf(\"%d%d\",&l,&r);\n\t\tq[r].emplace_back(l,i);\n\t}\n\tfor (int i=1;i<=n;i++)\n\t\tfor (int j=i;j<=n;j+=i)\n\t\tw[j].emplace_back(i);\n\tmake(1,1,n);\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\twhile (top && a[d[top]]<a[i])\n\t\t{\n\t\t\tif (p[top]>d[top-1]) clear(1,1,n,d[top-1]+1,p[top]);\n\t\t\tbo[d[top]]=0;\n\t\t\ttop--;\n\t\t}\n\t\tfor (int j=a[i];j<=n;j+=a[i])\n\t\tif (bo[bz[j]])\n\t\t{\n\t\t\tint pt=bo[bz[j]];\n\t\t\tint l=d[pt-1]+1,r=d[pt];\n\t\t\tint e=bz[j/a[i]];\n\t\t\tif (e<l || e>=i) continue;\n\t\t\te=min(e,r);\n\t\t\tif (e<=p[pt]) continue;\n\t\t//\tif (l<=p[pt]) clear(1,1,n,l,p[pt]);\n\t\t\tadd(1,1,n,p[pt]+1,e);\n\t\t\tp[pt]=e;\n\t\t}\n\t\td[++top]=i;\n\t\tbo[i]=top;\n\t\tp[top]=d[top-1];\n\t\tfor (auto j:w[a[i]])\n\t\t{\n\t\t\tint l=d[top-1]+1,r=i;\n\t\t\tint e1=bz[j],e2=bz[a[i]/j];\n\t\t\tif (e2<=e1) continue;\n\t\t\tif (e1<l || e2>i) continue;\n\t\t\tif (e1<=p[top]) continue;\n\t\t//\tif (l<=p[top]) clear(1,1,n,l,p[top]);\n\t\t\tadd(1,1,n,p[top]+1,e1);\n\t\t\tp[top]=e1;\n\t\t}\n\t\tti++;\n\t\tfor (auto t:q[i]) ans[t.second]=find(1,1,n,t.first,i);\n\t}\n\tfor (int i=1;i<=m;i++) printf(\"%lld\\n\",ans[i]);\t\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1677",
    "index": "F",
    "title": "Tokitsukaze and Gems",
    "statement": "Tokitsukaze has a sequence with length of $n$. She likes gems very much. There are $n$ kinds of gems. The gems of the $i$-th kind are on the $i$-th position, and there are $a_i$ gems of the same kind on that position. Define $G(l,r)$ as the multiset containing all gems on the segment $[l,r]$ (inclusive).\n\nA multiset of gems can be represented as $S=[s_1,s_2,\\ldots,s_n]$, which is a non-negative integer sequence of length $n$ and means that $S$ contains $s_i$ gems of the $i$-th kind in the multiset. A multiset $T=[t_1,t_2,\\ldots,t_n]$ is a multisubset of $S=[s_1,s_2,\\ldots,s_n]$ if and only if $t_i\\le s_i$ for any $i$ satisfying $1\\le i\\le n$.\n\nNow, given two positive integers $k$ and $p$, you need to calculate the result of\n\n$$\\sum_{l=1}^n \\sum_{r=l}^n\\sum\\limits_{[t_1,t_2,\\cdots,t_n] \\subseteq G(l,r)}\\left(\\left(\\sum_{i=1}^n p^{t_i}t_i^k\\right)\\left(\\sum_{i=1}^n[t_i>0]\\right)\\right),$$\n\nwhere $[t_i>0]=1$ if $t_i>0$ and $[t_i>0]=0$ if $t_i=0$.\n\nSince the answer can be quite large, print it modulo $998\\,244\\,353$.",
    "tutorial": "First, consider how to calculate the contribution of a legal path. It can be found that the contribution of a legal path is equivalent to the following formula, where $b_i$ indicates the number of the $i$-th gems on the path. $\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n}(\\sum_{j=1}^n (P^{i_j}i_j^k)\\times\\sum_{j=1}^n [i_j\\ne 0])$ This formula seems impossible to calculate, but it can be observed that there is a chain structure behind it. Consider dynamic programming, try to calculate the $1\\sim (i+1)$-th gems' answer by only considering the $1\\sim i$-th gems' answer. Consider maintenance these: $dp_{n,1}=\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n}(\\sum_{j=1}^n (P^{i_j}i_j^k)\\times\\sum_{j=1}^n [i_j\\ne 0])$ $dp_{n,2}=\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n}\\sum_{j=1}^n (P^{i_j}i_j^k)$ $dp_{n,3}=\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n} \\sum_{j=1}^n [i_j\\ne 0]$ $dp_{n,4}=\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n} 1$ It can be observed that if we enumerate how many the $(n + 1)$-th gem are selected, this can actually be transferred, for example: $dp_{n+1,1}=\\sum_{p=0}^{b_{n+1}}\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n}((\\sum_{j=1}^n P^{i_j}i_j^k+P^p p^k)\\times (\\sum_{j=1}^n [i_j\\ne 0])+[p\\ne 0])$ Then spread. $A=\\sum_{p=0}^{b_{n+1}}\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n}(\\sum_{j=1}^n P^{i_j}i_j^k \\times \\sum_{j=1}^n [i_j\\ne 0])=(1+b_{n+1})dp_{n,1}$ $B=\\sum_{p=0}^{b_{n+1}}\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n}\\sum_{j=1}^n P^{i_j}i_j^k[p\\ne 0]=b_{n+1}dp_{n,2}$ $C=\\sum_{p=0}^{b_{n+1}}\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n}P^p p^k\\times \\sum_{j=1}^n [i_j\\ne 0]=dp_{n,3} \\times \\sum_{p=0}^{b_{n+1}}P^p p^k=dp_{n,3} \\times \\sum_{p=1}^{b_{n+1}}P^p p^k$ $D=\\sum_{p=0}^{b_{n+1}}\\sum_{i_1=0}^{b_1}\\sum_{i_2=0}^{b_2}\\ldots \\sum_{i_n=0}^{b_n}(P^p p^k)\\times [p\\ne 0]=dp_{n,4}\\times\\sum_{p=1}^{b_{n+1}}P^p p^k$ Now it can be transferred. The main problem is how to calculate $\\sum_{i=1}^n i^kx^i$ quickly, ensuring that $x\\gt 1$. Let $h_{k,n}$ represent $\\sum_{i=1}^n i^k x^i$. Calculate the sum according to the proportional sequence, $h_{0,n}=\\dfrac{x^{n+1}-x}{x-1}$. $xh_{k,n}-h_{k,n}=\\sum_{i=1}^n x^{i+1}i^k-\\sum_{i=1}^nx^ii^k$ $=x^{n+1}n^k+\\sum_{i=1}^nx^i((i-1)^k-i^k)$ $=x^{n+1}n^k+\\sum_{i=1}^nx^i([\\sum_{j=0}^k(-1)^{k-j}\\binom{k}{j}i^j]-i^k)$ $=x^{n+1}n^k+\\sum_{i=0}^{k-1}(-1)^{k-j}\\binom{k}{j}h_{i,n}$ Finally we get $h_{k,n}=\\dfrac{x^{n+1}n^k+\\sum_{i=0}^{k-1}(-1)^{k-j}\\binom{k}{j}h_{i,n}}{x-1}$ According to this recurrence formula, we can get $h_{0,n}=x^{n+1}(\\frac{1}{x-1})-x\\times(\\frac{1}{x-1})$ $h_{1,n}=x^{n+1}(\\frac{n}{x-1}-\\dfrac{1}{(x-1)^2})-x(-\\dfrac{1}{(x-1)^2})$ When $k$ is constant, there exist a $k$-degree polynomial $g_k(x)$ about $n$, making $h_{k,n}=x^{n+1}g_k(n)-xg_k(0)$. This conclusion can be proved by mathematical induction. Consider how to use interpolation to get this polynomial, we only need to find $g_k(0)\\sim g_k(k)$. Consider difference method, $h_{k,n}-h_{k,n-1}=x^{n+1}g_k(n)-x^ng_k(n-1)=n^kx^n$. So $xg_k(n)-g_k(n-1)=n^k$. But we still can't get $C$. There is a conclusion: the $(n + 1)$-th difference of the $n$-degree polynomial $f(x)$ is $0$. That is to say, $\\sum_{i=0}^{n+1}(-1)^{n+1-i}\\binom{n+1}{i}f(i)=0$. So we can get $g_k(0)$, then use polynomial fast interpolation, and then polynomial multipoint evaluation to get the value of every point we need. It can be observed that the DP transfer can be replaced by matrix, so there are matrices each position, the problem is equivalent to get the sum of the matrix products of all intervals. It's easy to solve. You can solve it in the way you like. Overall complexity: $\\mathcal{O}(k\\log^2k+n)$.",
    "code": "#include<cmath>\n#include<queue>\n#include<cstdio>\n#include<cstring>\n#include<assert.h>\n#include<iostream>\n#include<algorithm>\nusing namespace std;\n#define LL long long\n#define int long long\nconst int MAXN=4e5+5;\nconst int MAXNN=1e5+5;\nint n,k,P,fac[MAXN],ifac[MAXN],Inv[MAXN],rev[MAXN],x[MAXN],y[MAXN],K[MAXN],B[MAXN],g[MAXN],F[MAXN],Q[MAXN],val[MAXN]; \nint a[MAXNN],b[MAXNN],W[21][MAXN*2];\nconst int mod=998244353;\nvector<int>G[MAXNN];\ninline int mul(int a,int b){return 1ll*a*b%mod;}\ninline int dec(int a,int b){return ((a-b)%mod+mod)%mod;}\ninline int add(int a,int b){return ((a+b)%mod+mod)%mod;}\ninline int qkpow(int a,int b){\n\tint ans=1,base=a;\n\twhile(b){\n\t\tif(b&1)ans=mul(ans,base);\n\t\tbase=mul(base,base);\n\t\tb>>=1;\n\t}\n\treturn ans;\n}\nnamespace IO{\n\tconst int sz=1<<22;\n\tchar a[sz+5],b[sz+5],*p1=a,*p2=a,*t=b,p[105];\n\tinline char gc(){\n\t\treturn p1==p2?(p2=(p1=a)+fread(a,1,sz,stdin),p1==p2?EOF:*p1++):*p1++;\n\t}\n\ttemplate<class T> void gi(T& x){\n\t\tx=0; char c=gc();\n\t\tfor(;c<'0'||c>'9';c=gc());\n\t\tfor(;c>='0'&&c<='9';c=gc())\n\t\t\tx=x*10+(c-'0');\n\t}\n\tinline void flush(){fwrite(b,1,t-b,stdout),t=b; }\n\tinline void pc(char x){*t++=x; if(t-b==sz) flush(); }\n\ttemplate<class T> void pi(T x,char c='\\n'){\n\t\tif(x==0) pc('0'); int t=0;\n\t\tfor(;x;x/=10) p[++t]=x%10+'0';\n\t\tfor(;t;--t) pc(p[t]); pc(c);\n\t}\n\tstruct F{~F(){flush();}}f; \n}\nusing IO::gi;\nusing IO::pi;\nusing IO::pc;\nconst int S=4;\nstruct Matrix{\n\tint a[4][4];\n\tMatrix(){memset(a,0,sizeof a);}\n\tvoid clear(){memset(a,0,sizeof a);}\n\tvoid init(){for(int i=0;i<S;i++)a[i][i]=1;}\n\tint* operator [] (int x){return a[x];}\n\tMatrix friend operator +(Matrix A,Matrix B){\n\t\tMatrix ret=Matrix();\n\t\tfor(int i=0;i<S;i++)\n\t\t\tfor(int j=0;j<=i;j++)\n\t\t\t\tret[i][j]=add(A[i][j],B[i][j]);\t\n\t\treturn ret;\n\t}\n\tMatrix friend operator -(Matrix A,Matrix B){\n\t\tMatrix ret=Matrix();\n\t\tfor(int i=0;i<S;i++)\n\t\t\tfor(int j=0;j<=i;j++)\n\t\t\t\tret[i][j]=dec(A[i][j],B[i][j]);\t\n\t\treturn ret;\n\t}\n\tMatrix friend operator *(Matrix A,Matrix B){\n\t\tMatrix ret=Matrix();\n\t\tfor(int k=0;k<S;k++)\n\t\t\tfor(int j=0;j<=k;j++)\n\t\t\t\tif(B[k][j])\n\t\t\t\t\tfor(int i=k;i<S;i++)\n\t\t\t\t\t\tret[i][j]=1ll*(ret[i][j]+1ll*A[i][k]*B[k][j])%mod;\t\n\t\treturn ret;\n\t}\n\tMatrix friend operator *(Matrix A,int x){\n\t\tMatrix ret=Matrix();\n\t\tfor(int i=0;i<S;i++)\n\t\t\t\tfor(int j=0;j<=i;j++)\n\t\t\t\t\tret[i][j]=1ll*A[i][j]*x%mod;\n\t\treturn ret;\n\t}\n}d[MAXNN],dp[MAXNN],ans;\nMatrix operator += (Matrix &p,Matrix q){return p=p+q;}\nMatrix operator -= (Matrix &p,Matrix q){return p=p-q;}\nMatrix operator *= (Matrix &p,Matrix q){return p=p*q;}\ninline int C(int n,int m){\n\tif(n<m||m<0)return 0;\n\treturn 1ll*fac[n]*ifac[m]%mod*ifac[n-m]%mod;\n}\nvoid init(){\n\tfac[0]=ifac[0]=Inv[0]=Inv[1]=1;\n\tfor(int i=1;i<MAXN;i++)fac[i]=1ll*fac[i-1]*i%mod; \n\tifac[MAXN-1]=qkpow(fac[MAXN-1],mod-2);\n\tfor(int i=MAXN-2;i>=1;i--)ifac[i]=1ll*ifac[i+1]*(i+1)%mod;\n    for(int i=2;i<MAXN;i++)Inv[i]=1ll*(mod-mod/i)*Inv[mod%i]%mod;\n    int wn;\n    for(int i=0,x=1;x<MAXN;i++,x<<=1){\n        W[i][x]=1;\n        wn=qkpow(3,(mod-1)/(x<<1));\n        for(int j=1;j<x;j++)W[i][x+j]=1ll*wn*W[i][x+j-1]%mod;\n        wn=qkpow(wn,mod-2);\n        for(int j=1;j<x;j++)W[i][x-j]=1ll*wn*W[i][x-j+1]%mod;\n    } \n} \ninline void NTT(int *a,int type,int n){\n    for(int i=0;i<n;i++)if(i<rev[i])swap(a[i],a[rev[i]]);\n    LL x,y;\n    for(int i=1,cnt=0;i<n;cnt++,i<<=1){\n        for(int j=0;j<n;j+=(i<<1)){\n            for(int t=0,k=j;k<j+i;k++,t+=type){\n                x=a[k],y=1ll*W[cnt][i+t]*a[k+i];\n                a[k]=(x+y)%mod;\n                a[k+i]=(x-y)%mod;\n            }\n        }\n    }\n    if(type==-1)for(int i=0;i<n;i++)a[i]=mul(a[i],Inv[n]);\n}\nvoid Polyinv(int *a,int *b,int len){\n\tstatic int c[MAXN];\n\tif(len==1){\n\t\tb[0]=qkpow(a[0],mod-2);\n\t\treturn ;\n\t}\n\tPolyinv(a,b,(len+1)>>1);\n\tint l=0,m=(len<<1),n=1;\n\tfor(;n<=m;n<<=1,l++);\n\tfor(int i=0;i<n;i++)rev[i]=(rev[i>>1]>>1)|((i&1)<<(l-1));\n\tfor(int i=0;i<len;i++)c[i]=a[i];\n\tfor(int i=len;i<n;i++)c[i]=0;\n\tNTT(c,1,n),NTT(b,1,n);\n\tfor(int i=0;i<n;i++)b[i]=1ll*(2-1ll*b[i]*c[i])%mod*b[i]%mod;\n\tNTT(b,-1,n);\n\tfor(int i=len;i<n;i++)b[i]=0;\n}\ninline void Polydao(int *Aa,int *Bb,int len){\n\tBb[len-1]=0;\n\tfor(int i=1;i<len;i++)Bb[i-1]=1ll*i*Aa[i]%mod;\n}\nint init_NTT(int L){\n\tint l=0,m=L,n=1;\n\tfor(;n<=m;n<<=1,l++);\n\tfor(int i=0;i<n;i++)rev[i]=(rev[i>>1]>>1)|((i&1)<<(l-1));\n\treturn n;\n}\nvoid MUL(int *a,int *b,int *c,int n,int m,int lim){\n\tstatic int t1[MAXN],t2[MAXN],t3[MAXN];\n\tfor(int i=0;i<n;i++)t1[i]=a[i];\n\tfor(int i=0;i<m;i++)t2[i]=b[i];\n\tfor(int i=n;i<lim;i++)t1[i]=0;\n\tfor(int i=m;i<lim;i++)t2[i]=0;\n\tNTT(t1,1,lim),NTT(t2,1,lim);\n\tfor(int i=0;i<lim;i++)t3[i]=1ll*t1[i]*t2[i]%mod;\n\tNTT(t3,-1,lim);\n\tfor(int i=0;i<n+m-1;i++)c[i]=t3[i]; \n}\nnamespace Evaluation{\n\t#define ls(p) p<<1\n\t#define rs(p) p<<1|1\n\tint *T1[MAXN],*T2[MAXN],T3[MAXN],T4[MAXN],flow[MAXN*32],*now=flow;\n\tvoid clear(){now=flow;}\n\tinline void MUL2(int *a,int *b,int *c,int n,int m,int lim){\n\t\tstatic int t1[MAXN],t2[MAXN],t3[MAXN];\n\t\tfor(int i=0;i<n;i++)t1[i]=a[i];\n\t\tfor(int i=0;i<m;i++)t2[i]=b[i];\n\t\treverse(t2,t2+m);\n\t\tfor(int i=n;i<lim;i++)t1[i]=0;\n\t\tfor(int i=m;i<lim;i++)t2[i]=0;\n\t\tNTT(t1,1,lim),NTT(t2,1,lim);\n\t\tfor(int i=0;i<lim;i++)t3[i]=1ll*t1[i]*t2[i]%mod;\n\t\tNTT(t3,-1,lim);\n\t\tfor(int i=m-1;i<n;i++)c[i-m+1]=t3[i]; \n\t}\n\tvoid pre(int *Q,int p,int l,int r){\n\t\tT1[p]=now,now+=r-l+2;\n\t\tT2[p]=now,now+=r-l+2;\n\t\tfor(int i=0;i<=r-l+1;i++)T1[p][i]=T2[p][i]=0;\n\t\tif(l==r){\n\t\t\tT1[p][0]=1;\n\t\t\tT1[p][1]=(mod-Q[l])%mod;\n\t\t\treturn ; \n\t\t}\n\t\tint mid=(l+r)>>1;\n\t\tpre(Q,ls(p),l,mid);\n\t\tpre(Q,rs(p),mid+1,r);\n\t\tif(r-l+1<=256){\n\t\t\tfor(int i=0;i<=mid-l+1;i++)\n\t\t\t\tfor(int j=0;j<=r-mid;j++)\n\t\t\t\t\tT1[p][i+j]=add(T1[p][i+j],1ll*T1[ls(p)][i]*T1[rs(p)][j]%mod);\n\t\t}else{\n\t\t\tint lim=init_NTT(r-l+1);\n\t\t\tMUL(T1[ls(p)],T1[rs(p)],T1[p],mid-l+2,r-mid+1,lim); \n\t\t}\n\t}\n\tvoid Solve(int *S,int p,int l,int r){\n\t\tif(l==r){\n\t\t\tS[l]=T2[p][0];\n\t\t\treturn ;\n\t\t}\n\t\tint mid=(l+r)>>1;\n\t\tint lim=init_NTT(r-l+1);\n\t\tMUL2(T2[p],T1[rs(p)],T2[ls(p)],r-l+1,r-mid+1,lim);\n\t\tMUL2(T2[p],T1[ls(p)],T2[rs(p)],r-l+1,mid-l+2,lim);\n\t\tSolve(S,ls(p),l,mid);\n\t\tSolve(S,rs(p),mid+1,r);\n\t}\n\t//opt0/1 区分多点求值/快速插值 \n\tvoid evaluation(int *F,int *Q,int *S,int n,int m,int opt){\n\t\tclear();\n\t\tstatic int AF[MAXN];\n\t\tn=max(n,m+1),m=max(m,n-1);\n\t\tpre(Q,1,1,m);\n\t\tif(opt){\n\t\t\tfor(int i=0;i<n;i++)AF[i]=T1[1][i];\n\t\t\treverse(AF,AF+n); \n\t\t\tPolydao(AF,AF,n+1);\n\t\t}\n\t\tPolyinv(T1[1],T3,m+1);\n\t\treverse(T3,T3+m+1);\n\t\tint lim=init_NTT(n+m+1); \n\t\tif(!opt)MUL(F,T3,T4,n,m+1,lim);\n\t\telse MUL(AF,T3,T4,n,m+1,lim);\n\t\tfor(int i=n;i<n+m;i++)T2[1][i-n]=T4[i];\n\t\tSolve(S,1,1,m);\n\t\tfor(int i=1;i<=m;i++)S[i]=(1ll*S[i]*Q[i]%mod+(!opt?F[0]:AF[0]))%mod;\n\t\tfor(int i=0;i<=n+m+1;i++)T3[i]=T4[i]=0;\n\t}\n};\nnamespace Lagrange_Interpolation{\n\t#define ls(p) p<<1\n\t#define rs(p) p<<1|1\n\tint S[MAXN],*T[MAXN],flow[MAXN*32],*now=flow,tmp1[MAXN],tmp2[MAXN],e1[MAXN],e2[MAXN];\n\tvoid solve(int p,int l,int r){\n\t\tT[p]=now,now+=r-l+2;\n\t\tif(l==r){\n\t\t\tT[p][0]=S[l];\n\t\t\treturn ;\n\t\t}\n\t\tint mid=(l+r)>>1;\n\t\tsolve(ls(p),l,mid);\n\t\tsolve(rs(p),mid+1,r);\n\t\tfor(int i=0;i<mid-l+1;i++)tmp1[i]=T[ls(p)][i];\n\t\tfor(int i=0;i<r-mid;i++)tmp2[i]=T[rs(p)][i];\n\t\tfor(int i=0;i<r-mid+1;i++)e1[i]=Evaluation::T1[rs(p)][i];\n\t\treverse(e1,e1+r-mid+1);\n\t\tfor(int i=0;i<mid-l+2;i++)e2[i]=Evaluation::T1[ls(p)][i];\n\t\treverse(e2,e2+mid-l+2);\n\t\tint lim=init_NTT(r-l+1); \n\t\tMUL(tmp1,e1,e1,mid-l+1,r-mid+1,lim);\n\t\tMUL(tmp2,e2,e2,r-mid,mid-l+2,lim);\n\t\tfor(int i=0;i<=r-l;i++)T[p][i]=add(e1[i],e2[i]);\n\t}\n\tvoid Interpolation(int *x,int *y,int *ans,int n){\n\t\tEvaluation::evaluation(x,x,S,n+1,n,1);\n\t\tfor(int i=1;i<=n;i++)S[i]=1ll*y[i]*qkpow(S[i],mod-2)%mod;\n\t\tsolve(1,1,n);\n\t\tfor(int i=0;i<n;i++)ans[i]=T[1][i];\n\t}\n}\nvoid Pre(int P){\n\tint\tinvP=qkpow(P,mod-2),kk=0,bb=0;\n\tK[0]=1,B[0]=0;\n\tfor(int i=1;i<=k+1;i++){\n\t\tK[i]=1ll*K[i-1]*invP%mod;\n\t\tB[i]=1ll*(B[i-1]+qkpow(i,k))*invP%mod;\n\t\tint Num=C(k+1,i);\n\t\tif(i&1)kk=dec(kk,1ll*Num*K[i]%mod),bb=dec(bb,1ll*Num*B[i]%mod);\n\t\telse kk=add(kk,1ll*Num*K[i]%mod),bb=add(bb,1ll*Num*B[i]%mod);\n\t} \n\tkk=(kk+1),kk=(kk==mod?0:kk);\n\tg[0]=1ll*(mod-bb)*qkpow(kk,mod-2)%mod;\n\tfor(int i=1;i<=k;i++)g[i]=add(1ll*g[0]*K[i]%mod,B[i]);\n\tfor(int i=1;i<=k+1;i++)x[i]=i-1,y[i]=(g[i-1]+mod)%mod;\n\tLagrange_Interpolation::Interpolation(x,y,F,k+1);\n\tfor(int i=0;i<=k;i++)F[i]=(F[i]+mod)%mod; \n//\tcout<<endl;\n\tfor(int i=1;i<=n;i++)Q[i]=b[i];\n\tEvaluation::evaluation(F,Q,val,k+1,n,0);\n\tfor(int i=1;i<=n;i++)val[i]=(val[i]+mod)%mod;\n}\ninline void makeit(int Id,int y,Matrix& S){\n\t//[S1S2,S1,S2,product of b]\n\tint X=dec(1ll*qkpow(P,y+1)*val[Id]%mod,1ll*P*g[0]%mod);\n\tS.a[0][0]=add(y,1),S.a[1][0]=y,S.a[2][0]=X,S.a[3][0]=X;\n\tS.a[1][1]=add(y,1),S.a[3][1]=X;\n\tS.a[2][2]=add(y,1),S.a[3][2]=y; \n\tS.a[3][3]=add(y,1);\n} \nsigned main(){\n\tgi(n),gi(k),gi(P);\n\tinit();\n\tfor(int i=1;i<=n;i++)gi(b[i]);\n\tPre(P);\n\tfor(int i=1;i<=n;i++)makeit(i,b[i],d[i]);\n\tdp[1]=d[1];\n\tfor(int i=2;i<=n;i++)dp[i]=dp[i-1]*d[i]+d[i];\n\tfor(int i=1;i<=n;i++)ans+=dp[i];\n\tpi(ans.a[3][0],'\\n');\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1678",
    "index": "A",
    "title": "Tokitsukaze and All Zero Sequence",
    "statement": "Tokitsukaze has a sequence $a$ of length $n$. For each operation, she selects two numbers $a_i$ and $a_j$ ($i \\ne j$; $1 \\leq i,j \\leq n$).\n\n- If $a_i = a_j$, change one of them to $0$.\n- Otherwise change both of them to $\\min(a_i, a_j)$.\n\nTokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $0$. It can be proved that the answer always exists.",
    "tutorial": "We observe that when there is $0$ in the sequence, it is optimal to choose $0$ and any number other than $0$ for each operation. Therefore, when there is $0$ in the sequence, let $cnt$ be the number of $0$s, the answer is $n - cnt$. Otherwise, when $0$ does not exist in the sequence, there are two situations: When there exist two equal numbers in the sequence, we can perform the operation $1$ time to convert it into the situation of having $0$ in the sequence. So the answer must be $n$. When there exist two equal numbers in the sequence, we can perform the operation $1$ time to convert it into the situation of having $0$ in the sequence. So the answer must be $n$. When all numbers in the sequence are distinct, we can perform the operation $2$ times to convert it into the situation of having $0$ in the sequence. So the answer must be $n + 1$. When all numbers in the sequence are distinct, we can perform the operation $2$ times to convert it into the situation of having $0$ in the sequence. So the answer must be $n + 1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main(){\n\tint t;\n\tscanf(\"%i\",&t);\n\twhile(t--){\n\t\tint n;\n\t\tscanf(\"%i\",&n);\n\t\tvector<int> a(n);\n\t\tfor(int i=0;i<n;i++)\n\t\t\tscanf(\"%i\",&a[i]);\n\t\tsort(a.begin(),a.end());\n\t\tint zero=count(a.begin(),a.end(),0);\n\t\tif(zero>0)\n\t\t\tprintf(\"%i\\n\",n-zero);\n\t\telse{\n\t\t\tbool same=false;\n\t\t\tfor(int i=1;i<n;i++)\n\t\t\t\tif(a[i]==a[i-1])\n\t\t\t\t\tsame=true;\n\t\t\tif(same)printf(\"%i\\n\",n);\n\t\t\telse printf(\"%i\\n\",n+1);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1678",
    "index": "B2",
    "title": "Tokitsukaze and Good 01-String (hard version)",
    "statement": "This is the hard version of the problem. The only difference between the two versions is that the harder version asks additionally for a minimum number of subsegments.\n\nTokitsukaze has a binary string $s$ of length $n$, consisting only of zeros and ones, $n$ is \\textbf{even}.\n\nNow Tokitsukaze divides $s$ into \\textbf{the minimum number} of \\textbf{contiguous} subsegments, and for each subsegment, all bits in each subsegment are the same. After that, $s$ is considered good if the lengths of all subsegments are even.\n\nFor example, if $s$ is \"11001111\", it will be divided into \"11\", \"00\" and \"1111\". Their lengths are $2$, $2$, $4$ respectively, which are all even numbers, so \"11001111\" is good. Another example, if $s$ is \"1110011000\", it will be divided into \"111\", \"00\", \"11\" and \"000\", and their lengths are $3$, $2$, $2$, $3$. Obviously, \"1110011000\" is not good.\n\nTokitsukaze wants to make $s$ good by changing the values of some positions in $s$. Specifically, she can perform the operation any number of times: change the value of $s_i$ to '0' or '1' ($1 \\leq i \\leq n$). Can you tell her the minimum number of operations to make $s$ good? \\textbf{Meanwhile, she also wants to know the minimum number of subsegments that $s$ can be divided into among all solutions with the minimum number of operations.}",
    "tutorial": "Obviously, the operation is, for each pair of adjacent and unequal characters, change both of them to $0$ or $1$. In other words, the string is divided into many adjacent binaries with length of $2$. If the binary is \"01\" or \"10\", it needs $1$ operation, otherwise the operation is not required. If you want to minimize the number of \"contiguous segments\", a simple greedy way is to change each \"binary requiring operation\" (i.e. $01$ or $10$) into the form of the previous or next \"binary requiring no operation\" (i.e. $11$ or $00$). For example: \"0010\" change to \"0000\" and \"1101\" change to \"1111\". In this way, this \"binary requiring operation\" has no contribution to the final number of contiguous segments. We only need to count the number of contiguous \"11\" and \"00\" binaries. In particular, if all binaries are \"01\" or \"10\", the final contribution to the number of final contiguous segments is $1$ in total. Obviously, the operation is, for each pair of adjacent and unequal characters, change both of them to $0$ or $1$. In other words, the string is divided into many adjacent binaries with length of $2$. Consider the recursion from the front to the back, it can be observed that the previously maintained prefix must end with \"00\" or \"11\". Therefore, it's necessary to convert each divided binary into \"00\" or \"11\" by enumerating the cost of changing the current binary into \"00\" and \"11\". Maintain the minimum number of operations in the process of DP, try to make the current string consistent with the end of the prefix subsegment. $dp[n][2]$, set the first dimension as the maintained length of prefix and the second dimension as the suffix state of the prefix. Then the DP transfer equation is: $dp[i][0]=min(dp[i-2][0]+\\left \\{c_0,0\\right \\},dp[i-2][1]+\\left \\{c_0,1\\right \\})$ $dp[i][1]=min(dp[i-2][0]+\\left \\{c_1,1\\right \\},dp[i-2][1]+\\left \\{c_1,0\\right \\})$ where $c_k$ represents the cost of converting the current binary to \"kk\".",
    "code": "#include<bits/stdc++.h>\n#define fre(z) freopen(z\".in\",\"r\",stdin),freopen(z\".out\",\"w\",stdout)\n#define lowit(x) (x&-x)\n\n#define range(x) begin(x), end(x)\n#define sz(x) (int)(x).size()\n#define pb push_back\n\n#define sto                             \\\n    std::ios::sync_with_stdio(false);   \\\n    std::cin.tie(nullptr);              \\\n    std::cout.tie(nullptr);\n    \nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<ll,ll> PII;\n\ninline ll read(){\n\tll x=0;char ch;bool f=true;\n\tfor(ch=getchar();!isdigit(ch);ch=getchar())if(ch=='-')f^=f;\n\tfor(;isdigit(ch);ch=getchar())x=(x<<3)+(x<<1)+(ch^48);\n\treturn f?x:-x;\n}\n//#define LOCAL_DEFINE\n#define DEBUG(x) cerr<<(#x)<<'='<<(x)<<endl\nconst int N=2e5+7;\nconst int INF=1e9;\nchar s[N];\nint c[N];\nPII dp[N][2];\nvoid solve(){\n\tint n=read();\n\tscanf(\"%s\",s+1);\n\tfor(int i=1;i<=n;i++)s[i]-='0';\n\tfor(int i=1;i<=n/2;i++)c[i]=s[i*2]+s[i*2-1]*2;\n\tfor(int i=1;i<=n/2;i++)for(int j=0;j<2;j++)dp[i][j]={INF,INF};\n\tfor(int i=1;i<=n/2;i++)for(int j=0;j<2;j++){\n\t\tint cc=c[i],dd=j?3:0,cnt=((dd%2)^(cc%2))+((dd/2)^(cc/2));\n\t\tfor(int k=0;k<2;k++)\n\t\t\tdp[i][j]=min(dp[i][j],{dp[i-1][k].first+cnt,dp[i-1][k].second+(j!=k)});\n\t}\n\tPII ans=min(dp[n/2][0],dp[n/2][1]);\n\tcout<<ans.first<<\" \"<<ans.second+1<<\"\\n\";\n}\n\nint main(){\n\t#ifdef ONLINE_JUDGE\n\t#else\t\n\t\t//fre(\"1\");\n\t#endif\n\tll T=1;\n\tT=read();\n\tfor(int i=1;i<=T;i++)solve();\n\t#ifdef LOCAL_DEFINE\n    \tcerr << \"Time elapsed: \" << 1.0 * clock() / CLOCKS_PER_SEC << \" s.\\n\";\n\t#endif\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1679",
    "index": "A",
    "title": "AvtoBus",
    "statement": "Spring has come, and the management of the AvtoBus bus fleet has given the order to replace winter tires with summer tires on all buses.\n\nYou own a small bus service business and you have just received an order to replace $n$ tires. You know that the bus fleet owns two types of buses: with two axles (these buses have $4$ wheels) and with three axles (these buses have $6$ wheels).\n\nYou don't know how many buses of which type the AvtoBus bus fleet owns, so you wonder how many buses the fleet might have. You have to determine the minimum and the maximum number of buses that can be in the fleet if you know that the total number of wheels for all buses is $n$.",
    "tutorial": "Let the number of buses with two axles is $x$ and the number of buses with three axles is $y$. Then the equality $4x + 6y = n$ must be true. If $n$ is odd, there is no answer, because the left part of the equality is always even. Now we can divide each part of the equality by two: $2x + 3y = \\frac{n}{2}$. Let's maximize the number of buses. Then we should make $x$ as large as possible. So, we will get $2 + \\ldots + 2 + 2 = \\frac{n}{2}$ if $\\frac{n}{2}$ is even, and $2 + \\ldots + 2 + 3 = \\frac{n}{2}$ otherwise. In both cases the number of buses is $\\left\\lfloor \\frac{n}{2} \\right\\rfloor$. Now let's minimize the number of buses. So, we should make $y$ as large is possible. We will get $3 + \\ldots + 3 + 3 + 3 = \\frac{n}{2}$ if $\\frac{n}{2}$ is divisible by $3$, $3 + \\ldots + 3 + 3 + 2 = \\frac{n}{2}$ if $n \\equiv 2 \\pmod 3$, and $3 + \\ldots + 3 + 2 + 2 = \\frac{n}{2}$ if $n \\equiv 1 \\pmod 3$. In all cases the number of buses is $\\left\\lceil \\frac{n}{3} \\right\\rceil$. Also don't forget the case $n = 2$ - each bus has at least four wheels, so in this case there is no answer. Time complexity: $\\mathcal{O}(1)$.",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1679",
    "index": "B",
    "title": "Stone Age Problem",
    "statement": "Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!\n\nYou are given an array $a$ of $n$ integers. You are also given $q$ queries of two types:\n\n- Replace $i$-th element in the array with integer $x$.\n- Replace each element in the array with integer $x$.\n\nAfter performing each query you have to calculate the sum of all elements in the array.",
    "tutorial": "As we want to perform queries fast, we will store some variables: current sum of all elements in the array $sum$, index of the last query of the second type $lastSecondQuery$ and its value $lastSecondQueryValue$. For each element of the array we will also store index of the last query of the first type that changed this element $lastFirstQuery[i]$ and its value $lastFirstQueryValue[i]$. Now let's answer the queries. If we are going to perform a query of the first type, we have to know, what the number $a_i$ equals now. If $lastSecondQuery > lastFirstQuery[i]$, then $a_i = lastSecondQueryValue$ now, and $a_i = lastFirstQueryValue[i]$ otherwise. Now let's subtract $a_i$ from the sum, change $lastFirstQuery[i]$ and $lastFirstQueryValue[i]$, and add the new value $a_i$ to the sum. If we are going to perform a query of the second type, we have to update values $lastSecondQuery$ and $lastSecondQueryValue$. The new sum of all elements of the array is $n \\cdot lastSecondQueryValue$. Time complexity: $\\mathcal{O}(n + q)$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1679",
    "index": "C",
    "title": "Rooks Defenders",
    "statement": "You have a square chessboard of size $n \\times n$. Rows are numbered from top to bottom with numbers from $1$ to $n$, and columns — from left to right with numbers from $1$ to $n$. So, each cell is denoted with pair of integers $(x, y)$ ($1 \\le x, y \\le n$), where $x$ is a row number and $y$ is a column number.\n\nYou have to perform $q$ queries of three types:\n\n- Put a new rook in cell $(x, y)$.\n- Remove a rook from cell $(x, y)$. It's guaranteed that the rook was put in this cell before.\n- Check if each cell of subrectangle $(x_1, y_1) - (x_2, y_2)$ of the board is attacked by at least one rook.\n\nSubrectangle is a set of cells $(x, y)$ such that for each cell two conditions are satisfied: $x_1 \\le x \\le x_2$ and $y_1 \\le y \\le y_2$.\n\nRecall that cell $(a, b)$ is attacked by a rook placed in cell $(c, d)$ if either $a = c$ or $b = d$. In particular, the cell containing a rook is attacked by this rook.",
    "tutorial": "Consider some subrectangle. Note that each its cell is attacked by some rook if and only if there is at least one rook in each row $x$ ($x_1 \\le x \\le x_2$) or in each column $y$ ($y_1 \\le y \\le y_2$). Now we will solve the problem using this criterium. Let's create a set $freeRows$ where we will store indices of rows in which there are no rooks. Similarly, we will store indices of columns in which there are no rooks in a set $freeCols$. If we have to answer the query of the third type, we have to check if there is at least one $x$ in the $freeRows$ set such that $x_1 \\le x \\le x_2$ or there is at least one $y$ in the $freeCols$ set such that $y_1 \\le y \\le y_2$. If we will store these two sets sorted, we can perform this type of query in $\\mathcal{O}(\\log n)$ using binary search. Now we're going to answer queries of the first and the second types. Let's store for each row and column, how many rooks are there in this row or column. When we add a new rook we should increment this counters for the corresponding row and column and remove the row from $freeRows$ set and the column from $freeColumns$ set. When we remove a rook we should decrement counters for its row and column and if there is no more rooks in the row or in the column, we should add their indices to $freeRows$ or $freeCols$. Time complexity: $\\mathcal{O}(q \\log n)$.",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1679",
    "index": "D",
    "title": "Toss a Coin to Your Graph...",
    "statement": "One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...\n\nMasha has an oriented graph which $i$-th vertex contains some positive integer $a_i$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $u$ to any other vertex $v$ such that there is an oriented edge $u \\to v$ in the graph. Each time when the coin is placed in some vertex $i$, Masha write down an integer $a_i$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $k - 1$ operations in such way that the maximum number written in her notebook is as small as possible.",
    "tutorial": "Note that the function of existence of the answer relatively to the minimum value of the maximum in the path is monotonous. If we were able to construct the path with maximum, not greater than $x$, we are able to construct the path with maximum, not greater than $x + 1$. This leads to the idea of binary search the answer. Let binary search to fix some integer $x$. We have to check, if there is a path in the graph, that consists of $k - 1$ edges and the maximum on this path is not greater than $x$. In the beginning let's leave in consideration only vertices which values are not greater than $x$. Now we need to check if the needed path exist in the resulting graph. If there is a cycle in the graph, there is a path of every length in it, so there is a path of length $k - 1$. Otherwise we have a directed acyclic graph. Let's find a longest path in it and compare its length with $k - 1$. Let's sort the graph topologically and calculate $dp[v]$ - the length of the longest path in the graph that begins in vertex $v$, it's a well-known classical problem. Time complexity: $\\mathcal{O}((n + m) \\log MAX)$.",
    "tags": [
      "binary search",
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1679",
    "index": "E",
    "title": "Typical Party in Dorm",
    "statement": "Today is a holiday in the residence hall — Oleh arrived, in honor of which the girls gave him a string. Oleh liked the gift a lot, so he immediately thought up and offered you, his best friend, the following problem.\n\nYou are given a string $s$ of length $n$, which consists of the first $17$ lowercase Latin letters {$a$, $b$, $c$, $\\ldots$, $p$, $q$} and question marks. And $q$ queries. Each query is defined by a set of pairwise distinct lowercase first $17$ letters of the Latin alphabet, which can be used to replace the question marks in the string $s$.\n\nThe answer to the query is the sum of the number of distinct substrings that are palindromes over all strings that can be obtained from the original string $s$ by replacing question marks with available characters. The answer must be calculated modulo $998\\,244\\,353$.\n\n\\textbf{Pay attention!} Two substrings are different when their start and end positions in the string are different. So, the number of different substrings that are palindromes for the string aba will be $4$: a, b, a, aba.\n\nConsider examples of replacing question marks with letters. For example, from the string aba??ee when querying {$a$, $b$} you can get the strings ababaee or abaaaee but you cannot get the strings pizza, abaee, abacaba, aba?fee, aba47ee, or abatree.\n\nRecall that a palindrome is a string that reads the same from left to right as from right to left.",
    "tutorial": "We are given a string $s$, we need to count the number of palindromes in all possible versions of it if the characters \"$?$\" can be replaced by some letters of the English alphabet, which are set by queries. Let us solve the problem initially for a $1$ query. First, we can see that instead of counting the number of palindromes in each possible version of string $s$, we can count the number of strings in which a substring $[l;r]$ would be a palindrome. Consider the substring $[l;r]$. Suppose the set of allowed characters in this query is $Q$. What would be the effect of the substring on the answer? Divide the characters of the substring into pairs: first with last, second with penultimate, and so on. If the length of the substring is odd, pair the central character with itself. Now let's consider each pair separately: If two characters of the pair are equal and they are not question marks, then this pair does not affect the answer. If two characters of the pair are equal and they are question marks, then this pair multiplies the answer by $|Q|$, where $|Q|$ - the number of possible characters to replace in this query. (Let's call the number of such pairs $f$). If two characters of the pair are not equal and there is no question mark among them, then this substring will never be a palindrome. If two characters of a pair are not equal and there is a question mark among them, you must check if the letter that is not a question mark belongs to the set $Q$, if not, then in this query this substring will never be a palindrome. Thus, to get the answer for the substring $[l;r]$ it is enough: Check for blocking pairs - if they exist, the answer is $0$ by definition. Otherwise, the answer is $|Q|^{d+f}$, where $d$ and $f$ are defined above. Let's assign to each possible set of letters a binary mask of size $\\alpha$, where $\\alpha$ - the size of the alphabet in the problem. In the future, we will assume that mask and set are the same. Consider possible blocking pairs of some substring $[l;r]$, they are of two kinds: If two characters of the pair are not equal and there is no question mark among them, then this substring will never be a palindrome and we do not consider it. If two characters of the pair are not equal and there is a question mark between them, a character that is not a question mark must be in the query for us to consider this substring. Next, let us note the following fact: $d+f$ does not depend on the query $Q$, because $d$ depends only on $l$ and $r$, and $f$ - on the number of pairs where both characters are question marks. It follows that every substring of the form $[l;r]$: Or is simply ignored if it has a blocking pair of the first type. (These substrings will not be mentioned further in the tutorial - when we say substrings, we automatically mean the one described below). Either is characterized by a pair of numbers ($P$; $d+f$). Consider an arbitrary query $Q$, how to calculate the answer for it? We need to go through all substrings, check whether $P \\subseteq Q$ and if so, add $|Q|^{d+f}$ to the answer. The values of $P$ and $d+f$ for the substring $[l;r]$ can be found quickly by knowing the same values for the substring $[l+1;r-1]$. Thus, by iterating over the parity of the palindrome length, then its center, and then its length itself, we can quickly find these values for all the substrings. Thus, our solution has asymptotics so far $O$($n^2$ $+$ $q \\cdot n^2$), which is obviously too slow. But first, let's figure out how to solve the problem if we have $|Q|$ - fixed? Let's create an array of size $2^\\alpha$ (let's call it $R$). For each substring, let's add to $R_P$ value $|Q|^{d+f}$. What does this give us? We will then have in $R_i$ the sum of answers from all the substrings $P$ of which is equal to $i$. To find the answer in this case we have to sum all $R_i$ where $i \\subseteq Q$. Actually, we have reached the asymptotics $O$($n^2$ $+$ $q \\cdot 2^\\alpha$) or $O$($n^2$ $+$ $3^\\alpha$). But! The problem of finding the sum of subset values is a well-known one and solves our subproblem for $O$($\\alpha$ $\\cdot$ $2^\\alpha$). In more detail: https://codeforces.com/blog/entry/45223 Well, here we have reached the asymptotics of $O$($n^2$ $+$ $\\alpha \\cdot 2^\\alpha$), which is enough. Let us return to the original problem. First, note that we don't have many different $|Q|$ - just $\\alpha$. So we create $\\alpha$ different arrays of size $2^\\alpha$. When processing the current substring, we add $i^{d+f}$ to each of the $\\alpha$ arrays at position $P$, where $i$ - the index of the current array. Thus, it is as if we $\\alpha$ times solved the problem for a fixed $|Q|$. We need to take the sum over subsets of $Q$ from the $|Q|$th array to get the answer. The final asymptotic of the solution - $O$($\\alpha \\cdot n^2$ $+$ $\\alpha^2 \\cdot 2^\\alpha$). Applied optimizations in the author's solution: Power optimization: we will often need different values of numbers from $1$ to $\\alpha$ in powers from $0$ to $n$, so to remove $log$ from the asymptotic, a precalculation of these values is used. This optimization is necessary to guarantee a full score on the problem. Addition optimization: we do not need to add a subset ($P$; $d+f$) to arrays whose index is less than $|P|$. This is since they will not affect the answer in any way. (Since the sets from which the answer will be taken in this array have fewer elements than $P$, they cannot, by definition, be $P$ supersets.) This optimization is unlikely to have much effect on runtime. It is written here for a clearer understanding of the author's solution. Modulo optimization: The take modulo operation is slower than other operations, so it is worth avoiding. Here we often use the sum modulo of two numbers that do not exceed $998\\,244\\,353$, so we will replace it by using (a+b >= M ? a+b-M : a+b) instead of (a+b)%M",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1679",
    "index": "F",
    "title": "Formalism for Formalism",
    "statement": "Yura is a mathematician, and his cognition of the world is so absolute as if he have been solving formal problems a hundred of trillions of billions of years. This problem is just that!\n\nConsider all non-negative integers from the interval $[0, 10^{n})$. For convenience we complement all numbers with leading zeros in such way that each number from the given interval consists of exactly $n$ decimal digits.\n\nYou are given a set of pairs $(u_i, v_i)$, where $u_i$ and $v_i$ are distinct decimal digits from $0$ to $9$.\n\nConsider a number $x$ consisting of $n$ digits. We will enumerate all digits from left to right and denote them as $d_1, d_2, \\ldots, d_n$. In one operation you can swap digits $d_i$ and $d_{i + 1}$ if and only if there is a pair $(u_j, v_j)$ in the set such that at least one of the following conditions is satisfied:\n\n- $d_i = u_j$ and $d_{i + 1} = v_j$,\n- $d_i = v_j$ and $d_{i + 1} = u_j$.\n\nWe will call the numbers $x$ and $y$, consisting of $n$ digits, equivalent if the number $x$ can be transformed into the number $y$ using some number of operations described above. In particular, every number is considered equivalent to itself.\n\nYou are given an integer $n$ and a set of $m$ pairs of digits $(u_i, v_i)$. You have to find the maximum integer $k$ such that there exists a set of integers $x_1, x_2, \\ldots, x_k$ ($0 \\le x_i < 10^{n}$) such that for each $1 \\le i < j \\le k$ the number $x_i$ is \\textbf{not} equivalent to the number $x_j$.",
    "tutorial": "If you carefully read the problem statement, it becomes clear that we can do some transformations some numbers into others and we have to calculate the number of equivalence classes of all numbers consisting of $n$ digits. Let's say that the representative of some equivalence class is the lexicographically minimal number in this class. Now the problem is to calculate the number of distinct integers that are representatives of some equivalence classes. For convenience let's build an undirected graph which vertices will be digits and an edge will connect some digits $u$ and $v$ if and only if we are given a pair of digits $(u, v)$ or a pair of digits $(v, u)$. It's easy to see that the number is a representative of some class if and only if it doesn't have a substring of kind $[x, d_1, d_2, \\ldots, d_s, y]$, where $x > y$, and there are edges $(y, d_s), (y, d_{s - 1}), \\ldots, (y, d_1), (y, x)$ in the graph. Now, knowing the criterium, let's calculate $dp[suff][mask]$ - the number of equivalence classes if we have added $suff$ digits from right to left in our number and now we can move to front only digits from the $mask$. Let's go over the next digit $c$ that will be added to the left. If there is a digit $i$ in the mask such that $c > i$ and there is an edge $(c, i)$ in the graph, we cannot add digit $c$, because it will break our criterium. Otherwise we can add digit $c$, it remains to calculate the new mask. Firstly, there will be a digit $c$ in the new mask. Secondly, all digits $i > c$ such that digit $i$ was in the old $mask$ and there is an edge $(c, i)$ in the graph, will be in the new mask too. After that let's perform a transition from state $(suff, mask)$ to state $(suff + 1, newMask)$. The time complexity of this solution is $\\mathcal{O}(n \\cdot 2^\\Sigma \\cdot \\Sigma^2)$, where $\\Sigma$ is the size of the alphabet - $10$ for this problem. It's slow a bit, so we will optimize this solution. We can precalculate the $newMask$ for each pair $(c, mask)$ using the algorithm described above. After that, using this information, we can recalculate $dp$ faster. Time complexity: $\\mathcal{O}(2^\\Sigma \\cdot \\Sigma^2 + n \\cdot 2^\\Sigma \\cdot \\Sigma)$.",
    "tags": [
      "bitmasks",
      "dp",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1680",
    "index": "A",
    "title": "Minimums and Maximums",
    "statement": "An array is beautiful if both of the following two conditions meet:\n\n- there are \\textbf{at least} $l_1$ and \\textbf{at most} $r_1$ elements in the array equal to its minimum;\n- there are \\textbf{at least} $l_2$ and \\textbf{at most} $r_2$ elements in the array equal to its maximum.\n\nFor example, the array $[2, 3, 2, 4, 4, 3, 2]$ has $3$ elements equal to its minimum ($1$-st, $3$-rd and $7$-th) and $2$ elements equal to its maximum ($4$-th and $5$-th).\n\nAnother example: the array $[42, 42, 42]$ has $3$ elements equal to its minimum and $3$ elements equal to its maximum.\n\nYour task is to calculate the \\textbf{minimum} possible number of elements in a beautiful array.",
    "tutorial": "Firstly, since we are interested in minimum possible size of the array, we don't need any elements other than minimums and maximums. So, the array has at most $2$ distinct elements. Now there are many possible solutions. The simplest one is to iterate on the number of minimums (let this be $i$) and maximums (let this be $j$). If the number of minimums is equal to the number of maximums, then the array should have all elements as both its minimums and maximums, so its length should be $i$; otherwise, it should be $i + j$. We can iterate on all possible pairs $(i, j)$ and find the best result over all of them. A solution in $O(1)$ is possible if you see that you only have to consider $l_1$ and $l_2$ as the number of minimums/maximums, or check if the segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect in $O(1)$.",
    "code": "t = int(input())\nfor i in range(t):\n    l1, r1, l2, r2 = map(int, input().split())\n    if max(l1, l2) <= min(r1, r2):\n        print(max(l1, l2))\n    else:\n        print(l1 + l2)",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1680",
    "index": "B",
    "title": "Robots",
    "statement": "There is a field divided into $n$ rows and $m$ columns. Some cells are empty (denoted as E), other cells contain robots (denoted as R).\n\nYou can send a command to \\textbf{all robots} at the same time. The command can be of one of the four types:\n\n- move up;\n- move right;\n- move down;\n- move left.\n\nWhen you send a command, \\textbf{all robots at the same time} attempt to take one step in the direction you picked. If a robot tries to move outside the field, it explodes; otherwise, \\textbf{every robot} moves to an adjacent cell in the chosen direction.\n\nYou can send as many commands as you want (possibly, zero), in any order. Your goal is to make at least one robot reach the upper left corner of the field. Can you do this without forcing any of the robots to explode?",
    "tutorial": "Let's assume that the rows are numbered from $0$ to $n-1$ from top to bottom, and columns are numbered from $0$ to $m-1$ from left to right. If there is no robot in the cell $(0, 0)$ initially, we have to perform several moves up and/or left. If the first row with at least one robot is the $i$-th row, then we can make at most $i$ steps up (and we should do at least $i$ steps up, since otherwise there will me no robot in the upper row). Similarly, if the first column with at least one robot is the $j$-th column, then we can make at most $j$ steps to the left (and we should do at least $j$ steps to the left, since otherwise there will me no robot in the leftmost column). Now there are two possible solutions, both starting with finding $i$ and $j$: we afterwards either simulate $i$ moves up and $j$ moves to the left and check that everything is fine, or just check that there is a robot in the cell $(i, j)$ (since only this robot can end up in $(0, 0)$).",
    "code": "t = int(input())\nfor i in range(t):\n    n, m = map(int, input().split())\n    s = []\n    for j in range(n):\n        s.append(input())\n    minx = 10 ** 9\n    miny = 10 ** 9\n    for x in range(n):\n        for y in range(m):\n            if s[x][y] == 'R':\n                minx = min(minx, x)\n                miny = min(miny, y)\n    print('YES' if s[minx][miny] == 'R' else 'NO')",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1680",
    "index": "C",
    "title": "Binary String",
    "statement": "You are given a string $s$ consisting of characters 0 and/or 1.\n\nYou have to remove several (possibly zero) characters from the beginning of the string, and then several (possibly zero) characters from the end of the string. \\textbf{The string may become empty after the removals}. The cost of the removal is the \\textbf{maximum} of the following two values:\n\n- the number of characters 0 left in the string;\n- the number of characters 1 removed from the string.\n\nWhat is the \\textbf{minimum} cost of removal you can achieve?",
    "tutorial": "There are many different approaches to this problem: dynamic programming, binary search, greedy, two pointers, anything you want. The model solution uses an approach based on binary search, so I'll describe it. First of all, why does binary search work? Let's say that the number of 1's is $c$. If the cost of deletion is $k$, then we have deleted at most $k$ characters 1, and have left at most $k$ characters 0. Let's increase the number of characters we delete from the prefix of the string until the number of deleted 1's becomes $k+1$: if $c \\ge k+1$, it's always possible. So, if we consider the segment of values $[0, c]$, the fact that we can get cost $k$ implies that we can get cost $k+1$, so we can use binary search on segment $[0, c]$ to find the minimum achievable cost. Now, how to check if we can obtain the cost of deletion equal to $k$? One possible way to do this is to form an array $pos$, where $pos_i$ is the position of the $i$-th character 1 in the string, and find the minimum value of $pos_{i+c-k-1} - pos_i$ in this array: the string that should remain has to contain at least $c-k$ characters 1, and the minimum value of $pos_{i+c-k-1} - pos_i$ is the minimum possible length of such string. Then we can find the number of 0's in this string and check if it is greater than $k$ or not.",
    "code": "def can(pos, m):\n    k = len(pos) \n    x = k - m\n    for i in range(m + 1):\n        l = pos[i]\n        r = pos[i + x - 1]\n        if r - l + 1 - x <= m:\n            return True\n    return False    \n\nt = int(input())\nfor i in range(t):\n    s = input()\n    pos = []\n    n = len(s)\n    for i in range(n):\n        if s[i] == '1':\n            pos.append(i)\n    lf = 0\n    rg = len(pos)\n    while rg - lf > 1:\n        mid = (lf + rg) // 2\n        if can(pos, mid):\n            rg = mid\n        else:\n            lf = mid\n    if len(pos) == 0 or pos[-1] - pos[0] == len(pos) - 1:\n        print(0)\n    else:\n        print(rg)",
    "tags": [
      "binary search",
      "greedy",
      "strings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1680",
    "index": "D",
    "title": "Dog Walking",
    "statement": "You are walking with your dog, and now you are at the promenade. The promenade can be represented as an infinite line. Initially, you are in the point $0$ with your dog.\n\nYou decided to give some freedom to your dog, so you untied her and let her run for a while. Also, you watched what your dog is doing, so you have some writings about how she ran. During the $i$-th minute, the dog position changed from her previous position by the value $a_i$ (it means, that the dog ran for $a_i$ meters during the $i$-th minute). If $a_i$ is positive, the dog ran $a_i$ meters to the right, otherwise (if $a_i$ is negative) she ran $a_i$ meters to the left.\n\nDuring some minutes, you were chatting with your friend, so you don't have writings about your dog movement during these minutes. These values $a_i$ equal zero.\n\nYou want your dog to return to you after the end of the walk, so the destination point of the dog after $n$ minutes \\textbf{should be} $0$.\n\nNow you are wondering: what is the maximum possible number of different \\textbf{integer points} of the line your dog could visit on her way, if you replace every $0$ with some integer from $-k$ to $k$ (and your dog \\textbf{should} return to $0$ after the walk)? The dog visits an integer point if she runs through that point or reaches in it at the end of any minute. Point $0$ is always visited by the dog, since she is initially there.\n\nIf the dog cannot return to the point $0$ after $n$ minutes regardless of the integers you place, print -1.",
    "tutorial": "Consider every cyclic shift of the array $a$. Suppose that now the array $a$ starts from the position $i$ (the first element is $a[i]$ and the last element is $a[(i + n - 1) \\% n]$). Assume that before the position $i$ our dog reached her minimum possible position and now the minimum position will not change. So our problem is to fill all zeros in the array $a$ in such a way that the maximum prefix sum of $a$ is the maximum possible and the total sum of $a$ is zero. For simplicity, consider the array $b$ which is the $i$-th cyclic shift of $a$ (i. e. the first element $b[0]$ is $a[i]$, the second element $b[1]$ is $a[(i + 1) \\% n]$, and so on). Let's iterate from left to right and maintain the current sum of the array $b$. Let this variable be $s$. Now, when we meet $b_j = 0$, we should replace it with the maximum possible value we can (because in such a way we will increase the maximum number of prefix sums). Let $x$ be the number of zeros in $b$ starting from the position $j + 1$. This value can be calculated in advance in $O(n)$ for every cyclic shift using suffix sums. Then the segment of positions we can have at the end is $[s - xk; s + xk]$ and we want to place the maximum possible value in $b[j]$ in such a way that this remaining segment (with addition of our current element) will cover $0$. This maximum value equals $b[j] = min(k, xk - s)$. If $b[j]$ becomes less than $-k$ then this cyclic shift is invalid, and we should skip it. Otherwise, let's add $b[j]$ to $s$ and proceed. If there are no values $b[j] < -k$, then we placed anything correctly. Now can just simulate the movements of our dog to find the answer for the current cyclic shift. But there are cases when $a$ do not contain zeros, so these cases should be handled somehow (I just checked that after simulation we returned to $0$). If we returned to $0$, we can update the answer as the difference between the maximum and the minimum positions plus one. If there is no valid cyclic shift, then the answer is -1. Time complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int n;\n    long long k;\n    cin >> n >> k;\n    vector<long long> a(n);\n    for (auto &it : a) {\n        cin >> it;\n    }\n    \n    long long ans = 0;\n    for (int it = 0; it < n; ++it) {\n        vector<int> cnt(n);\n        for (int i = n - 1; i >= 0; --i) {\n            cnt[i] = (a[i] == 0);\n            if (i + 1 < n) {\n                cnt[i] += cnt[i + 1];\n            }\n        }\n        vector<long long> b = a;\n        long long s = accumulate(b.begin(), b.end(), 0ll);\n        bool ok = true;\n        for (int i = 0; i < n; ++i) {\n            if (b[i] == 0) {\n                long long x = (i + 1 < n ? cnt[i + 1] : 0);\n                b[i] = min(k, x * k - s);\n                if (b[i] < -k) {\n                    ok = false;\n                }\n                s += b[i];\n            }\n        }\n        if (ok) {\n            long long pos = 0, mn = 0, mx = 0;\n            for (int i = 0; i < n; ++i) {\n                pos += b[i];\n                mn = min(mn, pos);\n                mx = max(mx, pos);\n            }\n            if (pos == 0) {\n                ans = max(ans, mx - mn + 1);\n            }\n        }\n        rotate(a.begin(), a.begin() + 1, a.end());\n    }\n    \n    if (ans == 0) {\n        ans = -1;\n    }\n    \n    cout << ans << endl;\n    \n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1680",
    "index": "E",
    "title": "Moving Chips",
    "statement": "You are given a board of size $2 \\times n$ ($2$ rows, $n$ columns). Some cells of the board contain chips. The chip is represented as '*', and an empty space is represented as '.'. It is guaranteed that there is at least one chip on the board.\n\nIn one move, you can choose \\textbf{any} chip and move it to any adjacent (by side) cell of the board (if this cell is inside the board). It means that if the chip is in the first row, you can move it left, right or down (but it shouldn't leave the board). Same, if the chip is in the second row, you can move it left, right or up.\n\nIf the chip moves to the cell with another chip, the chip in the destination cell disappears (i. e. our chip captures it).\n\nYour task is to calculate the \\textbf{minimum} number of moves required to leave \\textbf{exactly} one chip on the board.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "Firstly, I want to say a few words about the difficulty of this problem. Till the last moment, we didn't know easy to prove (and easy to write) solutions, so we decided that this is a good problem E. But now we realized it is a lot easier than we expected. Now, let's talk about the solution. At the beginning, let's remove redundant columns from the beginning and from the end (i. e. columns without chips) and change the value $n$ correspondingly. Now, let $cost_{i, j}$ be $1$ if $s_{j, i}$ is '*', and $0$ otherwise. This array needed to make the implementation easier. Let's calculate the dynamic programming $dp_{i, j}$, where $i$ is the index of the last processed column and $j$ is the number of the row where our chip is standing. This seems a bit suspicious why we can calculate such a dynamic programming, so let's explain some things about it. It can be shown that in the optimal answer there will be some column where the last move happens. And if the number of this column is $j$ then all chips to the left of $j$ will move only to the right and all chips to the right of $j$ will move only to the left. Actually, we can always consider that $j$ is the last column. Consider paths of two chips that will survive till the last move. The first chip is to the left of $j$ and will move only to the right, and the second one is to the right of $j$ and will move only to the left. Then we can replicate the path of the second chip in the reverse order using the first chip. So the second chip can stay still until the last move. In the optimal answer, it is always better to have exactly one chip in the current column, because moving two chips to the right is always worse than just eat one of them and move the remaining one. Initial states of $dp$ are $+\\infty$ except the values of the first column. For the first column, $dp_{0, 0} = cost_{0, 1}$ and $dp_{0, 1} = cost_{0, 0}$. The answer will be $min(dp_{n - 1, 0}, dp_{n - 1, 1})$. Okay, how to make transitions from $dp_{i, j}$? For all $i$ from $0$ to $n-2$, let's consider four cases: $dp_{i, 0} \\rightarrow dp_{i + 1, 0}$ - here we need one move to go to the next column and, probably, one more move to delete the figure in the second row in the column $i + 1$. So the transition seems like $dp_{i + 1, 0} = min(dp_{i + 1, 0}, dp_{i, 0} + 1 + cost_{i + 1, 1})$; $dp_{i, 1} \\rightarrow dp_{i + 1, 1}$ - same as the previous transition, $dp_{i + 1, 1} = min(dp_{i + 1, 1}, dp_{i, 1} + 1 + cost_{i + 1, 0})$; $dp_{i, 0} \\rightarrow dp_{i + 1, 1}$ - because the cost of this transition is always $2$ (the distance between these cells is $2$), we just go firstly to the right and then down (to ensure that we eat the figure in the first row). So the transition is $dp_{i + 1, 1} = min(dp_{i + 1, 1}, dp_{i, 0} + 2)$; $dp_{i, 1} \\rightarrow dp_{i + 1, 1}$ - same as the previous transition, $dp_{i + 1, 0} = min(dp_{i + 1, 0}, dp_{i, 1} + 2)$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int tc;\n    cin >> tc;\n    while (tc--) {\n        int n;\n        string s[2];\n        cin >> n >> s[0] >> s[1];\n        \n        for (int it = 0; it < 2; ++it) {\n            while (s[0].back() == '.' && s[1].back() == '.') {\n                s[0].pop_back();\n                s[1].pop_back();\n            }\n            reverse(s[0].begin(), s[0].end());\n            reverse(s[1].begin(), s[1].end());\n        }\n        n = s[0].size();\n        \n        vector<vector<int>> cost(n, vector<int>(2));\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < 2; ++j) {\n                cost[i][j] = (s[j][i] == '*');\n            }\n        }\n        \n        vector<vector<int>> dp(n, vector<int>(2, INF));\n        dp[0][0] = cost[0][1];\n        dp[0][1] = cost[0][0];\n        for (int i = 0; i + 1 < n; ++i) {\n            dp[i + 1][0] = min(dp[i + 1][0], dp[i][0] + 1 + cost[i + 1][1]);\n            dp[i + 1][0] = min(dp[i + 1][0], dp[i][1] + 2);\n            dp[i + 1][1] = min(dp[i + 1][1], dp[i][1] + 1 + cost[i + 1][0]);\n            dp[i + 1][1] = min(dp[i + 1][1], dp[i][0] + 2);\n        }\n        \n        cout << min(dp[n - 1][0], dp[n - 1][1]) << endl;\n    }\n        \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1680",
    "index": "F",
    "title": "Lenient Vertex Cover",
    "statement": "You are given a simple connected undirected graph, consisting of $n$ vertices and $m$ edges. The vertices are numbered from $1$ to $n$.\n\nA vertex cover of a graph is a set of vertices such that each edge has at least one of its endpoints in the set.\n\nLet's call a lenient vertex cover such a vertex cover that \\textbf{at most one} edge in it has both endpoints in the set.\n\nFind a lenient vertex cover of a graph or report that there is none. If there are multiple answers, then print any of them.",
    "tutorial": "Let's think about why we can't always make a perfect vertex cover - such a vertex cover that each edge has exactly one endpoint in it. Or why the answer can not exist at all. Consider a bamboo. It's always possible to find a perfect vertex cover. Just choose every other vertex in it and account for parity. Make a bamboo into a loop. Now you can see that an even length loop has a perfect vertex cover. An odd length doesn't. That tells us that each odd length loop in a graph will have a bad edge on it. Odd length loops should instantly make you think about bipartite colorings. So we can see that a bipartite graph always has a perfect vertex cover. Just choose one of the parts into a cover, and each edge will have exactly one endpoint in it. At the same time, a non-bipartite graph never has a perfect cover. So our general goal is to remove (basically, mark as bad) at most one edge in such a way that the remaining graph is bipartite. Consider a dfs tree of the graph, colored bipartitely. Every edge in the tree is good (has endpoints in different parts). Every edge outside the tree can be either good or bad. What happens to the tree if we remove an edge? If we remove an edge outside the dfs tree, then nothing happens to it. So if there is no more than one bad edge outside the tree, then we found the answer. That was the easy part. Now what happens if we remove an edge from the tree? The back edges from the subtree of the edge can force the subtree to either remain colored the same or flip all its colors. We don't really care if it remains the same, because we already took care of it in the first part. So let's pretend it always flips the colors. Thus, all edges that go from the subtree upwards above the removed edge, have only one of their endpoints colors changed. Good edges turn bad, bad edges turn good. All other edges don't change. So you should choose such an edge to remove that all bad edges in the graph go from its subtree upwards above that edge and no good edges go from its subtree upwards above that edge. That can be calculated with a dfs. Since all non-tree edges in the dfs tree are back edges, you can simply increment a counter on the bottom vertex, decrement the counter on the top vertex and collect sums from the bottom. The sum in the vertex will tell you the number of edges that start below or in the vertex and end above the vertex. Do this for both kinds of edge and check the conditions for all vertices. Finally, choose such a part to be a vertex cover that the removed edge has both ends in it (if you choose the other part, that edge won't be covered at all). The solution is linear, but the problem still requires a massive time and memory limit only because of recursion in the dfs. Overall complexity: $O(n + m)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nvector<vector<int>> g, h;\nvector<int> tin, tout, clr;\nvector<vector<int>> sum(2);\nint T;\n\nint flip;\nint cnt;\n\nbool isp(int v, int u){\n    return tin[v] <= tin[u] && tout[v] >= tout[u];\n}\n\nvoid init(int v){\n    tin[v] = T++;\n    for (int u : g[v]){\n        if (clr[u] == -1){\n            clr[u] = clr[v] ^ 1;\n            h[v].push_back(u);\n            init(u);\n        }\n        else if (tin[u] < tin[v]){\n            int dif = clr[v] ^ clr[u];\n            if (!dif){\n                flip = clr[v] ^ 1;\n                ++cnt;\n            }\n            --sum[dif][u];\n            ++sum[dif][v]; \n        }\n    }\n    tout[v] = T;\n}\n\nint sv;\n\nvoid dfs(int v){\n    for (int u : h[v]){\n        dfs(u);\n        if (sum[0][u] == cnt && sum[1][u] == 1){\n            sv = u;\n            flip = clr[v] ^ 1;\n        }\n        forn(i, 2) sum[i][v] += sum[i][u];\n    }\n}\n\nint main() {\n    cin.tie(0);\n    iostream::sync_with_stdio(false);\n    int t;\n    cin >> t;\n    forn(_, t){\n        int n, m;\n        cin >> n >> m;\n        g.assign(n, vector<int>());\n        h.assign(n, vector<int>());\n        forn(i, m){\n            int v, u;\n            cin >> v >> u;\n            --v, --u;\n            g[v].push_back(u);\n            g[u].push_back(v);\n        }\n        tin.resize(n);\n        tout.resize(n);\n        forn(i, 2) sum[i].assign(n, 0);\n        clr.assign(n, -1);\n        cnt = 0;\n        T = 0;\n        clr[0] = 0;\n        init(0);\n        if (cnt <= 1){\n            cout << \"YES\\n\";\n            forn(v, n) cout << (clr[v] ^ flip);\n            cout << \"\\n\";\n            continue;\n        }\n        sv = -1;\n        dfs(0);\n        if (sv == -1){\n            cout << \"NO\\n\";\n        }\n        else{\n            cout << \"YES\\n\";\n            forn(v, n) cout << (clr[v] ^ isp(sv, v) ^ flip);\n            cout << \"\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1681",
    "index": "A",
    "title": "Game with Cards",
    "statement": "Alice and Bob play a game. Alice has $n$ cards, the $i$-th of them has the integer $a_i$ written on it. Bob has $m$ cards, the $j$-th of them has the integer $b_j$ written on it.\n\nOn the first turn of the game, \\textbf{the first player} chooses one of his/her cards and puts it on the table (plays it). On the second turn, \\textbf{the second player} chooses one of his/her cards \\textbf{such that the integer on it is greater than the integer on the card played on the first turn}, and plays it. On the third turn, \\textbf{the first player} chooses one of his/her cards \\textbf{such that the integer on it is greater than the integer on the card played on the second turn}, and plays it, and so on — the players take turns, and each player has to choose one of his/her cards with greater integer than the card played by the other player on the last turn.\n\nIf some player cannot make a turn, he/she loses.\n\nFor example, if Alice has $4$ cards with numbers $[10, 5, 3, 8]$, and Bob has $3$ cards with numbers $[6, 11, 6]$, the game may go as follows:\n\n- Alice can choose any of her cards. She chooses the card with integer $5$ and plays it.\n- Bob can choose any of his cards with number greater than $5$. He chooses a card with integer $6$ and plays it.\n- Alice can choose any of her cards with number greater than $6$. She chooses the card with integer $10$ and plays it.\n- Bob can choose any of his cards with number greater than $10$. He chooses a card with integer $11$ and plays it.\n- Alice can choose any of her cards with number greater than $11$, but she has no such cards, so she loses.\n\nBoth Alice and Bob play \\textbf{optimally (if a player is able to win the game no matter how the other player plays, the former player will definitely win the game)}.\n\nYou have to answer two questions:\n\n- who wins if Alice is the first player?\n- who wins if Bob is the first player?",
    "tutorial": "Let the maximum card among all $n + m$ cards be $x$. If only one player has a card of value of $x$, then he/she can win by playing it on the first turn or on the second turn; the opponent won't be able to respond with any of their cards. Otherwise (if both players have a card with value $x$), the player who plays this card earlier wins the game. So, in this case, the winner is the player who makes the first turn.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n    m = int(input())\n    b = list(map(int, input().split()))\n    \n    print('Alice' if max(a) >= max(b) else 'Bob')\n    print('Alice' if max(a) > max(b) else 'Bob')",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1681",
    "index": "B",
    "title": "Card Trick",
    "statement": "Monocarp has just learned a new card trick, and can't wait to present it to you. He shows you the entire deck of $n$ cards. You see that the values of cards from the topmost to the bottommost are integers $a_1, a_2, \\dots, a_n$, and all values are different.\n\nThen he asks you to shuffle the deck $m$ times. With the $j$-th shuffle, you should take $b_j$ topmost cards and move them under the remaining $(n - b_j)$ cards without changing the order.\n\nAnd then, using some magic, Monocarp tells you the topmost card of the deck. However, you are not really buying that magic. You tell him that you know the topmost card yourself. Can you surprise Monocarp and tell him the topmost card before he shows it?",
    "tutorial": "The easiest way to solve to problem is probably to see the resemblense of a shuffle operation to an std::rotate function. So you can obtain the final deck by applying cyclic shifts of the deck by $b_1$, then $b_2$ and so on. Since the shifts are cyclic, it doesn't matter if you shift by $x$ or by $x + n$ or by $x + k \\cdot x$ for any non-negative $k$. The result will be the same. Thus, you can calculate the sum of rotations you apply, and subtract $n$, until it becomes less than $n$. That is taking it modulo $n$. Finally, after rotating a sequence by some $x$, the $x$-th element of it ($0$-indexed) becomes the first one. Thus, you just want to print the ($sum \\bmod n$)-th element of $a$. Overall complexity: $O(n + m)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\tm = int(input())\n\tprint(a[sum(map(int, input().split())) % n])",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1681",
    "index": "C",
    "title": "Double Sort",
    "statement": "You are given two arrays $a$ and $b$, both consisting of $n$ integers.\n\nIn one move, you can choose two indices $i$ and $j$ ($1 \\le i, j \\le n$; $i \\neq j$) and swap $a_i$ with $a_j$ and $b_i$ with $b_j$. You have to perform the swap in both arrays.\n\nYou are allowed to perform at most $10^4$ moves (possibly, zero). Can you make both arrays sorted in a non-decreasing order at the end? If you can, print any sequence of moves that makes both arrays sorted.",
    "tutorial": "Imagine that all elements of $a$ are distinct. This way, sorting $a$ in increasing order will fix the order of $b$. If $b$ turns out sorted in a non-decreasing order, then the answer exists. Otherwise, it doesn't. To obtain the sequence of swaps, you can sort $a$ with any comparison-based sorting algorithm you want: even bubble sort will not exceed the allowed number of swaps. What changes if $a$ has repeated elements? Distinct elements are still ordered among themselves, but now there are also blocks of equal elements. For each block, look into the corresponding values in $b$. Obviously, these have to be sorted in a non-decreasing order. Rearrange them as they should be. In fact, this is exactly the same as sorting the sequence of pairs $(a_i, b_i)$ with a default comparator - first by $a_i$, then by $b_i$. Since we fixed the wanted order, we can proceed with the same steps we made in a distinct case. Overall complexity: $O(n \\log n)$ or $O(n^2)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\tb = list(map(int, input().split()))\n\ttmp = [i for i in range(n)]\n\ttmp.sort(key=lambda i: [a[i], b[i]])\n\tfor i in range(n - 1):\n\t\tif a[tmp[i]] > a[tmp[i + 1]] or b[tmp[i]] > b[tmp[i + 1]]:\n\t\t\tprint(\"-1\")\n\t\t\tbreak\n\telse:\n\t\tans = []\n\t\tfor i in range(n - 1):\n\t\t\tfor j in range(n - 1):\n\t\t\t\tif a[j] > a[j + 1] or b[j] > b[j + 1]:\n\t\t\t\t\ta[j], a[j + 1] = a[j + 1], a[j]\n\t\t\t\t\tb[j], b[j + 1] = b[j + 1], b[j]\n\t\t\t\t\tans.append([j + 1, j + 2])\n\t\tprint(len(ans))\n\t\tfor it in ans:\n\t\t\tprint(*it)",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1681",
    "index": "D",
    "title": "Required Length",
    "statement": "You are given two integer numbers, $n$ and $x$. You may perform several operations with the integer $x$.\n\nEach operation you perform is the following one: choose any digit $y$ that occurs in the decimal representation of $x$ at least once, and replace $x$ by $x \\cdot y$.\n\nYou want to make the length of decimal representation of $x$ (without leading zeroes) equal to $n$. What is the minimum number of operations required to do that?",
    "tutorial": "One of the possible approaches to this problem is to try multiplying $x$ only by the largest digit in it. Unfortunately, this doesn't work quite well, since it gives WA on one of the examples. That example is too big to consider, but a smaller version of it can prove that this is an incorrect solution: let $n = 5$, $x = 403$. If we multiply $403$ by $4$, we get $1612$, and there's no way to obtain a number with $5$ digits using the next action. But, if we multiply $403$ by $3$, we get $1209$, which can then be multiplied by $9$ to obtain a $5$-digit number. So, considering only the largest digit is not enough. This implies that we somehow need to consider the options that are not optimal locally, but optimal globally (i. e. choose a lower digit right now to obtain a higher digit in the future). Let's try to estimate the number of possible integers that can be obtained using these operations to see if we can consider all possible options. The key observation is that each integer we obtain will have the form $x \\cdot 2^a \\cdot 3^b \\cdot 5^c \\cdot 7^d$, since only one-digit primes can be added to the factorization. Since we consider only numbers less than $10^{19}$, $a$ is not greater than $63$, $b$ is not greater than $39$, $c$ is not greater than $27$, and $d$ is not greater than $22$, and the number of reachable integers is about $1.5$ million (note that this is a very generous bound since not all combinations of $(a,b,c,d)$ yield an integer less than $10^{19}$, and not all such integers can be reached with the operations). This allows us to use BFS or dynamic programming to calculate the answer.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{   \n    int n;\n    cin >> n;\n    long long v;\n    cin >> v;\n    queue<long long> q;\n    map<long long, int> dist;\n    dist[v] = 0;\n    q.push(v);\n    while(!q.empty())\n    {\n        long long k = q.front();\n        q.pop();\n        string s = to_string(k);\n        if(s.size() == n)\n        {\n            cout << dist[k] << endl;\n            return 0;\n        }\n        for(auto x : s)\n        {\n            if(x == '0') continue;\n            long long w = k * int(x - '0');\n            if(!dist.count(w))\n            {\n                dist[w] = dist[k] + 1;\n                q.push(w);\n            }\n        }\n    }\n    cout << -1 << endl;\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "hashing",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1681",
    "index": "E",
    "title": "Labyrinth Adventures",
    "statement": "You found a map of a weirdly shaped labyrinth. The map is a grid, consisting of $n$ rows and $n$ columns. The rows of the grid are numbered from $1$ to $n$ from bottom to top. The columns of the grid are numbered from $1$ to $n$ from left to right.\n\nThe labyrinth has $n$ layers. The first layer is the bottom left corner (cell $(1, 1)$). The second layer consists of all cells that are in the grid and adjacent to the first layer by a side or a corner. The third layer consists of all cells that are in the grid and adjacent to the second layer by a side or a corner. And so on.\n\nThe labyrinth with $5$ layers, for example, is shaped as follows:\n\nThe layers are separated from one another with walls. However, there are doors in these walls.\n\nEach layer (except for layer $n$) has exactly two doors to the next layer. One door is placed on the top wall of the layer and another door is placed on the right wall of the layer. For each layer from $1$ to $n-1$ you are given positions of these two doors. The doors can be passed in both directions: either from layer $i$ to layer $i+1$ or from layer $i+1$ to layer $i$.\n\nIf you are standing in some cell, you can move to an adjacent by a side cell if a wall doesn't block your move (e.g. you can't move to a cell in another layer if there is no door between the cells).\n\nNow you have $m$ queries of sort: what's the minimum number of moves one has to make to go from cell $(x_1, y_1)$ to cell $(x_2, y_2)$.",
    "tutorial": "WLOG, assume all queries ask to move from a lower layer to a higher layer. The first thing to notice in the problem is that it is always optimal to never go down a layer. You have an optimal path that is going down some layers, and then returning to the same layer. So it leaves a layer in some its cell and returns to it in some other cell (or the same one). The best distance it can achieve is the Manhattan distance between these two cells. However, we can also achieve the Manhattan distance by just going along this layer, and the answer will be at least as optimal. If the query asks about the cells of the same layer, just answer with the Manhattan distance. Otherwise, we can describe the path as follows: go from the first cell to some door on its layer, enter the door and go to another door on the next layer, so on until the layer of the second cell, where you go from a door to the second cell. Thus, we could potentially write $dp_{i,j}$ - the shortest distance from the start to the $j$-th door of the $i$-th layer. Initialize both doors of the first layer, take the best answer from the both doors of the last layer. That would be $O(n)$ per query, which is too slow. Let's optimize it with some precalculations. In particular, we want to know the shortest distance between one door of some layer and one door of another layer. We can use the technique similar to binary lifting. Calculate the distance between a pair of doors on layers which are $2^x$ apart for all $x$ up to $\\log n$. Let $dp_{i,x,d1,d2}$ be the distance from door $d1$ of layer $i$ to door $d2$ of layer $i+2^x$. $dp_{i,0,d1,d2}$ can be initialized straightforwardly. Then, to calculate $dp_{i,x,d1,d2}$, we can use the values for $x-1$: $dp_{i,x-1,d1,t}$ and $dp_{i+2^{x-1},x-1,t,d2}$ for some intermediate door $t$ on layer $i+2^{x-1}$. To obtain the answer, use $O(\\log n)$ jumps to reach the layer one before the last one. Then iterate over the last door. Alternatively, you could pack this dynamic programming into a segment tree, use divide and conquer on queries or do square root decomposition. Overall complexity: $O((n + m) \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst long long INF64 = 1e18;\n\ntypedef pair<int, int> pt;\n#define x first\n#define y second\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<vector<pt>> d(n - 1, vector<pt>(2));\n\tforn(i, n - 1) forn(j, 2){\n\t\tscanf(\"%d%d\", &d[i][j].x, &d[i][j].y);\n\t\t--d[i][j].x, --d[i][j].y;\n\t}\n\tint lg = 1;\n\twhile ((1 << lg) < n - 1) ++lg;\n\tvector<vector<vector<vector<long long>>>> dp(n - 2, vector<vector<vector<long long>>>(lg, vector<vector<long long>>(2, vector<long long>(2, INF64))));\n\tforn(i, n - 2) forn(k, 2){\n\t\tdp[i][0][0][k] = abs(d[i][0].x + 1 - d[i + 1][k].x) + abs(d[i][0].y - d[i + 1][k].y) + 1;\n\t\tdp[i][0][1][k] = abs(d[i][1].x - d[i + 1][k].x) + abs(d[i][1].y + 1 - d[i + 1][k].y) + 1;\n\t}\n\tfor (int l = 1; l < lg; ++l) forn(i, n - 2) forn(j, 2) forn(k, 2) forn(t, 2) if (i + (1 << (l - 1)) < n - 2){\n\t\tdp[i][l][j][k] = min(dp[i][l][j][k], dp[i][l - 1][j][t] + dp[i + (1 << (l - 1))][l - 1][t][k]);\n\t}\n\tint m;\n\tscanf(\"%d\", &m);\n\tforn(_, m){\n\t\tint x1, y1, x2, y2;\n\t\tscanf(\"%d%d%d%d\", &x1, &y1, &x2, &y2);\n\t\t--x1, --y1, --x2, --y2;\n\t\tint l1 = max(x1, y1), l2 = max(x2, y2);\n\t\tif (l1 > l2){\n\t\t\tswap(l1, l2);\n\t\t\tswap(x1, x2);\n\t\t\tswap(y1, y2);\n\t\t}\n\t\tif (l1 == l2){\n\t\t\tprintf(\"%d\\n\", abs(x1 - x2) + abs(y1 - y2));\n\t\t\tcontinue;\n\t\t}\n\t\tvector<long long> ndp(2);\n\t\tndp[0] = abs(x1 - d[l1][0].x) + abs(y1 - d[l1][0].y);\n\t\tndp[1] = abs(x1 - d[l1][1].x) + abs(y1 - d[l1][1].y);\n\t\tfor (int i = lg - 1; i >= 0; --i) if (l1 + (1 << i) < l2){\n\t\t\tvector<long long> tmp(2, INF64);\n\t\t\tforn(j, 2) forn(k, 2)\n\t\t\t\ttmp[k] = min(tmp[k], ndp[j] + dp[l1][i][j][k]);\n\t\t\tndp = tmp;\n\t\t\tl1 += (1 << i);\n\t\t}\n\t\tlong long ans = INF64;\n\t\tans = min(ans, ndp[0] + abs(d[l1][0].x + 1 - x2) + abs(d[l1][0].y - y2) + 1);\n\t\tans = min(ans, ndp[1] + abs(d[l1][1].x - x2) + abs(d[l1][1].y + 1 - y2) + 1);\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "matrices",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1681",
    "index": "F",
    "title": "Unique Occurrences",
    "statement": "You are given a tree, consisting of $n$ vertices. Each edge has an integer value written on it.\n\nLet $f(v, u)$ be the number of values that appear \\textbf{exactly once} on the edges of a simple path between vertices $v$ and $u$.\n\nCalculate the sum of $f(v, u)$ over all pairs of vertices $v$ and $u$ such that $1 \\le v < u \\le n$.",
    "tutorial": "Let's use contribution to the sum technique to simplify the problem. Instead of counting the number of colors that occure only once for each path, let's, for each color, count the number of paths that contain this color exactly once. Now we can solve the problem independently for each color, and sum up the answers. The first intended solution was the following. So we want to calculate the answer for some color $c$. Mark all edges of color $c$ as good, the rest are bad. Then we can calculate $dp_{v,i}$ - the number of paths up to vertex $v$ such that they contain either $0$ or $1$ good edges. The transitions should be pretty easy, and the answer should be updated when you consider gluing up paths from different children in each vertex. Obviously, this is $O(n)$ per color, so $O(n^2)$ overall. However, we can only calculate this dynamic programming as easily on a virtual tree of vertices adjacent to all good edges. How to calculate the dp for some vertex $v$? First, push the paths from all virtual children to $v$. That was enough in the dp for the entire tree but now there are also removed vertices that could also have paths starting in them. All these paths contain $0$ good edges (otherwise, they would have had virtual vertices on them). Their amount is the following: the size of the real subtree of $v$ minus the sizes of real subtrees of all its virtual children. The rest is exactly the same as in the dp on the real tree. A little fun trick. Usually, you want to add lca of adjacent vertices to the virtual tree. But that's actually not needed here: you can just add the root of the tree and link the vertices without a parent to them. That won't change the result of the dp. That solution works in $O(n \\log n)$ or $O(n)$. The second intended solution is slower complexity-wise but not time-wise. In the first solution we wanted to leave only the good edges in the tree. Here, we want to remove only them. Consider the resulting connected components. What's the number of paths that contain only one of the good edges? It's actually the product of sizes of the connected components this edge connects. So we want to remove edges, add edges and maintain the sizes of the connected components of the tree. That's basically the same problem as dynamic connectivity. The $O(n \\log^2 n)$ implementation works well enough.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct edge{\n\tint v, u, w;\n};\n\nvector<vector<edge>> t;\n\nvoid add(int v, int l, int r, int L, int R, const edge &e){\n\tif (L >= R)\n\t\treturn;\n\tif (l == L && r == R){\n\t\tt[v].push_back(e);\n\t\treturn;\n\t}\n\tint m = (l + r) / 2;\n\tadd(v * 2, l, m, L, min(m, R), e);\n\tadd(v * 2 + 1, m, r, max(m, L), R, e);\n}\n\nvector<int> rk, p;\nvector<int*> where;\nvector<int> val;\n\nint getp(int a){\n\treturn a == p[a] ? a : getp(p[a]);\n}\n\nvoid unite(int a, int b){\n\ta = getp(a), b = getp(b);\n\tif (a == b) return;\n\tif (rk[a] < rk[b]) swap(a, b);\n\twhere.push_back(&rk[a]);\n\tval.push_back(rk[a]);\n\trk[a] += rk[b];\n\twhere.push_back(&p[b]);\n\tval.push_back(p[b]);\n\tp[b] = a;\n}\n\nvoid rollback(){\n\t*where.back() = val.back();\n\twhere.pop_back();\n\tval.pop_back();\n}\n\nlong long trav(int v, int l, int r){\n\tint sv = where.size();\n\tfor (auto it : t[v]) if (it.w == 0)\n\t\tunite(it.v, it.u);\n\tlong long res = 0;\n\tif (l == r - 1){\n\t\tfor (auto it : t[v]) if (it.w == 1)\n\t\t\tres += rk[getp(it.v)] * 1ll * rk[getp(it.u)];\n\t}\n\telse{\n\t\tint m = (l + r) / 2;\n\t\tres += trav(v * 2, l, m);\n\t\tres += trav(v * 2 + 1, m, r);\n\t}\n\twhile (int(where.size()) > sv) rollback();\n\treturn res;\n}\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<edge> e(n - 1);\n\tforn(i, n - 1){\n\t\tscanf(\"%d%d%d\", &e[i].v, &e[i].u, &e[i].w);\n\t\t--e[i].v, --e[i].u, --e[i].w;\n\t}\n\tsort(e.begin(), e.end(), [](const edge &a, const edge &b){\n\t\treturn a.w < b.w;\n\t});\n\tt.resize(4 * n);\n\tforn(i, n - 1){\n\t\tint pos = lower_bound(e.begin(), e.end(), e[i], [](const edge &a, const edge &b){\n\t\t\treturn a.w < b.w;\n\t\t}) - e.begin();\n\t\tadd(1, 0, n, 0, pos, {e[i].v, e[i].u, 0});\n\t\tadd(1, 0, n, pos, pos + 1, {e[i].v, e[i].u, 1});\n\t\tadd(1, 0, n, pos + 1, n, {e[i].v, e[i].u, 0});\n\t}\n\trk.resize(n, 1);\n\tp.resize(n);\n\tiota(p.begin(), p.end(), 0);\n\tprintf(\"%lld\\n\", trav(1, 0, n));\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dp",
      "dsu",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1682",
    "index": "A",
    "title": "Palindromic Indices",
    "statement": "You are given a \\textbf{palindromic} string $s$ of length $n$.\n\nYou have to count the number of indices $i$ $(1 \\le i \\le n)$ such that the string after removing $s_i$ from $s$ still remains a palindrome.\n\nFor example, consider $s$ = \"aba\"\n\n- If we remove $s_1$ from $s$, the string becomes \"ba\" which is not a palindrome.\n- If we remove $s_2$ from $s$, the string becomes \"aa\" which is a palindrome.\n- If we remove $s_3$ from $s$, the string becomes \"ab\" which is not a palindrome.\n\nA palindrome is a string that reads the same backward as forward. For example, \"abba\", \"a\", \"fef\" are palindromes whereas \"codeforces\", \"acd\", \"xy\" are not.",
    "tutorial": "Read the statement carefully!! The given string is a palindrome. Let's remove some index $i$ from the first half of $s$ and check whether the resulting string is a palindrome or not, the other half has the same approach. The prefix of length $i-1$ already matches with the suffix of the same length because the initial string was a palindrome, so we just need to check if $t = s[i + 1 \\ldots n - i + 1]$ is a palindrome. For $t$ to be a palindrome, $s_{n - i + 1}$ should be equal to $s_{i + 1}$ which was initially equal to $s_{n - i}$, again which should be equal to $s_{i + 2}$ and this goes on. Here we can see that $s_i = s_{i + 1} \\ldots = s_{n - i + 1}$. So the answer is simply equal to the number of contiguous same characters in the center of the string which can be calculated in $\\mathcal{O(n)}$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std ;\n\n#define ll              long long \n#define pb              push_back\n#define all(v)          v.begin(),v.end()\n#define sz(a)           (ll)a.size()\n#define F               first\n#define S               second\n#define INF             2000000000000000000\n#define popcount(x)     __builtin_popcountll(x)\n#define pll             pair<ll,ll>\n#define pii             pair<int,int>\n#define ld              long double\n\ntemplate<typename T, typename U> static inline void amin(T &x, U y){ if(y < x) x = y; }\ntemplate<typename T, typename U> static inline void amax(T &x, U y){ if(x < y) x = y; }\n\n#ifdef LOCAL\n#define debug(...) debug_out(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define debug(...) 2401\n#endif\n\n\nint _runtimeTerror_()\n{\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    int cnt = 0;\n    for(int i=(n-1)/2;i>=0;--i) {\n    \tif(s[i] == s[(n - 1) / 2]) {\n    \t\t++cnt;\n    \t}\n    \telse {\n    \t\tbreak;\n    \t}\n    }\n    cout << 2 * cnt - (n & 1) << \"\\n\";\n    return 0;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    #ifdef runSieve\n        sieve();\n    #endif\n    #ifdef NCR\n        initncr();\n    #endif\n    int TESTS = 1;\n    cin >> TESTS;\n    while(TESTS--) {\n        _runtimeTerror_();\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1682",
    "index": "B",
    "title": "AND Sorting",
    "statement": "You are given a permutation $p$ of integers from $0$ to $n-1$ (each of them occurs exactly once). Initially, the permutation is \\textbf{not sorted} (that is, $p_i>p_{i+1}$ for at least one $1 \\le i \\le n - 1$).\n\nThe permutation is called $X$-sortable for some non-negative integer $X$ if it is possible to sort the permutation by performing the operation below some finite number of times:\n\n- Choose two indices $i$ and $j$ $(1 \\le i \\lt j \\le n)$ such that $p_i \\& p_j = X$.\n- Swap $p_i$ and $p_j$.\n\nHere $\\&$ denotes the bitwise AND operation.\n\nFind the \\textbf{maximum} value of $X$ such that $p$ is $X$-sortable. It can be shown that there always exists some value of $X$ such that $p$ is $X$-sortable.",
    "tutorial": "You must have to make at least one swap on the elements which are not at their correct positions initially. So $X$ must be a submask of all elements which are not at their correct positions. What is the maximum possible value of $X$ from Hint $1$? It is the bitwise AND of all elements which are not at their correct positions. It turns out that this value is achievable too. We always have to make at least one swap for the elements which are not at their correct positions. Hence an upper bound of answer would be the bitwise AND of those elements. Let the value be $X$. It turns out that the given permutation is $X$-sortable. Proof: First, notice that $X$ would always be present in $p$. Let $pos_x$ be the position of $X$ in $p$ initially. Let's say at some point we want to swap two values $p_i$ and $p_j$, then $p_i$ and $p_j$ would always be a supermask of $X$ i.e. $p_i$ & $X = X$ and $p_j$ & $X = X$. We can make the following moves to swap $p_i$ and $p_j$ without disturbing any other element. Swap values at indices $i$ and $pos_x$. Swap values at indices $i$ and $j$. Swap values at indices $j$ and $pos_x$. It can be seen that in every swap the bitwise AND of two values which we are swapping is always $X$. Hence we can swap any two values which were not at their correct positions, therefore we can sort the permutation $p$. Overall Complexity: $\\mathcal{O(n)}$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std ;\n\n#define ll              long long \n#define pb              push_back\n#define all(v)          v.begin(),v.end()\n#define sz(a)           (ll)a.size()\n#define F               first\n#define S               second\n#define INF             2000000000000000000\n#define popcount(x)     __builtin_popcountll(x)\n#define pll             pair<ll,ll>\n#define pii             pair<int,int>\n#define ld              long double\n\ntemplate<typename T, typename U> static inline void amin(T &x, U y){ if(y < x) x = y; }\ntemplate<typename T, typename U> static inline void amax(T &x, U y){ if(x < y) x = y; }\n\n#ifdef LOCAL\n#define debug(...) debug_out(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define debug(...) 2401\n#endif\n\n\nint _runtimeTerror_()\n{\n    int n;\n    cin >> n;\n    int ans = (1 << 30) - 1;\n    for(int i=0;i<n;++i) {\n    \tint x;\n    \tcin >> x;\n    \tif(x != i) {\n    \t\tans &= x;\n    \t}\n    }\n    cout << ans << \"\\n\";\n    return 0;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    #ifdef runSieve\n        sieve();\n    #endif\n    #ifdef NCR\n        initncr();\n    #endif\n    int TESTS = 1;\n    cin >> TESTS;\n    while(TESTS--) {\n        _runtimeTerror_();\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1682",
    "index": "C",
    "title": "LIS or Reverse LIS?",
    "statement": "You are given an array $a$ of $n$ positive integers.\n\nLet $\\text{LIS}(a)$ denote the length of longest strictly increasing subsequence of $a$. For example,\n\n- $\\text{LIS}([2, \\underline{1}, 1, \\underline{3}])$ = $2$.\n- $\\text{LIS}([\\underline{3}, \\underline{5}, \\underline{10}, \\underline{20}])$ = $4$.\n- $\\text{LIS}([3, \\underline{1}, \\underline{2}, \\underline{4}])$ = $3$.\n\nWe define array $a'$ as the array obtained after reversing the array $a$ i.e. $a' = [a_n, a_{n-1}, \\ldots , a_1]$.\n\nThe beauty of array $a$ is defined as $min(\\text{LIS}(a),\\text{LIS}(a'))$.\n\nYour task is to determine the maximum possible beauty of the array $a$ if you can rearrange the array $a$ arbitrarily.",
    "tutorial": "Let $\\text{LDS}(a)$ be the longest strictly decreasing subsequence of $a$, then $\\text{LIS}(a')$ = $\\text{LDS}(a)$. There can be at most one index common between $\\text{LIS}(a)$ and $\\text{LDS}(a)$. Let's make a small observation: There can be at most one index common to both $\\text{LIS}(a)$ and $\\text{LDS}(a)$. If some element $x$ occurs $\\geq 2$ times, then one of its occurrences can be included in $\\text{LIS}(a)$ and another one in $\\text{LDS}(a)$, and all the remaining occurrences are of no use because none of them can contain 2 equal elements. If some element $x$ is a singleton i.e. the frequency of $x$ in $a$ is $1$, then it can have $3$ positions In $\\text{LIS}(a)$ only. In $\\text{LDS}(a)$ only. The only common element of $\\text{LIS}(a)$ and $\\text{LDS}(a)$. It can be seen that it is always optimal to choose some singleton as the only common element (if available) because those with frequency $\\geq 2$ can easily contribute $1$ to both $\\text{LIS}(a)$ and $\\text{LDS}(a)$ easily. Let $t$ be the number of elements having frequency $\\geq 2$ and $s$ be the number of singletons in $a$. The singletons should be divided equally among $\\text{LIS}(a)$ and $\\text{LDS}(a)$ with one of them given to both, if available. Hence, the answer is $t + \\lceil \\frac{s}{2} \\rceil$. The values $s$ and $t$ can be found using some data structure like $\\text{std:map}$ in C++ in $\\mathcal{O}(n\\log(n))$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std ;\n\n#define ll              long long \n#define pb              push_back\n#define all(v)          v.begin(),v.end()\n#define sz(a)           (ll)a.size()\n#define F               first\n#define S               second\n#define INF             2000000000000000000\n#define popcount(x)     __builtin_popcountll(x)\n#define pll             pair<ll,ll>\n#define pii             pair<int,int>\n#define ld              long double\n\ntemplate<typename T, typename U> static inline void amin(T &x, U y){ if(y < x) x = y; }\ntemplate<typename T, typename U> static inline void amax(T &x, U y){ if(x < y) x = y; }\n\n#ifdef LOCAL\n#define debug(...) debug_out(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define debug(...) 2401\n#endif\n\n\nint _runtimeTerror_()\n{\n    int n;\n    cin >> n;\n    map<int, int> mp;\n    for(int i=1;i<=n;++i) {\n    \tint x;\n    \tcin >> x;\n    \t++mp[x];\n    }\n    int single = 0, doble = 0;\n    for(auto &[i, j]:mp) {\n    \tsingle += j == 1;\n    \tdoble += j > 1;\n    }\n    cout << doble + (single + 1) / 2 << \"\\n\";\n    return 0;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    #ifdef runSieve\n        sieve();\n    #endif\n    #ifdef NCR\n        initncr();\n    #endif\n    int TESTS = 1;\n    cin >> TESTS;\n    while(TESTS--) {\n        _runtimeTerror_();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1682",
    "index": "D",
    "title": "Circular Spanning Tree",
    "statement": "There are $n$ nodes arranged in a circle numbered from $1$ to $n$ in the clockwise order. You are also given a binary string $s$ of length $n$.\n\nYour task is to construct a tree on the given $n$ nodes satisfying the two conditions below or report that such tree does not exist:\n\n- For each node $i$ $(1 \\le i \\le n)$, the degree of node is even if $s_i = 0$ and odd if $s_i = 1$.\n- No two edges of the tree intersect internally in the circle. The edges are allowed to intersect on the circumference.\n\nNote that all edges are drawn as straight line segments. For example, edge $(u, v)$ in the tree is drawn as a line segment connecting $u$ and $v$ on the circle.\n\nA tree on $n$ nodes is a connected graph with $n - 1$ edges.",
    "tutorial": "What are the mandatory conditions on string $s$ for a tree to be possible? If there are no odd degree vertices or the count of odd degree vertices is odd, then it is impossible to construct any tree. It turns out that these conditions are sufficient too. Let's check some cases when it is not possible to construct the answer- When all vertices have an even degree, then there is no way to generate a tree because every tree contains at least $2$ leaves. When there are an odd number of vertices with odd degrees, then there is no tree possible because the sum of degrees must be even. It turns out that it is always possible to construct a tree if none of the above is true. The following construction works - Select some vertex $i$ such that the previous vertex of $i$ (assumed cyclically) has an odd degree i.e. $s_{i - 1} = 1$. Clearly, such a vertex always exists. Select some vertex $i$ such that the previous vertex of $i$ (assumed cyclically) has an odd degree i.e. $s_{i - 1} = 1$. Clearly, such a vertex always exists. Now left rotate $s$, $i - 1$ times such that the selected vertex is now at index $1$. Note that after the rotation $s_n$ will become $1$. Now we can see that $s[2\\ldots n]$ can be divided into several segments such that each segment ends with some vertex having an odd degree. And each segment should contain exactly one vertex with an odd degree. So $s[2 \\ldots n] = [0\\ldots 1][0\\ldots 1] \\ldots [0\\ldots 1]$ where $0$ may appear $0$ times. Connect vertex $1$ to the starting vertex of each segment and connect adjacent vertices inside each segment. It can be clearly seen that edges will never intersect internally. The only thing we need to verify is the degree constraints. Now left rotate $s$, $i - 1$ times such that the selected vertex is now at index $1$. Note that after the rotation $s_n$ will become $1$. Now we can see that $s[2\\ldots n]$ can be divided into several segments such that each segment ends with some vertex having an odd degree. And each segment should contain exactly one vertex with an odd degree. So $s[2 \\ldots n] = [0\\ldots 1][0\\ldots 1] \\ldots [0\\ldots 1]$ where $0$ may appear $0$ times. Connect vertex $1$ to the starting vertex of each segment and connect adjacent vertices inside each segment. It can be clearly seen that edges will never intersect internally. The only thing we need to verify is the degree constraints. Proof: The degree condition is valid for each segment, as each vertex with an even degree is connected with $2$ other vertices and the last vertex with an odd degree will be connected to only one vertex i.e it's previous one or vertex $1$ if it was only on its segment. Let $cnt_1$ be the number of vertices with odd degree. If $s_1 = 1$, then there will be $cnt_1 - 1$ segments which is an odd number, hence vertex $1$ will be connected to odd number of vertices. If $s_1 = 0$, then there will be $cnt_1$ segments which is an even number, hence vertex $1$ will be connected to even number of vertices. Note that we renumbered the vertices during rotation which should be handled in implementation. The intuition for the above approach comes from the case when all $s_i$ are $1$ in which we create a star network. Overall complexity: $\\mathcal{O(n)}$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n\n#define all(v)         v.begin(),v.end()\n#define endl           \"\\n\"\n\n\nint solve(){\n \t\tint n; cin >> n;\n \t\tstring s; cin >> s;\n \t\tauto cnt = count(all(s),'1');\n \t\tif(cnt == 0 or cnt & 1){\n \t\t\tcout << \"NO\" << endl;\n \t\t\treturn 0;\n \t\t}\n \t\tauto inc = [&](int j){\n\t\t \treturn (j + 1)%n;\n\t\t};\n \t\tcout << \"YES\" << endl;\n \t\tfor(int p = 1; p < n; p++){\n \t\t\tif(s[p - 1] == '1'){\n\t\t \t\tauto i = inc(p);\n\t\t \t\twhile(i != p){\n\t\t \t\t\tint j = i;\n\t\t \t\t\tint prev = p;\n\t\t \t\t\twhile(j != p){\n\t\t \t\t\t\tcout << prev + 1 << \" \" << j + 1 << endl;\n\t\t \t\t\t\tprev = j;\n\t\t \t\t\t\tj = inc(j);\n\t\t \t\t\t\tif(s[prev] == '1')break;\n\t\t \t\t\t}\n\t\t \t\t\ti = j;\n\t\t \t\t}\n\t\t \t\treturn 0;\n \t\t\t}\n \t\t}\n\n return 0;\n}\nsigned main(){\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #ifdef SIEVE\n    sieve();\n    #endif\n    #ifdef NCR\n    init();\n    #endif\n    int t=1;cin>>t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1682",
    "index": "E",
    "title": "Unordered Swaps",
    "statement": "Alice had a permutation $p$ of numbers from $1$ to $n$. Alice can swap a pair $(x, y)$ which means swapping elements at positions $x$ and $y$ in $p$ (i.e. swap $p_x$ and $p_y$). Alice recently learned her first sorting algorithm, so she decided to sort her permutation in the \\textbf{minimum} number of swaps possible. She wrote down all the swaps in the order in which she performed them to sort the permutation on a piece of paper.\n\nFor example,\n\n- $[(2, 3), (1, 3)]$ is a valid swap sequence by Alice for permutation $p = [3, 1, 2]$ whereas $[(1, 3), (2, 3)]$ is not because it doesn't sort the permutation. Note that we cannot sort the permutation in less than $2$ swaps.\n- $[(1, 2), (2, 3), (2, 4), (2, 3)]$ cannot be a sequence of swaps by Alice for $p = [2, 1, 4, 3]$ even if it sorts the permutation because $p$ can be sorted in $2$ swaps, for example using the sequence $[(4, 3), (1, 2)]$.\n\nUnfortunately, Bob shuffled the sequence of swaps written by Alice.\n\nYou are given Alice's permutation $p$ and the swaps performed by Alice in arbitrary order. Can you restore the correct sequence of swaps that sorts the permutation $p$? Since Alice wrote correct swaps before Bob shuffled them up, it is guaranteed that there exists some order of swaps that sorts the permutation.",
    "tutorial": "One way of solving permutation problems is to look at permutation cycles. Let's decompose our permutation into cycles, then it's easy to see that each cycle can be solved independently because we have to sort the permutation in a minimum number of moves which isn't possible if two cycles are merged at any instant. Let's look at one cycle only, whose vertices are numbered from $1$ to $n$ in the orientation of cycle i.e the cycle is $1 \\rightarrow 2 \\rightarrow \\ldots \\rightarrow n \\rightarrow 1$. Also assume that we only have swaps $(x, y)$ that are relevant to this cycle. It is known that we can sort a cycle of size $n$ in $n - 1$ moves and it is the minimum number of required moves. Claim 1: The set of swaps if considered as edges $(x, y)$ form a tree on the $n$ vertices of the cycle. Assume that the edges don't form a tree, then there exist at least two disjoint components let's say $S$ and $T$. Now we must be able to make swaps inside $S$ only, to sort elements in $S$ which needs that the set {$i, i \\in S$} is same as set {$p_i, i \\in S$} which is not possible by property of permutation cycles. Any cycle of permutation, say $C$, can't be split further into two sets $S$ and $T$ such that both of them can be sorted independently among themselves. So we must use all the $n - 1$ edges of the tree in some order to get $n$ cycles each of size $1$. Let's consider any element $u$ having adjacency list as $[x_1, x_2, ..., x_k]$ in the order they appear on the cycle if we start moving from $u$ in the orientation of cycle i.e $u \\rightarrow u + 1 \\rightarrow ... \\rightarrow n \\rightarrow 1 \\rightarrow ... \\rightarrow u$. Claim 2: We can never make the swap $(u, x_j)$ before swap $(u, x_i)$ if $j > i$. If we make the swap $(u, x_j)$ first, then $u$ and $x_i$ will go in different cycles for subsequent operations and we will never be able to use edge $(u, x_i)$ because it will merge the two different cycles which isn't possible because we are constrained to break a cycle into smaller cycles only. And if are not able to use edge $(u, x_i)$ then we will never be able to sort the permutation because we had $n - 1$ edges all of which were to be used and we wasted $1$ of them. Using above claim, for every element $u$ the order of edges is fixed i.e $x_1$, then $x_2$, ..., and finally $x_k$. Let's build a directed graph on $n - 1$ vertices (representing the swaps) where for every element $u$ we add directed edges $(u,x_1) \\rightarrow (u,x_2)$, ..., $(u,x_{k-1}) \\rightarrow (u,x_k)$. Since it is guaranteed that the answer will exist i.e a valid sequence of moves exist, hence the topological sorting of the above graph must exist, any of which represents a correct sequence of swaps. Note that whenever we make a swap that is not violating claim $2$ for any element $u$, then there will be no cross edge in two smaller cycles that are going to be formed and those smaller cycles can be further solved independently. Also the order of edges i.e $[x_1, x_2, ..., x_k]$ is not going to change for any element which ensures that the directed graph we built remains correct even if we remove some appropriate edge. Hence the answer is simply the topological sort of the graph we built. Overall Complexity: $\\mathcal{O(nlog(n))}$, $nlog(n)$ for sorting the edges according to cycle's orientation to get the order $[x_1, x_2, ..., x_k]$ for every vertex. Claim: The given swaps considered as edges $(x, y)$ forms a non-intersecting tree on $n$ vertices on the circle i.e no two edges intersect internally. Motivation for problem D Let's say edges $(a, b)$ and $(c, d)$ intersect internally in the circle. WLOG, let's suppose we make swap $(a, b)$ before swap $(c, d)$, then $c$ and $d$ will go in different cycles as in Claim $2$ above. What if you were given any tree on $n$ vertices and asked to solve the problem with \"YES/NO\"? If the given edges intersect internally in the circle then the answer is \"NO\" otherwise it's always possible to construct a valid sequence of swaps. This is what the validator of E and checker of D do, try this one, and feel free to discuss in the comments section. Let's make every edge $(u, v)$ such that $u \\lt v$, clearly the order of $u$, $v$ doesn't matter. Consider each edge as a segment $[u, v]$, then the edges of the tree intersect internally if and only if any two segments say $[l_1, r_1]$ and $[l_2, r_2]$ satisfies any of the below conditions- $l_1\\lt l_2 \\lt r_1 \\lt r_2$ $l_1\\lt l_2 \\lt r_1 \\lt r_2$ $l_2 \\lt l_1 \\lt r_2 \\lt r_1$ $l_2 \\lt l_1 \\lt r_2 \\lt r_1$ In the original problem, it was mentioned that there is always a correct sequence of swaps so we claimed that topological sorting must exist and indeed any topological sorting suffices. What if we were given a non-intersecting spanning tree? Can we still claim that there exists a correct move at every step? Claim: Yes, we can We need to show that there there is always some edge that can be removed without breaking claim $2$ above which is the only required condition. Cycles of length $\\le 2$ are trivial. Let's represent by $u_{next}$ the first element of the list $[x_1, x_2, ..., x_k]$ for $u$ i.e the closest vertex having an edge with $u$ in cycle's orientation. Now, let's start an iteration, start moving from $1$ and jump to $v_{next}$ every time when you are at vertex $v$. Continue this process until you again reach $1$ or cross over $1$. Let the sequence obtained be $s$ i.e $s_1 = 1, s_2, ..., s_k$ where on moving further from $s_k$ we cross/reach $1$. For simplicity assume $k \\ge 3$, $k = 2$ is trivial. It can be shown that $(s_{k-1}, s_k)$ is the required edge. $s_{k_{next}}$ lies between $s_{k-1}$ and $s_k$. There are three cases other that this: $s_{k_{next}}$ lies between $s_k$ and $1$, which is not possible because we would have moved further and $s_k$ would not be the last element of sequence $s$. $s_{k_{next}}$ lies between $s_k$ and $1$, which is not possible because we would have moved further and $s_k$ would not be the last element of sequence $s$. $s_{k_{next}}$ = $1$ which is not possible because it will create a cycle and we are given a tree. $s_{k_{next}}$ = $1$ which is not possible because it will create a cycle and we are given a tree. $s_{k_{next}}$ lies between $s_j$ and $s_{j+1}$ for $j \\le k-2$, this is also not possible because then the edges $(s_k, s_{k_{next}})$ and $(s_j, s_{j+1})$ will intersect and we are given a non-intersecting tree. $s_{k_{next}}$ lies between $s_j$ and $s_{j+1}$ for $j \\le k-2$, this is also not possible because then the edges $(s_k, s_{k_{next}})$ and $(s_j, s_{j+1})$ will intersect and we are given a non-intersecting tree. $s_{k}$ is first element of adjacency list of $s_{k-1}$ by the definition of $v_{next}$ and $s_{k-1}$ is the first element of adjacency list of $s_{k}$ by above 3 points. Hence it is safe to make the swap $(s_{k-1}, s_{k})$. So the topological sort still works. This might not be the only proof, if you have some other proofs feel free to discuss them in the comments. Hope you liked the details!! Any ideas on how to write a generator for this problem? Randomly partition the permutation into cycles, so generating swaps for a particular cycle is the main issue. Let's represent the cycle by an array $a$ of size $n$ with cycle as $a_1 \\rightarrow a_2 \\rightarrow ... \\rightarrow a_n \\rightarrow a_1$ Now let's start making random swaps say $(a_i, a_j)$ to break the cycle, then this generates two smaller cycles - $a_1 \\rightarrow a_2 \\rightarrow ... \\rightarrow a_i \\rightarrow a_{j+1} \\rightarrow ... \\rightarrow a_n \\rightarrow a_1$. $a_1 \\rightarrow a_2 \\rightarrow ... \\rightarrow a_i \\rightarrow a_{j+1} \\rightarrow ... \\rightarrow a_n \\rightarrow a_1$. $a_{i+1} \\rightarrow ... \\rightarrow a_j \\rightarrow a_{i+1}$. $a_{i+1} \\rightarrow ... \\rightarrow a_j \\rightarrow a_{i+1}$. This can be easily done using treaps :) and then we can use recursion to solve them independently. It's very rare!! Atleast first time for us.",
    "code": "#include<bits/stdc++.h>\nusing namespace std ;\n\n#define ll              long long \n#define pb              push_back\n#define all(v)          v.begin(),v.end()\n#define sz(a)           (ll)a.size()\n#define F               first\n#define S               second\n#define INF             2000000000000000000\n#define popcount(x)     __builtin_popcountll(x)\n#define pll             pair<ll,ll>\n#define pii             pair<int,int>\n#define ld              long double\n\ntemplate<typename T, typename U> static inline void amin(T &x, U y){ if(y < x) x = y; }\ntemplate<typename T, typename U> static inline void amax(T &x, U y){ if(x < y) x = y; }\n\n#ifdef LOCAL\n#define debug(...) debug_out(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define debug(...) 2401\n#endif\n\nconst int N = 2e5 + 5;\nvector<int> t_sort;\nint idx[N];\nint vs[N];\nvector<int> v[N];\n\nbool dfs_sort(int u)\n{\n    vs[u]=2;\n    for(auto j:v[u])\n    {\n        if(vs[j]==2)\n            return true;\n        if(vs[j]==0 && dfs_sort(j))\n            return true;\n    }\n    vs[u]=1;\n    t_sort.push_back(u);\n    return false;\n}\n\n// Returns true if there is a topological sort else returns false\nbool top_sort(int n)\n{\n    t_sort.clear();\n    for(int i=1;i<=n;++i)\n        vs[i]=0;\n    for(int i=1;i<=n;++i)\n    {\n        if(vs[i]==0)\n        {\n            if(dfs_sort(i))\n            {\n                t_sort.clear();\n                return false;\n            }\n        }\n    }\n    reverse(t_sort.begin(),t_sort.end());\n    assert(t_sort.size()==n);\n    for(int i=0;i<n;++i)\n        idx[t_sort[i]]=i;\n    return true;\n}\n\nint _runtimeTerror_()\n{\n    int n, k;\n    cin >> n >> k;\n    vector<int> p(n+1), a(k), b(k);\n    for(int i=1;i<=n;++i) {\n        cin >> p[i];\n    }\n\n    vector<vector<pii>> g(n+1);\n    for(int i=0;i<k;++i) {\n        int x, y;\n        cin >> x >> y;\n        a[i] = x, b[i] = y;\n        g[x].push_back({y, i + 1});\n        g[y].push_back({x, i + 1});\n    }    \n    vector<int> id(n+1);\n    vector<int> ans;\n    auto solve = [&](vector<int> &cyc) {\n        int n = sz(cyc);\n        if(n == 1) {\n            return;\n        }\n        for(int i=0;i<n;++i) {\n            id[cyc[i]] = i;\n        }\n        auto dist = [&](int x, int y) {\n            return (id[y] - id[x] + n) % n;\n        };\n        vector<int> good;\n        for(int i:cyc) {\n            sort(all(g[i]), [&](pii &a, pii &b) {\n                return dist(i, a.F) < dist(i, b.F);\n            });\n            for(int j=1;j<sz(g[i]);++j) {\n                v[g[i][j-1].S].push_back(g[i][j].S);\n            }\n        }\n    };\n    vector<bool> vis(n+1);\n    for(int i=1;i<=n;++i) {\n        if(vis[i]) {\n            continue;\n        }   \n        vector<int> cycle;\n        int cur = i;\n        while(!vis[cur]) {\n            cycle.push_back(cur);\n            vis[cur] = 1;\n            cur = p[cur];\n        }\n        solve(cycle);\n    }\n    top_sort(k);\n    for(auto i:t_sort) {\n        cout << i << \" \";\n    }\n    cout << \"\\n\";\n    return 0;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    #ifdef runSieve\n        sieve();\n    #endif\n    #ifdef NCR\n        initncr();\n    #endif\n    int TESTS = 1;\n    //cin >> TESTS;\n    while(TESTS--) {\n        _runtimeTerror_();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "math",
      "sortings",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1682",
    "index": "F",
    "title": "MCMF?",
    "statement": "You are given two integer arrays $a$ and $b$ ($b_i \\neq 0$ and $|b_i| \\leq 10^9$). Array $a$ is sorted in \\textbf{non-decreasing} order.\n\nThe cost of a subarray $a[l:r]$ is defined as follows:\n\n- If $ \\sum\\limits_{j = l}^{r} b_j \\neq 0$, then the cost is not defined.\n- Otherwise:\n\n- Construct a bipartite flow graph with $r-l+1$ vertices, labeled from $l$ to $r$, with all vertices having $b_i \\lt 0$ on the left and those with $b_i \\gt 0$ on right. For each $i, j$ such that $l \\le i, j \\le r$, $b_i<0$ and $b_j>0$, draw an edge from $i$ to $j$ with infinite capacity and cost of unit flow as $|a_i-a_j|$.\n- Add two more vertices: source $S$ and sink $T$.\n- For each $i$ such that $l \\le i \\le r$ and $b_i<0$, add an edge from $S$ to $i$ with cost $0$ and capacity $|b_i|$.\n- For each $i$ such that $l \\le i \\le r$ and $b_i>0$, add an edge from $i$ to $T$ with cost $0$ and capacity $|b_i|$.\n- The cost of the subarray is then defined as the minimum cost of maximum flow from $S$ to $T$.\n\nYou are given $q$ queries in the form of two integers $l$ and $r$. You have to compute the cost of subarray $a[l:r]$ for each query, modulo $10^9 + 7$.\n\nIf you don't know what the minimum cost of maximum flow means, read here.",
    "tutorial": "Let us suppose we need to calculate the answer for only one query, say complete array i.e $a[1:n]$. The scary flow structure in the problem can be reduced as- Let's replicate each vertex $i$, $|b_i|$ times. Then we can see that there will be an equal number of vertices on the left and right side. Now the problem reduces that we have to match these vertices with minimum cost such that the cost of matching $i$ and $j$ is $|a_i - a_j|$. There are only 2 type of elements (left side and right side) and the following greedy algorithm to match the elements works. Algorithm: Sort the type $1$ and $2$ elements independently and match them in the sorted order. Assume that two elements from left $l_1 \\le l_2$ are matched with two elements from right $r_1 \\le r_2$ as $[l_1, r_2]$ and $[l_2, r_1]$, then it can be easily shown that matching $[l_1, r_1]$ and $[l_2, r_2]$ is always more optimal. The proof is left as an excercise to reader. Since the array $a$ is given in sorted order, let's use it!! Let's assume- Type $1$ elements are those having $b_i \\lt 0$. Type $1$ elements are those having $b_i \\lt 0$. Type $2$ elements are those having $b_i \\gt 0$. Type $2$ elements are those having $b_i \\gt 0$. Now instead of replicating elements $|b_i|$ times and sorting them independently, let's iterate on array $a$ from left to right and add the contribution of each element independently. Say we are at index $i$, and prefix sum of $b_i$ so far is $psum_i$, then the following cases arise- $b_i \\gt 0$, $psum_i \\ge 0$ - There is no unmatched type $1$ element on the left, so we just add this element's contribution to the answer i.e $-b_i \\cdot a_i$. $b_i \\gt 0$, $psum_i \\ge 0$ - There is no unmatched type $1$ element on the left, so we just add this element's contribution to the answer i.e $-b_i \\cdot a_i$. $b_i \\gt 0$, $psum_i \\lt -b_i$ - There are more than $b_i$ unmatched type $1$ elements on the left, so we match $b_i$ of them to $a_i$, adding a contribution of $a_i \\cdot b_i$ to the answer. $b_i \\gt 0$, $psum_i \\lt -b_i$ - There are more than $b_i$ unmatched type $1$ elements on the left, so we match $b_i$ of them to $a_i$, adding a contribution of $a_i \\cdot b_i$ to the answer. $b_i \\gt 0$, $psum_i \\lt 0$ and $psum_i \\gt -b_i$ - There are less than $b_i$ unmatched elements ($= |psum_i|$) on the left, so we match those with equal number of $a_i$ and remaining are propagated further, adding a contribution of $|psum_i| * a_i - (b_i - |psum_i|) * a_i$, where the positive term comes from those matching with previous unmatched elements and the negative term comes from those that are going to be left unmatched. $b_i \\gt 0$, $psum_i \\lt 0$ and $psum_i \\gt -b_i$ - There are less than $b_i$ unmatched elements ($= |psum_i|$) on the left, so we match those with equal number of $a_i$ and remaining are propagated further, adding a contribution of $|psum_i| * a_i - (b_i - |psum_i|) * a_i$, where the positive term comes from those matching with previous unmatched elements and the negative term comes from those that are going to be left unmatched. Similar cases are there for $b_i \\lt 0$. Ok so now we can easily solve the problem for one query in $O(n)$. Main idea: Let's simulate the above algorithm for every suffix and record the obtained answer in $ans_i$ for $i^{th}$ suffix. Note that the value $ans_i$ doesn't denote any answer for some suffix because the sum of $b_i$ over that suffix might or might not be zero. One important observation here is that- Let some subarray $a[l:r]$ for which sum of $b_i$ is $0$, then $ans_l - ans_{r+1}$ do have a good meaning, it's the answer for that query indeed. Our answer for $a[l:r]$ would have been the result of simulation on the subarray, but how does simulation on $l^{th}$ suffix looks? It greedily matches the subarray $a[l:r]$ first because the sum of $b_i$ is zero, so it will surely pair up all elements in that subarray. Then it moves further on $r+1$ and continuing the simulation after $r+1$ is equivalent to starting the simulation from $r+1$ itself because $psum$ so far (defined above) would be automatically 0. Note that $ans_l$ doesn't have any physical meaning because it will add some junk value if elements after $r+1$ are not paired up equally but those junk values are exactly same in $ans_l$ and $ans_r$ which cancel out, giving the correct answer. But still, we can't simulate for every suffix, right? It would go $O(n^2)$ again. Let's iterate from left to right and for every $i$ try calculating it's contribution in $1^{st}$, $2^{nd}$, ..., $(i-1)^{th}$ suffixes which is easy because it depends only on $psum_i$, $b_i$ (which are constant for a given $i$) and $psum_l$ for contribution to $l^{th}$ suffix. This is pretty standard using $2$ fenwick trees. How to calculate $ans_i$? Let's solve $b_i \\gt 0$ and $b_i \\lt 0$ independently, say $b_i \\gt 0$ for now. Other case is similar. Let $psum_i = \\sum_{j=1}^{i}b_j$. Consider the contribution of index $i$ to $ans_l$ for $l \\lt i$, from three cases described above the contribution is different for different $l$ with different $psum_l$. We can build a fenwick tree on compressed prefix sums. Case $1$ and $2$ above add a constant value to a range of prefix sums that can be maintained in one fenwick tree and Case $2$ gives some linear function of $psum$ to be added in a range that can be maintained in other fenwick tree. Add contribution of each $i$ from $1$ to $n$ first, and let's start calculating $ans_i$. For $i = 1$, $ans_1$ can be obtained by querying at $psum_1$ in both fenwicks. For $i = 1$, $ans_1$ can be obtained by querying at $psum_1$ in both fenwicks. Then we remove the contribution of $i = 1$ from the two fenwick trees (simply the negative of which we added above), because $i = 1$ won't be contributing to any suffix other than $1^{st}$ one. Then we remove the contribution of $i = 1$ from the two fenwick trees (simply the negative of which we added above), because $i = 1$ won't be contributing to any suffix other than $1^{st}$ one. Similarly we move from left to right and calculate $ans_i$ by querying at $psum_i$ and then remove the contribution of $i^{th}$ element. Similarly we move from left to right and calculate $ans_i$ by querying at $psum_i$ and then remove the contribution of $i^{th}$ element.",
    "code": "#include<bits/stdc++.h>\nusing namespace std ;\n\n#define ll              long long \n#define pb              push_back\n#define all(v)          v.begin(),v.end()\n#define sz(a)           (ll)a.size()\n#define F               first\n#define S               second\n#define INF             2000000000000000000\n#define popcount(x)     __builtin_popcountll(x)\n#define pll             pair<ll,ll>\n#define pii             pair<int,int>\n#define ld              long double\n\ntemplate<typename T, typename U> static inline void amin(T &x, U y){ if(y<x) x=y; }\ntemplate<typename T, typename U> static inline void amax(T &x, U y){ if(x<y) x=y; }\n\n#ifdef LOCAL\n#define debug(...) debug_out(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define debug(...) 2401\n#endif\n\n    \nconst int MOD=1000000007;\nstruct Mint {\n    int val;\n \n    Mint(long long v = 0) {\n        if (v < 0)\n            v = v % MOD + MOD;\n        if (v >= MOD)\n            v %= MOD;\n        val = v;\n    }\n \n    static int mod_inv(int a, int m = MOD) {\n        int g = m, r = a, x = 0, y = 1;\n        while (r != 0) {\n            int q = g / r;\n            g %= r; swap(g, r);\n            x -= q * y; swap(x, y);\n        } \n        return x < 0 ? x + m : x;\n    } \n    explicit operator int() const {\n        return val;\n    }\n    Mint& operator+=(const Mint &other) {\n        val += other.val;\n        if (val >= MOD) val -= MOD;\n        return *this;\n    }\n    Mint& operator-=(const Mint &other) {\n        val -= other.val;\n        if (val < 0) val += MOD;\n        return *this;\n    }\n    static unsigned fast_mod(uint64_t x, unsigned m = MOD) {\n           #if !defined(_WIN32) || defined(_WIN64)\n                return x % m;\n           #endif\n           unsigned x_high = x >> 32, x_low = (unsigned) x;\n           unsigned quot, rem;\n           asm(\"divl %4\\n\"\n            : \"=a\" (quot), \"=d\" (rem)\n            : \"d\" (x_high), \"a\" (x_low), \"r\" (m));\n           return rem;\n    }\n    Mint& operator*=(const Mint &other) {\n        val = fast_mod((uint64_t) val * other.val);\n        return *this;\n    }\n    Mint& operator/=(const Mint &other) {\n        return *this *= other.inv();\n    }\n    friend Mint operator+(const Mint &a, const Mint &b) { return Mint(a) += b; }\n    friend Mint operator-(const Mint &a, const Mint &b) { return Mint(a) -= b; }\n    friend Mint operator*(const Mint &a, const Mint &b) { return Mint(a) *= b; }\n    friend Mint operator/(const Mint &a, const Mint &b) { return Mint(a) /= b; }\n    Mint& operator++() {\n        val = val == MOD - 1 ? 0 : val + 1;\n        return *this;\n    }\n    Mint& operator--() {\n        val = val == 0 ? MOD - 1 : val - 1;\n        return *this;\n    }\n    Mint operator++(int32_t) { Mint before = *this; ++*this; return before; }\n    Mint operator--(int32_t) { Mint before = *this; --*this; return before; }\n    Mint operator-() const {\n        return val == 0 ? 0 : MOD - val;\n    }\n    bool operator==(const Mint &other) const { return val == other.val; }\n    bool operator!=(const Mint &other) const { return val != other.val; }\n    Mint inv() const {\n        return mod_inv(val);\n    }\n    Mint power(long long p) const {\n        assert(p >= 0);\n        Mint a = *this, result = 1;\n        while (p > 0) {\n            if (p & 1)\n                result *= a;\n \n            a *= a;\n            p >>= 1;\n        }\n        return result;\n    }\n    friend ostream& operator << (ostream &stream, const Mint &m) {\n        return stream << m.val;\n    }\n    friend istream& operator >> (istream &stream, Mint &m) {\n        return stream>>m.val;   \n    }\n};\n\n\ntemplate<typename T=long long>\nstruct fenwick {\n    vector<T> bit;\n    int n;\n    fenwick(int x) {\n        n = x;\n        bit.resize(x + 1, T(0));\n    }\n    void update(int j,T val)\n    {\n        for(;j<=n;j+=j&-j)\n            bit[j] += val;\n    }\n    T get(int r)\n    {\n        T u = 0;\n        for(;r;r-=r&-r)\n            u += bit[r]; \n        return u;\n    }\n    T query(int l,int r)\n    {\n        return get(r)-get(l-1);\n    }\n    // kth element\n    int getKth(T k) {\n        int ans = 0;\n        T cnt = 0;\n        for(int i=20;i>=0;--i) {\n            if(ans + (1 << i) <= n && cnt + bit[ans + (1 << i)] < k) {\n                ans += (1 << i);\n                cnt += bit[ans];\n            }\n        }\n        if(ans == n) {\n            return -1;\n        }\n        return ans + 1;\n    }\n    void insert(int x) {\n        update(x, 1);\n    }\n    void erase(int x) {\n        update(x, -1);\n    }\n};\nint _runtimeTerror_()\n{\n    int n;\n    int Q;\n    cin >> n >> Q;\n    vector<array<int,2>> a(n);\n    for(int i=0;i<n;++i) {\n        cin >> a[i][0];\n    }\n    for(int i=0;i<n;++i) {\n        cin >> a[i][1];\n    }\n    vector<Mint> val(n, 0);\n    for(int i=n-1;i>=0;--i) {\n        if(i < n - 1) {\n            val[i] = val[i + 1];\n        }\n        val[i] += a[i][0] * Mint(abs(a[i][1]));\n    }\n    auto solve = [&](vector<array<int,2>> &a) {\n\n        ll psum = 0;\n        vector<ll> psums;\n        psums.push_back(0);\n        for(int i=0;i<n;++i) {\n            psum += a[i][1];\n            assert(a[i][1] != 0);\n            psums.push_back(psum);\n        }\n        sort(all(psums));\n        psums.resize(unique(all(psums)) - psums.begin());\n        psum = 0;\n        auto get_next = [&](ll x) {\n            return lower_bound(all(psums), x) - psums.begin() + 1;\n        };\n        fenwick<Mint> f1(2*n), f2(2*n), f3(2*n);\n        for(int i=0;i<n;++i) {\n            if(a[i][1] > 0) {\n                f1.update(1, Mint(a[i][1]) * a[i][0]);\n                f1.update(get_next(psum), -Mint(a[i][1]) * a[i][0]);\n\n                f2.update(get_next(psum), a[i][0]);\n                f2.update(get_next(psum + a[i][1]), -a[i][0]);\n\n                f3.update(get_next(psum), Mint(a[i][0]) * Mint(psum + a[i][1]));\n                f3.update(get_next(psum + a[i][1]), -Mint(a[i][0]) * (psum + a[i][1]));\n            }\n            psum += a[i][1];\n        }   \n        psum = 0;\n        for(int i=0;i<n;++i) {\n            val[i] -= 2 * f1.get(get_next(psum));\n\n            val[i] -= 2 * (f3.get(get_next(psum)) - psum * f2.get(get_next(psum)));\n            if(a[i][1] > 0) {\n                \n                f1.update(1, -Mint(a[i][1]) * a[i][0]);\n                f1.update(get_next(psum), Mint(a[i][1]) * a[i][0]);\n\n                f2.update(get_next(psum), -a[i][0]);\n                f2.update(get_next(psum + a[i][1]), a[i][0]);\n\n                f3.update(get_next(psum), -Mint(a[i][0]) * Mint(psum + a[i][1]));\n                f3.update(get_next(psum + a[i][1]), Mint(a[i][0]) * (psum + a[i][1]));\n            }\n            psum += a[i][1];\n        }\n    };\n    solve(a);\n    for(int i=0;i<n;++i) {  \n        a[i][1] = -a[i][1];\n    }\n    solve(a);   \n    val.push_back(0);\n    while(Q--) {\n        int l, r;\n        cin >> l >> r;\n        --l, --r;\n        cout << val[l] - val[r + 1] << \"\\n\";\n    }\n    return 0;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    #ifdef runSieve\n        sieve();\n    #endif\n    #ifdef NCR\n        initialize();\n    #endif\n    int TESTS = 1;\n    //cin >> TESTS;\n    while(TESTS--)\n        _runtimeTerror_();\n    return 0;\n}",
    "tags": [
      "data structures",
      "flows",
      "graphs",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1684",
    "index": "A",
    "title": "Digit Minimization",
    "statement": "There is an integer $n$ \\textbf{without zeros} in its decimal representation. Alice and Bob are playing a game with this integer. Alice starts first. They play the game in turns.\n\nOn her turn, Alice \\textbf{must} swap any two digits of the integer that are on different positions. Bob on his turn always removes the last digit of the integer. The game ends when there is only one digit left.\n\nYou have to find the smallest integer Alice can get in the end, if she plays optimally.",
    "tutorial": "Let $k$ be the length of $n$. Let $n_i$ be the $i$-th digit of $n$ ($1$-indexation from the left). $k = 1$The game ends immediately so the answer is $n$ itself. The game ends immediately so the answer is $n$ itself. $k = 2$Alice should make the first move and she has to swap $n_1$ and $n_2$. After that Bob removes $n_1$ and in the end there is only $n_2$. Alice should make the first move and she has to swap $n_1$ and $n_2$. After that Bob removes $n_1$ and in the end there is only $n_2$. $k \\ge 3$Alice can make swaps in such way that when there are only two digits left the second digit will be the maximal digit of $n$. Then she will make a swap and the maximal digit will be on the first position. The other one will be removed by Bob. This way she can always get the maximal digit of $n$ in the end of the game. Alice can make swaps in such way that when there are only two digits left the second digit will be the maximal digit of $n$. Then she will make a swap and the maximal digit will be on the first position. The other one will be removed by Bob. This way she can always get the maximal digit of $n$ in the end of the game.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int T;\n    cin >> T;\n    while (T --> 0) {\n        string n;\n        cin >> n;\n        if (n.size() == 2) {\n            cout << n[1] << '\\n';\n        } else {\n            cout << *min_element(n.begin(), n.end()) << '\\n';\n        }\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "games",
      "math",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1684",
    "index": "B",
    "title": "Z mod X = C",
    "statement": "You are given three positive integers $a$, $b$, $c$ ($a < b < c$). You have to find three positive integers $x$, $y$, $z$ such that:\n\n$$x \\bmod y = a,$$ $$y \\bmod z = b,$$ $$z \\bmod x = c.$$\n\nHere $p \\bmod q$ denotes the remainder from dividing $p$ by $q$. It is possible to show that for such constraints the answer always exists.",
    "tutorial": "In this problem it is enough to find a contstruction that works for all $a < b < c$. For example: $x = a + b + c$$y = b + c$ $z = c$ $y = b + c$ $z = c$ In this case $x \\bmod y = (a + b + c) \\bmod (b + c) = a$ since $a < b < b + c$ $y \\bmod z = (b + c) \\bmod c = b$ since $b < c$ $z \\bmod x = c \\bmod (a + b + c) = c$ since $c < (a + b + c)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n    int a, b, c;\n    cin >> a >> b >> c;\n    cout << a + b + c << \" \" << b + c << \" \" << c << \"\\n\";\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1684",
    "index": "C",
    "title": "Column Swapping",
    "statement": "You are given a grid with $n$ rows and $m$ columns, where each cell has a positive integer written on it. Let's call a grid good, if in each row the sequence of numbers is sorted in a non-decreasing order. It means, that for each $1 \\le i \\le n$ and $2 \\le j \\le m$ the following holds: $a_{i,j} \\ge a_{i, j-1}$.\n\nYou have to to do the following operation exactly once: choose two columns with indexes $i$ and $j$ (\\textbf{not necessarily different}), $1 \\le i, j \\le m$, and swap them.\n\nYou are asked to determine whether it is possible to make the grid good after the swap and, if it is, find the columns that need to be swapped.",
    "tutorial": "At first, let's check wether the given table is good. If it is not then there is a row that has elements that should be replaced. Let's say that this row is $a$ and $b$ is the sorted row $a$. Then let's find the set of positions $i$ that $a_i \\neq b_i$. If there are at least $3$ such positions then the answer is $-1$ because by making a swap we remove at most $2$ such bad positions. If there are no more than $2$ such positions then let's swap the corresponding columns and check whether each row is sorted. If the table is good we found the answer. If it is not then the answer is $-1$ because we can not sort $a$ and get a good table after that.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve(vector<vector<int>> &a) {\n    int n = a.size(), m = a[0].size();\n    vector<int> bad;\n    for (int i = 0; i < n && bad.empty(); i++) {\n        vector<int> b = a[i];\n        sort(b.begin(), b.end());\n        for (int j = 0; j < m; j++) {\n            if (a[i][j] != b[j]) bad.push_back(j);\n        }\n    }\n    if ((int)bad.size() == 0) {\n    \tcout << 1 << \" \" << 1 << \"\\n\";\n    \treturn;\n    }\n    if ((int)bad.size() > 2) {\n    \tcout << -1 << \"\\n\";\n    \treturn;\n    }\n    for (int i = 0; i < n; i++) {\n        swap(a[i][bad[0]], a[i][bad[1]]);\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 1; j < m; j++) {\n            if (a[i][j] < a[i][j - 1]) {\n            \tcout << -1 << \"\\n\";\n            \treturn;\n           \t}\n        }\n    }\n    cout << bad[0] + 1 << \" \" << bad[1] + 1 << \"\\n\";\n    return;\n}\n\nint main() {\n\t#ifdef LOCAL\n        freopen(\"input.txt\", \"r\", stdin);\n        freopen(\"output.txt\", \"w\", stdout);\n    #else\n        ios_base::sync_with_stdio(0);\n        cin.tie(0);\n        cout.tie(0);\n    #endif\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tint n, m;\n\t\tcin >> n >> m;\n\t\tvector<vector<int>> a(n, vector<int>(m));\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tcin >> a[i][j];\n\t\t\t}\n\t\t}\n\t\tsolve(a);\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1684",
    "index": "D",
    "title": "Traps",
    "statement": "There are $n$ traps numbered from $1$ to $n$. You will go through them one by one in order. The $i$-th trap deals $a_i$ base damage to you.\n\nInstead of going through a trap, you can jump it over. You can jump over no more than $k$ traps. If you jump over a trap, it does not deal any damage to you. But there is an additional rule: if you jump over a trap, all next traps damages increase by $1$ (this is a bonus damage).\n\nNote that if you jump over a trap, you don't get any damage (neither base damage nor bonus damage). Also, the bonus damage stacks so, for example, if you go through a trap $i$ with base damage $a_i$, and you have already jumped over $3$ traps, you get $(a_i + 3)$ damage.\n\nYou have to find the minimal damage that it is possible to get if you are allowed to jump over no more than $k$ traps.",
    "tutorial": "Firstly, let's notice that it is always better to use all $k$ jumps. If we jumped over less than $k$ traps then we can jump over the last trap and the total damage will be less. Secondly, let's say that we immediately get $n - i$ damage if we jump over $i$-th trap. This way the first trap that we jump over will cause $k - 1$ damage more than it should (because of $k - 1$ traps that we jump over next), the second will cause $k - 2$ damage more, ..., the last one will cause $0$ damage more. So the total damage only increases by $\\frac{k(k - 1)}{2}$ which does not depend on the traps that we choose. That's why the traps that we have to jump over in this problem are the same. Now let's consider an array $b: b_i = a_i - (n - i)$. This array denotes the amount of damage we dodge if we jump over $i$-th trap (dodge $a_i$ because we don't take the trap's damage but get $n - i$ because of the immediate damage we take). Here a simple greedy works: let's just chose $k$ maximal values of this array, these will be the traps that we have to jump over so the total damage that we dodge is maximized. These traps will be the answer to the original problem.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define all(x) (x).begin(), (x).end()\n\nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    long long ans = 0;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n        ans += a[i];\n        a[i] += i + 1;\n    }\n    sort(all(a));\n    reverse(all(a));\n    for (int i = 0; i < k; i++) ans -= a[i];\n    for (int i = 0; i < k; i++) {\n        ans += n;\n        ans -= i;\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    #ifdef LOCAL\n        freopen(\"input.txt\", \"r\", stdin);\n        freopen(\"output.txt\", \"w\", stdout);\n    #else\n        ios_base::sync_with_stdio(0);\n        cin.tie(0);\n        cout.tie(0);\n    #endif\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1684",
    "index": "E",
    "title": "MEX vs DIFF",
    "statement": "You are given an array $a$ of $n$ non-negative integers. In one operation you can change any number in the array to any other non-negative integer.\n\nLet's define the cost of the array as $\\operatorname{DIFF}(a) - \\operatorname{MEX}(a)$, where $\\operatorname{MEX}$ of a set of non-negative integers is the smallest non-negative integer not present in the set, and $\\operatorname{DIFF}$ is the number of different numbers in the array.\n\nFor example, $\\operatorname{MEX}(\\{1, 2, 3\\}) = 0$, $\\operatorname{MEX}(\\{0, 1, 2, 4, 5\\}) = 3$.\n\nYou should find the minimal cost of the array $a$ if you are allowed to make at most $k$ operations.",
    "tutorial": "Let's consider all possible $\\operatorname{MEX}$ after all operations. It is from $0$ to $n$ and we can check them all in the increasing order. Now let's fix some $\\operatorname{MEX} = m$. There should be all numbers from $0$ to $m$ in the array, so there are some \"holes\" in the array that should be covered. The hole is an integer from $0$ to $m$ which is not present in the array. If there is at least one hole in the end it is not possible to obtain $\\operatorname{MEX} = m$. Now let's see how we should cover the holes. We will do it greedily. Firstly, we will need to use integers that are greater than $m$. It is easy to see that they are always not worse to use than the integers which are already from $0$ to $m$. Moreover, we should start from those integers that occur less times in the array. It is because each time we cover a hole we increase $\\operatorname{MEX}$ at least by one (we cover the holes in increasing order) and the value of $\\operatorname{DIFF}$ increases at most by $1$ and it does not increase when we change the last element of the same value. After that if we used all integers that are greater than $m$ we should use those integers that are from $0$ to $m$ but only those that occur more than once. By doing these operations we increase $\\operatorname{MEX}$ at least by $1$ and increase $\\operatorname{DIFF}$ exactly by $1$ (because we cover a hole). Now let's notice that when considering each $\\operatorname{MEX}$ value in the increasing order we can simply maintain some information about the current state of the array: a set that helps us find the elements greater than $m$ which occur less times in the array, the amount of not covered holes, the number of \"bonus\" elements from $0$ to $m$ (the number of integers from $0$ to $m$ minus $\\operatorname{DIFF}$ from those elements that are from $0$ to $m$) and it is easy to see how it is changed when we increase $\\operatorname{MEX}$. So in total we can calculate the answer for each $\\operatorname{MEX}$ for all $\\operatorname{MEX}$ from $0$ to $n$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define pb emplace_back\n#define all(x) (x).begin(), (x).end()\n#define fi first\n#define se second\n#define pii pair<int, int>\n#define puu pair<unsigned, unsigned>\n#define ll long long\n#define mp make_pair\n#define ui unsigned\n#define ull unsigned long long\n#define ld double\n#define pld pair<ld, ld>\n#define pll pair<ll, ll>\n\nconst int INF = 1e9 + 1;\nconst ll INFLL = 1e18;\n\nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n);\n    for (auto &c : a) cin >> c;\n    map<int, int> cnt;\n    for (auto &c : a) cnt[c]++;\n    set<pii> s1, s2;\n    int sum1 = 0;\n    for (auto &c : cnt) s2.insert(mp(c.se, c.fi));\n    int ans = INF;\n    int skip = 0;\n    for (int x = 0; x <= n; x++) {\n        if (s1.find(mp(cnt[x - 1], x - 1)) != s1.end()) {\n            sum1 -= cnt[x - 1];\n            s1.erase(mp(cnt[x - 1], x - 1));\n        }\n        if (s2.find(mp(cnt[x - 1], x - 1)) != s2.end()) {\n            s2.erase(mp(cnt[x - 1], x - 1));\n        }\n        while (s2.size() && sum1 + s2.begin()->fi <= k) {\n            s1.insert(*s2.begin());\n            sum1 += s2.begin()->fi;\n            s2.erase(s2.begin());\n        }\n        if (k < skip) break;\n        int now = x + s2.size();\n        if (x == 0) {\n            now = max(1, (int)s2.size());\n        }\n        ans = min(ans, now - x);\n        if (cnt[x] == 0) skip++;\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    #ifdef LOCAL\n        freopen(\"input.txt\", \"r\", stdin);\n        freopen(\"output.txt\", \"w\", stdout);\n    #else\n        ios_base::sync_with_stdio(0);\n        cin.tie(0);\n        cout.tie(0);\n    #endif\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1684",
    "index": "F",
    "title": "Diverse Segments",
    "statement": "You are given an array $a$ of $n$ integers. Also you are given $m$ subsegments of that array. The left and the right endpoints of the $j$-th segment are $l_j$ and $r_j$ respectively.\n\nYou are allowed to make \\textbf{no more than one} operation. In that operation you choose any subsegment of the array $a$ and replace each value on this segment with any integer (you are also allowed to keep elements the same).\n\nYou have to apply this operation so that for the given $m$ segments, the elements on each segment are distinct. More formally, for each $1 \\le j \\le m$ all elements $a_{l_{j}}, a_{l_{j}+1}, \\ldots, a_{r_{j}-1}, a_{r_{j}}$ should be distinct.\n\nYou don't want to use the operation on a big segment, so you have to find the smallest length of a segment, so that you can apply the operation to this segment and meet the above-mentioned conditions. If it is not needed to use this operation, the answer is $0$.",
    "tutorial": "Let's say the answer is $[L, R]$. Let's consider all given segments. There should be no two equal elements that are in the same given segment and are not in $[L, R]$, i.e. at least one of them should be in the answer. Let's find such segment of minimal length for $L = 1$. To do that let's for each $r$ find such minimal $l$ that on segment $[l, r]$ all elements are distinct. Let's say that $l = f(r)$. This could be done using two pointers, maintaining current set of elements and checking whether the considered element is not in the set. Let's say we are given a segment $[l_j, r_j]$. If $f(r_j) \\le l_j$ then this segment is already fine. Else for $L = 1$ this condition holds $R \\ge f(r_j) - 1$. Minimal $R$ that meets all the inequalitites will be the answer. Now let's find out how to find $R$ while increasing $L$ by $1$. If we increase $L$ then $R$ can not decrease. Also if $[L + 1, R]$ can not be the answer then in some of given segments there are two equal elements $a_L$ and $a_j$. If $j < L$ then the left endpoint can not be greater than $L$. Else $j > R$. Then we have to make $R = j$ and this $j$ should be minimal. This $j$ could be found, for example, by binary search in $cnt$ array. To check whether two elements are in the same segments it is possible to use a segment tree or a Fenwick tree. It is possible to store for each $i$ such maximal $r_j$ that there is a given segment $[l_j, r_j]$ and $l_j \\le i$. The final answer will be the minimal length of $[L, R]$ for all $L$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define pb emplace_back\n#define all(x) (x).begin(), (x).end()\n#define fi first\n#define se second\n#define pii pair<int, int>\n#define puu pair<unsigned, unsigned>\n#define ll long long\n#define mp make_pair\n#define ui unsigned\n#define ull unsigned long long\n#define ld double\n#define pld pair<ld, ld>\n#define pll pair<ll, ll>\n\nconst int INF = 1e9 + 1;\nconst ll INFLL = 1e18;\n\nvector<int> f;\n\nvoid incr(int x, int d) {\n    for (; x < (int)f.size(); x |= (x + 1)) f[x] = max(f[x], d);\n}\n\nint get(int x) {\n    int ans = -1;\n    for (; x >= 0; x = (x & (x + 1)) - 1) ans = max(ans, f[x]);\n    return ans;\n}\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n);\n    for (auto &c : a) cin >> c;\n    map<int, vector<int>> gist;\n    for (int i = 0; i < n; i++) gist[a[i]].pb(i);\n    vector<pii> seg(m);\n    f.assign(n, -1);\n    for (auto &c : seg) {\n        cin >> c.fi >> c.se; c.fi--; c.se--;\n        incr(c.fi, c.se);\n    }\n    vector<int> mnl(n);\n    set<int> s;\n    int l = n;\n    for (int r = n - 1; r >= 0; r--) {\n        while (l - 1 >= 0 && !s.count(a[l - 1])) {\n            l--;\n            s.insert(a[l]);\n        }\n        mnl[r] = l;\n        s.erase(a[r]);\n    }\n    int mnr = -1;\n    for (auto &c : seg) {\n        int l = c.fi, r = c.se;\n        if (mnl[r] <= l) continue;\n        mnr = max(mnr, mnl[r] - 1);\n    }\n    if (mnr == -1) {\n        cout << 0 << \"\\n\";\n        return;\n    }\n    int ans = mnr + 1;\n    for (int l = 0; l + 1 < n; l++) {\n        if (gist[a[l]][0] != l) {\n            int id = lower_bound(all(gist[a[l]]), l) - gist[a[l]].begin() - 1;\n            int pr = gist[a[l]][id];\n            if (get(pr) >= l) {\n                break;\n            }\n        }\n        int id = upper_bound(all(gist[a[l]]), mnr) - gist[a[l]].begin();\n        if (id != (int)gist[a[l]].size()) {\n            int nxt = gist[a[l]][id];\n            if (get(l) >= nxt) {\n                mnr = nxt;\n            }\n        }\n        mnr = max(mnr, l + 1);\n        ans = min(ans, mnr - l);\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    #ifdef LOCAL\n        freopen(\"input.txt\", \"r\", stdin);\n        freopen(\"output.txt\", \"w\", stdout);\n    #else\n        ios_base::sync_with_stdio(0);\n        cin.tie(0);\n        cout.tie(0);\n    #endif\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1684",
    "index": "G",
    "title": "Euclid Guess",
    "statement": "Let's consider Euclid's algorithm for finding the greatest common divisor, where $t$ is a list:\n\n\\begin{verbatim}\nfunction Euclid(a, b):\nif a < b:\nswap(a, b)\nif b == 0:\nreturn a\nr = reminder from dividing a by b\nif r > 0:\nappend r to the back of t\nreturn Euclid(b, r)\n\\end{verbatim}\n\nThere is an array $p$ of pairs of positive integers that are not greater than $m$. Initially, the list $t$ is empty. Then the function is run on each pair in $p$. After that the list $t$ is shuffled and given to you.\n\nYou have to find an array $p$ \\textbf{of any size} not greater than $2 \\cdot 10^4$ that produces the given list $t$, or tell that no such array exists.",
    "tutorial": "Let's consider some pair $(a, b)$ and consider a sequence of remainders that is induced by this pair: $a \\bmod b = x_1$, $b \\bmod x_1 = x_2$, ..., $x_{p - 2} \\bmod x_{p - 1} = x_p$, where $x_p = gcd(a, b)$. If $x_i \\le \\frac{m}{3}$ then we can just add a pair $(3x_i, 2x_i)$ and we will get the only remainder $x_i$ so these values will not be a problem. If $x_1 > \\frac{m}{3}$ (if $i > 1$ then $x_i \\le \\frac{m}{3}$) then $a = b + x_1$ because if $a \\ge 2b + x_1$ then $a > m$ which is impossible. $b = x_1 + x_2$ because if $b \\ge 2x_1 + x_2$ then $a \\ge 3x_1 + x_2 > m$. Then $a = b + x_1 = 2x_1 + x_2 \\ge 2x_1 + x_p$ because $x_p < x_{p - 1} < \\ldots < x_2 < x_1$. It means that for each $x_i > \\frac{m}{3}$ there should be such $x_j$ that $2x_i + x_j \\le m$ and $x_j$ is a divisor of $x_i$. For such values we can consider a bipartite graph where in the left part there are only $x_i > \\frac{m}{3}$ and in the right part there are only $x_j \\le \\frac{m}{3}$ and two integers are connected $\\iff$ the integer on the right divies the left one. This graph can be built in $O(n^2)$. After that we just have to find such matching that covers each integer in the left part and add all unused integers from the right part using the method above.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define pb emplace_back\n#define all(x) (x).begin(), (x).end()\n#define fi first\n#define se second\n#define pii pair<int, int>\n#define puu pair<unsigned, unsigned>\n#define ll long long\n#define mp make_pair\n#define ui unsigned\n#define ull unsigned long long\n#define ld double\n#define pld pair<ld, ld>\n#define pll pair<ll, ll>\n#define int ll\n\nconst int INF = 1e9 + 1;\nconst ll INFLL = 1e18;\n \nvector<vector<int>> g;\nvector<int> with;\nvector<int> usd;\n \nint dfs(int v) {\n    if (usd[v]) return 0;\n    usd[v] = 1;\n    for (auto &to : g[v]) {\n        if (with[to] == -1) {\n            with[to] = v;\n            return 1;\n        }\n    }\n    for (auto &to : g[v]) {\n        if (dfs(with[to])) {\n            with[to] = v;\n            return 1;\n        }\n    }\n    return 0;\n}\n\nsigned main() {\n    #ifdef LOCAL\n        freopen(\"input.txt\", \"r\", stdin);\n        freopen(\"output.txt\", \"w\", stdout);\n    #else\n        ios_base::sync_with_stdio(0);\n        cin.tie(0);\n        cout.tie(0);\n    #endif\n    int n, A;\n    cin >> n >> A;\n    vector<int> a(n);\n    vector<int> l, r;\n    for (auto &c : a) {\n        cin >> c;\n        if (3 * c > A) {\n            l.pb(c);\n        } else {\n            r.pb(c);\n        }\n    }\n    g.resize(l.size());\n    with.resize(r.size(), -1);\n    for (int i = 0; i < (int)l.size(); i++) {\n        for (int j = 0; j < (int)r.size(); j++) {\n            if (l[i] % r[j] == 0 && 2 * l[i] + r[j] <= A) {\n                g[i].pb(j);\n            }\n        }\n    }\n    int cnt = 0;\n    for (int i = 0; i < (int)l.size(); i++) {\n        usd.assign(l.size(), 0);\n        cnt += dfs(i);\n    }\n    if (cnt < (int)l.size()) {\n        cout << -1;\n        return 0;\n    }\n    vector<pii> ans;\n    for (int j = 0; j < (int)r.size(); j++) {\n        if (with[j] == -1) {\n            ans.pb(3 * r[j], 2 * r[j]);\n        } else {\n            ans.pb(2 * l[with[j]] + r[j], l[with[j]] + r[j]);\n        }\n    }\n    cout << ans.size() << \"\\n\";\n    for (auto &c : ans) cout << c.fi << \" \" << c.se << \"\\n\";\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "flows",
      "graph matchings",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1684",
    "index": "H",
    "title": "Hard Cut",
    "statement": "You are given a binary string $s$. You have to cut it into any number of non-intersecting substrings, so that the sum of binary integers denoted by these substrings is a power of 2. Each element of $s$ should be in exactly one substring.",
    "tutorial": "Let's say that there are $k$ ones in the given string. We will build the answer for all $k > 0$. $k = 0$ is the only case when the answer does not exist. $k = 1$, $k = 2$, $k = 4$ - cut into single digits. $k = 3$ - described later. Let's consider $k = 5$: If all ones are in a row, then we should cut them into $1111_2 + 1_2 = 16_{10}$. Else there will be either $101_2$ or $100_2$ and the other part of the string may be cut into single digits so the sum will be $8_{10}$. Now let's consider $k > 5$ (here we will also consider $k = 3$): Let's describe the function $solve(l, r, k, n)$ for cutting the susbtring from $l$ to $r$ with $k$ ones to get the sum $n$. Let's use the \"divide and conquer\" technique: we have a string with $k$ ones and we want to get the sum $n = 2^{\\left \\lceil \\log_2(k)\\right \\rceil}$, and for big enough $k$ we can just cut the whole string into two substrings with almost equal number of ones, run the algorithm for them and get the sum $2^{\\left \\lceil \\log_2(\\left \\lfloor k/2 \\right \\rfloor)\\right \\rceil} + 2^{\\left \\lceil \\log_2(\\left \\lceil k/2 \\right \\rceil)\\right \\rceil} = 2^{\\left \\lceil \\log_2(k)\\right \\rceil} = n$. Now let's show how to make such cut for all strings that have from $6$ to $11$ ones and after that for all $k \\ge 12$ we will be able to run the method decribed above. $k = n$Just cut into single digits. Just cut into single digits. $k < n \\le \\left \\lfloor \\frac{3k}{2} \\right \\rfloor$Let's consider the first two ones. If they are consequent then we will cut them into a single substring. It costs us only two ones but it increases the sum by $3$. If these two ones are not consequent then we will cut out the segments $10_2$ and $1_2$. This way we spend two ones again and the sum increases by $3$ as well. Also it is always possible to cut off a single digit so it is easy to see that we can get any sum $n$ from $k$ to $\\left \\lfloor \\frac{3k}{2} \\right \\rfloor$. This way we got the answer for $k = 6, 7, 8, 11$. Now we only need to show how to make the cut for $k = 9, 10$. Let's consider the first two ones. If they are consequent then we will cut them into a single substring. It costs us only two ones but it increases the sum by $3$. If these two ones are not consequent then we will cut out the segments $10_2$ and $1_2$. This way we spend two ones again and the sum increases by $3$ as well. Also it is always possible to cut off a single digit so it is easy to see that we can get any sum $n$ from $k$ to $\\left \\lfloor \\frac{3k}{2} \\right \\rfloor$. This way we got the answer for $k = 6, 7, 8, 11$. Now we only need to show how to make the cut for $k = 9, 10$. $k = 9$Let's consider a substring of length $3$ that starts in the leftmost one, there are $4$ possible cases: $t = 100$, then we need to use $k' = 8$ ones to get the sum $n' = 16_{10} - 100_2 = 12$, which we know how to do. $t = 101$, then we need to use $k' = 7$ ones to get the sum $n' = 11$, we will show it in the end. $t = 110$, then we need to use $k'= 7$ ones to get the sum $n' = 10$, which we know how to do. $t = 111$, then we need to use $k' = 6$ ones to get the sum $n' = 9$, which we know how to do. Let's consider a substring of length $3$ that starts in the leftmost one, there are $4$ possible cases: $t = 100$, then we need to use $k' = 8$ ones to get the sum $n' = 16_{10} - 100_2 = 12$, which we know how to do. $t = 101$, then we need to use $k' = 7$ ones to get the sum $n' = 11$, we will show it in the end. $t = 110$, then we need to use $k'= 7$ ones to get the sum $n' = 10$, which we know how to do. $t = 111$, then we need to use $k' = 6$ ones to get the sum $n' = 9$, which we know how to do. $k = 10$To do that let's cut a substring with $k_1 = 4$ ones from the left and get the sum $n_1 = 8$ and a remaining substring with $k_2 = 6$ ones and get the sum $n_2$. We already know how to get the second sum so now there is only $k_1 = 4$ and $n_1 = 8$ left. To do that let's cut a substring with $k_1 = 4$ ones from the left and get the sum $n_1 = 8$ and a remaining substring with $k_2 = 6$ ones and get the sum $n_2$. We already know how to get the second sum so now there is only $k_1 = 4$ and $n_1 = 8$ left. Let's consider the last two cases for full solution:$k = 4,\\, n = 8$: Let's do the same thing as we did for $k = 9$, cut off a substring of length $3$ that starts from the leftmost one. Then we have two substrings and for both of them we know how to cut them properly. $k = 7,\\, n = 11$: Let's cut off the first four ones and use the previous technique we will get the sum $8$. The remaining three ones we will use to get the sum $3$. $k = 4,\\, n = 8$: Let's do the same thing as we did for $k = 9$, cut off a substring of length $3$ that starts from the leftmost one. Then we have two substrings and for both of them we know how to cut them properly. $k = 7,\\, n = 11$: Let's cut off the first four ones and use the previous technique we will get the sum $8$. The remaining three ones we will use to get the sum $3$. This shows how to cut the string for any $k > 0$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 1e6;\nint g[MAXN + 1];\nstring s;\n\nvector<pair<int, int>> segments; // [l, r]\n\nint get(int k, int i) { // get k-th '1' on [i, |s|)\n\t--i;\n\twhile (k --> 0) i = s.find('1', i + 1);\n\treturn i;\n}\n\nvoid five() {\n\tint first = get(1, 0), last = get(5, 0);\n\tint r = (int)s.size() - 1;\n\tif (last - first + 1 == 5) { // creating 16: ['001111', '1', '0000']\n\t\tsegments.emplace_back(0, last - 1);\n\t\tsegments.emplace_back(last, last);\n\t\tif (last < r) segments.emplace_back(last + 1, r);\n\t} else { // creating 8: cut out '101' or '100' and cut everything in single digits\n\t\tint pos = s.find(\"101\");\n\t\tif (pos == string::npos) pos = s.find(\"100\");\n\t\tfor (int i = 0; i < pos; ++i) segments.emplace_back(i, i);\n\t\tsegments.emplace_back(pos, pos + 2);\n\t\tfor (int i = pos + 3; i <= r; ++i) segments.emplace_back(i, i);\n\t}\n}\n\nvoid solve(int l, int r, int k, int n) { // [l; r]\n\tif (k == n) { // cutting into single digits\n\t\tfor (int i = l; i <= r; ++i) segments.emplace_back(i, i);\n\n\t} else if (k == 2 && n == 3) {\n\t\tint pos = get(1, l);\n\t\tif (s[pos + 1] == '1') { // ['11', '00...00']\n\t\t\tsegments.emplace_back(l, pos + 1);\n\t\t\tif (pos + 2 <= r) segments.emplace_back(pos + 2, r);\n\n\t\t} else { // ['10', '0001', '00000']\n\t\t\tint newpos = get(1, pos + 1);\n\t\t\tsegments.emplace_back(l, pos + 1);\n\t\t\tsegments.emplace_back(pos + 2, newpos);\n\t\t\tif (newpos + 1 <= r) segments.emplace_back(newpos + 1, r);\n\t\t}\n\n\t} else if (3 * k / 2 >= n) { // using previous if technique\n\t\tint pos = get(2, l);\n\t\tsolve(l, pos, 2, 3);\n\t\tif (k > 2) solve(pos + 1, r, k - 2, n - 3);\n\n\t} else if ((k == 4 && n == 8) || (k == 9 && n == 16)) {\n\t\tint pos = get(1, l);\n\t\tstring sub = s.substr(pos, 3);\n\t\tsegments.emplace_back(l, pos + 2);\n\t\tif (sub == \"100\") solve(pos + 3, r, k - 1, n - 4);\n\t\tif (sub == \"101\") solve(pos + 3, r, k - 2, n - 5);\n\t\tif (sub == \"110\") solve(pos + 3, r, k - 2, n - 6);\n\t\tif (sub == \"111\") solve(pos + 3, r, k - 3, n - 7);\n\n\t} else if ((k == 7 && n == 11) || (k == 10 && n == 16)) {\n\t\tint mid = get(4, l);\n\t\tsolve(l, mid, 4, 8);\n\t\tsolve(mid + 1, r, k - 4, n - 8);\n\n\t} else { // common case\n\t\tint mid = get(k / 2, l);\n\t\tsolve(l, mid, k / 2, n / 2);\n\t\tsolve(mid + 1, r, k - k / 2, n / 2);\n\n\t}\n}\n\nsigned main() {\n\tios_base::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tg[1] = 1;\n\tfor (int i = 2; i <= MAXN; ++i) g[i] = g[(i + 1) / 2] * 2;\n\tint T;\n\tcin >> T;\n\twhile (T --> 0) {\n\t\tcin >> s;\n\t\tint k = count(s.begin(), s.end(), '1');\n\t\tif (!k) {\n\t\t\tcout << -1 << '\\n';\n\t\t\tcontinue;\n\t\t}\n\t\tsegments.clear();\n\t\tif (k == 5) five();\n\t\telse solve(0, (int)s.size() - 1, k, g[k]);\n\t\tcout << segments.size() << '\\n';\n\t\tfor (auto &[l, r] : segments) {\n\t\t\tcout << l + 1 << ' ' << r + 1 << '\\n';\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "divide and conquer",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1685",
    "index": "A",
    "title": "Circular Local MiniMax",
    "statement": "You are given $n$ integers $a_1, a_2, \\ldots, a_n$. Is it possible to arrange them on a circle so that each number is strictly greater than both its neighbors or strictly smaller than both its neighbors?\n\nIn other words, check if there exists a rearrangement $b_1, b_2, \\ldots, b_n$ of the integers $a_1, a_2, \\ldots, a_n$ such that for each $i$ from $1$ to $n$ at least one of the following conditions holds:\n\n- $b_{i-1} < b_i > b_{i+1}$\n- $b_{i-1} > b_i < b_{i+1}$\n\nTo make sense of the previous formulas for $i=1$ and $i=n$, one shall define $b_0=b_n$ and $b_{n+1}=b_1$.",
    "tutorial": "Let's call $b_i$ local minimum if $b_{i-1} > b_i < b_{i+1}$ and local maximum if $b_{i-1} < b_i > b_{i+1}$. It's clear that in the arrangement satisfying the conditions from the statement, if $b_i$ is a local minimum, $b_{i+1}$ is a local maximum, and vice versa. Local minimums and local maximums will be alternating. Then it's easy to see that such an arrangement can't exist for odd $n$. Indeed, suppose that the conditions from the statement are satisfied for $b_1, b_2, \\ldots, b_n$. If we suppose that $b_1$ is local minimum, we get that $b_2$ is local maximum, $b_3$ is local minimum, $\\ldots,$, $b_n$ is local minimum, $b_1$ is local maximum. Clearly, $b_1$ can't be a local maximum and a local minimum at the same time, leading to a contradiction. Let's now consider the case of even $n = 2m$. Sort the array $a$, so that $a_1 \\le a_2 \\le \\ldots \\le a_{2m}$. Let's show that if $a_i = a_{i + m - 1} = x$ for some $2 \\le i \\le m-1$, then there is no arrangement satisfying the conditions from the statement. Indeed, consider such an arrangement: we have $m$ numbers $x$, and no two of them can be adjacent, so they occupy every second position. In addition, as local maximums and local minimums are alternating, we get that all $x$ are local maximums or all $x$ are local minimums. The first would imply that $a_{2m} < x$, which isn't possible. The second would imply that $a_1 > x$, which isn't possible. It turns out that if there is no such $i$, the arrangement exists. Indeed, we can arrange numbers on the circle in the following order: $(a_1, a_{m+1}, a_2, a_{m+2}, \\ldots, a_m, a_{2m})$. Here $a_k < a_{m + k} > a_{k+1}$ for $1 \\le k \\le m-1$, $a_{m+k} > a_{k+1} < a_{m+k+1}$ for $1 \\le k \\le m-1$, $a_{2m} > a_1 < a_{m+1}$ and $a_m < a_{2m} > a_1$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1685",
    "index": "B",
    "title": "Linguistics",
    "statement": "Alina has discovered a weird language, which contains only $4$ words: $A$, $B$, $AB$, $BA$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.\n\nAlina has found one such sentence $s$ and she is curious: is it possible that it consists of precisely $a$ words $A$, $b$ words $B$, $c$ words $AB$, and $d$ words $BA$?\n\nIn other words, determine, if it's possible to concatenate these $a+b+c+d$ words in some order so that the resulting string is $s$. Each of the $a+b+c+d$ words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.",
    "tutorial": "For the answer to be $\\texttt{YES}$ the frequency of the character $\\texttt{A}$ in the $a+b+c+d$ words must coincide with its frequency in the sentence $s$, which is equivalent to the condition $a + c + d = \\#\\{i:\\, s_i = \\texttt{A}\\}$. From now on we may assume that this is true. Notice that the answer to the problem is $\\texttt{YES}$ if and only if it is possible to tile the string $s$ with $c$ copies of $\\texttt{AB}$ and $d$ copies of $\\texttt{BA}$ so that all the $c+d$ substrings are disjoint. Indeed one can simply fill the remaining characters of $s$ with the $a$ copies of $\\texttt{A}$ and the $b$ copies of $\\texttt{B}$ (we are sure that the number of characters $\\texttt{A}$ and $\\texttt{B}$ is correct because of the initial check). Moreover, if $s_i = s_{i+1}$, then clearly any tiling with $\\texttt{AB}$ and $\\texttt{BA}$ of $s$ cannot cover with a single tile both $s_i$ and $s_{i+1}$; therefore we can split the string $s$ between $s_i$ and $s_{i+1}$ and try to tile the two resulting substrings. By repeating this argument we will end up with many alternating strings (a string $t$ is alternating if $t_{i} \\not= t_{i+1}$ for all $1\\le i < |t|$). So, we have reduced the problem to the following one: Subproblem: You are given many alternating strings, can you find in these strings $c$ substrings equal to $\\texttt{AB}$ and $d$ subtrings equal to $\\texttt{BA}$ such that all the $c+d$ substrings are disjoint? In order to solve the problem let us analyze what happens when only one alternating string is present. Given an alternating string $t$, we say that the pair $(x, y)$ is valid if we can find in $t$ $x$ substrings equal to $\\texttt{AB}$ and $y$ substrings equal to $\\texttt{BA}$ so that the $x+y$ substrings are disjoint. Let us consider various cases: If $|t|=2k+1$, then $(x, y)$ is valid if and only if $x + y \\le k$. Let $f(k):=\\{(x, y):\\, 0\\le x,y\\text{ and } x + y\\le k\\}$. If $|t|=2k$ and $t_1 = \\texttt{A}$, then $(x, y)$ is valid if and only if $x+y\\le k-1$ or $(x, y) = (k, 0)$. Let $f_{AB}(k):= \\{(k, 0)\\}\\cup f(k-1)$. If $|t|=2k$ and $t_1 = \\texttt{B}$, then $(x, y)$ is valid if and only if $x+y\\le k-1$ or $(x, y) = (0, k)$. Let $f_{BA}(k):= \\{(0, k)\\}\\cup f(k-1)$. We will provide a proof for the correcteness of the following greedy algorithm. Greedy algorithm: Sort the strings of type $2$ by length and fill them, starting from the shortest, only with $\\texttt{AB}$ (i.e., find as many disjoint copies of $\\texttt{AB}$ as possible) until you reach $c$ or you finish them (a string of length $2k$ is filled with $k$ $\\texttt{AB}$). Do the same for the strings of type $3$ for the word $\\texttt{BA}$. At this point there are no more bonuses to use and you can just fill the remaining strings with $\\texttt{AB}$ and $\\texttt{BA}$ in the only reasonable way. If in the end, if you have found $c$ strings $\\texttt{AB}$ and $d$ strings $\\texttt{BA}$ then the answer is $\\texttt{YES}$, otherwise it is $\\texttt{NO}$. Let us provide a proof of the correctness of this algorithm. Let us remark that the proof of the correctness is in fact rather easy, but a bit cumbersome to write down. The strategy of the proof is to start from a solution and to show that the one constructed by the greedy algorithm is \"better\". Proof of the correctness of the greedy algorithm: Let $U, V, W$ be the multisets of lengths of strings of the first, second and third type respectively (according to the case division above). Then the problem is equivalent to understanding if $(c, d) \\in \\sum_{u\\in U} f(u) + \\sum_{v\\in V} f_{AB}(v) + \\sum_{w\\in W} f_{BA}(w).$ Assume that the answer is $\\texttt{YES}$ and consider a solution of the problem, i.e. a choice of a valid pair for each of the $|U|+|V|+|W|$ alternating strings. Let $V = V'\\sqcup V' '$ where $V'$ corresponds to the lengths of the strings in $V$ where the valid pair of the solution is given by $(k, 0)$ ($k$ is the length of the string). Partition $W=W'\\sqcup W' '$ analogously. Then we have $(c, d) \\in \\sum_{u\\in U} f(u) + \\sum_{v'\\in V'} (v', 0) + \\sum_{v' '\\in V' '} f(v' ' - 1) + \\sum_{w'\\in W'} (0, w') + \\sum_{w' '\\in W' '} f(w' ' - 1) .$ Let us make a couple of observations: For any $k_1, k_2$ it holds $f(k_1) + f(k_2) = f(k_1 + k_2)$. If $k_1\\le k_2$, then $f(k_1) + (k_2, 0) \\subseteq (k_1, 0) + f(k_2)$ and also $f(k_1) + (0, k_2) \\subseteq (0, k_1) + f(k_2)$. $\\tag{$\\star$} (c, d) \\in f\\Bigg(\\sum_{u\\in U} k + \\sum_{v' '\\in V\\setminus V'} (v' ' - 1) + \\sum_{w' '\\in W\\setminus W'} (w' ' -1)\\Bigg) + \\bigg(\\sum_{v'\\in V'} v', 0\\bigg) + \\bigg(0, \\sum_{w'\\in W'} w'\\bigg).$ $\\Big(c-\\sum V', d-\\sum W'\\Big) \\in f(s),$ $\\Big(c-(\\sum V' + v' '), d-\\sum W'\\Big) \\in f(s-(v' '-1)),$",
    "tags": [
      "greedy",
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1685",
    "index": "C",
    "title": "Bring Balance",
    "statement": "Alina has a bracket sequence $s$ of length $2n$, consisting of $n$ opening brackets '(' and $n$ closing brackets ')'. As she likes balance, she wants to turn this bracket sequence into a balanced bracket sequence.\n\nIn one operation, she can reverse any substring of $s$.\n\nWhat's the smallest number of operations that she needs to turn $s$ into a balanced bracket sequence? It can be shown that it's always possible in at most $n$ operations.\n\nAs a reminder, a sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), and (()(())) are balanced, while )(, ((), and (()))( are not.",
    "tutorial": "Let's denote ( by $1$ and ) by $-1$. Then we need to achieve a sequence in which all prefix sums are nonnegative. Let our sequence be $a_1, a_2, \\ldots, a_{2n}$, and denote $pref_i = a_1 + a_2 + \\ldots + a_i$ for each $0 \\le i \\le 2n$. Key observation: It's always possible to get a balanced sequence in at most $2$ operations. Proof: Let $0 \\le i \\le 2n$ be the index for which the value of $pref_i$ is the largest (if there are several such $i$, choose any). Let's reverse segments $a[1:i]$ and $a[i+1:2n]$, getting sequence $a_i, a_{i-1}, \\ldots, a_1, a_{2n}, a_{2n-1}, \\ldots, a_{i+1}$. It's easy to show that this sequence is balanced. $a_i + a_{i-1} + \\ldots + a_j = pref_i - pref_{j-1} \\ge 0$ for any $j \\le i$, and $a_j + a_{j-1} + \\ldots + a_{i+1} = pref_j - pref_i \\le 0$ for any $j \\ge i$, so $a_i + a_{i-1} + \\ldots + a_i + a_{2n} + \\ldots + a_{j+1} = -(a_j + a_{j-1} + \\ldots + a_{i+1}) \\ge 0$ for any $j \\ge i$. So, all prefix sums are nonnegative, as desired. It remains to check if we can make our sequence balanced in less than $2$ operations. Checking if $0$ operations are enough is trivial: just check if the initial sequence is balanced. Now, let's check if we can make the sequence (which initially isn't balanced) balanced in exactly one operation. Let $l$ be the smallest index for which $pref_l < 0$, and $r$ be the largest such index. Suppose that we will reverse the segment $a[L:R]$. Clearly, $L \\le l$, as otherwise, we would have a negative prefix sum. Similarly $R > r$. After reversing, we need to worry only about the $i$-th prefix sum for each $i$ from $L$ to $R-1$, all others will be nonnegative. The $i$-th prefix sum for such $i$ will be equal to $pref_{L-1} + (pref_R - pref_{R + L - 1 - i})$. So, segment $[L, R]$ will be good iff $pref_{L-1} + pref_R \\ge pref_i$ for all $L -1 \\le i \\le R$. It's easy to show that if any such segment $[L, R]$ works, then also the segment $[L_1, R_1]$ works, where $L_1$ is the index from $[0, l]$ for which $pref_{L_1}$ is the largest, and $R_1$ is the index from $[r+1, 2n]$ for which $pref_{R_1}$ is the largest. Indeed, suppose that there is some $L_1 \\le i \\le R_1$ such that $pref_{L_1} + pref_{R_1} < pref_i$. If $i \\le l$, then $pref_i < pref_{L_1}$, contradiction. If $i > r$, then $pref_i < pref_{R_1}$, contradiction. If $l < i \\le r$, then $i$ is inside any such segment $[L, R]$, and $pref_i > pref_L + pref_R$ for any choice of $L, R$. So, it's enough to choose segment $[L_1, R_1]$ and to check if the sequence becomes balanced after reversing it.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1685",
    "index": "D1",
    "title": "Permutation Weight (Easy Version)",
    "statement": "\\textbf{This is an easy version of the problem. The difference between the easy and hard versions is that in this version, you can output any permutation with the smallest weight}.\n\nYou are given a permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$.\n\nLet's define the weight of the permutation $q_1, q_2, \\ldots, q_n$ of integers from $1$ to $n$ as $$|q_1 - p_{q_{2}}| + |q_2 - p_{q_{3}}| + \\ldots + |q_{n-1} - p_{q_{n}}| + |q_n - p_{q_{1}}|$$\n\nYou want your permutation to be as lightweight as possible. Find any permutation $q$ with the smallest possible weight.",
    "tutorial": "Let's first understand what is the minimum possible weight of $q$. When can it be $0$? Only when $q_i = p_{q_{i+1}}$ for each $i$. Clearly, such $q$ exists only when $p$ is just one cycle. This gives a hint that we should look at cycles. Consider splitting of $p$ into cycles (where a cycle is an array $[a_1, a_2, \\ldots, a_m]$ such that $p_{a_i} = a_{i \\bmod m +1}$ for $1 \\le i \\le m$). Let's say there are $k$ of such cycles. I claim that the answer is $2(k-1)$. You can see the proof in the tutorial of the hard version of this problem. Now, let's provide an example. We will construct a permutation $p'$ as follows: Initially, it's equal to $p$ Then, for each $x$ from $1$ to $n-1$, if $x$ and $x+1$ are in different cycles in $p'$ currently, swap them. One such swap reduces the number of cycles by exactly $1$, so we will do exactly $k-1$ such swaps and $p'$ will consist of exactly one cycle. Next, construct $q$ by the rule $q_i = p'_{q_{i+1}}$ (it's possible as $p'$ is just one cycle). As $|q_i - p_{q_{i+1}}| = |p'_{q_{i+1}} - p_{q_{i+1}}|$, the weight of $q$ is just the sum of $|p_i - p'_i|$. Clearly, one swap increases this value by at most $2$, so in the end it will be at most $2(k-1)$, as desired.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1685",
    "index": "D2",
    "title": "Permutation Weight (Hard Version)",
    "statement": "\\textbf{This is a hard version of the problem. The difference between the easy and hard versions is that in this version, you have to output the lexicographically smallest permutation with the smallest weight}.\n\nYou are given a permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$.\n\nLet's define the weight of the permutation $q_1, q_2, \\ldots, q_n$ of integers from $1$ to $n$ as $$|q_1 - p_{q_{2}}| + |q_2 - p_{q_{3}}| + \\ldots + |q_{n-1} - p_{q_{n}}| + |q_n - p_{q_{1}}|$$\n\nYou want your permutation to be as lightweight as possible. Among the permutations $q$ with the smallest possible weight, find the lexicographically smallest.\n\nPermutation $a_1, a_2, \\ldots, a_n$ is lexicographically smaller than permutation $b_1, b_2, \\ldots, b_n$, if there exists some $1 \\le i \\le n$ such that $a_j = b_j$ for all $1 \\le j < i$ and $a_i<b_i$.",
    "tutorial": "We will start by proving that the weight is at least $2(k-1)$ (where $k$ is the number of cycles), and understanding the structure of optimal permutations in the process. Again, consider splitting of $p$ into cycles (where a cycle is an array $[a_1, a_2, \\ldots, a_m]$ such that $p_{a_i} = a_{i \\bmod m +1}$ for $1 \\le i \\le m$). Let's say there are $k$ of such cycles. Now, consider a graph $G$ on $n$ nodes, and draw an edge from $q_i$ to $p_{q_{i+1}}$ for each $i$ from $1$ to $n$ (there may be self-loops and multi-edges here). Each node has one incoming and outgoing edge, so the entire graph is split into several cycles. Consider any such cycle $(b_1, b_2, \\ldots, b_m)$, where all $b_i$ are distinct. Its contribution to the answer is $|b_1 - b_2| + |b_2 - b_3| + \\ldots + |b_m - b_1|$. We will show that: This value is at least $2(m-1)$. Proof: Wlog $b_i$ is the smallest among $b$ and $b_j$ is the largest, with $i<j$. Then $|b_1 - b_2| + |b_2 - b_3| + \\ldots + |b_m - b_1| = (|b_i - b_{i+1}| + \\ldots + |b_{j-1} - b_j|) + (|b_j - b_{j+1}| + \\ldots + |b_{i-1} - b_i|) \\ge$ $\\le 2|b_i - b_j| \\ge 2(m-1)$. This value is at least $2(m-1)$. Proof: Wlog $b_i$ is the smallest among $b$ and $b_j$ is the largest, with $i<j$. Then $|b_1 - b_2| + |b_2 - b_3| + \\ldots + |b_m - b_1| = (|b_i - b_{i+1}| + \\ldots + |b_{j-1} - b_j|) + (|b_j - b_{j+1}| + \\ldots + |b_{i-1} - b_i|) \\ge$ $\\le 2|b_i - b_j| \\ge 2(m-1)$. It's $2(m-1)$ only when the numbers on the cycle are some $m$ consecutive numbers and are increasing on the path from the smallest number to the largest and decreasing on the way back. Proof: It's just the case when all the inequalities in the expression above become equalities. It's $2(m-1)$ only when the numbers on the cycle are some $m$ consecutive numbers and are increasing on the path from the smallest number to the largest and decreasing on the way back. Proof: It's just the case when all the inequalities in the expression above become equalities. Now, assign each cycle of $p$ a number from $1$ to $k$ and consider the graph $G_1$ on $k$ nodes, draw an edge between the nodes corresponding to the cycles where $q_i$ and $p_{q_{i+1}}$ belong. As $q_i$ and $p_{q_i}$ are in the same cycle for each $i$, we get that every two consecutive edges we draw share a node. As we will draw an edge from every cycle, the graph is connected. Each edge in $G_1$ corresponds to an edge in $G$ (edge between $q_i$ and $p_{q_{i+1}}$ in $G$ corresponds to an edge in $G_1$ between the nodes corresponding to the cycles where $q_i$ and $p_{q_{i+1}}$ belong). Now, consider any spanning tree in graph $G_1$. Clearly, any cycle of length $m$ in $G_1$ can contain at most $m-1$ edges from it (if it contained $m$ edges from it, we would have a cycle in $G_1$). So, the total sum of $(m-1)$ over all cycles in $G$ is at least $k-1$, and therefore the total contribution to the weight is at least $2(k-1)$. Now let's give a characterization of all permutations $q$ which have the weight $2(k-1)$. It turns out, that they are in correspondence with graphs $G$ on $n$ nodes which satisfy the following conditions: Each node has one incoming and one outgoing edge (and therefore graph is split into cycles). Each node has one incoming and one outgoing edge (and therefore graph is split into cycles). In $G$, if a cycle has length $m$, then it consists of $m$ consecutive integers, where numbers go up from the smallest number to the largest and down on the way back In $G$, if a cycle has length $m$, then it consists of $m$ consecutive integers, where numbers go up from the smallest number to the largest and down on the way back The sum of $m-1$ over all cycles is precisely $k-1$. The sum of $m-1$ over all cycles is precisely $k-1$. If we draw an edge between two cycles of $p$ if an element of the first cycle is connected to the element of the second cycle in $G$, this graph on $k$ nodes is connected. If we draw an edge between two cycles of $p$ if an element of the first cycle is connected to the element of the second cycle in $G$, this graph on $k$ nodes is connected. Each such graph is a corresponding graph of some optimal permutation $q$. The proof is left for the reader as an exercise. Now, how to solve our problem? Let's build $q$ element by element. The weights of all cyclic shifts of the same permutation are the same, so we start with $q_1 = 1$. Now, the only subproblem we have to be able to solve is to check if the current prefix $q$ of length $l$ is a prefix of some permutation with weight $2(k-1)$. So, we have to check if our current $l-1$ edges $q_i \\to p_{q_{i+1}}$ can be a subset of some graph $G$ satisfying all the conditions above. Denote these edges $(u_1, v_1), \\ldots, (u_{l-1}, v_{l-1})$. If edge has $u_i<v_i$, consider segment $[l_i, r_i] = [u_i, v_i]$, and call it right segment. If edge has $u_i>v_i$, consider segment $[l_i, r_i] = [v_i, u_i]$, and call it left segment. If $u_i = v_i$, call $u_i$ loop node. We can show that the following criteria are sufficient: No two right segments intersect internally. No two right segments intersect internally. No two left segments intersect internally. No two left segments intersect internally. No right/left segment contains a loop node. No right/left segment contains a loop node. Consider a graph on $k$ nodes, corresponding to the cycles of $p$. For each $1 \\le i \\le n-1$, if $[i, i+1]$ is contained in some segment, draw an edge between the corresponding cycles in which $i$, $i+1$ are. Then, this graph can't have a cycle (has to be a forest). Consider a graph on $k$ nodes, corresponding to the cycles of $p$. For each $1 \\le i \\le n-1$, if $[i, i+1]$ is contained in some segment, draw an edge between the corresponding cycles in which $i$, $i+1$ are. Then, this graph can't have a cycle (has to be a forest). Consider a graph on $k$ nodes, corresponding to the cycles of $p$. For each $1 \\le i \\le n-1$, unless $i$ or $i+1$ are loop nodes, or $i$ is the right end of two segments, or $i+1$ is the left end of two segments, draw an edge between the corresponding cycles in which $i$, $i+1$ are. Then, this graph must be connected. Consider a graph on $k$ nodes, corresponding to the cycles of $p$. For each $1 \\le i \\le n-1$, unless $i$ or $i+1$ are loop nodes, or $i$ is the right end of two segments, or $i+1$ is the left end of two segments, draw an edge between the corresponding cycles in which $i$, $i+1$ are. Then, this graph must be connected. These conditions may sound complicated but they are very simple implications of the conditions on $G$ above. The proof that if these conditions are satisfied then edges form a subset of some valid $G$ is left to the reader as an exercise too (tutorial is already too long, sorry). Total complexity is $O(n^3)$, as we can do up $O(n^2)$ checks, and each check takes $O(n)$ time.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1685",
    "index": "E",
    "title": "The Ultimate LIS Problem",
    "statement": "It turns out that this is exactly the $100$-th problem of mine that appears in some programming competition. So it has to be special! And what can be more special than another problem about LIS...\n\nYou are given a permutation $p_1, p_2, \\ldots, p_{2n+1}$ of integers from $1$ to $2n+1$. You will have to process $q$ updates, where the $i$-th update consists in swapping $p_{u_i}, p_{v_i}$.\n\nAfter each update, find any cyclic shift of $p$ with $LIS \\le n$, or determine that there is no such shift. (Refer to the output section for details).\n\nHere $LIS(a)$ denotes the length of longest strictly increasing subsequence of $a$.\n\n\\textbf{Hacks are disabled in this problem. Don't ask why}.",
    "tutorial": "Consider element $n+1$. Replace for a while $n+1$ by $0$, each element $\\le n$ by $-1$, and each element $\\ge n+2$ by $1$. It's well-known that for an array of $n$ of $1$ and $n$ of $-1$ there exists a cyclic shift such that all its prefix sums are nonnegative (which is equivalent to the sequence of these $1$s and $-1$s being balanced). Consider such cyclic shift for our array. It's easy to see now that in this cycle there is no increasing subsequence of length at $n+1$ of element distinct from $n+1$. Indeed, in such a subsequence we would have $t$ of $-1$s, and then $n + 1 - t$ of $1$s, which would mean that $t$-th $1$ goes after the $t$-th $-1$, meaning that the subsequence isn't balanced. So, if there is an increasing subsequence of length $n+1$ in this shift, $n+1$ is in it. Let's say there are $t$ elements $\\le n$ before $n+1$ in this subsequence and $n - t$ elements $\\ge n$ after $n+1$ in this subsequence. As $t$-th $1$ goes before $t$-th $-1$ in this shift, we get that there are exactly $t$ elements $\\ge n+2$ in this shift before $n+1$, and (similarly) exactly $n-t$ elements $\\le n$ in this shift after $n+1$. In addition, these two parts form (as ones and minus ones) two separate balanced sequences. Now, consider a shift in which $n+1$ is the first element. It's easy to see that if the condition above holds, then in this shift ones and minus ones also form a balanced subsequence. If $LIS$ of this shift is $n+1$, it must be the case that $n+1$ and $n$ ones form it, which implies that elements $n+1, n+2, \\ldots, 2n+1$ go clockwise in this permutation. Similarly, after considering a shift in which $n+1$ is the last element, we get that elements $1, 2, \\ldots, n+1$ go clockwise in this permutation. It turns out that if all the conditions above hold, then all shifts have $LIS \\ge n+1$. Indeed, consider any shift, elements to the left of $n+1$ smaller than $n+1$, $n+1$, and elements to the right of $n+1$ larger than $n+1$ form an increasing subsequence. From the fact that $1$s and $-1$s are balanced we get that numbers smaller than $n+1$ take at least half of the space before $n+1$, and larger than $n+1$ take at least half of the space after $n+1$, so its length is at least $n+1$. With all this knowledge, how do we solve the problem? We will keep track of all the $1$s and $-1$s with a segment tree, with queries \"smallest prefix sum on the subsegment\". When we need to provide the answer after the update, we will do the following: Check if the circular segment from $n+1$ to $n+1$ is balanced. If not, find the shift that makes $1$s and $-1$s balanced, its $LIS$ is at most $n$. Check if the circular segment from $n+1$ to $n+1$ is balanced. If not, find the shift that makes $1$s and $-1$s balanced, its $LIS$ is at most $n$. Then, check if $n+1, n+2, \\ldots, 2n+1$ go clockwise in the permutation. If not, then the shift in which $n+1$ is the first element has $LIS\\le n$. Then, check if $n+1, n+2, \\ldots, 2n+1$ go clockwise in the permutation. If not, then the shift in which $n+1$ is the first element has $LIS\\le n$. Then, check if $1, 2, \\ldots, n+1$ go clockwise in the permutation. If not, then the shift in which $n+1$ is the last element has $LIS\\le n$. Then, check if $1, 2, \\ldots, n+1$ go clockwise in the permutation. If not, then the shift in which $n+1$ is the last element has $LIS\\le n$. Otherwise, output $-1$. Otherwise, output $-1$. We check if $1, 2, \\ldots, n+1$ go clockwise by saving the following sum: $\\sum_{i = 1}^{n} (pos(i\\bmod (n+1) + 1) - pos(i))\\bmod (2n+1)$ If it's $2n+1$, they go clockwise, else not. We can update this sum in $O(1)$ per query. Total complexity is $O(\\log(n))$ per query.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1686",
    "index": "A",
    "title": "Everything Everywhere All But One",
    "statement": "You are given an array of $n$ integers $a_1, a_2, \\ldots, a_n$. After you watched the amazing film \"Everything Everywhere All At Once\", you came up with the following operation.\n\nIn one operation, you choose $n-1$ elements of the array and replace each of them with their arithmetic mean (which doesn't have to be an integer). For example, from the array $[1, 2, 3, 1]$ we can get the array $[2, 2, 2, 1]$, if we choose the first three elements, or we can get the array $[\\frac{4}{3}, \\frac{4}{3}, 3, \\frac{4}{3}]$, if we choose all elements except the third.\n\nIs it possible to make all elements of the array equal by performing a finite number of such operations?",
    "tutorial": "Suppose that we did one operation and not all numbers are equal. Let's say that we have $n-1$ numbers $x$ and $1$ number $y$ now, with $x \\neq y$. In the next operation, we have two options: to make operation with $n-1$ numbers $x$, or with $n-2$ of $x$ and one $y$. If we go with the first option, we will still have $n-1$ of $x$ and one $y$: numbers won't change. If we go with the second option, we will have one number $x$ and $n-1$ numbers $\\frac{(n-2)x + y}{n-1}$, where $\\frac{(n-2)x + y}{n-1} = x + \\frac{y-x}{n-1} \\neq x$. So, we again are in a state where we have $n-1$ copies of one number and one different number. So, if after the first operation not all numbers are equal, they will never be all equal. Therefore, it's enough to check each possible operation in $O(n^2)$ (which can be clearly optimized to $O(n)$). And go watch the movie Everything Everywhere All At Once, it's fantastic!",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1686",
    "index": "B",
    "title": "Odd Subarrays",
    "statement": "For an array $[b_1, b_2, \\ldots, b_m]$ define its number of inversions as the number of pairs $(i, j)$ of integers such that $1 \\le i < j \\le m$ and $b_i>b_j$. Let's call array $b$ \\textbf{odd} if its number of inversions is odd.\n\nFor example, array $[4, 2, 7]$ is odd, as its number of inversions is $1$, while array $[2, 1, 4, 3]$ isn't, as its number of inversions is $2$.\n\nYou are given a permutation $[p_1, p_2, \\ldots, p_n]$ of integers from $1$ to $n$ (each of them appears exactly once in the permutation). You want to split it into several consecutive subarrays (maybe just one), so that the number of the \\textbf{odd} subarrays among them is as large as possible.\n\nWhat largest number of these subarrays may be \\textbf{odd}?",
    "tutorial": "Consider any optimal splitting. Clearly, for any subarray $[b_1, b_2, \\ldots, b_m]$ which is not odd, we can just split it into $[b_1], [b_2], \\ldots, [b_m]$, For any odd subarray $[b_1, b_2, \\ldots, b_m]$ with $m \\ge 3$, there exists an $1 \\le i \\le m-1$ such that $b_i > b_{i+1}$ (otherwise $b$ is sorted and has no inversions). Then, we can split $b$ into $[b_1], [b_2], \\ldots, [b_{i-1}], [b_i, b_{i+1}], [b_{i+2}], \\ldots, [b_m]$, where we also have one odd subarray. So, if we can split $p$ into several subarrays such that there are $k$ odd subarrays, we can split it into several subarrays of length $\\le 2$ so that there are $k$ odd subarrays too. Then, let $dp_i$ denote the largest number of odd subarrays we can get from splitting $p[1:i]$. Then, $dp_i = max(dp_{i-1}, dp_{i-2} + (p_{i-1} > p_i))$. This $dp$ can be calculated in $O(n)$. It's also easy to show that the following greedy algorithm works: traverse the permutation from left to right, whenever you see two elements $p_{i-1}>p_i$, make a subarray $[p_{i-1}, p_i]$, and proceed from $p_{i+1}$.",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1687",
    "index": "A",
    "title": "The Enchanted Forest",
    "statement": "\\begin{quote}\nThe enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.\n\\hfill —Perfect Memento in Strict Sense\n\\end{quote}\n\nMarisa comes to pick mushrooms in the Enchanted Forest.\n\nThe Enchanted forest can be represented by $n$ points on the $X$-axis numbered $1$ through $n$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $a_1,a_2,\\ldots,a_n$.\n\nMarisa can start out at \\textbf{any} point in the forest on minute $0$. Each minute, the followings happen in order:\n\n- She moves from point $x$ to $y$ ($|x-y|\\le 1$, possibly $y=x$).\n- She collects all mushrooms on point $y$.\n- A new mushroom appears on each point in the forest.\n\nNote that she \\textbf{cannot} collect mushrooms on minute $0$.\n\nNow, Marisa wants to know the maximum number of mushrooms she can pick after $k$ minutes.",
    "tutorial": "Consider $k\\le n$ and $k>n$ separately. Consider maximizing the initial mushrooms and the additional mushrooms separately. Is there any common strategy? If $k\\le n$: Consider how to maximize the initial mushrooms she collects. Obviously she will not walk into one position more than one times, and the answer is $\\max\\limits_{k\\le i\\le n}\\sum\\limits_{j=i-k+1}^ia_j$. Consider how to maximize the initial mushrooms she collects. Obviously she will not walk into one position more than one times, and the answer is $\\max\\limits_{k\\le i\\le n}\\sum\\limits_{j=i-k+1}^ia_j$. Consider how to maximize the additional mushrooms she collects. Obviously she will not walk into one position more than one times, and the answer is $\\frac{k(k+1)}{2}$. Consider how to maximize the additional mushrooms she collects. Obviously she will not walk into one position more than one times, and the answer is $\\frac{k(k+1)}{2}$. We can find that maximizing the two parts shares the same strategy. So add up the answers of the two parts. If $k>n$: Consider how to maximize the initial mushrooms she collects. Obviously she can collect all of them. The answer is $\\sum\\limits_{i=1}^n a_i$. Consider how to maximize the additional mushrooms she collects. Let $b_i$ be her position on minute $k-i$ ($0\\le i< n$). After she collects the mushrooms on position $b_i$, a mushroom appears on each point, and she can not collect more than $i$ of them. In other words, she leaves at least $\\sum\\limits_{i=0}^{n-1}(n-i)=\\frac{n(n+1)}{2}$ mushrooms in the forest. Let $b_i=i+1$, she will leave exactly $\\sum\\limits_{i=0}^{n-1}(n-i)=\\frac{n(n+1)}{2}$ mushrooms in the forest. We can find that maximizing the two parts shares the same strategy. So add up the answers of the two parts. The time complexity is $O(n)$.",
    "code": "T=int(input())\nfor t in range(T):\n\tn,m=map(int,input().split())\n\ta=[0]+list(map(int,input().split()))\n\tfor i in range(1,n+1):\n\t\ta[i]+=a[i-1]\n\tif m>n:\n\t\tprint(a[n]+(m-1+m-n)*n//2)\n\telse:\n\t\tans=0\n\t\tfor i in range(n+1):\n\t\t\tif i>=m:\n\t\t\t\tans=max(ans,a[i]-a[i-m])\n\t\tprint(ans+(1+m-1)*(m-1)//2)",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1687",
    "index": "B",
    "title": "Railway System",
    "statement": "\\begin{quote}\nAs for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.\n\\hfill —Yasaka Kanako, Symposium of Post-mysticism\n\\end{quote}\n\nThis is an interactive problem.\n\nUnder the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of $n$ stations with $m$ bidirectional tracks connecting them. The $i$-th track has length $l_i$ ($1\\le l_i\\le 10^6$). Due to budget limits, the railway system \\textbf{may not be connected}, though there may be more than one track between two stations.\n\nThe value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.\n\nIn brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.\n\nKanako has a simulator only able to process no more than $2m$ queries. The input of the simulator is a string $s$ of length $m$, consisting of characters 0 and/or 1. The simulator will assume the $i$-th track functional if $s_i=$ 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.\n\nKanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.\n\nThe structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.",
    "tutorial": "$2m=m+m$. What can we do with the first $m$ queries? We can now the lengths of each edge with $m$ queries. Kruskal. We can get the lengths of each edge using $m$ queries by asking the maximum capacity of each edge separately. Then, sort the edges in non-decreasing order represented by ${l}$, and ask the maximum capacity of all prefixes represented by ${s}$ using the rest $m$ queries. Consider the process of Kruskal's algorithm. The $i$-th edge $(u_i,v_i)$ being in the minimum full spanning forest is equivalent to there being no path between $u_i$ and $v_i$ in the graph consisting of former edges, which is equivalent to $s_i=s_{i-1}+l_i$. Then we know whether each edge exists in the minimum full spanning forest. The time complexity is $O(m^2)$.",
    "code": "n,m=map(int,input().split())\na=[]\nfor i in range(m):\n\tprint('?','0'*i+'1'+'0'*(m-i-1),flush=1)\n\ta.append(int(input()))\ncur=0\ns=['0' for i in range(m)]\nfor i in range(m):\n\tx=0\n\tfor j in range(m):\n\t\tif a[x]>a[j]:\n\t\t\tx=j\n\ts[x]='1'\n\tprint('? ',*s,sep='',flush=1)\n\tc=int(input())\n\tif (cur+a[x]==c):\n\t\tcur+=a[x]\n\telse:\n\t\ts[x]='0'\n\ta[x]=2000000\nprint('!',cur,flush=1)",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "interactive",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1687",
    "index": "C",
    "title": "Sanae and Giant Robot",
    "statement": "\\begin{quote}\nIs it really?! The robot only existing in my imagination?! The Colossal Walking Robot?!!\n\\hfill — Kochiya Sanae\n\\end{quote}\n\nSanae made a giant robot — Hisoutensoku, but something is wrong with it. To make matters worse, Sanae can not figure out how to stop it, and she is forced to fix it on-the-fly.The state of a robot can be represented by an array of integers of length $n$. Initially, the robot is at state $a$. She wishes to turn it into state $b$.\n\nAs a great programmer, Sanae knows the art of copy-and-paste. In one operation, she can choose some segment from given segments, copy the segment from $b$ and paste it into \\textbf{the same place} of the robot, replacing the original state there. However, she has to ensure that the sum of $a$ \\textbf{does not change} after each copy operation in case the robot go haywire. Formally, Sanae can choose segment $[l,r]$ and assign $a_i = b_i$ ($l\\le i\\le r$) if $\\sum\\limits_{i=1}^n a_i$ does not change after the operation.\n\nDetermine whether it is possible for Sanae to successfully turn the robot from the initial state $a$ to the desired state $b$ with any (possibly, zero) operations.",
    "tutorial": "Let $b_i=0$ for convenience. The interval selected satisfies $\\sum\\limits_{i=l}^r a_i=0$. What does range sum remind you of? Let $s_i=\\sum\\limits_{k=1}^i a_k-b_k$. The task can be described as: Given an array $s$. For some given interval $[l,r]$ if $s_{l-1}=s_r$, we can assign $s_r$ to $s_i$ ($l\\le i< r$). The goal is to make $s_i=0$ ($0\\le i\\le n$). Obviously assigning non-zero value to $s$ is useless, while assigning $0$ to $s$ does no harm. Therefore, we can repeatedly choose any interval $[l,r]$ satisfying $s_{l-1}=s_r=0$, and assigning $0$ to all non-zero $s_i$ ($l\\le i< r$) until there is no such interval. We can use set in C++ or disjoint set or segment tree to find such $i$. As each element can be assigned to $0$ at most once, the time complexity is $O((n+m)\\log n)$. It is Div.2 D at first.",
    "code": "#include \"bits/stdC++.h\"\nusing namespace std;\n#define all(x) (x).begin(),(x).end()\ntypedef long long ll;\nint main()\n{\n\tios::sync_with_stdio(0);cin.tie(0);\n\tint T;cin>>T;\n\twhile (T--)\n\t{\n\t\tint n,m,i;\n\t\tcin>>n>>m;\n\t\tvector<ll> a(n+1);\n\t\tvector<int> deg(m,2),b(n+1),id(n+1);\n\t\tvector<pair<int,int>> p(m);\n\t\tvector<vector<int>> e(n+1);\n\t\tiota(all(id),0);\n\t\tset<int> s(all(id));\n\t\tfor (i=1;i<=n;i++) cin>>a[i];\n\t\tfor (i=1;i<=n;i++) cin>>b[i];\n\t\tfor (i=0;i<m;i++)\n\t\t{\n\t\t\tauto &[l,r]=p[i];\n\t\t\tcin>>l>>r;\n\t\t\te[l-1].push_back(i);\n\t\t\te[r].push_back(i);\n\t\t}\n\t\tfor (i=1;i<=n;i++) a[i]-=b[i];\n\t\tfor (i=1;i<=n;i++) a[i]+=a[i-1];\n\t\tqueue<int> q;\n\t\tfor (i=0;i<=n;i++) if (!a[i]) q.push(i),s.erase(i);\n\t\twhile (q.size())\n\t\t{\n\t\t\tint x=q.front();q.pop();\n\t\t\tfor (int y:e[x]) if (!--deg[y])\n\t\t\t{\n\t\t\t\tauto [l,r]=p[y];\n\t\t\t\tauto lt=s.lower_bound(l),rt=s.upper_bound(r);\n\t\t\t\tfor (auto it=lt;it!=rt;++it) q.push(*it);\n\t\t\t\ts.erase(lt,rt);\n\t\t\t}\n\t\t}\n\t\tcout<<(s.size()?\"NO\\n\":\"YES\\n\");\n\t}\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dsu",
      "greedy",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1687",
    "index": "D",
    "title": "Cute number",
    "statement": "\\begin{quote}\nRan is especially skilled in computation and mathematics. It is said that she can do unimaginable calculation work in an instant.\n\\hfill —Perfect Memento in Strict Sense\n\\end{quote}\n\nRan Yakumo is a cute girl who loves creating cute Maths problems.\n\nLet $f(x)$ be the minimal square number \\textbf{strictly} greater than $x$, and $g(x)$ be the maximal square number less than or equal to $x$. For example, $f(1)=f(2)=g(4)=g(8)=4$.\n\nA positive integer $x$ is cute if $x-g(x)<f(x)-x$. For example, $1,5,11$ are cute integers, while $3,8,15$ are not.\n\nRan gives you an array $a$ of length $n$. She wants you to find the smallest non-negative integer $k$ such that $a_i + k$ is a cute number for any element of $a$.",
    "tutorial": "What is the range of the answer? How to solve it in $O(na_n)$? For any integer $x$, iff we can find $w$ satisfying $x\\in[w^2,w^2+w]$, we have $x-w^2 < (w+1)^2-x$, which means $x$ is beautiful. Define $f(x)=w$. It is easy to find that $k\\leq a_n^2$, and there are only $a_n$ useful $w$ because $w\\le a_n$. Enumerate $f(a_1+k)$ ($f(a_1+k)\\le a_n$), and calculate the range of $a_i+k$ in order. It can be shown that the range is an interval for all $1\\le i\\le n$. So we can solve this problem in $O(n a_n)$. We call $i$ a jump if $f(a_{i}+k)\\ne f(a_{i-1}+k)$. Assuming $f(a_1+k)=w$, there is no more than $\\frac{a_n}{w}$ jumps. We only need to enumerate jumps to calculate the ranges. We can use linked list or set in C++ to maintain it. The time complexity is $O(\\sum\\limits_{w=1}^{a_n} \\frac {a_n}{w}=a_n\\log a_n)$.",
    "code": "#include <bits/stdC++.h>\nusing namespace std;\ntypedef long long ll;\n#define all(x) (x).begin(),(x).end()\nconst int N=2e6+2;\nvector<int> e[N];\nstruct Q\n{\n\tint id;\n\tmutable int len,t;\n\tbool operator<(const Q &o) const {return id<o.id;}\n};\nint main()\n{\n\tios::sync_with_stdio(0);cin.tie(0);\n\tcout<<setiosflags(ios::fixed)<<setprecision(15);\n\tint n,i,j;\n\tcin>>n;\n\tvector<int> a(n);\n\tfor (int &x:a) cin>>x;\n\ta.resize(unique(all(a))-a.begin());\n\tn=a.size();\n\tset<Q> s;\n\tfor (i=1;i<n;i++) s.insert({i,a[i]-a[i-1],0}),e[a[i]-a[i-1]].push_back(i);\n\tfor (i=1;;i++)\n\t{\n\t\tfor (int x:e[i])\n\t\t{\n\t\t\tauto it=s.find({x,i,0});\n\t\t\tassert(it!=s.end());\n\t\t\tauto L=it==s.begin()?s.end():prev(it),R=next(it);\n\t\t\tif (L!=s.end()&&L->t&&R!=s.end()&&R->t)\n\t\t\t{\n\t\t\t\tL->len+=i+R->len;\n\t\t\t\ts.erase(it);\n\t\t\t\ts.erase(R);\n\t\t\t}\n\t\t\telse if (L!=s.end()&&L->t)\n\t\t\t{\n\t\t\t\tL->len+=i;\n\t\t\t\ts.erase(it);\n\t\t\t}\n\t\t\telse if (R!=s.end()&&R->t)\n\t\t\t{\n\t\t\t\tR->len+=i;\n\t\t\t\ts.erase(it);\n\t\t\t}\n\t\t\telse it->t=1;\n\t\t}\n\t\tif (a[0]<=(ll)i*(i+1)) //[i*i,i*(i+1)]\n\t\t{\n\t\t\tll L=max((ll)a[0],(ll)i*i),R=(ll)i*(i+1);\n\t\t\tint step=i;\n\t\t\tfor (auto [id,D,t]:s)\n\t\t\t{\n\t\t\t\tL+=D;\n\t\t\t\tif (!t)\n\t\t\t\t{\n\t\t\t\t\tstep=ceil((sqrt(1+4*L)-1)/2);\n\t\t\t\t\t//if (L>(ll)step*(step+1)) ++step;\n\t\t\t\t\tL=max(L,(ll)step*step);\n\t\t\t\t}\n\t\t\t\tR=min(R+D,(ll)step*(step+1));\n\t\t\t\tif (L>R) break;\n\t\t\t}\n\t\t\tif (L<=R)\n\t\t\t{\n\t\t\t\tcout<<L-a.back()<<endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dsu",
      "implementation",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1687",
    "index": "E",
    "title": "Become Big For Me",
    "statement": "\\begin{quote}\nCome, let's build a world where even the weak are not forgotten!\n\\hfill —Kijin Seija, Double Dealing Characters\n\\end{quote}\n\nShinmyoumaru has a mallet that can turn objects bigger or smaller. She is testing it out on a sequence $a$ and a number $v$ whose initial value is $1$. She wants to make $v = \\gcd\\limits_{i\\ne j}\\{a_i\\cdot a_j\\}$ by \\textbf{no more than} $10^5$ operations ($\\gcd\\limits_{i\\ne j}\\{a_i\\cdot a_j\\}$ denotes the $\\gcd$ of all products of two distinct elements of the sequence $a$).\n\nIn each operation, she picks a subsequence $b$ of $a$, and does one of the followings:\n\n- \\textbf{Enlarge}: $v = v \\cdot \\mathrm{lcm}(b)$\n- \\textbf{Reduce}: $v = \\frac{v}{\\mathrm{lcm}(b)}$\n\nNote that she does \\textbf{not} need to guarantee that $v$ is an integer, that is, $v$ does \\textbf{not} need to be a multiple of $\\mathrm{lcm}(b)$ when performing Reduce.\n\nMoreover, she wants to guarantee that the total length of $b$ chosen over the operations does not exceed $10^6$. Fine a possible operation sequence for her. \\textbf{You don't need to minimize anything}.",
    "tutorial": "Consider the Inclusion-Exclusion Principle. Let $f_p(x)$ be the maximum integer satisfying $p^{f_p(x)}|x$. For each prime $p$, WLOG, assuming $f_p(a_i) \\le f_p(a_{i+1})$ ($1\\le i<n$) then $f_p(\\gcd{a_ia_j})=f_p(a_1)+f_p(a_2)$. Consider the Inclusion-Exclusion Principle: $k\\text{-th}\\min{S}=\\sum\\limits_{\\varnothing\\ne T\\subseteq S}(-1)^{|T|-k}\\tbinom{|T|-1}{k-1}\\max{T}$. So $f_p(\\gcd\\{a_ia_j\\})=\\sum\\limits_{\\varnothing\\ne T\\subseteq \\{f_p(a)\\}}((-1)^{|T|-1}+(-1)^{|T|}(|T|-1))\\max\\{T\\}=\\sum\\limits_{\\varnothing\\ne T\\subseteq \\{f_p(a)}(-1)^{|T|}(|T|-2)\\max\\{T\\}$ Then $\\gcd{a_ia_j}=\\prod\\limits_{\\varnothing\\ne T\\subseteq {a}}\\operatorname{lcm}{T}^{(-1)^{|T|}(|T|-2)}$. We can solve the task by choosing a short subsequence $c$ satisfying $\\gcd{a_ia_j}=\\gcd{c_ic_j}$ and enumerating its subsets. To fit in the constraint, the length of $c$ should be no longer than $14$. Think of an easier task: choosing a small subset $g(a)$ satisfying $\\gcd{a}=\\gcd g(a)$. If we can solve it, we can construct $c$ by choosing $g(a)\\cup g(a-g(a))$ if $|g(a)|$ does not exceed $7$. First, choose an arbitrary element $x$ in ${a}$ as the only element of $S$, and factorize $x$ into $\\prod\\limits_{i=1}^{\\omega(x)} p_i^{k_i}$ ($p_i< p_{i+1}$). For each $i$, if $f_{p_i}(S)=\\min_j f_{p_i}(a_j)$ then add an arbitrary element $y_i$ in ${a}$ satisfying $f_{p_i}(y_i)=\\min_j f_{p_i}(a_j)$ to $S$. Now obviously $\\gcd S=\\gcd {a}$, but $|S|\\le\\omega(x)+1\\le 8$. We can prove that $|S|=8$ and $\\gcd(S-{x})\\ne \\gcd {a}$ do not hold at the same time, then we can solve the task by choosing $g(a)=\\begin{cases}S&(|S|<8)\\\\S-\\{x\\}&(|S|=8)\\end{cases}$ . Consider the necessary condition of $|S|=\\omega(x)=8\\land\\gcd(S-{x})\\ne \\gcd {a}$: $\\exists d\\in\\text{Prime}, f_{d}(x)<\\min\\limits_{y\\in S-{x}}f_{d}(y)$. According to how we choose $y_i$, $d\\ne p_i$, $d\\prod\\limits_{i=2} ^{7}p_i|y_1$, so $d\\prod\\limits_{i=1} ^{7}p_i|y_1p_1$. Since $2\\times3\\times5\\times7\\times11\\times13\\times17\\times19=9699690$ and $y_1\\le 10^6$, $p_1\\ge 11$. But $x\\ge 11\\times 13\\times 17\\times 19\\times 23\\times 29\\times 31>10^6$, causing a conflict. So $|S|=\\omega(x)=8\\land\\gcd(S-{x})\\ne \\gcd {a}$ does not hold. The time complexity is $O(n\\log \\max{a_i}+2^{\\max{\\omega(a_i)}}\\max{\\omega(a_i)}+n\\max{\\omega(a_i)})$. Worth mentioning, with this conclusion (such small set exists), we can solve it much more easier. Just choose a small set by greedy, and enumerate its subset of size $14$. There are more than $500$ tests at first.",
    "code": "#pragma GCC target(\"popcnt\")\n#include \"bits/stdC++.h\"\nusing namespace std;\ntypedef unsigned int ui;\ntypedef long long ll;\n#define all(x) (x).begin(),(x).end()\nnamespace Prime\n{\n\ttypedef unsigned int ui;\n\ttypedef unsigned long long ll;\n\tconst int N=1e6+2;\n\tui pr[N],mn[N],phi[N],cnt;\n\tint mu[N];\n\tvoid init_prime()\n\t{\n\t\tui i,j,k;\n\t\tphi[1]=mu[1]=1;\n\t\tfor (i=2;i<N;i++)\n\t\t{\n\t\t\tif (!mn[i])\n\t\t\t{\n\t\t\t\tpr[cnt++]=i;\n\t\t\t\tphi[i]=i-1;mu[i]=-1;\n\t\t\t\tmn[i]=i;\n\t\t\t}\n\t\t\tfor (j=0;(k=i*pr[j])<N;j++)\n\t\t\t{\n\t\t\t\tmn[k]=pr[j];\n\t\t\t\tif (i%pr[j]==0)\n\t\t\t\t{\n\t\t\t\t\tphi[k]=phi[i]*pr[j];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tphi[k]=phi[i]*(pr[j]-1);\n\t\t\t\tmu[k]=-mu[i];\n\t\t\t}\n\t\t}\n\t\t//for (i=2;i<N;i++) if (mu[i]<0) mu[i]+=p;\n\t}\n\tvector<pair<ui,ui>> getw(ll x)\n\t{\n\t\tui i;\n\t\tassert((ll)(N-1)*(N-1)>=x);\n\t\tvector<pair<ui,ui>> r;\n\t\tfor (i=0;i<cnt&&pr[i]*pr[i]<=x&&x>=N;i++) if (x%pr[i]==0)\n\t\t{\n\t\t\tui y=pr[i],z=1,tmp;\n\t\t\tx/=y;\n\t\t\twhile (x==(tmp=x/y)*y) x=tmp,++z;\n\t\t\tr.push_back({y,z});\n\t\t}\n\t\tif (x>=N)\n\t\t{\n\t\t\tr.push_back({x,1});\n\t\t\treturn r;\n\t\t}\n\t\twhile (x>1)\n\t\t{\n\t\t\tui y=mn[x],z=1,tmp;\n\t\t\tx/=y;\n\t\t\twhile (x==(tmp=x/y)*y) x=tmp,++z;\n\t\t\tr.push_back({y,z});\n\t\t}\n\t\treturn r;\n\t}\n}\nusing Prime::pr,Prime::phi,Prime::getw;\nusing Prime::mu,Prime::init_prime;\nconst int N=1e6+5;\nint a[N];\nbool ed[N];\nint main()\n{\n\tios::sync_with_stdio(0);cin.tie(0);\n\tcout<<setiosflags(ios::fixed)<<setprecision(15);\n\tint n,i,j;\n\tinit_prime();\n\tcin>>n;\n\tvector<vector<pair<ui,ui>>> b(n+1);\n\tfor (i=1;i<=n;i++)\n\t{\n\t\tcin>>a[i];\n\t\tb[i]=getw(a[i]);\n\t}\n\tif (n==3&&a[1]==6&&a[2]==10&&a[3]==15)\n\t{\n\t    cout<<\"1\\n0 3 1 2 3\\n\";\n\t    return 0;\n\t}\n\tif (n==4&&a[1]==2&&a[2]==4&&a[3]==8&&a[4]==16)\n\t{\n\t    cout<<\"2\\n0 1 4\\n1 1 1\\n\";\n\t    return 0;\n\t}\n\tvector<int> s;\n\tauto getmin=[&]()\n\t{\n\t\tint i,j,m=0;\n\t\tfor (i=1;i<=n;i++) if (!ed[i]) break;\n\t\tif (i>n) return;\n\t\tint x=i;\n\t\tvector<int> nm(N,1'000'000'000),id(N);\n\t\tvector<vector<int>> occ(N);\n\t\tvector<int> flg(n+1);\n\t\tset<int> S;\n\t\tfor (i=1;i<=n;i++) if (!ed[i])\n\t\t{\n\t\t\tfor (auto [p,t]:b[i])\n\t\t\t{\n\t\t\t\tocc[p].push_back(i);\n\t\t\t\tif (nm[p]>t)\n\t\t\t\t{\n\t\t\t\t\tnm[p]=t;\n\t\t\t\t\tid[p]=i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t++m;\n\t\t\tS.insert(i);\n\t\t}\n\t\tfor (i=2;i<N;i++) if (id[i]&&occ[i].size()!=m)\n\t\t{\n\t\t\tfor (int x:occ[i]) S.erase(x);\n\t\t\tnm[i]=0;id[i]=*S.begin();\n\t\t\tfor (int x:occ[i]) S.insert(x);\n\t\t}\n\t\tvector<int> r;\n\t\tfor (auto [p,t]:b[x]) if (t!=nm[p]) r.push_back(id[p]);\n\t\tvector<ui> mn(N,1'000'000'000),cnt(N),toc(N);\n\t\tfor (auto [p,t]:b[x]) toc[p]=t;\n\t\tfor (int x:r) for (auto [p,t]:b[x]) mn[p]=min(mn[p],t),++cnt[p];\n\t\tfor (i=2;i<N;i++) if (cnt[i]==r.size()&&mn[i]>toc[i]) break;\n\t\tif (i<N) r.push_back(x);\n\t\tfor (int x:r) ed[x]=1,s.push_back(x);\n\t};\n\tgetmin();getmin();\n\tsort(all(s));s.resize(unique(all(s))-s.begin());\n\tn=s.size();assert(n<=14);\n\tll D=0;\n\tfor (i=0;i<n;i++) for(j=i+1;j<n;j++) D=gcd(D,(ll)a[s[i]]*a[s[j]]);\n\tif (D==1) {cout<<\"0\\n\";return 0;}\n\tvector<pair<int,vector<int>>> ans;\n\tfor (i=1;i<1<<n;i++)\n\t{\n\t\tvector<int> v;\n\t\tfor (j=0;j<n;j++) if (i>>j&1) v.push_back(s[j]);\n\t\tint pc=__builtin_popcount(i);\n\t\tpc=pc&1?2-pc:pc-2;\n\t\tfor (j=1;j<=pc;j++) ans.push_back({0,v});\n\t\tpc=-pc;\n\t\tfor (j=1;j<=pc;j++) ans.push_back({1,v});\n\t}\n\tint totsize=0;\n\tcout<<ans.size()<<'\\n';\n\tfor (auto &[x,v]:ans)\n\t{\n\t\tcout<<x<<' '<<v.size();\n\t\tfor (int x:v) cout<<' '<<x;\n\t\tcout<<'\\n';\n\t\tassert((totsize+=v.size())<=1'000'000);\n\t}\n\t//cout<<totsize<<endl;\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1687",
    "index": "F",
    "title": "Koishi's Unconscious Permutation",
    "statement": "\\begin{quote}\nAs she closed the Satori's eye that could read minds, Koishi gained the ability to live in unconsciousness. Even she herself does not know what she is up to.\n\\hfill — Subterranean Animism\n\\end{quote}\n\nKoishi is unconsciously permuting $n$ numbers: $1, 2, \\ldots, n$.\n\nShe thinks the permutation $p$ is \\textbf{beautiful} if $s=\\sum\\limits_{i=1}^{n-1} [p_i+1=p_{i+1}]$. $[x]$ equals to $1$ if $x$ holds, or $0$ otherwise.\n\nFor each $k\\in[0,n-1]$, she wants to know the number of beautiful permutations of length $n$ satisfying $k=\\sum\\limits_{i=1}^{n-1}[p_i<p_{i+1}]$.",
    "tutorial": "How Elegia's mind works? We call a permutation $p$ of length $n-s$ is good if $\\forall i\\in[1,n-s-1],p_i+1\\not=p_{i+1}$. If we can calculate $ans_k=\\sum\\limits\\limits_{p\\ is\\ \\text{good}}[\\sum\\limits\\limits_{i=1}^{n-s-1}[p_i<p_{i+1}]=k]$ then, we can get the answer easily by Binomial inversion. So we only need to focus on how to calculate $ans_k$. For convenience, let $n\\rightarrow n-s$. We have: $ans_k = \\sum\\limits_{i=0}^{k} \\binom{n-1}{i} (-1)^i \\left\\langle\\begin{matrix} n-i\\\\n-k-1 \\end{matrix}\\right\\rangle$ where $\\left\\langle\\begin{matrix} n\\\\m \\end{matrix}\\right\\rangle$ is the Eulerian number. As is known to all, the generating function of Eulerian number is: $\\left\\langle\\begin{matrix} n\\\\m \\end{matrix}\\right\\rangle = [x^my^n]\\dfrac{n!(x-1)}{x-e^{(x-1)y}}$ So we have: $ans_k = \\sum\\limits_{j=0}^{k} \\binom{n-1}{j} (-1)^j \\left\\langle\\begin{matrix} n-j\\\\n-k-1 \\end{matrix}\\right\\rangle\\\\ = [x^{n-k-1}] \\sum\\limits_{j=0}^{k} \\binom{n-1}{j} (-1)^j [y^{n-j}]\\dfrac{(n-j)!(x-1)}{x-e^{(x-1)y}}\\\\ = [x^{n-k-1}] \\sum\\limits_{j=0}^{k} \\dfrac{(n-1)!}{j!} (-1)^j (n-j)[y^{n-j}]\\dfrac{x-1}{x-e^{(x-1)y}}\\\\ = [x^{n-k-1}] \\sum\\limits_{j=0}^{k} \\dfrac{(n-1)!}{j!} (-1)^j [y^{n-j-1}]\\dfrac{\\text{d}}{\\text{d}y}\\dfrac{x-1}{x-e^{(x-1)y}}\\\\ =(n-1)![x^{n-k-1}] \\sum\\limits_{j=0}^{k} \\dfrac{(-1)^j}{j!} [y^{n-j-1}] \\dfrac{(x-1)^2e^{(x-1)y}}{(x-e^{(x-1)y})^2}\\\\ =(n-1)![x^{n-k-1}] \\sum\\limits_{j=0}^{k} [y^j]e^{-y} [y^{n-j-1}] \\dfrac{(x-1)^2e^{(x-1)y}}{(x-e^{(x-1)y})^2}\\\\ =(n-1)![x^{n-k-1}] [y^{n-1}] \\dfrac{(x-1)^2e^{(x-2)y}}{(x-e^{(x-1)y})^2}\\\\ =(n-1)![x^{n-k-1}] [y^{n-1}] \\dfrac{(x-1)^2e^{xy}}{(xe^y-e^{xy})^2}\\\\ =(n-1)![x^{n-k-1}] [y^{n-1}] \\dfrac{(x-1)^2e^{-xy}}{(xe^{(1-x)y}-1)^2}\\\\$ Consider how to calculate $[y^{n-1}] \\dfrac{(x-1)^2e^{-xy}}{(xe^{(1-x)y}-1)^2}$. Let $u=(1-x)y$ and we have: $[y^{n-1}] \\dfrac{(x-1)^2e^{-xy}}{(xe^{(1-x)y}-1)^2} = (1-x)^{n+1} [u^{n-1}] \\dfrac{e^{\\frac{-xu}{1-x}}}{(xe^u-1)^2}\\\\ = (1-x)^{n+1} [u^{n-1}] \\dfrac{e^{\\frac{-xu}{1-x}}}{(1-xe^u)^2}$ And: $[u^{n-1}] \\dfrac{e^{\\frac{-xu}{1-x}}}{(1-xe^u)^2}\\\\= [u^{n-1}] \\sum\\limits_{i=0} (i+1)x^ie^{(i-\\frac{x}{1-x})u}\\\\= [u^{n-1}]\\sum\\limits_{i=0}(i+\\frac{1}{1-x}+\\frac{-x}{1-x})x^ie^{(i-\\frac{x}{1-x})u}\\\\= [u^{n-1}] \\sum\\limits_{i=0}(i-\\frac{x}{1-x})x^ie^{(i-\\frac{x}{1-x})u}+ [u^{n-1}] \\frac{1}{1-x}\\sum\\limits_{i=0}x^ie^{(i-\\frac{x}{1-x})u}\\\\= [u^{n}] \\sum\\limits_{i=0}nx^ie^{(i-\\frac{x}{1-x})u}+ [u^{n-1}] \\frac{1}{1-x}\\sum\\limits_{i=0}x^ie^{(i-\\frac{x}{1-x})u}\\\\= [u^{n}] \\dfrac{ne^{-\\frac{xu}{1-x}}}{1-xe^u}+ [u^{n-1}] \\frac{1}{1-x} \\dfrac{e^{-\\frac{xu}{1-x}}}{1-xe^u}$ So we just need to focus on how to calculate $[u^{n}]\\dfrac{e^{-\\frac{xu}{1-x}}}{1-xe^u}$. Let $w=e^u-1$, we have: $[u^{n}] \\dfrac{(w+1)^{-\\frac{x}{1-x}}}{1-x(w+1)}\\\\ = \\sum\\limits_{m=0}^n [u^n](e^u-1)^m[w^{m}] \\dfrac{(w+1)^{-\\frac{x}{1-x}}}{1-x(w+1)}\\\\ = \\sum\\limits_{m=0}^n [u^n](e^u-1)^m[w^{m}] \\dfrac{\\sum\\limits_{i=0}w^i\\binom{-\\frac{x}{1-x}}{i}}{1-x(w+1)}\\\\ = \\sum\\limits_{m=0}^n [u^n](e^u-1)^m[w^{m}] \\dfrac{\\sum\\limits_{i=0}w^i\\binom{-\\frac{x}{1-x}}{i}}{1-xw-x}\\\\ = \\dfrac{1}{1-x} \\sum\\limits_{m=0}^n [u^n](e^u-1)^m[w^{m}] \\dfrac{\\sum\\limits_{i=0}w^i\\binom{-\\frac{x}{1-x}}{i}}{1-\\frac{x}{1-x}w}\\\\ = \\dfrac{1}{1-x} \\sum\\limits_{m=0}^n [u^n](e^u-1)^m \\sum\\limits_{i=0}^m \\binom{-\\frac{x}{1-x}}{i} (\\dfrac{x}{1-x})^{m-i}$ Let $s=\\dfrac{x}{1-x}$ . Try to calculate $\\dfrac{1}{1-x} \\sum\\limits_{m=0}^n [u^n](e^u-1)^m \\sum\\limits_{i=0}^m \\binom{-s}{i} s^{m-i}$ . We know $[u^n]\\ (e^u-1)^m$ is the Stirling numbers of the second kind. We can calculate it in $O(n\\log n)$ or $O(n \\log^2 n)$. Build a $2 \\times 2$ matrix to get $\\sum\\limits_{i=0}^m \\binom{-s}{i} s^{m-i}$. Let $M_m=\\left[ \\begin{matrix} \\frac{-s-m}{m+1} & \\frac{-s-m}{m+1}\\\\ 0 & s \\end{matrix} \\right]$ And we have $\\left[ \\begin{matrix} \\binom{-s}{m} & \\sum\\limits_{i=0}^m\\binom{-s}{i}s^{m-i} \\end{matrix} \\right] \\times \\left[ \\begin{matrix} \\frac{-s-m}{m+1} & \\frac{-s-m}{m+1}\\\\ 0 & s \\end{matrix} \\right] = \\left[ \\begin{matrix} \\binom{-s}{m+1} & \\sum\\limits_{i=0}^{m+1}\\binom{-s}{i}s^{m+1-i} \\end{matrix} \\right]$ So we can divide and conquer to calculate it in $O(n \\log^2 n)$.",
    "code": "#include <cstdio>\n#include <cstring>\n \n#include <algorithm>\n#include <iostream>\n#include <chrono>\n#include <random>\n#include <functional>\n#include <vector>\n \n#define LOG(FMT...) fprintf(stderr, FMT)\n \nusing namespace std;\n \ntypedef long long ll;\ntypedef unsigned long long ull;\n \nconst int P = 998244353, R = 3;\nconst int BRUTE_N2_LIMIT = 50;\n \nint mpow(int x, int k, int p = P) {\n  int ret = 1;\n  while (k) {\n    if (k & 1)\n      ret = ret * (ll) x % p;\n    x = x * (ll) x % p;\n    k >>= 1;\n  }\n  return ret;\n}\n \nint norm(int x) { return x >= P ? x - P : x; }\n \nint reduce(int x) {\n  return x < 0 ? x + P : x;\n}\n \nvoid add(int& x, int y) {\n  if ((x += y) >= P)\n    x -= P;\n}\n \nvoid sub(int& x, int y) {\n  if ((x -= y) < 0)\n    x += P;\n}\n \nstruct Simple {\n  int n;\n  vector<int> fac, ifac, inv;\n \n  void build(int n) {\n    this->n = n;\n    fac.resize(n + 1);\n    ifac.resize(n + 1);\n    inv.resize(n + 1);\n    fac[0] = 1;\n    for (int x = 1; x <= n; ++x)\n      fac[x] = fac[x - 1] * (ll) x % P;\n    inv[1] = 1;\n    for (int x = 2; x <= n; ++x)\n      inv[x] = -(P / x) * (ll) inv[P % x] % P + P;\n    ifac[0] = 1;\n    for (int x = 1; x <= n; ++x)\n      ifac[x] = ifac[x - 1] * (ll) inv[x] % P;\n  }\n \n  Simple() {\n    build(1);\n  }\n \n  void check(int k) {\n    int nn = n;\n    if (k > nn) {\n      while (k > nn)\n        nn <<= 1;\n      build(nn);\n    }\n  }\n \n  int gfac(int k) {\n    check(k);\n    return fac[k];\n  }\n \n  int gifac(int k) {\n    check(k);\n    return ifac[k];\n  }\n \n  int ginv(int k) {\n    check(k);\n    return inv[k];\n  }\n \n  int binom(int n, int m) {\n    if (m < 0 || m > n)\n      return 0;\n    return gfac(n) * (ll) gifac(m) % P * gifac(n - m) % P;\n  }\n} simp;\n \nconst int L2 = 11;\n \nstruct NTT {\n  int L;\n  vector<int> root;\n \n  NTT() : L(-1) {}\n \n  void prepRoot(int l) {\n    L = l;\n    root.resize((1 << L) + 1);\n    int i, n = 1 << L;\n    int *w2 = root.data();\n    *w2 = 1;\n    w2[1 << l] = mpow(31, 1 << (21 - l));\n \n    for (i = l; i; --i)\n      w2[1 << (i - 1)] = (ull) w2[1 << i] * w2[1 << i] % P;\n \n    for (i = 1; i < n; ++i)\n      w2[i] = (ull) w2[i & (i - 1)] * w2[i & -i] % P;\n  }\n \n  void DIF(int *a, int l) {\n    int *j, *k, n = 1 << l, len = n >> 1, r, *o;\n \n    for (; len; len >>= 1)\n      for (j = a, o = root.data(); j != a + n; j += len << 1, ++o)\n        for (k = j; k != j + len; ++k) {\n          r = (ull) *o * k[len] % P;\n          k[len] = reduce(*k - r);\n          add(*k, r);\n        }\n  }\n \n  void DIT(int *a, int l) {\n    int *j, *k, n = 1 << l, len = 1, r, *o;\n \n    for (; len != n; len <<= 1)\n      for (j = a, o = root.data(); j != a + n; j += len << 1, ++o)\n        for (k = j; k != j + len; ++k) {\n          r = reduce(*k + k[len] - P);\n          k[len] = ull(*k - k[len] + P) * *o % P;\n          *k = r;\n        }\n  }\n \n  void fft(int *a, int lgn, int d = 1) {\n    if (L < lgn) prepRoot(lgn);\n    int n = 1 << lgn;\n    if (d == 1) DIF(a, lgn);\n    else {\n      DIT(a, lgn);\n      reverse(a + 1, a + n);\n      ull nv = P - (P - 1) / n;\n      for (int i = 0; i < n; ++i) a[i] = a[i] * nv % P;\n    }\n  }\n} ntt;\n \nstruct Poly {\n  vector<int> a;\n \n  Poly(int v = 0) : a(1) {\n    if ((v %= P) < 0)\n      v += P;\n    a[0] = v;\n  }\n \n  Poly(const vector<int> &a) : a(a) {}\n \n  Poly(initializer_list<int> init) : a(init) {}\n \n  // Helps\n  int operator[](int k) const { return k < a.size() ? a[k] : 0; }\n \n  int &operator[](int k) {\n    if (k >= a.size())\n      a.resize(k + 1);\n    return a[k];\n  }\n \n  int deg() const { return a.size() - 1; }\n \n  void redeg(int d) { a.resize(d + 1); }\n \n  Poly monic() const;\n \n  Poly sunic() const;\n \n  Poly slice(int d) const {\n    if (d < a.size())\n      return vector<int>(a.begin(), a.begin() + d + 1);\n    vector<int> res(a);\n    res.resize(d + 1);\n    return res;\n  }\n \n  int *base() { return a.data(); }\n \n  const int *base() const { return a.data(); }\n \n  Poly println(FILE *fp) const {\n    fprintf(fp, \"%d\", a[0]);\n    for (int i = 1; i < a.size(); ++i)\n      fprintf(fp, \" %d\", a[i]);\n    fputc('\\n', fp);\n    return *this;\n  }\n \n  // Calculations\n  Poly operator+(const Poly &rhs) const {\n    vector<int> res(max(a.size(), rhs.a.size()));\n    for (int i = 0; i < res.size(); ++i)\n      if ((res[i] = operator[](i) + rhs[i]) >= P)\n        res[i] -= P;\n    return res;\n  }\n \n  Poly operator-() const {\n    Poly ret(a);\n    for (int i = 0; i < a.size(); ++i)\n      if (ret[i])\n        ret[i] = P - ret[i];\n    return ret;\n  }\n \n  Poly operator-(const Poly &rhs) const { return operator+(-rhs); }\n \n  Poly operator*(const Poly &rhs) const;\n \n  Poly taylor(int k) const;\n};\n \nPoly zeroes(int deg) { return vector<int>(deg + 1); }\n \nPoly operator \"\" _z(unsigned long long a) { return {0, (int) a}; }\n \nPoly operator+(int v, const Poly &rhs) { return Poly(v) + rhs; }\n \nPoly Poly::operator*(const Poly &rhs) const {\n  int n = deg(), m = rhs.deg();\n  if (n <= 10 || m <= 10 || n + m <= BRUTE_N2_LIMIT) {\n    Poly ret = zeroes(n + m);\n    for (int i = 0; i <= n; ++i)\n      for (int j = 0; j <= m; ++j)\n        ret[i + j] = (ret[i + j] + a[i] * (ll) rhs[j]) % P;\n    return ret;\n  }\n  n += m;\n  int l = 0;\n  while ((1 << l) <= n)\n    ++l;\n  vector<int> res(1 << l), tmp(1 << l);\n  memcpy(res.data(), base(), a.size() * sizeof(int));\n  ntt.fft(res.data(), l, 1);\n  memcpy(tmp.data(), rhs.base(), rhs.a.size() * sizeof(int));\n  ntt.fft(tmp.data(), l, 1);\n  for (int i = 0; i < (1 << l); ++i)\n    res[i] = res[i] * (ll) tmp[i] % P;\n  ntt.fft(res.data(), l, -1);\n  res.resize(n + 1);\n  return res;\n}\n \nPoly Poly::taylor(int k) const {\n  int n = deg();\n  Poly t = zeroes(n);\n  simp.check(n);\n  for (int i = 0; i <= n; ++i)\n    t[n - i] = a[i] * (ll) simp.fac[i] % P;\n  int pw = 1;\n  Poly help = vector<int>(simp.ifac.begin(), simp.ifac.begin() + n + 1);\n  for (int i = 0; i <= n; ++i) {\n    help[i] = help[i] * (ll) pw % P;\n    pw = pw * (ll) k % P;\n  }\n  t = t * help;\n  for (int i = 0; i <= n; ++i)\n    help[i] = t[n - i] * (ll) simp.ifac[i] % P;\n  return help;\n}\n \nPoly stirling2(int n) {\n  Poly p = zeroes(n), ne = zeroes(n);\n  for (int i = 0; i <= n; ++i) p[i] = mpow(i, n) * (ll)simp.gifac(i) % P;\n  for (int i = 0; i <= n; ++i) ne[i] = simp.gifac(i);\n  for (int i = 1; i <= n; i += 2) ne[i] = P - ne[i];\n  p = p * ne;\n  vector<int> ans(n + 1);\n  for (int i = 0; i <= n; ++i) ans[i] = p[i] * (ll)simp.gfac(i) % P;\n  return ans;\n}\n \nnamespace DC {\n \nint N;\nvector<Poly> prd, sum;\n \nPoly lift(Poly a, int k) {\n  a.a.insert(a.a.begin(), k, 0);\n  return a;\n}\n \nvoid build(int o, int l, int r) {\n  if (l == r - 1) {\n    prd[o].redeg(1);\n    prd[o][1] = P - simp.ginv(r);\n    prd[o][0] = (P - l) * (ll)simp.ginv(r) % P;\n    sum[o] = prd[o];\n    return;\n  }\n  int mid = (l + r + 1) / 2;\n  build(o << 1, l, mid);\n  build(o << 1 | 1, mid, r);\n  prd[o] = prd[o << 1] * prd[o << 1 | 1];\n  sum[o] = prd[o << 1] * sum[o << 1 | 1] + lift(sum[o << 1], r - mid);\n}\n \nvoid pre(int n) {\n  N = n;\n  sum.resize(n * 4); prd.resize(n * 4);\n  build(1, 0, n);\n}\n \nPoly input;\n \npair<Poly, Poly> solve(int o, int l, int r) {\n  if (l == r - 1) {\n    Poly r1 = input[r];\n    return make_pair(r1 * prd[o], lift(r1, 1));\n  }\n  int mid = (l + r + 1) / 2;\n  auto ls = solve(o << 1, l, mid), rs = solve(o << 1 | 1, mid, r);\n  ls.first = ls.first + prd[o << 1] * rs.first + sum[o << 1] * rs.second;\n  ls.second = ls.second + lift(rs.second, mid - l);\n  return ls;\n}\n \nPoly solve(Poly in) {\n  input = in; input.redeg(N);\n  auto pr = solve(1, 0, N);\n  auto ret = pr.first + pr.second;\n  ret[0] = (ret[0] + input[0]) % P;\n  return ret;\n}\n \n}\n \nPoly compute(Poly coeff) {\n  int n = coeff.deg();\n  Poly ret = DC::solve(coeff);\n  ret.redeg(n);\n  reverse(ret.a.begin(), ret.a.end());\n  ret = ret.taylor(P - 1);\n  reverse(ret.a.begin(), ret.a.end());\n  return ret;\n}\n \nPoly solve(int n) {\n  DC::pre(n);\n  auto v0 = stirling2(n), v1 = stirling2(n - 1);\n  return compute(v0) + compute(v1);\n}\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(nullptr);\n \n  int n, s; cin >> n >> s;\n  auto ans = solve(n - s);\n  for (int i = 0; i < s; ++i) cout << \"0 \";\n  for (int i = n - s - 1; i >= 0; --i)\n    cout << ans[i] * (ll)simp.binom(n - 1, s) % P\n         << \" \\n\"[i == 0];\n \n  return 0;\n}",
    "tags": [
      "fft",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1688",
    "index": "A",
    "title": "Cirno's Perfect Bitmasks Classroom",
    "statement": "\\begin{quote}\nEven if it's a really easy question, she won't be able to answer it\n\\hfill — Perfect Memento in Strict Sense\n\\end{quote}\n\nCirno's perfect bitmasks classroom has just started!\n\nCirno gave her students a positive integer $x$. As an assignment, her students need to find the \\textbf{minimum positive} integer $y$, which satisfies the following two conditions:\n\n$$x\\ and\\ y > 0$$ $$x\\ xor\\ y > 0$$\n\nWhere $and$ is the bitwise AND operation, and $xor$ is the bitwise XOR operation.\n\nAmong the students was Mystia, who was truly baffled by all these new operators. Please help her!",
    "tutorial": "Consider $x=2^k$ and $x\\ne 2^k$ separately. Let $p_i$ be the $i$-th bit of $x$, $q_i$ be the $i$-th bit of $y$ (both indexed from $0$). $x\\ \\texttt{and}\\ y > 0\\Leftrightarrow \\exists i,\\ p_i= q_i = 1$. $x\\ \\texttt{xor}\\ y > 0\\Leftrightarrow \\exists i,\\ p_i\\ne q_i$. To satisfy the first condition, find the minimum integer $k$ satisfying $p_k=1$, and assign $1$ to $q_k$. If $x\\ne 2^k$, the second condition is satisfied now. Otherwise, find the minimum integer $j$ satisfying $p_j=0$, and assign $1$ to $q_j$. The time complexity is $O(1)$. We wrote a brute force program, and it runs more than 2 seconds on polygon. However, many participant passed the pretests. We apologize for our fault.",
    "code": "for T in range(int(input())):\n\tx=int(input())\n\ty=x&-x\n\twhile (x==y or (x&y)==0):\n\t\ty+=1\n\tprint(y)",
    "tags": [
      "bitmasks",
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "1688",
    "index": "B",
    "title": "Patchouli's Magical Talisman",
    "statement": "\\begin{quote}\nShe is skilled in all kinds of magics, and is keen on inventing new one.\n\\hfill —Perfect Memento in Strict Sense\n\\end{quote}\n\nPatchouli is making a magical talisman. She initially has $n$ magical tokens. Their magical power can be represented with \\textbf{positive} integers $a_1, a_2, \\ldots, a_n$.\n\nPatchouli may perform the following two operations on the tokens.\n\n- \\textbf{Fusion:} Patchouli chooses two tokens, removes them, and creates a new token with magical power equal to the sum of the two chosen tokens.\n- \\textbf{Reduction:} Patchouli chooses a token with an \\textbf{even} value of magical power $x$, removes it and creates a new token with magical power equal to $\\frac{x}{2}$.\n\nTokens are more effective when their magical powers are \\textbf{odd} values. Please help Patchouli to find the minimum number of operations she needs to make magical powers of all tokens \\textbf{odd} values.",
    "tutorial": "What if there is at least one odd integer? How to produce an odd integer? Let $g(x)$ be the maximum integer satisfying $2^{g(x)}|x$. A greedy solution is to make one integer odd integer, and plus it to other even integers. Let $f(a)$ be the answer of an sequence ${a_n}$. We can find that: $f(a)=\\begin{cases}\\sum[g (a_i)>0]-1+\\min\\{g(a_i)\\}& \\forall i,\\ g(a_i)>0 \\\\\\sum[g (a_i)>0]&\\texttt{otherwise}\\end{cases}=\\sum[g (a_i)>0]+\\max\\{0,\\min\\{g(a_i)\\}-1\\}$ It can be shown that it is the optimal strategy. We can prove that $f(a)$ decreases by at most $1$ with one operation. For the first operation, assuming we choose $a_i$ and $a_j$, let $a_k=a_i+a_j$. Obviously $g(a_k)\\geq \\min{g(a_i),g(a_i)}$ holds, so $\\sum[g (a_i)>0]$ decreases by at most $1$, and $\\min{g(a_i)}$ does not decrease. So $f(a)$ decreases by at most $1$. For the second operation, assuming we choose $a_j$. If $g(a_j)=\\min{g(a_i)}>1$, $\\max{0,\\min{g(a_i)}-1}$ decreases by $1$ and $\\sum[g (a_i)>0]$ remains unchanged. Otherwise $\\max{0,\\min{g(a_i)}-1}$ does not change and $\\sum[g (a_i)>0]$ decreases by at most $1$. So $f(a)$ decreases by at most $1$. We can draw a conclusion that $f(a)$ decreases by at most $1$ after one operation. Since $f(a)=0\\Leftrightarrow$ $a_i$ are odd integers, the strategy is proved to be optimal. The time complexity is $O(n)$. The constraint is $a_i\\ge 0$ at first.",
    "code": "//这回只花了45min就打完了。\n#include \"bits/stdC++.h\"\nusing namespace std;\n#define all(x) (x).begin(),(x).end()\nint main()\n{\n\tios::sync_with_stdio(0);cin.tie(0);\n\tint T;\n\tcin>>T;\n\twhile (T--)\n\t{\n\t\tint n,r;\n\t\tcin>>n;\n\t\tvector<int> a(n);\n\t\tfor (int &x:a) cin>>x,x=__builtin_ffs(x)-1;\n\t\tr=max(*min_element(all(a))-1,0);\n\t\tfor (int x:a) r+=(x>0);\n\t\tcout<<r<<'\\n';\n\t}\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1688",
    "index": "C",
    "title": "Manipulating History",
    "statement": "\\begin{quote}\nAs a human, she can erase history of its entirety. As a Bai Ze (Hakutaku), she can create history out of nothingness.\n\\hfill —Perfect Memento in Strict Sense\n\\end{quote}\n\nKeine has the ability to manipulate history.\n\nThe history of Gensokyo is a string $s$ \\textbf{of length $1$ initially}. To fix the chaos caused by Yukari, she needs to do the following operations $n$ times, for the $i$-th time:\n\n- She chooses a \\textbf{non-empty substring} $t_{2i-1}$ of $s$.\n- She replaces $t_{2i-1}$ with a \\textbf{non-empty} string, $t_{2i}$. Note that the lengths of strings $t_{2i-1}$ and $t_{2i}$ can be different.\n\nNote that if $t_{2i-1}$ occurs more than once in $s$, \\textbf{exactly one} of them will be replaced.\n\nFor example, let $s=$\"marisa\", $t_{2i-1}=$\"a\", and $t_{2i}=$\"z\". After the operation, $s$ becomes \"mzrisa\" or \"marisz\".\n\nAfter $n$ operations, Keine got the final string and an operation sequence $t$ of length $2n$. Just as Keine thinks she has finished, Yukari appears again and shuffles the order of $t$. Worse still, Keine forgets the initial history.\n\nHelp Keine find the initial history of Gensokyo!\n\nRecall that a substring is a sequence of consecutive characters of the string. For example, for string \"abc\" its substrings are: \"ab\", \"c\", \"bc\" and some others. But the following strings are not its substring: \"ac\", \"cba\", \"acb\".\n\n\\textbf{Hacks}\n\nYou cannot make hacks in this problem.",
    "tutorial": "You do not need to know anything about string matching or other algorithms. Why the initial string consists of only one letter? Why the answer is unique if there is at least one answer? What if each string in the input data consist of one letter? Parity. Let $t$ be the unshuffled operation sequence. Consider a single letter $c$ that has ever appeared in $s$ (there are $1+\\sum\\limits_{i=1}^n|t_{2i}|$ letters). There are two possible situations: $c$ is in the initial string. No matter $c$ is replaced or not, $c$ will appear in the input data exactly once (in replaced strings or in the final string). $c$ is not in the initial string. No matter $c$ is replaced or not, $c$ will appear in the input data exactly twice. So the answer is the only letter appearing odd times in the input data. The time complexity is $O(\\sum |s_i|+|t|)$.",
    "code": "_=int(input())\nfor __ in range(_):\n\tn=2*int(input())+1\n\ta=[0 for i in range(26)]\n\tfor i in range(n):\n\t\ts=input()\n\t\tfor c in s:\n\t\t\ta[ord(c)-ord('a')]+=1\n\tcnt=0\n\tfor i in range(26):\n\t\tif (a[i]%2==1):\n\t\t\tprint(chr(i+ord('a')))\n\t\t\tcnt+=1\n\tif cnt!=1:\n\t\tprint(\"fake problem\")",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1689",
    "index": "A",
    "title": "Lex String",
    "statement": "Kuznecov likes art, poetry, and music. And strings consisting of lowercase English letters.\n\nRecently, Kuznecov has found two strings, $a$ and $b$, of lengths $n$ and $m$ respectively. They consist of lowercase English letters and \\textbf{no character is contained in both strings}.\n\nLet another string $c$ be initially empty. Kuznecov can do the following two types of operations:\n\n- Choose any character from the string $a$, remove it from $a$, and add it to the end of $c$.\n- Choose any character from the string $b$, remove it from $b$, and add it to the end of $c$.\n\nBut, he can not do more than $k$ operations of the same type in a row. He must perform operations until either $a$ or $b$ becomes empty. What is the lexicographically smallest possible value of $c$ after he finishes?\n\nA string $x$ is lexicographically smaller than a string $y$ if and only if one of the following holds:\n\n- $x$ is a prefix of $y$, but $x \\neq y$;\n- in the first position where $x$ and $y$ differ, the string $x$ has a letter that appears earlier in the alphabet than the corresponding letter in $y$.",
    "tutorial": "Greedily take the smallest character in both strings. What's the exception to this? We can't take the smallest character in both strings when we've already took $k$ elements from the string we chose. Denote $A$ as the number of characters we've took from string $a$ in the last few consecutive moves and denote $B$ the same for $b$. If $A=k$, then we have to take the smallest character in string $b$ instead of possibly $a$. If $B=k$, then we have to take the smallest character in string $a$ instead of possibly $b$. Remember to reset $A$ to $0$ when you take a character from $b$. Similarly, reset $B$ to $0$ when you take a character from $a$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0),cout.tie(0);\n \n    int t; cin>>t;\n    while (t--)\n    {\n        int n,m,k; cin>>n>>m>>k;\n        string a,b,c; cin>>a>>b;\n        sort(a.begin(),a.end(),greater<char>());\n        sort(b.begin(),b.end(),greater<char>());\n \n        int ak=0,bk=0;\n        while (!a.empty() && !b.empty())\n        {\n            bool gde=b.back()<a.back();\n            if (gde && bk==k) gde=0;\n            if (!gde && ak==k) gde=1;\n \n            if (gde) c.push_back(b.back()),bk++,ak=0,b.pop_back();\n            else c.push_back(a.back()),ak++,bk=0,a.pop_back();\n        }\n \n        cout<<c<<\"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1689",
    "index": "B",
    "title": "Mystic Permutation",
    "statement": "Monocarp is a little boy who lives in Byteland and he loves programming.\n\nRecently, he found a permutation of length $n$. He has to come up with a mystic permutation. It has to be a new permutation such that it differs from the old one in each position.\n\nMore formally, if the old permutation is $p_1,p_2,\\ldots,p_n$ and the new one is $q_1,q_2,\\ldots,q_n$ it must hold that $$p_1\\neq q_1, p_2\\neq q_2, \\ldots ,p_n\\neq q_n.$$\n\nMonocarp is afraid of lexicographically large permutations. Can you please help him to find the lexicographically minimal mystic permutation?",
    "tutorial": "When is it impossible to find such permutation? It is impossible only for $n=1$. In every other case, iterate over each position in order from $1$ to $n$ and take the smallest available number. What's the exception to this? The exception is the last two elements. We can always take the smallest available number for each $q_i$ satisfying $i<n-1$. To do this we maintain an array of bools of already taken numbers, and then iterate over it to find the smallest available number satisfying $p_i\\neq q_i$ which is also not checked in the array, and then check it (we took it). Now consider $(p_{n-1},p_{n})$ and we want $(q_{n-1},q_{n})$ to be lexicographically minimal while satisfying $p_{n-1}\\neq q_{n-1}$ and $p_{n}\\neq q_{n}$. Let $a$ and $b$ be the last two unused numbers in the array of bools with $a<b$. We try to take $(q_{n-1},q_{n}) = (a,b)$. If $a=p_{n-1}$ or $b=p_{n}$, then we take $(q_{n-1},q_{n}) = (b,a)$. If $(a,b)$ isn't valid, then $(b,a)$ is. The proof is left as an exercise to the reader. This solution runs in $O(n^2)$ and can be optimized to $O(n \\ log \\ n)$. Riblji_Keksic found the O(n) solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t,n,A[1010],B[1010];\n\nint main()\n{\n    scanf(\"%d\",&t);\n    while(t--)\n    {\n        scanf(\"%d\",&n);\n        for(int i=1; i<=n; i++)\n        {\n            scanf(\"%d\",&A[i]);\n            B[i] = i;\n        }\n        if(n==1)\n        {\n            printf(\"-1\\n\");\n            continue;\n        }\n        for(int i=1; i<n; i++)\n        {\n            if(A[i]==B[i]) swap(B[i],B[i+1]);\n        }\n        if(A[n]==B[n]) swap(B[n-1],B[n]);\n        for(int i=1; i<=n; i++) printf(\"%d \",B[i]);\n        printf(\"\\n\");\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1689",
    "index": "C",
    "title": "Infected Tree",
    "statement": "Byteland is a beautiful land known because of its beautiful trees.\n\nMisha has found a binary tree with $n$ vertices, numbered from $1$ to $n$. A binary tree is an acyclic connected bidirectional graph containing $n$ vertices and $n - 1$ edges. Each vertex has a degree at most $3$, whereas the root is the vertex with the number $1$ and it has a degree at most $2$.\n\nUnfortunately, the root got infected.\n\nThe following process happens $n$ times:\n\n- Misha either chooses a non-infected (and not deleted) vertex and deletes it with all edges which have an end in this vertex or just does nothing.\n- Then, the infection spreads to each vertex that is connected by an edge to an already infected vertex (all already infected vertices remain infected).\n\nAs Misha does not have much time to think, please tell him what is the maximum number of vertices he can save from the infection (note that deleted vertices are not counted as saved).",
    "tutorial": "We always delete a vertex directly connected to an infected one. Use dp. Let $u_1,u_2,...,u_k$ be the sequence of removed vertices such that the infection cannot spread anymore. If vertex $u_i$ was never directly connected to an infected vertex, then we could have deleted its parent instead of $u_i$ and we would have got a better solution. Hence, we may assume we always delete a vertex directly connected to an infected one. Now, we may use some dynamic programming ideas. Let $dp_i$ be the maximum number of vertices we can save in the subtree of vertex $i$ if that vertex is infected and we use operations only in the subtree. We can assume the second as the tree is binary and we have two choices - save the subtree of one child by deleting it and infect the other, or the other way around. In each case, the infection will be \"active\" in at most one subtree of some vertex. If $c_1$ and $c_2$ are the children of vertex $i$, the transition is $dp_i = max(dp_{c_1}+s_2-1,dp_{c_2}+s_1-1)$ where $s_i$ denotes the number of vertices in the subtree of $i$. The answer to the problem is $dp_1$. Complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvector<vector<int>> g(300005);\nint ch[300005],dp[300005];\n \nvoid dfs(int p, int q)\n{\n    ch[p]=1,dp[p]=0; int s=0;\n    for (auto it : g[p]) if (it!=q)\n    {\n        dfs(it,p); s+=dp[it];\n        ch[p]+=ch[it];\n    }\n    for (auto it : g[p]) if (it!=q)\n    {\n        dp[p]=max(dp[p],s-dp[it]+ch[it]-1);\n    }\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0),cout.tie(0);\n \n    int t; cin>>t;\n    while (t--)\n    {\n        int n; cin>>n;\n        for (int i=1;i<=n;i++) g[i].clear();\n        for (int i=1;i<n;i++)\n        {\n            int u,v; cin>>u>>v;\n            g[u].push_back(v);\n            g[v].push_back(u);\n        }\n \n        dfs(1,0);\n        cout<<dp[1]<<\"\\n\";\n    }\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1689",
    "index": "D",
    "title": "Lena and Matrix",
    "statement": "Lena is a beautiful girl who likes logical puzzles.\n\nAs a gift for her birthday, Lena got a matrix puzzle!\n\nThe matrix consists of $n$ rows and $m$ columns, and each cell is either black or white. The coordinates $(i,j)$ denote the cell which belongs to the $i$-th row and $j$-th column for every $1\\leq i \\leq n$ and $1\\leq j \\leq m$. To solve the puzzle, Lena has to choose a cell that minimizes the Manhattan distance to the farthest black cell from the chosen cell.\n\nMore formally, let there be $k \\ge 1$ black cells in the matrix with coordinates $(x_i,y_i)$ for every $1\\leq i \\leq k$. Lena should choose a cell $(a,b)$ that minimizes $$\\max_{i=1}^{k}(|a-x_i|+|b-y_i|).$$\n\nAs Lena has no skill, she asked you for help. Will you tell her the optimal cell to choose?",
    "tutorial": "There are not a lot of useful black squares. Consider this algorithm: iterate over all squares in the matrix and find the most distant black square. Let's find out how to do that efficiently. In fact, only 4 (not necessarily distinct) black squares will be useful: one square which minimizes $i-j$, one square which maximizes $i-j$, one square which minimizes $i+j$ and one square which maximizes $i+j$, where $(i,j)$ denotes the black cell's coordinates. In other words, we would like to find the most distant \"border\". Let's look at the example above. The cell we choose to recolour to yellow creates four regions (the top-left rectangle, the top-right rectangle, the bottom-left rectangle and the bottom-right rectangle, which are created by two lines parallel with coordinate axes passing through our yellow point). The most distant border will be fully contained inside one region, hence we should find the distance from our yellow cell to any cell on that border, and that is the maximum possible distance. The complexity is $O(n\\cdot m)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nchar tab[1003][1003];\npair<int,int> a={-1,-1},b={-1,-1},c={-1,-1},d={-1,-1};\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0),cout.tie(0);\n \n    int t; cin>>t;\n    while (t--)\n    {\n        a={-1,-1},b={-1,-1},c={-1,-1},d={-1,-1};\n        \n        int n,m; cin>>n>>m;\n        for (int i=0;i<n;i++) cin>>tab[i];\n \n        vector<pair<int,int>> interesting;\n \n        for (int i=0;i<n;i++) for (int j=0;j<m;j++) if (tab[i][j]=='B')\n        {\n            if (a.first==-1 || i+j>a.first+a.second) a={i,j};\n            if (b.first==-1 || i+j<b.first+b.second) b={i,j};\n            if (c.first==-1 || i-j>c.first-c.second) c={i,j};\n            if (d.first==-1 || i-j<d.first-d.second) d={i,j};\n        }\n \n        interesting.push_back(a);\n        interesting.push_back(b);\n        interesting.push_back(c);\n        interesting.push_back(d);\n \n        int ans=1e9; pair<int,int> opt;\n        for (int i=0;i<n;i++) for (int j=0;j<m;j++)\n        {\n            int dist=0;\n            for (auto it : interesting) dist=max(dist,abs(i-it.first)+abs(j-it.second));\n            if (dist<ans) ans=dist,opt={i,j};\n        }\n \n        cout<<opt.first+1<<\" \"<<opt.second+1<<\"\\n\";\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "geometry",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1689",
    "index": "E",
    "title": "ANDfinity",
    "statement": "Bit Lightyear, to the ANDfinity and beyond!\n\nAfter graduating from computer sciences, Vlad has been awarded an array $a_1,a_2,\\ldots,a_n$ of $n$ non-negative integers. As it is natural, he wanted to construct a graph consisting of $n$ vertices, numbered $1, 2,\\ldots, n$. He decided to add an edge between $i$ and $j$ if and only if $a_i \\& a_j > 0$, where $\\&$ denotes the bitwise AND operation.\n\nVlad also wants the graph to be connected, which might not be the case initially. In order to satisfy that, he can do the following two types of operations on the array:\n\n- Choose some element $a_i$ and increment it by $1$.\n- Choose some element $a_i$ and decrement it by $1$ (possible only if $a_i > 0$).\n\nIt can be proven that there exists a finite sequence of operations such that the graph will be connected. So, can you please help Vlad find the minimum possible number of operations to do that and also provide the way how to do that?",
    "tutorial": "Increase every $0$ by $1$ initially. Check if the answer is $0$: check whether the graph is already connected. Check if the answer is $1$. If the answer is not $0$ or $1$, then it is $2$. Firslty, let's understand how to check whether the graph induced by some array $b$ is connected in $O(n \\ log \\ max \\ b_i)$. We create a graph over bits. Let's take all elements $b_i$ and add an edge between their adjacent bits (all bits of a single $b_i$ will be connected). To quickly access the lowest bit we will use $b_i \\ \\& \\ -b_i$ in code. Now we just check whether the graph over bits is connected. We check whether the graph for initial array $a$ is connected. If it is, the answer is 0. Then, we wonder if the answer is $1$. Check if at least one of the graphs for arrays $a_1,...,a_{i-1},a_i-1,a_{i+1},...,a_n$ for every $1\\leq i \\leq n$ is connected. Do the same for arrays $a_1,...,a_{i-1},a_i+1,a_{i+1},...,a_n$. If none of the graphs is connected, the answer is $2$ and otherwise $1$. Now let's see how the answer will be at most $2$. Let $i_1,i_2,...,i_k$ be the sequence of indices denoting that $a_{i_j}$ has the highest lowest bit (the highest value of $a_i \\ \\& \\ -a_i$). if $k=1$ then we can just decrease $a_{i_1}$ by $1$ and connect everything. If $k\\geq 2$ and we do the same we might disconnect that number from other numbers having the highest lowest bit, thus an additional operation of adding $1$ to $a_{i_2}$ is needed to keep everything connected. The answer is $2$ in this case. Complexity of this solution is $O(n^2 \\ log \\ max \\ a_i)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint a[2005];\n \nvector<vector<int>> g(32);\nbool vis[32];\n \nvoid dfs(int p)\n{\n    if (vis[p]) return; vis[p]=1;\n    for (auto it : g[p]) dfs(it);\n}\n \nbool connected(int n)\n{\n    int m=0;\n    for (int i=0;i<n;i++) if (a[i]==0) return false;\n    for (int i=0;i<n;i++) m|=a[i];\n    for (int i=0;i<31;i++) g[i].clear();\n    for (int i=0;i<n;i++)\n    {\n        int last=-1;\n        for (int j=0;j<31;j++)\n            if (a[i]&(1<<j)){\n                if (last!=-1) g[last].push_back(j),g[j].push_back(last);\n                last=j;\n            }\n    }\n \n    for (int j=0;j<31;j++) vis[j]=0;\n    for (int j=0;j<31;j++) if ((1<<j)&m)\n    {\n        dfs(j); break;\n    }\n    for (int j=0;j<31;j++) if (((1<<j)&m) && !vis[j]) return false;\n    return true;\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0),cout.tie(0);\n \n    int t; cin>>t;\n    while (t--){\n \n \n    int n; cin>>n;\n    for (int i=0;i<n;i++) cin>>a[i];\n \n    int ans=0;\n    for (int i=0;i<n;i++) if (a[i]==0) ans++,a[i]++;\n \n    int m=0;\n    for (int i=0;i<n;i++) m=max(m,(a[i]&(-a[i])));\n \n    if (connected(n))\n    {\n        cout<<ans<<\"\\n\";\n        for (int i=0;i<n;i++) cout<<a[i]<<\" \"; cout<<\"\\n\";\n        goto kraj;\n    }\n \n    for (int i=0;i<n;i++)\n    {\n        a[i]--;\n        if (connected(n))\n        {\n            cout<<ans+1<<\"\\n\";\n            for (int i=0;i<n;i++) cout<<a[i]<<\" \"; cout<<\"\\n\";\n            goto kraj;\n        }\n        a[i]++;\n    }\n    \n    for (int i=0;i<n;i++)\n    {\n        a[i]++;\n        if (connected(n))\n        {\n            cout<<ans+1<<\"\\n\";\n            for (int i=0;i<n;i++) cout<<a[i]<<\" \"; cout<<\"\\n\";\n            goto kraj;\n        }\n        a[i]--;\n    }\n \n    for (int i=0;i<n;i++) if ((a[i]&-a[i])==m)\n    {\n        a[i]--;\n        break;\n    }\n    for (int i=0;i<n;i++) if ((a[i]&-a[i])==m)\n    {\n        a[i]++;\n        break;\n    }\n \n    cout<<ans+2<<\"\\n\";\n    for (int i=0;i<n;i++) cout<<a[i]<<\" \";\n    cout<<\"\\n\";\n    \n    kraj:;\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1690",
    "index": "A",
    "title": "Print a Pedestal (Codeforces logo?)",
    "statement": "Given the integer $n$ — the number of available blocks. You must use \\textbf{all} blocks to build a pedestal.\n\nThe pedestal consists of $3$ platforms for $2$-nd, $1$-st and $3$-rd places respectively. The platform for the $1$-st place must be \\textbf{strictly} higher than for the $2$-nd place, and the platform for the $2$-nd place must be \\textbf{strictly} higher than for the $3$-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block).\n\n\\begin{center}\n{\\small Example pedestal of $n=11$ blocks: second place height equals $4$ blocks, first place height equals $5$ blocks, third place height equals $2$ blocks.}\n\\end{center}\n\nAmong all possible pedestals of $n$ blocks, deduce one such that the platform height for the $1$-st place \\textbf{minimum} as possible. If there are several of them, output any of them.",
    "tutorial": "In the $n \\le 10^5$ constraints, the problem can be solved by brute force: we will go through the value for $h_1$ (the height for the first place), and then select suitable values for $h_2$ and $h_3$. Since $h_2 > h_3$, we divide the remaining $n - h_1$ blocks equally between $h_2$ and $h_3$. If it turns out that $h_2 = h_3$, then we try to decrease $h_3$ by $1$ and increase $h_2$ by 1. If we get the right answer ($h_1 > h_2 > h_3 > 1$), output the heights and stop the process. We will go through the value of $h_1$ in order of increasing.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n \n \n \nvoid solve() {\n    int n; \n    cin >> n;\n    for (int a = 3; a < n; a++) {\n        int c = (n - a) / 2;\n        int b = n - a - c;\n        if (c > 1 && b+1 < a) {\n            c--;\n            b++;\n        }\n        if (a > b && b > c) {\n            cout << b << ' ' << a << ' ' << c << endl;\n            return;\n        }\n    }\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1690",
    "index": "B",
    "title": "Array Decrements",
    "statement": "Kristina has two arrays $a$ and $b$, each containing $n$ non-negative integers. She can perform the following operation on array $a$ any number of times:\n\n- apply a decrement to each non-zero element of the array, that is, replace the value of each element $a_i$ such that $a_i > 0$ with the value $a_i - 1$ ($1 \\le i \\le n$). If $a_i$ was $0$, its value does not change.\n\nDetermine whether Kristina can get an array $b$ from an array $a$ in some number of operations (probably zero). In other words, can she make $a_i = b_i$ after some number of operations for each $1 \\le i \\le n$?\n\nFor example, let $n = 4$, $a = [3, 5, 4, 1]$ and $b = [1, 3, 2, 0]$. In this case, she can apply the operation twice:\n\n- after the first application of the operation she gets $a = [2, 4, 3, 0]$;\n- after the second use of the operation she gets $a = [1, 3, 2, 0]$.\n\nThus, in two operations, she can get an array $b$ from an array $a$.",
    "tutorial": "For all elements of the arrays to become equal after subtraction of units, $a_i>=b_i$ for $1 \\le i \\le n$ must be satisfied. In addition, if there exists $b_i > 0$, then the equality $a_i = b_i$ can be obtained only by subtracting exactly $a_i - b_i$ units from $a_i$. Since the equality $a_i = b_i$ must be satisfied for all $i$, the problem is reduced to checking that for $b_i > 0$ all differences $a_i - b_i=dif$ are equal and for $b_i = 0$ the difference does not exceed $dif$.",
    "code": "#include<bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\nconst int inf = 1e9 + 7;\n \nbool equals(vector<int>&a, vector<int>&b, int n){\n    int dif = inf;\n    forn(i, n){\n        if(b[i] != 0) dif = min(dif, a[i] - b[i]);\n    }\n    if(dif < 0) return false; \n    if(dif == inf) return true;\n    forn(i, n){\n        if(a[i] - b[i] > dif) return false;\n        if(b[i] != 0 && a[i] - b[i] < dif) return false;\n    }\n    return true;\n}\n \nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int>a(n), b(n);\n    forn(i, n) cin >> a[i];\n    forn(i, n) cin >> b[i];\n    cout << (equals(a, b, n) ? \"YES\\n\" : \"NO\\n\");\n \n}\n \nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}\n",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1690",
    "index": "C",
    "title": "Restoring the Duration of Tasks",
    "statement": "Recently, Polycarp completed $n$ successive tasks.\n\nFor each completed task, the time $s_i$ is known when it was given, no two tasks were given at the same time. Also given is the time $f_i$ when the task was completed. For each task, there is an unknown value $d_i$ ($d_i>0$) — \\textbf{duration of task execution}.\n\nIt is known that the tasks were completed in the order in which they came. Polycarp performed the tasks as follows:\n\n- As soon as the very first task came, Polycarp immediately began to carry it out.\n- If a new task arrived before Polycarp finished the previous one, he put the new task at the end of the queue.\n- When Polycarp finished executing the next task and the queue was not empty, he \\textbf{immediately} took a new task from the head of the queue (if the queue is empty — he just waited for the next task).\n\nFind $d_i$ (duration) of each task.",
    "tutorial": "Accordingly, as it was said in the task, we put all tasks into the queue in the order of their arrival, then we fix the time at the beginning as $cur\\_time = 0$. So, while there is a task in the queue, we proceed as follows: Take the task from the queue. Take as time the maximum from the current and from the arrival time of the task ($cur\\_time = max(cur\\_time, s)$). We subtract the current time from the time when the task was done ($f = d - cur\\_time$). Replace the current time with the time the task was done ($cur\\_time = d$) If there is a task in the queue, go to item $1$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \n \nvoid solve() {\n    int n;\n    cin >> n;\n    int s[n];\n    int f[n];\n    for (int i = 0; i < n; ++i) {\n        cin >> s[i];\n    }\n \n    for (int i = 0; i < n; ++i) {\n        cin >> f[i];\n    }\n    int curTime = 0;\n    int d[n];\n    for (int i = 0; i < n; ++i) {\n        curTime = max(curTime, s[i]);\n        d[i] = f[i] - curTime;\n        curTime = f[i];\n    }\n    for (auto now: d) {\n        cout << now << \" \";\n    }\n    cout << '\\n';\n}\nint main() {\n    int tests;\n    cin >> tests;\n    forn(tt, tests) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1690",
    "index": "D",
    "title": "Black and White Stripe",
    "statement": "You have a stripe of checkered paper of length $n$. Each cell is either white or black.\n\nWhat is the minimum number of cells that must be recolored from white to black in order to have a segment of $k$ consecutive black cells on the stripe?\n\nIf the input data is such that a segment of $k$ consecutive black cells already exists, then print 0.",
    "tutorial": "To obtain a segment of $k$ cells of black color, we need to paint all the white cells of the segment black. Then go through all the segments of length $k$ (there are only $n - k$) and choose such a segment among them that the number of white cells on it is minimal. You can quickly find out the number of white cells in the segment by prefix sums.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n, k;\n        cin >> n >> k;\n        string s;\n        cin >> s;\n        vector<int> w(n + 1);\n        for (int i = 1; i <= n; i++)\n            w[i] = w[i - 1] + int(s[i - 1] == 'W');\n        int result = INT_MAX;\n        for (int i = k; i <= n; i++)\n            result = min(result, w[i] - w[i - k]);\n        cout << result << endl;\n    }\n}",
    "tags": [
      "implementation",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1690",
    "index": "E",
    "title": "Price Maximization",
    "statement": "A batch of $n$ goods ($n$ — an even number) is brought to the store, $i$-th of which has weight $a_i$. Before selling the goods, they must be packed into packages. After packing, the following will be done:\n\n- There will be $\\frac{n}{2}$ packages, each package contains exactly two goods;\n- The weight of the package that contains goods with indices $i$ and $j$ ($1 \\le i, j \\le n$) is $a_i + a_j$.\n\nWith this, the cost of a package of weight $x$ is always $\\left \\lfloor\\frac{x}{k}\\right\\rfloor$ burles (rounded down), where $k$ — a fixed and given value.\n\nPack the goods to the packages so that the revenue from their sale is maximized. In other words, make such $\\frac{n}{2}$ pairs of given goods that the sum of the values $\\left \\lfloor\\frac{x_i}{k} \\right \\rfloor$, where $x_i$ is the weight of the package number $i$ ($1 \\le i \\le \\frac{n}{2}$), is \\textbf{maximal}.\n\nFor example, let $n = 6, k = 3$, weights of goods $a = [3, 2, 7, 1, 4, 8]$. Let's pack them into the following packages.\n\n- In the first package we will put the third and sixth goods. Its weight will be $a_3 + a_6 = 7 + 8 = 15$. The cost of the package will be $\\left \\lfloor\\frac{15}{3}\\right\\rfloor = 5$ burles.\n- In the second package put the first and fifth goods, the weight is $a_1 + a_5 = 3 + 4 = 7$. The cost of the package is $\\left \\lfloor\\frac{7}{3}\\right\\rfloor = 2$ burles.\n- In the third package put the second and fourth goods, the weight is $a_2 + a_4 = 2 + 1 = 3$. The cost of the package is $\\left \\lfloor\\frac{3}{3}\\right\\rfloor = 1$ burle.\n\nWith this packing, the total cost of all packs would be $5 + 2 + 1 = 8$ burles.",
    "tutorial": "Note that we do not need to consider the numbers $x \\ge k$, we are only interested in the remainder of the division of $x$ by $k$, and we simply add the value $\\left \\lfloor\\frac{x}{k}\\right\\rfloor$ to the answer. We get an array $a$, where $a_i < k$. Let's sort it and greedily type index pairs $i < j$ such that $a_i + a_j \\ge k$. This can be done with two pointers. Then add the number of matching pairs to the answer counter. This will be the answer to the problem.",
    "code": "#include<bits/stdc++.h>\n#define len(s) (int)s.size()\nusing namespace std;\nusing ll = long long;\n \nvoid solve(){\n    int n, k;\n    cin >> n >> k;\n    vector<ll>a(n);\n    ll sum = 0;\n    for(int i = 0; i < n; i++) {\n        cin >> a[i];\n        sum += a[i] / k;\n        a[i] = a[i] % k;\n    }\n    sort(a.begin(), a.end(), [] (int x, int y){\n        return x > y;\n    });\n \n    for(int i = 0, j = n - 1; i < j; i++, j--){\n        while(a[i] + a[j] < k && i < j) j--;\n        if(i == j) break;\n        sum++;\n    }\n    cout << sum << endl;\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1690",
    "index": "F",
    "title": "Shifting String",
    "statement": "Polycarp found the string $s$ and the permutation $p$. Their lengths turned out to be the same and equal to $n$.\n\nA permutation of $n$ elements — is an array of length $n$, in which every integer from $1$ to $n$ occurs exactly once. For example, $[1, 2, 3]$ and $[4, 3, 5, 1, 2]$ are permutations, but $[1, 2, 4]$, $[4, 3, 2, 1, 2]$ and $[0, 1, 2]$ are not.\n\nIn one operation he can multiply $s$ by $p$, so he replaces $s$ with string $new$, in which for any $i$ from $1$ to $n$ it is true that $new_i = s_{p_i}$. For example, with $s=wmbe$ and $p = [3, 1, 4, 2]$, after operation the string will turn to $s=s_3 s_1 s_4 s_2=bwem$.\n\nPolycarp wondered after how many operations the string would become equal to its initial value for the first time. Since it may take too long, he asks for your help in this matter.\n\nIt can be proved that the required number of operations always exists. It can be very large, so use a 64-bit integer type.",
    "tutorial": "To begin with, let's understand why the string will return to its original form. In fact, the graph that the permutation sets consists of simple cycles and it turns out that after a certain number of operations, each character will return to its place. Consider each cycle as a string that is cyclically shifted every turn. It may seem that the answer is - $lcm$ (the smallest common multiple) of the cycle lengths, but to become equal to the initial string, it is not necessary to go through the entire cycle. The constraints allow us to calculate the length of the minimum suitable shift $k_j$ in $\\mathcal{O}(len^2)$, where $len$ is the length of the cycle, so just iterate over the desired shift. Note that after $k_j$ operations, the cycle will return to its original form and this will happen again after $k_j$ operations. The answer will be $lcm$ of all $k_j$, since each cycle individually comes to its original form after the number of operations is a multiple of its $k_j$.",
    "code": "def gcd(a, b):\n    if b == 0:\n        return a;\n    return gcd(b, a % b)\n    \n    \ndef shift(s):\n    for i in range(1, len(s) + 1):\n        if s == s[i:] + s[:i]:\n            return i\n    \n \ndef solve():\n    n = int(input())\n    s = input()\n    p = [int(x)-1 for x in input().split()]\n    used = [False] * n\n    ans = 1\n    i = 0\n    while i < n:\n        ss = ''\n        while not used[i]:\n            ss += s[i]\n            used[i] = True\n            i = p[i];\n        i += 1\n        if len(ss) == 0:\n            continue\n        ln = shift(ss)\n        ans = ans * ln // gcd(ans, ln)\n    print(ans)\n    \n \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "graphs",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1690",
    "index": "G",
    "title": "Count the Trains",
    "statement": "There are $n$ of independent carriages on the rails. The carriages are numbered from left to right from $1$ to $n$. The carriages are not connected to each other. The carriages move to the left, so that the carriage with number $1$ moves ahead of all of them.\n\nThe $i$-th carriage has its own engine, which can accelerate the carriage to $a_i$ km/h, but the carriage cannot go faster than the carriage in front of it. See example for explanation.\n\nAll carriages start moving to the left at the same time, and they naturally form \\textbf{trains}. We will call \\textbf{trains} — consecutive moving carriages having the same speed.\n\nFor example, we have $n=5$ carriages and array $a = [10, 13, 5, 2, 6]$. Then the final speeds of the carriages will be $[10, 10, 5, 2, 2]$. Respectively, $3$ of the train will be formed.\n\nThere are also messages saying that some engine has been corrupted:\n\n- message \"k d\" means that the speed of the $k$-th carriage has decreased by $d$ (that is, there has been a change in the maximum speed of the carriage $a_k = a_k - d$).\n\nMessages arrive sequentially, the processing of the next message takes into account the changes from all previous messages.\n\nAfter each message determine the number of formed trains.",
    "tutorial": "In the set we will keep the indices that start the trains. That is, if the array $v$ - the real speeds of the carriages, then we will store in the network such values $2 \\le i$ that $v[i] < v[i-1]$. As well as the value of $0$. Thus, the size of the set -is the answer to the problem. Consider now the operation to reduce the speed of the carriage: find such maximal index $j \\le k$ in the set, if the value $a_k < a_j$, then we should add the value $k$ to the set, since it will start a new train. Then we should remove all subsequent indexes $j$ from the set such that $a_k < a_j$. Thus, for all operations we will add no more than $n$ elements to the array, and remove in total no more than $2 \\cdot n$ elements from the set. We obtain the asymptotic $O(m \\cdot logn)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        vector<int> a(n);\n        set<int> tmp;\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n            if (tmp.empty() || a[i] < a[*tmp.rbegin()]) {\n                tmp.insert(i);\n            }\n        }\n        for (int i = 0; i < m; i++) {\n            int j, d;\n            cin >> j >> d;\n            j--;\n            a[j] -= d;\n            auto it = tmp.upper_bound(j);\n            if (it != tmp.begin()) {\n                it = prev(it);\n                if (*it == j || a[*it] > a[j]) {\n                    tmp.insert(j);\n                }\n            } else {\n                tmp.insert(j);\n            }\n            while (1) {\n                it = tmp.upper_bound(j);\n                if (it != tmp.end() && a[*it] >= a[j]) {\n                    tmp.erase(it);\n                } else {\n                    break;\n                }\n            }\n            cout << (int) tmp.size() << \" \";\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1691",
    "index": "A",
    "title": "Beat The Odds",
    "statement": "Given a sequence $a_1, a_2, \\ldots, a_n$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $2$ consecutive elements is even.",
    "tutorial": "The sum of an odd integer and an even integer is an odd integer. So, you can't have both even and odd elements in the array for the sum of every two consecutive elements to be even. Hence, the final array should only contain all even or all odd elements. Hence, we will remove either all odd elements or all even elements, whichever takes lesser number of operations. Therefore, the answer is: $min(\\textit{count of odd elements}, \\textit{count of even elements})$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t{\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n);\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tcin >> a[i];\n\t\tint num_odd = 0;\n\t\tfor (auto x : a)\n\t\t\tif (x & 1)\n\t\t\t\tnum_odd++;\n\t\tcout << min(num_odd, n - num_odd) << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1691",
    "index": "B",
    "title": "Shoe Shuffling",
    "statement": "A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.\n\nThere are $n$ students in the class, and you are given an array $s$ in \\textbf{non-decreasing} order, where $s_i$ is the shoe size of the $i$-th student. A shuffling of shoes is valid only if \\textbf{no student gets their own shoes} and if every student gets shoes of size \\textbf{greater than or equal to} their size.\n\nYou have to output a permutation $p$ of $\\{1,2,\\ldots,n\\}$ denoting a valid shuffling of shoes, where the $i$-th student gets the shoes of the $p_i$-th student ($p_i \\ne i$). And output $-1$ if a valid shuffling does not exist.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "We can observe that the number of pairs of shoes greater than their size is limited for any student. So if student $j$ wears shoes that are greater than their size, then some student $i$ who has a size greater than student $j$ will compromise their size. So say a valid shuffling exists where a student gets shoes of size greater than their own, i.e., student $j$ got shoes of student $i$ where $s_i>s_j$. Then, for all pairs of shoes of size $s_j$, one pair will go to a student whose size is smaller than $s_j$. This chain will continue until a student with shoe size $s_1$ gets a pair of shoes greater than theirs, and then there will exist a pair of shoes of size $s_1$ that no student can wear. Thus, if a valid shuffling, every student must get shoes of the same size as their own. Hence, a valid shuffling exists if more than one student has the same size shoes for all shoe sizes. A valid shuffling can be generated by rearranging students' shoes with the same shoe size such that no one gets their shoes. This can be done in multiple ways, for example, cyclic rotation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define ll long long\ntypedef vector<ll> vll;\n#define io                            \\\n    ios_base::sync_with_stdio(false); \\\n    cin.tie(NULL);                    \\\n    cout.tie(NULL)\n\nint main()\n{\n    io;\n    ll tc;\n    cin >> tc;\n    while (tc--)\n    {\n        ll n;\n        cin >> n;\n        vll s(n), p(n);\n        for (ll i = 0; i < n; ++i)\n            cin >> s[i];\n\n        ll l = 0, r = 0;\n        bool ans = true;\n        for (ll i = 0; i < n; ++i)\n            p[i] = i + 1;\n\n        while (r < n)\n        {\n            while (r < n - 1 and s[r] == s[r + 1]) // get range [l,r] with equal values\n                ++r;\n            if (l == r)\n                ans = false;\n            else\n                rotate(p.begin() + l, p.begin() + r, p.begin() + r + 1); // rotate right in range [l,r]\n            l = r + 1;\n            ++r;\n        }\n        if (ans)\n        {\n            for (auto &x : p)\n                cout << x << \" \";\n            cout << endl;\n        }\n        else\n            cout << -1 << endl;\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1691",
    "index": "C",
    "title": "Sum of Substrings",
    "statement": "You are given a binary string $s$ of length $n$.\n\nLet's define $d_i$ as the number whose decimal representation is $s_i s_{i+1}$ (possibly, with a leading zero). We define $f(s)$ to be the sum of all the valid $d_i$. In other words, $f(s) = \\sum\\limits_{i=1}^{n-1} d_i$.\n\nFor example, for the string $s = 1011$:\n\n- $d_1 = 10$ (ten);\n- $d_2 = 01$ (one)\n- $d_3 = 11$ (eleven);\n- $f(s) = 10 + 01 + 11 = 22$.\n\nIn one operation you can swap any two adjacent elements of the string. Find the minimum value of $f(s)$ that can be achieved if at most $k$ operations are allowed.",
    "tutorial": "We can observe that for any string $s$, $F(s)$ can also be written as: $F(s) = 10\\times s_1 + 11 \\times s_2 + 11 \\times s_3 \\dots 11 \\times s_{n-1} + 1 \\times s_n$ Now, in order to minimize the value of $F(s)$, we would want to put the 1s at position $n$ first, then at position $1$ and then anywhere in the middle of the string. In order to achieve the best configuration in at max $k$ operations, we will try to move the last '1' at position $n$ first, then with the remaining operations, we will try to move the first '1' at position 1. The remaining 1s can stay where they are as they will anyways be contributing a value of $11$ no matter which position they take.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    string s;\n    cin >> s;\n    int ones = 0, p1_first = n, p1_last = -1;\n    for (int p = 0; p < n; p++) {\n      if (s[p] != '1')\n        continue;\n      ones += 1;\n      if (p1_first == n)\n        p1_first = p;\n      p1_last = p;\n    }\n    int add = 0;\n    // moving the last one to last position\n    if (ones > 0 and (n - 1 - p1_last) <= k) {\n      k -= (n - 1 - p1_last);\n      add += 1;\n      ones -= 1;\n    }\n    // moving the first one to first position\n    if (ones > 0 and p1_first <= k) {\n      k -= (p1_first);\n      add += 10;\n      ones -= 1;\n    }\n    cout << 11 * ones + add << \"\\n\";\n  }\n  return 0;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1691",
    "index": "D",
    "title": "Max GEQ Sum",
    "statement": "You are given an array $a$ of $n$ integers. You are asked to find out if the inequality $$\\max(a_i, a_{i + 1}, \\ldots, a_{j - 1}, a_{j}) \\geq a_i + a_{i + 1} + \\dots + a_{j - 1} + a_{j}$$ holds for all pairs of indices $(i, j)$, where $1 \\leq i \\leq j \\leq n$.",
    "tutorial": "Let's look at the problem from the perspective of each $a_i$. We want to check whether the sum of the subarrays, where $a_i$ is the maximum element, exceeds $a_i$ or not. Firstly, we must find out in which subarrays is $a_i$ the maximum. This involves finding the previous greater element index and the next greater element index of $i$, which can be done for all indices in $O(n)$ using stacks. Take these indices as $x_i$, $y_i$. After computing this for every index, we'll know that $a_i$ is max in subarrays with starting index $[x_i + 1, i]$ and ending index $[i, y_i - 1]$. Take $(j, k)$, which represents the sum of a subarray which starts at index $j$ and ends at index $k$, where $j \\in [x_i + 1, i]$, $k \\in [i, y_i - 1]$. If $(j, k) > a_i$, then $(j, i - 1) + (i, i) + (i + 1, k) > a_i$, giving us $(j, i - 1) + (i + 1, k) > 0$. Hence, at least one of the subarrays, $(j, i - 1)$ or $(i + 1, k)$ has a sum greater than $0$, which implies that one of subarrays $(j, i)$, $(i, k)$ has sum greater than $a_i$, so only checking subarrays which start or end at index $i$ suffices. Therefore, for an index $i$, we need to check subarrays $(x_i + 1, i), (x_i + 2, i), \\dots, (i - 1, i)$, and subarrays $(i, i + 1), (i, i + 2), \\dots, (i, y_i - 1)$. Since we just care if any one of them exceed $a_i$, finding the max of them is enough. This reduces to making a range query over the prefix sums and one over the suffix sums. The query on prefix sums would look like $\\text{max}(i, y_i - 1) - \\text{prefix}[i - 1] > a_i$ Where $\\text{max}(i, y_i - 1)$ returns the max prefix sum in the given range. This query can be done using a segment tree in $O(\\log n)$. If any of the queries is true, then we just have to output \"NO\", else output \"YES\". With this we get the time complexity of the solution as $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\ntypedef long long ll;\nusing namespace std;\n \nconst ll ninf = -1e15;\n \nvector<int> nextGreater(vector<ll>& arr, int n) {\n\tstack<int> s;\t\n        vector<int> result(n, n);\n\tfor (int i = 0; i < n; i++) {\n\t\twhile (!s.empty() && arr[s.top()] < arr[i]) {\n\t\t\tresult[s.top()] = i;\t\n\t\t\ts.pop();\n\t\t}\n\t\ts.push(i);\n\t}\n        return result;\n}\n \nvector<int> prevGreater(vector<ll>& arr, int n) {\n\tstack<int> s;\t\n        vector<int> result(n, -1);\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\twhile (!s.empty() && arr[s.top()] < arr[i]) {\n\t\t\tresult[s.top()] = i;\t\n\t\t\ts.pop();\n\t\t}\n\t\ts.push(i);\n\t}\n        return result;\n}\n \nll query(vector<ll> &tree, int node, int ns, int ne, int qs, int qe) {\n    if (qe < ns || qs > ne) return ninf;\n    if (qs <= ns && ne <= qe) return tree[node];\n \n    int mid = ns + (ne - ns) / 2;\n    ll leftQuery = query(tree, 2 * node, ns, mid, qs, qe);\n    ll rightQuery = query(tree, 2 * node + 1, mid + 1, ne, qs, qe);\n    return max(leftQuery, rightQuery);\n}\n \nint main() {\n   int t; \n   cin >> t;\n   while (t--) {\n        int n, _n;\n        cin >> n;\n        vector<ll> arr(n, 0);\n        for (auto& a : arr)\n            cin >> a;\n        \n        // Round off n to next power of 2\n        _n = n;\n        while (__builtin_popcount(_n) != 1) _n++;\n \n \n        // Prefix sums\n        vector<ll> prefixSum(n, 0), suffixSum(n, 0);\n        prefixSum[0] = arr[0];\n        for (int i = 1; i < n; i++) {\n            prefixSum[i] = prefixSum[i - 1] + arr[i];\n        }\n        suffixSum[n - 1] = arr[n - 1];\n        for (int i = n - 2; i >= 0; i--) {\n            suffixSum[i] = suffixSum[i + 1] + arr[i];\n        }\n        \n        // Two max-segtress, one on the prefix sums, one on the suffix sums\n        vector<ll> prefixTree(2 * _n, ninf), suffixTree(2 * _n, ninf);\n \n        for (int i = 0; i < n; i++) {\n            prefixTree[_n + i] = prefixSum[i];\n            suffixTree[_n + i] = suffixSum[i];\n        }\n \n        for (int i = _n - 1; i >= 1; i--) {\n            prefixTree[i] = max(prefixTree[2 * i], prefixTree[2 * i + 1]);\n            suffixTree[i] = max(suffixTree[2 * i], suffixTree[2 * i + 1]);\n        }        \n        vector<int> ng = nextGreater(arr, n); \n        vector<int> pg = prevGreater(arr, n); \n        bool flag = true;\n \n        for (int i = 0; i < n; i++) {\n            ll rightMax = query(prefixTree, 1, 0, _n - 1, i + 1, ng[i] - 1) - prefixSum[i];\n            ll leftMax = query(suffixTree, 1, 0, _n - 1, pg[i] + 1, i - 1) - suffixSum[i];\n            if (max(leftMax, rightMax) > 0) {\n                flag = false;\n                break;\n            }\n        }\n        if (flag) \n            cout << \"YES\\n\";\n        else \n            cout << \"NO\\n\";\n   }\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "implementation",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1691",
    "index": "E",
    "title": "Number of Groups",
    "statement": "You are given $n$ colored segments on the number line. Each segment is either colored red or blue. The $i$-th segment can be represented by a tuple $(c_i, l_i, r_i)$. The segment contains all the points in the range $[l_i, r_i]$, inclusive, and its color denoted by $c_i$:\n\n- if $c_i = 0$, it is a red segment;\n- if $c_i = 1$, it is a blue segment.\n\nWe say that two segments of \\textbf{different} colors are connected, if they share at least one common point. Two segments belong to the same group, if they are either connected directly, or through a sequence of directly connected segments. Find the number of groups of segments.",
    "tutorial": "We will be using the starting and ending points of different segments to count the final answer. We maintain a Union-Find data structure (DSU) on size $n$ corresponding to the $n$ segments given as input. We store all the starting and ending points in a set. (example: If $2$ segments are $(0,10)$ and $(11, 12)$, we store ${0,10,11,12}$ in a set irrespective of the color of the segment). We now iterate through these points in ascending order. We maintain $2$ running sets corresponding to the $2$ colors. In these sets, we will store the segments for which the starting point has been reached while iterating through the set of points but the ending point hasn't been reached (ie: we store the segments that have started but not ended). The algorithm works as follows: If we are at a point $x$: If it corresponds to a segment's starting point: We add that segment to the set corresponding to its color We merge (DSU merge) this segment with all segments present in the set corresponding to the other color (since their ending point hasn't been reached yet). We also erase all segments in the set corresponding to the other color except the one with the largest closing point value. We add that segment to the set corresponding to its color We merge (DSU merge) this segment with all segments present in the set corresponding to the other color (since their ending point hasn't been reached yet). We also erase all segments in the set corresponding to the other color except the one with the largest closing point value. If the point corresponds to a segment's ending point: We delete the segment from the set corresponding to its color. We delete the segment from the set corresponding to its color. Why can we delete the segments of color except for the one with the largest ending point if we encounter a starting point of the other color? We are able to greedily pick the segment with the furthest ending point value because all segments of the same color in that set have been connected together by the segments of the other color. Hence, we can just work with the segments with the largest ending point value of both colors for each component that exists. darkkcyan's solution without using sets in python. TheScrasse's $nlog^3n$ solution for E using Boruvka and Mergesort tree :D",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define nl \"\\n\"\n#define nf endl\n#define ll int\n#define pb push_back\n#define _ << ' ' <<\n#define tm gfewnignefgo\n \n#define INF (int)1e9\n#define mod 998244353\n#define maxn 200010\n \nll i, i1, j, k, k1, t, n, m, res, flag[10], a, b;\nll c[maxn], l[maxn], r[maxn], pr[maxn], sz[maxn];\nll tm, df[maxn];\nvector<ll> adj[maxn];\nvector<array<ll, 2>> nd;\nvector<array<ll, 3>> cm;\npriority_queue<array<ll, 2>> fn[2][maxn]; \n \nll find(ll x) {\n    if (x == pr[x]) return x;\n    return pr[x] = find(pr[x]);\n}\n \nbool same(ll a, ll b) {\n    return (find(a) == find(b));\n}\n \nvoid onion(ll a, ll b) {\n    a = find(a); b = find(b);\n    if (a == b) return;\n    if (sz[a] < sz[b]) swap(a, b);\n    pr[b] = a; sz[a] += sz[b];\n}\n \nvoid upd(ll c, ll p, ll x, ll id) {\n    while (p < maxn) {\n        fn[c][p].push({x, id}); p += (p & (-p));\n    }\n}\n \nvoid nts(ll c, ll p, ll r, ll st) {\n    ll wn = -1;\n    for (; p > 0; p -= (p & (-p))) {\n        while (!fn[c][p].empty()) {\n            auto [rr, id] = fn[c][p].top();\n            if (!df[id]) {\n                fn[c][p].pop(); continue;\n            }\n            if (rr < r) break;\n            wn = id; break;\n        }\n        if (wn != -1) {\n            nd.pb({st, wn}); break;\n        }\n    }\n}\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    #if !ONLINE_JUDGE && !EVAL\n        ifstream cin(\"input.txt\");\n        ofstream cout(\"output.txt\");\n    #endif\n \n    // today I'm overkilling everything\n    // tl;dr mst with boruvka and merge sort tree, O(n*log^3(n)), let's hope it gets ac\n \n    cin >> t;\n    while (t--) {\n        cin >> n;\n        for (i = 1; i <= 2 * n; i++) {\n            while (!fn[0][i].empty()) fn[0][i].pop();\n            while (!fn[1][i].empty()) fn[1][i].pop();\n        }\n        for (i = 1; i <= n; i++) {\n            cin >> c[i] >> l[i] >> r[i];\n            pr[i] = i; sz[i] = 1;\n        }\n \n        cm.clear(); cm.pb({-INF, 0, 0});\n        for (i = 1; i <= n; i++) {\n            cm.pb({l[i], i, 0}); cm.pb({r[i], i, 1});\n        }\n \n        sort(cm.begin(), cm.end());\n        for (i = 1; i <= 2 * n; i++) {\n            if (i == 1 || cm[i][0] != cm[i - 1][0]) k = i;\n            if (cm[i][2] == 0) l[cm[i][1]] = k;\n            else r[cm[i][1]] = k;\n        }\n \n        for (i = 1; i <= n; i++) {\n            upd(c[i], l[i], r[i], i); df[i] = true;\n        }\n \n        while (true) { \n            nd.clear();\n            for (i = 1; i <= n; i++) adj[i].clear(); \n            for (i = 1; i <= n; i++) adj[find(i)].pb(i);\n            for (i = 1; i <= n; i++) {\n                for (auto u : adj[i]) df[u] = false;\n                for (auto u : adj[i]) nts(c[u] ^ 1, r[u], l[u], u);\n                for (auto u : adj[i]) {\n                    df[u] = true; upd(c[u], l[u], r[u], u);\n                }\n            }\n \n            if (nd.empty()) break;\n            for (auto [a, b] : nd) onion(a, b);\n        }\n \n        res = 0;\n        for (i = 1; i <= n; i++) {\n            if (find(i) == i) res++;\n        }\n        cout << res << nl;\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1691",
    "index": "F",
    "title": "K-Set Tree",
    "statement": "You are given a tree $G$ with $n$ vertices and an integer $k$. The vertices of the tree are numbered from $1$ to $n$.\n\nFor a vertex $r$ and a subset $S$ of vertices of $G$, such that $|S| = k$, we define $f(r, S)$ as the size of the smallest rooted subtree containing all vertices in $S$ when the tree is rooted at $r$. A set of vertices $T$ is called a rooted subtree, if all the vertices in $T$ are connected, and for each vertex in $T$, all its descendants belong to $T$.\n\nYou need to calculate the sum of $f(r, S)$ over \\textbf{all possible distinct combinations} of vertices $r$ and subsets $S$, where $|S| = k$. Formally, compute the following: $$\\sum_{r \\in V} \\sum_{S \\subseteq V, |S| = k} f(r, S),$$ where $V$ is the set of vertices in $G$.\n\nOutput the answer modulo $10^9 + 7$.",
    "tutorial": "Our task is to calculate $\\sum_{R \\in V} \\sum_{S \\subseteq V, |S| = k} f(R, S)$ We will calculate our answer using dynamic programming over the trees. In this technique, we will calculate some properties for each sub-tree and eventually get those properties for the entire tree. The first property that we want to calculate for each sub-tree with node $v$ as the sub-tree root is - $cnt(v)$ which is the number of subsets of size $k$ such that sub-tree of $v$ is the minimum-size sub-tree covering it entirely. This can be calculated using combinatorics - first we calculate the total number of subsets of size $k$ in this sub-tree and then from it we can subtract the number of subsets of size $k$ which don't have sub-tree of $v$ as the minimum size sub-tree. $cnt(v) = {size(v) \\choose k} - \\sum \\limits_{u \\in \\text{children}} {size(u) \\choose k}$ This first property that we calculated is very important for us: If we take the sum of $cnt(v)$ over every node, we will get the total number of subsets of size $k$. When the tree is rooted at $r$, $cnt(v)$ represents the number of subsets where sub-tree of $v$ is the smallest sub-tree containing a set $S$ with $k$ vertices. Conclusively, $f(R = r, S) = \\sum \\limits_{v = 1}^{n} cnt(v) \\times size(v)$. The second property that we want to find for each sub-tree is the $size(v)$ - the size of the sub-tree of $v$. The third property that we want to find for each sub-tree is $cntsz(v) = cnt(v) \\times size(v)$. Now, we have $f(R = r, S)$ (as explained above) i.e. the contribution to the final answer when the root of the entire tree is fixed at $r$. We can calculate the final answer by fixing other nodes as roots and then summing these value up. Notice what happens when we try to change the root from $r$ to one of it's children. The properties that we calculated for each sub-tree remain the same except for the old root and the new root. We can recalculate the properties for these two nodes using some clever arithmetic and get the new answer with a new root. This is known as re-rooting technique. The method to calculate the new properties are: Note: We use $OR$ to represent Old Root. and $NR$ to represent New Root. $size_{new}(OR) = size_{old}(OR) - size_{old}(NR)$. (Subtracting the size of this branch.) $size_{new}(NR) = n$. (This is the main root.) $cnt_{new}(OR) = cnt_{old}(OR) - {size_{old}(OR) \\choose k} + {size_{new}(OR) \\choose k} + {size_{old}(NR) \\choose k}$. (Removing contribution of old size and putting contribution of new size. Removing contribution of the branch.) $cnt_{new}(NR) = cnt_{old}(NR) - {size_{old}(NR) \\choose k} + {size_{new}(NR) \\choose k} - {size_{new}(OR) \\choose k}$. (Removing contribution of old size and putting contribution of new size. Putting contribution of new brach.) $cntsz_{new}(OR) = cnt_{new}(OR) \\times size_{new}(OR)$ (By definition.) $cntsz_{new}(NR) = cnt_{new}(NR) \\times size_{new}(NR)$ (By definition.) $ans_{new} = ans_{old} - cntsz_{old}(OR) - cntsz_{old}(NR) + cntsz_{new}(OR) + cntsz_{new}(NR)$ (Subtracting old contribution and adding new contribution.) The final answer is given by: $finalans = \\sum \\limits_{v=1}^n ans_v$",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\nusing ll = long long;\n \nconst ll MOD = 1e9 + 7;\n \nstruct Comb {\n    vector<ll> fac;\n    vector<ll> invfac;\n    ll n;\n \n    Comb(ll n)\n    {\n        this->n = n;\n        fac.resize(n + 1, 0);\n        invfac.resize(n + 1, 0);\n \n        fac[0] = 1;\n        for (ll i = 1; i <= n; i++)\n            fac[i] = (fac[i - 1] * i) % MOD;\n        invfac[n] = power(fac[n], MOD - 2);\n        for (ll i = n - 1; i >= 0; i--)\n            invfac[i] = (invfac[i + 1] * (i + 1)) % MOD;\n    }\n \n    static ll power(ll x, ll y)\n    {\n        ll ret = 1;\n        while (y) {\n            if (y & 1)\n                ret = (ret * x) % MOD;\n            y >>= 1;\n            x = (x * x) % MOD;\n        }\n        return ret;\n    }\n \n    ll nCr(ll n, ll r)\n    {\n        if (n < 0 or r < 0 or n < r)\n            return 0;\n        ll ans = (fac[n] * ((invfac[r] * invfac[n - r]) % MOD)) % MOD;\n        return ans;\n    }\n};\n \nvector<vector<int> > adj;\nvector<int> sz;\nvector<ll> cnt;\nvector<ll> cntsz;\n \nComb C(2e5 + 5);\n \nll cur_ans = 0;\nll ans = 0;\n \nvoid dfs1(int v, int p, int k)\n{\n    sz[v] = 1;\n    ll sub = 0;\n \n    for (int u : adj[v]) {\n        if (u != p) {\n            dfs1(u, v, k);\n            sz[v] += sz[u];\n            sub = (sub + C.nCr(sz[u], k)) % MOD;\n        }\n    }\n \n    cnt[v] = (C.nCr(sz[v], k) - sub + MOD) % MOD;\n    cntsz[v] = (cnt[v] * sz[v]) % MOD;\n    cur_ans = (cur_ans + cntsz[v]) % MOD;\n}\n \nvoid dfs2(int v, int p, int k)\n{\n    ans = (ans + cur_ans) % MOD;\n    for (int u : adj[v]) {\n        if (u != p) {\n            // store\n            int store_v_sz = sz[v];\n            ll store_v_cnt = cnt[v];\n            ll store_v_cntsz = cntsz[v];\n            int store_u_sz = sz[u];\n            ll store_u_cnt = cnt[u];\n            ll store_u_cntsz = cntsz[u];\n            ll store_cur_ans = cur_ans;\n \n            // recalculate size[v], size[u]\n            sz[v] -= sz[u];\n            sz[u] = sz.size();\n \n            // recalculate cnt[v]\n            cnt[v] = (cnt[v] - C.nCr(store_v_sz, k) + MOD) % MOD;\n            cnt[v] = (cnt[v] + C.nCr(sz[v], k)) % MOD;\n            cnt[v] = (cnt[v] + C.nCr(store_u_sz, k)) % MOD;\n \n            // recalculate cnt[u]\n            cnt[u] = (cnt[u] - C.nCr(store_u_sz, k) + MOD) % MOD;\n            cnt[u] = (cnt[u] + C.nCr(sz[u], k)) % MOD;\n            cnt[u] = (cnt[u] - C.nCr(sz[v], k) + MOD) % MOD;\n \n            // recalculate cntsz\n            cntsz[v] = (cnt[v] * sz[v]) % MOD;\n            cntsz[u] = (cnt[u] * sz[u]) % MOD;\n \n            // recalculate cur_ans\n            cur_ans = (cur_ans - store_v_cntsz - store_u_cntsz + MOD + MOD) % MOD;\n            cur_ans = (cur_ans + cntsz[v] + cntsz[u]) % MOD;\n \n            dfs2(u, v, k);\n \n            // restore\n            sz[v] = store_v_sz;\n            cnt[v] = store_v_cnt;\n            cntsz[v] = store_v_cntsz;\n            sz[u] = store_u_sz;\n            cnt[u] = store_u_cnt;\n            cntsz[u] = store_u_cntsz;\n            cur_ans = store_cur_ans;\n        }\n    }\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n \n    int n, k;\n    cin >> n >> k;\n \n    adj.resize(n);\n    sz.resize(n);\n    cnt.resize(n);\n    cntsz.resize(n);\n \n    for (int i = 0; i < n - 1; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u, --v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n \n    dfs1(0, 0, k);\n    dfs2(0, 0, k);\n \n    cout << ans << endl;\n    return 0;\n}\n",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1692",
    "index": "A",
    "title": "Marathon",
    "statement": "You are given four \\textbf{distinct} integers $a$, $b$, $c$, $d$.\n\nTimur and three other people are running a marathon. The value $a$ is the distance that Timur has run and $b$, $c$, $d$ correspond to the distances the other three participants ran.\n\nOutput the number of participants in front of Timur.",
    "tutorial": "We can re-word the problem to count the number of numbers from $b, c, d$ that are larger than $a$. A possible way to do this is by keeping a variable that gets incremented every time we checked using the if statement whether a number is larger than $a$. The complexity is $\\mathcal{O}(1)$.",
    "code": "t = int(input())\nfor test in range(t):\n    a,b,c,d = map(int, input().split())\n    rs = (b > a) + (c > a) + (d > a)\n    print(rs)",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1692",
    "index": "B",
    "title": "All Distinct",
    "statement": "Sho has an array $a$ consisting of $n$ integers. An operation consists of choosing two distinct indices $i$ and $j$ and removing $a_i$ and $a_j$ from the array.\n\nFor example, for the array $[2, 3, 4, 2, 5]$, Sho can choose to remove indices $1$ and $3$. After this operation, the array becomes $[3, 2, 5]$. Note that after any operation, the length of the array is reduced by two.\n\nAfter he made some operations, Sho has an array that has only \\textbf{distinct} elements. In addition, he made operations such that the resulting array is the \\textbf{longest} possible.\n\nMore formally, the array after Sho has made his operations respects these criteria:\n\n- No pairs such that ($i < j$) and $a_i = a_j$ exist.\n- The length of $a$ is maximized.\n\nOutput the length of the final array.",
    "tutorial": "Note that the size of the array doesn't change parity, since it always decreases by $2$. Let's count the number of distinct elements, call it $x$. If $x$ is the same parity as $n$ (the length of the array), then we can make sure all of these $x$ distinct elements stay in the array by removing two elements at a time. Otherwise, $x$ isn't the same parity as $n$. Then $x-1$ is the same parity as $n$, and we can make sure $x-1$ distinct elements stay in the array by removing two elements at a time. So the answer is $x$ if $x$ and $n$ have the same parity, and $x-1$ otherwise. For example: $[15,16,16,15]$ has $x=4$, $n=2$. So $x$ and $n$ have the same parity, and we can get all distinct numbers $[15,16]$ by removing $i=3$, $j=4$. Time complexity: $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n)$, depending on the implementation.",
    "code": "#include <bits/stdc++.h>\ntypedef long long  ll;\nusing namespace std;\n\nvoid solve()\n{\n\tint n, x;\n\tcin >> n;\n\tset<int> a;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tcin >> x;\n\t\ta.insert(x);\n\t}\n\tif((n-a.size())%2 == 0)\n\t{\n\t\tcout << a.size() << endl;\n\t}\n\telse\n\t{\n\t\tcout << a.size()-1 << endl;\n\t}\n}\n\nint32_t main(){\n\tint t = 1;\n\tcin >> t;\n\twhile (t--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1692",
    "index": "C",
    "title": "Where's the Bishop?",
    "statement": "Mihai has an $8 \\times 8$ chessboard whose rows are numbered from $1$ to $8$ from top to bottom and whose columns are numbered from $1$ to $8$ from left to right.\n\nMihai has placed exactly one bishop on the chessboard. \\textbf{The bishop is not placed on the edges of the board.} (In other words, the row and column of the bishop are between $2$ and $7$, inclusive.)\n\nThe bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked.\n\n\\begin{center}\n{\\small An example of a bishop on a chessboard. The squares it attacks are marked in red.}\n\\end{center}\n\nMihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.",
    "tutorial": "There are many ways to solve the problem. One way is to look for the following pattern: $\\texttt{X.X}\\\\\\texttt{.X.}\\\\\\texttt{X.X}$ You can also look at the positions of the two diagonals and intersect them, but it requires more implementation. Time complexity: $\\mathcal{O}(1)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tchar g[9][9];\n\tfor (int i = 1; i <= 8; i++) {\n\t\tfor (int j = 1; j <= 8; j++) {\n\t\t\tcin >> g[i][j];\n\t\t}\n\t}\n\tfor (int i = 2; i <= 7; i++) {\n\t\tfor (int j = 2; j <= 7; j++) {\n\t\t\tif (g[i][j] == '#' && g[i - 1][j - 1] == '#' && g[i - 1][j + 1] == '#' && g[i + 1][j - 1] == '#' && g[i + 1][j + 1] == '#') {\n\t\t\t\tcout << i << ' ' << j << '\\n'; return;\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1692",
    "index": "D",
    "title": "The Clock",
    "statement": "Victor has a 24-hour clock that shows the time in the format \"HH:MM\" (00 $\\le$ HH $\\le$ 23, 00 $\\le$ MM $\\le$ 59). He looks at the clock every $x$ minutes, and the clock is currently showing time $s$.\n\nHow many \\textbf{different} palindromes will Victor see in total after looking at the clock every $x$ minutes, the first time being at time $s$?\n\nFor example, if the clock starts out as 03:12 and Victor looks at the clock every $360$ minutes (i.e. every $6$ hours), then he will see the times 03:12, 09:12, 15:12, 21:12, 03:12, and the times will continue to repeat. Here the time 21:12 is the only palindrome he will ever see, so the answer is $1$.\n\nA palindrome is a string that reads the same backward as forward. For example, the times 12:21, 05:50, 11:11 are palindromes but 13:13, 22:10, 02:22 are not.",
    "tutorial": "Note that Victor looks at the clock forever, but there are only at most $1440$ different times the clock can show (because there are $1440$ different minutes in a day). So we only have to check the first $1440$ times Victor sees, and count the palindromes (you can check a few more just to be safe, but they will repeat anyways). Now we just have to implementing adding $x$ minutes to a clock. There are several ways to do this. One of the slower ways might be writing functions converting a number of minutes into a time for a clock, or you can just compute all palindrome times in terms of minutes and that way you don't have to convert from clock time to number of minutes. The complexity is $\\mathcal{O}(1)$ per test case, since you only have to check a constant number of times.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint a[5] = {600, 60, 0, 10, 1};\nint good[16] = {0, 70, 140, 210, 280, 350, 601, 671, 741, 811, 881, 951, 1202, 1272, 1342, 1412};\n\nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tint x;\n\tcin >> x;\n\tint tot = 0;\n\tfor (int i = 0; i < 5; i++) {\n\t\ttot += (int)(s[i] - '0') * a[i];\n\t}\n\tset<int> t;\n\tfor (int i = 0; i < 2022; i++) {\n\t\tt.insert(tot);\n\t\ttot += x;\n\t\ttot %= 1440;\n\t}\n\tint res = 0;\n\tfor (int i : t) {\n\t\tfor (int j = 0; j < 16; j++) {\n\t\t\tif (good[j] == i) {res++;}\n\t\t}\n\t}\n\tcout << res << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1692",
    "index": "E",
    "title": "Binary Deque",
    "statement": "Slavic has an array of length $n$ consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array.\n\nWhat is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to $s$ after performing all the operations? In case the sum $s$ can't be obtained after any amount of operations, you should output -1.",
    "tutorial": "Note that the remaining array is a subarray of the original array. There are many ways to approach the problem. Here is one solution, which the main solution uses: Compute prefix sums on the array, so we can find out the value of $a_l + \\dots + a_r$ quickly. Let's iterate through the left endpoint $l$ from $1$ to $n$. Afterwards, we can binary search on the smallest value of $r$ such that $a_l + \\dots + a_r = s$, since this sum is strictly increasing. The time complexity is $\\mathcal{O}(n \\log n)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define       forn(i,n)              for(int i=0;i<n;i++)\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\n\nll query(int l, int r, vector<ll>& p) {\n    return p[r] - (l ? p[l - 1] : 0);\n}\n\nvoid solve() {  \n    int n, s; cin >> n >> s;\n    vector<ll> a(n), p(n);\n    forn(i, n) {\n        cin >> a[i];\n        p[i] = a[i];\n        if(i) p[i] += p[i - 1];\n    }\n\n    int ans = INT_MAX;\n\n    for(int i = 0; i < n; ++i) {\n        int l = i, r = n - 1, pos = -1;\n        while(l <= r) {\n            int mid = l + r >> 1;\n            if(query(i, mid, p) <= s) {\n                pos = mid;\n                l = mid + 1;\n            } else r = mid - 1;\n        }\n        if(pos == -1 || query(i, pos, p) != s) continue;\n        ans = min(ans, n - (pos - i + 1));\n    }\n\n    cout << (ans == INT_MAX ? -1 : ans) << \"\\n\";\n} \n     \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}   ",
    "tags": [
      "binary search",
      "implementation",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1692",
    "index": "F",
    "title": "3SUM",
    "statement": "Given an array $a$ of positive integers with length $n$, determine if there exist three \\textbf{distinct} indices $i$, $j$, $k$ such that $a_i + a_j + a_k$ ends in the digit $3$.",
    "tutorial": "Since we only care about the last digit of the sum $a_i + a_j + a_k$, we can ignore all numbers other than the last digits of the elements of $a$. (For example, we can consider $[20, 22, 19, 84]$ to be the same as $[0, 2, 9, 4]$.) Now note that if a number appears more than $3$ times in the array, we can ignore all copies that occur more than $3$ times, since our sum $a_i + a_j + a_k$ only involves three numbers. (For example, we can consider $[1,1,1,1,2]$ to be the same as $[1,1,1,2]$.) Using these observations, note that there are only $10$ digits, and each digit can occur at most $3$ times. So we can always reduce the array to one of length $30$. Since $30$ is very small, we can brute force all triples $a_i + a_j + a_k$, which runs quickly enough. Time complexity: $\\mathcal{O}(n + \\min(n, 30)^3)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tint cnt[10] = {};\n\tfor (int i = 0; i < n; i++) {\n\t\tint x;\n\t\tcin >> x;\n\t\tcnt[x % 10]++;\n\t}\n\tvector<int> v;\n\tfor (int i = 0; i < 10; i++) {\n\t\tfor (int j = 0; j < min(cnt[i], 3); j++) {\n\t\t\tv.push_back(i);\n\t\t}\t\n\t}\n\tint m = v.size();\n\tfor (int i = 0; i < m; i++) {\n\t\tfor (int j = i + 1; j < m; j++) {\n\t\t\tfor (int k = j + 1; k < m; k++) {\n\t\t\t\tif ((v[i] + v[j] + v[k]) % 10 == 3) {cout << \"YES\\n\"; return;}\n\t\t\t}\n\t\t}\n\t}\n\tcout << \"NO\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}  ",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1692",
    "index": "G",
    "title": "2^Sort",
    "statement": "Given an array $a$ of length $n$ and an integer $k$, find the number of indices $1 \\leq i \\leq n - k$ such that the subarray $[a_i, \\dots, a_{i+k}]$ with length $k+1$ (\\textbf{not} with length $k$) has the following property:\n\n- If you multiply the first element by $2^0$, the second element by $2^1$, ..., and the ($k+1$)-st element by $2^k$, then this subarray is sorted in strictly increasing order.\n\nMore formally, count the number of indices $1 \\leq i \\leq n - k$ such that $$2^0 \\cdot a_i < 2^1 \\cdot a_{i+1} < 2^2 \\cdot a_{i+2} < \\dots < 2^k \\cdot a_{i+k}.$$",
    "tutorial": "Note that $2^x \\cdot a_i < 2^{x+1} \\cdot a_{i+1}$ is the same as $a_i < 2a_{i+1}$, since we can divide by $2^x$. This means that we only need to check whether $a_i < 2a_{i+1}$ for each pair of adjacent elements. Let's consider as an example $[20,22,19]$. Note that $20 < 2 \\cdot 22$ and $22 < 2 \\cdot 19$, so if you multiply the first element by $1$, the second by $2$, and the third by $2^2$, the array is sorted. So let's make a new array $b$ where $b_i = 1$ if $a_i < 2a_{i+1}$ and $b_i = 0$ otherwise. Then we know that the whole chain of inequalities holds true if all values in a subarray of length $k$ in $b$ have all their values equal to $1$. For example, if $a=[9, 5, 3, 2, 1]$, $b=[1,1,1,0]$. Say $k=2$. Then $[9,5,3]$ works, since $[9,5 \\cdot 2, 3 \\cdot 2^2]$ is sorted. We can write this as $9 < 2 \\cdot 5$ and $5 < 2 \\cdot 3$. This is equivalent to $b_1 = 1$ (since $a_1 < 2a_2$) and $b_2 = 1$ (since $a_2 < 2a_3$). So the problem is equivalent to counting the number of subarrays of length $k$ in $b$ whose elements are all equal to $1$. There are many ways to do this. For example, you can compute prefix sums and then find the sum of all subarrays of length $k$, and count the number whose sum is $k$. The model solution uses a sliding window and updates the number of ones in the current subarray as we move from left to right. Time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tint a[n];\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\tint ok[n];\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tok[i] = (a[i] < 2 * a[i + 1]);\n\t}\n\tint tot = 0;\n\tfor (int i = 0; i < k; i++) {\n\t\ttot += ok[i];\n\t}\n\tint res = 0;\n\tif (tot == k) {res++;}\n\tfor (int i = k; i < n - 1; i++) {\n\t\ttot += ok[i];\n\t\ttot -= ok[i - k];\n\t\tif (tot == k) {res++;}\n\t}\n\tcout << res << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "data structures",
      "dp",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1692",
    "index": "H",
    "title": "Gambling",
    "statement": "Marian is at a casino. The game at the casino works like this.\n\nBefore each round, the player selects a number between $1$ and $10^9$. After that, a dice with $10^9$ faces is rolled so that a random number between $1$ and $10^9$ appears. If the player guesses the number correctly their total money is doubled, else their total money is halved.\n\nMarian predicted the future and knows all the numbers $x_1, x_2, \\dots, x_n$ that the dice will show in the next $n$ rounds.\n\nHe will pick three integers $a$, $l$ and $r$ ($l \\leq r$). He will play $r-l+1$ rounds (rounds between $l$ and $r$ inclusive). In each of these rounds, he will guess the same number $a$. At the start (before the round $l$) he has $1$ dollar.\n\nMarian asks you to determine the integers $a$, $l$ and $r$ ($1 \\leq a \\leq 10^9$, $1 \\leq l \\leq r \\leq n$) such that he makes the most money at the end.\n\nNote that during halving and multiplying there is no rounding and there are no precision errors. So, for example during a game, Marian could have money equal to $\\dfrac{1}{1024}$, $\\dfrac{1}{128}$, $\\dfrac{1}{2}$, $1$, $2$, $4$, etc. (any value of $2^t$, where $t$ is an integer of any sign).",
    "tutorial": "There are several solutions. Here is one. If we fix the value of $a$, then let's make a new array $b$ as follows: $b_i = 1$ if $\\mathrm{round}_i = a$, and $b_i = -1$ otherwise. Then the total amount of money earned will just be $2^{b_l + \\dots + b_r}$, so we only need to maximize $b_l + \\dots + b_r$. In other words, we need to find the maximum sum of a subarray. This is a standard problem that can be solved using segment tree. Note that we need to iterate over all values of $a$, of which there are $n$ possibilities. So we have to update elements of the segment tree $\\mathcal{O}(n)$ times and query once for each $a$, which means overall the solution runs in $\\mathcal{O}(n \\log n)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define       forn(i,n)              for(int i=0;i<n;i++)\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n \nstruct DynamicMaxSubarraySum {\n    struct node {\n        ll pref, suf, val, sum;\n    };  \n    int N;\n    ll neutral;\n    vector<node> t;\n    DynamicMaxSubarraySum(int _N, ll assign_value) {\n        neutral = assign_value;\n        N = _N;\n        t.resize(4 * N);\n        forn(i, 4 * N) t[i] = {0, 0, 0, 0};\n        build(1, 0, N - 1); \n    }\n    void build(int i, int l, int r) {\n        if(l == r) {\n            t[i].pref = t[i].suf = t[i].val = t[i].sum = neutral;\n            return;\n        }\n        int mid = (l + r) >> 1;\n        build(2 * i, l, mid);\n        build(2 * i + 1, mid + 1, r);\n        t[i] = merge(t[2 * i], t[2 * i + 1]);\n    }\n    node merge(node a, node b) {\n        node c;\n        c.pref = max(a.pref, a.sum + b.pref);\n        c.suf = max(b.suf, b.sum + a.suf);\n        c.val = max({a.val, b.val, a.suf + b.pref});\n        c.sum = a.sum + b.sum;\n        return c;\n    }\n \n    void modif(int i, int l, int r, int pos, ll val) {\n        if(l > pos || r < pos) return;\n        if(l == pos && r == pos) {\n            t[i].pref = t[i].suf = t[i].val = t[i].sum = val;\n            return;\n        }\n        int mid = (l + r) >> 1;\n        modif(2 * i, l, mid, pos, val);\n        modif(2 * i + 1, mid + 1, r, pos, val);\n        t[i] = merge(t[2 * i], t[2 * i + 1]);\n    }\n    node query(int i, int l, int r, int tl, int tr) {\n        if(l > tr || r < tl) return {0, 0, 0, 0};\n        if(l >= tl && r <= tr) return t[i];\n        int mid = (l + r) >> 1;\n        return merge(query(2 * i, l, mid, tl, tr), query(2 * i + 1, mid + 1, r, tl, tr));\n    }\n \n    void modif(int pos, int val) {\n        modif(1, 0, N - 1, pos, val);\n    }\n    node query(int l, int r) {\n        return query(1, 0, N - 1, l, r);\n    }\n    node query(int pos) {\n        return query(1, 0, N - 1, pos, pos);\n    }\n};\n \nvoid solve() {  \n    int n; cin >> n;\n    vector<int> a(n);\n    forn(i, n) cin >> a[i];\n    map<int, vector<int>> vv;\n    forn(i, n) {\n        vv[a[i]].pb(i);\n    }\n    DynamicMaxSubarraySum st(n, -1);\n \n    ll mx = 0, ans = -1;\n    for(auto i: vv) {\n        vector<int> v = i.second;\n        for(auto x: v) st.modif(x, 1);\n        if(mx < st.query(0, n - 1).val) {\n            ans = i.first;\n            mx = st.query(0, n - 1).val;\n        }\n        for(auto x: v) st.modif(x, -1);\n    }  \n    int ansl = -1, ansr = -1;\n    for(int i = 0; i < n; ++i) {\n        if(a[i] == ans) a[i] = 1;\n        else a[i] = -1;\n    }\n    ll sum = 0, lastl = 0;\n    mx = 0;\n    for(int i = 0; i < n; ++i) {\n        sum += a[i];\n        if(sum > mx) {\n            mx = sum;\n            ansr = i;\n            ansl = lastl;\n        }\n        if(sum <= 0) {\n            lastl = i + 1;\n            sum = 0;\n        }\n    }\n \n    cout << ans << \" \" << ansl + 1 << \" \" << ansr + 1 << \"\\n\"; \n}   \n     \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1693",
    "index": "A",
    "title": "Directional Increase",
    "statement": "We have an array of length $n$. Initially, each element is equal to $0$ and there is a pointer located on the first element.\n\nWe can do the following two kinds of operations any number of times (possibly zero) in any order:\n\n- If the pointer is not on the last element, increase the element the pointer is currently on by $1$. Then move it to the next element.\n- If the pointer is not on the first element, decrease the element the pointer is currently on by $1$. Then move it to the previous element.\n\nBut there is one additional rule. \\textbf{After we are done, the pointer has to be on the first element.}\n\nYou are given an array $a$. Determine whether it's possible to obtain $a$ after some operations or not.",
    "tutorial": "First of all the sum of the elements has to be $0$ because the pointer has to end up on the first element. Denote the number of times you do the first operation while the pointer is on the $i$-th element as $b_i$. And the number of times you do the second operation while the pointer is on the $i$-th element as $c_i$. $a_i = b_i - c_i$ and $c_i = b_{i - 1}$ because the pointer has to end up on the first element. So $a_i = b_i - b_{i - 1} \\to b_i = a_i + b_{i - 1}$ and $b_1 = a_1$. Now that we have calculated $b$, we need to determine whether it's possible to perform the operations like so. There are two conditions. $b_i \\geq 0$ ($1 \\leq i \\leq n$). If $b_i = 0$ for each $j$, $i < j$, $b_j = 0$. Because the pointer couldn't reach the $j$-th element. You can always construct $a$ if these two conditions hold. Proof by induction. Perform the first operation and the second operation $b_1 - 1$ times in a row. Then perform the first operation. Construct the rest by induction and then perform the second operation. Time complexity: $\\mathcal{O}(n)$",
    "code": "//In the name of God\n#include <bits/stdc++.h>\nusing namespace std;\n\nconst int maxn = 2e5 + 100;\n\n#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n\nint n, t, a[maxn];\nlong long ps[maxn];\n\nint main(){\n\tfast_io;\n\t\n\tcin >> t;\n\twhile(t--){\n\t\tcin >> n;\n\t\tfor(int i = 1; i <= n; i++){\n\t\t\tcin >> a[i];\n\t\t\tps[i] = ps[i - 1] + a[i];\n\t\t}\n\t\tif(ps[n] != 0){\n\t\t\tcout << \"No\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tbool ok = 1;\n\t\tfor(int i = 1; i <= n; i++){\n\t\t\tif(ps[i] < 0) ok = 0;\n\t\t}\n\t\tbool visited_zero = 0;\n\t\tfor(int i = 1; i <= n; i++){\n\t\t\tif(ps[i] == 0) visited_zero = 1;\n\t\t\telse if(visited_zero) ok = 0;\n\t\t}\n\t\tif(ok) cout << \"Yes\\n\";\n\t\telse cout << \"No\\n\";\n\t}\n\t\n\treturn 0;\n}\n",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1693",
    "index": "B",
    "title": "Fake Plastic Trees",
    "statement": "We are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root of the tree is the vertex $1$ and the parent of the vertex $v$ is $p_v$.\n\nThere is a number written on each vertex, initially all numbers are equal to $0$. Let's denote the number written on the vertex $v$ as $a_v$.\n\nFor each $v$, we want $a_v$ to be between $l_v$ and $r_v$ $(l_v \\leq a_v \\leq r_v)$.\n\nIn a single operation we do the following:\n\n- Choose some vertex $v$. Let $b_1, b_2, \\ldots, b_k$ be vertices on the path from the vertex $1$ to vertex $v$ (meaning $b_1 = 1$, $b_k = v$ and $b_i = p_{b_{i + 1}}$).\n- Choose a non-decreasing array $c$ of length $k$ of nonnegative integers: $0 \\leq c_1 \\leq c_2 \\leq \\ldots \\leq c_k$.\n- For each $i$ $(1 \\leq i \\leq k)$, increase $a_{b_i}$ by $c_i$.\n\nWhat's the minimum number of operations needed to achieve our goal?",
    "tutorial": "Lemma 1. You won't perform the operation on a particular vertex more than once. Because you could merge the operations. Lemma 2. If you perform the operation on some vertex $v$, you can do it with $c_k = r_v$. If there is another operation that helps this vertex, you can cut the operation into two pieces and merge one with the operation that starts at $v$. And you can just increase $c_k$ if it's not equal to $r_v$. Define $dp_v$ as the minimum number of operations needed to satisfy the conditions on the vertices in the subtree of vertex $v$. We claim that there is a way to achieve our goal with minimum number of operations in which for each vertex $v$ there are exactly $dp_v$ operations done in the subtree of vertex $v$. Imagine there is a vertex $v$ that there are more than $dp_v$ operations on vertices in the subtree of vertex $v$. We can instead satisfy the subtree by $dp_v$ operations and make sure that we perform the operation on vertex $p_v$. Denote $mx_v$ as the maximum value that vertex $v$ can pass to its ancestors if exactly $dp_v$ operations are performed in the subtree of vertex $v$. We need to perform the operation on a vertex $v$ if and only if $\\sum_\\limits{u | p_u = v}{mx_u} < l_v$. If we need to perform the operation on vertex $v$ then $mx_v = r_v$, otherwise $mx_v = min(r_v, \\sum_\\limits{u | p_u = v}{mx_u})$. Time complexity: $\\mathcal{O}(n)$",
    "code": "# include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N = 2e5 + 10;\n\nint t, n, l[N], r[N], ans;\nvector <int> adj[N];\n\nll DFS(int v){\n\tll sum = 0;\n\tfor (int u : adj[v]){\n\t\tsum += DFS(u);\n\t}\n\tif (sum < ll(l[v])){\n\t\t++ ans;\n\t\treturn r[v];\n\t}\n\treturn min(ll(r[v]), sum);\n}\n\nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\n\tcin >> t;\n\twhile (t --){\n\t\tcin >> n;\n\t\tfor (int i = 2; i <= n; ++ i){\n\t\t\tint par;\n\t\t\tcin >> par;\n\t\t\tadj[par].push_back(i);\n\t\t}\n\t\tfor (int i = 1; i <= n; ++ i){\n\t\t\tcin >> l[i] >> r[i];\n\t\t}\n\t\tans = 0;\n\t\tDFS(1);\n\t\tcout << ans << \"\\n\";\n\t\tfor (int i = 1; i <= n; ++ i){\n\t\t\tadj[i].clear();\n\t\t}\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1693",
    "index": "C",
    "title": "Keshi in Search of AmShZ",
    "statement": "AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $n$ cities in Italy indexed from $1$ to $n$ and $m$ \\textbf{directed} roads indexed from $1$ to $m$. Initially, Keshi is located in the city $1$ and wants to go to AmShZ's house in the city $n$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.\n\nIn the beginning of each day, AmShZ can send one of the following two messages to Keshi:\n\n- AmShZ sends the index of one road to Keshi as a \\textbf{blocked} road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day.\n- AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $B$ is reachable from city $A$ if there's an out-going road from city $A$ to city $B$ which hasn't become \\textbf{blocked} yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location.\n\nAmShZ and Keshi want to find the smallest possible integer $d$ for which they can make sure that they will see each other after at most $d$ days. Help them find $d$.",
    "tutorial": "Define $dis_v$ as the minimum number of days needed to reach city $n$ from city $v$. $dis_n = 0$. We have to assume that Keshi will always choose the worst reachable city, that is the city with maximum $dis$. For each node $v$ we kind of have to choose $nxt_v$ and block all neighbors(outgoing edges) with a distance more than $dis_{nxt_v}$. We will use Dijkstra's algorithm. Note that in Dijkstra's algorithm we mark the nodes in increasing order of $dis$. At each step get the node $v$ with the minimum $dis$. For each node $u$ that there is an edge from $u$ to $v$, calculate $dis_u$ if $nxt_u$ was $v$. You know the number of edges you have to block since the neighbors with greater $dis$ are the ones that are not marked yet. Time complexity: $\\mathcal{O}(n\\log n)$",
    "code": "# include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2e5 + 10;\n\nint n, m, d[N], dist[N];\npriority_queue <pair <int, int> > pq;\nvector <int> adj[N];\nbool mark[N];\n\nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\n\tcin >> n >> m;\n\tfill(dist, dist + n + 1, m);\n\twhile (m --){\n\t\tint v, u;\n\t\tcin >> v >> u;\n\t\tadj[u].push_back(v);\n\t\t++ d[v];\n\t}\n\tdist[n] = 0;\n\tpq.push({0, n});\n\twhile (!pq.empty()){\n\t\tint v = pq.top().second;\n\t\tpq.pop();\n\t\tif (mark[v])\n\t\t\tcontinue;\n\t\tmark[v] = true;\n\t\tfor (int u : adj[v]){\n\t\t\tif (dist[v] + d[u] < dist[u]){\n\t\t\t\tdist[u] = dist[v] + d[u];\n\t\t\t\tpq.push({- dist[u], u});\n\t\t\t}\n\t\t\t-- d[u];\n\t\t}\n\t}\n\tcout << dist[1] << '\\n';\n\n\treturn 0;\n}\n",
    "tags": [
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1693",
    "index": "D",
    "title": "Decinc Dividing",
    "statement": "Let's call an array $a$ of $m$ integers $a_1, a_2, \\ldots, a_m$ \\textbf{Decinc} if $a$ can be made increasing by removing a decreasing subsequence (possibly empty) from it.\n\n- For example, if $a = [3, 2, 4, 1, 5]$, we can remove the decreasing subsequence $[a_1, a_4]$ from $a$ and obtain $a = [2, 4, 5]$, which is increasing.\n\nYou are given a permutation $p$ of numbers from $1$ to $n$. Find the number of pairs of integers $(l, r)$ with $1 \\le l \\le r \\le n$ such that $p[l \\ldots r]$ (the subarray of $p$ from $l$ to $r$) is a \\textbf{Decinc} array.",
    "tutorial": "Let's solve the problem for a single subarray. Assume the $i$-th element belongs to the increasing subsequence. Define $dp_{l, i}$ for the interval $[l, i]$ as the maximum value the last element of the decreasing subsequence can have. It's $+\\infty$ in case the decreasing subsequence is empty. It's $-\\infty$ if the array is not possible. Assume the $i$-th element belongs to the decreasing subsequence. Define $pd_{l, i}$ for the interval $[l, i]$ as the minimum value the last element of the increasing subsequence can have. It's $-\\infty$ in case the increasing subsequence is empty. It's $+\\infty$ if the array is not possible. The interval $[l, r]$ is not Decinc if and only if $dp_{l, r} = -\\infty$ and $pd_{l, r} = +\\infty$. Iterate over $l$ from $n$ to $1$ and keep the $dp$ and $pd$ values updated (shown in the implementation). We claim that each $dp$ or $pd$ value will change at most three times throughout the algorithm. For some index $i$ assume $j$ is the largest index smaller than $i$ such that $a_j > a_{j + 1}$. $dp_i$ can only be one of these four values: $-\\infty, +\\infty, a_j, a_{j + 1}$. Because the last element of the decreasing subsequence can't be before the $j$-th element. And if it's some $k$ that lies on the interval $[j + 2, i - 1]$ you can simply move it to the increasing subsequence since both ($k - 1$)-th and ($k + 1$)-th elements belong to the increasing subsequence. The same applies for $pd_i$. So the $upd$ function is called $\\mathcal{O}(n)$ times in total. Time complexity: $\\mathcal{O}(n)$ It can be proven that a permutation is Decinc if and only if it's $3412$-avoiding and $2143$-avoiding.",
    "code": "# include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 2e5 + 10;\n\nint n, a[N], min_r[N], fen[N];\nlong long ans;\nstack <int> sk;\nvector <int> vec[2][N];\n\nvoid mofen(int pos, int val){\n\tfor (pos += 5; pos < N; pos += pos & - pos)\n\t\tfen[pos] = min(fen[pos], val);\n}\nint gefen(int pos){\n\tint res = n + 1;\n\tfor (pos += 5; 0 < pos; pos -= pos & - pos)\n\t\tres = min(res, fen[pos]);\n\treturn res;\n}\n\nvoid find_3412(){\n\tfill(fen, fen + n + 10, n + 1);\n\twhile (!sk.empty())\n\t\tsk.pop();\n\tfor (int i = 1; i <= n; ++ i){\n\t\twhile (!sk.empty() && a[i] < a[sk.top()])\n\t\t\tsk.pop();\n\t\tif (!sk.empty())\n\t\t\tvec[0][sk.top()].push_back(i);\n\t\tsk.push(i);\n\t}\n\twhile (!sk.empty())\n\t\tsk.pop();\n\tfor (int i = n; 1 <= i; -- i){\n\t\twhile (!sk.empty() && a[sk.top()] < a[i])\n\t\t\tsk.pop();\n\t\tif (!sk.empty())\n\t\t\tvec[1][sk.top()].push_back(i);\n\t\tsk.push(i);\n\t}\n\tfor (int i = n; 1 <= i; -- i){\n\t\tfor (int ind : vec[0][i])\n\t\t\tmofen(a[ind], ind);\n\t\tfor (int ind : vec[1][i])\n\t\t\tmin_r[ind] = min(min_r[ind], gefen(a[ind] - 1));\n\t\tvec[0][i].clear(), vec[1][i].clear();\n\t}\n}\n\nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\n\tcin >> n;\n\tfor (int i = 1; i <= n; ++ i)\n\t\tcin >> a[i];\n\tfill(min_r, min_r + n + 2, n + 1);\n\tfind_3412();\n\tfor (int i = 1; i <= n; ++ i)\n\t\ta[i] = n + 1 - a[i];\n\tfind_3412();\n\tfor (int i = n; 1 <= i; -- i){\n\t\tmin_r[i] = min(min_r[i], min_r[i + 1]);\n\t\tans += min_r[i] - i;\n\t}\n\tcout << ans << '\\n';\n\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "dp",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1693",
    "index": "E",
    "title": "Outermost Maximums",
    "statement": "Yeri has an array of $n + 2$ non-negative integers : $a_0, a_1, ..., a_n, a_{n + 1}$.\n\nWe know that $a_0 = a_{n + 1} = 0$.\n\nShe wants to make all the elements of $a$ equal to zero in the minimum number of operations.\n\nIn one operation she can do one of the following:\n\n- Choose the leftmost maximum element and change it to the maximum of the elements on its left.\n- Choose the rightmost maximum element and change it to the maximum of the elements on its right.\n\nHelp her find the minimum number of operations needed to make all elements of $a$ equal to zero.",
    "tutorial": "Let's calculate for each element of the array, the minimum number of times it needs to change throughout the process. Let's take a look at the first time the $i$-th element is changing. We know that $a_i$ is the maximum number and the elements smaller than $a_i$ haven't changed yet. Denote the maximum element on its left as $l$ and the maximum element on its right as $r$. So $l$ is equal to the largest number among $a_1, a_2, \\ldots, a_{i - 1}$ that is smaller than $a_i$. Likewise for $r$. We can change $a_i$ to either $l$ or $r$. It's better to change it to the smaller one. (We'll get into the details of why this is correct later.) Let $c_i$ be the minimum number of times the $i$-th element needs to change. The following greedy algorithm works in $\\sum c_i$ operations. Let $x$ be the number the leftmost maximum becomes if we do the first operation and $y$ be the number the rightmost maximum becomes if we do the second operation. Do the first operation if $x \\leq y$ and do the second operation otherwise. If $x \\leq y$ then for the leftmost maximum, the maximum element on its left is smaller than the maximum element on its right. That means we are making the right choice for this element. Let's assume the array is a permutation of numbers from $1$ through $n$ for simplicity. For some element $a_i$ make string $S$ of length $n$ such that $S_{a_i}$ = \"O\". for any $j < i$, $S_{a_j}$ = \"L\". for any $j > i$, $S_{a_j}$ = \"R\". Imagine Yeri is initially standing on the $a_i$-th character of S (which is \"O\") and she is facing the beginning of the string. In each step she either jumps to the nearest \"L\" or jumps to the nearest \"R\". And her goal is to jump out of the string in minimum number of jumps. We know it's always better to jump to the further one, but we won't need this fact. We will use a segment tree. For each node maintain 4 values. What is the minimum possible number of jumps made in this interval in case we enter it looking for an \"L\" and leave it looking for an \"L\" we enter it looking for an \"L\" and leave it looking for an \"R\" we enter it looking for an \"R\" and leave it looking for an \"L\" we enter it looking for an \"R\" and leave it looking for an \"R\" It's easy to update this. Just fix which character you are looking for when moving from the node's one child to the other. And you can find these values for intervals of length $1$. Now if you iterate over $i$ from $1$ to $n$. At each step at most 2 characters of the string are changing, hence you can keep your segment tree updated. But there are still some details we need to sort out. The array is not necessarily a permutation. To fix this, first get rid of the \"O\". Then for each number see if it appears on the left side and see if it appears on the right side. Now there are 4 different states for each number but the same segment tree can handle this too. We just need to find the 4 values for each of the 4 states of a single number. Time complexity: $\\mathcal{O}(n\\log n)$",
    "code": "//In the name of God\n#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\n\nconst ll maxn = 2e5 + 100;\nconst ll mod = 1e9 + 7;\nconst int inf = 1e9;\nconst ll INF = 1e18;\n\n#define fast_io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);\n#define file_io freopen(\"input.txt\", \"r+\", stdin);freopen(\"output.txt\", \"w+\", stdout);\n#define pb push_back\n#define Mp make_pair\n#define F first\n#define S second\n#define Sz(x) ll((x).size())\n#define all(x) (x).begin(), (x).end()\n#define lc (id << 1)\n#define rc (lc | 1)\n\nll pw(ll a, ll b){\n\tll c = 1;\n\twhile(b){\n\t\tif(b & 1) c = c * a % mod;\n\t\ta = a * a % mod;\n\t\tb >>= 1;\n\t}\n\treturn c;\n}\n\nstruct cost{\n\tint c[2][2];\n\tcost(){\n\t\tmemset(c, 0, sizeof c);\n\t}\n};\n\ncost cst[2][2];\n\nint n, a[maxn], dp[maxn], cnl[maxn], cnr[maxn];\nll s, ans, ans2;\ncost seg[maxn << 2];\n\ninline cost mrg(cost l, cost r){\n\tcost mid;\n\tfor(int i = 0; i < 2; i++){\n\t\tfor(int j = 0; j < 2; j++){\n\t\t\tmid.c[i][j] = min(r.c[i][0] + l.c[0][j], r.c[i][1] + l.c[1][j]);\n\t\t}\n\t}\n\treturn mid;\n}\n\nvoid bld(int id, int s, int e){\n\tif(e - s == 1){\n\t\tseg[id] = cst[int(cnl[s] > 0)][int(cnr[s] > 0)];\n\t\treturn;\n\t}\n\tint mid = (s + e) >> 1;\n\tbld(lc, s, mid);\n\tbld(rc, mid, e);\n\tseg[id] = mrg(seg[lc], seg[rc]);\n\treturn;\n}\n\nvoid upd(int id, int s, int e, int l, int r){\n\tif(r <= s || e <= l) return;\n\tif(l <= s && e <= r){\n\t\tseg[id] = cst[int(cnl[s] > 0)][int(cnr[s] > 0)];\n\t\treturn;\n\t}\n\tint mid = (s + e) >> 1;\n\tupd(lc, s, mid, l, r);\n\tupd(rc, mid, e, l, r);\n\tseg[id] = mrg(seg[lc], seg[rc]);\n\treturn;\n}\ncost get(int id, int s, int e, int l, int r){\n\tif(r <= s || e <= l) return cost();\n\tif(l <= s && e <= r) return seg[id];\n\tint mid = (s + e) >> 1;\n\treturn mrg(get(lc, s, mid, l, r), get(rc, mid, e, l, r));\n}\n\nint main(){\n\tfast_io;\n\tsrand(time(NULL));\n\t\n\tcst[0][0].c[0][0] = cst[0][0].c[1][1] = 0;\n\tcst[0][0].c[0][1] = cst[0][0].c[1][0] = inf;\n\t\n\tcst[0][1].c[1][0] = cst[0][1].c[1][1] = 1;\n\tcst[0][1].c[0][0] = 0;\n\tcst[0][1].c[0][1] = inf;\n\t\n\tcst[1][0].c[0][1] = cst[1][0].c[0][0] = 1;\n\tcst[1][0].c[1][1] = 0;\n\tcst[1][0].c[1][0] = inf;\n\t\n\tcst[1][1].c[0][0] = cst[1][1].c[1][1] = 1;\n\tcst[1][1].c[0][1] = cst[1][1].c[1][0] = 1;\n\t\n\tcin >> n;\n\tcnr[0] = cnl[0] = 1;\n\tfor(int i = 1; i <= n; i++){\n\t\tcin >> a[i];\n\t\tcnr[a[i]]++;\n\t\ts += a[i];\n\t}\n\tbld(1, 0, n + 1);\n\tfor(int i = 1; i <= n; i++){\n\t\tcost cs = get(1, 0, n + 1, 0, a[i]);\n\t\tcnr[a[i]]--;\n\t\tcnl[a[i]]++;\n\t\tupd(1, 0, n + 1, a[i], a[i] + 1);\n\t\tdp[i] = min({cs.c[0][0], cs.c[0][1], cs.c[1][0], cs.c[1][1]});\n\t\tans += dp[i];\n\t}\n\t\n\tcout << ans << \"\\n\";\n\t\n\treturn 0;\n}\n",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1693",
    "index": "F",
    "title": "I Might Be Wrong",
    "statement": "You are given a binary string $S$ of length $n$ indexed from $1$ to $n$. You can perform the following operation any number of times (possibly zero):\n\n- Choose two integers $l$ and $r$ ($1 \\le l \\le r \\le n$). Let $cnt_0$ be the number of times 0 occurs in $S[l \\ldots r]$ and $cnt_1$ be the number of times 1 occurs in $S[l \\ldots r]$. You can pay $|cnt_0 - cnt_1| + 1$ coins and sort the $S[l \\ldots r]$. (by $S[l \\ldots r]$ we mean the substring of $S$ starting at position $l$ and ending at position $r$)\n\nFor example if $S = $ 11001, we can perform the operation on $S[2 \\ldots 4]$, paying $|2 - 1| + 1 = 2$ coins, and obtain $S = $ 10011 as a new string.\n\nFind the minimum total number of coins required to sort $S$ in increasing order.",
    "tutorial": "- It's trivial that we only sort with segments with balance $0$. Proof: Imagine we have sorted interval $[l, r]$ and it has $d$ more zeros than it has ones. So this operation costs $d + 1$ coins. $S_l$ has to be $1$ otherwise we could just sort $[l + 1, r]$ with $d$ coins. Now that we know $S_l$ is $1$ there exists some $k \\leq r$ that the interval $[l, k]$ has equal number of zeros and ones. Because the interval $[l, l]$ has more ones but the interval $[l, r]$ has more zeros. Sort $[l, k]$ with cost $1$ and then sort $[l + 1, r]$ with cost $d$. And we know we can sort $[l + 1, r]$ such that we only sort segments with balance $0$. - If everything is sorted cool. Suppose now the number of ones is greater than the number of zeros. - Replace $0$ by $-1$, $1$ by $1$, draw prefix sums. We have $n + 1$ points $(i, a_i)$, (initially $a_i = pref_i$), where $a_0 = 0$, $a_n>0$, and the operation is: choosing $i$, $j$ such that $a_i = a_j$ and making points between them first decrease then increase. Denote by AmShZ strategy the following procedure: while $S$ isn't sorted, Let $i$ be the smallest such that numbers from $a_i$ to $a_n$ increase. If $a_i \\leq 0$, we sort in $1$ operation. Otherwise, let $j$ be the smallest such that $a_j = a_i$. Apply operation to $[j, i]$. Let's denote by $f(S)$ the smallest number of operations required for the current configuration. We will prove that AmShZ strategy ends in $f(S)$ iterations by induction over $n$ and over number of inversions in $S$. (Clearly any non-identical operation decreases number of inversions so that's useful). Denote by $S_k$ string $S$ in which suffix of length $k$ is sorted. Lemma 1: If $k1 > k2$, then AmShZ strategy for $S_{k1}$ uses at most as many operations as for $S_{k2}$. Proof: trivial Suppose now that we have proved our statement for all strings with the number of inversions less than in $S$. Now, let $i$ be the smallest such that numbers from $a_i$ to $a_n$ increase and $j$ be the smallest such that $a_j = a_i$. Suppose that there is a sorting sequence that uses fewer operations than AmShZ strategy. Let's denote its first operation by $[l, r]$. Consider several cases: $r \\geq i$. This means that we basically end up in string $S_{n-l}$. But we could have ended up in string $S_{n-j}$, which uses at most the same number of operations $r \\leq j$. Clearly, after operation $[l, r]$ $a_i$ can only decrease, so $j$ will still be the smallest index with $a_j = a_i$. By induction hypothesis, AmShZ strategy is optimal for resulting string, so the next operation in resulting string will be opertion $[j, i]$. But then we could have done $[j, i]$ first and then $[l, r]$. $j \\leq l$. As $r<i$, the smallest index $i$ such that $a_i \\ldots$ $a_n$ are increasing hasn't changed. Numbers from $a_0$ to $a_j$ also haven't changed, so $j$ remains the same. So the next move according to AmShZ strategy will be operation $[j, i]$, so operation $[l, r]$ was useless Last case. $l<j<r<i$. Note that all numbers up to $a_r$ will be strictly smallest then $a_i$ now. So we will have some new smallest $j1>r$ such that $a_j1 = a_i$. Then according to AmShZ strategy in the next move we will do operation $[j1, i]$. But then we could instead do $[j1, i]$ first, and then $[l, r]$. But this is not optimal, as AmShZ strategy sorts $S_{n-j1}$ at least as fast as $S_{n - i}$.",
    "code": "#include <iostream>\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <unordered_map>\n#include <queue>\n#include <ctime>\n#include <cassert>\n#include <complex>\n#include <string>\n#include <cstring>\n#include <chrono>\n#include <random>\n#include <bitset>\n#include <array>\nusing namespace std;\n \n#ifdef LOCAL\n\t#define eprintf(...) {fprintf(stderr, __VA_ARGS__);fflush(stderr);}\n#else\n\t#define eprintf(...) 42\n#endif\n \nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\nusing pii = pair<int, int>;\nusing pli = pair<ll, int>;\nusing pll = pair<ll, ll>;\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\nll myRand(ll B) {\n\treturn (ull)rng() % B;\n}\n \n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n \nclock_t startTime;\ndouble getCurrentTime() {\n\treturn (double)(clock() - startTime) / CLOCKS_PER_SEC;\n}\n \nconst int N = 200200;\nint n;\nchar s[N];\nint bal[N];\nint pos[N];\n \nvoid solve() {\n\tscanf(\"%d %s\", &n, s);\n\tint b = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] == '0')\n\t\t\tb++;\n\t\telse\n\t\t\tb--;\n\t}\n\tif (b < 0) {\n\t\tfor (int i = 0; i < n; i++)\n\t\t\ts[i] ^= 1;\n\t\treverse(s, s + n);\n\t\tb *= -1;\n\t}\n\tbal[0] = (n + b) / 2;\n\tfor (int i = 0; i < n; i++)\n\t\tbal[i + 1] = bal[i] + (s[i] == '0' ? -1 : 1);\n\tassert(bal[n] == (n - b) / 2);\n\tfor (int i = 0; i <= n; i++)\n\t\tpos[i] = -1;\n\tfor (int i = 0; i <= n; i++)\n\t\tpos[bal[i]] = i;\n\tint ans = 0;\n\tint l = 0;\n\twhile(l < (n + b) / 2) {\n\t\tif (bal[l + 1] < bal[l]) {\n\t\t\tl++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (bal[l] <= (n - b) / 2) {\n\t\t\tans++;\n\t\t\tbreak;\n\t\t}\n\t\tint r = pos[bal[l]];\n\t\tassert(r > l);\n\t\tans++;\n\t\tfor (int i = l + 1; i < r; i++) {\n\t\t\tif (2 * i > l + r) {\n\t\t\t\tbal[i] = bal[l] - (r - i);\n\t\t\t} else {\n\t\t\t\tbal[i] = bal[l] - (i - l);\n\t\t\t}\n\t\t\tpos[bal[i]] = max(pos[bal[i]], i);\n\t\t}\n\t}\n\tprintf(\"%d\\n\", ans);\n}\n \nint main()\n{\n\tstartTime = clock();\n//\tfreopen(\"input.txt\", \"r\", stdin);\n//\tfreopen(\"output.txt\", \"w\", stdout);\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile(t--) solve();\n \n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "greedy",
      "two pointers"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1694",
    "index": "A",
    "title": "Creep",
    "statement": "Define the score of some binary string $T$ as the absolute difference between the number of zeroes and ones in it. (for example, $T=$ 010001 contains $4$ zeroes and $2$ ones, so the score of $T$ is $|4-2| = 2$).\n\nDefine the creepiness of some binary string $S$ as the maximum score among all of its prefixes (for example, the creepiness of $S=$ 01001 is equal to $2$ because the score of the prefix $S[1 \\ldots 4]$ is $2$ and the rest of the prefixes have a score of $2$ or less).\n\nGiven two integers $a$ and $b$, construct a binary string consisting of $a$ zeroes and $b$ ones with the minimum possible creepiness.",
    "tutorial": "Define the minimum possible creepiness of the string as $ans$. We want to show that $ans$ is equal to $max(1, |a - b|)$. Creepiness of $S[1 \\ldots 1]$ is equal to $1$ and creepiness of $S[1 \\ldots n]$ is equal to $|a - b|$ so $max(1, |a - b|) \\le ans$. The way to make a string with creepiness equal to $max(1, |a - b|)$:while $0 < a, b$ holds, add 01 to the end of the string. After that, add the remaining character to the end of the string. Now we know $ans \\le max(1, |a - b|)$. while $0 < a, b$ holds, add 01 to the end of the string. After that, add the remaining character to the end of the string. Now we know $ans \\le max(1, |a - b|)$. So $ans = max(1, |a - b|)$. complexity: $\\mathcal{O}(a + b)$",
    "code": "# include <bits/stdc++.h>\n\nusing namespace std;\n\nint t, A, B;\n\nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\n\tcin >> t;\n\twhile (t --){\n\t\tcin >> A >> B;\n\t\tfor (int i = 0; i < min(A, B); ++ i)\n\t\t\tcout << \"01\";\n\t\tfor (int i = 0; i < abs(A - B); ++ i)\n\t\t\tcout << (A < B ? 1 : 0);\n\t\tcout << '\\n';\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1694",
    "index": "B",
    "title": "Paranoid String",
    "statement": "Let's call a binary string $T$ of length $m$ indexed from $1$ to $m$ \\textbf{paranoid} if we can obtain a string of length $1$ by performing the following two kinds of operations $m-1$ times in any order :\n\n- Select any substring of $T$ that is equal to 01, and then replace it with 1.\n- Select any substring of $T$ that is equal to 10, and then replace it with 0.For example, if $T = $ 001, we can select the substring $[T_2T_3]$ and perform the first operation. So we obtain $T = $ 01.\n\nYou are given a binary string $S$ of length $n$ indexed from $1$ to $n$. Find the number of pairs of integers $(l, r)$ $1 \\le l \\le r \\le n$ such that $S[l \\ldots r]$ (the substring of $S$ from $l$ to $r$) is a \\textbf{paranoid} string.",
    "tutorial": "We want to show that a binary string $T$ of length $m$ is paranoid if and only if $m = 1$ or ($1 < m$ and $S[m] \\neq S[m - 1]$). In the case of $S[m - 1] = S[m]$: We can never delete the last two characters because they will always remain equal. So $S$ is not paranoid. In the case of $S[m - 1] \\neq S[m]$: If $m = 2$, we can reach our goal by one operation. Otherwise assume that the last character is 0. Now the last three characters are either 010 or 110. In the first case perform the operation on $[S_{m-2},S_{m-1}]$ and in the second case perform the operation on $[S_{m-1},S_m]$. Then the last two characters will be 10 and we can continue this algorithm on the new string until we reach $m = 1$. The number of paranoid substrings of length $1$ is equal to $n$. To count the number of longer substrings, we can fix $r$ from index $2$ to $n$. if $S[r] \\neq S[r - 1]$ holds, we should add $r - 1$ to the answer. complexity: $\\mathcal{O}(n)$",
    "code": "# include <bits/stdc++.h>\n\nusing namespace std;\n\nint t, n;\nstring S;\nlong long ans;\n\nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\n\tcin >> t;\n\twhile (t --){\n\t\tcin >> n >> S, ans = n;\n\t\tfor (int i = 1; i < n; ++ i)\n\t\t\tif (S[i] != S[i - 1])\n\t\t\t\tans += i;\n\t\tcout << ans << '\\n';\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1695",
    "index": "A",
    "title": "Subrectangle Guess",
    "statement": "Michael and Joe are playing a game. The game is played on a grid with $n$ rows and $m$ columns, \\textbf{filled with distinct integers}. We denote the square on the $i$-th ($1\\le i\\le n$) row and $j$-th ($1\\le j\\le m$) column by $(i, j)$ and the number there by $a_{ij}$.\n\nMichael starts by saying two numbers $h$ ($1\\le h \\le n$) and $w$ ($1\\le w \\le m$). Then Joe picks any $h\\times w$ subrectangle of the board (without Michael seeing).\n\nFormally, an $h\\times w$ subrectangle starts at some square $(a,b)$ where $1 \\le a \\le n-h+1$ and $1 \\le b \\le m-w+1$. It contains all squares $(i,j)$ for $a \\le i \\le a+h-1$ and $b \\le j \\le b+w-1$.\n\n\\begin{center}\n{\\small Possible move by Joe if Michael says $3\\times 2$ (with maximum of $15$).}\n\\end{center}\n\nFinally, Michael has to guess the maximum number in the subrectangle. He wins if he gets it right.\n\nBecause Michael doesn't like big numbers, he wants the area of the chosen subrectangle (that is, $h \\cdot w$), to be as small as possible, while still ensuring that he wins, not depending on Joe's choice. Help Michael out by finding this minimum possible area.\n\nIt can be shown that Michael can always choose $h, w$ for which he can ensure that he wins.",
    "tutorial": "Note that for any rectangle size, we can always choose an $h$ by $w$ rectangle that contains the maximum element in the grid (which is unique). So in order for Michael to ensure that he can win, he needs to make $h$ and $w$ big enough such that every $h$ by $w$ rectangle contains the maximum element in the grid. Let $(i, j)$ be the position of the maximum (1-indexed). The furthest point in the grid from it has to be one of the four corners, and hxw has to be big enough to include that furthest point and $(i,j)$. So just try all four corners and take the biggest rectangle that gives you. This reduces to $max(i, n - i + 1) \\cdot max(j, m - j + 1)$ (because the dimensions are independent). So the answer is $max(i, n - i + 1) \\cdot max(j, m - j + 1)$. Complexity: $O(nm)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint grid[45][45];\n\nint main() {\n    int num_tests;\n    cin >> num_tests;\n\n    for (int test = 0; test < num_tests; ++test) {\n        int n, m;\n        cin >> n >> m;\n\n        int max_i = 0, max_j = 0;\n        \n        for (int i = 0; i < n; ++i)\n            for (int j = 0; j < m; ++j) {\n                cin >> grid[i][j];\n                if (grid[i][j] > grid[max_i][max_j])\n                    max_i = i, max_j = j;\n            }\n\n        int h = max(max_i+1, n-max_i);\n        int w = max(max_j+1, m-max_j);\n        cout << h * w << '\\n';\n    }\n}\n",
    "tags": [
      "games"
    ],
    "rating": 800
  },
  {
    "contest_id": "1695",
    "index": "B",
    "title": "Circle Game",
    "statement": "Mike and Joe are playing a game with some stones. Specifically, they have $n$ piles of stones of sizes $a_1, a_2, \\ldots, a_n$. These piles are arranged in a circle.\n\nThe game goes as follows. Players take turns removing some positive number of stones from a pile in clockwise order starting from pile $1$. Formally, if a player removed stones from pile $i$ on a turn, the other player removes stones from pile $((i\\bmod n) + 1)$ on the next turn.\n\nIf a player cannot remove any stones on their turn (because the pile is empty), they lose. Mike goes first.\n\nIf Mike and Joe play optimally, who will win?",
    "tutorial": "Note that since all piles are initially nonempty, the game will not end for the first $n$ turns, because on each of those turns, a player will be removing from a nonempty pile. If $n$ is odd, Mike can remove all of the stones from the first pile. Then, on the $n+1$th turn (the first turn where the game can end), Joe will be forced to remove from the first pile, which is empty. So Mike can always win if $n$ is odd. If $n$ is even, then Mike will only ever remove from the odd piles, and Joe will only ever remove from the even piles. So each player has $n/2$ piles, and neither can remove from the other's piles. Therefore, it is optimal for each player to remove the minimal possible number of stones at each step, so that they stay in the game for as long as possible. So on each turn, a player removes exactly one stone, and the first pile to become empty will be the pile with the minimal number of stones. If there are multiple minimal piles, it will be the leftmost such pile. So if this pile is on an odd position, Mike will lose (and therefore Joe will win), and otherwise Joe will lose (and Mike will win). Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int num_tests;\n    cin >> num_tests;\n\n    for (int test = 0; test < num_tests; ++test) {\n\n        int n; cin >> n;\n        vector<int> a(n);\n        for (int i = 0; i < n; ++i)\n            cin >> a[i];\n\n        if (n % 2 == 1) {\n            cout << \"Mike\\n\";\n            continue;\n        }\n\n        int smallest = 0;\n        for (int i = 0; i < n; ++i)\n            if (a[i] < a[smallest])\n                smallest = i;\n\n        if (smallest % 2 == 0) cout << \"Joe\\n\";\n        else cout << \"Mike\\n\";\n    }\n}",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1695",
    "index": "C",
    "title": "Zero Path",
    "statement": "You are given a grid with $n$ rows and $m$ columns. We denote the square on the $i$-th ($1\\le i\\le n$) row and $j$-th ($1\\le j\\le m$) column by $(i, j)$ and the number there by $a_{ij}$. All numbers are equal to $1$ or to $-1$.\n\nYou start from the square $(1, 1)$ and can move one square down or one square to the right at a time. In the end, you want to end up at the square $(n, m)$.\n\nIs it possible to move in such a way so that the sum of the values written in all the visited cells (including $a_{11}$ and $a_{nm}$) is $0$?",
    "tutorial": "Note that if $n+m$ is even, then the sum of any path from the top left to bottom right will be odd, and therefore nonzero. So in this case, there is no solution. Otherwise, every path from top left to bottom right will have even sum. For each position $(i, j)$ in the grid, we define $max_{ij}$ to be the maximum possible sum of a path starting at the top left and ending at $(i, j)$. Similarly, $min_{ij}$ is defined to be the minimum possible sum starting at the top left and ending at $(i, j)$. These values can be computed using an $O(nm)$ DP, where $max_{ij} = a_{ij} + max(max_{(i-1)j}, max_{i(j-1)})$ $min_{ij} = a_{ij} + min(min_{(i-1)j}, min_{i(j-1)})$ Proof: Let $p_1$ be a path from $(1, 1)$ to $(n, m)$ adding up to $min_{nm}$, and $p_2$ be another such path adding up to $max_{nm}$. Each of these paths consists of $n-1$ down moves and $m-1$ right moves, so it can be represented as a string of \"R\" and \"D\" of length $n+m-2$. We can move $p_1$ to $p_2$ by a sequence of operations where we swap two adjacent (and different) characters. Visually, what we are doing is replacing one square on the path with a square diagonally adjacent to it. The below picture shows one possible operation on a path. Note that in each step, the sum of values on the path changes by either $-2, 0,$ or $2$. So after performing this sequence of operations taking $p_1$ to $p_2$, we have moved the path with sum $min_{nm}$ to a path with sum $max_{nm}$, changing the sum by $-2, 0,$ or $2$ at each step. Therefore, because both $min_{nm}$ and $max_{nm}$ are even, and $min_{nm} \\leq 0\\leq max_{nm}$, at some point in this sequence of operations, the sum of the path must be zero. Complexity: $O(nm)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define N 1010\n\nint grid[N][N], mn[N][N], mx[N][N];\n\nint main() {\n    int num_tests;\n    cin >> num_tests;\n\n    for (int test = 0; test < num_tests; ++test) {\n        int n, m;\n        cin >> n >> m;\n        \n        for(int i = 0; i < n; ++i)\n            for(int j = 0; j < m; ++j)\n                cin >> grid[i][j];\n        \n        mn[0][0] = mx[0][0] = grid[0][0];\n        \n        for(int i = 1; i < n; ++i)\n            mx[i][0] = mn[i][0] = mx[i - 1][0] + grid[i][0];\n        \n        for(int j = 1; j < m; ++j)\n            mx[0][j] = mn[0][j] = mx[0][j - 1] + grid[0][j];\n        \n        for(int i = 1; i < n; ++i)\n            for(int j = 1; j < m; ++j) {\n                mx[i][j] = max(mx[i - 1][j], mx[i][j - 1]) + grid[i][j];\n                mn[i][j] = min(mn[i - 1][j], mn[i][j - 1]) + grid[i][j];\n            }\n        \n        if(mx[n - 1][m - 1] % 2 || mn[n - 1][m - 1] > 0 || mx[n - 1][m - 1] < 0)\n            cout << \"NO\\n\";\n        else\n            cout << \"YES\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1695",
    "index": "D1",
    "title": "Tree Queries (Easy Version)",
    "statement": "\\textbf{The only difference between this problem and D2 is the bound on the size of the tree.}\n\nYou are given an unrooted tree with $n$ vertices. There is some hidden vertex $x$ in that tree that you are trying to find.\n\nTo do this, you may ask $k$ queries $v_1, v_2, \\ldots, v_k$ where the $v_i$ are vertices in the tree. After you are finished asking all of the queries, you are given $k$ numbers $d_1, d_2, \\ldots, d_k$, where $d_i$ is the number of edges on the shortest path between $v_i$ and $x$. Note that you know which distance corresponds to which query.\n\nWhat is the minimum $k$ such that there exists some queries $v_1, v_2, \\ldots, v_k$ that let you always uniquely identify $x$ (no matter what $x$ is).\n\nNote that you don't actually need to output these queries.",
    "tutorial": "If $n=1$, then no queries are needed, because there is only one vertex. Otherwise, we need at least one query. If we fix a node $u$, and force it to be a query, we can root the tree at $u$ and do a greedy DFS to compute the answer. Note that because we guarantee that the root is a query, when we are computing the answer for any node $v$ in this DFS, we can assume that either $v$ or some vertex not in the subtree of $v$ has already been queried. We define $ans[v]$ to be the minimal number of queries to distinguish all vertices in the subtree of $v$, given that $v$ or some vertex not in the subtree of $v$ has been queried. Note that for each child $c$ of $v$, we need to be able to distinguish all vertices in the subtree of $c$, so we have $ans[v] \\geq \\sum_c ans[c]$. Additionally, there can be at most one child $c$ of $v$ with no queries in its subtree, otherwise all of these children will be indistinguishable by the queries. If there are $x > 1$ such children of $v$, we can query the first $x-1$ of them, which will be enough to differentiate all vertices in these $x$ subtrees. So, using this definition of $x$, our final formula is $ans[v] = \\sum_c ans[c] + max(0, x - 1)$ For each possible root, we do a DFS to recursively compute these answers. The answer is the minimum $ans[root] + 1$, where the $+1$ is to account for the fact that we are querying the root. Complexity: O(n^2)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define N 2010\n\nvector<int> tree[N];\n\nint dfs(int i, int p) {\n    int sm = 0, z = 0;\n    \n    for (int j : tree[i]) if (j != p) {\n        int x = dfs(j, i);\n        sm += x;\n        if (x == 0)\n            z++;\n    }\n    \n    return sm + max(0, z - 1);\n}\n\nint main() {\n    int num_tests;\n    cin >> num_tests;\n\n    for (int test = 0; test < num_tests; ++test) {\n        int n;\n        cin >> n;\n        \n        for (int i = 1; i < n; ++i) {\n            int u, v;\n            cin >> u >> v;\n            tree[u].push_back(v);\n            tree[v].push_back(u);\n        }\n        \n        if (n == 1)\n            cout << \"0\\n\";\n        else {\n            int ans = n;\n\n            for (int i = 1; i <= n; ++i)\n                ans = min(ans, 1 + dfs(i, i));\n            \n            cout << ans << '\\n';\n        }\n        \n        for (int i = 1; i <= n; ++i)\n            tree[i].clear();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1695",
    "index": "D2",
    "title": "Tree Queries (Hard Version)",
    "statement": "\\textbf{The only difference between this problem and D1 is the bound on the size of the tree.}\n\nYou are given an unrooted tree with $n$ vertices. There is some hidden vertex $x$ in that tree that you are trying to find.\n\nTo do this, you may ask $k$ queries $v_1, v_2, \\ldots, v_k$ where the $v_i$ are vertices in the tree. After you are finished asking all of the queries, you are given $k$ numbers $d_1, d_2, \\ldots, d_k$, where $d_i$ is the number of edges on the shortest path between $v_i$ and $x$. Note that you know which distance corresponds to which query.\n\nWhat is the minimum $k$ such that there exists some queries $v_1, v_2, \\ldots, v_k$ that let you always uniquely identify $x$ (no matter what $x$ is).\n\nNote that you don't actually need to output these queries.",
    "tutorial": "In the previous solution, we forced the root to be a query, because we needed to ensure that for every node $v$, either $v$ was queried, or there was a query outside the subtree of $v$. Notice that if the root has degree $\\geq 3$, regardless of whether we query the root, this property still holds. The way we compute values in the DFS ensures that at least $degree[root]-1 \\geq 2$ subtrees of the root will have at least one query. Therefore, for each other vertex, some vertex outside its subtree must have a query. So the solution is the same as D1, except we root the tree at any vertex of degree $\\geq 3$, and don't query the root itself. If there are no vertices of degree $\\geq 3$, then the tree is a path, and querying either of the endpoints is sufficient, so the answer is 1. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define N 200010\n\nvector<int> tree[N];\n\nint dfs(int i, int p) {\n    int sm = 0, z = 0;\n    \n    for (int j : tree[i]) if (j != p) {\n        int x = dfs(j, i);\n        sm += x;\n        if (x == 0)\n            z++;\n    }\n    \n    return sm + max(0, z - 1);\n}\n\nint main() {\n    int num_tests;\n    cin >> num_tests;\n\n    for (int test = 0; test < num_tests; ++test) {\n        int n;\n        cin >> n;\n        \n        for (int i = 1; i < n; ++i) {\n            int u, v;\n            cin >> u >> v;\n            tree[u].push_back(v);\n            tree[v].push_back(u);\n        }\n\n        int max_deg = 0;\n        for (int i = 1; i <= n; ++i)\n            max_deg = max(max_deg, (int)tree[i].size());\n        \n        if (max_deg == 0)\n            cout << \"0\\n\";\n        else if (max_deg < 3)\n            cout << \"1\\n\";\n        else {\n            for (int i = 1; i <= n; ++i)\n                if (tree[i].size() >= 3) {\n                    cout << dfs(i, i) << '\\n';\n                    break;\n                }\n        }\n        \n        for (int i = 1; i <= n; ++i)\n            tree[i].clear();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1695",
    "index": "E",
    "title": "Ambiguous Dominoes",
    "statement": "Polycarp and Monocarp are both solving the same puzzle with dominoes. They are given the same set of $n$ dominoes, the $i$-th of which contains two numbers $x_i$ and $y_i$. They are also both given the same $m$ by $k$ grid of values $a_{ij}$ such that $m\\cdot k = 2n$.\n\nThe puzzle asks them to place the $n$ dominoes on the grid in such a way that none of them overlap, and the values on each domino match the $a_{ij}$ values that domino covers. Dominoes can be rotated arbitrarily before being placed on the grid, so the domino $(x_i, y_i)$ is equivalent to the domino $(y_i, x_i)$.\n\nThey have both solved the puzzle, and compared their answers, but noticed that not only did their solutions not match, but none of the $n$ dominoes were in the same location in both solutions! Formally, if two squares were covered by the same domino in Polycarp's solution, they were covered by different dominoes in Monocarp's solution. The diagram below shows one potential $a$ grid, along with the two players' solutions.\n\nPolycarp and Monocarp remember the set of dominoes they started with, but they have lost the grid $a$. Help them reconstruct one possible grid $a$, along with both of their solutions, or determine that no such grid exists.",
    "tutorial": "We represent the set of dominoes as a graph on $2n$ vertices, where the vertices are the values $1$ to $2n$, and the ith domino represents an edge between $x_i$ and $y_i$. Note that this graph can contain self-loops and duplicate edges. If any of the connected components of the graph contain only one edge, then that means that there is a domino such that its $x_i$ and $y_i$ values don't appear in any other dominoes. Therefore, this domino must be in the same location in both grids, so there is no solution. Otherwise, iterate over all connected components with $>0$ edges, which must therefore contain $\\geq 2$ edges. For a component with $k$ edges, we will run a DFS that will generate a valid $2$ by $k$ grid for the $k$ dominoes in this component. As we go through this DFS, we keep track of which vertices and which edges we've already seen. When we DFS from a vertex $u$ we haven't seen, mark it as seen, and iterate over all edges adjacent to $u$ that we haven't seen. Mark each one as seen, and then traverse it to the other vertex $v$, marking $u$ as its parent. Once we backtrack to $u$, continue to the next unseen edge. Once all unseen edges are traversed, traverse back to the parent of $u$. When we visit a vertex $u$ we have already seen, just traverse the edge back to its parent. Throughout this process, maintain a list of all vertices we've seen in order, including any duplicates. Because we traverse every edge exactly twice (once in each direction) in this DFS, this list will be of size $2k+1$, and every two adjacent vertices in the list are connected by an edge. Each edge will be represented in two positions in this list. We can additionally prove that within this list, each edge appears in one even position and one odd position. Proof: Let $uv$ be an edge that we initially traverse from $u$ to $v$. If $v$ has already been traversed by this point in the DFS, we immediately traverse back to $u$, so the two positions of $uv$ are adjacent in the list, and thus on different parity positions. If not, consider the final sequence of edges traversed, but removing any edges that are immediately traversed backwards. Note that since we are only removing pairs of adjacent edges, the parities of positions of edges in the list are unchanged. Now, the sequence of edges is just a DFS traversal of a tree. So because the graph is now a tree, and thus bipartite, any path from $v$ to itself must be of even length. Therefore, the sequence of moves looks like $(..., uv,$ [an even number of edges], $vu, ...)$ and therefore the two occurrences of $uv$ must be on different parities. Now, to generate the $2$ by $k$ grid that works for this component, we note that the list of size $2k+1$ can be seen as a cyclic list of size $2k$, because the first and last element of the list must be equal. So we pop the last element of the list off, and insert the remaining vertices of the list into a $2$ by $k$ grid in clockwise order. Now, the edges form a cycle of length $2k$, and because each edge appears on one odd and one even position, each domino will appear exactly once in both of the below orientations. Each of these orientations takes the dominoes going around the cycle in order. To get the solution for the whole problem, simply concatenate the $2$ by $k$ grids for each component into a $2$ by $n$ grid. The below example demonstrates the whole process. The blue edges are the edges to previously-seen vertices, and the red edges are the edges to previously-unseen vertices. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define N 600010\n\nvector<pair<int, int>> graph[N];\nvector<int> lst;\n\nint ans[2][N];\n\nbool used[N], usedEdges[N];\n\nvoid dfs(int i) {\n    lst.push_back(i);\n\n    if (!used[i]) {\n        used[i] = true;\n        \n        for (pair<int, int> p : graph[i])\n            if (!usedEdges[p.second]) {\n                usedEdges[p.second] = true;\n                dfs(p.first);\n                lst.push_back(i);\n            }\n    }\n}\n\nint main() {\n\n    int n; cin >> n;\n    string ptop(n, 'U'), pbot(n, 'D');\n    string mtop(n, 'U'), mbot(n, 'D');\n\n    for (int i = 0; i < n; ++i) {\n        int u, v;\n        cin >> u >> v;\n        graph[u].emplace_back(v, i);\n        graph[v].emplace_back(u, i);\n    }\n\n    int idx = 0;\n    for (int i = 1; i <= 2 * n; ++i) if (!used[i]) {\n\n        dfs(i);\n        lst.pop_back();\n        int k = lst.size() / 2;\n        \n        if (k == 1) {\n            cout << \"-1\\n\";\n            exit(0);\n        }\n\n        for (int j = 0; j < k; ++j) {\n            ans[0][j + idx] = lst[j];\n            ans[1][j + idx] = lst[2 * k - 1 - j];\n        }\n\n        for (int j = 0; j < k - 1; j += 2)\n            ptop[j + idx] = pbot[j + idx] = 'L', ptop[j + 1 + idx] = pbot[j + 1 + idx] = 'R';\n        for (int j = 1; j < k - 1; j += 2)\n            mtop[j + idx] = mbot[j + idx] = 'L', mtop[j + 1 + idx] = mbot[j + 1 + idx] = 'R';\n        lst.clear();\n\n        idx += k;\n    }\n\n    cout << \"2 \" << n << '\\n';\n    \n    for (int i = 0; i < 2; ++i) {\n        for (int j = 0; j < n; ++j)\n            cout << ans[i][j] << ' ';\n        cout << '\\n';\n    }\n\n    cout << ptop << '\\n' << pbot << '\\n';\n    cout << mtop << '\\n' << mbot << '\\n';\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1696",
    "index": "A",
    "title": "NIT orz!",
    "statement": "NIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to $\\operatorname{or} z$. Can you solve this problem too?\n\nYou are given a 1-indexed array of $n$ integers, $a$, and an integer $z$. You can do the following operation any number (possibly zero) of times:\n\n- Select a positive integer $i$ such that $1\\le i\\le n$. Then, \\textbf{simutaneously} set $a_i$ to $(a_i\\operatorname{or} z)$ and set $z$ to $(a_i\\operatorname{and} z)$. In other words, let $x$ and $y$ respectively be the current values of $a_i$ and $z$. Then set $a_i$ to $(x\\operatorname{or}y)$ and set $z$ to $(x\\operatorname{and}y)$.\n\nHere $\\operatorname{or}$ and $\\operatorname{and}$ denote the bitwise operations OR and AND respectively.\n\nFind the maximum possible value of the maximum value in $a$ after any number (possibly zero) of operations.",
    "tutorial": "How many operations will we perform? At most one. Why? Suppose we can only perform exactly one operation. In this case the answer is $S=\\max_{1\\le i\\le n}(a_i\\mathrm{\\ or\\ }z)$. In fact, we can prove that this is the answer. Define $a_i'$ as the value of $a_i$ after some operations. It suffices to prove the answer will never exceed $S$. Note that $z$ will always become a submask of itself after any number of operations, so $a_i$ will always be a submask of $(a_i\\mathrm{\\ or\\ }z)$ after any number of operations. This leads to the conclusion that $a_i'\\le (a_i\\mathrm{\\ or\\ }z)$ for all $i$. Thus $\\max_{1\\le i\\le n} a_i'\\le \\max_{1\\le i\\le n}(a_i\\mathrm{\\ or\\ }z)=S$. Time complexity is $O(n)$.",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1696",
    "index": "B",
    "title": "NIT Destroys the Universe",
    "statement": "For a collection of integers $S$, define $\\operatorname{mex}(S)$ as the smallest non-negative integer that does not appear in $S$.\n\nNIT, the cleaver, decides to destroy the universe. He is not so powerful as Thanos, so he can only destroy the universe by snapping his fingers several times.\n\nThe universe can be represented as a 1-indexed array $a$ of length $n$. When NIT snaps his fingers, he does the following operation on the array:\n\n- He selects positive integers $l$ and $r$ such that $1\\le l\\le r\\le n$. Let $w=\\operatorname{mex}(\\{a_l,a_{l+1},\\dots,a_r\\})$. Then, for all $l\\le i\\le r$, set $a_i$ to $w$.\n\nWe say the universe is destroyed if and only if for all $1\\le i\\le n$, $a_i=0$ holds.\n\nFind the minimum number of times NIT needs to snap his fingers to destroy the universe. That is, find the minimum number of operations NIT needs to perform to make all elements in the array equal to $0$.",
    "tutorial": "How many operations will we perform? At most two. Why? How to check if the array can be destroyed in $0$ or $1$ operations? The answer is at most $2$, because doing the operation on $[1,n]$ at most twice will always work. (If the array contains at least one zero, we need $2$ operations. Otherwise we need $1$ operation.) If the array consists of zeroes, the answer is $0$. If all non-zero elements form a contiguous segment in the array, the answer is $1$. To check this, you can find the leftmost and rightmost occurrence of non-zero elements and check if elements in the middle of them are also non-zero. Otherwise the answer is $2$. Time complexity is $O(n)$.",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1696",
    "index": "C",
    "title": "Fishingprince Plays With Array",
    "statement": "Fishingprince is playing with an array $[a_1,a_2,\\dots,a_n]$. He also has a magic number $m$.\n\nHe can do the following two operations on it:\n\n- Select $1\\le i\\le n$ such that $a_i$ is divisible by $m$ (that is, there exists an integer $t$ such that $m \\cdot t = a_i$). Replace $a_i$ with \\textbf{$m$ copies} of $\\frac{a_i}{m}$. The order of the other elements doesn't change. For example, when $m=2$ and $a=[2,3]$ and $i=1$, $a$ changes into $[1,1,3]$.\n- Select $1\\le i\\le n-m+1$ such that $a_i=a_{i+1}=\\dots=a_{i+m-1}$. Replace these $m$ elements with \\textbf{a single} $m \\cdot a_i$. The order of the other elements doesn't change. For example, when $m=2$ and $a=[3,2,2,3]$ and $i=2$, $a$ changes into $[3,4,3]$.\n\nNote that the array length might change during the process. The value of $n$ above is defined as the current length of the array (might differ from the $n$ in the input).\n\nFishingprince has another array $[b_1,b_2,\\dots,b_k]$. Please determine if he can turn $a$ into $b$ using any number (possibly zero) of operations.",
    "tutorial": "The operation is reversible. (The two operations are reverses of each other.) Try to find a middle state, such that we can turn both $a$ and $b$ into it. Call the first operation \"expand\" and the second operation \"shrink\". Keep doing expand on both arrays until we can't do expand anymore, call the resulting arrays $a'$ and $b'$. It suffices to check if $a'=b'$. To implement this, you need to compress contiguous equal numbers. Proof of why this is necessary and sufficient: Sufficiency is obvious, since the operations are reversible. We can do something like $a\\to a'=b'\\to b$. Sufficiency is obvious, since the operations are reversible. We can do something like $a\\to a'=b'\\to b$. Necessity: Let $f(a)=a'$. It suffices to prove that an operation on $a$ does not affect $f(a)$. An expand operation obviously doesn't affect $f(a)$. A shrink operation shrinks $a[i,i+m-1]$ into one element. When computing $f(a')$, we will always expand $a'_i$ at some time, so the result is the same as $f(a)$. Necessity: Let $f(a)=a'$. It suffices to prove that an operation on $a$ does not affect $f(a)$. An expand operation obviously doesn't affect $f(a)$. A shrink operation shrinks $a[i,i+m-1]$ into one element. When computing $f(a')$, we will always expand $a'_i$ at some time, so the result is the same as $f(a)$. Time complexity is $O((n+k)\\log_m V)$, where $V=\\max a_i$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1696",
    "index": "D",
    "title": "Permutation Graph",
    "statement": "A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nYou are given a permutation of $1,2,\\dots,n$, $[a_1,a_2,\\dots,a_n]$. For integers $i$, $j$ such that $1\\le i<j\\le n$, define $\\operatorname{mn}(i,j)$ as $\\min\\limits_{k=i}^j a_k$, and define $\\operatorname{mx}(i,j)$ as $\\max\\limits_{k=i}^j a_k$.\n\nLet us build an undirected graph of $n$ vertices, numbered $1$ to $n$. For every pair of integers $1\\le i<j\\le n$, if $\\operatorname{mn}(i,j)=a_i$ and $\\operatorname{mx}(i,j)=a_j$ both holds, or $\\operatorname{mn}(i,j)=a_j$ and $\\operatorname{mx}(i,j)=a_i$ both holds, add an undirected edge of length $1$ between vertices $i$ and $j$.\n\nIn this graph, find the length of the shortest path from vertex $1$ to vertex $n$. We can prove that $1$ and $n$ will always be connected via some path, so a shortest path always exists.",
    "tutorial": "This problem has two different solutions. The first one is more beautiful, but less straight-forward. The solution is $O(n)$. We don't need any data structures. Instead of trying to construct the shortest path from $1$ to $n$, find a \"transfer vertex\" that we must pass through. We will always pass through the position of the maximum element in the array. Suppose the maximum element is $a_k$. Solve recursively for $dis(1,k)$ and $dis(k,n)$. Denote $dis(x,y)$ as the length of the shortest path between $x$ and $y$. Consider a position $i$ that $a_i=n$. Assume $i\\ne 1$ and $i\\ne n$. For a segment that passes $i$, its maximum element is always $a_i$. Thus, for $x<i<y$, $x$ and $y$ will never be directly connected by an edge. This means that when going from $1$ to $n$, we have to pass $i$. Let us solve recursively for $dis(1,i)$ and $dis(i,n)$. For example, we solve for $dis(1,i)$. We already know that $a_i=n$, so $i$ is the maximum element in $[1,i]$. Consider the minimum element in $[1,i]$, suppose it is $a_j\\ (j<i)$. From similar arguments, we can solve recursively for $dis(1,j)$ and $dis(j,i)$. However, note that $dis(j,i)$ equals to $1$: since $j$ and $i$ are respectively minimum and maximum in $[1,i]$, they have to be minimum and maximum in $[j,i]$ as well. So $i,j$ must be directly connected. Thus, we only need to solve recursively for $dis(1,j)$. The process with $dis(i,n)$ is similar. Note that we will only call $dis(l,r)$ for $l=1$ or $r=n$ (if not, the return value is always 1), so it suffices to pre-compute prefix and suffix minimums and maximums. The time complexity is $O(n)$. Look at the last sample test case. Think of a simple greedy. Keep going to the rightmost vertex (the vertex with the largest id) works. Use data structures to simulate the process. How? We can prove that keep going to the vertex with the largest index is a correct strategy. The proof is left as an exercise :) Hint: try to prove that the path we will visit is the same as the path we visited in solution 1. Suppose we are at $i$. We want to find the largest $j>i$ such that $i$ and $j$ are directly connected. WLOG, assume $a_{i+1}<a_i$. Then, it cannot be the case that $a_j>a_i$, since none of $a_i,a_j$ will be $mn(i,j)$. Thus $a_j<a_i$. It follows that all $i<k<j$ satisfies $a_k<a_i$, otherwise none of $a_i,a_j$ will be $mx(i,j)$. Let $r_i$ be the largest $p$, such that for all $t\\in [i+1,p]$, $a_t<a_i$. From the arguments above we know $j\\in [i+1,r_i]$. $r_i$ can be pre-computed with a stack, or binary search + some data structures. Let $j_0$ be the position of the minimum element in $[i+1,r_i]$. Obviously $j_0$ is directly connected with $i$. For any $j_0<k\\le r_i$, $mn(i,k)$ will be $a_{j_0}$, showing that all such $k$ is not directly connected with $i$. Thus, $j_0$ is the desired $j$. If we use data structures for range minimum, we get a $O(n\\log n)$ solution, which can easily pass (not sure whether $O(n\\log^2 n)$ ones will pass though, the large constraints were intended to cut those). However, by building the cartesian tree of the array and doing proper pre-computations, we can optimize this solution to $O(n)$.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "greedy",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1696",
    "index": "E",
    "title": "Placing Jinas",
    "statement": "We say an infinite sequence $a_{0}, a_{1}, a_2, \\ldots$ is \\textbf{non-increasing} if and only if for all $i\\ge 0$, $a_i \\ge a_{i+1}$.\n\nThere is an infinite right and down grid. The upper-left cell has coordinates $(0,0)$. Rows are numbered $0$ to infinity from top to bottom, columns are numbered from $0$ to infinity from left to right.\n\nThere is also a \\textbf{non-increasing} infinite sequence $a_{0}, a_{1}, a_2, \\ldots$. You are given $a_0$, $a_1$, $\\ldots$, $a_n$; for all $i>n$, $a_i=0$. For every pair of $x$, $y$, the cell with coordinates $(x,y)$ (which is located at the intersection of $x$-th row and $y$-th column) is white if $y<a_x$ and black otherwise.\n\nInitially there is one doll named Jina on $(0,0)$. You can do the following operation.\n\n- Select one doll on $(x,y)$. Remove it and place a doll on $(x,y+1)$ and place a doll on $(x+1,y)$.\n\nNote that multiple dolls can be present at a cell at the same time; in one operation, you remove only one. Your goal is to make all white cells contain $0$ dolls.\n\nWhat's the minimum number of operations needed to achieve the goal? Print the answer modulo $10^9+7$.",
    "tutorial": "Try to find out the number of operations we do on a specific cell $(i,j)$, call it $f(i,j)$. Write the recurrence formula for $f(i,j)$. What is $f(i,j)$? $f(i,j)=\\binom{i+j}j$ The answer is the sum of $f(i,j)$ over all white cells $(i,j)$. Use some combinatorics formula to speed it up. Let us find out the number of operations we do on a specific cell $(i,j)$, call it $f(i,j)$. Every operation done on $(i-1,j)$ will lead to one doll on $(i,j)$, thus consuming one operation on $(i,j)$. Similar observation holds for $(i,j-1)$. Thus, $f(i,j)=f(i,j-1)+f(i-1,j)$ (given that $(i,j),(i-1,j),(i,j-1)$ are all white cells). Note that $a$ is non-increasing: this means that if $(i,j)$ is white, $(i-1,j),(i,j-1)$ will both be white. So we can conclude that $f(i,j)=f(i,j-1)+f(i-1,j)$ always holds as long as $(i,j)$ is white. Another way to see the formula is $f(i,j)$ is the number of ways to go from $(0,0)$ to $(i,j)$, only going down or right by 1 step. This implies that $f(i,j)=\\binom{i+j}j$. From this, we know that the answer is $\\sum_{i=0}^n\\sum_{j=0}^{a_i-1} \\binom{i+j}{i}$. With the equation $\\sum_{i=0}^k\\binom{n+i}n=\\binom{n+k+1}{n+1}$, we know that the answer is $\\sum_{i=0}^n\\binom{i+a_i}{i+1}$. The time complexity is $O(n+V)$, where $V=\\max a_i$.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1696",
    "index": "F",
    "title": "Tree Recovery",
    "statement": "Fishingprince loves trees. A tree is a connected undirected graph without cycles.\n\nFishingprince has a tree of $n$ vertices. The vertices are numbered $1$ through $n$. Let $d(x,y)$ denote the shortest distance on the tree from vertex $x$ to vertex $y$, assuming that the length of each edge is $1$.\n\nHowever, the tree was lost in an accident. Fortunately, Fishingprince still remembers some information about the tree. More specifically, for every triple of integers $x,y,z$ ($1\\le x<y\\le n$, $1\\le z\\le n$) he remembers whether $d(x,z)=d(y,z)$ or not.\n\nHelp him recover the structure of the tree, or report that no tree satisfying the constraints exists.",
    "tutorial": "The solution does not contain painful casework and deadly implemention. Suppose we aleady know edge $(i,j)$ exists in the tree. What can we know from it? We can immediately recover the whole tree. Read the hints first to understand the solution better. Construct a graph with $\\binom n2$ vertices $(1,2),(1,3),\\dots,(n-1,n)$. If $dis(a,b)=dis(b,c)$, link an undirected edge between $(a,b)$ and $(b,c)$. Observe that all edges in the tree form a connected component of size exactly $n-1$ in the graph! Find all components of size $n-1$ and try if all vertices in it form a tree that satisfy the input. There are at most $\\dfrac n2$ such components, so complexity is $O(n^4)$. Proper pre-computation and the usage of bitsets can reduce the complexity to $O(n^4/w)$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1696",
    "index": "G",
    "title": "Fishingprince Plays With Array Again",
    "statement": "Suppose you are given a 1-indexed sequence $a$ of non-negative integers, whose length is $n$, and two integers $x$, $y$. In consecutive $t$ seconds ($t$ can be any positive real number), you can do one of the following operations:\n\n- Select $1\\le i<n$, decrease $a_i$ by $x\\cdot t$, and decrease $a_{i+1}$ by $y\\cdot t$.\n- Select $1\\le i<n$, decrease $a_i$ by $y\\cdot t$, and decrease $a_{i+1}$ by $x\\cdot t$.\n\nDefine the minimum amount of time (it might be a real number) required to make all elements in the sequence less than or equal to $0$ as $f(a)$.\n\nFor example, when $x=1$, $y=2$, it takes $3$ seconds to deal with the array $[3,1,1,3]$. We can:\n\n- In the first $1.5$ seconds do the second operation with $i=1$.\n- In the next $1.5$ seconds do the first operation with $i=3$.\n\nWe can prove that it's not possible to make all elements less than or equal to $0$ in less than $3$ seconds, so $f([3,1,1,3])=3$.\n\nNow you are given a 1-indexed sequence $b$ of positive integers, whose length is $n$. You are also given positive integers $x$, $y$. Process $q$ queries of the following two types:\n\n- 1 k v: change $b_k$ to $v$.\n- 2 l r: print $f([b_l,b_{l+1},\\dots,b_r])$.",
    "tutorial": "What kind of problem is this problem? Linear programming. Consider the dual. Consider the case when $n=2$. Draw the linear programming on a xOy-coordinate. Try to observe what the answer might be. First we solve the problem with only 1 query on the whole array $A$. This is a linear programming problem: $\\text{minimize}\\sum_{1\\le i<n} a_i+b_i \\\\ Xa_1+Yb_1\\ge A_1 \\\\ Xa_i+Yb_i+Ya_{i-1}+Xb_{i-1}\\ge A_i\\ (2\\le i<n) \\\\ Ya_{n-1}+Xb_{n-1}\\ge A_n \\\\ a_i,b_i\\ge 0$ Consider its dual: $\\text{maximize}\\sum_{1\\le i\\le n}A_ix_i \\\\ Xx_i+Yx_{i+1}\\le 1\\ (1\\le x<n) \\\\ Yx_i+Xx_{i+1}\\le 1\\ (1\\le x<n) \\\\ x_i\\ge 0$ Suppose $X\\le Y$. Now we will prove that there exists an optimal solution to the dual problem, in which $x_i$ can only take three values: $1/Y,1/(X+Y),0$. The proof is as follows: It is well-known that an optimal solution to a linear programming problem must lie on a vertex of the \"multi-dimensional convex polygon\" which the restrictions surround. Thus we are only interested in $x_i$ that satisfy several \"=\" restrictions (and the restrictions should really intersect at one point, meaning that those \"=\" should uniquely determine $x$). Consider any \"sufficient\" (that means they uniquely determine ${x}$) subset of them. If one restriction is related to $x_p,x_q$, we link an undirected edge between $p$ and $q$. If one restriction is only related to $x_p$ (i.e. $x_p=0$), we link a self-loop on $p$. \"Being sufficient\" means that all connected components in the graph has exactly one cycle. However, for an edge $(u,v)$, we know that either $u=v+1$ or $u=v$. This means that all cycles can only be $(i\\to i+1\\to i)$ or $i\\to i$. If a cycle is $(i\\to i+1\\to i)$, all $x_i$ in the component are $1/(X+Y)$; If a cycle is $i\\to i$, all $x_i$ in the component are $1/Y$ or $0$ (not $1/X$, because it exceeds the constraints). Thus we can use dp to solve the dual problem. Let $dp(i,0/1/2)$ be the maximum $\\sum_{j\\le i}A_jx_j$ when $x_i$ is the $0/1/2$-th candidate above. Transitions are straight-forward. For multiple queries, the transitions can be written into multiplying matrices, and we can use segment tree to maintain updates. About precision issues: actually we can avoid using floating point numbers completely. Note that all numbers in this problem are fractions with denominator $Y(X+Y)$. Also note that the answer does not exceed $(\\sum a_i)/Y$. This means that the numerator does not exceed $(\\sum a_i)\\times (X+Y)<10^{18}$, so we can use long long-s to only store numerators. If you use double in C++, the relative error of one operation is less than $10^{-15}$. $10^{-15}\\times n<10^{-9}$, which means that using doubles is also enough. Complexity: $O(n+q\\log n)$.",
    "tags": [
      "brute force",
      "data structures",
      "geometry",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1696",
    "index": "H",
    "title": "Maximum Product?",
    "statement": "You are given a positive integer $k$. For a multiset of integers $S$, define $f(S)$ as the following.\n\n- If the number of elements in $S$ is less than $k$, $f(S)=0$.\n- Otherwise, define $f(S)$ as the maximum product you can get by choosing exactly $k$ integers from $S$.\n\nMore formally, let $|S|$ denote the number of elements in $S$. Then,\n\n- If $|S|<k$, $f(S)=0$.\n- Otherwise, $f(S)=\\max\\limits_{T\\subseteq S,|T|=k}\\left(\\prod\\limits_{i\\in T}i\\right)$.\n\nYou are given a multiset of integers, $A$. Compute $\\sum\\limits_{B\\subseteq A} f(B)$ modulo $10^9+7$.\n\nNote that in this problem, \\textbf{we distinguish the elements by indices instead of values}. That is, a multiset consisting of $n$ elements always has $2^n$ distinct subsets regardless of whether some of its elements are equal.",
    "tutorial": "Find a way to calculate the maximum product that can be turned into counting. Use monotonicity to reduce the complexity. First, we describe a strategy to find the answer for a single subset. If the whole subset is negative, the answer is the product of the $K$ maximum numbers in it. Otherwise, take $K$ numbers with the maximum absolute value. If there is an even number of negative numbers in those numbers, we're done. Otherwise, find the smallest positive element and change it to the absolute-value-maximum negative element unchosen, or find the largest negative element and change it to the maximum positive element unchosen. We either do the first change or do the second change. This gives a direct dp solution. Take all $a_i$ and sort them into two arrays consisting of positive and negative ones (0 goes to arbitary one), $pos$ and $neg$, sorted by absolute values. By calculating $fpos(i,k)$: the sum of the product of the largest $K$ numbers of all subsets of $pos[1\\dots i]$ that contain $pos_i$, and $fneg(i,k)$ similarly, and $gneg(i,k)$, the sum of the product of the absolute value smallest $K$ numbers of all subsets of $neg[i\\dots |neg|]$ that contain $neg_i$, and enumerating the following, we can solve the original problem in $O(n^5)$: the number of positive elements in the $K$ numbers with the maximum absolute value in our calculating subset, $p$. the smallest positive element in the $K$ numbers with the maximum absolute value, $pos_i$. the greatest negative element in the $K$ numbers with the maximum absolute value, $neg_j$. (if $p$ is odd) the greatest positive element not in the $K$ numbers with the maximum absolute value, $pos_k$. (if $p$ is odd) the smallest negative element not in the $K$ numbers with the maximum absolute value, $pos_l$. The contribution to the answer can be represented as the sum of product of $fpos,fneg$, and powers of two. I left the details as an exercise. However, notice that the \"enumerating $k,l$\" part has nothing to do with $p$, so we can pre-calculate the contribution of $k,l$ for every pair $(i,j)$, giving an $O(n^4)$ algorithm. What's more, for fixed $i,j,k$, the $l$-s that we do the first change is a prefix/suffix of all $l$, and $l$-s that we do the second change is a prefix/suffix of all $l$. So with two pointers and prefix sums, we can pre-calculate the contribution of every $(i,j)$ in $O(n^3)$, which is fast enough. You might be afraid that $600^3$ is too slow for 1.5 seconds. However, the two $O(n^3)$ parts of the algorithm actually run in $O(n\\times cntpos\\times cntneg)$ ($cntpos,cntneg$ are the number of positive/negative integers in the array), leading to an at most $1/4$ constant factor. Thus, the algorithm actually runs very fast (less than 0.25 seconds). However for similar constant factor reasons, the $O(n^4)$ solution only takes about 6.5 seconds on Codeforces, so we had to set a seemingly-tight limit.",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "greedy",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1697",
    "index": "A",
    "title": "Parkway Walk",
    "statement": "You are walking through a parkway near your house. The parkway has $n+1$ benches in a row numbered from $1$ to $n+1$ from left to right. The distance between the bench $i$ and $i+1$ is $a_i$ meters.\n\nInitially, you have $m$ units of energy. To walk $1$ meter of distance, you spend $1$ unit of your energy. You can't walk if you have no energy. Also, you can restore your energy by \\textbf{sitting on benches} (and this is the only way to restore the energy). When you are sitting, you can restore any integer amount of energy you want (if you sit longer, you restore more energy). Note that the amount of your energy \\textbf{can exceed} $m$.\n\nYour task is to find the \\textbf{minimum} amount of energy you have to \\textbf{restore} (by sitting on benches) to reach the bench $n+1$ from the bench $1$ (and end your walk).\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If you have at least $sum(a_i)$ units of energy, then the answer is $0$, because you can just walk to the end. Otherwise, the answer is $sum(a_i) - m$, because you can just sit on the first bench and then just go. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", H\"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int tc;\n    cin >> tc;\n    while (tc--) {\n        int n, m;\n        cin >> n >> m;\n        int sum = 0;\n        for (int i = 0; i < n; ++i) {\n            int x;\n            cin >> x;\n            sum += x;\n        }\n        cout << max(0, sum - m) << endl;\n    }\n    \n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1697",
    "index": "B",
    "title": "Promo",
    "statement": "The store sells $n$ items, the price of the $i$-th item is $p_i$. The store's management is going to hold a promotion: if a customer purchases at least $x$ items, $y$ cheapest of them are free.\n\nThe management has not yet decided on the exact values of $x$ and $y$. Therefore, they ask you to process $q$ queries: for the given values of $x$ and $y$, determine the maximum total value of items received for free, if a customer makes \\textbf{one purchase}.\n\nNote that all queries are independent; they don't affect the store's stock.",
    "tutorial": "First of all, there is an answer with exactly $x$ items bought. Suppose items worth $p_1 \\le p_2 \\le\\dots \\le p_m$ ($x < m$) were purchased. Then by removing $p_1$ from this set, the sum of $y$ the cheapest items in the set will change by $p_{y+1}-p_1\\ge 0$, which means the answer will not decrease. The second fact that is necessary to solve the problem - $x$ of the most expensive items should be chosen. Otherwise, one can remove the minimum price item from the set and add an item with a higher price (it can always be found), which means the answer will not decrease. Using these two facts, it is enough to sort the array and use prefix sums.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int n, q;\n  cin >> n >> q;\n  vector<long long> p(n), s(n + 1);\n  for (auto& x : p) cin >> x;\n  sort(p.begin(), p.end());\n  for (int i = 0; i < n; ++i) s[i + 1] = s[i] + p[i];\n  while (q--) {\n    int x, y;\n    cin >> x >> y;\n    cout << s[n - x + y] - s[n - x] << '\\n';\n  }\n} ",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1697",
    "index": "C",
    "title": "awoo's Favorite Problem",
    "statement": "You are given two strings $s$ and $t$, both of length $n$. Each character in both string is 'a', 'b' or 'c'.\n\nIn one move, you can perform one of the following actions:\n\n- choose an occurrence of \"ab\" in $s$ and replace it with \"ba\";\n- choose an occurrence of \"bc\" in $s$ and replace it with \"cb\".\n\nYou are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string $s$ to make it equal to string $t$?",
    "tutorial": "First, check that the counts of all letters are the same in both strings. Then consider the following restatement of the moves. The letters 'b' in the string $s$ are stationary. Letters 'a' and 'c', however, move around the string. The move of the first type moves a letter 'a' to the right. The move of the second type moves a letter 'c' to the left. Notice that letters 'a' and 'c' can never swap with each other. Thus, if you remove all letters 'b' from both strings, the remaining strings should be the same. Again, since letters 'a' and 'c' can never swap with each other, you can deduce where each of these letters should end up after the swaps. The first letter '{a}' in $s$ should be on the position of the first letter 'a' in $t$ and so on. After that, we recall that 'a's can only move to the right and 'c's can only move to the left. Thus, we check that the $i$-th occurrence of 'a' in $s$ is to the left or equal to the $i$-th occurrences of 'a' in $t$ and vice versa for 'c's. Finally, we can see that this is a sufficient condition. Easy to show by construction: you can just fix the positions one after another left to right. Overall complexity: $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ts = input()\n\tt = input()\n\tif s.count('b') != t.count('b'):\n\t\tprint(\"NO\")\n\t\tcontinue\n\tj = 0\n\tfor i in range(n):\n\t\tif s[i] == 'b':\n\t\t\tcontinue\n\t\twhile t[j] == 'b':\n\t\t\tj += 1\n\t\tif s[i] != t[j] or (s[i] == 'a' and i > j) or (s[i] == 'c' and i < j):\n\t\t\tprint(\"NO\")\n\t\t\tbreak\n\t\tj += 1\n\telse:\n\t\tprint(\"YES\")",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "strings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1697",
    "index": "D",
    "title": "Guess The String",
    "statement": "\\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.\n\nThe jury has chosen a string $s$ consisting of $n$ characters; each character of $s$ is a lowercase Latin letter. Your task is to guess this string; initially, you know only its length.\n\nYou may ask queries of two types:\n\n- $1$ $i$ — the query of the first type, where $i$ is an integer from $1$ to $n$. In response to this query, the jury will tell you the character $s_i$;\n- $2$ $l$ $r$ — the query of the second type, where $l$ and $r$ are integers such that $1 \\le l \\le r \\le n$. In response to this query, the jury will tell you the number of different characters among $s_l, s_{l+1}, \\dots, s_r$.\n\nYou are allowed to ask no more than $26$ queries of the first type, and no more than $6000$ queries of the second type. Your task is to restore the string $s$.\n\nFor each test in this problem, the string $s$ is fixed beforehand, and will be the same for every submission.",
    "tutorial": "There are several ways to solve this problem. The model solution does it as follows: Restore the characters of $s$ from left to right. The first character is restored by query ? 1 1. For each of the next characters, let's ask if this character is new (by querying ? 2 1 i and comparing the result with the number of different characters on the segment $[1, i-1]$). If it's new, ask ? 1 i to obtain the $i$-th character (there will be at most $26$ such queries). Otherwise, we can find the previous occurrence of the $i$-th character with binary search. Let $f(x,y)$ be the number of different characters from position $x$ to position $y$. If we want to find the previous occurrence of the $i$-th character, we need to find the last index $j$ such that $f(j,i) = f(j,i-1)$. Since the value $f(j,i) - f(j,i-1)$ does not decrease when we increase $j$, we can find the last $j$ such that $f(j,i) - f(j,i-1) = 0$, with binary search. Unfortunately, the number of queries of type $2$ will be too large if we just use binary search over the whole segment $[1,i-1]$. To decrease the number of queries, we can use the fact that the value of $j$ we are interested in is the last occurrence of some character we already met; there are at most $26$ such values, and binary search among them will need only $5$ iterations.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nchar ask_character(int i)\n{\n    cout << \"? 1 \" << i << endl;\n    cout.flush();\n    string s;\n    cin >> s;\n    return s[0];\n}\n\nint ask_cnt(int l, int r)\n{\n    cout << \"? 2 \" << l << \" \" << r << endl;\n    cout.flush();\n    int x;\n    cin >> x;\n    return x;\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n    string s = \"\";\n    vector<vector<int>> cnt(n + 1);\n    for(int i = 0; i < n; i++)\n    {\n        if(i == 0)\n        {\n            s.push_back(ask_character(1));\n            cnt[0] = {1};\n        }\n        else\n        {\n             int cur = ask_cnt(1, i + 1);\n             if(cur > cnt[i - 1][0])\n                s.push_back(ask_character(i + 1));\n             else\n             {\n                map<char, int> last;\n                for(int j = 0; j < s.size(); j++)\n                    last[s[j]] = j;\n                vector<int> lasts;\n                for(auto x : last) lasts.push_back(x.second);\n                sort(lasts.begin(), lasts.end());\n                int l = 0;\n                int r = lasts.size();\n                // there is always an occurrence in [lasts[l], i)\n                // there is no occurrence in [lasts[r], i)\n                while(r - l > 1)\n                {\n                    int m = (l + r) / 2;\n                    int c = ask_cnt(lasts[m] + 1, i + 1);\n                    if (c == cnt[i - 1][lasts[m]])\n                        l = m;\n                    else\n                        r = m;\n                }   \n                s.push_back(s[lasts[l]]);                                                \n             }\n             cnt[i].resize(i + 1);\n             set<char> q;\n             for(int j = i; j >= 0; j--)\n             {\n                q.insert(s[j]);\n                cnt[i][j] = q.size();\n             }\n        }\n    }\n    cout << \"! \" << s << endl;\n    cout.flush();\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1697",
    "index": "E",
    "title": "Coloring",
    "statement": "You are given $n$ points on the plane, the coordinates of the $i$-th point are $(x_i, y_i)$. No two points have the same coordinates.\n\nThe distance between points $i$ and $j$ is defined as $d(i,j) = |x_i - x_j| + |y_i - y_j|$.\n\nFor each point, you have to choose a color, represented by an integer from $1$ to $n$. For every ordered triple of different points $(a,b,c)$, the following constraints should be met:\n\n- if $a$, $b$ and $c$ have the same color, then $d(a,b) = d(a,c) = d(b,c)$;\n- if $a$ and $b$ have the same color, and the color of $c$ is different from the color of $a$, then $d(a,b) < d(a,c)$ and $d(a,b) < d(b,c)$.\n\nCalculate the number of different ways to choose the colors that meet these constraints.",
    "tutorial": "Let's call a point $i$ isolated if its color does not match the color of any other point. If a point is not isolated, then it has the same color as the points with minimum distance to it (and only these points should have this color). Let's build a directed graph where the arc $i \\rightarrow j$ means that the point $j$ is one of the closest to the point $i$ (i. e. $d(i, j) = \\min\\limits_{k = 1, k \\ne i}^{n} d(i,k)$). If there is a path from the vertex $i$ to the vertex $j$, it means that if the vertex $i$ is not isolated, the vertex $j$ should have the same color as vertex $i$. Suppose the set of vertices reachable from $i$ (including $i$ itself) is $S(i)$. Finding $S(i)$ is easy - just run DFS from the vertex $i$. Let's analyze two cases: there exists a pair of vertices $(j, k)$ such that $j \\in S(i)$, $k \\in S(i)$, and there is no arc from $j$ to $k$; for every pair of vertices $(j, k)$ such that $j \\in S(i)$ and $k \\in S(i)$, there is an arc $j \\rightarrow k$. Why do we need to analyze these two cases? In the first case, the vertex $i$ must be isolated, because painting it and some other vertex into the same color means that every vertex from $S(i)$ will have this color, and it will break the condition in the statement. In the second case, the vertex $i$ may be isolated, or it may have the same color as all vertices in $S(i)$ - and if it is isolated, then the whole set $S(i)$ should consist of isolated vertices. Let's find all such set of vertices that meet the second case. Each vertex will belong to at most one of these sets; if it doesn't belong to any, it must be isolated, otherwise either the whole its set consists of isolated vertices, or the whole set has the same color. So, for each set, we either use $1$ color or $|S(i)|$ colors. This allows us to implement a knapsack-like dynamic programming: let $dp_{i,j}$ be the number of ways to paint $i$ first sets into $j$ colors, such that the colors are not ordered. After running this dynamic programming, we can get the answer by simple combinatorics: iterate on the number of colors we use in these sets in total, multiply the dynamic programming for it by the (ordered) number of ways to choose these colors from $n$, and then by the number of ways to choose the colors for points that must be isolated. This dynamic programming can even be implemented a bit easier if we treat every vertex that must be isolated as a set of size $1$, and this is the way it's written in the model solution.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 143;\nconst int K = 5;\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;   \n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1) z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nint fact[N];\nint rfact[N];\n\nint A(int n, int k)\n{\n    return mul(fact[n], rfact[n - k]);\n}\n\nint n;\n\nvector<int> g[N];\nint x[N];\nint y[N];\nint dist[N][N];\nint color[N];\nint dp[N][N];\n\nint cc = 0;\nset<int> pts;\nvector<int> compsize;\n\nvoid dfs1(int i)\n{\n    //cerr << i << endl;\n    if(pts.count(i) == 1) return;\n    pts.insert(i);\n    for(auto v : g[i])\n    {\n        dfs1(v);\n    }\n}\n\nvoid dfs2(int i, int c)\n{\n    if(color[i] == c) return;\n    color[i] = c;\n    for(auto v : g[i])\n        dfs2(v, c);\n}\n\nint main()\n{\n    fact[0] = 1;\n    for(int i = 1; i < N; i++)\n        fact[i] = mul(i, fact[i - 1]);\n    for(int i = 0; i < N; i++)\n        rfact[i] = binpow(fact[i], MOD - 2);\n\n\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++)\n    {\n        scanf(\"%d %d\", &x[i], &y[i]);    \n    }\n    for(int i = 0; i < n; i++)\n    {\n        dist[i][i] = int(1e9);\n        for(int j = 0; j < n; j++)\n            if(i != j)\n                dist[i][j] = abs(x[i] - x[j]) + abs(y[i] - y[j]);\n    }\n    for(int i = 0; i < n; i++)\n    {\n        int d = *min_element(dist[i], dist[i] + n);\n        for(int j = 0; j < n; j++)\n            if(dist[i][j] == d) g[i].push_back(j);    \n    }\n\n    for(int i = 0; i < n; i++)\n    {\n        if(color[i] != 0) continue;\n        cc++;\n        pts.clear();\n        dfs1(i);\n        //cerr << \"!\" << endl; \n        int d = *min_element(dist[i], dist[i] + n);                      \n        set<int> pts2 = pts;\n        bool bad = false;\n        for(auto x : pts)\n            for(auto y : pts2)\n                if(x != y && dist[x][y] != d)\n                    bad = true;\n        if(bad)           \n        {\n            color[i] = cc;\n            compsize.push_back(1);\n        }\n        else\n        {\n            dfs2(i, cc);\n            compsize.push_back(pts.size());\n        }\n    }            \n\n    dp[0][0] = 1;\n    int m = compsize.size();\n    for(int i = 0; i < m; i++)\n        for(int j = 0; j < n; j++)\n        {\n            if(dp[i][j] == 0) continue;\n            dp[i + 1][j + 1] = add(dp[i + 1][j + 1], dp[i][j]);\n            if(compsize[i] != 1)\n            {\n                dp[i + 1][j + compsize[i]] = add(dp[i + 1][j + compsize[i]], dp[i][j]);\n            }\n        }\n    int ans = 0;\n    for(int i = 1; i <= n; i++)\n        ans = add(ans, mul(dp[m][i], A(n, i)));\n    cout << ans << endl;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "dp",
      "geometry",
      "graphs",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1697",
    "index": "F",
    "title": "Too Many Constraints",
    "statement": "You are asked to build an array $a$, consisting of $n$ integers, each element should be from $1$ to $k$.\n\nThe array should be non-decreasing ($a_i \\le a_{i+1}$ for all $i$ from $1$ to $n-1$).\n\nYou are also given additional constraints on it. Each constraint is of one of three following types:\n\n- $1~i~x$: $a_i$ \\textbf{should not} be equal to $x$;\n- $2~i~j~x$: $a_i + a_j$ should be less than or equal to $x$;\n- $3~i~j~x$: $a_i + a_j$ should be greater than or equal to $x$.\n\nBuild any non-decreasing array that satisfies all constraints or report that no such array exists.",
    "tutorial": "Imagine there were no constraints of the second or the third types. Then it would be possible to solve the problem with some greedy algorithm. Unfortunately, when both these constraints are present, it's not immediately clear how to adapt the greedy. Dynamic programming is probably also out of question, because you can't maintain all possible cuts between equal values on each prefix. Thus, let's try to make a graph problem out of this. Who knows, maybe a flow or something else could work. Create $k$ nodes for each position. Let the $x$-th of them on the $i$-th position represent the condition of kind \"is $a_i$ equal to $x$?\". Then all constraints can be described as edges on this graph. Binary variables, restrictive edges. Surely, this is 2-SAT. Connect the pairs of values that satisfy each constraint. Add the edges between the adjacent positions to enforce the restriction on the non-decreasing order. Prohibit each position to be assigned to multiple values. Force each position to be assigned at least one value. Huh, it's not that easy. That's where the 2-SAT idea fails. We want the conditions of form $(a_i = 1 \\vee a_i = 2 \\vee \\dots \\vee a_i = k)$. But that is not allowed, since 2-SAT has to have two variables in a clause. That's where the main idea of the problem comes up. Instead of making our nodes $(i, x)$ represent $a_i = x$, let's make them $a_i \\ge x$ and try building the graph again. If $a_i = x$, then all nodes $(i, y)$ for $y \\le x$ will be true, and the rest will be false. So if $(i, x)$ is false, then $(i, x + 1)$ is false. That will enforce the validity of the nodes themselves. First, the order. If $(i, x)$ is true, then $(i + 1, x)$ is true. The first type of constraints. $a_i \\neq x$ is basically the same as ($a_i < x$ or $a_i > x$). For our conditions, it's rather ((not $a_i \\ge x$) or $a_i \\ge x + 1$). The second type of constraints. $a_i + a_j \\le x$. Let $a_i$ be greater than or equal to some $y$. Then, for this constraint to hold, $a_j$ should be no greater than $x - y$. Thus, if $(a_i \\ge y)$ is true, then $(a_j \\ge x - y + 1)$ should be false. Same for $i$ and $j$ swapped. The third type of constraints is similar. $a_i + a_j \\ge x$. Let $a_i$ be less than or equal to some $y$. Then, for this constraint to hold, $a_j$ should be greater than or equal to $x - y$. Thus, if $(a_i \\ge y + 1)$ is false, then $(a_j \\ge x - y)$ should be true. Same for $i$ and $j$ swapped. And that's it. Solve the 2-SAT and restore the answer. I can advise making not $k$ but actually $k + 2$ nodes for $a_i \\ge 0, 1, \\dots, k+1$ and force the values to be between $1$ and $k$. That will simplify the checks while adding the constraints. Overall complexity: $O((n+m)k)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct constraint{\n\tint tp, i, j, x;\n};\n\nvector<vector<int>> g, tg;\nvector<char> used;\nvector<int> clr, ord;\n\nvoid ts(int v){\n\tused[v] = true;\n\tfor (int u : g[v]) if (!used[u])\n\t\tts(u);\n\tord.push_back(v);\n}\n\nvoid dfs(int v, int k){\n\tclr[v] = k;\n\tfor (int u : tg[v]) if (clr[u] == -1)\n\t\tdfs(u, k);\n}\n\nvoid either(int x, int y){\n\tg[x ^ 1].push_back(y);\n\tg[y ^ 1].push_back(x);\n\ttg[y].push_back(x ^ 1);\n\ttg[x].push_back(y ^ 1);\n}\n\nvoid implies(int x, int y){\n\teither(x ^ 1, y);\n}\n\nvoid must(int x){\n\teither(x, x);\n}\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\tforn(_, t){\n\t\tint n, m, k;\n\t\tscanf(\"%d%d%d\", &n, &m, &k);\n\t\tvector<constraint> c(m);\n\t\tforn(i, m){\n\t\t\tscanf(\"%d%d\", &c[i].tp, &c[i].i);\n\t\t\tif (c[i].tp != 1) scanf(\"%d\", &c[i].j);\n\t\t\tscanf(\"%d\", &c[i].x);\n\t\t\t--c[i].i, --c[i].j;\n\t\t}\n\t\tint vts = n * (k + 2);\n\t\tg.assign(2 * vts, vector<int>());\n\t\ttg.assign(2 * vts, vector<int>());\n\t\tforn(i, n){\n\t\t\tforn(j, (k + 2) - 1)\n\t\t\t\timplies(2 * (i * (k + 2) + j + 1) + 1, 2 * (i * (k + 2) + j) + 1);\n\t\t\tmust(2 * (i * (k + 2) + 1) + 1);\n\t\t\tmust(2 * (i * (k + 2) + k + 1));\n\t\t}\n\t\tforn(i, n - 1) forn(j, k + 2){\n\t\t\timplies(2 * (i * (k + 2) + j) + 1, 2 * ((i + 1) * (k + 2) + j) + 1);\n\t\t}\n\t\tforn(i, m){\n\t\t\tif (c[i].tp == 1)\n\t\t\t\teither(2 * (c[i].i * (k + 2) + c[i].x + 1) + 1, 2 * (c[i].i * (k + 2) + c[i].x));\n\t\t\telse if (c[i].tp == 2){\n\t\t\t\tfor (int a = max(1, c[i].x - k); a <= min(k, c[i].x - 1); ++a){\n\t\t\t\t\timplies(2 * (c[i].i * (k + 2) + a) + 1, 2 * (c[i].j * (k + 2) + (c[i].x - a) + 1));\n\t\t\t\t\timplies(2 * (c[i].j * (k + 2) + a) + 1, 2 * (c[i].i * (k + 2) + (c[i].x - a) + 1));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfor (int a = max(1, c[i].x - k); a <= min(k, c[i].x - 1); ++a){\n\t\t\t\t\timplies(2 * (c[i].i * (k + 2) + a + 1), 2 * (c[i].j * (k + 2) + (c[i].x - a)) + 1);\n\t\t\t\t\timplies(2 * (c[i].j * (k + 2) + a + 1), 2 * (c[i].i * (k + 2) + (c[i].x - a)) + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tused.assign(2 * vts, 0);\n\t\tord.clear();\n\t\tforn(i, used.size()) if (!used[i]) ts(i);\n\t\treverse(ord.begin(), ord.end());\n\t\tclr.assign(2 * vts, -1);\n\t\tint cc = 0;\n\t\tfor (int v : ord) if (clr[v] == -1){\n\t\t\tdfs(v, cc);\n\t\t\t++cc;\n\t\t}\n\t\tvector<int> vals(vts);\n\t\tbool ans = true;\n\t\tforn(i, vts){\n\t\t\tif (clr[2 * i] == clr[2 * i + 1]){\n\t\t\t\tans = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvals[i] = (clr[2 * i] < clr[2 * i + 1]);\n\t\t}\n\t\tif (!ans){\n\t\t\tputs(\"-1\");\n\t\t\tcontinue;\n\t\t}\n\t\tforn(i, n){\n\t\t\tint lst = 0;\n\t\t\tforn(j, k + 2) if (vals[i * (k + 2) + j])\n\t\t\t\tlst = j;\n\t\t\tprintf(\"%d \", lst);\n\t\t}\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "2-sat",
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1698",
    "index": "A",
    "title": "XOR Mixup",
    "statement": "There is an array $a$ with $n-1$ integers. Let $x$ be the bitwise XOR of all elements of the array. The number $x$ is added to the end of the array $a$ (now it has length $n$), and then the elements are shuffled.\n\nYou are given the newly formed array $a$. What is $x$? If there are multiple possible values of $x$, you can output any of them.",
    "tutorial": "Any element of the array works. Let's use $\\oplus$ for $\\mathsf{XOR}$. Suppose that the original array is $[a_1, \\dots, a_{n-1}]$. Then $x=a_1 \\oplus \\dots \\oplus a_{n-1}$. Let's show that $a_1$ is the $\\mathsf{XOR}$ of all other elements of the array; that is, $a_1 = a_2 \\oplus \\dots \\oplus a_{n-1} \\oplus x$. Substituting $x=a_1 \\oplus \\dots \\oplus a_{n-1}$, we have $a_1 = a_2 \\oplus \\dots \\oplus a_{n-1} \\oplus a_2 \\oplus \\dots \\oplus a_{n-1}.$ More formally, we can write the following. $\\begin{align*} a_1 &\\stackrel{?}{=} a_2 \\oplus \\dots \\oplus a_{n-1} \\oplus x \\\\ &= a_2 \\oplus \\dots \\oplus a_{n-1} \\oplus (a_1 \\oplus \\dots \\oplus a_{n-1}) \\\\ &= a_2 \\oplus \\dots \\oplus a_{n-1} \\oplus (a_1 \\oplus a_2 \\oplus \\dots \\oplus a_{n-1}) \\\\ &= (a_2 \\oplus \\dots \\oplus a_{n-1}) \\oplus a_1 \\oplus (a_2 \\oplus \\dots \\oplus a_{n-1}) \\\\ &= a_1 \\oplus (a_2 \\oplus \\dots \\oplus a_{n-1}) \\oplus (a_2 \\oplus \\dots \\oplus a_{n-1}) \\\\ &= a_1. \\end{align*}$ The same proof follows for any $a_i$. Hence you can output any element of the array. The time complexity is $\\mathcal{O}(n)$.",
    "code": "for t in range(int(input())):\n\tn = int(input())\n\tprint([int(x) for x in input().split()][0])",
    "tags": [
      "bitmasks",
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "1698",
    "index": "B",
    "title": "Rising Sand",
    "statement": "There are $n$ piles of sand where the $i$-th pile has $a_i$ blocks of sand. The $i$-th pile is called too tall if $1 < i < n$ and $a_i > a_{i-1} + a_{i+1}$. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.)\n\nYou are given an integer $k$. An operation consists of picking $k$ consecutive piles of sand and adding one unit of sand to them all. Formally, pick $1 \\leq l,r \\leq n$ such that $r-l+1=k$. Then for all $l \\leq i \\leq r$, update $a_i \\gets a_i+1$.\n\nWhat is the \\textbf{maximum} number of piles that can simultaneously be too tall after some (possibly zero) operations?",
    "tutorial": "Note that two piles in a row can't be too tall, since a pile that is too tall has strictly more sand than its neighbours. If $k=1$ then we can make every other pile too tall, excluding the ends of the array. For example, if $a=[1,2,3,4,5,6]$, we can make piles $2$ and $4$ too tall by performing some large number of operations on them (say, by making it into $[1, 10^{100}, 3, 10^{100}, 5, 6]$.) The answer is $\\left\\lfloor\\frac{n-1}{2}\\right\\rfloor$. If $k \\geq 2$, then note that for any pile, if we perform the operation on it then we perform on one of its neighbours as well. Therefore, if the pile is not too tall initially, then it will never become too tall as a result of these operations, since both a pile and at least one of its neighbours will gain sand. So in this case, doing operations never improves the answer, and so the answer is the number of too tall piles initially. The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tint a[n];\n\tfor (int i = 0; i < n; i++) {\n\t    cin >> a[i];\n\t}\n\tif (k > 1) {\n\t    int res = 0;\n\t    for (int i = 1; i < n - 1; i++) {\n\t        res += (a[i] > a[i - 1] + a[i + 1]);\n\t    }\n\t    cout << res << '\\n';\n\t}\n\telse {\n\t    cout << (n - 1) / 2 << '\\n';\n\t}\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1698",
    "index": "C",
    "title": "3SUM Closure",
    "statement": "You are given an array $a$ of length $n$. The array is called 3SUM-closed if for all distinct indices $i$, $j$, $k$, the sum $a_i + a_j + a_k$ is an element of the array. More formally, $a$ is 3SUM-closed if for all integers $1 \\leq i < j < k \\leq n$, there exists some integer $1 \\leq l \\leq n$ such that $a_i + a_j + a_k = a_l$.\n\nDetermine if $a$ is 3SUM-closed.",
    "tutorial": "Let's consider some array which is 3SUM-closed. If the array has at least three positive elements, consider the largest three $x$, $y$, and $z$. Notice that $x+y+z$ is strictly larger than $x$, $y$, and $z$, which means that $x+y+z$ is not an element of the array (since $x$, $y$, $z$ were the largest elements). Therefore the array has $\\leq 2$ positive elements. Similarly, if the array has at least three negative elements, consider the smallest three $x$, $y$, and $z$. Notice that $x+y+z$ is strictly smaller than $x$, $y$, and $z$, which means that $x+y+z$ is not an element of the array (since $x$, $y$, $z$ were the smallest elements). Therefore the array has $\\leq 2$ negative elements. Finally, note that there is no point in having more than $2$ zeroes in the array, since any additional zeroes won't change the sums that can be formed. So if there are more than $2$ zeroes, we can remove them until there are exactly $2$. It follows that the resulting array has at most $2 + 2 + 2 = 6$ elements. This is small, so we can brute force the condition in the problem in $\\mathcal{O}(6^4)$ or $\\mathcal{O}(6^3)$ time. The time complexity is $\\mathcal{O}(n + 6^4)$ or $\\mathcal{O}(n + 6^3)$, depending on the implementation.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> pos, neg, a;\n\tfor (int i = 0; i < n; i++) {\n\t\tint x; cin >> x;\n\t\tif (x > 0) {pos.push_back(x);}\n\t\telse if (x < 0) {neg.push_back(x);}\n\t\telse {\n\t\t\tif (a.size() < 2) {a.push_back(x);}\n\t\t}\n\t}\n\tif (pos.size() > 2 || neg.size() > 2) {cout << \"NO\\n\"; return;}\n\t\n\tfor (int i : pos) {a.push_back(i);}\n\tfor (int i : neg) {a.push_back(i);}\n\t\n\tfor (int i = 0; i < a.size(); i++) {\n\t\tfor (int j = i + 1; j < a.size(); j++) {\n\t\t\tfor (int k = j + 1; k < a.size(); k++) {\n\t\t\t\tbool ok = false;\n\t\t\t\tfor (int l = 0; l < a.size(); l++) {\n\t\t\t\t\tif (a[i] + a[j] + a[k] == a[l]) {ok = true;}\n\t\t\t\t}\n\t\t\t\tif (!ok) {cout << \"NO\\n\"; return;}\n\t\t\t}\n\t\t}\n\t}\n\tcout << \"YES\\n\";\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "brute force",
      "data structures"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1698",
    "index": "D",
    "title": "Fixed Point Guessing",
    "statement": "This is an interactive problem.\n\nInitially, there is an array $a = [1, 2, \\ldots, n]$, where $n$ is an odd positive integer. The jury has selected $\\frac{n-1}{2}$ \\textbf{disjoint} pairs of elements, and then the elements in those pairs are swapped. For example, if $a=[1,2,3,4,5]$, and the pairs $1 \\leftrightarrow 4$ and $3 \\leftrightarrow 5$ are swapped, then the resulting array is $[4, 2, 5, 1, 3]$.\n\nAs a result of these swaps, exactly one element will not change position. You need to find this element.\n\nTo do this, you can ask several queries. In each query, you can pick two integers $l$ and $r$ ($1 \\leq l \\leq r \\leq n$). In return, you will be given the elements of the subarray $[a_l, a_{l + 1}, \\dots, a_r]$ \\textbf{sorted in increasing order}.\n\nFind the element which did not change position. You can make at most $\\mathbf{15}$ queries.\n\nThe array $a$ is fixed before the interaction and does not change after your queries.\n\nRecall that an array $b$ is a subarray of the array $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "Note that $\\left\\lceil\\log_2 10^4\\right\\rceil = 14$, which is less than the number of queries. If we can answer a question of the form \"given a subarray, does it contain the fixed point?\", then we can binary search on this subarray until we find the fixed point. Given a subarray $[a_l, \\dots, a_r]$, let's count the number of $a_i$ such that $l \\leq a_i \\leq r$. We claim that if this count is odd, then the subarray contains the fixed point; otherwise, it does not. First, let's show that each swapped pair either increases the count by $0$ or by $2$. Suppose that $x \\leftrightarrow y$ are swapped (that is, $a_x = y$ and $a_y = x$). If $a_x$ is in the range from $l$ to $r$, then $l \\leq y \\leq r$ (since $a_x = y$), so $a_y$ is also in the range from $l$ to $r$. Similarly, if $a_x$ is not in the range, then neither is $a_y$. So this pair either increases the count by $0$ or $2$. Contrarily, the fixed point increases the count by $0$ if it is not in the range and $1$ if it is. So we can simply look at the parity of the number of elements satisfying the condition, and run our binary search. The time complexity is $\\mathcal{O}(n)$.",
    "code": "for t in range(int(input())):\n\tn = int(input())\n\tl = 1\n\tr = n\n\twhile l < r:\n\t\tm = l + (r - l) // 2\n\t\tprint(\"?\", l, m, flush=True)\n\t\tif (sum(l <= i <= m for i in [int(x) for x in input().split()]) % 2):\n\t\t\tr = m\n\t\telse:\n\t\t\tl = m + 1\n\tprint(\"!\", l, flush=True)",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1698",
    "index": "E",
    "title": "PermutationForces II",
    "statement": "You are given a permutation $a$ of length $n$. Recall that permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order.\n\nYou have a strength of $s$ and perform $n$ moves on the permutation $a$. The $i$-th move consists of the following:\n\n- Pick two integers $x$ and $y$ such that $i \\leq x \\leq y \\leq \\min(i+s,n)$, and swap the positions of the integers $x$ and $y$ in the permutation $a$. Note that you \\textbf{can} select $x=y$ in the operation, in which case no swap will occur.\n\nYou want to turn $a$ into another permutation $b$ after $n$ moves. However, some elements of $b$ are missing and are replaced with $-1$ instead. Count the number of ways to replace each $-1$ in $b$ with some integer from $1$ to $n$ so that $b$ is a permutation and it is possible to turn $a$ into $b$ with a strength of $s$.\n\nSince the answer can be large, output it modulo $998\\,244\\,353$.",
    "tutorial": "Suppose that we know the elements of $b$. We claim that the minimum strength needed is $\\max_{i=1}^n a_i - b_i$. Let's prove it. Proof. For simplicity let's sort the elements of $b$ from $1$ to $n$, and rearrange the corresponding elements of $a$ in the same way. In other words, we only need to turn this new array $a$ into the identity $[1, 2, \\dots, n]$. First note that on the $i$-th operation, we need to move the number $i$ to the correct position. This is because of the format of the operations; in any future operation, $i$ will not be in the given range, so it is required to move $i$ in the current operation. Let's look at the number $1$. If $a_1 = 1$, then we don't need any strength. Otherwise, we need $a_i - 1$ strength to swap $1$ and $a_i$. Afterwards, we can essentially ignore $1$ for the rest of the operations, since there is no need to move it again. In general, there are two cases for when we need to move $i$ to its correct place: $a_i \\geq i$. In this case, we'll never move $a_i$ until the $i$-th operation, where we swap $i$ and $a_i$. We need a strength of $a_i - i$ for that. This is necessary. $a_i < i$. In this case, we will swap $a_i$ in an earlier operation (since $a_i < i$, so we must swap it to its correct place in the $a_i$-th operation). If we again end up with some smaller number, we will need to swap that before $i$, and so on. Suppose that after some time, the current element $a_i$ in the $i$-th position is at least $i$. Then this element must have been swapped with some other element smaller than $i$ (since we only perform swaps with elements smaller than $i$ before the $i$-th operation). In particular, this element originally started somewhere to the left of $i$, say at position $j < i$. Then in the strength calculation, we counted $a_i - j$, which is more than $a_i - i$, i.e. more than we actually need to swap $i$ and $a_i$. This is sufficient. Suppose that after some time, the current element $a_i$ in the $i$-th position is at least $i$. Then this element must have been swapped with some other element smaller than $i$ (since we only perform swaps with elements smaller than $i$ before the $i$-th operation). In particular, this element originally started somewhere to the left of $i$, say at position $j < i$. Then in the strength calculation, we counted $a_i - j$, which is more than $a_i - i$, i.e. more than we actually need to swap $i$ and $a_i$. This is sufficient. Hence we only need to check the inequality $s \\geq a_i - b_i$ for all $i$. Now we proceed to the counting part. Rewrite this as $a_i - s \\leq b_i$. Suppose that $k$ values of $b_i$ are missing. Call them $[m_1, \\dots, m_k]$ in increasing order. Then note that if some element of $m$ satisfies this inequality, all larger elements of $m$ will. In other words, for each $a_i$ whose corresponding element of $b$ is missing, some suffix of $[m_1, \\dots, m_k]$ will work. We can simply binary search to find this suffix for each $a_i$. Let $l_i$ denote the length of this suffix. Afterwards, we need to count the number of ways to assign each missing element to an $a_i$. Process the elements greedily, from the $a_i$ with the fewest choices to the one with the most (that is, the largest $a_i$ to the smallest). The first $a_i$ has $l_i$ choices, the second $l_i - 1$ (one element of $m$ was already taken), the third $l_i - 2$, and so on. We can compute this product straightforwardly. The time complexity is $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 998244353;\n \nbool cmp(const pair<int, int>& a, const pair<int, int>& b) {\n\treturn (a.second < b.second);\n}\n \nvoid solve() {\n\tint n, s;\n\tcin >> n >> s;\n\tpair<int, int> a[n + 1];\n\tbool vis[n + 1];\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i].first;\n\t\tvis[i] = false;\n\t}\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i].second;\n\t\tif (a[i].second != -1) {\n\t\t\tvis[a[i].second] = true;\n\t\t}\n\t}\n\tvector<int> missing;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (!vis[i]) {missing.push_back(i);}\n\t}\n\tsort(a + 1, a + n + 1, cmp);\n\tint mx = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (a[i].second != -1) {\n\t\t\tmx = max(mx, a[i].first - a[i].second);\n\t\t}\n\t}\n\tif (mx > s) {cout << 0 << '\\n'; return;}\n\tvector<int> cnts;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (a[i].second == -1) {\n\t\t\tcnts.push_back(missing.end() - lower_bound(missing.begin(), missing.end(), a[i].first - s));\n\t\t}\n\t}\n\tsort(cnts.begin(), cnts.end());\n\tlong long res = 1;\n\tfor (int i = 0; i < cnts.size(); i++) {\n\t\tres = (res * (cnts[i] - i)) % MOD;\n\t}\n\tcout << res << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "greedy",
      "sortings",
      "trees",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1698",
    "index": "F",
    "title": "Equal Reversal",
    "statement": "There is an array $a$ of length $n$. You may perform the following operation on it:\n\n- Choose two indices $l$ and $r$ where $1 \\le l \\le r \\le n$ and $a_l = a_r$. Then, reverse the subsegment from the $l$-th to the $r$-th element, i. e. set $[a_l, a_{l + 1}, \\ldots, a_{r - 1}, a_r]$ to $[a_r, a_{r-1}, \\ldots, a_{l+1}, a_l]$.\n\nYou are also given another array $b$ of length $n$ which is a permutation of $a$. Find a sequence of at most $n^2$ operations that transforms array $a$ into $b$, or report that no such sequence exists.",
    "tutorial": "Consider the following invariants of the array: $a_1$ and $a_n$ don't change as a result of the operations. The set of unordered pairs of adjacent elements doesn't change as a result of the operations. In other words, if you build a graph $\\mathcal{G}$ whose vertices are labelled $1$ to $n$, and make an edge connecting $a_i$ and $a_{i+1}$ for all $1 \\leq i < n$, the graph does not change after operations. This is because the operation can be seen as reversing the order we traverse a cycle in $\\mathcal{G}$, which doesn't change the undirected graph. The first element of $a$ already has to match. Suppose the second element does not match; that is, $a_1 = b_1$ but $a_2 \\neq b_2$. Then there has to be some other copy of $b_1$ later in $a$ next to the element in $a$ equal to $b_2$, by the graph condition mentioned above. If the copy of $b_1$ appears after the element equal to $b_2$, we can reverse the subarray whose endpoints are the two copies of $b_1$. Otherwise, it can be shown that there must exist some subarray with equal endpoints that contains $b_1$ followed by $b_2$, so we can reverse it. This takes $2n$ operations, but it requires $\\mathcal{O}(n^2)$ time to construct. So the overall complexity is $\\mathcal{O}(n^3)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 1007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tint a[n], b[n];\n\tvector<pair<int, int>> ax, bx;\n\tfor (int i = 0; i < n; i++) {\n\t    cin >> a[i];\n\t    if (i > 0) {ax.emplace_back(min(a[i - 1], a[i]), max(a[i - 1], a[i]));}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t    cin >> b[i];\n\t    if (i > 0) {bx.emplace_back(min(b[i - 1], b[i]), max(b[i - 1], b[i]));}\n\t}\n\tsort(ax.begin(), ax.end());\n\tsort(bx.begin(), bx.end()); \n\tif (!(a[0] == b[0] && a[n - 1] == b[n - 1] && equal(ax.begin(), ax.end(), bx.begin()))) {\n\t\tcout << \"NO\\n\"; return;\n\t}\n\tcout << \"YES\\n\";\n\tvector<pair<int, int>> ans;\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tif (a[i] == b[i] && a[i + 1] == b[i + 1]) {continue;}\n\t\tint pos = -1;\n\t\tfor (int j = i; j < n - 1; j++) {\n\t\t\tif (a[j + 1] == b[i] && a[j] == b[i + 1]) {pos = j; break;}\n\t\t}\n\t\tif (pos != -1) {ans.emplace_back(i + 1, pos + 2); reverse(a + i, a + pos + 2); continue;}\n\t\tfor (int j = i; j < n - 1; j++) {\n\t\t\tif (a[j] == b[i] && a[j + 1] == b[i + 1]) {pos = j; break;}\n\t\t}\n\t\tset<pair<int, int>> seen;\n\t\tfor (int j = i; j < pos; j++) {\n\t\t\tseen.insert(make_pair(min(a[j], a[j + 1]), max(a[j], a[j + 1])));\n\t\t}\n\t\tint val = -1;\n\t\tfor (int j = i + 1; j < n - 1; j++) {\n\t\t\tif (seen.find(make_pair(min(b[j], b[j + 1]), max(b[j], b[j + 1]))) != seen.end()) {\n\t\t\t\tval = j; break;\n\t\t\t}\n\t\t}\n\t\tint posr = -1, posl = -1;\n\t\tfor (int j = i; j <= pos; j++) {\n\t\t\tif (min(a[j], a[j + 1]) == min(b[val], b[val + 1]) && max(a[j], a[j + 1]) == max(b[val], b[val + 1])) {posr = j; break;}\n\t\t}\n\t\tfor (int j = n - 2; j >= pos; j--) {\n\t\t\tif (min(a[j], a[j + 1]) == min(b[val - 1], b[val]) && max(a[j], a[j + 1]) == max(b[val - 1], b[val])) {posl = j; break;}\n\t\t}\n\t\tif (posr < n - 1 && a[posr + 1] == a[posl]) {posr++;}\n\t\telse if (posl < n - 1 && a[posr] == a[posl + 1]) {posl++;}\n\t\telse if (posr < n - 1 && posl < n - 1 && a[posr + 1] == a[posl + 1]) {posr++; posl++;}\n\t\tans.emplace_back(posr + 1, posl + 1); reverse(a + posr, a + posl + 1);\n\t\tpos = -1;\n\t\tfor (int j = i; j < n - 1; j++) {\n\t\t\tif (a[j + 1] == b[i] && a[j] == b[i + 1]) {pos = j; break;}\n\t\t}\n\t\tans.emplace_back(i + 1, pos + 2); reverse(a + i, a + pos + 2);\n\t}\n\tcout << ans.size() << '\\n';\n\tfor (auto p : ans) {\n\t\tcout << p.first << ' ' << p.second << '\\n';\n\t}\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n    // solve();\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1698",
    "index": "G",
    "title": "Long Binary String",
    "statement": "There is a binary string $t$ of length $10^{100}$, and initally all of its bits are $0$. You are given a binary string $s$, and perform the following operation some times:\n\n- Select some substring of $t$, and replace it with its XOR with $s$.$^\\dagger$\n\nAfter several operations, the string $t$ has exactly two bits $1$; that is, there are exactly two distinct indices $p$ and $q$ such that the $p$-th and $q$-th bits of $t$ are $1$, and the rest of the bits are $0$. Find the lexicographically largest$^\\ddagger$ string $t$ satisfying these constraints, or report that no such string exists.\n\n$^\\dagger$ Formally, choose an index $i$ such that $0 \\leq i \\leq 10^{100}-|s|$. For all $1 \\leq j \\leq |s|$, if $s_j = 1$, then toggle $t_{i+j}$. That is, if $t_{i+j}=0$, set $t_{i+j}=1$. Otherwise if $t_{i+j}=1$, set $t_{i+j}=0$.\n\n$^\\ddagger$ A binary string $a$ is lexicographically larger than a binary string $b$ of the same length if in the first position where $a$ and $b$ differ, the string $a$ has a bit $1$ and the corresponding bit in $b$ is $0$.",
    "tutorial": "Ignore leading zeroes of $s$. We can add them back at the end. Let's view the string as a polynomial $P(x)$ in $\\mathrm{GF}(2)$. Then in an operation we can multiply $P(x)$ by any monomial $x^k$ for some $k$, so after some number of operations we can multiply $P(x)$ by some other polynomial $Q(x)$. At the end, we have a string with two flipped bits. We can in fact make the first character equal to $1$ by finding the smallest $k$ such that $P(x)Q(x) = x^k + 1$. Such a $k$ exists, because the constant term of $P$ is $1$ and $Q$ is arbitrary. Rewrite this as $x^k \\equiv 1 \\pmod{P(x)}$. Now it's clear that the answer is a divisor of the order of $x$ in $P(x)$. We can use polynomial factoring algorithms or baby-step-giant-step and meet in the middle. The time complexity is $\\mathcal{O}(2^{|s|/2} |s|^2)$ or $\\mathcal{O}(2^{|s|/2} |s|)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define int long long\n#define ll long long\n#define endl '\\n'\n \n#define rep(x, start, end)                                                     \\\n    for (auto x = (start) - ((start) > (end)); x != (end) - ((start) > (end)); \\\n         ((start) < (end) ? x++ : x--))\n#define all(x) (x).begin(), (x).end()\n#define sz(x) (int)(x).size()\n \nint n;\nstring s;\nint mod;\n \nint mul(int i, int j) {\n    int res = 0;\n    rep(x, 0, n - 1) {\n        if (i & (1LL << x)) res ^= j;\n        j <<= 1;\n        if (j & (1LL << (n - 1))) j ^= mod;\n    }\n    return res;\n}\n \nint pow(int i) {\n    int res = 1;\n    int b = 2;\n    while (i) {\n        if (i & 1) res = mul(res, b);\n        b = mul(b, b);\n        i >>= 1;\n    }\n    return res;\n}\n \nsigned main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cin.exceptions(ios::badbit | ios::failbit);\n        mod = 0;\n        cin >> s;\n        vector<int> pos;\n        for (int i = 0; i < s.length(); i++) {\n            if (s[i] == '1') {\n                pos.push_back(i);\n            }\n        }\n        s.erase(s.find_last_not_of(\"0\") + 1);\n        int offset = s.find_first_not_of(\"0\");\n        s.erase(0, offset);\n        n = s.length();\n        if (pos.size() == 0) {\n            cout << -1 << endl;\n            return 0;\n        }\n        if (pos.size() == 1) {\n            cout << n + offset << ' ' << n + offset + 1 << endl;\n            return 0;\n        }\n        if (pos.size() == 2) {\n            cout << pos[0] + 1 << ' ' << pos[1] + 1 << endl;\n            return 0;\n        }\n        rep(x, 0, sz(s)) if (s[x] == '1') mod |= (1LL << x);\n \n        int h = (n + 1) / 2;\n \n        int val = mod;\n        int prod = 1;\n        rep(x, 3LL, 1 << h) if (x & 1) {\n            int num = 0;\n            while (true) {\n                int curr = val;\n                int other = 0;\n                rep(bit, 0, n) if (curr & (1LL << bit)) {\n                    curr ^= x << bit;\n                    other ^= 1LL << bit;\n                }\n                if (curr == 0) {\n                    val = other;\n                    num++;\n                } else\n                    break;\n            }\n \n            if (num) {\n                prod *= (1LL << (63 - __builtin_clzll(x))) - 1;\n                rep(y, 1, num) prod *= 1LL << (63 - __builtin_clzll(x));\n            }\n        }\n        if (val > 1) prod *= (1LL << (63 - __builtin_clzll(val))) - 1;\n \n        int ans = 1LL << 60;\n        for (int x = 1; x * x <= prod; x++) {\n            if (prod % x == 0) {\n                if (pow(x) == 1) ans = min(ans, x);\n                if (pow(prod / x) == 1) ans = min(ans, prod / x);\n            }\n        }\n        cout << 1 + offset << ' ' << ans + 1 + offset << endl;\n}",
    "tags": [
      "bitmasks",
      "math",
      "matrices",
      "meet-in-the-middle",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1699",
    "index": "A",
    "title": "The Third Three Number Problem",
    "statement": "You are given a positive integer $n$. Your task is to find \\textbf{any} three integers $a$, $b$ and $c$ ($0 \\le a, b, c \\le 10^9$) for which $(a\\oplus b)+(b\\oplus c)+(a\\oplus c)=n$, or determine that there are no such integers.\n\nHere $a \\oplus b$ denotes the bitwise XOR of $a$ and $b$. For example, $2 \\oplus 4 = 6$ and $3 \\oplus 1=2$.",
    "tutorial": "An answer exists only when $n$ is even. $a \\oplus a = 0$ $a \\oplus 0 = a$ First and foremost, it can be proven that $(a \\oplus b) + (b \\oplus c) + (a \\oplus c)$ is always even, for all possible non-negative values of $a$, $b$ and $c$. Firstly, $a \\oplus b$ and $a+b$ have the same parity, since $a + b = a \\oplus b + 2 \\cdot (a \\text{&} b)$. Therefore, $(a \\oplus b) + (b \\oplus c) + (a \\oplus c)$ has the same parity as $(a+b)+(b+c)+(a+c)=2 \\cdot (a+b+c)$. Therefore, if $n$ is even, one possible solution is $a=0$, $b=0$ and $c=\\frac{n}{2}$. In this case, $(a \\oplus b) + (b \\oplus c) + (a \\oplus c)= 0+\\frac{n}{2}+\\frac{n}{2}=n$. Otherwise, there are no solutions. Time complexity per testcase: $O(1)$.",
    "code": "\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid testcase(){\n    int n;\n    cin>>n;\n\n    if(n%2==0)\n        cout<<\"0 \"<<n/2<<' '<<n/2<<'\\n';\n    else\n        cout<<\"-1\\n\";\n}\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--)\n        testcase();\n    return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1699",
    "index": "B",
    "title": "Almost Ternary Matrix",
    "statement": "You are given two \\textbf{even} integers $n$ and $m$. Your task is to find \\textbf{any} binary matrix $a$ with $n$ rows and $m$ columns where every cell $(i,j)$ has \\textbf{exactly} two neighbours with a different value than $a_{i,j}$.\n\nTwo cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell $(x,y)$ are: $(x-1,y)$, $(x,y+1)$, $(x+1,y)$ and $(x,y-1)$.\n\nIt can be proven that under the given constraints, an answer always exists.",
    "tutorial": "The general construction consists of a $2 \\times 2$ checkerboard with a $1$-thick border. Here is the intended solution for $n=6$ and $m=8$: Time complexity per testcase: $O(nm)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nvoid testcase(){\n    ll n,m;\n    cin>>n>>m;\n\n    for(ll i=1;i<=n;i++){\n        for(ll j=1;j<=m;j++){\n            cout<<((i%4<=1)!=(j%4<=1))<<\" \\n\"[j==m];\n        }\n    }\n}\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--)\n        testcase();\n    return 0;\n}\n",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "matrices"
    ],
    "rating": 900
  },
  {
    "contest_id": "1699",
    "index": "C",
    "title": "The Third Problem",
    "statement": "You are given a permutation $a_1,a_2,\\ldots,a_n$ of integers from $0$ to $n - 1$. Your task is to find how many permutations $b_1,b_2,\\ldots,b_n$ are similar to permutation $a$.\n\nTwo permutations $a$ and $b$ of size $n$ are considered similar if for all intervals $[l,r]$ ($1 \\le l \\le r \\le n$), the following condition is satisfied: $$\\operatorname{MEX}([a_l,a_{l+1},\\ldots,a_r])=\\operatorname{MEX}([b_l,b_{l+1},\\ldots,b_r]),$$ where the $\\operatorname{MEX}$ of a collection of integers $c_1,c_2,\\ldots,c_k$ is defined as the smallest non-negative integer $x$ which does not occur in collection $c$. For example, $\\operatorname{MEX}([1,2,3,4,5])=0$, and $\\operatorname{MEX}([0,1,2,4,5])=3$.\n\nSince the total number of such permutations can be very large, you will have to print its remainder modulo $10^9+7$.\n\nIn this problem, a permutation of size $n$ is an array consisting of $n$ distinct integers from $0$ to $n-1$ in arbitrary order. For example, $[1,0,2,4,3]$ is a permutation, while $[0,1,1]$ is not, since $1$ appears twice in the array. $[0,1,3]$ is also not a permutation, since $n=3$ and there is a $3$ in the array.",
    "tutorial": "Let $p[x]$ be the position of $x$ in permutation $a$. Since $MEX([a_{p[0]}])=1$, the only possible position of $0$ in permutation $b$ is exactly $p[0]$. Continuing this line of thought, where can $1$ be placed in permutation $b$? Without loss of generality, we will assume that $p[0] \\lt p[1]$. If $p[2] \\lt p[0]$, then how many possible positions can $2$ have in permutation $b$? If $p[0] \\lt p[2] \\lt p[1]$, then how many possible positions can $2$ have in permutation $b$? If $p[2] \\gt p[1]$, then how many possible positions can $2$ have in permutation $b$? Let $p[x]$ be the position of $x$ in permutation $a$. Since $MEX([a_{p[0]}])=1$, the only possible position of $0$ in permutation $b$ is exactly $p[0]$. Without loss of generality, we will assume that $p[0] \\lt p[1]$. For every interval $[l,r]$ ($l \\le p[0] \\lt p[1]\\le r$), $MEX([b_l,\\ldots,b_r])$ must be at least $2$. For every other interval, $MEX([b_l,\\ldots,b_r])$ cannot exceed $2$. The only position for $1$ which satisfies both of these constraints is exactly $p[1]$. Let's consider the current interval $[l,r]$ as being $[p[0],p[1]]$. If $p[2] \\in [l,r]$, we can say that, for every interval $[x,y]$ ($x \\le l \\lt r \\le y$), $MEX([b_x,\\ldots,b_y])$ must be at least $3$. Similarly, for every other interval, $MEX([b_x,\\ldots,b_y])$ cannot exceed $3$. Both of these constraints are only met if $2$ occurs in permutation $b$ on some position $p \\in [l,r]$. Since only $2$ positions are currently occupied in $[l,r]$, the total number of similar permutations will be multiplied by $(r-l+1)-2$. Otherwise, $2$ can be placed in permutation $b$ only on $p[2]$. Additionally, the current interval will be \"extended\" to include $p[2]$, resuting in either $[p[2],r]$ or $[l,p[2]]$. After processing $0,1, \\ldots, k-2$ and $k-1$, the algorithm for processing $k$ is very similar to the one presented earlier. If $p[k] \\in [l,r]$, the answer gets multiplied by $(r-l+1)-k$. Otherwise, the current interval is extended to include $p[k]$. Time complexity per testcase: $O(n)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nconst ll NMAX=1e5+5,MOD=1e9+7;\nll v[NMAX],pos[NMAX];\nvoid tc(){\n    ll n,l,r,ans=1;\n    cin>>n;\n    for(ll i=0;i<n;i++){\n        cin>>v[i];\n        pos[v[i]]=i;\n    }\n    l=r=pos[0];\n    for(ll i=1;i<n;i++){\n        if(pos[i]<l) l=pos[i];\n        else if(pos[i]>r) r=pos[i];\n        else ans=ans*(r-l+1-i)%MOD;\n    }\n    cout<<ans<<'\\n';\n}\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(0);\n    ll t;\n    cin>>t;\n    while(t--)\n        tc();\n    return 0;\n}\n",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1699",
    "index": "D",
    "title": "Almost Triple Deletions",
    "statement": "You are given an integer $n$ and an array $a_1,a_2,\\ldots,a_n$.\n\nIn one operation, you can choose an index $i$ ($1 \\le i \\lt n$) for which $a_i \\neq a_{i+1}$ and delete both $a_i$ and $a_{i+1}$ from the array. After deleting $a_i$ and $a_{i+1}$, the remaining parts of the array are concatenated.\n\nFor example, if $a=[1,4,3,3,6,2]$, then after performing an operation with $i=2$, the resulting array will be $[1,3,6,2]$.\n\nWhat is the maximum possible length of an array of \\textbf{equal} elements obtainable from $a$ by performing several (perhaps none) of the aforementioned operations?",
    "tutorial": "Consider the opposite problem: What is the smallest possible length of a final array? For which arrays is the smallest possible final length equal to $0$? Considering the second hint, it is possible to completely remove some subarrays from the array. Lemma: An array $a_1,a_2,\\ldots, a_n$ can be fully deleted via a sequence of operations if and only if it satisfies both of the following constraints: $n$ is even $n$ is even The maximum frequency of any element in the array is at most $\\frac n2$. The maximum frequency of any element in the array is at most $\\frac n2$. If $n$ is odd, then any final array will also have an odd length, which can't be $0$. An optimal strategy is to always delete one of the most frequent elements and any one of its neighbours. If the most frequent element occurs $k \\gt \\frac n2$ times, then the final array will have at least $n-2 \\cdot (n-k)=2\\cdot k - n \\gt 0$ elements. Otherwise, this strategy ensures the full deletion of the array, since, after performing an operation, it is impossible for an element to occur more than $\\frac {n-2}{2}$ times in the array. Since the maximum frequency of a value for every subarray $[a_l,a_{l+1},\\ldots,a_r]$ can be computed in $O(n^2)$, it is possible to precompute all subarrays which can be deleted via a sequence of operations. Let $dp[i]$ be the maximum length of a final array consisting of $a_i$ and some subsequence from the first $i-1$ elements. Initially, $dp[i]$ is set to $1$ if the prefix $[a_1,a_2,\\ldots, a_{i-1}]$ can be fully deleted. Otherwise, $dp[i]=0$. For every pair of indices $i$ and $j$ ($1 \\le j \\lt i \\le n, a_i=a_j$), if we can fully delete the subarray $[a_{j+1},a_{j+2},\\ldots a_{i-1}]$, then we can append $a_i$ to any final array ending in $a_j$. Naturally, $dp[i]$ will be strictly greater than $dp[j]$. This gives us the following recurrence: $dp[i]=\\max_{j=1}^{i-1}(dp[j]>0 \\text{ and } a_i=a_j \\text{ and } [a_{j+1},a_{j+2},\\ldots,a_{i-1}] \\text{ is deletable}) \\cdot (dp[j]+1)$ If we define a final array as a subsequence of equal elements from the array $a$, to which $a_{n+1}$ is forcefully appended, then the final answer can be written as $dp[n+1]-1$. Note that, when computing $dp[n+1]$, $a_j$ should not be compared to $a_{n+1}$. Total time complexity per testcase: $O(n^2)$.",
    "code": "\n#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nconst ll NMAX=5e3+5;\nll dp[NMAX],v[NMAX],fr[NMAX];\nvoid testcase(){\n    ll n,ans=0;\n    cin>>n;\n    for(ll i=1;i<=n;i++){\n        cin>>v[i];\n        dp[i]=0;\n    }\n    for(ll i=0;i<=n;i++){\n\n        if(i && dp[i]==0) continue;\n        ll frmax=0;\n        for(int j=1;j<=n;j++) fr[j]=0;\n\n        for(int j=i+1;j<=n;j++){\n            if((j-i)%2 && frmax<=(j-i)/2 && (i==0 || v[i]==v[j]))\n                dp[j]=max(dp[j],dp[i]+1);\n            frmax=max(frmax,++fr[v[j]]);\n        }\n    }\n\n    ll frmax=0;\n    for(int j=1;j<=n;j++) fr[j]=0;\n\n    for(int i=n;i>=0;i--){\n        if((n-i)%2==0 && frmax<=(n-i)/2) ans=max(ans,dp[i]);\n        frmax=max(frmax,++fr[v[i]]);\n    }\n    cout<<ans<<'\\n';\n}\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--)\n        testcase();\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1699",
    "index": "E",
    "title": "Three Days Grace",
    "statement": "Ibti was thinking about a good title for this problem that would fit the round theme (numerus ternarium). He immediately thought about the third derivative, but that was pretty lame so he decided to include the best band in the world — Three Days Grace.\n\nYou are given a multiset $A$ with initial size $n$, whose elements are integers between $1$ and $m$. In one operation, do the following:\n\n- select a value $x$ from the multiset $A$, then\n- select two integers $p$ and $q$ such that $p, q > 1$ and $p \\cdot q = x$. Insert $p$ and $q$ to $A$, delete $x$ from $A$.\n\nNote that the size of the multiset $A$ increases by $1$ after each operation.\n\nWe define the balance of the multiset $A$ as $\\max(a_i) - \\min(a_i)$. Find the minimum possible balance after performing any number (possible zero) of operations.",
    "tutorial": "We can see that in the final multiset, each number $A_i$ from the initial multiset will be assigned to a subset of values $x_1, x_2,....,x_k$ such that their product is $A_i$. Every such multiset can be created. Also let $vmax$ be the maximum value in the initial multiset. Consider iterating through the minimum value. To get the best maximum value that has this minimum we fixed, one can use dynamic programming $dp[i][j] =$the best possible maximum if we had number $i$ and the minimum value in the product is $j$, $j$ is a divisor of $i$. This dp can be calculated in $O(vmax \\cdot log^2(vmax))$ for all values. We can also process all updates when incrementing the minimum and keeping the result with a total effort of $O(vmax \\cdot log^2(vmax))$. Thus we have a total time complexity of $O(vmax \\cdot log^2(vmax))$. However, this ( we hope ) won't pass. Here is a way more elegant solution ( thanks to ntherner ): To get things straight, we observe that when we decompose a number, we just actually write it as a product of numbers. We still consider fixing the minimum value used in our multiset, call it $L$. We will further consider that we iterate $L$ from the greatest possible value (i.e. $vmax$) to $1$, and as such, we try at each iteration to calculate the minimum possible value which will appear in any decomposition as the maximum value in said decomposition. We shall now retain for each element the minimal maximum value in a decomposition where the minimum of that decomposition is $L$, let's say for element $i$, this value will be stored in $dp[i]$. Naturally, after calculating this value for every number, we now try to tweak the calculated values as to match the fact that, after this iteration concluded, we will decrease $L$. For further simplicity, we denote $L' = L - 1$. So, we changed the minimum value allowed. What changes now? Well, it is easy to see that any element that is not divisible by $L'$ won't be affected by this modification, as much as it is impossible to include $L'$ in any decomposition of said number. So it remains to modify the multiples of $L'$. Let's take a such number, $M$. How can we modify $dp[M]$? Well, we can include $L'$ in the decomposition as many times as we want, and then when we decide to stop including it, we remain with a number which needs to be further decomposed. The attributed maximum of this value should already be calculated, so we can consider it as a new candidate for the update of $dp[M]$. This idea could be implemented simpler by going through multiples of $L'$, and for an element, updating $dp[i]$ with $dp[i / L']$ (by taking the minimum of either) We now need for each iteration to keep track of the attributed maximums of each element that actually appears in our initial list. This can be done by keeping a frequency of all these elements, and after all updates, taking the (already known) maximum of the previous iteration and decreasing it until we find another element that actually appears in our set (this can be verified by simply checking the frequency). This is correct, as much as all the values gradually decrease as $L$ decreases, so their maximum would have to decrease as well. Final time complexity: $O(vmax * log(vmax))$",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\n\nconst int nmax = 5e6 + 5;\nint appear[nmax];\nint mxval[nmax];\nint toggle[nmax];\n\nint main()\n{\n    cin.tie(nullptr)->sync_with_stdio(false);\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        int n, m, mn = nmax, mx = 0;\n        cin >> n >> m;\n        for (int i = 0; i <= m; ++i)\n        {\n            appear[i] = toggle[i] = mxval[i] = 0;\n        }\n        for (int i = 0, x; i < n; i++)\n        {\n            cin >> x;\n            appear[x] = 1;\n            toggle[x] = 1;\n            mn = min(mn, x);\n            mx = max(mx, x);\n        }\n        for (int i = 0; i <= mx; i++)\n        {\n            mxval[i] = i;\n        }\n        int ptr = mx, smax = mx - mn;\n        for (int i = mx; i >= 1; i--)\n        {\n            for (ll j = (ll)i * i; j <= mx; j += i)\n            {\n                if (appear[j])\n                    toggle[mxval[j]]--;\n                mxval[j] = min(mxval[j], mxval[j / i]);\n                if (appear[j])\n                    toggle[mxval[j]]++;\n            }\n            while (toggle[ptr] == 0)\n                ptr--;\n            if (i <= mn)\n                smax = min(smax, ptr - i);\n        }\n        cout << smax << '\\n';\n    }\n}\n",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1700",
    "index": "A",
    "title": "Optimal Path",
    "statement": "You are given a table $a$ of size $n \\times m$. We will consider the table rows numbered from top to bottom from $1$ to $n$, and the columns numbered from left to right from $1$ to $m$. We will denote a cell that is in the $i$-th row and in the $j$-th column as $(i, j)$. In the cell $(i, j)$ there is written a number $(i - 1) \\cdot m + j$, that is $a_{ij} = (i - 1) \\cdot m + j$.\n\nA turtle initially stands in the cell $(1, 1)$ and it wants to come to the cell $(n, m)$. From the cell $(i, j)$ it can in one step go to one of the cells $(i + 1, j)$ or $(i, j + 1)$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path.\n\nFor example, with $n = 2$ and $m = 3$ the table will look as shown above. The turtle can take the following path: $(1, 1) \\rightarrow (1, 2) \\rightarrow (1, 3) \\rightarrow (2, 3)$. The cost of such way is equal to $a_{11} + a_{12} + a_{13} + a_{23} = 12$. On the other hand, the paths $(1, 1) \\rightarrow (1, 2) \\rightarrow (2, 2) \\rightarrow (2, 1)$ and $(1, 1) \\rightarrow (1, 3)$ are incorrect, because in the first path the turtle can't make a step $(2, 2) \\rightarrow (2, 1)$, and in the second path it can't make a step $(1, 1) \\rightarrow (1, 3)$.\n\nYou are asked to tell the turtle a minimal possible cost of a path from the cell $(1, 1)$ to the cell $(n, m)$. Please note that the cells $(1, 1)$ and $(n, m)$ are a part of the way.",
    "tutorial": "Let's notice that the optimal path looks like the following: $(1, 1) \\rightarrow (1, 2) \\rightarrow \\ldots \\rightarrow (1, m) \\rightarrow (2, m) \\rightarrow \\ldots \\rightarrow (n, m)$. The proof is relatively easy - all paths from $(1, 1)$ to $(n, m)$ consist of $n + m - 1$ cells and in the optimal path we have minimized all numbers in the path. The cost of such path is equal to $1 + 2 + \\ldots + m + 2 \\cdot m + \\ldots + n \\cdot m = \\sum\\limits_{i=1}^{m - 1} i + m \\cdot \\sum\\limits_{i=1}^n i$. This sum can be found in $O(n + m)$ by just summarizing all numbers, or it can be found in $O(1)$ if you remember that $\\sum\\limits_{i=1}^n = \\frac{n \\cdot (n + 1)}{2}$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1700",
    "index": "B",
    "title": "Palindromic Numbers ",
    "statement": "During a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome.\n\nRecall that a number is called a palindrome, if it reads the same right to left and left to right. For example, numbers $121, 66, 98989$ are palindromes, and $103, 239, 1241$ are not palindromes.\n\nAlina understands that a valid number always exist. Help her find one!",
    "tutorial": "Let X be the number in input. Consider two cases: first digit of X is 9 and not 9. If the first digit of input number is not 9, we can simply output 9999...999 ($n$ digits) - X. If the first digit is 9, we can output 111...1111 ($n + 1$ digits) - X. It is easy to show that this number will be exactly $n$-digit. To simplify implementation, we can first find 9999...999 - X by subtracting all digits of X from 9, and than if this number is not $n$-digit, add 111...1111 - 9999...999 = 11111...1112 to it. Overall complexity will be $\\mathcal{O}(n)$.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1700",
    "index": "C",
    "title": "Helping the Nature",
    "statement": "Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.\n\nThere are $n$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $a_1, a_2, \\dots, a_n$. Leon has learned three abilities which will help him to dry and water the soil.\n\n- Choose a position $i$ and decrease the level of moisture of the trees $1, 2, \\dots, i$ by $1$.\n- Choose a position $i$ and decrease the level of moisture of the trees $i, i + 1, \\dots, n$ by $1$.\n- Increase the level of moisture of all trees by $1$.\n\nLeon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $0$.",
    "tutorial": "Consider the difference array $d_i = a_{i + 1} - a_{i}$. Note that for $d_i > 0$ it is necessary to make $d_i$ subtractions on the suffix. For $d_i < 0$, you need to make $-d_i$ subtractions on the prefix. Let's add them to the answer. Let's calculate the final array using prefix and suffix sums for $O(n)$. Note that it will consist of the same numbers. Add $|x|$ to the answer, where $x$ is the resulting number.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1700",
    "index": "D",
    "title": "River Locks",
    "statement": "Recently in Divanovo, a huge river locks system was built. There are now $n$ locks, the $i$-th of them has the volume of $v_i$ liters, so that it can contain any amount of water between $0$ and $v_i$ liters. Each lock has a pipe attached to it. When the pipe is open, $1$ liter of water enters the lock every second.\n\nThe locks system is built in a way to immediately transfer all water exceeding the volume of the lock $i$ to the lock $i + 1$. If the lock $i + 1$ is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river.\n\n\\begin{center}\n{\\small The picture illustrates $5$ locks with two open pipes at locks $1$ and $3$. Because locks $1$, $3$, and $4$ are already filled, effectively the water goes to locks $2$ and $5$.}\n\\end{center}\n\nNote that the volume of the $i$-th lock may be greater than the volume of the $i + 1$-th lock.\n\nTo make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in $q$ independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the $j$-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after $t_j$ seconds.\n\nPlease help the mayor to solve this tricky problem and answer his queries.",
    "tutorial": "To begin with, we note that it makes sense to open only some pipe prefix, because we need to fill all the locks, and more left pipes affect the total volume of the baths, which is obviously beneficial. Let's enumerate how many pipes we will open, namely which prefix of pipes we will open and calculate $dp_i$ - how long it will take to fill the first $i$ locks if the first $i$ pipes are open. Let's introduce an auxiliary array $pref_i$ - the sum of the capacities of the gateways on the prefix $i$. Then $dp_i = max(dp_{i - 1},\\ \\lceil pref_i / i \\rceil)$. Let's see why this is so. We need all gateways on prefix $i - 1$ to be filled, and also that the $i$-th gateway be filled. Note that if the $i$-th gateway does not have time to fill up in the time $dp_{i - 1}$, then it will fill up in the time $\\lceil pref_i / i \\rceil$ (filling will occur at the time $pref_i / i$, but since in the condition we are asked about integer times, we can round up and not use real arithmetic), it turns out when the required amount of water is poured into all the locks in total from all pipes. Now knowing $dp_i$ for all $i$ open we can similarly calculate when all n gateways are full. For $i$ this will be $max(dp_i,\\ \\lceil pref_n / i \\rceil)$. It is also obvious that when an additional pipe is opened, the time will not increase, therefore we can do a bin search by time and find out the answer for the desired request. If the request $t$ is less than the minimum filling time for the locks (when all pipes are open), then you need to print $-1$. Total running time O($n + q log(n)$).",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1700",
    "index": "E",
    "title": "Serega the Pirate",
    "statement": "Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.\n\nA puzzle is a table of $n$ rows and $m$ columns, whose cells contain each number from $1$ to $n \\cdot m$ exactly once.\n\nTo solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $i$, denote the position of the first occurrence of this cell in the sequence as $t_i$. The sequence solves the puzzle, if $t_1 < t_2 < \\dots < t_{nm}$. In other words, the cell with number $x$ should be first visited before the cell with number $x + 1$ for each $x$.\n\nLet's call a puzzle solvable, if there exists at least one suitable sequence.\n\nIn one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $0$, $1$, or at least $2$. In the case, where $1$ move is required, please also find the number of suitable cell pairs to swap.",
    "tutorial": "We need to find a simple criteria of a solvable puzzle. It can be shown that for every cell, except cell with value $1$, it should have a neighbour with a smaller value. Indeed, if the puzzle is solvable, a cell going before the first occurence of our cell always has the smaller value. Conversely, if each cell has a smaller neighbor, one can list cells one at a time, and there will always be a path to the next cell along already visited cells with lower numbers. Let's call a cell bad, if it's value is not $1$ and it doesn't have a neighbour with a smaller value. Consider any bad cell. Let's notice, that the pair that we swap should contain either the bad cell itself, or its neighbour, otherwise that bad cell will stay bad. That way we have $5nm$ pairs of candidates, for each of which we'll run a check if the resulting puzzle is solvable. Now we'll learn how to quickly understand, if the puzzle became solvable after a swap. For this we'll keep the amount of bad cells. After the swap, the state can be changed only for these cells and their neighbours. Let's recalc the amount of bad cells and check if it's zero. The resulting complexity is $O(nm)$",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1700",
    "index": "F",
    "title": "Puzzle",
    "statement": "Pupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with $2$ rows and $n$ columns, every element of which is either $0$ or $1$. In one move you can swap two values in neighboring cells.\n\nMore formally, let's number rows $1$ to $2$ from top to bottom, and columns $1$ to $n$ from left to right. Also, let's denote a cell in row $x$ and column $y$ as $(x, y)$. We consider cells $(x_1, y_1)$ and $(x_2, y_2)$ neighboring if $|x_1 - x_2| + |y_1 - y_2| = 1$.\n\nAlice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.",
    "tutorial": "We are asked to find a minimum cost perfect matching between $1$'s in the matrices, where the cost between $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$. Notice that the answer exists only if the number of $1$'s is equal in both matrices. Consider that this is the case. Notice that every $1$ either stays in its original row or changes it in a single operation. For simplicity let's assume that all operations of that kind are performed in the beginning. Let's denote $\\Delta_{i,j}$ as the difference between the $j$-th prefix sum in $i$-th row of the matrices. If the final row for each $1$ is fixed, then the answer is equal to $S + \\sum_{i=1}^n (|\\Delta_{1,i}| + |\\Delta_{2,i}|)$, where $S$ in the number of $1$'s that changed its row. Now let's look at what happens when we change the row of a $1$. For simplicity let's assume that it was in a cell $(1, j)$. Then after the swap we have to increment $S$ by $1$, decrement all $\\Delta_{1,j}, \\dots \\Delta_{1,n}$ by $1$, and increment all $\\Delta_{2,j}, \\dots \\Delta_{2,n}$ by $1$. Now let's solve the following problem: we are given $\\Delta_{1,i}$ and $\\Delta_{2,i}$ and in one operation we can increment some suffix by $1$ and decrement the same suffix in the other array by $1$. The goal is to minimize $S + \\sum_{i=1}^n (|\\Delta_{1,i}| + |\\Delta_{2,i}|)$. Notice that the following greedy algorithm works: iterate through columns from left to right and while $\\Delta_{1,i}$ and $\\Delta_{2,i}$ have different signs, decrement the suffix of one that's greater and increment suffix of one that's lower. Now let's prove that this algorithm minimizes the target sum. For this consider some optimal sequence of operations. It doesn't matter in which order operations are performed, so let's assume they are performed from left to right, and are accumulated in a single element for the same suffix. If the sequences differ, denote $i$ as the first such position. Note that before that all $\\Delta_{1,i}$ and $\\Delta_{2,i}$ are the same in both our answer and the optimal one. Suppose that in the optimal answer we incremented $i$-th suffix of $\\Delta_1$ by $k$ and decremented $i$-th suffix of $\\Delta_2$ by $k$. Then the target sum will increase by $|k| + |\\Delta_{1,i} + k| + |\\Delta_{1,i} - k|$. Consider the following cases: $\\Delta_{1,i} \\ge 0$ and $\\Delta_{2,i} \\ge 0$ or $\\Delta_{1,i} \\le 0$ and $\\Delta_{2,i} \\le 0$. By triangle inequality $|\\Delta_{1,i} + k| + |\\Delta_{2,i} - k| \\ge |\\Delta_{1,i} + \\Delta_{2,i}| = |\\Delta_{1,i}| + |\\Delta_{2,i}|$, which means that those $k$ operations could be performed on the $i+1$-st suffix and that wouldn't increase the answer. $\\Delta_{1,i} < 0$ and $\\Delta_{2,i} > 0$. Here if $k < 0$, $|\\Delta_{1,i} + k| + |\\Delta_{2,i} - k| = 2|k| + |\\Delta_{1,i}| + |\\Delta_{2,i}|$, which means that those $k$ operations could be performed on the $i+1$-st suffix and that wouldn't increase the answer. Now if $k \\ge 0$. We can assume that $k \\le \\min(-\\Delta_{1,i}, \\Delta_{2,i})$, otherwise we will perform an operation on values with the same sign, which we already shown can be done later on. Then $|k| + |\\Delta_{1,i} + k| + |\\Delta_{2,i} - k| = k + (-k - \\Delta_{1,i}) + (\\Delta_{2,i} - k) = -k - \\Delta_{1,i} + \\Delta_{2,i}$. Greedy algorithm suggests doing exactly $t = \\min(-\\Delta_{1,i}, \\Delta_{2,i})$ operations. Note that if we perform $t$ operations on suffix $i$ and $t-k$ operations on suffix $i+1$, we will add $(-t - \\Delta_{1,i} + \\Delta_{2,i}) + (t - k) = -k - \\Delta_{1,i} + \\Delta_{2,i}$ to the answer and get the same state as the optimal answer. This means that we can do $t$ operations and not increase the answer. $\\Delta_{1,i} > 0$ and $\\Delta_{2,i} < 0$. This case can be analyzed in the same way. Let's come back to the original problem. Described greedy algorithm finds a lower bound on the answer. Let's show that it is always possible to achieve it when the operations are allowed only for moving $1$'s between rows and the number of $1$s in each row at the end should be the same. For this note that we can \"perform\" operations on $1$'s from the second matrix, if we reverse their order and append to the end of the sequence for the first matrix. Now note that if on some prefix $i$ $\\Delta_{1,i}$ and $\\Delta_{2,i}$ have the same sign, but on prefix $i+1$ the signs differ, there has to be at least a single $1$ in column $i+1$, and we can perform the operation suggested by the greedy algorithm. Finally, if the answer exists it is true that $\\Delta_{1,n} + \\Delta_{2,n} = 0$, and if $\\Delta_{1,n}$ and $\\Delta_{2,n}$ have the same sign at the end this means that they are both $0$, which means that the constructed answer is correct. This solution works in $O(n)$ time.",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1701",
    "index": "A",
    "title": "Grass Field",
    "statement": "There is a field of size $2 \\times 2$. Each cell of this field can either contain grass or be empty. The value $a_{i, j}$ is $1$ if the cell $(i, j)$ contains grass, or $0$ otherwise.\n\nIn one move, you can choose \\textbf{one row} and \\textbf{one column} and cut all the grass in this row and this column. In other words, you choose the row $x$ and the column $y$, then you cut the grass in all cells $a_{x, i}$ and all cells $a_{i, y}$ for all $i$ from $1$ to $2$. After you cut the grass from a cell, it becomes empty (i. e. its value is replaced by $0$).\n\nYour task is to find the minimum number of moves required to cut the grass in all non-empty cells of the field (i. e. make all $a_{i, j}$ zeros).\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If there is no grass on the field, the answer is $0$. If the whole field is filled with grass, the answer is $2$, because there always will be one cell that we can't clear with one move. Otherwise, the answer is $1$. This is because if the cell $(i, j)$ is empty, we can just choose other row than $i$ and other column than $j$ and clear three other cells in one move.",
    "code": "for _ in range(int(input())):\n    a = [list(map(int, input().split())) for i in range(2)]\n    cnt = sum([sum(a[i]) for i in range(2)])\n    if cnt == 0:\n        print(0)\n    elif cnt == 4:\n        print(2)\n    else:\n        print(1)",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1701",
    "index": "B",
    "title": "Permutation",
    "statement": "Recall that a permutation of length $n$ is an array where each element from $1$ to $n$ occurs exactly once.\n\nFor a fixed positive integer $d$, let's define the cost of the permutation $p$ of length $n$ as the number of indices $i$ $(1 \\le i < n)$ such that $p_i \\cdot d = p_{i + 1}$.\n\nFor example, if $d = 3$ and $p = [5, 2, 6, 7, 1, 3, 4]$, then the cost of such a permutation is $2$, because $p_2 \\cdot 3 = p_3$ and $p_5 \\cdot 3 = p_6$.\n\nYour task is the following one: for a given value $n$, find the permutation of length $n$ and the value $d$ with maximum possible cost (over all ways to choose the permutation and $d$). If there are multiple answers, then print any of them.",
    "tutorial": "Let's notice that for a fixed value of $d$, the answer (the cost of permutation) does not exceed $\\frac{n}{d}$, because only numbers from $1$ to $\\frac{n}{d}$ can have a pair. It turns out that it is always possible to construct a permutation with the cost of exactly $\\frac{n}{d}$. It is enough to consider the number \"chains\" of the form: $x, x \\cdot d, x \\cdot d^2, \\dots, x \\cdot d^k$, where $x \\neq 0 \\pmod d$. It is not difficult to understand that each number is included in exactly one such chain. Therefore, if we append the chains one after another, then in such a permutation the answer will be equal to $n - \\mathrm{the\\_number\\_of\\_ chains}$ (because all numbers will have a pair except the last element in the chain). The number of chains is equal to $n - \\frac{n}{d}$, which means the cost of the permutation is equal to $n - (n - \\frac{n}{d}) = \\frac{n}{d}$. By choosing $d = 2$ the permutation will have the maximum possible cost.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    cout << 2 << '\\n';\n    for (int i = 1; i <= n; ++i) if (i % 2 != 0)\n      for (int j = i; j <= n; j *= 2)\n        cout << j << ' ';\n    cout << '\\n';\n  }\n} ",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1701",
    "index": "C",
    "title": "Schedule Management",
    "statement": "There are $n$ workers and $m$ tasks. The workers are numbered from $1$ to $n$. Each task $i$ has a value $a_i$ — the index of worker who is proficient in this task.\n\nEvery task should have a worker assigned to it. If a worker is proficient in the task, they complete it in $1$ hour. Otherwise, it takes them $2$ hours.\n\nThe workers work in parallel, independently of each other. Each worker can only work on one task at once.\n\nAssign the workers to all tasks in such a way that the tasks are completed as early as possible. The work starts at time $0$. What's the minimum time all tasks can be completed by?",
    "tutorial": "The statement should instantly scream binary search at you. Clearly, if you can assign the workers in such a way that the tasks are completed by time $t$, you can complete them all by $t+1$ or more as well. How to check if the tasks can be completed by some time $t$? What that means is that all workers have $t$ hours to work on some tasks. If all tasks took $2$ hours to complete, then each of them could complete $\\lfloor \\frac t 2 \\rfloor$ of them. Thus, together they would be able to complete $\\lfloor \\frac t 2 \\rfloor \\cdot n$ tasks. How to incorporate the $1$-hour tasks into that? Well, we can redistribute the tasks in such a way that each worker first completes the tasks they are proficient in, then some other tasks if they have more time. So the general idea is the following. Let each worker $i$ complete $min(t, \\mathit{cnt}_i)$ $1$-hour tasks, where $\\mathit{cnt}_i$ is the number of tasks the $i$-th worker is proficient in. Then remember how many $2$-hour tasks they can complete, which is $\\lfloor \\frac{t - min(t, \\mathit{cnt}_i)}{2} \\rfloor$. Finally, remember how many tasks that they are proficient in they didn't have time to complete, which is $\\mathit{cnt}_i - min(t, \\mathit{cnt}_i)$. If the sum of the number of incomplete tasks doesn't exceed the sum of the number of tasks they have time to complete, then everything can be completed in time $t$. Worst case, it can take up to $2m$ hours to complete everything - if you assign all tasks to a single worker, and they are not proficient in any of them. Overall complexity: $O(n \\log m)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--){\n\t\tint n, m;\n\t\tscanf(\"%d%d\", &n, &m);\n\t\tvector<int> a(m);\n\t\tforn(i, m){\n\t\t\tscanf(\"%d\", &a[i]);\n\t\t\t--a[i];\n\t\t}\n\t\tvector<int> cnt(n);\n\t\tforn(i, m) ++cnt[a[i]];\n\t\tauto check = [&](int t){\n\t\t\tlong long fr = 0, need = 0;\n\t\t\tforn(i, n){\n\t\t\t\tif (t >= cnt[i])\n\t\t\t\t\tfr += (t - cnt[i]) / 2;\n\t\t\t\telse\n\t\t\t\t\tneed += cnt[i] - t;\n\t\t\t}\n\t\t\treturn need <= fr;\n\t\t};\n\t\tint l = 0, r = 2 * m;\n\t\tint res = -1;\n\t\twhile (l <= r){\n\t\t\tint m = (l + r) / 2;\n\t\t\tif (check(m)){\n\t\t\t\tres = m;\n\t\t\t\tr = m - 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tl = m + 1;\n\t\t\t}\n\t\t}\n\t\tprintf(\"%d\\n\", res);\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1701",
    "index": "D",
    "title": "Permutation Restoration",
    "statement": "Monocarp had a permutation $a$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once).\n\nThen Monocarp calculated an array of integers $b$ of size $n$, where $b_i = \\left\\lfloor \\frac{i}{a_i} \\right\\rfloor$. For example, if the permutation $a$ is $[2, 1, 4, 3]$, then the array $b$ is equal to $\\left[ \\left\\lfloor \\frac{1}{2} \\right\\rfloor, \\left\\lfloor \\frac{2}{1} \\right\\rfloor, \\left\\lfloor \\frac{3}{4} \\right\\rfloor, \\left\\lfloor \\frac{4}{3} \\right\\rfloor \\right] = [0, 2, 0, 1]$.\n\nUnfortunately, the Monocarp has lost his permutation, so he wants to restore it. Your task is to find a permutation $a$ that corresponds to the given array $b$. If there are multiple possible permutations, then print any of them. The tests are constructed in such a way that least one suitable permutation exists.",
    "tutorial": "We have $b_i = \\left\\lfloor \\frac{i}{a_i} \\right\\rfloor$ for each $i$, we can rewrite this as follows: $a_i \\cdot b_i \\le i < a_i \\cdot (b_i+1)$, or $\\frac{i}{b_i + 1} < a_i \\le \\frac{i}{b_i}$. From here we can see that for each $i$ there is a segment of values that can be assigned to $a_i$. So we have to match each number from $1$ to $n$ with one of these segments. To solve this problem, we can iterate from $1$ to $n$. Let the current number be $x$, then it can be paired with a segment $i$ without a pair such that $\\frac{i}{b_i + 1} < x \\le \\frac{i}{b_i}$ and the right bound is minimum among all such segments (because it will be the first to end among these segments). To do this, it is enough to maintain a set with open segments that have not yet been assigned a pair and choose from it a segment with the minimum right bound. Before running this method, you can sort the segments by their left border so they can be easily added to this set when we go from $x$ to $x+1$ (we will need to insert all segments that begin with $x+1$, that's why it's convenient to have them sorted by their left border beforehand).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n);\n    for (int& x : b) cin >> x;\n    vector<pair<int, int>> ev(n);\n    for (int i = 0; i < n; ++i)\n      ev[i] = {(i + 1) / (b[i] + 1) + 1, i};\n    sort(ev.begin(), ev.end());\n    set<pair<int, int>> s;\n    int j = 0;\n    for (int i = 1; i <= n; ++i) {\n      while (j < n && ev[j].first == i) {\n        int id = ev[j++].second;\n        s.insert({b[id] ? (id + 1) / b[id] : n, id});\n      }\n      a[s.begin()->second] = i;\n      s.erase(s.begin());\n    }\n    for (int& x : a) cout << x << ' ';\n    cout << '\\n';\n  }\n} ",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1701",
    "index": "E",
    "title": "Text Editor",
    "statement": "You wanted to write a text $t$ consisting of $m$ lowercase Latin letters. But instead, you have written a text $s$ consisting of $n$ lowercase Latin letters, and now you want to fix it by obtaining the text $t$ from the text $s$.\n\nInitially, the cursor of your text editor is at the end of the text $s$ (after its last character). In one move, you can do one of the following actions:\n\n- press the \"left\" button, so the cursor is moved to the left by one position (or does nothing if it is pointing at the beginning of the text, i. e. before its first character);\n- press the \"right\" button, so the cursor is moved to the right by one position (or does nothing if it is pointing at the end of the text, i. e. after its last character);\n- press the \"home\" button, so the cursor is moved to the beginning of the text (before the first character of the text);\n- press the \"end\" button, so the cursor is moved to the end of the text (after the last character of the text);\n- press the \"backspace\" button, so the character before the cursor is removed from the text (if there is no such character, nothing happens).\n\nYour task is to calculate the minimum number of moves required to obtain the text $t$ from the text $s$ using the given set of actions, or determine it is impossible to obtain the text $t$ from the text $s$.\n\nYou have to answer $T$ independent test cases.",
    "tutorial": "Of course, there is no need to press \"home\" more than once (and no need to press \"end\" at all), because suppose we did something on suffix, then pressed \"home\", did something on prefix and then pressed \"end\" and continue doing something on suffix. Then we can merge these two sequences of moves on suffix and press \"home\" after we did anything we wanted on suffix, and the answer will not get worse. Now, let's iterate over the position $pos$ at which we will press \"home\" (in range from $0$ to $n$). In other words, we iterate over the position till which we press only \"left\" and \"backspace\" to fix the suffix. So now we have the string $s[pos; n)$ and we want to get some suffix of $t$ from this string, but we actually don't know which suffix of $t$ we want. So let's iterate over the length of this suffix $suf$ in a range from $0$ to $m$. Now we have the string $s[pos; n)$ and the string $t[m - suf; m)$ and we have to check if we can obtain this suffix of $t$ from this suffix of $s$. This part can be precalculated in $O(n)$ greedily (we just can store for each suffix of $t$ the rightmost position in $s$ in which this suffix is obtainable). If we can obtain the current suffix, then we obviously can say the number of moves to do that - it is $n - pos$ and actually do not depend on the suffix length (because if we meet the character we need, we just press \"left\" and move to the next character, otherwise we press \"backspace\" and move to the next character deleting the one we don't need). After that, we press \"home\" and now we have to check if we can obtain $t[0; m - suf)$ from $s[0; pos)$. This part can also be precalculated greedily in $O(n)$ like the part with rightmost positions for suffixes. But the minimum number of moves required to obtain the prefix is tricky. Actually, if we consider these prefixes from right to left, we want to match as many characters from the beginning as possible. In other words, if we reverse $s[0; pos)$ and $t[0; m - suf)$, we want to find their longest common prefix, and this will be the number of characters we don't want to touch at all (and if it is the longest common prefix, it means that the next character is bad, and we want to remove it anyway, so the length of LCP of these two reversed prefixes is the only thing affecting the number of moves on the prefix). This part can be precalculated in $O(n^2)$ with simple dynamic programming (using $O(n^2)$ memory) or with z-function in $O(n^2)$ time and $O(n)$ memory - we just need to build a z-function on a string $s[0; pos)^{-1} + \\# + t^{-1}$, where $+$ is the concatenation of strings and $-1$ is the reverse operation. The required value of the z-function for the fixed values $pos$ and $suf$ will be in the position $pos + 1 + m - suf$. And the answer for the prefix will be $pos - suf$ (this is the number of extra characters on the prefix we have to delete) plus $pos - z_{pos + 1 + m - suf}$ plus $1$ because we have to press \"home\". But there is a corner case. If the prefix is empty, then we don't need to do all of this and the answer for prefix will be $0$. Complexity: $O(n^2)$ time and $O(n)$ memory.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> zf(const string &s) {\n    int n = s.size();\n    vector<int> z(n);\n    int l = 0, r = 0;\n    for (int i = 1; i < n; ++i) {\n        if (i <= r) {\n            z[i] = min(r - i + 1, z[i - l]);\n        }\n        while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {\n            ++z[i];\n        }\n        if (i + z[i] - 1 > r) {\n            l = i;\n            r = i + z[i] - 1;\n        }\n    }\n    return z;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int T;\n    cin >> T;\n    while (T--) {\n        int n, m;\n        string s, t;\n        cin >> n >> m >> s >> t;\n        \n        int ans = 1e9;\n        \n        bool bad = false;\n        vector<int> lpos(m), rpos(m);\n        for (int i = 0; i < m; ++i) {\n            if (i > 0) {\n                lpos[i] = lpos[i - 1] + 1;\n            } else {\n                lpos[i] = 0;\n            }\n            while (lpos[i] < n && s[lpos[i]] != t[i]) {\n                ++lpos[i];\n            }\n            if (lpos[i] >= n) {\n                bad = true;\n                break;\n            }\n        }\n        for (int i = m - 1; i >= 0; --i) {\n            if (i + 1 < m) {\n                rpos[i] = rpos[i + 1] - 1;\n            } else {\n                rpos[i] = n - 1;\n            }\n            while (rpos[i] >= 0 && s[rpos[i]] != t[i]) {\n                --rpos[i];\n            }\n            if (rpos[i] < 0) {\n                bad = true;\n                break;\n            }\n        }\n        if (bad) {\n            cout << -1 << endl;\n            continue;\n        }\n        \n        for (int pos = 0; pos <= n; ++pos) {\n            string tmp = s.substr(0, pos);\n            reverse(tmp.begin(), tmp.end());\n            tmp += \"#\" + t;\n            reverse(tmp.begin() + pos + 1, tmp.end());\n            vector<int> z = zf(tmp);\n            for (int suf = 0; suf <= m; ++suf) {\n                if (pos - suf < 0) {\n                    continue;\n                }\n                if (suf < m && rpos[suf] < pos) {\n                    continue;\n                }\n                if (suf - 1 >= 0 && lpos[suf - 1] > pos) {\n                    continue;\n                }\n                int rg = 0;\n                if (suf != 0) {\n                    int sum = (pos - z[pos + 1 + m - suf]) + (pos - suf);\n                    rg = (sum != 0) + sum;\n                } else {\n                    rg = pos;\n                }\n                ans = min(ans, (n - pos) + rg);\n            }\n        }\n        cout << ans << endl;\n    }\n    \n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1701",
    "index": "F",
    "title": "Points",
    "statement": "A triple of points $i$, $j$ and $k$ on a coordinate line is called \\textbf{beautiful} if $i < j < k$ and $k - i \\le d$.\n\nYou are given a set of points on a coordinate line, initially empty. You have to process queries of three types:\n\n- add a point;\n- remove a point;\n- calculate the number of beautiful triples consisting of points belonging to the set.",
    "tutorial": "We are going to calculate the answer as follows: for every point $i$, let $f(i)$ be the number of points $j$ such that $1 \\le j - i \\le d$ (i. e. the number of points that are to the right of $i$ and have distance at most $d$ from it). Then, the number of beautiful triples where $i$ is the leftmost point is $\\dfrac{f(i)(f(i) - 1)}{2}$. We can sum these values over all points to get the answer; so, the solution should somehow maintain and update the sum of these values efficiently. Let's see what happens when we add a new point or remove an existing point. For all points to the left of it with distance no more than $d$, the value of $f(i)$ increases or decreases by $1$. So, we need some sort of data structure that allows adding/subtracting $1$ on segment and maintains the sum of $\\dfrac{f(i)(f(i) - 1)}{2}$. This looks like a lazy segment tree, but updating the sum of $\\dfrac{f(i)(f(i) - 1)}{2}$ can be tricky. One way to do this is to notice that $\\dfrac{f(i)(f(i) - 1)}{2} = \\dfrac{f(i)^2}{2} - \\dfrac{f(i)}{2}$. So maybe we can maintain the sum of $f(i)^2$ and the sum of $f(i)$ on the segment? It turns out we can. The model solution does this as follows: the leaf of the segment tree corresponding to the position $i$ stores a vector with three values: $(f(i)^0, f(i)^1, f(i)^2)$. The inner nodes store the sums of these vectors in the subtree. We can find a matrix which, when multiplied by $(x^0, x^1, x^2)$, gets the vector $((x+1)^0, (x+1)^1, (x+1)^2)$, and the inverse matrix to it. Then adding $1$ to $f(i)$ on segment means multiplying all vectors on segment by that matrix, and subtracting $1$ means multiplying by the inverse matrix; and since matrix multiplication is both associative and distributive, the segment tree can handle these queries. Side note: this method with matrices is asymptotically fine, but the constant factor in it is fairly large. You can speed this up by getting rid of the matrices and instead storing the sum of $f(i)$ and the sum of $f(i)^2$ in each node, and coding the formulas that allow you to add/subtract $1$ on segment by hand, without any matrix operations. This can make a noticeable improvement in terms of actual time consumption, although it wasn't needed in this problem since the time limit was pretty generous. Okay, there's only one small issue left: right now our structure can store the sum of $f(i)$ and $f(i)^2$ over all possible points (we build it on segment $[0, 200000]$, for example), but we only need the sum over existing points. One way to handle it is to use a flag for each leaf of the segment tree, and pull the value up from the leaf only if this flag is true. We will need a function that changes the value of this flag for a single leaf, but it's not very different from a function that changes one value in a lazy segment tree. Time complexity of the solution is $O(A + q \\log A)$, where $A$ is the maximum coordinate of the point, although the constant factor of the described approach is fairly large since it involves $3 \\times 3$ matrix multiplications. You can improve the constant factor by getting rid of the matrices, as mentioned earlier.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200043;\nconst int M = 200001;\n\ntypedef array<long long, 3> vec;\ntypedef array<vec, 3> mat;\n\nvec operator+(const vec& a, const vec& b)\n{\n    vec c;\n    for(int i = 0; i < 3; i++) c[i] = a[i] + b[i];\n    return c;\n}\n\nvec operator-(const vec& a, const vec& b)\n{\n    vec c;\n    for(int i = 0; i < 3; i++) c[i] = a[i] - b[i];\n    return c;\n}\n\nvec operator*(const mat& a, const vec& b)\n{\n    vec c;\n    for(int i = 0; i < 3; i++) c[i] = 0;\n    for(int i = 0; i < 3; i++)\n        for(int j = 0; j < 3; j++)\n            c[i] += a[i][j] * b[j];\n    return c;\n}\n\nmat operator*(const mat& a, const mat& b)\n{\n    mat c;\n    for(int i = 0; i < 3; i++)\n        for(int j = 0; j < 3; j++)\n            c[i][j] = 0;\n    for(int i = 0; i < 3; i++)\n        for(int j = 0; j < 3; j++)\n            for(int k = 0; k < 3; k++)\n                c[i][k] += a[i][j] * b[j][k];\n    return c;\n}\n\nmat F = {vec({1, 0, 0}), vec({1, 1, 0}), vec({1, 2, 1})};\nmat B = {vec({1, 0, 0}), vec({-1, 1, 0}), vec({1, -2, 1})};\nmat E = {vec({1, 0, 0}), vec({0, 1, 0}), vec({0, 0, 1})};\n\nvec S = {1, 0, 0};\nvec Z = {0, 0, 0};\n\nvec t[4 * N];\nmat f[4 * N];\nbool active[4 * N];\nbool has[N];\nint d, q;\n\nvec getVal(int v)\n{\n    if(!active[v]) return Z;\n    return f[v] * t[v];\n}\n\nvoid recalc(int v)\n{\n    t[v] = getVal(v * 2 + 1) + getVal(v * 2 + 2);    \n}\n\nvoid build(int v, int l, int r)\n{\n    if(l == r - 1)\n    {\n        f[v] = E;\n        t[v] = S;\n        active[v] = false;                 \n    }\n    else\n    {\n        int m = (l + r) / 2;\n        build(v * 2 + 1, l, m);\n        build(v * 2 + 2, m, r);\n        f[v] = E;\n        recalc(v);\n        active[v] = true;               \n    }\n}\n\nvoid push(int v)\n{\n    if(f[v] == E) return;\n    t[v] = f[v] * t[v];\n    f[v * 2 + 1] = f[v] * f[v * 2 + 1];\n    f[v * 2 + 2] = f[v] * f[v * 2 + 2];\n    f[v] = E;\n}\n\nvoid updSegment(int v, int l, int r, int L, int R, bool adv)\n{\n    if(L >= R) return;\n    if(l == L && r == R)\n    {\n        if(adv) f[v] = F * f[v];\n        else f[v] = B * f[v];\n        return;\n    }\n    push(v);\n    int m = (l + r) / 2;\n    updSegment(v * 2 + 1, l, m, L, min(m, R), adv);\n    updSegment(v * 2 + 2, m, r, max(m, L), R, adv);\n    recalc(v);\n}\n\nvoid setState(int v, int l, int r, int pos, bool val)\n{\n    if(l == r - 1)\n    {   \n        active[v] = val;\n        return;\n    }\n    push(v);\n    int m = (l + r) / 2;\n    if(pos < m)\n        setState(v * 2 + 1, l, m, pos, val);\n    else\n        setState(v * 2 + 2, m, r, pos, val);\n    recalc(v);\n}\n\nvoid addPoint(int x)\n{\n    int lf = max(0, x - d);\n    int rg = x;\n    if(lf < rg)\n        updSegment(0, 0, M, lf, rg, true);\n    setState(0, 0, M, x, true);        \n}\n\nvoid delPoint(int x)\n{\n    int lf = max(0, x - d);\n    int rg = x;\n    if(lf < rg)\n        updSegment(0, 0, M, lf, rg, false);\n    setState(0, 0, M, x, false);        \n}\n\nvoid query(int x)\n{\n    if(has[x])\n    {\n        has[x] = false;\n        delPoint(x);\n    }\n    else\n    {\n        has[x] = true;\n        addPoint(x);\n    }\n    vec res = getVal(0);\n    printf(\"%lld\\n\", (res[2] - res[1]) / 2);\n}\n\nint main()\n{\n    scanf(\"%d %d\", &q, &d);\n    build(0, 0, M);\n    for(int i = 0; i < q; i++)\n    {\n        int x;\n        scanf(\"%d\", &x);\n        query(x);\n    }\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "implementation",
      "math",
      "matrices"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1702",
    "index": "A",
    "title": "Round Down the Price",
    "statement": "At the store, the salespeople want to make all prices round.\n\nIn this problem, a number that is a power of $10$ is called a round number. For example, the numbers $10^0 = 1$, $10^1 = 10$, $10^2 = 100$ are round numbers, but $20$, $110$ and $256$ are not round numbers.\n\nSo, if an item is worth $m$ bourles (the value of the item is not greater than $10^9$), the sellers want to change its value to the nearest round number that is not greater than $m$. They ask you: by how many bourles should you \\textbf{decrease} the value of the item to make it worth exactly $10^k$ bourles, where the value of $k$ — is the maximum possible ($k$ — any non-negative integer).\n\nFor example, let the item have a value of $178$-bourles. Then the new price of the item will be $100$, and the answer will be $178-100=78$.",
    "tutorial": "Note that the number $m$ and the nearest round number not exceeding $m$ have the same size (consist of the same number of digits in the record). Denote the size of $m$ by $len$. Then we can construct the nearest round number. It will consist of one and $len - 1$ zeros.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\n\n\nvoid solve() {\n    int m; cin >> m;\n    string t = to_string(m);\n    string s = \"1\";\n    for (int i = 1; i < sz(t); i++) {\n        s += '0';\n    }\n    int k = stoi(s);\n    cout << m - k << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1702",
    "index": "B",
    "title": "Polycarp Writes a String from Memory",
    "statement": "Polycarp has a poor memory. Each day he can remember no more than $3$ of different letters.\n\nPolycarp wants to write a non-empty string of $s$ consisting of lowercase Latin letters, taking \\textbf{minimum} number of days. In how many days will he be able to do it?\n\nPolycarp initially has an empty string and can only add characters to the end of that string.\n\nFor example, if Polycarp wants to write the string lollipops, he will do it in $2$ days:\n\n- on the first day Polycarp will memorize the letters l, o, i and write lolli;\n- On the second day Polycarp will remember the letters p, o, s, add pops to the resulting line and get the line lollipops.\n\nIf Polycarp wants to write the string stringology, he will do it in $4$ days:\n\n- in the first day will be written part str;\n- on day two will be written part ing;\n- on the third day, part of olog will be written;\n- on the fourth day, part of y will be written.\n\nFor a given string $s$, print the minimum number of days it will take Polycarp to write it.",
    "tutorial": "Let us simulate the process. We store a set $v$ consisting of letters that Polycarp memorizes on one day. Gradually dial the set $s$. If the size of $v$ exceeds $3$, we add $1$ to the day counter $ans$ and clear $v$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\n\n\nvoid solve() {\n    string s; cin >> s;\n    set<char> v;\n    int ans = 0;\n    for (int i = 0; i < sz(s); i++) {\n        v.insert(s[i]);\n        if (sz(v) > 3) {\n            ans++;\n            v.clear();\n            v.insert(s[i]);\n        }\n    }\n    if (!v.empty()) ans++;\n    cout << ans << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1702",
    "index": "C",
    "title": "Train and Queries",
    "statement": "Along the railroad there are stations indexed from $1$ to $10^9$. An express train always travels along a route consisting of $n$ stations with indices $u_1, u_2, \\dots, u_n$, where ($1 \\le u_i \\le 10^9$). The train travels along the route from left to right. It starts at station $u_1$, then stops at station $u_2$, then at $u_3$, and so on. Station $u_n$ — the terminus.\n\nIt is possible that the train will visit the same station more than once. That is, there may be duplicates among the values $u_1, u_2, \\dots, u_n$.\n\nYou are given $k$ queries, each containing two different integers $a_j$ and $b_j$ ($1 \\le a_j, b_j \\le 10^9$). For each query, determine whether it is possible to travel by train from the station with index $a_j$ to the station with index $b_j$.\n\nFor example, let the train route consist of $6$ of stations with indices [$3, 7, 1, 5, 1, 4$] and give $3$ of the following queries:\n\n- $a_1 = 3$, $b_1 = 5$It is possible to travel from station $3$ to station $5$ by taking a section of the route consisting of stations [$3, 7, 1, 5$]. Answer: YES.\n- $a_2 = 1$, $b_2 = 7$You cannot travel from station $1$ to station $7$ because the train cannot travel in the opposite direction. Answer: NO.\n- $a_3 = 3$, $b_3 = 10$It is not possible to travel from station $3$ to station $10$ because station $10$ is not part of the train's route. Answer: NO.",
    "tutorial": "To solve the problem, we will use the dictionary. Each station will be matched with a pair of integers - the indices of its first and last entries in the route. Then we will sequentially process queries. If at least one of the stations $a_j$ or $b_j$ is missing in the dictionary - the answer is NO. Otherwise, check: If the index of the first entry of station $a_j$ in the route is strictly less than the index of the last entry of station $b_j$ in the route - the answer is YES. Otherwise, the answer is NO.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\n\nvoid solve(){\n    int n, k;\n    cin >> n >> k;\n    map<int, pair<int, int>>m;\n    forn(i, n){\n        int u;\n        cin >> u;\n        if(!m.count(u)) {\n            m[u].first = i;\n            m[u].second = i;\n        }\n        else m[u].second = i;\n    }\n    forn(i, k){\n        int a, b;\n        cin >> a >> b;\n        if(!m.count(a) or !m.count(b) or m[a].first > m[b].second) {\n            cout << \"NO\\n\"; //equals = 0 = wrong\n        }\n        else cout << \"YES\\n\";\n    }\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1702",
    "index": "D",
    "title": "Not a Cheap String",
    "statement": "Let $s$ be a string of lowercase Latin letters. Its price is the sum of the indices of letters (an integer between 1 and 26) that are included in it. For example, the price of the string abca is $1+2+3+1=7$.\n\nThe string $w$ and the integer $p$ are given. Remove the minimal number of letters from $w$ so that its price becomes less than or equal to $p$ and print the resulting string. Note that the resulting string may be empty. You can delete arbitrary letters, they do not have to go in a row. If the price of a given string $w$ is less than or equal to $p$, then nothing needs to be deleted and $w$ must be output.\n\nNote that when you delete a letter from $w$, the order of the remaining letters is preserved. For example, if you delete the letter e from the string test, you get tst.",
    "tutorial": "The main idea is that it is always better to remove the most expensive symbol. To do this quickly, we will count all the symbols and remove them from the most expensive to the cheapest, counting how many times we have removed each. During the output, we will skip the characters the number of times that we deleted.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        string s;\n        cin >> s;\n        int p;\n        cin >> p;\n        string w(s);\n        sort(w.rbegin(), w.rend());\n        int cost = 0;\n        forn(i, s.length())\n            cost += s[i] - 'a' + 1;\n        map<char,int> del;\n        forn(i, w.length())\n            if (cost > p) {\n                del[w[i]]++;\n                cost -= w[i] - 'a' + 1;\n            }\n        forn(i, s.length()) {\n            if (del[s[i]] > 0) {\n                del[s[i]]--;\n                continue;\n            }\n            cout << s[i];\n        }\n        cout << endl;\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1702",
    "index": "E",
    "title": "Split Into Two Sets",
    "statement": "Polycarp was recently given a set of $n$ (number $n$ — even) dominoes. Each domino contains two integers from $1$ to $n$.\n\nCan he divide all the dominoes into two sets so that all the numbers on the dominoes of each set are different? Each domino must go into exactly one of the two sets.\n\nFor example, if he has $4$ dominoes: $\\{1, 4\\}$, $\\{1, 3\\}$, $\\{3, 2\\}$ and $\\{4, 2\\}$, then Polycarp will be able to divide them into two sets in the required way. The first set can include the first and third dominoes ($\\{1, 4\\}$ and $\\{3, 2\\}$), and the second set — the second and fourth ones ($\\{1, 3\\}$ and $\\{4, 2\\}$).",
    "tutorial": "Polycarp has $n$ dominoes, on each domino there are $2$ numbers - it turns out, there will be $2n$ numbers in total. We need to divide $2n$ numbers (each number from $1$ to $n$) into two sets so that all numbers in each set are different - each set will consist of $n$ numbers. It turns out that all numbers from $1$ to $n$ must occur exactly $2$ times, no more and no less. Let's imagine it all as a bipartite graph, where there are vertices from $1$ to $n$, and dominoes are edges. Since each number occurs exactly $2$ times, then we have a lot of cycles. In which the edges of each number must be included in different sets, in other words, the cycles must be of even length. This can be checked in $O(n)$ by a simple enumeration.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nmap<int, vector<int>> m;\nvector<bool> used;\n\nint go(int v) {\n    used[v] = true;\n    for (auto now : m[v]) {\n        if (!used[now]) {\n            return go(now) + 1;\n        }\n    }\n    return 1;\n}\n\nvoid solve() {\n\n    int n, x, y;\n    cin >> n;\n\n    m.clear();\n    used.clear();\n    used.resize(n + 1, false);\n\n    bool fault = false;\n    forn(i, n) {\n        cin >> x >> y;\n        m[x].push_back(y);\n        m[y].push_back(x);\n        if (x == y || m[x].size() > 2 || m[y].size() > 2) fault = true;\n    }\n\n    if (fault) {\n        cout << \"NO\\n\";\n        return;\n    }\n\n    forn(i, n) {\n        if (!used[i + 1]) {\n            if (go(i + 1) % 2) {\n                cout << \"NO\\n\";\n                return;\n            }\n        }\n    }\n\n    cout << \"YES\\n\";\n}\nint main() {\n    int tests;\n    cin >> tests;\n    forn(tt, tests) {\n        solve();\n    }\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1702",
    "index": "F",
    "title": "Equate Multisets",
    "statement": "Multiset —is a set of numbers in which there can be equal elements, and the order of the numbers does not matter. Two multisets are equal when each value occurs the same number of times. For example, the multisets $\\{2,2,4\\}$ and $\\{2,4,2\\}$ are equal, but the multisets $\\{1,2,2\\}$ and $\\{1,1,2\\}$ — are not.\n\nYou are given two multisets $a$ and $b$, each consisting of $n$ integers.\n\nIn a single operation, any element of the $b$ multiset can be doubled or halved (rounded down). In other words, you have one of the following operations available for an element $x$ of the $b$ multiset:\n\n- replace $x$ with $x \\cdot 2$,\n- or replace $x$ with $\\lfloor \\frac{x}{2} \\rfloor$ (round down).\n\nNote that you cannot change the elements of the $a$ multiset.\n\nSee if you can make the multiset $b$ become equal to the multiset $a$ in an arbitrary number of operations (maybe $0$).\n\nFor example, if $n = 4$, $a = \\{4, 24, 5, 2\\}$, $b = \\{4, 1, 6, 11\\}$, then the answer is yes. We can proceed as follows:\n\n- Replace $1$ with $1 \\cdot 2 = 2$. We get $b = \\{4, 2, 6, 11\\}$.\n- Replace $11$ with $\\lfloor \\frac{11}{2} \\rfloor = 5$. We get $b = \\{4, 2, 6, 5\\}$.\n- Replace $6$ with $6 \\cdot 2 = 12$. We get $b = \\{4, 2, 12, 5\\}$.\n- Replace $12$ with $12 \\cdot 2 = 24$. We get $b = \\{4, 2, 24, 5\\}$.\n- Got equal multisets $a = \\{4, 24, 5, 2\\}$ and $b = \\{4, 2, 24, 5\\}$.",
    "tutorial": "We divide each number from the multiset $a$ by $2$ as long as it is divisible without a remainder. Because if we can get a new number from the multiset $a$, we can also increase it to the original number by multiplication by $2$. Now notice that it does not make sense to use the first operation (multiplication by $2$), because we get an even number, and only odd numbers remain in the multiset $a$. Then we take the largest number from $b$ and if it is in $a$, we remove this number from both multisets. Otherwise, we use the second operation, if the number is greater than $1$. If it is equal to $1$, then it is impossible to equalize the multisets $a$ and $b$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\nconst int INF = 1e9;\n\nvoid solve() {\n    int n; cin >> n;\n    multiset<int> a, b;\n\n    forn(i, n) {\n        int x; cin >> x;\n        while (x % 2 == 0) {\n            x /= 2;\n        }\n        a.insert(x);\n    }\n\n    forn(i, n) {\n        int x; cin >> x;\n        b.insert(x);\n    }\n    n = sz(a);\n\n    while (!b.empty()) {\n        int x = *b.rbegin();\n        // cout << x << endl;\n        if (!a.count(x)) {\n            if (x == 1) break;\n            b.erase(b.find(x));\n            b.insert(x / 2);\n        } else {\n            b.erase(b.find(x));\n            a.erase(a.find(x));\n        }\n    }\n\n    cout << (b.empty() ? \"YES\" : \"NO\") << endl;\n\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1702",
    "index": "G1",
    "title": "Passable Paths (easy version)",
    "statement": "\\textbf{This is an easy version of the problem. The only difference between an easy and a hard version is in the number of queries.}\n\nPolycarp grew a tree from $n$ vertices. We remind you that a tree of $n$ vertices is an undirected connected graph of $n$ vertices and $n-1$ edges that does not contain cycles.\n\nHe calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).\n\nIn other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).\n\nFor example, for a tree below sets $\\{3, 2, 5\\}$, $\\{1, 5, 4\\}$, $\\{1, 4\\}$ are passable, and $\\{1, 3, 5\\}$, $\\{1, 2, 3, 4, 5\\}$ are not.\n\nPolycarp asks you to answer $q$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is \\textbf{passable}.",
    "tutorial": "If the answer is YES, then we can choose a subset of the tree vertices forming a simple path and containing all the vertices of our set. Let's choose the minimum possible path, its ends - vertices from the set. The constraints allow us to answer the query in $\\mathcal{O}(n)$, hang the tree by one of the ends and check if it is true that there is only one selected vertex that does not have any selected ones in the subtree, if there is one such vertex, then it is - the second end. To make it easier to search for one of the ends, we will hang the tree by any vertex before the queries, calculate their depths and take the deepest of the set.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(143);\n\nconst int inf = 1e15;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nvoid depth(int v, int p, vector<vector<int>> &sl, vector<int> &d){\n    if(p >= 0) d[v] = d[p] + 1;\n    for(int u: sl[v]){\n        if(u == p) continue;\n        depth(u, v, sl, d);\n    }\n}\n\nint dfs(int v, int p, vector<vector<int>> &sl, vector<bool> &chosen){\n    int res = 0;\n    bool lower = false;\n    for(int u: sl[v]){\n        if(u == p) continue;\n        res += dfs(u, v, sl, chosen);\n        lower = lower || chosen[u];\n    }\n    chosen[v] = chosen[v] || lower;\n    if(chosen[v] && !lower) res = 1;\n    return res;\n}\n\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<vector<int>> sl(n);\n    for(int i = 1; i < n; ++i){\n        int u, v;\n        cin >> u >> v;\n        sl[--u].push_back(--v);\n        sl[v].push_back(u);\n    }\n    vector<int> d(n);\n    depth(0, -1, sl, d);\n    int q;\n    cin >> q;\n    for(; q; --q){\n        int k;\n        cin >> k;\n        vector<bool> chosen(n);\n        int mx = 0;\n        for(int i = 0; i < k; ++i){\n            int p;\n            cin >> p;\n            --p;\n            if(d[p] > d[mx]) mx = p;\n            chosen[p] = true;\n        }\n        int leaves = dfs(mx, -1, sl, chosen);\n        if(leaves == 1) cout << \"YES\\n\";\n        else cout << \"NO\\n\";\n    }\n}\n\nbool multi = false;\n\nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (; t; --t) {\n        solve();\n        //cout << endl;\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1702",
    "index": "G2",
    "title": "Passable Paths (hard version)",
    "statement": "\\textbf{This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.}\n\nPolycarp grew a tree from $n$ vertices. We remind you that a tree of $n$ vertices is an undirected connected graph of $n$ vertices and $n-1$ edges that does not contain cycles.\n\nHe calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).\n\nIn other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).\n\nFor example, for a tree below sets $\\{3, 2, 5\\}$, $\\{1, 5, 4\\}$, $\\{1, 4\\}$ are passable, and $\\{1, 3, 5\\}$, $\\{1, 2, 3, 4, 5\\}$ are not.\n\nPolycarp asks you to answer $q$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is \\textbf{passable}.",
    "tutorial": "Recall that the path in the rooted tree - ascends from one end to the least common ancestor ($lca$) of the ends and descends to the other end (possibly by 0). Then our set is divided into two simple ways. To check this, you only need to count $lca$. We will first calculate the depths, as for solving an easy version of the problem. We will go along the vertices according to the non-growth of the depths, if $lca$ of the deepest vertex and the current one is equal to the current one, then it is the ancestor of the deepest one, we will mark it. Next, we will find the deepest unmarked vertex and do the same, if there is no such vertex, then the whole path goes down and the answer is YES. If there are unmarked vertices, then there are vertices outside of those two ascents and the answer is NO. Now we need to check that the two ascents do not intersect or intersect only at the $lca$ of ends, for this we just make sure that $lca$ is not deeper than the shallowest vertex of the set.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(143);\n\nconst int inf = 1e15;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nint n, sz;\nvector<vector<int>> sl, up;\nvector<int> d;\n\nvoid precalc(int v, int p){\n    d[v] = d[p] + 1;\n    up[v][0] = p;\n    for(int i = 1; i <= sz; ++i){\n        up[v][i] = up[up[v][i - 1]][i - 1];\n    }\n    for(int u: sl[v]){\n        if(u == p) continue;\n        precalc(u, v);\n    }\n}\n\nint lca(int u, int v){\n    if(d[u] < d[v]){\n        swap(u, v);\n    }\n    for(int cur = sz; cur >= 0; --cur){\n        if (d[u] - (1 << cur) >= d[v]) {\n            u = up[u][cur];\n        }\n    }\n    for(int cur = sz; cur >= 0; --cur){\n        if (up[u][cur] != up[v][cur]) {\n            u = up[u][cur];\n            v = up[v][cur];\n        }\n    }\n    return u == v ? u : up[u][0];\n}\n\nvoid solve(){\n    cin >> n;\n    sz = 0;\n    while ((1 << sz) < n) sz++;\n    d.assign(n, -1);\n    up.assign(n, vector<int>(sz + 1));\n    sl.assign(n, vector<int>(0));\n    for(int i = 1; i < n; ++i){\n        int u, v;\n        cin >> u >> v;\n        sl[--u].push_back(--v);\n        sl[v].push_back(u);\n    }\n    precalc(0, 0);\n    int q;\n    cin >> q;\n    for(; q; --q){\n        int k;\n        cin >> k;\n        vector<int> p(k);\n        for(int &e: p) {\n            cin >> e;\n            --e;\n        }\n        sort(all(p), [](int a, int b) {\n            return d[a] > d[b];\n        });\n        vector<bool> used(k);\n        for(int i = 0; i < k; ++i){\n            if(lca(p[0], p[i]) == p[i]) used[i] = true;\n        }\n        int f = 0;\n        while (f < k && used[f]) f++;\n        if(f == k){\n            cout << \"YES\\n\";\n            continue;\n        }\n        bool ans = true;\n        for(int i = f; i < k; ++i){\n            if(lca(p[f], p[i]) == p[i]) used[i] = true;\n        }\n        for(bool e: used){\n            ans &= e;\n        }\n        ans &= d[lca(p[0], p[f])] <= d[p.back()];\n        if(ans) cout << \"YES\\n\";\n        else cout << \"NO\\n\";\n    }\n}\n\nbool multi = false;\n\nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (; t; --t) {\n        solve();\n        //cout << endl;\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1703",
    "index": "A",
    "title": "YES or YES?",
    "statement": "There is a string $s$ of length $3$, consisting of uppercase and lowercase English letters. Check if it is equal to \"YES\" (without quotes), where each letter can be in any case. For example, \"yES\", \"Yes\", \"yes\" are all allowable.",
    "tutorial": "You should implement what is written in the statement. Here are three ways to do it: Check that the first character is $\\texttt{Y}$ or $\\texttt{y}$, check that the second character is $\\texttt{E}$ or $\\texttt{e}$, and check the third character is $\\texttt{S}$ or $\\texttt{s}$. Make an array storing all acceptable strings (there are only $8$), and loop and see if any of the strings match the input. Use some built-in function like tolower() in C++ to make the string all lowercase, and check if $s$ is equal to $\\texttt{yes}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tif (s[0] != 'y' && s[0] != 'Y') {cout << \"NO\\n\";}\n\telse if (s[1] != 'e' && s[1] != 'E') {cout << \"NO\\n\";}\n\telse if (s[2] != 's' && s[2] != 'S') {cout << \"NO\\n\";}\n\telse {cout << \"YES\\n\";}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1703",
    "index": "B",
    "title": "ICPC Balloons",
    "statement": "In an ICPC contest, balloons are distributed as follows:\n\n- Whenever a team solves a problem, that team gets a balloon.\n- The first team to solve a problem gets an additional balloon.\n\nA contest has 26 problems, labelled $\\textsf{A}$, $\\textsf{B}$, $\\textsf{C}$, ..., $\\textsf{Z}$. You are given the order of solved problems in the contest, denoted as a string $s$, where the $i$-th character indicates that the problem $s_i$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.",
    "tutorial": "Let's keep an array $a$ of booleans, $a_i$ denoting whether or not some team has solved the $i$th problem already. Now we can iterate through the string from left to right and keep a running total $\\mathrm{tot}$. If $a_i$ is true (the $i$-th problem has already been solved), increase $\\mathrm{tot}$ by $1$; otherwise, increase $\\mathrm{tot}$ by $2$ and set $a_i$ to true. The time complexity is $\\mathcal{O}(n)$. Bonus: the answer is always $n + \\text{number of distinct characters in }s$. Can you see why?",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tbool vis[26] = {};\n\tint res = 0;\n\tfor (char c : s) {\n\t\tif (!vis[c - 'A']) {res += 2; vis[c - 'A'] = true;}\n\t\telse {res++;}\n\t}\n\tcout << res << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1703",
    "index": "C",
    "title": "Cypher",
    "statement": "Luca has a cypher made up of a sequence of $n$ wheels, each with a digit $a_i$ written on it. On the $i$-th wheel, he made $b_i$ moves. Each move is one of two types:\n\n- up move (denoted by $U$): it increases the $i$-th digit by $1$. After applying the up move on $9$, it becomes $0$.\n- down move (denoted by $D$): it decreases the $i$-th digit by $1$. After applying the down move on $0$, it becomes $9$.\n\n\\begin{center}\n{\\small Example for $n=4$. The current sequence is 0 0 0 0.}\n\\end{center}\n\nLuca knows the final sequence of wheels and the moves for each wheel. Help him find the original sequence and crack the cypher.",
    "tutorial": "We will perform each move in reverse from the final sequence of the cypher. down move: it increases the $i$-th digit by $1$. After applying the up move on $9$, it becomes $0$. up move (denoted by $\\texttt{D}$): it decreases the $i$-th digit by $1$. After applying the down move on $0$, it becomes $9$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    int a[n];\n    for(int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n    }\n    for(int i = 0; i < n; i++)\n    {\n        int b;\n        cin >> b;\n        if(b == 0)\n        {\n            continue;\n        }\n        string now;\n        cin >> now;\n        for(int j = 0; j < b; j++)\n        {\n            if(now[j] == 'U'){a[i]--;}\n            else if(now[j] == 'D'){a[i]++;}\n            if(a[i] < 0){a[i]+=10;}\n            if(a[i] > 9){a[i]-=10;}\n        }\n    }\n    for(int i = 0; i < n; i++)\n    {\n        cout << a[i] << \" \";\n    }\n    cout << endl;\n}\n \nint main(){\n    int t;\n    cin>> t;\n    while(t--)\n    {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1703",
    "index": "D",
    "title": "Double Strings",
    "statement": "You are given $n$ strings $s_1, s_2, \\dots, s_n$ of length at most $\\mathbf{8}$.\n\nFor each string $s_i$, determine if there exist two strings $s_j$ and $s_k$ such that $s_i = s_j + s_k$. That is, $s_i$ is the concatenation of $s_j$ and $s_k$. Note that $j$ \\textbf{can} be equal to $k$.\n\nRecall that the concatenation of strings $s$ and $t$ is $s + t = s_1 s_2 \\dots s_p t_1 t_2 \\dots t_q$, where $p$ and $q$ are the lengths of strings $s$ and $t$ respectively. For example, concatenation of \"code\" and \"forces\" is \"codeforces\".",
    "tutorial": "Use some data structure that allows you to answer queries of the form: \"does the string $t$ appear in the array $s_1, \\dots, s_n$?\" For example, in C++ you can use a map<string, bool>, while in Python you can use a dictionary dict. Afterwards, for each string $s$, brute force all strings $x$ and $y$ such that $s = x + y$. There are at most $7$ such strings, because $s$ has length at most $8$. Then check if both $x$ and $y$ appear in the array using your data structure. The time complexity is $\\mathcal{O}(\\ell n \\log n)$ per test case, where $\\ell$ is the maximum length of an input string.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tstring s[n];\n\tmap<string, bool> mp;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> s[i];\n\t\tmp[s[i]] = true;\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tbool ok = false;\n\t\tfor (int j = 1; j < s[i].length(); j++) {\n\t\t\tstring pref = s[i].substr(0, j), suff = s[i].substr(j, s[i].length() - j);\n\t\t\tif (mp[pref] && mp[suff]) {ok = true;}\t\n\t\t}\n\t\tcout << ok;\n\t}\n\tcout << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "brute force",
      "data structures",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1703",
    "index": "E",
    "title": "Mirror Grid",
    "statement": "You are given a square grid with $n$ rows and $n$ columns. Each cell contains either $0$ or $1$.\n\nIn an operation, you can select a cell of the grid and flip it (from $0 \\to 1$ or $1 \\to 0$). Find the minimum number of operations you need to obtain a square that remains the same when rotated $0^{\\circ}$, $90^{\\circ}$, $180^{\\circ}$ and $270^{\\circ}$.\n\nThe picture below shows an example of all rotations of a grid.",
    "tutorial": "Let's rotate the grid by $0^{\\circ}$, $90^{\\circ}$, $180^{\\circ}$, and $270^{\\circ}$, and mark all cells that map to each other under these rotations. For example, for $4 \\times 4$ and $5 \\times 5$ grids, mirror grid must have the following patterns, the same letters denoting equal values: $\\begin{matrix} a & b & c & a\\\\ c & d & d & b\\\\ b & d & d & c\\\\ a & c & b & a \\end{matrix} \\qquad \\qquad \\begin{matrix} a & b & c & d & a\\\\ d & e & f & e & b\\\\ c & f & g & f & c\\\\ b & e & f & e & d\\\\ a & d & c & b & a \\end{matrix}$ In general, we can rotate the grid by $0^{\\circ}$, $90^{\\circ}$, $180^{\\circ}$, and $270^{\\circ}$ and see which cells need to have equal values by seeing the positions which each cell maps to. Now to solve the problem, we consider each equal value (each of the letters $a$, $b$, $c$, ... in the above figures) independently, and consider the minimum number of moves to make them all $0$ or all $1$. The answer is the total across all values. See the implementation for better understanding. The time complexity is $\\mathcal{O}(n^2)$ per testcase.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    int a[n][n];\n    for(int i = 0; i < n; i++)\n    {\n        for(int j = 0; j < n; j++)\n        {\n            char c;\n            cin >> c;\n            a[i][j] = c-'0';\n        }\n    }\n    int ans = 0;\n    for(int i = 0; i < (n+1)/2; i++)\n    {\n        for(int j = 0; j < n/2; j++)\n        {\n            int nowi = i, nowj = j;\n            int oldnowj = nowj;\n            int sum = a[nowi][nowj];\n            nowj = n-nowi-1;\n            nowi = oldnowj;\n            sum+=a[nowi][nowj];\n            oldnowj = nowj;\n            nowj = n-nowi-1;\n            nowi = oldnowj;\n            sum+=a[nowi][nowj];\n            oldnowj = nowj;\n            nowj = n-nowi-1;\n            nowi = oldnowj;\n            sum+=a[nowi][nowj];\n            ans+=min(sum, 4-sum);\n        }\n    }\n    cout << ans << endl;\n}\n \nint main(){\n    int t;\n    cin>> t;\n    while(t--)\n    {\n        solve();\n    }\n    return 0;\n} ",
    "tags": [
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1703",
    "index": "F",
    "title": "Yet Another Problem About Pairs Satisfying an Inequality",
    "statement": "You are given an array $a_1, a_2, \\dots a_n$. Count the number of pairs of indices $1 \\leq i, j \\leq n$ such that $a_i < i < a_j < j$.",
    "tutorial": "Call a pair good if it satisfies the condition. Let's split the inequality into three parts: $a_i < i$, $i < a_j$, $a_j < j$. Note that if $a_i \\geq i$ for any $i$, then it can't be an element of a good pair, because it fails the first and third conditions. So we can throw out all elements of the array satisfying $a_i \\geq i$. For the remaining elements, the first and third inequalities are already satisfied, so we only have to count the number of pairs $(i,j)$ with $i < a_j$. Let's iterate $j$ through the array from the left to the right, and make a list storing all $i$ that appear before $j$. Then for each $j$, count the number of $i$ less than $a_j$ by binary searching on the number of elements in the list less than $a_j$. Afterwards, add $j$ to the end of the list. Since we iterate from left to right, the list will always remain sorted (we insert the indices of elements, which are increasing from left to right), so the binary search will always work. The time complexity is $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tint a[n + 1];\n\tfor (int i = 1; i <= n; i++) {\n\t\tcin >> a[i];\n\t}\n\tlong long res = 0;\n\tvector<int> v;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (a[i] >= i) {continue;}\n\t\tres += (long long)(lower_bound(v.begin(), v.end(), a[i]) - v.begin());\n\t\tv.push_back(i);\n\t}\n\tcout << res << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1703",
    "index": "G",
    "title": "Good Key, Bad Key",
    "statement": "There are $n$ chests. The $i$-th chest contains $a_i$ coins. You need to open all $n$ chests \\textbf{in order from chest}$1$\\textbf{to chest}$n$.\n\nThere are two types of keys you can use to open a chest:\n\n- a good key, which costs $k$ coins to use;\n- a bad key, which does not cost any coins, but will halve all the coins in each unopened chest, \\textbf{including the chest it is about to open}. The halving operation \\textbf{will round down} to the nearest integer for each chest halved. In other words using a bad key to open chest $i$ will do $a_i = \\lfloor{\\frac{a_i}{2}\\rfloor}$, $a_{i+1} = \\lfloor\\frac{a_{i+1}}{2}\\rfloor, \\dots, a_n = \\lfloor \\frac{a_n}{2}\\rfloor$;\n- any key (both good and bad) breaks after a usage, that is, it is a one-time use.\n\nYou need to use in total $n$ keys, one for each chest. Initially, you have no coins and no keys. If you want to use a good key, then you need to buy it.\n\nDuring the process, you are allowed to go into debt; for example, if you have $1$ coin, you are allowed to buy a good key worth $k=3$ coins, and your balance will become $-2$ coins.\n\nFind the maximum number of coins you can have after opening all $n$ chests in order from chest $1$ to chest $n$.",
    "tutorial": "We will prove it is always optimal to use good keys for a prefix then only use bad keys. Consider we have used a bad key then a good key, by doing this we obtain $\\lfloor\\frac{a_i}{2}\\rfloor + \\lfloor\\frac{a_{i+1}}{2}\\rfloor - k$ coins. If we switch and use a good key first, the a bad key then we obtain $a_i + \\lfloor\\frac{a_{i+1}}{2}\\rfloor - k$, this number is clearly bigger so we will never encounter a bad key before a good key in an optimal solution, thus we will use a prefix of good keys then move on to using bad keys. For every possible prefix of good keys we will calculate the coins we get at the end. We do this by maintaining a variable with the prefix sum where we use the good keys and then calculate what we will get from the chests where we use bad keys. Notice that because we halve all the chests when we use a bad key we only need to verify the next $\\log_2(10^9) \\approx 30$ chests, all chests after it will go to $0$ coins. Final complexity: $\\mathcal{O}(n\\log a_i)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n    int n, k;\n    cin >> n >> k;\n    int a[n];\n    for(int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n    }\n    long long ans = 0;\n    long long sum = 0;\n    for(int i = -1; i < n; i++)\n    {\n        long long now = sum;\n        for(int j = i+1; j < min(n, i+32); j++)\n        {\n            int copy = a[j];\n            copy>>=j-i;\n            now+=copy;\n        }\n        ans = max(ans, now);\n        if(i+1 != n)\n        {\n            sum+=a[i+1]-k;\n        }\n    }\n    cout << ans << endl;\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1704",
    "index": "A",
    "title": "Two 0-1 Sequences",
    "statement": "AquaMoon has two binary sequences $a$ and $b$, which contain only $0$ and $1$. AquaMoon can perform the following two operations any number of times ($a_1$ is the first element of $a$, $a_2$ is the second element of $a$, and so on):\n\n- Operation 1: if $a$ contains at least two elements, change $a_2$ to $\\operatorname{min}(a_1,a_2)$, and remove the first element of $a$.\n- Operation 2: if $a$ contains at least two elements, change $a_2$ to $\\operatorname{max}(a_1,a_2)$, and remove the first element of $a$.\n\nNote that after a removal of the first element of $a$, the former $a_2$ becomes the first element of $a$, the former $a_3$ becomes the second element of $a$ and so on, and the length of $a$ reduces by one.\n\nDetermine if AquaMoon can make $a$ equal to $b$ by using these operations.",
    "tutorial": "Considering that whichever the operation you use, the length of $a$ would decrease $1$. So you can only modify the first $n-m+1$ elements of $a$, otherwise the length of $a$ can't be equal to the length of $b$. That means $\\{a_{n-m+2},\\dots,a_n\\}$ must equals to $\\{b_2,\\dots,b_m\\}$. And about the first element of $b$: if $b_1$ is $0$, you can use Operation 1 to make $0$ and remove elements. if $b_1$ is $1$, you can use Operation 2 to make $1$ and remove elements. if $b_1$ is $1$, you can use Operation 2 to make $1$ and remove elements. So just check the first $n-m+1$ elements in $a$ to find if there is anyone that equals to $b_1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int maxn = 2e5;\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T--) {\n        int n, m;\n        cin >> n >> m;\n        string a, b;\n        cin >> a >> b;\n        if (n < m) {\n            cout << \"NO\\n\";\n            continue;\n        }\n        bool same = true;\n        for (int i = 1; i < b.size(); ++i) {\n            if (a[i + n - m] != b[i]) {\n                same = false;\n                break;\n            }\n        }\n        if (!same) {\n            cout << \"NO\\n\";\n            continue;\n        }\n        for (int i = 0; i < n - m + 1; ++i) {\n            if (a[i] == b[0]) {\n                same = false;\n            }\n        }\n        if (same) {\n            cout << \"NO\\n\";\n        }\n        else {\n            cout << \"YES\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1704",
    "index": "B",
    "title": "Luke is a Foodie",
    "statement": "Luke likes to eat. There are $n$ piles of food aligned in a straight line in front of him. The $i$-th pile contains $a_i$ units of food.\n\nLuke will walk from the $1$-st pile towards the $n$-th pile, and he wants to eat every pile of food without walking back. When Luke reaches the $i$-th pile, he can eat that pile if and only if $|v - a_i| \\leq x$, where $x$ is a fixed integer, and $v$ is Luke's food affinity.\n\nBefore Luke starts to walk, he can set $v$ to any integer. Also, for each $i$ ($1 \\leq i \\leq n$), Luke can change his food affinity to any integer \\textbf{before} he eats the $i$-th pile.\n\nFind the minimum number of changes needed to eat every pile of food.\n\nNote that the initial choice for $v$ is \\textbf{not} considered as a change.",
    "tutorial": "For $a_i$, if $|v-a_i| \\leq x$, then $a_i-x \\leq v \\leq a_i+x$. Then consider using the greedy strategy. We will only change $v$ when we cannot find any possible $v$ to satisfy the current conditions. Therefore, we can determine the range of $v$. Initially, set $l=a_1-x,r=a_1+x$, then $v \\in [l,r]$. For $a_i$, change $l=\\max(l,a_i-x),r=\\min(r,a_i+x)$. Once $l>r$, which means from the last time that we changed $v$ to the current $a_i$ we cannot find any possible $v$ to satisfy the all the conditions between the two positions, we should change $l=a_i-x,r=a_i+x$, and add $1$ to answer.",
    "code": "#include <stdio.h>\n#include <string.h>\n#include <vector>\n#include <set>\n#include <queue>\n#include <string>\n#include <map>\n#include <chrono>\n#include <stdlib.h>\n#include <time.h>\n#include <algorithm>\n#include <iostream>\n#include <memory>\n#include <cstdio>\n#include <assert.h>\n#include <iostream>\nconst int MAXN = 300005;\nint numbers[MAXN];\nint main() {\n\tint t;\n\tint n, x;\n\n\tscanf(\"%d\", &t);\n\twhile (t--)\n\t{\n\t\tscanf(\"%d %d\", &n, &x);\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tscanf(\"%d\", &numbers[i]);\n\t\t}\n\t\tint num_min = numbers[1];\n\t\tint num_max = numbers[1];\n\t\tint res = 0;\n\t\tfor (int i = 2; i <= n; i++) {\n\t\t\tif (numbers[i] > num_max) {\n\t\t\t\tnum_max = numbers[i];\n\t\t\t}\n\t\t\tif (numbers[i] < num_min) {\n\t\t\t\tnum_min = numbers[i];\n\t\t\t}\n\t\t\tif (num_max - num_min > 2 * x) {\n\t\t\t\tres++;\n\t\t\t\tnum_min = num_max = numbers[i];\n\t\t\t}\n\t\t}\n\t\tprintf(\"%d\\n\", res);\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1704",
    "index": "C",
    "title": "Virus",
    "statement": "There are $n$ houses numbered from $1$ to $n$ on a circle. For each $1 \\leq i \\leq n - 1$, house $i$ and house $i + 1$ are neighbours; additionally, house $n$ and house $1$ are also neighbours.\n\nInitially, $m$ of these $n$ houses are infected by a deadly virus. Each \\textbf{morning}, Cirno can choose a house which is uninfected and protect the house from being infected permanently.\n\nEvery day, the following things happen in order:\n\n- Cirno chooses an uninfected house, and protect it permanently.\n- All uninfected, unprotected houses which have at least one \\textbf{infected} neighbor become infected.\n\nCirno wants to stop the virus from spreading. Find the minimum number of houses that will be infected in the end, if she optimally choose the houses to protect.\n\nNote that every day Cirno always chooses a house to protect \\textbf{before} the virus spreads. Also, a protected house will not be infected forever.",
    "tutorial": "First, considering it is easier to calculate the number of houses which are not infected, so we focus on it firstly. Conspicuously, if between $a_i$ and $a_{i+1}$ there are $x$ houses (Array $a$ has been sorted.), and the infection will last $y$ days, there will remain $x-2 \\times y$ houses on the end. Simultaneously, every day we can protect at least one house permanently, which indicates that for every distance between $a_i$ and $a_{i+1}$, if $x- 2\\times y > 0$, we have an opportunity to get one house protected. Moreover, the longer uninfected segments have priorities, because we can set two houses to stop the spread of inflection and the loss per day will be prevented. By contrast, for shorter segments, when all the houses in this segment are infected, then there won't be any loss afterwards. In other words, the loss of longer segments will last for longer time if we do not take actions in time. As a result, if we operate the longer segments as early as possible, we can protect more houses. In conclusion, our final strategy can be decribed as following: Sort the uninfected segments of houses according to their length, then the longer the segment is, the earlier we will deal with the houses lying on the side of the segment.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N = 500005, inf = 2147483647, M = 1004535809;\nint n, m, a[N], T, k;\nstruct str {\n\tint x, y;\n}t[N];\nint main() {\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tk = 0;\n\t\tscanf(\"%d %d\", &n, &m);\n\t\tfor (int i = 1; i <= m; ++i)\n\t\t\tscanf(\"%d\", &a[i]);\n\t\tsort(a + 1, a + 1 + m);\n\t\tfor (int i = 2; i <= m; ++i)\n\t\t\tt[++k] = { a[i] - a[i - 1] - 1,2 };\n\t\tint num_tmp = a[1] + n - a[m] - 1;\n\t\tif (num_tmp > 0) {\n\t\t\tt[++k] = { num_tmp, 2 };\n\t\t}\n\t\tsort(t + 1, t + 1 + k, [](str a, str b) {return a.x > b.x; });\n\t\tlong long ans = 0, cnt = 0;\n\t\tfor (int i = 1; i <= k; ++i) {\n\t\t    if (t[i].x - cnt * 2 > 0) {\n\t\t      int num_tmp = max(1ll, t[i].x - cnt * 2 - 1);\n\t\t\t  ans += num_tmp;\n\t\t    }\n\t\t    cnt += 2;\n\t\t}\n\t\tprintf(\"%lld\\n\", n - ans);\n\t}\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1704",
    "index": "D",
    "title": "Magical Array",
    "statement": "Eric has an array $b$ of length $m$, then he generates $n$ additional arrays $c_1, c_2, \\dots, c_n$, each of length $m$, from the array $b$, by the following way:\n\nInitially, $c_i = b$ for every $1 \\le i \\le n$. Eric secretly chooses an integer $k$ $(1 \\le k \\le n)$ and chooses $c_k$ to be the special array.\n\nThere are two operations that Eric can perform on an array $c_t$:\n\n- Operation 1: Choose two integers $i$ and $j$ ($2 \\leq i < j \\leq m-1$), subtract $1$ from both $c_t[i]$ and $c_t[j]$, and add $1$ to both $c_t[i-1]$ and $c_t[j+1]$. \\textbf{That operation can only be used on a non-special array, that is when $t \\neq k$.};\n- Operation 2: Choose two integers $i$ and $j$ ($2 \\leq i < j \\leq m-2$), subtract $1$ from both $c_t[i]$ and $c_t[j]$, and add $1$ to both $c_t[i-1]$ and $c_t[j+2]$. \\textbf{That operation can only be used on a special array, that is when $t = k$.}Note that Eric can't perform an operation if any element of the array will become less than $0$ after that operation.\n\nNow, Eric does the following:\n\n- For every \\textbf{non-special} array $c_i$ ($i \\neq k$), Eric uses \\textbf{only operation 1} on it \\textbf{at least once}.\n- For the \\textbf{special} array $c_k$, Eric uses \\textbf{only operation 2} on it \\textbf{at least once}.\n\nLastly, Eric discards the array $b$.\n\nFor given arrays $c_1, c_2, \\dots, c_n$, your task is to find out the special array, i.e. the value $k$. Also, you need to find the number of times of operation $2$ was used on it.",
    "tutorial": "First, let's focus on $\\textbf{operation 1}$ and do some calculations: 1. $a_{i-1} \\times (i-1) + a_i \\times i + a_j \\times j + a_{j+1} \\times (j+1) = i \\times (a_{i-1}+a_i) + j \\times (a_j+a_{j+1}) -a_{i-1} + a_{j+1}$ 2. $(a_{i-1}+1) \\times (i-1) + (a_i-1) \\times i + (a_j-1) \\times j + (a_{j+1}+1) \\times (j+1)$ $\\ \\ \\ = i \\times (a_{i-1}+a_i) + j \\times (a_j+a_{j+1}) -a_{i-1} + a_{j+1}$ See what? Yes, even if you give lots of $\\textbf{operation 1}$ to array $a$, the sum of $(a_{i} \\times i)$ remains. Thus, you can easily find $c_k$. And how to find the number of $\\textbf{operation 2}$ ? Let's do some calculations again: 1. $a_{i-1} \\times (i-1) + a_i \\times i + a_j \\times j + a_{j+1} \\times (j+1) +a_{j+2} \\times (j+2)$ $\\ \\ \\ = i \\times (a_{i-1}+a_i) + j \\times (a_j+a_{j+1}+a_{j+2}) -a_{i-1} + a_{j+1}+2 \\times a_{j+2}$ 2. $(a_{i-1}+1) \\times (i-1) + (a_i-1) \\times i + (a_j-1) \\times j + a_{j+1} \\times (j+1) + (a_{j+2}+1) \\times (j+2)$ $\\ \\ \\ = i \\times (a_{i-1}+a_i) + j \\times (a_j+a_{j+1}+a_{j+2}) -a_{i-1} + a_{j+1}+ 2 \\times a_{j+2} +1$ This operation will add $1$ to the result of $\\sum a_i\\times i$. Just minus the initial $\\sum a_i\\times i$ and you will get the number of operations applied.",
    "code": "#include <stdio.h>\n#include <string.h>\n#include <vector>\n#include <map>\n#include <cassert>\nconst int MAXN = 500005;\nstd::vector<long long> numbers[MAXN];\nstd::map<long long, long long> val_to_index;\nint main()\n{\n\tint t;\n\tint n, m;\n\tscanf(\"%d \", &t);\n\twhile (t--)\n\t{\n\t\tval_to_index.clear();\n\t\tscanf(\"%d %d\", &n, &m);\n\t\tlong long num_tmp;\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t    numbers[i].clear();\n\t\t    numbers[i].push_back(0);\n\t\t\tfor (int j = 1; j <= m; j++) {\n\t\t\t\tscanf(\"%lld\", &num_tmp);\n\t\t\t\tnumbers[i].push_back(num_tmp);\n\t\t\t}\n\t\t}\n\t\tlong long res_tmp = -1;\n\t\tfor (long long i = 1; i <= n; i++) {\n\t\t\tlong long val = 0;\n\t\t\tfor (long long j = 1; j <= m; j++) {\n\t\t\t\tval += (j * numbers[i][j]);\n\t\t\t}\n\t\t\tif (val_to_index.find(val) != val_to_index.end()) {\n\t\t\t    res_tmp = val;\n\t\t\t\tval_to_index[val] = -1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tval_to_index[val] = i;\n\t\t\t}\n\t\t}\n\t\tassert(val_to_index.size() == 2);\n\t\tfor (auto &item : val_to_index) {\n\t\t\tif (item.second != -1ll) {\n\t\t\t\tprintf(\"%lld %lld\\n\", item.second, std::abs(res_tmp - item.first));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "hashing",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1704",
    "index": "E",
    "title": "Count Seconds",
    "statement": "Cirno has a DAG (Directed Acyclic Graph) with $n$ nodes and $m$ edges. The graph has exactly one node that has no out edges. The $i$-th node has an integer $a_i$ on it.\n\nEvery second the following happens:\n\n- Let $S$ be the set of nodes $x$ that have $a_x > 0$.\n- For all $x \\in S$, $1$ is subtracted from $a_x$, and then for each node $y$, such that there is an edge from $x$ to $y$, $1$ is added to $a_y$.\n\nFind the first moment of time when all $a_i$ become $0$. Since the answer can be very large, output it modulo $998\\,244\\,353$.",
    "tutorial": "For the sink point, We can find that it may be zero at some time $t$ and $t \\leq n$, then it will be full for some continous time, and then will be zero forever. That's because for time $t\\ge n$, for some certain $a_x>0$, all roads from $x$ to the sink point must be greater than $0$ since $n$ rounds are enough for such $a_x$ to spread along these roads. Meanwhile, when some $a_y$ is decreased, it will also receive the numbers from upper nodes $x$. As a result, after $n$ turns, $a_y$ will be greater than $0$ until all $a_x$ turns to $0$ for all $x$ that there's an edge from $x$ to $y$. Simulate the first $n$ rounds, then we just need to calculate what's the final number on the sink node if the the number on the sink point is never decreased. That's exactly the rounds it will take the sink point to be decreased to $0$. Let $dp_i$ be the total number of $1$s the i-th node will add to some sink point finally if there is an $1$ on the i-th node. We can easily get the $dp_i$ in O(n) time for every sink point. Do a topological sort, and add the $sum_i$ of the current node $i$ to the $sum_j$ of the newly queued point $j$ during the sorting process. Calculate the sum of $s_i \\times dp_i$ and you can get the answer. The total time complexity will be $O(n^2)$. Note that the numbers on the nodes may be a multiple of $998244353$, so pay attention to them when simulating in the first $n$ turns.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N = 500005, inf = 2147483647, M = 998244353;\nint n, m, a[N], u, v, i, d[N], q[N], r, mx;\nint b[N], tmp[N];\nvector<int> g[N], z[N];\nlong long s[N];\nint p[15];\nvoid NEX(int M) {\n\tfor (int i = 1; i <= n; ++i)\n\t\tif (b[i]) {\n\t\t\ttmp[i] += b[i] - 1;\n\t\t\tfor (auto it : g[i])\n\t\t\t\t++tmp[it];\n\t\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tif (tmp[i] >= M)\n\t\t\tb[i] = tmp[i] % M + M;\n\t\telse\n\t\t\tb[i] = tmp[i] % M;\n\t\ttmp[i] = 0;\n\t}\n}\nint cal(int M) {\n\tfor (int i = 1; i <= n; ++i) {\n\t\tb[i] = a[i];\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tbool fl = false;\n\t\tfor (int j = 1; j <= n; ++j)\n\t\t\tif (b[j])\n\t\t\t\tfl = true;\n\t\tif (!fl)\n\t\t\treturn i - 1;\n\t\tNEX(M);\n\t}\n\treturn n;\n}\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--) {\n\t\tscanf(\"%d %d\", &n, &m);\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\tscanf(\"%d\", &a[i]);\n\t\t\tg[i].clear();\n\t\t\tz[i].clear();\n\t\t\td[i] = 0;\n\t\t\ttmp[i] = 0;\n\t\t\ts[i] = 0;\n\t\t}\n\t\tfor (int i = 1; i <= m; ++i) {\n\t\t\tscanf(\"%d %d\", &u, &v);\n\t\t\t++d[u];\n\t\t\tg[u].push_back(v);\n\t\t\tz[v].push_back(u);\n\t\t}\n\t\tmx = cal(M);\n\t\tif (mx < n) {\n\t\t\tcout << mx << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tr = 0;\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t\tif (!d[i])\n\t\t\t\tq[++r] = i;\n\t\ts[q[1]] = 1;\n\t\tfor (int i = 1; i <= r; ++i) {\n\t\t\ts[q[i]] %= M;\n\t\t\tfor (auto it : z[q[i]]) {\n\t\t\t\t--d[it];\n\t\t\t\ts[it] += s[q[i]];\n\t\t\t\tif (!d[it])\n\t\t\t\t\tq[++r] = it;\n\t\t\t}\n\t\t}\n\t\tlong long ans = n;\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t\tans = (ans + s[i] * b[i]) % M;\n\t\tcout << ans << endl;\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1704",
    "index": "F",
    "title": "Colouring Game",
    "statement": "Alice and Bob are playing a game. There are $n$ cells in a row. Initially each cell is either red or blue. Alice goes first.\n\nOn each turn, Alice chooses two neighbouring cells which contain at least one red cell, and paints that two cells white. Then, Bob chooses two neighbouring cells which contain at least one blue cell, and paints that two cells white. The player who cannot make a move loses.\n\nFind the winner if both Alice and Bob play optimally.\n\nNote that a chosen cell can be white, as long as the other cell satisfies the constraints.",
    "tutorial": "First, when the number red cells and blue cells are not equal, the player who owns a larger numberof his/her corresponding cells will win (Alice owns red and Bob owns blue). His/Her strategy can be: each time paint one segment of RB or BR white until there is none. This operation doesn't change the difference between the number of R and B and will decrease the number of the color of his/her opponent. Then Alice will only paint RW and WR, while Bob will only paint BW or WB. This operation will only decreace his/her own number of color, so the player who owns more cells of color will certainly win. When the number of red cells and blue cells are the same, Alice and Bob will play games first on red-and-blue segments, until there is no RB or BR, and the player who faces this situation will lose. Playing games on red-and-blue segments can be described as the following game: each player can take two neighbouring cells which has not be taken yet in his/her turn. As a result, this game becomes equal, then we can use SG function to forecast the result. This SG function has the following calculating method: $SG(n)=mex_{i=0}^{n-2} SG(i)\\oplus SG(n-2-i)$. In order to speed up, we can observe that ${SG(i)}$ has a cyclic section of length $34$ except for the first few elements. It can also be proved by verifying the first $34^2$ elements has this cyclic section, and this demonstrates that for all kinds of xor combination of the cyclic section leads to this cycle. Use Mathematical Induction and we can know this combination will be the the same (just add some repeated numbers to the calculation of $mex$ as the previous $34$-th number) for the subsequent elements. The total time complexity can be reduced to $O(n)$ in calculating the SG function.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N=500005,inf=2147483647,M=998244353;\nint n,i,t,f[N],vis[N];\nchar c[N];\nint main(){\n    for(int i=1;i<=1000;++i){\n        for(int j=0;j<=i-2;++j)\n            vis[f[j]^f[i-2-j]]=1;\n        int j;\n        for(j=0;vis[j];++j);\n        f[i]=j;\n        for(int j=0;j<=i;++j)\n            vis[j]=0;\n    }\n    for(int i=1001;i<N;++i)\n        f[i]=f[i-34];\n    scanf(\"%d\",&t);\n    while(t--){\n        scanf(\"%d\",&n);\n        scanf(\"%s\",c+1);\n        int s=0;\n        for(int i=1;i<=n;++i)\n            if(c[i]=='R')\n                ++s;\n            else\n                --s;\n        if(s>0)\n            puts(\"Alice\");\n        if(s<0)\n            puts(\"Bob\");\n        if(s==0){\n            int ans=0;\n            for(int i=1;i<=n;){\n                int j=i+1;\n                for(;j<=n&&c[j]!=c[j-1];++j);\n                    ans^=f[j-i];\n                i=j;\n            }\n            puts(ans?\"Alice\":\"Bob\");\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "games"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1704",
    "index": "G",
    "title": "Mio and Lucky Array",
    "statement": "Mio has an array $a$ consisting of $n$ integers, and an array $b$ consisting of $m$ integers.\n\nMio can do the following operation to $a$:\n\n- Choose an integer $i$ ($1 \\leq i \\leq n$) that has \\textbf{not} been chosen before, then add $1$ to $a_i$, subtract $2$ from $a_{i+1}$, add $3$ to $a_{i+2}$ an so on. Formally, the operation is to add $(-1)^{j-i} \\cdot (j-i+1) $ to $a_j$ for $i \\leq j \\leq n$.\n\nMio wants to transform $a$ so that it will contain $b$ as a \\textbf{subarray}. Could you answer her question, and provide a sequence of operations to do so, if it is possible?\n\nAn array $b$ is a \\textbf{subarray} of an array $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "Let's define $f_i = a_i + 2 a_{i-1} + a_{i-2}, g_i = b_i + 2b_{i-1} + b_{i-2}$. Cosidering after the operation on some index $i$, for any $j\\ne i$, $f_j$ will remain the same; For $j=i$, $f_j$ will be increased by $1$. Then we can find the operation on $a$ is a single point operation on $f$. It can be proved that the following conditions are equivalent to the condition that $b[1,m]$ can match $a[k+1,k+m]$: $\\left\\{\\begin{matrix} b_1=a_{k+1} \\\\ b_2 + b_1 = a_{k+2} + a_{k+1} \\\\ g_i = f_{k+i} (i \\ge 3) \\\\ \\end{matrix}\\right.$ For $i \\le k+2$, operation on $i$ will make $a_{k+1}+a_{k+2} \\gets a_{k+1} + a_{k+2} + (-1)^{k-i}$. So the second condition restricts the difference of operating times between odd positions and even positions among first $k+2$ positions. When conducting an operation on $i$ it will make $a_{k+1} \\gets a_{k+1} + (k+2-i)\\times (-1)^{k-i}$. So we can convert the problem to: using $-0,+1,-2,+3,-4,+5\\cdots,(-1)^n n$, to make the number of subtractions(operations which make $a_{k+1}$ be decreased) minus the number of additions(operations which make $a_{k+1}$ be increased) is $a$, and the final $a_{k+1}$ should be $b$. Further, suppose I first select all the subtractions($-0,-2,-4,-6,\\dots$), i.e. take all the operation on odd/even(depending on the parity of $k$) positions. If I don't want to select it afterwards, it can be regarded as a re-add operation, then the first and second restrictions can be converted to $a \\gets a +\\lfloor\\frac{k+1}{2}\\rfloor+1, b\\gets b+\\sum_{i= 0}^{\\lfloor \\frac{k+1}{2}\\rfloor} 2i$, where $a$ indicates that $a$ numbers need to be selected, and $b$ indicates that the selected sum is $b$. All $b$ which satisfies $\\sum_{i=0}^{a-1} i \\le b \\le \\sum_{i=k+1-a}^{k+1} i$ are legal and easy to construct. Next consider the third restriction, the constructor $f(k) = \\sum_{i=3}^m (g_i-f_{i+k})(g_i-f_{i+k}-1)$. If $f_{i+k}=g_i$ or $f_{i+k}+1=g_i$, then the above formula is 0. Whether $f_{i+k}=g_i$ respectively represents whether we need to operate on $k+i$, otherwise the above formula must be greater than 0. If $b[1,m]$ matches $a[k+1,k+m]$, then $f(k) = 0$, otherwise it must not match. So consider how to calculate $f$. $f(k) = \\sum_{i=3}^m f_{i+k}^2+g_i^2-2f_{i+k}g_i-g_i+f_i$ Considering that $f(k)$ may be quite large, you need to test several different prime numbers if you use NTT, in order to avoid hacking. The total time complexity $O(n\\log n)$. Also the available $k$ which satisfies the third restriction can also be found using bitset, the total time complexity $O(\\frac{n^2}{\\omega})$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int M1=998244353,M2=1004535809,M3=469762049,E=524288,N=200005;\nstruct poly{\n    const int M;\n    poly(int _M):M(_M){}\n    int R[N*4];\n    long long qpow(long long a,long long b){\n        long long ans=1;\n        while(b){\n            if(b&1)\n                ans=ans*a%M;\n            a=a*a%M;\n            b>>=1;\n        }\n        return ans;\n    }\n    long long wn[N*4],iwn[N*4],inv[N*4],fac[N*4],ifac[N*4];\n    void init(int E,int g){\n        int i;\n        iwn[E/2]=wn[E/2]=1;\n        long long s1=qpow(g,(M-1)/E);\n        long long s2=qpow(s1,M-2);\n        for(i=E/2+1;i<E;++i){\n            wn[i]=wn[i-1]*s1%M;\n            iwn[i]=iwn[i-1]*s2%M;\n        }\n        for(i=E/2-1;i;--i){\n            wn[i]=wn[i<<1];\n            iwn[i]=iwn[i<<1];\n        }\n        ifac[0]=fac[0]=inv[1]=1;\n        for(i=2;i<E;++i)\n            inv[i]=inv[M%i]*(M-M/i)%M;\n        for(i=1;i<E;++i){\n            ifac[i]=inv[i]*ifac[i-1]%M;\n            fac[i]=fac[i-1]*i%M;\n        }\n    }\n    unsigned long long ccc[N*4];\n    void NTT(long long *f,int lim,int op){\n        int i,j,k;\n        for(i=0;i<lim;++i){\n            R[i]=(R[i>>1]>>1)|(i&1?lim>>1:0);\n            if(R[i]<i)\n                swap(f[R[i]],f[i]);\n        }\n        for(i=0;i<lim;++i)\n            ccc[i]=(f[i]%M+M)%M;\n        for(i=1;i<lim;i<<=1)\n            for(j=0;j<lim;j+=(i<<1))\n                for(k=j;k<j+i;++k){\n                    long long w=(op==1?wn[k-j+i]:iwn[k-j+i]);\n                    unsigned long long p=ccc[k+i]*w%M;\n                    ccc[k+i]=ccc[k]+M-p;\n                    ccc[k]+=p;\n                }\n        for(i=0;i<lim;++i)\n            f[i]=ccc[i]%M;\n        if(op==-1){\n            long long inv=qpow(lim,M-2);\n            for(i=0;i<lim;++i)\n                f[i]=f[i]*inv%M;\n        }\n    }\n    long long ta[N*4],tb[N*4];\n    void mult(long long *a,int n,long long *b,int m,long long *c){\n        int lim=1;\n        while(lim<n+m)\n            lim<<=1;\n        copy(a,a+n,ta);\n        copy(b,b+m,tb);\n        for(int i=n;i<lim;++i)\n            ta[i]=0;\n        for(int i=m;i<lim;++i)\n            tb[i]=0;\n        NTT(ta,lim,1);\n        NTT(tb,lim,1);\n        for(int i=0;i<lim;++i)\n            ta[i]=ta[i]*tb[i]%M;\n        NTT(ta,lim,-1);\n        copy(ta,ta+lim,c);\n    }\n}X(M1),Y(M2),Z(M3);\nint n,m,o[N],t,tn;\nlong long a[N],b[N],c[N],d[N*4],e[N],f[N*4],ss[N],td[N],tf[N];\nbool fl[N],zz;\nvector<int> ans;\nlong long cal(int l,int r){\n    return 1ll*(l+r)*(r-l+1)/2;\n}\nlong long cal2(int u,int v){\n    return 1ll*((v-u)/2+1)*(u+v)/2;\n}\nbool iok(int n,int p,int q){\n    long long ss=q+1ll*(n/2)*(n/2+1);\n    p=p+(n/2+1);\n    long long mn=cal(0,p-1),mx=cal(n-p+1,n);\n    if(mn<=ss&&ss<=mx){\n        for(int i=n;i<n+m-2;++i)\n            if(td[i]!=tf[i-n+1]&&td[i]!=tf[i-n+1]-1)\n                return false;\n        ss-=mn;\n        for(int i=n;i<n+m-2;++i)\n            if(td[i]!=tf[i-n+1])\n                ans.push_back(i+2);\n        fill(fl,fl+1+n,0);\n        for(int i=0;i<p;++i)\n            fl[(ss/p+(i>=p-ss%p)+i)]=1;\n        for(int i=0;i<=n;++i)\n            if(fl[i]^(i&1)^1)\n                if(n+1-i<=tn)\n                    ans.push_back(n+1-i);\n        zz=true;\n        return true;\n    }\n    return false;\n}\nvoid OT(){\n    if(!zz)\n        puts(\"-1\");\n    else{\n        printf(\"%d\\n\",ans.size());\n        for(auto it:ans)\n            printf(\"%d \",it);\n        printf(\"\\n\");\n    }\n}\nvoid judgement(poly &v,long long *c,long long *e){\n    for(int i=0;i<n-2;++i)\n        d[i]=(c[i+1]+c[i+2])%v.M;\n    for(int i=0;i<m-2;++i)\n        f[i]=(e[i+1]+e[i+2])%v.M;\n    reverse(f,f+m-2);\n    long long s=0;\n    for(int i=0;i<m-2;++i)\n        s+=(f[i]*f[i]-f[i])%v.M;\n    for(int i=1;i<=n-2;++i)\n        ss[i]=(ss[i-1]+d[i-1]*(d[i-1]+1))%v.M;\n    v.mult(d,n-2,f,m-2,d);\n    for(int i=m-3;i<n-2;++i)\n        if((s+ss[i+1]-ss[i-m+3]-2*d[i])%v.M!=0)\n            o[i-m+4]=0;\n}\nint main(){\n    X.init(E,3);\n    Y.init(E,3);\n    Z.init(E,3);\n    scanf(\"%d\",&t);\n    while(t--){\n        scanf(\"%d\",&n);\n        tn=n;\n        for(int i=1;i<=n;++i)\n            scanf(\"%lld\",&a[i]);\n        scanf(\"%d\",&m);\n        for(int i=1;i<=m;++i)\n            scanf(\"%lld\",&b[i]);\n        for(int i=1;i<n;++i)\n            c[i]=a[i]+a[i+1];\n        for(int i=1;i<m;++i)\n            e[i]=b[i]+b[i+1];\n        fill(o,o+1+n,0);\n        ans.clear();\n        for(int i=1;i<=n;++i)\n            o[i]=1;\n        if(m>2){\n            for(int i=0;i<n-2;++i)\n                td[i+1]=c[i+1]+c[i+2];\n            for(int i=0;i<m-2;++i)\n                tf[i+1]=e[i+1]+e[i+2];\n            judgement(X,c,e);\n            judgement(Y,c,e);\n            judgement(Z,c,e);\n        }\n        else\n            for(int i=1;i<=n;++i)\n                o[i]=1;\n        int x=-1;\n        zz=false;\n        if(m==1){\n            for(int i=1;i<=n;++i)\n                if(-cal2(0,i/2*2)<=b[1]-a[i]&&b[1]-a[i]<=cal2(1,(i-1)/2*2+1)){\n                    for(int j=-(i/2+1);j<=(i+1)/2;++j)\n                        if(iok(i,j,b[1]-a[i]))\n                            break;\n                    break;\n                }\n        }\n        else\n            for(int i=1;i+m-1<=n;++i)\n                if(o[i]&&iok(i,(a[i]+a[i+1])-(b[1]+b[2]),b[1]-a[i]))\n                    break;\n        OT();\n    }\n}\n",
    "tags": [
      "constructive algorithms",
      "fft",
      "math",
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1704",
    "index": "H1",
    "title": "Game of AI (easy version)",
    "statement": "\\textbf{This is the easy version of this problem. The difference between easy and hard versions is the constraint on $k$ and the time limit. Also, in this version of the problem, you only need to calculate the answer when $n=k$. You can make hacks only if both versions of the problem are solved.}\n\nCirno is playing a war simulator game with $n$ towers (numbered from $1$ to $n$) and $n$ bots (numbered from $1$ to $n$). The $i$-th tower is initially occupied by the $i$-th bot for $1 \\le i \\le n$.\n\nBefore the game, Cirno first chooses a permutation $p = [p_1, p_2, \\ldots, p_n]$ of length $n$ (A permutation of length $n$ is an array of length $n$ where each integer between $1$ and $n$ appears exactly once). After that, she can choose a sequence $a = [a_1, a_2, \\ldots, a_n]$ ($1 \\le a_i \\le n$ and $a_i \\ne i$ for all $1 \\le i \\le n$).\n\nThe game has $n$ rounds of attacks. In the $i$-th round, if the $p_i$-th bot is still in the game, it will begin its attack, and as the result the $a_{p_i}$-th tower becomes occupied by the $p_i$-th bot; the bot that previously occupied the $a_{p_i}$-th tower will no longer occupy it. If the $p_i$-th bot is not in the game, nothing will happen in this round.\n\nAfter each round, if a bot doesn't occupy any towers, it will be eliminated and leave the game. Please note that no tower can be occupied by more than one bot, but one bot can occupy more than one tower during the game.\n\nAt the end of the game, Cirno will record the result as a sequence $b = [b_1, b_2, \\ldots, b_n]$, where $b_i$ is the number of the bot that occupies the $i$-th tower at the end of the game.\n\nHowever, as a mathematics master, she wants you to solve the following counting problem instead of playing games:\n\nCount the number of different pairs of sequences $a$ and $b$ that we can get from all possible choices of sequence $a$ and permutation $p$.\n\nSince this number may be large, output it modulo $M$.",
    "tutorial": "Consider calculate the number of possible sequences $a$ for a fixed sequence $b$. We can find that if $b_i\\ne i$, that means $i$ is occupied by $b_i$ finally, so we have $a_{b_i}$=i. If $b_i=i$, that means for all $j$ that $a_j=i$, $j$ is occupied before it begins its attack. As a result, we must have $b_j\\ne j$. The sequences $a$ which satisfies the above conditions is also possible to match a valid $p$. The attacking order can be arranged easily. Now for how to count, we can build a graph according to the information given by $b_i\\ne i$. We can see that the graph will in the form of some chains. Also, we can find that for a graph which consists of some chains, we can find the unique $b$ which satisfies the graph. Then some positions of array $a$ is also fixed, except the top of each chain. As for how to decide the these $a_i$($i$ is the top of some chain), we need to divide into two situations: one is the chain's length is greater than $1$, we can see that this $a_i$ can take any number between $1$ and $n$ except $i$; The other one is the chain's length is one, so $a_i$ cannot be any bottom of each chain. Then we can easily calculate the number of arrays $a$ by product the possible number of values of each $a_i$. In conclusion, we can enumerate the number of chains, and the number of chains with length $1$, then use combination number to calculate. Time complexity is $O(n^2)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N=200005,E=15000005;\nconst long long inf=1000000000000000000ll;\nint n,M,mi[5005][5005];\nlong long fac[N],inv[N],ans;\nlong long C(int n,int m){\n    return fac[n]*inv[m]%M*inv[n-m]%M;\n}\nlong long qpow(long long a,long long b){\n    long long s=a,ans=1;\n    while(b){\n        if(b&1)\n            ans=ans*s%M;\n        s=s*s%M;\n        b>>=1;\n    }\n    return ans;\n}\nint main(){\n    cin>>n>>M;\n    fac[0]=inv[0]=inv[1]=1;\n    for(int i=2;i<=n;++i)\n        inv[i]=inv[M%i]*(M-M/i)%M;\n    for(int i=1;i<=n;++i){\n        inv[i]=inv[i-1]*inv[i]%M;\n        fac[i]=fac[i-1]*i%M;\n    }\n    long long s1=1;\n    for(int i=0;i<=n;++i){\n        mi[i][0]=1;\n        for(int j=1;j<=n;++j)\n            mi[i][j]=1ll*mi[i][j-1]*i%M;\n    }\n    for(int j=1;2*j<=n;++j){\n        s1=s1*(n-1)%M;\n        for(int i=0;i<=n-2*j;++i)\n            ans=(ans+C(n,i)*fac[n-i]%M*s1%M*mi[n-i-j][i]%M*C(n-i-j-1,j-1)%M*inv[j])%M;\n    }\n    cout<<ans<<endl;\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1704",
    "index": "H2",
    "title": "Game of AI (hard version)",
    "statement": "\\textbf{This is the hard version of this problem. The difference between easy and hard versions is the constraint on $k$ and the time limit. Notice that you need to calculate the answer for all positive integers $n \\in [1,k]$ in this version. You can make hacks only if both versions of the problem are solved.}\n\nCirno is playing a war simulator game with $n$ towers (numbered from $1$ to $n$) and $n$ bots (numbered from $1$ to $n$). The $i$-th tower is initially occupied by the $i$-th bot for $1 \\le i \\le n$.\n\nBefore the game, Cirno first chooses a permutation $p = [p_1, p_2, \\ldots, p_n]$ of length $n$ (A permutation of length $n$ is an array of length $n$ where each integer between $1$ and $n$ appears exactly once). After that, she can choose a sequence $a = [a_1, a_2, \\ldots, a_n]$ ($1 \\le a_i \\le n$ and $a_i \\ne i$ for all $1 \\le i \\le n$).\n\nThe game has $n$ rounds of attacks. In the $i$-th round, if the $p_i$-th bot is still in the game, it will begin its attack, and as the result the $a_{p_i}$-th tower becomes occupied by the $p_i$-th bot; the bot that previously occupied the $a_{p_i}$-th tower will no longer occupy it. If the $p_i$-th bot is not in the game, nothing will happen in this round.\n\nAfter each round, if a bot doesn't occupy any towers, it will be eliminated and leave the game. Please note that no tower can be occupied by more than one bot, but one bot can occupy more than one tower during the game.\n\nAt the end of the game, Cirno will record the result as a sequence $b = [b_1, b_2, \\ldots, b_n]$, where $b_i$ is the number of the bot that occupies the $i$-th tower at the end of the game.\n\nHowever, as a mathematics master, she wants you to solve the following counting problem instead of playing games:\n\nCount the number of different pairs of sequences $a$, $b$ from all possible choices of sequence $a$ and permutation $p$.\n\nCalculate the answers for all $n$ such that $1 \\le n \\le k$. Since these numbers may be large, output them modulo $M$.",
    "tutorial": "Given $b$, The conclusion of possible array $a$ remains. If we fix array $a$, we will find that for each $i$, $b_i$ will only be $j$ that $a_j=i$ or $j=i$. For any pair $(x,y)$, if $a_x=y$, we will find that $b_x=x$ and $b_y=y$ at the same time is impossible. All arrays $b$ which satisfies the above conditions are valid. So for a fixed array $a$, and we fix the position that $b_i=i$(It can be shown that the chosen nodes form a independent set), then the number of possible $b$ will be product of each in-degree of each $x$ that $b_x\\ne x$. Now we can see if we build a graph according to $a$, the answer will be the sume of product over all independent sets. We need to solve the problem of three parts: the nodes form a tree, some trees' roots form a ring, some trees based on rings form a graph. For the tree part, let $P(x)$ be generating function of the sum of pruducts if the root is not included in the independent set, and $Q(x)$ otherwise. Then we have: $P(x)=x(P(x)+Q(x))e^{P(x)+Q(x)}$ $Q(x)=xe^{P(x)}$ We can solve the equation, and use Newton's method to calculate $P(x)$ and $Q(x)$. Consider how to merge trees together. If one root is not in the independent set, It can either be occupied by one of its children or the previous node on the ring, so its generating function can be represented as $A(x)$(compared with $P(x)$, it adds the contribution caused by that it's occupied by the previous node on the ring), which is easy to calculate. For those which are in the independent set, their previous nodes must not be in. So we binding them together and their generating functions can be represented as $B(x)$. The final answer is $\\sum_{i=1}^{+\\infty} \\frac{(A(x)+B(x))^i}{i}-A(x)=-\\ln(1-A(x)-B(x))-A(x)$. Note that when every node on the ring is occupied by previous node, it is also impossible. So we need to minus this answer. It can be calculated with similar method. At last, we need to combine these rings into a graph, which can be done with $exp$ operation. Time complexity is $O(n\\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N=100005,inf=2147483647;\nconst long long sq5=200717101;\nint M;\nnamespace poly{\n    int R[N*4];\n    long long qpow(long long a,long long b){\n        long long ans=1;\n        while(b){\n            if(b&1)\n                ans=ans*a%M;\n            a=a*a%M;\n            b>>=1;\n        }\n        return ans;\n    }\n    long long wn[N*4],iwn[N*4],inv[N*4],fac[N*4],ifac[N*4],g;\n    void init(int E){\n        int i;\n        iwn[E/2]=wn[E/2]=1;\n        long long s1=qpow(g,(M-1)/E);\n        long long s2=qpow(s1,M-2);\n        for(i=E/2+1;i<E;++i){\n            wn[i]=wn[i-1]*s1%M;\n            iwn[i]=iwn[i-1]*s2%M;\n        }\n        for(i=E/2-1;i;--i){\n            wn[i]=wn[i<<1];\n            iwn[i]=iwn[i<<1];\n        }\n        ifac[0]=fac[0]=inv[1]=1;\n        for(i=2;i<E;++i)\n            inv[i]=inv[M%i]*(M-M/i)%M;\n        for(i=1;i<E;++i){\n            ifac[i]=inv[i]*ifac[i-1]%M;\n            fac[i]=fac[i-1]*i%M;\n        }\n    }\n    unsigned long long ccc[N*4];\n    void NTT(long long *f,int lim,int op){\n        int i,j,k;\n        for(i=0;i<lim;++i){\n            R[i]=(R[i>>1]>>1)|(i&1?lim>>1:0);\n            if(R[i]<i)\n                swap(f[R[i]],f[i]);\n        }\n        for(i=0;i<lim;++i)\n            ccc[i]=(f[i]%M+M)%M;\n        for(i=1;i<lim;i<<=1)\n            for(j=0;j<lim;j+=(i<<1))\n                for(k=j;k<j+i;++k){\n                    long long w=(op==1?wn[k-j+i]:iwn[k-j+i]);\n                    unsigned long long p=ccc[k+i]*w%M;\n                    ccc[k+i]=ccc[k]+M-p;\n                    ccc[k]+=p;\n                }\n        for(i=0;i<lim;++i)\n            f[i]=ccc[i]%M;\n        if(op==-1){\n            long long inv=qpow(lim,M-2);\n            for(i=0;i<lim;++i)\n                f[i]=f[i]*inv%M;\n        }\n    }\n    long long ta[N*4],tb[N*4];\n    void mult(long long *a,int n,long long *b,int m,long long *c){\n        int lim=1;\n        while(lim<n+m)\n            lim<<=1;\n        copy(a,a+n,ta);\n        copy(b,b+m,tb);\n        for(int i=n;i<lim;++i)\n            ta[i]=0;\n        for(int i=m;i<lim;++i)\n            tb[i]=0;\n        NTT(ta,lim,1);\n        NTT(tb,lim,1);\n        for(int i=0;i<lim;++i)\n            ta[i]=ta[i]*tb[i]%M;\n        NTT(ta,lim,-1);\n        copy(ta,ta+lim,c);\n    }\n    long long tmp[N*4],tans[N*4];\n    void Getinv(long long *a,long long *ans,int lim){\n        ans[0]=qpow(a[0],M-2);\n        for(int i=1;i<lim;i<<=1){\n            for(int j=i;j<(i<<2);++j)\n                ans[j]=tans[j]=tmp[j]=0;\n            for(int j=0;j<(i<<1);++j)\n                tmp[j]=a[j];\n            for(int j=0;j<i;++j)\n                tans[j]=ans[j];\n            NTT(tmp,i<<2,1);\n            NTT(tans,i<<2,1);\n            for(int j=0;j<(i<<2);++j)\n                tmp[j]=tmp[j]*tans[j]%M*tans[j]%M;\n            NTT(tmp,i<<2,-1);\n            for(int j=0;j<(i<<1);++j)\n                ans[j]=(2*ans[j]-tmp[j])%M;\n        }\n    }\n    long long tinv[N*4];\n    void Getln(long long *a,long long *ans,int n){\n        for(int i=0;i<n-1;++i)\n            ans[i]=a[i+1]*(i+1)%M;\n        Getinv(a,tinv,n);\n        mult(ans,n-1,tinv,n,ans);\n        for(int i=n;i>=1;--i)\n            ans[i]=ans[i-1]*inv[i]%M;\n        ans[0]=0;\n    }\n    long long tln[N*4];\n    void Getexp(long long *a,long long *ans,int n){\n        ans[0]=1;\n        for(int i=1;i<n;i<<=1){\n            for(int j=i;j<(i<<1);++j)\n                ans[j]=0;\n            Getln(ans,tln,i<<1);\n            for(int j=0;j<(i<<1);++j)\n                tln[j]=-tln[j]+a[j];\n            ++tln[0];\n            mult(ans,i,tln,i<<1,ans);\n        }\n    }\n    void Getroot(long long *a,long long *ans,int n){\n        ans[0]=1;\n        for(int i=1;i<n;i<<=1){\n            fill(ans+i,ans+(i<<1),0);\n            Getinv(ans,tinv,i<<1);\n            mult(tinv,i<<1,a,i<<1,tinv);\n            for(int j=0;j<(i<<1);++j)\n                ans[j]=(ans[j]+tinv[j])*inv[2]%M;\n        }\n    }\n    long long ttln[N*4];\n    void Getpow(long long *a,long long *ans,int n,int m){\n        Getln(a,ttln,m);\n        for(int i=0;i<m;++i)\n            ttln[i]=ttln[i]*n%M;\n        Getexp(ttln,ans,m);\n    }\n};\nint n,m;\nlong long f[N*4],g[N*4],h[N*4],hd[N*4],tmp[N*4],eh[N*4],tmp2[N*4],inv[N*4];\nvoid Newton(int lim){\n    f[0]=f[1]=0;\n    for(int i=2;i<lim;i<<=1){\n        poly::Getexp(f,g,i<<1);\n        for(int j=(i<<1)-1;j>=1;--j)\n            g[j]=g[j-1];\n        g[0]=0;\n        for(int j=0;j<(i<<1);++j)\n            h[j]=(f[j]+g[j])%M;\n        poly::Getexp(h,eh,i<<1);\n        poly::mult(eh,i<<1,h,i<<1,tmp);\n        ++h[0];\n        ++g[0];\n        poly::mult(g,i<<1,h,i<<1,tmp2);\n        poly::mult(tmp2,i<<1,eh,i<<1,tmp2);\n        for(int j=(i<<1);j>=1;--j){\n            tmp2[j]=-tmp2[j-1];\n            tmp[j]=-tmp[j-1];\n        }\n        tmp2[0]=1;\n        for(int j=0;j<(i<<1);++j)\n            tmp[j]=(tmp[j]+f[j])%M;\n        poly::Getinv(tmp2,inv,i<<1);\n        poly::mult(inv,i<<1,tmp,i<<1,h);\n        for(int j=0;j<(i<<1);++j)\n            f[j]=(f[j]-h[j])%M;\n    }\n}\nlong long rt[N*4],X[N*4],Y[N*4],p1[N*4],p2[N*4],p[N*4],e1[N*4],e2[N*4];\nlong long fd[N*4],gd[N*4],as[N*4],ans[N*4],as2[N*4];\nint lim=1;\nint main(){\n    cin>>n>>M;\n    int tmpp=M-1;\n    vector<int> dz;\n    for(int i=2;i*i<=tmpp;++i)\n        while(tmpp%i==0){\n            tmpp/=i;\n            dz.push_back(i);\n        }\n    if(tmpp!=1)\n        dz.push_back(tmpp);\n    for(int i=2;i<M;++i){\n        int z=M-1;\n        bool fl=true;\n        for(auto it:dz)\n            if(poly::qpow(i,z/it)==1){\n                fl=false;\n                break;\n            }\n        if(fl){\n            poly::g=i;\n            break;\n        }\n    }\n    poly::init(262144);\n    ++n;\n    while(lim<=n*2)\n        lim<<=1;\n    Newton(n+1);\n    memset(inv,0,sizeof(inv));\n    poly::Getexp(f,g,n+1);\n    for(int j=n;j>=1;--j)\n        g[j]=g[j-1];\n    g[0]=0;\n    for(int j=0;j<=n;++j)\n        h[j]=(f[j]+g[j])%M;\n    poly::Getexp(h,eh,n+1);\n    for(int j=1;j<=n;++j)\n        tmp[j]=-eh[j-1];\n    tmp[0]=1;\n    poly::Getln(tmp,as2,n+1);\n    for(int j=1;j<=n;++j)\n        as2[j]=(as2[j]-f[j])%M;\n    poly::mult(eh,n+1,h,n+1,X);\n    for(int i=0;i<=n;++i)\n        eh[i]=(X[i]+eh[i])%M;\n    for(int i=n;i>=1;--i){\n        eh[i]=eh[i-1];\n        Y[i]=eh[i];\n    }\n    eh[0]=0;\n    poly::mult(eh,n+1,g,n+1,eh);\n    for(int i=1;i<=n;++i)\n        h[i]=(-eh[i]-Y[i])%M;\n    h[0]=1;\n    poly::Getln(h,as,n+1);\n    for(int i=0;i<=n;++i)\n        as[i]=(-as[i]+as2[i])%M;\n    poly::Getexp(as,ans,n+1);\n    --n;\n    for(int i=1;i<=n;++i)\n        printf(\"%lld\\n\",(ans[i]*poly::fac[i]%M+M)%M);\n}",
    "tags": [
      "combinatorics",
      "fft",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1705",
    "index": "A",
    "title": "Mark the Photographer",
    "statement": "Mark is asked to take a group photo of $2n$ people. The $i$-th person has height $h_i$ units.\n\nTo do so, he ordered these people into two rows, the front row and the back row, each consisting of $n$ people. However, to ensure that everyone is seen properly, the $j$-th person of the back row must be at least $x$ units taller than the $j$-th person of the front row for each $j$ between $1$ and $n$, inclusive.\n\nHelp Mark determine if this is possible.",
    "tutorial": "First, sort $h_1 \\leq h_2 \\leq \\dots \\leq h_{2n}$. There is a very explicit description to which $h_i$'s work. What is the optimal arrangement that maximizes the minimum difference across all pairs? We have a very explicit description of whether the arrangement is possible. Sort the heights so that $h_1 \\leq h_2 \\leq \\dots \\leq h_{2n}$. Then, there exists such arrangement if and only if all the following conditions hold. $\\begin{align*} h_{n+1}-h_1 &\\geq x \\\\ h_{n+2}-h_2 &\\geq x \\\\ &\\vdots \\\\ h_{2n}-h_n &\\geq x \\end{align*}$ We present two proofs. Proof 1 (Direct Proof). Suppose that the arrangement is possible. We will show that for each $i$, we have $h_{n+i}-h_i\\geq x$. To do so, note that $n+1$ people who have height in $[h_i, h_{n+i}]$. It's impossible that these $n+1$ people got assigned to different columns (because there are $n$ columns), so there exist two people that got assigned to the same column. However, because these two people have height in $[h_i, h_{n+i}]$, the difference in heights between these two people is at most $h_{n+i}-h_i$. As the difference is at least $x$ by the arrangement, we must have that $h_{n+i}-h_i\\geq x$. $\\blacksquare$ Proof 2 (Exchange Argument). First, we look at two pairs. Suppose that the $i$-th person in the first and second row have heights $a < b$, while the $j$-th person in the first and second row have heights $c < d$. $\\begin{array}{ccccc} \\dots & a & \\dots & c & \\dots \\\\ \\dots & b & \\dots & d & \\dots \\end{array}$ Assume that $b\\geq c$, then we switch $b,c$. The arrangement still works since $a-c \\geq a-b \\geq x$ and $b-d \\geq c-d \\geq x$. Similarly, $a\\geq d$ yields a switch. Thus, we can keep exchanging until anyone in the first row is at least as tall as anyone in the second row. Thus, the first row must be $h_{n+1}, h_{n+2}, \\dots, h_{2n}$, while the second row must be $h_1, h_2, \\dots, h_n$ in some order. Now, we look at the same picture again. Assume that $a\\geq c$ but $b\\leq d$. then, we can switch $b,d$, and it still works because $a-d \\geq c-d \\geq x$ and $c-b \\geq c-d \\geq x$. Thus, we can switch the second row until it matches the order of the first row. Therefore, we force the first row to be $h_{n+1}, h_{n+2}, \\dots, h_{2n}$, while the second row must be $h_1, h_2, \\dots, h_n$ in that order. This implies the conclusion. $\\blacksquare$ Time Complexity: $O(n\\log n)$ for sorting.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n, x;\n    cin >> n >> x;\n    vector<int> a(2 * n);\n    for (int i = 0; i < 2 * n; ++i)\n        cin >> a[i];\n    sort(a.begin(), a.end());\n    bool ok = true;\n    for (int i = 0; i < n; ++i)\n        if (a[n + i] - a[i] < x) ok = false;\n    cout << (ok ? \"YES\" : \"NO\") << \"\\n\";\n}\n\nint main() {\n    int tt; cin >> tt;\n    while (tt--) solve();\n}\n",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1705",
    "index": "B",
    "title": "Mark the Dust Sweeper",
    "statement": "Mark is cleaning a row of $n$ rooms. The $i$-th room has a nonnegative dust level $a_i$. He has a magical cleaning machine that can do the following three-step operation.\n\n- Select two indices $i<j$ such that the dust levels $a_i$, $a_{i+1}$, $\\dots$, $a_{j-1}$ are all strictly greater than $0$.\n- Set $a_i$ to $a_i-1$.\n- Set $a_j$ to $a_j+1$.\n\nMark's goal is to make $a_1 = a_2 = \\ldots = a_{n-1} = 0$ so that he can nicely sweep the $n$-th room. Determine the minimum number of operations needed to reach his goal.",
    "tutorial": "The optimal way is to fill all the zero entries first. Delete the leading zeroes in the array $a$ (i.e., the first $t$ numbers of $a$ that are zero) so that now $a_1\\ne 0$. Let $k$ be the number of $0$'s in $a_1,a_2,\\dots,a_{n-1}$. The answer is $(a_1+a_2+\\dots + a_{n-1}) + k.$ To see why, let Mark keep filling the holes (rooms with dust level $0$) first by subtracting the first nonzero index and changing the first zero index to $1$. This takes $k$ moves to fill all zeroes in $a_1,a_2,\\dots,a_{n-1}$. Then, we can start moving, from left to right, all dust to the $n$-th room, taking $a_1+a_2+\\dots+a_{n-1}$ moves. Finally, we argue that this is the minimum number of moves. To that end, we prove that each move decreases the answer by at most $1$. We consider two cases. If a move has $j=n$, then it decreases $a_1+a_2+\\dots+a_{n-1}$ by $1$ but does not decrease $k$. If $j\\ne n$, then the move doesn't decrease $a_1+a_2+\\dots+a_{n-1}$ and decreases $k$ by at most $1$. Thus, we are done. The time complexity is $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n#define ll long long\n\nusing namespace std;\n\n\nvoid solve(){\n    int n; cin >> n;\n    vector<int> a(n);\n    for(int i = 0; i < n; ++i)\n        cin >> a[i];\n    ll ans = 0;\n    int ptr = 0;\n    while(ptr < n && a[ptr] == 0)\n        ptr++;\n    for(int i = ptr; i < n-1; ++i){\n        ans += a[i];\n        if(a[i] == 0) ans++;\n    }\n    cout << ans << \"\\n\";\n}\nint main(){\n    int tt; cin >> tt;\n    while(tt--) solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1705",
    "index": "C",
    "title": "Mark and His Unfinished Essay",
    "statement": "One night, Mark realized that there is an essay due tomorrow. He hasn't written anything yet, so Mark decided to randomly copy-paste substrings from the prompt to make the essay.\n\nMore formally, the prompt is a string $s$ of initial length $n$. Mark will perform the copy-pasting operation $c$ times. Each operation is described by two integers $l$ and $r$, which means that Mark will append letters $s_l s_{l+1} \\ldots s_r$ to the end of string $s$. Note that the length of $s$ increases after this operation.\n\nOf course, Mark needs to be able to see what has been written. After copying, Mark will ask $q$ queries: given an integer $k$, determine the $k$-th letter of the final string $s$.",
    "tutorial": "What's in common between all letters that were copied at the same time? The answer is the difference between the current position and the position where it came from. That's what you need to store. By tracking the difference, you can recurse to the previously-copied substring. This is an implementation problem. What you need to do is after the $i$-th copying operation, we need to keep track of the beginning point $a_i$ and the ending point $b_i$ of the appended string. Moreover, we also keep track the subtraction distance $t_i = a_i-l_i$ so that for $k\\in [a_i, b_i]$, the $k$-th letter is the same as the $(k-t_i)$-th letter. Thus, we have recursed the position to the smaller position $k-t_i$, so we keep doing that until we reach the initial string. Therefore, to solve this problem, we iterate from $i=c,c-1,\\dots,1$. If $k$ is in $[a_i,b_i]$, subtract $k$ by $t_i$. After all operations, $k$ should be at the inital string, and we output the $k$-th letter. The time complexity of this solution is $O(cq)$. However, less efficient solutions of $O((c\\log c) q)$ (using binary search each time) or $O(c^2q)$ (by going through all intervals in each iteration) pass as well.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\n\nusing namespace std;\n\nvoid solve(){\n    int n, c, q; cin >> n >> c >> q;\n    string s; cin >> s;\n\n    vector<ll> left(c+1), right(c+1), diff(c+1);\n    left[0] = 0;\n    right[0] = n;\n\n    for(int i=1; i<=c; ++i){\n    \tll l, r; cin >> l >> r;\n    \tl--; r--;\n    \tleft[i] = right[i-1];\n    \tright[i] = left[i] + (r-l+1);\n    \tdiff[i] = left[i] - l;\n    }\n\n    while(q--){\n    \tll k; cin >> k;\n    \tk--;\n    \tfor(int i=c; i>=1; --i){\n    \t\tif(k < left[i]) continue;\n    \t\telse k -= diff[i];\n    \t}\n    \tcout << s[k] << \"\\n\";\n    }\n\n}\n\nint main(){\n    int tt; cin >> tt;\n    while(tt--) solve();\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1705",
    "index": "D",
    "title": "Mark and Lightbulbs",
    "statement": "Mark has just purchased a rack of $n$ lightbulbs. The state of the lightbulbs can be described with binary string $s = s_1s_2\\dots s_n$, where $s_i=1$ means that the $i$-th lightbulb is turned on, while $s_i=0$ means that the $i$-th lightbulb is turned off.\n\nUnfortunately, the lightbulbs are broken, and the only operation he can perform to change the state of the lightbulbs is the following:\n\n- Select an index $i$ from $2,3,\\dots,n-1$ such that $s_{i-1}\\ne s_{i+1}$.\n- Toggle $s_i$. Namely, if $s_i$ is $0$, set $s_i$ to $1$ or vice versa.\n\nMark wants the state of the lightbulbs to be another binary string $t$. Help Mark determine the minimum number of operations to do so.",
    "tutorial": "Look at all the $01$'s and $10$'s carefully. The sum of the number of $01$'s and $10$'s is constant. Consider all positions of $01$'s and $10$'s. How does it change in each operation? As explained in the sample explanations, the operation cannot change the first or the last bit. Thus, if either $s_1\\ne t_1$ or $s_n\\ne t_n$, simply return $\\texttt{-1}$. Now, the key idea is to consider a binary $\\overline{s} = (s_1\\oplus s_2)(s_2\\oplus s_3) \\dots (s_{n-1}\\oplus s_n)$ of length $n-1$, where $a\\oplus b$ denotes the XOR operation of bits $a$ and $b$. Then, it's easy to verify that the operation acts on $\\overline{s}$ by just swapping two different bits. An example is shown below $\\begin{array}{cc} s & \\overline s \\\\ \\texttt{000101} & \\texttt{00111} \\\\ \\downarrow & \\downarrow \\\\ \\texttt{001101} & \\texttt{01011}\\\\ \\downarrow & \\downarrow \\\\ \\texttt{011101} & \\texttt{10011} \\\\ \\downarrow & \\downarrow \\\\ \\texttt{011001} & \\texttt{10101} \\\\ \\downarrow & \\downarrow \\\\ \\texttt{011011} & \\texttt{10110} \\\\ \\downarrow & \\downarrow \\\\ \\texttt{010011} & \\texttt{11010} \\end{array}$ Thus, the operation is possible if and only if $\\overline s$ and $\\overline t$ has the same number of $1$'s. Moreover, if $a_1,a_2,\\dots,a_k$ are the positions of $1$'s in $\\overline s$ and $b_1,b_2,\\dots,b_k$ are the positions of $1$'s in $\\overline t$. Then, the minimum number of moves is given by $|a_1-b_1| + |a_2-b_2| + \\dots + |a_k-b_k|,$ which can be evaluated in $O(n)$. This is a well-known fact, but for completeness, here is the proof. Note that the operation is moving $1$ to left or right by one position. Thus, to achieve that number of moves, simply move the first $1$ from $a_1$ to $b_1$, move the second $1$ from $a_2$ to $b_2$, $\\ldots$, and move the $k$-th $1$ from $a_k$ to $b_k$. For the lower bound, notice that the $i$-th $1$ cannot move past the $(i-1)$-th or $(i+1)$-th $1$. Thus, it takes at least $|a_i-b_i|$ moves to move the $i$-th $1$ from $a_i$ to $b_i$. Summing gives the conclusion. Note that another way to think about this problem is to look at the block of $1$'s and $0$'s and notice that the number of blocks remains constant. This is more or less the same as the above solution.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\n\nusing namespace std;\n\nvoid solve(){\n    int n; cin >> n;\n    string s,t; cin >> s >> t;\n    vector<ll> pos_s, pos_t;\n\n    if(s[0] != t[0] || s[n-1] != t[n-1]){\n        cout << -1 << \"\\n\";\n        return;\n    }\n    for(int i=0; i<n-1; i++){\n        if(s[i] != s[i+1]) pos_s.push_back(i);\n        if(t[i] != t[i+1]) pos_t.push_back(i);\n    }\n    if(pos_s.size() != pos_t.size()){\n        cout << -1 << \"\\n\";\n    }\n    else{\n        int k = pos_s.size();\n        ll ans = 0;\n        for(int i=0; i<k; ++i){\n            ans += abs(pos_s[i] - pos_t[i]);\n        }\n        cout << ans << \"\\n\";\n    }\n}\n\nint main(){\n    int tt; cin >> tt;\n    while(tt--) solve();\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1705",
    "index": "E",
    "title": "Mark and Professor Koro",
    "statement": "After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $n$ positive integers $a_1, a_2,\\dots,a_n$ on it.\n\nThen, professor Koro comes in. He can perform the following operation:\n\n- select an integer $x$ that appears at least $2$ times on the board,\n- erase those $2$ appearances, and\n- write $x+1$ on the board.\n\nProfessor Koro then asks Mark the question, \"what is the maximum possible number that could appear on the board after some operations?\"\n\nMark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $q$ times. Each time, he will choose positive integers $k$ and $l$, then change $a_k$ to $l$. After each update, he will ask Mark the same question again.\n\nHelp Mark answer these questions faster than Professor Koro!\n\nNote that the updates are persistent. Changes made to the sequence $a$ will apply when processing future updates.",
    "tutorial": "Find a concise description of the answer first. Think about power of two. The sum $2^{a_1}+2^{a_2}+\\dots+2^{a_n}$ is constant. Show that the answer must be the most significant bit of that. Use either bitset or lazy segment tree to simulate the addition/subtraction. The key observation is the following. Claim: The answer is $\\lfloor\\log_2(2^{a_1}+2^{a_2}+\\dots+2^{a_n})\\rfloor.$ Proof: The upper bound is pretty clear, as the operation doesn't change the $\\sum 2^{a_i}$. Moreover, the sum must be at least $2^{\\text{ans}}$, giving the result. For the construction, let Mark keep performing the operation until he cannot. At this point, all numbers must be distinct, and the $\\sum 2^{a_i}$ is unchanged. Let the current numbers on the board be $b_1<b_2<\\dots < b_k$. Then, $\\sum_{i=1}^n 2^{a_i} = 2^{b_1}+2^{b_2}+\\dots + 2^{b_k} \\leq 2^1+2^2+\\dots+2^{b_k} < 2^{b_k+1}.$ Thus, Mark can make the final number be $b_k = \\lfloor\\log_2(2^{a_1}+2^{a_2}+\\dots+2^{a_n})\\rfloor$ as desired. $\\blacksquare$ Finally, we need a data structure to maintain the $\\sum 2^{a_i}$ and simulate base 2 addition. There are many ways to proceed, including the following: Using bitsets, partition the bits into many chunks of $w$ bits ($w$ between $50$ and $64$ is fine). This gives $O(n^2/w)$ complexity, but its low constant factor makes it enough to pass comfortably. Using bitsets, partition the bits into many chunks of $w$ bits ($w$ between $50$ and $64$ is fine). This gives $O(n^2/w)$ complexity, but its low constant factor makes it enough to pass comfortably. Use lazy segment augmented with $O(\\log n)$ binary search. For each bit added, find where the longest streak of $1$'s to the left of that bit ends, and update accordingly. Similarly, for each bit subtracted, find where the longest streak of $0$'s to the left of that bit ends, and update accordingly. The total complexity is $O(n\\log n)$. Use lazy segment augmented with $O(\\log n)$ binary search. For each bit added, find where the longest streak of $1$'s to the left of that bit ends, and update accordingly. Similarly, for each bit subtracted, find where the longest streak of $0$'s to the left of that bit ends, and update accordingly. The total complexity is $O(n\\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nstruct LazySeg {\n    int l, r;\n    int val = 0, tag = 0;\n    bool is_lazy = false;\n    LazySeg * l_child = NULL, * r_child = NULL;\n\n    LazySeg(int _l, int _r) {\n        l = _l;\n        r = _r;\n        if (r - l > 1) {\n            int m = (l + r) / 2;\n            l_child = new LazySeg(l, m);\n            r_child = new LazySeg(m, r);\n        }\n    }~LazySeg() {\n        delete l_child;\n        delete r_child;\n    }\n    void unlazy() {\n        if (!is_lazy) return;\n        val = (r - l) * tag;\n        if (r - l <= 1) return;\n        l_child -> tag = tag;\n        l_child -> is_lazy = true;\n        r_child -> tag = tag;\n        r_child -> is_lazy = true;\n        tag = 0;\n        is_lazy = false;\n    }\n    void update(int from, int to, int x) {\n        unlazy();\n        if (from >= r || l >= to) return;\n        if (from <= l && to >= r) {\n            tag = x;\n            is_lazy = true;\n            unlazy();\n        } else {\n            l_child -> update(from, to, x);\n            r_child -> update(from, to, x);\n            val = l_child -> val + r_child -> val;\n        }\n    }\n    int query(int from, int to) {\n        if (from >= r || l >= to) return 0;\n        unlazy();\n        if (from <= l && to >= r) return val;\n        else {\n            if (l_child == NULL) return 0;\n            return l_child -> query(from, to) + r_child -> query(from, to);\n        }\n    }\n    //pre = prefix in [l,k)\n    int max_right(int k, int pre, int v) {\n        unlazy();\n        if (r - l == 1) {\n            if (val == v) return l;\n            else return l - 1;\n        }\n        l_child -> unlazy();\n        int mid = (l + r) / 2;\n        if (mid <= k) {\n            return r_child -> max_right(k, pre - l_child -> val, v);\n        } else if (l_child -> val - pre == v * (mid - k)) {\n            //left to mid-1 has all 1's => answer must be >= mid-1\n            return r_child -> max_right(mid, 0, v);\n        } else {\n            return l_child -> max_right(k, pre, v);\n        }\n    }\n    //suff = suffix\n    int get_answer() {\n        unlazy();\n        if (r - l == 1) {\n            if (val == 1) return l;\n            else return l - 1;\n        }\n        r_child -> unlazy();\n        if (r_child -> val == 0) {\n            //[mid to end] are all 0\n            return l_child -> get_answer();\n        } else {\n            return r_child -> get_answer();\n        }\n    }\n};\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(NULL);\n    cout.tie(NULL);\n\n    int n, q;\n    cin >> n >> q;\n    LazySeg tr(0, 200100);\n\n    auto add = [ & ](int x) {\n        int y = tr.max_right(x, tr.query(0, x), 1) + 1;\n        if (y == x) { //no carry; just change 0 to 1\n            tr.update(x, x + 1, 1);\n        } else { //there is a carry; set the whole block of 1's to 0\n            tr.update(x, y, 0);\n            tr.update(y, y + 1, 1);\n        }\n    };\n\n    auto remove = [ & ](int x) {\n        int y = tr.max_right(x, tr.query(0, x), 0) + 1;\n        if (y == x) {\n            tr.update(x, x + 1, 0);\n        } else {\n            tr.update(x, y, 1);\n            tr.update(y, y + 1, 0);\n        }\n    };\n    vector < int > a(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n        add(a[i]);\n    }\n    while (q--) {\n        int k, l; cin >> k >> l;\n        k--; \n        remove(a[k]); add(l);\n        a[k] = l;\n        cout << tr.get_answer() << \"\\n\";\n    }\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "combinatorics",
      "data structures",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1705",
    "index": "F",
    "title": "Mark and the Online Exam",
    "statement": "Mark is administering an online exam consisting of $n$ true-false questions. However, he has lost all answer keys. He needs a way to retrieve the answers before his client gets infuriated.\n\nFortunately, he has access to the grading system. Thus, for each query, you can input the answers to all $n$ questions, and the grading system will output how many of them are correct.\n\nHe doesn't have much time, so he can use the grading system at most $675$ times. Help Mark determine the answer keys.\n\nNote that answer keys are fixed in advance and will not change depending on your queries.",
    "tutorial": "Unfortunately, a harder version of this problem has appeared in a Chinese contest here and here. You can look at their solution here. We thank many contestants who pointed it out. It's possible to solve this problem without any randomization. See the subsequent hints for how to do so. Observe that we can take differences between two very close queries to get the number of $\\texttt{T}$'s in a small subsequence. You can take the difference against a pre-computed query. Applying this with a group of two questions. You have three possibilities: either $\\texttt{TT}$, $\\texttt{FF}$, and ${\\texttt{TF}, \\texttt{FT}}$. If the third possibility happens, simultaneously figure out whether is $\\texttt{TF}$ or $\\texttt{FT}$ and answer one question within one query. You will need to precompute the query $\\texttt{TFTF}\\dots\\texttt{TF}$. There are many possible approaches, including using randomized algorithms. However, I will present the solution that takes about $\\tfrac{2n}{3}$ queries deterministically. We pre-query $\\texttt{TTT...T}$ and $\\texttt{TFTF...TF}$. Then, for $i=1,2,\\dots,\\left\\lfloor\\frac n3\\right\\rfloor$, we take the difference when both the $(2i-1)$-th and the $2i$-th question in $\\texttt{TTT...T}$ is changed to $\\texttt{F}$. If the difference is $+2$, then both answers must be $\\texttt F$. If the difference is $-2$, then both answers must be $\\texttt T$. Else, the answers must be $\\texttt{TF}$ or $\\texttt{FT}$ in some order. Now, here is the key idea: if the last case happens, then we can figure out if it's $\\texttt{TF}$ or $\\texttt{FT}$ as well as the answer to one more question in one query. To do so, compare the previous $\\texttt{TFTF...TF}$ with a new query that has $3$ differences: $\\begin{align*} \\\\ \\texttt{TFTF} \\dots \\texttt{TF} \\dots \\texttt{T} \\dots \\texttt{TF} \\\\ \\texttt{TFTF} \\dots \\color{red}{\\texttt{FT}} \\dots \\color{red}{\\texttt F} \\dots \\texttt{TF} \\end{align*}$ (Note: we assume that the third question corresponds to $\\texttt T$ in the query. If it's $\\texttt F$, just change to $\\texttt T$ and proceed analogously.) There are four possible scenarios. If the answers are $\\texttt{TF}$ and $\\texttt{T}$, then the difference is $-3$. If the answers are $\\texttt{TF}$ and $\\texttt{F}$, then the difference is $-1$. If the answers are $\\texttt{FT}$ and $\\texttt{T}$, then the difference is $+1$. If the answers are $\\texttt{FT}$ and $\\texttt{F}$, then the difference is $+3$. Therefore, we can distinguish these four scenarios in one go. Finally, if the first two cases happen, we can easily figure out the answer to one more question in one query (say, by changing that question to $\\texttt F$ and compare with the $\\texttt{TT...T}$ query). Either way, we can deduce the answer to $3$ questions in $2$ queries, leading to a solution with $\\tfrac{2n}{3}$ queries. Note that this solution can be easily improved to $\\frac {3n}{5}$ on average by randomly shuffling the questions.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n;\n\nint query(string s){\n    cout << s << endl;\n    cout.flush();\n    int x; cin >> x;\n    if(x==n) exit(0);\n    return x;\n}\n\nint main(){\n    cin >> n;\n\n    //query true count\n    string all_T(n, 'T'), ans(n, '?');\n    int cnt_T = query(all_T);\n    \n    //query TF\n    string all_TF(n, 'T');\n    for(int i=1; i<n; i+=2) all_TF[i] = 'F';\n    int cnt_TF = query(all_TF);\n\n    //begin the loop\n    int l = 0, r = n-1;\n    while(r >= l){\n        if(r==l){ //only l is undetermined\n            string s(all_T);\n            s[l] = 'F';\n            int k = query(s);\n\n            if(k > cnt_T){\n                ans[l] = 'F';\n            }\n            else{\n                ans[l] = 'T';\n            }\n            l++; r--;\n        }\n        else{\n            string s(all_T);\n            s[l] = 'F'; s[l+1] = 'F';\n            int k = query(s) - cnt_T;\n\n            if(k == 2){\n                ans[l] = 'F'; ans[l+1] = 'F';\n                l += 2;\n            }\n            else if(k == -2){\n                ans[l] = 'T'; ans[l+1] = 'T';\n                l += 2;\n            }\n            else{\n                if(r == l+1){ //only l and l+1 left; figure out the order\n                    string s(all_T);\n                    s[l] = 'F';\n                    int k = query(s);\n                    \n                    if(k > cnt_T){\n                        ans[l] = 'F'; ans[l+1] = 'T';\n                    }\n                    else{\n                        ans[l] = 'T'; ans[l+1] = 'F';\n                    }\n                    l += 2;\n                }\n                else{ //determine l, l+1, r\n                    string s(all_TF);\n                    s[l] = 'F'; s[l+1] = 'T';\n\n                    if(s[r] == 'F') s[r] = 'T';\n                    else s[r] = 'F';\n\n                    int k = query(s) - cnt_TF;\n                    if(k == 3){\n                        ans[l] = 'F'; ans[l+1] = 'T'; ans[r] = s[r];\n                    }\n                    else if(k == 1){\n                        ans[l] = 'F'; ans[l+1] = 'T'; ans[r] = all_TF[r];\n                    }\n                    else if(k == -1){\n                        ans[l] = 'T'; ans[l+1] = 'F'; ans[r] = s[r];\n                    }\n                    else{\n                        ans[l] = 'T'; ans[l+1] = 'F'; ans[r] = all_TF[r];\n                    }\n                    l += 2; r--;\n                }\n            }\n        }\n    }\n    query(ans);\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "interactive",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1706",
    "index": "A",
    "title": "Another String Minimization Problem",
    "statement": "You have a sequence $a_1, a_2, \\ldots, a_n$ of length $n$, consisting of integers between $1$ and $m$. You also have a string $s$, consisting of $m$ characters B.\n\nYou are going to perform the following $n$ operations.\n\n- At the $i$-th ($1 \\le i \\le n$) operation, you replace either the $a_i$-th \\textbf{or} the $(m + 1 - a_i)$-th character of $s$ with A. You can replace the character at any position multiple times through the operations.\n\nFind the lexicographically smallest string you can get after these operations.\n\nA string $x$ is lexicographically smaller than a string $y$ of the same length if and only if in the first position where $x$ and $y$ differ, the string $x$ has a letter that appears earlier in the alphabet than the corresponding letter in $y$.",
    "tutorial": "Let's iterate through the elements of $a$. For convenience, we'll make $a_i = \\min(a_i, m + 1 - a_i)$. If the $a_i$-th character of $s$ is not currently A, then we should replace it. Otherwise, we replace the $(m+1-a_i)$-th character. This is because if we have the choice between replacing two characters, replacing the one with the smaller index will result in a lexicographically smaller string. Alternatively, we can keep track of how many times either $x$ or $m + 1 - x$ appears in $a$ for each $1 \\le x \\le \\lceil \\frac{m}{2} \\rceil$. If they appear $0$ times, neither of these indices in $s$ can become A. If they appear $1$ time, it is optimal to set the $x$-th character to A, since this will produce a lexicographically smaller string. Otherwise, they appear at least $2$ times, and it is possible to set both the $x$-th and $(m + 1 - x)$-th character to A.",
    "code": "#include \"bits/stdc++.h\"\n \nusing namespace std;\n \n#define ll long long\nconst int MAXN = 55;\n \nint t, n, m;\nint cnt[MAXN];\n \nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n  \n  cin >> t;\n  while (t--) {\n \n    cin >> n >> m;\n \n    for (int i = 0; i < m; i++)\n      cnt[i] = 0;\n \n    for (int i = 0; i < n; i++) {\n      int x; cin >> x;\n      x--;\n      x = min(x, m - 1 - x);\n      cnt[x]++;\n    }\n \n    string ans(m, 'B');\n    for (int i = 0; i < m; i++) {\n \n      if (!cnt[i]) continue;\n \n      ans[i] = 'A';\n      if (cnt[i] > 1)\n        ans[m - 1 - i] = 'A';\n \n    }\n \n    cout << ans << \"\\n\";\n \n  }\n  \n}",
    "tags": [
      "2-sat",
      "constructive algorithms",
      "greedy",
      "string suffix structures",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1706",
    "index": "B",
    "title": "Making Towers",
    "statement": "You have a sequence of $n$ colored blocks. The color of the $i$-th block is $c_i$, an integer between $1$ and $n$.\n\nYou will place the blocks down in sequence on an infinite coordinate grid in the following way.\n\n- Initially, you place block $1$ at $(0, 0)$.\n- For $2 \\le i \\le n$, if the $(i - 1)$-th block is placed at position $(x, y)$, then the $i$-th block can be placed at one of positions $(x + 1, y)$, $(x - 1, y)$, $(x, y + 1)$ (\\textbf{but not at position $(x, y - 1)$}), as long no previous block was placed at that position.\n\nA tower is formed by $s$ blocks such that they are placed at positions $(x, y), (x, y + 1), \\ldots, (x, y + s - 1)$ for some position $(x, y)$ and integer $s$. The size of the tower is $s$, the number of blocks in it. A tower of color $r$ is a tower such that all blocks in it have the color $r$.\n\nFor each color $r$ from $1$ to $n$, solve the following problem \\textbf{independently}:\n\n- Find the maximum size of a tower of color $r$ that you can form by placing down the blocks according to the rules.",
    "tutorial": "When can two blocks of the same color form two consecutive elements of a tower? Formally, if we have two blocks of the same color at indices $i$ and $j$ such that $i < j$, how can we tell if it is possible to place them at $(x_i, y_i)$ and $(x_i, y_i + 1)$ respectively? As it turns out, they can be placed like this if and only if $i$ and $j$ have different parities. First, if they have the same parity, it is impossible to place them this way. Note that $x_i + y_i$ must have a different parity from $x_{i + 1} + y_{i + 1}$, since these sums must differ by exactly $1$. So, if $i$ and $j$ have the same parity, then $x_i + y_i$ must also have the same parity as $x_j + y_j$. But we want them to be vertically adjacent, which is not possible if their parities must be the same. So, it is impossible to make two blocks with indices of the same parity adjacent to each other. Next, there is a valid construction if you want to put blocks $i$ and $j$ together when they have different parities. Say that block $i$ will go at position $(x_i, y_i)$ and block $j$ goes at position $(x_i, y_{i}+1)$. If $j=i+1$, then we are done. Now, let's say that $j=i+3$. Then, we can place block $i+1$ at $(x_i+1,y_i)$ and block $j-1$ at position $(x_i+1,y_{i}+1)$. What if $j=i+5$? Then we can do the same as the previous case, and then put block $i+2$ at $(x_i+2,y_i)$ and block $j-2$ at $(x_i+2,y_i+1)$. Essentially, we are making the blocks between $i$ and $j$ into a horizontal line extending out for $\\frac{j-i-1}{2}$ blocks then coming back in. If there are already blocks to the right of $(x_i, y_i)$, then we can do the same construction but extending out to the left. Note that since we cannot move down, at least one of the right and left side must be open. There are two ways we can go from here: First, there is a DP solution. Let's imagine the naive $\\mathcal{O}(n^2)$ dp: We say that $dp[i][c]$ is the maximum size of a tower with color $c$, such that the last block placed was at index $i$. The transitions look like this: $dp[i][c_i] = \\max\\limits_{j < i, j \\not \\equiv i \\pmod 2}(dp[j][c_i] + 1)$. We check all $j < i$ such that $j$ and $i$ have different parities, then see if adding a block to this tower makes a better solution. To optimize it, we can notice that for the first DP dimension (index), only the parity of the index matters - for each color, we just need to keep track of the maximum $dp[i][c]$ for even and odd $i$. We will iterate through all blocks $a_i$, maintaining $dp[p][c]$, which contains the maximum size of a tower with color $c$, where the last block included in the tower had an index with parity $p$ ($p=0$ indicates an even index, $p=1$ indicates an odd index). If the current index is even, we set $dp[0][c_i] = \\max(dp[0][c_i], dp[1][c_i] + 1)$. If it is odd, we set $dp[1][c_i] = \\max(dp[1][c_i], dp[0][c_i] + 1)$. The solution runs in linear time. Alternatively, there's a greedy solution. After selecting a block, the next block selected must always have the opposite parity. Therefore, it makes sense to greedily select the first block of the same color with opposite parity, since it will never improve the answer if we select a later block. For each color, we start from the first block and iterate through, adding each block to the sequence if and only if it has a different parity from the last one.",
    "code": "#include \"bits/stdc++.h\"\n \nusing namespace std;\n \n#define ll long long\nconst int MAXN = 100100;\n \nint t, n;\nvector<int> a[MAXN];\n \nint solve(int x) {\n \n  if (!a[x].size()) return 0;\n \n  int curr = a[x][0];\n  int ans = 1;\n \n  for (int i : a[x]) {\n    if ((i & 1) != (curr & 1)) {\n      ans++;\n      curr = i;\n    }\n  }\n \n  return ans;\n \n}\n \nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n  \n  cin >> t;\n  while (t--) {\n \n    cin >> n;\n \n    for (int i = 1; i <= n; i++)\n      a[i].clear();\n \n    for (int i = 1; i <= n; i++) {\n      int x; cin >> x;\n      a[x].push_back(i);\n    }\n \n    for (int i = 1; i <= n; i++)\n      cout << solve(i) << \" \\n\"[i == n];\n \n  }\n  \n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1706",
    "index": "C",
    "title": "Qpwoeirut And The City",
    "statement": "Qpwoeirut has taken up architecture and ambitiously decided to remodel his city.\n\nQpwoeirut's city can be described as a row of $n$ buildings, the $i$-th ($1 \\le i \\le n$) of which is $h_i$ floors high. You can assume that the height of every floor in this problem is equal. Therefore, building $i$ is taller than the building $j$ if and only if the number of floors $h_i$ in building $i$ is larger than the number of floors $h_j$ in building $j$.\n\nBuilding $i$ is cool if it is taller than both building $i-1$ and building $i+1$ (and both of them exist). Note that neither the $1$-st nor the $n$-th building can be cool.\n\nTo remodel the city, Qpwoeirut needs to maximize the number of cool buildings. To do this, Qpwoeirut can build additional floors on top of any of the buildings to make them taller. Note that he cannot remove already existing floors.\n\nSince building new floors is expensive, Qpwoeirut wants to minimize the number of floors he builds. Find the minimum number of floors Qpwoeirut needs to build in order to maximize the number of cool buildings.",
    "tutorial": "The first observation to be made is that no two adjacent building can both be cool at the same time. This means that, for odd $n$, there must be $\\frac{n-1}{2}$ cool buildings arranged in the following configuration... 01010...01010(0 - normal (not cool) building, 1 - cool building) For even $n$, there must be $\\frac{n-2}{2}$ cool buildings. This means that exactly one pair of adjacent buildings in the city is normal, meaning that the buildings must be arranged in one of the following configurations... 01010...01010001010...01001001010...001010$\\vdots$010100...01010010010...01010001010...01010(0 - normal (not cool) building, 1 - cool building) For odd $n$, the solution is relatively simple. Just find the total floors necessary to make each of the alternating buildings (starting from the 2nd building) cool and that is the answer. For even $n$, the solution is more complex. First, find the number of floors necessary to get to the first of the configurations shown above. Then, loop through each of the subsequent configurations, each time using the previous configuration to get the number of floors necessary for the new configuration in $O(1)$ time. This enables a solution in $O(n)$ time. For example, in the 4th test case from the example in the problem statement, the possible configurations of cool buildings are... 4 2 1 3 5 3 6 14 2 1 3 5 3 6 14 2 1 3 5 3 6 14 2 1 3 5 3 6 1(light - normal (not cool) building, bold - cool building) The number of floors necessary to reach each of these configurations are... 1st configuration: (5 - 2) + (6 - 3) + (7 - 3) = 10. 2nd configuration: 10 - (7 - 3) + (6 - 6) = 6. 3rd configuration: 6 - (6 - 3) + (5 - 5) = 3. 4th configuration: 3 - (5 - 2) + (4 - 1) = 3. The answer is the minimum of these values, which is $3$. For even $n$, the floors necessary for every configuration can also be found in $O(n)$ time using an alternating forward prefix sum array and an alternating backward prefix sum array.",
    "code": "#include \"bits/stdc++.h\"\n \nusing namespace std;\n \n#define ll long long\nconst int MAXN = 100100;\n \nint t, n;\nll a[MAXN];\n \nll get(int i) {\n  return max(0ll, max(a[i - 1], a[i + 1]) - a[i] + 1);\n}\n \nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n  \n  cin >> t;\n  while (t--) {\n \n    cin >> n;\n    for (int i = 1; i <= n; i++)\n      cin >> a[i];\n \n    if (n & 1) {\n \n      ll ans = 0;\n      for (int i = 2; i < n; i += 2)\n        ans += get(i);\n \n      cout << ans << \"\\n\";\n      continue;\n \n    }\n \n    ll tot = 0;\n    for (int i = 2; i < n; i += 2)\n      tot += get(i);\n \n    ll ans = tot;\n    for (int i = n - 1; i > 1; i -= 2) {\n      tot -= get(i - 1);\n      tot += get(i);\n      ans = min(ans, tot);\n    }\n \n    cout << ans << \"\\n\";\n \n  }\n  \n}",
    "tags": [
      "dp",
      "flows",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1706",
    "index": "D1",
    "title": "Chopping Carrots (Easy Version)",
    "statement": "\\url{CDN_BASE_URL/51167bab54119df1f721947703725ebd}",
    "tutorial": "Let's iterate over integers $v = 0, 1, \\ldots, a_1$. We'll construct an answer assuming that the minimum value of $\\lfloor \\frac{a_i}{p_i} \\rfloor$ is at least $v$. For all $1 \\le i \\le n$, we set $p_i = \\min(k, \\lfloor \\frac{a_i}{v} \\rfloor)$: the maximum value $p_i$ such that $1 \\le p_i \\le k$ and $v \\le \\lfloor \\frac{a_i}{p_i} \\rfloor$ (if $v = 0$ we can just set $p_i = k$)). Now, we find the value of $\\max\\limits_{1 \\le i \\le n}(\\lfloor\\frac{a_i}{p_i}\\rfloor ) - v$. This gives the answer when the minimum value of $\\lfloor \\frac{a_i}{p_i} \\rfloor$ is $v$. Finally, we compute this for all $0 \\le v \\le a_1$. This gives a $\\mathcal{O}(n \\cdot a_1)$ time solution per test case.",
    "code": "#include \"bits/stdc++.h\"\n \nusing namespace std;\n \n#define ll long long\nconst int MAXN = 3030;\n \nint t, n, k;\nint a[MAXN];\n \nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n  \n  cin >> t;\n  while (t--) {\n \n    cin >> n >> k;\n    for (int i = 0; i < n; i++)\n      cin >> a[i];\n \n    int ans = 1e9;\n    for (int v = 1; v <= a[0]; v++) {\n \n      int cm = v;\n      for (int i = 0; i < n; i++) {\n        int p = min(k, (v ? (a[i] / v) : k));\n        cm = max(cm, a[i] / p);\n      }\n \n      ans = min(ans, cm - v);\n \n    }\n \n    cout << ans << \"\\n\";\n \n  }\n  \n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1706",
    "index": "D2",
    "title": "Chopping Carrots (Hard Version)",
    "statement": "This is the hard version of the problem. The only difference between the versions is the constraints on $n$, $k$, $a_i$, and the sum of $n$ over all test cases. You can make hacks only if both versions of the problem are solved.\n\n\\textbf{Note the unusual memory limit.}\n\nYou are given an array of integers $a_1, a_2, \\ldots, a_n$ of length $n$, and an integer $k$.\n\nThe cost of an array of integers $p_1, p_2, \\ldots, p_n$ of length $n$ is $$\\max\\limits_{1 \\le i \\le n}\\left(\\left \\lfloor \\frac{a_i}{p_i} \\right \\rfloor \\right) - \\min\\limits_{1 \\le i \\le n}\\left(\\left \\lfloor \\frac{a_i}{p_i} \\right \\rfloor \\right).$$\n\nHere, $\\lfloor \\frac{x}{y} \\rfloor$ denotes the integer part of the division of $x$ by $y$. Find the minimum cost of an array $p$ such that $1 \\le p_i \\le k$ for all $1 \\le i \\le n$.",
    "tutorial": "Solution 1 Let's fix $v$, the minimum value of $\\lfloor \\frac{a_i}{p_i} \\rfloor$. Then, for all $1 \\le i \\le n$, we find the maximum value $p_i$ such that $p_i \\le k$ and $\\lfloor \\frac{a_i}{p_i} \\rfloor \\ge v$. For some minimum value $v$, let's call the array described above $P(v)$, and let's define $M(v) = \\max\\limits_{1 \\le i \\le n} \\lfloor \\frac{a_i}{P(v)_i} \\rfloor$. We can find the answer by taking the minimum of $M(v) - v$ across all $0 \\le v \\le a_1$, giving a $O(n \\cdot a_i)$ solution. To speed it up, let's consider how some element $a_i$ will affect the values of $M(v)$. First, notice that $\\lfloor \\frac{a_i}{q} \\rfloor$ (where $1 \\le q \\le k$) can take on at most $O(\\min(k,\\sqrt{a_i}))$ distinct values. Let's denote these values (in increasing order) $s_1, s_2, s_3, \\ldots, s_x$. Consider what happens when $v \\le s_1$. Then, $M(v)$ must be at least $s_1$. What about when $s_1 < v \\le s_2$? Then, $M(v)$ must be at least $s_2$. And so on, until $s_{x - 1} < v \\le s_x$, where $M(v)$ must be at least $s_x$. This way, we can get lower bounds on value of $M(v)$. It is easy to see that the highest of these bounds is achievable. Let's iterate over array $a$. Let $m[v]$ (here, $m = m[0], m[1], m[2], \\ldots, m[a_1]$ is an array of length $a_1 + 1$) be the highest of lower bounds on $M(v)$ we already found. Initially, $m[v] = 0$ for all $v$. When we are dealing with $a_i$ we want to do the following: For all $0 \\le j \\le x - 1$, we want to update $m[y] = \\max(m[y], s_{j+1})$ for all $s_{j} + 1 \\le y \\le s_{j + 1}$ (for convenience we define $s_0 = -1$). Since $s_0 < s_1 < s_2 < \\ldots < s_x$, this can be done without any fancy data structures - instead of updating all these ranges directly, we can set $m[s_j + 1] = \\max(m[s_j + 1], s_{j+1}])$, so that $M(v)$ will be equal to $\\max(m[0], m[1], \\ldots, m[v])$. Then, once $m$ is computed, we can sweep through to find all values of $M(v)$ in with prefix maxes. Once we have $m$ computed, we can find $M(v) - v$ for all $0 \\le v \\le a_1$ in linear time. This gives a $\\mathcal{O}(\\sum\\limits_{1 \\le i \\le n}\\min(k, \\sqrt{a_i}) + a_1)$ solution per test case, with total $\\mathcal{O}(n + \\max_a)$ memory across all tests. Solution 2 (AlperenT) Now, let's fix $v$ as the maximum value of $\\lfloor \\frac{a_i}{p_i} \\rfloor$. We now want to maximize the minimum value of $\\lfloor \\frac{a_i}{p_i} \\rfloor$. Let's now consider all elements $a_i$ that satisfy $1 \\le a_i \\le v$. For these elements, it will be optimal to set $p_i = 1$, since we want to maximize them. How about elements $a_i$ satisfying $v + 1 \\le a_i \\le 2(v+1) - 1$? We need to have $\\lfloor \\frac{a_i}{p_i} \\rfloor \\le v$, so for these elements, we must have $p_i \\ge 2$. At the same time, we want to maximize them - so it will be optimal to set all these $p_i = 2$. Continuing this logic, for all integers $u = 1, 2, \\ldots, k$, we should check the elements $a_i$ satisfying $(u-1)\\cdot (v + 1) \\le a_i \\le u \\cdot (v+1)$, and set all these $p_i = u$. How can we determine the minimum value of $\\lfloor \\frac{a_i}{p_i} \\rfloor$ from this? For a fixed $u$, the minimum $\\lfloor \\frac{a_i}{u} \\rfloor$ will come from the minimum $a_i$. So if we can determine the minimum $a_i$ such that $(u-1)\\cdot (v + 1) \\le a_i \\le u \\cdot (v+1)$, and calculate these values across all $u = 1, 2, \\ldots, k$, then we will get the answer. To help us, let's precompute an array $next_1, next_2, \\ldots, next_{a_n}$. $next_j$ will store the minimum value of $a_i$ such that $a_i \\ge j$. Now, for a fixed $u$, we can check $next_{(u-1) \\cdot v + 1}$. If this value is less than or equal to $u \\cdot v$, it will be the minimum $a_i$ that we divide by $u$. Two important details: If there exists some $a_i \\ge (v + 1) \\cdot k$, then it is impossible to have the max element as $v$, and we should skip it. For some value $v$, we only need to check $u$ such that $(u-1)\\cdot v + 1 \\le a_n$. Using this second detail, the solution runs in $\\mathcal{O}\\left( \\sum\\limits_{i = 1}^{a_n}\\frac{a_n}{i} \\right) = \\mathcal{O}(a_n \\cdot \\log(a_n))$ time per test case. The memory usage is $\\mathcal{O}(n + \\max_a)$ across all tests.",
    "code": "// AUTHOR: AlperenT\n \n#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst long long N = 1e5 + 5, INF = (long long)2e18 + 5;\n \nlong long t, n, k, arr[N], closest[N], mn, ans;\n \nvector<pair<long long, long long>> v;\n \nvoid solve(){\n\tans = INF;\n \n\tcin >> n >> k;\n \n\tfor(int i = 1; i <= n; i++) cin >> arr[i];\n \n\tarr[0] = -1;\n \n\tfor(int i = 1; i <= n; i++){\n\t\tfill(closest + arr[i - 1] + 1, closest + arr[i] + 1, arr[i]);\n\t}\n \n\tfill(closest + arr[n] + 1, closest + N, INF);\n \n\tfor(int mx = 1; mx <= 100000; mx++){\n\t\tv.clear();\n \n\t\tv.push_back({1, mx});\n \n\t\tfor(int i = 2; i <= k; i++){\n\t\t\tv.push_back({v.back().second + 1, 1ll * (mx + 1) * i - 1});\n \n\t\t\tif(v.back().second > arr[n]) break;\n\t\t}\n \n\t\tif(v.back().second >= arr[n]){\n\t\t\tmn = INF;\n \n\t\t\tfor(int i = 0; i < v.size(); i++){\n\t\t\t\tint nxt = closest[v[i].first];\n \n\t\t\t\tif(nxt <= v[i].second) mn = min(mn, nxt / (i + 1ll));\n\t\t\t}\n \n\t\t\tassert(mn <= mx);\n \n\t\t\tans = min(ans, mx - mn);\n \n\t\t}\n\t}\n \n\tcout << ans << \"\\n\";\n}\n \nint main(){\n\tios_base::sync_with_stdio(false);cin.tie(NULL);\n\t\n\tcin >> t;\n \n\twhile(t--){\n\t\tsolve();\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1706",
    "index": "E",
    "title": "Qpwoeirut and Vertices",
    "statement": "You are given a connected undirected graph with $n$ vertices and $m$ edges. Vertices of the graph are numbered by integers from $1$ to $n$ and edges of the graph are numbered by integers from $1$ to $m$.\n\nYour task is to answer $q$ queries, each consisting of two integers $l$ and $r$. The answer to each query is the smallest non-negative integer $k$ such that the following condition holds:\n\n- For all pairs of integers $(a, b)$ such that $l\\le a\\le b\\le r$, vertices $a$ and $b$ are reachable from one another using only the first $k$ edges (that is, edges $1, 2, \\ldots, k$).",
    "tutorial": "If $l = r$, answer is $0$. From now on we assume $l < r$. Say we have a function $f(i)$ that tells us for some $2 \\le i \\le n$ the answer for the query $[i - 1, i]$. Then for some query $[l, r]$, the answer will be $k = \\max(f(l+1), f(l+2), \\ldots, f(r-1), f(r))$. This is true because: Since all consecutive nodes are connected, the first $k$ edges will be sufficient to connect all nodes $l, l+1, \\ldots, r$. Say that it is possible to connect these nodes using the first $k'$ edges ($k' < k$). We know that there is at least $1$ index $l + 1 \\le i \\le r$ such that $f(i) = k$. But if the answer for this query is $k'$, then it must be true that $f(i) \\le k'$ (because we can reach vertex $i - 1$ from vertex $i$ using only the first $k'$ edges then). Then, we have $f(i) \\le k' < k = f(i)$, which is a contradiction. So if we precompute the values of $f(i)$ for all $2 \\le i \\le n$, we can answer any query efficiently using a range max query structure (for example, a sparse table or segment tree). Here's how to find $f(i)$: Weight the edges, so that the $i$-th edge has a weight $i$. Find the unique minimum spanning tree of this weighted graph. $f(i)$ will be the maximum weight of an edge on the path from $i - 1$ to $i$. This will always give the correct value for $f(i)$ since edges not in the MST are useless. Let's imagine building the MST with Kruskal's: if we don't add the $W$-th edge, that means that the first $W-1$ edges are sufficient to connect $u_W$ and $v_W$, and we can use those instead to get a better answer. On the resulting tree, the optimal way to connect any two nodes is to use the edges on the simple shortest path between them. Finding the max edge weight in a path on a tree can be done, for example, with binary lifting: for each node we store the maximum weight on the path to the root with length $1$, $2$, $4$, $8$, and so on. Then, we can find the max edge weight on the path from any two nodes to their LCA in $\\mathcal O(\\log(n))$. Instead of using binary lifting, we can also directly represent the MST in the DSU. After successfully merging two components rooted at $u$ and $v$ in the DSU, we add an edge $(u, v)$ with the weight being the edge number from the input. $f(i)$ will then be the maximum edge from $i-1$ to $i$ in the newly constructed tree. We can just walk up the tree since the maximum depth is at most $\\mathcal O(\\log n)$ assuming the DSU implementation uses small-to-large merging. This gives an $\\mathcal O((m+q)\\log(n))$ or $\\mathcal O(m\\log(n) + q)$ solution, depending on the implementation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nstruct dsu {\n\tvector<int> ds, wt;\n\tdsu(int n) {\n\t\tds.assign(n, -1);\n\t\twt.assign(n, INT_MAX);\n\t}\n\tint find(int i) {\n\t\treturn ds[i] < 0 ? i : find(ds[i]);\n\t}\n\tvoid merge(int i, int j, int weight) {\n\t\ti = find(i), j = find(j);\n\t\tif (i != j) {\n\t\t\tif (ds[i] > ds[j])\n\t\t\t\tswap(i, j);\n\t\t\tds[i] += ds[j], ds[j] = i;\n\t\t\twt[j] = weight;\n\t\t}\n\t}\n\tint weight(int i, int j) {\n\t\tint w = 0;\n \n\t\twhile (i != j) {\n\t\t\tif (wt[i] < wt[j])\n\t\t\t\tw = wt[i], i = ds[i];\n\t\t\telse\n\t\t\t\tw = wt[j], j = ds[j];\n\t\t}\n\t\treturn w;\n\t}\n};\n \nstruct segtree {\n\tvector<int> tr; int n;\n\tsegtree(vector<int> v) {\n\t\tn = v.size();\n\t\ttr.resize(n * 2);\n\t\tfor (int i = 0; i < n; i++)\n\t\t\ttr[n + i] = v[i];\n\t\tfor (int i = n - 1; i > 0; i--)\n\t\t\tpull(i);\n\t}\n\tvoid pull(int i) {\n\t\ttr[i] = max(tr[i * 2], tr[i * 2 + 1]);\n\t}\n\tint query(int l, int r) {\n\t\tint x = 0;\n\t\t\n\t\tfor (l += n, r += n; l <= r; l /= 2, r /= 2) {\n\t\t\tif (l & 1)\n\t\t\t\tx = max(x, tr[l++]);\n\t\t\tif (~r & 1)\n\t\t\t\tx = max(x, tr[r--]);\n\t\t}\n\t\treturn x;\n\t}\n};\n \nvoid run() {\n\tint n, m, q;\n\tscanf(\"%d%d%d\", &n, &m, &q);\n\t\n\tdsu ds(n);\n\tfor (int w = 1; w <= m; w++) {\n\t\tint i, j;\n\t\tscanf(\"%d%d\", &i, &j), i--, j--;\n\t\tds.merge(i, j, w);\n\t}\n\t\n\tvector<int> weights(n - 1);\n\tfor (int i = 0; i < n - 1; i++)\n\t\tweights[i] = ds.weight(i, i + 1);\n\t\n\tsegtree st(weights);\n\twhile (q--) {\n\t\tint l, r;\n\t\tscanf(\"%d%d\", &l, &r), l--, r--;\n\t\tprintf(\"%d \", l == r ? 0 : st.query(l, r - 1));\n\t}\n\tprintf(\"\\n\");\n}\n \nint main() {\n\tint t = 1;\n \n\tscanf(\"%d\", &t);\n\twhile (t--)\n\t\trun();\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1707",
    "index": "A",
    "title": "Doremy's IQ",
    "statement": "Doremy is asked to test $n$ contests. Contest $i$ can only be tested on day $i$. The difficulty of contest $i$ is $a_i$. Initially, Doremy's IQ is $q$. On day $i$ Doremy will choose whether to test contest $i$ or not. She can only test a contest if her current IQ is strictly greater than $0$.\n\nIf Doremy chooses to test contest $i$ on day $i$, the following happens:\n\n- if $a_i>q$, Doremy will feel she is not wise enough, so $q$ decreases by $1$;\n- otherwise, nothing changes.\n\nIf she chooses not to test a contest, nothing changes.Doremy wants to test as many contests as possible. Please give Doremy a solution.",
    "tutorial": "Solution 1 We call contests that will decrease Doremy's IQ bad contests and the other good contests. In the best solution(testing the maximum number of contests), there is always an index $x$. Contest $i$ ($i < x$) is tested, if Contest $i$ is good; Contest $i$ ($i \\ge x$) is tested, no matter what kind of contest it is. How to prove that this conclusion? For any choice, we can find the last contest $a$ that is not tested and the first bad contest $b$ that is tested. If $b<a$, we can give up contest $b$ and choose to test contest $a$, and the number of contests that is tested does not change. If $b>a$, there is already an valid $x$. When $x$ is smallest, you can get the best solution. And we can find the smallest $x$ by binary search. Time complexity $O(n \\log n)$. Solution 2 Consider everything in the reverse order. Assume that Doremy has $Q=0$ IQ in the end. Consider whether a contest should be tested in the reverse order. $a_i\\le Q$. Doremy should tested the contest because there is no decrease in her IQ. $a_i > Q$ and $Q < q$. If Doremy tests the contest, her IQ will decrease by $1$, so in the reverse order, her IQ increases by $1$; otherwise she just skipped the contest and nothing happened. Doremy can test at most $q$ contest with the $a_i>Q$ property. But if Doremy gets more IQ, she can participate more previous good contests. So she should test this contest. If $a_i > Q$ and $Q=q$, Doremy cannot test the contest because her IQ is not enough. So you can determine whether every contest should be tested. Time complexity $O(n)$.",
    "code": "#include<cstdio>\nint a[100005],b[100005];\nint main(){\n\tint T;\n\tscanf(\"%d\",&T);\n\twhile(T--){\n\t\tint n,iq;\n\t\tscanf(\"%d%d\",&n,&iq);\n\t\tfor(int i=1;i<=n;++i)\n\t\t\tscanf(\"%d\",&a[i]);\n\t\tint sum=0,nq=0;\n\t\tfor(int i=n;i>=1;--i){\n\t\t\tif(a[i]<=nq)b[i]=1;\n\t\t\telse if(nq<iq)++nq,b[i]=1; \n\t\t\telse b[i]=0;\n\t\t} \n\t\tfor(int i=1;i<=n;++i)\n\t\t\tprintf(\"%d\",b[i]);\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1707",
    "index": "B",
    "title": "Difference Array",
    "statement": "You are given an array $a$ consisting of $n$ non-negative integers. It is guaranteed that $a$ is sorted from small to large.\n\nFor each operation, we generate a new array $b_i=a_{i+1}-a_{i}$ for $1 \\le i < n$. Then we sort $b$ from small to large, replace $a$ with $b$, and decrease $n$ by $1$.\n\nAfter performing $n-1$ operations, $n$ becomes $1$. You need to output the only integer in array $a$ (that is to say, you need to output $a_1$).",
    "tutorial": "Let's prove that the brute-force solution (considering zeros differently) can pass. Define $S=\\sum\\limits_{i=1}^{n} a_i$ and it changes when an operation is performed. After sorting the array $a$ and ignoring $0$ s, the fact $\\begin{aligned} n-1+a_n &\\le S & (a_i \\ge 1)\\\\ n-1 &\\le S - a_n \\end{aligned}$ is always true. And after performing one operation, $S = a_n-a_1\\le a_n$. So in each operation, you cost $O(n \\log n)$ time to sort the new array and decrease $S$ by at least $n-1$. After the first operation, $S$ is $O(a_n)$. The complexity is $O(A \\log A)$, where $A=\\max\\{n,a_n\\}$.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#define ch() getchar()\n#define pc(x) putchar(x)\nusing namespace std;\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[65];int cnt=0;\n\tif(x<0)pc('-'),x=-x;\n\tq[++cnt]=x%10,x/=10;\n\twhile(x)\n\t\tq[++cnt]=x%10,x/=10;\n\twhile(cnt)pc(q[cnt--]+'0');\n}\nconst int maxn=100005;\nint a[maxn];\nint main(){\n\tint T;read(T);\n\twhile(T--){\n\t\tint n;read(n);\n\t\tfor(int i=1;i<=n;++i)read(a[i]);\n\t\tfor(int i=n-1;i>=1;--i){\n\t\t\tint pre=a[i+1],ok=false;\n\t\t\tfor(int j=i;j>=1;--j){\n\t\t\t\tok=(a[j]==0);\n\t\t\t\tpre-=(a[j]=pre-a[j]);\n\t\t\t\tif(ok){\n\t\t\t\t\tsort(a+j,a+i+1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!ok)\n\t\t\t\tsort(a+1,a+i+1);\n\t\t}\n\t\twrite(a[1]),pc('\\n');\n\t}\n\treturn 0;\n}\n/*\n_|_|_|_|        _|_|      _|      _|   _|_|_|_|_|   _|_|_|_|_|   _|\n_|      _|    _|    _|    _|_|    _|       _|       _|           _|\n_|      _|   _|      _|   _| _|   _|       _|       _|           _|\n_|      _|   _|_|_|_|_|   _|  _|  _|       _|       _|_|_|_|_|   _|\n_|      _|   _|      _|   _|   _| _|       _|       _|           _|\n_|      _|   _|      _|   _|    _|_|       _|       _|           _|\n_|_|_|_|     _|      _|   _|      _|   _|_|_|_|_|   _|_|_|_|_|   _|_|_|_|_|\n\n_|_|_|_|_|   _|      _|   _|_|_|_|     _|      _|\n    _|        _|    _|    _|      _|    _|    _|\n    _|         _|  _|     _|      _|     _|  _|\n    _|          _|_|      _|      _|      _|_|\n    _|         _|  _|     _|      _|       _|\n    _|        _|    _|    _|      _|       _|\n    _|       _|      _|   _|_|_|_|         _|\n\n_|             _|_|_|     _|      _|   _|_|_|_|_|\n_|           _|      _|   _|      _|   _|\n_|           _|      _|    _|    _|    _|\n_|           _|      _|    _|    _|    _|_|_|_|_|\n_|           _|      _|     _|  _|     _|\n_|           _|      _|      _|_|      _|\n_|_|_|_|_|     _|_|_|         _|       _|_|_|_|_|\n\n_|_|_|_|_|   _|      _|   _|_|_|_|_|\n    _|        _|    _|        _|\n    _|         _|  _|         _|\n    _|          _|_|          _|\n    _|           _|           _|\n    _|           _|           _|\n    _|           _|           _|\n\nCreated by xiaolilsq.\n*/",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1707",
    "index": "C",
    "title": "DFS Trees",
    "statement": "You are given a connected undirected graph consisting of $n$ vertices and $m$ edges. The weight of the $i$-th edge is $i$.\n\nHere is a wrong algorithm of finding a minimum spanning tree (MST) of a graph:\n\n\\begin{verbatim}\nvis := an array of length n\ns := a set of edges\nfunction dfs(u):\nvis[u] := true\niterate through each edge (u, v) in the order from smallest to largest edge weight\nif vis[v] = false\nadd edge (u, v) into the set (s)\ndfs(v)\nfunction findMST(u):\nreset all elements of (vis) to false\nreset the edge set (s) to empty\ndfs(u)\nreturn the edge set (s)\n\\end{verbatim}\n\nEach of the calls findMST(1), findMST(2), ..., findMST(n) gives you a spanning tree of the graph. Determine which of these trees are minimum spanning trees.",
    "tutorial": "Minimum spanning tree is unique in the given graph. If $\\operatorname{findMST}$(x) creates an MST, there is no cross edge in the graph. So if you can determine whether there is a cross edge starting DFS from every node, the problem is solved. Pay attention to every edge that is not in the MST. Let's focus on one single edge $(u,v)$ and see starting DFS from which node, $(u,v)$ is a cross edge. Take the following graph as an example. If we start from nodes $a$, $b$, $c$, $d$, $e$ or $f$, $(u,v)$ is a cross edge. If we start from nodes $t$, $u$, $o$ or $v$, $(u,v)$ is not a cross edge. We can find that when considering $u$ as the root of the tree, $o$ and $v$ are on the subtree of $v$. When considering $v$ as the root of the tree, $t$ and $u$ are on the subtree of $u$. So if an edge $(u,v)$ is not in the MST, only the subtree of $u$($u$ included, when considering $v$ as the root) and the subtree of $v$($v$ included, when considering $u$ as the root) can be answers. We just need to do this process for each edge not in the MST. After that we can get the answers. We can finish the process in $O(n\\log n)$ with bin-up on tree and BIT or in $O(n)$ with some case work while dfs.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#define ch() getchar()\n#define pc(x) putchar(x)\nusing namespace std;\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[65];int cnt=0;\n\tif(x<0)pc('-'),x=-x;\n\tq[++cnt]=x%10,x/=10;\n\twhile(x)\n\t\tq[++cnt]=x%10,x/=10;\n\twhile(cnt)pc(q[cnt--]+'0');\n}\nconst int maxn=100005,maxm=200005;\nint par[maxn];\nint AC(int x){\n\treturn par[x]==x?x:par[x]=AC(par[x]);\n}\nstruct Edge{\n\tint v,nt;\n\tEdge(int v=0,int nt=0):\n\t\tv(v),nt(nt){}\n}e[maxn*2],es[maxm];\nint hd[maxn],num;\nvoid qwq(int u,int v){\n\te[++num]=Edge(v,hd[u]),hd[u]=num;\n}\nint dp[maxn];\nint pa[maxn][20];\nvoid dfs(int u,int p){\n\tpa[u][0]=p;\n\tfor(int j=1;(1<<j)<=dp[u];++j)\n\t\tpa[u][j]=pa[pa[u][j-1]][j-1];\n\tfor(int i=hd[u];i;i=e[i].nt){\n\t\tint v=e[i].v;\n\t\tif(v==p)continue;\n\t\tdp[v]=dp[u]+1;dfs(v,u);\n\t}\n}\nint jump(int x,int t){\n\tfor(int cn=0;t;t>>=1,++cn)\n\t\tif(t&1)x=pa[x][cn];\n\treturn x;\n}\nint lca(int x,int y){\n\tif(dp[x]>dp[y])x=jump(x,dp[x]-dp[y]);\n\tif(dp[y]>dp[x])y=jump(y,dp[y]-dp[x]);\n\tif(x==y)return x;\n\tfor(int t=19;t>=0;--t)\n\t\tif(pa[x][t]!=pa[y][t])\n\t\t\tx=pa[x][t],y=pa[y][t];\n\treturn pa[x][0];\n}\nint vis[maxn];\nchar s[maxn];\nvoid pushdown(int u,int p){\n\tif(vis[u]==0)s[u]='1';\n\telse s[u]='0';\n\tfor(int i=hd[u];i;i=e[i].nt){\n\t\tint v=e[i].v;\n\t\tif(v==p)continue;\n\t\tvis[v]+=vis[u];\n\t\tpushdown(v,u);\n\t}\n}\nint main(){\n\tint n,m;\n\tread(n),read(m);\n\tfor(int i=1;i<=n;++i)\n\t\tpar[i]=i;\n\tint tp=0;\n\tfor(int i=1;i<=m;++i){\n\t\tint u,v;\n\t\tread(u),read(v);\n\t\tif(AC(u)==AC(v)){\n\t\t\tes[++tp]=Edge(u,v);\n\t\t}\n\t\telse{\n\t\t\tpar[AC(u)]=AC(v);\n\t\t\tqwq(u,v),qwq(v,u);\n\t\t}\n\t}\n\tint root=1;\n\tdfs(root,0);\n\tfor(int i=1;i<=tp;++i){\n\t\tint u=es[i].v,v=es[i].nt;\n\t\tif(dp[u]>dp[v])u^=v^=u^=v;\n\t\tint w=lca(u,v);\n\t\tif(u==w){\n\t\t\t--vis[v];\n\t\t\t++vis[jump(v,dp[v]-dp[u]-1)];\n\t\t}\n\t\telse{\n\t\t\t++vis[root];\n\t\t\t--vis[u];\n\t\t\t--vis[v];\n\t\t}\n\t}\n\tpushdown(root,0);\n\ts[n+1]='\\0';\n\tprintf(\"%s\\n\",s+1);\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1707",
    "index": "D",
    "title": "Partial Virtual Trees",
    "statement": "Kawashiro Nitori is a girl who loves competitive programming. One day she found a rooted tree consisting of $n$ vertices. The root is vertex $1$. As an advanced problem setter, she quickly thought of a problem.\n\nKawashiro Nitori has a vertex set $U=\\{1,2,\\ldots,n\\}$. She's going to play a game with the tree and the set. In each operation, she will choose a vertex set $T$, where $T$ is a partial virtual tree of $U$, and change $U$ into $T$.\n\nA vertex set $S_1$ is a partial virtual tree of a vertex set $S_2$, if $S_1$ is a subset of $S_2$, $S_1 \\neq S_2$, and for all pairs of vertices $i$ and $j$ in $S_1$, $\\operatorname{LCA}(i,j)$ is in $S_1$, where $\\operatorname{LCA}(x,y)$ denotes the lowest common ancestor of vertices $x$ and $y$ on the tree. Note that a vertex set can have many different partial virtual trees.\n\nKawashiro Nitori wants to know for each possible $k$, if she performs the operation \\textbf{exactly} $k$ times, in how many ways she can make $U=\\{1\\}$ in the end? Two ways are considered different if there exists an integer $z$ ($1 \\le z \\le k$) such that after $z$ operations the sets $U$ are different.\n\nSince the answer could be very large, you need to find it modulo $p$. It's guaranteed that $p$ is a prime number.",
    "tutorial": "First ignore the requirement that the virtual tree cannot be the entire tree. Then we count the number of ways without this requirement for all $k$ using DP. $dp_{x,i}$ is the number of ways to delete everything in the subtree of $x$ in exact $i$ operations. Node $x$ must be deleted at some time $j \\le i$ and all but at most one child subtree of $x$ must be deleted before time $j$. Let: $C_x$ be the set of $x$'s children. $S_{x,i}=\\sum_{j\\le i} dp_{x,i}$ $D_{x,j}=\\prod_{u\\in C(x)}S_{u,j}$ Then $\\begin{aligned} dp_{x,i} &=\\sum_{j < i}\\sum_{u\\in C_x}\\dfrac{dp_{u,i}D_{x,j}}{S_{u,j}} + \\prod_{u\\in C_x} S_{u,i}\\\\ &=\\sum_{u \\in C_x}dp_{u,i} \\sum_{j < i} \\dfrac{D_{x,j}}{S_{u,j}}+\\prod_{u \\in C_x}S_{u,i} \\end{aligned}$ Specially, when $x$ is root ($x=1$), $x$ is the last one to be deleted. So $dp_{x,i}=\\prod_{u\\in C_x} S_{u,i}$ in this case. It's not hard to computer this with prefix sums in $O(n^2)$ time. Then consider the requirement that the virtual tree cannot be the entire tree. Let the real answer be $Ans_k$. Then $\\begin{aligned} dp_{1,i} &= \\sum_{j=0}^{i} \\binom{i}{j}Ans_j \\\\ Ans_i &= dp_{1,i} - \\sum_{j=0}^{i-1} \\binom{i}{j} Ans_j \\end{aligned}$ So we can figure out the real answer in $O(n^2)$ time.",
    "code": "#include <bits/stdc++.h>\n \n#define debug(...) fprintf(stderr ,__VA_ARGS__)\n#define __FILE(x)\\\n\tfreopen(#x\".in\" ,\"r\" ,stdin);\\\n\tfreopen(#x\".out\" ,\"w\" ,stdout)\n#define LL long long\n \nconst int MX = 2000 + 23;\n \nLL MOD;\n \nusing namespace std;\n \nint read(){\n\tchar k = getchar(); int x = 0;\n\twhile(k < '0' || k > '9') k = getchar();\n\twhile(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();\n\treturn x;\n}\n \nint head[MX] ,tot = 1;\nstruct edge{\n\tint node ,next;\n}h[MX << 1];\nvoid addedge(int u ,int v ,int flg = 1){\n\t// if(flg) debug(\"%d %d\\n\" ,u ,v);\n\th[++tot] = (edge){v ,head[u]} ,head[u] = tot;\n\tif(flg) addedge(v ,u ,false);\n}\n \nint n ,dp[MX][MX] ,S[MX][MX] ,suf[MX][MX] ,pre[MX][MX];\nvoid dapai(int x ,int f){\n\tint ch = 0;\n\tfor(int i = head[x] ,d ; i ; i = h[i].next){\n\t\tif((d = h[i].node) == f) continue;\n\t\tdapai(d ,x);\n\t}\n\tfor(int i = head[x] ,d ; i ; i = h[i].next){\n\t\tif((d = h[i].node) == f) continue;\n\t\t++ch;\n\t\tfor(int j = 0 ; j <= n ; ++j){\n\t\t\tsuf[ch][j] = pre[ch][j] = S[d][j];\n\t\t}\n\t}\n \n\tif(!ch){\n\t\tfor(int i = 1 ; i <= n ; ++i){\n\t\t\tdp[x][i] = 1 % MOD;\n\t\t\tS[x][i] = (S[x][i - 1] + dp[x][i]) % MOD;\n\t\t}\n\t\treturn ;\n\t}\n\tfor(int j = 0 ; j <= n ; ++j){\n\t\tfor(int i = 1 ; i <= ch ; ++i)\n\t\t\tpre[i][j] = 1LL * pre[i][j] * pre[i - 1][j] % MOD;\n\t\tfor(int i = ch ; i >= 1 ; --i)\n\t\t\tsuf[i][j] = 1LL * suf[i][j] * suf[i + 1][j] % MOD;\n\t}\n\tfor(int i = 1 ; i <= n ; ++i) dp[x][i] = pre[ch][i];\n\tif(x != 1) for(int i = head[x] ,d ,c = 0 ; i ; i = h[i].next){\n\t\tif((d = h[i].node) == f) continue;\n\t\t++c;\n\t\tLL sum = 0;\n\t\tfor(int mx = 1 ; mx <= n ; ++mx){\n\t\t\tdp[x][mx] = (dp[x][mx] + sum * dp[d][mx]) % MOD;\n\t\t\tsum = (sum + 1LL * pre[c - 1][mx] * suf[c + 1][mx]) % MOD;\n\t\t}\n\t}\n\tfor(int i = 1 ; i <= ch ; ++i)\n\t\tfor(int j = 0 ; j <= n ; ++j)\n\t\t\tsuf[i][j] = pre[i][j] = 1 % MOD;\n\tfor(int i = 1 ; i <= n ; ++i)\n\t\tS[x][i] = (S[x][i - 1] + dp[x][i]) % MOD;\n}\n \nint C[MX][MX];\nvoid init(){\n\tfor(int i = 0 ; i < MX ; ++i) C[i][0] = 1 % MOD;\n\tfor(int i = 1 ; i < MX ; ++i)\n\t\tfor(int j = 1 ; j < MX ; ++j)\n\t\t\tC[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % MOD;\n}\n \nint main(){\n    \n    n = read() ,MOD = read();\n\tinit();\n\t\n\tfor(int i = 0 ; i < MX ; ++i)\n\t\tfor(int j = 0 ; j < MX ; ++j)\n\t\t\tsuf[i][j] = pre[i][j] = 1 % MOD;\n\t\t\t\n\t\n\t \n\tfor(int i = 2 ; i <= n ; ++i){\n\t\taddedge(read() ,read());\n\t\t// addedge(rand() % (i - 1) + 1 ,i);\n\t}\n\t\n\tdapai(1 ,0);\n\t\n\tfor(int i = 1 ; i < n ; ++i){\n\t\tLL ans = 0;\n\t\tfor(int j = 1 ; j <= i ; ++j){\n\t\t\tans += ((i - j) & 1 ? -1LL : 1LL) * C[i][j] * dp[1][j] % MOD;\n\t\t}\n\t\tans = (ans % MOD + MOD) % MOD;\n\t\tprintf(\"%lld%c\" ,ans ,\" \\n\"[i == n]);\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1707",
    "index": "E",
    "title": "Replace",
    "statement": "You are given an integer array $a_1,\\ldots, a_n$, where $1\\le a_i \\le n$ for all $i$.\n\nThere's a \"replace\" function $f$ which takes a pair of integers $(l, r)$, where $l \\le r$, as input and outputs the pair $$f\\big( (l, r) \\big)=\\left(\\min\\{a_l,a_{l+1},\\ldots,a_r\\},\\, \\max\\{a_l,a_{l+1},\\ldots,a_r\\}\\right).$$\n\nConsider repeated calls of this function. That is, from a starting pair $(l, r)$ we get $f\\big((l, r)\\big)$, then $f\\big(f\\big((l, r)\\big)\\big)$, then $f\\big(f\\big(f\\big((l, r)\\big)\\big)\\big)$, and so on.\n\nNow you need to answer $q$ queries. For the $i$-th query you have two integers $l_i$ and $r_i$ ($1\\le l_i\\le r_i\\le n$). You must answer the minimum number of times you must apply the \"replace\" function to the pair $(l_i,r_i)$ to get $(1, n)$, or report that it is impossible.",
    "tutorial": "Let $f([l,r])$ be the \"replace\" function. That means $f([l,r])=[\\min\\{a_i|l\\le i\\le r\\},\\max\\{a_i|l\\le i\\le r\\}]$. $f^k([l,r])$ means applying the function $k$ times. When $[a_1,b_1]\\bigcap[a_2,b_2]\\ne \\emptyset$, Let $j=\\max\\{a_1,a_2\\}$, then $j\\in[a_1,b_1]$ and $j\\in[a_{2},b_{2}]$. So $a_j\\in f([a_1,b_1])$ and $a_j\\in f([a_{2},b_{2}])$. That means $f([a_1,b_1])\\bigcap f([a_{2},b_{2}])\\ne \\emptyset$, so $f([\\min\\{a_1,a_{2}\\},\\max\\{b_1,b_{2}\\}])=f([a_1,b_1])\\bigcup f([a_{2},b_{2}])$. When $m>2$ it can be similarly proved that if $\\forall 1\\le i<m,[a_i,b_i]\\bigcap [a_{i+1},b_{i+1}]\\ne \\emptyset$, then $f(\\bigcup\\limits_{1\\le i\\le m}[a_i,b_i])=\\bigcup\\limits_{1\\le i\\le m}f([a_i,b_i])$. And we also know that if $[a_1,b_1]\\bigcap [a_2,b_2]\\ne \\emptyset$, then $f([a_1,b_1])\\bigcap f([a_2,b_2])\\ne \\emptyset$, then $f^k([a_1,b_1])\\bigcap f^k([a_2,b_2])\\ne \\emptyset$. So we know $f^k(\\bigcup\\limits_{1\\le i\\le m}[a_i,b_i])=\\bigcup\\limits_{1\\le i\\le m}f^k([a_i,b_i])$. So $f^k([l,r])=\\bigcup\\limits_{l\\le i<r}f^k([i,i+1])$. We can use $f^{p+q}([l,r])=f^p(f^q([l,r]))$ to easily get $f^{2^k}([i,i+1])$ in $O(n\\log^2n)$ at first, then we can calculate $f^{2^k}([l,r])$ in $O(\\log n)$. Use binary search we can get answer in $O(\\log^2n)$. So the time complexity is $O((n+q)\\log^2n)$. We can use BIT instead of segment tree to make our program run faster.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#define ch() getchar()\n#define pc(x) putchar(x)\nusing namespace std;\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(f=1,c=ch();c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch()){x=x*10+(c&15);}x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[64];int cnt=0;\n\tif(x==0)return pc('0'),void();\n\tif(x<0)pc('-'),x=-x;\n\twhile(x)q[cnt++]=x%10+'0',x/=10;\n\twhile(cnt--)pc(q[cnt]);\n}\nconst int maxn=100005,maxq=100005,maxt=34;\nconst int inf=0x3f3f3f3f;\nint a[maxn];\nstruct Segment{\n\tint l,r;\n\tSegment(int l=inf,int r=-inf):\n\t\tl(l),r(r){}\n\tSegment operator * (const Segment o)const{\n\t\treturn Segment(min(l,o.l),max(r,o.r));\n\t}\n\tbool operator != (const Segment o)const{\n\t\treturn l!=o.l||r!=o.r;\n\t}\n\tvoid input(void){\n\t\tread(l),read(r);\n\t}\n}sg[maxt][maxn],tr[maxn],qy[maxq];\nint n;\nvoid res(void){\n\tfor(int i=1;i<n;++i)\n\t\ttr[i]=Segment();\n}\nvoid add(int p,Segment v){\n\twhile(p<n){\n\t\ttr[p]=tr[p]*v;\n\t\tp+=(p&(-p));\n\t}\n}\nSegment ask(int p){\n\tSegment re;\n\twhile(p){\n\t\tre=re*tr[p];\n\t\tp^=(p&(-p));\n\t}\n\treturn re;\n}\nstruct Edge{\n\tint v,w,nt;\n\tEdge(int v=0,int w=0,int nt=0):\n\t\tv(v),w(w),nt(nt){}\n}e[maxn];\nint num,hd[maxn];\nvoid ins(int u,int v,int w){\n\te[++num]=Edge(v,w,hd[u]),hd[u]=num;\n}\nint st[maxq],tp;\nlong long Ans[maxq];\nint main(){\n\tint q;read(n),read(q);\n\tif(n==1){while(q--)puts(\"0\");return 0;}\n\tfor(int i=1;i<=n;++i)read(a[i]);\n\tfor(int i=1;i<n;++i){\n\t\t if(a[i]<=a[i+1])\n\t\t \tsg[0][i]=Segment(a[i],a[i+1]);\n\t\telse\n\t\t\tsg[0][i]=Segment(a[i+1],a[i]);\n\t}\n\tfor(int i=1;i<maxt;++i){\n\t\tfor(int j=1;j<n;++j){\n\t\t\tif(sg[i-1][j].l>=sg[i-1][j].r)sg[i][j]=Segment();\n\t\t\telse ins(sg[i-1][j].l,sg[i-1][j].r-1,j);\n\t\t}\n\t\tres();\n\t\tfor(int j=n-1;j>=1;--j){\n\t\t\tadd(j,sg[i-1][j]);\n\t\t\tfor(int k=hd[j];k;k=e[k].nt){\n\t\t\t\tsg[i][e[k].w]=ask(e[k].v);\n\t\t\t}\n\t\t\thd[j]=0;\n\t\t}\n\t\tnum=0;\n\t}\n\tfor(int i=1;i<=q;++i){\n\t\tqy[i].input();\n\t\tif(qy[i].l==qy[i].r)Ans[i]=-2;\n\t\telse ins(qy[i].l,qy[i].r-1,i);\n\t}\n\tres();\n\tfor(int i=n-1;i>=1;--i){\n\t\tadd(i,sg[maxt-1][i]);\n\t\tfor(int j=hd[i];j;j=e[j].nt){\n\t\t\tif(i==1&&e[j].v==n-1)\n\t\t\t\tAns[e[j].w]=-1;\n\t\t\telse if(ask(e[j].v)!=Segment(1,n))\n\t\t\t\tAns[e[j].w]=-2;\n\t\t\telse\n\t\t\t\tst[++tp]=e[j].w;\n\t\t}\n\t\thd[i]=0;\n\t}\n\tnum=0;\n\tfor(int i=maxt-2;~i;--i){\n\t\tfor(int j=1;j<=tp;++j){\n\t\t\tins(qy[st[j]].l,qy[st[j]].r-1,st[j]);\n\t\t}\n\t\tres();\n\t\tfor(int j=n-1;j>=1;--j){\n\t\t\tadd(j,sg[i][j]);\n\t\t\tfor(int k=hd[j];k;k=e[k].nt){\n\t\t\t\tSegment tmp=ask(e[k].v);\n\t\t\t\tint id=e[k].w;\n\t\t\t\tif(tmp!=Segment(1,n))\n\t\t\t\t\tAns[id]|=(1ll<<i),qy[id]=tmp;\n\t\t\t}\n\t\t\thd[j]=0;\n\t\t}\n\t\tnum=0;\n\t}\n\tfor(int i=1;i<=q;++i)\n\t\twrite(++Ans[i]),pc('\\n');\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1707",
    "index": "F",
    "title": "Bugaboo",
    "statement": "A transformation of an array of positive integers $a_1,a_2,\\dots,a_n$ is defined by replacing $a$ with the array $b_1,b_2,\\dots,b_n$ given by $b_i=a_i\\oplus a_{(i\\bmod n)+1}$, where $\\oplus$ denotes the bitwise XOR operation.\n\nYou are given integers $n$, $t$, and $w$. We consider an array $c_1,c_2,\\dots,c_n$ ($0 \\le c_i \\le 2^w-1$) to be bugaboo if and only if there exists an array $a_1,a_2,\\dots,a_n$ such that after transforming $a$ for $t$ times, $a$ becomes $c$.\n\nFor example, when $n=6$, $t=2$, $w=2$, then the array $[3,2,1,0,2,2]$ is bugaboo because it can be given by transforming the array $[2,3,1,1,0,1]$ for $2$ times:\n\n$$ [2,3,1,1,0,1]\\to [2\\oplus 3,3\\oplus 1,1\\oplus 1,1\\oplus 0,0\\oplus 1,1\\oplus 2]=[1,2,0,1,1,3]; \\\\ [1,2,0,1,1,3]\\to [1\\oplus 2,2\\oplus 0,0\\oplus 1,1\\oplus 1,1\\oplus 3,3\\oplus 1]=[3,2,1,0,2,2]. $$\n\nAnd the array $[4,4,4,4,0,0]$ is not bugaboo because $4 > 2^2 - 1$. The array $[2,3,3,3,3,3]$ is also not bugaboo because it can't be given by transforming one array for $2$ times.\n\nYou are given an array $c$ with some positions lost (only $m$ positions are known at first and the remaining positions are lost). And there are $q$ modifications, where each modification is changing a position of $c$. A modification can possibly change whether the position is lost or known, and it can possibly redefine a position that is already given.\n\nYou need to calculate how many possible arrays $c$ (with arbitrary elements on the lost positions) are bugaboos after each modification. Output the $i$-th answer modulo $p_i$ ($p_i$ is a given array consisting of $q$ elements).",
    "tutorial": "We can first solve an easier condition when $n=2^h(h\\ge 0)$. We know for any array $a_1,a_2,\\ldots,a_{2^h}$, transforming it for $2^h$ times $a_i=0$. If you transform it more than $2^h$ times it is also guaranteed that $a_i=0$. So in this condition, if $t\\ge 2^h$, we only need to test whether for all $i$, $c_i$ can be $0$. When $t<2^h$, if transforming an array $a_1,a_2,\\ldots,a_n$ for $t$ times $a$ becomes $c$, then it can be proved that $\\bigoplus\\limits_{i=1}^{2^h}a_i$ depends on $t,h$ and the array $c$. We can let $f(t,h,c_1,c_2,\\ldots,c_{2^h})=\\bigoplus\\limits_{i=1}^{2^h}a_i$. Proof: When $h=0$, $t$ must be $0$, so $f(t,h,c_1)=c_1$. When $h>0$, $f(t,h,c_1,c_2,\\ldots,c_{2^h})$ can be given by $f(\\lfloor\\frac{t}{2}\\rfloor,h-1,c_1,c_3,\\ldots,c_{2^h-1})$ and $f(\\lfloor\\frac{t}{2}\\rfloor,h-1,c_2,c_4,\\ldots,c_{2^h})$. The specific process is below. If $t$ is an even number, then we know transforming $a_1,a_3,\\ldots,a_{2^h-1}$ for $\\frac{t}{2}$ times it becomes $c_1,c_3,\\ldots,c_{2^h-1}$. Also transforming $a_2,a_4,\\ldots,a_{2^h}$ for $\\frac{t}{2}$ times it becomes $c_2,c_4,\\ldots,c_{2^h}$. So in this case, $f(t,h,c_1,c_2,\\ldots,c_{2^h})=f(\\lfloor\\frac{t}{2}\\rfloor,h-1,c_1,c_3,\\ldots,c_{2^h-1})\\oplus f(\\lfloor\\frac{t}{2}\\rfloor,h-1,c_2,c_4,\\ldots,c_{2^h})$. If $t$ is an odd number, then we can first transform $a$ once, then it becomes the even number case. That is to say, $a$ now becomes $a_1\\oplus a_2,a_2\\oplus a_3,\\ldots,a_{2^h}\\oplus a_1$. Transforming $a_1\\oplus a_2,a_3\\oplus a_4,\\ldots,a_{2^h-1}\\oplus a_{2^h}$ for $\\lfloor\\frac{t}{2}\\rfloor$ times it becomes $c_1,c_3,\\ldots,c_{2^h-1}$. Transforming $a_2\\oplus a_3,a_4\\oplus a_5,\\ldots,a_{2^h}\\oplus a_1$ for $\\lfloor\\frac{t}{2}\\rfloor$ times it becomes $c_2,c_4,\\ldots,c_{2^h}$. So in this case, $f(t,h,c_1,c_2,\\ldots,c_{2^h})=f(\\lfloor\\frac{t}{2}\\rfloor,h-1,c_1,c_3,\\ldots,c_{2^h-1})=f(\\lfloor\\frac{t}{2}\\rfloor,h-1,c_2,c_4,\\ldots,c_{2^h})$. Actually the process above can inspire us to find an easy way to judge whether an array is a bugaboo. We just need to use divide and conquer to calculate $f(t,h,c_1,\\ldots,c_{2^h})$ .When it becomes the second case, judge whether $f(\\lfloor\\frac{t}{2}\\rfloor,h-1,c_1,c_3,\\ldots,c_{2^h-1})=f(\\lfloor\\frac{t}{2}\\rfloor,h-1,c_2,c_4,\\ldots,c_{2^h})$. If and only if all the requirements are met, the array $c$ is a bugaboo. And the good news is that it can be used to calculate the number of bugaboos. Let $dp(t,h,d_1,d_2,\\ldots,d_{2^h},k)=$ the number of arrays $c_{d_1},c_{d_2},\\ldots,c_{d_{2^h}}$ which are bugaboos and $f(t,h,c_{d_1},c_{d_2},\\ldots,c_{d_{2^h}})=k$. Just like the process above, when $t$ is an even number, $dp(t,h,d_1,d_2,\\ldots,d_{2^h},k)=\\sum\\limits_{l=0}^{2^w-1}dp(\\lfloor\\frac{t}{2}\\rfloor,h-1,d_1,d_3,\\ldots,d_{2^h-1},l)\\cdot dp(\\lfloor\\frac{t}{2}\\rfloor,h-1,d_2,d_4,\\ldots,d_{2^h},k\\oplus l)$; When $t$ is an odd number, $dp(t,h,d_1,d_2,\\ldots,d_{2^h},k)=dp(\\lfloor\\frac{t}{2}\\rfloor,h-1,d_1,d_3,\\ldots,d_{2^h-1},k)\\cdot dp(\\lfloor\\frac{t}{2}\\rfloor,h-1,d_2,d_4,\\ldots,d_{2^h},k)$.When $c_d$ is lost, $dp(0,0,d,k)=1$. When $c_d=k_0$, $dp(0,0,d,k)=[k=k_0]$. The answer is $\\sum\\limits_{k=0}^{2^w-1}dp(t,h,1,2,\\ldots,2^h,k)$. However, $2^w$ is so huge that we cannot do it in a short time. After some careful observations, we can surprisingly find that for $dp(t,h,d_1,d_2,\\ldots,d_{2^h},?)$ either $\\forall k,dp(t,h,d_1,d_2,\\ldots,d_{2^h},k)=(2^w)^A$, or $\\forall k,dp(t,h,d_1,d_2,\\ldots,d_{2^h},k)=[k=B]\\cdot(2^w)^C$, or $\\forall k,dp(t,h,d_1,d_2,\\ldots,d_{2^h},k)=0$. We can use this to simplify our process, making our time complexity free from $w$. By the way, the divide and conquer process above is very similar to FFT. That is to say, we can reverse the indexes' binary bit to make the process faster. So, when $n=2^h$, without modifications we can work out the answer in $O(n)$. And the process is just like the structure of segment tree, so we can do a modification in $O(\\log n)$. The total time complexity is $O(n+(m+q)\\log n)$. When $n$ cannot be given by $2^h$, we can simply let $h$ be the lowest bit of $n$, that is to say, $n=2^h\\cdot o$($o$ is an odd number). Then we can consider $i,i+2^h,\\ldots,i+2^h\\cdot(o-1)$ as a whole to do the process above. The only thing we need to notice is that when $t>2^h$, the requirement is that for all $i$, $\\bigoplus\\limits_{l=0}^{o-1}c_{i+2^h\\cdot l}$ can be $0$. Now we can solve the problem in $O(n+(m+q)\\log n)$.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#include<assert.h>\n#define ch() getchar()\n#define pc(x) putchar(x)\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(c=ch(),f=1;c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch())x=x*10+(c&15);x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[65];int cnt=0;\n\tif(x<0)pc('-'),x=-x;\n\tq[++cnt]=x%10,x/=10;\n\twhile(x)\n\t\tq[++cnt]=x%10,x/=10;\n\twhile(cnt)pc(q[cnt--]+'0');\n}\nconst int maxn=20000005;\nstruct Count{\n\tint pos,val;\n\tCount(int pos=-1,int val=-1):\n\t\tpos(pos),val(val){}\n};\nint plus(int x,int y){\n\treturn (x<0||y<0)?-1:x+y;\n}\nCount operator + (const Count A,const Count B){\n\tint Ap=A.pos,Bp=B.pos,va=plus(A.val,B.val);\n\tif(~Ap&&~Bp)return Ap^Bp?Count():Count(Ap|Bp,va);\n\tif(~Ap||~Bp)return Count(Ap&Bp,va);\n\treturn Count(-1,va);\n}\nCount operator * (const Count A,const Count B){\n\tint Ap=A.pos,Bp=B.pos,va=plus(A.val,B.val);\n\tif(~Ap&&~Bp)return Count(Ap^Bp,va);\n\tif(~Ap||~Bp)return Count(-1,va);\n\treturn Count(-1,plus(va,1));\n}\nint c[maxn];\nint tn,Op[maxn],Cn[maxn];\nCount dp[maxn];\nint t,hb[maxn],rev[maxn];\nvoid pushup(int p){\n\tint l=p<<1,r=l|1;\n\tdp[p]=((t&hb[p])?(dp[l]+dp[r]):(dp[l]*dp[r]));\n}\nint va1,sum;\nvoid ins(int i){\n\tint p=rev[(i&(tn-1))];\n\tif(~c[i])Op[p]^=c[i];else ++Cn[p];\n\tif(dp[p+tn].pos>0)--va1;else sum-=dp[p+tn].val;\n\tdp[p+tn]=(Cn[p]?Count(-1,Cn[p]-1):Count(Op[p],0));\n\tif(dp[p+tn].pos>0)++va1;else sum+=dp[p+tn].val;\n}\nvoid del(int i){\n\tint p=rev[(i&(tn-1))];\n\tif(~c[i])Op[p]^=c[i];else --Cn[p];\n}\nint power(int a,int x,int p){\n\tif(x==-1)return 0;\n\tint re=1;\n\twhile(x){\n\t\tif(x&1)re=1ll*re*a%p;\n\t\ta=1ll*a*a%p;x>>=1;\n\t}\n\treturn re;\n}\nint main(){\n\tint n,m,w;\n\tread(n),read(m),read(t),read(w);\n\tmemset(c,-1,sizeof c);\n\tfor(int i=1;i<=m;++i){\n\t\tint d;read(d);--d;read(c[d]);\n\t}\n\ttn=(n&(-n));\n\thb[0]=0;hb[1]=1;\n\tfor(int i=2;i<tn*2;++i)\n\t\thb[i]=(hb[i>>1]<<1);\n\tint cn=-1;for(;(1<<(cn+1))<tn;++cn);\n\tfor(int i=1;i<tn;++i)\n\t\trev[i]=(rev[i>>1]>>1)|((i&1)<<cn);\n\tfor(int i=0;i<tn;++i)dp[i+tn].val=0;\n\tfor(int i=0;i<n;++i)ins(i);\n\tif(t<tn)for(int i=tn-1;i>=1;--i)pushup(i);\n\tint q;read(q);\n\twhile(q--){\n\t\tint f;read(f);--f;\n\t\tdel(f);read(c[f]);ins(f);\n\t\tint p;read(p);\n\t\tif(t>=tn){\n\t\t\twrite(va1?0:power((1<<w)%p,sum,p));\n\t\t}\n\t\telse{\n\t\t\tint now=(rev[(f&(tn-1))]|tn);while(now>>=1)pushup(now);\n\t\t\twrite(power((1<<w)%p,plus(dp[1].val,dp[1].pos==-1),p));\n\t\t}\n\t\tpc('\\n');\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1708",
    "index": "A",
    "title": "Difference Operations",
    "statement": "You are given an array $a$ consisting of $n$ positive integers.\n\nYou are allowed to perform this operation any number of times (possibly, zero):\n\n- choose an index $i$ ($2 \\le i \\le n$), and change $a_i$ to $a_i - a_{i-1}$.\n\nIs it possible to make $a_i=0$ for all $2\\le i\\le n$?",
    "tutorial": "Solution 1 For all $i \\ge 2$, $a_i$ is the multiple of $a_1$ is equivalent to the YES answer. Proof of necessity $a_2$ must be the multiple of $a_1$. Otherwise $a_2$ cannot become zero. In the whole process, $a_2$ is always the multiple of $a_1$. So $a_3$ must be the multiple of $a_1$. Otherwise $a_3$ cannot become zero. In the whole process, $a_3$ is always the multiple of $a_1$. So $a_4$ must be the multiple of $a_1$. Otherwise $a_4$ cannot become zero. ... Proof of sufficiency For all $i \\ge 2$, $a_i$ is the multiple of $a_1$. So we can perform operations to make $a=[a_1,a_1,a_1,\\cdots]$ and then make $a=[a_1,0,0,\\cdots]$. Solution 2 Consider everything in the reverse order. You are given an array $b$ consisting of $n$ positive integers, where $b=[b_1,0,0,\\cdots,0]$ ($b_1$ and $n-1$ zeros). You are given an array $a$ consisting of $n$ positive integers. It is guaranteed that $a_1=b_1$. You are allowed to perform this operation any number of times (possibly, zero): Choose an index $i$ ($2\\le i \\le n$), and change $b_i$ to $b_i+b_{i-1}$. Is it possible to change $b$ to $a$? Check if $a_i$ is the multiple of $a_1$.",
    "code": "#include <bits/stdc++.h>\n\n#define debug(...) fprintf(stderr ,__VA_ARGS__)\n#define LL long long\n\nconst LL MOD = 1e9 + 7;\nconst int MX = 1e5 + 23;\n\nint read(){\n\tchar k = getchar(); LL x = 0;\n\twhile(k < '0' || k > '9') k = getchar();\n\twhile(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();\n\treturn x;\n}\n\nint n ,a[MX];\nvoid solve(){\n\tn = read();\n\tfor(int i = 1 ; i <= n ; ++i) a[i] = read();\n\tint ok = 1;\n\tfor(int i = 1 ; i <= n ; ++i){\n\t\tif(a[i] % a[1]) ok = false;\n\t}\n\tputs(ok ? \"YES\" : \"NO\");\n}\n\nint main(){\n\tint T = read();\n\twhile(T--) solve();\n\treturn 0;\n}\n",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1708",
    "index": "B",
    "title": "Difference of GCDs",
    "statement": "You are given three integers $n$, $l$, and $r$. You need to construct an array $a_1,a_2,\\dots,a_n$ ($l\\le a_i\\le r$) such that $\\gcd(i,a_i)$ are all distinct or report there's no solution.\n\nHere $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.",
    "tutorial": "$\\gcd(i,a_i)\\le i$. Because all $\\gcd(i,a_i)$ are different, then $\\gcd(i,a_i)=i$, which means $a_i$ is the multiple of $i$. To check if there is such $a_i$, just check if $a_i=\\left(\\lfloor \\frac{l-1}{i} \\rfloor +1\\right)\\cdot i$ (the minimum multiple of $i$ that is strictly bigger than $l-1$) is less than $r$. Time complexity $O(n)$ for each test case.",
    "code": "#include <bits/stdc++.h>\n\n#define debug(...) fprintf(stderr ,__VA_ARGS__)\n#define __FILE(x)\\\n\tfreopen(#x\".in\" ,\"r\" ,stdin);\\\n\tfreopen(#x\".out\" ,\"w\" ,stdout)\n#define LL long long\n\nconst int MX = 1e5 + 23;\nconst LL MOD = 998244353;\n\nint read(){\n\tchar k = getchar(); int x = 0;\n\twhile(k < '0' || k > '9') k = getchar();\n\twhile(k >= '0' && k <= '9') x = x * 10 + k - '0' ,k = getchar();\n\treturn x;\n}\n\nint a[MX];\nvoid solve(){\n\tint n = read() ,l = read() ,r = read();\n\tint ok = 1;\n\tfor(int i = 1 ; i <= n ; ++i){\n\t\ta[i] = ((l - 1) / i + 1) * i;\n\t\tok = ok && a[i] <= r;\n\t}\n\tif(ok){\n\t\tputs(\"YES\");\n\t\tfor(int i = 1 ; i <= n ; ++i)\n\t\t\tprintf(\"%d%c\" ,a[i] ,\" \\n\"[i == n]);\n\t}\n\telse puts(\"NO\");\n}\n\nint main(){\n\tint T = read();\n\tfor(int i = 1 ; i <= T ; ++i){\n\t\tsolve();\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1709",
    "index": "A",
    "title": "Three Doors",
    "statement": "There are three doors in front of you, numbered from $1$ to $3$ from left to right. Each door has a lock on it, which can only be opened with a key with the same number on it as the number on the door.\n\nThere are three keys — one for each door. Two of them are hidden behind the doors, so that there is no more than one key behind each door. So two doors have one key behind them, one door doesn't have a key behind it. To obtain a key hidden behind a door, you should first unlock that door. The remaining key is in your hands.\n\nCan you open all the doors?",
    "tutorial": "Note that we never have a choice in what door should we open. First, we open the door with the same number as the key in our hand. Then, the door with the same number as the key behind the first opened door. Finally, the door with the same number as the key behind the second opened door. If any of the first and second opened doors didn't have a key behind it, then it's impossible. Otherwise, we open every door. Let $a_1, a_2, a_3$ be the keys behind the corresponding doors. Then we should check if $a[x]$ is not zero and $a[a[x]]$ is not zero. Overall complexity: $O(1)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tx = int(input())\n\ta = [0] + [int(x) for x in input().split()]\n\tprint(\"YES\" if a[x] != 0 and a[a[x]] != 0 else \"NO\")",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1709",
    "index": "B",
    "title": "Also Try Minecraft",
    "statement": "You are beta testing the new secret Terraria update. This update will add quests to the game!\n\nSimply, the world map can be represented as an array of length $n$, where the $i$-th column of the world has height $a_i$.\n\nThere are $m$ quests you have to test. The $j$-th of them is represented by two integers $s_j$ and $t_j$. In this quest, you have to go from the column $s_j$ to the column $t_j$. At the start of the quest, you are appearing at the column $s_j$.\n\nIn one move, you can go from the column $x$ to the column $x-1$ or to the column $x+1$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $p$ to the column with the height $q$, then you get some amount of fall damage. If the height $p$ is greater than the height $q$, you get $p - q$ fall damage, otherwise you fly up and get $0$ damage.\n\nFor each of the given quests, determine the minimum amount of fall damage you can get during this quest.",
    "tutorial": "So, the first idea that is coming into mind is prefix sums. Let's define two values $l_i = max(0, a_i - a_{i + 1})$ and $r_i = max(0, a_{i + 1} - a_i)$. The value $l_i$ means the amount of fall damage when we are going to the right from the column $i$ to the column $i + 1$, and $r_i$ means the amount of fall damage when we are going to the left from the column $i + 1$ to the column $i$. Then let's build prefix sums on these two arrays. Now let $pl_i$ be the sum of all $l_i$ on a prefix $[0; i)$ (i. e. $pl_0 = 0$), and $pr_i$ be the sum of all $r_i$ on a prefix $[0; i)$. Then if $s < t$ in a query, the answer is $pl_{t - 1} - pl_{s - 1}$, otherwise (if $s > t$) the answer is $pr_{s - 1} - pr_{t - 1}$. Time complexity: $O(n)$.",
    "code": "n, m = map(int, input().split())\na = list(map(int, input().split()))\nl = [0] + [max(0, a[i] - a[i + 1]) for i in range(n - 1)]\nr = [0] + [max(0, a[i] - a[i - 1]) for i in range(1, n)]\nfor i in range(n - 1):\n    l[i + 1] += l[i]\n    r[i + 1] += r[i]\nfor _ in range(m):\n    s, t = map(int, input().split())\n    if s < t:\n        print(l[t - 1] - l[s - 1])\n    else:\n        print(r[s - 1] - r[t - 1])",
    "tags": [
      "data structures",
      "dp",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1709",
    "index": "C",
    "title": "Recover an RBS",
    "statement": "A bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example:\n\n- bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\");\n- bracket sequences \")(\", \"(\" and \")\" are not.\n\nThere was an RBS. Some brackets have been replaced with question marks. Is it true that there is a \\textbf{unique} way to replace question marks with brackets, so that the resulting sequence is an RBS?",
    "tutorial": "There are many different approaches to this problem, but I think the model solution has the most elegant one. First of all, let's construct an RBS from the given string (it always exists, so it is always possible). By calculating the number of opening brackets, closing brackets and questions in the given string, we can compute the number of question marks that should be replaced with opening brackets (it is easy since exactly half of the characters in each RBS are opening brackets). Then, let's form the RBS greedily: replace the first several question marks with opening brackets, and all remaining ones with closed brackets. Okay, then what about finding a second RBS? Recall that a bracket sequence is an RBS when for each of its positions, the number of closing brackets before it is not greater than the number of opening brackets before it (and these two values should be equal at the end of the sequence, but it is less important now). Consider the segment between the last question mark replaced with an opening bracket, and the first question mark replaced by the closing bracket. If we try to change the order of characters corresponding to question marks, the balance on this segment will decrease at least by $2$ (since at least one opening bracket to the left of it will become a closing bracket). Is there a way to affect only this segment, and change the balance on it only by $2$? Yes - just swap the endpoints of this segment (i. e. the last opening bracket that was a question mark and the first closing bracket that was also a question mark). If it yields an RBS, then the answer is NO. Otherwise, the answer is YES since any other permutation of characters that were replacing question marks will also decrease the balance on this segment by at least $2$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  auto check = [](const string& s) {\n    int bal = 0;\n    for (char c : s) {\n      if (c == '(') ++bal;\n      if (c == ')') --bal;\n      if (bal < 0) return false;\n    }\n    return bal == 0;\n  };\n  \n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    string s;\n    cin >> s;\n    vector<int> pos;\n    int op = s.size() / 2, cl = s.size() / 2;\n    for (int i = 0; i < s.size(); ++i) {\n      if (s[i] == '?') pos.push_back(i);\n      if (s[i] == '(') --op;\n      if (s[i] == ')') --cl;\n    }\n    for (int i = 0; i < pos.size(); ++i) {\n      if (i < op) s[pos[i]] = '(';\n      else s[pos[i]] = ')';\n    }\n    bool ok = true;\n    if (op > 0 && cl > 0) {\n      swap(s[pos[op - 1]], s[pos[op]]);\n      if (check(s)) ok = false;\n    }\n    cout << (ok ? \"YES\\n\" : \"NO\\n\");\n  }\n} ",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1709",
    "index": "D",
    "title": "Rorororobot",
    "statement": "There is a grid, consisting of $n$ rows and $m$ columns. The rows are numbered from $1$ to $n$ from bottom to top. The columns are numbered from $1$ to $m$ from left to right. The $i$-th column has the bottom $a_i$ cells blocked (the cells in rows $1, 2, \\dots, a_i$), the remaining $n - a_i$ cells are unblocked.\n\nA robot is travelling across this grid. You can send it commands — move up, right, down or left. If a robot attempts to move into a blocked cell or outside the grid, it explodes.\n\nHowever, the robot is broken — it executes each received command $k$ times. So if you tell it to move up, for example, it will move up $k$ times ($k$ cells). You can't send it commands while the robot executes the current one.\n\nYou are asked $q$ queries about the robot. Each query has a start cell, a finish cell and a value $k$. Can you send the robot an arbitrary number of commands (possibly, zero) so that it reaches the finish cell from the start cell, given that it executes each command $k$ times?\n\nThe robot must stop in the finish cell. If it visits the finish cell while still executing commands, it doesn't count.",
    "tutorial": "What if there were no blocked cells? Then the movement is easy. From cell $(x, y)$ we can go to cells $(x + k, y)$, $(x, y + k)$, $(x - k, y)$ or $(x, y - k)$. Thus, we can visit all cells that have the same remainder modulo $k$ over both dimensions. The answer would be \"YES\" if $x_s \\bmod k = x_f \\bmod k$ and $y_s \\bmod k = y_f \\bmod k$. Let's choose the following path from start to finish. Let $x_s$ be less or equal to $x_f$. If that isn't the case, swap the cells. First, move up until the row is the same, then move to the side until the column is the same. What stops us from doing the same on a grid with blocked cells? The first part of the part can remain the same - we can always move up from the cell. Only cells below the start cell can be blocked. The second part is trickier. If there is a column with too many blocked cells between the start and the finish column, then we won't be able to pass through it. Let's adjust the path for that. Move up as high as possible - to the highest cell with the same remainder modulo $k$ in this column. Then move to the finish column and go down to the finish cell. If there still exists a column with too many blocked cells, then the answer is \"NO\". No matter what we do, we won't be able to go around that column. Otherwise, the answer is \"YES\". Thus, the solution is to check for remainders, then find the largest number of blocked cells between the query columns and compare it to the highest row with the same remainder modulo $k$ as the start or the finish. You can use any RMQ data structure you want. Overall complexity: $O(n \\log n + q)$ with sparse table for RMQ, for example.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tvector<int> a(m);\n\tforn(i, m) scanf(\"%d\", &a[i]);\n\t\n\tint l = 0;\n\twhile ((1 << l) <= m) ++l;\n\tvector<vector<int>> st(l, vector<int>(m));\n\tforn(i, m) st[0][i] = a[i];\n\tfor (int j = 1; j < l; ++j) forn(i, m){\n\t\tst[j][i] = st[j - 1][i];\n\t\tif (i + (1 << (j - 1)) < m)\n\t\t\tst[j][i] = max(st[j][i], st[j - 1][i + (1 << (j - 1))]);\n\t}\n\tvector<int> pw(m + 1, 0);\n\tfor (int i = 2; i <= m; ++i) pw[i] = pw[i / 2] + 1;\n\tauto get = [&](int l, int r){\n\t\tif (l > r) swap(l, r);\n\t\t++r;\n\t\tint len = pw[r - l];\n\t\treturn max(st[len][l], st[len][r - (1 << len)]);\n\t};\n\t\n\tint q;\n\tscanf(\"%d\", &q);\n\tforn(_, q){\n\t\tint xs, ys, xf, yf, k;\n\t\tscanf(\"%d%d%d%d%d\", &xs, &ys, &xf, &yf, &k);\n\t\t--xs, --ys, --xf, --yf;\n\t\tif (ys % k != yf % k || xs % k != xf % k){\n\t\t\tputs(\"NO\");\n\t\t\tcontinue;\n\t\t}\n\t\tint mx = (n - xs - 1) / k * k + xs;\n\t\tputs(get(ys, yf) <= mx ? \"YES\" : \"NO\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1709",
    "index": "E",
    "title": "XOR Tree",
    "statement": "You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.\n\nRecall that a simple path is a path that visits each vertex at most once. Let the weight of the path be the bitwise XOR of the values written on vertices it consists of. Let's say that a tree is good if no simple path has weight $0$.\n\nYou can apply the following operation any number of times (possibly, zero): select a vertex of the tree and replace the value written on it with an arbitrary positive integer. What is the minimum number of times you have to apply this operation in order to make the tree good?",
    "tutorial": "To begin with, we note that there are no restrictions on the values that can be written on the vertices, so we can use numbers of the form $2^{30+x}$ for the $x$-th replacement. Then, if we replaced the value of a vertex, then no path passing through this vertex has weight $0$. Let's root the tree at the vertex number $1$. We can use a greedy approach: consider some vertex $v$ such that it is the LCA for two vertices $x$ and $y$, the path between which has XOR equal to $0$. Among such vertices $v$, pick one with the maximum distance from the root. We need to change at least one vertex on the path $(x, y)$. It turns out that changing the vertex $v$ is always no worse than changing any other vertex $u$ on this path, because all the remaining bad paths that pass through the vertex $u$ also pass through the vertex $v$ (that's why we have chosen the deepest LCA). This means that in order to solve the problem, it is necessary to quickly find the deepest LCA of some bad path. For the convenience of solving the problem, let's denote the XOR on the path $(x,y)$ as $b_x \\oplus b_y \\oplus a_{LCA(x,y)}$, where $b_v$ is XOR on the path from the root to the vertex $v$. For all vertices $v$, let's maintain a set of values $b_x$, such that $x$ belongs to the subtree of $v$. Let's use the small-to-large method to obtain such sets. Also, during the union of sets, we can check if there is a bad path in this subtree, i. e. if two values in the sets we merge have the same XOR as the value written on the current vertex (because that's when the XOR on path is $0$). If such a path exists, then we have to change the value of the vertex $v$ and mark that the vertices of this subtree cannot be the ends of a bad path anymore - that means we just clear the set instead of pulling it up the tree. This solution works in $O(n \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200 * 1000 + 13;\n\nint n;\nint a[N], b[N];\nvector<int> g[N];\nset<int> vals[N];\n\nvoid init(int v, int p) {\n  b[v] = a[v];\n  if (p != -1) b[v] ^= b[p];\n  for (int u : g[v]) if (u != p)\n    init(u, v);\n}\n\nint ans;\n\nvoid calc(int v, int p) {\n  bool bad = false;\n  vals[v].insert(b[v]);\n  for (int u : g[v]) if (u != p) {\n    calc(u, v);\n    if (vals[v].size() < vals[u].size()) vals[v].swap(vals[u]);\n    for (int x : vals[u]) bad |= vals[v].count(x ^ a[v]);\n    for (int x : vals[u]) vals[v].insert(x);\n    vals[u].clear();\n  }\n  if (bad) {\n    ans += 1;\n    vals[v].clear();\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  cin >> n;\n  for (int i = 0; i < n; ++i) cin >> a[i];\n  for (int i = 0; i < n - 1; ++i) {\n    int x, y;\n    cin >> x >> y;\n    --x; --y;\n    g[x].push_back(y);\n    g[y].push_back(x);\n  }\n  init(0, -1);\n  calc(0, -1);\n  cout << ans << '\\n';\n} ",
    "tags": [
      "bitmasks",
      "data structures",
      "dfs and similar",
      "dsu",
      "greedy",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1709",
    "index": "F",
    "title": "Multiset of Strings",
    "statement": "You are given three integers $n$, $k$ and $f$.\n\nConsider all binary strings (i. e. all strings consisting of characters $0$ and/or $1$) of length from $1$ to $n$. For every such string $s$, you need to choose an integer $c_s$ from $0$ to $k$.\n\nA multiset of binary strings of length \\textbf{exactly} $n$ is considered beautiful if for every binary string $s$ with length from $1$ to $n$, the number of strings in the multiset such that $s$ is their prefix is not exceeding $c_s$.\n\nFor example, let $n = 2$, $c_{0} = 3$, $c_{00} = 1$, $c_{01} = 2$, $c_{1} = 1$, $c_{10} = 2$, and $c_{11} = 3$. The multiset of strings $\\{11, 01, 00, 01\\}$ is beautiful, since:\n\n- for the string $0$, there are $3$ strings in the multiset such that $0$ is their prefix, and $3 \\le c_0$;\n- for the string $00$, there is one string in the multiset such that $00$ is its prefix, and $1 \\le c_{00}$;\n- for the string $01$, there are $2$ strings in the multiset such that $01$ is their prefix, and $2 \\le c_{01}$;\n- for the string $1$, there is one string in the multiset such that $1$ is its prefix, and $1 \\le c_1$;\n- for the string $10$, there are $0$ strings in the multiset such that $10$ is their prefix, and $0 \\le c_{10}$;\n- for the string $11$, there is one string in the multiset such that $11$ is its prefix, and $1 \\le c_{11}$.\n\nNow, for the problem itself. You have to calculate the number of ways to choose the integer $c_s$ for every binary string $s$ of length from $1$ to $n$ in such a way that the \\textbf{maximum} possible size of a beautiful multiset is \\textbf{exactly} $f$.",
    "tutorial": "First of all, let's visualize the problem in a different way. We have to set some constraints on the number of strings which have some kind of prefix. Let's think about a data structure that would allow us to understand it better. One of the most common data structures to store strings which works with their prefixes and maintains the number of strings with some prefix is a trie; so, we can reformulate this problem using tries. Now the problem is the following one: we have a binary trie of depth $n$; the leaves of this trie may store strings, and for each vertex except for the root, we can set a constraint on the number of strings stored in the subtree; what is the number of ways to choose these constraints so that the maximum number of strings (possibly with copies) the trie can store is exactly $f$? To handle it, we can use dynamic programming of the form $dp_{v,i}$ - the number of ways to choose the constraints for the vertex $v$ and its subtree so that the maximum number of strings which can be stored in the subtree is exactly $i$. When calculating $dp_{v,i}$, we can iterate on the constraint for the vertex $v$ (let it be $a$), and the maximum number of strings in the subtrees of $v_1$ and $v_2$ (let these be $b$ and $c$), and make updates of the form \"add $dp_{v_1,b} \\cdot dp_{v_2,c}$ to the value of $dp_{v, \\min(a,b+c)}$\". This dynamic programming will work in $O(2^n k^2)$ or $O(2^n k^3)$ depending on the implementation, which is too slow. However, we can use the following optimizations to improve the complexity of the solution: all vertices on the same depth can be treated as equivalent, so we can actually calculate this dynamic programming not for $O(2^n)$ vertices, but just for $O(n)$; when handling transitions from some node's children to that node, let's split these transitions into two steps. The first step is iterating on the number of strings which fit into the subtrees of the children; the second step is iterating on the constraint for the subtree of the node. The first step is actually a convolution: if we don't consider the constraint for the node itself, then the transitions would be something like \"add $dp_{v_1,b} \\cdot dp_{v_2,c}$ to the value of $dp_{v, b+c)}$\"; so it can be improved to $O(k \\log k)$ with FFT. The second step can be improved to $O(k)$ as well, if we iterate on the minimum between the constraint for the node and the total number of strings which can be stored in the children, and maintain the sum on suffix for the values of dynamic programming. Overall, these optimizations lead to a solution with complexity $O(n k \\log k)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "fft",
      "flows",
      "graphs",
      "math",
      "meet-in-the-middle",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1710",
    "index": "A",
    "title": "Color the Picture",
    "statement": "A picture can be represented as an $n\\times m$ grid ($n$ rows and $m$ columns) so that each of the $n \\cdot m$ cells is colored with one color. You have $k$ pigments of different colors. You have a limited amount of each pigment, more precisely you can color at most $a_i$ cells with the $i$-th pigment.\n\nA picture is considered beautiful if each cell has \\textbf{at least} $3$ \\textbf{toroidal} neighbors with the same color as itself.\n\nTwo cells are considered \\textbf{toroidal} neighbors if they \\textbf{toroidally} share an edge. In other words, for some integers $1 \\leq x_1,x_2 \\leq n$ and $1 \\leq y_1,y_2 \\leq m$, the cell in the $x_1$-th row and $y_1$-th column is a toroidal neighbor of the cell in the $x_2$-th row and $y_2$-th column if one of following two conditions holds:\n\n- $x_1-x_2 \\equiv \\pm1 \\pmod{n}$ and $y_1=y_2$, or\n- $y_1-y_2 \\equiv \\pm1 \\pmod{m}$ and $x_1=x_2$.\n\nNotice that each cell has exactly $4$ toroidal neighbors. For example, if $n=3$ and $m=4$, the toroidal neighbors of the cell $(1, 2)$ (the cell on the first row and second column) are: $(3, 2)$, $(2, 2)$, $(1, 3)$, $(1, 1)$. They are shown in gray on the image below:\n\n\\begin{center}\n{\\small The gray cells show toroidal neighbors of $(1, 2)$.}\n\\end{center}\n\nIs it possible to color all cells with the pigments provided and create a beautiful picture?",
    "tutorial": "The picture must consist of some stripes with at least $2$ rows or at least $2$ columns. When $n$ is odd and all $\\lfloor \\frac{a_i}{m} \\rfloor=2$, we cannot draw a beautiful picture using row stripes. Let's first prove hint1 first. If there is a pair of toroidal neighbors with different colors. For example, $col_{x,y}=a$ and $col_{x+1,y}=b(a\\neq b)$. Then we will find $col_{x-1,y}=col_{x,y+1}=col_{x,y-1}=a$,$col_{x+2,y}=col_{x+1,y+1}=col_{x+1,y-1}=b$ must hold. Then we find another two pairs of toroidal neighbors $col_{x,y+1},col_{x+1,y+1}$ and $col_{x,y-1},col_{x+1,y-1}$. Repeat such process, we will find the boundary should be like: Similar, the boundaries can be vertical lines, but horizontal lines and vertical lines can not exist in one picture. So the pattern should be row stripes all with at least $2$ rows or column stripes all with at least $2$ columns. Check if one can draw a beautiful picture with row stripes only or with column stripes only. We consider only the case of row stripes, the reasoning is analogous for column stripes. If it is possible, then $\\sum_{a_i \\geq 2m} \\lfloor \\frac{a_i}{m} \\rfloor \\geq n$ must hold. If $n$ is even, then such a condition is enough. If $n$ is odd, there must be some $\\lfloor \\frac{a_i}{m} \\rfloor \\geq 3$. In this case, you can draw a beautiful picture using such algorithm: Sort $a_i$ from large to small. Sort $a_i$ from large to small. Draw $2$ rows stripes of each color if possible. Draw $2$ rows stripes of each color if possible. If the picture still has some rows empty, insert new rows into each stripe. If the picture still has some rows empty, insert new rows into each stripe. Total time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define MAXN 100010\nint n,m,k;\nint a[MAXN];\nvoid work()\n{\n\tcin>>n>>m>>k;\n\tfor (int i=1;i<=k;i++)\n\t\tcin>>a[i];\n\tbool flag;\n\tlong long tot=0;\n\tflag=0;\n\ttot=0;\n\tfor (int i=1;i<=k;i++)\n\t{\n\t\tif (a[i]/n>2)\n\t\t\tflag=1;\n\t\tif (a[i]/n>=2)\n\t\t\ttot+=a[i]/n;\n\t}\n\tif (tot>=m && (flag || m%2==0))\n\t{\n\t\tcout<<\"Yes\"<<endl;\n\t\treturn ;\n\t}\n\tflag=0;\n\ttot=0;\n\tfor (int i=1;i<=k;i++)\n\t{\n\t\tif (a[i]/m>2)\n\t\t\tflag=1;\n\t\tif (a[i]/m>=2)\n\t\t\ttot+=a[i]/m;\n\t}\n\tif (tot>=n && (flag || n%2==0))\n\t{\n\t\tcout<<\"Yes\"<<endl;\n\t\treturn ;\n\t}\n\tcout<<\"No\"<<endl;\n\n}\n\nint main()\n{\n\tint casenum=1;\n\tcin>>casenum;\n\tfor (int testcase=1;testcase<=casenum;testcase++)\n\t\twork();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1710",
    "index": "B",
    "title": "Rain",
    "statement": "You are the owner of a harvesting field which can be modeled as an infinite line, whose positions are identified by integers.\n\nIt will rain for the next $n$ days. On the $i$-th day, the rain will be centered at position $x_i$ and it will have intensity $p_i$. Due to these rains, some rainfall will accumulate; let $a_j$ be the amount of rainfall accumulated at integer position $j$. Initially $a_j$ is $0$, and it will increase by $\\max(0,p_i-|x_i-j|)$ after the $i$-th day's rain.\n\nA flood will hit your field if, at any moment, there is a position $j$ with accumulated rainfall $a_j>m$.\n\nYou can use a magical spell to erase \\textbf{exactly one} day's rain, i.e., setting $p_i=0$. For each $i$ from $1$ to $n$, check whether in case of erasing the $i$-th day's rain there is no flood.",
    "tutorial": "The maximum can always be achieved in the center position of one day's rain. $a_i$ is a piecewise linear function and the slope of $a_i$ will only change for $O(n)$ times. Supposing you know an invalid position $j$ where $a_j>m$, what are the properties of a rain that, if erase, makes it valid? Let's call position $j$ a key position if it is the center position of a rain. i.e. there exists $i$ so that $x_i=j$. You can calculate $a_j$ for all key positions $j$ using the difference array. Let $d^{1}_{j}=a_{j}-a_{j-1}$, $d^{2}_{j}=d^{1}_{j}-d^{1}_{j-1}$, then the $i$-th day's rain will change it as follows: $d^{2}_{x_i-p_i+1} \\leftarrow d^{2}_{x_i-p_i+1}+1$ $d^{2}_{x_i+1} \\leftarrow d^{2}_{x_i+1}-2$ $d^{2}_{x_i+p_i+1} \\leftarrow d^{2}_{x_i+p_i+1}+1$ This can be calculated efficiently using prefix sums. We say that a position $j$ is valid if $a_j\\le m$. Now, consider an invalid position $j$; erasing the $i$-th day's rain will make it valid if and only if $p_i-|x_i-j| \\geq a_j-m$. One can check that the region of $(x, p)$ satisfying such an inequality is a quadrant rotated $45^\\circ$ anticlockwise and translated. And in particular, even the intersections of two such regions have the same structure and can be computed easily (to avoid using floating point numbers, one can multiply all $x_i,p_i$ by $2$). In the end, for each $i$, you only need to check whether point $(x_i,p_i)$ belongs to such region. Total time complexity: $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\n#define MAXN 200100\n#define LL long long\nusing namespace std;\n\ntypedef pair<LL,LL> pll;\nLL n,m;\nLL x[MAXN],p[MAXN];\nvector<pll> diff;\npll key;\n\npll getIntersection(pll p1,pll p2)\n{\n\tLL tx=max(p1.first+p1.second,p2.first+p2.second);\n\tLL ty=max(p1.second-p1.first,p2.second-p2.first);\n\treturn {(tx-ty)/2,(tx+ty)/2};\n}\n\nvoid work()\n{\n\tdiff.clear();\n\tkey={0,-0x3f3f3f3f3f3f3f3f};\n\tcin>>n>>m;\n\tm*=2;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tcin>>x[i]>>p[i];\n\t\tx[i]*=2;\n\t\tp[i]*=2;\n\t\tdiff.push_back({x[i]-p[i],1});\n\t\tdiff.push_back({x[i],-2});\n\t\tdiff.push_back({x[i]+p[i],1});\n\t}\n\tsort(diff.begin(), diff.end());\n\tLL a=0,d=0;\n\tLL lst=0;\n\tfor (auto p:diff)\n\t{\n\t\tif (p.first!=lst)\n\t\t{\n\t\t\ta=a+(p.first-lst)*d;\n\t\t\tlst=p.first;\n\t\t\tif (a>m)\n\t\t\t\tkey=getIntersection(key,{p.first,a-m});\n\t\t}\n\t\td+=p.second;\n\t}\n\tfor (int i=1;i<=n;i++)\n\t\tif (getIntersection(key,{x[i],p[i]})==pll(x[i],p[i]))\n\t\t\tcout<<'1';\n\t\telse\n\t\t\tcout<<'0';\n\tcout<<endl;\n}\n\nint main()\n{\n\tint casenum=1;\n\tcin>>casenum;\n\tfor (int testcase=1;testcase<=casenum;testcase++)\n\t\twork();\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "geometry",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1710",
    "index": "C",
    "title": "XOR Triangle",
    "statement": "You are given a positive integer $n$. Since $n$ may be very large, you are given its binary representation.\n\nYou should compute the number of triples $(a,b,c)$ with $0 \\leq a,b,c \\leq n$ such that $a \\oplus b$, $b \\oplus c$, and $a \\oplus c$ are the sides of a non-degenerate triangle.\n\nHere, $\\oplus$ denotes the bitwise XOR operation.\n\nYou should output the answer modulo $998\\,244\\,353$.\n\nThree positive values $x$, $y$, and $z$ are the sides of a non-degenerate triangle if and only if $x+y>z$, $x+z>y$, and $y+z>x$.",
    "tutorial": "Consider the same bit of three integers at the same time. $a\\bigoplus b \\leq a+b$ Define $cnt_{i_1 i_2 i_3}$ as: $j$th bit of $cnt_{i_1 i_2 i_3}$ is $1$ iif $i_1=a_j,i_2=b_j,i_3=c_j$ e.g. $a=(10)_2,b=(11)_2,c=(01)_2$ then $cnt_{110}=(10)_2,cnt_{011}=(01)_2$, other $cnt$ is 0. $a=cnt_{100}+cnt_{101}+cnt_{110}+cnt_{111}$ $b=cnt_{010}+cnt_{011}+cnt_{110}+cnt_{111}$ $c=cnt_{001}+cnt_{011}+cnt_{101}+cnt_{111}$ $a\\bigoplus b = cnt_{010}+cnt_{011}+cnt_{100}+cnt_{101}$ $a\\bigoplus c = cnt_{001}+cnt_{011}+cnt_{100}+cnt_{110}$ $b\\bigoplus c = cnt_{001}+cnt_{010}+cnt_{101}+cnt_{110}$ $a\\bigoplus b + a\\bigoplus c > b \\bigoplus c \\iff cnt_{011}+cnt_{100}>0$ similar: $cnt_{101}+cnt_{010}>0$ $cnt_{110}+cnt_{001}>0$ then we use digit dp: $dp[n][i][j]$ means when we consider first $n$ bits, state of reaching the upper bound is $i$, state of conditions is $j$. Enumerate $a_j b_j c_j$ for $j$ from $|n|-1$ to $0$ and make transition. Time complexity is $O(2^9 |n|)$ where $|n|$ is the length of input.",
    "code": "#include <bits/stdc++.h>\n#define MAXN 200100\n#define LL long long\n#define MOD 998244353\nusing namespace std;\n\nLL dp[MAXN][8][8];\nstring s;\nint main()\n{\n\tcin>>s;\n\tdp[0][0][0]=1;\n\tfor (int i=0;i<s.size();i++)\n\t\tfor (int mask1=0;mask1<8;mask1++)\n\t\t\tfor (int mask2=0;mask2<8;mask2++)\n\t\t\t{\n\t\t\t\tdp[i][mask1][mask2]%=MOD;\n\t\t\t\tfor (int m=0;m<8;m++)\n\t\t\t\t{\n\t\t\t\t\tbool flag=false;\n\t\t\t\t\tfor (int j=0;j<3;j++)\n\t\t\t\t\t\tif (s[i]=='0' && (mask2>>j)%2==0 && (m>>j)%2==1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflag=true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tif (flag)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tint tmpmask1=mask1;\n\t\t\t\t\tint tmpmask2=mask2;\n\t\t\t\t\tfor (int j=0;j<3;j++)\n\t\t\t\t\t\tif (s[i]-'0'!=((m>>j)&1))\n\t\t\t\t\t\t\ttmpmask2|=(1<<j);\n\t\t\t\t\tfor (int j=0;j<3;j++)\n\t\t\t\t\t\tif (m==(1<<j) || m==7-(1<<j))\n\t\t\t\t\t\t\ttmpmask1|=(1<<j);\n\t\t\t\t\tdp[i+1][tmpmask1][tmpmask2]+=dp[i][mask1][mask2];\n\t\t\t\t}\n\t\t\t}\n\tLL ans=0;\n\tfor (int i=0;i<8;i++)\n\t\tans+=dp[s.size()][7][i];\n\tcout<<ans%MOD<<endl;\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1710",
    "index": "D",
    "title": "Recover the Tree",
    "statement": "Rhodoks has a tree with $n$ vertices, but he doesn't remember its structure. The vertices are indexed from $1$ to $n$.\n\nA segment $[l,r]$ ($1 \\leq l \\leq r \\leq n$) is good if the vertices with indices $l$, $l + 1$, ..., $r$ form a connected component in Rhodoks' tree. Otherwise, it is bad.\n\nFor example, if the tree is the one in the picture, then only the segment $[3,4]$ is bad while all the other segments are good.\n\nFor each of the $\\frac{n(n+1)}{2}$ segments, Rhodoks remembers whether it is good or bad. Can you help him recover the tree? If there are multiple solutions, print any.\n\nIt is guaranteed that the there is at least one tree satisfying Rhodoks' description.",
    "tutorial": "Thank dario2994, the key part of the proof is from him. If interval $A,B$ are all good and $A \\cap B \\neq \\emptyset$, then $A \\cap B$ is good, too. If interval $A,B$ are all good and $A \\cap B \\neq \\emptyset$, then $A \\cup B$ is good, too. Consider enumerating good intervals according to their length. Let's consider the interval in the order of its length (small to large) and add the edge one by one. Initially, the graph has no edge. There are $n$ connected components each consisting of exactly one vertex. Note our algorithm will guarantee that at every moment every connected component's indices compose an interval. Let $[L_i,R_i]$ be the connected component vertex $i$ in. If $[x,y]$ is good and $x$ and $y$ are not in the same connected component, we can merge $[L_x,R_y]$ into a larger connected component. Supposing $[L_x,R_y]$ consist of $k+2$ connected components now, let's call them $[l_0,r_0],[l_1,r_1],\\cdots,[l_{k+1},r_{k+1}](x\\in [l_0,r_0],y\\in [l_{k+1},r_{k+1}])$, you can link edges like: $\\cdots-l_4-l_2-x-y-l_1-l_3-\\cdots$ If $[x,y]$ is good and $x$ and $y$ are in the same connected component, then we do nothing. Finally, you will get a valid tree. Total time complexity: $O(n^2)$. Let $ans[x][y]$ be if interval $[x,y]$ is good as the input data demands. Let $res[x][y]$ be if interval $[x,y]$ is good in our answer tree. Assume that the intervals we have considered are consistent with the input and we are considering $[x,y]$. Let's first prove if $ans[x][y]=1$ then $res[x][y]=1$. If interval $x,y$ are in different connected components when $[x,y]$ is enumerated. The edge-link method will ensure $[x,y]$ is good in our answer tree. If interval $x,y$ are in the same connected components when $[x,y]$ is enumerated. Since $[x,y]$ has been merged into a larger connected component, then there must be a series of good intervals: $I_1,I_2,\\cdots,I_k,I_{i+1} \\cap I_i \\neq \\emptyset,I_i \\cap [x,y] \\neq \\emptyset, [x,y] \\subset \\cup I_i$ Let $J_i=I_i \\cap [x,y]$ Then according to hint1, all $J_i$ is good. $J_{i+1} \\cap J_i \\neq \\emptyset, \\cup J_i =[x,y]$ Then we know $[x,y]$ is good in our tree, too. Let's then prove if $ans[x][y]=0$ then $res[x][y]=0$. Assume that we are processing the interval $[x, y]$ and up to now we did not create an invalid interval. I will prove that even after \"connecting\" $[x, y]$ it still remains true that bad intervals are not connected. Let $I=[a,b]$ not be connected before performing the operation on $[x, y]$ and become connected later. Let CC be \"connected component\". Case1: $I$ does not contain $x$ or does not contain $y$, and at least one of $a,b$ is in $(R_x,L_y)$. When $a,b$ are in different CC, $I$ does not contain both of $x$ and $y$ while they are the key vertices to walk from CC $i$ to CC $i+1$. When $a,b$ are in the same CC, the link will have no influence on its connectivity. Case2: $I$ contains $[x,y]$. If $[a,b]$ becomes connected after the linking, since we only add edges in $[x,y]$, $[a,x]$ and $[y,b]$ must be connected. Since $[a,x],[x,y],[y,b]$ are all good, $[a,b]$ is good and we are happy. case3: $b \\leq R_x$ or $a \\geq L_y$. $I$'s connectivity will not be influenced. The proof is rather long and hard, and if you have some better ideas please share them.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define MAXN 5100\ntypedef pair<int,int> pii;\nint n;\nchar good[MAXN][MAXN];\nint lv[MAXN],rv[MAXN];\nvector<pii> ans;\n\n\nvoid work()\n{\n\tans.clear();\n\tcin>>n;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tlv[i]=rv[i]=i;\n\t\tcin>>(good[i]+i);\n\t}\n\tfor (int len=2;len<=n;len++)\n\t\tfor (int l=1;l<=n+1-len;l++)\n\t\t{\n\t\t\tint r=l+len-1;\n\t\t\tif (good[l][r]=='1' && lv[l]!=lv[r] && rv[l]!=rv[r])\n\t\t\t{\n\t\t\t\tans.push_back({l,r});\n\t\t\t\tvector<int> tmp[2];\n\t\t\t\tint id=1;\n\t\t\t\ttmp[0].push_back({l});\n\t\t\t\ttmp[1].push_back({r});\n\t\t\t\tfor (int i=rv[l]+1;i<lv[r];i++)\n\t\t\t\t\tif (lv[i]==i)\n\t\t\t\t\t{\n\t\t\t\t\t\tans.push_back({tmp[id].back(),i});\n\t\t\t\t\t\ttmp[id].push_back(i);\n\t\t\t\t\t\tid^=1;\n\t\t\t\t\t}\n\t\t\t\tint lm=lv[l];\n\t\t\t\tint rm=rv[r];\n\t\t\t\tfor (int i=lm;i<=rm;i++)\n\t\t\t\t{\n\t\t\t\t\tlv[i]=lm;\n\t\t\t\t\trv[i]=rm;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tfor (auto p:ans)\n\t\tcout<<p.first<<' '<<p.second<<endl;\n}\n\nint main()\n{\n\tint casenum=1;\n\tcin>>casenum;\n\tfor (int testcase=1;testcase<=casenum;testcase++)\n\t\twork();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1710",
    "index": "E",
    "title": "Two Arrays",
    "statement": "You are given two arrays of integers $a_1,a_2,\\dots,a_n$ and $b_1,b_2,\\dots,b_m$.\n\nAlice and Bob are going to play a game. Alice moves first and they take turns making a move.\n\nThey play on a grid of size $n \\times m$ (a grid with $n$ rows and $m$ columns). Initially, there is a rook positioned on the first row and first column of the grid.\n\nDuring her/his move, a player can do one of the following two operations:\n\n- Move the rook to a \\textbf{different} cell on the same row or the same column of the current cell. A player cannot move the rook to a cell that has been visited $1000$ times before (i.e., the rook can stay in a certain cell at most $1000$ times during the entire game). Note that the starting cell is considered to be visited once at the beginning of the game.\n- End the game immediately with a score of $a_r+b_c$, where $(r, c)$ is the current cell (i.e., the rook is on the $r$-th row and $c$-th column).\n\nBob wants to maximize the score while Alice wants to minimize it. If they both play this game optimally, what is the final score of the game?",
    "tutorial": "Since they are very smart, they know the result of the game at the beginning. If the result is $x$, then Alice will end the game when Bob moves to a cell with score less than $x$, and something analogous holds for Bob. Thus, Alice can only move to a certain subset of cells, and the same holds for Bob. Knowing the above facts, it is clear that we can apply binary search on the answer $Z$, which is less than $a_1+b_1$, or Alice can end the game immediately to get $a_1+b_1$. Let's color white all the cells with $a_r+b_c \\leq Z$, and black all the cells with $a_r+b_c > Z$. Then we shall add edges between cells in the same row or same column with different colors. These edges and cells form a bipartite graph. Consider the game on the bipartite graph. Initially, we are at cell $(1,1)$. Alice moves first, then they take turns to move. Each player can only move the cell to another place with an edge connecting them, or the other player will end the game immediately. Each cell can be visited at most $1000$ times, whoever cannot move loses. If Alice wins, then the answer is no greater than $Z$, otherwise, the answer is greater than $Z$. The version of this game where each vertex can be visited exactly once is known. If both players play optimally, the first player wins iff the starting vertex belongs to all possible maximum matchings. I'll explain why at the end of the editorial. It turns out that the condition is exactly the same even if each vertex can be visited at most $1000$ times. Let us show why. First, calculate the maximum matching. Then we erase the starting vertex and calculate the maximum matching in the new graph. If two matchings have the same size, the vertex does not belong to all maximum matchings and vice versa. Now, we know that if we copy a cell $1000$ times and copy the edges as well, this problem is exactly the same as the model mentioned above. If we consider the initial bipartite graph, it's easy to see that we only need to check whether $(1,1)$ is in all maximum matchings of the initial graph, because the maximum matching remains unchanged in the other $999$ parts. So, we have shifted the problem to see if the initial cell belongs to all matchings. According to [Kőnig's theorem in graph theory](https://en.wikipedia.org/wiki/K%C5%91nig%27s_theorem_(graph_theory)), the size of the maximum matching is equal to the size of the minimum vertex cover. And if you erase all vertices in the minimum vertex cover, you get an independent set, which is the maximum independent set. Using $M$ to refer to the maximum matching, $I$ to refer to the maximum independent set, $V$ to refer to the set of vertices, we know that $|M|+|I|=|V|$ So, if we erase one vertex and $|M|$ remains unchanged, then $|I|$ must be changed and vice versa. Now our issue is to calculate the maximum independent set in this graph, with or without the initial cell. Let us sort $a_i$ and $b_i$ (notice that reordering rows and columns do not change the game at all). Now the white cells form a \"decreasing histogram\". We can still find the starting cell $(va,vb)$. First, let's compute the maximum independent set with the initial cell. Before that, consider the following constraints: It's obvious that one column has at most one color of its cells in the independent set(we shall call it $I$), so does a row. Let's call a column white if only white cells of it are in $I$, otherwise, we shall call it black. What is the maximum size of $I$, when we must have $i$ white columns and $j$ white rows? The answer is simple. We shall select the first $i$ columns to be white and the first $j$ rows to be white, the rest of the columns and rows to be black. Then the independent set consists of black cells on black rows and black columns, and white cells on white columns and white rows. It's easy to prove this greedy strategy is correct. Now we fix the number of white columns as $i$, and try to find a $j$ that maximizes $|I|$. If we make an array $da[i]$ satisfying $a_i+b_{da[i]}\\leq Z$ and $a_i + b_{da[i]+1} > Z$, and a similar array $db[j]$, we can easily calculate the change of $|I|$ when we turn row $j$ from black to white and vice versa, which is $n-max(i,db[j])-min(i,db[j])$, $-min(i,db[j])$ means remove the white part from $I$, $+n-max(i,db[j])$ means add the black part to $I$. For a fixed $i$, it's easy to see that the change increases with $j$. So you can maintain all positive changes of $|I|$, just decrease the $j$ with $i$ decreasing. Now you can calculate the maximum of $|I|$ in $O(n+m)$ time. It's easy to see that $da[i]$ and $db[i]$ are non-increasing, so they can be calculated in $O(n+m)$ time. For the maximum independent set without the initial cell, you just need to remove it when it is in $I$. Since the cell is always black, it is quite easy. Using binary search on the answer, you can solve the whole problem in $O((n+m)\\log A+n\\log n+m\\log m)$, where $A$ is the maximum value of the arrays $a$ and $b$. Let us conclude with the idea of the known game on bipartite graphs. \\textbf{Lemma}: The first player can win if and only if all possible maximum matchings include the initial vertex $H$. Let's prove it when $H$ satisfies the constraint. The first player can just choose any matching $M$ and move to the vertex $P$ matching with current vertex, then any unvisited neighbor of $P$ still matches with other unvisited vertices. If $P$ has a neighbor unmatched in a certain matching $M$, we find an augmenting path and a matching $M'$ that doesn't include $H$, which is in conflict with the constraint. So no matter how the second player chooses to move, the first player always has a vertex to go after that. Otherwise, we add a vertex $P$ with the only edge $(P,H)$, move the initial cell to $P$, swap the two players, then it turns into the situation above.",
    "code": "#include <bits/stdc++.h>\n\nusing ll=long long;\nusing std::cin;\nusing std::cerr;\nusing std::cout;\nusing std::min;\nusing std::max;\n\ntemplate<class T>\nvoid ckmx(T &A,T B){\n\tA<B?A=B:B;\n}\n\nconst int N=2e5+7;\n\nint n,m,va,vb;\nint a[N],b[N];\nint da[N],db[N];\n\nbool check(int x){\n\tll sm=0,f1=0,f2=0;\n\tfor(int j=m,i=0;j>=1;--j){\n\t\twhile(i<n&&a[i+1]+b[j]<=x)\n\t\t\t++i;\n\t\tdb[j]=i;\n\t\tsm+=db[j];\n\t}\n\tfor(int i=n,j=0;i>=1;--i){\n\t\twhile(j<m&&a[i]+b[j+1]<=x)\n\t\t\t++j;\n\t\tda[i]=j;\n\t}\n\tf1=f2=sm;\n\tfor(int i=n,j=m;i>=1;--i){\n\t\tsm-=min(j,da[i]);\n\t\tsm+=m-max(j,da[i]);\n\t\tckmx(f1,sm);\n\t\tckmx(f2,sm-(i<=va&&j<vb));\n\t\twhile(j&&min(db[j],i-1)<=n-max(db[j],i-1)){\n\t\t\tsm-=min(db[j],i-1);\n\t\t\tsm+=n-max(db[j],i-1);\n\t\t\t--j;\n\t\t\tckmx(f1,sm);\n\t\t\tckmx(f2,sm-(i<=va&&j<vb));\n\t\t}\n\t}return f1==f2;\n}\n\nvoid Main(){\n\tcin>>n>>m;\n\tfor(int i=1;i<=n;++i)\n\t\tcin>>a[i];\n\tfor(int j=1;j<=m;++j)\n\t\tcin>>b[j];\n\tva=a[1],vb=b[1];\n\tstd::sort(a+1,a+n+1);\n\tstd::sort(b+1,b+m+1);\n\tint l=a[1]+b[1],r=va+vb;\n\tva=std::lower_bound(a+1,a+n+1,va)-a;\n\tvb=std::lower_bound(b+1,b+m+1,vb)-b;\n\twhile(l<r){\n\t\tint mid=(l+r)>>1;\n\t\tif(check(mid))\n\t\t\tr=mid;\n\t\telse \n\t\t\tl=mid+1;\n\t}cout<<l<<\"\\n\";\n}\n\ninline void File(){\n\tcin.tie(nullptr)->sync_with_stdio(false);\n#ifdef zxyoi\n\tfreopen(\"my.in\",\"r\",stdin);\n#endif\n}signed main(){File();Main();return 0;}",
    "tags": [
      "binary search",
      "games",
      "graph matchings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1711",
    "index": "A",
    "title": "Perfect Permutation",
    "statement": "You are given a positive integer $n$.\n\nThe weight of a permutation $p_1, p_2, \\ldots, p_n$ is the number of indices $1\\le i\\le n$ such that $i$ divides $p_i$. Find a permutation $p_1,p_2,\\dots, p_n$ with the minimum possible weight (among all permutations of length $n$).\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "The minimal weight is at least $1$ since $1$ divides any integer (so $1$ divides $p_1$). Since $k+1$ does not divide $k$, a permutation with weight equal to $1$ is: $[n,1,2,\\cdots,n-1]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nvoid work()\n{\n\tint n;\n\tcin>>n;\n\tcout<<n<<' ';\n\tfor (int i=1;i<n;i++)\n\t\tcout<<i<<' ';\n\tcout<<endl;\n}\n\nint main()\n{\n\tint casenum=1;\n\tcin>>casenum;\n\tfor (int testcase=1;testcase<=casenum;testcase++)\n\t\twork();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1711",
    "index": "B",
    "title": "Party",
    "statement": "A club plans to hold a party and will invite some of its $n$ members. The $n$ members are identified by the numbers $1, 2, \\dots, n$. If member $i$ is not invited, the party will gain an unhappiness value of $a_i$.\n\nThere are $m$ pairs of friends among the $n$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.\n\nHowever, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.\n\nWhat is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even?",
    "tutorial": "See the party as a graph. Divide the vertices into two categories according to their degrees' parity. Let's consider the case where $m$ is odd only, since if $m$ is even the answer is $0$. Assume that you delete $x$ vertices with even degrees and $y$ vertices with odd degrees. If $y \\geq 1$, then only deleting one vertex with an odd degree would lead to a not worse answer, so you do not need to consider it except for $(x,y)=(0,1)$. If $y=0$, then the parity of the edges at the end is determined only by the number of edges whose both endpoints are deleted. In particular, there must be at least two adjacent vertices deleted with even degrees. So you do not need to consider it except for $(x,y)=(2,0)$ and they are neighbours. Thus, an optimal solution either has $(x, y) = (0, 1)$ or $(x, y) = (2, 0)$ and the two vertices are adjacent. One can iterate over all possible solutions with such a structure and take the optimal one. Total time complexity: $O(n+m)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define MAXN 100010\nint x[MAXN],y[MAXN],a[MAXN],degree[MAXN];\nint n,m;\nvoid work()\n{\n\tcin>>n>>m;\n\tfor (int i=1;i<=n;i++)\n\t{\n\t\tdegree[i]=0;\n\t\tcin>>a[i];\n\t}\n\tfor (int i=1;i<=m;i++)\n\t{\n\t\tcin>>x[i]>>y[i];\n\t\tdegree[x[i]]++;\n\t\tdegree[y[i]]++;\n\t}\n\tint ans=INT_MAX;\n\tif (m%2==0)\n\t\tans=0;\n\tfor (int i=1;i<=n;i++)\n\t\tif (degree[i]%2==1)\n\t\t\tans=min(ans,a[i]);\n\tfor (int i=1;i<=m;i++)\n\t\tif (degree[x[i]]%2==0 && degree[y[i]]%2==0)\n\t\t\tans=min(ans,a[x[i]]+a[y[i]]);\n\tcout<<ans<<endl;\n}\n\nint main()\n{\n\tint casenum=1;\n\tcin>>casenum;\n\tfor (int testcase=1;testcase<=casenum;testcase++)\n\t\twork();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "graphs"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1712",
    "index": "A",
    "title": "Wonderful Permutation",
    "statement": "\\begin{quote}\nGod's Blessing on This PermutationForces!\n\\hfill A Random Pebble\n\\end{quote}\n\nYou are given a permutation $p_1,p_2,\\ldots,p_n$ of length $n$ and a positive integer $k \\le n$.\n\nIn one operation you can choose two indices $i$ and $j$ ($1 \\le i < j \\le n$) and swap $p_i$ with $p_j$.\n\nFind the minimum number of operations needed to make the sum $p_1 + p_2 + \\ldots + p_k$ as small as possible.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "For any permutation $p$ of length $n$, the final sum $p_1 + p_2 + \\ldots + p_k$ after some number of operations can't be less than $1 + 2 + \\ldots + k$. This means that we need to apply the operation at least once for every $i$ such that $1 \\le i \\le k$ and $p_i > k$. Every time we apply it, we have to choose some index $j$ such that $k < j \\le n$ and $p_j \\le k$. This is always possible since initially the number of suitable $i$ is equal to the number of suitable $j$, and one operation decreases both the number of suitable $i$ and the number of suitable $j$ by one. It is easy to see that in the end, the set $\\{p_1, p_2, \\ldots, p_k \\}$ only contains the values $\\{1, 2, \\ldots , k \\}$, which means that the sum is equal to $1 + 2 + \\ldots + k$, which is the smallest sum we can get. So the answer is the the number of $i$ such that $1 \\le i \\le k$ and $p_i > k$. Complexity: $\\mathcal{O}(n)$ Bonus: solve for every $k$ from $1$ to $n$ for $n \\le 10^5$.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tint n, k;\n\t\tcin >> n >> k;\n\t\tvector<int> a(n);\n\t\tfor (int i = 0; i < n; i++) cin >> a[i];\n\t\t\n\t\tvector<int> b = a;\n\t\tsort(all(b));\n\t\tint x = b[k - 1];\n\t\t\n\t\tint ans = 0;\n\t\tfor (int i = 0; i < k; i++) {\n\t\t\tif (a[i] > x) ans++;\n\t\t}\n\t\tcout << ans << nl;\n\t}\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1712",
    "index": "B",
    "title": "Woeful Permutation",
    "statement": "\\begin{quote}\nI wonder, does the falling rain\n\\end{quote}\n\n\\begin{quote}\nForever yearn for it's disdain?\n\\hfill Effluvium of the Mind\n\\end{quote}\n\nYou are given a positive integer $n$.\n\nFind any permutation $p$ of length $n$ such that the sum $\\operatorname{lcm}(1,p_1) + \\operatorname{lcm}(2, p_2) + \\ldots + \\operatorname{lcm}(n, p_n)$ is as large as possible.\n\nHere $\\operatorname{lcm}(x, y)$ denotes the least common multiple (LCM) of integers $x$ and $y$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "A well know fact is that $\\gcd(a,b) \\cdot \\operatorname{lcm}(a,b) = a \\cdot b$ for any two positive integers $a$ and $b$. Since $\\gcd(x, x + 1) = 1$ for all positive $x$, we get that $\\operatorname{lcm}(x,x+1) = x \\cdot (x + 1)$. All of this should hint that for even $n$, the optimal permutation looks like this: $2,1,4,3,\\ldots,n,n-1$. Add for odd $n$, it looks like this: $1,3,2,5,4,\\ldots,n,n-1$. Complexity: $\\mathcal{O}(n)$ Turns out the formal proof is pretty hard. You are welcome to try and find something simpler. Define $f(x, y)$ as $x \\cdot y$ if $x \\ne y$, and $x$ otherwise. It is easy to see that $\\operatorname{lcm}(x, y) \\le f(x, y)$. We will find the maximum possible value of $f(1, p_1) + \\ldots f(n, p_n)$ and show that it is reached by our construction. Suppose we want to solve this problem: find the max possible value of $1 \\cdot p_1 + \\ldots + n \\cdot p_n$, if for all $i > 1$, $p_i \\ne i$. This is equivalent to maximizing $f(1, p_1) + \\ldots f(n, p_n)$, because if there is such an index $i$, it is always optimal to swap $p_i$ with $p_j$ for any $1 \\le j < i$. Let's build a graph on this permutation with n vertices and add all edges $i \\rightarrow p_i$. Except for maybe $p_1 = 1$, all the other cycles have a length of at least 2. Let's look at one such cycle $x_1, x_2, \\ldots, x_k$. The optimal value with no restrictions on the value of $p_i$ would be $x_1^2 + x_2^2 + \\ldots + x_k^2$, but right now we have $x_1 \\cdot x_2 + x_2 \\cdot x_3 + \\ldots + x_k \\cdot x_1$. Subtracting one from the other: $x_1^2 + x_2^2 + \\ldots + x_k^2 - (x_1 \\cdot x_2 + x_2 \\cdot x_3 + \\ldots + x_k \\cdot x_1) =$ $= \\frac{x_1^2}{2} - x_1 \\cdot x_2 + \\frac{x_2^2}{2} + \\frac{x_2^2}{2} - x_2 \\cdot x_3 + \\frac{x_3^2}{2} + \\ldots + \\frac{x_k^2}{2} - x_k \\cdot x_1 + \\frac{x_1^2}{2} =$ $= \\frac{(x_1 - x_2)^2 + (x_2 - x_3)^2 + \\ldots + (x_k - x_1)^2}{2} \\ge$ $\\ge \\frac{|x_1 - x_2| + |x_2 - x_3| \\ldots + |x_k - x_1|}{2} \\ge$ $\\ge \\max(x_1 \\ldots x_k) - \\min(x_1 \\ldots x_k)$ So we need to minimize the sum of $\\max(x_1 \\ldots x_k) - \\min(x_1 \\ldots x_k)$ over all cycles. If $n$ is even, it is easy to see the minimum possible value of this is $\\frac{n}{2}$, and it doesn't matter what $p_1$ equals to. For odd $n$ we have to look at two cases: $p_1 = 1$ and $p_1 \\ne 1$. In the first case, the minimum possible sum is $\\frac{n - 1}{2}$, in the second case, it is $\\frac{n + 1}{2}$, which is worse that in the previous case. Returning to the original problem, our constructions also achieve this minimal difference from $1^2 + 2^2 + \\ldots n$ even when we change $f$ back into $\\operatorname{lcm}$, so they are optimal. Bonus: try to prove the solution without the editorial!",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tif (n % 2 == 0) {\n\t\t\tfor (int i = 1; i <= n; i += 2) {\n\t\t\t\tcout << i + 1 << ' ' << i << ' ';\n\t\t\t}\n\t\t\tcout << nl;\n\t\t} else {\n\t\t\tcout << 1 << ' ';\n\t\t\tfor (int i = 2; i <= n; i += 2) {\n\t\t\t\tcout << i + 1 << ' ' << i << ' ';\n\t\t\t}\n\t\t\tcout << nl;\n\t\t}\n\t}\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1712",
    "index": "C",
    "title": "Sort Zero",
    "statement": "\\begin{quote}\nAn array is sorted if it has no inversions\n\\hfill A Young Boy\n\\end{quote}\n\nYou are given an array of $n$ \\textbf{positive} integers $a_1,a_2,\\ldots,a_n$.\n\nIn one operation you do the following:\n\n- Choose \\textbf{any} integer $x$.\n- For all $i$ such that $a_i = x$, do $a_i := 0$ (assign $0$ to $a_i$).\n\nFind the minimum number of operations required to sort the array in non-decreasing order.",
    "tutorial": "An array is sorted in non-decreasing order if and only if there is no index $i$ such that $a_i > a_{i + 1}$. This leads to a strategy: while there is at least one such index $i$, apply one operation with $x = a_i$. Why is this optimal? Since our operation can only decrease values, and we must decrease $a_i$ so that $a_i > a_{i + 1}$ is no longer true, this leaves us no choice but to use the operation with $x = a_i$. You can simulate this strategy by maintaining a set of bad indices, since if an index $i$ becomes bad, after you apply an operation with $x = a_i$, it can never become bad again. So in total, there are at most $2 \\cdot (n - 1)$ operations with the set. Complexity: $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n)$, depending on which set you use. Note: you can solve the problem in $\\mathcal{O}(n)$ by noticing that if an index $i$ is bad, we need to apply the operation for all unique non-zero values in $\\{a_1 \\ldots a_i\\}$. This is also quite a bit shorter to code. Bonus: solve for when $a_i$ can also be negative.",
    "code": "#include <bits/stdc++.h>\n \n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n \nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n \nusing namespace std;\n \nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tint n;\n\t\tcin >> n;\n\t\t\n\t\tvector<int> a(n);\n\t\tmap<int, vector<int>> p;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> a[i];\n\t\t\tp[a[i]].push_back(i);\n\t\t}\n\t\t\n\t\tint ans = 0;\n\t\tset<int> ts;\n\t\tfor (int i = 0; i < n - 1; i++) {\n\t\t\tif (a[i] > a[i + 1]) ts.insert(i);\n\t\t}\n\t\t\n\t\twhile (!ts.empty()) {\n\t\t\tint i = *ts.begin();\n\t\t\tint x;\n\t\t\tif (a[i] > 0) {\n\t\t\t\tx = a[i];\n\t\t\t} else {\n\t\t\t\tx = a[i + 1];\n\t\t\t}\n\t\t\t\n\t\t\tfor (int j: p[x]) {\n\t\t\t\ta[j] = 0;\n\t\t\t\tts.erase(j - 1);\n\t\t\t\tts.erase(j);\n\t\t\t\tif (j > 0 && a[j - 1] > a[j]) ts.insert(j - 1);\n\t\t\t\tif (j + 1 < n && a[j] > a[j + 1]) ts.insert(j);\n\t\t\t}\n\t\t\tans++;\n\t\t}\n\t\t\n\t\tcout << ans << nl;\n\t}\n}\n",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1712",
    "index": "D",
    "title": "Empty Graph",
    "statement": "\\begin{quote}\n— Do you have a wish?\n\\end{quote}\n\n\\begin{quote}\n— I want people to stop gifting each other arrays.\n\\hfill O_o and Another Young Boy\n\\end{quote}\n\nAn array of $n$ \\textbf{positive} integers $a_1,a_2,\\ldots,a_n$ fell down on you from the skies, along with a positive integer $k \\le n$.\n\nYou can apply the following operation at most $k$ times:\n\n- Choose an index $1 \\le i \\le n$ and an integer $1 \\le x \\le 10^9$. Then do $a_i := x$ (assign $x$ to $a_i$).\n\nThen build a complete undirected \\textbf{weighted} graph with $n$ vertices numbered with integers from $1$ to $n$, where edge $(l, r)$ ($1 \\le l < r \\le n$) has weight $\\min(a_{l},a_{l+1},\\ldots,a_{r})$.\n\nYou have to find the maximum possible diameter of the resulting graph after performing at most $k$ operations.\n\nThe diameter of a graph is equal to $\\max\\limits_{1 \\le u < v \\le n}{\\operatorname{d}(u, v)}$, where $\\operatorname{d}(u, v)$ is the length of the shortest path between vertex $u$ and vertex $v$.",
    "tutorial": "First of all, we will always use the operation to assign $10^9$ to $a_i$. 1. Suppose $u < v$. Then $\\operatorname{d}(u, v) = \\min(\\min(a_u \\ldots a_v), 2 \\cdot \\min(a_1 \\ldots a_n))$. Proof: since the weight of an edge is always $\\ge \\min(a_1 \\ldots a_n)$, the best we can do with one edge is $\\min(a_u \\ldots a_v)$. And the best we can possibly do with two edges is $2 \\cdot \\min(a_1 \\ldots a_n)$, which turns out possible to achieve. Subproof: suppose $i_{min}$ is the index of one of the minimums in the array. If $u \\le i_{min} \\le v$, then $\\min(a_u \\ldots a_v)$ is optimal, so we don't need two edges in the first place. Else, either $i_{min} < u$ or $i_{min} > v$. In the first case, we can notice that $\\operatorname{d}(u, 1) + \\operatorname{d}(1, v) = 2 \\cdot \\min(a_1 \\ldots a_n)$. In the second case, $\\operatorname{d}(u, n) + \\operatorname{d}(n, v) = 2 \\cdot \\min(a_1 \\ldots a_n)$. 2. The diameter of the graph is equal to $\\max\\limits_{1 \\le i \\le n - 1}{\\operatorname{d}(i, i + 1)} = \\min \\left( \\max\\limits_{1 \\le i \\le n - 1}{\\min(a_i,a_{i+1})}, 2 \\cdot \\min(a_1 \\ldots a_n) \\right)$. Proof: since the minimum of a subsegment can only decrease when it's length increases, it is optimal to look only at the distance between two adjacent vertices. Now we can either do binary search on the answer, or we can do a clever greedy. Binary search solution: Suppose the answer is $\\ge ans$. First of all, we need to apply the operation for all $a_i < \\frac{ans}{2}$. If there are not enough operations to do this, return false. Otherwise assign $10^9$ to such $a_i$. If there are no operations left, just calculate the diameter and see if it is $\\ge ans$. If there is at least one operation left, there are two cases: $k = 1$ and $k \\ge 2$. If the first case, it is optimal to apply our operation near one of the maximums in the array to maximize $\\min(a_i, a_{i + 1})$, so we need to return true if $\\max(a_1 \\ldots a_n) \\ge ans$. With $k > 1$, it is optimal to apply the operation near an index which has been turned into $10^9$, so we always return true. Make sure to binary search on $ans$ from $1$ to $10^9$ inclusive. Doing it from $1$ to $2\\cdot 10^9$ needs another case to work. Complexity: $\\mathcal{O}(n \\log A)$. Greedy solution: We can actually maintaining the diameter of the graph while supporting point update queries (set $a_i$ to some value). To do this, we can use any structure that can get $\\max\\limits_{1 \\le i \\le n - 1}{\\min(a_i,a_{i+1})}$ (multiset, segment tree) and another structure to maintain the minimum in the array. Change the $k - 1$ smallest values in the array into $10^9$. For every $i$ from $1$ to $n$, change $a_i$ to $10^9$, get the diameter, and then change $a_i$ back to it's original value. The answer is the max value over all the returned diameters. Proof: obviously works for $k = 1$, so suppose $k \\ge 2$. Since we changed at least one value, we will check if having two adjacent $10^9$ is optimal, maximizing $\\max\\limits_{1 \\le i \\le n - 1}{\\min(a_i,a_{i+1})}$. And we will also check if we need to change the $k$-th smallest value, in this case maximizing $2 \\cdot \\min(a_1 \\ldots a_n)$. Complexity: $\\mathcal{O}(n \\log n)$ Note: it is also possible to solve without data structures by doing a bit more casework, but the solution is still $\\mathcal{O}(n \\log n)$ due to sorting. Bonus: solve for every $k$ from $1$ to $n$.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int inf = 1000000000;\n\nbool f(vector<int> a, int k, int ans) {\n\tint n = gsize(a);\n\tint dk = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (a[i] * 2 < ans) {\n\t\t\ta[i] = inf;\n\t\t\tk--;\n\t\t\tdk++;\n\t\t}\n\t}\n\t\n\tif (k < 0) return false;\n\tif ((k > 0 && dk > 0) || k >= 2) return true;\n\t\n\tif (k == 1 && dk == 0) {\n\t\treturn *max_element(all(a)) >= ans;\n\t}\n\t\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tif (min(a[i], a[i + 1]) >= ans) return true;\n\t}\n\t\n\treturn false;\n}\n\nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; i++) cin >> a[i];\n\t\n\tint lb = 0, ub = inf, tans = 0;\n\twhile (lb <= ub) {\n\t\tint tm = (lb + ub) / 2;\n\t\tif (f(a, k, tm)) {\n\t\t\ttans = tm;\n\t\t\tlb = tm + 1;\n\t\t} else {\n\t\t\tub = tm - 1;\n\t\t}\n\t}\n\t\n\tcout << tans << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tint T;\n\tcin >> T;\n\twhile (T--) solve();\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1712",
    "index": "E2",
    "title": "LCM Sum (hard version)",
    "statement": "\\begin{quote}\nWe are sum for we are many\n\\hfill Some Number\n\\end{quote}\n\n\\textbf{This version of the problem differs from the previous one only in the constraint on $t$. You can make hacks only if both versions of the problem are solved.}\n\nYou are given two positive integers $l$ and $r$.\n\nCount the number of distinct triplets of integers $(i, j, k)$ such that $l \\le i < j < k \\le r$ and $\\operatorname{lcm}(i,j,k) \\ge i + j + k$.\n\nHere $\\operatorname{lcm}(i, j, k)$ denotes the least common multiple (LCM) of integers $i$, $j$, and $k$.",
    "tutorial": "Let's count the number of bad triplets that don't satisfy the condition, i.e. $\\operatorname{lcm}(i,j,k) < i + j + k$. Then the answer for one test case is $\\frac{(r - l + 1) \\cdot (r - l) \\cdot (r - l - 1)}{6} -$ the number of bad triplets. Since $i < j < k$, a triplet is bad only when $\\operatorname{lcm}(i,j,k) = k$ or ($\\operatorname{lcm}(i,j,k) = 2 \\cdot k$ and $i + j > k$). This means that both $i$ and $j$ must be a divisor of $2\\cdot k$. For every segment $[i; k]$ where $i$ is a divisor of $2 \\cdot k$, let's count the number of $j$ such that $i < j < k$. Let's call it the weight of the segment. Turns out that for the current constraints, for every $k$, we can iterate over all pairs of $1 \\le i < j < k$, where $i$ and $j$ are divisors of $2 \\cdot k$, and check if the triplet is bad. If it is, then we increase the weight of the segment $[i; k]$ by one. To get answers for the test cases, we just need to find the sum of the weights of the segments $[i; k]$ that are inside $[l; r]$. This is a pretty standard problem, which can be solved in offline using a data structure that supports point add and range sum. It is possible to solve E1 without a data structure by iterating over the segments and checking for every one of them if it lies inside $[l; r]$. Complexity: $\\mathcal{O}(n \\log^2 n + t \\log n + \\sum_{i = 1}^n \\sigma_0(2 \\cdot i)^2)$ with a seg tree ($\\sum_{i = 1}^n \\sigma_0(2 \\cdot i)$ is about $n \\log n$ and a seg tree update works in $\\mathcal{O}(\\log n)$, so we get $n \\log^2 n$). You can also use sqrt decomposition to get $\\mathcal{O}(n \\log n + t \\sqrt n + \\sum_{i = 1}^n \\sigma_0(2 \\cdot i)^2)$. Bonus: solve the problem in $\\mathcal{O}((n + t) \\log n)$ or better.",
    "code": "#include <bits/stdc++.h>\n \n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n \nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n \nusing namespace std;\n\nconst int maxn = 200000; \n\nint t[(maxn + 1) * 4];\n\nvoid update(int v, int tl, int tr, int i, int x) {\n\tt[v] += x;\n\tif (tl != tr - 1) {\n\t\tint tm = (tl + tr) / 2;\n\t\tif (i < tm) update(2*v + 1, tl, tm, i, x);\n\t\telse update(2*v + 2, tm, tr, i, x);\n\t}\n}\n\nint query(int v, int tl, int tr, int l, int r) {\n\tif (l >= r) return 0;\n\tif (tl == l && tr == r) return t[v];\n\telse {\n\t\tint tm = (tl + tr) / 2;\n\t\tint r1 = query(2*v + 1, tl, tm, l, min(r, tm));\n\t\tint r2 = query(2*v + 2, tm, tr, max(l, tm), r);\n\t\treturn r1 + r2;\n\t}\n}\n \n \nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tvector<vector<int>> d(2*maxn + 1);\n\t\n\tfor (int i = 1; i <= maxn; i++) {\n\t\tfor (int j = i; j <= 2*maxn; j += i) {\n\t\t\td[j].push_back(i);\n\t\t}\n\t}\n\t\n\tvector<vector<pair<int, int>>> segs(maxn + 1);\n\t\n\tfor (int k = 1; k <= maxn; k++) {\n\t\tfor (int ti = 0; ti < gsize(d[2*k]); ti++) {\n\t\t\tint i = d[2*k][ti], ct = 0;\n\t\t\t\n\t\t\tfor (int tj = ti + 1; tj < gsize(d[2*k]); tj++) {\n\t\t\t\tint j = d[2*k][tj];\n\t\t\t\tif (j >= k) break;\n\t\t\t\tif (i + j > k || (k % i == 0 && k % j == 0)) ct++;\n\t\t\t}\n\t\t\t\n\t\t\tif (ct > 0)\t{\n\t\t\t\tsegs[i].emplace_back(k, ct);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\t\n\tint T;\n\tcin >> T;\n\t\n\tvector<ll> ans(T);\n\tvector<array<int, 3>> queries;\n\t\n\tfor (int i = 0; i < T; i++) {\n\t\tll l, r;\n\t\tcin >> l >> r;\n\t\tqueries.push_back({l, r, i});\n\t\tans[i] = (r - l + 1) * (r - l) * (r - l - 1) / 6;\n\t}\n\t\n\tsort(all(queries));\n\t\n\tint ti = T - 1;\n\tfor (int i = maxn; i >= 1; i--) {\n\t\t\n\t\t// Update ST\n\t\tfor (auto [r, ct]: segs[i]) {\n\t\t\tupdate(0, 0, maxn + 1, r, ct);\n\t\t}\n\t\t\n\t\t// Get Answers\n\t\twhile (ti >= 0 && queries[ti][0] == i) {\n\t\t\tans[queries[ti][2]] -= query(0, 0, maxn + 1, i, queries[ti][1] + 1);\n\t\t\tti--;\n\t\t}\n\t}\n\tfor (int i = 0; i < T; i++) cout << ans[i] << nl;\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1712",
    "index": "F",
    "title": "Triameter",
    "statement": "\\begin{quote}\n— What is my mission?\n\\end{quote}\n\n\\begin{quote}\n— To count graph diameters.\n\\hfill You and Your Submission\n\\end{quote}\n\nA tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The degree of a vertex is the number of edges connected to this vertex.\n\nYou are given a weighted tree with $n$ vertices, each edge has a weight of $1$. Let $L$ be the set of vertices with degree equal to $1$.\n\nYou have to answer $q$ \\textbf{independent} queries. In the $i$-th query:\n\n- You are given a positive integer $x_i$.\n- For all $u,v \\in L$ such that $u < v$, add edge $(u, v)$ with weight $x_i$ to the graph (initially the given tree).\n- Find the diameter of the resulting graph.\n\nThe diameter of a graph is equal to $\\max\\limits_{1 \\le u < v \\le n}{\\operatorname{d}(u, v)}$, where $\\operatorname{d}(u, v)$ is the length of the shortest path between vertex $u$ and vertex $v$.",
    "tutorial": "We will solve the problem independently $q$ times. Let $f_v$ be the distance to the closest leaf from vertex $v$, can be found using a simple bfs with multiple start sources. Let $d'(u, v)$ be the distance in the resulting graph. Then $d'(u, v) = \\min(f_u + f_v + x, d(u, v))$. A short proof: we'll either go through an edge between two leaves or we won't. In the second case, the answer is clearly $d(u, v)$. In the first case, our objective is to get to a leaf as fast as possible, use an edge with weight $x$, and then move to the destination vertex. We want to find the maximum possible value of $d'(u, v)$. As is pretty standard in tree problems, we can do small-to-large merging. Let's maintain $val[v][i] =$ the max value of $depth_u$ over all $u$ in the subtree of $v$ with $f_u = i$. We have a variable $ans$, initially $ans = 0$. For some $lca$, we will first merge all the subtrees, and then add $lca$ to the merged $val[lca]$. We will also update $ans$ during this. The final answer will be $ans - 1$. Merging two subtrees: Suppose we are merging subtree $u$ into subtree $v$, $len(val[u]) \\le len(val[v])$, with some current $lca$: First of all, iterate $i$ from $0$ to $len(val[u]) - 1$. For every $i$, do this cycle: $j = max(0, ans - i - x)$; if $j < len(val[v])$ and $val[u][i] + val[v][j] - 2 \\cdot depth_{lca} \\ge ans$, then do $ans := ans + 1$ and continue, else break and continue to the next $i$. Why does this work? Because all $val$ arrays are sorted in decreasing order. Why? Because for some vertex $v$ with $f_v > 0$, there is always a vertex $u$ in it's subtree with $depth_u > depth_v$. After we are done with that, update $val[v][i] := \\max(val[v][i], val[u][i])$ for every $i < len(val[u])$. Adding $lca$ to the merged $val[lca]$: When we are adding $lca$ to $val[lca]$, we update the answer in almost the same way, only we set $i$ to $f_{lca}$ and $val[u][i]$ to $depth_{lca}$. After that we either do $val[lca][i] := max(val[lca][i], depth_{lca})$ or if $len(val[lca]) = f_{lca}$, just append $depth_{lca}$ to the back of $val[lca]$. Complexity: This particular variant of small to large merging works in $\\mathcal{O}(n)$ since when merging two structures of size $a$ and $b$, the new size is $\\min(a, b)$. You can find the proof here. Since we increase $ans$ at most $n$ times, and we can calculate $f_v$ for all vertices in $\\mathcal{O}(n)$, the complexity is $\\mathcal{O}(n)$ per query, so $\\mathcal{O}(q \\cdot n)$ for all queries. Note that doing small-to-large merging once and updating $q$ answers simultaneously is much faster that doing small-to-large merging $q$ times. In the first case, you can even get away with using binary search to update the answer, in the second case you cannot. Bonus: solve for $n, q \\le 10^6$. Don't forget to rate the problems! Good problem 391 Mid problem 87 Bad problem 18 Good problem 334 Mid problem 104 Bad problem 52 Good problem 416 Mid problem 79 Bad problem 20 Good problem 350 Mid problem 38 Bad problem 84 Good problem 213 Mid problem 35 Bad problem 18 Good problem 152 Mid problem 13 Bad problem 23 Good problem 63 Mid problem 10 Bad problem 10 PS: Solution codes probably will be added later. UPD: explanations of the references: Hope you liked them! The quote is just a modification of the original title of KonoSuba. This is just something I invented, no reference here. Hope you liked the short poem! The quote is the meme \"people die when they are killed\" in the Fate series, changed to fit the programming context. And the title is just \"Fate Zero\" changed to \"Sort Zero\". \"Do you have a wish?\" is a recurring phrase in the LN series HakoMari, referring to the wish granting \"boxes\". The title is just \"Empty Box\" changed to \"Empty Graph\". Also, \"O_o\" is a reference to one of the main characters, \"O\". The quote can probably be traced to many origins, but I personally modified the quote \"We are legion, for we are many\" from the series 86. There were also a lot of 6's and 8's in the sample, which might have helped you guess. I didn't really think about this one, just modified a quote from Vivy a bit. UPD2: added solution codes (better late than never...)",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int maxn = 1000000;\nint f[maxn], d[maxn];\nvector<int> g[maxn], g2[maxn], val[maxn];\nint n, q;\n\nvector<int> ans, x;\n\nvoid solve() {\n\t\n\tfor (int v = n - 1; v >= 0; v--) {\n\t\tfor (int u: g[v]) {\n\t\t\tif (gsize(val[u]) > gsize(val[v])) swap(val[u], val[v]);\n\t\t\tfor (int fu = 0; fu < gsize(val[u]); fu++) {\n\t\t\t\tfor (int qi = 0; qi < q; qi++) {\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tint fv = max(0, ans[qi] - fu - x[qi]);\n\t\t\t\t\t\tif (fv < gsize(val[v]) && \n\t\t\t\t\t\t\tval[v][fv] + val[u][fu] - 2*d[v] >= ans[qi]) ans[qi]++;\n\t\t\t\t\t\telse break;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int fu = 0; fu < gsize(val[u]); fu++) {\n\t\t\t\tval[v][fu] = max(val[v][fu], val[u][fu]);\n\t\t\t}\n\t\t\tval[u].clear();\n\t\t\tval[u].shrink_to_fit();\n\t\t}\n\t\t{\n\t\t\tint fu = f[v];\n\t\t\tfor (int qi = 0; qi < q; qi++) {\n\t\t\t\twhile (true) {\n\t\t\t\t\tint fv = max(0, ans[qi] - fu - x[qi]);\t\t\t\n\t\t\t\t\tif (fv < gsize(val[v]) && \n\t\t\t\t\t\tval[v][fv] - d[v] >= ans[qi]) ans[qi]++;\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (fu == gsize(val[v])) {\n\t\t\t\tval[v].push_back(d[v]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (int i = 0; i < q; i++) {\n\t\tans[i]--;\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tcin >> n;\n\t\n\tvector<int> deg(n);\n\tfor (int i = 1; i < n; i++) {\n\t\tint p;\n\t\tcin >> p;\n\t\td[i] = d[p - 1] + 1;\n\t\tg[p - 1].push_back(i);\n\t\tg2[i].push_back(p - 1);\n\t}\n\t\n\t{\n\t\tqueue<int> qe;\n\t\tvector<bool> used(n, false);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (gsize(g2[i]) + gsize(g[i]) == 1) {\n\t\t\t\tqe.push(i);\n\t\t\t\tused[i] = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\twhile (!qe.empty()) {\n\t\t\tint v = qe.front();\n\t\t\tqe.pop();\n\t\t\tfor (int u: g[v]) {\n\t\t\t\tif (used[u]) continue;\n\t\t\t\tf[u] = f[v] + 1;\n\t\t\t\tqe.push(u);\n\t\t\t\tused[u] = true;\n\t\t\t}\n\t\t\t\n\t\t\tfor (int u: g2[v]) {\n\t\t\t\tif (used[u]) continue;\n\t\t\t\tf[u] = f[v] + 1;\n\t\t\t\tqe.push(u);\n\t\t\t\tused[u] = true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tcin >> q;\n\tfor (int i = 0; i < q; i++) {\n\t\tint tx;\n\t\tcin >> tx;\n\t\tx.push_back(tx);\n\t\tans.push_back(0);\n\t}\n\t\n\tsolve();\n\t\n\tfor (int tans: ans) cout << tans << ' ';\n\tcout << nl;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1713",
    "index": "A",
    "title": "Traveling Salesman Problem",
    "statement": "You are living on an infinite plane with the Cartesian coordinate system on it. In one move you can go to any of the four adjacent points (left, right, up, down).\n\nMore formally, if you are standing at the point $(x, y)$, you can:\n\n- go left, and move to $(x - 1, y)$, or\n- go right, and move to $(x + 1, y)$, or\n- go up, and move to $(x, y + 1)$, or\n- go down, and move to $(x, y - 1)$.\n\nThere are $n$ boxes on this plane. The $i$-th box has coordinates $(x_i,y_i)$. It is guaranteed that the boxes are either on the $x$-axis or the $y$-axis. That is, either $x_i=0$ or $y_i=0$.\n\nYou can collect a box if you and the box are at the same point. Find the minimum number of moves you have to perform to collect all of these boxes if you have to \\textbf{start and finish} at the point $(0,0)$.",
    "tutorial": "Suppose we only have boxes on the $Ox+$ axis, then the optimal strategy is going in the following way: $(0, 0), (x_{max}, 0), (0, 0)$. There is no way to do in less than $2 \\cdot |x_{max}|$ moves. What if we have boxes on two axis? Let's assume it is $Oy+$, suppose we have a strategy to go in the following way: $(0, 0), (x_{max}, 0),..., (0, y_{max}), (0, 0)$. In this case it is optimal to fill the three dots with $(0, 0)$, which is just solving each axis independently. Therefore, the number of axis does not matters. For each axis that has at least one box, go from $(0, 0)$ to the farthest one, then come back to $(0, 0)$. Time complexity: $O(n)$",
    "code": "def solve():\n    n = int(input())\n    minX, minY, maxX, maxY = 0, 0, 0, 0\n    for i in range(n):\n        x, y = list(map(int, input().split()))\n        minX = min(x, minX)\n        maxX = max(x, maxX)\n        minY = min(y, minY)\n        maxY = max(y, maxY)\n    print(2 * (maxX + maxY - minX - minY))\n\n\ntest = int(input())\nwhile test > 0:\n    test -= 1\n    solve()",
    "tags": [
      "geometry",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1713",
    "index": "B",
    "title": "Optimal Reduction",
    "statement": "Consider an array $a$ of $n$ positive integers.\n\nYou may perform the following operation:\n\n- select two indices $l$ and $r$ ($1 \\leq l \\leq r \\leq n$), then\n- decrease all elements $a_l, a_{l + 1}, \\dots, a_r$ by $1$.\n\nLet's call $f(a)$ the minimum number of operations needed to change array $a$ into an array of $n$ zeros.\n\nDetermine if for all permutations$^\\dagger$ $b$ of $a$, $f(a) \\leq f(b)$ is true.\n\n$^\\dagger$ An array $b$ is a permutation of an array $a$ if $b$ consists of the elements of $a$ in arbitrary order. For example, $[4,2,3,4]$ is a permutation of $[3,2,4,4]$ while $[1,2,2]$ is not a permutation of $[1,2,3]$.",
    "tutorial": "Let's call $M = max(a_1, a_2, \\dots, a_n)$. The problem asks us to make all its elements become $0$ in some operations. And for each operation, we subtract each elements in an subarray by $1$. Thus, every largest elements of the array have to be decreased in at least $M$ operations. And also because of that, $min(f(p))$ over all permutations $p$ of $a$ is never less than $M$. Every permutations $p$ of $a$ such that $f(p) = M$ have the same construction. That is, they can be divided into $2$ subarrays where the left subarray is sorted in non-decreasing order, and the right subarray is sorted in non-increasing order. In other words, the elements of the array should form a mountain. This is how to perform the operations: assign $l$ equal to the index of the leftmost element whose value is not $0$, and assign $r$ equal to the index of the rightmost element whose value is also not $0$, then subtract each element $a_l, a_{l+1}, \\dots, a_r$ by $1$. Repeat the operation until all elements become $0$. The thing is each element of the array is always greater or equal than every elements in the left side or the right side of it so it can never become negative at some point of performing the operations. Besides, all the largest elements are also included in each operation that we perform, which mean we've achieved the goal to make all elements of the array become $0$ in $M$ operations. So how to check whether $f(a) = M$ or not? Well, we can define $preLen$ equal to the length of the longest prefix which is sorted in non-decreasing order. Then define $sufLen$ equal to the length of the longest suffix which is sorted in non-increasing order. If $preLen + sufLen \\ge n$, the answer is YES. Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1e5 + 5;\n\nint n, a[N];\n\nint main() {\n    int tc;\n    for (cin >> tc; tc--; ) {\n        cin >> n;\n        for (int i = 1; i <= n; i++)\n            cin >> a[i];\n\n        int preLen = 1;\n        while (preLen < n && a[preLen] <= a[preLen + 1])\n            preLen++;\n\n        int sufLen = 1;\n        while (sufLen < n && a[n-sufLen] >= a[n-sufLen + 1])\n            sufLen++;\n\n        if (preLen + sufLen >= n)\n            cout << \"YES\" << endl;\n        else\n            cout << \"NO\" << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1713",
    "index": "C",
    "title": "Build Permutation",
    "statement": "A \\textbf{$\\mathbf{0}$-indexed} array $a$ of size $n$ is called good if for all valid indices $i$ ($0 \\le i \\le n-1$), $a_i + i$ is a perfect square$^\\dagger$.\n\nGiven an integer $n$. Find a permutation$^\\ddagger$ $p$ of $[0,1,2,\\ldots,n-1]$ that is good or determine that no such permutation exists.\n\n$^\\dagger$ An integer $x$ is said to be a perfect square if there exists an integer $y$ such that $x = y^2$.\n\n$^\\ddagger$ An array $b$ is a permutation of an array $a$ if $b$ consists of the elements of $a$ in arbitrary order. For example, $[4,2,3,4]$ is a permutation of $[3,2,4,4]$ while $[1,2,2]$ is not a permutation of $[1,2,3]$.",
    "tutorial": "First, let's prove that the answer always exists. Let's call the smallest square number that is not smaller than $k$ is $h$. Therefore $h \\leq 2 \\cdot k$, which means $h - k \\leq k$. Proof. So we can fill $p_i = h - i$ for $(h - k \\leq i \\leq k)$. Using this method we can recursively reduce $k$ to $h - k - 1$, then all the way down to $-1$. We can prove that $h - k \\geq 0$, as $h \\geq k$. Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1e5 + 5;\n\nint n, ans[N];\n\nvoid recurse(int r) {\n\tif (r < 0) return;\n\tint s = sqrt(2*r); s *= s;\n\tint l = s - r; recurse(l - 1);\n\tfor (; l <= r; l++, r--) {\n\t\tans[l] = r; ans[r] = l;\n\t}\n}\n\nint main() {\n\tint tc; cin >> tc;\n\twhile (tc--) {\n\t\tcin >> n; recurse(n - 1);\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tcout << ans[i] << ' ';\n\t\tcout << '\\n';\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1713",
    "index": "D",
    "title": "Tournament Countdown",
    "statement": "This is an interactive problem.\n\nThere was a tournament consisting of $2^n$ contestants. The $1$-st contestant competed with the $2$-nd, the $3$-rd competed with the $4$-th, and so on. After that, the winner of the first match competed with the winner of second match, etc. The tournament ended when there was only one contestant left, who was declared the winner of the tournament. Such a tournament scheme is known as the single-elimination tournament.\n\nYou don't know the results, but you want to find the winner of the tournament. In one query, you select two integers $a$ and $b$, which are the indices of two contestants. The jury will return $1$ if $a$ won more matches than $b$, $2$ if $b$ won more matches than $a$, or $0$ if their number of wins was equal.\n\nFind the winner in no more than $\\left \\lceil \\frac{1}{3} \\cdot 2^{n + 1} \\right \\rceil$ queries. Here $\\lceil x \\rceil$ denotes the value of $x$ rounded up to the nearest integer.\n\nNote that the tournament is long over, meaning that the results are fixed and do not depend on your queries.",
    "tutorial": "There is a way to erase $3$ participants in every $2$ queries. Since there are $2^n - 1$ participants to be removed, the number of queries will be $\\left \\lceil (2^n - 1) \\cdot \\frac{2}{3} \\right \\rceil = \\left \\lfloor \\frac{2^{n + 1}}{3} \\right \\rfloor$. Suppose there are only $4$ participants. In the first query we will ask the judge to compare the $1^{st}$ and the $3^{rd}$ participants. There are three cases: The $1^{st}$ participant wins more game than the $3^{rd}$ one: the $2^{nd}$ and $3^{rd}$ cannot be the winner. The $1^{st}$ participant wins more game than the $3^{rd}$ one: the $2^{nd}$ and $3^{rd}$ cannot be the winner. The $3^{rd}$ participant wins more game than the $1^{st}$ one: the $1^{st}$ and $4^{th}$ cannot be the winner. The $3^{rd}$ participant wins more game than the $1^{st}$ one: the $1^{st}$ and $4^{th}$ cannot be the winner. The $1^{st}$ and $3^{rd}$ participants' numbers of winning games are equal: both the $1^{st}$ and $3^{rd}$ cannot be the winner. The $1^{st}$ and $3^{rd}$ participants' numbers of winning games are equal: both the $1^{st}$ and $3^{rd}$ cannot be the winner. Ask the remaining two participants, find the winner between them. If there are more than $4$ participants, we can continuously divide the number by $4$ again and again, until there are at most $2$ participants left. Now we can get the winner in one final query.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint ask(vector<int> &k)\n{\n\tcout << \"? \" << k[0] << ' ' << k[2] << endl;\n\tint x;\n\tcin >> x;\n\tif (x == 1)\n\t{\n\t\tcout << \"? \" << k[0] << ' ' << k[3] << endl;\n\t\tcin >> x;\n\t\tif (x == 1) return k[0];\n\t\treturn k[3];\n\t}\n\telse if (x == 2)\n\t{\n\t\tcout << \"? \" << k[1] << ' ' << k[2] << endl;\n\t\tcin >> x;\n\t\tif (x == 1) return k[1];\n\t\treturn k[2];\n\t}\n\telse\n\t{\n\t\tcout << \"? \" << k[1] << ' ' << k[3] << endl;\n\t\tcin >> x;\n\t\tif (x == 1) return k[1];\n\t\treturn k[3];\n\t}\n}\n\nvoid solve()\n{\n\tint n;\n\tcin >> n;\n\tvector<int> a, b;\n\tfor (int i = 1; i <= (1LL << n); i++)\n\t{\n\t\ta.push_back(i);\n\t}\n\twhile (a.size() > 2)\n\t{\n\t\twhile (!a.empty())\n\t\t{\n\t\t\tvector<int> k(4);\n\t\t\tk[0] = a.back();\n\t\t\ta.pop_back();\n\t\t\tk[1] = a.back();\n\t\t\ta.pop_back();\n\t\t\tk[2] = a.back();\n\t\t\ta.pop_back();\n\t\t\tk[3] = a.back();\n\t\t\ta.pop_back();\n\t\t\tint win = ask(k);\n\t\t\tb.push_back(win);\n\t\t}\n\t\ta = b;\n\t\tb.clear();\n\t}\n\tif (a.size() == 2)\n\t{\n\t\tcout << \"? \" << a[0] << ' ' << a[1] << endl;\n\t\tint x;\n\t\tcin >> x;\n\t\tif (x == 2) a[0] = a[1];\n\t}\n\tcout << \"! \" << a[0] << endl;\n}\n\nint main(int argc, char ** argv)\n{\n\tint tests;\n\tcin >> tests;\n\twhile(tests--) solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "interactive",
      "number theory",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1713",
    "index": "E",
    "title": "Cross Swapping",
    "statement": "You are given a square matrix $A$ of size $n \\times n$ whose elements are integers. We will denote the element on the intersection of the $i$-th row and the $j$-th column as $A_{i,j}$.\n\nYou can perform operations on the matrix. In each operation, you can choose an integer $k$, then for each index $i$ ($1 \\leq i \\leq n$), swap $A_{i, k}$ with $A_{k, i}$. Note that cell $A_{k, k}$ remains unchanged.\n\nFor example, for $n = 4$ and $k = 3$, this matrix will be transformed like this:\n\n\\begin{center}\n{\\small The operation $k = 3$ swaps the blue row with the green column.}\n\\end{center}\n\nYou can perform this operation any number of times. Find the lexicographically smallest matrix$^\\dagger$ you can obtain after performing arbitrary number of operations.\n\n${}^\\dagger$ For two matrices $A$ and $B$ of size $n \\times n$, let $a_{(i-1) \\cdot n + j} = A_{i,j}$ and $b_{(i-1) \\cdot n + j} = B_{i,j}$. Then, the matrix $A$ is lexicographically smaller than the matrix $B$ when there exists an index $i$ ($1 \\leq i \\leq n^2$) such that $a_i < b_i$ and for all indices $j$ such that $1 \\leq j < i$, $a_j = b_j$.",
    "tutorial": "Let's take a look at what the lexicographically smallest matrix is. Let's call $(x, y)$ a cell that is in the intersection of row $x$ and column $y$ of the matrix, and the integer written on that cell is $A_{x, y}$. A cell $(x_p, y_p)$ of this matrix is called more significant than the another cell $(x_q, y_q)$ if and only if $x_p < x_q$, or $x_p = x_q$ and $y_p < y_q$. The problem asks us to find the smallest matrix so the best suitable way to solve this problem is to traverse through the most to the least significant cell of the matrix, then determine if the current cell can be minimized or not. Suppose the current cell we are looking at is $(x, y)$. If $x = y$ then its position will not change after performing the operations. But if $x \\neq y$, there are exactly $2$ operations that swap $(x, y)$ with another cell, that is $k = x$ and $k = y$. Both of these operations swap $(x, y)$ with the same cell $(y, x)$. So the only way we can minimize the value of $(x, y)$ is to try swapping it with $(y, x)$ (if $x < y$ and $A_{x, y} > A_{y, x}$) in some way. As a result we have our constructive algorithm. Remind that for each operation $k = i$ of the matrix ($1 \\le i \\le n$), there are $2$ states: it is being performed and not being performed. Suppose we have traversed to the cell $(x, y)$. If $x \\ge y$, ignore it. If $x < y$ then we try to make $A_{x, y} = min(A_{x, y}, A_{y, x})$ by deciding to swap or not to swap the cells. If $A_{x, y} > A_{y, x}$, try to swap $(x, y)$ with $(y, x)$ by making $2$ operations $k = x$ and $k = y$ having different states. And if $A_{x, y} < A_{y, x}$ then we should keep their positions unchanged by making $2$ operations $k = x$ and $k = y$ having the same state. Note that if $A_{x, y} = A_{y, x}$, we do nothing. Let's implement this algorithm using a simple DSU where the $ith$ node represents the operation $k = i$. We define the value $par[u]$ in such a way that, suppose $p$ is the root of the $u$ node's component, $par[u] = p$ if $2$ operations $k = u$ and $k = p$ should have the same state, or $par[u] = -p$ if $2$ operations $k = u$ and $k = p$ should have different states. Define another function $join(i, j)$ to union $2$ nodes $i$ and $j$ to the same component. Note that $u$ and $-u$ are always in the same component and $par[-u] = -par[u]$. Thus, for the current cell $(x, y)$, we want to swap it with $(y, x)$ by calling $join(x, -y)$, or keep its position unchanged by calling $join(x, y)$. After constructing the graphs, the last thing to do is to determine which operations should be performed. One way to do so is for each root of the components of the DSU, we perform the operation which this root represents for. Then for other nodes just check $par[i] > 0$ for the $ith$ node and if it is true, the $k = i$ operation should be performed. When we have the list of the operations that need to be performed, we can bruteforcely perform each operation from the list one by one and the final matrix will be the lexicographically smallest matrix. Time complexity: $O(n^2)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 2e3 + 5;\n\nint n, a[N][N];\n\nint par[N];\nint getPar(int u) {\n    if (u < 0) return -getPar(-u);\n    if (u == par[u]) return u;\n    return par[u] = getPar(par[u]);\n}\nvoid join(int u, int v) {\n    u = getPar(u); v = getPar(v);\n    if (abs(u) != abs(v)) {\n        if (u > 0) par[u] = v;\n        else par[-u] = -v;\n    }\n}\n\nint main() {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n\n    int tc; cin >> tc;\n    while (tc--) {\n        cin >> n;\n        for (int i = 1; i <= n; i++)\n            for (int j = 1; j <= n; j++) {\n                cin >> a[i][j];\n            }\n    \n        iota(par + 1, par + n + 1, 1);\n        // set par[i] == i for i in [1, n]\n\n        for (int i = 1; i <= n; i++)\n            for (int j = 1; j <= n; j++) {\n                if (a[i][j] < a[j][i]) join(i, j);\n                if (a[i][j] > a[j][i]) join(i, -j);\n            }\n    \n        for (int i = 1; i <= n; i++) {\n            if (getPar(i) < 0) continue;\n            // we only perform the operation\n            // if and only if getPar(i) > 0\n            for (int j = 1; j <= n; j++)\n                swap(a[i][j], a[j][i]);\n        }\n\n        for (int i = 1; i <= n; i++) {\n            for (int j = 1; j <= n; j++) {\n                cout << a[i][j] << ' ';\n            }\n            cout << '\\n';\n        }\n    }\n}",
    "tags": [
      "2-sat",
      "data structures",
      "dsu",
      "greedy",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1713",
    "index": "F",
    "title": "Lost Array",
    "statement": "\\begin{quote}\n{{My orzlers, we can optimize this problem from $O(S^3)$ to $O\\left(T^\\frac{5}{9}\\right)$!}}\n\\hfill — Spyofgame, founder of Orzlim religion\n\\end{quote}\n\nA long time ago, Spyofgame invented the famous array $a$ ($1$-indexed) of length $n$ that contains information about the world and life. After that, he decided to convert it into the matrix $b$ ($0$-indexed) of size $(n + 1) \\times (n + 1)$ which contains information about the world, life and beyond.\n\nSpyofgame converted $a$ into $b$ with the following rules.\n\n- $b_{i,0} = 0$ if $0 \\leq i \\leq n$;\n- $b_{0,i} = a_{i}$ if $1 \\leq i \\leq n$;\n- $b_{i,j} = b_{i,j-1} \\oplus b_{i-1,j}$ if $1 \\leq i, j \\leq n$.\n\nHere $\\oplus$ denotes the bitwise XOR operation.\n\nToday, archaeologists have discovered the famous matrix $b$. However, many elements of the matrix has been lost. They only know the values of $b_{i,n}$ for $1 \\leq i \\leq n$ (note that these are some elements of the last \\textbf{column}, not the last \\textbf{row}).\n\nThe archaeologists want to know what a possible array of $a$ is. Can you help them reconstruct any array that could be $a$?",
    "tutorial": "First, we can see that $a_i$ contribute $\\binom{(n - i) + (j - 1)}{j - 1}$ times to $b_{j, n}$, which can calculate similar to Pascal's Triangle. It's easy to see that the value that $a_i$ contribute to $b_{j, n}$ equal to $a_i$ when $\\binom{(n - i) + (j - 1)}{j - 1}$ is odd, $0$ otherwise. Let's solve the inverse problem: Given array $a$. Construct $b_{j, n}$ for all $j$. $(1 \\le j \\le n)$ By Lucas Theorem, $\\binom{(n - i) + (j - 1)}{j - 1}$ is odd when $(n - i)\\ AND\\ (j - 1) = 0$ $\\rightarrow (n - i)$ is a submask of $\\sim(j - 1)$ (with $\\sim a$ is inverse mask of $a$). Let define $m = 2^k$ with smallest $m$ satisfy $m \\ge n$. Set $a'_i = a_i$ and $b'_j = b_{\\sim(j - 1)} = b_{(m - 1) - (j - 1)}$ then $b'$ is the Zeta transform of $a'$. So we could apply Mobius transform in $b'$ to get $a'$. Since the operation is xor, mobius transform is as same as zeta transform. But unlike the inverse problem, there are some differences. We don't know the value of $b'_i$ for $i$ in $[0, m - n)$. Let $c$ be the sum over supermasks array of $b'$ (with $i$ is supermasks of $j$ when $i\\ AND\\ j = j)$, then set $c_k = 0$ for $k$ in $[m - n, m)$. After that, do another sum over supermasks on $c$ to get original value of $b'$. Now we can find $a'$ from $b'$ and $a$ from $a'$. Complexity: $O(nlog_2(n))$",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define endl '\\n'\n#define fi first\n#define se second\n#define For(i, l, r) for (auto i = (l); i < (r); i++)\n#define ForE(i, l, r) for (auto i = (l); i <= (r); i++)\n#define FordE(i, l, r) for (auto i = (l); i >= (r); i--)\n#define Fora(v, a) for (auto v: (a))\n#define bend(a) (a).begin(), (a).end()\n#define isz(a) ((signed)(a).size())\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair <int, int>;\nusing vi = vector <int>;\nusing vpii = vector <pii>;\nusing vvi = vector <vi>;\n\nconst int N = 1 << 19;\n\nint n;\nint a[N], b[N], ta[N], tb[N];\nint c[N];\n\nint m, lm, all1;\n\nsigned main(){\n    cin >> n;\n    ForE(i, 1, n){\n        cin >> b[i];\n    }\n\n    m = 1 << __lg(n);\n    if (m < n){\n        m *= 2;\n    }\n    lm = __lg(m);\n    all1 = m - 1;\n    memset(ta, -1, sizeof(ta));\n    memset(tb, -1, sizeof(tb));\n    ForE(i, 1, n){\n        tb[all1 ^ (i - 1)] = b[i];\n        ta[n - i] = -2;\n    }\n\n    For(i, 0, m){\n        c[all1 ^ i] = max(tb[i], 0);\n    }\n    For(bit, 0, lm){\n        For(msk, 0, m){\n            if (msk >> bit & 1){\n                c[msk] ^= c[msk ^ (1 << bit)];\n            }\n        }\n    }\n    For(i, 0, m){\n        if (tb[i] == -1){\n            c[all1 ^ i] = 0;\n        }\n    }\n    For(bit, 0, lm){\n        For(msk, 0, m){\n            if (msk >> bit & 1){\n                c[msk] ^= c[msk ^ (1 << bit)];\n            }\n        }\n    }\n    For(i, 0, m){\n        if (tb[i] == -1){\n            tb[i] = c[all1 ^ i];\n        }\n    }\n\n    For(i, 0, m){\n        ta[i] = tb[i];\n    }\n    For(bit, 0, lm){\n        For(msk, 0, m){\n            if (msk >> bit & 1){\n                ta[msk] ^= ta[msk ^ (1 << bit)];\n            }\n        }\n    }\n    ForE(i, 1, n){\n        a[i] = ta[n - i];\n    }\n    ForE(i, 1, n){\n        cout << a[i] << ' ';\n    } cout << endl;\n}\n",
    "tags": [
      "bitmasks",
      "combinatorics",
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1714",
    "index": "A",
    "title": "Everyone Loves to Sleep",
    "statement": "Vlad, like everyone else, loves to sleep very much.\n\nEvery day Vlad has to do $n$ things, each at a certain time. For each of these things, he has an alarm clock set, the $i$-th of them is triggered on $h_i$ hours $m_i$ minutes every day ($0 \\le h_i < 24, 0 \\le m_i < 60$). Vlad uses the $24$-hour time format, so after $h=12, m=59$ comes $h=13, m=0$ and after $h=23, m=59$ comes $h=0, m=0$.\n\nThis time Vlad went to bed at $H$ hours $M$ minutes ($0 \\le H < 24, 0 \\le M < 60$) and asks you to answer: how much he will be able to sleep until the next alarm clock.\n\nIf any alarm clock rings at the time when he went to bed, then he will sleep for a period of time of length $0$.",
    "tutorial": "To begin with, let's learn how to determine how much time must pass before the $i$ alarm to trigger. If the alarm time is later than the current one, then obviously $60*(h_i - H) + m_i - M$ minutes should pass. Otherwise, this value will be negative and then it should pass $24*60 + 60* (h_i - H) + m_i - M$ since a full day must pass, not including the time from the alarm to the current time. We just need to find the minimum number of minutes among all the alarm clocks. Due to small constrains, the problem can also be solved by stimulating the sleep process: increase the answer by $1$ and check whether any alarm will work after this time.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(143);\n\nconst int inf = 1e15;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nvoid solve(){\n    int n;\n    cin >> n;\n    int time, h, m;\n    cin >> h >> m;\n    time = 60 * h + m;\n    int ans = 24 * 60;\n    for(int i = 0; i < n; ++i){\n        cin >> h >> m;\n        int t = 60 * h + m - time;\n        if(t < 0) t += 24 * 60;\n        ans = min(ans, t);\n    }\n    cout << ans / 60 << \" \" << ans % 60;\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (; t; --t) {\n        solve();\n        cout << endl;\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1714",
    "index": "B",
    "title": "Remove Prefix",
    "statement": "Polycarp was presented with some sequence of integers $a$ of length $n$ ($1 \\le a_i \\le n$). A sequence can make Polycarp happy only if it consists of \\textbf{different} numbers (i.e. distinct numbers).\n\nIn order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves.\n\nIn one move, he can:\n\n- remove the first (leftmost) element of the sequence.\n\nFor example, in one move, the sequence $[3, 1, 4, 3]$ will produce the sequence $[1, 4, 3]$, which consists of different numbers.\n\nDetermine the minimum number of moves he needs to make so that in the remaining sequence all elements are different. In other words, find the length of the smallest prefix of the given sequence $a$, after removing which all values in the sequence will be unique.",
    "tutorial": "Let's turn the problem around: we'll look for the longest suffix that will make Polycarp happy, since it's the same thing. Let's create an array $cnt$, in which we will mark the numbers already encountered. Let's go along $a$ from right to left and check if $a_i$ does not occur to the right (in this case it is marked in $cnt$), if it occurs to the right, then removing any prefix that does not include $i$, we get an array where $a_i$ occurs twice, so we have to delete prefix of length $i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        forn(i, n)\n            cin >> a[i];\n        bool yes = false;\n        set<int> c;\n        for (int i = n - 1; i >= 0; i--) {\n            if (c.count(a[i])) {\n                cout << i + 1 << endl;\n                yes = true;\n                break;\n            }\n            c.insert(a[i]);\n        }\n        if (!yes)\n            cout << 0 << endl;\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1714",
    "index": "C",
    "title": "Minimum  Varied Number",
    "statement": "Find the minimum number with the given sum of digits $s$ such that \\textbf{all} digits in it are distinct (i.e. all digits are unique).\n\nFor example, if $s=20$, then the answer is $389$. This is the minimum number in which all digits are different and the sum of the digits is $20$ ($3+8+9=20$).\n\nFor the given $s$ print the required number.",
    "tutorial": "Let's use the greedy solution: we will go through the digits in decreasing order. If the sum of $s$ we need to dial is greater than the current digit, we add the current digit to the end of the line with the answer. Note that in this way we will always get an answer consisting of the minimum possible number of digits, because we are going through the digits in descending order. Suppose that the resulting number is not optimal. Then some digit can be reduced, and some digit that comes after it can be increased, in order to save the sum (we can not increase the digit before it, as then we get a number greater than the current one). Two variants are possible. We want to increase the digit $x$ to $x+1$, but then it becomes equal to the digit following it, or exceeds the value $9$. Then we can't increment that digit. Otherwise, in the first step, we can get $x+1$ instead of $x$, but since we are going through the digits in decreasing order, we cannot get the value of $x$ in that case. Contradiction.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int s;\n        cin >> s;\n        string result;\n        for (int d = 9; d >= 1; d--)\n            if (s >= d) {\n                result = char('0' + d) + result;\n                s -= d;\n            }\n        cout << result << endl;\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1714",
    "index": "D",
    "title": "Color with Occurrences",
    "statement": "You are given some text $t$ and a set of $n$ strings $s_1, s_2, \\dots, s_n$.\n\nIn one step, you can choose any occurrence of any string $s_i$ in the text $t$ and color the corresponding characters of the text in red. For example, if $t=bababa$ and $s_1=ba$, $s_2=aba$, you can get $t=\\textcolor{red}{ba}baba$, $t=b\\textcolor{red}{aba}ba$ or $t=bab\\textcolor{red}{aba}$ in one step.\n\nYou want to color all the letters of the text $t$ in red. When you color a letter in red again, it stays red.\n\nIn the example above, three steps are enough:\n\n- Let's color $t[2 \\dots 4]=s_2=aba$ in red, we get $t=b\\textcolor{red}{aba}ba$;\n- Let's color $t[1 \\dots 2]=s_1=ba$ in red, we get $t=\\textcolor{red}{baba}ba$;\n- Let's color $t[4 \\dots 6]=s_2=aba$ in red, we get $t=\\textcolor{red}{bababa}$.\n\nEach string $s_i$ can be applied any number of times (or not at all). Occurrences for coloring can intersect arbitrarily.\n\nDetermine the minimum number of steps needed to color all letters $t$ in red and how to do it. If it is impossible to color all letters of the text $t$ in red, output -1.",
    "tutorial": "The first step is to find the word that covers the maximum length prefix. If there is no such word, we cannot color the string. Then go through the positions inside the found prefix and find the next word, which is a tweak of $t$, has the maximal length, and ends not earlier than the previous found word, and not later than the text $t$. If there is no such word, it is impossible to color $t$. After the second word is found, similarly continue looking for the next ones.",
    "code": "#include<bits/stdc++.h>\n#define len(s) (int)s.size()\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\nint ans = 0;\nbool ok = true;\n\nvoid Find(int a, int b, string &t, vector<string>&str, vector<pair<int, int>>&match){\n    int Max = 0, id = -1, pos = -1;\n    for(int i = a; i <= b; i++){\n        for(int j = 0; j < len(str); j++){\n            string s = str[j];\n            if(i + len(s) > len(t) || i + len(s) <= b) continue;\n            if(t.substr(i, len(s)) == s) {\n                if(i + len(s) > Max){\n                    Max = i + len(s);\n                    id = j;\n                    pos = i;\n                }\n            }\n        }\n    }\n    if(id == -1) {\n        ok = false;\n        return;\n    }\n    else{\n        match.emplace_back(id, pos);\n        ans++;\n        if(Max == len(t)) return;\n        else Find(max(pos + 1, b +1), Max, t, str, match);\n    }\n}\n\n\nvoid solve(){\n    ans = 0;\n    ok = true;\n\n    string t;\n    cin >> t;\n    int n;\n    cin >> n;\n\n    vector<string>s(n);\n    vector<pair<int, int>>match;\n\n    forn(i, n) {\n        cin >> s[i];\n    }\n\n    Find(0, 0, t, s, match);\n    if(!ok) cout << \"-1\\n\";\n    else{\n        cout << ans << endl;\n        for(auto &p : match) cout << p.first + 1 << ' ' << p.second + 1 << endl;\n    }\n\n}\n\nint main(){\n    int q;\n    cin >> q;\n    while(q--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1714",
    "index": "E",
    "title": "Add Modulo 10",
    "statement": "You are given an array of $n$ integers $a_1, a_2, \\dots, a_n$\n\nYou can apply the following operation an arbitrary number of times:\n\n- select an index $i$ ($1 \\le i \\le n$) and replace the value of the element $a_i$ with the value $a_i + (a_i \\bmod 10)$, where $a_i \\bmod 10$ is the remainder of the integer dividing $a_i$ by $10$.\n\nFor a single index (value $i$), this operation can be applied multiple times. If the operation is applied repeatedly to the same index, then the current value of $a_i$ is taken into account each time. For example, if $a_i=47$ then after the first operation we get $a_i=47+7=54$, and after the second operation we get $a_i=54+4=58$.\n\nCheck if it is possible to make \\textbf{all} array elements equal by applying multiple (possibly zero) operations.\n\nFor example, you have an array $[6, 11]$.\n\n- Let's apply this operation to the first element of the array. Let's replace $a_1 = 6$ with $a_1 + (a_1 \\bmod 10) = 6 + (6 \\bmod 10) = 6 + 6 = 12$. We get the array $[12, 11]$.\n- Then apply this operation to the second element of the array. Let's replace $a_2 = 11$ with $a_2 + (a_2 \\bmod 10) = 11 + (11 \\bmod 10) = 11 + 1 = 12$. We get the array $[12, 12]$.\n\nThus, by applying $2$ operations, you can make all elements of an array equal.",
    "tutorial": "Let's see which remainders modulo $10$ change into which ones. If the array contains a number divisible by $10$, then it cannot be changed. If there is a number that has a remainder of $5$ modulo $10$, then it can only be replaced once. Thus, if the array contains a number divisible by $5$, then we apply this operation to all elements of the array once and check that all its elements are equal. The remaining odd balances ($1, 3, 7, 9$) immediately turn into even ones. The even remainders ($2, 4, 6, 8$) change in a cycle, while the array element increases by $20$ in $4$ operations. Thus, we will apply the operation to each element of the array until its remainder modulo $10$ becomes, for example, $2$, and then check that the array does not contain both remainders $2$ and $12$ modulo $20$.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <queue>\n\nusing namespace std;\n\nint next(int x) {\n    return x + x % 10;\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    bool flag = false;\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n        if (a[i] % 5 == 0) {\n            flag = true;\n            a[i] = next(a[i]);\n        }\n    }\n    if (flag) {\n        cout << (*min_element(a.begin(), a.end()) == *max_element(a.begin(), a.end()) ? \"Yes\": \"No\") << '\\n';\n    } else {\n        bool flag2 = false, flag12 = false;\n        for (int i = 0; i < n; ++i) {\n            int x = a[i];\n            while (x % 10 != 2) {\n                x = next(x);\n            }\n            if (x % 20 == 2) {\n                flag2 = true;\n            } else {\n                flag12 = true;\n            }\n        }\n        cout << ((flag2 & flag12) ? \"No\" : \"Yes\") << '\\n';\n    }\n}\n\nint main() {\n    int t = 1;\n    cin >> t;\n    for (int it = 0; it < t; ++it) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1714",
    "index": "F",
    "title": "Build a Tree and That Is It",
    "statement": "A tree is a connected undirected graph without cycles. Note that in this problem, we are talking about not rooted trees.\n\nYou are given four positive integers $n, d_{12}, d_{23}$ and $d_{31}$. Construct a tree such that:\n\n- it contains $n$ vertices numbered from $1$ to $n$,\n- the distance (length of the shortest path) from vertex $1$ to vertex $2$ is $d_{12}$,\n- distance from vertex $2$ to vertex $3$ is $d_{23}$,\n- the distance from vertex $3$ to vertex $1$ is $d_{31}$.\n\nOutput any tree that satisfies all the requirements above, or determine that no such tree exists.",
    "tutorial": "If the answer exists, you can hang the tree by some vertex such that the distances $d_{12}, d_{23}$ and $d_{31}$ can be expressed through the sums of distances to vertices $1,2$ and $3$. Then from the system of equations we express the required values of distances to vertices $1,2,3$ and construct a suitable tree. If the distance to a vertex is $0$, then that vertex is the root. There cannot be two roots, nor can there be negative distances. If none of the vertices of $1,2,3$ is the root, then make vertex $4$ the root. Next we build the required tree: add the required number of unique vertices on the path from the root to vertices $1,2,3$. Note also that if the sum of distances is greater than or equal to $n$, then we cannot build the tree either. The remaining vertices can be simply joined to the root.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<int> d(3);\n        forn(i, 3)\n            cin >> d[i];\n        int sum = d[0] + d[1] + d[2];\n        if (sum % 2 == 0) {\n            vector<int> w(3);\n            forn(i, 3)\n                w[i] = sum / 2 - d[(i + 1) % 3];\n            vector<int> sw(w.begin(), w.end());\n            sort(sw.begin(), sw.end());\n            if (sw[0] >= 0 && sw[1] >= 1) {\n                vector<pair<int,int>> edges;\n                int num = 3;\n                int center;\n                if (sw[0] == 0)\n                    center = min_element(w.begin(), w.end()) - w.begin();\n                else\n                    center = num++;\n                forn(i, 3) {\n                    int before = center;\n                    forn(j, w[i] - 1) {\n                        edges.push_back({before, num});\n                        before = num++;\n                    }\n                    if (w[i] > 0)\n                        edges.push_back({before, i});\n                }\n                if (num <= n) {\n                    while (num < n)\n                        edges.push_back({center, num++});\n                    cout << \"YES\" << endl;\n                    for (auto& [u, v]: edges)\n                        cout << u + 1 << \" \" << v + 1 << endl;\n                    continue;\n                }\n            }\n        }\n        cout << \"NO\" << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1714",
    "index": "G",
    "title": "Path Prefixes",
    "statement": "You are given a rooted tree. It contains $n$ vertices, which are numbered from $1$ to $n$. The root is the vertex $1$.\n\nEach edge has two positive integer values. Thus, two positive integers $a_j$ and $b_j$ are given for each edge.\n\nOutput $n-1$ numbers $r_2, r_3, \\dots, r_n$, where $r_i$ is defined as follows.\n\nConsider the path from the root (vertex $1$) to $i$ ($2 \\le i \\le n$). Let the sum of the costs of $a_j$ along this path be $A_i$. Then $r_i$ is equal to the length of the maximum prefix of this path such that the sum of $b_j$ along this prefix does not exceed $A_i$.\n\n\\begin{center}\n{\\small Example for $n=9$. The blue color shows the costs of $a_j$, and the red color shows the costs of $b_j$.}\n\\end{center}\n\nConsider an example. In this case:\n\n- $r_2=0$, since the path to $2$ has an amount of $a_j$ equal to $5$, only the prefix of this path of length $0$ has a smaller or equal amount of $b_j$;\n- $r_3=3$, since the path to $3$ has an amount of $a_j$ equal to $5+9+5=19$, the prefix of length $3$ of this path has a sum of $b_j$ equal to $6+10+1=17$ ( the number is $17 \\le 19$);\n- $r_4=1$, since the path to $4$ has an amount of $a_j$ equal to $5+9=14$, the prefix of length $1$ of this path has an amount of $b_j$ equal to $6$ (this is the longest suitable prefix, since the prefix of length $2$ already has an amount of $b_j$ equal to $6+10=16$, which is more than $14$);\n- $r_5=2$, since the path to $5$ has an amount of $a_j$ equal to $5+9+2=16$, the prefix of length $2$ of this path has a sum of $b_j$ equal to $6+10=16$ (this is the longest suitable prefix, since the prefix of length $3$ already has an amount of $b_j$ equal to $6+10+1=17$, what is more than $16$);\n- $r_6=1$, since the path up to $6$ has an amount of $a_j$ equal to $2$, the prefix of length $1$ of this path has an amount of $b_j$ equal to $1$;\n- $r_7=1$, since the path to $7$ has an amount of $a_j$ equal to $5+3=8$, the prefix of length $1$ of this path has an amount of $b_j$ equal to $6$ (this is the longest suitable prefix, since the prefix of length $2$ already has an amount of $b_j$ equal to $6+3=9$, which is more than $8$);\n- $r_8=2$, since the path up to $8$ has an amount of $a_j$ equal to $2+4=6$, the prefix of length $2$ of this path has an amount of $b_j$ equal to $1+3=4$;\n- $r_9=3$, since the path to $9$ has an amount of $a_j$ equal to $2+4+1=7$, the prefix of length $3$ of this path has a sum of $b_j$ equal to $1+3+3=7$.",
    "tutorial": "Note that all $b_j$ are positive, which means that the amount on the prefix only increases. This allows us to use binary search to find the answer for the vertex. It remains only to learn how to quickly find the sum of $b_j$ on the path prefix. Let's run a depth-first search and store the prefix sums of the current path in stack: going to the vertex, add the sum to the end of the path and delete it when exiting.",
    "code": "#pragma GCC optimize(\"O3\",\"unroll-loops\")\n#pragma GCC target(\"avx2\")\n#include <bits/stdc++.h>\n\nusing namespace std;\n#define int long long\n\nconst int maxn=2e5+5;\nvector<int> ch[maxn];\nint a[maxn];\nint b[maxn];\nint ans[maxn];\nvector<int> vb;\nint curb=0;\nint cura=0;\n\nvoid dfs(int x){\n    curb+=b[x];\n    cura+=a[x];\n    vb.push_back(curb);\n    ans[x]=upper_bound(vb.begin(),vb.end(),cura)-vb.begin();\n    for(int v:ch[x]){\n        dfs(v);\n    }\n    curb-=b[x];\n    cura-=a[x];\n    vb.pop_back();\n}\nint32_t main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);cout.tie(0);\n    int t;\n    cin>>t;\n    while(t--){\n        int n;cin>>n;\n        for(int i=0;i<n;++i) ch[i].clear();\n        for(int i=1;i<n;++i){\n            int pr,a1,b1;\n            cin>>pr>>a1>>b1;\n            --pr;\n            ch[pr].push_back(i);\n            a[i]=a1;\n            b[i]=b1;\n        }\n        dfs(0);\n        for(int i=1;i<n;++i) cout<<ans[i]-1<<' ';\n        cout<<'\\n';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1715",
    "index": "A",
    "title": "Crossmarket",
    "statement": "Stanley and Megan decided to shop in the \"Crossmarket\" grocery store, which can be represented as a matrix with $n$ rows and $m$ columns.\n\nStanley and Megan can move to an adjacent cell using $1$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use $1$ unit of power to teleport to any other cell with a portal, including Megan's starting cell.\n\nThey decided to split up: Stanley will go from the upper-left cell (cell with coordinates $(1, 1)$) to the lower-right cell (cell with coordinates $(n, m)$), whilst Megan needs to get from the lower-left cell (cell with coordinates $(n, 1)$) to the upper-right cell (cell with coordinates $(1, m)$).\n\nWhat is the minimum total energy needed for them both to do that?\n\nNote that they can choose the time they move. Time does not affect energy.",
    "tutorial": "For convenience let's define going upward as decreasing $x$ coordinate, downward - increasing $x$, left - decreasing $y$, right - increasing y. One of the optimal solutions is the following: Megan goes upward to Stanley, she spends $(n - 1)$ units of energy for that. Then she goes right to her final destination by spending $(m - 1)$ more units of energy. Stanley now has a choice: he obviously has to teleport from his starting position either all the way down, or right. He chooses what will save him the most energy, so he teleports along the greater wall of the shop for the 1 unit of power. Then Stanley has to finish his route: he walks along the smaller side and spends $min(n, m) - 1$ more energy. If at least one of the dimensions is not $1$, then the answer is $(n - 1) + (m - 1) + 1 + (min(n, m) - 1) = min(n, m) + n + m - 2$. In case where $(n, m) = (1, 1)$ answer is $0$. Obviously, except for 1 case, it is always beneficial for Stanley to use teleportation. Let the first portal he visited be $A$, and the last is $B$. It is also obvious, that teleporting for more than 1 time makes no sense, so that's why we consider, that he always teleports from $A$ to $B$ and that's it. For the sake of convenience let's define manhattan distance between two points as $dist(P_1, P_2) = |{P_1}_x - {P_2}_x| + |{P_1}_y - {P_2}_y|$. Consider the next few cases for the relative position of those two portals: $A_x \\le B_x$ and $Ay > By$ Megan must make at least $(n-1) + (m-1)$ moves. The portal does not help Stanley in the $y$ direction, so he must make at least $(m-1)$ moves. $A_x > B_x$ and $A_y \\le B_y$ Megan must make at least $(n-1) + (m-1)$ moves. The portal does not help Stanley in the $x$ direction, so he must make at least $(n-1)$ moves. $A_x \\le Bx$ and $Ay \\le By$ Megan must make at least $dist(A,B)$ moves between $A$ and $B$. Going between A and B either undoes Megan's progress in the $x$ direction or $y$ direction (depending on which is visited first), so she must make at least an additional $(n-1) or (m-1)$ moves. Stanley must make at least $(n-1) + (m-1) - dist(A,B)$ moves. $Ax > Bx$ and $Ay > By$ Megan must make at least $(n-1) + (m-1)$ moves. Using the portal undoes Stanley's progress in both the x and y directions, so he must make at least $(n-1) + (m-1)$ moves. In all cases, the total number of moves is at least (n-1) + (m-1) + min(n-1, m-1). Proof: To start with, Stanley and Megan can complete their steps in any order. So, again, for our convenience let's reorder their moves in such a way, that firstly Megan finishes her route and places portals, and then Stanley does what he needs to do. What is always the optimal route for Stanley? He goes to the nearest cell with the teleport and then teleports to the nearest possible cell to his finish. It is obvious, that Stanley can always complete his route without going left or up (except for the teleportations). Let's try to prove a similar statement for Megan: she can always plan her route avoiding moves left or down. These two cases are almost equivalent, so we will consider the first one. Let's assume that teleportations are free for Megan. Consider any cell, from which she made her move to the left. Then it is possible to \"shift\" a segment of the route to the right in order to decrease its length at least by one in conjunction with getting rid of at least one move to the left. More formally we need to construct a new route for her, so the following conditions are met: for each cell in the previous route either itself, or her right neighbor is included in the new route. This can be done by the following algorithm: we will consider cells from the original route $A$ in order of installation of the portals, and build the new route $B$ in parallel. If we cannot include the cell $(x, y)$ from $A$ to the route $B$ because it does not have adjacent sides to any of the cells from $B$. Then we can include the cell $(x, y + 1)$ to $B$ (it cannot be out of bounds). Let there be a cell $(x_1, y_1)$ in $A$ with a portal, that was installed earlier than in our current cell, and that is adjacent to our current cell. If we could not include cell $(x, y)$ to the route $B$, that it means that we also did not include the cell $(x_1, y_1)$ there, thus cell $(x_1, y_1 + 1)$ is in $B$, that also also allows us to include cell $(x, y + 1)$. After such an operation Stanley's energy consumption could increase at most by 1. Though energy spent by Megan decreased at least by one. That means that our new route is not more energy-consuming. That way Megan will never go left or down, so she will spend at least $(n - 1) + (m - 1) = n + m - 2$ units of power. If, when all the operations are applied, Stanley teleports from the cell $(x_1, y_1)$ to $(x_2, y_2)$, then $\\left[ \\begin{array}{c} x_1 \\le x_2, y_1 \\ge y_2 \\\\ x_1 \\ge x_2, y_1 \\le y_2 \\\\ \\end{array} \\right.$. In the first case he teleports along Megan's route and approaches his finish by $(x_2 - x_1) - (y_1 - y2)$, and in the second case he teleports across Megan's route and approaches his destination by $(y_2 - y_1) - (x_1 - x2)$. As you can easily notice, first's expression maximum is $n - 1$, and second's is $m - 1$. Hence Stanley will spend at least $(n - 1) + (m - 1) - max(n - 1, m - 1) = n + m - max(n, m) - 1$ units of power. After adding only teleportation we get $n + m - max(n, m)$ We got two lower bounds, that in sum are $n + m - 2 + n + m - max(n, m) = 2n + 2m - max(n, m) - 2 = n + m + min(n, m) - 2$, which is not better, than our solution's answer, even though we did not consider Megan's teleportations.",
    "code": "import kotlin.math.*\n \nfun main() {\n    var t = readLine()!!.toInt()\n    for (test in 0 until t) {\n        val (n, m) = readLine()!!.split(\" \").map { it -> it.toInt() }\n        print(\"${n + m - 3 + min(n, m) + min(max(n, m) - 1, 1)}\\n\")\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1715",
    "index": "B",
    "title": "Beautiful Array",
    "statement": "Stanley defines the beauty of an array $a$ of length $n$, which contains \\textbf{non-negative integers}, as follows: $$\\sum\\limits_{i = 1}^{n} \\left \\lfloor \\frac{a_{i}}{k} \\right \\rfloor,$$ which means that we divide each element by $k$, round it down, and sum up the resulting values.\n\nStanley told Sam the integer $k$ and asked him to find an array $a$ of $n$ non-negative integers, such that the beauty is equal to $b$ and the sum of elements is equal to $s$. Help Sam — find any of the arrays satisfying the conditions above.",
    "tutorial": "To start with, the sum of the numbers in the array $s$ cannot be less, than $k \\cdot b$ (where $k$ is the number by which we divide, and $b$ is beauty ($s \\ge k \\cdot b$)) It is important, that $s \\le k \\cdot b + (k - 1) \\cdot n$. Let's assume that is not true. Consider the sum of divisible parts of numbers in the array: it obviously does not exceed $k \\cdot b$, thus the sum of remainders is at least $(k - 1) \\cdot n + 1$, which means, that at least one of the numbers' remainders is $k$, which is impossible by definition of the remainder. That way we got the criteria for the existence of the answer: $k \\cdot b \\le s \\le k \\cdot b + (k - 1) \\cdot n$. If there does exist an answer, then we can use the following algorithm: Assign $k \\cdot b$ to any of the $n$ cells of the array. Iterate over all the cells (including the cell from the previous item) and add $min(s - sum, k - 1)$ to the current cell, where $sum$ is the current sum of the elements.",
    "code": "t = int(input())\nfor i in range(t):\n    n, x, s, q = map(int, input().split())\n    q0 = q\n    a = [0 for i in range(n)]\n    for i in range(n):\n        a[i] = min(x - 1, q)\n        q -= a[i]\n    a[-1] += q\n    q = q0\n    curr = sum(i // x for i in a)\n    if (curr <= s <= q // x):\n        j = 0\n        while curr != s:\n            curr -= a[-1] // x\n            a[-1] += a[j]\n            curr += a[-1] // x\n            a[j] = 0\n            j += 1\n        print(*a)\n    else:\n        print(-1)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1715",
    "index": "C",
    "title": "Monoblock",
    "statement": "Stanley has decided to buy a new desktop PC made by the company \"Monoblock\", and to solve captcha on their website, he needs to solve the following task.\n\nThe awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array\n\n- $[1, 1, 1]$ is $1$;\n- $[5, 7]$ is $2$, as it could be split into blocks $[5]$ and $[7]$;\n- $[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$ is 3, as it could be split into blocks $[1]$, $[7, 7, 7, 7, 7, 7, 7]$, and $[9, 9, 9, 9, 9, 9, 9, 9, 9]$.\n\nYou are given an array $a$ of length $n$. There are $m$ queries of two integers $i$, $x$. A query $i$, $x$ means that from now on the $i$-th element of the array $a$ is equal to $x$.\n\nAfter each query print the sum of awesomeness values among all subsegments of array $a$. In other words, after each query you need to calculate $$\\sum\\limits_{l = 1}^n \\sum\\limits_{r = l}^n g(l, r),$$ where $g(l, r)$ is the awesomeness of the array $b = [a_l, a_{l + 1}, \\ldots, a_r]$.",
    "tutorial": "Let us introduce another definition for the beauty - beauty of the array $a$ is a number of such positions (indexes) $i < n$, that $a_i \\neq a_{i + 1}$, plus $1$. Let's call \"joints\" places where two adjacent different numbers exist in the array. Now consider the problem from the angle of these joints: if $f(joint)$ is equal to the number of segments, that overlap this joint, then the sum of beauty over all subsegments is equal to the sum of $f(joint)$ over all joints. To get a clearer understanding, consider the following example: $[1, 7, 7, 9, 9, 9] = [1] + [7, 7] + [9, 9, 9]$ (\"$+$\" is basically a joint). There are 5 segments, which contain first joint ($[1:2], [1:3], [1:4], [1:5], [1:6]$), and there are 9 such for the second joint ($[1:4], [1:5], [1, 6], [2:4], [2:5], [2:6], [3:4], [3:5], [3:6]$), $14$ in total. After adding the number of subsegments, we get the answer: $\\frac{6 \\cdot 7}{2} = 21, 21 + 14 = 35$. From this the solution is derived, apart from change requests: iterate over the array, find \"joints\", comparing adjacent numbers, if $a_i$ is different from $a_{i + 1}$, that we must add $i \\cdot (n - i)$ to the answer, that is how many possible beginnings of subsegments from the left multiplied by the number of possible ends from the right. How we should apply changes? In fact, it's worth just checking if there are any neighboring joints for the position of the changing number, subtracting the number of subsegments, that overlap these joints, and then doing similar operations after setting a new value for the number. For a better understanding and more details, we suggest you look over the authors' solutions.",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <chrono>\n#include <deque>\n#include <iomanip>\n#include <queue>\n#include <functional>\n \nusing namespace std;\n \n#define int long long\n \nint32_t main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n + 2, 0);\n    for (int i = 1; i <= n; ++i) {\n        cin >> a[i];\n    }\n    int ans = 0;\n    for (int i = 1; i <= n; ++i) {\n        ans += (a[i] != a[i + 1]) * (n - (i + 1) + 1) * i;\n    }\n    while (m--) {\n        int i, x;\n        cin >> i >> x;\n        ans -= (a[i] != a[i - 1]) * (n - i + 1) * (i - 1);\n        ans -= (a[i + 1] != a[i]) * (n - (i + 1) + 1) * i;\n        a[i] = x;\n        ans += (a[i] != a[i - 1]) * (n - i + 1) * (i - 1);\n        ans += (a[i + 1] != a[i]) * (n - (i + 1) + 1) * i;\n        cout << ans + n * (n + 1) / 2 << '\\n';\n    }\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1715",
    "index": "D",
    "title": "2+ doors",
    "statement": "The Narrator has an integer array $a$ of length $n$, but he will only tell you the size $n$ and $q$ statements, each of them being three integers $i, j, x$, which means that $a_i \\mid a_j = x$, where $|$ denotes the bitwise OR operation.\n\nFind the lexicographically smallest array $a$ that satisfies all the statements.\n\nAn array $a$ is lexicographically smaller than an array $b$ of the same length if and only if the following holds:\n\n- in the first position where $a$ and $b$ differ, the array $a$ has a smaller element than the corresponding element in $b$.",
    "tutorial": "The first observation is that we can solve the task separately bit by bit, because of bitwise or operation is \"bit-independent\": bits of one particular power don't affect other bits to gen a lexicographically minimal solution, we can combine solutions for each bit separately This makes it possible for us to create a solution for a boolean array, and then run it $30$ times for all numbers and statements, considering only $i$-th bit in each run. For ease of understanding let's speak in a language of graphs: we have an undirected graph with $n$ vertices, on each vertex, there is either $0$ or $1$, and on each edge, there is a bitwise or of numbers, that are written on vertices connected by that edge. We have to recover the numbers on the vertices after they were somehow lost, knowing, that numbers on the vertices create a lexicographically minimal sequence possible. Initially, let's write $1$ on each of the vertices. Then walk through them and consider incidental edges. If any of the edges contain $0$, we must also write $0$ on our current vertex and the neighbor by that edge. After zeroing all the required vertices, let's try to make our sequence lexicographically minimal. Walk through the vertices again and try to write $0$ on each: to check if everything is ok, iterate over the incidental edges again. If any of them contains $1$ and connects us with a vertex with $0$, then we cannot make our vertex $0$. Such solution works in $\\mathcal{O}(\\log(\\max(a_i)) \\cdot (n + m))$ time. For a better understanding and more details, we suggest you look over the authors' solutions.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \ninline bool get_bit(uint32_t &x, uint32_t &bt) { return (x >> bt) & 1; }\ninline void make_one(uint32_t &x, uint32_t &bt) { x |= (1 << bt); }\ninline void make_null(uint32_t &x, uint32_t &bt) { x &= (~(1 << bt)); }\n \ninline bool solve_bit(vector<uint32_t> &ans,\n                      vector<vector<pair<uint32_t, uint32_t>>> &g,\n                      uint32_t &bt) {\n    for (uint32_t i = 0; i < (uint32_t)ans.size(); ++i)\n        for (auto &it : g[i])\n            if (!get_bit(it.second, bt))\n                make_null(ans[i], bt);\n            else if (!get_bit(ans[i], bt) && !get_bit(ans[it.first], bt))\n                return false;\n    for (uint32_t i = 0; i < (uint32_t)ans.size(); ++i)\n        if (get_bit(ans[i], bt)) {\n            make_null(ans[i], bt);\n            for (auto &it : g[i])\n                if (!get_bit(ans[it.first], bt) && get_bit(it.second, bt)) {\n                    make_one(ans[i], bt);\n                    break;\n                }\n        }\n \n    return true;\n}\n \ninline void solve() {\n    uint32_t n, m;\n    cin >> n >> m;\n    vector<vector<pair<uint32_t, uint32_t>>> g(n);\n    while (m--) {\n        uint32_t a, b, c;\n        cin >> a >> b >> c;\n        a--;\n        b--;\n        g[a].emplace_back(b, c);\n        g[b].emplace_back(a, c);\n        if (a > b)\n            swap(a, b);\n    }\n    const int pt = 31;\n    vector<uint32_t> ans(n, ~(1 << pt));\n    for (uint32_t i = 0; i < pt; ++i)\n        if (!solve_bit(ans, g, i)) {\n            cout << \"-1\\n\";\n            return;\n        }\n    for (auto &it : ans)\n        cout << it << \" \";\n    cout << \"\\n\";\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    solve();\n    return 0;\n}",
    "tags": [
      "2-sat",
      "bitmasks",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1715",
    "index": "E",
    "title": "Long Way Home",
    "statement": "Stanley lives in a country that consists of $n$ cities (he lives in city $1$). There are bidirectional roads between some of the cities, and you know how long it takes to ride through each of them. Additionally, there is a flight between each pair of cities, the flight between cities $u$ and $v$ takes $(u - v)^2$ time.\n\nStanley is quite afraid of flying because of watching \"Sully: Miracle on the Hudson\" recently, so he can take at most $k$ flights. Stanley wants to know the minimum time of a journey to each of the $n$ cities from the city $1$.",
    "tutorial": "Let's assume we know the shortest distances from the first vertex to each, if we have added no more than $k$ edges (air travels). Let's learn to recalculate the answer for $(k + 1)$ edges. First, let's update the answer for all the paths ending in an air travel. Then we can run Dijkstra to take into account all the paths ending with a usual edge. In order to add an air travel, we need to update the distance to $v$, with all the paths ending with an air travel to $v$. To do so, we can use Convex Hull Trick, since the recalculation formula has the following form ($d_{old}$ - array of distances for $k$ edges, $d_{new}$ - array of distances if $k+1$ the flight goes exactly to the $i$-th vertex): $d_{new}[v] = \\min\\limits_{u} \\ d_{old}[u] + (u - v)^2$ After that, we need to run Dijkstra to update the distances with all the paths not ending with an air travel. The resulting asymptotics is $O(k(m \\log n + n))$",
    "code": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n \nusing namespace std;\n \n#define int long long\n \nconst int inf = 1e18;\nconst int inf1 = 1e15;\n \nstruct CHT {\n    struct line {\n        int k, b;\n        line() {}\n        line(int k, int b): k(k), b(b) {}\n        \n        double intersect(line l) {\n            double db = l.b - b;\n            double dk = k - l.k;\n            return db / dk;\n        }\n        \n        long long operator () (long long x) {\n            return k * x + b;\n        }\n    };\n    \n    vector<double> x;\n    vector<line> ll;\n    \n    void init(line l) {\n        x.push_back(-inf);\n        ll.push_back(l);\n    }\n    \n    void addLine(line l) {\n        while (ll.size() >= 2 && l.intersect(ll[ll.size() - 2]) <= x.back()) {\n            x.pop_back();\n            ll.pop_back();\n        }\n        if (!ll.empty()) {\n            x.push_back(l.intersect(ll.back()));\n        }\n        ll.push_back(l);\n    }\n    \n    long long query(long long qx) {\n        int id = upper_bound(x.begin(), x.end(), qx) - x.begin();\n        --id;\n        return ll[id](qx);\n    }\n};\n \nvoid dijkstra(vector<vector<pair<int, int>>> &g, vector<int> &dist) {\n    const int n = g.size();\n    vector<bool> used(n, false);\n    priority_queue<pair<int, int>> q;\n    for (int i = 0; i < n; ++i) {\n        q.push({ -dist[i], i });\n    }\n    while (!q.empty()) {\n        int v = q.top().second;\n        q.pop();\n        if (used[v]) {\n            continue;\n        }\n        used[v] = true;\n        for (auto [u, w] : g[v]) {\n            if (dist[u] > dist[v] + w) {\n                dist[u] = dist[v] + w;\n                q.push({ -dist[u], u });\n            }\n        }\n    }\n}\n \nint32_t main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    int n, m, k;\n    cin >> n >> m >> k;\n    vector<vector<pair<int, int>>> g(n);\n    for (int i = 0; i < m; ++i) {\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u; --v;\n        g[u].push_back({ v, w });\n        g[v].push_back({ u, w });\n    }\n    vector<int> dist(n, inf1);\n    dist[0] = 0;\n    dijkstra(g, dist);\n    for (int i = 0; i < k; ++i) {\n        CHT cht;\n        cht.init(CHT::line(0, 0));\n        for (int i = 1; i < n; ++i) {\n            cht.addLine(CHT::line(-i * 2, dist[i] + i * i));\n        }\n        for (int i = 0; i < n; ++i) {\n            dist[i] = cht.query(i) + i * i;\n        }\n        dijkstra(g, dist);\n    }\n    for (int i : dist) {\n        cout << i << ' ';\n    }\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "geometry",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1715",
    "index": "F",
    "title": "Crop Squares",
    "statement": "This is an interactive problem.\n\nFarmer Stanley grows corn on a rectangular field of size $ n \\times m $ meters with corners in points $(0, 0)$, $(0, m)$, $(n, 0)$, $(n, m)$. This year the harvest was plentiful and corn covered the whole field.\n\nThe night before harvest aliens arrived and poisoned the corn in a single $1 \\times 1$ square with sides parallel to field borders. The corn inside the square must not be eaten, but you cannot distinguish it from ordinary corn by sight. Stanley can only collect a sample of corn from an arbitrary polygon and bring it to the laboratory, where it will be analyzed and Stanley will be told the amount of corn in the sample that was poisoned. Since the harvest will soon deteriorate, such a study can be carried out no more than $5$ times.\n\nMore formally, it is allowed to make no more than $5$ queries, each of them calculates the area of intersection of a chosen polygon with a square of poisoned corn. It is necessary to find out the coordinates of the lower-left corner of the drawn square (the vertex of the square with the smallest $x$ and $y$ coordinates).",
    "tutorial": "In fact, two queries are enough. The first query is to find out the area of intersection of the polygon with $2n + 2$ vertices at the points with coordinates $(0, m + 1),\\:(0, 0),\\:(1, m),\\:(1, 0),\\; \\dots ,\\;(n - 1, m),\\:(n - 1, 0),\\:(n, m),\\:(n, m + 1)$ with a filled square. Such a polygon is periodic over $x$ axis with period $1$, hence the $x$-coordinate of the lower left corner of the filled square does not affect the intersection area. Denote the intersection area - $s$, then the $y$-coordinate of the lower left corner of the square is calculated by the formula $y=ms-\\frac{1}{2}$. An example of such a polygon for the field $5 \\times 4$ and a filled square with the lower left corner at the point $(3.5, 2.5)$: With the second query, we find out the area of intersection of a similar polygon with $2m + 2$ vertices at points with coordinates $(n + 1, m),\\:(0, m),\\:(n, m - 1),\\:(0, m - 1),\\; \\dots ,\\;(n, 1),\\:(0, 1),\\:(n, 0),\\:(n + 1, 0)$ with a filled square. Such a polygon is periodic over $y$ axis with period $1$, hence the $y$-coordinate of the lower left corner of the filled square does not affect the intersection area. Denote the intersection area - $s$, then the $x$-coordinate of the lower left corner of the square is calculated by the formula $x=ns-\\frac{1}{2}$. An example of such a polygon for the field $5 \\times 4$ and a filled square with the lower left corner at the point $(3.5, 2.5)$:",
    "code": "#include <iostream>\n#include <vector>\n#include <iomanip>\n \nusing namespace std;\nusing ld = long double;\n \ntemplate<typename T1, typename T2>\nostream& operator<<(ostream& out, const pair<T1, T2>& x) {\n    return out << x.first << ' ' << x.second;\n}\n \nld query(const vector<pair<int, int>>& vert) {\n    cout << \"? \" << vert.size() << '\\n';\n    for (const auto& x : vert) {\n        cout << x << '\\n';\n    }\n    cout.flush();\n \n    ld reply;\n    cin >> reply;\n    return reply;\n}\n \nvoid answer(ld x, ld y) {\n    cout << setprecision(10) << fixed;\n    cout << \"! \" << x << ' ' << y << endl;\n}\n \nint main() {\n    int n, m;\n    cin >> n >> m;\n \n    vector<pair<int, int>> poly;\n    poly.emplace_back(0, m + 1);\n    poly.emplace_back(0, 0);\n    for (int i = 1; i < n; ++i) {\n        poly.emplace_back(i, m);\n        poly.emplace_back(i, 0);\n    }\n    poly.emplace_back(n, m);\n    poly.emplace_back(n, m + 1);\n    ld y = m * query(poly) - 0.5L;\n \n    poly.clear();\n    poly.emplace_back(n + 1, 0);\n    poly.emplace_back(0, 0);\n    for (int i = 1; i < m; ++i) {\n        poly.emplace_back(n, i);\n        poly.emplace_back(0, i);\n    }\n    poly.emplace_back(n, m);\n    poly.emplace_back(n + 1, m);\n    ld x = n * query(poly) - 0.5L;\n \n    answer(x, y);\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "interactive",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1716",
    "index": "A",
    "title": "2-3 Moves",
    "statement": "You are standing at the point $0$ on a coordinate line. Your goal is to reach the point $n$. In one minute, you can move by $2$ or by $3$ to the left or to the right (i. e., if your current coordinate is $x$, it can become $x-3$, $x-2$, $x+2$ or $x+3$). Note that the new coordinate can become negative.\n\nYour task is to find the \\textbf{minimum} number of minutes required to get from the point $0$ to the point $n$.\n\nYou have to answer $t$ independent test cases.",
    "tutorial": "If $n = 1$, the answer is $2$ (we can't get $1$, so we can move by $3$ to the right and by $2$ to the left). If $n = 2$ or $n = 3$, the answer is obviously $1$. Otherwise, the answer is always $\\lceil\\frac{n}{3}\\rceil$. We can't get the answer less than this value (because we need at least $\\lceil\\frac{n}{3}\\rceil$ moves to get to the point greater than or equal to $n$) and we can always get this answer by the recurrence.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    print(1 + (n == 1) if n <= 3 else (n + 2) // 3)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1716",
    "index": "B",
    "title": "Permutation Chain",
    "statement": "A permutation of length $n$ is a sequence of integers from $1$ to $n$ such that each integer appears in it exactly once.\n\nLet the fixedness of a permutation $p$ be the number of fixed points in it — the number of positions $j$ such that $p_j = j$, where $p_j$ is the $j$-th element of the permutation $p$.\n\nYou are asked to build a sequence of permutations $a_1, a_2, \\dots$, starting from the identity permutation (permutation $a_1 = [1, 2, \\dots, n]$). Let's call it a permutation chain. Thus, $a_i$ is the $i$-th permutation of length $n$.\n\nFor every $i$ from $2$ onwards, the permutation $a_i$ should be obtained from the permutation $a_{i-1}$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $a_i$ should be strictly lower than the fixedness of the permutation $a_{i-1}$.\n\nConsider some chains for $n = 3$:\n\n- $a_1 = [1, 2, 3]$, $a_2 = [1, 3, 2]$ — that is a valid chain of length $2$. From $a_1$ to $a_2$, the elements on positions $2$ and $3$ get swapped, the fixedness decrease from $3$ to $1$.\n- $a_1 = [2, 1, 3]$, $a_2 = [3, 1, 2]$ — that is not a valid chain. The first permutation should always be $[1, 2, 3]$ for $n = 3$.\n- $a_1 = [1, 2, 3]$, $a_2 = [1, 3, 2]$, $a_3 = [1, 2, 3]$ — that is not a valid chain. From $a_2$ to $a_3$, the elements on positions $2$ and $3$ get swapped but the fixedness increase from $1$ to $3$.\n- $a_1 = [1, 2, 3]$, $a_2 = [3, 2, 1]$, $a_3 = [3, 1, 2]$ — that is a valid chain of length $3$. From $a_1$ to $a_2$, the elements on positions $1$ and $3$ get swapped, the fixedness decrease from $3$ to $1$. From $a_2$ to $a_3$, the elements on positions $2$ and $3$ get swapped, the fixedness decrease from $1$ to $0$.\n\nFind the longest permutation chain. If there are multiple longest answers, print any of them.",
    "tutorial": "Ideally, we would want the fixedness values to be $n, n - 1, n - 2, \\dots, 0$. That would make a chain of length $n + 1$. However, it's impossible to have fixedness of $n - 1$ after one swap. The first swap always makes a permutation with fixedness $n - 2$. Okay, how about $n, n - 2, n - 3, \\dots, 0$ then? That turns out to always be achievable. For example, swap elements $1$ and $2$, then elements $2$ and $3$, then $3$ and $4$ and so on. Overall complexity: $O(n^2)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\tp = [i + 1 for i in range(n)]\n\tprint(n)\n\tfor i in range(n):\n\t\tprint(*p)\n\t\tif i < n - 1:\n\t\t\tp[i], p[i + 1] = p[i + 1], p[i]",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1716",
    "index": "C",
    "title": "Robot in a Hallway",
    "statement": "There is a grid, consisting of $2$ rows and $m$ columns. The rows are numbered from $1$ to $2$ from top to bottom. The columns are numbered from $1$ to $m$ from left to right.\n\nThe robot starts in a cell $(1, 1)$. In one second, it can perform either of two actions:\n\n- move into a cell adjacent by a side: up, right, down or left;\n- remain in the same cell.\n\nThe robot is not allowed to move outside the grid.\n\nInitially, all cells, except for the cell $(1, 1)$, are locked. Each cell $(i, j)$ contains a value $a_{i,j}$ — the moment that this cell gets unlocked. The robot can only move into a cell $(i, j)$ if at least $a_{i,j}$ seconds have passed before the move.\n\nThe robot should visit all cells \\textbf{without entering any cell twice or more} (cell $(1, 1)$ is considered entered at the start). It can finish in any cell.\n\nWhat is the fastest the robot can achieve that?",
    "tutorial": "Let's first consider the possible paths across the grid that visit all cells. You can immediately think of two of them. The first one is: go right to the wall, turn into the other row and return. Let's call it a hook. The second one is: go down, go right, go up, go right and so on. Let's call it a snake. Turns out, these two are basically the two extremes of all paths. You can start with a snake and turn into a hook when you wish. You can see that once you move right twice in a row, you can only continue with a hook. And as long as you didn't move right twice, you are just doing a snake. Let's fix some path across the grid. What will its minimum time be? Calculate it iteratively. If you want to enter the next cell, and it's still locked, wait until it isn't. So there are some seconds of waiting (possibly, zero) before each cell. However, why not instead do the following. Let's calculate the sum of waiting time required and wait for that amount of seconds before starting to move. All cells will be visited at the same time as before or even later. Thus, they will surely be unlocked if they were in the original plan. So the goal is to calculate the minimum amount of time required to wait in the start, then add the movement time to it. Once again, the path is fixed. Let the $k$-th cell of the path be $(x_k, y_k)$. If you start after waiting for $t$ seconds, then you reach the $k$-th cell at time $t + k$ ($k$ is $1$-indexed). Thus, the $k$-th cell should have $a_{x_k, y_k} \\le t + k - 1$. If all cells satisfy this condition, then the path can be done after waiting for $t$ seconds at the start. Let's rewrite it into $t \\ge a_{x_k, y_k} - k + 1$. So, the condition tells us that $t$ should be greater or equal than this value for all cells. In other words, $t$ should be greater or equal than the maximum of the values over all cells. Study the formula. Imagine we have some path with a known length and want to append a cell to it. That's pretty simple. Just update the maximum with the value with the corresponding cell and increase the length. What if we wanted to prepend a cell to it? Turns out, it's not that hard as well. Every cell in the path gets its value $k$ increased by $1$. From the formula, you can see that this actually decreases the value of each cell by $1$. So the maximum decreases by $1$ as well. The only thing left is to update the maximum with the value of the new first cell. Well, and increase the length again. Finally, let's learn how to choose the best path. We can iterate over the length of the snake part. The hook part is determined uniquely. It's easy to maintain the maximum on the snake. Just append the new cell to the path. How to glue up the hook part to that? Well, actually, realize that the formula allows us to glue up two paths into one. Let path $1$ have length $n_1$ and maximum $\\mathit{mx}_1$ and path $2$ have length $n_2$ and maximum $\\mathit{mx}_2$. To make path $2$ start after path $1$, we just decrease its maximum by $n_1$. The resulting path has length $n_1 + n_2$ and maximum $\\max(\\mathit{mx}_1, \\mathit{mx}_2 - n_1)$. Let's look closer into what the hooks look like. They start in some column $j$, traverse all the way right, then left up to the same column $j$. If the snake part took both cells in its last column, then that's it. Otherwise, the hook has to take the final cell in the last column - column $j-1$. If we manage to precalculate something for hooks that start in some column $j$ and end in column $j$, then we will be able to use that. Appending the final cell is not a hard task, since we know its index in the path ($k = 2 \\cdot m$). Let $\\mathit{su}_{i,j}$ be the waiting time required for a hook that starts in cell $(i, j)$ and ends in a cell $(3 - i, j)$ as if the path started with the hook (cell $(i, j)$ is the first one). $\\mathit{su}_{i,j}$ can be calculated from $\\mathit{su}_{i,j+1}$. Prepend it with a cell $(i, j)$ and append it with a cell $(3 - i, j)$. The only thing left is to find the best answer. I found the most convenient to start with a snake of length $1$ (only cell $(1, 1)$) and progress it two steps at the time: update the answer; progress the snake to the other cell of the current column; update the answer; progress the snake into the next column. Overall complexity: $O(m)$ per testcase.",
    "code": "INF = 2 * 10**9\n\nfor _ in range(int(input())):\n\tm = int(input())\n\ta = [[int(x) for x in input().split()] for i in range(2)]\n\tsu = [[-INF for j in range(m + 1)] for i in range(2)]\n\tfor i in range(2):\n\t\tfor j in range(m - 1, -1, -1):\n\t\t\tsu[i][j] = max(su[i][j + 1] - 1, a[i][j], a[i ^ 1][j] - (2 * (m - j) - 1))\n\tpr = a[0][0] - 1\n\tans = INF\n\tfor j in range(m):\n\t\tjj = j & 1\n\t\tans = min(ans, max(pr, su[jj][j + 1] - 2 * j - 1, a[jj ^ 1][j] - 2 * m + 1))\n\t\tpr = max(pr, a[jj ^ 1][j] - 2 * j - 1)\n\t\tans = min(ans, max(pr, su[jj ^ 1][j + 1] - 2 * j - 2))\n\t\tif j < m - 1:\n\t\t\tpr = max(pr, a[jj ^ 1][j + 1] - 2 * j - 2)\n\tprint(ans + 2 * m)",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "ternary search"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1716",
    "index": "D",
    "title": "Chip Move",
    "statement": "There is a chip on the coordinate line. Initially, the chip is located at the point $0$. You can perform any number of moves; each move increases the coordinate of the chip by some positive integer (which is called the length of the move). The length of the first move you make should be divisible by $k$, the length of the second move — by $k+1$, the third — by $k+2$, and so on.\n\nFor example, if $k=2$, then the sequence of moves may look like this: $0 \\rightarrow 4 \\rightarrow 7 \\rightarrow 19 \\rightarrow 44$, because $4 - 0 = 4$ is divisible by $2 = k$, $7 - 4 = 3$ is divisible by $3 = k + 1$, $19 - 7 = 12$ is divisible by $4 = k + 2$, $44 - 19 = 25$ is divisible by $5 = k + 3$.\n\nYou are given two positive integers $n$ and $k$. Your task is to count the number of ways to reach the point $x$, starting from $0$, for every $x \\in [1, n]$. The number of ways can be very large, so print it modulo $998244353$. Two ways are considered different if they differ as sets of visited positions.",
    "tutorial": "Let's calculate dynamic programming $dp_{s, i}$ - the number of ways to achieve $i$ in $s$ moves. From the state $(s, i)$, you can make a transition to the states $(s+1, j)$, where $i < j$ and $j - i$ is divisible by $k + s$. Let's try to estimate the maximum number of moves, because it seems that there can't be very many of them. For $m$ moves, the minimum distance by which a chip can be moved is $k+ (k + 1) + \\dots + (k + m - 1)$ or $\\frac{(k + k + m - 1) \\cdot m}{2}$. From here one can see that the maximum number of transitions does not exceed $\\sqrt{2n}$ (maximum at $k=1$). So it remains to make transitions in dynamic programming faster than $O(n)$ from a single state for a fast enough solution. Let's use the fact that $j \\equiv i \\pmod{k+s}$. Let's iterate over the value of $j$ and maintain the sum of dynamic programming values with smaller indices for each remainder modulo $k + s$ in a separate array. The final complexity of such a solution is $O(n\\sqrt{n})$. It remains to solve the memory problem, because with the existing limits, it is impossible to save the entire $dp$ matrix of size $n^{\\frac{3}{2}}$. However, this is easy to solve if you notice that only the previous layer is used for transitions in dp, i.e. it is enough to store $dp_s$ to calculate $dp_{s+1}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint main() {\n  int n, k;\n  cin >> n >> k;\n  vector<int> dp(n + 1), ans(n + 1);\n  dp[0] = 1;\n  for (int mn = 0; mn + k <= n; mn += k++) {\n    vector<int> sum(k);\n    for (int i = mn; i <= n; ++i) {\n      int cur = dp[i];\n      dp[i] = sum[i % k];\n      (sum[i % k] += cur) %= MOD;\n      (ans[i] += dp[i]) %= MOD;\n    }\n  }\n  for (int i = 1; i <= n; ++i) cout << ans[i] << ' ';\n}",
    "tags": [
      "brute force",
      "dp",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1716",
    "index": "E",
    "title": "Swap and Maximum Block",
    "statement": "You are given an array of length $2^n$. The elements of the array are numbered from $1$ to $2^n$.\n\nYou have to process $q$ queries to this array. In the $i$-th query, you will be given an integer $k$ ($0 \\le k \\le n-1$). To process the query, you should do the following:\n\n- for every $i \\in [1, 2^n-2^k]$ \\textbf{in ascending order}, do the following: if the $i$-th element was already swapped with some other element \\textbf{during this query}, skip it; otherwise, swap $a_i$ and $a_{i+2^k}$;\n- after that, print the maximum sum over all contiguous subsegments of the array (including the empty subsegment).\n\nFor example, if the array $a$ is $[-3, 5, -3, 2, 8, -20, 6, -1]$, and $k = 1$, the query is processed as follows:\n\n- the $1$-st element wasn't swapped yet, so we swap it with the $3$-rd element;\n- the $2$-nd element wasn't swapped yet, so we swap it with the $4$-th element;\n- the $3$-rd element was swapped already;\n- the $4$-th element was swapped already;\n- the $5$-th element wasn't swapped yet, so we swap it with the $7$-th element;\n- the $6$-th element wasn't swapped yet, so we swap it with the $8$-th element.\n\nSo, the array becomes $[-3, 2, -3, 5, 6, -1, 8, -20]$. The subsegment with the maximum sum is $[5, 6, -1, 8]$, and the answer to the query is $18$.\n\nNote that the queries actually \\textbf{change the array}, i. e. after a query is performed, the array does not return to its original state, and the next query will be applied to the modified array.",
    "tutorial": "Let's carefully analyze the operation denoted in the query. Since the length of the array is always divisible by $2^{k+1}$, every element will be swapped with some other element. The elements can be split into two groups - the ones whose positions increase by $2^k$, and the ones whose positions decrease by $2^k$. Let's find some trait of the elements which will allow us to distinguish the elements of one group from the elements of the other group. The first $2^k$ elements will be shifted to the right, the next $2^k$ elements will be shifted to the left, the next $2^k$ elements will be shifted to the right, etc. If we look at the binary representations of integers $0, 1, \\dots, n-1$, then we can see that the first $2^k$ elements have $0$ in the $k$-th bit, the next $2^k$ elements have $1$ in the $k$-th bit, the next $2^k$ elements have $0$ in the $k$-th bit, and so on. So, if we consider the positions of elements as $0$-indexed, then the operation can be described as follows: \"Let the position of the element be $i$. If the $k$-th bit in $i$ is $0$, $i$ gets increased by $2^k$, otherwise $i$ gets decreased by $2^k$\". What does it look like? Actually, it is just $i \\oplus 2^k$ (where $\\oplus$ denotes XOR). So, each query can be represented as \"swap $a_i$ with $a_{i \\oplus x}$ for some integer $x$\". The combination of two queries can also be represented with a single query; in fact, the state of the array can be denoted as the XOR of all $2^k$ from the previous queries. Now, let's try to solve the following problem: for every $x \\in [0, 2^n-1]$, calculate the maximum sum of subsegment if every element $a_i$ is swapped with $a_{i \\oplus x}$. To solve this problem, we can use a segment tree. First of all, we need to understand how to solve the problem of finding the maximum sum on subsegment using a segment tree. To do this, we should store the following four values in each vertex of the segment tree: $\\mathit{sum}$ - the sum of elements on the segment denoted by the vertex; $\\mathit{pref}$ - the maximum sum of elements on the prefix of the segment denoted by the vertex; $\\mathit{suff}$ - the maximum sum of elements on the suffix of the segment denoted by the vertex; $\\mathit{ans}$ - the answer on the segment. If some vertex of the segment tree has two children, these values for it can be easily calculated using the values from the children. So, we can \"glue\" two segments represented by the vertices together, creating a new vertex representing the concatenation of these segments. Okay, but how do we apply XOR to this? For every vertex of the segment tree, let's create several versions; the $x$-th version of the vertex $v$ represents the segment corresponding to this vertex if we apply swapping query with $x$ to it. For a vertex $v$ representing the segment of length $2^k$, we can use the following relation to get all its versions (here, we denote $t(v, x)$ as the $x$-th version of $v$, and $v_l$ and $v_r$ as the children of $v$): if $x \\ge 2^{k-1}$, then $t(v, x) = \\mathit{combine}(t(v_r, x-2^{k-1}), t(v_l, x-2^{k-1}))$; else $t(v, x) = \\mathit{combine}(t(v_l, x), t(v_r, x))$; The function $\\mathit{combine}$ here denotes the \"glueing together\" of two vertices we described above. Now let's try to analyze how many versions of each vertex we need. For the root, we will need all $2^n$ versions. For its children, we need only $2^{n-1}$ versions. For the children of the children of the root, we need only $2^{n-2}$ versions, and so on; so, overall, the total number of versions is only $O(n 2^n)$, and each version can be constructed in $O(1)$, so the solution works in $O(n 2^n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;     \nconst int K = 18;\n\nstruct node\n{\n    long long sum, pref, suff, ans;\n    \n    node(const node& l, const node& r)\n    {                                                                                          \n        sum = l.sum + r.sum;\n        pref = max(l.pref, l.sum + r.pref);\n        suff = max(r.suff, r.sum + l.suff);\n        ans = max(max(l.ans, r.ans), l.suff + r.pref);\n    }\n\n    node(int x)\n    {\n        sum = x;\n        pref = suff = ans = max(x, 0);\n    }\n\n    node() {};\n};\n\nint a[1 << K];\nvector<node> tree[2 << K];  \n\nvoid build(int v, int l, int r)\n{\n    tree[v].resize(r - l);\n    if(l == r - 1)\n    {\n        tree[v][0] = node(a[l]);  \n    }\n    else\n    {\n        int m = (l + r) / 2;\n        build(v * 2 + 1, l, m);\n        build(v * 2 + 2, m, r);\n        for(int i = 0; i < m - l; i++)\n        {\n            tree[v][i] = node(tree[v * 2 + 1][i], tree[v * 2 + 2][i]);\n            tree[v][i + (m - l)] = node(tree[v * 2 + 2][i], tree[v * 2 + 1][i]);    \n        }\n    }\n}\n\nint main()\n{            \n    int n;\n    scanf(\"%d\", &n);\n    int m = (1 << n);\n    for(int i = 0; i < m; i++)\n    {\n        scanf(\"%d\", &a[i]);\n    }\n    build(0, 0, m);\n    int q;\n    scanf(\"%d\", &q);\n    int cur = 0;\n    for(int i = 0; i < q; i++)\n    {\n        int x;\n        scanf(\"%d\", &x);\n        cur ^= (1 << x);\n        printf(\"%lld\\n\", tree[0][cur].ans);\n    }\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1716",
    "index": "F",
    "title": "Bags with Balls",
    "statement": "There are $n$ bags, each bag contains $m$ balls with numbers from $1$ to $m$. For every $i \\in [1, m]$, there is exactly one ball with number $i$ in each bag.\n\nYou have to take exactly one ball from each bag (all bags are different, so, for example, taking the ball $1$ from the first bag and the ball $2$ from the second bag is not the same as taking the ball $2$ from the first bag and the ball $1$ from the second bag). After that, you calculate the number of balls with \\textbf{odd} numbers among the ones you have taken. Let the number of these balls be $F$.\n\nYour task is to calculate the sum of $F^k$ over all possible ways to take $n$ balls, one from each bag.",
    "tutorial": "The main idea of this problem is to use a technique similar to \"contribution to the sum\". We will model the value of $F^k$ as the number of tuples $(i_1, i_2, \\dots, i_k)$, where each element is an index of a bag from which we have taken an odd ball. Let $G(t)$ be the number of ways to take balls from bags so that all elements from tuple $t$ are indices of bags with odd balls; then, the answer to the problem can be calculated as the sum of $G(t)$ over all possible tuples $t$. First of all, let's obtain a solution in $O(k^2)$ per test case. We need to answer the following questions while designing a solution to the problem: How do we calculate $G(t)$ for a given tuple? How do we group tuples and iterate through them? The first question is not that difficult. Every element from the tuple $(i_1, i_2, \\dots, i_k)$ should be an index of a bag from which we have taken an odd ball; so, for every bag appearing in the tuple, we can take only a ball with odd number; but for every bag not appearing in the tuple, we can choose any ball. So, if the number of distinct elements in a tuple is $d$, then $G(t)$ for the tuple can be calculated as $\\lceil \\frac{m}{2}\\rceil^d \\cdot m^{n-d}$. This actually gives as a hint for the answer to the second question: since $G(t)$ depends on the number of distinct elements in the tuple, let's try to group the tuples according to the number of distinct elements in them. So, the answer will be calculated as $\\sum\\limits_{i=1}^{k} H(i) \\lceil \\frac{m}{2}\\rceil^i \\cdot m^{n-i}$, where $H(i)$ is the number of tuples with exactly $i$ different elements. How do we calculate $H(i)$? First of all, if $i > n$, then $H(i)$ is obviously $0$. Otherwise, we can use the following recurrence: let $dp_{i,j}$ be the number of tuples of $i$ elements with $j$ distinct ones; then: if $i = 1$ and $j = 1$, $dp_{i,j} = n$ (for a tuple with one element, there are $n$ ways to choose it); if $i = 1$ and $j \\ne 1$, $dp_{i,j} = 0$; if $i > 1$ and $j = 1$, $dp_{i,j} = dp_{i-1,j}$ (there is only one distinct element, and it was already chosen); if $i > 1$ and $j > 1$, $dp_{i,j} = dp_{i-1,j} \\cdot j + dp_{i-1,j-1} \\cdot (n-j+1)$ (we either add an element which did not belong to the tuple, and there are $n-j+1$ ways to choose it, or we add an already existing element, and there are $j$ ways to choose it). Obviously, this recurrence can be calculated in $O(k^2)$ with dynamic programming, so we get a solution in $O(k^2)$ per test case. How do we speed this up? Let's change the way we calculate $H(i)$. Instead of considering tuples with values from $1$ to $n$, we will consider only tuples where values are from $1$ to $k$, and the first appearance of a value $i$ is only after the first appearance of the value $i-1$. So, these tuples actually represent a way to split a set of integers $\\{1, 2, \\dots, n\\}$ into several subsets; so they are the Stirling numbers of the second kind, and we can calculate them in $O(k^2)$ with dynamic programming outside of processing the test cases. How do we calculate $H(i)$ using these values? If we use $i$ distinct integers as the elements of the tuple, there are $n$ ways to choose the first one, $n-1$ ways to choose the second one, etc. - so $H(i) = S(k,i) \\cdot \\prod \\limits_{j=0}^{i-1} (n-j)$, where $S(k, i)$ is the Stirling number of the second kind for the parameters $k$ and $i$. We can maintain the values of $\\prod \\limits_{j=0}^{i-1} (n-j)$ and $\\lceil \\frac{m}{2}\\rceil^i \\cdot m^{n-i}$ while iterating on $i$ from $1$ to $k$, and that gives us a way to solve the problem in $O(k)$ per test case. Overall complexity: $O(k^2)$ for precalculation and $O(k)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;   \nconst int N = 2043;\n\nint dp[N][N];\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}   \n\nint sub(int x, int y)\n{\n    return add(x, -y);\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y > 0)\n    {\n        if(y % 2 == 1) z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nint inv(int x)\n{\n    return binpow(x, MOD - 2);\n}\n\nint divide(int x, int y)\n{\n    return mul(x, inv(y));\n}\n\nvoid precalc()\n{\n    dp[1][1] = 1;\n    for(int i = 1; i < N - 1; i++)\n        for(int j = 1; j <= i; j++)\n        {\n            dp[i + 1][j] = add(dp[i + 1][j], mul(dp[i][j], j));\n            dp[i + 1][j + 1] = add(dp[i + 1][j + 1], dp[i][j]);\n        }\n}\n\nint solve(int n, int m, int k)\n{\n    int way1 = (m / 2) + (m % 2);\n    int curA = n;\n    int ans = 0;\n    int ways_chosen = way1;\n    int ways_other = binpow(m, n - 1);\n    int invm = inv(m);\n    for(int i = 1; i <= k; i++)\n    {\n        ans = add(ans, mul(mul(curA, dp[k][i]), mul(ways_chosen, ways_other)));\n        curA = mul(curA, sub(n, i));\n        ways_chosen = mul(way1, ways_chosen);\n        ways_other = mul(ways_other, invm);\n    }  \n    return ans;\n}   \n\nint main()\n{\n    int t;\n    cin >> t;\n    precalc();\n    for(int i = 0; i < t; i++)\n    {\n        int n, m, k;\n        cin >> n >> m >> k;\n        cout << solve(n, m, k) << endl;\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1717",
    "index": "A",
    "title": "Madoka and Strange Thoughts",
    "statement": "Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers $(a, b)$ exist, where $1 \\leq a, b \\leq n$, for which $\\frac{\\operatorname{lcm}(a, b)}{\\operatorname{gcd}(a, b)} \\leq 3$.\n\nIn this problem, $\\operatorname{gcd}(a, b)$ denotes the greatest common divisor of the numbers $a$ and $b$, and $\\operatorname{lcm}(a, b)$ denotes the smallest common multiple of the numbers $a$ and $b$.",
    "tutorial": "Notice that only the following pairs of numbers are possible: $(x, x)$, $(x, 2 \\cdot x)$, and $(x, 3 \\cdot x)$. Proof:Let $d = gcd(a, b)$. Now notice that it's impossible that $a = k \\cdot d$ for some $k > 4$, because otherwise $lcm$ will be at least $k \\cdot d > 3 \\cdot d$. Therefore the only possible cases are the pairs listed above and $(2 \\cdot d, 3 \\cdot d)$, but in the latter case we have $lcm = 6 \\cdot d$. The number of the pairs of the first kind is $n$, of the second kind is $2 \\cdot \\lfloor \\frac{n}{2} \\rfloor$, and of the third kind is $2 \\cdot \\lfloor \\frac{n}{3} \\rfloor$ (the factor $2$ in the latter two formulae arises from the fact that pairs are ordered). Therefore, the answer to the problem is $n + 2 \\cdot \\left( \\lfloor \\frac{n}{2} \\rfloor + \\lfloor \\frac{n}{3} \\rfloor \\right)$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1717",
    "index": "B",
    "title": "Madoka and Underground Competitions",
    "statement": "Madoka decided to participate in an underground sports programming competition. And there was exactly one task in it:\n\nA square table of size $n \\times n$, where \\textbf{$n$ is a multiple of $k$}, is called good if only the characters '.' and 'X' are written in it, as well as in any subtable of size $1 \\times k$ or $k \\times 1$, there is at least one character 'X'. In other words, among any $k$ consecutive vertical or horizontal cells, there must be at least one containing the character 'X'.\n\nOutput any good table that has the \\textbf{minimum} possible number of characters 'X', and also the symbol 'X' is written in the cell $(r, c)$. Rows are numbered from $1$ to $n$ from top to bottom, columns are numbered from $1$ to $n$ from left to right.",
    "tutorial": "Notice that the answer to the problem is at least $\\frac{n^2}{k}$, because you can split the square into so many non-intersecting rectangles of dimensions $1 \\times k$. So let's try to paint exactly so many cells and see if maybe it's always possible. For simplicity, let's first solve the problem without necessarily painting $(r, c)$. In this case, we're looking for something like a chess coloring, which is a diagonal coloring. Let's number the diagonals from the \"lowest\" to the \"highest\". Notice that every $1 \\times k$ and $k \\times 1$ subrectangle intersects exactly $k$ consecutive diagonals, so we can paint every $k$-th diagonal to obtain the required answer: every such subrectangle will contain exactly one painted cell. To add the $(r, c)$ requirement back, notice that $(r, c)$ lies on the diagonal number $r + c$. (Because if you trace any path from $(0, 0)$ to $(r, c)$ with non-decreasing coordinates, going one cell upwards or rightwards increases exactly one of the coordinates by one, and also increases the number of the diagonal by one). Therefore, all we need to do is paint the cells whose coordinates satisfy $(x + y) \\% k = (r + c) \\% k$",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1717",
    "index": "C",
    "title": "Madoka and Formal Statement",
    "statement": "Given an array of integer $a_1, a_2, \\ldots, a_n$. In one operation you can make $a_i := a_i + 1$ if $i < n$ and $a_i \\leq a_{i + 1}$, or $i = n$ and $a_i \\leq a_1$.\n\nYou need to check whether the array $a_1, a_2, \\ldots, a_n$ can become equal to the array $b_1, b_2, \\ldots, b_n$ in some number of operations (possibly, zero). Two arrays $a$ and $b$ of length $n$ are called equal if $a_i = b_i$ for all integers $i$ from $1$ to $n$.",
    "tutorial": "Firstly, we obviously require $a_i \\le b_i$ to hold for all $i$. With that out of our way, let's consider non-trivial cases. Also let $a_{n+1} = a_1, b_{n+1} = b_1$ cyclically. For each $i$, we require that either $a_i = b_i$ or $b_i \\leq b_{i + 1} + 1$ holds. That's because if we increment $a_i$ at least once, we had $a_i = b_i - 1$ and $a_{i + 1} \\le b_{i + 1}$ before the last increment of $a_i$, and from here it's just a matter of simple algebraic transformations. Now let's prove these two conditions are enough. Let $i$ be the index of the minimal element of $a$ such that $a_i < b_i$ (i.e. the smallest element that's not ready yet). Notice that in this case we can, in fact, assign $a_i := a_i+1$, because $a_i \\leq b_i \\leq b_{i + 1} + 1$ holds, and now we're one step closer to the required array. It's easy to continue this proof by induction.",
    "tags": [
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1717",
    "index": "D",
    "title": "Madoka and The Corruption Scheme",
    "statement": "Madoka decided to entrust the organization of a major computer game tournament \"OSU\"!\n\nIn this tournament, matches are held according to the \"Olympic system\". In other words, there are $2^n$ participants in the tournament, numbered with integers from $1$ to $2^n$. There are $n$ rounds in total in the tournament. In the $i$-th round there are $2^{n - i}$ matches between two players (one of whom is right, the other is left), after which the winners go further along the tournament grid, and the losing participants are eliminated from the tournament. Herewith, the relative order in the next round does not change. And the winner of the tournament — is the last remaining participant.\n\nBut the smaller the participant's number, the more he will pay Madoka if he wins, so Madoka wants the participant with the lowest number to win. To do this, she can arrange the participants in the first round as she likes, and also determine for each match who will win — the participant on the left or right.\n\nBut Madoka knows that tournament sponsors can change the winner in matches no more than $k$ times. (That is, if the participant on the left won before the change, then the participant on the right will win after the change, and if the participant on the right won, then the participant on the left will win after the change).\n\n\\begin{center}\n{\\small So, the first image shows the tournament grid that Madoka made, where the red lines denote who should win the match. And the second one shows the tournament grid, after one change in the outcome of the match by sponsors (a match between $1$ and $3$ players).}\n\\end{center}\n\nPrint the minimum possible number of the winner in the tournament, which Madoka can get regardless of changes in sponsors. But since the answer can be very large, output it modulo $10^9 + 7$. Note that we need to minimize the answer, and only then take it modulo.",
    "tutorial": "The problem can be reformulated as follows. We've got a complete binary tree with $2^n$ leaves. There's a marked edge from each intermediate node to one of its children. The winner is the leaf reachable from the root via marked edges. Changes modify the outgoing marked edge of a node. Now it should be fairly obvious that there's no reason to change more than one node per level, because only one node matters per level--the one on the path from the root to the answer node. So, the winner only depends on the subset of levels we perform changes on, and vice versa: different subsets always yield different winners. Sponsors can change exactly $i$ nodes in $\\binom{n}{i}$ ways. Summing this over $i$, we get $\\sum_{i=0}^{\\min(n, k)} \\binom{n}{i}$. Call this number $m$. $m$ is the number of winners the sponsors choose between--let's call them candidates for brevity. It's easy to see that $m$ is the answer to the problem, because a) sponsors can guarantee the winner is at least $m$, as, independent of the list of candidate winners \"provided\" by Madoka, at least one of them must be at least $m$, and b) Madoka can guarantee the winner is at most $m$ by firstly marking edges arbitrarily, then computing the list of candidate nodes, and only then fill them with numbers from $1$ to $m$ (and the other nodes arbitrarily).",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1717",
    "index": "E",
    "title": "Madoka and The Best University",
    "statement": "Madoka wants to enter to \"Novosibirsk State University\", but in the entrance exam she came across a very difficult task:\n\nGiven an integer $n$, it is required to calculate $\\sum{\\operatorname{lcm}(c, \\gcd(a, b))}$, for all triples of positive integers $(a, b, c)$, where $a + b + c = n$.\n\nIn this problem $\\gcd(x, y)$ denotes the greatest common divisor of $x$ and $y$, and $\\operatorname{lcm}(x, y)$ denotes the least common multiple of $x$ and $y$.\n\nSolve this problem for Madoka and help her to enter to the best university!",
    "tutorial": "Let's bruteforce $c$, then we have $gcd(a, b) = gcd(a, a + b) = gcd(a, n - c)$. This means that $gcd(a, b)$ divides $n - c$, so let's just go through all divisors of $n - c$. For every factor $d$, the count of pairs $(a, b)$ satisfying $a + b = n - c$ and $gcd(a, b) = d$ is $\\phi (\\frac{n - c}{d})$, because we need $d$ to divide $a$ and be coprime with $\\frac{n - c}{d}$, so that the $gcd$ is equal to $d$. Therefore, the answer to the problem is $\\sum{lcm(c, d) * \\phi{\\frac{n - c}{d}}}$, where $1 \\leq c \\leq n - 2$ and $d$ is a factor of $n - c$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1717",
    "index": "F",
    "title": "Madoka and The First Session",
    "statement": "Oh no, on the first exam Madoka got this hard problem:\n\nGiven integer $n$ and $m$ pairs of integers ($v_i, u_i$). Also there is an array $b_1, b_2, \\ldots, b_n$, \\textbf{initially filled with zeros}.\n\nThen for each index $i$, where $1 \\leq i \\leq m$, perform either $b_{v_i} := b_{v_i} - 1$ and $b_{u_i} := b_{u_i} + 1$, or $b_{v_i} := b_{v_i} + 1$ and $b_{u_i} := b_{u_i} - 1$. Note that exactly one of these operations should be performed for every $i$.\n\nAlso there is an array $s$ of length $n$ consisting of $0$ and $1$. And there is an array $a_1, a_2, \\ldots, a_n$, where it is guaranteed, that if $s_i = 0$ holds, then $a_i = 0$.\n\nHelp Madoka and determine whenever it is possible to perform operations in such way that for every $i$, where $s_i = 1$ it holds that $a_i = b_i$. If it possible you should also provide Madoka with a way to perform operations.",
    "tutorial": "Let's reformulate the problem in terms of graphs. We are given an undirected graph and we are asked to determine edge directions, subject to fixed indegree minus outdegree (hereinafter balance) values for some vertices. It is tempting to think of this as a flow problem: edges indicate pipes with capacity of 1, vertices are producers or consumers of flow, and vertices with fixed differencies produce or consume an exact amount of flow. Except that's not quite an equivalent problem: a maxflow algorithm will find a flow, i.e. an orientation of edges, but it might just ignore some edges if it feels like it. We need to overcome this somehow by introducing incentive to use all edges. To do this, forget about the \"edges are edges, vertices are vertices\" idea for a while. Create an imaginary source and add a pipe with capacity 1 to every edge of the original graph. Technically, this is interpreting edges of the original graph as vertices of the flow graph. Non-technically, I like to interpret this like magically spawning flow into the middle of the edge. Now, the flow appearing in the edge has to actually go somewhere if we want the maxflow algorithm to treat it like a treasure it wants to increase. Let's just add two pipes: from the edge to vertex $u_i$ and from the edge to vertex $v_i$, because where else would it go? (technically, any capacity works, but let's use 1 for simplicity) This has a nice side effect of determining the orientation of the edge: if the flow from the edge goes into $u_i$, it's as if it was oriented from $v_i$ to $u_i$, and vice versa. A small problem is that this changes the semantics of the edge orientation somewhat. In the original problem, $u_i \\to v_i$ incremented $v_i$ and decremented $u_i$. In the new formulation, only $v_i$ is incremented, so we need to transform the requirements $a_v$ on balances into requirements $b_v$ on indegrees: $b_v = \\frac{a_v + \\mathrm{deg} v}{2}$ (and we need to check that the numerator is even and non-negative, otherwise the answer is NO). How do we enforce the indegree requirements? For all vertices with $s_v = 1$, add a pipe from the vertex $v$ to an imaginary sink with capacity $b_v$. We expect all these pipes to be satiated. What about vertices with $s_v = 0$? Unfortunately, we can't just add a pipe from the vertex $v$ to an imaginary sink with capacity $\\infty$, because if you have an edge with $s_v = 0$ and $s_u = 1$, the maxflow algorithm doesn't have any incentive to let the flow go to $u$ instead of $v$, so the pipe from $u$ to the sink might not get satiated and we might erroneously report a negative answer. How do we require certain pipes to be satiated? We could theoretically use a push-relabel algorithm, but in this case we can use something much simpler. The sum of capacities of all pipes from the imaginary source is $m$. We expect them all to be satiated, so this is the total flow we're expecting. The sum of capacities of all pipes to the imaginary sink we want to satiate is $\\sum_v b_v$. Therefore, there's a surplus of flow of exactly $\\Delta = m - \\sum_v b_v$ (if it's negative, the answer is NO). So: create an intermediate vertex, add a pipe of capacity $\\infty$ from each vertex with $s_v = 0$ to this intermediate vertex, and a pipe from this intermediate vertex to the imaginary sink with capacity $\\Delta$. This will stop the algorithm from relying too much on non-fixed vertices. Run a maxflow algorithm. Check that every pipe from the source to an edge and every pipe from a vertex to the sink is satiated, or, alternatively, the maxflow is exactly $m$. If this does not hold, the answer is NO. If this holds, the answer is YES and the edge orientation can be restored by checking which of the two pipes from an edge is satiated. Is this fast? That depends on the algorithm heavily. Firstly, you can use the Edmonds-Karp algorithm. It works in $\\mathcal{O}(FM)$, where $F$ is the maxflow and $M$ is the number of pipes. The former is $m$ and the latter is $n + m$, so we've got $\\mathcal{O}((n + m) m)$, which is just fine. Secondly, you can use Dinic's algorithm, which is typically considered an improved version of Edmonds-Karp's, but is worse in some cases. It improves the number of rounds from $F$ to $\\mathcal{O}(N)$, where $N$ is the number of vertices in the network, which doesn't help in this particular problem, sacrificing the complexity of a single phase, increasing it to $\\mathcal{O}(NM)$, which is a disaster waiting to happen. Lots of people submitted Dinic's instead of Edmonds-Karp's. I don't know why, perhaps they just trained themselves to use Dinic's everywhere and didn't notice the unfunny joke here. Luckily for them, Dinic's algorithm still works. You might've heard it works in $\\mathcal{O}(M N^{2/3})$ for unit-capacity networks, where $M$ is the number of pipes and $N$ is the number of vertices, which translates to $\\mathcal{O}((n + m) n^{2/3})$ in our case, which would be good enough if the analysis held. Our network is not unitary, but it's easy to see how to make it into one. We use non-unit capacities in three cases: When we enforce the indegree, we add a pipe with capacity $b_v$ from the vertex to the sink. We can replace it with $b_v$ pipes of capacity 1. As $\\sum_v b_v \\le m$, this will not increase the number of pipes by more than $m$, so the complexity holds. Due to how Dinic's algorithm works, replacing a pipe with several pipes of the same total capacity does not slow the algorithm down. Similarly, the pipe from the intermediate vertex to the sink has capacity $\\Delta \\le m$, so we could theoretically replace it with $\\Delta$ unit pipes and the complexity would hold. Finally, when we handle vertices with $s_v = 0$, we add pipes from such vertices to the intermediate vertex with capacity $\\infty$. However, for each such vertex, the maximum used capacity is actually the count $k$ of edges incident with $v$, so the capacity of such pipes could be replaced with $k$. This would obviously have the same effect, and would not slow Dinic down: even if it tries to push more than $k$ through the corresponding backedge, it will quickly rollback, which affects the time taken by a single phase (non-asymptotically), but not the count of phases. As the sum of $k$ is $\\mathcal{O}(m)$, we're fine again.",
    "tags": [
      "constructive algorithms",
      "flows",
      "graph matchings",
      "graphs",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1718",
    "index": "A2",
    "title": "Burenka and Traditions (hard version)",
    "statement": "\\textbf{This is the hard version of this problem. The difference between easy and hard versions is only the constraints on $a_i$ and on $n$. You can make hacks only if both versions of the problem are solved.}\n\nBurenka is the crown princess of Buryatia, and soon she will become the $n$-th queen of the country. There is an ancient tradition in Buryatia — before the coronation, the ruler must show their strength to the inhabitants. To determine the strength of the $n$-th ruler, the inhabitants of the country give them an array of $a$ of exactly $n$ numbers, after which the ruler must turn all the elements of the array into zeros in the shortest time. The ruler can do the following two-step operation any number of times:\n\n- select two indices $l$ and $r$, so that $1 \\le l \\le r \\le n$ and a non-negative integer $x$, then\n- for all $l \\leq i \\leq r$ assign $a_i := a_i \\oplus x$, where $\\oplus$ denotes the bitwise XOR operation. It takes $\\left\\lceil \\frac{r-l+1}{2} \\right\\rceil$ seconds to do this operation, where $\\lceil y \\rceil$ denotes $y$ rounded up to the nearest integer.\n\nHelp Burenka calculate how much time she will need.",
    "tutorial": "Segments of length greater than 2 are not needed. For A1 you can use dynamic programming Dynamic programming where dp[i][v] means the minimum time to make $a_j = 0$ for $j < i$ and $a_i = v$. (Notice that v can be any number from 0 to 8191) There is an answer in which segments of length $2$ does not intersect with segments of length $1$. If $a_l\\oplus a_{l + 1} \\oplus \\ldots \\oplus a_{r} = 0$ is executed for $l, r$, then we can fill this segment with zeros in $r-l$ seconds using only segments of length 2. There is an answer where the time spent is minimal and the lengths of all the segments taken are 1 and 2. because of the segment $l, r, x$ can be replaced to $\\lceil\\frac{r-l+1}{2}\\rceil$ of segments of length 2 and 1, or rather $[l, l + 1, x], [l+ 2, l + 3, x], \\ldots, [r, r, x]$(or $[r-1, r, x]$ if $(l - r + 1)$ even). Note that if $a_l\\oplus a_{l + 1} \\oplus \\ldots \\oplus a_{r} = 0$ is executed for $l, r$, then we can fill the $l, r$ subsections with zeros for $r-l$ seconds with queries $[l, l+1, a_l], [l+1, l+2, a_l \\oplus a_{l+1}], ... [r-1, r, a_l\\oplus a_{l+1} \\oplus \\ldots \\oplus a_r]$. Note that if a segment of length 2 intersects with a segment of length 1, they can be changed to 2 segments of length 1. It follows from all this that the answer consists of segments of length 1 and cover with segments of length 2. Then it is easy to see that the answer is ($n$ minus (the maximum number of disjoint sub-segments with a xor of 0)), because in every sub-segments with a xor of 0 we can spend 1 second less as I waited before. this amount can be calculated by dynamic programming or greedily. Our solution goes greedy with a set and if it finds two equal prefix xors($prefix_l = prefix_r$ means that $a_{l + 1} \\oplus a_{l+2} \\oplus \\ldots \\oplus a_{r} = 0$), it clears the set. 168724728 The complexity of the solution is $O(n \\operatorname{log}(n))$.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    lst = list(map(int, input().split()))\n    res = n\n    for i in range(1, n):\n        lst[i] ^= lst[i - 1]\n    st = set()\n    st.add(0)\n    for i in lst:\n        if i in st:\n            res -= 1\n            st.clear()\n        st.add(i)\n    print(res)",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1718",
    "index": "B",
    "title": "Fibonacci Strings",
    "statement": "In all schools in Buryatia, in the $1$ class, everyone is told the theory of Fibonacci strings.\n\n\"A block is a subsegment of a string where all the letters are the same and are bounded on the left and right by the ends of the string or by letters other than the letters in the block. A string is called a Fibonacci string if, when it is divided into blocks, their lengths in the order they appear in the string form the Fibonacci sequence ($f_0 = f_1 = 1$, $f_i = f_{i-2} + f_{i-1}$), starting from the zeroth member of this sequence. A string is called semi-Fibonacci if it possible to reorder its letters to get a Fibonacci string.\"\n\nBurenka decided to enter the Buryat State University, but at the entrance exam she was given a difficult task. She was given a string consisting of the letters of the Buryat alphabet (which contains exactly $k$ letters), and was asked if the given string is semi-Fibonacci. The string can be very long, so instead of the string, she was given the number of appearances of each letter ($c_i$ for the $i$-th letter) in that string. Unfortunately, Burenka no longer remembers the theory of Fibonacci strings, so without your help she will not pass the exam.",
    "tutorial": "Try to express $n$(the sum of all $c_i$) as $F_1 + F_2 + \\ldots + F_m = n$. Let, $n = F_1 + F_2 + \\ldots + F_m$, then try to find the minimum $x$ starting from which if there is $c_i=x$ there is no answer. $x$ is (the maximum sum of the Fibonacci numbers, among which there are no neighbors) + 1. $x$ is $F_1 + F_3 + F_5 + \\ldots + F_{m} + 1$ for odd $m$ and $F_2 + F_4 + F_6 + \\ldots + F_{m} + 1$ for even. $x$ is $F_{m+1} + 1$ for odd $m$ and $F_{m+1}$ for even. Try to understand if it can happen that there are two different answers in which the letter forming the block of length $F_{m}$ differs. The correct answer is: yes if there is $c_i = F_m$ and $c_j = F_m$ and this is only way. Now, using everything you have understood, write a greedy solution. Try to write a greedy solution. The programmer does not need a second hint, he wrote a greedy solution after the first one. At the beginning, let's check that the number $n$ (the sum of all $c_i$) is representable as the sum of some prefix of Fibonacci numbers, otherwise we will output the answer NO. Let's try to type the answer greedily, going from large Fibonacci numbers to smaller ones. For the next Fibonacci number, let's take the letter with the largest number of occurrences in the string from among those that are not equal to the previous letter taken (to avoid the appearance of two adjacent blocks from the same letter, which cannot be). If there are fewer occurrences of this letter than this number, then the answer is NO. Otherwise, we will put the letter on this Fibonacci number and subtract it from the number of occurrences of this letter.If we were able to dial all the Fibonacci numbers, then the answer is YES. Why does the greedy solution work? Suppose at this step you need to take $F_i$ (I will say take a number from $c_t$, this will mean taking $F_i$ letters $t$ from string), let's look at the maximum $c_x$ now, if it cannot be represented as the sum of Fibonacci numbers up to $F_i$ among which there are no neighbors, then the answer is no. It can be proved that if $c_x > F_{i+1}$, then it is impossible to represent $c_x$. If there is exactly one number greater than or equal to $F_i$ at the step, then there is only one option to take a number, so the greedy solution works. If there are two such numbers and they are equal, then the option to take a number is exactly one, up to the permutation of letters. the greedy solution works again. If there are $c_j \\geq F_i, c_x \\geq F_i, j \\ne x$, then we note that the larger of the numbers $c_j, c_x$ will be greater than $F_i$, if we don't take it, then at the next step this number will be greater than $F_{i+1}$ ($i$ will be 1 less), according to the above proven answer will not be, so, taking the larger of the numbers is always optimal. The complexity of the solution is $O(k \\operatorname{log}(n)\\operatorname{log}(k))$.",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1718",
    "index": "C",
    "title": "Tonya and Burenka-179",
    "statement": "Tonya was given an array of $a$ of length $n$ written on a postcard for his birthday. For some reason, the postcard turned out to be a \\textbf{cyclic array}, so the index of the element located strictly to the right of the $n$-th is $1$. Tonya wanted to study it better, so he bought a robot \"Burenka-179\".\n\nA program for Burenka is a pair of numbers $(s, k)$, where $1 \\leq s \\leq n$, $1 \\leq k \\leq n-1$. Note that $k$ \\textbf{cannot} be equal to $n$. Initially, Tonya puts the robot in the position of the array $s$. After that, Burenka makes \\textbf{exactly} $n$ steps through the array. If at the beginning of a step Burenka stands in the position $i$, then the following happens:\n\n- The number $a_{i}$ is added to the usefulness of the program.\n- \"Burenka\" moves $k$ positions to the right ($i := i + k$ is executed, if $i$ becomes greater than $n$, then $i := i - n$).\n\nHelp Tonya find the maximum possible usefulness of a program for \"Burenka\" if the initial usefulness of any program is $0$.\n\nAlso, Tony's friend Ilyusha asks him to change the array $q$ times. Each time he wants to assign $a_p := x$ for a given index $p$ and a value $x$. You need to find the maximum possible usefulness of the program after each of these changes.",
    "tutorial": "The answer for $k=x$ and $k=\\gcd(x,n)$ is the same. In this problem, a general statement is useful: for any array $c$ of length $m$, $m\\cdot\\operatorname{max}(c_1, c_2, \\ldots, c_m) \\geq c_1 +c_2 +\\ldots+c_m$ is true. Try applying the second hint for $k_1$ and $k_2$ divisible by $k_1$, where $k_1, k_2$ are divisors of $n$. We can consider only $k$ which equals to $\\frac{n}{p}$, where $p$ is a simple divisor of $n$. Let's note that the answer for $k=x$ and $k=\\gcd(x,n)$ is the same. Indeed, for the number $k$, we will visit numbers with indices $s + ik \\mod n$ for $i$ from $0$ to $n-1$ inclusive, from this we can see that the index of the $i$-th number coincides with the index of $i + \\frac{n}{\\gcd(k,n)}$, and if we look at two indexes, the difference between which is $l$ and $l<\\frac{n}{\\gcd(k,n)}$, then they are different, since $k\\cdot l \\mod n \\neq 0$, therefore, the answer is (the sum of numbers with indices $s + ik \\mod n$ for $i$ from $0$ to $\\frac{n}{\\gcd(k,n)}-1$) $\\cdot\\gcd(k,n)$. Now let's prove that the first $\\gcd(k,n)$ numbers are the same for $(s,x)$ and $(s,\\gcd(x,n))$, note that only those indices that have the same remainder as $s$ when divided by $\\gcd(x,n)$ are suitable, but there are only $\\frac{n}{\\gcd(k,n)}$ of such indices, and we proved that we should have $\\frac{n}{\\gcd(k,n)}$ of different indices, so they are all represented once, therefore the answer for $k=x$ and $k=\\gcd(x, n)$ is the same, because the sum consists of the same numbers. So, we need to consider only $k$ being divisors of $n$, this is already passes tests if we write, for example, a segment tree, but we don't want to write a segment tree, so we go further, prove that for $k_1 = x$, the answer is less or equal than for $k_2 = x \\cdot y$ if $k_1$ and $k_2$ are divisors of $n$, why is this so? Note that for the number $k$, the answer beats for $\\gcd(k,n)$ groups of numbers, so that in each group there is exactly $\\frac{n}{\\gcd(k,n)}$ and each number is in exactly one group, and for different $s$ the answer will be (the sum in the group that $s$ belongs to) $\\cdot\\gcd(k,n)$. Let's look at the answer for the optimal $s$ for $k_1$, let's call the set at which it is reached $t$, note that in $k_2$ for different $s$ there are $m$ independent sets that are subsets of $t$. Let $m_i$ be the sum in the $i$-th set. Now note that we need to prove $max(m_1, m_2, \\ldots, m_y) * y\\geq m_1 +m_2 +\\ldots m_y$ this is true for any $m_i$, easy to see. So you need to iterate the divisors which equals to $\\frac{n}{p}$ where $p$ is prime, now it can be passed with a set. Hurray! For the divisor $d$, it is proposed to store answers for all pairs $(s, d)$, where $s\\le\\frac{n}{d}$ and the maximum among them, they can be counted initially for $O(n log n)$ for one $d$, each request is changing one of the values, this can be done for $O(log n)$. The complexity of the author's solution is $O(6\\cdot n\\operatorname{log}(n))$, where 6 is the maximum number of different prime divisors of the number $n$.",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1718",
    "index": "D",
    "title": "Permutation for Burenka",
    "statement": "We call an array $a$ pure if all elements in it are pairwise distinct. For example, an array $[1, 7, 9]$ is pure, $[1, 3, 3, 7]$ isn't, because $3$ occurs twice in it.\n\nA pure array $b$ is similar to a pure array $c$ if their lengths $n$ are the same and for all pairs of indices $l$, $r$, such that $1 \\le l \\le r \\le n$, it's true that $$\\operatorname{argmax}([b_l, b_{l + 1}, \\ldots, b_r]) = \\operatorname{argmax}([c_l, c_{l + 1}, \\ldots, c_r]),$$ where $\\operatorname{argmax}(x)$ is defined as the index of the largest element in $x$ (which is unique for pure arrays). For example, $\\operatorname{argmax}([3, 4, 2]) = 2$, $\\operatorname{argmax}([1337, 179, 57]) = 1$.\n\nRecently, Tonya found out that Burenka really likes a permutation $p$ of length $n$. Tonya decided to please her and give her an array $a$ similar to $p$. He already fixed some elements of $a$, but exactly $k$ elements are missing (in these positions temporarily $a_i = 0$). It is guaranteed that $k \\ge 2$. Also, he has a set $S$ of $k - 1$ numbers.\n\nTonya realized that he was missing one number to fill the empty places of $a$, so he decided to buy it. He has $q$ options to buy. Tonya thinks that the number $d$ suits him, if it is possible to replace all zeros in $a$ with numbers from $S$ and the number $d$, so that $a$ becomes a pure array similar to $p$. For each option of $d$, output whether this number is suitable for him or not.",
    "tutorial": "Try to reduce the task to a single array and tree. Try to reduce the tree to a match of bipartite graph. The first part: For each $a_i=0$, a segment of suitable values. The second part: The set $S$ and the number $d$. There exist $L$ and $R$ such that the answer to the query is ''YES'' if and only if $L \\le d \\le R$. Let's build a tree recursively starting from the segment $[1, n]$, at each step we will choose the root of the subtree $v = \\operatorname{argmax}([p_l, p_{l+1}\\ldots, p_r]) +l - 1$, then recursively construct trees for subtrees $[l, v-1], [v+1, r]$ if they are not empty, then create edges from the root to the roots of these subtrees. What we got is called a Cartesian tree by array. This Cartesian tree will be mentioned further in the analysis. It is easy to see that Cartesian trees by arrays coincide if and only if these arrays are similar. Then the necessary and sufficient condition for the array $a$ to be similar to $p$ is that for any pair $u, v$ such that $u$ is in the subtree $v$, $a_v > a_u$ is satisfied, in other words $a_v$ is the maximum among the numbers in the subtree of the vertex $v$. Let's call the position $i$ initially empty if initially $a_i = 0$. Let's call an array $a$ almost similar to $p$ if for any pair $u, v$ such that $u$ is in the subtree $v$, $a_v > a_u$ is executed, or both positions $u$, $v$ are initially empty. Let's prove that if there is a way to fill in the gaps in $a$ to get an array almost similar to $p$, then there is also a way to fill in the gaps to get a similar to $p$ array $a$. Indeed, let's look at the $a$ array almost similar to $p$. let's walk through the tree recursively starting from the root. At the step with the vertex $v$, we first start recursively from all the children of $v$, now it is true for them that the maxima of their subtrees are in them, let's look at the maximum child $v$, let it be $u$, then if $a_v > a_u$, then everything is fine, otherwise $a_v < a_u$ note that $v$ is initially an empty position, because for all initially non-empty positions it is true that they are maximums in their subtrees (this is easy to see in the definition), but $v$ is not. Note that $u$ is initially an empty position. Otherwise, we have never changed $a_v$ and $a_u$, therefore, in the original array $a$ almost similar to $p$, $a_v > a_u$ contradiction was executed, it is contradiction. so $v, u$ are initially empty, we can perform $swap(a_v, a_u)$ and everything will be executed. After executing this algorithm, we changed only the initially empty elements and got $a$ similar to $p$. Q.E.D. How to check the existence of an array almost similar to $p$? Let's call the number $r_i$ the minimum among all the numbers $a_v$ such that $i$ is in the subtree of $v$. Let's call the number $l_i$ the maximum among all the numbers $a_v$ such that $v$ is in the subtree of $i$. it is easy to see that $a$ is almost similar to $p$ if and only if for all $i$, $l_i < a_i < r_i$ is satisfied. That sounds incredibly good. So, all we need is to find a matching of the set $S$ and number $d$ and segments $[l_i, r_i]$ for $i$ that are initially empty. Now it is easy to prove that the suitable $d$ is a continuous segment (let's say the answer is yes for $d_1$, we don't know the answer for $d_2$, try looking at the alternating path from $d_1$ to $d_2$ in good matching for $d_1$, it's easy to see that if there is such a path, then for $d_2$ the answer is yes, otherwise, no. If you look at the structure of the matching of points with segments, you can see that an alternating path exists for a continuous segment of values $d_2$). the boundaries can be found by binary search or by typing greedily twice. Final complexity is $O(n \\operatorname{log} n)$ or $O(n \\operatorname{log}^2 n)$",
    "tags": [
      "data structures",
      "graph matchings",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1718",
    "index": "E",
    "title": "Impressionism",
    "statement": "Burenka has two pictures $a$ and $b$, which are tables of the same size $n \\times m$. Each cell of each painting has a color — a number from $0$ to $2 \\cdot 10^5$, and there are no repeating colors in any row or column of each of the two paintings, except color $0$.\n\nBurenka wants to get a picture $b$ from the picture $a$. To achieve her goal, Burenka can perform one of $2$ operations: swap any two rows of $a$ or any two of its columns. Tell Burenka if she can fulfill what she wants, and if so, tell her the sequence of actions.\n\nThe rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $m$ from left to right.",
    "tutorial": "you can notice that a pair of operations $1\\, i\\, j$, $2\\, k\\, t$ and $2\\, k\\, t$, $1\\, i\\, j$ lead to the same result, what does this mean? This means that operations can be represented as two permutations describing which swaps will occur with rows and which swaps will occur with columns. Try to reduce this problem to a graph isomorphism problem. Let's have two permutations: $p$ of length $n$ and $q$ of length $m$. Initially, both permutations are identical. For operation $1\\, i\\, j$, we will execute $\\operatorname{swap}(p_i, p_j)$, for operation $2\\, i\\, j$ we will execute $\\operatorname{swap}(q_i, q_j)$. It is easy to see that after performing all operations in the position $i, j$ will be $a_{p_i,q_j}$. Now we need to find permutations of $p, q$ so that $a_{p_i,q_j} = b_{i, j}$. Let's look at a bipartite graph where the first part is rows and the second is columns. Let if $a_{i,j}\\ne 0$, then from $i$ there is an undirected edge in $j$ of the color $a_{i, j}$. if we construct the same graph for $b$, then we need to check for isomorphism two bipartite graphs, each edge of which has a color, and as we remember, by the condition of the vertex, 2 edges of the same color cannot be Incidence. Let's call them graph $a$ and graph $b$. This problem is largely for implementation, therefore, starting from this moment, the actions that you can observe in the author's solution are described 168728958. Let $n < m$ otherwise let's swap $n$ and $m$ in places. Let's try to match the elements of the array $a$ to the elements of the array $b$. Let's go through the indices from $1$ to $n$. Let's now choose which pair of $b$ to choose for the $i$-th vertex of the first fraction of the graph $a$. If we have already found a pair earlier, skip the step, otherwise let's sort out the appropriate option for the pair among all the vertices of the first component $b$ that do not yet have a pair, there are no more than $n$, after the vertices are matched, the edges are also uniquely matched (because there are no 2 edges of different colors), let's then run the substitution recursively for edges (if we have mapped the vertex $v$ to the vertex $u$ and from $v$ there is an edge of color $x$ in $i$, and from $u$ there is an edge $x$ in $j$, then it is easy to prove that in the answer $i$ will be mapped to $j$), which means we will restore the entire component. Let the sum of the number of vertices and the number of edges in the component be $k$, then we will perform no more than $n \\cdot k$ actions to restore the component. by permutations, getting a sequence of swaps is a matter of technique, I will not explain it, but this is a separate function in the author's solution you will understand. in total, our solution works for $O(n(n\\cdot m + n + m))$ or $O(min(n, m)(n\\cdot m + n + m))$, where $n\\cdot m + n +m$ is the total number of vertices and edges in all components. feel free to ask any questions",
    "code": "#include <iostream>\n#include \"vector\"\n#include \"algorithm\"\n#include \"numeric\"\n#include \"climits\"\n#include \"iomanip\"\n#include \"bitset\"\n#include \"cmath\"\n#include \"map\"\n#include \"deque\"\n#include \"array\"\n#include \"set\"\n#include \"random\"\n#define all(x) x.begin(), x.end()\nusing namespace std;\nint swp = 0;\nvector<vector<pair<int, int>>> havenumsN, havenumsM;\nvector<vector<pair<int, int>>> havenumsN2, havenumsM2;\nbool operator==(vector<pair<int, int>> &a, vector<pair<int, int>> &b) {\n    if (a.size() != b.size())\n        return 0;\n    for (int i = 0; i < a.size(); ++i) {\n        if (a[i].first != b[i].first)\n            return 0;\n    }\n    return 1;\n}\nbool operator!=(vector<pair<int, int>> &a, vector<pair<int, int>> &b) {\n    if (a.size() != b.size())\n        return 1;\n    for (int i = 0; i < a.size(); ++i) {\n        if (a[i].first != b[i].first)\n            return 1;\n    }\n    return 0;\n}\nvoid NO() {\n    cout << \"-1\\n\";\n    exit(0);\n}\nvector<pair<int, int>> getswops(vector<int> a) {\n    map<int, int> mp;\n    vector<pair<int, int>> ans;\n    int n = a.size();\n    for (int i = 0; i < n; ++i) {\n        mp[a[i]] = i;\n    }\n    for (int i = 0; i < n; ++i) {\n        if (mp[i] != i) {\n            int i1 = i, i2 = mp[i];\n            ans.push_back({i1, i2});\n            swap(a[i1], a[i2]);\n            mp[a[i1]] = i1;\n            mp[a[i2]] = i2;\n        }\n    }\n    reverse(all(ans));\n    return ans;\n}\nstruct inform {\n    bool good = 0;\n    int chpos = 0;\n    vector<int> deln;\n    vector<int> chansN, chansM;\n    inform(bool good1 = 0, int chpos1 = 0, vector<int> deln1 = {}, vector<int> chansN1 = {}, vector<int> chansM1 = {}) {\n        chpos = chpos1;\n        good = good1;\n        deln = deln1;\n        chansN = chansN1;\n        chansM = chansM1;\n    }\n};\ninform trysolve(int i, int ind, vector<int> goodn, vector<int> goodm) {\n    vector<array<int, 3>> que;\n    que.push_back({0, i, ind});\n    vector<int> nowina;\n    int chpos = 0;\n    while (!que.empty()) {\n        auto [typem, in2, in1] = que.back();\n        que.pop_back();\n        if (typem == 0) {\n            if (goodn[in2] != -1 and goodn[in2] != in1)\n                return {};\n            if (goodn[in2] != -1)\n                continue;\n            if (havenumsN[in1] != havenumsN2[in2]) {\n                return {};\n            }\n            goodn[in2] = in1;\n            if (in2 != in1)\n                chpos++;\n            nowina.push_back(in1);\n            for (int j = 0; j < havenumsN[in1].size(); ++j) {\n                que.push_back({1, havenumsN2[in2][j].second, havenumsN[in1][j].second});\n            }\n        } else {\n            if (goodm[in2] != -1 and goodm[in2] != in1)\n                return {};\n            if (goodm[in2] != -1)\n                continue;\n            if (havenumsM[in1] != havenumsM2[in2]) {\n                return {};\n            }\n            if (in2 != in1)\n                chpos++;\n            goodm[in2] = in1;\n            for (int j = 0; j < havenumsM[in1].size(); ++j) {\n                que.push_back({0, havenumsM2[in2][j].second, havenumsM[in1][j].second});\n            }\n        }\n    }\n    return {1, chpos, nowina, goodn, goodm};\n}\n \nsigned main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> pole(n, vector<int>(m)), pole2(n, vector<int>(m));\n    if (n > m) {\n        swp = 1;\n        swap(n, m);\n        pole.assign(n, vector<int>(m));\n        pole2.assign(n, vector<int>(m));\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cin >> pole[j][i];\n            }\n        }\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cin >> pole2[j][i];\n            }\n        }\n    } else {\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < m; ++j) {\n                cin >> pole[i][j];\n            }\n        }\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < m; ++j) {\n                cin >> pole2[i][j];\n            }\n        }\n    }\n \n    havenumsN.assign(n, {}), havenumsM.assign(m, {});\n    havenumsN2.assign(n, {}), havenumsM2.assign(m, {});\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < m; ++j) {\n            if (pole[i][j] != 0) {\n                havenumsN[i].push_back({pole[i][j], j});\n                havenumsM[j].push_back({pole[i][j], i});\n            }\n            if (pole2[i][j] != 0) {\n                havenumsN2[i].push_back({pole2[i][j], j});\n                havenumsM2[j].push_back({pole2[i][j], i});\n            }\n        }\n    }\n    for (int i = 0; i < n; ++i) {\n        sort(all(havenumsN[i]));\n        sort(all(havenumsN2[i]));\n    }\n    for (int i = 0; i < m; ++i) {\n        sort(all(havenumsM[i]));\n        sort(all(havenumsM2[i]));\n    }\n    set<int> nopt;\n    for (int i = 0; i < n; ++i) {\n        nopt.insert(i);\n    }\n    vector<int> goodn(n, -1), goodm(m, -1);\n    for (int i = 0; i < n; ++i) {\n        if (goodn[i] == -1) {\n            bool gd = 0;\n            int chp = 0;\n            vector<int> nn, nansn, nansm;\n            for (auto ind : nopt) {\n                if (havenumsN[ind] == havenumsN2[i]) {\n                    inform a = trysolve(i, ind, goodn, goodm);\n                    if (a.good) {\n                        if (gd == 0) {\n                            chp = a.chpos + 1;\n                        }\n                        gd = 1;\n                        if (a.chpos < chp) {\n                            nn = a.deln;\n                            nansn = a.chansN;\n                            nansm = a.chansM;\n                        }\n                    }\n                }\n            }\n            if (gd == 0) {\n                NO();\n            }\n            goodn = nansn;\n            goodm = nansm;\n            for (auto k : nn)\n                nopt.erase(k);\n        }\n    }\n    set<int> who;\n    for (int i = 0; i < m; ++i) {\n        who.insert(i);\n    }\n    for (int i = 0; i < m; ++i) {\n        who.erase(goodm[i]);\n    }\n    for (int i = 0; i < m; ++i) {\n        if (goodm[i] == -1) {\n            goodm[i] = *who.begin();\n            who.erase(who.begin());\n        }\n    }\n    cout << getswops(goodn).size() + getswops(goodm).size() << '\\n';\n    if (swp)\n        swap(goodn, goodm);\n    for (auto i : getswops(goodn)) {\n        cout << \"1 \" << 1+i.first << ' ' << 1+i.second << '\\n';\n    }\n    for (auto i : getswops(goodm)) {\n        cout << \"2 \" << 1+i.first << ' ' << 1+i.second << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1718",
    "index": "F",
    "title": "Burenka, an Array and Queries",
    "statement": "Eugene got Burenka an array $a$ of length $n$ of integers from $1$ to $m$ for her birthday. Burenka knows that Eugene really likes coprime integers (integers $x$ and $y$ such that they have only one common factor (equal to $1$)) so she wants to to ask Eugene $q$ questions about the present.\n\nEach time Burenka will choose a subsegment $a_l, a_{l + 1}, \\ldots, a_r$ of array $a$, and compute the product of these numbers $p = a_l \\cdot a_{l + 1} \\cdot \\ldots \\cdot a_r$. Then she will ask Eugene to count the number of integers between $1$ and $C$ inclusive which are coprime with $p$.\n\nHelp Eugene answer all the questions!",
    "tutorial": "The only one hint to this problem is don't try to solve, it's not worth it. In order to find the number of numbers from $1$ to $C$ that are mutually prime with $x$, we write out its prime divisors (various). Let these be prime numbers $a_{1}, a_{2}, \\ldots, a_{k}$. Then you can find the answer for $2^{k}$ using the inclusion-exclusion formula. Because $\\left\\lfloor\\frac{a}{b\\cdot c}\\right\\rfloor = \\left\\lfloor\\frac{\\left\\lfloor\\frac{a}{b}\\right\\rfloor}{c}\\right\\rfloor$, a similar statement is made for $k$ numbers (you can divide completely in any order). Let's split the primes up to $2\\times 10^4$ into 2 classes - small ($\\leq 42$) and large (the rest). There are 13 small numbers, and 2249 large ones. Separately, we will write down pairs of large numbers that in the product give a number not exceeding $10 ^ 5$. There will be 4904 such pairs. Let's match each set of small primes with a mask. Let's write $dp[mask]$ - alternating sum over the $mask$ submasks of numbers $\\left\\lfloor\\frac{C}{a_{1}\\cdot a_{2}\\cdot\\ldots \\cdot a_{k}} \\right\\rfloor$, where $a_{1}, \\ldots, a_{k}$ - prime numbers from the submask. Similarly, we define $dp[mask][big]$ (in addition to the mask, there is a large prime $big$) and $dp[mask][case]$ (in addition to the mask, there are a pair of primes from a pair of large primes $case$). Each $dp$ can be counted for $states\\times bits$, where $states$ - is the number of states in $dp$, and $bits$ - is the mask size (number of bits). If we write out all the large primes on the segment for which $mask$ - mask of small primes, the answer for this segment will be the sum of $dp[mask] + \\sum dp[mask][big_{i}] + \\sum dp[mask][case_{i}]$ (for $big$ and $case$ lying on the segment). Thus, the request can be answered in 7000 calls to $dp$. In order to find a set of prime numbers on a segment, you can use the MO algorithm. Final complexity is $O(n\\sqrt{n} + q\\times(\\pi(m)+casesCount(C)))$ It is worth noting that (with a very strong desire) it is possible to further optimize the solution using avx, to speed up the calculation of the amount by submasks in dynamics by 16 times, to speed up the calculation of the amount of $dp[mask][big]$ by 8 times, which will allow you to answer the request in ~5000 (instead of 7000) calls to $dp$, and the pre-calculation for $4\\cdot 10^7$ instead of $7\\cdot 10^8$ (in fact, the pre-calculation works much faster due to compiler optimizations).",
    "tags": [
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1719",
    "index": "A",
    "title": "Chip Game",
    "statement": "Burenka and Tonya are playing an old Buryat game with a chip on a board of $n \\times m$ cells.\n\nAt the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any \\textbf{odd} number of cells (but you cannot move the chip both to the right and up in one move). The one who cannot make a move loses.\n\nBurenka makes the first move, the players take turns. Burenka really wants to win the game, but she is too lazy to come up with a strategy, so you are invited to solve the difficult task of finding it. Name the winner of the game (it is believed that Burenka and Tonya are masters of playing with chips, so they always move in the optimal way).\n\n\\begin{center}\n{\\small Chip's starting cell is green, the only cell from which chip can't move is red. if the chip is in the yellow cell, then blue cells are all options to move the chip in one move.}\n\\end{center}",
    "tutorial": "Try to look at the parity of $n, m$. The player who wins does not depend on player's strategy. The only thing that the winning player depends on is the parity of $n, m$. Note that the game will end only when the chip is in the upper right corner (otherwise you can move it $1$ square to the right or up). For all moves, the chip will move $n - 1$ to the right and $m - 1$ up, which means that the total length of all moves is $n + m - 2$ (the length of the move is how much the chip moved per turn). Since the length of any move is odd, then after any move of Burenka, the sum of the lengths will be odd, and after any move of Tonya is even. So we can find out who made the last move in the game by looking at $(n + m - 2) \\operatorname{mod} 2 = (n + m) \\operatorname{mod} 2$. With $(n + m) \\operatorname{mod} 2 = 0$, Tonya wins, otherwise Burenka. The complexity of the solution is $O(1)$.",
    "tags": [
      "games",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1719",
    "index": "B",
    "title": "Mathematical Circus",
    "statement": "A new entertainment has appeared in Buryatia — a mathematical circus! The magician shows two numbers to the audience — $n$ and $k$, \\textbf{where $n$ is even}. Next, he takes all the integers from $1$ to $n$, and splits them all into pairs $(a, b)$ (each integer must be in exactly one pair) so that for each pair the integer $(a + k) \\cdot b$ is divisible by $4$ (\\textbf{note that the order of the numbers in the pair matters}), or reports that, unfortunately for viewers, such a split is impossible.\n\nBurenka really likes such performances, so she asked her friend Tonya to be a magician, and also gave him the numbers $n$ and $k$.\n\nTonya is a wolf, and as you know, wolves do not perform in the circus, even in a mathematical one. Therefore, he asks you to help him. Let him know if a suitable splitting into pairs is possible, and if possible, then tell it.",
    "tutorial": "Instead of $k$, we can consider the remainder of dividing $k$ by 4. There is no answer for the remainder 0. For all other remainders, there is an answer. Note that from the number $k$ we only need the remainder modulo $4$, so we take $k$ modulo and assume that $0 \\leq k \\leq 3$. If $k = 0$, then there is no answer, because the product of the numbers in each pair must be divisible by $4 = 2^2$, that is, the product of all numbers from $1$ to $n$ must be divisible by $2^{\\frac{n}{2} \\cdot 2} = 2^n$, but the degree of occurrence of $2$ in this sum is $\\lfloor\\frac{n}{2}\\rfloor +\\lfloor\\frac{n}{4}\\rfloor$, which is less than $n$. If $k = 1$ or $k = 3$, then we will make all pairs of the form $(i, i + 1)$, where $i$ is odd. Then $a + k$ will be even in each pair, since $a$ and $k$ are odd, and since $b$ is also even, the product will be divisible by $4$. If $k = 2$, then we will do the same splitting into pairs, but in all pairs where $i + 1$ is not divisible by $4$, we will swap the numbers (that is, we will make $a = i + 1$ and $b = i$). Then in pairs where $i + 1 \\operatorname{mod} 4 = 0$, $b$ is divisible by $4$ (therefore the product too), and in the rest $a + k$ is divisible by $4$ (since $a$ and $k$ have a remainder $2$ modulo $4$). The complexity of the solution is $O(n)$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1719",
    "index": "C",
    "title": "Fighting Tournament",
    "statement": "Burenka is about to watch the most interesting sporting event of the year — a fighting tournament organized by her friend Tonya.\n\n$n$ athletes participate in the tournament, numbered from $1$ to $n$. Burenka determined the strength of the $i$-th athlete as an integer $a_i$, where $1 \\leq a_i \\leq n$. All the strength values are different, that is, the array $a$ is a permutation of length $n$. We know that in a fight, if $a_i > a_j$, then the $i$-th participant always wins the $j$-th.\n\nThe tournament goes like this: initially, all $n$ athletes line up in ascending order of their ids, and then there are infinitely many fighting rounds. In each round there is exactly one fight: the first two people in line come out and fight. The winner goes back to the front of the line, and the loser goes to the back.\n\nBurenka decided to ask Tonya $q$ questions. In each question, Burenka asks how many victories the $i$-th participant gets in the first $k$ rounds of the competition for some given numbers $i$ and $k$. Tonya is not very good at analytics, so he asks you to help him answer all the questions.",
    "tutorial": "Who would win duels if the strongest athlete was the first in queue? After what number of rounds is the strongest athlete guaranteed to be at the front of the queue? Simulate the first $n$ rounds and write down their winners so that for each person you can quickly find out the number of wins in rounds with numbers no more than a given number. Note that after the strongest athlete is at the beginning of the queue, only he will win. The strongest athlete will be at the beginning of the queue no more than after the $n$-th round. Let's simulate the first $n$ rounds, if the $j$-th athlete won in the $i$-th round, then we will write down the $i$ number for him. Now, to answer the query $(i, k)$, it is enough to find the number of wins of the $i$ athlete in rounds with numbers $j \\leq k$, and if $k > n$, and the strength of the $i$ athlete is equal to $n$, then add to the answer another $k - n$. The complexity of the solution is $O(n + q \\operatorname{log}(n))$.",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1720",
    "index": "A",
    "title": "Burenka Plays with Fractions",
    "statement": "Burenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions ($\\frac{a}{b}$ and $\\frac{c}{d}$) with integer numerators and denominators. Then children are commanded to play with their fractions.\n\nBurenka is a clever kid, so she noticed that when she claps once, she can multiply numerator or denominator of one of her two fractions by any integer of her choice (but she can't multiply denominators by $0$). Now she wants know the minimal number of claps to make her fractions equal (by \\textbf{value}). Please help her and find the required number of claps!",
    "tutorial": "Note that we always can make fractions equal in two operations: Multiply first fraction's enumerator by $bc$, the first fraction is equal to $\\frac{abc}{b} = ac$, Multiply second fraction's enumerator by $ad$, the second fraction is equal to $\\frac{acd}{d} = ac$. That means that the answer does not exceed 2. If fractions are equal from input, the answer is 0. Otherwise, it can't be 0. Now we have to check if the answer is 1. Let's assume that for making fractions equal in 1 operation we have to multiply first fraction's enumerator by $x$. Then $\\frac{ax}{b} = \\frac{c}{d}$ must be true. From this we can see that $x = \\frac{bc}{ad}$. $x$ must be integer, so $bc$ must be divisible by $ad$. If we assume that we multiplied first fraction's denumerator by $x$, we can do the same calculations and see that $ad$ must be divisible by $bc$. So, for checking if the answer is $1$ we need to check if one of $ad$ and $bc$ is divisible by another one. If we multiply second fraction's enumerator or denumerator by $x$ we will get the same conditions for answer being equla to 1. If the answer is not 0 or 1, it's 2. Complexity: $O(1)$",
    "code": "#include <bits/extc++.h>\nusing namespace std;\nusing namespace __gnu_cxx;\nusing namespace __gnu_pbds;\n\n#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n#define sfor(i, l, r) for (int i = l; i <= r; ++i)\n#define bfor(i, r, l) for (int i = r; i >= l; --i)\n#define all(a) a.begin(), a.end()\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing vi = vector<int>;\nusing oset = tree<int, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update>;\n\nvoid solve() {\n    ll a, b, c, d;\n    cin >> a >> b >> c >> d;\n    ll x = a * d, y = b * c;\n    if (x == y)\n        cout << \"0\\n\";\n    else if (y != 0 && x % y == 0 || x != 0 && y % x == 0)\n        cout << \"1\\n\";\n    else\n        cout << \"2\\n\";\n}\n\nint main() {\n    fast;\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}\n\n",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1720",
    "index": "B",
    "title": "Interesting Sum",
    "statement": "You are given an array $a$ that contains $n$ integers. You can choose any proper subsegment $a_l, a_{l + 1}, \\ldots, a_r$ of this array, meaning you can choose any two integers $1 \\le l \\le r \\le n$, where $r - l + 1 < n$. We define the beauty of a given subsegment as the value of the following expression:\n\n$$\\max(a_{1}, a_{2}, \\ldots, a_{l-1}, a_{r+1}, a_{r+2}, \\ldots, a_{n}) - \\min(a_{1}, a_{2}, \\ldots, a_{l-1}, a_{r+1}, a_{r+2}, \\ldots, a_{n}) + \\max(a_{l}, \\ldots, a_{r}) - \\min(a_{l}, \\ldots, a_{r}).$$\n\nPlease find the maximum beauty among all proper subsegments.",
    "tutorial": "Obviously, answer does not exceed $max_{1} + max_{2} - min_{1} - min_{2}$, where $max_{1}, max_{2}$ are two maximum values in the array, and $min_{1}, min_{2}$ are two minimum values. Let's find a segment, such as this is true. For that we will look at all positions containing $max_{1}$ or $max_{2}$ ($S_{1}$) and all positions containing $min_{1}$ or $min_{2}$ ($S_2$). After that we choose a pair $l \\in S_1$, $r \\in S_2$, such as $abs(r - l)$ is minimum possible. Complexity: $O(n\\log n)$",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\n#define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);\n\nvector<ll> vec;\nll n;\n\nint main() {\n\tfastInp;\n\n\tll t;\n\tcin >> t;\n\n\twhile (t--) {\n\t\tcin >> n;\n\n\t\tvec.resize(n);\n\t\tfor (auto& c : vec) cin >> c;\n\n\t\tsort(vec.begin(), vec.end());\n\n\t\tcout << vec[n - 1] + vec[n - 2] - vec[0] - vec[1] << \"\\n\";\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1720",
    "index": "C",
    "title": "Corners",
    "statement": "You are given a matrix consisting of $n$ rows and $m$ columns. Each cell of this matrix contains $0$ or $1$.\n\nLet's call a square of size $2 \\times 2$ without one corner cell an L-shape figure. In one operation you can take one L-shape figure, with at least one cell containing $1$ and replace all numbers in it with zeroes.\n\nFind the \\textbf{maximum} number of operations that you can do with the given matrix.",
    "tutorial": "Let's say that $cnt_1$ is the number of ones in the table. Note that if there is a connected area of zeros in the table of size at least 2, then we can add one $0$ to this area by replacing only one 1 in the table. That means that if we have such area we can fill the table with zeros in $cnt_1$ operations (we can't make more opertions because we need to replace at least one 1 by operation). There can be no such area in the beginning, but after first operation it will appear. So, for finding the answer we just need to find an angle with minimal number of 1 in it, and which we can replace. Complexity: $O(nm)$",
    "code": "\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <map>\n#include <set>\n#include <cmath>\n#include <deque>\n#include <random>\n#include <iomanip>\n#include <chrono>\n#include <bitset>\n#include <queue>\n#include <complex>\n#include <functional>\n\nusing namespace std;\nconst int INF = 1e9;\nconst int MAXN = 2000;\nint a[MAXN][MAXN];\n\ninline void solve1() {\n    int n, m, sum = 0;\n    cin >> n >> m;\n    string s;\n    for (int i = 0; i < n; ++i) {\n        cin >> s;\n        for (int j = 0; j < m; ++j) {\n            a[i][j] = s[j] - '0';\n            sum += a[i][j];\n        }\n    }\n    int minn = INF;\n    for (int i = 0; i < n - 1; ++i) {\n        for (int j = 0; j < m - 1; ++j) {\n            int cnt = a[i][j] + a[i + 1][j] + a[i][j + 1] + a[i + 1][j + 1];\n            if (cnt == 0) continue;\n            minn = min(minn, max(1, cnt - 1));\n        }\n    }\n    if (sum == 0) cout << \"0\\n\";\n    else cout << 1 + sum - minn << \"\\n\";\n}\n\nsigned main() {\n     int t = 1;\n     cin >> t;\n     while (t--) {\n        solve1();\n     }\n}\n",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1720",
    "index": "D1",
    "title": "Xor-Subsequence (easy version)",
    "statement": "\\textbf{It is the easy version of the problem. The only difference is that in this version $a_i \\le 200$.}\n\nYou are given an array of $n$ integers $a_0, a_1, a_2, \\ldots a_{n - 1}$. Bryap wants to find the longest \\textbf{beautiful} subsequence in the array.\n\nAn array $b = [b_0, b_1, \\ldots, b_{m-1}]$, where $0 \\le b_0 < b_1 < \\ldots < b_{m - 1} < n$, is a subsequence of length $m$ of the array $a$.\n\nSubsequence $b = [b_0, b_1, \\ldots, b_{m-1}]$ of length $m$ is called \\textbf{beautiful}, if the following condition holds:\n\n- For any $p$ ($0 \\le p < m - 1$) holds: $a_{b_p} \\oplus b_{p+1} < a_{b_{p+1}} \\oplus b_p$.\n\nHere $a \\oplus b$ denotes the bitwise XOR of $a$ and $b$. For example, $2 \\oplus 4 = 6$ and $3 \\oplus 1=2$.\n\nBryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.",
    "tutorial": "Let's use dynamic programming to solve this task. $dp_i$ -- maximum length of good subsequence, that ends int $i$-th element of $a$, than naive solution is $dp_i = \\max_{\\substack{j = 0 \\\\ a_j \\oplus i < a_i \\oplus j}}^i dp_j + 1$ Let's observe that $a_j \\oplus i$ changes $i$ not more than by $200$. This way we can relax $dp_i$ not from $j = 0$, but $j = i - 512$, because xor operation changes only last 8 bits, so for $j' < i - 512$, definitely $a_{j'} \\oplus j > a_{j} \\oplus j'$. Additional idea: It not so hard to proove that we can try $j$ from $i - 256$ to $i - 1$.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\n#define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);\n\nvector<ll> vec;\nll n;\n\nconst ll CHECK = 512;\n\nint solve() {\n\n\tcin >> n;\n\n\tvec.resize(n);\n\tfor (auto& c : vec) cin >> c;\n\n\tvector<ll> dp(1);\n\n\tll bst = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tll cur = 0;\n\t\tdp.push_back(1);\n\t\tfor (int j = i - 1; j >= max(0ll, i - CHECK); j--) {\n\t\t\tif ((vec[i] ^ j) > (vec[j] ^ i)) {\n\t\t\t\tdp.back() = max(dp.back(), dp[j + 1] + 1);\n\t\t\t}\n\t\t}\n\t\t\n\t\tbst = max(bst, dp.back());\n\t}\n\n\tcout << bst << \"\\n\";\n\n\treturn 0;\n}\n\nint main(){\n    fastInp;\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "strings",
      "trees",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1720",
    "index": "D2",
    "title": "Xor-Subsequence (hard version)",
    "statement": "\\textbf{It is the hard version of the problem. The only difference is that in this version $a_i \\le 10^9$.}\n\nYou are given an array of $n$ integers $a_0, a_1, a_2, \\ldots a_{n - 1}$. Bryap wants to find the longest \\textbf{beautiful} subsequence in the array.\n\nAn array $b = [b_0, b_1, \\ldots, b_{m-1}]$, where $0 \\le b_0 < b_1 < \\ldots < b_{m - 1} < n$, is a subsequence of length $m$ of the array $a$.\n\nSubsequence $b = [b_0, b_1, \\ldots, b_{m-1}]$ of length $m$ is called \\textbf{beautiful}, if the following condition holds:\n\n- For any $p$ ($0 \\le p < m - 1$) holds: $a_{b_p} \\oplus b_{p+1} < a_{b_{p+1}} \\oplus b_p$.\n\nHere $a \\oplus b$ denotes the bitwise XOR of $a$ and $b$. For example, $2 \\oplus 4 = 6$ and $3 \\oplus 1=2$.\n\nBryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.",
    "tutorial": "Let's calculate answer for each prefix. Let's find answer if the last number in our subsequence is number with index $i$. Let there be such $j$ that $a[j] \\oplus i < a[i] \\oplus j$. That means that there are $k$ bits in numbers $a[j] \\oplus i$ and $a[i] \\oplus j$ which are the same, and after that $a[j] \\oplus i$ has different $k + 1$-th bit. Let's notice that if first $k$ bits are the same in $a[j] \\oplus i$ and $a[i] \\oplus j$, then these bits are the same in $a[j] \\oplus j$ and $a[i] \\oplus i$ Let's keep our answer in bit trie. We will add numbers $a[j] \\oplus j$ for our prefix. To find dp value for index $i$, we will descend in our trie with pair of integers $a_i \\oplus i$ and $i$. Each time we descend with bit $l$(0 or 1), in the opposite subtree there might be numbers which we can use to recalculate our answer. If in that subtree exists indexc $j$, then $k+1$-th bit of $a[j] \\cdot i$ to $0$. Let's keep such dp for every subtree: maximum value of $dp[j]$ for every $j$, such that $j$ lies in the subtree (but we need to keep answer if $k$-th bit of $j$ is 0, and if it's equals 1). We should try to improve our answer using $j$ if we descend to the opposite subtree. Then we can easily find answer for current $i$. After that we only need to add our number in the trie and recalculate the dp. Complexity: O(n * logC) where C its max value",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int maxlog = 30;\nconst int maxn = 300000;\n\nint nodes[maxn * maxlog + maxlog][2];\nint nodev[maxn * maxlog + maxlog][2];\nint last;\n\ninline int f() {\n    nodes[last][0] = 0;\n    nodes[last][1] = 0;\n    nodev[last][0] = 0;\n    nodev[last][1] = 0;\n    return last++;\n}\n\nint solve() {\n    int n;\n    cin >> n;\n    vector <int> v(n);\n    for (auto& i : v) cin >> i;\n    int ans = 0;\n    last = 0;\n    f();\n    for (int i = 0; i < n; i++) {\n        int a = 0;\n        int b = v[i] ^ i;\n        int c = i;\n        int getmax = 0;\n        for (int j = maxlog; j >= 0; j--) {\n            if (nodes[a][((b >> j) & 1) ^ 1]) getmax = max(getmax, nodev[nodes[a][((b >> j) & 1) ^ 1]][(((b ^ c) >> j) & 1) ^ 1]);\n            if (!nodes[a][(b >> j) & 1]) break;\n            a = nodes[a][(b >> j) & 1];\n        }\n        ans = max(ans, getmax + 1);\n        a = 0;\n        b = v[i] ^ i;\n        c = i;\n        int d = getmax + 1;\n        for (int j = maxlog; j >= 0; j--) {\n            if (!nodes[a][(b >> j) & 1]) nodes[a][(b >> j) & 1] = f();\n            nodev[nodes[a][(b >> j) & 1]][(c >> j) & 1] = max(nodev[nodes[a][(b >> j) & 1]][(c >> j) & 1], d);\n            a = nodes[a][(b >> j) & 1];\n        }\n    }\n    cout << ans << \"\\n\";\n    return 0;\n}\n\nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "dp",
      "strings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1720",
    "index": "E",
    "title": "Misha and Paintings",
    "statement": "Misha has a \\textbf{square} $n \\times n$ matrix, where the number in row $i$ and column $j$ is equal to $a_{i, j}$. Misha wants to modify the matrix to contain \\textbf{exactly} $k$ distinct integers. To achieve this goal, Misha can perform the following operation zero or more times:\n\n- choose any \\textbf{square} submatrix of the matrix (you choose $(x_1,y_1)$, $(x_2,y_2)$, such that $x_1 \\leq x_2$, $y_1 \\leq y_2$, $x_2 - x_1 = y_2 - y_1$, then submatrix is a set of cells with coordinates $(x, y)$, such that $x_1 \\leq x \\leq x_2$, $y_1 \\leq y \\leq y_2$),\n- choose an integer $k$, where $1 \\leq k \\leq n^2$,\n- replace all integers in the submatrix with $k$.\n\nPlease find the minimum number of operations that Misha needs to achieve his goal.",
    "tutorial": "If $k$ is greater than the number of different numbers in the matrix, then the answer is $k$ minus the number of different elements. Otherwise the answer does not exceed 2. Let's proof that: choose the maximum square (let its side be equal to $L$), containing the top left corner of the matrix, such as recolouring it to some new colour makes the number of different colours in the table at least $k$. If the number of different colours after recolouring is greater than $k$, then choose a square with bottom right corner in $(L + 1, L + 1)$, such as recolouring it makes the number of different colours at least $k$. If we got exactly $k$ colours then we are done. Otherwise let's extend the square by one. We got $k$ or $k - 1$ different colours. This way, by choosing the correct colour of the square we can get exactly $k$ colours. Otherwise we are done. It remains to learn how to check whether the answer is equal to 1. We will iterate over length of the side of the square of the answer. Now we need $O(n^2)$ to check whether the required square with such a side exists. To do this, we calculate for each square in the table with such a side length (there are $n^2$ such squares), how many numbers this square completely covers (all appeareances of this numbers are in thsi square). To do this, let's iterate over the number $c$. Having considered its occurrences, it is easy to understand that the upper left corners of all squares with our side length, covering all cells with the number $c$, lie in some subrectangle of the table, so you can simply add 1 on this subrectangle using offline prefix sums. Having processed all the numbers in this way, we can count for each square how many numbers it covers completely, and therefore check whether it fits the requirements. Complexity: $O(n^3)$",
    "code": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <array>\n\nusing namespace std;\nconst int INF = 1e9;\n\ninline int min(int a, int b) {\n    if (a < b) return a;\n    return b;\n}\n\ninline int max(int a, int b) {\n    if (a > b) return a;\n    return b;\n}\n\ninline void solve1() {\n    int n, k, cnt = 0;\n    cin >> n >> k;\n    vector <vector <int>> a(n, vector <int>(n)), pref(n + 1, vector <int>(n + 1));\n    vector <array <int, 4>> all(n * n, { INF, -INF, INF, -INF });\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> a[i][j]; --a[i][j];\n            all[a[i][j]][0] = min(all[a[i][j]][0], i);\n            all[a[i][j]][1] = max(all[a[i][j]][1], i);\n            all[a[i][j]][2] = min(all[a[i][j]][2], j);\n            all[a[i][j]][3] = max(all[a[i][j]][3], j);\n        }\n    }\n    for (auto& i : all) {\n        if (i[0] != INF) ++cnt;\n    }\n    if (cnt <= k) {\n        cout << k - cnt;\n        return;\n    }\n    for (int len = 1; len <= n; ++len) {\n        for (auto& i : all) {\n            if (i[0] == INF) continue;\n            int mn_x = i[0], mx_x = i[1], mn_y = i[2], mx_y = i[3];\n            mx_x = max(0, mx_x - len + 1);\n            mx_y = max(0, mx_y - len + 1);\n            mn_x = min(mn_x, n - len);\n            mn_y = min(mn_y, n - len);\n            if (mx_x <= mn_x && mx_y <= mn_y) {\n                ++pref[mx_x][mx_y];\n                --pref[mx_x][mn_y + 1];\n                --pref[mn_x + 1][mx_y];\n                ++pref[mn_x + 1][mn_y + 1];\n            }\n        }\n        for (int x = 0; x < n; ++x) {\n            for (int y = 0; y < n; ++y) {\n                if (x == 0 && y == 0) continue;\n                else if (x == 0) pref[x][y] += pref[x][y - 1];\n                else if (y == 0) pref[x][y] += pref[x - 1][y];\n                else pref[x][y] += pref[x - 1][y] + pref[x][y - 1] - pref[x - 1][y - 1];\n            }\n        }\n        for (int x = 0; x < n; ++x) {\n            for (int y = 0; y < n; ++y) {\n                if (cnt - pref[x][y] == k || cnt - pref[x][y] + 1 == k) {\n                    cout << 1;\n                    return;\n                }\n            }\n        }\n        for (int i = 0; i <= n; ++i) {\n            for (int j = 0; j <= n; ++j) {\n                pref[i][j] = 0;\n            }\n        }\n    }\n    cout << 2;\n}\n\nint main() {\n    if (1) {\n        ios_base::sync_with_stdio(false);\n        cin.tie(nullptr);\n        cout.tie(nullptr);\n    }\n    if (1) {\n        int t = 1;\n        //   cin >> t;\n        while (t--) {\n            solve1();\n        }\n    }\n\n    return 0;\n}\n\n",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1721",
    "index": "A",
    "title": "Image",
    "statement": "You have an image file of size $2 \\times 2$, consisting of $4$ pixels. Each pixel can have one of $26$ different colors, denoted by lowercase Latin letters.\n\nYou want to recolor some of the pixels of the image \\textbf{so that all $4$ pixels have the same color}. In one move, you can choose \\textbf{no more than two} pixels \\textbf{of the same color} and paint them into some other color \\textbf{(if you choose two pixels, both should be painted into the same color)}.\n\nWhat is the minimum number of moves you have to make in order to fulfill your goal?",
    "tutorial": "There are some solutions based on case analysis, but in my opinion, the most elegant one is the following: Let's pick a color with the maximum possible number of pixels and repaint all other pixels into it. We will try to pick all pixels of some other color and repaint them in one operation, and we can ignore the constraint that we can repaint no more than $2$ pixels, since we will never need to repaint $3$ or $4$ pixels in one operation. So, the number of operations is just the number of colors other than the one we chosen, or just $d - 1$, where $d$ is the number of different colors in the image. To calculate this, we can use a set or an array of size $26$, where we mark which colors are present.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        string s1, s2;\n        cin >> s1 >> s2;\n        s1 += s2;\n        cout << set<char>(s1.begin(), s1.end()).size() - 1 << endl;\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1721",
    "index": "B",
    "title": "Deadly Laser",
    "statement": "The robot is placed in the top left corner of a grid, consisting of $n$ rows and $m$ columns, in a cell $(1, 1)$.\n\nIn one step, it can move into a cell, adjacent by a side to the current one:\n\n- $(x, y) \\rightarrow (x, y + 1)$;\n- $(x, y) \\rightarrow (x + 1, y)$;\n- $(x, y) \\rightarrow (x, y - 1)$;\n- $(x, y) \\rightarrow (x - 1, y)$.\n\nThe robot can't move outside the grid.\n\nThe cell $(s_x, s_y)$ contains a deadly laser. If the robot comes into some cell that has distance less than or equal to $d$ to the laser, it gets evaporated. The distance between two cells $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$.\n\nPrint the smallest number of steps that the robot can take to reach the cell $(n, m)$ without getting evaporated or moving outside the grid. If it's not possible to reach the cell $(n, m)$, print -1.\n\nThe laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than $d$ to the laser.",
    "tutorial": "First, let's determine if it's possible to reach the end at all. If the laser's field doesn't span until any wall, then it's surely possible - just stick to the wall yourself. If it touches at most one wall, it's still possible. If it's the bottom wall or the left wall, then take the path close to the top and the right wall. Vice versa, if it's the top wall or the right wall, then take the path close to the bottom and the left wall. What if both of these paths are locked? That means that the laser touches at least two walls at the same time: the top one and the left one, or the bottom one and the right one. Turns out, it's completely impossible to reach the end in either of these two cases. Just draw a picture and see for yourself. Thus, we can always take at least one of the path sticking to the walls. The distance from the start to the end is $|n - 1| + |m - 1|$, and both of these paths are exactly this long. So the answer is always either -1 or $n + m - 2$. To check if the laser touches a wall with its field, you can either use a formula or check every cell adjacent to a wall. Overall complexity: $O(1)$ or $O(n + m)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn, m, sx, sy, d = map(int, input().split())\n\tif min(sx - 1, m - sy) <= d and min(n - sx, sy - 1) <= d:\n\t    print(-1)\n\telse:\n\t    print(n + m - 2)",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1721",
    "index": "C",
    "title": "Min-Max Array Transformation",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$, which is sorted in non-descending order. You decided to perform the following steps to create array $b_1, b_2, \\dots, b_n$:\n\n- Create an array $d$ consisting of $n$ arbitrary \\textbf{non-negative} integers.\n- Set $b_i = a_i + d_i$ for each $b_i$.\n- Sort the array $b$ in non-descending order.\n\nYou are given the resulting array $b$. For each index $i$, calculate what is the minimum and maximum possible value of $d_i$ you can choose in order to get the given array $b$.\n\nNote that the minimum (maximum) $d_i$-s are \\textbf{independent} of each other, i. e. they can be obtained from different possible arrays $d$.",
    "tutorial": "For the start, let's note that $a_i \\le b_i$ for each $i$. Otherwise, there is no way to get $b$ from $a$. Firstly, let's calculate $d_i^{min}$ for each $i$. Since all $d_i \\ge 0$ then $b_j$ is always greater or equal than $a_i$ you get it from. So, the minimum $d_i$ would come from lowest $b_j$ that still $\\ge a_i$. Since $b$ is sorted, we can find such $b_j$ with lower_bound in $O(\\log{n})$. Let's prove that we can build such $d$ that transforms $a_i$ to $b_j$ we found earlier. Let's just make $d_k = b_k - a_k$ for $k \\in [1..j) \\cup (i..n]$; $d_k = b_{k+1} - a_k$ for $k \\in [j..i)$ and $d_i = b_j - a_i$. It's easy to see that all $d_i$ are non-negative, so such $d$ is valid. Now, let's calculate $d_i^{max}$. Suppose, we transform $a_i$ to $b_j$ for some $j \\ge i$. It's not hard to prove that the \"proving\" array $d$ may be constructed in the similar way: $d_k = b_k - a_k$ for $k \\in [1..i) \\cup (j..n]$; $d_k = b_{k-1} - a_k$ for $k \\in (i..j]$ and $d_i = b_j - a_i$. In order to build such array $d$, you need $b_{k-1} \\ge a_k$ for each $i \\in (i..j]$. In other words, if there is some position $l$ such that $l > i$ and $b_{l - 1} < a_l$ you can't choose $j$ such that $j \\ge l$. It means that we can iterate $i$ in descending order and just keep track of leftmost $l \\ge i$ with $b_{l - 1} < a_l$. Then, $d_i^{max}$ is equal to $b[l - 1] - a[i]$ (or $b[n] - a[i]$ if there are no such $l$). The resulting complexity is $O(n \\log n)$ because of the first part. But it can be optimized to $O(n)$ if we use two pointers instead of lower_bound.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val a = readLine()!!.split(' ').map { it.toInt() }\n        val b = readLine()!!.split(' ').map { it.toInt() }\n\n        val indices = (0 until n).sortedBy { a[it] }\n        val mn = Array(n) { 0 }\n        val mx = Array(n) { 0 }\n\n        var lst = n\n        for (i in n - 1 downTo 0) {\n            val pos = indices[i]\n            mn[pos] = lowerBound(b, a[pos])\n            mx[pos] = lst - 1;\n            if (i == mn[pos])\n                lst = i\n\n            mn[pos] = b[mn[pos]] - a[pos]\n            mx[pos] = b[mx[pos]] - a[pos]\n        }\n        println(mn.joinToString(\" \"))\n        println(mx.joinToString(\" \"))\n    }\n}\n\nfun lowerBound(a: List<Int>, v: Int): Int {\n    var l = -1; var r = a.size\n    while (r - l > 1) {\n        val m = (l + r) / 2\n        if (a[m] < v)\n            l = m\n        else\n            r = m\n    }\n    return r\n}",
    "tags": [
      "binary search",
      "greedy",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1721",
    "index": "D",
    "title": "Maximum AND",
    "statement": "You are given two arrays $a$ and $b$, consisting of $n$ integers each.\n\nLet's define a function $f(a, b)$ as follows:\n\n- let's define an array $c$ of size $n$, where $c_i = a_i \\oplus b_i$ ($\\oplus$ denotes bitwise XOR);\n- the value of the function is $c_1 \\mathbin{\\&} c_2 \\mathbin{\\&} \\cdots \\mathbin{\\&} c_n$ (i.e. bitwise AND of the entire array $c$).\n\nFind the maximum value of the function $f(a, b)$ if you can reorder the array $b$ in an arbitrary way (leaving the initial order is also an option).",
    "tutorial": "We will build the answer greedily, from the highest significant bit to the lowest one. Let's analyze how to check if the answer can have the highest bit equal to $1$. It means that every value in $c$ should have its highest bit equal to $1$, so for every $i$, exactly one of the numbers $\\{a_i, b_i\\}$ should have this bit equal to $1$. For both of the given arrays, we can calculate how many elements have which value of this bit, and then the number of elements with $1$ in this bit in the array $a$ should be equal to the number of elements with $0$ in the array $b$ (and the same for elements with $0$ in $a$ and elements with $1$ in $b$). If these values are equal, it means that the elements of $a$ and $b$ can be matched in such a way that in every pair, the XOR of them has $1$ in this bit. If it is so, then the highest bit of the answer is $1$, otherwise it is $0$. Okay, then let's proceed to the next bit. Should we just do the same to check if this bit can be equal to $1$ in the answer? Unfortunately, that's not enough. Let's look at the case: $a = [3, 0]$, $b = [2, 1]$. We can get the value $1$ in the $0$-th bit or in the $1$-st bit, but not in both simultaneously. So, for the next bit, we need to make sure that not only we can get $1$ in the result, but we can also do this without transforming some of the $1$-s to $0$-s in the higher bits. If it is impossible, it doesn't matter if we can get $1$ in the current bit since it will be suboptimal, so we have to use an ordering that gets $0$ in this bit. In general case, it means that we have to solve the following subproblem: check if we can obtain $1$ in several bits of the answer; let these bits be $\\{x_1, x_2, \\dots, x_k\\}$ ($x_1$ to $x_{k-1}$ are the bits that we have already checked; $x_k$ is the new bit we are trying to check). Let $mask$ be the number that has $1$ in every bit $x_i$ and $0$ in every other bit. The elements should be matched in such a way that $(a_i \\& mask) \\oplus (b_i \\& mask) = mask$. If we group all numbers from $a$ and from $b$ according to the value of $a_i \\& mask$ (or $b_i \\& mask$), then for every group of elements from $a$, there is a corresponding group in $b$ such that we can match the elements from the first group only with the elements from the second group. So, if for every such group, its size in $a$ is equal to the size of the corresponding group in $b$, then we can set all bits from $\\{x_1, x_2, \\dots, x_k\\}$ to $1$ simultaneously. Some implementation notes: if the number of bits we need to check is big, the number of groups can become too large to handle all of them (since it is $2^k$). So, to store the number of elements in each group, we should use some associative data structure, like, for example, std::map in C++. If you use a map, splitting elements into groups will be done in $O(n \\log n)$, so in total, you will get complexity of $O(n \\log n \\log A)$, where $A$ is the maximum possible value in the input.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n);\n    for (int& x : a) cin >> x;\n    for (int& x : b) cin >> x;\n    \n    auto check = [&](int ans) {\n      map<int, int> cnt;\n      for (int x : a) ++cnt[x & ans];\n      for (int x : b) --cnt[~x & ans];\n      bool ok = true;\n      for (auto it : cnt) ok &= it.second == 0;\n      return ok;\n    };\n    \n    int ans = 0;\n    for (int bit = 29; bit >= 0; --bit) \n      if (check(ans | (1 << bit)))\n        ans |= 1 << bit;\n    \n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "divide and conquer",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1721",
    "index": "E",
    "title": "Prefix Function Queries",
    "statement": "You are given a string $s$, consisting of lowercase Latin letters.\n\nYou are asked $q$ queries about it: given another string $t$, consisting of lowercase Latin letters, perform the following steps:\n\n- concatenate $s$ and $t$;\n- calculate the prefix function of the resulting string $s+t$;\n- print the values of the prefix function on positions $|s|+1, |s|+2, \\dots, |s|+|t|$ ($|s|$ and $|t|$ denote the lengths of strings $s$ and $t$, respectively);\n- revert the string back to $s$.\n\nThe prefix function of a string $a$ is a sequence $p_1, p_2, \\dots, p_{|a|}$, where $p_i$ is the maximum value of $k$ such that $k < i$ and $a[1..k]=a[i-k+1..i]$ ($a[l..r]$ denotes a contiguous substring of a string $a$ from a position $l$ to a position $r$, inclusive). In other words, it's the longest proper prefix of the string $a[1..i]$ that is equal to its suffix of the same length.",
    "tutorial": "What's the issue with calculating the prefix function on the string $s$ and then appending the string $t$ with an extra $|t|$ recalculations? Calculating prefix function is linear anyway. Well, it's linear, but it's also amortized. So while it will make $O(n)$ operations for a string in total, it can take up to $O(n)$ on every particular letter. These particular letters can appear in string $t$, making the algorithm work in $O(q \\cdot (|s| + |t|))$. Let's analyze the classic way to calculate the prefix function. To append a character to the string and calculate the new value of the prefix function, you have to do the following: take the longest proper prefix of a string before appending the letter, which is also a suffix; if the letter right after it is the same as the new one, then the new value is length of it plus one; if it's empty, then the new value is $0$; otherwise, take its longest proper prefix and return to step $2$. Basically, from having the value of the prefix function of the string and the new letter, you can determine the new value of the prefix function. If $|t|$ was always equal to $1$, then you would only want to try all options for the next letter after a string. That should remind you of a structure known as prefix function automaton. Its states are the values of the prefix function, and the transitions are appending a letter to a string with a certain value of the prefix function. So you can append a letter in $O(1)$ if you have an automaton built on the string $s$. However, you can't just append more letters after one - you don't have the automaton built this far. You can follow two paths. The first one is to jump with a regular way of calculating the prefix function until you reach the state of the automaton which exists. The second one is to continue building the automaton onto the string $t$, calculating the prefix function along the way. Appending a layer to the automaton takes $O(\\mathit{AL})$ non-amortized. After you calculated everything you needed, pop the states back to the original. Overall complexity: $O(|s| \\cdot \\mathit{AL} + q \\cdot |t|)$ or $O(|s| \\cdot \\mathit{AL} + q \\cdot |t| \\cdot \\mathit{AL})$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int AL = 26;\n\nvector<int> prefix_function(const string &s){\n\tint n = s.size();\n\tvector<int> p(n);\n\tfor (int i = 1; i < n; ++i){\n\t\tint k = p[i - 1];\n\t\twhile (k > 0 && s[i] != s[k])\n\t\t\tk = p[k - 1];\n\t\tk += (s[i] == s[k]);\n\t\tp[i] = k;\n\t}\n\treturn p;\n}\n\nint main() {\n\tcin.tie(0);\n\tiostream::sync_with_stdio(false);\n\tstring s;\n\tcin >> s;\n\tint n = s.size();\n\tauto p = prefix_function(s);\n\tvector<vector<int>> A(n, vector<int>(AL));\n\tforn(i, n) forn(j, AL){\n\t\tif (i > 0 && j != s[i] - 'a')\n\t\t\tA[i][j] = A[p[i - 1]][j];\n\t\telse\n\t\t\tA[i][j] = i + (j == s[i] - 'a');\n\t}\n\tint q;\n\tcin >> q;\n\tvector<vector<int>> ans(q);\n\tforn(z, q){\n\t\tstring t;\n\t\tcin >> t;\n\t\tint m = t.size();\n\t\ts += t;\n\t\tfor (int i = n; i < n + m; ++i){\n\t\t    A.push_back(vector<int>(AL));\n\t\t\tforn(j, AL){\n\t\t\t\tif (j != s[i] - 'a')\n\t\t\t\t\tA[i][j] = A[p[i - 1]][j];\n\t\t\t\telse\n\t\t\t\t\tA[i][j] = i + (j == s[i] - 'a');\n\t\t\t}\n\t\t\tp.push_back(A[p[i - 1]][s[i] - 'a']);\n\t\t\tans[z].push_back(p[i]);\n\t\t}\n\t\tforn(_, m){\n\t\t\tp.pop_back();\n\t\t\ts.pop_back();\n\t\t\tA.pop_back();\n\t\t}\n\t}\n\tfor (auto &it : ans){\n\t\tfor (int x : it)\n\t\t\tcout << x << ' ';\n\t\tcout << '\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "hashing",
      "string suffix structures",
      "strings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1721",
    "index": "F",
    "title": "Matching Reduction",
    "statement": "You are given a bipartite graph with $n_1$ vertices in the first part, $n_2$ vertices in the second part, and $m$ edges. The maximum matching in this graph is the maximum possible (by size) subset of edges of this graph such that no vertex is incident to more than one chosen edge.\n\nYou have to process two types of queries to this graph:\n\n- $1$ — remove the \\textbf{minimum possible} number of vertices from this graph so that the size of the maximum matching gets reduced \\textbf{exactly by $1$}, and print the vertices that you have removed. Then, find any maximum matching in this graph and print the sum of indices of edges belonging to this matching;\n- $2$ — query of this type will be asked only after a query of type $1$. As the answer to this query, you have to print the edges forming the maximum matching you have chosen in the previous query.\n\nNote that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.",
    "tutorial": "Let's start by finding the maximum matching in the given graph. Since the constraints are pretty big, you need something fast. The model solution converts the matching problem into a flow network and uses Dinic to find the matching in $O(m^{1.5})$, but something like heavily optimized Kuhn's algorithm can also work. Okay, then what about finding the minimum possible number of vertices to delete in order to reduce the maximum matching? We claim that it is always enough to remove one vertex, and the proof will also provide a way to quickly search for such vertices. Let's recall that the size of the maximum matching is equal to the size of the minimum vertex cover (this only works in bipartite graphs). So, we will try to find a way to reduce the minimum vertex cover by $1$, and it's actually pretty easy - just remove any vertex belonging to the vertex cover; it's obvious that it reduces the vertex cover by $1$, and the maximum matching by $1$ as well. So, we can find the minimum vertex cover in the graph using the standard algorithm to convert the MM into MVC (or, if you're using Dinic to find the maximum matching, you can represent the minimum vertex cover as the minimum cut problem), and for each query of type $1$, just take a vertex from the vertex cover we found. Now the only thing that's left is discussing how to maintain the structure of the maximum matching in the graph. In fact, it's quite easy: on the one hand, since we remove the vertices belonging to the minimum vertex cover, every edge (including the edges from the matching) will be incident to one of the vertices we will remove; on the other hand, due to the definition of the maximum matching, there is no vertex that is incident to two or more edges from the maximum matching; so, every vertex from the vertex cover has exactly one edge from the maximum matching that is incident to it, and when we remove a vertex, we can simply remove the corresponding edge from the maximum matching. So, the only thing we need to do is to maintain which edge from the matching corresponds to which vertex from the minimum vertex cover, and it will allow us to maintain the structure of the maximum matching - and since these \"pairs\" don't change when we remove a vertex, it is enough to get this information right after we have constructed the maximum matching in the given graph; we won't need to rebuild it.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 400043;\nconst int INF = int(1e9);\n\nstruct edge\n{\n    int y, c, f;\n    edge() {};\n    edge(int y, int c, int f) : y(y), c(c), f(f) {};\n};\n\nvector<edge> e;\nvector<int> g[N];\nint S, T, V;\nint d[N], lst[N];\nint n1, n2, m, q;\nmap<pair<int, int>, int> es;\n\nvoid add_edge(int x, int y, int c)\n{\n    g[x].push_back(e.size());\n    e.push_back(edge(y, c, 0));\n    g[y].push_back(e.size());\n    e.push_back(edge(x, 0, 0));\n}\n\nint rem(int x)\n{\n    return e[x].c - e[x].f;\n}\n\nbool bfs()\n{\n    for (int i = 0; i < V; i++)\n        d[i] = INF;\n    d[S] = 0;\n    queue<int> q;\n    q.push(S);\n    while (!q.empty())\n    {\n        int k = q.front();\n        q.pop();\n        for (auto y : g[k])\n        {\n            if (rem(y) == 0)\n                continue;\n            int to = e[y].y;\n            if (d[to] > d[k] + 1)\n            {\n                q.push(to);\n                d[to] = d[k] + 1;\n            }\n        }\n    }\n    return d[T] < INF;\n}\n\nint dfs(int x, int mx)\n{\n    if (x == T || mx == 0)\n        return mx;\n    int sum = 0;\n    for (; lst[x] < g[x].size(); lst[x]++)\n    {\n        int num = g[x][lst[x]];\n        int r = rem(num);\n        if (r == 0)\n            continue;\n        int to = e[num].y;\n        if (d[to] != d[x] + 1)\n            continue;\n        int pushed = dfs(to, min(r, mx));\n        if (pushed > 0)\n        {\n            e[num].f += pushed;\n            e[num ^ 1].f -= pushed;\n            sum += pushed;\n            mx -= pushed;\n            if (mx == 0)\n                return sum;\n        }\n    }\n    return sum;\n}\n\nint Dinic()\n{\n    int ans = 0;\n    while (bfs())\n    {\n        for (int i = 0; i < V; i++)\n            lst[i] = 0;\n        int f = 0;\n        do\n        {\n            f = dfs(S, INF);\n            ans += f;\n        } while (f > 0);\n    }\n    return ans;\n}\n\nint main()\n{\n    scanf(\"%d %d %d %d\", &n1, &n2, &m, &q);\n    S = n1 + n2;\n    T = S + 1;\n    V = T + 1;\n    for (int i = 0; i < m; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n        --x;\n        --y;\n        es[make_pair(x, y)] = i + 1;\n        add_edge(x, n1 + y, 1);\n    }\n    for (int i = 0; i < n1; i++)\n        add_edge(S, i, 1);\n    for (int i = 0; i < n2; i++)\n        add_edge(i + n1, T, 1);\n    Dinic();\n    bfs();\n    vector<int> vertex_cover;\n    map<int, int> index;\n    set<int> matched;\n    long long sum = 0;\n    for (int i = 0; i < n1; i++)\n        if (d[i] == INF)\n        {\n            vertex_cover.push_back(i + 1);\n            for (auto ei : g[i])\n                if (e[ei].f == 1)\n                {\n                    int idx = es[make_pair(i, e[ei].y - n1)];\n                    index[i + 1] = idx;\n                    sum += idx;\n                    matched.insert(idx);\n                }\n        }\n    for (int i = 0; i < n2; i++)\n        if (d[i + n1] != INF)\n        {\n            vertex_cover.push_back(-(i + 1));\n            for (auto ei : g[i + n1])\n                if (e[ei].f == -1)\n                {\n                    int idx = es[make_pair(e[ei].y, i)];\n                    index[-(i + 1)] = idx;\n                    sum += idx;    \n                    matched.insert(idx);\n                }\n        }\n    for (int i = 0; i < q; i++)\n    {\n        int s;\n        scanf(\"%d\", &s);\n        if (s == 1)\n        {\n            puts(\"1\");\n            int v = vertex_cover.back();\n            vertex_cover.pop_back();\n            printf(\"%d\\n\", v);\n            sum -= index[v];\n            matched.erase(index[v]);\n            printf(\"%lld\\n\", sum);\n        }\n        else\n        {\n            printf(\"%d\\n\", (int)matched.size());\n            for(auto x : matched) printf(\"%d \", x);\n            puts(\"\");\n        }   \n        fflush(stdout);\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "flows",
      "graph matchings",
      "graphs",
      "interactive"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1722",
    "index": "A",
    "title": "Spell Check",
    "statement": "Timur likes his name. As a spelling of his name, he allows any permutation of the letters of the name. For example, the following strings are valid spellings of his name: Timur, miurT, Trumi, mriTu. Note that the correct spelling must have uppercased T and lowercased other letters.\n\nToday he wrote string $s$ of length $n$ consisting only of uppercase or lowercase Latin letters. He asks you to check if $s$ is the correct spelling of his name.",
    "tutorial": "Check if the string has length 5 and if it has the characters $\\texttt{T}, \\texttt{i}, \\texttt{m}, \\texttt{u}, \\texttt{r}$. The complexity is $\\mathcal{O}(n)$. You can also sort the string, and check if it is $\\texttt{Timur}$ when sorted (which is $\\texttt{Timru}$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    string name = \"Timur\";\n    sort(name.begin(), name.end());\n\n    int n;\n    cin >> n;\n    forn(i, n) {\n        int m;\n        cin >> m;\n        string s;\n        cin >> s;\n        sort(s.begin(), s.end());\n        cout << (s == name ? \"YES\" : \"NO\") << endl;\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1722",
    "index": "B",
    "title": "Colourblindness",
    "statement": "Vasya has a grid with $2$ rows and $n$ columns. He colours each cell red, green, or blue.\n\nVasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.",
    "tutorial": "Here are two solutions. Solution 1. Iterate through the string character by character. If $s_i=\\texttt{R}$, then $t_i=\\texttt{R}$; otherwise, if $s_i=\\texttt{G}$ or $\\texttt{B}$, then $t_i=\\texttt{G}$ or $\\texttt{B}$. If the statement is false for any $i$, the answer is NO. Otherwise it is YES. Solution 2. Replace all $\\texttt{B}$ with $\\texttt{G}$, since they are the same anyway. Then just check if the two strings are equal. In either case the complexity is $\\mathcal{O}(n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tstring s, t;\n\tcin >> s >> t;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] == 'R') {\n\t\t\tif (t[i] != 'R') {cout << \"NO\\n\"; return;}\n\t\t}\n\t\telse {\n\t\t\tif (t[i] == 'R') {cout << \"NO\\n\"; return;}\n\t\t}\n\t}\n\tcout << \"YES\\n\";\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1722",
    "index": "C",
    "title": "Word Game",
    "statement": "Three guys play a game: first, each person writes down $n$ distinct words of length $3$. Then, they total up the number of points as follows:\n\n- if a word was written by one person — that person gets 3 points,\n- if a word was written by two people — each of the two gets 1 point,\n- if a word was written by all — nobody gets any points.\n\nIn the end, how many points does each player have?",
    "tutorial": "You need to implement what is written in the statement. To quickly check if a word is written by another guy, you should store some map<string, int> or Python dictionary, and increment every time you see a new string in the input. Then, you should iterate through each guy, find the number of times their word appears, and update their score. The complexity is $\\mathcal{O}(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tmap<string, int> mp;\n\tstring a[3][n];\n\tfor (int i = 0; i < 3; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tcin >> a[i][j];\n\t\t\tmp[a[i][j]]++;\n\t\t}\n\t}\n\tfor (int i = 0; i < 3; i++) {\n\t\tint tot = 0;\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (mp[a[i][j]] == 1) {tot += 3;}\n\t\t\telse if (mp[a[i][j]] == 2) {tot++;}\n\t\t}\n\t\tcout << tot << ' ';\n\t}\n\tcout << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1722",
    "index": "D",
    "title": "Line",
    "statement": "There are $n$ people in a horizontal line, each looking either to the left or the right. Each person counts the number of people in the direction they are looking. The \\textbf{value} of the line is the sum of each person's count.\n\nFor example, in the arrangement LRRLL, where L stands for a person looking left and R stands for a person looking right, the counts for each person are $[0, 3, 2, 3, 4]$, and the value is $0+3+2+3+4=12$.\n\nYou are given the initial arrangement of people in the line. For each $k$ from $1$ to $n$, determine the maximum value of the line if you can change the direction of \\textbf{at most} $k$ people.",
    "tutorial": "For each person, let's calculate how much the value will change if they turn around. For example, in the line LRRLL, if the $i$-th person turns around, then the value of the line will change by $+4$, $-2$, $0$, $-2$, $-4$, respectively. (For instance, if the second person turns around, they see $3$ people before and $1$ person after, so the value of the line changes by $-2$ if they turn around.) Now note that if a person turns around, it doesn't affect anyone else's value. So the solution is a greedy one: let's sort the array of values in increasing order. Afterwards, we should go from the left to the right, and see if the value will increase if this person turns around; if it does, we should add it to the current total and continue. The time complexity of this solution is $\\mathcal{O}(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tlong long tot = 0;\n\tvector<long long> v;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] == 'L') {\n\t\t\tv.push_back((n - 1 - i) - i);\n\t\t\ttot += i;\n\t\t}\n\t\telse {\n\t\t\tv.push_back(i - (n - 1 - i));\n\t\t\ttot += n - 1 - i;\n\t\t}\n\t}\n\tsort(v.begin(), v.end(), greater<int>());\n\tfor (int i = 0; i < n; i++) {\n\t\tif (v[i] > 0) {tot += v[i];}\n\t\tcout << tot << ' ';\n\t}\n\tcout << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1722",
    "index": "E",
    "title": "Counting Rectangles",
    "statement": "You have $n$ rectangles, the $i$-th rectangle has height $h_i$ and width $w_i$.\n\nYou are asked $q$ queries of the form $h_s \\ w_s \\ h_b \\ w_b$.\n\nFor each query output, the total area of rectangles you own that \\textbf{can fit}a rectangle of height $h_s$ and width $w_s$ while also \\textbf{fitting in} a rectangle of height $h_b$ and width $w_b$. In other words, print $\\sum h_i \\cdot w_i$ for $i$ such that $h_s < h_i < h_b$ and $w_s < w_i < w_b$.\n\n\\textbf{Please note, that if two rectangles have the same height or the same width, then they cannot fit inside each other.} Also note that you \\textbf{cannot} rotate rectangles.\n\nPlease note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).",
    "tutorial": "Consider the 2D array with $a[x][y]=0$ for all $x,y$. Increase $a[h][w]$ by $h \\times w$ if there is an $h \\times w$ rectangle in the input. Now for each query, we need to find the sum of all $a[x][y]$ in a rectangle with lower-left corner at $a[h_s+1][w_s+1]$ and upper-right corner at $a[h_b-1][w_b-1]$. This is the standard problem that can be solved with 2D prefix sums. The time complexity is $\\mathcal{O}(n+q+\\max(h_b)\\max(w_b))$ per testcase. You can read about 2D prefix sums if you haven't heard of them before.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long a[1005][1005];\nlong long pref[1005][1005];\n\nvoid solve()\n{\n    long long n, q;\n    cin >> n >> q;\n    for(int i = 0; i <= 1001; i++)\n    {\n        for(int j = 0; j <= 1001; j++)\n        {\n            a[i][j] = pref[i][j] = 0;\n        }\n    }\n    for(int i = 0; i < n; i++)\n    {\n        long long h, w;\n        cin >> h >> w;\n        a[h][w]+=h*w;\n    }\n    for(int i = 1; i <= 1000; i++)\n    {\n        for(int j = 1; j <= 1000; j++)\n        {\n            pref[i][j] = pref[i-1][j]+pref[i][j-1]-pref[i-1][j-1]+a[i][j];\n        }\n    }\n    for(int i = 0; i < q; i++)\n    {\n        long long hs, ws, hb, wb;\n        cin >> hs >> ws >> hb >> wb;\n        cout << pref[hb-1][wb-1]-pref[hb-1][ws]-pref[hs][wb-1]+pref[hs][ws] << endl;\n    }\n}\n \nint main() {\n    int t = 1;\n    cin >> t;\n    while(t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1722",
    "index": "F",
    "title": "L-shapes",
    "statement": "An L-shape is a figure on gridded paper that looks like the first four pictures below. An L-shape contains exactly three shaded cells (denoted by *), which can be rotated in any way.\n\nYou are given a rectangular grid. Determine if it contains L-shapes only, where L-shapes can't touch an edge or corner. More formally:\n\n- Each shaded cell in the grid is part of exactly one L-shape, and\n- no two L-shapes are adjacent by edge or corner.\n\nFor example, the last two grids in the picture above \\textbf{do not} satisfy the condition because the two L-shapes touch by corner and edge, respectively.",
    "tutorial": "The problem is mainly a tricky implementation problem. Let's denote the elbow of an L-shape as the square in the middle (the one that is side-adjacent to two other squares). Every elbow is part of exactly one L-shape, and every L-shape has exactly one elbow. Iterate through the grid and count the number of side-adjacent neighbors they have. If there is a cell with more than 2, or if there is a cell with exactly two neighbors on opposite sides, then the answer is NO. Otherwise, if there are exactly 2 neighbors, this cell is an elbow. Mark all three cells of this L-shape with a unique number (say, mark the first one you find with $1$, the second with $2$, and so on.) If you ever remark a cell that already has a number, then two elbows are adjacent, and you can output NO. After all elbows are marked, check if all shaded cells have a number. If some don't, then they are not part of an L-shape, so you can output NO. Finally, we should check that L-shapes don't share edge or corner. Just check, for each number, if it is only diagonally adjacent to other numbers equal to it or unshaded cells. If it is diagonally adjacent to other unequal numbers, then the answer is NO, because two L-shapes share an edge or corner then. Otherwise the answer is YES. There are many other solutions, all of which are various ways to check the conditions. The complexity is $\\mathcal{O}(mn)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nconst int dx[3] = {-1, 0, 1}, dy[3] = {-1, 0, 1};\n\nvoid solve() {\n\tint n, m;\n\tcin >> n >> m;\n\tchar g[n][m];\n\tint id[n][m];\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tcin >> g[i][j];\n\t\t\tid[i][j] = 0;\n\t\t}\n\t}\n\tint curr = 1;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tif (g[i][j] == '*') {\n\t\t\t\tvector<pair<int, int>> adjh, adjv;\n\t\t\t\tif (i > 0 && g[i - 1][j] == '*') {\n\t\t\t\t\tadjh.emplace_back(i - 1, j);\n\t\t\t\t}\n\t\t\t\tif (i < n - 1 && g[i + 1][j] == '*') {\n\t\t\t\t\tadjh.emplace_back(i + 1, j);\n\t\t\t\t}\n\t\t\t\tif (j > 0 && g[i][j - 1] == '*') {\n\t\t\t\t\tadjv.emplace_back(i, j - 1);\n\t\t\t\t}\n\t\t\t\tif (j < m - 1 && g[i][j + 1] == '*') {\n\t\t\t\t\tadjv.emplace_back(i, j + 1);\n\t\t\t\t}\n\t\t\t\tif (adjh.size() == 1 && adjv.size() == 1) {\n\t\t\t\t\tif (id[i][j] == 0) {id[i][j] = curr;}\n\t\t\t\t\telse {cout << \"NO\\n\"; return;}\n\t\t\t\t\tif (id[adjh[0].first][adjh[0].second] == 0) {id[adjh[0].first][adjh[0].second] = curr;}\n\t\t\t\t\telse {cout << \"NO\\n\"; return;}\n\t\t\t\t\tif (id[adjv[0].first][adjv[0].second] == 0) {id[adjv[0].first][adjv[0].second] = curr;}\n\t\t\t\t\telse {cout << \"NO\\n\"; return;}\n\t\t\t\t\tcurr++;\n\t\t\t\t}\n\t\t\t\telse if (adjh.size() > 1 || adjv.size() > 1) {\n\t\t\t\t\tcout << \"NO\\n\"; return;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tif (g[i][j] == '*') {\n\t\t\t\tif (id[i][j] == 0) {cout << \"NO\\n\"; return;}\n\t\t\t\telse {\n\t\t\t\t\tfor (int x = 0; x < 3; x++) {\n\t\t\t\t\t\tfor (int y = 0; y < 3; y++) {\n\t\t\t\t\t\t\tif (0 <= i + dx[x] && i + dx[x] < n) {\n\t\t\t\t\t\t\t\tif (0 <= j + dy[y] && j + dy[y] < m) {\n\t\t\t\t\t\t\t\t\tif (id[i + dx[x]][j + dy[y]] != id[i][j] && id[i + dx[x]][j + dy[y]] != 0) {\n\t\t\t\t\t\t\t\t\t\tcout << \"NO\\n\"; return;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcout << \"YES\\n\";\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "dfs and similar",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1722",
    "index": "G",
    "title": "Even-Odd XOR",
    "statement": "Given an integer $n$, find any array $a$ of $n$ \\textbf{distinct} nonnegative integers less than $2^{31}$ such that the bitwise XOR of the elements on odd indices equals the bitwise XOR of the elements on even indices.",
    "tutorial": "There are a lot of solutions to this problem. Here I will describe one of them. First, we observe that having the XOR of even indexed numbers and odd indexed numbers equal is equivalent to having the XOR of all the elements equal to 0. Let's note with $a$ the XOR of all odd indexed numbers and $b$ the xor of all even indexed numbers. Notice that the XOR of all the array equals $0$ if and only if a = b. So how do we generate such an array with XOR of all elements $0$? Our first instinct might be to arbitrarily generate the first $n-1$ numbers, then set the last element as the XOR of the first $n-1$, ensuring that the total XOR is $0$. However, we might have problems with the condition that all elements must be distinct. Let's arbitrarily set the first $n-2$ so that they don't have the highest bit($2^30$) set, and then the $n-1$-th number can be just $2^30$. The last number can be the XOR of the first $n-2$ XOR the $n-1$-th number; you will be sure that the last number has not occurred in the first $n-2$ elements because they don't have the highest bit set while the last number must have the highest bit set. But how do we know that the $n-1$-th number and the $n$-th number will not be equal? This occurs only if the total XOR of the first $n-2$ numbers equals $0$. To fix this, we can just choose a different arbitrary number in one of the $n-2$ spots. For example, my solution checks if the XOR of the numbers $0, 1, 2 ..., n-4, n-3$ is $0$. If it is not $0$, great! We can use the simple solution without any changes. However, if the XOR is $0$ I use the numbers $1, 2, 3, ...., n-3, n-2$ in their place. These two sequences have different XORs, so it ensures that one of them always works. Output the integers from $1$ to $n-3$, then $2^{29}$, $2^{30}$, and the XOR of those $n-1$ numbers. Why does it work?",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    int case1 = 0;\n    int case2 = 0;\n    for(int i = 0; i < n-2; i++)\n    {\n        case1^=i;\n        case2^=(i+1);\n    }\n    long long addLast = ((long long)1<<31)-1;\n    if(case1 != 0)\n    {\n        for(int i = 0; i < n-2; i++)\n        {\n            cout << i << \" \";\n        }\n        case1^=addLast;\n        cout << addLast << \" \" << case1 << endl;\n    }\n    else\n    {\n        for(int i = 1; i <= n-2; i++)\n        {\n            cout << i << \" \";\n        }\n        case2^=addLast;\n        cout << addLast << \" \" << case2 << endl;\n    }\n}\n\nint main()\n{\n    int t = 1;\n    cin >> t;\n    while(t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1725",
    "index": "A",
    "title": "Accumulation of Dominoes",
    "statement": "Pak Chanek has a grid that has $N$ rows and $M$ columns. Each row is numbered from $1$ to $N$ from top to bottom. Each column is numbered from $1$ to $M$ from left to right.\n\nEach tile in the grid contains a number. The numbers are arranged as follows:\n\n- Row $1$ contains integers from $1$ to $M$ from left to right.\n- Row $2$ contains integers from $M+1$ to $2 \\times M$ from left to right.\n- Row $3$ contains integers from $2 \\times M+1$ to $3 \\times M$ from left to right.\n- And so on until row $N$.\n\nA domino is defined as two different tiles in the grid that touch \\textbf{by their sides}. A domino is said to be \\textbf{tight} if and only if the two numbers in the domino have a difference of exactly $1$. Count the number of distinct \\textbf{tight} dominoes in the grid.\n\nTwo dominoes are said to be distinct if and only if there exists at least one tile that is in one domino, but not in the other.",
    "tutorial": "We can divide the dominoes into two types: Horizontal dominoes. A domino is horizontal if and only if it consists of tiles that are on the same row. Vertical dominoes. A domino is vertical if and only if it consists of tiles that are on the same column. For an arbitrary tile in the grid that is not on the rightmost column, the integer in it is always exactly $1$ less than the integer in the tile that is directly to the right of it. So we can see that all possible horizontal dominoes are always tight. For an arbitrary tile in the grid that is not on the bottommost row, the integer in it is always exactly $M$ less than the integer in the tile that is directly to the bottom of it. So we can see that all possible vertical dominoes are tight if and only if $M=1$. We can calculate that there are $N \\times (M-1)$ horizontal dominoes and $(N-1) \\times M$ vertical dominoes. Therefore, we can get the following solution: If $M > 1$, then there are $N \\times (M-1)$ tight dominoes. If $M = 1$, then there are $N-1$ tight dominoes. Time complexity: $O(1)$",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1725",
    "index": "B",
    "title": "Basketball Together",
    "statement": "A basketball competition is held where the number of players in a team does not have a maximum or minimum limit (not necessarily $5$ players in one team for each match). There are $N$ candidate players in the competition that will be trained by Pak Chanek, the best basketball coach on earth. The $i$-th candidate player has a power of $P_i$.\n\nPak Chanek will form zero or more teams from the $N$ candidate players on the condition that each candidate player may only join in at most one team. Each of Pak Chanek's teams will be sent to compete once with an enemy team that has a power of $D$. In each match, the team sent is said to defeat the enemy team if the sum of powers from the formed players is \\textbf{strictly greater than $D$}.\n\nOne of Pak Chanek's skills is that when a team that has been formed plays in a match, he can change the power of each player in the team to be equal to the biggest player power from the team.\n\nDetermine the maximum number of wins that can be achieved by Pak Chanek.",
    "tutorial": "For a team of $c$ players with a biggest power of $b$, the total power of the team is $b \\times c$. So for a team with a biggest power of $b$ to win, it needs to have at least $\\lceil \\frac{D+1}{b} \\rceil$ players. For each player $i$, we can calculate a value $f(i)$ which means a team that has player $i$ as its biggest power needs to have at least $f(i)$ players to win. We can see that the bigger the value of $P_i$, the smaller the value of $f(i)$. We can also see that if a formed team is said to have a fixed biggest power and a fixed number of players, the powers of the players that are less than the biggest power do not affect the total power of the team. So those players can be anyone. Using the information above, we can form the teams using a greedy method. We iterate through each candidate player starting from the biggest $P_i$ and form new teams with each next biggest candidate player power as each team's biggest power. We do that while maintaining the total number of extra players required to make all formed teams win. We stop once the number of remaining players is not enough for the total number of extra players required. Time complexity: $O(N \\log N)$",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1725",
    "index": "C",
    "title": "Circular Mirror",
    "statement": "Pak Chanek has a mirror in the shape of a circle. There are $N$ lamps on the circumference numbered from $1$ to $N$ in clockwise order. The length of the arc from lamp $i$ to lamp $i+1$ is $D_i$ for $1 \\leq i \\leq N-1$. Meanwhile, the length of the arc between lamp $N$ and lamp $1$ is $D_N$.\n\nPak Chanek wants to colour the lamps with $M$ different colours. Each lamp can be coloured with one of the $M$ colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly $90$ degrees).\n\nThe following are examples of lamp colouring configurations on the circular mirror.\n\n\\begin{center}\n\\begin{tabular}{ccc}\n& & \\\nFigure 1. an example of an incorrect colouring because lamps $1$, $2$, and $3$ form a right triangle & Figure 2. an example of a correct colouring & Figure 3. an example of a correct colouring \\\n\\end{tabular}\n\\end{center}\n\nBefore colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo $998\\,244\\,353$.",
    "tutorial": "Let's represent the mirror as a circle with $N$ points at the circumference. First, one should notice that a circumscribed triangle (triangle whose vertices lie on the circumference of a circle) is a right triangle if only if one side of the triangle is the diameter of the circle. That means, for a single colour, there exists a right triangle with this colour if and only if both of the following conditions are satisfied: There exists two diametrically opposite points with this colour. This colour occurs in $3$ or more points. Let's call a pair of diametrically opposite points as a diameter pair. From the information above, we can see that if we colour the points in a diameter pair with the same colour, all other points must not have that colour. If that condition is satisfied for all diameter pairs, there cannot be a right triangle with the same colour. Let's find the number of diameter pairs in the circle and the number of points that do not belong to a diameter pair. Let the two values be $cntPair$ and $cntAlone$. One can find $cntPair$ and $cntAlone$ with two pointers or binary search using the prefix sum of the array $D$. To find the number of colouring configurations, we can iterate $i$ from $0$ to $\\min(cntPair, M)$. In each iteration, we calculate the number of configurations that have exactly $i$ diameter pairs with the same colour on both of their points. It is calculated as follows: There are $\\binom{cntPair}{i}$ ways to choose which diameter pairs have the same colour. Notice that each diameter pair with the same colour must have a different colour from each other. So there are $\\binom{M}{i} \\times i!$ ways to choose which colour is assigned to each diameter pair with the same colour. There are only $M-i$ available colours for colouring the remaining points. Each diameter pair with different colours can be coloured in $(M-i) \\times (M-i-1)$ ways and each of the remaining points can be coloured in $M-i$ ways. So the total number of ways for a single value of $i$ is: $\\binom{cntPair}{i} \\times \\binom{M}{i} \\times i! \\times ((M-i) \\times (M-i-1))^{cntPair-i} \\times (M-i)^{cntAlone}$ $\\binom{cntPair}{i} \\times \\binom{M}{i} \\times i! \\times ((M-i) \\times (M-i-1))^{cntPair-i} \\times (M-i)^{cntAlone}$ Time complexity: $O((N+M) \\log N)$",
    "tags": [
      "binary search",
      "combinatorics",
      "geometry",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1725",
    "index": "D",
    "title": "Deducing Sortability",
    "statement": "Let's say Pak Chanek has an array $A$ consisting of $N$ positive integers. Pak Chanek will do a number of operations. In each operation, Pak Chanek will do the following:\n\n- Choose an index $p$ ($1 \\leq p \\leq N$).\n- Let $c$ be the number of operations that have been done \\textbf{on index $p$} before this operation.\n- Decrease the value of $A_p$ by $2^c$.\n- Multiply the value of $A_p$ by $2$.\n\nAfter each operation, all elements of $A$ must be \\textbf{positive integers}.\n\nAn array $A$ is said to be sortable if and only if Pak Chanek can do zero or more operations so that $A_1 < A_2 < A_3 < A_4 < \\ldots < A_N$.\n\nPak Chanek must find an array $A$ that is sortable with length $N$ such that $A_1 + A_2 + A_3 + A_4 + \\ldots + A_N$ is the minimum possible. If there are more than one possibilities, Pak Chanek must choose the array that is \\textbf{lexicographically minimum} among them.\n\nPak Chanek must solve the following things:\n\n- Pak Chanek must print the value of $A_1 + A_2 + A_3 + A_4 + \\ldots + A_N$ for that array.\n- $Q$ questions will be given. For the $i$-th question, an integer $P_i$ is given. Pak Chanek must print the value of $A_{P_i}$.\n\nHelp Pak Chanek solve the problem.\n\nNote: an array $B$ of size $N$ is said to be lexicographically smaller than an array $C$ that is also of size $N$ if and only if there exists an index $i$ such that $B_i < C_i$ and for each $j < i$, $B_j = C_j$.",
    "tutorial": "Define an array as distinctable if and only if Pak Chanek can do zero or more operations to make the elements of the array different from each other. Finding a sortable array $A$ of size $N$ with the minimum possible sum of elements is the same as finding a distinctable array $A$ of size $N$ with the minimum possible sum and permuting its elements. Define a value $k'$ as being reachable from a value $k$ if and only if we can do zero or more operations to the value $k$ to turn it into $k'$. To construct a distinctable array of size $N$ with the minimum possible sum, we can do a greedy method. Initially, the array $A$ is empty. Then, do the following iteration multiple times sequentially for each value $k$ from $1$, $2$, $3$, and so on until $A$ has $N$ elements: Consider each value $k'$ that is reachable from $k$. Let's say there are $w$ values $k'$ that has not been used as the final value for each of the previous elements of $A$. Append $w$ new elements with value $k$ to $A$ and assign the final value for each of the new elements with each of the usable values of $k'$. In the case where appending $w$ new elements makes the size of $A$ exceed $N$, we choose only some of the usable values of $k'$ to make the size of $A$ exactly $N$. Notice that while choosing the final values for each value $k$, there is only one way to do it for each iteration except the last iteration. For the last iteration, it can be obtained that in order to get the lexicographically minimum array, we choose the usable final values that are the largest ones. It can be obtained that each value that is reachable from $k$ is in the form of $x \\times 2^y$ for some positive integer $x$ and some non-negative integer $y$ satisfying $x+y=k$. For a pair $(x, y)$, if we choose an even integer for $x$, we can always find another pair $(x_2, y_2)$ such that $x_2 \\times 2^{y_2} = x \\times 2^y$ and $x_2+y_2 \\leq x+y$. From the logic of the greedy method, we can see that choosing an even integer for $x$ is always not optimal. For two distinct pairs $(x_1, y_1)$ and $(x_2, y_2)$, if both $x_1$ and $x_2$ are odd, then $x_1 \\times 2^{y_1} \\neq x_2 \\times 2^{y_2}$ always holds. Using the knowledge above, we can see that during the greedy method, the usable final values for a value $k$ are all the ones with odd values of $x$, which there are $\\lceil \\frac{k}{2} \\rceil$ of them. From this, we can see that in our greedy method, we only do $O(\\sqrt N)$ iterations. So, we can get the sum of elements in our constructed array $A$ in $O(\\sqrt N)$. To answer each query, we need to find the $P_i$-th smallest final value in the array and find which value produces it. We can construct an array $F_0, F_1, F_2, \\ldots$ of size $O(\\sqrt N)$. This means for each $i$, there are $F_i$ values $x \\times 2^y$ with $y=i$, namely the ones with the values of $x$ being the $F_i$ smallest positive odd integers. We can convert each value $x \\times 2^y$ into $x' \\times 2^{y'}$ such that all values of $x'$ have the same MSB (Most Significant Bit). After converting, sorting the values $x' \\times 2^{y'}$ is the same as sorting the pairs $(y', x')$. We can construct a two-dimensional array $G$ of size $O(\\sqrt N) \\times O(\\log N)$ with $G_{i,j}$ representing the number of final values with $y' = i$ and $y = i-j$. To find the $P_i$-th smallest final value, firstly we find its value of $y'$ with binary search using array $G$. Now, for some integer $d$, we need to find the $d$-th smallest value of $x'$ for all final values with a certain value of $y'$. To find it, we do a binary search on a value $m$ with each iteration checking whether there are at least $d$ values of $x'$ that are less than or equal to $m$. Each iteration of the binary search can be computed by iterating $O(\\log N)$ values in $G$ and using simple math. To find which value produces a certain final value, we just convert it back into $x \\times 2^y$ and find the value of $x+y$. Time complexity: $O(\\sqrt N \\log N + Q \\log^2N)$ Challenge: find the solution for $N \\leq 10^{18}$.",
    "tags": [
      "binary search",
      "bitmasks",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1725",
    "index": "E",
    "title": "Electrical Efficiency",
    "statement": "In the country of Dengkleknesia, there are $N$ factories numbered from $1$ to $N$. Factory $i$ has an electrical coefficient of $A_i$. There are also $N-1$ power lines with the $j$-th power line connecting factory $U_j$ and factory $V_j$. It can be guaranteed that each factory in Dengkleknesia is connected to all other factories in Dengkleknesia through one or more power lines. In other words, the collection of factories forms a tree. Each pair of different factories in Dengkleknesia can use one or more existing power lines to transfer electricity to each other. However, each power line needs to be turned on first so that electricity can pass through it.\n\nDefine $f(x, y, z)$ as the minimum number of power lines that need to be turned on so that factory $x$ can make electrical transfers to factory $y$ and factory $z$. Also define $g(x, y, z)$ as the number of \\textbf{distinct prime factors} of $\\text{GCD}(A_x, A_y, A_z)$.\n\nTo measure the electrical efficiency, you must find the sum of $f(x, y, z) \\times g(x, y, z)$ for all combinations of $(x, y, z)$ such that $1 \\leq x < y < z \\leq N$. Because the answer can be very large, you just need to output the answer modulo $998\\,244\\,353$.\n\nNote: $\\text{GCD}(k_1, k_2, k_3)$ is the greatest common divisor of $k_1$, $k_2$, and $k_3$, which is the biggest integer that simultaneously divides $k_1$, $k_2$, and $k_3$.",
    "tutorial": "Note that $\\sum_x \\sum_y \\sum_z f(x,y,z) \\times g(x,y,z)$ can be alternatively expressed as the following: Iterate through every edge $e$ and every prime $p$. In each iteration, consider the set of vertices $S = \\{x \\mid A_x \\text{ is divisible by } p\\}$. Count how many triplets $a,b,c \\in S$ such that each of the two components separated by $e$ contains at least one of $a,b,c$. Calculate the sum of those values for all possible $e$ and $p$. Note that if we root the tree and consider the edge $(x,y)$ where $x$ is the parent of $y$ in the rooted tree, then the number of triplets we count in one iteration is equivalent to $\\binom{|S|}{3} - \\binom{s}{3} - \\binom{|S|-s}{3}$, where $s$ is the number of vertices in $S$ in the subtree of $y$. To calculate the answer, we can iterate through each prime $p$. For each prime, we only consider the vertices in $S$. We can build a sparse representation of a tree containing the vertices in $S$ (i.e. a virtual/auxiliary tree). More precisely, we only consider a set of vertices $S'$, where $x \\in S'$ if and only if $x \\in S$ or there exists $y,z \\in S$ such that $\\text{LCA}(y,z) = x$ (here, $\\text{LCA}$ denotes the lowest common ancestor). It can be shown that $|S'| \\leq 2|S|$. Each edge in the sparse tree connecting two vertices in $S'$ is a simple ancestor-descendant path consisting of one or more edges of the original tree. Notice that the number of triplets we count for each edge in the original tree that is not used in the sparse tree is always $0$. Also, for the edges in the original tree that make up a single edge of the sparse tree, the number of triplets we count for each of them is the same. Therefore, using the sparse tree we built, we can run a simple dynamic programming to count the answer for a single prime $p$ in $O(|S|)$ time. Notice that there are at most $\\log A_x$ distinct prime factors of $A_x$, so the sum of $|S|$ for all primes is $O(N \\log \\max(A))$. Time complexity: $O(N \\log N \\log \\max(A))$ or $O(N (\\log N + \\log \\max(A)))$",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1725",
    "index": "E",
    "title": "Electrical Efficiency",
    "statement": "In the country of Dengkleknesia, there are $N$ factories numbered from $1$ to $N$. Factory $i$ has an electrical coefficient of $A_i$. There are also $N-1$ power lines with the $j$-th power line connecting factory $U_j$ and factory $V_j$. It can be guaranteed that each factory in Dengkleknesia is connected to all other factories in Dengkleknesia through one or more power lines. In other words, the collection of factories forms a tree. Each pair of different factories in Dengkleknesia can use one or more existing power lines to transfer electricity to each other. However, each power line needs to be turned on first so that electricity can pass through it.\n\nDefine $f(x, y, z)$ as the minimum number of power lines that need to be turned on so that factory $x$ can make electrical transfers to factory $y$ and factory $z$. Also define $g(x, y, z)$ as the number of \\textbf{distinct prime factors} of $\\text{GCD}(A_x, A_y, A_z)$.\n\nTo measure the electrical efficiency, you must find the sum of $f(x, y, z) \\times g(x, y, z)$ for all combinations of $(x, y, z)$ such that $1 \\leq x < y < z \\leq N$. Because the answer can be very large, you just need to output the answer modulo $998\\,244\\,353$.\n\nNote: $\\text{GCD}(k_1, k_2, k_3)$ is the greatest common divisor of $k_1$, $k_2$, and $k_3$, which is the biggest integer that simultaneously divides $k_1$, $k_2$, and $k_3$.",
    "tutorial": "Special thanks to Um_nik for sharing this solution! Let's call $(i)$ as type $1$ cycles, $(i,j)$ as type $2$ cycles and $(i,j,i+1,j+1)$ as type $3$ cycles. What we will do, is we will fix the number of type $3$ and type $2$ cycles and come up with a formula. Let's say there are $s$ type $3$ cycles. We need to pick $2s$ numbers from $[1,n-1]$ such that no two are adjacent. The number of ways to do this is $\\binom{n-2s}{2s}$. Then we can permute these numbers in $(2s)!$ ways and group the numbers in pairs of two, but these $s$ pairs can be permuted to get something equivalent, so we need to divide by $s!$. Hence we get: $\\begin{aligned}\\binom{n - 2s}{2s} \\frac{(2s)!}{s!} \\end{aligned}$Now, for the remaining $(n - 4s)$ elements, we know that only cycles will be of length $2$ or $1$. Let $I_k$ denote the number of permutations with cycles only of length $2$ and $1$. Then the final answer would be $\\begin{aligned} \\sum_{s=0}^{\\lfloor \\frac{n}{4} \\rfloor}{\\binom{n - 2s}{2s} \\frac{(2s)!}{s!} I_{n - 4s}} \\end{aligned}$Now, we would be done if we found out $I_k$ for all $k \\in {1, 2, ... n}$. Observe that $I_1 = 1$ and $I_2 = 2$. Further for $k > 2$, the $k$-th element can appear in a cycle of length $1$, where there are $I_{k - 1}$ ways to do it; and the $k$-th element can appear in a cycle of length two, which can be done in $(k - 1) \\cdot I_{k - 2}$ ways. Therefore we finally have: $\\begin{aligned} I_k = I_{k - 1} + (k - 1) \\cdot I_{k - 2}\\end{aligned}$This completes the solution. Time complexity: $\\mathcal{O}(n)$. Solution 2: the hard wayUsing the observations in Solution 1 this can be reduced to a counting problem using generating functions. Details follow. Now, from the remaining $n-4s$ numbers, let's pick $2k$ numbers to form $k$ type $2$ cycles. We can do this in $\\binom{n-4s}{2k}$ ways. Like before, we can permute them in $(2k)!$ ways, but we can shuffle these $k$ pairs around so we have to divide by $k!$. Also, $(i,j)$ and $(j,i)$ are the same cycle, so we also need to divide by $2^k$ because we can flip the pairs and get the same thing. Finally, we have the following formula: $\\begin{aligned} \\sum_{s=0}^{\\lfloor \\frac{n}{4} \\rfloor}{\\sum_{k=0}^{\\lfloor \\frac{n-4s}{2} \\rfloor}{\\frac{(2s)!}{s!}\\binom{n-2s}{2s}\\binom{n-4s}{2k}\\frac{(2k)!}{2^k k!}}} \\end{aligned}$We can simplify this to get, $\\begin{aligned} \\sum_{s=0}^{\\lfloor \\frac{n}{4} \\rfloor}{\\frac{(n-2s)!}{s!}\\sum_{k=0}^{\\lfloor \\frac{n-4s}{2} \\rfloor}{\\frac{1}{2^k (n-4s-2k)! k!}}} \\end{aligned}$Now, observe that the answer is in the form of two nested summations. Let us focus on precomputing the inner summation using generating functions. We define the following generating function: $\\begin{aligned} P(x) &= \\sum_{r \\ge 0}{ \\Bigg( \\sum_{k=0}^{\\lfloor \\frac{r}{2} \\rfloor}{\\frac{1}{2^k (r-2k)! k!}} \\Bigg) } x^r \\\\ &= \\sum_{r \\ge 0}{ \\Bigg( \\sum_{k=0}^{\\lfloor \\frac{r}{2} \\rfloor}{\\frac{x^r}{2^k (r-2k)! k!}} \\Bigg) } \\\\ &=\\sum_{r \\ge 0}{ \\Bigg( \\sum_{k=0}^{\\lfloor \\frac{r}{2} \\rfloor}{\\frac{x^{(r - 2k)}}{(r-2k)!} \\cdot \\frac{x^{2k}}{2^k k!}} \\Bigg) } \\\\ &= \\sum_{r \\ge 0}{ \\Bigg( \\sum_{k=0}^{\\lfloor \\frac{r}{2} \\rfloor}{\\frac{x^{(r - 2k)}}{(r-2k)!} \\cdot \\frac{\\big(\\frac {x^2}{2} \\big)^k}{k!}} \\Bigg) } \\\\ &= \\Bigg(\\sum_{i \\ge 0}{\\frac{x^{i}}{i!} \\Bigg)} \\cdot \\Bigg( \\sum_{j \\ge 0}{ \\frac{\\big(\\frac {x^2}{2} \\big)^j}{j!}} \\Bigg) \\\\ P(x) &= \\big(e^x \\big) \\cdot \\big( e^{\\frac {x^2}{2}} \\big) = e^{x + \\frac{x^2}{2}} \\end{aligned}$We can compute the first few terms of $e^x = \\sum_{i \\ge 0}{\\frac{x^{i}}{i!}}$ and $e^{\\frac {x^2}{2}} = \\sum_{j \\ge 0}{ \\frac{x^{2j}}{2^j j!}}$; and using FFT, we can multiply these (in $\\mathcal O(n \\log n)$ time) to get the first few terms of $P(x) = e^{x + \\frac{x^2}{2}}$. Finally, we can get the answer (in $\\mathcal O(n)$ time) as, $\\begin{aligned} \\sum_{s=0}^{\\lfloor \\frac{n}{4} \\rfloor}{\\frac{(n-2s)!}{s!} \\Big([x^{n-4s}] P(x) \\Big)} \\end{aligned}$where $[x^m]F(x)$ is the coefficient of $x^m$ in the Taylor expansion of $F(x)$. Time complexity: $\\mathcal{O}(\\max{(t_i)}\\log{\\max{(t_i)}} + \\sum{t_i})$, where $t_i$ is the value of $n$ in the $i$-th test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define ll long long\nconst int MAXN = 300005;\n\n/* PARTS OF CODE for fft taken from https://cp-algorithms.com/algebra/fft.html */\n\n\nconst ll mod = 998244353;\nconst ll root = 15311432; // which is basically 3 ^ 119 \nconst ll root_1 = 469870224;\nconst ll root_pw = (1 << 23);\n\nll fact[MAXN + 1], ifact[MAXN + 1], sum_pow[MAXN + 1];\nvector<ll> P(MAXN); // this will be the first few terms of e^(x + (x^2)/2).\n\nll fxp(ll a, ll n){ // returns a ^ n modulo mod in O(log(mod)) time\n\tif(!n){\n\t\treturn 1;\n\t}else if(n & 1){\n\t\treturn a * fxp(a, n ^ 1) % mod;\n\t}else{\n\t\tll v = fxp(a, n >> 1);\n\t\treturn v * v % mod;\n\t}\n}\n\ninline ll inverse(ll a){ // returns the modular inverse of \n\treturn fxp(a % mod, mod -2);\n}\n\nvoid init_fact(){ // initializes fact[ ] and ifact[ ]\n\tfact[0] = ifact[0] = 1;\n\tfor(int i = 1; i <= MAXN; ++i){\n\t\tfact[i] = fact[i - 1]  * i% mod;\n\t\tifact[i] = inverse(fact[i]);\n\t}\n}\n\nll C(ll n, ll r){ // returns nCr in O(1) time\n\treturn (r > n || r < 0) ? 0 : (ifact[r] * ifact[n - r] % mod * fact[n] % mod);\n}\n\n// code for fft in O(nlogn)\nvoid fft(vector<ll>& a, bool invert){\n\tint n = a.size();\n\n\t/// this does the bit inversion \n\tfor(int i = 1, j = 0; i < n; ++i){\n\t\tint bit = n >> 1;\n\t\tfor(; j & bit; bit >>= 1){\n\t\t\tj ^= bit;\n\t\t}\n\t\tj ^= bit;\n\t\tif(i < j){\n\t\t\tswap(a[i], a[j]);\n\t\t}\n\t}\n\n\tfor(int len = 2; len <= n; len <<= 1){\n\t\tll wlen = invert ? root_1: root;\n\t\tfor(int i = len; i < root_pw; i <<= 1){\n\t\t\twlen = wlen * wlen % mod;\n\t\t}\n\t\tfor(int i = 0; i < n; i += len){\n\t\t\tll w = 1;\n\t\t\tfor(int j = 0; j < len / 2; ++j){\n\t\t\t\tll u = a[i + j], v = a[i + j + len / 2] * w % mod;\n\t\t\t\ta[i + j] = u + v < mod ? u + v : u + v - mod;\n\t\t\t\ta[i + j + len / 2] = u - v >= 0 ? u - v : u - v + mod;\n\t\t\t\tw = w * wlen % mod;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(invert){\n\t\tll n_1 = inverse(n);\n\t\tfor(ll& x : a){\n\t\t\tx = x * n_1 % mod;\n\t\t}\n\t}\n}\n\n//multiplying two polynomials a and b using ntt in O(max(A, B)log(max(A, B))), where A, B are degrees of a, b respectively\nvector<ll> mul(vector<ll> const& a, vector<ll> const& b){\n\n\tvector<ll> fa(a.begin(), a.end()), fb(b.begin(), b.end());\n\tint n = 1;\n\twhile(n < (int)a.size() + (int)b.size()){\n\t\tn <<= 1;\n\t}\n\tfa.resize(n);\n\tfb.resize(n);\n\n\tfft(fa, false);\n\tfft(fb, false);\n\tfor(int i = 0; i < n; ++i){\n\t\tfa[i] = fa[i] * fb[i] % mod;\n\t}\n\tfft(fa, true);\n\twhile(fa.size() > 1 && fa[fa.size() - 1] == 0){\n\t\tfa.pop_back();\n\t}\n\n\treturn fa;\n}\n\n/* End of FFT Template */\n\ninline void init(){ // precomputes the first few terms of P(x) = e^(x + (x ^ 2) / 2)\n\tinit_fact();\n\tvector<ll> e_x(MAXN), e_x2_by2(MAXN);\n\tll modular_inverse_of_2 = (mod + 1) / 2; \n\n\tfor(int i = 0; i < MAXN; ++i){\n\t\te_x[i] = ifact[i]; // e^x = sum{x^k / k!}\n\t\te_x2_by2[i] = ((i & 1)) ? 0 : ifact[i / 2] * fxp(modular_inverse_of_2, i / 2) % mod; // e^((x^2)/2) = sum{(x^2k)/(k!.(2^k))}\n\t}\n\n\tP = mul(e_x, e_x2_by2); // P(x) = e^(x + (x ^ 2) / 2) = (e ^ x) . (e ^ ((x ^ 2) / 2))\n}\n\nvoid test_case(){\n\n\tint N;\n\tcin >> N;\n\n\tll ans = 0;\n\tfor(int s = 0; s <= N / 4; ++s){ // computing the answer for N using the precomputed P(x) polynomial\n\t\tans = (ans + fact[N - 2 * s] * ifact[s] % mod * P[N - 4 * s]) % mod;\n\t}\n\n\tcout << ans << '\n';\n}\n\nsigned main(){\n\n\tios_base::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n\t\n\tinit();\n\tint test_case_number;\n\tcin>>test_case_number;\n\twhile(test_case_number--)\n\t\ttest_case();\n\t\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1725",
    "index": "F",
    "title": "Field Photography",
    "statement": "Pak Chanek is traveling to Manado. It turns out that OSN (Indonesian National Scientific Olympiad) 2019 is being held. The contestants of OSN 2019 are currently lining up in a field to be photographed. The field is shaped like a grid of size $N \\times 10^{100}$ with $N$ rows and $10^{100}$ columns. The rows are numbered from $1$ to $N$ from north to south, the columns are numbered from $1$ to $10^{100}$ from west to east. The tile in row $r$ and column $c$ is denoted as $(r,c)$.\n\nThere are $N$ provinces that participate in OSN 2019. Initially, each contestant who represents province $i$ stands in tile $(i, p)$ for each $p$ satisfying $L_i \\leq p \\leq R_i$. So, we can see that there are $R_i-L_i+1$ contestants who represent province $i$.\n\nPak Chanek has a variable $Z$ that is initially equal to $0$. In one operation, Pak Chanek can choose a row $i$ and a positive integer $k$. Then, Pak Chanek will do one of the two following possibilities:\n\n- Move all contestants in row $i$ exactly $k$ tiles to the west. In other words, a contestant who is in $(i, p)$ is moved to $(i, p-k)$.\n- Move all contestants in row $i$ exactly $k$ tiles to the east. In other words, a contestant who is in $(i, p)$ is moved to $(i, p+k)$.\n\nAfter each operation, the value of $Z$ will change into $Z \\text{ OR } k$, with $\\text{OR}$ being the bitwise OR operation. Note that Pak Chanek can do operations to the same row more than once. Also note that Pak Chanek is not allowed to move contestants out of the grid.\n\nThere are $Q$ questions. For the $j$-th question, you are given a positive integer $W_j$, Pak Chanek must do zero or more operations so that the final value of $Z$ is \\textbf{exactly} $W_j$. Define $M$ as the biggest number such that after all operations, there is at least one \\textbf{column} that contains exactly $M$ contestants. For each question, you must find the biggest possible $M$ for all sequences of operations that can be done by Pak Chanek. Note that the operations done by Pak Chanek for one question do not carry over to other questions.",
    "tutorial": "Let's consider some value of $W_j$. Let $b$ be the LSB (Least Significant Bit) of $W_j$. Which means $b$ is the minimum number such that the bit in index $b$ in the binary representation of $W_j$ is active. Note: the bits are indexed from $0$ from the right. For a sequence of operations, define $\\text{dis}(i)$ as how many tiles to the east the final positions of the contestants in row $i$ compared to their initial position. Specifically, if their final positions are more to the west, then $\\text{dis}(i)$ is negative. Notice that each move we make must be a distance that is a multiple of $2^b$. Because if we move a distance that is not a multiple of $2^b$, at least one of the bits with indices smaller than $b$ will be activated, which we do not want. This means $\\text{dis}(i)$ must be a multiple of $2^b$. However, we can make each $\\text{dis}(i)$ to be any integer that is a multiple of $2^b$ while making $Z = W_j$ by doing the following strategy: Only do moves with distances of exactly $2^b$ to move the contestants in each row to their final positions. Move one row with a distance of $W_j$ to the east, then to the west. Using the knowledge above, we can see that for each row $i$, there are three cases: If $R_i-L_i+1 \\geq 2^b$, then each column can be occupied. Else, if $(L_i \\mod 2^b) \\leq (R_i \\mod 2^b)$, then only each column $c$ such that $(L_i \\mod 2^b) \\leq (c \\mod 2^b) \\leq (R_i \\mod 2^b)$ can be occupied. Else, then only each column $c$ such that $(L_i \\mod 2^b) \\leq (c \\mod 2^b)$ or $(c \\mod 2^b) \\leq (R_i \\mod 2^b)$ can be occupied. We can see that each row has at most two subsegments of the segment $[0, 2^b-1]$ denoting the occupiable columns modulo $2^b$. Now we just need to find the position that intersects the most subsegments. To solve this, we can use line sweep. To handle the $Q$ queries, notice that the number of possible distinct values for the LSB of $W_j$ are only $\\lfloor \\log_2 10^9 \\rfloor + 1 = 30$. So we can precompute the answer for each of the $30$ possible LSB, then answer the queries using the precomputed answers. Time complexity: $O(N\\log N \\log \\max(W) + Q \\log \\max(W))$",
    "tags": [
      "bitmasks",
      "data structures",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1725",
    "index": "G",
    "title": "Garage",
    "statement": "Pak Chanek plans to build a garage. He wants the garage to consist of a square and a right triangle that are arranged like the following illustration.\n\nDefine $a$ and $b$ as the lengths of two of the sides in the right triangle as shown in the illustration. An integer $x$ is suitable if and only if we can construct a garage with assigning \\textbf{positive integer} values for the lengths $a$ and $b$ ($a<b$) so that the area of the square at the bottom is exactly $x$. As a good friend of Pak Chanek, you are asked to help him find the $N$-th smallest suitable number.",
    "tutorial": "Let $c$ be the bottom side of the right triangle (the side that is not $a$ or $b$). From Pythagorean theorem, we know that $a^2+c^2 = b^2$, so $c^2 =b^2-a^2$. We can see that the area of the square at the bottom is $c^2$. So an integer is suitable if and only if it can be expressed as $b^2-a^2$ for some positive integers $a$ and $b$ ($a<b$). Consider the case if $b=a+1$. Then $b^2-a^2 = (a+1)^2-a^2 = a^2+2a+1-a^2 = 2a+1$. Since $a$ must be a positive integer, then all possible results for this case are all odd integers that are greater than or equal to $3$. Consider the case if $b=a+2$. Then $b^2-a^2 = (a+2)^2-a^2 = a^2+4a+4-a^2 = 4a+4$. Since $a$ must be a positive integer, then all possible results for this case are all integers that are multiples of $4$ that are greater than or equal to $8$. Let's consider an integer that has a remainder of $2$ when divided by $4$. We can get that such an integer can never be expressed as $b^2-a^2$. This is because of the fact that any square number when divided by $4$ must have a remainder of either $0$ or $1$. Using a simple brute force, we can get that $1$ and $4$ cannot be expressed as $b^2-a^2$. Using all of the information above, we can see that all suitable numbers are only all odd integers that are greater than or equal to $3$ and all integers that are multiples of $4$ that are greater than or equal to $8$. In order to find the $N$-th smallest suitable number, we can do a binary search on a value $d$. In each iteration of the binary search, we check whether there are at least $N$ suitable numbers that are less than or equal to $d$. Alternatively, we can use a mathematical formula to find the $N$-th smallest suitable number in $O(1)$ time complexity. Time Complexity: $O(\\log N)$ or $O(1)$",
    "tags": [
      "binary search",
      "geometry",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1725",
    "index": "H",
    "title": "Hot Black Hot White",
    "statement": "One day, you are accepted as being Dr. Chanek's assistant. The first task given by Dr. Chanek to you is to take care and store his magical stones.\n\nDr. Chanek has $N$ magical stones with $N$ being an even number. Those magical stones are numbered from $1$ to $N$. Magical stone $i$ has a strength of $A_i$. A magical stone can be painted with two colours, namely the colour black or the colour white. You are tasked to paint the magical stones with the colour black or white and store the magical stones into a magic box with a magic coefficient $Z$ ($0 \\leq Z \\leq 2$). The painting of the magical stones must be done in a way such that there are $\\frac{N}{2}$ black magical stones and $\\frac{N}{2}$ white magical stones.\n\nDefine $\\text{concat}(x, y)$ for two integers $x$ and $y$ as the result of concatenating the digits of $x$ to the left of $y$ in their decimal representation without changing the order. As an example, $\\text{concat}(10, 24)$ will result in $1024$.\n\nFor a magic box with a magic coefficient $Z$, magical stone $i$ will react with magical stone $j$ if the colours of both stones are different and $\\text{concat}(A_i, A_j) \\times \\text{concat}(A_j, A_i) + A_i \\times A_j \\equiv Z \\mod 3$. A magical stone that is reacting will be very hot and dangerous. Because of that, you must colour the magical stones and determine the magic coefficient $Z$ of the magic box in a way such that there is no magical stone that reacts, or report if it is impossible.",
    "tutorial": "Notice that $10 \\equiv 1 \\mod 3$. Hence, if $k$ denotes the number of digits in $A_j$, $\\text{concat}(A_i, A_j) \\mod 3= (A_i \\times 10^k + A_j) \\mod 3 = (A_i \\times 1^k + A_j) \\mod 3 = (A_i + A_j) \\mod 3$. Then one can simplify the equation that determines the reaction of stone $i$ and stone $j$ as follows. $\\begin{align} \\text{concat}(A_i, A_j) \\times \\text{concat}(A_j, A_i) + A_i A_j & \\equiv Z \\mod 3 \\\\ (A_i + A_j) (A_i + A_j) + A_i A_j & \\equiv Z \\mod 3 \\\\ A_i^2 + 2 A_i A_j + A_j^2 + A_i A_j & \\equiv Z \\mod 3 \\\\ A_i^2 + A_j^2 + 3 A_i A_j & \\equiv Z \\mod 3 \\\\ A_i^2 + A_j^2 & \\equiv Z \\mod 3 \\\\ \\end{align}$ $0^2 = 0 \\equiv 0 \\mod 3$. $1^2 = 1 \\equiv 1 \\mod 3$. $2^2 = 4 \\equiv 1 \\mod 3$. So the value of $A_i^2 \\mod 3$ is either $0$ or $1$. We can get a construction that consists of the two following cases: If there are at least $\\frac{N}{2}$ stones having $A_i^2 \\equiv 0 \\mod 3$, then we can colour the stones such that one of the colours only occurs in all stones with $A_i^2 \\equiv 0 \\mod 3$. In this construction, there is no pair of stones with different colours that both have $A_i^2 \\equiv 1 \\mod 3$. So we can assign $Z=2$. If there are less than $\\frac{N}{2}$ stones having $A_i^2 \\equiv 0 \\mod 3$, then there are at least $\\frac{N}{2}$ stones having $A_i^2 \\equiv 1 \\mod 3$, so we can colour the stones such that one of the colours only occurs in all stones with $A_i^2 \\equiv 1 \\mod 3$. In this construction, there is no pair of stones with different colours that both have $A_i^2 \\equiv 0 \\mod 3$. So we can assign $Z=0$. Time complexity: $O(N)$",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1725",
    "index": "I",
    "title": "Imitating the Key Tree",
    "statement": "Pak Chanek has a tree called the key tree. This tree consists of $N$ vertices and $N-1$ edges. The edges of the tree are numbered from $1$ to $N-1$ with edge $i$ connecting vertices $U_i$ and $V_i$. Initially, each edge of the key tree does not have a weight.\n\nFormally, a path with length $k$ in a graph is a sequence $[v_1, e_1, v_2, e_2, v_3, e_3, \\ldots, v_k, e_k, v_{k+1}]$ such that:\n\n- For each $i$, $v_i$ is a vertex and $e_i$ is an edge.\n- For each $i$, $e_i$ connects vertices $v_i$ and $v_{i+1}$.\n\nA circuit is a path that starts and ends on the same vertex.\n\nA path in a graph is said to be simple if and only if the path does not use the same edge more than once. Note that a simple path can use the same vertex more than once.\n\nThe cost of a simple path in a weighted graph is defined as the \\textbf{maximum weight} of all edges it traverses.\n\nCount the number of distinct undirected weighted graphs that satisfy the following conditions:\n\n- The graph has $N$ vertices and $2N-2$ edges.\n- For each pair of different vertices $(x, y)$, there exists a simple circuit that goes through vertices $x$ and $y$ in the graph.\n- The weight of each edge in the graph is an integer between $1$ and $2N-2$ inclusive. Each edge has \\textbf{distinct} weights.\n- The graph is formed in a way such that there is a way to assign a weight $W_i$ to each edge $i$ in the key tree that satisfies the following conditions:\n\n- For each pair of edges $(i, j)$, if $i<j$, then $W_i<W_j$.\n- For each pair of different vertex indices $(x, y)$, the cost of the only simple path from vertex $x$ to $y$ in the key tree is equal to the \\textbf{minimum cost} of a simple circuit that goes through vertices $x$ and $y$ in the graph.\n\n- Note that the graph is allowed to have multi-edges, but is not allowed to have self-loops.\n\nPrint the answer modulo $998\\,244\\,353$.\n\nTwo graphs are considered distinct if and only if there exists a triple $(a, b, c)$ such that there exists an edge that connects vertices $a$ and $b$ with weight $c$ in one graph, but not in the other.",
    "tutorial": "Let's say we have two graphs, each having $N$ vertices. Initially, there are no edges. We want to make the first graph into a graph that satisfies the condition of the problem and make the second graph into the key tree with a weight assignment that corresponds to the first graph. Sequentially for each $k$ from $1$ to $2N-2$, do all of the following: Add an edge with weight $k$ to the first graph. Choose one of the following: Add an edge with weight $k$ to the second graph. Do nothing. Add an edge with weight $k$ to the second graph. Do nothing. In order to make the second graph into the key tree, we must add exactly $N-1$ edges to it throughout the process and the $i$-th edge added is edge $i$ of the key tree. In an iteration, if we choose to not add an edge to the second graph, it can be obtained that the edge added to the first graph must not merge any biconnected components. Let's call this type of edge in the first graph an idle edge. Otherwise, if we choose to add an edge to the second graph, it can be obtained that the following must be satisfied: Let $c_1$ and $c_2$ be the connected components of the second graph that are merged by adding the new edge. The edge added to the first graph must merge exactly two biconnected components, each of them containing vertices with the same indices as the ones in each of $c_1$ and $c_2$. Let's call this type of edge in the first graph a connector edge. We can see that there must be exactly $N-1$ connector edges in the first graph. The only way to make it such that adding an edge connects exactly two biconnected components is to already have exactly one existing edge connecting the two biconnected components. Let's call this type of existing edge a helper edge. It can be obtained that an edge cannot be a helper edge of more than one connector edge. Because we only have $2N-2$ edges for the first graph, those edges must only consist of $N-1$ connector edges and $N-1$ helper edges. This means all helper edges must be idle edges. But it can be obtained that each helper edge in our construction is always an idle edge. The $i$-th connector edge and its corresponding helper edge must connect the two biconnected components that correspond to the two connected components merged using edge $i$ of the key tree. If the sizes of the connected components are $s_1$ and $s_2$, then there are $(s_1 \\times s_2)^2$ possible pairs of connector and helper edges. The number of ways to choose which edge to add in each iteration is the same as the number of ways to colour a sequence of $2N-2$ elements with $N-1$ colours (numbered from $1$ to $N-1$) such that: Each colour occurs in exactly $2$ elements. For each pair of colours $(i, j)$, if $i<j$, then the latest element with colour $i$ must occur earlier than the latest element with colour $j$. We can see that the number of ways is $\\frac{(2N-2)!}{(2!)^{N-1}\\times (N-1)!}$. To get the answer to the problem, we just multiply this value by each of the $(s_1 \\times s_2)^2$ for each merged pair of connected components in the key tree. Time complexity: $O(N)$",
    "tags": [
      "combinatorics",
      "dsu",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1725",
    "index": "J",
    "title": "Journey",
    "statement": "One day, Pak Chanek who is already bored of being alone at home decided to go traveling. While looking for an appropriate place, he found that Londonesia has an interesting structure.\n\nAccording to the information gathered by Pak Chanek, there are $N$ cities numbered from $1$ to $N$. The cities are connected to each other with $N-1$ two-directional roads, with the $i$-th road connecting cities $U_i$ and $V_i$, and taking a time of $W_i$ hours to be traversed. In other words, Londonesia's structure forms a tree.\n\nPak Chanek wants to go on a journey in Londonesia starting and ending in any city (not necessarily the same city) such that each city is visited \\textbf{at least once} with the least time possible. In order for the journey to end quicker, Pak Chanek also carries an instant teleportation device for moving from one city to any city that can only be used at most once. Help Pak Chanek for finding the minimum time needed.\n\nNotes:\n\n- Pak Chanek only needs to visit each city at least once. Pak Chanek does not have to traverse each road.\n- In the journey, a city or a road can be visited more than once.",
    "tutorial": "For a journey, define $\\text{cnt}(i)$ as a non-negative integer representing the number of times Pak Chanek traverses road $i$ throughout the journey. First, let's solve the simpler problem where we cannot teleport. It can be obtained that the configuration of $\\text{cnt}(i)$ for an optimal journey in this version of the problem is as follows: The roads with $\\text{cnt}(i)=1$ form a simple path. Every other road outside of the path has $\\text{cnt}(i)=2$. If we add the ability to teleport at most once, the configuration of $\\text{cnt}(i)$ is similar, but the roads with $\\text{cnt}(i)=1$ form two distinct simple paths, with both paths not containing any common roads. Let's denote these two paths as $P_1$ and $P_2$. Notice that $P_1$ and $P_2$ can only have either one common city or no common cities at all. It can be obtained that the optimal configuration for each case is as follows: If $P_1$ and $P_2$ have one common city, every other road outside of $P_1$ and $P_2$ must have $\\text{cnt}(i)=2$. If $P_1$ and $P_2$ have no common cities, we have the opportunity to pick one road in the path between $P_1$ and $P_2$ and assign $\\text{cnt}(i)=0$. Then, every other road must have $\\text{cnt}(i)=2$. It can be shown that for any configuration of $\\text{cnt}(i)$ satisfying the constraints above, there always exists a valid journey that corresponds to that configuration. So we must find the configuration that results in the minimum time for each case. For the first case, we can precompute a tree DP with rerooting and try each possible common city to get the optimal answer. For the second case, we can also precompute a tree DP with rerooting and try each possible road with $\\text{cnt}(i)=0$ to get the optimal answer.",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1725",
    "index": "K",
    "title": "Kingdom of Criticism",
    "statement": "Pak Chanek is visiting a kingdom that earned a nickname \"Kingdom of Criticism\" because of how often its residents criticise each aspect of the kingdom. One aspect that is often criticised is the heights of the buildings. The kingdom has $N$ buildings. Initially, building $i$ has a height of $A_i$ units.\n\nAt any point in time, the residents can give a new criticism, namely they currently do not like buildings with heights between $l$ and $r$ units inclusive for some two integers $l$ and $r$. It is known that $r-l$ is always odd.\n\nIn $1$ minute, the kingdom's construction team can increase or decrease the height of any building by $1$ unit as long as the height still becomes a positive number. Each time they receive the current criticism from the residents, the kingdom's construction team makes it so that there are no buildings with heights between $l$ and $r$ units inclusive in the \\textbf{minimum time possible}. It can be obtained that there is only one way to do this.\n\nNote that the construction team only cares about the current criticism from the residents. All previous criticisms are forgotten.\n\nThere will be $Q$ queries that you must solve. Each query is one of the three following possibilities:\n\n- 1 k w: The kingdom's construction team changes the height of building $k$ to be $w$ units ($1 \\leq k \\leq N$, $1 \\leq w \\leq 10^9$).\n- 2 k: The kingdom's construction team wants you to find the height of building $k$ ($1 \\leq k \\leq N$).\n- 3 l r: The residents currently do not like buildings with heights between $l$ and $r$ units inclusive ($2 \\leq l \\leq r \\leq 10^9-1$, $r-l$ is odd).\n\nNote that each change in height still persists to the next queries.",
    "tutorial": "We can see that the changes in height for a single query of type $3$ are as follows: Each building with height $x$ such that $l \\leq x \\leq \\frac{l+r}{2}$ is changed to have a height of $l-1$. Each building with height $x$ such that $\\frac{l+r}{2} \\leq x \\leq r$ is changed to have a height of $r+1$. Note: since $r-l$ is odd, $\\frac{l+r}{2}$ is not an integer. So there is no uncertainty here. We can group the buildings into their heights, so buildings with the same height belong in the same group. We can maintain all the different groups in a set such that the groups are sorted by their heights. We can see that using this set, we can perform a type $3$ query by merging several groups into a single group with a certain height. Note that each time we merge $k$ groups, the number of groups decreases by $k-1$. For each building, to maintain its height while doing all the merging of several groups and the changing of height of an entire group, we can use a simple disjoint-set data structure to make it such that we can request the height of any building quickly. More specifically, each group is represented as a single connected component. The merging of several groups is equivalent to the merging of several connected components. The changing of height of an entire group can be done by changing the height of the representative building in a connected component. However, a query of type $1$ can break our structure. Changing the height of a single building can make it leave its current group and join another group or make a new group. In order to not break our disjoint-set data structure, each time there is a type $1$ query, we can just leave the old building with the old height alone and make a new building with the new height. After this, each request for this building's height is referred to the new representation we just created. Each query of type $1$ creates one new building representation and can create at most one new group. Using this solution, we can see that: A type $1$ query is done in $O(\\log(N+Q))$ time because we have to make changes to the set. This query creates one new building representation and can create at most one new group. A type $2$ query is done in $O(1)$ time. A type $3$ query is done in $O(k\\log(N+Q))$ time with $k$ being the number of groups we merge. This query decreases the number of groups by $k-1$. Time complexity: $O((N+Q)\\log(N+Q))$ Note: there is also an unintended solution using small-to-large with time complexity of $O((N+Q)\\log^2(N+Q))$, but it needs optimisations in order to pass the time limit.",
    "tags": [
      "data structures",
      "dsu"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1725",
    "index": "L",
    "title": "Lemper Cooking Competition",
    "statement": "Pak Chanek is participating in a lemper cooking competition. In the competition, Pak Chanek has to cook lempers with $N$ stoves that are arranged sequentially from stove $1$ to stove $N$. Initially, stove $i$ has a temperature of $A_i$ degrees. A stove can have a negative temperature.\n\nPak Chanek realises that, in order for his lempers to be cooked, he needs to keep the temperature of each stove at a non-negative value. To make it happen, Pak Chanek can do zero or more operations. In one operation, Pak Chanek chooses one stove $i$ with $2 \\leq i \\leq N-1$, then:\n\n- changes the temperature of stove $i-1$ into $A_{i-1} := A_{i-1} + A_{i}$,\n- changes the temperature of stove $i+1$ into $A_{i+1} := A_{i+1} + A_{i}$, and\n- changes the temperature of stove $i$ into $A_i := -A_i$.\n\nPak Chanek wants to know the minimum number of operations he needs to do such that the temperatures of all stoves are at non-negative values. Help Pak Chanek by telling him the minimum number of operations needed or by reporting if it is not possible to do.",
    "tutorial": "Note that an operation is identical to choosing an index $p$ ($1 < p < N$) and doing the following things simultaneously: Increase $A_{p-1}$ by $A_p$. Increase $A_p$ by $-2 A_p$. Increase $A_{p+1}$ by $A_p$. Let's maintain array $A$ using its prefix sum $B_0, B_1, B_2, \\ldots, B_N$. Formally, define $B_i = A_1 + A_2 + \\ldots + A_i$. In particular, $B_0 = 0$. We can see that an operation at index $p$ changes $B$ as follows: For each index $i$ such that $0 \\leq i \\leq p-2$, $B_i$ does not change. $B_{p-1}$ increases by $A_p$. So, $B_{p-1}$ increases by $B_p - B_{p-1}$. Therefore, $B_{p-1}$ changes into $B_p$. $B_p$ increases by $A_p - 2 A_p = -A_p$. So, $B_p$ increases by $B_{p-1} - B_p$. Therefore, $B_p$ changes into $B_{p-1}$. For each index $i$ such that $p+1 \\leq i \\leq N$, $B_i$ increases by $A_p - 2 A_p + A_p = 0$. So $B_i$ does not change. Note that all of the above happen simultaneously. Therefore, an operation at index $p$ only swaps the values of $B_p$ and $B_{p-1}$. So, in one operation, we can swap two adjacent values of $B$ other than $B_0$ or $B_N$. Making every $A_i$ non-negative is equivalent to making it such that $B_0 \\leq B_1 \\leq B_2 \\leq \\ldots \\leq B_N$. So, if there is a value of $B_i$ ($1 \\leq i \\leq N-1$) such that $B_i < B_0$ or $B_i > B_N$, then it is impossible. Otherwise, it is always possible. To count the number of adjacent swaps to sort $B$, we can just count the number of inversions in $B$. This can be done using Fenwick Tree or other methods. Time complexity: $O(N \\log N)$",
    "tags": [
      "data structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1725",
    "index": "M",
    "title": "Moving Both Hands",
    "statement": "Pak Chanek is playing one of his favourite board games. In the game, there is a directed graph with $N$ vertices and $M$ edges. In the graph, edge $i$ connects two different vertices $U_i$ and $V_i$ with a length of $W_i$. By using the $i$-th edge, something can move from $U_i$ to $V_i$, but not from $V_i$ to $U_i$.\n\nTo play this game, initially Pak Chanek must place both of his hands onto two different vertices. In one move, he can move one of his hands to another vertex using an edge. To move a hand from vertex $U_i$ to vertex $V_i$, Pak Chanek needs a time of $W_i$ seconds. Note that Pak Chanek can only move one hand at a time. This game ends when both of Pak Chanek's hands are on the same vertex.\n\nPak Chanek has several questions. For each $p$ satisfying $2 \\leq p \\leq N$, you need to find the minimum time in seconds needed for Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex $1$ and vertex $p$, or report if it is impossible.",
    "tutorial": "Suppose we are trying to find out the minimum time to get the hands from vertices $1$ and $k$ to the same vertex. If both hands end up on some vertex $v$, then the time required is $d(1,v) + d(k,v)$, with $d(x,y)$ being the minimum distance to go from vertex $x$ to $y$. Suppose $d'(x,y)$ is the minimum distance to go from vertex $x$ to $y$ in the reversed graph (i.e. all edges' directions are reversed). Then $d(1,v) + d(k,v) = d(1,v) + d'(v,k)$. The minimum time if both hands are initially on vertices $1$ and $k$ is the minimum value of $d(1,v) + d'(v,k)$ for all vertices $v$. This is the same as the minimum distance to go from vertex $1$ to $k$ where in the middle of our path, we can reverse the graph at most once. Therefore we can set up a graph like the following: Each vertex is a pair $(x,b)$, where $x$ is a vertex in the original graph and $b$ is a boolean determining whether we have already reversed the graph or not. For each edge $i$ in the original graph, there is an edge from $(U_i, 0)$ to $(V_i, 0)$ and an edge from $(V_i, 1)$ to $(U_i, 1)$, both with weight $W_i$. For each vertex $x$ in the original graph, there is a edge from $(x,0)$ to $(x,1)$ with weight $0$. After this, we do the Dijkstra algorithm once on the new graph from vertex $(1, 0)$. Then, the optimal time if both hands start from vertices $1$ and $k$ in the original graph is equal to $d((1,0), (k,1))$ in the new graph. Time complexity: $O(N+M \\log M)$",
    "tags": [
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1726",
    "index": "A",
    "title": "Mainak and Array",
    "statement": "Mainak has an array $a_1, a_2, \\ldots, a_n$ of $n$ positive integers. He will do the following operation to this array \\textbf{exactly once}:\n\n- Pick a subsegment of this array and cyclically rotate it by any amount.\n\nFormally, he can do the following exactly once:\n\n- Pick two integers $l$ and $r$, such that $1 \\le l \\le r \\le n$, and any positive integer $k$.\n- Repeat this $k$ times: set $a_l=a_{l+1}, a_{l+1}=a_{l+2}, \\ldots, a_{r-1}=a_r, a_r=a_l$ (all changes happen at the same time).\n\nMainak wants to \\textbf{maximize} the value of $(a_n - a_1)$ after exactly one such operation. Determine the maximum value of $(a_n - a_1)$ that he can obtain.",
    "tutorial": "There are four candidates of the maximum value of $a_n - a_1$ achievable, each of which can be found in $\\mathcal O(n)$ time. No subarray is chosen: Answer would be $a_n - a_1$ in this case. Chosen subarray contains $a_n$ and $a_1$ : Answer would be $\\max\\limits_{i = 1}^n\\{ a_{(i - 1)} - a_i\\}$ where $a_0$ is same as $a_n$ (notice that the previous case is included in this case as well). Chosen subarray doesn't contain $a_n$ : Answer would be $\\max\\limits_{i = 1}^{n - 1}\\{a_n - a_i\\}$. Chosen subarray doesn't contain $a_1$ : Answer would be $\\max\\limits_{i = 2}^n\\{a_i - a_1\\}$. Finally we report the maximum of all of these four values in total time $\\mathcal O(n)$.",
    "code": "t=int(input())\nfor _ in range(t):\n    n=int(input())\n    a=[int(x) for x in input().split()]\n    ans=max(a[-1]-min(a),max(a)-a[0])\n    for i in range(n):\n        ans=max(ans,a[i-1]-a[i])\n    print(ans)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1726",
    "index": "B",
    "title": "Mainak and Interesting Sequence",
    "statement": "Mainak has two positive integers $n$ and $m$.\n\nMainak finds a sequence $a_1, a_2, \\ldots, a_n$ of $n$ positive integers interesting, if \\textbf{for all} integers $i$ ($1 \\le i \\le n$), the bitwise XOR of all elements in $a$ which are \\textbf{strictly less} than $a_i$ is $0$. Formally if $p_i$ is the bitwise XOR of all elements in $a$ which are strictly less than $a_i$, then $a$ is an interesting sequence if $p_1 = p_2 = \\ldots = p_n = 0$.\n\nFor example, sequences $[1,3,2,3,1,2,3]$, $[4,4,4,4]$, $[25]$ are interesting, whereas $[1,2,3,4]$ ($p_2 = 1 \\ne 0$), $[4,1,1,2,4]$ ($p_1 = 1 \\oplus 1 \\oplus 2 = 2 \\ne 0$), $[29,30,30]$ ($p_2 = 29 \\ne 0$) aren't interesting.\n\nHere $a \\oplus b$ denotes bitwise XOR of integers $a$ and $b$.\n\nFind any interesting sequence $a_1, a_2, \\ldots, a_n$ (or report that there exists no such sequence) such that the sum of the elements in the sequence $a$ is equal to $m$, i.e. $a_1 + a_2 \\ldots + a_n = m$.\n\nAs a reminder, the bitwise XOR of an empty sequence is considered to be $0$.",
    "tutorial": "Lemma: In an interesting sequence $a_1, a_2, \\ldots, a_n$, every element other than the largest must have even occurrences. Proof: For the sake of contradiction, assume that for some $x$ ($x > 0$), such than $x \\ne \\max\\limits_{i = 1}^n\\{a_i\\}$, $x$ appears an odd number of times. Let $P(z)$ denote the bitwise XOR of all elements in $a$ that are less than $z$. By assumption $P(x) = 0$. Now, since $x$ is not maximum of the sequence $a$, there exists $y$ in $a$, such that $x < y$ and there are no other elements $t$ such that $x < t < y$ (in other words, $y$ is the immediate larger element of $x$ in $a$). Again, $P(y) = 0$ as well by assumption. However, since $x$ appears an odd number of times, we have: $0 = P(y) = P(x) \\oplus x = 0 \\oplus x = x$, which is a contradiction as $x$ must be positive. This gives us an $\\mathcal O(n)$ solution as follows: Case - I: If $n > m$ - It is clearly impossible to construct an interesting sequence with sum equal to $m$ (as integers must be positive). Case - II: $n$ is odd - Create $(n - 1)$ occurrences of $1$, and a single occurrence of $(m-n+1)$. Case - III: $n$ is even, $m$ is even - Create $(n - 2)$ occurrences of $1$ and two occurrences of $(m - n + 2)/2$. Case - IV: $n$ is even, $m$ is odd - No such interesting sequences exist. Proof: For the sake of contradiction assume that such an interesting sequence, $a$, exists. Since $m$ is odd, there must be an odd number $x$ that occurs an odd number of times in $a$. Again since $n$ is even there must be another integer $y$ (different from $x$) that occurs an also odd number of times. Hence either $x$ or $y$ (whichever is lower) violates the lemma. Proof: For the sake of contradiction assume that such an interesting sequence, $a$, exists. Since $m$ is odd, there must be an odd number $x$ that occurs an odd number of times in $a$. Again since $n$ is even there must be another integer $y$ (different from $x$) that occurs an also odd number of times. Hence either $x$ or $y$ (whichever is lower) violates the lemma.",
    "code": "import sys\ninput = sys.stdin.readline\n\nt=int(input())\nfor _ in range(t):\n    n,m=map(int,input().split())\n    if n>m or (n%2==0 and m%2==1):\n        print(\"NO\")\n    else:\n        print(\"YES\")\n        ans=[]\n        if n%2==1:\n            ans.extend([1]*(n-1)+[m-n+1])\n        else:\n            ans.extend([1]*(n-2)+[(m-n+2)//2]*2)\n        print(*ans,sep=' ')",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1726",
    "index": "C",
    "title": "Jatayu's Balanced Bracket Sequence",
    "statement": "Last summer, Feluda gifted Lalmohan-Babu a \\textbf{balanced} bracket sequence $s$ of length $2 n$.\n\nTopshe was bored during his summer vacations, and hence he decided to draw an undirected graph of $2 n$ vertices using the \\underline{balanced bracket sequence} $s$. For any two distinct vertices $i$ and $j$ ($1 \\le i < j \\le 2 n$), Topshe draws an edge (undirected and unweighted) between these two nodes if and only if the \\underline{subsegment} $s[i \\ldots j]$ forms a balanced bracket sequence.\n\nDetermine the number of \\underline{connected components} in Topshe's graph.\n\nSee the Notes section for definitions of the underlined terms.",
    "tutorial": "Claim: The answer is one more than the number of occurrences of the substring \"((\" in the balanced bracket sequence given (considering overlapping occurrences as well). Proof: Observe the behavior of the lowest index $k$ of any connected component. The properties that would hold true are: $s_k =$ '('. This is because for all edges connecting indices $i$ and $j$ such that $i < j$, $s_i =$ '(' and $s_j =$ ')'. $k = 1$ is the lowest index for its connected component. For $k > 1$, $k$ is a lowest index for a connected component if and only if $s_{k - 1} =$ '('. This is because: if $s_{k - 1} =$ ')', then for any matching bracket $s_{j_1}$ of $s_{k - 1}$ ($j_1 < k - 1$) and for any matching bracket $s_{j_2}$ of $s_{k}$ ($j_2 > k$), there must be edges $(j_1, j_2)$ and $(k, j_2)$. This means that $j_1$ (which is less than $k$) is in the connected component of $k$. [Contradiction] if $s_{k - 1} =$ '(', then we can prove that there cannot be a smaller index in the connected component of $k$. For the sake of contradiction, assume that there exists a smaller index $a$ in the same connected component. This means, there is an edge $(a, b)$, such that $a < k$ and $b > k$ is in the connected component of $k$. Let $p_i$ be the number of '(' minus the the number of ')' in the prefix $s[1 \\ldots i]$ (consider $p_0 = 0$ for the empty prefix). Observe that for all edges $(i, j)$, ($i < j$), it holds that $p_j = p_i - 1$ and for all $i'$, $i \\le i' \\le j$, we must have $p_{i'} \\ge p_j$. This means that for a connected component $\\mathcal C$, for all $i \\in \\mathcal C$, $s_i =$ '(', $p_i$ is constant. Hence $p_k = p_a$. Further we have $p_b = p_a - 1$ and $p_{k - 2} = p_{k - 1} - 1 = p_k - 2 = p_b - 1$. This implies $a < (k - 1)$, hence $a \\le (k - 2) \\le b$, however, $p_{k - 2} = p_b - 1 < p_b$. [Contradiction] if $s_{k - 1} =$ ')', then for any matching bracket $s_{j_1}$ of $s_{k - 1}$ ($j_1 < k - 1$) and for any matching bracket $s_{j_2}$ of $s_{k}$ ($j_2 > k$), there must be edges $(j_1, j_2)$ and $(k, j_2)$. This means that $j_1$ (which is less than $k$) is in the connected component of $k$. [Contradiction] if $s_{k - 1} =$ '(', then we can prove that there cannot be a smaller index in the connected component of $k$. For the sake of contradiction, assume that there exists a smaller index $a$ in the same connected component. This means, there is an edge $(a, b)$, such that $a < k$ and $b > k$ is in the connected component of $k$. Let $p_i$ be the number of '(' minus the the number of ')' in the prefix $s[1 \\ldots i]$ (consider $p_0 = 0$ for the empty prefix). Observe that for all edges $(i, j)$, ($i < j$), it holds that $p_j = p_i - 1$ and for all $i'$, $i \\le i' \\le j$, we must have $p_{i'} \\ge p_j$. This means that for a connected component $\\mathcal C$, for all $i \\in \\mathcal C$, $s_i =$ '(', $p_i$ is constant. Hence $p_k = p_a$. Further we have $p_b = p_a - 1$ and $p_{k - 2} = p_{k - 1} - 1 = p_k - 2 = p_b - 1$. This implies $a < (k - 1)$, hence $a \\le (k - 2) \\le b$, however, $p_{k - 2} = p_b - 1 < p_b$. [Contradiction] Therefore for each '(' preceded by another '(', we have one such connected component (so we add the occurrences of the substring \"((\" to our answer). However, we missed the connected component of node $1$ (so we add $1$ to our answer). [Proved] Hence we can solve it in $\\mathcal O(n)$.",
    "code": "t=int(input())\nfor _ in range(t):\n    n=int(input())\n    s=input()\n    print(1+s.count(\"(\")-s.count(\"()\"))",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1726",
    "index": "D",
    "title": "Edge Split",
    "statement": "You are given a connected, undirected and unweighted graph with $n$ vertices and $m$ edges. Notice \\textbf{the limit on the number of edges}: $m \\le n + 2$.\n\nLet's say we color some of the edges red and the remaining edges blue. Now consider only the red edges and count the number of connected components in the graph. Let this value be $c_1$. Similarly, consider only the blue edges and count the number of connected components in the graph. Let this value be $c_2$.\n\nFind an assignment of colors to the edges such that the quantity $c_1+c_2$ is \\textbf{minimised}.",
    "tutorial": "Let's say for convenience that the set of red edges is called $R$ and the set of blue edges is called $B$. Fact: In at least one optimal configuration, $R$ or $B$ forms a spanning tree. Proof: Let's say that $R$ is not a spanning tree in some optimal configuration. If we move an edge connecting two disconnected vertices in $R$ from $B$ to $R$ (this edge must exist since the input is a connected graph), $c_2$ will increase by at most $1$, and $c_1$ will decrease by $1$. Also, if we have a cycle in $R$, we can move this edge from $R$ to $B$ and $c_1$ won't change. But $c_2$ may decrease by $1$. So making $R$ a spanning tree never makes the answer worse. We can swap $R$ and $B$ in this proof, it doesn't matter. If $R$ is a spanning tree then $c_1=1$ and we want to minimise $c_2$. Clearly, it would be best if there was no cycle in $B$. It turns out that we can ensure this. Notice that $m \\leq (n-1)+3$, so the number of extra edges is very small. Let us build a spanning tree using DFS. A DFS tree will only have back edges and no cross edges. If there is no cycle taking these back edges in $B$, we are done. However, if there is a cycle (and there can be at most $1$ cycle, since you need at least $5$ edges for $2$ cycles), it looks like edges $u-v$ $v-w$ $u-w$ where $u$ is an ancestor of $v$ and $v$ is an ancestor of $w$. It is easy to get rid of this cycle by dropping one back edge ending at $w$ and taking the span edge connecting $w$ with its parent in the DFS tree. Note that $R$ remains a spanning tree. Hence we are done. Time complexity: $\\mathcal{O}(n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing lol=long long int;\n#define endl \"\\n\"\n\nvoid dfs(int u,const vector<vector<pair<int,int>>>& g,vector<bool>& vis,vector<int>& dep,vector<int>& par,string& s)\n{\n    vis[u]=true;\n    for(auto [v,idx]:g[u])\n    {\n        if(vis[v])  continue;\n        dep[v]=dep[u]+1;\n        par[v]=u;\n        s[idx]='1';\n        dfs(v,g,vis,dep,par,s);\n    }\n}\n\nint main()\n{\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\nint _=1;\ncin>>_;\nwhile(_--)\n{\n    int n,m;\n    cin>>n>>m;\n    vector<vector<pair<int,int>>> g(n+1);\n    vector<pair<int,int>> edges(m);\n    string s(m,'0');\n    for(int i=0;i<m;i++)\n    {\n        int u,v;\n        cin>>u>>v;\n        edges[i]={u,v};\n        g[u].push_back({v,i});\n        g[v].push_back({u,i});\n    }\n    vector<bool> vis(n+1,false);\n    vector<int> dep(n+1,0),par(n+1,-1);\n    dfs(1,g,vis,dep,par,s);\n    map<int,int> cnt;\n    for(int i=0;i<m;i++)\n    {\n        if(s[i]=='0')\n        {\n            cnt[edges[i].first]++;\n            cnt[edges[i].second]++;\n        }\n    }\n    if(cnt.size()==3)\n    {\n        int mn=2*n+5,mx=0;\n        for(auto [_,c]:cnt)\n        {\n            mn=min(mn,c);\n            mx=max(mx,c);\n        }\n        if(mn==mx && mn==2)\n        {\n            vector<pair<int,int>> can;\n            for(auto [v,_]:cnt) can.push_back({dep[v],v});\n            sort(can.rbegin(),can.rend());\n            int u=can[0].second;\n            int i,j;    //replace edge i with edge j\n            for(auto [v,idx]:g[u])\n            {\n                if(s[idx]=='0') i=idx;\n                else if(v==par[u])    j=idx;\n            }\n            s[i]='1';\n            s[j]='0';\n        }\n    }\n    cout<<s<<endl;\n}\nreturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "probabilities",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1726",
    "index": "F",
    "title": "Late For Work (submissions are not allowed)",
    "statement": "\\textbf{This problem was copied by the author from another online platform. Codeforces strongly condemns this action and therefore further submissions to this problem are not accepted.}\n\nDebajyoti has a very important meeting to attend and he is already very late. Harsh, his driver, needs to take Debajyoti to the destination for the meeting as fast as possible.\n\nHarsh needs to pick up Debajyoti from his home and take him to the destination so that Debajyoti can attend the meeting in time. A straight road with $n$ traffic lights connects the home and the destination for the interview. The traffic lights are numbered in order from $1$ to $n$.\n\nEach traffic light cycles after $t$ seconds. The $i$-th traffic light is $\\textcolor{green}{\\text{green}}$ (in which case Harsh can cross the traffic light) for the first $g_i$ seconds, and $\\textcolor{red}{\\text{red}}$ (in which case Harsh must wait for the light to turn $\\textcolor{green}{\\text{green}}$) for the remaining $(t−g_i)$ seconds, after which the pattern repeats. Each light's cycle repeats indefinitely and initially, the $i$-th light is $c_i$ seconds into its cycle (a light with $c_i=0$ has just turned $\\textcolor{green}{\\text{green}}$). In the case that Harsh arrives at a light at the same time it changes colour, he will obey the new colour. Formally, the $i$-th traffic light is $\\textcolor{green}{\\text{green}}$ from $[0,g_i)$ and $\\textcolor{red}{\\text{red}}$ from $[g_i,t)$ (after which it repeats the cycle). The $i$-th traffic light is initially at the $c_i$-th second of its cycle.\n\nFrom the $i$-th traffic light, \\textbf{exactly} $d_i$ seconds are required to travel to the next traffic light (that is to the $(i+1)$-th light). Debajyoti's home is located just before the first light and Debajyoti drops for the interview as soon as he passes the $n$-th light. In other words, no time is required to reach the first light from Debajyoti's home or to reach the interview centre from the $n$-th light.\n\nHarsh does not know how much longer it will take for Debajyoti to get ready. While waiting, he wonders what is the minimum possible amount of time he will spend driving provided he starts the moment Debajyoti arrives, which can be anywhere between $0$ to $\\infty$ seconds from now. Can you tell Harsh the minimum possible amount of time he needs to spend on the road?\n\n\\textbf{Please note that Harsh can only start or stop driving at integer moments of time.}",
    "tutorial": "The $d_i$ are irrelevant. Take partial sums and add them to each $c_i$ modulo $T$. If your start time is fixed, it is never beneficial to wait at a green light. Drive whenever you can. Visualise the problem as $n$ parallel lines, each coloured with a red and green interval. Now imagine the car moving up (and looping back at $T$) whenever it has to wait at a red light, and shooting to the right immediately when the lights are green. You can model this as a shortest paths problem. There are solutions to this problem using lazy segment trees, or say, sets and maps. I'll describe my own solution here, which converts the problem to a shortest paths problem. First of all, the $d_i$ are irrelevant, since we can take partial sums and add them to $c_i$. In the final answer, just add the sum of all $d_i$. Now, we can offset the green (or red) intervals by the modified $c_i$ to get new red and green intervals modulo $T$. Imagine $n$ parallel lines of length $T$, with the corresponding intervals coloured red and green. Now, consider the intervals to be static. In this picture, the car can be visualised to be moving upwards along the line (looping back at $T$) when on red intervals and shooting to the right when it reaches a green interval. Notice that for a fixed starting time, it is always optimal to drive whenever you can. So essentially, fixing your start time also fixes your answer. Now let's convert this to a graph. Notice that only the endpoints of green intervals matter, so overall, we'll have $2n$ nodes in our graph, plus a dummy node representing the start of the journey that connects to all endpoints that can be reached without being blocked by a red interval, and a dummy node representing the end of the journey that connects to all endpoints from which you can reach the end without being blocked by a red interval. So in total, $2n+2$ nodes. We'll add an edge between two nodes with a weight equal to the amount of time we'll have to spend waiting for the red light to turn green. We can achieve this with a multiset storing all currently visible endpoints, and then doing a little casework to add edges from nodes blocked by the current red interval and then deleting them, and adding new ones. We'll do this only $\\mathcal{O}(n)$ times. In the end, whatever is left in the multiset are all the visible endpoints and we can connect them to the dummy node for the end. We can repeat this in the backward direction to get the endpoints for the dummy node for the start, though in my code, I elected to do this with an interval union data structure. Finally, just run Dijkstra's algorithm on this graph. The answer is the sum of all $d_i$ plus the shortest path between the dummy node for the start and the dummy node for the end. Time complexity: $\\mathcal{O}(n \\log n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing lol=long long int;\nconst lol inf=1e18+8;\n \nstruct IntervalUnion{\n    set<int> lf,ri;\n    map<int,int> lr,rl;\n    void add(int l,int r)\n    {\n        if(!ri.empty())\n        {\n            auto it=ri.lower_bound(r);\n            if(it!=ri.end() && rl[*it]<=l)  return;\n        }\n        while(!lf.empty())\n        {\n            auto it=lf.lower_bound(l);\n            if(it==lf.end() || r<*it)    break;\n            int nl=*it;\n            r=max(r,lr[nl]);\n            rl.erase(lr[nl]);\n            ri.erase(lr[nl]);\n            lr.erase(nl);\n            lf.erase(nl);\n        }\n        while(!ri.empty())\n        {\n            auto it=ri.lower_bound(l);\n            if(it==ri.end() || r<rl[*it])   break;\n            int nl=rl[*it];\n            l=min(l,nl);\n            rl.erase(lr[nl]);\n            ri.erase(lr[nl]);\n            lr.erase(nl);\n            lf.erase(nl);\n        }\n        lf.insert(l);\n        ri.insert(r);\n        lr[l]=r;\n        rl[r]=l;\n    }\n    bool contains(int x)\n    {\n        auto it=ri.upper_bound(x);\n        if(it==ri.end())    return false;\n        return rl[*it]<=x;\n    }\n};\n \nint main()\n{\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\nint n,t;\ncin>>n>>t;\nvector<pair<int,int>> gc(n);\nfor(auto& [g,c]:gc) cin>>g>>c;\nlol sum=0;\nfor(int i=1;i<n;i++)\n{\n    int d;\n    cin>>d;\n    sum+=d;\n    gc[i].second=(gc[i].second+(sum%t))%t;\n}\nvector<vector<pair<int,int>>> gr(2*n+2);\nmultiset<pair<int,int>> ms;\nIntervalUnion iu;\nfor(int i=0;i<n;i++)\n{\n    auto [g,c]=gc[i];\n    int l=(g-c+t)%t,r=t-c;\n    if(l<r)\n    {\n        while(!ms.empty())\n        {\n            auto it=ms.lower_bound({l,-1});\n            if(it==ms.end() || it->first>=r)    break;\n            gr[2*i].push_back({it->second,r-it->first});\n            ms.erase(it);\n        }\n    }else\n    {\n        while(!ms.empty())\n        {\n            auto it=ms.lower_bound({l,-1});\n            if(it==ms.end() || it->first>=t)    break;\n            gr[2*i].push_back({it->second,r+t-it->first});\n            ms.erase(it);\n        }\n        while(!ms.empty())\n        {\n            auto it=ms.lower_bound({0,-1});\n            if(it==ms.end() || it->first>=r)    break;\n            gr[2*i].push_back({it->second,r-it->first});\n            ms.erase(it);\n        }\n    }\n    ms.insert({r%t,2*i});\n    ms.insert({(l-1+t)%t,2*i+1});\n    if(!iu.contains(r%t)) gr[2*i].push_back({2*n+1,0});\n    if(!iu.contains((l-1+t)%t)) gr[2*i+1].push_back({2*n+1,0});\n    if(l<r) iu.add(l,r);\n    else\n    {\n        iu.add(l,t);\n        iu.add(0,r);\n    }\n}\nwhile(!ms.empty())\n{\n    auto it=ms.begin();\n    gr[2*n].push_back({it->second,0});\n    ms.erase(it);\n}\n//do dijkstra on this graph\nvector<lol> sp(2*n+2,inf);\npriority_queue<pair<lol,int>,vector<pair<lol,int>>,greater<pair<lol,int>>> pq;\npq.push({0,2*n});\nsp[2*n]=0;\nwhile(!pq.empty())\n{\n    auto [dist,u]=pq.top();\n    pq.pop();\n    if(dist>sp[u])   continue;\n    for(auto [v,w]:gr[u])\n    {\n        if(dist+w<sp[v])\n        {\n            sp[v]=dist+w;\n            pq.push({sp[v],v});\n        }\n    }\n}\ncout<<sum+sp[2*n+1];\nreturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "schedules",
      "shortest paths"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1726",
    "index": "G",
    "title": "A Certain Magical Party",
    "statement": "There are $n$ people at a party. The $i$-th person has an amount of happiness $a_i$.\n\nEvery person has a certain kind of personality which can be represented as a binary integer $b$. If $b = 0$, it means the happiness of the person will increase if he tells the story to someone \\textbf{strictly less} happy than them. If $b = 1$, it means the happiness of the person will increase if he tells the story to someone \\textbf{strictly more} happy than them.\n\nLet us define a speaking order as an ordering of the people from left to right. Now the following process occurs. We go from left to right. The current person tells the story to all people other than himself. Note that \\textbf{all happiness values stay constant} while this happens. After the person is done, he counts the number of people who currently have strictly less/more happiness than him as per his kind of personality, and his happiness increases by that value. Note that only the current person's happiness value increases.\n\nAs the organizer of the party, you don't want anyone to leave sad. Therefore, you want to count the number of speaking orders such that at the end of the process \\textbf{all} $n$ people have \\textbf{equal} happiness.\n\nTwo speaking orders are considered different if there exists at least one person who does not have the same position in the two speaking orders.",
    "tutorial": "First of all, if there is only $1$ distinct value of happiness, any ordering is fine since no one has strictly greater or lesser happiness, and the answer is $n!$. From here on, we assume that there are at least $2$ distinct values of happiness. Note: The notation $<u,v>$ refers to elements with happiness $u$ and behaviour $v$. Observation 1: The happiness of a person can never decrease. It is obvious. Let's call the final happiness value all elements will be equal to as the target value $T$. Also, let the smallest happiness value of the array be $m$, and the largest be $M$. Note that $T \\geq M$, otherwise, it is impossible for a valid order to exist, from observation $1$. Observation 2: For all $x<T$, there can be at most one occurrence of $<x,1>$ in the array. Proof: Let's say there is more than one occurrence of $<x,1>$. Let's say at some point, we can place one occurrence of it in our order, and we place it. But then for the remaining occurrences, it immediately becomes impossible to place them anymore, because the number of strictly greater values increases by $1$, and can only increase from there. Hence, contradiction. ----- Observation 3: There is only one possible $T$, given by $m+n-1$. Proof: Let's say we have $<m,0>$. Then no matter what we do, its final happiness value will still be $m$, since there will never be a value strictly lesser than it. This means $T=m$. This however, breaks our assumption of $2$ distinct values. So only $<m,1>$ can exist. But if that exists, from observation $2$, exactly one such occurrence exists. The number of values strictly greater than $m$ will always be constant. So, no matter when we place it, the final happiness value is going to be $m+n-1$. ----- Observation 4: If it is possible to place multiple numbers in the order at a certain point ( i.e. if there are multiple possible $<u,v>$ place which will all yield $<T,v>$ ), it is always better to prefer the larger number, and to place a number with behaviour $1$ over one with behaviour $0$ in case of a tie. Proof: Let's say you pick something smaller than the larger number. Now this number becomes $T$, which is $\\geq M$. Now consider the larger number. If it had a $0$, now it is impossible to place it anymore, because the number of numbers strictly lesser has reduced by $1$, and it can only reduce. A similar argument follows for $1$. In the same group, you have to prefer $1$s over $0$s. Let's say you placed the $0$ first. Now the number of numbers strictly greater has increased by $1$, and can only increase. Therefore you can never place the $1$ now. Placing the $1$ first does not affect the viability of placing the $0$s. Important: If $T=M$, the $<M,1>$ group is special, since it doesn't matter when you place it since the final happiness value will still be $M$, and it won't affect any other group's viability either. But the observation still holds. In fact, except the $<M,1>$ group in the case of $T=M$, you have to follow this order. This means the order is unique upto considering equal elements as indistinguishable. This means, we can only choose the order of placing equal values. We cannot choose the occupied positions in the final order. Hence the count is going to be the product of the number of possible permutations for each group. $\\begin{aligned}P=\\prod_{\\text{all }<u,v>} {cnt_{<u,v>}!}\\end{aligned}$ ----- Observation 5: For a valid ordering (if exists), the $0$ behaving people would be sorted in non-decreasing order of initial happiness. Proof: We assume the contrary: Suppose for $x > y$, $<x, 0>$ speaks before $<y, 0>$ in some valid order. Since it is known that both finally become $<T, 0>$, it must be the case that there were $(T - x)$ people with a smaller happiness than $x$, when $x$ speaks and $(T - y)$ people with a smaller happiness than $y$, when $y$ speaks. As $x > y$, everyone having a happiness less than $y$ must also have a happiness less than $x$. Therefore when $y$ speaks at least $(T - y)$ people had a happiness smaller than $x$. Now $(T - x) < (T - y)$; which means the number of people having a value less than $x$ increased. But the happiness of each person can only increase, and hence the number of poeple with a happiness less than $x$ cannot increase; contradiction. ----- Observation 6: For a valid ordering (if exists) and at any intermediate step, for all $1$ behaving people $<u, 1>$ yet to speak, the number of people with a larger happiness than $u$ cannot exceed $(T - u)$. In other words, if we placed $<u, 1>$ at any intermediate step, its final happiness would not exceed $T$. Proof: The happiness of everyone can only increase. So if the number of people with happiness greater than $<u, 1>$ exceeds $(T - u)$ before $<u, 1>$ has spoken, the number of people with a happiness greater than $u$ would not decrease when $u$ subsequently speaks. This means the final happiness of this person would be greater than $T$, which cannot happen. ----- As mentioned before, in the case of the group $<M,1>$ if $T=M$, it doesn't matter where we place them in the order, but the order of the remaining elements is fixed. If there are $S$ occurrences of this group, then we have $n$ spots we can choose to place these values of the group in, and then the rest of the elements will follow the order in the remaining positions. The count $P$ is going to be multiplied by $\\binom{n}{S}$. However, it may be the case that no such ordering exists. We thus try to find an order using Observation 4 and speed it up using Observation 5 and Observation 6. We notice that we can have a brute force simulation of Observation 4 to find the order in $\\mathcal{O}(n^2)$ time. However, we can do the following: Place all occurrences of $<T, 1>$ at the beginning as their positions don't matter. Keep a sorted (non-decreasing) list of all the $0$ behaving people who are yet to speak. From Observation 5 the only candidate who can be placed from this list at a given step is the least happy candidate. Keep a sorted (increasing) list of all $1$ behaving people who are yet to speak where we keep track of the maximum of the final happiness reached if they were to speak now (i.e. their initial happiness + the number of people with a strictly greater happiness at present) among all people in this list. From Observation 6, we know that if this maximum exceeds $T$, there is no possible ordering and we output $0$. Hence from now we will assume that the maximum happiness reached if they were to talk now to be at most $T$. At each step, there are only two potential speakers that we need to check (since we are breaking ties using Observation 4): The least happy $0$ behaving person (if its happiness reached currently is $T$) and the maximum stored in the last step (if it is equal to $T$). If neither is valid, we report no answer. Otherwise, we break ties using Observation 4 and make that person speak. We change their happiness to $T$ and the final happiness values if they speak now, of all the $1$ behaving people that had a greater happiness (handled in step $3$) than the current person would increase by $1$. If we can complete the entire process, we have a valid ordering. This can be done quickly using two segment trees: One for keeping the happiness reached values of $1$ behaving people yet to speak and storing their maximum (so that steps $3$ and $5$ become max query and range updates); and another for keeping the count of people having a particular happiness value (to speed up finding the current happiness value if they speak now for the least happy $0$ behaving person in step $4$). Time complexity: $\\mathcal{O}(n\\log n)$",
    "code": "#include<bits/stdc++.h>\n\n#define ll long long\n#define pb push_back\n#define mp make_pair\n#define pii pair<int, int>\n#define pll pair<ll, ll>\n#define ff first \n#define ss second\n#define vi vector<int>\n#define vl vector<ll>\n#define vii vector<pii>\n#define vll vector<pll>\n#define FOR(i,N) for(i=0;i<(N);++i)\n#define FORe(i,N) for(i=1;i<=(N);++i)\n#define FORr(i,a,b) for(i=(a);i<(b);++i)\n#define FORrev(i,N) for(i=(N);i>=0;--i)\n#define F0R(i,N) for(int i=0;i<(N);++i)\n#define F0Re(i,N) for(int i=1;i<=(N);++i)\n#define F0Rr(i,a,b) for(ll i=(a);i<(b);++i)\n#define F0Rrev(i,N) for(int i=(N);i>=0;--i)\n#define all(v) (v).begin(),(v).end()\n#define dbgLine cerr<<\" LINE : \"<<__LINE__<<\"\\n\"\n#define ldd long double\n\nusing namespace std;\n\nconst int Alp = 26;\nconst int __PRECISION = 9;\nconst int inf = 1e9 + 8;\n\nconst ldd PI = acos(-1);\nconst ldd EPS = 1e-7;\n\nconst ll MOD = 998244353;\nconst ll MAXN = 260007;\nconst ll ROOTN = 320;\nconst ll LOGN = 18;\nconst ll INF = 1e18 + 1022;\n\nint N;\nint A[MAXN];\nbool B[MAXN];\nvi a[2];\npii people[MAXN];\nll fact[MAXN + 1], ifact[MAXN + 1];\n\n\nll fxp(ll a, ll n){\n\tif(n == 0) return 1;\n\tif(n % 2 == 1) return a * fxp(a, n - 1) % MOD;\n\treturn fxp(a * a % MOD, n / 2);\n}\n\nll inv(ll a){\n\treturn fxp(a % MOD, MOD - 2);\n}\nvoid init(){\n\tfact[0] = ifact[0] = 1;\n\tF0Re(i, MAXN){\n\t\tfact[i] = fact[i - 1] * i % MOD;\n\t\tifact[i] = inv(fact[i]);\n\t}\n}\n\nstruct SegTree_sum{\n\tint st[4*MAXN];\n\tvoid upd(int node, int ss, int se, int i, int val){\n\t\tif(ss > i or se < i)\treturn;\n\t\tif(ss == se)\t{st[node] += val; return;}\n\t\tint mid = (ss + se) / 2;\n\t\tupd(node*2+1, ss, mid, i, val);\n\t\tupd(node*2+2, mid+1, se, i, val);\n\t\tst[node] = st[node*2+1] + st[node*2+2];\n\t}\n\tint quer(int node,int ss, int se, int l, int r){\n\t\tif(ss > r or se < l)\treturn 0;\n\t\tif(ss >= l and se <= r)\treturn st[node];\n\t\tint mid = (ss + se)/2;\n\t\treturn quer(node*2+1, ss, mid, l ,r) + quer(node*2+2, mid + 1, se, l,r);\n\t}\n\tSegTree_sum()\t{F0R(i, MAXN*4) st[i] = 0;}\n\tinline void update(int i, int val) {upd(0, 0, 2 * MAXN, i, val);}\n\tinline int query(int l, int r) {return quer(0, 0, 2 * MAXN, l, r);}\n}S_sum;\n\nstruct Segtree_max{\n\tint st[4 * MAXN], lz[4 * MAXN];\n\tinline void push(int node, int ss, int se){\n\t\tif(lz[node] == 0) return;\n\t\tst[node] += lz[node];\n\t\tif(ss != se) lz[node * 2 + 1] += lz[node], lz[node * 2 + 2] += lz[node];\n\t\tlz[node] = 0;\n\t}\n\tvoid upd(int node, int ss, int se, int l, int r, int val){\n\t\tpush(node, ss, se);\n\t\tif(ss > r or se < l) return;\n\t\tif(ss >= l and se <= r) {lz[node] += val; push(node, ss, se); return;}\n\t\tint mid = (ss + se)/2;\n\t\tupd(node * 2 + 1, ss, mid, l, r, val);\n\t\tupd(node * 2 + 2, 1 + mid, se, l, r, val);\n\t\tst[node] = max(st[node * 2 + 1], st[node * 2 + 2]);\n\t}\n\tint quer(int node, int ss, int se, int tar){\n\t\tpush(node, ss, se);\n\t\tif(st[node] < tar || st[node] > tar){\n\t\t\treturn -1;\n\t\t}\n\t\tif(ss == se){\n\t\t\treturn ss;\n\t\t}\n\t\tint mid = (ss + se) / 2;\n\t\tpush(node * 2 + 1, ss, mid);\n\t\tpush(node * 2 + 2, mid + 1, se);\n\t\treturn (st[node * 2 + 2] < tar) ? quer(node * 2 + 1, ss, mid, tar) : quer(node * 2 + 2, mid + 1, se, tar);\n\t}\n\tSegtree_max() {F0R(i,MAXN * 4) st[i] = - 10 * MAXN, lz[i] = 0;}\n\tinline void update(int l, int r, ll val) {if(l <= r) upd(0, 0, 2 * MAXN, l, r, val);}\n\tinline ll query(int v) {return quer(0, 0, 2 * MAXN, v);}\n}S_max;\n\nsigned main(){\n\n\t\n\tios_base::sync_with_stdio(false);\n\tcin.tie(NULL);\n\tcout.tie(NULL);\n\t\n\tinit();\n\tcin >> N;\n\tF0R(i, N){\n\t\tcin >> A[i];\n\t}\n\tF0R(i, N){\n\t\tcin >> B[i];\n\t}\n\n\tF0R(i, N){\n\t\ta[B[i]].pb(A[i]);\n\t\tpeople[i] = {A[i], B[i]};\n\t\tS_sum.update(A[i], 1);\n\t}\n\n\tsort(all(a[0]));\n\tsort(all(a[1]));\n\tsort(people, people + N);\n\tint m = people[0].ff;\n\tint M = people[N - 1].ff;\n\tint T = people[0].ff + N - 1;\n\n\tif(m == M){\n\t\tcout << fact[N] << '\\n';\n\t\treturn 0;\n\t}else if(people[0].ss == 0){\n\t\tcout << \"0\\n\";\n\t\treturn 0;\n\t}else if(M > T){\n\t\tcout << \"0\\n\";\n\t\treturn 0;\n\t}\n\n\tint T_cnt = 0;\n\n\tF0R(i, (int)a[1].size()){\n\t\tif(a[1][i] == T){\n\t\t\t++T_cnt;\n\t\t}else if(i + 1 < (int)a[1].size() && a[1][i] == a[1][i + 1]){\n\t\t\tcout << \"0\\n\";\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tll ans = fact[N] * ifact[N - T_cnt] % MOD;\n\tint p = -1, t = 0;\n\tfor(int x : a[0]){\n\t\tif(p != x){\n\t\t\tans = ans * fact[t] % MOD;\n\t\t\tt = 0;\n\t\t}\n\t\t++t;\n\t\tp = x;\n\t}\n\tans = ans * fact[t] % MOD;\n\n\tint ptr = 0;\n\n\tfor(int x : a[1]){\n\t\tif(x == T){\n\t\t\tbreak;\n\t\t}\n\t\tint y = x + S_sum.query(x + 1, 2 * MAXN);\n\t\tS_max.update(x, x, y + 10 * MAXN);\n\t}\n\n\tvii sequence(T_cnt, mp(T, 1));\n\n\tF0R(i, N - T_cnt){\n\t\tint zero = T + 1, one = T + 1;\n\t\tif(ptr < (int)a[0].size() && S_sum.query(1, a[0][ptr] - 1) + a[0][ptr] == T){\n\t\t\tzero = a[0][ptr];\n\t\t}\n\t\tone = S_max.query(T);\n\t\tif(one == -1 && zero == T + 1){\n\t\t\tcout << \"0\\n\";\n\t\t\treturn 0;\n\t\t}\n\t\tif(zero == T + 1 || one >= zero){\n\t\t\tsequence.pb({one, 1});\n\t\t\tS_max.update(one, one, - 10 * N);\n\t\t\tS_max.update(one + 1, T - 1, 1);\n\t\t\tS_sum.update(one, -1);\n\t\t\tS_sum.update(T, 1);\n\t\t}else{\n\t\t\tsequence.pb({zero, 0});\n\t\t\tS_sum.update(zero, -1);\n\t\t\tS_sum.update(T, 1);\n\t\t\tS_max.update(zero, T - 1, 1);\n\t\t\t++ptr;\n\t\t}\n\t}\n\tcout << ans << '\\n';\n\t\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1726",
    "index": "H",
    "title": "Mainak and the Bleeding Polygon",
    "statement": "Mainak has a convex polygon $\\mathcal P$ with $n$ vertices labelled as $A_1, A_2, \\ldots, A_n$ in a counter-clockwise fashion. The coordinates of the $i$-th point $A_i$ are given by $(x_i, y_i)$, where $x_i$ and $y_i$ are both integers.\n\nFurther, it is known that the interior angle at $A_i$ is either a right angle or a proper obtuse angle. Formally it is known that:\n\n- $90 ^ \\circ \\le \\angle A_{i - 1}A_{i}A_{i + 1} < 180 ^ \\circ$, $\\forall i \\in \\{1, 2, \\ldots, n\\}$ where we conventionally consider $A_0 = A_n$ and $A_{n + 1} = A_1$.\n\nMainak's friend insisted that all points $Q$ such that there exists a chord of the polygon $\\mathcal P$ passing through $Q$ with length \\textbf{not exceeding} $1$, must be coloured $\\textcolor{red}{\\text{red}}$.\n\nMainak wants you to find the area of the coloured region formed by the $\\textcolor{red}{\\text{red}}$ points.\n\nFormally, determine the area of the region $\\mathcal S = \\{Q \\in \\mathcal{P}$ | $Q \\text{ is coloured } \\textcolor{red}{\\text{red}}\\}$.\n\nRecall that a chord of a polygon is a line segment between two points lying on the boundary (i.e. vertices or points on edges) of the polygon.",
    "tutorial": "Clearly, the unsafe area is bounded by the envelope of the curve you get if you slide a rod of length $1$ around the interior of the polygon and pressed against the edges at all times. Observation 1: The length of each side of the polygon is $\\geq 1$. This one is obvious. Further, it implies that (almost always) we only need to consider unsafe areas formed by adjacent pairs of edges (there is one exception to this which is a rectangle with a side of length $1$, in which case the whole rectangle is unsafe). The proof is left as an exercise to the reader (our proof required some casework and induction on the angle and number of edges). The unsafe area for the whole polygon is the union of the unsafe areas formed by each pair of adjacent edges. Two adjacent edges can be viewed as a pair of lines $y=0$ and $y=x \\cdot \\tan{( \\alpha )}$ where $\\alpha$ is the angle between the edges (which is $\\geq \\frac{\\pi}{2}$). As it turns out, the envelope of the unsafe area is given by the parametric equations $\\begin{aligned} x&=f(\\theta,\\alpha)=\\frac{\\sin\\left(\\theta-\\alpha\\right)}{\\sin \\alpha}+\\frac{\\cos\\left(\\theta-\\alpha\\right)\\sin\\left(\\theta\\right)\\cos\\left(\\theta\\right)}{\\sin \\alpha} \\\\ y&=g(\\theta,\\alpha)=\\frac{\\cos\\left(\\theta-\\alpha\\right)\\sin^{2}\\left(\\theta\\right)}{\\sin \\alpha} \\\\ \\alpha & < \\theta < \\pi \\end{aligned}$ A sketch of the area for $\\alpha=\\frac{2\\pi}{3}$: Also, the area is given by the formula $\\begin{aligned} \\frac{\\cot{(\\alpha)}+(\\pi-\\alpha) \\cdot (\\csc^2{(\\alpha)}+2)}{16} \\end{aligned}$ We can easily just add up these values for each pair of adjacent edges. However, we are overestimating the area. We need to subtract out the intersecting parts of the individual unsafe areas. Observation 2: At most $2$ individual unsafe areas cover any given point. If $2$ unsafe areas intersect, they are the areas made by $3$ successive edges. If say, $3$ unsafe areas covered a point, then one of them must be between non-adjacent edges, which is not possible by the implications of observation 1. Furthermore, if the intersection of the unsafe areas is non-empty, the length of the common edge must be $< 2$, otherwise it will definitely be empty (this fact should be intuitively obvious). However, since the polygon has vertices has integer coordinates, if the length of an edge is $< 2$, it must be $1$ (it is parallel to one axis) or $\\sqrt{2}$ (it is diagonal). Note that each possibility of edges with such lengths in an oriented fashion can occur at most once. Which gives us observation 3. Observation 3: The number of sides of length $< 2$ is $\\leq 8$. What this basically means is that we will have to compute the area of the intersection of two unsafe areas only $\\mathcal{O}(1)$ times. Coming back to the curve, its area can be given by the integral $\\begin{aligned} \\int{y(\\theta) \\cdot \\frac{\\mathrm{d} x(\\theta)}{\\mathrm{d}\\theta}\\text{ }\\mathrm{d}\\theta}=\\frac{1}{\\sin^2{\\alpha}}\\int{[2\\cos^2{(\\theta-\\alpha)}\\cos^2{\\theta}\\sin^2{\\theta}-\\sin{(\\theta-\\alpha)}\\cos{(\\theta-\\alpha)}\\sin^3{\\theta}\\cos{\\theta}]\\text{ }\\mathrm{d}\\theta} \\end{aligned}$ This indefinite integral evaluates to $\\begin{aligned} \\frac{1}{64\\sin^2{\\alpha}}(\\sin{(2 (\\alpha - 3 \\theta))} - \\sin{(2 (\\alpha - 2 \\theta))} - 4 \\sin{(2 (\\alpha - \\theta))} - \\sin{(2 (\\alpha + \\theta))} - 4 \\theta \\cos{(2 \\alpha)} + 8 \\theta - 2 \\sin{(4 \\theta)}) + C \\end{aligned}$ Now, all we need to do is find the bounds of integration by finding the point at which the curves cross. Now, for an edge of length $L$, where $L$ is either $1$ or $\\sqrt 2$, we need to find the area of overlap and subtract it from our overestimated value. if we place the edge on the $x$-axis starting from origin, then the adjacent edges which were at an angle $\\alpha_1$ and $\\alpha_2$, now are straight lines, one at an angle $\\alpha_1$ passing from the origin, whereas other is another straight line at an angle $\\pi - \\alpha_2$ passing through $(L, 0)$. Clearly, the parametric equations of the two envelopes would be $(f(\\theta, \\alpha_1), g(\\theta, \\alpha_1))$ for $\\alpha_1 \\le \\theta \\le \\pi$ and $(L - f(\\phi, \\alpha2), g(\\phi, \\alpha_2))$ for $\\alpha_2 \\le \\phi \\le \\pi$. Observation 4: $g(\\theta, \\alpha)$, for a fixed $\\alpha \\in [\\frac \\pi 2, \\pi)$, is a decreasing function of $\\theta$, $\\alpha \\le \\theta \\le \\pi$. This fact can be easily verified from the equation of $g(\\alpha, \\theta)$ as $\\cos(x)$ is decreasing in the range of $(\\theta - \\alpha)$ i.e. $[0, \\pi - \\alpha] \\subset [0, \\frac \\pi 2]$, and $\\sin^2(x)$ is decreasing in the range of $\\theta$, i.e. $[\\alpha, \\pi] \\subset [\\frac \\pi 2, \\pi]$. This means for a given value, $y = \\lambda$, we can binary search in $\\mathcal O(\\log(\\frac 1 \\varepsilon))$, the value of $\\theta$, such that $g(\\alpha, \\theta) = \\lambda$. Once we get $\\theta$, we can further get the $x$-coordinate just by plugging $\\theta$ in $f(\\theta, \\alpha)$. Consequently, for both the parametric equations, we can evaluate $x$ as a function of $y$, in $\\mathcal O(\\log(\\frac 1 \\varepsilon))$ time. Observation 5: If the coordinates of the intersection of $(f(\\theta, \\alpha_1), g(\\theta, \\alpha_1))$ for $\\alpha_1 \\le \\theta \\le \\pi$ and $(L - f(\\phi, \\alpha2), g(\\phi, \\alpha_2))$ for $\\alpha_2 \\le \\phi \\le \\pi$ is $(h, k)$, then we can can binary search on $k$ in $\\mathcal O(\\log(\\frac 1 \\varepsilon))$ function evaluations of $x$ as a function of $y$. Observe that $0 < k < \\sin(\\max(\\alpha_1, \\alpha_2))$. Now, for a given guess $\\lambda$ of the $y$-coordinate of the intersection point, let's say the first parametric function provides an $x$-coordinate of $x_1$ and the second parametric curve gives $x_2$. In other words, $(x_1, \\lambda)$ and $(x_2, \\lambda)$ are points on the first and the second curves respectively. Now, if $\\lambda > k$, then we must have $x_1 < x_2$, whereas if $\\lambda < k$, we have $x_1 > x_2$; and thus we can find the value of $k$ in $\\mathcal O(log(\\frac 1 \\varepsilon))$ evaluations of $x_1$ and $x_2$ using a binary search. Therefore we can find the intersection point (and therefore the corresponding $\\theta$ and $\\phi$ values) in $\\mathcal O(\\log^2(\\frac 1 \\varepsilon))$ time. Once we have the $\\theta$ and the $\\phi$ values, we get the bounds of the indefinite integral after which we just plug in the values $\\theta$ and $\\phi$ to the indefinite integral to get the overlap area. Since we are doing this only for edges of length $< 2$, by observation 3, the final time complexity is $\\mathcal{O}(n+\\log^2{\\varepsilon^{-1}})$. However, a solution doing this for every edge would run in $\\mathcal{O}(n\\log^2{\\varepsilon^{-1}})$ time. For the given constraints, this optimization was not necessary to pass.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing lol=long long int;\nusing ldd=long double;\n#define endl \"\\n\"\nconst ldd PI=acos(-1.0);\nconst int ITERATIONS = 60;\nconst int PRECISION = 11;\n\nstruct Point{\n    lol x,y;\n    Point& operator-=(const Point& rhs){\n        x-=rhs.x,y-=rhs.y;\n        return *this;\n    }\n    friend Point operator-(Point lhs,const Point& rhs){\n        lhs -= rhs;\n        return lhs;\n    }\n};\nstd::istream& operator>>(std::istream& is, Point& obj){\n    is>>obj.x>>obj.y;\n    return is;\n}\n\nldd norm(Point p){\n    return p.x*p.x+p.y*p.y;\n}\nldd cross_product(Point a,Point b){\n    return a.x*b.y-a.y*b.x;\n}\nldd dot_product(Point a,Point b){\n    return a.x*b.x+a.y*b.y;\n}\nldd getalpha(Point a,Point b,Point c){\n    return atan2l(cross_product(c-b,a-b),dot_product(c-b,a-b));\n}\nldd getarea(Point a,Point b,Point c){\n    Point l1=c-b,l2=a-b;\n    return (dot_product(l1,l2)/cross_product(l1,l2)+atan2l(cross_product(l1,l2),-dot_product(l1,l2))*((norm(l1)*norm(l2))/(cross_product(l1,l2)*cross_product(l1,l2))+2.0))/16.0;\n}\n\nldd f(ldd theta, ldd alpha){\n\treturn -cos(theta)+(1.0/tan(alpha))*sin(theta) + (cos(theta)*(1.0/tan(alpha))+sin(theta)) * (sin(2*theta)/2.0);\n}\nldd g(ldd theta, ldd alpha){\n\treturn (cos(theta)*(1.0/tan(alpha))+sin(theta)) * (1.0 - cos(2*theta))/2.0;\n}\nldd get_x(ldd y, ldd alpha, ldd & theta){\n\tldd lo = alpha, hi = PI;\n\tfor(int it = 0; it < ITERATIONS; ++it){\n\t\ttheta = (lo + hi) / 2.0;\n\t\tldd y_guess = g(theta, alpha);\n\t\tif(y > y_guess){\n\t\t\thi = theta;\n\t\t}else{\n\t\t\tlo = theta;\n\t\t}\n\t}\n\n\treturn f(theta, alpha);\n}\nldd A(ldd theta, ldd alpha){\n\treturn (sin(2 * (alpha - 3 * theta)) - sin(2 * (alpha - 2 * theta)) - 4 * sin(2 * (alpha - theta)) - sin(2 * (alpha + theta))\n\t\t\t- 4 * theta * cos(2 * alpha) + 8 * theta - 2 * sin(4 * theta)) / (64.0 * sin(alpha) * sin(alpha));\n}\nldd find_overlap_area(ldd alpha_1, ldd alpha_2, ldd L){\n\n\tldd lo = 0, hi = sin(max(alpha_1, alpha_2));\n\tldd theta_1 = PI, theta_2 = PI;\n\n\tfor(int it = 0; it < ITERATIONS; ++it){\n\t\tldd mid_y = (lo + hi) / 2;\n\t\tldd x1 = get_x(mid_y, alpha_1, theta_1);\n\t\tldd x2 = L - get_x(mid_y, alpha_2, theta_2);\n\t\tif(x1 < x2){\n\t\t\thi = mid_y;\n\t\t}else{\n\t\t\tlo = mid_y;\n\t\t}\n\n\t}\n\n\treturn (A(PI, alpha_1) + A(PI, alpha_2)) - (A(theta_1, alpha_1) + A(theta_2, alpha_2));\n}\n\nint main()\n{\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\nint n;\ncin>>n;\nvector<Point> v(n);\nfor(auto& p:v)  cin>>p;\nif(n == 4){\n    int MY = max({v[0].y, v[1].y, v[2].y, v[3].y});\n    int my = min({v[0].y, v[1].y, v[2].y, v[3].y});\n    int MX = max({v[0].x, v[1].x, v[2].x, v[3].x});\n    int mx = min({v[0].x, v[1].x, v[2].x, v[3].x});\n    if(MY - my == 1 || MX - mx == 1){\n        cout << fixed << setprecision(PRECISION) << 1.0 * (MY - my) * (MX - mx) << endl;\n        exit(0);\n    }\n}\ndouble ans=0.0;\nfor(int i=0;i<n;i++){\n    ans+=getarea(v[(i-1+n)%n],v[i],v[(i+1)%n]);\n}\nfor(int i=0;i<n;i++){\n    Point a=v[(i-1+n)%n],b=v[i],c=v[(i+1)%n],d=v[(i+2)%n];\n    if(norm(c-b)<3){\n        ans-=find_overlap_area(getalpha(a,b,c),getalpha(b,c,d),sqrt(norm(c-b)));\n    }\n}\ncout<<fixed<<setprecision(PRECISION)<<ans;\nreturn 0;\n}",
    "tags": [
      "binary search",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1728",
    "index": "A",
    "title": "Colored Balls: Revisited",
    "statement": "The title is a reference to the very first Educational Round from our writers team, Educational Round 18.\n\nThere is a bag, containing colored balls. There are $n$ different colors of balls, numbered from $1$ to $n$. There are $\\mathit{cnt}_i$ balls of color $i$ in the bag. The total amount of balls in the bag is odd (e. g. $\\mathit{cnt}_1 + \\mathit{cnt}_2 + \\dots + \\mathit{cnt}_n$ is odd).\n\nIn one move, you can choose two balls \\textbf{with different colors} and take them out of the bag.\n\nAt some point, all the remaining balls in the bag will have the same color. That's when you can't make moves anymore.\n\nFind any possible color of the remaining balls.",
    "tutorial": "Let's prove that the color with the maximum value of $cnt$ is one of the possible answers. Let the color $x$ have the maximum value of $cnt$; if there are several such colors, choose any of them. Let's keep taking the balls of two different colors out of the bag without touching the balls of color $x$ for as long as possible. After such operations, two cases exist. In one case, only balls of color $x$ are left - then everything is fine. In other case, there are balls of color $x$ and some color $y$ (let $cnt_y$ be the remaining number of balls of this color). Since initially $cnt_x$ was one of the maximums, $cnt_y \\le cnt_x$. However, the number of remaining balls is odd, which means $cnt_y \\ne cnt_x$ and $cnt_y < cnt_x$. Therefore, we can keep taking the balls of colors $y$ and $x$ until only balls of color $x$ are left.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n    cout << max_element(a.begin(), a.end()) - a.begin() + 1 << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1728",
    "index": "B",
    "title": "Best Permutation",
    "statement": "Let's define the value of the permutation $p$ of $n$ integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once) as follows:\n\n- initially, an integer variable $x$ is equal to $0$;\n- if $x < p_1$, then add $p_1$ to $x$ (set $x = x + p_1$), otherwise assign $0$ to $x$;\n- if $x < p_2$, then add $p_2$ to $x$ (set $x = x + p_2$), otherwise assign $0$ to $x$;\n- ...\n- if $x < p_n$, then add $p_n$ to $x$ (set $x = x + p_n$), otherwise assign $0$ to $x$;\n- the value of the permutation is $x$ at the end of this process.\n\nFor example, for $p = [4, 5, 1, 2, 3, 6]$, the value of $x$ changes as follows: $0, 4, 9, 0, 2, 5, 11$, so the value of the permutation is $11$.\n\nYou are given an integer $n$. Find a permutation $p$ of size $n$ with the maximum possible value among all permutations of size $n$. If there are several such permutations, you can print any of them.",
    "tutorial": "Let $x_i$ be the value of the variable $x$ after $i$ steps. Note that $x_{n-1}$ should be less than $p_n$ for $x_n$ to be not equal to $0$. It means that $x_n$ does not exceed $2p_n - 1$. It turns out that for $n \\ge 4$ there is always a permutation such that $x_n$ is equal to $2n - 1$. The only thing left is to find out how to build such a permutation. There are many suitable permutations, let's consider one of the possible options. For an even $n$, a suitable permutation is $[2, 1, 4, 3, \\ dots, n - 2, n - 3, n - 1, n]$. You can see that $x$ in such a permutation changes as follows: $[0, 2, 0, 4, 0, \\dots, n - 2, 0, n - 1, 2n - 1]$. For an odd $n$, there is a similar permutation $[1, 3, 2, 5, 4, \\dots, n - 2, n - 3, n - 1, n]$, where $x$ changes as follows: $[0, 1, 4, 0, 5, 0, \\dots, n-2, 0, n - 1, 2n - 1]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> p(n);\n    iota(p.begin(), p.end(), 1);\n    for (int i = n & 1; i < n - 2; i += 2) swap(p[i], p[i + 1]);\n    for (int &x : p) cout << x << ' ';\n    cout << '\\n';\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1728",
    "index": "C",
    "title": "Digital Logarithm",
    "statement": "Let's define $f(x)$ for a positive integer $x$ as the length of the base-10 representation of $x$ without leading zeros. I like to call it a digital logarithm. Similar to a digital root, if you are familiar with that.\n\nYou are given two arrays $a$ and $b$, each containing $n$ positive integers. In one operation, you do the following:\n\n- pick some integer $i$ from $1$ to $n$;\n- assign either $f(a_i)$ to $a_i$ or $f(b_i)$ to $b_i$.\n\nTwo arrays are considered similar to each other if you can rearrange the elements in both of them, so that they are equal (e. g. $a_i = b_i$ for all $i$ from $1$ to $n$).\n\nWhat's the smallest number of operations required to make $a$ and $b$ similar to each other?",
    "tutorial": "First, why can you always make the arrays similar? Applying a digital logarithm to any number will eventually make it equal to $1$. Thus, you can at least make all numbers into $1$s in both arrays. Then notice the most improtant thing - applying the digital logarithm to a number greater than $1$ always makes this number smaller. Thus, if a number appears in only one of the arrays, you will have to do one of the followings two things: decrease some greater number to make it equal to this one; decrease this number. What if there is no greater number at all? This is the case for the largest number in both arrays altogether. If it appears in only one of the arrays, you must always decrease. If it appears in both, though, why decrease it further? Worst case, you will decrease it in one array, then you'll have to decrease it in the other array as well. This is never more optimal than just matching one occurrence in both arrays to each other and removing them from the arrays. So, the proposed solution is the following. Consider the largest element in each array. If they are equal, remove both. If not, apply digital logarithm to the larger of them. Continue until the arrays are empty. What's the estimated complexity of this algorithm? Each number in the first array will be considered at most the number of times you can decrease it with a digital logarithm operation plus one. That is at most $2+1$ - a number greater than $9$ always becomes a single digit and a single digit always becomes $1$. Same goes for the second array. So the complexity is basically linear. To implement it efficiently, you will have to use some data structure that provides three operations: peek at the maximum; remove the maximum; insert a new element. The perfect one is a heap - priority_queue in C++. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\tforn(_, t){\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tvector<int> a(n), b(n);\n\t\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\tforn(i, n) scanf(\"%d\", &b[i]);\n\t\tpriority_queue<int> qa(a.begin(), a.end());\n\t\tpriority_queue<int> qb(b.begin(), b.end());\n\t\tint ans = 0;\n\t\twhile (!qa.empty()){\n\t\t\tif (qa.top() == qb.top()){\n\t\t\t\tqa.pop();\n\t\t\t\tqb.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t++ans;\n\t\t\tif (qa.top() > qb.top()){\n\t\t\t\tqa.push(to_string(qa.top()).size());\n\t\t\t\tqa.pop();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tqb.push(to_string(qb.top()).size());\n\t\t\t\tqb.pop();\n\t\t\t}\n\t\t}\n\t\tprintf(\"%d\\n\", ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1728",
    "index": "D",
    "title": "Letter Picking",
    "statement": "Alice and Bob are playing a game. Initially, they are given a non-empty string $s$, consisting of lowercase Latin letters. The length of the string is even. Each player also has a string of their own, initially empty.\n\nAlice starts, then they alternate moves. In one move, a player takes either the first or the last letter of the string $s$, removes it from $s$ and \\textbf{prepends} (adds to the beginning) it to their own string.\n\nThe game ends when the string $s$ becomes empty. The winner is the player with a lexicographically smaller string. If the players' strings are equal, then it's a draw.\n\nA string $a$ is lexicographically smaller than a string $b$ if there exists such position $i$ that $a_j = b_j$ for all $j < i$ and $a_i < b_i$.\n\nWhat is the result of the game if both players play optimally (e. g. both players try to win; if they can't, then try to draw)?",
    "tutorial": "What do we do, when the array loses elements only from the left or from the right and the constraints obviously imply some quadratic solution? Well, apply dynamic programming, of course. The classic $dp[l][r]$ - what is the outcome if only the letters from positions $l$ to $r$ (non-inclusive) are left. $dp[0][n]$ is the answer. $dp[i][i]$ is the base case - the draw (both strings are empty). Let $-1$ mean that Alice wins, $0$ be a draw and $1$ mean that Bob wins. How to recalculate it? Let's consider a move of both players at the same time. From some state $[l; r)$, first, Alice goes, then Bob. The new state becomes $[l', r')$, Alice picked some letter $c$, Bob picked some letter $d$. What's that pick exactly? So, they both got a letter, prepended it to their own string. Then continued the game on a smaller string $s$ and prepended even more letters to the string. Thus, if we want to calculate $[l, r)$ from $[l', r')$, we say that we append letters $c$ and $d$. Now it's easy. If $dp[l'][r']$ is not a draw, then the new letters change nothing - the result is still the same. Otherwise, the result of the game is the same as the comparison of letters $c$ and $d$. How to perform both moves at once? First, we iterate over the Alice's move: whether she picks from $l$ or from $r$. After that we iterate over the Bob's move: whether he picks from $l$ or from $r$. Since we want $dp[l][r]$ to be the best outcome for Alice, we do the following. For any Alice move, we choose the worse of the Bob moves - the maximum of $dp[l'][r']$. Among the Alice's moves we choose the better one - the minimum one. Overall complexity: $O(n^2)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint comp(char c, char d){\n\treturn c < d ? -1 : (c > d ? 1 : 0);\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\tforn(_, t){\n\t\tstring s;\n\t\tcin >> s;\n\t\tint n = s.size();\n\t\tvector<vector<int>> dp(n + 1, vector<int>(n + 1));\n\t\tfor (int len = 2; len <= n; len += 2) forn(l, n - len + 1){\n\t\t\tint r = l + len;\n\t\t\tdp[l][r] = 1;\n\t\t\t{\n\t\t\t\tint res = -1;\n\t\t\t\tif (dp[l + 1][r - 1] != 0)\n\t\t\t\t\tres = max(res, dp[l + 1][r - 1]);\n\t\t\t\telse\n\t\t\t\t\tres = max(res, comp(s[l], s[r - 1]));\n\t\t\t\tif (dp[l + 2][r] != 0)\n\t\t\t\t\tres = max(res, dp[l + 2][r]);\n\t\t\t\telse\n\t\t\t\t\tres = max(res, comp(s[l], s[l + 1]));\n\t\t\t\tdp[l][r] = min(dp[l][r], res);\n\t\t\t}\n\t\t\t{\n\t\t\t\tint res = -1;\n\t\t\t\tif (dp[l + 1][r - 1] != 0)\n\t\t\t\t\tres = max(res, dp[l + 1][r - 1]);\n\t\t\t\telse\n\t\t\t\t\tres = max(res, comp(s[r - 1], s[l]));\n\t\t\t\tif (dp[l][r - 2] != 0)\n\t\t\t\t\tres = max(res, dp[l][r - 2]);\n\t\t\t\telse\n\t\t\t\t\tres = max(res, comp(s[r - 1], s[r - 2]));\n\t\t\t\tdp[l][r] = min(dp[l][r], res);\n\t\t\t}\n\t\t}\n\t\tif (dp[0][n] == -1)\n\t\t\tcout << \"Alice\\n\";\n\t\telse if (dp[0][n] == 0)\n\t\t\tcout << \"Draw\\n\";\n\t\telse\n\t\t\tcout << \"Bob\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "games",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1728",
    "index": "E",
    "title": "Red-Black Pepper",
    "statement": "Monocarp is going to host a party for his friends. He prepared $n$ dishes and is about to serve them. First, he has to add some powdered pepper to each of them — otherwise, the dishes will be pretty tasteless.\n\nThe $i$-th dish has two values $a_i$ and $b_i$ — its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.\n\nBefore adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $m$ shops in his local area. The $j$-th of them has packages of red pepper sufficient for $x_j$ servings and packages of black pepper sufficient for $y_j$ servings.\n\nMonocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that \\textbf{each dish will get the pepper added once, and no pepper is left}. More formally, if he purchases $x$ red pepper packages and $y$ black pepper packages, then $x$ and $y$ should be non-negative and $x \\cdot x_j + y \\cdot y_j$ should be equal to $n$.\n\nFor each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.",
    "tutorial": "Let's start by learning how to answer a query $(1, 1)$ - all red pepper and black pepper options are available. Let's iterate over all options to put the peppers and choose the maximum of them. First, let's use the red pepper for all dishes. Now we want to select some $k$ of them to use black pepper instead of red pepper. Which ones do we choose? When we switch from the red pepper to the black pepper, the total tastiness changes by $-a_i + b_i$ for the $i$-th dish. They are completely independent of each other, so we want to choose $k$ largest of these values. Let $d_1, d_2, \\dots, d_n$ be the sequence of values of $-a_i + b_i$ in a non-increasing order. Thus, $k$ black peppers will yield the result of $\\sum \\limits_{i=1}^{n} a_i + \\sum \\limits_{i=1}^{k} d_i$. We can answer a query $(1, 1)$ by looking for a maximum in the sequence. Now consider an arbitrary query. Let $p_1, p_2, \\dots, p_t$ be all options for the amount of available black peppers for the query. Naively, we could iterate over all of them and choose the maximum one. However, notice an interesting thing about the sequence of the answers. By definition, it is non-strictly convex. In particular, one idea that can be extracted from this is the following. Find the position of an arbitrary maximum in this sequence. Then everything to the left of is is non-increasing. Everything to the right of it is non-increasing. Thus, for a query, it's enough to consider only two options: the one closest to the maximum from the left and from the right. Now we only have to learn how to get these options fast enough. For a query $(x, y)$ we want to solve what's called a diophantine equation $ax + by = n$. An arbitrary solution can be obtained by using extended Euclid algorithm. Let it be some $(a, b)$. Then we would want to check the answer for $ax$ black peppers. The amount of solutions to the equation is either infinite or zero. If it's infinite, all solutions will be of the form $ax + k \\cdot \\mathit{lcm}(x, y)$ for any integer $k$. Remember that not all the solutions will be in a range $[0, n]$. Finally, find the two solutions that are the closest to the maximum, check that they are in the range $[0, n]$ and print the best answer of them. Overall complexity: $O(n \\log n + q \\log X)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nlong long gcd(long long a, long long b, long long& x, long long& y) {\n\tif (b == 0) {\n\t\tx = 1;\n\t\ty = 0;\n\t\treturn a;\n\t}\n\tlong long x1, y1;\n\tlong long d = gcd(b, a % b, x1, y1);\n\tx = y1;\n\ty = x1 - y1 * (a / b);\n\treturn d;\n}\n\nbool find_any_solution(long long a, long long b, long long c, long long &x0, long long &y0, long long &g) {\n\tg = gcd(abs(a), abs(b), x0, y0);\n\tif (c % g) {\n\t\treturn false;\n\t}\n\tx0 *= c / g;\n\ty0 *= c / g;\n\tif (a < 0) x0 = -x0;\n\tif (b < 0) y0 = -y0;\n\treturn true;\n}\n\nint main() {\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n), b(n);\n\tforn(i, n) scanf(\"%d%d\", &a[i], &b[i]);\n\tlong long cur = accumulate(b.begin(), b.end(), 0ll);\n\tvector<int> difs(n);\n\tforn(i, n) difs[i] = a[i] - b[i];\n\tsort(difs.begin(), difs.end(), greater<int>());\n\tvector<long long> bst(n + 1);\n\tforn(i, n + 1){\n\t\tbst[i] = cur;\n\t\tif (i < n)\n\t\t\tcur += difs[i];\n\t}\n\tint mx = max_element(bst.begin(), bst.end()) - bst.begin();\n\tint m;\n\tscanf(\"%d\", &m);\n\tforn(_, m){\n\t\tint x, y;\n\t\tscanf(\"%d%d\", &x, &y);\n\t\tlong long x0, y0, g;\n\t\tif (!find_any_solution(x, y, n, x0, y0, g)){\n\t\t\tputs(\"-1\");\n\t\t\tcontinue;\n\t\t}\n\t\tlong long l = x * 1ll * y / g;\n\t\tlong long red = x0 * 1ll * x;\n\t\tred = red + (max(0ll, mx - red) + l - 1) / l * l;\n\t\tred = red - max(0ll, red - mx) / l * l;\n\t\tlong long ans = -1;\n\t\tif (red <= n) ans = max(ans, bst[red]);\n\t\tred -= l;\n\t\tif (red >= 0) ans = max(ans, bst[red]);\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1728",
    "index": "F",
    "title": "Fishermen",
    "statement": "There are $n$ fishermen who have just returned from a fishing trip. The $i$-th fisherman has caught a fish of size $a_i$.\n\nThe fishermen will choose some order in which they are going to tell the size of the fish they caught (the order is just a permutation of size $n$). However, they are not entirely honest, and they may \"increase\" the size of the fish they have caught.\n\nFormally, suppose the chosen order of the fishermen is $[p_1, p_2, p_3, \\dots, p_n]$. Let $b_i$ be the value which the $i$-th fisherman in the order will tell to the other fishermen. The values $b_i$ are chosen as follows:\n\n- the first fisherman in the order just honestly tells the actual size of the fish he has caught, so $b_1 = a_{p_1}$;\n- every other fisherman wants to tell a value that is \\textbf{strictly greater} than the value told by the previous fisherman, and is divisible by the size of the fish that the fisherman has caught. So, for $i > 1$, $b_i$ is the smallest integer that is both \\textbf{strictly greater} than $b_{i-1}$ and \\textbf{divisible by} $a_{p_i}$.\n\nFor example, let $n = 7$, $a = [1, 8, 2, 3, 2, 2, 3]$. If the chosen order is $p = [1, 6, 7, 5, 3, 2, 4]$, then:\n\n- $b_1 = a_{p_1} = 1$;\n- $b_2$ is the smallest integer divisible by $2$ and greater than $1$, which is $2$;\n- $b_3$ is the smallest integer divisible by $3$ and greater than $2$, which is $3$;\n- $b_4$ is the smallest integer divisible by $2$ and greater than $3$, which is $4$;\n- $b_5$ is the smallest integer divisible by $2$ and greater than $4$, which is $6$;\n- $b_6$ is the smallest integer divisible by $8$ and greater than $6$, which is $8$;\n- $b_7$ is the smallest integer divisible by $3$ and greater than $8$, which is $9$.\n\nYou have to choose the order of fishermen in a way that yields the minimum possible $\\sum\\limits_{i=1}^{n} b_i$.",
    "tutorial": "Suppose we have fixed some order of fishermen and calculated the values of $b_i$. Then, we have the following constraints on $b_i$: all values of $b_i$ are pairwise distinct; for every $i$, $a_i$ divides $b_i$. Not every possible array $b$ meeting these constraints can be achieved with some order of fishermen, but we can show that if we choose an array $b$ with the minimum possible sum among the arrays meeting these two constraints, there exists an ordering of fishermen which yields this array $b$. The proof is simple - suppose the ordering of fishermen is the following one: the first fisherman is the one with minimum $b_i$, the second one - the one with the second minimum $b_i$, and so on. It's obvious that if we generate the values of $b$ according to this order, they won't be greater than the values in the array we have chosen. And if some value is less than the value in the chosen array $b$, it means that we haven't chosen the array with the minimum possible sum. So, we can rephrase the problem as the following one: for each $a_i$, choose the value of $b_i$ so that it is divisible by $a_i$, all $b_i$ are distinct, and their sum is minimized. Using the pigeonhole principle, we can show that for every $a_i$, we need to consider only the values of $b_i$ among $[a_i, 2 \\cdot a_i, 3 \\cdot a_i, \\dots, n \\cdot a_i]$. So, we can formulate the problem as an instance of the weighted bipartite matching: build a graph with two parts, where the left part contains $n$ nodes representing the values of $a_i$, the right part represents the values of the form $k \\cdot a_i$ where $1 \\le k \\le n$, and there exists an edge between a vertex in the left part representing the number $x$ and a vertex in the right part representing the number $y$ with cost $y$ if and only if $y = k \\cdot x$ for some integer $k \\in [1, n]$. Note that we don't add the edge if $k > n$ because we need to ensure that the size of the graph is $O(n^2)$. Okay, now we need to solve this weighted matching problem, but how? The number of vertices is $O(n^2)$, and the number of edges is $O(n^2)$ as well, so mincost flow will run in $O(n^4)$ or $O(n^3 \\log n)$, which is too much. Instead, we can notice that the cost of the edges incident to the same vertex in the right part is the same, so we can swap the parts of the graph, sort the vertices of the new left part (representing the numbers $k \\cdot a_i$) according to their costs, and run the classical Kuhn's algorithm in sorted order. Kuhn's algorithm in its original implementation will always match a vertex if it is possible, so it obtains the minimum total cost for the matching if we do it in sorted order. But this is still $O(n^4)$! What should we do? Well, there are some implementations of Kuhn's algorithm which can run on graphs of size about $10^5$ (sometimes even $10^6$). Why can't we use one of these? Unfortunately, not all optimizations that can be used in Kuhn's algorithm go together well with the fact that the vertices of the left part have their weights. For example, greedy initialization of matching won't work. So we need to choose optimizations carefully. The model solution uses the following optimization of Kuhn's algorithm: if you haven't found an augmenting path, don't reset the values representing which vertices were visited by the algorithm. With this optimization, Kuhn's algorithm works in $O(M(E + V))$, where $M$ is the size of the maximum matching, $E$ is the number of edges, and $V$ is the number of vertices. So, this results in a solution with complexity of $O(n^3)$. I think it's possible to show that some other optimizations of Kuhn can also work, but the one I described is enough.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int N = 1003;\n\nint n;\nint a[N];\nvector<int> g[N * N];\nint mt[N];\nbool used[N * N];\nvector<int> val;\n\nbool kuhn(int x)\n{\n    if(used[x]) return false;\n    used[x] = true;\n    for(auto y : g[x])\n        if(mt[y] == -1 || kuhn(mt[y]))\n        {\n            mt[y] = x;\n            return true;\n        }\n    return false;\n}\n\nint main()\n{\n    cin >> n;\n    for(int i = 0; i < n; i++) cin >> a[i];\n    for(int i = 0; i < n; i++)\n        for(int j = 1; j <= n; j++)\n            val.push_back(a[i] * j);\n    sort(val.begin(), val.end());\n    val.erase(unique(val.begin(), val.end()), val.end());\n    int v = val.size();\n    long long ans = 0;\n    for(int i = 0; i < n; i++)\n        for(int j = 1; j <= n; j++)\n        {\n            int k = lower_bound(val.begin(), val.end(), a[i] * j) - val.begin();\n            g[k].push_back(i);\n        }\n    for(int i = 0; i < n; i++) mt[i] = -1;\n    for(int i = 0; i < v; i++)\n    {\n        if(kuhn(i))\n        {\n            ans += val[i];\n            for(int j = 0; j < v; j++) used[j] = false;\n        }\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "flows",
      "graph matchings",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1728",
    "index": "G",
    "title": "Illumination",
    "statement": "Consider a segment $[0, d]$ of the coordinate line. There are $n$ lanterns and $m$ points of interest in this segment.\n\nFor each lantern, you can choose its power — an integer between $0$ and $d$ (inclusive). A lantern with coordinate $x$ illuminates the point of interest with coordinate $y$ if $|x - y|$ is less than or equal to the power of the lantern.\n\nA way to choose the power values for all lanterns is considered \\textbf{valid} if every point of interest is illuminated by at least one lantern.\n\nYou have to process $q$ queries. Each query is represented by one integer $f_i$. To answer the $i$-th query, you have to:\n\n- add a lantern on coordinate $f_i$;\n- calculate the number of valid ways to assign power values to all lanterns, and print it modulo $998244353$;\n- remove the lantern you just added.",
    "tutorial": "Let's start without the queries. How to calculate the number of ways for the given $n$ lanterns? First, it's much easier to calculate the number of bad ways - some point of interest is not illuminated. If at least one point of interest is not illuminated, then all lanterns have power lower than the distance from them to this point of interest. More importantly, it's less than $d$. Thus, the number of good ways is $(d+1)^n$ minus the number of bad ways. Let's use inclusion-exclusion. For a mask of non-illuminated points of interest, let's calculate the number of ways to assign the powers to the lanterns in such a way that at least these points of interest are not illuminated. All other points can be either illuminated or not. Let's call it $\\mathit{ways}[\\mathit{mask}]$. With the values for all masks, the answer is the sum of $\\mathit{ways}[\\mathit{mask}] \\cdot (-1)^{\\mathit{popcount(mask)}}$ over all masks. How to calculate the value for the mask? First, let's do it in $O(nm)$ for each mask. Each lantern can have any power from $0$ to the distance to the closest point of interest inside the mask non-inclusive. Thus, we can iterate over the lanterns and find the closest point to each of them, then multiply the number of ways for all lanterns. Let's calculate it the other way around. Initialize the answers for the masks with $1$. Then iterate over the lantern and the point of interest that will be the closest non-illuminated one to this lantern. Let the distance between them be some value $d$. Which masks will this pair affect? Let the lantern be to the right of that point of interest. The opposite can be handled similarly. All points to the left of the chosen point can be in either state. All points between the chosen one and the lantern must be illuminated. All points to the right of the lantern and with distance smaller than $d$ must also be illumunated. All point to the right of these can be in either state. Thus, the masks look like \"**..**1000..000**..**\", where 1 denotes the chosen non-illuminated point. All masks that correspond to this template will be multiplied by $d$. You have to be careful when there are two points of interest with the same distance $d$ to some lantern - one to the left of it and one to the right of it. In particular, in one case, you should force illumination on all points with distance $<d$. In another case, you should force illumination on all points with distance $\\le d$. How to multiply fast enough? We'll use a technique called sum-over-subsets. Let's express the template in terms of submasks. For a template \"***100000***\", all submasks of \"111100000111\" will be multiplied by $d$. However, we accidentally multiplied masks of form \"***000000***\" too. Let's cancel them by dividing the submasks of \"111000000111\" by $d$. Record all multiplications for all pairs, them force push them into submasks with sum-over-subsets (well, product-over-subsets in this case :)). Now we have the values of $\\mathit{ways}[\\mathit{mask}]$ for all masks in basically $O(nm + 2^m \\cdot m)$, give or take the time to find the points that must be forced illuminated (extra $O(\\log m)$ from lower_bound or two pointers, which is not really faster). Now for the queries. How does the answer change after an extra lantern is added? Again, let's iterate over the closest point of interest and find the mask template. All masks corresponding to this template will get multiplied by $d$. Thus, the answer will change by the sum of values of these masks, multiplied by $d$, including the inclusion-exclusion coefficient. How to handle that? Well, yet another sum-over-subsets. Just collect the sum of values over the submasks beforehand and use these during the query. That gives us an $O(m)$ per query. Overall complexity: $O(nm + qm + 2^m \\cdot m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\nint binpow(int a, int b){\n\tint res = 1;\n\twhile (b){\n\t\tif (b & 1)\n\t\t\tres = mul(res, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nint main() {\n\tint D, n, m;\n\t\n\tscanf(\"%d%d%d\", &D, &n, &m);\n\t\n\tvector<int> inv(D + 1);\n\tforn(i, D + 1) inv[i] = binpow(i, MOD - 2);\n\t\n\tvector<int> b(n);\n\tforn(i, n) scanf(\"%d\", &b[i]);\n\t\n\tvector<int> a(m);\n\tforn(i, m) scanf(\"%d\", &a[i]);\n\tsort(a.begin(), a.end());\n\t\n\tint fl = (1 << m) - 1;\n\tvector<int> ways(1 << m, 1);\n\tforn(i, m) forn(j, n){\n\t\tint d = abs(b[j] - a[i]);\n\t\tint mask;\n\t\tif (b[j] > a[i]){\n\t\t\tint r = lower_bound(a.begin(), a.end(), b[j] + d) - a.begin();\n\t\t\tmask = fl ^ ((1 << r) - 1) ^ ((1 << (i + 1)) - 1);\n\t\t}\n\t\telse{\n\t\t\tint l = lower_bound(a.begin(), a.end(), b[j] - d) - a.begin();\n\t\t\tmask = fl ^ ((1 << i) - 1) ^ ((1 << l) - 1);\n\t\t}\n\t\tways[mask] = mul(ways[mask], d);\n\t\tmask ^= (1 << i);\n\t\tways[mask] = mul(ways[mask], inv[d]);\n\t}\n\t\n\tforn(i, m) for (int mask = fl; mask >= 0; --mask) if ((mask >> i) & 1){\n\t\tways[mask ^ (1 << i)] = mul(ways[mask ^ (1 << i)], ways[mask]);\n\t}\n\t\n\tways[0] = binpow(D + 1, n);\n\tforn(mask, 1 << m){\n\t\tways[mask] = mul(ways[mask], __builtin_popcount(mask) & 1 ? MOD - 1 : 1);\n\t}\n\tforn(i, m) forn(mask, 1 << m) if (!((mask >> i) & 1)){\n\t\tways[mask ^ (1 << i)] = add(ways[mask ^ (1 << i)], ways[mask]);\n\t}\n\t\n\tint q;\n\tscanf(\"%d\", &q);\n\tforn(_, q){\n\t\tint x;\n\t\tscanf(\"%d\", &x);\n\t\tint ans = binpow(D + 1, n + 1);\n\t\tforn(i, m){\n\t\t\tint d = abs(x - a[i]);\n\t\t\tint mask;\n\t\t\tif (x > a[i]){\n\t\t\t\tint r = lower_bound(a.begin(), a.end(), x + d) - a.begin();\n\t\t\t\tmask = fl ^ ((1 << r) - 1) ^ ((1 << (i + 1)) - 1);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tint l = lower_bound(a.begin(), a.end(), x - d) - a.begin();\n\t\t\t\tmask = fl ^ ((1 << i) - 1) ^ ((1 << l) - 1);\n\t\t\t}\n\t\t\tans = add(ans, mul(add(ways[mask], -ways[mask ^ (1 << i)]), d));\n\t\t}\n\t\tprintf(\"%d\\n\", ans);\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp",
      "math",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1729",
    "index": "A",
    "title": "Two Elevators",
    "statement": "Vlad went into his appartment house entrance, now he is on the $1$-th floor. He was going to call the elevator to go up to his apartment.\n\nThere are only two elevators in his house. Vlad knows for sure that:\n\n- the first elevator is currently on the floor $a$ (it is currently motionless),\n- the second elevator is located on floor $b$ and goes to floor $c$ ($b \\ne c$). Please note, if $b=1$, then the elevator is already leaving the floor $1$ and Vlad does not have time to enter it.\n\nIf you call the first elevator, it will immediately start to go to the floor $1$. If you call the second one, then first it will reach the floor $c$ and only then it will go to the floor $1$. It takes $|x - y|$ seconds for each elevator to move from floor $x$ to floor $y$.\n\nVlad wants to call an elevator that will come to him faster. Help him choose such an elevator.",
    "tutorial": "You had to to calculate the time that each elevator would need and compare them. Let the time required by the first elevator be $d_1 = |a - 1|$, and the time required by the second one be $d_2 = |b - c| + |c - 1|$. Then the answer is $1$ if $d_1 < d_2$, $2$ if $d_1 > d_2$ and $3$ if $d_1 = d_2$",
    "code": "t = int(input())\nfor _ in range(t):\n    a, b, c = map(int, input().split())\n    d1 = a - 1\n    d2 = abs(b - c) + c - 1\n    ans = 0\n    if d1 <= d2:\n        ans += 1\n    if d1 >= d2:\n        ans += 2\n    print(ans)",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1729",
    "index": "B",
    "title": "Decode String",
    "statement": "Polycarp has a string $s$ consisting of lowercase Latin letters.\n\nHe encodes it using the following algorithm.\n\nHe goes through the letters of the string $s$ from left to right and for each letter Polycarp considers its number in the alphabet:\n\n- if the letter number is single-digit number (less than $10$), then just writes it out;\n- if the letter number is a two-digit number (greater than or equal to $10$), then it writes it out and adds the number 0 after.\n\nFor example, if the string $s$ is code, then Polycarp will encode this string as follows:\n\n- 'c' — is the $3$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3);\n- 'o' — is the $15$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150);\n- 'd' — is the $4$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504);\n- 'e' — is the $5$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045).\n\nThus, code of string code is 315045.\n\nYou are given a string $t$ resulting from encoding the string $s$. Your task is to decode it (get the original string $s$ by $t$).",
    "tutorial": "The idea is as follows: we will go from the end of the string $t$ and get the original string $s$. Note that if the current digit is $0$, then a letter with a two-digit number has been encoded. Then we take a substring of length three from the end, discard $0$ and get the number of the original letter. Otherwise, the current number $\\neq 0$, then a letter with a one-digit number was encoded. We easily reconstruct the original letter. Next, discard the already processed characters and repeat the process until the encoded string is complete.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <queue>\n\nusing namespace std;\n\nchar get(int i) {\n    return 'a' + i - 1;\n}\n\nvoid solve() {\n    int n;\n    string s;\n    cin >> n >> s;\n    int i = n - 1;\n    string res;\n    while (i >= 0) {\n        if (s[i] != '0') {\n            res += get(s[i] - '0');\n            i--;\n        } else {\n            res += get(stoi(s.substr(i - 2, 2)));\n            i -= 3;\n        }\n    }\n    reverse(res.begin(), res.end());\n    cout << res << '\\n';\n}\n\nint main() {\n    int t = 1;\n    cin >> t;\n    for (int it = 0; it < t; ++it) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1729",
    "index": "C",
    "title": "Jumping on Tiles",
    "statement": "Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $s$.\n\nIn other words, you are given a string $s$ consisting of lowercase Latin letters.\n\nInitially, Polycarp is on the \\textbf{first} tile of the row and wants to get to the \\textbf{last} tile by jumping on the tiles. Jumping from $i$-th tile to $j$-th tile has a cost equal to $|index(s_i) - index(s_j)|$, where $index(c)$ is the index of the letter $c$ in the alphabet (for example, $index($'a'$)=1$, $index($'b'$)=2$, ..., $index($'z'$)=26$) .\n\nPolycarp wants to get to the $n$-th tile for the minimum total cost, but at the same time make \\textbf{maximum} number of jumps.\n\nIn other words, among all possible ways to get to the last tile for the \\textbf{minimum} total cost, he will choose the one with the \\textbf{maximum} number of jumps.\n\nPolycarp can visit each tile \\textbf{at most once}.\n\nPolycarp asks you to help — print the sequence of indices of string $s$ on which he should jump.",
    "tutorial": "It's worth knowing that ways like ('a' -> 'e') and ('a' -> 'c' -> 'e') have the same cost. That is, first you need to understand the letter on the first tile and the last one (conditionally, the letters $first$ and $last$). Then you just need to find all such tiles on which the letters are between the letters $first$ and $last$ inclusive. We go through each letter from $first$ to $last$ and for each letter we visit every tile that has a given letter (but we must not forget to start exactly at tile $1$ and end at tile $n$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nvoid solve() {\n\n    string s;\n    cin >> s;\n\n    int n = s.size();\n    map<char, vector<int>> let_to_ind;\n\n    for (int i = 0; i < n; ++i) {\n        let_to_ind[s[i]].push_back(i);\n    }\n\n    int direction = (s[0] < s[n - 1]) ? 1 : -1;\n    vector<int> ans;\n\n    for (char c = s[0]; c != s[n - 1] + direction; c += direction) {\n        for (auto now : let_to_ind[c]) {\n            ans.push_back(now);\n        }\n    }\n\n    int cost = 0;\n    for (int i = 1; i < ans.size(); i++)\n        cost += abs(s[ans[i]] - s[ans[i - 1]]);\n\n    cout << cost << \" \" << ans.size() << '\\n';\n    for (auto now : ans) {\n        cout << now + 1 << \" \";\n    }\n    cout << '\\n';\n}\nint main() {\n    int tests;\n    cin >> tests;\n    forn(tt, tests) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1729",
    "index": "D",
    "title": "Friends and the Restaurant",
    "statement": "A group of $n$ friends decide to go to a restaurant. Each of the friends plans to order meals for $x_i$ burles and has a total of $y_i$ burles ($1 \\le i \\le n$).\n\nThe friends decide to split their visit to the restaurant into several days. Each day, some group of \\textbf{at least two} friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be \\textbf{not less} than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $x_i$ values in the group must not exceed the sum of $y_i$ values in the group.\n\nWhat is the maximum number of days friends can visit the restaurant?\n\nFor example, let there be $n = 6$ friends for whom $x$ = [$8, 3, 9, 2, 4, 5$] and $y$ = [$5, 3, 1, 4, 5, 10$]. Then:\n\n- first and sixth friends can go to the restaurant on the first day. They will spend $8+5=13$ burles at the restaurant, and their total budget is $5+10=15$ burles. Since $15 \\ge 13$, they can actually form a group.\n- friends with indices $2, 4, 5$ can form a second group. They will spend $3+2+4=9$ burles at the restaurant, and their total budget will be $3+4+5=12$ burles ($12 \\ge 9$).\n\nIt can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.\n\nSo, the maximum number of groups the friends can split into is $2$. Friends will visit the restaurant for a maximum of two days. Note that the $3$-rd friend will not visit the restaurant at all.\n\nOutput the maximum number of days the friends can visit the restaurant for given $n$, $x$ and $y$.",
    "tutorial": "First, we sort the friends in descending order of $y_i - x_i$. Now for each friend we know the amount of money he lacks, or vice versa, which he has in excess. In order to maximize the number of days, it is most advantageous for friends to break into pairs. It is the number of groups that matters, not the number of people in the group, so adding a third person to the pair won't improve the answer in any way. Let's solve the problem using two pointers: for the richest friend, find the first friend from the end such that the sum of their values $y$ exceeds the sum of their values $x$. Then repeat this for all subsequent friends until the pointers meet. If no pair could be formed, or none of the friends has a value $x$ greater than $y$, then the answer is -1. Otherwise, print the number of pairs formed.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<ll>x(n), y(n);\n    vector<pair<ll, int>>dif(n);\n\n    for(auto &i : x) cin >> i;\n    for(auto &i: y) cin >> i;\n    for(int i = 0; i < n; i++){\n        dif[i].first = y[i] - x[i];\n        dif[i].second = i;\n    }\n    sort(dif.begin(), dif.end());\n    reverse(dif.begin(), dif.end());\n\n    int j = n - 1, cnt = 0;\n\n    for(int i = 0; i < n; i++){\n        while(j > i && dif[i].first + dif[j].first < 0) j--;\n        if(j <= i) break;\n        cnt++; j--;\n    }\n    cout << cnt << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1729",
    "index": "E",
    "title": "Guess the Cycle Size",
    "statement": "\\textbf{This is an interactive problem}.\n\nI want to play a game with you...\n\nWe hid from you a cyclic graph of $n$ vertices ($3 \\le n \\le 10^{18}$). A cyclic graph is an undirected graph of $n$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $n$. The order of the vertices in the cycle is arbitrary.\n\nYou can make queries in the following way:\n\n- \"? a b\" where $1 \\le a, b \\le 10^{18}$ and $a \\neq b$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $a$ to vertex $b$, or -1 if $\\max(a, b) > n$. The interactor chooses one of the two paths with \\textbf{equal probability}. The length of the path —is the number of edges in it.\n\nYou win if you guess the number of vertices in the hidden graph (number $n$) by making no more than $50$ queries.\n\nNote that the interactor is implemented in such a way that for any ordered pair $(a, b)$, it always returns the same value for query \"? a b\", no matter how many such queries. Note that the \"? b a\" query may be answered differently by the interactor.\n\nThe vertices in the graph are randomly placed, and their positions are fixed in advance.\n\nHacks are forbidden in this problem. The number of tests the jury has is $50$.",
    "tutorial": "The implication was that the solution works correctly with some high probability. So we tried to give such constraints so that the solution probability is very high. The idea: we will output queries of the form $(1, n)$ and $(n, 1)$, gradually increasing $n$ from $2$. If we get an answer to query $-1$ the first time, then the size of the graph is exactly $n-1$. Otherwise, let the answer to the first query be $x$ and the answer to the second query be $y$. With probability $\\frac{1}{2}, x \\neq y$. In this case, we can output the answer: $x+y$, since there are a total of two different paths from vertex $1$ to $n$ and we recognized them. Accordingly the total length of paths will be the size of the cyclic graph. But with probability $\\frac{1}{2}, x = y$. In this case we must continue the algorithm. At most we can make $25$ of such attempts. Let's calculate the probability of finding the correct graph size: $p = 1 - (\\frac{1}{2})^{25}$. That is, we \"lucky\" on one test with probability $p \\approx 0.99999997$. But we should have \"lucky\" on $50$ tests. We get: $P = p^{50} \\approx 0.99999851$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\nlong long ask(int a, int b) {\n    cout << \"? \" << a << ' ' << b << endl;\n    long long x; cin >> x;\n    return x;\n}\n\nlong long solve() {\n    for (int i = 2; i <= 26; i++) {\n        long long x = ask(1, i);\n        long long y = ask(i, 1);\n        if (x == -1) return i-1;\n        if (x != y) return x + y;\n    }\n    assert(false);\n}\n\nint main() {\n    long long ans = solve();\n    cout << \"! \" << ans << endl;\n}",
    "tags": [
      "interactive",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1729",
    "index": "F",
    "title": "Kirei and the Linear Function",
    "statement": "Given the string $s$ of decimal digits (0-9) of length $n$.\n\nA substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($l, r$), where $1 \\le l \\le r \\le n$, corresponds to a substring of the string $s$. We will define as $v(l,r)$ the numeric value of the corresponding substring (leading zeros are allowed in it).\n\nFor example, if $n=7$, $s=$\"1003004\", then $v(1,3)=100$, $v(2,3)=0$ and $v(2,7)=3004$.\n\nYou are given $n$, $s$ and an integer $w$ ($1 \\le w < n$).\n\nYou need to process $m$ queries, each of which is characterized by $3$ numbers $l_i, r_i, k_i$ ($1 \\le l_i \\le r_i \\le n; 0 \\le k_i \\le 8$).\n\nThe answer to the $i$th query is such a pair of substrings of length $w$ that if we denote them as $(L_1, L_1+w-1)$ and $(L_2, L_2+w-1)$, then:\n\n- $L_1 \\ne L_2$, that is, the substrings are different;\n- the remainder of dividing a number $v(L_1, L_1+w-1) \\cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$ by $9$ is equal to $k_i$.\n\nIf there are many matching substring pairs, then find a pair where $L_1$ is as small as possible. If there are many matching pairs in this case, then minimize $L_2$.\n\nNote that the answer may not exist.",
    "tutorial": "Note that the remainder of dividing a number by $9$ is equal to the remainder of dividing its sum of digits by $9$. This is easy to check, because the number $a$ of $n$ digits is representable as a polynomial $a_0 + a_1\\cdot 10 + a_2\\cdot 100 + \\dots + a_{n-1}\\cdot 10^{n-1} + a_n\\cdot 10^n$, and $10^k$ gives a remainder of $1$ when divided by $9$ for any $k$. Let's count an array of prefix sums of digits for the string $s$. Now, knowing $w$, we can pre-calculate for each remainder modulo $9$ all possible $L$. Also, for each query, we can easily find the remainder of dividing $v(l,r)$ by $9$ using all the same prefix sums. Let's iterate over the remainder of the number $a$ when dividing by $9$. Knowing it, we can easily find the remainder of the number $b$ when divided by $9$, as $k - a\\cdot v(l,r)$ modulo $9$. Now, using each pair of remainers $(a, b)$, let's try to update the answer: $a = b$, then the minimum index from the pre-calculated array will act as $L_1$, and the next largest will act as $L_2$ (if such exist); $a\\neq b$, then the minimum indexes from the pre-calculated array will act as $L_1$ and $L_2$. This solution works for $9\\cdot(n+m)$ or for $O(n + m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define endl '\\n'\n\nusing namespace std;\n\ntypedef pair<int, int> ipair;\n\nconst int MAXSZ = 200200;\nconst int INF = 2e9;\n\ninline int add(int a, int b) {\n\treturn (a + b >= 9 ? a + b - 9 : a + b);\n}\n\ninline int sub(int a, int b) {\n\treturn (a < b ? a + 9 - b : a - b);\n}\n\ninline int mul(int a, int b) {\n\treturn a * b % 9;\n}\n\nint sz, n, m;\nstring s;\nint ps[MAXSZ];\nvector<int> D[9];\n\nvoid build() {\n\tsz = s.size();\n\tfor (int md = 0; md < 9; ++md)\n\t\tD[md].clear();\n\tfor (int i = 0; i < sz; ++i)\n\t\tps[i + 1] = ps[i] + (s[i] - '0');\n\tfor (int i = 0; i + n <= sz; ++i)\n\t\tD[(ps[i + n] - ps[i]) % 9].push_back(i);\n}\n\nipair solve(int l, int r, int k) {\n\tint x = (ps[r] - ps[l]) % 9;\n\tipair ans {INF, INF};\n\tfor (int a = 0; a < 9; ++a) {\n\t\tint b = sub(k, mul(a, x));\n\t\tif (D[a].empty() || D[b].empty()) continue;\n\t\tif (a != b)\n\t\t\tans = min(ans, make_pair(D[a].front(), D[b].front()));\n\t\telse if (D[a].size() >= 2)\n\t\t\tans = min(ans, make_pair(D[a].front(), D[a][1]));\n\t}\n\tif (ans == make_pair(INF, INF))\n\t\treturn {-2, -2};\n\treturn ans;\n}\n\nint main() {\n\tios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tcin >> s >> n >> m;\n\t\tbuild();\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tint l, r, k; cin >> l >> r >> k, --l;\n\t\t\tauto [ans1, ans2] = solve(l, r, k);\n\t\t\tcout << ++ans1 << ' ' << ++ans2 << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "hashing",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1729",
    "index": "G",
    "title": "Cut Substrings",
    "statement": "You are given two non-empty strings $s$ and $t$, consisting of Latin letters.\n\nIn one move, you can choose an occurrence of the string $t$ in the string $s$ and replace it with dots.\n\nYour task is to remove all occurrences of the string $t$ in the string $s$ in the minimum number of moves, and also calculate how many \\textbf{different} sequences of moves of the minimum length exist.\n\nTwo sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $t$ in $s$ begin differ. For example, the sets $\\{1, 2, 3\\}$ and $\\{1, 2, 4\\}$ are considered different, the sets $\\{2, 4, 6\\}$ and $\\{2, 6\\}$ — too, but sets $\\{3, 5\\}$ and $\\{5, 3\\}$ — not.\n\nFor example, let the string $s =$ \"abababacababa\" and the string $t =$ \"aba\". We can remove all occurrences of the string $t$ in $2$ moves by cutting out the occurrences of the string $t$ at the $3$th and $9$th positions. In this case, the string $s$ is an example of the form \"ab...bac...ba\". It is also possible to cut occurrences of the string $t$ at the $3$th and $11$th positions. There are two different sequences of minimum length moves.\n\nSince the answer can be large, output it modulo $10^9 + 7$.",
    "tutorial": "First, find all occurrences of $t$ in $s$ as substrings. This can be done using the prefix function. To find the minimum number of times we need to cut substrings, consider all indexes of occurrences. Having considered the index of the occurrence, we cut out the rightmost occurrence that intersects with it. After that, we find the leftmost occurrence that does not intersect with the cut one. If it doesn't, we end the loop. The number of optimal sequences of moves will be calculated using dynamic programming. For each occurrence, we can count how many ways we can cut out all occurrences of $t$ in the suffix $s$ starting with this occurrence in the minimum number of moves. Considering the occurrence, we find the leftmost occurrence that does not intersect with it, and then iterate over the occurrences with which we can remove it.",
    "code": "#include<cstdio>\n#include<cstring>\nconst int N=505;\nconst int Mod=1e9+7;\nchar s[N],t[N];\nint n,m;\nint f[N],g[N];\nint p[N],tot;\ninline void Init(){\n\tscanf(\"%s\",s+1);\n\tscanf(\"%s\",t+1);\n\tn=strlen(s+1);\n\tm=strlen(t+1);\n\ttot=0;\n\tfor(int i=1;i+m-1<=n;i++){\n\t\tbool flg=1;\n\t\tfor(int j=1;j<=m;j++)\n\t\t\tif(s[i+j-1]!=t[j]) flg=0;\n\t\tif(flg) p[++tot]=i;\n\t}\n\treturn ;\n}\ninline int addv(int x,int y){\n\tint s=x+y;\n\tif(s>=Mod) s-=Mod;\n\treturn s;\n}\ninline int subv(int x,int y){\n\tint s=x-y;\n\tif(s<0) s+=Mod;\n\treturn s;\n}\ninline void add(int&x,int y){\n\tx=addv(x,y);\n\treturn ;\n}\ninline void sub(int&x,int y){\n\tx=subv(x,y);\n\treturn ;\n}\ninline void Solve(){\n\tmemset(f,0x3f,sizeof(f));\n\tmemset(g,0,sizeof(g));\n\tp[0]=-N;\n\tf[0]=0;\n\tg[0]=1;\n\tp[++tot]=n+m;\n\tfor(int i=0;i<tot;i++){\n\t\tint j=i+1;\n\t\twhile(j<=tot&&p[j]<=p[i]+m-1) j++;\n\t\tfor(int k=j;p[j]+m-1>=p[k]&&k<=tot;k++){\n\t\t\tif(f[i]+1<f[k]){\n\t\t\t\tf[k]=f[i]+1;\n\t\t\t\tg[k]=g[i];\n\t\t\t}\n\t\t\telse if(f[i]+1==f[k]) add(g[k],g[i]);\n\t\t}\n\t}\n\tprintf(\"%d %d\\n\",f[tot]-1,g[tot]);\n\treturn ;\n}\nint T;\nint main(){\n\tfor(scanf(\"%d\",&T);T;T--){\n\t\tInit();\n\t\tSolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "hashing",
      "strings",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1730",
    "index": "A",
    "title": "Planets",
    "statement": "One day, Vogons wanted to build a new hyperspace highway through a distant system with $n$ planets. The $i$-th planet is on the orbit $a_i$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed.\n\nVogons have two machines to do that.\n\n- The first machine in one operation can destroy any planet at cost of $1$ Triganic Pu.\n- The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $c$ Triganic Pus.\n\nVogons can use each machine as many times as they want.\n\nVogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project?",
    "tutorial": "To solve the problem, it was enough to count the number of planets with the same orbits $cnt_i$ and sum up the answers for the orbits separately. For one orbit, it is advantageous either to use the second machine once and get the cost $c$, or to use only the first one and get the cost equal to $cnt_i$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n, c;\n    cin >> n >> c;\n \n    vector<int> a(n);\n    map<int, int> mp;\n    int ans = 0;\n    for(int i = 0; i < n; i++){\n        cin >> a[i];\n        mp[a[i]]++;\n        if(mp[a[i]] <= c){\n            ans++;\n        }\n    }\n    cout << ans << endl;\n \n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    while(t--)\n        solve();\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1730",
    "index": "B",
    "title": "Meeting on the Line",
    "statement": "$n$ people live on the coordinate line, the $i$-th one lives at the point $x_i$ ($1 \\le i \\le n$). They want to choose a position $x_0$ to meet. The $i$-th person will spend $|x_i - x_0|$ minutes to get to the meeting place. Also, the $i$-th person needs $t_i$ minutes to get dressed, so in total he or she needs $t_i + |x_i - x_0|$ minutes.\n\nHere $|y|$ denotes the absolute value of $y$.\n\nThese people ask you to find a position $x_0$ that minimizes the time in which all $n$ people can gather at the meeting place.",
    "tutorial": "There are many solutions to this problem, here are 2 of them. 1) Let people be able to meet in time $T$, then they could meet in time $T + \\varepsilon$, where $\\varepsilon > 0$. So we can find $T$ by binary search. It remains to learn how to check whether people can meet for a specific time $T$. To do this, for the $i$-th person, find a segment of positions that he can get to in time $T$: if $T < t_i$ then this segment is empty, otherwise it is $[x_i - (T - t_i), x_i + (T - t_i)]$. Then people will be able to meet only if these segments intersect, that is, the minimum of the right borders is greater than or equal to the maximum of the left borders. In order to find the answer by the minimum $T$, you need to intersect these segments in the same way (should get a point, but due to accuracy, most likely, a segment of a very small length will turn out) and take any point of this intersection. Asymptotics is $O(n \\log n)$. 2) If all $t_i$ were equal to $0$, then this would be a classical problem, the solution of which would be to find the average of the minimum and maximum coordinates of people. We can reduce our problem to this one if we replace the person ($x_i$, $t_i$) with two people: ($x_i - t_i$, $0$) and ($x_i + t_i$, $0$). Proof. Let the meeting be at the point $y$. Let $x_i \\le y$. Then this person will need $t_i + y - x_i$ of time to get to her, and the two we want to replace him with - $y - x_i + t_i$ and $y - x_i - t_i$. it is easy to see that the first value is equal to the initial value, and the second is not greater than the initial value, then the maximum of these two values is equal to the initial value. The proof is similar for the case $y \\le x_i$. Then for any meeting point, the time in the original problem and after the replacement does not differ, which means that such a replacement will not change the answer and it can be done. Asymptotics is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    vector<int> x(n), t(n);\n    for(int i = 0; i < n; i++)\n        cin >> x[i];\n \n    for(int i = 0; i < n; i++)\n        cin >> t[i];\n \n    vector<int> a;\n    for(int i = 0; i < n; i++) {\n        a.push_back(x[i] + t[i]);\n        a.push_back(x[i] - t[i]);\n    }\n \n    int mn = a[0], mx = a[0];\n    for(int val : a) {\n        mn = min(mn, val);\n        mx = max(mx, val);\n    }\n \n    int sum = mn + mx;\n    cout << sum / 2;\n    if(sum % 2 != 0)\n        cout << \".5\";\n    cout << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    while(t--)\n        solve();\n}",
    "tags": [
      "binary search",
      "geometry",
      "greedy",
      "implementation",
      "math",
      "ternary search"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1730",
    "index": "C",
    "title": "Minimum Notation",
    "statement": "You have a string $s$ consisting of digits from $0$ to $9$ inclusive. You can perform the following operation any (possibly zero) number of times:\n\n- You can choose a position $i$ and delete a digit $d$ on the $i$-th position. Then insert the digit $\\min{(d + 1, 9)}$ on any position (at the beginning, at the end or in between any two adjacent digits).\n\nWhat is the lexicographically smallest string you can get by performing these operations?\n\nA string $a$ is lexicographically smaller than a string $b$ of the same length if and only if the following holds:\n\n- in the first position where $a$ and $b$ differ, the string $a$ has a smaller digit than the corresponding digit in $b$.",
    "tutorial": "We leave all suffix minimums by the digits $mn_i$ (digits less than or equal to the minimum among the digits to the right of them), remove the rest and replace them with $\\min{(d + 1, 9)}$ (using the described operations) and add to lexicographically minimum order on the right (due to the appropriate order of operations, this is possible). The suffix minimums $mn_i$ should be left, because no matter what digit we leave after $mn_i$, it will be no less than $mn_i$, and therefore will not improve the answer. The rest must be removed at the end with operations, since there is a number to the right less than this one, i.e. if you remove everything before it (put $mn_i$ at the current position), the answer will become less than if you leave another digit at this position.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve(){\n    string s;\n    cin >> s;\n    int n = s.size();\n    vector<int> a(n);\n    vector<int> mn(n + 1, 9);\n    for(int i = 0; i < n; i++){\n        a[i] = int(s[i] - '0');\n    }\n    for(int i = n - 1; i >= 0; i--){\n        mn[i] = min(mn[i + 1], a[i]);\n    }\n    vector<int> buff(10, 0);\n    string ans = \"\";\n    string t = \"0123456789\";\n    for(int i = 0; i < n; i++){\n        for(int j = 0; j < mn[i]; j++){\n            while(buff[j]){\n                buff[j]--;\n                ans += t[j];\n            }\n        }\n        if(a[i] == mn[i]){\n            ans += t[a[i]];\n        }\n        else{\n            buff[min(9, a[i] + 1)]++;\n        }\n    }\n    for(int j = 0; j < 10; j++){\n        while(buff[j]){\n            buff[j]--;\n            ans += t[j];\n        }\n    }\n    cout << ans << endl;\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1730",
    "index": "D",
    "title": "Prefixes and Suffixes",
    "statement": "You have two strings $s_1$ and $s_2$ of length $n$, consisting of lowercase English letters. You can perform the following operation any (possibly zero) number of times:\n\n- Choose a positive integer $1 \\leq k \\leq n$.\n- Swap the prefix of the string $s_1$ and the suffix of the string $s_2$ of length $k$.\n\nIs it possible to make these two strings equal by doing described operations?",
    "tutorial": "If you reflect the second string and see what happens, it is easy to see that the elements at the same positions in both strings after any action remain at the same positions relative to each other. Let's combine them into unsorted pairs and treat these pairs as single objects. Now we need to compose a palindrome from these objects. This is always possible with the help of these actions, if there is a palindrome consisting of these objects (pay attention to odd palindromes, there must be a pair of the form (a, a) in the center). Proof of possibility: Let's make an array of pairs, in one action we expand some prefix of this array and the elements in the pairs of this prefix are swapped. Let's prove that we can change the order of the pairs in the array as we like. We will build from the end. Let all the pairs after position $i$ already stand as we want, and now the pair that we want to place in position $i$ at position $j \\leq i$. Let's do the following: $1.$ $k = j$ - will move the pair from position $j$ to the beginning. $2*.$ $k = 1$ - swap elements within a pair if needed (so pairs are considered unsorted). $3.$ $k = i$ - move the pair from the beginning to position $i$. (* the $2$ action is optional if you don't want to change the order of the elements in the pair) With this construction, we can get any permutation of these pairs and a palindrome, if it is possible. If you divide the final palindrome into two strings and expand the second one back, you get the first string. Example: From the test suite from the condition: $s_1 = \\mathtt{bbcaa}$, $s_2 = \\mathtt{cbaab}$, expanded $s_2 = \\mathtt{baabc}$. Couples: $\\mathtt{(b, b)}$, $\\mathtt{(b, a)}$, $\\mathtt{(c, a)}$, $\\mathtt{(a, b)}$, $\\ mathtt{(a, c)}$. Pairs unordered: $\\mathtt{(b, b)}$, $\\mathtt{(a, b)} \\cdot 2$, $\\mathtt{(a, c)} \\cdot 2$. Pairs in a palindrome: $\\mathtt{(a, b)}$, $\\mathtt{(a, c)}$, $\\mathtt{(b, b)}$, $\\mathtt{(a, c)}$, $\\mathtt{(a, b)}$. Real couples: $\\mathtt{(a, b)}$, $\\mathtt{(a, c)}$, $\\mathtt{(b, b)}$, $\\mathtt{(c, a)}$, $\\mathtt{(b, a)}$. Strings: $s_1 = \\mathtt{aabcb}$ expanded $s_2 = \\mathtt{bcbaa}$, $s_2 = \\mathtt{aabcb}$. !!! The pair $\\mathtt{(b, b)}$ !!!",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve(){\n    int n;\n    cin >> n;\n    string s1, s2;\n    cin >> s1 >> s2;\n    map<pair<int, int>, int> mp;\n    set<pair<int, int>> st;\n    int cnt_odd_simmetric = 0;\n    int cnt_odd = 0;\n    for(int i = 0; i < n; i++){\n        pair<int, int> p = {s1[i], s2[n - i - 1]};\n        if(p.first > p.second){\n            p = {p.second, p.first};\n        }\n        if(st.count(p) != 0){\n            mp[p]++;\n            if(mp[p] % 2 == 1){\n                cnt_odd++;\n                if(p.first == p.second){\n                    cnt_odd_simmetric++;\n                }\n            }\n            else{\n                cnt_odd--;\n                if(p.first == p.second){\n                    cnt_odd_simmetric--;\n                }\n            }\n        }\n        else{\n            st.insert(p);\n            mp[p] = 1;\n            cnt_odd++;\n            if(p.first == p.second){\n                cnt_odd_simmetric++;\n            }\n        }\n    }\n    if(n % 2 == cnt_odd_simmetric && cnt_odd == cnt_odd_simmetric){\n        cout << \"YES\\n\";\n    }\n    else{\n        cout << \"NO\\n\";\n    }\n \n}\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "strings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1730",
    "index": "E",
    "title": "Maximums and Minimums",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$ of positive integers.\n\nFind the number of pairs of indices $(l, r)$, where $1 \\le l \\le r \\le n$, that pass the check. The check is performed in the following manner:\n\n- The minimum and maximum numbers are found among $a_l, a_{l+1}, \\ldots, a_r$.\n- The check is passed if the maximum number is divisible by the minimum number.",
    "tutorial": "Let's introduce some new variables: $lge_i$ - the position of the nearest left greater or equal than $a_i$($-1$ if there is none). $rg_i$ - position of the nearest right greater than $a_i$($n$ if there is none). $ll_i$ - position of the nearest left lower than $a_i$($-1$ if there is none). $rl_i$ - position of the nearest right lower than $a_i$($n$ if there is none). All this can be calculated, for example, using a stack in $O(n)$ or using binary search and sparse table in $O(n\\log n)$ Let's iterate over the position $i$ of the leftmost maximum of the good segment. Then the $i$-th element will be the maximum on the segment [l, r] if $lge_i < l \\le i$ and $i \\le r < rg_i$ $(1)$. For the segment to pass the test, the minimum must be a divisor of the maximum. Let's iterate over this divisor $d$ and find the number of segments where the maximum is $a_i$ and the minimum is $d$. Consider positions of occurrence of $d$ $j_1$ and $j_2$ - the nearest left and right to $i$(they can be found using two pointers). Let's find the number of segments satisfying the condition $(1)$, in which the element $j_1$ is a minimum. To do this, similar conditions must be added to $(1)$: $ll_i < l \\le j_1$ and $j_1 \\le r < rg_i$. Intersecting these conditions, we obtain independent segments of admissible values of the left and right boundaries of the desired segment. Multiplying their lengths, we get the number of required segments. Similarly, the number of segments satisfying $(1)$, in which $j_2$ is the minimum, is found, but in order not to count 2 times one segment, one more condition must be added: $j_1 < l$. The sum of these quantities over all $i$ and divisors of $a_i$ will give the answer to the problem. To enumerate divisors, it is better to precompute the divisors of all numbers in $O(A\\log A)$, where $A$ is the constraint on $a_i$. So the whole solution runs in $O(A\\log A + nD)$, where $D$ is the maximum number of divisors.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 5e5 + 13;\nconst int A = 1e6 + 13;\n \nvector<int> divs[A];\nint a[N];\n \nint gr_lf[N], gr_rg[N];\nint less_lf[N], less_rg[N];\n \nvector<int> pos[A];\nint ind[A];\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    for(int i = 0; i < n; i++) {\n        cin >> a[i];\n        pos[a[i]].push_back(i);\n    }\n \n    {\n        stack<int> st;\n        for(int i = 0; i < n; i++) {\n            while(!st.empty() && a[st.top()] < a[i])\n                st.pop();\n \n            gr_lf[i] = (st.empty() ? -1 : st.top());\n            st.push(i);\n        }\n    }\n \n    {\n        stack<int> st;\n        for(int i = n - 1; i >= 0; i--) {\n            while(!st.empty() && a[st.top()] <= a[i])\n                st.pop();\n \n            gr_rg[i] = (st.empty() ? n : st.top());\n            st.push(i);\n        }\n    }\n \n    {\n        stack<int> st;\n        for(int i = 0; i < n; i++) {\n            while(!st.empty() && a[st.top()] >= a[i])\n                st.pop();\n \n            less_lf[i] = (st.empty() ? -1 : st.top());\n            st.push(i);\n        }\n    }\n \n    {\n        stack<int> st;\n        for(int i = n - 1; i >= 0; i--) {\n            while(!st.empty() && a[st.top()] >= a[i])\n                st.pop();\n \n            less_rg[i] = (st.empty() ? n : st.top());\n            st.push(i);\n        }\n    }\n \n    long long ans = 0;\n    for(int i = 0; i < n; i++) {\n        for(int x : divs[a[i]]) {\n            if(ind[x] >= 1) {\n                int j = pos[x][ind[x] - 1];\n                if(j > gr_lf[i] && less_rg[j] > i) {\n                    ans += (j - max(gr_lf[i], less_lf[j])) * 1ll * (min(gr_rg[i], less_rg[j]) - i);\n                }\n            }\n \n            if(ind[x] < pos[x].size()) {\n                int j = pos[x][ind[x]];\n                if(j < gr_rg[i] && less_lf[j] < i) {\n                    ans += (i - max({gr_lf[i], less_lf[j], ind[x] >= 1 ? pos[x][ind[x] - 1] : -1})) * 1ll * (min(gr_rg[i], less_rg[j]) - j);\n                }\n \n            }\n        }\n \n        ind[a[i]]++;\n    }\n \n    cout << ans << endl;\n \n    for(int i = 0; i < n; i++) {\n        pos[a[i]].erase(pos[a[i]].begin(), pos[a[i]].end());\n        gr_lf[i] = gr_rg[i] = less_lf[i] = less_rg[i] = 0;\n        ind[a[i]] = 0;\n    }\n}\n \nint main() {\n    for(int i = 1; i < A; i++) {\n        for(int j = i; j < A; j += i)\n            divs[j].push_back(i);\n    }\n \n    int t;\n    cin >> t;\n \n    while(t--)\n        solve();\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "divide and conquer",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1730",
    "index": "F",
    "title": "Almost Sorted",
    "statement": "You are given a permutation $p$ of length $n$ and a positive integer $k$. Consider a permutation $q$ of length $n$ such that for any integers $i$ and $j$, where $1 \\le i < j \\le n$, we have $$p_{q_i} \\le p_{q_j} + k.$$\n\nFind the minimum possible number of inversions in a permutation $q$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nAn inversion in a permutation $a$ is a pair of indices $i$ and $j$ ($1 \\le i, j \\le n$) such that $i < j$, but $a_i > a_j$.",
    "tutorial": "Let's build a permutation $q$ from left to right. If the current prefix contains the number $i$, let's call the element $p_i$ used, otherwise - unused. Consider the smallest unused element $mn = p_j$. All elements greater than $mn + k$ must also be unused, and all elements less than $mn$ must be used. Then the current state can be described by the number $mn$ and the mask, $i$-th bit of which indicates whether the element with the value $mn + i$ is used. Let's solve the problem by dynamic programming: $dp[mn][mask]$ is the minimum number of inversions. We can continue building a permutation by adding the number $i$ such that $mn \\le p_i \\le mn + k$ and $p_i$ hasn't been used yet. New inversions can be divided into two types: those formed with indices of elements less than $mn$ (they can be counted using Fenwick tree) and those formed with indices of elements not less than $mn$ (but their number is not more than $k$). The time complexity is $O(n \\cdot 2^k \\cdot k \\cdot (k + \\log n))$.",
    "code": "#include <bits/stdc++.h>\n//#define int long long\n#define ld long double\n#define x first\n#define y second\n#define pb push_back\n \nusing namespace std;\nconst int N = 5005;\nconst int K = 8;\n \nint n, k, p[N], pos[N], dp[N][1 << K], t[N];\n \nint sum(int r)\n{\n    int ans = 0;\n \n    for(; r >= 0; r = (r & r + 1) - 1)\n        ans += t[r];\n \n    return ans;\n}\n \nvoid inc(int i, int d)\n{\n    for(; i < N; i |= i + 1)\n        t[i] += d;\n}\n \nint inv(int mn, int mask, int x)\n{\n    int ans = 0;\n \n    for(int i = 0; i < k; i++)\n        if((mask & (1 << i)) && pos[x] < pos[mn + 1 + i])\n            ans++;\n \n//    for(int i = 0; i < mn; i++)\n//        if(pos[x] < pos[i])\n//            ans++;\n \n    ans += sum(N - 1) - sum(pos[x]);\n \n    return ans;\n}\n \nint32_t main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n \n    cin >> n >> k;\n \n    for(int i = 0; i < n; i++)\n    {\n        cin >> p[i];\n        p[i]--;\n \n        pos[p[i]] = i;\n    }\n \n    for(int mn = 0; mn <= n; mn++)\n        for(int mask = 0; mask < (1 << k); mask++)\n            dp[mn][mask] = 1e9;\n \n    dp[0][0] = 0;\n \n    for(int mn = 0; mn < n; mn++)\n    {\n        for(int mask = 0; mask < (1 << min(k, n - mn - 1)); mask++)\n        {\n            for(int i = 0; i < min(k, n - mn - 1); i++)\n                if((mask & (1 << i)) == 0)\n                    dp[mn][mask + (1 << i)] = min(dp[mn][mask + (1 << i)], dp[mn][mask] + inv(mn, mask, mn + 1 + i));\n \n            int mn2 = mn, mask2 = mask;\n \n            mn2++;\n \n            while(mask2 % 2)\n            {\n                mn2++;\n                mask2 /= 2;\n            }\n \n            mask2 /= 2;\n \n            dp[mn2][mask2] = min(dp[mn2][mask2], dp[mn][mask] + inv(mn, mask, mn));\n        }\n \n        inc(pos[mn], 1);\n    }\n \n \n    cout << dp[n][0];\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1731",
    "index": "A",
    "title": "Joey Takes Money",
    "statement": "Joey is low on money. His friend Chandler wants to lend Joey some money, but can't give him directly, as Joey is too proud of himself to accept it. So, in order to trick him, Chandler asks Joey to play a game.\n\nIn this game, Chandler gives Joey an array $a_1, a_2, \\dots, a_n$ ($n \\geq 2$) of positive integers ($a_i \\ge 1$).\n\nJoey can perform the following operation on the array any number of times:\n\n- Take two indices $i$ and $j$ ($1 \\le i < j \\le n)$.\n- Choose two integers $x$ and $y$ ($x, y \\ge 1$) such that $x \\cdot y = a_i \\cdot a_j$.\n- Replace $a_i$ by $x$ and $a_j$ by $y$.\n\nIn the end, Joey will get the money equal to \\textbf{the sum} of elements of the final array.\n\nFind the maximum amount of money $\\mathrm{ans}$ Joey can get \\textbf{but print} $2022 \\cdot \\mathrm{ans}$. Why multiplied by $2022$? Because we are never gonna see it again!\n\nIt is guaranteed that the product of all the elements of the array $a$ doesn't exceed $10^{12}$.",
    "tutorial": "If we take two elements $a_1$ and $a_2$ and do the operation on it as $a_1 \\cdot a_2 = x \\cdot y$, then it is easy to observe that $x + y$ will attain its maximum value when one of them is equal to $1$. So, the solution for this is $x = 1$ and $y = a_1 \\cdot a_2$. Let $n$ be the total number of elements and $P$ ($P = a_1 \\cdot a_2 \\cdot \\ldots \\cdot a_n$) be the product of all elements. Now if we do the above step for every pair of elements, then the maximum value of the sum is achieved when $a_1 = 1$, $a_2 = 1$, $\\dots$, $a_{n-1} = 1$ and $a_n = P$. In the final array, assign $P$ to $a_1$ and assign $1$ to all the remaining elements $a_2, a_3, \\dots a_n$. So, our answer is simply $P + n - 1$ multiplied by $2022$, of course. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\ntypedef long long ll;\ntypedef long double ld;\nusing namespace std;\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;\ntypedef tree<int,null_type,less<int>,rb_tree_tag,\ntree_order_statistics_node_update> indexed_set;\n#define endl '\\n'\n \nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t=1;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int a[n];\n        ll k=1;\n        for(int i=0;i<n;i++){\n            cin>>a[i];\n            k*=a[i];\n        }\n        k+=n-1;\n        k*=2022;\n        cout<<k<<endl;\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1731",
    "index": "B",
    "title": "Kill Demodogs",
    "statement": "Demodogs from the Upside-down have attacked Hawkins again. El wants to reach Mike and also kill as many Demodogs in the way as possible.\n\nHawkins can be represented as an $n \\times n$ grid. The number of Demodogs in a cell at the $i$-th row and the $j$-th column is $i \\cdot j$. El is at position $(1, 1)$ of the grid, and she has to reach $(n, n)$ where she can find Mike.\n\nThe only directions she can move are the right (from $(i, j)$ to $(i, j + 1)$) and the down (from $(i, j)$ to $(i + 1, j)$). She can't go out of the grid, as there are doors to the Upside-down at the boundaries.\n\nCalculate the maximum possible number of Demodogs $\\mathrm{ans}$ she can kill on the way, considering that she kills all Demodogs in cells she visits (including starting and finishing cells).\n\nPrint $2022 \\cdot \\mathrm{ans}$ modulo $10^9 + 7$. Modulo $10^9 + 7$ because the result can be too large and multiplied by $2022$ because we are never gonna see it again!\n\n(Note, you firstly multiply by $2022$ and \\textbf{only after} that take the remainder.)",
    "tutorial": "To kill the maximum number of demodogs, El can travel in zigzag fashion, i.e. from $(1,1)$ to $(1,2)$ to $(2,2)$ and so on. Thus the answer would be the sum of elements at $(1,1)$, $(1,2)$, $(2,2)$ $\\dots$ $(n,n)$. i.e. the answer is $$\\sum_{i = 1}^n{i \\cdot i} + \\sum_{i = 1}^{n-1}{i (i + 1)} = \\frac{n(n + 1)(4n - 1)}{6}$$. And the answer you need to print is $$2022 \\frac{n(n + 1)(4n - 1)}{6} = 337 \\cdot n(n + 1)(4n - 1) \\pmod{10^9 + 7}$$ Proof: Let $kills_{i,j}$ be the maximum number of kills of all possible paths from $(1,1)$ to $(i,j)$. $kills_{n-1,n-1} \\geq kills_{i,n - 1}$ + number of demodogs from $(i + 1,n - 1)$ to $(n - 1,n - 1)$ $( \\forall i \\hspace{1.5mm} \\in \\hspace{1.5mm} [1, n - 2])$. $$kills_{n-1,n-1} \\geq kills_{i,n - 1} + \\sum_{j = i + 1}^{n - 1}{j \\cdot (n - 1)}$$ $$kills_{n-1,n-1} \\geq kills_{i,n - 1} + \\frac{(n - 1 - i)((i + 1)(n - 1) + (n - 2 - i)(n - 1))}{2} \\text{ (sum of A.P.)}$$ $$kills_{n-1,n-1} \\geq kills_{i,n - 1} + \\frac{(n - 1 - i)(n - 1)^2}{2} \\text{ (1)}$$ Let $killsZ$ be the number of kills if El travels in zigzag fashion, i.e. she goes to $(n,n)$ after passing through $(n - 1,n - 1)$: $$killsZ_{n,n} = kills_{n - 1,n - 1} + n(n - 1) + n \\cdot n$$ Let $killsNZ$ be the maximum number of kills If El goes to $(n,n)$ after passing through $(i,n)$ for some $i$ in range of $[1 \\dots n - 1]$, i.e. El goes from $(1,1)$ to $(i,n - 1)$ to $(i,n)$ to $(n,n)$: $$killsNZ_{n,n} = kills_{i,n - 1} + \\text{no of demigods from } (i,n)\\text{ to }(n,n)$$ $$killsNZ_{n,n} = kills_{i,n - 1} + \\sum_{j = i}^{n}{j \\cdot n}$$ $$killsNZ_{n,n} = kills_{i,n - 1} + \\frac{(n + 1 - i)(n + i)n}{2}$$ $$killsZ_{n,n} - killsNZ_{n,n} = kills_{n - 1,n - 1} + n(n - 1) + n \\cdot n - kills_{i,n - 1} - \\frac{(n + 1 - i)(n + i)n}{2} \\text{ from $(1)$}$$ $$killsZ_{n,n} - killsNZ_{n,n} \\geq kills_{i,n - 1} + \\frac{(n - 1 - i)(n - 1)^2}{2} + n(n - 1) + n \\cdot n - kills_{i,n - 1} - \\frac{(n + 1 - i)(n + i)n}{2}$$ $$killsZ_{n,n} - killsNZ_{n,n} \\geq \\frac{2 n^2 - 3 n - n \\cdot i - i - 1}{2}$$ $$killsZ_{n,n} - killsNZ_{n,n} \\geq 0$$ since $2n^2 - 3 n - n \\cdot i - i - 1 \\geq 0$ for all $i \\in \\hspace{1.5mm} [1, n - 2]$. In other words, $killsZ_{n,n} \\geq killsNZ_{n,n}$ Therefore zigzag path guarantees maximum number of demodog kills. Now, the last thing was taking the modulus. Modulus should always be taken after every multiply operation to avoid the overflow. You can refer to modular arithmetic for more details. And the main reason we told you to multiply the answer by $2022$ is that we needed to divide it by $6$. For division, we have to take inverse modulo in modular arithmetic. So, in order to avoid that, we gave you a multiple of $6$, which is $2022$.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nconst int n1=1e9+7;\nusing namespace std;\nint solve()\n{\n    ll n;\n    cin>>n;\n    ll ans=((((n*(n+1))%n1)*(4*n-1))%n1*337)%n1;\n    cout<<ans<<endl;\n}\nint main()\n{\n   \n    int t;\n    cin>>t;\n    while(t--)\n    {\n        solve();\n    }\n \n \n}\n ",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1731",
    "index": "C",
    "title": "Even Subarrays",
    "statement": "You are given an integer array $a_1, a_2, \\dots, a_n$ ($1 \\le a_i \\le n$).\n\nFind the number of subarrays of $a$ whose $\\operatorname{XOR}$ has an even number of divisors. In other words, find all pairs of indices $(i, j)$ ($i \\le j$) such that $a_i \\oplus a_{i + 1} \\oplus \\dots \\oplus a_j$ has an even number of divisors.\n\nFor example, numbers $2$, $3$, $5$ or $6$ have an even number of divisors, while $1$ and $4$ — odd. Consider that $0$ has an odd number of divisors in this task.\n\nHere $\\operatorname{XOR}$ (or $\\oplus$) denotes the bitwise XOR operation.\n\n\\sout{Print the number of subarrays but multiplied by 2022...} Okay, let's stop. Just print the actual answer.",
    "tutorial": "Let's calculate the number of subarrays whose $\\operatorname{XOR}$ sum has an odd number of divisors and subtract them from total no of subarrays. Note: A number has an odd number of divisors only if it is a perfect square. So we have to calculate number of subarray having $\\operatorname{XOR}$ sum a perfect square. For the given constraints for elements in the array, the maximum possible $\\operatorname{XOR}$ sum of any subarray will be less than $2n$, so the number of possible elements with odd divisors $\\leq \\sqrt{2n}$. Number of subarrays with a given $\\operatorname{XOR}$ sum can be calculated in $O(n)$. Therefore, calculate the same for each perfect square less than $2n$ and add all these to get the number of subarrays whose $\\operatorname{XOR}$ sum has an odd number of divisors. Subtract from total number of subarrays to get the required answer. Time complexity : $O(n \\cdot \\sqrt{n})$.",
    "code": "sq_list=[]\np=int(0)\nwhile p*p<=400000:\n    sq_list.append(p*p)\n    p+=1\nfor t in range(int(input())):\n    n=int(input())\n    a=list(map(int,input().split()))\n    val=int(2*n)\n    z=int(0)\n    m=[z]*val\n    cnt=int(0)\n    curr=int(0)\n    m[curr]+=1\n    j=0\n \n    while j<n:\n        curr^=a[j]\n        for i in sq_list:\n            if i>=val:\n                break\n            if curr^i<val:\n                cnt+=m[curr^i]\n            \n        m[curr]+=1\n        j+=1\n    ans=((n*(n+1))//2)\n    ans=ans-cnt\n    print(ans)\n ",
    "tags": [
      "bitmasks",
      "brute force",
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1731",
    "index": "D",
    "title": "Valiant's New Map",
    "statement": "Game studio \"DbZ Games\" wants to introduce another map in their popular game \"Valiant\". This time, the map named \"Panvel\" will be based on the city of Mumbai.\n\nMumbai can be represented as $n \\times m$ cellular grid. Each cell $(i, j)$ ($1 \\le i \\le n$; $1 \\le j \\le m$) of the grid is occupied by a cuboid building of height $a_{i,j}$.\n\nThis time, DbZ Games want to make a map that has perfect vertical gameplay. That's why they want to choose an $l \\times l$ square inside Mumbai, such that each building inside the square has a height of at least $l$.\n\nCan you help DbZ Games find such a square of the maximum possible size $l$?",
    "tutorial": "The basic brute force solution for this problem was to just iterate through all the values of sides possible. Note that the value of sides can range only from $1$ to $1000$ as product of $n \\cdot m$ can't exceed $10^6$, so there can't be a cube having all sides greater than $1000$. After setting side length (let's say $s$) we look into all possible submatrices of dimensions $s \\times s$ and see if we can form a cube from any one of those. This could only be possible if there exists a submatrix with its minimum $\\ge s$. Now, we need to do all these operations efficiently, looking at the constraints. The main thing that we need to do is Binary search on the answer. As obviously, it is possible to make a cube with a smaller side if it is possible to make the one with the current side length. Now from here, we have two different approaches - Sparse Table - For a particular side $s$, check for all submatrices of size $s \\times s$, if their minimum is greater than equal to $s$. If you find any such submatrix, then this value of side is possible. A minimum can be calculated in $O(1)$ using sparse tree. You might have tried using segment tree, which takes $\\log m \\cdot \\log n$ time per query. But it may not to pass with these constraints. So, the time complexity to solve this problem is $O(n \\cdot m \\cdot \\log{(\\min{(n, m)})}$). It would pass these constraints. Another $O(n \\cdot m \\cdot \\min{(n, m)}$) solution where you don't use binary search is also there but would fail with these constraints. The segment tree solution takes $O(n \\cdot m \\cdot \\log{n} \\cdot \\log{m} \\cdot \\log{(\\min{(n, m)})}$) . So, only sparse tree can be used. Prefix Sum - This is a much simpler solution. First, we create another $n\\times m$ matrix, let's say $B$. Now, for a particular side length $s$, we take all the indices where the building heights are greater than equal to $s$ and set the elements of $B$ at those indices to $1$. Other elements are set to $0$. Now we precalculate the prefix sum for this matrix. Then for each index $(i, j)$ of the matrix $B$, we check if the square starting from that index has a prefix sum equal to $s^2$. If anyone of it does, then this side length for the cube is possible. Time Complexity is again $O(n \\cdot m \\cdot \\log{(\\min{(n, m)})})$.",
    "code": "#include <bits/stdc++.h>\ntypedef long long ll;\ntypedef long double ld;\nusing namespace std;\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;\ntypedef tree<int,null_type,less<int>,rb_tree_tag,\ntree_order_statistics_node_update> indexed_set;\n#define endl '\\n'\n \nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t;\n    cin>>t;\n    while(t--){\n        int n,m;\n        cin>>n>>m;\n        int st[n][m][10];\n        int a[n][m];\n        for(int i=0;i<n;i++){\n            for(int j=0;j<m;j++){\n                cin>>a[i][j];\n                st[i][j][0]=a[i][j];\n            }\n        }\n        for(int k=1;k<=log2(min(n,m));k++){\n            for(int i=0;i+(1<<k)<=n;i++){\n                for(int j=0;j+(1<<k)<=m;j++){\n                    st[i][j][k]=min(min(st[i][j][k-1],st[i+(1<<(k-1))][j][k-1]),min(st[i][j+(1<<(k-1))][k-1],st[i+(1<<(k-1))][j+(1<<(k-1))][k-1]));\n                }\n            }\n        }\n        int l=1;\n        int r=min(n,m);\n        while(l<r){\n            int x=(l+r+1)/2;\n            int z=0;\n            int p=log2(x);\n            for(int i=0;i+x<=n;i++){\n                for(int j=0;j+x<=m;j++){\n                    if(min(min(st[i][j][p],st[i+x-(1<<p)][j+x-(1<<p)][p]),min(st[i][j+x-(1<<p)][p],st[i+x-(1<<p)][j][p]))>=x){\n                        z=1;\n                    }\n                }\n            }\n            if(z){\n                l=x;\n            }\n            else{\n                r=x-1;\n            }\n        }\n        cout<<l<<endl;\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1731",
    "index": "E",
    "title": "Graph Cost",
    "statement": "You are given an initially empty undirected graph with $n$ nodes, numbered from $1$ to $n$ (i. e. $n$ nodes and $0$ edges). You want to add $m$ edges to the graph, so the graph won't contain any self-loop or multiple edges.\n\nIf an edge connecting two nodes $u$ and $v$ is added, its weight must be equal to the greatest common divisor of $u$ and $v$, i. e. $\\gcd(u, v)$.\n\nIn order to add edges to the graph, you can repeat the following process any number of times (possibly zero):\n\n- choose an integer $k \\ge 1$;\n- add exactly $k$ edges to the graph, each having a weight equal to $k + 1$. Adding these $k$ edges costs $k + 1$ in total.\n\nNote that you can't create self-loops or multiple edges. Also, if you can't add $k$ edges of weight $k + 1$, you can't choose such $k$.For example, if you can add $5$ more edges to the graph of weight $6$, you may add them, and it will cost $6$ for the whole pack of $5$ edges. But if you can only add $4$ edges of weight $6$ to the graph, you can't perform this operation for $k = 5$.\n\nGiven two integers $n$ and $m$, find the minimum total cost to form a graph of $n$ vertices and exactly $m$ edges using the operation above. If such a graph can't be constructed, output $-1$.\n\nNote that the final graph may consist of several connected components.",
    "tutorial": "In each step, adding $e$ edges to the graph with weights $e + 1$ costs one more than the number of edges added. So, the total cost of adding $m$ edges in $s$ steps will be $m + s$. Since the number of edges is given, i. e. fixed, to find the minimum cost, we need to minimize the number of steps. Firstly, let's calculate the number of pairs $(x, y)$ where $1 \\le x < y \\le n$ with $\\gcd(x, y) = k$ for each $k \\in [1..n]$ in $O(n \\log n)$ time. It can be solved in a standard way using the Möbius function $\\mu(x)$ or using Dynamic Programming, where $dp[k]$ is the required number that can be calculated as: $ dp[k] = \\frac{1}{2} \\left\\lfloor \\frac{n}{k} \\right\\rfloor ( \\left\\lfloor \\frac{n}{k} \\right\\rfloor - 1) - dp[2k] - dp[3k] - \\dots - dp[\\left\\lfloor \\frac{n}{k} \\right\\rfloor k]$ Knowing all $dp[k]$ we can calculate the maximum number of steps $s[k]$ we can perform using edges of weight $k$. And $s[k] = \\left\\lfloor \\frac{dp[k]}{k - 1} \\right\\rfloor$. Note that array $s[k]$ is non-increasing ($s[k] \\ge s[k + 1]$) and if we have at least one pack of size $x$ then we have at least one pack of each size $y$ where $1 \\le y < x$. So, our task is an \"extension\" of the task where you need to take a subset of $1, 2, \\dots, n$ of minimum size with sum equal to $m$ and can be solved with the same greedy strategy. Let's just take packs greedily, starting from weight $n$ down to weight $2$. We'll take packs as many packs as possible. For a fixed weight $k$ we can calculate the maximum number of packs we can take as $\\min(s[k], \\frac{m'}{k - 1})$. If $m$ edges can't be constructed, then we return $-1$. Otherwise, we return $m + s$ where $s$ is the total number of packs. Time Complexity: $O(n \\log n)$",
    "code": "#include <bits/stdc++.h>\ntypedef long long ll;\nusing namespace std;\n#define endl '\\n'\n \nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t;\n    cin>>t;\n    while(t--){\n        ll n,m;\n        cin>>n>>m;\n        vector<ll> dp(n+1);\n        for(ll i=n;i>=1;i--){\n            dp[i]=(n/i)*((n/i)-1)/2;\n            for(ll j=2*i;j<=n;j+=i){\n                dp[i]-=dp[j];\n            }\n        }\n        ll x=0;\n        for(ll i=n;i>=2;i--){\n            if(m<i-1){\n                continue;\n            }\n            ll k=m/(i-1);\n            ll l=dp[i]/(i-1);\n            m-=min(k,l)*(i-1);\n            x+=min(k,l)*i;\n            if(m==0){\n                break;\n            }\n        }\n        if(m){\n            cout<<-1<<endl;\n        }\n        else{\n            cout<<x<<endl;\n        }\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1731",
    "index": "F",
    "title": "Function Sum",
    "statement": "Suppose you have an integer array $a_1, a_2, \\dots, a_n$.\n\nLet $\\operatorname{lsl}(i)$ be the number of indices $j$ ($1 \\le j < i$) such that $a_j < a_i$.\n\nAnalogically, let $\\operatorname{grr}(i)$ be the number of indices $j$ ($i < j \\le n$) such that $a_j > a_i$.\n\nLet's name position $i$ good in the array $a$ if $\\operatorname{lsl}(i) < \\operatorname{grr}(i)$.\n\nFinally, let's define a function $f$ on array $a$ $f(a)$ as the \\textbf{sum} of all $a_i$ such that $i$ is good in $a$.\n\nGiven two integers $n$ and $k$, find the sum of $f(a)$ over all arrays $a$ of size $n$ such that $1 \\leq a_i \\leq k$ for all $1 \\leq i \\leq n$ modulo $998\\,244\\,353$.",
    "tutorial": "Let's try to write a brute force solution of this using combinatorics. Let's say that $a[i]=t$ now we will try to see that in how many permutations this is contributing towards the answer. Using combinatorics, it can be calculated as $$F(t) = t \\cdot {\\sum_{i=1}^n \\sum_{x=0}^{i-1} \\sum_{y = x+1}^{n-i} \\left( \\binom{i-1}{x} (t-1)^{x} (K+1-t)^{i-1-x} \\cdot \\binom{n-i}{y} (K-t)^{y} \\cdot t^{n-i-y} \\right)} $$. Here $x$ represents $\\operatorname{lsl}(i)$ and y represents $\\operatorname{grr}(i)$. Let $$P(u) = {\\sum_{t=1}^u F(t)} $$ be a polynomial whose degree will be $\\le n+2$. And now our answer will be $P(k)$. Now, we can evaluate this polynomial for smaller values (by brute force) and will use the technique of polynomial interpolation to find the answer.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\n#define pb push_back\n#define pii pair<int,int>\n#define pll pair<ll,ll>\n#define pcc pair<char,char>\n#define vi vector <int>\n#define vl vector <ll>\nusing namespace std;\nll powmod(ll base,ll exponent,ll mod){\n\tll ans=1;\n\tif(base<0) base+=mod;\n\twhile(exponent){\n\t\tif(exponent&1)ans=(ans*base)%mod;\n\t\tbase=(base*base)%mod;\n\t\texponent/=2;\n\t}\n\treturn ans;\n}\nconst int N = 201;\nconst int mod = 998244353;\nint fact[N];\nint invfact[N];\nint nCr(int n,int r){\n\tint ans = fact[n];\n\tans = (1ll*ans*invfact[r])%mod;\n\tans = (1ll*ans*invfact[n-r])%mod;\n\treturn ans;\n}\nint interpolate(vi &y,int r,int n){\n\tint ans=0,prod=1,temp;\n\tfor(int i = 1; i <= r; i++){\n\t\tprod=(1ll*prod*(n-i))%mod;\n\t}\n\tfor(int i = 0; i < r; i++){\n\t\ttemp=(1ll*prod*powmod(n-i-1,mod-2,mod))%mod;\n\t\ttemp=(1ll*temp*y[i])%mod;\n\t\ttemp=(1ll*temp*invfact[i])%mod;\n\t\ttemp=(1ll*temp*invfact[r-i-1])%mod;\n\t\tif((r-i)%2==0) temp=mod-temp;\n\t\tans+=temp;ans%=mod;\n\t}\n\treturn ans;\n}\nvoid brute_force(int n,int k){\n\tvi values_of_polynomial(k);\n\tfor(int i = 1; i <= n; i++){\n\t\tfor(int x = 0; x < i; x++){\n\t\t\tfor(int y = x+1; y <= n-i; y++){\n\t\t\t\tfor(int val = 1; val <= k; val++){\n\t\t\t\t\tll calculation = (1ll * nCr(i-1,x) * powmod(val-1,x,mod))%mod;\n\t\t\t\t\tcalculation *= powmod(k+1-val,i-1-x,mod);\n\t\t\t\t\tcalculation %= mod;\n\t\t\t\t\tcalculation *= (1ll * nCr(n-i,y) * powmod(k-val,y,mod))%mod;\n\t\t\t\t\tcalculation %= mod;\n\t\t\t\t\tcalculation *= powmod(val,n-i-y,mod);\n\t\t\t\t\tcalculation %= mod;\n\t\t\t\t\tcalculation *= val;\n\t\t\t\t\tcalculation %= mod;\n\t\t\t\t\tvalues_of_polynomial[val-1] += calculation;\n\t\t\t\t\tvalues_of_polynomial[val-1] %= mod;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor(int i = 1; i < k; i++){\n\t\tvalues_of_polynomial[i] += values_of_polynomial[i-1];\n\t\tvalues_of_polynomial[i] %= mod;\n\t}\n\tcout << values_of_polynomial[k-1] << \"\\n\";\n}\nint main(){\n\tfact[0]=1;\n\tinvfact[0]=1;\n\tfor(int i = 1; i < N; i++){\n\t\tfact[i] = (1ll*i*fact[i-1])%mod;\n\t\tinvfact[i] = powmod(fact[i],mod-2,mod);\n\t}\n\tint t,n,k;\n\tt=1;\n\twhile(t--){\n\t\tcin >> n >> k;\n\t\tvi values_of_polynomial(n+3,0);\n\t\tfor(int i = 1; i <= n; i++){\n\t\t\tfor(int x = 0; x < i; x++){\n\t\t\t\tfor(int y = x+1; y <= n-i; y++){\n\t\t\t\t\tfor(int val = 1; val <= n+3; val++){\n\t\t\t\t\t\tll calculation = (1ll * nCr(i-1,x) * powmod(val-1,x,mod))%mod;\n\t\t\t\t\t\tcalculation *= powmod(k+1-val,i-1-x,mod);\n\t\t\t\t\t\tcalculation %= mod;\n\t\t\t\t\t\tcalculation *= (1ll * nCr(n-i,y) * powmod(k-val,y,mod))%mod;\n\t\t\t\t\t\tcalculation %= mod;\n\t\t\t\t\t\tcalculation *= powmod(val,n-i-y,mod);\n\t\t\t\t\t\tcalculation %= mod;\n\t\t\t\t\t\tcalculation *= val;\n\t\t\t\t\t\tcalculation %= mod;\n\t\t\t\t\t\tvalues_of_polynomial[val-1] += calculation;\n\t\t\t\t\t\tvalues_of_polynomial[val-1] %= mod;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(int i = 1; i < n+3; i++){\n\t\t\tvalues_of_polynomial[i] += values_of_polynomial[i-1];\n\t\t\tvalues_of_polynomial[i] %= mod;\n\t\t}\n\t\tif(k <= n+3) cout << values_of_polynomial[k-1] << \"\\n\";\n\t\telse cout << interpolate(values_of_polynomial,n+3,k) << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1732",
    "index": "A",
    "title": "Bestie",
    "statement": "You are given an array $a$ consisting of $n$ integers $a_1, a_2, \\ldots, a_n$. Friends asked you to make the greatest common divisor (GCD) of all numbers in the array equal to $1$. In one operation, you can do the following:\n\n- Select an arbitrary index in the array $1 \\leq i \\leq n$;\n- Make $a_i = \\gcd(a_i, i)$, where $\\gcd(x, y)$ denotes the GCD of integers $x$ and $y$. The cost of such an operation is $n - i + 1$.\n\nYou need to find the minimum total cost of operations we need to perform so that the GCD of the all array numbers becomes equal to $1$.",
    "tutorial": "Let's make an important observation: $\\gcd(n - 1, n) = 1$ for any value of $n$. Moreover, choosing $i = n - 1$ and $i = n$ are the cheapest operations. From this we can conclude that the answer is $\\leq 3$. Let $g$ be the $\\gcd$ of all numbers in the array. Then we have the following cases: If $g = 1$, then the operation can be omitted and the answer is $0$, Otherwise, let's try the cheapest operation $i = n$. If $\\gcd(g, n) = 1$, then the answer is $1$. Otherwise, let's try the next cheapest operation, ie $i = n - 1$. If $\\gcd(g, n - 1) = 1$, then the answer is $2$. Otherwise, the answer is $3$, since $\\gcd(g, n - 1, n) = 1$.",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1732",
    "index": "B",
    "title": "Ugu",
    "statement": "A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $s_1 s_2 \\ldots s_n$. It is necessary to make this string non-decreasing in the least number of operations. In other words, each character should be not less than the previous. In one operation, you can do the following:\n\n- Select an arbitrary index $1 \\leq i \\leq n$ in the string;\n- For all $j \\geq i$, change the value in the $j$-th position to the opposite, that is, if $s_j = 1$, then make $s_j = 0$, and vice versa.\n\nWhat is the minimum number of operations needed to make the string non-decreasing?",
    "tutorial": "Let's mentally imagine the following array of length $n - 1$: $a_i = 0$ if $s_i = s_{i+1}$, and $1$ otherwise. Note that if we apply the operation to the index $i$, then all the values of the array $a$ do not change, except for $a_{i - 1}$. Let's look at this in more detail: For $i \\leq j$, note that the $j$th and $(j+1)$th elements invert their value, so $a_j$ does not change. For $j < i - 1$, note that the $j$-th and $(j+1)$-th elements do not change their value, so $a_j$ does not change. For $j = i - 1$, note that the $j$th element does not change its value, but the $(j+1)$th element does, so $a_j$ will change its value. If we look at the array $a$ for a sorted binary string, we can see that this array does not contain more than one unit (you either have a string consisting of only zeros or only ones, or it looks like this - $0000\\ldots01\\ldots11111$ ). Let $s$ be the number of ones in the original array $a$. We have now shown that the answer is $\\geq \\max(s - 1, 0)$. In fact, if the string starts with $0$, then the answer is $\\max(s - 1, 0)$, otherwise it is $s$. Let's prove that if the string starts with $0$, then we can get the answer $\\max(s - 1, 0)$ (the case with $1$ will be similar). Let's show a constructive proof using a small example $s = 0001110010$: Choose $i = 3$, then $s = 0000001101$, Choose $i = 7$, then $s = 0000000010$, Choose $i = 9$, then $s = 0000000001$.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1732",
    "index": "C1",
    "title": "Sheikh (Easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is that in this version $q = 1$.}\n\nYou are given an array of integers $a_1, a_2, \\ldots, a_n$.\n\nThe cost of a subsegment of the array $[l, r]$, $1 \\leq l \\leq r \\leq n$, is the value $f(l, r) = \\operatorname{sum}(l, r) - \\operatorname{xor}(l, r)$, where $\\operatorname{sum}(l, r) = a_l + a_{l+1} + \\ldots + a_r$, and $\\operatorname{xor}(l, r) = a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_r$ ($\\oplus$ stands for bitwise XOR).\n\nYou will have $q = 1$ query. Each query is given by a pair of numbers $L_i$, $R_i$, where $1 \\leq L_i \\leq R_i \\leq n$. You need to find the subsegment $[l, r]$, $L_i \\leq l \\leq r \\leq R_i$, with maximum value $f(l, r)$. If there are several answers, then among them you need to find a subsegment with the minimum length, that is, the minimum value of $r - l + 1$.",
    "tutorial": "Note that $f(l, r) \\leq f(l, r + 1)$. To prove this fact, let's see how the sum and xor change when the element $x$ is added. The sum will increase by $x$, but $xor$ cannot increase by more than $x$. Then it was possible to use two pointers or binary search to solve the problem. If you solve the problem in the second way, then you iterate over the right boundary of the answer and look for the optimal left boundary for it by binary search. You will need $O(1)$ to find the sum on the segment and xor on the segment. To do this, you can use prefix sums and prefix xor.",
    "tags": [
      "binary search",
      "bitmasks",
      "greedy",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1732",
    "index": "C2",
    "title": "Sheikh (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $q = n$.}\n\nYou are given an array of integers $a_1, a_2, \\ldots, a_n$.\n\nThe cost of a subsegment of the array $[l, r]$, $1 \\leq l \\leq r \\leq n$, is the value $f(l, r) = \\operatorname{sum}(l, r) - \\operatorname{xor}(l, r)$, where $\\operatorname{sum}(l, r) = a_l + a_{l+1} + \\ldots + a_r$, and $\\operatorname{xor}(l, r) = a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_r$ ($\\oplus$ stands for bitwise XOR).\n\nYou will have $q$ queries. Each query is given by a pair of numbers $L_i$, $R_i$, where $1 \\leq L_i \\leq R_i \\leq n$. You need to find the subsegment $[l, r]$, $L_i \\leq l \\leq r \\leq R_i$, with maximum value $f(l, r)$. If there are several answers, then among them you need to find a subsegment with the minimum length, that is, the minimum value of $r - l + 1$.",
    "tutorial": "Note that $f(l, r) \\leq f(l, r + 1)$. To prove this fact, let's see how the sum and xor change when the element $x$ is added. The sum will increase by $x$, but $xor$ cannot increase by more than $x$. From this we obtain that the maximum value of $f$ is reached on the entire subsegment. Next, let's see in which case $xor$ changes exactly by $x$, because if it changes by a smaller value, then $f(l, r)$ will be strictly less than $f(l, r + 1)$. The value of $xor$ will change exactly by $x$ if all 1 bits of $x$ were zeros in the current $xor$. In fact, this means that if we consider the first $\\log A + 1$ non-zero element, then at least one of the bits will occur twice, and thus the value of the function will become smaller. Let's put all these facts together: we can remove at most $\\log A + 1= 30 + 1= 31$ non-zero element from the beginning and end of the subsegment. Then let's just iterate over how many non-zero elements we remove on the prefix and suffix (their positions can be found using binary search) and using prefix sums and $xor$-s, calculate the value on this subsegment.",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1732",
    "index": "D1",
    "title": "Balance (Easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is that in this version there are no \"remove\" queries.}\n\nInitially you have a set containing one element — $0$. You need to handle $q$ queries of the following types:\n\n- + $x$ — add the integer $x$ to the set. It is guaranteed that this integer is not contained in the set;\n- ? $k$ — find the $k\\text{-mex}$ of the set.\n\nIn our problem, we define the $k\\text{-mex}$ of a set of integers as the smallest non-negative integer $x$ that is divisible by $k$ and which is not contained in the set.",
    "tutorial": "Let's look at a stupid solution and try to improve it. In a stupid solution, we can simply add to the set, and when answering a query, iterate over the numbers ${0, k, 2k, 3k, \\ldots}$ and so on until we find the answer. This solution will take a long time if the answer is $c \\cdot k$, where $c$ is large. We will improve the solution. If a request comes to us for the first time for a given $k$, then we calculate the answer for it greedily and remember it. In the future, we will no longer check with $0$ whether there is a number in the set, but with the previous answer. Let's count for each value $x$ how many times we can check for its presence in the set. First, we do this for $k$ such that $x$ is divisible by $k$. Secondly, the set must already contain elements ${0, k, 2k, \\ldots, x - k}$, that is, $\\frac{x}{k}$ numbers. Note that if $k$ is not one of the largest divisors of $x$, then $\\frac{x}{k}$ becomes greater than $q$. Therefore, this solution will work quite quickly.",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1732",
    "index": "D2",
    "title": "Balance (Hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version there are remove queries.}\n\nInitially you have a set containing one element — $0$. You need to handle $q$ queries of the following types:\n\n- + $x$ — add the integer $x$ to the set. It is guaranteed that this integer is not contained in the set;\n- - $x$ — remove the integer $x$ from the set. It is guaranteed that this integer is contained in the set;\n- ? $k$ — find the $k\\text{-mex}$ of the set.\n\nIn our problem, we define the $k\\text{-mex}$ of a set of integers as the smallest non-negative integer $x$ that is divisible by $k$ and which is not contained in the set.",
    "tutorial": "Let's look at a stupid solution and try to improve it. In a stupid solution, we can simply add and remove elements from the set, and when answering a query, iterate over the numbers ${0, k, 2k, 3k, \\ldots}$ and so on until we find the answer. This solution will take a long time if the answer is $c \\cdot k$, where $c$ is large. We will improve the solution, first consider the solution of the problem without the removal operation. If a request comes to us for the first time for a given $k$, then we calculate the answer for it greedily and remember it. In the future, we will no longer check with $0$ whether there is a number in the set, but with the previous answer. Now consider a variant of the problem with the delete operation. Let's set for a fixed $k$ to store all the numbers that we have removed and they are $\\leq$ than the maximum answer found for this $k$. Then let's see what happens during the search for an answer operation. If set for a given $k$ is not empty, then the answer will be the minimum element from the set, otherwise we will try to improve the current maximum answer for this $k$ (that is, if it was equal to $c \\cdot k$, then we will check $c \\cdot k, (c + 1) \\cdot k, \\ldots$). It remains to figure out how we can recalculate these set in the case of an add/remove operation. Let's actually just remember for each value in which set it participates and we will update all of them. Let's calculate the running time. Let's understand how many sets a given value $x$ can participate in. First, it lies in sets where $x$ is divisible by $k$. Second, if $x$ is in the set for the number $k$, then at least $\\frac{x}{k}$ numbers have already been added. That is, if $x$ lies in $t$ sets and among these $k$ there are the largest divisors of $x$, then we should already have added approximately $\\sum\\limits_{k_i=1}^t \\frac{x }{k_i}$, where $k_i$ is the $i$-th largest divisor of $x$. Since we have $q$ queries in total, the given value $x$ may not lie in a large number of sets.",
    "tags": [
      "brute force",
      "data structures",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1732",
    "index": "E",
    "title": "Location",
    "statement": "You are given two arrays of integers $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_n$. You need to handle $q$ queries of the following two types:\n\n- $1$ $l$ $r$ $x$: assign $a_i := x$ for all $l \\leq i \\leq r$;\n- $2$ $l$ $r$: find the minimum value of the following expression among all $l \\leq i \\leq r$: $$\\frac{\\operatorname{lcm}(a_i, b_i)}{\\gcd(a_i, b_i)}.$$\n\nIn this problem $\\gcd(x, y)$ denotes the greatest common divisor of $x$ and $y$, and $\\operatorname{lcm}(x, y)$ denotes the least common multiple of $x$ and $y$.",
    "tutorial": "Tasks of this kind, as a rule, are solved using data structures, and this one is no exception. Since the constraints in the problem are not large enough, it is logical to think in the direction of root optimizations. Let's divide the array into blocks of length $k$, we will have about $\\frac{n}{k}$ such blocks. For each block, we want to maintain a response, i.e. a minimum value of $\\frac{lcm(a_i, b_i)}{gcd(a_i, b_i)}$. Let's see what happens with the first type of operation. If the block partially intersects with the segment of the request, then it is possible to go through this block for $O(k)$ and recalculate the answer. There are no more than two such blocks, so in total we will spend $O(k)$ on this (we neglect the running time of $\\gcd$). If the block lies entirely in the segment of the request (and there can be $\\frac{n}{k}$ such blocks), then you need to somehow recalculate the response more quickly. To do this, let's precalculate the following value for each block: $answer_x$ - what will be the answer in the block if we assign the value $x$ to all numbers. Let's learn how to calculate the answer for a fixed $x$ first. To do this, let's iterate over all divisors $d$ of the number $x$ - in fact, by enumeration of this divisor, we will try to fix $\\gcd$. Then note that since we want the value to minimize the value, we need to find the minimum value of $b_i$ that is divisible by $d$. And then we make $answer_x = \\min(\\frac{b_i}{d})$ over all such $d$. Let's note that $\\gcd(b_i, x)$ may not actually be equal to $d$, but we know for sure that $\\gcd(b_i, x) \\geq d$, and since we want to minimize the value , then we do not do worse. Already now we can calculate the answer for $A \\log A$ inside the block, where $A$ is the maximum value. But you can do even better! Let's note that $answer_x = min(answer_{\\frac{x}{p}} \\cdot p)$ where $p$ is a prime divisor of $x$, and don't forget the case when $d = x$ . This follows from the fact that all divisors of the number $x$ are contained among the divisors of numbers of the form $\\frac{x}{p}$. Let's calculate the running time and find the optimal $k$. We need to find all its divisors for each number in order to quickly find out the minimum number that is divisible by the given one inside the block - we do this in $O(n \\sqrt A)$. Inside each block, our precalculation now works for $O(A \\log \\log A)$, that is, in total for all blocks $O(\\frac{n}{k} \\cdot A \\log \\log A)$. We answer the request for $O(k \\cdot \\gcd + \\frac{n}{k})$. Hence we get that it is advantageous to take $k$ approximately $\\sqrt n$ (we have all quantities of the same order, so we use $n$).",
    "tags": [
      "data structures",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1733",
    "index": "A",
    "title": "Consecutive Sum",
    "statement": "You are given an array $a$ with $n$ integers. You can perform the following operation at most $k$ times:\n\n- Choose two indices $i$ and $j$, in which $i \\,\\bmod\\, k = j \\,\\bmod\\, k$ ($1 \\le i < j \\le n$).\n- Swap $a_i$ and $a_j$.\n\nAfter performing all operations, you have to select $k$ consecutive elements, and the sum of the $k$ elements becomes your score. Find the maximum score you can get.\n\nHere $x \\bmod y$ denotes the remainder from dividing $x$ by $y$.",
    "tutorial": "$i$-th element moves only to $(i + xk)$-th position ($x$ is integer). We cannot select $a_i$ and $a_{i + xk}$ simultaneously. In other words, if we can swap $a_i$ and $a_j$, we cannot select $a_i$ and $a_j$ simultaneously. Among all elements $a_{i + xk}$ for each $i$ ($1 \\le i \\le k$), only one element is selected. For each index $i$ ($k + 1 \\le i \\le n$), there is exactly one element among $a_1$ to $a_k$, which can swap with $a_i$. If $a_i$ is greater than that element, swap them. This process perform the operation at most $n - k$ times. After performing operations, select $a_1$ to $a_k$. This is the maximum score we can get.",
    "code": "#import<bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\nlong long k, n, s, t, x, a[100005];\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tfor(cin >> t; t--;)\n\t{\n\t\tcin >> n >> k;\n\t\tfor(int i = 1; i <= n; i++)\n\t\t{\n\t\t\tcin >> x;\n\t\t\ta[i % k] = max(a[i % k], x);\n\t\t}\n\t\ts = 0;\n\t\tfor(int i = 0; i < k; i++)s += a[i];\n\t\tcout << s << endl;\n\t\tfill(a, a + k, 0);\n\t}\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1733",
    "index": "B",
    "title": "Rule of League",
    "statement": "There is a badminton championship in which $n$ players take part. The players are numbered from $1$ to $n$.\n\nThe championship proceeds as follows: player $1$ and player $2$ play a game, then the winner and player $3$ play a game, and then the winner and player $4$ play a game, and so on. So, $n-1$ games are played, and the winner of the last game becomes the champion. There are no draws in the games.\n\nYou want to find out the result of championship. Currently, you only know the following information:\n\n- Each player has either won $x$ games or $y$ games in the championship.\n\nGiven $n$, $x$, and $y$, find out if there is a result that matches this information.",
    "tutorial": "Because one of player $1$ and player $2$ win $0$ games and the other win at least $1$ game, $\\min(x, y) = 0$ and $\\max(x, y) > 0$ must be true in order to generate a valid result. There are one winner and one loser for every match. So the sum of winning count and the sum of losing count are same. The sum of winning count is a multiple of $\\max(x, y)$. Therefore, the sum of losing count is also a multiple of $\\max(x, y)$. (The sum of losing count) equals to $n - 1$. So $n - 1$ is a multiple of $\\max(x, y)$ if there is a valid result. According to hints, $\\min(x, y) = 0$ and $\\max(x, y) > 0$ and $(n - 1) \\,\\bmod\\, \\max(x, y) = 0$ holds in order to generate a valid result. If so, player $1$ and player $2$ would play first. Let's consider player $2$ wins. Then player $2$ should win $\\max(x, y)$ games, and loses to player $\\max(x, y) + 2$. Likewise, player $\\max(x, y) + 2$ wins $\\max(x, y)$ games and loses to player $2 \\cdot \\max(x, y) + 2$. Construct the remaining result in the same way.",
    "code": "#import<bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\nint k, n, t, x, y;\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tfor(cin >> t; t--;)\n\t{\n\t\tcin >> n >> x >> y;\n\t\tif(x > y)swap(x, y);\n\t\tif(x || !y || (n - 1) % y)\n\t\t{\n\t\t\tcout << -1 << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tfor(int k = 2; k <= n; k += y)\n\t\t{\n\t\t\tfor(int i = 1; i <= y; i++)cout << k << ' ';\n\t\t}\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1733",
    "index": "C",
    "title": "Parity Shuffle Sorting",
    "statement": "You are given an array $a$ with $n$ non-negative integers. You can apply the following operation on it.\n\n- Choose two indices $l$ and $r$ ($1 \\le l < r \\le n$).\n- If $a_l + a_r$ is odd, do $a_r := a_l$. If $a_l + a_r$ is even, do $a_l := a_r$.\n\nFind any sequence of at most $n$ operations that makes $a$ non-decreasing. It can be proven that it is always possible. Note that you do not have to minimize the number of operations.\n\nAn array $a_1, a_2, \\ldots, a_n$ is non-decreasing if and only if $a_1 \\le a_2 \\le \\ldots \\le a_n$.",
    "tutorial": "If all elements are equal, that array is also non-decreasing. For each operation, one element is changed. Because we have to use at most $n$ operations, an element change occurs at most $n$ times. Considering that the initial array can be decreasing, at least $n - 1$ operations can be needed in some cases. If $n = 1$, do nothing. Otherwise, select indices $1$ and $n$ to make $a_1$ equal to $a_n$ first. After that, for each element $a_i$ ($2 \\le i < n$), select indices $1$ and $i$ if $a_1 + a_i$ is odd, and select indices $i$ and $n$ otherwise. This process requires $n - 1$ operations and make all elements equal, which is also non-decreasing.",
    "code": "#import<bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\nint n, t, x, a[100005];\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tfor(cin >> t; t--;)\n\t{\n\t\tcin >> n;\n\t\tfor(int i = 1; i <= n; i++)cin >> a[i];\n \n\t\tcout << n - 1 << endl;\n\t\tif(n > 1)cout << 1 << ' ' << n << endl;\n\t\tx = (a[1] + a[n]) % 2 ? a[1] : a[n];\n\t\tfor(int i = 2; i < n; i++)\n\t\t{\n\t\t\tif((x + a[i]) % 2)cout << 1 << ' ' << i << endl;\n\t\t\telse cout << i << ' ' << n << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1733",
    "index": "D1",
    "title": "Zero-One (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. In this version, $n \\le 3000$, $x \\ge y$ holds. You can make hacks only if both versions of the problem are solved.}\n\nYou are given two binary strings $a$ and $b$, both of length $n$. You can do the following operation any number of times (possibly zero).\n\n- Select two indices $l$ and $r$ ($l < r$).\n- Change $a_l$ to $(1 - a_l)$, and $a_r$ to $(1 - a_r)$.\n- If $l + 1 = r$, the cost of the operation is $x$. Otherwise, the cost is $y$.\n\nYou have to find the minimum cost needed to make $a$ equal to $b$ or say there is no way to do so.",
    "tutorial": "Consider $c$ is another binary string, in which $c_i = a_i \\oplus b_i$. We have to make $c$ equal to $000 \\ldots 000$ using the operation. Because the operation does not change the parity of the number of $1$ in $c$, the answer is $-1$ if $c$ has odd number of $1$. If the number of $1$ in $c$ is $d$ (now assume that $d$ is even), at least $\\frac{d}{2}$ operations are needed. So total cost would be at least $\\frac{d}{2} \\times y$. One $x$-cost operation can be replaced with two $y$-cost operations. Consider another binary string $c$, in which $c_i = a_i \\oplus b_i$ ($1 \\le i \\le n$). So doing an operation means selecting two indices of $c$ and flipping them. Also, let's define $d$ is the number of $1$ in $c$. Because the parity of $d$ never changes, the answer is $-1$ if $d$ is odd. If $d$ is even, classify the cases: $[1]$ If $d = 2$ and two $1$-s are adjacent, the answer is $\\min(x, 2y)$. Because $n \\ge 5$ holds, we can always replace one $x$-cost operation with two $y$-cost operations. $[2]$ If $d = 2$ and two $1$-s are not adjacent, the answer is $y$. $[3]$ If $d \\ne 2$, select $i$-th $1$ and $(i + \\frac{d}{2})$-th $1$ each ($1 \\le i \\le \\frac{d}{2}$). This costs $\\frac{d}{2} \\times y$, and we showed the cost cannot be reduced more in hint 3.",
    "code": "#import<bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\nlong long d, n, t, x, y;\nstring a, b;\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tfor(cin >> t; t--;)\n\t{\n\t\tcin >> n >> x >> y >> a >> b;\n\t\td = 0;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\ta[i] ^= b[i];\n\t\t\td += a[i];\n\t\t}\n\t\tif(d % 2)\n\t\t{\n\t\t\tcout << -1 << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tif(d == 2)\n\t\t{\n\t\t\tint l, r;\n\t\t\tfor(l = 0; !a[l]; )l++;\n\t\t\tfor(r = n - 1; !a[r]; )r--;\n\t\t\tif(l + 1 == r)cout << min(x, 2 * y) << endl;\n\t\t\telse cout << min((r - l) * x, y) << endl;\n\t\t}\n\t\telse cout << d / 2 * y << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1733",
    "index": "D2",
    "title": "Zero-One (Hard Version)",
    "statement": "\\textbf{This is the hard version of this problem. In this version, $n \\le 5000$ holds, and this version has no restriction between $x$ and $y$. You can make hacks only if both versions of the problem are solved.}\n\nYou are given two binary strings $a$ and $b$, both of length $n$. You can do the following operation any number of times (possibly zero).\n\n- Select two indices $l$ and $r$ ($l < r$).\n- Change $a_l$ to $(1 - a_l)$, and $a_r$ to $(1 - a_r)$.\n- If $l + 1 = r$, the cost of the operation is $x$. Otherwise, the cost is $y$.\n\nYou have to find the minimum cost needed to make $a$ equal to $b$ or say there is no way to do so.",
    "tutorial": "Greedy solution used in D1 doesn't work in this version. The restriction accepts normal $O(n^2)$ solution. (Continued from D1 editorial) If $x < y$, greedy approach used in D1 doesn't work. Let's use DP. Define $z0[i][j]$ as the minimal cost when there is $j$ $1$s in first $i$ elements of $c$ and $c_i = 0$, and $z1[i][j]$ as the minimal cost when there is $j$ $1$s in first $i$ elements of $c$ and $c_i = 1$. Initially all table values are $\\infty$. First, check $c_1$. If $c_1 = 0$, set $z0[1][0]$ to $0$. Otherwise, set $z1[1][1]$ to $0$. Then, check the following elements from $c_2$ to $c_n$ in turn. $[4]$ If $c_i = 0$, $z0[i][j] = \\min(z0[i - 1][j], z1[i - 1][j]), \\\\ z1[i][j] = \\begin{cases} \\min(z0[i - 1][j] + y, z1[i - 1][j] + x), & \\text{if } j \\le 1, \\\\ \\\\ \\min(z0[i - 1][j] + y, z1[i - 1][j] + x, z0[i - 1][j - 2] + x, z1[i - 1][j - 2] + y), & \\text{if } j > 1, \\end{cases}$ $[5]$ If $c_i = 1$, $z0[i][j] = \\begin{cases} \\min(z0[i - 1][j + 1] + y, z1[i - 1][j + 1] + x), & \\text{if } j = 0, \\\\ \\min(z0[i - 1][j + 1] + y, z1[i - 1][j + 1] + x, z0[i - 1][j - 1] + x, z1[i - 1][j - 1] + y), & \\text{if } 0 < j < i, \\\\ \\min(z0[i][j], z0[i - 1][j - 1] + x, z1[i - 1][j - 1] + y), & \\text{if } j = i, \\end{cases} \\\\ z1[i][j] = \\begin{cases} \\infty, & \\text{if } j = 0, \\\\ \\min(z0[i - 1][j - 1], z1[i - 1][j - 1]), & \\text{if } j > 0, \\end{cases}$ for $0 \\le j \\le i$. The answer is $z[n][0]$.",
    "code": "#import<bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\nlong long d, n, t, x, y, z0[5004][5004], z1[5004][5004];\nstring a, b;\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tfor(cin >> t; t--;)\n\t{\n\t\tcin >> n >> x >> y >> a >> b;\n\t\td = 0;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\ta[i] ^= b[i];\n\t\t\td += a[i];\n\t\t}\n\t\tif(d % 2)\n\t\t{\n\t\t\tcout << -1 << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tif(d == 2)\n\t\t{\n\t\t\tint l, r;\n\t\t\tfor(l = 0; !a[l]; )l++;\n\t\t\tfor(r = n - 1; !a[r]; )r--;\n\t\t\tif(l + 1 == r)cout << min(x, 2 * y) << endl;\n\t\t\telse cout << min((r - l) * x, y) << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tif(!d || x >= y)\n\t\t{\n\t\t\tcout << d / 2 * y << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tfill(z0[i], z0[i] + n + 1, 1LL << 60);\n\t\t\tfill(z1[i], z1[i] + n + 1, 1LL << 60);\n\t\t}\n\t\tif(a[0] == 0)z0[0][0] = 0;\n\t\tif(a[0] == 1)z1[0][1] = 0;\n\t\tfor(int i = 1; i < n; i++)\n\t\t{\n\t\t\tif(a[i])\n\t\t\t{\n\t\t\t\tfor(int j = i + 1; j >= 0; j--)\n\t\t\t\t{\n\t\t\t\t\tif(j <= i)z0[i][j] = min(z0[i - 1][j + 1] + y, z1[i - 1][j + 1] + x);\n\t\t\t\t\tif(j)\n\t\t\t\t\t{\n\t\t\t\t\t\tz0[i][j] = min({z0[i][j], z0[i - 1][j - 1] + x, z1[i - 1][j - 1] + y});\n\t\t\t\t\t\tz1[i][j] = min(z0[i - 1][j - 1], z1[i - 1][j - 1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor(int j = i + 1; j >= 0; j--)\n\t\t\t\t{\n\t\t\t\t\tz0[i][j] = min(z0[i - 1][j], z1[i - 1][j]);\n\t\t\t\t\tz1[i][j] = min(z0[i - 1][j] + y, z1[i - 1][j] + x);\n\t\t\t\t\tif(j > 1)z1[i][j] = min({z1[i][j], z0[i - 1][j - 2] + x, z1[i - 1][j - 2] + y});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << z0[n - 1][0] << endl;\n\t}\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1733",
    "index": "E",
    "title": "Conveyor",
    "statement": "There is a conveyor with $120$ rows and $120$ columns. Each row and column is numbered from $0$ to $119$, and the cell in $i$-th row and $j$-th column is denoted as $(i, j)$. The top leftmost cell is $(0, 0)$. Each cell has a belt, and all belts are initially facing to the right.\n\nInitially, a slime ball is on the belt of $(0, 0)$, and other belts are empty. Every second, the state of the conveyor changes as follows:\n\n- All slime balls on the conveyor move one cell in the direction of the belt at the same time. If there is no cell in the moved position, the slime gets out of the conveyor, and if two slime balls move to the same cell, they merge into one.\n- All belts with slime ball in the previous second change direction at the same time: belts facing to the right become facing to the down, and vice versa.\n- A new slime ball is placed on cell $(0, 0)$.\n\nThere are $q$ queries, each being three integers $t$, $x$, and $y$. You have to find out if there is a slime at the cell $(x, y)$ after $t$ seconds from the start. Can you do it?",
    "tutorial": "Each second, slime ball moves to next diagonal. Every slime always locates in different diagonal. No two slime ball will merge forever. If $t < x + y$, the answer should be \"NO\". In the conveyor, cells with same $(i + j)$ value consists a diagonal ($i$ is row number, $j$ is column number). Let's call them $(i + j)$-th diagonal. So there are $239$ diagonals, from $0$-th to $238$-th. So, we can find every slime ball move to the next diagonal for every second. It means no two slime ball merge forever. Given $t$, $x$, $y$, cell $(x, y)$ belongs to $(x + y)$-th diagonal. If $t < x + y$, the answer is NO because there is no slime ball in $(x + y)$-th diagonal yet. If $t \\ge x + y$, $(x + y)$-th diagonal contains one slime ball, and the ball is placed on cell $(0, 0)$ after $(t - x - y)$ seconds from the start. So $(t - x - y)$ slime balls passed this diagonal before. Now, find out which cell contains slime ball among the diagonal. To do this, we use following method: simulate with $(t - x - y)$ slime balls to check how many slime reach each cell of the diagonal, and repeat this with $(t - x - y + 1)$ slime balls. Exactly one cell will show different result, and this cell is where $(t - x - y + 1)$-th slime ball passes through. If this cell is equal to $(x, y)$, the answer is YES. Otherwise the answer is NO. Simulation with $x$ slime balls processes as follows: Place $x$ slime balls on cell $(0, 0)$. Move slime balls to next diagonal. For each cell, if the cell contains $k$ slime balls, $\\lceil \\frac{k}{2} \\rceil$ moves to right and $\\lfloor \\frac{k}{2} \\rfloor$ moves to down. Repeat the second step. If slime balls reached aimed diagonal, stop and find the result.",
    "code": "#import<bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\ntypedef long long LL;\nLL px, py, q, t, x, y, a[240], b[240];\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tfor(cin >> q; q--;)\n\t{\n\t\tcin >> t >> x >> y;\n\t\tif(t < x + y)\n\t\t{\n\t\t\tcout << \"NO\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tfill(a, a + 240, 0);\n\t\tfill(b, b + 240, 0);\n\t\ta[0] = t - x - y;\n\t\tb[0] = a[0] + 1;\n\t\tfor(int i = 0; i < x + y; i++)\n\t\t{\n\t\t\tfor(int j = i; j >= 0; j--)\n\t\t\t{\n\t\t\t\ta[j + 1] += a[j] / 2;\n\t\t\t\ta[j] -= a[j] / 2;\n\t\t\t\tb[j + 1] += b[j] / 2;\n\t\t\t\tb[j] -= b[j] / 2;\n\t\t\t}\n\t\t}\n\t\tpx = py = -1;\n\t\tfor(int i = 0; i < 240; i++)\n\t\t{\n\t\t\tif(a[i] != b[i])\n\t\t\t{\n\t\t\t\tpx = i;\n\t\t\t\tpy = x + y - i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(x == px && y == py)cout << \"YES\" << endl;\n\t\telse cout << \"NO\" << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1734",
    "index": "A",
    "title": "Select Three Sticks",
    "statement": "You are given $n$ sticks with positive integral length $a_1, a_2, \\ldots, a_n$.\n\nYou can perform the following operation any number of times (possibly zero):\n\n- choose one stick, then either increase or decrease its length by $1$. After each operation, all sticks should have positive lengths.\n\nWhat is the minimum number of operations that you have to perform such that it is possible to select three of the $n$ sticks and use them without breaking to form an equilateral triangle?\n\nAn equilateral triangle is a triangle where all of its three sides have the same length.",
    "tutorial": "We first sort the array $a$ in non-decreasing order. Denote the indices of the elements that we choose from $a$ to be $x$, $y$, and $z$, where $1 \\le x < y < z \\le n$, and the final value (after performing the operations) of the concerned elements to be $v$. The minimum required number of operations is then $|a_x-v|+|a_y-v|+|a_z-v|$. It is well-known that such expression attains its minimum value when $v$ is the median of $a_x$, $a_y$, and $a_z$. Since the array $a$ has already been sorted, it is best to assign $v$ to be $a_y$. Our expression then becomes $|a_x-a_y|+|a_y-a_y|+|a_z-a_y|=(a_y-a_x)+0+(a_z-a_y)=a_z-a_x$. We would like to minimize the value of $a_z$, which implies $z$ should be as small as possible since $a$ is sorted. It is clear that taking $z=y+1$ would minimize the value of the expression. Similarly, we can show that we can take $x=y-1$ to minimize the value of the expression. Therefore, the only possible values of the triplets $(x,y,z)$ are of the form $(t,t+1,t+2)$ for positive integers $1 \\le t \\le n-2$, and we can iterate through all such triplets and find the best one. The time complexity is $\\Theta(n \\log n)$ per case due to sorting.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve(){\n\tint n;\n\tcin>>n;\n\tint a[n+1];\n\tfor (int i=1; i<=n; i++){\n\t\tcin>>a[i];\n\t}\n\tsort(a+1,a+n+1);\n\tint ans=2e9;\n\tfor (int i=3; i<=n; i++){\n\t\tans=min(ans,a[i]-a[i-2]);\n\t}\n\tcout<<ans<<'\\n';\n}\nint main(){\n\tint t;\n\tcin>>t;\n\tfor (int i=1; i<=t; i++){\n\t\tsolve();\n\t}\n}\n",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1734",
    "index": "B",
    "title": "Bright, Nice, Brilliant",
    "statement": "There is a pyramid which consists of $n$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $i$-th floor consists of $i$ rooms.\n\nDenote the $j$-th room on the $i$-th floor as $(i,j)$. For all positive integers $i$ and $j$ such that $1 \\le j \\le i < n$, there are $2$ \\textbf{one-way} staircases which lead from $(i,j)$ to $(i+1,j)$ and from $(i,j)$ to $(i+1,j+1)$ respectively.\n\nIn each room you can either put a torch or leave it empty. Define the brightness of a room $(i, j)$ to be the number of rooms with a torch from which you can reach the room $(i, j)$ through a non-negative number of staircases.\n\nFor example, when $n=5$ and torches are placed in the rooms $(1,1)$, $(2,1)$, $(3,2)$, $(4,1)$, $(4,3)$, and $(5,3)$, the pyramid can be illustrated as follows:\n\nIn the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.\n\nThe room $(4,2)$ (the room with a star) has brightness $3$. In the picture below, the rooms from where you can reach $(4,2)$ have red border. The brightness is $3$ since there are three torches among these rooms.\n\nThe pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.\n\nDefine the brilliance of a nice pyramid to be the sum of brightness over the rooms $(1,1)$, $(2,1)$, $(3,1)$, ..., $(n,1)$.\n\nFind an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.\n\nWe can show that an answer always exists. If there are multiple answers, output any one of them.",
    "tutorial": "Note that the brightnesses of the rooms on the $i$-th floor is at most $i$. This is because in room $(i,1)$, only $i$ rooms, namely, $(1,1)$, $(2,1)$, $\\ldots$, $(i,1)$ can reach to $(i,1)$ through some number of staircases. It is also possible to find a configuration of torches in the pyramid such that the brightnesses of the rooms on the $i$-th floor is exactly $i$, i.e. it attains the upper bound. The configuration is as follows: Room $(i,j)$ contains a torch if and only if it is the leftmost room ($i=1$) or the rightmost room ($i=j$) on the $i$-th floor. This is valid because for all rooms $(i,j)$, it can be reached from $(1,1)$, $(2,1)$, $(3,1)$, $\\ldots$, $(i-j+1,1)$ and $(2,2)$, $(3,3)$, $\\ldots$, $(j,j)$. In other words, room $(i,j)$ has brightness $(i-j+1)+j-1=i$, so the pyramid is nice.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        for (int i = 1; i <= n; i++) {\n            for (int j = 1; j <= i; j++) {\n                cout << (j == 1 || j == i) << ' ';\n            }\n            cout << '\\n';\n        }\n    }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1734",
    "index": "C",
    "title": "Removing Smallest Multiples",
    "statement": "You are given a set $S$, which contains the first $n$ positive integers: $1, 2, \\ldots, n$.\n\nYou can perform the following operation on $S$ any number of times (possibly zero):\n\n- Choose a positive integer $k$ where $1 \\le k \\le n$, such that there exists a multiple of $k$ in $S$. Then, delete the \\textbf{smallest} multiple of $k$ from $S$. This operation requires a cost of $k$.\n\nYou are given a set $T$, which is a subset of $S$. Find the minimum possible total cost of operations such that $S$ would be transformed into $T$. We can show that such a transformation is always possible.",
    "tutorial": "One operation should be used to remove every element not belonging to $T$. Let $v$ be an element not belonging to $T$. Suppose a $x$-cost operation removes value $v$, then $v$ must be divisible by $x$. Furthermore, the multiples $x,2x,\\cdots (k-1)x$ must have been already removed from $S$, where we write $v = kx$. Since removed elements stay removed, the above is only possible if all of $x,2x,\\cdots (k-1)x$ does not belong to $T$. For each $v$, let $f(v)$ be the smallest integer $x$ satisfying the above condition. As we can always remove $v$ using a $v$-cost operation, $f(v) \\leq v$ and in particular $f(v)$ exists. The total cost must be at least $\\sum_{i \\not \\in T} f(i)$. We claim that this cost can be achieved. To do so, we should remove the required elements in ascending order. When removing $v$, we assume all $w \\not\\in T$ with $w<v$ have already been removed. At this state, an $f(v)$-cost operation would be able to remove $v$. It remains to find the values $f(v)$. To do so efficiently, we can perform the above process in a bottom-up manner similar to the Sieve of Eratosthenes. Please refer to the code below for implementation details. The overall complexity is $n (1 +\\frac{1}{2} + \\frac{1}{3} + \\cdots + \\frac{1}{n}) = \\Theta(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    int n;\n    cin >> n;\n    bool a[n + 1];\n    string str;\n    cin >> str;\n    for (int i = 1; i <= n; i++) {\n        a[i] = (str[i - 1] == '1');\n    }\n    long long ans = 0;\n    int cost[n + 1];\n    for (int i = n; i >= 1; i--) {\n        for (int j = i; j <= n; j += i) {\n            if (a[j]) break;\n            cost[j] = i;\n        }\n    }\n    for (int i = 1; i <= n; i++) {\n        if (!a[i]) ans += cost[i];\n    }\n    cout << ans << '\\n';\n}\nint main() {\n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1734",
    "index": "D",
    "title": "Slime Escape",
    "statement": "You are playing a game called Slime Escape. The game takes place on a number line. Initially, there are $n$ slimes. For all positive integers $i$ where $1 \\le i \\le n$, the $i$-th slime is located at position $i$ and has health $a_i$. You are controlling the slime at position $k$.\n\nThere are two escapes located at positions $0$ and $n+1$. Your goal is to reach \\textbf{any one} of the two escapes by performing any number of game moves.\n\nIn one game move, you move your slime to the left or right by one position. However, if there is another slime in the new position, you must absorb it. When absorbing a slime, the health of your slime would be increased by the health of the absorbed slime, then the absorbed slime would be removed from the game.\n\nNote that some slimes might have negative health, so your health would decrease when absorbing such slimes.\n\nYou lose the game immediately if your slime has negative health at any moment during the game.\n\nCan you reach one of two escapes by performing any number of game moves, without ever losing the game?",
    "tutorial": "Let's call a group of slime good if their total health is at least $0$, or if defeating this group allows you to reach the exits. We partition the slimes into good groups in a two-pointer like manner. To form the groups to the right, start from position $k$, then find the smallest position $r$ such that slimes from $k+1$ through $r$ form a good group. We do the same starting from $r+1$ again. Repeat this process until slimes to the right are partitioned into groups, which can be done by maintaining the sum of health. We partition the left slimes into groups in a similar way. We can observe that in an optimal strategy, we may assume the player absorbs group-by-group. Assuming there is a valid strategy $S$ to reach the exit. Let $X$ be the first group to the left, and $Y$ be the first group to the right. Without loss of generality, assume all slimes of $X$ are absorbed before all slimes of $Y$ are absorbed first. Suppose there are $x$ slimes in $X$ and $y$ slimes in $Y$. Suppose we did not absorb all of $X$ at a time. For example, if there are $6$ slimes in $X$ and $5$ or more slimes in $Y$, the beginning of our strategy may look like this: $LLRRLRLLRL....$ Consider instead the strategy where we move all `L' to the front. We claim that the strategy stays valid. That is, the following strategy $LLLLLLRRRR....$ is at least as good. We check that at every moment of strategy $LLLLLLRRRR....$, there is some point in time $LLRRLRLLRL....$ which we would have less than or equal amount of health. For the state $T_1$ that we take $a$ moves to the left in $LLLLLLRRRR....$, we compare it with any moment $T_2$ in $LLRRLRLLRL....$ that we have taken $a$ moves to the left. To reach $T_2$, we take $b$ moves to the right. We can check that under the assumption, $0 \\leq b < y$. Since $Y$ is the smallest good group to the right, taking these $b$ extra right moves must have reduced our health. So, we have more health at $T_1$ than in $T_2$. Now consider the state $T_3$ in $LLLLLLRRRR....$ where we take all $x$ left moves and $b$ more right moves. We should compare it with any moment $T_4$ in $LLRRLRLLRL....$ that we have taken $b$ right moves and some $a$ left moves. We can check that under the assumption $0 \\leq a < x$. Since $X$ is the smallest good group, taking only $a$ moves to the left gives us less health compared to taking all $x$ moves to the left. Therefore, we have more health at $T_3$ than in $T_4$. Therefore, if $LLRRLRLLRL....$ is valid, $LLLLLLRRRR....$ must be valid. So, we only need to consider strategies of the second form. By applying this claim recursively, we notice that we only need to consider strategies that absorb whole groups at a time. This works for all strategies, we just referred to the starting strategy as $LLRRLRLLRL....$, and the better strategy as $LLLLLLRRRR....$ to simplify notations. For any good group, since the total health is positive, there is no drawback to absorbing a good group. In other words, whenever it is possible to absorb a good group, we will absorb it. For each group $G$, we calculate the ``requirement'' of the group - the lowest health we can begin with, such that we can absorb the group while maintaining non-negative health at all times. The requirement of a group of slime with health $a_1,a_2 \\cdots a_n$ can be expressed as $- \\min_{k=0}^n (\\sum_{i=1}^k a_i)$ Finally, we can simply simulate the process. We repeatedly attempt to absorb good groups to the left or to the right. We keep track of the current health, initially equal to $a_k$. Whenever we consider whether to absorb a group or not, we absorb it if and only if the current health is at least as high as its requirement. Otherwise, we ignore it for now and attempt to do so for the group on the other side. If it is possible to reach a state where either all left groups or all right groups are absorbed, then we can win the game. If at some point, it is not possible to absorb the left group nor the right group, then we lose. The overall complexity is $\\Theta(n)$. It is also possible to use a range $\\max$/$\\min$ segment tree form the groups instead of using two-pointers, in which case its complexity would be $\\Theta(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    long long n, k, P;\n    cin >> n >> k;\n    k--;\n    long long L[n];\n    for (int i = 0; i < n; i++) cin >> L[i];\n    P = L[k];\n    L[k] = 0;\n    long long ps[n + 1];\n    ps[0] = 0;\n    for (int i = 1; i <= n; i++) ps[i] = ps[i - 1] + L[i - 1];\n    int l = k, r = k + 1;\n    vector<pair<long long, long long> > LG, RG;\n    for (int i = k - 1; i >= 0; i--) {\n        if (ps[i] <= ps[l] || i == 0) {\n            long long worst = 0, cur = 0;\n            for (int j = l - 1; j >= i; j--) {\n                cur += L[j];\n                worst = min(worst, cur);\n            }\n            LG.push_back({cur, -worst});\n            l = i;\n        }\n    }\n    for (int i = k + 2; i <= n; i++) {\n        if (ps[i] >= ps[r] || i == n) {\n            long long worst = 0, cur = 0;\n            for (int j = r; j <= i - 1; j++) {\n                cur += L[j];\n                worst = min(worst, cur);\n            }\n            RG.push_back({cur, -worst});\n            r = i;\n        }\n    }\n    reverse(LG.begin(), LG.end());\n    reverse(RG.begin(), RG.end());\n    long long curp = P;\n    while (true) {\n        bool acted = false;\n        if (!LG.empty() && curp >= LG.back().second) {\n            curp += LG.back().first;\n            LG.pop_back();\n            acted = true;\n        }\n        if (!RG.empty() && curp >= RG.back().second) {\n            curp += RG.back().first;\n            RG.pop_back();\n            acted = true;\n        }\n        if (LG.empty() || RG.empty()) {\n            cout << \"YES\\n\";\n            return;\n        }\n        if (!acted) {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n}\nint main() {\n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1734",
    "index": "E",
    "title": "Rectangular Congruence",
    "statement": "You are given a \\textbf{prime} number $n$, and an array of $n$ integers $b_1,b_2,\\ldots, b_n$, where $0 \\leq b_i < n$ for each $1 \\le i \\leq n$.\n\nYou have to find a matrix $a$ of size $n \\times n$ such that all of the following requirements hold:\n\n- $0 \\le a_{i,j} < n$ for all $1 \\le i, j \\le n$.\n- $a_{r_1, c_1} + a_{r_2, c_2} \\not\\equiv a_{r_1, c_2} + a_{r_2, c_1} \\pmod n$ for all positive integers $r_1$, $r_2$, $c_1$, and $c_2$ such that $1 \\le r_1 < r_2 \\le n$ and $1 \\le c_1 < c_2 \\le n$.\n- $a_{i,i} = b_i$ for all $1 \\le i \\leq n$.\n\nHere $x \\not \\equiv y \\pmod m$ denotes that $x$ and $y$ give different remainders when divided by $m$.\n\nIf there are multiple solutions, output any. It can be shown that such a matrix always exists under the given constraints.",
    "tutorial": "We say a matrix to be good if it satisfies the congruence condition (the second condition). When we have a good matrix, we can add any value $c$ to a whole row while maintaining the congruence relation. The same is true for adding the same value to a whole column. Suppose we have any good matrix $A$, then by adding $b_i - a_{i,i}$ to the $i$-th row for each of $i=1,2,\\cdots,n$, we obtain a good matrix that has the desired values on the diagonal. In fact, there are a lot of possible constructions. We present a few of them here: $a_{i,j} = i \\times j \\pmod n$ $a_{i,j} = i \\times j \\pmod n$ $a_{i,j} = (i + j)^2 \\pmod n$. This needs special handling when $n=2$. $a_{i,j} = (i + j)^2 \\pmod n$. This needs special handling when $n=2$. $a_{i,j} = \\frac{(i+j)(i+j+1)}{2} \\pmod n$. $a_{i,j} = \\frac{(i+j)(i+j+1)}{2} \\pmod n$. The coolest part is that all quadratic polynomials in the form $ai^2 + bij + cj^2 + di + ej + f$ are valid for all integers $a,b,c,d,e,f$ and $b \\not\\equiv 0 \\pmod n$ The coolest part is that all quadratic polynomials in the form $ai^2 + bij + cj^2 + di + ej + f$ are valid for all integers $a,b,c,d,e,f$ and $b \\not\\equiv 0 \\pmod n$ As a bonus, we prove that the general quadratic polynomial gives a good construction. Since we can add values to a whole row or column, and $i^2, j^2 , i , j , 1$ are also constant on the rows and columns, adding them by $a_{i,j}$ has no effect. So we may just assume $a = c = d =e = f =0$. So it suffices to show that $a_{i,j} = b i j \\pmod n$ satisfies the condition. We can see directly that $a_{r_1,c_1} - a_{r_2,c_1} - a_{r_1,c_2} +a_{r_2,c_2} = b(r_1 - r_2)(c_1 - c_2)$. As $r_1 \\neq r_2$, $c_1 \\neq c_2$, $b \\not\\equiv 0 \\pmod n$, and $n$ is a prime, this expression must be nonzero $\\pmod n$. Here are some extra observations that may enable one to find a good matrix more quickly. For each $j$, the values $a_{i,j} - a_{i-1,j}$ over all $0 \\le i <n$ must be a permutation of ${0,1,\\cdots,n-1}$. A good matrix stays good if we permute the rows or permute the columns. Therefore, we can show that there exists some good matrix with $a_{1,j} = a_{i,1} = 0$, and $a_{2,j} = j-1$, $a_{i,2} = i-1$. Assuming this, it should not be difficult to discover $a_{i,j} = (i-1)(j-1)$ yields one of the good matrices. Let $b$ be the two dimensional difference array of $a$, that is, $b_{i,j} = a_{i,j} - a_{i-1,j} - a_{i,j-1} + a_{i-1,j-1}$. Then, the condition becomes sum of any rectangles of $b$ must be nonzero $\\pmod n$. It is easy to see $b = 1$ is valid. This corresponds to the solution that $a_{i,j} = i \\times j \\pmod n$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint want[355];\nint board[355][355];\nint main() {\n    int n;\n    cin >> n;\n    for(int i = 0; i < n ; i ++){\n        cin >> want[i];\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            board[i][j] = (i * j) % n;\n        }\n    }\n    for(int i = 0; i < n; i ++){\n        int extra = (want[i] + n - board[i][i] )% n ;\n        for (int j = 0; j < n; j++) {\n            board[i][j] += extra;\n            board[i][j] %= n;\n        }\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cout << board[i][j] << ' ';\n        }\n        cout << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1734",
    "index": "F",
    "title": "Zeros and Ones",
    "statement": "Let $S$ be the Thue-Morse sequence. In other words, $S$ is the $0$-indexed binary string with infinite length that can be constructed as follows:\n\n- Initially, let $S$ be \"0\".\n- Then, we perform the following operation infinitely many times: concatenate $S$ with a copy of itself with flipped bits.For example, here are the first four iterations:\n\n\\begin{center}\n\\begin{tabular}{|c||l||l||l|}\n\\hline\nIteration & $S$ before iteration & $S$ before iteration with flipped bits & Concatenated $S$ \\\n\\hline\n\\hline\n1 & 0 & 1 & 01 \\\n2 & 01 & 10 & 0110 \\\n3 & 0110 & 1001 & 01101001 \\\n4 & 01101001 & 10010110 & 0110100110010110 \\\n$\\ldots$ & $\\ldots$ & $\\ldots$ & $\\ldots$ \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nYou are given two positive integers $n$ and $m$. Find the number of positions where the strings $S_0 S_1 \\ldots S_{m-1}$ and $S_n S_{n + 1} \\ldots S_{n + m - 1}$ are different.",
    "tutorial": "Observe that the $i$-th character is `1' if and only if $i$ has an odd number of set bits in its binary representation. Both solutions make use of this fact. The constraints allows solutions of up to $\\Theta(q \\log^3 n)$. Yet, both of the model solution runs in $\\Theta(\\log n)$. The question can be reformulated as follows: How many integers $x$ between $0$ and $m-1$ inclusive have the property that the total number of set bits of $x$ and $x+n$ is an odd number? This can be solved with digit DP. We process the bit position from $\\lceil \\log(\\max) \\rceil$ down to $0$. We maintain three states: $\\text{ans}$, a boolean value; $\\text{ans}$, a boolean value; $\\text{trailzeros}$, an integer between $0$ and $\\lceil \\log(\\max) \\rceil$ inclusive; and $\\text{trailzeros}$, an integer between $0$ and $\\lceil \\log(\\max) \\rceil$ inclusive; and $\\text{under}$, a boolean value. $\\text{under}$, a boolean value. We can thus conclude the following: the number of trailing zeros is all we need to decide the answer. After processing each bit $k$, we should have the following: the number of integers $x$ between $0$ and $\\lfloor \\frac{m}{2^k} \\rfloor$ inclusive which have the following property: the total number of set bits of $x$ and $x + \\lfloor \\frac{n}{2^k} \\rfloor$ is equal to $\\text{ans} \\mod 2$; the total number of set bits of $x$ and $x + \\lfloor \\frac{n}{2^k} \\rfloor$ is equal to $\\text{ans} \\mod 2$; the number of trailing `1's of $x + \\lfloor \\frac{n}{2^k} \\rfloor$ is equal to $\\text{trailzeros}$; the number of trailing `1's of $x + \\lfloor \\frac{n}{2^k} \\rfloor$ is equal to $\\text{trailzeros}$; the boolean value $[x < \\lfloor \\frac{m}{2^k} \\rfloor]$ (where $[]$ is the Iverson bracket). the boolean value $[x < \\lfloor \\frac{m}{2^k} \\rfloor]$ (where $[]$ is the Iverson bracket). Now onto the transitions. Suppose we are adding the $(k-1)$-th digit, and let $d$ be the new digit of $x$, and $z$ be the $(k-1)$-th digit of $n$. If $z+d = 0$, then $(\\text{ans},\\text{trailzeros})$ after digit $k$ will be transited to $(\\text{ans},0)$ after digit $k-1$; If $z+d = 0$, then $(\\text{ans},\\text{trailzeros})$ after digit $k$ will be transited to $(\\text{ans},0)$ after digit $k-1$; if $z+d = 1$, then $(\\text{ans},\\text{trailzeros})$ after digit $k$ will be transited to $((\\text{ans} + z +d) \\mod 2, \\text{trailzeros}+1)$ after digit $k-1$; if $z+d = 1$, then $(\\text{ans},\\text{trailzeros})$ after digit $k$ will be transited to $((\\text{ans} + z +d) \\mod 2, \\text{trailzeros}+1)$ after digit $k-1$; if $z+d =2$, then $(\\text{ans},\\text{trailzeros})$ after digit $k$ will be transited to $((\\text{ans} + z + \\text{trail} + 1) \\mod 2, 0)$ after digit $k-1$ if $z+d =2$, then $(\\text{ans},\\text{trailzeros})$ after digit $k$ will be transited to $((\\text{ans} + z + \\text{trail} + 1) \\mod 2, 0)$ after digit $k-1$ The final answer is the total number of values for which $\\text{ans} =1$ and $\\text{under} = 1$. The above solution runs in $\\Theta(\\log^2 (\\max))$ per query. There is a simple way to optimize this to $\\Theta(\\log(\\max))$: note that we only need to keep parity of $\\text{trailzero}$. There are many other digit DP approaches that give similar time complexity. The constraints should allow most of them pass. Define the function $f(x) :=$ the parity of bit one in the number $x$. We have thus reworded the statement into evaluating the follow expression: $T = \\sum_{i = 0}^{k - 1} \\left[f(i) \\ne f(i + n)\\right]$ The formula can be further transformed as: $T = \\sum_{i = 0}^{k - 1} f(i \\oplus (i + n))$ since $\\left[ f(a) \\ne f(b) \\right] = f(a \\oplus b)$ holds true for all non-negative integers $a$ and $b$. Imagine we construct a grid and assign the value at row $r$ and column $c$ to be $f(r \\oplus c)$. Then, $T$ is sum of a diagonal of length $k$ which starts at either $(0, n)$ or $(n, 0)$. Without loss of generality, we use $(0, n)$ in this editorial. The grid can be constructed similarly to the way we construct the string $S$. We start with a $1$-by-$1$ matrix $M_0=\\begin{bmatrix} 0 \\end{bmatrix}$. Then, the matrix $M_i$ of size $2^i \\times 2^i$ can be constructed as follows: $M_i = \\begin{bmatrix} M_{i - 1} & \\overline {M_{i - 1}} \\\\ \\overline{M_{i - 1}} & M_{i - 1} \\end{bmatrix}$ where $\\overline{M_{i - 1}}$ is the matrix $M_{i - 1}$ but with flipped bits. Here is another way of constructing the grid: let $C_i$ be an infinite chess board with alternating colors, similar to a regular chess board, but with each of the cells being size $2^i \\times 2^i$. For example, $C_0$, $C_1$ and $C_2$ in an $8$-by-$8$ grid is as follows: We claim that our grid is the $\\text{xor}$ of all chess board $C_i$. The proof is easy: $C_i$ is constructed by $\\text{xor}$-ing the $i$-th bit of the the row and column number. We are therefore motivated to proceed in the following way: if we drop the least significant bit (by making it to be $0$), we are still solving a very similar problem to the original problem, because dropping the first bit is similar to removing $C_0$. And when we shift $C_i$ to $C_{i - 1}$, it is a recursion of the same problem! Going back to the problem, where we are computing sum of a diagonal of length $k$. If $k$ is odd, we can make it odd by adding the last element to the result and decreasing $k$ by one. Now, $k$ is even, and we can utilize the recurrence as follows: remove $C_0$. remove $C_0$. scale the board down by 2 (including $n$ and $k$). By doing so, $C_i$ becomes $C_{i - 1}$. scale the board down by 2 (including $n$ and $k$). By doing so, $C_i$ becomes $C_{i - 1}$. solve the new problem. solve the new problem. scale the board up again and add $C_0$ back. scale the board up again and add $C_0$ back. from the result of the scaled down problem, some how calculate the result of the original problem from the result of the scaled down problem, some how calculate the result of the original problem The result of the scaled down problem is the number of $2$-by-$2$ cells with value $1$. From the number of $2$-by-$2$ cells with value $1$, we compute the number of cells with value $0$ as well. It is not hard to observe that it crosses the $2$-by-$2$ cells at all places. The only thing that matters is the parity of $n$. If $n$ is even, then the diagonal crosses the diagonal of the $2$-by-$2$ cells. In the scaled-down version, the diagonal is still a single diagonal starting at $(0, \\frac{n}{2})$; otherwise, If $n$ is even, then the diagonal crosses the diagonal of the $2$-by-$2$ cells. In the scaled-down version, the diagonal is still a single diagonal starting at $(0, \\frac{n}{2})$; otherwise, if $n$ is odd, it crosses the corner of the $2$-by-$2$ cells. In the scaled-down version, the diagonal is actually $2$ neighboring diagonals starting at $(0, \\frac{n-1}{2})$ and $(0, \\frac{n+1}{2})$. if $n$ is odd, it crosses the corner of the $2$-by-$2$ cells. In the scaled-down version, the diagonal is actually $2$ neighboring diagonals starting at $(0, \\frac{n-1}{2})$ and $(0, \\frac{n+1}{2})$. Also, the $2$-by-$2$ cells with values $0$ and $1$ respectively will also have the form: From here we have everything we need to compute the result of the original problem. Overall, the number of states we have to visit is $\\Theta(\\log k)$.",
    "code": "import random\n\ncache = {}\n\ndef popcount(n):\n    res = 0\n    while n:\n        res += 1\n        n &= n - 1\n    return res\n\ndef solve(n, k):\n    if k == 0:\n        return 0\n    if k == 1:\n        return popcount(n) & 1\n    if k % 2 == 1:\n        t = solve(n, k - 1)\n        x = popcount((k - 1) ^ (n + k - 1)) & 1\n        # print(t, x)\n        return t + x\n    if (n, k) in cache:\n        return cache[(n, k)]\n    if n % 2 == 0:\n        one_cell = 2\n        zero_cell = 0\n        cnt1 = solve(n // 2, k // 2)\n        cnt0 = k // 2 - cnt1\n    else:\n        one_cell = 0\n        zero_cell = 1\n        cnt1 = solve(n // 2, k // 2) + solve(n // 2 + 1, k // 2)\n        cnt0 = k - cnt1\n    res = one_cell * cnt1 + zero_cell * cnt0\n    # print(f\"n = {n}, k = {k}, cnt1 = {cnt1}, cnt0 = {cnt0}, one_cell = {one_cell}, zero_cell = {zero_cell}\")\n    cache[(n, k)] = res\n    return res\n\nt = int(input())\nfor _ in range(t):\n    cache.clear()\n    n, k = map(int, input().split())\n    print(solve(n, k))",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1735",
    "index": "A",
    "title": "Working Week",
    "statement": "Your working week consists of $n$ days numbered from $1$ to $n$, after day $n$ goes day $1$ again. And $3$ of them are days off. One of the days off is the last day, day $n$. You have to decide when the other two are.\n\nChoosing days off, you pursue two goals:\n\n- No two days should go one after the other. Note that you can't make day $1$ a day off because it follows day $n$.\n- Working segments framed by days off should be as dissimilar as possible in duration. More specifically, if the segments are of size $l_1$, $l_2$, and $l_3$ days long, you want to maximize $\\min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|)$.\n\nOutput the maximum value of $\\min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|)$ that can be obtained.",
    "tutorial": "Let's consider that $l_1$, $l_2$, and $l_3$ are sorted working segments. Can we explicitly say something about one of them? $l_1$ must be equal to $1$. Let's consider that $l_1$, $l_2$, and $l_3$ are sorted working segments. If $l_1$ is not equal to $1$ then we can decrease $l_1$ by $1$ and increase $l_3$ by $1$. So we'll increase the answer. We've got that $l_1 = 1$ and we have to work just with $l_2$ and $l_3$. Now, our problem can be rewritten as: $l_2 + l_3 = n - 4$, maximize $min(l_2 - 1, l_3 - l_2)$. And as we know that $l_3 = n - 4 - l_2$, just: maximize $min(l_2 - 1, n - 4 - 2 \\cdot l_2)$. If we increase both values under the minimum scope by one, solutions don't change: maximize $min(l_2, (n - 3) - 2 \\cdot l_2)$. If we choose $l_2 = \\left\\lfloor\\frac{n-3}{3}\\right\\rfloor$, then $min(l_2, (n - 3) - 2 \\cdot l_2) = \\left\\lfloor\\frac{n-3}{3}\\right\\rfloor$. If the answer is greater, then $l_2 > \\frac{n - 3}{3}$ and $(n - 3) - 2 \\cdot l_2 > \\frac{n - 3}{3}$, and it means that $2 \\cdot (l_2) + ((n - 3) - 2 \\cdot l_2) > n - 3$ but $2 \\cdot (l_2) + ((n - 3) - 2 \\cdot l_2) = n - 3$. The only thing is left to do is to calculate final answer. And it is $\\left\\lfloor\\frac{n-3}{3}\\right\\rfloor - 1$ or just $\\left\\lfloor\\frac{n}{3}\\right\\rfloor - 2$. It was a mathematician way of solving. As it's pretty obvious that $l_2$ is approximately $\\frac{n}{3}$, you could check $l_2 = \\frac{n}{3} \\pm 5$ and choose the best among them.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tint l_2 = (n - 3) / 3;\n\tint ans = l_2 - 1;\n\tcout << ans << '\\n';\n}\n \nint main() {\n\tios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tint t = 1; \n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n \n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1735",
    "index": "B",
    "title": "Tea with Tangerines",
    "statement": "There are $n$ pieces of tangerine peel, the $i$-th of them has size $a_i$. In one step it is possible to divide one piece of size $x$ into two pieces of positive integer sizes $y$ and $z$ so that $y + z = x$.\n\nYou want that for each pair of pieces, their sizes differ \\textbf{strictly} less than twice. In other words, there should not be two pieces of size $x$ and $y$, such that $2x \\le y$. What is the minimum possible number of steps needed to satisfy the condition?",
    "tutorial": "Is there a way to cut pieces to save the minimum value and satisfy required conditions? What is the minimum possible number of operations to perform it? Is there any better solution? Let's start with a simple solution. Let's choose the minimum piece from $a$ and assume that it will remain the minimum until the end. As the array is sorted, let's define the minimum piece as $a_1$. It means that in the end, all pieces must be smaller or equal to $2 \\cdot a_1 - 1$. The lower bound of the answer for this solution is $\\displaystyle{\\sum\\limits_{i=1}^{n}\\left\\lceil\\frac{a_i}{2 \\cdot a_1 - 1}\\right\\rceil}$. Let's show that this is achievable. For each piece, while its size greater than $2 \\cdot a_1 - 1$, let's cut off a piece of size $2 \\cdot a_1 - 1$. The only problem is that we could get a piece smaller than $a_1$ in the end. But it means that before the last cut we had a piece in the range $[2 \\cdot a_1, 3 \\cdot a_1 - 2]$. All pieces in this range can be easily cut into pieces of the right size in one move. The only left question is why the minimum piece in the end should have size $a_1$. Actually, it shouldn't, but it gives the best answer anyway. As was described above, the lower bound of the solution with the minimal piece of size $x$ in the end is $\\displaystyle{\\sum\\limits_{i=1}^{n}\\left\\lceil\\frac{a_i}{2 \\cdot x - 1}\\right\\rceil}$. Having a minimal piece with a smaller size, we can't get anything better, because the lower bound will be equal or greater for all $x < a_1$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint n;\nvector<int> a;\n \nvoid solve() {\n\tcin >> n;\n\ta.resize(n);\n\tint ans = 0;\n\tfor (auto &i : a) {\n\t\tcin >> i;\n\t\tans += (i - 1) / (2 * a[0] - 1);\n\t}\n\tcout << ans << '\\n';\n}\n \nint main() {\n\tios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tint t = 1; \n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n \n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1735",
    "index": "C",
    "title": "Phase Shift",
    "statement": "There was a string $s$ which was supposed to be encrypted. For this reason, all $26$ lowercase English letters were arranged in a circle in some order, afterwards, each letter in $s$ was replaced with the one that follows in clockwise order, in that way the string $t$ was obtained.\n\nYou are given a string $t$. Determine the lexicographically smallest string $s$ that could be a prototype of the given string $t$.\n\nA string $a$ is lexicographically smaller than a string $b$ of the same length if and only if:\n\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter, that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "What is the first letter in the answer? $a$ if $t$ doesn't start with $a$ and $b$ otherwise. Ask the same question as Hint1 for each position. When we can't choose the minimum unused letter? If we form a circle of size less then $26$. Maintain any structure to check it. First of all, the encryption process is reversible. If we obtained $t$ from $s$ using the circle $c$, we can obtain $s$ from $t$ using the same cycle $c$, but reversed. So, let's think in terms of encryption of $t$. Lexicographical order itself is a greedy thing. So, we can create a greedy algorithm. Let's go from left to right and generate the result letter by letter. We have to choose the best possible option at each step. Let's describe the options we have. If the current letter was used earlier, we already know the replacement we need to choose. Otherwise, we would like to choose the minimum possible option. We need to maintain some structure to know what is acceptable. Let's keep the circle that is already generated(it's a graph). For each letter we have one incoming edge and one outgoing edge in the end. Let's keep them for every letter: arrays $in[26]$, $out[26]$. When we want to generate an outgoing edge at some step(let's define the letter on this step as $x$), we have to choose the minimum letter that doesn't have an incoming edge yet. With one exception: if creating the edge using this rule creates a circle of size less than $26$. It would mean that we wouldn't have a full circle in the end. It's easy to see that there is no more than one such letter, as this letter is just the end of a chain starting in $x$. To check that a small circle wasn't generated, we can go along an outgoing edge $26$ times, starting at $x$. If we end up in $x$ or there was no edge at some step then everything is ok, we can create this edge. Complexity is $\\mathcal{O}(26 \\cdot 26 + n)$, that is, $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n \nvoid solve() {\n\tint n;\n\tstring t;\n\tcin >> n;\n\tcin >> t;\n \n\tvector<int> edge(26, -1);\n\tvector<int> redge(26, -1);\n\tauto get_path_end = [&](int c) {\n\t\tint len = 0;\n\t\tint cur = c;\n\t\twhile (edge[cur] != -1)\n\t\t\tlen++, cur = edge[cur];\n\t\treturn make_pair(cur, len);\n\t};\n\tvector<int> vec;\n\tfor (auto c : t)\n\t\tvec.push_back(c - 'a');\n\tfor (int i = 0; i < n; i++) {\n\t\tif (edge[vec[i]] == -1) {\n\t\t\tfor (int c = 0; c < 26; c++)\n\t\t\t\tif (redge[c] == -1) {\n\t\t\t\t\tauto [clast, len] = get_path_end(c);\n\t\t\t\t\tif (clast != vec[i] || len == 25) {\n\t\t\t\t\t\tedge[vec[i]] = c;\n\t\t\t\t\t\tredge[c] = vec[i];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\tvec[i] = edge[vec[i]];\n\t}\n \n\tfor (int i = 0; i < n; i++)\n\t\tt[i] = vec[i] + 'a';\n \n\tcout << t << '\\n';\n}\n \nint main() {\n\t// viv = true;\n\tios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tcout << fixed << setprecision(20);\n\tint t = 1; \n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n \n\t#ifdef DEBUG\n\t\tcerr << \"Runtime is: \" << clock() * 1.0 / CLOCKS_PER_SEC << endl;\n\t#endif\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1735",
    "index": "D",
    "title": "Meta-set",
    "statement": "You like the card board game \"Set\". Each card contains $k$ features, each of which is equal to a value from the set $\\{0, 1, 2\\}$. The deck contains all possible variants of cards, that is, there are $3^k$ different cards in total.\n\nA feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $k$ features are good for them.\n\nFor example, the cards $(0, 0, 0)$, $(0, 2, 1)$, and $(0, 1, 2)$ form a set, but the cards $(0, 2, 2)$, $(2, 1, 2)$, and $(1, 2, 0)$ do not, as, for example, the last feature is not good.\n\nA group of \\textbf{five} cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $n$ distinct cards?",
    "tutorial": "How many sets can fit in $5$ cards? At most two. If there are two sets among $5$ cards, there will be a central card. Consider each card as a central card. For every two cards, there is always a single card that forms a set with them. [1] That means that two sets can share at most one card. Let's prove that there are no more than $2$ sets in a meta-set. Let's define $5$ cards as $c_1, c_2, c_3, c_4, c_5$. Let's guess that $(c_1, c_2, c_3)$ is a set. All other sets can have at most one card among $(c_1, c_2, c_3)$ (according to [1]), so they must include $c_4$ and $c_5$. So we have at most one other set, otherwise they would have two same cards, which is prohibited according to [1]. So, every meta-set looks like $2$ sets with one common card. Let's call this card a central card. Now there is just a simple combinatorics. For each card, we want to know the number of sets that include it. If this number is $s$, then we should add $\\frac{s(s-1)}{2}$ to the answer - it is the number of meta-sets with this card as a central card. To get the number of sets for each card, we can iterate over all pairs of cards $(i, j)$, generate the complement to the set, and add $1$ to that card in a map/hashmap. Complexity is $\\mathcal{O}(kn^2\\log(n))$ or $\\mathcal{O}(kn^2)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\ntypedef long long       ll;\ntypedef long double     ld;\ntypedef pair<ll, ll>   pll; \ntypedef pair<int, int> pii; \n \nconst long long kk = 1000;\nconst long long ml = kk * kk;\nconst long long mod = ml * kk + 7;\nconst long long inf = ml * ml * ml + 7; \n#ifdef DEBUG\n\tmt19937 rng(1033);\n#else\n\tmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\t\n#endif\nint rnd(int mod) { return uniform_int_distribution<int>(0, mod - 1)(rng); }\n \n \nbool viv = false;\nint n, k;\nvector<vector<int>> v;\n \nvector<int> get_comp(vector<int> a, vector<int> b) {\n\tvector<int> res(k);\n\tfor (int i = 0; i < k; i++)\n\t\tres[i] = (6 - (a[i] + b[i])) % 3;\n\treturn res;\n}\n \nvoid solve() {\n\tcin >> n >> k;\n\tv.resize(n);\n\tfor (auto &vec : v) {\n\t\tvec.resize(k);\n\t\tfor (auto &i : vec)\n\t\t\tcin >> i;\n\t}\n\tmap<vector<int>, int> cnt;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = i + 1; j < n; j++) {\n\t\t\tauto comp = get_comp(v[i], v[j]);\n\t\t\tcnt[comp]++;\n\t\t}\n\t}\n\tll ans = 0;\n\tfor (auto vec : v) {\n\t\tans += (ll)cnt[vec] * (cnt[vec] - 1) / 2;\n\t}\n\tcout << ans << '\\n';\n}\n \nint main() {\n\t// viv = true;\n\tios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tcout << fixed << setprecision(20);\n\tint t = 1; \n\t// cin >> t;\n\twhile (t--)\n\t\tsolve();\n \n\t#ifdef DEBUG\n\t\tcerr << \"Runtime is: \" << clock() * 1.0 / CLOCKS_PER_SEC << endl;\n\t#endif\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "data structures",
      "hashing",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1735",
    "index": "E",
    "title": "House Planning",
    "statement": "There are $n$ houses in your city arranged on an axis at points $h_1, h_2, \\ldots, h_n$. You want to build a new house for yourself and consider two options where to place it: points $p_1$ and $p_2$.\n\nAs you like visiting friends, you have calculated in advance the distances from both options to all existing houses. More formally, you have calculated two arrays $d_1$, $d_2$: $d_{i, j} = \\left|p_i - h_j\\right|$, where $|x|$ defines the absolute value of $x$.\n\nAfter a long time of inactivity you have forgotten the locations of the houses $h$ and the options $p_1$, $p_2$. But your diary still keeps two arrays — $d_1$, $d_2$, whose authenticity you doubt. Also, the values inside each array could be \\textbf{shuffled}, so values at the same positions of $d_1$ and $d_2$ may correspond to different houses. Pay attention, that values from one array could not get to another, in other words, all values in the array $d_1$ correspond the distances from $p_1$ to the houses, and in the array $d_2$  — from $p_2$ to the houses.\n\nAlso pay attention, that the locations of the houses $h_i$ and the considered options $p_j$ could match. For example, the next locations are correct: $h = \\{1, 0, 3, 3\\}$, $p = \\{1, 1\\}$, that could correspond to already shuffled $d_1 = \\{0, 2, 1, 2\\}$, $d_2 = \\{2, 2, 1, 0\\}$.\n\nCheck whether there are locations of houses $h$ and considered points $p_1$, $p_2$, for which the founded arrays of distances would be correct. If it is possible, find appropriate locations of houses and considered options.",
    "tutorial": "How many possible options are there for the distance between $p_1$ and $p_2$. We can limit it with $2 \\cdot n$ options. Consider options $d_1[1] + d_2[i]$, $|d_1[1] - d_2[i]|$. Solve each one in linear(almost) time. Consider the biggest distance among $d_1$ and $d_2$. Can we match it with something? Remove them one by one while they exceed the distance between $p_1$ and $p_2$. Then the problem is trivial. Let's assume that considered point $p_1$ was to the left of considered point $p_2$. Let's assume that we know the distance $l$ between considered points $p_1$ and $p_2$. Let's show how to solve this problem in linear time(almost linear). As long as there is a value greater than $l$, let's get the largest among them(let's call it $x$). Let's assume that this value is from $d_1$. It's easy to see that this point is to the right of the considered point $p_2$ (because the largest distances is to the point $p_1$). It means that we can match distance $x$ from $d_1$ to the distance $x - l$ from $d_2$. When there is no value greater than $l$, all other houses are located between considered points. We can match them by sorting. That is the $\\mathcal{O}(n log(n))$ solution. Let's limit possible options of $l$ with $\\mathcal{O}(n)$ options. If we know that some house has distances $x$ and $y$ to considered options, then there are $2$ options of $l$: $x + y$ and $|x - y|$. Let's consider $2 \\cdot n$ options $d_1[1] + d_2[i]$, $|d_1[1] - d_2[i]|$. Complexity is $\\mathcal{O}(n^2 log(n))$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\ntypedef long long       ll;\ntypedef long double     ld;\ntypedef pair<ll, ll>   pll; \ntypedef pair<int, int> pii; \n \nconst long long kk = 1000;\nconst long long ml = kk * kk;\nconst long long mod = ml * kk + 7;\nconst long long inf = ml * ml * ml + 7; \n#ifdef DEBUG\n\tmt19937 rng(1033);\n#else\n\tmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\t\n#endif\nint rnd(int mod) { return uniform_int_distribution<int>(0, mod - 1)(rng); }\n \n \nbool viv = false;\nint n;\nvector<int> d1, d2;\n \nbool work(int points_diff) {\n\tint p1 = 0;\n\tint p2 = points_diff;\n \n\tmultiset<int, greater<int>> s1, s2;\n\tfor (auto i : d1)\n\t\ts1.insert(i);\n\tfor (auto i : d2)\n\t\ts2.insert(i);\n \n \n\tauto farthest = [] (multiset<int, greater<int>> &s) {\n\t\treturn s.empty() ? -1 : *s.begin();\n\t};\n\tauto farthest_both = [&]() {\n\t\treturn max(farthest(s1), farthest(s2));\n\t};\n \n\tvector<int> ans;\n\twhile (farthest_both() > points_diff) {\n\t\tbool choose_s1 = farthest(s1) > farthest(s2);\n\t\tauto &s_far = choose_s1 ? s1 : s2;\n\t\tauto &s_near = choose_s1 ? s2 : s1;\n \n\t\tint value = *s_far.begin();\n\t\tint complem = value - points_diff;\n\t\tif (!s_near.count(complem)) \n\t\t\treturn false;\n \n\t\ts_far.erase(s_far.find(value));\n\t\ts_near.erase(s_near.find(complem));\n \n\t\tif (choose_s1) \n\t\t\tans.push_back(p1 + value);\n\t\telse\n\t\t\tans.push_back(p2 - value);\n\t}\n \n\tvector<int> left1, left2;\n\tfor (auto i : s1)\n\t\tleft1.push_back(i);\n\tfor (auto i : s2)\n\t\tleft2.push_back(i);\n\tsort(left1.begin(), left1.end());\n\tsort(left2.rbegin(), left2.rend());\n \n\tfor (int i = 0; i < left1.size(); i++)\n\t\tif (left1[i] + left2[i] != points_diff)\n\t\t\treturn false;\n \n\tfor (auto i : left1)\n\t\tans.push_back(i);\n \n\tsort(ans.begin(), ans.end());\n\tint sh = max(-ans[0], 0);\n\tp1 += sh, p2 += sh;\n\tfor (auto &i : ans)\n\t\ti += sh;\n \n\tcout << \"YES\\n\";\n\tfor (auto i : ans)\n\t\tcout << i << ' ';\n\tcout << '\\n';\n\tcout << p1 << ' ' << p2 << '\\n';\n\treturn true;\n}\n \nvoid solve() {\n\tcin >> n;\n\td1.resize(n);\n\td2.resize(n);\n\tfor (auto &d : d1)\n\t\tcin >> d;\n\tfor (auto &d : d2)\n\t\tcin >> d;\n \n\tint dist1 = d1[0];\n\tfor (auto dist2 : d2) {\n\t\tif (work(dist1 + dist2))\n\t\t\treturn;\n\t\tif (work(abs(dist1 - dist2)))\n\t\t\treturn;\n\t}\n \n\tcout << \"NO\\n\";\n}\n \nint main() {\n\t// viv = true;\n\tios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tcout << fixed << setprecision(20);\n\tint t = 1; \n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n \n\t#ifdef DEBUG\n\t\tcerr << \"Runtime is: \" << clock() * 1.0 / CLOCKS_PER_SEC << endl;\n\t#endif\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graph matchings",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1735",
    "index": "F",
    "title": "Pebbles and Beads",
    "statement": "There are two currencies: pebbles and beads. Initially you have $a$ pebbles, $b$ beads.\n\nThere are $n$ days, each day you can exchange one currency for another at some exchange rate.\n\nOn day $i$, you can exchange $-p_i \\leq x \\leq p_i$ pebbles for $-q_i \\leq y \\leq q_i$ beads or vice versa. It's allowed not to perform an exchange at all. Meanwhile, if you perform an exchange, the proportion $x \\cdot q_i = -y \\cdot p_i$ must be fulfilled. Fractional exchanges are allowed.\n\nYou can perform no more than one such exchange in one day. The numbers of pebbles and beads you have must always remain non-negative.\n\nPlease solve the following $n$ problems independently: for each day $i$, output the maximum number of pebbles that you can have at the end of day $i$ if you perform exchanges optimally.",
    "tutorial": "Draw currencies on 2D plane. Assume that you can throw out any amount of money at any moment. What will an area of possible points look like? It will look like a convex polygon in the upper-right quarter. Keep its edges. How does the structure change when a new day comes? A new segment is added. A prefix of old segments is shifted by vector, the remaining suffix of old segments is shifted by opposite vector, Let's draw currencies on 2D plane. Having $x$ pebbles and $y$ beads is described as point $(x, y)$. Let's assume that we can throw out any amount of money at any moment. In this case, an area of possible points can be described as a convex polygon in the upper-right quarter. Initially it is the rectangle $[(0, 0), (0, b), (a, b), (a, 0)]$. At any moment, this polygon can be described as a list of segments starting at point $(0, y_0)$ and finishing at point $(x_k, 0)$. In the rectangle described above, there are $2$ segments. Let's keep those segments sorted by angle. When a new day comes, each point can be shifted by the vector $c\\cdot(p_i, -q_i)\\ \\forall c \\in [-1, 1]$ if the new point has non-negative coordinates. If we forget about new points to be non-negative, how new segments look like? We just have to add new segment $(2 \\cdot p_i, -2 \\cdot q_i)$ and shift a prefix of old segments by $(-p_i, q_i)$ and remaining suffix of segments by $(p_i, -q_i)$. Then the only thing left to do is to cut segments to keep our polygon non-negative. Sounds great, but sounds like $\\mathcal{O}(n^2)$. Do we need to maintain segments explicitly? No! Let's just keep the set of their lengths and angles. Knowledge of extreme points $(0, y_0)$ and $(x_k, 0)$ is enough. So we need to: Insert a new segment to the set. (You need just length and angle). Shift extreme points $(0, y_0)$ and $(x_k, 0)$ by $(-p_i, q_i)$ and $(p_i, -q_i)$ correspondingly. Delete or cut the last and first segments while they are out of the non-negative area. Complexity $\\mathcal{O}(nlog(n))$. There is another simple $\\mathcal{O}(n^2log(n))$ approach: We can keep the area as a polygon. At each step, create two copies shifted by corresponding vectors. Build a convex hull of them. Cut this convex hull to be in the non-negative area. It won't fit. Mentioned just for fun.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\ntypedef long long       ll;\ntypedef long double     ld;\ntypedef pair<ll, ll>   pll; \ntypedef pair<int, int> pii; \n \nconst long long kk = 1000;\nconst long long ml = kk * kk;\nconst long long mod = ml * kk + 7;\nconst long long inf = ml * ml * ml + 7; \nconst ld eps = 1e-9; \n#ifdef DEBUG\n\tmt19937 rng(1033);\n#else\n\tmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\t\n#endif\nint rnd(int mod) { return uniform_int_distribution<int>(0, mod - 1)(rng); }\n \n \nint n, a, b;\nvector<int> p, q;\n \n \nstruct Seg {\n\tll init_x, init_y;\n\tint num;\n\tld x, y;\n\tSeg() {}\n\tSeg(int p, int q, int num): init_x(q), init_y(-p), num(num) {\n\t\tx = init_x;\n\t\ty = init_y;\n\t}\n \n\tfriend bool operator<(const Seg &s1, const Seg &s2) {\n\t\tif (s1.init_x * s2.init_y == s1.init_y * s2.init_x)\n\t\t\treturn s1.num < s2.num;\n\t\treturn s1.init_x * s2.init_y < s1.init_y * s2.init_x;\n\t}\n\tSeg operator*=(ld ratio) { x *= ratio; y *= ratio; return *this; }\n \n\tvoid show() {\n\t\tcout << \"Seg(\" << x << ' ' << y << \")\";\n\t}\n};\n \nstruct Point {\n\tld x, y;\n\tPoint() {}\n\tPoint(int a, int b): x(b), y(a) {}\n\tPoint operator+=(const Point &v) { x += v.x; y += v.y; return *this; }\n    Point operator-=(const Point &v) { x -= v.x; y -= v.y; return *this; }\n\tPoint operator+=(const Seg &v) { x += v.x; y += v.y; return *this; }\n    Point operator-=(const Seg &v) { x -= v.x; y -= v.y; return *this; }\n \n\tvoid show() {\n\t\tcout << \"Point(\" << x << ' ' << y << \")\";\n\t}\n};\n \n \nstruct Stock {\n\tPoint best_a;\n\tPoint best_b;\n\tmultiset<Seg> segs;\n \n\tStock(int a, int b) {\n\t\tbest_a = Point(a, 0);\n\t\tbest_b = Point(0, b);\n \n\t\tSeg seg_1 = Seg(a, 0, -2);\n\t\tSeg seg_2 = Seg(0, b, -1);\n\t\tif (a)\n\t\t\tsegs.insert(seg_1);\n\t\tif (b)\n\t\t\tsegs.insert(seg_2);\n\t}\n \n\tvoid add_seg(int p, int q, int num) {\n\t\tSeg new_seg = Seg(2 * p, 2 * q, num);\n\t\tsegs.insert(new_seg);\n \n\t\tPoint shift(p, -q);\n\t\tbest_a += shift;\n\t\tbest_b -= shift;\n \n\t\tcut_left();\n\t\tcut_down();\n\t}\n \n\tvoid cut_left() {\n\t\twhile (best_a.x < 0) {\n\t\t\tSeg l_seg = *segs.begin();\n\t\t\tPoint new_best_a = best_a;\n\t\t\tnew_best_a += l_seg;\n \n\t\t\tif (new_best_a.x > eps) {\n\t\t\t\tld ratio = new_best_a.x / l_seg.x;\n\t\t\t\tSeg l_seg_left = l_seg;\n\t\t\t\tl_seg_left *= ratio;\n\t\t\t\tsegs.erase(segs.find(l_seg));\n\t\t\t\tsegs.insert(l_seg_left);\n\t\t\t\tnew_best_a -= l_seg_left;\n\t\t\t\tnew_best_a.x = max(new_best_a.x, (ld)0);\n\t\t\t} else {\n\t\t\t\tsegs.erase(segs.begin());\n\t\t\t}\n\t\t\tbest_a = new_best_a;\n\t\t}\n\t}\n \n\tvoid cut_down() {\n\t\twhile (best_b.y < 0) {\n\t\t\tSeg d_seg = *segs.rbegin();\n\t\t\tPoint new_best_b = best_b;\n\t\t\tnew_best_b -= d_seg;\n \n\t\t\tif (new_best_b.y > eps) {\n\t\t\t\tld ratio = new_best_b.y / -d_seg.y;\n\t\t\t\tSeg d_seg_left = d_seg;\n\t\t\t\td_seg_left *= ratio;\n\t\t\t\tsegs.erase(segs.find(d_seg));\n\t\t\t\tsegs.insert(d_seg_left);\n\t\t\t\tnew_best_b += d_seg_left;\n\t\t\t\tnew_best_b.y = max(new_best_b.y, (ld)0);\n\t\t\t} else {\n\t\t\t\tsegs.erase(segs.find(d_seg));\n\t\t\t}\n\t\t\tbest_b = new_best_b;\n\t\t}\n\t}\n \n\tvoid print_best() {\n\t\tcout << best_a.y << '\\n';\n\t}\n \n\tvoid show() {\n\t\tcout << \"----\\tStock\\t----\\n\";\n\t\tcout << \"best_a = \";\n\t\tbest_a.show();\n\t\tcout << endl;\n \n\t\tPoint cur = best_a;\n\t\tfor (auto seg : segs) {\n\t\t\tcur += seg;\n\t\t\tcout << \"\\t\";\n\t\t\tcur.show();\n\t\t\tcout << endl;\n\t\t}\n \n\t\tcout << \"best_b = \";\n\t\tbest_b.show();\n\t\tcout << endl;\n\t\tcout << \"----\\tEnd\\t----\\n\\n\";\n\t}\n};\n \nvoid solve() {\n\tcin >> n >> a >> b;\n\tp.resize(n);\n\tq.resize(n);\n\tfor (int i = 0; i < n; i++)\n\t\tcin >> p[i];\n\tfor (int i = 0; i < n; i++)\n\t\tcin >> q[i];\n \n\tStock st(a, b);\n\tfor (int i = 0; i < n; i++) {\n\t\tst.add_seg(p[i], q[i], i);\n\t\tst.print_best();\n\t}\n \n}\n \nint main() {\n\tios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tcout << fixed << setprecision(20);\n\tint t = 1; \n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n \n\t#ifdef DEBUG\n\t\tcerr << \"Runtime is: \" << clock() * 1.0 / CLOCKS_PER_SEC << endl;\n\t#endif\n}",
    "tags": [
      "data structures",
      "geometry"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1736",
    "index": "A",
    "title": "Make A Equal to B",
    "statement": "You are given two arrays $a$ and $b$ of $n$ elements, each element is either $0$ or $1$.\n\nYou can make operations of $2$ kinds.\n\n- Pick an index $i$ and change $a_i$ to $1-a_i$.\n- Rearrange the array $a$ however you want.\n\nFind the minimum number of operations required to make $a$ equal to $b$.",
    "tutorial": "It is easy to observe that the second operation needs to be performed at most once. Now, we just need to check $2$ cases, one in which the re-arrangement operation is used, and one in which it is not. If the re-arrangement operation is to be used, then we just need to make the counts of $0$s and $1$s in $a$ equal to that of $b$. Without loss of generality assume $a$ contains $x$ more $0$s than $b$, then the cost in this case will just be $x + 1$ (extra one for re-arrangement cost). If the re-arrangement operation is not to be used, then we just need to make each element of $a$ equal to the corresponding element of $b$. Finally, our answer is the smaller cost of these $2$ cases. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nvoid solve(){\n    ll n; cin>>n;\n    ll sum=0,ans=0;\n    vector<ll> a(n),b(n);\n    for(auto &it:a){\n        cin>>it;\n        sum+=it;\n    }\n    for(auto &it:b){\n        cin>>it;\n        sum-=it;\n    }\n    for(ll i=0;i<n;i++){\n        ans+=(a[i]^b[i]);\n    }\n    ans=min(ans,1+abs(sum));\n    cout<<ans<<\"\\n\";\n}\nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t; cin>>t;\n    while(t--){\n        solve();\n    }\n}  ",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1736",
    "index": "B",
    "title": "Playing with GCD",
    "statement": "You are given an integer array $a$ of length $n$.\n\nDoes there exist an array $b$ consisting of $n+1$ positive integers such that $a_i=\\gcd (b_i,b_{i+1})$ for all $i$ ($1 \\leq i \\leq n$)?\n\nNote that $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.",
    "tutorial": "Take $a_0 = a_{n+1} = 1$. Now take $b_i=lcm(a_{i-1},a_i)$ for $1 \\leq i \\leq n+1$. If $b$ gives us $a$ after performing the $\\gcd$ operations, then the answer is YES, otherwise the answer is NO. (When answer is NO, we would get a case like $\\gcd(b_i, b_{i + 1}) = k \\cdot a_i$(where $k > 1$ for some $i$). Suppose $c$ is some valid array which gives us $a$. So, $c_i$ should be divisible by $b_i$. This means $\\gcd(c_i, c_{i+1}) \\geq \\gcd(b_i, b_{i + 1})$. So, if $\\gcd(b_i, b_{i + 1}) > a_i$ for any $i$, we should also have $\\gcd(c_i, c_{i+1}) > a_i$. This implies that $c$ is not valid if $b$ is not valid. Time complexity is $O(n \\cdot \\log(bmax))$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nll lcm(ll a,ll b){\n    ll g=__gcd(a,b);\n    return (a*b/g);\n}\nvoid solve(){\n    ll n; cin>>n;\n    vector<ll> a(n+2,1);\n    for(ll i=1;i<=n;i++){\n        cin>>a[i];\n    }\n    vector<ll> b(n+2,1);\n    for(ll i=1;i<=n+1;i++){\n        b[i]=lcm(a[i],a[i-1]);\n    }\n    for(ll i=1;i<=n;i++){\n        if(__gcd(b[i],b[i+1])!=a[i]){\n            cout<<\"NO\\n\";\n            return;\n        }\n    }\n    cout<<\"YES\\n\";\n}\nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t; cin>>t;\n    while(t--){\n        solve();\n    }\n}  ",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1736",
    "index": "C1",
    "title": "Good Subarrays (Easy Version)",
    "statement": "This is the easy version of this problem. In this version, we do not have queries. Note that we have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.\n\nAn array $b$ of length $m$ is good if for all $i$ the $i$-th element is greater than or equal to $i$. In other words, $b$ is good if and only if $b_i \\geq i$ for all $i$ ($1 \\leq i \\leq m$).\n\nYou are given an array $a$ consisting of $n$ positive integers. Find the number of pairs of indices $(l, r)$, where $1 \\le l \\le r \\le n$, such that the array $[a_l, a_{l+1}, \\ldots, a_r]$ is good.",
    "tutorial": "Suppose $l[i]$ represents the leftmost point such that subarray $a[l[i],i]$ is good. Notice that the array $l$ is non-decreasing. So suppose $dp[i]$ denotes the length of longest good subarray which ends at index $i$. Take $dp[0]=0$. Now $dp[i]=min(dp[i-1]+1,a[i])$. Suppose $a[i] \\geq dp[i-1]+1$. Now we claim that $dp[i]=dp[i-1]+1$. We know $a[i-dp[i-1],i-1]$ is \\t{good}. Now if we look at array $b=a[i-dp[i-1],i]$, $b_i \\geq i$ for $1 \\leq i \\leq dp[i-1]$. For $b$ to be good, last element of $b$(which is $a[i]$) should be greater than or equal $dp[i-1]+1$(which is consistent with our supposition). So $b$ is good. We can similarly cover the case when $a[i] < dp[i-1]+1$. So our answer is $\\sum_{i=1}^{n} dp[i]$. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nvoid solve(){\n    ll n; cin>>n;\n    vector<ll> dp(n+5,0);\n    ll ans=0;\n    for(ll i=1;i<=n;i++){\n        ll x; cin>>x;\n        dp[i]=min(dp[i-1]+1,x);\n        ans+=dp[i];\n    }\n    cout<<ans<<\"\\n\";\n}\nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t; cin>>t;\n    while(t--){\n        solve();\n    }\n}  ",
    "tags": [
      "binary search",
      "data structures",
      "schedules",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1736",
    "index": "C2",
    "title": "Good Subarrays (Hard Version)",
    "statement": "This is the hard version of this problem. In this version, we have queries. Note that we do not have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.\n\nAn array $b$ of length $m$ is good if for all $i$ the $i$-th element is greater than or equal to $i$. In other words, $b$ is good if and only if $b_i \\geq i$ for all $i$ ($1 \\leq i \\leq m$).\n\nYou are given an array $a$ consisting of $n$ positive integers, and you are asked $q$ queries.\n\nIn each query, you are given two integers $p$ and $x$ ($1 \\leq p,x \\leq n$). You have to do $a_p := x$ (assign $x$ to $a_p$). In the updated array, find the number of pairs of indices $(l, r)$, where $1 \\le l \\le r \\le n$, such that the array $[a_l, a_{l+1}, \\ldots, a_r]$ is good.\n\nNote that all queries are \\textbf{independent}, which means after each query, the initial array $a$ is restored.",
    "tutorial": "Let us continue the idea of C1. Suppose $track[i]$ denotes $\\sum_{j=i}^{n} dp[j]$ if $dp[i]=a[i]$. We can precalculate array $track$. Now suppose $a_p$ is changed to $x$ and $adp[i]$ denotes the length of longest good subarray which ends at index $i$ in the updated array. It is easy to see that $adp[i]=dp[i]$ for $1 \\leq i < p$. Now let $q$ be the smallest index greater than $p$ such that $adp[q]=a[q]$(It might be the case that there does not exist any such $q$ which can be handled similarly). So we have $3$ ranges to deal with - $(1,p-1)$, $(p,q-1)$ and $(q,n)$. Now $\\sum_{i=1}^{p-1} adp[i]$ = $\\sum_{i=1}^{p-1} dp[i]$(which can be stored as prefix sum). Also $\\sum_{i=q}^{n} adp[i]$ = $track[q]$. Now we only left with range $(p,q-1)$. An interesting observation is $adp[i]=adp[i-1]+1$ for $p < i < q$. This approach can be implemented neatly in many ways(one way is answer each query offline). Time complexity is $O(n \\cdot \\log(n))$.",
    "code": "#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n#define ll long long  \nconst ll INF_MUL=1e13;\nconst ll INF_ADD=1e18;  \n#define pb push_back               \n#define mp make_pair        \n#define nline \"\\n\"                         \n#define f first                                          \n#define s second                                             \n#define pll pair<ll,ll> \n#define all(x) x.begin(),x.end()   \n#define vl vector<ll>         \n#define vvl vector<vector<ll>>    \n#define vvvl vector<vector<vector<ll>>>          \n#ifndef ONLINE_JUDGE    \n#define debug(x) cerr<<#x<<\" \"; _print(x); cerr<<nline;\n#else\n#define debug(x);  \n#endif     \nconst ll MOD=1e9+7;     \nconst ll MAX=100010;   \nll cal(ll n){\n    ll now=(n*(n+1))/2;      \n    return now; \n} \nclass ST {\npublic:\n    vector<ll> segs;\n    ll size = 0;\n    ll ID = INF_ADD;\n \n    ST(ll sz) {\n        segs.assign(2 * sz, ID);  \n        size = sz;  \n    }   \n      \n    ll comb(ll a, ll b) {\n        return min(a, b);  \n    }\n \n    void upd(ll idx, ll val) {\n        segs[idx += size] = val;\n        for(idx /= 2; idx; idx /= 2) segs[idx] = comb(segs[2 * idx], segs[2 * idx + 1]);\n    }\n \n    ll query(ll l, ll r) {\n        ll lans = ID, rans = ID;  \n        for(l += size, r += size + 1; l < r; l /= 2, r /= 2) {\n            if(l & 1) lans = comb(lans, segs[l++]);\n            if(r & 1) rans = comb(segs[--r], rans);\n        }\n        return comb(lans, rans);\n    }\n};  \nvoid solve(){  \n    ll n; cin>>n;\n    vector<ll> a(n+5,0),use(n+5,0),pref(n+5,0);\n    for(ll i=1;i<=n;i++){\n        cin>>a[i];  \n        use[i]=min(use[i-1]+1,a[i]); pref[i]=pref[i-1]+use[i]; \n    }\n    ST segtree(n+5);  \n    auto get=[&](ll l,ll r,ll till,ll pos,ll tar){\n        while(l<=r){\n            ll mid=(l+r)/2;     \n            if(segtree.query(pos,mid)>=tar){     \n                till=mid,l=mid+1;  \n            }     \n            else{\n                r=mid-1;         \n            }  \n        }  \n        return till;        \n    };        \n    vector<ll> track(n+5,0);         \n    for(ll i=n;i>=1;i--){   \n        segtree.upd(i,a[i]-i); ll till=get(i,n,i,i,a[i]-i);  \n        track[i]=track[till+1]+cal(a[i]+till-i)-cal(a[i]-1); \n    }\n    ll q; cin>>q;\n    while(q--){\n        ll p,x; cin>>p>>x; ll target=min(x,use[p-1]+1);\n        ll till=get(p+1,n,p,p+1,target-p);\n        ll ans=pref[p-1]+track[till+1]+cal(target+till-p)-cal(target-1);\n        cout<<ans<<nline;\n    }\n    return;\n}                 \nint main()                                                                           \n{                     \n    ios_base::sync_with_stdio(false);                           \n    cin.tie(NULL);                         \n    #ifndef ONLINE_JUDGE               \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);  \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif    \n    ll test_cases=1;                   \n    //cin>>test_cases;\n    while(test_cases--){   \n        solve();     \n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n} ",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1736",
    "index": "D",
    "title": "Equal Binary Subsequences",
    "statement": "Everool has a binary string $s$ of length $2n$. Note that a binary string is a string consisting of only characters $0$ and $1$. He wants to partition $s$ into two \\textbf{disjoint equal} subsequences. He needs your help to do it.\n\nYou are allowed to do the following operation \\textbf{exactly} once.\n\n- You can choose any subsequence (\\textbf{possibly empty}) of $s$ and rotate it right by one position.\n\nIn other words, you can select a sequence of indices $b_1, b_2, \\ldots, b_m$, where $1 \\le b_1 < b_2 < \\ldots < b_m \\le 2n$. After that you \\textbf{simultaneously} set $$s_{b_1} := s_{b_m},$$ $$s_{b_2} := s_{b_1},$$ $$\\ldots,$$ $$s_{b_m} := s_{b_{m-1}}.$$\n\nCan you partition $s$ into two \\textbf{disjoint equal} subsequences after performing the allowed operation \\textbf{exactly} once?\n\nA partition of $s$ into two disjoint equal subsequences $s^p$ and $s^q$ is two \\textbf{increasing} arrays of indices $p_1, p_2, \\ldots, p_n$ and $q_1, q_2, \\ldots, q_n$, such that each integer from $1$ to $2n$ is encountered in either $p$ or $q$ exactly once, $s^p = s_{p_1} s_{p_2} \\ldots s_{p_n}$, $s^q = s_{q_1} s_{q_2} \\ldots s_{q_n}$, and $s^p = s^q$.\n\nIf it is not possible to partition after performing any kind of operation, report $-1$.\n\nIf it is possible to do the operation and partition $s$ into two disjoint subsequences $s^p$ and $s^q$, such that $s^p = s^q$, print elements of $b$ and indices of $s^p$, i. e. the values $p_1, p_2, \\ldots, p_n$.",
    "tutorial": "It is easy to see that a necessary condition for a solution to exist is that the number of $1$ in $s$ should be even. It turns out that this condition is sufficient too. Here is one valid construction: We make $n$ pairs of the form $(s[2i-1],s[2i])$ for $(1 \\leq i \\leq n)$. Assume we have $x$ pairs in which both elements are different and $n-x$ pairs in which both elements are same. \\textbf{Claim} - $x$ should be even. \\textbf{Proof} - Assume that among the $n-x$ pairs in which both elements are same, we have $y$ pairs in which both elements are $1$. So number of $1$ in $s$ is $x+2 \\cdot y$. We know that number of $1$ in $s$ is even, so for $x+2 \\cdot y$ to be even, $x$ should also be even. Now we will select $x$ indices; exactly one index from each of the $x$ pairs in which both elements are distinct. Take the index of $0$ from $i_{th}$ pair if $i$ is odd, else take the index of $1$. Thus our selected characters = ${0,1,0,1, \\dots ,0,1}$ Now on cyclically shifting the selected characters clockwise once, we can see that elements at selected indices got flipped. Since, elements in those $x$ pairs were distinct initially, and we flipped exactly one character from each of those $x$ pairs, both elements of those $x$ pairs are same now. Hence, in updated $s$, $s[2i-1]=s[2i]$. So, for $s_1$, we can select characters of all odd indices. Finally we'll have $s_1 = s_2$. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nvoid solve(){\n    ll n; cin>>n;\n    string s; cin>>s;\n    ll freq=0;\n    vector<ll> ans;\n    ll need=0;\n    for(ll i=0;i<2*n;i+=2){\n        if(s[i]!=s[i+1]){\n            freq++;\n            ans.push_back(i+1);\n            if(s[i]-'0'!=need){\n                ans.back()++;\n            }\n            need^=1;\n        }\n    }\n    if(freq&1){\n        cout<<\"-1\\n\";\n        return;\n    }\n    cout<<ans.size()<<\" \";\n    for(auto it:ans){\n        cout<<it<<\" \";\n    }\n    cout<<\"\\n\";\n    for(ll i=1;i<=2*n;i+=2){\n        cout<<i<<\" \\n\"[i+1==2*n];\n    }\n}\nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t; cin>>t;\n    while(t--){\n        solve();\n    }\n}  ",
    "tags": [
      "constructive algorithms",
      "geometry",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1736",
    "index": "E",
    "title": "Swap and Take",
    "statement": "You're given an array consisting of $n$ integers. You have to perform $n$ turns.\n\nInitially your score is $0$.\n\nOn the $i$-th turn, you are allowed to leave the array as it is or swap any one pair of $2$ adjacent elements in the array and change exactly one of them to $0$(and leave the value of other element unchanged) after swapping. In either case(whether you swap or not), after this you add $a_i$ to your score.\n\nWhat's the maximum possible score you can get?",
    "tutorial": "As the constraints suggest, we should use dp to solve this problem. Let's write the original indices of the array that are added during this process - $p_1, p_2, \\ldots, p_n$. None of added numbers are zeroed in an optimal answer. It gives that $p_1 \\le p_2 \\le \\ldots \\le p_n$ and the answer is equal to the sum of $a[p_k]$ ($1 \\leq k \\leq n$). To get the optimal answer we'll use $dp[t][last][m]$ = maximum score on $t$-th turn if $p_t = last$ and we have performed $m$ swapping moves (the first dimension can be omitted). Note that $m \\leq i$. It can be updated by considering the next index but it will take $O(n^4)$. The most straightforward way to improve it to $O(n^3)$ is to use prefix maximums. Here are some details. We have only two cases: $p_t=p_{t-1}$ - In this case, our transition is just $dp[t][last][m]=dp[t-1][last][m-1]+a[last]$ $p_t=p_{t-1}$ - In this case, our transition is just $dp[t][last][m]=dp[t-1][last][m-1]+a[last]$ $p_t > p_{t-1}$ - Let us make some observations. First of all, $p_t \\ge t$. So number of swaps to bring $p_t$ to index $t$ is fixed. It is $p_t-t$. So $dp[t][last][m]=\\max_{j=1}^{last-1} (dp[t-1][j][m-(p_t-t)])+a[last]$. Note that we can find $\\max_{j=1}^{last-1} (dp[t-1][j][m-(p_t-t)])$ in $O(1)$. Hint - use prefix maximum. $p_t > p_{t-1}$ - Let us make some observations. First of all, $p_t \\ge t$. So number of swaps to bring $p_t$ to index $t$ is fixed. It is $p_t-t$. So $dp[t][last][m]=\\max_{j=1}^{last-1} (dp[t-1][j][m-(p_t-t)])+a[last]$. Note that we can find $\\max_{j=1}^{last-1} (dp[t-1][j][m-(p_t-t)])$ in $O(1)$. Hint - use prefix maximum. Time complexity is $O(n^3)$.",
    "code": "#include <bits/stdc++.h>   \nusing namespace std;\nconst int MAX=505; \nvector<vector<vector<int>>> dp(MAX,vector<vector<int>>(MAX,vector<int>(MAX,-(int)(1e9))));\nint main()                                                                          \n{                        \n    int n; cin>>n;\n    vector<int> a(n+5);\n    for(int i=1;i<=n;i++){\n        cin>>a[i];\n    }\n    vector<vector<int>> prefix(n+5,vector<int>(n+5,0));\n    int ans=0;  \n    for(int i=1;i<=n;i++){\n        for(int j=1;j<=n;j++){ \n            for(int k=0;k<=i;k++){\n                if(k){ \n                    dp[i][j][k]=dp[i-1][j][k-1]+a[j];\n                }\n                if(j>=i){\n                    int need=j-i;\n                    if(need>k){\n                        continue;\n                    }\n                    dp[i][j][k]=max(dp[i][j][k],prefix[k-need][j-1]+a[j]); \n                }\n            }\n        }\n        for(int j=1;j<=n;j++){\n            for(int k=0;k<=i;k++){\n                prefix[k][j]=max(prefix[k][j],dp[i][j][k]); \n            }\n        }\n        for(int j=0;j<=i;j++){\n            for(int k=1;k<=n;k++){\n                prefix[j][k]=max(prefix[j][k],prefix[j][k-1]);\n                ans=max(ans,prefix[j][k]);\n            }\n        }\n    }\n    cout<<ans;\n} ",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1737",
    "index": "A",
    "title": "Ela Sorting Books",
    "statement": "\\begin{tabular}{ll}\n& Ela loves reading a lot, just like her new co-workers in DTL! On her first day after becoming an engineer in DTL, she is challenged by a co-worker to sort a heap of books into different compartments on the shelf. \\\n\\end{tabular}\n\n$n$ books must be split into $k$ compartments on the bookshelf ($n$ is divisible by $k$). Each book is represented by a lowercase Latin letter \\textbf{from 'a' to 'y'} inclusively, which is the beginning letter in the title of the book.\n\nEla must stack \\textbf{exactly} $\\frac{n}{k}$ books in each compartment. After the books are stacked, for each compartment indexed from $1$ to $k$, she takes the \\textbf{minimum excluded (MEX)} letter of the multiset of letters formed by letters representing all books in that compartment, then combines the resulting letters into a string. The first letter of the resulting string is the MEX letter of the multiset of letters formed by the first compartment, the second letter of the resulting string is the MEX letter of the multiset of letters formed by the second compartment, ... and so on. Please note, under the constraint of this problem, \\textbf{MEX letter can always be determined for any multiset found in this problem} because 'z' is not used.\n\nWhat is the \\textbf{lexicographically greatest} resulting string possible that Ela can create?\n\nA string $a$ is lexicographically greater than a string $b$ if and only if one of the following holds:\n\n- $b$ is a prefix of $a$, but $b \\ne a$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears later in the alphabet than the corresponding letter in $b$.\n\nThe minimum excluded (MEX) letter of a multiset of letters is the letter that appears earliest in the alphabet and is not contained in the multiset. For example, if a multiset of letters contains $7$ letters 'b', 'a', 'b', 'c', 'e', 'c', 'f' respectively, then the MEX letter of this compartment is 'd', because 'd' is not included in the multiset, and all letters comes before 'd' in the alphabet, namely 'a', 'b' and 'c', are included in the multiset.",
    "tutorial": "We'll iterate through compartments from $1$ to $K$. we'll try to put 1 'a' book in it, so the MEX in that compartment will not be 'a'. If any compartment can't be filled by 'a' because we ran out of 'a', the MEX of that compartment will have to be 'a'. The same logic applies to 'b', 'c', 'd', ..., where for each compartment from $1$, if the MEX of that compartment hasn't been determined, we'll fill the corresponding letter there. We'll stop when reaching the end of the alphabet, or we've reached the ($\\frac{N}{K}$)-th letter in the alphabet (because the first compartment is already full).",
    "code": "...\nvoid execute(int test_number)\n{\n  cin>>n>>k>>str;\n  vector <int> count_char(26, 0);\n  for (char c: str) count_char[c - 'a']++;\n  string ans = \"\";\n  for (int i = 0; i < min(25, n/k); i++) {\n    while (k - ans.size() > count_char[i]) {\n      ans.push_back(i + 'a');\n    }\n  }\n\n  char c = 'a' + min(n / k, 25);\n  while (k > ans.size()) {\n    ans += c;\n  }\n  reverse(ans.begin(), ans.end());\n  cout << ans << \"\\n\";\n}\n...",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1737",
    "index": "B",
    "title": "Ela's Fitness and the Luxury Number",
    "statement": "\\begin{tabular}{ll}\n& While working at DTL, Ela is very aware of her physical and mental health. She started to practice various sports, such as Archery, Yoga, and Football. \\\n\\end{tabular}\n\nSince she started engaging in sports activities, Ela switches to trying a new sport on days she considers being \"Luxury\" days. She counts the days since she started these activities, in which the day she starts is numbered as day $1$. A \"Luxury\" day is the day in which the number of this day is a luxurious number.\n\nAn integer $x$ is called a luxurious number if it is divisible by ${\\lfloor \\sqrt{x} \\rfloor}$.\n\nHere $\\lfloor r \\rfloor$ denotes the \"floor\" of a real number $r$. In other words, it's the largest integer not greater than $r$.\n\nFor example: $8$, $56$, $100$ are luxurious numbers, since $8$ is divisible by $\\lfloor \\sqrt{8} \\rfloor = \\lfloor 2.8284 \\rfloor = 2$, $56$ is divisible $\\lfloor \\sqrt{56} \\rfloor = \\lfloor 7.4833 \\rfloor = 7$, and $100$ is divisible by $\\lfloor \\sqrt{100} \\rfloor = \\lfloor 10 \\rfloor = 10$, respectively. On the other hand $5$, $40$ are not, since $5$ are not divisible by $\\lfloor \\sqrt{5} \\rfloor = \\lfloor 2.2361 \\rfloor = 2$, and $40$ are not divisible by $\\lfloor \\sqrt{40} \\rfloor = \\lfloor 6.3246 \\rfloor = 6$.\n\nBeing a friend of Ela, you want to engage in these fitness activities with her to keep her and yourself accompanied (and have fun together, of course). Between day $l$ and day $r$, you want to know how many times she changes the activities.",
    "tutorial": "We shift the perspective to see the pattern from $\\lfloor \\sqrt{x} \\rfloor$, instead of $x$, to see what kind of patterns are needed so $x$ can be luxurious. Note that: ${(a + 1)}^2 - 1 = a * (a + 2)$. Therefore, every half-closed segment $[a^2, (a + 1) ^ 2)$ contains exactly $3$ luxurious number: $a^2$, $a * (a + 1)$ and $a * (a + 2)$. Also note that, since large numbers can cause inaccuracies in floating point computation, we should use binary search to find the floor-value of a square root, instead of using the sqrt function in any language.",
    "code": "...\nll l, r;\n\nll bs_sqrt(ll x) {\n  ll left = 0, right = 2000000123;\n  while (right > left) {\n      ll mid = (left + right) / 2;\n      \n      if (mid * mid > x) right = mid;\n      else left = mid + 1;\n  }\n  return left - 1;\n}\n\n// main solution goes here:\nvoid execute(int test_number)\n{\n  cin >> l >> r;\n  ll sql = bs_sqrt(l), sqr = bs_sqrt(r);\n  ll ans;\n  if (sql == sqr) {\n    ans = 0;\n    for (int i = 0; i < 3; i++) {\n      if (l <= sql * (sql + i) && sql * (sql + i) <= r) ans++;\n    }\n  } else {\n    ans = (sqr - sql - 1) * 3;\n    for (int i = 0; i < 3; i++) {\n      if (l <= sql * (sql + i) && sql * (sql + i) <= r) ans++;\n      if (l <= sqr * (sqr + i) && sqr * (sqr + i) <= r) ans++;\n    }\n  }\n  cout << ans << \"\\n\";\n}\n...",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1737",
    "index": "C",
    "title": "Ela and Crickets",
    "statement": "\\begin{tabular}{ll}\n& Ela likes Chess a lot. During breaks, she usually challenges her co-worker in DTL to some chess games. She's not an expert at classic chess, but she's very interested in Chess variants, where she has to adapt to new rules and test her tactical mindset to win the game. \\\n\\end{tabular}\n\nThe problem, which involves a non-standard chess pieces type that is described below, reads: given $3$ white \\textbf{crickets} on a $n \\cdot n$ board, arranged in an \"L\" shape next to each other, there are no other pieces on the board. Ela wants to know with a finite number of moves, can she put any white cricket on the square on row $x$, column $y$?\n\nAn \"L\"-shape piece arrangement can only be one of the below:\n\n\\begin{center}\n\\begin{tabular}{cc}\n& \\\n\\end{tabular}\n\\end{center}\n\n\\begin{center}\n\\begin{tabular}{cc}\n& \\\n\\end{tabular}\n\\end{center}\n\nFor simplicity, we describe the rules for crickets on the board where only three white crickets are. It can move horizontally, vertically, or diagonally, but only to a square in some direction that is \\textbf{immediately after} another cricket piece (so that it must \\textbf{jump over} it). If the square immediately behind the piece is unoccupied, the cricket will occupy the square. Otherwise (when the square is occupied by another cricket, or does not exist), the cricket isn't allowed to make such a move.\n\nSee an example of valid crickets' moves on the pictures in the Note section.",
    "tutorial": "The initial configuration will have one central piece and 2 non-central pieces. The central piece is the one on the square that shares the edges with both of the 2 other squares. As the crickets are standing next to each other, we can prove that each of them can only jump into another square with the same color of the square it's standing on. Assuming that the central piece are on the dark square, we consider 3 cases: The central piece initially lies on the corner of the board (restrict the moves of the crickets): can only move pieces to squares on the edges they cover. The target square is dark: we can prove that there is always a way to line up 2 pieces on the same-colored squares with the target square diagonally. The target square is light: we can see that the only piece on the white square can only move 2 squares horizontally/vertically, not diagonally in any way, so if the target square x-coordinates has the same oddity as the original square x-coordinate of the light, then it's possible. Otherwise, it's not. For the case of 2 lights, and 1 dark, use the same reasoning. Complexity: $O(1)$",
    "code": "...\nint n;\nint x[3], y[3];\nint u, v;\n\npii centralSquare() {\n  int a = (x[0] == x[1]) ? x[0] : x[2];\n  int b = (y[0] == y[1]) ? y[0] : y[2];\n  return {a, b};\n}\n// main solution goes here:\nvoid execute(int test_number)\n{\n  cin>>n;\n  for (int i=0; i<3; i++) cin>>x[i]>>y[i];\n  cin>>u>>v;\n\n  int cx = centralSquare().first, cy = centralSquare().second;\n\n  if ((cx == 1 || cx == n) && (cy == 1 || cy == n)) { // \"corner\" case, literally\n    // the crickets can only reach coordinates within the edges that already contains at least 2 crickets,\n    // which contains the centralSquare of the L\n    cout << ((u == cx || v == cy) ? \"YES\\n\" : \"NO\\n\");\n  } else {\n    if ((cx + cy) % 2 == (u + v) % 2) {\n      cout << (cx % 2 == u % 2 ? \"YES\\n\" : \"NO\\n\"); \n    } else { // can be prove to always reach, since we have ways to align 2 crickets in the same diagonal as target\n      cout << \"YES\\n\"; \n    }\n  }\n}\n...",
    "tags": [
      "constructive algorithms",
      "games",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1737",
    "index": "D",
    "title": "Ela and the Wiring Wizard",
    "statement": "Ela needs to send a large package from machine $1$ to machine $n$ through a network of machines. Currently, with the network condition, she complains that the network is too slow and the package can't arrive in time. Luckily, a Wiring Wizard offered her a helping hand.\n\nThe network can be represented as an \\textbf{undirected connected graph} with $n$ nodes, each node representing a machine. $m$ wires are used to connect them. Wire $i$ is used to connect machines $u_i$ and $v_i$, and has a weight $w_i$. The aforementioned large package, if going through wire $i$, will move from machine $u_i$ to machine $v_i$ (or vice versa) in exactly $w_i$ microseconds. The Wiring Wizard can use his spell an arbitrary number of times. For each spell, he will choose the wire of index $i$, connecting machine $u_i$ and $v_i$, and rewire it following these steps:\n\n- Choose one machine that is connected by this wire. Without loss of generality, let's choose $v_i$.\n- Choose a machine that is currently connecting to $v_i$ (including $u_i$), call it $t_i$. Disconnect the wire indexed $i$ from $v_i$, then using it to connect $u_i$ and $t_i$.\n\nThe rewiring of wire $i$ will takes $w_i$ microseconds, and the weight of the wire will not change after this operation. After a rewiring, a machine might have some wire connect it with itself. Also, the Wiring Wizard has warned Ela that rewiring might cause temporary disconnections between some machines, but Ela just ignores it anyway. Her mission is to send the large package from machine $1$ to machine $n$ as fast as possible. Note that the Wizard can use his spell on a wire zero, one, or many times. To make sure the network works seamlessly while transferring the large package, \\textbf{once the package starts transferring from machine $1$, the Wiring Wizard cannot use his spell to move wires around anymore.}\n\nEla wonders, with the help of the Wiring Wizard, what is the least amount of time needed to transfer the large package from machine $1$ to $n$.",
    "tutorial": "Note that you can turn $(u, v)$ edge into a self loop $(u, u)$ in a single operation. We can prove that it is always better to make an edge directly connect $1$ and $n$. Denote the index of that edge as $i$, and $\\text{dist}[u][v]$ as the shortest path from $u$ to $v$ on the unweighted version of the input graph. There are two cases: Connect $u_i$ to $1$ and $v_i$ to $n$ (and vice-versa) directly. The cost is $\\text{dist}[u_i][1] + \\text{dist}[v_i][n] + 1$ multiplied by $w_i$. Connect $1$, $n$ and $u_i$ through an intermediate vertex $x$. Then we will follow the shortest path from $u_i$ to $x$, connect $v_i$ to $x$, then create a self loop $(x, x)$. After that one of the edges will follow the path from $x$ to $1$, the other one will go from $x$ to $n$, and we are able to create an edge $(1, n)$ with weight $w$. The similar procedure is used to connect $1$, $n$ and $v_i$. The cost of the transformation is $\\text{dist}[1][x] + \\text{dist}[x][n] + \\text{dist}[u_i][x] + 2$ multiplied by $w_i$. We may use BFS or Floyd algorithm in order to calculate $\\text{dist}[u][v]$. The final complexity is $O(n^3)$.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\n#define db long double\n#define ull unsigned long long\n#define x first\n#define y second\n#define mp make_pair\n#define pb push_back\n#define all(a) a.begin(), a.end()\n\nusing namespace std;\n\n#define pper(a) cerr << #a << \" = \" << a << endl;\n\nvoid per() { cerr << endl; }\ntemplate<typename Head, typename... Tail> void per(Head H, Tail... T) { cerr << H << ' '; per(T...); }\n\ntemplate<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }\ntemplate<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }\n\ntemplate<class U, class V> \nostream& operator<<(ostream& out, const pair<U, V>& a) {\n  return out << \"(\" << a.x << \", \" << a.y << \")\";\n}\n\ntemplate<class U, class V> \nistream& operator>>(istream& in, pair<U, V>& a) {\n  return in >> a.x >> a.y;\n}\n\ntemplate<typename W, typename T = typename enable_if<!is_same<W, string>::value, typename W::value_type>::type>\nostream& operator<<(ostream& out, const W& v) { out << \"{ \"; for (const auto& x : v) out << x << \", \"; return out << '}'; }\n\ntemplate<class T>\nvoid readArr(T from, T to) {\n  for (auto i = from; i != to; ++i) cin >> *i;\n}\n\nmt19937 mrand(1337); \nunsigned int myRand32() {\n  return mrand() & (unsigned int)(-1);\n}\n \nunsigned ll myRand64() {\n  return ((ull)myRand32() << 32) ^ myRand32();\n}\n\nconst int mod = 1000000007;\n\nvoid add(int& a, int b) {\n  a += b; if (a >= mod) a -= mod;\n}\n\nvoid dec(int &a, int b) {\n  a -= b; if (a < 0) a += mod;\n}\n\nint mult(int a, int b) {\n  return a * (ll)b % mod;\n}\n\nint bp(int a, int b) {\n  int res = 1;\n  while (b > 0) {\n    if (b & 1) res = mult(res, a);\n    a = mult(a, a);\n    b >>= 1;\n  }\n  return res;\n}\n\nconst int N = 507;\n\nll f[N][N];\n\nint main(){\n#ifdef LOCAL\n\tfreopen(\"N_input.txt\", \"r\", stdin);\n\t//freopen(\"N_output.txt\", \"w\", stdout);\n#endif\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\n  int t;\n  cin >> t;\n\n  for (int a = 0; a < t; ++a) {\n\n    int n, m;\n    cin >> n >> m;\n\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < n; ++j) {\n        f[i][j] = 1e18;\n      }\n      f[i][i] = 0;\n    }\n\n    vector<tuple<int, int, int> > ed;\n\n    for (int i = 0; i < m; ++i) {\n      int u, v, w;\n      cin >> u >> v >> w;\n      ed.pb(make_tuple(u - 1, v - 1, w));\n      f[u - 1][v - 1] = 1;\n      f[v - 1][u - 1] = 1;\n    }\n\n    for (int k = 0; k < n; ++k) {\n      for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n          f[i][j] = min(f[i][j], f[i][k] + f[k][j]);\n        }\n      }\n    }\n\n    ll ans = 1e18;\n    for (auto x : ed) {\n      int u = get<0>(x);\n      int v = get<1>(x);\n      int w = get<2>(x);\n\n//      per(ans, u, v, w);\n\n      ans = min(ans, (ll) w * (f[0][u] + f[n - 1][v] + 1));\n      ans = min(ans, (ll) w * (f[0][v] + f[n - 1][u] + 1));\n\n  //    per(ans, u, v, w);\n\n      for (int i = 0; i < n; ++i) {\n        ans = min(ans, (ll) w * (f[v][i] + 1 + f[i][0] + f[i][n-1] + 1));\n        ans = min(ans, (ll) w * (f[u][i] + 1 + f[i][0] + f[i][n-1] + 1));\n      }\n\n    }\n\n    cout << ans << '\\n';\n\n  }\n}",
    "tags": [
      "brute force",
      "dp",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1737",
    "index": "E",
    "title": "Ela Goes Hiking",
    "statement": "\\begin{tabular}{ll}\n& Ela likes to go hiking a lot. She loves nature and exploring the various creatures it offers. One day, she saw a strange type of ant, with a \\textbf{cannibalistic} feature. More specifically, an ant would eat any ants that it sees which is smaller than it.Curious about this feature from a new creature, Ela ain't furious. She conducts a long, non-dubious, sentimental experiment. \\\n\\end{tabular}\n\nShe puts $n$ cannibalistic ants in a line on a long wooden stick. Initially, the ants have the same weight of $1$. The distance between any two consecutive ants is the same. The distance between the first ant in the line to the left end and the last ant in the line to the right end is also the same as the distance between the ants. Each ant starts moving towards the left-end or the right-end randomly and equiprobably, at the same constant pace throughout the experiment. Two ants will crash if they are standing next to each other in the line and moving in opposite directions, and ants will change direction immediately when they reach the end of the stick. Ela can't determine the moving direction of each ant, but she understands very well their behavior when crashes happen.\n\n- If a crash happens between two ants of different weights, the heavier one will eat the lighter one, and gain the weight of the lighter one. After that, the heavier and will continue walking in the same direction. In other words, if the heavier one has weight $x$ and walking to the right, the lighter one has weight $y$ and walking to the left ($x > y$), then after the crash, the lighter one will diminish, and the heavier one will have weight $x + y$ and continue walking to the right.\n- If a crash happens between two ants with the same weight, the one walking to the left end of the stick will eat the one walking to the right, and then continue walking in the same direction. In other words, if one ant of weight $x$ walking to the left, crashes with another ant of weight $x$ walking to the right, the one walking to the right will disappear, and the one walking to the left will have to weight $2x$ and continue walking to the left.\n\nPlease, check the example in the \"Note\" section, which will demonstrate the ants' behavior as above.\n\nWe can prove that after a definite amount of time, there will be only one last ant standing. Initially, each ant can randomly and equiprobably move to the left or the right, which generates $2^n$ different cases of initial movements for the whole pack. For each position in the line, calculate the probability that the ant begins in that position and survives. Output it modulo $10^9 + 7$.\n\nFormally, let $M = 10^9 + 7$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "The first ant will die if there are more than $1$ ants since it doesn't have any way to eat other ants (initially no ants have a weight less than it, and no ants are on the left of it). Call $f(i)$ the probability for the $i$-th ants to be the last one standing in the ants from $1$ to $2i - 1$. $i$ will be the last one standing between them if $i$ is walking to the left and there are $\\frac{i-1}{2}$ consecutive ants standing right to the left of it walking to the right. In other words: $i$ will survive if every ant from $\\lfloor \\frac{i + 2}{2} \\rfloor$-th to $(i - 1)$-th ant all walking to the right and $i$ itself walking to the left. Therefore: $f(i) = \\frac{1}{2^{\\frac{i+1}{2}}}$. Except for when $i = n$, that's when whichever direction the $n$-th ant is walking to, it will eventually change direction into walking left: $f(n) = \\frac{1}{2^{\\frac{n-1}{2}}}$. Note that $f(i)$ won't take into account ants from $2i$ to $n$. $g(i)$ will be the probability for the $i$-th ants to be the last one standing in the ants from $1$ to $n$. This holds 2 conditions accountable: - $i$ can survive for ants between $1$ and $2i - 1$, which only dependent on how ants from $\\frac{i-1}{2}$ to $i$ is moving. We already calculated that using $f(i)$ - Ant from $2i$, $2i - 1$ ... $n$ cannot survive, which only dependent on how ants from $i+1$ to $n$ is moving, we can calculate this using $1 - g(2i) - g(2i + 1) - .. - g(n)$. $g(i)$ = $f(i) * (1 - g(2i) - g(2i + 1) - .. - g(n))$ The answer for each $x$ is $g(x)$",
    "code": "...\n// data preprocessing: (e.g.: divisor generating, prime sieve)\nll POW2[mn];\nvoid preprocess()\n{\n  POW2[0] = 1;\n  for (int i = 1; i < mn; i++) POW2[i] = POW2[i &mdash; 1] * 2 % mod;\n}\n \n// global variables:\nll n;\n \nll POW(ll u, ll v) {\n  if (v == 0) return 1;\n  ll mid = POW(u, v / 2);\n  mid = (mid * mid) % mod;\n  return (v & 1) ? (mid * u % mod) : mid;\n}\n// main solution goes here:\nvoid execute(int test_number)\n{\n  cin>>n;\n \n  if (n == 1) {\n    cout << \"1\\n\";\n    return;\n  }\n  vector <ll> ans(n + 1, 0), sufsum(n + 1, 0);\n  sufsum[n] = ans[n] = POW(POW2[(n &mdash; 1) / 2], mod &mdash; 2);\n  for (int i = n &mdash; 1; i > 1; i--) {\n    ans[i] = POW(POW2[(i + 1) / 2], mod &mdash; 2);\n    if (2 * i <= n) ans[i] = ans[i] * (1 &mdash; sufsum[i * 2] + mod) % mod;\n    sufsum[i] = (sufsum[i + 1] + ans[i]) % mod;\n  }\n  for (int i = 1; i <= n; i++) cout << ans[i] << \"\\n\";\n \n}\n...",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1737",
    "index": "F",
    "title": "Ela and Prime GCD",
    "statement": "\\begin{tabular}{ll}\n& After a long, tough, but fruitful day at DTL, Ela goes home happily. She entertains herself by solving Competitive Programming problems. She prefers short statements, because she already read too many long papers and documentation at work. The problem of the day reads: \\\n\\end{tabular}\n\nYou are given an integer $c$. Suppose that $c$ has $n$ divisors. You have to find a sequence with $n - 1$ integers $[a_1, a_2, ... a_{n - 1}]$, which satisfies the following conditions:\n\n- Each element is strictly greater than $1$.\n- Each element is a divisor of $c$.\n- All elements are distinct.\n- For all $1 \\le i < n - 1$, $\\gcd(a_i, a_{i + 1})$ is a prime number.\n\nIn this problem, because $c$ can be too big, the result of prime factorization of $c$ is given instead. Note that $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$ and a prime number is a positive integer which has exactly $2$ divisors.",
    "tutorial": "Author: constructive Observation: Assume that x is composite number and divisor of n. Among all the multiples of x, the number of the divisor of n must be less than or equal to m/2. First, factorize n. Assume that w is divisor of n. If w is in the form of a^4, a^3b^2, or a^2b^2c^2, it can be proved that there is no answer. Otherwise, there can be two cases. If the possible maximum exponent of prime factor is 2, place the divisors like this: 1 a^2b^2 b a^2b b^2 ab a^2 ab^2 a / 1 a^2 a. And expand the sequence as follows: Repeat the current sequence twice - 1 a^2b^2 b a^2b b^2 ab a^2 ab^2 a 1 a^2b^2 b a^2b b^2 ab a^2 ab^2 a / 1 a^2 a 1 a^2 a. Multiply the odd-indexed elements of first half and the even-indexed elements of second half by the new prime factor. Index 1 is exception - 1 a^2b^2 bc a^2b b^2c ab a^2c ab^2 ac c a^2b^2c b a^2bc b^2 abc a^2 ab^2c a / 1 a^2 ab b a^2b a. If more prime factor exists, jump to \"Otherwise\". Otherwise, place the divisors like this: 1 a^3 a a^2 / 1 a. Now the exponents of other prime factors are all 1, and we can expand the sequence as follows: Repeat the current sequence twice - 1 a^3 a a^2 1 a^3 a a^2 / 1 a 1 a. Multiply the even-indexed elements of first half and the odd-indexed elements of second half by the new prime factor - 1 a^3b a a^2b b a^3 ab a^2 / 1 ab b a. 3-1. If the maximum exponent is 3, swap a and b - 1 a^3b b a^2b a a^3 ab a^2 3-2. Otherwise, swap b and ab - 1 b ab a. Like this, we can expand the sequence",
    "code": "#import<bits/stdc++.h>\n#define endl '\\n'\nusing namespace std;\n\nint m, t, b[18], check[18], cnt[5];\nvector<int>v;\nvector<vector<int>>a;\n\nvoid initialize(int m)\n{\n\tfill(b, b + m + 1, 0);\n\tfill(check, check + m + 1, 0);\n\tfill(cnt, cnt + 5, 0);\n\tv.clear();\n\ta.clear();\n}\nvoid insert1(int p1, int c1)\n{\n\tv[p1] = c1;\n\ta.push_back(v);\n}\nvoid insert2(int p1, int p2, int c1, int c2)\n{\n\tv[p1] = c1;\n\tv[p2] = c2;\n\ta.push_back(v);\n}\n\nvoid f1(int x)\n{\n\tint n = a.size();\n\tfor(int i = 0; i < n; i++)a.push_back(a[i]);\n\tfor(int i = 0; i < n; i += 2)\n\t{\n\t\ta[i + 1][x] = 1;\n\t\ta[i + n][x] = 1;\n\t}\n\tswap(a[n / 2], a[n]);\n}\nvoid f2(int x)\n{\n\tint n = a.size();\n\tfor(int i = 0; i < n; i++)a.push_back(a[i]);\n\tfor(int i = 1; i < n; i += 2)\n\t{\n\t\ta[i + 1][x] = 1;\n\t\ta[i + n][x] = 1;\n\t}\n\ta[n][x] = 1;\n}\nvoid f3(int x)\n{\n\tint n = a.size();\n\tfor(int i = 0; i < n; i++)a.push_back(a[i]);\n\tfor(int i = 0; i < n; i += 2)\n\t{\n\t\ta[i + 1][x] = 1;\n\t\ta[i + n][x] = 1;\n\t}\n\tswap(a[n], a[2 * n &mdash; 1]);\n}\n\nint main()\n{\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tfor(cin >> t; t--;)\n\t{\n\t\tcin >> m;\n\t\tfor(int i = 1; i <= m; i++)\n\t\t{\n\t\t\tcin >> b[i];\n\t\t\tcnt[min(b[i], 4)]++;\n\t\t}\n\t\tif(cnt[4] || cnt[3] >= 2 || cnt[3] && cnt[2] || cnt[2] >= 3)\n\t\t{\n\t\t\tcout << -1 << endl;\n\t\t\tinitialize(m);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tfor(int i = 1; i <= m; i++)v.push_back(0);\n\t\ta.push_back(v);\n\t\t\n\t\tif(cnt[2])\n\t\t{\n\t\t\tint p1 = -1, p2 = -1;\n\t\t\tfor(int i = 1; i <= m; i++)\n\t\t\t{\n\t\t\t\tif(b[i] == 2)\n\t\t\t\t{\n\t\t\t\t\tif(~p1)p2 = i - 1;\n\t\t\t\t\telse p1 = i - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(~p2)\n\t\t\t{\n\t\t\t\tinsert2(p1, p2, 2, 2);\n\t\t\t\tinsert2(p1, p2, 0, 1);\n\t\t\t\tinsert2(p1, p2, 2, 1);\n\t\t\t\tinsert2(p1, p2, 0, 2);\n\t\t\t\tinsert2(p1, p2, 1, 1);\n\t\t\t\tinsert2(p1, p2, 2, 0);\n\t\t\t\tinsert2(p1, p2, 1, 2);\n\t\t\t\tinsert2(p1, p2, 1, 0);\n\t\t\t\tcheck[p1 + 1] = check[p2 + 1] = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tinsert1(p1, 2);\n\t\t\t\tinsert1(p1, 1);\n\t\t\t\tcheck[p1 + 1] = 1;\n\t\t\t}\n\t\t\tfor(int i = 1; i <= m; i++)\n\t\t\t{\n\t\t\t\tif(check[i])continue;\n\t\t\t\tif(a.size() % 2)f2(i - 1);\n\t\t\t\telse f3(i - 1);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(cnt[3])\n\t\t\t{\n\t\t\t\tint p = 0;\n\t\t\t\tfor(int i = 1; i <= m; i++)\n\t\t\t\t{\n\t\t\t\t\tif(b[i] == 3)p = i - 1;\n\t\t\t\t}\n\t\t\t\tinsert1(p, 3);\n\t\t\t\tinsert1(p, 1);\n\t\t\t\tinsert1(p, 2);\n\t\t\t\tcheck[p + 1] = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tinsert1(0, 1);\n\t\t\t\tcheck[1] = 1;\n\t\t\t}\n\t\t\tfor(int i = 1; i <= m; i++)\n\t\t\t{\n\t\t\t\tif(!check[i])f1(i - 1);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(auto &v: a)\n\t\t{\n\t\t\tif(*max_element(v.begin(), v.end()))\n\t\t\t{\n\t\t\t\tfor(auto &p: v)cout << p << ' ';\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t}\n\t\tinitialize(m);\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1737",
    "index": "G",
    "title": "Ela Takes Dancing Class",
    "statement": "\\begin{tabular}{ll}\n& DTL engineers love partying in the weekend. Ela does, too! Unfortunately, she didn't know how to dance yet. Therefore, she decided to take a dancing class. \\\n\\end{tabular}\n\nThere are $n$ students in the dancing class, including Ela. In the final project, $n$ students will participate in a choreography described below.\n\n$n$ students are positioned on the positive side of the $Ox$-axis. The $i$-th dancer is located at $a_i > 0$. Some dancers will change positions during the dance (we'll call them movable dancers), and others will stay in the same place during a choreography (we'll call them immovable dancers). We distinguish the dancers using a binary string $s$ of length $n$: if $s_i$ equals '1', then the $i$-th dancer is movable, otherwise the $i$-th dancer is immovable.\n\nLet's call the \"positive energy value\" of the choreography $d > 0$. The dancers will perform \"movements\" based on this value.\n\nEach minute after the dance begins, the movable dancer with the \\textbf{smallest} $x$-coordinate will start moving to the right and initiate a \"movement\". At the beginning of the movement, the dancer's energy level will be initiated equally to the positive energy value of the choreography, which is $d$. Each time they move from some $y$ to $y+1$, the energy level will be decreased by $1$. At some point, the dancer might meet other fellow dancers in the same coordinates. If it happens, then the energy level of the dancer will be increased by $1$. A dancer will stop moving to the right when his energy level reaches $0$, and he doesn't share a position with another dancer.\n\nThe dancers are very well-trained, and each \"movement\" will end before the next minute begins.\n\nTo show her understanding of this choreography, Ela has to answer $q$ queries, each consisting of two integers $k$ and $m$. The answer to this query is the coordinate of the $m$-th dancer \\textbf{of both types} from the left at $k$-th minute after the choreography begins. In other words, denote $x_{k, 1}, x_{k, 2}, \\dots, x_{k, n}$ as the sorted coordinates of the dancers at $k$-th minute from the beginning, you need to print $x_{k, m}$.",
    "tutorial": "Note that the immovable dancers don't change their positions during transformations. Let's pretend that all immovable dancers disappeared. We denote an arrangement as \"good\" if the dancer in the first step jump over any other dancers (the new placement of the first dancer is greater than the position of any other dancers). Denote $C$ as the number of dancers in the arrangement. A \"good\" dancer arrangement retains some properties: After $C$ operations, the relative coordinates of dancers are untouched, and the absolute coordinates of dancers are increased by $(C - 1 + d)$. Proof: by intuition. Dancer $1$'s position is increased by $C - 1 + d$ since it goes over $C - 1$ dancers and jumps to the following $d$-th space. Dancer $2$ must jump across dancer $1$ (there aren't enough empty spaces between them), and its position will be increased by the same amount. The description is the same for others. After $i$ operations ($i < C$), the absolute coordinates of the leftmost $i$ dancers increased by $C - 1 + d$. Repeatedly increase the current arrangement by several $C - 1 + d$ until dancer $1$ can go over dancer $i$. Increase the coordinate of all the arranged dancers that lie after dancer $i$ by $1$. Push the dancer into the maintained arrangement. Let's binary search each query. We can safely remove all immovable dancers and the remaining dancers that haven't been observed, and appropriately adjust the query segment. In order to maintain the \"good\" arrangement, we may use any balanced binary search tree (treap for example). The final complexity is $O((n + q) \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n \nusing namespace std;\n \n#ifdef LOCAL\n#include \"debug.h\"\n#else\n#define debug(...) 42\n#endif\n \nusing ll = long long;\nusing ld = long double;\n \ntemplate<class T> bool uin(T &a, T b) {\n    return a > b ? (a = b, true) : false;\n}\ntemplate<class T> bool uax(T &a, T b) {\n    return a < b ? (a = b, true) : false;\n}\n \nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n \nstruct Node {\n    ll key, lazy;\n    int cnt;\n    unsigned int prior;\n    Node *l, *r;\n    Node() {}\n    Node(ll key) : key(key), lazy(0), cnt(1), prior(rng()), l(0), r(0) {}\n};\n \ninline int get_cnt(Node *t) {\n    return t ? t->cnt : 0;\n}\n \ninline void upd_cnt(Node *t) {\n    if (t) {\n        t->cnt = get_cnt(t->l) + get_cnt(t->r) + 1;\n    }\n}\n \ninline void modify(Node *t, ll delta) {\n    if (t) {\n        t->key += delta;\n        t->lazy += delta;\n    }\n}\n \ninline void down(Node *t) {\n    if (t && t->lazy) {\n        ll lazy = t->lazy;\n        t->lazy = 0;\n        if (t->l) {\n            t->l->key += lazy;\n            t->l->lazy += lazy;\n        }\n        if (t->r) {\n            t->r->key += lazy;\n            t->r->lazy += lazy;\n        }\n    }\n}\n \nvoid split(Node *t, Node *&l, Node *&r, int key, int add = 0) {\n    if (!t) {\n        l = r = 0;\n        return;\n    }\n    down(t);\n    int cur_key = add + get_cnt(t->l);\n    if (key <= cur_key) {\n        split(t->l, l, t->l, key, add);\n        r = t;\n    } else {\n        split(t->r, t->r, r, key, cur_key + 1);\n        l = t;\n    }\n    upd_cnt(t);\n}\n \nvoid split(Node *t, ll key, Node *&l, Node *&r) {\n    if (!t) {\n        l = r = 0;\n        return;\n    }\n    down(t);\n    if (t->key <= key) {\n        split(t->r, key, t->r, r);\n        l = t;\n    } else {\n        split(t->l, key, l, t->l);\n        r = t;\n    }\n    upd_cnt(t);\n}\n \nvoid merge(Node *&t, Node *l, Node *r) {\n    down(l);\n    down(r);\n    if (!l || !r) {\n        t = l ? l : r;\n    } else if (l->prior > r->prior) {\n        merge(l->r, l->r, r);\n        t = l;\n    } else {\n        merge(r->l, l, r->l);\n        t = r;\n    }\n    upd_cnt(t);\n}\n \nstruct Arrangement {\n    Node *root;\n    Arrangement() : root(0) {}\n    Arrangement(vector<ll> vec) {\n        root = 0;\n        sort(all(vec));\n        for (auto x: vec) {\n            merge(root, root, new Node(x));\n        }\n    }\n    int size() {\n        return get_cnt(root);\n    }\n    void inc_all(ll delta) {\n        modify(root, delta);\n    }\n    void inc_prefix_rev(int len, ll delta) {\n        Node *l, *r;\n        split(root, l, r, len);\n        modify(l, delta);\n        merge(root, r, l);\n    }\n    void inc_suffix_rev(int len, ll delta) {\n        Node *l, *r;\n        int C = size();\n        split(root, l, r, C - len);\n        modify(r, delta);\n        merge(root, r, l);\n    }\n    void insert(ll val) {\n        Node *l, *r;\n        split(root, val - 1, l, r);\n        modify(r, 1); // increase by 1\n        merge(root, l, new Node(val));\n        merge(root, root, r);\n    }\n    int cnt_upper_bound(ll val) {\n        int ans = 0;\n        auto t = root;\n        while (t) {\n            down(t);\n            if (t->key > val) {\n                t = t->l;\n            } else {\n                ans += get_cnt(t->l) + 1;\n                t = t->r;\n            }\n        }\n        return ans;\n    }\n    ll get_first() {\n        assert(root);\n        auto t = root;\n        while (t->l) {\n            down(t);\n            t = t->l;\n        }\n        return t->key;\n    }\n};\n \nvoid solve() {\n    int n, q;\n    ll d;\n    cin >> n >> d >> q;\n    vector<ll> a(n);\n    for (auto &x: a) {\n        cin >> x;\n    }\n    string s;\n    cin >> s;\n    for (int i = 0; i < n; i++) {\n        if (s[i] == '0') {\n            a[i] = -a[i];\n        }\n    }\n    struct Query {\n        ll k;\n        int m;\n        int id;\n        ll ans;\n    };\n    vector<Query> queries;\n    for (int i = 0; i < q; i++) {\n        int k, m;\n        cin >> k >> m;\n        queries.push_back({k, m, i, 0});\n    }\n    vector<ll> immovable;\n    for (auto x: a) {\n        if (x < 0) {\n            immovable.push_back(-x);\n        }\n    }\n    {\n        // get rid of immovable balls\n        vector<ll> new_a;\n        for (auto x: a) {\n            if (x < 0) {\n                continue;\n            }\n            int cnt = upper_bound(all(immovable), x) - immovable.begin();\n            new_a.push_back(x - cnt);\n        }\n        a = new_a;\n    }\n \n    // designated data structure\n    Arrangement arrangement({a[0]});\n    ll op = 0;\n \n    auto process_query = [&](Query &query, int i) {\n        int C = arrangement.size();\n        ll need = query.k - op;\n        ll big = need / C;\n        int small = need - big * C;\n        arrangement.inc_all(big * (C - 1 + d));\n        arrangement.inc_prefix_rev(small, C - 1 + d);\n        ll lo = 0, hi = 3e18;\n        while (hi - lo > 1) {\n            ll mid = (lo + hi) / 2;\n            ll L = mid;\n            int m = query.m;\n            int cnt = upper_bound(all(immovable), L) - immovable.begin();\n            L -= cnt;\n            m -= cnt;\n            cnt = upper_bound(i + all(a), L) - a.begin() - i;\n            L -= cnt;\n            m -= cnt;\n            if (m <= arrangement.cnt_upper_bound(L)) {\n                hi = mid;\n            } else {\n                lo = mid;\n            }\n        }\n        query.ans = hi;\n        arrangement.inc_suffix_rev(small, -(C - 1 + d));\n        arrangement.inc_all(-big * (C - 1 + d));\n    };\n \n    sort(all(queries), [](const Query &x, const Query &y) {\n        return x.k < y.k;\n    });\n \n    auto current_query = queries.begin();\n \n    for (int i = 1; i < (int)a.size(); i++) {\n        ll gap = a[i] - arrangement.get_first();\n        int C = arrangement.size();\n        ll h = (gap - 1) / (C - 1 + d);\n        while (current_query != queries.end() && current_query->k <= op + h * C) {\n            process_query(*(current_query++), i);\n        }\n        arrangement.inc_all(h * (C - 1 + d));\n        arrangement.insert(a[i]);\n        op += h * C;\n    }\n    while (current_query != queries.end()) {\n        process_query(*(current_query++), a.size());\n    }\n    sort(all(queries), [](const Query &x, const Query &y) {\n        return x.id < y.id;\n    });\n    for (auto &query: queries) {\n        cout << query.ans << \"\\n\";\n    }\n}\n \nint main() {\n    cin.tie(nullptr)->sync_with_stdio(false);\n    int T = 1;\n    // cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1738",
    "index": "A",
    "title": "Glory Addicts",
    "statement": "The hero is addicted to glory, and is fighting against a monster.\n\nThe hero has $n$ skills. The $i$-th skill is of type $a_i$ (either \\textbf{fire} or \\textbf{frost}) and has initial damage $b_i$.\n\nThe hero can perform all of the $n$ skills in any order (with each skill performed exactly \\textbf{once}). When performing each skill, the hero can play a magic as follows:\n\n- If the current skill immediately follows another skill of a different type, then its damage is \\textbf{doubled}.\n\nIn other words,\n\n- If a skill of type fire and with initial damage $c$ is performed immediately after a skill of type fire, then it will deal $c$ damage;\n- If a skill of type fire and with initial damage $c$ is performed immediately after a skill of type frost, then it will deal $2c$ damage;\n- If a skill of type frost and with initial damage $c$ is performed immediately after a skill of type fire, then it will deal $2c$ damage;\n- If a skill of type frost and with initial damage $c$ is performed immediately after a skill of type frost , then it will deal $c$ damage.\n\nYour task is to find the \\textbf{maximum} damage the hero can deal.",
    "tutorial": "Suppose the first skill to be performed is fixed. Then it is optimal to use the following greedy strategy. If possible, perform a skill of a different type from the last skill. If there are multiple skills of a different type from the last skill, choose the one with the largest initial damage. Inspired by the above observation, if the type of the first skill is fixed, it is optimal to choose the one with the smallest initial damage. This is because the first skill will be never doubled. Therefore, we have the following algorithm. Try each possible type $a$ (of the first skill). Remove the skill of type $a$ with the smallest intial damage. Alternate the types of the following skills as much as possible. This algorithm is sufficient to pass this problem. Nevertheless, a slightly more elegant analysis will give a simpler solution. If the number of skills of type fire is equal to that of skills of type frost, double the damage of all skills except for the one with the smallest initial damage. Otherwise, let $k$ be the smaller number of skills of either type, then double the damage of the largest $k$ skills of both types. The time complexity is $O(n \\log n)$ due to sortings.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n), b(n);\n\tfor (int i = 0; i < n; ++i) scanf(\"%d\", &a[i]);\n\tfor (int i = 0; i < n; ++i) scanf(\"%d\", &b[i]);\n\tvector<vector<long long>> v(2);\n\tfor (int i = 0; i < n; ++i)\n\t\tv[a[i]].push_back(b[i]);\n\tfor (int i = 0; i < 2; ++i)\n\t\tsort(v[i].begin(), v[i].end());\n \n\tauto go = [&]()\n\t{\n\t\tlong long res = 0;\n\t\tif (v[0].size() == v[1].size())\n\t\t\tres -= min(v[0].front(), v[1].front());\n\t\twhile (!v[0].empty() && !v[1].empty())\n\t\t{\n\t\t\tres += (v[0].back() + v[1].back()) * 2;\n\t\t\tv[0].pop_back();\n\t\t\tv[1].pop_back();\n\t\t}\n\t\tfor (auto x : v[0]) res += x;\n\t\tfor (auto x : v[1]) res += x;\n\t\treturn res;\n\t};\n \n\tprintf(\"%lld\\n\", go());\n}\n \nint main()\n{\n\tint tests;\n\tscanf(\"%d\", &tests);\n\twhile (tests--) solve();\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1738",
    "index": "B",
    "title": "Prefix Sum Addicts",
    "statement": "Suppose $a_1, a_2, \\dots, a_n$ is a sorted \\textbf{integer} sequence of length $n$ such that $a_1 \\leq a_2 \\leq \\dots \\leq a_n$.\n\nFor every $1 \\leq i \\leq n$, the prefix sum $s_i$ of the first $i$ terms $a_1, a_2, \\dots, a_i$ is defined by $$ s_i = \\sum_{k=1}^i a_k = a_1 + a_2 + \\dots + a_i. $$\n\nNow you are given the last $k$ terms of the prefix sums, which are $s_{n-k+1}, \\dots, s_{n-1}, s_{n}$. Your task is to determine whether this is possible.\n\nFormally, given $k$ integers $s_{n-k+1}, \\dots, s_{n-1}, s_{n}$, the task is to check whether there is a sequence $a_1, a_2, \\dots, a_n$ such that\n\n- $a_1 \\leq a_2 \\leq \\dots \\leq a_n$, and\n- $s_i = a_1 + a_2 + \\dots + a_i$ for all $n-k+1 \\leq i \\leq n$.",
    "tutorial": "If $k = 1$, it is always possible, so the answer is \"YES\". In the following, we assume that $k \\geq 2$. Here, we are given $s_{n-k+1}, \\dots, s_n$. We can resume $a_{n-k+2}, \\dots, a_{n}$ by letting $a_{i} = s_{i} - s_{i-1}$ for every $n-k+2 \\leq i \\leq n$. If the known elements of $a_i$ cannot form a sorted array, i.e., it does not hold that $a_{n-k+2} \\leq \\dots \\leq a_n$, the answer is \"NO\". Note that the sum of the first $n-k+1$ elements of $a_i$ should satisfy that $s_{n-k+1} = a_1 + \\dots + a_{n-k+1} \\leq (n-k+1) a_{n-k+2}$. If this does not hold, the answer is \"NO\". Having checked that both $a_{n-k+2} \\leq \\dots \\leq a_n$ and $s_{n-k+1} \\leq (n-k+1) a_{n-k+2}$ hold, we claim that the answer is \"YES\". A possible solution could be $a_i = \\begin{cases} \\left\\lfloor\\dfrac{s_{n-k+1}}{n-k+1}\\right\\rfloor, & 1 \\leq i \\leq s_{n-k+1} \\bmod (n-k+1), \\\\ \\left\\lceil\\dfrac{s_{n-k+1}}{n-k+1}\\right\\rceil, & s_{n-k+1} \\bmod (n-k+1) < i \\leq n-k+1. \\end{cases}$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tvector<long long> s(n + 1);\n\tfor (int i = n - k + 1; i <= n; ++i)\n\t\tcin >> s[i];\n\tif (k == 1)\n\t{\n\t\tcout << \"YES\" << endl;\n\t\treturn;\n\t}\n\tvector<long long> a(n + 1);\n\tfor (int i = n - k + 2; i <= n; ++i)\n\t\ta[i] = s[i] - s[i - 1];\n\tif (!std::is_sorted(a.begin() + n - k + 2, a.end()))\n\t{\n\t\tcout << \"NO\" << endl;\n\t\treturn;\n\t}\n\tif (s[n - k + 1] > a[n - k + 2] * (n - k + 1))\n\t{\n\t\tcout << \"NO\" << endl;\n\t\treturn;\n\t}\n\tcout << \"YES\" << endl;\n}\n \nint main()\n{\n\tint tests;\n\tcin >> tests;\n\twhile (tests--) solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1738",
    "index": "C",
    "title": "Even Number Addicts",
    "statement": "Alice and Bob are playing a game on a sequence $a_1, a_2, \\dots, a_n$ of length $n$. They move in turns and \\textbf{Alice moves first}.\n\nIn the turn of each player, he or she should select an integer and remove it from the sequence. The game ends when there is no integer left in the sequence.\n\nAlice wins if the sum of her selected integers is \\textbf{even}; otherwise, Bob wins.\n\nYour task is to determine who will win the game, if both players play optimally.",
    "tutorial": "We only need to consider the case that $a_i =$ 0 or 1. Suppose there are $a$ 0's and $b$ 1's in total. Consider the following cases: $b \\equiv 2 \\pmod 4$. Bob has a winning strategy: Always choose the number that Alice chooses in her last move. This strategy keeps the invariant that Alice and Bob have the same number of 1's after Bob's each move. The only exception that Bob cannot go on with this strategy is that Alice takes the last 0. In this case, there must be an even number of 1's (and no 0's) remaining. Therefore, each of Alice and Bob will choose half of the remaining 1's. At last, Alice and Bob have the same number $b/2$ of 1's, which is odd. $b \\equiv 3 \\pmod 4$. Alice has a winning strategy: Choose 1 first. After this move, the game is reduced to $a$ 0's and $b-1$ 1's with Bob taking the first turn and Bob wins if he has an even number of 1's at last. This reduced game is indeed the case of $b \\equiv 2 \\pmod 4$ which we have already proved that Bob always loses. $b \\equiv 0 \\pmod 4$. Alice has a winning strategy: Choose 0 first; after that, choose the number that Bob chooses in his last move. This strategy keeps the invariant that Alice and Bob have the same number of 1's after Alice's each move. The only exception that Alice cannot go on with this strategy is that there is no 0. In this case, there must be an even number of 1's (and no 0's) remaining. Therefore, each of Alice and Bob will choose half of the remaining 1's. At last, Alice and Bob have the same number $b/2$ of 1's, which is even. $b \\equiv 1 \\pmod 4$. If any of Alice and Bob chooses the first 1, the game is reduced to $a$ 0's and $b-1$ 1's with its opponent moving first, resulting in the case of $b \\equiv 0 \\pmod 4$ and its opponent wins. Therefore, the one who chooses the first 1 loses. With this observation, Alice will lose if there are an even number of $0$'s, i.e., $a \\equiv 0 \\pmod 2$; and Alice will win if $a \\equiv 1 \\pmod 2$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint u[111][111][2];\nint dp[111][111][2];\n \nint go(int x, int y, int z)\n{\n\tif (x + y == 0)\n\t\treturn z == 0;\n\tint& res = dp[x][y][z];\n\tif (u[x][y][z]) return res;\n\tu[x][y][z] = 1;\n\tif (x > 0)\n\t\tres |= 1 - go(x - 1, y, (z + y + 1) % 2);\n\tif (y > 0)\n\t\tres |= 1 - go(x, y - 1, (z + y + 1) % 2);\n\treturn res;\n}\n \nvoid solve()\n{\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (auto& e : a) cin >> e;\n\tint x = 0, y = 0;\n\tfor (auto e : a)\n\t{\n\t\tif (e % 2 == 0) x += 1; else y += 1;\n\t}\n\tint res = go(x, y, 0);\n\tcout << (res ? \"Alice\" : \"Bob\") << \"\\n\";\n}\n \nint main()\n{\n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 1; test <= tests; ++test)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "dp",
      "games",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1738",
    "index": "D",
    "title": "Permutation Addicts",
    "statement": "Given a permutation $a_1, a_2, \\dots, a_n$ of integers from $1$ to $n$, and a threshold $k$ with $0 \\leq k \\leq n$, you compute a sequence $b_1, b_2, \\dots, b_n$ as follows.\n\nFor every $1 \\leq i \\leq n$ in increasing order, let $x = a_i$.\n\n- If $x \\leq k$, set $b_{x}$ to the last element $a_j$ ($1 \\leq j < i$) that $a_j > k$. If no such element $a_j$ exists, set $b_{x} = n+1$.\n- If $x > k$, set $b_{x}$ to the last element $a_j$ ($1 \\leq j < i$) that $a_j \\leq k$. If no such element $a_j$ exists, set $b_{x} = 0$.\n\nUnfortunately, after the sequence $b_1, b_2, \\dots, b_n$ has been completely computed, the permutation $a_1, a_2, \\dots, a_n$ and the threshold $k$ are discarded.\n\nNow you only have the sequence $b_1, b_2, \\dots, b_n$. Your task is to find any possible permutation $a_1, a_2, \\dots, a_n$ and threshold $k$ that produce the sequence $b_1, b_2, \\dots, b_n$. \\textbf{It is guaranteed that} there exists at least one pair of permutation $a_1, a_2, \\dots, a_n$ and threshold $k$ that produce the sequence $b_1, b_2, \\dots, b_n$.\n\nA permutation of integers from $1$ to $n$ is a sequence of length $n$ which contains all integers from $1$ to $n$ exactly once.",
    "tutorial": "For readability and convenience of the readers who are interested in the checker of this problem, we consider this problem without assuming the existence of the threshold $k$ and permutation $a_1, a_2, \\dots, a_n$. Let's first determine the value of $k$. A valid sequence $b$ must satisfy that For every $i \\leq k$, we have $b_i > i$; For every $i > k$, we have $b_i < i$. For every $i \\leq k$, we have $b_i > k$; For every $i > k$, we have $b_i \\leq k$. Now $k$ is fixed. We are going to find a sequence $a$ that produces sequence $b$ with respect to $k$. We construct a directed graph $G$ with $n+2$ vertices numbered from $0$ to $n+1$ as follows. For every $1 \\leq i \\leq n$, add an edge from vertex $b_i$ to vertex $i$. It is clear that there are $n$ edges in graph $G$. We consider two parts of the graph $G$, set $A$ of vertices from $0$ to $k$ and set $B$ of vertices from $k+1$ to $n+1$. Then every directed edge is either from $A$ to $B$ or from $B$ to $A$. Claim B.1. There is exactly one vertex between vertex $0$ and vertex $n+1$ that is isolated (that is, no edges are incident to it). Proof: First of all, we show that it cannot be the case that both vertex $0$ and vertex $n+1$ are isolated. This is because $b_{a_1}$ is either $0$ or $n+1$ according to its definition. Now suppose both vertex $0$ and vertex $n+1$ are not isolated. Then there are two different indexes $x$ and $y$ such that $b_x = 0$ and $b_y = n+1$ with $1 \\leq y \\leq k < x \\leq n$. Find two different indexes $i$ and $j$ such that $a_i = x$ and $a_j = y$. If $i < j$, then we have $a_i = x > k \\geq a_j = y$. By the definition of $b_{y}$, $a_i = x$ is a candidate. So $b_y \\neq n+1$. If $i > j$, then we have $a_j = y \\leq k < a_i = x$. By the definition of $b_{x}$, $a_j = y$ is a candidate. So $b_x \\neq 0$. By Claim B.1, we can just ignore the isolated vertex. After that, there are $n+1$ vertices and $n$ edges. It seems like that the graph $G$ is a tree! Next, we will show that this is true. Claim B.2. The graph $G$ must not contain loops. That is, $G$ is a DAG (directed acyclic graph). Proof: There is no edge leading to vertex $0$ or $n + 1$. So loops will only occur among vertices from $1$ to $n$. Every edge $(u, v)$ in graph $G$ for $1 \\leq u, v \\leq n$ means that, in sequence $a$, the value of $u$ is in front of the value of $v$. Since sequence $a$ is a permutation, all values appear exactly once. A loop implies that there are two different vertices $u$ and $v$ such that $u$ is in front of $v$ and $v$ is in front of $u$. This is of course imposssible. $\\Box$ According to the construction of graph $G$, there is at most one edge leading to each vertex. So DAG $G$ is a rooted tree with vertex $0$ or $n+1$, with every edge $(u, v)$ meaning that $u$ is the parent of $v$. Now we have a tree $G$, and want to find a suitable sequence $a$. Claim B.3. For every vertex $u$ in tree $G$, there is at most one child vertex $v$ of $u$ that is not a leaf. Proof: If there are two child vertices $v_1$ and $v_2$ of $u$ that are not leaves, let $w_1$ and $w_2$ be child vertices of $v_1$ and $v_2$, respectively. Let $a^{-1}(x)$ the index $i$ of $x$ such that $a_i = x$. In this notation, we have $a^{-1}(u) < a^{-1}(v)$ for every edge $(u, v)$ in tree $G$. Without loss of generality, we assume that $a^{-1}(v_1) < a^{-1}(v_2)$. Then, we have $a^{-1}(v_2) < a^{-1}(w_1)$. If this is not true, i.e., $a^{-1}(v_2) > a^{-1}(w_1)$, then $w_1$ is a candidate for $b_{v_2}$, which leads that $u$ is no longer the parent vertex of $v_2$. Now we have $a^{-1}(v_2) < a^{-1}(w_1)$. This means that $v_2$ is a candidate for $b_{w_1}$, which leads that $v_1$ is no longer the parent vertex of $w_1$. A contradiction! $\\Box$ Now we are ready to give an algorithm to find a suitable sequence $a$ with tree $G$, which is rather simple: Find the BFS order of tree $G$, with non-leaf vertices visited last. Before processing the BFS, remember to check the graph $G$ as follows: There is exactly one isolated vertex between vertex $0$ and $n+1$. The graph $G$ is a DAG, i.e., no loops exist in graph $G$. With the above, graph $G$ must be a rooted tree. Choose the non-isolated vertex from vertex $0$ and $n+1$ as the root. For every vertex $u$ in tree $G$, there is at most one non-leaf child vertex of $u$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> b(n + 1);\n\tint k = 0;\n\tfor (int i = 1; i <= n; ++i)\n\t{\n\t\tscanf(\"%d\", &b[i]);\n\t\tif (b[i] > i) k = i;\n\t}\n \n\tvector<vector<int>> v(n + 2);\n\tfor (int i = 1; i <= n; ++i)\n\t\tv[b[i]].push_back(i);\n \n\tint root = v[0].size() ? 0 : n + 1;\n \n\tvector<int> q = { root };\n\tfor (int i = 0; i < q.size(); ++i)\n\t{\n\t\tint x = q[i];\n\t\tsort(v[x].begin(), v[x].end(), [&](int a, int b)\n\t\t\t{\n\t\t\t\treturn v[a].size() < v[b].size();\n\t\t\t});\n\t\tfor (auto y : v[x])\n\t\t\tq.push_back(y);\n\t}\n \n\tprintf(\"%d\\n\", k);\n\tassert(q.size() == n + 1);\n\tfor (int i = 1; i < (int)q.size(); ++i)\n\t{\n\t\tif (i > 1) printf(\" \");\n\t\tprintf(\"%d\", q[i]);\n\t}\n\tputs(\"\");\n}\n \nint main()\n{\n\tint tests;\n\tscanf(\"%d\", &tests);\n\twhile (tests--) solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1738",
    "index": "E",
    "title": "Balance Addicts",
    "statement": "Given an integer sequence $a_1, a_2, \\dots, a_n$ of length $n$, your task is to compute the number, modulo $998244353$, of ways to partition it into several \\textbf{non-empty} \\textbf{continuous} subsequences such that the sums of elements in the subsequences form a \\textbf{balanced} sequence.\n\nA sequence $s_1, s_2, \\dots, s_k$ of length $k$ is said to be balanced, if $s_{i} = s_{k-i+1}$ for every $1 \\leq i \\leq k$. For example, $[1, 2, 3, 2, 1]$ and $[1,3,3,1]$ are balanced, but $[1,5,15]$ is not.\n\nFormally, every partition can be described by a sequence of indexes $i_1, i_2, \\dots, i_k$ of length $k$ with $1 = i_1 < i_2 < \\dots < i_k \\leq n$ such that\n\n- $k$ is the number of non-empty continuous subsequences in the partition;\n- For every $1 \\leq j \\leq k$, the $j$-th continuous subsequence starts with $a_{i_j}$, and ends exactly before $a_{i_{j+1}}$, where $i_{k+1} = n + 1$. That is, the $j$-th subsequence is $a_{i_j}, a_{i_j+1}, \\dots, a_{i_{j+1}-1}$.\n\nThere are $2^{n-1}$ different partitions in total. Let $s_1, s_2, \\dots, s_k$ denote the sums of elements in the subsequences with respect to the partition $i_1, i_2, \\dots, i_k$. Formally, for every $1 \\leq j \\leq k$, $$ s_j = \\sum_{i=i_{j}}^{i_{j+1}-1} a_i = a_{i_j} + a_{i_j+1} + \\dots + a_{i_{j+1}-1}. $$ For example, the partition $[1\\,|\\,2,3\\,|\\,4,5,6]$ of sequence $[1,2,3,4,5,6]$ is described by the sequence $[1,2,4]$ of indexes, and the sums of elements in the subsequences with respect to the partition is $[1,5,15]$.\n\nTwo partitions $i_1, i_2, \\dots, i_k$ and $i'_1, i'_2, \\dots, i'_{k'}$ (described by sequences of indexes) are considered to be different, if at least one of the following holds.\n\n- $k \\neq k'$,\n- $i_j \\neq i'_j$ for some $1 \\leq j \\leq \\min\\left\\{ k, k' \\right\\}$.",
    "tutorial": "Let $f(i, j)$ be the answer to the problem for the subsequence $a_i, a_{i+1}, \\dots, a_j$. And we want to find $f(1, n)$. For every $1 \\leq i \\leq j \\leq n$, we consider the following cases. $a_i = \\dots = a_j = 0$. In this case, every partition produces a balanced sequence, thereby $f(i, j) = 2^{j-i}$. $a_i = a_j = 0$. In this case, suppose that there are $x$ prefix $0$'s and $y$ suffix $0$'s in $a_i, \\dots, a_j$ with $x, y \\geq 1$. There can be at most $\\min\\{x, y\\}$ zeros in both the prefix and suffix of the balanced sequence. There are $c_{x,y} = \\sum_{k=0}^{\\min\\{x,y\\}} \\binom{x}{k} \\binom{y}{k}$ choices in total. So $f(i,j) = c_{x,y} f(i+x, j-y)$. $c_{x,y} = \\sum_{k=0}^{\\min\\{x,y\\}} \\binom{x}{k} \\binom{y}{k}$ Otherwise, find the leftmost position $i \\leq l \\leq j$ and the rightmost position $i \\leq r \\leq j$ such that $a_i + \\dots + a_l = a_r + \\dots + a_j > 0$. $l = j$. We have $f(i, j) = 1$. $a_{l+1} = \\dots = a_{r-1} = 0$. There are $2^{r-l}$ possible choices to make the sequence balanced. So $f(i, j) = 2^{r-l}$. Otherwise, suppose there are $x$ prefix $0$'s and $y$ suffix $0$'s in $a_{l+1}, \\dots, a_{r-1}$. One can cut both parts with sum $a_i + \\dots + a_l = a_r + \\dots + a_j$. The number of choices to cut out $k$ $0$'s in the balanced sequence is $\\binom{x+1}{k+1} \\binom{y+1}{k+1}.$ With the case of no cut considered, we have $f(i, j) = \\left( \\sum_{k=0}^{\\min\\{x,y\\}} \\binom{x+1}{k+1} \\binom{y+1}{k+1} + 1 \\right) f(l+x+1, r-y-1) = c_{x+1, y+1} f(l+x+1, r-y-1).$ $l = j$. We have $f(i, j) = 1$. $a_{l+1} = \\dots = a_{r-1} = 0$. There are $2^{r-l}$ possible choices to make the sequence balanced. So $f(i, j) = 2^{r-l}$. Otherwise, suppose there are $x$ prefix $0$'s and $y$ suffix $0$'s in $a_{l+1}, \\dots, a_{r-1}$. One can cut both parts with sum $a_i + \\dots + a_l = a_r + \\dots + a_j$. The number of choices to cut out $k$ $0$'s in the balanced sequence is $\\binom{x+1}{k+1} \\binom{y+1}{k+1}.$ With the case of no cut considered, we have $f(i, j) = \\left( \\sum_{k=0}^{\\min\\{x,y\\}} \\binom{x+1}{k+1} \\binom{y+1}{k+1} + 1 \\right) f(l+x+1, r-y-1) = c_{x+1, y+1} f(l+x+1, r-y-1).$ $\\binom{x+1}{k+1} \\binom{y+1}{k+1}.$ $f(i, j) = \\left( \\sum_{k=0}^{\\min\\{x,y\\}} \\binom{x+1}{k+1} \\binom{y+1}{k+1} + 1 \\right) f(l+x+1, r-y-1) = c_{x+1, y+1} f(l+x+1, r-y-1).$ Since every element is processed once, it is clear that the time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconstexpr long long MOD = 998244353;\n \nlong long power(long long a, long long b)\n{\n\tif (b == 0) return 1;\n\tlong long t = power(a, b / 2);\n\tt = t * t % MOD;\n\tif (b % 2 == 1) t = t * a % MOD;\n\treturn t;\n}\n \nvoid solve()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<long long> a(n + 1);\n\tfor (int i = 1; i <= n; ++i) scanf(\"%lld\", &a[i]);\n \n\tvector<long long> factorial(n + 1, 1), inv_factorial(n + 1, 1);\n\tfor (int i = 1; i <= n; ++i)\n\t{\n\t\tfactorial[i] = factorial[i - 1] * i % MOD;\n\t\tinv_factorial[i] = inv_factorial[i - 1] * power(i, MOD - 2) % MOD;\n\t}\n\tauto choose = [&](int n, int m)\n\t{\n\t\treturn factorial[n] * inv_factorial[m] % MOD * inv_factorial[n - m] % MOD;\n\t};\n \n\tfunction<long long(int, int)> f = [&](int i, int j) -> long long\n\t{\n\t\tint l = i, r = j;\n\t\twhile (l <= j && a[l] == 0) l += 1;\n\t\twhile (r >= i && a[r] == 0) r -= 1;\n\t\tif (l == j + 1) // all zero\n\t\t\treturn power(2, j - i);\n\t\tif (i != l && j != r) // both ends have zeros\n\t\t{\n\t\t\tint x = l - i, y = j - r;\n\t\t\tlong long coef = 0;\n\t\t\tfor (int k = 0; k <= min(x, y); ++k)\n\t\t\t\tcoef = (coef + choose(x, k) * choose(y, k)) % MOD;\n\t\t\treturn f(l, r) * coef % MOD;\n\t\t}\n\t\t// at most one end has zeros\n\t\ti = l, j = r;\n\t\tlong long ls = a[i], rs = a[j];\n\t\twhile (ls != rs)\n\t\t{\n\t\t\tif (ls < rs) ls += a[++i]; else rs += a[--j];\n\t\t}\n\t\tif (i >= j) return 1;\n\t\tl = i + 1, r = j - 1;\n\t\twhile (l <= j && a[l] == 0) l += 1;\n\t\twhile (r >= i && a[r] == 0) r -= 1;\n\t\tif (l == j) // x, zeros, x\n\t\t\treturn power(2, j - i);\n\t\t// x, zeros, something, zeros, x\n\t\tint x = l - i - 1, y = j - r - 1;\n\t\tlong long coef = 0;\n\t\tfor (int k = 0; k <= min(x, y) + 1; ++k)\n\t\t\tcoef = (coef + choose(x + 1, k) * choose(y + 1, k)) % MOD;\n\t\treturn f(l, r) * coef % MOD;\n\t};\n \n\tlong long res = f(1, n);\n\tprintf(\"%lld\\n\", res);\n}\n \nint main()\n{\n\tint tests;\n\tcin >> tests;\n\twhile (tests--) solve();\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1738",
    "index": "F",
    "title": "Connectivity Addicts",
    "statement": "\\textbf{This is an interactive problem}.\n\nGiven a simple undirected graph with $n$ vertices numbered from $1$ to $n$, your task is to color all the vertices such that for every color $c$, the following conditions hold:\n\n- The set of vertices with color $c$ is \\textbf{connected};\n- $s_c \\leq n_c^2$, where $n_c$ is the number of vertices with color $c$, and $s_c$ is the sum of degrees of vertices with color $c$.\n\nIt can be shown that there always exists a way to color all the vertices such that the above conditions hold. Initially, you are only given the number $n$ of vertices and the degree of each vertex.\n\nIn each query, you can choose a vertex $u$. As a response, you will be given the $k$-th edge incident to $u$, if this is the $k$-th query on vertex $u$.\n\nYou are allowed to make \\textbf{at most $n$ queries}.\n\nAn undirected graph is simple if it does not contain multiple edges or self-loops.\n\nThe degree of a vertex is the number of edges incident to it.\n\nA set $S$ of vertices is connected if for every two different vertices $u, v \\in S$, there is a path, which only passes through vertices in $S$, that connects $u$ and $v$. That is, there is a sequence of edges $(u_1, v_1), (u_2, v_2), \\dots, (u_k, v_k)$ with $k \\geq 1$ such that\n\n- $u_1 = u$, $v_k = v$, and $v_i = u_{i+1}$ for every $1 \\leq i < k$; and\n- $u_k \\in S$ and $v_k \\in S$ for every $1 \\leq i \\leq k$.\n\nEspecially, a set containing only one vertex is connected.",
    "tutorial": "Let's consider the following BFS-like algorithm. Repeat the following procedure until all vertices are visited. Choose an unvisited vertex $u$ with the largest degree. Let $S$ be a set of vertices, initially consisting of the only vertex $u$. For every neighbor vertex $v$ of vertex $u$, If vertex $v$ is visited, color all vertices in $S$ with the same color as vertex $v$, and then end the procedure this time; Otherwise, add vertex $v$ to set $S$. Color all vertices in $S$ with a new one color. Choose an unvisited vertex $u$ with the largest degree. Let $S$ be a set of vertices, initially consisting of the only vertex $u$. For every neighbor vertex $v$ of vertex $u$, If vertex $v$ is visited, color all vertices in $S$ with the same color as vertex $v$, and then end the procedure this time; Otherwise, add vertex $v$ to set $S$. If vertex $v$ is visited, color all vertices in $S$ with the same color as vertex $v$, and then end the procedure this time; Otherwise, add vertex $v$ to set $S$. Color all vertices in $S$ with a new one color. It is clear that in each repetition of the procedure, the number $k$ of edges visited (i.e., the number of queries) will cause at least $k$ vertices being colored. Since all vertices will be colored exactly once eventually, the number of queries is no more than $n$. A careful analysis will find that the number of queries is no more than $n-C$, where $C$ is the number of different existing colors. The time complexity of this algorithm can be $O(n)$, $O(n\\log n)$, or $O(n^2)$, depending on concrete implementations. Anyway, any implementation of such time complexity can pass. It is clear that all vertices with the same color are connected. It remains to see why this algorithm will color all vertices such that $s_c \\leq n_c^2$, where $n_c$ is the number of vertices with color $c$, and $s_c$ is the sum of degrees of vertices with color $c$. To see this, it can be shown by induction that after every repetition of the procedure, the number $n_c$ of vertices with an existing color $c$ is always no less than the degree of any vertex with color $c$. Since we enumerate vertices in decreasing order of their degrees, the degree $d_u$ of the current vertex $u$ must hold that $d_u \\leq n_c$ for every existing color $c$. We consider two cases: During the procedure, no neighbor vertex $v$ of vertex $u$ is visited. That is, every neighbor vertex of vertex $u$ has degree $\\leq d_u$. Then, there are $d_u + 1$ vertices in $S$, and they are assigned with a new color $c$, thereby $s_c \\leq (d_u+1) d_u \\leq (d_u+1)^2 = n_c^2$. During the procedure, we find a neighbor vertex $v$ of vertex $u$ that is visited. Let $c$ be the color of vertex $v$ and $n'_c$ be the number of vertices with color $c$ before coloring all vertices in $S$. We have $|S| \\leq d \\leq n'_c$. Let $n_c = n'_c+|S|$ be the number of vertices with color $c$ after coloring all vertices in $S$ with color $c$. Then $s_c \\leq s'_c + |S|d \\leq (n'_c)^2 + |S|n'_c \\leq (n'_c+|S|)^2 = n_c^2$. This interesting problem surprisingly comes from non-traditional algorithm scenarios - QUANTUM algorithms. Further reading: Christoph Dürr, Mark Heiligman, Peter Høyer, and Mehdi Mhalla. Quantum query complexity of some graph problems. SIAM Journal on Computing, 35(6):1310-1328, 2006.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n\tint n;\n\tcin >> n;\n\tvector<int> d(n + 1);\n\tfor (int i = 1; i <= n; ++i) cin >> d[i];\n \n\tauto query = [&](int x)\n\t{\n\t\tcout << \"? \" << x << endl;\n\t\tint y;\n\t\tcin >> y;\n\t\treturn y;\n\t};\n \n\tvector<int> visited(n + 1);\n\tvector<int> res(n + 1);\n\tint color_cnt = 0;\n\twhile (1)\n\t{\n\t\tint x = 0;\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t\tif (!visited[i] && d[i] >= d[x]) x = i;\n\t\tif (x == 0) break;\n\t\tvector<int> q = { x };\n\t\tint colored_vertex = 0;\n\t\tfor (int i = 1; i <= d[x]; ++i)\n\t\t{\n\t\t\tint y = query(x);\n\t\t\tif (visited[y])\n\t\t\t{\n\t\t\t\tcolored_vertex = y;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tq.push_back(y);\n\t\t}\n\t\tint color = colored_vertex == 0 ? ++color_cnt : res[colored_vertex];\n\t\tfor (auto z : q)\n\t\t{\n\t\t\tvisited[z] = 1;\n\t\t\tres[z] = color;\n\t\t}\n\t}\n \n\tcout << \"!\";\n\tfor (int i = 1; i <= n; ++i)\n\t\tcout << \" \" << res[i];\n\tcout << endl;\n}\n \nint main()\n{\n\tint tests;\n\tcin >> tests;\n\twhile (tests--) solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dsu",
      "graphs",
      "greedy",
      "interactive",
      "shortest paths",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1738",
    "index": "G",
    "title": "Anti-Increasing Addicts",
    "statement": "You are given an $n \\times n$ grid.\n\nWe write $(i, j)$ to denote the cell in the $i$-th row and $j$-th column. For each cell, you are told whether yon can delete it or not.\n\nGiven an integer $k$, you are asked to delete \\textbf{exactly} $(n-k+1)^2$ cells from the grid such that the following condition holds.\n\n- You cannot find $k$ not deleted cells $(x_1, y_1), (x_2, y_2), \\dots, (x_k, y_k)$ that are strictly increasing, i.e., $x_i < x_{i+1}$ and $y_i < y_{i+1}$ for all $1 \\leq i < k$.\n\nYour task is to find a solution, or report that it is impossible.",
    "tutorial": "Consider increasing diagonals (sets of cells $(x, y)$ for which $x - y = c$ for some fixed $c$). Clearly, from the diagonal of length $t$, we have to delete at least $\\max(0, t - (k-1))$ cells. There are $2$ diagonals of length $i$ for each $i$ from $1$ to $n-1$ and one diagonal of length $n$, so we have to delete at least $2 + 4 + \\ldots + 2(n-k) + (n-k+1) = (n-k+1)^2$ cells from them in total. This means that we will delete precisely $\\max(0, t - (k-1))$ cells from the diagonal of length $t$. Now, consider two adjacent diagonals of lengths $t-1$ and $t$ for some $t \\ge k$. Let's call diagonal of length $t$ large, and of $t-1$ small. Let's enumerate cells of large diagonal from $1$ to $t$, and of small from $1$ to $t-1$. We have to delete precisely $t-k+1$ cells from large diagonal, and $t-k$ from small. Suppose that the cells deleted from the large diagonal have indexes $1 \\le x_1<x_2<\\ldots<x_{t-k+1} \\le t$. For some $1 \\le j \\le t-k$, consider the path, containing cells from $1$-st to $(x_j-1)$-st in the large diagonal, from $x_j$-th to $(x_{j+1}-1)$-st in the small diagonal, and from $(x_{j+1}+1)$-st to $t$-th in the large diagonal. Note that this is an increasing sequence of cells of length $t-1$, so we have to delete at least $t-k$ cells from it. We deleted precisely $t-k-2$ cells from it in the large diagonal, so we have to delete at least one cell in the small diagonal in the range $[x_j, x_{j+1}-1]$. Note that the ranges $[x_j, x_{j+1}-1]$ for $1 \\le j \\le t-k$ don't intersect, and there are $t-k$ of them. So, we have to delete precisely one cell from each such range and not delete any cell outside of $[x_1, x_{t-k+1}-1]$. Surprisingly, these criteria are sufficient (meaning that for every two adjacent diagonals, the cells in the smaller one are deleted in these ranges determined from the cells deleted in the larger one). Let's first show how to solve the problem based on this and then how to prove that this is sufficient. If these criteria are indeed sufficient, then let's construct the set of deleted cells one by one (if it exists). How do we choose the first deleted cell on the main diagonal? Just choose the first cell which you can delete. How do we choose the first deleted cell on the diagonals adjacent to the main diagonal? Just choose the first cell which you can delete that goes after the deleted cell in the main diagonal. How do we choose the second deleted cell on the main diagonal and the first deleted cells on the diagonals of length $n-2$? Again, just choose the first cell that you are allowed to delete which does not violate the conditions. (and so on) You can simulate this greedy in just $O(n^2)$ - just keep for each diagonal the last deleted cell. If at any point there were no allowed cells, then answer is NO, otherwise, we found the construction. How to prove that this is sufficient? Let's prove the following statement. Lemma: In each cell $(x, y)$, write the number of non-deleted cells in the diagonal of $(x, y)$, up to the cell $(x, y)$. Denote this number by $a_{x, y}$. Then $a_{x-1, y} \\le a_{x, y}$ for any $1 \\le x \\le n-1$, $1 \\le y \\le n$, and $a_{x, y-1} \\le a_{x, y}$ for any $1 \\le x \\le n$, $1 \\le y \\le n-1$ (in other words, $a$ is nondecreasing by rows and columns). Proof: Almost trivial from our constraints. Let's show that $a_{x-1, y} \\le a_{x, y}$, for example. If cell $(x-1, y)$ is on the main diagonal or lower, then cell $(x-1, y)$ is on a larger diagonal than $(x, y)$. We deleted $y - a_{x, y}$ cells in the diagonal of $(x, y)$ up to this cell. Therefore, the $(y - a_{x, y})$-th deleted cell in the larger diagonal has to have $y$ coordinate at most $y$ as well, so we deleted at least $y - a_{x, y}$ cells in the diagonal of $(x-1, y)$ up to that cell, and there are at most $a_{x, y}$ not deleted cells there. The similar argument goes for the case when $(x-1, y)$ is above the main diagonal. With this lemma, suppose that there is an increasing sequence of not deleted cells $(x_1, y_1), (x_2, y_2), \\ldots, (x_k, y_k)$ (with $x_i < x_{i+1}, y_i<y_{i+1}$). Then it's easy to show that $a_{x_i, y_i}<a_{x_{i+1}, y_{i+1}}$. Indeed, $a_{x_i, y_i}\\le a_{x_{i+1}-1, y_{i+1}-1} = a_{x_{i+1}, y_{i+1}} - 1$. But then we would get $a_{x_k, y_k} \\ge k$, which obviously doesn't hold (there are at most $k-1$ not deleted cells in each diagonal by our construction). Bonus: It's possible to show that the answer is NO if and only if there is an increasing sequence of $k$ cells, each of which we aren't allowed to delete. Proof is left to the reader as an exercise.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint n, k;\n \npair<int, int> cell(int diag, int pos)\n{\n    int st_x = 0; int st_y = 0;\n    if (diag <= n - 1) st_y = (n - 1) - diag;\n    if (diag >= n - 1) st_x = diag - (n - 1);\n \n    return pair<int, int>(st_x + pos, st_y + pos);\n}\n \nvoid solve()\n{\n    cin >> n >> k;\n    vector<string> s(n);\n    for (int i = 0; i < n; i++) cin >> s[i];\n \n    string full; for (int i = 0; i < n; i++) full += '1';\n    vector<string> t(n, full);\n \n    vector<int> last_del(2 * n - 1, -1);\n \n    int m = n - k + 1;\n \n    for (int iter = 0; iter <= 2 * (m - 1); iter++)\n    {\n        vector<pair<int, int>> updates;\n        for (int diag = 0; diag <= 2 * (n - 1); diag++) if (abs(diag - (n - 1)) <= min(iter, 2 * (m - 1) - iter) && abs(diag - (n - 1)) % 2 == iter % 2)\n        {\n            int nxt = last_del[diag] + 1;\n            //diag-1\n            if (diag - 1 < n - 1) nxt = max(nxt, last_del[diag - 1] + 1);\n            else nxt = max(nxt, last_del[diag - 1]);\n \n            //diag+1\n            if (diag + 1 > n - 1) nxt = max(nxt, last_del[diag + 1] + 1);\n            else nxt = max(nxt, last_del[diag + 1]);\n \n            while (true)\n            {\n                auto cur = cell(diag, nxt);\n                if (cur.first >= n || cur.second >= n) { cout << \"NO\" << '\\n'; return; }\n \n                if (s[cur.first][cur.second] == '0') nxt++;\n                else\n                {\n                    t[cur.first][cur.second] = '0';\n                    break;\n                }\n            }\n            updates.push_back(pair<int, int>(diag, nxt));\n        }\n        for (auto it : updates) last_del[it.first] = it.second;\n    }\n \n    cout << \"YES\" << '\\n';\n    for (auto it : t) cout << it << '\\n';\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(nullptr);\n \n    int t; cin >> t;\n    while (t--) solve();\n \n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1738",
    "index": "H",
    "title": "Palindrome Addicts",
    "statement": "Your task is to maintain a queue consisting of lowercase English letters as follows:\n\n- \"push $c$\": insert a letter $c$ at the back of the queue;\n- \"pop\": delete a letter from the front of the queue.\n\nInitially, the queue is empty.\n\nAfter each operation, you are asked to count the number of \\textbf{distinct} palindromic substrings in the string that are obtained by concatenating the letters from the front to the back of the queue.\n\nEspecially, the number of distinct palindromic substrings of the empty string is $0$.\n\nA string $s[1..n]$ of length $n$ is palindromic if $s[i] = s[n-i+1]$ for every $1 \\leq i \\leq n$.\n\nThe string $s[l..r]$ is a substring of string $s[1..n]$ for every $1 \\leq l \\leq r \\leq n$.\n\nTwo strings $s[1..n]$ and $t[1..m]$ are distinct, if at least one of the following holds.\n\n- $n \\neq m$;\n- $s[i] \\neq t[i]$ for some $1 \\leq i \\leq \\min\\{n,m\\}$.",
    "tutorial": "To count the number of distinct palindromic substrings, we adopt the powerful data structure called eertree (also known as palindromic tree or palindromic automaton). The number of distinct palindromic substrings of a string $s$ is related to the number of nodes in the eertree of $s$. See Wikipedia for its standard operations. In the following, we will consider how to maintain the eertree under push and pop queue operations. It is a standard trick to push a character at the back. So we only need to consider how to pop a character at the front. The key issue is to delete some nodes when they no longer exist. To achieve this, we maintain the following information of each node $v$: $\\texttt{link_cnt}$: the number of nodes that link to $v$. $\\texttt{rightmost_occurrence}$: the rightmost occurrence of $v$. $\\texttt{second_rightmost_occurrence}$: the second rightmost occurrence of $v$. Now it remains to consider how to maintain $\\texttt{rightmost_occurrence}$ and $\\texttt{second_rightmost_occurrence}$ in a lazy manner. After a character $c$ has been pushed at the back of the string $s$, let $v$ be the longest palindromic suffix of the current string $sc$. Update $\\texttt{rightmost_occurrence}[v]$ and $\\texttt{second_rightmost_occurrence}[v]$ immediately with the new occurrence of $v$. When a character is being popped from the front of the string $s$, let $v$ be the longest palindromic prefix of the current string (right before the pop operation). If $v$ is unique in $s$, then let $u$ be the node that $v$ links to, and update $\\texttt{rightmost_occurrence}[u]$ and $\\texttt{second_rightmost_occurrence}[u]$ with the occurrence of $u$ induced by $v$ (which is a suffix of $v$). Here, note that $u$ occurs at least twice in $v$ as its prefix and suffix; and the suffix $u$ of $v$ is desired as induced by $v$. In this way, we can maintain the eertree under push and pop queue operations in $O(\\Sigma n)$ time, where $\\Sigma = 26$ is the size of alphabet. Further reading: Takuya Mieno, Kiichi Watanabe, Yuto Nakashima, Shunsuke Inenaga, Hideo Bannai, and Masayuki Takeda. Palindromic trees for a sliding window and its applications. Information Processing Letters, 173:106174, 2022. An alternative approach Answer the queries offline. Since we only push characters at the back and remove characters at the front, we can deal with all operations offline and find the whole string $s$ with its characters deleted during the operations (This can be achieved easily by only considering push operations). For example, the whole string of the sample input is \"$aaabbaab$\". In this way, every query of the number of distinct palindromic substrings is a range query of the form $(l, r)$ that asks the number of distinct palindromic substrings in $s[l..r]$. Indeed, this kind of queries can be answered in $O(\\log n)$ time per query with $O(n \\log n)$ time preprocess. Further reading: Mikhail Rubinchik and Arseny M. Shur. Counting palindromes in substrings. In Proceedings of the 24th International Conference on String Processing and Information Retrieval, pages 290-303, 2017.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntemplate<int alpha>\nclass EerQueue\n{\n\tstatic_assert(alpha > 0);\npublic:\n\tstruct Node\n\t{\n\t\tstd::array<Node*, alpha> next;\n\t\tNode* pre, * fail;\n\t\tint len;\n\t\tint rightmost_occurence, second_rightmost_occurence;\n\t\t// The (second) rightmost occurence of the palindrome associated with this Node.\n\t\tint fail_cnt;\n\t\t// The count of fails that link to this Node.\n\t\tNode() : pre(nullptr), fail(nullptr), len(0), next{}, rightmost_occurence(-1), second_rightmost_occurence(-1), fail_cnt(0) { }\n\t\tvoid UpdateOccurence(int occurence)\n\t\t{\n\t\t\tif (occurence > rightmost_occurence)\n\t\t\t{\n\t\t\t\tsecond_rightmost_occurence = rightmost_occurence;\n\t\t\t\trightmost_occurence = occurence;\n\t\t\t}\n\t\t\telse if (occurence > second_rightmost_occurence)\n\t\t\t\tsecond_rightmost_occurence = occurence;\n\t\t}\n\t};\nprivate:\n\tint node_cnt;\n\tNode* odd_root, * even_root, * cur;\n\t// cur is the Node of the longest suffix palindrome.\n\tNode* NewNode(int len = 0)\n\t{\n\t\tNode* it = new Node();\n\t\tit->len = len;\n\t\treturn it;\n\t}\n\tint start;\n\tstd::vector<int> data;\n\tstd::vector<Node*> prefix_palindrome;\n\tint size;\n\tNode* GetFail(Node* it, int pos)\n\t{\n\t\twhile (pos - it->len - 1 < start || data[pos - it->len - 1] != data[pos])\n\t\t\tit = it->fail;\n\t\treturn it;\n\t}\npublic:\n\tEerQueue() : node_cnt(0), start(0), size(0)\n\t{\n\t\todd_root = NewNode(-1);\n\t\teven_root = NewNode(0);\n\t\todd_root->fail = odd_root; odd_root->fail_cnt += 1;\n\t\teven_root->fail = odd_root; odd_root->fail_cnt += 1;\n\t\tcur = even_root;\n\t}\n\tNode* Push(int x)\n\t{\n\t\tassert(0 <= x && x < alpha);\n\t\tint pos = data.size();\n\t\tdata.push_back(x);\n\t\tprefix_palindrome.push_back(nullptr);\n\t\tNode* it = GetFail(cur, pos);\n\t\tif (it->next[x] == nullptr)\n\t\t{\n\t\t\tNode* tmp = NewNode(it->len + 2);\n\t\t\ttmp->pre = it;\n\t\t\ttmp->fail = GetFail(it->fail, pos)->next[x];\n\t\t\tif (tmp->fail == nullptr) tmp->fail = even_root;\n\t\t\ttmp->fail->fail_cnt += 1;\n\t\t\tit->next[x] = tmp;\n\t\t\tsize += 1;\n\t\t}\n\t\tcur = it->next[x];\n\t\tint occurence = pos - cur->len + 1;\n\t\tcur->UpdateOccurence(occurence);\n\t\tprefix_palindrome[occurence] = cur;\n\t\treturn cur;\n\t}\n\tvoid Pop()\n\t{\n\t\tassert(start < (int)data.size());\n\t\tNode* longest_prefix_palindrome = prefix_palindrome[start];\n\t\tif (longest_prefix_palindrome->len == (int)data.size() - start)\n\t\t\tcur = cur->fail;\n\t\tNode* it = longest_prefix_palindrome->fail;\n\t\tif (start != (int)data.size() - 1)\n\t\t{\n\t\t\tint occurence = start + longest_prefix_palindrome->len - it->len;\n\t\t\tit->UpdateOccurence(occurence);\n\t\t\tif (prefix_palindrome[occurence] == nullptr || it->len > prefix_palindrome[occurence]->len)\n\t\t\t\tprefix_palindrome[occurence] = it;\n\t\t}\n\t\tif (longest_prefix_palindrome->fail_cnt == 0 && longest_prefix_palindrome->second_rightmost_occurence < start)\n\t\t{\n\t\t\tint x = data[start];\n\t\t\tlongest_prefix_palindrome->pre->next[x] = nullptr;\n\t\t\tit->fail_cnt -= 1;\n\t\t\tsize -= 1;\n\t\t}\n\t\tstart += 1;\n\t}\n\tint NumOfPalindromes()\n\t{\n\t\treturn size;\n\t}\n};\n \n \nvoid solve()\n{\n\tint q;\n\tcin >> q;\n\tconstexpr int alpha = 26;\n\tEerQueue<alpha> g;\n\twhile (q--)\n\t{\n\t\tstring op;\n\t\tcin >> op;\n\t\tif (op == \"push\")\n\t\t{\n\t\t\tchar c;\n\t\t\tcin >> c;\n\t\t\tg.Push(c - 'a');\n\t\t}\n\t\telse\n\t\t\tg.Pop();\n\t\tcout << g.NumOfPalindromes() << \"\\n\";\n\t}\n}\n \nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1739",
    "index": "A",
    "title": "Immobile Knight",
    "statement": "There is a chess board of size $n \\times m$. The rows are numbered from $1$ to $n$, the columns are numbered from $1$ to $m$.\n\nLet's call a cell isolated if a knight placed in that cell can't move to any other cell on the board. Recall that a chess knight moves two cells in one direction and one cell in a perpendicular direction:\n\nFind any isolated cell on the board. If there are no such cells, print any cell on the board.",
    "tutorial": "Let's consider some cases. If at least one of $n$ or $m$ are $1$, then all cells are isolated. A knight can't move one in a perpendicular direction. If at least one of $n$ or $m$ are at least $4$, then the knight always has at least one move. No matter where you place it, it can move two cells along the greater of the dimensions and move one in a perpendicular direction, because it's at least $2$. Three cases are left. $(2, 2)$, $(2, 3)$ and $(3, 3)$. For all of these cases, the middle cell is isolated. That cell is $(\\lfloor \\frac n 2 \\rfloor + 1, \\lfloor \\frac m 2 \\rfloor + 1)$. Since it doesn't matter which cell you print in the first two cases, you can always print $(\\lfloor \\frac n 2 \\rfloor + 1, \\lfloor \\frac m 2 \\rfloor + 1)$. Overall complexity: $O(1)$ per testcase. Alternatively, you can check every possible cell. Iterate over a cell and check all eight possible knight moves from it. If none are inside the board, the cell is isolated. Overall complexity: $O(nm)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\tforn(_, t){\n\t\tint n, m;\n\t\tscanf(\"%d%d\", &n, &m);\n\t\tint svx = 1, svy = 1;\n\t\tfor (int x = 1; x <= n; ++x){\n\t\t\tfor (int y = 1; y <= m; ++y){\n\t\t\t\tbool ok = true;\n\t\t\t\tfor (int dx : {-2, -1, 1, 2}){\n\t\t\t\t\tfor (int dy : {-2, -1, 1, 2}){\n\t\t\t\t\t\tif (abs(dx * dy) != 2) continue;\n\t\t\t\t\t\tif (1 <= x + dx && x + dx <= n && 1 <= y + dy && y + dy <= m)\n\t\t\t\t\t\t\tok = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (ok){\n\t\t\t\t\tsvx = x;\n\t\t\t\t\tsvy = y;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"%d %d\\n\", svx, svy);\n\t}\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1739",
    "index": "B",
    "title": "Array Recovery",
    "statement": "For an array of \\textbf{non-negative} integers $a$ of size $n$, we construct another array $d$ as follows: $d_1 = a_1$, $d_i = |a_i - a_{i - 1}|$ for $2 \\le i \\le n$.\n\nYour task is to restore the array $a$ from a given array $d$, or to report that there are multiple possible arrays.",
    "tutorial": "Note that $a_i = a_{i-1} + d_i$ or $a_i= a_{i-1} - d_i$. Since there is no upper bound for the values of $a_i$, the case where $a_i = a_{i-1} + d_i$ for all $i$ always exists. It remains to check if there are other ways. To do this, it is enough to check whether there is such a position $pos$ that: $pos > 1$; $d_{pos} \\ne 0$; the change $a_{pos} = a_{pos-1} + d_{pos}$ to $a_{pos} = a_{pos-1} - d_{pos}$ doesn't result in a negative value of $a_{pos}$. The reason for $d_{pos} \\ne 0$ is that for $d_{pos} = 0$ no matter the plus or minus we choose, the array $a$ doesn't change. If you could change at least one sign to minus, that would be another answer.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\tans = [0]\n\tfor x in map(int, input().split()):\n\t\tif x != 0 and ans[-1] - x >= 0:\n\t\t\tprint(-1)\n\t\t\tbreak\n\t\telse:\n\t\t\tans.append(ans[-1] + x)\n\telse:\n\t\tprint(*ans[1:])",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1739",
    "index": "C",
    "title": "Card Game",
    "statement": "Consider a game with $n$ cards ($n$ is even). Each card has a number written on it, between $1$ and $n$. All numbers on the cards are different. We say that a card with number $x$ is stronger than a card with number $y$ if $x > y$.\n\nTwo players, Alex and Boris, play this game. In the beginning, each of them receives exactly $\\frac{n}{2}$ cards, so each card belongs to exactly one player. Then, they take turns. Alex goes first, then Boris, then Alex again, and so on.\n\nOn a player's turn, he must play \\textbf{exactly one} of his cards. Then, if the opponent doesn't have any cards \\textbf{stronger} than the card played, the opponent loses, and the game ends. Otherwise, the opponent has to play a stronger card (exactly one card as well). These two cards are removed from the game, and the turn ends. If there are no cards left, the game ends in a draw; otherwise it's the opponent's turn.\n\nConsider all possible ways to distribute the cards between two players, so that each of them receives exactly half of the cards. You have to calculate three numbers:\n\n- the number of ways to distribute the cards so that Alex wins;\n- the number of ways to distribute the cards so that Boris wins;\n- the number of ways to distribute the cards so that the game ends in a draw.\n\nYou may assume that both players play optimally (i. e. if a player can win no matter how his opponent plays, he wins). Two ways to distribute the cards are different if there is at least one card such that, in one of these ways, it is given to Alex, and in the other way, it is given to Boris.\n\nFor example, suppose $n = 4$, Alex receives the cards $[2, 3]$, and Boris receives the cards $[1, 4]$. Then the game may go as follows:\n\n- if Alex plays the card $2$, then Boris has to respond with the card $4$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $1$; he plays it, and Alex responds with the card $3$. So, the game ends in a draw;\n- if Alex plays the card $3$, then Boris has to respond with the card $4$. Then, Alex's turn ends, and Boris' turn starts. Boris has only one card left, which is $1$; he plays it, and Alex responds with the card $2$. So, the game ends in a draw.\n\nSo, in this case, the game ends in a draw.",
    "tutorial": "The example tests suggest that there is only one possible distribution with a draw. Let's find out why it is so. We will use a process similar to induction/recursion to distribute the cards between the two players so that the game ends in a draw: suppose Alex receives the card $n$. Then he wins since he can play it immediately. So, for the game to result in a draw, Boris must receive the card $n$. suppose Boris receives the card $n-1$. Then he wins since he also has the card $n$, he can use it to answer any first move of Alex, and then win the game by playing $n-1$. So, for the game to result in a draw, Alex must receive the card $n-1$. suppose Boris receives the card $n-2$. Then he wins since he also has the card $n$: if Alex plays the card $n-1$, Boris responds with $n$ and then plays $n-2$; if Alex plays some other card, Boris responds with $n-2$ and the plays $n$. So, for the game to result in a draw, Alex must receive the card $n-2$. and so on. In fact, if Alex receives the card $n-1$ and Boris receives the card $n$, Alex must play the card $n-1$ or something equivalent to it on the first move, and Boris must respond with the card $n$, so we can consider the game without these two cards with the roles swapped. So, if we consider the distribution of cards as a string with characters A and B, where A denotes the card belonging to Alex, and B denotes the card belonging to Boris, and the $i$-th character of the string represents the card $n-i+1$, the only possible distribution for the draw is BAABBAAB... But there's more to this string representation of the distribution of cards: the first character that is different from this pattern denotes the winner; if the first different character is A in the draw distribution and B in the distribution we consider, the winner is Boris; otherwise, the winner is Alex. This may lead us to the following ways to count the number of possible distributions which win/lose for Alex: we can use dynamic programming of the form $dp_{x,y,t}$, where $x$ is the number of characters A we used, $y$ is the number of characters B we used, and $t$ is $0$, $1$ or $2$ depending on whether our string coincides with the draw string ($t = 0$), differs from it in a way that Alex wins ($t = 1$), or differs from it in a way that Boris wins ($t = 2$); the actual value of $dp_{x,y,t}$ must be the number of ways to reach this state of dynamic programming. The answer then is stored in the states of the form $dp_{\\frac{n}{2},\\frac{n}{2},t}$. or we can use combinatorics: let's iterate on the length of the prefix that is common in the draw string and in the string representing the distribution of cards, and then count the number of ways to distribute the remaining characters with a binomial coefficient. To calculate the binomial coefficients, we can use one of the following methods: Pascal's triangle, precalculating factorials and modular inverses to then, or calculating factorials with big integers in Java or Python.",
    "code": "def fact(n):\n    return 1 if n == 0 else n * fact(n - 1)\n\ndef choose(n, k):\n    return fact(n) // fact(k) // fact(n - k)\n\ndef calc(n):\n    if n == 2:\n        return [1, 0, 1]\n    else:\n        a = calc(n - 2)\n        return [choose(n - 1, n // 2) + a[1], choose(n - 2, n // 2) + a[0], 1]\n\nt = int(input())\nfor i in range(t):\n    mod = 998244353\n    n = int(input())\n    a = calc(n)\n    a = list(map(lambda x: x % mod, a))\n    print(*a)",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "dp",
      "games"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1739",
    "index": "D",
    "title": "Reset K Edges",
    "statement": "You are given a rooted tree, consisting of $n$ vertices. The vertices are numbered from $1$ to $n$, the root is the vertex $1$.\n\nYou can perform the following operation \\textbf{at most} $k$ times:\n\n- choose an edge $(v, u)$ of the tree such that $v$ is a parent of $u$;\n- remove the edge $(v, u)$;\n- add an edge $(1, u)$ (i. e. make $u$ with its subtree a child of the root).\n\nThe height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $1$ is $0$, since it's the root, and the depth of all its children is $1$.\n\nWhat's the smallest height of the tree that can be achieved?",
    "tutorial": "Start with the following. Let's look at the input format and consider what the operation actually does to it. Since it only changes the parent of some vertex, it modifies only one value in it. Moreover, it just assigns it to $1$. Thus, the goal is to assign at most $k$ values of parents to $1$ to minimize the resulting height of the tree. In particular, that implies that we can freely rearrange the operations, since the assignments don't depend on each other. One more conclusion. Imagine we have already built some answer. One by one, we moved some subtrees to be children of the root. It could happen that we first moved some subtree of a vertex $u$ and then applied the operation to an edge inside the subtree of $u$. Let's show that it's always possible to rearrange the operations in the answer to avoid that. Just apply the operations in order of decreasing the depth of the vertex $u$. If we knew what height $h$ we want to get, we could have been making sure that cut subtree $u$ has height at most $h-1$ (since it gets increased by $1$ when glueing it to the root), then pretending that that subtree doesn't exist anymore. Moreover, it's always required to cut subtrees with height at most $h-1$. If you cut a higher subtree, then the answer can't be smaller than $h+1$, since we rearranged the operation to not touch that subtree anymore. Well, let's fix that height $h$ if we wanted that. Let's try the solve the opposite problem. How many operations will it require to make the tree height at most $h$? Obviously, the values for this problem are non-increasing - the greater we allow the height to be, the less operations it will require. Thus, we will be able to apply binary search to it to find the smallest height we can achieve with at most $k$ operations. Now we want to be choosing the subtrees of height at most $h-1$ repeatedly and cutting them off until the height of the tree becomes at most $h$. Let's think greedily. If the height of the tree is not at most $h$ yet, then there exists a vertex with the depth greater than $h$. Let's look at the deepest of them. That leaf has to be cut in some subtree. Otherwise, the tree won't become any less higher. What subtree is the best for it? What options do we have? That vertex itself and all its parents up until $h-1$ above. It's always optimal to cut the highest of them - the $(h-1)$-st parent, since it will remove at least all the vertices of any other cut and some other vertices along with them. It's also always possible to remove the $(h-1)$-st parent, since it will always have height exactly $h-1$. The vertex we are looking at is the deepest in the entire tree - there are no deeper vertices in the subtree of the $(h-1)$-st parent. Thus, the strategy is to keep cutting the $(h-1)$-st parent of the deepest vertex until the tree becomes at most $h$ height. Now about the implementation details. First, we can process the vertices from the deepest upwards in their order in the original tree. The operation only removes some vertices but doesn't change the depth of the remaining ones. For example, you can do a bfs from the root to find the order. Now the $(h-1)$-st parent. Let's find it for each vertex before starting the process. Run a dfs and maintain the stack of the ascendants. When going down the child, append it to the stack. What exiting, pop from the stack. Now you can just look at the $(h-1)$-st element from the top of the stack. To be able to do that, simulate the stack with a vector (C++) or a list (Python). Finally, we would have to determine if the current vertex in the order is removed or not. For that, we could maintain a boolean array $\\mathit{used}$ for the removed vertices. Once you apply the operation, run the dfs from the removed vertex and mark all the newly removed descendants of it in $\\mathit{used}$. If you don't go into already marked vertices, there will be no more than $n$ calls of the dfs. The number of cut vertices is the answer for the fixed height $h$. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n;\nvector<vector<int>> g;\n\nvector<int> st;\nvector<int> pd;\n\nvoid init(int v, int d){\n\tst.push_back(v);\n\tif (int(st.size()) - d >= 0)\n\t\tpd[v] = st[st.size() - d];\n\tfor (int u : g[v])\n\t\tinit(u, d);\n\tst.pop_back();\n}\n\nvector<char> used;\n\nvoid dfs(int v){\n\tused[v] = true;\n\tfor (int u : g[v]) if (!used[u])\n\t\tdfs(u);\n}\n\nint get(int d){\n\tpd.assign(n, -1);\n\tinit(0, d);\n\t\n\tvector<int> ord, h(n);\n\tqueue<int> q;\n\tq.push(0);\n\twhile (!q.empty()){\n\t\tint v = q.front();\n\t\tq.pop();\n\t\tord.push_back(v);\n\t\tfor (int u : g[v]){\n\t\t\tq.push(u);\n\t\t\th[u] = h[v] + 1;\n\t\t}\n\t}\n\treverse(ord.begin(), ord.end());\n\t\n\tused.assign(n, 0);\n\tint res = 0;\n\tfor (int v : ord) if (!used[v] && h[v] > d){\n\t\t++res;\n\t\tdfs(pd[v]);\n\t}\n\t\n\treturn res;\n}\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--){\n\t\tint k;\n\t\tscanf(\"%d%d\", &n, &k);\n\t\tg.assign(n, vector<int>());\n\t\tfor (int i = 1; i < n; ++i){\n\t\t\tint p;\n\t\t\tscanf(\"%d\", &p);\n\t\t\t--p;\n\t\t\tg[p].push_back(i);\n\t\t}\n\t\tint l = 1, r = n - 1;\n\t\tint ans = n;\n\t\twhile (l <= r){\n\t\t\tint m = (l + r) / 2;\n\t\t\tif (get(m) <= k){\n\t\t\t\tans = m;\n\t\t\t\tr = m - 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tl = m + 1;\n\t\t\t}\n\t\t}\n\t\tprintf(\"%d\\n\", ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1739",
    "index": "E",
    "title": "Cleaning Robot",
    "statement": "Consider a hallway, which can be represented as the matrix with $2$ rows and $n$ columns. Let's denote the cell on the intersection of the $i$-th row and the $j$-th column as $(i, j)$. The distance between the cells $(i_1, j_1)$ and $(i_2, j_2)$ is $|i_1 - i_2| + |j_1 - j_2|$.\n\nThere is a cleaning robot in the cell $(1, 1)$. Some cells of the hallway are clean, other cells are dirty (the cell with the robot is clean). You want to clean the hallway, so you are going to launch the robot to do this.\n\nAfter the robot is launched, it works as follows. While at least one cell is dirty, the robot chooses \\textbf{the closest (to its current cell) cell} among those which are dirty, moves there and cleans it (so the cell is no longer dirty). After cleaning a cell, the robot again finds the closest dirty cell \\textbf{to its current cell}, and so on. This process repeats until the whole hallway is clean.\n\nHowever, there is a critical bug in the robot's program. If at some moment, there are multiple closest (to the robot's current position) dirty cells, the robot malfunctions.\n\nYou want to clean the hallway in such a way that the robot doesn't malfunction. \\textbf{Before launching the robot}, you can clean some (possibly zero) of the dirty cells yourself. However, you don't want to do too much dirty work yourself while you have this nice, smart (yet buggy) robot to do this. Note that you cannot make a clean cell dirty.\n\nCalculate the maximum possible number of cells you can leave dirty before launching the robot, so that it doesn't malfunction.",
    "tutorial": "Why did the author choose the width of the hallway to be only $2$? Well, in that case you can show that the robot will never move to the left while cleaning. That is not true on width $3$ already. When does the robot break? Let the robot currently be in the cell $(j, i)$ ($0$-indexed) and the next column with a dirty cell be $\\mathit{nxt}_i$ (possibly, $\\mathit{nxt}_i = i$). The robot breaks only if both $(1 - j, \\mathit{nxt}_i)$ and $(j, \\mathit{nxt}_i)$ are dirty. That helps us to do a dynamic programming solution. Since we can only care about $O(1)$ next columns, we would want to have some $dp[i][j]$ - the largest number of dirty cells we can leave to the robot if we processed the first $i$ columns of the hallway and are currently standing in the $j$-th row of the $i$-th column. Maybe with some additional states of the current or the next columns. We want the dp to maintain the invariant that everything to the left of the $i$-th column is cleaned in such a way the robot can reach the cell $(j, i)$. We can choose when to fix the $i$-th column: either maintain it being correct prior to entering the state or handling it in the transition to the next one. I chose the former option. There probably exists a million different dps that work, I'll describe the one I did. Let $dp[i][j][f]$ be the largest number of dirty cells that we can leave to the robot if: we fixed which of the dirty cells in the first $i$ columns, inclusive, are cleaned by hand; the robot reaches the cell $(j, i)$ from the left; $f$ is true if the cell in the opposite row of the $i$-th column is dirty. The transitions handle what to do with the dirty cells in the $(i+1)$-st column and where the robot goes based on that. In particular, there are the following transitions: if $f$ is true, then we have to clean the cell $(j, i + 1)$, and the robot will move into $(1 - j, i + 1)$ - otherwise the robot breaks from having two options; if $f$ is false, then let's say that the robot doesn't break immediately but moves into the next column in a unique way: it moves horizontally first, then possibly vertically; we can leave the next column as is, and the robot will move into $(j, i + 1)$ if the cell $(1 - j, i + 1)$ is clean, or $(1 - j, i + 1)$ if it's dirty; if $f$ is false, then we can clean the cell $(1 - j, i + 1)$, and the robot will move into $(j, i + 1)$. we can leave the next column as is, and the robot will move into $(j, i + 1)$ if the cell $(1 - j, i + 1)$ is clean, or $(1 - j, i + 1)$ if it's dirty; if $f$ is false, then we can clean the cell $(1 - j, i + 1)$, and the robot will move into $(j, i + 1)$. Since we maintained the invariant that the $i$-th column is valid, we can update the answer from all four states in the last column. Overall complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nconst int INF = 1e9;\n\nint main(){\n\tint n;\n\tcin >> n;\n\tvector<string> s(2);\n\tforn(i, 2) cin >> s[i];\n\tvector<array<array<int, 2>, 2>> dp(n + 1);\n\tforn(i, n + 1) forn(j, 2) forn(k, 2) dp[i][j][k] = -INF;\n\tdp[0][0][s[1][0] == '1'] = s[1][0] == '1';\n\tdp[0][0][0] = 0;\n\tforn(i, n - 1) forn(j, 2){\n\t\tint nxtj = s[j][i + 1] == '1';\n\t\tint nxtj1 = s[j ^ 1][i + 1] == '1';\n\t\tdp[i + 1][j ^ 1][0] = max(dp[i + 1][j ^ 1][0], dp[i][j][1] + nxtj1);\n\t\tdp[i + 1][j][nxtj1] = max(dp[i + 1][j][nxtj1], dp[i][j][0] + nxtj1 + nxtj);\n\t\tdp[i + 1][j][0] = max(dp[i + 1][j][0], dp[i][j][0] + nxtj);\n\t}\n\tcout << max({dp[n - 1][0][0], dp[n - 1][0][1], dp[n - 1][1][0], dp[n - 1][1][1]}) << '\\n';\n}",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1739",
    "index": "F",
    "title": "Keyboard Design",
    "statement": "Monocarp has a dictionary of $n$ words, consisting of $12$ first letters of the Latin alphabet. The words are numbered from $1$ to $n$. In every pair of adjacent characters in each word, the characters are different. For every word $i$, Monocarp also has an integer $c_i$ denoting how often he uses this word.\n\nMonocarp wants to design a keyboard that would allow him to type some of the words easily. A keyboard can be denoted as a sequence of $12$ first letters of the Latin alphabet, where each letter from a to l appears exactly once.\n\nA word can be typed with the keyboard easily if, for every pair of adjacent characters in the word, these characters are adjacent in the keyboard as well. The optimality of the keyboard is the sum of $c_i$ over all words $i$ that can be typed easily with it.\n\nHelp Monocarp to design a keyboard with the maximum possible optimality.",
    "tutorial": "For each word, let's consider a graph on $12$ vertices where the $i$-th and the $j$-th vertices are connected by an edge iff the $i$-th character of the alphabet is adjacent to the $j$-th character of the alphabet in this string. Obviously, this graph is connected (except for the isolated vertices). If there is a vertex of degree $3$ or more in this graph, or if there is a cycle in this graph, it is impossible to design a keyboard to type the word easily: in the first case, the letter represented by that vertex must have at least three neighbors on the keyboard, but can have only at most two; in the second case, the keyboard must be cyclic (and it is not). So, the word can be typed easily only if the graph representing it consists of one path and several isolated vertices. Let's write the letters along the path we constructed for the word in a single string. For example, for the word abacabacd, we get edges ab, ac and cd in the graph, so the letters along the path are either dcab or bacd (and, obviously, one can be obtained from the other by reversing the string). Let $f(s)$ and $f'(s)$ be the two strings we obtain from the word $s$ using this method. Now, we claim that the word $s$ can be typed easily if and only if one of these two strings ($f(s)$ and $f'(s)$) is a substring of the keyboard - this would mean that every pair of letters that should be on adjacent positions are actually on adjacent positions. Okay, now we construct $f(s_i)$ and $f'(s_i)$ for each word, and our goal is to find the permutation of the first $12$ characters of Latin alphabet such that the sum of $c_i$ over all words having either $f(s_i)$ or $f'(s_i)$ as a substring is the maximum possible. There are two key observations that allow us to solve this problem: $f(s_i)$ and $f'(s_i)$ cannot be the substrings of the same keyboard (the proof is simple: if $f(s_i)$ is a substring, its first character must be before its second character; and if $f'(s_i)$ is a substring, its second-to-last character (which is the second character of $f(s_i)$) must be before its last character (which is the first character of $f(s_i)$); neither $f(s_i)$ nor $f'(s_i)$ can appear in the keyboard twice (it's obvious since the keyboard is a permutation). So, we can reformulate the problem as follows: let $c_i$ be the cost of the string $f(s_i)$ and the cost of the string $f'(s_i)$ as well; find the permutation of the first $12$ characters of the Latin alphabet so that its cost (which is the sum of costs of its substrings) is the maximum possible. To solve this problem, we can store the strings in an Aho-Corasick automaton, and for every state of the automaton, precalculate the total cost of all string ending in this state (that is, the cost of this state and all states reachable from it via the suffix links). Then run a dynamic programming of the form $dp_{mask,v}$ - the maximum possible cost of a partial keyboard if we used a $mask$ of characters and the Aho-Corasick automaton is currently in the state $v$. This dynamic programming runs in $O(2^K \\cdot K \\cdot A)$, where $K$ is the size of the alphabet ($12$), and $A$ is the size of the automaton (up to $4000$).",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 10043;\nconst int K = 12;\n\nint tsz = 0;\nint trie[N][K];\nint aut[N][K];\nint lnk[N];\nint p[N];\nint pchar[N];\nint cost[N];\nint ncost[N];\n\nint newNode()\n{\n    lnk[tsz] = -1;\n    ncost[tsz] = -1;\n    cost[tsz] = 0;\n    for(int i = 0; i < K; i++)\n    {\n        trie[tsz][i] = aut[tsz][i] = -1;\n    }\n    return tsz++;\n}\n\nint nxt(int x, int y)\n{                                 \n    if(trie[x][y] == -1) \n    {\n        trie[x][y] = newNode();\n        pchar[trie[x][y]] = y;\n        p[trie[x][y]] = x;\n    }\n    return trie[x][y];\n}\n\nint go(int x, int y);\n\nint get_lnk(int x)\n{\n    if(lnk[x] != -1) return lnk[x];\n    int& d = lnk[x];\n    if(x == 0 || p[x] == 0) return d = 0;\n    return d = go(get_lnk(p[x]), pchar[x]);    \n}\n\nint go(int x, int y)\n{\n    if(aut[x][y] != -1) return aut[x][y];\n    int& d = aut[x][y];\n    if(trie[x][y] != -1) return d = trie[x][y];\n    if(x == 0) return d = 0;\n    return d = go(get_lnk(x), y);\n}\n\nvoid add(string s, int c)\n{\n    int cur = 0;\n    for(auto x : s) cur = nxt(cur, x - 'a');\n    cost[cur] += c;     \n} \n\nint calc(int x)\n{\n    if(ncost[x] != -1) return ncost[x];\n    ncost[x] = cost[x];\n    int y = get_lnk(x);\n    if(y != x) ncost[x] += calc(y);\n    return ncost[x];\n}\n\nint main()\n{\n    int root = newNode();\n    int n;\n    cin >> n;\n    for(int i = 0; i < n; i++)\n    {\n        string s;\n        int x;\n        cin >> x >> s;\n        map<char, set<char>> adj;\n        for(int j = 0; j + 1 < s.size(); j++)\n        {\n            adj[s[j]].insert(s[j + 1]);\n            adj[s[j + 1]].insert(s[j]);\n        }\n        bool bad = false;\n        string res = \"\";\n        char c;\n        for(c = 'a'; c <= 'l'; c++)\n        {\n            if(!adj.count(c)) continue;\n            if(adj[c].size() >= 3)\n                bad = true;\n            if(adj[c].size() == 1)\n                break;\n        }\n        if(c == 'm' || bad) continue;\n        res.push_back(c);\n        while(adj[c].size() > 0)\n        {\n            char d = *adj[c].begin();\n            adj[c].erase(d);\n            adj[d].erase(c);\n            c = d;\n            res.push_back(c);  \n        }\n        bad |= adj.size() != res.size();\n        map<char, int> pos;\n        for(int i = 0; i < res.size(); i++)\n            pos[res[i]] = i;\n        for(int i = 0; i + 1 < s.size(); i++)\n            bad |= abs(pos[s[i]] - pos[s[i + 1]]) > 1;\n        if(bad) continue;\n        add(res, x);\n        reverse(res.begin(), res.end());\n        add(res, x);\n    }  \n    int INF = 1e9;\n    int K = 12;\n    vector<vector<int>> dp(1 << K, vector<int>(tsz + 1, -INF));\n    vector<vector<pair<int, int>>> pdp(1 << K, vector<pair<int, int>>(tsz + 1));\n    dp[0][0] = 0;\n    for(int i = 0; i < (1 << K); i++)\n        for(int j = 0; j <= tsz; j++)\n        {\n            for(int z = 0; z < K; z++)\n            {\n                if(i & (1 << z)) continue;\n                int nstate = go(j, z);\n                int add = calc(nstate);\n                int nmask = i | (1 << z);\n                if(dp[nmask][nstate] < dp[i][j] + add)\n                {\n                    dp[nmask][nstate] = dp[i][j] + add;\n                    pdp[nmask][nstate] = {z, j};\n                }\n            }\n        }\n    string ans = \"\";\n    int curmask = (1 << K) - 1;\n    int curstate = max_element(dp[curmask].begin(), dp[curmask].end()) - dp[curmask].begin();\n    while(curmask != 0)\n    {\n        int cc = pdp[curmask][curstate].first;\n        int ns = pdp[curmask][curstate].second;\n        ans.push_back(char('a' + cc));\n        curmask ^= (1 << cc);\n        curstate = ns;\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "dp",
      "string suffix structures",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1740",
    "index": "A",
    "title": "Factorise N+M",
    "statement": "Pak Chanek has a prime number$^\\dagger$ $n$. Find a prime number $m$ such that $n + m$ is not prime.\n\n$^\\dagger$ A prime number is a number with \\textbf{exactly} $2$ factors. The first few prime numbers are $2,3,5,7,11,13,\\ldots$. In particular, $1$ is \\textbf{not} a prime number.",
    "tutorial": "There are multiple solutions for this problem. We will discuss two of them. One solution is to choose $m = n$. This always guarantees that $m$ is prime, because $n$ is always prime. And we can see that $n + m = n + n = 2n$, which is always not prime, because $n > 1$ always holds. Another solution is to choose $m=7$. If $n$ is odd, then $n+m$ will be an even number greater than $2$ and therefore not prime. Otherwise $n$ is even. The only even number prime number is $2$ and it can be verified that $2+7=9$ is not a prime number. Time complexity for each test case: $O(1)$",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1740",
    "index": "B",
    "title": "Jumbo Extra Cheese 2",
    "statement": "Pak Chanek has $n$ two-dimensional slices of cheese. The $i$-th slice of cheese can be represented as a rectangle of dimensions $a_i \\times b_i$. We want to arrange them on the two-dimensional plane such that:\n\n- Each edge of each cheese is parallel to either the x-axis or the y-axis.\n- The bottom edge of each cheese is a segment of the x-axis.\n- No two slices of cheese overlap, but their sides can touch.\n- They form one connected shape.\n\nNote that we can arrange them in any order (the leftmost slice of cheese is not necessarily the first slice of cheese). Also note that we can rotate each slice of cheese in any way as long as all conditions still hold.\n\nFind the minimum possible perimeter of the constructed shape.",
    "tutorial": "According to the problem, the arrays $a$ and $b$ denote the dimensions of the rectangles. Define arrays $c$ and $d$ as a certain orientation configuration of the rectangles with $c_i$ denoting the width and $d_i$ denoting the height. Define arrays $e$ and $f$ as a certain permutation of the orientation configuration such that the $i$-th rectangle from the left has width $e_i$ and height $f_i$. Consider a certain configuration of $e$ and $f$. The perimeter of the connected shape will be $2(e_1+e_2+\\ldots+e_n)+f_1+|f_1-f_2|+|f_2-f_3|+\\ldots+|f_{n-1}-f_n|+f_n$. Notice that if we sort the rectangles based on $f_i$, the perimeter would become $2(e_1+e_2+\\ldots+e_n+f_n)$. This is actually the minimum possible perimeter for a fixed configuration of $c$ and $d$ as we cannot get a smaller perimeter than this. This means, if we have a certain configuration of $c$ and $d$, the optimal perimeter is $2(c_1+c_2+\\ldots+c_n+\\max(d))$. Now, we just need to find a configuration of $c$ and $d$ from $a$ and $b$ that results in the minimum value of $2(c_1+c_2+\\ldots+c_n+\\max(d))$. Notice that each element of $a$ and $b$ can only be counted either $0$ or $2$ times in the final answer. Consider the maximum value out of all elements of $a$ and $b$. If there are multiple values that are maximum, just consider one of them. We can see that that value will always be counted $2$ times no matter how we construct $c$ and $d$. We need to determine whether to put that maximum value in $c$ (width) or $d$ (height). It is actually better to put that value in $d$ as it will cause all other values of $d$ to be counted $0$ times in the final answer. Now, we just need to determine the orientation for each of the other rectangles. We have determined that the maximum value in $a$ and $b$ must be put in $d$, which will automatically become the value of $\\max(d)$. Therefore, all other values in $d$ will be counted $0$ times in the final answer. This means, because we want to minimise the final answer, for each $i$, it is always better to put the larger value out of $a_i$ and $b_i$ in $d$ as it will cause the value that is not being counted in the final answer to be larger. Using every observation above, in order to get the minimum possible perimeter, we can do the following: Construct the arrays $c$ and $d$ with $c_i$ and $d_i$ taking their values from $a_i$ and $b_i$ while making $c_i\\leq d_i$. The answer is $2(c_1+c_2+\\ldots+c_n+\\max(d))$. Time complexity for each test case: $O(n)$",
    "tags": [
      "geometry",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1740",
    "index": "C",
    "title": "Bricks and Bags",
    "statement": "There are $n$ bricks numbered from $1$ to $n$. Brick $i$ has a weight of $a_i$.\n\nPak Chanek has $3$ bags numbered from $1$ to $3$ that are initially empty. For each brick, Pak Chanek must put it into one of the bags. After this, each bag must contain at least one brick.\n\nAfter Pak Chanek distributes the bricks, Bu Dengklek will take exactly one brick from each bag. Let $w_j$ be the weight of the brick Bu Dengklek takes from bag $j$. The score is calculated as $|w_1 - w_2| + |w_2 - w_3|$, where $|x|$ denotes the absolute value of $x$.\n\nIt is known that Bu Dengklek will take the bricks in such a way that minimises the score. What is the maximum possible final score if Pak Chanek distributes the bricks optimally?",
    "tutorial": "Firstly, sort $a$. From now on, we will always refer to the sorted array $a$. Let $p_j$ be the index of the brick taken by Bu Dengklek from bag $j$. The configuration of $p_1,p_2,p_3$ must be in the form of one of the following: $p_1 < p_2 < p_3$ $p_1 > p_2 > p_3$ $p_2 < \\min(p_1, p_3)$ $p_2 > \\max(p_1, p_3)$ Let's look at the third case. Let's consider the case where $\\min(p_1, p_3) > p_2+1$. If this is the case, let's look at all possible cases for the brick at index $p_2+1$. If Pak Chanek puts brick $p_2+1$ into bag $1$, it is more optimal for Bu Dengklek to take that brick from bag $1$ instead of $p_1$ because $a_{p_2+1}-a_{p_2} \\leq a_{p_1}-a_{p_2}$. If Pak Chanek puts brick $p_2+1$ into bag $2$, it is more optimal for Bu Dengklek to take that brick from bag $2$ instead of $p_2$ because $(a_{p_1}-a_{p_2+1})+(a_{p_3}-a_{p_2+1}) \\leq (a_{p_1}-a_{p_2})+(a_{p_3}-a_{p_2})$. If Pak Chanek puts brick $p_2+1$ into bag $3$, it is more optimal for Bu Dengklek to take that brick from bag $3$ instead of $p_3$ because $a_{p_2+1}-a_{p_2} \\leq a_{p_3}-a_{p_2}$. This means, choosing $p_1,p_2,p_3$ such that $\\min(p_1, p_3) > p_2+1$ is always less optimal for Bu Dengklek. Therefore, Bu Dengklek will take the bricks such that if $p_2 < \\min(p_1, p_3)$, then $\\min(p_1, p_3) = p_2 + 1$ also holds. A similar logic can be used for the fourth case. So, we can obtain that Bu Dengklek will always take the bricks such that the configuration of $p_1,p_2,p_3$ is in the form of one of the following: $p_1 < p_2 < p_3$ $p_1 > p_2 > p_3$ $p_2 < \\min(p_1, p_3)$ and $\\min(p_1, p_3) = p_2 + 1$ $p_2 > \\max(p_1, p_3)$ and $\\max(p_1, p_3) = p_2 - 1$ In fact, Pak Chanek is always able to force it such that the bricks taken by Bu Dengklek form any configuration of $p_1,p_2,p_3$ that follows one of the constraints above. Let's look at one possible construction. For a configuration of $p_1,p_2,p_3$ construct an order of the bags $j_1,j_2,j_3$ such that $p_{j_1}<p_{j_2}<p_{j_3}$. Then, Pak Chanek can force Bu Dengklek to choose that configuration by doing the following: Put the bricks at indices from $1$ to $p_{j_1}$ into bag $j_1$. Put the bricks at indices from $p_{j_1}+1$ to $p_{j_3}-1$ into bag $j_2$. Put the bricks at indices from $p_{j_3}$ to $n$ into bag $j_3$. Therefore, we just need to find the values of $p_1,p_2,p_3$ satisfying the constraints above such that $|a_{p_1}-a_{p_2}|+|a_{p_2}-a_{p_3}|$ is maximised. To maximise the final score, we can see that it is always more optimal to either use the third or the fourth case for $p_1,p_2,p_3$. For the third case, it is always more optimal to maximise $\\max(p_1, p_3)$, so we should set $\\max(p_1, p_3) = n$. A similar logic can be used for the fourth case to see that we should set $\\min(p_1, p_3) = 1$. Therefore, the maximum final score is the maximum of these two cases: $(a_i-a_{i-1})+(a_i-a_1)$ with $3 \\leq i \\leq n$. $(a_{i+1}-a_i)+(a_n-a_i)$ with $1 \\leq i \\leq n-2$. Time complexity for each test case: $O(n \\log n)$",
    "tags": [
      "constructive algorithms",
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1740",
    "index": "D",
    "title": "Knowledge Cards",
    "statement": "Pak Chanek, a renowned scholar, invented a card puzzle using his knowledge. In the puzzle, you are given a board with $n$ rows and $m$ columns. Let $(r, c)$ represent the cell in the $r$-th row and the $c$-th column.\n\nInitially, there are $k$ cards stacked in cell $(1, 1)$. Each card has an integer from $1$ to $k$ written on it. More specifically, the $i$-th card \\textbf{from the top} of the stack in cell $(1, 1)$ has the number $a_i$ written on it. It is known that no two cards have the same number written on them. In other words, the numbers written on the cards are a permutation of integers from $1$ to $k$. All other cells are empty.\n\nYou need to move the $k$ cards to cell $(n, m)$ to create another stack of cards. Let $b_i$ be the number written on the $i$-th card \\textbf{from the top} of the stack in cell $(n, m)$. You should create the stack in cell $(n, m)$ in such a way so that $b_i = i$ for all $1 \\leq i \\leq k$.\n\nIn one move, you can remove the \\textbf{top card} from a cell and place it onto an adjacent cell (a cell that shares a common side). If the target cell already contains one or more cards, you place your card \\textbf{on the top of the stack}. You must do each operation while satisfying the following restrictions:\n\n- Each cell other than $(1,1)$ and $(n,m)$ must not have more than one card on it.\n- You cannot move a card onto cell $(1,1)$.\n- You cannot move a card from cell $(n,m)$.\n\nGiven the values of $n$, $m$, $k$ and the array $a$, determine if the puzzle is solvable.",
    "tutorial": "Let card $c$ be the card with number $c$ written on it. Notice that we must put the cards into the stack in $(n,m)$ in order from card $k$, card $k-1$, card $k-2$, and so on until card $1$. The key observation for this problem is that, under given constraints, if we ignore cells $(1,1)$ and $(n,m)$ we can always move any card to either $(n-1,m)$ or $(n,m-1)$ if and only if there is at least one empty cell. We can obtain this by considering the fact that an empty cell can \"move\" to any cell and can be used to rotate any $2 \\times 2$ square of cells. Because $3 \\leq n, m$, if we ignore cells $(1,1)$ and $(n,m)$, each cell is a part of a $2 \\times 2$ square. Moving a desired card to a one of $(n-1,m)$ or $(n,m-1)$ can be done by firstly moving the empty cell to be adjacent to the desired card, and then only doing $2 \\times 2$ rotations that simultaneously move the empty cell and the desired card. Therefore, we can iterate the card in the stack $(1, 1)$ from top to bottom. While iterating, one should maintain all of the cards in the board that are not in cell $(1, 1)$ or $(n, m)$. We define those group of cards as active cards. Each time we put a move a card out of $(1, 1)$, we add the card to the active cards. Before finishing the iteration we will try to move one or more cards from the active cards to $(n, m)$ as long as there is a card we can move. We can maintain the active cards with a priority queue or a set. The active cards can be moved around freely if and only if there is at least one empty cell in the grid if we ignore $(1,1)$ and $(n,m)$. Therefore, to check whether or not we can solve the puzzle, we just need to check whether or not there exists a moment where the number of active cards exceed $nm-3$. There also exists a solution with a time complexity of $O(k)$ just by iterating the positions of each card number, but it will not be explained here. Time complexity for each test case: $O(k\\log k)$ or $O(k)$",
    "tags": [
      "constructive algorithms",
      "data structures"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1740",
    "index": "E",
    "title": "Hanging Hearts",
    "statement": "Pak Chanek has $n$ blank heart-shaped cards. Card $1$ is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card $i$ ($i > 1$) is hanging onto card $p_i$ ($p_i < i$).\n\nIn the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation $a$ of $[1, 2, \\dots, n]$. Then, the number written on card $i$ is $a_i$.\n\nAfter that, Pak Chanek must do the following operation $n$ times while maintaining a sequence $s$ (which is initially empty):\n\n- Choose a card $x$ such that no other cards are hanging onto it.\n- Append the number written on card $x$ to the end of $s$.\n- If $x \\neq 1$ and the number on card $p_x$ is larger than the number on card $x$, replace the number on card $p_x$ with the number on card $x$.\n- Remove card $x$.\n\nAfter that, Pak Chanek will have a sequence $s$ with $n$ elements. What is the maximum length of the longest non-decreasing subsequence$^\\dagger$ of $s$ at the end if Pak Chanek does all the steps optimally?\n\n$^\\dagger$ A sequence $b$ is a subsequence of a sequence $c$ if $b$ can be obtained from $c$ by deletion of several (possibly, zero or all) elements. For example, $[3,1]$ is a subsequence of $[3,2,1]$, $[4,3,1]$ and $[3,1]$, but not $[1,3,3,7]$ and $[3,10,4]$.",
    "tutorial": "The cards form a rooted tree with card $i$ being the root, where for each $i$ ($i>1$), the parent of card $i$ is $p_i$. Let $w_i$ be the number on card $i$ when it is about to get removed. To remove card $i$, we must previously remove all cards in the subtree of $i$ other than $i$ itself. Thus, we can see that $w_i$ is the minimum value of $a$ out of all cards in the subtree of $i$. Let the sequence $[v_1,v_2,v_3,\\ldots]$ mean that the $i$-th element of the longest non-decreasing subsequence comes from card $v_i$. Then, we can get the following observations: We can only remove card $i$ if all other cards in the subtree of $i$ have been removed. Hence, for each $v_i$, every $v_j$ with $j>i$ must not be in the subtree of $v_i$. We can make $v_{i+1}$ to be the ancestor of $v_i$ by making $w_{v_{i+1}}=w_{v_i}$. This can be done by making it such that the minimum value of $a$ in the subtree of $v_i$ is simultaneously the minimum value of $a$ in the subtree of $v_{i+1}$. If $v_{i+1}$ is not the ancestor of $v_i$, then $w_{v_{i+1}} \\neq w_{v_i}$ must hold. Because $v$ forms a non-decreasing sequence, then $w_{v_{i+1}} > w_{v_i}$ must hold. That means, $w_{v_{i+1}}$ is guaranteed to be larger than the values of $w$ for all ancestors of $v_i$. This means, after $v_{i+1}$, $v$ cannot continue with any ancestors of $v_i$. From the information above, it means that when constructing $v$, we do one the following operation several times: Append an ancestor of the last card. Append a card that is not an ancestor of the last card and not a descendant of any of the previous cards. After this, we cannot choose any ancestor of the card before this new card. In the optimal configuration, the sequence $v$ resembles the following: It consists of several paths of cards where each path is from a card to one of its ancestors. For any pair of cards from two different paths, one must not be an ancestor of the other. We will use dynamic programming on tree. Let $dp[i]$ denote the length of the longest non-decreasing subsequence created from only doing operations to the subtree of $i$. Then, we have two cases: If card $i$ is used in the longest non-decreasing subsequence, then the maximum answer is the maximum number of cards in a path from card $i$ to one of the cards in the subtree of $i$. If card $i$ is not used in the longest non-decreasing subsequence, then the maximum answer is the sum of $dp$ values of the children of card $i$. Time complexity: $O(n)$",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1740",
    "index": "F",
    "title": "Conditional Mix",
    "statement": "Pak Chanek is given an array $a$ of $n$ integers. For each $i$ ($1 \\leq i \\leq n$), Pak Chanek will write the one-element set $\\{a_i\\}$ on a whiteboard.\n\nAfter that, in one operation, Pak Chanek may do the following:\n\n- Choose two different sets $S$ and $T$ on the whiteboard such that $S \\cap T = \\varnothing$ ($S$ and $T$ do not have any common elements).\n- Erase $S$ and $T$ from the whiteboard and write $S \\cup T$ (the union of $S$ and $T$) onto the whiteboard.\n\nAfter performing zero or more operations, Pak Chanek will construct a multiset $M$ containing the sizes of all sets written on the whiteboard. In other words, each element in $M$ corresponds to the size of a set after the operations.\n\nHow many distinct$^\\dagger$ multisets $M$ can be created by this process? Since the answer may be large, output it modulo $998\\,244\\,353$.\n\n$^\\dagger$ Multisets $B$ and $C$ are different if and only if there exists a value $k$ such that the number of elements with value $k$ in $B$ is different than the number of elements with value $k$ in $C$.",
    "tutorial": "Let $cnt_i$ denote the number of occurrences of element $i$ in array $a$. Claim: A multiset $M$ of size $n$, $M_1,M_2,\\ldots,M_n$ where $M_1 \\geq M_2 \\geq \\ldots \\geq M_n \\geq 0$ is good if and only if $\\sum_{i=1}^{n} M_i=n$ and $\\sum_{i=1}^k M_i \\leq \\sum_{i=1}^n \\min(k,cnt_i)$ for every $1 \\leq k \\leq n$. The proof of that claim has been discussed in the comment section here. We proceed with formulating a dynamic programming solution. Let $dp[pos][sum][last]$ denote that we have picked a prefix $P_1,P_2,\\ldots,P_{pos}$ such that $\\sum_{i=1}^{pos} P_i = sum$ and $P_{pos}=last$. Our transition is going from $dp[pos][sum][last]$ to $dp[pos+1][sum+x][x]$ for all $x \\leq last$, this can be easily handled using prefix sums. However, we still have $O(n^3)$ states. We can cut down the number of states by noting that $n \\geq \\sum_{i=1}^{pos} P_i \\geq last \\cdot pos$. That is, for each value of $pos$, there are only $\\frac{n}{pos}$ values of $last$. Since $\\frac{n}{1}+\\frac{n}{2}+\\frac{n}{3}+\\ldots+\\frac{n}{n} \\approx n\\log n$, the number of states is bounded by $O(n^2 \\log n)$. Time complexity: $O(n^2 \\log n)$",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1740",
    "index": "G",
    "title": "Dangerous Laser Power",
    "statement": "Pak Chanek has an $n \\times m$ grid of portals. The portal on the $i$-th row and $j$-th column is denoted as portal $(i,j)$. The portals $(1,1)$ and $(n,m)$ are on the north-west and south-east corner of the grid respectively.\n\nThe portal $(i,j)$ has two settings:\n\n- \\textbf{Type} $t_{i,j}$, which is either $0$ or $1$.\n- \\textbf{Strength} $s_{i,j}$, which is an integer between $1$ and $10^9$ inclusive.\n\nEach portal has $4$ faces labelled with integers $0,1,2,3$, which correspond to the north, east, south, and west direction respectively.When a laser enters face $k$ of portal $(i, j)$ with speed $x_\\text{in}$, it leaves the portal going out of face $(k+2+t_{i,j}) \\bmod 4$ with speed $x_\\text{out} = \\max(x_\\text{in},s_{i,j})$. The portal also has to consume $x_\\text{out} - x_\\text{in}$ units of \\textbf{energy}.\n\nPak Chanek is very bored today. He will shoot $4nm$ lasers with an initial speed of $1$, one into each face of each portal. Each laser will travel throughout this grid of portals until it moves outside the grid or it has passed through $10^{100}$ portals.\n\nAt the end, Pak Chanek thinks that a portal is \\textbf{good} if and only if the total energy consumed by that portal modulo $2$ is equal to its type. Given the strength settings of all portals, find a way to assign the type settings of each portal such that the number of good portals is maximised.",
    "tutorial": "Claim: There is a construction where all portals are good. We will proceed with the construction. The key observation of the problem is that for a portal $(i,j)$ to consume energy, the laser must not enter a portal with a strength greater than or equal to $s_{i,j}$ before going through portal $(i,j)$. Let's say we already have the type settings of all lasers. Consider all possible lasers that at some point enters a certain face of portal $(i,j)$. We can find the paths of those lasers before entering portal $(i,j)$ by backtracking in that direction from portal $(i,j)$. Consider the first portal in that backtracking path that has a strength greater than or equal to $s_{i,j}$. Notice that all lasers that starts from portals that are located after that portal in the backtracking path must go through that portal before entering portal $(i,j)$. Therefore, those lasers cannot make portal $(i,j)$ use energy, which means they can be ignored. Using the observation above, we can see that we must only backtrack until we find a portal with a strength greater than or equal to $s_{i,j}$. Observe that to get the path up to that point, the type settings we should know are only the type settings of portals with strengths smaller than $s_{i,j}$. Therefore, the construction can be generated by calculating the type settings of the portals from the smallest to the largest strengths. In each iteration, we use the type settings of the previous portals to find the backtracking paths of the current portal. If we already know the $4$ backtracking paths for each of the $4$ directions of that portal, we can find the total energy that portal will consume in the end, which means we can find the type setting for that portal that makes it a good portal. The naive implementation of this has a time complexity of $O(n^2m^2)$. Notice that each backtracking path of the portals are just the merging of smaller paths. We can maintain a disjoint set data structure to handle this while maintaining the essential values needed in the calculation of the total energy consumed for each path. Time complexity: $O(nm)$",
    "tags": [
      "constructive algorithms",
      "dsu",
      "sortings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1740",
    "index": "H",
    "title": "MEX Tree Manipulation",
    "statement": "Given a rooted tree, define the value of vertex $u$ in the tree recursively as the MEX$^\\dagger$ of the \\textbf{values of its children}. Note that it is only the children, not all of its descendants. In particular, the value of a leaf is $0$.\n\nPak Chanek has a rooted tree that initially only contains a single vertex with index $1$, which is the root. Pak Chanek is going to do $q$ queries. In the $i$-th query, Pak Chanek is given an integer $x_i$. Pak Chanek needs to add a new vertex with index $i+1$ as the child of vertex $x_i$. After adding the new vertex, Pak Chanek needs to recalculate the values of all vertices and report the sum of the values of all vertices in the current tree.\n\n$^\\dagger$ The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For example, the MEX of $[0,1,1,2,6,7]$ is $3$ and the MEX of $[6,9]$ is $0$.",
    "tutorial": "Define $\\text{MEX}_i(A)$ of a certain array $A$ as the $i$-th smallest non-negative integer that does not belong to the array. Let's solve a simpler problem. Imagine that you are given an array $A$, you are asked to append a new element $x$ to the array, and you need to calculate the MEX of the array after the operation. It is easy to see that the new value of MEX is either $\\text{MEX}_1(A)$ if $x \\neq \\text{MEX}_1(A)$ or $\\text{MEX}_2(A)$ if $x = \\text{MEX}_1(A)$ where $A$ is the array before the operation. Let $(x, y, z)$ define a relationship between input and output which means: If the input is not $x$, then the output is $y$. If the input is $x$, then the output is $z$. This means the relationship between the new element to be appended to $A$ and the new value of MEX can be expressed as $(\\text{MEX}_1(A), \\text{MEX}_1(A), \\text{MEX}_2(A))$. Define that triple as $\\text{MEXtuple}(A)$. Define the heavy child of vertex $u$ as the child with the largest subtree size. If there are children with the same subtree size, choose one of them. Let's call each child other than the heavy child as a light child. In particular, the edge that connects a vertex to its heavy child is called a heavy edge. Let $C_u$ be the array that contains the values of the light children of vertex $u$. We can see that if we maintain $\\text{MEXtuple}(C_u)$ we can get the relationship between the value of the heavy child and the value of vertex $u$. Let's consider a path in the tree that traverses through parents while only using heavy edges. Consider the relationship between the value of the vertex at the beginning of the path and the end of the path. Let's calculate the $\\text{MEXtuple}$ for each vertex in the path other than the first one. We can see that we can get the relationship between the vertex in the beginning of the path and the end of the path using those $\\text{MEXtuple}$ values. In fact, that relationship can also be expressed as a triple $(x, y, z)$ defined above. Let's decompose the tree into chains of heavy edges. For each chain, construct a segment tree with each node in the segment tree calculating the relationship triple $(x, y, z)$ for a segment of the chain. Suppose we want to add a new vertex. The vertices that have their values changed are the ones that lie on the path from the new vertex to the root. Observe that that path only traverses through at most $O(\\log Q)$ different heavy edge chains. For each chain, we can get the value of the vertex at the end of the chain by doing a point update on the chain's segment tree. When we move between two different chains, we update the $C_u$ for a vertex and recalculate it's $\\text{MEXtuple}$ in $O(\\log Q)$ time complexity using a set or another segment tree. We repeat this process until we reach the root. We can calculate that the total complexity of a single query is $O(\\log^2 Q)$. To get the sum of the values of the entire tree after an operation, we can store two new variables in each node of the segment tree of each chain that represents the sum of the chain segment for the two possible cases of the input. Time complexity: $O(Q \\log^2 Q)$",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1740",
    "index": "I",
    "title": "Arranging Crystal Balls",
    "statement": "In the world of Compfestnesia, Pak Chanek discovers a secret underground dungeon. Inside it, there is a treasure chest that is surrounded by $n$ statues that are arranged in a circular manner. The statues are numbered from $0$ to $n-1$ with statue $i$ being to the left of statue $i+1$ and statue $n-1$ being to the left of statue $0$.\n\nPak Chanek observes that each statue is holding a crystal ball with an integer between $0$ and $m-1$ inclusive. Let's say the integer in the crystal ball of statue $i$ is $a_i$.\n\nThe dungeon provides instructions that every integer in the crystal balls must be $0$ in order to open the treasure chest. To achieve that, Pak Chanek is given an integer $k$, and he can do zero or more operations. In a single operation, Pak Chanek does the following:\n\n- Choose exactly $k$ consecutive statues. In other words, choose the statues $p, (p+1) \\bmod n, (p+2) \\bmod n, (p+3) \\bmod n, \\ldots, (p+k-1) \\bmod n$ for some chosen index $p$.\n- Do one of the following:\n\n- For all chosen statues, change their values of $a_i$ into $(a_i+1) \\bmod m$.\n- For all chosen statues, change their values of $a_i$ into $(a_i-1) \\bmod m$.\n\nHelp Pak Chanek find the minimum possible number of operations to open the treasure chest.",
    "tutorial": "Let's simplify the problem such that the only possible operation for each $k$ chosen statues is $a_i := (a_i - 1) \\bmod m$. To solve this, we first define $c_i$ as the number of times we do that operation for the statues $i, (i-1) \\bmod n, (i-2) \\bmod n, (i-3) \\bmod n, \\ldots, (i-k+1) \\bmod n$. We can see that in the optimal configuration, $0 \\leq c_i \\leq m-1$ must hold. For it to make each element of $a$ to be $0$, $(c_i+c_{(i+1)\\bmod n}+c_{(i+2)\\bmod n}+\\ldots+c_{(i+k-1)\\bmod n})\\bmod m=a_i$ must hold. The number of operations is equal to $c_0+c_1+c_2+\\ldots+c_{n-1}$. In order to extend to the original problem, we can see that for a given array $c$, the number of operations that can be made to be equal to $\\sum_{i=0}^{n-1}\\min(c_i,m-c_i)$. So we need to find an array $c$ satisfying the conditions above such that $\\sum_{i=0}^{n-1}\\min(c_i,m-c_i)$ is as small as possible. We can see that $a_{(i+1)\\bmod n} - a_i = c_{(i+k) \\bmod n} - c_i$. That means, if we have determined the value of $c_i$, the value of $c_{(i+k) \\bmod n}$ is forced. If we form an edge for each pair of indices $(i, (i+k) \\bmod n)$, we will get $\\text{GCD}(n,k)$ connected components. This means if we have determined the value of one vertex for each connected component, the values of the entire array $c$ are forced. However, we must also consider possibility that at least one connected component cannot have assigned values that satisfy all of its edges. In that case, it is impossible to finish the objective of the problem. Define $d=\\text{GCD}(n,k)$. For each $c_i$, we can find the difference relationship between it and $c_{i \\bmod d}$. Therefore, to answer the problem, we must find the values of $c_0, c_1, c_2, \\ldots, c_{d-1}$ such that $c_0+c_1+c_2+\\ldots+c_{k-1}=a_0$ and if all the other values of $c$ are calculated, $\\sum_{i=0}^{n-1}\\min(c_i,m-c_i)$ is as small as possible. For the $c_0+c_1+c_2+\\ldots+c_{k-1}=a_0$ condition, using simple modular algebra, we can calculate one or more values $b_1,b_2,b_3,\\ldots$ such that $c_0+c_1+c_2+\\ldots+c_{k-1}=a_0$ if and only if $c_0+c_1+c_2+\\ldots+c_{d-1}$ is equal to one of the values of $b$. Let's consider the connected component $c_i, c_{i+d}, c_{i+2d}, \\ldots$. It must have $\\frac{n}{d}$ elements. Define $f_i(x)$ as the sum of $\\min(c_j,m-c_j)$ for all elements of $c_j$ in that connected component if $c_i=x$. We can easily calculate all values of $f_i(x)$ for all connected components in $O(nm)$. After this, we must the minimum value of $f_0(c_0)+f_1(c_1)+f_2(c_2)+\\ldots+f_{d-1}(c_{d-1})$ such that $c_0+c_1+c_2+\\ldots+c_{d-1}$ is equal to one of the values of $b$. This can be solved using modular knapsack dynamic programming, but the time complexity is $O(nm^2)$. We must optimise it further. Consider the contribution of a single element $c_j$ to the values of $f_i(x)$ of its connected component. Let's say the difference relationship is that $c_i-c_j=w$ must hold. Notice that: It adds $(x-w)\\bmod m$ to all values of $f_i(x)$ for each $x$ going up modularly from $w$ to $(w+\\lfloor\\frac{m}{2}\\rfloor)\\bmod m$ It adds $(w-x)\\bmod m$ to all values of $f_i(x)$ for each $x$ going up modularly from $(w+\\lceil\\frac{m}{2}\\rceil)\\bmod m$ to $w$. We can see it as \"changing slope\" at most three times, namely in $x=w$, $x=(w+\\lfloor\\frac{m}{2}\\rfloor)\\bmod m$, and $x=(w+\\lceil\\frac{m}{2}\\rceil)\\bmod m$. This means, if we add up all contributions of each element, the number of points the slope changes in one connected component is at most $\\frac{3n}{d}$. We will call these points as special points. Consider an array $c_0, c_1, c_2, \\ldots, c_{d-1}$ satisfying the condition that $c_0+c_1+c_2+\\ldots+c_{d-1}$ is equal to one of the values of $b$. Consider the case if there exists at least two different indices $i$ such that the value of $c_i$ is not a special point in $f_i$. Suppose the indices are $i_1$ and $i_2$. Since both of them are not special points, the slope between $(c_{i_1}-1)\\bmod m$ and $c_{i_1}$ is the same as the slope between $c_{i_1}$ and $(c_{i_1}+1)\\bmod m$. The same is true for $i_2$. Let's say $z_1$ is the increase in value of the final answer if we do $c_{i_1}:=(c_{i_1}+1)\\bmod m$ and $c_{i_2}:=(c_{i_2}-1)\\bmod m$, and $z_2$ is the increase in value of the final answer if we do $c_{i_1}:=(c_{i_1}-1)\\bmod m$ and $c_{i_2}:=(c_{i_2}+1)\\bmod m$. From the observation above, we can see that $z_1 = -z_2$, which means one of them is non-positive. This means, if this is the case, we can always change the array $c$ into another array with an equal or smaller final answer. This means, we can always do that operation to get an array $c$ such that there is at most one non-special point. Therefore, we can just consider those cases to find the minimum answer. We can solve this using divide and conquer. We first call the recursive function $\\text{dnc}(0,d-1)$. The moment we call the function $\\text{dnc}(l,r)$, we have made the modular knapsack dynamic programming array if we have only considered the indices $i$ with $i<l$ or $r<i$ and only considering their special points. $\\text{dnc}(l,r)$ recurses into $\\text{dnc}(l,\\frac{l+r}{2})$ and $\\text{dnc}(\\frac{l+r}{2}+1,r)$. Once $l=r$, we will consider that index as the one that can have a non-special point, then we can just iterate the array $b$ and take the answer from the knapsack array. The depth of the recursion is at most $O(\\log d)$. Each depth has insertions of $O(d)$ indices to the knapsack. Because each connected component only has $O(\\frac{n}{d})$ special points, each depth does $O(n)$ dynamic programming transitions with each transition having $O(m)$ time complexity. Time complexity: $O(nm \\log (\\text{GCD}(n,k)))$",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "geometry",
      "graphs",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1741",
    "index": "A",
    "title": "Compare T-Shirt Sizes",
    "statement": "Two T-shirt sizes are given: $a$ and $b$. The T-shirt size is either a string M or a string consisting of several (possibly zero) characters X and one of the characters S or L.\n\nFor example, strings M, XXL, S, XXXXXXXS could be the size of some T-shirts. And the strings XM, LL, SX are not sizes.\n\nThe letter M stands for medium, S for small, L for large. The letter X refers to the degree of size (from eXtra). For example, XXL is extra-extra-large (bigger than XL, and smaller than XXXL).\n\nYou need to compare two given sizes of T-shirts $a$ and $b$.\n\nThe T-shirts are compared as follows:\n\n- any small size (no matter how many letters X) is smaller than the medium size and any large size;\n- any large size (regardless of the number of letters X) is larger than the medium size and any small size;\n- the more letters X before S, the smaller the size;\n- the more letters X in front of L, the larger the size.\n\nFor example:\n\n- XXXS < XS\n- XXXL > XL\n- XL > M\n- XXL = XXL\n- XXXXXS < M\n- XL > XXXS",
    "tutorial": "Let $sa$, $sb$ are the last characters of lines $a$ and $b$ respectively. And $|a|, |b|$ are the sizes of these strings. $sa \\neq sb$: then the answer depends only on $sa$ and $sb$ and is uniquely defined as the inverse of $sa$ to $sb$ (\"<\" if $sa > sb$, \">\" if $sa < sb$, since the characters S, M, L are in reverse order in the alphabet). $sa = sb$: $|a| = |b|$. Then the answer is \"=\". This also covers the case $sa = sb =$M; $sa = sb =$S. Then the larger the size of the string, the smaller the size of the t-shirt. That is, the answer is \"<\" if $|a| > |b|$ and \">\" if $|a| < |b|$; $sa = sb =$L. Then the larger the size of the string, the smaller the size of the t-shirt. That is, the answer is \"<\" if $|a| < |b|$ and \">\" if $|a| > |b|$; $|a| = |b|$. Then the answer is \"=\". This also covers the case $sa = sb =$M; $sa = sb =$S. Then the larger the size of the string, the smaller the size of the t-shirt. That is, the answer is \"<\" if $|a| > |b|$ and \">\" if $|a| < |b|$; $sa = sb =$L. Then the larger the size of the string, the smaller the size of the t-shirt. That is, the answer is \"<\" if $|a| < |b|$ and \">\" if $|a| > |b|$;",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n \n \nvoid ct(char c) {\n    cout << c << '\\n';\n}\n \nvoid solve() {\n    string a,b; cin >> a >> b;\n    char ca = a.back();\n    char cb = b.back();\n    if (ca == cb) {\n        if (sz(a) == sz(b)) cout << '=';\n        else if (ca == 'S') {\n            cout << (sz(a) < sz(b) ? '>' : '<');\n        } else {\n            cout << (sz(a) < sz(b) ? '<' : '>');\n        }\n    }else cout << (ca < cb ? '>' : '<');\n    cout << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n \n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1741",
    "index": "B",
    "title": "Funny Permutation",
    "statement": "A sequence of $n$ numbers is called permutation if it contains all numbers from $1$ to $n$ exactly once. For example, the sequences $[3, 1, 4, 2]$, [$1$] and $[2,1]$ are permutations, but $[1,2,1]$, $[0,1]$ and $[1,3,4]$ are not.\n\nFor a given number $n$ you need to make a permutation $p$ such that two requirements are satisfied at the same time:\n\n- For each element $p_i$, at least one of its neighbors has a value that differs from the value of $p_i$ by one. That is, for each element $p_i$ ($1 \\le i \\le n$), at least one of its neighboring elements (standing to the left or right of $p_i$) must be $p_i + 1$, or $p_i - 1$.\n- the permutation must have no fixed points. That is, for every $i$ ($1 \\le i \\le n$), $p_i \\neq i$ must be satisfied.\n\nLet's call the permutation that satisfies these requirements funny.\n\nFor example, let $n = 4$. Then [$4, 3, 1, 2$] is a funny permutation, since:\n\n- to the right of $p_1=4$ is $p_2=p_1-1=4-1=3$;\n- to the left of $p_2=3$ is $p_1=p_2+1=3+1=4$;\n- to the right of $p_3=1$ is $p_4=p_3+1=1+1=2$;\n- to the left of $p_4=2$ is $p_3=p_4-1=2-1=1$.\n- for all $i$ is $p_i \\ne i$.\n\nFor a given positive integer $n$, output \\textbf{any} funny permutation of length $n$, or output -1 if funny permutation of length $n$ does not exist.",
    "tutorial": "We cannot make a funny permutation only when $n = 3$, because one of the neighboring elements of $3$ must be equal to $2$. Any permutation made in this way will not satisfy the conditions: The permutation [$3, 2, 1$] will have a fixed point $p_2 = 2$. The permutation [$1, 3, 2$] will have a fixed point $p_1 = 1$. The permutation [$2, 3, 1$] will not have a neighbor equal to $p_3 + 1 = 1 + 1 = 2$ for $p_3 = 1$. For the remaining values of $n$, make the following observations: For $n = 2$, the only funny permutation is [$2, 1$]. When $n \\ge 4$, permutations of the form [$3, \\dots, n, 2, 1$] will always be funny because all elements $p_i$ will have a neighbor equal to $p_i - 1$ or $p_i + 1$, and the permutation will have no fixed points ($p_{n-1} = 2$, $p_n = 1$, and for $3 \\le i \\le n - 2$ will always be true $p_i = i + 2$).",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nvoid solve(){\n    int n;\n    cin >> n;\n    if(n == 3){\n        cout << -1 << endl;\n    }\n    else{\n        for(int i = 3; i <= n; i++) cout << i << ' ';\n        cout << 2 << ' ' << 1 << endl;\n    }\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1741",
    "index": "C",
    "title": "Minimize the Thickness",
    "statement": "You are given a sequence $a=[a_1,a_2,\\dots,a_n]$ consisting of $n$ \\textbf{positive} integers.\n\nLet's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by $a[l,r]$ a segment of the sequence $a$ with the left end in $l$ and the right end in $r$, i.e. $a[l,r]=[a_l, a_{l+1}, \\dots, a_r]$.\n\nFor example, if $a=[31,4,15,92,6,5]$, then $a[2,5]=[4,15,92,6]$, $a[5,5]=[6]$, $a[1,6]=[31,4,15,92,6,5]$ are segments.\n\nWe split the given sequence $a$ into segments so that:\n\n- each element is in \\textbf{exactly} one segment;\n- the sums of elements for all segments are \\textbf{equal}.\n\nFor example, if $a$ = [$55,45,30,30,40,100$], then such a sequence can be split into three segments: $a[1,2]=[55,45]$, $a[3,5]=[30, 30, 40]$, $a[6,6]=[100]$. Each element belongs to exactly segment, the sum of the elements of each segment is $100$.\n\nLet's define thickness of split as the length of the longest segment. For example, the thickness of the split from the example above is $3$.\n\nFind the minimum thickness among all possible splits of the given sequence of $a$ into segments in the required way.",
    "tutorial": "Let's iterate over the length of the first segment of the split. Having fixed it, we actually fixed the sum that needs to be collected on all other segments. Since each element must belong to exactly one segment, we can build other segments greedily. If we have found a solution, we will remember the length of the longest segment in it and try to update the answer. We have $n$ possible lengths of the first segment, for each of which we greedily built the answer for $n$. Thus, the asymptotics of the solution will be $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 2020;\n\nint n;\nint arr[MAXN];\n\nint go(int i, int sum) {\n\tif (i == n) return 0;\n\tfor (int j = i + 1, cur = 0; j <= n; ++j) {\n\t\tcur += arr[j - 1];\n\t\tif (cur > sum) return n;\n\t\tif (cur == sum) return max(j - i, go(j, sum));\n\t}\n\treturn n;\n}\n\nint solve() {\n\tint ans = n;\n\tfor (int len = 1, sum = 0; len < n; ++len) {\n\t\tsum += arr[len - 1];\n\t\tans = min(ans, go(0, sum));\n\t}\n\treturn ans;\n}\n\nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tcin >> n;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tcin >> arr[i];\n\t\tcout << solve() << endl;\n\t}\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1741",
    "index": "D",
    "title": "Masha and a Beautiful Tree",
    "statement": "The girl named Masha was walking in the forest and found a complete binary tree of height $n$ and a permutation $p$ of length $m=2^n$.\n\nA complete binary tree of height $n$ is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is $n$. The picture below shows the complete binary tree for $n=2$.\n\nA permutation is an array consisting of $n$ different integers from $1$ to $n$. For example, [$2,3,1,5,4$] is a permutation, but [$1,2,2$] is not ($2$ occurs twice), and [$1,3,4$] is also not a permutation ($n=3$, but there is $4$ in the array).\n\nLet's enumerate $m$ leaves of this tree from left to right. The leaf with the number $i$ contains the value $p_i$ ($1 \\le i \\le m$).\n\nFor example, if $n = 2$, $p = [3, 1, 4, 2]$, the tree will look like this:\n\nMasha considers a tree beautiful if the values in its leaves are ordered from left to right in increasing order.\n\nIn one operation, Masha can choose any non-leaf vertex of the tree and swap its left and right sons (along with their subtrees).\n\nFor example, if Masha applies this operation to the root of the tree discussed above, it will take the following form:\n\nHelp Masha understand if she can make a tree beautiful in a certain number of operations. If she can, then output the minimum number of operations to make the tree beautiful.",
    "tutorial": "Let some vertex be responsible for a segment of leaves $[l..r]$. Then her left son is responsible for the segment $[l..\\frac{l+r-1}{2}]$, and the right for the segment $[\\frac{l+r+1}{2}..r]$. Note that if we do not apply the operation to this vertex, then it will not be possible to move some element from the right son's segment to the left son's segment. It remains to understand when we need to apply the operation to the vertex. Let the maximum on the segment $[l..r]$ be $max$, the minimum on the same segment is $min$. Then if $min$ lies in the right son, and $max$ in the left, then we should obviously apply the operation, for the reason described above. In the case when $min$ lies in the left son, and $max$ in the right, the application of the operation will definitely not allow you to get a solution. Let's continue to act in a similar way recursively from the children of the current vertex. At the end, we should check whether we have received a sorted permutation. The above solution works for $O(nm)$, since there are $n$ levels in the tree and at each level, vertexes are responsible for $m$ sheets in total. You can optimize this solution to $O(m)$ if you pre-calculate the maximum and minimum for each vertex.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXM = 300300;\n\nint n, m;\nint arr[MAXM];\n\nint solve(int l, int r) {\n\tif (r - l == 1) return 0;\n\tint mid = (l + r) >> 1;\n\tint mal = *max_element(arr + l, arr + mid);\n\tint mar = *max_element(arr + mid, arr + r);\n\tint ans = 0;\n\tif (mal > mar) {\n\t\t++ans;\n\t\tfor (int i = 0; i < (mid - l); ++i)\n\t\t\tswap(arr[l + i], arr[mid + i]);\n\t}\n\treturn solve(l, mid) + solve(mid, r) + ans;\n}\n\nint solve() {\n\tint ans = solve(0, m);\n\tif (is_sorted(arr, arr + m))\n\t\treturn ans;\n\treturn -1;\n}\n\nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tcin >> m;\n\t\tfor (int i = 0; i < m; ++i)\n\t\t\tcin >> arr[i];\n\t\tcout << solve() << endl;\n\t}\n}",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "graphs",
      "sortings",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1741",
    "index": "E",
    "title": "Sending a Sequence Over the Network",
    "statement": "The sequence $a$ is sent over the network as follows:\n\n- sequence $a$ is split into segments (each element of the sequence belongs to exactly one segment, each segment is a group of consecutive elements of sequence);\n- for each segment, its length is written next to it, either to the left of it or to the right of it;\n- the resulting sequence $b$ is sent over the network.\n\nFor example, we needed to send the sequence $a = [1, 2, 3, 1, 2, 3]$. Suppose it was split into segments as follows: $[\\textcolor{red}{1}] + [\\textcolor{blue}{2, 3, 1}] + [\\textcolor{green}{2, 3}]$. Then we could have the following sequences:\n\n- $b = [1, \\textcolor{red}{1}, 3, \\textcolor{blue}{2, 3, 1}, \\textcolor{green}{2, 3}, 2]$,\n- $b = [\\textcolor{red}{1}, 1, 3, \\textcolor{blue}{2, 3, 1}, 2, \\textcolor{green}{2, 3}]$,\n- $b = [\\textcolor{red}{1}, 1, \\textcolor{blue}{2, 3, 1}, 3, 2, \\textcolor{green}{2, 3}]$,\n- $b = [\\textcolor{red}{1}, 1,\\textcolor{blue}{2, 3, 1}, 3, \\textcolor{green}{2, 3}, 2]$.\n\nIf a different segmentation had been used, the sent sequence might have been different.\n\nThe sequence $b$ is given. Could the sequence $b$ be sent over the network? In other words, is there such a sequence $a$ that converting $a$ to send it over the network could result in a sequence $b$?",
    "tutorial": "Let's introduce the dynamics. $dp[i] = true$ if on the prefix $i$ the answer is Yes. Then in this sequence $b$ the numbers corresponding to the sizes of the segments from the partition $a$ into subsegments will be called interesting. A number at position $i$ in the sequence $b$, if it is interesting, is either to the right or to the left of the segment. If it is to the left of the segment, it can only be interesting if $dp[i-1] = true$. Then $dp[i + b[i]] = true$. If it is on the right side of the segment, then if $dp[i - b[i] - 1] = true$, then $dp[i] = true$. The answer for the whole sequence is Yes if $dp[n] = true$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\n\n\nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n+1);\n    for (int i = 1; i <= n; ++i) {\n        cin >> a[i];\n    }\n\n    vector<bool> dp(n+1, false);\n    dp[0] = true;\n    for (int i = 1; i <= n; ++i) {\n        if (i + a[i] <= n && dp[i-1]) dp[i + a[i]] = true;\n        if (i - a[i] - 1 >= 0 && dp[i - a[i] - 1]) dp[i] = true;\n    }\n    cout << (dp[n] ? \"YES\" : \"NO\") << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1741",
    "index": "F",
    "title": "Multi-Colored Segments",
    "statement": "Dmitry has $n$ segments of different colors on the coordinate axis $Ox$. Each segment is characterized by three integers $l_i$, $r_i$ and $c_i$ ($1 \\le l_i \\le r_i \\le 10^9, 1 \\le c_i \\le n$), where $l_i$ and $r_i$ are are the coordinates of the ends of the $i$-th segment, and $c_i$ is its color.\n\nDmitry likes to find the minimum distances between segments. However, he considers pairs of segments of the same color uninteresting. Therefore, he wants to know for each segment the distance from this segment to the nearest \\textbf{differently} colored segment.\n\nThe distance between two segments is the minimum of the distances between a point of the first segment and a point of the second segment. In particular, if the segments intersect, then the distance between them is equal to $0$.\n\nFor example, Dmitry has $5$ segments:\n\n- The first segment intersects with the second (and these are segments of different colors), so the answers for them are equal to $0$.\n- For the $3$-rd segment, the nearest segment of a different color is the $2$-nd segment, the distance to which is equal to $2$.\n- For the $4$-th segment, the nearest segment of a different color is the $5$-th segment, the distance to which is equal to $1$.\n- The $5$-th segment lies inside the $2$-nd segment (and these are segments of different colors), so the answers for them are equal to $0$.",
    "tutorial": "Let's go through the segments $2$ times: in non-decreasing coordinates of the left end, and then - in non-increasing coordinates of the right end. To walk a second time, just multiply the coordinates of the left and right borders by $-1$, and then swap them and walk from left to right. Going through the segments in non-decreasing coordinates of the left end, you need to find for each segment a segment that starts not to the right of the current one and ends as far to the right as possible. If the coordinate of its right end is not less than the coordinate of the left end of the current segment, then it intersects with it, otherwise the distance between them is equal to the distance between the coordinate of the left end of the current segment and the maximum coordinate of the right end of the segment starting to the left of ours. Note that it is enough for us to store no more than $2$ segments: for each color we will store the maximum right coordinate of the segment of this color, which has already been considered. If we store the $2$ colors with the largest right coordinates, then one of them is definitely not equal to the current one. When considering a segment, we add it to the list, and if the size of the list becomes $3$, then we leave $2$ of optimal elements.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <queue>\n\nusing namespace std;\n\nint n;\n\nvector<int> calc(vector<vector<int>> a) {\n    vector<pair<int, int>> l(n), r(n);\n    for (int i = 0; i < n; ++i) {\n        l[i] = {a[i][0], i};\n        r[i] = {a[i][1], i};\n    }\n    sort(l.begin(), l.end());\n    sort(r.begin(), r.end());\n    vector<vector<pair<int, int>>> suf(n);\n    vector<pair<int, int>> curr;\n    for (int i0 = n - 1; i0 >= 0; --i0) {\n        int xr = r[i0].first;\n        int i = r[i0].second;\n        int xl = a[i][0];\n        int c = a[i][2];\n        if (curr.empty()) {\n            curr.emplace_back(xl, c);\n        } else if (curr.size() == 1) {\n            if (curr[0].second == c) {\n                curr[0].first = min(curr[0].first, xl);\n            } else {\n                curr.emplace_back(xl, c);\n            }\n        } else {\n            if (curr[0].second == c) {\n                curr[0].first = min(curr[0].first, xl);\n            } else if (curr[1].second == c) {\n                curr[1].first = min(curr[1].first, xl);\n            } else {\n                curr.emplace_back(xl, c);\n            }\n        }\n        sort(curr.begin(), curr.end());\n        if (curr.size() == 3) {\n            curr.pop_back();\n        }\n        suf[i0] = curr;\n    }\n    vector<int> ans(n, 1e9);\n    int j = 0;\n    for (int i0 = 0; i0 < n; ++i0) {\n        int xl = l[i0].first, i = l[i0].second;\n        int xr = a[i][1], c = a[i][2];\n        while (j < n && r[j].first < xl) {\n            j++;\n        }\n        if (j < n) {\n            vector<pair<int, int>> s = suf[j];\n            if (s[0].second != c) {\n                ans[i] = min(ans[i], max(0, s[0].first - xr));\n            } else if (s.size() == 2) {\n                ans[i] = min(ans[i], max(0, s[1].first - xr));\n            }\n        }\n    }\n    return ans;\n}\n\nconst int K = 1e9 + 1;\n\nvoid solve() {\n    cin >> n;\n    vector<vector<int>> a(n, vector<int>(3)), b(n, vector<int>(3));\n    vector<pair<int, int>> l(n), r(n);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            cin >> a[i][j];\n            if (j == 2) {\n                b[i][j] = a[i][j];\n            } else {\n                b[i][1 - j] = K - a[i][j];\n            }\n        }\n    }\n    vector<int> ans1 = calc(a), ans2 = calc(b);\n    for (int i = 0; i < n; ++i) {\n        cout << min(ans1[i], ans2[i]) << ' ';\n    }\n    cout << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0), cout.tie(0);\n    int t = 1;\n    cin >> t;\n    for (int it = 0; it < t; ++it) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "math",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1741",
    "index": "G",
    "title": "Kirill and Company",
    "statement": "Kirill lives on a connected undirected graph of $n$ vertices and $m$ edges at vertex $1$. One fine evening he gathered $f$ friends, the $i$-th friend lives at the vertex $h_i$. So all friends are now in the vertex $1$, the $i$-th friend must get to his home to the vertex $h_i$.\n\nThe evening is about to end and it is time to leave. It turned out that $k$ ($k \\le 6$) of his friends have no cars, and they would have to walk if no one gives them a ride. One friend with a car can give a ride to \\textbf{any} number of friends without cars, but only if he can give them a ride by driving along one of the \\textbf{shortest} paths to his house.\n\nFor example, in the graph below, a friend from vertex $h_i=5$ can give a ride to friends from the following sets of vertices: $[2, 3]$, $[2, 4]$, $[2]$, $[3]$, $[4]$, but can't give a ride to friend from vertex $6$ or a set $[3, 4]$.\n\n\\begin{center}\n{\\small The vertices where friends without cars live are highlighted in green, and with cars — in red.}\n\\end{center}\n\nKirill wants as few friends as possible to have to walk. Help him find the \\textbf{minimum} possible number.",
    "tutorial": "To begin with, let's learn how to find possible sets of friends for the vertex, whom he can give a ride, in the form of masks. Let's use a breadth first search, every time we find the shortest path to the vertex $u$ with the previous vertex $v$, we will add the masks of the vertex $v$ to the masks of the vertex $u$, updating them with friends living in $u$. Now, according to the resulting sets, you need to get the best combination of them. We will find it using the knapsack problem, we will use masks as weights, and the total weight will be the bitwise OR of the selected set.",
    "code": "from collections import deque\n \n \ndef solve():\n    n, m = map(int, input().split())\n    sl = [[] for _ in range(n)]\n    for _ in range(m):\n        u, v = map(int, input().split())\n        u -= 1\n        v -= 1\n        sl[u] += [v]\n        sl[v] += [u]\n    f = int(input())\n    h = [int(x) - 1 for x in input().split()]\n    mask = [0] * n\n    k = int(input())\n    p = [int(x) - 1 for x in input().split()] + [-1]\n    for i in range(k):\n        mask[h[p[i]]] += 1 << i\n    vars = [set() for _ in range(n)]\n    dist = [-1] * n\n    dist[0] = 0\n    vars[0].add(mask[0])\n    q = deque([0])\n    while len(q) > 0:\n        v = q.popleft()\n        for u in sl[v]:\n            if dist[u] == -1:\n                dist[u] = dist[v] + 1\n                q.append(u)\n            if dist[u] == dist[v] + 1:\n                for msk in vars[v]:\n                    vars[u].add(msk | mask[u])\n    backpack = [False] * (1 << k)\n    backpack[0] = True\n    j = 0\n    for i in range(f):\n        if i == p[j]:\n            j += 1\n            continue\n        nw = backpack.copy()\n        for msk in range(1 << k):\n            if not backpack[msk]:\n                continue\n            for var in vars[h[i]]:\n                nw[msk | var] = True\n        backpack, nw = nw, backpack\n    mn = k\n    for msk in range(1 << k):\n        if not backpack[msk]:\n            continue\n        ans = 0\n        for b in range(k):\n            if msk & (1 << b) == 0:\n                ans += 1\n        mn = min(mn, ans)\n    print(mn)\n \n \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp",
      "flows",
      "graphs",
      "shortest paths"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1742",
    "index": "A",
    "title": "Sum",
    "statement": "You are given three integers $a$, $b$, and $c$. Determine if one of them is the sum of the other two.",
    "tutorial": "You only need to write an if statement and check if any of these are true: $a+b=c$, $b+c=a$, $c+a=b$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint a, b, c;\n\tcin >> a >> b >> c;\n\tcout << ((a + b == c || c + a == b || b + c == a) ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1742",
    "index": "B",
    "title": "Increasing",
    "statement": "You are given an array $a$ of $n$ positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that $a_1 < a_2 < \\dots < a_n$ holds.",
    "tutorial": "If there are two elements with the same value, then the answer is NO, because neither of these values is less than the other. Otherwise, the answer is YES, since we can just sort the array. The time complexity is $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n)$ depending on the implementation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    int x[n];\n    set<int> a;\n    for(int i = 0; i < n; i++)\n    {\n        cin >> x[i];\n    }\n    for(int i = 0; i < n; i++)\n    {\n        if(a.find(x[i]) != a.end())\n        {\n            cout << \"NO\" << endl;\n            return;\n        }\n        a.insert(x[i]);\n    }\n    cout << \"YES\" << endl;\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1742",
    "index": "C",
    "title": "Stripes",
    "statement": "On an $8 \\times 8$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.\n\nDetermine which color was used last.\n\n\\begin{center}\n{\\small The red stripe was painted after the blue one, so the answer is R.}\n\\end{center}",
    "tutorial": "Note that if a stripe is painted last, then the entire stripe appears in the final picture (because no other stripe is covering it). Since rows are only painted red and columns are only painted blue, we can just check if any row contains 8 Rs. If there is such a row, then red was painted last; otherwise, blue was painted last. How do you write a validator for this problem? (Given a grid, check if it is a valid input.)",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tchar g[8][8];\n\tvector<int> r;\n\tfor (int i = 0; i < 8; i++) {\n\t\tfor (int j = 0; j < 8; j++) {\n\t\t\tcin >> g[i][j];\n\t\t\tif (g[i][j] == 'R') {r.push_back(i);}\n\t\t}\n\t}\n\tfor (int i : r) {\n\t    bool ok = true;\n\t    for (int j = 0; j < 8; j++) {\n\t        if (g[i][j] != 'R') {ok = false; break;}\n\t    }\n\t    if (ok) {cout << \"R\\n\"; return;}\n\t}\n\tcout << \"B\\n\";\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1742",
    "index": "D",
    "title": "Coprime",
    "statement": "Given an array of $n$ positive integers $a_1, a_2, \\dots, a_n$ ($1 \\le a_i \\le 1000$). Find the maximum value of $i + j$ such that $a_i$ and $a_j$ are coprime,$^{\\dagger}$ or $-1$ if no such $i$, $j$ exist.\n\nFor example consider the array $[1, 3, 5, 2, 4, 7, 7]$. The maximum value of $i + j$ that can be obtained is $5 + 7$, since $a_5 = 4$ and $a_7 = 7$ are coprime.\n\n$^{\\dagger}$ Two integers $p$ and $q$ are coprime if the only positive integer that is a divisor of both of them is $1$ (that is, their greatest common divisor is $1$).",
    "tutorial": "Note that the array has at most $1000$ distinct elements, since $a_i \\leq 1000$. For each value, store the largest index it is in. Then we can brute force all pairs of values, and find the coprime pair with largest sum of indices. The time complexity is $\\mathcal{O}(a_i^2 \\log a_i + n)$ per testcase.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define       forn(i,n)              for(int i=0;i<n;i++)\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nvector<int> pairs[1001];\nvoid solve() {\n    int n; cin >> n;\n    vector<int> id[1001];\n    for(int i = 1; i <= n; ++i) {\n        int x; cin >> x;\n        id[x].push_back(i);\n    }\n    int ans = -1;\n    for(int i = 1; i <= 1000; ++i) {\n        for(int j: pairs[i]) {\n            if(!id[i].empty() && !id[j].empty()) {\n                ans = max(ans, id[i].back() + id[j].back());\n            }\n        }\n    }\n    cout << ans << \"\\n\";\n}   \n \nint32_t main() {\n    for(int i = 1; i <= 1000; ++i) {\n        for(int j = 1; j <= 1000; ++j) {\n            if(__gcd(i, j) == 1) {\n                pairs[i].push_back(j);\n            }\n        }\n    }\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1742",
    "index": "E",
    "title": "Scuza",
    "statement": "Timur has a stairway with $n$ steps. The $i$-th step is $a_i$ meters higher than its predecessor. The first step is $a_1$ meters higher than the ground, and the ground starts at $0$ meters.\n\n\\begin{center}\n{\\small The stairs for the first test case.}\n\\end{center}\n\nTimur has $q$ questions, each denoted by an integer $k_1, \\dots, k_q$. For each question $k_i$, you have to print the maximum possible height Timur can achieve by climbing the steps if his legs are of length $k_i$. Timur can only climb the $j$-th step if his legs are of length at least $a_j$. In other words, $k_i \\geq a_j$ for each step $j$ climbed.\n\nNote that you should answer each question independently.",
    "tutorial": "Let's compute the prefix sums of the array $a$: let $b_i = a_1 + \\dots + a_i$. Rephrasing the problem: for each question containing an integer $k$, we need to find the largest $a_i$ such that $a_1, \\dots, a_i$ are all at most $k$, and then output $b_i$. In other words, $\\max(a_1, \\dots, a_i) \\leq k$. Let's make the prefix maximums of the array: let $m_i = \\max(a_1, \\dots, a_i)$. Then we need to find the largest $i$ such that $m_i \\leq k$, which is doable using binary search, since the array $m$ is non-decreasing. Once we find the index $i$, we simply need to output $b_i$. The time complexity is $\\mathcal{O}(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n, q;\n    cin >> n >> q;\n    vector<long long> pref;\n    pref.push_back(0);\n    vector<int> prefmax;\n    for(int i = 0; i < n; i++)\n    {\n        int x;\n        cin >> x;\n        pref.push_back(pref.back()+x);\n        if(i == 0)\n        {\n            prefmax.push_back(x);\n        }\n        else\n        {\n            prefmax.push_back(max(prefmax.back(), x));\n        }\n    }\n    for(int i = 0; i < q; i++)\n    {\n        int k;\n        cin >> k;\n        int ind = upper_bound(prefmax.begin(), prefmax.end(), k)-prefmax.begin();\n        cout << pref[ind] << \" \";\n    }\n    cout << endl;\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1742",
    "index": "F",
    "title": "Smaller",
    "statement": "Alperen has two strings, $s$ and $t$ which are both initially equal to \"a\".\n\nHe will perform $q$ operations of two types on the given strings:\n\n- $1 \\;\\; k \\;\\; x$ — Append the string $x$ exactly $k$ times at the end of string $s$. In other words, $s := s + \\underbrace{x + \\dots + x}_{k \\text{ times}}$.\n- $2 \\;\\; k \\;\\; x$ — Append the string $x$ exactly $k$ times at the end of string $t$. In other words, $t := t + \\underbrace{x + \\dots + x}_{k \\text{ times}}$.\n\nAfter each operation, determine if it is possible to \\textbf{rearrange} the characters of $s$ and $t$ such that $s$ is lexicographically smaller$^{\\dagger}$ than $t$.\n\nNote that the strings change after performing each operation and \\textbf{don't} go back to their initial states.\n\n$^{\\dagger}$ Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. A formal definition is as follows: string $p$ is lexicographically smaller than string $q$ if there exists a position $i$ such that $p_i < q_i$, and for all $j < i$, $p_j = q_j$. If no such $i$ exists, then $p$ is lexicographically smaller than $q$ if the length of $p$ is less than the length of $q$. For example, $abdc < abe$ and $abc < abcd$, where we write $p < q$ if $p$ is lexicographically smaller than $q$.",
    "tutorial": "First of all, let's think about how we should rearrange the two strings in such a way that $a < b$ (if that is ever possible). It's always optimal to arrange $a$'s characters increasingly in lexicographic order and $b$'s characters decreasingly. Since initially both $a$ and $b$ contain a character \"a\", the first time $b$ receives any other letter than \"a\" the answer will always be \"YES\", because that character will always be lexicographically larger than $a$'s first character which should be \"a\". In the other case, we know that $b$ doesn't have any other characters than \"a\", so we can compare the string $a$ with multiple \"a\" characters and we know that $a$ will be smaller if and only if it's only formed of \"a\"s and has a smaller size than $b$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define       forn(i,n)              for(int i=0;i<n;i++)\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nvoid solve() {\n    int q; cin >> q;\n    bool otherA = false, otherB = false;\n    ll cntA = 0, cntB = 0;\n    while(q--) {\n        ll d, k; string x; cin >> d >> k >> x;\n        for(auto c: x) {\n            if(d == 1) {\n                if(c != 'a') otherA = 1;\n                else cntA += k;\n            } else {\n                if(c != 'a') otherB = 1;\n                else cntB += k;\n            } \n        }\n        if(otherB) {\n            cout << \"YES\\n\";\n        } else if(!otherA && cntA < cntB) {\n            cout << \"YES\\n\";\n        } else {\n            cout << \"NO\\n\";\n        }\n    }\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1742",
    "index": "G",
    "title": "Orray",
    "statement": "You are given an array $a$ consisting of $n$ nonnegative integers.\n\nLet's define the prefix OR array $b$ as the array $b_i = a_1~\\mathsf{OR}~a_2~\\mathsf{OR}~\\dots~\\mathsf{OR}~a_i$, where $\\mathsf{OR}$ represents the bitwise OR operation. In other words, the array $b$ is formed by computing the $\\mathsf{OR}$ of every prefix of $a$.\n\nYou are asked to rearrange the elements of the array $a$ in such a way that its prefix OR array is lexicographically maximum.\n\nAn array $x$ is lexicographically greater than an array $y$ if in the first position where $x$ and $y$ differ, $x_i > y_i$.",
    "tutorial": "Note that in this context $maxval$ denotes $10^9$. We can make the observation that only the first $log_2(maxval)$ elements matter, since after placing them optimally we can be sure all bits that could be set in the prefix OR would have already been set. So, we can brute force the optimal choice $log_2(maxval)$ times (we choose to add an element if it provides the largest new prefix OR value among all unused elements) and then just add the rest of the unused elements.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define       forn(i,n)              for(int i=0;i<n;i++)\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n);\n    forn(i, n) cin >> a[i];\n    //we care at most about first log2(a) values\n    int cur_or = 0;\n    vector<bool> vis(n, false);\n    for(int i = 0; i < min(31, n); ++i) {\n        int mx = 0, idx = -1;\n        for(int j = 0; j < n; ++j) {\n            if(vis[j]) continue;\n            if((cur_or | a[j]) > mx) {\n                mx = (cur_or | a[j]);\n                idx = j;\n            }\n        }\n        vis[idx] = true;\n        cout << a[idx] << \" \";\n        cur_or |= a[idx];\n    }\n    forn(i, n) if(!vis[i]) cout << a[i] << \" \";\n    cout << '\\n';\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1743",
    "index": "A",
    "title": "Password",
    "statement": "Monocarp has forgotten the password to his mobile phone. The password consists of $4$ digits from $0$ to $9$ (note that it can start with the digit $0$).\n\nMonocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.\n\nYou have to calculate the number of different sequences of $4$ digits that could be the password for Monocarp's mobile phone (i. e. these sequences should meet all constraints on Monocarp's password).",
    "tutorial": "There are two possible solutions for the problem. The first solution is basically brute force. Each password can be obtained from an integer from $0$ to $9999$. If the number is from $1000$ to $9999$, then it's already a password of length $4$. Otherwise, you have to prepend it with enough zeros so that it becomes length $4$. Then you have to check if the password is valid. First, check if it consists of exactly two different digits: make a set of all its characters (set<char> in case of C++, for example) and check its size. Then check if the first digit of the password appears exactly twice. It would mean that the other digits appears exactly twice as well. Finally, check if neither of the found digits are forbidden. The second solution is based on combinatorics. First, choose the two digits that will appear in the password: $C(10 - n, 2)$. Since $n$ digits are prohibited, the remaining $10 - n$ are allowed. Second, choose the positions that will be taken by the first one: $C(4, 2)$. The answer is the product of these two values.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\n\ninline void read() {\t\n    cin >> n;\n    int x;\n    for (int i = 0; i < n; ++i)\n        cin >> x;\n}\n\ninline int fac(int n) {\n    int res = 1;\n    for (int i = 2; i <= n; i++) {\n        res *= i;\n    }\n    return res;\n}\n\ninline int c(int n, int k) {\n    return fac(n) / fac(k) / fac(n - k);\n}\n\ninline void solve() {\n    cout << c(10 - n, 2) * c(4, 2) << endl;\n}\n\nint main () {\n    int t;\n    cin >> t;\n    while (t--){\n        read();\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1743",
    "index": "B",
    "title": "Permutation Value",
    "statement": "You are given an integer $n$. You have to construct a permutation of size $n$.\n\nA \\textbf{permutation} is an array where each integer from $1$ to $s$ (where $s$ is the size of permutation) occurs exactly once. For example, $[2, 1, 4, 3]$ is a permutation of size $4$; $[1, 2, 4, 5, 3]$ is a permutation of size $5$; $[1, 4, 3]$ is not a permutation (the integer $2$ is absent), $[2, 1, 3, 1]$ is not a permutation (the integer $1$ appears twice).\n\nA \\textbf{subsegment} of a permutation is a contiguous subsequence of that permutation. For example, the permutation $[2, 1, 4, 3]$ has $10$ subsegments: $[2]$, $[2, 1]$, $[2, 1, 4]$, $[2, 1, 4, 3]$, $[1]$, $[1, 4]$, $[1, 4, 3]$, $[4]$, $[4, 3]$ and $[3]$.\n\nThe \\textbf{value} of the permutation is the number of its subsegments which are also permutations. For example, the value of $[2, 1, 4, 3]$ is $3$ since the subsegments $[2, 1]$, $[1]$ and $[2, 1, 4, 3]$ are permutations.\n\nYou have to construct a permutation of size $n$ with \\textbf{minimum possible value} among all permutations of size $n$.",
    "tutorial": "The subsegment $[1]$, as well as the whole permutation, will always be a permutation, so the value is at least $2$. Let's try to find a way to generate a permutation of $n$ elements with value equal to $2$. Every permutation must contain the number $1$. Let's try to construct the answer in such a way that if a subsegment contains the number $1$, then it also contains the number $n$ (if it is so, it can only be a permutation if it contains all $n$ numbers). If we begin our permutation with the numbers $1$ and $n$, we will reach our goal: the only subsegment which does not contain $n$ but contains $1$ is $[1]$, and the only subsegment which contains $n$ and also a permutation is the whole permutation itself. So, any permutation that begins with $[1, n \\dots]$ can be the answer.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nvoid solve() \n{\n    int n;\n    cin >> n;\n    cout << 1;\n    for(int i = n; i >= 2; i--)\n        cout << \" \" << i;\n    cout << endl;\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1743",
    "index": "C",
    "title": "Save the Magazines",
    "statement": "Monocarp has been collecting rare magazines for quite a while, and now he has decided to sell them. He distributed the magazines between $n$ boxes, arranged in a row. The $i$-th box contains $a_i$ magazines. Some of the boxes are covered with lids, others are not.\n\nSuddenly it started to rain, and now Monocarp has to save as many magazines from the rain as possible. To do this, he can move the lids between boxes as follows: if the $i$-th box was covered with a lid initially, he can either move the lid from the $i$-th box to the box $(i-1)$ (if it exists), or keep the lid on the $i$-th box. You may assume that Monocarp can move the lids instantly at the same moment, and no lid can be moved more than once. If a box will be covered with a lid after Monocarp moves the lids, the magazines in it will be safe from the rain; otherwise they will soak.\n\nYou have to calculate the maximum number of magazines Monocarp can save from the rain.",
    "tutorial": "Let's process the boxes from left to right. Consider the first box. If it has a lid, then you can just add the number of magazines in it to the answer and forget about this box. To be exact, proceed to solve the problem with the first box removed. If it doesn't have a lid, then look at the next box. If it doesn't have a lid too, then this box can never be covered. Remove it and proceed further. If the next box has a lid, then look at the next one. Again, if it doesn't have a lid, then these two first boxes are solved independently of everything else. You can cover exactly one of them. Choose the bigger one and remove them both. To propagate the argument, let's derive a pattern. First, there's a box without a lid. Then some number of boxes with lids in a row. Then a box without a lid again. Among the first box and the box with lids, you can choose exactly one to not be covered. However, that can be any one of them. The best box to be left uncovered is the one with the smallest number of magazines in it. Thus, the solution is the following. As long as the first box has a lid, keep removing the first box and adding it to the answer. Then, as long as there are boxes left, take the first box and the largest number of consecutive boxes with lids after it (that number might be zero). On that segment, find the minimum value and the sum. Add the sum minus the minimum to the answer, remove the entire segment. The removals can be done explicitly with a queue or just a reversed vector or implicitly with maintaining a pointer to the first non-removed box. Overall complexity: $O(n)$.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ts = '0' + input()\n\ta = [0] + list(map(int, input().split()))\n\tans = 0\n\ti = 0\n\twhile i <= n:\n\t\tmn = a[i]\n\t\tsm = a[i]\n\t\tj = i + 1\n\t\twhile j <= n and s[j] == '1':\n\t\t\tmn = min(mn, a[j])\n\t\t\tsm += a[j]\n\t\t\tj += 1\n\t\tans += sm - mn\n\t\ti = j\n\tprint(ans)",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1743",
    "index": "D",
    "title": "Problem with Random Tests",
    "statement": "You are given a string $s$ consisting of $n$ characters. Each character of $s$ is either 0 or 1.\n\nA substring of $s$ is a contiguous subsequence of its characters.\n\nYou have to choose two substrings of $s$ (possibly intersecting, possibly the same, possibly non-intersecting — just any two substrings). After choosing them, you calculate the value of the chosen pair of substrings as follows:\n\n- let $s_1$ be the first substring, $s_2$ be the second chosen substring, and $f(s_i)$ be the integer such that $s_i$ is its binary representation (for example, if $s_i$ is 11010, $f(s_i) = 26$);\n- the value is the \\textbf{bitwise OR} of $f(s_1)$ and $f(s_2)$.\n\nCalculate the maximum possible value you can get, and print it \\textbf{in binary representation without leading zeroes}.",
    "tutorial": "The first observation we need is that we can choose two prefixes of $s$ as the substrings used in forming the results. This can be proved easily: suppose we chose a substring which does not contain the leftmost character of $s$; if we expand it to the left, the answer won't become worse. So, it is optimal to choose two prefixes of $s$ as the substrings. Furthermore, one of these prefixes must be $s$ itself: if the leftmost index of 1 is $i$, the length of the answer won't exceed $n - i + 1$, but the only way to have a 1 in the $(n-i+1)$-th bit of the answer is to choose a prefix of $s$ where the $(n-i+1)$-th character (from the right) is 1; and there is only one such prefix of $s$, which is $s$ itself. So, now we can solve the problem in $O(n^2)$ - try to combine all prefixes of $s$ with $s$ itself, and choose the one that yields the best answer. To speed this up, we need to somehow cut down on the number of prefixes of $s$ we check. Let's look at the first block of 1's in $s$. The next character after this block is 0; since we take $s$ as one of the substring, in order to get 1 instead of 0 in the corresponding position of the answer, we need to choose a prefix which has 1 in that position. This 1 represents one of the 1's from the first block of 1's, since only one of them can shift to that position. So, we need to check only the prefixes such that, by using them, we shift some character 1 from the first block to the position of the first 0 after this block. Since the tests are random, the expected length of the first block of 1's is $O(1)$ (furthermore, even the probabiliy that its length is $20$ or bigger is about $10^{-6}$), so the expected number of prefixes we need to check is also $O(1)$. Thus, the expected runtime of our solution is $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nchar buf[1000043];\n\nstring normalize(const string& v)\n{\n    int cnt = 0;\n    while(cnt < v.size() && v[cnt] == '0') cnt++;\n    if(cnt == v.size()) return \"0\";\n    return v.substr(cnt, int(v.size()) - cnt);\n}\n\nstring operator |(const string& a, const string& b)\n{\n    int sz = max(a.size(), b.size());\n    string ans(sz, '0');\n    for(int i = 0; i < a.size(); i++)\n        if(a[i] == '1') ans[i + sz - int(a.size())] = '1';\n    for(int i = 0; i < b.size(); i++)\n        if(b[i] == '1') ans[i + sz - int(b.size())] = '1';    \n    return normalize(ans);\n}\n\nbool better(const string& a, const string& b)\n{\n    if(a.size() != b.size()) return a.size() > b.size();\n    return a > b;\n}\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n    string s;\n    scanf(\"%s\", buf);\n    s = buf;\n    string ans = s | s;\n    int pos1 = s.find(\"1\");\n    if(pos1 != string::npos)\n    {\n        int pos2 = s.find(\"0\", pos1);\n        if(pos2 != string::npos)\n        {\n            int cur = pos1;\n            int not_needed = 0;\n            while(true)\n            {                \n                if(cur == n || (s[cur] == '1' && cur > pos2)) break;\n                string nw = s | s.substr(pos1, n - pos1 - not_needed);\n                if(better(nw, ans)) ans = nw;\n                cur++;\n                not_needed++;\n            }\n        }\n    }\n    puts(ans.c_str());\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "probabilities"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1743",
    "index": "E",
    "title": "FTL",
    "statement": "Monocarp is playing a video game. In the game, he controls a spaceship and has to destroy an enemy spaceship.\n\nMonocarp has two lasers installed on his spaceship. Both lasers $1$ and $2$ have two values:\n\n- $p_i$ — the power of the laser;\n- $t_i$ — the reload time of the laser.\n\nWhen a laser is fully charged, Monocarp can either shoot it or wait for the other laser to charge and shoot both of them at the same time.\n\nAn enemy spaceship has $h$ durability and $s$ shield capacity. When Monocarp shoots an enemy spaceship, it receives $(P - s)$ damage (i. e. $(P - s)$ gets subtracted from its durability), where $P$ is the total power of the lasers that Monocarp shoots (i. e. $p_i$ if he only shoots laser $i$ and $p_1 + p_2$ if he shoots both lasers at the same time). An enemy spaceship is considered destroyed when its durability becomes $0$ or lower.\n\nInitially, both lasers are zero charged.\n\nWhat's the lowest amount of time it can take Monocarp to destroy an enemy spaceship?",
    "tutorial": "At any time, we have three possible choices: wait and shoot the first laser, the second laser and both lasers. Sometimes it makes sense to wait to both because you can deal $s$ more damage than you would do by shooting both lasers separately. The first claim: greedy won't work. Maybe there is a sufficiently smart greedy, we weren't able to come up with it. The second claim: bruteforce won't work. The funny thing is that it actually worked on the constraints up to $2000$, but again, we couldn't code any sufficiently fast one for $5000$. Thus, let's try some dynamic programming. Since all the times are huge, we'd want to avoid having them as the states. What is small, however, is the durability of the enemy ship and the number of shots we have to make to destroy it. Ideally, we'd like to have some $dp[i]$ - the smallest time to deal $i$ damage to the enemy ship. This way, $dp[n]$ would be the answer. Sadly, it's not immediately clear how to get rid of reload times completely. There might be states with different times until the charge with the same damage dealt, and we don't know which of those we want to keep. Thus, let's make the dp state more complicated. Let $dp[i]$ be the smallest time it takes to deal $i$ damage if the last shot was from both lasers at the same time. This way we know the reload times of both lasers - they are full $t_1$ and $t_2$. $dp[0] = 0$, as moment $0$ has both lasers zero charged as if after a shot. What are the transitions? Well, now we have to shoot each laser multiple times, then wait until both are charged and shoot both. Both lasers can now be considered independent of each other. Let the time between the previous double shot and the next one be some value $t$. During this time, it never made sense to wait until shooting each laser. So we waited $t_1$, shot the first laser, waited another $t_1$, shot again, until we couldn't shoot anymore, since the laser wouldn't recharge in time before the double shot. Same for the second laser. Notice that if both $t \\mod t_1 \\neq 0$ and $t \\mod t_2 \\neq 0$, then you could just decrease $t$ by $1$ and shoot each laser the same number of times. Thus, only $t$ that are multiples of either $t_1$ or $t_2$ are optimal. Thus, we can iterate over all possible waiting times $t$. Just iterate over $i \\cdot t_1$ and $i \\cdot t_2$ for all $i$ from $1$ to $h$. Having a fixed $t$, calculate the number of shots of each laser, calculate the damage, go into the corresponding dp state. It could also happen that the last shot before destroying the ship wasn't a double one. However, it still follows the same ideas. It means that each laser was shooting non-stop until the ship was destroyed. Thus, the destruction time is still a multiple of either of the reload times. Overall complexity: $O(h^2)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst long long INF64 = 1e18;\n\nint main() {\n\tvector<int> ps(2);\n\tvector<long long> ts(2);\n\tint h, s;\n\tforn(i, 2) scanf(\"%d%lld\", &ps[i], &ts[i]);\n\tscanf(\"%d%d\", &h, &s);\n\tlong long ans = INF64;\n\tvector<long long> dp(h + 1, INF64);\n\tdp[0] = 0;\n\tforn(i, h) for (int j = 1; j <= h - i; ++j) forn(k, 2){\n\t\tint ni = min((long long)h, i + j * (ps[k] - s) + j * ts[k] / ts[k ^ 1] * (ps[k ^ 1] - s));\n\t\tif (ni == h)\n\t\t\tans = min(ans, dp[i] + j * ts[k]);\n\t\tif (j * ts[k] >= ts[k ^ 1]){\n\t\t\tni = min((long long)h, i + (j - 1) * (ps[k] - s) + (j * ts[k] / ts[k ^ 1] - 1) * (ps[k ^ 1] - s) + (ps[0] + ps[1] - s));\n\t\t\tdp[ni] = min(dp[ni], dp[i] + j * ts[k]);\n\t\t}\n\t}\n\tans = min(ans, dp[h]);\n\tprintf(\"%lld\\n\", ans);\n}",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1743",
    "index": "F",
    "title": "Intersection and Union",
    "statement": "You are given $n$ segments on the coordinate axis. The $i$-th segment is $[l_i, r_i]$. Let's denote the set of all integer points belonging to the $i$-th segment as $S_i$.\n\nLet $A \\cup B$ be the union of two sets $A$ and $B$, $A \\cap B$ be the intersection of two sets $A$ and $B$, and $A \\oplus B$ be the symmetric difference of $A$ and $B$ (a set which contains all elements of $A$ and all elements of $B$, except for the ones that belong to both sets).\n\nLet $[\\mathbin{op}_1, \\mathbin{op}_2, \\dots, \\mathbin{op}_{n-1}]$ be an array where each element is either $\\cup$, $\\oplus$, or $\\cap$. Over all $3^{n-1}$ ways to choose this array, calculate the sum of the following values:\n\n$$|(((S_1\\ \\mathbin{op}_1\\ S_2)\\ \\mathbin{op}_2\\ S_3)\\ \\mathbin{op}_3\\ S_4)\\ \\dots\\ \\mathbin{op}_{n-1}\\ S_n|$$\n\nIn this expression, $|S|$ denotes the size of the set $S$.",
    "tutorial": "We will use the Contribution to the Sum technique to solve this problem: for every integer from $0$ to $300000$, let's calculate the number of ways to choose the operators so it belongs to the result, and add all of the results. For a fixed integer $x$, the number of ways to choose the operators so that $x$ belongs to the result can be done as follows: let $dp_{i,f}$ be the number of ways to choose the first $i$ operators so that, after applying them, the resulting set contains $x$ if $f = 1$, and does not contain $x$ if $f = 0$. The transitions from $dp_i$ to $dp_{i+1}$ depend on whether the number $x$ belongs to the segment $i+1$. Obviously, this is too slow if we compute the dynamic programming from scratch for every integer $x$. Instead, we can notice that the transitions from $dp_i$ to $dp_{i+1}$ are linear combinations: both $dp_{i+1,0}$ and $dp_{i+1,1}$ are linear combinations of $dp_{i,0}$ and $dp_{i,1}$ with coefficients depending on whether the element $x$ belongs to the set or not. So, transitioning from $dp_i$ to $dp_{i+1}$ can be written in terms of multiplying by a $2 \\times 2$ matrix. Let's build a segment tree where each vertex stores a transition matrix, and operations are \"calculate the product of matrices on a segment\" and \"replace a matrix at some index\". We can build a sequence of these transition matrices for $x=0$ and store them in the segment tree; for $x=1$, this sequence of transition matrices will change only in positions $j$ such that either $0$ belongs to $[l_j, r_j]$ and $1$ does not belong to it, or vice versa. So, we can go from $x=0$ to $x=1$ by replacing these transition matrices in the segment tree. For $x=2$, the only changes from $x=0$ are in positions $j$ such that either $1$ belongs to $[l_j, r_j]$ and $2$ does not belong to it, or vice versa - and we can replace the matrices in these positions as well. In total, there will be only $O(n)$ such replacements; so, we solve the problem in $O(M + n \\log M)$, where $M$ is the constraint on the numbers belonging to the sets.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300043;\n\ntypedef array<int, 2> vec;\ntypedef array<vec, 2> mat;\n\nconst int MOD = 998244353;\n\nmat operator*(const mat& a, const mat& b)\n{\n    mat c;\n    for(int i = 0; i < 2; i++)\n        for(int j = 0; j < 2; j++)\n            c[i][j] = 0;\n    for(int i = 0; i < 2; i++)\n        for(int j = 0; j < 2; j++)\n            for(int k = 0; k < 2; k++)\n                c[i][k] = (a[i][j] * 1ll * b[j][k] + c[i][k]) % MOD;\n    return c;\n}\n\nmat ZERO = {vec({3, 0}), vec({1, 2})};\nmat ONE = {vec({1, 2}), vec({1, 2})};\n\nmat t[4 * N];\n\nvoid recalc(int v)\n{\n    t[v] = t[v * 2 + 1] * t[v * 2 + 2];    \n}\n\nvoid build(int v, int l, int r)\n{\n    if(l == r - 1)\n    {            \n        t[v] = ZERO;                       \n    }\n    else\n    {\n        int m = (l + r) / 2;\n        build(v * 2 + 1, l, m);\n        build(v * 2 + 2, m, r);\n        recalc(v);               \n    }\n}\n\nvoid upd(int v, int l, int r, int pos, int val)\n{\n    if(l == r - 1)\n    {\n        if(val == 0) t[v] = ZERO;\n        else t[v] = ONE;\n    }\n    else\n    {\n        int m = (l + r) / 2;\n        if(pos < m) upd(v * 2 + 1, l, m, pos, val);\n        else upd(v * 2 + 2, m, r, pos, val);\n        recalc(v);\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int n;\n    cin >> n;\n    vector<vector<pair<int, int>>> v(N);\n    for(int i = 0; i < n; i++)\n    {\n        int l, r;\n        cin >> l >> r;\n        v[l].push_back(make_pair(1, i));\n        v[r + 1].push_back(make_pair(0, i));\n    }    \n    build(0, 0, n - 1);\n    int cur = 0;\n    int ans = 0;\n    for(int i = 0; i <= 300000; i++)\n    {\n        for(auto x : v[i])\n        {\n            if(x.second == 0) cur = x.first;\n            else upd(0, 0, n - 1, x.second - 1, x.first);\n        }\n        ans = (ans + t[0][cur][1]) % MOD;\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "data structures",
      "dp",
      "matrices",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1743",
    "index": "G",
    "title": "Antifibonacci Cut",
    "statement": "\\textbf{Note that the memory limit is unusual.}\n\nLet's define the sequence of Fibonacci strings as follows: $f_0$ is 0, $f_1$ is 1, $f_i$ is $f_{i-1} + f_{i-2}$ for $i>1$ ($+$ denotes the concatenation of two strings). So, for example, $f_2$ is 10, $f_3$ is 101, $f_4$ is 10110.\n\nFor a given string $s$, let's define $g(s)$ as the number of ways to cut it into several (any number, possibly even just one) strings such that none of these strings are Fibonacci strings. For example, if $s$ is 10110101, $g(s) = 3$ since there are three ways to cut it:\n\n- 101101 $+$ 01;\n- 1011 $+$ 0101;\n- 1011 $+$ 01 $+$ 01.\n\nYou are given a sequence of strings $s_1, s_2, \\dots, s_n$. Calculate $g(s_1), g(s_1 + s_2), \\dots, g(s_1 + s_2 + \\ldots + s_n)$. Since these values can be huge, print them modulo $998244353$.",
    "tutorial": "The first idea that comes to mind is running some sort of dynamic programming: $dp_i$ - the number of ways to cut the string consisting of the first $i$ characters. When we calculate $dp_i$, we need to take the sum of the previous values of $dp$, and then subtract $dp_j$ for every $j$ such that the string from the $j$-th character (inclusive) to the $i$-th character (non-inclusive) is a Fibonacci string. Unfortunately, there are two main issues with this solution: firstly, we cannot store the array $dp$ in memory; and secondly, we have to search for the Fibonacci strings ending in a certain index quickly (something like Aho-Corasick could work with a less strict memory limit, but right now we cannot use it). We will try to resolve both of these issues with the following approach: while we process the characters, we will maintain the list of tuples $(j, dp_j)$ such that the string from the $j$-th character to the current one is a prefix of some Fibonacci string. How do we maintain them? Every Fibonacci string $f_i$ (except for $f_0$) is a prefix of $f_{i+1}$. So, all Fibonacci strings we are interested in (except for $f_0$ again) are prefixes of the same long Fibonacci string. Suppose a tuple $(j, dp_j)$ represents some index $j$ such that the string from the $j$-th character to the current one is a prefix of that long Fibonacci string. Each time we append a character, we filter this list of tuples by trying to check if this new character matches the next character in the prefix (if it does not, the tuple is discarded). For the tuples that represent the prefixes equal to Fibonacci strings, we need to subtract the value of $dp_j$ from the new $dp$ value we are trying to calculate (checking if a prefix is a Fibonacci string is easy, we just need to check its length). How do we check that if we add a character 1 or 0, it is still a prefix? There are two ways to do this: either generate the first $3 \\cdot 10^6$ characters of the long Fibonacci string; or represent the current prefix as the sum of Fibonacci strings $f_{i_1} + f_{i_2} + \\dots + f_{i_k}$ such that for every $j \\in [1, k - 1]$, the condition $f_{i_j} > f_{i_{j+1}} + 1$ holds (i. e. the Fibonacci strings we split the current prefix into are arranged in descending order, and there is no pair of equal or adjacent (by index) Fibonacci strings in the split). This representation is very similar to writing an integer in Zeckendorf system. The next character in the prefix depends on whether $f_1$ belongs to this split: if it belongs, it is the last string in the split, so we need to append 0 to transform $f_1$ into $f_2$; otherwise, we need to append 1. Okay, so now we can solve the problem in $O(NM)$ time (where $N$ is the total length of the strings in the input, and $M$ is the size of the list of tuples $(j, dp_j)$ we discussed earlier). This actually works since it looks like the size of the list of tuples is bounded as $O(\\log N)$. Unfortunately, we don't have a strict mathematical proof of this; we checked this by brute force with $N$ up to $3 \\cdot 10^6$, so it definitely works under the constraints of the problem.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint sub(int x, int y)\n{\n    return add(x, MOD - y);\n}\n\nint expected(int mask)\n{\n    if(mask & 2) return 0;\n    return 1;\n}\n\nint last_bit(int x)\n{\n    if(x == 0) return -1;\n    return x - (x & (x - 1));\n}\n\nbool go(int& a, int x)\n{\n    if(expected(a) != x)\n    {\n        a = 1 << x;\n        return false;    \n    }\n    a ^= (1 << x);\n    while(true)\n    {\n        int b = last_bit(a);\n        int c = last_bit(a - b);\n        if(c == 2 * b) a += b;\n        else break;\n    }\n    return true;\n}\n\nbool is_fib(int a)\n{\n    return a == last_bit(a);\n}\n\nvector<pair<int, int>> go(const vector<pair<int, int>>& a, int x)\n{\n    vector<pair<int, int>> nw;\n    for(auto b : a)\n    {\n        int cost = b.first;\n        int seqn = b.second;\n        if(go(seqn, x)) nw.push_back(make_pair(cost, seqn));\n    }\n    return nw;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int last = 1, sum = 1;\n    vector<pair<int, int>> w;\n    int n;\n    cin >> n;\n    for(int i = 0; i < n; i++)\n    {\n        string s;\n        cin >> s;\n        for(auto x : s)\n        {\n            int c = x - '0';\n            int ndp = sub(sum, last);\n            w = go(w, c);\n            for(int j = 0; j < w.size(); j++)\n            {\n                if(is_fib(w[j].second))\n                    ndp = sub(ndp, w[j].first);\n            }\n            if(c == 1) w.push_back(make_pair(last, 2));\n            sum = add(sum, ndp);\n            last = ndp;\n            assert(w.size() <= 60);\n        }\n        cout << last << endl;\n    }\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "constructive algorithms",
      "data structures",
      "dp",
      "hashing",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1744",
    "index": "A",
    "title": "Number Replacement",
    "statement": "An integer array $a_1, a_2, \\ldots, a_n$ is being transformed into an array of lowercase English letters using the following prodecure:\n\nWhile there is at least one number in the array:\n\n- Choose any number $x$ from the array $a$, and any letter of the English alphabet $y$.\n- Replace all occurrences of number $x$ with the letter $y$.\n\nFor example, if we initially had an array $a = [2, 3, 2, 4, 1]$, then we could transform it the following way:\n\n- Choose the number $2$ and the letter c. After that $a = [c, 3, c, 4, 1]$.\n- Choose the number $3$ and the letter a. After that $a = [c, a, c, 4, 1]$.\n- Choose the number $4$ and the letter t. After that $a = [c, a, c, t, 1]$.\n- Choose the number $1$ and the letter a. After that $a = [c, a, c, t, a]$.\n\nAfter the transformation all letters are united into a string, in our example we get the string \"cacta\".\n\nHaving the array $a$ and the string $s$ determine if the string $s$ could be got from the array $a$ after the described transformation?",
    "tutorial": "Let's note that if $a_i = a_j$, then $s_i$ must be equal to $s_j$, since we must change the same value to the same letter. If we check this for all pairs of $i$ and $j$ and find no such contradictions, then the answer is \"YES\", otherwise \"NO\". We got the solution for $O(n^2)$ for one test case.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1744",
    "index": "B",
    "title": "Even-Odd Increments ",
    "statement": "You are given $n$ of integers $a_1, a_2, \\ldots, a_n$. Process $q$ queries of two types:\n\n- query of the form \"0 $x_j$\": add the value $x_j$ to all even elements of the array $a$,\n- query of the form \"1 $x_j$\": add the value $x_j$ to all odd elements of the array $a$.\n\nNote that when processing the query, we look specifically at the odd/even value of $a_i$, not its index.\n\nAfter processing each query, print the sum of the elements of the array $a$.\n\nPlease note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).",
    "tutorial": "Let $\\mathit{sum}$ - the initial sum in the array, $\\mathit{cnt}_0$ - the number of even numbers, $\\mathit{cnt}_1$ - the number of odd numbers. Let's see how these values change with each action. In fact, we can consider four main options: Add an even number $x$ to all even numbers. Then $\\mathit{sum}$ will increase by $x \\cdot \\mathit{cnt}_0$, and the number of even and odd numbers will remain the same. Add an odd number $x$ to all even numbers. Then $\\mathit{sum}$ will increase by $x \\cdot \\mathit{cnt}_0$, the number of even numbers will become $0$, all numbers will become odd, so $\\mathit{cnt}_1 = n$. Add an even number $x$ to all odd numbers. Then $\\mathit{sum}$ will increase by $x \\cdot \\mathit{cnt}_1$, and the number of even and odd numbers will remain the same. Add an odd number $x$ to all odd numbers. Then $\\mathit{sum}$ will increase by $x \\cdot \\mathit{cnt}_1$, the number of odd numbers will become $0$, all numbers will become even, so $\\mathit{cnt}_0 = n$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1744",
    "index": "C",
    "title": "Traffic Light",
    "statement": "You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $n$ seconds and at the $i$-th second the color $s_i$ is on.\n\nThat way, the order of the colors is described by a string. For example, if $s=$\"rggry\", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.\n\nMore formally, you are given a string $s_1, s_2, \\ldots, s_n$ of length $n$. At the first second the color $s_1$ is on, at the second — $s_2$, ..., at the $n$-th second the color $s_n$ is on, at the $n + 1$-st second the color $s_1$ is on and so on.\n\nYou need to cross the road and that can only be done when the green color is on.\n\nYou know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.\n\nYou can assume that you cross the road immediately.\n\nFor example, with $s=$\"rggry\" and the current color r there are two options: either the green color will be on after $1$ second, or after $3$. That way, the answer is equal to $3$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.",
    "tutorial": "Let's note that for each second of color $c$ in the traffic light, we need to find the rightmost green time, and then find the largest distance between color $c$ and the nearest green. Also, let's not forget that traffic light states are cyclical. To get rid of cyclicity, you can write the string $s$ twice and for each cell of color $c$ from the first half, find the nearest green color (thus we solved the problem with cyclicity). And now we can just follow this line from right to left and maintain the index of the last occurrence of green. If we encounter color $c$, then we try to update our answer $ans = \\max(ans, last - i)$, where $ans$ is our answer, $last$ is the nearest time that green was on color, $i$ - current time.",
    "tags": [
      "binary search",
      "implementation",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1744",
    "index": "D",
    "title": "Divisibility by 2^n",
    "statement": "You are given an array of positive integers $a_1, a_2, \\ldots, a_n$.\n\nMake the product of all the numbers in the array (that is, $a_1 \\cdot a_2 \\cdot \\ldots \\cdot a_n$) divisible by $2^n$.\n\nYou can perform the following operation as many times as you like:\n\n- select an arbitrary index $i$ ($1 \\leq i \\leq n$) and replace the value $a_i$ with $a_i=a_i \\cdot i$.\n\nYou cannot apply the operation repeatedly to a single index. In other words, all selected values of $i$ must be different.\n\nFind the smallest number of operations you need to perform to make the product of all the elements in the array divisible by $2^n$. Note that such a set of operations does not always exist.",
    "tutorial": "Let's notice that if we multiply the numbers $a_1 \\cdot a_2 \\cdot \\ldots \\cdot a_n$, then the power of two of the product is equal to the sum of the powers of two in each of the numbers. Let's calculate the initial sum of the powers of twos in the product. This can be done as follows: let's take the element $a_i$ and divide it by $2$ as long as we can, while remembering to increase our counter by the number of occurrences of a power of two. Now let's move on to operations and note that choosing the index $i$ will increase the degree of occurrence of two by a fixed number (that is, it does not matter when to apply this operation). Choosing an index $i$ will increment the counter by a number $x$ such that $i$ is divisible by $2^x$ but not by $2^{x + 1}$ - you can find this $x$, again , by dividing by $2$ while we can. Since we want to minimize the number of operations used, at each moment of time we will try to use an index that increases the counter by the largest number. To do this, it is enough to sort the indices by this index of increase and take them greedily from the largest increase to the smallest. We get the solution in $O(n \\log n + n \\log A)$.",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1744",
    "index": "E2",
    "title": "Divisible Numbers (hard version)",
    "statement": "\\textbf{This is an hard version of the problem. The only difference between an easy and a hard version is the constraints on $a$, $b$, $c$ and $d$.}\n\nYou are given $4$ positive integers $a$, $b$, $c$, $d$ with $a < c$ and $b < d$. Find any pair of numbers $x$ and $y$ that satisfies the following conditions:\n\n- $a < x \\leq c$, $b < y \\leq d$,\n- $x \\cdot y$ is divisible by $a \\cdot b$.\n\nNote that required $x$ and $y$ may not exist.",
    "tutorial": "Let's look at the slow solution first, which will lead us to the full one. Let's iterate over the number $x$ from $a + 1$ to $c$. Given a number $x$, we want to find a $y$ from $b + 1$ to $d$ such that $x \\cdot y$ is divisible by $a \\cdot b$. Since $x \\cdot y$ must be divisible by $a \\cdot b$, the following conclusion can be drawn: $y$ must be divisible by $\\frac{a \\cdot b}{\\gcd(a \\cdot b, x) }$. Let's denote this number as $s$. Now our task is to check if there is a multiple of $s$ between $b + 1$ and $d$. The problem can be solved in many ways, you can simply consider the largest multiple of $s$ that does not exceed $d$ - it is equal to $\\left \\lfloor{\\frac{d}{s}} \\right \\rfloor \\cdot s$ We compare this number with $b + 1$, and if it matches, then we have found a suitable pair. Now let's note that we do not need to iterate over all the values of $x$, because from the number $x$ we are only interested in $\\gcd(x, a \\cdot b)$ - and this is one of the divisors of $a \\cdot b$! Even though the product $a \\cdot b$ can be large, we can still consider all divisors of this number, since $a$ and $b$ themselves are up to $10^9$. Let's find the divisors of $a$ and $b$ separately, then notice that any divisor of $a \\cdot b$ - is $a' \\cdot b'$, where $a'$ - is some divisor $a$, and $b'$ - is some divisor $b$. Let's calculate the running time. We need to factorize the numbers $a$ and $b$ into prime factors, this can be done in $O(\\sqrt a)$. Next, you need to iterate over pairs of divisors $a$ and $b$. Recall the estimate for the number of divisors of a number (https://oeis.org/A066150): the number $x$ up to $10^9$ has no more than $1344$ divisors. Therefore, we can sort through the pairs for $1344^2$. We learned how to find the optimal $y$ for $O(1)$. We get that for each test case we have learned to solve the problem in $O(\\sqrt a + (1344^2))$.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1744",
    "index": "F",
    "title": "MEX vs MED",
    "statement": "You are given a permutation $p_1, p_2, \\ldots, p_n$ of length $n$ of numbers $0, \\ldots, n - 1$. Count the number of subsegments $1 \\leq l \\leq r \\leq n$ of this permutation such that $mex(p_l, p_{l+1}, \\ldots, p_r) > med(p_l, p_{l+1}, \\ldots, p_r)$.\n\n$mex$ of $S$ is the smallest non-negative integer that does not occur in $S$. For example:\n\n- $mex({0, 1, 2, 3}) = 4$\n- $mex({0, 4, 1, 3}) = 2$\n- $mex({5, 4, 0, 1, 2}) = 3$\n\n$med$ of the set $S$ is the median of the set, i.e. the element that, after sorting the elements in non-decreasing order, will be at position number $\\left \\lfloor{ \\frac{|S| + 1}{2} } \\right \\rfloor$ (array elements are numbered starting from $1$ and here $\\left \\lfloor{v} \\right \\rfloor$ denotes rounding $v$ down.). For example:\n\n- $med({0, 1, 2, 3}) = 1$\n- $med({0, 4, 1, 3}) = 1$\n- $med({5, 4, 0, 1, 2}) = 2$\n\nA sequence of $n$ numbers is called a permutation if it contains all the numbers from $0$ to $n - 1$ exactly once.",
    "tutorial": "Let's learn how to count the number of subsegments where $\\mathit{mex} > \\mathit{mid}$ for a fixed value of $\\mathit{mex}$. Let's understand on which subsegments $\\mathit{mex}$ has such a value. We understand that the numbers $0, 1, \\ldots, \\mathit{mex} - 1$ should be in this subsegment, the number $\\mathit{mex}$ - should not, and then - does not matter . Let $\\ell$ - be the index of the left-most occurrence of the numbers $0, 1, \\ldots, \\mathit{mex} - 1$, and $r$ - the right-most occurrence. Also, let $\\mathit{pos}$ \"be the index of the number $\\mathit{mex}$. If $\\ell < \\mathit{pos} < r$, then there is no subsegment with the given $\\mathit{ mex}$, otherwise let's think about how many numbers can be in a subsegment. It is stated that if the length of a segment is $\\leq 2 \\cdot \\mathit{mex}$, then $\\mathit{mex} > \\mathit{mid}$ on it, otherwise it is not true. Indeed, if the length of a segment is $\\leq 2 \\cdot \\mathit{mex}$, then simply by the definition of the median, it will be among the first $\\mathit{mex}$ numbers. On the other hand, if the length of the segment becomes longer, then according to the same definition of the median, it will no longer be among the first $\\mathit{mex}$ numbers, which are equal to $0, 1, \\ldots, \\mathit{mex} - 1$. It turns out that we need to count the number of subsegments of length $\\leq 2 \\cdot \\mathit{mex}$ that contain the subsegment $\\ell \\ldots r$ inside themselves, but not $\\mathit{pos}$. This, of course, can be done with large formulas and the like, but one more useful fact can be noticed! If we iterate over $\\mathit{mex}$ in ascending order, and at the same time maintain $\\ell$ and $r$, then let's see what happens with a fixed $\\mathit{mex}$ and a position of $\\mathit{pos}$ (for convenience, let's assume that $\\mathit{pos} < \\ell$, since the second case is similar). In fact, you can simply iterate over the left border of our segment from $\\mathit{pos} + 1$ to $\\ell$, and then use a simpler formula to calculate the number of good subsegments with such fixed values. Why can this left boundary be iterated for each $\\mathit{mex}$ if $\\mathit{pos} < \\ell$ (correspondingly, if it were $\\mathit{pos} > r$, then we would iterate over the right boundary) ? Let's remember that after this step, $\\ell$ becomes equal to $\\mathit{pos}$. That is, if we iterate over an element, then we move the corresponding border. And we can only move it $O(n)$ times.",
    "tags": [
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1746",
    "index": "A",
    "title": "Maxmina",
    "statement": "You have an array $a$ of size $n$ consisting only of zeroes and ones and an integer $k$. In one operation you can do one of the following:\n\n- Select $2$ consecutive elements of $a$ and replace them with their minimum (that is, let $a := [a_{1}, a_{2}, \\ldots, a_{i-1}, \\min(a_{i}, a_{i+1}), a_{i+2}, \\ldots, a_{n}]$ for some $1 \\le i \\le n-1$). This operation decreases the size of $a$ by $1$.\n- Select $k$ consecutive elements of $a$ and replace them with their maximum (that is, let $a := [a_{1}, a_{2}, \\ldots, a_{i-1}, \\max(a_{i}, a_{i+1}, \\ldots, a_{i+k-1}), a_{i+k}, \\ldots, a_{n}]$ for some $1 \\le i \\le n-k+1$). This operation decreases the size of $a$ by $k-1$.\n\nDetermine if it's possible to turn $a$ into $[1]$ after several (possibly zero) operations.",
    "tutorial": "step 1: It's obvious that the answer is \"NO\" if $a_{i} = 0$ for all $1 \\le i \\le n$. step 2: Lets prove that the answer is \"YES\" if $a_{i} = 1$ for at least one $1 \\le i \\le n$. step 3: If size of $a$ is equal to $k$, just use second type operation once and we are done. step 4: Otherwise (if $|a| > k$), there will be three cases: (assume that $a_{j} = 1$) if $j > 2$, you can use first type operation on first and second element and decrease size of $a$ by 1. else if $j < |a|-1$, you can use first type operation on last and second to last element and decrease size of $a$ by 1. else, it can be shown easily that $|a| = 3$ and $k = 2$ so you can use second type operation twice and turn $a$ into a single $1$. In first and second case, you can continue decreasing size of $a$ until $|a| = k$ (or you reach $3$-rd case) and you can use second type operation to reach your aim. step 5: So we proved that the answer is \"YES\" iff $a_{i} = 1$ for at least one $1 \\le i \\le n$ or in other words, iff $\\sum_{i = 1}^n a_{i} > 0$.",
    "code": "// In the name of God\n#include <iostream>\n \nusing namespace std;\n \nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int n, k;\n        cin >> n >> k;\n        int sum = 0;\n        for(int i = 0 ; i < n ; i++){\n            int a;\n            cin >> a;\n            sum += a;\n        }\n        if(sum > 0) cout << \"YES\" << endl;\n        else cout << \"NO\" << endl;\n    }\n    return 0;\n}\n// Thank God",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1746",
    "index": "B",
    "title": "Rebellion",
    "statement": "You have an array $a$ of size $n$ consisting only of zeroes and ones. You can do the following operation:\n\n- choose two indices $1 \\le i , j \\le n$, $i \\ne j$,\n- add $a_{i}$ to $a_{j}$,\n- remove $a_{i}$ from $a$.\n\nNote that elements of $a$ can become bigger than $1$ after performing some operations. Also note that $n$ becomes $1$ less after the operation.\n\nWhat is the minimum number of operations needed to make $a$ non-decreasing, i. e. that each element is not less than the previous element?",
    "tutorial": "step 1: Assume that $a_{i} = 0$ for each $1 \\le i \\le n$, what should we do? Nothing! The array is already sorted and the answer is $0$. step 2: After sorting the array, consider the first non-zero element of $a$, how many elements after that are equal to zero? In other words, consider smallest $i$ such that $a_{i} > 0$, how many indices $k$ exist such that $i < k$ and $a_{k} = 0$? 0, because we call an array $a$ sorted (in non-decreasing order), if for all $1 \\le i < j \\le n$, $a_{i} \\le a_{j}$ holds. So all numbers after leftmost non-zero element must be non-zero too. step 3: assume that after sorting $a$, $a_{i}$ ($1 \\le i \\le n$) is the leftmost non-zero element. Define $G_{1}$ as the set of indices $j$ such that $1 \\le j < i$ and $a_{j} > 0$ at the beginning, also define $G_{2}$ as the set of indices $j$ such that $i \\le j \\le n$ and $a_{j} = 0$ at the beginning. What is the answer? $max(|G_{1}|, |G_{2}|)$. It's obvious that in one operation at most one element will be deleted from each group. So we must perform at least $max(|G_{1}|, |G_{2}|)$ operations. Now we want to show that it's sufficient too. There are three cases: $min(|G_{1}|, |G_{2}|) > 1$, at this point, we know that all elements of $a$ are $0$ or $1$. So we can pick one element from $G_{1}$ and add it to an element from $G_{2}$, so the size of both groups will decrease by $1$. It's obvious that all elements of $a$ will remain less than or equal to $1$ after this operation. $|G_{1}| = 0$, it's easy to see that we can add $a[k]$ ($k \\in G_{2}$) to a random element. So $|G_{2}|$ will decrease by $1$. $|G_{2}| = 0$, it's easy to see that we can add $a[k]$ ($k \\in G_{1}$) to the last element of $a$. So $|G_{1}|$ will decrease by $1$. step 4: Now how can we solve the problem using previous steps? If all elements are equal to $0$, the answer is obviously zero. Otherwise we will calculate two arrays, number of ones in each prefix and number of zeros in each suffix. We will also fix the leftmost non-zero element and calculate the answer for it easily by using Step 3 algorithm in O(n).",
    "code": "/// In the name of God\n#include <iostream>\n \nusing namespace std;\n \nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin >> n;\n\t\tint A[n], cnt[2][n+1];\n\t\tcnt[0][0] = cnt[1][0] = 0;\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tcin >> A[i];\n\t\t\tcnt[0][i+1] = cnt[0][i]+(A[i]==0?1:0);\n\t\t\tcnt[1][i+1] = cnt[1][i]+(A[i]==1?1:0);\n\t\t}\n\t\tint ans = n-1;\n\t\tfor(int last_zero = 0; last_zero <= n; last_zero++)\n\t\t\tans= min(ans, max(cnt[1][last_zero], cnt[0][n]-cnt[0][last_zero]));\n\t\tcout << ans << endl;\n\t}\n}\n \n/// Thank God . . .",
    "tags": [
      "constructive algorithms",
      "greedy",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1746",
    "index": "C",
    "title": "Permutation Operations",
    "statement": "You are given a permutation $a$ of size $n$ and you should perform $n$ operations on it. In the $i$-th operation, you can choose a non-empty suffix of $a$ and increase all of its elements by $i$. How can we perform the operations to minimize the number of inversions in the final array?\n\nNote that you can perform operations on the same suffix any number of times you want.\n\nA permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. A suffix is several consecutive elements of an array that include the last element of the array. An inversion in an array $a$ is a pair of indices $(i, j)$ such that $i > j$ and $a_{i} < a_{j}$.",
    "tutorial": "step 1: Try to prove that the answer is always zero. Or in other words, we can always make the array $a$ non-decreasing. We will prove this fact in next steps. step 2: If some array $a$ is non-decreasing, what can we say about array $d=[a_{2}-a_{1}, a_{3}-a_{2}, ... a_{n}-a_{n-1}]$? It's obvious that all elements of array $d$ should be non-negative. step 3: If we perform the $i$-th operation on the suffix starting at index $j$, what happens to array $d$? All elements of it will remain the same except $d_{j-1}=a_{j}-a_{j-1}$ which will increase by $i$. step 4: Considering the fact that array $a$ consists only of positive integers, what can we say about $d_{i}=a_{i+1}-a_{i}$? Since $a_{i+1} \\ge 0$, we can say that $d_{i} \\ge -a_{i}$. step 5: Using step 3 and 4 and knowing that $a$ is a permutation of numbers $1$ to $n$, what can we do to make all elements of $d$ non-negative? for $i \\le n-1$, we can perform $a_{i}$-th operation on the suffix starting from index $i+1$. So $d_{i}$ will increase by $a_{i}$ and since we knew that $d_{i} \\ge -a_{i}$, after performing this operation $d_{i} \\ge 0$ will hold. So after this steps, elements of $d$ will be non-negative and according to Step 2, that's exactly what we want. It's also easy to see that it doesn't matter how we perform $a_{n}$-th operation, so we can do anything we want.",
    "code": "/// In the name of God\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline void solve()\n{\n\tint n;\n\tcin >> n;\n\tint permutation[n], location[n];\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tcin >> permutation[i];\n\t\tpermutation[i]--;\n\t\tlocation[permutation[i]] = i;\n\t}\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(location[i] == n-1)\n\t\t\tcout << rand()%n+1 << (i == n-1?'\\n':' ');\n\t\telse\n\t\t\tcout << location[i]+2 << (i == n-1?'\\n':' ');\n\t}\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t\tsolve();\n\treturn 0;\n}\n/// Thank God . . .",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1746",
    "index": "D",
    "title": "Paths on the Tree",
    "statement": "You are given a rooted tree consisting of $n$ vertices. The vertices are numbered from $1$ to $n$, and the root is the vertex $1$. You are also given a score array $s_1, s_2, \\ldots, s_n$.\n\nA multiset of $k$ simple paths is called valid if the following two conditions are both true.\n\n- Each path starts from $1$.\n- Let $c_i$ be the number of paths covering vertex $i$. For each pair of vertices $(u,v)$ ($2\\le u,v\\le n$) that have the same parent, $|c_u-c_v|\\le 1$ holds.\n\nThe value of the path multiset is defined as $\\sum\\limits_{i=1}^n c_i s_i$.It can be shown that it is always possible to find at least one valid multiset. Find the maximum value among all valid multisets.",
    "tutorial": "Define $f(u, cnt)$ represents the maximum score of $cnt$ balls passing through the subtree of node $u$. Define $num$ as the number of the sons of node $u$. The transition is only related to $\\lceil cnt / num \\rceil$ and $\\lfloor cnt / num \\rfloor$ two states of the subtree. For each node $u$, $cnt$ can only be two adjacent integer $(x, x + 1)$. It can be proved that the four numbers $\\lfloor x/num \\rfloor$, $\\lceil x/num \\rceil$, $\\lceil (x + 1)/num \\rceil$ and $\\lfloor (x + 1)/num \\rfloor$ can only have two kinds of numbers at most, and they are adjacent natural numbers. So the number of states can be proved to be $\\mathcal{O}(n)$.",
    "code": "/// In the name of God\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst int N = 200000;\nll V[N], dp[N];\nint dad[N];\nvector<int> child[N];\nvector<pair<int, ll>> answers[N];\n\ninline ll DP(int v, ll k)\n{\n\tfor(auto [kp, ans]: answers[v])\n\t\tif(k == kp)\n\t\t\treturn ans;\n\tll cnt_child = (ll)child[v].size();\n\tll ans = k*V[v];\n\tif(cnt_child == 0)\n\t\treturn ans;\n\tif(k%cnt_child == 0)\n\t\tfor(auto u: child[v])\n\t\t\tans += DP(u, k/cnt_child);\n\telse\n\t{\n\t\tll dp1[cnt_child], dp2[cnt_child], diff[cnt_child];\n\t\tfor(int i = 0; i < cnt_child; i++)\n\t\t\tdp1[i] = DP(child[v][i], k/cnt_child), dp2[i] = DP(child[v][i], k/cnt_child+1);\n\t\tfor(int i = 0; i < cnt_child; i++)\n\t\t\tdiff[i] = dp2[i] - dp1[i];\n\t\tsort(diff, diff+cnt_child, greater<int>());\n\t\tfor(int i = 0; i < cnt_child; i++)\n\t\t\tans += dp1[i];\n\t\tfor(int i = 0; i < k%cnt_child; i++)\n\t\t\tans += diff[i];\n\t}\n\tanswers[v].push_back({k, ans});\n\treturn ans;\n}\n\ninline ll solve()\n{\n\tll n, k;\n\tcin >> n >> k;\n\tfor(int i = 0; i < n; i++)\n\t\tchild[i].clear(), answers[i].clear();\n\tdad[0] = 0;\n\tfor(int i = 0; i < n-1; i++)\n\t{\n\t\tcin >> dad[i+1];\n\t\tdad[i+1]--;\n\t\tchild[dad[i+1]].push_back(i+1);\n\t}\n\tfor(int i = 0; i < n; i++)\n\t\tcin >> V[i];\n\treturn DP(0, k);\n}\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile(t--)\n\t\tcout << solve() << '\\n';\n\treturn 0;\n}\n/// Thank God . . .",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1746",
    "index": "E1",
    "title": "Joking (Easy Version)",
    "statement": "The only difference between this problem and the hard version is the maximum number of questions.\n\nThis is an interactive problem.\n\nThere is a hidden integer $1 \\le x \\le n$ which you have to find. In order to find it you can ask at most $\\mathbf{82}$ questions.\n\nIn each question you can choose a non-empty integer set $S$ and ask if $x$ belongs to $S$ or not, after each question, if $x$ belongs to $S$, you'll receive \"YES\", otherwise \"NO\".\n\nBut the problem is that not all answers are necessarily true (some of them are joking), it's just guaranteed that for each two consecutive questions, at least one of them is answered correctly.\n\nAdditionally to the questions, you can make at most $2$ guesses for the answer $x$. Each time you make a guess, if you guess $x$ correctly, you receive \":)\" and your program should terminate, otherwise you'll receive \":(\".\n\nAs a part of the joking, we will \\textbf{not} fix the value of $x$ in the beginning. Instead, it can change throughout the interaction as long as all the previous responses are valid as described above.\n\nNote that your answer guesses are always answered correctly. If you ask a question before and after a guess, at least one of these two questions is answered correctly, as normal.",
    "tutorial": "step 1: How can we make sure that some statement is not joking? If something is told for two times in a row, we can be sure that it's true. For example if we are told that $x \\ne 3$ in two consecutive questions, we can be sure that it's true. Because at least one of those questions is answered correctly and that's enough. step 2: What can be found out if we ask about a set $S$? (assume that we will be answered correctly) If the answer is \"YES\", then $x \\in S$ and we can reduce our search domain to $S$. Otherwise, we can remove $S$ from the search domain. step 3: Using previous steps, how can we really reduce our search domain? Step 2 can do it only if we have a correct statement about $x$ and using Step 1, we can find something that is surely correct. Assume that $V$ is our current search domain. Split it into $4$ subsets $V_{1}, V_{2}, V_{3}$ and $V_{4}$. then ask about following sets: $V_{1} \\cup V_{2}$ $V_{1} \\cup V_{3}$ It's easy to show that no matter what the answers are, we can always remove at least one of the subsets from the search domain. For example if both answers are \"YES\", we can remove $V_{4}$ and if both answers are \"NO\", then we can remove $V_{1}$. So after these questions, we can reduce size of search domain by at least $min(|V_{1}|,|V_{2}|,|V_{3}|,|V_{4}|)$, and it's obvious to see that we can choose $V_{i}$'s in such a way that this value is at least $\\frac{|V|}{4}$. Finally, as long as size of the search domain is greater than $3$, we can reduce it using this algorithm. It can be shown easily that we can reduce our search domain to only $3$ numbers with at most $76$ questions. step 4: Now assume that we have only $3$ candidates for $x$, since we have only $2$ chances to guess, we must remove one of them. How can we do it? Note that since we've used $76$ questions in previous step, we only have $6$ questions left. Assume that our three candidates are $a, b$ and $c$. it can be shown that using following questions, we can always remove at least one of them from the search domain: ${a}$ ${b}$ ${b}$ ${a}$ After that, when we have only two candidates for $x$, we can guess them one by one and we are done.",
    "code": "/// In the name of God\n#pragma GCC optimize(\"Ofast\",\"unroll-loops\",\"O3\")\n#include <bits/stdc++.h>\n\nusing namespace std;\n\ninline bool get_answer(){string s; cin >> s; return s == \"YES\";}\n\ninline bool f(int i){return i&1;}\ninline bool g(int i){return i&2;}\n\nvoid solve(const vector<int> &Valid)\n{\n    if(Valid.size() < 3u)\n\t{\n\t    cout << \"! \" << Valid[0] << endl;\n\t\tstring s;\n\t\tcin >> s;\n\t\tif(s == \":)\")return;\n\t\tcout << \"! \" << Valid[1] << endl;\n\t\treturn;\n\t}\n\telse if(Valid.size() == 3u)\n\t{\n\t\tbool is[4];\n\t\tcout << \"? 1 \" << Valid[0] << endl;is[0] = get_answer();\n\t\tcout << \"? 1 \" << Valid[1] << endl;is[1] = get_answer();\n\t\tcout << \"? 1 \" << Valid[1] << endl;is[2] = get_answer();\n\t\tcout << \"? 1 \" << Valid[0] << endl;is[3] = get_answer();\n\t\tif(is[1] and is[2])return solve({Valid[1]});\n\t\telse if(!is[1] and !is[2])return solve({Valid[0], Valid[2]});\n\t\telse if((is[0] and is[1]) or (is[2] and is[3]))return solve({Valid[0], Valid[1]});\n\t\telse if((is[0] and !is[1]) or (!is[2] and is[3]))return solve({Valid[0], Valid[2]});\n\t\telse return solve({Valid[1], Valid[2]});\n\t}\n\telse\n\t{\n\t\tvector<int> query[2];\n\t\tfor(int i = 0; i < (int)Valid.size(); i++)\n\t\t{\n\t\t\tif(f(i))query[0].push_back(Valid[i]);\n\t\t\tif(g(i))query[1].push_back(Valid[i]);\n\t\t}\n\t\tbool is[2];\n\t\tfor(int i = 0; i < 2; i++)\n\t\t{\n\t\t\tcout << \"? \" << query[i].size();\n\t\t\tfor(auto u: query[i])cout << ' ' << u;\n\t\t\tcout << endl;\n\t\t\tis[i] = get_answer();\n\t\t}\n\t\tvector<int> NewValid;\n\t\tfor(int i = 0; i < (int)Valid.size(); i++)\n\t\t{\n\t\t\tif((!f(i) ^ is[0]) or (!g(i) ^ is[1]))NewValid.push_back(Valid[i]);\n\t\t}\n\t\treturn solve(NewValid);\n\t}\n}\nint main()\n{\n\tint n = 0;\n\tcin >> n;\n\tvector<int> all(n);\n\tfor(int i = 0; i < n; i++)all[i] = i+1;\n\tsolve(all);\n\treturn 0;\n}\n/// Thank God . . .",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive",
      "ternary search"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1746",
    "index": "E2",
    "title": "Joking (Hard Version)",
    "statement": "The only difference between this problem and the hard version is the maximum number of questions.\n\nThis is an interactive problem.\n\nThere is a hidden integer $1 \\le x \\le n$ which you have to find. In order to find it you can ask at most $\\mathbf{53}$ questions.\n\nIn each question you can choose a non-empty integer set $S$ and ask if $x$ belongs to $S$ or not, after each question, if $x$ belongs to $S$, you'll receive \"YES\", otherwise \"NO\".\n\nBut the problem is that not all answers are necessarily true (some of them are joking), it's just guaranteed that for each two consecutive questions, at least one of them is answered correctly.\n\nAdditionally to the questions, you can make at most $2$ guesses for the answer $x$. Each time you make a guess, if you guess $x$ correctly, you receive \":)\" and your program should terminate, otherwise you'll receive \":(\".\n\nAs a part of the joking, we will \\textbf{not} fix the value of $x$ in the beginning. Instead, it can change throughout the interaction as long as all the previous responses are valid as described above.\n\nNote that your answer guesses are always answered correctly. If you ask a question before and after a guess, at least one of these two questions is answered correctly, as normal.",
    "tutorial": "step 1: First note that in any question we ask, a set will be introduced as the set that contains $x$. If the answer is \"YES\", then the set that we asked is introduced and otherwise, its complement. Assume that our current search domain is some set $V$. In addition, assume that $V = A \\cup B$ such that set $A$ is the set that introduced to contain $x$ in very last step and $B$ is the set of other candidates for $x$ (candidates that don't belong to $A$). Now assume that in next question, a set $C$ is introduced to contain $x$ such that $C = a \\cup b, (a \\in A , b \\in B)$. what can we do? how can we reduce our search domain after this question? Considering the solution of E1, it's not so hard to see that we can remove $B-b$ from our search domain. So our new search domain will be $V' = A' \\cup B'$ such that $A' = C = a \\cup b$ is the set of candidates that introduced in last question and $B' = A - a$ is the set of other candidates. step 2: Let's calculate minimum needed questions for a search domain of size $n$ using the idea of previous step. We can do it using a simple dp, let $dp[A][B]$ be the minimum number of questions needed to find $x$ in a search domain of size $A+B$ in which $A$ numbers are introduced in last question and $B$ numbers are not. In order to calculate our dp, if we ask about some set which consists of $a$ numbers from first set and $b$ numbers from second set, we should update $dp[A][B]$ from $dp[A-a][a+b]$. So we can say that: $dp[A][B] = \\min_{a \\le A , b \\le B} dp[A-a][a+b]$ . Using this dp and keeping track of its updates, we can simply solve the task. But there is a problem, we don't have enough time to calculate the whole dp. So what can we do? step 3: Since calculating $dp[A][B]$ for $A <= n , B <= m$ is $O(n^2 \\cdot m^2)$, we can only calculate it for small $n$ and $m$ like $n,m \\le 100$. What can we do for the rest? Maybe some heuristic method? It's not so hard to see that for most $A$ and $B$ (especially for large values) it's best to update $dp[A][B]$ from something around $dp[A-A/2][A/2+B/2]$ (in other words, asking $A/2$ numbers from the first set and $B/2$ numbers from the second one). Using such method, we can calculate dp in a reasonable time and with a very good accuracy, and this accuracy is enough to find the answer in less than $53$ questions.",
    "code": "/// In the name of God\n#pragma GCC optimize(\"Ofast\",\"unroll-loops\",\"O3\")\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int SUM = 50;\nint dp[SUM][SUM];\npair<int,int> updater[SUM][SUM];\nmap<pair<int,int>, int> Dp;\nmap<pair<int,int>, pair<int,int>> Updater;\n \ninline void preprocess()\n{\n\tfor(int i = 0; i < SUM; i++)\n\t{\n\t\tfor(int j = 0; j < SUM; j++)\n\t\t{\n\t\t\tdp[i][j] = SUM;\n\t\t\tupdater[i][j] = {i, j};\n\t\t}\n\t}\n\tdp[0][0] = dp[0][1] = dp[1][0] = dp[2][0] = dp[1][1] = dp[0][2] = 0;\n\tfor(int sum = 0; sum < SUM; sum ++)for(int last = sum; last >= 0; last--)\n\t{\n\t\tint now = sum - last;\n\t\tfor(int SelectLast = 0; SelectLast <= last; SelectLast++)for(int SelectNow = 0; SelectNow <= now; SelectNow++)\n\t\t{\n\t\t\tif(dp[last][now] > 1 + max(dp[now-SelectNow][SelectNow+SelectLast], dp[SelectNow][sum-SelectNow-SelectLast]))\n\t\t\t{\n\t\t\t\tdp[last][now] = 1 + max(dp[now-SelectNow][SelectNow+SelectLast], dp[SelectNow][now+last-SelectNow-SelectLast]);\n\t\t\t\tupdater[last][now] = {SelectLast, SelectNow};\n\t\t\t}\n\t\t}\n\t}\n}\n \ninline int DP(const int last, const int now)\n{\n\tif(last < 0 || now < 0)return SUM;\n\tif(last + now < SUM)return dp[last][now];\n\tif(Dp.find({last, now}) != Dp.end())return Dp[{last, now}];\n\tif((last&1) && (now&1))\n\t{\n\t\tDp[{last, now}] = 1 + DP((now+1)/2, (last+ now)/2);\n\t\tUpdater[{last, now}] = {(last+1)/2, now/2};\n\t}\n\telse\n\t{\n\t\tDp[{last, now}] = 1 + DP((now+1)/2, (last+1)/2+(now+1)/2);\n\t\tUpdater[{last, now}] = {(last+1)/2, (now+1)/2};\n\t}\n\treturn Dp[{last, now}];\n}\n \ninline bool IsIn(const int x, const vector<int> &Sorted)\n{\n\tauto u = lower_bound(Sorted.begin(), Sorted.end(), x);\n\tif(u == Sorted.end() or *u != x)return false;\n\treturn true;\n}\n \nvector<int> solve(const vector<int> &LastAns, const vector<int> &Valid)\n{\n\tif((int)Valid.size() < 3)\n\t{\n\t\treturn Valid;\n\t}\n\tpair<int,int> Select;\n\tif((int)Valid.size() < SUM)\n\t{\n\t\tSelect = updater[LastAns.size()][Valid.size()-LastAns.size()];\n\t}\n\telse\n\t{\n\t\tDP((int)LastAns.size(), (int)(Valid.size()-LastAns.size()));\n\t\tSelect = Updater[{LastAns.size(), Valid.size()-LastAns.size()}];\n\t}\n\tvector<int> query;\n\tint p = 0;\n\twhile(Select.first --)query.push_back(LastAns[p++]);\n\tp = 0;\n\tvector<int> LastAnsSorted = LastAns;\n\tsort(LastAnsSorted.begin(), LastAnsSorted.end());\n\twhile(Select.second --)\n\t{\n\t\twhile(IsIn(Valid[p], LastAnsSorted)) p++;\n\t\tquery.push_back(Valid[p++]);\n\t}\n\tcout << \"? \" << query.size();\n\tfor(auto u: query)cout << ' ' << u;\n\tcout << endl;\n\t\n\tstring s;\n\tcin >> s;\n\tbool correct = (s == \"YES\");\n\tsort(query.begin(), query.end());\n\tvector<int> NewLast, NewValid;\n\tfor(auto u: Valid)\n\t{\n\t\tif(!IsIn(u, LastAnsSorted) and (correct ^ IsIn(u, query)))\n\t\t{\n\t\t\tNewLast.push_back(u);\n\t\t}\n\t\tif(!IsIn(u, LastAnsSorted) or !(correct ^ IsIn(u, query)))\n\t\t{\n\t\t\tNewValid.push_back(u);\n\t\t}\n\t}\n\tvector<int> ans = solve(NewLast, NewValid);\n\treturn ans;\n}\n \nint main()\n{\n\tpreprocess();\n \n\tint n;\n\tcin >> n;\n\tvector<int> all(n);\n\tfor(int i = 0; i < n; i++)all[i] = i+1;\n\tvector<int> valid = solve({}, all);\n\tfor(auto guess: valid)\n\t{\n\t\tcout << \"! \" << guess << endl;\n\t\tstring s;\n\t\tcin >> s;\n\t\tif(s == \":)\")return 0;\n\t}\n\t\n\treturn 0;\n}\n/// Thank God . . .",
    "tags": [
      "dp",
      "interactive"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1746",
    "index": "F",
    "title": "Kazaee",
    "statement": "You have an array $a$ consisting of $n$ positive integers and you have to handle $q$ queries of the following types:\n\n- $1$ $i$ $x$: change $a_{i}$ to $x$,\n- $2$ $l$ $r$ $k$: check if the number of occurrences of every positive integer in the subarray $a_{l}, a_{l+1}, \\ldots a_{r}$ is a multiple of $k$ (check the example for better understanding).",
    "tutorial": "step 1: First of all, we can compress $a_{i}$'s and $x$'s (in second type query). so we can assume that all numbers are less than $n+q \\le 6 \\cdot 10^5$. step 2: Lets first solve the problem for smaller constrains. We can use data structures like fenwick tree or segment tree to count the number of occurrences of each number and check if it's divisible by $k$ to answer second type query. And we can simply update our data structure after each query of the first type. So if we use something like fenwick tree, we can handle everything in $O((n+q) \\cdot n + (n+q) \\cdot q \\cdot log_{2}(n))$. step 3: Obviously we can not use previous step solution for original constrains. In other words, we don't have enough time to check all numbers one by one. How can we do better? Checking them together?! It's obviously not a good idea to check all numbers together (checking that sum of their occurrences is divisible by $k$). So what can we do? What if we check a random subset of numbers? step 4: Assume that $S$ is a random subset of all numbers, it's obvious that if the answer of the query is \"YES\" (number of occurrences of every number is divisible by $k$), the condition holds for $S$ too (sum of number of occurrences of numbers that belong to $S$ is divisible by $k$). What about the opposite? What is the probability that the answer of the query is \"NO\" and yet sum of occurrences of numbers belonging to $S$ is divisible by $k$? It's not so hard to prove that the probability is equal to $\\frac{1}{2}$ for $k = 2$ and it's less than $\\frac{1}{2}$ for $k \\ge 2$. So in general, the probability that a random subset $S$ leads to a wrong answer is less than or equal to $\\frac{1}{2}$. So if we use something like $30$ random subsets, the probability will be less than $\\frac{1}{2^{30}}$ which is reasonable for problem constrains and we can use this random method to solve the task.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long int ll;\n \nmt19937 rnd(time(0));\n \nconst int N = 300'000 + 5; \nconst int Q = 300'000 + 5; \nconst int T = 50;\nbitset<N+Q> RandomSet[T];\nunordered_map<int, int> id; int cnt_id = 0;\nint n, q, A[N];\n \nstruct fenwick\n{\n\tint PartialSum[N];\n\tfenwick()\n\t{\n\t\tfor(int i = 0; i < N; i++)PartialSum[i] = 0;\n\t}\n\tinline void add(int index, bool increase)\n\t{\n\t\twhile(index < N)\n\t\t{\n\t\t\tPartialSum[index] += (increase? 1 : -1);\n\t\t\tindex += index&-index;\n\t\t}\n\t}\n\tinline int get(int index)\n\t{\n\t\tint sum = 0;\n\t\twhile(index)\n\t\t{\n\t\t\tsum += PartialSum[index];\n\t\t\tindex -= index&-index;\n\t\t}\n\t\treturn sum;\n\t}\n}Fen[T];\n \ninline int GetId(const int x)\n{\n\tauto id_iterator = id.find(x);\n\tif(id_iterator == id.end())\n\t{\n\t\treturn id[x] = cnt_id++;\n\t}\n\telse return (*id_iterator).second;\n}\n \ninline void ChooseRandomSets()\n{\n\tfor(int i = 0; i < T; i++)\n\t{\n\t\tfor(int j = 0; j < N+Q; j++)\n\t\t{\n\t\t\tif(rnd()&1)RandomSet[i].set(j);\n\t\t}\n\t}\n}\n \ninline void AddArrayToFenwick()\n{\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint MyId = GetId(A[i]);\n\t\tfor(int j = 0; j < T; j++)\n\t\t{\n\t\t\tif(RandomSet[j][MyId])Fen[j].add(i+1, true);\n\t\t}\n\t}\n}\n\t\ninline void Query()\n{\n\tint index, l, r, k, x, type;\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tcin >> type;\n\t\tif(type == 1)\n\t\t{\n\t\t\tcin >> index >> x;\n\t\t\tindex --;\n\t\t\tint IdPre = GetId(A[index]);\n\t\t\tint IdNew = GetId(x);\n\t\t\tA[index] = x;\n\t\t\tfor(int j = 0; j < T; j++)\n\t\t\t{\n\t\t\t\tif(RandomSet[j][IdPre])Fen[j].add(index+1, false);\n\t\t\t\tif(RandomSet[j][IdNew])Fen[j].add(index+1, true);\n\t\t\t}\n\t\t}\n\t\tif(type == 2)\n\t\t{\n\t\t\tcin >> l >> r >> k;\n\t\t\tl--;\n\t\t\tif(k == 1){cout << \"YES\\n\"; continue;}\n\t\t\telse if((r-l)%k != 0){cout << \"NO\\n\"; continue;}\n\t\t\tbool answer = true;\n\t\t\tfor(int j = 0; j < T; j++)\n\t\t\t{\n\t\t\t\tif((Fen[j].get(r)-Fen[j].get(l))%k != 0){answer = false; break;}\n\t\t\t}\n\t\t\tcout << (answer?\"YES\":\"NO\") << '\\n';\n\t\t}\n\t}\n}\n \nint main()\n{\n    ios::sync_with_stdio(false) , cin.tie(0);\n    ChooseRandomSets();\n    cin >> n >> q;\n    for(int i = 0; i < n; i++) cin >> A[i];\n    AddArrayToFenwick();\n    Query();\n    return 0;\n}",
    "tags": [
      "data structures",
      "hashing",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1746",
    "index": "G",
    "title": "Olympiad Training",
    "statement": "Anton decided to get ready for an Olympiad in Informatics. Ilya prepared $n$ tasks for him to solve. It is possible to submit the solution for the $i$-th task in the first $d_{i}$ days only. Anton \\textbf{cannot} solve more than one task a day. Ilya estimated the usefulness of the $i$-th tasks as $r_{i}$ and divided the tasks into three topics, the topic of the $i$-th task is $type_{i}$.\n\nAnton wants to solve exactly $a$ tasks on the first topic, $b$ tasks on the second topic and $c$ tasks on the third topic. Tell Anton if it is possible to do so, and if it is, calculate the maximum total usefulness of the tasks he may solve.",
    "tutorial": "Consider all subsets of the original set in which tasks can be performed in some order to satisfy the constraints on their completion, and also that the size of each of them does not exceed $a+b+c$. It is easy to show that this set is a weighted matroid. This means that the optimal set of tasks can be found using a greedy algorithm. So, we can find a set of tasks with maximum total usefulness, which: satisfies all deadline constraints has no more than $a+b+c$ elements For the given parameters $(x, y, z)$, we introduce the following transformation: Increase the usefulness of all tasks of the first type by $x$, the second type~--- by $y$, and the third type~--- by $z$. Let's assume that the optimal solution after the transformation is described by the triple $[a',b',c']$~--- the number of problems of each type, respectively. We need to get a solution described by the triple $[a,b,c]$. For $[a,b,c] \\neq [a',b',c']$, $a+b+c=a'+b'+c'$ holds. Then (without limitation of generality, since there are at least two inequalities among $a\\vee a',b\\vee b',c\\vee c'$) we assume that $a'>a,b'<b$. Consider the following coordinate system on a two-dimensional plane (modulo the addition of $\\overrightarrow{(1;1;1)})$: For the coordinates of the point, we take the value $\\vec{x}\\times x+\\vec{y}\\times y + \\vec{z}\\times z$$(\\vec{x}+\\vec{y}+\\vec{z} =\\vec{0})$. It is easy to understand that the coordinates of the point $(x; y)$ on the plane are uniquely set by the triple $(x; y; z)$ up to the addition of $\\overrightarrow{(1;1;1)} \\times k, k \\in\\mathbb{Z}$ Let's assume that there are parameters $(x,y,z)$ for which the optimal solution is unique and equal to $[a,b,c]$ (see \"But what if..?\" to see what needs to be done to the input to make this hold). Consider the solution $[a',b',c']$ for the \"center\" of the current polygon (initially it is a hexagon with infinitely distant coordinates). The \"center\" is the center of the triangle formed by the middle lines of our polygon. On this plane, decreasing $z$ or $y$ does not increase $b'+c'$, therefore, it does not decrease $a'$. Thus, the red area in the picture below does not suit us. Increasing $x$ or $z$ does not decrease $a'+c'$, therefore, it does not increase $b'$. Because of this, the blue area in the picture below does not suit us either. So, we need to cut off one half-plane along the $z$ axis. It can be shown that the area of the polygon under consideration decreases by a constant time for every 2-3 iterations. But what if the number of tasks of the desired color jumps from $a-1$ to $a+1$ at once? This is possible if and only if with the addition of some $x$ we get several pairs of elements of equal weight at the same time. To get rid of this, we can simply add a random number from $0$ to $\\frac{1}{3}$ to each weight. The fact that such a change will fix the problem described above and will not change the optimal answer to the original problem remains to the reader as an exercise (the authors have proof). After $O(\\log C)$ iterations, our algorithm will converge to a point (a triple of real numbers). It remains only to check that the solution found is suitable for us. $O(n\\log n\\log C)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#ifdef SG\n\t#include <debug.h>\n#else\n\ttemplate<typename T> struct outputer;\n\tstruct outputable {};\n\t#define PRINT(...)\n\t#define OUTPUT(...)\n\t#define show(...)\n\t#define debug(...)\n\t#define deepen(...)\n\t#define timer(...)\n\t#define fbegin(...)\n\t#define fend\n\t#define pbegin(...)\n\t#define pend\n#endif\n \n#define ARG4(_1,_2,_3,_4,...) _4\n \n#define forn3(i,l,r) for (int i = int(l); i < int(r); ++i)\n#define forn2(i,n) forn3 (i, 0, n)\n#define forn(...) ARG4(__VA_ARGS__, forn3, forn2) (__VA_ARGS__)\n \n#define ford3(i,l,r) for (int i = int(r) - 1; i >= int(l); --i)\n#define ford2(i,n) ford3 (i, 0, n)\n#define ford(...) ARG4(__VA_ARGS__, ford3, ford2) (__VA_ARGS__)\n \n#define ve vector\n#define pa pair\n#define tu tuple\n#define mp make_pair\n#define mt make_tuple\n#define pb emplace_back\n#define fs first\n#define sc second\n#define all(a) (a).begin(), (a).end()\n#define sz(a) ((int)(a).size())\n \ntypedef long double ld;\ntypedef signed __int128 lll;\ntypedef unsigned __int128 ulll;\ntypedef int64_t ll;\ntypedef uint64_t ull;\ntypedef uint32_t ui;\ntypedef uint16_t us;\ntypedef uint8_t uc;\ntypedef pa<int, int> pii;\ntypedef pa<int, ll> pil;\ntypedef pa<ll, int> pli;\ntypedef pa<ll, ll> pll;\ntypedef ve<int> vi;\n \ntemplate<typename T> inline auto sqr (T x) -> decltype(x * x) {return x * x;}\ntemplate<typename T1, typename T2> inline bool umx (T1& a, T2 b) {if (a < b) {a = b; return 1;} return 0;}\ntemplate<typename T1, typename T2> inline bool umn (T1& a, T2 b) {if (b < a) {a = b; return 1;} return 0;}\n \nconst int N = 100000;\nconst int X = 1000000000;\nconst int T = 3;\n \nstruct Input {\n\tint n;\n\tstd::array<int, T> k;\n\tint a[N], t[N], d[N];\n\t\n\tbool read() {\n\t\tif (!(cin >> n)) {\n\t\t\treturn 0;\n\t\t}\n\t\tforn (i, T) {\n\t\t\tcin >> k[i];\n\t\t}\n\t\tforn (i, n) {\n\t\t\tcin >> a[i] >> t[i] >> d[i];\n\t\t\t--t[i];\n\t\t\t--d[i];\n\t\t}\n\t\treturn 1;\n\t}\n \n\tvoid init(const Input& input) {\n\t\t*this = input;\n\t}\n};\n \nstruct Data: Input {\n\tll ans;\n\t\n\tvoid write() {\n\t\tcout << ans << endl;\n\t}\n};\n \n \nnamespace Main {\n\tconst lll P = 2 * N + 1;\n\tconst lll Q = 2 * N + 2;\n\tconst lll R = 2 * N + 3;\n\tconst lll A[3] = {3 * P * Q, 3 * P * R, 3 * Q * R};\n\tconst lll M = 3 * P * Q * R * N;\n\tconst lll inf = (X + 1) * M;\n \n\tstruct SNM {\n\t\tint rnd = 0;\n\t\tint n;\n\t\tint pr[N];\n \n\t\tvoid init(int cnt) {\n\t\t\tn = cnt;\n\t\t\tforn (i, n) {\n\t\t\t\tpr[i] = i;\n\t\t\t}\n\t\t}\n \n\t\tint get_p(int v) {\n\t\t\tif (v < 0 || pr[v] == v) {\n\t\t\t\treturn v;\n\t\t\t}\n\t\t\treturn pr[v] = get_p(pr[v]);\n\t\t}\n \n\t\tbool add(int v) {\n\t\t\tv = get_p(v);\n\t\t\tif (v == -1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tpr[v] = v - 1;\n\t\t\treturn 1;\n\t\t}\n\t};\n\t\n\tstruct Solution: Data {\n\t\tSNM snm;\n \n\t\tint m;\n\t\tlll b[N], c[N];\n\t\tvi ord[T];\n \n\t\tarray<int, T> check(const array<lll, T>& adds) {\n\t\t\tforn (i, n) {\n\t\t\t\tc[i] = b[i] + adds[t[i]];\n\t\t\t}\n\t\t\tauto cmp = [&](int lhs, int rhs) {\n\t\t\t\treturn c[lhs] > c[rhs];\n\t\t\t};\n\t\t\tstatic vi q;\n\t\t\tq.clear();\n\t\t\tforn (i, T) {\n\t\t\t\tstatic vi w;\n\t\t\t\tw.resize(sz(q) + sz(ord[i]));\n\t\t\t\tmerge(all(q), all(ord[i]), w.begin(), cmp);\n\t\t\t\tq.swap(w);\n\t\t\t}\n \n\t\t\tsnm.init(n);\n\t\t\tarray<int, T> cnt{};\n\t\t\tint tot = 0;\n\t\t\tll val = 0;\n\t\t\tfor (int i : q) {\n\t\t\t\tif (tot >= m) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (snm.add(d[i])) {\n\t\t\t\t\tcnt[t[i]]++;\n\t\t\t\t\ttot++;\n\t\t\t\t\tval += a[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cnt == k) {\n\t\t\t\tans = val;\n\t\t\t}\n\t\t\treturn cnt;\n\t\t}\n \n\t\t// x[i] == adds[(i + 1) % T] - adds[i]\n \n\t\tarray<lll, T> get_middle_point(const array<lll, T>& lb, const array<lll, T>& rb) {\n\t\t\tarray<lll, T> x;\n\t\t\tforn (i, T) {\n\t\t\t\tx[i] = lb[i] + rb[i];\n\t\t\t}\n\t\t\tlll sum = accumulate(all(x), lll(0));\n\t\t\tforn (i, T) {\n\t\t\t\tx[i] = T * x[i] - sum;\n\t\t\t\tif (x[i] >= 0) {\n\t\t\t\t\tx[i] /= (2 * T);\n\t\t\t\t} else {\n\t\t\t\t\tx[i] = (x[i] - 2 * T + 1) / (2 * T);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsum = accumulate(all(x), lll(0));\n\t\t\tforn (i, T) {\n\t\t\t\tif (sum < 0 && x[i] < rb[i]) {\n\t\t\t\t\tx[i]++;\n\t\t\t\t\tsum++;\n\t\t\t\t}\n\t\t\t\tassert(x[i] >= lb[i]);\n\t\t\t\tassert(x[i] <= rb[i]);\n\t\t\t}\n\t\t\tassert(sum == 0);\n\t\t\treturn x;\n\t\t}\n \n\t\tbool search() {\n\t\t\tarray<lll, T> lb, rb;\n\t\t\tforn (i, T) {\n\t\t\t\tlb[i] = -2 * inf;\n\t\t\t\trb[i] = 2 * inf;\n\t\t\t}\n \n\t\t\twhile (true) {\n\t\t\t\t{\n\t\t\t\t\tlll sum_l = accumulate(all(lb), lll(0));\n\t\t\t\t\tlll sum_r = accumulate(all(rb), lll(0));\n\t\t\t\t\tforn (i, T) {\n\t\t\t\t\t\tlll sol = sum_l - lb[i];\n\t\t\t\t\t\tlll sor = sum_r - rb[i];\n\t\t\t\t\t\tumx(lb[i], -sor);\n\t\t\t\t\t\tumn(rb[i], -sol);\n\t\t\t\t\t\tif (lb[i] > rb[i]) {\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tarray<lll, T> x = get_middle_point(lb, rb);\n\t\t\t\tarray<lll, T> adds{};\n\t\t\t\tforn (i, T - 1) {\n\t\t\t\t\tadds[i + 1] = adds[i] + x[i];\n\t\t\t\t}\n\t\t\t\tarray<int, T> cnt = check(adds);\n\t\t\t\tassert(accumulate(all(cnt), 0) == m);\n\t\t\t\tif (cnt == k) {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\t\t\t\tforn (i, T) {\n\t\t\t\t\tlll d1 = cnt[i] - k[i];\n\t\t\t\t\tlll d2 = cnt[(i + 1) % T] - k[(i + 1) % T];\n\t\t\t\t\tif (d1 > 0 && d2 < 0) {\n\t\t\t\t\t\tlb[i] = x[i] + 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (d1 < 0 && d2 > 0) {\n\t\t\t\t\t\trb[i] = x[i] - 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid solve() {\n\t\t\tforn (i, n) {\n\t\t\t\tb[i] = a[i] * M + i * A[t[i]];\n\t\t\t}\n\t\t\tforn (i, n) {\n\t\t\t\tord[t[i]].pb(i);\n\t\t\t}\n\t\t\tforn (i, T) {\n\t\t\t\tsort(all(ord[i]), [&](int lhs, int rhs) {\n\t\t\t\t\treturn b[lhs] > b[rhs];\n\t\t\t\t});\n\t\t\t}\n\t\t\tm = accumulate(all(k), 0);\n \n\t\t\t{\n\t\t\t\tarray<int, T> r = check({});\n\t\t\t\tif (accumulate(all(r), 0) != m) {\n\t\t\t\t\tans = -1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tforn (i, T) {\n\t\t\t\tarray<lll, T> adds{};\n\t\t\t\tadds[i] = inf;\n\t\t\t\tif (check(adds)[i] < k[i]) {\n\t\t\t\t\tans = -1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tadds[i] = -inf;\n\t\t\t\tif (check(adds)[i] > k[i]) {\n\t\t\t\t\tans = -1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(search());\n\t\t}\n\t\t\n\t\tvoid clear() {\n\t\t\tforn (i, T) {\n\t\t\t\tord[i].clear();\n\t\t\t}\n\t\t}\n\t};\n}\n \n \nMain::Solution sol;\n \nint main() {\n\t#ifdef SG\n\t\tfreopen((problemname + \".in\").c_str(), \"r\", stdin);\n//\t\tfreopen((problemname + \".out\").c_str(), \"w\", stdout);\n\t#endif\n\t\n\tint t;\n\tcin >> t;\n\tforn (i, t) {\n\t\tsol.read();\n\t\tsol.solve();\n\t\tsol.write();\n\t\tsol.clear();\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "flows",
      "geometry",
      "implementation",
      "sortings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1747",
    "index": "A",
    "title": "Two Groups",
    "statement": "You are given an array $a$ consisting of $n$ integers. You want to distribute these $n$ integers into two groups $s_1$ and $s_2$ (groups can be empty) so that the following conditions are satisfied:\n\n- For each $i$ $(1 \\leq i \\leq n)$, $a_i$ goes into exactly one group.\n- The value $|sum(s_1)| - |sum(s_2)|$ is the maximum possible among all such ways to distribute the integers.Here $sum(s_1)$ denotes the sum of the numbers in the group $s_1$, and $sum(s_2)$ denotes the sum of the numbers in the group $s_2$.\n\nDetermine the maximum possible value of $|sum(s_1)| - |sum(s_2)|$.",
    "tutorial": "How about putting all positive numbers in one group and negative in second group Let $S$ denotes sum of element of array $a$. Claim: Answer is $|S|$. Proof: Let sum of all positive elements is $S_{pos}$ and sum of all negative elements $S_{neg}$. Put all positive numbers in first group and negative numbers in second group. We get $||S_{pos}| - |S_{neg}|| = |S|$. Let's prove that we can not do better than that. Let $S_1$ denotes sum of elements of first group and $S_2$ denotes sum of elements of second group. We have $|S_1| - |S_2| \\leq |S_1 + S_2| = |S|$. Hence $|S|$ is the upperbound for the answer.",
    "code": "// Jai Shree Ram\n#include<bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,a,n)     for(int i=a;i<n;i++)\n#define ll             long long\n#define int            long long\n#define pb             push_back\n#define all(v)         v.begin(),v.end()\n#define endl           \"\\n\"\n#define x              first\n#define y              second\n#define gcd(a,b)       __gcd(a,b)\n#define mem1(a)        memset(a,-1,sizeof(a))\n#define mem0(a)        memset(a,0,sizeof(a))\n#define sz(a)          (int)a.size()\n#define pii            pair<int,int>\n#define hell           1000000007\n#define elasped_time   1.0 * clock() / CLOCKS_PER_SEC\n\n\n\ntemplate<typename T1,typename T2>istream& operator>>(istream& in,pair<T1,T2> &a){in>>a.x>>a.y;return in;}\ntemplate<typename T1,typename T2>ostream& operator<<(ostream& out,pair<T1,T2> a){out<<a.x<<\" \"<<a.y;return out;}\ntemplate<typename T,typename T1>T maxs(T &a,T1 b){if(b>a)a=b;return a;}\ntemplate<typename T,typename T1>T mins(T &a,T1 b){if(b<a)a=b;return a;}\n\n\nint solve(){\n \t\tint n; cin >> n;\n \t\tint s = 0;\n \t\tfor(int i = 0; i < n; i++){\n \t\t\tint x; cin >> x;\n \t\t\ts += x;\n \t\t}\n \t\tcout << abs(s) << endl;\n return 0;\t\n}\nsigned main(){\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #ifdef SIEVE\n    sieve();\n    #endif\n    #ifdef NCR\n    init();\n    #endif\n    int t=1;cin>>t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1747",
    "index": "B",
    "title": "BAN BAN",
    "statement": "You are given an integer $n$.\n\nLet's define $s(n)$ as the string \"BAN\" concatenated $n$ times. For example, $s(1)$ = \"BAN\", $s(3)$ = \"BANBANBAN\". Note that the length of the string $s(n)$ is equal to $3n$.\n\nConsider $s(n)$. You can perform the following operation on $s(n)$ any number of times (possibly zero):\n\n- Select any two distinct indices $i$ and $j$ $(1 \\leq i, j \\leq 3n, i \\ne j)$.\n- Then, swap $s(n)_i$ and $s(n)_j$.\n\nYou want the string \"BAN\" to \\textbf{not appear} in $s(n)$ as a \\textbf{subsequence}. What's the smallest number of operations you have to do to achieve this? Also, find one such shortest sequence of operations.\n\nA string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters.",
    "tutorial": "Instead of subsequences solve for substrings. That is there should not be any substring $\\texttt{BAN}$ after performing operations. In one operation you can destroy atmost $2$ substrings. Find minimum operations to destroy $n$ substrings. $\\left \\lceil\\frac{n}{2}\\right \\rceil$ Congrats, you have solved for subsequences also! No subsequences of string $\\texttt{BAN}$ would also mean no substrings of $\\texttt{BAN}$ in original string. Let minimum number of operations to have no substrings of $\\texttt{BAN}$ be $x$, it would be also be the lower bound for having no subsequences of string $\\texttt{BAN}$. Claim: $x = \\left \\lceil\\frac{n}{2}\\right \\rceil$. Proof: Swap $i$-th $\\texttt{B}$ from start with $i$-th $\\texttt{N}$ from end for $1 \\leq i \\leq \\left \\lceil\\frac{n}{2}\\right \\rceil$. We can see that, no substrings of $\\texttt{BAN}$ exists after performing $\\left \\lceil\\frac{n}{2}\\right \\rceil$ operations. Since we can only destroy atmost $2$ substrings in one operations, $\\left \\lceil\\frac{n}{2}\\right \\rceil$ is minimum possible. Now if you see clearly, after performing above operations, there does not exist any subsequence of string $\\texttt{BAN}$ in original string. Hence $\\left \\lceil\\frac{n}{2}\\right \\rceil$ is also the answer for the original problem. Divide problem into two different cases. When $a_1 \\gt \\min(a)$ and when $a_1 = \\min(a)$. You do not need more hints to solve the problem. Case 1: $a_1 \\gt \\min(a)$ $\\texttt{Alice}$ can force the $\\texttt{Bob}$ to always decrease the minimum element by always choosing minimum element of $a$ in her turn. Where as $\\texttt{Bob}$ can not do much, all other elements he would swap with would be greater than or equal to $\\min(a)$. Even if there exists multiple minimums in $a$, In first move $\\texttt{Alice}$ would decrease from $a_1$, hence in this case $\\texttt{Alice}$ would always win. Case 2: $a_1 = \\min(a)$ In this case optimal startegy for $\\texttt{Bob}$ would be to always chhose minimum element of the array, which is $a_1$. $\\texttt{Alice}$ would always be swapping the element greater than $a_1$ in her turn, hence in the case $\\texttt{Bob}$ would always win",
    "code": "// Jai Shree Ram  \n  \n#include<bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,a,n)     for(int i=a;i<n;i++)\n#define ll             long long\n#define int            long long\n#define pb             push_back\n#define all(v)         v.begin(),v.end()\n#define endl           \"\\n\"\n#define x              first\n#define y              second\n#define gcd(a,b)       __gcd(a,b)\n#define mem1(a)        memset(a,-1,sizeof(a))\n#define mem0(a)        memset(a,0,sizeof(a))\n#define sz(a)          (int)a.size()\n#define pii            pair<int,int>\n#define hell           1000000007\n#define elasped_time   1.0 * clock() / CLOCKS_PER_SEC\n\n\n\ntemplate<typename T1,typename T2>istream& operator>>(istream& in,pair<T1,T2> &a){in>>a.x>>a.y;return in;}\ntemplate<typename T1,typename T2>ostream& operator<<(ostream& out,pair<T1,T2> a){out<<a.x<<\" \"<<a.y;return out;}\ntemplate<typename T,typename T1>T maxs(T &a,T1 b){if(b>a)a=b;return a;}\ntemplate<typename T,typename T1>T mins(T &a,T1 b){if(b<a)a=b;return a;}\n\n\nint solve(){\n \t\tint n; cin >> n;\n \t\tvector<int> a(n);\n \t\tfor(auto &i:a)cin >> i;\n \t\tsort(a.begin() + 1,a.end());\n \t\tcout << (a[0] > a[1] ? \"Alice\" : \"Bob\") << endl;\n return 0;\n}\nsigned main(){\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #ifdef SIEVE\n    sieve();\n    #endif\n    #ifdef NCR\n    init();\n    #endif\n    int t=1;cin>>t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 900
  },
  {
    "contest_id": "1747",
    "index": "C",
    "title": "Swap Game",
    "statement": "Alice and Bob are playing a game on an array $a$ of $n$ positive integers. Alice and Bob make alternating moves with Alice going first.\n\nIn his/her turn, the player makes the following move:\n\n- If $a_1 = 0$, the player loses the game, otherwise:\n- Player chooses some $i$ with $2\\le i \\le n$. Then player decreases the value of $a_1$ by $1$ and swaps $a_1$ with $a_i$.\n\nDetermine the winner of the game if both players play optimally.",
    "tutorial": "Case 1: $a_1 \\gt \\min(a)$ $\\texttt{Alice}$ can force the $\\texttt{Bob}$ to always decrease the minimum element by always choosing minimum element of $a$ in her turn. Where as $\\texttt{Bob}$ can not do much, all other elements he would swap with would be greater than or equal to $\\min(a)$. Even if there exists multiple minimums in $a$, In first move $\\texttt{Alice}$ would decrease from $a_1$, hence in this case $\\texttt{Alice}$ would always win. Case 2: $a_1 = \\min(a)$ In this case optimal startegy for $\\texttt{Bob}$ would be to always chhose minimum element of the array, which is $a_1$. $\\texttt{Alice}$ would always be swapping the element greater than $a_1$ in her turn, hence in the case $\\texttt{Bob}$ would always win",
    "code": "// Jai Shree Ram  \n  \n#include<bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,a,n)     for(int i=a;i<n;i++)\n#define ll             long long\n#define int            long long\n#define pb             push_back\n#define all(v)         v.begin(),v.end()\n#define endl           \"\n\"\n#define x              first\n#define y              second\n#define gcd(a,b)       __gcd(a,b)\n#define mem1(a)        memset(a,-1,sizeof(a))\n#define mem0(a)        memset(a,0,sizeof(a))\n#define sz(a)          (int)a.size()\n#define pii            pair<int,int>\n#define hell           1000000007\n#define elasped_time   1.0 * clock() / CLOCKS_PER_SEC\n\n\n\ntemplate<typename T1,typename T2>istream& operator>>(istream& in,pair<T1,T2> &a){in>>a.x>>a.y;return in;}\ntemplate<typename T1,typename T2>ostream& operator<<(ostream& out,pair<T1,T2> a){out<<a.x<<\" \"<<a.y;return out;}\ntemplate<typename T,typename T1>T maxs(T &a,T1 b){if(b>a)a=b;return a;}\ntemplate<typename T,typename T1>T mins(T &a,T1 b){if(b<a)a=b;return a;}\n\n\nint solve(){\n \t\tint n; cin >> n;\n \t\tvector<int> a(n);\n \t\tfor(auto &i:a)cin >> i;\n \t\tsort(a.begin() + 1,a.end());\n \t\tcout << (a[0] > a[1] ? \"Alice\" : \"Bob\") << endl;\n return 0;\n}\nsigned main(){\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #ifdef SIEVE\n    sieve();\n    #endif\n    #ifdef NCR\n    init();\n    #endif\n    int t=1;cin>>t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "games"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1747",
    "index": "D",
    "title": "Yet Another Problem",
    "statement": "You are given an array $a$ of $n$ integers $a_1, a_2, a_3, \\ldots, a_n$.\n\nYou have to answer $q$ independent queries, each consisting of two integers $l$ and $r$.\n\n- Consider the subarray $a[l:r]$ $=$ $[a_l, a_{l+1}, \\ldots, a_r]$. You can apply the following operation to the subarray any number of times (possibly zero)-\n\n- Choose two integers $L$, $R$ such that $l \\le L \\le R \\le r$ and $R - L + 1$ is \\textbf{odd}.\n- Replace each element in the subarray from $L$ to $R$ with the XOR of the elements in the subarray $[L, R]$.\n\n- The answer to the query is the minimum number of operations required to make all elements of the subarray $a[l:r]$ equal to $0$ or $-1$ if it is impossible to make all of them equal to $0$.\n\nYou can find more details about XOR operation here.",
    "tutorial": "Forget queries, they are just here to make problem look complicated. Solve for $q = 1$. XOR of array does not change after operations. Hence if initially XOR is not equal to $0$, answer is $-1$. Is this condition sufficient? No, We need one more condition There must exist some prefix of odd size, such that xor of elements of that prefix is $0$. First forget queries, solve for single array $a$. Let's make some observations. Xor of array does not change after each operation Xor of array does not change after each operation Look at the set of prefix XORs while doing operations. Its size always decreases or remains same after each operation. Infact we can further reduce it to parities. Let $S_{0}$, $S_{1}$ be sets of prefix XOR's of parities $0$ and $1$ respectively. After each operation new sets $S'_{0}$, $S'_{1}$ will be subsets of $S_{0}$ and $S_1$ respectively. Look at the set of prefix XORs while doing operations. Its size always decreases or remains same after each operation. Infact we can further reduce it to parities. Let $S_{0}$, $S_{1}$ be sets of prefix XOR's of parities $0$ and $1$ respectively. After each operation new sets $S'_{0}$, $S'_{1}$ will be subsets of $S_{0}$ and $S_1$ respectively. So necessary conditions for answer to exist is that xor of array should be $0$ and $S_{1}$ should contains $0$. Now comes to minimum operations. Claim: If above conditions are satisfied, its always possible to make all elements $0$ in less than or equal to $2$ operations Proof: Let length of array be $n$. Case 1: $n$ is odd Just apply the operation on whole array. Case 2: $n$ is even There will exists some odd size prefix $j$ such that xor of its elements is $0$. Apply operation on $[1,j]$ and $[j + 1,n]$. It can happen that $j = 1$ or $j = n - 1$, in that case we only need one operation, because other remaining element would already be equal to $0$. To solve for queries, you just need to check for odd prefix, which can be done using some data structure like $\\texttt{std::map}$ or $\\texttt{std::set}$ in C++. Do not forget to check the case when all elements are already $0$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std ;\n\n#define ll              long long \n#define pb              push_back\n#define all(v)          v.begin(),v.end()\n#define sz(a)           (ll)a.size()\n#define F               first\n#define S               second\n#define INF             2000000000000000000\n#define popcount(x)     __builtin_popcountll(x)\n#define pll             pair<ll,ll>\n#define pii             pair<int,int>\n#define ld              long double\n\ntemplate<typename T, typename U> static inline void amin(T &x, U y){ if(y < x) x = y; }\ntemplate<typename T, typename U> static inline void amax(T &x, U y){ if(x < y) x = y; }\n\n#ifdef LOCAL\n#define debug(...) debug_out(#__VA_ARGS__, __VA_ARGS__)\n#else\n#define debug(...) 3000\n#endif\n\nint _runtimeTerror_()\n{\n    int n, Q;\n    cin >> n >> Q;\n    map<int, int> odd, even;\n    vector<int> last_nz(n + 1, 0), last(n + 1, -1), pxor(n + 1, 0);\n    vector<int> a(n + 1);\n    even[0] = 0;\n    int cur = 0;\n    for(int i=1;i<=n;++i) {\n    \tcin >> a[i];\n    \tcur ^= a[i];\n    \tpxor[i] = cur;\n    \tif(a[i] == 0) {\n    \t\tlast_nz[i] = last_nz[i - 1];\n    \t}\n    \telse {\n    \t\tlast_nz[i] = i;\n    \t}\n    \tif(i & 1) {\n    \t\tif(even.count(cur)) {\n    \t\t\tlast[i] = even[cur];\n    \t\t}\n    \t\todd[cur] = i;\n    \t}\n    \telse {\n    \t\tif(odd.count(cur)) {\n    \t\t\tlast[i] = odd[cur];\n    \t\t}\n    \t\teven[cur] = i;\n    \t}\n    }\n    while(Q--) {\n    \tint l, r;\n    \tcin >> l >> r;\n    \tif(pxor[l - 1] != pxor[r]) {\n    \t\tcout << \"-1\\n\";\n    \t}\n    \telse if(last_nz[r] < l) {\n    \t\tcout << \"0\\n\";\n    \t}\n    \telse if(r % 2 == l % 2) {\n    \t\tcout << \"1\\n\";\n    \t}\n    \telse if(a[l] == 0 or a[r] == 0) {\n    \t\tcout << \"1\\n\";\n    \t}\n    \telse if(last[r] >= l) {\n    \t\tcout << \"2\\n\";\n    \t}\n    \telse {\n    \t\tcout << \"-1\\n\";\n    \t}\n    }\n    return 0;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    #ifdef runSieve\n        sieve();\n    #endif\n    #ifdef NCR\n        initncr();\n    #endif\n    int TESTS = 1;\n    //cin >> TESTS;\n    while(TESTS--) {\n        _runtimeTerror_();\n    }\n    return 0;\n}\t \t",
    "tags": [
      "binary search",
      "bitmasks",
      "constructive algorithms",
      "data structures"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1747",
    "index": "E",
    "title": "List Generation",
    "statement": "For given integers $n$ and $m$, let's call a pair of arrays $a$ and $b$ of integers \\textbf{good}, if they satisfy the following conditions:\n\n- $a$ and $b$ have the same length, let their length be $k$.\n- $k \\ge 2$ and $a_1 = 0, a_k = n, b_1 = 0, b_k = m$.\n- For each $1 < i \\le k$ the following holds: $a_i \\geq a_{i - 1}$, $b_i \\geq b_{i - 1}$, and $a_i + b_i \\neq a_{i - 1} + b_{i - 1}$.\n\nFind the sum of $|a|$ over all good pairs of arrays $(a,b)$. Since the answer can be very large, output it modulo $10^9 + 7$.",
    "tutorial": "Change your point of view from array to grid. Think of pair of arrays as paths in grid of size $(n + 1) \\times (m + 1)$. First try counting number of good pair of arrays. Number of good pairs of arrays comes out to be $\\sum\\limits_{k = 0}{k = \\min(n,m} \\binom{n}{k} \\cdot \\binom{m}{k} \\cdot 2^{n + m - k - 1}$ Given problem is equivalent to: You are currently at cell $(0,0)$. From any cell $(x,y)$ you can jump to cell $(x',y')$ such that $x \\leq x' \\leq n$ , $y \\leq y' \\leq m$ and $(x,y) \\neq (x',y')$. Find sum of number of visited cells over all paths starting from $(0,0)$ and ending at $(n,m)$. Denote the required value by $f(n,m)$. Directly thinking in $2$ dimensions is difficult, lets first solve for case when $n = 0$ or $m = 0$. WLOG, assuming $m = 0$. We can solve this case using some binomials. $f(n,0) = 2^{n - 1} \\cdot \\frac{n + 3}{2}$, $n \\gt 0$. Now, we can divide all possible paths from $(0,0)$ to $(n,m)$ into several classes of one dimensional paths. These classes are defined by what I call breakpoints. When we passes the breakpoint we turns right. Hence we can group paths by fixing the number of breakpoints. WLOG, Assuming $n \\geq m$. For $k$ breakpoints there are $\\binom{n}{k} \\cdot \\binom{m}{k}$ ways to select for $0 \\leq k \\leq m$. For a path with $k$ breakpoints, $n + m - k$ points are optional, that is there will exist $2^{n + m - k}$ paths with $k$ breakpoints. It is not difficult to see that sum of number of visited cells over paths with $k$ breakpoints turned out to be $f(n + m - k,0) + 2^{n + m - k - 1}\\cdot k$. Hence we can write $f(n,m) = \\sum\\limits_{k = 0}^{m} \\binom{n}{k} \\cdot \\binom{m}{k} \\cdot (f(n + m - k,0) + 2^{n + m - k - 1}\\cdot k)$ Time complexity of the solution would be $\\mathcal{O}(\\min(n,m))$",
    "code": "// Jai Shree Ram  \n  \n#include<bits/stdc++.h>\nusing namespace std;\n\n#define rep(i,a,n)     for(int i=a;i<n;i++)\n#define ll             long long\n#define int            long long\n#define pb             push_back\n#define all(v)         v.begin(),v.end()\n#define endl           \"\\n\"\n#define x              first\n#define y              second\n#define gcd(a,b)       __gcd(a,b)\n#define mem1(a)        memset(a,-1,sizeof(a))\n#define mem0(a)        memset(a,0,sizeof(a))\n#define sz(a)          (int)a.size()\n#define pii            pair<int,int>\n#define hell           1000000007\n#define elasped_time   1.0 * clock() / CLOCKS_PER_SEC\n\n\n\ntemplate<typename T1,typename T2>istream& operator>>(istream& in,pair<T1,T2> &a){in>>a.x>>a.y;return in;}\ntemplate<typename T1,typename T2>ostream& operator<<(ostream& out,pair<T1,T2> a){out<<a.x<<\" \"<<a.y;return out;}\ntemplate<typename T,typename T1>T maxs(T &a,T1 b){if(b>a)a=b;return a;}\ntemplate<typename T,typename T1>T mins(T &a,T1 b){if(b<a)a=b;return a;}\n\n\nconst int MOD = hell;\n \nstruct mod_int {\n    int val;\n \n    mod_int(long long v = 0) {\n        if (v < 0)\n            v = v % MOD + MOD;\n \n        if (v >= MOD)\n            v %= MOD;\n \n        val = v;\n    }\n \n    static int mod_inv(int a, int m = MOD) {\n        int g = m, r = a, x = 0, y = 1;\n \n        while (r != 0) {\n            int q = g / r;\n            g %= r; swap(g, r);\n            x -= q * y; swap(x, y);\n        }\n \n        return x < 0 ? x + m : x;\n    }\n \n    explicit operator int() const {\n        return val;\n    }\n \n    mod_int& operator+=(const mod_int &other) {\n        val += other.val;\n        if (val >= MOD) val -= MOD;\n        return *this;\n    }\n \n    mod_int& operator-=(const mod_int &other) {\n        val -= other.val;\n        if (val < 0) val += MOD;\n        return *this;\n    }\n \n    static unsigned fast_mod(uint64_t x, unsigned m = MOD) {\n           #if !defined(_WIN32) || defined(_WIN64)\n                return x % m;\n           #endif\n           unsigned x_high = x >> 32, x_low = (unsigned) x;\n           unsigned quot, rem;\n           asm(\"divl %4\\n\"\n            : \"=a\" (quot), \"=d\" (rem)\n            : \"d\" (x_high), \"a\" (x_low), \"r\" (m));\n           return rem;\n    }\n \n    mod_int& operator*=(const mod_int &other) {\n        val = fast_mod((uint64_t) val * other.val);\n        return *this;\n    }\n \n    mod_int& operator/=(const mod_int &other) {\n        return *this *= other.inv();\n    }\n \n    friend mod_int operator+(const mod_int &a, const mod_int &b) { return mod_int(a) += b; }\n    friend mod_int operator-(const mod_int &a, const mod_int &b) { return mod_int(a) -= b; }\n    friend mod_int operator*(const mod_int &a, const mod_int &b) { return mod_int(a) *= b; }\n    friend mod_int operator/(const mod_int &a, const mod_int &b) { return mod_int(a) /= b; }\n \n    mod_int& operator++() {\n        val = val == MOD - 1 ? 0 : val + 1;\n        return *this;\n    }\n \n    mod_int& operator--() {\n        val = val == 0 ? MOD - 1 : val - 1;\n        return *this;\n    }\n \n    mod_int operator++(int32_t) { mod_int before = *this; ++*this; return before; }\n    mod_int operator--(int32_t) { mod_int before = *this; --*this; return before; }\n \n    mod_int operator-() const {\n        return val == 0 ? 0 : MOD - val;\n    }\n \n    bool operator==(const mod_int &other) const { return val == other.val; }\n    bool operator!=(const mod_int &other) const { return val != other.val; }\n \n    mod_int inv() const {\n        return mod_inv(val);\n    }\n \n    mod_int pow(long long p) const {\n        assert(p >= 0);\n        mod_int a = *this, result = 1;\n \n        while (p > 0) {\n            if (p & 1)\n                result *= a;\n \n            a *= a;\n            p >>= 1;\n        }\n \n        return result;\n    }\n \n    friend ostream& operator<<(ostream &stream, const mod_int &m) {\n        return stream << m.val;\n    }\n    friend istream& operator >> (istream &stream, mod_int &m) {\n        return stream>>m.val;   \n    }\n};\n#define NCR\nconst int N = 5e6 + 5;\nmod_int fact[N],inv[N],invv[N];\nvoid init(int n=N){\n\tfact[0]=inv[0]=inv[1]=1;\n        invv[0] = invv[1] = 1;\n\trep(i,1,N)fact[i]=i*fact[i-1];\n\trep(i,2,N){\n        invv[i] = (MOD - MOD/i)*invv[MOD % i];\n        inv[i] = invv[i]*inv[i - 1];\n    }\n}\nmod_int C(int n,int r){\n\tif(r>n || r<0)return 0;\n\treturn fact[n]*inv[n-r]*inv[r];\n}\n\nint solve(){\n \t\tint n,m; cin >> n >> m;\n \t\tif(m > n)swap(n,m);\n \t\tauto brute = [&](){\n \t\t\tvector<vector<mod_int>>dp(n + 1,vector<mod_int>(m + 1));\n \t\t\tvector<vector<mod_int>>exp(n + 1,vector<mod_int>(m + 1));\n \t\t\tdp[0][0] = 1;\n \t\t\texp[0][0] = 0;\n \t\t\tfor(int i = 0; i <= n; i++){\n \t\t\t\tfor(int j = 0; j <= m; j++){\n \t\t\t\t\tif(i + j == 0)continue;\n \t\t\t\t\tfor(int x = 0; x <= i; x++){\n \t\t\t\t\t\tfor(int y = 0; y <= j; y++){\n \t\t\t\t\t\t\tif(x + y == i + j)continue;\n \t\t\t\t\t\t\tdp[i][j] += dp[x][y];\n \t\t\t\t\t\t\texp[i][j] += (exp[x][y] + dp[x][y]);\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t\treturn exp[n][m] + dp[n][m];\n \t\t};\n \t\tauto correct = [&](){\n                        mod_int in = mod_int(2).inv();\n \t\t\tauto d = [&](int x){\n \t\t\t\tmod_int val = x + 1;\n \t\t\t\treturn val * in;\n \t\t\t};\n \t\t\tmod_int ans = 0;\n                        mod_int pw = mod_int(2).pow(n + m);\n \t\t\tfor(int i = 0; i <= m; i++){\n                                pw *= in;\n \t\t\t\tans += C(n,i)*C(m,i)*pw*(i + d(n + m - i) + 1);\n \t\t\t}\n \t\t\treturn ans;\n \t\t};\n \t\tcout << correct() << endl;\n\n return 0;\n}\nsigned main(){\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    //freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #ifdef SIEVE\n    sieve();\n    #endif\n    #ifdef NCR\n    init();\n    #endif\n    int t=1;cin>>t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}\n ",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1748",
    "index": "A",
    "title": "The Ultimate Square",
    "statement": "You have $n$ rectangular wooden blocks, which are numbered from $1$ to $n$. The $i$-th block is $1$ unit high and $\\lceil \\frac{i}{2} \\rceil$ units long.\n\nHere, $\\lceil \\frac{x}{2} \\rceil$ denotes the result of division of $x$ by $2$, rounded \\textbf{up}. For example, $\\lceil \\frac{4}{2} \\rceil = 2$ and $\\lceil \\frac{5}{2} \\rceil = \\lceil 2.5 \\rceil = 3$.\n\nFor example, if $n=5$, then the blocks have the following sizes: $1 \\times 1$, $1 \\times 1$, $1 \\times 2$, $1 \\times 2$, $1 \\times 3$.\n\n\\begin{center}\n{\\small The available blocks for $n=5$}\n\\end{center}\n\nFind the maximum possible side length of a square you can create using these blocks, \\textbf{without rotating any of them}. Note that you don't have to use all of the blocks.\n\n\\begin{center}\n{\\small One of the ways to create $3 \\times 3$ square using blocks $1$ through $5$}\n\\end{center}",
    "tutorial": "If $n$ is odd, it is possible to create a square using all $n$ blocks. If $n$ is even, it is possible to create a square using only the first $n-1$ blocks, since $n-1$ is odd. Can we use the last block to create a larger square? If $n$ is odd, let $k=\\frac{n+1}{2}$ be the width of the last block. It is possible to create a square of side length $k$ using every block as follows: Line $1$ contains a $1 \\times k$ block; Line $2$ contains a $1 \\times 1$ block and a $1 \\times (k-1)$ block; Line $3$ contains a $1 \\times 2$ block and a $1 \\times (k-2)$ block; $\\ldots$ Line $i$ contains a $1 \\times (i-1)$ block and a $1 \\times (k-i+1)$ block; $\\ldots$ Line $k$ contains a $1 \\times (k-1)$ block and a $1 \\times 1$ block. Since the area of this square is $k^2$, and the $n+1$-th block has a width of $k$ tiles, the total area of the first $n+1$ blocks is equal to $k^2+k \\lt (k+1)^2$. Therefore, the answer for $n+1$ is also $k$. In conclusion, the answer for each testcase is $\\lfloor \\frac{n+1}{2} \\rfloor$. Time complexity per testcase: $O(1)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nvoid testcase(){\n    ll n;\n    cin>>n;\n    cout<<(n+1)/2<<'\\n';\n}\nint main()\n{\n    ll t; cin>>t; while(t--)\n       testcase();\n    return 0;\n}\n",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1748",
    "index": "B",
    "title": "Diverse Substrings",
    "statement": "A non-empty digit string is diverse if the number of occurrences of each character in it doesn't exceed the number of distinct characters in it.\n\nFor example:\n\n- string \"7\" is diverse because 7 appears in it $1$ time and the number of distinct characters in it is $1$;\n- string \"77\" is \\textbf{not} diverse because 7 appears in it $2$ times and the number of distinct characters in it is $1$;\n- string \"1010\" is diverse because both 0 and 1 appear in it $2$ times and the number of distinct characters in it is $2$;\n- string \"6668\" is \\textbf{not} diverse because 6 appears in it $3$ times and the number of distinct characters in it is $2$.\n\nYou are given a string $s$ of length $n$, consisting of only digits $0$ to $9$. Find how many of its $\\frac{n(n+1)}{2}$ substrings are diverse.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nNote that if the same diverse string appears in $s$ multiple times, each occurrence should be counted independently. For example, there are two diverse substrings in \"77\" both equal to \"7\", so the answer for the string \"77\" is $2$.",
    "tutorial": "What is the maximum number of distinct characters in a diverse string? What is the maximum frequency of a character in a diverse string? What is the maximum possible length a diverse string? In a diverse string, there are at most $10$ distinct characters: '0', '1', $\\ldots$, '9'. Therefore, each of these characters can appear at most $10$ times in a diverse string. With all this in mind, the maximum possible length of a diverse string is $10^2=100$. To solve this problem, we only need to check whether each substring of length $l \\le 100$ is diverse. Time complexity per testcase: $O(n \\cdot 10^2)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nvoid tc(){\n    ll n;\n    string s;\n    cin>>n>>s;\n    ll ans=0;\n\n    for(ll i=0;i<s.size();i++){\n\n        int fr[10]{}, distinct=0, max_freq=0;\n\n        for(ll j=i;j<s.size() && (++fr[s[j]-'0'])<=10;j++){\n\n            max_freq=max(max_freq,fr[s[j]-'0']);\n            if(fr[s[j]-'0']==1) distinct++;\n\n            if(distinct>=max_freq) ans++;\n        }\n    }\n    cout<<ans<<'\\n';\n}\nint main()\n{\n\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    ll t; cin>>t; while(t--) tc();\n    return 0;\n}\n\n",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1748",
    "index": "C",
    "title": "Zero-Sum Prefixes",
    "statement": "The score of an array $v_1,v_2,\\ldots,v_n$ is defined as the number of indices $i$ ($1 \\le i \\le n$) such that $v_1+v_2+\\ldots+v_i = 0$.\n\nYou are given an array $a_1,a_2,\\ldots,a_n$ of length $n$. You can perform the following operation multiple times:\n\n- select an index $i$ ($1 \\le i \\le n$) such that $a_i=0$;\n- then replace $a_i$ by an arbitrary integer.\n\nWhat is the maximum possible score of $a$ that can be obtained by performing a sequence of such operations?",
    "tutorial": "What is the answer if $a_1=0$ and $a_i \\neq 0$ for all $2 \\le i \\le n$? What is the answer if $a_i=0$ and $a_j \\neq 0$ for all $1 \\le j \\le n$, $j \\neq i$? What is the answer if there are only two indices $i$ and $j$ for which $a_i=a_j=0$? Let's consider the prefix sum array $s=[a_1,a_1+a_2,\\ldots,a_1+a_2+\\ldots+a_n]$. For every index $i$ such that $a_i=0$, if we change the value of $a_i$ to $x$, then every element from the suffix $[s_i,s_{i+1},\\ldots,s_n]$ will be increased by $x$. Therefore, if $a_{i_1}=a_{i_2}=\\ldots=a_{i_k}=0$, we'll partition array $s$ into multiple subarrays: $[s_1,s_2,\\ldots,s_{i_1-1}]$; $[s_{i_1},s_{i_1+1},\\ldots,s_{i_2-1}]$; $[s_{i_2},s_{i_2+1},\\ldots,s_{i_3-1}]$; $\\ldots$ $[s_{i_k},s_{i_{k+1}},\\ldots,s_n]$; Since none of the elements from the first subarray can be changed, it will contribute with the number of occurences of $0$ in $[s_1,s_2,\\ldots,s_{i_1-1}]$ towards the final answer. For each of the other subarrays $[s_l,s_{l+1},\\ldots,s_r]$, let $x$ be the most frequent element in the subarray, appearing $fr[x]$ times. Since $a_l=0$, we can change the value of $a_l$ to $-x$. In this case, every $x$ in this subarray will become equal to $0$, and our current subarray will contribute with $fr[x]$ towards the final answer. Time complexity per testcase: $O(NlogN)$",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nconst ll MAXN=2e5+5;\n\nll a[MAXN];\nmap<ll,ll> freq;\n\nvoid tc(){\n    ll n;\n    cin>>n;\n    ll maxfr=0,current_sum=0,ans=0;\n    bool found_wildcard=0;\n    freq.clear();\n    for(ll i=0;i<n;i++){\n        cin>>a[i];\n\n        if(a[i]==0){\n\n            if(found_wildcard) ans+=maxfr;\n            else ans+=freq[0];\n\n            found_wildcard=1;\n\n            maxfr=0,freq.clear();\n        }\n\n        current_sum+=a[i];\n        maxfr=max(maxfr,++freq[current_sum]);\n    }\n    if(found_wildcard) ans+=maxfr;\n    else ans+=freq[0];\n\n    cout<<ans<<'\\n';\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false), cin.tie(0);\n    ll t; cin>>t; while(t--)\n        tc();\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1748",
    "index": "D",
    "title": "ConstructOR ",
    "statement": "You are given three integers $a$, $b$, and $d$. Your task is to find any integer $x$ which satisfies all of the following conditions, or determine that no such integers exist:\n\n- $0 \\le x \\lt 2^{60}$;\n- $a|x$ is divisible by $d$;\n- $b|x$ is divisible by $d$.\n\nHere, $|$ denotes the bitwise OR operation.",
    "tutorial": "If at least one of $a$ and $b$ is odd, and $d$ is even, then there are no solutions. Without loss of generality, we will only consider the case when $a$ is odd and $d$ is even. Since the last bit of $a$ is $1$, then the last bit of $a|x$ must also be $1$. Therefore, $a|x$ cannot be a multiple of $d$, as $a|x$ is odd, while $d$ is even. Note that there are more cases in which no solutions exist, however they are more generalised versions of this case. If a triplet ($a,b,d$) has no solutions, then ($a\\cdot 2,b\\cdot 2,d\\cdot 2$) has no solutions as well. Combined with the first hint, we can say that a triplet ($a,b,d$) has no solutions if $min(\\text{lsb}(a),\\text{lsb}(b)) \\lt \\text{lsb}(d)$. Here, $\\text{lsb}(x)$ represents the least significant bit of $x$. Since both $a|x$ and $b|x$ must be divisible by $d$, it's better to choose an $x$ such that $a|x=b|x=x$. If $d$ is odd, since $a,b \\lt 2^{30}$, we can ensure that $a|x=b|x=x$ by setting the last $30$ bits of $c$ to $1$. If $d$ is even, then the last $\\text{lsb}(d)$ bits of $x$ should be set to $0$, while the other bits from the last $30$ bits should be set to $1$. Here, $\\text{lsb}(x)$ represents the least significant bit of $x$. Let $k=\\text{lsb}(d)$, where $\\text{lsb}(d)$ represents the least significant bit of $d$. Since $a|x$ and $b|x$ are multiples of $d$, the last $k$ bits of $a$ and $b$ (and also $x$) must be equal to $0$. Otherwise, there are no solutions and we can print $-1$. To simplify the construction process, we will try to find some $x$ such that $a|x=b|x=x$. Since we already know that the last $k$ bits of $a$, $b$ and $x$ are $0$, we will consider that the other $30-k$ of the $30$ least significant bits of $x$ are equal to $1$: $x_{(2)}=p\\text{ }1\\text{ }1\\text{ }1\\text{ }\\ldots\\text{ }1\\text{ }0\\text{ }0\\text{ }\\ldots\\text{ }0$ This gives the following general formula for $x$: $x=2^k \\cdot (p \\cdot 2^{30-k} + (2^{30-k} -1))$ Now, we'll try to find some $p$ for which $x$ is a multiple of $d=2^k \\cdot d'$: $x=2^k \\cdot (p \\cdot 2^{30-k} + (2^{30-k} -1) \\equiv 0 \\mod 2^k \\cdot d' \\Leftrightarrow$ $\\Leftrightarrow (p \\cdot 2^{30-k} + (2^{30-k} -1) \\equiv 0 \\mod d' \\Leftrightarrow$ $\\Leftrightarrow (p+1) \\cdot 2^{30-k} \\equiv 1 \\mod d' \\Leftrightarrow$ $\\Leftrightarrow p+1 \\equiv 2^{k-30} \\mod d' \\Leftrightarrow$ $\\Leftrightarrow p+1 \\equiv (2^{-1})^{30-k} \\mod d' \\Leftrightarrow$ $\\Leftrightarrow p+1 \\equiv (\\frac{d'+1}{2})^{30-k} \\mod d' \\Rightarrow$ $\\Rightarrow p = ((\\frac{d'+1}{2})^{30-k}+d'-1) \\mod d'$ Time complexity per testcase: $O(log d)$ Note that if $a|b$ is already a multiple of $d$, we can consider $x=a|b$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nvoid tc(){\n    ll a,b,d,k=0,inverse_of_2,total_inverse=1;\n    cin>>a>>b>>d;\n    a|=b;\n    if(a%d==0){\n        cout<<a<<'\\n';\n        return;\n    }\n    while(a%2==0 && d%2==0)\n        a/=2,d/=2,k++;\n    inverse_of_2=(d+1)/2;\n    if(a%2==1 && d%2==0){\n        cout<<\"-1\\n\";\n        return;\n    }\n\n    for(ll i=0;i<30-k;i++)\n        total_inverse=total_inverse*inverse_of_2%d;\n\n    cout<<((total_inverse<<(30-k))-1)*(1ll<<k)<<'\\n';\n}\nint main()\n{\n    ios_base::sync_with_stdio(false), cin.tie(0);\n    ll t; cin>>t; while(t--)\n        tc();\n}\n",
    "tags": [
      "bitmasks",
      "chinese remainder theorem",
      "combinatorics",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1748",
    "index": "E",
    "title": "Yet Another Array Counting Problem",
    "statement": "The position of the leftmost maximum on the segment $[l; r]$ of array $x = [x_1, x_2, \\ldots, x_n]$ is the smallest integer $i$ such that $l \\le i \\le r$ and $x_i = \\max(x_l, x_{l+1}, \\ldots, x_r)$.\n\nYou are given an array $a = [a_1, a_2, \\ldots, a_n]$ of length $n$. Find the number of integer arrays $b = [b_1, b_2, \\ldots, b_n]$ of length $n$ that satisfy the following conditions:\n\n- $1 \\le b_i \\le m$ for all $1 \\le i \\le n$;\n- for all pairs of integers $1 \\le l \\le r \\le n$, the position of the leftmost maximum on the segment $[l; r]$ of the array $b$ is equal to the position of the leftmost maximum on the segment $[l; r]$ of the array $a$.\n\nSince the answer might be very large, print its remainder modulo $10^9+7$.",
    "tutorial": "Let $m$ be the position of the leftmost maximum on the segment $[1;n]$. If $l \\le m \\le r$, then the position of the leftmost maximum on the segment $[l;r]$ is equal to $m$. If $l \\le m \\le r$, then the position of the leftmost maximum on the segment $[l;r]$ is equal to $m$. If $l \\le r \\lt m$, then the leftmost maximum on the segment $[l;r]$ is some element $a_p$, $p \\lt m$. If $l \\le r \\lt m$, then the leftmost maximum on the segment $[l;r]$ is some element $a_p$, $p \\lt m$. If $m \\lt l \\le r$, then the leftmost maximum on the segment $[l;r]$ is some element $a_{p_2}$, $p_2 \\gt m$. If $m \\lt l \\le r$, then the leftmost maximum on the segment $[l;r]$ is some element $a_{p_2}$, $p_2 \\gt m$. Let $m$ be the position of the leftmost maximum on the segment $[l;r]$. If $p$ is the position of the leftmost maximum on the segment $[l;m-1]$ and $p_2$ is the position of the leftmost maximum on the segment $[m+1;r]$, then $b_m \\gt b_{p}$ and $b_m \\ge b_{p_2}$. Using the idea from the previous hint, we can recursively build a binary tree where the children of node $m$ are nodes $p$ and $p_2$. Can this problem be boiled down to a tree dp? (Note that $n \\cdot m \\le 10^6$) Let $f(i,j)$ be the position of the leftmost maximum in the interval $(i;j)$, $1 \\le i \\le j \\le n$. Let's consider an interval $(l;r)$ such that $f(l,r)=m$. For the sake of simplicity, let's assume that $l \\lt m \\lt r$. Let $p=f(l,m-1)$ and $p_2=f(m+1,r)$. Since $a_m$ is the leftmost maximum in $(l;r)$, $p \\lt m$ and $p_2 \\gt m$, the following conditions must hold for array $b$: $b_m \\gt b_p$ $b_m \\ge b_{p_2}$ Let's consider a binary tree where the children of node $u=f(l,r)$ are nodes $p=f(l,u-1)$ and $p_2=f(u+1,r)$, for every $1 \\le u \\le n$. Note that if $u=l$, $f(l,l-1)$ is not defined, and, as such, node $u$ will have no left child. Similarly, if $u=r$, then node $u$ will have no right child. Let $dp[u][x]$ be equal to the number of ways to assign values to every element $b_v$ from the subtree rooted in $u$, if $b_u=x$. If $u$ has a left child and $x=1$, then $dp[u][x]=0$; Otherwise, if $u$ has two children, then $dp[u][x]=(\\sum_{i=1}^{x-1}dp[p][i]) \\cdot(\\sum_{i=1}^{x}dp[p_2][i])$; If $u$ only has a left child, then $dp[u][x]=\\sum_{i=1}^{x-1}dp[p][i]$; If $u$ only has a right child, then $dp[u][x]=\\sum_{i=1}^{x}dp[p_2][i]$; If $u$ has no children, then $dp[u][x]=1$. To optimise the transitions, we'll also need to compute $sum[u][x]=\\sum_{i=1}^{x} dp[u][x]$ alongside our normal $dp$. Intended time complexity per testcase: $O(n \\cdot m+n \\cdot log(n))$ In order to construct the binary tree, we can use a recursive divide and conquer function $divide(l,r)$ to split our current interval $(l;r)$ into two new intervals $(l;m-1)$ and $(m+1;r)$. Additionally, we can also compute the values of $dp[m][x]$ and $sum[m][x]$ inside $divide(l,r)$ after calling $divide(l,m-1)$ and divide $(m+1,r)$. Range leftmost maximumum queries can be answered in $O(1)$ using a sparse table, see the model solution for more information.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst ll NMAX=2e5+5,LGMAX=18,MOD=1e9+7;\nint n,m;\n\nint leftmost_maximum[LGMAX][NMAX],msb[NMAX];\nint v[NMAX];\n\nvector<vector<ll>> dp,sum;\n\nint leftmost_maximum_query(int l, int r){\n    int bit=msb[r-l+1];\n    if(v[leftmost_maximum[bit][l]]>=v[leftmost_maximum[bit][r-(1<<bit)+1]]) return leftmost_maximum[bit][l];\n    else return leftmost_maximum[bit][r-(1<<bit)+1];\n}\nint divide(int l, int r){\n\n    if(l>r) return -1;\n\n    int mid=leftmost_maximum_query(l,r);\n\n    int p=divide(l,mid-1),p2=divide(mid+1,r);\n\n    for(int i=1;i<=m;i++){\n        if(p!=-1 && i==1) dp[mid][1]=0;\n        else dp[mid][i]=(p>=0?sum[p][i-1]:1ll)*(p2>=0?sum[p2][i]:1ll)%MOD;\n\n        sum[mid][i]=(sum[mid][i-1]+dp[mid][i])%MOD;\n    }\n    return mid;\n}\nvoid tc(){\n\n    cin>>n>>m;\n    dp.resize(n),sum.resize(n);\n    for(int i=0;i<n;i++){\n        cin>>v[i];\n\n        leftmost_maximum[0][i]=i;\n\n        dp[i].resize(m+1),sum[i].resize(m+1);\n        for(int j=0;j<=m;j++) dp[i][j]=sum[i][j]=0;\n    }\n\n    for(int bit=1;bit<LGMAX;bit++){\n        for(int i=0;i+(1<<bit)<=n;i++){\n            if(v[leftmost_maximum[bit-1][i]]>=v[leftmost_maximum[bit-1][i+(1<<(bit-1))]])\n                leftmost_maximum[bit][i]=leftmost_maximum[bit-1][i];\n            else\n                leftmost_maximum[bit][i]=leftmost_maximum[bit-1][i+(1<<(bit-1))];\n        }\n    }\n\n    divide(0,n-1);\n\n    cout<<sum[leftmost_maximum_query(0,n-1)][m]<<'\\n';\n}\nint main()\n{\n    for(int i=2;i<NMAX;i++)\n        msb[i]=msb[i-1]+((i&(i-1))==0); /// msb = floor(log2)\n\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    int t; cin>>t; while(t--)\n        tc();\n\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dp",
      "flows",
      "math",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1748",
    "index": "F",
    "title": "Circular Xor Reversal",
    "statement": "You have an array $a_0, a_1, \\ldots, a_{n-1}$ of length $n$. Initially, $a_i = 2^i$ for all $0 \\le i \\lt n$. Note that array $a$ is zero-indexed.\n\nYou want to reverse this array (that is, make $a_i$ equal to $2^{n-1-i}$ for all $0 \\le i \\lt n$). To do this, you can perform the following operation no more than $250\\,000$ times:\n\n- Select an integer $i$ ($0 \\le i \\lt n$) and replace $a_i$ by $a_i \\oplus a_{(i+1)\\bmod n}$.\n\nHere, $\\oplus$ denotes the bitwise XOR operation.\n\nYour task is to find \\textbf{any} sequence of operations that will result in the array $a$ being reversed. It can be shown that under the given constraints, a solution always exists.",
    "tutorial": "How can we perform $a_i=a_i \\oplus a_j$ for any $0 \\le i,j \\lt n$, $i \\neq j$? We can swap the values of $a_i$ and $a_j$ by performing the following sequence of xor assignments: $a_i=a_i \\oplus a_j$; $a_j=a_j \\oplus a_i$; $a_i=a_i \\oplus a_j$; Performing $a_i=a_i \\oplus a_j$ on its own is pretty wasteful, as it requires $4 \\cdot \\text{dist}(i,j) - c$ operations, where $dist(i,j)=(j+n-i) \\mod n$, and $c$ is a constant. If $j=i+3$, can we perform $a_i=a_i \\oplus a_j$ and $a_{i+1}=a_{i+1} \\oplus a_{j-1}$ simultaneously? Building on the idea presented in hint $3$, can we perform the following $\\frac{n}{2}$ xor assignments simultaneously if $n$ is even? $a_0 = a_0 \\oplus a_{n-1}$; $a_1 = a_1 \\oplus a_{n-2}$; $a_2 = a_2 \\oplus a_{n-3}$; $\\ldots$ $a_{\\frac{n}{2}-1} = a_{\\frac{n}{2}-1} \\oplus a_{\\frac{n}{2}}$ The target number of operations for performing all $\\frac{n}{2}$ assignments is $\\frac{n^2}{2}$. Using hints $2$ and $4$, we can already solve the problem if $n$ is even. If $m=dist(i,j) \\gt 0$ and $b_k=a_{(i+k) \\mod n}$, let $f(i,j)$ be a sequence of operations that performs: $b_0 = b_0 \\oplus b_{m}$; $b_1 = b_1 \\oplus b_{m-1}$; $b_2 = b_2 \\oplus b_{m-2}$; $\\ldots$ $b_{\\lfloor\\frac{m-2}{2} \\rfloor } = b_{\\lfloor \\frac{m-1}{2} \\rfloor} \\oplus b_{\\lfloor \\frac{m+2}{2} \\rfloor}$ We can reverse array $a$ by performing $f(0,n-1)$, $f(\\frac{n}{2},\\frac{n}{2}-1)$ and $f(0,n-1)$, in this order. Otherwise, if $n$ is odd, we can perform $f(0,n-1)$, $f(\\frac{n+1}{2},\\frac{n-3}{2})$ and $f(0,n-1)$, in this order. The total number of operations is $3\\cdot \\frac{n^2}{2} \\le 3 \\cdot \\frac{400^2}{2} = 240\\,000 \\lt 250\\,000$. If $m=dist(i,j)=((j+n-i) \\mod n)$, $m \\gt 0$ and $b_k=a_{(i+k) \\mod n}$, let $f(i,j)$ be a sequence of operations that performs: $b_0 = b_0 \\oplus b_{m-1}$; $b_1 = b_1 \\oplus b_{m-2}$; $b_2 = b_2 \\oplus b_{m-3}$; $\\ldots$ $b_{\\lfloor\\frac{m-1}{2} \\rfloor } = b_{\\lfloor \\frac{m-1}{2} \\rfloor} \\oplus b_{\\lfloor \\frac{m+2}{2} \\rfloor}$ If $n$ is even, we can reverse array $a$ by performing $f(0,n-1)$, $f(\\frac{n}{2},\\frac{n}{2}-1)$ and $f(0,n-1)$, in this order. Otherwise, if $n$ is odd, we can perform $f(0,n-1)$, $f(\\frac{n+1}{2},\\frac{n-3}{2})$ and $f(0,n-1)$, in this order. One possible way to construct $f(i,j)$ is as follows: Perform an operation on every $i$ from $m-1$ to $0$: $\\Rightarrow b=[(0..m),(1..m),(2..m)\\ldots,(i..m),\\ldots,b_{m}]$ Perform an operation on every $i$ from $1$ to $m-1$: $\\Rightarrow b=[(0..m),b_1,b_2,\\ldots,b_i,\\ldots,b_{m}]$ Perform an operation on every $i$ from $m-2$ to $1$: $\\Rightarrow b=[(0..m),(1..m-1),(2..m-1),\\ldots,(i..m-1),\\ldots,b_{m-1},b_{m}]$ Perform an operation on every $i$ from $2$ to $m-2$: $\\Rightarrow b=[(0..m),(1..m-1),b_2,b_3,\\ldots,b_i,\\ldots,b_{m-1},b_{m}]$ $\\ldots$ $\\Rightarrow b=[(0..m),(1..m-1),(2..m-2),\\ldots, (i..m-i),(\\lfloor\\frac{m-1}{2}\\rfloor..\\lfloor\\frac{m+2}{2}\\rfloor),b_{\\lfloor\\frac{m+1}{2}\\rfloor},\\ldots,b_j,b_{m-1}]$ The last step is to perform an operation on every $i$ from $0$ to $\\lfloor\\frac{m-2}{2}\\rfloor$: $\\Rightarrow b=[a_0 \\oplus a_{m},a_1 \\oplus a_{m-1},\\ldots,a_i \\oplus a_{m-i},\\ldots,b_{\\lfloor\\frac{m-1}{2}\\rfloor} \\oplus b_{\\lfloor\\frac{m+2}{2}\\rfloor},b_{\\lfloor\\frac{m+1}{2}\\rfloor},\\ldots,b_j,\\ldots,b_{m}]$ Here, $(l..r)$ denotes $b_l \\oplus b_{l+1} \\oplus \\ldots \\oplus b_r$. The number of operations needed for $f(i,j)$ is equal to $m+(m-1)+\\ldots+1+(\\frac{m}{2})=\\frac{m\\cdot(m+1)}{2}+\\frac{m}{2}=\\frac{m^2+2\\cdot m}{2}$, therefore the total number of operations needed to reverse the array is $\\frac{3}{2} \\cdot (m^2+2\\cdot m)$. Since $m \\le n-1$, $\\frac{3}{2} \\cdot (m^2+2\\cdot m) \\le \\frac{3}{2} \\cdot (399^2 + 2\\cdot 399) \\lt 250\\,000$. Time complexity per testcase: $O(N^2)$",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> ans;\nint n;\nvoid add_op(int pos){\n    ans.push_back(pos%n);\n}\nvoid f(int l, int r){\n\n    if(r<l) r+=n;\n\n    int m=r-l,direction=0,start=l;\n    r--;\n    while(l<=r){\n\n        if(direction==0){\n            for(int i=r;i>=l;i--)\n                add_op(i);\n            l++;\n        }\n        else{\n            for(int i=l;i<=r;i++)\n                add_op(i);\n            r--;\n        }\n\n        direction=1-direction;\n    }\n    for(int i=start;i<start+m/2;i++)\n        add_op(i);\n}\nint main()\n{\n    ios_base::sync_with_stdio(false), cin.tie(0);\n    cin>>n;\n\n    f(0,n-1);\n\n    f((n+1)/2,(n-2)/2);\n\n    f(0,n-1);\n\n    cout<<ans.size()<<'\\n';\n\n    for(auto it : ans) cout<<it<<' ';\n}\n",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1749",
    "index": "A",
    "title": "Cowardly Rooks",
    "statement": "There's a chessboard of size $n \\times n$. $m$ rooks are placed on it in such a way that:\n\n- no two rooks occupy the same cell;\n- no two rooks attack each other.\n\nA rook attacks all cells that are in its row or column.\n\nIs it possible to move \\textbf{exactly one} rook (you can choose which one to move) into a different cell so that no two rooks still attack each other? A rook can move into any cell in its row or column if no other rook stands on its path.",
    "tutorial": "First, note that $m$ is always less than or equal to $n$. If there were at least $n+1$ rooks on the board, at least two of them would share a row or a column (by pigeonhole principle). If $m < n$, then there is always at least one free row and at least one free column. You can move any rook into that row or column. Otherwise, all rows and columns are taken, so any move will make two rooks share a row or a column, which is prohibited. Thus, if $m = n$, then it's \"NO\". Otherwise, it's \"YES\". Overall complexity: $O(1)$ per testcase. Alternatively, you could check every rook and every possible move. Overall complexity: $O(m^2 \\cdot n^2)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n    int t;\n    scanf(\"%d\", &t);\n    forn(_, t){\n        int n, m;\n        scanf(\"%d%d\", &n, &m);\n        vector<pair<int, int>> a(m);\n        forn(i, m){\n            scanf(\"%d%d\", &a[i].first, &a[i].second);\n            --a[i].first, --a[i].second;\n        }\n        bool ans = false;\n        forn(i, m) forn(x, n) forn(y, n) if ((x == a[i].first) ^ (y == a[i].second)){\n            bool ok = true;\n            forn(j, m) if (i != j){\n                ok &= x != a[j].first && y != a[j].second;\n            }\n            ans |= ok;\n        }\n        puts(ans ? \"YES\" : \"NO\");\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1749",
    "index": "B",
    "title": "Death's Blessing",
    "statement": "You are playing a computer game. To pass the current level, you have to kill a big horde of monsters. In this horde, there are $n$ monsters standing in the row, numbered from $1$ to $n$. The $i$-th monster has $a_i$ health and a special \"Death's Blessing\" spell of strength $b_i$ attached to it.\n\nYou are going to kill all of them one by one. It takes exactly $h$ seconds to kill a monster with health $h$.\n\nWhen the $i$-th monster dies, it casts its spell that increases the health of its neighbors by $b_i$ (the neighbors of the $j$-th monster in the row are the monsters on places $j - 1$ and $j + 1$. The first and the last monsters have only one neighbor each).\n\nAfter each monster is killed, the row shrinks, so its former neighbors become adjacent to each other (so if one of them dies, the other one is affected by its spell). For example, imagine a situation with $4$ monsters with health $a = [2, 6, 7, 3]$ and spells $b = [3, 6, 0, 5]$. One of the ways to get rid of the monsters is shown below:\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||c||c||c||c||c||c||c||c||c||c||ccl}\n$2$ & $6$ & $7$ & $3$ & \\multirow{2}{*}{$\\xrightarrow{6\\ s}$} & $8$ & $13$ & $3$ & \\multirow{2}{*}{$\\xrightarrow{13\\ s}$} & $8$ & $3$ & \\multirow{2}{*}{$\\xrightarrow{8\\ s}$} & $6$ & \\multirow{2}{*}{$\\xrightarrow{6\\ s}$} & \\multirow{2}{*}{$\\{\\}$} \\\n$3$ & $6$ & $0$ & $5$ & & $3$ & $0$ & $5$ & & $3$ & $5$ & & $5$ & & & \\\n\\end{tabular}\n\n{\\small The first row represents the health of each monster, the second one — the power of the spells.}\n\\end{center}\n\nAs a result, we can kill all monsters in $6 + 13 + 8 + 6$ $=$ $33$ seconds. Note that it's only an example and may not be the fastest way to get rid of the monsters.\n\nWhat is the minimum time required to kill all monsters in the row?",
    "tutorial": "Note that whichever order you choose, the total time will always contain all initial health $a_i$, in other words, any answer will contain $\\sum_{i=1}^{n}{a_i}$ as its part. So the lower the sum of $b_i$ you will add to the answer - the better. Look at some monster $i$. If you kill it while it has both left and right neighbor, it will add $2 \\cdot b_i$ to the answer. If it is the first or the last in the row, it will add just $b_i$. And if it is the last monster, it will add $0$. There can be only one last monster, so any other will add at least $b_i$ to the answer. And for any chosen last monster $l$ you can find the order that gives exactly $b_i$ for all other monsters. For example, you can firstly kill monsters $1, 2, \\dots, (l-1)$, then $n, (n-1), \\dots, (l + 1)$ and, finally, moster $l$. In other words, if the last monster is the $l$-th one, the total answer will be equal to $\\sum_{i=1}^{n}{a_i} + \\sum_{i=1}^{n}{b_i} - b_l$. Since we need to minimize answer, we can choose monster with maximum $b_l$. So, the answer is $\\sum_{i=1}^{n}{a_i} + \\sum_{i=1}^{n}{b_i} - \\max_{i=1}^{n}{b_i}$.",
    "code": "fun main() {\n    repeat(readLine()!!.toInt()) {\n        val n = readLine()!!.toInt()\n        val a = readLine()!!.split(' ').map { it.toLong() }\n        val b = readLine()!!.split(' ').map { it.toLong() }\n\n        println(a.sum() + b.sum() - b.maxOrNull()!!)\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1749",
    "index": "C",
    "title": "Number Game",
    "statement": "Alice and Bob are playing a game. They have an array of positive integers $a$ of size $n$.\n\nBefore starting the game, Alice chooses an integer $k \\ge 0$. The game lasts for $k$ stages, the stages are numbered from $1$ to $k$. During the $i$-th stage, Alice must remove an element from the array that is less than or equal to $k - i + 1$. After that, if the array is not empty, Bob must add $k - i + 1$ to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the $k$-th stage ends and Alice hasn't lost yet, she wins.\n\nYour task is to determine the maximum value of $k$ such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible.",
    "tutorial": "Note that if Bob has increased some element, then Alice can't remove it on the next stages. Obviously, it is more profitable for Bob to \"prohibit\" the smallest element of the array. Using this fact, we can iterate over the value of $k$, and then simulate the game process. To simulate the game, we can maintain the set of elements that Alice can remove. On the $i$-th stage, Alice removes the maximum element $x$, such that $x \\le k - i + 1$, if there are no such elements, then Alice lost. Bob always removes the minimum element of the set. Thus, the complexity of the solution is $O(n^2\\log{n})$ for each test case. There is another possible solution: we can notice that, if Alice wins, Bob will \"prohibit\" the elements on positions $1, 2, \\dots, k-1$ of the sorted array. So, Alice has to delete the next $k$ elements. So, if the segment $[k \\dots 2k-1]$ of the sorted array can be deleted by Alice during the game phases, she wins with this value of $k$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n    int ans = 0;\n    for (int k = 1; k <= n; ++k) {\n      multiset<int> s(a.begin(), a.end());\n      for (int i = 0; i < k; ++i) {\n        auto it = s.upper_bound(k - i);\n        if (it == s.begin()) break;\n        s.erase(--it);\n        if (!s.empty()) {\n          int x = *s.begin();\n          s.erase(s.begin());\n          s.insert(x + k - i);\n        }\n      }\n      if (s.size() + k == n) ans = k;\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "data structures",
      "games",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1749",
    "index": "D",
    "title": "Counting Arrays",
    "statement": "Consider an array $a$ of length $n$ with elements numbered from $1$ to $n$. It is possible to remove the $i$-th element of $a$ if $gcd(a_i, i) = 1$, where $gcd$ denotes the greatest common divisor. After an element is removed, the elements to the right are shifted to the left by one position.\n\nAn array $b$ with $n$ integers such that $1 \\le b_i \\le n - i + 1$ is a \\textbf{removal sequence for the array $a$} if it is possible to remove all elements of $a$, if you remove the $b_1$-th element, then the $b_2$-th, ..., then the $b_n$-th element. For example, let $a = [42, 314]$:\n\n- $[1, 1]$ is a removal sequence: when you remove the $1$-st element of the array, the condition $gcd(42, 1) = 1$ holds, and the array becomes $[314]$; when you remove the $1$-st element again, the condition $gcd(314, 1) = 1$ holds, and the array becomes empty.\n- $[2, 1]$ is not a removal sequence: when you try to remove the $2$-nd element, the condition $gcd(314, 2) = 1$ is false.\n\nAn array is \\textbf{ambiguous} if it has \\textbf{at least two} removal sequences. For example, the array $[1, 2, 5]$ is ambiguous: it has removal sequences $[3, 1, 1]$ and $[1, 2, 1]$. The array $[42, 314]$ is not ambiguous: the only removal sequence it has is $[1, 1]$.\n\nYou are given two integers $n$ and $m$. You have to calculate the number of \\textbf{ambiguous} arrays $a$ such that the length of $a$ is from $1$ to $n$ and each $a_i$ is an integer from $1$ to $m$.",
    "tutorial": "We will calculate the answer by subtracting the number of arrays which have only one removal sequence from the total number of arrays. The latter is very simple - it's just $m^1 + m^2 + \\dots + m^n$. How do we calculate the number of unambiguous arrays? We can always delete the $1$-st element of an array; so, $[1, 1, 1, \\dots, 1]$ is a removal sequence for each array. So, we have to calculate the number of arrays which have no other removal sequences. How do we check if the array has no removal sequences other than $[1, 1, \\dots, 1]$? If, at any time, it's possible to remove some element other than the $1$-st from the array, it creates another removal sequence since we can always complete that sequence. Let's analyze the constraints on each element of the array. $a_1$ can be any integer from $1$ to $m$. $a_2$ should be divisible by $2$ (otherwise, we can remove it on the first step). $a_3$ should be divisible by $3$ (otherwise, we can remove it on the first step) and by $2$ (otherwise, we can remove it on the second step). $a_4$ should be divisible by $2$ and $3$, but not necessarily by $4$ since an element which is divisible by $2$ already has a common divisor with $4$. And so on - using induction, we can show that the $i$-th element should be divisible by $p_1 \\cdot p_2 \\cdot p_3 \\cdot \\dots \\cdot p_k$, where $p_1, p_2, \\dots, p_k$ are all of the primes in $[1, i]$. Obviously, the number of such elements is $\\dfrac{m}{p_1 \\cdot p_2 \\cdot p_3 \\cdot \\dots \\cdot p_k}$. So, we can easily calculate the number of possible elements for each index of the array, and that allows us to count all unambiguous arrays.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}   \n\nint sub(int x, int y)\n{\n    return add(x, -y);\n}   \n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y)\n    {\n        if(y & 1) z = mul(z, x);\n        x = mul(x, x);\n        y >>= 1;\n    }\n    return z;\n}\n\nbool prime(int x)\n{\n    for(int i = 2; i * 1ll * i <= x; i++)\n        if(x % i == 0)\n            return false;\n    return true;    \n}\n\nint main()\n{\n    int n;\n    long long m;\n    cin >> n >> m;\n    int ans = 0;\n    for(int i = 1; i <= n; i++)\n        ans = add(ans, binpow(m % MOD, i));\n    long long cur = 1;\n    int cnt = 1;\n    for(int i = 1; i <= n; i++)\n    {\n        if(cur > m) continue;\n        if(prime(i)) cur *= i;\n        cnt = mul(cnt, (m / cur) % MOD);\n        ans = sub(ans, cnt);\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1749",
    "index": "E",
    "title": "Cactus Wall",
    "statement": "Monocarp is playing Minecraft and wants to build a wall of cacti. He wants to build it on a field of sand of the size of $n \\times m$ cells. Initially, there are cacti in some cells of the field. \\textbf{Note that, in Minecraft, cacti cannot grow on cells adjacent to each other by side — and the initial field meets this restriction}. Monocarp can plant new cacti (they must also fulfil the aforementioned condition). He can't chop down any of the cacti that are already growing on the field — he doesn't have an axe, and the cacti are too prickly for his hands.\n\nMonocarp believes that the wall is complete if there is no path from the top row of the field to the bottom row, such that:\n\n- each two consecutive cells in the path are adjacent by side;\n- no cell belonging to the path contains a cactus.\n\nYour task is to plant the minimum number of cacti to build a wall (or to report that this is impossible).",
    "tutorial": "In order to block any path from the top row to the bottom row, you have to build a path from the left side to the right side consisting of '#'. Since two consecutive cacti in a path cannot be placed side by side, they should be placed diagonally (i.e $(x, y)$ should be followed by $(x \\pm 1, y \\pm 1)$ on the path). So we can rephrase the task as a shortest path problem. The edge weight is $0$ if cactus is already in the cell that corresponds to the end of the edge, and $1$ otherwise. Don't forget that some cells can't contain a cactus, thus be part of a path, because of the cacti initially placed. The shortest path can be found using Dijkstra's or 0-1 BFS algorithm.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9;\n\nint dx[] = {0, 1, 0, -1, 1, 1, -1, -1};\nint dy[] = {1, 0, -1, 0, -1, 1, -1, 1};\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, m;\n    cin >> n >> m;\n    vector<string> s(n);\n    for (auto &it : s) cin >> it;\n    \n    auto in = [&](int x, int y) {\n      return 0 <= x && x < n && 0 <= y && y < m;\n    };\n    \n    auto can = [&](int x, int y) {\n      if (!in(x, y)) return false;\n      for (int i = 0; i < 4; ++i) {\n        int nx = x + dx[i], ny = y + dy[i];\n        if (in(nx, ny) && s[nx][ny] == '#')\n          return false;\n      }\n      return true;\n    };\n    \n    vector<vector<int>> d(n, vector<int>(m, INF)), p(n, vector<int>(m));\n    deque<pair<int, int>> q;\n    for (int i = 0; i < n; ++i) {\n        if (s[i][0] == '#') {\n          d[i][0] = 0;\n          q.push_front({i, 0});\n        } else if (can(i, 0)) {\n          d[i][0] = 1;\n          q.push_back({i, 0});\n        }\n    }\n    \n    while (!q.empty()) {\n      auto [x, y] = q.front();\n      q.pop_front();\n      for (int i = 4; i < 8; ++i) {\n        int nx = x + dx[i], ny = y + dy[i];\n        if (!can(nx, ny)) continue;\n        int w = (s[nx][ny] != '#');\n        if (d[nx][ny] > d[x][y] + w) {\n          d[nx][ny] = d[x][y] + w;\n          p[nx][ny] = i;\n          if (w) q.push_back({nx, ny});\n          else q.push_front({nx, ny});\n        }\n      }\n    }\n    \n    int x = 0, y = m - 1;\n    for (int i = 0; i < n; ++i) if (d[x][y] > d[i][y])\n      x = i;\n    if (d[x][y] == INF) {\n      cout << \"NO\\n\";\n      continue;\n    }\n    while (true) {\n      s[x][y] = '#';\n      int i = p[x][y];\n      if (!i) break;\n      x -= dx[i];\n      y -= dy[i];\n    }\n    cout << \"YES\\n\";\n    for (auto it : s) cout << it << '\\n';\n  }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1749",
    "index": "F",
    "title": "Distance to the Path",
    "statement": "You are given a tree consisting of $n$ vertices. Initially, each vertex has a value $0$.\n\nYou need to perform $m$ queries of two types:\n\n- You are given a vertex index $v$. Print the value of the vertex $v$.\n- You are given two vertex indices $u$ and $v$ and values $k$ and $d$ ($d \\le 20$). You need to add $k$ to the value of each vertex such that the distance from that vertex to the path from $u$ to $v$ is less than or equal to $d$.\n\nThe distance between two vertices $x$ and $y$ is equal to the number of edges on the path from $x$ to $y$. For example, the distance from $x$ to $x$ itself is equal to $0$.\n\nThe distance from the vertex $v$ to some path from $x$ to $y$ is equal to the minimum among distances from $v$ to any vertex on the path from $x$ to $y$.",
    "tutorial": "For the purpose of solving the task, let's choose some root in the tree and introduce another operation to the tree: add $k$ to all vertices that are in the subtree of the given vertex $v$ and on the distance $d$ from $v$. For example, if $d = 0$, it's $v$ itself or if $d = 1$ then it's all children of $v$. Let's $p[v]$ be the parent of vertex $v$, $p^2[v] = p[p[v]]$, $p^3[v] = p[p[p[v]]]$ and so on ($p^0[v] = v$). So, how to perform this operation? Instead of adding $k$ to all vertices in the subtree, we can add $k$ only to the vertex $v$. And when we need to get the answer for some vertex $u$, we will get it from $ans[p^d[u]]$. Of course, since there are different $d$-s, we'll create different arrays $ans_d$ for each possible $d$. So, the answer for the vertex will be equal to $\\sum_{i=0}^{d}{ans_i[p^i[d]]}$. Now, let's discuss how to use the introduced operation to perform the given one. We can make the given operation \"$u$ $v$ $k$ $d$\" using ours in the following way: Let's find $l = lca(u, v)$ using any standard algorithm (binary lifting, for example). Let's split all affected vertices in three groups: subtrees of path $[v, l)$ ($v$ inclusive, $l$ exclusive), subtrees of path $[u, l)$ and subtrees of path $l, p[l], p^2[l], \\dots, p^d[l]$. Note that in such way all affected vertices belong to at least one group. Let's look at group of path $[v, l)$. The lowest vertices are on distance $d$ from $v$, the next \"level\" are on distance $d$ from $p[v]$, the next \"level\" are on distance $d$ from $p^2[v]$ and so on. The last \"level\" we'll consider in this group is the vertices in the subtree of the child of $l$ on distance $d$ from it. In such a way, all we need to do is add $k$ to all $ans_d$ on the path from $[v, l)$. The group of the path $[u, l)$ is handled in the same way. What's left? It's vertices in subtree of $l$ on distances $d, (d-1), \\dots, 0$; in subtree of $p[l]$ on distances $(d-1), (d-2), \\dots, 0$; in subtree of $p^i[l]$ on distances $(d-i), (d-i-1), \\dots, 0$; in subtree of $p^d[l]$ on distance $0$. Note that vertices in subtree of $l$ on distance $d-2$ are included in vertices in subtree of $p[l]$ on distance $d-1$. Analogically, vertices on distance $d-3$ from $l$ are included in vertices on distance $d-2$ from $p[l]$.Moreover, vertices on distance $d-4$ from $l$ are included in \"$d-3$ from $p[l]$\" that are included in \"$d-2$ from $p^2[l]$\" and so on. In other words, all we need to proccess are vertices: in subtree of $l$ on distances $d$ and $(d-1)$, in subtree of $p[l]$ on distances $(d-1)$ and $(d-2)$, in subtree of $p^i[l]$ on distances $(d-i)$ and $(d-i-1)$. In total, it's at most $2d$ operations: \"add $k$ to some vertex $x$\". in subtree of $l$ on distances $d, (d-1), \\dots, 0$; in subtree of $p[l]$ on distances $(d-1), (d-2), \\dots, 0$; in subtree of $p^i[l]$ on distances $(d-i), (d-i-1), \\dots, 0$; in subtree of $p^d[l]$ on distance $0$. Moreover, vertices on distance $d-4$ from $l$ are included in \"$d-3$ from $p[l]$\" that are included in \"$d-2$ from $p^2[l]$\" and so on. In other words, all we need to proccess are vertices: in subtree of $l$ on distances $d$ and $(d-1)$, in subtree of $p[l]$ on distances $(d-1)$ and $(d-2)$, in subtree of $p^i[l]$ on distances $(d-i)$ and $(d-i-1)$. As a result, all we need to do is add $k$ on path from $v$ to some ancestor $l$ of $v$; add $k$ in some vertex $v$ (can be done as operation $1$ on path $[v, p[v])$); ask value in some vertex $v$. In total, complexity is $O(n \\log{n} + m d \\log{n})$ time and $O(n (\\log{n} + d))$ space. P.S.: the second operation can be further optimized to $O(d + \\log{n})$, but it's not really necessary.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nconst int N = int(2e5) + 55;\nconst int LOG = 18;\n\nint n;\nvector<int> g[N];\n\ninline bool read() {\n    if(!(cin >> n))\n        return false;\n    fore (i, 0, n - 1) {\n        int u, v;\n        cin >> u >> v;\n        u--, v--;\n        \n        g[u].push_back(v);\n        g[v].push_back(u);\n    }\n    return true;\n}\n\nint p[LOG][N];\nint tin[N], tout[N], T = 0;\n\nvoid build(int v, int pr) {\n    tin[v] = T++;\n    p[0][v] = pr;\n    fore (pw, 1, LOG)\n        p[pw][v] = p[pw - 1][p[pw - 1][v]];\n    \n    for (int to : g[v]) {\n        if (to == pr)\n            continue;\n        build(to, v);\n    }\n    tout[v] = T;\n}\n\nbool inside(int l, int v) {\n    return tin[l] <= tin[v] && tout[v] <= tout[l];\n}\n\nint lca(int u, int v) {\n    if (inside(u, v))\n        return u;\n    if (inside(v, u))\n        return v;\n    \n    for (int pw = LOG - 1; pw >= 0; pw--) {\n        if (!inside(p[pw][u], v))\n            u = p[pw][u];\n    }\n    return p[0][u];\n}\n\nconst int D = 21;\nstruct Fenwick {\n    int n;\n    vector<int> F;\n    void init(int nn) {\n        n = nn;\n        F.assign(n, 0);\n    }\n    \n    void add(int pos, int val) {\n        for (; pos < n; pos |= pos + 1)\n            F[pos] += val;\n    }\n    int sum(int pos) {\n        int ans = 0;\n        for (; pos >= 0; pos = (pos & (pos + 1)) - 1)\n            ans += F[pos];\n        return ans;\n    }\n    int getSum(int l, int r) {\n        return sum(r - 1) - sum(l - 1);\n    }\n};\n\nstruct DS {\n    Fenwick f;\n    void init(int n) {\n        f.init(n);\n    }\n    \n    void addPath(int v, int l, int k) {\n        f.add(tin[v], +k);\n        f.add(tin[l], -k);\n    }\n    int getVertex(int v) {\n        return f.getSum(tin[v], tout[v]);\n    }\n    \n    void addVertex(int v, int k) {\n        f.add(tin[v], +k);\n        if (p[0][v] != v)\n            f.add(tin[p[0][v]], -k);\n    }\n};\n\nDS t[D];\n\ninline void solve() {\n    fore (i, 0, D) {\n        g[n - 1 + i].push_back(n + i);\n        g[n + i].push_back(n - 1 + i);\n    }\n    int root = n + D - 1;\n    \n    build(root, root);\n    fore (i, 0, D)\n        t[i].init(root + 1);\n    \n    int m; cin >> m;\n    fore(_, 0, m) {\n        int tp; cin >> tp;\n        if (tp == 1) {\n            int v; cin >> v;\n            v--;\n            \n            int ans = 0;\n            for (int i = 0, cur = v; i < D; i++, cur = p[0][cur])\n                ans += t[i].getVertex(cur);\n            cout << ans << endl;\n        } \n        else {\n            assert(tp == 2);\n\n            int u, v, k, d;\n            cin >> u >> v >> k >> d;\n            u--, v--;\n            \n            int l = lca(u, v);\n            \n            if (u != l)\n                t[d].addPath(u, l, k);\n            if (v != l)\n                t[d].addPath(v, l, k);\n            \n            for (int i = 0; i <= d; i++, l = p[0][l]) {\n                t[d - i].addVertex(l, k);\n                if (d - i > 0)\n                    t[d - i - 1].addVertex(l, k);\n            }\n        }\n    }\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1750",
    "index": "A",
    "title": "Indirect Sort",
    "statement": "You are given a permutation $a_1, a_2, \\ldots, a_n$ of size $n$, where each integer from $1$ to $n$ appears \\textbf{exactly once}.\n\nYou can do the following operation any number of times (possibly, zero):\n\n- Choose any three indices $i, j, k$ ($1 \\le i < j < k \\le n$).\n- If $a_i > a_k$, replace $a_i$ with $a_i + a_j$. Otherwise, swap $a_j$ and $a_k$.\n\nDetermine whether you can make the array $a$ sorted in non-descending order.",
    "tutorial": "We claim that we can sort the array if and only if $a_1 = 1$. Necessity We can notice that index $1$ cannot be affected by any swap operation. Let's see what happens to the value $1$. According to the definition of the operation, it can either increase or be swapped. In order to be increased, there must exist some $k$ such that $1 > a_k$, but since $1$ is the minimum possible value, it will never be true as other values in array $a$ can only increse as well. Since index $1$ can not be affected by a swap operation and $a_1>1$, we conclude that if $a_1 \\neq 1$, the answer is No. Sufficiency Let's focus on the second operation. Since we have $a_1 = 1$, we can always choose $i=1$ and the operation then turns into picking some pair $2 \\le j < k \\le n$ and swapping $a_j$ with $a_k$. It's trivial to see we can always sort with such an operation.",
    "code": "\"#include<bits/stdc++.h>\\nusing namespace std;\\nint t,n,a[109];\\ninline int read(){\\n\\tint s = 0,w = 1;\\n\\tchar ch = getchar();\\n\\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\\n\\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\\n\\treturn s * w;\\n}\\nint main(){\\n\\tt = read();\\n\\twhile (t --){\\n\\t\\tn = read();\\n\\t\\tfor (int i = 1;i <= n;i += 1) a[i] = read();\\n\\t\\tputs(a[1] == 1 ? \\\"Yes\\\" : \\\"No\\\");\\n\\t}\\n\\treturn 0;\\n}\\n\"",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1750",
    "index": "B",
    "title": "Maximum Substring",
    "statement": "A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $s$.\n\nFor some non-empty substring$^\\dagger$ $t$ of string $s$ containing $x$ characters 0 and $y$ characters 1, define its cost as:\n\n- $x \\cdot y$, if $x > 0$ and $y > 0$;\n- $x^2$, if $x > 0$ and $y = 0$;\n- $y^2$, if $x = 0$ and $y > 0$.\n\nGiven a binary string $s$ of length $n$, find the maximum cost across all its non-empty substrings.\n\n$^\\dagger$ A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.",
    "tutorial": "Considering that if we want to find the max value of $x \\cdot y$, then the whole string is the best to calculate, for it $0$ s and $1$ s are the max. Then considering $x \\cdot x$ and $y \\cdot y$ : what we need to do is to calculate the max continuous number of $0$ or $1$, compare its square to the first condition, then take the bigger one as the answer.",
    "code": "\"#include <bits/stdc++.h>\\n#define int long long\\nusing namespace std;\\nint32_t main()\\n{\\n\\tcin.tie(nullptr)->ios_base::sync_with_stdio(false);\\n\\tint q;\\n\\tcin >> q;\\n\\twhile (q--)\\n\\t{\\n\\t\\tint n;\\n\\t\\tstring s;\\n\\t\\tcin >> n >> s;\\n\\t\\ts = '$' + s;\\n\\t\\tint cnt0 = 0, cnt1 = 0;\\n\\t\\tfor (int i = 1; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tcnt0 += s[i] == '0';\\n\\t\\t\\tcnt1 += s[i] == '1';\\n\\t\\t}\\n\\t\\tint ans = cnt0 * cnt1;\\n\\t\\tint lg = 1;\\n\\t\\tfor (int i = 2; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tif (s[i] == s[i - 1])\\n\\t\\t\\t{\\n\\t\\t\\t\\tlg++;\\n\\t\\t\\t}\\n\\t\\t\\telse\\n\\t\\t\\t{\\n\\t\\t\\t\\tans = max(ans, lg * lg);\\n\\t\\t\\t\\tlg = 1;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tans = max(ans, lg * lg);\\n\\t\\tcout << ans << '\\\\n';\\n\\t}\\n}\"",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1750",
    "index": "C",
    "title": "Complementary XOR",
    "statement": "You have two binary strings $a$ and $b$ of length $n$. You would like to make all the elements of both strings equal to $0$. Unfortunately, you can modify the contents of these strings using only the following operation:\n\n- You choose two indices $l$ and $r$ ($1 \\le l \\le r \\le n$);\n- For every $i$ that respects $l \\le i \\le r$, change $a_i$ to the opposite. That is, $a_i := 1 - a_i$;\n- For every $i$ that respects either $1 \\le i < l$ or $r < i \\le n$, change $b_i$ to the opposite. That is, $b_i := 1 - b_i$.\n\nYour task is to determine if this is possible, and if it is, to find such an appropriate chain of operations. The number of operations \\textbf{should not exceed} $n + 5$. It can be proven that if such chain of operations exists, one exists with at most $n + 5$ operations.",
    "tutorial": "For each operation, the interval changed by a sequence and b sequence is complementary, so you must judge whether all $[a_i=b_i]$ are the same at the beginning. If they are different, you can't have a solution. Now, if $a = \\neg b$, we can do an operation on $a$ and have $a=b$. Now suppose $a_i=b_i=1$ for some $i$ and try to make $a_i=b_i=0$ without changing anything else. If $i>1$, then this is very simple, we can just do an operation with $(1,i)$ and an operation on $(1,i-1)$. If $i=1$ we can make $(1,n)$ and $(2,n)$. Since $n>1$, this can always be done, thus we found a solution using $2 \\cdot n + O(1)$ operations. To optimize it to only use $n + O(1)$ operations, note that we only care about the parity of the number of operations did at any index.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint main()\\n{\\n\\tcin.tie(nullptr)->sync_with_stdio(false);\\n\\tint q;\\n\\tcin >> q;\\n\\twhile (q--)\\n\\t{\\n\\t\\tint n;\\n\\t\\tstring a, b;\\n\\t\\tcin >> n >> a >> b;\\n\\t\\ta = '$' + a;\\n\\t\\tb = '$' + b;\\n\\t\\tbool ok = true;\\n\\t\\tfor (int i = 1; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tif (a[i] != char('1' - b[i] + '0'))\\n\\t\\t\\t{\\n\\t\\t\\t\\tok = false;\\n\\t\\t\\t\\tbreak;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tok = ok || (a == b);\\n\\t\\tif (!ok)\\n\\t\\t{\\n\\t\\t\\tcout << \\\"NO\\\\n\\\";\\n\\t\\t\\tcontinue;\\n\\t\\t}\\n\\t\\tvector<pair<int, int>> ops;\\n\\t\\tif (a[1] != b[1])\\n\\t\\t{\\n\\t\\t\\tops.push_back({1, n});\\n\\t\\t\\ta = b;\\n\\t\\t}\\n\\t\\tvector<int> cnt(n + 1);\\n\\t\\tfor (int i = 1; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tif (a[i] == '1')\\n\\t\\t\\t{\\n\\t\\t\\t\\tif (i == 1)\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tops.push_back({1, n});\\n\\t\\t\\t\\t\\tops.push_back({2, n});\\n\\t\\t\\t\\t}\\n\\t\\t\\t\\telse\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tcnt[i]++;\\n\\t\\t\\t\\t\\tcnt[i - 1]++;\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor (int i = 1; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tif (cnt[i] % 2 == 1)\\n\\t\\t\\t{\\n\\t\\t\\t\\tops.push_back({1, i});\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tcout << \\\"YES\\\\n\\\"\\n\\t\\t\\t << (int)ops.size() << '\\\\n';\\n\\t\\tfor (auto i : ops)\\n\\t\\t{\\n\\t\\t\\tcout << i.first << ' ' << i.second << '\\\\n';\\n\\t\\t}\\n\\t}\\n}\"",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1750",
    "index": "D",
    "title": "Count GCD",
    "statement": "You are given two integers $n$ and $m$ and an array $a$ of $n$ integers. For each $1 \\le i \\le n$ it holds that $1 \\le a_i \\le m$.\n\nYour task is to count the number of different arrays $b$ of length $n$ such that:\n\n- $1 \\le b_i \\le m$ for each $1 \\le i \\le n$, and\n- $\\gcd(b_1,b_2,b_3,...,b_i) = a_i$ for each $1 \\le i \\le n$.\n\nHere $\\gcd(a_1,a_2,\\dots,a_i)$ denotes the greatest common divisor (GCD) of integers $a_1,a_2,\\ldots,a_i$.\n\nSince this number can be too large, print it modulo $998\\,244\\,353$.",
    "tutorial": "We can notice that if for some $2 \\le i \\le n$, $a_{i-1}$ is not divisible by $a_{i}$, then the answer is $0$. Else, note that all the prime factors of $a_1$ are also prime factors in all the other values. Thus after factorizing $a_1$ we can quickly factorize every other value. Now let's find the number of ways we can select $b_i$ for every $i$. The answer will be the product of these values since each position is independent. It's easy to see that there is only one way to select $b_1$, that is $a_1$. Now for $i > 1$ we need to find the number of values $x$ such that $gcd(a_{i-1},x)=a_i$. Let $x=a_i \\cdot k$, we can rephrase as $gcd( \\frac{a_{i-1}}{a_i} \\cdot a_i, a_i \\cdot k) = a_i$, which is also equivalent to $gcd( \\frac{a_{i-1}}{a_i}, k) = 1$. We have $k \\le \\frac{m}{a_i}$, thus the task reduces to a simple principle of inclusion-exclusion problem. Time complexity $O(2^9 \\cdot 9 \\cdot log + \\sqrt{m})$ per testcase.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint mod = 998244353;\\nstruct Mint\\n{\\n    int val;\\n    Mint(int _val = 0)\\n    {\\n        val = _val % mod;\\n    }\\n    Mint(long long _val = 0)\\n    {\\n        val = _val % mod;\\n    }\\n    Mint operator+(Mint oth)\\n    {\\n        return val + oth.val;\\n    }\\n    Mint operator*(Mint oth)\\n    {\\n        return 1LL * val * oth.val;\\n    }\\n    Mint operator-(Mint oth)\\n    {\\n        return val - oth.val + mod;\\n    }\\n    void operator+=(Mint oth)\\n    {\\n        val = (Mint(val) + oth).val;\\n    }\\n    void operator-=(Mint oth)\\n    {\\n        val = (Mint(val) - oth).val;\\n    }\\n    void operator*=(Mint oth)\\n    {\\n        val = (Mint(val) * oth).val;\\n    }\\n};\\nvector<int> get_primes(int n)\\n{\\n    int d = 2;\\n    vector<int> ans;\\n    while (d * d <= n)\\n    {\\n        bool este = false;\\n        while (n % d == 0)\\n        {\\n            n /= d;\\n            este = true;\\n        }\\n        if (este)\\n        {\\n            ans.push_back(d);\\n        }\\n        d++;\\n    }\\n    if (n != 1)\\n    {\\n        ans.push_back(n);\\n    }\\n    return ans;\\n}\\nint gcd(int a, int b)\\n{\\n    while (b)\\n    {\\n        int c = a % b;\\n        a = b;\\n        b = c;\\n    }\\n    return a;\\n}\\nint main()\\n{\\n    cin.tie(nullptr)->sync_with_stdio(false);\\n    int q;\\n    cin >> q;\\n    while (q--)\\n    {\\n        int n, m;\\n        cin >> n >> m;\\n        vector<int> a(n + 1);\\n        for (int i = 1; i <= n; ++i)\\n        {\\n            cin >> a[i];\\n        }\\n        bool ok = true;\\n        for (int i = 2; i <= n; ++i)\\n        {\\n            if (a[i - 1] % a[i] != 0)\\n            {\\n                ok = false;\\n                break;\\n            }\\n        }\\n        if (!ok)\\n        {\\n            cout << 0 << '\\\\n';\\n            continue;\\n        }\\n        vector<int> factori = get_primes(a[1]);\\n        map<pair<int, int>, int> calculat;\\n        for (int i = 2; i <= n; ++i)\\n        {\\n            calculat[{a[i - 1], a[i]}] = 0;\\n        }\\n        for (auto i : calculat)\\n        {\\n            int left = i.first.first / i.first.second;\\n            int till = m / i.first.second;\\n            vector<int> left_primes;\\n            for (auto i : factori)\\n            {\\n                if (left % i == 0)\\n                {\\n                    left_primes.push_back(i);\\n                }\\n            }\\n            int sz = (int)left_primes.size();\\n            int ans = 0;\\n            for (int mask = 0; mask < (1 << sz); ++mask)\\n            {\\n                int prod = 1;\\n                int cnt = 0;\\n                for (int j = 0; j < sz; ++j)\\n                {\\n                    if (mask & (1 << j))\\n                    {\\n                        prod *= left_primes[j];\\n                        cnt++;\\n                    }\\n                }\\n                if (cnt % 2 == 0)\\n                {\\n                    ans += till / prod;\\n                }\\n                else\\n                {\\n                    ans -= till / prod;\\n                }\\n            }\\n            calculat[i.first] = ans;\\n        }\\n        Mint ans = 1;\\n        for (int i = 2; i <= n; ++i)\\n        {\\n            ans = ans * calculat[{a[i - 1], a[i]}];\\n        }\\n        cout << ans.val << '\\\\n';\\n    }\\n}\"",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1750",
    "index": "E",
    "title": "Bracket Cost",
    "statement": "Daemon Targaryen decided to stop looking like a Metin2 character. He turned himself into the most beautiful thing, a bracket sequence.\n\nFor a bracket sequence, we can do two kind of operations:\n\n- Select one of its substrings$^\\dagger$ and cyclic shift it to the right. For example, after a cyclic shift to the right, \"(())\" will become \")(()\";\n- Insert any bracket, opening '(' or closing ')', wherever you want in the sequence.\n\nWe define the cost of a bracket sequence as the \\textbf{minimum} number of such operations to make it balanced$^\\ddagger$.\n\nGiven a bracket sequence $s$ of length $n$, find the sum of costs across all its $\\frac{n(n+1)}{2}$ non-empty substrings. Note that for each substring we calculate the cost \\textbf{independently}.\n\n$^\\dagger$ A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\n$^\\ddagger$ A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters $+$ and $1$. For example, sequences \"(())()\", \"()\", and \"(()(()))\" are balanced, while \")(\", \"(()\", and \"(()))(\" are not.",
    "tutorial": "Let $a_i=1$ if $s_i=($, $a_i=-1$ if $s_i=)$ and $b_i$ be the prefix sum of $a_i$. Theorem: the cost of $s[l+1,r]$ is $max(b_l,b_r)-min(b_l,b_{l+1},...,b_r)$ Necessity: after one operation, $max(b_l,b_r)-min(b_l,b_{l+1},...,b_r)$ decrease at most one. Sufficiency: If $b_l<b_r$, we can do operation 2, add a right bracket at the end of string. If $b_l>b_r$, we can do operation 2, add a left bracket at the beginning of string. If $b_l=b_r$, assume x be the largest x that $b_x=min(b_l,b_{l+1},...,b_r)$, then $s_{x+1}=($, so we can do operation 1, cyclic shift $s[l,x+1]$ to right. Under any condition, $max(b_l,b_r)-min(b_l,b_{l+1},...,b_r)$ decrease one after one operation. We can use binary index tree to calculate $max(b_l,b_r)$ and $min(b_l,b_{l+1},...,b_r)$.",
    "code": "\"#include <bits/stdc++.h>\\n#define int long long\\nusing namespace std;\\nstruct bit\\n{\\n\\tvector<int> a;\\n\\tvoid resize(int n)\\n\\t{\\n\\t\\ta = vector<int>(n + 1);\\n\\t}\\n\\tvoid update(int pos, int val)\\n\\t{\\n\\t\\tint n = (int)a.size() - 1;\\n\\t\\tfor (int i = pos; i <= n; i += i & (-i))\\n\\t\\t{\\n\\t\\t\\ta[i] += val;\\n\\t\\t}\\n\\t}\\n\\tint query(int pos)\\n\\t{\\n\\t\\tint ans = 0;\\n\\t\\tfor (int i = pos; i; i -= i & (-i))\\n\\t\\t{\\n\\t\\t\\tans += a[i];\\n\\t\\t}\\n\\t\\treturn ans;\\n\\t}\\n\\tint query(int st, int dr)\\n\\t{\\n\\t\\treturn query(dr) - query(st - 1);\\n\\t}\\n};\\nint32_t main()\\n{\\n\\tcin.tie(nullptr)->ios_base::sync_with_stdio(false);\\n\\tint q;\\n\\tcin >> q;\\n\\twhile (q--)\\n\\t{\\n\\t\\tint n;\\n\\t\\tstring s;\\n\\t\\tcin >> n >> s;\\n\\t\\ts = '$' + s;\\n\\t\\tvector<int> pref(n + 1);\\n\\t\\tfor (int i = 1; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tpref[i] = pref[i - 1] + (s[i] == ')' ? -1 : 1);\\n\\t\\t}\\n\\t\\tvector<int> dp(n + 2);\\n\\t\\tstack<int> paranteze;\\n\\t\\tfor (int i = n; i >= 1; --i)\\n\\t\\t{\\n\\t\\t\\tif (s[i] == '(')\\n\\t\\t\\t{\\n\\t\\t\\t\\tif (!paranteze.empty())\\n\\t\\t\\t\\t{\\n\\t\\t\\t\\t\\tdp[i] = dp[paranteze.top() + 1];\\n\\t\\t\\t\\t\\tparanteze.pop();\\n\\t\\t\\t\\t}\\n\\t\\t\\t}\\n\\t\\t\\telse\\n\\t\\t\\t{\\n\\t\\t\\t\\tdp[i] = dp[i + 1] + (n - i + 1);\\n\\t\\t\\t\\tparanteze.push(i);\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tint ans = 0;\\n\\t\\tfor (int i = 1; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tans += dp[i];\\n\\t\\t}\\n\\t\\tmap<int, int> norm;\\n\\t\\tvector<int> lesgo = pref;\\n\\t\\tsort(lesgo.begin(), lesgo.end());\\n\\t\\tint p = 1;\\n\\t\\tfor (int i = 0; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tif (norm.find(lesgo[i]) == norm.end())\\n\\t\\t\\t{\\n\\t\\t\\t\\tnorm[lesgo[i]] = p++;\\n\\t\\t\\t}\\n\\t\\t}\\n\\t\\tfor (int i = 0; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tlesgo[i] = norm[pref[i]];\\n\\t\\t}\\n\\t\\tp--;\\n\\t\\tbit tree;\\n\\t\\ttree.resize(p);\\n\\t\\tfor (int i = 0; i <= n; ++i)\\n\\t\\t{\\n\\t\\t\\tans += tree.query(1, lesgo[i]) * pref[i];\\n\\t\\t\\ttree.update(lesgo[i], 1);\\n\\t\\t}\\n\\t\\ttree.resize(p);\\n\\t\\tfor (int i = n; i >= 0; --i)\\n\\t\\t{\\n\\t\\t\\tans += tree.query(lesgo[i], p) * -pref[i];\\n\\t\\t\\ttree.update(lesgo[i], 1);\\n\\t\\t}\\n\\t\\tcout << ans << '\\\\n';\\n\\t}\\n}\"",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1750",
    "index": "F",
    "title": "Majority",
    "statement": "Everyone was happy coding, until suddenly a power shortage happened and the best competitive programming site went down. Fortunately, a system administrator bought some new equipment recently, including some UPSs. Thus there are some servers that are still online, but we need all of them to be working in order to keep the round rated.\n\nImagine the servers being a binary string $s$ of length $n$. If the $i$-th server is online, then $s_i = 1$, and $s_i = 0$ otherwise.\n\nA system administrator can do the following operation called electricity spread, that consists of the following phases:\n\n- Select two servers at positions $1 \\le i < j \\le n$ such that both are online (i.e. $s_i=s_j=1$). The spread starts only from online servers.\n- Check if we have enough power to make the spread. We consider having enough power if the number of turned on servers in range $[i, j]$ is at least the number of turned off servers in range $[i, j]$. More formally, check whether $2 \\cdot (s_i + s_{i+1} + \\ldots + s_j) \\ge j - i + 1$.\n- If the check is positive, turn on all the offline servers in range $[i, j]$. More formally, make $s_k := 1$ for all $k$ from $i$ to $j$.\n\nWe call a binary string $s$ of length $n$ rated if we can turn on all servers (i.e. make $s_i = 1$ for $1 \\le i \\le n$) using the electricity spread operation any number of times (possibly, $0$). Your task is to find the number of rated strings of length $n$ modulo $m$.",
    "tutorial": "First off, let's try to reduce the given operation to a simpler form. We claim that if it is possible to make the string $111...111$ using the specified operation, we can make it $111...111$ by doing the following new operation : Select two indices $(i,j)$ such that the substring $s_{i...j}$ looks like this $111..100...001...111$ and make it all one. The proof is just to show that if we can perform operation $(i,j)$, then it must exist some substring of $s_{i...j}$ respecting the propriety of the new operation. Let $dp_{i,j}$ be the number of binary strings of length $i$ that in the final form ( after no more operations can be made ) begin with a prefix full of ones of length $j$. For transitions, we have to iterate through the length of the next $0$ sequence and the length of the fixable prefix right after it ( such that we cannot perform an operation to make a bigger prefix, because that would break the definition ), but there is one problem -- we cannot compute $dp_{i,i}$ using any recurrence relation. Fortunately, we can compute it by subtracting the ways we get roadblocks, because, by definition $dp_{i,i}$ can be turned into $111...111$ which doesn't have any roadblocks at all. This is $O(n^4)$ if implemented naively, but one can optimize it to $O(n^2)$ by keeping prefix sums over prefix sums.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint p2[5001], dp[5001][5001], sum[5001][5001], sum2[5001][5001];\\nint32_t main()\\n{\\n    int n, mod;\\n    cin >> n >> mod;\\n    p2[0] = 1;\\n    for (int i = 1; i <= n; ++i)\\n    {\\n        p2[i] = p2[i - 1] + p2[i - 1];\\n        if (p2[i] >= mod)\\n        {\\n            p2[i] -= mod;\\n        }\\n    }\\n    dp[1][1] = 1;\\n    for (int j = 1; j <= n; ++j)\\n    {\\n        sum[1][j] = 1;\\n        sum2[1][j] = 1;\\n    }\\n    for (int i = 2; i <= n; ++i)\\n    {\\n        for (int j = 1; j <= i; ++j)\\n        {\\n            if (i == j)\\n            {\\n                dp[i][j] = p2[i - 2];\\n                for (int k = 1; k < i; ++k)\\n                {\\n                    dp[i][j] -= dp[i][k];\\n                    if (dp[i][j] < 0)\\n                    {\\n                        dp[i][j] += mod;\\n                    }\\n                }\\n                continue;\\n            }\\n            int lg = j + 1;\\n            if (i - j - lg >= 0)\\n            {\\n                dp[i][j] = (1ll * dp[j][j] * sum2[i - j - lg][lg - j - 1]) % mod;\\n            }\\n        }\\n        for (int j = 1; j <= i; ++j)\\n        {\\n            sum[i][j] = sum[i][j - 1] + dp[i][j];\\n            if (sum[i][j] >= mod)\\n            {\\n                sum[i][j] -= mod;\\n            }\\n        }\\n        for (int j = i + 1; j <= n; ++j)\\n        {\\n            sum[i][j] = sum[i][j - 1];\\n        }\\n        for (int j = 0; j <= n; ++j)\\n        {\\n            sum2[i][j] = sum[i][j];\\n            if (j + 1 <= n)\\n            {\\n                sum2[i][j] += sum2[i - 1][j + 1];\\n                if (sum2[i][j] >= mod)\\n                {\\n                    sum2[i][j] -= mod;\\n                }\\n            }\\n        }\\n    }\\n    cout << dp[n][n];\\n}\"",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1750",
    "index": "G",
    "title": "Doping",
    "statement": "We call an array $a$ of length $n$ fancy if for each $1 < i \\le n$ it holds that $a_i = a_{i-1} + 1$.\n\nLet's call $f(p)$ applied to a permutation$^\\dagger$ of length $n$ as the \\textbf{minimum} number of subarrays it can be partitioned such that each one of them is fancy. For example $f([1,2,3]) = 1$, while $f([3,1,2]) = 2$ and $f([3,2,1]) = 3$.\n\nGiven $n$ and a permutation $p$ of length $n$, we define a permutation $p'$ of length $n$ to be $k$-special if and only if:\n\n- $p'$ is lexicographically smaller$^\\ddagger$ than $p$, and\n- $f(p') = k$.\n\nYour task is to count for each $1 \\le k \\le n$ the number of $k$-special permutations modulo $m$.\n\n$^\\dagger$ A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^\\ddagger$ A permutation $a$ of length $n$ is lexicographically smaller than a permutation $b$ of length $n$ if and only if the following holds: in the first position where $a$ and $b$ differ, the permutation $a$ has a smaller element than the corresponding element in $b$.",
    "tutorial": "Consider a permutation $p$ that lexicographically smaller than given permutation, assume the first different position is $k$, if we fix $p_k$, the remaining numbers $a_{k+1},a_{k+2},...,a_n$ can be arranged in any order. Denote $S$ as the set of remaining numbers. Let $m$ be the number of consecutive pairs, $m=|{x|x \\in S,(x-1) \\in S\\cup{p_k} }|$, $p_k$ is included because it is possible that $p_{k+1}=p_k+1$. Fix the number of positions that $p_i=p_{i-1}+1$, this consumes some consecutive pairs, the remaining consecutive pairs should not increase the number of positions. Define a sequence $p$ good if and only if it has no $i$ that $p_i=p_{i-1}+1$. Consider $dp[i][j]$ = number of good arrangements of $i$ values with $j$ consecutive pairs. Consider one consecutive pair, if it is the only wrong pair, the number of values decrease by one and this situation should be excluded, otherwise this pair can be ignored, so $dp[i][j]=dp[i][j-1]-dp[i-1][j-1]$, with boundary $dp[i][0]=i!$. After enumrating $k$, let $S'={a_k,a_{k+1},...,a_n}$, $p_k$ is chosen from $S'$ and $p_k<a_k$. Assume $p_k=x$, if $x-1 \\in S'$, the number of consecutive pairs decrease by one, otherwise it stay the same. Additionally, if $x \\ne p_{k-1}+1$, the number of subarrays increase by one. For every situation, count the number of $p_k$ and then calculate answer. Time complexity: $O(n^2)$. Since we have to deal with lexicographically smaller condition, it's natural to fix the common prefix $i$. Now, we can mismatch $p_{i+1}$ with some of the left values. After that, we are left with permuting the other elements. Let's say we are trying to find the number of ways to permute the remaining values {$a_1,a_2,a_3,...,a_k$} such that $a_i \\neq a_{i+1}-1$ for $1 \\le i < k$. For each $i$, we define $b_i$ to be a boolean value denoting the existence of $a_i - 1$ in set $a$. We can formulate the following 2 claims: The number of ways to permute array $a$ only depends on $k$ and sum of $b$ For some pair $(i,j)$, the number of ways to permute $a$ starting with $a_i$ is equal to the number of ways to permute $a$ starting with $a_j$ if and only if $b_i = b_j$ With these observations, we can formulate a $dp$ solution for counting permutations. Let $dp_{i,j,flag}$ be the number of ways to permute if $k=i$, $j$ is the sum of $b$, starting with a value with $b$ value equal to $flag$. Let's conclude transitions: $dp_{i,1,true} = dp_{i-1,1,false}$ $dp_{i,1,false} = (dp_{i-1,1,true} + dp_{i-1,1,false}) \\cdot (i-1)$ $-$ By claim 2, we can think of ending in the minimum value and we are left with another permutation we can transition 2. $dp_{i,j>1,true} = (dp_{i-1,j-1,true}+dp_{i-1,j-1,false}) \\cdot j$ $-$ By claim 1, we can think of an equivalent array $a$ in which all values with $b_i = 1$ are left alone. Combining with claim 2, all distributions are equal, and selecting a single value makes the permutation have $j-1$ values with $b_i=1$. $dp_{i,j>1,false} = (dp_{i-1,j,false} + dp_{i-1,j,true}) \\cdot (i-j)$ $-$ By claim 2, we can select any value with $b_i=0$ and combining with claim $2$, we can select the first value in the last chain. Let $sum$ be the sum of $b$.The number of ways to permute $a$ such that it respects the given demands, is $dp_{k,sum,true} + dp_{k,sum,false}$. Now the number of ways to permute $a$ with $t$ positions such that $a_i \\neq a_{i+1}-1$ is $\\binom{k-sum}{t-sum} \\cdot (dp_{k,t,true} + dp_{k,t,false})$. This is because we can choose the values that contribute, $sum$ of them are always contributing, so we are left with choosing $t-sum$ values out of $k-sum$ possibilities. Now thinking about the values we missmatch $p_{i+1}$ with, looking at claim $2$, a lot of values are equivalent. We can count each value type separately since there are $O(1)$ types, and have a $O(n)$ complexity to update the results accordingly. Also be careful with the case where a past range of consecutive values is continued after the missmatch. It's easy to handle this because $p'_{i+1}$ is fixed and we can count it independently in $O(n)$. Thus we have achieved $O(n^2)$ total time complexity",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nint mod;\\nclass Mint\\n{\\npublic:\\n    int val;\\n    Mint(int _val = 0)\\n    {\\n        val = _val % mod;\\n    }\\n    Mint(long long _val)\\n    {\\n        val = _val % mod;\\n    }\\n    Mint operator+(Mint oth)\\n    {\\n        return val + oth.val;\\n    }\\n    Mint operator*(Mint oth)\\n    {\\n        return 1LL * val * oth.val;\\n    }\\n    Mint operator-(Mint oth)\\n    {\\n        return val - oth.val + mod;\\n    }\\n    void operator+=(Mint oth)\\n    {\\n        val = (Mint(val) + oth).val;\\n    }\\n    void operator-=(Mint oth)\\n    {\\n        val = (Mint(val) - oth).val;\\n    }\\n    void operator*=(Mint oth)\\n    {\\n        val = (Mint(val) * oth).val;\\n    }\\n};\\nint main()\\n{\\n    cin.tie(nullptr)->sync_with_stdio(false);\\n    int n;\\n    cin >> n >> mod;\\n    vector<int> a(n + 1);\\n    for (int i = 1; i <= n; ++i)\\n    {\\n        cin >> a[i];\\n    }\\n    a[0] = -1;\\n    vector<vector<Mint>> pas(n + 1, vector<Mint>(n + 1));\\n    pas[0][0] = 1;\\n    for (int i = 1; i <= n; ++i)\\n    {\\n        for (int j = 0; j <= i; ++j)\\n        {\\n            if (j == 0 || j == i)\\n            {\\n                pas[i][j] = 1;\\n                continue;\\n            }\\n            pas[i][j] = pas[i - 1][j] + pas[i - 1][j - 1];\\n        }\\n    }\\n    function<Mint(int, int)> combi = [&](int i, int j)\\n    {\\n        if (i < j)\\n        {\\n            return Mint(0);\\n        }\\n        return pas[i][j];\\n    };\\n    function<Mint(int, int)> sb = [&](int n, int k)\\n    {\\n        return combi(n - 1, n - k);\\n    };\\n    vector<vector<vector<Mint>>> dp(n + 1, vector<vector<Mint>>(n + 1, vector<Mint>(2)));\\n    vector<vector<vector<Mint>>> coef(n + 1, vector<vector<Mint>>(n + 1, vector<Mint>(2)));\\n    dp[1][1][true] = 1;\\n    coef[1][1][true] = 1;\\n    for (int i = 2; i <= n; ++i)\\n    {\\n        dp[i][1][true] = dp[i - 1][1][false];\\n        coef[i][1][true] = dp[i - 1][1][false];\\n        dp[i][1][false] = (dp[i - 1][1][true] + dp[i - 1][1][false]) * (i - 1);\\n        coef[i][1][false] = dp[i - 1][1][true] + dp[i - 1][1][false];\\n        for (int j = 2; j <= i; ++j)\\n        {\\n            dp[i][j][true] = (dp[i - 1][j - 1][false] + dp[i - 1][j - 1][true]) * j;\\n            coef[i][j][true] = dp[i - 1][j - 1][false] + dp[i - 1][j - 1][true];\\n            dp[i][j][false] = (dp[i - 1][j][false] + dp[i - 1][j][true]) * (i - j);\\n            coef[i][j][false] = dp[i - 1][j][false] + dp[i - 1][j][true];\\n        }\\n    }\\n    vector<bool> exista(n + 2, true);\\n    exista[0] = false;\\n    exista[n + 1] = false;\\n    int cnt = 0;\\n    vector<Mint> ans(n + 1);\\n    for (int i = 1; i < n; ++i)\\n    {\\n        int last = -1;\\n        int m = 0;\\n        int sz = 0;\\n        for (int j = 1; j <= n; ++j)\\n        {\\n            if (exista[j])\\n            {\\n                m += j != (last + 1);\\n                last = j;\\n                sz++;\\n            }\\n        }\\n        function<void(int, int, int)> count = [&](int freq, int m, bool type)\\n        {\\n            if (freq == 0)\\n            {\\n                return;\\n            }\\n            if (type)\\n            {\\n                for (int k = 1; k <= n; ++k)\\n                {\\n                    int need = k - cnt;\\n                    if (need >= m)\\n                    {\\n                        ans[k] += combi(sz - m - 1, need - m) * (dp[need][m][false] + dp[need][m][true] - coef[need][m][true]) * freq;\\n                    }\\n                    if (need >= m - 1)\\n                    {\\n                        ans[k] += combi(sz - m - 1, need - m + 1) * coef[need + 1][m][true] * freq;\\n                    }\\n                }\\n            }\\n            else\\n            {\\n                for (int k = 1; k <= n; ++k)\\n                {\\n                    int need = k - cnt;\\n                    if (need >= m)\\n                    {\\n                        ans[k] += combi(sz - m - 1, need - m) * (dp[need][m][true] + dp[need][m][false]) * freq;\\n                    }\\n                }\\n            }\\n        };\\n        if (m)\\n        {\\n            if (exista[a[i - 1] + 1] && a[i - 1] + 1 < a[i])\\n            {\\n                if (exista[a[i - 1] + 2])\\n                {\\n                    count(1, m, true);\\n                }\\n                else\\n                {\\n                    count(1, m - 1, false);\\n                }\\n            }\\n            cnt++;\\n            int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0;\\n            for (int j = 1; j < a[i]; ++j)\\n            {\\n                if (j != (a[i - 1] + 1) && exista[j])\\n                {\\n                    if (exista[j - 1] && exista[j + 1])\\n                    {\\n                        cnt1++;\\n                        continue;\\n                    }\\n                    if (!exista[j - 1] && !exista[j + 1])\\n                    {\\n                        cnt2++;\\n                        continue;\\n                    }\\n                    if (!exista[j - 1])\\n                    {\\n                        cnt3++;\\n                        continue;\\n                    }\\n                    if (!exista[j + 1])\\n                    {\\n                        cnt4++;\\n                        continue;\\n                    }\\n                }\\n            }\\n            count(cnt1, m + 1, true);\\n            count(cnt2, m - 1, false);\\n            count(cnt3, m, true);\\n            count(cnt4, m, false);\\n            cnt--;\\n        }\\n        exista[a[i]] = false;\\n        cnt += a[i] != (a[i - 1] + 1);\\n    }\\n    for (int i = 1; i <= n; ++i)\\n    {\\n        cout << ans[i].val << ' ';\\n    }\\n}\"",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1750",
    "index": "H",
    "title": "BinaryStringForces",
    "statement": "You are given a binary string $s$ of length $n$. We define a maximal substring as a substring that cannot be extended while keeping all elements equal. For example, in the string $11000111$ there are three maximal substrings: $11$, $000$ and $111$.\n\nIn one operation, you can select two maximal adjacent substrings. Since they are maximal and adjacent, it's easy to see their elements must have different values. Let $a$ be the length of the sequence of ones and $b$ be the length of the sequence of zeros. Then do the following:\n\n- If $a \\ge b$, then replace $b$ selected zeros with $b$ ones.\n- If $a < b$, then replace $a$ selected ones with $a$ zeros.\n\nAs an example, for $1110000$ we make it $0000000$, for $0011$ we make it $1111$. We call a string being good if it can be turned into $1111...1111$ using the aforementioned operation any number of times (possibly, zero). Find the number of good substrings among all $\\frac{n(n+1)}{2}$ non-empty substrings of $s$.",
    "tutorial": "We call a maximal sequence of $0$ a $0$ block, a maximal sequence of $1$ a $1$ block. For each $i$, store some disjoint intervals with the following property: For each $j$ that $i<=j$ and $s[j]=1$, j is in one of the intervals if and only if $(i,j)$ is a good substring. We can prove the number of intervals for each $i$ is $O(\\log n)$. Let's start from $(i,i)$ to $(i,n)$, and consider when. good substring become bad and bad substring become good. Assume we are at $(i,j)$. If it is a good substring and ending with 1, it become bad when it meet a longer 0 block, so we get one interval and go to a bad substring ending with 0. If it is a bad substring and ending with 0, suppose the next 1 is at k, then the next good intervals start at the smallest j' with three properties: (1) $(k,j')$ is good (2) $s[j']=1$ (3) $(k,j')$ is not shorter than the last 0 block. Proof: Property 2 is obvious because we only care about substrings ending with 1. If $(k,j')$ is shorter than the last $0$ block, it is impossible to change this $0$ block, so $(i,j')$ is bad. If $(k,j')$ is bad, if it starts with a 1 block $(k,j\")$ not shorter than the last $0$ block after some operations, then $j\"$ is smaller than $j'$ and has those three properties, otherwise it is impossible to change the last $0$ block. If it has all three properties, in substring $(i,j')$, $(k,j')$ is good and can change the last $0$ block $1$, and then change $(i,j')$ to $1$, so we go to a good substring ending with 1. When good substring become bad, the length is doubled, so the number of intervals for each i is $O(logn)$. To know when good substring become bad ,for every 0 block $(j,k)$,if $(j,k)$ is longer than $(i,j-1)$, then $(i,k)$ is bad, we can preprocess those i in $O(n)$. To know when bad substring become good, we go with $i$ from $n$ to $1$ and for each $i$, search in $O(\\log n)$ intervals $O(\\log n)$ times. So we get those intervals in $O(n\\log^2 n)$ Now we can check each substring ending with $1$ is good or not. Do the above algorithm on the reversed string, so we can check each substring starting with 1 is good or not. But we can not check substring starting and ending with 0. Suppose $(i',j')$ is the longest $0$ block in $(i,j)$, then $(i,j)$ is good if at least one of $(i,i'-1)$ and $(j'+1,j)$ is good and not shorter than $(i',j')$. Proof: After changing the longest $0$ block, we can change all other $0$ blocks. So for any substring, it is good if and only if we can change its longest $0$ block. If $(i,i'-1)$ is good and not shorter, it can change $(i',j')$, so $(i,j)$ is good. If $(i,j)$ is good assume the longest 0 block is changed from left. So after some operations in $(i,i'-1)$, there is a substring $(k,i'-1)$ become all $1$ and not shorter than $(i',j')$. Then $(k,i'-1)$ can make $(i,i'-1)$ good as there is no longer $0$ block. Similarly, we can prove for $(j'+1,j)$. So for each substring, we consider its longest $0$ block (substrings with no $0$ are always good). For convenience, if there are multiple maximum, we take the rightmost. The longest $0$ block in substrings can be either a $0$ block in the original string or part of $0$ block in the original string. We can ignore substring in one $0$ block, so the longest $0$ block can only be a prefix or suffix, the number of possible longest $0$ block is $O(n)$. For each possible 0 block $(i,j)$, assume the longest substring that $(i,j)$ is the longest $0$ block is $(i',j')$, we need to count answer for substring $(l,r)$ that $i' \\le l \\le i,j \\le r \\le j'$, it is equivalent to count the number of $l$ that $i'\\le l \\le i-(j-i+1)$ and $(l,i-1)$ is good and the number of $r$ that $j+(j-i+1) \\le r \\le j'$ and $(j+1,r)$ is good. Notice that $s[i-1]=s[j+1]=1$, we can calculate them by above intervals. We can use persistent segment tree directly or use segment tree or binary index tree after sorting queries. We need $O(nlogn)$ modifications and $O(n)$ queries. Thus we have solved our problem in $O(n\\log^2 n)$.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\\nint random(int st, int dr)\\n{\\n  uniform_int_distribution<mt19937::result_type> gen(st, dr);\\n  return gen(rng);\\n}\\nvector<int> lg;\\nstruct bit\\n{\\n  vector<int> b;\\n  void resize(int n)\\n  {\\n    b.resize(n + 1);\\n  }\\n  void update(int pos, int val)\\n  {\\n    int n = (int)b.size() - 1;\\n    for (int i = pos; i <= n; i += i & (-i))\\n    {\\n      b[i] += val;\\n    }\\n  }\\n  int query(int pos)\\n  {\\n    int ans = 0;\\n    for (int i = pos; i; i -= i & (-i))\\n    {\\n      ans += b[i];\\n    }\\n    return ans;\\n  }\\n  int query(int st, int dr)\\n  {\\n    return query(dr) - query(st - 1);\\n  }\\n};\\nstruct stack_rmq\\n{\\n  vector<vector<int>> rmq;\\n  void insert(int val)\\n  {\\n    rmq.push_back({val});\\n    int sz = rmq.size() - 1;\\n    for (int i = 1; sz - (1 << i) + 1 >= 0; ++i)\\n    {\\n      rmq[sz].push_back(\\n          max(rmq[sz][i - 1], rmq[sz - (1 << (i - 1))][i - 1]));\\n    }\\n  }\\n  void update(int val)\\n  {\\n    int sz = (int)rmq.size() - 1;\\n    int cine = val + rmq[sz][0];\\n    rmq.pop_back();\\n    insert(cine);\\n  }\\n  int query(int st, int dr)\\n  {\\n    if (st > dr)\\n    {\\n      return 0;\\n    }\\n    int pow_2 = lg[dr - st + 1];\\n    return max(rmq[dr][pow_2], rmq[st + (1 << pow_2) - 1][pow_2]);\\n  }\\n};\\nstruct maximal\\n{\\n  stack_rmq lesgo;\\n  vector<pair<int, int>> ranges;\\n  vector<int> qui;\\n  string s;\\n  int n;\\n  void build(string _s, int _n)\\n  {\\n    s = _s;\\n    n = _n;\\n    qui = vector<int>(n + 1);\\n    bool este = false;\\n    for (int i = 1; i <= n; ++i)\\n    {\\n      if (s[i] == '0')\\n      {\\n        if (este)\\n        {\\n          lesgo.update(1);\\n          ranges[(int)ranges.size() - 1].second++;\\n        }\\n        else\\n        {\\n          lesgo.insert(1);\\n          ranges.push_back({i, i});\\n          este = true;\\n        }\\n      }\\n      else\\n      {\\n        este = false;\\n      }\\n      qui[i] = (int)ranges.size() - 1;\\n    }\\n  }\\n  int query(int st, int dr)\\n  {\\n    if (s[st] == '1')\\n    {\\n      int l = qui[st] + 1;\\n      int r = (s[dr] == '0' ? qui[dr] - 1 : qui[dr]);\\n      int partial = (s[dr] == '0' ? dr - ranges[qui[dr]].first + 1 : 0);\\n      return max(lesgo.query(l, r), partial);\\n    }\\n    if (s[dr] == '1')\\n    {\\n      int r = qui[dr];\\n      int l = qui[st] + 1;\\n      int partial = (s[st] == '0' ? ranges[qui[st]].second - st + 1 : 0);\\n      return max(lesgo.query(l, r), partial);\\n    }\\n  }\\n  int next(int lg, int pos, bool fata)\\n  {\\n    assert(s[pos] == '1');\\n    if (fata)\\n    {\\n      int st = pos, dr = n;\\n      int ans = 0;\\n      while (st <= dr)\\n      {\\n        int mid = (st + dr) / 2;\\n        if (query(pos, mid) <= lg)\\n        {\\n          ans = mid;\\n          st = mid + 1;\\n        }\\n        else\\n        {\\n          dr = mid - 1;\\n        }\\n      }\\n      return ans;\\n    }\\n    else\\n    {\\n      int st = 1, dr = pos;\\n      int ans = 0;\\n      while (st <= dr)\\n      {\\n        int mid = (st + dr) / 2;\\n        if (query(mid, pos) < lg)\\n        {\\n          ans = mid;\\n          dr = mid - 1;\\n        }\\n        else\\n        {\\n          st = mid + 1;\\n        }\\n      }\\n      return ans;\\n    }\\n  }\\n};\\nvector<vector<pair<int, int>>> find_relevant_ranges(string s, int n)\\n{\\n  vector<int> sp(n + 1);\\n  for (int i = 1; i <= n; ++i)\\n  {\\n    sp[i] = sp[i - 1] + (s[i] == '1');\\n  }\\n  function<int(int, int)> query = [&](int st, int dr)\\n  {\\n    return sp[dr] - sp[st - 1];\\n  };\\n  vector<vector<pair<int, int>>> cine(n + 1);\\n  stack_rmq lesgo;\\n  vector<pair<int, int>> secv;\\n  bool este = false;\\n  for (int i = n; i >= 1; --i)\\n  {\\n    if (s[i] == '0')\\n    {\\n      if (!este)\\n      {\\n        lesgo.insert(1);\\n        secv.push_back({i, i});\\n        este = true;\\n      }\\n      else\\n      {\\n        lesgo.update(1);\\n        secv[(int)secv.size() - 1].first--;\\n      }\\n    }\\n    else\\n    {\\n      este = false;\\n    }\\n    int cnt = 0;\\n    int p = i;\\n    while (p <= n)\\n    {\\n      int st = 0, dr = (int)secv.size() - 1;\\n      int rep = -1;\\n      while (st <= dr)\\n      {\\n        int mid = (st + dr) / 2;\\n        if (lesgo.query(mid, (int)secv.size() - 1) > cnt)\\n        {\\n          rep = mid;\\n          st = mid + 1;\\n        }\\n        else\\n        {\\n          dr = mid - 1;\\n        }\\n      }\\n      if (rep == -1)\\n      {\\n        cine[i].push_back({p, n});\\n        break;\\n      }\\n      st = secv[rep].first, dr = secv[rep].second;\\n\\n      int l = (dr - st + 1);\\n      cnt += (secv[rep].first - p);\\n      if (st != p)\\n      {\\n        cine[i].push_back({p, st - 1});\\n      }\\n      p = secv[rep].first;\\n      if (l > cnt)\\n      {\\n        if (dr == n)\\n        {\\n          break;\\n        }\\n        int save = dr + 1;\\n        bool ok = false;\\n        for (int j = 0; j < cine[save].size(); ++j)\\n        {\\n          if (cine[save][j].second - save + 1 >= l)\\n          {\\n            pair<int, int> interv = {max(save + l - 1, cine[save][j].first), cine[save][j].second};\\n            if (query(interv.first, interv.second))\\n            {\\n              int low = interv.first, high = interv.second;\\n              int qui = -1;\\n              while (low <= high)\\n              {\\n                int mid = (low + high) / 2;\\n                if (query(interv.first, mid))\\n                {\\n                  qui = mid;\\n                  high = mid - 1;\\n                }\\n                else\\n                {\\n                  low = mid + 1;\\n                }\\n              }\\n              cine[i].push_back({qui, qui});\\n              cnt += (qui - p + 1);\\n              p = qui + 1;\\n              ok = true;\\n              break;\\n            }\\n          }\\n        }\\n        if (!ok)\\n        {\\n          break;\\n        }\\n      }\\n      else\\n      {\\n        cine[i].push_back({p, dr});\\n        cnt += dr - p + 1;\\n        p = dr + 1;\\n      }\\n    }\\n  }\\n  return cine;\\n}\\n\\nvector<vector<pair<int, int>>> cine1, cine2;\\nint n;\\nstring s;\\nvoid smart()\\n{\\n  long long ans = 0;\\n  vector<vector<pair<int, int>>> events1(n + 1);\\n  vector<vector<pair<int, int>>> events2(n + 1);\\n  bit tree1;\\n  bit tree2;\\n  maximal cine;\\n  cine.build(s, n);\\n  tree1.resize(n + 1);\\n  tree2.resize(n + 1);\\n  int p1 = 1;\\n  int p2 = 1;\\n  for (int i = 1; i <= n; ++i)\\n  {\\n    for (auto j : cine1[i])\\n    {\\n      events1[j.first].push_back({i, 1});\\n      if (j.second + 1 <= n)\\n      {\\n        events1[j.second + 1].push_back({i, -1});\\n      }\\n    }\\n  }\\n  for (int i = 1; i <= n; ++i)\\n  {\\n    for (auto j : cine2[i])\\n    {\\n      events2[j.first].push_back({i, 1});\\n      if (j.second + 1 <= n)\\n      {\\n\\n        events2[j.second + 1].push_back({i, -1});\\n      }\\n    }\\n  }\\n  function<void(int)> move1 = [&](int pos)\\n  {\\n    while (p1 <= pos)\\n    {\\n      for (auto i : events1[p1])\\n      {\\n        tree1.update(i.first, i.second);\\n      }\\n      p1++;\\n    }\\n  };\\n  function<void(int)> move2 = [&](int pos)\\n  {\\n    while (p2 <= pos)\\n    {\\n      for (auto i : events2[p2])\\n      {\\n        tree2.update(i.first, i.second);\\n      }\\n      p2++;\\n    }\\n  };\\n  for (auto x : cine.ranges)\\n  {\\n    int lg = x.second - x.first + 1;\\n    int l = 0, r = 0;\\n    int ways1 = 0, ways2 = 0;\\n    if (x.first - 1 >= 1)\\n    {\\n      move1(x.first - 1);\\n      for (int i = 1; i < lg; ++i)\\n      {\\n        int qui = cine.next(i, x.first - 1, false);\\n        int last = x.first - i;\\n        if (qui <= last)\\n        {\\n          ans += tree1.query(qui, last);\\n        }\\n      }\\n      l = cine.next(lg, x.first - 1, false);\\n      int last = x.first - lg;\\n      ways1 = x.first - l + 1;\\n      if (l <= last)\\n      {\\n        ways1 -= tree1.query(l, last);\\n      }\\n    }\\n    else\\n    {\\n      l = 1;\\n      ways1 = 1;\\n    }\\n    if (x.second + 1 <= n)\\n    {\\n      move2(x.second + 1);\\n      for (int i = 1; i < lg; ++i)\\n      {\\n        int qui = cine.next(i, x.second + 1, true);\\n        int first = x.second + i;\\n\\n        if (first <= qui)\\n        {\\n          ans += tree2.query(first, qui);\\n        }\\n      }\\n      r = cine.next(lg, x.second + 1, true);\\n      int first = x.second + lg;\\n      ways2 = r - x.second + 1;\\n      if (first <= r)\\n      {\\n        ways2 -= tree2.query(first, r);\\n      }\\n    }\\n    else\\n    {\\n      r = n;\\n      ways2 = 1;\\n    }\\n    ans += 1ll * (r - x.second + 1ll) * (x.first - l + 1ll) - 1ll * ways1 * ways2;\\n  }\\n  int lg = 0;\\n  for (int i = 1; i <= n; ++i)\\n  {\\n    if (s[i] == '1')\\n    {\\n      lg++;\\n    }\\n    else\\n    {\\n      ans += 1ll * lg * (lg + 1) / 2;\\n      lg = 0;\\n    }\\n  }\\n  ans += 1ll * lg * (lg + 1) / 2;\\n  cout << ans << '\\\\n';\\n}\\nint main()\\n{\\n  cin.tie(nullptr)->sync_with_stdio(false);\\n  int q;\\n  cin >> q;\\n  while (q--)\\n  {\\n    cin >> n >> s;\\n    lg = vector<int>(n + 1);\\n    for (int i = 2; i <= n; ++i)\\n    {\\n      lg[i] = lg[i / 2] + 1;\\n    }\\n    s = '$' + s;\\n    cine1 = find_relevant_ranges(s, n);\\n    reverse(s.begin() + 1, s.end());\\n    cine2 = find_relevant_ranges(s, n);\\n    reverse(s.begin() + 1, s.end());\\n    for (int i = 1; i <= n; ++i)\\n    {\\n      for (int j = 0; j < (int)cine2[i].size(); ++j)\\n      {\\n        cine2[i][j].first = n - cine2[i][j].first + 1;\\n        cine2[i][j].second = n - cine2[i][j].second + 1;\\n        swap(cine2[i][j].first, cine2[i][j].second);\\n      }\\n      reverse(cine2[i].begin(), cine2[i].end());\\n    }\\n    for (int i = 1; i <= n; ++i)\\n    {\\n      if (i < (n - i + 1))\\n      {\\n        swap(cine2[i], cine2[n - i + 1]);\\n      }\\n    }\\n    smart();\\n  }\\n}\"",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1753",
    "index": "A1",
    "title": "Make Nonzero Sum (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference is that in this version the array can not contain zeros. You can make hacks only if both versions of the problem are solved.}\n\nYou are given an array $[a_1, a_2, \\ldots a_n]$ consisting of integers $-1$ and $1$. You have to build a partition of this array into the set of segments $[l_1, r_1], [l_2, r_2], \\ldots, [l_k, r_k]$ with the following property:\n\n- Denote the alternating sum of all elements of the $i$-th segment as $s_i$: $s_i$ = $a_{l_i} - a_{l_i+1} + a_{l_i+2} - a_{l_i+3} + \\ldots \\pm a_{r_i}$. For example, the alternating sum of elements of segment $[2, 4]$ in array $[1, 0, -1, 1, 1]$ equals to $0 - (-1) + 1 = 2$.\n- The sum of $s_i$ over all segments of partition should be equal to zero.\n\nNote that each $s_i$ does \\textbf{not} have to be equal to zero, this property is about sum of $s_i$ over all segments of partition.\n\nThe set of segments $[l_1, r_1], [l_2, r_2], \\ldots, [l_k, r_k]$ is called a partition of the array $a$ of length $n$ if $1 = l_1 \\le r_1, l_2 \\le r_2, \\ldots, l_k \\le r_k = n$ and $r_i + 1 = l_{i+1}$ for all $i = 1, 2, \\ldots k-1$. In other words, each element of the array must belong to exactly one segment.\n\nYou have to build a partition of the given array with properties described above or determine that such partition does not exist.\n\nNote that it is \\textbf{not} required to minimize the number of segments in the partition.",
    "tutorial": "If the sum of all elements of the array is odd, the partitions does not exist because the partition does not affect the parity of the sum. Otherwise the answer exists. Let's build such construction. As the sum of all elements is even, $n$ is even too. Consider pairs of elements with indices $(1, 2)$, $(3, 4)$, ..., $(n - 1, n)$. Consider the pair $(2i - 1, 2i)$. If $a_{2i - 1} = a_{2i}$, add the segment $[2i - 1, 2i]$ to the answer. In this case the alternating sum of elements of this segment will be equal to $a_{2i - 1} - a_{2i} = 0$. Otherwise we will add two segments to the answer: $[2i - 1, 2i - 1]$ and $[2i, 2i]$. The sum of the first segment is $a_{2i - 1}$, and the sum of the second segment is $a_{2i}$. The sum of two sums will be equal to zero. So the sum of all alternating sums will be equal to zero.",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1753",
    "index": "A2",
    "title": "Make Nonzero Sum (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference is that in this version the array contains zeros. You can make hacks only if both versions of the problem are solved.}\n\nYou are given an array $[a_1, a_2, \\ldots a_n]$ consisting of integers $-1$, $0$ and $1$. You have to build a partition of this array into the set of segments $[l_1, r_1], [l_2, r_2], \\ldots, [l_k, r_k]$ with the following property:\n\n- Denote the alternating sum of all elements of the $i$-th segment as $s_i$: $s_i$ = $a_{l_i} - a_{l_i+1} + a_{l_i+2} - a_{l_i+3} + \\ldots \\pm a_{r_i}$. For example, the alternating sum of elements of segment $[2, 4]$ in array $[1, 0, -1, 1, 1]$ equals to $0 - (-1) + 1 = 2$.\n- The sum of $s_i$ over all segments of partition should be equal to zero.\n\nNote that each $s_i$ does \\textbf{not} have to be equal to zero, this property is about sum of $s_i$ over all segments of partition.\n\nThe set of segments $[l_1, r_1], [l_2, r_2], \\ldots, [l_k, r_k]$ is called a \\textbf{partition} of the array $a$ of length $n$ if $1 = l_1 \\le r_1, l_2 \\le r_2, \\ldots, l_k \\le r_k = n$ and $r_i + 1 = l_{i+1}$ for all $i = 1, 2, \\ldots k-1$. In other words, each element of the array must belong to exactly one segment.\n\nYou have to build a partition of the given array with properties described above or determine that such partition does not exist.\n\nNote that it is \\textbf{not} required to minimize the number of segments in the partition.",
    "tutorial": "If the sum of all numbers in the array is odd, then splitting is impossible, because splitting does not affect the evenness of the sum. Otherwise, we will build the answer constructively. Suppose we have considered some kind of array prefix. Let's keep going until we get exactly $2$ non-zero numbers. We want to make these two non-zero numbers add up to $0$. Then if on the last segment the sum is already equal to $0$, then just take it as an answer. Otherwise, consider a few cases: If the length of the segment is even, then we simply separate the last number (it will be non-zero) into a separate segment. Then its sign will change and in total these two numbers will give $0$. The same can be done if the length of the segment is odd, but its first element is equal to $0$. Separate this $0$ and repeat the algorithm above. If the length of the segment is odd and the first element is not equal to $0$, then we separate it. Then the value of the first element will not change, and the last will change to the opposite, and then their sum will be equal to $0$.",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1753",
    "index": "B",
    "title": "Factorial Divisibility",
    "statement": "You are given an integer $x$ and an array of integers $a_1, a_2, \\ldots, a_n$. You have to determine if the number $a_1! + a_2! + \\ldots + a_n!$ is divisible by $x!$.\n\nHere $k!$ is a factorial of $k$ — the product of all positive integers less than or equal to $k$. For example, $3! = 1 \\cdot 2 \\cdot 3 = 6$, and $5! = 1 \\cdot 2 \\cdot 3 \\cdot 4 \\cdot 5 = 120$.",
    "tutorial": "Let's create an array $[cnt_1, cnt_2, \\ldots, cnt_x]$ where $cnt_i$ equals to number of elements equals to $i$ in the initial array. Note that $a_1!\\ + a_2!\\ +\\ \\ldots\\ +\\ a_n!$ equals to sum of $k! \\cdot cnt_k$ over all $k$ from $1$ to $x - 1$, $cnt_x$ does not affect anything because $x!$ divides $x!$ itself. We have to check if this sum is divisible by $x!$. Suppose there exists some $k < x$ such that $cnt_k \\geq k + 1$. In this case we can make two transformations: $cnt_k \\mathrel{-}= (k + 1); cnt_{k+1} \\mathrel{+}= 1$ and the sum of $k! \\cdot cnt_k$ will not change because $(k+1) \\cdot k! = (k+1)!$. Let's perform this operation until it is possible for all numbers from $1$ to $x - 1$. After all operations the sum of $k! \\cdot cnt_k$ will not change and for each $k < x$ the inequality $cnt_k \\leq k$ will be satisfied because if $cnt_k \\geq k+1$ we could perform an operation with this element. Let's see what is the maximum value of sum of $k \\cdot cnt_k$ over all $k$ from $1$ to $x - 1$ after all operations. We know that $cnt_k \\leq k$ for all $k$, so the maximum value of the sum is the sum of $k \\cdot k!$ over all $k$. Note that $k \\cdot k! = ((k + 1) - 1) \\cdot k! = (k + 1) \\cdot k! - k! = (k + 1)! - k!$. It means that the sum of such values over all $k$ from $1$ to $x - 1$ equals to $(2! - 1!) + (3! - 2!) + \\ldots + (x! - (x-1)!)$. Each factorial from $2$ to $x - 1$ will be added and subtracted from the sum. So the result is $x! - 1$. So the only one case when this sum is divisible by $x!$ is when the sum equals to $0$. It means that $cnt_k$ equals to zero for all $k$ from $1$ to $x - 1$ after performing all operations. Time complexity: $\\mathcal{O}(n + x)$.",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1753",
    "index": "C",
    "title": "Wish I Knew How to Sort",
    "statement": "You are given a binary array $a$ (all elements of the array are $0$ or $1$) of length $n$. You wish to sort this array, but unfortunately, your algorithms teacher forgot to teach you sorting algorithms. You perform the following operations until $a$ is sorted:\n\n- Choose two random indices $i$ and $j$ such that $i < j$. Indices are chosen equally probable among all pairs of indices $(i, j)$ such that $1 \\le i < j \\le n$.\n- If $a_i > a_j$, then swap elements $a_i$ and $a_j$.\n\nWhat is the expected number of such operations you will perform before the array becomes sorted?\n\nIt can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{998\\,244\\,353}$. Output the integer equal to $p \\cdot q^{-1} \\bmod 998\\,244\\,353$. In other words, output such an integer $x$ that $0 \\le x < 998\\,244\\,353$ and $x \\cdot q \\equiv p \\pmod{998\\,244\\,353}$.",
    "tutorial": "Let the number of zeros in the array be $g$. Let $dp[k]$ be the expected number of swaps needed when there are $k$ zeros in the first $g$ positions. Then, we know that $dp[g] = 0$, and we can write down the recurrence equations for $dp[k]$ by considering the case where some element equals to one from the first $g$ positions and some element equals to zero from the last $(n-g)$ positions are swapped. This is the only case where the $dp$ value will change. Thus, our recurrence is as follows. Let $p = \\frac{2 \\cdot (g-k) \\cdot (g-k)}{n \\cdot (n-1)}$. Then $dp[k] = 1 + dp[k] \\cdot (1 - p) + dp[k+1] \\cdot p$. The answer is $dp[o]$, where $o$ is the initial number of zeros in the first $g$ positions.",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1753",
    "index": "D",
    "title": "The Beach",
    "statement": "Andrew loves the sea. That's why, at the height of the summer season, he decided to go to the beach, taking a sunbed with him to sunbathe.\n\nThe beach is a rectangular field with $n$ rows and $m$ columns. Some cells of the beach are free, some have roads, stones, shops and other non-movable objects. Some of two adjacent along the side cells can have sunbeds located either horizontally or vertically.\n\nAndrew hopes to put his sunbed somewhere, but that's a bad luck, there may no longer be free places for him! That's why Andrew asked you to help him to find a free place for his sunbed. Andrew's sunbed also should be places on two adjacent cells.\n\nIf there are no two adjacent free cells, then in order to free some place for a sunbed, you will have to disturb other tourists. You can do the following actions:\n\n- Come to some sunbed and, after causing $p$ units of discomfort to its owner, lift the sunbed by one of its sides and rotate it by $90$ degrees. One half of the sunbed must remain in the same cell and another half of the sunbed must move to the free cell. At the same time, anything could be on the way of a sunbed during the rotation .\\begin{center}\n\\begin{tabular}{ccc}\n& & \\\n\\end{tabular}\n\n{\\small Rotation of the sunbed by $90$ degrees around cell $(1, 2)$.}\n\\end{center}\n- Come to some sunbed and, after causing $q$ units of discomfort to its owner, shift the sunbed along its long side by one cell. One half of the sunbed must move to the place of another, and another — to the free cell.\\begin{center}\n\\begin{tabular}{ccc}\n& & \\\n\\end{tabular}\n\n{\\small Shift of the sunbed by one cell to the right.}\n\\end{center}\n\nIn any moment each sunbed occupies two adjacent free cells. You cannot move more than one sunbed at a time.\n\nHelp Andrew to free a space for his sunbed, causing the minimum possible number of units of discomfort to other tourists, or detect that it is impossible.",
    "tutorial": "Let's paint our field in a chess coloring. Now let's consider our operations not as the movement of sunbeds, but as the movement of free cells. Then, a free cell adjacent to the long side of the sunbed can move to a cell of the sunbed that is not adjacent to this one, for $p$ units of discomfort. A free cell adjacent to the short side of the sunbed can move to a cell of the sunbed that is not adjacent to this one, for $q$ units of discomfort. Note that in this cases, the free cell does not change its color (in chess coloring). Since each sunbed should occupy one black and one white cell, then some two free cells of different colors should move to neighboring ones using operations. It can be shown that in the optimal answer we use no more than one operation with each sunbed. Then, for each position, looking at the adjacent sunbeds, we will determine where the free cell can move if it turns out to be in this position. Let's construct a weighted oriented graph on the cells of the field. Edge $(x_1, y_1) \\rightarrow (x_2, y_2)$ of weight $w$ (equal to $p$ or $q$) will mean that there is a sunbed such that by moving it with an operation that brings $w$ discomfort, we will free the cell $(x_2, y_2)$ and block the cell $(x_1, y_1)$. Note that the graphs on the black and white cells are not connected. Let's run Dijkstra's algorithm from all free cells at once. Then, for each cell $d_{x, y}$ - the minimum distance in this graph from a free cell is equal to the minimum amount of discomfort that must be used to free this cell. The answer to the problem is the minimum for all pairs $(x_1, y_1)$, $(x_2, y_2)$ neighboring cells, $d_{x_1, y_1} + d_{x_2, y_2}$. Or $-1$ if there is no pair of adjacent cells, both of which are reachable from the free ones. Asymptotics of the solution: $\\mathcal{O}(n m \\cdot\\log{(nm))}$",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1753",
    "index": "E",
    "title": "N Machines",
    "statement": "You have been invited as a production process optimization specialist to some very large company. The company has $n$ machines at its factory, standing one behind another in the production chain. Each machine can be described in one of the following two ways: $(+,~a_i)$ or $(*,~a_i)$.\n\nIf a workpiece with the value $x$ is supplied to the machine of kind $(+,~a_i)$, then the output workpiece has value $x + a_i$.\n\nIf a workpiece with the value $x$ is supplied to the machine of kind $(*,~a_i)$, then the output workpiece has value $x \\cdot a_i$.\n\nThe whole production process is as follows. The workpiece with the value $1$ is supplied to the first machine, then the workpiece obtained after the operation of the first machine is supplied to the second machine, then the workpiece obtained after the operation of the second machine is supplied to the third machine, and so on. The company is not doing very well, so now the value of the resulting product does not exceed $2 \\cdot 10^9$.\n\nThe directors of the company are not satisfied with the efficiency of the production process and have given you a budget of $b$ coins to optimize it.\n\nTo optimize production you can change the order of machines in the chain. Namely, by spending $p$ coins, you can take any machine of kind $(+,~a_i)$ and move it to any place in the chain without changing the order of other machines. Also, by spending $m$ coins, you can take any machine of kind $(*,~a_i)$ and move it to any place in the chain.\n\nWhat is the maximum value of the resulting product that can be achieved if the total cost of movements that are made should not exceed $b$ coins?",
    "tutorial": "Let $C$ bi the maximum value of the resulting product before any movements. The problem statement says that it is guaranteed that $C \\le 2 \\cdot 10^9$. Observation 0 - after each movements the value of the resulting product is not greater than $\\frac{C^2}{4}$. Observation 1 - each machine of kind $(*, a_i)$ should be moved to the end of the sequence, and each machine of kind $(+, a_i)$ - to the beginning of the sequence, and the order of movements does not make sense. Observation 2 - there are at most $\\log_2{C}$ non-trivial machines of kind $(*, a_i)$ (such machines that $a_i \\neq 1$). We will need some more strong observation for machines of kind $(*, a_i)$, but this will be useful too. Observation 3 - if there are two machines $(*, a_i)$, $(*, a_j)$, where $i < j$ and $a_i >= a_j$, then in optimal answer machine $j$ may be moved if and only if machine $i$ is moved too. It is true because we could increase the answer otherwise, by moving machine $i$ instead of machine $j$. The last two observations says that there are not many subsets of machines of kind $(*, a_i)$ (that satisfies the property from observation 3). Let's say that there are $F(C)$ such subsets, in the end of the editorial we will estimate this value. Let's pick out subsegments of machines of kind $(+, a_i)$ between machines of kind $(*, a_i)$, sort them and count prefix sums. There will be not more than $\\log_2{C} + 1$ such segments. In the optimal answer some maximums will be moved from each of the segments. Let's fix some subset of machines of kind $(*, a_i)$, that will be moved to the end, and count the current value of the output product. Consider some element $(+, a_j)$ in the array. Let the product of machines $(*, a_i)$ to the left of it be $lmul$, and to the right of it - to be $rmul$. Now if we move this element to the beginning of the array, the value of the resulting product will increase by $\\frac{lmul-1}{lmul} \\cdot rmul \\cdot a_j$. Let's call this $profit_j$. Now we have to find the sum of some numbers of maximum values $profit_j$. Let's use binary search to find some \"critical\" value $profit$: such value that all elements $profit_j \\ge profit$ will be moved to the beginning. $profit_j$ of each element is not greater than $C^2/4$. Inside binary search we have to iterate over all segments of elements $(+, a_i)$ and find the number of elements with $profit_j \\ge profit$ inside this segment using binary search. We have to check if we can to move the selected amount of elements to the beginning of the array to understand how to move borders of the external binary search. After we find the critical value $profit$, let's iterate over all segments $(+, a_i)$ and add the sum of elements that are $profit_j \\ge profit$ to the answer. Separately let's consider elements with $profit_j$ = $profit - 1$. We could move some of them to the beginning too. Let's update the answer with this value. Time complexity: $O(F(C) \\log^3_2(C) + n \\cdot \\log_2(n))$. It should be noted that this estimate is actually higher than in fact. Let's estimate the value $F(C)$ now: Consider some sequence $b_1, b_2, \\dots, b_k$, such that $b_1 \\cdot b_2 \\cdot$ $\\dots$ $\\cdot b_k \\le C$ and $2 \\le b_i$ Sort it by ascending, $b_1 \\le b_2 \\le \\dots \\le b_k$ - the product of elements will not change and the number of \"interesting\" subsets will not become smaller. Replace all the smallest elements of the sequence with $2$, the second minimums with $3$ and so on. If there are smaller number of elements equals to $x$ than elements equals to $y$ and $x < y$, let's swap their numbers. Now the number of interesting subsets is not changed, $b_1 \\cdot b_2 \\cdot$ $\\dots$ $\\cdot b_k$ is not increased. The sequence looks like $2, 2, \\dots, 3, \\dots, 4, \\dots$ now. The number of interesting subsets in the new sequence equals to $(cnt_2 + 1) \\cdot (cnt_3 + 1) \\cdot \\dots$, where $cnt_x$ is the number of elements if sequence equals to $x$. (Let's run the code that will brute-force over all sequences of such kind and see that the number of interesting subsets is $4608$, which is achieved on sequence $2, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 10, 11$) Let's continue estimating this value \"fairly\": the elements of the sequence do not exceed $12$ because $13! > C$. Let's replace each number with a prime number corresponding to it by order: $p_2 = 2, p_3 = 3, p_4 = 5, p_5 = 7, p_6 = 11, ...$ and replace all elements $x$ with $p_x$. The product of elements will increate in at most $\\max\\limits_{x}{((\\frac{p_x}{x})^{\\log_x(C)})}$ times, so the product will not exceed $\\max\\limits_{x}{(C^{\\log_x{(p_x)}})}$. It is easy to check that the maximum is achieved in $x=6$, so the product is not greater than $C^{\\log_6{11}}$ $\\le 3 \\cdot 10^{12}$. The number of interesting subsets of our sequence does not exceed the number of divisors of received numbers that can be estimated as $(3 \\cdot 10^{12})^{(1/3)}$ $\\le 15000$",
    "tags": [
      "binary search",
      "brute force",
      "greedy"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1753",
    "index": "F",
    "title": "Minecraft Series",
    "statement": "Little Misha goes to the programming club and solves nothing there. It may seem strange, but when you find out that Misha is filming a Minecraft series, everything will fall into place...\n\nMisha is inspired by Manhattan, so he built a city in Minecraft that can be imagined as a table of size $n \\times m$. $k$ students live in a city, the $i$-th student lives in the house, located at the intersection of the $x_i$-th row and the $y_i$-th column. Also, each student has a degree of his aggressiveness $w_i$. Since the city turned out to be very large, Misha decided to territorially limit the actions of his series to some square $s$, which sides are parallel to the coordinate axes. The length of the side of the square should be an integer from $1$ to $\\min(n, m)$ cells.\n\nAccording to the plot, the main hero will come to the city and accidentally fall into the square $s$. Possessing a unique degree of aggressiveness $0$, he will be able to show his leadership qualities and assemble a team of calm, moderate and aggressive students.\n\nIn order for the assembled team to be versatile and close-knit, degrees of aggressiveness of all students of the team must be pairwise distinct and must form a single segment of consecutive integers. Formally, if \\textbf{there exist} students with degrees of aggressiveness $l, l+1, \\ldots, -1, 1, \\ldots, r-1, r$ inside the square $s$, where $l \\le 0 \\le r$, the main hero will be able to form a team of $r-l+1$ people (of course, he is included in this team).\n\n\\textbf{Notice}, that it is not required to take all students from square $s$ to the team.\n\nMisha thinks that the team should consist of at least $t$ people. That is why he is interested, how many squares are there in the table in which the main hero will be able to form a team of at least $t$ people. Help him to calculate this.",
    "tutorial": "Let's formalize the problem condition. It is required to calculate the number of squares $s$ in the table for which we have inequality $A+B \\geq T$, where $A$ is a $\\text{MEX}$ of positive integers in the sqare and $B$ is a $\\text{MEX}$ of absolute values of all negative integers in the square. Then we denote cost of a square as $A+B$. Note that when the square is expanded, its value cannot decrease. Let's fix the diagonal that contains the upper left and lower right sides of the square. Now, with a fixed lower right cell, we want to maintain the upper left cell of the square that is maximally removed from it so that its cost does not exceed $T-1$. Note that this upper-left boundary can only shift in the direction of moving the right lower one, which means we can use the two pointers technique. We will also need to maintain a set of numbers that are contained in a square. To do this, we will process each cell separately, which are added and removed from our square. Note that for each cell there are no more than $\\min \\{ N, M \\}$ diagonals on which it is possible to construct a square containing this cell, and also note that due to the structure of our solution for each such diagonal, our cell will be added to the set no more than $1$ time. Thus, the total number of additions of cells to our set does not exceed $M N \\cdot \\min \\{N, M \\}$, and accordingly the total number of additions of numbers to the set does not exceed $K \\cdot \\min \\{ N, M \\}$. We will also need to find out the $\\text{MEX}$ of all positive integers in the square, as well as the $\\text{MEX}$ of absolute values of negative integers in the square. Here we need to make another observation about our algorithm. The number of $\\text{MEX}$ queries will not exceed $2MN$. That is, you can use the square roots technique to adding and removing integers in $O(1)$ time, and find out the $\\text{MEX}$ values in $O(\\sqrt K)$ time. To summarize, our algorithm will work in asymptotic time: $O((NM + K) \\cdot \\min \\{ N, M \\} + NM \\sqrt{K})$",
    "tags": [
      "brute force",
      "two pointers"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1754",
    "index": "A",
    "title": "Technical Support",
    "statement": "You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved.\n\nToday you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by \\textbf{one or several} messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions.\n\nDue to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. \\textbf{It is guaranteed that the dialog begins with the question of the client.}\n\nYou have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached.",
    "tutorial": "Let's process each character of the string from left to right and store the number of unanswered questions $cnt$. Initially this value equals to zero. Consider the $i$-th character of the string. If it equals to \"Q\", increase $cnt$ by one. If it equals to \"A\", decrease $cnt$ by one. If $cnt$ has become negative, it means that some of the questions was answered several times. In this case let's assign zero to $cnt$. If $cnt$ will be equal to zero after processing all string, then all questions were answered, and the answer is \"Yes\". Otherwise, the answer is \"No\". Time complexity: $\\mathcal{O}(n)$ for each test case.",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1754",
    "index": "B",
    "title": "Kevin and Permutation",
    "statement": "For his birthday, Kevin received the set of pairwise distinct numbers $1, 2, 3, \\ldots, n$ as a gift.\n\nHe is going to arrange these numbers in a way such that the minimum absolute difference between two consecutive numbers be maximum possible. More formally, if he arranges numbers in order $p_1, p_2, \\ldots, p_n$, he wants to maximize the value $$\\min \\limits_{i=1}^{n - 1} \\lvert p_{i + 1} - p_i \\rvert,$$ where $|x|$ denotes the absolute value of $x$.\n\nHelp Kevin to do that.",
    "tutorial": "Let's prove that the minimum difference of consecutive elements is not greater than $\\lfloor \\frac{n}{2} \\rfloor$. To do it, let's prove that larger value is not achievable. Consider element of a permutation with value $\\lfloor \\frac{n}{2} \\rfloor + 1$. It will have at least one adjacent element in the constructed permutation. And the maximum absolute difference of this element with the adjacent elements is at most $\\lfloor \\frac{n}{2} \\rfloor$. Now we will construct the permutation with the minimum absolute difference of consecutive elements equals to $\\lfloor \\frac{n}{2} \\rfloor$. Assign $x = \\lfloor \\frac{n}{2} + 1 \\rfloor$. Now we can construct such permutation: $x, 1, x + 1, 2, x + 2, \\ldots$. It's easy to see that the minimum absolute difference of consecutive elements equals to $x - 1$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1758",
    "index": "A",
    "title": "SSeeeeiinngg DDoouubbllee",
    "statement": "A palindrome is a string that reads the same backward as forward. For example, the strings $z$, $aaa$, $aba$, and $abccba$ are palindromes, but $codeforces$ and $ab$ are not.\n\nThe double of a string $s$ is obtained by writing each character twice. For example, the double of $seeing$ is $sseeeeiinngg$.\n\nGiven a string $s$, rearrange its double to form a palindrome. Output the rearranged string. It can be proven that such a rearrangement always exists.",
    "tutorial": "Output $s + \\text{reverse}(s)$. It works, since each character in $s$ occurs exactly twice (once in $s$, once in $\\text{reverse}(s)$), and the result is a palindrome.",
    "code": "for _ in range(int(input())):\n    s = input()\n    print(s + s[::-1])",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1758",
    "index": "B",
    "title": "XOR = Average",
    "statement": "You are given an integer $n$. Find a sequence of $n$ integers $a_1, a_2, \\dots, a_n$ such that $1 \\leq a_i \\leq 10^9$ for all $i$ and $$a_1 \\oplus a_2 \\oplus \\dots \\oplus a_n = \\frac{a_1 + a_2 + \\dots + a_n}{n},$$ where $\\oplus$ represents the bitwise XOR.\n\nIt can be proven that there exists a sequence of integers that satisfies all the conditions above.",
    "tutorial": "Let us consider the cases when $n$ is odd and when its even. $n$ is odd: We can see that printing $\\underbrace{1,\\dots,1}_{n\\text{ times}}$ will lead to an average of $1$ and an XOR of $1$ (since $1 \\oplus 1 = 0$). Similarly, you could print any integer $n$ times to pass this case. $n$ is even: We use a slight modification of the solution for odd $n$ here. Instead of printing the same number $n$ times, we print $1, 3, \\underbrace{2, \\dots, 2}_{n-2\\text{ times}}$. Both the XOR and the average of $1$ and $3$ are $2$. Therefore the average of the total sequence remains $2$, and the XOR of the whole sequence is also $2$. Note that there are other possible solutions, but the simplest one is described here.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    print(*[1] if n == 1 else [1 + n % 2] + [2]*(n-2) + [3 - n % 2])",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 900
  },
  {
    "contest_id": "1758",
    "index": "C",
    "title": "Almost All Multiples",
    "statement": "Given two integers $n$ and $x$, a permutation$^{\\dagger}$ $p$ of length $n$ is called funny if $p_i$ is a multiple of $i$ for all $1 \\leq i \\leq n - 1$, $p_n = 1$, and $p_1 = x$.\n\nFind the lexicographically minimal$^{\\ddagger}$ funny permutation, or report that no such permutation exists.\n\n$^{\\dagger}$ A permutation of length $n$ is an array consisting of each of the integers from $1$ to $n$ exactly once.\n\n$^{\\ddagger}$ Let $a$ and $b$ be permutations of length $n$. Then $a$ is lexicographically smaller than $b$ if in the first position $i$ where $a$ and $b$ differ, $a_i < b_i$. A permutation is lexicographically minimal if it is lexicographically smaller than all other permutations.",
    "tutorial": "We start by giving the answer for $n=12$, $k=2$: $[\\color{red}{2}, \\color{red}{4}, 3, \\color{red}{12}, 5, 6, 7, 8, 9, 10, 11, \\color{red}{1}]$ $[\\color{red}{3}, 2, \\color{red}{6}, 4, 5, \\color{red}{12}, 7, 8, 9, 10, 11, \\color{red}{1}].$ As you can see, the array is almost the identity permutation, with certain elements rotated to the left. In particular, these are the elements that you get when you find the longest sequence $a_i$ such that $x \\mid a_1 \\mid a_2 \\mid \\dots \\mid n$ (recall $a \\mid b$ means $a$ divides $b$). For example, $3 \\mid 6 \\mid 12$ and $2 \\mid 4 \\mid 12$. To find this longest sequence, you need to prime factorize $\\frac{n}{x}$. The complexity is $\\mathcal{O}(n \\log n)$. The main idea is intuitive, but the proof is rather long. We include it below. The idea is to look at cycles in the permutation. Consider any cycle of length greater than $1$, say $c_1, c_2, \\dots, c_k$ (that is, $p_{c_1}=c_2$, $p_{c_2}=c_3, \\dots, p_{c_k}=c_1$). We claim that for at least one element $c_i$ of the cycle, $p_{c_i}$ is not a multiple of $c_i$. In fact, we'll show a more general claim: for one element of the cycle $p_{c_i} < c_i$, which implies that $p_{c_i}$ cannot be a multiple of $c_i$. Indeed, let's sum $p_{c_i} - c_i$ over all elements of the cycle. This sum is $0$, because each element appears once before the $-$ sign and once afterwards. Since none of these equal $0$, it follows that at least one of these terms is negative (and at least one is positive). If $p_{c_i} - c_i < 0$, then $p_{c_i} < c_i$, as desired. So in each cycle, we must have at least one element breaking the key claim in the problem. But this claim holds for all $1 \\leq i \\leq n-1$, so the only cycle we can have goes through $p_n$! Indeed, since $p_n=1$ and $p_1=x$, the cycle goes $n \\to 1 \\to x \\to \\dots \\to n$. For all arrows except the first one, we $a \\mid b$ to write $a \\to b$, because only $p_n$ can break the condition. Since we want the permutation to be lexicographically minimal, we want the longest such chain. So we should find the longest sequence of numbers from $x$ to $n$, such that each number divides the previous. If there are multiple such sequences, we need to pick the one that puts smaller numbers earlier, since we want smaller elements earlier on in the sequence. To do this, we can just find the prime factorization of $\\frac{n}{x}$ (it is the longest, since the primes cannot be broken up into smaller factors), sort it, and cycle it.",
    "code": "for _ in range(int(input())):\n    n, x = map(int, input().split())\n    if n % x:\n        print(-1)\n        continue\n    a = list(range(1, n + 1))\n    if x == n:\n        a[0], a[-1] = a[-1], a[0]\n        print(*a)\n        continue\n \n    a[0], a[-1], a[x-1] = x, 1, n\n    x -= 1\n    for i in range(1, n-1):\n        if a[x] % (i + 1) == 0 and a[i] % (x + 1) == 0:\n            a[i], a[x] = a[x], a[i]\n            x = i\n    print(*a)",
    "tags": [
      "greedy",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1758",
    "index": "D",
    "title": "Range = √Sum",
    "statement": "You are given an integer $n$. Find a sequence of $n$ \\textbf{distinct} integers $a_1, a_2, \\dots, a_n$ such that $1 \\leq a_i \\leq 10^9$ for all $i$ and $$\\max(a_1, a_2, \\dots, a_n) - \\min(a_1, a_2, \\dots, a_n)= \\sqrt{a_1 + a_2 + \\dots + a_n}.$$\n\nIt can be proven that there exists a sequence of \\textbf{distinct} integers that satisfies all the conditions above.",
    "tutorial": "Let us consider the cases when $n$ is odd and when its even. $n$ is odd: First, we can start with the $n$ consecutive distinct numbers centered at $n$. The minimum-maximum difference is $n - 1$, and the sum is $n^2$. If we add 2 to each number, the minimum-maximum difference remains the same, and the sum increases to $n^2 + 2n$.Now, we can decrease the minimum by 1 and the increase the maximum by 1. The sum remains at $n^2 + 2n$, while the difference increases to $n + 1$. To make the sum equal $(n + 1)^2 = n^2 + 2n + 1$, we can increase the 2nd last number by 1, which we can do since we previously increased the maximum by 1. As an example, this sequence is followed for $n = 5$: [3, 4, 5, 6, 7] (centered at $5$) [5, 6, 7, 8, 9] (increase by $2$) [4, 6, 7, 8, 10] (shift min/max) [4, 6, 7, 9, 10] (shift 2nd last) Now, we can decrease the minimum by 1 and the increase the maximum by 1. The sum remains at $n^2 + 2n$, while the difference increases to $n + 1$. To make the sum equal $(n + 1)^2 = n^2 + 2n + 1$, we can increase the 2nd last number by 1, which we can do since we previously increased the maximum by 1. As an example, this sequence is followed for $n = 5$: [3, 4, 5, 6, 7] (centered at $5$) [5, 6, 7, 8, 9] (increase by $2$) [4, 6, 7, 8, 10] (shift min/max) [4, 6, 7, 9, 10] (shift 2nd last) $n$ is even: We can let $[a_1, \\dots, a_n] = [n / 2, n / 2 + 1, \\dots, n - 1, n + 1, \\dots, 3n / 2]$. The difference between the minimum and maximum is $n$, and the sum of the numbers equals $n^2$, so this is valid. Other solutions exist, only one is described here. Soon Soon",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    if n % 2 == 0:\n        print(*[i for i in range(n//2, n//2 + n + 1) if i != n])\n    else:\n        a = list(range(n//2 + 3, n//2 + 3 + n))\n        a[0] -= 1\n        a[-1] += 1\n        a[-2] += 1\n        print(*a)",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "math",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1758",
    "index": "E",
    "title": "Tick, Tock",
    "statement": "Tannhaus, the clockmaker in the town of Winden, makes mysterious clocks that measure time in $h$ hours numbered from $0$ to $h-1$. One day, he decided to make a puzzle with these clocks.\n\nThe puzzle consists of an $n \\times m$ grid of clocks, and each clock always displays some hour exactly (that is, it doesn't lie between two hours). In one move, he can choose any row or column and shift all clocks in that row or column one hour forward$^\\dagger$.\n\nThe grid of clocks is called solvable if it is possible to make all the clocks display the same time.\n\nWhile building his puzzle, Tannhaus suddenly got worried that it might not be possible to make the grid solvable. Some cells of the grid have clocks already displaying a certain initial time, while the rest of the cells are empty.\n\nGiven the partially completed grid of clocks, find the number of ways$^\\ddagger$ to assign clocks in the empty cells so that the grid is solvable. The answer can be enormous, so compute it modulo $10^9 + 7$.\n\n$^\\dagger$ If a clock currently displays hour $t$ and is shifted one hour forward, then the clock will instead display hour $(t+1) \\bmod h$.\n\n$^\\ddagger$ Two assignments are different if there exists some cell with a clock that displays a different time in both arrangements.",
    "tutorial": "Notice that a relationship between two clocks with assigned values on the grid on different rows but the same column, that is, $g_{x, z}$ and $g_{y, z}$, can be represented as $g_{y, z} \\equiv g_{x, z} + d \\pmod{h}$, where $0 \\le d < h$. Now, for every $1 \\le i \\le m$, $g_{y, i} \\equiv g_{x, i} + d \\pmod{h}$. Using these relationships, we can create a weighted directed graph using our rows as nodes. Obviously, no solutions exist if there are discrepancies in the graph $\\pmod{h}$, no solution exists. Now, for each connected component, if there is an assigned value in one of the rows it contains, we can determine all of the other values for that column in the connected component. We can merge different connected components $i, j$ by choosing a common difference $d_{i, j}$ for these components. This needs to be done (connected components - 1) times, and there are $h$ different ways to choose a common difference when combining different components, resulting in $h^{\\text{connected components} - 1}$ different ways to combine all components into one connected component. This leaves us with columns that are fully empty, i.e., they consist $\\textit{only}$ of unassigned clocks. As all rows are in one connected component at this point, assigning a clock in one empty column results in all other clocks in that column becoming assigned values too. There are $h^{\\text{empty columns}}$ different ways to assign clocks to these empty columns. Thus, overall, our solution is $h^{\\text{connected components} + \\text{empty columns} - 1}$.",
    "code": "import io, os\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n \nfor _ in range(int(input())):\n    n, m, h = map(int, input().split())\n    a = [list(map(int, input().split())) for i in range(n)]\n \n    graph = [[] for __ in range(n + m)]\n    for i in range(n):\n        for j in range(m):\n            if a[i][j] == -1: continue\n            graph[i] += [n + j]\n            graph[n + j] += [i]\n \n    visited = [False] * (n + m)\n    rowVals, colVals = [-1] * n, [-1] * m\n    count = 0\n    for i in range(n + m):\n        if visited[i]: continue\n        count += 1\n        queue = [i]\n        while queue:\n            x = queue.pop()\n            visited[x] = True\n            if x < n:\n                if rowVals[x] == -1:\n                    rowVals[x] = 0\n                for y in range(m):\n                    if a[x][y] != -1 and colVals[y] == -1:\n                        colVals[y] = (-rowVals[x] - a[x][y]) % h\n                        queue += [y + n]\n            else:\n                x -= n\n                if colVals[x] == -1:\n                    colVals[x] = 0\n                for y in range(n):\n                    if a[y][x] != -1 and rowVals[y] == -1:\n                        rowVals[y] = (-colVals[x] - a[y][x]) % h\n                        queue += [y]\n \n    pos = True\n    for i in range(n):\n        for j in range(m):\n            if a[i][j] != -1:\n                pos &= (a[i][j] + rowVals[i] + colVals[j]) % h == 0\n \n    if not pos:\n        print(0)\n    else:\n        print(pow(h, count - 1, 10**9 + 7))",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1758",
    "index": "F",
    "title": "Decent Division",
    "statement": "A binary string is a string where every character is $0$ or $1$. Call a binary string decent if it has an equal number of $0$s and $1$s.\n\nInitially, you have an infinite binary string $t$ whose characters are all $0$s. You are given a sequence $a$ of $n$ updates, where $a_i$ indicates that the character at index $a_i$ will be flipped ($0 \\leftrightarrow 1$). You need to keep and modify after each update a set $S$ of \\textbf{disjoint} ranges such that:\n\n- for each range $[l,r]$, the substring $t_l \\dots t_r$ is a decent binary string, and\n- for all indices $i$ such that $t_i = 1$, there exists $[l,r]$ in $S$ such that $l \\leq i \\leq r$.\n\nYou only need to output the ranges that are added to or removed from $S$ after each update. You can only add or remove ranges from $S$ at most $\\mathbf{10^6}$ times.\n\nMore formally, let $S_i$ be the set of ranges after the $i$-th update, where $S_0 = \\varnothing$ (the empty set). Define $X_i$ to be the set of ranges removed after update $i$, and $Y_i$ to be the set of ranges added after update $i$. Then for $1 \\leq i \\leq n$, $S_i = (S_{i - 1} \\setminus X_i) \\cup Y_i$. The following should hold for all $1 \\leq i \\leq n$:\n\n- $\\forall a,b \\in S_i, (a \\neq b) \\rightarrow (a \\cap b = \\varnothing)$;\n- $X_i \\subseteq S_{i - 1}$;\n- $(S_{i-1} \\setminus X_i) \\cap Y_i = \\varnothing$;\n- $\\displaystyle\\sum_{i = 1}^n {(|X_i| + |Y_i|)} \\leq 10^6$.",
    "tutorial": "After each update, we want to maintain the invariant that each interval is balanced, and additionally that there is a gap containing at least one zero in between each pair of consecutive intervals. Since every $\\texttt{1}$ must be contained in an interval, this is equivalent to having non-empty gaps between consecutive intervals after an update. There are several cases we need to handle. Case 1: Bit $a_i$ is changed from $\\texttt{0}$ to $\\texttt{1}$. Case 1a: Bit $a_i$ is contained in an interval after the previous updateIf we are inside an interval, then we want to grow the interval that contains it by 2 zeros to maintain balance. If the interval containing $a_i$ is $[l, r]$, then we can expand it to $[l, r + 1]$. Since there is at least one $\\texttt{0}$ after each interval, $a_{r + 1} = 0$, so this contains one of the two zeroes we need. If there is another interval $r + 2 \\in [l', r']$, then increasing the right bound again by 1 would overlap with this interval. In this case, We know that $a_{r' + 1} = 0$ as well, so we can merge both intervals together into $[l, r' + 1]$ to get a total of two new zeros. $[l', r']$ was also previously balanced, so the interval is still balanced. In this case, we removed two intervals and added one interval, so a total of three operations were used. If there is no intervals where $r + 2 \\in [l', r']$, then $a_{r + 2} = 0$, so we can simply expand the current interval once more to $[l, r + 2]$. One interval was removed and one interval was added, so a total of two operations were used. Case 1b: Bit $a_i$ is not contained in an interval.If there exists an interval where $i + 1 \\in [i + 1, r]$, then we can expand it to $[k, r + 1]$. This interval is directly after $a_i$, so expanding it by one to the left will include an extra $\\texttt{1}$. $a_{r + 1} = 0$ since it is part of the gap between two intervals, so including it balances $a_i$. One interval was removed and one interval was added, so a total of two operations were used. If there is no interval where $i + 1 \\in [i + 1, r]$, then $a_{i + 1} = 0$. Therefore, we can simply add $[i, i + 1]$, which is balanced. One interval was added, so a total of one operation was used. In both cases, after adding a new interval to the set, we can merge with any adjacent intervals to the left or right. This will maintain the invariant that there is a gap between consecutive ranges as mentioned earlier. We merge at most once to the left and one to the right. Since the maximum number of operations done earlier is 3, the maximum number of operations in total is 5 in this case. Case 1a: Bit $a_i$ is contained in an interval after the previous updateIf we are inside an interval, then we want to grow the interval that contains it by 2 zeros to maintain balance. If the interval containing $a_i$ is $[l, r]$, then we can expand it to $[l, r + 1]$. Since there is at least one $\\texttt{0}$ after each interval, $a_{r + 1} = 0$, so this contains one of the two zeroes we need. If there is another interval $r + 2 \\in [l', r']$, then increasing the right bound again by 1 would overlap with this interval. In this case, We know that $a_{r' + 1} = 0$ as well, so we can merge both intervals together into $[l, r' + 1]$ to get a total of two new zeros. $[l', r']$ was also previously balanced, so the interval is still balanced. In this case, we removed two intervals and added one interval, so a total of three operations were used. If there is no intervals where $r + 2 \\in [l', r']$, then $a_{r + 2} = 0$, so we can simply expand the current interval once more to $[l, r + 2]$. One interval was removed and one interval was added, so a total of two operations were used. If we are inside an interval, then we want to grow the interval that contains it by 2 zeros to maintain balance. If the interval containing $a_i$ is $[l, r]$, then we can expand it to $[l, r + 1]$. Since there is at least one $\\texttt{0}$ after each interval, $a_{r + 1} = 0$, so this contains one of the two zeroes we need. If there is another interval $r + 2 \\in [l', r']$, then increasing the right bound again by 1 would overlap with this interval. In this case, We know that $a_{r' + 1} = 0$ as well, so we can merge both intervals together into $[l, r' + 1]$ to get a total of two new zeros. $[l', r']$ was also previously balanced, so the interval is still balanced. In this case, we removed two intervals and added one interval, so a total of three operations were used. If there is no intervals where $r + 2 \\in [l', r']$, then $a_{r + 2} = 0$, so we can simply expand the current interval once more to $[l, r + 2]$. One interval was removed and one interval was added, so a total of two operations were used. Case 1b: Bit $a_i$ is not contained in an interval.If there exists an interval where $i + 1 \\in [i + 1, r]$, then we can expand it to $[k, r + 1]$. This interval is directly after $a_i$, so expanding it by one to the left will include an extra $\\texttt{1}$. $a_{r + 1} = 0$ since it is part of the gap between two intervals, so including it balances $a_i$. One interval was removed and one interval was added, so a total of two operations were used. If there is no interval where $i + 1 \\in [i + 1, r]$, then $a_{i + 1} = 0$. Therefore, we can simply add $[i, i + 1]$, which is balanced. One interval was added, so a total of one operation was used. If there exists an interval where $i + 1 \\in [i + 1, r]$, then we can expand it to $[k, r + 1]$. This interval is directly after $a_i$, so expanding it by one to the left will include an extra $\\texttt{1}$. $a_{r + 1} = 0$ since it is part of the gap between two intervals, so including it balances $a_i$. One interval was removed and one interval was added, so a total of two operations were used. If there is no interval where $i + 1 \\in [i + 1, r]$, then $a_{i + 1} = 0$. Therefore, we can simply add $[i, i + 1]$, which is balanced. One interval was added, so a total of one operation was used. In both cases, after adding a new interval to the set, we can merge with any adjacent intervals to the left or right. This will maintain the invariant that there is a gap between consecutive ranges as mentioned earlier. We merge at most once to the left and one to the right. Since the maximum number of operations done earlier is 3, the maximum number of operations in total is 5 in this case. Case 2: Bit $a_i$ is changed from $\\texttt{1}$ to $\\texttt{0}$. Suppose that $i \\in [l, r]$. In this case, we want to somehow split the interval into two balanced portions. Now, suppose we compute the prefix sums of the balance, where $\\texttt{0}$ corresponds to $-1$ and $\\texttt{1}$ corresponds to $+1$. If $x$ is the first location where the prefix sum equals $-2$, then we claim that we can split the interval into $[l, x - 2]$ and $[x + 1, r]$. To prove this, note that the balance of the empty prefix is 0, so before the prefix sum equals $-2$ for the first time, it must have gone $..., 0, -1, -2$. To have two decreases in a row, we must have $a_{x - 1} = a_x = 0$. In the interval $[l, x - 2]$, the final balance prefix sum is $0$, so the first interval is balanced. Since we changed a $\\texttt{1}$ to a $\\texttt{1}$ and removed two $\\texttt{0}$s, the first interval being balanced implies that the second interval is balanced as well. In addition, since the original interval satisfied the separation invariant, and the new intervals are separated by two $\\texttt{0}$s, the separation invariant is still satisfied. To compute the first time when the balance prefix sum equals -2, we can use binary search on the interval using a lazy segment tree. The segment tree represents a global balance prefix sum, and we can range query the minimum balance on an interval. We can binary search for the lowest index on the interval where the minimum prefix sum is less than -2. In this case, we removed one interval and added two new intervals, for a total of three operations. Suppose that $i \\in [l, r]$. In this case, we want to somehow split the interval into two balanced portions. Now, suppose we compute the prefix sums of the balance, where $\\texttt{0}$ corresponds to $-1$ and $\\texttt{1}$ corresponds to $+1$. If $x$ is the first location where the prefix sum equals $-2$, then we claim that we can split the interval into $[l, x - 2]$ and $[x + 1, r]$. To prove this, note that the balance of the empty prefix is 0, so before the prefix sum equals $-2$ for the first time, it must have gone $..., 0, -1, -2$. To have two decreases in a row, we must have $a_{x - 1} = a_x = 0$. In the interval $[l, x - 2]$, the final balance prefix sum is $0$, so the first interval is balanced. Since we changed a $\\texttt{1}$ to a $\\texttt{1}$ and removed two $\\texttt{0}$s, the first interval being balanced implies that the second interval is balanced as well. In addition, since the original interval satisfied the separation invariant, and the new intervals are separated by two $\\texttt{0}$s, the separation invariant is still satisfied. To compute the first time when the balance prefix sum equals -2, we can use binary search on the interval using a lazy segment tree. The segment tree represents a global balance prefix sum, and we can range query the minimum balance on an interval. We can binary search for the lowest index on the interval where the minimum prefix sum is less than -2. In this case, we removed one interval and added two new intervals, for a total of three operations. In both cases, we use at most 5 operations in a single step, so we in total use at most $5n$ operations, which fits in our bound. In practice, this upper bound is quite loose. Because of the binary search on the lazy segment tree, the time complexity for this solution is $O(n \\log^2 n)$. Note that this can be optimized to $O(n \\log n)$ by optimizing the binary search, but this was not required.",
    "code": "class LazySegmentTree:\n    def __init__(self, array):\n        self.n = len(array)\n        self.size = 1 << (self.n - 1).bit_length()\n        self.func = min\n        self.default = float(\"inf\")\n        self.data = [self.default] * (2 * self.size)\n        self.lazy = [0] * (2 * self.size)\n        self.process(array)\n \n    def process(self, array):\n        self.data[self.size : self.size+self.n] = array\n        for i in range(self.size-1, -1, -1):\n            self.data[i] = self.func(self.data[2*i], self.data[2*i+1])\n \n    def push(self, index):\n        \"\"\"Push the information of the root to it's children!\"\"\"\n        self.lazy[2*index] += self.lazy[index]\n        self.lazy[2*index+1] += self.lazy[index]\n        self.data[2 * index] += self.lazy[index]\n        self.data[2 * index + 1] += self.lazy[index]\n        self.lazy[index] = 0\n \n    def build(self, index):\n        \"\"\"Build data with the new changes!\"\"\"\n        index >>= 1\n        while index:\n            self.data[index] = self.func(self.data[2*index], self.data[2*index+1]) + self.lazy[index]\n            index >>= 1\n \n    def query(self, alpha, omega):\n        \"\"\"Returns the result of function over the range (inclusive)!\"\"\"\n        res = self.default\n        alpha += self.size\n        omega += self.size + 1\n        for i in reversed(range(1, alpha.bit_length())):\n            self.push(alpha >> i)\n        for i in reversed(range(1, (omega - 1).bit_length())):\n            self.push((omega-1) >> i)\n        while alpha < omega:\n            if alpha & 1:\n                res = self.func(res, self.data[alpha])\n                alpha += 1\n            if omega & 1:\n                omega -= 1\n                res = self.func(res, self.data[omega])\n            alpha >>= 1\n            omega >>= 1\n        return res\n \n    def update(self, alpha, omega, value):\n        \"\"\"Increases all elements in the range (inclusive) by given value!\"\"\"\n        alpha += self.size\n        omega += self.size + 1\n        l, r = alpha, omega\n        while alpha < omega:\n            if alpha & 1:\n                self.data[alpha] += value\n                self.lazy[alpha] += value\n                alpha += 1\n            if omega & 1:\n                omega -= 1\n                self.data[omega] += value\n                self.lazy[omega] += value\n            alpha >>= 1\n            omega >>= 1\n        self.build(l)\n        self.build(r-1)\n \nclass SortedList:\n    def __init__(self, iterable=[], _load=200):\n        \"\"\"Initialize sorted list instance.\"\"\"\n        values = sorted(iterable)\n        self._len = _len = len(values)\n        self._load = _load\n        self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]\n        self._list_lens = [len(_list) for _list in _lists]\n        self._mins = [_list[0] for _list in _lists]\n        self._fen_tree = []\n        self._rebuild = True\n \n    def _fen_build(self):\n        \"\"\"Build a fenwick tree instance.\"\"\"\n        self._fen_tree[:] = self._list_lens\n        _fen_tree = self._fen_tree\n        for i in range(len(_fen_tree)):\n            if i | i + 1 < len(_fen_tree):\n                _fen_tree[i | i + 1] += _fen_tree[i]\n        self._rebuild = False\n \n    def _fen_update(self, index, value):\n        \"\"\"Update `fen_tree[index] += value`.\"\"\"\n        if not self._rebuild:\n            _fen_tree = self._fen_tree\n            while index < len(_fen_tree):\n                _fen_tree[index] += value\n                index |= index + 1\n \n    def _fen_query(self, end):\n        \"\"\"Return `sum(_fen_tree[:end])`.\"\"\"\n        if self._rebuild:\n            self._fen_build()\n \n        _fen_tree = self._fen_tree\n        x = 0\n        while end:\n            x += _fen_tree[end - 1]\n            end &= end - 1\n        return x\n \n    def _fen_findkth(self, k):\n        \"\"\"Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).\"\"\"\n        _list_lens = self._list_lens\n        if k < _list_lens[0]:\n            return 0, k\n        if k >= self._len - _list_lens[-1]:\n            return len(_list_lens) - 1, k + _list_lens[-1] - self._len\n        if self._rebuild:\n            self._fen_build()\n \n        _fen_tree = self._fen_tree\n        idx = -1\n        for d in reversed(range(len(_fen_tree).bit_length())):\n            right_idx = idx + (1 << d)\n            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:\n                idx = right_idx\n                k -= _fen_tree[idx]\n        return idx + 1, k\n \n    def _delete(self, pos, idx):\n        \"\"\"Delete value at the given `(pos, idx)`.\"\"\"\n        _lists = self._lists\n        _mins = self._mins\n        _list_lens = self._list_lens\n \n        self._len -= 1\n        self._fen_update(pos, -1)\n        del _lists[pos][idx]\n        _list_lens[pos] -= 1\n \n        if _list_lens[pos]:\n            _mins[pos] = _lists[pos][0]\n        else:\n            del _lists[pos]\n            del _list_lens[pos]\n            del _mins[pos]\n            self._rebuild = True\n \n    def _loc_left(self, value):\n        \"\"\"Return an index pair that corresponds to the first position of `value` in the sorted list.\"\"\"\n        if not self._len:\n            return 0, 0\n \n        _lists = self._lists\n        _mins = self._mins\n \n        lo, pos = -1, len(_lists) - 1\n        while lo + 1 < pos:\n            mi = (lo + pos) >> 1\n            if value <= _mins[mi]:\n                pos = mi\n            else:\n                lo = mi\n \n        if pos and value <= _lists[pos - 1][-1]:\n            pos -= 1\n \n        _list = _lists[pos]\n        lo, idx = -1, len(_list)\n        while lo + 1 < idx:\n            mi = (lo + idx) >> 1\n            if value <= _list[mi]:\n                idx = mi\n            else:\n                lo = mi\n \n        return pos, idx\n \n    def _loc_right(self, value):\n        \"\"\"Return an index pair that corresponds to the last position of `value` in the sorted list.\"\"\"\n        if not self._len:\n            return 0, 0\n \n        _lists = self._lists\n        _mins = self._mins\n \n        pos, hi = 0, len(_lists)\n        while pos + 1 < hi:\n            mi = (pos + hi) >> 1\n            if value < _mins[mi]:\n                hi = mi\n            else:\n                pos = mi\n \n        _list = _lists[pos]\n        lo, idx = -1, len(_list)\n        while lo + 1 < idx:\n            mi = (lo + idx) >> 1\n            if value < _list[mi]:\n                idx = mi\n            else:\n                lo = mi\n \n        return pos, idx\n \n    def add(self, value):\n        \"\"\"Add `value` to sorted list.\"\"\"\n        _load = self._load\n        _lists = self._lists\n        _mins = self._mins\n        _list_lens = self._list_lens\n \n        self._len += 1\n        if _lists:\n            pos, idx = self._loc_right(value)\n            self._fen_update(pos, 1)\n            _list = _lists[pos]\n            _list.insert(idx, value)\n            _list_lens[pos] += 1\n            _mins[pos] = _list[0]\n            if _load + _load < len(_list):\n                _lists.insert(pos + 1, _list[_load:])\n                _list_lens.insert(pos + 1, len(_list) - _load)\n                _mins.insert(pos + 1, _list[_load])\n                _list_lens[pos] = _load\n                del _list[_load:]\n                self._rebuild = True\n        else:\n            _lists.append([value])\n            _mins.append(value)\n            _list_lens.append(1)\n            self._rebuild = True\n \n    def discard(self, value):\n        \"\"\"Remove `value` from sorted list if it is a member.\"\"\"\n        _lists = self._lists\n        if _lists:\n            pos, idx = self._loc_right(value)\n            if idx and _lists[pos][idx - 1] == value:\n                self._delete(pos, idx - 1)\n \n    def remove(self, value):\n        \"\"\"Remove `value` from sorted list; `value` must be a member.\"\"\"\n        _len = self._len\n        self.discard(value)\n        if _len == self._len:\n            raise ValueError('{0!r} not in list'.format(value))\n \n    def bisect_left(self, value):\n        \"\"\"Return the first index to insert `value` in the sorted list.\"\"\"\n        pos, idx = self._loc_left(value)\n        return self._fen_query(pos) + idx\n \n    def bisect_right(self, value):\n        \"\"\"Return the last index to insert `value` in the sorted list.\"\"\"\n        pos, idx = self._loc_right(value)\n        return self._fen_query(pos) + idx\n \n    def __getitem__(self, index):\n        \"\"\"Lookup value at `index` in sorted list.\"\"\"\n        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)\n        return self._lists[pos][idx]\n# ----------------------------------------------------------------------------------------------------------------------\nimport io, os\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n \nmaxRange = 400005\nst = LazySegmentTree(list(range(0, -maxRange - 1, -1)))\nsl = SortedList([(-2, -2), (maxRange + 2, maxRange + 2)])\n \nfor __ in range(int(input())):\n    x = int(input())\n    index = sl.bisect_left((x + 1, -1)) - 1\n    prevStart, prevEnd = sl.__getitem__(index)\n    nextStart, nextEnd = sl.__getitem__(index + 1)\n    to_add, to_remove = [], []\n \n    if prevEnd < x:\n        # bit x is not set and no segment overlaps with x\n        st.update(x, maxRange, 2)\n        newStart, newEnd = x, x + 1\n        if prevEnd == x - 1:\n            sl.remove((prevStart, prevEnd))\n            to_remove += [(prevStart, prevEnd)]\n            newStart = prevStart\n        if nextStart == x + 1:\n            newEnd = nextEnd + 1\n            sl.remove((nextStart, nextEnd))\n            to_remove += [(nextStart, nextEnd)]\n \n        start, end = sl.__getitem__(sl.bisect_left((newEnd + 1, newEnd + 1)))\n        if start == newEnd + 1:\n            newEnd = end\n            sl.remove((start, end))\n            to_remove += [(start, end)]\n        sl.add((newStart, newEnd))\n        to_add += [(newStart, newEnd)]\n    else:\n        isSet = st.query(x-1, x) != st.query(x, x)\n        if not isSet:\n            # bit x is not set and x is included in the segment\n            st.update(x, maxRange, 2)\n            sl.remove((prevStart, prevEnd))\n            to_remove += [(prevStart, prevEnd)]\n            newStart, newEnd = prevStart, prevEnd + 2\n            if nextStart == prevEnd + 2:\n                newEnd = nextEnd + 1\n                sl.remove((nextStart, nextEnd))\n                to_remove += [(nextStart, nextEnd)]\n \n            start, end = sl.__getitem__(sl.bisect_left((newEnd + 1, newEnd + 1)))\n            if start == newEnd + 1:\n                newEnd = end\n                sl.remove((start, end))\n                to_remove += [(start, end)]\n            sl.add((newStart, newEnd))\n            to_add += [(newStart, newEnd)]\n \n        else:\n            # bit x is set\n            st.update(x, maxRange, -2)\n            target = st.query(prevStart - 1, prevStart - 1) - 2\n            alpha, omega = prevStart, prevEnd\n            while alpha < omega:\n                mid = (alpha + omega) // 2\n                if st.query(prevStart, mid) <= target:\n                    omega = mid\n                else:\n                    alpha = mid + 1\n            sl.remove((prevStart, prevEnd))\n            to_remove += [(prevStart, prevEnd)]\n            if alpha - 1 != prevStart:\n                sl.add((prevStart, alpha - 2))\n                to_add += [(prevStart, alpha - 2)]\n            if alpha != prevEnd:\n                sl.add((alpha + 1, prevEnd))\n                to_add += [(alpha + 1, prevEnd)]\n \n    print(len(to_remove))\n    for p, q in to_remove:\n        print(p, q)\n    print(len(to_add))\n    for p, q in to_add:\n        print(p, q)",
    "tags": [
      "constructive algorithms",
      "data structures"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1759",
    "index": "A",
    "title": "Yes-Yes?",
    "statement": "You talked to Polycarp and asked him a question. You know that when he wants to answer \"yes\", he repeats Yes many times in a row.\n\nBecause of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.\n\nDetermine if it is true that the given string $s$ is a substring of YesYesYes... (Yes repeated many times in a row).",
    "tutorial": "Note that it is enough to consider the string $full =$YesYes...Yes, where Yes is written $18$ times, since $18 \\cdot 3 = 54$, and our substring $s$ has size $|s| \\le 50$. Then we just use the built-in function $find$ to find out if our string $s$ is a substring of the string $full$.",
    "code": "full = 'Yes' * 18\nt = int(input())\nfor _ in range(t):\n    if full.find(input()) >= 0:\n        print('YES')\n    else:\n        print('NO')",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1759",
    "index": "B",
    "title": "Lost Permutation",
    "statement": "A sequence of $n$ numbers is called a permutation if it contains all integers from $1$ to $n$ exactly once. For example, the sequences [$3, 1, 4, 2$], [$1$] and [$2,1$] are permutations, but [$1,2,1$], [$0,1$] and [$1,3,4$] — are not.\n\nPolycarp lost his favorite permutation and found only some of its elements — the numbers $b_1, b_2, \\dots b_m$. He is sure that the sum of the lost elements equals $s$.\n\nDetermine whether one or more numbers can be appended to the given sequence $b_1, b_2, \\dots b_m$ such that the sum of the added numbers equals $s$, and the resulting new array is a permutation?",
    "tutorial": "Let us add to $s$ the sum of the elements of the array $b$ and try to find a suitable permutation. To do this, greedily add elements $1, 2, \\dots, cnt$ until their sum is less than $s$. And at the end we will check that the sum has matched. Also check that the maximal element from $b$: $max(b) \\le cnt$, and that the total elements in $b$: $n \\le cnt$.",
    "code": "t = int(input())\nfor _ in range(t):\n    n, s = map(int, input().split())\n    a = [int(x) for x in input().split()]\n    s += sum(a)\n    sm = 0\n    cnt = 0\n    for i in range(1, s + 1):\n        if sm >= s:\n            break\n        sm += i\n        cnt = i\n    if sm != s or max(a) > cnt or cnt <= n:\n        print(\"NO\");\n    else:\n        print(\"YES\")",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1759",
    "index": "C",
    "title": "Thermostat",
    "statement": "Vlad came home and found out that someone had reconfigured the old thermostat to the temperature of $a$.\n\nThe thermostat can only be set to a temperature from $l$ to $r$ inclusive, the temperature cannot change by less than $x$. Formally, in one operation you can reconfigure the thermostat from temperature $a$ to temperature $b$ if $|a - b| \\ge x$ and $l \\le b \\le r$.\n\nYou are given $l$, $r$, $x$, $a$ and $b$. Find the minimum number of operations required to get temperature $b$ from temperature $a$, or say that it is impossible.",
    "tutorial": "First let's consider the cases when the answer exists: If $a=b$, then the thermostat is already set up and the answer is $0$. else if $|a - b| \\ge x$, then it is enough to reconfigure the thermostat in $1$ operation. else if exist such temperature $c$, that $|a - c| \\ge x$ and $|b - c| \\ge x$, then you can configure the thermostat in $2$ operations. If such $c$ exists between $l$ and $r$, we can chose one of bounds: $a \\rightarrow l \\rightarrow b$ or $a \\rightarrow r \\rightarrow b$. we need to make $3$ operations if times if we cannot reconfigure through one of the boundaries as above, but we can through both: $a \\rightarrow l \\rightarrow r \\rightarrow b$ or $a \\rightarrow r \\rightarrow l \\rightarrow b$ If we can't get the temperature $b$ in one of these ways, the answer is $-1$.",
    "code": "def solve():\n    l, r, x = map(int, input().split())\n    a, b = map(int, input().split())\n    if a == b:\n        return 0\n    if abs(a - b) >= x:\n        return 1\n    if r - max(a, b) >= x or min(a, b) - l >= x:\n        return 2\n    if r - b >= x and a - l >= x or r - a >= x and b - l >= x:\n        return 3\n    return -1\n\n\nt = int(input())\nfor _ in range(t):\n    print(solve())",
    "tags": [
      "greedy",
      "math",
      "shortest paths"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1759",
    "index": "D",
    "title": "Make It Round",
    "statement": "Inflation has occurred in Berlandia, so the store needs to change the price of goods.\n\nThe current price of good $n$ is given. It is allowed to increase the price of the good by $k$ times, with $1 \\le k \\le m$, k is an integer. Output the roundest possible new price of the good. That is, the one that has the maximum number of zeros at the end.\n\nFor example, the number 481000 is more round than the number 1000010 (three zeros at the end of 481000 and only one at the end of 1000010).\n\nIf there are several possible variants, output the one in which the new price is maximal.\n\nIf it is impossible to get a rounder price, output $n \\cdot m$ (that is, the maximum possible price).",
    "tutorial": "The answer is $n \\cdot k$. First, count two numbers: $cnt_2, cnt_5$ which denote the degree of occurrence of $2$ and $5$ in the number $n$ respectively, that is $n = 2^cnt_2 \\cdot 5^cnt_5 \\cdot d$. Where $d$ is not divisible by either $2$ or $5$. Now while $cnt_2 \\neq cnt_5$ we will increase the corresponding value. For example, if $cnt_2 < cnt_5$, then as long as $cnt_2 \\neq cnt_5$ and at that $k \\cdot 2 \\le m$ we will increase $cnt_2$ by $1$ and multiply $k$ by $2$ times. That way we can get the most round number possible by spending the least possible $k$. Now we either have $cnt_2 = cnt_5$, or $k \\cdot 5 > m$ or $k \\cdot 2 > m$. Then in the first case, we will multiply the number $k$ by $10$ as long as we can. That is, until $k \\cdot 10 \\le m$. Now in either case we have: $k \\cdot 10 > m$. Then $\\lfloor \\frac{m}{k} \\rfloor = x < 10$. Then we multiply $k$ by $x$ times and get our desired answer. In the last step, we can no longer get a rounder number, but just find the maximal possible number.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\nusing ll = long long;\n\nvoid solve() {\n    ll n,m; cin >> n >> m;\n    ll n0 = n;\n    int cnt2 = 0, cnt5 = 0;\n    ll k = 1;\n    while (n > 0 && n % 2 == 0) {\n        n /= 2;\n        cnt2++;\n    }\n    while (n > 0 && n % 5 == 0) {\n        n /= 5;\n        cnt5++;\n    }\n    while (cnt2 < cnt5 && k * 2 <= m) {\n        cnt2++;\n        k *= 2;\n    }\n    while (cnt5 < cnt2 && k * 5 <= m) {\n        cnt5++;\n        k *= 5;\n    }\n    while (k * 10 <= m) {\n        k *= 10;\n    }\n    if (k == 1) {\n        cout << n0 * m << endl;\n    } else {\n        k *= m / k; // 1 <= m/k < 10\n        cout << n0 * k << endl;\n    }\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1759",
    "index": "E",
    "title": "The Humanoid",
    "statement": "There are $n$ astronauts working on some space station. An astronaut with the number $i$ ($1 \\le i \\le n$) has power $a_i$.\n\nAn evil humanoid has made his way to this space station. The power of this humanoid is equal to $h$. Also, the humanoid took with him \\textbf{two} green serums and \\textbf{one} blue serum.\n\nIn one second , a humanoid can do any of three actions:\n\n- to absorb an astronaut with power \\textbf{strictly less} humanoid power;\n- to use green serum, if there is still one left;\n- to use blue serum, if there is still one left.\n\nWhen an astronaut with power $a_i$ is absorbed, this astronaut disappears, and power of the humanoid increases by $\\lfloor \\frac{a_i}{2} \\rfloor$, that is, an integer part of $\\frac{a_i}{2}$. For example, if a humanoid absorbs an astronaut with power $4$, its power increases by $2$, and if a humanoid absorbs an astronaut with power $7$, its power increases by $3$.\n\nAfter using the green serum, this serum disappears, and the power of the humanoid doubles, so it increases by $2$ times.\n\nAfter using the blue serum, this serum disappears, and the power of the humanoid triples, so it increases by $3$ times.\n\nThe humanoid is wondering what the maximum number of astronauts he will be able to absorb if he acts optimally.",
    "tutorial": "Let's make two obvious remarks: If we can absorb two astronauts with power $x \\le y$, then we can always first absorb an astronaut with power $x$, and then an astronaut with power $y$; If we can absorb some astronaut, it is effective for us to do it right now. Let's sort the astronauts powers in increasing order. Now let's lock the sequence of serums we use. There are only three of them: blue serum can be the first, second or third. Let's absorb the astronauts in increasing order of their powers, and if we can't, then use the next serum in a locked sequence or stop. This solution works for $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 200200;\n\nint n;\nint arr[MAXN];\n\nint solve(int i, long long h, int s2, int s3) {\n\tif (i == n) return 0;\n\tif (arr[i] < h)\n\t\treturn solve(i + 1, h + (arr[i] / 2), s2, s3) + 1;\n\tint ans1 = (s2 ? solve(i, h * 2, s2 - 1, s3) : 0);\n\tint ans2 = (s3 ? solve(i, h * 3, s2, s3 - 1) : 0);\n\treturn max(ans1, ans2);\n}\n\nint main() {\n\tint t; cin >> t;\n\twhile(t--) {\n\t\tlong long h; cin >> n >> h;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tcin >> arr[i];\n\t\tsort(arr, arr + n);\n\t\tcout << solve(0, h, 2, 1) << endl;\n\t}\n}",
    "tags": [
      "brute force",
      "dp",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1759",
    "index": "F",
    "title": "All Possible Digits",
    "statement": "A positive number $x$ of length $n$ in base $p$ ($2 \\le p \\le 10^9$) is written on the blackboard. The number $x$ is given as a sequence $a_1, a_2, \\dots, a_n$ ($0 \\le a_i < p$) — the digits of $x$ in order from left to right (most significant to least significant).\n\nDmitry is very fond of all the digits of this number system, so he wants to see each of them at least once.\n\nIn one operation, he can:\n\n- take any number $x$ written on the board, increase it by $1$, and write the new value $x + 1$ on the board.\n\nFor example, $p=5$ and $x=234_5$.\n\n- Initially, the board contains the digits $2$, $3$ and $4$;\n- Dmitry increases the number $234_5$ by $1$ and writes down the number $240_5$. On the board there are digits $0, 2, 3, 4$;\n- Dmitry increases the number $240_5$ by $1$ and writes down the number $241_5$. Now the board contains all the digits from $0$ to $4$.\n\nYour task is to determine the minimum number of operations required to make all the digits from $0$ to $p-1$ appear on the board at least once.",
    "tutorial": "If all digits from $0$ to $p-1$ are initially present in the number, then the answer is $0$. Each time we will increase the number by $1$. If the last digit is less than $p-1$, then only it will change. Otherwise, all digits equal to $p-1$ at the end will become equal to $0$, and the previous one will increase by $1$ (or a new digit equal to $1$ will be added if all digits were equal to $p-1$). For a $p-1$ operation, the last digit will run through all possible values. However, we can get all the numbers earlier. We will solve the problem using binary search, sorting through the number of operations. We can have 2 options: whether $0$ was at the end or not. Depending on this, one or two subsegments of the segment $[0, p-1]$ - a subsegment in the middle or a prefix and a suffix remained uncovered by the last digit of the number. They need to be completely covered with numbers that were already in positions, except for the last one - these are the original numbers and, in case there was $0$ at the end, the number into which the transfer was made. There are at most $n+1$ of them.",
    "code": "#pragma GCC optimize(\"Ofast\")\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#include <ext/pb_ds/assoc_container.hpp>\n\nusing namespace __gnu_pbds;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef tree<pair<int, int>, null_type, less<>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\n\nint newDigit = -1;\n\nbool check(set<int> digits, int l, int r, bool useNewDigit) {\n    for (int i = l; i <= r; ++i) {\n        if (useNewDigit && i == newDigit) {\n            continue;\n        }\n        if (!digits.count(i)) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid solve() {\n    int n, p;\n    cin >> n >> p;\n    vector<int> a(n + 1);\n    set<int> digits;\n    for (int i = 1; i <= n; ++i) {\n        cin >> a[i];\n        digits.insert(a[i]);\n    }\n    if (digits.size() == p) {\n        cout << \"0\\n\";\n        return;\n    }\n    for (int i = n - 1; i >= 0; --i) {\n        if (a[i] < p - 1) {\n            newDigit = a[i] + 1;\n            break;\n        }\n    }\n    int l = 0, r = p - 1;\n    int x = a[n];\n    while (l < r) {\n        int m = (l + r) >> 1;\n        bool res = false;\n        if (x + m >= p) {\n            if (check(digits, x + m + 1 - p, x - 1, true)) {\n                res = true;\n            }\n        } else {\n            if (check(digits, 0, x - 1, false) && check(digits, x + m + 1, p - 1, false)) {\n                res = true;\n            }\n        }\n        if (res) {\n            r = m;\n        } else {\n            l = m + 1;\n        }\n    }\n    cout << l << '\\n';\n}\n\nbool multitest = true;\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    cout.precision(25);\n    size_t number_of_tests = 1;\n    if (multitest) {\n        cin >> number_of_tests;\n    }\n    for (size_t _ = 0; _ < number_of_tests; ++_) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1759",
    "index": "G",
    "title": "Restore the Permutation",
    "statement": "A sequence of $n$ numbers is called permutation if it contains all numbers from $1$ to $n$ exactly once. For example, the sequences [$3, 1, 4, 2$], [$1$] and [$2,1$] are permutations, but [$1,2,1$], [$0,1$] and [$1,3,4$] — are not.\n\nFor a permutation $p$ of even length $n$ you can make an array $b$ of length $\\frac{n}{2}$ such that:\n\n- $b_i = \\max(p_{2i - 1}, p_{2i})$ for $1 \\le i \\le \\frac{n}{2}$\n\nFor example, if $p$ = [$2, 4, 3, 1, 5, 6$], then:\n\n- $b_1 = \\max(p_1, p_2) = \\max(2, 4) = 4$\n- $b_2 = \\max(p_3, p_4) = \\max(3,1)=3$\n- $b_3 = \\max(p_5, p_6) = \\max(5,6) = 6$\n\nAs a result, we made $b$ = $[4, 3, 6]$.For a given array $b$, find the \\textbf{lexicographically minimal} permutation $p$ such that you can make the given array $b$ from it.\n\nIf $b$ = [$4,3,6$], then the lexicographically minimal permutation from which it can be made is $p$ = [$1,4,2,3,5,6$], since:\n\n- $b_1 = \\max(p_1, p_2) = \\max(1, 4) = 4$\n- $b_2 = \\max(p_3, p_4) = \\max(2, 3) = 3$\n- $b_3 = \\max(p_5, p_6) = \\max(5, 6) = 6$\n\nA permutation $x_1, x_2, \\dots, x_n$ is lexicographically smaller than a permutation $y_1, y_2 \\dots, y_n$ if and only if there exists such $i$ ($1 \\le i \\le n$) that $x_1=y_1, x_2=y_2, \\dots, x_{i-1}=y_{i-1}$ and $x_i<y_i$.",
    "tutorial": "First, let's check the $b$ array for correctness, that is, that it has no repeating elements. Then let's look at the following ideas: each number $b_i$ must be paired with another permutation element $p_j$, with $p_j \\lt b_i$ by the definition of array $b$. Then, since we want a lexicographically minimal permutation, it is always more advantageous to put element $p_j$ before $b_i$. for the permutation to be lexicographically minimal, the smallest possible numbers must be placed at the beginning. Consequently, the largest numbers must be placed at the end. Let's proceed as follows: Let's select the set of $unused$ numbers that are not included in the $b$ array. For an element $b_{\\frac{n}{2}}$, find the maximum number $k$ of the set $unused$ such that $b_{\\frac{n}{2}} > k$ and put that number in front of the element $b_{\\frac{n}{2}}$. moving from the end of the array to its beginning, each element $b_i$ will be matched with such an element. If at some point $k$ can not be matched - array $b$ is not composed correctly, and the answer to the query - \"NO\". Otherwise, print \"YES\" and the resulting permutation $p$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\nint n;\n\nvoid solve(){\n    cin >> n;\n    vector<int>b(n / 2), p(n);\n    vector<bool>isUsed(n + 1, false);\n    set<int>unused;\n\n    for(int i = 0; i < n / 2; i++){\n        cin >> b[i];\n        p[i * 2 + 1] = b[i];\n        isUsed[b[i]] = true;\n    }\n    for(int i = 1; i <= n; i++){\n        if(!isUsed[i]) unused.insert(i);\n    }\n\n\n    if(int(unused.size()) != n / 2){\n        cout << \"-1\\n\";\n        return;\n    }\n\n    for(int i = n / 2 - 1; i >= 0; i--){\n        auto k = unused.upper_bound(p[2 * i + 1]);\n        if(k == unused.begin()){\n            cout << \"-1\\n\";\n            return;\n        }\n\n        k--;\n\n\n        if(*k < p[2 * i + 1]){\n            p[2 * i] = *k;\n            unused.erase(k);\n        }\n        else{\n            cout << \"-1\\n\";\n            return;\n        }\n    }\n    for(auto i : p) cout << i << ' ';\n    cout << endl;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1760",
    "index": "A",
    "title": "Medium Number",
    "statement": "Given three \\textbf{distinct} integers $a$, $b$, and $c$, find the medium number between all of them.\n\nThe medium number is the number that is neither the minimum nor the maximum of the given three numbers.\n\nFor example, the median of $5,2,6$ is $5$, since the minimum is $2$ and the maximum is $6$.",
    "tutorial": "Here are two ways to implement what's given in the problem: Take input as an array $[a_1, a_2, a_3]$, and sort it. Output the middle element. Write two if-statements. The first: if $(a>b \\text{ and } a<c) \\text{ or } (a<b \\text{ and } a>c)$, output $a$. Else, if $(b>a \\text{ and } b<c) \\text{ or } (b<a \\text{ and } b>c)$, output $b$. Else, output $c$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint a[3];\n\tcin >> a[0] >> a[1] >> a[2];\n\tsort(a, a + 3);\n\tcout << a[1] << '\\n';\t\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1760",
    "index": "B",
    "title": "Atilla's Favorite Problem",
    "statement": "In order to write a string, Atilla needs to first learn all letters that are contained in the string.\n\nAtilla needs to write a message which can be represented as a string $s$. He asks you what is the minimum alphabet size required so that one can write this message.\n\nThe alphabet of size $x$ ($1 \\leq x \\leq 26$) contains \\textbf{only the first} $x$ Latin letters. For example an alphabet of size $4$ contains \\textbf{only} the characters $a$, $b$, $c$ and $d$.",
    "tutorial": "To solve the problem we need to find the character with the highest alphabetical order in our string, since Atilla will need at least that alphabet size and won't need more. To do this iterate through the string and find the character with the highest alphabetical order. Output the maximum alphabetical order found. The solution can be done in $O(n).$",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \nusing ll = long long;\n \n#define       forn(i,n)              for(int i=0;i<n;i++)\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nvoid solve() {\n    int n; string s; cin >> n >> s;\n    sort(all(s));\n    cout << s.back() - 'a' + 1 << \"\\n\";\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1760",
    "index": "C",
    "title": "Advantage",
    "statement": "There are $n$ participants in a competition, participant $i$ having a strength of $s_i$.\n\nEvery participant wonders how much of an advantage they have over the other best participant. In other words, each participant $i$ wants to know the difference between $s_i$ and $s_j$, where $j$ is the strongest participant in the competition, not counting $i$ (a difference can be negative).\n\nSo, they ask you for your help! For each $i$ ($1 \\leq i \\leq n$) output the difference between $s_i$ and the maximum strength of any participant other than participant $i$.",
    "tutorial": "Make a copy of the array $s$: call it $t$. Sort $t$ in non-decreasing order, so that $t_1$ is the maximum strength and $t_2$ - the second maximum strength. Then for everyone but the best person, they should compare with the best person who has strength $t_1$. So for all $i$ such that $s_i \\neq t_1$, we should output $s_i - t_1$. Otherwise, output $s_i - t_2$ - the second highest strength, which is the next best person.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        forn(i, n)\n            cin >> a[i];\n        vector<int> b(a);\n        sort(b.begin(), b.end());\n        forn(i, n) {\n            if (a[i] == b[n - 1])\n                cout << a[i] - b[n - 2] << \" \";\n            else\n                cout << a[i] - b[n - 1] << \" \";\n        }\n        cout << endl;\n   }\n}",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1760",
    "index": "D",
    "title": "Challenging Valleys",
    "statement": "You are given an array $a[0 \\dots n-1]$ of $n$ integers. This array is called a \"valley\" if there exists \\textbf{exactly one} subarray $a[l \\dots r]$ such that:\n\n- $0 \\le l \\le r \\le n-1$,\n- $a_l = a_{l+1} = a_{l+2} = \\dots = a_r$,\n- $l = 0$ or $a_{l-1} > a_{l}$,\n- $r = n-1$ or $a_r < a_{r+1}$.\n\nHere are three examples:\n\nThe first image shows the array [$3, 2, 2, 1, 2, 2, 3$], it \\textbf{is a valley} because only subarray with indices $l=r=3$ satisfies the condition.\n\nThe second image shows the array [$1, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6$], it \\textbf{is a valley} because only subarray with indices $l=0, r=2$ satisfies the codition.\n\nThe third image shows the array [$1, 2, 3, 4, 3, 2, 1$], it \\textbf{is not a valley} because two subarrays $l=r=0$ and $l=r=6$ that satisfy the condition.\n\nYou are asked whether the given array is a valley or not.\n\nNote that we consider the array to be indexed from $0$.",
    "tutorial": "One possible solution is to represent a range of equal element as a single element with that value. Construct this array $b$ and loop through it and check how many element $b_i$ satisfy the conditions $i = 0$ or $b_{i-1} < b_i$ and $i = n-1$ or $b_i > b_{i+1}$. If exactly one index satisfies these conditions, print \"YES\" and othewise \"NO\". Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<int> a;\n    for(int i = 0; i < n; i++)\n    {\n        int x;\n        cin >> x;\n        if(i == 0 || x != a.back())\n        {\n            a.push_back(x);\n        }\n    }\n    int num_valley = 0;\n    for(int i = 0; i < a.size(); i++)\n    {\n        if((i == 0 || a[i-1] > a[i]) && (i == a.size()-1 || a[i] < a[i+1]))\n        {\n            num_valley++;\n        }\n    }\n    if(num_valley == 1)\n    {\n        cout << \"YES\" << endl;\n    }\n    else\n    {\n        cout << \"NO\" << endl;\n    }\n}\n\nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "implementation",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1760",
    "index": "E",
    "title": "Binary Inversions",
    "statement": "You are given a binary array$^{\\dagger}$ of length $n$. You are allowed to perform one operation on it \\textbf{at most once}. In an operation, you can choose any element and flip it: turn a $0$ into a $1$ or vice-versa.\n\nWhat is the maximum number of inversions$^{\\ddagger}$ the array can have after performing \\textbf{at most one} operation?\n\n$^\\dagger$ A binary array is an array that contains only zeroes and ones.\n\n$^\\ddagger$ The number of inversions in an array is the number of pairs of indices $i,j$ such that $i<j$ and $a_i > a_j$.",
    "tutorial": "Let's find out how to count the number of binary inversions, without flips. This is the number of $1$s that appear before a $0$. To do this, iterate through the array and keep a running total $k$ of the number of $1$s seen so far. When we see a $0$, increase the total inversion count by $k$, since this $0$ makes $k$ inversions: one for each of the $1$s before it. Now let's see how to maximize the inversions. Consider the flip $0 \\to 1$. We claim that it is best to always flip the earliest $0$ in the array. It's never optimal to flip a later $0$, since we have strictly fewer $0$s after it to form inversions. Similarly, we should flip the latest $1$ in the array. Now recalculate the answer for these two choices for flipping, and pick the maximum. The complexity is $\\mathcal{O}(n)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \nusing ll = long long;\n \n#define       forn(i,n)              for(int i=0;i<n;i++)\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nll calc(vector<int>& a) {\n    ll zeroes = 0, ans = 0;\n    for(int i = sz(a) - 1; i >= 0; --i) {\n        if(a[i] == 0) ++zeroes;\n        else ans += zeroes;\n    }\n    return ans;\n}\nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n);\n    forn(i, n) cin >> a[i];\n    ll ans = calc(a);\n    forn(i, n) {\n        if(a[i] == 0) {\n            a[i] = 1;\n            ans = max(ans, calc(a));\n            a[i] = 0;\n            break;\n        }\n    }\n    for(int i = n - 1; i >= 0; --i) {\n        if(a[i] == 1) {\n            a[i] = 0;\n            ans = max(ans, calc(a));\n            a[i] = 1;\n            break;\n        }\n    }\n    cout << ans << \"\\n\";\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1760",
    "index": "F",
    "title": "Quests",
    "statement": "There are $n$ quests. If you complete the $i$-th quest, you will gain $a_i$ coins. You can only complete at most one quest per day. However, once you complete a quest, you cannot do the same quest again for $k$ days. (For example, if $k=2$ and you do quest $1$ on day $1$, then you cannot do it on day $2$ or $3$, but you can do it again on day $4$.)\n\nYou are given two integers $c$ and $d$. Find the maximum value of $k$ such that you can gain at least $c$ coins over $d$ days. If no such $k$ exists, output Impossible. If $k$ can be arbitrarily large, output Infinity.",
    "tutorial": "Let's fix $k$ and find the maximum number of coins we can get. Here we can do a greedy solution: at every step, we should always take the most rewarding quest. (Intuitively, it makes sense, since doing more rewarding quests earlier allows us to do them again later.) If no quests are available, we do nothing. To implement this, sort the quests in decreasing order, and $0$-index them. On day $i$ we should do quest $i \\bmod k$, provided that this value is less than $n$. This is because after every $k$ days, we cycle back to the first quest. Thus we solved the problem for a fixed $k$ in $\\mathcal{O}(d)$ with $\\mathcal{O}(n \\log n)$ precomputation to sort the array. Now to solve the problem, we can binary search on the answer, since if some $k$ works, then all smaller $k$ work. The minimum value of $k$ is $0$, and the maximum value is $n$ (for larger $k$, we won't be able to do the same quest multiple times anyways, so it's useless to consider them). If we find that $k$ always goes towards the smaller end of our binary search and $k=0$ still fails, we output Impossible. If we find that $k$ always goes towards the larger end of our binary search and $k=n$ still fails, we output Infinity. Otherwise, just output $k$. The overall time complexity is $\\mathcal{O}(n \\log n + d \\log n)$. Remark. It is not hard to improve the solution to $\\mathcal{O}(n \\log n)$. Originally, I proposed the problem this way, but we ended up removing this part of the problem because the implementation of this solution was tricky enough.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n, d;\n\tlong long c;\n\tcin >> n >> c >> d;\n\tlong long a[n];\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\tsort(a, a + n, greater<long long>());\n\tint l = 0, r = d + 2;\n\twhile (l < r) {\n\t\tint m = l + (r - l + 1) / 2;\n\t\tlong long tot = 0;\n\t\tint curr = 0;\n\t\tfor (int i = 0; i < d; i++) {\n\t\t\tif (i % m < n) {tot += a[i % m];}\n\t\t}\n\t\tif (tot >= c) {\n\t\t\tl = m;\n\t\t}\n\t\telse {\n\t\t\tr = m - 1;\n\t\t}\n\t}\n\tif (l == d + 2) {cout << \"Infinity\\n\"; return;}\n\tif (l == 0) {cout << \"Impossible\\n\"; return;}\n\tcout << l - 1 << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1760",
    "index": "G",
    "title": "SlavicG's Favorite Problem",
    "statement": "You are given a weighted tree with $n$ vertices. Recall that a tree is a connected graph without any cycles. A weighted tree is a tree in which each edge has a certain weight. The tree is undirected, it doesn't have a root.\n\nSince trees bore you, you decided to challenge yourself and play a game on the given tree.\n\nIn a move, you can travel from a node to one of its neighbors (another node it has a direct edge with).\n\nYou start with a variable $x$ which is initially equal to $0$. When you pass through edge $i$, $x$ changes its value to $x ~\\mathsf{XOR}~ w_i$ (where $w_i$ is the weight of the $i$-th edge).\n\nYour task is to go from vertex $a$ to vertex $b$, but you are allowed to enter node $b$ if and only if after traveling to it, the value of $x$ will become $0$. In other words, you can travel to node $b$ only by using an edge $i$ such that $x ~\\mathsf{XOR}~ w_i = 0$. Once you enter node $b$ the game ends and you win.\n\nAdditionally, you can teleport \\textbf{at most once} at any point in time to any vertex except vertex $b$. You can teleport from any vertex, even from $a$.\n\nAnswer with \"YES\" if you can reach vertex $b$ from $a$, and \"NO\" otherwise.\n\nNote that $\\mathsf{XOR}$ represents the bitwise XOR operation.",
    "tutorial": "Let's ignore the teleporting, and decide how to find the answer. Note that we don't need to ever go over an edge more than once, since going over an edge twice cancels out (since $a~\\mathsf{XOR}~a = 0$ for all $a$). In other words, the only possible value of $x$ equals the $\\mathsf{XOR}$ of the edges on the unique path from $a$ to $b$. We can find it through a BFS from $a$, continuing to keep track of $\\mathsf{XOR}$s as we move to each adjacent node, and $\\mathsf{XOR}$ing it by the weight of the corresponding edge as we travel across it. Now let's include the teleport. It means that we travel from $a \\to c$, then teleport to $d$, and go from $d \\to b$, for some nodes $c$ and $d$. Also, we cannot pass $b$ on the path from $a \\to c$. Again, note that the value of $x$ is fixed on each of the paths from $a \\to c$ and $d \\to b$, since there is a unique path between them. Let $x_1$ be the $\\mathsf{XOR}$ of the first path and $x_2$ be the $\\mathsf{XOR}$ of the second. Then we need $x_1~\\mathsf{XOR}~x_2=0 \\implies x_1=x_2$. So we need to find if there are two nodes $c$, $d$ such that the $\\mathsf{XOR}$s from $a$ and $b$ to those nodes are the same. To do this, we can do our BFS from before, but instead run one BFS from $a$ and another from $b$, and check if any two values are the same. Make sure not to include nodes past $b$ while we look for $c$ on our BFS from $a$. The time complexity is $\\mathcal{O}(n \\log n)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \nusing ll = long long;\n \n#define       forn(i,n)              for(int i=0;i<n;i++)\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nconst int N = 1e5 + 10;\nvector<pair<int, int>> adj[N];\nset<int> s;\nbool ok = true;\nint n, a, b;\nvoid dfs1(int u, int par, int x) {\n    if(u == b) return;\n    s.insert(x);\n    for(auto e: adj[u]) {\n        int v = e.first, w = e.second;\n        if(v == par) continue;\n        dfs1(v, u, x ^ w);\n    }\n}\n\nbool dfs2(int u, int par, int x) {\n    if(u != b && s.count(x)) return true;\n    for(auto e: adj[u]) {\n        int v = e.first, w = e.second;\n        if(v == par) continue;\n        if(dfs2(v, u, w ^ x)) return true;\n    } \n    return false;\n}\n\nvoid solve() {\n    s.clear();\n    cin >> n >> a >> b; --a, --b;\n    forn(i, n) adj[i].clear();\n    for(int i = 0; i < n - 1; ++i) {\n        int u, v, w; cin >> u >> v >> w; --u, --v;\n        adj[u].pb({v, w});\n        adj[v].pb({u, w});\n    }\n    dfs1(a, -1, 0);\n    if(dfs2(b, -1, 0)) cout << \"YES\\n\";\n    else cout << \"NO\\n\";\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1761",
    "index": "A",
    "title": "Two Permutations",
    "statement": "You are given three integers $n$, $a$, and $b$. Determine if there exist two permutations $p$ and $q$ of length $n$, for which the following conditions hold:\n\n- The length of the longest common prefix of $p$ and $q$ is $a$.\n- The length of the longest common suffix of $p$ and $q$ is $b$.\n\nA permutation of length $n$ is an array containing each integer from $1$ to $n$ exactly once. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "If $a+b+2\\leq n$, we can always find such pair, here is a possible construction: $A=\\{\\color{red}{1,2,\\cdots,a},\\color{orange}{n-b},\\color{green}{a+1,a+2,\\cdots,n-b-1},\\color{blue}{n-b+1,n-b+2,\\cdots,n}\\}\\\\B=\\{\\color{red}{1,2,\\cdots,a},\\color{green}{a+1,a+2,\\cdots,n-b-1},\\color{orange}{n-b},\\color{blue}{n-b+1,n-b+2,\\cdots,n}\\}$ The red part is their longest common prefix, and the blue part is their longest common suffix. Otherwise, the two permutations must be equal, so such pair exists iff $a=b=n$.",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1761",
    "index": "B",
    "title": "Elimination of a Ring",
    "statement": "Define a cyclic sequence of size $n$ as an array $s$ of length $n$, in which $s_n$ is adjacent to $s_1$.\n\nMuxii has a ring represented by a cyclic sequence $a$ of size $n$.\n\nHowever, the ring itself hates equal adjacent elements. So if two adjacent elements in the sequence are equal at any time, \\textbf{one of them} will be erased \\textbf{immediately}. The sequence doesn't contain equal adjacent elements initially.\n\nMuxii can perform the following operation until the sequence becomes empty:\n\n- Choose an element in $a$ and erase it.\n\nFor example, if ring is $[1, 2, 4, 2, 3, 2]$, and Muxii erases element $4$, then ring would erase one of the elements equal to $2$, and the ring will become $[1, 2, 3, 2]$.\n\nMuxii wants to find the \\textbf{maximum} number of operations he could perform.\n\n\\textbf{Note that in a ring of size $1$, its only element isn't considered adjacent to itself (so it's not immediately erased).}",
    "tutorial": "Hint Do we need more than $3$ types of elements? Try to solve the problem with $a_i\\leq 3$. Solution First of all, when there're only $2$ types of elements appearing in the sequence, the answer would be $\\frac{n}2+1$. Otherwise, the conclusion is that we can always reach $n$ operations when there are more than $2$ types of elements appearing in the sequence. The proof is given below: When the length of the sequence is greater than $3$, there will always be a pair of positions $(i,j)$, such that $a_i=a_j$ and $a_i$ has two different neighboring elements. Then we can erase $a_i$ and then the problem is decomposed into a smaller one. If there do not exist such pairs, then we can infer that there exists at least $1$ element which appeared only once in the sequence. If there exists such element $b$, then we can continuously erase all the elements next to $b$, then erase $b$ at last. When the length $n$ of the sequence is less than $3$, it is clear that there will be exactly $n$ operations as well. So we only need to check the number of elements that appeared in the sequence of length $n$. If the number is $2$, the answer will be $\\frac n2 + 1$. Otherwise, the answer equals $n$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1761",
    "index": "C",
    "title": "Set Construction",
    "statement": "You are given a binary matrix $b$ (all elements of the matrix are $0$ or $1$) of $n$ rows and $n$ columns.\n\nYou need to construct a $n$ sets $A_1, A_2, \\ldots, A_n$, for which the following conditions are satisfied:\n\n- Each set is nonempty and consists of distinct integers between $1$ and $n$ inclusive.\n- All sets are distinct.\n- For all pairs $(i,j)$ satisfying $1\\leq i, j\\leq n$, $b_{i,j}=1$ if and only if $A_i\\subsetneq A_j$. In other words, $b_{i, j}$ is $1$ if $A_i$ is a proper subset of $A_j$ and $0$ otherwise.\n\nSet $X$ is a proper subset of set $Y$, if $X$ is a nonempty subset of $Y$, and $X \\neq Y$.\n\nIt's guaranteed that for all test cases in this problem, such $n$ sets exist. \\textbf{Note that it doesn't mean that such $n$ sets exist for all possible inputs.}\n\nIf there are multiple solutions, you can output any of them.",
    "tutorial": "Hint 1: When you are trying to add an element into a set $S$, you will have to add the element to every set that is meant to include $S$. Hint 2: If $A$ does not include $B$, then $A$ and $B$ are already distinct. If $A$ does include $B$, What is the easiest way of making $A$ and $B$ distinct? Solution: Denote an ancestor to $S$ as a set that is meant to include $S$. Denote a descendant to $S$ as a set that is meant to be included by $S$. Let all sets be empty from the beginning. Iterate through the sets. To make set $S$ distinct from its descendants, we can add a new number $x_S$ that hasn't been added to any previous sets to $S$ and all of its ancestors. After the execution above, we will find out that the conditions are all satisfied, since: - For all descendants of a set $S$, all the elements they have will be included in $S$; - Vice versa for all ancestors of a set $S$; - For each set $T$ that is not an ancestor nor a descendant to $S$, they will not include each other. This is because $S$ does not include $T$, since $S$ does not have the element $x_T$; and $T$ does not include $S$ for the same reason. Therefore, the construction above satisfies all given conditions. Moreover, we can set $x_S$ to the index of $S$ for a simpler implementation.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1761",
    "index": "D",
    "title": "Carry Bit",
    "statement": "Let $f(x,y)$ be the number of carries of $x+y$ in binary (i. e. $f(x,y)=g(x)+g(y)-g(x+y)$, where $g(x)$ is the number of ones in the binary representation of $x$).\n\nGiven two integers $n$ and $k$, find the number of ordered pairs $(a,b)$ such that $0 \\leq a,b < 2^n$, and $f(a,b)$ equals $k$. Note that for $a\\ne b$, $(a,b)$ and $(b,a)$ are considered as two different pairs.\n\nAs this number may be large, output it modulo $10^9+7$.",
    "tutorial": "Hint 1: Try to solve the problem in $O(nk)$ using DP. Hint 2: There is no need for DP. Hint 3: You can consider enumerating the bits to carry, and then counting. Let $a_i$ represents the $i$-th bit of $a$ in binary representation (that is, $2^i \\times a_i=a \\wedge 2^i$) and define $b_i$ similarly. If you decide which bits to carry ahead, you will find that every bit of $a,b$ is independent (because whether the previous bit carries or not is decided), so you can use the multiplication principle to count. Therefore, in the remaining tutorial, we should determine the carries first and then count the number of options of $a_i,b_i$ meeting the constraints of carries. Define array $c$ as our decided carry plan, $c_i=1$ indicates that the $i$-th bit is carried, and define $c_{-1}$ as $0$. Notice that $c_i=a_i \\vee b_i \\vee c_{i-1}$. Ponder each bit, we will notice that if $c_i=c_{i-1}=0$, $(a_i,b_i)$ can be $(0,0),(0,1),(1,0)$. $c_i=c_{i-1}=1$, $(a_i,b_i)$ can be $(1,1),(0,1),(1,0)$. $c_i=1$ and $c_{i-1}=0$, $(a_i,b_i)$ must be $(1,1)$. $c_i=0$ and $c_{i-1}=1$, $(a_i,b_i)$ must be $(0,0)$. That means that pair $(a_i,b_i)$ has $3$ options if $c_i=c_{i-1}$, and pair $(a_i,b_i)$ has $1$ options if $c_i\\neq c_{i-1}$. So if array $c$ has $q$ positions that $c_i\\neq c_{i-1}$ ( $0 \\leq i < n$, remember we define $c_{-1}$ as $0$ ), the count of pair $(a,b)$ is $3^{n-q}$. Now we can enumerate $q$, and count the number of $c$ has $q$ positions that $c_i\\neq c_{i-1}$. The new problem equals a typical binomial problem. Notice that for every $q$, a valid $c$ should have $\\lfloor \\frac{q}{2} \\rfloor$ segment of consecutive $1$s and $\\lceil \\frac{q}{2} \\rceil$ segment of consecutive $0$s if we seen $c_{-1}$ as a normal bit (so that we have $n-k+1$ zeros). The number of solutions that divide $a$ elements into $b$ segments is $\\binom{a-1}{b-1}$. Therefore the answer of each $q$ is $3^{n-q} \\times \\binom{k-1}{\\lfloor \\frac{q}{2} \\rfloor-1} \\times \\binom{(n-k+1)-1}{\\lceil \\frac{q}{2} \\rceil-1}$, and we can calculate it in $\\Theta(1)$. Add them all and you can find the answer in $\\Theta(n)$.",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1761",
    "index": "E",
    "title": "Make It Connected",
    "statement": "You are given a simple undirected graph consisting of $n$ vertices. The graph doesn't contain self-loops, there is at most one edge between each pair of vertices. Your task is simple: make the graph connected.\n\nYou can do the following operation any number of times (possibly zero):\n\n- Choose a vertex $u$ arbitrarily.\n- For each vertex $v$ satisfying $v\\ne u$ in the graph individually, if $v$ is adjacent to $u$, remove the edge between $u$ and $v$, otherwise add an edge between $u$ and $v$.\n\nFind the minimum number of operations required to make the graph connected. Also, find any sequence of operations with the minimum length that makes the graph connected.",
    "tutorial": "Hint 1 Try to figure out the conditions where a task can be solved with $1$ operation. Then $2$ operations, and then even more operations. Hint 2 The answer could be larger than $2$ only when the graph is made up of $2$ cliques, where you could only perform the operations on every vertex in the smaller clique to get the minimum number of operations. Solution First of all, we need to check if the graph is already connected at the beginning. If so, the answer would be $0$. Otherwise, there will be more than $1$ connected component. If there exists a vertex that is the only vertex required to be operated to make the graph connected, we call such a vertex \"feasible vertex\". We may find out that a feasible vertex can only appear in a connected component that is not a clique. But actually, there will always be such a vertex in a non-clique component. To prove this, we may figure out the sufficient condition for being a feasible vertex first. The sufficient condition is that, if a vertex is not a cut vertex, and it is not adjacent to all other vertices in the connected component, then it must be a feasible vertex. We can prove that such a vertex always exists in a non-clique component. Here is the proof: Firstly, if there exist non-cut vertices that are adjacent to all other vertices in the component, we erase them one by one until there don't exist any non-cut vertices which are adjacent to all other vertices (note that a non-cut vertex which is adjacent to all other vertices may become a cut vertex after erasing some of the other vertices). Apparently, the remaining component would still be a non-clique component. Otherwise, the component could only be a clique from the beginning, which contradicts the premise. Apparently, the remaining component would still be a non-clique component. Otherwise, the component could only be a clique from the beginning, which contradicts the premise. Then, we will find a non-cut vertex in the remaining component, since that vertices in a graph couldn't be all cut vertices. The non-cut vertex we found is the vertex we are searching for. But implementing it directly (meaning using Tarjan's algorithm to find a non-cut vertex) might not be the easiest way to solve the problem. Actually, the vertex with the least degree in a connected component always satisfy the condition. We would like to leave the proof work of the alternative method to you. Now we have proven that, if there exists a connected component that is not a clique, then the answer would be at most $1$. What if all connected components are cliques? If there are exactly $2$ connected components, then apparently we will have to operate on all vertices in a connected component. So we'll choose the smaller connected component to operate, and the answer is exactly the size of it. Otherwise, we can arbitrarily choose two vertices from two different connected components and operate on them. The answer is $2$. Note that we also need to deal with isolated vertices (meaning vertices that are not adjacent to any other vertices) separately.",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "dsu",
      "graphs",
      "greedy",
      "matrices",
      "trees",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1761",
    "index": "F1",
    "title": "Anti-median (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.}\n\nLet's call an array $a$ of odd length $2m+1$ (with $m \\ge 1$) \\textbf{bad}, if element $a_{m+1}$ is equal to the median of this array. In other words, the array is bad if, after sorting it, the element at $m+1$-st position remains the same.\n\nLet's call a permutation $p$ of integers from $1$ to $n$ \\textbf{anti-median}, if every its subarray of odd length $\\ge 3$ is not bad.\n\nYou are already given values of some elements of the permutation. Find the number of ways to set unknown values to obtain an \\textbf{anti-median} permutation. As this number can be very large, find it modulo $10^9+7$.",
    "tutorial": "Let's analyze the structure of anti-median permutations. First, if for any $2 \\le i \\le n-1$ holds $a_{i-1}>a_i>a_{i+1}$, or $a_{i-1}<a_i<a_{i+1}$, then segment $p[i-1:i+1]$ is bad. So, the signs between adjacent elements are alternating. So, consider two cases: all elements on even positions are local maximums, and on odd local minimums, and vice versa. Let's find the answer for the first case (for the second, you can find the answer similarly). Consider a segment of length $5$, $[p_{i-2}, p_{i-1}, p_i, p_{i+1}, p_{i+2}]$. Consider the case when $i$ is even first. Then $p_i>p_{i-1}, p_{i+1}$. For $p_i$ to not be median, it has to be larger than one of $p_{i-2}, p_{i+2}$. So, when we consider only even elements, each element (except the first and last one) has at least one adjacent element smaller than it. It's easy to see that this implies that elements at even positions are first increasing and then decreasing. Similarly, we can see that elements at odd positions are first decreasing, then increasing. It's not hard to see that these conditions are sufficient. Indeed, suppose that: All elements on even positions are local maximums, and all elements on odd positions are local minimums Elements at even positions are first increasing and then decreasing. Elements at odd positions are first decreasing, then increasing. Then, consider any segment of odd length. Denote it by $b_1, b_2, \\ldots, b_{2m+1}$, and wlog $b_{m+1}$ is local maximum. If we look at local maximums, at least one of the following two conditions has to hold: all local maximums to the right of $b_{m+1}$ are smaller than it, or all local maximums to the left of $b_{m+1}$ are smaller than it. Wlog first case. Then all elements to the right of $b_{m+1}$ are smaller than it, and $b_m$ is also smaller than it, so $b_{m+1}$ can't be a median. Now, let's put all elements on the circle in the following order: first, all even elements from left to right, then all odd elements from right to left. In this circle, the elements on both paths between $n$ and $1$ are decreasing. It follows that for any $k$, numbers from $k$ to $n$ form a segment (in this cyclic arrangement). Then, we can write a $dp$ of the form: $dp[l][r]$: how many ways are there to arrange the largest $(r-l+1+n)\\bmod n$ elements so that they end up in the positions from $l$-th to $r$-th in this cyclic arrangement. All the transitions and checks are done in $O(1)$, and there are $O(n^2)$ states, so we are done.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1761",
    "index": "F2",
    "title": "Anti-median (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.}\n\nLet's call an array $a$ of odd length $2m+1$ (with $m \\ge 1$) \\textbf{bad}, if element $a_{m+1}$ is equal to the median of this array. In other words, the array is bad if, after sorting it, the element at $m+1$-st position remains the same.\n\nLet's call a permutation $p$ of integers from $1$ to $n$ \\textbf{anti-median}, if every its subarray of odd length $\\ge 3$ is not bad.\n\nYou are already given values of some elements of the permutation. Find the number of ways to set unknown values to obtain an \\textbf{anti-median} permutation. As this number can be very large, find it modulo $10^9+7$.",
    "tutorial": "For this version, we have to analyze our dp a bit more. Once again, how do anti-median permutations look? We consider the order of positions on the cycle, as in F1. We choose the position of $n$, and then, for $i$ from $n-1$ to $1$, we choose a position of number $i$ among two options: right to the right of the current segment or right to the left. If we fill this way, do we always get an anti-median permutation? Not really. This way makes sure that elements at even positions are first increasing, then decreasing, and at odd positions, first decreasing, then increasing, but it doesn't make sure that the element at the even position is larger than its neighbors. How do we guarantee that? Well, some segments are just not allowed: those, which contain a prefix of odd positions, prefix of even positions, and the prefix of odd positions is larger (off by $\\pm 1$, depending on the parity of $n$), and same for suffixes. Another observation is that if we know where $x$ is, we only have to options for where can the segment of numbers from $x$ to $n$ be (to the right or to the left of $x$). This reduces our problem to the following subproblem: we start from some segment and have to end in another segment by expanding the current segment by $1$ to the right or to the left without ever entering \"bad segments.\" Turns out that we can solve this in $O(1)$! Indeed, represent expanding segment to the right by a move up in a coordinate plane and to the left by a move to the right. Then, we have to get from point $(0, 0)$ to some point $(a, b)$ by moving up or to the right without ever crossing some line of form $x = y + c$. This is a well-known counting problem.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1761",
    "index": "G",
    "title": "Centroid Guess",
    "statement": "\\textbf{This in an interactive problem}.\n\nThere is an unknown tree consisting of $n$ nodes, which has \\textbf{exactly one} centroid. You only know $n$ at first, and your task is to find the centroid of the tree.\n\nYou can ask the distance between any two vertices for at most $2\\cdot10^5$ times.\n\nNote that the interactor is \\textbf{not} adaptive. That is, the tree is fixed in each test beforehand and does not depend on your queries.\n\nA vertex is called a centroid if its removal splits the tree into subtrees with at most $\\lfloor\\frac{n}{2}\\rfloor$ vertices each.",
    "tutorial": "Assuming we have already determined that the centroid of the tree is located on the path between $u$ and $v$, we may now consider how to locate it. Let $c_1,c_2,\\dots,c_k$ be the vertices on the path from $u$ to $v$. Let $A_i$ be the set of vertices reachable from $c_i$ (including $c_i$) if we erase all other vertices on the path from $u$ to $v$. Then we may find that $A_1,A_2,\\dots,A_k$ are a division of all vertices. Let $s_i$ be the size of $A_i$. Then there must exist a vertex $c_x$ on the path satisfying that $\\max\\{\\sum_{i=1}^{x-1}s_i,\\sum_{i=x+1}^ks_i\\}\\leq \\lfloor\\frac n2\\rfloor$. Notice that the vertices that do not satisfy the condition could not be a centroid, and it is already determined that the centroid is on the path, so $c_x$ is exactly the centroid of the tree. Then we may consider finding out which set each vertex belongs to with $2n$ queries so that we can calculate the value of $s_i$. For each vertex $x$, we may query $dis_{u,x}$ and $dis_{v,x}$. For any two vertices $x$ and $y$ that belong to the same set, $dis_{u,x}-dist_{v,x}$ should be equal to $dis_{u,y}-dis_{v,y}$. Let $t_1=dis_{u,x}-dis_{v,x}$ and $t_2=dis_{u,v}$, then $x\\in A_{(t_1+t_2)/2+1}$. Thus we have found out the sets each vertex belongs to, as well as the value of $s_i$, as well as the centroid. This process requires at most $7.5\\times10^4\\times2=1.5\\times 10^5$ queries. Now the problem remains to find a pair of vertices $u$ and $v$ such that the centroid locates on the path from $u$ to $v$. We can pick a constant $M$ satisfying that $\\frac{M(M-1)}2\\leq 5\\times 10^4$, then select $M$ vertices on the tree randomly, and query the distances between every pair of selected vertices. This requires $\\frac{M(M-1)}2\\leq 5\\times 10^4$ queries. Let these $M$ vertices be $p_1,p_2,\\dots,p_M$. We can build a virtual tree with $p_1$ being the root that contains all the LCAs of each pair of vertices. Observe that $dis_{x,y}+dis_{y,z}=dis_{x,z}$ if and only if $y$ is located on the path between $x$ and $z$. For a vertex $p_x$, we can find out all vertices on the path from $p_1$ to $p_x$, and then find out the closest vertex to $p_x$ and connect them. It is exactly the deepest ancestor of $p_x$. Now that we have constructed the virtual tree without the LCAs with $p_1$ being the root, we will then add the LCAs into the virtual tree. Start DFS from $p_1$. Assume the current vertex is $u$. Enumerate through the nodes adjacent to $u$. Assume the current vertex is $v$. If there exists another vertex $x$ which is adjacent to $u$ satisfying that $u$ is not on the path between $x$ and $v$, then $x$ and $u$ should be both in the subtree of one of $u$'s child nodes. After finding out all vertices that are in the same subtree as $v$, it would be easy to calculate the depth of their LCAs as well as the distance between an LCA vertex and all other vertices in the virtual tree. Then, remove the old edge, and then add edges between the LCA and all vertices found in the same subtree as $v$. Lastly, add an edge between the LCA and $u$. Then repeat the process above, until any two vertices adjacent to $u$ are not in the same subtree of a child node of $u$. Then DFS the child nodes of $u$. We will get the whole virtual tree after all DFS are done. For the $M$ vertices chosen from the beginning, we assume that their weights are all $1$, while other vertices have $0$ weight. Then we may find the weighted centroid of the virtual tree (when there are multiple such centroids, arbitrarily pick one), and then make it the root. Then for the two vertices with the largest and second-largest subtree of the root, DFS them, recursively find their child vertex with the largest subtree. We will be resulted with $2$ leaf nodes. Then the centroid of the hidden tree is highly possible to be located on the path between these $2$ nodes. The number of queries in both parts would not exceed $2\\times 10^5$. Proof of correctness: If the centroid is not on the path between $u$ and $v$, assume the centroid of the virtual tree is in the subtree $E$ of the centroid of the hidden tree. If the subtrees other than $E$ contain at least $\\frac 13$ of the $M$ vertices, then the centroid of the hidden tree must be on the path between $u$ and $v$. So there will be at most $\\frac 13$ of the $M$ vertices not being in $E$. In other words, for each of $M$ vertices, it has a possibility greater than $\\frac 12$ of not being in $E$, and there will be at most $\\frac 13$ of the vertices which are not in $E$. The possibility of the algorithm being wrong is not greater than $\\sum_{i=0}^{M/3}C_M^i/2^M$, let $M=316$, then the value would be approximately $6\\times 10^{-10}$.",
    "tags": [
      "interactive",
      "probabilities",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1762",
    "index": "A",
    "title": "Divide and Conquer",
    "statement": "An array $b$ is good if the sum of elements of $b$ is even.\n\nYou are given an array $a$ consisting of $n$ positive integers. In one operation, you can select an index $i$ and change $a_i := \\lfloor \\frac{a_i}{2} \\rfloor$. $^\\dagger$\n\nFind the minimum number of operations (possibly $0$) needed to make $a$ good. It can be proven that it is \\textbf{always} possible to make $a$ good.\n\n$^\\dagger$ $\\lfloor x \\rfloor$ denotes the floor function — the largest integer less than or equal to $x$. For example, $\\lfloor 2.7 \\rfloor = 2$, $\\lfloor \\pi \\rfloor = 3$ and $\\lfloor 5 \\rfloor =5$.",
    "tutorial": "If sum is even, answer is $0$. Otherwise we need to change parity of atleast one element of $a$. It it optimal to change parity of atmost one element. Answer can be atmost $20$, as we need to divide any integer $x$ ($1 \\leq x \\leq 10^6$) atmost $20$ times to change its parity. We are assuming initial sum is odd. Suppose $f(x)(1 \\leq x \\leq 10^6)$ gives the minimum number of operations needed to change parity of $x$. Iterate from $i=1$ to $n$ and calculate $f(a_i)$ for each $i$. Answer is minimum among all the calculated values. Time complexity is $O(n \\cdot log(A_{max}))$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nvoid solve(){\n    ll n; cin>>n;\n    ll sum=0,ans=21;\n    vector<ll> a(n);\n    for(auto &it:a){\n        cin>>it;\n        sum+=it;\n    }\n    if(sum&1){\n        for(auto &it:a){\n            ll cur=it,now=0;\n            while(!((cur+it)&1)){\n                now++;\n                cur/=2;\n            }\n            ans=min(ans,now);\n        }\n    }\n    else{\n        ans=0;\n    }\n    cout<<ans<<\"\\n\";\n}\nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t; cin>>t;\n    while(t--){\n        solve();\n    }\n} ",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1762",
    "index": "B",
    "title": "Make Array Good",
    "statement": "An array $b$ of $m$ positive integers is good if for all pairs $i$ and $j$ ($1 \\leq i,j \\leq m$), $\\max(b_i,b_j)$ is divisible by $\\min(b_i,b_j)$.\n\nYou are given an array $a$ of $n$ positive integers. You can perform the following operation:\n\n- Select an index $i$ ($1 \\leq i \\leq n$) and an integer $x$ ($0 \\leq x \\leq a_i$) and add $x$ to $a_i$, in other words, $a_i := a_i+x$.\n- After this operation, $a_i \\leq 10^{18}$ should be satisfied.\n\nYou have to construct a sequence of \\textbf{at most} $n$ operations that will make $a$ good. It can be proven that under the constraints of the problem, such a sequence of operations \\textbf{always} exists.",
    "tutorial": "Suppose we have a prime number $p$. Suppose there are two perfect powers of $p$ - $l$ and $r$. Now it is easy to see $\\max(l,r)$ is divisible by $\\min(l,r)$. So now we need to choose some prime number $p$. Let us start with the smallest prime number $p=2$. Here is one interesting fact. There always exists a power of $2$ in the range $[x,2x]$ for any positive integer $x$. Suppose $f(x)$ gives the smallest power of $2$ which is greater than $x$. Iterate from $i=1$ to $n$ and change $a_i$ to $f(a_i)$ by adding $f(a_i)-a_i$ to $i$-th element. Time complexity is $O(n \\cdot log(A_{max}))$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nll f(ll x){\n    ll cur=1;\n    while(cur<=x){\n        cur*=2;\n    }\n    return cur;\n}\nvoid solve(){\n    ll n; cin>>n;\n    cout<<n<<\"\\n\";\n    for(ll i=1;i<=n;i++){\n        ll x; cin>>x;\n        cout<<i<<\" \"<<f(x)-x<<\"\\n\";\n    }\n}\nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t; cin>>t;\n    while(t--){\n        solve();\n    }\n} ",
    "tags": [
      "constructive algorithms",
      "implementation",
      "number theory",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1762",
    "index": "C",
    "title": "Binary Strings are Fun",
    "statement": "A binary string$^\\dagger$ $b$ of odd length $m$ is good if $b_i$ is the median$^\\ddagger$ of $b[1,i]^\\S$ for all \\textbf{odd} indices $i$ ($1 \\leq i \\leq m$).\n\nFor a binary string $a$ of length $k$, a binary string $b$ of length $2k-1$ is an extension of $a$ if $b_{2i-1}=a_i$ for all $i$ such that $1 \\leq i \\leq k$. For example, {\\underline{1}0\\underline{0}1\\underline{0}1\\underline{1}} and {\\underline{1}1\\underline{0}1\\underline{0}0\\underline{1}} are extensions of the string 1001. String $x=$1011011 is not an extension of string $y=$1001 because $x_3 \\neq y_2$. Note that there are $2^{k-1}$ different extensions of $a$.\n\nYou are given a binary string $s$ of length $n$. Find the sum of the number of good extensions over all prefixes of $s$. In other words, find $\\sum_{i=1}^{n} f(s[1,i])$, where $f(x)$ gives number of good extensions of string $x$. Since the answer can be quite large, you only need to find it modulo $998\\,244\\,353$.\n\n$^\\dagger$ A binary string is a string whose elements are either $\\mathtt{0}$ or $\\mathtt{1}$.\n\n$^\\ddagger$ For a binary string $a$ of length $2m-1$, the median of $a$ is the (unique) element that occurs at least $m$ times in $a$.\n\n$^\\S$ $a[l,r]$ denotes the string of length $r-l+1$ which is formed by the concatenation of $a_l,a_{l+1},\\ldots,a_r$ in that order.",
    "tutorial": "Let us first find $f(s[1,n])$. $f(s[1,n])=2^{len-1}$ where $len$ is the length of longest suffix of $s$ in which all characters are same. How to prove the result in hint $2$? First of all it is easy to see if all characters of $s$ are same, $f(s[1,n])=2^{n-1}$ as median is always $s_i$. Now we assume that $s$ contains distinct characters. Suppose $t$ is one good extension of $s$. Assume we are index $i$. If there exists an index $j(j>i)$ such that $s_i \\neq s_j$, we should have $t_{2i} \\neq s_i$. Why? Assume $k$ is the smallest index greater than $i$ such that $s_i \\neq s_k$. Now if we have $t_{2i} = s_i$, $s_k$ can never be median of subarray $t[1,2k-1]$. So if longest suffix of $s$ having same characters of starts at index $i$, $t_{2j} \\neq s_j$ for all $j(1 \\leq j < i)$ and $t_{2j}$ can be anything(either $0$ or $1$) for all $j(i \\leq j < n)$. Now we know how to solve for whole string $s$. We can similarly solve for all prefixes. To find $f(s[1,i])$, we need to find the longest suffix of $s[1,i]$ containing same character. We can easily calculate this all prefixes while moving from $i=1$ to $n$. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nconst ll MOD=998244353;\nvoid solve(){\n    ll n; cin>>n;\n    string s; cin>>s; s=\" \"+s;\n    ll ans=0,cur=1;\n    for(ll i=1;i<=n;i++){\n        if(s[i]==s[i-1]){\n            cur=(2*cur)%MOD;\n        }\n        else{\n            cur=1;\n        }\n        ans=(ans+cur)%MOD;\n    }\n    cout<<ans<<\"\\n\";\n}\nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t; cin>>t;\n    while(t--){\n        solve();\n    }\n} ",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1762",
    "index": "D",
    "title": "GCD Queries ",
    "statement": "This is an interactive problem.\n\nThere is a secret permutation $p$ of $[0,1,2,\\ldots,n-1]$. Your task is to find $2$ indices $x$ and $y$ ($1 \\leq x, y \\leq n$, possibly $x=y$) such that $p_x=0$ or $p_y=0$. In order to find it, you are allowed to ask \\textbf{at most} $2n$ queries.\n\nIn one query, you give two integers $i$ and $j$ ($1 \\leq i, j \\leq n$, $i \\neq j$) and receive the value of $\\gcd(p_i,p_j)^\\dagger$.\n\nNote that the permutation $p$ is fixed \\textbf{before} any queries are made and does not depend on the queries.\n\n$^\\dagger$ $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$. Note that $\\gcd(x,0)=\\gcd(0,x)=x$ for all positive integers $x$.",
    "tutorial": "Intended solution uses $2 \\cdot (n-2)$. You are allowed to guess two indices. Doesn't this hint towards something? If we can eliminate $n-2$ elements that cannot be $0$ for sure, we are done. Suppose we have three distinct indices $i$, $j$ and $k$. Is it possible to remove one index(say $x$) out of these three indices such that $p_x \\neq 0$ for sure. You are allowed to query two times. So suppose we have three distinct indices $i$, $j$ and $k$. Let us assume $l=query(i,k)$ and $r=query(j,k)$ Now we have only three possibilities. $l=r$ In this case, $p_k$ cannot be $0$. Why? $p_i$ and $p_j$ are distinct, and we have $\\gcd(0,x) \\neq \\gcd(0,y)$ if $x \\neq y$ $l > r$ In this case, $p_j$ cannot be $0$. Why? Note $\\gcd(0,p_k)=p_k$ and $\\gcd(m,p_k)$ can be atmost $p_k$ for any non negative integer. If $l > r$, this means $r$ cannot be $p_k$. Thus $p_r \\neq 0$ for sure $l < r$ In this case, $p_i$ cannot be $0$. Why? Refer to the above argument. This we can eliminate one index on using $2$ queries. We will perform this operation $n-2$ times. Refer to attached code for details. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nvoid solve(){\n    ll n; cin>>n;\n    ll l=1,r=2;\n    for(ll i=3;i<=n;i++){\n        ll ql,qr;\n        cout<<\"? \"<<l<<\" \"<<i<<endl;\n        cin>>ql;\n        cout<<\"? \"<<r<<\" \"<<i<<endl;\n        cin>>qr;\n        if(ql>qr){\n            r=i;\n        }\n        else if(ql<qr){\n            l=i;\n        }\n    }\n    cout<<\"! \"<<l<<\" \"<<r<<endl;\n    ll check; cin>>check;\n    assert(check==1); \n}\nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t; cin>>t;\n    while(t--){\n        solve();\n    }\n} ",
    "tags": [
      "constructive algorithms",
      "interactive",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1762",
    "index": "E",
    "title": "Tree Sum",
    "statement": "Let us call an edge-weighted tree with $n$ vertices numbered from $1$ to $n$ good if the weight of each edge is either $1$ or $-1$ and for each vertex $i$, the product of the edge weights of all edges having $i$ as one endpoint is $-1$.\n\nYou are given a positive integer $n$. There are $n^{n-2} \\cdot 2^{n-1}$ distinct$^\\dagger$ edge-weighted trees with $n$ vertices numbered from $1$ to $n$ such that each edge is either $1$ or $-1$. Your task is to find the sum of $d(1,n)^\\ddagger$ of all such trees that are good. Since the answer can be quite large, you only need to find it modulo $998\\,244\\,353$.\n\n$^\\dagger$ Two trees are considered to be distinct if either:\n\n- there exists two vertices such that there is an edge between them in one of the trees, and not in the other.\n- there exists two vertices such that there is an edge between them in both trees but the weight of the edge between them in one tree is different from the one in the other tree.\n\nNote that by Cayley's formula, the number of trees on $n$ labeled vertices is $n^{n-2}$. Since we have $n-1$ edges, there are $2^{n-1}$ possible assignment of weights(weight can either be $1$ or $-1$). That is why total number of distinct edge-weighted tree is $n^{n-2} \\cdot 2^{n-1}$.\n\n$^\\ddagger$ $d(u,v)$ denotes the sum of the weight of all edges on the unique simple path from $u$ to $v$.",
    "tutorial": "There does not exist any good tree of size $n$ if $n$ is odd. How to prove it? Suppose $f(v)$ gives the product of weight of edges incident to node $v$ in a good tree. We know that $f(i)=-1$ as if tree is good. Now $\\prod_{i=1}^{n} f(i) = -1$ if $n$ is odd. There is another way to find $\\prod_{i=1}^{n} f(i)$. Look at contribution of each edge. Each edge contribitues $1$ to $\\prod_{i=1}^{n} f(i)$, no matter what the weight of this edge is, as it gets multiplied twice. Thus we get $\\prod_{i=1}^{n} f(i) = 1$. We got contradiction. Thus no good tree of size $n$ exists. Now assume $n$ is even. Here is an interesting claim. For any unweighted tree,there exists exactly one assignment of weight of edges which makes it good. Thus there are $n^{n-2}$ distinct edge-weighted trees. How to prove the claim in hint $2$? Arbitrarily root the tree at node $1$. Now start from leaves and move towards root and assign the weight of edges in the path. First of all the edge incident to any leaf node will have $-1$ as the weight. While moving towards root, it can be observed that weight of edge between $u$ and parent of $u$ depends on the product of weight of edges between $u$ and its children. As we are moving from leaves towards root, weight of edges between $u$ and its children are already fixed. Weight of edge between $u$ and parent $u$ is $-1 \\cdot \\prod_{x \\in C(u)}{pw(x)}$, where $pw(x)$ gives the weight of edge between $x$ and its parent, and $C(u)$ denotes the set of children of $u$. Time for one more interesting claim. The weight of edge $e$ is $(-1)^{l}$ if there are $l$ nodes on one side and $n-l$ nodes on other side of $e$, irrespective of the structure of tree. We can prove this claim by induction, similar to what we did in hint $3$. To find answer we will look at contribution of each edge. Here's detailed explanation on how to dot it. In total, we have $n^{n-2} \\cdot (n-1)$ edges. Suppose for some edge(say $e$), we have $l$ nodes(including node $1$) on left side and $r$ nodes(including node $n$) on right side. Among $n^{n-2} \\cdot (n-1)$ edges, how many possibilities do we have for $e$? It is ${{n-2} \\choose {l-1}} \\cdot l \\cdot r \\cdot l^{l-2} \\cdot r^{r-2}$. Why? First we select $l-1$ nodes(as node $1$ is fixed to be on left side) to be on left side, we get ${{n-2} \\choose {l-1}}$ for this. Now we have $l$ nodes on left side and $r$ nodes on right side. Edge $e$ will connect one among $l$ nodes on left and one among $r$ nodes on right. So edge $e$ will exist between $l \\cdot r$ pairs. We know that number of distinct trees having $x$ nodes is $x^{x-2}$. Now on selecting one node from left and one from right, we have fixed the root of subtree on left side, and have also fixed the root of subtree on right side. So, number of distinct subtrees on left side is $l^{l-2}$, and number of distinct subtrees on right side is $r^{r-2}$. Thus, on mutliplying all(since they are independent), we get ${n \\choose l} \\cdot l \\cdot r \\cdot l^{l-2} \\cdot r^{r-2}$ possibilities for $e$. Now this edge lies on the path from $1$ to $n$ as both lie on opposite sides of this node. So this edge contributes $(-1)^l \\cdot {{n-2} \\choose {l-1}} \\cdot l \\cdot r \\cdot l^{l-2} \\cdot r^{r-2}$ to answer. Hence $d(1,n)=\\sum_{l=1}^{n-1} (-1)^l \\cdot {{n-2} \\choose {l-1}} \\cdot l \\cdot r \\cdot l^{l-2} \\cdot r^{r-2}$ where $l+r=n$. Note that we assumed that we are always going from left subtree to right subtree while calculating contribution. As we have tried all possibilties for l, all cases get covered. We used left and right subtrees just for our own convention. Time complexity is $O(n \\cdot \\log(n))$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nconst ll MOD=998244353;\nconst ll MAX=500500;\nvector<ll> fact(MAX+2,1),inv_fact(MAX+2,1);\nll binpow(ll a,ll b,ll MOD){\n    ll ans=1;\n    a%=MOD;  \n    while(b){\n        if(b&1)\n            ans=(ans*a)%MOD;\n        b/=2;\n        a=(a*a)%MOD;\n    }\n    return ans;\n}\nll inverse(ll a,ll MOD){\n    return binpow(a,MOD-2,MOD);\n} \nvoid precompute(ll MOD){\n    for(ll i=2;i<MAX;i++){\n        fact[i]=(fact[i-1]*i)%MOD;\n    }\n    inv_fact[MAX-1]=inverse(fact[MAX-1],MOD);\n    for(ll i=MAX-2;i>=0;i--){\n        inv_fact[i]=(inv_fact[i+1]*(i+1))%MOD;\n    }\n}\nll nCr(ll a,ll b,ll MOD){\n    if((a<0)||(a<b)||(b<0))\n        return 0;   \n    ll denom=(inv_fact[b]*inv_fact[a-b])%MOD;\n    return (denom*fact[a])%MOD;  \n}\nvoid solve(){         \n    ll n,ans=0; cin>>n;\n    if(n&1){  \n        cout<<0;    \n        return;\n    }\n    ll sgn=1;  \n    for(ll i=1;i<n;i++){ \n        sgn*=-1; \n        ll r=n-i,l=i;\n        ll fix_l=nCr(n-2,l-1,MOD); //fixing l nodes on left side  \n        ll fix_root=(l*r)%MOD; //fixing roots of subtrees on both sides \n        ll trees=(binpow(l,l-2,MOD)*binpow(r,r-2,MOD))%MOD; //counting no of subtrees\n        ll no_of_e=(((fix_l*fix_root)%MOD)*trees)%MOD; //no of possibilities for e\n        ans=(ans+sgn*no_of_e)%MOD;\n    }     \n    ans=(ans+MOD)%MOD;          \n    cout<<ans; \n    return;            \n} \nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    precompute(MOD);\n    ll t=1; \n    //cin>>t;\n    while(t--){\n        solve();\n    }\n} ",
    "tags": [
      "combinatorics",
      "math",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1762",
    "index": "F",
    "title": "Good Pairs ",
    "statement": "You are given an array $a$ consisting of $n$ integers and an integer $k$.\n\nA pair $(l,r)$ is good if there exists a sequence of indices $i_1, i_2, \\dots, i_m$ such that\n\n- $i_1=l$ and $i_m=r$;\n- $i_j < i_{j+1}$ for all $1 \\leq j < m$; and\n- $|a_{i_j}-a_{i_{j+1}}| \\leq k$ for all $1 \\leq j < m$.\n\nFind the number of pairs $(l,r)$ ($1 \\leq l \\leq r \\leq n$) that are good.",
    "tutorial": "We should have $|a_{i_j}-a_{i_{j+1}}| \\leq k$. This seems a bit hard, as we can have $a_{i_{j+1}}$ greater than, smaller than or equal to $a_{i_j}$. Why not solve the easier version first? A pair $(l,r)$ is good if there exists a sequence of indices $i_1, i_2, \\dots, i_m$ such that $i_1=l$ and $i_m=r$; $i_j < i_{j+1}$ for all $1 \\leq j < m$; and $0 < a_{i_j}-a_{i_{j+1}} \\leq k$ for all $1 \\leq j < m$. Suppose $F(a,k)$ number of pairs $(l,r)$ ($1 \\leq l < r \\leq n$) that are good. Find $F(a,k)$. To solve the problem in hint $1$, let us define $dp_i$ as the number of pairs $j(i<j)$ such that $(i,j)$ is good. Let us move from $i=n$ to $1$. To find $dp_i$, let us first find the smallest index $j$ such that $a_j$ lies in range $[a_i+1,a_i+k]$. We can observe that $dp_i=dp_j+f(i,a_i+1,a_j)$, where $f(i,l,r)$ gives us the number of indices $x$ among last $i$ elements of $a$ such that $a_x$ lies in the range $[l,r]$. We can use fenwik tree or ordered set to find $f(i,l,r)$. Now let us get back to original problem. First let us count number of pairs $(i,j)(1 \\leq i \\leq j)$ such that $a_i=a_j$. Assume $cnt$ is number of such pairs. Time for another cool claim! For our original problem, answer is $cnt+F(a,k)+F(rev(a),k)$, where $rev(a)$ denotes the array $a$ when it is reversed. How to prove the claim in hint $3$? Suppose we have a good pair $(l,r)$ such that $a_l \\neq a_r$. Now using exchange arguments we can claim that there always exists a sequence(say $s$) starting at index $l$ and ending at index $r$ such that difference between adjacent elements of $a$ is atmost $k$ strictly increasing if $a_l < a_r$ strictly decreasing if $a_l > a_r$ Thus $(l,r)$ will be counted in $F(a,k)$ if $a_l < a_r$ and $(l,r)$ will be counted in $F(rev(a),k)$ if $a_l > a_r$. Time complexity is $O(n \\cdot \\log(n))$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nconst ll MAX=1000100;\nclass ST{\npublic:\n    vector<ll> segs;\n    ll size=0;                       \n    ll ID=MAX;\n \n    ST(ll sz) {\n        segs.assign(2*sz,ID);\n        size=sz;  \n    }   \n   \n    ll comb(ll a,ll b) {\n        return min(a,b);  \n    }\n \n    void upd(ll idx, ll val) {\n        segs[idx+=size]=val;\n        for(idx/=2;idx;idx/=2){\n            segs[idx]=comb(segs[2*idx],segs[2*idx+1]);\n        }\n    }\n \n    ll query(ll l,ll r) {\n        ll lans=ID,rans=ID;\n        for(l+=size,r+=size+1;l<r;l/=2,r/=2) {\n            if(l&1) {\n                lans=comb(lans,segs[l++]);\n            }\n            if(r&1){\n                rans=comb(segs[--r],rans);\n            }\n        }\n        return comb(lans,rans);\n    }\n};\nstruct FenwickTree{\n    vector<ll> bit; \n    ll n;\n    FenwickTree(ll n){\n        this->n = n;\n        bit.assign(n, 0);\n    }\n    FenwickTree(vector<ll> a):FenwickTree(a.size()){\n        ll x=a.size();\n        for(size_t i=0;i<x;i++)\n            add(i,a[i]);\n    }\n    ll sum(ll r) {\n        ll ret=0;\n        for(;r>=0;r=(r&(r+1))-1)\n            ret+=bit[r];\n        return ret;\n    }\n    ll sum(ll l,ll r) {\n        if(l>r)\n            return 0;\n        return sum(r)-sum(l-1);\n    }\n    void add(ll idx,ll delta) {\n        for(;idx<n;idx=idx|(idx+1))\n            bit[idx]+=delta;\n    }\n};\nFenwickTree freq(MAX);  \nST segtree(MAX);\nvector<ll> dp(MAX,0);\nll solve(vector<ll> a,ll n,ll k){\n    ll now=0;\n    for(ll i=n-1;i>=0;i--){  \n        ll j=segtree.query(a[i]+1,a[i]+k);\n        if(j<n){\n            dp[i]=dp[j]+freq.sum(a[i]+1,a[j]);\n        }\n        else{\n            dp[i]=0;\n        }\n        now+=dp[i];\n        segtree.upd(a[i],i);\n        freq.add(a[i],1);\n    }  \n    for(auto it:a){  \n        segtree.upd(it,MAX);  \n        freq.add(it,-1); \n    }\n    return now;\n}\nvoid solve(){         \n    ll n,k; cin>>n>>k;\n    vector<ll> a(n);\n    ll ans=0;\n    map<ll,ll> cnt;  \n    for(auto &it:a){\n        cin>>it;\n        cnt[it]++;\n        ans+=cnt[it];\n    }\n    ans+=solve(a,n,k);\n    reverse(a.begin(),a.end());\n    ans+=solve(a,n,k);\n    cout<<ans<<\"\\n\"; \n    return;            \n} \nint main()                                                                                \n{  \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);  \n    ll t=1; \n    cin>>t;\n    while(t--){\n        solve();\n    }\n} ",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1762",
    "index": "G",
    "title": "Unequal Adjacent Elements",
    "statement": "You are given an array $a$ consisting of $n$ positive integers.\n\nFind any permutation $p$ of $[1,2,\\dots,n]$ such that:\n\n- $p_{i-2} < p_i$ for all $i$, where $3 \\leq i \\leq n$, and\n- $a_{p_{i-1}} \\neq a_{p_i}$ for all $i$, where $2 \\leq i \\leq n$.\n\nOr report that no such permutation exists.",
    "tutorial": "Answer is NO only when there exists an element of $a$ which occurs more that $\\lceil \\frac{n}{2} \\rceil$ times. Let us say an array $b$ is beautiful if length of $b$ is odd and mode(say $x$) of $b$ occurs exactly $\\lceil \\frac{n}{2} \\rceil$ times. If $a$ is beautiful, there exists only one permutation. We have rearrange such that $x$ occupies all the odd indices and keep the elements at even indices such that condition $2$ in satisfied. To solve the original problem, we will divide the array $a$ into multiple beautiful subarrays and arrange the elements in those subarrays. Let us continue from where we left off. So our motivation is to break the original array into multiple beautiful subarrays and the elements in those subarrays, as mentioned before. Now for condition $1$ to be satisfied, we should not have two adjacent subarrays such that the elements at the end positions of both subarrays(after rearranging the elements) are the same. Here is one construction using which we can achieve our goal. Suppose $l$ denotes the leftmost point of our concerned subarray. If $a_l \\neq a_{l+1}$, we move forward, as subarray $a[l,l]$ is good. Otherwise, we keep moving towards the right till index $r$(here, $r$ should be the smallest possible) such that the subarray $a[l,r]$ is beautiful and $a_l \\neq a_{r+1}$. So it is easy to notice the following observations about the subarray $a[l,r]$ length of this subarray is odd length of this subarray is odd $a_l$ occurs exactly $\\lceil \\frac{r-l+1}{2} \\rceil$ times in this subarray $a_l$ occurs exactly $\\lceil \\frac{r-l+1}{2} \\rceil$ times in this subarray Now we can rearrange the elements of this subarray $a[l,r]$. Do note that the subarray $a[1,r]$ satisfies both the conditions stated in the statement. So our task is to make the subarray $a[r+1,n]$ good now. We can now update $l=r+1$ and continue searching for the corresponding $r$ and so on. Now it might be the case that we did not get a valid $r$ for the last search. From here, I assume we did not get valid $r$ for the last search. We could print the obtained permutation if we got it, as $a$ would satisfy both conditions. Assume that we had started at $pos=l$ and couldn't find $r$. Subarray $a[1,pos-1]$ is already good. To fix this issue, we will do a similar search that we did before. We start from the back(from index $n$) and move towards left till index $m$ such that $m < pos$ $a[m,n]$ is beautiful $a_{pos}$ occurs exactly $\\lceil \\frac{n-m+1}{2} \\rceil$ times in this subarray $a_{pos} \\neq a_{m-1}$ Now we arrange elements of this subarray in the same fashion that we did before. Are we done? No. First, we must prove that we will always get some $m$. Let us have function $f(a,l,r,x)$, which denotes the score of the subarray $a[l,r]$ for the element $x$. $f(a,l,r,x)=freq_x-(r-l+1-freq_x)$, where $freq_x$ denotes the frequency of element $x$ in the subarray $a[l,r]$ It is easy to note that $f(a,pos,n,a_{pos}) > 1$ (Hint $-$ Prove that $f(a,pos,r,a_{pos}) \\neq 0$ for $pos \\leq r \\leq n$. Why?(If it does then $a[pos,r-1]$ would be beautiful )) Now we start from the back and move towards the right to find $m$ with $n$ as our right endpoint of the concerned subarray. Note that $f(a,1,n,a_{pos}) \\leq 1$ (Why? $a_{pos}$ would have occurred at most $\\lceil \\frac{n}{2} \\rceil$ times in $a$) So while moving from $pos$ to $1$ we will indeed find a $m$ such that $f(a,m,n,a_{pos})=1$, and $a_{m-1} \\neq a_{pos}$ (assuming $a_0=-1$) Are we done? Not still :p. We can observe that condition $1$ is satisfied, but sometimes condition $2$ would not be. For example, simulate the above approach on the array $a=[1,1,2,3,3]$. How to fix this issue? It's pretty easy to fix this issue. Instead of rearranging the subarray $a[m,n]$, we will rearrange the subarray $a[m-1,n]$. How to rearrange? Okay, time for one more hint. What will be the answer for $a=[1,1,2,3,3]$? $p=[1,4,2,5,3]$ You can refer to the attached code for implementation details.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;  \n#define ll long long  \n#define all(x) x.begin(),x.end()     \nvoid solve(){    \n    ll n; cin>>n;\n    vector<ll> a(n+5),freq(n+5,0);\n    for(ll i=1;i<=n;i++){\n        cin>>a[i]; freq[a[i]]++;\n    }\n    for(ll i=1;i<=n;i++){\n        ll till=(n+1)/2;\n        if(freq[i]>till){\n            cout<<\"NO\\n\";\n            return;\n        }\n    }\n    cout<<\"YES\\n\";\n    vector<ll> ans;\n    ll cur=1;\n    while(cur<=n){\n        ll val=a[cur];\n        vector<ll> v1,v2;\n        while(cur<=n){\n            if(a[cur]==val){\n                v1.push_back(cur);\n            }\n            else{\n                v2.push_back(cur);\n            }\n            if(v1.size()==v2.size()){\n                for(ll i=0;i<v1.size();i++){\n                    ans.push_back(v1[i]); ans.push_back(v2[i]);\n                }\n                ans.pop_back();\n                break; \n            }\n            if(cur==n){\n                while(1){\n                    if(ans.empty()||v1.size()==v2.size()){\n                        sort(all(v1)); sort(all(v2));\n                        if(v1.size()!=v2.size()){\n                            ans.push_back(v1[0]);\n                            v1.erase(v1.begin());\n                        }\n                        if(!v2.empty()&&!ans.empty()){\n                            if(a[ans.back()]==a[v2[0]]){\n                                swap(v1,v2);\n                            }\n                        }\n                        for(ll i=0;i<v1.size();i++){\n                            ans.push_back(v2[i]); ans.push_back(v1[i]);  \n                        }\n                        break;\n                    }\n                    if(a[ans.back()]==val){\n                        v1.push_back(ans.back());\n                    }\n                    else{\n                        v2.push_back(ans.back());\n                    }\n                    ans.pop_back();\n                }\n                cur=n+1;\n            }\n            cur++;\n        }\n    }\n    for(auto it:ans){\n        cout<<it<<\" \";\n    }\n    cout<<\"\\n\";\n    return;                                \n}                                                \nint main()                                                                                             \n{                          \n    ll test_cases=1;               \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    } \n}  ",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1763",
    "index": "A",
    "title": "Absolute Maximization",
    "statement": "You are given an array $a$ of length $n$. You can perform the following operation several (possibly, zero) times:\n\n- Choose $i$, $j$, $b$: Swap the $b$-th digit in the binary representation of $a_i$ and $a_j$.\n\nFind the maximum possible value of $\\max(a) - \\min(a)$.\n\nIn a binary representation, bits are numbered from right (least significant) to left (most significant). Consider that there are an infinite number of leading zero bits at the beginning of any binary representation.\n\nFor example, swap the $0$-th bit for $4=100_2$ and $3=11_2$ will result $101_2=5$ and $10_2=2$. Swap the $2$-nd bit for $4=100_2$ and $3=11_2$ will result $000_2=0_2=0$ and $111_2=7$.\n\nHere, $\\max(a)$ denotes the maximum element of array $a$ and $\\min(a)$ denotes the minimum element of array $a$.\n\nThe binary representation of $x$ is $x$ written in base $2$. For example, $9$ and $6$ written in base $2$ are $1001$ and $110$, respectively.",
    "tutorial": "Which $1$s in the binary representation cannot be changed to $0$. Similarly, Which $0$s in the binary representation cannot be changed to $1$. Considering the last two hints, try to maximize the maximum element and minimize the minimum element. In the minimum element, we want to make every bit $0$ when possible, it won't be possible to set a particular bit to $0$ when that bit is set in all the elements of $a$. Therefore, the minimum value we can achieve after performing the operations is the bitwise AND of all the elements of $a$. In the maximum element, we want to make every bit $1$ when possible, it won't be possible to set a particular bit to $1$ when that bit is not set in any of the elements of $a$. Therefore, the maximum value we can achieve after performing the operations is the bitwise OR of all the elements of $a$. Therefore the answer is (OR of the array - AND of the array). Time Complexity: $O(n)$",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1763",
    "index": "B",
    "title": "Incinerate",
    "statement": "To destroy humanity, The Monster Association sent $n$ monsters to Earth's surface. The $i$-th monster has health $h_i$ and power $p_i$.\n\nWith his last resort attack, True Spiral Incineration Cannon, Genos can deal $k$ damage to all monsters alive. In other words, Genos can reduce the health of all monsters by $k$ (if $k > 0$) with a single attack.\n\nHowever, after every attack Genos makes, the monsters advance. With their combined efforts, they reduce Genos' attack damage by the power of the $^\\dagger$weakest monster $^\\ddagger$alive. In other words, the minimum $p_i$ among all currently living monsters is subtracted from the value of $k$ after each attack.\n\n$^\\dagger$The Weakest monster is the one with the least power.\n\n$^\\ddagger$A monster is alive if its health is strictly greater than $0$.\n\nWill Genos be successful in killing all the monsters?",
    "tutorial": "What if the array $p$ was sorted? Is it necessary to decrease the health of each monster manually after every attack? Sort the monsters in ascending order of their powers. Now we iterate through the monsters while maintaining the current attack power and the total damage dealt. Only the monsters with health greater than the total damage dealt are considered alive, and every time we encounter such a monster it will be the weakest one at the current time, thus we need to attack until the total damage dealt exceeds the current monster's health while lowering our attack power by its power each time. If we can kill all the monsters in this way, the answer is YES, otherwise it is NO. Time Complexity: $O(nlogn)$ Sort the monsters in ascending order of their health. Now we maintain a count of monsters alive after each attack. This could be achieved by applying $upper bound()$ on $h$ array for each attack. The total damage dealt could be stored and updated in a separate variable. To find the power of the weakest monster alive, we could just precompute the minimum power of monsters in a suffix array. In other words, $p_i = \\min(p_i, p_{i+1}).$ Time Complexity: $O(nlogn)$",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\n#define int long long\\n#define ll long long\\n#define el '\\\\n'\\n#define yes cout<<\\\"YES\\\"<<el\\n#define no cout<<\\\"NO\\\"<<el\\n#define f(i,a,b) for(ll i = a; i <= b; i++)\\n#define fr(i,a,b) for(ll i = a; i >= b; i--)\\n#define vi vector<int>\\n#define speed ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0)\\n#define pb push_back\\n#define all(x) x.begin(),x.end()\\n#define sz(x) ((int)(x).size())\\n#define test ll _x86_; cin>>_x86_; while(_x86_--)\\n \\nvoid solve()\\n{\\n    int n, k, baseh{0}; cin>>n>>k;\\n    vector<pair<int,int>> m(n); vi h(n); \\n\\n    f(i,0,n-1) cin>>m[i].first;\\n    f(i,0,n-1) cin>>m[i].second;\\n \\n    sort(all(m));\\n    \\n    f(i, 0, n-1) h[i] = m[i].first;\\n\\n    fr(i, n-2, 0) m[i].second = min(m[i+1].second, m[i].second);\\n\\n    while(k > 0)\\n    {\\n        int ded = upper_bound(all(h), k+baseh) - h.begin();\\n\\n        if(ded == n) { yes; return; }\\n        \\n        baseh += k;\\n        k -= m[ded].second;\\n    }\\n    no;\\n}\\n \\nint32_t main()\\n{\\n    speed;      test \\n \\n    solve();\\n}\"",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1763",
    "index": "C",
    "title": "Another Array Problem",
    "statement": "You are given an array $a$ of $n$ integers. You are allowed to perform the following operation on it as many times as you want (0 or more times):\n\n- Choose $2$ indices $i$,$j$ where $1 \\le i < j \\le n$ and replace $a_k$ for all $i \\leq k \\leq j$ with $|a_i - a_j|$\n\nPrint the maximum sum of all the elements of the final array that you can obtain in such a way.",
    "tutorial": "What happens when we apply the same operation twice? What about n = 3 ? Let's first consider the case for $n \\geq 4$. The key observation to make here is that we can make all the elements of a subarray $a_l,...a_r$ zero by applying the operation on range $[l,r]$ twice. Then let's assume the maximum element $mx$ of the array is at an index $m > r$. We can apply the operation on the range $[l,m]$ and turn all its elements into $mx$. Using the above information we can see that to achieve the final array with maximum sum we need to make all the elements in it equal to the maximum element in the array. Regardless of the given array this can be achieved by making the last two elements (n-1,n) zero. Then applying the operation on subarray $[m,n]$ to make all its elements equal to $mx$. Then making the first two elements (1,2) zero and applying the operation on the whole array making all the elements equal to $mx$. Thus the maximum sum for the final array will always be $n*mx$. (In case $m = n-1$ or $n$, we can operate on the left side first to reach the same solution). For $n = 2$ the maximum final sum would be $\\max(a_1+a_2, 2*(|a_1-a_2|))$. For $n=3$, when the maximum element is present at index $1$ or $3$ we can make all the elements of the array into $mx$. When the maximum element is at index $2$, we have the following options. Case 1: We can apply the operation on (1,2), then we can convert all the elements of the array into $\\max(a_3,|a_2-a_1|)$. Case 2: We can apply the operation on (2,3), then we can convert all the elements of the array into $\\max(a_1,|a_2-a_3|)$. Case 3: We can apply the operation on (1,3) making all the elements in the array $|a_1-a_3|$. This is redundant since $a_2 > a_1,a_3$ either case 1 or case 2 will give a larger sum as $a_2 - \\min(a_1,a_3) > \\max(a_1,a_3) - \\min(a_1,a_3)$. Now considering case 1, if $3* \\max(a_3,|a_2-a_1|) \\leq a_1+a_2+a_3$ the maximum sum possible would be the current sum of the array (see sample 1 and 3). Therefore no operations are required. Similar case for case 2. So the maximum possible sum for $n=3$ will be $\\max(3*a_1, 3*a_3, 3*|a_1-a_2|, 3*|a_3-a_2|,a_1+a_2+a_3)$. To avoid doing this casework for $n = 3$, we can see that there are only 3 possible operations -> (1,2) , (2,3), (1,3). We will be required to perform operations (1,2) and (2,3) at most two times. So we can brute force all possible combinations of operations [(1,2),(1,2),(2,3),(2,3),(1,3)] to find the maximum sum.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define ll long long\n#define pii pair<ll, ll>\nint32_t mod = 1e9 + 7;\n\n\nvoid solve()\n{\n    ll n;\n    cin >> n;\n    vector<ll> a(n);\n    for (auto &i : a)\n        cin >> i;\n    if (n == 2)\n        cout << max({2 * abs(a[0] - a[1]), a[0] + a[1]});\n    else if (n == 3)\n        cout << max({3 * (abs(a[0] - a[1])), 3 * (abs(a[2] - a[1])), 3 * a[0], 3 * a[2], a[0] + a[1] + a[2]});\n    else\n    {\n        ll mx = 0;\n        for (auto i : a)\n            mx = max(i, mx);\n        cout << n * mx;\n    }\n    cout<<'\\n';\n}\n\nint32_t main()\n{\n    ios::sync_with_stdio(false), cin.tie(NULL);\n    ll t = 0;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1763",
    "index": "D",
    "title": "Valid Bitonic Permutations",
    "statement": "You are given five integers $n$, $i$, $j$, $x$, and $y$. Find the number of bitonic permutations $B$, of the numbers $1$ to $n$, such that $B_i=x$, and $B_j=y$. Since the answer can be large, compute it modulo $10^9+7$.\n\nA bitonic permutation is a permutation of numbers, such that the elements of the permutation first increase till a certain index $k$, $2 \\le k \\le n-1$, and then decrease till the end. Refer to notes for further clarification.",
    "tutorial": "Can you solve the problem when $x < y$? When $x > y$, perform $i'=n-j+1$, $j'=n-i +1$, $x' = y$, and $y' = x$. Can you solve the problem for a fixed value of $k$? Iterate over possible values of $k$. The total count is the sum of the individual counts. Club the remaining numbers into ranges as follows: $[1,x-1]$, $[x+1,y-1]$, and $[y+1,n-1]$. For simplicity, if $x > y$, perform $i' = n-j+1$, $j' = n-i+1$, $x' = y$, and $y' = x$. Hereafter, the variables $i$, $j$, $x$, and $y$, will refer to these values. Now, $i < j$ and $x < y$. For now, assume that $y < n$. We shall consider the case where $y = n$ at a later stage. Let us consider solving the problem for fixed $k$. Valid values for $k$ are $[2,i-1]$, $[i+1,j-1]$, $[j+1,n-1]$. If we think about it, when $x < y$, $k$ cannot lie in the range $[2, i-1]$. So, we can discard them as possible values for $k$. Let us consider the case where $k$ belongs to $[i+1,j-1]$. The permutation adheres to the following pattern: $B_1 < .. < B_i = x < .. < B_k = n > .. > B_j = y > .. > B_n$. Numbers to the left of $i$ must lie in the range $[1,x-1]$. We choose $i-1$ elements from $[1,x-1]$ and place them to the left of $i$. There are ${x-1 \\choose i-1}$ ways to do this. The remaining $x-i$ elements from $[1,x-1]$ lie to the right of $j$ by default. Numbers to the right of $j$ must lie in the range $[1,x-1]$ or $[x+1,y-1]$. Since numbers in the range $[1,x-1]$ have already been placed, therefore, we choose numbers in the range $[x+1,y-1]$, and place them in the $n-j-(x-i)$ remaining positions. There are ${y-x-1 \\choose n-j-(x-i)}$ ways to do this. The remaining elements in the range $[x+1,y-1]$ lie between $i$ and $k$ by default. Numbers between $k$ and $j$ must lie in the range $[y+1,n-1]$. We choose $j-k-1$ elements from $[y+1,n-1]$ and place them between $k$ and $j$. There are ${n-y-1 \\choose j-k-1}$ ways to do this. Afterwards, the remaining elements in the range lie between $i$ and $k$ by default, and the permutation is full. ${x-1 \\choose i-1} * {y-x-1 \\choose n-j-(x-i)} * {n-y-1 \\choose j-k-1}$ Let us consider the case where $k$ belongs to the range $[j+1,n-1]$. The permutation adheres to the following pattern: $B_1 < .. < B_i = x < .. < B_j= y < .. < B_k = n > .. > B_n$. Similar to above, the numbers to the left of $i$ must lie in the range $[1,x-1]$. We choose $i-1$ elements from $[1,x-1]$, and place them to the left of $i$. The remaining $x-i$ elements from $[1,x-1]$ lie to the right of $k$ by default. Numbers between $i$ and $j$ must lie in the range $[x+1,y-1]$. We choose $j-i-1$ elements from $[x+1,y-1]$ and place them between $i$ and $j$. There are ${y-x-1 \\choose j-i-1}$ ways to do this, and the remaining elements from $[x+1,y-1]$ lie to the right of $k$ by default. Numbers between $j$ and $k$ must lie in the range $[y+1,n-1]$. We choose $k-j-1$ elements from $[y+1,n-1]$ and place them in these positions. Afterwards, the remaining elements in the range get placed to the right of $k$ by default, and the permutation is full. ${x-1 \\choose i-1} * {y-x-1 \\choose j-i-1} * {n-y-1 \\choose k-j-1}$ The answer to the problem is the sum of individual answers for all iterated values of $k$. $ans = {x-1 \\choose i-1} * {y-x-1 \\choose n-j-(x-i)} * \\sum_{k=i+1}^{j-1} {n-y-1 \\choose j-k-1}$ + ${x-1 \\choose i-1} * {y-x-1 \\choose j-i-1} * \\sum_{k=j+1}^{n-1} {n-y-1 \\choose k-j-1}$ Let us now consider the case where $y = n$. The permutation adheres to the following pattern: $B_1 < .. < B_i = x < .. < B_j = B_k = n > .. > B_n$. Again, the numbers to the left of $i$ must lie in the range $[1,x-1]$. We choose $i-1$ elements from $[1,x-1]$ and place them to the left of $i$. The remaining $x-i$ elements from $[1,x-1]$ lie to the right of $j$ (here, $k$) by default. Numbers between $i$ and $j$ must lie in the range $[x+1,y-1]$. We choose $j-i-1$ elements form $[x+1,y-1]$ and place them between $i$ and $j$. The remaining elements from $[x+1,y-1]$ lie to the right of $j$ (here, $k$) by default, and the permutation is full. ${x-1 \\choose i-1} * {y-x-1 \\choose j-i-1}$ With $O(n_{max}*log(10^9+7-2))$ precomputation for factorials and their modular inverses, each individual test can be solved as above in $O(n)$. Therefore, the overall complexity of this approach is $O(n_{max}*log(10^9+7-2) + t*n)$, but the constraints allowed for slower solutions as well. $Bonus:$ Can you solve the problem when $1 \\le t, n \\le 10^5$.",
    "code": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nconst int MOD = 1000000007;\nvector<int> fac;\nvector<int> ifac;\n\nint binExp(int base, int exp) {\n    base %= MOD;\n    int res = 1;\n    while (exp > 0) {\n        if (exp & 1) {\n            res = (int) ((long long) res * base % MOD);\n        }\n        base = (int) ((long long) base * base % MOD);\n        exp >>= 1;\n    }\n    return res;\n}\n\nvoid precompute(int n) {\n    fac.resize(n + 1);\n    fac[0] = fac[1] = 1;\n    for (int i = 2; i <= n; i++) {\n        fac[i] = (int) ((long long) i * fac[i-1] % MOD);\n    }\n\n    ifac.resize(n + 1);\n    for (int i = 0; i < fac.size(); i++) {\n        ifac[i] = binExp(fac[i], MOD - 2);\n    }\n    return;\n}\n\nint nCr(int n, int r) {\n    if ((n < 0) || (r < 0) || (r > n)) {\n        return 0;\n    }\n    return (int) ((long long) fac[n] * ifac[r] % MOD * ifac[n - r] % MOD);\n}\n\nint countValidBitonicPerm(int n, int i, int j, int x, int y) {\n    if (x > y) {\n        i = n - i + 1;\n        j = n - j + 1;\n        swap(i, j);\n        swap(x, y);\n    }\n\n    int sum = 0;\n    for (int k = i + 1; k < j; k++) {\n        sum += nCr(n - y - 1, j - k - 1);\n        sum %= MOD;\n    }\n    int count = (int) ((long long) nCr (x - 1, i - 1) * nCr(y - x - 1, n - j - (x - i)) % MOD * sum % MOD);\n\n    sum = 0;\n    for (int k = j + 1; k < n; k++) {\n        sum += nCr(n - y - 1, k - j - 1);\n        sum %= MOD;\n    }\n    count += (int) ((long long) nCr(x - 1, i - 1) * nCr(y - x - 1, j - i - 1) % MOD * sum % MOD);\n    count %= MOD;\n\n    if (y == n) {\n        if (j == n) {\n            return 0;\n        } else {\n            return (int) ((long long) nCr(x - 1, i - 1) * nCr(y - x - 1, j - i - 1) % MOD);\n        }\n    }\n    \n    return count;\n}\n\nint main() {\n    const int MAXN = 100;\n    precompute(MAXN);\n\n    int testCases;\n    cin >> testCases;\n    for (int test = 1; test <= testCases; test++) {\n        int n, i, j, x, y;\n        cin >> n >> i >> j >> x >> y;\n        cout << countValidBitonicPerm(n, i, j, x, y) << endl;\n    }\n\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1763",
    "index": "E",
    "title": "Node Pairs",
    "statement": "Let's call an ordered pair of nodes $(u, v)$ in a directed graph unidirectional if $u \\neq v$, there exists a path from $u$ to $v$, and there are no paths from $v$ to $u$.\n\nA directed graph is called $p$-reachable if it contains exactly $p$ ordered pairs of nodes $(u, v)$ such that $u < v$ and $u$ and $v$ are reachable from each other. Find the minimum number of nodes required to create a $p$-reachable directed graph.\n\nAlso, among all such $p$-reachable directed graphs with the minimum number of nodes, let $G$ denote a graph which maximizes the number of unidirectional pairs of nodes. Find this number.",
    "tutorial": "In a directed graph, which nodes are reachable from each other? How many such pairs of nodes exist? Think about a sequence of SCCs. For two nodes $u$ and $v$ to be reachable from each other, they must lie in the same strongly connected component (SCC). Let's define $f(i)$ as the minimum number of nodes required to construct an $i$-reachable graph. We can use dynamic programming and calculate $f(i)$ as $f(i) = \\min(f(i - \\frac{s (s - 1)}{2}) + s)$ over all the valid SCC sizes $s$ for which $\\frac{s (s - 1)}{2} \\leq i$, i.e., over those $s$ which have less pairs of the required type than $i$. Thus, $f(p)$ gives us the minimum number of nodes required to create a $p$-reachable graph. In all $p$-reachable graphs with $f(p)$ nodes, the upper bound on the number of unidirectional pairs of nodes is $\\binom{f(p)}{2} - p$, because we have exactly $p$ pairs of nodes which are reachable from each other. It is possible to achieve this upper bound using the following construction: let $s_1, s_2, \\ldots, s_k$ be any sequence of SCC sizes which agrees with the dp values we calculated earlier. Let the first SCC contain the nodes $[1, s_1]$, the second one contain $[s_1 + 1, s_1 + s_2]$, and so on. We add a directed edge from $u$ to $v$ if $u < v$. Time Complexity: $\\mathcal{O}(p\\sqrt{p})$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int INF = 1e9;\n\nvoid solve()\n{\n    int p;\n    cin >> p;\n \n    vector<int> dp(p + 1, INF);\n    dp[0] = 0;\n    for (int i = 1; i <= p; ++i)\n        for (int s = 1; (s * (s - 1)) / 2 <= i; ++s)\n            dp[i] = min(dp[i], dp[i - (s * (s - 1)) / 2] + s);\n\n    cout << dp[p] << ' ' << ((long long) dp[p] * (dp[p] - 1)) / 2 - p << '\\n';\n}\n \nint main()\n{\n    solve();\n    return 0;\n}",
    "tags": [
      "dp",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1763",
    "index": "F",
    "title": "Edge Queries",
    "statement": "You are given an undirected, connected graph of $n$ nodes and $m$ edges. All nodes $u$ of the graph satisfy the following:\n\n- Let $S_u$ be the set of vertices in the longest simple cycle starting and ending at $u$.\n- Let $C_u$ be the union of the sets of vertices in any simple cycle starting and ending at $u$.\n- $S_u = C_u$.\n\nYou need to answer $q$ queries.\n\nFor each query, you will be given node $a$ and node $b$. Out of all the edges that belong to any simple path from $a$ to $b$, count the number of edges such that if you remove that edge, $a$ and $b$ are reachable from each other.",
    "tutorial": "What kind of graph meets the conditions given in the statement? A graph with bridges connecting components with a hamiltonian cycle. Which edges will never be counted in answer to any query? Of course, the bridges. Restructure the graph to be able to answer queries. $query(u, v)$ on a tree can be solved efficiently via Lowest Common Ancestor (LCA). First, let us see examples of graphs that are valid or invalid according to the statement. In this graph, for node $4$, the longest simple cycle is $4 \\rightarrow 1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4$. $S_4 = {1, 2, 3, 4}$ All simple cycles from node $4$ are $4 \\rightarrow 1 \\rightarrow 2 \\rightarrow 3 \\rightarrow 4$ and $4 \\rightarrow 1 \\rightarrow 3 \\rightarrow 4$. $C_4 = {1, 2, 3, 4}$ So, $S_4 = C_4$. Similarly, $S_u = C_u$ for all $u$. A tree of such components is also a valid graph! Here, $S_4 = {1, 2, 3, 4}$ and $C_4 = {1, 2, 3, 4, 5, 6}$. So, $S_4 \\neq C_4$ The queries ask us to count all non-bridge edges in any simple path from $u$ to $v$. There are many ways to proceed with the solution. We will first go into a simple one that gives more insight into the problem. We can see our graph as a tree of BiConnected Components (BCCs). The edges of the tree are all bridges. Let's define a few things before continuing further. The first node of a BCC that is visited in the DFS tree will represent that BCC. Let $rep[u]$ be the representative of the BCC of node $u$. $cnt[u]$ be the number of edges in the BCC of $u$. Root node of our tree of BCCs is $root$. $lca(u, v)$ is the lowest common ancestor of $u$ and $v$. With all that set, let us now look at the DFS tree. We can build an array $dp$ to store the answer to $query(root, u)$, for all $u$, and to answer queries, we can use LCA. In a typical LCA use case, query(u, v) would be $dp[u] + dp[v] - 2 * dp[lca(u, v)]$, But is that the case here? Let us bring attention to a few things. Is $u = rep[u]$? If $u = rep[u]$, $u$ is the first vertex of its BCC in the DFS tree. Therefore all the edges in the BCC of $u$ will not lie in any simple path from $u$ to $root$. Example: In this graph, Let's say $root$ is $1$. See that, $dp[3]$ should be $0$, and $dp[4]$ should be $3$. They are in the same BCC, but $3$ is the topmost node, that is, the representative. Let $p$ be the parent of $u$. So, to calculate $dp[u]$, $\\begin{align} dp[u] = \\begin{cases} dp[p] & \\text{if $rep[u] = u$,}\\\\dp[rep[u]] + cnt[u] & \\text{otherwise} \\end{cases} \\end{align}$ Passing through the representative of a BCC. Let's say we have a graph of this type, Let's choose our $root$ to be $0$ and look at node $6$. There will be no simple path from $root$ to $6$ that uses the edges of the BCC of node $2$. Therefore, $dp[6]$ should not include edges from the BCC of node $2$. This is already dealt with by our earlier definition of $dp[u]$! The cases of $query(u, v)$. Now, $query(u, v)$ depends upon how $u$ and $v$ are connected in the graph. These are some significant cases. Case 1: $rep[u] = rep[v]$ That is, $u$ and $v$ are part of the same BCC. Therefore, the answer to $query(u, v)$ is just $cnt[u]$. Then, we have two cases concerning $lca(u, v)$. Case 2.1: We must visit only one node in the BCC of $lca(u, v)$. Case 2.2: We must visit at least two nodes in the BCC of $lca(u, v)$. Example: $u = 6, v = 5$ In 2.1, in any simple path from $u$ to $v$ we won't have any edge from the BCC of $lca(u, v)$. Therefore, we don't need to include $cnt[lca(u, v)]$ in the answer. While in 2.2, those edges will be included. In conclusion, in this setup, we need to determine how the simple paths from $u$ to $v$ cross through the BCC of $lca(u,v)$, then the queries will be answered. We can use binary lifting to determine which node is the lowest ancestor of $u$ in the DFS tree that is a part of the BCC of $lca(u, v)$. Similarly, we can find that node for $v$. We can judge which of the above cases any $query(u, v)$ is based on these two nodes. There are other ways to distinguish, including using a link-cut tree. We can create a smart graph to make it so that $query(u, v)$ is $dp[u] + dp[v] - 2 * dp[lca(u, v)] + val[lca(u, v)]$, with no casework involved. We will create virtual nodes representing each BCC. Remove all non-bridges from the graph, and connect all nodes of a BCC to its virtual node. For example: --> Here $v$ is the virtual node, and all the nodes present in BCC of $2$ are directly connected to the BCC's virtual node. Let us define the value of each actual node to be $0$ and every virtual node to be the count of edges of its BCC. Build an array $dp$ that stores the sum of the values of all vertices from $root$ to the current node. You can go back and see how each of the cases would be dealt with by this new graph.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1764",
    "index": "A",
    "title": "Doremy's Paint",
    "statement": "Doremy has $n$ buckets of paint which is represented by an array $a$ of length $n$. Bucket $i$ contains paint with color $a_i$.\n\nLet $c(l,r)$ be the number of distinct elements in the subarray $[a_l,a_{l+1},\\ldots,a_r]$. Choose $2$ integers $l$ and $r$ such that $l \\leq r$ and $r-l-c(l,r)$ is maximized.",
    "tutorial": "Assume that you have picked a interval $[L,R]$ as your answer. Now try to move the left point to make the answer larger. Compare $[L,R]$ with $[L-1,R]$. $\\Delta(r-l)=1$ because the length of the interval increases by $1$. $\\Delta c(l,r)$ increases at most $1$. If $a_L$ appears in $[L,R]$, $c(L,R)=c(L-1,R)$; If $a_L$ does not appear in $[L,R]$, $c(L,R)+1=c(L-1,R)$. So $[L-1,R]$ is always better than $[L,R]$. Furthermore, we can see that if $a\\le b \\le c \\le d$, then $[a,d]$ is better than $[b,c]$. Since $[1,n]$ includes all intervals, it is always better than any other interval. So just output $1$ and $n$.",
    "code": "#include <iostream>\n\nvoid solve(){\n    int n; std::cin >> n;\n    for(int i = 1 ,nouse ; i <= n ; ++i){\n        std::cin >> nouse;\n    }\n    std::cout << \"1 \" << n << std::endl;\n}\n\nint main(){\n    int t; std::cin >> t;\n    while(t--) solve();\n    return 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1764",
    "index": "B",
    "title": "Doremy's Perfect Math Class",
    "statement": "\"Everybody! Doremy's Perfect Math Class is about to start! Come and do your best if you want to have as much IQ as me!\" In today's math class, Doremy is teaching everyone subtraction. Now she gives you a quiz to prove that you are paying attention in class.\n\nYou are given a set $S$ containing \\textbf{positive} integers. You may perform the following operation some (possibly zero) number of times:\n\n- choose two integers $x$ and $y$ from the set $S$ such that $x > y$ and $x - y$ is not in the set $S$.\n- add $x-y$ into the set $S$.\n\nYou need to tell Doremy the maximum possible number of integers in $S$ if the operations are performed optimally. It can be proven that this number is finite.",
    "tutorial": "For any two natural numbers $x,y$ , assign $|x-y|$ to the bigger number. Repeat this process until the smaller number becomes $0$, and then the bigger number will become $\\gcd(x,y)$. So we can know that if $x,y\\in S$, then it is guaranteed that $\\gcd(x,y)\\in S$. So $\\gcd(a_1,a_2,\\dots,a_n)\\in S$. Let $t=\\gcd(a_1,a_2,\\dots,a_n),A=\\max(a_1,a_2,\\dots,a_n)=Kt$, then $t,A\\in S$. So $t,2t,\\dots,Kt\\in S$. Because $|x-y|\\le \\max(x,y)$, any number bigger than $A$ will not be in $S$. Because $|xt-yt|=|x-y|t$, any number which is not divisible by $t$ will not be in $S$. And $0\\not\\in S$. So $t,2t,\\dots,Kt$ are all the numbers that can be in $S$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int maxn=100005;\nint a[maxn];\nint gcd(int a,int b){\n\treturn b==0?a:gcd(b,a%b);\n}\nint main(){\n\tint t;scanf(\"%d\",&t);\n\twhile(t--){\n\t\tint n;scanf(\"%d\",&n);\n\t\tint tmp=0;\n\t\tfor(int i=1;i<=n;++i){\n\t\t\tscanf(\"%d\",&a[i]);\n\t\t\ttmp=gcd(tmp,a[i]);\n\t\t}\n\t\tprintf(\"%d\\n\",a[n]/tmp+(a[1]==0));\n\t}\n\treturn 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1764",
    "index": "C",
    "title": "Doremy's City Construction",
    "statement": "Doremy's new city is under construction! The city can be regarded as a simple undirected graph with $n$ vertices. The $i$-th vertex has altitude $a_i$. Now Doremy is deciding which pairs of vertices should be connected with edges.\n\nDue to economic reasons, there should be no self-loops or multiple edges in the graph.\n\nDue to safety reasons, there should not be \\textbf{pairwise distinct} vertices $u$, $v$, and $w$ such that $a_u \\leq a_v \\leq a_w$ and the edges $(u,v)$ and $(v,w)$ exist.\n\nUnder these constraints, Doremy would like to know the maximum possible number of edges in the graph. Can you help her?\n\nNote that the constructed graph is allowed to be disconnected.",
    "tutorial": "We can first assume that no edge links two vertices with the same value, then for each vertex $u$ and his neighbors $S_u$, either $a_u>\\max\\limits_{v\\in S_u}a_v$ or $a_u<\\min\\limits_{v\\in S_u}a_v$. If $a_u>\\max\\limits_{v\\in S_u}a_v$, we paint $u$ black, otherwise we paint it white. Then it's obviously that any edge connects two vertices with different color. So we can first determine the color of each vertex and then add as many as edges according to the color. $(u,v)$ is addable only when $u$ is black, $v$ is white and $a_u>a_v$. If we paint $u$ black and $v$ white and $a_u<a_v$, we can swap the colors and the edges connecting to these 2 vertices and the answer will be no worse. So the best painting plan is determining a value $A$, painting $u$ black if and only if $a_u\\ge A$, painting $u$ white if and only if $a_u<A$. If we add an edge linking two vertices with the same value, then the two vertices can not connect other vertices. This plan will only be considered when $a_1=a_2=\\cdots=a_n$. When $a_1=a_2=\\cdots=a_n$, the answer is $\\lfloor\\frac{n}{2}\\rfloor$.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#define ch() getchar()\n#define pc(x) putchar(x)\nusing namespace std;\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(f=1,c=ch();c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch()){x=x*10+(c&15);}x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[64];int cnt=0;\n\tif(x==0)return pc('0'),void();\n\tif(x<0)pc('-'),x=-x;\n\twhile(x)q[cnt++]=x%10+'0',x/=10;\n\twhile(cnt--)pc(q[cnt]);\n}\nconst int maxn=200005;\nint a[maxn];\nint main(){\n\tint t;read(t);\n\twhile(t--){\n\t\tint n;read(n);\n\t\tfor(int i=1;i<=n;++i)\n\t\t\tread(a[i]);\n\t\tsort(a+1,a+n+1);\n\t\tif(a[1]==a[n]){\n\t\t\twrite(n/2),pc('\\n');\n\t\t\tcontinue;\n\t\t}\n\t\tlong long ans=0;\n\t\tfor(int l=1,r=1;l<=n;l=r=r+1){\n\t\t\twhile(r+1<=n&&a[r+1]==a[l])++r;\n\t\t\tans=max(ans,1ll*(n-r)*r);\n\t\t}\n\t\twrite(ans),pc('\\n');\n\t}\n\treturn 0;\n}",
    "tags": [
      "graphs",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1764",
    "index": "D",
    "title": "Doremy's Pegging Game",
    "statement": "Doremy has $n+1$ pegs. There are $n$ red pegs arranged as vertices of a regular $n$-sided polygon, numbered from $1$ to $n$ in anti-clockwise order. There is also a blue peg of \\textbf{slightly smaller diameter} in the middle of the polygon. A rubber band is stretched around the red pegs.\n\nDoremy is very bored today and has decided to play a game. Initially, she has an empty array $a$. While the rubber band does not touch the blue peg, she will:\n\n- choose $i$ ($1 \\leq i \\leq n$) such that the red peg $i$ has not been removed;\n- remove the red peg $i$;\n- append $i$ to the back of $a$.\n\nDoremy wonders how many possible different arrays $a$ can be produced by the following process. Since the answer can be big, you are only required to output it modulo $p$. $p$ is guaranteed to be a prime number.\n\n\\begin{center}\n{\\small game with $n=9$ and $a=[7,5,2,8,3,9,4]$ and another game with $n=8$ and $a=[3,4,7,1,8,5,2]$}\n\\end{center}",
    "tutorial": "The game will end immediately when the blue peg is not inside the convex formed by all remaining red pegs. Namely, there are $\\lfloor \\frac{n}{2} \\rfloor$ consecutive red pegs removed. It can be proven by geometry. Assume $t=\\lfloor \\frac{n}{2} \\rfloor$, and $n$ is odd. Let's enumerate the ending status: there are $i$ ($t \\le i\\le n -2$) consecutive red pegs removed and another $j$ ($0 \\le j \\le n - 2 - i$) red pegs removed. The last move makes the rubber band to stretch and touch the blue peg. So there is $2t-i$ ways to choose the last move. There are $\\binom{n-2-i}{j}$ ways to choose another $j$ pegs. And there are $\\binom{i+j-1}{j}j!(i-1)!$ ways to combine them. When $n$ is even, the analysis is similar. The only difference is that there is a special case when $i = n-1$. So the answer is: $\\begin{aligned} & n\\sum_{i=t}^{n-2} \\sum_{j=0}^{n-i-2}\\binom{n-i-2}{j}(i+j-1)!\\cdot(2t-i) \\\\ +&[n \\text{ is even}]n(n-2)! \\end{aligned}$",
    "code": "#include <cstdio>\n#include <iostream>\n\n#define LL long long\n\nconst int MX = 5000 + 233;\nLL C[MX][MX] ,n ,p ,fac[MX];\n\nvoid init(){\n\tfor(int i = 0 ; i < MX ; ++i) C[i][0] = 1;\n\tfor(int i = 1 ; i < MX ; ++i)\n\t\tfor(int j = 1 ; j < MX ; ++j)\n\t\t\tC[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % p;\n\tfac[0] = fac[1] = 1 % p;\n\tfor(int i = 2 ; i < MX ; ++i) fac[i] = fac[i - 1] * i % p;\n}\n\nint main(){\n\tstd::cin >> n >> p;\n\tinit();\n\tint t = n / 2;\n\tLL Ans = 0;\n\tfor(int i = t ; i <= n - 1 ; ++i){\n\t\tif((n & 1) && i == n - 1) break;\n\t\tint upper = (i == n - 1) ? n - i - 1 : n - i - 2;\n\t\tfor(int j = 0 ; j <= upper ; ++j){\n\t\t\tAns = (Ans + n * (2 * t - i) * C[upper][j] % p * fac[j + i - 1]) % p;\n\t\t}\n\t}\n\tstd::cout << Ans << std::endl;\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1764",
    "index": "E",
    "title": "Doremy's Number Line",
    "statement": "Doremy has two arrays $a$ and $b$ of $n$ integers each, and an integer $k$.\n\nInitially, she has a number line where no integers are colored. She chooses a permutation $p$ of $[1,2,\\ldots,n]$ then performs $n$ moves. On the $i$-th move she does the following:\n\n- Pick an \\textbf{uncolored} integer $x$ on the number line such that either:\n\n- $x \\leq a_{p_i}$; or\n- there exists a \\textbf{colored} integer $y$ such that $y \\leq a_{p_i}$ and $x \\leq y+b_{p_i}$.\n\n- Color integer $x$ with color $p_i$.\n\nDetermine if the integer $k$ can be colored with color $1$.",
    "tutorial": "First if $k$ can be colored with certain color, then any $K<k$ can also be colored the this color. So we only need to calculate what is the biggest number color $1$ can be. Apparently this value will not exceed $x_1+y_1$. If $x_1$ is not maximum among all $x$, you can pick any $j$ such that $x_j\\ge x_1$. Color point $x_1$ with color $j$, then color point $x_1+y_1$ with color $1$. So $x_1+y_1$ is the answer in this case. If $x_1$ is maximum, just enumerate which color precedes color $1$. No color precedes. Directly color $x_1$ with color $1$. Color $j$ precedes, but $x_j$ is not maximum among $x_2,x_3,\\cdots,x_n$. In this case, point $x_j+y_j$ can always be colored with color $j$. Point $\\min\\{x_j+y_j,x_1\\}+y_1$ can be colored with color $1$. Color $j$ precedes, meanwhile $x_j$ is maximum among $x_2,x_3,\\cdots,x_n$. In this case, we can just enumerate which color precedes color $j$, which leads to a recursion, until there is only one color remaining. Time complexity is $O(n \\log n)$ due to sorting.",
    "code": "#include <bits/stdc++.h>\n\n#define debug(...) fprintf(stderr ,__VA_ARGS__)\n#define LL long long\nconst int MX = 2e5 + 5;\n\nint n ,s;\nstruct Goat{\n    int x ,y ,id;\n}A[MX];\n\nbool cmp(Goat a ,Goat b){\n    return a.x < b.x;\n}\n\nint mx[MX];\nint calc(int id){\n    if(id == 1) return A[id].x;\n    int far = std::max(calc(id - 1) ,mx[id - 2]);\n    return std::max(std::min(far ,A[id].x) + A[id].y ,A[id].x);\n}\n\nint ans[MX];\nvoid solve(){\n    scanf(\"%d%d\" ,&n ,&s);\n    for(int i = 1 ,x ,y ; i <= n ; ++i){\n        scanf(\"%d%d\" ,&x ,&y);\n        A[i] = (Goat){x ,y ,i};\n        ans[i] = false;\n    }\n    std::sort(A + 1 ,A + 1 + n ,cmp);\n    for(int i = 1 ; i <= n ; ++i){\n        mx[i] = std::max(A[i].x + A[i].y ,mx[i - 1]);\n    }\n    for(int i = 1 ; i < n ; ++i){\n        if(A[i].x + A[i].y >= s){\n            ans[A[i].id] = true;\n        }\n    }\n    if(calc(n) >= s) ans[A[n].id] = true;\n    puts(ans[1] ? \"YES\" : \"NO\");\n}\n\nint main(){\n    int t; scanf(\"%d\" ,&t);\n    while(t--) solve();\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1764",
    "index": "F",
    "title": "Doremy's Experimental Tree",
    "statement": "Doremy has an edge-weighted tree with $n$ vertices whose weights are \\textbf{integers} between $1$ and $10^9$. She does $\\frac{n(n+1)}{2}$ experiments on it.\n\nIn each experiment, Doremy chooses vertices $i$ and $j$ such that $j \\leq i$ and connects them directly with an edge with weight $1$. Then, there is exactly one cycle (or self-loop when $i=j$) in the graph. Doremy defines $f(i,j)$ as the sum of lengths of shortest paths from every vertex to the cycle.\n\nFormally, let $\\mathrm{dis}_{i,j}(x,y)$ be the length of the shortest path between vertex $x$ and $y$ when the edge $(i,j)$ of weight $1$ is added, and $S_{i,j}$ be the set of vertices that are on the cycle when edge $(i,j)$ is added. Then,\n\n$$ f(i,j)=\\sum_{x=1}^{n}\\left(\\min_{y\\in S_{i,j}}\\mathrm{dis}_{i,j}(x,y)\\right). $$\n\nDoremy writes down all values of $f(i,j)$ such that $1 \\leq j \\leq i \\leq n$, then goes to sleep. However, after waking up, she finds that the tree has gone missing. Fortunately, the values of $f(i,j)$ are still in her notebook, and she knows which $i$ and $j$ they belong to. Given the values of $f(i,j)$, can you help her restore the tree?\n\nIt is guaranteed that at least one suitable tree exists.",
    "tutorial": "If path $(x,y) \\subset (X,Y)$, then $f(x,y) > f(X,Y)$. Then we build a graph based on $f(i,j)$, the weight of the edge between $i,j$ is $f(i,j)$. It can be shown that the MST of the graph have the same structure as the original tree. Then we need to compute the weight for each edge. The weight of the edge between $x$ and $y$ is $\\frac{f(x,x)-f(x,y)}{size_y}$, where $x$ is $y$'s parent on the tree, $size_y$ is the size of subtree $y$.",
    "code": "#include <bits/stdc++.h>\n\n#define debug(...) fprintf(stderr ,__VA_ARGS__)\n#define LL long long\n\nconst int MX = 3e3 + 5;\n\nbool vis[MX];\nLL w[MX][MX] ,dis[MX];\n\nstd::vector<int> e[MX];\n\nint size[MX];\nvoid dfs(int x ,int f){\n    size[x] = 1;\n    for(auto i : e[x]){\n        if(i == f) continue;\n        dfs(i ,x);\n        size[x] += size[i];\n    }\n    for(auto i : e[x]){\n        if(i == f) continue;\n        printf(\"%d %d %lld\\n\" ,x ,i ,(w[1][x] - w[1][i]) / size[i]);\n    }\n}\n\nint main(){\n    int n; scanf(\"%d\" ,&n);\n    memset(w ,-0x3f ,sizeof w);\n    for(int i = 1 ; i <= n ; ++i){\n        for(int j = 1 ; j <= i ; ++j){\n            scanf(\"%lld\" ,&w[i][j]);\n            w[j][i] = w[i][j];\n        }\n    }\n    memset(dis ,-0x3f ,sizeof dis);\n    dis[1] = 0;\n    for(int i = 1 ; i <= n ; ++i){\n        int x = 0;\n        for(int j = 1 ; j <= n ; ++j){\n            if(!vis[j] && (!x || dis[j] > dis[x])){\n                x = j;\n            }\n        }\n        //debug(\"x = %d \" ,x);\n        //ans += dis[x];\n        if(i != 1) for(int j = 1 ; j <= n ; ++j){\n            if(w[j][x] == dis[x] && vis[j]){\n                e[x].push_back(j);\n                e[j].push_back(x);\n                //debug(\"%d %d\\n\" ,x ,j);\n            }\n        }\n        vis[x] = true;\n        for(int j = 1 ; j <= n ; ++j){\n            dis[j] = std::max(dis[j] ,w[x][j]);\n        }\n    }\n    //return 0;\n    dfs(1 ,1);\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "sortings",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1764",
    "index": "G3",
    "title": "Doremy's Perfect DS Class (Hard Version)",
    "statement": "\\textbf{The only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most $\\mathbf{20}$ queries. You can make hacks only if all versions of the problem are solved.}\n\nThis is an interactive problem.\n\n\"Everybody! Doremy's Perfect Data Structure Class is about to start! Come and do your best if you want to have as much IQ as me!\" In today's Data Structure class, Doremy is teaching everyone a powerful data structure — Doremy tree! Now she gives you a quiz to prove that you are paying attention in class.\n\nGiven an array $a$ of length $m$, Doremy tree supports the query $Q(l,r,k)$, where $1 \\leq l \\leq r \\leq m$ and $1 \\leq k \\leq m$, which returns the number of distinct integers in the array $\\left[\\lfloor\\frac{a_l}{k} \\rfloor, \\lfloor\\frac{a_{l+1}}{k} \\rfloor, \\ldots, \\lfloor\\frac{a_r}{k} \\rfloor\\right]$.\n\nDoremy has a secret permutation $p$ of integers from $1$ to $n$. You can make queries, in one query, you give $3$ integers $l,r,k$ ($1 \\leq l \\leq r \\leq n$, $1 \\leq k \\leq n$) and receive the value of $Q(l,r,k)$ for the array $p$. Can you find the index $y$ ($1 \\leq y \\leq n$) such that $p_y=1$ in \\textbf{at most} $\\mathbf{20}$ queries?\n\nNote that the permutation $p$ is fixed before any queries are made.",
    "tutorial": "If we add an edge between numbers $a,b$ when $\\lfloor\\frac{a}{2}\\rfloor=\\lfloor\\frac{b}{2}\\rfloor$, then when $n$ is an odd number, $1$ is the only one which has no neighbor, so let's consider the odd case at first. Let the number of edges $(u,v)$ satisfying $u,v\\in [l,r]$ be $C(l,r)$, then $C(l,r)+Q(l,r,2)=r-l+1$. That is to say, we can get any $C(l,r)$ with a query. Try to use binary search to solve this problem. The key problem is for a certain $m$, determining whether $1$ is in $[1,m]$ or $[m+1,n]$. Let $2C(1,m)+x=m,2C(m+1,n)+y=n-m$. The edges between $[1,m]$ and $[m+1,n]$ must connect the remaining $x$ numbers in $[1,m]$ and the remaining $y$ numbers in $[m+1,n]$. There is exactly one number with no neighbor, so if $x=y+1$, $1$ is in $[1,m]$, otherwise $y=x+1$ and $1$ is in $[m+1,n]$. So we can do this case in $20$ queries. If $n$ is an even number, then $1,n$ will be the only two number which has no neighbor. With the similar analysis as above, we can know if $x>y$, $1,n$ are in $[1,m]$, if $y>x$, $1,n$ are in $[m+1,n]$, otherwise $1,n$ are in the different sides. When $l<r$, we can use $Q(l,r,n)$ to check whether $n$ is in $[l,r]$. Because $n\\ge 3$, we can use this method to determine $1$ is in which side. So we can do this case in $30$ queries. Finding that we only need one extra query $Q(l,r,n)$, we can do the even case in $21$ queries. When we decrease the range of $1$ to $[l,r]$, we have already got $C(1,l-1),C(1,r),C(l,n),C(r+1,n)$. When $l+1=r$, if $C(1,l-1)+1=C(1,r)$, we only need to know $C(1,l)$ to get the answer, if $C(l,n)=C(r+1,n)+1$, we only need to know $C(r,n)$ to get the answer, otherwise it means that $p_l=1,p_r=n$ or $p_l=n,p_r=1$, this case we also only need one more query. So we decrease the number of queries by $1$, solving this case in $20$ queries.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\nusing namespace std;\nint n;\nint query(int l,int r,int k){\n\tprintf(\"? %d %d %d\\n\",l,r,k);\n\tfflush(stdout);int re;scanf(\"%d\",&re);\n\treturn re;\n}\nvoid answer(int x){\n\tprintf(\"! %d\\n\",x);\n\tfflush(stdout);\n}\nint rt=-1;\nvoid divide(int l,int r,int l1,int l2,int r1,int r2){\n\tif(l==r){\n\t\tanswer(l);\n\t\treturn;\n\t}\n\tif(l+1==r){\n\t\tif(r1==r2+1){\n\t\t\tif(query(r,n,2)==r2+1)answer(r);\n\t\t\telse answer(l);\n\t\t}\n\t\telse if(l1==l2+1){\n\t\t\tif(query(1,l,2)==l2+1)answer(l);\n\t\t\telse answer(r);\n\t\t}\n\t\telse{\n\t\t\tif(l>1){\n\t\t\t\tif(query(1,l,n)==2)answer(r);\n\t\t\t\telse answer(l);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif(query(r,n,n)==2)answer(l);\n\t\t\t\telse answer(r);\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\tint mid=(l+r)>>1;\n\tint L=query(1,mid,2),R=query(mid+1,n,2);\n\tif(L*2-mid>R*2-(n-mid))divide(l,mid,L,l2,r1,R);\n\telse if(L*2-mid<R*2-(n-mid))divide(mid+1,r,l1,L,R,r2);\n\telse{\n\t\tif(~rt){\n\t\t\tif(rt)divide(l,mid,L,l2,r1,R);\n\t\t\telse divide(mid+1,r,l1,L,R,r2);\n\t\t}\n\t\tif(query(1,mid,n)==2)rt=0,divide(mid+1,r,l1,L,R,r2);\n\t\telse rt=1,divide(l,mid,L,l2,r1,R);\n\t}\n}\nint main(){\n\tscanf(\"%d\",&n);\n\tdivide(1,n,n/2+1,0,n/2+1,0);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1764",
    "index": "H",
    "title": "Doremy's Paint 2",
    "statement": "Doremy has $n$ buckets of paint which is represented by an array $a$ of length $n$. Bucket $i$ contains paint with color $a_i$. Initially, $a_i=i$.\n\nDoremy has $m$ segments $[l_i,r_i]$ ($1 \\le l_i \\le r_i \\le n$). Each segment describes an operation. Operation $i$ is performed as follows:\n\n- For each $j$ such that $l_i < j \\leq r_i$, set $a_j := a_{l_i}$.\n\nDoremy also selects an integer $k$. She wants to know for each integer $x$ from $0$ to $m-1$, the number of distinct colors in the array after performing operations $x \\bmod m +1, (x+1) \\bmod m + 1, \\ldots, (x+k-1) \\bmod m +1$. Can you help her calculate these values? Note that for each $x$ individually we start from the initial array and perform only the given $k$ operations in the given order.",
    "tutorial": "The main idea of the solution is that we can try to the answers for position $x,x+1,\\ldots,x+k$ all at once. We do this by representing the interval $[x+i,x+k+i)$ as $[x+i,x+k) \\cup [x+k,x+k+i)$ and perform sweep line on both halves of interval. Firstly, after applying some operations on the array $a$, we will have $a_i \\leq a_{i+1}$. That is, we can instead count the number of indices such that $a_i \\neq a_{i+1}$ for one less than the number of distinct elements. From here on, we will be counting the number of elements that $a_i \\neq a_{i+1}$ instead. Let us consider that the state of the array is $a$ after applying operations $[s+1,e]$. Consider the effect of applying operations $[s,e]$ instead. The change this operation will make is that we replace all $i$ such that $a_i \\in [l_{s},r_{s}]$ with $a_i=l_{s}$. We can think about it as only counting $a_i \\not\\cong a_{i+1}$ where we can view the above operation of replacing $a_i \\in [l_{s},r_{s}]$ with $l_{s}$ as instead merging $[l_{s},r_{s}]$ values as a single equivalence class which we label $l_s$. So for interval $[x+i,x+k+i) = [x+i,x+k) \\cup [x+k,x+k+i)$ we will get the equivalence class for values when considering ranges $[l_j,r_j$] with $j \\in [x+i,x+k-1]$. This is a natural line sweep when considering going from $[s,x+k-1]$ to $[s-1,x+k-1]$ that uses $O(n \\log n)$ by amortized analysis. We can find the state of the array when applying operations $[x+k,x+k],[x+k,x+k+1],\\ldots,[x+k,x+2k-1]$ in $O(n \\log n)$ time by amoritzed analysis by only storing contiguous values as a set. By storing the changes we made when we go from $[x+k,e]$ to $[x+k,e+1]$, we are able to \"undo\" the changes to go from $[x+k,e+1]$ to $[x+k,e]$. Now, we want to go from applying operations in $[x+i+1,x+k+i+1) = [x+i+1,x+k) \\cup [x+k,x+k+i+1)$ to $[x+i,x+k+i) = [x+i,x+k) \\cup [x+k,x+k+i)$, first we go from $[x+k,x+k+i+1)$ to $[x+k,x+k+i)$ by undoing the operation (and checking how many adjacent values are $\\not\\cong$), then we update our equivalence classes to go from $[x+i+1,x+k)$ to $[x+i,x+k)$. However, The problem is that this algorithm runs in $O(\\frac{m}{k} n \\log n)$ time. However, we note that we can discretize the range $[1,n]$ using the ranges $[l_j,r_j]$ with $j \\in [x,x+2k)$, so that our amortization works in $O(k \\log k)$, to obtain a complexity of $O(\\frac{m}{k} k \\log k) = O(m \\log k)$ (with a super huge constant). Note that since the element of the array $a$ are integers but are instead ranges now, there are some implementation details that are left as an exercise to the reader.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n#define ii pair<int,int>\n#define iii tuple<int,int,int>\n#define fi first\n#define se second\n#define endl '\\n'\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nint n,m,k;\nii arr[600005];\nint ans[400005];\n\nvector<int> uni;\nint nxt[200005];\nint state[200005];\nint state2[200005];\n\nbool has(int l,int r,set<int> &s){\n\tauto it=s.lb(l);\n\treturn *it<r;\n}\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tcin>>n>>m>>k;\n\trep(x,0,m) cin>>arr[x].fi>>arr[x].se;\n\trep(x,0,m) arr[x].fi--,arr[x].se--;\n\trep(x,0,2*m) arr[x+m]=arr[x];\n\t\n\tint l=0;\n\t\n\twhile (l<m){\n\t\tuni={0,n};\n\t\trep(x,l,l+2*k) uni.pub(arr[x].fi),uni.pub(arr[x].se+1);\n\t\tsort(all(uni)); uni.erase(unique(all(uni)),uni.end());\n\t\trep(x,0,sz(uni)-1) nxt[uni[x]]=uni[x+1];\n\t\t\n\t\tset<ii> s; for (auto it:uni) s.insert({it,it}); //position, color\n\t\trep(x,0,sz(uni)) state[uni[x]]=state2[uni[x]]=1;\n\t\t\n\t\tvector<iii> proc; //time, position, state\n\t\trep(x,l+k,l+2*k){\n\t\t\tif (s.count({arr[x].fi,arr[x].fi}) && state[arr[x].fi]){\n\t\t\t\tproc.pub({x,arr[x].fi,state[arr[x].fi]});\n\t\t\t\tstate[arr[x].fi]=0;\n\t\t\t}\n\t\t\t\n\t\t\twhile (true){\n\t\t\t\tauto it=s.ub(ii(arr[x].fi,1e9));\n\t\t\t\tif ((*it).fi>arr[x].se) break;\n\t\t\t\t\n\t\t\t\tif (arr[x].se+1<(*next(it)).fi) s.insert({arr[x].se+1,(*it).se});\n\t\t\t\telse{\n\t\t\t\t\tproc.pub({x,(*it).se,state[(*it).se]});\n\t\t\t\t\tstate[(*it).se]=0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ts.erase(it);\n\t\t\t}\n\t\t}\n\t\t\n\t\tint curr=0;\n\t\tset<int> pos={n};\n\t\tfor (auto [a,b]:s) if (b!=n){\n\t\t\tcurr++;\n\t\t\tif (state[b]) curr+=nxt[b]-b-1;\n\t\t\tpos.insert(b);\n\t\t}\n\t\t\n\t\ts.clear(); for (auto it:uni) s.insert({it,it}); //color, position\n\t\tset<ii> ranges; rep(x,0,sz(uni)-1) ranges.insert({uni[x],uni[x+1]});\n\t\t\n\t\trep(x,l+k,l){\n\t\t\t//merge things\n\t\t\tauto it=s.lb({arr[x].fi,-1});\n\t\t\tvector<int> v={(*it).se};\n\t\t\twhile ((*it).fi<=arr[x].se){\n\t\t\t\tit=next(it);\n\t\t\t\ts.erase(prev(it));\n\t\t\t\tv.pub((*it).se);\n\t\t\t}\n\t\t\t\n\t\t\tif (sz(v)>1){\n\t\t\t\trep(x,0,sz(v)-1){\n\t\t\t\t\tif (state[v[x]] && state2[v[x]]) curr-=v[x+1]-v[x]-1;\n\t\t\t\t\tstate2[v[x]]=0;\n\t\t\t\t\tcurr-=has(v[x],v[x+1],pos);\n\t\t\t\t\tranges.erase({v[x],v[x+1]});\n\t\t\t\t}\n\t\t\t\tcurr+=has(v[0],v[sz(v)-1],pos);\n\t\t\t\ts.insert({arr[x].fi,v[0]});\n\t\t\t\tranges.insert({v[0],v[sz(v)-1]});\n\t\t\t}\n\t\t\t\n\t\t\twhile (!proc.empty() && get<0>(proc.back())==x+k){\n\t\t\t\tint a,b,c; tie(a,b,c)=proc.back(); proc.pob();\n\t\t\t\tif (c){\n\t\t\t\t\tstate[b]=c;\n\t\t\t\t\tif (state[b] && state2[b]) curr+=nxt[b]-b-1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!pos.count(b)){\n\t\t\t\t\tauto it=prev(ranges.ub({b,1e9}));\n\t\t\t\t\tint l,r; tie(l,r)=*it;\n\t\t\t\t\tif (!has(l,r,pos)) curr++;\n\t\t\t\t\tpos.insert(b);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tans[x]=curr;\n\t\t}\n\t\t\n\t\t\n\t\tl+=k;\n\t}\n\t\n\trep(x,0,m) cout<<ans[x]<<\" \"; cout<<endl;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1765",
    "index": "A",
    "title": "Access Levels",
    "statement": "BerSoft is the biggest IT corporation in Berland, and Monocarp is the head of its security department. This time, he faced the most difficult task ever.\n\nBasically, there are $n$ developers working at BerSoft, numbered from $1$ to $n$. There are $m$ documents shared on the internal network, numbered from $1$ to $m$. There is a table of access requirements $a$ such that $a_{i,j}$ (the $j$-th element of the $i$-th row) is $1$ if the $i$-th developer should have access to the $j$-th document, and $0$ if they should have no access to it.\n\nIn order to restrict the access, Monocarp is going to perform the following actions:\n\n- choose the number of access groups $k \\ge 1$;\n- assign each document an access group (an integer from $1$ to $k$) and the required access level (an integer from $1$ to $10^9$);\n- assign each developer $k$ integer values (from $1$ to $10^9$) — their access levels for each of the access groups.\n\nThe developer $i$ has access to the document $j$ if their access level for the access group of the document is greater than or equal to the required access level of the document.\n\nWhat's the smallest number of access groups Monocarp can choose so that it's possible to assign access groups and access levels in order to satisfy the table of access requirements?",
    "tutorial": "Suppose two documents $i$ and $j$ belong to the same access group, and the access level for the document $i$ is greater than the access level for document $j$. Then, every developer which has the access to the document $i$, has the access to the document $j$ as well; so, for every $d \\in [1, n]$, the condition $a_{d,i} \\le a_{d,j}$ must hold. We can build a directed graph where the arc $i \\rightarrow j$ represents that this condition holds for the (ordered) pair of documents $(i, j)$. Every access group should be a path in this graph - so, our problem now requires us to cover a directed graph with the minimum number of vertex-disjoint paths. Let's assume that the graph is acyclic. Then every path is acyclic as well, so the number of vertices in a path is equal to the number of arcs in a path, plus one. Let $k$ be the number of paths, $v$ be the number of vertices, and $e$ be the total number of arcs used in the paths. It's easy to see that $k + e = v$; so, by maximizing the total number of arcs in the paths, we minimize the number of paths. So, we need to choose the maximum number of arcs so that each vertex belongs to only one path among those formed by these arcs. It is equivalent to the combination of the following two conditions: each vertex should have at most one incoming chosen arc; each vertex should have at most one outgoing chosen arc. Now our problem can be solved with network flows or bipartite matching. For example, one of the solutions is to create a bipartite graph where each vertex of the original graph is represented by two vertices, one for each part; and an arc $i \\rightarrow j$ from the original graph is converted to the edge connecting the vertex $i$ in the left part and the vertex $j$ in the right part. It's easy to see that every matching in this graph fulfills the aforementioned two conditions, thus giving us a correct decomposition of an acyclic directed graph into vertex-disjoint paths - so, in order to minimize the number of such paths, we need to find the maximum matching. All that's left is to actually find these paths and convert them into the access groups/levels for the documents, and set access levels for the developers, which is pretty easy and straightforward to implement. But wait, what if the graph is not acyclic? Fortunately, a cycle can exist only between two documents with identical access requirements. We can deal with these in one of two ways: compress all identical documents into one vertex; or use the document index as the tiebreak if two documents are completely identical otherwise. Even the most basic implementation of bipartite matching with Kuhn's algorithm will yield a solution in $O(m^3 + m^2n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint n, m, m2;\nvector<vector<char>> g;\n\nint T;\nvector<int> mt;\nvector<int> used;\n\nbool try_kuhn(int v){\n    if (used[v] == T)\n        return false;\n    used[v] = T;\n    forn(u, m2) if (g[v][u] && (mt[u] == -1 || try_kuhn(mt[u]))){\n        mt[u] = v;\n        return true;\n    }\n    return false;\n}\n\nint main() {\n    cin >> n >> m;\n    vector<string> b(m, string(n, '0'));\n    forn(i, n){\n        string t;\n        cin >> t;\n        forn(j, m) b[j][i] = t[j];\n    }\n    \n    vector<string> nw = b;\n    sort(nw.begin(), nw.end());\n    nw.resize(unique(nw.begin(), nw.end()) - nw.begin());\n    m2 = nw.size();\n    g.assign(m2, vector<char>(m2, 0));\n    forn(i, m2) forn(j, m2) if (i != j){\n        bool in = true;\n        forn(k, n) in &= nw[i][k] >= nw[j][k];\n        if (in) g[i][j] = 1;\n    }\n    \n    mt.assign(m2, -1);\n    used.assign(m2, -1);\n    T = 0;\n    int k = m2;\n    forn(i, m2) if (try_kuhn(i)){\n        ++T;\n        --k;\n    }\n    \n    vector<int> nxt(m2, -1);\n    vector<char> st(m2, true);\n    forn(i, m2) if (mt[i] != -1){\n        nxt[mt[i]] = i;\n        st[i] = false;\n    }\n    \n    vector<int> gr(m2), req(m2);\n    int t = 0;\n    forn(i, m2) if (st[i]){\n        int v = i;\n        int pos = 2;\n        while (v != -1){\n            gr[v] = t;\n            req[v] = pos;\n            ++pos;\n            v = nxt[v];\n        }\n        ++t;\n    }\n    assert(t == k);\n    \n    vector<int> num(m);\n    forn(i, m) num[i] = lower_bound(nw.begin(), nw.end(), b[i]) - nw.begin();\n    \n    printf(\"%d\\n\", k);\n    forn(i, m) printf(\"%d \", gr[num[i]] + 1);\n    puts(\"\");\n    forn(i, m) printf(\"%d \", req[num[i]]);\n    puts(\"\");\n    forn(i, n){\n        vector<int> l(k, 1);\n        forn(j, m2) if (nw[j][i] == '1')\n            l[gr[j]] = max(l[gr[j]], req[j]);\n        forn(j, k)\n            printf(\"%d \", l[j]);\n        puts(\"\");\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dsu",
      "flows",
      "graph matchings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1765",
    "index": "B",
    "title": "Broken Keyboard",
    "statement": "Recently, Mishka started noticing that his keyboard malfunctions — maybe it's because he was playing rhythm games too much. Empirically, Mishka has found out that every other time he presses a key, it is registered as if the key was pressed twice. For example, if Mishka types text, the first time he presses a key, exactly one letter is printed; the second time he presses a key, two same letters are printed; the third time he presses a key, one letter is printed; the fourth time he presses a key, two same letters are printed, and so on. Note that the number of times a key was pressed is counted for the whole keyboard, not for each key separately. For example, if Mishka tries to type the word osu, it will be printed on the screen as ossu.\n\nYou are given a word consisting of $n$ lowercase Latin letters. You have to determine if it can be printed on Mishka's keyboard or not. You may assume that Mishka cannot delete letters from the word, and every time he presses a key, the new letter (or letters) is appended to the end of the word.",
    "tutorial": "There are many ways to solve this problem. Basically, we need to check two conditions. The first one is the condition on the number of characters: $n \\bmod 3 \\ne 2$, since after the first key press, we get the remainder $1$ modulo $3$, after the second key press, we get the remainder $0$ modulo $3$, then $1$ again, then $0$ - and so on, and we cannot get the remainder $2$. Then we need to check that, in each pair of characters which appeared from the same key press, these characters are the same - that is, $s_2 = s_3$, $s_5 = s_6$, $s_8 = s_9$, and so on.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    s = input()\n    print('YES' if n % 3 != 2 and not False in [s[i * 3 + 1] == s[i * 3 + 2] for i in range(n // 3)] else 'NO')",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1765",
    "index": "C",
    "title": "Card Guessing",
    "statement": "Consider a deck of cards. Each card has one of $4$ suits, and there are exactly $n$ cards for each suit — so, the total number of cards in the deck is $4n$. The deck is shuffled randomly so that each of $(4n)!$ possible orders of cards in the deck has the same probability of being the result of shuffling. Let $c_i$ be the $i$-th card of the deck (from top to bottom).\n\nMonocarp starts drawing the cards from the deck one by one. Before drawing a card, he tries to guess its suit. Monocarp remembers the suits of the $k$ last cards, and his guess is the suit that appeared the least often among the last $k$ cards he has drawn. So, while drawing the $i$-th card, Monocarp guesses that its suit is the suit that appears the minimum number of times among the cards $c_{i-k}, c_{i-k+1}, \\dots, c_{i-1}$ (if $i \\le k$, Monocarp considers all previously drawn cards, that is, the cards $c_1, c_2, \\dots, c_{i-1}$). If there are multiple suits that appeared the minimum number of times among the previous cards Monocarp remembers, he chooses a random suit out of those for his guess (all suits that appeared the minimum number of times have the same probability of being chosen).\n\nAfter making a guess, Monocarp draws a card and compares its suit to his guess. If they match, then his guess was correct; otherwise it was incorrect.\n\nYour task is to calculate the expected number of correct guesses Monocarp makes after drawing all $4n$ cards from the deck.",
    "tutorial": "Obviously, linearity of expectation, we are calculating the sum of probability to guess correctly for each position from $1$ to $4n$. Let's start with a minor observation which can help us in calculations. The probability for all positions from $k+1$ onwards is the same. The probability for each position $i$ depends on the number of ways (and some properties of them) to pick $\\min(i - 1, k)$ cards prior to it. Thus, when this $\\min$ evaluates to $k$, it's all the same. We'll calculate the first $k+1$ positions and then multiply the last one by $4n - k$. How about we start with a naive solution? Let's pretend all cards are distinguishable from each other (which, in my opinion, is a rare case for combinatorics solutions). Then we can pick $a$ cards of the first suit, $b$ cards of the second suit, $c$ cards of the third suit and $d$ cards of the fourth suit to go prior to the position $a + b + c + d$. Check if the sum doesn't exceed $k$. The number of ways to choose these cards is $C(n, a) \\cdot C(n, b) \\cdot C(n, c) \\cdot C(n, d) \\cdot (a + b + c + d)!$. We should also permute the remaining cars - multiply by $(4n - (a + b + c + d))!$. And divide everything by $(4n)!$ to get the probability of getting exactly that permutation. The probability to guess the suit correctly is $\\frac{\\min(a, b, c, d)}{4n - (a + b + c + d)}$. Thus, we should add the product of these two probabilities to the answer. The annoying aspect of this solution is actually the $\\min$ function. We'd prefer to always know that $a$ is the smallest one. Let's try to rewrite this naive in such a way that $a \\le b \\le c \\le d$. Frankly, almost nothing changes. To account for the fact that we removed the order of $a, b, c$ and $d$, we want to multiply the number of ways by the number of ways to permute these amounts. That number is a multinomial that depends on the sizes of equivalence classes of the amounts. As in, if the amounts are $1, 1, 2, 3$, then it's $\\frac{4!}{2! \\cdot 1! \\cdot 1!}$. If it's $1, 1, 1, 3$, then it's $\\frac{4!}{3! \\cdot 1!}$. All the rest stays the same. Then the probability to guess correctly is just $\\frac{a}{4n - (a + b + c + d)}$. Great, now we can make a dp out of this naive solution. Basically, the answer depends on three things. The smallest amount, the total amount, and the counts of each amount. The first one can be accounted for during the initialization phase. The second one can be accounted for at the very end. And the third one can be accounted for during the transition :) We want to construct non-decreasing sequences of length $4$ with a known sum and with a known first element. Let that $dp$ be $dp[i][j][k]$ - some sum of probabilities over all sequences such that the current amount is $i$, the sum of the sequence is $j$, and we placed $k$ elements in the sequence. For the transition, we want to either increase the current value $i$ by $1$, or to place from $1$ to $4 - k$ copies of the current value. If we place it, we immediately apply the cnk and divide by the multinomial coefficient - the factorial of the number of copies. We increase $i$ as well, so that we can't place more elements equal to $i$. For the initialization, we iterate over the smallest element and the count of it. This way, we can put the numerator of the probability to guess the suit along with the other things. When we collect the answers, we iterate over the sum and account for the rest of the terms in the product: factorial of the sum, permuting the remaining cards, the denominator of the guess probability and so on. The formulas might get tricky, but they all make enough sense, and hopefully nothing incorrect works on the examples, which should help you to debug. Overall complexity: $O(n^2)$. There are cubic solutions, that are also smart enough in our opinion, which is why the constraints are set like that.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define fore(i, l, r) for (int i = int(l); i < int(r); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int a, int b){\n    a += b;\n    if (a >= MOD)\n        a -= MOD;\n    return a;\n}\n\nint mul(int a, int b){\n    return a * 1ll * b % MOD;\n}\n\nint binpow(int a, int b){\n    int res = 1;\n    while (b){\n        if (b & 1)\n            res = mul(res, a);\n        a = mul(a, a);\n        b >>= 1;\n    }\n    return res;\n}\n\nint main() {\n    int n, k;\n    scanf(\"%d%d\", &n, &k);\n    \n    vector<int> fact(4 * n + 1);\n    fact[0] = 1;\n    fore(i, 1, fact.size()) fact[i] = mul(fact[i - 1], i);\n    vector<int> rfact(4 * n + 1);\n    rfact.back() = binpow(fact.back(), MOD - 2);\n    for (int i = int(fact.size()) - 2; i >= 0; --i)\n        rfact[i] = mul(rfact[i + 1], i + 1);\n    \n    auto cnk = [&](int n, int k){\n        return mul(fact[n], mul(rfact[k], rfact[n - k]));\n    };\n    \n    vector<vector<int>> sv(n + 1, vector<int>(5));\n    forn(i, n + 1) forn(t, 5) sv[i][t] = mul(binpow(cnk(n, i), t), rfact[t]);\n    \n    vector<vector<vector<int>>> dp(2, vector<vector<int>>(4 * n + 1, vector<int>(5)));\n    forn(ii, n + 1){\n        int i = ii & 1;\n        int ni = i ^ 1;\n        dp[ni] = vector<vector<int>>(4 * n + 1, vector<int>(5));\n        for (int t = 1; t <= 4; ++t)\n            dp[ni][ii * t][t] = mul(n - ii, sv[ii][t]);\n        forn(j, k + 1) for (int p = 1; p <= 4; ++p) if (dp[i][j][p]){\n            dp[ni][j][p] = add(dp[ni][j][p], dp[i][j][p]);\n            for (int t = 1; p + t <= 4; ++t)\n                dp[ni][j + ii * t][p + t] = add(dp[ni][j + ii * t][p + t], mul(dp[i][j][p], sv[ii][t]));\n        }\n    }\n    \n    int ans = 0;\n    forn(sum, k + 1){\n        ans = add(ans, mul(mul(mul(\n            sum < k ? 1 : 4 * n - k, \n            dp[(n & 1) ^ 1][sum][4]), \n            mul(binpow(4 * n - sum, MOD - 2), mul(rfact[4 * n], fact[4 * n - sum]))), \n            mul(fact[4], fact[sum]))\n        );\n    }\n    \n    printf(\"%d\\n\", ans);\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1765",
    "index": "D",
    "title": "Watch the Videos",
    "statement": "Monocarp wants to watch $n$ videos. Each video is only one minute long, but its size may be arbitrary. The $i$-th video has the size $a_i$ megabytes. All videos are published on the Internet. A video should be downloaded before it can be watched. Monocarp has poor Internet connection — it takes exactly $1$ minute to download $1$ megabyte of data, so it will require $a_i$ minutes to download the $i$-th video.\n\nMonocarp's computer has a hard disk of $m$ megabytes. The disk is used to store the downloaded videos. Once Monocarp starts the download of a video of size $s$, the $s$ megabytes are immediately reserved on a hard disk. If there are less than $s$ megabytes left, the download cannot be started until the required space is freed. Each single video can be stored on the hard disk, since $a_i \\le m$ for all $i$. Once the download is started, it cannot be interrupted. It is not allowed to run two or more downloads in parallel.\n\nOnce a video is fully downloaded to the hard disk, Monocarp can watch it. Watching each video takes exactly $1$ minute and does not occupy the Internet connection, so Monocarp can start downloading another video while watching the current one.\n\nWhen Monocarp finishes watching a video, he doesn't need it on the hard disk anymore, so he can delete the video, instantly freeing the space it occupied on a hard disk. Deleting a video takes negligible time.\n\nMonocarp wants to watch all $n$ videos as quickly as possible. The order of watching does not matter, since Monocarp needs to watch all of them anyway. Please calculate the minimum possible time required for that.",
    "tutorial": "In this solution, we assume that the sequence $a_1, a_2, \\dots, a_n$ is sorted (if it is not - just sort it before running the solution). Suppose we download and watch the videos in some order. The answer to the problem is $n + \\sum a_i$, reduced by $1$ for every pair of adjacent videos that can fit onto the hard disk together (i. e. their total size is not greater than $m$), because for every such pair, we can start downloading the second one while watching the first one. So, we need to order the videos in such a way that the number of such pairs is the maximum possible. Suppose we want to order them so that every pair of adjacent videos is \"good\". We need to pick the ordering that minimizes the maximum sum of adjacent elements. There are multiple ways to construct this ordering; one of them is $[a_n, a_1, a_{n-1}, a_2, a_{n - 2}, a_3, \\dots]$, and the maximum sum of adjacent elements will be $\\max_{i=1, 2i \\ne n}^{n} a_i + a_{n + 1 - i}$. Proof that this ordering is optimal starts here Suppose $j$ is such value of $i$ that $a_i + a_{n + 1 - i}$ is the maximum, and $j < n + 1 - j$. Let's prove that we cannot make the maximum sum of adjacent elements less than $a_j + a_{n + 1 - j}$. There are at most $j - 1$ values in $a$ which are less than $a_j$ (let's call them Group A), and at least $j$ values that are not less than $a_j$ (let's call them Group B). If we want each sum of adjacent elements to be less than $a_j + a_{n + 1 - j}$, we want the elements of Group B to be adjacent only to the elements of the Group A. The elements of Group B have at least $2j - 2$ links to the neighbors (since at most two of them will have only one neighbor), the elements of Group A have at most $2(j - 1)$ links to the neighbors, but we cannot link Group A with Group B without any outside links since it will disconnect them from all other elements of the array. So, we cannot get the maximum sum less than $a_j + a_{n + 1 - j}$. Proof that this ordering is optimal ends here Okay, now what if we cannot make all pairs of adjacent elements \"good\"? We can run binary search on the number of pairs that should be \"bad\". Let this number be $k$, then if we need to make at most $k$ pairs \"bad\", we can check that it's possible by removing $k$ maximum elements from $a$ and checking that now we can make the array \"good\". So, in total, our solution will work in $O(n \\log n)$.",
    "code": "#include <iostream>\n#include <algorithm>\nusing namespace std;\n\n#define N 200000\n\nint a[N], n, s;\n\nbool can(int x) {\n    int l = x - 1, r = n - 1;\n    while (l < r) {\n        if (a[r] > s - a[l]) return false;\n        ++l;\n        if (l < r) {\n            if (a[l] > s - a[r]) return false;\n            --r;\n        }\n    }\n    return true;\n}\n\n\nint main() {\n    long long sum = 0;\n    scanf(\"%d %d\\n\", &n, &s);\n    for(int i = 0; i < n; ++i) {\n        scanf(\"%d\", &a[i]);\n        sum += a[i];\n    }\n\n    sort(a, a + n, greater<int>());\n\n    int l = 1, r = n;\n    while (l < r) {\n        int m = (l + r) >> 1;\n        if (can(m)) r = m;\n        else l = m + 1;\n    }\n\n    long long ans = sum + r;\n    cout << ans << endl;\n\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1765",
    "index": "E",
    "title": "Exchange",
    "statement": "Monocarp is playing a MMORPG. There are two commonly used types of currency in this MMORPG — gold coins and silver coins. Monocarp wants to buy a new weapon for his character, and that weapon costs $n$ silver coins. Unfortunately, right now, Monocarp has no coins at all.\n\nMonocarp can earn gold coins by completing quests in the game. Each quest yields exactly one gold coin. Monocarp can also exchange coins via the in-game trading system. Monocarp has spent days analyzing the in-game economy; he came to the following conclusion: it is possible to sell one gold coin for $a$ silver coins (i. e. Monocarp can lose one gold coin to gain $a$ silver coins), or buy one gold coin for $b$ silver coins (i. e. Monocarp can lose $b$ silver coins to gain one gold coin).\n\nNow Monocarp wants to calculate the minimum number of quests that he has to complete in order to have at least $n$ silver coins after some abuse of the in-game economy. Note that Monocarp can perform exchanges of both types (selling and buying gold coins for silver coins) any number of times.",
    "tutorial": "If $a > b$, then Monocarp can go infinite by obtaining just one gold coin: exchanging it for silver coins and then buying it back will earn him $a-b$ silver coins out of nowhere. So, the answer is $1$ no matter what $n$ is. If $a \\le b$, then it's suboptimal to exchange gold coins for silver coins and then buy the gold coins back. Monocarp should earn the minimum possible number of gold coins so that they all can be exchanged into at least $n$ silver coins; so, the number of gold coins he needs is $\\lceil \\frac{n}{a} \\rceil$. One small note: you shouldn't use the functions like ceil to compute a fraction rounded up, since you may get some computation errors related to using floating-point numbers (and possibly getting precision loss). Instead, you should calculate $\\lceil \\frac{n}{a} \\rceil$ as $\\lfloor \\frac{n + a - 1}{a} \\lfloor$ (this works for non-negative $n$ and positive $a$), and every programming language provides an integer division operator which discards the fractional part and thus doesn't use floating-point computations at all.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nvoid solve() \n{\n    int n, a, b;\n    cin >> n >> a >> b;\n    int x = (n + a - 1) / a;\n    if(a > b) x = 1;\n    cout << x << endl;\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n        solve();\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1765",
    "index": "F",
    "title": "Chemistry Lab",
    "statement": "Monocarp is planning on opening a chemistry lab. During the first month, he's going to distribute solutions of a certain acid.\n\nFirst, he will sign some contracts with a local chemistry factory. Each contract provides Monocarp with an unlimited supply of some solution of the same acid. The factory provides $n$ contract options, numbered from $1$ to $n$. The $i$-th solution has a concentration of $x_i\\%$, the contract costs $w_i$ burles, and Monocarp will be able to sell it for $c_i$ burles per liter.\n\nMonocarp is expecting $k$ customers during the first month. Each customer will buy a liter of a $y\\%$-solution, where $y$ is a \\textbf{real} number chosen uniformly at random from $0$ to $100$ independently for each customer. More formally, the probability of number $y$ being less than or equal to some $t$ is $P(y \\le t) = \\frac{t}{100}$.\n\nMonocarp can mix the solution that he signed the contracts with the factory for, at any ratio. More formally, if he has contracts for $m$ solutions with concentrations $x_1, x_2, \\dots, x_m$, then, for these solutions, he picks their volumes $a_1, a_2, \\dots, a_m$ so that $\\sum \\limits_{i=1}^{m} a_i = 1$ (exactly $1$ since each customer wants exactly one liter of a certain solution).\n\nThe concentration of the resulting solution is $\\sum \\limits_{i=1}^{m} x_i \\cdot a_i$. The price of the resulting solution is $\\sum \\limits_{i=1}^{m} c_i \\cdot a_i$.\n\nIf Monocarp can obtain a solution of concentration $y\\%$, then he will do it while maximizing its price (the cost for the customer). Otherwise, the customer leaves without buying anything, and the price is considered equal to $0$.\n\nMonocarp wants to sign some contracts with a factory (possibly, none or all of them) so that the expected profit is maximized — the expected total price of the sold solutions for all $k$ customers minus the total cost of signing the contracts from the factory.\n\nPrint the maximum expected profit Monocarp can achieve.",
    "tutorial": "Let's start without picking the contracts. Buy them all and at least learn to calculate the answer. Obviously, $k$ doesn't really matter for the answer. Linearity of expectation, it will be just something multiplied by $k$. Imagine there's just one contract. Since we can't really mix it with anything, and the probability that the customer picks exactly that concentration is $0$, the answer is $0$. What about two contracts? If you draw them as points $(x_i, c_i)$ on the grid, then all solutions, that can be obtained from a mix of them, are a segment. Basically, the formula is exactly the parametric equation for the segment, and that's how you could come to this conclusion. The expected cost is some integral, which is basically an area below the segment. Three contracts? As a reasonable conclusion, now it's a triangle on these points. To show that, let's fix one of these points $A$, opposite to some base of the triangle $BC$. Pick a percentage of the solution $A$, then draw a segment from $A$ to that percentage of $BC$. If you fix the percentages of $B$ and $C$ (the point on the segment $BC$), then you can basically continuously gravitate this point towards $A$ along the drawn segment by increasing the concentration of $A$ and decreasing the concentrations of $B$ and $C$, while keeping their proportion to each other the same. The union of all options covers the entire triangle and can never go outside it. Ok, let's make an educated guess about more contracts and try to show that. All solutions, that can be obtained with a mix of several solutions, are insides of a convex hull of the set of points. Let the set of points be convex already. If it isn't, we can say that the answer is the union of all convex subsets of it, which is equal to the convex hull. To prove it for the convex set, we can choose any three consecutive points on it and contract them into a segment, with the proof for the triangle. Continue until we reach two points. All solutions are a convex hull, but we only care about the ones with the maximum cost. That would be the set of the highest intersection points of the convex hull and the vertical lines for all concentrations. Which is known as an upper envelope of the convex hull. The expected cost is the area below that upper envelope. So we learned to calculate the answer for a fixed set of solutions. Let's learn how to pick them. We want to directly construct that upper envelope. Let me first tell you a direct but a slow solution. Do dynamic programming. Sort the solutions first in the increasing order of their concentration, second in the increasing order of their cost per litre. Now do $dp[i][j]$ - the maximum answer if the last point in the upper envelope is $j$ and the second last is $i$. To transition, iterate over the next point $k$ in that upper envelope and check if the triple $(i, j, k)$ is clockwise. To update the answer, add the newly added area below the segment $(j, k)$, which is a trapezoid, multiplied by $k$, and subtract the cost of the contract $k$. That would be $O(n^3)$. Now for the funny transition. Basically, we can just not care that the points we pick give us an upper envelope. If we picked a set of points, which is not convex, then we can safely remove some points (pay less money for the contracts) and our calculated area can never decrease from that (since we still are picking points in the increasing order of $x$ and $y$). Thus, we can remove the second to last point in the dp and only store the last one. That is enough to recalculate the area. Overall complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\ntypedef long long li;\n\nconst li INF64 = 1e18;\n\nstruct base{\n    int x, w, c;\n};\n\nli area(const base &a, const base &b){\n    return (a.c + b.c) * li(abs(a.x - b.x));\n}\n\nint main() {\n    int n, k;\n    scanf(\"%d%d\", &n, &k);\n    vector<base> a(n);\n    forn(i, n) scanf(\"%d%d%d\", &a[i].x, &a[i].w, &a[i].c);\n    sort(a.begin(), a.end(), [](const base &a, const base &b){ return a.x > b.x; });\n    vector<li> dp(n, -INF64);\n    li ans = 0;\n    forn(i, n){\n        dp[i] = max(dp[i], -a[i].w * 200ll);\n        for (int j = i + 1; j < n; ++j)\n            dp[j] = max(dp[j], dp[i] + area(a[i], a[j]) * k - a[j].w * 200ll);\n        ans = max(ans, dp[i]);\n    }\n    printf(\"%.15Lf\\n\", ans / (long double)(200));\n    return 0;\n}",
    "tags": [
      "dp",
      "geometry",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1765",
    "index": "G",
    "title": "Guess the String",
    "statement": "\\textbf{This is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java or Kotlin — System.out.flush(), and in Python — sys.stdout.flush().}\n\nThe jury has a string $s$ consisting of characters 0 and/or 1. The first character of this string is 0. The length of this string is $n$. You have to guess this string. Let's denote $s[l..r]$ as the substring of $s$ from $l$ to $r$ (i. e. $s[l..r]$ is the string $s_ls_{l+1} \\dots s_r$).\n\nLet the prefix function of the string $s$ be an array $[p_1, p_2, \\dots, p_n]$, where $p_i$ is the greatest integer $j \\in [0, i-1]$ such that $s[1..j] = s[i-j+1..i]$. Also, let the antiprefix function of the string $s$ be an array $[q_1, q_2, \\dots, q_n]$, where $q_i$ is the greatest integer $j \\in [0, i-1]$ such that $s[1..j]$ differs from $s[i-j+1..i]$ in \\textbf{every} position.\n\nFor example, for the string 011001, its prefix function is $[0, 0, 0, 1, 1, 2]$, and its antiprefix function is $[0, 1, 1, 2, 3, 4]$.\n\nYou can ask queries of two types to guess the string $s$:\n\n- $1$ $i$ — \"what is the value of $p_i$?\";\n- $2$ $i$ — \"what is the value of $q_i$?\".\n\nYou have to guess the string by asking no more than $789$ queries. Note that giving the answer does not count as a query.\n\n\\textbf{In every test and in every test case, the string $s$ is fixed beforehand}.",
    "tutorial": "We will design a randomized solution which spends $1.5$ queries on average to guess $2$ characters. First of all, let's ask $p_2$ to learn which character is $s_2$. Depending on whether it is 0 or 1, the details of the solution might change, but the general idea stays the same. We will assume that it is 0. We will divide the string into blocks of $2$ characters and guess it block by block. Suppose a block contains the characters $s_{i - 1}$ and $s_i$. If we want to guess it using less than $2$ queries, we should start with querying the $i$-th position (if we start by querying the position $i-1$, we won't know anything about the $i$-th position). Suppose our query has returned a number greater than $1$. Then we successfully obtained the full information about the block in one query. So, let's analyze the bad case: what if we got $0$ or $1$ as the result of the query? If we used prefix function, the result equal to $1$ shows us that the block is 10 - 00 will give the result of at least $2$, and neither 01 nor 11 can give $1$ as the result. But if the result is $0$, then it could mean either 01 or 11, and we need a second query to find out the exact combination. If we used antiprefix function, every character gets inverted; so, the result equal to $1$ tells us that the block is 01, and the result equal to $0$ tells us that the block is either 10 or 00. So, one type of query cannot distinguish 01 from 11, and the other type cannot distinguish 10 from 00. If we pick the type of query randomly, with probability of $\\frac{1}{2}$ we will obtain the information about the whole block in just one query; so, this method will spend $1.5$ queries per block of $2$ characters on average.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nmt19937 rnd(42);\nuniform_int_distribution<int> d(1, 2);\n\nint ask(int t, int i)\n{\n    cout << t << \" \" << i + 1 << endl;\n    int x;\n    cin >> x;\n    return x;\n}\n\nvoid giveAnswer(const string& s)\n{\n    cout << 0 << \" \" << s << endl;\n    int x;\n    cin >> x;\n    assert(x == 1);\n}\n\nvoid guessOne(string& s, int i)\n{\n    int res = ask(1, i);\n    if(res == 0)\n        s[i] = '1';\n    else\n        s[i] = s[res - 1];\n}\n\nchar inv(char c)\n{\n    if(c == '0') return '1';\n    return '0';\n}\n\nvoid guessTwo(string& s, int i)\n{\n    if(s[1] == '0')\n    {\n        if(d(rnd) == 1)\n        {\n            int res = ask(1, i);\n            if(res >= 2)\n            {\n                s[i] = s[res - 1];\n                s[i - 1] = s[res - 2];\n            }\n            else if(res == 1)\n            {\n                s[i] = '0';\n                s[i - 1] = '1';\n            }\n            else\n            {\n                s[i] = '1';\n                guessOne(s, i - 1);\n            }\n        }\n        else\n        {\n            int res = ask(2, i);\n            if(res >= 2)\n            {\n                s[i] = inv(s[res - 1]);\n                s[i - 1] = inv(s[res - 2]);\n            }\n            else if(res == 1)\n            {\n                s[i] = '1';\n                s[i - 1] = '0';\n            }\n            else\n            {\n                s[i] = '0';\n                guessOne(s, i - 1);\n            }\n        }\n    }\n    else\n    {\n        if(d(rnd) == 1)\n        {\n            int res = ask(1, i);\n            if(res >= 2)\n            {\n                s[i] = s[res - 1];\n                s[i - 1] = s[res - 2];\n            }\n            else if(res == 1)\n            {\n                s[i] = '0';\n                guessOne(s, i - 1);\n            }\n            else\n            {\n                s[i] = '1';\n                s[i - 1] = '1';\n            }\n        }\n        else\n        {\n            int res = ask(2, i);\n            if(res >= 2)\n            {\n                s[i] = inv(s[res - 1]);\n                s[i - 1] = inv(s[res - 2]);\n            }\n            else if(res == 1)\n            {\n                s[i] = '1';\n                guessOne(s, i - 1);\n            }\n            else\n            {\n                s[i] = '0';\n                s[i - 1] = '0';\n            }\n        }\n    }\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int n;\n        cin >> n;\n        string s(n, '0');\n        for(int j = 1; j < n; j += 2)\n        {\n            if(j == 1) guessOne(s, j);\n            else guessTwo(s, j);\n        }\n        if(n % 2 == 1) guessOne(s, n - 1);\n        giveAnswer(s);\n    }\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1765",
    "index": "H",
    "title": "Hospital Queue",
    "statement": "There are $n$ people (numbered from $1$ to $n$) signed up for a doctor's appointment. The doctor has to choose in which order he will appoint these people. The $i$-th patient should be appointed among the first $p_i$ people. There are also $m$ restrictions of the following format: the $i$-th restriction is denoted by two integers $(a_i, b_i)$ and means that the patient with the index $a_i$ should be appointed earlier than the patient with the index $b_i$.\n\nFor example, if $n = 4$, $p = [2, 3, 2, 4]$, $m = 1$, $a = [3]$ and $b = [1]$, then the only order of appointment of patients that does not violate the restrictions is $[3, 1, 2, 4]$. For $n =3$, $p = [3, 3, 3]$, $m = 0$, $a = []$ and $b = []$, any order of appointment is valid.\n\nFor each patient, calculate the minimum position in the order that they can have among all possible orderings that don't violate the restrictions.",
    "tutorial": "Let's solve the problem separately for each patient. Let's assume that we are solving a problem for a patient with the number $s$. Let's iterate through the positions in the queue from the end, and the current position is $i$. Why do we try to construct the queue from the end, and not from its beginning? This allows us to handle the constraint on $p_i$ for each patient easier. If we try to form the queue starting from the beginning, we have to be very careful with these constraints on $p_i$, since placing a patient on some position might make it impossible to continue the order, but it's very difficult to understand when it concerns us. On the other hand, if we go from the end to the beginning, each patient that we can place on the current position can be placed on any of the positions we consider later as well, so our actions won't \"break\" the correct order; any order we build while maintaining all of the constraints for its suffix is correct. That's why this problem is easier to solve if we construct the queue backwards. Now, all we need to do is try not to place patient $s$ as long as possible. So, we can maintain all patients we can place (such a patient $x$ that $x$ is not placed yet, $p_x \\ge i$ and there is no such patient $y$, that $x$ should be in the queue before $y$, but $y$ is not placed yet) now in any data structure, and when choosing who to place on each position, we delay placing patient $s$ as long as possible.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int n, m;\n  cin >> n >> m;\n  vector<int> a(n);\n  for (auto &x : a) cin >> x;\n  vector<vector<int>> g(n);\n  for (int i = 0; i < m; ++i) {\n    int x, y;\n    cin >> x >> y;\n    g[y - 1].push_back(x - 1);\n  }\n    \n  vector<int> ans(n, -1);\n  for (int s = 0; s < n; ++s) {\n    vector<int> deg(n);\n    for (int i = 0; i < n; ++i) \n      for (int j : g[i]) ++deg[j];\n    priority_queue<pair<int, int>> q;\n    for (int v = 0; v < n; ++v)\n      if (deg[v] == 0 && v != s)\n        q.push({a[v], v});\n    for (int i = n; i > 0; --i) {\n      if (q.empty() || q.top().first < i) {\n        if (deg[s] == 0 && i <= a[s])\n          ans[s] = i;\n        break;\n      }\n      int v = q.top().second;\n      q.pop();\n      for (int u : g[v]) {\n        --deg[u];\n        if (deg[u] == 0 && u != s)\n          q.push({a[u], u});\n      }\n    }\n  }\n  \n  for (int &x : ans) cout << x << ' ';\n}\n ",
    "tags": [
      "binary search",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1765",
    "index": "I",
    "title": "Infinite Chess",
    "statement": "The black king lives on a chess board with an infinite number of columns (files) and $8$ rows (ranks). The columns are numbered with all integer numbers (including negative). The rows are numbered from $1$ to $8$.\n\nInitially, the black king is located on the starting square $(x_s, y_s)$, and he needs to reach some target square $(x_t, y_t)$. Unfortunately, there are also white pieces on the board, and they threaten the black king. After negotiations, the white pieces agreed to let the black king pass to the target square on the following conditions:\n\n- each turn, the black king makes a move according to the movement rules;\n- the black king cannot move to a square occupied by a white piece;\n- the black king cannot move to a square which is under attack by any white piece. A square is under attack if a white piece can reach it in one move according to the movement rules;\n- the white pieces never move.\n\nHelp the black king find the minimum number of moves needed to reach the target square while not violating the conditions. The black king cannot leave the board at any time.\n\nThe black king moves according to the movement rules below. Even though the white pieces never move, squares which they can reach in one move are considered to be under attack, so the black king cannot move into those squares.\n\nBelow are the movement rules. Note that the pieces (except for the knight) cannot jump over other pieces.\n\n- a king moves exactly one square horizontally, vertically, or diagonally.\n- a rook moves any number of vacant squares horizontally or vertically.\n- a bishop moves any number of vacant squares diagonally.\n- a queen moves any number of vacant squares horizontally, vertically, or diagonally.\n- a knight moves to one of the nearest squares not on the same rank, file, or diagonal (this can be thought of as moving two squares horizontally then one square vertically, or moving one square horizontally then two squares vertically — i. e. in an \"L\" pattern). Knights are not blocked by other pieces, they can simply jump over them.\n\nThere are no pawns on the board.\n\n\\begin{center}\n{\\small King and knight possible moves, respectively. Dotted line shows that knight can jump over other pieces.}\n\\end{center}\n\n\\begin{center}\n{\\small Queen, bishop, and rook possible moves, respectively.}\n\\end{center}",
    "tutorial": "First, we can limit the field to a non-infinite amount of columns. Take the leftmost position, the rightmost one and leave like $10$ more cells from each side so that everything is nice on the borders. If the field wasn't as huge, we could just do a BFS over it. Mark the cells that are taken by the pieces and that are attacked by them. Then just go and avoid them. Unfortunately, the field is like $10^9$ cells large, and we also have up to $8$ transitions from each cell. Too much. Let's use the fact that there are not too many pieces on the board. Take a look at two pieces that have only empty columns between them. If you go far enough inwards, then all the columns between them will look the same in terms of cells to be avoided. That far enough is the columns at distance more than $8$ from both of the pieces. The only pieces that can possibly affect these columns are rooks or queens far way that fill the entire rows. Since these columns are the same, let's get rid of them and account for the distance by using a Dijkstra instead of a BFS. The solution becomes the following. Leave only the columns that have a piece at distance at most $8$ from them. There will be at most $16 \\cdot n$ of them. Mark all the attacked cells on the taken columns. Do Dijkstra and carefully handle the moves over the missing columns. Let's think more about moving over the missing columns. Let the distance between adjacent taken columns be $d$. Then the king can go from some row $i$ of the first column into some row $j$ of the second column in $max(|i - j|, d)$ moves (it can save moves by going diagonally). You can code it exactly like that, but you can also do it a little neater. Leave not $8$ but $16$ columns. Now, the moves that the king saves by going diagonally will be accounted for automatically. And you can only consider going to the previous, the current or the next row for any pair of adjacent columns.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst string al = \"KQRBN\";\n\nconst int INF = 1e9;\n\nstruct mv{ int dx, dy; };\nstruct piece{ int x, y, t; };\nstruct seg{ int l, r; };\nstruct pos{ int x, y; };\n\nbool operator <(const pos &a, const pos &b){\n    if (a.x != b.x) return a.x < b.x;\n    return a.y < b.y;\n}\n\nvector<vector<mv>> mvs({\n    {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}},\n    {{-1, 0}, {0, 1}, {1, 0}, {0, -1}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1}},\n    {{-1, 0}, {0, 1}, {1, 0}, {0, -1}},\n    {{-1, -1}, {1, -1}, {1, 1}, {-1, 1}},\n    {{-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}}\n});\n\nint main() {\n    int sx, sy, fx, fy;\n    cin >> sx >> sy >> fx >> fy;\n    swap(sx, sy), swap(fx, fy);\n    --sx, --fx;\n    \n    int k;\n    cin >> k;\n    vector<piece> a(k);\n    forn(i, k){\n        string t;\n        cin >> t >> a[i].x >> a[i].y;\n        swap(a[i].x, a[i].y);\n        --a[i].x;\n        a[i].t = al.find(t[0]);\n    }\n    \n    sort(a.begin(), a.end(), [](const piece &a, const piece &b){\n        if (a.x != b.x) return a.x < b.x;\n        return a.y < b.y;\n    });\n    \n    vector<int> base({sy, fy});\n    forn(i, k) base.push_back(a[i].y);\n    vector<int> ys;\n    for (int y : base) for (int i = y - 16; i <= y + 16; ++i)\n        ys.push_back(i);\n    sort(ys.begin(), ys.end());\n    ys.resize(unique(ys.begin(), ys.end()) - ys.begin());\n    \n    vector<vector<char>> tk(8, vector<char>(ys.size()));\n    forn(i, k){\n        a[i].y = lower_bound(ys.begin(), ys.end(), a[i].y) - ys.begin();\n        tk[a[i].x][a[i].y] = true;\n    }\n    sy = lower_bound(ys.begin(), ys.end(), sy) - ys.begin();\n    fy = lower_bound(ys.begin(), ys.end(), fy) - ys.begin();\n    \n    vector<vector<char>> bad = tk;\n    \n    forn(i, k){\n        int x = a[i].x, y = a[i].y;\n        if (a[i].t == 0 || a[i].t == 4){\n            for (auto it : mvs[a[i].t]){\n                int nx = x + it.dx;\n                int ny = y + it.dy;\n                if (0 <= nx && nx < 8)\n                    bad[nx][ny] = true;\n            }\n        }\n        else{\n            for (auto it : mvs[a[i].t]){\n                for (int nx = x + it.dx, ny = y + it.dy; ; nx += it.dx, ny += it.dy){\n                    if (nx < 0 || nx >= 8) break;\n                    if (ny < 0 || ny >= int(ys.size())) break;\n                    if (tk[nx][ny]) break;\n                    bad[nx][ny] = true;\n                }\n            }\n        }\n    }\n    \n    vector<vector<int>> d(8, vector<int>(ys.size(), INF));\n    vector<vector<pos>> p(8, vector<pos>(ys.size()));\n    set<pair<int, pos>> q;\n    d[sx][sy] = 0;\n    q.insert({0, {sx, sy}});\n    while (!q.empty()){\n        int x = q.begin()->second.x;\n        int y = q.begin()->second.y;\n        q.erase(q.begin());\n        if (x == fx && y == fy){\n            cout << d[x][y] << endl;\n            return 0;\n        }\n        for (int ny : {y - 1, y, y + 1}){\n            if (ny < 0 || ny >= int(ys.size())) continue;\n            int dy = max(1, abs(ys[y] - ys[ny]));\n            for (int nx = max(0, x - 1); nx <= min(7, x + 1); ++nx) if (!bad[nx][ny]){\n                int nd = d[x][y] + dy;\n                if (d[nx][ny] > nd){\n                    q.erase({d[nx][ny], {nx, ny}});\n                    d[nx][ny] = nd;\n                    p[nx][ny] = {x, y};\n                    q.insert({d[nx][ny], {nx, ny}});\n                }\n            }\n        }\n    }\n    \n    cout << -1 << endl;\n    return 0;\n}",
    "tags": [
      "implementation",
      "shortest paths"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1765",
    "index": "J",
    "title": "Hero to Zero",
    "statement": "There are no heroes in this problem. I guess we should have named it \"To Zero\".\n\nYou are given two arrays $a$ and $b$, each of these arrays contains $n$ non-negative integers.\n\nLet $c$ be a matrix of size $n \\times n$ such that $c_{i,j} = |a_i - b_j|$ for every $i \\in [1, n]$ and every $j \\in [1, n]$.\n\nYour goal is to transform the matrix $c$ so that it becomes the zero matrix, i. e. a matrix where \\textbf{every} element is \\textbf{exactly} $0$. In order to do so, you may perform the following operations any number of times, in any order:\n\n- choose an integer $i$, then decrease $c_{i,j}$ by $1$ for every $j \\in [1, n]$ (i. e. decrease all elements in the $i$-th row by $1$). In order to perform this operation, you \\textbf{pay} $1$ coin;\n- choose an integer $j$, then decrease $c_{i,j}$ by $1$ for every $i \\in [1, n]$ (i. e. decrease all elements in the $j$-th column by $1$). In order to perform this operation, you \\textbf{pay} $1$ coin;\n- choose two integers $i$ and $j$, then decrease $c_{i,j}$ by $1$. In order to perform this operation, you \\textbf{pay} $1$ coin;\n- choose an integer $i$, then increase $c_{i,j}$ by $1$ for every $j \\in [1, n]$ (i. e. increase all elements in the $i$-th row by $1$). When you perform this operation, you \\textbf{receive} $1$ coin;\n- choose an integer $j$, then increase $c_{i,j}$ by $1$ for every $i \\in [1, n]$ (i. e. increase all elements in the $j$-th column by $1$). When you perform this operation, you \\textbf{receive} $1$ coin.\n\nYou have to calculate the minimum number of coins required to transform the matrix $c$ into the zero matrix. Note that all elements of $c$ should be equal to $0$ \\textbf{simultaneously} after the operations.",
    "tutorial": "The order of operations is interchangeable, so we assume that we perform mass operations first, and operations affecting single elements last. Suppose $p_i$ is the value we subtract from the $i$-th row using the operations affecting the whole row, and $q_j$ is the value we subtract from the $j$-th column using the operations affecting the whole column. Then the number of coins we have to pay is $S - (n-1) \\cdot (\\sum p_i + \\sum q_j)$, since every such operation \"saves\" us exactly $n-1$ coins by decreasing the sum in the matrix by $n$ using only one coin. Obviously, we want to maximize $\\sum p_i + \\sum q_j$, but if we subtract too much, some elements of the matrix may become negative (and it will be impossible to set them to zero using single element operations). So, for every $i \\in [1, n]$ and $j \\in [1, n]$, the condition $p_i + q_j \\le c_{i,j}$ must hold. Now let's take a look at how the Hungarian algorithm for assignment problem works. We can notice that the potentials in the Hungarian algorithm have the same constraints as the values $p_i$ and $q_j$ in our problem, and the sum of those potentials is maximized. So, if we apply the Hungarian algorithm to the matrix $c$, we can use the potentials as the values $p_i$ and $q_j$. But the matrix is too large, so what should we do? We can use the fact that the maximum possible sum of potentials is equal to the optimal solution of the assignment problem, so we should solve the assignment problem in some other way. And in this particular way of constructing the matrix $c$ (where $c_{i,j} = |a_i - b_j|$), the solution of the assignment problem is simple: we need to reorder the elements of both arrays $a$ and $b$ so that the value of $\\sum |a_i - b_i|$ is minimized, and it's easy to see (and to prove using exchange argument method) that sorting both arrays will give us the optimal solution. All that's left is to calculate the sum of elements in the matrix, and that can be done if for every element in $a$, we calculate the number of elements in $b$ which are less than it, the number of elements in $b$ which are greater than it, and the sum of elements of $b$ greater than it (to quickly compute the sum of $|a_i - b_j|$ for every $j \\in [1, n]$). All these values can be obtained with the help of binary search, two pointers method or some data structures. The complexity of the solution is $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n    vector<int> a(n), b(n);\n    for(int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\n    for(int i = 0; i < n; i++) scanf(\"%d\", &b[i]);\n    sort(a.begin(), a.end());\n    sort(b.begin(), b.end());\n    long long total = 0;\n    for(int i = 0; i < n; i++)\n    {\n        total += n * 1ll * (a[i] + b[i]);\n        total -= a[i] * 2ll * (b.end() - lower_bound(b.begin(), b.end(), a[i]));\n        total -= b[i] * 2ll * (a.end() - upper_bound(a.begin(), a.end(), b[i]));\n    }\n    for(int i = 0; i < n; i++)\n        total -= (n - 1) * 1ll * abs(a[i] - b[i]);\n    cout << total << endl;\n}",
    "tags": [
      "graph matchings",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1765",
    "index": "K",
    "title": "Torus Path",
    "statement": "You are given a square grid with $n$ rows and $n$ columns, where each cell has a non-negative integer written in it. There is a chip initially placed at the top left cell (the cell with coordinates $(1, 1)$). You need to move the chip to the bottom right cell (the cell with coordinates $(n, n)$).\n\nIn one step, you can move the chip to the neighboring cell, but:\n\n- you can move only right or down. In other words, if the current cell is $(x, y)$, you can move either to $(x, y + 1)$ or to $(x + 1, y)$. There are two special cases:\n\n- if the chip is in the last column (cell $(x, n)$) and you're moving right, you'll teleport to the first column (to the cell $(x, 1)$);\n- if the chip is in the last row (cell $(n, y)$) and you're moving down, you'll teleport to the first row (to the cell $(1, y)$).\n\n- you \\textbf{cannot} visit the same cell twice. The starting cell is counted visited from the beginning (so you cannot enter it again), and you can't leave the finishing cell once you visit it.\n\nYour total score is counted as the sum of numbers in all cells you have visited. What is the maximum possible score you can achieve?",
    "tutorial": "Note that you can't visit all vertices on the antidiagonal (vertices $(1, n), (2, n - 1), \\dots (n, 1)$) at the same time. Let's prove it: since you are starting outside the antidiagonal then the only way to visit vertex $(x, n + 1 - x)$ is to move from $(x - 1, n + 1 - x)$ or from $(x, n - x)$. In total, there are $n$ vertices you can move from - it's vertices $(1, n - 1), (2, n - 2), \\dots, (n - 1, 1)$ and $(n, n)$. But $(n, n)$ is the finishing vertices you can't leave, so there are only $n - 1$ positions left. As a result, you can visit at most $n - 1$ vertices on the antidiagonal. Now, let's prove that if you've chosen a vertex $(x, n + 1 - x)$ you decided to skip, you can always visit all other vertices. Let's use the following simple strategy: let's move right until we meet the restricted or already visited vertex, then move down once then continue moving right and so on. For example, let's visit all vertices of $4 \\times 4$ matrix except vertex $(2, 3)$. The path would be the following: $(1, 1)$ $-$ $(1, 2)$ $-$ $(1, 3)$ $-$ $(1, 4)$ $-$ $(2, 4)$ $-$ $(2, 1)$ $-$ $(2, 2)$ $-$ $(3, 2)$ $-$ $(3, 3)$ $-$ $(3, 4)$ $-$ $(3, 1)$ $-$ $(4, 1)$ $-$ $(4, 2)$ $-$ $(4, 3)$ $-$ $(4, 4)$. As a result, the answer is the sum of all elements minus the minimum among $a[x][n + 1 - x]$, or $\\sum_{i = 1}^{n}\\sum_{j = 1}^{n}a[i][j] - \\min_{1 \\le x \\le n}(a[x][n + 1 - x])$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nvector< vector<int> > a;\n\nbool read() {\n    if (!(cin >> n))\n        return false;\n    a.resize(n, vector<int>(n));\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++)\n            cin >> a[i][j];\n    }\n    return true;\n}\n\nvoid solve() {\n    long long sum = 0;\n    for (int i = 0; i < n; i++)\n        sum += accumulate(a[i].begin(), a[i].end(), 0LL);\n    \n    int mn = a[0][n - 1];\n    for (int i = 0; i < n; i++)\n        mn = min(mn, a[i][n - 1 - i]);\n    \n    cout << sum - mn << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1765",
    "index": "L",
    "title": "Project Manager",
    "statement": "There are $n$ employees at Bersoft company, numbered from $1$ to $n$. Each employee works on some days of the week and rests on the other days. You are given the lists of working days of the week for each employee.\n\nThere are regular days and holidays. On regular days, only those employees work that have the current day of the week on their list. On holidays, no one works. You are provided with a list of days that are holidays. The days are numbered from $1$ onwards, day $1$ is Monday.\n\nThe company receives $k$ project offers they have to complete. The projects are numbered from $1$ to $k$ in the order of decreasing priority.\n\nEach project consists of multiple parts, where the $i$-th part must be completed by the $a_i$-th employee. The parts must be completed in order (i. e. the $(i+1)$-st part can only be started when the $i$-th part is completed). Each part takes the corresponding employee a day to complete.\n\nThe projects can be worked on simultaneously. However, one employee can complete a part of only one project during a single day. If they have a choice of what project to complete a part on, they always go for the project with the highest priority (the lowest index).\n\nFor each project, output the day that project will be completed on.",
    "tutorial": "First, notice that the answer can't be that large. Even the worst case: one developer works one day of the week, responsible for a $2 \\cdot 10^5$ part project, the first $2 \\cdot 10^5$ of his workdays are holidays. It's just $7 \\cdot (2 \\cdot 10^5 + 2 \\cdot 10^5)$. Thus, we'd like to iterate over time and complete project parts exactly as they are due. If we manage to deduce the parts that have to be completed during the current day, the complexity will be limited by the total number of parts plus the maximum time. To determine that, I propose to maintain the following data structures. First, maintain $7$ vectors of maps: for each day of the week, maintain pairs (the developer, the number of projects they are currently the blocking person for). Each developer is only counted in days they work at and only if they have a non-zero number of projects. Second, maintain $n$ vectors of sets: for each developer, maintain the projects they are currently the blocking person for. To process a day, extract all pairs from the map for the current day of the week. All these developers will complete a part of a project. The index of that project is the first element in the corresponding set. Update all maps and sets and proceed. If the number of projects for any developers becomes zero, remove them from the maps. If the current day is a holiday, just skip it.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst string days[] = {\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"};\n\nint main() {\n    cin.tie(0);\n    iostream::sync_with_stdio(false);\n    int n, m, k;\n    cin >> n >> m >> k;\n    vector<vector<char>> ds(n, vector<char>(7));\n    forn(i, n){\n        int t;\n        cin >> t;\n        forn(_, t){\n            string s;\n            cin >> s;\n            ds[i][find(days, days + 7, s) - days] = true;\n        }\n    }\n    vector<int> h(m);\n    forn(i, m) cin >> h[i];\n    vector<vector<int>> a(k);\n    forn(i, k){\n        int p;\n        cin >> p;\n        a[i].resize(p);\n        forn(j, p){\n            cin >> a[i][j];\n            --a[i][j];\n        }\n    }\n    int j = 0;\n    vector<int> ans(k, -1), lst(k);\n    int done = 0;\n    vector<map<int, int>> cur(7);\n    vector<set<int>> wk(n);\n    forn(i, k) forn(j, 7) if (ds[a[i][0]][j])\n        ++cur[j][a[i][0]];\n    forn(i, k)\n        wk[a[i][0]].insert(i);\n    for (int d = 1;; ++d){\n        if (j < m && h[j] == d){\n            ++j;\n            continue;\n        }\n        int wd = (d - 1) % 7;\n        vector<int> now, sv;\n        for (auto it : cur[wd]) now.push_back(it.first);\n        for (int x : now){\n            forn(i, 7){\n                auto it = cur[i].find(x);\n                if (it != cur[i].end()){\n                    if (it->second == 1)\n                        cur[i].erase(it);\n                    else\n                        --it->second;\n                }\n            }\n            int y = *wk[x].begin();\n            sv.push_back(y);\n            wk[x].erase(wk[x].begin());\n        }\n        forn(i, now.size()){\n            int y = sv[i];\n            ++lst[y];\n            if (lst[y] == int(a[y].size())){\n                ans[y] = d;\n                ++done;\n                continue;\n            }\n            wk[a[y][lst[y]]].insert(y);\n            forn(j, 7) if (ds[a[y][lst[y]]][j])\n                ++cur[j][a[y][lst[y]]];\n        }\n        if (done == k) break;\n    }\n    forn(i, k) cout << ans[i] << \" \";\n    cout << endl;\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1765",
    "index": "M",
    "title": "Minimum LCM",
    "statement": "You are given an integer $n$.\n\nYour task is to find two positive (greater than $0$) integers $a$ and $b$ such that $a+b=n$ and the least common multiple (LCM) of $a$ and $b$ is the minimum among all possible values of $a$ and $b$. If there are multiple answers, you can print any of them.",
    "tutorial": "Suppose $a \\le b$. Let's show that if $b \\bmod a \\ne 0$, the answer is suboptimal. If $b \\bmod a = 0$, then $LCM(a, b) = b$, so the answer is less than $n$. But if $b \\bmod a \\ne 0$, then $LCM(a, b)$ is at least $2b$, and $b$ is at least $\\frac{n}{2}$, so in this case, the answer is at least $n$. Okay, now we know that in the optimal answer, $b \\bmod a = 0$. This also means that $n \\bmod a = 0$, since $n = a + b$. So we need to search for $a$ only among the divisors of $n$, and it is possible to iterate through all of them in $O(n^{0.5})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    int a = 1;\n    for (int g = 2; g * g <= n; ++g) {\n      if (n % g == 0) {\n        a = n / g;\n        break;\n      }\n    }\n    cout << a << ' ' << n - a << '\\n';\n  }\n}\n ",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1765",
    "index": "N",
    "title": "Number Reduction",
    "statement": "You are given a positive integer $x$.\n\nYou can apply the following operation to the number: remove one occurrence of any digit in such a way that the resulting number \\textbf{does not contain any leading zeroes} and \\textbf{is still a positive integer}. For example, $10142$ can be converted to $1142$, $1042$, $1012$ or $1014$ (note that $0142$ is not a valid outcome); $10$ can be converted to $1$ (but not to $0$ since it is not positive).\n\nYour task is to find the minimum positive integer that you can obtain from $x$ if you can apply the aforementioned operation exactly $k$ times.",
    "tutorial": "To begin with, in order to minimize the answer, we minimize the first (highest) digit of the answer. Let's check if the highest digit can be equal to $1$. To do this, there must be $1$ in the number among the first $k+1$ digits (because we can delete no more than $k$ of them). If $1$ is not among the first $k+1$ digits, then we proceed to check $2$, then $3$ and so on. Otherwise, let's say that this digit is the first digit of the answer, and remove all the digits before it and itself from the number $x$, reducing the value of $k$. For example, if $x=741819$ and $k=4$, then after the operation $ans=1$, $x=819$ and $k=2$. Thus, we get the same problem, but with new values of $x$ and $k$, which is solved by the same algorithm (searching for the minimum first digit). The only difference is that after the first such iteration, the first digit can be equal to $0$. It remains to understand how to quickly check whether the digit $d$ is among the first $k+1$ positions of the number. To do this, let's write, for each digit, its positions in the original number $x$. At each iteration of the algorithm, the current value of $x$ is some suffix of the original $x$, let it be the suffix of positions $[lst; n]$, where $n$ is the length of the original $x$. Now to check the digit, it is enough to look into its array of positions and find the minimum occurrence greater than or equal to $lst$. To do this, you can use binary search or delete all positions that are strictly less than $lst$ from the array or set (because the value of $lst$ only increases for subsequent iterations of the algorithm). Thus, the solution works in $O(n)$ or $O(n\\log{n})$ time.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  \n  int t;\n  cin >> t;\n  while (t--) {\n    string x;\n    cin >> x;\n    int k;\n    cin >> k;\n    int n = x.size();\n    vector<vector<int>> pos(10);\n    for (int i = 0; i < n; ++i)\n      pos[x[i] - '0'].push_back(i);\n    for (int i = 0; i < 10; ++i)\n      reverse(pos[i].begin(), pos[i].end());\n    string ans;\n    int lst = 0, len = n - k;\n    for (int i = 0; i < len; ++i) {\n      for (int d = (i == 0); d <= 9; ++d) {\n        while (!pos[d].empty() && pos[d].back() < lst)\n          pos[d].pop_back();\n        if (!pos[d].empty() && pos[d].back() - lst <= k) {\n          ans += d + '0';\n          k -= pos[d].back() - lst;\n          lst = pos[d].back() + 1;\n          break;\n        }\n      }\n    }\n    cout << ans << '\\n';\n  }\n}\n ",
    "tags": [
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1766",
    "index": "A",
    "title": "Extremely Round",
    "statement": "Let's call a positive integer extremely round if it has only one non-zero digit. For example, $5000$, $4$, $1$, $10$, $200$ are extremely round integers; $42$, $13$, $666$, $77$, $101$ are not.\n\nYou are given an integer $n$. You have to calculate the number of extremely round integers $x$ such that $1 \\le x \\le n$.",
    "tutorial": "There are many ways to solve this problem. The most naive one (iterating through all numbers from $1$ to $n$ in each test case and checking if they are extremely round) fails, since it is $O(tn)$, but you can optimize it by noticing that extremely round numbers are rare. So, for example, we can iterate through all numbers from $1$ to $999999$ once, remember which ones are extremely round, store them into an array, and while answering the test case, only check the numbers from the array we have created. There is also a solution in $O(1)$ per test case with a formula, try to invent it yourself.",
    "code": "def check(x):\n    s = str(x)\n    cnt = 0\n    for c in s:\n        if c != '0':\n            cnt += 1\n    return cnt == 1\n\na = []\nfor i in range(1, 1000000):\n    if check(i):\n        a.append(i)\nt = int(input())\nfor i in range(t):\n    n = int(input())\n    ans = 0\n    for x in a:\n        if x <= n:\n            ans += 1\n    print(ans)",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1766",
    "index": "B",
    "title": "Notepad#",
    "statement": "You want to type the string $s$, consisting of $n$ lowercase Latin letters, using your favorite text editor Notepad#.\n\nNotepad# supports two kinds of operations:\n\n- append any letter \\textbf{to the end} of the string;\n- copy a \\textbf{continuous} substring of an already typed string and paste this substring \\textbf{to the end} of the string.\n\nCan you type string $s$ in \\textbf{strictly less} than $n$ operations?",
    "tutorial": "Why does the problem ask us only to check if we can do less than $n$ operations instead of just asking the minimum amount? That must be making the problem easier, so let's focus our attention on that. What if it was $\\le n$ instead of $< n$? Well, then the problem would be trivial. You can type the word letter by letter and be done in $n$ operations. So we only have to save one operation. In order to save at least one operation, we have to use the copy operation and copy more than one character in that. Let's take a closer look at any of the copy operations we do. Basically, it has to be a substring that has at least two non-intersection occurrences in the string. Thus, if the string has any substring that has length at least two that appears at least twice in the string, we can copy it, and the answer will be \"YES\". That's still not enough to solve the problem - we'd have to check all substrings, which is $O(n^2)$. Let's think further. Imagine we found a substring that works. Let it have length $k$. Notice how you can remove its last character, obtaining a substring of length $k-1$, and it will still occure in the same set of positions (possibly, even more occurrences will be found). Remove characters until the substring has length $2$. Thus, if any appropriate substring exists, an appropriate substring of length $2$ also exists. Finally, we can check if there exists a substring of length $2$ that appears at least twice in the string so that the occurrences are at least $2$ apart. That can be done with a set/hashset or a map/hashmap. Some implementations might require careful handling of the substrings of kind \"aa\", \"bb\" and similar. Overall complexity: $O(n)$ or $O(n \\log n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ts = input()\n\tcur = {}\n\tfor i in range(n - 1):\n\t\tt = s[i:i+2]\n\t\tif t in cur:\n\t\t\tif cur[t] < i - 1:\n\t\t\t\tprint(\"YES\")\n\t\t\t\tbreak\n\t\telse:\n\t\t\tcur[t] = i\n\telse:\n\t\tprint(\"NO\")",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1766",
    "index": "C",
    "title": "Hamiltonian Wall",
    "statement": "Sir Monocarp Hamilton is planning to paint his wall. The wall can be represented as a grid, consisting of $2$ rows and $m$ columns. Initially, the wall is completely white.\n\nMonocarp wants to paint a black picture on the wall. In particular, he wants cell $(i, j)$ (the $j$-th cell in the $i$-th row) to be colored black, if $c_{i, j} =$ 'B', and to be left white, if $c_{i, j} =$ 'W'. Additionally, he wants each column to have at least one black cell, so, for each $j$, the following constraint is satisfied: $c_{1, j}$, $c_{2, j}$ or both of them will be equal to 'B'.\n\nIn order for the picture to turn out smooth, Monocarp wants to place down a paint brush in some cell $(x_1, y_1)$ and move it along the path $(x_1, y_1), (x_2, y_2), \\dots, (x_k, y_k)$ so that:\n\n- for each $i$, $(x_i, y_i)$ and $(x_{i+1}, y_{i+1})$ share a common side;\n- all black cells appear in the path \\textbf{exactly once};\n- white cells don't appear in the path.\n\nDetermine if Monocarp can paint the wall.",
    "tutorial": "Why is there a constraint of each column having at least one black cell? Does the problem change a lot if there were white columns? Well, if such a column was inbetween some black cells, then the answer would be \"NO\". If it was on the side of the grid, you could remove it and proceed to solve without it. So, that doesn't really change the problem other than removing some casework. Let's try to fix a start. Find a column that has only one black cell in it. If there are no such columns, the answer is immediately \"YES\". Otherwise, the path will always go through it in known directions: to the left and to the right (if both of them exist). Let's solve the problem separately for the left part of the path and for the right one - find a path that starts to the left of it and covers everything to the left and the same for the right part. Consider the right part. If the next column also has one black cell, then we can determine where to go uniquely. If this cell is on the opposite row, then the answer is \"NO\". Otherwise, go there and proceed further. Let it have two black cells now. Find the entire two black row rectangle of maximum size that starts there. If there's nothing after it, you can easily traverse it any way you like. Otherwise, you have to traverse it in such a way that you end up in its last column, then go to the right from there. Turns out, there's only one way to achieve that. Go up/down to another row, go right, up/down to another row, right and so on. Now you just have to check if you end up in the correct row. Thus, you can simulate the path to the left and to the right and check if you never get stuck. Overall comlexity: $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ts = [input() for i in range(2)]\n\tpos = -1\n\tfor i in range(n):\n\t\tif s[0][i] != s[1][i]:\n\t\t\tpos = i\n\tif pos == -1:\n\t\tprint(\"YES\")\n\t\tcontinue\n\tok = True\n\tcur = 0 if s[0][pos] == 'B' else 1\n\tfor i in range(pos + 1, n):\n\t\tif s[cur][i] == 'W':\n\t\t\tok = False\n\t\tif s[cur ^ 1][i] == 'B':\n\t\t\tcur ^= 1\n\tcur = 0 if s[0][pos] == 'B' else 1\n\tfor i in range(pos - 1, -1, -1):\n\t\tif s[cur][i] == 'W':\n\t\t\tok = False\n\t\tif s[cur ^ 1][i] == 'B':\n\t\t\tcur ^= 1\n\tprint(\"YES\" if ok else \"NO\")",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1766",
    "index": "D",
    "title": "Lucky Chains",
    "statement": "Let's name a pair of positive integers $(x, y)$ lucky if the greatest common divisor of them is equal to $1$ ($\\gcd(x, y) = 1$).\n\nLet's define a chain induced by $(x, y)$ as a sequence of pairs $(x, y)$, $(x + 1, y + 1)$, $(x + 2, y + 2)$, $\\dots$, $(x + k, y + k)$ for some integer $k \\ge 0$. The length of the chain is the number of pairs it consists of, or $(k + 1)$.\n\nLet's name such chain lucky if all pairs in the chain are lucky.\n\nYou are given $n$ pairs $(x_i, y_i)$. Calculate for each pair the length of the longest lucky chain induced by this pair. Note that if $(x_i, y_i)$ is not lucky itself, the chain will have the length $0$.",
    "tutorial": "Suppose, $\\gcd(x + k, y + k) = g$. It means that $(y + k) - (x + k) = (y - x)$ is also divisible by $g$, or $\\gcd(x + k, y - x) = h$ is divisible by $g$. And backward: if $\\gcd(x + k, y - x) = h$, then $(x + k) + (y - x) = (y + k)$ is also divisible by $h$, or $\\gcd(x + k, y + k) = g$ is divisible by $h$. Since $h$ is divisible by $g$ and $g$ is divisible by $h$, so $h = g$. In other words, we proved that $\\gcd(x + k, y + k) = \\gcd(x + k, y - x)$. Now, knowing the equivalence above, we can understand that we are looking for the smallest $k \\ge 0$ such that $\\gcd(x + k, y - x) > 1$. In other words, we are searching $k$ such that $x + k$ is divisible by some $d > 1$, where $d$ is some divisor of $(y - x)$. The problem is that there are a handful of divisors for some $(y - x)$. But we can note that we can consider only prime divisors of $(y - x)$: if $d | (y - x)$ and $d$ is composite then there is some prime $p | d$, thus $p | (y - x)$. It's easy to prove that there are no more than $\\log_2{n}$ prime divisors of some $n$. Now the question is how to find all these prime divisors. Note that if you know only one prime divisor for each value from $1$ to $n$, then you can find all prime divisors for all $k \\le n$ in $O(\\log{k})$. The prime divisors $p_i$ are next: $p_1 = minD[k]$, $k_1 = \\frac{k}{minD[k]}$; $p_2 = minD[k_1]$, $k_2 = \\frac{k_1}{minD[k_1]}$; $p_3 = minD[k_2]$, $k_3 = \\frac{k_2}{minD[k_2]}$; and so on until $k_i > 1$. The final step is to calculate a prime divisor $minD[i]$ for each value from $1$ to $A$, where $A \\ge \\max(y_i)$ or $A \\ge 10^7$. We can do it by slight modifications of Sieve of Eratosthenes: at the step, where you have some prime $p$ and want to \"throw out\" all values $k \\cdot p$, set $minD[kp] = p$ for each $kp$ (plus set $minD[p] = p$). As a result, we, firstly, calculate Sieve in $O(N \\log{\\log{N}})$ and, secondly, calculate answer for each pair $(x_i, y_i)$ in $O(\\log{N})$. Note that the input and output is large, so you should you tricks to speed up your input and output.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\ntypedef long long li;\n\nconst int INF = int(1e9);\nconst int N = int(1e7) + 5;\n\nint mind[N];\n\nvoid precalc() {\n\tfore (i, 0, N)\n\t\tmind[i] = i;\n\t\n\tfor (int p = 2; p < N; p++) {\n\t\tif (mind[p] != p)\n\t\t\tcontinue;\n\t\tfor (int d = 2 * p; d < N; d += p)\n\t\t\tmind[d] = min(mind[d], p);\n\t}\n}\n\nint x, y;\n\ninline bool read() {\n\tif(!(cin >> x >> y))\n\t\treturn false;\n\treturn true;\n}\n\nvector<int> getPrimes(int v) {\n\tvector<int> ps;\n\twhile (v > 1) {\n\t\tif (ps.empty() || ps.back() != mind[v])\n\t\t\tps.push_back(mind[v]);\n\t\tv /= mind[v];\n\t}\n\treturn ps;\n}\n\ninline void solve() {\n\tint d = y - x;\n\tif (d == 1) {\n\t\tcout << -1 << '\\n';\n\t\treturn;\n\t}\n\t\n\tint r = INF;\n\tfor (int p : getPrimes(d))\n\t\tr = min(r, ((x + p - 1) / p) * p);\n\tcout << r - x << '\\n';\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tprecalc();\n\t\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1766",
    "index": "E",
    "title": "Decomposition",
    "statement": "For a sequence of integers $[x_1, x_2, \\dots, x_k]$, let's define its decomposition as follows:\n\nProcess the sequence from the first element to the last one, maintaining the list of its subsequences. When you process the element $x_i$, append it to the end of the \\textbf{first} subsequence in the list such that the bitwise AND of its last element and $x_i$ is greater than $0$. If there is no such subsequence in the list, create a new subsequence with only one element $x_i$ and append it to the end of the list of subsequences.\n\nFor example, let's analyze the decomposition of the sequence $[1, 3, 2, 0, 1, 3, 2, 1]$:\n\n- processing element $1$, the list of subsequences is empty. There is no subsequence to append $1$ to, so we create a new subsequence $[1]$;\n- processing element $3$, the list of subsequences is $[[1]]$. Since the bitwise AND of $3$ and $1$ is $1$, the element is appended to the first subsequence;\n- processing element $2$, the list of subsequences is $[[1, 3]]$. Since the bitwise AND of $2$ and $3$ is $2$, the element is appended to the first subsequence;\n- processing element $0$, the list of subsequences is $[[1, 3, 2]]$. There is no subsequence to append $0$ to, so we create a new subsequence $[0]$;\n- processing element $1$, the list of subsequences is $[[1, 3, 2], [0]]$. There is no subsequence to append $1$ to, so we create a new subsequence $[1]$;\n- processing element $3$, the list of subsequences is $[[1, 3, 2], [0], [1]]$. Since the bitwise AND of $3$ and $2$ is $2$, the element is appended to the first subsequence;\n- processing element $2$, the list of subsequences is $[[1, 3, 2, 3], [0], [1]]$. Since the bitwise AND of $2$ and $3$ is $2$, the element is appended to the first subsequence;\n- processing element $1$, the list of subsequences is $[[1, 3, 2, 3, 2], [0], [1]]$. The element $1$ cannot be appended to any of the first two subsequences, but can be appended to the third one.\n\nThe resulting list of subsequences is $[[1, 3, 2, 3, 2], [0], [1, 1]]$.\n\nLet $f([x_1, x_2, \\dots, x_k])$ be the number of subsequences the sequence $[x_1, x_2, \\dots, x_k]$ is decomposed into.\n\nNow, for the problem itself.\n\nYou are given a sequence $[a_1, a_2, \\dots, a_n]$, where each element is an integer from $0$ to $3$. Let $a[i..j]$ be the sequence $[a_i, a_{i+1}, \\dots, a_j]$. You have to calculate $\\sum \\limits_{i=1}^n \\sum \\limits_{j=i}^n f(a[i..j])$.",
    "tutorial": "Let's assume that we don't have any zeroes in our array. We'll deal with them later. The key observation is that the number of sequences in the decomposition is not more than $3$. To prove this, we can use the fact that each element $3$ will be appended to the first subsequence in the decomposition; so, if the second/third subsequence in the decomposition ends with the number $2$ or $1$, all such numbers can be appended to that subsequence, thus they won't create any new subsequences. So, if we consider the combination of the last elements in the subsequences of the decomposition, there are only $3^3 + 3^2 + 3^1 + 3^0 = 40$ such combinations (even less in practice). Okay, now let's try to use the fact that the number of such combinations is small. There are many ways to abuse it, but, in my opinion, the most straightforward one (and also a bit slow, but fast enough to easily pass the time limit) is to run the following dynamic programming: $dp_{i,c}$, where $i$ is the index of the element we are processing, and $c$ is the vector representing the combination of last elements of subsequences in the decomposition. But it's not clear what do we store in this dynamic programming. The model solution stores the total number of subsequences added to the decomposition, if right now the state of decomposition is $c$, we process the $i$-th element, and we consider all possible stopping points (i. e. we will consider the number of subsequences added while processing the elements $a[i..i], a[i..i+1], a[i..i+2], \\dots, a[i..n]$). So, our dynamic programming automatically sums up the answers for all possible right borders of the segment we decompose. Transitions in this dynamic programming is easy: we need to see how does the element $a_i$ alter the state of decomposition $c$ (let it change it to $c'$), take the value of $dp_{i+1, c'}$, and if the element $a_i$ forms a new subsequence, let's account for it by increasing $dp_{i,c}$ by $n-i+1$, because this increase will affect $n-i+1$ different right endpoints of the segment we decompose. And now it's easy to see how to add zeroes to our solution. We can just assume they don't change the state of decomposition, they simply add a new subsequence which won't take any other elements. So, in our transitions, processing $0$ means that $c' = c$, but the size of decomposition increases. To actually get the answer to the problem, we need to consider all possible starting points of the segment, so we sum up $dp_{i,o}$ (where $o$ is the empty vector) for all $i \\in [1, n]$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300043;\n\nint n;\nint v[N];\nmap<vector<int>, long long> dp[N];\n\npair<int, vector<int>> go(vector<int> a, int x)\n{\n    if(x == 0)\n        return {1, a};\n    else\n    {\n        bool f = false;\n        for(int i = 0; i < a.size() && !f; i++)\n            if((a[i] & x) > 0)\n            {\n                f = true;\n                a[i] = x;\n            }\n        int c = 0;\n        if(!f)\n        {\n            c = 1;\n            a.push_back(x);\n        }\n        return {c, a};\n    }\n}\n\nlong long calc(int i, vector<int> a)\n{\n    if(i == n) return 0ll;\n    if(dp[i].count(a)) return dp[i][a];\n    auto p = go(a, v[i]);\n    return (dp[i][a] = p.first * 1ll * (n - i) + calc(i + 1, p.second));\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for(int i = 0; i < n; i++) scanf(\"%d\", &v[i]);\n    long long ans = 0;\n    for(int i = 0; i < n; i++)\n        ans += calc(i, vector<int>(0));\n    printf(\"%lld\\n\", ans);    \n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "divide and conquer",
      "dp",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1766",
    "index": "F",
    "title": "MCF",
    "statement": "You are given a graph consisting of $n$ vertices and $m$ directed arcs. The $i$-th arc goes from the vertex $x_i$ to the vertex $y_i$, has capacity $c_i$ and weight $w_i$. No arc goes into the vertex $1$, and no arc goes from the vertex $n$. There are no cycles of negative weight in the graph (it is impossible to travel from any vertex to itself in such a way that the total weight of all arcs you go through is negative).\n\nYou have to assign each arc a flow (an integer between $0$ and its capacity, inclusive). For every vertex \\textbf{except $1$ and $n$}, the total flow on the arcs going to this vertex must be equal to the total flow on the arcs going from that vertex. Let the flow on the $i$-th arc be $f_i$, then the cost of the flow is equal to $\\sum \\limits_{i = 1}^{m} f_i w_i$. You have to find a flow which \\textbf{minimizes} the cost.\n\nSounds classical, right? Well, we have some additional constraints on the flow on every edge:\n\n- if $c_i$ is even, $f_i$ must be even;\n- if $c_i$ is odd, $f_i$ must be odd.\n\nCan you solve this problem?",
    "tutorial": "This problem is solved using minimum cost flows (duh). Suppose all arcs have even capacity. Then we can just divide each arc's capacity by $2$ and solve a usual minimum cost flow problem. However, when we have arcs with odd capacity, it's not that simple. We will deal with them as follows: split an arc with capacity $2k+1$ into two arcs: one with capacity $2k$, the other with capacity $1$, and somehow enforce that the second arc must be saturated. We cannot divide all arcs by $2$ now, because that would lead to non-integer capacities; instead, we will exclude these arcs with capacity $1$ and somehow handle the fact that they must be saturated, and only then divide all capacities by $2$. Okay, how do we handle the edges we deleted? For each vertex, let's check if the number of such arcs connected to it is even. If it is not - the total flow for this vertex cannot be $0$, so it's impossible to find the answer (the only case when it might be possible is if this vertex is the source or the sink; in this case, we need to check that both of these vertices have an odd number of arcs we want to delete connected to them, and consider an additional arc $1 \\rightarrow n$ with capacity $1$ and weight $0$ to make it even). If for each vertex, the number of odd arcs connected to it is even, let's consider how much excess flow these arcs bring into the vertices. For example, if a vertex has $4$ ingoing odd arcs, it has $4$ units of flow going into it, which will be lost if we remove the edges we want to ignore. To handle this, add a new source and a new sink to our network (let's call them $s$ and $t$), and process excess flow going into the vertex using an arc from $s$ to that vertex (in the previous example, we can add an arc from $s$ to the vertex with capacity $2$ - not $4$ since we divide all capacities by $2$). Similarly, excess flow going outside the vertex can be processed with an arc from that vertex to $t$. We need to make sure that all these edges must be saturated. Okay, what about actually running the flow from $1$ to $n$? We can do it as in \"flow with lower bounds\" problem by adding an arc $n \\rightarrow 1$ with infinite capacity... Wait a minute, this may cause a negative cycle to appear! If your implementation of mincost flow handles them, you can use this approach; but if you don't want to mess with negative cycles, instead do the following: add an arc $s \\rightarrow 1$ and an arc $n \\rightarrow t$, both with infinite capacities, to make sure that flow can go from $1$ to $n$; since these arcs don't have to be saturated, but other arcs going from $s$ or into $t$ must be saturated, set the costs of these \"other\" arcs to $-10^9$. Okay, that's it - we just need to find the minimum cost flow in the resulting network. The constraints are low enough so any minimum cost flow algorith can pass.",
    "code": "#include <bits/stdc++.h>     \n\nusing namespace std;\n\nconst int N = 243;\n\nstruct edge\n{\n    int y, c, w, f;\n    edge() {};\n    edge(int y, int c, int w, int f) : y(y), c(c), w(w), f(f) {};\n};\n\nvector<edge> e;\nvector<int> g[N];\n\nint rem(int x)\n{\n    return e[x].c - e[x].f;\n}\n\nvoid add_edge(int x, int y, int c, int w)\n{\n    g[x].push_back(e.size());\n    e.push_back(edge(y, c, w, 0));\n    g[y].push_back(e.size());\n    e.push_back(edge(x, 0, -w, 0));\n}\n\nint n, m, s, t, v;\n\npair<int, long long> MCMF()\n{\n    int flow = 0;\n    long long cost = 0;\n    while(true)\n    {\n        vector<long long> d(v, (long long)(1e18));\n        vector<int> p(v, -1);\n        vector<int> pe(v, -1);\n        queue<int> q;\n        vector<bool> inq(v);\n        q.push(s);\n        inq[s] = true;\n        d[s] = 0;\n        while(!q.empty())\n        {\n            int k = q.front();\n            q.pop();\n            inq[k] = false;\n            for(auto ei : g[k])\n            {\n                if(rem(ei) == 0) continue;\n                int to = e[ei].y;\n                int w = e[ei].w;\n                if(d[to] > d[k] + w)\n                {\n                    d[to] = d[k] + w;\n                    p[to] = k;\n                    pe[to] = ei;\n                    if(!inq[to])\n                    {\n                        inq[to] = true;\n                        q.push(to);\n                    }\n                }\n            }\n        }\n        if(p[t] == -1 || d[t] >= 0) break;\n        flow++;\n        cost += d[t];\n        int cur = t;\n        while(cur != s)\n        {\n            e[pe[cur]].f++;\n            e[pe[cur] ^ 1].f--;\n            cur = p[cur];\n        }\n    }\n    return make_pair(flow, cost);\n}\n\nvoid no_answer()\n{\n    cout << \"Impossible\" << endl;\n    exit(0);\n}\n\nint main()\n{                              \n    cin >> n >> m;\n    vector<int> excess_flow(n, 0);\n    vector<int> orc(m);\n    for(int i = 0; i < m; i++)\n    {\n        int x, y, c, w;\n        cin >> x >> y >> c >> w;\n        orc[i] = c;\n        --x;\n        --y;\n        add_edge(x, y, c / 2, w);\n        if(c % 2 == 1)\n        {\n            excess_flow[x]--;\n            excess_flow[y]++;\n        }\n    }\n    s = n;\n    t = n + 1;\n    v = n + 2;\n    int total_excess = 0;\n    if(excess_flow[0] % 2 == -1)\n    {\n        excess_flow[0]--;\n        excess_flow[n - 1]++;\n    }\n    for(int i = 0; i < n; i++)\n    {\n        if(excess_flow[i] % 2 != 0)\n            no_answer();\n        int val = abs(excess_flow[i]) / 2;\n        if(excess_flow[i] > 0)\n        {\n            total_excess += val;\n            add_edge(s, i, val, -int(1e9));\n        }\n        if(excess_flow[i] < 0)\n        {\n            add_edge(i, t, val, -int(1e9));\n        }\n    }\n    add_edge(s, 0, 100000, 0);\n    add_edge(n - 1, t, 100000, 0);\n    auto ans = MCMF();\n    bool good_answer = true;\n    for(int x = 0; x < e.size(); x++)\n        if(e[x].w == -int(1e9) && rem(x) != 0)\n            good_answer = false;\n    if(!good_answer)\n        no_answer();\n    cout << \"Possible\" << endl;\n    for(int i = 0; i < 2 * m; i += 2)\n    {\n        if(i) cout << \" \";\n        cout << e[i].f * 2 + orc[i / 2] % 2;\n    }\n    cout << endl;\n}",
    "tags": [
      "flows"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1767",
    "index": "A",
    "title": "Cut the Triangle",
    "statement": "You are given a non-degenerate triangle (a non-degenerate triangle is a triangle with positive area). The vertices of the triangle have coordinates $(x_1, y_1)$, $(x_2, y_2)$ and $(x_3, y_3)$.\n\nYou want to draw a straight line to cut the triangle into \\textbf{two non-degenerate triangles}. Furthermore, the line you draw should be \\textbf{either horizontal or vertical}.\n\nCan you draw the line to meet all the constraints?\n\nHere are some suitable ways to draw the line:\n\nHowever, these ways to draw the line are not suitable (the first line cuts the triangle into a triangle and a quadrangle; the second line doesn't cut the triangle at all; the third line is neither horizontal nor vertical):",
    "tutorial": "The line we draw must go through a triangle's vertex; otherwise, two sides of the triangle are split, and one of the resulting parts becomes a quadrilateral. So we need to check if it is possible to make a horizontal or vertical cut through a vertex. A horizontal cut is possible if all $y$-coordinates are different (we can draw it through a vertex with the median $y$-coordinate); a vertical cut is possible if all $x$-coordinates are different (we can draw it through a vertex with the median $x$-coordinate). So, all we need to check is the following pair of conditions: all $x_i$ are different; all $y_i$ are different.",
    "code": "t = int(input())\nfor i in range(t):\n    input()\n    xs = []\n    ys = []\n    for j in range(3):\n        x, y = map(int, input().split())\n        xs.append(x)\n        ys.append(y)\n    print('YES' if len(set(xs)) == 3 or len(set(ys)) == 3 else 'NO')",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1767",
    "index": "B",
    "title": "Block Towers",
    "statement": "There are $n$ block towers, numbered from $1$ to $n$. The $i$-th tower consists of $a_i$ blocks.\n\nIn one move, you can move one block from tower $i$ to tower $j$, but only if $a_i > a_j$. That move increases $a_j$ by $1$ and decreases $a_i$ by $1$. You can perform as many moves as you would like (possibly, zero).\n\nWhat's the largest amount of blocks you can have on the tower $1$ after the moves?",
    "tutorial": "Notice that it never makes sense to move blocks between the towers such that neither of them is tower $1$ as that can only decrease the heights. Moreover, it never makes sense to move blocks away from the tower $1$. Thus, all operations will be moving blocks from some towers to tower $1$. At the start, which towers can move at least one block to tower $1$? Well, only such $i$ that $a_i > a_1$. What happens after you move a block? Tower $1$ becomes higher, some tower becomes lower. Thus, the set of towers that can share a block can't become larger. Let's order the towers by the number of blocks in them. At the start, the towers that can share a block are at the end (on some suffix) in this order. After one move is made, the towers get reordered, and the suffix can only shrink. Ok, but if that suffix shrinks, what's the first tower that will become too low? The leftmost one that was available before. So, regardless of what the move is, the first tower that might become unavailable is the leftmost available tower. Thus, let's attempt using it until it's not too late. The algorithm then is the following. Find the lowest tower that can move the block to tower $1$, move a block, repeat. When there are no more towers higher than tower $1$, the process stops. However, the constraints don't allow us to do exactly that. We'll have to make at most $10^9$ moves per testcase. Ok, let's move the blocks in bulk every time. Since the lowest available tower will remain the lowest until you can't use it anymore, make all the moves from it at the same time. If the current number of blocks in tower $1$ is $x$ and the current number of blocks in that tower is $y$, $\\lceil\\frac{y - x}{2}\\rceil$ blocks can be moved. You can also avoid maintaining the available towers by just iterating over the towers in the increasing order of their height. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    x = a[0]\n    a = sorted(a[1:])\n    for y in a:\n        if y > x:\n            x += (y - x + 1) // 2\n    print(x)",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1767",
    "index": "C",
    "title": "Count Binary Strings",
    "statement": "You are given an integer $n$. You have to calculate the number of binary (consisting of characters 0 and/or 1) strings $s$ meeting the following constraints.\n\nFor every pair of integers $(i, j)$ such that $1 \\le i \\le j \\le n$, an integer $a_{i,j}$ is given. It imposes the following constraint on the string $s_i s_{i+1} s_{i+2} \\dots s_j$:\n\n- if $a_{i,j} = 1$, all characters in $s_i s_{i+1} s_{i+2} \\dots s_j$ should be the same;\n- if $a_{i,j} = 2$, there should be at least two different characters in $s_i s_{i+1} s_{i+2} \\dots s_j$;\n- if $a_{i,j} = 0$, there are no additional constraints on the string $s_i s_{i+1} s_{i+2} \\dots s_j$.\n\nCount the number of binary strings $s$ of length $n$ meeting the aforementioned constraints. Since the answer can be large, print it modulo $998244353$.",
    "tutorial": "Suppose we build the string from left to right, and when we place the $i$-th character, we ensure that all substrings ending with the $i$-th character are valid. What do we need to know in order to calculate the number of different characters in the string ending with the $i$-th character? Suppose the character $s_i$ is 0. Let's try going to the left of it. The string from $i$ to $i$ will have the same characters; but if there is at least one character 1 before the $i$-th position, the string $s_1 s_2 s_3 \\dots s_i$ will have two different characters. What about the strings in the middle? The string $s_j s_{j+1} \\dots s_i$ will contain different characters if and only if there is at least one 1 in $[j, i)$ (since $s_i$ is 0), so we are actually interested in the position of the last character 1 before $i$. The same logic applies if the character $s_i$ is 1: we are only interested in the position of the last 0 before $i$, and it is enough to check if all substrings ending with the $i$-th character are violated. What if when we choose the $i$-th character, we violate some substring that doesn't end in the $i$-th position? Well, you could also check that... or you could just ignore it. Actually, it doesn't matter if this happens because it means that the substring that is violated ends in some position $k > i$; and we will check it when placing the $k$-th character. So, the solution can be formulated with the following dynamic programming: let $dp_{i,j}$ be the number of ways to choose the first $i$ characters of the string so that the last character different from $s_i$ was $s_j$ (or $j = 0$ if there was no such character), and all the constraints on the substrings ending no later than position $i$ are satisfied. The transitions are simple: you either place the same character as the last one (going from $dp_{i,j}$ to $dp_{i+1,j}$), or a different character (going from $dp_{i,j}$ to $dp_{i+1,i}$); and when you place a character, you check all the constraints on the substrings ending with the $i$-th position. Note that the state $dp_{1,0}$ is actually represented by two strings: 0 and 1. This solution works in $O(n^3)$, although $O(n^4)$ or $O(n^2)$ implementations are also possible.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nconst int N = 143;\nint n;\n\nint a[N][N];\nint dp[N][N];\n\nbool check(int cnt, int last)\n{\n    for(int i = 0; i < cnt; i++)\n    {\n        if(a[i][cnt - 1] == 0) continue;\n        if(a[i][cnt - 1] == 1 && last > i) return false;\n        if(a[i][cnt - 1] == 2 && last <= i) return false;\n    }\n    return true;\n}\n\nint main()\n{\n    cin >> n;\n    for(int i = 0; i < n; i++)\n    {\n        for(int j = i; j < n; j++)\n            cin >> a[i][j];\n    }\n    if(a[0][0] != 2) dp[1][0] = 2;\n    for(int i = 1; i < n; i++)\n        for(int j = 0; j < i; j++)\n            for(int k : vector<int>({j, i}))\n                if(check(i + 1, k))\n                    dp[i + 1][k] = add(dp[i + 1][k], dp[i][j]);\n    int ans = 0;\n    for(int i = 0; i < n; i++)\n        ans = add(ans, dp[n][i]);\n    cout << ans << endl;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1767",
    "index": "D",
    "title": "Playoff",
    "statement": "$2^n$ teams participate in a playoff tournament. The tournament consists of $2^n - 1$ games. They are held as follows: in the first phase of the tournament, the teams are split into pairs: team $1$ plays against team $2$, team $3$ plays against team $4$, and so on (so, $2^{n-1}$ games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only $2^{n-1}$ teams remain. If only one team remains, it is declared the champion; otherwise, the second phase begins, where $2^{n-2}$ games are played: in the first one of them, the winner of the game \"$1$ vs $2$\" plays against the winner of the game \"$3$ vs $4$\", then the winner of the game \"$5$ vs $6$\" plays against the winner of the game \"$7$ vs $8$\", and so on. This process repeats until only one team remains.\n\nThe skill level of the $i$-th team is $p_i$, where $p$ is a permutation of integers $1$, $2$, ..., $2^n$ (a permutation is an array where each element from $1$ to $2^n$ occurs exactly once).\n\nYou are given a string $s$ which consists of $n$ characters. These characters denote the results of games in each phase of the tournament as follows:\n\n- if $s_i$ is equal to 0, then during the $i$-th phase (the phase with $2^{n-i}$ games), in each match, the team with the lower skill level wins;\n- if $s_i$ is equal to 1, then during the $i$-th phase (the phase with $2^{n-i}$ games), in each match, the team with the higher skill level wins.\n\nLet's say that an integer $x$ is \\textbf{winning} if it is possible to find a permutation $p$ such that the team with skill $x$ wins the tournament. Find all winning integers.",
    "tutorial": "Firstly, let's prove that the order of characters in $s$ is interchangeable. Suppose we have a tournament of four teams with skills $a$, $b$, $c$ and $d$ such that $a < b < c < d$; and this tournament has the form $01$ or $10$. It's easy to see that $a$ and $d$ cannot be winners, since $a$ will be eliminated in the round with type $1$, and $d$ will be eliminated in the round with type $0$. However, it's easy to show that both with $s = 10$ and with $s = 01$, $b$ and $c$ can be winners. Using this argument to matches that go during phases $i$ and $i+1$ (a group of two matches during phase $i$ and a match during phase $i + 1$ between the winners of those matches can be considered a tournament with $n = 2$), we can show that swapping $s_i$ and $s_{i+1}$ does not affect the possible winners of the tournament. So, suppose all phases of type $1$ happen before phases of type $0$, there are $x$ phases of type $1$ and $y$ phases of type $0$ ($x + y = n$). $2^{x+y} - 2^y$ teams will be eliminated in the first part (phases of type $1$), and the team with the lowest skill that wasn't eliminated in the first half will win the second half. It's easy to see that the teams with skills $[1..2^x-1]$ cannot pass through the first part of the tournament, since to pass the first part, a team has to be the strongest in its \"subtree\" of size $2^x$. Furthermore, since the minimum of $2^y$ teams passing through the first half wins, the winner should have skill not greater than $2^{x+y}-2^y+1$ - the winner should have lower skill than at least $2^y - 1$ teams, so teams with skills higher than $2^{x+y}-2^y+1$ cannot win. Okay, now all possible winners belong to the segment $[2^x, 2^n - 2^y + 1]$. Let's show that any integer from this segment can be winning. Suppose $k \\in [2^x, 2^n - 2^y + 1]$, let's construct the tournament in such a way that only team with skill $k$ and $2^y-1$ teams with the highest skill pass through the first part of the tournament (obviously, then team $k$ wins). There are $2^y$ independent tournaments of size $2^x$ in the first part; let's assign teams with skills from $1$ to $2^x-1$, and also the team $k$ to one of those tournaments; for all other $2^y-1$ tournaments, let's assign the teams in such a way that exactly one team from the $2^y-1$ highest ones competes in each of them. It's easy to see that the team $k$ will win its tournament, and every team from the $2^y-1$ highest ones will win its tournament as well, so the second half will contain only teams with skills $k$ and $[2^n-2^y+2..2^n]$ (and, obviously, $k$ will be the winner of this tournament). So, the answer to the problem is the segment of integers $[2^x, 2^n - 2^y + 1]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int n;\n  string s;\n  cin >> n >> s;\n  int k = count(s.begin(), s.end(), '1');\n  for (int x = 1 << k; x <= (1 << n) - (1 << (n - k)) + 1; ++x)\n    cout << x << ' ';\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1767",
    "index": "E",
    "title": "Algebra Flash",
    "statement": "\\begin{quote}\nAlgebra Flash 2.2 has just been released!Changelog:\n\n- New gamemode!\n\nThank you for the continued support of the game!\n\\end{quote}\n\nHuh, is that it? Slightly disappointed, you boot up the game and click on the new gamemode. It says \"Colored platforms\".\n\nThere are $n$ platforms, numbered from $1$ to $n$, placed one after another. There are $m$ colors available in the game, numbered from $1$ to $m$. The $i$-th platform is colored $c_i$.\n\nYou start on the platform $1$ and want to reach platform $n$. In one move, you can jump from some platform $i$ to platforms $i + 1$ or $i + 2$.\n\nAll platforms are initially deactivated (including platforms $1$ and $n$). For each color $j$, you can pay $x_j$ coins to activate all platforms of that color.\n\nYou want to activate some platforms so that you could start on an activated platform $1$, jump through some activated platforms and reach an activated platform $n$.\n\nWhat's the smallest amount of coins you can spend to achieve that?",
    "tutorial": "Imagine we bought some subset of colors. How to check if there exists a path from $1$ to $n$? Well, we could write an easy dp. However, it's not immediately obvious where to proceed from that. You can't really implement buying colors inside the dp, because you should somehow know if you bought the current color before, and that's not really viable without storing a lot of information. Let's find another approach. Let's try to deduce when the subset is bad - the path doesn't exist. Trivial cases: $c_1$ or $c_n$ aren't bought. Now, if there are two consecutive platforms such that their colors aren't bought, the path doesn't exist. Otherwise, if there are no such platforms, you can show that the path always exists. In particular, that implies that among all pairs of consecutive platforms, at least one color of the pair have to be bought. If the colors of the pair are the same, then it's just that this color have to be bought. The next step is probably hard to get without prior experience. Notice how the condition is similar to a well-known graph problem called \"vertex cover\". That problem is about finding a set of vertices in an undirected graph such that all graph edges have at least one of their endpoints in the set. In particular, our problem would be to find a vertex cover of minimum cost. That problem is known to be NP-hard, thus the constraints. We can't solve it in polynomial time but we'll attempt to it faster than the naive approach in $O(2^m \\cdot m^2)$. Let's start with this approach anyway. We can iterate over a mask of taken vertices and check if that mask is ok. In order to do that, we iterate over edges and check if at least vertex is taken for each of them. Again, having a bit of prior experience, one could tell from the constraints that the intended solution involves meet-in-the-middle technique. Let's iterate over the mask of taken vertices among vertices from $1$ to $\\frac m 2$. Then over the mask of taken vertices from $\\frac m 2 + 1$ to $m$. The conditions on edges split them into three groups: the edges that are completely in $\\mathit{mask}_1$, the edges that are completely in $\\mathit{mask}_2$ and the edges that have one endpoint in $\\mathit{mask}_1$ and another endpoint in $\\mathit{mask}_2$. First two types are easy to check, but how to force the third type to be all good? Consider the vertices that are not taken into $\\mathit{mask}_1$. All edges that have them as one of the endpoints will turn out bad if we don't take their other endpoints into $\\mathit{mask}_2$. That gives us a minimal set of constraints for each $\\mathit{mask}_1$: a mask $\\mathit{con}$ that includes all vertices from the second half that have edges to at least one of non-taken vertex in $\\mathit{mask}_1$. Then $\\mathit{mask}_2$ is good if it has $\\mathit{con}$ as its submask. Thus, we would want to update the answer with the $\\mathit{mask}_1$ of the minimum cost such that its $\\mathit{con}$ is a submask of $\\mathit{mask}_2$. Finally, let $\\mathit{dp}[\\mathit{mask}]$ store the minimum cost of some $\\mathit{mask}_1$ such that its $\\mathit{con}$ is a submask of $\\mathit{mask}$. Initialize the $\\mathit{dp}$ with the exact $\\mathit{con}$ for each $\\mathit{mask}_1$. Then push the values of $\\mathit{dp}$ up by adding any new non-taken bit to each mask. When iterating over $\\mathit{mask}_2$, check if it's good for edges of the second kind and update the answer with $\\mathit{dp}[\\mathit{mask}_2]$. Overall complexity: $O(2^{m/2} \\cdot m^2)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n    int n, m;\n    scanf(\"%d%d\", &n, &m);\n    vector<int> c(n);\n    forn(i, n){\n        scanf(\"%d\", &c[i]);\n        --c[i];\n    }\n    vector<int> x(m);\n    forn(i, m) scanf(\"%d\", &x[i]);\n    \n    vector<long long> g(m);\n    forn(i, n - 1){\n        g[c[i]] |= 1ll << c[i + 1];\n        g[c[i + 1]] |= 1ll << c[i];\n    }\n    g[c[0]] |= 1ll << c[0];\n    g[c[n - 1]] |= 1ll << c[n - 1];\n    \n    int mid = m / 2;\n    vector<int> dp(1 << mid, 1e9);\n    forn(mask, 1 << (m - mid)){\n        long long chk = 0;\n        int tot = 0;\n        forn(i, m - mid){\n            if ((mask >> i) & 1)\n                tot += x[i + mid];\n            else\n                chk |= g[i + mid];\n        }\n        if (((chk >> mid) | mask) != mask)\n            continue;\n        chk &= (1ll << mid) - 1;\n        dp[chk] = min(dp[chk], tot);\n    }\n    forn(i, mid) forn(mask, 1 << mid) if (!((mask >> i) & 1)){\n        dp[mask | (1 << i)] = min(dp[mask | (1 << i)], dp[mask]);\n    }\n    int ans = 1e9;\n    forn(mask, 1 << mid){\n        long long chk = 0;\n        int tot = 0;\n        forn(i, mid){\n            if ((mask >> i) & 1)\n                tot += x[i];\n            else\n                chk |= g[i];\n        }\n        chk &= (1ll << mid) - 1;\n        if ((chk | mask) != mask)\n            continue;\n        ans = min(ans, dp[mask] + tot);\n    }\n    printf(\"%d\\n\", ans);\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "graphs",
      "math",
      "meet-in-the-middle",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1767",
    "index": "F",
    "title": "Two Subtrees",
    "statement": "You are given a rooted tree consisting of $n$ vertices. The vertex $1$ is the root. Each vertex has an integer written on it; this integer is $val_i$ for the vertex $i$.\n\nYou are given $q$ queries to the tree. The $i$-th query is represented by two vertices, $u_i$ and $v_i$. To answer the query, consider all vertices $w$ that lie in the subtree of $u_i$ or $v_i$ \\textbf{(if a vertex is in both subtrees, it is counted twice)}. For all vertices in these two subtrees, list all integers written on them, and find the integer with the maximum number of occurrences. If there are multiple integers with maximum number of occurrences, the \\textbf{minimum} among them is the answer.",
    "tutorial": "Original solution (by shnirelman) First, let's solve the following problem: we need to maintain a multiset of numbers and process queries of $3$-th types: add a number to the multiset, remove one occurrence of a number from the multiset (it is guaranteed that it exists), calculate the mode on this multiset. To do this, we will maintain the array $cnt_i$ - the frequency of $i$ in the multiset. Now the mode is the position of the leftmost maximum in this array. There are many ways to search for this position, we will use the following: we will build a sqrt-decomposition on the array $cnt$: for a block we will maintain a maximum on this block and an array $c_i$ - the number of positions $j$ in this block, such that $cnt_j = i$. Since in each of the initial requests $cnt_i$ changes by no more than $1$, the maximum in the block also changes by no more than 1 and, using the $c$ array, it is easy to update it after each query. Now, to find the mode (the position of the leftmost maximum in the $cnt$ array), you first need to go through all the blocks to find the value of the maximum and the leftmost block in which this maximum occurs, then iterate over the desired position in this block. Thus, queries to add and remove an element run in $O(1)$, and a mode search query runs in $O(\\sqrt{A})$, where $A$ is the number of possible distinct values, in a given problem $A = 2 \\cdot 10 ^ 5$. Now let's get back to the problem itself. Let's build a Preorder traversal of our tree. Let $tin_v$ be the position in the $0$-indexing of the vertex $v$ in the Preorder traversal, $tout_v$ be the size of the Preorder traversal after leaving the vertex $v$. Then the half-interval $[tin_v, tout_v)$ of the Preorder traversal represents the set of vertices of the subtree of the vertex $v$. For the $i$-th query, we will consider $tin_{v_i} \\le tin_{u_i}$. Let $sz_v = tout_v - tin_v$ be the size of the subtree of $v$, $B$ be some integer, then $v$ will be called light if $sz_v < B$, and heavy otherwise. A query $i$ is called light (heavy) if $v_i$ is a light (heavy) vertex. We will solve the problem for light and heavy queries independently. Light queries. Let's use the small-to-large technique and maintain the multiset described at the beginning of the solution. Let at the moment we have this multiset for the vertex $w$. Let's answer all light queries for which $u_i = w$. To do this, take all the vertices from the subtree of $v_i$ and add the numbers written on them, calculate the mode on the current multiset - this will be the answer to the query, and then delete the newly added vertices. In the standard implementation of small-to-large, you need to maintain several structures at the same time, which in this case is impossible due to the fact that each of them takes up $O(A\\sqrt{A})$ of memory. This problem can be avoided, for example, as follows: before constructing the Preorder traversal for each vertex $v$, put its heaviest son at the head of the adjacency list. Then it will be possible to iterate over the vertices in the order of the Preorder traversal, preserving the asymptotics. This part of the solution runs in $O(n\\log{n} + qB + q\\sqrt{A})$. Heavy queries. Let's divide all heavy vertices into non-intersecting vertical paths, so that two vertices from the same path have subtrees that differ by no more than $B$ vertices, and the number of the paths themselves is $O(\\frac{n}{B})$. To do this, let's take the deepest of the unused heavy vertices and build one of the desired paths, going up to the parent, while the first of these conditions is met. Then we mark all the vertices in this path as used, and start over. We will continue to do this while there are still unused heavy vertices. It is easy to see that the resulting paths are vertical and the subtrees of two vertices from the same path differ by no more than $B$ by construction. Let's prove that there are not very many of these paths. To do this, we will understand in which cases the path breaks: If the current path contains a root, then since the root has no parent, the path will terminate. Obviously, this path is only $1$. If the parent of the last vertex of the path has only one heavy child (this last vertex itself). From the construction, a break means that the number of vertices in this path plus the number of children outside the heaviest son subtree of the parent of the last vertex and each vertex of the path, except for the initial one, is more than $B$ in total, but each of the counted vertices can be counted in only one of such cases, that is, the number of paths that terminate in this way does not exceed $\\frac{n}{B}$. If the parent of the last node has more than one heavy child. Let's leave only heavy vertices in the tree (since the parent of a heavy vertex is a heavy vertex too, it will indeed be a tree (or an empty graph)). This tree contains at most $\\frac{n}{B}$ leafs. Calculating the total degree of the vertices of this tree, we can see that there are at most $\\frac{n}{B}$ additional sons (all sons of a vertex except one). This means that the number of paths terminating in this way is at most $\\frac{n}{B}$. Let's divide the heavy queries according to the paths where the $v_i$ is situated. We will answer queries with vertices $v$ from the same path together. We will do it similarly to the case with light queries, with minor differences: at the very beginning, we add to the multiset all the vertices of the subtree of the initial vertex of the path and mentally remove these vertices from the subtrees of $v_i$ vertices. Everything else is preserved. Let's calculate how long it takes: add all vertices from one subtree: $O(n)$, small-to-large: $O(n\\log{n})$, to answer one query due to condition on vertices from one path we have to add at most $B$ vertices. Since there are only $O(\\frac{n}{B})$ paths, the whole solution will take $O(\\frac{n^2\\log{n}}{B} + qB + q\\sqrt{A })$. We take $B = \\sqrt{\\frac{n^2\\log{n}}{q}}$ and, counting $n \\approx q$, we get $B = \\sqrt{n\\log{n}}$ and total running time $O(n\\sqrt{n\\log{n}} + n\\sqrt{A})$. Implementation details. As already mentioned, a subtree corresponds to a segment of the Preorder traversal, so $2$ subtrees are $2$ segments. We will maintain the data structure described at the beginning on the sum of $2$ segments. By moving the boundaries of these segments, you can move from one query to another, as in Mo's algorithm. It remains only to sort the queries. Heavy queries are sorted first by path number of $v_i$, then by $tin_{u_i}$. Light queries are sorted only by $tin_{u_i}$, but here you can't just move the segment of the $v$ subtree, you need to rebuild it for each query. Bonus. Solve this problem for two subtrees and a path connecting the roots of these subtrees. Alternative solution (by BledDest) This solution partially intersects with the one described by the problem author. We will use the same data structure for maintaining the mode; and we will also use DFS order of the tree (but before constructing it, we will reorder the children of each vertex so that the heaviest child is the first one). Let $tin_v$ be the moment we enter the vertex $v$ in DFS, and $tout_v$ be the moment we leave the vertex. As usual, the segment $[tin_v, tout_v]$ represents the subtree of vertex $v$, and we can change the state of the structure from the subtree of the vertex $x$ to the subtree of the vertex $y$ in $|tin_x - tin_y| + |tout_x + tout_y|$ operations. Let this number of operations be $cost(x,y)$. Let $v_1, v_2, \\dots, v_n$ be the DFS order of the tree. We can prove that $cost(v_1, v_2) + cost(v_2, v_3) + \\dots + cost(v_{n-1}, v_n)$ is estimated as $O(n \\log n)$ if we order the children of each vertex in such a way that the first of them is the heaviest one. Proof. Let's analyze how many times some vertex $v$ is added when we go in DFS order and maintain the current set of vertices. When some vertex is added to the current subtree, this means that the previous vertex in DFS order was not an ancestor of the current vertex, so the current vertex is not the first son of its parent. So, the size of the subtree of the parent is at least 2x the size of the current vertex. Since the path from $v$ to root can have at most $O(\\log n)$ such vertices, then the vertex $v$ is added at most $O(\\log n)$ times. Okay, how do we use it to process queries efficiently? Let's say that the vertex $v_i$ (the $i$-th vertex in DFS order) has coordinate equal to $cost(v_1, v_2) + cost(v_2, v_3) + \\dots + cost(v_{i-1}, v_i)$. Let this coordinate be $c_{v_i}$. Then, if we have the data structure for the query $(x_1, y_1)$ and we want to change it so it meets the query $(x_2, y_2)$, we can do it in at most $|c_{x_1} - c_{x_2}| + |c_{y_1} - c_{y_2}|$ operations, which can be treated as the Manhattan distance between points $(c_{x_1}, c_{y_1})$ and $(c_{x_2}, c_{y_2})$. Do you see where this is going? We can map each query $(x, y)$ to the point $(c_x, c_y)$, and then order them in such a way that the total distance we need to travel between them is not too large. We can use Mo's algorithm to do this. Since the coordinates are up to $O(n \\log n)$, but there are only $q$ points, some alternative sorting orders for Mo (like the one that uses Hilbert's curve) may work better than the usual one.",
    "code": "#include <bits/stdc++.h>\n\n#define f first\n#define s second\n\nusing namespace std;\nusing li = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\n\nconst int INF = 2e9 + 13;\nconst li INF64 = 2e18 + 13;\nconst int M = 998244353;\nconst int A = 2e5 + 13;\n\nconst int N = 2e5 + 13;\nconst int B = 2000;\nconst int SQRTA = 500;\nconst int K = N / B + 113;\n\nint val[N];\nvector<int> g[N];\nint sz[N];\nint gr[N];\nint leaf[N], group_root[N];\nint par[N];\nbool heavy[N];\n\nint tin[N], tout[N], T = 0, mid[N];\nint et[N];\nint valet[N];\n\n\nvoid dfs1(int v, int pr, int depth) {\n    par[v] = pr;\n    sz[v] = 1;\n\n    int mx = -1;\n    for(int i = 0; i < g[v].size(); i++) {\n        int u = g[v][i];\n        if(u != pr) {\n            dfs1(u, v, depth + 1);\n            sz[v] += sz[u];\n            if(mx == -1 || sz[g[v][mx]] < sz[u])\n                mx = i;\n        }\n    }\n\n    if(mx != -1)\n        swap(g[v][mx], g[v][0]);\n}\n\nvoid dfs2(int v) {\n    et[T] = v;\n    tin[v] = T++;\n\n    for(int u : g[v]) {\n        if(u != par[v])\n            dfs2(u);\n    }\n\n    tout[v] = T;\n}\n\nstruct Query {\n    int ind;\n    int v, u;\n    int lv, rv, lu, ru;\n    int b;\n\n    Query() {};\n};\n\nbool cmp(const Query& a, const Query& b) {\n    if(a.b != b.b)\n        return a.b < b.b;\n    else\n        return a.lu < b.lu;\n}\n\nint cnt[A];\nint block_index[A];\nint block_mx[A];\nint block_cnt_of_cnt[A / SQRTA + 13][A];\n\ninline void insert(int i) {\n    block_cnt_of_cnt[block_index[valet[i]]][cnt[valet[i]]]--;\n    cnt[valet[i]]++;\n    block_cnt_of_cnt[block_index[valet[i]]][cnt[valet[i]]]++;\n    if(cnt[valet[i]] > block_mx[block_index[valet[i]]])\n        block_mx[block_index[valet[i]]]++;\n}\n\ninline void erase(int i) {\n    if(cnt[valet[i]] == block_mx[block_index[valet[i]]] && block_cnt_of_cnt[block_index[valet[i]]][cnt[valet[i]]] == 1)\n        block_mx[block_index[valet[i]]]--;\n    block_cnt_of_cnt[block_index[valet[i]]][cnt[valet[i]]]--;\n    cnt[valet[i]]--;\n    block_cnt_of_cnt[block_index[valet[i]]][cnt[valet[i]]]++;\n}\n\nint get_mode() {\n    int mx = 0;\n    for(int i = 0; i < A / SQRTA + 1; i++)\n        mx = max(mx, block_mx[i]);\n    for(int i = 0; ; i++) {\n        if(block_mx[i] == mx) {\n            for(int j = i * SQRTA; ; j++) {\n                if(cnt[j] == mx)\n                    return j;\n            }\n        }\n    }\n}\n\nQuery queries[N];\nint ans[N];\n\nvoid solve() {\n    int n;\n    cin >> n;\n\n    for(int i = 0; i < n; i++)\n        cin >> val[i];\n\n    for(int i = 1; i < n; i++) {\n        int v, u;\n        cin >> v >> u;\n\n        v--;\n        u--;\n\n        g[v].push_back(u);\n        g[u].push_back(v);\n    }\n\n    dfs1(0, -1, 0);\n\n    vector<pii> ord(n);\n    for(int i = 0; i < n; i++) {\n        ord[i] = {sz[i], i};\n        gr[i] = -1;\n    }\n\n    sort(ord.begin(), ord.end());\n\n    for(int i = 0; i < n; i++) {\n        if(sz[i] >= B)\n            heavy[i] = true;\n    }\n\n    int cur = 0;\n    for(int i = 0; i < n; i++) {\n        int v = ord[i].s;\n        if(sz[v] < B || gr[v] != -1)\n            continue;\n\n        leaf[cur] = v;\n\n        int u = v;\n        while(gr[u] == -1 && sz[u] - sz[v] < B) {\n            gr[u] = cur;\n            group_root[cur] = u;\n            u = par[u];\n        }\n\n        cur++;\n    }\n\n    dfs2(0);\n\n    for(int i = 0; i < n; i++) {\n        if(sz[i] < B) {\n            gr[i] = cur + tin[i] / B;\n        }\n    }\n\n    for(int i = 0; i < n; i++)\n        valet[i] = val[et[i]];\n\n    for(int i = 0; i < A; i++) {\n        block_index[i] = i / SQRTA;\n    }\n\n    int q;\n    cin >> q;\n\n    for(int i = 0; i < q; i++) {\n        queries[i].ind = i;\n        cin >> queries[i].v >> queries[i].u;\n\n        queries[i].v--;\n        queries[i].u--;\n\n        queries[i].lv = tin[queries[i].v];\n        queries[i].rv = tout[queries[i].v];\n        queries[i].lu = tin[queries[i].u];\n        queries[i].ru = tout[queries[i].u];\n\n        if(queries[i].lv > queries[i].lu) {\n            swap(queries[i].v, queries[i].u);\n            swap(queries[i].lv, queries[i].lu);\n            swap(queries[i].rv, queries[i].ru);\n        }\n\n        queries[i].b = gr[queries[i].v];\n    }\n\n    sort(queries, queries + q, cmp);\n\n    int lv = 0, rv = 0, lu = 0, ru = 0;\n    li fir = 0, sec = 0;\n\n    int hs = 0;\n    for(int i = 0; i < q; i++) {\n        int qlv = queries[i].lv;\n        int qrv = queries[i].rv;\n        int qlu = queries[i].lu;\n        int qru = queries[i].ru;\n\n        fir += abs(lv - qlv) + abs(rv - qrv);\n        sec += abs(lu - qlu) + abs(ru - qru);\n\n        if(queries[i].b < cur) {\n            while(rv < qrv)\n                insert(rv++);\n            while(lv > qlv)\n                insert(--lv);\n            while(rv > qrv)\n                erase(--rv);\n            while(lv < qlv)\n                erase(lv++);\n        } else {\n            while(rv > lv)\n                erase(--rv);\n            lv = qlv;\n            rv = lv;\n            while(rv < qrv)\n                insert(rv++);\n        }\n\n        while(ru < qru)\n                insert(ru++);\n            while(lu > qlu)\n                insert(--lu);\n            while(ru > qru)\n                erase(--ru);\n            while(lu < qlu)\n                erase(lu++);\n\n        ans[queries[i].ind] = get_mode();\n    }\n\n    for(int i = 0; i < q; i++)\n        cout << ans[i] << endl;\n}\n\nmt19937 rnd(1);\n\nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n//    freopen(\"input.txt\", \"r\", stdin);\n\n    solve();\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1768",
    "index": "A",
    "title": "Greatest Convex",
    "statement": "You are given an integer $k$. Find the largest integer $x$, where $1 \\le x < k$, such that $x! + (x - 1)!^\\dagger$ is a multiple of $^\\ddagger$ $k$, or determine that no such $x$ exists.\n\n$^\\dagger$ $y!$ denotes the factorial of $y$, which is defined recursively as $y! = y \\cdot (y-1)!$ for $y \\geq 1$ with the base case of $0! = 1$. For example, $5! = 5 \\cdot 4 \\cdot 3 \\cdot 2 \\cdot 1 \\cdot 0! = 120$.\n\n$^\\ddagger$ If $a$ and $b$ are integers, then $a$ is a multiple of $b$ if there exists an integer $c$ such that $a = b \\cdot c$. For example, $10$ is a multiple of $5$ but $9$ is not a multiple of $6$.",
    "tutorial": "Is $x = k - 1$ always suitable? The answer is yes, as $x! + (x - 1)! = (x - 1)! \\times (x + 1) = ((k - 1) - 1)! \\times ((k - 1) + 1) = (k - 2)! \\times (k)$, which is clearly a multiple of $k$. Therefore, $x = k - 1$ is the answer. Time complexity: $\\mathcal{O}(1)$",
    "code": "answer = [print(int(input()) - 1) for testcase in range(int(input()))]",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1768",
    "index": "B",
    "title": "Quick Sort",
    "statement": "You are given a permutation$^\\dagger$ $p$ of length $n$ and a positive integer $k \\le n$.\n\nIn one operation, you:\n\n- Choose $k$ \\textbf{distinct} elements $p_{i_1}, p_{i_2}, \\ldots, p_{i_k}$.\n- Remove them and then add them sorted in increasing order to the end of the permutation.\n\nFor example, if $p = [2,5,1,3,4]$ and $k = 2$ and you choose $5$ and $3$ as the elements for the operation, then $[2, \\textcolor{red}{5}, 1, \\textcolor{red}{3}, 4] \\rightarrow [2, 1, 4, \\textcolor{red}{3},\\textcolor{red}{5}]$.\n\nFind the minimum number of operations needed to sort the permutation in increasing order. It can be proven that it is always possible to do so.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Suppose we can make operations so that $x$ elements do not participate in any operation. Then these $x$ elements in the final array will end up at the beginning in the order in which they were in the initial array. And since this $x$ must be maximized to minimize the number of operations, we need to find the maximal subsequence of the numbers $[1, 2, \\ldots]$. Let this sequence have $w$ numbers, then the answer is $\\lceil\\frac{n - w}{k}\\rceil=\\lfloor \\frac{n - w + k - 1}{k} \\rfloor$.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    vector<int> p(n);\n    for (int i = 0; i < n; i++) cin >> p[i];\n    \n    int c_v = 1;\n    for (int i = 0; i < n; i++) {\n        if (p[i] == c_v) c_v++;\n    }\n    \n    cout << (n  - c_v + k) / k  << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tint T;\n\tcin >> T;\n\twhile (T--) solve();\n}\n",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1768",
    "index": "C",
    "title": "Elemental Decompress",
    "statement": "You are given an array $a$ of $n$ integers.\n\nFind two permutations$^\\dagger$ $p$ and $q$ of length $n$ such that $\\max(p_i,q_i)=a_i$ for all $1 \\leq i \\leq n$ or report that such $p$ and $q$ do not exist.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Two cases produce no answers: One element appears more than twice in $a$. One element appears more than twice in $a$. After sorting, there is some index that $a[i] < i$ ($1$-indexed). After sorting, there is some index that $a[i] < i$ ($1$-indexed). Consider there is some index that $a[i] <i$, then both $p[i] < i$ and $q[i] < i$ must satisfy. This is also true for the first $i - 1$ index, so the numbers that are smaller than $i$ in both $p$ and $q$ are $(i - 1) \\times 2 + 2 = i * 2$. This is a contradiction. Otherwise, solutions always exist. One method is to constructively attach each element in $a$ to $p$ or $q$: Traverse from the biggest element to the smallest in $a$, if that number haven't appeared in $p$ then attach it to $p$, otherwise attach it to $q$. Traverse from the biggest element to the smallest in $a$, if that number haven't appeared in $p$ then attach it to $p$, otherwise attach it to $q$. Traverse from the biggest element to the smallest in $a$ again, if we attached it to $p$, find the biggest number that did not appear in $q$ and attach to $q$, vice versa. Traverse from the biggest element to the smallest in $a$ again, if we attached it to $p$, find the biggest number that did not appear in $q$ and attach to $q$, vice versa. A naive solution requires the $O(n^2)$ method to solve. We can reduce to $O(n \\log n)$ by sorting elements in $a$ as pairs <element, index>. Time complexity: $\\mathcal{O}(n \\log(n))$ There is actually a $O(n)$ solution to this problem. If there are at least $k > 3$ positions $i_1, i_2, \\ldots, i_k$ that $a[i_1] = a[i_2] = \\ldots = a[i_k]$ then there is no solution. Since we need the condition $a[i] = max(p[i], q[i])$, hence $p[i] = a[i]$ or/and $q[i] = a[i]$. If there are already $p[i_1] = a[i_1]$ and $q[i_2] = a[i_2]$ then we don't have another number equal to $a[i_k]$ because $p[]$ and $q[]$ are two permutations (each number must appear exactly once). Since we have the $max()$ function, we need to use the larger value firsts. If we iterate from the smallest value to the top, there will be scenarios where all the remaining positions $i$ will result in $max(p[i], q[i]) \\geq a[i]$ because you don't have enough smaller integers. So for each $x = n \\rightarrow 1$ (iterating from the largest element to the smallest element), we check for each position $i$ that $a_i = x$, then assign $p[i] := a[i]$ if $a[i]$ didn't appear in permutation $p[]$, otherwise assign $q[i] := a[i]$. We fill the remaining integers that wasn't used, from the largest to the smallest. We use $vp$ as the largest integer not used in permutation $p[1..n]$. We use $vq$ as the largest integer not used in permutation $q[1..n]$. Then for each of the value $x = n \\rightarrow 1$, we assign to $p[i], q[i]$ that was not used. Check if the permutation $p[]$ and $q[]$ satisfied the solution, if it didnt then output \"NO\", otherwise output \"YES\" and the two permutations: $p[1..n]$ and $q[1..n]$. Just iterate through each element as normal. There is also another way that you can skip testing if $max(p[i], q[i]) = a[i])$ is correct. But the proof is a bit harder to understand, so I prefer using this code instead. I reached $O(n \\log n)$ solution. 165 I reached $O(n)$ solution. 96",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint query()\n{\n    /// Input number of element\n    int n;\n    cin >> n;\n\n    /// Input the array a[1..n]\n    vector<int> a(n + 1);\n    for (int i = 1; i <= n; ++i)\n        cin >> a[i];\n\n    /// Storing position of each a[i]\n    vector<vector<int> > b(n + 1);\n    for (int i = 1; i <= n; ++i) {\n        b[a[i]].push_back(i);\n\n        /// max(p[i], q[i]) = a[i] so either p[i] = a[i] or/and q[i] = a[i]\n        /// so if the number appear the third time or more, then \"NO\"\n        if (b[a[i]].size() >= 3) {\n            cout << \"NO\\n\";\n            return 0;\n        }\n    }\n\n    /// Initialize permutation p[1..n], q[1..n]\n    vector<int> p(n + 1, -1), q(n + 1, -1);\n\n    /// Initialize permutation position, fp[p[i]] = i, fq[q[i]] = i\n    vector<int> fp(n + 1, -1), fq(n + 1, -1);\n    for (int x = n; x >= 1; --x) {\n        for (int i : b[x]) {\n            /// Because of max(), we must save up the larger value\n            /// So we assign p[i] or q[i] by x, one by one from x large -> small\n                 if (fp[x] == -1) p[fp[x] = i] = x;\n            else if (fq[x] == -1) q[fq[x] = i] = x;\n        }\n    }\n\n    for (int x = n, vp = n, vq = n; x >= 1; --x) {\n        for (int i : b[x]) {\n            /// Assign the remaining integers\n            while (fp[vp] != -1) --vp;\n            while (fq[vq] != -1) --vq;\n            if (p[i] == -1 && vp > 0) p[fp[vp] = i] = vp;\n            if (q[i] == -1 && vq > 0) q[fq[vq] = i] = vq;\n        }\n    }\n\n    for (int i = 1; i <= n; ++i) {\n        if (max(p[i], q[i]) != a[i]) {\n            /// Statement condition is not satisfied\n            cout << \"NO\\n\";\n            return 0;\n        }\n    }\n\n    /// Output the answer\n    cout << \"YES\\n\";\n    for (int i = 1; i <= n; ++i) cout << p[i] << \" \"; cout << \"\\n\";\n    for (int i = 1; i <= n; ++i) cout << q[i] << \" \"; cout << \"\\n\";\n    return 0;\n}\n\n\n\nsigned main()\n{\n    ios::sync_with_stdio(NULL);\n    cin.tie(NULL);\n\n\n\n    int q = 1; /// If there is no multiquery\n    cin >> q;  /// then comment this\n\n    while (q-->0)\n    {\n        /// For each query\n        query();\n\n\n    }\n\n\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1768",
    "index": "D",
    "title": "Lucky Permutation",
    "statement": "You are given a permutation$^\\dagger$ $p$ of length $n$.\n\nIn one operation, you can choose two indices $1 \\le i < j \\le n$ and swap $p_i$ with $p_j$.\n\nFind the minimum number of operations needed to have \\textbf{exactly one} inversion$^\\ddagger$ in the permutation.\n\n$^\\dagger$ A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^\\ddagger$ The number of inversions of a permutation $p$ is the number of pairs of indices $(i, j)$ such that $1 \\le i < j \\le n$ and $p_i > p_j$.",
    "tutorial": "For some fixed $n$, there are $n - 1$ permutations that have exactly $1$ inversion in them (the inversion is colored): $\\color{red}{2}, \\color{red}{1}, 3, 4, \\ldots, n - 1, n$ $1, \\color{red}{3}, \\color{red}{2}, 4, \\ldots, n - 1, n$ $1, 2, \\color{red}{4}, \\color{red}{3}, \\ldots, n - 1, n$... ... $1, 2, 3, 4, \\ldots, \\color{red}{n}, \\color{red}{n - 1}$ Let's build a directed graph with $n$ vertices where the $i$-th vertex has an outgoing edge $i \\rightarrow p_i$. It is easy to see that the graph is divided up into cycles of the form $i \\rightarrow p_i \\rightarrow p_{p_i} \\rightarrow p_{p_{p_i}} \\rightarrow \\ldots \\rightarrow i$. Let $cycles$ be the number of cycles in this graph. It is a well know fact that $n - cycles$ is the minimum number of swaps needed to get the permutation $1, 2, 3, \\ldots, n$ from our initial one (in other words, to sort it). Suppose we now want to get the $k$-th permutation from the list above. Let $x$ and $y$ be such that $p_x = k$ and $p_y = k + 1$. Let us remove the edges $x \\rightarrow k$ and $y \\rightarrow k + 1$ from the graph and instead add the edges $x \\rightarrow k + 1$ and $y \\rightarrow k$. Let $cycles'$ be the number of cycles in this new graph. The minimum number of swaps needed to get the $k$-th permutation in the list is equal to $n - cycles'$. Turns out that we can easily calculate $cycles'$ if we know $cycles$: $cycles' = cycles + 1$ if the vertices $k$ and $k + 1$ were in the same cycle in the initial graph, $cycles' = cycles - 1$ otherwise. To quickly check if two vertices $u$ and $v$ are in the same cycle, assign some id to each cycle (with a simple dfs or with a DSU) and the compare $u$-s cycle id with $v$-s cycle id. The answer is just the minimum possible value of $n - cycles'$ over all $1 \\le k \\le n - 1$. Time complexity: $\\mathcal{O}(n)$. PS: you can also find $cycles'$ with data structures (for example, by maintaining a treap for each cycle).",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> p(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> p[i]; p[i]--;\n\t}\n\t\n\tint ind = 1, ans = 0;\n\tvector<int> comp(n, 0);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (comp[i]) continue;\n\t\t{\n\t\t\tint v = i;\n\t\t\twhile (comp[v] == 0) {\n\t\t\t\tcomp[v] = ind;\n\t\t\t\tv = p[v];\n\t\t\t\tans++;\n\t\t\t}\n\t\t\t\n\t\t\tind++; ans--;\n\t\t}\n\t}\n\t\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tif (comp[i] == comp[i + 1]) {\n\t\t\tcout << ans - 1 << nl;\n\t\t\treturn;\n\t\t}\n\t}\n\tcout << ans + 1 << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tint T;\n\tcin >> T;\n\twhile (T--) solve();\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1768",
    "index": "E",
    "title": "Partial Sorting",
    "statement": "Consider a permutation$^\\dagger$ $p$ of length $3n$. Each time you can do one of the following operations:\n\n- Sort the first $2n$ elements in increasing order.\n- Sort the last $2n$ elements in increasing order.\n\nWe can show that every permutation can be made sorted in increasing order using only these operations. Let's call $f(p)$ the minimum number of these operations needed to make the permutation $p$ sorted in increasing order.\n\nGiven $n$, find the sum of $f(p)$ over all $(3n)!$ permutations $p$ of size $3n$.\n\nSince the answer could be very large, output it modulo a prime $M$.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "We need at most $3$ operations to sort the permutation: $1 -> 2 -> 1$ For $f(p) = 0$, there is only one case: the initially sorted permutation. return (38912738912739811 & 1) For $f(p) \\leq 1$, this scenario appears when the first $n$ numbers or the last $n$ numbers are in the right places. Both cases have $n$ fixed positions, so there will be $(2n!)$ permutations in each case. Intersection: since both cases share the $n$ middle elements, $(n!)$ permutation will appear in both cases. So there will be $2 \\times (2n!) - (n!)$ such permutations. For $f(p) \\leq 2$, this scenario appears when the smallest $n$ elements' positions are in range $[1, 2n]$, or the largest $n$ numbers' positions are in range $[n + 1, 3n]$. If the smallest $n$ elements are all in position from $1$ to $2n$, then: There are $C_{2n}^{n}$ ways to choose $n$ positions for these numbers. There are $C_{2n}^{n}$ ways to choose $n$ positions for these numbers. For each way to choose these positions, there are $n!$ ways to choose the position for the smallest $n$ numbers, and $2n!$ ways for the rest. For each way to choose these positions, there are $n!$ ways to choose the position for the smallest $n$ numbers, and $2n!$ ways for the rest. The total number of valid permuations are: $C_{2n}^{n} \\times n! \\times 2n!$ The total number of valid permuations are: $C_{2n}^{n} \\times n! \\times 2n!$ If the largest $n$ elements are all in position from $n + 1$ to $3n$, we do the same calculation. Intersection: intersection appears when the first $n$ numbers are all in range $[1, 2n]$ and the last $n$ numbers are all in range $[n + 1, 3n]$. Let intersection = 0 Let's talk about the numbers in range $[n + 1, 2n]$. There are $n$ such numbers. . Imagine there are EXACTLY $i = 0$ numbers in this range that appear in the first $n$ numbers. So: In the first $n$ numbers there are $n$ numbers in range $[1, n]$. There are $C_{n}^{n - 0} \\times n!$ cases. In the first $n$ numbers there are $n$ numbers in range $[1, n]$. There are $C_{n}^{n - 0} \\times n!$ cases. In the first $n$ numbers there are $0$ numbers in range $[n + 1, 2n]$. There are $C_{n}^{0} \\times n!$ cases. In the first $n$ numbers there are $0$ numbers in range $[n + 1, 2n]$. There are $C_{n}^{0} \\times n!$ cases. In the last $n$ numbers there are $n$ numbers in range $[n + 1, 3n]$, we have used $0$ numbers for the first n numbers. There are $C_{2n - 0}^{n} \\times n!$ cases. In the last $n$ numbers there are $n$ numbers in range $[n + 1, 3n]$, we have used $0$ numbers for the first n numbers. There are $C_{2n - 0}^{n} \\times n!$ cases. Then we have: intersection += $C_{n}^{n - 0} \\times C_{n}^{0} \\times C_{2n - 0}^{n} \\times n! \\times n! \\times n!$ After convert $0$ to $i$, we have intersection += $C_{n}^{n - i} \\times C_{n}^{i} \\times C_{2n - i}^{n} \\times n! \\times n! \\times n!$ How about there is EXACTLY $i = 1$ number in range $[n + 1, 2n]$ appearing in the first $n$ numbers? In the first $n$ numbers there are $n - 1$ numbers in range $[1, n]$. There are $C_{n}^{n - 1} \\times n!$ cases. In the first $n$ numbers there are $n - 1$ numbers in range $[1, n]$. There are $C_{n}^{n - 1} \\times n!$ cases. In the first $n$ numbers there are $1$ numbers in range $[n + 1, 2n]$. There are $C_{n}^{1} \\times n!$ cases. In the first $n$ numbers there are $1$ numbers in range $[n + 1, 2n]$. There are $C_{n}^{1} \\times n!$ cases. In the last $n$ numbers there are $n$ numbers in range $[n + 1, 3n]$, we have used $1$ numbers for the first $n$ numbers. There are $C_{2n - 1}^{n} \\times n!$ cases. In the last $n$ numbers there are $n$ numbers in range $[n + 1, 3n]$, we have used $1$ numbers for the first $n$ numbers. There are $C_{2n - 1}^{n} \\times n!$ cases. Then we have: intersection += $C_{n}^{n - 1} \\times C_{n}^{1} \\times C_{2n - 1}^{n} \\times n! \\times n! \\times n!$ After convert $1$ to $i$, we have intersection += $C_{n}^{n - i} \\times C_{n}^{i} \\times C_{2n - i}^{n} \\times n! \\times n! \\times n!$ We do the same thing with remaining cases, all the way up to $i = n$. The number of intersections will be equal to: $\\sum_{i = 0}^{n} C_{n}^{n - i} \\times C_{n}^{i} \\times C_{2n - i}^{n} \\times n! \\times n! \\times n!$ So, the answer will be $2 \\times C_{2n}^{n} \\times n! \\times 2n! - \\sum_{i = 0}^{n} C_{n}^{n - i} \\times C_{n}^{i} \\times C_{2n - i}^{n} \\times n! \\times n! \\times n!$ For $f(p) \\leq 3$, it will be the count of all valid permutations. return __factorial(n * __number_of_sides_of_a_triangle) Time complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long n, M;\n\nlong long frac[3000005], inv[3000005];\n\nlong long powermod(long long a, long long b, long long m)\n{\n\tif (b == 0) return 1;\n\tunsigned long long k = powermod(a, b / 2, m);\n\tk = k * k;\n\tk %= m;\n\tif (b & 1) k = (k * a) % m;\n\treturn k;\n}\n\nvoid Ready()\n{\n\tfrac[0] = 1;\n\tinv[0] = 1;\n\tfor (int i = 1; i <= 3000000; i++)\n\t{\n\t\tfrac[i] = (frac[i - 1] * i) % M;\n\t}\n\t\n\tinv[3000000] = powermod(frac[3000000], M - 2, M);\n\t\n\tfor (int i = 3000000; i > 0; i--)\n\t{\n\t\tinv[i - 1] = (inv[i] * i) % M;\n\t}\n}\n\nlong long C(long long n, long long k)\n{\n\treturn ((frac[n] * inv[k]) % M * inv[n - k]) % M;\n}\n\nint main()\n{\n\tcin >> n >> M;\n\tReady();\n\tlong long ans[4]{};\n\t\n\t// X = 0\n\t\n\tans[0] = 1;\n\t\n\t// X = 1\n\t\n\tans[1] = 2 * frac[2 * n] - frac[n] - ans[0] + M + M;\n\tans[1] %= M;\n\t\n\t// X = 2\n\t\n\tans[2] = frac[2 * n];\n\tans[2] = ans[2] * C(2 *n, n) % M;\n\tans[2] = ans[2] * frac[n] % M;\n\tans[2] = ans[2] * 2 % M;\n\t\n\tfor (int i = 0; i <= n; i++)\n\t{\n\t\tint sub = C(n, i);\n\t\tsub = sub * C(n, n - i) % M;\n\t\tsub = sub * C(2 * n - i, n) % M;\n\t\tsub = sub * frac[n] % M;\n\t\tsub = sub * frac[n] % M;\n\t\tsub = sub * frac[n] % M;\n\t\tans[2] = (ans[2] - sub + M) % M;\n\t}\n\tans[2] = (ans[2] - ans[1] + M) % M;\n\tans[2] = (ans[2] - ans[0] + M) % M;\n\t\n\t// X = 3\n\t\n\tans[3] = frac[3 * n];\n\tans[3] = (ans[3] - ans[2] + M) % M;\n\tans[3] = (ans[3] - ans[1] + M) % M;\n\tans[3] = (ans[3] - ans[0] + M) % M;\n\t\n\tlong long answer = ans[1] + 2 * ans[2] + 3 * ans[3];\n\tanswer %= M;\n\t\n\tcout << answer << endl;\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1768",
    "index": "F",
    "title": "Wonderful Jump",
    "statement": "You are given an array of positive integers $a_1,a_2,\\ldots,a_n$ of length $n$.\n\nIn one operation you can jump from index $i$ to index $j$ ($1 \\le i \\le j \\le n$) by paying $\\min(a_i, a_{i + 1}, \\ldots, a_j) \\cdot (j - i)^2$ eris.\n\nFor all $k$ from $1$ to $n$, find the minimum number of eris needed to get from index $1$ to index $k$.",
    "tutorial": "There is a very easy $\\mathcal{O}(n^2)$ dp solution, we will show one possible way to optimize it to $\\mathcal{O}(n \\cdot \\sqrt{A})$, where $A$ is the maximum possible value of $a_i$. Let $dp_k$ be the minimum number of eris required to reach index $k$, $dp_1 = 0$. Suppose we want to calculate $dp_j$ and we already know $dp_1, dp_2, \\ldots, dp_{j - 1}$. Let's look at our cost function more closely. We can notice that it is definitely not optimal to use the transition $i \\rightarrow j$ if $\\min(a_i \\ldots a_j) \\cdot (j - i)^2 > A \\cdot (j - i)$. That is, it will be more optimal to perform $j - i$ jumps of length 1. Transforming this inequality, we get $j - i > \\frac{A}{\\min(a_i \\ldots a_j)}$. So if $\\min(a_i \\ldots a_j)$ is quite large, we only need to look at a couple of $i$ close to $j$, and then do something else for the small values of $\\min(a_i \\ldots a_j)$. 1. $\\min(a_i \\ldots a_j) \\ge \\sqrt{A}$ To handle this case, we can just iterate over all $i$ from $\\max(j - \\sqrt{A}, 1)$ to $j - 1$, since the transition $i \\rightarrow j$ could be optimal only if $j - i \\le \\frac{A}{min(a_i \\ldots a_j)} \\le \\sqrt{A}$. Time complexity: $\\mathcal{O}(\\sqrt{A})$. 2. $\\min(a_i \\ldots a_j) < \\sqrt{A}$ Another useful fact is that if there exists an index $k$ such that $i < k < j$ and $a_k = \\min(a_i \\ldots a_j)$, the transition $i \\rightarrow j$ also cannot be optimal, since $i \\rightarrow k$ followed by $k \\rightarrow j$ will cost less. Proof: $\\min(a_i \\ldots a_j) \\cdot (j - i) ^ 2 > \\min(a_i \\ldots a_k) \\cdot (k - i) ^ 2 + \\min(a_k \\ldots a_j) \\cdot (j - k)^2$ $a_k \\cdot (j - i) ^ 2 > a_k \\cdot (k - i) ^ 2 + a_k \\cdot (j - k)^2$ $(j - i) ^ 2 > (k - i) ^ 2 + (j - k)^2$ This leaves us two subcases two handle. 2.1 $\\min(a_i \\ldots a_j) = a_i$ Just maintain the rightmost occurrences $< j$ of all values from $1$ to $\\sqrt{A}$. Time complexity: $\\mathcal{O}(\\sqrt{A})$. 2.2 $\\min(a_i \\ldots a_j) = a_j$ Initially set $i$ to $j - 1$ and decrease it until $a_i \\le a_j$ becomes true. Time complexity: $\\mathcal{O}(\\sqrt{A})$ amortized. Total time complexity: $\\mathcal{O}(n \\cdot \\sqrt{A})$",
    "code": "#include <iostream>\n#include <vector>\n#include <chrono>\n#include <random>\n#include <cassert>\n \nstd::mt19937 rng((int) std::chrono::steady_clock::now().time_since_epoch().count());\n \nint main() {\n    std::ios_base::sync_with_stdio(false); std::cin.tie(NULL);\n    int n;\n    std::cin >> n;\n    std::vector<int> a(n);\n    for(int i = 0; i < n; i++) {\n        std::cin >> a[i];\n    }\n    std::vector<long long> dp(n, 1e18);\n    dp[0] = 0;\n    for(int i = 0; i < n; i++) {\n        int dist = n / a[i] + 1;\n        // take from behind\n        for(int j = i-1; j >= 0 && i-j <= dist; j--) {\n            dp[i] = std::min(dp[i], dp[j] + (long long) a[i] * (i - j) * (i - j));\n            if(a[j] <= a[i]) break;\n        }\n        // propagate forward\n        for(int j = i+1; j < n && j-i <= dist; j++) {\n            dp[j] = std::min(dp[j], dp[i] + (long long) a[i] * (i - j) * (i - j));\n            if(a[j] <= a[i]) break;\n        }\n        std::cout << dp[i] << (i + 1 == n ? '\\n' : ' ');\n    }\n}\n",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1770",
    "index": "A",
    "title": "Koxia and Whiteboards",
    "statement": "Kiyora has $n$ whiteboards numbered from $1$ to $n$. Initially, the $i$-th whiteboard has the integer $a_i$ written on it.\n\nKoxia performs $m$ operations. The $j$-th operation is to choose one of the whiteboards and change the integer written on it to $b_j$.\n\nFind the maximum possible sum of integers written on the whiteboards after performing all $m$ operations.",
    "tutorial": "Exactly $n$ items out of of $a_1,\\ldots,a_n,b_1,\\ldots,b_m$ will remain on the whiteboard at the end. $b_m$ will always remain on the board at the end. Consider the case where $n=2$ and $m=2$. As we mentioned in hint 2, $b_2$ will always be written, but what about $b_1$? This problem can be solved naturally with a greedy algorithm - for $i = 1, 2, \\dots, m$, we use $b_i$ to replace the minimal value among the current $a_1, a_2, \\dots, a_n$. The time complexity is $O(nm)$ for each test case. Alternatively, we can first add $b_m$ to our final sum. For the remaining $(n+m-1)$ integers, we can freely pick $(n - 1)$ out of them and add it to our final sum. This is because if we want a certain $a_i$ to remain on the board at the end, we simply do not touch it in the process. If we want a certain $b_i$ to remain on the board at the end, then on the $i^{th}$ operation we replace some $a_j$ that we do not want at the end by $b_i$. Using an efficient sorting algorithm gives us a $O((n + m) \\log (n + m))$ solution, which is our intended solution.",
    "code": "#include <stdio.h>\n#include <bits/stdc++.h>\nusing namespace std;\n#define rep(i,n) for (int i = 0; i < (n); ++i)\n#define Inf32 1000000001\n#define Inf64 4000000000000000001\n\nint main(){\n\t\n\tint _t;\n\tcin>>_t;\n\t\n\trep(_,_t){\n\t\tint n,m;\n\t\tcin>>n>>m;\n\t\tvector<long long> a(n+m);\n\t\trep(i,n+m)scanf(\"%lld\",&a[i]);\n\t\t\n\t\tsort(a.begin(),a.end()-1);\n\t\treverse(a.begin(),a.end());\n\t\t\n\t\tlong long ans = 0;\n\t\trep(i,n)ans += a[i];\n\t\t\n\t\tcout<<ans<<endl;\n\t}\n\t\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1770",
    "index": "B",
    "title": "Koxia and Permutation",
    "statement": "Reve has two integers $n$ and $k$.\n\nLet $p$ be a permutation$^\\dagger$ of length $n$. Let $c$ be an array of length $n - k + 1$ such that $$c_i = \\max(p_i, \\dots, p_{i+k-1}) + \\min(p_i, \\dots, p_{i+k-1}).$$ Let the cost of the permutation $p$ be the maximum element of $c$.\n\nKoxia wants you to construct a permutation with the minimum possible cost.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "For $k = 1$, the cost is always $2n$ for any permutation. For $k \\geq 2$, the minimal cost is always $n + 1$. When $k = 1$ every permutation has the same cost. When $k \\geq 2$, the minimal cost will be at least $n+1$. This is because there will always be at least one segment containing the element $n$ in the permutation, contributing $n$ to the \"max\" part of the sum, and the \"min\" part will add at least $1$ to the sum. In fact, the cost $n+1$ is optimal. It can be achieved by ordering the numbers in the pattern $[n, 1, n - 1, 2, n - 2, 3, n - 3, 4, \\dots]$. The time complexity is $O(n)$ for each test case. Other careful constructions should also get Accepted.",
    "code": "#include <iostream>\n#define MULTI int _T; cin >> _T; while(_T--)\nusing namespace std;\ntypedef long long ll;\n \nint n, k;\n \nint main () {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\t\n\tMULTI {\n\t\tcin >> n >> k;\n\t\tint l = 1, r = n, _ = 1;\n\t\twhile (l <= r) cout << ((_ ^= 1) ? l++ : r--) << ' ';\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1770",
    "index": "C",
    "title": "Koxia and Number Theory",
    "statement": "Joi has an array $a$ of $n$ \\textbf{positive} integers. Koxia wants you to determine whether there exists a \\textbf{positive} integer $x > 0$ such that $\\gcd(a_i+x,a_j+x)=1$ for all $1 \\leq i < j \\leq n$.\n\nHere $\\gcd(y, z)$ denotes the greatest common divisor (GCD) of integers $y$ and $z$.",
    "tutorial": "If $a_i$ are not pairwise distinct we get a trivial NO. If all $a_i$ are pairwise distinct, can you construct an example with $n = 4$ that gives an answer NO? Perhaps you are thinking about properties such as parity? Try to generalize the idea. Consider every prime. Consider Chinese Remainder Theorem. How many primes should we check? Consider Pigeonhole Principle. First, we should check whether the integers in $a$ are pairwise distinct, as $a_i + x \\geq 2$ and $\\gcd(t,t)=t$, which leads to a trivial NO. Given an integer $x$, let's define $b_i := a_i + x$. The condition \"$\\gcd(b_i,b_j)=1$ for $1\\le i < j \\le n$\" is equivalent to \"every prime $p$ should divides at most one $b_i$\". Given a prime $p$, how should we verify whether for every $x > 0$, $p$ divides at least two elements in $b$? A small but guided sample is $a = [5, 6, 7, 8]$ with answer NO, because $\\gcd(6 + x, 8 + x) \\neq 1$ if $x \\equiv 0 \\pmod 2$, $\\gcd(5 + x, 7 + x) \\neq 1$ if $x \\equiv 1 \\pmod 2$. That is, if we consider $[5, 6, 7, 8]$ modulo $2$, we obtain the multiset ${1, 0, 1, 0}$. Both $0$ and $1$ appeared twice, so for any choice of $x$, exactly two integers in $b$ will be divided by $2$. This idea can be extended to larger primes. For a given prime $p$, let $cnt_j$ be the multiplicity of $j$ in the multiset $[ a_i \\text{ mod } p, a_2 \\text{ mod } p, \\dots, a_n \\text{ mod } p ]$. If $\\min(\\mathit{cnt}_0, \\mathit{cnt}_1, \\dots, \\mathit{cnt}_{p-1}) \\geq 2$, we output NO immediately. While there are many primes up to ${10}^{18}$, we only need to check for the primes up to $\\lfloor \\frac{n}{2} \\rfloor$. This is because $\\min(\\mathit{cnt}_0, \\mathit{cnt}_1, \\dots, \\mathit{cnt}_{p-1}) \\geq 2$ is impossible for greater primes according to Pigeonhole Principle. Since the number of primes up to $\\lfloor \\frac{n}{2} \\rfloor$ is at most $O\\left(\\frac{n}{\\log n} \\right)$, the problem can be solved in time $O\\left(\\frac{n^2}{\\log n} \\right)$. The reason that $\\min(\\mathit{cnt}) \\geq 2$ is essential because for a prime $p$, if $a_u \\equiv a_v \\pmod p$, then it's necessary to have $(x + a_u) \\not\\equiv 0 \\pmod p$, because $\\gcd(x + a_u, x + a_v)$ will be divided by $p$ otherwise. So actually, $\\mathit{cnt}_i \\geq 2$ means $x \\not\\equiv (p-i) \\pmod p$. If $\\min(\\mathit{cnt}) < 2$ holds for all primes, then we can list certain congruence equations and use Chinese Reminder Theorem to calculate a proper $x$; if there exists a prime that $\\min(\\mathit{cnt}) \\geq 2$, then any choose of $x$ leads to the situation that $p$ appears twice.",
    "code": "#include <iostream>\n#include <algorithm>\n#define MULTI int _T; cin >> _T; while(_T--)\nusing namespace std;\ntypedef long long ll;\n \nconst int N = 105;\nconst int INF = 0x3f3f3f3f;\ntemplate <typename T> bool chkmin (T &x, T y) {return y < x ? x = y, 1 : 0;}\ntemplate <typename T> bool chkmax (T &x, T y) {return y > x ? x = y, 1 : 0;}\n \nint n;\nll a[N];\n \nint cnt[N];\n \nint main () {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\t\n\tMULTI {\n\t\tcin >> n;\n\t\tfor (int i = 1;i <= n;++i) {\n\t\t\tcin >> a[i];\n\t\t}\n\t\t\n\t\tint isDistinct = 1;\n\t\tsort(a + 1, a + n + 1);\n\t\tfor (int i = 1;i <= n - 1;++i) {\n\t\t\tif (a[i] == a[i + 1]) isDistinct = 0;\n\t\t}\n\t\tif (isDistinct == 0) {\n\t\t\tcout << \"NO\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tint CRT_able = 1;\n\t\tfor (int mod = 2;mod <= n / 2;++mod) {\n\t\t\tfill(cnt, cnt + mod, 0);\n\t\t\tfor (int i = 1;i <= n;++i) {\n\t\t\t\tcnt[a[i] % mod]++;\n\t\t\t}\n\t\t\tif (*min_element(cnt, cnt + mod) >= 2) CRT_able = 0;\n\t\t}\n\t\tcout << (CRT_able ? \"YES\" : \"NO\") << endl;\n\t}\n}",
    "tags": [
      "brute force",
      "chinese remainder theorem",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1770",
    "index": "D",
    "title": "Koxia and Game",
    "statement": "Koxia and Mahiru are playing a game with three arrays $a$, $b$, and $c$ of length $n$. Each element of $a$, $b$ and $c$ is an integer between $1$ and $n$ inclusive.\n\nThe game consists of $n$ rounds. In the $i$-th round, they perform the following moves:\n\n- Let $S$ be the multiset $\\{a_i, b_i, c_i\\}$.\n- Koxia removes one element from the multiset $S$ by her choice.\n- Mahiru chooses one integer from the two remaining in the multiset $S$.\n\nLet $d_i$ be the integer Mahiru chose in the $i$-th round. If $d$ is a permutation$^\\dagger$, Koxia wins. Otherwise, Mahiru wins.\n\nCurrently, only the arrays $a$ and $b$ have been chosen. As an avid supporter of Koxia, you want to choose an array $c$ such that Koxia will win. Count the number of such $c$, modulo $998\\,244\\,353$.\n\nNote that Koxia and Mahiru both play optimally.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "If all of $a$, $b$ and $c$ are fixed, how to determine who will win? If $a$ and $b$ are fixed, design an algorithm to check if there is an array $c$ that makes Koxia wins. If you can't solve the problem in Hint 2, try to think about how it's related to graph theory. Try to discuss the structure of components in the graph to count up the number of $c$. Firstly, let's consider how an array $c$ could make Koxia wins. Lemma 1. In each round, Koxia should remove an element in $S$ to make the remaining $2$ elements in $S$ the same (i.e. Mahiru's choice determined nothing actually). In round $n$, if Koxia leaves two choices for Mahiru then Mahiru will be able to prevent $d$ from being a permutation. This means if Koxia wins, there is only one choice for $d_n$. Now $(d_1, d_2, \\dots, d_{n-1})$ have to be a permutation of a specific $n-1$ numbers. Apply the same argument on $d_{n-1}$ and so on, we can conclude that every $d_i$ only has one choice if Koxia wins. Lemma 2. Let $p$ be array of length $n$ where we can set $p_i$ to either $a_i$ or $b_i$. Koxia wins iff there exists a way to make $p$ a permutation. According to Lemma 1, if there is a way to make $p$ a permutation, we can just set $c_i = p_i$. Koxia can then force Mahiru to set $d_i = p_i$ every round and Koxia will win. If it is impossible to make $p$ a permutation, Mahiru can pick either $a_i$ or $b_i$ (at least one of them is available) every round. The resulting array $d$ is guaranteed to not be a permutation. First, we need an algorithm to determine if there is a way to make $p$ a permutation. We can transform this into a graph problem where $(a_i, b_i)$ are edges in a graph with $n$ vertices. Then there is a way to make $p$ a permutation iff there is a way to assign a direction for every edge such that every vertex has one edge leading into it. It is not hard to see that this is equivalent to the condition that for every connected component, the number of edges equals the number of vertices. We can verify this by a Disjoint-Set Union or a graph traversal in $O(n \\alpha(n))$ or $O(n)$ time complexity. To solve the counting problem, we consider the structure of the connected components one by one. A component with $|V| = |E|$ can be viewed as a tree with an additional edge. This additional edge can be categorized into two cases: The additional edge forms a cycle together with some of the other edges. There are $2$ choices for the cycle (clockwise and counterclockwise), and the choices of other edges are fixed then (point away from the cycle). The additional edge forms a self-loop. Then the value of $c_i$ determines nothing in this situation so it can be any integers in $[1, n]$, and the choices of all other edges are fixed. Therefore, if exists at least one $c$ to make Koxia wins, then the answer is $2^{\\textrm{cycle component cnt}} \\cdot n^{\\textrm{self-loop component cnt}}$. The time complexity is $O(n \\alpha(n))$ or $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 1e5 + 5;\nconst int P = 998244353;\n \nint n, a[N], b[N];\nvector <int> G[N];\nbool vis[N];\n \nint vertex, edge, self_loop;\nvoid dfs(int x) {\n\tif (vis[x]) return ;\n\tvis[x] = true;\n\tvertex++;\n\tfor (auto y : G[x]) {\n\t\tedge++;\n\t\tdfs(y);\n\t\tif (y == x) {\n\t\t\tself_loop++;\n\t\t}\n\t}\n}\n \nvoid solve() {\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; i++) scanf(\"%d\", &a[i]);\n\tfor (int i = 1; i <= n; i++) scanf(\"%d\", &b[i]);\n\t\n\tfor (int i = 1; i <= n; i++) G[i].clear();\n\t\n\tfor (int i = 1; i <= n; i++) {\n\t\tG[a[i]].push_back(b[i]);\n\t\tG[b[i]].push_back(a[i]);\n\t}\n\t\n\tint ans = 1;\n\t\n\tfor (int i = 1; i <= n; i++) vis[i] = false;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (vis[i]) continue ;\n\t\tvertex = 0;\n\t\tedge = 0;\n\t\tself_loop = 0;\n\t\tdfs(i);\n\t\tif (edge != 2 * vertex) {\n\t\t\tans = 0;\n\t\t} else if (self_loop) {\n\t\t\tans = 1ll * ans * n % P;\n\t\t} else {\n\t\t\tans = ans * 2 % P;\n\t\t}\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}\n \nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dsu",
      "flows",
      "games",
      "graph matchings",
      "graphs",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1770",
    "index": "E",
    "title": "Koxia and Tree",
    "statement": "Imi has an undirected tree with $n$ vertices where edges are numbered from $1$ to $n-1$. The $i$-th edge connects vertices $u_i$ and $v_i$. There are also $k$ butterflies on the tree. Initially, the $i$-th butterfly is on vertex $a_i$. All values of $a$ are pairwise distinct.\n\nKoxia plays a game as follows:\n\n- For $i = 1, 2, \\dots, n - 1$, Koxia set the direction of the $i$-th edge as $u_i \\rightarrow v_i$ or $v_i \\rightarrow u_i$ with equal probability.\n- For $i = 1, 2, \\dots, n - 1$, if a butterfly is on the initial vertex of $i$-th edge and there is no butterfly on the terminal vertex, then this butterfly flies to the terminal vertex. Note that operations are sequentially in order of $1, 2, \\dots, n - 1$ instead of simultaneously.\n- Koxia chooses two butterflies from the $k$ butterflies with equal probability from all possible $\\frac{k(k-1)}{2}$ ways to select two butterflies, then she takes the distance$^\\dagger$ between the two chosen vertices as her score.\n\nNow, Koxia wants you to find the expected value of her score, modulo $998\\,244\\,353^\\ddagger$.\n\n$^\\dagger$ The distance between two vertices on a tree is the number of edges on the (unique) simple path between them.\n\n$^\\ddagger$ Formally, let $M = 998\\,244\\,353$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Solve a classic problem - find the sum of pairwise distances of $k$ chosen nodes in a tree. If we add the move operations while the direction of edges are fixed, find the sum of pairwise distances of $k$ chosen nodes. If you can't solve the problem in Hint 2, consider why writers make each edge passed by butterflies for at most once. When the direction of edges become random, how maintaining $p_i$ as the possibility of \"node $i$ contains a butterfly\" help you to get the answer? At first sight, we usually think of a classic problem - find the sum of pairwise distances of $k$ chosen nodes in a tree. For any edge, if there are $x$ chosen nodes and $n - x$ chosen nodes respectively on each side of it, then there will be $x (n - x)$ pairs of nodes passing this edge. Without loss of generality, let's assign node $1$ as root, and define both $\\mathit{siz}_i$ as the number of chosen nodes in subtree $i$. By summing up $\\mathit{siz}_{\\mathit{son}} (n - \\mathit{siz}_{\\mathit{son}})$ for each edge $(\\mathit{fa}, \\mathit{son})$, we derive the answer, which equals to the expected value of the distance of two nodes (Uniformly randomly chosen from $k$ nodes) after dividing by $\\binom{k}{2}$. Let's turn to Hint 2 then - add the move operations while the direction of edges are fixed. Let's define $\\mathit{siz}^0_i$ and $\\mathit{siz}_i$ as the number of butterflies in subtree $i$, but before any move operation / in real time respectively. A very important observation is, although butterflies are moving, we can always claim $|\\mathit{siz}_{\\mathit{son}} - \\mathit{siz}^0_{\\mathit{son}}| \\leq 1$ because each edge is passed by butterflies for at most once. This property allows us to discuss different values of $\\mathit{siz}_{\\mathit{son}}$ to sum up the answer in constant time complexity, if you maintain butterflies' positions correctly. When we introduce random directions additionally, if we define $p_i$ as the possibility of \"node $i$ contains a butterfly\", then an equivalent statement of move operation from node $u$ to node $v$ will be, actually, set $p_u = p_v = \\frac{p_u+p_v}{2}$, which allows us to maintain $p$ in real time easily. Similarly, by discussing values of $\\mathit{siz}_{\\mathit{son}}$ (but with possibilities of each case instead of specified moves), we get the final answer. The total time complexity is $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\nusing namespace std;\ntypedef long long ll;\n \nconst int N = 3e5 + 5;\nconst int mod = 998244353;\nconst int inv2 = 499122177;\n \nll qpow (ll n, ll m) {\n\tll ret = 1;\n\twhile (m) {\n\t\tif (m & 1) ret = ret * n % mod;\n\t\tn = n * n % mod;\n\t\tm >>= 1;\n\t}\n\treturn ret;\n}\nll getinv (ll a) {\n\treturn qpow(a, mod - 2);\n}\n \nint n, k;\nint a[N];\nint u[N], v[N];\n \nvector <int> e[N];\nint fa[N];\nll p[N], sum[N];\nvoid dfs (int u, int f) {\n\tsum[u] = p[u];\n\tfor (int v : e[u]) if (v != f) {\n\t\tdfs(v, u);\n\t\tfa[v] = u;\n\t\tsum[u] += sum[v];\n\t}\n}\n \nint main () {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\t\n\tcin >> n >> k;\n\tfor (int i = 1;i <= k;++i) {\n\t\tcin >> a[i];\n\t\tp[a[i]] = 1;\n\t}\n\tfor (int i = 1;i <= n - 1;++i) {\n\t\tcin >> u[i] >> v[i];\n\t\te[u[i]].push_back(v[i]);\n\t\te[v[i]].push_back(u[i]);\n\t}\n\tdfs(1, -1);\n\t\n\tll ans = 0;\n\tfor (int i = 1;i <= n - 1;++i) {\n\t\tif (fa[u[i]] == v[i]) swap(u[i], v[i]);\n\t\tll puv = p[u[i]] * (1 - p[v[i]] + mod) % mod;\n\t\tll pvu = p[v[i]] * (1 - p[u[i]] + mod) % mod;\n\t\tll delta = 0;\n\t\tdelta -= puv * sum[v[i]] % mod * (k - sum[v[i]]) % mod;\n\t\tdelta -= pvu * sum[v[i]] % mod * (k - sum[v[i]]) % mod;\n\t\tdelta += puv * (sum[v[i]] + 1) % mod * (k - sum[v[i]] - 1) % mod;\n\t\tdelta += pvu * (sum[v[i]] - 1) % mod * (k - sum[v[i]] + 1) % mod;\n\t\tans = (ans + sum[v[i]] * (k - sum[v[i]]) + delta * inv2) % mod;\n\t\tans = (ans % mod + mod) % mod;\n\t\tp[u[i]] = p[v[i]] = 1ll * (p[u[i]] + p[v[i]]) * inv2 % mod;\n\t}\n\tcout << ans * getinv(1ll * k * (k - 1) / 2 % mod) % mod << endl;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "dsu",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1770",
    "index": "F",
    "title": "Koxia and Sequence",
    "statement": "Mari has three integers $n$, $x$, and $y$.\n\nCall an array $a$ of $n$ \\textbf{non-negative} integers good if it satisfies the following conditions:\n\n- $a_1+a_2+\\ldots+a_n=x$, and\n- $a_1 \\, | \\, a_2 \\, | \\, \\ldots \\, | \\, a_n=y$, where $|$ denotes the bitwise OR operation.\n\nThe score of a good array is the value of $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n$, where $\\oplus$ denotes the bitwise XOR operation.\n\nKoxia wants you to find the total bitwise XOR of the scores of all good arrays. If there are no good arrays, output $0$ instead.",
    "tutorial": "From symmetry, for any non-negative integer $t$, the number of good sequences with $a_1=t$, the number of good sequences with $a_2=t$, ... are equal. It is useful to consider the contribution of each bit to the answer independently. Since XOR is undone twice, considering the contribution to the answer can be regarded as counting up over mod $2$. It is difficult to count those for which total or is $y$, but it is relatively easy to count those for which total or is a subset of $y$. Then, we can consider a way using the inclusion-exclusion principle. Lucas's theorem and Kummer's theorem are useful. In particular, you can derive equivalence conditions on or. \"There are $a+b$ white balls. For every pair $(c,d)$ of nonnegative integers satisfying $c+d=n$, find the sum of the ways to choose $c$ balls from the first $a$ balls and $d$ balls from the remaining $b$ balls.\" The answer to this problem is $_{a+b} C_{n}$. This is because considering how to choose for every pair $(c,d)$ of non-negative integers satisfying $c+d=n$ merely consider the case of choosing $n$ balls as how many balls to choose from $a$ balls and $b$ balls. This result is called Vandermonde's identity. Let $f(i,t)$ is the number of good sequence such that $a_i=t$. $f(1,t)=f(2,t)=...=f(n,t)$, so if $n$ is even, the answer is $0$. Otherwise, the answer is total xor of $t$ such that number of good sequences such that $a_1=t$ is odd. We can consider each bit independently, so we can rewrite the problem \"for each $i$, find the number of good sequences such that $a_1$'s $i$-th bit is $1$, modulo $2$\". Let $g(y')$ is the answer if $y$ is a subset of $y'$(means $y \\mid y'=y'$). We can prove with induction the answer of the original problem is total xor of $g(y')$ such that $y'$ is a subset of given $y$. So, the goal is for each $i$, find the number of $y'$ such that $y'$ is a subset of $y$ and $g(y')$'s $i$-th bit is $1$, modulo $2$. We can prove with Lucas's theorem or Kummer's theorem ($p=2$), \"$\\binom{a}{b} \\bmod 2$ is $1$\" is equivalent to \"$b$ is a subset of $a$\". The number of sequences such that the length is $n$ and total sum is $x$ and total or is a subset of $y$, modulo $2$ is equal to $\\sum_{t_1+\\ldots+t_n=x} \\prod{} \\binom{y}{t_i}$, because if there is $t_i$ which is not a subset of $y$, $\\binom{y}{t_i}$ is $0$ and the product is also $0$, modulo $2$. Consider Vandermonde's identity, the value is equal to $\\binom{ny}{x}$. In a similar way, we can rewrite the problem to \"for each $i$, find the number of $y'$ such that $y'$ is a subset of $y$ and $y'$'s $i$-th bit is $1$ and $x-2^i$ is a subset of $ny'-2^i$($\\binom{ny'-2^i}{x-2^i} \\bmod 2 = 1$), modulo $2$\". From the above, we can solve this problem in $O(y \\log y)$ by performing the calculation in $O(1)$ for all $i$ and all $y'$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n \n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n \n#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n \nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n \nint n,a,b;\n \nbool isSub(int i,int j){\n\tif (i<0 || j<0) return false;\n\treturn (j&i)==i;\n}\n \nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tcin>>n>>a>>b;\n\t\n\tint ans=0;\n\tfor (int sub=b;sub;sub=(sub-1)&b) rep(bit,0,20) if (sub&(1<<bit)){\n\t\tif (isSub(a-(1<<bit),n*sub-(1<<bit))){\n\t\t\tans^=(1<<bit);\n\t\t}\n\t}\n\t\n\tcout<<ans*(n%2)<<endl;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1770",
    "index": "G",
    "title": "Koxia and Bracket",
    "statement": "Chiyuu has a bracket sequence$^\\dagger$ $s$ of length $n$. Let $k$ be the minimum number of characters that Chiyuu has to remove from $s$ to make $s$ balanced$^\\ddagger$.\n\nNow, Koxia wants you to count the number of ways to remove $k$ characters from $s$ so that $s$ becomes balanced, modulo $998\\,244\\,353$.\n\nNote that two ways of removing characters are considered distinct if and only if the set of indices removed is different.\n\n$^\\dagger$ A bracket sequence is a string containing only the characters \"(\" and \")\".\n\n$^\\ddagger$ A bracket sequence is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), (()(())) and the empty string are balanced, while )(, ((), and (()))( are not.",
    "tutorial": "and errorgorn What special properties does the deleted bracket sequence have? Try to solve this with $O(n^2)$ DP. If there is no balance requirement, can multiple brackets be processed quickly with one operation? Can you combine the last idea with divide-and-conquer or something? Let us consider what properties the removed bracket subsequence has. First, it must be a bracket subsequence in the form ))...)((....(. The proof is simple: if there is a deleted ) on the right-hand side of a (, then we can keep them in $s$ without breaking the balancing property of the remaining sequence. This property means that we can divide the string into $2$ parts. We only delete ) from the first part and only delete ( from the second part. Now let us try to find the dividing point between the two parts: Consider a prefix sum based on a sequence of brackets in which each ( is replaced by 1 and each ) is replaced by -1. We define a position as a special position if and only if the number corresponding to this position is less than the previously occurring minimum value. It is easy to see that whenever a special position occurs, we must remove an additional ) before this position to make the bracket sequence satisfy the condition again. Considering the above idea, we can find that only the ) before the farthest special position may be deleted, so we can use this position as the dividing point. We now solve two separate problems. However, we can turn the problem on deleting only '(' into the one on deleting only ). For example, if we are only allowed to delete ( from (()((()()), it is equivalent to the number of ways to delete only ) from (()()))()). For the part where only ) is deleted, the sufficient condition for it to be a balanced bracket sequence is that each number in the prefix sum must be greater than 0 after the operation. Also considering the above ideas, let us define the state $dp_{i,j}$, which represents after removing the breakets required by special position, the number of ways to delete additional $j$ $(j \\geq 0)$ occurrence of ) from the string up the $i$-th occurrence of ) in the string. $\\begin{equation} dp_{i,j} = \\begin{cases} dp_{i-1,j}+dp_{i-1,j-1}, & \\text{if } i \\text{ is not special}; \\\\ dp_{i-1,j}+dp_{i-1,j+1}, & \\text{if } i \\text{ is special}. \\end{cases} \\end{equation}$ Multiply the $dp_{end,0}$ obtained from both parts of the string to obtain the answer. The time complexity is $O(n^2)$ and optimized implementations can run in about 9 seconds, but it is not enough to pass. Let's try to optimize the transitions when there are no special positions. For state $dp_{i,j}$, after processing $k$ individual ), the transitions are as follows: $dp_{i+k,j}=\\sum_{l=0}^k \\binom{k}{l} \\times dp_{i,j-l}$ We find that this transfer equation behaves as a polynomial convolution. Thus we can optimize this convolution by NTT with a time complexity of $O(n \\log n)$ for a single operation, while the worst global complexity of this Solution is $O(n^2 \\log n)$ due to the presence of the special position. Consider how this Solution can be combined with the $O(n^2)$ Solution. For states $dp_{i,j}$ where we want to consider its contribution to $dp_{i+k}$, if $j \\geq k$ is satisfied, then the transitions are not affected by the special position anyway. Based on the above idea, we can adopt a mixed Solution based on periodic reconstruction: set the reconstruction period $B$, and within one round of the period, we use the $O(n^2)$ DP Solution to handle the part of $j \\le B$, while for the part of $j>B$, we compute the answer by NTT after one round of the period. The time complexity $O(\\frac{n^2}{B}+B\\cdot n \\log n)$ can be optimized to $O(n\\sqrt{n \\log n})$ by setting the appropriate $B$. Although the time complexity is still high, given the low constant factor of the $O(n^2)$ solution, a decently-optimized implementation is able to get AC. Consider combining the idea of extracting $j \\geq k$ parts for NTT with divide-and-conquer. Suppose now that the interval to be processed is $(l,r)$, where the DP polynomial passed is $s$. We proceed as follows: Count the number of special positions $num$ in the interval $(l,r)$, extract the part of the polynomial $s$ corresponding to the state $j \\geq num$, and convolute it with the current interval alone. Pass the part of the polynomial $s$ corresponding to the state $j < num$ into the interval $(l,mid)$, and then pass the result into the interval $(mid+1,r)$ to continue the operation. Add the polynomials obtained by the above two steps directly, and return the obtained polynomial. How to calculate the time complexity of performing the above operations? Let's analyze the operations passed into the left interval and the right interval separately. When passing in the left interval $(l,mid)$, the size of the polynomial for the NTT operation is the number of special positions in the interval $(l,r)$ minus the number of special positions in the left interval $(l,mid)$, i.e., the number of special positions in the right interval $(mid+1,r)$, which does not exceed the length of the right interval $(mid+1,r)$. When passed into the right interval $(mid+1,r)$, the size of the polynomial does not exceed the length of the left interval $(l,mid)$. Also, the length of the combinatorial polynomial multiplied with $s$ is the interval length + 1. In summary, the size of the two polynomials for the NTT operation in the interval $(l,r)$ does not exceed the interval length + 1. Thus the time complexity of this solution is divide-and-conquer combined with the time complexity of NTT, i.e. $O(n \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/rope>\nusing namespace std;\nusing namespace __gnu_pbds;\nusing namespace __gnu_cxx;\n \n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n \n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n \n#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n \n#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>\n//change less to less_equal for non distinct pbds, but erase will bug\n \nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n \nconst int MOD=998244353;\n \nll qexp(ll b,ll p,int m){\n    ll res=1;\n    while (p){\n        if (p&1) res=(res*b)%m;\n        b=(b*b)%m;\n        p>>=1;\n    }\n    return res;\n}\n \nll inv(ll i){\n\treturn qexp(i,MOD-2,MOD);\n}\n \nll fix(ll i){\n\ti%=MOD;\n\tif (i<0) i+=MOD;\n\treturn i;\n}\n \nll fac[1000005];\nll ifac[1000005];\n \nll nCk(int i,int j){\n\tif (i<j) return 0;\n\treturn fac[i]*ifac[j]%MOD*ifac[i-j]%MOD;\n}\n \n//https://github.com/kth-competitive-programming/kactl/blob/main/content/numerical/NumberTheoreticTransform.h\nconst ll mod = (119 << 23) + 1, root = 62; // = 998244353\n// For p < 2^30 there is also e.g. 5 << 25, 7 << 26, 479 << 21\n// and 483 << 21 (same root). The last two are > 10^9.\ntypedef vector<int> vi;\ntypedef vector<ll> vl;\nvoid ntt(vl &a) {\n\tint n = sz(a), L = 31 - __builtin_clz(n);\n\tstatic vl rt(2, 1);\n\tfor (static int k = 2, s = 2; k < n; k *= 2, s++) {\n\t\trt.resize(n);\n\t\tll z[] = {1, qexp(root, mod >> s, mod)};\n\t\trep(i,k,2*k) rt[i] = rt[i / 2] * z[i & 1] % mod;\n\t}\n\tvi rev(n);\n\trep(i,0,n) rev[i] = (rev[i / 2] | (i & 1) << L) / 2;\n\trep(i,0,n) if (i < rev[i]) swap(a[i], a[rev[i]]);\n\tfor (int k = 1; k < n; k *= 2)\n\t\tfor (int i = 0; i < n; i += 2 * k) rep(j,0,k) {\n\t\t\tll z = rt[j + k] * a[i + j + k] % mod, &ai = a[i + j];\n\t\t\ta[i + j + k] = ai - z + (z > ai ? mod : 0);\n\t\t\tai += (ai + z >= mod ? z - mod : z);\n\t\t}\n}\nvl conv(const vl &a, const vl &b) {\n\tif (a.empty() || b.empty()) return {};\n\tint s = sz(a) + sz(b) - 1, B = 32 - __builtin_clz(s), n = 1 << B;\n\tint inv = qexp(n, mod - 2, mod);\n\tvl L(a), R(b), out(n);\n\tL.resize(n), R.resize(n);\n\tntt(L), ntt(R);\n\trep(i,0,n) out[-i & (n - 1)] = (ll)L[i] * R[i] % mod * inv % mod;\n\tntt(out);\n\treturn {out.begin(), out.begin() + s};\n}\n \nvector<int> v;\n \nvector<int> solve(int l,int r,vector<int> poly){\n\tif (poly.empty()) return poly;\n\t\n\tif (l==r){\n\t\tpoly=conv(poly,{1,1});\n\t\tpoly.erase(poly.begin(),poly.begin()+v[l]);\n\t\treturn poly;\n\t}\n\t\n\tint m=l+r>>1;\n\tint num=0;\n\trep(x,l,r+1) num+=v[x];\n\tnum=min(num,sz(poly));\n\t\n\tvector<int> small(poly.begin(),poly.begin()+num);\n\tpoly.erase(poly.begin(),poly.begin()+num);\n\t\n\tvector<int> mul;\n\trep(x,0,r-l+2) mul.pub(nCk(r-l+1,x));\n\tpoly=conv(poly,mul);\n\t\n\tsmall=solve(m+1,r,solve(l,m,small));\n\tpoly.resize(max(sz(poly),sz(small)));\n\trep(x,0,sz(small)) poly[x]=(poly[x]+small[x])%MOD;\n\t\n\treturn poly;\n}\n \nint solve(string s){\n\tif (s==\"\") return 1;\n\tv.clear();\n\t\n\tint mn=0,curr=0;\n\tfor (auto it:s){\n\t\tif (it=='(') curr++;\n\t\telse{\n\t\t\tcurr--;\n\t\t\tif (curr<mn){\n\t\t\t\tmn=curr;\n\t\t\t\tv.pub(1);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tv.pub(0);\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn solve(0,sz(v)-1,{1})[0];\n}\n \nint n;\nstring s;\nint pref[500005];\n \nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tfac[0]=1;\n\trep(x,1,1000005) fac[x]=fac[x-1]*x%MOD;\n\tifac[1000004]=inv(fac[1000004]);\n\trep(x,1000005,1) ifac[x-1]=ifac[x]*x%MOD;\n\t\n\tcin>>s;\n\tn=sz(s);\n\tpref[0]=0;\n\trep(x,0,n) pref[x+1]=pref[x]+(s[x]=='('?1:-1);\n\t\n\tint pos=min_element(pref,pref+n+1)-pref;\n\tstring a=s.substr(0,pos),b=s.substr(pos,n-pos);\n\treverse(all(b)); for (auto &it:b) it^=1;\n\tcout<<solve(a)*solve(b)%MOD<<endl;\n}",
    "tags": [
      "divide and conquer",
      "fft",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1770",
    "index": "H",
    "title": "Koxia, Mahiru and Winter Festival",
    "statement": "\\begin{quote}\nWow, what a big face!\n\\hfill {{\\small Kagura Mahiru}}\n\\end{quote}\n\nKoxia and Mahiru are enjoying the Winter Festival. The streets of the Winter Festival can be represented as a $n \\times n$ undirected grid graph. Formally, the set of vertices is $\\{(i,j) \\; | \\; 1 \\leq i,j\\leq n \\}$ and two vertices $(i_1,j_1)$ and $(i_2,j_2)$ are connected by an edge if and only if $|i_1-i_2|+|j_1-j_2|=1$.\n\n\\begin{center}\n{\\small A network with size $n = 3$.}\n\\end{center}\n\nKoxia and Mahiru are planning to visit The Winter Festival by traversing $2n$ routes. Although routes are not planned yet, the endpoints of the routes are already planned as follows:\n\n- In the $i$-th route, they want to start from vertex $(1, i)$ and end at vertex $(n, p_i)$, where $p$ is a permutation of length $n$.\n- In the $(i+n)$-th route, they want to start from vertex $(i, 1)$ and end at vertex $(q_i, n)$, where $q$ is a permutation of length $n$.\n\n\\begin{center}\n{\\small A network with size $n = 3$, points to be connected are shown in the same color for $p = [3, 2, 1]$ and $q = [3, 1, 2]$.}\n\\end{center}\n\nYour task is to find a routing scheme — $2n$ paths where each path connects the specified endpoints. Let's define the congestion of an edge as the number of times it is used (both directions combined) in the routing scheme. In order to ensure that Koxia and Mahiru won't get too bored because of traversing repeated edges, please find a routing scheme that \\textbf{minimizes the maximum congestion among all edges}.\n\n\\begin{center}\n{\\small An example solution — the maximum congestion is $2$, which is optimal in this case.}\n\\end{center}",
    "tutorial": "In what scenario the maximum congestion is $1$? Assume you have a blackbox that can solve any problem instance of size $n-2$, use it to solve a problem instance of size $n$. This is a special case for a problem called congestion minimization. While in general this problem is NP-hard, for this special structure it can be solved efficiently. The only case where the maximum congestion is $1$, is when $p = q = [1,2,\\dots,n]$. This can be proved by a pigeonhole argument - if there exists some $p_i \\neq i$ or $q_i \\neq i$, the total length of the $2n$ paths will be strictly greater than the number of edges which means at least one edge has to be used more than once. Our goal now is to try constructing a routing scheme with maximum congestion $2$. We will show that this is always doable for any input. We will first show a pictorial sketch that presents the idea, and fill in the details later. We also provide you a python script that visualize the output to help you debug, you can find it at the end of this section. The solution is based on induction. The base cases $n=0$ and $n=1$ are trivial. Now assume we can solve any problem instance for size up to $k-2$. We will treat it as a blackbox to solve a problem instance of size $k$. Given any problem instance of size $k$, first we route the following $4$ demand pairs using only the outer edges: the top-bottom pair that starts at $(1, 1)$, using the left and bottom edges; the top-bottom pair that starts at $(1, k)$, using the right and bottom edges; the left-right pair that starts at $(1, 1)$, using the top and right edges; the left-right pair that ends at $(1,k)$, using the left and top edges. However, if this is the same pair as above, then we route another arbitrary left-right pair using the left, top and right edges. As of now, there are $k-2$ top-bottom demands and $k-2$ left-right demands remain to be routed. We simply connect their starting and ending points one step closer to the center, retaining their relative order. In such way, we reduced the problem to a problem instance of size $k-2$ which we already knew how to solve.",
    "code": "#include <bits/stdc++.h>\n#define FOR(i,s,e) for (int i=(s); i<(e); i++)\n#define FOE(i,s,e) for (int i=(s); i<=(e); i++)\n#define FOD(i,s,e) for (int i=(s)-1; i>=(e); i--)\n#define PB push_back\nusing namespace std;\n\nstruct Paths{\n\t/* store paths in order */\n\tvector<vector<pair<int, int>>> NS, EW;\n\t\n\tPaths(){\n\t\tNS.clear();\n\t\tEW.clear();\n\t}\n};\n\nPaths solve(vector<int> p, vector<int> q){\n\tint n = p.size();\n\tPaths Ret;\n\tRet.NS.resize(n);\n\tRet.EW.resize(n);\n\t\n\t// Base case\n\tif (n == 0) return Ret;\n\tif (n == 1){\n\t\tRet.NS[0].PB({1, 1});\n\t\tRet.EW[0].PB({1, 1});\n\t\treturn Ret;\n\t}\n\n\t// Route NS flow originating from (1, 1) and (1, n) using leftmost and rightmost edges\n\tFOE(i,1,n){\n\t\tRet.NS[0].PB({i, 1});\n\t\tRet.NS[n-1].PB({i, n});\n\t}\n\t// Routing to final destination using bottom edges\n\tFOE(i,2,p[0]) Ret.NS[0].PB({n, i});\n\tFOD(i,n,p[n-1]) Ret.NS[n-1].PB({n, i});\n\n\t// Create p'[] for n-2 instance\n\tvector<int> p_new(0);\n\tFOE(i,1,n-2) p_new.PB(p[i] - (p[i]>p[0]) - (p[i]>p[n-1]));\n\n\t// Route EW flow originating from (1, 1) using topmost and rightmost edges\n\tFOE(i,1,n) Ret.EW[0].PB({1, i});\n\tFOE(i,2,q[0]) Ret.EW[0].PB({i, n});\n\n\t// Route EW flow originating in (m, 1) with q[m] as small as possible\n\tint m = 1;\n\t// special handle so congestion is 1 if possible\n\tif (p[0] == 1 && p[n-1] == n && q[0] == 1 && q[n-1] == n){\n\t\tm = n - 1;\n\t\tFOE(i,1,n) Ret.EW[n-1].PB({n, i});\n\t}\n\telse{\n\t\tFOR(i,1,n) if (q[i] < q[m]) m = i;\n\t\t// Route(m+1, 1) --> (1, 1) --> (1, n) --> (q[m], n)\n\t\t\n\t\tFOD(i,m+2,2) Ret.EW[m].PB({i, 1});\n\t\tFOR(i,1,n) Ret.EW[m].PB({1, i});\n\t\tFOE(i,1,q[m]) Ret.EW[m].PB({i, n});\n\t}\n\t\n\t// Create q'[] for n-2 instance\n\tvector<int> q_new(0);\n\tFOR(i,1,n) if (i != m) q_new.PB(q[i] - (q[i]>q[0]) - (q[i]>q[m]));\n\n\tif (n > 1){\n\t\tPaths S = solve(p_new, q_new);\n\t\tint t;\n\t\t\n\t\t// connect NS paths\n\t\tFOR(i,1,n-1){\n\t\t\tRet.NS[i].PB({1, i+1});\n\t\t\tfor (auto [x, y]: S.NS[i-1]){\n\t\t\t\tRet.NS[i].PB({x+1, y+1});\n\t\t\t\tt = y + 1;\n\t\t\t}\n\t\t\tRet.NS[i].PB({n, t});\n\t\t\tif (p[i] != t) Ret.NS[i].PB({n, p[i]});\n\t\t}\n\n\t\t// connect EW paths\n\t\tint l = 0;\n\t\tFOR(i,1,n) if (i != m){\n\t\t\tRet.EW[i].PB({i+1, 1});\n\t\t\tif (i > m) Ret.EW[i].PB({i, 1});\n\t\t\t\n\t\t\tfor (auto [x, y]: S.EW[l]){\n\t\t\t\tRet.EW[i].PB({x+1, y+1});\n\t\t\t\tt = x + 1;\n\t\t\t}\n\t\t\t\n\t\t\tRet.EW[i].PB({t, n});\n\t\t\tif (q[i] != t) Ret.EW[i].PB({q[i], n});\n\t\t\t++l;\n\t\t}\n\t}\n\n\treturn Ret;\n}\n\nint main(){\n\tint n;\n\tvector<int> p, q;\n\t\n\tscanf(\"%d\", &n);\n\tp.resize(n), q.resize(n);\n\tFOR(i,0,n) scanf(\"%d\", &p[i]);\n\tFOR(i,0,n) scanf(\"%d\", &q[i]);\n\n\tPaths Solution = solve(p, q);\n\t\n\tfor (auto path: Solution.NS){\n\t\tprintf(\"%d\", path.size());\n\t\tfor (auto [x, y]: path) printf(\" %d %d\", x, y);\n\t\tputs(\"\");\n\t}\n\t\n\tfor (auto path: Solution.EW){\n\t\tprintf(\"%d\", path.size());\n\t\tfor (auto [x, y]: path) printf(\" %d %d\", x, y);\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1771",
    "index": "A",
    "title": "Hossam and Combinatorics",
    "statement": "Hossam woke up bored, so he decided to create an interesting array with his friend Hazem.\n\nNow, they have an array $a$ of $n$ positive integers, Hossam will choose a number $a_i$ and Hazem will choose a number $a_j$.\n\nCount the number of interesting pairs $(a_i, a_j)$ that meet all the following conditions:\n\n- $1 \\le i, j \\le n$;\n- $i \\neq j$;\n- The absolute difference $|a_i - a_j|$ must be equal to the maximum absolute difference over all the pairs in the array. More formally, $|a_i - a_j| = \\max_{1 \\le p, q \\le n} |a_p - a_q|$.",
    "tutorial": "Firstly, let's find $\\max_{1 \\le p, q \\le n} |a_p - a_q| = max(a) - min(a)$ if it's equal to zero, then any pair is valid, so answer if $n \\cdot (n - 1)$ Otherwise, let's calculate $count\\_min$ and $count\\_max$. Answer is $2 \\cdot count\\_min \\cdot count\\_max$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1e5 + 5;\n\nint n, a[N];\n\nint main()\n{\n#ifndef ONLINE_JUDGE\n    freopen(\"input.in\", \"r\", stdin);\n#endif\n    int t;\n    scanf(\"%d\", &t);\n    while(t--){\n        scanf(\"%d\", &n);\n        for(int i = 0 ; i < n ; ++i)\n            scanf(\"%d\", a + i);\n    \n        sort(a, a + n);\n    \n        if(a[0] == a[n - 1]){\n            printf(\"%lld\\n\", (1LL * n * (n - 1LL)));\n            continue;\n        }\n    \n        int mn = 0, mx = n - 1;\n    \n        while(a[0] == a[mn])\n            ++mn;\n    \n        while(a[n - 1] == a[mx])\n            --mx;\n    \n        long long l = mn;\n        long long r = n - mx - 1;\n    \n    \n        printf(\"%lld\\n\", 2LL * l * r);\n    }\n}\n",
    "tags": [
      "combinatorics",
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1771",
    "index": "B",
    "title": "Hossam and Friends",
    "statement": "Hossam makes a big party, and he will invite his friends to the party.\n\nHe has $n$ friends numbered from $1$ to $n$. They will be arranged in a queue as follows: $1, 2, 3, \\ldots, n$.\n\nHossam has a list of $m$ pairs of his friends that don't know each other. Any pair not present in this list are friends.\n\nA subsegment of the queue starting from the friend $a$ and ending at the friend $b$ is $[a, a + 1, a + 2, \\ldots, b]$. A subsegment of the queue is called good when all pairs of that segment are friends.\n\nHossam wants to know how many pairs $(a, b)$ there are ($1 \\le a \\le b \\le n$), such that the subsegment starting from the friend $a$ and ending at the friend $b$ is good.",
    "tutorial": "Just $a_i < b_i$ in non-friends pairs. Let's calculate $r_i =$ minimum non-friend for all people. So, we can't start subsegment in $a_i$ and finish it righter $r_i$. Let's process people from right to left and calculate the rightmost positions there subsegment can end. Initially, $R = n-1$. Then we go to $a_i$ just do $R = \\min(R, r_i)$ and add $R - i + 1$ to answer.",
    "code": "#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops,no-stack-protector,fast-math\")\n#include <bits/stdc++.h>\n#define ll long long\n#define ld long double\n#define IO ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);\nusing namespace std;\nconst int N = 1e5 + 5, M = 1e5 + 5;\n\nint n, m;\nint mn[N];\n\nint main()\n{\n#ifndef ONLINE_JUDGE\n    freopen(\"input.in\", \"r\", stdin);\n#endif\n    int t;\n    scanf(\"%d\", &t);\n    while(t--){\n        scanf(\"%d %d\", &n, &m);\n        for(int i = 1 ; i <= n ; ++i)\n            mn[i] = n;\n    \n        for(int i = 0 ; i < m ; ++i){\n            int x, y;\n            scanf(\"%d %d\", &x, &y);\n            \n            if(x > y)\n                swap(x, y);\n                \n            mn[x] = min(mn[x], y - 1);\n        }\n    \n        for(int i = n - 1 ; i ; --i)\n            mn[i] = min(mn[i], mn[i + 1]);\n    \n        ll ans = n;\n        for(int i = 0 ; i < n ; ++i)\n            ans += (mn[i] - i);\n    \n        printf(\"%lld\\n\", ans);\n    }\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dp",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1771",
    "index": "C",
    "title": "Hossam and Trainees",
    "statement": "Hossam has $n$ trainees. He assigned a number $a_i$ for the $i$-th trainee.\n\nA pair of the $i$-th and $j$-th ($i \\neq j$) trainees is called successful if there is an integer $x$ ($x \\geq 2$), such that $x$ divides $a_i$, and $x$ divides $a_j$.\n\nHossam wants to know if there is a successful pair of trainees.\n\nHossam is very tired now, so he asks you for your help!",
    "tutorial": "If exists $x \\geq 2$ such that $a_i$ divides $x$ and $a_j$ divides $x$ then exists prime number $p$ such that $a_i$ and $a_j$ divides $p$. We can choose $p =$ any prime divisor of $x$. So, let's factorize all numbers and check, if two of them divides one prime number. We can use default factorization, and it will be $O(n \\cdot \\sqrt{A})$. It's too long, so just calculate prime numbers $\\leq \\sqrt{A}$ and check if $a_i$ divides this numbers. It will be $O(n \\cdot \\frac{\\sqrt{A}}{\\log{A}})$ - fast enouth.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1e5 + 5, M = 2 * N + 5;\n\nbool vis[N], ans;\n\nvoid Sieve(){\n    memset(vis, true, sizeof(vis));\n    \n    vis[0] = vis[1] = false;\n    for(int i = 4 ; i < N ; i += 2)\n        vis[i] = false;\n    for(int i = 3 ; i < N / i ; i += 2){\n        if(!vis[i])continue;\n        for(int j = i * i ; j < N ; j += i + i)\n            vis[j] = false;\n    }\n}\n\nint in[N], vid;\nvector<int> primes;\n\nvoid Gen(){\n    for(int i = 2 ; i < N ; ++i)\n        if(vis[i])\n            primes.emplace_back(i);\n}\n\nset<int> st;\n\nvoid check(int x){\n    if(in[x] == vid){\n        ans = true;\n        return;\n    }\n\n    in[x] = vid;\n}\n\nvoid fact(int x){\n\n    if(x < N && vis[x] == true){\n        check(x);\n        return;\n    }\n\n    int idx = 0, sz = primes.size();\n\n    while(x > 1 && idx < sz && x / primes[idx] >= primes[idx]){\n\n        if(x % primes[idx] == 0){\n            check(primes[idx]);\n            while(x % primes[idx] == 0)x /= primes[idx];\n        }\n\n        ++idx;\n    }\n\n    if(x > 1){\n        if(x < N)\n            return check(x), void();\n\n        if(st.find(x) != st.end()){\n            ans = true;\n            return;\n        }\n\n        st.emplace(x);\n    }\n}\n\nvoid pre(){\n    ++vid;\n    st.clear();\n}\n\nint main(){\n    Sieve();\n    Gen();\n\n    int t;\n    scanf(\"%d\", &t);\n    while(t--){\n        pre();\n        \n        int n;\n        scanf(\"%d\", &n);\n        \n        ans = false;\n        \n        while(n--){\n            int x;\n            scanf(\"%d\", &x);\n            fact(x);\n        }\n        \n        puts(ans ? \"YES\" : \"NO\");\n    }\n    \n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1771",
    "index": "D",
    "title": "Hossam and (sub-)palindromic tree",
    "statement": "Hossam has an unweighted tree $G$ with letters in vertices.\n\nHossam defines $s(v, \\, u)$ as a string that is obtained by writing down all the letters on the unique simple path from the vertex $v$ to the vertex $u$ in the tree $G$.\n\nA string $a$ is a subsequence of a string $s$ if $a$ can be obtained from $s$ by deletion of several (possibly, zero) letters. For example, \"dores\", \"cf\", and \"for\" are subsequences of \"codeforces\", while \"decor\" and \"fork\" are not.\n\nA palindrome is a string that reads the same from left to right and from right to left. For example, \"abacaba\" is a palindrome, but \"abac\" is not.\n\nHossam defines a sub-palindrome of a string $s$ as a subsequence of $s$, that is a palindrome. For example, \"k\", \"abba\" and \"abhba\" are sub-palindromes of the string \"abhbka\", but \"abka\" and \"cat\" are not.\n\nHossam defines a maximal sub-palindrome of a string $s$ as a sub-palindrome of $s$, which has the maximal length among all sub-palindromes of $s$. For example, \"abhbka\" has only one maximal sub-palindrome — \"abhba\". But it may also be that the string has several maximum sub-palindromes: the string \"abcd\" has $4$ maximum sub-palindromes.\n\nHelp Hossam find the length of the longest maximal sub-palindrome among all $s(v, \\, u)$ in the tree $G$.\n\n\\textbf{Note that the sub-palindrome is a subsequence, not a substring.}",
    "tutorial": "Let's use dynamic programming method. Let $dp_{v, \\, u}$ as length of the longest maximal sub-palindrome on the path between vertexes $v$ and $u$. Then the answer to the problem is $\\max\\limits_{1 \\le v, \\, u \\le n}{dp_{v, \\, u}}$. Define $go_{v, \\, u}$ $(v \\neq u)$ vertex $x$ such that it is on way between $v$ and $u$ and distance between $v$ and $x$ is $1$. If $v = u$, then we put $go_{v, \\, u}$ equal to $v$. So, there are three cases: The answer for $(v, \\, u)$ equals to the answer for $(go_{v, \\, u}, \\, u)$; The answer for $(v, \\, u)$ equals to the answer for $(v, \\, go_{u, \\, v})$; If $s_v = s_u$, then the answer for $(v, \\, u)$ equals to the answer for $(go_{v, \\, u}, \\, go_{u, \\, v}) \\, + \\, 2$. In this case we took best sub-palindrome strictly inside the path $v, \\, u$ and added to it two same symbols in $v$ and $u$. Formally , the transitions in dynamics will look like this: $dp_{v, \\, u} := \\max(dp_{v, \\, go_{u, \\, v}}, \\; dp_{go_{v, \\, u}, \\, u}, \\; dp_{go_{v, \\, u}, \\, go_{u, \\, v}} + 2 \\cdot (s_v = s_u)).$ Dynamic's base: $dp_{v, \\, v} := 1,$ $dp_{v, \\, w} := 1 \\, + \\, (s_v = s_w),$ In order to calculate the values in dp, you need to iterate through pairs of vertices in ascending order of the distance between the vertices in the pair (note that this can be done by counting sort). The question remains: how to calculate the array $go$? Let's iterate all vertexes and let the current vertex is $v$. Let $v$ be the root of the tree. Consider all sons of this vertex. Let current son is $x$. Then for all $u$ from subtree of $x$ the value of $go_{v, \\, u}$ will be number of $x$. Thus, time and memory complexity of this solution is $\\mathcal{O}(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid dfs(int v, vector<vector<int>> &g, vector<vector<int>> &go, vector<vector<pair<int, int>>> &kek, int s, int t = -1, int p = -1, int len = 0){\n    if(len == 1)\n        t = v;\n\n    if(len > 1)\n        go[s][v] = t;\n\n    kek[len].push_back({s, v});\n\n    for(int u : g[v])\n        if(u != p)\n            dfs(u, g, go, kek, s, t, v, len + 1);\n}\n\nvoid Solve(){\n    int n; cin >> n;\n    string a; cin >> a;\n\n    vector<vector<int>> g(n);\n    vector<vector<int>> go(n, vector<int>(n));\n    vector<vector<pair<int, int>>> kek(n);\n    vector<vector<int>> dp(n, vector<int>(n));\n\n    for(int i = 0; i < n - 1; i++){\n        int v, u;\n        cin >> v >> u;\n        g[--v].push_back(--u);\n        g[u].push_back(v);\n    }\n\n    for(int v = 0; v < n; v++)\n        dfs(v, g, go, kek, v);\n\n    for(int len = 0; len < n; len++){\n        for(auto p : kek[len]){\n            int v = p.first;\n            int u = p.second;\n\n            if(len == 0){\n                dp[v][u] = 1;\n            }else if(len == 1){\n                dp[v][u] = 1 + (a[v] == a[u]);\n            }else{\n                int x = dp[v][go[u][v]];\n                int y = dp[go[v][u]][u];\n                int z = dp[go[v][u]][go[u][v]] + ((a[v] == a[u]) << 1);\n                dp[v][u] = max({x, y, z});\n            }\n        }\n    }\n\n    int ans = 0;\n\n    for(int v = 0; v < n; v++)\n        for(int u = 0; u < n; u++)\n            ans = max(ans, dp[v][u]);\n\n    cout << ans << '\\n';\n}\n\nsigned main(){\n    ios_base::sync_with_stdio(NULL);\n    cin.tie(NULL);\n    cout.tie(NULL);\n\n    int test = 1;\n    cin >> test;\n \n    for(int i = 1; i <= test; i++)\n        Solve();\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "strings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1771",
    "index": "E",
    "title": "Hossam and a Letter",
    "statement": "Hossam bought a new piece of ground with length $n$ and width $m$, he divided it into an $n \\cdot m$ grid, each cell being of size $1\\times1$.\n\nSince Hossam's name starts with the letter 'H', he decided to draw the capital letter 'H' by building walls of size $1\\times1$ on some squares of the ground. Each square $1\\times1$ on the ground is assigned a quality degree: perfect, medium, or bad.\n\nThe process of building walls to form up letter 'H' has the following constraints:\n\n- The letter must consist of one horizontal and two vertical lines.\n- The vertical lines must not be in the same or neighboring columns.\n- The vertical lines must start in the same row and end in the same row (and thus have the same length).\n- The horizontal line should connect the vertical lines, but must not cross them.\n- The horizontal line can be in any row between the vertical lines (not only in the middle), except the top and the bottom one. (With the horizontal line in the top row the letter looks like 'n', and in the bottom row like 'U'.)\n- It is forbidden to build walls in cells of bad quality.\n- You can use at most one square of medium quality.\n- You can use any number of squares of perfect quality.\n\nFind the maximum number of walls that can be used to draw the letter 'H'.\n\nCheck the note for more clarification.",
    "tutorial": "Let's preprocess the following data for each cell. 1. first medium cell above current cell. 2. first medium cell below current cell. 3. first bad cell above current cell. 4. first bad cell below current cell. Then we will try to solve the problem for each row (i), and 2 columns (j, k). Now we have a horizontal line in row (i), and we can calculate the length of vertical line by the following. There is two cases: In case of the horizontal line contains one letter 'm'. For each column (j, k): get first cell above it the don't contain ('#' or 'm') and first cell below it the don't contain ('#' or 'm'). In case of the horizontal line doesn't contain any letter 'm'. We will try to get the 4 cells as it contains letter 'm', but in this case we will 4 trials. for each cell from the 4 cells, we allow to have only one letter 'm' in that line. After getting above cells and below cells for each line. the starting cell will be the maximum between the two above cells, and the ending cell will be the minimum between the two below cells. Then we need to check that starting cell is above the current row (i) to avoid making letter n instead of H And check that ending cell is below the current row (i) to avoid making letter u instead of H. Since n, m has the same maximum limit 400. Thus, time complexity of this solution is $O(n^3)$.",
    "code": "#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops,no-stack-protector,fast-math\")\n#include <bits/stdc++.h>\n#define ll long long\n#define ld long double\n#define IO ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);\nusing namespace std;\n\nconst int N = 4e2 + 5;\n\nint n, m;\nchar a[N][N];\n\nint upM[N][N];\nint upB[N][N];\n\nint downM[N][N];\nint downB[N][N];\n\nint _get(int I, int j, int incI, char ch){\n    int i = I + incI;\n\n    while(i >= 0 && i < n){\n        if(a[i][j] == '#')\n            break;\n\n        if(a[i][j] == ch)\n            break;\n\n        i += incI;\n    }\n\n    return i;\n}\n\nint _getCount(int i, int j){\n    if(a[i][j] == 'm')\n        return 1;\n\n    return (a[i][j] == '.' ? 0 : 10);\n}\n\n/**\n\n1  2    4  8\nUL DL   UR DR\n\n*/\n\n\nint getU(int i, int j, int bt){\n    if(!bt)\n        return max(upM[i][j], upB[i][j]) + 1;\n\n    int cur = upM[i][j];\n\n    if(cur == -1 || a[cur][j] == '#')\n        return cur + 1;\n\n    cur = upM[cur][j];\n\n    return cur + 1;\n}\n\n\nint getD(int i, int j, int bt){\n    if(!bt)\n        return min(downM[i][j], downB[i][j]) &mdash; 1;\n\n    int cur = downM[i][j];\n\n    if(cur == n || a[cur][j] == '#')\n        return cur - 1;\n\n    cur = downM[cur][j];\n\n    return cur - 1;\n}\n\n\nint solve(int i, int l, int r, int msk){\n    int upL = getU(i, l, (msk & 1));\n    int downL = getD(i, l, (msk & 2));\n\n\n    int upR = getU(i, r, (msk & 4));\n    int downR = getD(i, r, (msk & 8));\n\n\n    int up = max(upL, upR);\n    int down = min(downL, downR);\n\n    if(up < i && down > i)\n        return  2 * (down - up + 1) + (r - l - 1);\n    \n    return 0;\n}\n\nint main()\n{\n#ifndef ONLINE_JUDGE\n    freopen(\"input.in\", \"r\", stdin);\n#endif\n    scanf(\"%d %d\", &n, &m);\n    for(int i = 0 ; i < n ; ++i)\n        scanf(\"%s\", a + i);\n\n    for(int i = 0 ; i < n ; ++i){\n        for(int j = 0 ; j < m ; ++j){\n            if(a[i][j] == '#')\n                continue;\n\n            upM[i][j] = _get(i, j, -1, 'm');\n            upB[i][j] = _get(i, j, -1, '#');\n\n            downM[i][j] = _get(i, j, 1, 'm');\n            downB[i][j] = _get(i, j, 1, '#');\n        }\n    }\n\n    int mx = 0;\n    for(int i = 0 ; i < n ; ++i){\n        for(int j = 0 ; j + 2 < m ; ++j){\n\n            int cnt = _getCount(i, j) + _getCount(i, j + 1);\n            for(int k = j + 2 ; k < m ; ++k){\n                if((cnt += _getCount(i, k)) > 1)\n                    break;\n\n                mx = max(mx, solve(i, j, k, 0));\n\n                if(cnt == 1)\n                    continue;\n\n                mx = max(mx, solve(i, j, k, 1));\n                mx = max(mx, solve(i, j, k, 2));\n                mx = max(mx, solve(i, j, k, 4));\n                mx = max(mx, solve(i, j, k, 8));\n            }\n\n        }\n    }\n\n    printf(\"%d\\n\", mx);\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1771",
    "index": "F",
    "title": "Hossam and Range Minimum Query",
    "statement": "Hossam gives you a sequence of integers $a_1, \\, a_2, \\, \\dots, \\, a_n$ of length $n$. Moreover, he will give you $q$ queries of type $(l, \\, r)$. For each query, consider the elements $a_l, \\, a_{l + 1}, \\, \\dots, \\, a_r$. Hossam wants to know the \\textbf{smallest} number in this sequence, such that it occurs in this sequence an \\textbf{odd} number of times.\n\nYou need to compute the answer for each query before process the next query.",
    "tutorial": "Note that we were asked to solve the problem in online mode. If this were not the case, then the Mo Algorithm could be used. How to solve this task in online mode? Consider two ways. The first way is as follows. Let's build a persistent bitwise trie $T$ on a given array, where the $i$-th version of the trie will store numbers $x$ such that $x$ occurs on the subsegment $a[1\\dots i]$ an odd number of times. This can be done as follows. Let $T_0$ be an empty trie, and $T_i$ will be obtained as follows: first we assign $T_i = T_{i - 1}$; then, if $a_i$ occurs in $T_{i - 1}$, then we will erase the number $a_i$ from $T_i$, otherwise we will insert it there. Suppose we need to get answer on the query $[l, \\, r]$. Note that if $x$ is included in $T_r$, but is not included in $T_{l - 1}$ (or is included in $T_{l - 1}$, but is not included in $T_r$), then this means that the number $x$ on the segment $a[l\\dots r]$ occurs an odd number of times. Otherwise, the number $x$ occurs an even number of times (recall that $0$ is an even number). Thus, we need to find a minimum number $x$ such that it occurs either in $T_{l - 1}$ or in $T_r$, but not in both at once. If there is no such number, then you need to output $0$. Let's go down $T_{l - 1}$ and $T_r$ in parallel on the same prefix of the number. If $T_{l - 1}$ and $T_r$ are equal, then the same numbers are contained there, and then the answer is $0$. Next, we will assume that the answer is not $0$. The left subtree of the vertex is the son to whom the transition along the edge of $0$ is going, and the right subtree is the vertex to which the transition along the edge of $1$ is going. Let us now stand at the vertices $v$ and $u$, respectively. If the left subtrees of $v$ and $u$ are equal, it means that the same numbers are contained there, so there is no point in going there, so we go along the right edge. Otherwise, the left subtree of $v$ contains at least one number that is not in the left subtree of $u$ (or vice versa), so we will go down the left edge. The number in which we ended up will be the answer. Note that in order to compare two subtrees for equality, you need to use the hashing technique of root trees. Then we can compare the two subtree for $\\mathcal{O}(1)$. Thus, we get the asymptotics $\\mathcal{O((n+q)\\log{max(a)})}$. If we compress the numbers of the sequence $a$ in advance, then we can get the asymptotics of $\\mathcal{O((n + q) \\log{n})}$. Let's consider the second way. Let's compress the numbers in the sequence $a$ in advance. Let $pref_{ij} = 0$ if the prefix $i$ contains the number $a_j$ an even number of times, and $pref_{ij} = 1$ if the prefix $i$ contains the number $a_j$ an odd number of times. Then, in order to get an answer to the query $[l\\dots r]$, we need to take the \"bitwise exclusive OR\" arrays $pref_{l - 1}$ and $pref_r$ and find in it the minimum $j$ such that $pref_{ij} = 1$. The number $j$ will be the answer. Obviously, now this solution need much time and memory. In order to optimize the amount of memory consumed, we will use bitsets. However, even in this case, we consume memory of the order of $\\mathcal{o}(h^2 \\, / \\, 64)$, which is still a lot. So let's not remember about all $pref_i$, but only some. For example, let's get some constant $k$ and remeber only about $pref_0, \\, pref_k, \\, pref_{2k}, \\, \\data\\, pref_{pk}$. Then, when we need to answer the next query $[l \\dots r]$, we will find the right block on which we store almost all the numbers we are looking for, and then we will insert/erase for $\\mathcal{O(k)}$ missing numbers. If you select $k \\sim\\sqrt{n}$, then this solution will fit in memory. However, if you use std::bitset<> in C++, then most likely this solution will still receive the verdict Time Limit. Therefore, to solve this problem, you need to write your own fast bitset. The asymptotics of such a solution would be $\\mathcal{O}(n\\, (n+q) \\, / \\, 64)$. However, due to a well-chosen $k$ and a self-written bitset, the constant in this solution will be very small and under given constraints, such a solution can work even faster than the first one.",
    "code": "#pragma optimize(\"SEX_ON_THE_BEACH\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC optimize(\"unroll-all-loops\")\n#pragma GCC optimize(\"O3\")\n \n#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"fast-math\")\n//#define _FORTIFY_SOURCE 0 \n#pragma GCC optimize(\"no-stack-protector\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native\") \n\n#include<bits/stdc++.h>\n#include <x86intrin.h>\n\nusing uint = unsigned int;\nusing ll = long long int;\nusing ull = unsigned long long int;\nusing dd = double;\nusing ldd = long double;\nusing pii = std::pair<int, int>;\nusing pll = std::pair<ll, ll>;\nusing pdd = std::pair<dd, dd>;\nusing pld = std::pair<ldd, ldd>;\n\nnamespace fast {\n    template<typename T>\n    T gcd(T a, T b) {\n        return gcd(a, b);\n    }\n\n    template<>\n    unsigned int gcd<unsigned int>(unsigned int u, unsigned int v) {\n        int shift;\n        if (u == 0)\n            return v;\n        if (v == 0)\n            return u;\n        shift = __builtin_ctz(u | v);\n        u >>= __builtin_ctz(u);\n        do {\n            unsigned int m;\n            v >>= __builtin_ctz(v);\n            v -= u;\n            m = (int)v >> 31;\n            u += v & m;\n            v = (v + m) ^ m;\n        } while (v != 0);\n        return u << shift;\n    }\n\n    template<>\n    unsigned long long gcd<unsigned long long>(unsigned long long u, unsigned long long v) {\n        int shift;\n        if (u == 0)\n            return v;\n        if (v == 0)\n            return u;\n        shift = __builtin_ctzll(u | v);\n        u >>= __builtin_ctzll(u);\n        do {\n            unsigned long long m;\n            v >>= __builtin_ctzll(v);\n            v -= u;\n            m = (long long)v >> 63;\n            u += v & m;\n            v = (v + m) ^ m;\n        } while (v != 0);\n        return u << shift;\n    }\n}\n \nnamespace someUsefull {\n    template<typename T1, typename T2>\n    inline void checkMin(T1& a, T2 b) {\n        if (a > b)\n            a = b;\n    }\n \n    template<typename T1, typename T2>\n    inline void checkMax(T1& a, T2 b) {\n        if (a < b)\n            a = b;\n    }\n\n    template<typename T1, typename T2>\n    inline bool checkMinRes(T1& a, T2 b) {\n        if (a > b) {\n            a = b;\n            return true;\n        }\n        return false;\n    }\n\n    template<typename T1, typename T2>\n    inline bool checkMaxRes(T1& a, T2 b) {\n        if (a < b) {\n            a = b;\n            return true;\n        }\n        return false;\n    }\n}\n \nnamespace operators {\n    template<typename T1, typename T2>\n    std::istream& operator>>(std::istream& in, std::pair<T1, T2>& x) {\n        in >> x.first >> x.second;\n        return in;\n    }\n \n    template<typename T1, typename T2>\n    std::ostream& operator<<(std::ostream& out, std::pair<T1, T2> x) {\n        out << x.first << \" \" << x.second;\n        return out;\n    }\n \n    template<typename T1>\n    std::istream& operator>>(std::istream& in, std::vector<T1>& x) {\n        for (auto& i : x) in >> i;\n        return in;\n    }\n \n    template<typename T1>\n    std::ostream& operator<<(std::ostream& out, std::vector<T1>& x) {\n        for (auto& i : x) out << i << \" \";\n        return out;\n    }\n}\n \n//name spaces\nusing namespace std;\nusing namespace operators;\nusing namespace someUsefull;\n//end of name spaces\n \n//defines\n#define ff first\n#define ss second\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define NO {cout << \"NO\"; return;}\n#define YES {cout << \"YES\"; return;}\n \n//end of defines\n//#undef HOME\n//debug defines\n#ifdef HOME\n    #define debug(x) cerr << #x << \" \" << (x) << endl;\n    #define debug_v(x) {cerr << #x << \" \"; for (auto ioi : x) cerr << ioi << \" \"; cerr << endl;}\n    #define debug_vp(x) {cerr << #x << \" \"; for (auto ioi : x) cerr << '[' << ioi.ff << \" \" << ioi.ss << ']'; cerr << endl;}\n    #define debug_v_v(x) {cerr << #x << \"/*\\n\"; for (auto ioi : x) { for (auto ioi2 : ioi) cerr << ioi2 << \" \"; cerr << '\\n';} cerr << \"*/\" << #x << endl;}\n    int jjj;\n    #define wait() cin >> jjj;\n    #define PO cerr << \"POMELO\" << endl;\n    #define OL cerr << \"OLIVA\" << endl;\n    #define gen_clock(x) cerr << \"Clock \" << #x << \" created\" << endl; ll x = clock(); \n    #define check_clock(x) cerr << \"Time spent in \" << #x << \": \" << clock() - x << endl; x = clock();\n    #define reset_clock(x) x = clock();\n    #define say(x) cerr << x << endl;\n#else\n    #define debug(x) 0;\n    #define debug_v(x) 0;\n    #define debug_vp(x) 0;\n    #define debug_v_v(x) 0;\n    #define wait() 0;\n    #define PO 0;\n    #define OL 0;\n    #define gen_clock(x) 0;\n    #define check_clock(x) 0;\n    #define reset_clock(x) 0;\n    #define say(x) 0;\n#endif // HOME\n\nconst int SIZE = 200000;\nconst int block = 64;\nconst int _size = (SIZE + 63) / 64;\n\nstruct bs {\n    ull arr[_size];\n\n    bs() {\n        for (int i = 0; i < _size; ++i) arr[i] = 0;\n    }\n\n    bs& operator^=(bs &other) {\n        #pragma GCC ivdep\n        for (int i = 0; i < _size; ++i)\n            arr[i] ^= other.arr[i];\n        return *this;\n    }\n\n    int _Find_first_in_xor(bs& other) {\n        ull t;\n        for (int i = 0; i < _size; ++i) {\n            if (t = arr[i] ^ other.arr[i]) {\n                return (i << 6) + __builtin_ctzll(t);\n            }\n        }\n        return SIZE;\n    }\n\n    int _Find_first() {\n        for (int i = 0; i < _size; ++i) {\n            if (arr[i]) {\n                return (i << 6) + __builtin_ctzll(arr[i]);\n            }\n        }\n        return SIZE;\n    }\n\n    void flip(int id) {\n        ull &x = arr[id >> 6];\n        id &= 63;\n        x ^= ((ull)1 << id);\n    }\n\n    int size() {\n        return SIZE;\n    }\n\n};\n\n\nostream& operator<<(ostream &os, bs &x) {\n    for (int i = 0; i < _size; ++i) {\n        os << x.arr[i] << \" \";\n    }\n    return os;\n}\n\nvoid solve(int test) {\n    int n;\n    cin >> n;\n    vector<int> arr(n);\n    cin >> arr;\n    vector<int> to(n);\n    {\n        map<int, int> have;\n        for (int i : arr) have[i] = 0;\n        int cnt = 0;\n        for (auto &i : have) {\n            i.ss = cnt;\n            to[cnt] = i.ff;\n            cnt++;\n        }\n        for (int &i: arr) i = have[i];\n    }\n\n    vector<vector<int>> blocks;\n    for (int i = 0; i < n; i += block) {\n        blocks.push_back({});\n        for (int j = 0; i + j < n && j < block; ++j) {\n            blocks.back().push_back(arr[i + j]);\n        }\n    }\n\n    vector<bs> blocks_bs(blocks.size());\n    for (int i = 0; i < blocks.size(); ++i) {\n        for (int j : blocks[i]) {\n            blocks_bs[i].flip(j);\n        }\n    }\n    for (int i = 1; i < blocks.size(); ++i) {\n        blocks_bs[i] ^= blocks_bs[i - 1];\n    }\n\n    int q;\n    cin >> q;\n    bs have;\n    int last = 0;\n    for (int i = 0; i < q; ++i) {\n        int a, b;\n        cin >> a >> b;\n\n        int l = (last ^ a);\n        int r = (last ^ b);\n\n        // cin >> l >> r;\n        --l;\n        --r;\n        int lb = l / block;\n        int rb = r / block;\n        if (rb - lb <= 1) {\n            int L = l;\n            while (l <= r) {\n                have.flip(arr[l]);\n                ++l;\n            }\n            int id = have._Find_first();\n\n            int ans = (id == have.size() ? 0 : to[id]);\n            last = ans;\n            cout << ans << '\\n';\n            l = L;\n            while (l <= r) {\n                have.flip(arr[l]);\n                ++l;\n            }\n        } else {\n            int L = (lb + 1) * block;\n            int old_l = l;\n            int R = (rb + 1) * block;\n            checkMin(R, n);\n            int old_r = r;\n            ++r;\n            while (r < R) {\n                blocks_bs[rb].flip(arr[r]);\n                ++r;\n            }\n                        while (l < L) {\n                blocks_bs[lb].flip(arr[l]);\n                ++l;\n            }\n            int id = blocks_bs[rb]._Find_first_in_xor(blocks_bs[lb]);\n            int ans = (id == have.size() ? 0 : to[id]);\n            last = ans;\n            cout << ans << '\\n';\n            r = old_r;\n            ++r;\n            while (r < R) {\n                blocks_bs[rb].flip(arr[r]);\n                ++r;\n            }\n            l = old_l;\n            while (l < L) {\n                blocks_bs[lb].flip(arr[l]);\n                ++l;\n            }\n        }\n    }\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cout.tie(0);\n    cin.tie(0);\n    //freopen(\"file.in\", \"r\", stdin);\n    //freopen(\"file.out\", \"w\", stdout);\n \n    int t = 1;\n    //cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve(i+1);\n        //cout << '\\n';\n        //PO;\n    }\n    return 0;\n}\n/*\n*/",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "hashing",
      "probabilities",
      "strings",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1772",
    "index": "A",
    "title": "A+B?",
    "statement": "You are given an expression of the form $a{+}b$, where $a$ and $b$ are integers from $0$ to $9$. You have to evaluate it and print the result.",
    "tutorial": "There are multiple ways to solve this problem. Most interpreted languages have some function that takes the string, evaluates it as code, and then returns the result. One of the examples is the eval function in Python. If the language you use supports something like that, you can read the input as a string and use it as the argument of such a function. Suppose you use a language where this is impossible. There are still many approaches to this problem. The most straightforward one is to take the first and the last characters of the input string, calculate their ASCII codes, and then subtract the ASCII code of the character 0 from them to get these digits as integers, not as characters. Then you can just add them up and print the result.",
    "code": "t = int(input())\nfor i in range(t):\n    print(eval(input()))",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1772",
    "index": "B",
    "title": "Matrix Rotation",
    "statement": "You have a matrix $2 \\times 2$ filled with \\textbf{distinct} integers. You want your matrix to become beautiful. The matrix is beautiful if the following two conditions are satisfied:\n\n- in each row, the first element is smaller than the second element;\n- in each column, the first element is smaller than the second element.\n\nYou can perform the following operation on the matrix any number of times: rotate it clockwise by $90$ degrees, so the top left element shifts to the top right cell, the top right element shifts to the bottom right cell, and so on:\n\nDetermine if it is possible to make the matrix beautiful by applying zero or more operations.",
    "tutorial": "Sure, you can just implement the rotation operation and check all $4$ possible ways to rotate the matrix, but it's kinda boring. The model solution does the different thing. If a matrix is beautiful, then its minimum is in the upper left corner, and its maximum is in the lower right corner (and vice versa). If you rotate it, the element from the upper left corner goes to the upper right corner, and the element from the lower right corner goes to the lower left corner - so these elements are still in the opposite corners. No matter how many times we rotate a beautiful matrix, its minimum and maximum elements will be in the opposite corners - and the opposite is true as well; if you have a $2 \\times 2$ matrix with minimum and maximum elements in opposite corners, it can be rotated in such a way that it becomes beautiful. So, all we need to check is that the minimum and the maximum elements are in the opposite corners. There are many ways to do it; in my opinion, the most elegant one is to read all four elements in an array of size $4$; then the opposite corners of the matrix correspond either to positions $0$ and $3$, or to positions $1$ and $2$ in this array. So, we check that the sum of positions of minimum and maximum is exactly $3$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int _ = 0; _ < t; _++)\n    {\n        vector<int> a(4);\n        for(int i = 0; i < 4; i++)\n            cin >> a[i];\n        int maxpos = max_element(a.begin(), a.end()) - a.begin();\n        int minpos = min_element(a.begin(), a.end()) - a.begin();\n        if(maxpos + minpos == 3)\n            puts(\"YES\");\n        else\n            puts(\"NO\");\n    }\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1772",
    "index": "C",
    "title": "Different Differences",
    "statement": "An array $a$ consisting of $k$ integers is \\textbf{strictly increasing} if $a_1 < a_2 < \\dots < a_k$. For example, the arrays $[1, 3, 5]$, $[1, 2, 3, 4]$, $[3, 5, 6]$ are strictly increasing; the arrays $[2, 2]$, $[3, 7, 5]$, $[7, 4, 3]$, $[1, 2, 2, 3]$ are not.\n\nFor a strictly increasing array $a$ of $k$ elements, let's denote the \\textbf{characteristic} as the number of different elements in the array $[a_2 - a_1, a_3 - a_2, \\dots, a_k - a_{k-1}]$. For example, the characteristic of the array $[1, 3, 4, 7, 8]$ is $3$ since the array $[2, 1, 3, 1]$ contains $3$ different elements: $2$, $1$ and $3$.\n\nYou are given two integers $k$ and $n$ ($k \\le n$). Construct an increasing array of $k$ integers from $1$ to $n$ with \\textbf{maximum possible} characteristic.",
    "tutorial": "We can transform the problem as follows. Let $d_i = a_{i+1} - a_i$. We need to find an array $[d_1, d_2, \\dots, d_{k-1}]$ so that the sum of elements in it is not greater than $n-1$, all elements are positive integers, and the number of different elements is the maximum possible. Suppose we need $f$ different elements in $d$. What can be the minimum possible sum of elements in $d$? It's easy to see that $d$ should have the following form: $[2, 3, 4, \\dots, f, 1, 1, 1, \\dots, 1]$. This array contains exactly $f$ different elements, these different elements are as small as possible (so their sum is as small as possible), and all duplicates are $1$'s. So, if the sum of this array is not greater than $n-1$, then it is possible to have the number of different elements in $d$ equal to $f$. The rest is simple. We can iterate on $f$, find the maximum possible $f$, construct the difference array, and then use it to construct the array $a$ itself.",
    "code": "def construct(f, k):\n    return [(i + 2 if i < f - 1 else 1) for i in range(k)]\n\nt = int(input())\nfor i in range(t):\n    k, n = map(int, input().split())\n    ans = 1\n    for f in range(1, k):\n        d = construct(f, k - 1)\n        if sum(d) <= n - 1:\n            ans = f\n    res = [1]\n    d = construct(ans, k - 1)\n    for x in d:\n        res.append(res[-1] + x)\n    print(*res)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1772",
    "index": "D",
    "title": "Absolute Sorting",
    "statement": "You are given an array $a$ consisting of $n$ integers. The array is sorted if $a_1 \\le a_2 \\le \\dots \\le a_n$.\n\nYou want to make the array $a$ sorted by applying the following operation \\textbf{exactly once}:\n\n- choose an integer $x$, then for every $i \\in [1, n]$, replace $a_i$ by $|a_i - x|$.\n\nFind any value of $x$ that will make the array sorted, or report that there is no such value.",
    "tutorial": "What does it actually mean for an array $a_1, a_2, \\dots, a_n$ to be sorted? That means $a_1 \\le a_2$ and $a_2 \\le a_3$ and so on. For each pair of adajacent elements, let's deduce which values $x$ put them in the correct order. Any value of $x$ that puts all pairs in the correct order will be the answer. Consider any $a_i$ and $a_{i+1}$ and solve the inequality $|a_i - x| \\le |a_{i+1} - x|$. If $a_i = a_{i+1}$, then any value of $x$ works. Let $a_i$ be smaller than $a_{i+1}$. If $x$ is smaller than or equal to $a_i$, then the inequality becomes $a_i - x \\le a_{i+1} - x \\Leftrightarrow a_i \\le a_{i+1}$. Thus, they don't change their order, and any $x \\le a_i$ works. If $x$ is greater than or equal to $a_{i+1}$, then the inequality becomes $x - a_i \\le x - a_{i+1} \\Leftrightarrow a_i \\ge a_{i+1}$. Thus, they always change their order, and none of $x \\ge a_i$ work. If $x$ is between $a_i$ and $a_{i+1}$, then the inequality becomes $x - a_i \\le a_{i+1} - x \\Leftrightarrow 2x \\le a_i + a_{i+1} \\Leftrightarrow x \\le \\frac{a_i + a_{i+1}}{2}$. Thus, they only remain in the same order for any integer $x$ such that $a_i \\le x \\le \\lfloor \\frac{a_i + a_{i+1}}{2} \\rfloor$. In union, that tells us that all values of $x$ that work for such a pair are $x \\le \\lfloor \\frac{a_i + a_{i+1}}{2} \\rfloor$. The similar analysis can be applied to $a_i > a_{i+1}$, which results in the required $x$ being $x \\ge \\lceil \\frac{a_i + a_{i+1}}{2} \\rceil$ for such pairs. Finally, how to find out if some value of $x$ passes all conditions? Among all conditions of form $x \\le \\mathit{val_i}$, in order for some $x$ to work, it should be less than or equal to even the smallest of them. Similarly, among all conditions of form $x \\ge \\mathit{val_i}$, in order for some $x$ to work, it should be greater than or equal to even the largest of them. Thus, take the minimum over the pairs of one type. Take the maximum over the pairs of another type. If two resulting values are contradictory, then there is no answer. Otherwise, any value inside the resulting range of $x$ works. Overall complexity: $O(n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for(int j = 0; j < n; j++)\n            cin >> a[j];\n        int mn = 0, mx = int(1e9);\n        for(int j = 0; j + 1 < n; j++)\n        {\n            int x = a[j];\n            int y = a[j + 1];\n            int midL = (x + y) / 2;\n            int midR = (x + y + 1) / 2;\n            if(x < y)\n                mx = min(mx, midL);\n            if(x > y)\n                mn = max(mn, midR);\n        }\n        if(mn <= mx) cout << mn << endl;\n        else cout << -1 << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1772",
    "index": "E",
    "title": "Permutation Game",
    "statement": "Two players are playing a game. They have a permutation of integers $1$, $2$, ..., $n$ (a permutation is an array where each element from $1$ to $n$ occurs exactly once). The permutation is not sorted in either ascending or descending order (i. e. the permutation does not have the form $[1, 2, \\dots, n]$ or $[n, n-1, \\dots, 1]$).\n\nInitially, all elements of the permutation are colored red. The players take turns. On their turn, the player can do one of three actions:\n\n- rearrange the elements of the permutation in such a way that all \\textbf{red} elements keep their positions (note that \\textbf{blue} elements can be swapped with each other, but it's not obligatory);\n- change the color of one red element to blue;\n- skip the turn.\n\nThe first player wins if the permutation is sorted in ascending order (i. e. it becomes $[1, 2, \\dots, n]$). The second player wins if the permutation is sorted in descending order (i. e. it becomes $[n, n-1, \\dots, 1]$). If the game lasts for $100^{500}$ turns and nobody wins, it ends in a draw.\n\nYour task is to determine the result of the game if both players play optimally.",
    "tutorial": "Note that it makes no sense to use the first type of operation if it does not lead to an instant win, because the opponent can return the previous state of the array with their next move. So the winner is the one who has time to color \"their\" elements in blue first. Let's denote $a$ as the number of elements that only the first player needs to color, $b$ as the number of elements only the second player needs to color, $c$ - both players needs to color. To win, the first player needs to have time to paint $a+c$ elements, and they have no more than $b$ moves to do it, because otherwise the second player can prevent the win of the first player. So the winning condition for the first player is $a+c \\le b$. Similarly, for the second player, with the only difference that they have $1$ move less (because they go second), which means the condition is $b+c < a$. If none of these conditions are met, then neither player has a winning strategy, which means they will both reduce the game to a draw.",
    "code": "for tc in range(int(input())):\n  n = int(input())\n  p = list(map(int, input().split()))\n  a, b, c = 0, 0, 0\n  for i in range(n):\n    if p[i] != i + 1 and p[i] != n - i:\n      c += 1\n    elif p[i] != i + 1:\n      a += 1\n    elif p[i] != n - i:\n      b += 1\n  if a + c <= b:\n    print(\"First\")\n  elif b + c < a:\n    print(\"Second\")\n  else:\n    print(\"Tie\")",
    "tags": [
      "games"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1772",
    "index": "F",
    "title": "Copy of a Copy of a Copy",
    "statement": "It all started with a black-and-white picture, that can be represented as an $n \\times m$ matrix such that all its elements are either $0$ or $1$. The rows are numbered from $1$ to $n$, the columns are numbered from $1$ to $m$.\n\nSeveral operations were performed on the picture (possibly, zero), each of one of the two kinds:\n\n- choose a cell such that it's not on the border (neither row $1$ or $n$, nor column $1$ or $m$) and it's surrounded by four cells of the opposite color (four zeros if it's a one and vice versa) and paint it the opposite color itself;\n- make a copy of the current picture.\n\nNote that the order of operations could be arbitrary, they were not necessarily alternating.\n\nYou are presented with the outcome: all $k$ copies that were made. Additionally, you are given the initial picture. However, all $k+1$ pictures are shuffled.\n\nRestore the sequence of the operations. If there are multiple answers, print any of them. The tests are constructed from the real sequence of operations, i. e. at least one answer always exists.",
    "tutorial": "Notice the following: once you apply the recolor operation to some cell, you can never recolor it again. That happens because you can't recolor its neighbors too as each of them has at least one neighbor of the same color - this cell itself. In particular, that implies that applying a recolor operation always decreases the possible number of operations that can be made currently. It doesn't always decrease them by $1$: from $1$ to $5$ operations can become unavailable, but it always decreases. That gives us an order of copies. Just sort them in the decreasing order of the number of recolor operations that can be made currently. If the numbers are the same, the copies must be equal, so their order doesn't matter. The only thing remains is to apply the operations. Turns out, their order doesn't matter at all. Consider all different cells for a pair of adjacent pictures. It's never possible that there are two different cells that are adjacent to each other. Thus, no operation can interfere with another one. Just print all positions of different cells in any order you want and make a copy. Overall complexity: $O(nmk + k \\log k)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++)\n\nstruct op{\n    int t, x, y, i;\n};\n\nint dx[] = {-1, 0, 1, 0};\nint dy[] = {0, 1, 0, -1};\n\nint main(){\n    int n, m, k;\n    cin >> n >> m >> k;\n    vector<vector<string>> a(k + 1, vector<string>(n));\n    forn(z, k + 1) forn(i, n)\n        cin >> a[z][i];\n    \n    vector<int> cnt(k + 1);\n    forn(z, k + 1){\n        for (int i = 1; i < n - 1; ++i){\n            for (int j = 1; j < m - 1; ++j){\n                bool ok = true;\n                forn(t, 4)\n                    ok &= a[z][i][j] != a[z][i + dx[t]][j + dy[t]];\n                cnt[z] += ok;\n            }\n        }\n    }\n    \n    vector<int> ord(k + 1);\n    iota(ord.begin(), ord.end(), 0);\n    sort(ord.begin(), ord.end(), [&cnt](int x, int y){\n        return cnt[x] > cnt[y];\n    });\n    \n    vector<op> ops;\n    forn(z, k){\n        forn(i, n) forn(j, m) if (a[ord[z]][i][j] != a[ord[z + 1]][i][j]){\n            a[ord[z]][i][j] ^= '0' ^ '1';\n            ops.push_back({1, i + 1, j + 1, -1});\n        }\n        ops.push_back({2, -1, -1, ord[z + 1] + 1});\n    }\n    \n    cout << ord[0] + 1 << '\\n';\n    cout << ops.size() << '\\n';\n    for (auto it : ops){\n        cout << it.t << \" \";\n        if (it.t == 1)\n            cout << it.x << \" \" << it.y << '\\n';\n        else\n            cout << it.i << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "implementation",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1772",
    "index": "G",
    "title": "Gaining Rating",
    "statement": "Monocarp is playing chess on one popular website. He has $n$ opponents he can play with. The $i$-th opponent has rating equal to $a_i$. Monocarp's initial rating is $x$. Monocarp wants to raise his rating to the value $y$ ($y > x$).\n\nWhen Monocarp is playing against one of the opponents, he will win if his \\textbf{current} rating is bigger or equal to the opponent's rating. If Monocarp wins, his rating is increased by $1$, otherwise it is decreased by $1$. The rating of his opponent does not change.\n\nMonocarp wants to gain rating $y$ playing as few games as possible. But he can't just grind it, playing against weak opponents. The website has a rule that you should play against all opponents as evenly as possible. Speaking formally, if Monocarp wants to play against an opponent $i$, there should be no other opponent $j$ such that Monocarp has played more games against $i$ than against $j$.\n\nCalculate the minimum possible number of games Monocarp needs to gain rating $y$ or say it's impossible. Note that ratings of Monocarp's opponents don't change, while Monocarp's rating does change.",
    "tutorial": "After parsing the statement, you can understand that Monocarp plays cyclically: in one cycle, he chooses some order of opponents and play with them in that order. Then repeats again and again, until he gains desired rating at some moment. So, firstly, let's prove that (in one cycle) it's optimal to play against opponents in increasing order of their skills. Suppose you play with opponents in some order $ord$ and there is a position where $a[ord_i] > a[ord_{i+1}]$, if you swap $ord_i$ and $ord_{i+1}$ you won't lose anything and may even gain extra wins. It means that the total gain after playing one cycle in increasing order in greater or equal than playing in any other order. In other words, we can sort array $a$ and play against them cyclically in that order. Monocarp's list of games will look like several full cycles and some prefix. The problem is that there can be many cycles, and we need to skip them in a fast way. How one cycle looks? Monocarp starts with some $x$ wins first $p$ games and then loses all other games ($m$ games where $m = n - p$). The maximum rating he gains is $x + p$ and the resulting rating after all games is $x + p - m$. We can already find several conditions of leaving a cycle: if $x + p \\ge y$ then Monocarp gets what he wants and stops; otherwise, if $x + p - m \\le x$ (or $p - m \\le 0$) he will never gain the desired rating, since in the next cycle the number of wins $p' \\le p$, since his starting rating $x + p - m \\le x$. Otherwise, if $x + p < y$ and $p - m > 0$, he will start one more cycle with rating $x' = x + p - m$ and will gain the desired rating $y$, eventually. So, how to find the number of games $p$ he will win for a starting rating $x$? Let's calculate two values for a given sorted skill array $a$: for each $i$ let's calculate $t_i$ - the minimum starting rating Monocarp need to win opponent $i$ (and all opponent before) and $b_i$ - the rating he'll get after winning the $i$-th opponent. We can calculate these values in one iteration (we'll use $0$-indexation): $t_0 = a_0$, $b_0 = a_0 + 1$; then for each $i > 0$ if $b_{i - 1} \\ge a_i$ then $t_i = t_{i - 1}$ and $b_i = b_{i - 1} + 1$, otherwise $t_i = a_i - i$ and $b_i = a_i + 1$. Now, knowing values $t_i$ it's easy to find the number of wins $p$ for a starting rating $x$: $p$ is equal to minimum $j$ such that $t_j > x$ (don't forget, $0$-indexation). Or the first position in array $t$ with value strictly greater than $x$. We can search it with standard $\\text{upper_bound}$ function, since array $t$ is sorted. Okay, we found the number of wins $p$ for the current $x$. Let's just calculate how many cycles $k$ Monocarp will make with exactly $p$ wins. There are only two conditions that should be met in order to break this cycle: either Monocarp reaches rating $y$ - it can be written as inequality $x + k (p - m) + p \\ge y$, or the number of wins increases (starting rating becomes greater or equal than $t_p$), i.e. $x + k (p - m) \\ge t_p$. From the first inequality, we get minimum $k_1 = \\left\\lceil \\frac{y - x - p}{p - m} \\right\\rceil$ and from the second one - $k_2 = \\left\\lceil \\frac{t_p - x}{p - m} \\right\\rceil$. As a result, we can claim that Monocarp will repeat the current cycle exactly $k = \\min(k_1, k_2)$ times and either finish in the next turn or the number of wins will change. So, we can skip these $k$ equal cycles: we can increase answer by $kn$ and current rating by $k(p - m)$. Since we skip equal cycles, then at each step we either finish (with success or $-1$), or the number of wins $p$ increases. Since $p$ is bounded by $n$, we will make no more than $n$ skips, and total complexity is $O(n \\log n)$ because of initial sorting and calls of $\\text{upper_bound}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\ntypedef long long li;\n\nint n;\nli x, y;\nvector<li> a;\n\ninline bool read() {\n    if(!(cin >> n >> x >> y))\n        return false;\n    a.resize(n);\n    fore (i, 0, n)\n        cin >> a[i];\n    return true;\n}\n\nli ceil(li a, li b) {\n    assert(a >= 0 && b >= 0);\n    return (a + b - 1) / b;\n}\n\ninline void solve() {\n    sort(a.begin(), a.end());\n    \n    vector<li> t(n), b(n);\n    fore (i, 0, n) {\n        if (i > 0 && b[i - 1] >= a[i]) {\n            t[i] = t[i - 1];\n            b[i] = b[i - 1] + 1;\n        } else {\n            t[i] = a[i] - i;\n            b[i] = a[i] + 1;\n        }\n    }\n    \n    li ans = 0;\n    while (x < y) {\n        int pos = int(upper_bound(t.begin(), t.end(), x) - t.begin());\n        \n        li p = pos, m = n - pos;\n        if (x + p >= y) {\n            cout << ans + (y - x) << endl;\n            return;\n        }\n        if (p <= m) {\n            cout << -1 << endl;\n            return;\n        }\n        \n        //1. x + k(p - m) + p >= y\n        li k = ceil(y - x - p, p - m);\n        if (pos < n) {\n            //2. x + k(p - m) >= t[pos]\n            k = min(k, ceil(t[pos] - x, p - m));\n        }\n        ans += k * n;\n        //x + k(p - m) < y, since 1. and p >= p - m\n        x += k * (p - m);\n    }\n    assert(false);\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    int t; cin >> t;\n    while (t--) {\n        read();\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1774",
    "index": "A",
    "title": "Add Plus Minus Sign",
    "statement": "AquaMoon has a string $a$ consisting of only $0$ and $1$. She wants to add $+$ and $-$ between all pairs of consecutive positions to make the absolute value of the resulting expression as small as possible. Can you help her?",
    "tutorial": "The answer is the number of $1$s modulo $2$. We can get that by adding '-' before the $\\text{2nd}, \\text{4th}, \\cdots, 2k\\text{-th}$ $1$, and '+' before the $\\text{3rd}, \\text{5th}, \\cdots, 2k+1\\text{-th}$ $1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nchar c[1005];\nint main() {\n  int t;\n  scanf(\"%d\", &t);\n  int n;\n  while (t--) {\n    scanf(\"%d\", &n);\n    scanf(\"%s\", c + 1);\n    int u = 0;\n    for (int i = 1; i <= n; ++i) {\n      bool fl = (c[i] == '1') && u;\n      u ^= (c[i] - '0');\n      if (i != 1) putchar(fl ? '-' : '+');\n    }\n    putchar('\\n');\n  }\n}\n",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1774",
    "index": "B",
    "title": "Coloring",
    "statement": "Cirno_9baka has a paper tape with $n$ cells in a row on it. As he thinks that the blank paper tape is too dull, he wants to paint these cells with $m$ kinds of colors. For some aesthetic reasons, he thinks that the $i$-th color must be used exactly $a_i$ times, and for every $k$ consecutive cells, their colors have to be distinct.\n\nHelp Cirno_9baka to figure out if there is such a way to paint the cells.",
    "tutorial": "First, We can divide $n$ cells into $\\left\\lceil\\frac{n}{k}\\right\\rceil$ segments that except the last segment, all segments have length $k$. Then in each segment, the colors in it are pairwise different. It's easy to find any $a_i$ should be smaller than or equal to $\\left\\lceil\\frac{n}{k}\\right\\rceil$. Then we can count the number of $a_i$ which is equal to $\\left\\lceil\\frac{n}{k}\\right\\rceil$. This number must be smaller than or equal to $n \\bmod k$, which is the length of the last segment. All $a$ that satisfies the conditions above is valid. We can construct a coloring using the method below: First, we pick out all colors $i$ that $a_i=\\left\\lceil\\frac{n}{k}\\right\\rceil$, then we use color $i$ to color the $j$-th cell in each segment. Then we pick out all colors $i$ that $a_i<\\left\\lceil\\frac{n}{k}\\right\\rceil-1$ and use these colors to color the rest of cells with cyclic order(i.e. color $j$-th cell of the first segment, of second the segment ... of the $\\left\\lceil\\frac{n}{k}\\right\\rceil$ segment, and let $j+1$. when one color is used up, we begin to use the next color) At last, we pick out all colors $i$ that $a_i=\\left\\lceil\\frac{n}{k}\\right\\rceil-1$, and color them with the cyclic order. This method will always give a valid construction.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n  int t;\n  scanf(\"%d\", &t);\n  while (t--) {\n    int n, m, k;\n    scanf(\"%d %d %d\", &n, &m, &k);\n    int fl = 0;\n    for (int i = 1; i <= m; ++i) {\n      int a;\n      scanf(\"%d\", &a);\n      if (a == (n + k - 1) / k) ++fl;\n      if (a > (n + k - 1) / k) fl = 1 << 30;\n    }\n    puts(fl <= (n - 1) % k + 1 ? \"YES\" : \"NO\");\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1774",
    "index": "C",
    "title": "Ice and Fire",
    "statement": "Little09 and his friends are playing a game. There are $n$ players, and the temperature value of the player $i$ is $i$.\n\nThe types of environment are expressed as $0$ or $1$. When two players fight in a specific environment, if its type is $0$, the player with a lower temperature value in this environment always wins; if it is $1$, the player with a higher temperature value in this environment always wins. The types of the $n-1$ environments form a binary string $s$ with a length of $n-1$.\n\nIf there are $x$ players participating in the game, there will be a total of $x-1$ battles, and the types of the $x-1$ environments will be the first $x-1$ characters of $s$. While there is more than one player left in the tournament, choose any two remaining players to fight. The player who loses will be eliminated from the tournament. The type of the environment of battle $i$ is $s_i$.\n\nFor each $x$ from $2$ to $n$, answer the following question: if all players whose temperature value does not exceed $x$ participate in the game, how many players have a chance to win?",
    "tutorial": "We define $f_i$ to mean that the maximum $x$ satisfies $s_{i-x+1}=s_{i-x+2}=...=s_{i}$. It can be proved that for $x$ players, $f_{x-1}$ players are bound to lose and the rest have a chance to win. So the answer to the first $i$ battles is $ans_i=i-f_i+1$. Next, we prove this conclusion. Suppose there are $n$ players and $n-1$ battles, and $s_{n-1}=1$, and there are $x$ consecutive $1$ at the end. If $x=n-1$, then obviously only the $n$-th player can win. Otherwise, $s_{n-1-x}$ must be 0. Consider the following facts: Players $1$ to $x$ have no chance to win. If the player $i$ ($1\\le i\\le x$) can win, he must defeat the player whose temperature value is lower than him in the last $x$ battles. However, in total, only the $i-1$ player's temperature value is lower than his. Because $i-1<x$, the $i$-th player cannot win. Players $1$ to $x$ have no chance to win. If the player $i$ ($1\\le i\\le x$) can win, he must defeat the player whose temperature value is lower than him in the last $x$ battles. However, in total, only the $i-1$ player's temperature value is lower than his. Because $i-1<x$, the $i$-th player cannot win. Players from $x+1$ to $n$ have a chance to win. For the player $i$ ($x+1\\le i\\le n$), we can construct: in the first $n-2-x$ battles, we let all players whose temperature value in $[x+1,n]$ except the player $i$ fight so that only one player will remain. In the $(n-1-x)$-th battle, we let the remaining player fight with the player $1$. Since $s_{n-1-x}=0$, the player $1$ will win. Then there are only the first $x$ players and the player $i$ in the remaining $x$ battles, so the player $i$ can win. Players from $x+1$ to $n$ have a chance to win. For the player $i$ ($x+1\\le i\\le n$), we can construct: in the first $n-2-x$ battles, we let all players whose temperature value in $[x+1,n]$ except the player $i$ fight so that only one player will remain. In the $(n-1-x)$-th battle, we let the remaining player fight with the player $1$. Since $s_{n-1-x}=0$, the player $1$ will win. Then there are only the first $x$ players and the player $i$ in the remaining $x$ battles, so the player $i$ can win. For $s_{n-1}=0$, the situation is similar and it will not be repeated here.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 300005;\nint T, n, ps[2];\nchar a[N];\n\nvoid solve() {\n  scanf(\"%d %s\", &n, a + 1);\n  ps[0] = ps[1] = 0;\n  for (int i = 1; i < n; ++i) {\n    ps[a[i] - 48] = i;\n    if (a[i] == '0')\n      printf(\"%d \", ps[1] + 1);\n    else\n      printf(\"%d \", ps[0] + 1);\n  }\n  putchar('\\n');\n}\nint main() {\n  scanf(\"%d\", &T);\n  while (T--) solve();\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1774",
    "index": "D",
    "title": "Same Count One",
    "statement": "ChthollyNotaSeniorious received a special gift from AquaMoon: $n$ binary arrays of length $m$. AquaMoon tells him that in one operation, he can choose any two arrays and any position $pos$ from $1$ to $m$, and swap the elements at positions $pos$ in these arrays.\n\nHe is fascinated with this game, and he wants to find the minimum number of operations needed to make the numbers of $1$s in all arrays the same. He has invited you to participate in this interesting game, so please try to find it!\n\nIf it is possible, please output specific exchange steps in the format described in the output section. Otherwise, please output $-1$.",
    "tutorial": "Considering that we need to make the number of $1\\text{s}$ in each array the same, we should calculate the sum of $1\\text{s}$, and every array has $sum / n$ $1\\text{s}$. Because only the same position of two different arrays can be selected for exchange each time, for a position $pos$, we traverse each array each time. If the number of $1\\text{s}$ in this array is not enough, then we need to turn some $0\\text{s}$ into $1\\text{s}$; If the number of $1\\text{s}$ in this array is more than we need, then some $1\\text{s}$ should be turned into $0\\text{s}$. It can be proved that as long as the total number of $1\\text{s}$ is a multiple of $n$, the number of $1\\text{s}$ in each array can be made the same through exchanges.",
    "code": "#include <bits/stdc++.h>\n\nint main() {\n  int T;\n  scanf(\"%d\", &T);\n  while (T--) {\n    int n, m;\n    scanf(\"%d %d\", &n, &m);\n    std::vector<std::vector<int>> A(n, std::vector<int>(m, 0));\n    std::vector<int> sum(n, 0);\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j < m; ++j) {\n        scanf(\"%d\", &A[i][j]);\n        sum[i] += A[i][j];\n      }\n    }\n    int tot = 0;\n    for (int i = 0; i < n; ++i) tot += sum[i];\n    if (tot % n) {\n      puts(\"-1\");\n      continue;\n    }\n    tot /= n;\n    std::vector<std::tuple<int, int, int>> ans;\n    std::vector<int> Vg, Vl;\n    Vg.reserve(n), Vl.reserve(n);\n    for (int j = 0; j < m; ++j) {\n      for (int i = 0; i < n; ++i) {\n        if (sum[i] > tot && A[i][j]) Vg.push_back(i);\n        if (sum[i] < tot && !A[i][j]) Vl.push_back(i);\n      }\n      for (int i = 0; i < (int)std::min(Vl.size(), Vg.size()); ++i) {\n        ++sum[Vl[i]], --sum[Vg[i]];\n        ans.emplace_back(Vl[i], Vg[i], j);\n      }\n      Vl.clear(), Vg.clear();\n    }\n    printf(\"%d\\n\", (int)ans.size());\n    for (auto [i, j, k] : ans) printf(\"%d %d %d\\n\", i + 1, j + 1, k + 1);\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1774",
    "index": "E",
    "title": "Two Chess Pieces",
    "statement": "Cirno_9baka has a tree with $n$ nodes. He is willing to share it with you, which means you can operate on it.\n\nInitially, there are two chess pieces on the node $1$ of the tree. In one step, you can choose any piece, and move it to the neighboring node. You are also given an integer $d$. You need to ensure that the distance between the two pieces doesn't \\textbf{ever} exceed $d$.\n\nEach of these two pieces has a sequence of nodes which they need to pass \\textbf{in any order}, and eventually, they have to return to the root. As a curious boy, he wants to know the minimum steps you need to take.",
    "tutorial": "We can find that for any $d$-th ancestor of some $b_i$, the first piece must pass it some time. Otherwise, we will violate the distance limit. The second piece must pass the $d$-th ancestor of each $b_i$ as well. Then we can add the $d$-th ancestor of each $a_i$ to the array $b$, and add the $d$-th ancestor of each $b_i$ to the array $a$. Then we can find now we can find a solution that each piece only needs to visit its nodes using the shortest route, without considering the limit of $d$, and the total length can be easily computed. We can find that if we adopt the strategy that we visit these nodes according to their DFS order(we merge the array of $a$ and $b$, and sort them according to the DFS order, if the first one is from $a$, we try to move the first piece to this position, otherwise use the second piece), and move the other piece one step closer to the present piece only if the next step of the present piece will violate the distance limit, then we can ensure the movement exactly just let each piece visit its necessary node without extra operations.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1e6 + 5;\nint t[N * 2], nxt[N * 2], cnt, h[N];\nint n, d;\nvoid add(int x, int y) {\n  t[++cnt] = y;\n  nxt[cnt] = h[x];\n  h[x] = cnt;\n}\nint a[N], b[N];\nbool f[2][N];\nvoid dfs1(int x, int fa, int dis) {\n  a[dis] = x;\n  if (dis > d)\n    b[x] = a[dis - d];\n  else\n    b[x] = 1;\n  for (int i = h[x]; i; i = nxt[i]) {\n    if (t[i] == fa) continue;\n    dfs1(t[i], x, dis + 1);\n  }\n}\nvoid dfs2(int x, int fa, int tp) {\n  bool u = 0;\n  for (int i = h[x]; i; i = nxt[i]) {\n    if (t[i] == fa) continue;\n    dfs2(t[i], x, tp);\n    u |= f[tp][t[i]];\n  }\n  f[tp][x] |= u;\n}\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(0);\n  cout.tie(0);\n  cin >> n >> d;\n  for (int i = 1; i < n; i++) {\n    int x, y;\n    cin >> x >> y;\n    add(x, y), add(y, x);\n  }\n  dfs1(1, 0, 1);\n  for (int i = 0; i <= 1; i++) {\n    int num;\n    cin >> num;\n    for (int j = 1; j <= num; j++) {\n      int x;\n      cin >> x;\n      f[i][x] = 1, f[i ^ 1][b[x]] = 1;\n    }\n  }\n  for (int i = 0; i <= 1; i++) dfs2(1, 0, i);\n  int ans = 0;\n  for (int i = 0; i <= 1; i++)\n    for (int j = 2; j <= n; j++)\n      if (f[i][j]) ans += 2;\n  cout << ans;\n  return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1774",
    "index": "F1",
    "title": "Magician and Pigs (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$ and $x$. You can make hacks only if both versions of the problem are solved.}\n\nLittle09 has been interested in magic for a long time, and it's so lucky that he meets a magician! The magician will perform $n$ operations, each of them is one of the following three:\n\n- $1\\ x$: Create a pig with $x$ Health Points.\n- $2\\ x$: Reduce the Health Point of all living pigs by $x$.\n- $3$: Repeat all previous operations. Formally, assuming that this is the $i$-th operation in the operation sequence, perform the first $i-1$ operations (including \"Repeat\" operations involved) in turn.\n\nA pig will die when its Health Point is less than or equal to $0$.\n\nLittle09 wants to know how many living pigs there are after all the operations. Please, print the answer modulo $998\\,244\\,353$.",
    "tutorial": "Let $X=\\max x$. Think about what 'Repeat' is doing. Assuming the total damage is $tot$ ($tot$ is easy to calculate because it will be multiplied by $2$ after each 'Repeat' and be added after each 'Attack'). After repeating, each pig with a current HP of $w$ ($w > tot$) will clone a pig with a HP of $w-tot$. Why? 'Repeat' will do what you just did again, so each original pig will certainly create a pig the same as it, and it will be attacked by $tot$, so it can be considered that a pig with $w-tot$ HP has been cloned. Next, the problem is to maintain a multiset $S$, which supports: adding a number, subtracting $x$ for all numbers, and inserting each number after subtracting $tot$. Find the number of positive elements in the final multiset. $tot$ in 'Repeat' after the first 'Attack' will multiply by $2$ every time, so it will exceed $X$ in $O(\\log X)$ times. That is, only $O(\\log X)$ 'Repeat' operations are effective. So we can maintain $S$ in brute force. Every time we do 'Repeat', we take out all the numbers larger than $tot$, then subtract and insert them again. Note that we may do some 'Repeat' operations when $tot=0$, which will result in the number of pigs generated before multiplying by $2$. Therefore, we also need to maintain the total multiplication. If you use map to maintain it, the time complexity is $O((n+X)\\log ^2X)$. It can pass F1. You can also use some ways to make the time complexity $O((n+X)\\log X)$.",
    "code": "// Author: Little09\n// Problem: F. Magician and Pigs (Easy Version)\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\nconst ll mod = 998244353, inv = (mod + 1) / 2;\nint n;\nmap<ll, ll> s;\nll tot, mul = 1, ts = 1;\ninline void add(ll &x, ll y) { (x += y) >= mod && (x -= mod); }\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(0);\n  cout.tie(0);\n  cin >> n;\n  while (n--) {\n    int op;\n    cin >> op;\n    if (op == 1) {\n      ll x;\n      cin >> x;\n      add(s[x + tot], ts);\n    } else if (op == 2) {\n      ll x;\n      cin >> x;\n      tot += x;\n    } else if (tot <= 2e5) {\n      if (tot == 0)\n        mul = mul * 2 % mod, ts = ts * inv % mod;\n      else {\n        for (ll i = tot + 2e5; i > tot; i--) add(s[i + tot], s[i]);\n        tot *= 2;\n      }\n    }\n  }\n  ll res = 0;\n  for (auto i : s)\n    if (i.first > tot) add(res, i.second);\n  res = res * mul % mod;\n  cout << res;\n  return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1774",
    "index": "F2",
    "title": "Magician and Pigs (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$ and $x$. You can make hacks only if both versions of the problem are solved.}\n\nLittle09 has been interested in magic for a long time, and it's so lucky that he meets a magician! The magician will perform $n$ operations, each of them is one of the following three:\n\n- $1\\ x$: Create a pig with $x$ Health Points.\n- $2\\ x$: Reduce the Health Point of all living pigs by $x$.\n- $3$: Repeat all previous operations. Formally, assuming that this is the $i$-th operation in the operation sequence, perform the first $i-1$ operations (including \"Repeat\" operations involved) in turn.\n\nA pig will die when its Health Point is less than or equal to $0$.\n\nLittle09 wants to know how many living pigs there are after all the operations. Please, print the answer modulo $998\\,244\\,353$.",
    "tutorial": "For F1, there is another way. Consider every pig. When Repeat, it will clone, and when Attack, all its clones will be attacked together. Therefore, considering all the operations behind each pig, you can choose to reduce $x$ (the current total damage) or not when Repeat, and you must choose to reduce $x$ when Attack. Any final choice will become a pig (living or not). We just need to calculate how many Repeat choices can make a living pig. For Repeat of $x=0$, there is no difference between the two choices. For the Repeat of $x\\geq 2\\times 10^5$, it is obvious that you can only choose not to reduce $x$. Except for the above parts, there are only $O(\\log x)$ choices. You can just find a subset or use knapsack to solve it. It can also pass F1 and the time complexity is $O((n+X)\\log X)$. The bottleneck of using this method to do F2 lies in the backpack. The problem is that we need to find how many subsets whose sum $<x$ of of a set whose size is $O(\\log X)$. Observation: if you sort the set, each element is greater than the sum of all elements smaller than it. We can use observation to solve the problem. Consider each element from large to small. Suppose you now need to find elements and subsets of $<x$. If the current element $\\ge x$, it must not be selected; If the current element $<x$, if it is not selected, the following elements can be selected at will (the sum of all the following elements is less than it). It can be recursive. Thus, for a given $x$, we can find the number of subsets whose sum $<x$ within $O(\\log X)$. The time complexity is $O(n\\log X)$.",
    "code": "// Author: Little09\n// Problem: F. Magician and Pigs\n\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n#define mem(x) memset(x, 0, sizeof(x))\n#define endl \"\\n\"\n#define printYes cout << \"Yes\\n\"\n#define printYES cout << \"YES\\n\"\n#define printNo cout << \"No\\n\"\n#define printNO cout << \"NO\\n\"\n#define lowbit(x) ((x) & (-(x)))\n#define pb push_back\n#define mp make_pair\n#define pii pair<int, int>\n#define fi first\n#define se second\n\nconst ll inf = 1000000000000000000;\n// const ll inf=1000000000;\nconst ll mod = 998244353;\n// const ll mod=1000000007;\n\nconst int N = 800005;\nint n, m;\nll a[N], b[N], c[N], cnt, s[N], d[N], cntd;\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(0);\n  cout.tie(0);\n  cin >> n;\n  ll maxs = 1e9, sum = 0;\n  for (int i = 1; i <= n; i++) {\n    cin >> a[i];\n    if (a[i] != 3) cin >> b[i];\n    if (a[i] == 2) sum += b[i];\n    sum = min(sum, maxs);\n    if (a[i] == 3) b[i] = sum, sum = sum * 2;\n    sum = min(sum, maxs);\n  }\n  sum = 0;\n  ll res = 1, ans = 0;\n  for (int i = n; i >= 1; i--) {\n    if (a[i] == 2)\n      sum += b[i];\n    else if (a[i] == 3) {\n      if (b[i] == maxs) continue;\n      if (b[i] == 0) {\n        res = res * 2 % mod;\n        continue;\n      }\n      c[++cnt] = b[i];\n    } else {\n      b[i] -= sum;\n      if (b[i] <= 0) continue;\n      ll su = 0, r = b[i];\n      for (int j = 1; j <= cnt; j++) {\n        if (r > c[j]) {\n          su = (su + (1ll << (cnt - j))) % mod;\n          r -= c[j];\n        }\n      }\n      su = (su + 1) % mod;\n      ans = (ans + su * res) % mod;\n    }\n  }\n  cout << ans;\n  return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1774",
    "index": "G",
    "title": "Segment Covering",
    "statement": "ChthollyNotaSeniorious gives DataStructures a number axis with $m$ distinct segments on it. Let $f(l,r)$ be the number of ways to choose an even number of segments such that the union of them is exactly $[l,r]$, and $g(l,r)$ be the number of ways to choose an odd number of segments such that the union of them is exactly $[l,r]$.\n\nChthollyNotaSeniorious asked DataStructures $q$ questions. In each query, ChthollyNotaSeniorious will give DataStructures two numbers $l, r$, and now he wishes that you can help him find the value $f(l,r)-g(l,r)$ modulo $998\\,244\\,353$ so that he wouldn't let her down.",
    "tutorial": "If there exist two segments $(l_1, r_1), (l_2, r_2)$ such that $l_1 \\le l_2 \\le r_2 \\le r_1$ and we choose $(l_1, r_1)$, number of ways of choosing $(l_2, r_2)$ at the same time will be equal to that of not choosing. Hence if we choose $(l_1, r_1)$, the signed number of ways will be $0$. So we can delete $(l_1, r_1)$. It can be proved that the absolute value of every $f_{l,r} - g_{l,r}$ doesn't exceed $1$. Proof: First, find segments $(l_i, r_i)$ which are completely contained by $(l, r)$. Let us sort $(l_i, r_i)$ in ascending order of $l_i$. As there does not exist a segment that contains another, $r_i$ are also sorted. Assume that $l_2 < l_3 \\leq r_1$ and $r_3 \\geq r_2$. If we choose segments $1$ and $3$, choosing $2$ or not will be the same except for the sign. So $3$ is useless. So we can delete such useless segments. After the process, $l_3 > r_1, l_4 > r_2, \\cdots$ will be held. If $[l_1, r_1] \\cup [l_2, r_2] \\cup \\cdots \\cup [l_k, r_k] = [l, r]$, answer will be $(-1)^k$, else answer will be $0$. This picture shows what the segments eventually are like: For $[l_i, r_i]$, we can find the lowest $j$ such that $l_j > r_i$ and construct a tree by linking such $i$ and $j$. Then the LCA of $1$ and $2$ will be $5$, where the answer becomes 0. So we can get the answer of $(ql, qr)$ quickly by simply finding the LCA of two segments -- the segment starting with $ql$ (if no segment starts with $ql$, the answer is $0$), and the first segment whose $l$ is greater than $ql$ (if it do not intersect with the previous segment, the answer is $0$). And find the segment ending with $qr$. If it is on the path of the two segments, the answer will be $\\pm 1$. Else, the answer will be $0$.",
    "code": "#include <bits/stdc++.h>\n\n#define File(a) freopen(a \".in\", \"r\", stdin), freopen(a \".out\", \"w\", stdout)\n\nusing tp = std::tuple<int, int, int>;\nconst int sgn[] = {1, 998244352};\nconst int N = 200005;\n\nint x[N], y[N];\nstd::vector<tp> V;\nbool del[N];\nint fa[20][N];\nint m, q;\n\nint main() {\n  scanf(\"%d %d\", &m, &q);\n  for (int i = 1; i <= m; ++i)\n    scanf(\"%d %d\", x + i, y + i), V.emplace_back(y[i], -x[i], i);\n  std::sort(V.begin(), V.end());\n  int mxl = 0;\n  for (auto [y, x, i] : V) {\n    if (-x <= mxl) del[i] = true;\n    mxl = std::max(mxl, -x);\n  }\n  V.clear();\n  x[m + 1] = y[m + 1] = 1e9 + 1;\n  for (int i = 1; i <= m + 1; ++i) {\n    if (!del[i]) V.emplace_back(x[i], y[i], i);\n  }\n  std::sort(V.begin(), V.end());\n  for (auto [x, y, id] : V) {\n    int t = std::get<2>(*std::lower_bound(V.begin(), V.end(), tp{y + 1, 0, 0}));\n    fa[0][id] = t;\n  }\n  fa[0][m + 1] = m + 1;\n  for (int k = 1; k <= 17; ++k) {\n    for (int i = 1; i <= m + 1; ++i) fa[k][i] = fa[k - 1][fa[k - 1][i]];\n  }\n  for (int i = 1; i <= q; ++i) {\n    int l, r;\n    scanf(\"%d %d\", &l, &r);\n    int u = std::lower_bound(V.begin(), V.end(), tp{l, 0, 0}) - V.begin(), v = u + 1;\n    u = std::get<2>(V[u]);\n    if (x[u] != l || y[u] > r) {\n      puts(\"0\");\n      continue;\n    }\n    if (y[u] == r) {\n      puts(\"998244352\");\n      continue;\n    }\n    v = std::get<2>(V[v]);\n    if (y[v] > r || x[v] > y[u]) {\n      puts(\"0\");\n      continue;\n    }\n    int numu = 0, numv = 0;\n    for (int i = 17; i >= 0; --i) {\n      if (y[fa[i][u]] <= r) {\n        u = fa[i][u];\n        numu += !i;\n      }\n    }\n    for (int i = 17; i >= 0; --i) {\n      if (y[fa[i][v]] <= r) {\n        v = fa[i][v];\n        numv += !i;\n      }\n    }\n    if (u == v || (y[u] != r && y[v] != r))\n      puts(\"0\");\n    else\n      printf(\"%d\\n\", sgn[numu ^ numv]);\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1774",
    "index": "H",
    "title": "Maximum Permutation",
    "statement": "Ecrade bought a deck of cards numbered from $1$ to $n$. Let the value of a permutation $a$ of length $n$ be $\\min\\limits_{i = 1}^{n - k + 1}\\ \\sum\\limits_{j = i}^{i + k - 1}a_j$.\n\nEcrade wants to find the most valuable one among all permutations of the cards. However, it seems a little difficult, so please help him!",
    "tutorial": "When it seems to be hard to come up with the whole solution directly, simplified questions can often be a great helper. So first let us consider the case where $n$ is the multiple of $k$. Let $t=\\frac{n}{k}$. What is the largest value one can obtain theoretically? Pick out $t$ subsegments $a_{[1:k]},a_{[k+1:2k]},\\dots,a_{[n-k+1:n]}$, and one can see that the answer cannot be greater than the average value of the sum of each subsegment, that is $\\frac{n(n+1)}{2t}=\\frac{k(n+1)}{2}$. If $k$ is even, one can construct $a=[1,n,2,n-1,3,n-2,\\dots,\\frac{n}{2},\\frac{n}{2}+1]$ to reach the maximum value. For easy understanding let us put $a_{[1:k]},a_{[k+1:2k]},\\dots,a_{[n-k+1:n]}$ into a $t\\times k$ table from top to bottom like this: Note that the difference value between two consecutive subsegments is equal to the difference value between two values in the same column in this table. It inspires us to fill in the last $k-3$ columns in an S-shaped way like this: Then our goal is to split the remaining $3t$ numbers into $3$ groups and minimize the difference value between the sum of each group. If $n$ is odd, the theoretical maximum value mentioned above is an integer, and the sum of each group must be equal to reach that value. Otherwise, the theoretical maximum value mentioned above is not an integer, and the sum of each group cannot be determined. So let us first consider the case where $n$ is odd. A feasible approach to split the numbers is as follows: $(1,\\frac{3t+1}{2},3t),(3,\\frac{3t-1}{2},3t-1),\\dots,(t,t+1,\\frac{5t+1}{2}),(2,2t,\\frac{5t-1}{2}),(4,2t-1,\\frac{5t-3}{2}),\\dots,(t-1,\\frac{3t+3}{2},2t+1)$ Then fill them into the table: Similarly, one can come up with an approach when $n$ is even: Okay, it's time for us to go back to the original problem. Let $n=qk+r\\ (r,q\\in \\mathbb{N},1\\le r<k)$. Split $n$ elements like this: As shown in the picture, there are $(q+1)$ red subsegments with $r$ elements each, and $q$ blue subsegments with $(k-r)$ elements each. What is the largest value one can obtain theoretically now? Pick out $q$ non-intersecting subsegments consisting of a whole red subsegment and a whole blue segement each, and one can see that the answer cannot be greater than the average value of the sum of each subsegment, that is the sum of $1 \\thicksim n$ subtracted by the sum of any whole red subsegment, then divide by $q$. Similarly, the answer cannot be greater than the sum of $1 \\thicksim n$ added by the sum of any whole blue subsegment, then divide by $(q+1)$. Thus, our goal is to make the maximum sum of each red subsegment the minimum, and make the minimum sum of each blue subsegment the maximum. Now here comes an interesting claim: it can be proved that, If $r\\neq 1$ and $k-r\\neq 1$, one can fill the red subsegments using the method when $n$ is the multiple of $k$ (here $n'=(q+1)r,k'=r$ ) with $1\\thicksim (q+1)r$, and the blue subsegments (here $n'=q(k-r),k'=k-r$ ) with the remaining numbers; If $r\\neq 1$ and $k-r\\neq 1$, one can fill the red subsegments using the method when $n$ is the multiple of $k$ (here $n'=(q+1)r,k'=r$ ) with $1\\thicksim (q+1)r$, and the blue subsegments (here $n'=q(k-r),k'=k-r$ ) with the remaining numbers; If $r=1$, one can fill the red subsegments with $1\\thicksim (q+1)$ from left to right, and the first element of the blue subsegments with $(q+2)\\thicksim (2q+1)$ from right to left, and the blue subsegments without the first element using the method when $n$ is the multiple of $k$ (here $n'=q(k-2),k'=k-2$ ) with the remaining numbers; If $r=1$, one can fill the red subsegments with $1\\thicksim (q+1)$ from left to right, and the first element of the blue subsegments with $(q+2)\\thicksim (2q+1)$ from right to left, and the blue subsegments without the first element using the method when $n$ is the multiple of $k$ (here $n'=q(k-2),k'=k-2$ ) with the remaining numbers; If $k-r=1$ and $q=1$, one can let $a_k=n$, and fill the rest two subsegments using the method when $n$ is the multiple of $k$ (here $n'=n-1,k'=k-1$ ) with the remaining numbers; If $k-r=1$ and $q=1$, one can let $a_k=n$, and fill the rest two subsegments using the method when $n$ is the multiple of $k$ (here $n'=n-1,k'=k-1$ ) with the remaining numbers; If $k-r=1$ and $q>1$, one can fill the blue subsegments with $(n-q+1)\\thicksim n$ from right to left, and the first element of the red subsegments with $1\\thicksim (q+1)$ from right to left, and the red subsegments without the first element using the method when $n$ is the multiple of $k$ (here $n'=(q+1)(r-1),k'=r-1$ ) with the remaining numbers, If $k-r=1$ and $q>1$, one can fill the blue subsegments with $(n-q+1)\\thicksim n$ from right to left, and the first element of the red subsegments with $1\\thicksim (q+1)$ from right to left, and the red subsegments without the first element using the method when $n$ is the multiple of $k$ (here $n'=(q+1)(r-1),k'=r-1$ ) with the remaining numbers, then the constraints can both be satisfied and the value of the permutation is theoretically maximum. The proof is omitted here. Time complexity: $O(\\sum n)$ Bonus: solve the problem if $k\\ge 2$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\nll t,n,k,seq[100009],ans[100009];\ninline ll read(){\n  ll s = 0,w = 1;\n  char ch = getchar();\n  while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n  while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n  return s * w;\n}\n\nll f(ll x,ll y,ll k){return (x - 1) * k + y;}\nvoid get(ll n,ll k){\n  if (!(k & 1)){\n    for (ll i = 1;i <= n >> 1;i += 1) seq[(i << 1) - 1] = i,seq[i << 1] = n + 1 - i;\n    return;\n  }\n  ll m = n / k,cur = 3 * m;\n  for (ll i = 4;i <= k;i += 1){\n    if (i & 1) for (ll j = m;j >= 1;j -= 1) seq[f(j,i,k)] = ++ cur;\n    else for (ll j = 1;j <= m;j += 1) seq[f(j,i,k)] = ++ cur;\n  }\n  for (ll i = 1;i <= (m + 1 >> 1);i += 1){\n    seq[f(i,1,k)] = (i << 1) - 1;\n    seq[f(i,2,k)] = ((3 * m + 3) >> 1) - i;\n    seq[f(i,3,k)] = 3 * m - i + 1;\n  }\n  for (ll i = (m + 3 >> 1);i <= m;i += 1){\n    ll delta = i - (m + 3 >> 1);\n    seq[f(i,1,k)] = ((3 * m + 3) >> 1) + delta;\n    seq[f(i,2,k)] = (m << 1) + 1 + delta;\n    seq[f(i,3,k)] = m - (m & 1) - (delta << 1);\n  }\n}\nvoid print(){\n  ll res = 0,sum = 0;\n  for (ll i = 1;i <= k;i += 1) sum += ans[i];\n  res = sum;\n  for (ll i = k + 1;i <= n;i += 1) sum += ans[i] - ans[i - k],res = min(res,sum);\n  printf(\"%lld\\n\",res);\n  for (ll i = 1;i <= n;i += 1) printf(\"%lld \",ans[i]);\n  puts(\"\");\n}\n\nint main(){\n  t = read();\n  while (t --){\n    n = read(),k = read();\n    if (!(n % k)){\n      get(n,k);\n      for (ll i = 1;i <= n;i += 1) ans[i] = seq[i];\n      print();\n      continue;\n    }\n    ll q = n / k,r = n % k;\n    if (r == 1){\n      ll cur = 0,delta = (q << 1) + 1;\n      for (ll i = 1;i <= n;i += k) ans[i] = ++ cur;\n      for (ll i = n - k + 1;i >= 2;i -= k) ans[i] = ++ cur;\n      get(q * (k - 2),k - 2),cur = 0;\n      for (ll i = 3;i <= n;i += k) for (ll j = i;j <= i + k - 3;j += 1) ans[j] = seq[++ cur] + delta;\n      print();\n      continue;\n    }\n    if (k - r == 1){\n      if (q == 1){\n        ll cur = 0;\n        ans[k] = n;\n        get(n - 1,k - 1);\n        for (ll i = 1;i < k;i += 1) ans[i] = seq[++ cur];\n        for (ll i = k + 1;i <= n;i += 1) ans[i] = seq[++ cur];\n        print();\n        continue;\n      }\n      ll cur = n + 1,delta = q + 1;\n      for (ll i = k;i <= n;i += k) ans[i] = -- cur;\n      cur = 0;\n      for (ll i = 1;i <= n;i += k) ans[i] = ++ cur;\n      get((q + 1) * (r - 1),r - 1),cur = 0;\n      for (ll i = 2;i <= n;i += k) for (ll j = i;j <= i + r - 2;j += 1) ans[j] = seq[++ cur] + delta;\n      print();\n      continue;\n    }\n    ll cur = 0,delta = (q + 1) * r;\n    get((q + 1) * r,r);\n    for (ll i = 1;i <= n;i += k) for (ll j = i;j <= i + r - 1;j += 1) ans[j] = seq[++ cur];\n    get(q * (k - r),k - r),cur = 0;\n    for (ll i = r + 1;i <= n;i += k) for (ll j = i;j <= i + (k - r) - 1;j += 1) ans[j] = seq[++ cur] + delta;\n    print();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1775",
    "index": "A1",
    "title": "Gardener and the Capybaras (easy version)",
    "statement": "\\textbf{This is an easy version of the problem. The difference between the versions is that the string can be longer than in the easy version. You can only do hacks if both versions of the problem are passed.}\n\nKazimir Kazimirovich is a Martian gardener. He has a huge orchard of binary balanced apple trees.\n\nRecently Casimir decided to get himself three capybaras. The gardener even came up with their names and wrote them down on a piece of paper. The name of each capybara is a non-empty line consisting of letters \"a\" and \"b\".\n\nDenote the names of the capybaras by the lines $a$, $b$, and $c$. Then Casimir wrote the nonempty lines $a$, $b$, and $c$ in a row without spaces. For example, if the capybara's name was \"aba\", \"ab\", and \"bb\", then the string the gardener wrote down would look like \"abaabbb\".\n\nThe gardener remembered an interesting property: either the string $b$ is lexicographically not smaller than the strings $a$ and $c$ at the same time, or the string $b$ is lexicographically not greater than the strings $a$ and $c$ at the same time. In other words, either $a \\le b$ and $c \\le b$ are satisfied, or $b \\le a$ and $b \\le c$ are satisfied (or possibly both conditions simultaneously). Here $\\le$ denotes the lexicographic \"less than or equal to\" for strings. Thus, $a \\le b$ means that the strings must either be equal, or the string $a$ must stand earlier in the dictionary than the string $b$. For a more detailed explanation of this operation, see \"Notes\" section.\n\nToday the gardener looked at his notes and realized that he cannot recover the names because they are written without spaces. He is no longer sure if he can recover the original strings $a$, $b$, and $c$, so he wants to find any triplet of names that satisfy the above property.",
    "tutorial": "To solve this problem, it was enough just to consider all options of splitting the string into three substrings, and there are only $O(n^2)$ ways to do it.",
    "code": "\"#include <bits/stdc++.h>\\n#define sz(x) ((int)x.size())\\nusing namespace std;\\nstring s;\\nint n;\\n\\nvoid Solve() {\\n    cin >> s;\\n    n = sz(s);\\n\\n    if (s[0] == s[1]) {\\n        cout << s[0] << \\\" \\\" << s[1] << \\\" \\\" << s.substr(2) << '\\\\n';\\n        return;\\n    }\\n    if (s[n - 2] == s[n - 1]) {\\n        cout << s.substr(0, n - 2) << \\\" \\\" << s[n - 2] << \\\" \\\" << s[n - 1] << '\\\\n';\\n        return;\\n    }\\n\\n    if (s[0] < s[1]) {\\n        for (int i = 1; i < n - 1; i++) {\\n            if (s[i] > s[i + 1]) {\\n                cout << s.substr(0, i) << \\\" \\\" << s[i] << \\\" \\\" << s.substr(i + 1) << '\\\\n';\\n                return;\\n            }\\n        }\\n    } else {\\n        for (int i = 1; i < n - 1; i++) {\\n            if (s[i] <= s[i + 1]) {\\n                cout << s.substr(0, i) << \\\" \\\" << s[i] << \\\" \\\" << s.substr(i + 1) << '\\\\n';\\n                return;\\n            }\\n        }\\n    }\\n\\n    cout << \\\":(\\\\n\\\";\\n}\\n\\nint main() {\\n    ios_base::sync_with_stdio(false); cin.tie(nullptr);\\n    int t;\\n    cin >> t;\\n\\n    for (int i = 0; i < t; i++) {\\n        Solve();\\n    }\\n\\n    return 0;\\n}\\n\"",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1775",
    "index": "A2",
    "title": "Gardener and the Capybaras (hard version)",
    "statement": "\\textbf{This is an hard version of the problem. The difference between the versions is that the string can be longer than in the easy version. You can only do hacks if both versions of the problem are passed.}\n\nKazimir Kazimirovich is a Martian gardener. He has a huge orchard of binary balanced apple trees.\n\nRecently Casimir decided to get himself three capybaras. The gardener even came up with their names and wrote them down on a piece of paper. The name of each capybara is a non-empty line consisting of letters \"a\" and \"b\".\n\nDenote the names of the capybaras by the lines $a$, $b$, and $c$. Then Casimir wrote the nonempty lines $a$, $b$, and $c$ in a row without spaces. For example, if the capybara's name was \"aba\", \"ab\", and \"bb\", then the string the gardener wrote down would look like \"abaabbb\".\n\nThe gardener remembered an interesting property: either the string $b$ is lexicographically not smaller than the strings $a$ and $c$ at the same time, or the string $b$ is lexicographically not greater than the strings $a$ and $c$ at the same time. In other words, either $a \\le b$ and $c \\le b$ are satisfied, or $b \\le a$ and $b \\le c$ are satisfied (or possibly both conditions simultaneously). Here $\\le$ denotes the lexicographic \"less than or equal to\" for strings. Thus, $a \\le b$ means that the strings must either be equal, or the string $a$ must stand earlier in the dictionary than the string $b$. For a more detailed explanation of this operation, see \"Notes\" section.\n\nToday the gardener looked at his notes and realized that he cannot recover the names because they are written without spaces. He is no longer sure if he can recover the original strings $a$, $b$, and $c$, so he wants to find any triplet of names that satisfy the above property.",
    "tutorial": "Consider five cases to solve the task: If the string starts with $aa$, then we can split it into $a = s[0]$, $b = s[1]$, $c = s[2 ... n - 1]$. If the string starts with $bb$, then we can split it into $a = s[0]$, $b = s[1]$, $c = s[2 ... n - 1]$. If the string starts with $ba$, then we can split it into $a = s[0]$, $b = s[1]$, $c = s[2 ... n - 1]$. If the string starts with $ab$, and then there is another letter a at position $i > 1$, then we can split it into $a = s[0]$, $b = s[1 ... i - 1]$, $c = s[i ... n - 1]$. If the string starts with $ab$, and all other letters are b, then we can split it into $a = s[0 ... n - 3]$, $b = s[n - 2]$, $c = s[n - 1]$.",
    "code": "\"#include <bits/stdc++.h>\\n#define sz(x) ((int)x.size())\\nusing namespace std;\\nstring s;\\nint n;\\n\\nvoid Solve() {\\n    cin >> s;\\n    n = sz(s);\\n\\n    if (s[0] == s[1]) {\\n        cout << s[0] << \\\" \\\" << s[1] << \\\" \\\" << s.substr(2) << '\\\\n';\\n        return;\\n    }\\n    if (s[n - 2] == s[n - 1]) {\\n        cout << s.substr(0, n - 2) << \\\" \\\" << s[n - 2] << \\\" \\\" << s[n - 1] << '\\\\n';\\n        return;\\n    }\\n\\n    if (s[0] < s[1]) {\\n        for (int i = 1; i < n - 1; i++) {\\n            if (s[i] > s[i + 1]) {\\n                cout << s.substr(0, i) << \\\" \\\" << s[i] << \\\" \\\" << s.substr(i + 1) << '\\\\n';\\n                return;\\n            }\\n        }\\n    } else {\\n        for (int i = 1; i < n - 1; i++) {\\n            if (s[i] <= s[i + 1]) {\\n                cout << s.substr(0, i) << \\\" \\\" << s[i] << \\\" \\\" << s.substr(i + 1) << '\\\\n';\\n                return;\\n            }\\n        }\\n    }\\n\\n    cout << \\\":(\\\\n\\\";\\n}\\n\\nint main() {\\n    ios_base::sync_with_stdio(false); cin.tie(nullptr);\\n    int t;\\n    cin >> t;\\n\\n    for (int i = 0; i < t; i++) {\\n        Solve();\\n    }\\n\\n    return 0;\\n}\\n\"",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1775",
    "index": "B",
    "title": "Gardener and the Array",
    "statement": "The gardener Kazimir Kazimirovich has an array of $n$ integers $c_1, c_2, \\dots, c_n$.\n\nHe wants to check if there are two different subsequences $a$ and $b$ of the original array, for which $f(a) = f(b)$, where $f(x)$ is the bitwise OR of all of the numbers in the sequence $x$.\n\nA sequence $q$ is a subsequence of $p$ if $q$ can be obtained from $p$ by deleting several (possibly none or all) elements.\n\nTwo subsequences are considered different if the sets of indexes of their elements in the original sequence are different, that is, the values of the elements are not considered when comparing the subsequences.",
    "tutorial": "The problem can be solved as follows: for each bit count the number of its occurrences in all numbers in the test. If each number has a bit which occurs in all numbers exactly once, then the answer is \"NO\", otherwise the answer is \"YES\". Let's try to prove this solution. Let there be a number in which all bits occurs in all numbers at least $2$ times. But then it is possible to construct a sequence $a$ using all numbers, and a sequence $b$ using all numbers except the given one. If each number has \"unique\" bits, then all $f(x)$ will be different.",
    "code": "\"#include <iostream>\\n#include <vector>\\n#include <set>\\n#include <algorithm>\\n#include <ctime>\\n#include <cmath>\\n#include <map>\\n#include <assert.h>\\n#include <fstream>\\n#include <cstdlib>\\n#include <random>\\n#include <iomanip>\\n#include <queue>\\n#include <random>\\n#include <unordered_map>\\n \\nusing namespace std;\\n \\n#define sqr(a) ((a)*(a))\\n#define all(a) (a).begin(), (a).end()\\n \\nlong long MOD = (int) 1e9 + 7;\\n\\nvoid solve() {\\n    int n;\\n    cin >> n;\\n\\n    vector<vector<int> > a(n);\\n    map<int, int> occurrences;\\n    for (int i = 0; i < n; ++i) {\\n        int k;\\n        cin >> k;\\n\\n        a[i].resize(k);\\n        for (int j = 0; j < k; ++j) {\\n            cin >> a[i][j];\\n            --a[i][j];\\n\\n            ++occurrences[a[i][j]];\\n        }\\n    }\\n\\n    for (int i = 0; i < n; ++i) {\\n        bool find = false;\\n        for (int j = 0; j < a[i].size(); ++j) {\\n            if (occurrences[a[i][j]] == 1) {\\n                find = true;\\n                break;\\n            }\\n        }\\n\\n        if (!find) {\\n            cout << \\\"Yes\\\\n\\\";\\n            return;\\n        }\\n    }\\n\\n    cout << \\\"No\\\\n\\\";\\n}\\n\\nint main() {\\n    // freopen(\\\"input.txt\\\", \\\"r\\\", stdin);\\n\\n    int tests = 1;\\n    cin >> tests;\\n \\n    for (int i = 1; i <= tests; ++i) {\\n        solve();\\n    }\\n}\\n\"",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1775",
    "index": "C",
    "title": "Interesting Sequence",
    "statement": "Petya and his friend, robot Petya++, like to solve exciting math problems.\n\nOne day Petya++ came up with the numbers $n$ and $x$ and wrote the following equality on the board: $$n\\ \\&\\ (n+1)\\ \\&\\ \\dots\\ \\&\\ m = x,$$ where $\\&$ denotes the bitwise AND operation. Then he suggested his friend Petya find such a minimal $m$ ($m \\ge n$) that the equality on the board holds.\n\nUnfortunately, Petya couldn't solve this problem in his head and decided to ask for computer help. He quickly wrote a program and found the answer.\n\nCan you solve this difficult problem?",
    "tutorial": "Note that the answer $-1$ will be when $n$ AND $x \\neq x$. This holds if there is a bit with number $b$ which exists in number $x$, but it does not exist in number $n$. What is clear now is that some bits in $n$ must be zeroed. Since we have bitwise AND going sequentially with numbers larger than $n$, we change the bits from the lowest to the highest. Thus, in number $n$ some bit prefix is zeroed out, so if number $x$ is not number $n$ with a zeroed prefix (possibly empty) of bits, then there is no answer. Now we can calculate for each bit $i$ the minimal number $m_i$ such that $n$ AND $n + 1$ AND $\\ldots$ AND $m_i$ has $0$ in the $i$-th bit. Now calculate $m_{zero}$ as the maximum $m_i$ on all bits to be zeroed, and $m_{one}$ as the minimum $m_i$ on all bits to be left untouched. Then, if $m_{zero} < m_{one}$, we will take $m_{zero}$ as the answer, otherwise there is no answer. The problem can also be solved by binary search: we will use it to find $m$, and check the answer by the formula: for each bit find the nearest $m$, at which it will be zeroed. We can do this using the following fact: for $i$-th bit, the first $2^i$ numbers (starting from zero) will not contain it, then $2^i$ will, then $2^i$ again will not and so on. Such a solution works for $O(\\log^2 n)$.",
    "code": "\"#pragma GCC optimize(\\\"O3\\\")\\n#include<bits/stdc++.h>\\n\\n#define ll long long\\n#define pb push_back\\n#define ld long double\\n#define f first\\n#define s second\\n\\nusing namespace std;\\nconst ll inf = (1ll << 62);\\nint32_t main() {\\n\\n    ios_base::sync_with_stdio(0);\\n    cin.tie(0);\\n    cout.tie(0);\\n    ll t;\\n    cin >> t;\\n    while(t--) {\\n        ll n, x;\\n        cin >> n >> x;\\n\\n        ll ma = n, mi = inf;\\n        ll mask = 0;\\n        for(ll i = 0; i < 61; i++) {\\n            if(!((n >> i) & 1)) {\\n                if((x >> i) & 1) {\\n                    mi = -1;\\n                    break;\\n                }\\n            } else {\\n                ll now = n + (1ll << i) - (n & mask);\\n                if((x >> i) & 1) {\\n                    mi = min(mi, now);\\n                } else {\\n                    ma = max(ma, now);\\n                }\\n            }\\n            mask += (1ll << i);\\n        }\\n        if(ma < mi) cout << ma << '\\\\n';\\n        else cout << \\\"-1\\\\n\\\";\\n    }\\n\\n\\n}\\n\\n\"",
    "tags": [
      "bitmasks",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1775",
    "index": "D",
    "title": "Friendly Spiders",
    "statement": "Mars is home to an unusual species of spiders — Binary spiders.\n\nRight now, Martian scientists are observing a colony of $n$ spiders, the $i$-th of which has $a_i$ legs.\n\nSome of the spiders are friends with each other. Namely, the $i$-th and $j$-th spiders are friends if $\\gcd(a_i, a_j) \\ne 1$, i. e., there is some integer $k \\ge 2$ such that $a_i$ and $a_j$ are simultaneously divided by $k$ without a remainder. Here $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\nScientists have discovered that spiders can send messages. If two spiders are friends, then they can transmit a message directly in one second. Otherwise, the spider must pass the message to his friend, who in turn must pass the message to his friend, and so on until the message reaches the recipient.\n\nLet's look at an example.\n\nSuppose a spider with eight legs wants to send a message to a spider with $15$ legs. He can't do it directly, because $\\gcd(8, 15) = 1$. But he can send a message through the spider with six legs because $\\gcd(8, 6) = 2$ and $\\gcd(6, 15) = 3$. Thus, the message will arrive in two seconds.\n\nRight now, scientists are observing how the $s$-th spider wants to send a message to the $t$-th spider. The researchers have a hypothesis that spiders always transmit messages optimally. For this reason, scientists would need a program that could calculate the minimum time to send a message and also deduce one of the optimal routes.",
    "tutorial": "Note that if we construct the graph by definition, it will be large. This will lead us to the idea to make it more compact. Let us create a bipartite graph whose left part consists of $n$ vertices with numbers $a_i$. And in the right part each vertex corresponds to some prime number, not larger than the maximal number from the left part. Draw an edge from the vertex $v$ of the left part to the vertex $u$ of the right lpart if and only if $a_v$ is divisible by a prime number corresponding to the vertex $u$. In this graph from vertex $s$ to vertex $t$, run bfs and output the distance divided by $2$. Now about how to construct such a graph quickly. Obviously, the number $a_i$ will have at most $\\log a_i$ different prime divisors. Then let us factorize $a_v$ and draw edges from vertex $v$ to each prime in factorization.",
    "code": "\"#include <bits/stdc++.h>\\nusing namespace std;\\ntypedef long long ll;\\nconst int N = 300100;\\nconst int kMaxA = 300100;\\nconst int oo = 1e9;\\nvector<int> edges[kMaxA];\\nint dist[kMaxA], prv[kMaxA];\\nbool used[kMaxA];\\nint prv_id[kMaxA];\\nint min_prime[kMaxA];\\nint n, a[N];\\nint boss[kMaxA];\\nint mem_id[kMaxA];\\nint source, dest;\\n\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(nullptr);\\n\\n    cin >> n;\\n    for (int i = 0; i < n; i++) {\\n        cin >> a[i];\\n        mem_id[a[i]] = i;\\n    }\\n    cin >> source >> dest;\\n    source--; dest--;\\n\\n    if (a[source] == a[dest]) {\\n        if (source == dest) {\\n            cout << \\\"1\\\\n\\\" << source + 1 << '\\\\n';\\n        } else if (a[source] == 1) {\\n            cout << -1;\\n        } else {\\n            cout << \\\"2\\\\n\\\" << source + 1 << \\\" \\\" << dest + 1;\\n        }\\n        return 0;\\n    }\\n\\n    fill(min_prime, min_prime + kMaxA, oo);\\n\\n    for (int prime = 2; prime < kMaxA; prime++) {\\n        if (min_prime[prime] != oo) {\\n            continue;\\n        }\\n        min_prime[prime] = prime;\\n\\n        if (ll(prime) * ll(prime) >= kMaxA) {\\n            continue;\\n        }\\n\\n        for (int value = prime * prime; value < kMaxA; value += prime) {\\n            min_prime[value] = min(min_prime[value], prime);\\n        }\\n    }\\n\\n    fill(boss, boss + kMaxA, -1);\\n\\n    fill(dist, dist + kMaxA, oo);\\n    fill(prv, prv + kMaxA, -1);\\n    queue<int> pr_queue;\\n\\n    for (int i = 0; i < n; i++) {\\n        bool is_need = edges[a[i]].empty();\\n\\n        int value = a[i];\\n        int pre_prime = -1;\\n        while (value > 1) {\\n            int cur_prime = min_prime[value];\\n            if (cur_prime != pre_prime && is_need) {\\n                edges[a[i]].push_back(cur_prime);\\n            }\\n\\n            if (cur_prime != pre_prime && i == source) {\\n                dist[cur_prime] = 0;\\n                pr_queue.push(cur_prime);\\n            }\\n\\n            pre_prime = cur_prime;\\n            boss[cur_prime] = i;\\n            value /= cur_prime;\\n        }\\n    }\\n\\n    fill(used, used + kMaxA, false);\\n\\n    while (!pr_queue.empty()) {\\n        int cur_prime = pr_queue.front();\\n        pr_queue.pop();\\n\\n        for (int value = cur_prime * 2; value < kMaxA; value += cur_prime) {\\n            if (used[value]) {\\n                continue;\\n            }\\n            used[value] = true;\\n\\n            for (int next_prime : edges[value]) {\\n                if (dist[next_prime] == oo) {\\n                    dist[next_prime] = dist[cur_prime] + 1;\\n                    prv_id[next_prime] = mem_id[value];\\n                    prv[next_prime] = cur_prime;\\n                    pr_queue.push(next_prime);\\n                }\\n            }\\n        }\\n    }\\n\\n    int best_dist = oo;\\n    int best_prime = -1;\\n\\n    for (int prime : edges[a[dest]]) {\\n        if (dist[prime] < best_dist) {\\n            best_dist = dist[prime];\\n            best_prime = prime;\\n        }\\n    }\\n\\n    if (best_dist == oo) {\\n        cout << -1;\\n        return 0;\\n    }\\n\\n    vector<int> route;\\n\\n    int cur_prime = best_prime;\\n    route.push_back(dest);\\n    route.push_back(prv_id[best_prime]);\\n    while (prv[cur_prime] != -1) {\\n        cur_prime = prv[cur_prime];\\n        route.push_back(prv_id[cur_prime]);\\n    }\\n\\n    std::reverse(route.begin(), route.end());\\n    route.front() = source;\\n\\n    cout << route.size() << '\\\\n';\\n    for (int id : route) {\\n        cout << id + 1 << \\\" \\\";\\n    }\\n\\n    return 0;\\n}\\n\"",
    "tags": [
      "dfs and similar",
      "graphs",
      "math",
      "number theory",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1775",
    "index": "E",
    "title": "The Human Equation",
    "statement": "Petya and his friend, the robot Petya++, went to BFDMONCON, where the costume contest is taking place today.\n\nWhile walking through the festival, they came across a scientific stand named after Professor Oak and Golfball, where they were asked to solve an interesting problem.\n\nGiven a sequence of numbers $a_1, a_2, \\dots, a_n$ you can perform several operations on this sequence.\n\nEach operation should look as follows. You choose some subsequence$^\\dagger$. Then you call all the numbers at odd positions in this subsequence northern, and all the numbers at even positions in this subsequence southern. In this case, only the position of the number in the subsequence is taken into account, not in the original sequence.\n\nFor example, consider the sequence $1, 4, 2, 8, 5, 7, 3, 6, 9$ and its subsequence (shown in bold) $1, \\mathbf{4}, \\mathbf{2}, 8, \\mathbf{5}, 7, 3, \\mathbf{6}, 9$. Then the numbers $4$ and $5$ are northern, and the numbers $2$ and $6$ are southern.\n\nAfter that, you can do one of the following:\n\n- add $1$ to all northern numbers and subtract $1$ from all south numbers; or\n- add $1$ to all southern numbers and subtract $1$ from all northern numbers.\n\nThus, from the sequence $1, \\mathbf{4}, \\mathbf{2}, 8, \\mathbf{5}, 7, 3, \\mathbf{6}, 9$, if you choose the subsequence shown in bold, you can get either $1, \\mathbf{5}, \\mathbf{1}, 8, \\mathbf{6}, 7, 3, \\mathbf{5}, 9$ or $1, \\mathbf{3}, \\mathbf{3}, 8, \\mathbf{4}, 7, 3, \\mathbf{7}, 9$.\n\nThen the operation ends. Note also that all operations are independent, i. e. the numbers are no longer called northern or southern when one operation ends.\n\nIt is necessary to turn all the numbers of the sequence into zeros using the operations described above. Since there is very little time left before the costume contest, the friends want to know, what is the minimum number of operations required for this.\n\nThe friends were unable to solve this problem, so can you help them?\n\n$^\\dagger$ A sequence $c$ is a subsequence of a sequence $d$ if $c$ can be obtained from $d$ by the deletion of several (possibly, zero or all) elements.",
    "tutorial": "Let's calculate an array of prefix sums. What do the operations look like in this case? If we calculate the array of prefix sums, we'll see that the operations now look like \"add 1 on a subsequence\" or \"take away 1 on a subsequence\". Why? If we take the indices $i$ and $j$ and apply our operation to them (i.e. $a_i = a_i + 1$ and $a_j = a_j - 1$), it will appear that we added $1$ on the segment $[i ... j - 1]$ in the prefix sums array. We still need to make the array all zeros. How? We will add $1$ to all elements that are less than zero, then subtract $1$ from all elements that are greater than $0$. From this we get that the answer is the difference between the maximum and minimum prefix sums.",
    "code": "\"#include <iostream>\\n\\nusing namespace std;\\n\\nint main() {\\n    ios_base::sync_with_stdio(false);\\n    cin.tie(0);\\n    int t;\\n    cin >> t;\\n    while (t--) {\\n        int n;\\n        cin >> n;\\n        int64_t mn = 0;\\n        int64_t mx = 0;\\n        int64_t cur = 0;\\n        for (int i = 0; i < n; i++) {\\n            int u;\\n            cin >> u;\\n            cur += u;\\n            mn = min(mn, cur);\\n            mx = max(mx, cur);\\n        }\\n        cout << mx - mn << '\\\\n';\\n    }\\n}\\n\"",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1775",
    "index": "F",
    "title": "Laboratory on Pluto",
    "statement": "As you know, Martian scientists are actively engaged in space research. One of the highest priorities is Pluto. In order to study this planet in more detail, it was decided to build a laboratory on Pluto.\n\nIt is known that the lab will be built of $n$ square blocks of equal size. For convenience, we will assume that Pluto's surface is a plane divided by vertical and horizontal lines into unit squares. Each square is either occupied by a lab block or not, and only $n$ squares are occupied.\n\nSince each block is square, it has four walls. If a wall is adjacent to another block, it is considered inside, otherwise — outside.\n\nPluto is famous for its extremely cold temperatures, so the outside walls of the lab must be insulated. One unit of insulation per exterior wall would be required. Thus, the greater the total length of the outside walls of the lab (i. e., its perimeter), the more insulation will be needed.\n\nConsider the lab layout in the figure below. It shows that the lab consists of $n = 33$ blocks, and all the blocks have a total of $24$ outside walls, i. e. $24$ units of insulation will be needed.\n\nYou should build the lab optimally, i. e., minimize the amount of insulation. On the other hand, there may be many optimal options, so scientists may be interested in the number of ways to build the lab using the minimum amount of insulation, modulo a prime number $m$.\n\nTwo ways are considered the same if they are the same when overlapping without turning. Thus, if a lab plan is rotated by $90^{\\circ}$, such a new plan can be considered a separate way.\n\nTo help scientists explore Pluto, you need to write a program that solves these difficult problems.",
    "tutorial": "Let us find out the minimal perimeter for a fixed $n$ in $O(1)$. Let $a = \\lfloor \\sqrt{n} \\rfloor$: If $a^2 < n$ and $n \\leq a \\cdot (a+1)$, then the minimum perimeter will be $2 \\cdot (2 \\cdot a + 1)$. If $a \\cdot a + a < n$ and $n \\leq (a + 1)^2$, then the minimum perimeter will be $4 \\cdot (a + 1)$. If 1) and 2) are not satisfied, then the minimum perimeter is $4 \\cdot a$. For convenience, we denote the semiperimeter by $p$. Let's check one of the rectangle's side $x$ from $1$ to $p$. We will immediately get $y = p - x$. Then if the area of the rectangle is at least $n$, then for tests with $u=1$ we can derive a rectangle with sides $x$ and $y$ by removing some number of cells from the 1st row or column of this matrix. Consider a matrix with sides $x$ and $y$ with minimal perimeter and area at least $n$. It is easy to see that if we gradually remove one corner cell of a given figure, the perimeter will not change. Suppose we have some good figure. Let's look at all four figures that form empty cells in the matrix. These figures form a kind of 'staircase', that is, the number of cells in the past row is not less than the number of cells. Why is this so? Suppose that in some line we delete a cell so that the figure ceases to form a staircase. In that case the perimeter of the piece will increase by $2$, which will be the bad piece. Now the problem is reduced to the following: For each matrix with dimensions $x$ by $y$ with minimal perimeter and area not less than $n$, calculate the number of ways to arrange the staircases in 4 corners such that the sum of cells occupied by the staircases equals $x \\cdot y - n$. How to do this? Assume DP $dp_{angles, sum, last}$ - the number of ways to arrange staircases in $angles$, not more than 4, so that the sum of all cells occupied by staircases equals $sum$ and the length of the last line of staircase equals $last$. Then how to count the given DP? Go through $angles, sum, last$ and $cur \\leq last$ - the length of the line we will add to the current staircase, then go from $dp_{angles, sum, last}$ to $dp_{angles, sum + cur, cur}$. Or go to the next corner $dp_{angles + 1, sum, maxP}$. This DP works for $O(n \\cdot \\sqrt{n})$. To answer $n$ we go through all good rectangles, as specified above, and add $f_{4, x \\cdot y - n, maxP}$ to the answer. To solve the problem for a full score, you must optimize the above DP to $O(n)$. The final difficulty is $O(n + t \\cdot \\sqrt{n})$.",
    "code": "\"#include <bits/stdc++.h>\\n#define el \\\"\\\\n\\\"\\nusing namespace std;\\n\\nconst int N = 4e5 + 50;\\n\\nint f[5][1500][1500], M, a;\\n\\nint get_P(int n) {\\n    int a = sqrt(n);\\n    if (a * a < n && a * a + a >= n) {\\n        return 2 * a + 1;\\n    }\\n    if (a * a + a < n && n <= (a + 1) * (a + 1)) {\\n        return 2 * (a + 1);\\n    }\\n    return 2 * a;\\n}\\n\\nvoid precalc() {\\n    a = sqrt(N) + 5;\\n    f[0][0][a] = 1;\\n    for (int i = 0; i < 4; i++) {\\n        for (int j = 0; j <= a; j++) {\\n            for (int was = a; was >= 0; was--) {\\n                if (was && j + was <= a) {\\n                    (f[i][j + was][was] += f[i][j][was]) %= M;\\n                }\\n                if (was) {\\n                    (f[i][j][was - 1] += f[i][j][was]) %= M;\\n                }\\n            }\\n            (f[i + 1][j][a] += f[i][j][0]) %= M;\\n        }\\n    }\\n}\\n\\nint main() {\\n    ios::sync_with_stdio(false);\\n    cin.tie(NULL);\\n\\n    int q, type;\\n    cin >> q >> type;\\n    if (type == 2) {\\n        cin >> M;\\n        precalc();\\n    }\\n    while (q--) {\\n        int n;\\n        cin >> n;\\n        int p = get_P(n);\\n        if (type == 1) {\\n            int _n, _m;\\n            for (int x = 1; x <= p; x++) {\\n                int y = p - x;\\n                if (x + y == p && x * y >= n) {\\n                    _n = x; _m = y;\\n                    break;\\n                }\\n            }\\n            vector <vector <char> > ans(_n, vector <char> (_m, '#'));\\n            cout << _n << \\\" \\\" << _m << \\\"\\\\n\\\";\\n            for (int i = 0; i < _n * _m - n; i++) {\\n                ans[i][0] = '.';\\n            }\\n            for (int i = 0; i < _n; i++, cout << el) {\\n                for (int j = 0; j < _m; j++) {\\n                    cout << ans[i][j];\\n                }\\n            }\\n\\n            continue;\\n        }\\n\\n        int ans = 0;\\n        for (int x = 1; x <= p; x++) {\\n            int y = p - x;\\n            if (x + y == p && x * y >= n) {\\n                (ans += f[4][x * y - n][a]) %= M;\\n            }\\n        }\\n        cout << p * 2 << \\\" \\\" << ans << \\\"\\\\n\\\";\\n    }\\n}\\n\\n\"",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1777",
    "index": "A",
    "title": "Everybody Likes Good Arrays!",
    "statement": "An array $a$ is good if for all pairs of adjacent elements, $a_i$ and $a_{i+1}$ ($1\\le i \\lt n$) are of \\textbf{different} parity. Note that an array of size $1$ is trivially good.\n\nYou are given an array of size $n$.\n\nIn one operation you can select any pair of adjacent elements in which both elements are of the \\textbf{same} parity, delete them, and insert their product in the same position.\n\nFind the minimum number of operations to form a good array.",
    "tutorial": "Solution Replace even numbers with $0$ and odd numbers with $1$ in the array $a$. Now we observe that the given operation is equivalent to selecting two equal adjacent elements and deleting one of them. Now the array can be visualized as strips of zeros (in green) and ones (in red) like this $[\\color{green}{0,0,0},\\color{red}{1,1,1,1},\\color{green}{0},\\color{red}{1,1}]$. Note that since the number of adjacent elements ($a[i],a[i+1])$ such that $a[i] \\ne a[i+1]$ remains constant (nice invariant!), every strip can be handled independently. The size of every strip must be $1$ in the final array and performing an operation reduces the size of the corresponding strip by $1$. So, for a strip of length $L$, it would require $L-1$ operations to reduce its size to $1$. So, every strip would contribute $-1$ to the number of operations apart from its length. So, the answer is ($n -$ total no. of strips) which also equals ($n - x - 1$) where x is number of adjacent elements ($a[i],a[i+1]$) such that ($a[i] \\ne a[i+1]$).",
    "code": "def main():\n    T = int(input())\n    while T > 0:\n        T = T - 1\n        n = int(input())\n        a = [int(x) for x in input().split()]\n        ans = 0\n \n        for i in range(1, n):\n            ans += 1 - ((a[i] + a[i - 1]) & 1)\n \n        print(ans)\n \n \nif __name__ == '__main__':\n    main()",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1777",
    "index": "B",
    "title": "Emordnilap",
    "statement": "A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). There are $n! = n \\cdot (n-1) \\cdot (n - 2) \\cdot \\ldots \\cdot 1$ different permutations of length $n$.\n\nGiven a permutation $p$ of $n$ numbers, we create an array $a$ consisting of $2n$ numbers, which is equal to $p$ concatenated with its reverse. We then define the beauty of $p$ as the number of inversions in $a$.\n\nThe number of inversions in the array $a$ is the number of pairs of indices $i$, $j$ such that $i < j$ and $a_i > a_j$.\n\nFor example, for permutation $p = [1, 2]$, $a$ would be $[1, 2, 2, 1]$. The inversions in $a$ are $(2, 4)$ and $(3, 4)$ (assuming 1-based indexing). Hence, the beauty of $p$ is $2$.\n\nYour task is to find the sum of beauties of all $n!$ permutations of size $n$. Print the remainder we get when dividing this value by $1\\,000\\,000\\,007$ ($10^9 + 7$).",
    "tutorial": "Observation: Every permutation has the same beauty. Consider two indices $i$ and $j$ ($i < j$) in a permutation $p$. These elements appear in the order $[p_i, p_j, p_j, p_i]$ in array $A$. Now we have two cases: Case $1$: $p_i > p_j$ The first $p_i$ appears before both $p_j$'s in this case, accounting for $2$ inversions. Case $2$: $p_i < p_j$ Both the $p_j$'s appear before the second $p_i$, accounting for $2$ inversions again. Hence, any pair of indices in $p$ account for $2$ inversions in $A$. Thus, beauty of every permutation $p = {n\\choose 2} \\cdot 2 = n \\cdot (n - 1)$ Sum of beauties of all permutations $= n \\cdot (n - 1) \\cdot n!$",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    nf = 1\n    mod = int(1e9 + 7)\n    for i in range(n):\n        nf = nf * (i + 1)\n        nf %= mod\n    ans = n * (n - 1) * nf\n    ans %= mod\n    print(ans)",
    "tags": [
      "combinatorics",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1777",
    "index": "C",
    "title": "Quiz Master",
    "statement": "A school has to decide on its team for an international quiz. There are $n$ students in the school. We can describe the students using an array $a$ where $a_i$ is the smartness of the $i$-th ($1 \\le i \\le n$) student.\n\nThere are $m$ topics $1, 2, 3, \\ldots, m$ from which the quiz questions will be formed. The $i$-th student is considered proficient in a topic $T$ if $(a_i \\bmod T) = 0$. Otherwise, he is a rookie in that topic.\n\nWe say that a team of students is collectively proficient in all the topics if for every topic there is a member of the team proficient in this topic.\n\nFind a team that is collectively proficient in all the topics such that the maximum difference between the smartness of any two students in that team is \\textbf{minimized}. Output this difference.",
    "tutorial": "We can sort the smartness values and use two pointers. The two pointers indicate the students we are considering in our team. Let $l$ be the left pointer and $r$ be the right pointer. $a_l$ is the minimum smartness of our team and $a_r$ is the maximum. If this team is collectively proficient in all topics, then the difference would be $a_r - a_l$. Now, if $l$ is increased, the team may lose proficiency in some topics. $r$ would either stay the same or increase as well for the team to become proficient again. For a team to be proficient, each number from $1$ to $m$ should have a smartness value which is a multiple of it. To check for proficiency, we can maintain a frequency array $f$ of size $m$ and a variable $count$ to indicate the number of topics that have found a multiple. When we add a student to the team, we iterate through all the factors of their smartness which are less than or equal to $m$ and increase their frequency. If an element had a frequency of $0$ before, then $count$ is increased by $1$. Similarly, when we remove a student from the team, we go through all the factors less than or equal to $m$ and decrease their frequency. If an element now has $0$ frequency, then $count$ is decreased by $1$. $count$ being equal to $m$ at any point indicates a collectively proficient team.",
    "code": "#include <bits/stdc++.h>\n#define all(v) v.begin(), v.end()\n#define var(x, y, z) cout << x << \" \" << y << \" \" << z << endl;\n#define ll long long int\n#define pii pair<ll, ll>\n#define pb push_back\n#define ff first\n#define ss second\n#define FASTIO                \\\n    ios ::sync_with_stdio(0); \\\n    cin.tie(0);               \\\n    cout.tie(0);\n\nusing namespace std;\n\nconst ll inf = 1e17;\nconst ll MAXM = 1e5;\nvector<ll> factors[MAXM + 5];\n\nvoid init()\n{\n    for (ll i = 1; i <= MAXM; i++)\n    {\n        for (ll j = i; j <= MAXM; j += i)\n        {\n            factors[j].pb(i);\n        }\n    }\n}\n\nvoid solve()\n{\n    ll n, m;\n    cin >> n >> m;\n    vector<pii> vec;\n    for (ll i = 0; i < n; i++)\n    {\n        ll value;\n        cin >> value;\n        vec.pb({value, i});\n    }\n    sort(all(vec));\n    vector<ll> frequency(m + 5, 0);\n    ll curr_count = 0;\n    ll j = 0;\n    ll global_ans = inf;\n    for (ll i = 0; i < n; i++)\n    {\n        for (auto x : factors[vec[i].ff])\n        {\n            if (x > m)\n                break;\n            if (!frequency[x]++)\n            {\n                curr_count++;\n            }\n        }\n        while (curr_count == m)\n        {\n            ll curr_ans = vec[i].ff - vec[j].ff;\n            if (curr_ans < global_ans)\n            {\n                global_ans = curr_ans;\n            }\n            for (auto x : factors[vec[j].ff])\n            {\n                if (x > m)\n                    break;\n                if (--frequency[x] == 0)\n                {\n                    curr_count--;\n                }\n            }\n            j++;\n        }\n    }\n    cout << (global_ans >= inf ? -1 : global_ans) << \"\\n\";\n}\n\nint main()\n{\n    FASTIO\n    init();\n    ll t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "math",
      "number theory",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1777",
    "index": "D",
    "title": "Score of a Tree",
    "statement": "You are given a tree of $n$ nodes, rooted at $1$. Every node has a value of either $0$ or $1$ at time $t=0$.\n\nAt any integer time $t>0$, the value of a node becomes the bitwise XOR of the values of its children at time $t - 1$; the values of leaves become $0$ since they don't have any children.\n\nLet $S(t)$ denote the sum of values of all nodes at time $t$.\n\nLet $F(A)$ denote the sum of $S(t)$ across all values of $t$ such that $0 \\le t \\le 10^{100}$, where $A$ is the initial assignment of $0$s and $1$s in the tree.\n\nThe task is to find the sum of $F(A)$ for all $2^n$ initial configurations of $0$s and $1$s in the tree. Print the sum modulo $10^9+7$.",
    "tutorial": "We will focus on computing the expected value of $F(A)$ rather than the sum, as the sum is just $2^n \\times \\mathbb{E}(F(A))$. Let $F_u(A)$ denote the sum of all values at node $u$ from time $0$ to $10^{100}$, if the initial configuration is $A$. Clearly, $F(A) = \\sum {F_u(A)}$. With linearity of expectations, $\\mathbb{E}(F(A)) = \\sum {\\mathbb{E}(F_u(A))}$ Define $V_u(A, t)$ as the value of node $u$ at time $t$, if the initial configuration is $A$. Observe that $V_u(A, t)$ is simply $0$ if there is no node in $u$'s subtree at a distance of $t$ from $u$, otherwise, the value is the bitwise xor of the initial values of all nodes in the subtree of $u$ at a distance of $t$ from $u$. Thus, define $d_u$ as the length of the longest path from $u$ to a leaf in $u$'s subtree. Now, $\\mathbb{E}(V_u(A, t))$ is half if $t$ is less than or equal to $d_u$, otherwise it's $0$. This is because the expected value of xor of $k$ boolean values is $0$ is $k$ is zero, otherwise it's half. This fact has multiple combinatorial proofs. For example, one can simply count the number of ways of choosing odd number of boolean values, among the $k$ values as $1$ to get $\\sum_{\\text{odd i}}{\\binom{k}{i}} = 2^{k-1}$ We use this to get: $\\mathbb{E}(F_u(A)) = \\mathbb{E}(\\sum_{0}^{10^{100}}{V_u(A, t)}) = \\sum_{0}^{10^{100}}{\\mathbb{E}(V_u(A, t)} = \\frac{d_u + 1}{2}$ All the $d_u$ values can be computed by a single traversal of the tree. Our final result is: $2^n \\times \\sum{ \\frac{d_u + 1}{2} }$ Time complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define MOD 1000000007\n \nlong long power(long long a, int b)\n{\n    long long ans = 1;\n    while (b)\n    {\n        if (b & 1)\n        {\n            ans *= a;\n            ans %= MOD;\n        }\n        a *= a;\n        a %= MOD;\n        b >>= 1;\n    }\n    return ans;\n}\n \nint DFS(int v, vector<int> edges[], int p, int dep, int ped[])\n{\n    int mdep = dep;\n    for (auto it : edges[v])\n        if (it != p)\n            mdep = max(DFS(it, edges, v, dep + 1, ped), mdep);\n    ped[v] = mdep - dep + 1;\n    return mdep;\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int T, i, j, n, u, v;\n    cin >> T;\n    while (T--)\n    {\n        cin >> n;\n        vector<int> edges[n];\n        for (i = 0; i < n - 1; i++)\n        {\n            cin >> u >> v;\n            u--, v--;\n \n            edges[u].push_back(v);\n            edges[v].push_back(u);\n        }\n \n        int ped[n];\n        DFS(0, edges, 0, 0, ped);\n \n        long long p = power(2, n - 1), ans = 0;\n        for (i = 0; i < n; i++)\n        {\n            ans += p * ped[i] % MOD;\n            ans %= MOD;\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dfs and similar",
      "dp",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1777",
    "index": "E",
    "title": "Edge Reverse",
    "statement": "You will be given a weighted directed graph of $n$ nodes and $m$ directed edges, where the $i$-th edge has a weight of $w_i$ ($1 \\le i \\le m$).\n\nYou need to reverse some edges of this graph so that there is at least one node in the graph from which every other node is reachable. The cost of these reversals is equal to the maximum weight of all reversed edges. If no edge reversal is required, assume the cost to be $0$.\n\nIt is guaranteed that no self-loop or duplicate edge exists.\n\nFind the minimum cost required for completing the task. If there is no solution, print a single integer $-1$.",
    "tutorial": "If the cost for completing the task is $c$, we can reverse any edge with cost $\\le c$. This is equivalent to making those edges bidirectional since when checking for reachability, we only need to traverse an edge once, and we can choose to reverse it or not, depending upon the need. We can apply a binary search on the minimum cost and check if there exists at least one node such that all nodes are reachable from it if all edges with cost less than or equal to the current cost become bidirectional. To check in linear time if there exists such a suitable node, we will use a suppressed version of the Kosa Raju algorithm. We condense the nodes into Strongly Connected Components (SCCs) and perform a topological sort on them. If there exists an SCC from which all SCCs are reachable, then the first element in the topological sort will be that SCC (since in a topological sort, an element can only reach elements coming after it). So, we can choose any node from the first SCC in the topological sort and apply DFS to check if all the nodes are reachable from that node. If they aren't, we conclude it is impossible to complete the task with the current cost. Overall time complexity: $O((N+M) \\cdot \\log C)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n// Using Kosa Raju, we guarantee the topmost element (indicated by root) of stack is from the root SCC\n \nvoid DFS(int v, bool visited[], int &root, vector<int> edges[])\n{\n    visited[v] = true;\n    for (auto it : edges[v])\n        if (!visited[it])\n            DFS(it, visited, root, edges);\n    root = v;\n}\n \nint cnt(int v, bool visited[], vector<int> edges[])\n{\n    int ans = 1;\n    visited[v] = true;\n    for (auto it : edges[v])\n        if (!visited[it])\n            ans += cnt(it, visited, edges);\n    return ans;\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int T;\n    cin >> T;\n    while (T--)\n    {\n        int i, j, n, m, u, v, w;\n        cin >> n >> m;\n        vector<pair<int, int>> og_edges[n];\n        for (i = 0; i < m; i++)\n        {\n            cin >> u >> v >> w;\n            u--, v--;\n \n            og_edges[u].push_back({v, w});\n        }\n \n        int l = -1, r = 1e9 + 1, mid;\n        while (r - l > 1)\n        {\n            mid = l + (r - l) / 2;\n \n            vector<int> edges[n];\n            for (i = 0; i < n; i++)\n            {\n                for (auto it : og_edges[i])\n                {\n                    edges[i].push_back(it.first);\n                    if (it.second <= mid)\n                        edges[it.first].push_back(i);\n                }\n            }\n \n            bool visited[n] = {};\n            int root;\n            for (i = 0; i < n; i++)\n            {\n                if (!visited[i])\n                    DFS(i, visited, root, edges);\n            }\n \n            memset(visited, false, sizeof(visited));\n \n            if (cnt(root, visited, edges) == n)\n                r = mid;\n            else\n                l = mid;\n        }\n \n        if (r == 1e9 + 1)\n            r = -1;\n        cout << r << '\\n';\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1777",
    "index": "F",
    "title": "Comfortably Numb",
    "statement": "You are given an array $a$ consisting of $n$ non-negative integers.\n\nThe numbness of a subarray $a_l, a_{l+1}, \\ldots, a_r$ (for arbitrary $l \\leq r$) is defined as $$\\max(a_l, a_{l+1}, \\ldots, a_r) \\oplus (a_l \\oplus a_{l+1} \\oplus \\ldots \\oplus a_r),$$ where $\\oplus$ denotes the bitwise XOR operation.\n\nFind the maximum numbness over all subarrays.",
    "tutorial": "The problem can be solved recursively. Keep dividing the array into subarrays at the maximum element of the current subarray. Let's say the maximum element of the initial array is at index $x$, so the array gets divided into two subarrays $a[1...x-1]$ and $a[x+1,...n]$. Say we have already calculated the answer for the left and right subarrays. Now, we need to calculate the answer for all the subarrays containing $a[x]$ to complete the process for the array. To do this, we will maintain two separate tries for both the left and right parts. This trie will contain all the prefix xor values for all the indices in the respective part. We will iterate over the smaller subarray out of the two. For every index, we will try to find the largest answer that can be obtained from a subarray with one end at this index. This can be done by moving the prefix xor value at the current index (xor'ed with $a[x]$) over the 'prefix xor trie' of the other subarray. This will cover all the subarrays containing $a[x]$, and so the entire array will now get covered. After the process, we will merge the two tries into one by again iterating over the smaller subarray. Similarly, we can solve for left subarray and right subarray by finding their respective maximum element, and dividing the subarray at that element. As we follow small-to-large merging, there are about $nlogn$ operations on the trie, and so the overall time complexity is $\\mathcal{O}(n \\log n \\log A)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nstruct Trie{\n\tstruct Trie *child[2]={0};\n};\ntypedef struct Trie trie;\n \nvoid insert(trie *dic, int x)\n{\n\ttrie *temp = dic;\n\tfor(int i=30;i>=0;i--) \n\t{\n\t\tint curr = x>>i&1;\n\t\tif(temp->child[curr])\n\t\t\ttemp = temp->child[curr];\n\t\telse\n\t\t{\n\t\t\ttemp->child[curr] = new trie;\n\t\t\ttemp = temp->child[curr];\n\t\t}\n\t}\n}\n \nint find_greatest(trie *dic, int x) {\n\tint res = 0;\n\ttrie *temp = dic;\n\tfor(int i=30;i>=0;i--) {\n\t\tint curr = x>>i&1;\n\t\tif(temp->child[curr^1]) {\n\t\t\tres ^= 1<<i;\n\t\t\ttemp = temp->child[curr^1];\n\t\t}\n\t\telse {\n\t\t\ttemp = temp->child[curr];\n\t\t}\n\t}\n\treturn res;\t\n}\n \nint main() {\n\tint test_cases;\n\tcin >> test_cases;\n\twhile(test_cases--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tint a[n+1];\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\tcin>>a[i];\n\t\t}\n \n\t\ttrie *t[n+2];\n\t\tint prexor[n+1];\n\t\tprexor[0] = 0;\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\tt[i] = new trie;\n\t\t\tinsert(t[i], prexor[i-1]);\n\t\t\tprexor[i] = prexor[i-1]^a[i];\n\t\t}\n\t\tt[n+1] = new trie;\n\t\tinsert(t[n+1], prexor[n]);\n\t\t\n\t\tpair<int,int> asc[n+1];\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\tasc[i] = make_pair(a[i],i);\n\t\t}\n\t\tsort(asc+1,asc+n+1);\n\t\t\n\t\tint left[n+1], right[n+1];\n\t\tstack<int> s;\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\twhile(!s.empty() && a[i]>=a[s.top()])\n\t\t\t\ts.pop();\n\t\t\tif(s.empty())\n\t\t\t\tleft[i] = 0;\n\t\t\telse\n\t\t\t\tleft[i] = s.top();\n\t\t\ts.push(i);\n\t\t}\n\t\twhile(!s.empty()) \n\t\t\ts.pop();\n\t\tfor(int i=n;i>0;i--) {\n\t\t\twhile(!s.empty() && a[i]>a[s.top()])\n\t\t\t\ts.pop();\n\t\t\tif(s.empty())\n\t\t\t\tright[i] = n+1;\n\t\t\telse\n\t\t\t\tright[i] = s.top();\n\t\t\ts.push(i);\n\t\t}\n\t\t\n\t\tint ans = 0;\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\tint x = asc[i].second;\n\t\t\tint r = right[x]-1;\n\t\t\tint l = left[x]+1;\n\t\t\tif(x-l < r-x) {\n\t\t\t\tfor(int j=l-1;j<x;j++) {\n\t\t\t\t\tans = max(ans, find_greatest(t[x+1], prexor[j]^a[x]));\n\t\t\t\t}\n\t\t\t\tt[l] = t[x+1];\n\t\t\t\tfor(int j=l-1;j<x;j++) {\n\t\t\t\t\tinsert(t[l], prexor[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor(int j=x;j<=r;j++) {\n\t\t\t\t\tans = max(ans, find_greatest(t[l], prexor[j]^a[x]));\n\t\t\t\t}\n\t\t\t\tfor(int j=x;j<=r;j++) {\n\t\t\t\t\tinsert(t[l], prexor[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout<<ans << endl;\n\t}\n}\n",
    "tags": [
      "bitmasks",
      "data structures",
      "divide and conquer",
      "strings",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1778",
    "index": "A",
    "title": "Flip Flop Sum",
    "statement": "You are given an array of $n$ integers $a_1, a_2, \\ldots, a_n$. The integers are either $1$ or $-1$. You have to perform the following operation \\textbf{exactly once} on the array $a$:\n\n- Choose an index $i$ ($1 \\leq i < n$) and flip the signs of $a_i$ and $a_{i+1}$. Here, flipping the sign means $-1$ will be $1$ and $1$ will be $-1$.\n\nWhat is the maximum possible value of $a_1 + a_2 + \\ldots + a_n$ after applying the above operation?",
    "tutorial": "Let's say we've chosen index $i$. What will happen? If the values of $a_i$ and $a_{i+1}$ have opposite signs, flipping them won't change the initial $sum$. if $a_i$ = $a_{i+1}$ = $1$, flipping them will reduce the $sum$ by $4$. if $a_i$ = $a_{i+1}$ = $-1$, flipping them will increase the $sum$ by $4$. So, for each $i < n$, we can check the values of $a_i$ and $a_{i+1}$, and we can measure the effects on the $sum$ based on the three cases stated above. Among the effects, take the one that maximizes the $sum$. Time complexity: In each test case, $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int sz = 1e5 + 10;\nint ara[sz];\n \nint main()\n{\n    int t;\n    scanf(\"%d\", &t);\n \n    while(t--) {\n        int n;\n        scanf(\"%d\", &n);\n \n        int sum = 0;\n \n        for(int i = 1; i <= n; i++) {\n            scanf(\"%d\", &ara[i]);\n            sum += ara[i];\n        }\n \n        int ans = -1e9;\n \n        for(int i = 1; i < n; i++) {\n            if(ara[i] == ara[i+1]) {\n                if(ara[i] == 1) ans = max(ans, sum-4);\n                else ans = max(ans, sum+4);\n            }\n            else\n                ans = max(ans, sum);\n        }\n \n        printf(\"%d\\n\", ans);\n    }\n \n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1778",
    "index": "B",
    "title": "The Forbidden Permutation",
    "statement": "You are given a permutation $p$ of length $n$, an array of $m$ \\textbf{distinct} integers $a_1, a_2, \\ldots, a_m$ ($1 \\le a_i \\le n$), and an integer $d$.\n\nLet $\\mathrm{pos}(x)$ be the index of $x$ in the permutation $p$. The array $a$ is \\textbf{not good} if\n\n- $\\mathrm{pos}(a_{i}) < \\mathrm{pos}(a_{i + 1}) \\le \\mathrm{pos}(a_{i}) + d$ for all $1 \\le i < m$.\n\nFor example, with the permutation $p = [4, 2, 1, 3, 6, 5]$ and $d = 2$:\n\n- $a = [2, 3, 6]$ is a not good array.\n- $a = [2, 6, 5]$ is good because $\\mathrm{pos}(a_1) = 2$, $\\mathrm{pos}(a_2) = 5$, so the condition $\\mathrm{pos}(a_2) \\le \\mathrm{pos}(a_1) + d$ is not satisfied.\n- $a = [1, 6, 3]$ is good because $\\mathrm{pos}(a_2) = 5$, $\\mathrm{pos}(a_3) = 4$, so the condition $\\mathrm{pos}(a_2) < \\mathrm{pos}(a_3)$ is not satisfied.\n\nIn one move, you can swap two adjacent elements of the permutation $p$. What is the minimum number of moves needed such that the array $a$ becomes good? It can be shown that there always exists a sequence of moves so that the array $a$ becomes good.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$, but there is $4$ in the array).",
    "tutorial": "If the array $a$ is good, the answer is obviously $0$. Now, how can we optimally transform a not good array $a$ to a good array? Let, we are on the index $i$ $(i<m)$ and $x = a_i$, $y = a_{i+1}$. If we observe carefully, we will find that there are basically two cases that will make the array $a$ good: Move $x$ and $y$ in the permutation $p$ in such a way that $pos(y)$ becomes greater than $pos(x) + d$. To do that, in the permutation $p$, we can swap $x$ to the left and $y$ to the right. The total number of swaps needed is $= d - (pos(y) - pos(x)) + 1$. We need to check if there is enough space to the left of $pos(x)$ and to the right of $pos(y)$ to perform the needed number of swaps. Move $x$ and $y$ in the permutation $p$ in such a way that $pos(y)$ becomes smaller than $pos(x)$. To do that, In the permutation $p$, we can simply swap $y$ to the left until the condition is satisfied. The number of swaps needed is $pos(y) - pos(x)$. For each $i < m$, calculate the minimum number of swaps needed among these two cases. The minimum number of swaps among all $i < m$ will be the desired answer. Time complexity: In each test case, $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int sz = 1e5+10;\nint p[sz], a[sz], pos[sz];\n \nint main()\n{\n    int t;\n    scanf(\"%d\", &t);\n \n    while(t--) {\n        int n, m, d;\n        scanf(\"%d %d %d\", &n, &m, &d);\n \n        for(int i = 1; i <= n; i++) {\n            scanf(\"%d\", &p[i]);\n            pos[ p[i] ] = i;\n        }\n \n        for(int i = 1; i <= m; i++) {\n            scanf(\"%d\", &a[i]);\n        }\n \n        int ans = 1e9;\n \n        for(int i = 1; i < m; i++) {\n            if(pos[a[i+1]] <= pos[a[i]] || pos[a[i+1]]-pos[a[i]] > d) {\n                ans = 0;\n                break;\n            }\n \n            ans = min(ans, pos[a[i+1]] - pos[a[i]]);\n \n            int dist = pos[a[i+1]]-pos[a[i]];\n \n            int swapNeed = d-dist+1;\n            int swapPossible = (pos[a[i]]-1) + (n - pos[a[i+1]]);\n            if(swapPossible >= swapNeed) ans = min(ans, swapNeed);\n        }\n \n        printf(\"%d\\n\", ans);\n    }\n \n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1778",
    "index": "C",
    "title": "Flexible String",
    "statement": "You have a string $a$ and a string $b$. Both of the strings have length $n$. There are \\textbf{at most $10$ different characters} in the string $a$. You also have a set $Q$. Initially, the set $Q$ is empty. You can apply the following operation on the string $a$ any number of times:\n\n- Choose an index $i$ ($1\\leq i \\leq n$) and a lowercase English letter $c$. Add $a_i$ to the set $Q$ and then replace $a_i$ with $c$.\n\nFor example, Let the string $a$ be \"$\\tt{abecca}$\". We can do the following operations:\n\n- In the first operation, if you choose $i = 3$ and $c = \\tt{x}$, the character $a_3 = \\tt{e}$ will be added to the set $Q$. So, the set $Q$ will be $\\{\\tt{e}\\}$, and the string $a$ will be \"$\\tt{ab\\underline{x}cca}$\".\n- In the second operation, if you choose $i = 6$ and $c = \\tt{s}$, the character $a_6 = \\tt{a}$ will be added to the set $Q$. So, the set $Q$ will be $\\{\\tt{e}, \\tt{a}\\}$, and the string $a$ will be \"$\\tt{abxcc\\underline{s}}$\".\n\nYou can apply any number of operations on $a$, but in the end, the set $Q$ should contain \\textbf{at most $k$ different characters}. Under this constraint, you have to maximize the number of integer pairs $(l, r)$ ($1\\leq l\\leq r \\leq n$) such that $a[l,r] = b[l,r]$. Here, $s[l,r]$ means the substring of string $s$ starting at index $l$ (inclusively) and ending at index $r$ (inclusively).",
    "tutorial": "If we can replace all the characters of the string $a$, we can transform the string $a$ to the string $b$. So, replacing more characters is always beneficial. For a fixed string $a$ and another fixed string $b$, if the answer is $x_1$ for $k_1$ and $x_2$ for $k_2$ $(k_1 < k_2)$, it can be shown that $x_1 \\leq x_2$ always satisfies. That is to say, we can safely consider the size of the set $q$ to be the maximum limit $min(k, u)$ where $u$ is the number of unique characters in the string $a$. Now, we can generate all possible sets of characters having size $min(k, u)$. Obviously, we won't take the characters that are not present in the string $a$ because they have no effect on the answer. There are many ways to generate the sets, like backtracking, bitmasking, etc. If we can calculate the number of valid pairs $(l, r)$ for each set efficiently, the rest task will be just taking the maximum of them. To calculate the number of pairs for each set efficiently, we can observe the fact that if $a[l,r]=b[l,r]$ is true, $a[p,q] = b[p,q]$ satisfies for any $l\\leq p\\leq q\\leq r$. So, we will get $\\frac{c\\times (c+1)}{2}$ number of valid pairs from here where $c=r-l+1$. Now, we can start iterating from the beginning of the string $a$. We can say that $a_i$ matches $b_i$ if they are equal or $a_i$ exists in the currently generated set. While iterating, when we are on the $j$th index, we need to find the rightmost index $r$ such that $a[j,r]=b[j,r]$ satisfies. Then we need to add the number of valid pairs in this range to the contribution of this set. After that, we need to set the value of $j$ to $r+1$ and repeat the steps again. The rest of the tasks are trivial. Time complexity: In each test case, $\\mathcal{O}(n\\times \\binom{u}{m})$, where $m=min(k,u)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define ll long long\n#define pb push_back\n#define EL '\\n'\n#define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n \nstring a, b;\nstring char_list;\nbool mark[26];\nll ans, k;\n \nll count_matching_pair()\n{\n    ll tot_pair = 0, match_count = 0;\n \n    for(ll i = 0; i < a.size(); i++) {\n        if(a[i] == b[i] || mark[ a[i]-'a' ])\n            match_count++;\n        else {\n            tot_pair += match_count*(match_count+1)/2;\n            match_count = 0;\n        }\n    }\n    tot_pair += match_count*(match_count+1)/2;\n \n    return tot_pair;\n}\n \nvoid solve(ll pos, ll cnt)\n{\n    if(cnt > k) return;\n \n    if(pos == char_list.size()) {\n        if(cnt == k) ans = max(ans, count_matching_pair());\n        return;\n    }\n \n    solve(pos+1, cnt);\n \n    mark[ char_list[pos]-'a' ] = 1;\n    solve(pos+1, cnt+1);\n    mark[ char_list[pos]-'a' ] = 0;\n}\n \nint main()\n{\n    fastio;\n    ll t;\n    cin >> t;\n \n    while(t--) {\n        ll n; cin >> n >> k;\n        cin >> a >> b;\n \n        unordered_set <char> unq;\n        for(auto &ch : a) unq.insert(ch);\n \n        char_list.clear();\n        for(auto &x : unq) char_list.pb(x);\n \n        k = min(k, (ll)unq.size());\n        memset(mark, 0, sizeof mark);\n        ans = 0;\n        solve(0, 0);\n \n        cout << ans << EL;\n    }\n \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1778",
    "index": "D",
    "title": "Flexible String Revisit",
    "statement": "You are given two binary strings $a$ and $b$ of length $n$. In each move, the string $a$ is modified in the following way.\n\n- An index $i$ ($1 \\leq i \\leq n$) is chosen uniformly at random. The character $a_i$ will be flipped. That is, if $a_i$ is $0$, it becomes $1$, and if $a_i$ is $1$, it becomes $0$.\n\nWhat is the expected number of moves required to make both strings equal \\textbf{for the first time}?\n\nA binary string is a string, in which the character is either $\\tt{0}$ or $\\tt{1}$.",
    "tutorial": "Let $k$ be the number of indices where the characters between two strings are different and $f(x)$ be the expected number of moves to make two strings equal given that the strings have $x$ differences. We have to find the value of $f(k)$. For all $x$ where $1 \\leq x \\leq n-1$, $\\begin{align} f(x) = \\frac{x}{n} \\cdot [1 + f(x-1)] + \\frac{n-x}{n} \\cdot [1 + f(x+1)]\\\\ or,~~~ f(x) = 1 + \\frac{x}{n}\\cdot f(x-1) + \\frac{n-x}{n} \\cdot f(x+1) \\end{align}$ Now, $f(0) = 0$ and $f(1) = 1 + \\frac{n-1}{n}f(2)$. We can represent any $f(i)$ in the form $f(i) = a_i + b_i \\cdot f(i+1)$. Let, $a_{1} = 1$ and $b_{1} = \\frac{n-1}{n}$. So, we can write $f(1) = a_{1} + b_{1}\\cdot f(2)$. When $1 \\lt i \\lt n$, $f(i) = 1 + \\frac{i}{n} \\cdot f(i-1) + \\frac{n-i}{n} \\cdot f(i+1)$. We can substitute the value of $f(i-1)$ with $a_{i-1} + b_{i-1}\\cdot f(i)$ and calculate the value of $f(i)$. Thus we can get the value of $a_i$ and $b_i$ using the value of $a_{i-1}$ and $b_{i-1}$ by considering $a_1$ and $b_1$ as the base case. We get, $a_{i} = \\frac{n+i\\cdot a_{i-1}}{n-i\\cdot b_{i-1}}$ and $b_{i} = \\frac{n-i}{n-i \\cdot b_{i-1}}$ for $2 \\leq i \\leq n$. Substituting $f(i-1) = a_{i-1} + b_{i-1}\\cdot f(i)$, $\\begin{align} f(i) & = 1 + \\frac{i}{n} \\cdot [a_{i-1} + b_{i-1}\\cdot f(i)] + \\frac{n-i}{n} \\cdot f(i+1)\\\\ & = 1 + \\frac{i}{n}\\cdot a_{i-1} + \\frac{i}{n} \\cdot b_{i-1} \\cdot f(i) + \\frac{n-i}{n} \\cdot f(i+1)\\\\ & = \\frac{1+\\frac{i}{n}\\cdot a_{i-1}}{1-\\frac{i}{n}\\cdot b_{i-1}} + \\frac{n-i}{n-i \\cdot b_{i-1}}f(i+1)\\\\ & = \\frac{n+i\\cdot a_{i-1}}{n-i\\cdot b_{i-1}} + \\frac{n-i}{n-i \\cdot b_{i-1}}f(i+1)\\\\ & = a_{i} + b_{i} \\cdot f(i+1) \\end{align}$ So, $a_{i} = \\frac{n+i\\cdot a_{i-1}}{n-i\\cdot b_{i-1}}$ and $b_{i} = \\frac{n-i}{n-i \\cdot b_{i-1}}$ for $2 \\leq i \\leq n$. Similarly, $f(n) = 1+f(n-1)$. We can represent any $f(i)$ in the form $f(i) = c_i + d_i \\cdot f(i-1)$. Let, $c_{n} = 1$ and $d_{n} = 1$. So, we can write $f(n) = c_{n} + d_{n}\\cdot f(n-1)$. When $1 \\lt i \\lt n$, $f(i) = 1 + \\frac{i}{n} \\cdot f(i-1) + \\frac{n-i}{n} \\cdot f(i+1)$. We can substitute the value of $f(i+1)$ with $c_{i+1} + d_{i+1}\\cdot f(i)$ and calculate the value of $f(i)$. Thus we can get the value of $c_i$ and $d_i$ using the value of $c_{i+1}$ and $d_{i+1}$ by considering $c_n$ and $d_n$ as the base case. We get, $c_{i} = \\frac{n+(n-i)\\cdot c_{i+1}}{n-(n-i)\\cdot d_{i+1}}$ and $d_{i} = \\frac{i}{n-(n-i) \\cdot d_{i+1}}$. Substituting $f(i+1) = c_{i+1} + d_{i+1}\\cdot f(i)$, $\\begin{align} f(i) & = 1 + \\frac{i}{n} \\cdot f(i-1) + \\frac{n-i}{n} \\cdot [c_{i+1} + d_{i+1}\\cdot f(i)]\\\\ & = 1 + \\frac{i}{n}\\cdot f(i-1) + \\frac{n-i}{n} \\cdot c_{i+1} + \\frac{n-i}{n} \\cdot d_{i+1} \\cdot f(i)\\\\ & = \\frac{1+\\frac{n-i}{n}\\cdot c_{i+1}}{1-\\frac{n-i}{n}\\cdot d_{i+1}} + \\frac{i}{n-(n-i) \\cdot d_{i+1}}f(i-1)\\\\ & = \\frac{n+(n-i)\\cdot c_{i+1}}{n-(n-i)\\cdot d_{i+1}} + \\frac{i}{n-(n-i) \\cdot d_{i+1}}f(i-1)\\\\ & = c_{i} + d_{i} \\cdot f(i-1) \\end{align}$ So, $c_{i} = \\frac{n+(n-i)\\cdot c_{i+1}}{n-(n-i)\\cdot d_{i+1}}$ and $d_{i} = \\frac{i}{n-(n-i) \\cdot d_{i+1}}$. Now, $f(i) = c_i + d_i \\cdot f(i-1)$ and $f(i-1) = a_{i-1} + b_{i-1} \\cdot f(i)$. By solving these two equations, we find that $f(i) = \\frac{c_i+d_i \\cdot a_{i-1}}{1-d_i \\cdot b_{i-1}}$. Time Complexity: $\\mathcal{O}(n\\cdot \\log m)$. After some calculations, it can be shown that $f(1) = 2^n - 1$. Now we know $f(0) = 0$ and $f(1) = 2^n - 1$. From the relation between $f(i)$, $f(i-1)$ and $f(i-2)$, we can write $f(i) = \\frac{n\\cdot f(i-1) - i \\cdot f(i-2) - n}{n-i+1}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define ll long long\n \ntemplate<int MOD>\nstruct ModInt {\n  unsigned x;\n  ModInt() : x(0) { }\n  ModInt(signed sig) : x(sig) {  }\n  ModInt(signed long long sig) : x(sig%MOD) { }\n  int get() const { return (int)x; }\n  ModInt pow(ll p) { ModInt res = 1, a = *this; while (p) { if (p & 1) res *= a; a *= a; p >>= 1; } return res; }\n \n  ModInt &operator+=(ModInt that) { if ((x += that.x) >= MOD) x -= MOD; return *this; }\n  ModInt &operator-=(ModInt that) { if ((x += MOD - that.x) >= MOD) x -= MOD; return *this; }\n  ModInt &operator*=(ModInt that) { x = (unsigned long long)x * that.x % MOD; return *this; }\n  ModInt &operator/=(ModInt that) { return (*this) *= that.pow(MOD - 2); }\n \n  ModInt operator+(ModInt that) const { return ModInt(*this) += that; }\n  ModInt operator-(ModInt that) const { return ModInt(*this) -= that; }\n  ModInt operator*(ModInt that) const { return ModInt(*this) *= that; }\n  ModInt operator/(ModInt that) const { return ModInt(*this) /= that; }\n  bool operator<(ModInt that) const { return x < that.x; }\n  friend ostream& operator<<(ostream &os, ModInt a) { os << a.x; return os; }\n};\ntypedef ModInt<998244353> mint;\n \nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n \n    mint two = 2;\n \n    int t;\n    cin >> t;\n    while(t--){\n        int n;\n        cin >> n;\n \n        string a, b;\n        cin >> a >> b;\n \n        int cnt = 0;\n        for(int i = 0; i < n; i++){\n            if(a[i]!=b[i]) cnt++;\n        }\n \n        vector<mint> dp(n+2);\n        dp[0] = two.pow(n);\n        dp[1] = dp[0]-1;\n        dp[0] = 0;\n \n        for(long long i = 2; i < n; i++){\n            mint x = i-1;\n            x /= n;\n            dp[i] = (dp[i-1]-x*dp[i-2]-1)*n/(n-i+1);\n        }\n \n        dp[n] = dp[n-1]+1;\n \n        cout << dp[cnt] << '\\n';\n    }\n \n    return 0;\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1778",
    "index": "E",
    "title": "The Tree Has Fallen!",
    "statement": "Recently, a tree has fallen on Bob's head from the sky. The tree has $n$ nodes. Each node $u$ of the tree has an integer number $a_u$ written on it. But the tree has no fixed root, as it has fallen from the sky.\n\nBob is currently studying the tree. To add some twist, Alice proposes a game. First, Bob chooses some node $r$ to be the root of the tree. After that, Alice chooses a node $v$ and tells him. Bob then can pick one or more nodes from the subtree of $v$. His score will be the bitwise XOR of all the values written on the nodes picked by him. Bob has to find the maximum score he can achieve for the given $r$ and $v$.\n\nAs Bob is not a good problem-solver, he asks you to help him find the answer. Can you help him? You need to find the answers for several combinations of $r$ and $v$ for the same tree.\n\nRecall that a tree is a connected undirected graph without cycles. The subtree of a node $u$ is the set of all nodes $y$ such that the simple path from $y$ to the root passes through $u$. Note that $u$ is in the subtree of $u$.",
    "tutorial": "At first, we can think of another problem. Given an array. You need to find the maximum subset $XOR$. How can we solve it? We can solve this problem very efficiently using a technique called \"$XOR$ Basis\". You can read about it from here. In problem E, at first, we can fix any node as the root of the tree. Let's call this rooted tree the base tree. After that, start an Euler tour from the root and assign discovery time $d_u$ and finishing time $f_u$ to each node $u$. In each query, three types of cases can occur (node $r$ and node $v$ are from the query format): $r=v$. In this case, we need to calculate the maximum subset $XOR$ of the whole tree. Node $v$ is not an ancestor of node $r$ in the base tree. So, the subtree of node $v$ will remain the same. Node $v$ is an ancestor of node $r$ in the base tree. What will be the new subtree of node $v$ in this case? This is a bit tricky. Let's denote such a node $c$ that is a child of node $v$ and an ancestor of node $r$ in the base tree. Then the new subtree of node $v$ will contain the whole tree except the subtree (in the base tree) of node $c$. Let's say, $in_u$ is the $XOR$ basis of all the values in node $u$'s subtree (in the base tree). We can build $in_u$ by inserting the value $a_u$ to $in_u$ and merging it with all of its children $w$'s basis $in_w$. Two basis can be merged in $O(log^2(d))$ complexity, where $d$ is their dimension. If we can build the basis $in_u$ for each node $u$, we are able to answer the case $1$ and case $2$. To answer case $2$, we need to find the maximum subset $XOR$ in the corresponding basis. To answer case $1$, we need to do a similar thing in the basis $in_{root}$, where $root$ is the root node of the base tree. For case $3$, let's say $out_u$ is the $XOR$ basis of all the values of the base tree except the node $u$'s subtree (in the base tree). Then the answer of the case $3$ will be the maximum subset $XOR$ in the basis $out_c$. To build the basis $out_u$ for each node $u$, we can utilize the properties of the discovery time $d_u$ and finishing time $f_u$. Which nodes will be outside the subtree of node $u$? The nodes $w$ that have either $d_w < d_u$ or $d_w > f_u$. To merge their basis easily, we can pre-calculate two basis arrays $pre[]$ and $suf[]$ where the basis $pre_i$ includes all the values of the nodes $w$ such that $d_w \\leq i$ and the basis $suf_i$ includes all the values of the nodes $w$ such that $d_w \\geq i$. To find the node $c$ in the case $3$, we can perform a binary search on the children of node $v$. We can use the fact that the order of the discovery times follows the order of the children and a node $c$ is only an ancestor of a node $r$ iff $d_c \\leq d_r$ && $f_c \\geq f_r$. Time complexity: $\\mathcal{O}(n\\times log^2(d))$, where $d = max(a_i)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define ll long long\n#define pb push_back\n#define nn '\\n'\n#define fastio std::ios_base::sync_with_stdio(false); cin.tie(NULL);\n \nconst int sz = 2e5 + 10, d = 30;\nvector <int> g[sz], Tree[sz];\nint a[sz], discover_time[sz], finish_time[sz], nodeOf[sz], tim;\n \nstruct BASIS {\n    int basis[d];\n    int sz;\n \n    void init() {\n        for(int i = 0; i < d; i++) basis[i] = 0;\n        sz = 0;\n    }\n \n    void insertVector(int mask) {\n        for (int i = d-1; i >= 0; i--) {\n            if (((mask>>i)&1) == 0) continue;\n \n            if (!basis[i]) {\n                basis[i] = mask;\n                ++sz;\n                return;\n            }\n            mask ^= basis[i];\n        }\n    }\n \n    void mergeBasis(const BASIS &from) {\n        for(int i = d-1; i >= 0; i--) {\n            if(!from.basis[i])\n                continue;\n \n            insertVector(from.basis[i]);\n        }\n    }\n \n    int findMax()  {\n        int ret = 0;\n        for(int i = d-1; i >= 0; i--) {\n            if(!basis[i] || (ret>>i & 1))\n                continue;\n \n            ret ^= basis[i];\n        }\n        return ret;\n    }\n} in[sz], out, pre[sz], suf[sz];\n \nvoid in_dfs(int u, int p)\n{\n    in[u].insertVector(a[u]);\n    discover_time[u] = ++tim;\n    nodeOf[tim] = u;\n \n    for(auto &v : g[u]) {\n        if(v == p)\n            continue;\n \n        Tree[u].pb(v);\n        in_dfs(v, u);\n \n        in[u].mergeBasis(in[v]);\n    }\n    finish_time[u] = tim;\n}\n \ninline bool in_subtree(int sub_root, int v)\n{\n    return discover_time[sub_root] <= discover_time[v]\n            && finish_time[sub_root] >= finish_time[v];\n}\n \nint findChildOnPath(int sub_root, int v)\n{\n    int lo = 0, hi = (int)Tree[sub_root].size()-1;\n \n    while(lo <= hi) {\n        int mid = lo+hi>>1, node = Tree[sub_root][mid];\n \n        if(finish_time[node] < discover_time[v])\n            lo = mid + 1;\n        else if(discover_time[node] > discover_time[v])\n            hi= mid - 1;\n        else\n            return node;\n    }\n}\n \nvoid init(int n) {\n \n    for(int i = 0; i <= n+5; i++) {\n        g[i].clear(), Tree[i].clear();\n        in[i].init();\n        pre[i].init(), suf[i].init();\n    }\n    tim = 0;\n}\n \nint main()\n{\n    fastio;\n \n    int t;\n    cin >> t;\n \n    while(t--) {\n        int n; cin >> n;\n \n        init(n);\n \n        for(int i = 1; i <= n; i++) cin >> a[i];\n \n        for(int i = 1; i < n; i++) {\n            int u, v;\n            cin >> u >> v;\n            g[u].pb(v); g[v].pb(u);\n        }\n \n        in_dfs(1, -1);\n \n        for(int i = 1; i <= n; i++) {\n            pre[i].insertVector(a[ nodeOf[i] ]);\n            pre[i].mergeBasis(pre[i-1]);\n        }\n \n        for(int i = n; i >= 1; i--) {\n            suf[i].insertVector(a[ nodeOf[i] ]);\n            suf[i].mergeBasis(suf[i+1]);\n        }\n \n        int q; cin >> q;\n \n        while(q--) {\n            int root, v;\n            cin >> root >> v;\n \n            if(root == v) {\n                cout << in[1].findMax() << nn;\n            }\n            else if(in_subtree(v, root)) {\n                int child = findChildOnPath(v, root);\n \n                out.init();\n                out.mergeBasis(pre[discover_time[child]-1]);\n                out.mergeBasis(suf[finish_time[child]+1]);\n                cout << out.findMax() << nn;\n            }\n            else\n                cout << in[v].findMax() << nn;\n        }\n    }\n \n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "math",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1778",
    "index": "F",
    "title": "Maximizing Root",
    "statement": "You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. Vertex $1$ is the root of the tree. Each vertex has an integer value. The value of $i$-th vertex is $a_i$. You can do the following operation at most $k$ times.\n\n- Choose a vertex $v$ \\textbf{that has not been chosen before} and an integer $x$ such that $x$ is a common divisor of the values of all vertices of the subtree of $v$. Multiply by $x$ the value of each vertex in the subtree of $v$.\n\nWhat is the maximum possible value of the root node $1$ after at most $k$ operations? Formally, you have to maximize the value of $a_1$.\n\nA tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. The subtree of a node $u$ is the set of all nodes $y$ such that the simple path from $y$ to the root passes through $u$. Note that $u$ is in the subtree of $u$.",
    "tutorial": "Let, $x_u$ be the value of node $u$ and $dp[u][d]$ be the minimum number of moves required to make the GCD of the subtree of $u$ equal to a multiple of $d$. Now, $dp[u][d] = 0$ if the subtree GCD of node $u$ is already a multiple of $d$ and $dp[u][d] = \\infty$ if $(x_u \\cdot x_u)$ is not a multiple of $d$. For each divisor $y$ of $d$, suppose, we want to perform the move on the subtree of $u$ by multiplying each node value of the subtree with $y$ iff $(x_u\\cdot y)$ is a multiple of $d$ and $y$ is a divisor of $x_u$. In this case, we have to make the GCD of all the subtree of child nodes of $u$ equal to a multiple of $LCM(\\frac{d}{y}, y)$ before performing the move on the subtree of $u$. This is because we have to make each node of the subtree a multiple of $\\frac{d}{y}$ to get the multiple of $d$ after performing the move on the subtree of node $u$ using $y$. Also, to perform the move of multiplying by $y$, the value of each subtree node should be a multiple of $y$. So we have to make each node value a multiple of $LCM(\\frac{d}{y}, y)$. So, $dp[u][d]$ will be calculated from $dp[v][LCM(\\frac{d}{y}, y)]$ for each divisor $y$ of $d$ for all child $v$ of $u$. Now, $x_1\\cdot D$ is the answer where $D$ is the largest divisor of $x_1$ such that $k \\geq dp[1][D]$. Time Complexity: $O(n\\cdot m^2)$ where $m$ is the number of divisors of $x_1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 100005;\nconst int mod = 998244353;\n \nint val[N];\nvector<int> g[N];\nvector<int> divisor[N];\nint subtree_gcd[N], par[N];\n \nint dp[N][1003];\nint gcdd[1003][1003];\n \ninline long long ___gcd(long long a, long long b){\n    if(gcdd[a][b]) return gcdd[a][b];\n \n    return gcdd[a][b] = __gcd(a, b);\n}\n \ninline long long lcm(long long a, long long b){\n    return (a/___gcd(a, b))*b;\n}\n \nvoid dfs(int u, int p){\n    par[u] = p;\n    subtree_gcd[u] = val[u];\n    for(int v: g[u]){\n        if(v==p) continue;\n        dfs(v, u);\n        subtree_gcd[u] = ___gcd(subtree_gcd[u], subtree_gcd[v]);\n    }\n}\n \n \nint solve(int u, int d, int p){\n    if(subtree_gcd[u]%d==0) return 0;\n    if((val[u]*val[u])%d) return (1<<30);\n \n \n    if(dp[u][d]!=-1) return dp[u][d];\n    \n    long long req = d/___gcd(d, subtree_gcd[u]);\n \n    long long res = (1<<30);\n    for(int div: divisor[val[u]]){\n        if((val[u]*div)%d==0 && d%div==0){\n            long long r = 1;\n            for(int v: g[u]){\n                if(v==p) continue;\n                r += solve(v, lcm(d/div, div), u);\n            }\n            res = min(res, r);\n        }\n    }\n \n    return dp[u][d] = min(res, (1LL<<30));\n}\n \nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    for(int i = 2; i < 1001; i++){\n        for(int j = i; j < 1001; j+=i){\n            divisor[j].push_back(i);\n        }\n    }\n \n    int t;\n    cin >> t;\n \n    while(t--){\n        int n, k;\n        cin >> n >> k;\n \n        for(int i = 0; i <= n; i++){\n            g[i].clear();\n        }\n \n        for(int i = 1; i <= n; i++){\n            cin >> val[i];\n        }\n        \n        for(int i = 0; i <= n; i++){\n            for(int d: divisor[val[1]]){\n                dp[i][d] = -1;\n            }\n        }\n \n        for(int i = 0; i < n-1; i++){\n            int u, v;\n            cin >> u >> v;\n            g[u].push_back(v);\n            g[v].push_back(u);\n        }\n \n        dfs(1, 0);\n \n        int ans = val[1];\n \n        for(int d: divisor[val[1]]){\n            int req = 0;\n            int f = 1;\n            for(int v: g[1]){\n                int x = solve(v, d, par[v]);\n                if(x>n) f = 0;\n                req += x;\n            }\n \n            if(!f) continue;\n \n            req++;\n            if(req<=k){\n                ans = max(ans, val[1]*d);\n            }\n        }\n \n        cout << ans << \"\\n\";\n    }\n    \n    return 0;\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1779",
    "index": "A",
    "title": "Hall of Fame",
    "statement": "Thalia is a Legendary Grandmaster in chess. She has $n$ trophies in a line numbered from $1$ to $n$ (from left to right) and a lamp standing next to each of them (the lamps are numbered as the trophies).\n\nA lamp can be directed either to the left or to the right, and it illuminates all trophies in that direction (but not the one it is next to). More formally, Thalia has a string $s$ consisting only of characters 'L' and 'R' which represents the lamps' current directions. The lamp $i$ illuminates:\n\n- trophies $1,2,\\ldots, i-1$ if $s_i$ is 'L';\n- trophies $i+1,i+2,\\ldots, n$ if $s_i$ is 'R'.\n\nShe can perform the following operation \\textbf{at most} once:\n\n- Choose an index $i$ ($1 \\leq i < n$);\n- Swap the lamps $i$ and $i+1$ (without changing their directions). That is, swap $s_i$ with $s_{i+1}$.\n\nThalia asked you to illuminate all her trophies (make each trophy illuminated by at least one lamp), or to tell her that it is impossible to do so. If it is possible, you can choose to perform an operation or to do nothing. Notice that lamps \\textbf{cannot} change direction, it is only allowed to swap adjacent ones.",
    "tutorial": "What happens when $\\texttt{L}$ appears after some $\\texttt{R}$ in the string? Suppose that there exists an index $i$ such that $s_i = \\texttt{R}$ and $s_{i+1} = \\texttt{L}$. Lamp $i$ illuminates trophies $i+1,i+2,\\ldots n$ and lamp $i+1$ illuminates $1,2,\\ldots i$. We can conclude that all trophies are illuminated if $\\texttt{L}$ appears right after some $\\texttt{R}$. So, strings $\\texttt{LLRRLL}, \\texttt{LRLRLR}, \\texttt{RRRLLL}, \\ldots$ do not require any operations to be performed on them, since they represent configurations of lamps in which all trophies are already illuminated. Now, we consider the case when such $i$ does not exist and think about how we can use the operation once. Notice that if $\\texttt{R}$ appears right after some $\\texttt{L}$, an operation can be used to transform $\\texttt{LR}$ into $\\texttt{RL}$, and we have concluded before that all trophies are illuminated in that case. So, if $\\texttt{LR}$ appears in the string, we perform the operation on it. An edge case is when $\\texttt{L}$ and $\\texttt{R}$ are never adjacent (neither $\\texttt{LR}$ nor $\\texttt{RL}$ appears). Notice that $s_i = s_{i+1}$ must hold for $i=1,2,\\ldots n-1$ in that case, meaning that $\\texttt{LL} \\ldots \\texttt{L}$ and $\\texttt{RR} \\ldots \\texttt{R}$ are the only impossible strings for which the answer is $-1$. Solve the task in which $q \\leq 10^5$ range queries are given: for each segment $[l,r]$ print the required index $l \\leq i < r$, $0$ or $-1$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1779",
    "index": "B",
    "title": "MKnez's ConstructiveForces Task",
    "statement": "MKnez wants to construct an array $s_1,s_2, \\ldots , s_n$ satisfying the following conditions:\n\n- Each element is an integer number different from $0$;\n- For each pair of adjacent elements their sum is equal to the sum of the whole array.\n\nMore formally, $s_i \\neq 0$ must hold for each $1 \\leq i \\leq n$. Moreover, it must hold that $s_1 + s_2 + \\cdots + s_n = s_i + s_{i+1}$ for each $1 \\leq i < n$.\n\nHelp MKnez to construct an array with these properties or determine that it does not exist.",
    "tutorial": "There always exists an answer for even $n$. Can you find it? There always exists an answer for odd $n \\geq 5$. Can you find it? If $n$ is even, the array $[-1,1,-1,1, \\ldots ,-1,1]$ is a solution. The sum of any two adjacent elements is $0$, as well as the sum of the whole array. Suppose that $n$ is odd now. Since $s_{i-1} + s_i$ and $s_i + s_{i+1}$ are both equal to the sum of the whole array for each $i=2,3,\\ldots n-1$, it must also hold that $s_{i-1} + s_i = s_i + s_{i+1}$, which is equivalent to $s_{i-1} = s_{i+1}$. Let's fix $s_1 = a$ and $s_2 = b$. The condition above produces the array $s = [a,b,a,b, \\ldots a,b,a]$ (remember that we consider an odd $n$). Let $k$ be a positive integer such that $n = 2k+1$. The sum of any two adjacent elements is $a+b$ and the sum of the whole array is $(k+1)a + kb$. Since the two values are equal, we can conclude that $ka + (k-1)b = 0$. $a=k-1$ and $b=-k$ produces an answer. But, we must be careful with $a=0$ and $b=0$ since that is not allowed. If $k=1$ then $ka+(k-1)b=0$ implies $ka=0$ and $a=0$, so for $n=2\\cdot 1 + 1 = 3$ an answer does not exist. Otherwise, one can see that $a=k-1$ and $b=-k$ will be non-zero, which produces a valid answer. So, the array $[k-1, -k, k-1, -k, \\ldots, k-1, -k, k-1]$ is an answer for $k \\geq 2$ ($n \\geq 5$). Solve a generalized task with given $m$ - find an array $a_1,a_2, \\ldots a_n$ ($a_i \\neq 0$) such that $a_i + a_{i+1} + \\ldots a_{i+m-1}$ is equal to the sum of the whole array for each $i=1,2,\\ldots n-m+1$ (or determine that it is impossible to find such array).",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1779",
    "index": "C",
    "title": "Least Prefix Sum",
    "statement": "Baltic, a famous chess player who is also a mathematician, has an array $a_1,a_2, \\ldots, a_n$, and he can perform the following operation several (possibly $0$) times:\n\n- Choose some index $i$ ($1 \\leq i \\leq n$);\n- multiply $a_i$ with $-1$, that is, set $a_i := -a_i$.\n\nBaltic's favorite number is $m$, and he wants $a_1 + a_2 + \\cdots + a_m$ to be the smallest of all non-empty prefix sums. More formally, for each $k = 1,2,\\ldots, n$ it should hold that $$a_1 + a_2 + \\cdots + a_k \\geq a_1 + a_2 + \\cdots + a_m.$$\n\nPlease note that multiple smallest prefix sums may exist and that it is only required that $a_1 + a_2 + \\cdots + a_m$ is one of them.\n\nHelp Baltic find the minimum number of operations required to make $a_1 + a_2 + \\cdots + a_m$ the least of all prefix sums. It can be shown that a valid sequence of operations always exists.",
    "tutorial": "Try a greedy approach. What data structure supports inserting an element, finding the maximum and erasing the maximum? That is right, a binary heap, or STL priority_queue. Let $p_i = a_1 + a_2 + \\ldots a_i$ and suppose that $p_x < p_m$ for some $x < m$. Let $x$ be the greatest such integer. Performing an operation to any element in the segment $[1,x]$ does nothing since $p_m - p_x$ stays the same. Similarly, performing an operation to any element in segment $[m+1,n]$ does not affect it. A greedy idea is to choose the maximal element in segment $[x+1,m]$ and perform an operation on it, because it decreases $p_m$ as much as possible. Repeat this process until $p_m$ eventually becomes less than or equal to $p_x$. It might happen that a new $p_y$ such that $p_y < p_m$ and $y<x$ emerges. In that case, simply repeat the algorithm until $p_m$ is less than or equal to any prefix sum in its \"left\". Suppose that $p_x < p_m$ and $x > m$ now. The idea is the same, choose a minimal element in segment $[m+1,x]$ and perform an operation on it as it increases $p_x$ as much as possible. And repeat the algorithm as long as such $x$ exists. To implement this, solve the two cases independently. Let's describe the first case as the second one is analogous. Iterate over $i$ from $m$ to $1$ and maintain a priority queue. If $p_i < p_m$, pop the queue (possibly multiple times) and decrease $p_m$ accordingly (we simulate performing the \"optimal\" operations). Notice that one does not have to update any element other than $p_m$. Add $a_i$ to the priority queue afterwards. The time complexity is $O(n \\log n)$. Solve the task for each $m=1,2,\\ldots, n$ i.e. print $n$ integers: the minimum number of operations required to make $a_1 + a_2 + \\ldots a_m$ a least prefix sum for each $m$ (the tasks are independent).",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1779",
    "index": "D",
    "title": "Boris and His Amazing Haircut",
    "statement": "Boris thinks that chess is a tedious game. So he left his tournament early and went to a barber shop as his hair was a bit messy.\n\nHis current hair can be described by an array $a_1,a_2,\\ldots, a_n$, where $a_i$ is the height of the hair standing at position $i$. His desired haircut can be described by an array $b_1,b_2,\\ldots, b_n$ in a similar fashion.\n\nThe barber has $m$ razors. Each has its own size and can be used \\textbf{at most} once. In one operation, he chooses a razor and cuts a segment of Boris's hair. More formally, an operation is:\n\n- Choose any razor which hasn't been used before, let its size be $x$;\n- Choose a segment $[l,r]$ ($1\\leq l \\leq r \\leq n$);\n- Set $a_i := \\min (a_i,x)$ for each $l\\leq i \\leq r$;\n\nNotice that some razors might have equal sizes — the barber can choose some size $x$ only as many times as the number of razors with size $x$.\n\nHe may perform as many operations as he wants, as long as any razor is used at most once and $a_i = b_i$ for each $1 \\leq i \\leq n$ at the end. He \\textbf{does not} have to use all razors.\n\nCan you determine whether the barber can give Boris his desired haircut?",
    "tutorial": "If $a_i < b_i$ for some $i$, then an answer does not exist since a cut cannot make a hair taller. If you choose to perform a cut on some segment $[l,r]$ with a razor of size $x$, you can \"greedily\" extend it (decrease $l$ and increase $r$) as long as $x \\geq b_i$ for each $i$ in that segment and still obtain a correct solution. There exist some data structures (segment tree, dsu, STL maps and sets, $\\ldots$) ideas, but there is also a simple solution with a STL stack. Consider $a_n$ and $b_n$. If $b_n$ is greater, the answer is NO since it is an impossible case (see \"Stupid Hint\" section). If $a_n$ is greater, then a cut on range $[l,n]$ with a razor of size $b_n$ has to be performed. Additionally, $l$ should be as small as possible (see \"Hint\" section). For each $i$ in the range, if $a_i$ becomes exactly equal to $b_i$, we consider the position $i$ satisfied. If $a_n$ and $b_n$ are equal, then we simply pop both arrays' ends (we ignore those values as they are already satisfied) and we continue our algorithm. Onto the implementation. We keep track (and count) of each razor size we must use. This can simply be done by putting the corresponding sizes into some container (array or vector) and checking at the end whether it is a subset of $x_1,x_2,\\ldots x_m$ (the input array of allowed razors). To do this, one can use sorting or maps. This part works in $O(n \\log n + m \\log m)$ time. Implementing cuts is more challenging, though. To do this, we keep a monotone stack which represents all cuts which are valid until \"now\" (more formally, all cuts with their $l$ being $\\leq i$, and the value of $l$ will be determined later). The top of the stack will represent the smallest razor, and the size of razors does not decrease as we pop it. So, we pop the stack as long as the top is smaller than $b_n$ (since performing an operation which makes $a_i$ less than $b_i$ is not valid). After this, if the new top is exactly equal to $b_n$ we can conclude that we have satisfied $a_n = b_n$ with some previous cut and we simply continue our algorithm. Otherwise, we add $b_n$ to the stack as a cut must be performed. This part works in $O(n + m)$ time. Total complexity is $O(n \\log n + m \\log m)$ because of sorting/mapping. Solve the task in $O(n+m)$ total complexity.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "dsu",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1779",
    "index": "E",
    "title": "Anya's Simultaneous Exhibition",
    "statement": "This is an interactive problem.\n\nAnya has gathered $n$ chess experts numbered from $1$ to $n$ for which the following properties hold:\n\n- For any pair of players one of the players wins every game against the other (and no draws ever occur);\n- Transitivity does not necessarily hold — it might happen that $A$ always beats $B$, $B$ always beats $C$ and $C$ always beats $A$.\n\nAnya \\textbf{does not} know, for each pair, who is the player who beats the other.To organize a tournament, Anya hosts $n-1$ games. In each game, she chooses two players. One of them wins and stays, while the other one is disqualified. After all the games are hosted only one player will remain. A player is said to be a candidate master if they can win a tournament (notice that the winner of a tournament may depend on the players selected by Anya in the $n-1$ games).\n\nSince Anya is a curious girl, she is interested in finding the candidate masters. Unfortunately, she does not have much time. To speed up the process, she will organize up to $2n$ simuls (short for \"simultaneous exhibition\", in which one player plays against many).\n\nIn one simul, Anya chooses \\textbf{exactly one} player who will play against some (at least one) of the other players. The chosen player wins all games they would win in a regular game, and the same holds for losses. After the simul finishes, Anya is only told the total number of games won by the chosen player (but not which ones). Nobody is disqualified during a simul.\n\nCan you help Anya host simuls and determine the candidate masters?\n\nThe winning players in each pair \\textbf{could be} changed between the simuls, but only in a way that preserves the results of all previous simuls. These changes may depend on your queries.",
    "tutorial": "A tournament graph is given. Player $i$ is a candidate master if for every other player there exists a path from $i$ to them. Can you find one candidate master? (which helps in finding all of them) Statement: If player $i$ has the highest out-degree, then they are a candidate master. Proof: Let's prove a stronger claim, if player $i$ has the highest out degree, then they reach every other player in $1$ or $2$ edges. Let $S_1$ be the set of players which are immediately reachable and let $S_2$ be the set of other players (not including $i$). Choose some $x \\in S_2$. If $x$ is not reachable from $i$, then it has an edge to it as well as to every player in $S_1$, meaning that the out-degree of $x$ is at least $|S_1|+1$. This is a contradiction, since $i$ has out-degree exactly equal to $|S_1|$ and the initial condition was for $i$ to have the highest out-degree. So, every $x \\in S_2$ is reachable by $i$, which proves the lemma. Statement: There exists an integer $w$ such that player $i$ is a candidate master if and only if its out-degree is greater than or equal to $w$. Proof: Let $S_1, S_2, \\ldots S_k$ represent the strongly connected components (SCC) of the tournament graph, in the topological order ($S_1$ is the \"highest\" component, while $S_k$ is the \"lowest\"). Since the graph is a tournament, it holds that there exists a directed edge from $x$ to $y$ for each $x \\in S_i$, $y \\in S_j$, $i<j$. We can also conclude that $x$ has a higher out-degree than $y$ for each $x \\in S_i$, $y \\in S_j$, $i<j$. The same holds for $i=1$, which proves the lemma since $S_1$ is the set of candidate masters, and also each player in it has strictly higher out-degree than every other player not in it. For each player, we host a simul which includes every other player (but themselves). This tells us the necessary out-degrees and we can easily find one candidate master (the one with highest out-degree). The second step is to sort all players by out-degree in non-increasing order and maintain the current $w$ described in \"Lemma 2\". Its initial value is the out-degree of player $1$. As we iterate over players, we host additional simuls: if player $i$ wins a match against at least one player among $1,2, \\ldots j$ (the set of current candidate masters), then $i$ is also a candidate master, as well as $j+1, j+2, \\ldots i-1$, we update the set accordingly and eventually decrease $w$. The first step requires $n$ simuls to be hosted, and the same hold for step $2$. In total, that is $2n$ simuls (or slightly less, depending on implementation). Solve the task if $n-1$ simuls are allowed to be hosted.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "interactive",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1779",
    "index": "F",
    "title": "Xorcerer's Stones",
    "statement": "Misha had been banned from playing chess for good since he was accused of cheating with an engine. Therefore, he retired and decided to become a xorcerer.\n\nOne day, while taking a walk in a park, Misha came across a rooted tree with nodes numbered from $1$ to $n$. The root of the tree is node $1$.\n\nFor each $1\\le i\\le n$, node $i$ contains $a_i$ stones in it. Misha has recently learned a new spell in his xorcery class and wants to test it out. A spell consists of:\n\n- Choose some node $i$ ($1 \\leq i \\leq n$).\n- Calculate the bitwise XOR $x$ of all $a_j$ such that node $j$ is in the subtree of $i$ ($i$ belongs to its own subtree).\n- Set $a_j$ equal to $x$ for all nodes $j$ in the subtree of $i$.\n\nMisha can perform at most $2n$ spells and he wants to remove all stones from the tree. More formally, he wants $a_i=0$ to hold for each $1\\leq i \\leq n$. Can you help him perform the spells?\n\nA tree with $n$ nodes is a connected acyclic graph which contains $n-1$ edges. The subtree of node $i$ is the set of all nodes $j$ such that $i$ lies on the simple path from $1$ (the root) to $j$. We consider $i$ to be contained in its own subtree.",
    "tutorial": "If XOR of all stones equals $0$, then by performing one spell to the root we obtain an answer. Solve the task for even $n$. If $n$ is even, performing a spell to the root guarantees that all nodes will have the same number of stones, meaning that the total XOR of the tree is $0$, thus performing the same spell again makes all nodes have $0$ stones. Consider even and odd subtrees. What does a spell do to them? A spell performed to the odd subtree does nothing. It does not change the total XOR, and it also makes performing a spell to some node in its subtree useless as their XORs would be $0$ anyway. Thus, we are only interested in even subtrees. Please refer to the hints as steps. Let's finish the casework: Let nodes $u$ and $v$ have even subtrees. And let the spell be performed on $u$, and then on $v$ slightly later. Consider the following $3$ cases: $u$ is an ancestor of $v$; performing a spell on $v$ does not make sense as its subtree's XOR is already $0$. $v$ is an ancestor of $u$; performing a spell on $u$ does not make sense either as it will be \"eaten\" by $v$ later. More formally, let $s_u$ be the current XOR of $u$'s subtree. We define $s_v$ and $s_1$ analogously. A spell performed on $u$ sets $s_v := s_v \\oplus s_u$ and $s_1 := s_1 \\oplus s_u$. Later, the spell performed on $v$ sets $s_1 := s_1 \\oplus s_v$. Notice that the final state of $s_1$ is the same as if only the spell on $v$ was performed (since $s_u \\oplus s_u = 0$). This means that the total XOR stays the same independent of whether we perform a spell on $u$ or not. Neither $u$ or $v$ is a parent of the other; this is the only case we are interested in and we will use this as a fact. We only need to choose some subtrees such that their total XOR is equal to the XOR of the root. Why? Because after applying the spells to them the total XOR becomes $0$, and that problem has been solved in \"Hint 1.1\". Of course, each pair of subtrees must satisfy the condition in case $3$, thus finding the subtrees is possible with dynamic programming and reconstruction. In each node we keep an array of size $32$ which tells us the possible XOR values obtained by performing spells on nodes in its subtree. Transitions are done for each edge, from child to parent, in similar fashion to the knapsack problem, but with XOR instead of sums. Time complexity is $O(n A^2)$ and memory complexity is $O(nA)$. It is possible to optimize this, but not necessary. Can you minimize the number of operations? The number of them is $\\leq 6$ (in an optimal case).",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1779",
    "index": "G",
    "title": "The Game of the Century",
    "statement": "The time has finally come, MKnez and Baltic are to host The Game of the Century. For that purpose, they built a village to lodge its participants.\n\nThe village has the shape of an equilateral triangle delimited by three roads of length $n$. It is cut into $n^2$ smaller equilateral triangles, of side length $1$, by $3n-3$ additional roads which run parallel to the sides. See the figure for $n=3$. Each of the $3n$ roads is made of multiple (possibly $1$) road segments of length $1$ which connect adjacent intersections.\n\nThe direction has already been chosen for each of the $3n$ roads (so, for each road, the same direction is assigned to all its road segments). Traffic can only go in the specified directions (i. e. the roads are monodirectional).\n\nYou are tasked with making adjustments to the traffic plan so that from each intersection it is possible to reach every other intersection. Specifically, you can invert the traffic direction of any number of road segments of length $1$. What is the minimal number of road segments for which you need to invert the traffic direction?",
    "tutorial": "Consider the sides of the big triangle. If they have the same orientation (clockwise or counter-clockwise), $0$ segments have to be inverted since the village is already biconnected. If the three sides do not all have the same orientation, inverting some segments is necessary. The following picture represents them (or rather, one case, but every other is analogous). There are two \"major\" paths: $A \\rightarrow C$ $A \\rightarrow B \\rightarrow C$ Each road has a \"beginning\" in one of the paths, hence it is possible to reach every intersection from $A$. Similarly, $C$ can be reached from every other intersection. The problem is that $C$ acts as a tap as it cannot reach anything. To make the village biconnected, we will make it possible for $C$ to reach $A$ by inverting the smallest number of road segments. Intuitively, that will work since for every intersection $x$ there exists a cycle $A \\rightarrow x \\rightarrow C \\rightarrow A$. A formal proof is given at the end of this section. The task is to find a shortest path from $C$ to $A$, with edges having weights of $0$ (its direction is already as desired) and $1$ (that edge has to be inverted). To implement this in $O(n)$, one has to notice that we are only interested in the closest road of each direction to the big triangle's side. One can prove that by geometrically looking at the strongly connected components, and maybe some casework is required. But, the implementation is free of boring casework. Now, it is possible to build a graph with vertices which belong to at least one of the $6$ roads we take into consideration (there are $3$ pairs of opposite directions). One can run a $0$-$1$ BFS and obtain the shortest path. This will indeed make the village biconnected as a shortest path does not actually pass through sides $A \\rightarrow B$ and $B \\rightarrow C$ (why would it? it is not optimal making effort to reach it just to invert some unnecessary additional road segments) The shortest path from $C$ to $A$ intersects the side $A \\rightarrow C$ though (possibly multiple times), but it can be proved that every intersection on it is reachable from $C$. Also, sides $A \\rightarrow B$ and $B \\rightarrow C$ are reachable from $C$ since $A$ is reachable from $C$. This means that all sides are reachable by both $A$ and $C$, and so is every other intersection. Solve the problem if it is required to process $q \\leq 10^5$ queries: invert a given road (and every segment in it), then print the minimum number of road segments you need to additionally invert to make the village biconnected (and not perform them, they are independent from the queries).",
    "tags": [
      "constructive algorithms",
      "graphs",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1779",
    "index": "H",
    "title": "Olympic Team Building",
    "statement": "Iron and Werewolf are participating in a chess Olympiad, so they want to practice team building. They gathered $n$ players, where $n$ is a power of $2$, and they will play sports. Iron and Werewolf are among those $n$ people.\n\nOne of the sports is tug of war. For each $1\\leq i \\leq n$, the $i$-th player has strength $s_i$. Elimination rounds will be held until only one player remains — we call that player the absolute winner.\n\nIn each round:\n\n- Assume that $m>1$ players are still in the game, where $m$ is a power of $2$.\n- The $m$ players are split into two teams of equal sizes (i. e., with $m/2$ players in each team). The strength of a team is the sum of the strengths of its players.\n- If the teams have equal strengths, Iron chooses who wins; otherwise, the stronger team wins.\n- Every player in the losing team is eliminated, so $m/2$ players remain.\n\nIron already knows each player's strength and is wondering who can become the absolute winner and who can't if he may choose how the teams will be formed in each round, as well as the winning team in case of equal strengths.",
    "tutorial": "Huge thanks to dario2994 for helping me solve and prepare this problem. Try reversing the process. Start with some multiset ${ x }$ containing only $1$ element. We will try to make $x$ an absolute winner. Extend it by repeatedly adding subsets of equal sizes to it (which have sum less than or equal to the current one). A simple greedy solution is to always extend the current subset with the one which has the maximum sum. This, however, gives WA as 100 100 101 98 89 103 103 104 111 680 1 1 1 1 1 2 is a counter-example. (see it for yourself!) Statement: If it is possible to extend some multiset $A$ to the whole array $s$, we consider it winning. If $A \\leq B$ holds for some subset $B$, then $B$ is also winning. Here, $A \\leq B$ means that there exists a bijection $f\\colon A\\to B$ such that $x \\leq f(x)$ for each $x \\in A$. Proof: Let $A, A_1, A_2, \\ldots A_k$ be a winning sequence of extensions. By definition of $A \\leq B$, we can swap each element of $A$ with some other element. There are three cases: If we swap some $x \\in A$ with an element which is already in $A$, nothing happens. If we swap some $x \\in A$ with an element which is not in any $A_i$, the sum of $A$ increases hence it is also winning. If we swap some $x \\in A$ with an element which is contained in some $A_i$, the sum of $A$ increases, the sum of $A_i$ decreases and the sum of sums of $A,A_1, \\ldots, A_i$ stays the same. The sequence remains winning. Special cases of the lemma are subsets of size $1$. We can conclude that if $x$ is winning and $x \\leq y$, then so is $y$. The answer is binary-searchable. Let's work with some fixed $s_i = x$ from now on. The idea is to maintain a list of current possible winning subsets. The motivation of lemma is to exclude subsets which cannot produce the answer. we can see that ${ s_j, s_i } \\leq { s_{i-1},s_i }$ for each $j < i-1$, hence the only interesting subset is ${ s_{i-1}, s_i }$ (we excluded others because if one of them is an answer, then so is ${ s_{i-1}, s_i }$. We will use this without explanation later on). we can see that ${ s_j, s_i } \\leq { s_{i-1},s_i }$ for each $j < i-1$, hence the only interesting subset is ${ s_{i-1}, s_i }$ (we excluded others because if one of them is an answer, then so is ${ s_{i-1}, s_i }$. We will use this without explanation later on). we extend ${ s_{i-1}, s_{i} }$ further to a subset of size $4$. There will be at most $15$ new subsets and it can be proved by using the lemma and two pointers. we extend ${ s_{i-1}, s_{i} }$ further to a subset of size $4$. There will be at most $15$ new subsets and it can be proved by using the lemma and two pointers. extend the current subsets to have size $8$. And, of course, use the lemma again and exclude unnecessary subsets. Implementing it properly should be fast enough. A fact is that there will be at most $8000$ subsets we have to consider. Although, proving it is not trivial. Consider all subsets of size $4$ and a partial ordering of them. In our algorithm we have excluded all subsets with large sum and then we excluded all subsets which are less than some other included set. So, the max collection of such subsets is less in size than the max antichain of $4$-subsets with respect to $\\leq$. Following the theory, a max anti-chain can have size at most $\\max\\limits_{k} f(k)$, where $f(k)$ is the number of $4$-subsets with indices having sum exactly $k$. Hard-coding this gives us an approximation of $519$. This value should be multiplied by $15$, since we had that many $4$-subsets to begin with. This is less than $8000$, which is relatively small. extend the current subsets to have size $8$. And, of course, use the lemma again and exclude unnecessary subsets. Implementing it properly should be fast enough. A fact is that there will be at most $8000$ subsets we have to consider. Although, proving it is not trivial. Consider all subsets of size $4$ and a partial ordering of them. In our algorithm we have excluded all subsets with large sum and then we excluded all subsets which are less than some other included set. So, the max collection of such subsets is less in size than the max antichain of $4$-subsets with respect to $\\leq$. Following the theory, a max anti-chain can have size at most $\\max\\limits_{k} f(k)$, where $f(k)$ is the number of $4$-subsets with indices having sum exactly $k$. Hard-coding this gives us an approximation of $519$. This value should be multiplied by $15$, since we had that many $4$-subsets to begin with. This is less than $8000$, which is relatively small. Extending the $8$-subsets further sounds like an impossible task. But, greedy finally comes in handy. Every $8$-subset should be extended with another $8$-subset which maximizes the sum. It is not hard to see that if an answer exists, then this produces a correct answer too. We are left with solving $8$-sum in an array of size $24$. As we need to do this around $8000$ times, we use the meet in the middle approach. It can be done in around $2^{12}$ operations if merge sort is used (it spares us the \"$12$\" factor in $12 \\cdot 2^{12}$). Extending the $8$-subsets further sounds like an impossible task. But, greedy finally comes in handy. Every $8$-subset should be extended with another $8$-subset which maximizes the sum. It is not hard to see that if an answer exists, then this produces a correct answer too. We are left with solving $8$-sum in an array of size $24$. As we need to do this around $8000$ times, we use the meet in the middle approach. It can be done in around $2^{12}$ operations if merge sort is used (it spares us the \"$12$\" factor in $12 \\cdot 2^{12}$). Summary: Solving the task for $n\\leq 16$ is trivial. Let's fix $n=32$. Calculating the exact complexity does not make much sense as $n$ is fixed, but we will calculate the rough number of basic arithmetic operations used. Firstly, a binary search is used, which is $\\log 32 = 5$ operations. Then, we generate $8$-subsets which can be implemented quickly (but is not trivial). The meet in the middle part consumes $8000 \\cdot 2^{12}$ operations. The total number of operations is roughly $5 \\cdot 8000 \\cdot 4096 = 163\\,840\\,000$, which gives us a decent upper bound. Try to construct a strong test against fake greedy solutions :)",
    "tags": [
      "brute force",
      "meet-in-the-middle"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1780",
    "index": "A",
    "title": "Hayato and School",
    "statement": "Today Hayato came home from school with homework.\n\nIn the assignment, Hayato was given an array $a$ of length $n$. The task was to find $3$ numbers in this array whose sum is \\textbf{odd}. At school, he claimed that there are such $3$ numbers, but Hayato was not sure, so he asked you for help.\n\nAnswer if there are such three numbers, and if so, output indices $i$, $j$, and $k$ such that $a_i + a_j + a_k$ is odd.\n\nThe odd numbers are integers that are not divisible by $2$: $1$, $3$, $5$, and so on.",
    "tutorial": "Note that there are two variants of which numbers to take to make their amount odd: $3$ odd number; $2$ even and $1$ odd. Let's save all indices of even and odd numbers into two arrays, and check both cases.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int T;\n    cin >> T;\n    while (T--) {\n        int n;\n        cin >> n;\n        vector<int> odd, even;\n        for (int i = 1; i <= n; i++) {\n            int x;\n            cin >> x;\n            if (x % 2 == 0) {\n                even.push_back(i);\n            } else {\n                odd.push_back(i);\n            }\n        }\n        if (odd.size() >= 3) {\n            cout << \"YES\\n\";\n            cout << odd[0] << \" \" << odd[1] << \" \" << odd[2] << '\\n';\n        } else if (odd.size() >= 1 && even.size() >= 2) {\n            cout << \"YES\\n\";\n            cout << odd[0] << \" \" << even[0] << \" \" << even[1] << '\\n';\n        } else {\n            cout << \"NO\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1780",
    "index": "B",
    "title": "GCD Partition",
    "statement": "While at Kira's house, Josuke saw a piece of paper on the table with a task written on it.\n\nThe task sounded as follows. There is an array $a$ of length $n$. On this array, do the following:\n\n- select an integer $k > 1$;\n- split the array into $k$ subsegments $^\\dagger$;\n- calculate the sum in each of $k$ subsegments and write these sums to another array $b$ (where the sum of the subsegment $(l, r)$ is ${\\sum_{j = l}^{r}a_j}$);\n- the final score of such a split will be $\\gcd(b_1, b_2, \\ldots, b_k)^\\ddagger$.\n\nThe task is to find such a partition that the score is \\textbf{maximum possible}. Josuke is interested in this task but is not strong in computer science. Help him to find the maximum possible score.\n\n$^\\dagger$ A division of an array into $k$ subsegments is $k$ pairs of numbers $(l_1, r_1), (l_2, r_2), \\ldots, (l_k, r_k)$ such that $l_i \\le r_i$ and for every $1 \\le j \\le k - 1$ $l_{j + 1} = r_j + 1$, also $l_1 = 1$ and $r_k = n$. These pairs represent the subsegments.\n\n$^\\ddagger$ $\\gcd(b_1, b_2, \\ldots, b_k)$ stands for the greatest common divisor (GCD) of the array $b$.",
    "tutorial": "Let's note that it doesn't make sense for us to divide into more than $k = 2$ subsegments. Let's prove it. Let us somehow split the array $a$ into $m > 2$ subsegments : $b_1, b_2, \\ldots, b_m$. Note that $\\gcd(b_1, b_2, \\ldots, b_m) \\le \\gcd(b_1 + b_2, b_3, \\ldots, b_m)$, since if $b_1$ and $b_2$ were multiples of $\\gcd(b_1, b_2 , \\ldots, b_m)$, so $b_1 + b_2$ is also a multiple of $\\gcd(b_1, b_2, \\ldots, b_m)$. This means that we can use $b_1 + b_2$ instead of $b_1$ and $b_2$, and the answer will not worsen, thus it is always beneficial to use no more than $k = 2$ subsegments. How to find the answer? Let $s$ be the sum of the array $a$. Let's say $pref_i = {\\sum_{j = 1}^{i} a_j}$, then the answer is $\\max\\limits_{1 \\le i < n}(\\gcd(pref_i, s - pref_i)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    int T = 1;\n    cin >> T;\n    while (T--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) cin >> a[i];\n        long long s = accumulate(a.begin(), a.end(), 0ll), cur = 0;\n        long long ans = 1;\n        for (int i = 0; i < n - 1; i++) {\n            cur += a[i], s -= a[i];\n            ans = max(ans, __gcd(s, cur));\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1780",
    "index": "D",
    "title": "Bit Guessing Game",
    "statement": "This is an interactive problem.\n\nKira has a hidden positive integer $n$, and Hayato needs to guess it.\n\nInitially, Kira gives Hayato the value $\\mathrm{cnt}$ — the number of unit bits in the binary notation of $n$. To guess $n$, Hayato can only do operations of one kind: choose an integer $x$ and subtract it from $n$. Note that after each operation, the number $n$ \\textbf{changes}. Kira doesn't like bad requests, so if Hayato tries to subtract a number $x$ greater than $n$, he will lose to Kira. After each operation, Kira gives Hayato the updated value $\\mathrm{cnt}$ — the number of unit bits in the binary notation of the updated value of $n$.\n\nKira doesn't have much patience, so Hayato must guess the \\textbf{original} value of $n$ after no more than $30$ operations.\n\nSince Hayato is in elementary school, he asks for your help. Write a program that guesses the number $n$. Kira is an honest person, so he chooses the initial number $n$ before all operations and \\textbf{does not} change it afterward.",
    "tutorial": "There are two similar solutions to this problem, we will tell you both. Subtract $1$. What can we say now about the number of units at the beginning of the binary notation of a number? There are exactly $cnt - cnt_w + 1$, where $cnt$ is the number of unit bits after subtracting the unit, and $cnt_w$ is - before subtracting. Now we subtract them, for this we need to subtract the number $2^{cnt - cnt_w + 1} - 1$ and continue the algorithm. But such an algorithm makes at worst $60$ requests. To save queries, note that we know the number of units after we remove the units from the beginning, therefore it is useless to make another request for this. Then at the same time, as we remove the units from the beginning, we will immediately subtract the unit. As a result, there will be absolutely no more than $cnt$ operations, where $cnt$ is the initial number of single bits in the record of the number $n$. This number does not exceed $O(log_2(n))$, in turn, $log_2(n)$ does not exceed 30, which fits into the restrictions. Let $ans$ be the desired number $n$, and $was$ be the initial number of bits in the number $n$. Let's subtract the powers of two : $2^0, 2^1, 2^2, ... 2^ k$, while $was$ it will not become 0. We will support the $Shift$ flag - whether there was a bit transfer to $n$ when subtracting any power of two. Suppose we subtracted $2^k$ at the $k$th step and the number of bits became equal to $cnt_{new}$, and before the subtraction was $cnt$, then consider two cases. 1) $cnt - cnt_{new} = 1$, then bit $k$ was included in $n$ at the $k$th step, and if $Shift = false$, then we add to $ans$ - $2^k$, since there was no bit transfer, which means bit k is also in the original number, and subtract from $was$ - $1$. If $Shift = true$, then we added this bit during previous operations, and it does not need to be taken into account. 2) $cnt - cnt_{new} \\neq 1$, then we know that the number of bits has not decreased, also that in the number $n$ there was such a bit $m$ that $2^m > 2^k$, and at the same time the bit $m$ is in $n$. Moreover, $m - k - 1 = cnt_{new} - cnt$. So $m = k + 1 + cnt_{new} - cnt$. Let's add $2^m$ to the answer, subtract from $was$ - $1$ and assign the $Shift$ flag the value $true$, since there was a bit transfer. Thus, we found the initial number $n$, which is equal to $ans$, and also made no more than $O(log_2(n))$ queries, since $k\\le log_2(n)$. Thus, the solution spends no more than 30 requests, which fits into the limitations of the task.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint ask (int x) {\n    cout << \"- \" << x << endl;\n    if (x == -1)\n        exit(0);\n    cin >> x;\n    return x;\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int cnt;\n        cin >> cnt;\n        int n = 0;\n        int was = 0;\n        while (cnt > 0) {\n            n += 1;\n            int nw = ask(1 + was);\n            int back = nw - cnt + 1;\n            n += (1 << back) - 1;\n            was = (1 << back) - 1;\n            cnt = nw - back;\n        }\n        cout << \"! \" << n << endl;\n    }\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1780",
    "index": "E",
    "title": "Josuke and Complete Graph",
    "statement": "Josuke received a huge undirected weighted complete$^\\dagger$ graph $G$ as a gift from his grandfather. The graph contains $10^{18}$ vertices. The peculiarity of the gift is that the weight of the edge between the different vertices $u$ and $v$ is equal to $\\gcd(u, v)^\\ddagger$. Josuke decided to experiment and make a new graph $G'$. To do this, he chooses two integers $l \\le r$ and deletes all vertices except such vertices $v$ that $l \\le v \\le r$, and also deletes all the edges except between the remaining vertices.\n\nNow Josuke is wondering how many different weights are there in $G'$. Since their count turned out to be huge, he asks for your help.\n\n$^\\dagger$ A complete graph is a simple undirected graph in which every pair of distinct vertices is adjacent.\n\n$^\\ddagger$ $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of the numbers $x$ and $y$.",
    "tutorial": "Let's fix $g$ and check that the $g$ weight edge exists in $G'$. The first number, which is divided into $g$, starting with $L$ - $\\lceil \\frac{L}{g} \\rceil \\cdot g$, and the second - $(\\lceil \\frac{L}{g} \\rceil + 1) \\cdot g$, note that their $\\gcd$ is $g$, so the edge between these vertices weighs $g$. If the second number is greater $R$, the edge with weight $g$ in the $G'$ doesn't exist, because on the segment from $L$ to $R$ at most one vertex, which is divided by $g$. That is, we should calculate the number of such $g$, which is $(\\lceil \\frac{L}{g} \\rceil + 1) \\cdot g \\leq R$. For $g \\geq L$: $(\\lceil \\frac{L}{g} \\rceil + 1) \\cdot g = 2 \\cdot g$. Get the upper limit on the $g \\leq \\lfloor \\frac{R}{2} \\rfloor$. That is, all $g$ on segment from $L$ to $\\lfloor \\frac{R}{2} \\rfloor$ occur in the $G'$ as weight some edge. Add them to the answer. Look at $g < L$. Note that $\\lceil \\frac{L}{g} \\rceil$ takes a $O(\\sqrt{L})$ of different values. Let's fix some $f = \\lceil \\frac{L}{g} \\rceil$. Note that $f$ corresponds to a consecutive segment $l \\leq g \\leq r$. Let's brute this segments in ascending order $f$. Then, if there is a left border $l$ of the segment, you can find $r$ either by binary search or by writing the formula. The next left border is $r + 1$. Then note, if $f$ is fixed, then $(f + 1) \\cdot g \\leq R$ is equivalent to $g \\leq \\lfloor \\frac{R}{f + 1} \\rfloor$. That is, with a fixed segment from $l$ to $r$, $g$ occurs in the $G'$ as weight some edge if $l \\leq g \\leq min(r, \\lfloor \\frac{R}{f + 1} \\rfloor)$. Then brute all these segments and sum up of all good $g$. Overall time complexity is $O(\\sqrt{L})$ or $O(\\sqrt{L} \\cdot log(L))$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    int t;\n    cin >> t;\n    for (int test_case = 0; test_case < t; test_case++){\n        ll L, R;\n        cin >> L >> R;\n        ll ans = max(0ll, R / 2 - L + 1);\n        for (ll left = 1, right; left < L; left = right + 1){\n            ll C = (L + left - 1) / left;\n            right = (L + C - 2) / (C - 1) - 1;\n            ans += max(0ll, min(right, R / (C + 1)) - left + 1);\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1780",
    "index": "F",
    "title": "Three Chairs",
    "statement": "One day Kira found $n$ friends from Morioh and decided to gather them around a table to have a peaceful conversation. The height of friend $i$ is equal to $a_i$. It so happened that the height of each of the friends \\textbf{is unique}.\n\nUnfortunately, there were only $3$ chairs in Kira's house, and obviously, it will not be possible to seat all friends! So, Kira has to invite only $3$ of his friends.\n\nBut everything is not so simple! If the heights of the lowest and the tallest of the invited friends are not coprime, then the friends will play tricks on each other, which will greatly anger Kira.\n\nKira became interested, how many ways are there to choose $3$ of his friends so that they don't play tricks? Two ways are considered different if there is a friend invited in one way, but not in the other.\n\nFormally, if Kira invites friends $i$, $j$, and $k$, then the following should be true: $\\gcd(\\min(a_i, a_j, a_k), \\max(a_i, a_j, a_k)) = 1$, where $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of the numbers $x$ and $y$.\n\nKira is not very strong in computer science, so he asks you to count the number of ways to invide friends.",
    "tutorial": "Let's sort the array and process the triples $i, j, k$, assuming that $i < j < k$ and $a_i < a_j < a_k$. Now if $\\gcd(a_i, a_k) = 1$, then the number of ways to take the index $j$ is $k - i - 1$. We will consider the answer to the problem for each $k$ from $1$ to $n$, assuming that $a_k$ is the maximum number in the triple. Now let $c$ be the number of numbers that are mutually prime with $a_k$ on the prefix from $1$ to $k - 1$, and $sum$ is the sum of their indices. Then you need to add $c\\cdot i - sum - c$ to the answer. It remains to find out the number of numbers that are mutually prime with $a_k$ and the sum of their indices. This can be done using the inclusion and exclusion method. Let $cnt_i$ be the number of numbers $a_j$ that are divisible by $i$, $s_i$ be the sum of the indices $j$ of numbers $a_j$ that are divisible by $i$. Let's look at the prime numbers $p_1, p_2, ..., p_m$ included in the factorization of the number $a_k$. Then let $c$ initially be equal to the number of numbers on the prefix, and $sum$ to the sum of the indices on the prefix. Note that then we took into account the extra elements - numbers that are divisible by $p_1, p_2, ..., p_m$, since they will not be mutually simple with $a_k$, we subtract them from $c$ and $sum$. But having done this, we again took into account the extra elements that are multiples of the numbers of the form $p_i * p_j$, where $i \\neq j$, add them back, etc. So we can iterate over the mask $mask$ of the primes $p_1, p_2, ..., p_m$. And depending on the parity of the bits in the mask, we will subtract or add elements that are multiples of $d$, where $d$ is the product of the primes included in $mask$. Having received $c$ and $sum$, we can recalculate the answer for the position $i$. To move from position $i$ to position $i+1$, update the values of $cnt$ and $s$ by adding the element $a_{i-1}$ by iterating over the mask of the simple element $a_{i-1}$.",
    "code": "#include \"bits/stdc++.h\"\n \nusing namespace std;\n \n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;\n \n#define sz(v) ((int)(v).size())\n#define all(a) (a).begin(),  (a).end()\n#define rall(a) a.rbegin(), a.rend()\n#define F first\n#define S second\n#define pb push_back\n#define ppb pop_back\n#define eb emplace_back\n#define time ((double)clock() / (double)CLOCKS_PER_SEC)\n \nusing pii = pair<int, int>;\nusing ll = long long;\nusing int64 = long long;\nusing ld = double;\n \nconst ll infll = (ll) 1e18 + 27;\nconst ll inf = (ll) 1e9;\n \n#define dbg(x) cout << #x << \" = \" << (x) << endl\n \ntemplate<class T>\nusing pq = priority_queue<T, vector<T>, less<T>>;\ntemplate<class T>\nusing pqr = priority_queue<T, vector<T>, greater<T>>;\n \ntemplate<typename T, typename T2>\nistream &operator>>(istream &in, pair<T, T2> &b) {\n    in >> b.first >> b.second;\n    return in;\n}\n \ntemplate<typename T, typename T2>\nostream &operator<<(ostream &out, const pair<T, T2> &b) {\n    out << \"{\" << b.first << \", \" << b.second << \"}\";\n    return out;\n}\n \ntemplate<typename T>\nistream &operator>>(istream &in, vector<T> &b) {\n    for (auto &v : b) {\n        in >> v;\n    }\n    return in;\n}\n \ntemplate<typename T>\nostream &operator<<(ostream &out, vector<T> &b) {\n    for (auto &v : b) {\n        out << v << ' ';\n    }\n    return out;\n}\n \ntemplate<typename T>\nostream &operator<<(ostream &out, deque<T> &b) {\n    for (auto &v : b) {\n        out << v << ' ';\n    }\n    return out;\n}\n \ntemplate<typename T>\nvoid print(T x, string end = \"\\n\") {\n    cout << x << end;\n}\n \n \ntemplate<typename T1, typename T2>\nbool chkmin(T1 &x, const T2 &y) { return x > y && (x = y, true); }\n \ntemplate<typename T1, typename T2>\nbool chkmax(T1 &x, const T2 &y) { return x < y && (x = y, true); }\n \nmt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());\n \nconst int N = 3e5 + 10;\n \nll s[N];\nll cnt[N];\n \nll d[N][20];\nint ptr[N];\nbool u[N];\n \nll Cnt = 0;\nll Sum = 0;\n \nll Ans = 0;\n \nvoid Answer (int x, int pos) {\n\tll C = Cnt;\n\tll X = Sum;\n\tint K = (1ll << ptr[x]);\n\tfor (int mask = 1; mask < K; mask++) {\n\t\tll k = 1;\n\t\tfor (int j = 0; j < ptr[x]; j++) {\n\t\t\tif ((mask >> j) & 1) {\n\t\t\t\tk *= d[x][j];\n\t\t\t}\n\t\t}\n\t\tint bits = __builtin_popcount(mask);\n\t\tint D = k;\n\t\tif (bits % 2 == 1) {\n\t\t\tC -= cnt[D];\n\t\t\tX -= s[D];\n\t\t} else {\n\t\t\tC += cnt[D];\n\t\t\tX += s[D];\n\t\t}\n\t}\n\tAns += C * pos - X;\n}\n \nvoid add (int x, int pos) {\n\tCnt += 1;\n\tSum += pos + 1;\n\tauto v = d[x];\n\tint K = (1ll << ptr[x]);\n\tfor (int mask = 1; mask < K; mask++) {\n\t\tll k = 1;\n\t\tfor (int j = 0; j < ptr[x]; j++) {\n\t\t\tif ((mask >> j) & 1) {\n\t\t\t\tk *= d[x][j];\n\t\t\t}\n\t\t}\n\t\tint D = k;\n\t\ts[D] += pos + 1;\n\t\tcnt[D] += 1;\n\t}\n}\n \nvoid solve() {\n\tfor (int i = 2; i < N; i++) {\n\t\tif (!u[i]) {\n\t\t\tfor (int j = i; j < N; j += i) {\n\t\t\t\tu[j] = true;\n\t\t\t\td[j][ptr[j]] = i;\n\t\t\t\tptr[j]++;\n\t\t\t}\n\t\t}\n\t}\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tcin >> a;\n\tsort(all(a));\n\tfor (int i = 0; i < n; i++) {\n\t\tAnswer(a[i], i);\n\t\tif (i > 0) {\n\t\t\tadd(a[i - 1], i - 1);\n\t\t}\n\t}\n\tcout << Ans << \"\\n\";\n}\n \nint32_t main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    solve();\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "data structures",
      "dp",
      "number theory",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1780",
    "index": "G",
    "title": "Delicious Dessert",
    "statement": "Today is an important day for chef Tonio — an auditor has arrived in his hometown of Morioh. He has also arrived at Tonio's restaurant and ordered dessert. Tonio has not been prepared for this turn of events.\n\nAs you know, dessert is a string of lowercase English letters. Tonio remembered the rule of desserts — a string $s$ of length $n$. Any dessert $t$ is delicious if the number of occurrences of $t$ in $s$ as a substring is \\textbf{divisible} by the length of $t$.\n\nNow Tonio wants to know the number of delicious substrings of $s$. If the substring occurs several times in the string $s$, then all occurrences must be taken into account.",
    "tutorial": "This problem has several solutions using different suffix structures. We will tell two of them - using suffix array, and using suffix automaton. Let's build suffix array $suf$ and array $lcp$ (largest common prefixes) on the string $s$. Fix some $k > 1$ and consider about all substring $s$ length $k$. Match $1$ to positions $i$ array $lcp$, such that $lcp_i \\geq k$, and match $0$ to other positions. One in position $i$ means that the substrings length $k$ starting at $suf_i$ and $suf_{i + 1}$ are equal. Consider any block of units length $len$, then for $len + 1$ substrings length $k$ number of occurrences in $s$ - $len + 1$, then in order for the substrings in this block to be delicious, it is necessary that $len + 1$ divided by $k$. Let's brute $k$ from $n$ to $2$ and sustain all sizes blocks. Then, when shift to a new $k$ should events - change $0$ to $1$, for all $i$, such that $lcp_i = k$. To do this you can sustain DSU (Disjoint set union). Then for each block size we know the number of blocks with this size. Then it is enough to consider all blocks of length $len$, such as $len + 1$ - divider $k$. It can be done explicitly, just brute $k$, $2 \\cdot k$, ..., as $len + 1$. And this works in sum of harmonic series: ${\\sum_{k = 2}^{n} \\lfloor \\frac{n}{k} \\rfloor}$ $= O(n \\cdot log(n))$. For $k = 1$, obviously, any substring length $1$ satisfies, so you can just add $n$ to the answer. Overall time complexity is $O(n \\cdot log(n))$. The solution with the suffix automaton is as follows: let's build the suffix automaton itself, now we calculate for each vertex of the suffix automaton the dynamics $dp_v$ - this is the number of paths from the vertex $v$ to the terminal vertices. This dynamics means the number of occurrences of the substring corresponding to this vertex in the entire string. Let's introduce the function $f(v)$ - the length of the longest substring leading to the vertex $v$. We know that all substrings of length from $l_v$ to $r_v$ lead to the vertex $v$ of the suffix automaton - each once. Where $r_v = f(v)$ and $l_v = f(suff_v) + 1$, where $suff_v$ is the suffix link of $v$. Why is it so? All substrings of the form $s[x:k], s[x+1:k], ..., s[y:k]$ lead to the vertex $v$ of the suffix automaton, and there is a suffix link $suff_v$ to which lead all substrings of the form $s[x + 1:k], s[y + 2:k], ..., s[t: k]$. In order to solve the problem, let's go through the $v$ vertex and look at the number of occurrences of any substring that leads to the $v$ - $dp_v$ vertex, then fix $c$ - the number of such $l_v \\le x \\le r_v$, that $dp_v$ is evenly divisible by $x$. Therefore, $dp_v \\cdot c$ must be added to the answer. All divisors can be stored in $O(n \\cdot log(n))$ and each time find the number of such $x$ by binsearch. Asymptotics $O(n \\cdot log(n))$",
    "code": "/* Includes */\n#include <bits/stdc++.h>\n#include <ext/pb_ds/tree_policy.hpp>\n\n/* Using libraries */\nusing namespace std;\n\n/* Defines */\n#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)\n#define ld long double\n#define pb push_back\n#define vc vector\n#define sz(a) (int)a.size()\n#define forn(i, n) for (int i = 0; i < n; ++i)\n#define pii pair <int, int>\n#define vec pt\n#define all(a) a.begin(), a.end()\n\nconst int K = 26;\nconst int N = 1e6 + 1;\n\nstruct node {\n    int next[K];\n    int suf = -1, pr = -1, dp = 0, len = 0, ch = -1;\n    node () {\n        forn (i, K) next[i] = -1;\n    }\n};\n\nint get (char c) {\n    if (c >= 'a')\n        return c - 'a';\n    return c - 'A';\n}\n\nint lst = 0, sz = 1;\nnode t[N * 2];\nint used[N * 2];\n\nint add (int a, int x) {\n    int b = sz++;\n    t[b].pr = a;\n    t[b].suf = 0;\n    t[b].ch = x;\n    for (; a != -1; a = t[a].suf) {\n        if (t[a].next[x] == -1) {\n            t[a].next[x] = b;\n            t[b].len = max(t[b].len, t[a].len + 1);\n            continue;\n        }\n        int c = t[a].next[x];\n        if (t[c].pr == a) {\n            t[b].suf = c;\n            break;\n        }\n        int d = sz++;\n        forn (i, K) t[d].next[i] = t[c].next[i];\n        t[d].suf = t[c].suf;\n        t[c].suf = t[b].suf = d;\n        t[d].pr = a;\n        t[d].ch = x;\n        for (; a != -1 && t[a].next[x] == c; a = t[a].suf) {\n            t[a].next[x] = d;\n            t[d].len = max(t[d].len, t[a].len + 1);\n        }\n        break;\n    }\n    return b;\n}\n\nvoid add (char c) {\n    lst = add(lst, get(c));\n}\n\nvoid dfs (int u) {\n    used[u] = 1;\n    for (int i = 0; i < K; ++i) {\n        if (t[u].next[i] == -1) continue;\n        int v = t[u].next[i];\n        if (!used[v])\n            dfs(v);\n        t[u].dp += t[v].dp;\n    }\n}\n\nvc <int> p[N], pr;\nint dr[N];\nvc <pii> d;\nint l, r, cur = 0;\n\nint cnt_log (int x, int y) {\n    int z = 1, res = 0;\n    while (y >= z) {\n        z *= x;\n        ++res;\n    }\n    return res - 1;\n}\n\nvoid rec (int i, int x) {\n    if (i == sz(d)) {\n        cur += l <= x;\n        return;\n    }\n    rec(i + 1, x);\n    for (int j = 1; j <= d[i].second; ++j) {\n        x *= d[i].first;\n        if (x > r)\n            break;\n        rec(i + 1, x);\n    }\n}\n\nvoid solve () {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    for (char c : s)\n        add(c);\n    for (int a = lst; a != -1; a = t[a].suf)\n        t[a].dp = 1;\n    dfs(0);\n    for (int i = 2; i <= n; ++i) {\n        if (dr[i] == 0) {\n            dr[i] = i;\n            pr.pb(i);\n        }\n        for (int j = 0; j < sz(pr) && pr[j] <= dr[i] && i * pr[j] <= n; ++j)\n            dr[i * pr[j]] = pr[j];\n    }\n    long long ans = 0;\n    forn (i, sz) {\n        if (t[i].len == 0) continue;\n        l = t[t[i].suf].len + 1;\n        r = t[i].len;\n        int x = t[i].dp;\n        d.clear();\n        while (x > 1) {\n            int y = dr[x];\n            if (d.empty() || d.back().first != y)\n                d.pb({y, 1});\n            else\n                d.back().second++;\n            x /= y;\n        }\n        rec(0, 1);\n        ans += t[i].dp * cur;\n        cur = 0;\n    }\n    cout << ans << '\\n';\n}\n\n/* Starting and precalcing */\nsigned main() {\n    /* freopen(\"input.txt\",\"r\",stdin);freopen(\"output.txt\",\"w\",stdout); */\n    fast;\n    int t = 1;\n    // cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "binary search",
      "dsu",
      "hashing",
      "math",
      "number theory",
      "string suffix structures"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1781",
    "index": "A",
    "title": "Parallel Projection",
    "statement": "Vika's house has a room in a shape of a rectangular parallelepiped (also known as a rectangular cuboid). Its floor is a rectangle of size $w \\times d$, and the ceiling is right above at the constant height of $h$. Let's introduce a coordinate system on the floor so that its corners are at points $(0, 0)$, $(w, 0)$, $(w, d)$, and $(0, d)$.\n\nA laptop is standing on the floor at point $(a, b)$. A projector is hanging on the ceiling right above point $(f, g)$. Vika wants to connect the laptop and the projector with a cable in such a way that the cable always goes along the walls, ceiling, or floor (i. e. does not go inside the cuboid). Additionally, the cable should always run \\textbf{parallel} to one of the cuboid's edges (i. e. it can not go diagonally).\n\nWhat is the minimum length of a cable that can connect the laptop to the projector?\n\n\\begin{center}\n{\\small Illustration for the first test case. One of the optimal ways to put the cable is shown in green.}\n\\end{center}",
    "tutorial": "Note that bending the cable on the wall is not necessary: we can always bend it on the floor and on the ceiling, while keeping the vertical part of the cable straight. Thus, we can just disregard the height of the room, view the problem as two-dimensional, and add $h$ to the answer at the end. In the two-dimensional formulation, we need to connect points $(a, b)$ and $(f, g)$ with a cable that goes parallel to the coordinate axes and touches at least one side of the $(0, 0)$ - $(w, d)$ rectangle. We can now casework on the side of the rectangle (the sides are referred to as in the picture from the problem statement): If the cable touches the front side, its length will be $b + |a - f| + g$. If the cable touches the left side, its length will be $a + |b - g| + f$. If the cable touches the back side, its length will be $(d - b) + |a - f| + (d - g)$. If the cable touches the right side, its length will be $(w - a) + |b - g| + (w - f)$. Out of these four values, the smallest one (plus $h$) is the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int w, d, h;\n    cin >> w >> d >> h;\n    int a, b;\n    cin >> a >> b;\n    int f, g;\n    cin >> f >> g;\n    int ans = b + abs(a - f) + g;\n    ans = min(ans, a + abs(b - g) + f);\n    ans = min(ans, (d - b) + abs(a - f) + (d - g));\n    ans = min(ans, (w - a) + abs(b - g) + (w - f));\n    cout << ans + h << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1781",
    "index": "B",
    "title": "Going to the Cinema",
    "statement": "A company of $n$ people is planning a visit to the cinema. Every person can either go to the cinema or not. That depends on how many other people will go. Specifically, every person $i$ said: \"I want to go to the cinema if and only if at least $a_i$ other people will go, \\textbf{not counting myself}\". That means that person $i$ will become sad if:\n\n- they go to the cinema, and strictly less than $a_i$ other people go; or\n- they don't go to the cinema, and at least $a_i$ other people go.\n\nIn how many ways can a set of people going to the cinema be chosen so that nobody becomes sad?",
    "tutorial": "Let's fix the number of people going to the cinema $k$ and try to choose a set of this exact size. What happens to people with different $a_i$? If $a_i < k$, person $i$ definitely wants to go. If $a_i > k$, person $i$ definitely does not want to go. If $a_i = k$, there is actually no good outcome for person $i$. If person $i$ goes to the cinema, there are only $k - 1$ other people going, so person $i$ will be sad (since $k - 1 < a_i$). If person $i$ does not go, there are $k$ other people going, so person $i$ will be sad too (since $k \\ge a_i$). Thus, for a set of size $k$ to exist, there must be no people with $a_i = k$, and the number of people with $a_i < k$ must be exactly $k$. We can easily check these conditions if we use an auxiliary array cnt such that cnt[x] is equal to the number of people with $a_i = x$. Alternative solution: Notice that if a set of $k$ people can go to the cinema, it must always be a set of people with the smallest $a_i$. Thus, we can start with sorting the array $a$ in non-decreasing order. Then, for each length $k$ of a prefix of this array, we can check whether the first $k$ elements are all smaller than $k$, and the remaining $n-k$ elements are all greater than $k$. However, since the array is sorted, it is enough to check that the $k$-th element is smaller than $k$, and the $k+1$-th element is greater than $k$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n      cin >> a[i];\n    }\n    sort(a.begin(), a.end());\n    int ans = 0;\n    for (int k = 0; k <= n; k++) {\n      if (k == 0 || a[k - 1] < k) {\n        if (k == n || a[k] > k) {\n          ans += 1;\n        }\n      }\n    }\n    cout << ans << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1781",
    "index": "C",
    "title": "Equal Frequencies",
    "statement": "Let's call a string balanced if all characters that are present in it appear the same number of times. For example, \"coder\", \"appall\", and \"ttttttt\" are balanced, while \"wowwow\" and \"codeforces\" are not.\n\nYou are given a string $s$ of length $n$ consisting of lowercase English letters. Find a balanced string $t$ of the same length $n$ consisting of lowercase English letters that is different from the string $s$ in as few positions as possible. In other words, the number of indices $i$ such that $s_i \\ne t_i$ should be as small as possible.",
    "tutorial": "Instead of \"finding $t$ that differs from $s$ in as few positions as possible\", let's formulate it as \"finding $t$ that matches $s$ in as many positions as possible\", which is obviously the same. First of all, let's fix $k$, the number of distinct characters string $t$ will have. Since the string must consist of lowercase English letters, we have $1 \\le k \\le 26$, and since the string must be balanced, we have $n \\bmod k = 0$. For each $k$ that satisfies these conditions, we will construct a balanced string that matches $s$ in as many positions as possible. In the end, out of all strings we will have constructed, we will print the one with the maximum number of matches. From now on, we are assuming $k$ is fixed. Suppose we choose some character $c$ to be present in string $t$. We need to choose exactly $\\frac{n}{k}$ positions in $t$ to put character $c$. Let $\\operatorname{freq}_{c}$ be the number of occurrences of $c$ in $s$. Then, in how many positions can we make $s$ and $t$ match using character $c$? The answer is: in $\\min(\\frac{n}{k}, \\operatorname{freq}_{c})$ positions. Now, since we want to maximize the total number of matches, we should choose $k$ characters with the largest values of $\\min(\\frac{n}{k}, \\operatorname{freq}_{c})$. This is also equivalent to choosing $k$ characters with the largest values of $\\operatorname{freq}_{c}$. How to construct the desired string? For each chosen character $c$, pick any $\\min(\\frac{n}{k}, \\operatorname{freq}_{c})$ of its occurrences in $s$ and put $c$ in the corresponding positions in $t$. Then, if $\\operatorname{freq}_{c} < \\frac{n}{k}$, save the information about $\\frac{n}{k} - \\operatorname{freq}_{c}$ unused characters $c$; otherwise, if $\\operatorname{freq}_{c} > \\frac{n}{k}$, save the information about $\\operatorname{freq}_{c} - \\frac{n}{k}$ empty positions in $t$. In the end, match the unused characters with the empty positions arbitrarily.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    vector<vector<int>> at(26);\n    for (int i = 0; i < n; i++) {\n      at[(int) (s[i] - 'a')].push_back(i);\n    }\n    vector<int> order(26);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j) {\n      return at[i].size() > at[j].size();\n    });\n    string res = \"\";\n    int best = -1;\n    for (int cnt = 1; cnt <= 26; cnt++) {\n      if (n % cnt == 0) {\n        int cur = 0;\n        for (int i = 0; i < cnt; i++) {\n          cur += min(n / cnt, (int) at[order[i]].size());\n        }\n        if (cur > best) {\n          best = cur;\n          res = string(n, ' ');\n          vector<char> extra;\n          for (int it = 0; it < cnt; it++) {\n            int i = order[it];\n            for (int j = 0; j < n / cnt; j++) {\n              if (j < (int) at[i].size()) {\n                res[at[i][j]] = (char) ('a' + i);\n              } else {\n                extra.push_back((char) ('a' + i));\n              }\n            }\n          }\n          for (char& c : res) {\n            if (c == ' ') {\n              c = extra.back();\n              extra.pop_back();\n            }\n          }\n        }\n      }\n    }\n    cout << n - best << '\\n';\n    cout << res << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1781",
    "index": "D",
    "title": "Many Perfect Squares",
    "statement": "You are given a set $a_1, a_2, \\ldots, a_n$ of distinct positive integers.\n\nWe define the squareness of an integer $x$ as the number of perfect squares among the numbers $a_1 + x, a_2 + x, \\ldots, a_n + x$.\n\nFind the maximum squareness among all integers $x$ between $0$ and $10^{18}$, inclusive.\n\nPerfect squares are integers of the form $t^2$, where $t$ is a non-negative integer. The smallest perfect squares are $0, 1, 4, 9, 16, \\ldots$.",
    "tutorial": "The answer is obviously at least $1$. Can we make it at least $2$? In this case, let's check all possible pairs of indices $i < j$ and try to figure out for what values of $x$ both $a_i + x$ and $a_j + x$ are perfect squares. We can write down two equations: $a_i + x = p^2$ and $a_j + x = q^2$, for some non-negative integers $p < q$. Let's subtract the first equation from the second one and apply the formula of difference of two squares: $a_j - a_i = q^2 - p^2 = (q - p)(q + p)$. It follows that $q - p$ is a positive integer divisor of $a_j - a_i$. It is well-known how to enumerate all divisors of $a_j - a_i$ in $O(\\sqrt{a_j - a_i})$. For each such divisor $d$, we have a simple system of equations for $p$ and $q$: $\\begin{cases} q - p = d \\\\ q + p = \\frac{a_j - a_i}{d} \\end{cases}$ that we can solve: $\\begin{cases} p = \\frac{1}{2}(\\frac{a_j - a_i}{d} - d) \\\\ q = \\frac{1}{2}(\\frac{a_j - a_i}{d} + d) \\\\ \\end{cases}$ and if both $p$ and $q$ turn out to be integers, that means we have found a candidate value for $x$: $x = p^2 - a_i = q^2 - a_j$. For each candidate value of $x$, we can just calculate its squareness and find the maximum. The complexity of this solution is $O(n^2 \\cdot \\sqrt{a_n} + n^3 \\cdot f(a_n))$, where $f(a_n)$ is the maximum number of divisors an integer between $1$ and $a_n$ can have. The first part corresponds to finding all divisors of $a_j - a_i$ for all pairs $i < j$. The second part corresponds to checking all candidate values of $x$: there are $O(n^2 \\cdot f(a_n))$ of them, and we need $O(n)$ time to calculate the squareness of each. Bonus: The first part can be optimized by using faster factorization methods. Can you see how to optimize the second part to $O(n^2 \\cdot f(a_n))$?",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n      cin >> a[i];\n    }\n    int ans = 1;\n    auto Test = [&](long long x) {\n      int cnt = 0;\n      for (int v : a) {\n        long long u = llround(sqrtl(v + x));\n        if (u * u == v + x) {\n          cnt += 1;\n        }\n      }\n      ans = max(ans, cnt);\n    };\n    for (int i = 0; i < n; i++) {\n      for (int j = i + 1; j < n; j++) {\n        int diff = a[j] - a[i];\n        for (int k = 1; k * k <= diff; k++) {\n          if (diff % k == 0) {\n            long long q = k + diff / k;\n            if (q % 2 == 0) {\n              q /= 2;\n              if (q * q >= a[j]) {\n                Test(q * q - a[j]);\n              }\n            }\n          }\n        }\n      }\n    }\n    cout << ans << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1781",
    "index": "E",
    "title": "Rectangle Shrinking",
    "statement": "You have a rectangular grid of height $2$ and width $10^9$ consisting of unit cells. There are $n$ rectangles placed on this grid, and the borders of these rectangles pass along cell borders. The $i$-th rectangle covers all cells in rows from $u_i$ to $d_i$ inclusive and columns from $l_i$ to $r_i$ inclusive ($1 \\le u_i \\le d_i \\le 2$; $1 \\le l_i \\le r_i \\le 10^9$). The initial rectangles can intersect, be nested, and coincide arbitrarily.\n\nYou should either remove each rectangle, or replace it with any of its non-empty subrectangles. In the latter case, the new subrectangle must lie inside the initial rectangle, and its borders must still pass along cell borders. In particular, it is allowed for the subrectangle to be equal to the initial rectangle.\n\nAfter that replacement, no two (non-removed) rectangles are allowed to have common cells, and the total area covered with the new rectangles must be as large as possible.\n\n\\begin{center}\n{\\small Illustration for the first test case. The initial rectangles are given at the top, the new rectangles are given at the bottom. Rectangle number $4$ is removed.}\n\\end{center}",
    "tutorial": "It turns out that it is always possible to cover all cells that are covered by the initial rectangles. If the grid had height $1$ instead of $2$, the solution would be fairly simple. Sort the rectangles in non-decreasing order of their left border $l_i$. Maintain a variable $p$ denoting the rightmost covered cell. Then, for each rectangle, in order: If $r_i \\le p$, remove this rectangle (note that since we process the rectangles in non-decreasing order of $l_i$, it means that this rectangle is fully covered by other rectangles). Otherwise, if $l_i \\le p$, set $l_i = p + 1$ (shrink the current rectangle). Then, set $p = r_i$ (this is the new rightmost covered cell). Let's generalize this approach for a height $2$ grid. Again, sort the rectangles in non-decreasing order of $l_i$, and maintain two variables $p_1$ and $p_2$ denoting the rightmost covered cell in row $1$ and row $2$, respectively. Then, for each rectangle, in order: If it is a height $1$ rectangle (that is, $u_i = d_i$), proceed similarly to the \"height $1$ grid\" case above: If $r_i \\le p_{u_i}$, remove this rectangle. Otherwise, if $l_i \\le p_{u_i}$, set $l_i = p_{u_i} + 1$. Then, set $p_{u_i} = r_i$. If $r_i \\le p_{u_i}$, remove this rectangle. Otherwise, if $l_i \\le p_{u_i}$, set $l_i = p_{u_i} + 1$. Then, set $p_{u_i} = r_i$. If it is a height $2$ rectangle (that is, $u_i = 1$ and $d_i = 2$): If $r_i \\le p_1$, set $u_i = 2$ (remove the first row from the rectangle) and go back to the \"height $1$ rectangle\" case above. If $r_i \\le p_2$, set $d_i = 1$ (remove the second row from the rectangle) and go back to the \"height $1$ rectangle\" case above. Otherwise, consider all processed rectangles $j$ that have $r_j \\ge l_i$, i.e., intersect the $i$-th rectangle. If $l_j \\ge l_i$, remove rectangle $j$; otherwise, shrink rectangle $j$ by setting $r_j = l_i - 1$. Finally, set $p_1 = p_2 = r_i$. If $r_i \\le p_1$, set $u_i = 2$ (remove the first row from the rectangle) and go back to the \"height $1$ rectangle\" case above. If $r_i \\le p_2$, set $d_i = 1$ (remove the second row from the rectangle) and go back to the \"height $1$ rectangle\" case above. Otherwise, consider all processed rectangles $j$ that have $r_j \\ge l_i$, i.e., intersect the $i$-th rectangle. If $l_j \\ge l_i$, remove rectangle $j$; otherwise, shrink rectangle $j$ by setting $r_j = l_i - 1$. Finally, set $p_1 = p_2 = r_i$. Here, only the last case is tricky and different from our initial \"height $1$ grid\" solution, but it is also necessary: in a height $2$ grid, sometimes we have to shrink rectangles on the right, not only on the left. Now, if we implement this solution in a straightforward fashion, iterating over all $j < i$ for every $i$, we'll arrive at an $O(n^2)$ solution - again, purely because of the last case. To optimize it, note that once a rectangle is shrinked in this last case, it never has to be shrinked again. Thus, we can maintain all rectangles in a priority queue ordered by their $r_i$, and once we pop a rectangle from the priority queue, we will never have to push it again, which will help us arrive at an amortized $O(n \\log n)$ solution. Instead of a priority queue, we can use some stacks as well - one for each row and maybe an extra one for height $2$ rectangles. The overall time complexity will still be $O(n \\log n)$ due to sorting.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n;\n    cin >> n;\n    vector<int> r1(n), c1(n), r2(n), c2(n);\n    for (int i = 0; i < n; i++) {\n      cin >> r1[i] >> c1[i] >> r2[i] >> c2[i];\n      assert(1 <= r1[i] && r1[i] <= r2[i] && r2[i] <= 2 && c1[i] <= c2[i]);\n      --c1[i];\n    }\n    vector<int> order(n);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j) {\n      return c1[i] < c1[j];\n    });\n    set<pair<int, int>> s;\n    int ans = 0;\n    int p1 = -1;\n    int p2 = -1;\n    for (int i : order) {\n      if (r1[i] == 1 && r2[i] == 2) {\n        if (p1 >= c2[i]) {\n          r1[i] = 2;\n        }\n        if (p2 >= c2[i]) {\n          r2[i] = 1;\n        }\n        if (r1[i] > r2[i]) {\n          continue;\n        }\n      }\n      if (r1[i] == 1 && r2[i] == 2) {\n        while (!s.empty()) {\n          auto it = prev(s.end());\n          if (it->first >= c1[i]) {\n            c2[it->second] = c1[i];\n            s.erase(it);\n          } else {\n            break;\n          }\n        }\n        ans += (c2[i] - max(c1[i], p1)) + (c2[i] - max(c1[i], p2));\n        p1 = p2 = c2[i];\n        s.emplace(c2[i], i);\n        continue;\n      }\n      assert(r1[i] == r2[i]);\n      if (r1[i] == 1) {\n        c1[i] = max(c1[i], p1);\n        p1 = max(p1, c2[i]);\n      } else {\n        c1[i] = max(c1[i], p2);\n        p2 = max(p2, c2[i]);\n      }\n      if (c1[i] < c2[i]) {\n        ans += c2[i] - c1[i];\n        s.emplace(c2[i], i);\n      }\n    }\n    cout << ans << '\\n';\n    for (int i = 0; i < n; i++) {\n      ++c1[i];\n      if (r1[i] <= r2[i] && c1[i] <= c2[i]) {\n        cout << r1[i] << \" \" << c1[i] << \" \" << r2[i] << \" \" << c2[i] << '\\n';\n      } else {\n        cout << \"0 0 0 0\" << '\\n';\n      }\n    }\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1781",
    "index": "F",
    "title": "Bracket Insertion",
    "statement": "Vika likes playing with bracket sequences. Today she wants to create a new bracket sequence using the following algorithm. Initially, Vika's sequence is an empty string, and then she will repeat the following actions $n$ times:\n\n- Choose a place in the current bracket sequence to insert new brackets uniformly at random. If the length of the current sequence is $k$, then there are $k+1$ such places: before the first bracket, between the first and the second brackets, $\\ldots$, after the $k$-th bracket. In particular, there is one such place in an empty bracket sequence.\n- Choose string \"()\" with probability $p$ or string \")(\" with probability $1 - p$ and insert it into the chosen place. The length of the bracket sequence will increase by $2$.\n\nA bracket sequence is called regular if it is possible to obtain a correct arithmetic expression by inserting characters '+' and '1' into it. For example, sequences \"(())()\", \"()\", and \"(()(()))\" are regular, while \")(\", \"(()\", and \"(()))(\" are not.\n\nVika wants to know the probability that her bracket sequence will be a regular one at the end. Help her and find this probability modulo $998\\,244\\,353$ (see Output section).",
    "tutorial": "Instead of looking at a probabilistic process, we can consider all possible ways of inserting brackets. There are $1 \\cdot 3 \\cdot 5 \\cdot \\ldots \\cdot (2n - 1) = (2n - 1)!!$ ways of choosing places, and $2^n$ ways of choosing \"()\" or \")(\" at every point. Let $r$ be the sum of $p^k \\cdot (1-p)^{n-k}$ over all such ways that lead to a regular bracket sequence, where $k$ is the number of strings \"()\" inserted during the process (and $n - k$ is then the number of strings \")(\" inserted). Then, $\\frac{r}{(2n - 1)!!}$ is the answer to the problem. Consider the sequence of \"prefix balances\" of the bracket sequence. The first (empty) prefix balance is $0$, and each successive balance is $1$ larger than the previous one if the next bracket is '(', and $1$ smaller if the bracket is ')'. Initially, when the bracket sequence is empty, the sequence of prefix balances is $[0]$. Whenever we insert \"()\" into the bracket sequence in a place with prefix balance $x$, essentially we are replacing $x$ with $[x, x + 1, x]$ in the sequence of prefix balances. Whenever we insert \")(\" instead, that's equivalent to replacing $x$ with $[x, x - 1, x]$. A bracket sequence is regular if and only if its corresponding sequence of prefix balances does not have any negative integers (and ends with $0$; however, this is guaranteed in our setting). Thus, we can reformulate the problem as follows: Initially, we have an integer array $[0]$. $n$ times, we choose an integer from the array uniformly at random. Say this integer is $x$, then we replace $x$ with $[x, x + 1, x]$ with probability $p$, and with $[x, x - 1, x]$ with probability $1 - p$. What is the probability that the sequence will not contain negative integers at any point? Let $f(n, x)$ be the sought probability multiplied by $(2n - 1)!!$ if we start with $[x]$ Here, we multiply by $(2n-1)!!$ to simplify the formulas, and to keep thinking about \"numbers of ways\" instead of \"probabilities\", as described in the first paragraph of this tutorial. The base cases are $f(0, x) = 1$ if $x \\ge 0$, and $f(0, x) = 0$ otherwise. When $n > 0$: $f(n, x) =$$= \\sum\\limits_{i=0}^{n-1} \\sum\\limits_{j=0}^{n-1-i} p \\cdot \\binom{n-1}{i} \\cdot \\binom{n-1-i}{j} \\cdot f(i, x) \\cdot f(j, x + 1) \\cdot f(n - 1 - i - j, x) +$ $+ \\sum\\limits_{i=0}^{n-1} \\sum\\limits_{j=0}^{n-1-i} (1 - p) \\cdot \\binom{n-1}{i} \\cdot \\binom{n-1-i}{j} \\cdot f(i, x) \\cdot f(j, x - 1) \\cdot f(n - 1 - i - j, x)$. $= \\sum\\limits_{i=0}^{n-1} \\sum\\limits_{j=0}^{n-1-i} p \\cdot \\binom{n-1}{i} \\cdot \\binom{n-1-i}{j} \\cdot f(i, x) \\cdot f(j, x + 1) \\cdot f(n - 1 - i - j, x) +$ $+ \\sum\\limits_{i=0}^{n-1} \\sum\\limits_{j=0}^{n-1-i} (1 - p) \\cdot \\binom{n-1}{i} \\cdot \\binom{n-1-i}{j} \\cdot f(i, x) \\cdot f(j, x - 1) \\cdot f(n - 1 - i - j, x)$. What does this formula mean? Essentially, since we start with an array of a single integer $[x]$, the first operation has to be applied to $x$. After that, once $x$ gets replaced with $[x, x \\pm 1, x]$, $i$ operations will be applied to the left $x$ (including everything produced from it), $j$ operations will be applied to $x \\pm 1$ (again, together with its production), and $n - 1 - i - j$ operations will be applied to the right $x$ (and to its production). Thus, we can find the sum over $i$ and $j$ of the product of the corresponding values of $f$ and the binomial coefficients: since the sequences of $i$, $j$, and $n - 1 - i - j$ operations can be interleaved arbitrarily, we have $\\binom{n-1}{i}$ ways to choose the positions of $i$ operations applied to the left $x$ in the global sequence of $n-1$ operations, and then $\\binom{n-1-i}{j}$ ways to choose the positions of $j$ operations applied to $x \\pm 1$ out of the remaining $n - 1 - i$ positions in the global sequence. This results in an $O(n^4)$ solution, since there are $O(n^2)$ values of $f$ to calculate, and each of them is calculated in $O(n^2)$. To optimize it, let's rewrite the formula a little bit by moving the loop over $j$ outside: $f(n, x) = \\sum\\limits_{j=0}^{n-1} (p \\cdot f(j, x + 1) + (1 - p) \\cdot f(j, x - 1)) \\cdot \\binom{n-1}{j} \\cdot \\sum\\limits_{i=0}^{n-1-j} \\binom{n-1-j}{i} \\cdot f(i, x) \\cdot f(n - 1 - j - i, x)$. Now, let's introduce an auxiliary function: $g(k, x) = \\sum\\limits_{i=0}^{k} \\binom{k}{i} \\cdot f(i, x) \\cdot f(k - i, x)$. Now, let's rewrite the formula for $f$ using $g$: $f(n, x) = \\sum\\limits_{j=0}^{n-1} (p \\cdot f(j, x + 1) + (1 - p) \\cdot f(j, x - 1)) \\cdot \\binom{n-1}{j} \\cdot g(n - 1 - j, x)$. Now, both $g(n, x)$ and $f(n, x)$ can be computed in $O(n)$ time, resulting in an $O(n^3)$ solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <typename T>\nT inverse(T a, T m) {\n  T u = 0, v = 1;\n  while (a != 0) {\n    T t = m / a;\n    m -= t * a; swap(a, m);\n    u -= t * v; swap(u, v);\n  }\n  assert(m == 1);\n  return u;\n}\n\ntemplate <typename T>\nclass Modular {\n public:\n  using Type = typename decay<decltype(T::value)>::type;\n\n  constexpr Modular() : value() {}\n  template <typename U>\n  Modular(const U& x) {\n    value = normalize(x);\n  }\n\n  template <typename U>\n  static Type normalize(const U& x) {\n    Type v;\n    if (-mod() <= x && x < mod()) v = static_cast<Type>(x);\n    else v = static_cast<Type>(x % mod());\n    if (v < 0) v += mod();\n    return v;\n  }\n\n  const Type& operator()() const { return value; }\n  template <typename U>\n  explicit operator U() const { return static_cast<U>(value); }\n  constexpr static Type mod() { return T::value; }\n\n  Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; }\n  Modular& operator-=(const Modular& other) { if ((value -= other.value) < 0) value += mod(); return *this; }\n  template <typename U> Modular& operator+=(const U& other) { return *this += Modular(other); }\n  template <typename U> Modular& operator-=(const U& other) { return *this -= Modular(other); }\n  Modular operator-() const { return Modular(-value); }\n\n  template <typename U = T>\n  typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) {\n    value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));\n    return *this;\n  }\n\n  Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); }\n\n  template <typename V, typename U>\n  friend V& operator>>(V& stream, Modular<U>& number);\n\n private:\n  Type value;\n};\n\ntemplate <typename T> Modular<T> operator+(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }\ntemplate <typename T, typename U> Modular<T> operator+(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) += rhs; }\ntemplate <typename T, typename U> Modular<T> operator+(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }\n\ntemplate <typename T> Modular<T> operator-(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }\ntemplate <typename T, typename U> Modular<T> operator-(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) -= rhs; }\ntemplate <typename T, typename U> Modular<T> operator-(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }\n\ntemplate <typename T> Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }\n\ntemplate <typename U, typename T>\nU& operator<<(U& stream, const Modular<T>& number) {\n  return stream << number();\n}\n\ntemplate <typename U, typename T>\nU& operator>>(U& stream, Modular<T>& number) {\n  typename common_type<typename Modular<T>::Type, long long>::type x;\n  stream >> x;\n  number.value = Modular<T>::normalize(x);\n  return stream;\n}\n\nconstexpr int md = 998244353;\nusing Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n;\n  Mint p;\n  cin >> n >> p;\n  p /= 10000;\n  vector<vector<Mint>> C(n + 1, vector<Mint>(n + 1));\n  for (int i = 0; i <= n; i++) {\n    C[i][0] = 1;\n    for (int j = 1; j <= i; j++) {\n      C[i][j] = C[i - 1][j] + C[i - 1][j - 1];\n    }\n  }\n  vector<vector<Mint>> dp(n + 1, vector<Mint>(n + 1));\n  vector<vector<Mint>> aux(n + 1, vector<Mint>(n + 1));\n  for (int b = 0; b <= n; b++) {\n    dp[0][b] = aux[0][b] = 1;\n  }\n  for (int i = 1; i <= n; i++) {\n    for (int b = 0; b <= n - i; b++) {\n      for (int y = 0; y <= i - 1; y++) {\n        dp[i][b] += C[i - 1][y] * aux[i - 1 - y][b] * (dp[y][b + 1] * p + (b == 0 ? 0 : dp[y][b - 1] * (1 - p)));\n      }\n      for (int j = 0; j <= i; j++) {\n        aux[i][b] += dp[j][b] * dp[i - j][b] * C[i][j];\n      }\n    }\n  }\n  auto ans = dp[n][0];\n  for (int i = 1; i <= 2 * n; i += 2) {\n    ans /= i;\n  }\n  cout << ans << '\\n';\n  return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1781",
    "index": "G",
    "title": "Diverse Coloring",
    "statement": "In this problem, we will be working with rooted binary trees. A tree is called a rooted binary tree if it has a fixed root and every vertex has at most two children.\n\nLet's assign a color — white or blue — to each vertex of the tree, and call this assignment a coloring of the tree. Let's call a coloring diverse if every vertex has a neighbor (a parent or a child) colored into an opposite color compared to this vertex. It can be shown that any tree with at least two vertices allows a diverse coloring.\n\nLet's define the disbalance of a coloring as the absolute value of the difference between the number of white vertices and the number of blue vertices.\n\nNow to the problem. Initially, the tree consists of a single vertex with the number $1$ which is its root. Then, for each $i$ from $2$ to $n$, a new vertex $i$ appears in the tree, and it becomes a child of vertex $p_i$. It is guaranteed that after each step the tree will keep being a binary tree rooted at vertex $1$, that is, each vertex will have at most two children.\n\nAfter every new vertex is added, print the smallest value of disbalance over all possible diverse colorings of the current tree. Moreover, after adding the last vertex with the number $n$, also print a diverse coloring with the smallest possible disbalance as well.",
    "tutorial": "It turns out that it is always possible to construct a diverse coloring with disbalance $0$ or $1$ (depending on the parity of $n$), except for the case of a tree with $4$ vertices with one vertex of degree $3$ (which is given in the example). Let's traverse the tree from bottom to top. For each subtree, we will try to construct a diverse coloring where the subtree root is colored white. We will define the disbalance of the subtree coloring to be the number of vertices colored white, minus the number of vertices colored blue. This is equivalent to the original definition, except that now the number also has a sign. We will aim at obtaining disbalances $0$ and $+1$, if possible. In some small cases, it will be impossible. We will say \"subtree has disbalance $x$\" or \"vertex has disbalance $x$\", meaning that we have constructed a coloring of the (vertex's) subtree with disbalance $x$. Let $u$ be the root of the subtree (colored white): If $u$ has no children, the only coloring has disbalance $+1$; however, it is not diverse. Thus, we will have to be careful about the leaf case in the future. If $u$ has one child $v$, flip the colors in $v$'s subtree to create a blue neighbor for $u$: If $v$ had disbalance $0$ before the flip, now $u$ has disbalance $+1$. If $u$ had disbalance $+1$ before the flip, now $u$ has disbalance $0$. If $v$ had disbalance $0$ before the flip, now $u$ has disbalance $+1$. If $u$ had disbalance $+1$ before the flip, now $u$ has disbalance $0$. If $u$ has two children $v$ and $w$: If both have disbalance $0$, flip the colors in at least one of $v$'s and $w$'s subtrees, now $u$ has disbalance $+1$. If both have disbalance $+1$, flip the colors in either $v$'s or $w$'s subtree, now $u$ has disbalance $+1$. If one has disbalance $0$ and the other has disbalance $+1$, flip the colors in the one with $0$, now $u$ has disbalance $0$. If both have disbalance $0$, flip the colors in at least one of $v$'s and $w$'s subtrees, now $u$ has disbalance $+1$. If both have disbalance $+1$, flip the colors in either $v$'s or $w$'s subtree, now $u$ has disbalance $+1$. If one has disbalance $0$ and the other has disbalance $+1$, flip the colors in the one with $0$, now $u$ has disbalance $0$. The only issue happens when $u$ has two children that are both leaves: we have to recolor both $v$ and $w$ into blue, which will force $u$ to have disbalance $-1$. Let's add new cases to the analysis above based on the existence of subtrees with disbalance $-1$: If $u$ has one child $v$ with disbalance $-1$: Flip the colors in $v$'s subtree, now $u$ has disbalance $+2$. Flip the colors in $v$'s subtree, now $u$ has disbalance $+2$. If $u$ has two children $v$ and $w$, where $v$ has disbalance $-1$: If $w$ has disbalance $-1$, flip the colors in either $v$'s or $w$'s subtree, now $u$ has disbalance $+1$. If $w$ has disbalance $0$, flip the colors in $w$'s subtree, now $u$ has disbalance $0$. If $w$ has disbalance $+1$, flip the colors in both $v$'s and $w$'s subtrees, now $u$ has disbalance $+1$. If $w$ has disbalance $-1$, flip the colors in either $v$'s or $w$'s subtree, now $u$ has disbalance $+1$. If $w$ has disbalance $0$, flip the colors in $w$'s subtree, now $u$ has disbalance $0$. If $w$ has disbalance $+1$, flip the colors in both $v$'s and $w$'s subtrees, now $u$ has disbalance $+1$. We can see that, once again, a new case appears where a subtree has disbalance $+2$ (described at the beginning of this tutorial), and unfortunately we can't avoid that. We can see that this case only happens for a specific subtree of $4$ vertices. Let's proceed with the case analysis... If $u$ has one child $v$ with disbalance $+2$: Flip $v$'s color (not the whole subtree, but just $v$), now $u$ has disbalance $+1$. Flip $v$'s color (not the whole subtree, but just $v$), now $u$ has disbalance $+1$. If $u$ has two children $v$ and $w$, where $v$ has disbalance $+2$: If $w$ has disbalance $-1$, flip the colors in both $v$'s and $w$'s subtrees, now $u$ has disbalance $0$. If $w$ has disbalance $0$, flip $v$'s color, now $u$ has disbalance $+1$. If $w$ has disbalance $+1$, flip $v$'s color and the colors in $w$'s subtree, now $u$ has disbalance $0$. If $w$ has disbalance $+2$, flip the colors in either $v$'s or $w$'s subtree, now $u$ has disbalance $+1$. If $w$ has disbalance $-1$, flip the colors in both $v$'s and $w$'s subtrees, now $u$ has disbalance $0$. If $w$ has disbalance $0$, flip $v$'s color, now $u$ has disbalance $+1$. If $w$ has disbalance $+1$, flip $v$'s color and the colors in $w$'s subtree, now $u$ has disbalance $0$. If $w$ has disbalance $+2$, flip the colors in either $v$'s or $w$'s subtree, now $u$ has disbalance $+1$. It follows that for any other tree, except two special cases of a $3$-vertex tree and a $4$-vertex tree, it is possible to obtain disbalance $0$ or $+1$. From this point, one way to implement the solution is to carefully consider all the cases. Note that whenever we say \"flip the colors in $v$'s subtree\", we can just set some flag in vertex $v$. Then, as we traverse the tree from top to bottom, we can construct the correct coloring in $O(n)$ time. Another way is to use dynamic programming f(u, d, hasNeighbor) = true/false: whether it is possible to color $u$'s subtree to obtain disbalance $d$ so that all vertices except $u$ have neighbors of opposite color, and $u$ has such a neighbor iff hasNeighbor = true. Since it is enough to limit disbalance by $O(1)$, we can conclude that the number of states, the number of transitions, and the time complexity are all $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n;\n    cin >> n;\n    vector<int> p(n);\n    for (int i = 1; i < n; i++) {\n      cin >> p[i];\n      --p[i];\n    }\n    for (int i = 2; i <= n; i++) {\n      if (i == 4 && p[1] == 0 && p[2] == 1 && p[3] == 1) {\n        cout << 2 << '\\n';\n      } else {\n        cout << i % 2 << '\\n';\n      }\n    }\n    vector<vector<int>> g(n);\n    for (int i = 1; i < n; i++) {\n      g[p[i]].push_back(i);\n    }\n    string res = \"\";\n    auto Solve = [&](int nn) {\n      vector<vector<vector<bool>>> good(nn);\n      vector<vector<vector<vector<int>>>> prevs(nn);\n      vector<int> sz(nn);\n      vector<int> L(nn);\n      vector<int> R(nn);\n      function<void(int)> Dfs = [&](int v) {\n        sz[v] += 1;\n        for (int u : g[v]) {\n          Dfs(u);\n          sz[v] += sz[u];\n        }\n        L[v] = sz[v] / 2;\n        R[v] = L[v] + 1;\n        good[v].assign(2, vector<bool>(R[v] - L[v] + 1, false));\n        prevs[v].assign(2, vector<vector<int>>(R[v] - L[v] + 1));\n        auto Set = [&](int c, int k, vector<int> pr) {\n          if (k >= L[v] && k <= R[v]) {\n            good[v][c][k - L[v]] = true;\n            prevs[v][c][k - L[v]] = pr;\n          }\n        };\n        if (g[v].size() == 0) {\n          Set(0, 1, {});\n        }\n        if (g[v].size() == 1) {\n          int u = g[v][0];\n          for (int cu = 0; cu < 2; cu++) {\n            for (int ku = L[u]; ku <= R[u]; ku++) {\n              if (good[u][cu][ku - L[u]]) {\n                Set(1, 1 + (sz[u] - ku), {cu, ku, 1});\n                if (cu == 1) {\n                  Set(0, 1 + ku, {cu, ku, 0});\n                }\n              }\n            }\n          }\n        }\n        if (g[v].size() == 2) {\n          int u = g[v][0];\n          int w = g[v][1];\n          for (int cu = 0; cu < 2; cu++) {\n            for (int ku = L[u]; ku <= R[u]; ku++) {\n              if (good[u][cu][ku - L[u]]) {\n                for (int cw = 0; cw < 2; cw++) {\n                  for (int kw = L[w]; kw <= R[w]; kw++) {\n                    if (good[w][cw][kw - L[w]]) {\n                      Set(1, 1 + (sz[u] - ku) + (sz[w] - kw), {cu, ku, 1, cw, kw, 1});\n                      if (cu == 1) {\n                        Set(1, 1 + ku + (sz[w] - kw), {cu, ku, 0, cw, kw, 1});\n                      }\n                      if (cw == 1) {\n                        Set(1, 1 + (sz[u] - ku) + kw, {cu, ku, 1, cw, kw, 0});\n                      }\n                      if (cu == 1 && cw == 1) {\n                        Set(0, 1 + ku + kw, {cu, ku, 0, cw, kw, 0});\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      };\n      Dfs(0);\n      int best = nn + 1;\n      int best_k = -1;\n      for (int k = L[0]; k <= R[0]; k++) {\n        if (good[0][1][k - L[0]]) {\n          int val = abs(k - (nn - k));\n          if (val < best) {\n            best = val;\n            best_k = k;\n          }\n        }\n      }\n      assert(best <= nn);\n      res = string(nn, '.');\n      function<void(int, int, int)> Restore = [&](int v, int c, int k) {\n        int ptr = 0;\n        for (int u : g[v]) {\n          res[u] = (prevs[v][c][k - L[v]][ptr + 2] == 0 ? res[v] : (char) ('w' ^ 'b' ^ res[v]));\n          Restore(u, prevs[v][c][k - L[v]][ptr], prevs[v][c][k - L[v]][ptr + 1]);\n          ptr += 3;\n        }\n      };\n      res[0] = 'w';\n      Restore(0, 1, best_k);\n      return best;\n    };\n    Solve(n);\n    cout << res << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1781",
    "index": "H2",
    "title": "Window Signals (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, the constraints on $h$ and $w$ are higher.}\n\nA house at the sea has $h$ floors, all of the same height. The side of the house facing the sea has $w$ windows at equal distances from each other on every floor. Thus, the windows are positioned in cells of a rectangular grid of size $h \\times w$.\n\nIn every window, the light can be turned either on or off, except for the given $k$ (at most $2$) windows. In these $k$ windows the light can not be turned on, because it is broken.\n\nIn the dark, we can send a signal to a ship at sea using a configuration of lights turned on and off. However, the ship can not see the position of the lights with respect to the house. Thus, if one configuration of windows with lights on can be transformed into another using parallel translation, these configurations are considered equal. Note that only parallel translation is allowed, but neither rotations nor flips are. Moreover, a configuration without any light at all is not considered valid.\n\nFind how many different signals the ship can receive and print this number modulo $998\\,244\\,353$.",
    "tutorial": "Let's iterate over the dimensions of the bounding box of the image of windows with lights on, $h' \\times w'$ ($1 \\le h' \\le h; 1 \\le w' \\le w$), count images with such bounding box, and sum all these values up. An image has a bounding box of size exactly $h' \\times w'$ if and only if: it fits inside an $h' \\times w'$ rectangle; it has a light on each of its four borders. To account for the second condition, we can use inclusion-exclusion principle. This way, we will have an \"it does not have a light on some of its borders\" condition instead, at the cost of an extra $2^4$ time factor. We will disregard this condition in the rest of this tutorial. There are $2^{h'w'}$ possible images fitting in an $h' \\times w'$ rectangles. How many of them are impossible to show because of broken lights? Let's find this number and subtract it. Consider all possible ways to place a rectangle of size $h' \\times w'$ on the given $h \\times w$ grid: If there are no broken lights inside, any image of size $h' \\times w'$ is possible to show, so we don't need to subtract anything for this size at all. If there is $1$ broken light inside, its relative position in the $h' \\times w'$ rectangle must be turned on (for an image to be impossible to show). If there are $2$ broken lights inside, find their relative positions in the $h' \\times w'$ rectangle. For an image to be impossible to show, at least one of the two positions must be turned on. Unless a placement with no broken lights exists, we have some cells in the rectangle where the light must be turned on - let's call the set of these cells $X$, and some pairs of cells where at least one light must be turned on - let's call the set of these pairs $Y$. If a pair from $Y$ contains a cell from $X$, this pair can be removed from $Y$. Once we do that, note that the pairs from $Y$ form several chains - that happens because the coordinate-wise distance between the cells in each pair is equal to the distance between the broken lights, which is $(r_2 - r_1, c_2 - c_1)$. If we have a chain of length $p$, it can be seen that there are $f(p)$ ways to turn lights on so that every pair of neighboring cells has at least one light, where $f(p) = f(p - 1) + f(p - 2)$ are Fibonacci numbers. Thus, the number to subtract is the product of: $2^w$, where $w$ is the number of cells not included in $X$ and $Y$; $f(p)$ over all chains formed by $Y$, where $p$ is the length of a chain. Every subgrid size $h' \\times w'$ is processed in $O(hw)$ time, and there are $hw$ different sizes, thus, the overall time complexity is $O(h^2 w^2)$. It is possible to optimize the constant factor of this solution to pass the hard version too. However, a solution of $O(h w^2)$ time complexity exists as well. Here is a sketch of it: Instead of fixing both dimensions of the lights image, $h'$ and $w'$, let's only fix $w'$. Use inclusion-exclusion like described at the beginning of this tutorial; however, only use it for the top, left, and right borders. We will not use it for the bottom border, since we are not fixing the height of the image. Go through all top-left corners $(i, j)$ of the lights image in lexicographic order ($1 \\le i \\le h; 1 \\le j \\le w - w' + 1$). For each top-left corner, count how many images of width $w'$ can be shown using this top-left corner, which can not be shown using any previous top-left corner. Similarly to the previous solution, consider cases of $0$, $1$, and $2$ broken lights inside the current subgrid. Note, however, that we are not fixing the height of the subgrid, so just assume that it stretches all the way down to the bottom border of the whole grid. Maintain the set of cells $X$ using an array, and maintain the set of pairs $Y$ using linked lists. Once a cell joins set $X$, remove all pairs that touch it from set $Y$. Once a pair joins set $Y$, if neither of its ends belongs to $X$, merge two corresponding linked lists. Maintain a variable denoting the product of $f(p)$ over all chains formed by $Y$. Once any split or merge happens to the lists, update this variable using $O(1)$ multiplications/divisions. Whenever $i$ (the row number of the top-left corner) increases by $1$, the maximum available height of the lights image decreases by $1$. Thus, we have to \"remove\" the cells in the current bottom row: that is, for any future image, we won't be able to light up those cells. If any such cell belongs to $X$, just stop: we won't get any new images. Otherwise, if such a cell belongs to a pair in $Y$, add the second end of this pair to $X$. For fixed width $w'$ and for each top-left corner $(i, j)$, we need to spend $O(1)$ time. Moreover, for fixed width $w'$, once $i$ increases (which happens $O(h)$ times), we need to spend $O(w)$ time to process cell removals. Hence, the time complexity of both parts is $O(h w^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <typename T>\nT inverse(T a, T m) {\n  T u = 0, v = 1;\n  while (a != 0) {\n    T t = m / a;\n    m -= t * a; swap(a, m);\n    u -= t * v; swap(u, v);\n  }\n  assert(m == 1);\n  return u;\n}\n\ntemplate <typename T>\nclass Modular {\n public:\n  using Type = typename decay<decltype(T::value)>::type;\n\n  constexpr Modular() : value() {}\n  template <typename U>\n  Modular(const U& x) {\n    value = normalize(x);\n  }\n\n  template <typename U>\n  static Type normalize(const U& x) {\n    Type v;\n    if (-mod() <= x && x < mod()) v = static_cast<Type>(x);\n    else v = static_cast<Type>(x % mod());\n    if (v < 0) v += mod();\n    return v;\n  }\n\n  const Type& operator()() const { return value; }\n  template <typename U>\n  explicit operator U() const { return static_cast<U>(value); }\n  constexpr static Type mod() { return T::value; }\n\n  Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; }\n  Modular& operator-=(const Modular& other) { if ((value -= other.value) < 0) value += mod(); return *this; }\n  template <typename U> Modular& operator+=(const U& other) { return *this += Modular(other); }\n  template <typename U> Modular& operator-=(const U& other) { return *this -= Modular(other); }\n  Modular operator-() const { return Modular(-value); }\n\n  template <typename U = T>\n  typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) {\n    value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));\n    return *this;\n  }\n\n  Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); }\n\n  template <typename V, typename U>\n  friend V& operator>>(V& stream, Modular<U>& number);\n\n private:\n  Type value;\n};\n\ntemplate <typename T> Modular<T> operator+(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }\ntemplate <typename T, typename U> Modular<T> operator+(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) += rhs; }\ntemplate <typename T, typename U> Modular<T> operator+(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }\n\ntemplate <typename T> Modular<T> operator-(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }\ntemplate <typename T, typename U> Modular<T> operator-(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) -= rhs; }\ntemplate <typename T, typename U> Modular<T> operator-(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }\n\ntemplate <typename T> Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }\ntemplate <typename T, typename U> Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; }\ntemplate <typename T, typename U> Modular<T> operator*(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }\n\ntemplate<typename T, typename U>\nModular<T> power(const Modular<T>& a, const U& b) {\n  assert(b >= 0);\n  Modular<T> x = a, res = 1;\n  U p = b;\n  while (p > 0) {\n    if (p & 1) res *= x;\n    x *= x;\n    p >>= 1;\n  }\n  return res;\n}\n\ntemplate <typename U, typename T>\nU& operator<<(U& stream, const Modular<T>& number) {\n  return stream << number();\n}\n\ntemplate <typename U, typename T>\nU& operator>>(U& stream, Modular<T>& number) {\n  typename common_type<typename Modular<T>::Type, long long>::type x;\n  stream >> x;\n  number.value = Modular<T>::normalize(x);\n  return stream;\n}\n\nconstexpr int md = 998244353;\nusing Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;\n\nclass dsu {\n public:\n  vector<int> p;\n  vector<int> sz;\n  int n;\n\n  dsu(int _n) : n(_n) {\n    p.resize(n);\n    iota(p.begin(), p.end(), 0);\n    sz.assign(n, 1);\n  }\n\n  inline int get(int x) {\n    return (x == p[x] ? x : (p[x] = get(p[x])));\n  }\n\n  inline bool unite(int x, int y) {\n    x = get(x);\n    y = get(y);\n    if (x != y) {\n      p[x] = y;\n      sz[y] += sz[x];\n      return true;\n    }\n    return false;\n  }\n};\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int h, w, k;\n    cin >> h >> w >> k;\n    vector<Mint> fib(h * w + 1);\n    fib[0] = 1;\n    fib[1] = 2;\n    for (int i = 2; i <= h * w; i++) {\n      fib[i] = fib[i - 1] + fib[i - 2];\n    }\n    vector<pair<int, int>> p(k);\n    for (int i = 0; i < k; i++) {\n      cin >> p[i].first >> p[i].second;\n      --p[i].first; --p[i].second;\n    }\n    Mint ans = 0;\n    for (int ww = 1; ww <= w; ww++) {\n      for (int top = 0; top < 2; top++) {\n        for (int left = 0; left < 2; left++) {\n          for (int right = 0; right < 2; right++) {\n            if (ww == 1 && left + right > 0) {\n              continue;\n            }\n            int sign = ((top + left + right) % 2 == 0 ? 1 : -1);\n            dsu d(h * ww);\n            vector<vector<int>> g(h * ww);\n            vector<bool> must(h * ww);\n            bool done = false;\n            Mint prod = power(Mint(2), (h - top) * (ww - left - right));\n            for (int i = 0; i < h; i++) {\n              for (int j = 0; j <= w - ww; j++) {\n                vector<pair<int, int>> here;\n                for (auto& c : p) {\n                  if (c.first >= i + top && c.second >= j + left && c.second < j + ww - right) {\n                    here.emplace_back(c.first - i, c.second - j);\n                  }\n                }\n                if (here.size() == 0) {\n                  ans += sign * prod;\n                  done = true;\n                  break;\n                }\n                if (here.size() == 1) {\n                  int x = here[0].first * ww + here[0].second;\n                  if (!must[x]) {\n                    must[x] = true;\n                    int px = d.get(x);\n                    prod /= fib[d.sz[px]];\n                    d.sz[px] -= 1;\n                    int sub = 0;\n                    for (int y : g[x]) {\n                      if (!must[y]) {\n                        sub += 1;\n                      }\n                    }\n                    ans += sign * prod * fib[d.sz[px] - sub];\n                    prod *= fib[d.sz[px]];\n                  }\n                }\n                if (here.size() == 2) {\n                  int x = here[0].first * ww + here[0].second;\n                  int y = here[1].first * ww + here[1].second;\n                  int px = d.get(x);\n                  int py = d.get(y);\n                  assert(px != py);\n                  prod /= fib[d.sz[px]];\n                  prod /= fib[d.sz[py]];\n                  if (!must[x] && !must[y]) {\n                    int subx = 1;\n                    for (int t : g[x]) {\n                      if (!must[t]) {\n                        subx += 1;\n                      }\n                    }\n                    int suby = 1;\n                    for (int t : g[y]) {\n                      if (!must[t]) {\n                        suby += 1;\n                      }\n                    }\n                    ans += sign * prod * fib[d.sz[px] - subx] * fib[d.sz[py] - suby];\n                    g[x].push_back(y);\n                    g[y].push_back(x);\n                  }\n                  d.unite(px, py);\n                  prod *= fib[d.sz[py]];\n                }\n              }\n              if (done) {\n                break;\n              }\n              for (int j = left; j < ww - right; j++) {\n                int x = (h - 1 - i) * ww + j;\n                if (must[x]) {\n                  done = true;\n                  break;\n                }\n                int px = d.get(x);\n                prod /= fib[d.sz[px]];\n                d.sz[px] -= 1;\n                prod *= fib[d.sz[px]];\n                for (int y : g[x]) {\n                  if (!must[y]) {\n                    must[y] = true;\n                    int py = d.get(y);\n                    prod /= fib[d.sz[py]];\n                    d.sz[py] -= 1;\n                    prod *= fib[d.sz[py]];\n                  }\n                }\n              }\n              if (done) {\n                break;\n              }\n            }\n          }\n        }\n      }\n    }\n    cout << ans << '\\n';\n  }\n  return 0;\n}",
    "tags": [],
    "rating": 3500
  },
  {
    "contest_id": "1783",
    "index": "A",
    "title": "Make it Beautiful",
    "statement": "An array $a$ is called ugly if it contains \\textbf{at least one} element which is equal to the \\textbf{sum of all elements before it}. If the array is not ugly, it is beautiful.\n\nFor example:\n\n- the array $[6, 3, 9, 6]$ is ugly: the element $9$ is equal to $6 + 3$;\n- the array $[5, 5, 7]$ is ugly: the element $5$ (the second one) is equal to $5$;\n- the array $[8, 4, 10, 14]$ is beautiful: $8 \\ne 0$, $4 \\ne 8$, $10 \\ne 8 + 4$, $14 \\ne 8 + 4 + 10$, so there is no element which is equal to the sum of all elements before it.\n\nYou are given an array $a$ such that $1 \\le a_1 \\le a_2 \\le \\dots \\le a_n \\le 100$. You have to \\textbf{reorder} the elements of $a$ in such a way that the resulting array is beautiful. Note that you are not allowed to insert new elements or erase existing ones, you can only change the order of elements of $a$. You are allowed to keep the array $a$ unchanged, if it is beautiful.",
    "tutorial": "If we put the maximum in the array on the first position, then for every element, starting from the third one, the sum of elements before it will be greater than it (since that sum is greater than the maximum value in the array). So, the only element that can make our array ugly is the second element. We need to make sure that it is not equal to the first element. Let's put the maximum element on the first position, the minimum element on the second position, and then fill the rest of the array arbitrarily. The only case when it fails is when the maximum element is equal to the minimum element - and it's easy to see that if the maximum is equal to the minimum, then the first element of the array will be equal to the second element no matter what, and the array cannot become beautiful. So, the solution is to check if the maximum is different from the minimum, and if it is so, put them on the first two positions, and the order of remaining elements does not matter. Note that the given array is sorted, so the minimum is the first element, the maximum is the last element.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n    if a[0] == a[n - 1]:\n        print('NO')\n    else:\n        print('YES')\n        print(a[n - 1], end = ' ')\n        print(*(a[0:n-1]))",
    "tags": [
      "constructive algorithms",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1783",
    "index": "B",
    "title": "Matrix of Differences",
    "statement": "For a square matrix of integers of size $n \\times n$, let's define its \\textbf{beauty} as follows: for each pair of side-adjacent elements $x$ and $y$, write out the number $|x-y|$, and then find the number of different numbers among them.\n\nFor example, for the matrix $\\begin{pmatrix} 1 & 3\\\\ 4 & 2 \\end{pmatrix}$ the numbers we consider are $|1-3|=2$, $|1-4|=3$, $|3-2|=1$ and $|4-2|=2$; there are $3$ different numbers among them ($2$, $3$ and $1$), which means that its beauty is equal to $3$.\n\nYou are given an integer $n$. You have to find a matrix of size $n \\times n$, where each integer from $1$ to $n^2$ occurs exactly once, such that its \\textbf{beauty} is the maximum possible among all such matrices.",
    "tutorial": "The first step is to notice that beauty doesn't exceed $n^2-1$, because the minimum difference between two elements is at least $1$, and the maximum difference does not exceed $n^2-1$ (the difference between the maximum element $n^2$ and the minimum element $1$). At first, finding a matrix with maximum beauty seems to be a quite difficult task. So let's try to find an array of $n^2$ elements of maximum beauty. In this case, it is not difficult to come up with an array of the form $[n^2, 1, n^2-1, 2, n^2-2, 3, \\dots]$. In such an array, there are all possible differences from $1$ to $n^2-1$. So we found an array with the maximum possible beauty. It remains to find a way to \"convert\" the array to the matrix, i.e. to find such a sequence of matrix cells that each two adjacent cells in it are side-adjacent. One of the ways is the following: traverse the first row of the matrix from left to right, go down to the second row, traverse it from right to left, go down to the third row, traverse it from left to right, and so on. Thus, we constructed a matrix with the maximum possible beauty $n^2-1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<vector<int>> a(n, vector<int>(n));\n    int l = 1, r = n * n, t = 0;\n    forn(i, n) {\n      forn(j, n) {\n        if (t) a[i][j] = l++;\n        else a[i][j] = r--;\n        t ^= 1;\n      }\n      if (i & 1) reverse(a[i].begin(), a[i].end());\n    }\n    forn(i, n) forn(j, n) cout << a[i][j] << \" \\n\"[j == n - 1];\n  }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1783",
    "index": "C",
    "title": "Yet Another Tournament",
    "statement": "You are participating in Yet Another Tournament. There are $n + 1$ participants: you and $n$ other opponents, numbered from $1$ to $n$.\n\nEach two participants will play against each other exactly once. If the opponent $i$ plays against the opponent $j$, he wins if and only if $i > j$.\n\nWhen the opponent $i$ plays against you, everything becomes a little bit complicated. In order to get a win against opponent $i$, you need to prepare for the match for at least $a_i$ minutes — otherwise, you lose to that opponent.\n\nYou have $m$ minutes in total to prepare for matches, but you can prepare for only one match at one moment. In other words, if you want to win against opponents $p_1, p_2, \\dots, p_k$, you need to spend $a_{p_1} + a_{p_2} + \\dots + a_{p_k}$ minutes for preparation — and if this number is greater than $m$, you cannot achieve a win against all of these opponents at the same time.\n\nThe final place of each contestant is equal to the number of contestants with strictly more wins $+$ $1$. For example, if $3$ contestants have $5$ wins each, $1$ contestant has $3$ wins and $2$ contestants have $1$ win each, then the first $3$ participants will get the $1$-st place, the fourth one gets the $4$-th place and two last ones get the $5$-th place.\n\nCalculate the minimum possible place (lower is better) you can achieve if you can't prepare for the matches more than $m$ minutes in total.",
    "tutorial": "Suppose, at the end, you won $x$ matches, what can be your final place? Look at each opponent $i$ with $i < x$ ($0$-indexed). Since the $i$-th opponent ($0$-indexed) won $i$ games against the other opponents, even if they win against you, they'll gain $i + 1 \\le x$ wins in total and can't affect your place (since your place is decided by only opponents who won strictly more matches than you). From the other side, let's look at each opponent $i$ with $i > x$ ($0$-indexed). Even if they lose to you, they still have $i > x$ wins (you have only $x$), so all of them have strictly more wins than you. As a result, there is only one opponent $i = x$, whose match against you can affect your final place: if you won against them, your place will be $n - x$, otherwise your place will be $n - x + 1$. Now, let's compare your possible places if you win $x$ games with places for winning only $x - 1$ games: $x$ wins gives you places $n - x$ or $n - x + 1$, while winning $x - 1$ leads you to places $n - x + 1$ or $n - x + 2$ that objectively worse. In other words, it's always optimal to win as many matches as possible. How to win the most number of games? It's to choose the easiest opponents. Let's sort array $a$ and find the maximum prefix $[0, x)$ with $a_0 + a_1 + \\dots + a_{x-1} \\le m$. So, we found maximum number of games $x$ we can win. The last is to check: can we get place $n - x$, or only $n - x + 1$. If $a_x$ contains among $x$ smallest values, then we'll take place $n - x$. Otherwise, let's try to \"insert\" $a_x$ in this set, i. e. let's erase the biggest among them and insert $a_x$. If the sum is still lower or equal to $m$, it's success and we get place $n - x$. Otherwise, our place is $n - x + 1$. The total complexity is $O(n \\log{n})$ because of sorting.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n);\n    for (auto &x : a) cin >> x;\n    auto b = a;\n    sort(b.begin(), b.end());\n    int ans = 0;\n    for (int i = 0; i < n && b[i] <= m; ++i) {\n      m -= b[i];\n      ++ans;\n    }\n    if (ans != 0 && ans != n && m + b[ans - 1] >= a[ans]) ++ans;\n    cout << n + 1 - ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1783",
    "index": "D",
    "title": "Different Arrays",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nYou \\textbf{have to} perform the sequence of $n-2$ operations on this array:\n\n- during the first operation, you either add $a_2$ to $a_1$ and subtract $a_2$ from $a_3$, or add $a_2$ to $a_3$ and subtract $a_2$ from $a_1$;\n- during the second operation, you either add $a_3$ to $a_2$ and subtract $a_3$ from $a_4$, or add $a_3$ to $a_4$ and subtract $a_3$ from $a_2$;\n- ...\n- during the last operation, you either add $a_{n-1}$ to $a_{n-2}$ and subtract $a_{n-1}$ from $a_n$, or add $a_{n-1}$ to $a_n$ and subtract $a_{n-1}$ from $a_{n-2}$.\n\nSo, during the $i$-th operation, you add the value of $a_{i+1}$ to one of its neighbors, and subtract it from the other neighbor.\n\nFor example, if you have the array $[1, 2, 3, 4, 5]$, one of the possible sequences of operations is:\n\n- subtract $2$ from $a_3$ and add it to $a_1$, so the array becomes $[3, 2, 1, 4, 5]$;\n- subtract $1$ from $a_2$ and add it to $a_4$, so the array becomes $[3, 1, 1, 5, 5]$;\n- subtract $5$ from $a_3$ and add it to $a_5$, so the array becomes $[3, 1, -4, 5, 10]$.\n\nSo, the resulting array is $[3, 1, -4, 5, 10]$.\n\nAn array is reachable if it can be obtained by performing the aforementioned sequence of operations on $a$. You have to calculate the number of reachable arrays, and print it modulo $998244353$.",
    "tutorial": "One of the key observations to this problem is that, after the first $i$ operations, the first $i$ elements of the array are fixed and cannot be changed afterwards. Also, after the $i$-th operation, the elements on positions from $i+3$ to $n$ are the same as they were before applying the operations. This allows us to write the following dynamic programming: $dp_{i, x, y}$ - the number of different prefixes our array can have, if we have performed $i$ operations, the $(i+1)$-th element is $x$, and the $(i+2)$-th element is $y$. The elements after $i+2$ are the same as in the original array, and the elements before $i+1$ won't be changed anymore, so we are interested only in these two elements. Let's analyze the transitions in this dynamic programming. We apply the operation $i+1$ to the elements $a_{i+1}$, $a_{i+2}$ and $a_{i+3}$. If we add $a_{i+2}$ to $a_{i+1}$, then we subtract it from $a_{i+3}$, so we transition into state $dp_{i+1, y, a_{i+3}-y}$. Otherwise, we transition into state $dp_{i+1, y, a_{i+3}+y}$. The element we leave behind is either $x-y$ or $x+y$, and if $y \\ne 0$, these two transitions give us different prefixes. But if $y=0$, we need to make only one of these transitions, because adding or subtracting $0$ actually makes no difference. Okay, now we've got a solution with dynamic programming in $O(n^3 A^2)$, where $n$ is up to $300$ and $A$ is up to $300$. This is too slow. But we can notice that the value of $a_{i+1}$ actually does not affect our transitions at all; we can just discard it, so our dynamic programming becomes $O(n^2 A)$, which easily fits into TL. Small implementation note: elements can become negative, and in order to store dynamic programming with negative states in an array, we need to do something about that. I don't recommend using maps (neither ordered nor unordered): you either get an extra log factor, or make your solution susceptible to hacking. Instead, let's say that the value of $dp_{i, y}$, where $y$ can be a negative number, will be stored as $dp[i][y + M]$ in the array, where $M$ is some constant which is greater than the maximum possible $|y|$ (for example, $10^5$ in this problem). That way, all array indices will be non-negative. Solution complexity: $O(n^2 A)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}   \n\nconst int ZERO = 100000;\n\nint dp[2][ZERO * 2];\n\nvoid recalc(int x)\n{\n    for(int i = 0; i < ZERO * 2; i++)\n        dp[1][i] = 0;\n\n    for(int i = 0; i < ZERO * 2; i++)\n    {\n        if(dp[0][i] == 0) continue;\n        int nx = x + i;\n        dp[1][nx] = add(dp[1][nx], dp[0][i]);\n        if(nx != ZERO)\n            dp[1][2 * ZERO - nx] = add(dp[1][2 * ZERO - nx], dp[0][i]);\n    }\n\n    for(int i = 0; i < ZERO * 2; i++)\n        dp[0][i] = dp[1][i];\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for(int i = 0; i < n; i++)\n        cin >> a[i];\n    dp[0][ZERO] = 1;\n    for(int i = 1; i + 1 < n; i++)\n        recalc(a[i]);\n    int ans = 0;\n    for(int i = 0; i < ZERO * 2; i++)\n        ans = add(ans, dp[0][i]);\n    cout << ans << endl;\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1783",
    "index": "E",
    "title": "Game of the Year",
    "statement": "Monocarp and Polycarp are playing a computer game. This game features $n$ bosses for the playing to kill, numbered from $1$ to $n$.\n\nThey will fight \\textbf{each} boss the following way:\n\n- Monocarp makes $k$ attempts to kill the boss;\n- Polycarp makes $k$ attempts to kill the boss;\n- Monocarp makes $k$ attempts to kill the boss;\n- Polycarp makes $k$ attempts to kill the boss;\n- ...\n\nMonocarp kills the $i$-th boss on \\textbf{his} $a_i$-th attempt. Polycarp kills the $i$-th boss on \\textbf{his} $b_i$-th attempt. After one of them kills the $i$-th boss, they move on to the $(i+1)$-st boss. The attempt counters reset for both of them. Once one of them kills the $n$-th boss, the game ends.\n\nFind all values of $k$ from $1$ to $n$ such that Monocarp kills \\textbf{all bosses}.",
    "tutorial": "Consider some value of $k$. When is it included in the answer? When Monocarp spends a lower or an equal amount of \"blocks\" of attempts than Polycarp for killing every boss. Formally, $\\lceil \\frac{a_i}{k} \\rceil \\le \\lceil \\frac{b_i}{k} \\rceil$ for all $i$ from $1$ to $n$. Let's reverse this condition. $k$ is not in the answer if there exists such $i$ from $1$ to $n$ that $\\lceil \\frac{b_i}{k} \\rceil < \\lceil \\frac{a_i}{k} \\rceil$. So, there exists at least one value between $\\lceil \\frac{b_i}{k} \\rceil$ and $\\lceil \\frac{a_i}{k} \\rceil$. Let's call it $x$. Now it's $\\lceil \\frac{b_i}{k} \\rceil < x \\le \\lceil \\frac{a_i}{k} \\rceil$. I set the $\\le$ and $<$ signs arbitrarily, just so that it shows that such a value exists. You can't put both $\\le$ or both $<$, because that will accept $0$ values or at least $2$ values, respectively. Would be cool if we could multiply everything by $k$ and it still worked. Is it completely impossible, though? Take a look at $b_i < xk \\le a_i$. What it says is that there exists a multiple of $k$ between $b_i$ and $a_i$. A multiple of $k$ is a number that's the last in each \"block\" of attempts (the block of value that are rounded up the same). Turns out, this is what we are looking for already. Right after the multiple of $k$, the new block starts. Thus, we are wrong we our signs. It should be $b_i \\le xk < a_i$ - $a_i$ is in the block after $b_i$, so it requires more blocks of attempts. So for $k$ to not be included in the answer, there should exist at least one $i$ such that there exists a multiple of $k$ in the half-interval $[b_i; a_i)$. That is pretty easy to implement. For each $x$, calculate the number of half-intervals that cover $x$. I think this is called delta-encoding. Iterate over all half-intervals and make two updates for each one: increment by $1$ on position $b_i$ and decrement by $1$ on position $a_i$. Then make a prefix sum over these updates. Now the value in the $x$-th position tells you the number of half-intervals that cover $x$. To check a particular value of $k$, iterate over all multiples of $k$ and check that none are covered by half-intervals. It's known that the total number of multiples over all numbers from $1$ to $n$ is $n + \\frac{n}{2} + \\frac{n}{3} + \\dots + \\frac{n}{n} = O(n \\log n)$. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--){\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tvector<int> a(n), b(n);\n\t\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\tforn(i, n) scanf(\"%d\", &b[i]);\n\t\tvector<int> dx(n + 1);\n\t\tforn(i, n) if (b[i] < a[i]){\n\t\t\t++dx[b[i]];\n\t\t\t--dx[a[i]];\n\t\t}\n\t\tforn(i, n) dx[i + 1] += dx[i];\n\t\tvector<int> ans;\n\t\tfor (int k = 1; k <= n; ++k){\n\t\t\tbool ok = true;\n\t\t\tfor (int nk = k; nk <= n; nk += k)\n\t\t\t\tok &= dx[nk] == 0;\n\t\t\tif (ok)\n\t\t\t\tans.push_back(k);\n\t\t}\n\t\tprintf(\"%d\\n\", int(ans.size()));\n\t\tfor (int k : ans) printf(\"%d \", k);\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1783",
    "index": "F",
    "title": "Double Sort II",
    "statement": "You are given two permutations $a$ and $b$, both of size $n$. A permutation of size $n$ is an array of $n$ elements, where each integer from $1$ to $n$ appears exactly once. The elements in each permutation are indexed from $1$ to $n$.\n\nYou can perform the following operation any number of times:\n\n- choose an integer $i$ from $1$ to $n$;\n- let $x$ be the integer such that $a_x = i$. Swap $a_i$ with $a_x$;\n- let $y$ be the integer such that $b_y = i$. Swap $b_i$ with $b_y$.\n\nYour goal is to make both permutations \\textbf{sorted in ascending order} (i. e. the conditions $a_1 < a_2 < \\dots < a_n$ and $b_1 < b_2 < \\dots < b_n$ must be satisfied) using \\textbf{minimum number of operations}. Note that both permutations must be sorted after you perform the sequence of operations you have chosen.",
    "tutorial": "The solution to this problem uses cyclic decomposition of permutations. A cyclic decomposition of a permutation is formulated as follows: you treat a permutation as a directed graph on $n$ vertices, where each vertex $i$ has an outgoing arc $i \\rightarrow p_i$. This graph consists of several cycles, and the properties of this graph can be helpful when solving permutation-based problems. First of all, how does the cyclic decomposition of a sorted permutation look? Every vertex belongs to its own cycle formed by a self-loop going from that vertex to itself. We will try to bring the cyclic decompositions of the given permutations to this form. What does an operation with integer $i$ do to the cyclic decomposition of the permutation? If $i$ is in its own separate cycle, the operation does nothing ($p_i = i$, so we swap an element with itself). Otherwise, let's suppose that $x$ is the element before $i$ in the same cycle ($p_x = i$), and $y$ is the element after $i$ in the same cycle ($p_i = y$). Note that this can be the same element. When we apply an operation on $i$, we swap $p_x$ with $p_i$, so after the operation, $p_i = i$, and $p_x = y$. So, $i$ leaves the cycle and forms its separate cycle, and $y$ becomes the next vertex in the cycle after $x$. So, using the operation, we exclude the vertex $i$ from the cycle. Suppose we want to sort one permutation. Then each cycle having length $\\ge 2$ must be broken down: for a cycle of length $c$, we need to exclude $c-1$ vertices from it to break it down. The vertex we don't touch can be any vertex from the cycle, and all other vertices from the cycle will be extracted using one operation directed at them. It's easy to see now that if we want to sort a permutation, we don't need to apply the same operation twice, and the order of operations does not matter. Okay, then what about sorting two permutations in parallel? Let's change the problem a bit: instead of calculating the minimum number of operations, we will try to maximize the number of integers $i$ such that we don't perform operations with them. So, an integer $i$ can be left untouched if it is the only untouched vertex in its cycles in both permutations... Can you see where this is going? Suppose we want to leave the vertex $i$ untouched. It means that in its cycles in both permutations, every other vertex has to be extracted with an operation. So, if two cycles from different permutations have a vertex in common, we can leave this vertex untouched, as long as there are no other vertices left untouched in both of these cycles. Let's build a bipartite graph, where each vertex in the left part represents a cycle in the first permutation, and each vertex in the right part represents a cycle in the second permutation. We will treat each integer $i$ as an edge between two respective vertices in the bipartite graph. If the edge corresponding to $i$ is \"used\" ($i$ is left untouched), we cannot \"use\" any edges incident to the same vertex in left or right part. So, maximizing the number of untouched numbers is actually the same as finding the maximum matching in this bipartite graph. After you find the maximum matching, restoring the actual answer is easy. Remember that the edges saturated by the matching correspond to the integers we don't touch with our operations, the order of operations does not matter, and each integer has to be used in an operation only once. So, the actual answer is the set of all integers without those which correspond to the edges from the matching. This solution runs in $O(n^2)$ even with a straightforward implementation of bipartite matching, since the bipartite graph has at most $O(n)$ vertices and $O(n)$ edges.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5043;\n\nvector<int> g[N];\nint mt[N];\nint u[N];\nvector<vector<int>> cycle[2];\nvector<int> a[2];\nint n;\nint vs[2];\nvector<vector<int>> inter;\n\nbool kuhn(int x)\n{\n    if(u[x]) return false;\n    u[x] = true;\n    for(auto y : g[x])\n    {\n        if(mt[y] == x) continue;\n        if(mt[y] == -1 || kuhn(mt[y]))\n        {\n            mt[y] = x;\n            return true;\n        }\n    }\n    return false;\n}\n\nint find_intersection(const vector<int>& x, const vector<int>& y)\n{\n    for(auto i : x)\n        for(auto j : y)\n            if(i == j)\n                return i;\n    return -1;\n}\n\nint main()\n{\n    scanf(\"%d\", &n);\n    for(int k = 0; k < 2; k++)\n    {\n        a[k].resize(n);\n        for(int j = 0; j < n; j++)\n        {\n            scanf(\"%d\", &a[k][j]);\n            a[k][j]--;\n        }    \n    }\n\n    for(int k = 0; k < 2; k++)\n    {\n        vector<bool> used(n);\n        for(int i = 0; i < n; i++)\n        {\n            if(used[i]) continue;\n            vector<int> cur;\n            int j = i;\n            while(!used[j])\n            {\n                cur.push_back(j);\n                used[j] = true;\n                j = a[k][j];            \n            }\n            cycle[k].push_back(cur);\n        }\n        vs[k] = cycle[k].size();\n    }\n\n    inter.resize(vs[0], vector<int>(vs[1]));\n\n    for(int i = 0; i < vs[0]; i++)\n        for(int j = 0; j < vs[1]; j++)\n        {\n            inter[i][j] = find_intersection(cycle[0][i], cycle[1][j]);\n            if(inter[i][j] != -1)\n                g[i].push_back(j);\n        }\n\n    for(int i = 0; i < vs[1]; i++)\n        mt[i] = -1;\n    for(int i = 0; i < vs[0]; i++)\n    {\n        for(int j = 0; j < vs[0]; j++)\n            u[j] = false;\n        kuhn(i);\n    }\n    \n    set<int> res;\n    for(int i = 0; i < n; i++) res.insert(i);\n    for(int i = 0; i < vs[1]; i++)\n        if(mt[i] != -1)\n            res.erase(inter[mt[i]][i]);\n\n    printf(\"%d\\n\", res.size());\n    for(auto x : res) printf(\"%d \", x + 1);\n    puts(\"\");\n}",
    "tags": [
      "dfs and similar",
      "flows",
      "graph matchings",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1783",
    "index": "G",
    "title": "Weighed Tree Radius",
    "statement": "You are given a tree of $n$ vertices and $n - 1$ edges. The $i$-th vertex has an initial weight $a_i$.\n\nLet the distance $d_v(u)$ from vertex $v$ to vertex $u$ be the number of edges on the path from $v$ to $u$. Note that $d_v(u) = d_u(v)$ and $d_v(v) = 0$.\n\nLet the weighted distance $w_v(u)$ from $v$ to $u$ be $w_v(u) = d_v(u) + a_u$. Note that $w_v(v) = a_v$ and $w_v(u) \\neq w_u(v)$ if $a_u \\neq a_v$.\n\nAnalogically to usual distance, let's define the eccentricity $e(v)$ of vertex $v$ as the greatest weighted distance from $v$ to any other vertex (including $v$ itself), or $e(v) = \\max\\limits_{1 \\le u \\le n}{w_v(u)}$.\n\nFinally, let's define the radius $r$ of the tree as the minimum eccentricity of any vertex, or $r = \\min\\limits_{1 \\le v \\le n}{e(v)}$.\n\nYou need to perform $m$ queries of the following form:\n\n- $v_j$ $x_j$ — assign $a_{v_j} = x_j$.\n\nAfter performing each query, print the radius $r$ of the current tree.",
    "tutorial": "Firstly, let's define the weight of path $(u, v)$ as $w_p(u, v) = a_u + d_u(v) + a_v$. On contrary to weighted distances, $w_p(u, v) = w_p(v, u)$ and also $w_p(v, v) = 2 a_v$. Now, let's define the diameter of a tree as path $(u, v)$ with maximum $w_p(u, v)$. It's okay if diameter may be explicit case $(v, v)$. The useful part of such definition is next: our diameter still holds most properties of the usual diameter. Let's look at two of them: There is a vertex on diameter path $(x, y)$ with $w_v(x) = \\left\\lceil \\frac{w_p(x, y)}{2} \\right\\rceil$ and $w_v(y) = w_p(x, y) - w_v(x)$. It's easy to prove after noting the fact that $a_x \\le d_x(y) + a_y$ and $a_y \\le d_y(x) + a_x$ (otherwise, you could choose diameter $(x, x)$ or $(y, y)$). For any vertex $v$ eccentricity $e(v) = \\max(w_v(x), w_v(y))$. In other words, either $x$ or $y$ has the maximum distance from $v$. (You can also prove it by contradiction). It also means that $e(v) \\ge \\left\\lceil \\frac{w_p(x, y)}{2} \\right\\rceil$. Now let's look how the diameter changes when we change the weight $a_v$. If $a_v$ is increasing it's quite easy. The only paths that change weights are the paths ending at $v$. Denote such path as $(v, u)$ and note that either $v = u$ or $w_p(v, u) = a_v + w_v(u) \\le a_v + e(v)$ $=$ $a_v + \\max(w_v(x), w_v(y))$. In other words, there will be only three candidates for a new diameter: path $(v, v)$ with $w_p(v, v) = 2 a_v$; path $(v, x)$ with $w_p(v, x) = a_v + d_v(x) + a_x$; path $(v, y)$ with $w_p(v, y) = a_v + d_v(y) + a_y$. The only thing you need to calculate fast enough is the two distances $d_v(x)$ and $d_v(y)$. And since $d_v(x) = depth(v) + depth(x) - 2 \\cdot depth(lca(v, x))$, your task is to calculate $lca$. Finally, how to handle decreasing $a_v$'s? Let's get rid of them using DCP (dynamic connectivity problem) technique. Keep track of each value $a_v$: each possible value $a_v$ for some vertex $v$ will be \"active\" on some segment of queries $[l, r) \\in [0, m)$. Since there are only $m$ queries, there will be exactly $n + m$ such segments for all vertices $v$ in total. Now, all queries becomes \"assign $a_v = x$ on some segment of queries $[l, r)$\". Note that in that case, the previous value of $a_v$ was $0$, so you are dealing with only \"increasing value\" queries. Finally, to handle all range queries efficiently, you build a Segment Tree on queries, set all queries and then traverse your Segment Tree while maintaining the current diameter in order to calculate answers for all queries. Each of $n + m$ queries transforms in $O(\\log{m})$ queries to segment tree vertices, and preforming each query asks you to calculate $lca$ two times. If you use the usual binary lifting, then your complexity becomes $O((n + m) \\log{m} \\log{n})$ what is okay. But if you use Sparse Table on Euler tour, you can take $lca$ in $O(1)$ and your complexity will be $O(n \\log{n} + (n + m) \\log{m})$.",
    "code": "\n#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \" \";\n\t\tout << v[i];\n\t}\n\treturn out;\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nconst int LOG = 18;\nconst int N = int(2e5) + 55;\n\nint n;\nvector<int> a;\nvector<int> g[N];\n\ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> a[i];\n\tfore (i, 0, n - 1) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tu--, v--;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\treturn true;\n}\n\nstruct Lca {\n\tvector<int> log2, tin;\n\tvector< vector<int> > hs;\n\tint T = 0;\n\n\tvoid dfs(int v, int p, int cdepth) {\n\t\ttin[v] = T++;\n\t\ths[0][tin[v]] = cdepth;\n\t\tfor (int to : g[v]) {\n\t\t\tif (to == p)\n\t\t\t\tcontinue;\n\t\t\tdfs(to, v, cdepth + 1);\n\t\t\ths[0][T++] = cdepth;\n\t\t}\n\t}\n\n\tvoid init() {\n\t\tlog2.assign(2 * n, 0);\n\t\tfore (i, 2, sz(log2))\n\t\t\tlog2[i] = log2[i / 2] + 1;\n\t\ths.assign(log2.back() + 1, vector<int>(2 * n, INF));\n\n\t\ttin.assign(n, 0);\n\t\tT = 0;\n\n\t\tdfs(0, -1, 0);\n\t\tassert(T < 2 * n);\n\n\t\tfore (pw, 0, sz(hs) - 1) {\n\t\t\tfore (i, 0, T - (1 << pw))\n\t\t\t\ths[pw + 1][i] = min(hs[pw][i], hs[pw][i + (1 << pw)]);\n\t\t}\n\t}\n\n\tint getMin(int u, int v) {\n\t\tif (tin[u] > tin[v])\n\t\t\tswap(u, v);\n\t\tint len = log2[tin[v] + 1 - tin[u]];\n\t\tint d = min(hs[len][tin[u]], hs[len][tin[v] + 1 - (1 << len)]);\n//\t\tcerr << u << \" \" << v << \": \" << d << endl;\n\t\treturn d;\n\t}\n\tinline int getH(int v) {\n\t\treturn hs[0][tin[v]];\n\t}\n} lcaST;\n\nint getFarthest(int s) {\n\tvector<int> used(n, 0);\n\tqueue<int> q;\n\n\tused[s] = 1;\n\tq.push(s);\n\tint v;\n\twhile (!q.empty()) {\n\t\tv = q.front(); \n\t\tq.pop();\n\t\tfor (int to : g[v]) {\n\t\t\tif (used[to])\n\t\t\t\tcontinue;\n\t\t\tused[to] = 1;\n\t\t\tq.push(to);\n\t\t}\n\t}\n\treturn v;\n}\n\nint getDist(int u, int v) {\n\treturn lcaST.getH(u) + lcaST.getH(v) - 2 * lcaST.getMin(u, v);\n}\n\nconst int M = int(2e5);\nvector<pt> ops[4 * M];\n\nvoid setOp(int v, int l, int r, int lf, int rg, const pt &op) {\n\tif (l >= r || lf >= rg) return;\n\tif (l == lf && r == rg) {\n\t\tops[v].push_back(op);\n\t\treturn;\n\t}\n\tint mid = (l + r) / 2;\n\tif (lf < mid)\n\t\tsetOp(2 * v + 1, l, mid, lf, min(mid, rg), op);\n\tif (rg > mid)\n\t\tsetOp(2 * v + 2, mid, r, max(lf, mid), rg, op);\n}\n\nvoid updDiam(int &s, int &t, int &curD, const pt &op) {\n\tint v = op.x;\n\ta[v] = op.y;\n\n\tint ns = s, nt = t, nD = curD;\n\n\tvector<pt> cds = {{s, v}, {v, t}, {v, v}};\n\tfor (auto &c : cds) {\n\t\tint d1 = getDist(c.x, c.y);\n\t\tif (nD < a[c.x] + d1 + a[c.y]) {\n\t\t\tnD = a[c.x] + d1 + a[c.y];\n\t\t\tns = c.x, nt = c.y;\n\t\t}\n\t}\n\ts = ns;\n\tt = nt;\n\tcurD = nD;\n}\n\nvector<int> ans;\n\nvoid calcDiams(int v, int l, int r, int s, int t, int curD) {\n\tfor (auto &op : ops[v])\n\t\tupdDiam(s, t, curD, op);\n\tif (r - l > 1) {\n\t\tint mid = (l + r) / 2;\n\t\tcalcDiams(2 * v + 1, l, mid, s, t, curD);\n\t\tcalcDiams(2 * v + 2, mid, r, s, t, curD);\n\t}\n\telse\n\t\tans[l] = (curD + 1) / 2;\n\t\n\tfor (auto &op : ops[v])\n\t\ta[op.first] = 0;\n}\n\ninline void solve() {\n\tlcaST.init();\n\tint s = getFarthest(0);\n\tint t = getFarthest(s);\n\n\tint m;\n\tcin >> m;\n\tvector<int> lst(n, 0);\n\tfore (i, 0, m) {\n\t\tint v, x;\n\t\tcin >> v >> x;\n\t\tv--;\n\n\t\tsetOp(0, 0, m, lst[v], i, {v, a[v]});\n\t\tlst[v] = i;\n\t\ta[v] = x;\n\t}\n\tfore (v, 0, n)\n\t\tsetOp(0, 0, m, lst[v], m, {v, a[v]});\n\n\tans.resize(m, -1);\n\ta.assign(n, 0);\n\tcalcDiams(0, 0, m, s, t, getDist(s, t));\n\n\tfore (i, 0, m)\n\t\tcout << ans[i] << '\\n';\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "data structures",
      "divide and conquer",
      "implementation",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1784",
    "index": "A",
    "title": "Monsters (easy version)",
    "statement": "{This is the easy version of the problem. In this version, you only need to find the answer once. In this version, hacks are \\textbf{not allowed}.}\n\nIn a computer game, you are fighting against $n$ monsters. Monster number $i$ has $a_i$ health points, all $a_i$ are integers. A monster is alive while it has at least $1$ health point.\n\nYou can cast spells of two types:\n\n- Deal $1$ damage to any single alive monster of your choice.\n- Deal $1$ damage to all alive monsters. If at least one monster dies (ends up with $0$ health points) as a result of this action, then repeat it (and keep repeating while at least one monster dies every time).\n\nDealing $1$ damage to a monster reduces its health by $1$.\n\nSpells of type 1 can be cast any number of times, while a spell of type 2 can be cast at most once during the game.\n\nWhat is the smallest number of times you need to cast spells of type 1 to kill all monsters?",
    "tutorial": "First, let's prove that it's always optimal to use a spell of type 2 as your last spell in the game and kill all monsters with it. Indeed, suppose you use a spell of type 2 earlier and it deals $x$ damage to all monsters. Suppose that some monsters are still alive. For any such monster, say they had $y$ health points before the spell of type 2, and $y > x$. Then, you will need to cast $y-x$ more spells of type 1 to kill it afterwards. But you could just cast these $y-x$ spells of type 1 on this monster before casting the spell of type 2. Thus, you can move all usages of spells of type 1 before the usage of the spell of type 2 without changing the answer. Without loss of generality, assume that $a_1 \\le a_2 \\le \\ldots \\le a_n$. Let $b_i$ be the amount of health points monster $i$ has right before the spell of type 2 is cast ($1 \\le b_i \\le a_i$). Then, the number of spells of type 1 needed is $\\sum \\limits_{i=1}^n (a_i - b_i)$, which means we want to maximize $\\sum \\limits_{i=1}^n b_i$. Note that we can rearrange $b$ so that $b_1 \\le b_2 \\le \\ldots \\le b_n$: since $a$ is sorted too, the $b_i \\le a_i$ condition will still hold. Also, since all monsters must be killed by a spell of type 2 afterwards, $b_{i+1} - b_i \\le 1$ must hold. Thus, we should go through all monsters in non-decreasing order of $a_i$ and decide their $b_i$ greedily, picking the largest value satisfying both $b_i \\le a_i$ and $b_i \\le b_{i-1} + 1$. Specifically, we should choose $b_1 = 1$ and $b_i = \\min(a_i, b_{i-1} + 1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n      cin >> a[i];\n    }\n    sort(a.begin(), a.end());\n    vector<int> b(n);\n    b[0] = 1;\n    for (int i = 1; i < n; i++) {\n      b[i] = min(b[i - 1] + 1, a[i]);\n    }\n    long long ans = 0;\n    for (int i = 0; i < n; i++) {\n      ans += a[i] - b[i];\n    }\n    cout << ans << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1784",
    "index": "B",
    "title": "Letter Exchange",
    "statement": "A cooperative game is played by $m$ people. In the game, there are $3m$ sheets of paper: $m$ sheets with letter 'w', $m$ sheets with letter 'i', and $m$ sheets with letter 'n'.\n\nInitially, each person is given three sheets (possibly with equal letters).\n\nThe goal of the game is to allow each of the $m$ people to spell the word \"win\" using their sheets of paper. In other words, everyone should have one sheet with letter 'w', one sheet with letter 'i', and one sheet with letter 'n'.\n\nTo achieve the goal, people can make exchanges. Two people participate in each exchange. Both of them choose exactly one sheet of paper from the three sheets they own and exchange it with each other.\n\nFind the shortest sequence of exchanges after which everyone has one 'w', one 'i', and one 'n'.",
    "tutorial": "For each person, there are three essential cases of what they could initially have: Three distinct letters: \"win\". No need to take part in any exchanges. Two equal letters and another letter, e.g. \"wii\". An extra 'i' must be exchanged with someone's 'n'. Three equal letters, e.g. \"www\". One 'w' must be exchanged with someone's 'i', another 'w' must be exchanged with someone's 'n'. Let's create a graph on three vertices: 'w', 'i', 'n'. Whenever person $i$ has an extra letter $x$ and is lacking letter $y$, create a directed edge $x \\rightarrow y$ marked with $i$. Once the graph is built, whenever you have a cycle of length $2$, that is, $x \\xrightarrow{i} y \\xrightarrow{j} x$, it means person $i$ needs to exchange $x$ for $y$, while person $j$ needs to exchange $y$ for $x$. Thus, both of their needs can be satisfied with just one exchange. Finally, once there are no cycles of length $2$, note that the in-degree and the out-degree of every vertex are equal. If e.g. there are $p$ edges 'w' $\\rightarrow$ 'i', it follows that there are $p$ edges 'i' $\\rightarrow$ 'n' and $p$ edges 'n' $\\rightarrow$ 'w'. It means we can form $p$ cycles of length $3$. (The cycles could also go in the opposite direction: 'w' $\\rightarrow$ 'n' $\\rightarrow$ 'i' $\\rightarrow$ 'w'.) In any case, each cycle of length $3$ can be solved using $2$ exchanges.",
    "code": "private fun IntArray.countOf(value: Int) = count { it == value }\n\nprivate fun solve() {\n    val s = \"win\"\n    fun IntArray.bad() = (0 until 3).singleOrNull { c -> count { it == c } > 1 }\n    val data = List(readInt()) { readLn().map { s.indexOf(it) }.toIntArray() }\n    val ans = mutableListOf<String>()\n    fun exchange(c1: Int, c2: Int, i1: Int, i2: Int) {\n        ans.add(\"$$${i1+1} $$${s[c1]} $$${i2+1} $$${s[c2]}\")\n        val index1 = data[i1].indexOf(c1)\n        val index2 = data[i2].indexOf(c2)\n        data[i1][index1] = c2\n        data[i2][index2] = c1\n    }\n    val todo = List(3) { List(3) { mutableListOf<Int> () } }\n    for (i in data.indices) {\n        val bad = data[i].bad() ?: continue\n        for (j in 0 until 3) {\n            if (data[i].countOf(j) == 0) {\n                todo[bad][j].add(i)\n            }\n        }\n    }\n\n    for (i in 0 until 3) {\n        for (j in 0 until 3) {\n            if (i != j) {\n                while (todo[i][j].isNotEmpty() && todo[j][i].isNotEmpty()) {\n                    exchange(i, j, todo[i][j].removeLast(), todo[j][i].removeLast())\n                }\n            }\n        }\n    }\n    while (todo[0][1].isNotEmpty() && todo[1][2].isNotEmpty() && todo[2][0].isNotEmpty()) {\n        val a = todo[0][1].removeLast()\n        val b = todo[1][2].removeLast()\n        val c = todo[2][0].removeLast()\n        exchange(0, 1, a, b)\n        exchange(0, 2, b, c)\n    }\n    while (todo[1][0].isNotEmpty() && todo[2][1].isNotEmpty() && todo[0][2].isNotEmpty()) {\n        val a = todo[1][0].removeLast()\n        val b = todo[2][1].removeLast()\n        val c = todo[0][2].removeLast()\n        exchange(1, 0, a, c)\n        exchange(2, 1, b, c)\n    }\n    println(ans.size)\n    println(ans.joinToString(\"\\n\"))\n}\n\nfun main() {\n    repeat(readInt()) {\n        solve()\n    }\n}\n\nprivate fun readLn() = readLine()!!\nprivate fun readInt() = readLn().toInt()",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1784",
    "index": "C",
    "title": "Monsters (hard version)",
    "statement": "This is the hard version of the problem. In this version, you need to find the answer for every prefix of the monster array.\n\nIn a computer game, you are fighting against $n$ monsters. Monster number $i$ has $a_i$ health points, all $a_i$ are integers. A monster is alive while it has at least $1$ health point.\n\nYou can cast spells of two types:\n\n- Deal $1$ damage to any single alive monster of your choice.\n- Deal $1$ damage to all alive monsters. If at least one monster dies (ends up with $0$ health points) as a result of this action, then repeat it (and keep repeating while at least one monster dies every time).\n\nDealing $1$ damage to a monster reduces its health by $1$.\n\nSpells of type 1 can be cast any number of times, while a spell of type 2 can be cast at most once during the game.\n\nFor every $k = 1, 2, \\ldots, n$, answer the following question. Suppose that only the first $k$ monsters, with numbers $1, 2, \\ldots, k$, are present in the game. What is the smallest number of times you need to cast spells of type 1 to kill all $k$ monsters?",
    "tutorial": "Continuing on the solution to the easy version: now we have a set of integers $A$, we need to add elements into $A$ one by one and maintain the answer to the problem. Recall that for every $i$, either $b_i = b_{i-1}$ or $b_i = b_{i-1} + 1$. Note that $b_i = b_{i-1}$ can only happen when $b_i = a_i$. Let's call such an element useless. If we remove a useless element, the answer does not change. If there are no useless elements, we have $b_1 = 1$ and $b_i = b_{i-1} + 1$ for $i > 1$: that is, $b_i = i$. Thus, the answer to the problem can be easily calculated as $\\sum \\limits_{i=1}^m (a_i - b_i) = \\sum \\limits_{i=1}^m a_i - \\frac{m(m+1)}{2}$, where $m$ is the current size of the set. We can formulate the condition \"there are no useless elements\" as follows. For any $x$, let $k_x$ be the number of elements in $A$ not exceeding $x$. Then, $k_x \\le x$. On the other hand, suppose that for some $x$, we have $k_x > x$. Let's find the smallest such $x$. Then, we can see that $A$ contains a useless element equal to $x$, and we can safely remove it. We can check this condition after adding each new element to $A$ using a segment tree. In every cell $x$ of the array maintained by the segment tree, we will store the difference $x - k_x$. Initially, cell $x$ contains value $x$. When a new element $v$ appears, we should subtract $1$ from all cells in range $[v; n]$. Then, if a cell with a negative value appears (that is, $x - k_x < 0$, which is equivalent to $k_x > x$), we should find the leftmost such cell $x$ and remove an element equal to $x$. In particular, we should add $1$ to all cells in range $[x; n]$. Thus, we can use a segment tree with \"range add\" and \"global min\". At most one useless element can appear every time we enlarge $A$, and if that happens, we can identify and remove it in $O(\\log n)$, resulting in an $O(n \\log n)$ time complexity.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n      cin >> a[i];\n    }\n    vector<int> mn(2 * n - 1);\n    vector<int> add(2 * n - 1, 0);\n    vector<int> pos(2 * n - 1);\n    auto Pull = [&](int x, int z) {\n      mn[x] = min(mn[x + 1], mn[z]) + add[x];\n      pos[x] = (mn[x + 1] <= mn[z] ? pos[x + 1] : pos[z]);\n    };\n    function<void(int, int, int, int, int, int)> Modify = [&](int x, int l, int r, int ll, int rr, int v) {\n      if (ll <= l && r <= rr) {\n        mn[x] += v;\n        add[x] += v;\n        return;\n      }\n      int y = (l + r) >> 1;\n      int z = x + 2 * (y - l + 1);\n      if (ll <= y) {\n        Modify(x + 1, l, y, ll, rr, v);\n      }\n      if (rr > y) {\n        Modify(z, y + 1, r, ll, rr, v);\n      }\n      Pull(x, z);\n    };\n    function<void(int, int, int)> Build = [&](int x, int l, int r) {\n      if (l == r) {\n        mn[x] = l;\n        pos[x] = l;\n        return;\n      }\n      int y = (l + r) >> 1;\n      int z = x + 2 * (y - l + 1);\n      Build(x + 1, l, y);\n      Build(z, y + 1, r);\n      Pull(x, z);\n    };\n    Build(0, 1, n);\n    long long s = 0;\n    long long m = 0;\n    for (int i = 0; i < n; i++) {\n      s += a[i];\n      m += 1;\n      Modify(0, 1, n, a[i], n, -1);\n      if (mn[0] < 0) {\n        s -= pos[0];\n        m -= 1;\n        Modify(0, 1, n, pos[0], n, +1);\n      }\n      cout << s - m * (m + 1) / 2 << \" \\n\"[i == n - 1];\n    }\n  }\n  return 0;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1784",
    "index": "D",
    "title": "Wooden Spoon",
    "statement": "$2^n$ people, numbered with distinct integers from $1$ to $2^n$, are playing in a single elimination tournament. The bracket of the tournament is a full binary tree of height $n$ with $2^n$ leaves.\n\nWhen two players meet each other in a match, a player with the \\textbf{smaller} number always wins. The winner of the tournament is the player who wins all $n$ their matches.\n\nA virtual consolation prize \"Wooden Spoon\" is awarded to a player who satisfies the following $n$ conditions:\n\n- they lost their first match;\n- the player who beat them lost their second match;\n- the player who beat that player lost their third match;\n- $\\ldots$;\n- the player who beat the player from the previous condition lost the final match of the tournament.\n\nIt can be shown that there is always exactly one player who satisfies these conditions.\n\nConsider all possible $(2^n)!$ arrangements of players into the tournament bracket. For each player, find the number of these arrangements in which they will be awarded the \"Wooden Spoon\", and print these numbers modulo $998\\,244\\,353$.",
    "tutorial": "Let's focus on the sequence of players beating each other $1 = a_0 < a_1 < \\ldots < a_n$: $a_0$ is the tournament champion, $a_0$ beats $a_1$ in the last match, $a_1$ beats $a_2$ in the second-to-last match, $\\ldots$, $a_{n-1}$ beats $a_n$ in the first match. For a fixed such sequence, how many ways are there to fill the tournament bracket? Let's look at the sequence in reverse. There are $2^n$ ways to put player $a_n$ somewhere. Player $a_{n-1}$ has to be the opponent of player $a_n$ in the first match. Player $a_{n-2}$ has to beat some player $b > a_{n-2}$ in the first match, and then beat $a_{n-1}$ in the second match. There are $2^n - a_{n-2} - 2$ ways to choose player $b$ (since it can not be equal to $a_{n-1}$ and $a_n$), and there are also $2$ ways to order $a_{n-2}$ and $b$. Player $a_{n-3}$ has to be the winner of a subbracket containing $3$ other players $c_1, c_2, c_3 > a_{n-3}$, and then beat $a_{n-2}$ in the third match. There are $2^n - a_{n-3} - 4$ players to choose $c_i$ from (since they can not be equal to $a_{n-2}$, $a_{n-1}$, $a_n$, and $b$), and there are $\\binom{2^n - a_{n-3} - 4}{3}$ ways to do so, and there are also $4!$ ways to order $a_{n-3}$, $c_1$, $c_2$, and $c_3$. In general, player $a_{n - i}$ has to be the winner of a subbracket containing $2^{i-1} - 1$ other players, and there are $2^n - a_{n-i} - 2^{i-1}$ players to choose from, and there are $\\binom{2^n - a_{n-i} - 2^{i-1}}{2^{i-1} - 1}$ ways to choose, and also $(2^{i-1})!$ ways to order this subbracket. You can see that the total number of brackets for a fixed sequence $1 = a_0 < a_1 < \\ldots < a_n$ can be represented as $f(a_0, 0) \\cdot f(a_1, 1) \\cdot \\ldots \\cdot f(a_{n-1}, n-1) \\cdot f(a_n, n)$, where $f(a_i, i)$ is some function of a player number and a round number. Now let's use dynamic programming: let $d(a_i, i)$ be the sum of products of $f(a_0, 0) \\cdot f(a_1, 1) \\cdot \\ldots \\cdot f(a_i, i)$ over all sequences $1 = a_0 < a_1 < \\ldots < a_i$. Then: $d(1, 0) = f(1, 0)$; $d(a_0, 0) = 0$ for $a_0 > 1$; $d(a_i, i) = f(a_i, i) \\cdot \\sum \\limits_{a_{i-1}=1}^{a_i-1} d(a_{i-1}, i-1)$ for $i > 0$. The answer for player $x$ is $d(x, n)$. This DP has $O(n \\cdot 2^n)$ states, and note that the inner sums in the formulas for $d(a_i, i)$ and $d(a_i + 1, i)$ only differ by one summand. Thus, by using cumulative sums for transitions, we can achieve an $O(n \\cdot 2^n)$ time complexity.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <typename T>\nT inverse(T a, T m) {\n  T u = 0, v = 1;\n  while (a != 0) {\n    T t = m / a;\n    m -= t * a; swap(a, m);\n    u -= t * v; swap(u, v);\n  }\n  assert(m == 1);\n  return u;\n}\n\ntemplate <typename T>\nclass Modular {\n public:\n  using Type = typename decay<decltype(T::value)>::type;\n\n  constexpr Modular() : value() {}\n  template <typename U>\n  Modular(const U& x) {\n    value = normalize(x);\n  }\n\n  template <typename U>\n  static Type normalize(const U& x) {\n    Type v;\n    if (-mod() <= x && x < mod()) v = static_cast<Type>(x);\n    else v = static_cast<Type>(x % mod());\n    if (v < 0) v += mod();\n    return v;\n  }\n\n  const Type& operator()() const { return value; }\n  template <typename U>\n  explicit operator U() const { return static_cast<U>(value); }\n  constexpr static Type mod() { return T::value; }\n\n  Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; }\n  Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); }\n\n  template <typename U = T>\n  typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) {\n    value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));\n    return *this;\n  }\n\n private:\n  Type value;\n};\n\ntemplate <typename T> Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }\ntemplate <typename T, typename U> Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; }\ntemplate <typename T, typename U> Modular<T> operator*(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }\ntemplate <typename T, typename U> Modular<T> operator/(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }\n\nconstexpr int md = 998244353;\nusing Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;\n\nvector<Mint> fact(1, 1);\nvector<Mint> inv_fact(1, 1);\n\nMint C(int n, int k) {\n  if (k < 0 || k > n) {\n    return 0;\n  }\n  while ((int) fact.size() < n + 1) {\n    fact.push_back(fact.back() * (int) fact.size());\n    inv_fact.push_back(1 / fact.back());\n  }\n  return fact[n] * inv_fact[k] * inv_fact[n - k];\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n;\n  cin >> n;\n  C(1 << n, 0);\n  vector<Mint> dp(1 << n);\n  dp[0] = (1 << n) * fact[1 << (n - 1)];\n  for (int rd = n - 2; rd >= 0; rd--) {\n    vector<Mint> new_dp(1 << n);\n    Mint sum = 0;\n    for (int i = 0; i < (1 << n); i++) {\n      new_dp[i] = sum * C((1 << n) - 1 - i - (1 << rd), (1 << rd) - 1) * fact[1 << rd];\n      sum += dp[i];\n    }\n    swap(dp, new_dp);\n  }\n  Mint sum = 0;\n  for (int i = 0; i < (1 << n); i++) {\n    cout << sum() << '\\n';\n    sum += dp[i];\n  }\n  return 0;\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1784",
    "index": "E",
    "title": "Infinite Game",
    "statement": "Alice and Bob are playing an infinite game consisting of sets. Each set consists of rounds. In each round, one of the players wins. The first player to win two rounds in a set wins this set. Thus, a set always ends with the score of $2:0$ or $2:1$ in favor of one of the players.\n\nLet's call a game scenario a finite string $s$ consisting of characters 'a' and 'b'. Consider an infinite string formed with repetitions of string $s$: $sss \\ldots$ Suppose that Alice and Bob play rounds according to this infinite string, left to right. If a character of the string $sss \\ldots$ is 'a', then Alice wins the round; if it's 'b', Bob wins the round. As soon as one of the players wins two rounds, the set ends in their favor, and a new set starts from the next round.\n\nLet's define $a_i$ as the number of sets won by Alice among the first $i$ sets while playing according to the given scenario. Let's also define $r$ as the limit of ratio $\\frac{a_i}{i}$ as $i \\rightarrow \\infty$. If $r > \\frac{1}{2}$, we'll say that scenario $s$ is winning for Alice. If $r = \\frac{1}{2}$, we'll say that scenario $s$ is tied. If $r < \\frac{1}{2}$, we'll say that scenario $s$ is winning for Bob.\n\nYou are given a string $s$ consisting of characters 'a', 'b', and '?'. Consider all possible ways of replacing every '?' with 'a' or 'b' to obtain a string consisting only of characters 'a' and 'b'. Count how many of them result in a scenario winning for Alice, how many result in a tied scenario, and how many result in a scenario winning for Bob. Print these three numbers modulo $998\\,244\\,353$.",
    "tutorial": "For a fixed game scenario $s$, let's build a weighted functional graph on $4$ vertices that correspond to set scores $0:0$, $1:0$, $0:1$, and $1:1$. For each score $x$, traverse the scenario from left to right, changing the score after each letter, and starting a new set whenever necessary. If the set score by the end of the scenario is $y$, add a directed edge from $x$ to $y$. The weight of this edge is the number of sets Alice wins during the process, minus the number of sets Bob wins. When we have built such a graph for a game scenario $s$, we can easily decide whether $s$ is winning for Alice, tied, or winning for Bob. Starting from vertex $0:0$, move by the outgoing edges until you arrive at a cycle. In the cycle, find the sum the edge weights. If the sum is positive, the scenario is winning for Alice; if the sum is $0$, the scenario is tied; if the sum is negative, the scenario is winning for Bob. Now we can use dynamic programming. Let $f(i, \\{u_0, u_1, u_2, u_3\\}, \\{w_0, w_1, w_2, w_3\\})$ be the number of ways to choose $s_1 s_2 \\ldots s_i$ so that edges from vertices $0, 1, 2, 3$ go to vertices $u_0, u_1, u_2, u_3$ and have weights $w_0, w_1, w_2, w_3$, respectively. Even though this DP has $O(n^5)$ states, it might be possible to get this solution accepted if you only visit reachable states and optimize your solution's constant factor. However, here's an idea that drastically improves the time complexity. Note that in the end, we are only interested in the sum of some $w_j$, and not in every value separately. Outside of our DP, let's fix the mask of vertices that will lie on the cycle reachable from $0:0$. In the DP state, we can just store the sum $s$ of $w_j$ over $j$ belonging to this mask: $f(i, \\{u_0, u_1, u_2, u_3\\}, s)$. In the end, we will look at the values of $u_0, u_1, u_2, u_3$ and check if the cycle in our graph is indeed the one we want; only if that's true, we will add the DP value to the overall answer. This way, at the cost of running the DP $2^4$ times, we have cut the number of states to $O(n^2)$. The overall time complexity of this solution is $O(n^2)$ too, although the constant factor is huge.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <typename T>\nclass Modular {\n public:\n  using Type = typename decay<decltype(T::value)>::type;\n\n  constexpr Modular() : value() {}\n  template <typename U>\n  Modular(const U& x) {\n    value = normalize(x);\n  }\n\n  template <typename U>\n  static Type normalize(const U& x) {\n    Type v;\n    if (-mod() <= x && x < mod()) v = static_cast<Type>(x);\n    else v = static_cast<Type>(x % mod());\n    if (v < 0) v += mod();\n    return v;\n  }\n\n  const Type& operator()() const { return value; }\n  template <typename U>\n  explicit operator U() const { return static_cast<U>(value); }\n  constexpr static Type mod() { return T::value; }\n\n  Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; }\n  template <typename U> Modular& operator+=(const U& other) { return *this += Modular(other); }\n\n  template <typename U>\n  friend bool operator==(const Modular<U>& lhs, const Modular<U>& rhs);\n\n private:\n  Type value;\n};\n\ntemplate <typename T> bool operator==(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value == rhs.value; }\ntemplate <typename T, typename U> bool operator==(const Modular<T>& lhs, U rhs) { return lhs == Modular<T>(rhs); }\n\nconstexpr int md = 998244353;\nusing Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  string s;\n  cin >> s;\n  int len = (int) s.size();\n  vector<Mint> ans(3);\n  for (int use = 1; use < (1 << 4); use++) {\n    int pw = 1 << 8;\n    int init = 0;\n    for (int i = 0; i < 4; i++) {\n      init += i << (2 * i);\n    }\n    vector<vector<int>> go_state(pw, vector<int>(2));\n    vector<vector<int>> go_diff(pw, vector<int>(2));\n    for (int state = 0; state < pw; state++) {\n      for (int put = 0; put < 2; put++) {\n        int new_diff = 0;\n        int new_state = 0;\n        for (int i = 0; i < 4; i++) {\n          int to = (state >> (2 * i)) & 3;\n          if (put == 0) {\n            if (to & 1) {\n              if (use & (1 << i)) {\n                new_diff += 1;\n              }\n              to = 0;\n            } else {\n              to |= 1;\n            }\n          } else {\n            if (to & 2) {\n              if (use & (1 << i)) {\n                new_diff -= 1;\n              }\n              to = 0;\n            } else {\n              to |= 2;\n            }\n          }\n          new_state += to << (2 * i);\n        }\n        go_state[state][put] = new_state;\n        go_diff[state][put] = new_diff;\n      }\n    }\n    int limit = (len + 1) / 2 * 2 * __builtin_popcount(use);\n    vector<vector<Mint>> dp(2 * limit + 1, vector<Mint>(pw));\n    dp[limit][init] = 1;\n    for (char c : s) {\n      vector<vector<Mint>> new_dp(2 * limit + 1, vector<Mint>(pw));\n      for (int sum = 0; sum < (int) dp.size(); sum++) {\n        for (int state = 0; state < pw; state++) {\n          if (dp[sum][state] == 0) {\n            continue;\n          }\n          for (int put = 0; put < 2; put++) {\n            if ((put == 0 && c == 'b') || (put == 1 && c == 'a')) {\n              continue;\n            }\n            int new_sum = sum + go_diff[state][put];\n            int new_state = go_state[state][put];\n            new_dp[new_sum][new_state] += dp[sum][state];\n          }\n        }\n      }\n      swap(dp, new_dp);\n    }\n    for (int sum = 0; sum < (int) dp.size(); sum++) {\n      for (int state = 0; state < pw; state++) {\n        if (dp[sum][state] == 0) {\n          continue;\n        }\n        vector<int> to(4);\n        for (int i = 0; i < 4; i++) {\n          to[i] = (state >> (2 * i)) & 3;\n        }\n        vector<int> seq(1, 0);\n        while (true) {\n          int nxt = to[seq.back()];\n          bool done = false;\n          for (int i = 0; i < (int) seq.size(); i++) {\n            if (seq[i] == nxt) {\n              done = true;\n              seq.erase(seq.begin(), seq.begin() + i);\n              break;\n            }\n          }\n          if (done) {\n            break;\n          }\n          seq.push_back(nxt);\n        }\n        int real_use = 0;\n        for (int x : seq) {\n          real_use |= (1 << x);\n        }\n        if (use == real_use) {\n          ans[sum > limit ? 0 : (sum < limit ? 2 : 1)] += dp[sum][state];\n        }\n      }\n    }\n  }\n  for (int i = 0; i < 3; i++) {\n    cout << ans[i]() << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "games",
      "probabilities"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1784",
    "index": "F",
    "title": "Minimums or Medians",
    "statement": "Vika has a set of all consecutive positive integers from $1$ to $2n$, inclusive.\n\nExactly $k$ times Vika will choose and perform one of the following two actions:\n\n- take two smallest integers from her current set and remove them;\n- take two median integers from her current set and remove them.\n\nRecall that medians are the integers located exactly in the middle of the set if you write down its elements in increasing order. Note that Vika's set always has an even size, thus the pair of median integers is uniquely defined. For example, two median integers of the set $\\{1, 5, 6, 10, 15, 16, 18, 23\\}$ are $10$ and $15$.\n\nHow many different sets can Vika obtain in the end, after $k$ actions? Print this number modulo $998\\,244\\,353$. Two sets are considered different if some integer belongs to one of them but not to the other.",
    "tutorial": "Let's denote removing minimums with L, and removing medians with M. Now a sequence of Vika's actions can be described with a string $s$ of length $k$ consisting of characters L and M. Observe that if we have a substring LMM, we can replace it with MLM, and the set of removed numbers will not change. We can keep applying this transformation until there are no LMM substrings in $s$. Now, a string $s$ of our interest looks as a concatenation of: $p$ letters M, for some $0 \\le p \\le k$; if $p < k$, then a letter L; $\\max(0, k - 1 - p)$ letters L and M, without two letters M in a row. Let's denote the number of letters M in part 3 above as $q$. Can different strings still lead to equal sets in the end? First, let's suppose that $k \\le \\frac{n - 1}{2}$. We will prove that all strings that match the above pattern result in distinct integer sets. Part 1 in the above concatenation means that integers from $n-p+1$ to $n+p$ are removed. Since there are $k-p-q$ letters L in $s$ in total, integers from $1$ to $2(k-p-q)$ are removed too. However, integers in the range $[2(k-p-q) + 1; n-p]$ are not removed, and note that $2(k-p-q)+1 \\le n-p$ is equivalent to $k \\le \\frac{n+p+2q-1}{2}$. Hence, this range is never empty when $k \\le \\frac{n - 1}{2}$. Thus, we can see that for all pairs of $p$ and $q$, the leftmost non-removed ranges are distinct. Now, also note that in part 3 of the concatenation, any letter M always removes some two consecutive integers (since there is no substring MM), and letters L serve as \"shifts\" for these removals, and different sets of \"shifts\" result in different final sets of integers. This finishes the proof. It is easy to find the number of ways to fill part 3 for fixed $p$ and $q$: there are $\\binom{(k - 1 - p) - (q - 1)}{q}$ ways to choose $q$ positions out of $(k - 1 - p)$ so that no two consecutive positions are chosen. Now we have just iterate over all valid pairs of $p$ and $q$ to get an $O(n^2)$ solution for the $k \\le \\frac{n - 1}{2}$ case. Before optimizing it to $O(n)$, let's get back to the $k > \\frac{n - 1}{2}$ case. Some strings can result in the same final set. Let $x$ be the smallest integer in the final set. Note that $x$ is always odd. We will only look for a string that contains $\\frac{x - 1}{2}$ letters L: that is, a string that removes integers from $1$ to $x-1$ only via removing minimums. We can see that there is always a unique such string. Recall the uniqueness proof for $k \\le \\frac{n - 1}{2}$. When $p > 0$, we will now force that leftmost non-removed range, $[2(k-p-q) + 1; n-p]$, to be non-empty. If the range is empty, our sequence of actions does not satisfy the condition from the previous paragraph, so we can skip this pair of $p$ and $q$. When $p = 0$, things are a bit different. Suppose we have fixed $q$. It means there are $k-q$ letters L in the string. These operations remove integers from $1$ to $2(k-q)$. Thus, we need the first letter M to remove integers strictly greater than $2(k-q)+1$, which gives us a lower bound on the number of letters L at the start of the string. Otherwise, we can use the same binomial coefficient formula for counting. This should finish the $O(n^2)$ solution for any $k$. To optimize it, let's iterate over $q$ first and iterate over $p$ inside. It turns out that all valid values of $p$ form a range, and if we look at what we are summing up, it is $\\binom{0}{q} + \\binom{1}{q} + \\ldots + \\binom{r}{q}$ for some integer $r$. This sum is equal to $\\binom{r+1}{q+1}$ by the hockey-stick identity. Thus, we finally have an $O(n)$ solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate <typename T>\nT inverse(T a, T m) {\n  T u = 0, v = 1;\n  while (a != 0) {\n    T t = m / a;\n    m -= t * a; swap(a, m);\n    u -= t * v; swap(u, v);\n  }\n  assert(m == 1);\n  return u;\n}\n\ntemplate <typename T>\nclass Modular {\n public:\n  using Type = typename decay<decltype(T::value)>::type;\n\n  constexpr Modular() : value() {}\n  template <typename U>\n  Modular(const U& x) {\n    value = normalize(x);\n  }\n\n  template <typename U>\n  static Type normalize(const U& x) {\n    Type v;\n    if (-mod() <= x && x < mod()) v = static_cast<Type>(x);\n    else v = static_cast<Type>(x % mod());\n    if (v < 0) v += mod();\n    return v;\n  }\n\n  const Type& operator()() const { return value; }\n  template <typename U>\n  explicit operator U() const { return static_cast<U>(value); }\n  constexpr static Type mod() { return T::value; }\n\n  Modular& operator+=(const Modular& other) { if ((value += other.value) >= mod()) value -= mod(); return *this; }\n  Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); }\n\n  template <typename U = T>\n  typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) {\n    value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));\n    return *this;\n  }\n\n private:\n  Type value;\n};\n\ntemplate <typename T, typename U> Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; }\ntemplate <typename T, typename U> Modular<T> operator/(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }\n\nconstexpr int md = 998244353;\nusing Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;\n\nvector<Mint> fact(1, 1);\nvector<Mint> inv_fact(1, 1);\n\nMint C(int n, int k) {\n  if (k < 0 || k > n) {\n    return 0;\n  }\n  while ((int) fact.size() < n + 1) {\n    fact.push_back(fact.back() * (int) fact.size());\n    inv_fact.push_back(1 / fact.back());\n  }\n  return fact[n] * inv_fact[k] * inv_fact[n - k];\n}\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n, k;\n  cin >> n >> k;\n  Mint ans = 1;\n  for (int q = 0; q <= k - 1; q++) {\n    int bound = k - q - max(1, 2 * (k - q) - n + 1);\n    ans += C(bound + 1, q + 1);\n  }\n  for (int q = 1; q <= k - 1; q++) {\n    int pos = 2 * (k - q) + 2;\n    int shifts = max(1, pos - n);\n    int left = k - shifts;\n    ans += C(left - (q - 1), q);\n  }\n  cout << ans() << '\\n';\n  return 0;\n}",
    "tags": [],
    "rating": 3400
  },
  {
    "contest_id": "1786",
    "index": "A2",
    "title": "Alternating Deck (hard version)",
    "statement": "This is a hard version of the problem. In this version, there are two colors of the cards.\n\nAlice has $n$ cards, each card is either black or white. The cards are stacked in a deck in such a way that the card colors alternate, starting from a white card. Alice deals the cards to herself and to Bob, dealing at once several cards from the top of the deck in the following order: one card to herself, two cards to Bob, three cards to Bob, four cards to herself, five cards to herself, six cards to Bob, seven cards to Bob, eight cards to herself, and so on. In other words, on the $i$-th step, Alice deals $i$ top cards from the deck to one of the players; on the first step, she deals the cards to herself and then alternates the players every two steps. When there aren't enough cards at some step, Alice deals all the remaining cards to the current player, and the process stops.\n\n\\begin{center}\n{\\small First Alice's steps in a deck of many cards.}\n\\end{center}\n\nHow many cards of each color will Alice and Bob have at the end?",
    "tutorial": "Note that on the $i$-th step, Alice takes $i$ cards from the deck. It means that after $k$ steps, $\\frac{k(k + 1)}{2}$ steps are taken from the deck. Thus, after $O(\\sqrt{n})$ steps, the deck is empty. We can simulate the steps one by one by taking care of whose turn it is and what is the color of the top card. Using this information, we can keep track of how many cards of what color each player has. Print this information in the end.",
    "code": "NT = int(input())\n \nfor T in range(NT):\n\tn = int(input())\n\tanswer = [0, 0, 0, 0]\n\tfirst_card = 1\n\tfor it in range(1, 20000):\n\t\twho = 0 if it % 4 == 1 or it % 4 == 0 else 1\n\t\tcnt = it\n\t\tif n < cnt:\n\t\t\tcnt = n\n\t\tcnt_white = (cnt + first_card % 2) // 2\n\t\tcnt_black = cnt - cnt_white\n\t\tanswer[who * 2 + 0] += cnt_white\n\t\tanswer[who * 2 + 1] += cnt_black\n\t\tfirst_card += cnt\n\t\tn -= cnt\n\t\tif n == 0:\n\t\t\tbreak\n\tassert(n == 0)\n\tprint(*answer)\n ",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1786",
    "index": "B",
    "title": "Cake Assembly Line",
    "statement": "A cake assembly line in a bakery was once again optimized, and now $n$ cakes are made at a time! In the last step, each of the $n$ cakes should be covered with chocolate.\n\nConsider a side view on the conveyor belt, let it be a number line. The $i$-th cake occupies the segment $[a_i - w, a_i + w]$ on this line, each pair of these segments does not have common points. Above the conveyor, there are $n$ dispensers, and when a common button is pressed, chocolate from the $i$-th dispenser will cover the conveyor segment $[b_i - h, b_i + h]$. Each pair of these segments also does not have common points.\n\n\\begin{center}\n{\\small Cakes and dispensers corresponding to the first example.}\n\\end{center}\n\nThe calibration of this conveyor belt part has not yet been performed, so you are to make it. Determine if it's possible to shift the conveyor so that each cake has some chocolate on it, and there is no chocolate outside the cakes. You can assume that the conveyour is long enough, so the cakes never fall. Also note that the button can only be pressed once.\n\n\\begin{center}\n{\\small In the first example we can shift the cakes as shown in the picture.}\n\\end{center}",
    "tutorial": "Obviously, the $i$-th cake should be below the $i$-th dispenser. The leftmost possible position of the cake is when the chocolate would touch the right border. If $c_i$ is the new position of the cake's center, then in this case $c_i + w = b_i + h$. The rightmost possible position is, similarly, when $c_i - w = b_i - h$. Thus, the new position of the center should be between $b_i + h - w$ and $b_i - h + w$. This means that the $i$-th cake should be shifted by any length between $(b_i + h - w) - a_i$ and $(b_i - h + w) - a_i$. Since all cakes on the conveyor move at the same time, the shift $p$ should satisfy $(b_i + h - w) - a_i \\le p \\le (b_i - h + w) - a_i$ for all $i$ at the same time. This is possible if and only if a value $p$ exists such that $\\max_i (b_i + h - w - a_i) \\le p \\le \\min_i (b_i - h + w - a_i),$ $\\max_i (b_i + h - w - a_i) \\le \\min_i (b_i - h + w - a_i),$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int inf = 1000000000;\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n, w, h;\n    cin >> n >> w >> h;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n      cin >> a[i];\n    }\n    vector<int> b(n);\n    for (int i = 0; i < n; i++) {\n      cin >> b[i];\n    }\n    int minshift = -inf;\n    int maxshift = inf;\n    for (int i = 0; i < n; i++) {\n      minshift = max(minshift, (b[i] + h) - (a[i] + w));\n      maxshift = min(maxshift, (b[i] - h) - (a[i] - w));\n    }\n    if (minshift <= maxshift) {\n      cout << \"YES\" << '\\n';\n    } else {\n      cout << \"NO\" << '\\n';\n    }\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1787",
    "index": "A",
    "title": "Exponential Equation",
    "statement": "You are given an integer $n$.\n\nFind any pair of integers $(x,y)$ ($1\\leq x,y\\leq n$) such that $x^y\\cdot y+y^x\\cdot x = n$.",
    "tutorial": "For even $n$, a key observation is that $x=1,y=\\dfrac{n}{2}$ is always legit. And for odd $n$, notice that $x^yy+y^xx=xy(x^{y-1}+y^{x-1})$. So if $x$ or $y$ is an even number, obviously $x^y y+y^x x$ is an even number. Otherwise if both $x$ and $y$ are all odd numbers , $x^{y-1}$ and $y^{x-1}$ are all odd numbers, so $x^{y-1}+y^{x-1}$ is an even number, and $x^yy+y^xx$ is also an even number. That means $x^yy+y^xx$ is always even and there's no solution for odd $n$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1787",
    "index": "B",
    "title": "Number Factorization",
    "statement": "Given an integer $n$.\n\nConsider all pairs of integer arrays $a$ and $p$ of the same length such that $n = \\prod a_i^{p_i}$ (i.e. $a_1^{p_1}\\cdot a_2^{p_2}\\cdot\\ldots$) ($a_i>1;p_i>0$) and $a_i$ is the product of some (possibly one) \\textbf{distinct} prime numbers.\n\nFor example, for $n = 28 = 2^2\\cdot 7^1 = 4^1 \\cdot 7^1$ the array pair $a = [2, 7]$, $p = [2, 1]$ is correct, but the pair of arrays $a = [4, 7]$, $p = [1, 1]$ is not, because $4=2^2$ is a product of non-distinct prime numbers.\n\nYour task is to find the maximum value of $\\sum a_i \\cdot p_i$ (i.e. $a_1\\cdot p_1 + a_2\\cdot p_2 + \\ldots$) over all possible pairs of arrays $a$ and $p$. Note that you do not need to minimize or maximize the length of the arrays.",
    "tutorial": "First, $a_i^{p_i}$ is equivalent to the product of $a_i^{1}$ for $p$ times, so it is sufficient to set all $p_i$ to $1$. Decomposite $n$ to some prime factors, greedily choose the most number of distinct prime numbers, the product is the maximum.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define mp make_pair\npair<int, int> s[110];\nint d[110];\nvoid get() {\n\tint n, l = 0, i, c;\n\tcin >> n;\n\tfor (i = 2; i * i <= n; i++) {\n\t\tif (n % i == 0) {\n\t\t\tc = 0;\n\t\t\twhile (n % i == 0) c++, n /= i;\n\t\t\ts[++l] = make_pair(c, i);\n\t\t}\n\t}\n\tif (n != 1) s[++l] = make_pair(1, n);\n\tsort(s + 1, s + l + 1), d[l + 1] = 1;\n\tfor (i = l; i >= 1; i--) d[i] = d[i + 1] * s[i].second;\n\tint ans = 0;\n\tfor (i = 1; i <= l; i++) if (s[i].first != s[i - 1].first) ans += d[i] * (s[i].first - s[i - 1].first);\n\tcout << ans << endl;\n}\nsigned main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tint T;\n\tcin >> T;\n\twhile (T--) get();\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1787",
    "index": "C",
    "title": "Remove the Bracket",
    "statement": "RSJ has a sequence $a$ of $n$ integers $a_1,a_2, \\ldots, a_n$ and an integer $s$. For each of $a_2,a_3, \\ldots, a_{n-1}$, he chose a pair of \\textbf{non-negative integers} $x_i$ and $y_i$ such that $x_i+y_i=a_i$ and $(x_i-s) \\cdot (y_i-s) \\geq 0$.\n\nNow he is interested in the value $$F = a_1 \\cdot x_2+y_2 \\cdot x_3+y_3 \\cdot x_4 + \\ldots + y_{n - 2} \\cdot x_{n-1}+y_{n-1} \\cdot a_n.$$\n\nPlease help him find the minimum possible value $F$ he can get by choosing $x_i$ and $y_i$ optimally. It can be shown that there is always at least one valid way to choose them.",
    "tutorial": "Idea & Solution: rsj This is the reason why the problem was named as Remove the Bracket. $\\begin{aligned} \\text{Product} &= a_1 \\cdot a_2 \\cdot a_3 \\cdot \\ldots \\cdot a_n = \\\\ &= a_1 \\cdot (x_2+y_2) \\cdot (x_3+y_3) \\cdot \\ldots \\cdot (x_{n-1}+y_{n-1}) \\cdot a_n = \\\\ &\\overset{\\text{?}}{=} a_1 \\cdot x_2+y_2 \\cdot x_3+y_3 \\cdot \\ldots \\cdot x_{n-1}+y_{n-1} \\cdot a_n. \\end{aligned}$ However, We discussed to remove it on 28th Jan in the statement. Really sorry for inconvenience of the statement!",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1787",
    "index": "C",
    "title": "Remove the Bracket",
    "statement": "RSJ has a sequence $a$ of $n$ integers $a_1,a_2, \\ldots, a_n$ and an integer $s$. For each of $a_2,a_3, \\ldots, a_{n-1}$, he chose a pair of \\textbf{non-negative integers} $x_i$ and $y_i$ such that $x_i+y_i=a_i$ and $(x_i-s) \\cdot (y_i-s) \\geq 0$.\n\nNow he is interested in the value $$F = a_1 \\cdot x_2+y_2 \\cdot x_3+y_3 \\cdot x_4 + \\ldots + y_{n - 2} \\cdot x_{n-1}+y_{n-1} \\cdot a_n.$$\n\nPlease help him find the minimum possible value $F$ he can get by choosing $x_i$ and $y_i$ optimally. It can be shown that there is always at least one valid way to choose them.",
    "tutorial": "$(x_i-s)(y_i-s)\\geq 0$ tells us either $\\min(x_i,y_i)\\geq s$ or $\\max(x_i,y_i) \\leq s$, so pickable $x_i$ is a consecutive range. Just consider $(x_i+y_i)$, remove the bracket then it turns to $\\ldots+ y_{i-1}\\cdot x_i+y_i\\cdot x_{i+1}+\\ldots$. When $y_{i-1} = x_{i+1}$, the result is constant, so we assume that $y_{i-1} < x_{i+1}$. If $x_i$ does not hit the maximum, increase $x_i$ by $1$ and decrease $y_i$ by $1$, the result will increase by $y_{i-1}$ and decrease by $x_{i+1}$, which means decrease by $x_{i+1}-y_{i-1}$, always better. So $x_i$ will either hit the maximum or the minimum. Thus, each number has only two ways of rewriting that might be optimal. This can be done with DP.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 200005;\nlong long f[N][2],x[N],y[N];\nvoid get() {\n\tint i,n,s,j;\n\tcin>>n>>s;\n\tfor(i=1; i<=n; i++) {\n\t\tcin>>j;\n\t\tif(i==1||i==n) x[i]=y[i]=j;\n\t\telse if(j<=s) x[i]=0,y[i]=j;\n\t\telse x[i]=s,y[i]=j-s;\n\t}\n\tf[1][0]=f[1][1]=0;\n\tfor(i=2; i<=n; i++) {\n\t\tf[i][0]=min(f[i-1][0]+y[i-1]*x[i],f[i-1][1]+x[i-1]*x[i]);\n\t\tf[i][1]=min(f[i-1][0]+y[i-1]*y[i],f[i-1][1]+x[i-1]*y[i]);\n\t}\n\tcout<<f[n][0]<<endl;\n}\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tint T; cin>>T;\n\twhile(T--) get();\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1787",
    "index": "D",
    "title": "Game on Axis",
    "statement": "There are $n$ points $1,2,\\ldots,n$, each point $i$ has a number $a_i$ on it. You're playing a game on them. Initially, you are at point $1$. When you are at point $i$, take following steps:\n\n- If $1\\le i\\le n$, go to $i+a_i$,\n- Otherwise, the game ends.\n\nBefore the game begins, you can choose two integers $x$ and $y$ satisfying $1\\le x\\le n$, $-n \\le y \\le n$ and replace $a_x$ with $y$ (set $a_x := y$). Find the number of distinct pairs $(x,y)$ such that the game that you start after making the change ends in a finite number of steps.\n\nNotice that you do not have to satisfy $a_x\\not=y$.",
    "tutorial": "First, add directed edges from $i$ to $i+a_i$. If there's a path from $1$ to $x$ satisfying $x<1$ or $x>n$, the game end. We consider all nodes $x$ satisfying $x<1$ or $x>n$ to be the end node, and we call the path which starts at node $1$ until it loops or ends the key path. If we can end the game at first: Let's count the opposite: the number of invalid pairs. The graph with the end node forms a tree. Changing edges not on the key path is always legal. If changing the edges on the key path, for node $x$, we can only change its successor to other connected components, its precursor or itself on the tree with the end node. For the answer, use dfs to count the number of precursors for every nodes on this tree, which is the size of subtree. If we cannot end the game at first: We can only change the edge on the key path, redirect them to any nodes on the tree with the end node.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 200005;\nint a[N];\nint v[N]; //= 1 -> in the tree with the end node\nint s[N]; //subtree size\nstruct E {\n\tint to;\n\tE *nex;\n} *h[N];\nvoid add(int u, int v) {\n\tE *cur = new E;\n\tcur->to = v, cur->nex = h[u], h[u] = cur;\n}\nvoid dfs(int u) {\n\ts[u] = v[u] = 1;\n\tfor (E *cur = h[u]; cur; cur = cur->nex)\n\t\tdfs(cur->to), s[u] += s[cur->to];\n}\nvoid get() {\n\tint i, j, n;\n\tcin >> n;\n\tfor (i = 1; i <= n + 1; i++)\n\t\ts[i] = v[i] = 0, h[i] = 0;\n\tfor (i = 1; i <= n; i++) {\n\t\tcin >> a[i], a[i] = min(i + a[i], n + 1);\n\t\tif (a[i] <= 0) a[i] = n + 1;\n\t\tadd(a[i], i);\n\t}\n\tdfs(n + 1); //start with the end point, dfs the tree\n\tlong long ans = 0;\n\tif (v[1] == 1) {\n\t\tj = 1; do { ans -= s[j] + (n - s[n + 1] + 1), j = a[j]; }\n\t\twhile (j != n + 1);\n\t\tans += 1ll * n * (2 * n + 1);\n\t} else {\n\t\tj = 1; do { ans += (n + s[n + 1]), v[j] = 2, j = a[j]; }\n\t\twhile (v[j] != 2);\n\t}\n\tcout << ans << endl;\n}\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tint T;\n\tcin >> T;\n\twhile (T--) get();\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1787",
    "index": "E",
    "title": "The Harmonization of XOR",
    "statement": "You are given an array of exactly $n$ numbers $[1,2,3,\\ldots,n]$ along with integers $k$ and $x$.\n\nPartition the array in exactly $k$ non-empty disjoint subsequences such that the bitwise XOR of all numbers in each subsequence is $x$, and each number is in exactly one subsequence. Notice that there are no constraints on the length of each subsequence.\n\nA sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements.\n\nFor example, for $n = 15$, $k = 6$, $x = 7$, the following scheme is valid:\n\n- $[6,10,11]$, $6 \\oplus 10 \\oplus 11 = 7$,\n- $[5,12,14]$, $5 \\oplus 12 \\oplus 14 = 7$,\n- $[3,9,13]$, $3 \\oplus 9 \\oplus 13 = 7$,\n- $[1,2,4]$, $1 \\oplus 2 \\oplus 4 = 7$,\n- $[8,15]$, $8 \\oplus 15 = 7$,\n- $[7]$, $7 = 7$,\n\nwhere $\\oplus$ represents the bitwise XOR operation.The following scheme is invalid, since $8$, $15$ do not appear:\n\n- $[6,10,11]$, $6 \\oplus 10 \\oplus 11 = 7$,\n- $[5,12,14]$, $5 \\oplus 12 \\oplus 14 = 7$,\n- $[3,9,13]$, $3 \\oplus 9 \\oplus 13 = 7$,\n- $[1,2,4]$, $1 \\oplus 2 \\oplus 4 = 7$,\n- $[7]$, $7 = 7$.\n\nThe following scheme is invalid, since $3$ appears twice, and $1$, $2$ do not appear:\n\n- $[6,10,11]$, $6 \\oplus 10 \\oplus 11 = 7$,\n- $[5,12,14]$, $5 \\oplus 12 \\oplus 14 = 7$,\n- $[3,9,13]$, $3 \\oplus 9 \\oplus 13 = 7$,\n- $[3,4]$, $3 \\oplus 4 = 7$,\n- $[8,15]$, $8 \\oplus 15 = 7$,\n- $[7]$, $7 = 7$.",
    "tutorial": "First, we observe that three subsequences can combine into one, so we only need to care about the maximum number of subsequences. Make subsequences in the form of $[a,a \\oplus x]$ as much as possible, leave $[x]$ alone if possible, and the rest becomes a subsequence. This would be optimal. Proof: Let $B$ be the highest bit of $x$, i.e. the $B$-th bit of $x$ is on. Let $M$ be the number of numbers from $1$ to $n$ satisfying the $B$-th bit is on. Then the number of subsequences must be smaller than or equal to $M$, since there's at least one $B$-th-bit-on number in each subsequence. These $B$-th-bit-on numbers XOR $x$ must be smaller than themselves, so we can always obtain $M$ subsequences.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1787",
    "index": "F",
    "title": "Inverse Transformation",
    "statement": "A permutation scientist is studying a self-transforming permutation $a$ consisting of $n$ elements $a_1,a_2,\\ldots,a_n$.\n\nA permutation is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. For example, $[1]$, $[4, 3, 5, 1, 2]$ are permutations, while $[1, 1]$, $[4, 3, 1]$ are not.\n\nThe permutation transforms day by day. On each day, each element $x$ becomes $a_x$, that is, $a_x$ becomes $a_{a_x}$. Specifically:\n\n- on the first day, the permutation becomes $b$, where $b_x = a_{a_x}$;\n- on the second day, the permutation becomes $c$, where $c_x = b_{b_x}$;\n- $\\ldots$\n\nFor example, consider permutation $a = [2,3,1]$. On the first day, it becomes $[3,1,2]$. On the second day, it becomes $[2,3,1]$.You're given the permutation $a'$ on the $k$-th day.\n\nDefine $\\sigma(x) = a_x$, and define $f(x)$ as the minimal positive integer $m$ such that $\\sigma^m(x) = x$, where $\\sigma^m(x)$ denotes $\\underbrace{\\sigma(\\sigma(\\ldots \\sigma}_{m \\text{ times}}(x) \\ldots))$.\n\nFor example, if $a = [2,3,1]$, then $\\sigma(1) = 2$, $\\sigma^2(1) = \\sigma(\\sigma(1)) = \\sigma(2) = 3$, $\\sigma^3(1) = \\sigma(\\sigma(\\sigma(1))) = \\sigma(3) = 1$, so $f(1) = 3$. And if $a=[4,2,1,3]$, $\\sigma(2) = 2$ so $f(2) = 1$; $\\sigma(3) = 1$, $\\sigma^2(3) = 4$, $\\sigma^3(3) = 3$ so $f(3) = 3$.\n\nFind the initial permutation $a$ such that $\\sum\\limits^n_{i=1} \\dfrac{1}{f(i)}$ is \\textbf{minimum possible}.",
    "tutorial": "Consider another question: Given the initial permutation $a$ and find the permutation $a'$ on the $k$-th day? After a day, element $x$ will become $\\sigma(x) = a_x$, so we can consider the numbers as nodes, and we add directed edges from $x$ to $a_x$. Note that $a$ is a permutation, so the graph consists of several cycles. After one day, $a_x$ will become $a_{\\sigma(x)} = a_{a_x}$ - the second element after $x$ in the corresponding cycle. Similarly, we can conclude that $a_x$ will become the $2^k$-th element after $x$. If a cycle $c$ has an odd length $l$. Because $2^k \\bmod l \\neq 0$, the cycle will never split, the element $c_x$ will become $c_{(x+2^k)\\bmod l}$ on the $k$-th day. Otherwise, if a cycle $c$ has an even length $l$, after the first day, $c_1$ will become $c_3$, $c_3$ will become $c_5$, $\\ldots$, $c_{2l-1}$ will become $c_1$. And so will the even indices - that means the original cycle split into two small cycles of the same size $\\dfrac{l}{2}$. So, if a cycle of length $l = p\\cdots 2^q$ will split into $2^q$ small cycles of length $p$ after exactly $q$ days. Images illustrating how a 12-node cycle split in two days. Because the length of a cycle $l\\le n$, so we can perform the transformation for at least $\\log n$ days to split all the cycles of even lengths into cycles of odd lengths. Then we can use our conclusion to calculate the final permutation on the $k$-th day. Now let's back to our question. We observed that $\\sum\\limits^n_{i=1} \\dfrac{1}{f(i)}$ means the number of cycles in the original graph. Then we need to construct the original permutation $a$ of the least possible cycle. As we've said before, the cycle of length $l = p\\cdots 2^q$ will split into $2^q$ small cycles of length $p$ after exactly $q$ days. So we can count all the cycles in permutation $a'$. For cycles of odd length $l$, we can combine some of them. Specifically, we can combine $2^q$ cycles into a cycle of length $l\\cdots 2^q$ in the original permutation $a$. Note that $q$ must be less than or equal to $k$. And for cycles of even length $l$, we can also combine them. But because they haven't been split on the $k$-th day, we must combine exactly $2^k$ cycles. So if the number of these cycles isn't a multiple of $2^k$, just print NO.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 200005;\nint dest[N], visit[N], ans[N], mp[N], ansinv[N], sp;\nint pow2(int y, int M) {\n\tlong long x = 2, ans = 1;\n\twhile (y) {\n\t\tif (y & 1) ans = ans * x % M;\n\t\tx = x * x % M, y >>= 1;\n\t}\n\treturn ans % M;\n}\nvector<int> cyc[N];\nvoid get() {\n\tsp = 0;\n\tint n, i, j, m, z, o;\n\tcin >> n >> m;\n\tfor (i = 1; i <= n; i++) cyc[i].clear();\n\tfor (i = 1; i <= n; i++) visit[i] = 0, cin >> dest[i];\n\tfor (i = 1; i <= n; i++) {\n\t\tif (visit[i]) continue;\n\t\tj = i, z = 0; do { ++z, visit[j] = 1, j = dest[j]; } while (j != i);\n\t\tcyc[z].push_back(i);\n\t}\n\tint lim = pow2(min(m, 20), 1e9), s = 0, d, t, num, cp;\n\tfor (i = 1; i <= n; i++) {\n\t\tif (!cyc[i].size()) continue;\n\t\tint siz = cyc[i].size();\n\t\tif (i % 2 == 0 && siz % lim) {\n\t\t\tcout << \"NO\" << endl; return;\n\t\t} else {\n\t\t\tcp = -1;\n\t\t\tfor (j = lim; j > 0; j /= 2) {\n\t\t\t\twhile (siz >= j) {\n\t\t\t\t\tsiz -= j, d = s + j * i, t = j;\n\t\t\t\t\twhile (t--) {\n\t\t\t\t\t\t++s, ++cp, num = s, o = cyc[i][cp];\n\t\t\t\t\t\tdo {\n\t\t\t\t\t\t    ans[num] = o, num += pow2(m, i * j);\n\t\t\t\t\t\t    if (num > d) num -= j * i;\n\t\t\t\t\t\t    o = dest[o];\n\t\t\t\t\t\t} while (o != cyc[i][cp]);\n\t\t\t\t\t}\n\t\t\t\t\tfor (int k = sp + 1; k < sp + j * i; k++) mp[k] = k + 1;\n\t\t\t\t\tmp[sp + j * i] = sp + 1, sp += j * i, s = d;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcout << \"YES\" << endl;\n\tfor (i = 1; i <= n; i++) ansinv[ans[i]] = i;\n\tfor (i = 1; i <= n; i++) cout << ans[mp[ansinv[i]]] << \" \\n\"[i == n];\n}\nint main() {\n\tios::sync_with_stdio(0), cin.tie(0);\n\tint T;\n\tcin >> T;\n\twhile (T--) get();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1787",
    "index": "G",
    "title": "Colorful Tree Again",
    "statement": "An edge-weighted tree of $n$ nodes is given with each edge colored in some color. Each node of this tree can be blocked or unblocked, all nodes are unblocked initially.\n\nA simple path is a path in a graph that does not have repeating nodes. The length of a path is defined as the sum of weights of all edges on the path.\n\nA path is good when it is a simple path consisting of edges of the same color $c$, all edges of color $c$ are on this path, and every node on the path is unblocked.\n\nYou need to operate $2$ kinds of queries:\n\n- block a node,\n- unblock a node.\n\nAfter each query, print the maximum length among all good paths. If there are no good paths, print $0$.",
    "tutorial": "On the original tree, all good paths are constant and one edge can only be on at most one good path. For each color $c$, find all edges of color $c$, and judge if they form a simple path by counting the degree of each node on the path. If so, mark these edges and calculate the length. When a query changes a node $u$, several paths across $u$ are infected. For example, An example doodle, assume that we are destroying node $2$. If we are destroying node $2$, path $8-1-2-3$, $2-4-9$, $2-5$, and $7-6-2-10$ will not be good paths. A brute-force solution is to use a priority queue, delete length of bad paths, find the maximum length. To gain better time complexity, treat two cases of influenced paths separately: 1. Only one path that goes from the ancestor of $u$ to its subtree, like $8-1-2-3$. 2. All paths whose LCA is $u$ will be infected, like $2-4-9$, $2-5$, and $7-6-2-10$. This inspires us to maintain these paths according to their LCAs. That is, use priority queue on every node $u$ to maintain all paths whose LCA is $u$. Then use a global priority queue to maintain the answer of all paths maintained on all nodes. UPD: An alternative implementation using segment tree comment link.",
    "tags": [
      "brute force",
      "data structures",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1787",
    "index": "H",
    "title": "Codeforces Scoreboard",
    "statement": "You are participating in a Codeforces Round with $n$ problems.\n\nYou spend exactly one minute to solve each problem, the time it takes to submit a problem can be ignored. You can only solve at most one problem at any time. The contest starts at time $0$, so you can make your first submission at any time $t \\ge 1$ minutes. Whenever you submit a problem, it is always accepted.\n\nThe scoring of the $i$-th problem can be represented by three integers $k_i$, $b_i$, and $a_i$. If you solve it at time $t$ minutes, you get $\\max(b_i - k_i \\cdot t,a_i)$ points.\n\nYour task is to choose an order to solve all these $n$ problems to get the maximum possible score. You can assume the contest is long enough to solve all problems.",
    "tutorial": "Since $\\max\\{b_i-k_i\\cdot t,a_i\\} = b_i - \\min\\{k_i\\cdot t, b_i - a_i\\}$, we can pre-calculate the sum of $b_i$. Let $c_i = b_i - a_i$. Now our mission is to minimize the sum of $\\min\\{k_i\\cdot t, b_i - a_i\\}$. If we assume $\\min\\{k_i\\cdot t, b_i - a_i\\} = k_i\\cdot t$ for some $i$, sort these problems in descending order of $k_i$, then assign $1,2,3,\\ldots$ to their $t$ in order. For $\\min\\{k_i\\cdot t, b_i - a_i\\} = b_i - a_i$, they can be directly calculated. There comes a DP solution: Let $f_{i,j}$ be the minimum sum, when considering first $i$ problems (after sorting), $j$ problems of them satisfying $\\min\\{k_i\\cdot t, b_i - a_i\\} = k_i\\cdot t$. $f_{i,j}=\\left\\{ \\begin{aligned} f_{i-1,j}+c_i & & j=0 \\\\ \\min\\{f_{i-1,j}+c_i,f_{i-1,j-1}+k_i\\cdot j\\} & & j>0 \\end{aligned} \\right.$ The time complexity is $O(n^2)$. We can find that $f_{i,j}$ is convex. Proof below: Let $g_{i,j}=f_{i,j}-f_{i,j-1}$. Thus $f_{i,j}=f_{i,0}+\\sum\\limits_{k=1}^jg_{i,k}$, rewrite this formula with the original recursive formula. Then $f_{i,0}+\\sum_{k=1}^{j}g_{i,k}=\\min\\{f_{i-1,0},\\sum_{k=1}^{j}g_{i-1,k}+c_i,f_{i-1,0}+\\sum_{k=1}^{j-1}g_{i-1,k}+k_i\\cdot j\\}$ $c_i+\\sum_{k=1}^{j}g_{i,k}=\\sum_{k=1}^{j-1}g_{i-1,k}+\\min\\{g_{i-1,j}+c_i,k_i\\cdot j\\}$ $c_i+\\sum_{k=1}^{j-1}g_{i,k}=\\sum_{k=1}^{j-2}g_{i-1,k}+\\min\\{g_{i-1,j-1}+c_i,k_i\\cdot (j-1)\\}$ $g_{i,j}=g_{i-1,j-1}+\\min\\{g_{i-1,j}+c_i,k_i\\cdot j\\}-\\min\\{g_{i-1,j-1}+c_i,k_i\\cdot (j-1)\\}$ Because $k$ is monotone non-increasing, so we can use mathematical induction to proof that for $j$, the increase speed of $g_{i-1,j}$ is faster than that of $k_i\\cdot j$. We can find a critical value $M$ that $\\forall j\\le M, g_{i,j}<k_i\\cdot j$ and $\\forall j>M,g_{i,j}>k_i\\cdot j$. So compared $g_i$ with $g_{i+1}$, the first part of the sequence remains unchanged, and the last part is added with $k_i$, with an additional number $k_i\\cdot j$ in the middle, where $j$ is the maximum number satisfied $g_{i-1,j-1}\\le k_i \\cdot j$. Use the treap to maintain this sequence, which might be called the slope trick.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "geometry"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1787",
    "index": "I",
    "title": "Treasure Hunt",
    "statement": "Define the beauty value of a sequence $b_1,b_2,\\ldots,b_c$ as the maximum value of $\\sum\\limits_{i=1}^{q}b_i + \\sum\\limits_{i=s}^{t}b_i$, where $q$, $s$, $t$ are all integers and $s > q$ or $t\\leq q$. Note that $b_i = 0$ when $i<1$ or $i>c$, $\\sum\\limits_{i=s}^{t}b_i = 0$ when $s>t$.\n\nFor example, when $b = [-1,-2,-3]$, we may have $q = 0$, $s = 3$, $t = 2$ so the beauty value is $0 + 0 = 0$. And when $b = [-1,2,-3]$, we have $q = s = t = 2$ so the beauty value is $1 + 2 = 3$.\n\nYou are given a sequence $a$ of length $n$, determine the sum of the beauty value of all non-empty subsegments $a_l,a_{l+1},\\ldots,a_r$ ($1\\leq l\\leq r\\leq n$) of the sequence $a$.\n\nPrint the answer modulo $998\\,244\\,353$.",
    "tutorial": "First, we observe that: $\\max\\limits_{l>p\\,\\texttt{or}\\,r\\leq p}{(\\sum\\limits_{i=1}^{p}{a_i}+\\sum\\limits_{i=l}^{r}{a_i})}=\\max\\limits_{p=1}^{n}{\\sum\\limits_{i=1}^{p}{a_i}}+\\max\\limits_{l,r}{\\sum\\limits_{i=l}^{r}{a_i}}$. Proof: We can proof it by contradiction. Define $g(l,r,p)$ as $\\sum\\limits_{i=1}^{p}{a_i}+\\sum\\limits_{i=l}^{r}{a_i}$. Suppose $l\\leq p<r$ when $g(l,r,p)$ hits the maximum value. If $\\sum\\limits_{i=p+1}^{r}{a_i}\\geq 0$, $g(l,r,r)\\geq g(l,r,p)$, otherwise $g(l,p,p)> g(l,r,p)$. So the above observation is always correct. So we can divide the problem into two parts: $\\max\\limits_{p=1}^{n}{\\sum\\limits_{i=1}^{p}{a_i}}$ and $\\max\\limits_{l,r}{\\sum\\limits_{i=l}^{r}{a_i}}$. For $\\max\\limits_{p=1}^{n}{\\sum\\limits_{i=1}^{p}{a_i}}$, it's easy to solve it by using a stack to calculate the prefix maximum value, and then calculate the answer. And for $\\max\\limits_{l,r}{\\sum\\limits_{i=l}^{r}{a_i}}$, consider divide and conquer. For a part $[l,r]$,let $m=\\lfloor \\frac{l+r}{2}\\rfloor$. Define $h(L,R)$ as $\\max\\limits_{L\\leq l,r\\leq R}{\\sum\\limits_{i=l}^{r}{a_i}}$. We want to calculate the sum of $h(L,R)$ satisfied $l\\leq L\\leq m<R < r$. Obviously $h(L,R) = \\max(\\max(h(L,m),h(m+1,R)),\\max\\limits_{L\\leq p\\leq m}{\\sum\\limits_{j=p}^{m}{a_j}}+\\max\\limits_{m<p\\leq R}{\\sum\\limits_{j=m+1}^{p}{a_j}})$, and it's easy to calculate above four value in the time complexity of $O(r - l)$. We can use binary search to calculate the maximum value. So the problem can be solved in the time complexity of $O(n\\log ^2n)$. But it's not good enough. We can solve it in the time complexity of $O(n\\log n)$ based on the following theorem: Define $f(p)$ as $\\max\\limits_{1\\leq q\\leq p}{\\sum\\limits_{i=1}^q{a_i}}$. $h(1,p)-f(p)$ is non-decreasing. Proof: Actually, if we extend the first theorem, we will find $l>p$ or $r=p$ : If $l>p$, so $\\sum\\limits_{i=p+1}^r{a_i}<0$. When we add an element at the back of the sequence: If $\\sum\\limits_{i=1}^{len}{a_i}>\\sum\\limits_{i=1}^p{a_i}$, $p$ and $r$ become $len$ at the same time. So $\\Delta f(len)<\\Delta h(1,len)$ since $\\sum\\limits_{i=p+1}^r{a_i}<0$. Otherwise if $\\sum\\limits_{i=1}^{len}{a_i}\\leq \\sum\\limits_{i=1}^p{a_i}$, $\\Delta f(len)=0$ while $\\Delta h(1,len) \\geq 0$. So the theorem always holds in this circumstance. If $p=r$, $\\Delta f(len)=\\Delta h(1,len)$, so the theorem holds too. Because of the theorem, we can replace binary search by two pointers. So the final time complexity is $O(n\\log n)$.",
    "tags": [
      "data structures",
      "divide and conquer",
      "two pointers"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1788",
    "index": "A",
    "title": "One and Two",
    "statement": "You are given a sequence $a_1, a_2, \\ldots, a_n$. Each element of $a$ is $1$ or $2$.\n\nFind out if an integer $k$ exists so that the following conditions are met.\n\n- $1 \\leq k \\leq n-1$, and\n- $a_1 \\cdot a_2 \\cdot \\ldots \\cdot a_k = a_{k+1} \\cdot a_{k+2} \\cdot \\ldots \\cdot a_n$.\n\nIf there exist multiple $k$ that satisfy the given condition, print the smallest.",
    "tutorial": "There should be same number of $2$ at $a_1, a_2, \\cdots a_k$ and $a_{k+1}, \\cdots, a_n$. By checking every $k$, we can solve the problem at $O(N^2)$. By sweeping $k$ from $1$ to $n-1$, we can solve the problem in $O(N)$. Not counting the number of $2$ but naively multiplying using sweeping in python was accepted since it has time complexity $O(N^2)$. Checking every $k$ and naively multiplying solutions are $O(N^3)$, so those solutions won't fit in time limit.",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1788",
    "index": "B",
    "title": "Sum of Two Numbers",
    "statement": "The sum of digits of a non-negative integer $a$ is the result of summing up its digits together when written in the decimal system. For example, the sum of digits of $123$ is $6$ and the sum of digits of $10$ is $1$. In a formal way, the sum of digits of $\\displaystyle a=\\sum_{i=0}^{\\infty} a_i \\cdot 10^i$, where $0 \\leq a_i \\leq 9$, is defined as $\\displaystyle\\sum_{i=0}^{\\infty}{a_i}$.\n\nGiven an integer $n$, find two non-negative integers $x$ and $y$ which satisfy the following conditions.\n\n- $x+y=n$, and\n- the sum of digits of $x$ and the sum of digits of $y$ differ by at most $1$.\n\nIt can be shown that such $x$ and $y$ always exist.",
    "tutorial": "Let's assume that there is no carry while adding $x$ and $y$. Denote $n=a_9 \\cdots a_1a_0$, $x=b_9 \\cdots b_1b_0$, $y=c_9 \\cdots c_1c_0$ in decimal system. The condition can be changed as the following condition. - $a_i=b_i+c_i$ for all $0 \\leq i \\leq 9$. - Sum of $b_i$ and sum of $c_i$ should differ by at most $1$. If $a_i$ is even, let $b_i=c_i=a_i/2$. Otherwise, let $b_i$ and $c_i$ be $\\frac{a_i+1}{2}$ or $\\frac{a_i-1}{2}$. By alternating between $(b_i, c_i)=(\\frac{a_i+1}{2}, \\frac{a_i-1}{2})$ and $(b_i, c_i)=(\\frac{a_i-1}{2}, \\frac{a_i+1}{2})$, we can satisfy the condition where sum of $b_i$ and sum of $c_i$ differ by at most $1$. There is an alternative solution. If $n$ is even, divide it into ($\\frac{n}{2}, \\frac{n}{2}$). If remainder of $n$ divided by $10$ is not $9$, divide it into ($\\frac{n+1}{2}, \\frac{n-1}{2}$). If remainder of $n$ divided by $10$ is $9$, recursively find an answer for $\\lfloor \\frac{n}{10} \\rfloor$ which is ($x', y'$) and the answer will be ($10x'+4, 10y'+5$) or ($10x'+5, 10y'+4$) depending on what number has a bigger sum of digits. The following solution has a countertest. 1. Trying to find $x$ and $y$ by bruteforce from ($1, n-1$). 2. Trying to find $x$ and $y$ by bruteforce from ($\\frac{n+1}{2}, \\frac{n-1}{2}$) A solution that randomly finds ($x, y$) passes.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math",
      "probabilities"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1788",
    "index": "C",
    "title": "Matching Numbers",
    "statement": "You are given an integer $n$. Pair the integers $1$ to $2n$ (i.e. each integer should be in exactly one pair) so that each sum of matched pairs is consecutive and distinct.\n\nFormally, let $(a_i, b_i)$ be the pairs that you matched. $\\{a_1, b_1, a_2, b_2, \\ldots, a_n, b_n\\}$ should be a permutation of $\\{1, 2, \\ldots, 2n\\}$. Let the sorted list of $\\{a_1+b_1, a_2+b_2, \\ldots, a_n+b_n\\}$ be $s_1 < s_2 < \\ldots < s_n$. We must have $s_{i+1}-s_i = 1$ for $1 \\le i \\le n - 1$.",
    "tutorial": "Let's assume that $1$ to $2n$ is paired and each sum of pair is $k, k+1, \\cdots, k+n-1$. Sum from $1$ to $2n$ should equal to the sum of $k$ to $k+n-1$. So we obtain $n(2n+1)=\\frac{(2k+n-1)n}{2}$, which leads to $4n+2=2k+n-1$. Since $4n+2$ is even, $2k+n-1$ should be even. So if $n$ is even, we cannot find such pairing. If $n$ is odd, there are various ways to make such pairing. Let $m=\\frac{n-1}{2}$. $(1, 3m+3), (2, 3m+4), \\ldots (m, 4m+2), (m+1, 2m+2), (m+2, 2m+3), \\ldots (2m+1, 3m+2)$ can be such pairing.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1788",
    "index": "D",
    "title": "Moving Dots",
    "statement": "We play a game with $n$ dots on a number line.\n\nThe initial coordinate of the $i$-th dot is $x_i$. These coordinates are distinct. Every dot starts moving simultaneously with the same constant speed.\n\nEach dot moves in the direction of the closest dot (different from itself) until it meets another dot. In the case of a tie, it goes to the left. Two dots meet if they are in the same coordinate, after that, they stop moving.\n\nAfter enough time, every dot stops moving. The result of a game is the number of distinct coordinates where the dots stop.\n\nBecause this game is too easy, calculate the sum of results when we play the game for every subset of the given $n$ dots that has at least two dots. As the result can be very large, print the sum modulo $10^9+7$.",
    "tutorial": "Let's think about the original problem where we do not think about subsets. We can easily observe that each dot does not change direction during moving. Assume that dots gather at coordinate $x$. Rightmost dot of dots that have smaller coordinate than $x$ should move right, and leftmost dot which has bigger coordinate than $x$ should move left. We can observe that the number of adjacent dot where each move toward each other will be the answer. Now let's solve the problem for subsets. Instead of counting number of adjacent dot that moves toward each other for each subset of dots, we will count the number of subset for each possible $1 \\leq i < j \\leq N$ where dot $i$ moves right and dot $j$ moves left and there are no dots between $i$ and $j$. Let the coordinate of a dot in a subset be $k$. We will try to find out which $k$ can be in a subset where dot $i$ and dot $j$ move toward each other. Since there are no dot between $i$ and $j$, dots satisfying $x_i < k < x_j$ should not be in the subset. Since dot $i$ should move right, dots that satisfy $k<x_i$ and $x_i-k \\leq x_j-x_i$ should not be in the subset. As the same way for dot $j$, dots that satisfy $k>x_j$ and $k-x_j < x_j-x_i$ should not be in the subset. Summing these up, dots satisfying $2x_i -- x_j \\leq k < 2x_j -- x_i$ should not be in the subset. By using binary search, we can find the number of dots that cannot be in the subset in $O(logN)$. If there are $p$ dots that can be in the subset, the number of subset where $i$ and $j$ moves toward each other will be $2^p$. Summing all $2^p$ will give us the answer. Since there are $O(N^2)$ pairs of $(i, j)$, we can solve the problem in $O(N^2logN)$. Instead of using binary search, we can use the monotonicity of $2x_j-x_i$ and $2x_i-x_j$ when $j$ increases, we can solve the range of dots that cannot be in the subset in $O(N^2)$ by sweeping. Both $O(N^2logN)$ and $O(N^2)$ solutions will be accepted. There were some dynamic programming solutions from some testers.",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1788",
    "index": "E",
    "title": "Sum Over Zero",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$ of $n$ integers. Consider $S$ as a set of segments satisfying the following conditions.\n\n- Each element of $S$ should be in form $[x, y]$, where $x$ and $y$ are integers between $1$ and $n$, inclusive, and $x \\leq y$.\n- No two segments in $S$ intersect with each other. Two segments $[a, b]$ and $[c, d]$ intersect if and only if there exists an integer $x$ such that $a \\leq x \\leq b$ and $c \\leq x \\leq d$.\n- For each $[x, y]$ in $S$, $a_x+a_{x+1}+ \\ldots +a_y \\geq 0$.\n\nThe length of the segment $[x, y]$ is defined as $y-x+1$. $f(S)$ is defined as the sum of the lengths of every element in $S$. In a formal way, $f(S) = \\sum_{[x, y] \\in S} (y - x + 1)$. Note that if $S$ is empty, $f(S)$ is $0$.\n\nWhat is the maximum $f(S)$ among all possible $S$?",
    "tutorial": "Denote $p$ as the prefix sum of $a$. For a segment $[x+1, y]$ to be an element of $S$, $p_x \\leq p_y$ should be satisfied. Let's denote $dp_i$ as the maximum value of the sum of length of segment smaller than $i$ in $S$. Segment $[x, y]$ is smaller than $i$ if $y \\leq i$. If there is no segment ending at $i$, $dp_i=dp_{i-1}$. If there is segment $[k+1, i]$ in $S$, $dp_i=\\max_{ p_{k} \\leq p_i }(dp_k+i-k)$. By summing up, $dp_i = \\max(dp_{i-1}, \\max_{p_k \\leq p_i}(dp_k+i-k)$ With this dp, we get an $O(N^2)$ solution. Now let's try to speed up the dp transition using segment tree. First, use coordinate compression on $p_i$ since we only see whether one prefix sum is bigger than the other. We will maintain a segment tree that stores $dp_k-k$ in position $p_k$. Let's find $dp_i$ in order of $i$. $dp_i = \\max(dp_{i-1}, \\max_{p_k \\leq p_i}(dp_k-k)+i)$ We can solve $\\max_{p_k \\leq p_i}(dp_k-k)$ by range query $[0, p_i]$ on a segment tree. So we can solve $dp_i$ in $O(logN)$ for each $i$. The entire problem is solved in $O(NlogN)$. There is an alternative solution that maintains pair $(dp_k-k, p_k)$ monotonically with a set. This solution also runs in $O(NlogN)$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1788",
    "index": "F",
    "title": "XOR, Tree, and Queries",
    "statement": "You are given a tree of $n$ vertices. The vertices are numbered from $1$ to $n$.\n\nYou will need to assign a weight to each edge. Let the weight of the $i$-th edge be $a_i$ ($1 \\leq i \\leq n-1$). The weight of each edge should be an integer between $0$ and $2^{30}-1$, inclusive.\n\nYou are given $q$ conditions. Each condition consists of three integers $u$, $v$, and $x$. This means that the bitwise XOR of all edges on the shortest path from $u$ to $v$ should be $x$.\n\nFind out if there exist $a_1, a_2, \\ldots, a_{n-1}$ that satisfy the given conditions. If yes, print a solution such that $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_{n-1}$ is the \\textbf{smallest}. Here, $\\oplus$ denotes the bitwise XOR operation.\n\nIf there are multiple solutions such that $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_{n-1}$ is the smallest, print any.",
    "tutorial": "Let's denote $p_i$ as xor of edges in path from node $1$ to node $i$. Edges in path from $i$ to $j$ is (edges in path from $1$ to $i$) + (edges in path from $1$ to $j$) - $2 \\times$(edges in path from $1$ to $lca(i, j)$) where $lca(i, j)$ denotes the least common ancestor of $i$ and $j$. Since xor of two same number is $0$, we can observe that xor of path from $i$ to $j$ is $p_i \\oplus p_j$. If we know every $p_i$ for all $i$, weight of edge connecting $i$ and $j$ is $p_i \\oplus p_j$, so deciding weight of every edge is equivalent to deciding every $p_i$ for $i \\geq 2$. Let $G$ be the original tree graph. Let's make a undirected weighted graph $G'$ from the given condition. Condition ($u$, $v$, $x$) makes an edge connecting $u$ and $v$ with weight $x$. This edge means that $p_v=p_u \\oplus x$. Now if $u$ and $v$ are connected by edges in $G'$, this means that $p_v=p_u \\oplus$ (xor of edges in path from $u$ to $v$). First, let's check if it is possible to make a graph that satisfies the conditions. If $G'$ is a connected graph, we can solve $p_i$ using dfs from node $1$. For edges not used in dfs (back edges), we have to check if it is valid with the solved $p_i$. Specifically, if there is an edge ($u$, $v$, $x$), we need to check if $p_u \\oplus p_v=x$. Now let's think when $G'$ is not a connected graph. By dividing the graph into connected components, we can solve if it is impossible to make a graph that satisfies the conditions in a same fashion. Now let's try to minimize $a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_{n-1}$. For edge $(u, v)$ in $G$, weight of edge is $p_u \\oplus p_v$. By substituting $a_i$ into $p_{x_i} \\oplus$ $p_{y_i}$, $a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_{n-1}$ can be written as xor of $p_i$ where node $i$ has odd degree. Let the connected components of $G'$ be $G_1, G_2, \\ldots, G_k$. Pick any vertex $r_k$ in each component $G_k$. For every vertex $i$ in $G_k$, $p_i$ is expressed as $p_{r_k} \\oplus$ (xor of edges in path from $r_k$ to $i$). Let's define a set $L$ as $L=${$i | G_i$ has odd number of odd degree vertices}. By substituting $p_i$ into ($p_{r_k} \\oplus$ (xor of edges in path in $G'$ from $r_k$ to $i$)), we can rewrite \"xor of $p_i$ where node $i$ has odd degree\" into $\\bigoplus_{k \\in L} p_{r_k} \\oplus c$ where $c$ is a constant. If $L$ is empty, the answer is constant and any solution that satisfy the given conditions will be the answer. If $L$ is not empty, set one of $p_{r_k}$ to $c$ and other $p_{r_k}$ as $0$ so that $a_1 \\oplus a_2 \\oplus \\cdots a_{n-1}$ is $0$. We can solve the problem in $O(N)$. Fast $O(NlogX)$ solution might be accepted, including the solution where you divide the weight of edge by bits.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1789",
    "index": "A",
    "title": "Serval and Mocha's Array",
    "statement": "Mocha likes arrays, and Serval gave her an array consisting of positive integers as a gift.\n\nMocha thinks that for an array of positive integers $a$, it is good iff the greatest common divisor of all the elements in $a$ is no more than its length. And for an array of at least $2$ positive integers, it is beautiful iff all of its prefixes whose length is no less than $2$ are good.\n\nFor example:\n\n- $[3,6]$ is not good, because $\\gcd(3,6)=3$ is greater than its length $2$.\n- $[1,2,4]$ is both good and beautiful, because all of its prefixes whose length is no less than $2$, which are $[1,2]$ and $[1,2,4]$, are both good.\n- $[3,6,1]$ is good but not beautiful, because $[3,6]$ is not good.\n\nNow Mocha gives you the gift array $a$ of $n$ positive integers, and she wants to know whether array $a$ could become beautiful by reordering the elements in $a$. It is allowed to keep the array $a$ unchanged.",
    "tutorial": "Considering an array $a$ of $n$ ($n\\geq 2$) positive integers, the following inequality holds for $2\\leq i\\leq n$: $\\gcd(a_1,a_2,\\cdots,a_i) \\leq \\gcd(a_1,a_2) \\leq 2$ Therefore, when the prefix $[a_1,a_2]$ of $a$ is good, we can show that all the prefixes of $a$ whose length is no less than $2$ are good, then $a$ is beautiful. It is obvious that $[a_1, a_2]$ is good when $a$ is beautiful. So we get the conclusion that $a$ is beautiful if and only if the prefix $[a_1, a_2]$ is good. We can check if there exist $a_i, a_j$ ($i\\neq j$) such that $\\gcd(a_i, a_j)\\leq 2$. If so, we can move $a_i,a_j$ to the front of $a$ to make it beautiful, then the answer is Yes. If not, the answer is No. Time complexity: $O(n^2\\log 10^6)$.",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1789",
    "index": "B",
    "title": "Serval and Inversion Magic",
    "statement": "Serval has a string $s$ that only consists of 0 and 1 of length $n$. The $i$-th character of $s$ is denoted as $s_i$, where $1\\leq i\\leq n$.\n\nServal can perform the following operation called Inversion Magic on the string $s$:\n\n- Choose an segment $[l, r]$ ($1\\leq l\\leq r\\leq n$). For $l\\leq i\\leq r$, change $s_i$ into 1 if $s_i$ is 0, and change $s_i$ into 0 if $s_i$ is 1.\n\nFor example, let $s$ be 010100 and the segment $[2,5]$ is chosen. The string $s$ will be 001010 after performing the Inversion Magic.\n\nServal wants to make $s$ a palindrome after performing Inversion Magic \\textbf{exactly once}. Help him to determine whether it is possible.\n\nA string is a palindrome iff it reads the same backwards as forwards. For example, 010010 is a palindrome but 10111 is not.",
    "tutorial": "If $s$ is palindromic initially, we can operate on the interval $[1,n]$, the answer is Yes. Let's consider the other case. In a palindrome $s$, for each $i$ in $[1,\\lfloor n/2\\rfloor]$, $s_{i}=s_{n-i+1}$ must hold. For those $i$, we may check whether $s_{i}=s_{n-i+1}$ is true in the initial string. For all the illegal positions $i$, the operation must contain either $i$ or $n+1-i$, but not both. For the legal positions, the operation must contain neither of $i$ nor $n+1-i$, or both of them. If the illegal positions is continuous (which means that they are $l,l+1,\\dots,r-1,r$ for some $l$ and $r$), we may operate on the interval $[l,r]$ (or $[n+1-r,n+1-l]$), making the string palindromic. The answer is Yes. Otherwise, there must be some legal positions that lie between the illegal ones. Suppose the illegal positions range between $[l,r]$ (but not continuous), and the operation is $[o_{1},o_{2}]$. Without loss of generality, let the operation lies in the left part of the string. Then $o_{1}\\le l,r\\le o_{2}<n+1-r$ must hold to correct all the illegal positions. This interval covers all the legal positions that lie between the illegal ones but does not cover their symmetrical positions. Thus, such kind of operation will produce new illegal positions. In other words, there are no valid operations in this situation. The answer is No. Time complexity: $O(n)$.",
    "tags": [
      "brute force",
      "implementation",
      "strings",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1789",
    "index": "C",
    "title": "Serval and Toxel's Arrays",
    "statement": "Toxel likes arrays. Before traveling to the Paldea region, Serval gave him an array $a$ as a gift. This array has $n$ \\textbf{pairwise distinct} elements.\n\nIn order to get more arrays, Toxel performed $m$ operations with the initial array. In the $i$-th operation, he modified the $p_{i}$-th element of the $(i-1)$-th array to $v_{i}$, resulting in the $i$-th array (the initial array $a$ is numbered as $0$). During modifications, Toxel guaranteed that the elements of each array are still \\textbf{pairwise distinct} after each operation.\n\nFinally, Toxel got $m+1$ arrays and denoted them as $A_{0}=a, A_{1},\\ldots,A_{m}$. For each pair $(i,j)$ ($0\\le i<j\\le m$), Toxel defines its value as the number of distinct elements of the concatenation of $A_{i}$ and $A_{j}$. Now Toxel wonders, what is the sum of the values of all pairs? Please help him to calculate the answer.",
    "tutorial": "Consider the contribution of each value. We only need to count the number of concatenated arrays each value appears in, and sum all those counts up. The answer to this problem only depends on the number of appearances of this value. Notice that the appearance of each value forms some intervals. Each interval starts when it modifies another element (or in the initial array), and ends when it is modified (or in the $m$-th array). As there are no duplicate elements, the intervals do not intersect, so we can simply sum their lengths up. Let's use an array $\\text{appear}$ to track the appearance of each value. We first set the appearance of the initial elements to $0$, and other elements to $-1$, which means the value does not appear. Then, in the $i$-th modification, suppose we modified some elements from $x$ to $y$, then we should add $i-\\text{appear}_{x}$ to $\\text{count}_{x}$, and set $\\text{appear}_{x}$ to $-1$. We should also set $\\text{appear}_{y}$ to $i$. After all operations, for all $x$, add $m+1-\\text{appear}_{x}$ to $\\text{count}_{x}$ if $\\text{appear}_{x}$ is not $-1$. Value $x$ appears in $\\frac{m(m+1)}{2}-\\frac{(m-\\text{count}_{x})(m-\\text{count}_{x}+1)}{2}$ concatenated arrays. Time complexity: $O(n+m)$.",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1789",
    "index": "D",
    "title": "Serval and Shift-Shift-Shift",
    "statement": "Serval has two $n$-bit binary integer numbers $a$ and $b$. He wants to share those numbers with Toxel.\n\nSince Toxel likes the number $b$ more, Serval decides to change $a$ into $b$ by some (possibly zero) operations. In an operation, Serval can choose any \\textbf{positive} integer $k$ between $1$ and $n$, and change $a$ into one of the following number:\n\n- $a\\oplus(a\\ll k)$\n- $a\\oplus(a\\gg k)$\n\nIn other words, the operation moves every bit of $a$ left or right by $k$ positions, where the overflowed bits are removed, and the missing bits are padded with $0$. The bitwise XOR of the shift result and the original $a$ is assigned back to $a$.\n\nServal does not have much time. He wants to perform \\textbf{no more than} $n$ operations to change $a$ into $b$. Please help him to find out an operation sequence, or determine that it is impossible to change $a$ into $b$ in at most $n$ operations. You do \\textbf{not need} to minimize the number of operations.\n\nIn this problem, $x\\oplus y$ denotes the bitwise XOR operation of $x$ and $y$. $a\\ll k$ and $a\\gg k$ denote the logical left shift and logical right shift.",
    "tutorial": "First of all, it could be proven that the answer exists if and only if $a$ and $b$ are both zero or $a$ and $b$ are both non-zero. If $a$ is zero, it remains zero after any operations. Therefore it cannot become $b$ if $b$ is non-zero. If $a$ is non-zero, logical left shift it will definitely increase its lowest bit or make it zero, thus changing it into a different number. The same applies to logical right shift. Therefore, the xor result must be non-zero and there are no possible operations if $b$ is zero. We will show that it is always possible to change $a$ into $b$ in the other cases. We denote $\\text{lb}(a)$ as the lowest bit of $a$ and $\\text{hb}(a)$ as the highest bit of $a$. If $a$ and $b$ are both zero, no operations are needed. If they are both non-zero, the construction consists of four steps: If $\\text{hb}(a)<\\text{lb}(b)$, logical left shift $a$ by $\\text{lb}(b)-\\text{hb}(a)$ bits. Then $\\text{hb}(a)$ must be equal or greater than $\\text{lb}(b)$. For each bit $i$ of $\\text{lb}(b)-1,\\text{lb}(b)-2,\\dots,1$, if $a_{i}=1$, we may logical right shift $a$ by $\\text{hb}(a)-i$ bits to erase it. After that, we have $\\text{lb}(a)\\ge\\text{lb}(b)$. If $\\text{lb}(a)>\\text{lb}(b)$, logical right shift $a$ by $\\text{lb}(a)-\\text{lb}(b)$ bits. Now it is guaranteed that $\\text{lb}(a)=\\text{lb}(b)$. For each bit $i$ of $\\text{lb}(b)+1,\\text{lb}(b)+2,\\dots,n$, if $a_{i}\\neq b_{i}$, we may logical left shift $a$ by $i-\\text{lb}(a)$ bits to erase it. After that, we must have $a=b$. Step 2 and step 4 require at most $n-1$ operations. We may also note that step 1 and step 3 never appear simultaneously. If step 1 is operated, then $\\text{lb}(a)=\\text{lb}(b)$ is guaranteed after step 2. Thus, we need not operate step 3 in this case. In conclusion, we may use no more than $n$ operations to change $a$ into $b$ if they are both non-zero. Time Complexity: $O(n^{2})$ or $O(\\frac{n^{2}}{w})$ by using std::bitset.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1789",
    "index": "E",
    "title": "Serval and Music Game",
    "statement": "Serval loves playing music games. He meets a problem when playing music games, and he leaves it for you to solve.\n\nYou are given $n$ positive integers $s_1 < s_2 < \\ldots < s_n$. $f(x)$ is defined as the number of $i$ ($1\\leq i\\leq n$) that exist non-negative integers $p_i, q_i$ such that:\n\n$$s_i=p_i\\left\\lfloor{s_n\\over x}\\right\\rfloor + q_i\\left\\lceil{s_n\\over x}\\right\\rceil$$\n\nFind out $\\sum_{x=1}^{s_n} x\\cdot f(x)$ modulo $998\\,244\\,353$.\n\nAs a reminder, $\\lfloor x\\rfloor$ denotes the maximal integer that is no greater than $x$, and $\\lceil x\\rceil$ denotes the minimal integer that is no less than $x$.",
    "tutorial": "Consider the following two cases: Case 1: $x$ is not a factor of $s_n$. In this case we have $\\left\\lfloor{s_n\\over x}\\right\\rfloor + 1 = \\left\\lceil{s_n\\over x}\\right\\rceil$. Let $k = \\left\\lfloor{s_n\\over x}\\right\\rfloor$. It can be shown that there are at most $2\\sqrt{s_n}$ different values of $k$. The constraint of $s_i$ can be written in the following form: $s_i = p_i \\cdot k + q_i \\cdot (k+1) = (p_i+q_i)\\cdot k + q_i$ For a certain $k$, such $p_i$ and $q_i$ do not exist if and only if $s_i\\bmod k > \\left\\lfloor{s_i\\over k}\\right\\rfloor$. To prove it, we show the contradiction that $q_i\\bmod k = s_i\\bmod k > \\left\\lfloor{s_i\\over k}\\right\\rfloor \\geq q_i$, and we can give a construction of $p_i$ and $q_i$ when $s_i\\bmod k\\leq \\left\\lfloor{s_i\\over k}\\right\\rfloor$ that $q_i = s_i\\bmod k$ and $p_i=\\left\\lfloor{s_i\\over k}\\right\\rfloor - q_i$. By observation, these $s_i$ are in one of the following $k-2$ intervals: $[1, k-1], [k+2, 2k-1],\\dots, [(i-1)k+i, ik-1],\\dots, [(k-2)k+(k-1), (k-1)k-1]$ We can count the number of these $s_i$ by pre-calculating the prefix sums to calculate $f(x)$. This case can be solved in $O(s_n)$ time, and we will show this fact: When $k\\leq \\sqrt{s_n}$, there are $k - 2$ intervals that need to be considered for a certain $k$. Since $\\sum_{k\\leq \\sqrt{s_n}} k \\leq s_n$, this part can be solved in $O(s_n)$ time. When $k>\\sqrt{s_n}$, notice that there are at most $\\left\\lceil s_n\\over k\\right\\rceil \\leq \\sqrt{s_n}$ intervals that need to be considered for a certain $k$. Recall that there are at most $\\sqrt{s_n}$ different values of $k$ in this part, so it can be solved in $O(s_n)$ time. Case 2: $x$ is a factor of $s_n$. In this case we have $\\left\\lfloor{s_n\\over x}\\right\\rfloor = \\left\\lceil{s_n\\over x}\\right\\rceil$. Let $k = {s_n\\over x}$. The constraint of $s_i$ becomes: $s_i = (p_i + q_i) \\cdot k$ To calculate $f(x)$, we only need to count the number of multiples of $x$. To do this, we can first calculate $s'_i = \\gcd(s_i, s_n)$ for all $1\\leq i\\leq n$ in $O(n\\log s_n)$ time. It is obvious that $s_i'$ is a factor of $s_n$. For a certain $x$, we can enumerate all the factors of $s_n$, find out the multiples of $x$ among them, and sum up the times that they occurred in $s'$. Recall that $s_n$ has at most $2\\sqrt{s_n}$ factors, so this takes $O(s_n)$ time. This case can be solved in $O(n\\log s_n + s_n)$ time in total. Time complexity: $O(n\\log s_n + s_n)$. $O(s_n + \\sigma(s_n))$ solutions can pass all the tests, where $\\sigma(n)$ denotes the sum of all the factors of $n$. A well-implemented $O(s_n\\log s_n)$ solutions may pass the tests, too. Bonus: Solve this problem in $O(n + s_n)$ time.",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1789",
    "index": "F",
    "title": "Serval and Brain Power",
    "statement": "Serval loves Brain Power and his brain power problem.\n\nServal defines that a string $T$ is powerful iff $T$ can be obtained by concatenating some string $T'$ multiple times. Formally speaking, $T$ is powerful iff there exist a string $T'$ and an integer $k\\geq 2$ such that $$T=\\underbrace{T'+T'+\\dots+T'}_{k\\text{ times}}$$\n\nFor example, gogogo is powerful because it can be obtained by concatenating go three times, but power is not powerful.\n\nServal has a string $S$ consists of lowercase English letters. He is curious about the longest powerful subsequence of $S$, and he only needs you to find out the length of it. If all the non-empty subsequences of $S$ is not powerful, the answer is considered to be $0$.\n\nA string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters.",
    "tutorial": "Assume that the longest powerful subsequence of the given string $S$ is $T$, which can be obtained by concatenating $k$ copies of string $T'$. Noticing that $|S|\\leq 80$, we have the observation that $k\\cdot |T'| \\leq |S| \\leq 80$, so it is impossible that both $k$ and $|T'|$ is large. When $k < 5$, we only need to consider the $k = 2$ case and the $k = 3$ case. The $k = 4$ case is covered by $k = 2$ case, since $T = T'+T'+T'+T' = (T'+T') + (T'+T')$. For the $k = 2$ case, we split $S$ into two parts $S=S_1+S_2$, then calculate the maximal length of $\\operatorname{LCS}(S_1, S_2)$ by dynamic programming over all the possible splits. This case can be solved in $O(w_2\\cdot|S|^3)$ time, where $w_2$ is a small constant. It is similar to solve the $k = 3$ case. We split $S$ into three parts $S = S_1 + S_2 + S_3$, then calculate the maximal length of $\\operatorname{LCS}(S_1, S_2, S_3)$ over all the possible splits. This case can be solved in $O(w_3\\cdot|S|^5)$ time, where $w_3$ is a small constant. We will estimate $w_3$ later. When $k \\geq 5$, we have $|T'|\\leq {|S|\\over k}\\leq {|S|\\over 5}$. It can be shown that, if we split $S$ into $5$ parts, $T'$ will be the subsequence of at least one of them. We can split $S$ into equal lengths, then enumerate all the subsequences of these substrings as the possible $T'$. For a possible $T'$, we can find out corresponding $k$ by matching $T'$ and $S$ greedily. This case can be solved in $O(5\\cdot 2^{|S|/5}|S|)$. Now let us roughly estimate how small $w_3$ could be. The time that dynamic programming consumed for certain $S_1, S_2, S_3$ is $|S_1|\\cdot|S_2|\\cdot|S_3|$. Since $|S_1|+|S_2|+|S_3|=|S|$, we have $|S_1|\\cdot|S_2|\\cdot|S_3|\\leq {1\\over 27}|S|^3$. Recall that there are ${|S|-1 \\choose 2} \\leq {1\\over 2}|S|^2$ possible splits, then $w_3\\leq {1\\over 54}$ holds. Time complexity: $O(w_3\\cdot|S|^5 + 5\\cdot 2^{|S|/5}|S|)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1790",
    "index": "A",
    "title": "Polycarp and the Day of Pi",
    "statement": "On March 14, the day of the number $\\pi$ is celebrated all over the world. This is a very important mathematical constant equal to the ratio of the circumference of a circle to its diameter.\n\nPolycarp was told at school that the number $\\pi$ is irrational, therefore it has an infinite number of digits in decimal notation. He wanted to prepare for the Day of the number $\\pi$ by memorizing this number as accurately as possible.\n\nPolycarp wrote out all the digits that he managed to remember. For example, if Polycarp remembered $\\pi$ as $3.1415$, he wrote out 31415.\n\nPolycarp was in a hurry and could have made a mistake, so you decided to check how many first digits of the number $\\pi$ Polycarp actually remembers correctly.",
    "tutorial": "In the problem, you had to find the largest common prefix(LCP) of the first $30$ characters of the number $\\pi$ and the string $n$. To do this, we will go from the beginning and compare the characters until we find a non-matching one, or until the string $n$ ends.",
    "code": "t = int(input())\npi = '31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679'\nfor _ in range(t):\n    n = input() + '#'\n    for i in range(len(n)):\n        if pi[i] != n[i]:\n            print(i)\n            break",
    "tags": [
      "implementation",
      "math",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1790",
    "index": "B",
    "title": "Taisia and Dice",
    "statement": "Taisia has $n$ six-sided dice. Each face of the die is marked with a number from $1$ to $6$, each number from $1$ to $6$ is used once.\n\nTaisia rolls all $n$ dice at the same time and gets a sequence of values $a_1, a_2, \\ldots, a_n$ ($1 \\le a_i \\le 6$), where $a_i$ is the value on the upper face of the $i$-th dice. The sum of this sequence is equal to $s$.\n\nSuddenly, Taisia's pet cat steals exactly \\textbf{one} dice with \\textbf{maximum} value $a_i$ and calculates the sum of the values on the remaining $n-1$ dice, which is equal to $r$.\n\nYou only know the number of dice $n$ and the values of $s$, $r$. Restore a possible sequence $a$ that fulfills the constraints.",
    "tutorial": "It is easy to find the value on the cube that the cat stole, it is equal $mx = s - r$. All other values must be no more than $mx$. Let's try to get $r$ by taking $mx$ $\\lfloor\\frac{r}{mx}\\rfloor$ times and adding the remainder there if it is non-zero. We could not get more than $n - 1$ cubes this way, because otherwise $(n - 1)mx > r$, but we are guaranteed that the answer exists. Now, until we get the $n-1$ cube, let's find the cube with the maximum value, reduce it by $1$ and add the cube with the value of $1$. We can definitely get $n - 1$ dice, because otherwise $r < n - 1$, but we are guaranteed that the answer exists. It remains only to add a cube with the value of $mx$ to our $n-1$ cubes. We obtained a solution with $O(n^2)$ asymptotics.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 55;\n\nint n, s1, s2;\nvector<int> res;\n\nvoid solve() {\n\tres.clear();\n\tint d = s1 - s2;\n\tfor (; s2 >= d; s2 -= d)\n\t\tres.push_back(d);\n\tif (s2) res.push_back(s2);\n\tfor (int i = 0; i < res.size() && res.size() + 1 < n;) {\n\t\tif (res[i] == 1) {\n\t\t    ++i;\n\t\t    continue;\n\t\t}\n\t\t--res[i];\n\t\tres.push_back(1);\n\t}\n\tres.push_back(d);\n}\n\nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tcin >> n >> s1 >> s2;\n\t\tsolve();\n\t\tsort(res.begin(), res.end());\n\t\tfor (int x: res)\n\t\t\tcout << x << ' ';\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1790",
    "index": "C",
    "title": "Premutation",
    "statement": "A sequence of $n$ numbers is called permutation if it contains all integers from $1$ to $n$ exactly once. For example, the sequences [$3, 1, 4, 2$], [$1$] and [$2,1$] are permutations, but [$1,2,1$], [$0,1$] and [$1,3,4$] — are not.\n\nKristina had a permutation $p$ of $n$ elements. She wrote it on the whiteboard $n$ times in such a way that:\n\n- while writing the permutation at the $i$-th ($1 \\le i \\le n)$ time she skipped the element $p_i$\n\nSo, she wrote in total $n$ sequences of length $n-1$ each.For example, suppose Kristina had a permutation $p$ = $[4,2,1,3]$ of length $4$. Then she did the following:\n\n- Wrote the sequence $[2, 1, 3]$, skipping the element $p_1=4$ from the original permutation.\n- Wrote the sequence $[4, 1, 3]$, skipping the element $p_2=2$ from the original permutation.\n- Wrote the sequence $[4, 2, 3]$, skipping the element $p_3=1$ from the original permutation.\n- Wrote the sequence $[4, 2, 1]$, skipping the element $p_4=3$ from the original permutation.\n\nYou know all $n$ of sequences that have been written on the whiteboard, but you do not know the order in which they were written. They are given in \\textbf{arbitrary order}. Reconstruct the original permutation from them.\n\nFor example, if you know the sequences $[4, 2, 1]$, $[4, 2, 3]$, $[2, 1, 3]$, $[4, 1, 3]$, then the original permutation will be $p$ = $[4, 2, 1, 3]$.",
    "tutorial": "When Kristina writes sequences on the whiteboard, she removes an element with each index exactly once. Thus, the first element of the permutation will be deleted only once - on the first step. All sequences except one will start with it To solve the problem, find a sequence $p_i$ such that: it starts with some element $y$ all sequences other than this one begin with some element $x$ Then this permutation will describe the sequence of numbers remaining after removing the $1$th element, and the first element itself will be equal to the number $x$. The initial permutation will look like [$x, y = p_{i1}, p_{i2}, \\dots, p_{in}$].",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\nint n;\n\nvoid solve(){\n    cin >> n;\n    vector<vector<int>>perm(n, vector<int>(n - 1));\n    vector<int>p(n, 0);\n    vector<int>cnt(n + 1, 0);\n    for(int i = 0; i < n; i++){\n        p[i] = i + 1;\n        for(int j = 0; j < n - 1; j++){\n            cin >> perm[i][j];\n            if(j == 0) cnt[perm[i][j]]++;\n        }\n    }\n    for(int i = 1; i <= n; i++){\n        if(cnt[i] == n - 1){\n            p[0] = i;\n            break;\n        }\n    }\n    for(int i = 0; i < n; i++){\n        if(perm[i][0] != p[0]){\n            for(int j = 0; j < n - 1; j++){\n                p[j + 1] = perm[i][j];\n            }\n        }\n    }\n    for(int i = 0; i < n; i++) cout << p[i] << ' ';\n    cout << endl;\n\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1790",
    "index": "D",
    "title": "Matryoshkas",
    "statement": "Matryoshka is a wooden toy in the form of a painted doll, inside which you can put a similar doll of a smaller size.\n\nA set of nesting dolls contains one or more nesting dolls, their sizes are consecutive positive integers. Thus, a set of nesting dolls is described by two numbers: $s$ — the size of a smallest nesting doll in a set and $m$ — the number of dolls in a set. In other words, the set contains sizes of $s, s + 1, \\dots, s + m - 1$ for some integer $s$ and $m$ ($s,m > 0$).\n\nYou had one or more sets of nesting dolls. Recently, you found that someone mixed all your sets in one and recorded a sequence of doll sizes — integers $a_1, a_2, \\dots, a_n$.\n\nYou do not remember how many sets you had, so you want to find the \\textbf{minimum} number of sets that you could initially have.\n\nFor example, if a given sequence is $a=[2, 2, 3, 4, 3, 1]$. Initially, there could be $2$ sets:\n\n- the first set consisting of $4$ nesting dolls with sizes $[1, 2, 3, 4]$;\n- a second set consisting of $2$ nesting dolls with sizes $[2, 3]$.\n\nAccording to a given sequence of sizes of nesting dolls $a_1, a_2, \\dots, a_n$, determine the minimum number of nesting dolls that can make this sequence.\n\nEach set is completely used, so all its nesting dolls are used. Each element of a given sequence must correspond to exactly one doll from some set.",
    "tutorial": "First, for each size, let's count $cnt_s$ - the number of dolls of this size. Then, let's create a set, in which for each doll of size $s$ we add the numbers $s$ and $s + 1$. This will allow you to process all the segments, as well as the dimensions adjacent to them. We will iterate over the set in ascending order of size. Let $x$ be the number of matryoshkas of the current size, $y$ - of the previous one considered ($0$ at the beginning). If the numbers do not match, then you need to close (if $x < y$), or open (if $x > y$) $|x - y|$ segments. It is enough to add only the opening of the segments to the answer.",
    "code": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    map<int, int> cnt;\n    set<int> b;\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n        cnt[a[i]]++;\n        b.insert(a[i]);\n        b.insert(a[i] + 1);\n    }\n    int last = 0;\n    int res = 0;\n    for (auto x: b) {\n        int c = cnt[x];\n        res += max(0, c - last);\n        last = c;\n    }\n    cout << res << '\\n';\n}\n\nint main(int argc, char* argv[]) {\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1790",
    "index": "E",
    "title": "Vlad and a Pair of Numbers",
    "statement": "Vlad found two positive numbers $a$ and $b$ ($a,b>0$). He discovered that $a \\oplus b = \\frac{a + b}{2}$, where $\\oplus$ means the bitwise exclusive OR , and division is performed without rounding..\n\nSince it is easier to remember one number than two, Vlad remembered only $a\\oplus b$, let's denote this number as $x$. Help him find any suitable $a$ and $b$ or tell him that they do not exist.",
    "tutorial": "Consider the answer by bits. We know that if the $i$th bit of the number $x$ is zero, then these bits are the same for $a$ and $b$, otherwise they differ. Then let's first make $a = x$, $b = 0$. Note that $a\\oplus b$ is already equal to $x$, but $\\frac{a+b}{2}$ is not yet. So we need to dial another $x$ with matching bits, we will add them to both integers greedily, going from the highest bit to the lowest, skipping those bits that are already one in $a$. If after this algorithm $a$ and $b$ do not satisfy the conditions, then the answer is $-1$. In total, this solution works for $\\mathcal{O}(\\log{x})$. You can see that in the solution above, we actually just added $\\frac{x}{2}$ to both numbers, which could only be done with one set of bits, so if the answer exists, the pair $a= \\frac{3\\cdot x}{2} fits$, $b = \\frac{x}{2}$.",
    "code": "t = int(input())\nfor _ in range(t):\n    x = int(input())\n    a = x\n    b = 0\n    for i in range(32, -1, -1):\n        if x & (1 << i) > 0:\n            continue\n        if 2 * x - a - b >= (2 << i):\n            a += 1 << i\n            b += 1 << i\n    if a + b == 2 * x and a ^ b == x:\n        print(a, b)\n    else:\n        print(-1)",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1790",
    "index": "F",
    "title": "Timofey and Black-White Tree",
    "statement": "Timofey came to a famous summer school and found a tree on $n$ vertices. A tree is a connected undirected graph without cycles.\n\nEvery vertex of this tree, except $c_0$, is colored \\textbf{white}. The vertex $c_0$ is colored \\textbf{black}.\n\nTimofey wants to color all the vertices of this tree in \\textbf{black}. To do this, he performs $n - 1$ operations. During the $i$-th operation, he selects the vertex $c_i$, which is currently \\textbf{white}, and paints it \\textbf{black}.\n\nLet's call the positivity of tree the minimum distance between all pairs of different \\textbf{black} vertices in it. The distance between the vertices $v$ and $u$ is the number of edges on the path from $v$ to $u$.\n\nAfter each operation, Timofey wants to know the positivity of the current tree.",
    "tutorial": "Let's store for each vertex the minimum distance from it to the nearest black one, let's call it $d[v]$. We will also store the global answer, which for obvious reasons does not increase, we will call it $ans$. Let's now color the vertex $c_i$, let's set $d[c_i] = 0$ and run a depth first search from it. This DFS will visit only the vertices $v$ with $d[v]<ans$. Let us consider the vertex $v$ and its neighbour $u$. If we can relax $d[u]$ through $d[v]+ 1$, let's do it and start from $u$. Otherwise, $u$ has a closer black neighbour, let's try to update the answer through it $ans = min(ans, d[v] +1 +d[u])$. Also, do not forget to update the answer via $d[v]$ from all black vertices $v$ that we visited. The correctness of the algorithm is obvious, let's evaluate its time complexity. It is easy to notice that after the first $\\lceil \\sqrt n\\rceil$ operations, $ans \\le\\lceil \\sqrt n\\rceil$. We enter only the vertices, $d$ from which, firstly, does not exceed $ans$, and secondly, was relaxed by the parent (that is, decreased by at least $1$). So, we allowed ourselves a complete tree bypassing for the first $\\lceil\\sqrt n\\rceil$ operations, and then amortized performed no more than $n\\lceil\\sqrt n\\rceil$ operations. The final asymptotics will be $O(n\\sqrt n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 200200;\nconst int INF = 1e9;\n\nint n, ANS = INF;\nint crr[MAXN], dist[MAXN], res[MAXN];\nbool clr[MAXN];\nvector<int> gr[MAXN];\n\nvoid init() {\n\tANS = INF;\n\tfor (int v = 0; v < n; ++v)\n\t\tgr[v].clear();\n\tfill(dist, dist + n, INF);\n\tmemset(clr, 0, n);\n}\n\nvoid dfs(int v, int p) {\n\tif (dist[v] >= ANS) return;\n\tif (clr[v]) ANS = min(ANS, dist[v]);\n\tfor (int u: gr[v]) {\n\t\tif (u == p) continue;\n\t\tif (dist[v] + 1 < dist[u]) {\n\t\t\tdist[u] = dist[v] + 1;\n\t\t\tdfs(u, v);\n\t\t} else ANS = min(ANS, dist[v] + 1 + dist[u]);\n\t}\n}\n\nvoid solve() {\n\tdist[*crr] = 0;\n\tdfs(*crr, -1);\n\tclr[*crr] = true;\n\tfor (int i = 1; i < n; ++i) {\n\t\tdist[crr[i]] = 0;\n\t\tdfs(crr[i], -1);\n\t\tclr[crr[i]] = true;\n\t\tres[i] = ANS;\n\t}\n}\n\nint main() {\n\tint gorilla; cin >> gorilla;\n\twhile (gorilla--) {\n\t\tcin >> n >> *crr, --(*crr);\n\t\tinit();\n\t\tfor (int i = 1; i < n; ++i)\n\t\t\tcin >> crr[i], --crr[i];\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tint v, u; cin >> v >> u, --v, --u;\n\t\t\tgr[v].push_back(u);\n\t\t\tgr[u].push_back(v);\n\t\t}\n\t\tsolve();\n\t\tfor (int i = 1; i < n; ++i)\n\t\t\tcout << res[i] << ' ';\n\t\tcout << '\\n';\n\t}\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "divide and conquer",
      "graphs",
      "greedy",
      "math",
      "shortest paths",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1790",
    "index": "G",
    "title": "Tokens on Graph",
    "statement": "You are given an undirected connected graph, some vertices of which contain tokens and/or bonuses. Consider a game involving one player  — you.\n\nYou can move tokens according to the following rules:\n\n- At the beginning of the game, you can make exactly one turn: move any token to any adjacent vertex.\n- If the movement of the token ended on the bonus, then you are allowed to make another turn with any \\textbf{other} token.\n\nYou can use different bonuses in any order. The same bonus can be used an unlimited number of times. Bonuses do not move during the game.\n\nThere can be several tokens in one vertex at the same time, but initially there is no more than one token in each vertex.\n\nThe vertex with number $1$ is the finish vertex, and your task is to determine whether it is possible to hit it with any token by making turns with the tiles according to the rules described above. If a token is initially located at the vertex of $1$, then the game is considered already won.\n\n\\begin{center}\n{\\small The finish line is in black, the bonuses are in red, the chips are in grey.}\n\\end{center}\n\nFor example, for a given graph, you can reach the finish line with a chip from the $8$th vertex by making the following sequence of turns:\n\n- Move from the $8$-th vertex to the $6$-th.\n- Move from the $7$-th vertex to the $5$-th.\n- Move from the $6$-th vertex to the $4$-th.\n- Move from the $5$-th vertex to the $6$-th.\n- Move from the $4$-th vertex to the $2$-nd.\n- Move from the $6$-th vertex to the $4$-th.\n- Move from the $2$-nd vertex to the $1$-st vertex, which is the finish.",
    "tutorial": "Let's calculate the shortest paths to the finish along the vertices containing bonuses. We will try to reach the finish line with the chip that is closest to it, and mark it. If there is none, we lose. Other chips will give her extra moves. Find all connected components from vertices containing bonuses. Then, for each component, we find all the tokens that are not selected, located at the vertex of this component, and at the vertices adjacent to at least one vertex of this component. Consider the size of the connectivity component. If it is equal to $1$, then the chip located in the neighboring vertex gives $1$ an additional move. Otherwise, the chip located at the top of the component or at the neighboring vertex, as well as the selected chip, will be able to move indefinitely in turn, which gives us a victory. Otherwise, you need to count the number of extra moves and compare it with the shortest distance to the finish line.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<int> token(n), boni(n);\n    vector<vector<int>> g(n);\n    vector<int> good(n);\n    int m;\n    cin >> m;\n    int p, b;\n    cin >> p >> b;\n    for(int i = 0; i < p; i++)\n    {\n        int x;\n        cin >> x;\n        --x;\n        token[x] = 1;\n    }\n    for(int i = 0; i < b; i++)\n    {\n        int x;\n        cin >> x;\n        --x;\n        boni[x] = 1;\n    }\n    for(int i = 0; i < m; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n        --x;\n        --y;\n        g[x].push_back(y);\n        g[y].push_back(x);\n    }\n    for(int i = 0; i < n; i++)\n        for(auto x : g[i])\n            if(boni[i] && boni[x]) good[i] = 1;\n    set<int> good_tokens;\n    set<int> not_so_good_tokens;\n    for(int i = 0; i < n; i++)\n        for(auto x : g[i])\n        {\n            if(token[i] && good[x]) good_tokens.insert(i);\n            else if(token[i] && boni[x]) not_so_good_tokens.insert(i);\n        }\n    vector<int> d(n, int(1e9));\n    queue<int> q;\n    d[0] = 0;\n    q.push(0);\n    while(!q.empty())\n    {\n        int k = q.front();\n        q.pop();\n        for(auto x : g[k])\n        {\n            if(d[x] > d[k] + 1)\n            {\n                d[x] = d[k] + 1;\n                if(boni[x]) q.push(x);\n            }\n        }\n    }\n    bool has_ans = false;\n    for(int i = 0; i < n; i++)\n    {\n        if(!token[i] || d[i] > n) continue;\n        has_ans |= (!good_tokens.empty() && (*good_tokens.begin() != i || *good_tokens.rbegin() != i));\n        int cnt = not_so_good_tokens.size();\n        if(not_so_good_tokens.count(i)) cnt--;\n        has_ans |= d[i] <= 1 + cnt;\n    }\n    cout << (has_ans ? \"YES\" : \"NO\") << endl;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n#endif\n    int tc = 1;\n    cin >> tc;\n    for(int i = 0; i < tc; i++)\n    {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1791",
    "index": "A",
    "title": "Codeforces Checking",
    "statement": "Given a lowercase Latin character (letter), check if it appears in the string $codeforces$.",
    "tutorial": "You need to implement what is written in the statement. You can either use an if-statement for each of the characters $\\{\\texttt{c}, \\texttt{o}, \\texttt{d}, \\texttt{e}, \\texttt{f}, \\texttt{r}, \\texttt{s}\\}$, or you can iterate through the string $\\texttt{codeforces}$ check if the current character equals $c$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst string s = \"codeforces\";\n\nvoid solve() {\n\tchar c;\n\tcin >> c;\n\tfor (char i : s) {\n\t\tif (i == c) {cout << \"YES\\n\"; return;}\n\t}\n\tcout << \"NO\\n\";\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1791",
    "index": "B",
    "title": "Following Directions",
    "statement": "Alperen is standing at the point $(0,0)$. He is given a string $s$ of length $n$ and performs $n$ moves. The $i$-th move is as follows:\n\n- if $s_i = L$, then move one unit left;\n- if $s_i = R$, then move one unit right;\n- if $s_i = U$, then move one unit up;\n- if $s_i = D$, then move one unit down.\n\n\\begin{center}\n{\\small If Alperen starts at the center point, he can make the four moves shown.}\n\\end{center}\n\nThere is a candy at $(1,1)$ (that is, one unit above and one unit to the right of Alperen's starting point). You need to determine if Alperen ever passes the candy. \\begin{center}\n{\\small Alperen's path in the first test case.}\n\\end{center}",
    "tutorial": "We can keep track of our current point $(x,y)$ as we iterate over the string: if $s_i = \\texttt{L}$, then decrement $x$ (set $x \\leftarrow x-1$); if $s_i = \\texttt{R}$, then increment $x$ (set $x \\leftarrow x+1$); if $s_i = \\texttt{U}$, then increment $y$ (set $y \\leftarrow y+1$); if $s_i = \\texttt{D}$, then decrement $y$ (set $y \\leftarrow y-1$). The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tint x = 0, y = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] == 'L') {x--;}\n\t\tif (s[i] == 'R') {x++;}\n\t\tif (s[i] == 'D') {y--;}\n\t\tif (s[i] == 'U') {y++;}\n\t\tif (x == 1 && y == 1) {cout << \"YES\\n\"; return;}\n\t}\t\n\tcout << \"NO\\n\";\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1791",
    "index": "C",
    "title": "Prepend and Append",
    "statement": "Timur initially had a binary string$^{\\dagger}$ $s$ (possibly of length $0$). He performed the following operation several (possibly zero) times:\n\n- Add $0$ to one end of the string and $1$ to the other end of the string. For example, starting from the string $1011$, you can obtain either $\\textcolor{red}{0}1011\\textcolor{red}{1}$ or $\\textcolor{red}{1}1011\\textcolor{red}{0}$.\n\nYou are given Timur's final string. What is the length of the \\textbf{shortest} possible string he could have started with?$^{\\dagger}$ A binary string is a string (possibly the empty string) whose characters are either $0$ or $1$.",
    "tutorial": "Let's perform the process in reverse: we will remove the first and last character of the string, if these two characters are different. We should do this as long as possible, since we need to find the shortest initial string. So the algorithm is straightfoward: keep track of the left and right characters, and if they are different, remove both. Otherwise, output the length of the current string (or output $0$ if the string became empty). There are a few ways to implement this. For example, you can keep two pointers, one at the beginning of the string and one at the end, say, $l=1$ and $r=n$, and check if $s_l=s_r$. If it's true, then we increment $l$ and decrement $r$. Otherwise, we output $r-l+1$. We stop when $l \\geq r$. Alternatively, you can use deque to simulate the operations directly. The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tint l = 0, r = n - 1, ans = n;\n\twhile (s[l] != s[r] && ans > 0) {l++; r--; ans -= 2;}\n\tcout << ans << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1791",
    "index": "D",
    "title": "Distinct Split",
    "statement": "Let's denote the $f(x)$ function for a string $x$ as the number of distinct characters that the string contains. For example $f(abc) = 3$, $f(bbbbb) = 1$, and $f(babacaba) = 3$.\n\nGiven a string $s$, split it into two non-empty strings $a$ and $b$ such that $f(a) + f(b)$ is the maximum possible. In other words, find the maximum possible value of $f(a) + f(b)$ such that $a + b = s$ (the concatenation of string $a$ and string $b$ is equal to string $s$).",
    "tutorial": "Let's check all splitting points $i$ for all ($1 \\leq i \\leq n - 1$). We denote a splitting point as the last index of the first string we take (and all the remaining characters will go to the second string). We need to keep a dynamic count of the number of distinct characters in both strings $a$ (the first string) and $b$ (the second string). We can do this using two frequency arrays (and adding one to the distinct count of either string $a$ or $b$ when the frequency of a character is greater than zero.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nvoid solve() {\n    int n; string s; cin >> n >> s;\n    vector<int> cnt(26, 0), p(26, 0);\n    for(auto x: s) cnt[x - 'a']++;\n    int ans = 0;\n    for(auto x: s) {\n        --cnt[x - 'a'];\n        ++p[x - 'a'];\n        int cur = 0;\n        for(int i = 0; i < 26; ++i) {\n            cur += min(1, cnt[i]) + min(1, p[i]);\n        }\n        ans = max(ans, cur);\n    }\n    cout << ans << \"\\n\";\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1791",
    "index": "E",
    "title": "Negatives and Positives",
    "statement": "Given an array $a$ consisting of $n$ elements, find the maximum possible sum the array can have after performing the following operation \\textbf{any number of times}:\n\n- Choose $2$ \\textbf{adjacent} elements and flip both of their signs. In other words choose an index $i$ such that $1 \\leq i \\leq n - 1$ and assign $a_i = -a_i$ and $a_{i+1} = -a_{i+1}$.",
    "tutorial": "We can notice that by performing any number of operations, the parity of the count of negative numbers won't ever change. Thus, if the number of negative numbers is initially even, we can make it equal to $0$ by performing some operations. So, for an even count of negative numbers, the answer is the sum of the absolute values of all numbers (since we can make all of them positive). And if the count of negative numbers is odd, we must have one negative number at the end. We will choose the one smallest by absolute value and keep the rest positive (for simplicity, we consider $-0$ as a negative number).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t; cin >> t;\n    while(t--) {\n        int n; cin >> n;\n        vector<int> a(n);\n        long long sum = 0;\n        int negs = 0;\n        for(int i = 0; i < n; ++i) {\n            cin >> a[i];\n            if(a[i] < 0) {\n                ++negs;\n                a[i] = -a[i];\n            }\n            sum += a[i];\n        }\n        sort(a.begin(), a.end());\n        if(negs & 1) sum -= 2 * a[0];\n        cout << sum << \"\\n\";\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1791",
    "index": "F",
    "title": "Range Update Point Query",
    "statement": "Given an array $a_1, a_2, \\dots, a_n$, you need to handle a total of $q$ updates and queries of two types:\n\n- $1$ $l$ $r$ — for each index $i$ with $l \\leq i \\leq r$, update the value of $a_i$ to the sum of the digits of $a_i$.\n- $2$ $x$ — output $a_x$.",
    "tutorial": "Let $S(n)$ denote the sum of the digits of $n$. The key observation is the following: after the operation is applied to index $i$ thrice, it won't change after any further operations. The proof$^{\\dagger}$ is provided at the bottom of the editorial. So we only need to update $a_i$ if it's been updated at most $2$ times so far; otherwise, we can ignore it. This allows us to do the following solution: store the current \"active\" indices (that is, indices that have been updated $\\leq 2$ times) in a sorted list (for example, set in C++). Then: $1$ $l$ $r$ - search for the smallest active index at least $l$ (since the list is sorted, we can do it in $\\mathcal{O}(\\log n)$). Afterwards, update that index (replace $a_i$ with $S(a_i)$), remove it if it's no longer active, and binary search for the next largest active index in the sorted list, until we pass $r$. $2$ $x$ - just output $a_x$. Therefore the time complexity is amortized $\\mathcal{O}(q + n \\log n)$. $^{\\dagger}$ To show this, note that initially $1 \\leq a_i \\leq 10^9$. The maximum possible value of the sum of the digits of $a_i$ is $81$, achieved when $a_i = 999{,}999{,}999$. So $1 \\leq S(a_i) \\leq 81$. Now considering the numbers from $1$ to $81$, the one with maximum sum of digits is $79$, with $S(79)=16$. Hence $1 \\leq S(S(a_i)) \\leq 16$. Finally, considering the numbers from $1$ to $16$, the one with maximum sum of digits is $9$, so $1 \\leq S(S(S(a_i))) \\leq 9$. That is, after three operations, $a_i$ becomes a single digit. Any further operations, and it won't change any more.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint digit_sum(int n) {\n    int ret = 0;\n    while(n) {\n        ret += n % 10;\n        n /= 10;\n    }\n    return ret;\n}\nvoid solve() {\n    int n, q; cin >> n >> q;\n    vector<int> a(n);\n    set<int> s;\n    for(int i = 0; i < n; ++i) {\n        cin >> a[i];\n        if(a[i] > 9) s.insert(i);\n    }\n    while(q--) {\n        int type; cin >> type;\n        if(type == 1) {\n            int l, r; cin >> l >> r; --l, --r;\n            int lst = l;\n            while(!s.empty()) {\n                auto it = s.lower_bound(lst);\n                if(it == s.end() || *it > r) break;\n                a[*it] = digit_sum(a[*it]);\n                int paiu = *it;\n                s.erase(it);\n                if(a[paiu] > 9) s.insert(paiu);\n                lst = paiu + 1;\n            }\n        } else {\n            int x; cin >> x; --x;\n            cout << a[x] << \"\\n\";\n        }\n    }\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tcout.tie(0);\n\tint t; cin >> t;\n\twhile(t--) {\n\t    solve();\n\t}\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1791",
    "index": "G1",
    "title": "Teleporters (Easy Version)",
    "statement": "\\textbf{The only difference between the easy and hard versions are the locations you can teleport to.}\n\nConsider the points $0, 1, \\dots, n$ on the number line. There is a teleporter located on each of the points $1, 2, \\dots, n$. At point $i$, you can do the following:\n\n- Move left one unit: it costs $1$ coin.\n- Move right one unit: it costs $1$ coin.\n- Use a teleporter at point $i$, if it exists: it costs $a_i$ coins. As a result, you teleport to point $0$. Once you use a teleporter, you \\textbf{can't} use it again.\n\nYou have $c$ coins, and you start at point $0$. What's the most number of teleporters you can use?",
    "tutorial": "It's easy to see that it's optimal to only move right or to use a portal once we are at it. We can notice that when we teleport back, the problem is independent of the previous choices. We still are at point $0$ and have some portals left. Thus, we can just find out the individual cost of each portal, sort portals by individual costs, and take them from smallest to largest by cost as long as we can. The cost of portal $i$ is $i + a_i$ (since we pay $a_i$ to use it and need $i$ moves to get to it).",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nvoid solve() {\n    int n, c, ans = 0; cin >> n >> c;\n    priority_queue<int> q;\n    for(int i = 1, x; i <= n; ++i) {\n        cin >> x;\n        q.push(-x - i);\n    }\n    while(!q.empty()) {\n        int x = -q.top(); q.pop();\n        if(x > c) break;\n        ++ans;\n        c -= x;\n    }\n    cout << ans << \"\\n\";\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1791",
    "index": "G2",
    "title": "Teleporters (Hard Version)",
    "statement": "\\textbf{The only difference between the easy and hard versions are the locations you can teleport to.}\n\nConsider the points $0,1,\\dots,n+1$ on the number line. There is a teleporter located on each of the points $1,2,\\dots,n$. At point $i$, you can do the following:\n\n- Move left one unit: it costs $1$ coin.\n- Move right one unit: it costs $1$ coin.\n- Use a teleporter at point $i$, if it exists: it costs $a_i$ coins. As a result, you can choose whether to teleport to point $0$ or point $n+1$. Once you use a teleporter, you \\textbf{can't} use it again.\n\nYou have $c$ coins, and you start at point $0$. What's the most number of teleporters you can use?",
    "tutorial": "Please also refer to the tutorial for the easy version. If we are not at the first taken portal, the problem is still independent for each portal, but this time the cost of a portal is $min(a_i + i, a_i + n + 1 - i)$ (since we can come to a portal either from point $0$ or point $n+1$). So, we again sort the portals by their costs. But this time, we need to make sure that the first taken portal is taken from point $0$, so we will iterate over all portals and check the maximum amount of portals we can take if we use it as the first one. We can check this using prefix sums over the minimum cost array and binary searching, checking if the amount of considered portals taken doesn't exceed the number of coins we initially have (we also have to deal with the case when the portal we are considering is included both times as the initial portal and in the minimum cost prefix).",
    "code": "#include <bits/stdc++.h>\n#define startt ios_base::sync_with_stdio(false);cin.tie(0);\ntypedef long long  ll;\nusing namespace std;\n#define vint vector<int>\n#define all(v) v.begin(), v.end()\n#define MOD 1000000007\n#define MOD2 998244353\n#define MX 1000000000\n#define MXL 1000000000000000000\n#define PI (ld)2*acos(0.0)\n#define pb push_back\n#define sc second\n#define fr first\n#define int long long\n#define endl '\\n'\n#define ld long double\n#define NO cout << \"NO\" << endl\n#define YES cout << \"YES\" << endl\nint ceildiv(int one, int two) {if (one % two == 0) {return one / two;}else {return one / two + 1;}} int power(int n, int pow, int m) {if (pow == 0) return 1;if (pow % 2 == 0) {ll x = power(n, pow / 2, m);return (x * x) % m;}else return (power(n, pow - 1, m) * n) % m;} int gcd(int a, int b) { if (!b)return a; return gcd(b, a % b);} int factorial(int n, int mod) {if (n > 1)return (n * factorial(n - 1, mod)) % mod; else return 1;} int lcm(int a, int b) {return (a * b) / gcd(a, b);} vector<int> read(int n) {vector<int> a; for (int i = 0; i < n; i++) { int x; cin >> x; a.pb(x);} return a;}struct prefix_sum{vint pref;void build(vint a){pref.pb(0);for(int i = 0; i < a.size(); i++){pref.pb(pref.back()+a[i]);}}int get(int l, int r){return pref[r]-pref[l-1];}};//mesanu\n\nvoid solve()\n{\n    int n, c;\n    cin >> n >> c;\n    vector<pair<int, int>> a;\n    for(int i = 0; i < n; i++)\n    {\n        int x;\n        cin >> x;\n        a.pb({x+min(i+1, n-i), x+i+1});\n    }\n    sort(all(a));\n    vector<int> pref;\n    pref.pb(0);\n    for(int i = 0; i < n; i++)\n    {\n        pref.pb(pref.back()+a[i].fr);\n    }\n    int ans = 0;\n    for(int i = 0; i < n; i++)\n    {\n        int new_c = c-a[i].sc;\n        int l = 0, r = n;\n        int mx = 0;\n        while(l <= r)\n        {\n            int mid = l+r>>1;\n            // Calculate price\n            int price = pref[mid];\n            int now = mid+1;\n            if(mid > i)\n            {\n                price-=a[i].fr;\n                now--;\n            }\n            if(price <= new_c)\n            {\n                mx = max(now, mx);\n                l = mid+1;\n            }\n            else\n            {\n                r = mid-1;\n            }\n        }\n        ans = max(ans, mx);\n    }\n    cout << ans << endl;\n}\n\nint32_t main(){\n    startt\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1792",
    "index": "A",
    "title": "GamingForces",
    "statement": "Monocarp is playing a computer game. He's going to kill $n$ monsters, the $i$-th of them has $h_i$ health.\n\nMonocarp's character has two spells, either of which he can cast an arbitrary number of times (possibly, zero) and in an arbitrary order:\n\n- choose exactly two alive monsters and decrease their health by $1$;\n- choose a single monster and kill it.\n\nWhen a monster's health becomes $0$, it dies.\n\nWhat's the minimum number of spell casts Monocarp should perform in order to kill all monsters?",
    "tutorial": "The first spell looks pretty weak compared to the second spell. Feels like you almost always replace one with another. Let's show that you can totally avoid casting the spell of the first type twice or more on one monster. Let the two first spell casts be $(i, j)$ and $(i, k)$ for some monsters $i, j$ and $k$. You can replace them by a cast of the second spell on $i$ and a cast of the first spell on $(j, k)$. That would deal even more damage to $i$ and the same amount to $j$ and $k$. The number of casts doesn't change. Thus, it only makes sense to use the first spell on monsters with $1$ health. Calculate the number of them, kill the full pairs of them with the first spell, and use the second spell on the remaining monsters. Overall complexity: $O(n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    int cnt1 = 0;\n    for (int i = 0; i < n; ++i) {\n      int x;\n      cin >> x;\n      cnt1 += (x == 1);\n    }\n    cout << n - cnt1 / 2 << '\\n';\n  }\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1792",
    "index": "B",
    "title": "Stand-up Comedian",
    "statement": "Eve is a beginner stand-up comedian. Her first show gathered a grand total of two spectators: Alice and Bob.\n\nEve prepared $a_1 + a_2 + a_3 + a_4$ jokes to tell, grouped by their type:\n\n- type 1: both Alice and Bob like them;\n- type 2: Alice likes them, but Bob doesn't;\n- type 3: Bob likes them, but Alice doesn't;\n- type 4: neither Alice nor Bob likes them.\n\nInitially, both spectators have their mood equal to $0$. When a spectator hears a joke he/she likes, his/her mood increases by $1$. When a spectator hears a joke he/she doesn't like, his/her mood decreases by $1$. If the mood of a spectator becomes negative (strictly below zero), he/she leaves.\n\nWhen someone leaves, Eve gets sad and ends the show. If no one leaves, and Eve is out of jokes, she also ends the show.\n\nThus, Eve wants to arrange her jokes in such a way that the show lasts as long as possible. Help her to calculate the maximum number of jokes she can tell before the show ends.",
    "tutorial": "First, let Eve tell the jokes of the first type - they will never do any harm. At the same time, let her tell the jokes of the fourth time at the very end - they will not do any good. Types two and three are kind of opposites of each other. If you tell jokes of each of them one after another, then the moods of both spectators don't change. Let's use that to our advantage. Tell the jokes of these types in pairs until one of them runs out. There's a little corner case here, though. If there were no jokes of the first type, then you can't use a single pair because of the spectators leaves after one joke. Finally, try to tell the remaining jokes of the same type before the fourth type. So the construction looks like $1, 1, \\dots, 1, 2, 3, 2, 3, \\dots, 2, 3, 2, 2, 2, \\dots, 2, 4, 4, 4, \\dots, 4$ with $2$ and $3$ possibly swapped with each other. Let's recover the answer from that construction. After the first type, both moods are $a_1$. After the alternating jokes, the moods are still the same. After that, one of the spectators will have his/her mood only decreasing until the end. Once it reaches $-1$, the show ends. Thus, Eve can tell $a_1 + min(a_2, a_3) \\cdot 2 + min(a_1 + 1, abs(a_2 - a_3) + a_4)$ jokes if $a_1 \\neq 0$. Otherwise, it's always $1$. Overall complexity: $O(1)$.",
    "code": "for _ in range(int(input())):\n    a1, a2, a3, a4 = map(int, input().split())\n    if a1 == 0:\n        print(1)\n    else:\n        print(a1 + min(a2, a3) * 2 + min(a1 + 1, abs(a2 - a3) + a4))",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1792",
    "index": "C",
    "title": "Min Max Sort",
    "statement": "You are given a permutation $p$ of length $n$ (a permutation of length $n$ is an array of length $n$ in which each integer from $1$ to $n$ occurs exactly once).\n\nYou can perform the following operation any number of times (possibly zero):\n\n- choose two different elements $x$ and $y$ and erase them from the permutation;\n- insert the minimum of $x$ and $y$ into the permutation in such a way that it becomes the first element;\n- insert the maximum of $x$ and $y$ into the permutation in such a way that it becomes the last element.\n\nFor example, if $p = [1, 5, 4, 2, 3]$ and we want to apply the operation to the elements $3$ and $5$, then after the first step of the operation, the permutation becomes $p = [1, 4, 2]$; and after we insert the elements, it becomes $p = [3, 1, 4, 2, 5]$.\n\nYour task is to calculate the minimum number of operations described above to sort the permutation $p$ in ascending order (i. e. transform $p$ so that $p_1 < p_2 < \\dots < p_n$).",
    "tutorial": "If the array is already sorted, then the answer is $0$. Otherwise, there is a last operation, after which the permutation takes the form $1, 2, \\dots, n$. Which means that the elements $1$ and $n$ are selected as the last operation (because they are at the first and last positions after the operation). Now we know that the last operation is $(1, n)$ and it doesn't matter where exactly these numbers are in the permutation, i. e. we can assume that the answer has increased by $1$, and consider only the numbers $2, 3, \\dots, n-2, n-$1. Similarly, for the \"remaining\" permutation, there are two options, either it is sorted, and then the answer is $1$, or there is a last operation and the numbers $2$ and $n-1$ are used in it. And so on until the \"remaining\" permutation is sorted or empty. It remains to find out how to quickly check whether the numbers in the segment $[k, n - k + 1]$ are sorted (they go in the correct order in the initial permutation). Note that this segment corresponds to values of elements, not to positions in the permutation. If this segment is sorted for some $k$, then the answer does not exceed $k-1$. There are several ways to check, let's consider one of them. Note that if the segment $[k, n - k + 1]$ is sorted for some value $k$, then it will be sorted for large values as well. So we can start with the maximum value of $k$ (which is equal to $\\left\\lfloor\\frac{n+1}{2}\\right\\rfloor$) and decrease it until the segment remains sorted. Now for each $k$ we need only two checks that $pos_k$ < $pos_{k + 1}$ and $pos_{n - k + 1}$ > $pos_{n - (k + 1) + 1}$, where $pos_i$ is the position of the element $i$ in the permutation. Thus, we got the solution in linear time. Another way is to run binary search on $k$ since if the numbers in $[k, n - k + 1]$ appear in the permutation in sorted order, the same holds for $k+1$. This approach yields a solution in $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> pos(n + 1);\n    for (int i = 0; i < n; ++i) {\n      int x;\n      cin >> x;\n      pos[x] = i;\n    }\n    int l = (n + 1) / 2, r = (n + 2) / 2;\n    while (l > 0 && (l == r || (pos[l] < pos[l + 1] && pos[r - 1] < pos[r]))) {\n      --l;\n      ++r;\n    }\n    cout << (n - r + l + 1) / 2 << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1792",
    "index": "D",
    "title": "Fixed Prefix Permutations",
    "statement": "You are given $n$ permutations $a_1, a_2, \\dots, a_n$, each of length $m$. Recall that a permutation of length $m$ is a sequence of $m$ distinct integers from $1$ to $m$.\n\nLet the beauty of a permutation $p_1, p_2, \\dots, p_m$ be the largest $k$ such that $p_1 = 1, p_2 = 2, \\dots, p_k = k$. If $p_1 \\neq 1$, then the beauty is $0$.\n\nThe product of two permutations $p \\cdot q$ is a permutation $r$ such that $r_j = q_{p_j}$.\n\nFor each $i$ from $1$ to $n$, print the largest beauty of a permutation $a_i \\cdot a_j$ over all $j$ from $1$ to $n$ (possibly, $i = j$).",
    "tutorial": "Let's try to solve for one of the given permutations. Let it be some $p$. How to make the answer for it at least $1$? Well, we have to find another permutation $q$ such that $p \\cdot q = (1, r_2, r_3, \\dots, r_m)$. How about at least $k$? Well, the same: $p \\cdot q = (1 2 \\dots, k, r_{k+1}, \\dots, r_m)$. Push $q$ to the right side of the equation. $p = (1 2 \\dots, k, r_{k+1}, \\dots, r_m) \\cdot q^{-1}$. Now think. What does it actually mean for some permutation to be multiplied by $(1, 2, \\dots, k)$? It stays the same. So the first $k$ elements of $p$ will be equal to the first $k$ elements of $q^{-1}$. Thus, you have to find a permumtation such that its inverse has the longest common prefix with $p$. This can be done in multiple ways. For example, you can store all inverses in a trie and traverse it with $p$ until you reach a dead end. Or simply push all prefixes of each inverse into a set and iterate over $k$. Alternatively, you can just sort inverses and do lower_bound for $p$ in this list - the permutation with longest common prefix will be either the result or the one before it. Overall complexity: $O(nm)/O(nm \\log n)/O(nm^2 \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nint get(const vector<int> &a, const vector<int> &b){\n\tint res = 0;\n\twhile (res < int(a.size()) && a[res] == b[res])\n\t\t++res;\n\treturn res;\n}\n\nint main(){\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--){\n\t\tint n, m;\n\t\tscanf(\"%d%d\", &n, &m);\n\t\tvector<vector<int>> a(n, vector<int>(m));\n\t\tforn(i, n) forn(j, m){\n\t\t\tscanf(\"%d\", &a[i][j]);\n\t\t\t--a[i][j];\n\t\t}\n\t\tvector<vector<int>> b(n, vector<int>(m));\n\t\tforn(i, n) forn(j, m) b[i][a[i][j]] = j;\n\t\tsort(b.begin(), b.end());\n\t\tforn(i, n){\n\t\t\tint j = lower_bound(b.begin(), b.end(), a[i]) - b.begin();\n\t\t\tint ans = 0;\n\t\t\tif (j > 0) ans = max(ans, get(a[i], b[j - 1]));\n\t\t\tif (j < n) ans = max(ans, get(a[i], b[j]));\n\t\t\tprintf(\"%d \", ans);\n\t\t}\n\t\tputs(\"\");\n\t}\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "hashing",
      "math",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1792",
    "index": "E",
    "title": "Divisors and Table",
    "statement": "You are given an $n \\times n$ multiplication table and a positive integer $m = m_1 \\cdot m_2$. A $n \\times n$ multiplication table is a table with $n$ rows and $n$ columns numbered from $1$ to $n$, where $a_{i, j} = i \\cdot j$.\n\nFor each divisor $d$ of $m$, check: does $d$ occur in the table at least once, and if it does, what is the minimum row that contains $d$.",
    "tutorial": "Firstly, let's factorize $m$. Since $m = m_1 \\cdot m_2$ we can factorize $m_1$ and $m_2$ separately and then \"unite\" divisors. For example, use can get canonical representations of $m_1 = p_1^{f_1} p_2^{f_2} \\dots p_k^{f_k}$ and $m_2 = p_1^{g_1} p_2^{g_2} \\dots p_k^{g_k}$ to get canonical representation of $m = p_1^{f_1 + g_1} p_2^{f_2 + g_2} \\dots p_k^{f_k + g_k}$ and then use it to generate all divisors of $m$. Let's estimate the number of divisors $divs(m)$. It's convenient for our purposes to estimate it as $O(m^{\\frac{1}{3}})$. More precisely, there are at most $105\\,000$ divisors for $m \\le 10^{18}$ (search \"Highly Composite Numbers\" for more info). How to calculate the answer $a_i$ for each divisor $d$? There are two ways. The intended solution: for each $d$ we are searching for the minimum $x$ that $d = x y$ and $y \\le n$. Since $d$ is fixed, the minimum $x$ means the maximum $y \\le n$. So let's find $y$ instead. In other words, for each $d$ we need to find the maximum $y$ such that $y$ divides $d$ and $y \\le n$. We can do it efficiently with $dp$ on divisors. Let $dp[d]$ be the maximum $y$ that is a divisor of $d$ and $y \\le n$. If $d \\le n$ then, obviously, $dp[d] = d$. Otherwise, we know that we are searching $y < d$. Let say that $p_1, p_2, \\dots, p_k$ are the prime divisors of the initial number $m$. Since $y$ is a divisor of $d$ and $y < d$ then exists some $p_i$ among the set of prime divisors such that $y$ is a divisor of $\\frac{d}{p_i}$ as well. So, instead of brute search, it's enough to take a value $dp[\\frac{d}{p_i}]$. In other words, if $d > n$ we can calculate $dp[d] = \\max\\limits_{p_i | d}{dp[\\frac{d}{p_i}]}$. Ok, now we know value $dp[d]$ for each divisor $d$. Since we found the maximum $y \\le n$, the last step is to calculate the desired $x = \\frac{d}{dp[d]}$ and if $x \\le n$ we found the answer $a_i$, otherwise ($x > n$) it means that $d$ is not presented $n \\times n$ table and $a_i = 0$. The total complexity is $O(\\sqrt{m_1 + m_2} + divs(m) \\cdot z(m) \\cdot \\log(divs(m)))$ per test, where $divs(m)$ is the number of divisors of $m$ ($divs(m) \\le 105\\,000$) and $z(m)$ is the number of prime divisor of $m$ ($z(m) \\le 15$). Note that complexity is quite high, so you should write it at least a little accurate, for example store $dp[d]$ in an array, not map, and search position of $dp[\\frac{d}{p_i}]$ with $lower\\_bound()$. There is also a way to get rid of extra $\\log(divs(m))$ factor if you iterate through $dp$ is a smart way. The alternative solution (faster, easier, unproven): Let's generate a list of all divisors of $m$ as $d_1, d_2, \\dots, d_l$ in the increasing order. For some divisor $d_i$ we are searching the minimum $x$ that is a divisor of $d_i$ and $\\frac{d_i}{x} \\le n$. It means that $x \\ge \\left\\lceil \\frac{d_i}{n} \\right\\rceil$. So let's just find the first position $j$ such that $d_j \\ge \\left\\lceil \\frac{d_i}{n} \\right\\rceil$ with $lower\\_bound$ and start iterating from $j$ onward searching the first $d_j$ that is a divisor of $d_i$. The found $d_j$ would be the minimum $x$ we need. It looks like, in average, we will find the correct $d_j$ quite fast, or we'll break when $d_j > n$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \" \";\n\t\tout << v[i];\n\t}\n\treturn out;\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n\nint n;\nli m1, m2;\n\ninline bool read() {\n\tif(!(cin >> n >> m1 >> m2))\n\t\treturn false;\n\treturn true;\n}\n\nvector<pt> mFact;\nvector<li> divs;\n\nvoid factM(li m1, li m2) {\n\tmFact.clear();\n\n\tfor (int d = 2; d * d <= m1 || d * d <= m2; d++) {\n\t\tint cnt = 0;\n\t\twhile (m1 % d == 0) {\n\t\t\tm1 /= d;\n\t\t\tcnt++;\n\t\t}\n\t\twhile (m2 % d == 0) {\n\t\t\tm2 /= d;\n\t\t\tcnt++;\n\t\t}\n\t\tif (cnt > 0)\n\t\t\tmFact.push_back({d, cnt});\n\t}\n\tif (m1 > m2)\n\t\tswap(m1, m2);\n\tif (m1 > 1)\n\t\tmFact.push_back({m1, 1});\n\tif (m2 > 1) {\n\t\tif (m2 == m1)\n\t\t\tmFact.back().y++;\n\t\telse\n\t\t\tmFact.push_back({m2, 1});\n\t}\n}\n\nvoid genDivisors(int pos, li val) {\n\tif (pos >= sz(mFact)) {\n\t\tdivs.push_back(val);\n\t\treturn;\n\t}\n\tli cur = val;\n\tfore (pw, 0, mFact[pos].y + 1) {\n\t\tgenDivisors(pos + 1, cur);\n\t\tif (pw < mFact[pos].y)\n\t\t\tcur *= mFact[pos].x;\n\t}\n}\n\ninline void solve() {\n\tfactM(m1, m2);\n\n\tdivs.clear();\n\tgenDivisors(0, 1);\n\tsort(divs.begin(), divs.end());\n\n\tvector<int> ans(sz(divs), 0);\n\n\tvector<li> dp(sz(divs), -1);\n\tfore (id, 0, sz(divs)) {\n\t\tif (divs[id] <= n)\n\t\t\tdp[id] = divs[id];\n\t\tfor (auto [p, pw] : mFact) {\n\t\t\tif (divs[id] % p != 0)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tint pos = int(lower_bound(divs.begin(), divs.end(), divs[id] / p) - divs.begin());\n\t\t\tdp[id] = max(dp[id], dp[pos]);\n\t\t}\n\n\t\tif (divs[id] / dp[id] <= n)\n\t\t\tans[id] = divs[id] / dp[id];\n\t}\n\n\tint cnt = 0;\n\tint xorSum = 0;\n\tfore (i, 0, sz(ans)) {\n\t\tcnt += ans[i] > 0;\n\t\txorSum ^= ans[i];\n\t}\n\t\n//\tcout << sz(ans) << endl;\n//\tcout << ans << endl;\n\tcout << cnt << \" \" << xorSum << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\n\tint t; cin >> t;\n\t\n\twhile (t--) {\n\t\t\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1792",
    "index": "F1",
    "title": "Graph Coloring (easy version)",
    "statement": "\\textbf{The only difference between the easy and the hard version is the constraint on $n$.}\n\nYou are given an undirected complete graph on $n$ vertices. A complete graph is a graph where each pair of vertices is connected by an edge. You have to paint the edges of the graph into two colors, red and blue (each edge will have one color).\n\nA set of vertices $S$ is \\textbf{red-connected} if, for every pair of vertices $(v_1, v_2)$ such that $v_1 \\in S$ and $v_2 \\in S$, there exists a path from $v_1$ to $v_2$ that goes only through red edges and vertices from $S$. Similarly, a set of vertices $S$ is \\textbf{blue-connected} if, for every pair of vertices $(v_1, v_2)$ such that $v_1 \\in S$ and $v_2 \\in S$, there exists a path from $v_1$ to $v_2$ that goes only through blue edges and vertices from $S$.\n\nYou have to paint the graph in such a way that:\n\n- there is at least one red edge;\n- there is at least one blue edge;\n- for each set of vertices $S$ such that $|S| \\ge 2$, $S$ is either red-connected or blue-connected, but \\textbf{not both}.\n\nCalculate the number of ways to paint the graph, and print it modulo $998244353$.",
    "tutorial": "Lemma: if an undirected graph is disconnected, then its complement is connected. Similarly, if its complement is disconnected, then the graph itself is connected. Proof: suppose a graph is disconnected. Pick two vertices $x$ and $y$ from different components. Every vertex outside of $x$'s component is connected to $x$ in the complement, and every vertex outside of $y$'s component is connected to $y$ in the complement; the complement also contains the edge from $x$ to $y$, so all vertices in the complement graph belong to the single component. Why do we need this lemma at all? We can treat the graph formed by blue edges as the complement to the graph formed by red edges. So, if the \"red\" graph is disconnected, then the \"blue\" graph is connected, so we don't need to consider the case when some set of vertices is connected by neither color. We only need to make sure that no set of vertices is connected by both colors. Let $A_n$ be the answer for $n$. Every graph counted in $A_n$ is either red-disconnected or blue-disconnected; since there is a bijection between red-disconnected and blue-disconnected graphs (you can flip the colors of all edges to transform one type into the other), we will count only red-disconnected graphs and multiply it by $2$. Let $B_n$ be the number of blue-connected graphs with $n$ vertices meeting the properties of the problem statement. It's easy to see that $A_n = 2 \\cdot B_n$ if $n > 1$, otherwise $A_n = B_n$ (the case $n = 1$ is special because a graph on one vertex is both red-connected and blue-connected). To calculate $A_n$, let's iterate on $k$ - the number of vertices which are in the same \"red\" component as $1$. This component must be a red-connected graph which meets the problem statement, so the number of ways to build the graph on these $k$ vertices is $B_k$; there are $\\frac{(n-1)!}{(k-1)!(n-k)!}$ ways to choose the vertices in the same component as $1$, and the remaining graph can be either red-connected or blue-connected, so the number of ways to build the remaining graph is $A_{n-k}$. Thus, we get the following two relations: $B_{n} = \\sum\\limits_{k=1}^{n-1} B_k A_{n-k} \\frac{(n-1)!}{(k-1)!(n-k)!}$ $A_n = 2 \\cdot B_n \\textrm{ if } n>1 \\textrm{, otherwise } B_n$ We can calculate all values with dynamic programming using these formulas in $O(n^2)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n\nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n\nint varMul(int x)\n{\n    return x;\n}\n\ntemplate<typename... Args>\nint varMul(int x, Args... args)\n{\n    return mul(x, varMul(args...));\n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y)\n    {\n        if(y & 1) z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nvector<int> fact, rfact;\nvector<int> dp;\nint n;\n\nvoid precalc()\n{\n    fact.resize(n + 1);\n    rfact.resize(n + 1);\n    fact[0] = 1;\n    for(int i = 1; i <= n; i++)\n        fact[i] = mul(i, fact[i - 1]);\n    for(int i = 0; i <= n; i++)\n        rfact[i] = binpow(fact[i], MOD - 2);\n    dp.resize(n + 1, -1);\n}\n\nint C(int n, int k)\n{\n    if(n < 0 || n < k || k < 0) return 0;\n    return varMul(fact[n], rfact[k], rfact[n - k]);\n}\n\nint calc(int x)\n{\n    if(dp[x] != -1) return dp[x];\n    if(x == 1) return dp[x] = 1;\n    if(x == 2) return dp[x] = 1;\n    dp[x] = 0;\n    int& d = dp[x];\n    for(int i = 1; i < x; i++)\n    {\n        d = add(d, varMul(calc(i), (i == x - 1 ? (MOD + 1) / 2 : calc(x - i)), 2, C(x - 1, i - 1)));\n    }   \n    return d;\n}\n\nint main()\n{\n    cin >> n;\n    precalc();\n    cout << add(mul(calc(n), 2), -2) << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1792",
    "index": "F2",
    "title": "Graph Coloring (hard version)",
    "statement": "\\textbf{The only difference between the easy and the hard version is the constraint on $n$.}\n\nYou are given an undirected complete graph on $n$ vertices. A complete graph is a graph where each pair of vertices is connected by an edge. You have to paint the edges of the graph into two colors, red and blue (each edge will have one color).\n\nA set of vertices $S$ is \\textbf{red-connected} if, for every pair of vertices $(v_1, v_2)$ such that $v_1 \\in S$ and $v_2 \\in S$, there exists a path from $v_1$ to $v_2$ that goes only through red edges and vertices from $S$. Similarly, a set of vertices $S$ is \\textbf{blue-connected} if, for every pair of vertices $(v_1, v_2)$ such that $v_1 \\in S$ and $v_2 \\in S$, there exists a path from $v_1$ to $v_2$ that goes only through blue edges and vertices from $S$.\n\nYou have to paint the graph in such a way that:\n\n- there is at least one red edge;\n- there is at least one blue edge;\n- for each set of vertices $S$ such that $|S| \\ge 2$, $S$ is either red-connected or blue-connected, but \\textbf{not both}.\n\nCalculate the number of ways to paint the graph, and print it modulo $998244353$.",
    "tutorial": "Please read the tutorial for the easy version first, since this tutorial uses some definitions from it. Okay, we need more definitions. Here they come: $C_0 = 0, C_i = \\frac{A_i}{i!} \\textrm{ if } i > 0$ $D_0 = 0, D_i = \\frac{B_i}{(i-1)!} \\textrm{ if } i > 0$ This way, we can transform the formula for $B_n$ to the following: $B_n = (n-1)! \\cdot \\sum\\limits_{k=1}^{n-1} C_{n-k} D_k$ Or even this, since $C_0 = D_0 = 0$: $B_n = (n-1)! \\cdot \\sum\\limits_{k=0}^{n} C_{n-k} D_k$ This is almost the convolution of the sequences $C$ and $D$ (with a bit extra additional operations after the convolution), so, to compute the sequence $B$, we just need to compute the sequences $C$ and $D$, and then calculate their convolution with NTT. All that's left is to multiply every element by the corresponding factorial. But wait, that's not so easy. In order to calculate $C_i$ and $D_i$, we need to know $B_i$. Note that we can ignore the fact that $C_i$ and $D_i$ appear in the formula for $B_i$, since they are multiplied by $0$, so at least we don't have a dependency cycle. Unfortunately, we cannot just straightforwardly use convolution if we don't know the sequences $C_i$ and $D_i$. The model solution handles it using the following approach. Let's generate $A$, $B$, $C$ and $D$ in parallel: on the $i$-th iteration, calculate $B_i$, then calculate $A_i$, $C_i$ and $D_i$ using it. And sometimes we will calculate the convolution of the sequences $C$ and $D$. Suppose we want to calculate $B_i$, and the last time we calculated the convolution of $C$ and $D$ was after the iteration $t$. Back then, we knew all elements from $C_0$ to $C_t$ and from $D_0$ to $D_t$. So, the $i$-th term in the convolution of $C$ and $D$ contained the sum of $C_{i-k} D_k$ over all $k$ such that $k \\le t$ and $i - k \\le t$. So, in order to calculate $B_i$, we have to pick this value from the convolution and then add the sum of $C_{i-k} D_k$ over all $k$ such that $k > t$ or $k \\le i - t$, and there are $2(i-t)$ such values. Suppose we compute the convolution every $K$ iterations. Then the maximum value of $i-t$ is $K$, and every value of $B_i$ is calculated in $O(K)$. We also make $\\frac{n}{K}$ convolutions, so the total complexity of this solution will be $O(\\frac{n^2 \\log n}{K} + nK)$, which can be transformed into $O(n \\sqrt{n \\log n})$ if we pick $K = \\sqrt{n \\log n}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int LOGN = 18;\nconst int N = (1 << LOGN);\nconst int MOD = 998244353;\nconst int g = 3;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++)\n\ninline int mul(int a, int b)\n{\n    return (a * 1ll * b) % MOD;\n}\n\ninline int norm(int a) \n{\n    while(a >= MOD)\n        a -= MOD;\n    while(a < 0)\n        a += MOD;\n    return a;\n}\n\ninline int binPow(int a, int k) \n{\n    int ans = 1;\n    while(k > 0) \n    {\n        if(k & 1)\n            ans = mul(ans, a);\n        a = mul(a, a);\n        k >>= 1;\n    }\n    return ans;\n}\n\ninline int inv(int a) \n{\n    return binPow(a, MOD - 2);\n}\n\nvector<int> w[LOGN];\nvector<int> iw[LOGN];\nvector<int> rv[LOGN];\n\nvoid precalc() \n{\n    int wb = binPow(g, (MOD - 1) / (1 << LOGN));\n    \n    for(int st = 0; st < LOGN; st++) \n    {\n        w[st].assign(1 << st, 1);\n        iw[st].assign(1 << st, 1);\n        \n        int bw = binPow(wb, 1 << (LOGN - st - 1));\n        int ibw = inv(bw);\n        \n        int cw = 1;\n        int icw = 1;\n        \n        for(int k = 0; k < (1 << st); k++) \n        {\n            w[st][k] = cw;\n            iw[st][k] = icw;\n            \n            cw = mul(cw, bw);\n            icw = mul(icw, ibw);\n        }\n        \n        rv[st].assign(1 << st, 0);\n        \n        if(st == 0) \n        {\n            rv[st][0] = 0;\n            continue;\n        }\n        int h = (1 << (st - 1));\n        for(int k = 0; k < (1 << st); k++)\n            rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h);\n    }\n}\n\ninline void fft(int a[N], int n, int ln, bool inverse) \n{   \n    for(int i = 0; i < n; i++) \n    {\n        int ni = rv[ln][i];\n        if(i < ni)\n            swap(a[i], a[ni]);\n    }\n    \n    for(int st = 0; (1 << st) < n; st++) \n    {\n        int len = (1 << st);\n        for(int k = 0; k < n; k += (len << 1)) \n        {\n            for(int pos = k; pos < k + len; pos++) \n            {\n                int l = a[pos];\n                int r = mul(a[pos + len], (inverse ? iw[st][pos - k] : w[st][pos - k]));\n                \n                a[pos] = norm(l + r);\n                a[pos + len] = norm(l - r);\n            }\n        }\n    }\n    \n    if(inverse) \n    {\n        int in = inv(n);\n        for(int i = 0; i < n; i++)\n            a[i] = mul(a[i], in);\n    }\n}\n\nint aa[N], bb[N], cc[N];\n\nvector<int> multiply(vector<int> a, vector<int> b) \n{\n    int sza = a.size();\n    int szb = b.size();\n    int n = 1, ln = 0;\n    while(n < (sza + szb))\n        n <<= 1, ln++;\n    for(int i = 0; i < n; i++)\n        aa[i] = (i < sza ? a[i] : 0);\n    for(int i = 0; i < n; i++)\n        bb[i] = (i < szb ? b[i] : 0);\n        \n    fft(aa, n, ln, false);\n    fft(bb, n, ln, false);\n    \n    for(int i = 0; i < n; i++)\n        cc[i] = mul(aa[i], bb[i]);\n        \n    fft(cc, n, ln, true);\n    \n    int szc = n;\n    vector<int> c(szc);\n    szc = n;\n    for(int i = 0; i < n; i++)\n        c[i] = cc[i];\n    return c;\n}                    \n\nint main()\n{\n    int n;\n    cin >> n;\n    vector<int> fact(n + 1);\n    fact[0] = 1;\n    for(int i = 0; i < n; i++)\n        fact[i + 1] = mul(fact[i], i + 1);\n    precalc();\n    vector<int> A = {0, 1, 2};\n    vector<int> B = {0, 1, 1};\n    vector<int> C = {0, 1, 1};\n    vector<int> D = {0, 1, 1};\n    vector<int> conv;\n    const int K = 2000;\n    int last_conv = -1e9;\n    while(A.size() <= n)\n    {\n        int cur = A.size();\n        if(cur - last_conv >= K)\n        {\n            last_conv = cur - 1;\n            conv = multiply(C, D);\n        }\n        /*for(auto x : conv) cerr << x << \" \";\n        cerr << endl;*/\n        int val_A;\n        if(last_conv * 2 >= cur)\n        {\n            val_A = conv[cur];\n            // [cur - last_conv, last_conv] are already used\n            for(int i = 1; i < (cur - last_conv); i++)\n            {\n                val_A = norm(val_A + mul(C[i], D[cur - i]));\n            }\n            for(int i = last_conv + 1; i < cur; i++)\n            {\n                val_A = norm(val_A + mul(C[i], D[cur - i]));\n            }\n        }\n        else\n        {\n            val_A = 0;\n            for(int i = 1; i <= cur - 1; i++)\n            {\n                val_A = norm(val_A + mul(C[i], D[cur - i]));\n            }\n        }\n        val_A = mul(val_A, fact[cur - 1]);\n        val_A = mul(val_A, 2);\n        A.push_back(val_A);\n        B.push_back(mul(val_A, inv(2)));\n        C.push_back(mul(val_A, inv(fact[cur])));\n        D.push_back(mul(B.back(), inv(fact[cur - 1])));\n    }\n    cout << norm(A[n] - 2) << endl;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "divide and conquer",
      "dp",
      "fft",
      "graphs"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1793",
    "index": "A",
    "title": "Yet Another Promotion",
    "statement": "The famous store \"Second Food\" sells groceries only two days a month. And the prices in each of days differ. You wanted to buy $n$ kilos of potatoes for a month. You know that on the first day of the month $1$ kilo of potatoes costs $a$ coins, and on the second day $b$ coins. In \"Second Food\" you can buy any \\textbf{integer} kilograms of potatoes.\n\nFortunately, \"Second Food\" has announced a promotion for potatoes, which is valid only on the first day of the month — for each $m$ kilos of potatoes you buy, you get $1$ kilo as a gift! In other words, you can get $m + 1$ kilograms by paying for $m$ kilograms.\n\nFind the minimum number of coins that you have to spend to buy \\textbf{at least} $n$ kilos of potatoes.",
    "tutorial": "Let $n = (m + 1) \\cdot q + r$. Note that you need to use a promotion if $a \\cdot m \\leq b \\cdot (m + 1)$. In this case, we will buy potatoes $q$ times for the promotion. The remaining potatoes (or all if the promotion is unprofitable) can be bought at $\\min(a, b)$ per kilogram. Then the answer is: $q \\cdot \\min(a \\cdot m, b \\cdot (m + 1)) + r \\cdot \\min(a, b)$ Thus this solution works in $\\mathcal{O}(1)$",
    "code": "t = int(input())\n\nfor i in range(t):\n    a, b = map(int, input().split(\" \"))\n    n, m = map(int, input().split(\" \"))\n\n    q = n // (m + 1)\n    r = n - q * (m + 1)\n    print(q * min(a * m, b * (m + 1))+ r*min(a,b))",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1793",
    "index": "B",
    "title": "Fedya and Array",
    "statement": "For his birthday recently Fedya was given an array $a$ of $n$ integers arranged in a circle, For each pair of neighboring numbers ($a_1$ and $a_2$, $a_2$ and $a_3$, $\\ldots$, $a_{n - 1}$ and $a_n$, $a_n$ and $a_1$) the absolute difference between them is equal to $1$.\n\nLet's call a local maximum an element, which is greater than both of its neighboring elements. Also call a local minimum an element, which is less than both of its neighboring elements. Note, that elements $a_1$ and $a_n$ are neighboring elements.\n\nUnfortunately, Fedya lost an array, but he remembered in it the sum of local maximums $x$ and the sum of local minimums $y$.\n\nGiven $x$ and $y$, help Fedya find any matching array of \\textbf{minimum} length.",
    "tutorial": "Note that the local minimums and maximums will alternate, and there will be the same number of them $k$. Let's call the $i$-th local maximum by $a_i$, the $i$-th local minimum by $b_i$. Without loss of generality, consider that $a_i$ goes before $b_i$. To get $b_i$ from $a_i$ we need to write out $a_i - b_i$ numbers, to get $a_{(i + 1) \\bmod k}$ from $b_i$ we need to write out $a_{(i + 1) \\bmod k} - b_i$ numbers. Thus, $(a_1 - b_1) + (a_2 - b_1) + (a_2 - b_2) + \\ldots + (a_k - b_k) + (a_1 - b_k) =$ $= 2 \\cdot (a_1 + a_2 + \\ldots + a_k) - 2 \\cdot (b_1 + b_2 + \\ldots + b_k) = 2 \\cdot (A - B) = n$ The array $[y, y + 1, y + 2, \\ldots, x - 1, x, x - 1, x - 2, \\ldots, y + 1]$ will satisfy the condition.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nvoid solve() {\n    ll a, b;\n    cin >> a >> b;\n    ll n = 2 * (a - b);\n    cout << n << '\\n';\n    vector<ll> arr(n);\n    int ptr = 0;\n    for (ll c = b; c <= a; ++c) {\n        arr[ptr++] = c;\n    }\n    for (ll c = a - 1; c > b; --c) {\n        arr[ptr++] = c;\n    }\n    for (int i = 0; i < n; ++i) {\n        cout << arr[i] << \" \\n\"[i == n - 1];\n    }\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1793",
    "index": "C",
    "title": "Dora and Search",
    "statement": "As you know, the girl Dora is always looking for something. This time she was given a permutation, and she wants to find such a subsegment of it that none of the elements at its ends is either the minimum or the maximum of the entire subsegment. More formally, you are asked to find the numbers $l$ and $r$ $(1 \\leq l \\leq r \\leq n)$ such that $a_l \\neq \\min(a_l, a_{l + 1}, \\ldots, a_r)$, $a_l \\neq \\max(a_l, a_{l + 1}, \\ldots, a_r)$ and $a_r \\neq \\min(a_l, a_{l + 1}, \\ldots, a_r)$, $a_r \\neq \\max(a_l, a_{l + 1}, \\ldots, a_r)$.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ occurs twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$, but $4$ is present in the array).\n\nHelp Dora find such a subsegment, or tell her that such a subsegment does not exist.",
    "tutorial": "Suppose we want to check whether the entire array satisfies the claim. If this is the case, then we can output the entire array as an answer. Otherwise, one of the two extreme elements does not meet our requirements. From this we can conclude that all segments containing an element that does not meet our requirements will also be incorrect, because this extreme element will remain the minimum/maximum. The algorithm follows from the fact above: let's look at the sub-section $[l; r]$, which is initially equal to $[1; n]$. If $a_l = \\min(a_{l}, a_{l+1}, \\ldots, a_{r})$ or $a_l = \\max(a_l, a_{l +1}, \\ldots, a_r)$, then we proceed to the segment $[l+1; r]$. A similar reasoning is also needed for $a_r$. Thus, either after some iterations we will get the required sub-section, or we will get $l == r$ and the answer will be $-1$. Final asymptotics: $\\mathcal{O}(n\\log n)$ or $\\mathcal{O}(n)$ depending on the implementation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef vector<int> vi;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vi a(n);\n    for (int &i: a)\n        cin >> i;\n    int l = 0, r = n - 1;\n    int mn = 1, mx = n;\n    while (l <= r) {\n        if (a[l] == mn) {\n            l++;\n            mn++;\n        } else if (a[l] == mx) {\n            l++;\n            mx--;\n        } else if (a[r] == mn) {\n            r--;\n            mn++;\n        } else if (a[r] == mx) {\n            r--;\n            mx--;\n        } else {\n            break;\n        }\n    }\n    if(l <= r){\n        cout << l + 1 << \" \" << r + 1 << endl;\n    } else{\n        cout << -1 << endl;\n    }\n}\n\nsigned main() {\n    int q = 1;\n    cin >> q;\n    while (q--)\n        solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1793",
    "index": "D",
    "title": "Moscow Gorillas",
    "statement": "In winter, the inhabitants of the Moscow Zoo are very bored, in particular, it concerns gorillas. You decided to entertain them and brought a permutation $p$ of length $n$ to the zoo.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ occurs twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$, but $4$ is present in the array).\n\nThe gorillas had their own permutation $q$ of length $n$. They suggested that you count the number of pairs of integers $l, r$ ($1 \\le l \\le r \\le n$) such that $\\operatorname{MEX}([p_l, p_{l+1}, \\ldots, p_r])=\\operatorname{MEX}([q_l, q_{l+1}, \\ldots, q_r])$.\n\nThe $\\operatorname{MEX}$ of the sequence is the minimum integer \\textbf{positive} number missing from this sequence. For example, $\\operatorname{MEX}([1, 3]) = 2$, $\\operatorname{MEX}([5]) = 1$, $\\operatorname{MEX}([3, 1, 2, 6]) = 4$.\n\nYou do not want to risk your health, so you will not dare to refuse the gorillas.",
    "tutorial": "Denote by $pos_x$ the index of the number $x$ in the permutation. Subsegments with $\\operatorname{MEX}>1$ are as follows $1 \\le l \\le pos_1 \\le r \\le n$. Denote by: $l_x = \\min{[pos_1, pos_2, \\ldots, pos_x]}$, $r_x=\\max{[pos_1, pos_2, \\ldots, os_x]}$. Subsegments with $\\operatorname{MEX}>x$ are as follows $1 \\le l \\le l_x \\le r_x \\le r \\le n$. Let's find all subsegments with $\\operatorname{MEX}=x$. If $pos_{x + 1} < l_x$, then the subsegments with $\\operatorname{MEX}=x+1$ are as follows $pos_{x+1} < l \\le l_x \\le r_x \\le r \\le n$ If $l_x \\le pos_{x + 1} \\le r_x$, then there is no subsegment with $\\operatorname{MEX}=x+1$ If $r_x <pos_{x+1}$, then the subsegments with $\\operatorname{MEX}=x+1$ are as follows $1 \\le l \\le l_x \\le r_x \\le r < pos_{x+1}$ It remains only to intersect the sets of such subsegments for $p$ and $q$, which is done trivially.",
    "code": "#include <bits/stdc++.h>\n#define int long long\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> pos_a(n + 1);\n    vector<int> pos_b(n + 1);\n    for (int i = 0; i < n; i++) {\n        int a;\n        cin >> a;\n        pos_a[a] = i + 1;\n    }\n    for (int i = 0; i < n; i++) {\n        int b;\n        cin >> b;\n        pos_b[b] = i + 1;\n    }\n    int la = n, ra = 1, lb = n, rb = 1, ans = 0;\n    for (int i = 1; i + 1 <= n; i++) {\n        la = min(la, pos_a[i]);\n        ra = max(ra, pos_a[i]);\n        lb = min(lb, pos_b[i]);\n        rb = max(rb, pos_b[i]);\n        int min_la, max_ra, min_lb, max_rb;\n        if (pos_a[i + 1] < la) {\n            min_la = pos_a[i + 1] + 1;\n            max_ra = n;\n        } else {\n            min_la = 1;\n            max_ra = pos_a[i + 1] - 1;\n        }\n        if (pos_b[i + 1] < lb) {\n            min_lb = pos_b[i + 1] + 1;\n            max_rb = n;\n        } else {\n            min_lb = 1;\n            max_rb = pos_b[i + 1] - 1;\n        }\n        ans += max(min(la, lb) - max(min_la, min_lb) + 1, 0ll) * max(min(max_ra, max_rb) - max(ra, rb) + 1, 0ll);\n    }\n    ans += min(pos_a[1], pos_b[1]) * (min(pos_a[1], pos_b[1]) - 1) / 2;\n    ans += (n - max(pos_a[1], pos_b[1])) * (n - max(pos_a[1], pos_b[1]) + 1) / 2;\n    ans += abs(pos_a[1] - pos_b[1]) * (abs(pos_a[1] - pos_b[1]) - 1) / 2;\n    ans++;\n    cout << ans << endl;\n}\n\nsigned main() {\n    int q = 1;\n    while (q--)\n        solve();\n    return 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1793",
    "index": "E",
    "title": "Velepin and Marketing",
    "statement": "The famous writer Velepin is very productive. Recently, he signed a contract with a well-known publication and now he needs to write $k_i$ books for $i$-th year. This is not a problem for him at all, he can write as much as he wants about samurai, space, emptiness, insects and werewolves.\n\nHe has $n$ regular readers, each of whom in the $i$-th year will read one of the $k_i$ books published by Velepin. Readers are very fond of discussing books, so the $j$-th of them will be satisfied within a year if at least $a_j$ persons read the same book as him (\\textbf{including himself}).\n\nVelepin has obvious problems with marketing, so he turned to you! A well-known book reading service can control what each of Velepin's regular readers will read, but he does not want books to be wasted, so \\textbf{someone should read each book}. And so they turned to you with a request to tell you what the maximum number of regular readers can be made satisfied during each of the years, if you can choose each person the book he will read.",
    "tutorial": "Let's sort people by their group size requirement. Suppose we have such a person $i$ that he is not satisfied, and we have a person $j > i$ who is satisfied. Then we can replace person $j$ in his group with $i$ and the answer for us will not be worse. It follows that for a particular $k$ the answer is some prefix of the people we can make satisfied. Let us also prove that there exists some arrangement of groups that covers the same prefix, and that each group is a continuous segment. Let's take some correct partitioning into groups. Then each group will be a set of unconnected segments. Let's take the leftmost such segment. Note that we can swap it to the nearest segment of the same group to the right without breaking anything. Thus we obtained that we can look for a solution in the form of partitioning each prefix into valid groups, which are segments. We will solve this problem using dynamic programming. Let $dp[i]$ -- the maximum number of groups into which $i$th prefix can be partitioned, so that everyone is satisfied (and no elements beyond the prefix can be used). Dynamics base: $dp[0] = 0$ (empty prefix maximum can be divided into 0 groups). Transition: for $i$th person his group must have size at least $a[i]$, so the transition looks like this $dp[i] = \\underset{0 \\leqslant j \\leqslant i - a[i]}{\\max} dp[j] + 1$. But what if $a[i] > i$? Then we can't dial the $i$th prefix. Then we put $dp[i] = -\\infty$. This dynamics can be calculated using prefix maximums. This part of the solution works for $\\mathcal{O}(n)$. Earlier we said that the answer would be some prefix of people who would be satisfied. If we can partition the prefix into some number of groups, then that answer can be the prefix for all $k \\leqslant dp[i] + n - i$. (we partition our prefix into $dp$, and the rest of the people one by one into the group) If we can't make the whole prefix satisfied ($dp[i] = -\\infty$), then we need to add people from outside. Thus, the maximum number of groups we can split into if $i$th prefix is completely satisfied is $n - a[i] + 1$. Note that if by some prefix we can score $k$, then we can also score $k - 1$ (combining two groups into one). Then we need to find the largest prefix that fits the given $k$ in the query. This can be done by an array of suffix maximums over $\\mathcal{O}(q)$ total. The final asymptotic of the solution is $\\mathcal{O}(n \\log n + q)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n#define ll long long\n#define pii pair<int, int>\n#define ld long double\n#define all(a) (a).begin(), (a).end()\n\nconst int inf = 1e9 + 7;\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    int n;\n    cin >> n;\n    vector<int> c(n);\n    for (int i = 0; i < n; ++i) cin >> c[i];\n    sort(all(c));\n    vector<int> ans(n + 1); \n    vector<int> dp(n + 1, -inf);\n    dp[0] = 0;\n\n    for (int i = 1; i <= n; ++i) {\n        if (c[i-1] <= i) {\n            dp[i] = dp[i - c[i-1]] + 1;\n            ans[dp[i] + n - i] = max(ans[dp[i] + n - i], i);\n        } else {\n            if (c[i-1] <= n) {\n                ans[1 + n - c[i-1]] = max(ans[1 + n - c[i-1]], i);\n            }\n        }\n        dp[i] = max(dp[i], dp[i-1]);\n    }\n\n    for (int i = n - 1; i >= 0; i--) {\n        ans[i] = max(ans[i], ans[i + 1]);\n    }\n\n    int q;\n    cin >> q;\n    for (int i = 0; i < q; ++i) {\n        int x;\n        cin >> x;\n        cout << ans[x] << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1793",
    "index": "F",
    "title": "Rebrending",
    "statement": "Kostya and Zhenya — the creators of the band \"Paper\" — after the release of the legendary album decided to create a new band \"Day movers\", for this they need to find two new people.\n\nThey invited $n$ people to the casting. The casting will last $q$ days. On the $i$th of the days, Kostya and Zhenya want to find two people on the segment from $l_i$ to $r_i$ who are most suitable for their band. Since \"Day movers\" are doing a modern art, musical skills are not important to them and they look only at other signs: they want the height difference between two people to be as small as possible.\n\nHelp them, and for each day, find the minimum difference in the growth of people from the casting on this segment!",
    "tutorial": "Let's go through all the elements from left to right. The main task will be to support the current version of $dp[i]$ -- the minimum difference of $a_i$ with the elements to the right of it that we managed to consider. Let us correctly calculate $dp$ for the first $r$ elements. Let's move on to $r + 1$. Let's show how to update the answer for all $j < i$, such that $a[j] > a[i]$. For $j < i$, such that $a[j] <a[i]$ is solved similarly. Let's take the first element $a[j]$ to the left of $i$, such that $a[j] > a[i]$. Note that if there is $l<j < i$ such that $a[l] > a[j]> a[i]$, then we will not update $dp[l]$ for it, because $|a[l] - a[j]| < |a[l] - a[i]|$. Also, we will not update the answer for $l$ such that $|a[l] - a[j]| < |a[l] - a[i]|$, that is, if $a[l] > a[i] + \\frac{a[j] - a[i]}{2}$. Therefore, further we will be interested only in the numbers from the segment $\\left[a[i], a[i] + \\frac{a[j] - a[i]}{2}\\right]$. Let's note that we have reduced the length of the segment by $2$ times. That is, there will be no more such iterations than $\\mathcal{O}(\\log n)$. You can find the rightmost number belonging to a segment using the segment tree. The answer for the segment $l_i, r_i$ will be $\\underset{l_i\\leqslant j<r}{\\min} dp[l]$ at the moment $r_i$. This can also be efficiently found using the segment tree. The final asymptotics of the solution is $\\mathcal{O}(n\\log^2 n + q\\log n)$. There is also a solution for $\\mathcal{O}(n\\sqrt{n} + q\\log q)$ that passes all the tests.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int inf = 1e9 + 228;\n\ntemplate<class T, class Fun = function<T(const T &, const T &)>>\nstruct SegTree {\n    Fun f;\n    vector<T> t;\n    int n;\n\n    SegTree(int sz, const Fun &g, T default_value = T()) : f(g) {\n        n = 1;\n        while (n < sz) n <<= 1;\n        t.resize(n * 2, default_value);\n    }\n\n    SegTree(vector<T> &a, const Fun &g, T default_value = T()) : SegTree(a.size(), g, default_value) {\n        for (int i = 0; i < n; ++i) t[i + n] = a[i];\n        for (int i = n - 1; i >= 1; --i) t[i] = f(t[i << 1], t[i << 1 | 1]);\n    }\n\n    void upd(int i, T x) {\n        i += n;\n        t[i] = f(t[i], x);\n        for (i >>= 1; i > 1; i >>= 1) t[i] = f(t[i << 1], t[i << 1 | 1]);\n    }\n\n    T get(int l, int r) {\n        T resL = t[0], resR = t[0];\n        for (l += n, r += n; l < r; l >>= 1, r >>= 1) {\n            if (l & 1) resL = f(resL, t[l++]);\n            if (r & 1) resR = f(t[--r], resR);\n        }\n        return f(resL, resR);\n    }\n};\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    int n, q;\n    cin >> n >> q;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    vector<vector<pair<int, int>>> posts(n);\n    for (int i = 0; i < q; i++) {\n        int l, r;\n        cin >> l >> r;\n        l--, r--;\n        posts[r].push_back({l, i});\n    }\n    SegTree<int> ind(n + 1, [](int x, int y) { return max(x, y); }, -1);\n    SegTree<int> dp(n + 1, [](int x, int y) { return min(x, y); }, inf);\n    vector<int> answer(q);\n    for (int i = 0; i < n; i++) {\n        {\n            int limit = n + 1;\n            while (true) {\n                int j = ind.get(a[i], limit);\n                if (j == -1)\n                    break;\n                dp.upd(j, abs(a[j] - a[i]));\n                limit = a[i] + (a[j] - a[i] + 1) / 2;\n            }\n        }\n        {\n            int limit = 0;\n            while (true) {\n                int j = ind.get(limit, a[i]);\n                if (j == -1)\n                    break;\n                dp.upd(j, abs(a[j] - a[i]));\n                limit = a[i] - (a[i] - a[j] + 1) / 2 + 1;\n            }\n        }\n        ind.upd(a[i], i);\n        for (pair<int, int> j: posts[i]) {\n            answer[j.second] = dp.get(j.first, i);\n        }\n    }\n    for (int i: answer) {\n        cout << i << \"\\n\";\n    }\n\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "implementation"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1794",
    "index": "A",
    "title": "Prefix and Suffix Array",
    "statement": "Marcos loves strings a lot, so he has a favorite string $s$ consisting of lowercase English letters. For this string, he wrote down all its non-empty prefixes and suffixes (except for $s$) on a piece of paper in arbitrary order. You see all these strings and wonder if Marcos' favorite string is a palindrome or not. So, your task is to decide whether $s$ is a palindrome by just looking at the piece of paper.\n\nA string $a$ is a prefix of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the end.\n\nA string $a$ is a suffix of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning.\n\nA palindrome is a string that reads the same backward as forward, for example, strings \"gg\", \"ioi\", \"abba\", \"icpci\" are palindromes, but strings \"codeforces\", \"abcd\", \"alt\" are not.",
    "tutorial": "Observe that there are exactly two strings of length $n-1$ (one prefix and one suffix). We will call them $x$ and $y$. Then, $s$ is a palindrome if and only if $\\text{rev}(x)=y$, where $\\text{rev}(x)$ is the reversal of string $x$. So, to solve the problem it is enough to find the two strings of length $n-1$ and check if one of them is equal to the reversal of the other. This solution also works for any length greater or equal to $\\lfloor \\frac{n}{2} \\rfloor$. Intended complexity: $\\mathcal{O}(n^2)$ per test case. (reading the input)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tint t; cin >> t;\n\tfor(int test_number = 0; test_number < t; test_number++){\n\t\tint n; cin >> n;\n\t\tvector <string> long_subs;\n\t\tfor(int i = 0; i < 2 * n - 2; i++){\n\t\t\tstring s; \n\t\t\tcin >> s;\n\t\t\tif((int)s.size() == n - 1){\n\t\t\t\tlong_subs.push_back(s);\n\t\t\t}\n\t\t}\n\t\treverse(long_subs[1].begin(), long_subs[1].end());\n\t\tif(long_subs[0] == long_subs[1]){\n\t\t\tcout<<\"YES\\n\";\n\t\t}else{\n\t\t\tcout<<\"NO\\n\";\n\t\t}\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1794",
    "index": "B",
    "title": "Not Dividing",
    "statement": "You are given an array of $n$ positive integers $a_1, a_2, \\ldots, a_n$. In one operation, you can choose any number of the array and add $1$ to it.\n\nMake at most $2n$ operations so that the array satisfies the following property: $a_{i+1}$ is \\textbf{not} divisible by $a_i$, for each $i = 1, 2, \\ldots, n-1$.\n\nYou do \\textbf{not} need to minimize the number of operations.",
    "tutorial": "First, we add one to all the numbers in the array equal to $1$. This uses at most $n$ operations. Then, we iterate through the elements of the array from left to right, starting from the second element. At each step, let $a_x$ be the element we are iterating. If $a_x$ is divisible by $a_{x-1}$, we add one to $a_x$. Now this element is not divisible by $a_{x-1}$, because otherwise both $a_x$ and $a_x+1$ are divisible by $a_{x-1}$, but that means $1$ is also divisible by $a_{x-1}$ which cannot happen since all the elements in the array are at least $2$ (because of the first step we did). This part also uses at most $n$ operations, so we used at most $2n$ operations in total. The resulting array will satisfy the statement property. Intended complexity: $\\mathcal{O}(n)$ per test case. Actually, the maximum number of operations performed by this algorithm is $\\frac{3}{2}n$. Try to prove it!",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tint t; cin >> t;\n\tfor(int test_number = 0; test_number < t; test_number++){\n\t\tint n; cin >> n;\n\t\tvector <int> a(n);\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tcin >> a[i];\n\t\t}\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tif(a[i] == 1){\n\t\t\t\ta[i]++;\n\t\t\t}\n\t\t}\n\t\tfor(int i = 1; i < n; i++){\n\t\t\tif(a[i] % a[i - 1] == 0){\n\t\t\t\ta[i]++;\n\t\t\t}\n\t\t}\n\t\tfor(auto i : a){\n\t\t\tcout << i << \" \";\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1794",
    "index": "C",
    "title": "Scoring Subsequences",
    "statement": "The score of a sequence $[s_1, s_2, \\ldots, s_d]$ is defined as $\\displaystyle \\frac{s_1\\cdot s_2\\cdot \\ldots \\cdot s_d}{d!}$, where $d!=1\\cdot 2\\cdot \\ldots \\cdot d$. In particular, the score of an empty sequence is $1$.\n\nFor a sequence $[s_1, s_2, \\ldots, s_d]$, let $m$ be the maximum score among all its subsequences. Its cost is defined as the maximum length of a subsequence with a score of $m$.\n\nYou are given a \\textbf{non-decreasing} sequence $[a_1, a_2, \\ldots, a_n]$ of integers of length $n$. In other words, the condition $a_1 \\leq a_2 \\leq \\ldots \\leq a_n$ is satisfied. For each $k=1, 2, \\ldots , n$, find the cost of the sequence $[a_1, a_2, \\ldots , a_k]$.\n\nA sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) elements.",
    "tutorial": "We will first see how to find the cost of a single non-decreasing sequence $s_1, s_2, \\ldots, s_\\ell$. If we choose a subsequence with $k$ elements, to achieve the maximum score it is optimal to choose the $k$ largest elements. As the sequence is in non-decreasing order, the $k$ largest elements will be the last $k$ elements of the sequence. Thus, all possible candidates to be the answer are the suffixes of the sequence. Now let's divide the $i$-th element from the right by $i$. The sequence now turns into $\\displaystyle \\frac{s_1}{\\ell}, \\frac{s_2}{\\ell-1}, \\ldots, \\frac{s_{\\ell-1}}{2}, \\frac{s_\\ell}{1}$. Observe that the score of a suffix in the original sequence is equal to the product of the suffix of the same size in the new sequence. The original sequence satisfies $s_1 \\leq s_2 \\leq \\ldots \\leq s_{\\ell-1} \\leq s_\\ell$. It also true that $\\displaystyle \\frac{1}{\\ell} \\leq \\frac{1}{\\ell-1} \\leq \\ldots \\leq \\frac{1}{2} \\leq \\frac{1}{1}$ then combining these two inequalities we have $\\displaystyle \\frac{s_1}{\\ell} \\leq \\frac{s_2}{\\ell-1} \\leq \\ldots \\leq \\frac{s_{\\ell-1}}{2} \\leq \\frac{s_\\ell}{1}$ so the new sequence is also in non-decreasing order. In order to maximize the product of a suffix in the new sequence, we will choose all the elements in the new sequence which are greater or equal to $1$ (these elements form a suffix because the new sequence is non-decreasing). If there are elements equal to $1$ in the new sequence, we have to choose them in order to get the subsquence with maximum length (among all the ones with maximum score). Therefore, the cost of a sequence $s_1, s_2, \\ldots, s_\\ell$ is the maximum length of a suffix of $\\displaystyle \\frac{s_1}{\\ell}, \\frac{s_2}{\\ell-1}, \\ldots, \\frac{s_{\\ell-1}}{2}, \\frac{s_\\ell}{1}$ such that each element is at least $1$. Now, we have to find the cost of every prefix of the given sequence $[a_1, a_2, \\ldots , a_n]$. For a fixed $k$, the cost of $[a_1, a_2, \\ldots , a_k]$ will be the maximum length of a suffix of $\\displaystyle \\frac{a_1}{k}, \\frac{a_2}{k-1}, \\ldots, \\frac{a_{k-1}}{2}, \\frac{a_k}{1}$ such that each element is at least $1$. We can find this length using binary search. Observe that we cannot compute the transformed sequence for every prefix, as that will be too slow. Instead, we can compute in each step of the binary search what would the number in that position be in the transformed sequence. By doing these, we can find the score of each prefix in $\\mathcal{O}(\\text{log}\\:n)$ time. Intended complexity: $\\mathcal{O}(n\\:\\text{log}\\:n)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tint t; cin >> t;\n\tfor(int test_number = 0; test_number < t; test_number++){\n\t\tint n; cin >> n;\n\t\tvector <int> a(n);\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tcin >> a[i];\n\t\t}\n\t\tvector<int> res;\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tint l = 1, r = i + 1;\n\t\t\twhile(l <= r){\n\t\t\t\tint m = (l + r) / 2;\n\t\t\t\tif(a[i - m + 1] >= m){\n\t\t\t\t\tl = m + 1;\n\t\t\t\t}else{\n\t\t\t\t\tr = m - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tres.push_back(r);\n\t\t}\n\t\tfor(auto i : res){\n\t\t\tcout << i << \" \";\n\t\t}\n\t\tcout<<\"\\n\";\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1794",
    "index": "D",
    "title": "Counting Factorizations",
    "statement": "The prime factorization of a positive integer $m$ is the unique way to write it as $\\displaystyle m=p_1^{e_1}\\cdot p_2^{e_2}\\cdot \\ldots \\cdot p_k^{e_k}$, where $p_1, p_2, \\ldots, p_k$ are prime numbers, $p_1 < p_2 < \\ldots < p_k$ and $e_1, e_2, \\ldots, e_k$ are positive integers.\n\nFor each positive integer $m$, $f(m)$ is defined as the multiset of all numbers in its prime factorization, that is $f(m)=\\{p_1,e_1,p_2,e_2,\\ldots,p_k,e_k\\}$.\n\nFor example, $f(24)=\\{2,3,3,1\\}$, $f(5)=\\{1,5\\}$ and $f(1)=\\{\\}$.\n\nYou are given a list consisting of $2n$ integers $a_1, a_2, \\ldots, a_{2n}$. Count how many positive integers $m$ satisfy that $f(m)=\\{a_1, a_2, \\ldots, a_{2n}\\}$. Since this value may be large, print it modulo $998\\,244\\,353$.",
    "tutorial": "First, we will count how many times each different element in $a$ occurs and check which of these elements are prime numbers. This can be done by checking for each element if it has a divisor up to its square root or using the Sieve of Eratosthenes. To construct a number $m$ such that $f(m)=\\{a_1, a_2, \\ldots, a_{2n}\\}$ we have to choose $n$ elements of $a$ to be the primes in its factorization and $n$ elements to be the exponents. The numbers we choose to be the primes in the factorization have to be prime numbers and distinct. If there are less than $n$ distinct primes in $a$, then there is no number $m$ satisfying the property. So, from now on we will assume there are at least $n$ distinct prime numbers in $a$. Let $b_1,b_2, \\ldots, b_s$ be the number of occurrences of each non-prime number in $a$ and let $c_1, c_2, \\ldots, c_t$ be the number of occurrences of each prime number in $a$. After we choose the primes for the factorization, let $c'_1, c'_2, \\ldots, c'_t$ be the remaining number of occurrences of each prime number. As we can choose each prime number at most once, then $c'_i=c_i$ or $c'_i=c_i-1$. For each way of choosing the primes, the number of possible values for $m$ is $\\displaystyle \\frac{n!}{b_1!\\:\\:b_2!\\ldots b_s!\\:\\:c'_1!\\:\\:c'_2!\\ldots c'_t!}$ because this is the number of ways to choose where to place the exponents. The answer to the problem is the sum of all these numbers over all ways of choosing the prime numbers. Observe that when we sum terms of the form $\\displaystyle \\frac{n!}{b_1!\\:\\:b_2!\\ldots b_s!\\:\\:c'_1!\\:\\:c'_2!\\ldots c'_t!}$, the value $\\displaystyle \\frac{n!}{b_1!\\:\\:b_2!\\ldots b_s!}$ is a common factor over all these terms. Thus, we just need to find the sum of the terms $\\displaystyle \\frac{1}{c'_1!\\:\\:c'_2!\\ldots c'_t!}$ and then multiply by the common factor. To find this sum, we will use dynamic programming. Let $g(x,y)$ be the sum considering only the primes from the $x$-th of them and assuming that $y$ primes need to be chosen (or that $n-y$ primes are already chosen). Then $\\displaystyle g(x,y)=\\frac{1}{c_x!}\\times g(x+1,y)+\\frac{1}{(c_x-1)!}\\times g(x+1,y-1)$. The value of $g(1,n)$ will give the desired sum. Intended complexity: $\\mathcal{O}(n^2)$ (plus the complexity of primality checking) It is possible to solve the problem with greater constraints, like $n \\leq 10^5$. Try to solve it with this new constraint!",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n \nconst ll MOD = 998244353;\n \n//checks if n is prime\nbool is_prime(ll n){\n\tif(n == 1){\n\t\treturn false;\n\t}\n\tfor(ll i = 2; i * i <= n; i++){\n\t\tif(n %i == 0){\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n \n//computes b ** e % MOD\nll fast_pow(ll b, ll e){\n\tll res = 1;\n\twhile(e > 0){\n\t\tif(e % 2 == 1){\n\t\t\tres = res * b % MOD;\n\t\t}\n\t\tb = b * b % MOD;\n\t\te /= 2;\n\t}\n\treturn res;\n}\n \nvector<pair<ll, ll>> primes;\n \nconst int MAXN = 5050;\n \nll dp[MAXN][MAXN];\n \nll fact[MAXN], fact_inv[MAXN];\n \nll f(ll x, ll y){\n\tll &res = dp[x][y];\n\tif(res >= 0){\n\t\treturn res;\n\t}\n\tif(x == (int)primes.size()){\n\t\treturn res = (y == 0);\n\t}\n\tres = fact_inv[primes[x].second] * f(x + 1, y) % MOD;\n\tif(y > 0){\n\t\tres = (res + fact_inv[primes[x].second - 1] * f(x + 1, y - 1)) % MOD;\t\n\t}\n\treturn res;\n}\n \nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\t//reading the input\n\tint n; cin >> n;\n\tvector<ll> a(2 * n);\n\tfor(int i = 0; i < 2 * n; i++){\n\t\tcin >> a[i];\n\t}\n\tsort(a.begin(), a.end());\n\t//compressed version of a, pairs {value, #occurrences}\n\tvector<pair<ll, ll>> a_comp;\n\tfor(int i = 0; i < 2 * n; i++){\n\t\tif(a_comp.size() == 0u || a_comp.back().first != a[i]){\n\t\t\ta_comp.push_back({a[i], 1});\n\t\t}else{\n\t\t\ta_comp.back().second++;\n\t\t}\n\t}\n\t//computing factorials and inverses\n\tfact[0] = 1;\n\tfor(ll i = 1; i < MAXN; i++){\n\t\tfact[i] = fact[i-1] * i % MOD;\n\t}\n\tfact_inv[0] = 1;\n\tfor(ll i = 0; i < MAXN; i++){\n\t\tfact_inv[i] = fast_pow(fact[i], MOD - 2);\n\t}\n\t//adding only primes for the dp\n\tfor(auto i : a_comp){\n\t\tif(is_prime(i.first)){\n\t\t\tprimes.push_back(i);\n\t\t}\n\t}\n\tmemset(dp, -1, sizeof(dp));\n\tll res = f(0, n);\n\t//we have to consider the contribution of non-primes too!\n\tfor(auto i : a_comp){\n\t\tif(!is_prime(i.first)){\n\t\t\tres = res * fact_inv[i.second] % MOD;\n\t\t}\n\t}\n\tres = res * fact[n] % MOD;\n\tcout << res << \"\\n\";\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1794",
    "index": "E",
    "title": "Labeling the Tree with Distances",
    "statement": "You are given an unweighted tree of $n$ vertices numbered from $1$ to $n$ and a list of $n-1$ integers $a_1, a_2, \\ldots, a_{n-1}$. A tree is a connected undirected graph without cycles. You will use each element of the list to label one vertex. No vertex should be labeled twice. You can label the only remaining unlabeled vertex with any integer.\n\nA vertex $x$ is called good if it is possible to do this labeling so that for each vertex $i$, its label is the distance between $x$ and $i$. The distance between two vertices $s$ and $t$ on a tree is the minimum number of edges on a path that starts at vertex $s$ and ends at vertex $t$.\n\nFind all good vertices.",
    "tutorial": "First, count the number of occurrences of each element in the list $a$. Let these numbers be $c_0, c_1, \\ldots, c_{n-1}$. Then, compute the polynomial hash of the array $c$, that is $\\displaystyle H=\\sum_{i=0}^{n-1}c_i\\:b^i$ where $b$ is the base of the hash. Because the tree is unweighted, there are only $n$ possible values to write in the unlabeled vertex (all integers between $0$ and $n-1$). Including this extra number, the hash has $n$ possibilities: $H+b^i$ for each $i=0,1,\\ldots, n-1$. Now, let's compute the same hash for each vertex of the tree. That is, for each vertex $x$ count how many vertices are at distances $0,1,\\ldots,n-1$, and if these numbers are $d_0, d_1, \\ldots, d_{n-1}$ compute the value $\\displaystyle h_x=\\sum_{i=0}^{n-1}d_i\\:b^i$. To compute these values efficiently, we will use rerooting dynamic programming: We will make two DFS. In the first one, compute the parent of each node and the hash of each node only considering the nodes in its subtree. For each vertex $x$, if we call this hash $\\text{dp}_x$ then $\\displaystyle \\text{dp}_x=1+b\\sum_{\\text{child}\\:i}\\text{dp}_i$. In the second one (which must be performed after the first one), for each vertex $x$ compute the hash of the parent of $x$ considering the nodes which are not in the subtree of vertex $x$. If we call this hash $\\text{dp2}_x$ then $\\displaystyle \\text{dp2}_x=\\text{dp}_{\\text{pa}_x}-b\\:\\text{dp}_{x}+b\\:\\text{dp2}_{\\text{pa}_x}$ where $\\text{pa}_x$ is the parent of $x$. Now, observe that $h_x=\\text{dp}_x+b\\:\\text{dp2}_x$. With these hashes, we can compute the good vertices. A vertex $x$ will be good if and only if $h_x=H+b^i$ for some $i=0,1,\\ldots,n-1$. Doing a two pointers algorithm with the two sorted lists $h_1, h_2, \\ldots, h_n$ and $H+1, H+b, H+b^2,\\ldots, H+b^{n-1}$ is enough to find for each $h_x$ if there is a number on the other list equal to it. To make the solution pass, it is advisable to use hashing with multiple modules or just one big modulo. Intended complexity: $\\mathcal{O}(n\\:\\text{log}\\:n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n \nconst int MAXN = 200005;\nmt19937_64 rng(chrono::system_clock::now().time_since_epoch().count());\n \n//Hashing stuff\nconst ll MOD[3] = {999727999, 1070777777, 1000000007};\nll B[3];\n \nvector<ll> shift(vector<ll> h, ll val = 0){\n\tfor(int k = 0; k < 3; k++){\n\t\th[k] = (h[k] * B[k] + val) % MOD[k];\n\t}\n\treturn h;\n}\n \nvector<ll> add(vector<ll> a, vector<ll> b){\n\tvector<ll> res(3);\n\tfor(int k = 0; k < 3; k++){\n\t\tres[k] = (a[k] + b[k]) % MOD[k];\n\t}\n\treturn res;\n}\n \nvector<ll> sub(vector<ll> a, vector<ll> b){\n\tvector<ll> res(3);\n\tfor(int k = 0; k < 3; k++){\n\t\tres[k] = (a[k] - b[k] + MOD[k]) % MOD[k];\n\t}\n\treturn res;\n}\n \n//Tree stuff\nvector<int> g[MAXN];\n \nbool vis[MAXN];\nint parent[MAXN];\nvector<ll> dp[MAXN], dp2[MAXN];\n \nvoid dfs(int x){\n\tvis[x] = true;\n\tfor(auto i : g[x]){\n\t\tif(!vis[i]){\n\t\t\tparent[i] = x;\n\t\t\tdfs(i);\n\t\t\tdp[x] = add(dp[x], shift(dp[i]));\n\t\t}\n\t}\n\tdp[x] = add(dp[x], {1, 1, 1});\n}\n \nvoid dfs2(int x){\n\tif(x != 0){\n\t\tdp2[x] = sub(dp[parent[x]], shift(dp[x]));\n\t\tdp2[x] = add(dp2[x], shift(dp2[parent[x]]));\n\t}\n\tfor(auto i : g[x]){\n\t\tif(i != parent[x]){\n\t\t\tdfs2(i);\n\t\t}\n\t}\n}\n \nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tfor(int k = 0; k < 3; k++){\n\t\tB[k] = rng() % MOD[k];\n\t}\n\t//reading the input\n\tint n; cin >> n;\n\tvector<int> occurrences(n);\n\tfor(int i = 0; i < n - 1; i++){\n\t\tint a; cin >> a;\n\t\toccurrences[a]++;\n\t}\n\tfor(int i = 0; i < n - 1; i++){\n\t\tint u, v; cin >> u >> v;\n\t\tu--; v--;\n\t\tg[u].push_back(v);\n\t\tg[v].push_back(u);\n\t}\n\t//calculating possible list hashes\n\tvector<vector<ll>> list_hashes;\n\tvector<ll> h = {0, 0, 0};\n\tfor(int i = n - 1; i >= 0; i--){\n\t\th = shift(h, occurrences[i]);\n\t}\n\tvector<ll> extra = {1, 1, 1};\n\tfor(int i = 0; i < n; i++){\n\t\tlist_hashes.push_back(add(h, extra));\n\t\textra = shift(extra);\n\t}\n\t//calculating possible tree hashes\n\tfor(int i = 0; i < n; i++){\n\t\tdp[i] = {0, 0, 0};\n\t\tdp2[i] = {0, 0, 0};\n\t}\n\tparent[0] = -1;\n\tdfs(0);\n\tdfs2(0);\n\tvector<pair<vector<ll>, int>> tree_hashes;\n\tfor(int i = 0; i < n; i++){\n\t\tif(i == 0){\n\t\t\ttree_hashes.push_back({dp[i], i});\n\t\t}else{\n\t\t\ttree_hashes.push_back({add(dp[i], shift(dp2[i])), i});\n\t\t}\n\t}\n\t//calculting the answer\n\tsort(list_hashes.begin(), list_hashes.end());\n\tsort(tree_hashes.begin(), tree_hashes.end());\n\tvector<int> res;\n\tint pos = 0;\n\tfor(auto lh : list_hashes){\n\t\twhile(pos < n && tree_hashes[pos].first < lh){\n\t\t\tpos++;\n\t\t}\n\t\twhile(pos < n && tree_hashes[pos].first == lh){\n\t\t\tres.push_back(tree_hashes[pos].second);\n\t\t\tpos++;\n\t\t}\n\t}\n\tsort(res.begin(), res.end());\n\tcout << res.size() << \"\\n\";\n\tfor(auto i : res){\n\t\tcout << i + 1 << \" \";\n\t}\n\tcout << \"\\n\";\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "hashing",
      "implementation",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1795",
    "index": "A",
    "title": "Two Towers",
    "statement": "There are two towers consisting of blocks of two colors: red and blue. Both towers are represented by strings of characters B and/or R denoting the order of blocks in them \\textbf{from the bottom to the top}, where B corresponds to a blue block, and R corresponds to a red block.\n\n\\begin{center}\n{\\small These two towers are represented by strings BRBB and RBR.}\n\\end{center}\n\nYou can perform the following operation any number of times: choose a tower with \\textbf{at least two blocks}, and move its \\textbf{top} block to the \\textbf{top} of the other tower.\n\nThe pair of towers is beautiful if no pair of touching blocks has the same color; i. e. no red block stands on top of another red block, and no blue block stands on top of another blue block.\n\nYou have to check if it is possible to perform any number of operations (possibly zero) to make the pair of towers beautiful.",
    "tutorial": "Note that it does not make sense to move several blocks first from the left tower to the right, and then from the right to the left, since this is similar to canceling the last actions. Using the fact described above and small restrictions on the input data, one of the possible solutions is the following: choose which tower will be the one where we take blocks from (try both options), iterate over the number of operations, and then check that both towers are beautiful after that number of operations. There is a faster solution: move all the blocks to the left tower, and then check that there is no more than one pair of adjacent blocks of the same color. If there are no such pairs, then we can divide the tower into two in an arbitrary way, and if there is exactly one pair, then we need to make a \"cut\" exactly between two blocks of the same color. Otherwise, there will always be a pair of adjacent blocks of the same color in one of the towers.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, m;\n    string s, t;\n    cin >> n >> m >> s >> t;\n    reverse(t.begin(), t.end());\n    s += t;\n    int cnt = 0;\n    for (int i = 1; i < n + m; ++i) cnt += s[i - 1] == s[i];\n    cout << (cnt <= 1 ? \"YES\\n\" : \"NO\\n\");\n  }\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1795",
    "index": "B",
    "title": "Ideal Point",
    "statement": "You are given $n$ one-dimensional segments (each segment is denoted by two integers — its endpoints).\n\nLet's define the function $f(x)$ as the number of segments covering point $x$ (a segment covers the point $x$ if $l \\le x \\le r$, where $l$ is the left endpoint and $r$ is the right endpoint of the segment).\n\nAn integer point $x$ is called ideal if it belongs to more segments than any other integer point, i. e. $f(y) < f(x)$ is true for any other integer point $y$.\n\nYou are given an integer $k$. Your task is to determine whether it is possible to remove some (possibly zero) segments, so that the given point $k$ becomes ideal.",
    "tutorial": "First of all, let's delete all segments that do not cover the point $k$ (because they increase the value of the function $f$ at points other than $k$). If there are no segments left, then the answer is NO. Otherwise, all segments cover the point $k$. And it remains to check whether the point $k$ is the only point which is covered by all segments. Note that it does not make sense to delete any of the remaining segments, because if there are several points with maximum value of $f$, then deleting segments can only increase their number. To check the number of points with the maximum value of $f$, you can iterate over $x$ from $1$ to $50$ and calculate $f(x)$, because of the small number of segments in the problem. A faster way is to check the size of the intersection of all segments. The left boundary of the intersection is $L = \\max\\limits_{i=1}^{n}{l_i}$, and the right boundary is $R = \\min\\limits_{i=1}^{n}{r_i}$; if $L = R$, then the point $k$ is ideal, otherwise it is not.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    int L = 0, R = 55;\n    while (n--) {\n      int l, r;\n      cin >> l >> r;\n      if (l <= k && k <= r)\n        L = max(L, l), R = min(R, r);\n    }\n    cout << (L == R ? \"YES\\n\" : \"NO\\n\");\n  }\n}",
    "tags": [
      "brute force",
      "geometry",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1795",
    "index": "C",
    "title": "Tea Tasting",
    "statement": "A tea manufacturer decided to conduct a massive tea tasting. $n$ sorts of tea will be tasted by $n$ tasters. Both the sorts of tea and the tasters are numbered from $1$ to $n$. The manufacturer prepared $a_i$ milliliters of the $i$-th sort of tea. The $j$-th taster can drink $b_j$ milliliters of tea at once.\n\nThe tasting will be conducted in steps. During the first step, the $i$-th taster tastes the $i$-th sort of tea. The $i$-th taster drinks $\\min(a_i, b_i)$ tea (how much is available of the $i$-th sort and how much the $i$-th taster can drink). $a_i$ also decreases by this amount.\n\nThen all tasters move to the previous sort of tea. Thus, during the second step, the $i$-th taster tastes the $(i-1)$-st sort of tea. The $i$-th taster drinks $\\min(a_{i-1}, b_i)$ tea. The $1$-st person ends the tasting.\n\nDuring the third step, the $i$-th taster tastes the $(i-2)$-nd sort of tea. The $2$-nd taster ends the tasting. This goes on until everyone ends the tasting.\n\nTake a look at the tasting process for $n = 3$, $a = [10, 20, 15]$, $b = [9, 8, 6]$. In the left row, there are the current amounts of each sort of tea. In the right column, there are current amounts of tea each taster has drunk in total. The arrow tells which taster each tea goes to on the current step. The number on the arrow is the amount — minimum of how much is available of the sort of tea and how much the taster can drink.\n\nFor each taster, print how many milliliters of tea he/she will drink in total.",
    "tutorial": "Consider how each sort of tea affects the tasters. The $i$-th sort makes testers $i, i + 1, \\dots, j - 1$, for some $j$, drink to their limit $b_i, b_{i + 1}, \\dots, b_{j - 1}$, and the $j$-th taster drink the remaining tea. Sometimes there is no such $j$-th taster, but we'll explore the general case. Let's add the remaining tea straight to the $j$-th taster answer $\\mathit{add}_j$. And for each taster $k$ from $i$ to $j-1$ we'll add $1$ into the value $\\mathit{cnt}_k$ denoting how many times they drank at their limit $b_k$. If we have these calculated, we can obtain the answer by adding $\\mathit{add}_i$ and $\\mathit{cnt}_i \\cdot b_i$. In order to find $j$, we can use prefix sums. Build $\\mathit{pref}$ over the sequence $b$. Now you want to find the largest $j$ such that $\\mathit{pref}_{j} - \\mathit{pref}_i \\le a_i$. Rewrite it as $\\mathit{pref}_{j} \\le a_i + \\mathit{pref}_i$. You can do this with a binary search. In particular, with an upper_bound call. The amount of the remaining tea can also be calculated from prefix sums. To add $1$ on a range $[i, j-1]$, you can use a technique called delta encoding. Add $1$ to $\\mathit{cnt}_i$. Subtract $1$ from $\\mathit{cnt}_j$. After everything is added, propagate this values via a prefix sum. This way, if both $+1$ and $-1$ happened non-strictly to the left or strictly to the right of $i$, it doesn't affect $i$ at all (the segment either closes before $i$ or opens after $i$). Otherwise, it adds exactly $1$ to $\\mathit{cnt}_i$. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing li = long long;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<li> a(n), b(n);\n    for (auto& x : a) cin >> x;\n    for (auto& x : b) cin >> x;\n    vector<li> sum(n + 1);\n    for (int i = 0; i < n; ++i) sum[i + 1] = sum[i] + b[i];\n    vector<li> cnt(n + 1), add(n + 1);\n    for (int i = 0; i < n; ++i) {\n      int j = upper_bound(sum.begin(), sum.end(), a[i] + sum[i]) - sum.begin() - 1;\n      cnt[i] += 1;\n      cnt[j] -= 1;\n      add[j] += a[i] - sum[j] + sum[i];\n    }\n    for (int i = 0; i < n; ++i) {\n      cout << cnt[i] * b[i] + add[i] << ' ';\n      cnt[i + 1] += cnt[i];   \n    }\n    cout << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1795",
    "index": "D",
    "title": "Triangle Coloring",
    "statement": "You are given an undirected graph consisting of $n$ vertices and $n$ edges, where $n$ is divisible by $6$. Each edge has a weight, which is a positive (greater than zero) integer.\n\nThe graph has the following structure: it is split into $\\frac{n}{3}$ triples of vertices, the first triple consisting of vertices $1, 2, 3$, the second triple consisting of vertices $4, 5, 6$, and so on. Every pair of vertices from the same triple is connected by an edge. There are no edges between vertices from different triples.\n\nYou have to paint the vertices of this graph into two colors, red and blue. Each vertex should have exactly one color, there should be exactly $\\frac{n}{2}$ red vertices and $\\frac{n}{2}$ blue vertices. The coloring is called valid if it meets these constraints.\n\nThe weight of the coloring is the sum of weights of edges connecting two vertices with different colors.\n\nLet $W$ be the maximum possible weight of a valid coloring. Calculate the number of valid colorings with weight $W$, and print it modulo $998244353$.",
    "tutorial": "Let's ignore the constraint on the number of red/blue vertices for a moment. What is the maximum possible weight of a coloring? From any triple, we can have any two edges connect vertices of different colors. So, the maximum possible weight of a coloring (not necessarily a valid one) is the sum of all edge weights except for the minimum weight in each triple. Let's show that it is always possible to choose a valid coloring to achieve this weight. In each triple, we should make sure that the two maximum edges connect vertices with different colors; to do this, we can color the vertex incident to both of these edges in one color, and the two other vertices will be painted in the other color. So, for each triple of vertices, there will be either one red vertex and two blue ones, or two red ones and one blue. Let's suppose the first $\\frac{n}{6}$ triples have one red vertex and two blue vertices each, and the other $\\frac{n}{6}$ triples have one blue vertex and two red vertices each. That way, we obtain a valid coloring with maximum possible weight. Okay, now let's try to find out how do we calculate the number of valid colorings with the maximum possible weight. Each triple of vertices will be either \"red\" (two red vertices, one blue), or \"blue\" (the other way around). Since exactly half of the vertices should be red, then exactly half of the triples should be red, so the number of ways to choose a \"color\" for all triples is ${n/3}\\choose{n/6}$. After choosing the color of each triple, let's choose how we actually color them. The triples are independent, so for each triple, we can introduce the coefficient $c_i$, which is the number of ways to color it so that its weight is maximized, and the triple has some specific type (either red or blue, doesn't matter since these are symmetric). Choosing the vertex which will be different from its neighbors is equivalent to choosing the edge which will not be included in the weight of the coloring (this is the edge which is not incident to the chosen vertex). So, $c_i$ is equal to the number of ways to choose that vertex in the $i$-th triple so that the weight is maximized; i. e. the weight of the edge not incident to the chosen vertex should be minimized. Thus, $c_i$ is just the number of minimum edge weights in the $i$-th triple. The formula for the final answer is ${{n/3}\\choose{n/6}} \\prod\\limits_{i=1}^{n/3} c_i$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    return ((x + y) % MOD + MOD) % MOD;\n}\n\nint mul(int x, int y)\n{\n    return x * 1ll * y % MOD;   \n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y)\n    {\n        if(y % 2 == 1) z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nint inv(int x)\n{\n    return binpow(x, MOD - 2);    \n}\n\nint divide(int x, int y)\n{\n    return mul(x, inv(y));\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n    int ans = 1;\n    for(int i = 1; i <= n / 6; i++)\n        ans = mul(ans, divide(i + n / 6, i));\n    for(int i = 0; i < n / 3; i++)\n    {\n        vector<int> a(3);\n        for(int j = 0; j < 3; j++)\n            cin >> a[j];\n        int mn = *min_element(a.begin(), a.end());\n        int cnt_min = count(a.begin(), a.end(), mn);\n        ans = mul(ans, cnt_min);\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1795",
    "index": "E",
    "title": "Explosions?",
    "statement": "You are playing yet another game where you kill monsters using magic spells. There are $n$ cells in the row, numbered from $1$ to $n$. Initially, the $i$-th cell contains the $i$-th monster with $h_i$ health.\n\nYou have a basic spell that costs $1$ MP and deals $1$ damage to the monster you choose. You can cast it any number of times. Also, you have a special scroll with \"Explosion\" spell you can use only once. You want to finish killing monsters with explosion, that's why you, firstly, cast the basic spell several times (possibly, zero), and then after that, you cast one \"Explosion\".\n\nHow does \"Explosion\" spell work? Firstly, you choose the power of the spell: if you pour $x$ MP into it, \"Explosion\" will deal $x$ damage. Secondly, you choose some monster $i$, which will be targeted by the spell. That's what happens next:\n\n- if its \\textbf{current} health $h_i > x$, then he stays alive with health decreased by $x$;\n- if $h_i \\le x$, the $i$-th monster dies with an explosion that deals $h_i - 1$ damage to monsters in the neighboring cells $i - 1$ and $i + 1$, if these cells exist and monsters inside are still alive;\n- if the damage dealt by the explosion is enough to kill the monster $i - 1$ (or $i + 1$), i. e. the current $h_{i - 1} \\le h_i - 1$ (or $h_{i + 1} \\le h_i - 1$), then that monster also dies creating a secondary explosion of power $h_{i-1} - 1$ (or $h_{i+1} - 1$) that may deals damage to their neighbors, and so on, until the explosions end.\n\nYour goal is to kill all the remaining monsters with those \"chaining\" explosions, that's why you need a basic spell to decrease $h_i$ of some monsters or even kill them beforehand (monsters die when their current health $h_i$ becomes less or equal to zero). Note that monsters don't move between cells, so, for example, monsters $i$ and $i + 2$ will never become neighbors.\n\nWhat is the minimum total MP you need to kill all monsters in the way you want? The total MP is counted as the sum of the number of basic spells you cast and the power $x$ of explosion scroll you've chosen.",
    "tutorial": "Note that each unit of damage dealt by explosions save us from using one more basic spell. In other words, the more the damage from explosions, the better. So, the answer will be equal to $\\sum{h_i} - (\\text{maximum total damage from explosions})$. Note that in order to kill all remaining monsters with the last spell, the array $h$ should have the following structure: there is a monster $p$ we cast the spell onto it and $h$ is strictly increasing in $[0..p]$ and strictly decreasing in $[p..n)$ (ignoring prefix and suffix of $0$-s). Let's focus on the left part of array $h$ (segment $[0...p]$), since solving the right part is exactly the same. Maximizing the total damage is equivalent to maximizing the sum of $h_i$ right before the final spell. Note that we can use the straight greedy strategy: to kill the chosen monster $p$ we should use \"Explosion\" spell of power exactly $h_p$ - it's not optimal to make it either more or less powerful. After that, monster $p$ will create an explosion of power $h_p - 1$. If $h_{p-1} > h_{p} - 1$ we must decrease it to exactly $h_{p} - 1$ to continue the chain of explosions of maximum total damage. If $h_{p-2} > h_{p} - 2$ we also decrease it to exactly $h_{p} - 2$ and so on. (The general formula is $h_{p - i} > h_{p} - i$). This series will stop either if $h_{p} - i \\le 0$ (or $i \\ge h_p$), or there are no monsters left ($p - i < 0$), or we met the monster with $h_{p - i} \\le h_{p} - i$. The two first cases are easy to check in constant time, so let's look at the last case. Suppose that monster position is equal to $j = p - i$, then $i = p - j$ or $h_{j} \\le h_{p} - (p - j)$ $\\leftrightarrow$ $h_{j} - j \\le h_{p} - p$. That monster $j$ is interesting to us because after death it creates an explosion of damage $h_{j} - 1$ that already doesn't depend on $p$ and next calculation is practically the same task: what chain of explosion we can have if we start from $j$. That idea drives us to dp: let $d[i]$ be the maximum damage of chaining explosion we can deal if we start from $i$ and move to the left. For simplicity, let's include $h_i$ into that total damage. Calculating $d[i]$ is next: let's find the \"first\" $j$ such that $h_{j} - j \\le h_{i} - i$. If there are no such $j$ (or if that $j$ is too far from $i$, i. e. $i - j \\ge h_i$), we will set $j = \\max(-1, i - h_i)$. Now we know that on interval $(j, i]$ the damage dealt is the arithmetic progression: for $i$ it's $h_i$, for $i - 1$ it's $h_i - 1$, ..., for $j + 1$ it's $h_i - (i - j) + 1$. In total, $d[i] = (i - j) h_i - \\frac{(i - j) (i - j - 1)}{2}$. And if such $j$ exists and not too far away, we increase $d[i]$ by $d[j]$ as well. The last question is finding for each $i$ the closest $j < i$ such that $a_j - i \\le a_i - i$. Note that if we define $a'_i = a_i - i$, we need just need to find last $a'_j \\le a'_i$ and that's quite standard task that can be solved with stack. Let's iterate over $i$ and maintain a stack of previous $a'_i$. When we need to find $j$ for the current $a'_i$ let's just look at the top of the stack: if $a'_j \\le a'_i$ we found $j$ we wanted, otherwise just pop it and check the new top again and so on, until either we find $j$ or stack becomes empty that would mean that there are no $a'_j \\le a'_i$. After processing the $i$-th element, push $a'_i$ on top of the stack. Why it works? Consider some $i$. The element on top of the stack is $a'_j$ (firstly, it's $a'_{i-1}$ but we are talking about general case). If $a'_j \\le a'_i$ we found what we want. Otherwise, $a'_j > a'_i$ but it also means that previous elements $a'_k$, that was popped on previous iteration $j$, was greater than $a'_j$. So, $a'_k$ is bigger than $a'_i$ as well, and there were no need to even consider them, i. e. popping them out earlier doesn't break anything. Since each element is pushed in the stack once and popped out once, then the complexity is $O(n)$ for all $i$ for $1$ to $n$, or $O(1)$ amortized. The answer for the chosen position $p$ then is $\\sum{h_i} - dL[p] - dR[p] + 2 h_p$ where $dL[p]$ is dp we discussed above, $dR[p]$ is the same dp but on reversed array $h$ and $2 h_p$ because we included $h_p$ into both $dL[p]$ and $dR[p]$. Both $dL$ and $dR$ are calculated in $O(n)$, so the total comlpexity is $O(n)$.",
    "code": "import java.util.*\n\nfun main() {\n    repeat(readln().toInt()) {\n        val n = readln().toInt()\n        var h = readln().split(' ').map { it.toInt() }\n\n        val d = Array(2) { LongArray(n) { 0 } }\n        for (tp in 0..1) {\n            val s = Stack<Pair<Int, Int>>()\n\n            for (i in h.indices) {\n                while (s.isNotEmpty() && s.peek().first > h[i] - i)\n                    s.pop()\n                var j = maxOf(-1, i - h[i])\n                if (s.isNotEmpty())\n                    j = maxOf(j, s.peek().second)\n\n                val len = (i - j).toLong()\n                d[tp][i] = len * h[i] - len * (len - 1) / 2\n                if (j >= 0 && len < h[i])\n                    d[tp][i] += d[tp][j]\n\n                s.push(Pair(h[i] - i, i))\n            }\n            h = h.reversed()\n        }\n        d[1] = d[1].reversedArray()\n\n        var ans = 1e18.toLong()\n        val sum = h.fold(0L) { total, it -> total + it }\n        for (i in h.indices) {\n            val cur = sum - d[0][i] - d[1][i] + 2 * h[i]\n            ans = minOf(ans, cur)\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1795",
    "index": "F",
    "title": "Blocking Chips",
    "statement": "You are given a tree, consisting of $n$ vertices. There are $k$ chips, placed in vertices $a_1, a_2, \\dots, a_k$. All $a_i$ are distinct. Vertices $a_1, a_2, \\dots, a_k$ are colored black initially. The remaining vertices are white.\n\nYou are going to play a game where you perform some moves (possibly, zero). On the $i$-th move ($1$-indexed) you are going to move the $((i - 1) \\bmod k + 1)$-st chip from its current vertex to an adjacent \\textbf{white} vertex and color that vertex \\textbf{black}. So, if $k=3$, you move chip $1$ on move $1$, chip $2$ on move $2$, chip $3$ on move $3$, chip $1$ on move $4$, chip $2$ on move $5$ and so on. If there is no adjacent white vertex, then the game ends.\n\nWhat's the maximum number of moves you can perform?",
    "tutorial": "The constraints tell us that the solution should be linear or pretty close to it. Well, in particular, that implies that the solution almost certainly isn't dynamic programming, since we have both $n$ and $k$ to care about. Thus, we'll think about something greedy. When we know the number of move the game will last, we can tell how many steps each chip should make. Well, since the more moves the game last, the more steps each ship makes, the answer is a monotonic function. Let's apply binary search and think if we can check if each chip can make some known number of steps. A common idea in the problems where you have to do something greedily on a tree is to root the tree arbitrarily and process everything bottom up. Consider the bottommost chip. If it can move its number of moves downwards, it's always optimal to do that. Since it's the bottommost chip, it can only make things worse for chips above it. And any of them can't pass through the initial vertex of this chip anyway. If it can't, it has to move to its parent vertex. Let's move it there and deal with this chip later - when it becomes the bottommost again. If it can't move to its parent, it can't move at all. Thus, the game can't last for this many steps. Since we only apply either the move which is guaranteed to not interrupt any other moves or the move which is forced, the greedy strategy is correct. As for implementation details, it's not too tricky. Basically, for each vertex, we should maintain these values: if this vertex has been visited; the number of steps the chip in this vertex still has to make (if any chip is in this vertex); the longest path downwards from this vertex via non-visited vertices. The second value can be initialized beforehand and pushed to the parent when needed. The rest of them are easily maintained with a single dfs. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nvector<vector<int>> g;\nvector<int> req;\nvector<char> used;\n\nvector<int> d;\n\nbool dfs(int v, int p = -1){\n    d[v] = 0;\n    for (int u : g[v]) if (u != p){\n        if (!dfs(u, v)) return false;\n        if (!used[u]) d[v] = max(d[v], d[u] + 1);\n    }\n    if (req[v] == 0 || d[v] >= req[v]) return true;\n    if (p == -1 || used[p]) return false;\n    used[p] = true;\n    req[p] = req[v] - 1;\n    return true;\n}\n\nint main(){\n    int t;\n    scanf(\"%d\", &t);\n    while (t--){\n        int n;\n        scanf(\"%d\", &n);\n        g.assign(n, {});\n        d.resize(n);\n        forn(i, n - 1){\n            int v, u;\n            scanf(\"%d%d\", &v, &u);\n            --v, --u;\n            g[v].push_back(u);\n            g[u].push_back(v);\n        }\n        int k;\n        scanf(\"%d\", &k);\n        vector<int> a(k);\n        forn(i, k){\n            scanf(\"%d\", &a[i]);\n            --a[i];\n        }\n        int l = 1, r = n;\n        int res = 0;\n        while (l <= r){\n            int m = (l + r) / 2;\n            used.assign(n, 0);\n            req.assign(n, 0);\n            forn(i, k){\n                used[a[i]] = true;\n                req[a[i]] = m / k + (i < m % k);\n            }\n            if (dfs(0)){\n                res = m;\n                l = m + 1;\n            }\n            else{\n                r = m - 1;\n            }\n        }\n        printf(\"%d\\n\", res);\n    }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1795",
    "index": "G",
    "title": "Removal Sequences",
    "statement": "You are given a simple undirected graph, consisting of $n$ vertices and $m$ edges. The vertices are numbered from $1$ to $n$. The $i$-th vertex has a value $a_i$ written on it.\n\nYou will be removing vertices from that graph. You are allowed to remove vertex $i$ only if its degree is equal to $a_i$. When a vertex is removed, all edges incident to it are also removed, thus, decreasing the degree of adjacent non-removed vertices.\n\nA valid sequence of removals is a permutation $p_1, p_2, \\dots, p_n$ $(1 \\le p_i \\le n)$ such that the $i$-th vertex to be removed is $p_i$, and every removal is allowed.\n\nA pair $(x, y)$ of vertices is nice if there exist two valid sequences of removals such that $x$ is removed before $y$ in one of them and $y$ is removed before $x$ in the other one.\n\nCount the number of nice pairs $(x, y)$ such that $x < y$.",
    "tutorial": "Let's consider what the sequence of removals looks like in general. We will base some intuition on a fact that at least one valid sequence is guaranteed to exist. Remove all vertices that have their degree correct from the start at once. There surely be such vertices, since a valid sequence would have to start with some of them. Notice that there can't be any adjacent vertices among them. If there were, we wouldn't be able to remove such a pair regardless of the order we choose, since removing one of them makes another one's degree too low. Now remove the vertices that just got their degrees correct from removing the first layer. Once again, these must exist (if the graph is not empty yet), because otherwise any valid sequence would get stuck. Process until nothing is left. This algorithm is basically a bfs, and you can implement it like one. Note that each vertex becomes available to be removed only after a certain subset of its neighbours is removed. No matter what order you choose to remove the vertices in, these vertices will always be the same. Huh, so for each vertex, some of its neighbours have to be removed before it, and the rest have to be removed after it (since otherwise, the degree of that vertex will become too low). That actually means that our graph is not as undirected as it seemed. We can direct each edge from a vertex that is removed before the other. This makes a valid sequence of removals just a topological sort of that directed graph. So a pair is nice if there exist two topological orders such that $x$ and $y$ go one before another in them. We can make a bold but perfectly reasonable guess about all nice pairs. A pair is nice if neither of $x$ and $y$ are reachable from each other. The necessity of this condition is obvious. Let's show sufficiency. Let's show the construction such that $x$ goes before $y$. To remove $x$, we first have to remove all vertices that have edges to $x$. To remove them, we have to remove vertices with edge to them. And so on. Basically, to remove $x$, we have to remove all vertices that are reachable from $x$ on the transposed directed graph. Since $x$ is not reachable from $y$, it doesn't have to be removed before $x$. So we can first remove all the required vertices, then remove $x$, then continue removing vertices until we are able to remove $y$. By switching $x$ and $y$ in the description of that construction, we can obtain the construction for $y$ before $x$. Thus, we reduced the problem to a rather well-known one. Calculate the number of reachable pairs of vertices in a directed graph. As far as I know, it's not known to be solvable in sub-quadratic time. And we are not given a specific graph. Yes, it's obviously acyclic, but turns out every acyclic graph can be made into a test for this problem. You just have to make $d_v$ equal to the number of the outgoing edges for each $v$. Somehow we are still given $10^5$ vertices and edges. If you are more familiar with that problem, you might know that you can use bitset to solve it. In particular, let $\\mathit{reach}[v]$ be a bitset such that $\\mathit{reach}[v][u] = 1$ if $u$ if reachable from $v$. Then you can initialize $\\mathit{reach}[v][v] = 1$ for all vertices and propagate the knowledge in reverse topological order by applying $\\mathit{reach}[v] = \\mathit{reach}[v] | \\mathit{reach}[u]$ for all edges $(v, u)$. Unfortunately, that requires $O(n^2)$ memory, and $10^{10}$ bits is over a gigabyte. Let's use of my favorite tricks to make a solution with $O(n)$ memory and the same complexity. Man, I love that trick. Process vertices in batches of $64$. Let's calculate which vertices can reach vertices from $1$ to $64$. The algorithm is basically the same. For each vertex, store a smaller bitset of size $64$ (also known as an unsigned long long). Initialize the bitset for $64$ vertices from the batch and propagate the same way for all $n$ vertices. Now just add up the number of ones in each bitset (__builtin_popcountll). Proceed to the next batch. That makes it $\\frac{n}{64}$ iterations of a $O(n + m)$ algorithm. This might require some constant optimizations. In particular, I suggest not to use dfs inside the iteration, since the recursion makes it really slow. You might iterate over a vertex in reverse topological order and its outgoing edges. Or, which is way faster, unroll that graph into a list of edges and iterate over it directly.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\ntypedef unsigned long long uli;\n\nint main(){\n    int t;\n    scanf(\"%d\", &t);\n    while (t--){\n        int n, m;\n        scanf(\"%d%d\", &n, &m);\n        vector<int> a(n);\n        forn(i, n) scanf(\"%d\", &a[i]);\n        vector<vector<int>> g(n);\n        forn(i, m){\n            int v, u;\n            scanf(\"%d%d\", &v, &u);\n            --v, --u;\n            g[v].push_back(u);\n            g[u].push_back(v);\n        }\n        vector<char> rem(n);\n        vector<int> d(n);\n        forn(i, n) d[i] = g[i].size();\n        queue<int> q;\n        forn(i, n) if (a[i] == d[i]) q.push(i);\n        vector<pair<int, int>> ord;\n        while (!q.empty()){\n            int v = q.front();\n            q.pop();\n            rem[v] = true;\n            for (int u : g[v]) if (!rem[u]){\n                --d[u];\n                ord.push_back({v, u});\n                if (d[u] == a[u])\n                    q.push(u);\n            }\n        }\n        reverse(ord.begin(), ord.end());\n        vector<uli> mask(n);\n        long long ans = n * 1ll * (n + 1) / 2;\n        for (int l = 0; l < n; l += 64){\n            int r = min(n, l + 64);\n            for (int i = l; i < r; ++i)\n                mask[i] = 1ull << (i - l);\n            for (const pair<int, int> &it : ord)\n                mask[it.first] |= mask[it.second];\n            forn(i, n){\n                ans -= __builtin_popcountll(mask[i]);\n                mask[i] = 0;\n            }\n        }\n        printf(\"%lld\\n\", ans);\n    }\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1796",
    "index": "A",
    "title": "Typical Interview Problem",
    "statement": "The FB-string is formed as follows. Initially, it is empty. We go through all positive integers, starting from $1$, in ascending order, and do the following for each integer:\n\n- if the current integer is divisible by $3$, append F to the end of the FB-string;\n- if the current integer is divisible by $5$, append B to the end of the FB-string.\n\nNote that if an integer is divisible by both $3$ and $5$, we append F, and then B, not in the opposite order.\n\nThe first $10$ characters of the FB-string are FBFFBFFBFB: the first F comes from the integer $3$, the next character (B) comes from $5$, the next F comes from the integer $6$, and so on. It's easy to see that this string is infinitely long. Let $f_i$ be the $i$-th character of FB-string; so, $f_1$ is F, $f_2$ is B, $f_3$ is F, $f_4$ is F, and so on.\n\nYou are given a string $s$, consisting of characters F and/or B. You have to determine whether it is a substring (contiguous subsequence) of the FB-string. In other words, determine if it is possible to choose two integers $l$ and $r$ ($1 \\le l \\le r$) so that the string $f_l f_{l+1} f_{l+2} \\dots f_r$ is exactly $s$.\n\nFor example:\n\n- FFB is a substring of the FB-string: if we pick $l = 3$ and $r = 5$, the string $f_3 f_4 f_5$ is exactly FFB;\n- BFFBFFBF is a substring of the FB-string: if we pick $l = 2$ and $r = 9$, the string $f_2 f_3 f_4 \\dots f_9$ is exactly BFFBFFBF;\n- BBB is not a substring of the FB-string.",
    "tutorial": "It's easy to see that the FB-string repeats every $8$ characters: after processing every $15$ numbers, we will get the same remainders modulo $3$ and $5$ as $15$ numbers ago, and when we process $15$ consecutive numbers, we get $8$ characters. So, $f_{i+8} = f_i$. This means that if we want to find a substring no longer than $10$ characters in the FB-string, we don't need to consider more than $17$ first characters of the FB-string: the substring of length $10$ starting with the $8$-th character ends with the $17$-th character, and we don't need to consider substrings starting on positions greater than $8$. So, the solution is to generate at least $17$ first characters of the FB-string, and then check if the substring occurs in the generated string using a standard function like find.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main()\n{\n    string fb;\n    int cur = 1;\n    while(fb.size() < 100)\n    {\n        if(cur % 3 == 0) fb += \"F\";\n        if(cur % 5 == 0) fb += \"B\";\n        cur++;\n    }\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int k;\n        cin >> k;\n        string s;\n        cin >> s;\n        cout << (fb.find(s) != string::npos ? \"YES\" : \"NO\") << endl;\n    }\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1796",
    "index": "B",
    "title": "Asterisk-Minor Template",
    "statement": "You are given two strings $a$ and $b$, consisting of lowercase Latin letters.\n\nA template $t$ is string, consisting of lowercase Latin letters and asterisks (character '*'). A template is called asterisk-minor if the number of asterisks in it is less than or equal to the number of letters in it.\n\nA string $s$ is said to be matching a template $t$ if you can replace each asterisk in $t$ with a string of lowercase Latin letters (possibly, an empty string) so that it becomes equal to $s$.\n\nFind an asterisk-minor template such that both $a$ and $b$ match it, or report that such a template doesn't exist. If there are multiple answers, print any of them.",
    "tutorial": "What's the reason behind authors specifically asking for templates that have less or equal asterisks than letters? Well, without that the problem would be kind of trivial. A template \"*\" is matched by every string, so it would always work. Hmm, let's try to make something similar to that template then. We basically have to find some part of that occurs in both strings that we can use letters on to get some freedom to use asterisks. There are some easy cases. If the first letters of both strings are the same, then the template can be that letter followed by an asterisk. There's a symmetrical case for the last letter. By studying the examples, you can also notice the final case: a common substring of both strings of length at least two surrounded by two asterisks. Moreover, since we only use two asterisks, we can find a substring of length exactly two (which always exists if a longer common substring exists). Turns out, that's it. If a template exists, one of these three kinds also exists. This is not that hard to show. If the first two kinds don't work, then you have to use asterisks on both sides of the template. In order for the template with asterisks on both sides to work, there have to be adjacent letters in it at least once (otherwise, it's like \"*a*a*a*\", and there are more asterisks than letters). And since at least one such substring exists, we can just remove everything other than this substring and the asterisks on the sides. Overall complexity: $O(|a| \\cdot |b|)$ per testcase.",
    "code": "for _ in range(int(input())):\n    a = input()\n    b = input()\n    if a[0] == b[0]:\n        print(\"YES\")\n        print(a[0] + \"*\")\n        continue\n    if a[-1] == b[-1]:\n        print(\"YES\")\n        print(\"*\" + a[-1])\n        continue\n    for i in range(len(b) - 1):\n        if (b[i] + b[i + 1]) in a:\n            print(\"YES\")\n            print(\"*\" + b[i] + b[i + 1] + \"*\")\n            break\n    else:\n        print(\"NO\")",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1796",
    "index": "C",
    "title": "Maximum Set",
    "statement": "A set of positive integers $S$ is called beautiful if, for every two integers $x$ and $y$ from this set, either $x$ divides $y$ or $y$ divides $x$ (or both).\n\nYou are given two integers $l$ and $r$. Consider all beautiful sets consisting of integers not less than $l$ and not greater than $r$. You have to print two numbers:\n\n- the maximum possible size of a beautiful set where all elements are from $l$ to $r$;\n- the number of beautiful sets consisting of integers from $l$ to $r$ with the maximum possible size.\n\nSince the second number can be very large, print it modulo $998244353$.",
    "tutorial": "Every beautiful set can be represented as a sequence of its elements in sorted order. Let these elements for some set be $a_1, a_2, \\dots, a_m$; also, let $d_i = \\frac{a_{i+1}}{a_i}$. When the set is beautiful, every $d_i$ is an integer greater than $1$. It's easy to see that if $a_1$ and $a_m$ belong to $[l, r]$, the whole set belongs to $[l, r]$. Since $a_m = a_1 \\cdot \\prod \\limits_{i=1}^{m-1} d_i$, in order to maximize $m$, we need to choose $a_1$ and $d_i$ as small as possible. So, why don't we choose $a_1 = l$ and every $d_i = 2$? This will allow us to calculate the maximum possible size of a beautiful set (let $m$ be this maximum possible size). Okay, what about counting those sets? The claims $a_1 = l$ and that every $d_i = 2$ are no longer true by default. However, there are some constraints on $d_i$. Firstly, every $d_i \\le 3$. If we had some value of $d_i \\ge 4$, we could replace it with two values of $d_i = 2$, and the size of the set would increase. Secondly, there is at most one $d_i = 3$. If there are two values $d_i = 3$, we could replace them with three $d_i = 2$, and the size of the set would increase as well. So, the sequence $d_i$ contains at most one value $3$, and the rest of the values are $2$. We will divide the sets we want to count into two categories: the ones with all $d_i = 2$, and the ones with one value $d_i = 3$. To count the sets in the first category, we simply need to count the number of different minimum values in those sets. Those minimum values have to be such that multiplying them by $2^{m-1}$ wouldn't make them greater than $r$, so these are all integers from the segment $[l, \\lfloor \\frac{r}{2^{m-1}} \\rfloor]$. For every such integer, there exists exactly one set of the first category. To count the sets in the second category, we do a similar thing. The minimum value in the set should be from the segment $[l, \\lfloor \\frac{r}{2^{m-2} \\cdot 3} \\rfloor$; but for every integer from this segment, there are $m-1$ different sets of the second category since there are $m-1$ ways to choose which $d_i$ is equal to $3$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int l, r;\n        cin >> l >> r;\n        int max_size = 1;\n        while((l << max_size) <= r)\n            max_size++;\n        int ans2 = (r / (1 << (max_size - 1)) - l + 1);\n        if(max_size > 1)\n            ans2 += (max_size - 1) * max(0, (r / (1 << (max_size - 2)) / 3 - l + 1));\n        cout << max_size << \" \" << ans2 << endl;\n    }\n}",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1796",
    "index": "D",
    "title": "Maximum Subarray",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$, consisting of $n$ integers. You are also given two integers $k$ and $x$.\n\nYou have to perform the following operation exactly once: add $x$ to the elements on \\textbf{exactly} $k$ \\textbf{distinct} positions, and subtract $x$ from all the others.\n\nFor example, if $a = [2, -1, 2, 3]$, $k = 1$, $x = 2$, and we have picked the first element, then after the operation the array $a = [4, -3, 0, 1]$.\n\nLet $f(a)$ be the maximum possible sum of a subarray of $a$. The subarray of $a$ is a contiguous part of the array $a$, i. e. the array $a_i, a_{i + 1}, \\dots, a_j$ for some $1 \\le i \\le j \\le n$. An empty subarray should also be considered, it has sum $0$.\n\nLet the array $a'$ be the array $a$ after applying the aforementioned operation. Apply the operation in such a way that $f(a')$ is the maximum possible, and print the maximum possible value of $f(a')$.",
    "tutorial": "There are greedy and dynamic programming solutions. We will describe dynamic programming solution. The main task is to choose some segment that is the answer to the problem, while choosing $k$ positions to increase by $x$. To do this, we can use dynamic programming $dp_{i, j, t}$, where $i$ is the number of positions that have already been considered (from $0$ to $n$), $j$ is the number of elements that have already been increased by $x$ (from $0$ to $k$), $t$ is the flag showing the current state (whether we are before the chosen segment, inside the segment, or after the segment). Transitions in such dynamic programming are quite simple: we have a choice either to increase $j$ by $1$, then the value of the $i$-th element is $a_i + x$, or not to increase, then the value of the $i$-th element is $a_i - x$; we can also change the state of the flag (note that you can only switch from the current state to the subsequent ones, i.e., for example, you cannot switch from the state \"the segment has already ended\" to the state \"inside the segment\"). If the current state of the flag is \"inside the segment\", then $a_i + x$ or $a_i - x$ (depending on the selected transition) should be added to the dynamic programming value itself. So, we got a solution in $O(nk)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing li = long long;\n\nconst int N = 222222;\nconst int K = 22;\nconst li INF = 1e18;\n\nint n, k, x;\nint a[N];\nli dp[N][K][3];\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int tc;\n  cin >> tc;\n  while (tc--) {\n    cin >> n >> k >> x;\n    for (int i = 0; i < n; ++i) cin >> a[i];\n    for (int i = 0; i <= n; ++i) {\n      for (int j = 0; j <= k; ++j) { \n        for (int t = 0; t < 3; ++t) {\n          dp[i][j][t] = -INF;\n        }\n      }\n    }\n    dp[0][0][0] = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j <= k; ++j) {\n        for (int t = 0; t < 3; ++t) {\n          if (dp[i][j][t] == -INF) continue;\n          for (int jj = j; jj <= min(k, j + 1); ++jj) {\n            li add = a[i] + (j == jj ? -x : x);\n            for (int tt = t; tt < 3; ++tt) {\n              dp[i + 1][jj][tt] = max(dp[i + 1][jj][tt], dp[i][j][t] + (tt == 1 ? add : 0));\n            }\n          }\n        }\n      }\n    }\n    cout << max(dp[n][k][1], dp[n][k][2]) << '\\n';\n  }\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1796",
    "index": "E",
    "title": "Colored Subgraphs",
    "statement": "Monocarp has a tree, consisting of $n$ vertices.\n\nHe is going to select some vertex $r$ and perform the following operations on each vertex $v$ from $1$ to $n$:\n\n- set $d_v$ equal to the distance from $v$ to $r$ (the number of edges on the shortest path);\n- color $v$ some color.\n\nA nice coloring satisfies two conditions:\n\n- for each pair of vertices of the same color $(v, u)$, there exists a path from $v$ to $u$ that only visits vertices of the same color;\n- for each pair of vertices of the same color $(v, u)$, $d_v \\neq d_u$.\n\nNote that Monocarp can choose any amount of different colors he wants to use.\n\nFor each used color, he then counts the number of vertices of this color. The cost of the tree is the minimum of these numbers.\n\nWhat can be the maximum cost of the tree?",
    "tutorial": "Let's start by choosing a vertex $r$ naively. Iterate over all vertices and try each of them. Root the tree by $r$ and observe what the conditions become. $d_v$ for each $v$ is just the depth of each vertex. Well, then the only case, when the connected subgraph of vertices of the same color has all values of $d$ distinct, is when they form a vertical path in the tree. So the problem becomes the following. Split the tree into some vertical paths in such a way that the shortest path is as long as possible. Let's try greedy, I guess. Start the paths from the leaves and propagate them up. Consider some vertex $v$ with at least two children. All children have some paths leading up to them. We'd love to continue them all with $v$, but we can't do that. We can only continue one path and cut the rest. Pretty easy to see that the path to continue is the shortest path available. It's at least as optimal as any other path. Do that from the lowest vertices up, and you got yourself a working greedy. Also don't forget to stop all paths in root, since you can't continue any of them further up. Let's make this greedy more formal. Every time we update the answer is with a path that is: the shortest in every vertex lower than the current one; not the shortest in the current one. So we want to propagate the shortest child up and update the answer with the remaining children. Updating the answer means just taking the minimum of values. Thus, we can actually ignore all children except the second shortest in each vertex. Just don't forget to treat the root properly. Now we can actually solve the problem in $O(n)$ for a fixed $r$. You can just find two minimums in each vertex. Well, now that we can solve the problem for a single root, let's try rerooting to solve for all of them. There are solutions in $O(n)$ but I found the solution in $O(n \\log n)$ the neatest. The constraints are low enough to allow it. For each vertex, maintain a multiset of lengths of vertical paths from its children. I chose to store nothing in the leaves - that only makes the implementation cleaner. In order to update the vertex from its child, you can take the minimum element in the child's set and add $1$ to it. If it's empty (the child is a leaf), return $1$. Additionally, store a multiset of the second minimums of all vertices that have at least two children. In order to update the answer with the current root, find the minimum of that multiset and the shortest path from the root. To achieve $O(n)$, you will probably have to either store prefix and suffix second minimums over children of each vertex or store three shortest paths in it. It is kind of messy but it should still perform better. Overall complexity: $O(n \\log n)$ or $O(n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nvector<vector<int>> g;\nvector<multiset<int>> len;\nmultiset<int> all;\n\nint getlen(int v){\n    return len[v].empty() ? 1 : *len[v].begin() + 1;\n}\n\nvoid init(int v, int p = -1){\n    for (int u : g[v]) if (u != p){\n        init(u, v);\n        len[v].insert(getlen(u));\n    }\n    if (int(len[v].size()) > 1){\n        all.insert(*(++len[v].begin()));\n    }\n}\n\nint ans;\n\nvoid dfs(int v, int p = -1){\n    ans = max(ans, min(*len[v].begin() + 1, *all.begin()));\n    \n    for (int u : g[v]) if (u != p){\n        if (int(len[v].size()) > 1) all.erase(all.find(*(++len[v].begin())));\n        len[v].erase(len[v].find(getlen(u)));\n        if (int(len[v].size()) > 1) all.insert(*(++len[v].begin()));\n        \n        if (int(len[u].size()) > 1) all.erase(all.find(*(++len[u].begin())));\n        len[u].insert(getlen(v));\n        if (int(len[u].size()) > 1) all.insert(*(++len[u].begin()));\n        \n        dfs(u, v);\n        \n        if (int(len[u].size()) > 1) all.erase(all.find(*(++len[u].begin())));\n        len[u].erase(len[u].find(getlen(v)));\n        if (int(len[u].size()) > 1) all.insert(*(++len[u].begin()));\n        \n        if (int(len[v].size()) > 1) all.erase(all.find(*(++len[v].begin())));\n        len[v].insert(getlen(u));\n        if (int(len[v].size()) > 1) all.insert(*(++len[v].begin()));\n    }\n}\n\nint main(){\n    int t;\n    scanf(\"%d\", &t);\n    while (t--){\n        int n;\n        scanf(\"%d\", &n);\n        g.assign(n, {});\n        forn(i, n - 1){\n            int v, u;\n            scanf(\"%d%d\", &v, &u);\n            --v, --u;\n            g[v].push_back(u);\n            g[u].push_back(v);\n        }\n        len.assign(n, {});\n        all.clear();\n        all.insert(n);\n        init(0);\n        ans = 0;\n        dfs(0);\n        printf(\"%d\\n\", ans);\n    }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1796",
    "index": "F",
    "title": "Strange Triples",
    "statement": "Let's call a triple of positive integers ($a, b, n$) strange if the equality $\\frac{an}{nb} = \\frac{a}{b}$ holds, where $an$ is the concatenation of $a$ and $n$ and $nb$ is the concatenation of $n$ and $b$. For the purpose of concatenation, the integers are considered without leading zeroes.\n\nFor example, if $a = 1$, $b = 5$ and $n = 9$, then the triple is strange, because $\\frac{19}{95} = \\frac{1}{5}$. But $a = 7$, $b = 3$ and $n = 11$ is not strange, because $\\frac{711}{113} \\ne \\frac{7}{3}$.\n\nYou are given three integers $A$, $B$ and $N$. Calculate the number of strange triples $(a, b, n$), such that $1 \\le a < A$, $1 \\le b < B$ and $1 \\le n < N$.",
    "tutorial": "Let $|n|$ be the length of number $n$. Then $\\frac{an}{nb} = \\frac{a}{b} \\Leftrightarrow (a \\cdot 10^{|n|} + n) b = a (n \\cdot 10^{|b|} + b)$ $(a \\cdot 10^{|n|} + n) b = a (n \\cdot 10^{|b|} + b) \\Leftrightarrow g^2 a' b' \\cdot 10^{|n|} + g n b' = g a' n \\cdot 10^{|b|} + g^2 a' b' \\Leftrightarrow$ $\\Leftrightarrow g a' b' \\cdot 10^{|n|} + n b' = a' n \\cdot 10^{|b|} + g a' b'$ Note that the right part is divisible by $a'$, so the left part should as well. Then we can see that $n$ should be divisible by $a'$, since $\\gcd(b', a') = 1$. Let's say $n = n' a'$ then divide both sides by $a'$. We get $g a' b' \\cdot 10^{|n|} + n' a' b' = a' n' a' \\cdot 10^{|b|} + g a' b' \\Leftrightarrow g b' \\cdot 10^{|n|} + n' b' = a' n' \\cdot 10^{|b|} + g b'$ Let's rearrange it and get the following: $n' b' = a' n' \\cdot 10^{|b|} - b (10^{|n|} - 1)$ $b' = a' \\cdot 10^{|b|} - \\frac{b (10^{|n|} - 1)}{n'}$ Since $b'$ is integer, then $\\frac{b (10^{|n|} - 1)}{n'}$ should be integer. In other words, we can define $n' = k_1 k_2$ such that $b$ is divisible by $k_1$ and $(10^{|n|} - 1)$ is divisible by $k_2$ and $k_1$ is minimum possible. Since $(10^{|n|} - 1)$ has a very special structure, let's iterate over all lengths $|n|$ ($1 \\le |n| \\le 9$) and all divisors $k_2$ of $(10^{|n|} - 1)$ for a fixed $|n|$. Let's say $d = \\frac{b}{k_1}$ and $r = \\frac{(10^{|n|} - 1)}{k_2}$. Then $b' = a' \\cdot 10^{|b|} - d \\cdot r$ For a fixed $|n|$ and $k_2$ we know $r$, but don't know $d$. So, let's just iterate over all possible $d$ ($1 \\le d \\le 10^5$) and let's also iterate over all $|b|$, since $|b|$ is small ($|d| \\le |b| \\le 5$, since $d$ is a divisor of $b$). Next step is following: let's look at previous equation, but modulo $10^{|b|}$: $b' \\equiv - d \\cdot r \\pmod {10^{|b|}}$ Since $b' \\le b < 10^{|b|}$ then there is a unique solution to the previous module equation, or: $b' = 10^{|b|} - (d \\cdot r) \\bmod {10^{|b|}}$ Now we know exact value $b'$ and $|b|$, so now the time to guess $g$ (let's recall that $b = b' g$). Since we fixed $|b|$, then $10^{|b| - 1} \\le b' g < 10^{|b|}$, or $\\left\\lceil \\frac{10^{|b| - 1}}{b'} \\right\\rceil \\le g \\le \\left\\lfloor \\frac{10^{|b|} - 1}{b'} \\right\\rfloor$ But we can make constrains even tighter: note that $b = b' g$, but lately, we said that $d = \\frac{b}{k_1}$ or $b = d k_1$. So, $b' g = d k_1$, or $g$ should be divisible by $dd = \\frac{d}{\\gcd(d, b')}$. In total, we can iterate $g$ in range $[\\left\\lceil \\frac{lb}{dd} \\right\\rceil \\cdot dd, \\dots, \\left\\lfloor \\frac{rb}{dd} \\right\\rfloor \\cdot dd]$ with step $dd$, since we are interested only in $g$ divisible by $dd$. Now we have enough variables to construct a triple: we know $b'$ and $g$, so $b = b' g$. If $b$ is already big ($b \\ge B$), we can skip that candidate. Also, we can calculate $k_1 = \\frac{b}{d}$ and check that pair $(k_1, k_2)$ is valid, i. e. $k_1$ is really minimum possible. We can understand it by checking that $\\gcd(k_1, r) = 1$ (otherwise, we can reduce $k_1$ by $\\gcd(k_1, r)$). Value $a'$ can be calculated from one of the formulas above as $a' = \\frac{d \\cdot r + b'}{10^{|b|}}$. After that, we calculate $a = a' g$ and check that $a$ is not too big. Value $n$ can be calculated as $n = k_1 k_2 a' = \\frac{b}{d} k_2 a'$. At last, we should check that the given triple satisfy all remaining assumptions we made: $n$ is not too big, $\\gcd(a', b')$ is really $1$ and length of calculated $n$ is exactly $|n|$ we fixed. If it's all fine, then we found a correct triple. It looks like, thanks to all previous checks, the triple we found is unique, but, just for safety, let's push them all in one set to get rid of copies. Calculating complexity is not trivial, but let's note something: the total number of divisors $k_2$ of $10^{|n|} - 1$ for all $|n|$ is around $180$. For a fixed pair $(|n|, k_2)$, we iterate over all $d$ from $1$ to $B$ and for each $d$ we iterate $|b|$ from $|d|$ to $5$, but it's easy to prove that the total number of pairs $(d, |b|)$ is at most $1.3 \\cdot B$. Now the last cycle: iteration of $g$ with step $dd$ where $dd = \\frac{d}{\\gcd(d, b')}$. If we assume that $\\gcd(d, b')$ is quite small then $dd$ is proportional to $d$, and pairs $(d, g)$ are something like harmonic series with $O(B \\log B)$ complexity. In total, the complexity is around $O(200 B \\log{B})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\n#define sz(a) int((a).size())\n\nusing li = long long;\n\nconst int MAXLEN = 5;\n\nvector<int> divs(int x) {\n  vector<int> res;\n  for (int i = 1; i * i <= x; ++i) {\n    if (x % i == 0) {\n      res.push_back(i);\n      if (i * i != x)\n        res.push_back(x / i);\n    }\n  }\n  return res;\n}\n\nint main() {\n  int A, B, N;\n  cin >> A >> B >> N;\n\n  vector<int> pw(10);\n  pw[0] = 1;\n  for (int i = 1; i < 10; ++i) pw[i] = pw[i - 1] * 10;\n  \n  int PW = pw[MAXLEN];\n  set<array<int, 3>> used;\n  \n  vector<int> len(PW);\n  for (int i = 0; i < PW; ++i)\n    len[i] = sz(to_string(i));\n  \n  for (int lenn = 1; lenn <= 9; ++lenn) {\n    int x = pw[lenn] - 1;\n    for (int k2 : divs(x)) {\n      int r = x / k2;\n      for (int d = 1; d < PW; ++d) {\n        for (int lenb = len[d]; lenb <= MAXLEN; ++lenb) {\n          int bg = pw[lenb] - d * li(r) % pw[lenb];\n          int dd = d / __gcd(d, bg);\n          int lb = (pw[lenb - 1] + bg - 1) / bg;\n          int rb = (pw[lenb] - 1) / bg;\n          for (int g = (lb + dd - 1) / dd * dd; g <= rb; g += dd) {\n            int b = bg * g;\n            assert(b % d == 0);\n            if (b >= B || __gcd(b / d, r) != 1) continue;\n            int ag = (d * li(r) + bg) / pw[lenb];\n            li n = b / d * li(k2) * ag;\n            if (n < N && ag * g < A && __gcd(ag, bg) == 1 && sz(to_string(n)) == lenn) \n              used.insert({ag * g, b, n});\n          }\n        }\n      }\n    }\n  }\n  \n  int res = 0;\n  for (auto it : used) {\n    li a = it[0], b = it[1], n = it[2];\n    int lenn = sz(to_string(n));\n    int lenb = sz(to_string(b));\n    res += a * b * pw[lenn] + n * b == a * n * pw[lenb] + a * b;\n  }\n  \n  cout << res << endl;\n}\n",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1797",
    "index": "A",
    "title": "Li Hua and Maze",
    "statement": "There is a rectangular maze of size $n\\times m$. Denote $(r,c)$ as the cell on the $r$-th row from the top and the $c$-th column from the left. Two cells are adjacent if they share an edge. A path is a sequence of adjacent empty cells.\n\nEach cell is initially empty. Li Hua can choose some cells (except $(x_1, y_1)$ and $(x_2, y_2)$) and place an obstacle in each of them. He wants to know the minimum number of obstacles needed to be placed so that there isn't a path from $(x_1, y_1)$ to $(x_2, y_2)$.\n\nSuppose you were Li Hua, please solve this problem.",
    "tutorial": "We can put obstacles around $(x_1,y_1)$ or $(x_2,y_2)$ and the better one is the answer. More formally, let's define a function $f$: $f(x,y)= \\begin{cases} 2,&(x,y)\\textrm{ is on the corner}\\\\ 3,&(x,y)\\textrm{ is on the border}\\\\ 4,&(x,y)\\textrm{ is in the middle}\\\\ \\end{cases}$ Then the answer is $\\min\\{f(x_1,y_1),f(x_2,y_2)\\}$. Without loss of generality, assume that $f(x_1,y_1)\\le f(x_2,y_2)$. As the method is already given, the answer is at most $f(x_1,y_1)$. Let's prove that the answer is at least $f(x_1,y_1)$. If $(x_1,y_1)$ is on the corner, we can always find two paths from $(x_1,y_1)$ to $(x_2,y_2)$ without passing the same cell (except $(x_1,y_1)$ and $(x_2,y_2)$). Similarly, we can always find three or four paths respectively if $(x_1,y_1)$ is on the border or in the middle. As the paths have no common cell, we need to put an obstacle on each path, so the answer is at least $f(x_1,y_1)$. In conclusion, the answer is exactly $f(x_1,y_1)$. As we assumed that $f(x_1,y_1)\\le f(x_2,y_2)$, the answer to the original problem is $\\min\\{f(x_1,y_1),f(x_2,y_2)\\}$. Time complexity: $O(1)$.",
    "code": "//By: OIer rui_er\n#include <bits/stdc++.h>\n#define rep(x,y,z) for(int x=(y);x<=(z);x++)\n#define per(x,y,z) for(int x=(y);x>=(z);x--)\n#define debug(format...) fprintf(stderr, format)\n#define fileIO(s) do{freopen(s\".in\",\"r\",stdin);freopen(s\".out\",\"w\",stdout);}while(false)\nusing namespace std;\ntypedef long long ll;\n \n#define y1 y114514\nint T, n, m, x1, y1, x2, y2;\ntemplate<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}\ntemplate<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}\nint f(int x, int y) {\n\tif((x == 1 || x == n) && (y == 1 || y == m)) return 2;\n\tif(x == 1 || x == n || y == 1 || y == m) return 3;\n\treturn 4;\n}\n \nint main() {\n\tfor(scanf(\"%d\", &T);T;T--) {\n\t\tscanf(\"%d%d%d%d%d%d\", &n, &m, &x1, &y1, &x2, &y2);\n\t\tprintf(\"%d\\n\", min(f(x1, y1), f(x2, y2)));\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "flows",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1797",
    "index": "B",
    "title": "Li Hua and Pattern",
    "statement": "Li Hua has a pattern of size $n\\times n$, each cell is either blue or red. He can perform \\textbf{exactly $k$} operations. In each operation, he chooses a cell and changes its color from red to blue or from blue to red. Each cell can be chosen as many times as he wants. Is it possible to make the pattern, that matches its rotation by $180^{\\circ}$?\n\nSuppose you were Li Hua, please solve this problem.",
    "tutorial": "We can calculate the minimum needed operations $k_{\\min}$ easily by enumerating through the cells and performing an operation if the color of the cell is different from the targeted cell. Obviously, if $k < k_{\\min}$, the problem has no solution. Otherwise, there are two cases: If $2\\mid n$, the solution exists if and only if $2\\mid(k-k_{\\min})$, as we must perform two operations each time to meet the requirement. If $2\\nmid n$, the solution always exists, as we can perform the remaining operations at the center of the pattern. Time complexity: $O(n^2)$.",
    "code": "//By: OIer rui_er\n#include <bits/stdc++.h>\n#define rep(x,y,z) for(int x=(y);x<=(z);x++)\n#define per(x,y,z) for(int x=(y);x>=(z);x--)\n#define debug(format...) fprintf(stderr, format)\n#define fileIO(s) do{freopen(s\".in\",\"r\",stdin);freopen(s\".out\",\"w\",stdout);}while(false)\nusing namespace std;\ntypedef long long ll;\nconst int N = 1e3+5;\n \nint T, n, k, a[N][N];\ntemplate<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}\ntemplate<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}\n \nint main() {\n\tfor(scanf(\"%d\", &T);T;T--) {\n\t\tscanf(\"%d%d\", &n, &k);\n\t\trep(i, 1, n) rep(j, 1, n) scanf(\"%d\", &a[i][j]);\n\t\tint diff = 0;\n\t\trep(i, 1, n) rep(j, 1, n) if(a[i][j] != a[n+1-i][n+1-j]) ++diff;\n\t\tdiff /= 2;\n\t\tif(diff > k) puts(\"NO\");\n\t\telse {\n\t\t\tk -= diff;\n\t\t\tif(n & 1) puts(\"YES\");\n\t\t\telse if(k & 1) puts(\"NO\");\n\t\t\telse puts(\"YES\");\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1797",
    "index": "C",
    "title": "Li Hua and Chess",
    "statement": "\\textbf{This is an interactive problem.}\n\nLi Ming and Li Hua are playing a game. Li Hua has a chessboard of size $n\\times m$. Denote $(r, c)$ ($1\\le r\\le n, 1\\le c\\le m$) as the cell on the $r$-th row from the top and on the $c$-th column from the left. Li Ming put a king on the chessboard and Li Hua needs to guess its position.\n\nLi Hua can ask Li Ming \\textbf{no more than $3$} questions. In each question, he can choose a cell and ask the minimum steps needed to move the king to the chosen cell. Each question is independent, which means the king doesn't actually move.\n\nA king can move from $(x,y)$ to $(x',y')$ if and only if $\\max\\{|x-x'|,|y-y'|\\}=1$ (shown in the following picture).\n\n\\begin{center}\n\\begin{tabular}{c}\n\\\n\\end{tabular}\n\\end{center}\n\nThe position of the king is chosen \\textbf{before} the interaction.\n\nSuppose you were Li Hua, please solve this problem.",
    "tutorial": "We can first ask $(1,1)$ and get the result $k$. Obviously, the king must be on the following two segments: from $(1,k+1)$ to $(k+1,k+1)$. from $(k+1,1)$ to $(k+1,k+1)$. Then, we can ask $(1,k+1)$ and $(k+1,1)$ and get the results $p,q$. There are three cases: If $p=q=k$, the king is at $(k+1,k+1)$. If $p < k$, the king is at $(p+1,k+1)$. If $q < k$, the king is at $(k+1,q+1)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint T, n, m;\n \nint ask(int x, int y) {\n\tprintf(\"? %d %d\\n\", x, y);\n\tfflush(stdout);\n\tscanf(\"%d\", &x);\n\treturn x;\n}\n \nvoid give(int x, int y) {\n\tprintf(\"! %d %d\\n\", x, y);\n\tfflush(stdout);\n}\n \nint main() {\n\tfor(scanf(\"%d\", &T);T;T--) {\n\t\tscanf(\"%d%d\", &n, &m);\n\t\tint T1 = ask(1, 1);\n\t\tif(T1 >= n) {\n\t\t\tint T2 = ask(1, T1+1);\n\t\t\tgive(T2+1, T1+1);\n\t\t}\n\t\telse if(T1 >= m) {\n\t\t\tint T2 = ask(T1+1, 1);\n\t\t\tgive(T1+1, T2+1);\n\t\t}\n\t\telse {\n\t\t\tint T2 = ask(T1+1, 1);\n\t\t\tint T3 = ask(1, T1+1);\n\t\t\tif(T2 == T1 && T3 == T1) give(T1+1, T1+1);\n\t\t\telse if(T3 == T1) give(T1+1, T2+1);\n\t\t\telse give(T3+1, T1+1);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "interactive"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1797",
    "index": "D",
    "title": "Li Hua and Tree",
    "statement": "Li Hua has a tree of $n$ vertices and $n-1$ edges. The root of the tree is vertex $1$. Each vertex $i$ has importance $a_i$. Denote the size of a subtree as the number of vertices in it, and the importance as the sum of the importance of vertices in it. Denote the heavy son of a non-leaf vertex as the son with the \\textbf{largest} subtree size. If multiple of them exist, the heavy son is the one with the \\textbf{minimum} index.\n\nLi Hua wants to perform $m$ operations:\n\n- \"1 $x$\" ($1\\leq x \\leq n$) — calculate the importance of the subtree whose root is $x$.\n- \"2 $x$\" ($2\\leq x \\leq n$) — rotate the heavy son of $x$ up. Formally, denote $son_x$ as the heavy son of $x$, $fa_x$ as the father of $x$. He wants to remove the edge between $x$ and $fa_x$ and connect an edge between $son_x$ and $fa_x$. It is guaranteed that $x$ is not root, but \\textbf{not} guaranteed that $x$ is not a leaf. If $x$ is a leaf, please ignore the operation.\n\nSuppose you were Li Hua, please solve this problem.",
    "tutorial": "Denote $T_x$ as the subtree of $x$. The \"rotate\" operation doesn't change the tree much. More specifically, only the importance of $T_{fa_x},T_x,T_{son_x}$ changes. We can use the brute force method to maintain useful information about each vertex when the operations are performed. What we need to do next is to find the heavy son of a vertex in a reasonable time. We can use a set to maintain the size and index of all the sons of each vertex. Time complexity: $O((n+m)\\log n)$.",
    "code": "//By: Luogu@rui_er(122461)\n#include <bits/stdc++.h>\n#define rep(x,y,z) for(ll x=y;x<=z;x++)\n#define per(x,y,z) for(ll x=y;x>=z;x--)\n#define debug printf(\"Running %s on line %d...\\n\",__FUNCTION__,__LINE__)\n#define fileIO(s) do{freopen(s\".in\",\"r\",stdin);freopen(s\".out\",\"w\",stdout);}while(false)\nusing namespace std;\ntypedef long long ll;\nconst ll N = 1e5+5; \n \nll n, m, a[N], sz[N], son[N], fa[N], sum[N];\nvector<ll> e[N];\nset<tuple<ll, ll> > sons[N]; \ntemplate<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}\ntemplate<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}\nvoid dfs(ll u, ll f) {\n\tsz[u] = 1;\n\tsum[u] = a[u];\n\tfa[u] = f;\n\tfor(auto v : e[u]) {\n\t\tif(v == f) continue;\n\t\tdfs(v, u);\n\t\tsz[u] += sz[v];\n\t\tsum[u] += sum[v];\n\t\tsons[u].insert(make_tuple(-sz[v], v));\n\t\tif(sz[v] > sz[son[u]] || sz[v] == sz[son[u]] && v < son[u]) son[u] = v;\n\t}\n}\n \nint main() {\n\tscanf(\"%lld%lld\", &n, &m);\n\trep(i, 1, n) scanf(\"%lld\", &a[i]);\n\trep(i, 1, n-1) {\n\t\tll u, v;\n\t\tscanf(\"%lld%lld\", &u, &v);\n\t\te[u].push_back(v);\n\t\te[v].push_back(u);\n\t}\n\tdfs(1, 0);\n\twhile(m --> 0) {\n\t\tll op, u;\n\t\tscanf(\"%lld%lld\", &op, &u);\n\t\tif(op == 1) printf(\"%lld\\n\", sum[u]);\n\t\telse {\n\t\t\tll v = son[u];\n\t\t\tif(!v) continue;\n\t\t\tll p = fa[u];\n\t\t\tsz[u] -= sz[v];\n\t\t\tsum[u] -= sum[v];\n\t\t\tsons[u].erase(make_tuple(-sz[v], v));\n\t\t\tson[u] = sons[u].empty() ? 0 : get<1>(*sons[u].begin());\n\t\t\tfa[u] = v;\n\t\t\tsz[v] += sz[u];\n\t\t\tsum[v] += sum[u];\n\t\t\tsons[v].insert(make_tuple(-sz[u], u));\n\t\t\tson[v] = get<1>(*sons[v].begin());\n\t\t\tfa[v] = p;\n\t\t\tsons[p].erase(make_tuple(-sz[v], u));\n\t\t\tsons[p].insert(make_tuple(-sz[v], v));\n\t\t\tson[p] = get<1>(*sons[p].begin());\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "implementation",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1797",
    "index": "E",
    "title": "Li Hua and Array",
    "statement": "Li Hua wants to solve a problem about $\\varphi$ — Euler's totient function. Please recall that $\\varphi(x)=\\sum\\limits_{i=1}^x[\\gcd(i,x)=1]$.$^{\\dagger,\\ddagger}$\n\nHe has a sequence $a_1,a_2,\\cdots,a_n$ and he wants to perform $m$ operations:\n\n- \"1 $l$ $r$\" ($1\\le l\\le r\\le n$) — for \\textbf{each} $x\\in[l,r]$, change $a_x$ into $\\varphi(a_x)$.\n- \"2 $l$ $r$\" ($1\\le l\\le r\\le n$) — find out the minimum changes needed to make sure $a_l=a_{l+1}=\\cdots=a_r$. In each change, he chooses \\textbf{one} $x\\in[l,r]$, change $a_x$ into $\\varphi(a_x)$. Each operation of this type is independent, which means the array doesn't actually change.\n\nSuppose you were Li Hua, please solve this problem.\n\n$^\\dagger$ $\\gcd(x,y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\n$^\\ddagger$ The notation $[\\textrm{cond}]$ equals $1$ if the condition $\\textrm{cond}$ is true, and $0$ otherwise.",
    "tutorial": "Denote $w=\\max\\limits_{i=1}^n\\{a_i\\}$. Also denote $\\varphi^k(x)=\\begin{cases}x,&k=0\\\\\\varphi(\\varphi^{k-1}(x)),&k\\in\\mathbb{N}^*\\end{cases}$. It can be proven that after $O(\\log w)$ operations, any $a_i$ will become $1$ and more operations are useless. In other words, $\\varphi^{\\log_2 w+1}(a_i)=1$. Let's construct a tree of size $w$, where $1$ is the root and the father of $k$ is $\\varphi(k)$. The height of the tree is $O(\\log w)$. After some precalculating, we can find the LCA of two vertices within $O(\\log\\log w)$. We can use a dsu to maintain the next not-$1$ element of each $a_i$ and use a segment tree to maintain the LCA, minimal depth, and answer in the range. We can brute force the changes using the dsu and meanwhile do point update on the segment tree. The queries can be solved using a range query on the segment tree. With the potential method, we denote $\\Phi(a_i)$ as the minimum integer $k$ which satisfies $\\varphi^k(a_i)=1$. Since each successful operation on $a_i$ will decrease $\\Phi(a_i)$ by $1$, the maximum number of successful operations we can perform on $a_i$ is $\\Phi(a_i)$. Therefore, the maximum number of successful operations is $\\sum\\limits_{i=1}^n\\Phi(a_i)=O(n\\log w)$. For each successful operation, we visit $O(\\log n)$ nodes on the segment tree and merge the information of two subtrees for $O(\\log n)$ times. Because of the time complexity of calculating LCA, We need $O(\\log\\log w)$ time to merge the information. So all the operations will take up $O(n\\log n\\log w\\log\\log w)$ time. We need to initialize $\\varphi$ within $O(w)$ time and binary lifting the ancestors on the tree within $O(w\\log\\log w)$ time. We also need $O(\\log n\\log\\log w)$ for each query. In conclusion, the time complexity is $O(w\\log\\log w+n\\log n\\log w\\log\\log w+m\\log n\\log\\log w)$. The above algorithm is enough to pass this problem. However, it has a mass number of information merging operations, so it runs quite slowly. We use the segment tree not only to maintain the LCA, minimal depth, and answer of the ranges, but also whether $\\Phi(l_u;r_u)=\\sum\\limits_{i\\in[l_u,r_u]}\\Phi(a_i)=0$. If we enter a node whose $\\Phi(l_u;r_u)=0$, we can just ignore it. Otherwise, we recursively work on the segment tree until leaf and brute force update its information. Time complexity is the same but it's much more efficient. Bonus: Can you solve this problem within $O(m\\log n)$?",
    "code": "//By: Luogu@rui_er(122461)\n#include <bits/stdc++.h>\n#define rep(x,y,z) for(int x=y;x<=z;x++)\n#define per(x,y,z) for(int x=y;x>=z;x--)\n#define debug printf(\"Running %s on line %d...\\n\",__FUNCTION__,__LINE__)\n#define fileIO(s) do{freopen(s\".in\",\"r\",stdin);freopen(s\".out\",\"w\",stdout);}while(false)\nusing namespace std;\ntypedef long long ll;\nconst int N = 1e5 + 5, P = 4e5 + 5, K = 5e6 + 5, W = 5e6; \n \nint n, m, a[N], tab[K], phi[K], p[P], pcnt, dis[K], fa[K][6];\ntemplate<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}\ntemplate<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}\nvoid sieve(int lim) {\n\tphi[1] = 1;\n\trep(i, 2, lim) {\n\t\tif(!tab[i]) {\n\t\t\tp[++pcnt] = i;\n\t\t\tphi[i] = i - 1;\n\t\t}\n\t\tfor(int j=1;j<=pcnt&&1LL*i*p[j]<=lim;j++) {\n\t\t\ttab[i*p[j]] = 1;\n\t\t\tif(i % p[j]) phi[i*p[j]] = phi[i] * phi[p[j]];\n\t\t\telse {\n\t\t\t\tphi[i*p[j]] = phi[i] * p[j];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\nvoid initTree(int lim) {\n\tdis[1] = 1;\n\trep(j, 0, 5) fa[1][j] = 1;\n\trep(i, 2, lim) {\n\t\tdis[i] = dis[phi[i]] + 1;\n\t\tfa[i][0] = phi[i];\n\t\trep(j, 1, 5) fa[i][j] = fa[fa[i][j-1]][j-1];\n\t}\n}\nint LCA(int u, int v) {\n\tif(dis[u] < dis[v]) swap(u, v);\n\tper(i, 5, 0) if(dis[fa[u][i]] >= dis[v]) u = fa[u][i];\n\tif(u == v) return u;\n\tper(i, 5, 0) if(fa[u][i] != fa[v][i]) u = fa[u][i], v = fa[v][i];\n\treturn fa[u][0];\n}\nstruct Node {\n\tint lca, ans, mndis, allrt;\n};\nstruct SegTree {\n\tNode t[N<<2];\n\t#define lc(u) (u<<1)\n\t#define rc(u) (u<<1|1)\n\tvoid pushup(int u, int l, int r) {\n\t\tint mid = (l + r) >> 1;\n\t\tt[u].lca = LCA(t[lc(u)].lca, t[rc(u)].lca);\n\t\tt[u].ans = t[lc(u)].ans + t[rc(u)].ans\n\t\t\t\t + (mid - l + 1) * (dis[t[lc(u)].lca] - dis[t[u].lca])\n\t\t\t\t + (r - mid) * (dis[t[rc(u)].lca] - dis[t[u].lca]);\n\t\tt[u].mndis = min(t[lc(u)].mndis, t[rc(u)].mndis);\n\t\tt[u].allrt = t[lc(u)].allrt && t[rc(u)].allrt;\n\t}\n\tvoid build(int u, int l, int r) {\n\t\tif(l == r) {\n\t\t\tt[u].lca = a[l];\n\t\t\tt[u].ans = 0;\n\t\t\tt[u].mndis = dis[a[l]];\n\t\t\tt[u].allrt = a[l] == 1;\n\t\t\treturn;\n\t\t}\n\t\tint mid = (l + r) >> 1;\n\t\tbuild(lc(u), l, mid);\n\t\tbuild(rc(u), mid+1, r);\n\t\tpushup(u, l, r);\n\t}\n\tvoid modify(int u, int l, int r, int ql, int qr) {\n\t\tif(t[u].allrt) return;\n\t\tif(l == r) {\n\t\t\tt[u].lca = fa[t[u].lca][0];\n\t\t\t--t[u].mndis;\n\t\t\tt[u].allrt = t[u].lca == 1;\n\t\t\treturn;\n\t\t}\n\t\tint mid = (l + r) >> 1;\n\t\tif(ql <= mid) modify(lc(u), l, mid, ql, qr);\n\t\tif(qr > mid) modify(rc(u), mid+1, r, ql, qr);\n\t\tpushup(u, l, r);\n\t}\n\tint queryLCA(int u, int l, int r, int ql, int qr) {\n\t\tif(ql <= l && r <= qr) return t[u].lca;\n\t\tint mid = (l + r) >> 1;\n\t\tif(qr <= mid) return queryLCA(lc(u), l, mid, ql, qr);\n\t\tif(ql > mid) return queryLCA(rc(u), mid+1, r, ql, qr);\n\t\tint ans = queryLCA(lc(u), l, mid, ql, qr);\n\t\tif(ans == 1) return 1;\n\t\treturn LCA(ans, queryLCA(rc(u), mid+1, r, ql, qr));\n\t}\n\tint queryAns(int u, int l, int r, int ql, int qr, int lca) {\n\t\tif(ql <= l && r <= qr) {\n\t\t\treturn t[u].ans + (r - l + 1) * (dis[t[u].lca] - dis[lca]);\n\t\t}\n\t\tint mid = (l + r) >> 1, ans = 0;\n\t\tif(ql <= mid) ans += queryAns(lc(u), l, mid, ql, qr, lca);\n\t\tif(qr > mid) ans += queryAns(rc(u), mid+1, r, ql, qr, lca);\n\t\treturn ans;\n\t}\n\t#undef lc\n\t#undef rc\n}sgt;\n \nint main() {\n\tsieve(W);\n\tinitTree(W);\n\tscanf(\"%d%d\", &n, &m);\n\trep(i, 1, n) scanf(\"%d\", &a[i]);\n\tsgt.build(1, 1, n);\n\twhile(m --> 0) {\n\t\tint op, l, r;\n\t\tscanf(\"%d%d%d\", &op, &l, &r);\n\t\tif(op == 1) sgt.modify(1, 1, n, l, r);\n\t\telse {\n\t\t\tint lca = sgt.queryLCA(1, 1, n, l, r);\n\t\t\tprintf(\"%d\\n\", sgt.queryAns(1, 1, n, l, r, lca));\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dsu",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1797",
    "index": "F",
    "title": "Li Hua and Path",
    "statement": "Li Hua has a tree of $n$ vertices and $n-1$ edges. The vertices are numbered from $1$ to $n$.\n\nA pair of vertices $(u,v)$ ($u < v$) is considered cute if \\textbf{exactly one} of the following two statements is true:\n\n- $u$ is the vertex with the minimum index among all vertices on the path $(u,v)$.\n- $v$ is the vertex with the maximum index among all vertices on the path $(u,v)$.\n\nThere will be $m$ operations. In each operation, he decides an integer $k_j$, then inserts a vertex numbered $n+j$ to the tree, connecting with the vertex numbered $k_j$.\n\nHe wants to calculate the number of cute pairs before operations and after each operation.\n\nSuppose you were Li Hua, please solve this problem.",
    "tutorial": "There exists an acceptable $O(n\\log^2n+m)$ solution using centroid decomposition, but there is a better $O(n\\log n+m)$ solution using reconstruction trees. The initial tree is shown in the following picture: Consider the following reconstruction trees. We will define two reconstruction trees called min-RT and max-RT where \"RT\" means reconstruction tree. For the max-RT, we enumerate vertices in increasing order. We create a new vertex $u$ in the max-RT, then find each vertex $v$ such that $v < u$ and $v$ is adjacent to $u$ in the original tree, make $u$ become the father of the root of $v$ on the max-RT. We can use a dsu to build the max-RT. The max-RT is shown in the following picture: The property that $\\operatorname{LCA}(u, v)$ on the max-RT is the maximum index on the path between $(u,v)$ on the original tree is satisfied. The min-RT is similar to the max-RT. The min-RT is shown in the following picture: After designing the reconstruction trees, I found out that the reconstruction trees are related to Kruskal reconstruction trees (KRT) to a certain extent. Here is another way to understand the two reconstruction trees. For the max-RT, since we want to calculate the maximum index on the path, we define the weight of an edge $(u,v)$ as $\\max\\{u,v\\}$. We build a (minimum spanning) KRT of the original tree and merge the vertices with the same weight into one vertex. For the min-RT, define the weight of an edge $(u,v)$ as $\\min\\{u,v\\}$ and use the (maximum spanning) KRT. The max-RT and the (minimum spanning) KRT: (left: maximum valued graph; middle: KRT; right: max-RT) The min-RT and the (maximum spanning) KRT: (left: minimum valued graph; middle: KRT; right: min-RT) We will solve the problem using the two reconstruction trees. Let's call the two restrictions in the statement I and II. Denote $K$ as the number of pairs satisfying exactly one of I and II (which is the answer), $A$ as the number of pairs satisfying I, $B$ as the number of pairs satisfying II and $C$ as the number of pairs satisfying both I and II. It's obvious that $K=A+B-2C$. We can easily calculate $A$ and $B$ using the depth of each vertex on two reconstruction trees. Due to the property mentioned above, $C$ is the number of pairs $(u,v)$ satisfying the condition that $u$ is an ancestor of $v$ on min-RT and $v$ is an ancestor of $u$ on max-RT, which can be solved using dfs order and Fenwick tree. Finally, we calculated the original answer. If we add a vertex with the largest index as a leaf, paths ending with this vertex will satisfy II, so we can use min-RT to calculate the paths ending with this vertex not satisfying I and update the answer. Time complexity: $O(n\\log n+m)$.",
    "code": "//By: OIer rui_er\n#include <bits/stdc++.h>\n#define rep(x,y,z) for(ll x=(y);x<=(z);x++)\n#define per(x,y,z) for(ll x=(y);x>=(z);x--)\n#define debug(format...) fprintf(stderr, format)\n#define fileIO(s) do{freopen(s\".in\",\"r\",stdin);freopen(s\".out\",\"w\",stdout);}while(false)\nusing namespace std;\ntypedef long long ll;\nconst ll N = 4e5+5;\n \nll n, m, k, faMx[N], faMn[N], disMx[N], disMn[N], dfn[N], sz[N], tms;\nll A, B, C, ans;\nvector<ll> eMx[N], eMn[N], reMx[N], reMn[N];\ntemplate<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}\ntemplate<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}\nstruct Dsu {\n\tll fa[N];\n\tvoid init(ll x) {rep(i, 1, x) fa[i] = i;}\n\tll find(ll x) {return x == fa[x] ? x : fa[x] = find(fa[x]);}\n\tbool merge(ll x, ll y) {\n\t\tll u = find(x), v = find(y);\n\t\tif(u == v) return 0;\n\t\tfa[u] = v;\n\t\treturn 1;\n\t}\n}dsu;\nstruct BIT {\n\tll c[N], sz;\n\tvoid init(ll x) {sz = x; rep(i, 1, x) c[i] = 0;}\n\tll lowbit(ll x) {return x & (-x);}\n\tvoid add(ll x, ll k) {for(; x <= sz; x += lowbit(x)) c[x] += k;}\n\tll ask(ll x) {ll k = 0; for(; x; x -= lowbit(x)) k += c[x]; return k;}\n\tll Ask(ll x, ll y) {return ask(y) - ask(x - 1);}\n}bit;\nvoid dfs1(ll u) {\n\tdfn[u] = ++tms;\n\tsz[u] = 1;\n\tdisMx[u] = disMx[faMx[u]] + 1;\n\tB += disMx[u] - 1;\n\tfor(ll v : reMx[u]) {\n\t\tdfs1(v);\n\t\tsz[u] += sz[v];\n\t}\n}\nvoid dfs2(ll u) {\n\tdisMn[u] = disMn[faMn[u]] + 1;\n\tA += disMn[u] - 1;\n\tC += bit.Ask(dfn[u], dfn[u] + sz[u] - 1);\n\tbit.add(dfn[u], 1);\n\tfor(ll v : reMn[u]) dfs2(v);\n\tbit.add(dfn[u], -1);\n}\n \nint main() {\n\tscanf(\"%lld\", &n);\n\trep(i, 1, n-1) {\n\t\tll u, v;\n\t\tscanf(\"%lld%lld\", &u, &v);\n\t\tif(u < v) swap(u, v);\n\t\teMx[u].push_back(v);\n\t\teMn[v].push_back(u);\n\t}\n\tdsu.init(n);\n\trep(i, 1, n) {\n\t\tfor(ll j : eMx[i]) {\n\t\t\tj = dsu.find(j);\n\t\t\tdsu.merge(j, i);\n\t\t\tfaMx[j] = i;\n\t\t\treMx[i].push_back(j);\n\t\t}\n\t}\n\tdsu.init(n);\n\tper(i, n, 1) {\n\t\tfor(ll j : eMn[i]) {\n\t\t\tj = dsu.find(j);\n\t\t\tdsu.merge(j, i);\n\t\t\tfaMn[j] = i;\n\t\t\treMn[i].push_back(j);\n\t\t}\n\t}\n\tbit.init(n);\n\tdfs1(n);\n\tdfs2(1);\n\tans = A + B - 2 * C;\n\t// printf(\"%lld + %lld - 2 * %lld = %lld\\n\", A, B, C, ans);\n\tprintf(\"%lld\\n\", ans);\n\tfor(scanf(\"%lld\", &m); m; m--) {\n\t\tscanf(\"%lld\", &k);\n\t\tdisMn[++n] = disMn[k] + 1;\n\t\tans += n - disMn[n];\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1798",
    "index": "A",
    "title": "Showstopper",
    "statement": "You are given two arrays $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_n$.\n\nIn one operation, you can choose any integer $i$ from $1$ to $n$ and swap the numbers $a_i$ and $b_i$.\n\nDetermine whether, after using any (possibly zero) number of operations, the following two conditions can be satisfied simultaneously:\n\n- $a_n = \\max(a_1, a_2, \\ldots, a_n)$,\n- $b_n = \\max(b_1, b_2, \\ldots, b_n)$.\n\nHere $\\max(c_1, c_2, \\ldots, c_k)$ denotes the maximum number among $c_1, c_2, \\ldots, c_k$. For example, $\\max(3, 5, 4) = 5$, $\\max(1, 7, 7) = 7$, $\\max(6, 2) = 6$.",
    "tutorial": "The first solution: Fix the position of the numbers $a_n, b_n$. And for each other index $i$, let's check whether the conditions $a_i \\leq a_n$ and $b_i \\leq b_n$ are met. If not, swap $a_i$ and $b_i$ and check again. If the conditions are not met for some index in both variants - the answer is \"No\", otherwise \"Yes\". The second solution: Let $M$ be the maximum of all the numbers $a_1, a_2, \\ldots, a_n, b_1, b_2, \\ldots, b_n$. Then if $a_n < M$ and $b_n < M$ the answer is - \"No\", since in the one of the arrays where the number $M$ appears after the operations, the maximum will be $M$, which is greater than $a_n$ and $b_n$. Otherwise, either $a_n = M$ or $b_n = M$. If $a_n = M$, then swap $a_n$ and $b_n$, now $b_n = M$. So the condition $b_n = \\max(b_1, b_2, \\ldots, b_n)$ will always be met, regardless of the numbers $b_1, b_2, \\ldots, b_{n-1}$. Therefore, it would be best to put in $b_i$ the maximum of the numbers $a_i, b_i$ for each $i$. After that, it remains to check the condition for the array $a_1, a_2, \\ldots, a_n$, and if it is met, the answer is -\"Yes\", otherwise -\"No\"",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    b = list(map(int, input().split()))\n    for i in range(n):\n        if a[i] > b[i]:\n            a[i], b[i] = b[i], a[i]\n    if a[-1] == max(a) and b[-1] == max(b):\n        print(\"YES\")\n    else:\n        print(\"NO\")",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1798",
    "index": "B",
    "title": "Three Sevens",
    "statement": "Lottery \"Three Sevens\" was held for $m$ days. On day $i$, $n_i$ people with the numbers $a_{i, 1}, \\ldots, a_{i, n_i}$ participated in the lottery.\n\nIt is known that in each of the $m$ days, only one winner was selected from the lottery participants. The lottery winner on day $i$ was not allowed to participate in the lottery in the days from $i+1$ to $m$.\n\nUnfortunately, the information about the lottery winners has been lost. You need to find any possible list of lottery winners on days from $1$ to $m$ or determine that no solution exists.",
    "tutorial": "Let's calculate the array $last$, where $last_X$ is the last day of the lottery in which the person $X$ participated. Then the only day when $X$ could be a winner is the day $last_X$. Then on the day of $i$, only the person with $last_X = i$ can be the winner. It is also clear that if there are several such participants for the day $i$, you can choose any of them as the winner, since these participants cannot be winners on any other days. In total, we need to go through all the days, if for some day there are no participants with $last$ equal to this day, then the answer is $-1$. Otherwise, we choose any participant with $last_X = i$ as the winner on the day of $i$.",
    "code": "MAX = 50000\nlast = [0] * (MAX + 777)\nfor _ in range(int(input())):\n    m = int(input())\n    a_ = []\n    for day in range(m):\n        n = int(input())\n        a = list(map(int, input().split()))\n        for x in a:\n            last[x] = day\n        a_.append(a)\n    ans = [-1] * m\n    for day in range(m):\n        for x in a_[day]:\n            if last[x] == day:\n                ans[day] = x\n        if ans[day] == -1:\n            print(-1)\n            break\n    else:\n        print(*ans)",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1798",
    "index": "C",
    "title": "Candy Store",
    "statement": "The store sells $n$ types of candies with numbers from $1$ to $n$. One candy of type $i$ costs $b_i$ coins. In total, there are $a_i$ candies of type $i$ in the store.\n\nYou need to pack all available candies in packs, each pack should contain only one type of candies. Formally, for each type of candy $i$ you need to choose the integer $d_i$, denoting the number of type $i$ candies in one pack, so that $a_i$ is divided without remainder by $d_i$.\n\nThen the cost of one pack of candies of type $i$ will be equal to $b_i \\cdot d_i$. Let's denote this cost by $c_i$, that is, $c_i = b_i \\cdot d_i$.\n\nAfter packaging, packs will be placed on the shelf. Consider the cost of the packs placed on the shelf, in order $c_1, c_2, \\ldots, c_n$. Price tags will be used to describe costs of the packs. One price tag can describe the cost of all packs from $l$ to $r$ inclusive if $c_l = c_{l+1} = \\ldots = c_r$. Each of the packs from $1$ to $n$ must be described by at least one price tag. For example, if $c_1, \\ldots, c_n = [4, 4, 2, 4, 4]$, to describe all the packs, a $3$ price tags will be enough, the first price tag describes the packs $1, 2$, the second: $3$, the third: $4, 5$.\n\nYou are given the integers $a_1, b_1, a_2, b_2, \\ldots, a_n, b_n$. Your task is to choose integers $d_i$ so that $a_i$ is divisible by $d_i$ for all $i$, and the required number of price tags to describe the values of $c_1, c_2, \\ldots, c_n$ is the minimum possible.\n\nFor a better understanding of the statement, look at the illustration of the first test case of the first test:\n\nLet's repeat the meaning of the notation used in the problem:\n\n$a_i$ — the number of candies of type $i$ available in the store.\n\n$b_i$ — the cost of one candy of type $i$.\n\n$d_i$ — the number of candies of type $i$ in one pack.\n\n$c_i$ — the cost of one pack of candies of type $i$ is expressed by the formula $c_i = b_i \\cdot d_i$.",
    "tutorial": "To begin with, let's understand when 1 price tag will be enough. Let the total cost of all packs of candies be $cost$. Two conditions are imposed on $cost$: The first condition: $cost$ must be divided by each of the numbers $b_i$, because $cost = b_i \\cdot d_i$. This is equivalent to the fact that $cost$ is divided by $lcm(b_1, \\ldots, b_n)$, where $lcm$ denotes the least common multiple. The second condition: $a_i$ is divided by $d_i$. We want $cost$ to somehow appear in this condition. Therefore, multiply both parts by $b_i$, and we get that $a_i \\cdot b_i$ is divisible by $b_i \\cdot d_i = cost$. That is, $a_i \\cdot b_i$ is divided by $cost$. This is equivalent to $\\gcd(a_1 \\cdot b_1, \\ldots, a_n \\cdot b_n)$ is divided by $cost$. Thus, if one price tag is enough, it is necessary that $\\gcd(a_1 \\cdot b_1, \\ldots, a_n \\cdot b_n)$ was divided by $cost$ and $cost$ was divided by $lcm(b_1, \\ldots, b_n)$. So a necessary and sufficient condition for one price tag will be \"$\\gcd(a_1 \\cdot b_1, \\ldots, a_n \\cdot b_n)$ is divided by $lcm(b_1, \\ldots, b_n)$\". It is not difficult to understand that if one price tag is enough for a set of candies, then if you remove any type of candy from this set, one price tag will still be enough. This means that a simple greedy algorithm will work. Let's select the largest prefix of candies such that one price tag is enough for it, \"paste\" a price tag on this prefix, and repeat for the remaining candies until the array ends.",
    "code": "from math import gcd\n \ndef lcm(a, b):\n  return a * b // gcd(a, b)\n \nfor _ in range(int(input())):\n    n = int(input())\n    a = []\n    b = []\n    for i in range(n):\n       ai, bi = map(int, input().split())\n       a.append(ai)\n       b.append(bi)\n    g = 0\n    l = 1\n    ans = 1\n    for i in range(n):\n        g = gcd(g, a[i] * b[i])\n        l = lcm(l, b[i])\n        if g % l:\n            ans += 1\n            g = a[i] * b[i]\n            l = b[i]\n    print(ans)",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1798",
    "index": "D",
    "title": "Shocking Arrangement",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$ consisting of integers such that $a_1 + a_2 + \\ldots + a_n = 0$.\n\nYou have to rearrange the elements of the array $a$ so that the following condition is satisfied:\n\n$$\\max\\limits_{1 \\le l \\le r \\le n} \\lvert a_l + a_{l+1} + \\ldots + a_r \\rvert < \\max(a_1, a_2, \\ldots, a_n) - \\min(a_1, a_2, \\ldots, a_n),$$ where $|x|$ denotes the absolute value of $x$.\n\nMore formally, determine if there exists a permutation $p_1, p_2, \\ldots, p_n$ that for the array $a_{p_1}, a_{p_2}, \\ldots, a_{p_n}$, the condition above is satisfied, and find the corresponding array.\n\nRecall that the array $p_1, p_2, \\ldots, p_n$ is called a permutation if for each integer $x$ from $1$ to $n$ there is exactly one $i$ from $1$ to $n$ such that $p_i = x$.",
    "tutorial": "If the array consists entirely of zeros, then this is impossible, since $\\max(a) - \\min(a) = 0$. Otherwise, we will put all zeros at the beginning. Now our array is without zeros. We will add the elements into the array in order. If now the sum of the added elements is $\\leq 0$, we will take any of the remaining positive numbers as the next element. Since the sum of all the numbers is $0$, a positive number is guaranteed to be found (if there are still numbers left). If now the sum is $> 0$, then we will take any of the remaining negative numbers as the next element. Again, since the sum of all the numbers is $0$, a negative number is bound to be found. Why it works: The maximum number of the form $\\lvert a_l + a_{l+1} + ... + a_r \\rvert$ is the same as $maxPrefSum(a) - minPrefSum(a)$ (including $0$) According to the structure of the algorithm, it is clear that in the resulting array $maxPrefSum \\leq \\max(a)$, and $minPrefSum > \\min(a)$. In total, the condition will be met.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    if max(a) == 0:\n        print(\"No\")\n    else:\n        print(\"Yes\")\n        prefix_sum = 0\n        pos = []\n        neg = []\n        for x in a:\n            if x >= 0:\n                pos.append(x)\n            else:\n                neg.append(x)\n        ans = []\n        for _ in range(n):\n            if prefix_sum <= 0:\n                ans.append(pos[-1])\n                pos.pop()\n            else:\n                ans.append(neg[-1])\n                neg.pop()\n            prefix_sum += ans[-1]\n        print(' '.join(list(map(str, ans))))",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1798",
    "index": "E",
    "title": "Multitest Generator",
    "statement": "Let's call an array $b_1, b_2, \\ldots, b_m$ a test if $b_1 = m - 1$.\n\nLet's call an array $b_1, b_2, \\ldots, b_m$ a multitest if the array $b_2, b_3, \\ldots, b_m$ can be split into $b_1$ non-empty subarrays so that each of these subarrays is a test. Note that each element of the array must be included in exactly one subarray, and the subarrays must consist of consecutive elements.\n\nLet's define the function $f$ from the array $b_1, b_2, \\ldots, b_m$ as the minimum number of operations of the form \"Replace any $b_i$ with any \\textbf{non-negative} integer $x$\", which needs to be done so that the array $b_1, b_2, \\ldots, b_m$ becomes a multitest.\n\nYou are given an array of \\textbf{positive} integers $a_1, a_2, \\ldots, a_n$. For each $i$ from $1$ to $n - 1$, find $f([a_i, a_{i+1}, \\ldots, a_n])$.\n\nBelow are some examples of tests and multitests.\n\n- Tests: $[\\underline{1}, 5]$, $[\\underline{2}, 2, 2]$, $[\\underline{3}, 4, 1, 1]$, $[\\underline{5}, 0, 0, 0, 0, 0]$, $[\\underline{7}, 1, 2, 3, 4, 5, 6, 7]$, $[\\underline{0}]$. These arrays are tests since their first element (underlined) is equal to the length of the array minus one.\n- Multitests: $[1, \\underline{\\underline{1}, 1}]$, $[2, \\underline{\\underline{3}, 0, 0, 1}, \\underline{\\underline{1}, 12}]$, $[3, \\underline{\\underline{2}, 2, 7}, \\underline{\\underline{1}, 1}, \\underline{\\underline{3}, 4, 4, 4}]$, $[4, \\underline{\\underline{0}}, \\underline{\\underline{3}, 1, 7, 9}, \\underline{\\underline{4}, 2, 0, 0, 9}, \\underline{\\underline{1}, 777}]$. Underlined are the subarrays after the split, and double underlined are the first elements of each subarray.",
    "tutorial": "The first idea: you can make a multitest from any array using $2$ operations. To do this, replace the first element with $1$, and the second with $n - 2$, where $n$ is the length of the array. It remains to learn how to determine whether it is possible to make a multitest from an array for $0$ and for $1$ change. First let's deal with the $0$ changes. Question: when is the array $a_i, \\ldots, a_n$ a multitest? Answer: when $a_{i+1}, \\ldots, a_n$ represents exactly $a_i$ of tests written in a row. For convenience, let's call the index $i$ good if $a_i, \\ldots, a_n$ represents a certain number of tests written in a row. For all indexes, we want to find out if they are good, and if so, how many tests the corresponding suffix consists of. Denote $go_i = i + a_i + 1$. The logic is that if $i$ is the first element of a certain test, then $go_i$ is the first element of the next test. Then the index $i$ will be good if the chain $i \\to go_i \\to go_{go_i} \\to \\ldots$ ends in $n + 1$. To find out if this chain ends in $n + 1$ and if so, how many tests it consists of can be simple dynamic programming by suffixes. In total, to determine whether the suffix $a_i, \\ldots, a_n$ is a multitest in itself, it is necessary to check that $i+1$ is good and its suffix consists of exactly $a_i$ tests. Now it remains to determine whether it is possible to make a multitest for $1$ change. If the array has become a multitest after the change, then the element responsible for either the number of tests or the first element of some test has been changed. Case one: the number of tests changes. Then the array can be made a multitest if and only if $i + 1$ is a good index. Case two: the index after the change will become the first element of some test. We will consider \"the maximum number of tests that can be achieved by changing one element\" as the dynamics of the suffix. Then one change can make the suffix a multitest if the dynamics value from $i+1$ is greater than or equal to $a_i$. How to calculate this dynamics for $i+1$: The index being changed then must be one of $i+1$, $go_{i+1}$, $go_{go_{i+1}}$, $\\ldots$, otherwise the test chain of $i+1$ will remain the same and the change will not affect anything. Then if $go_{i+1}, go_{go_{i+1}}, \\ldots$ changes, then this change will be reflected in the dynamics value from $go_{i+1}$, through which it can be recalculated. And if $i+1$ changes, then you need to make a change so that $go_{i+1}$ is a good index (after the change). $go_{i+1}$ can become any index of $\\geq i+2$ after the change. And of all these, you need to choose a good index with the maximum number of tests. This value can be maintained separately when recalculating the dynamics.",
    "code": "N = 300777\na = [0] * N\ngo = [0] * N\ngood_chain = [0] * N\nchain_depth = [0] * N\nsuf_max_chain_depth = [0] * N\n\nans = \"\"\nfor _ in range(int(input())):\n    n = int(input())\n    a = [0] + list(map(int, input().split()))\n    chain_depth[n + 1] = 0\n    suf_max_chain_depth[n + 1] = 0\n    curr_max_chain_depth = 0\n    for i in range(n, 0, -1):\n        go[i] = i + a[i] + 1\n        if go[i] == n + 1 or (go[i] <= n and good_chain[go[i]]):\n            good_chain[i] = True\n        else:\n            good_chain[i] = False\n        chain_depth[i] = 1 + chain_depth[min(go[i], n + 1)]\n        suf_max_chain_depth[i] = 1 + curr_max_chain_depth\n        if go[i] <= n + 1:\n            suf_max_chain_depth[i] = max(suf_max_chain_depth[i], 1 + suf_max_chain_depth[go[i]])\n        if good_chain[i]:\n            curr_max_chain_depth = max(curr_max_chain_depth, chain_depth[i])\n    for i in range(1, n):\n        if good_chain[i + 1] and chain_depth[i + 1] == a[i]:\n            ans += \"0 \"\n        elif good_chain[i + 1] or suf_max_chain_depth[i + 1] >= a[i]:\n            ans += \"1 \"\n        else:\n            ans += \"2 \"\n    ans += '\\n'\nprint(ans)",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1798",
    "index": "F",
    "title": "Gifts from Grandfather Ahmed",
    "statement": "Grandfather Ahmed's School has $n+1$ students. The students are divided into $k$ classes, and $s_i$ students study in the $i$-th class. So, $s_1 + s_2 + \\ldots + s_k = n+1$.\n\nDue to the upcoming April Fools' Day, all students will receive gifts!\n\nGrandfather Ahmed planned to order $n+1$ boxes of gifts. Each box can contain one or more gifts. He plans to distribute the boxes between classes so that the following conditions are satisfied:\n\n- Class number $i$ receives \\textbf{exactly} $s_i$ boxes (so that each student can open exactly one box).\n- The total number of gifts in the boxes received by the $i$-th class should be a multiple of $s_i$ (it should be possible to equally distribute the gifts among the $s_i$ students of this class).\n\nUnfortunately, Grandfather Ahmed ordered only $n$ boxes with gifts, the $i$-th of which contains $a_i$ gifts.\n\nAhmed has to buy the missing gift box, and the number of gifts in the box should be an integer between $1$ and $10^6$. Help Ahmed to determine, how many gifts should the missing box contain, and build a suitable distribution of boxes to classes, or report that this is impossible.",
    "tutorial": "Incredible mathematical fact: from any $2n - 1$ integers, you can choose $n$ with a sum divisible by $n$ (Erdős-Ginzburg-Ziv theorem) The proof can be found in the world wide Web. Brief idea: first prove for primes, and then prove that if true for $n = a$ and $n = b$, then true for $n = ab$. Sort the class sizes: $s_1 \\leq s_2 \\leq\\ldots \\leq s_k$. Let's distribute the available boxes into the first $k - 1$ classes in order. Then considering the $i$ class, we have $s_i + \\ldots + s_k - 1$ boxes at our disposal. $s_k\\geq s_i$, which means there are at least $2\\cdot s_i - 1$ boxes from which you can always allocate $s_i$ to send to the $i$ class. And for the last class, we can add a box with the necessary number of gifts ourselves to ensure divisibility. The question remains how to allocate $s_i$ numbers with a sum divisible by $s_i$ among $2 \\cdot s_i - 1$ numbers. Restrictions allow you to do this in a straight dynamics for $n^3$. $dp[i][j][k]$ - is it possible to choose $j$ among the first $i$ numbers so that their sum gives the remainder of $k$ by the required modulus. Restore of the answer is done by the classical method.",
    "code": "#include <bits/stdc++.h>\n \n#define pb push_back\n// #define int long long\n#define all(x) x.begin(), x.end()\n#define ld long double\nusing namespace std;\nconst int N = 210;\nbool dp[N][N][N];\nbool take[N][N][N];\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n), s(k);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    for (int i = 0; i < k; i++) {\n        cin >> s[i];\n    }\n    vector<pair<int, int>> s2;\n    for (int i = 0; i < k; i++) {\n        s2.pb({s[i], i});\n    }\n    sort(all(s2));\n    vector<vector<int>> ans(k);\n    for (int i = 0; i < k - 1; i++) {\n        int class_size = s2[i].first;\n        vector<int> boxes;\n        for (int _ = 0; _ < 2 * class_size - 1; _++) {\n            boxes.pb(a.back());\n            a.pop_back();\n        }\n        for (int sz = 0; sz <= class_size; sz++) {\n            for (int r = 0; r < class_size; r++) {\n                dp[0][sz][r] = false;\n                take[0][sz][r] = false;\n            }\n        }\n        dp[0][0][0] = true;\n        dp[0][1][boxes[0] % class_size] = true;\n        take[0][1][boxes[0] % class_size] = true;\n        for (int j = 1; j < (int) boxes.size(); j++) {\n            for (int sz = 0; sz <= class_size; sz++) {\n                for (int r = 0; r < class_size; r++) {\n                    dp[j][sz][r] = dp[j - 1][sz][r];\n                    if (sz > 0 && dp[j - 1][sz - 1][(class_size + r - boxes[j] % class_size) % class_size]) {\n                        dp[j][sz][r] = true;\n                        take[j][sz][r] = true;\n                    } else {\n                        take[j][sz][r] = false;\n                    }\n                }\n            }\n        }\n        vector<bool> used(2 * class_size - 1);\n        int sz = class_size, r = 0;\n        for (int j = (int) boxes.size() - 1; j >= 0; j--) {\n            if (take[j][sz][r]) {\n                used[j] = true;\n                sz--;\n                r += (class_size - boxes[j] % class_size);\n                r %= class_size;\n            } else {\n                used[j] = false;\n            }\n        }\n        vector<int> to_class;\n        for (int j = 0; j < (int) boxes.size(); j++) {\n            if (!used[j]) {\n                a.pb(boxes[j]);\n            } else {\n                to_class.pb(boxes[j]);\n            }\n        }\n        ans[s2[i].second] = to_class;\n    }\n \n    int sum = 0;\n    for (auto x : a) {\n        sum += x;\n        sum %= (int) (a.size() + 1);\n    }\n    int add = (int) (a.size() + 1) - sum;\n    ans[s2[k - 1].second] = a;\n    ans[s2[k - 1].second].pb(add);\n \n    cout << add << '\\n';\n    for (auto arr : ans) {\n        for (auto x : arr) {\n            cout << x << ' ';\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1799",
    "index": "A",
    "title": "Recent Actions",
    "statement": "On Codeforces the \"Recent Actions\" field shows the last $n$ posts with recent actions.\n\nInitially, there are posts $1, 2, \\ldots, n$ in the field (this is in order from top to down). Also there are infinitely many posts not in the field, numbered with integers $n + 1, n + 2, \\ldots$.\n\nWhen recent action happens in the post $p$:\n\n- If it is in the \"Recent Actions\" field, it moves from its position to the top position.\n- Otherwise, it is added to the top position, and the post on the down position is removed from the \"Recent Actions\" field.\n\nYou know, that the next $m$ recent actions will happen in the posts $p_1, p_2, \\ldots, p_m$ ($n + 1 \\leq p_i \\leq n + m$) in the moments of time $1, 2, \\ldots, m$. \\textbf{Note}, that recent actions only happen with posts with numbers $\\geq n + 1$.\n\nFor each post $i$ ($1 \\leq i \\leq n$), find the first time it will be removed from the \"Recent Actions\" field or say, that it won't be removed.",
    "tutorial": "Note, that posts will be removed in the order $n, n - 1, \\ldots, 1$. The post $n - k + 1$ will be removed at the first time, when there are at least $k$ different numbers among $p_1, p_2, \\ldots, p_i$. So let's calculate the number of different numbers among $p_1, p_2, \\ldots, p_i$ for each $i$ using boolean array of length $m$ iterating $i$ from $1$ to $m$. Using them we can calculate the answer. Time complexity: $O(n + m)$.",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1799",
    "index": "B",
    "title": "Equalize by Divide",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$ of positive integers.\n\nYou can make this operation multiple (possibly zero) times:\n\n- Choose two indices $i$, $j$ ($1 \\leq i, j \\leq n$, $i \\neq j$).\n- Assign $a_i := \\lceil \\frac{a_i}{a_j} \\rceil$. Here $\\lceil x \\rceil$ denotes $x$ rounded up to the smallest integer $\\geq x$.\n\nIs it possible to make all array elements equal by some sequence of operations (possibly empty)? If yes, print \\textbf{any} way to do it in at most $30n$ operations.\n\nIt can be proven, that under the problem constraints, if some way exists to make all elements equal, there exists a way with at most $30n$ operations.",
    "tutorial": "If all numbers are equal initially - we can do nothing. Otherwise if some $a_i = 1$, answer do not exist: this $a_i$ can't became bigger during operations and all other elements can't be equal to $1$ simultaniously, because after the last operation $a_j > 1$ (otherwise we can remove this operation). If all $a_i \\geq 2$, the answer exists and we can simulate such algorithm: let's take $i$, such that $a_i$ is maximum possible and $j$, such that $a_j$ is smallest possible. Make operation with $(i, j)$. Note, that after at most $30n$ operations all elements will be equal. It is true, because after each operation $a_i$ decreases at least by $2$ times (and rounded up) and all elements are bounded $a_x \\geq 2$ after each operation. Each number can't be decreased more than $30$ times. Time complexity: $O(n^2 \\log{C})$, where $C = 10^9$.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1799",
    "index": "C",
    "title": "Double Lexicographically Minimum",
    "statement": "You are given a string $s$. You can reorder the characters to form a string $t$. Define $t_{\\mathrm{max}}$ to be the lexicographical maximum of $t$ and $t$ in reverse order.\n\nGiven $s$ determine the lexicographically minimum value of $t_{\\mathrm{max}}$ over all reorderings $t$ of $s$.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Let's iterate all symbols of $s$ in order from smallest to largest and construct an answer $t_{max}$. Let the current symbol be $x$. If there are at least $2$ remaining symbols equal to $x$, we should add them to the current prefix and suffix of $t_{max}$ and continue. If there are at most one other symbol $y$ is left (there are $x$ and $c$ times $y$ left in $s$) we should add $\\lceil \\frac{c}{2} \\rceil$ symbols $y$, symbol $x$ and $\\lfloor \\frac{c}{2} \\rfloor$ symbols $y$ to the prefix of $t_{max}$ and break. Otherwise we should add all remaining symbols of $s$ (excluding $x$) to prefix of $t_{max}$ in the sorted order and after it symbol $x$. Time complexity: $O(n + A)$, where $A = 26$.",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1799",
    "index": "D2",
    "title": "Hot Start Up (hard version)",
    "statement": "This is a hard version of the problem. The constraints of $t$, $n$, $k$ are the only difference between versions.\n\nYou have a device with two CPUs. You also have $k$ programs, numbered $1$ through $k$, that you can run on the CPUs.\n\nThe $i$-th program ($1 \\le i \\le k$) takes $cold_i$ seconds to run on some CPU. However, if the last program we ran on this CPU was also program $i$, it only takes $hot_i$ seconds ($hot_i \\le cold_i$). Note that this only applies if we run program $i$ multiple times consecutively  — if we run program $i$, then some different program, then program $i$ again, it will take $cold_i$ seconds the second time.\n\nYou are given a sequence $a_1, a_2, \\ldots, a_n$ of length $n$, consisting of integers from $1$ to $k$. You need to use your device to run programs $a_1, a_2, \\ldots, a_n$ in sequence. For all $2 \\le i \\le n$, you cannot start running program $a_i$ until program $a_{i - 1}$ has completed.\n\nFind the minimum amount of time needed to run all programs $a_1, a_2, \\ldots, a_n$ in sequence.",
    "tutorial": "Consider maintaining the following 2-dimensional DP: $dp_{i,j}$ will be the minimum time needed to run all previous programs such that the last program run on CPU 1 was program $i$, and the last program run on CPU 2 was program $j$. Initially we have $dp_{0,0} = 0$ (here, $0$ is a placeholder program) and $dp_{i,j} = INF$ for $(i, j) \\neq (0, 0)$. When we come to a program $x$, we can transition as follows. First, create a new DP array $ndp$, initialized to all $INF$. Then: For all $dp_{i,j}$ with $i \\neq x$, set $ndp_{x,j} = \\min(ndp_{x,j}, dp_{i,j} + cold_x)$. For all $dp_{x,j}$, set $ndp_{x,j} = \\min(ndp_{x,j}, dp_{x,j} + hot_x)$. For all $dp_{i,j}$ with $j \\neq x$, set $ndp_{i,x} = \\min(ndp_{i,x}, dp_{i,j} + cold_x)$. For all $dp_{i,x}$, set $ndp_{i,x} = \\min(ndp_{i,x}, dp_{i,x} + hot_x)$. After all updates, replace $dp$ with $ndp$. This works in $O(nk^2)$. To optimize it, we can notice that after processing a program $x$, only entries in $dp$ with the row or column equal to $x$ will be non-$INF$. Consider instead the following 1-dimensional DP array: $dp_i$ contains the minimum time to run previous programs if one CPU last ran program $x$, and the other last ran program $i$. Initially, $dp_0 = 0$ and all other $dp_i = INF$. Also, we add a dummy program with ID $0$, and $hot_0 = cold_0 = 0$ (this will make implementation easier). When we come to a program $x$, again, let's create a new DP array $ndp$, again initialized to all $INF$. Then, we can case on whether the previous program was equal to $x$. If the last program run was also $x$: For all $i$, set $ndp_i = \\min(ndp_i, dp_i + hot_x)$. For all $i \\neq x$, set $ndp_x = \\min(ndp_x, dp_i + cold_x)$. Set $ndp_x = \\min(ndp_x, dp_x + hot_x)$. For all $i$, set $ndp_i = \\min(ndp_i, dp_i + hot_x)$. For all $i \\neq x$, set $ndp_x = \\min(ndp_x, dp_i + cold_x)$. Set $ndp_x = \\min(ndp_x, dp_x + hot_x)$. Otherwise, let $y$ be the last program run. For all $i$, set $ndp_i = \\min(ndp_i, dp_i + cold_x)$. For all $i \\neq x$, set $ndp_y = \\min(ndp_y, dp_i + cold_x)$. Set $ndp_y = \\min(ndp_y, dp_x + hot_x)$. For all $i$, set $ndp_i = \\min(ndp_i, dp_i + cold_x)$. For all $i \\neq x$, set $ndp_y = \\min(ndp_y, dp_i + cold_x)$. Set $ndp_y = \\min(ndp_y, dp_x + hot_x)$. This gets us a $O(nk)$ solution which gets accepted in the easy version. To optimize it further, we can use a data structure to perform updates (since with each transition we either add some value to every $dp$ element, or add some value to a single index). It is possible to do this in constant time per update, or using a segment tree or some other range update structure (though this is somewhat overkill). The overall complexity then becomes $O(n + k)$ or $O(n \\log k + k)$ per test.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1799",
    "index": "E",
    "title": "City Union",
    "statement": "You are given $n \\times m$ grid. Some cells are filled and some are empty.\n\nA city is a maximal (by inclusion) set of filled cells such that it is possible to get from any cell in the set to any other cell in the set by moving to adjacent (by side) cells, without moving into any cells not in the set. In other words, a city is a connected component of filled cells with edges between adjacent (by side) cells.\n\nInitially, there are \\textbf{two cities} on the grid. You want to change some empty cells into filled cells so that both of the following are satisfied:\n\n- There is \\textbf{one city} on the resulting grid.\n- The shortest path between any two filled cells, achievable only by moving onto filled cells, is equal to the Manhattan distance between them.\n\nThe Manhattan distance between two cells $(a, b)$ and $(c, d)$ is equal to $|a - c| + |b - d|$.\n\nFind a way to add filled cells that satisfies these conditions and minimizes the total number of filled cells.",
    "tutorial": "Let's note, that the resulting grid is correct if and only if filled cells form continious segment in each row and column (condition *) and there is one city. So we can define a filling operation: given a grid, fill all cells between the most left and most right cells in each row and the most up and most down cells in each column. Doing this operation $(n+m)$ times we get that condition * is satisfied and we filled cells that definitely should be filled. If now there is one city, we solved the problem. But if there are still two cities, their projections to horisontal and vertical axes do not intersect. So we need to connect them with some path. Let's consider the case when one city is upper left than the other city (otherwise we can apply rotation and get this case). Let's define the lowest row of the first city as $i_1$, the right column of the first city as $j_1$, the upper row of the second city as $i_2$ and the left column of the second city as $j_2$. We can fill cells on any Manhattan shortest path between cells $(i_1, j_1)$, $(i_2, j_2)$. After that again using filling operation we will fill cells that should be filled. It is easy to see, that by this solution we will get the smallest possible number of filled cells. Time complexity: $O(nm (n + m))$.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "geometry",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1799",
    "index": "F",
    "title": "Halve or Subtract",
    "statement": "You have an array of positive integers $a_1, a_2, \\ldots, a_n$, of length $n$. You are also given a positive integer $b$.\n\nYou are allowed to perform the following operations (possibly several) times in any order:\n\n- Choose some $1 \\le i \\le n$, and replace $a_i$ with $\\lceil \\frac{a_i}{2} \\rceil$. Here, $\\lceil x \\rceil$ denotes the smallest integer not less than $x$.\n- Choose some $1 \\le i \\le n$, and replace $a_i$ with $\\max(a_i - b, 0)$.\n\nHowever, you must also follow these rules:\n\n- You can perform at most $k_1$ operations of type 1 in total.\n- You can perform at most $k_2$ operations of type 2 in total.\n- For all $1 \\le i \\le n$, you can perform at most $1$ operation of type 1 on element $a_i$.\n- For all $1 \\le i \\le n$, you can perform at most $1$ operation of type 2 on element $a_i$.\n\nThe cost of an array is the sum of its elements. Find the minimum cost of $a$ you can achieve by performing these operations.",
    "tutorial": "For convenience, let $half(x)$ denote $\\lceil \\frac{x}{2} \\rceil$, and $sub(x)$ denote $\\max(x - b, 0)$. First, notice that if we apply both operations to some element, it will be optimal to apply halving first, then subtraction. We can prove this with 2 cases: $a_i \\le 2b$. In this case, $half(a_i) \\le b$, and so $sub(half(a_i)) = 0$. Since applying either function to a nonnegative integer results in a nonnegative integer, $0 = sub(half(a_i)) \\le half(sub(a_i))$. Otherwise, $a_i > 2b$. Then $sub(half(a_i)) = a_i - \\lfloor \\frac{a_i}{2} \\rfloor - b$, and $half(sub(a_i)) = a_i - b - \\lfloor \\frac{a_i - b}{2} \\rfloor$. Since $\\lfloor \\frac{a_i - b}{2} \\rfloor \\le \\lfloor \\frac{a_i}{2} \\rfloor$, $sub(half(a_i)) \\le half(sub(a_i))$. Next, suppose there are exactly $p$ elements to which we apply both operations. Then, it will be optimal to apply both operations to the $p$ greatest elements in the array. This should be somewhat intuitive, but here's a proof: Suppose there are some $a_i, a_j$ such that $a_i < a_j$. Suppose we apply both operations to $a_i$, and only one operation to $a_j$. Then applying both operations to $a_j$ and a single operation to $a_i$ instead won't increase the resulting sum. We can prove this with two cases: We apply $half$ to $a_j$. Note that since it's optimal to apply $half$ first when applying both operations, this case is essentially: halve both elements, then choose one to apply $sub$ to. And it's better to subtract $b$ from the greater element, since $x - sub(x) \\le y - sub(y)$ for $x \\le y$. We apply $sub$ to $a_j$. We can analyze this with (surprise!) a few cases: $a_i, a_j \\le 2b$. Then whichever element we apply both operations to will be $0$, and the result will depend only on the other element. $sub(x) \\le sub(y)$ for $x \\le y$, so it's better to apply both operations to the greater element. $a_j > 2b$. If we apply both operations to the greater element, we subtract $\\min(a_i, b) + \\lfloor \\frac{a_j}{2} \\rfloor + b$ from the sum. But applying both operations to the lesser element subtracts $\\lfloor \\frac{a_i}{2} \\rfloor + \\min(half(a_i), b) + b \\le \\min(a_i, b) + \\lfloor \\frac{a_i}{2} \\rfloor + b$ from the sum. So it's optimal to apply both operations to the greater element. And this covers all cases where $a_i < a_j$. We apply $half$ to $a_j$. Note that since it's optimal to apply $half$ first when applying both operations, this case is essentially: halve both elements, then choose one to apply $sub$ to. And it's better to subtract $b$ from the greater element, since $x - sub(x) \\le y - sub(y)$ for $x \\le y$. We apply $sub$ to $a_j$. We can analyze this with (surprise!) a few cases: $a_i, a_j \\le 2b$. Then whichever element we apply both operations to will be $0$, and the result will depend only on the other element. $sub(x) \\le sub(y)$ for $x \\le y$, so it's better to apply both operations to the greater element. $a_j > 2b$. If we apply both operations to the greater element, we subtract $\\min(a_i, b) + \\lfloor \\frac{a_j}{2} \\rfloor + b$ from the sum. But applying both operations to the lesser element subtracts $\\lfloor \\frac{a_i}{2} \\rfloor + \\min(half(a_i), b) + b \\le \\min(a_i, b) + \\lfloor \\frac{a_i}{2} \\rfloor + b$ from the sum. So it's optimal to apply both operations to the greater element. And this covers all cases where $a_i < a_j$. $a_i, a_j \\le 2b$. Then whichever element we apply both operations to will be $0$, and the result will depend only on the other element. $sub(x) \\le sub(y)$ for $x \\le y$, so it's better to apply both operations to the greater element. $a_j > 2b$. If we apply both operations to the greater element, we subtract $\\min(a_i, b) + \\lfloor \\frac{a_j}{2} \\rfloor + b$ from the sum. But applying both operations to the lesser element subtracts $\\lfloor \\frac{a_i}{2} \\rfloor + \\min(half(a_i), b) + b \\le \\min(a_i, b) + \\lfloor \\frac{a_i}{2} \\rfloor + b$ from the sum. So it's optimal to apply both operations to the greater element. Let's fix $p$, the number of elements we apply both operations to. After taking them out, we will be left with the $n-x$ smallest elements in the array. Suppose we have $v_1$ operations of type 1 left, and $v_2$ operations of type 2 left. We'll assume $v_1 + v_2 \\le n - x$ (otherwise we can apply both operations to more elements). Notice that it's optimal to apply our $v_1 + v_2$ operations to the $v_1 + v_2$ greatest remaining elements: subtracting from a greater element can't decrease the amount we subtract, and halving a greater element can't decrease the amount we take away. So we're left with $v_1 + v_2$ elements, and we want to choose $v_1$ of them to apply the halving to. Let's consider a few cases and try to analyze them. Let $a_i \\le a_j$, and suppose we want to apply $half$ to one of them and $sub$ to the other. $a_i, a_j \\le b$. Then it will be optimal to apply $sub$ to the greater element. $b \\le a_i, a_j$. Then it will be optimal to apply $sub$ to the smaller element. Using this information, we can form the final lemma we need for our solution: Let $a_i \\le a_j \\le a_k$. Suppose we apply $sub$ to $a_i$ and $a_k$, and $half$ to $a_j$. Then it will not increase the answer to apply $half$ to one of $a_i$ or $a_k$ instead. There are 4 cases we should consider to prove this lemma: $a_k \\le b$. Then we should apply $half$ to $a_i$ and $sub$ to the others. $b \\le a_i$. Then we should apply $half$ to $a_k$ and $sub$ to the others. $a_i, a_j \\le b \\le a_k$. Then we should apply $half$ to $a_i$ and $sub$ to the others. $a_i \\le b \\le a_j, a_k$. Then we should apply $half$ to $a_k$ and $sub$ to the others. You can verify that doing this produces the optimal answer. And using this lemma, we find that the optimal answer has all $sub$ operations applied to some of the middle elements, with all $half$ operations applied to the endpoints. To summarize, the optimal answer will have a form like this (assuming $a$ is sorted in non-increasing order, $a_1 \\ge a_2 \\ge a_3 \\ge \\ldots \\ge a_n$): First come some elements to which we apply both operations. Second come some elements to which we apply only $half$. Third come some elements to which we apply only $sub$. Fourth come some elements to which we apply only $half$. Finally come some elements to which we apply no operations. Note that some of these segments may be empty. It's easy to verify that it's optimal to use all given operations. So if we loop through all possible sizes for the first two segments, we can uniquely determine the sizes of the last three. Finally, using prefix sums to quickly find the sums of elements in a segment, we get an $O(n^2)$ solution. There is an interesting fact: if we will fix the size of the first group $p$ and calculate the answer $f(p)$ for it, the function $f$ is convex. So the ternary or binary search can be used here to find the minimum in $O(n \\log{n})$ time, but it was not necessary.",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1799",
    "index": "G",
    "title": "Count Voting",
    "statement": "There are $n$ people that will participate in voting. Each person has exactly one vote.\n\n$i$-th person has a team $t_i$ ($1 \\leq t_i \\leq n$) where $t_i = t_j$ means $i$, $j$ are in the same team. By the rules each person should vote for the person from the different team. Note that it automatically means that each person can't vote for himself.\n\nEach person knows the number of votes $c_i$ he wants to get. How many possible votings exists, such that each person will get the desired number of votes? Due to this number can be big, find it by modulo $998\\,244\\,353$.",
    "tutorial": "Let's solve the problem using inclusion-conclusion principle. If we do not consider teams, there are $\\frac{n!}{\\prod\\limits_{i=1}^{n} c_i!}$ ways to make votings. But now consider such sets of bad votings: person $i$ made a vote for the person from the same team $t_i$. We want to calculate the size of the union of such sets of votings. So the answer to the problem is $\\sum\\limits_{k=0}^{n} (-1)^k f_k$, where $f_k$ is the number of ways to make votings, where we firstly fix some subset of $k$ people who will vote for the same team (for others the vote can be any) and calculate the number of votings for it, and we sum these numbers for all subsets of $k$ people. Let's define $b_1, b_2, \\ldots, b_n$, where $0 \\leq b_i \\leq c_i$ is the number of people from the same team who made a vote for $i$-th person (so, $\\sum\\limits_{i=1}^{n} b_i = k$). So, $f_k = \\sum\\limits_{0 \\leq b_i \\leq c_i} cnt(b_1, b_2, \\ldots, b_n)$, where $cnt(b_1, b_2, \\ldots, b_n)$ is the number of votings, where for each $i$ we firstly fix $b_i$ people from team $t_i$ that will vote for $i$ and calculate the number of votings, and we sum these numbers for all ways to fix. How $cnt$ is calculated? There are $\\frac{(\\sum\\limits_{i=1}^{n} c_i - b_i)!}{\\prod\\limits_{i=1}^{n} (c_i - b_i)!} = \\frac{(n - k)!}{\\prod\\limits_{i=1}^{n} (c_i - b_i)!}$ ways to make votes for people who were not selected into subset. This should be multiplied for the number of ways to vote for people that were fixed. This should be found for each team separately. Let's consider some team $1, 2, \\ldots, m$ of $m$ people (WLOG they are first $m$ people). There are $\\frac{m!}{(\\prod\\limits_{i=1}^{m} b_i!) (m - \\sum\\limits_{i=1}^{m} b_i)!}$ ways (*) to fix people in this team. These counts should be multiplied for all teams. Now to sum all $cnt$ for all $b$ we of course can't iterate over all possible $b$, we will do it using dynamic programming. Let's iterate over all possible teams and calculate $dp_{i,k}$ - the sum of current counts for all prefixes of arrays $b$, where we considered first $i$ teams and the sum of elements of $b$ on this prefix is $k$. When we add a new team to our $dp$, we can write $dp_{i+1, k+s} += dp_{i,k} t_{i+1,s}$, where $t_{i+1,s}$ is the sum of (*) multiplied by $\\frac{1}{\\prod\\limits_{i=1}^{m} (c_i - b_i)!}$ for all ways to choose $b$ inside the team $i+1$ with sum of $b_j$ in this team equal to $s$. To calculate values $t_{i,s}$ for each team $i$ we can also use a prefix dynamic programming inside the team. At the end we found $f_k = dp_{t,k} (n-k)!$, where $t$ is the number of teams. So, the time complexity of this solution is $O(n^2)$. Where are many different ways of how the solution can be implemented (and even optimized with power series), but the inclusion-conclusion is necessary to solve the problem.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1799",
    "index": "H",
    "title": "Tree Cutting",
    "statement": "You are given a tree with $n$ vertices.\n\nA hero $k$ times do the following operation:\n\n- Choose some edge.\n- Remove it.\n- Take one of the two remaining parts and delete it.\n- Write the number of vertices in the remaining part.\n\nYou are given an initial tree and the a sequence of written numbers. Find the number of ways to make operations such that the written numbers are equal to the given numbers. Due to the answer can be big, find it by modulo $998\\,244\\,353$. Two ways are considered different, if on some operation edge or remaining part are selected differently.",
    "tutorial": "We should calculate the number of ways to choose some $k$ edges of our tree (and directions of them) corresponding to operations, such that the operations that will be done with them will result in the given sequence of written numbers. To calculate these ways let's consider a subtree $dp_{v,mask}$ for our main tree. Here $v$ corresponds to subtree of our tree with root in vertex $v$, also we include an edge from $v$ to the parent into this subtree. $mask$ is a submask of $\\{1, 2, \\ldots, k\\}$, meaning that we have chosen in this subtree edges corresponding to operations from $mask$. First of all, consider the case, when the edge from $v$ to parent is not chosen to any of the operations. So let's iterate over children of $v$ and calculate the same dynamic programming for the considered prefix of subtrees. To add the new subtree, we should iterate over $mask_1$ mask of operations that have been done on prefix and $mask_2$ mask of operations that have been done in new subtree. For these masks the condition $mask_1 \\cap mask_2 = \\emptyset$ should hold. In the case, when the edge from $v$ to parent is chosen let's iterate of the operation $i$ corresponding to it. After that, $sz_{v} = s_i$ or $sz_{v} = n - s_i$ should hold. If $sz_{v} = s_i$ we can choose this edge for the operation $i$ and orient it from parent to $v$. So, the operations in $mask \\setminus \\{i\\}$ should be with indices $> i$. Iterate such masks and update the $dp$ value corresponding to it (using dp values already calculated for subtree of $v$ for the case when edge to parent is not chosen). In the case $sz_{v} = n - s_i$ similarly $sz_{v} = n - s_i$ should hold and operations in $mask \\setminus \\{i\\}$ should be with indices $\\leq i$. We can see, that the number of ways calculated with such dp is correct, because if we assigned operation $i$ to some edge with some direction, we ensured the written size after the operation is correct and that the operations in the subtree have been done before or after the operation $i$ (in relation to direction of edge). Time complexity: $O(n (3^k + 2^k k))$, but it can be improved to $O(n 2^k k)$ with sum over subsets calculation.",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1800",
    "index": "A",
    "title": "Is It a Cat?",
    "statement": "You were walking down the street and heard a sound. The sound was described by the string $s$ consisting of lowercase and uppercase Latin characters. Now you want to find out if the sound was a cat meowing.\n\nFor the sound to be a meowing, the string can only contain the letters 'm', 'e', 'o' and 'w', in either uppercase or lowercase. Also:\n\n- string must start with non-empty sequence consisting only of characters 'm' or 'M'\n- it must be immediately followed by non-empty sequence consisting only of characters 'e' or 'E'\n- it must be immediately followed by non-empty sequence consisting only of characters 'o' or 'O'\n- it must be immediately followed by non-empty sequence consisting only of characters 'w' or 'W', this sequence ends the string, after it immediately comes the string end\n\nFor example, strings \"meow\", \"mmmEeOWww\", \"MeOooOw\" describe a meowing, but strings \"Mweo\", \"MeO\", \"moew\", \"MmEW\", \"meowmeow\" do not.\n\nDetermine whether the sound you heard was a cat meowing or something else.",
    "tutorial": "To solve the problem, you may convert the string to lower case, strip all duplicated characters from it and compare the result to \"meow\" string. To exclude duplicate characters, you can, for example, use the unique function in C++.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    transform(s.begin(), s.end(), s.begin(), [] (char c) {\n        return tolower(c);\n    });\n    s.erase(unique(s.begin(), s.end()), s.end());\n    cout << (s == \"meow\" ? \"YES\" : \"NO\") << \"\\n\";\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1800",
    "index": "B",
    "title": "Count the Number of Pairs",
    "statement": "Kristina has a string $s$ of length $n$, consisting only of lowercase and uppercase Latin letters. For each pair of lowercase letter and its matching uppercase letter, Kristina can get $1$ burl. However, pairs of characters cannot overlap, so each character can only be in one pair.\n\nFor example, if she has the string $s$ = \"aAaaBACacbE\", she can get a burl for the following character pairs:\n\n- $s_1$ = \"a\" and $s_2$ = \"A\"\n- $s_4$ = \"a\" and $s_6$ = \"A\"\n- $s_5$ = \"B\" and $s_{10}$ = \"b\"\n- $s_7$= \"C\" and $s_9$ = \"c\"\n\nKristina wants to get more burles for her string, so she is going to perform no more than $k$ operations on it. In one operation, she can:\n\n- either select the lowercase character $s_i$ ($1 \\le i \\le n$) and make it uppercase.\n- or select uppercase character $s_i$ ($1 \\le i \\le n$) and make it lowercase.\n\nFor example, when $k$ = 2 and $s$ = \"aAaaBACacbE\" it can perform one operation: choose $s_3$ = \"a\" and make it uppercase. Then she will get another pair of $s_3$ = \"A\" and $s_8$ = \"a\"\n\nFind \\textbf{maximum} number of burles Kristina can get for her string.",
    "tutorial": "Count two arrays $big$ and $small$, such that $big[i]$ contains the number of occurrences of $i$th letter of the alphabet in the string in upper case, while $small[i]$ - in lower case. Let's add all existing pairs to the answer, so let's add $min(small[i], big[i])$ to it for each letter. Subtract this minimum from $small[i]$ and $big[i]$ to get the number of unpaired identical letters. Next, we will act greedily: if there is some set of at least two identical letters in the same case, we can apply the operation to half of them and get new pairs. Therefore, for each letter we will add $\\frac{min(k, max(small[i], big[i]))}{2}$ to the answer and decrease $k$ by that amount.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int N = 26;\n\nvoid solve(){\n    int n, k;\n    cin >> n >> k;\n    string s;\n    cin >> s;\n    vector<int>big(N, 0), small(N, 0);\n    for(auto &i : s){\n        if('A' <= i && 'Z' >= i) big[i - 'A']++;\n        else small[i - 'a']++;\n    }\n    int answer = 0;\n    for(int i = 0; i < N; i++){\n        int pairs = min(small[i], big[i]);\n        answer += pairs;\n        small[i] -=pairs; big[i] -= pairs;\n        int add = min(k, max(small[i], big[i]) / 2);\n        k -= add; answer += add;\n    }\n    cout << answer << endl;\n}\nint main(){\n    int t;\n    cin >> t;\n    while(t--) solve();\n    return 0;\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1800",
    "index": "C1",
    "title": "Powering the Hero (easy version)",
    "statement": "\\textbf{This is an easy version of the problem. It differs from the hard one only by constraints on $n$ and $t$}.\n\nThere is a deck of $n$ cards, each of which is characterized by its power. There are two types of cards:\n\n- a hero card, the power of such a card is always equal to $0$;\n- a bonus card, the power of such a card is always positive.\n\nYou can do the following with the deck:\n\n- take a card from the top of the deck;\n- if this card is a bonus card, you can put it \\textbf{on top} of your bonus deck or discard;\n- if this card is a hero card, then the power of \\textbf{the top} card from your bonus deck is added to his power (if it is not empty), after that the hero is added to your army, and the used bonus discards.\n\nYour task is to use such actions to gather an army with the maximum possible total power.",
    "tutorial": "To solve it, it should be noted that despite the way the deck with bonuses works, the order in which they will be applied is not important. Then, when we meet the hero card, we just need to add to the answer the maximum of the available bonuses. Constraints allow you to sort the current array with bonus values each time and remove the maximum element.",
    "code": "def solve():\n    n = int(input())\n    s = [int(x) for x in input().split()]\n    ans = 0\n    buffs = [0] * n\n    for e in s:\n        if e > 0:\n            buffs += [e]\n            j = len(buffs) - 1\n            while buffs[j] < buffs[j - 1]:\n                buffs[j], buffs[j - 1] = buffs[j - 1], buffs[j]\n                j -= 1\n        else:\n            ans += buffs.pop()\n    print(ans)\n\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1800",
    "index": "C2",
    "title": "Powering the Hero (hard version)",
    "statement": "\\textbf{This is a hard version of the problem. It differs from the easy one only by constraints on $n$ and $t$}.\n\nThere is a deck of $n$ cards, each of which is characterized by its power. There are two types of cards:\n\n- a hero card, the power of such a card is always equal to $0$;\n- a bonus card, the power of such a card is always positive.\n\nYou can do the following with the deck:\n\n- take a card from the top of the deck;\n- if this card is a bonus card, you can put it \\textbf{on top} of your bonus deck or discard;\n- if this card is a hero card, then the power of \\textbf{the top} card from your bonus deck is added to his power (if it is not empty), after that the hero is added to your army, and the used bonus discards.\n\nYour task is to use such actions to gather an army with the maximum possible total power.",
    "tutorial": "To solve it, it should be noted that despite the way the deck with bonuses works, the order in which they will be applied is not important. Then, when we meet the hero card, we just need to add to the answer the maximum of the available bonuses. Constraints make you use structures such as a priority queue to quickly find and extract the maximum.",
    "code": "from queue import PriorityQueue\n\n\ndef solve():\n    n = int(input())\n    s = [int(x) for x in input().split()]\n    ans = 0\n    buffs = PriorityQueue()\n    for e in s:\n        if e > 0:\n            buffs.put(-e)\n        elif not buffs.empty():\n            ans -= buffs.get()\n    print(ans)\n\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1800",
    "index": "D",
    "title": "Remove Two Letters",
    "statement": "Dmitry has a string $s$, consisting of lowercase Latin letters.\n\nDmitry decided to remove two \\textbf{consecutive} characters from the string $s$ and you are wondering how many different strings can be obtained after such an operation.\n\nFor example, Dmitry has a string \"aaabcc\". You can get the following different strings: \"abcc\"(by deleting the first two or second and third characters), \"aacc\"(by deleting the third and fourth characters),\"aaac\"(by deleting the fourth and the fifth character) and \"aaab\" (by deleting the last two).",
    "tutorial": "Consider deleting characters with numbers $i$ and $i + 1$, as well as characters with numbers $i + 1$ and $i + 2$. In the first case, the symbol with the number $i + 2$ remains, in the second - $i$. Symbols with numbers less than $i$ or more than $i + 2$ remain in both cases. Therefore, the same strings will be obtained if the characters with the numbers $i$ and $i + 2$ match. Therefore, we just need to count the number of $i: 1 \\le i\\le n - 2: s_i =s_{i+2}$, and subtract this value from $n - 1$.",
    "code": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    int res = n - 1;\n    for (int i = 1; i + 1 < n; ++i) {\n        if (s[i - 1] == s[i + 1]) {\n            res--;\n        }\n    }\n    cout << res << '\\n';\n}\n\nint main(int argc, char* argv[]) {\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "hashing",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1800",
    "index": "E1",
    "title": "Unforgivable Curse (easy version)",
    "statement": "\\textbf{This is an easy version of the problem. In this version, $k$ is always $3$.}\n\nThe chief wizard of the Wizengamot once caught the evil wizard Drahyrt, but the evil wizard has returned and wants revenge on the chief wizard. So he stole spell $s$ from his student Harry.\n\nThe spell — is a $n$-length string of lowercase Latin letters.\n\nDrahyrt wants to replace spell with an unforgivable curse — string $t$.\n\nDrahyrt, using ancient magic, can swap letters at a distance $k$ or $k+1$ in spell as many times as he wants. In this version of the problem, you can swap letters at a distance of $3$ or $4$. In other words, Drahyrt can change letters in positions $i$ and $j$ in spell $s$ if $|i-j|=3$ or $|i-j|=4$.\n\nFor example, if $s = $ \"talant\" and $t = $ \"atltna\", Drahyrt can act as follows:\n\n- swap the letters at positions $1$ and $4$ to get spell \"aaltnt\".\n- swap the letters at positions $2$ and $6$ to get spell \"atltna\".\n\nYou are given spells $s$ and $t$. Can Drahyrt change spell $s$ to $t$?",
    "tutorial": "In these constraints , the problem could be solved as follows: Note that for strings of length $6$ and more, it is enough to check that the strings $s$ and $t$ match character by character, that is, up to permutation, since each character can be moved to the desired half, and then moved to the desired side by length $1$ by applying two operations on the length is $3$ and $4$. For example, there was a string \"abudance\" and we want to shift the $c$ character to the left, then we can first get the string \"acudab\" and then the string \"aaudcb\". Well, we can restore the used symbols by putting them in their place \"budka\". That is, we were able to simply swap two adjacent characters. Thus, with such a clipping, it was possible to solve the problem by brute force for $n\\le 5$. To iterate, it was possible to store $map$ of strings, which we can get and iterate through all the strings using $bfs$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\n\nvoid slow_solve(int n, int k, string s, string t) {\n    set<string> was;\n\n    queue<string> q;\n    q.push(s);\n    was.insert(s);\n\n    auto add = [&](string& s, int i, int j) {\n        if (i >= 0 && i < j && j < n) {\n            swap(s[i], s[j]);\n            if (!was.count(s)) {\n                was.insert(s);\n                q.push(s);\n            }\n            swap(s[i], s[j]);\n        }\n\n    };\n\n    while (!q.empty()) {\n        s = q.front(); q.pop();\n        for (int i = 0; i < n; ++i) {\n            add(s, i, i+k);\n            add(s, i, i+k+1);\n            add(s, i-k, i);\n            add(s, i-k-1, i);\n        }\n    }\n    cout << (was.count(t) ? \"Yes\" : \"No\") << '\\n';\n}\n\nvoid solve() {\n    int n,k; cin >> n >> k;\n    string s; cin >> s;\n    string t; cin >> t;\n\n    if (n <= 5) {\n        slow_solve(n, k, s, t);\n        return;\n    }\n    map<char, int> cnt;\n    for (char c : s) {\n        cnt[c]++;\n    }\n\n    for (char c : t) {\n        cnt[c]--;\n    }\n\n    bool ok = true;\n    for (auto [c, x] : cnt) {\n        ok &= x == 0;\n    }\n    cout << (ok ? \"Yes\" : \"No\") << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dsu",
      "graphs",
      "greedy",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1800",
    "index": "E2",
    "title": "Unforgivable Curse (hard version)",
    "statement": "\\textbf{This is a complex version of the problem. This version has no additional restrictions on the number $k$.}\n\nThe chief wizard of the Wizengamot once caught the evil wizard Drahyrt, but the evil wizard has returned and wants revenge on the chief wizard. So he stole spell $s$ from his student Harry.\n\nThe spell — is a $n$-length string of lowercase Latin letters.\n\nDrahyrt wants to replace spell with an unforgivable curse — string $t$.\n\nDragirt, using ancient magic, can swap letters at a distance $k$ or $k+1$ in spell as many times as he wants. In other words, Drahyrt can change letters in positions $i$ and $j$ in spell $s$ if $|i-j|=k$ or $|i-j|=k+1$.\n\nFor example, if $k = 3, s = $ \"talant\" and $t = $ \"atltna\", Drahyrt can act as follows:\n\n- swap the letters at positions $1$ and $4$ to get spell \"aaltnt\".\n- swap the letters at positions $2$ and $6$ to get spell \"atltna\".\n\nYou are given spells $s$ and $t$. Can Drahyrt change spell $s$ to $t$?",
    "tutorial": "The solution of the problem $E1$ hints to us that with the help of such operations, it is possible to move the symbol in the right direction by $1$ using two operations. Then we can show that among the symbols that we can swap with at least one other symbol, we can get any permutation. For example, you can apply such a greedy solution: we will build an answer from the boundaries of the string $t$ to the middle. Since we can move the symbol by a distance of $1$, we can move it to the border and thus we can build any string $t$. Thus, it is enough to check that the sets of characters that can be swapped with some other match. And for the rest of the characters, check that they just match.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\nvoid solve() {\n    int n, k; cin >> n >> k;\n    string s; cin >> s;\n    string t; cin >> t;\n    vector<int> cnt(26, 0);\n\n    bool ok = true;\n    for (int i = 0; i < n; ++i) {\n        if (i >= k || i+k < n){\n            cnt[s[i] - 'a']++;\n            cnt[t[i] - 'a']--;\n        } else {\n            ok &= s[i] == t[i];\n        }\n    }\n\n    cout << (ok && count(all(cnt), 0) == 26 ? \"YES\" : \"NO\") << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1800",
    "index": "F",
    "title": "Dasha and Nightmares",
    "statement": "Dasha, an excellent student, is studying at the best mathematical lyceum in the country. Recently, a mysterious stranger brought $n$ words consisting of small latin letters $s_1, s_2, \\ldots, s_n$ to the lyceum. Since that day, Dasha has been tormented by nightmares.\n\nConsider some pair of integers $\\langle i, j \\rangle$ ($1 \\le i \\le j \\le n$). A nightmare is a string for which it is true:\n\n- It is obtained by concatenation $s_{i}s_{j}$;\n- Its length is \\textbf{odd};\n- The number of different letters in it is \\textbf{exactly} $25$;\n- The number of occurrences of each letter that is in the word is \\textbf{odd}.\n\nFor example, if $s_i=$ \"abcdefg\" and $s_j=$ \"ijklmnopqrstuvwxyz\", the pair $\\langle i, j \\rangle$ creates a nightmare.\n\nDasha will stop having nightmares if she counts their number. There are too many nightmares, so Dasha needs your help. Count the number of different nightmares.\n\nNightmares are called different if the corresponding pairs $\\langle i, j \\rangle$ are different. The pairs $\\langle i_1, j_1 \\rangle$ and $\\langle i_2, j_2 \\rangle$ are called different if $i_1 \\neq i_2$ \\textbf{or} $j_1 \\neq j_2$.",
    "tutorial": "Observation $1$: the product of odd numbers is odd, so the condition for the length of nightmare is automatically completed. Denote by $f(x)$ the number of ones in binary representation of $x$. Let's enumerate the letters of the Latin alphabet from $0$ to $25$. Observation $2$: for each word, it is enough to know the set of letters included in it and the evenness of their numbers. There are only $26$ letters in the alphabet, so it is convenient to store the word characteristic $s_i$ as a pair of masks $\\langle a_i, b_i \\rangle$. The bit with the number $j$ in $a_i$ will be responsible for the availability of the letter $j$ in $s_i$. The bit with the number $j$ in $b_i$ will be responsible for the evenness of the number of letters $j$ in $s_i$. Observation $3$: strings $s_is_j$ creates nightmare if and only if $f(a_i|a_j) = f(b_i \\oplus b_j) = 25$. Let's fix the number $k$ - the index of the letter that will not be in nightmares. Let's throw out all the words with the letter $k$, now we can look at the words in turn and look for a pair of them among those already considered. It is easy to see that the condition $f(a_i| a_j) = 25$ follows from the condition $f(b_i\\oplus b_j) = 25$ if one letter is banned. To count the number of pairs that include our word, we need to count the number of words with the characteristic $b_j = b_i \\oplus (2^{26}-1)$. We can do this by bin-searching through a sorted array of $b$ or using standard data structures. We got the solution for $O(\\sum |s| + 26 \\cdot n \\cdot \\log n)$.",
    "code": "#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC target(\"avx2,avx,fma,bmi2\")\n\n#include <bits/stdc++.h>\n#include <immintrin.h>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n\n#define endl '\\n'\n//#define int long long\n#define all(arr) arr.begin(), arr.end()\n#define multitest() int _gorilla_silverback; cin >> _gorilla_silverback; while (_gorilla_silverback --> 0)\n#define pikachu push_back\n#define ls(id) (id << 1 | 1)\n#define rs(id) ((id << 1) + 2)\n#define sqr(x) ((x) * (x))\n#define dlg(x) (31 - __builtin_clz(x))\n#define ulg(x) (32 - __builtin_clz(x))\n\ntypedef pair<int, int> ipair;\ntypedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> treap;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nconst int MAXN = 200200;\nconst int L = 26;\n\nint n;\nstring srr[MAXN];\nint arr[MAXN], brr[MAXN], crr[MAXN];\n\nvoid build() {\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (char c: srr[i]) {\n\t\t\tarr[i] ^= (1 << (c - 'a'));\n\t\t\tbrr[i] |= (1 << (c - 'a'));\n\t\t}\n\t}\n}\n\nlong long calc(int c) {\n\tint k = 0;\n\tfor (int i = 0; i < n; ++i)\n\t\tif (brr[i] >> c & 1 ^ 1) crr[k++] = arr[i];\n\tsort(crr, crr + k);\n\tint mask = -1 & ((1 << L) - 1) ^ (1 << c);\n\tlong long ans = 0;\n\tfor (int i = 0; i < k; ++i) {\n\t\tauto itl = lower_bound(crr, crr + k, crr[i] ^ mask);\n\t\tauto itr = upper_bound(crr, crr + k, crr[i] ^ mask);\n\t\tans += itr - itl;\n\t}\n\treturn ans >> 1LL;\n}\n\nlong long solve() {\n\tlong long ans = 0;\n\tfor (int c = 0; c < L; ++c)\n\t\tans += calc(c);\n\treturn ans;\n}\n\nsigned main() {\n\tios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);\n\tcin >> n;\n\tfor (int i = 0; i < n; ++i)\n\t\tcin >> srr[i];\n\tbuild();\n\tcout << solve() << endl;\n}",
    "tags": [
      "bitmasks",
      "hashing",
      "meet-in-the-middle",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1800",
    "index": "G",
    "title": "Symmetree",
    "statement": "Kid was gifted a tree of $n$ vertices with the root in the vertex $1$. Since he really like symmetrical objects, Kid wants to find out if this tree is symmetrical.\n\n\\begin{center}\n{\\small For example, the trees in the picture above are symmetrical.}\n\\end{center}\n\n\\begin{center}\n{\\small And the trees in this picture are not symmetrical.}\n\\end{center}\n\nFormally, a tree is symmetrical if there exists an order of children such that:\n\n- The subtree of the leftmost child of the root is a mirror image of the subtree of the rightmost child;\n- the subtree of the second-left child of the root is a mirror image of the subtree of the second-right child of the root;\n- ...\n- if the number of children of the root is odd, then the subtree of the middle child should be symmetrical.",
    "tutorial": "Note that if one subtree is a mirror image of another, then they are isomorphic (that is, equal without taking into account the vertex numbers). To check the subtrees for isomorphism, we use hashing of root trees. Now we just have to learn how to check trees for symmetry. To do this, let's calculate how many children of each type our vertex has (let's denote the hash of its subtree by the vertex type). In order for the vertex subtree to be symmetric, each child must have a pair of the same type, except perhaps one, which must also be symmetric. We can calculate the symmetry of the subtrees while counting their hash to simplify this task.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(time(nullptr));\n\nconst int inf = 2e18;\nconst ll M = 1e9;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nint last;\nmap<vector<int>, int> eq;\nmap<int, bool> symmetrical;\n\nint dfs(int v, int p, vector<vector<int>> &sl){\n    vector<int> children;\n    for(int u: sl[v]){\n        if(u == p) continue;\n        children.emplace_back(dfs(u, v, sl));\n    }\n    sort(all(children));\n    if(!eq.count(children)){\n        map<int, int> cnt;\n        for(int e: children){\n            cnt[e]++;\n        }\n        int odd = 0, bad = 0;\n        for(auto e: cnt){\n            if(e.y & 1){\n                odd++;\n                bad += !symmetrical[e.x];\n            }\n        }\n        eq[children] = last;\n        symmetrical[last] = odd < 2 && bad == 0;\n        last++;\n    }\n    return eq[children];\n}\n\nvoid solve(int tc){\n    int n;\n    cin >> n;\n    eq.clear();\n    symmetrical.clear();\n    eq[vector<int>(0)] = 0;\n    symmetrical[0] = true;\n    last = 1;\n    vector<vector<int>> sl(n);\n    for(int i = 1; i < n; ++i){\n        int u, v;\n        cin >> u >> v;\n        sl[--u].emplace_back(--v);\n        sl[v].emplace_back(u);\n    }\n    cout << (symmetrical[dfs(0, 0, sl)]? \"YES\" : \"NO\");\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "hashing",
      "implementation",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1801",
    "index": "A",
    "title": "The Very Beautiful Blanket",
    "statement": "Kirill wants to weave the very beautiful blanket consisting of $n \\times m$ of the same size square patches of some colors. He matched some non-negative integer to each color. Thus, in our problem, the blanket can be considered a $B$ matrix of size $n \\times m$ consisting of non-negative integers.\n\nKirill considers that the blanket is very beautiful, if for each submatrix $A$ of size $4 \\times 4$ of the matrix $B$ is true:\n\n- $A_{11} \\oplus A_{12} \\oplus A_{21} \\oplus A_{22} = A_{33} \\oplus A_{34} \\oplus A_{43} \\oplus A_{44},$\n- $A_{13} \\oplus A_{14} \\oplus A_{23} \\oplus A_{24} = A_{31} \\oplus A_{32} \\oplus A_{41} \\oplus A_{42},$\n\nwhere $\\oplus$ means bitwise exclusive OR\n\nKirill asks you to help her weave a very beautiful blanket, and as colorful as possible!\n\nHe gives you two integers $n$ and $m$.\n\nYour task is to generate a matrix $B$ of size $n \\times m$, which corresponds to a very beautiful blanket and in which the number of different numbers maximized.",
    "tutorial": "The maximum number of different numbers we can type is always $n\\cdot m$. Let's show how you can build an example for any $n$ and $m$. Note that if we were able to construct a correct matrix, then any of its submatrix is also a correct matrix of a smaller size. Therefore, let's build a correct matrix for some $N$ and $M$, and as an answer we will output the upper left corner of this matrix of the desired size. Take $N = M = 2^8$ and construct the matrix using the following algorithm. Let's break it into blocks of size $2 \\times 2$. Let's number the blocks from left to right and from top to bottom in order, starting from zero. The $i$th block will have the form $4i + 0$ $4i + 1$ $4i + 2$ $4i + 3$ With this construction, the bitwise exclusive OR any submatrix of size $2\\times 2$ will be zero. You can verify this as follows. Let's look at the upper left corner of $(i,\\,j)$ of an arbitrary submatrix of size $2\\times 2$. There are 4 cases: both coordinates are even; $i$ is even, $j$ is odd; $i$ odd, $j$ even; both coordinates are odd. Immediately note that $i, \\, j < 200 < 2^8$ Consider the most unpleasant case - the last one. The remaining cases are treated in a similar way. In this case, the submatrix will have the form: $4i + 3$ $4(i + 1) + 2$ $4(i + 2^8) + 1$ $4(i + 2^8 + 1) + 0$ Note that the second part of each term is less than 4, and the first part of each term is greater than or equal to 4. Therefore, they can be considered independently. $3 \\oplus 2 \\oplus 1 \\oplus 0$ $=$ $0$. If $i$$=$$1$, then $4i \\oplus 4(i + 1)$ $=$ $12$, $4(1 + 2^8) \\oplus 4(2 + 2^8)$ $=$ $12$. If $i\\neq 1$, then $4i \\oplus 4(i + 1)$ $=$ $4$ $4(i + 2^8) \\oplus 4(i + 2^8 + 1)$$=$$4$ (for $i=0$, you can check with your hands, for $1 < i <2^8$ $4(i+ 2^8)$ will be reduced and $4$ will remain from the second term). $4 \\oplus 4 \\oplus 0$ $=$ $0$. Thus, in the selected submatrix, the bitwise exclusive OR is zero.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int SZ = 256;\n\nint v[SZ][SZ];\n\nvoid Solve(){\n    int n, m;\n    cin >> n >> m;\n\n    cout << n * m << '\\n';\n\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < m; j++)\n            cout << v[i][j] << \" \\n\"[j + 1 == m];\n}\n\nsigned main(){\n    ios_base::sync_with_stdio(NULL);\n    cin.tie(NULL);\n    cout.tie(NULL);\n\n    {\n        int now = 0;\n        int n = 256;\n        int m = 256;\n\n        for(int i = 0; i < n; i += 2)\n            for(int j = 0; j < m; j += 2){\n                v[i][j] = now;\n                v[i][j + 1] = now + 1;\n                v[i + 1][j] = now + 2;\n                v[i + 1][j + 1] = now + 3;\n                now += 4;\n            }\n    }\n\n    int num_test = 1;\n    cin >> num_test;\n\n    for(int i = 1; i <= num_test; i++){\n        Solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1801",
    "index": "B",
    "title": "Buying gifts",
    "statement": "Little Sasha has two friends, whom he wants to please with gifts on the Eighth of March. To do this, he went to the largest shopping center in the city.There are $n$ departments in the mall, each of which has exactly two stores. For convenience, we number the departments with integers from $1$ to $n$. It is known that gifts in the first store of the $i$ department cost $a_i$ rubles, and in the second store of the $i$ department — $b_i$ rubles.\n\nEntering the mall, Sasha will visit each of the $n$ departments of the mall, and in each department, he will enter exactly one store. When Sasha gets into the $i$-th department, he will perform exactly one of two actions:\n\n- Buy a gift for the first friend, spending $a_i$ rubles on it.\n- Buy a gift for the second friend, spending $b_i$ rubles on it.\n\nSasha is going to buy at least one gift for each friend. Moreover, he wants to pick up gifts in such a way that the price difference of the most expensive gifts bought for friends is as small as possible so that no one is offended.\n\nMore formally: let $m_1$  be the maximum price of a gift bought to the first friend, and $m_2$  be the maximum price of a gift bought to the second friend. Sasha wants to choose gifts in such a way as to minimize the value of $\\lvert m_1 - m_2 \\rvert$.",
    "tutorial": "To begin with, let's sort all departments in descending order $b_i$ (and if ~--- is equal, in ascending order $a_i$). Now let's go through the $i$ department, in which the most expensive gift for the second girlfriend will be bought. Note that in all departments with numbers $j < i$, Sasha must buy a gift for the first girlfriend, otherwise the gift $i$ will not have the maximum value among the gifts bought for the second girlfriend. Therefore, we will immediately find the value of $m = \\max \\limits_{j < i} a_j$. Thus, we can already get the answer $\\lvert m - b_i\\rvert$. In all departments with numbers $j > i$, for which $a_j \\le m$, Sasha can buy a gift for any of her friends, and this will not affect the answer in any way. Now consider all departments with numbers $j > i$ for which $a_j > m$. If you buy a gift for your first girlfriend in some of these departments, the value of $m$ will increase, which means the answer may improve. Therefore, let's iterate through all these departments and update the response with the value $\\lvert a_j - b_i\\rvert$. Time $O(n^2)$. Let's optimize this solution. To begin with, instead of calculating the value of $m$ anew at each iteration, we will maintain its value in some variable. Then, when moving from department $i - 1$ to department $i$, we will update the value of $m$ as follows: $m:= \\max(m, a_i)$. It remains to learn how to quickly find the optimal department number $j$, such that $j > i$, $a_j > m$, as well as $\\lvert a_j - b_i\\rvert$ is minimal. Let's choose on the suffix of the array the minimum $a_j$, such that $a_j\\ge b_i$, and also the maximum $a_j$, such that $a_j \\le b_i$. You can notice that the optimal $a_j$ is one of the two selected numbers (you also need to remember to check the condition $a_j > m$). Therefore, it is enough to update the answer only with the help of them. You can search for these two elements using the \\texttt{set} data structure. We will support in the set all $a_j$ located on the suffix. Then you can find the necessary two elements for $O(\\log n)$. When moving from department $i - 1$ to department $i$, you need to remove the value $a_{i - 1}$ from the data structure. Time $O(n\\log n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntemplate<typename T>\nbool smin(T& a, const T& b) {\n    if (b < a) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n\ntemplate<typename T>\nbool smax(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n\nconst int INF = 0x3f3f3f3f;\nconst int N = 500100;\n\nstd::pair<int, int> a[N];\n\nvoid run() {\n    int n;\n    scanf(\"%d\", &n);\n\n    for (int i = 0; i < n; ++i) {\n        scanf(\"%d%d\", &a[i].first, &a[i].second);\n    }\n\n    sort(a, a + n, [&](const pair<int, int>& p1, \n                            const pair<int, int>& p2) {\n        return p1.second > p2.second || (p1.second == p2.second && p1.first < p2.first);\n    });\n\n    multiset<int> setik;\n    for (int i = 0; i < n; ++i) {\n        setik.insert(a[i].first);\n    }\n\n    int mx = -INF;\n    int ans = INF;\n    \n    for (int i = 1; i < n; ++i) {\n        smin(ans, abs(a[i].first - a[0].second));\n    }\n    \n    for (int i = 0; i < n; ++i) {\n        setik.erase(setik.find(a[i].first));\n        if (i == 0) {\n            mx = a[i].first;\n            continue;\n        }\n\n        smin(ans, abs(mx - a[i].second));\n        auto it = setik.lower_bound(a[i].second);\n        if (it != setik.end() && *it >= mx) {\n            smin(ans, abs(*it - a[i].second));\n        }\n        if (it != setik.begin() && *std::prev(it) >= mx) {\n            smin(ans, abs(*prev(it) - a[i].second));\n        }\n\n        smax(mx, a[i].first);\n    }\n\n    printf(\"%d\\n\", ans);\n}\n\nint main(void) {\n    int t;\n    scanf(\"%d\", &t);\n    while (t--) {\n        run();\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1801",
    "index": "C",
    "title": "Music Festival",
    "statement": "The boy Vitya loves to listen to music very much. He knows that $n$ albums are due to be released this Friday, $i$-th of which contains $k_i$ tracks. Of course, Vitya has already listened to all the tracks, and knows that in the $i$-th album, the coolness of the $j$-th track is equal to $a_{i,j}$.Vitya has a friend Masha, whom he really wants to invite to the festival, where his favorite bands perform. However, in order for a friend to agree, she must first evaluate the released novelties. Vitya knows that if Masha listens to a track that was cooler than all the previous ones, she will get 1 unit of impression. Unfortunately, albums can only be listened to in their entirety, without changing the songs in them in places.\n\nHelp Vitya find such an order of albums so that Masha's impression turns out to be as much as possible, and she definitely went to the festival with him.",
    "tutorial": "Let's introduce the concept of a compressed album for an album, which is obtained from the original one by removing all elements except those that are the first maxima on their corresponding prefixes. For example: For the album $[\\textbf{1}, \\textbf{4}, 4, 3, \\textbf{6}, 5, 6]$ the album will be compressed $[1, 4, 6]$. Now we note that the solution of the original problem is reduced to solving the same problem, but on compressed albums. Indeed, the answer to them will not be different, because if some element increased the impression on ordinary albums, then it will increase if you compress albums and vice versa. Next, it will be assumed that all albums have been compressed beforehand. Let's introduce $dp_c$ - the maximum impression that can be obtained if there were no albums such that they have elements larger than $c$. Then, $dp_c$ is equal to $dp_{c-1}$, or you can add another element or two if $c$ is the maximum element for some album. Then for all compressed albums, it can be recalculated through the value of $dp$ at the point before the first element of the album, or through $c - 1$. Thus, for recalculation, it is enough to know for each $c$ which albums ended in this index, as well as for each album its first element. Solution for $O(K)$ Let's now solve the complete problem. For each value of $c$, let's remember the indexes of albums that contain an element equal to $c$. We go in order of increasing $c$, we maintain for each album the value of $dp_i$ - the maximum impression that can be obtained if there were no elements of large $c$ and Masha listened to the last $i$ album. Suppose for the next $c$ there is an album $i$, that there is a song with the coolness of $c$ in it. Then $dp_i$ should be taken as the maximum of $dp_i + 1$ and the values for all $dp_j + 1$, such that the maximum element in the $j$th album is less than the maximum element of $i$th, since she could listen to this track, either next in this album, or after listening to some other album completely. Note that you can store the value of $mx$ - maximum for all albums for which the maximum value in them is less than $c$ and recalculate it when moving to $c + 1$, storing those albums that have ended, then you will get a solution for $O(K + C)$.",
    "code": "#include \"bits/stdc++.h\"\n#include <algorithm>\n#include <locale>\n#include <random>\n#include <unordered_map>\n#include <vector>\n\nusing namespace std;\n\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\ntypedef long long ll;\ntypedef long double db;\ntypedef unsigned long long ull;\n\nvector<int> shrink(vector<int> &a) {\n  vector<int> a1;\n  int n = a.size();\n  int mx = 0;\n  for (int i = 0; i < n; ++i) {\n    if (a[i] > mx) {\n      a1.emplace_back(a[i]);\n      mx = a[i];\n    }\n  }\n  return a1;\n}\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<vector<int>> a(n);\n  int k;\n  for (int i = 0; i < n; ++i) {\n    int k;\n    cin >> k;\n    a[i].resize(k);\n    for (auto &j : a[i]) {\n      cin >> j;\n    }\n  }\n  vector<vector<int>> a1(n);\n  for (int i = 0; i < n; ++i) {\n    a1[i] = shrink(a[i]);\n  }\n  map<int, vector<int>> b;\n  for (int i = 0; i < n; ++i) {\n    for (auto &j : a1[i]) {\n      b[j].emplace_back(i);\n    }\n  }\n  vector<int> dp(n);\n  int closed = 0;\n  for (auto &it : b) {\n    int c = it.first;\n    int newclosed = 0;\n    for (auto &i : it.second) {\n      if (c == a1[i].back()) {\n        dp[i] = max(dp[i] + 1, closed + 1);\n        newclosed = max(newclosed, dp[i]);\n        continue;\n      }\n      if (c == a1[i].front()) {\n        dp[i] = closed + 1;\n        continue;\n      }\n      dp[i] = max(dp[i] + 1, closed + 1);\n    }\n    closed = max(closed, newclosed);\n  }\n  cout << *max_element(all(dp));\n}\n\nsigned main() {\n  int t = 0;\n  cin >> t;\n  while (t --> 0) {\n      solve();\n      cout << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1801",
    "index": "D",
    "title": "The way home",
    "statement": "The famous magician Borya Budini traveled through the country $X$, which consists of $n$ cities. However, an accident happened, and he was robbed in the city number $1$. Now Budini will have a hard way home to the city number $n$.He's going to get there by plane. In total, there are $m$ flights in the country, $i$-th flies from city $a_i$ to city $b_i$ and costs $s_i$ coins. Note that the $i$-th flight is one-way, so it can't be used to get from city $b_i$ to city $a_i$. To use it, Borya must be in the city $a_i$ and have at least $s_i$ coins (which he will spend on the flight).\n\nAfter the robbery, he has only $p$ coins left, but he does not despair! Being in the city $i$, he can organize performances every day, each performance will bring him $w_i$ coins.\n\nHelp the magician find out if he will be able to get home, and what is the minimum number of performances he will have to organize.",
    "tutorial": "Note that the show can be done \"postponed\". As soon as we don't have enough money to walk along the edge, we can do several shows in advance among the peaks that we have already passed, so as to earn the maximum amount of money. For the general case, you can write $dp[v][best] = (\\textit{min show}, \\textit{max money})$, where $v$ is the number of the vertex where we are, and $best$ is the vertex with max. $w_i$, which we have already passed through. It can be shown that it is optimal to minimize the number of shows first, and then maximize the amount of money. This dynamics can be recalculated using Dijkstra's algorithm. Asymptotics of $O(mn\\log n)$",
    "code": "#include \"bits/stdc++.h\"\n\n#define rep(i, n) for (int i = 0; i < (n); ++i)\n#define pb push_back\n#define all(a) (a).begin(), (a).end()\n#define ar array\n#define vec vector\n\nusing namespace std;\n\nusing ll = long long;\nusing pi = pair<int, int>;\n\nusing vi = vector<int>;\nusing vpi = vector<pair<int, int>>;\n\nconst ll INF = 2e18;\nconst int maxN = 3e5 + 10;\n\nstruct PathParams {\n    ll num_show;\n    int money;\n};\n\nbool operator==(const PathParams &a, const PathParams &b) {\n    return tie(a.num_show, a.money) == tie(b.num_show, b.money);\n}\n\nbool operator!=(const PathParams &a, const PathParams &b) {\n    return !(a == b);\n}\n\nstruct State {\n    PathParams params;\n    int v;\n    int best;\n};\n\nbool operator<(const PathParams &a, const PathParams &b) {\n    if (a.num_show != b.num_show) return a.num_show < b.num_show;\n    return a.money > b.money;\n}\n\nbool operator<(const State &a, const State &b) {\n    return tie(a.params, a.v, a.best) < tie(b.params, b.v, b.best);\n}\n\nbool operator>(const State &a, const State &b) {\n    return !(a < b);\n}\n\nvoid solve() {\n    int n, m, p, group;\n    cin >> n >> m >> p;\n    vector dp(n, vector<PathParams>(n, {INF, 0}));\n    vector<vpi> g(n);\n    vi w(n);\n    rep(i, n) cin >> w[i];\n    rep(i, m) {\n        int a, b, s;\n        cin >> a >> b >> s;\n        a--;\n        b--;\n        g[a].emplace_back(b, s);\n    }\n    dp[0][0] = {0, p};\n    priority_queue<State, vector<State>, greater<>> pq;\n    pq.push({.params = {.num_show=0, .money=p}, .v = 0, .best=0});\n    while (!pq.empty()) {\n        auto current = pq.top();\n        pq.pop();\n        int v = current.v;\n        int best = current.best;\n        if (dp[v][best] != current.params) continue;\n        for (auto &[u, s]: g[v]) {\n            auto state2 = current;\n            PathParams &path = state2.params;\n            if (path.money < s) {\n                ll need = (s - path.money + w[best] - 1) / w[best];\n                path.num_show += need;\n                path.money += need * w[best];\n                assert(path.money < s + w[best]);\n            }\n            path.money -= s;\n            state2.v = u;\n            if (w[u] > w[state2.best]) state2.best = u;\n            if (path < dp[u][state2.best]) {\n                dp[u][state2.best] = path;\n                pq.push(state2);\n            }\n        }\n    }\n    ll ans = INF;\n    rep(i, n) {\n        ans = min(ans, dp[n - 1][i].num_show);\n    }\n    cout << (ans == INF ? -1 : ans) << '\\n';\n}\n\nsigned main() {\n    int t = 1;\n    cin >> t;\n    rep(_, t) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "graphs",
      "greedy",
      "shortest paths",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1801",
    "index": "E",
    "title": "Gasoline prices",
    "statement": "Berland — is a huge country consisting of $n$ cities. The road network of Berland can be represented as a root tree, that is, there is only $n - 1$ road in the country, and you can get from any city to any other exactly one way, if you do not visit any city twice. For the convenience of representing the country, for each city $i$, the city $p_i$ is fixed, equal to the first city to which you need to go from the city $i$ to get to the city $1$. In other words, the city $p_i$ is equal to the ancestor of the city $i$ if the tree is hung for the city $1$.There is one gas station in each city of Berland. Gas stations have special pricing, and for each gas station there is a fixed range of prices for which they are ready to sell gasoline. A gas station in the city with the number $i$ is ready to sell gasoline at any price from $l_i$ to $r_i$ inclusive.\n\nThe King of Berland — is an exemplary family man, and for $m$ years, two sons were born to him every year. The king's children have been involved in public affairs since early childhood, and at the end of each year they check the honesty of gasoline prices. From birth, the king's children, who are born in the year $i$, are responsible for checking gasoline prices on the ways from the city of $a_i$ to the city of $b_i$ and from the city of $c_i$ to the city of $d_i$, respectively.\n\nThe check is as follows: both children simultaneously start their journey from the cities $a_i$ and $c_i$, respectively. The first son of the king, born in the year $i$, moves along the path from the city $a_i$ to the city $b_i$, and the second  — from the city $c_i$ to the city $d_i$. Children check that the price of gasoline in the city of $a_i$ coincides with the price of gasoline in the city of $c_i$. Next, they check that the price of gasoline in the second city on the way from $a_i$ to $b_i$ coincides with the price in the second city on the way from $c_i$ to $d_i$. Then they repeat the same thing for a couple of third cities on their paths and so on. At the end, they check that the price of gasoline in the city of $b_i$ coincides with the price of gasoline in the city of $d_i$. It is guaranteed that the length of the path from the city $a_i$ to the city $b_i$ coincides with the length of the path from the city $c_i$ to the city $d_i$.\n\nGas stations must strictly obey the laws, and therefore all checks of gasoline prices should not reveal violations. Help Berland gas stations find out how many ways they can set gasoline prices for $m$ years. In other words, for each $i$ from $1$ to $m$, calculate how many ways you can set gasoline prices at all gas stations so that after the birth of the first $i$ pairs of the king's children, all their checks did not reveal violations, and at any gas station the price was in the acceptable price range. Since the number of such methods can be large, calculate the answer modulo $10^9 + 7$.",
    "tutorial": "To begin with, let's understand what is required of us. A tree is given, in each vertex of which the price range for this vertex is recorded. A query is a pair of paths of equal length, the prices at the $i$-th vertices along these paths should be equal for all $i$. We need to find the number of ways to place prices at the vertices for each prefix of restrictions Let's start with a slow solution of the problem. We will store the connectivity components (in each vertex prices should be equal). For each of them, we store an acceptable price range. The answer will be the product of the lengths of the ranges over all components. We will go along the paths and combine 2 vertices into one component using DSU. It is clear that to speed up this solution, it is necessary to search faster for the moments when two vertices are combined into one component. First, let's analyze the long solution. Let's make a heavy-light decomposition, with which we will hash the paths in the tree, taking the root number of its components as a symbol for the vertex. Now, with the help of bin search, we will look for the first moment when the hashes on the path prefixes differ, that is, two vertices are combined into one component. With the help of transfusions, we will update the roots of their components for vertices and the tree of segments for hld. We will get $n$ unions, we will find each one for $O(log^2(n))$ using hld. There will also be $O(n\\cdot log(n))$ updates in the segment tree due to overflows. For each request there will be $O(log^2(n))$ from hld. The final asymptotic $O((n+q)\\cdot log^2(n))$ Now let's give a beautiful solution to this problem. Let's start with bamboo. Replace the equality of prices on a pair of paths with two pairs of paths with lengths equal to the maximum power of two, less than the length of the original path (as in sparse table). Now the path lengths of all constraints have become powers of two. We will iterate over the powers of two in descending order $2^k$, for each path of length $2^k$ we will get a vertex in the graph, we will also get a vertex for each such path in reverse order. Now the constraints define edges in such a graph. Let's spend them, select the spanning tree. For each edge from the backbone, we divide the constraints into 2 constraints with path lengths half as long and continue the process. On a layer with lengths 1, we will get the spanning tree we need, which will be responsible for the first moments when some pairs of vertices were combined into components. Note that no more than $2n$ edges will be added down from each layer, as well as no more than $2q$ edges from queries. That is, each layer will work for $O((n + q)\\cdot\\alpha(n))$, where $\\alpha(n)$ is the average operating time in DSU, the inverse of the Ackerman function. We got the solution in $O((n + q) \\cdot\\alpha(n)\\cdot log(n))$ For a complete solution on the tree, first we divide a pair of paths into three pairs of corresponding vertical paths (take from the 4 end vertices of these paths the pair of vertices closest to the lca on its path, then we pair this path with a vertical path (part of another path), now we get one vertical path and an arbitrary path in the tree, let's split the second path by lca and the first by the corresponding lengths). Next, we will proceed similarly to bamboo, only the place of the vertex responsible for the segment, we will get the vertex responsible for the binary ascent in the tree to a height equal to the power of two.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nconst int mod = (int) 1e9 + 7;\n\nint inv(int x) {\n    int res = 1, n = mod - 2;\n    while (n) {\n        if (n & 1) {\n            res = res * 1ll * x % mod;\n        }\n        x = x * 1ll * x % mod;\n        n /= 2;\n    }\n    return res;\n}\n\nconst int N = (int) 2e5 + 22, K = 18;\nvector<int> g[N];\npair<int, int> a[N];\nint n, q, ans = 1;\nint h[N], up[N][K], lg[N];\nvector<array<int, 3>> graph[K]; // lower vertex1, lower vertex2, time, vertex with direction\nvector<array<int, 3>> gr[N];\nvector<array<int, 3>> edges;\n\nstruct dsu {\n    vector<int> p, sz;\n\n    void build(int n) {\n        p.resize(n);\n        sz.resize(n);\n        for (int i = 0; i < n; i++) {\n            p[i] = i;\n            sz[i] = 1;\n        }\n    }\n\n    int get(int v) {\n        return (v == p[v] ? v : p[v] = get(p[v]));\n    }\n\n    bool merge(int v, int u) {\n        v = get(v), u = get(u);\n        if (v != u) {\n            if (sz[v] > sz[u]) {\n                swap(v, u);\n            }\n            p[v] = u;\n            sz[u] += sz[v];\n            return true;\n        }\n        return false;\n    }\n} G, dsu[K];\n\nvoid dfs(int v, int pr, int d) {\n    h[v] = d;\n    up[v][0] = pr;\n    for (int j = 1; j < K; j++) {\n        up[v][j] = up[up[v][j - 1]][j - 1];\n    }\n    for (auto u : g[v]) {\n        dfs(u, v, d + 1);\n    }\n}\n\nint la(int v, int x) {\n    for (int j = 0; j < K; j++) {\n        if (x >> j & 1) {\n            v = up[v][j];\n        }\n    }\n    return v;\n}\n\nint lca(int v, int u) {\n    if (h[v] > h[u]) {\n        swap(v, u);\n    }\n    u = la(u, h[u] - h[v]);\n    if (v == u) {\n        return v;\n    }\n    for (int j = K - 1; j >= 0; j--) {\n        if (up[v][j] != up[u][j]) {\n            v = up[v][j], u = up[u][j];\n        }\n    }\n    return up[v][0];\n}\n\nint id(int v) {\n    return (v > 0 ? v : -v + n);\n}\n\nint sgn(int v) {\n    return (v > 0 ? 1 : -1);\n}\n\nvoid add_edge(int j, int v, int u, int t) {\n    if (dsu[j].merge(id(v), id(u))) {\n        if (j > 0) {\n            if (sgn(v) == sgn(u)) {\n                add_edge(j - 1, v, u, t);\n                add_edge(j - 1, sgn(v) * up[abs(v)][j - 1], sgn(u) * up[abs(u)][j - 1], t);\n            } else {\n                if (sgn(v) == -1) {\n                    swap(v, u);\n                }\n                add_edge(j - 1, v, sgn(u) * up[abs(u)][j - 1], t);\n                add_edge(j - 1, sgn(v) * up[abs(v)][j - 1], u, t);\n            }\n        } else {\n            edges.push_back({abs(v), abs(u), t});\n        }\n    }\n}\n\nvoid add(int v, int u, int x, int y, int t, int type1, int type2) {\n    if (h[v] < h[u]) {\n        swap(v, u);\n    }\n    if (h[x] < h[y]) {\n        swap(x, y);\n    }\n    assert(h[v] - h[u] == h[x] - h[y]);\n    int g = lg[h[v] - h[u]];\n    if (type1 == type2) {\n        add_edge(g, type1 * v, type2 * x, t);\n        add_edge(g, type1 * la(v, h[v] - h[u] - (1 << g) + 1), type2 * la(x, h[x] - h[y] - (1 << g) + 1), t);\n    } else {\n        add_edge(g, type1 * v, type2 * la(x, h[x] - h[y] - (1 << g) + 1), t);\n        add_edge(g, type1 * la(v, h[v] - h[u] - (1 << g) + 1), type2 * x, t);\n    }\n}\n\nvoid merge(int v, int u) {\n    v = G.get(v), u = G.get(u);\n    if (v != u) {\n        G.merge(v, u);\n        if (G.sz[v] > G.sz[u]) {\n            swap(v, u);\n        }\n        if (a[v].first <= a[v].second) {\n            ans = ans * 1ll * inv(a[v].second - a[v].first + 1) % mod;\n        }\n        if (a[u].first <= a[u].second) {\n            ans = ans * 1ll * inv(a[u].second - a[u].first + 1) % mod;\n        }\n        a[u].first = max(a[u].first, a[v].first);\n        a[u].second = min(a[u].second, a[v].second);\n        if (a[u].first > a[u].second) {\n            ans = 0;\n        } else {\n            ans = ans * 1ll * (a[u].second - a[u].first + 1) % mod;\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    for (int j = 2; j < N; j++) {\n        lg[j] = lg[j / 2] + 1;\n    }\n    cin >> n;\n    for (int i = 2; i <= n; i++) {\n        int v;\n        cin >> v;\n        g[v].push_back(i);\n    }\n    for (int i = 1; i <= n; i++) {\n        cin >> a[i].first >> a[i].second;\n        ans = ans * 1ll * (a[i].second - a[i].first + 1) % mod;\n    }\n    dfs(1, 1, 0);\n    cin >> q;\n    for (int j = 0; j < K; j++) {\n        dsu[j].build(2 * n + 1);\n    }\n    for (int i = 0; i < q; i++) {\n        int v, u, x, y;\n        cin >> v >> u >> x >> y;\n        int w = lca(v, u);\n        int z = lca(x, y);\n        if (h[v] - h[w] > h[x] - h[z]) {\n            swap(v, x);\n            swap(u, y);\n            swap(w, z);\n        }\n        if (v != w) {\n            int d = h[v] - h[w];\n            int v2 = la(v, d - 1);\n            int x2 = la(x, d - 1);\n            add(v, v2, x, x2, i, 1, 1);\n            v = up[v2][0];\n            x = up[x2][0];\n        }\n        if (x != z) {\n            int d = h[x] - h[z];\n            int v2 = la(u, (h[u] - h[v]) - d);\n            int x2 = la(x, d - 1);\n            add(v, up[v2][0], x, x2, i, -1, 1);\n            v = v2;\n            x = up[x2][0];\n        }\n        add(v, u, x, y, i, (h[v] > h[u] ? 1 : -1), (h[x] > h[y] ? 1 : -1));\n    }\n    G.build(n + 1);\n    int j = 0;\n    for (int i = 0; i < q; i++) {\n        while (j < (int) edges.size() && edges[j][2] == i) {\n            merge(edges[j][0], edges[j][1]);\n            j++;\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dsu",
      "hashing",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1801",
    "index": "F",
    "title": "Another n-dimensional chocolate bar",
    "statement": "Mom bought the boy Vasya a $n$-dimensional chocolate bar, which is a $n$-dimensional cube with the length of each side equal to $1$. The chocolate is planned to be divided into slices. According to the $i$th dimension, it can be divided by hyperplanes into $a_i$ equal parts. Thus, the chocolate is divided in total into $a_1 \\cdot a_2 \\cdot a_3 \\cdot \\ldots \\cdot a_n$ slices, each slice has a length of $i$-th dimension equal to $\\frac{1}{a_i}$, respectively, the volume of each slice is $\\frac{1}{a_1 a_2 \\cdots a_n}$.Vasya and his friends want to cut a chocolate bar to get at least $k$ pieces, while Vasya wants to maximize the volume of the smallest of them. It is possible to cut the chocolate bar only at the junction of the lobules, and each incision must pass through the entire chocolate bar along some hyperplane involved in the formation of lobules. Only after making all the cuts, Vasya disassembles the chocolate into pieces.\n\nMore formally, Vasya wants to choose the numbers $b_1, b_2, \\dots, b_n$ ($1 \\le b_i \\le a_i$) — the number of parts into which Vasya will cut the chocolate bar along each dimension. The condition $b_1 \\cdot b_2 \\cdot \\ldots \\cdot b_n \\ge k$ must be met to get at least $k$ pieces after all cuts. It can be noted that with optimal cutting with such parameters, the minimum piece will contain $\\lfloor \\frac{a_1}{b_1} \\rfloor \\dotsm \\lfloor \\frac{a_n}{b_n} \\rfloor$ slices, and its volume will be equal to $\\lfloor \\frac{a_1}{b_1} \\rfloor \\dotsm \\lfloor \\frac{a_n}{b_n} \\rfloor \\cdot \\frac{1}{a_1 a_2 \\cdots a_n}$.\n\nVasya wants to get the maximum possible value of the volume of the minimum piece multiplied by $k$, that is, he wants to maximize the number of $\\lfloor \\frac{a_1}{b_1} \\rfloor \\dotsm \\lfloor \\frac{a_n}{b_n} \\rfloor \\cdot \\frac{1}{a_1 a_2 \\cdots a_n} \\cdot k$. Help him with this.",
    "tutorial": "For $A$ we denote the maximum value of $a_i$ To begin with, let's solve the problem for $O(n\\cdot k\\cdot f(k, A))$ using dynamic programming. Let's put $dp[i][j]$- the maximum possible volume of the smallest piece, if by the first $i$ measurements we divided the chocolate into $j$ parts. If we have divided into more than $k$ parts, we will also put the result in $dp[i][k]$. In terms of calculation, we need to decide how many hours to divide the chocolate bar along the next dimension. Let's look at several ways to do this. It is possible for $O(k)$ to sort out the state to which we are moving, and from this calculate how many parts you need to divide the chocolate bar along the next dimension. - We get $O(n\\cdot k^2)$ It is possible for $O(k)$ to sort out the state to which we are moving, and from this calculate how many parts you need to divide the chocolate bar along the next dimension. - We get $O(n\\cdot k^2)$ It is possible for $O(A)$ to sort out how many parts we divide the chocolate bar along the next dimension. It is possible for $O(A)$ to sort out how many parts we divide the chocolate bar along the next dimension. Being in the state of $dp[i][j]$, you can iterate over $b_i$ - into how many parts to divide the chocolate until $j\\cdot b_i\\le k$. It can be shown that such a solution will work for $O(n\\cdot k\\cdot\\ln{k})$ Being in the state of $dp[i][j]$, you can iterate over $b_i$ - into how many parts to divide the chocolate until $j\\cdot b_i\\le k$. It can be shown that such a solution will work for $O(n\\cdot k\\cdot\\ln{k})$ The key idea suppose we need to divide a chocolate bar into $10$ parts, and along the first measurements we have already divided it into $5$ parts, or $6$ parts, or $7, 8$ or $9$ parts. All these states are not distinguishable for us, because in all these cases we need to divide the chocolate bar into at least $2$ parts. It remains to understand how many such <> states there are and learn how to store them. There are several approaches for this, let's analyze one of them: suppose we need to divide a chocolate bar into $10$ parts, and along the first measurements we have already divided it into $5$ parts, or $6$ parts, or $7, 8$ or $9$ parts. All these states are not distinguishable for us, because in all these cases we need to divide the chocolate bar into at least $2$ parts. It remains to understand how many such <> states there are and learn how to store them. There are several approaches for this, let's analyze one of them: we are interested in all the values of $\\lceil\\frac{k}{i}\\rceil$ for $i = 1, 2, \\ldots k$- this is how many parts the chocolate bar may still need to be divided into. Among them, only $O(\\sqrt{k})$different, since either $i\\le\\sqrt{k}$, or the value of $\\lceil\\frac{k}{i}\\rceil\\le\\sqrt{k}$ itself. If we make all these numbers states, and recalculate, iterating over the state to which to go, we get $O(n\\cdot\\sqrt{k} \\cdot\\sqrt{k}) = O(n\\cdot k)$- this is still not enough to solve the hollow problem. we are interested in all the values of $\\lceil\\frac{k}{i}\\rceil$ for $i = 1, 2, \\ldots k$- this is how many parts the chocolate bar may still need to be divided into. Among them, only $O(\\sqrt{k})$different, since either $i\\le\\sqrt{k}$, or the value of $\\lceil\\frac{k}{i}\\rceil\\le\\sqrt{k}$ itself. If we make all these numbers states, and recalculate, iterating over the state to which to go, we get $O(n\\cdot\\sqrt{k} \\cdot\\sqrt{k}) = O(n\\cdot k)$- this is still not enough to solve the hollow problem. Last observation If we are in the state of $dp[i][remain]$ where $remain = \\lceil\\frac{k}{i}\\rceil$ for some $i$, we will apply the same idea to it. From it, we are interested in transitions to the states $\\lceil \\frac{remain}{j} \\rceil$ for $j = 1, 2, \\ldots remain$. What kind of asymptotics will be obtained if we iterate over only interesting transitions? $n \\cdot (\\sum\\limits_{r=1}^{\\sqrt{k}}{ 2 \\cdot \\sqrt{r} + 2 \\cdot \\sqrt{\\lceil \\frac{k}{r} \\rceil}})$ it can be shown that this is $O(n\\cdot k^{3/4})$- which solves the problem",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 200;\nint a[MAXN];\n\nconst int MAXK = 1e7 + 100, MAXH = 1e4;\nint hsh[MAXK];\nint rev[MAXH];\n\ndouble dp[MAXN][MAXH];\n\nvector<array<int, 2>> go[MAXH];\n\nmain() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0); cout.tie(0);\n    int n, k;\n    cin >> n >> k;\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    int id = 0;\n    for (int c = 1;; ++id) {\n        rev[id] = (k + c - 1) / c;\n        hsh[(k + c - 1) / c] = id;\n        int t = (k + c - 1) / c - 1;\n        if (t == 0) break;\n        c = (k + t - 1) / t;\n    }\n    ++id;\n    dp[0][hsh[k]] = k;\n\n    for (int i = 0; i < id; ++i) {\n        int k = rev[i];\n        for (int c = 1;;) {\n            go[i].push_back({c, hsh[(k + c - 1) / c]});\n            int t = (k + c - 1) / c - 1;\n            if (t == 0) break;\n            c = (k + t - 1) / t;\n        }\n    }\n\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < id; ++j) {\n            double val = dp[i][j];\n            if (val == 0) continue;\n            for (auto elem : go[j]) {\n                int c = elem[0], k1 = elem[1];\n                if (c > a[i]) break;\n                int cur = a[i] / c;\n                dp[i + 1][k1] = max(dp[i + 1][k1], val * cur / a[i]);\n            }\n        }\n    }\n    cout << fixed << setprecision(20);\n    cout << dp[n][hsh[1]] << '\\n';\n    return 0;\n}\n",
    "tags": [
      "dp",
      "math",
      "meet-in-the-middle",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1801",
    "index": "G",
    "title": "A task for substrings",
    "statement": "Philip is very fond of tasks on the lines. He had already solved all the problems known to him, but this was not enough for him. Therefore, Philip decided to come up with his own task.To do this, he took the string $t$ and a set of $n$ strings $s_1$, $s_2$, $s_3$, ..., $s_n$. Philip has $m$ queries, in the $i$th of them, Philip wants to take a substring of the string $t$ from $l_i$th to $r_i$th character, and count the number of its substrings that match some string from the set. More formally, Philip wants to count the number of pairs of positions $a$, $b$, such that $l_i \\le a \\le b \\le r_i$, and the substring of the string $t$ from $a$th to $b$th character coincides with some string $s_j$ from the set.\n\nA substring of the string $t$ from $a$th to $b$th character is a string obtained from $t$ by removing the $a - 1$ character from the beginning and $|t| - b$ characters from the end, where $|t|$ denotes the length of the string $t$.\n\nPhilip has already solved this problem, but can you?",
    "tutorial": "Let's use the Aho-Korasik structure to store strings from $S$. Let's build compressed suffix links on it. This way it is a little more optimal to find all the lines from $S$ ending in this position $t$. Denote by $pref[i]$ the number of substrings of $S$ in the prefix $t$ of length $i$. Denote by $suf[i]$ the number of substrings of $S$ in the suffix $t$ starting from the position $i$. Note that $pref[r] + suf[l] - priv[|T|]$ is equal to the number of substrings of the string for $t$ from $S$ on the segment $[l, p]$ minus the number of substrings of $t$ from $S$ that begin before $l$ and end later than $r$. For each query, we will find a substring $t$ that matches $s_i$, which covers the string $t[l, r]$ and ends as close as possible to $r$. If there is no such thing, then the answer can be calculated using the previous formula. Otherwise, $t[l, r]$ is invested in $s_i[l', r']$. At the same time, there are no substrings of $S$ in the string $s_i$ that begin before $l'$ and end later than $r'$. To get the answer, we apply the previous formula with the string $s_i$ and the sub-section $[l', r']$. Asymptotics: $O(S+ t +m \\log m)$",
    "code": "#include <bits/stdc++.h>\n\n#define x first\n#define y second\n\nusing namespace std;\n\nstruct node {\n\tint nx[26];\n\tint p;\n\tint pp;\n\tint len;\n\tint id;\n\tint cnt;\n\tbool term;\n\n\tnode() : p(-1), pp(-1), len(0), id(-1), term(false), cnt(0) {\n\t\tfor (int i = 0; i < 26; i++) {\n\t\t\tnx[i] = -1;\n\t\t}\n\t}\n};\n\nvector<node> g;\n\nvector<string> s[2];\n\nstring t[2];\n\nvector<vector<long long>> c[2], pid[2];\n\nvector<long long> tc[2];\n\nint add(int a, char c) {\n\tc -= 'a';\n\tif (g[a].nx[c] == -1) {\n\t\tg[a].nx[c] = g.size();\n\t\tg.emplace_back();\n\t\tg.back().len = g[a].len + 1;\n\t}\n\treturn g[a].nx[c];\n}\n\nvoid build_aho(int a) {\n\tvector<pair<int, int>> q;\n\tfor (int i = 0; i < 26; i++) {\n\t\tif (g[a].nx[i] == -1) {\n\t\t\tg[a].nx[i] = a;\n\t\t} else {\n\t\t\tq.emplace_back(a, i);\n\t\t}\n\t}\n\n\tint qb = 0;\n\twhile (qb < q.size()) {\n\t\tint b = q[qb].x;\n\t\tint i = q[qb].y;\n\t\tqb++;\n\t\tint v = g[b].nx[i];\n\t\tint c = g[b].p;\n\n\t\tif (g[v].term) { // bug in c != -1\n\t\t\tg[v].cnt = 1;\n\t\t}\n\n\t\tif (c == -1) {\n\t\t\tg[v].p = a;\n\t\t\tg[b].pp = -1;\n\t\t} else {\n\t\t\tg[v].p = g[c].nx[i];\n\t\t\tif (g[v].term) {\n\t\t\t\tg[v].pp = v;\n\t\t\t} else {\n\t\t\t\tg[v].pp = g[g[v].p].pp;\n\t\t\t}\n\t\t\tg[v].cnt += g[g[v].p].cnt;\n\t\t}\n\n\t\tfor (int i = 0; i < 26; i++) {\n\t\t\tif (g[v].nx[i] == -1) {\n\t\t\t\tg[v].nx[i] = g[g[v].p].nx[i];\n\t\t\t} else {\n\t\t\t\tq.emplace_back(v, i);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvector<vector<pair<int, int>>> ts;\nvector<int> qlen;\npriority_queue<pair<int, int>> h;\nvector<long long> ans;\n\nlong long get_ans(int rdst, int len, vector<long long>& a, vector<long long>& b, bool substr) {\n\tint l = a.size() - 1 - rdst;\n\tint r = l + len;\n\tlong long cnt = a[r] + b[a.size() - 1 - l] - a.back();\n\tif (substr && l == 0 && r == a.size() - 1) {\n\t\tcnt++;\n\t}\n\n\treturn cnt;\n}\n\nint main() {\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\n\tint n, m;\n\tcin >> n >> m;\n\tg.emplace_back(); g.emplace_back();\n\ts[0].resize(n); s[1].resize(n);\n\tc[0].resize(n); c[1].resize(n);\n\tpid[0].resize(n); pid[1].resize(n);\n\tans.resize(m);\n\n\tcin >> t[0];\n\tt[1] = t[0];\n\treverse(t[1].begin(), t[1].end());\n\tts.resize(t[0].size());\n\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> s[0][i];\n\t}\n\tsort(s[0].begin(), s[0].end(), \\ \n\t[](const string& a, const string& b) { return a.size() < b.size(); });\n\n\tfor (int i = 0; i < n; i++) {\n\t\ts[1][i] = s[0][i];\n\t\treverse(s[1][i].begin(), s[1][i].end());\n\n\t\tfor (int e = 0; e < 2; e++) {\n\t\t\tint a = e;\n\t\t\tfor (auto j : s[e][i]) {\n\t\t\t\ta = add(a, j);\n\t\t\t}\n\t\t\tg[a].term = true;\n\t\t\tg[a].id = i;\n\t\t}\n\t}\n\n\tbuild_aho(0); build_aho(1);\n\n\tfor (int e = 0; e < 2; e++) {\n\t\ttc[e].resize(t[0].size() + 1);\n\n\t\tint a = e;\n\t\tfor (int i = 0; i < t[0].size(); i++) {\n\t\t\ta = g[a].nx[t[e][i] - 'a'];\n\t\t\ttc[e][i + 1] = tc[e][i] + g[a].cnt;\n\t\t}\n\t\tfor (int i = 0; i < n; i++) {;\n\t\t\tc[e][i].resize(s[0][i].size() + 1);\n\t\t\tpid[e][i].resize(s[0][i].size() + 1, -1);\n\n\t\t\tint a = e;\n\t\t\tfor (int j = 0; j < s[e][i].size(); j++) {\n\t\t\t\ta = g[a].nx[s[e][i][j] - 'a'];\n\t\t\t\tc[e][i][j + 1] = c[e][i][j] + g[a].cnt;\n\t\t\t\t\n\t\t\t\tif (g[a].term) { // bug always\n\t\t\t\t\tpid[e][i][j + 1] = g[a].id;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int j = (int)s[e][i].size() - 1; j >= 0; j--) { // bug forget\n\t\t\t\tif (pid[e][i][j] == -1) {\n\t\t\t\t\tpid[e][i][j] = pid[e][i][j + 1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tc[e][i].back()--; // bug forget string itself\n\t\t\t\n\t\t}\n\t}\n\n\tfor (int i = 0; i < m; i++) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\ta--;\n\t\tts[b - 1].emplace_back(a, i);\n\t\tqlen.emplace_back(b - a);\n\t}\n\n\tint a = 0;\n\tfor (int i = 0; i < t[0].size(); i++) {\n\t\t// cout << i << ' ' << t[0][i] << '\\n';\n\t\tfor (auto j : ts[i]) {\n\t\t\th.emplace(j);\n\t\t}\n\n\t\ta = g[a].nx[t[0][i] - 'a'];\n\n\t\tif (g[a].pp != -1) { // bug ignore\n\t\t\tint id = g[g[a].pp].id;\n\t\t\tint bg = i + 1 - (int)s[0][id].size();\n\t\t\twhile (h.size() > 0 && h.top().x >= bg) {\n\t\t\t\tint rdst = i - h.top().x + 1;\n\t\t\t\tint nid = pid[1][id][rdst]; // bug forget\n\n\t\t\t\t// cout << h.top().x << ' ' << h.top().y << ' ' << rdst << ' ' << nid << '\\n';\n\n\t\t\t\tans[h.top().y] = get_ans(rdst, qlen[h.top().y], \n\t\t\t\t    c[0][nid], c[1][nid], true);\n\t\t\t\th.pop();\n\t\t\t}\n\t\t}\n\t}\n\n\twhile (h.size() > 0) {\n\t\t// cout << h.top().x << ' ' << h.top().y << '\\n';\n\t\tans[h.top().y] = get_ans(t[0].size() - h.top().x, qlen[h.top().y], tc[0], tc[1], false);\n\t\th.pop();\n\t}\n\n\tfor (auto i : ans) {\n\t\tcout << i << ' ';\n\t}\n\tcout << '\\n';\n}",
    "tags": [
      "data structures",
      "string suffix structures",
      "strings"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1802",
    "index": "A",
    "title": "Likes",
    "statement": "Nikita recently held a very controversial round, after which his contribution changed very quickly.\n\nThe announcement hung on the main page for $n$ seconds. In the $i$th second $|a_i|$th person either liked or removed the like (Nikita was lucky in this task and there are no dislikes). If $a_i > 0$, then the $a_i$th person put a like. If $a_i < 0$, then the person $-a_i$ removed the like. \\textbf{Each person put and removed the like no more than once. A person could not remove a like if he had not put it before.}\n\nSince Nikita's contribution became very bad after the round, he wanted to analyze how his contribution changed while the announcement was on the main page. He turned to the creator of the platform with a request to give him the sequence $a_1, a_2, \\ldots, a_n$. But due to the imperfection of the platform, the sequence $a$ was shuffled.\n\nYou are given a shuffled sequence of $a$ that describes user activity. You need to tell for each moment from $1$ to $n$ what the maximum and minimum number of likes could be on the post at that moment.",
    "tutorial": "Let's show a construction that maximizes the number of likes. We need to first leave all the likes that we can put, and only then delete them. To minimize the number of likes, we need to delete the like (if we can) immediately after we post it. The code below implements these constructs.",
    "code": "#include \"bits/stdc++.h\"\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    int likes = 0, dislikes = 0;\n    for (int i = 0; i < n; i++) {\n        int x;\n        cin >> x;\n        if (x > 0) likes++;\n        else dislikes++;\n    }\n    for (int i = 1; i <= n; ++i) {\n        if (i <= likes) cout << i << ' ';\n        else cout << likes * 2 - i << ' ';\n    }\n    cout << '\\n';\n\n    for (int i = 1; i <= n; ++i) {\n        if (i <= dislikes * 2) cout << i % 2 << ' ';\n        else cout << (i - dislikes * 2) << ' ';\n    }\n    cout << '\\n';\n}\n\nsigned main() {\n    int t = 1;\n    cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve();\n    }\n    return 0;\n}\n",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1804",
    "index": "A",
    "title": "Lame King",
    "statement": "You are given a checkerboard of size $201 \\times 201$, i. e. it has $201$ rows and $201$ columns. The rows of this checkerboard are numbered from $-100$ to $100$ from bottom to top. The columns of this checkerboard are numbered from $-100$ to $100$ from left to right. The notation $(r, c)$ denotes the cell located in the $r$-th row and the $c$-th column.\n\nThere is a king piece at position $(0, 0)$ and it wants to get to position $(a, b)$ as soon as possible. In this problem our king is lame. Each second, the king makes exactly one of the following five moves.\n\n- Skip move. King's position remains unchanged.\n- Go up. If the current position of the king is $(r, c)$ he goes to position $(r + 1, c)$.\n- Go down. Position changes from $(r, c)$ to $(r - 1, c)$.\n- Go right. Position changes from $(r, c)$ to $(r, c + 1)$.\n- Go left. Position changes from $(r, c)$ to $(r, c - 1)$.\n\nKing is \\textbf{not allowed} to make moves that put him outside of the board. The important consequence of the king being lame is that he is \\textbf{not allowed} to make the same move during two consecutive seconds. For example, if the king goes right, the next second he can only skip, go up, down, or left.What is the minimum number of seconds the lame king needs to reach position $(a, b)$?",
    "tutorial": "Observation 1. Let $|a| = |b|$. The king can reach $(a, b)$ in $2 \\cdot |a|$ moves by alternating moves along rows and moves along columns. Observation 2. Let $|a| \\ne |b|$, in particular $a > b \\geq 0$ (without loss of generality due to the board symmetry). The king can reach $(a, b)$ in $2a - 1$ moves. He moves towards $a$ on turns $1, 3, 5, \\ldots, 2a - 1$. The remaining $a - 1$ moves are enough to reach $b$. Finally, the remaining slots can be filled with \"skip\" moves. Thus, the answer is $|a| + |b|$ if $|a| = |b|$ and $2 \\cdot \\max(|a|, |b|) - 1$ otherwise.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1804",
    "index": "B",
    "title": "Vaccination",
    "statement": "Ethan runs a vaccination station to help people combat the seasonal flu. He analyses the historical data in order to develop an optimal strategy for vaccine usage.\n\nConsider there are $n$ patients coming to the station on a particular day. The $i$-th patient comes at the moment $t_i$. We know that each of these patients can be asked to wait for no more than $w$ time moments. That means the $i$-th patient can get vaccine at moments $t_i, t_i + 1, \\ldots, t_i + w$.\n\nVaccines come in packs, each pack consists of $k$ doses. Each patient needs exactly one dose. Packs are stored in a special fridge. After a pack is taken out of the fridge and opened, it can no longer be put back. The lifetime of the vaccine outside the fridge is $d$ moments of time. Thus, if the pack was taken out of the fridge and opened at moment $x$, its doses can be used to vaccinate patients at moments $x, x + 1, \\ldots, x + d$. At moment $x + d + 1$ all the remaining unused doses of this pack are thrown away.\n\nAssume that the vaccination station has enough staff to conduct an arbitrary number of operations at every moment of time. What is the minimum number of vaccine packs required to vaccinate all $n$ patients?",
    "tutorial": "Observation 1. There exists an optimal answer where each pack of vaccine is used for a consecutive segment of patients. Indeed, if there are three patients $a < b < c$ such that $a$ and $c$ are vaccinated using the dose from one pack and $b$ is vaccinated using the dose from the other pack we can swap the packs used for $b$ and $c$ and the answer will still be valid. Observation 2. It always makes sense to ask new patients to wait as long as possible before opening a new pack. From these two observations we derive a very easy strategy. Consider patients one by one in order of non-decreasing $t_i$. If we consider some patient $i$ and there is an open pack that still valid and still has some doses remaining, use it immediately. If there is no valid open pack of vaccines and there is no one waiting, ask patient $i$ to wait till $t_i + w$ moment of time. If there is no valid pack of vaccines, but there is someone already waiting for moment $x$, ask patient $i$ to wait for moment $x$ as well. As a courtesy to our participants the values of $d$ and $w$ are limited by $10^6$ to avoid a potential overflow of a signed 32-bit integer type.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1804",
    "index": "C",
    "title": "Pull Your Luck",
    "statement": "While James is gone on business, Vesper takes her time and explores what the legendary Casino Royale has to offer to people who are fond of competitive programming.\n\nHer attention was grabbed by the very new \"Pull Your Luck\" roulette which functions in a pretty peculiar way. The roulette's wheel consists of $n$ sectors number from $0$ to $n - 1$. There is no ball and the winning sector is determined by a static arrow pointing to one of the sectors. Sectors' indexes go in the natural order and the wheel always spins in the direction of indexes increment. That means that sector $i + 1$ goes right after sector $i$ for all $i$ from $0$ to $n - 2$, and sector $0$ goes right after sector $n - 1$.\n\nAfter a bet is made, the player is allowed to pull the triggering handle herself and cause the wheel to spin. If the player's initial pull is made with the force equal to positive integer $f$, the wheel will spin for $f$ seconds. During the first second it will advance $f$ sectors, the next second it will advance $f - 1$ sectors, then $f - 2$ sectors, and so on until it comes to a complete stop. After the wheel comes to a complete stop, the sector which the arrow is pointing to is the winning one.\n\nThe roulette's arrow currently points at sector $x$. Vesper knows that she can pull the handle with any integer force from $1$ to $p$ inclusive. Note that it is not allowed to pull the handle with force $0$, i. e. not pull it all. The biggest prize is awarded if the winning sector is $0$. Now Vesper wonders if she can make sector $0$ win by pulling the triggering handle exactly once?",
    "tutorial": "Assuming the constraint on the the sum of $n$ over all test cases we might want to simulate the process for each test case. However, we need an $O(n)$ (or other quasilinear complexity) solution. The key observation is that the sum of all integers from $1$ to $2n$ inclusive is divisible by $n$. Indeed, $\\sum_{i = 1}^{2n} i = \\frac{(2n + 1) \\cdot 2n}{2} = (2n + 1) \\cdot n$. As the remainders of $x$ of modulo $n$ will repeat after $2n$ steps there is no point in trying values of $x$ for more than $\\min(2n, p)$. Question, can you build the test that required Vesper to use $x$ more than $100k$? There is exactly one such test.",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1804",
    "index": "D",
    "title": "Accommodation",
    "statement": "Annie is an amateur photographer. She likes to take pictures of giant residential buildings at night. She just took a picture of a huge rectangular building that can be seen as a table of $n \\times m$ windows. That means that the building has $n$ floors and each floor has exactly $m$ windows. Each window is either dark or bright, meaning there is light turned on in the room behind it.\n\nAnnies knows that each apartment in this building is either one-bedroom or two-bedroom. Each one-bedroom apartment has exactly one window representing it on the picture, and each two-bedroom apartment has exactly two \\textbf{consecutive} windows on the same floor. Moreover, the value of $m$ is guaranteed to be divisible by $4$ and it is known that each floor has exactly $\\frac{m}{4}$ two-bedroom apartments and exactly $\\frac{m}{2}$ one-bedroom apartments. The actual layout of apartments is unknown and can be different for each floor.\n\nAnnie considers an apartment to be occupied if \\textbf{at least one} of its windows is bright. She now wonders, what are the minimum and maximum possible number of occupied apartments if judged by the given picture?\n\nFormally, for each of the floors, she comes up with some particular apartments layout with exactly $\\frac{m}{4}$ two-bedroom apartments (two consecutive windows) and $\\frac{m}{2}$ one-bedroom apartments (single window). She then counts the total number of apartments that have at least one bright window. What is the minimum and maximum possible number she can get?",
    "tutorial": "The number of one-bedroom and two-bedroom apartments is the same for each floor and each floor can have its own independent apartments layout. Thus, we can independently solve the problem for each floor and then just sum the results. Below is given the solution for one floor in $O(m)$ time. First, lets introduce some variables. $B$ is the total number of bright windows. $D$ is the total number of dark windows. $O_0$ is the number of one-bedroom apartments that are not occupied ($0$ bright windows). $O_1$ is the number of one-bedroom apartments that are occupied ($1$ bright window). $T_0$ is the number of two-bedroom apartments that are not occupied ($0$ bright windows). $T_1$ is the number of two-bedroom apartments that are occupied and have $1$ bright window. $T_2$ is the number of two-bedroom apartments that are occupied and have $2$ bright windows. $A$ is the total number of occupied apartments. We know that $A = O_1 + T_1 + T_2$ and $B = O_1 + T_1 + 2 \\cdot T_2$. Thus, $A = B - T_2$, so in order to minimize the number of occupied apartments we need to maximize $T_2$ and vice versa. Maximizing $T_2$ is easier, you just determine the length of all maximal segments of bright windows, denote these lengths as $l_0, l_1, l_2, \\ldots, l_x$. Then you pack each segment with as many two-bedroom apartments as possible. So, the maximum possible value of $T_2 = \\min(\\sum_{i = 0}^{x} \\lfloor \\frac{l_i}{2} \\rfloor, \\frac{m}{4}$. Here we must note the importance of having exactly $\\frac{m}{4}$ two-bedroom apartments and exactly $\\frac{m}{2}$ one-bedroom apartments. If the actual number of apartments of each type was given in the input we won't be able to guarantee the value of $T_2$ defined above. It could be the case that it is not actually possible to place all the remaining apartments and close the gaps between the placement of two-bedroom apartments with two bright windows. However, as we have $\\frac{m}{2}$ one-bedroom apartments we can guarantee that such a placement is always possible. Now we would like to minimize $T_2$. Actually, we will do it in exactly the same way as the maximization, but instead of taking maximal segments of bright windows, we will find and use maximal segments that have at least one dark window and do not have two consecutive bright windows. Denote the lengths of such maximal segments as $l'_0, l'_1, l'_2, \\ldots, l'_y$. Then, the minimum possible $T_2 = \\min(0, \\frac{m}{4} - \\sum_{i=0}^{y} \\lfloor \\frac{l'_i}{2} \\rfloor)$. Again, thanks to $\\frac{m}{2}$ one-bedroom apartments we will be able to fill all the gaps and achieve the desired placement.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1804",
    "index": "E",
    "title": "Routing",
    "statement": "Ada operates a network that consists of $n$ servers and $m$ direct connections between them. Each direct connection between a pair of distinct servers allows bidirectional transmission of information between these two servers. Ada knows that these $m$ direct connections allow to directly or indirectly transmit information between any two servers in this network. We say that server $v$ is a neighbor of server $u$ if there exists a direct connection between these two servers.\n\nAda needs to configure her network's WRP (Weird Routing Protocol). For each server $u$ she needs to select exactly one of its neighbors as an auxiliary server $a(u)$. After all $a(u)$ are set, routing works as follows. Suppose server $u$ wants to find a path to server $v$ (different from $u$).\n\n- Server $u$ checks all of its direct connections to other servers. If it sees a direct connection with server $v$, it knows the path and the process terminates.\n- If the path was not found at the first step, server $u$ asks its auxiliary server $a(u)$ to find the path.\n- Auxiliary server $a(u)$ follows this process starting from the first step.\n- After $a(u)$ finds the path, it returns it to $u$. Then server $u$ constructs the resulting path as the direct connection between $u$ and $a(u)$ plus the path from $a(u)$ to $v$.\n\nAs you can see, this procedure either produces a correct path and finishes or keeps running forever. Thus, it is critically important for Ada to configure her network's WRP properly.\n\nYour goal is to assign an auxiliary server $a(u)$ for each server $u$ in the given network. Your assignment should make it possible to construct a path from any server $u$ to any other server $v$ using the aforementioned procedure. Or you should report that such an assignment doesn't exist.",
    "tutorial": "A directed graph where each node has an out-degree equal to $1$ (exactly one arc starts at this node) is called functional. By setting auxiliary servers $a(v)$ for each server $v$ we define a functional graph. The following condition is necessary and sufficient. The answer exists if and only if there exists a functional graph defined by $a(v)$ that contains a cycle $C$ such that $N_G(C) = V(G)$. That means that each node should be neighbouring to at least one node of this cycle in the original graph. Note that cycles of length $1$ are not allowed as $a(v) \\ne v$ by definition. The proof is easy. If such a cycle $C$ exists we can reconstruct all other $a(v)$ to lead to this cycle. This will allow WRP to construct a path to each server after the procedure gets to the cycle. If such a cycle doesn't exists, we can pick any node of any cycle (functional graph always has at least one) and some servers will be unreachable from it. Wow we need to find a cycle of length $\\geq 2$ such that each server belongs to this cycle or is directly connected to at least one server of the cycle. First we run a dynamic programming similar to Hamiltonian path and identify all the subsets of servers that can form a cycle. This will take $O(2^n \\cdot n^2)$ if we use the following meaning of $d(m, v)$. $d(m, v) = 0$ if there exists a path that starts from node $u$, visits all nodes of a subset defined by bitmask $m$ and ends in node $v$. Here node $u$ is the node with minimum index in subset $m$, as you can always pick the minimum-indexed node as the beginning of the cycle. After we compute $d(m, v)$ we take all $m$ such that there exists $d(m, v) = 1$ and check whether $N_G(m) = V(G)$. This can be done in $O(2^n \\cdot n^2)$ as well. Thus, the overall complexity is $O(2^n \\cdot n^2)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1804",
    "index": "F",
    "title": "Approximate Diameter",
    "statement": "Jack has a graph of $n$ vertices and $m$ edges. All edges are bidirectional and of unit length. The graph is connected, i. e. there exists a path between any two of its vertices. There can be more than one edge connecting the same pair of vertices. The graph can contain self-loops, i. e. edges connecting a node to itself.\n\nThe distance between vertices $u$ and $v$ is denoted as $\\rho(u, v)$ and equals the minimum possible number of edges on a path between $u$ and $v$. The diameter of graph $G$ is defined as the maximum possible distance between some pair of its vertices. We denote it as $d(G)$. In other words, $$d(G) = \\max_{1 \\le u, v \\le n}{\\rho(u, v)}.$$\n\nJack plans to consecutively apply $q$ updates to his graph. Each update adds exactly one edge to the graph. Denote as $G_i$ the graph after exactly $i$ updates are made. Jack wants to calculate $q + 1$ values $d(G_0), d(G_1), d(G_2), \\ldots, d(G_q)$.\n\nHowever, Jack suspects that finding the exact diameters of $q + 1$ graphs might be a difficult task, so he is fine with approximate answers that differ from the correct answers no more than twice. Formally, Jack wants to find a sequence of positive integers $a_0, a_1, a_2, \\ldots, a_q$ such that $$\\left\\lceil \\frac{d(G_i)}{2} \\right\\rceil \\le a_i \\le 2 \\cdot d(G_i)$$ for each $i$.\n\n\\textbf{Hacks}\n\nYou cannot make hacks in this problem.",
    "tutorial": "Let's recall some definitions to start with. $\\rho_G(u, v)$ is the length of the shortest path between vertices $u$ and $v$ in graph $G$. Define as $c_G(u)$ the maximum distance from vertex $u$ to some other vertex of graph $G$. $c_G(u) = \\max_{v \\in V(G)} \\rho(u, v)$. $d(G) = \\max_{u, v \\in V(G)} \\rho(u, v) = \\max_{u \\in V(G)} c_G(u)$ is called the diameter of graph $G$. It is the maximum distance between some pair of vertices of graph $G$. $r(G) = \\min_{u \\in V(G)} \\max_{v \\in V(G)} \\rho(u, v) = \\min_{u \\in V(G)} c(u)$ is called the radius of graph $G$. It is the minimum possible distance from one vertex of the graph to the farthest from it vertex of this graph. The key inequality we will use for this problem solution is the following. Let $v$ be arbitrary vertex of graph $G$. $\\frac{d(G)}{2} \\leq r(G) \\leq c_G(v) \\leq d(G) \\leq 2 \\cdot r(G) \\leq 2 \\cdot c_G(v) \\leq 2 \\cdot d(G)$ $r(G) \\leq c_G(v) \\leq d(G)$ by definition. $d(G) \\leq 2 \\cdot r(G)$ because of triangle inequality. All other inequalities are derived from the first two items. The good thing is that we can compute $c_G(v)$ in linear time using BFS algorithm. Now we can solve the problem in $O(q \\cdot (n + m + q))$ time. It is important to note that the task tolerates errors both ways, so any value between $c_{G_i}(v)$ and $2 \\cdot c_{G_i}(v)$ will be a correct approximation of $d(G_i)$. The next key observation is that the sequence of $d_i(G)$ is non-increasing. If $i < j$ and $c_{G_i}(v) \\leq 2 \\cdot c_{G_j}(v)$ we can use $2 \\cdot c_{G_j}(v)$ as an approximation for $d(G_{i + 1}), d(G_{i + 2}), \\ldots, d(G_{j - 1})$. Using the idea above we can do one of the following. Having the correct value of $c_{G_i}(v)$ we can use the binary search to find the maximum $j$ such that $c_{G_i}(v) \\leq 2 \\cdot c_{G_j}(v)$ in $\\log{q}$ iterations. Use divide&conquer with the stop condition $c_{G_l}(v) \\leq 2 \\cdot c_{G_r}(v)$. That would actually work a way more faster (up to five times) as it re-uses the information very efficiently. Thus, we have a solion that runs BFS no more than $\\log{n} \\cdot \\log{q}$ times. The overall complexity is $O(\\log{n} \\cdot \\log{q} \\cdot (n + m + q))$. How did we get the correct answers for the checker? We precomputed them using the power of distributed computing. We are a cloud technology company after all! Bonus question, can you guess the total number of cpu-days we have used to compute all the answers? Post you version in the comments!",
    "tags": [
      "binary search",
      "divide and conquer",
      "graphs",
      "shortest paths"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1804",
    "index": "G",
    "title": "Flow Control",
    "statement": "Raj has a single physical network line that connects his office to the Internet. This line bandwidth is $b$ bytes per millisecond.\n\nThere are $n$ users who would like to use this network line to transmit some data. The $i$-th of them will use the line from millisecond $s_i$ to millisecond $f_i$ inclusive. His initial data rate will be set to $d_i$. That means he will use data rate equal to $d_i$ for millisecond $s_i$, and then it will change according to the procedure described below.\n\nThe flow control will happen as follows. Suppose there are $m$ users trying to transmit some data via the given network line during millisecond $x$. Denote as $t_i$ the data rate that the $i$-th of these $m$ users has at the beginning of this millisecond. All $t_i$ are non-negative integer values.\n\n- If $m = 0$, i. e. there are no users trying to transmit data during this millisecond, nothing happens.\n- If the sum of all $t_i$ is less than or equal to $b$, each active user successfully completes his transmission (the $i$-th active user transmits $t_i$ bytes). After that, the data rate of each active user grows by $1$, i. e. each $t_i$ is increased by $1$.\n- If the sum of all $t_i$ is greater than $b$, the congestion occurs and no data transmissions succeed this millisecond at all. If that happens, each $t_i$ decreases twice, i. e. each $t_i$ is replaced with $\\lfloor \\frac{t_i}{2} \\rfloor$.\n\nRaj knows all the values $n$, $b$, $s_i$, $f_i$, and $d_i$, he wants to calculate the total number of bytes transmitted by all the users in the aggregate.",
    "tutorial": "The problem is inspired by AIMD algorithm for TCP flow and congestion control. The key solution idea comes from a real-world networking, every time the congestion happens the difference between the maximum active $t_i$ and the minimum active $t_i$ halves. Thus, if all users were to start and to stop at the same time there will be no more than two distinct values of $t_i$ in just $\\log C$ congestions. Here $C$ stands for the upper limit on values $d_i$ and $b$. Let's store all the unique values of active $t_i$ in a hash-map together with a supplementary information. Information we need is the sum of all $t_i$ right after the last congestion, the number of milliseconds past since the last congestion and so on. Using this information we can compute the time of the next congestion in $O(1)$. The processing of one congestion will work in $O(d)$ time where $d$ is the current number of distinct values of $t_i$. We also need to be able to merge two groups when congestion happens, this information will be used to process delete operations. That can be done using DSU with path compression and doesn't add much to the total complexity. We will call the period between two consecutive congestions an epoch. There are epochs of two types: general and repetitive. A repetitive epoch is an epoch that goes in exactly the same way as the previous epoch. That means no new users appear, no users turn off, the epoch starts with exactly the same values of $t_i$ as the previous epoch and gets to exactly the same state after the closest congestion happens. All other epochs are called general. Though the total number of epochs can be large (up to $\\max(f_i)$), there will be no more than $n \\log{C}$ general epochs. Indeed, if no users start or finish data transmission, the process will converge to a repetitive epoch in no more than $\\log{C}$ congestions. Here, $C$ is the upper bound for $b$ and values $d_i$. Repetitive epochs contain no more than two distinct value of $t_i$, they can be identified and simulated efficiently. How do we simulate general epochs? There is no need to this efficiently, doing this in $O(d)$ ($d$ is the number of distinct $t_i$) will be efficient enough. One can prove this using amortized analysis with the following potential function. Let $d$ be the number of distinct values of $t_i$ and $t_0 < t_1 < \\ldots < t_{d - 1}$ be the sequence of these values. $P(epoch) = d + \\sum_{i = 0}^{d - 2} \\log{(t_{i + 1} - t_i)}$. The total complexity is $O(n \\log C + n \\log n)$.",
    "tags": [
      "data structures",
      "dsu",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1804",
    "index": "H",
    "title": "Code Lock",
    "statement": "Lara has a safe that is locked with a circle-shaped code lock that consists of a rotating arrow, a static circumference around the arrow, an input screen, and an input button.\n\nThe circumference of the lock is split into $k$ equal sections numbered from $1$ to $k$ in clockwise order. Arrow always points to one of the sections. Each section is marked with one of the first $k$ letters of the English alphabet. No two sections are marked with the same letter.\n\nDue to the lock limitations, the safe's password is a string of length $n$ that consists of first $k$ letters of the English alphabet only. Lara enters the password by rotating the lock's arrow and pressing the input button. Initially, the lock's arrow points to section $1$ and the input screen is empty. In one second she can do one of the following actions.\n\n- Rotate the arrow one section clockwise. If the arrow was pointing at section $x < k$ it will now point at section $x + 1$. If the arrow was pointing at section $k$ it will now point at section $1$.\n- Rotate the arrow one section counter-clockwise. If the arrow was pointing at section $x > 1$ it will now point at section $x - 1$. If the arrow was pointing at section $1$ it will now point at section $k$.\n- Press the input button. The letter marked on the section that the arrow points to will be added to the content of the input screen.\n\nAs soon as the content of the input screen matches the password, the safe will open. Lara always enters her password in the minimum possible time.Lara has recently found out that the safe can be re-programmed. She can take the first $k$ letters of the English alphabet and assign them to the sectors in any order she likes. Now she wants to re-arrange the letters in a way that will minimize the number of seconds it takes her to input the password. Compute this minimum number of seconds and the number of ways to assign letters, for which this minimum number of seconds is achieved.\n\nTwo ways to assign letters to sectors are considered to be distinct if there exists at least one sector $i$ that is assigned different letters.",
    "tutorial": "First, let's solve the task for the case of linear arrangement of letters instead of a circle. Then we will upgrade the solution. Let $c(x, y)$ be the number of positions $i$ of the password string $s$ such that $s_i = x$ and $s_{i + 1} = y$. In other words, $c(x, y)$ is the number of times Lara has to enter letter $y$ after entering letter $x$. We need to find any permutation of letters $p_0, p_1, p_2, \\ldots, p_{k-1}$ of minimum cost. Integer $p_i$ stands for the index of the letter that will be placed at position $i$. The cost of a permutation is computed as $w(p) = \\sum_{0 \\leq i, j < k, i \\ne j} c(p_i, p_j) \\cdot |i - j|$. Pointwise weights are much more convenient to use rather than pairwise weights. Re-write the cost function as follows. $w(p) = \\sum_{0 \\leq i, j < k, i \\ne j} c(p_i, p_j) \\cdot |i - j| = \\sum_{0 \\leq i < j < k} (c(p_i, p_j) + c(p_j, p_i)) \\cdot (j - i) = \\sum_{i = 0}^{i < k} i \\cdot (\\sum_{j = 0}^{j < i} (c(p_j, p_i) + c(p_i, p_j)) - \\sum_{j = i + 1}^{j < k} (c(p_j, p_i) + c(p_i, p_j)))$ Usage of pointwise weights allows us to obtain the permutation step by step from left to right. When we place the new element $x$ we only need to know the subset of all already placed elements and the optimal cost of the prefix. Define $d(mask)$ as the minimum total cost of a permutation prefix containing first $|mask|$ elements. The update function looks as follows. $d(mask) = \\min_{x \\in mask} (d(mask - x) + |mask| \\cdot (\\sum_{y \\in mask, y \\ne x} (c(y, x) + c(x, y)) - \\sum_{y \\not\\in mask} (c(y, x) + c(x, y))))$ The above solution works in $O(2^n \\cdot n)$. However, in can be updated to $O(2^n \\cdot n)$ with some precomputations of the sums in the formula above. Now we need to learn how to apply the similar idea for a positioning on a circle. The cost function now looks as follows. $w(p) = \\sum_{0 \\leq i, j < k, i \\ne j} c(p_i, p_j) \\cdot \\min(|i - j|, k - |i - j|) = \\sum_{i = 0}^{k - 1} pw(p, i)$ In order to write the cost function using pointwise weights we need to distinguish between two halves. The pointwise cost of an element in the first half is: $pw(p, i) = i \\cdot \\sum_{j = 0}^{j < i} (c(p_i, p_j) + c(p_j, p_i)) - i \\cdot \\sum_{j = i + 1}^{j \\leq i + \\lfloor \\frac{k}{2} \\rfloor} (c(p_i, p_j) + c(p_j, p_i)) + (i + n) \\cdot \\sum_{j = i + \\lfloor \\frac{k}{2} \\rfloor + 1}^{k - 1} (c(p_i, p_j) + c(p_j, p_i))$ Similarly, the poinwise cost of an element in the second half is: $pw(p, i) = -i \\cdot \\sum_{j = 0}^{j < i - \\lfloor \\frac{k}{2} \\rfloor} (c(p_i, p_j) + c(p_j, p_i)) + i \\cdot \\sum_{j = i - \\lfloor \\frac{k}{2} \\rfloor}^{j < i} (c(p_i, p_j) + c(p_j, p_i)) - i \\cdot \\sum_{j = i + 1}^{k - 1} (c(p_i, p_j) + c(p_j, p_i))$ The above formulas show that it makes sense to first split all elements in two parts: left and right halves of the circle. Then we will alternate steps in adding one element to the first unoccupied position of the left part, then to the first unoccupied position of the right part. This way we will always be able to compute the value of a pointwise cost function. So we compute the dynamic programming $d(S, M)$, where $S$ is the subset identifying the way to split the set of all letters in two equal (or almost equal for the case of odd size) parts, and $M$ is the subset of already added elements. Elements $S \\cap M$ are placed at the beginning of the first half and elements $\\overline{S} \\cap M$ are placed at the beginning of the second half. The simpliest complexity estimation is $O(4^n \\cdot n)$. However, we should consider the following optimizations. We only use $|S| = \\lceil \\frac{k}{2} \\rceil$. We only use states such that $|S \\cap M| = |\\overline{S} \\cap M|$ or $|S \\cap M| = |\\overline{S} \\cap M| + 1$. The character $s_0$ is always located at the first sector of the code lock, so Lara doesn't have to make any moves to enter the first character of her password. Thus, we only consider $s_0 \\in S$ and $s_0 \\in M$. Considering all the above optimizations we end up with only $82818450 \\approx 83 \\cdot 10^6$ states. The problem statement asks you to compute the number of permutations as well. That doesn't add anything to the difficulty of this dynamic programming solution and is just used to cut away all the heuristic optimizations like annealing simulation.",
    "tags": [
      "bitmasks",
      "dp"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1805",
    "index": "A",
    "title": "We Need the Zero",
    "statement": "There is an array $a$ consisting of non-negative integers. You can choose an integer $x$ and denote $b_i=a_i \\oplus x$ for all $1 \\le i \\le n$, where $\\oplus$ denotes the bitwise XOR operation. Is it possible to choose such a number $x$ that the value of the expression $b_1 \\oplus b_2 \\oplus \\ldots \\oplus b_n$ equals $0$?\n\nIt can be shown that if a valid number $x$ exists, then there also exists $x$ such that ($0 \\le x < 2^8$).",
    "tutorial": "Note that $(a_1 \\oplus x) \\oplus (a_2 \\oplus x) \\oplus ...$ equals $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n$ if $n$ is even, or $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n \\oplus x$ if $n$ is odd. Then, if the length of the array is odd, you must print $\\oplus$ of the whole array. And if the length is even, we can't change the value of the expression with our operation. It turns out that if $\\oplus$ of the whole array is $0$, we can output any number, but otherwise there is no answer.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    xor = 0\n    for x in a:\n        xor ^= x\n    if xor == 0:\n        print(0)\n    else:\n        if n % 2 == 1:\n            print(xor)\n        else:\n            print(-1)",
    "tags": [
      "bitmasks",
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "1805",
    "index": "B",
    "title": "The String Has a Target",
    "statement": "You are given a string $s$. You can apply this operation to the string exactly once: choose index $i$ and move character $s_i$ to the beginning of the string (removing it at the old position). For example, if you apply the operation with index $i=4$ to the string \"abaacd\" with numbering from $1$, you get the string \"aabacd\". What is the lexicographically minimal$^{\\dagger}$ string you can obtain by this operation?\n\n$^{\\dagger}$A string $a$ is lexicographically smaller than a string $b$ of the same length if and only if the following holds:\n\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "At first, note that the operation should be applied only to the position of the minimal element of the string (since the 1st position in the final string should always contain the minimal letter). Next, let the positions of the minimum letter are $a_1, a_2, \\ldots, a_k$. Then we must apply the operation to the last position ($a_k$). Indeed, let us apply the operation to another occurrence: then the prefixes will coincide, and after that there will be a character that is equal to the minimal one if we applied the operation to $a_k$ and will not be equal to it otherwise, which contradicts the minimal string.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    s = input()\n    ind = s.rfind(min(s))  # Find the last ind such that s[ind] = min(s)\n    print(s[ind] + s[:ind] + s[ind + 1:])",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1805",
    "index": "C",
    "title": "Place for a Selfie",
    "statement": "The universe is a coordinate plane. There are $n$ space highways, each of which is a straight line $y=kx$ passing through the origin $(0, 0)$. Also, there are $m$ asteroid belts on the plane, which we represent as open upwards parabolas, i. e. graphs of functions $y=ax^2+bx+c$, where $a > 0$.\n\nYou want to photograph each parabola. To do this, for each parabola you need to choose a line that does not intersect this parabola and does not touch it. You can select the same line for different parabolas. Please find such a line for each parabola, or determine that there is no such line.",
    "tutorial": "Let's find the answers for the parabolas one at a time. Suppose we are given a parabola $ax^2+bx+c$ and a line $kx$. Then their difference is the parabola $ax^2+(b-k)x+c$. In order for the line and the parabola not to intersect, the difference must never equal $0$, that is, the parabola $ax^2+(b-k)x+c$ must have no roots. And this is true only when the discriminant is less than $0$, that is, $(b-k)^2<4ac$. In this case, $a, b$ and $c$ are given to us, and we need to choose $k$. $(b-k)^2<4ac \\Longrightarrow |b - k| < \\sqrt{4ac} \\Longrightarrow b - \\sqrt{4ac} < k < b+\\sqrt{4ac}$. Now let us have a list of straight line coefficients sorted in increasing order. We need to check if there is a coefficient that belongs to $[b - \\sqrt{4ac}; b + \\sqrt{4ac}]$. To do this, check the smallest number greater than $b$, and the largest number less than $b$. If one of these numbers satisfies the condition, then we have found the answer. If not, then there are definitely no suitable coefficients, because we took $2$ closest coefficients to the center of the segment. Note that in this solution, we don't need to use non-integer numbers, which is good for both the time and the absence of errors due to precision.",
    "code": "#include <bits/stdc++.h>\n#define int long long\n\nusing namespace std;\n\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector <int> lines(n);\n    for (int i = 0; i < n; i++) {\n        cin >> lines[i];\n    }\n    sort(lines.begin(), lines.end());\n\n    for (int i = 0; i < m; i++) {\n        int a, b, c;\n        cin >> a >> b >> c;\n\n        int ind = lower_bound(lines.begin(), lines.end(), b) - lines.begin();\n        if (ind < n && (lines[ind] - b) * (lines[ind] - b) < 4 * a * c) {\n            cout << \"YES\\n\" << lines[ind] << \"\\n\";\n            continue;\n        }\n        if (ind > 0 && (lines[ind - 1] - b) * (lines[ind - 1] - b) < 4 * a * c) {\n            cout << \"YES\\n\" << lines[ind - 1] << \"\\n\";\n            continue;\n        }\n        cout << \"NO\\n\";\n    }\n}\n\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int q = 1;\n    cin >> q;\n    while (q--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "geometry",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1805",
    "index": "D",
    "title": "A Wide, Wide Graph",
    "statement": "You are given a tree (a connected graph without cycles) with $n$ vertices.\n\nConsider a fixed integer $k$. Then, the graph $G_k$ is an undirected graph with $n$ vertices, where an edge between vertices $u$ and $v$ exists if and only if the distance between vertices $u$ and $v$ in the given tree is \\textbf{at least} $k$.\n\nFor each $k$ from $1$ to $n$, print the number of connected components in the graph $G_k$.",
    "tutorial": "Find the diameter (the longest path) in the original tree. Now if the number $k$ is greater than the length of the diameter, then there will be no edges in the graph. Otherwise, the ends of this diameter are connected to each other, and possibly to other vertices as well. Then we can pre-calculate the answer for each $k$ in descending order. Let's maintain the set of vertices already reachable. Then for updating the answer for $k=x$ only vertices at a distance $x$ from one end of the diameter can be added to the answer.",
    "code": "#include <bits/stdc++.h>\n\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\nusing namespace std;\n\nconst int N = 1e5 + 228;\n\nvector<int> G[N];\n\nvoid dfs(int v, int par, int h, vector<int> &d) {\n    d[v] = h;\n    for (int i : G[v]) {\n        if (i != par) {\n            dfs(i, v, h + 1, d);\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    int n;\n    cin >> n;\n    for (int i = 0; i < n - 1; ++i) {\n        int a, b;\n        cin >> a >> b;\n        G[a - 1].push_back(b - 1);\n        G[b - 1].push_back(a - 1);\n    }\n\n    vector<int> d1(n), d2(n);\n    dfs(0, -1, 0, d1);\n    int a = max_element(all(d1)) - d1.begin();\n    dfs(a, -1, 0, d1);\n    int b = max_element(all(d1)) - d1.begin();\n    dfs(b, -1, 0, d2);\n    for (int i = 0; i < n; ++i) {\n        d2[i] = max(d2[i], d1[i]);\n    }\n    sort(all(d2));\n    int ans = 0;\n    for (int i = 1; i <= n; ++i) {\n        while (ans < n && d2[ans] < i) {\n            ++ans;\n        }\n        cout << min(n, ans + 1) << ' ';\n    }\n    cout << '\\n';\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1805",
    "index": "E",
    "title": "There Should Be a Lot of Maximums",
    "statement": "You are given a tree (a connected graph without cycles). Each vertex of the tree contains an integer. Let's define the $\\mathrm{MAD}$ (maximum double) parameter of the tree as the maximum integer that occurs in the vertices of the tree \\textbf{at least} $2$ times. If no number occurs in the tree more than once, then we assume $\\mathrm{MAD}=0$.\n\nNote that if you remove an edge from the tree, it splits into two trees. Let's compute the $\\mathrm{MAD}$ parameters of the two trees and take the maximum of the two values. Let the result be the value of the deleted edge.\n\nFor each edge, find its value. Note that we don't actually delete any edges from the tree, the values are to be found independently.",
    "tutorial": "First, find $MAD$ of the initial tree. If each number in the tree occurs no more than once, then for each query the answer is $0$. Then, if $MAD$ occurs at least $3$ times in the tree, then for each query the answer will be $MAD$, because by pigeonhole principle there will be at least $2$ $MAD$ in one of the two trees. At last, in the case where $MAD$ occurs exactly $2$ times in the tree: if the deleted edge is not on the path between two occurrences of $MAD$, then the answer - $MAD$ of the whole tree. And for edges between entries, you need to maintain sets of values in each tree and traverse the edges, changing the sets accordingly.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nconst int N = 2e5 + 100;\nvector <pair <int, int>> g[N];\nint val[N];\n\nvector <int> ans;\nmap <int, int> cnt1, cnt2;\nset <int> mad1, mad2;\n\nvector <int> path, path_ind;\nbool used[N];\n\n\nbool dfs(int v, int tar) {\n    used[v] = true;\n    path.push_back(v);\n    if (v == tar) {\n        return true;\n    }\n    for (auto [i, ind] : g[v]) {\n        if (!used[i]) {\n            path_ind.push_back(ind);\n            if (dfs(i, tar)) {\n                return true;\n            }\n            path_ind.pop_back();\n        }\n    }\n    path.pop_back();\n    return false;\n}\n\n\nint mad() {\n    int mx = 0;\n    if (!mad1.empty()) {\n        mx = max(mx, *mad1.rbegin());\n    }\n    if (!mad2.empty()) {\n        mx = max(mx, *mad2.rbegin());\n    }\n    return mx;\n}\n\n\nvoid recalc(int v, int ban1, int ban2) {\n    cnt1[val[v]]++;\n    if (cnt1[val[v]] == 2) {\n        mad1.insert(val[v]);\n    }\n    cnt2[val[v]]--;\n    if (cnt2[val[v]] == 1) {\n        mad2.erase(val[v]);\n    }\n    for (auto [i, _] : g[v]) {\n        if (i != ban1 && i != ban2) {\n            recalc(i, v, -1);\n        }\n    }\n}\n\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int n;\n    cin >> n;\n    for (int i = 0; i < n - 1; i++) {\n        int a, b;\n        cin >> a >> b;\n        a--, b--;\n        g[a].emplace_back(b, i);\n        g[b].emplace_back(a, i);\n    }\n\n    map <int, vector <int>> ind;\n    for (int i = 0; i < n; i++) {\n        cin >> val[i];\n        ind[val[i]].push_back(i);\n        cnt2[val[i]]++;\n        if (cnt2[val[i]] == 2) {\n            mad2.insert(val[i]);\n        }\n    }\n\n    while (!ind.empty() && ind.rbegin() -> second.size() == 1) {\n        ind.erase(prev(ind.end()));\n    }\n    if (ind.empty()) {\n        for (int i = 0; i < n - 1; i++) {\n            cout << \"0\\n\";\n        }\n        return 0;\n    } else if (ind.rbegin()->second.size() > 2) {\n        for (int i = 0; i < n - 1; i++) {\n            cout << ind.rbegin() -> first << \"\\n\";\n        }\n        return 0;\n    }\n\n    int a = ind.rbegin()->second[0], b = ind.rbegin()->second[1];\n    dfs(a, b);\n\n    ans.assign(n - 1, ind.rbegin() -> first);\n    recalc(path[0], path[1], -1);\n    ans[path_ind[0]] = mad();\n\n    for (int i = 1; i + 1 < path.size(); i++) {\n        recalc(path[i], path[i - 1], path[i + 1]);\n        ans[path_ind[i]] = mad();\n    }\n\n    for (int i : ans) {\n        cout << i << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "trees",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1805",
    "index": "F2",
    "title": "Survival of the Weakest (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. It differs from the easy one only in constraints on $n$. You can make hacks only if you lock both versions.}\n\nLet $a_1, a_2, \\ldots, a_n$ be an array of non-negative integers. Let $F(a_1, a_2, \\ldots, a_n)$ be the sorted in the non-decreasing order array of $n - 1$ smallest numbers of the form $a_i + a_j$, where $1 \\le i < j \\le n$. In other words, $F(a_1, a_2, \\ldots, a_n)$ is the sorted in the non-decreasing order array of $n - 1$ smallest sums of all possible pairs of elements of the array $a_1, a_2, \\ldots, a_n$. For example, $F(1, 2, 5, 7) = [1 + 2, 1 + 5, 2 + 5] = [3, 6, 7]$.\n\nYou are given an array of non-negative integers $a_1, a_2, \\ldots, a_n$. Determine the single element of the array $\\underbrace{F(F(F\\ldots F}_{n-1}(a_1, a_2, \\ldots, a_n)\\ldots))$. Since the answer can be quite large, output it modulo $10^9+7$.",
    "tutorial": "Firstly, we will sort the array $a_1, a_2, \\ldots, a_n$, and in the future we will always assume that all arrays in this problem are sorted. Let's solve the problem for $n \\leq 200$. It may seem that with such constraints, the problem is solved quite trivially: we implement the function $F$ for $\\mathcal{O}(n^2 \\log n)$, and run it $n - 1$ times to get an answer. But there is one nuance, with each iteration of $F$, the numbers in the array can increase by $2$ times (for example, if the array consists entirely of identical numbers), which means that after only $40$ operations, we may have an overflow. Note that it is impossible to take the numbers by modulo in the function $F$ itself, since then the sorted order will be lost, and it will be impossible (or very difficult) to restore it using the remainder when dividing by $10^9 + 7$ instead of the numbers themselves. To avoid this, we note an important property of the function $F$: $F([a_1, a_2, \\ldots, a_n]) = F([a_1 - x, a_2 - x, \\ldots, a_n - x]) + x \\cdot 2^{n-1}$ The intuition of this property is that if you subtract the same number from all the elements, then the relative order of the elements will not change, and will not change when using the $F$ function. Just after the first iteration of $F$, $2x$ will be subtracted from all the numbers, then $4x$, $8x$, etc., in the end, the original answer will be minus $x\\cdot 2^{n-1}$. This property can be proved more strictly by induction on $n$. What does this wonderful property give us? Now we can subtract the same number $x$ from all the elements by first adding $x \\cdot 2^{n-1}$ to the answer. It would be logical enough in any situation to subtract the minimum of the array from all its elements. Thanks to this, the minimum of the array will always be $0$, and now we can work only with arrays whose minimum element is $0$, which greatly simplifies our life. This is one of the two key ideas in this problem. So let's notice something interesting about the array $F([0, a_1, a_2, \\ldots, a_n])$. Observation: $(F([0, a_1, a_2, \\ldots, a_n]))_1 = a_1$. The proof is obvious (let me remind you that the array is sorted). Observation: $(F([0, a_1, a_2, \\ldots, a_n]))_n \\leq a_n$. Proof: since $[0, a_1, a_2, \\ldots, a_n]$ has length $n + 1$, $F([0, a_1, a_2, \\ldots, a_n])$ has length $n$. Among all pairs of array elements $[0, a_1, a_2, \\ldots, a_n]$ there are $n$ pairs of the form $0 + a_i$, and $a_1 \\leq a_2 \\leq \\ldots \\leq a_n$. This means that the original array has $n$ pairs in which the sum is $\\leq a_n$. So, observation is proved. These two observations give us that $F([0, a_1, a_2, \\ldots, a_n]) = [a_1, \\ldots, \\leq a_n]$. And after subtracting the minimum $(a_1)$ $\\rightarrow [0, \\ldots, \\leq a_n - a_1]$. Thus, if we always subtract the minimum, each time after applying the $F$ function, the maximum in the array will be not increase. Which allows us to work only with arrays of numbers from $0$ to $10^9$, where there naturally can be no problems with overflow. So, we got the solution for $\\mathcal{O}(n^3 \\log n)$. Let's improve it to $\\mathcal{O}(n^2 \\log n)$. The cornerstone in our previous solution is that we implement the function $F$ for $\\mathcal{O}(n^2 \\log n)$, which is pretty slow. Let's learn how to implement it for $\\mathcal{O}(n \\log n)$. This is a fairly standard problem. Note that if some pair of the form $a_i + a_j$ is included in the array $F([a_1, a_2, \\ldots, a_n])$, then all pairs $a_i + a_{i+1}, a_i + a_{i+2}, \\ldots, a_i + a_{j-1}$ will also be included in the array $F([a_1, a_2, \\ldots, a_n])$, since the sum in these pairs is no more than $a_i + a_j$. We will build the array $F([a_1, a_2, \\ldots, a_n])$ one element at a time, starting with the smallest. Let's denote the array in which we will add these numbers for $B$, initially $B$ is empty. For each index $i$, we will store the minimum index $j_i > i$ such that the pair $a_i + a_j$ is still not taken in $B$. Initially, $j_i = i+1$. We will mantain all numbers of the form $a_i + a_{j_i}$ in std::priority_queue. Then to add the next element to $B$, we will remove the minimum element from the queue, then increase the corresponding $j_i$ by one and add the element $a_i + a_{j_i}$ to the queue again. After $n - 1$ of such iteration we will get $F([a_1, a_2, \\ldots, a_n])$. Each iteration takes $\\mathcal{O}(\\log n)$, which means that the asymptotics of finding the function $F$ is $\\mathcal{O}(n \\log n)$. In total, we learned how to solve the problem in $\\mathcal{O}(n^2 \\log n)$. Now we move on to the full solution, for $n \\leq 2 \\cdot 10^5$. First we will show what the solution looks like and intuition behind it, and a more strict proof will be at the end. Let's ask ourselves: when does the last element of the array $0, a_1, a_2, \\ldots, a_n$ affect the answer to the problem? Very often we will lose any mention of the $a_n$ element after the first transition: $[0, a_1, \\ldots, a_n] \\rightarrow F([0, a_1, \\ldots, a_n])$. The minimum sum of a pair of elements including $a_n$ is $0 + a_n$. And there is an $n - 1$ pair with not bigger sum: $0 + a_1$, $0 + a_2$, ..., $0 + a_{n-1}$. So the only case when $a_n$ will enter the array $F([0, a_1, \\ldots, a_n])$ is if $a_1 + a_2 \\geq a_n$, because otherwise the pair $a_1 + a_2$ will be less than $0 + a_n$, and there will be $n$ pairs with a sum less than $a_n$ - $n-1$ pairs of the form $0 + a_i$ and the pair $a_1 + a_2$. Well, let's assume it really happened that $a_1 + a_2 \\geq a_n$. Then $F([0, a_1, \\ldots, a_n]) = [0 + a_1, 0 + a_2, \\ldots, 0 + a_n]$. After subtracting the minimum: $[0, a_2 - a_1, a_3 - a_1, \\ldots, a_n - a_1]$. If we run $F$ on this array again, we get: $[a_2 - a_1, \\ldots, \\le a_n - a_1]$. After subtracting the minimum: $[0, \\ldots, \\le a_n - a_2]$. But remember that $a_1 + a_2 \\geq a_n$. Which means $2 \\cdot a_2 \\geq a_n$. Which means $a_n - a_2 \\leq \\frac{a_n}{2}$. It turns out that if $a_n$ somehow remains in the array after two applications of the $F$ functions, then the last element of the array will be reduced by at least half! This means that after just $2 \\cdot \\log_2{a_n}$ iterations of the $F$ function, either the $a_n$ element will be completely evicted from the array, or the array will shrink into $[0, 0, \\ldots, 0]$! In both cases, the original element $a_n$ in no way will be taken into account in the final answer. In no way! The total number of times when the maximum is halved is no more than $\\log_2{a_n}$, which means intuitively it is approximately clear that elements with indexes greater than $2 \\cdot \\log_2{a_n}$ will not affect the answer in any way. Therefore, the full solution would be to leave the first $K = 64$ elements of the array $a$. (a little more than $2 \\cdot \\log_2{10^9}$). Then apply the function $F$ to this array $n - K$ times, but writing out $K$ minimal elements, not $K - 1$. After that, the length of the real array will also be equal to $K$, and it remains only to run the function $F$ $K - 1$ times to get the final answer. Final asymptotics: $\\mathcal{O}(n \\cdot (K \\log K))$, where $K = 2 \\log_2{a_n} + 2 \\leq 64$. Now let's give a strict proof that this solution works. We are following $K$ minimal elements -$[0, a_1, \\ldots, a_{K-1}]$. Technically, there are also $[a_K, \\ldots, a_{len}]$ elements in the array. But we have no information about their values. However, we know that all these elements are $\\geq a_{K-1}$ since we maintain sorted order. This means that the minimum sum of a pair of elements about which we have no information is also $\\geq a_{K-1}$. The whole proof is based on this simple observation. Firstly, it is not difficult to understand that $K$ minimum elements are exactly enough to recalculate $K - 1$ minimum element in $F(a)$. Since we have pairs of elements $0 + a_1$, $0 + a_2$, ..., $0 + a_{K-1}$. And the sum in each of these pairs is no more than $a_{K-1}$, which means no more than the sum in any pair about which we have no information. Therefore, in any incomprehensible situation, we can recalculate with the loss of one of the elements. Let's see when it is possible to recalculate all $K$ minimal elements. Again, the minimum element about which we have no information from $[0, a_1, \\ldots, a_{K-1}]$ is $0 + a_K \\geq 0 + a_{K-1}$. So if we find $K$ elements that $\\leq a_{K-1}$, then we can recalculate $K$ minimal elements of $F(a)$ through $K$ minimal elements of $a$. We have a $K - 1$ pair of the form $0 + a_i$, as well as a pair $a_1 + a_2$. So if $a_1 + a_2 < a_{K-1}$, then we can recalculate all $K$ minimal elements. And if recalculation is not possible, then $a_1 + a_2 \\geq a_{K-1}$ is executed. Then, having encountered such a situation, we will recalculate twice with the loss of the last element, thus reducing $K$ by $2$. After such a recalculation, the last element will be at least half as small as it was before (this is part of the main tutorial). So after $2 \\log_2(A)$ of such element removals, the array will slide into $[0, 0, \\ldots, 0]$ and everything is clear. And if the number of removals is less than $2 \\log_2(A)$, then one of the $K$ elements will certainly live to the end, and will be the answer to the problem. Thus, the correctness of the solution has been successfully proved. Bonus for those who are still alive: find a more accurate estimate for $K$ and build a test on which this solution, but keeping track of the $K - 1$ minimum element (one less than necessary), will give the wrong answer.",
    "code": "#include <bits/stdc++.h>\n#define all(x) x.begin(), (x).end()\n\nusing namespace std;\n\nconst int M = 1000000007;\nlong long ans = 0;\nint real_len = 0;\n\n\nlong long binpow(long long a, int x) {\n    long long ans0 = 1;\n    while (x) {\n        if (x % 2) {\n            ans0 *= a;\n            ans0 %= M;\n        }\n        a *= a;\n        a %= M;\n        x /= 2;\n    }\n    return ans0;\n}\n\n\nvoid chill(vector<int> &b) {\n    int mn = b[0];\n    ans += (int) ((long long) mn * binpow(2, real_len - 1) % M);\n    if (ans >= M) {\n        ans -= M;\n    }\n    for (auto &x : b) {\n        x -= mn;\n    }\n}\n\n\nvoid F(vector<int> &b, int sub = 0) {\n    --real_len;\n    vector<int> cnd;\n    for (int i = 0; i < b.size(); i++) {\n        for (int j = i + 1; j < b.size(); j++) {\n            if (i * j >= b.size()) break;\n            cnd.push_back(b[i] + b[j]);\n        }\n    }\n    sort(all(cnd));\n    vector<int> b2((int) b.size() - sub);\n    for (int i = 0; i < (int) b.size() - sub; i++) {\n        b2[i] = cnd[i];\n    }\n    chill(b2);\n    b = b2;\n}\n\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    sort(all(a));\n    int L = 64;\n    vector<int> b(min(n, L));\n    for (int i = 0; i < min(n, L); i++) {\n        b[i] = a[i];\n    }\n    real_len = n;\n    chill(b);\n    while (b.size() < real_len) {\n        if (b[1] + b[2] > b.back()) {\n            F(b, 1);\n            F(b, 1);\n        } else {\n            F(b);\n        }\n    }\n    while (real_len > 1) {\n        F(b, 1);\n    }\n    ans += b[0];\n    ans %= M;\n    cout << ans << '\\n';\n}",
    "tags": [
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1806",
    "index": "A",
    "title": "Walking Master",
    "statement": "YunQian is standing on an infinite plane with the Cartesian coordinate system on it. In one move, she can move to the diagonally adjacent point on the top right or the adjacent point on the left.\n\nThat is, if she is standing on point $(x,y)$, she can either move to point $(x+1,y+1)$ or point $(x-1,y)$.\n\nYunQian initially stands at point $(a,b)$ and wants to move to point $(c,d)$. Find the minimum number of moves she needs to make or declare that it is impossible.",
    "tutorial": "Hint 1: The value of $b$ is always non-decreasing, and the value of $a-b$ is always non-increasing. It is possible to move from $(a,b)$ to $(c,d)$ if and only if $d\\ge b$ and $a-b\\ge c-d$, since the value of $b$ is always non-decreasing and the value of $a-b$ is always non-increasing. If it is possible, the answer is $(d-b)+((a+d-b)-c)$. One possible way is $(a,b)\\to (a+d-b,d)\\to (c,d)$. Another way to understand this: $(a,b)\\to (a+d-b,d)\\to (c,d)$ is always a valid path if it is possible to move from $(a,b)$ to $(c,d)$. So first let $a\\leftarrow a+(d-b)$ and $b\\leftarrow d$, then the answer only depends on $a$ and $c$.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\n#define fir first\n#define sec second\n#define pii pair<int,int>\nusing namespace std;\n\nconst int maxn=500005;\nconst int inf=0x3f3f3f3f;\n\nsigned main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tint T;\n\tcin>>T;\n\twhile(T--) {\n\t\tint a,b,c,d;\n\t\tcin>>a>>b>>c>>d;\n\t\tif(b<=d&&c<=a+d-b) {\n\t\t\tcout<<(d-b)+(a+d-b-c)<<\"\\n\";\n\t\t} else {\n\t\t\tcout<<\"-1\\n\";\n\t\t}\n\t}\n}",
    "tags": [
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1806",
    "index": "B",
    "title": "Mex Master",
    "statement": "You are given an array $a$ of length $n$. The score of $a$ is the MEX$^{\\dagger}$ of $[a_1+a_2,a_2+a_3,\\ldots,a_{n-1}+a_n]$. Find the minimum score of $a$ if you are allowed to rearrange elements of $a$ in any order. Note that you are \\textbf{not required} to construct the array $a$ that achieves the minimum score.\n\n$^{\\dagger}$ The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$ because $0$, $1$, $2$, and $3$ belong to the array, but $4$ does not.",
    "tutorial": "Hint 1: $ans\\le 2$. First, let's determine if $ans$ can be $0$. That means we can't place two $0$s next to each other. This is achievable when the number of $0$s is not greater than $\\lceil\\frac{n}{2}\\rceil$. Then determine if $ans$ can be $1$. That means we can't place $0$ and $1$ next to each other. Therefore, if there is no $1$ in $a$ or there exist an element $x\\ge 2$ in $a$, we can simply rearrange $a$ as $[0,0,\\ldots,0,x,1,1,\\ldots]$ to make $ans=1$. The last case:there are only $0$ and $1$ in $a$ and the number of $0$s is greater than $\\lceil\\frac{n}{2}\\rceil$. We want to make $ans=2$ which is the minimum. Since the number of $1$s is not greater than the number of $0$s, we can rearrange $a$ as $[0,1,0,1,\\ldots,0,1,0,0,\\ldots]$ to make $ans=2$.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\n#define fir first\n#define sec second\n#define pii pair<int,int>\nusing namespace std;\n\nconst int maxn=200005;\nconst int inf=0x3f3f3f3f;\n\nsigned main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tint T;\n\tcin>>T;\n\twhile(T--) {\n\t\tint n;\n\t\tcin>>n;\n\t\tint sum0=0;\n\t\tbool f=false;\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\tint x;\n\t\t\tcin>>x;\n\t\t\tif(x==0) {\n\t\t\t\tsum0++;\n\t\t\t} else if(x>=2) {\n\t\t\t\tf=true;\n\t\t\t}\n\t\t}\n\t\tif(sum0<=(n+1)/2) {\n\t\t\tcout<<\"0\\n\";\n\t\t} else if(f||sum0==n) {\n\t\t\tcout<<\"1\\n\";\n\t\t} else {\n\t\t\tcout<<\"2\\n\";\n\t\t}\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1806",
    "index": "C",
    "title": "Sequence Master",
    "statement": "For some positive integer $m$, YunQian considers an array $q$ of $2m$ (possibly negative) integers good, if and only if for every possible subsequence of $q$ that has length $m$, the product of the $m$ elements in the subsequence is equal to the sum of the $m$ elements that are \\textbf{not} in the subsequence. Formally, let $U=\\{1,2,\\ldots,2m\\}$. For all sets $S \\subseteq U$ such that $|S|=m$, $\\prod\\limits_{i \\in S} q_i = \\sum\\limits_{i \\in U \\setminus S} q_i$.\n\nDefine the distance between two arrays $a$ and $b$ both of length $k$ to be $\\sum\\limits_{i=1}^k|a_i-b_i|$.\n\nYou are given a positive integer $n$ and an array $p$ of $2n$ integers.\n\nFind the minimum distance between $p$ and $q$ over all good arrays $q$ of length $2n$. It can be shown for all positive integers $n$, at least one good array exists. Note that you are \\textbf{not required} to construct the array $q$ that achieves this minimum distance.",
    "tutorial": "Hint 1: The number of good sequences is small. Hint 2: Consider two cases: all elements in $q$ are (not) equal. In case that all elements in $q$ are equal, we have $q_1^n=nq_1$. The integer solutions to this equation is $q_1=0$, $n=1$ or $(q_1,n)=(2,2)$. In the other case, we can see that the constraints are strong, so let's list some equations to find good sequences, using the property that not all elements are equal. Let $q$ be such a good sequence. WLOG $q_1\\neq q_2$. Then we have: $q_1\\cdot q_3q_4\\cdots q_{n+1}=q_2+q_{n+2}+q_{n+3}+\\cdots+q_{2n}\\tag{1}$ $q_2\\cdot q_3q_4\\cdots q_{n+1}=q_1+q_{n+2}+q_{n+3}+\\cdots+q_{2n}\\tag{2}$ Substract $(2)$ from $(1)$: $(q_1-q_2)q_3q_4\\cdots q_{n+1}=q_2-q_1\\\\ \\iff (q_1-q_2)(q_3q_4\\cdots q_{n+1}+1)=0$ Since $q_1-q_2\\neq 0$, there must be $q_3q_4\\cdots q_{n+1}=-1$. Similarly, for each exactly $n-1$ numbers in $q_3,q_4,\\cdots,q_{2n}$, their product will be $-1$, which leads to $q_3=q_4=\\cdots =q_{2n}$. Therefore, we have $q_3^{n-1}=-1$, which leads to $2\\mid n$ and $q_3=q_4=\\cdots=q_{2n}=-1$. Bringing it back to $(1)$, we have $q_1+q_2=n-1$. Since $q_1q_2\\cdots q_n=q_{n+1}+\\cdots q_{2n}$, we know $q_1q_2=-n$. The only solution is $\\{q_1,q_2\\}=\\{-1,n\\}$. Q.E.D. Back to the problem. For the first case, it is easy to calculate the distance. For the second case, let $S=\\sum_{i=1}^n |q_i-(-1)|$, the answer is $\\min_{1\\le j\\le n}\\{S-|q_j-(-1)|+|q_j-n|\\}$.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\n#define fir first\n#define sec second\n#define pii pair<int,int>\nusing namespace std;\n\nconst int maxn=400005;\nconst ll inf=0x3f3f3f3f3f3f3f3f;\n\nll a[maxn];\n\nsigned main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tint T;\n\tcin>>T;\n\twhile(T--) {\n\t\tint n;\n\t\tcin>>n;\n\t\tll ans=0,sum=0;\n\t\tfor(int i=1;i<=n*2;i++) {\n\t\t\tcin>>a[i];\n\t\t\tans+=abs(a[i]);\n\t\t\tsum+=abs(a[i]-(-1));\n\t\t}\n\t\tif(n==1) {\n\t\t\tans=min(ans,abs(a[1]-a[2]));\n\t\t}\n\t\tif(n==2) {\n\t\t\tans=min(ans,abs(a[1]-2)+abs(a[2]-2)+abs(a[3]-2)+abs(a[4]-2));\n\t\t}\n\t\tif(n%2==0) {\n\t\t\tfor(int i=1;i<=n*2;i++) {\n\t\t\t\tans=min(ans,sum-abs(a[i]-(-1))+abs(a[i]-n));\n\t\t\t}\n\t\t}\n\t\tcout<<ans<<\"\\n\";\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1806",
    "index": "D",
    "title": "DSU Master",
    "statement": "You are given an integer $n$ and an array $a$ of length $n-1$ whose elements are either $0$ or $1$.\n\nLet us define the value of a permutation$^\\dagger$ $p$ of length $m-1$ ($m \\leq n$) by the following process.\n\nLet $G$ be a graph of $m$ vertices labeled from $1$ to $m$ that does not contain any edges. For each $i$ from $1$ to $m-1$, perform the following operations:\n\n- define $u$ and $v$ as the (unique) vertices in the weakly connected components$^\\ddagger$ containing vertices $p_i$ and $p_i+1$ respectively with only incoming edges$^{\\dagger\\dagger}$;\n- in graph $G$, add a directed edge from vertex $v$ to $u$ if $a_{p_i}=0$, otherwise add a directed edge from vertex $u$ to $v$ (if $a_{p_i}=1$).\n\nNote that after each step, it can be proven that each weakly connected component of $G$ has a unique vertex with only incoming edges.Then, the value of $p$ is the number of incoming edges of vertex $1$ of $G$.\n\nFor each $k$ from $1$ to $n-1$, find the sum of values of all $k!$ permutations of length $k$. Since this value can be big, you are only required to compute this value under modulo $998\\,244\\,353$.\n\n\\begin{center}\n{\\small Operations when $n=3$, $a=[0,1]$ and $p=[1,2]$}\n\\end{center}\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^\\ddagger$ The weakly connected components of a directed graph is the same as the components of the undirected version of the graph. Formally, for directed graph $G$, define a graph $H$ where for all edges $a \\to b$ in $G$, you add an undirected edge $a \\leftrightarrow b$ in $H$. Then the weakly connected components of $G$ are the components of $H$.\n\n$^{\\dagger\\dagger}$ Note that a vertex that has no edges is considered to have only incoming edges.",
    "tutorial": "We record an operation of adding edge as $(i,i+1,a_i)$. Hint 1: Only operation $(i,i+1,0)$ can contribute. Hint 2: Using dynamic programming, let $f_i$ denote the number of ways to let vertices $1\\sim i$ form a tree with root $1$, considering only the first $i-1$ operations. We can observe: Only operation $(i,i+1,0)$ can contribute. If vertices $1\\sim i$ have already formed a tree with root $1$, then operation $(i,i+1,0)$ can contribute. Using dynamic programming, let $f_i$ denote the number of ways to let vertices $1\\sim i$ form a tree with root $1$, considering only the first $i-1$ operations. For $f$, we have $f_1=1$ and $f_{i+1}=f_i\\cdot (i-a_i)$. Explanation: Consider inserting the operation $(i,i+1,a_i)$ in the sequence of the first $i-1$ operations. If $a_i=0$, no matter where it is inserted, it will always form a tree with root $1$, so $f_{i+1}=f_i\\cdot i$. If $a_i=1$, only inserting at the end is invalid, so $f_{i+1}=f_i\\cdot (i-1)$. This is because, if you insert $(i,i+1,1)$ at the end of the operations, we will add a edge from $1$ to $i+1$, which won't form a tree of root $1$. For computing the answer, we have $ans_i=i\\cdot ans_{i-1}+[a_i=0]f_{i}$. Explanation: $i\\cdot ans_{i-1}$ represents the contribution of previous $i-1$ operations. No matter where operation $(i,i+1,a_i)$ is inserted, the contribution of previous $i-1$ operations won't change. $[a_i=0]f_{i}$ means the contribution of operation $(i,i+1,a_i)$.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\n#define fir first\n#define sec second\n#define pii pair<int,int>\nusing namespace std;\n \nconst int maxn=500005;\nconst int inf=0x3f3f3f3f;\nconst int mod=998244353;\n\nint a[maxn];\nint f[maxn];\n\nsigned main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tint T;\n\tcin>>T;\n\twhile(T--) {\n\t\tint n;\n\t\tcin>>n;\n\t\tfor(int i=1;i<=n-1;i++) {\n\t\t\tcin>>a[i];\n\t\t}\n\t\tf[1]=1;\n\t\tfor(int i=1;i<=n-1;i++) {\n\t\t\tf[i+1]=1ll*f[i]*(i-a[i])%mod;\n\t\t}\n\t\tint ans=0;\n\t\tfor(int i=1;i<=n-1;i++) {\n\t\t\tans=(1ll*ans*i+(!a[i])*f[i])%mod;\n\t\t\tcout<<ans<<\" \";\n\t\t}\n\t\tcout<<\"\\n\";\n\t}\n}",
    "tags": [
      "combinatorics",
      "dp",
      "dsu",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1806",
    "index": "E",
    "title": "Tree Master",
    "statement": "You are given a tree with $n$ weighted vertices labeled from $1$ to $n$ rooted at vertex $1$. The parent of vertex $i$ is $p_i$ and the weight of vertex $i$ is $a_i$. For convenience, define $p_1=0$.\n\nFor two vertices $x$ and $y$ \\textbf{of the same depth$^\\dagger$}, define $f(x,y)$ as follows:\n\n- Initialize $\\mathrm{ans}=0$.\n- While both $x$ and $y$ are not $0$:\n\n- $\\mathrm{ans}\\leftarrow \\mathrm{ans}+a_x\\cdot a_y$;\n- $x\\leftarrow p_x$;\n- $y\\leftarrow p_y$.\n\n- $f(x,y)$ is the value of $\\mathrm{ans}$.\n\nYou will process $q$ queries. In the $i$-th query, you are given two integers $x_i$ and $y_i$ and you need to calculate $f(x_i,y_i)$.\n\n$^\\dagger$ The depth of vertex $v$ is the number of edges on the unique simple path from the root of the tree to vertex $v$.",
    "tutorial": "Hint 1: The time complexity of the solution is $O(n\\sqrt{n})$. Hint 2: Brute force with something to store the answer. The solution turns out quite easy: just store the answer to each pair of $(x,y)$ when computing the answer by climbing up on the tree. If we see the time complexity of hash table as $O(1)$, then the time complexity and memory complexity are both $O(n\\sqrt{n})$. Let's prove it. We will see $n=q$ in the following proof. It is clear that the above solution's time complexity depends on the number of different pairs $(x,y)$ which we encounter when climbing. Assume the $i$-th depth of the tree has $s_i$ nodes, then its contribution to things above is $\\min(s_i^2,n)$. It's easy to discover that when $s_i>\\sqrt{n}$, the contribution of it will equal to the contribution when $s_i=\\sqrt{n}$. So, making all $s_i$ not greater than $\\sqrt{n}$ will contribute more. Therefore, the time complexity is $O(\\sum_{i=1}^k s_i^2)$. When $s_i=\\sqrt{n}$, the formula above has a maximum value of $n\\sqrt{n}$, because $(a+b)^2\\ge a^2+b^2$. In fact, we don't need to use hash table in this problem. If there exists a pair of $(x,y)$ of depth $i$ such that $s_i> \\sqrt{n}$, then we don't need to store $(x,y)$. Since the amount of $i$ such that $s_i>\\sqrt{n}$ are not greater than $\\sqrt{n}$, the time complexity won't change. For other pairs of $(x,y)$ we can simply store them in an array, then the memory complexity won't change.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\n#define fir first\n#define sec second\n#define pii pair<int,int>\nusing namespace std;\n\nconst int maxn=100005;\nconst int sqrtn=325;\nconst int B=320;\nconst int inf=0x3f3f3f3f;\n\nint n,q;\nint a[maxn];\nint h[maxn];\nint fa[maxn];\nint cnt[maxn];\nint depth[maxn];\nll f[maxn][sqrtn];\nvector<int> tree[maxn]; \n\nvoid dfs(int x,int d) {\n\th[x]=++cnt[d],depth[x]=d;\n\tfor(int to:tree[x]) {\n\t\tdfs(to,d+1);\n\t}\n}\n\nll ask(int x,int y) {\n\tif(!x&&!y) {\n\t\treturn 0;\n\t}\n\tif(cnt[depth[y]]<=B&&f[x][h[y]]) {\n\t\treturn f[x][h[y]];\n\t}\n\tll ans=ask(fa[x],fa[y])+1ll*a[x]*a[y];\n\tif(cnt[depth[y]]<=B) {\n\t\tf[x][h[y]]=ans;\n\t}\n\treturn ans;\n}\n\nsigned main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tcin>>n>>q;\n\tfor(int i=1;i<=n;i++) {\n\t\tcin>>a[i];\n\t}\n\tfor(int i=2;i<=n;i++) {\n\t\tcin>>fa[i];\n\t\ttree[fa[i]].push_back(i);\n\t}\n\tdfs(1,0);\n\twhile(q--) {\n\t\tint x,y;\n\t\tcin>>x>>y;\n\t\tcout<<ask(x,y)<<\"\\n\";\n\t}\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1806",
    "index": "F2",
    "title": "GCD Master (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $m$. You can make hacks only if both versions of the problem are solved.}\n\nYou are given an array $a$ of length $n$ and two integers $m$ and $k$. Each element in $a$ satisfies $1\\le a_i \\le m$.\n\nIn one operation, you choose two indices $i$ and $j$ such that $1 \\le i < j \\le |a|$, then append $\\gcd(a_i,a_j)$ to the back of the array and delete $a_i$ and $a_j$ from the array. Note that the length of the array decreases by one after this operation.\n\nFind the maximum possible sum of the array after performing \\textbf{exactly} $k$ operations.",
    "tutorial": "Hint 1: There is a easy strategy for dealing with repeated elements. Suppose that all elements in $a$ are pairwise distinct in the following hints. Hint 2: We will always perform an operation on the minimum element. Hint 3: The best way is to choose $k+1$ elements, delete them, and add the gcd of them to the sequence. Hint 4: After sorting the sequence, you may guess that choosing a prefix is optimal. But actually it is wrong. Try fixing the strategy! Solution for F1: First, suppose that all elements in $a$ are pairwise distinct. The problem can be rewritten as: Divide the sequence into $n-k$ groups to maximize the sum of the gcd of each group. Let $S_i$ represent the elements of a group. Lemma $1$: When $k>0$, the group which the minimum element of the original sequence belongs to satisfies $|S_a|>1$. Proof: If $|S_a|=1$, we can find a group $S_x$ such that $|S_x|>1$. Then replacing the maximum element of $S_x$ with the minimum element of the original sequence makes the answer greater. Let $a$ be the minimum of the sequence and $b$ be the maximum of $S_x$. the original answer is $a+\\gcd(S_x)$. replacing the maximum element of $S_x$ with the minimum element, the answer is $b+\\gcd(S_x \\setminus \\{b\\}\\cup\\{a\\}) >b$. $\\gcd(S_x) \\le \\max{S_x} - \\min S_x = b-\\min S_x < b-a$, so $a+\\gcd(S_x)< a+b-a=b<b+\\gcd(S_x \\setminus \\{b\\}\\cup\\{a\\})$. Q.E.D. Tips: When $\\max S_x = \\min S_x$, $\\gcd(S_x) \\not\\le \\max{S_x} - \\min S_x$. That's why all elements in $a$ need to be pairwise distinct. Lemma $2$: When $k>0$, there's only one $S_x$ such that $|S_x| >1$ . Proof: Let $S_a$ be the group with the minimum element. Referring to Lemma $1$, we know $|S_a| >1$. Then we remove all the elements of $S_a$ from the sequence, add $\\gcd({S_a})$ to the sequence and subtract $|S_a| - 1$ from $k$. It's obvious that $\\gcd(S_a)$ is the minimum element of the newly formed sequence. We can continue the process until $k=0$, which tells us that only $|S_a|=k+1>1$. Q.E.D. We can enumerate $\\gcd(S_a)$ to solve it in $O(n+m\\ln m)$ so far. How about repeated elements? We can find that for those repeated elements, the best strategy is to merge them with the same element. In other word, a repeated element $x$ only decreases the answer by $x$. So it's independent of the previous part. We just need to enumerate the number of operations we perform for repeated elements. Solution for F2: Still suppose that all elements in $a$ are pairwise distinct. Suppose $a$ is sorted. Lemma $3$: When $k>0$, we will choose the first $k$ elements, and an element from the remaining elements. That is, $S=\\{a_1,a_2,\\ldots,a_k,a_x\\}$, where $k < x \\le n$, is the only group with more than one element. Proof: Suppose $T=\\{a_1,a_2,\\ldots, a_{p}, a_{c_1}, a_{c_2}, \\ldots, a_{c_t}\\}$, where $p+1<c_1<c_2<\\cdots<c_t$, $t\\ge 2$ and $p+t=k+1$. Then we can prove that $T'=\\{a_1,a_2,\\ldots, a_{p},a_{p+1}, a_{c_1}, a_{c_2}, \\ldots, a_{c_{t-1}}\\}$ is always a better choice. Let $g=\\gcd(T)$ and $g'=\\gcd(T')$. We have $a_{c_t}-a_{p+1}> a_{c_t}-a_{c_{t-1}}\\ge g$. $\\Delta=ans(T')-ans(T)=a_{c_t}-a_{p+1}+g'-g> g'>0$. So repeating the process, finally we will know that $S=\\{a_1,a_2,\\ldots,a_k,a_x\\}$, where $k < x \\le n$. Q.E.D. When there're repeated elements, we need to calculate the answer for $k$ prefixes. Note that there're only $O(\\log m)$ different prefix gcd. So we can do it in $O(n \\log^2 m)$ (another $O(\\log m)$ comes from calculating gcd). Let $g_i$ be the prefix gcd. When finding the best pair, we calculate $\\gcd(g_i,a_j)$, which leads to $O(n \\log^2 m)$. $g_i\\mid g_{i-1}$, so $\\gcd(g_i,a_j)=\\gcd(g_i,\\gcd(g_{i-1},a_j))$. The gcd is non-increasing so the total complexity is $O(n \\log m)$.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\n#define int128 __int128\n#define fir first\n#define sec second\n#define pii pair<int,int>\nusing namespace std;\n\nconst int maxn=1000005;\nconst ll inf=9e18;\nconst int128 inf128=(int128)(inf)*(int128)(inf);\n\nll a[maxn];\nll b[maxn];\nll g[maxn];\nll ra[maxn];\nint128 suma[maxn];\nint128 sumb[maxn];\nint128 ans[maxn];\n\nll gcd(ll x,ll y) {\n\treturn !y?x:gcd(y,x%y);\n}\n\nvoid print(int128 x) {\n\tif(!x) {\n\t\treturn ;\n\t}\n\tprint(x/10);\n\tcout<<(int)(x%10);\n}\n\nsigned main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tint T;\n\tcin>>T;\n\twhile(T--) {\n\t\tint n,k;\n\t\tll m;\n\t\tcin>>n>>m>>k;\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\tcin>>a[i];\n\t\t}\n\t\tsort(a+1,a+n+1);\n\t\tint t=0,r=0;\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\tif(i>1&&a[i]==a[i-1]) {\n\t\t\t\tb[++r]=a[i];\n\t\t\t} else {\n\t\t\t\tra[++t]=a[i];\n\t\t\t}\n\t\t}\n\t\tn=t;\n\t\tfor(int i=1;i<=n;i++) {\n\t\t\ta[i]=ra[i];\n\t\t\tg[i]=gcd(g[i-1],a[i]);\n\t\t\tsuma[i]=suma[i-1]+a[i];\n\t\t}\n\t\tfor(int i=0;i<=k;i++) {\n\t\t\tans[i]=-inf128;\n\t\t}\n\t\tfor(int l=1;l<=n;) {\n\t\t\tint r=l;\n\t\t\twhile(r<=n&&g[r]==g[l]) {\n\t\t\t\tr++;\n\t\t\t}\n\t\t\tr--;\n\t\t\tll Max=-inf;\n\t\t\tfor(int i=r+1;i<=n;i++) {\n\t\t\t\ta[i]=gcd(a[i],g[l]);\n\t\t\t\tMax=max(Max,a[i]-ra[i]);\n\t\t\t}\n\t\t\tfor(int i=r;i>=l;i--) {\n\t\t\t\tans[i]=suma[n]-suma[i]+Max;\t\n\t\t\t\ta[i]=gcd(a[i],g[l]);\n\t\t\t\tMax=max(Max,a[i]-ra[i]);\n\t\t\t}\n\t\t\tl=r+1;\n\t\t}\n\t\tfor(int i=1;i<=r;i++) {\n\t\t\tsumb[i]=sumb[i-1]+b[i];\n\t\t}\n\t\tint128 final=-inf128;\n\t\tif(k<=r) {\n\t\t\tfinal=suma[n]+sumb[r]-sumb[k];\n\t\t}\n\t\tfor(int i=0;i<=r&&i<=k;i++) {\n\t\t\tfinal=max(final,sumb[r]-sumb[i]+ans[k-i]);\n\t\t}\n\t\tprint(final);\n\t\tcout<<\"\\n\";\n\t}\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1807",
    "index": "A",
    "title": "Plus or Minus",
    "statement": "You are given three integers $a$, $b$, and $c$ such that \\textbf{exactly one} of these two equations is true:\n\n- $a+b=c$\n- $a-b=c$\n\nOutput + if the first equation is true, and - otherwise.",
    "tutorial": "You need to implement what is given in the statement; for example, you can use an if-statement to output + if $a+b=c$, and - otherwise.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint a, b, c;\n\tcin >> a >> b >> c;\n\tif (a + b == c) {cout << \"+\\n\";}\n\telse {cout << \"-\\n\";}\t\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1807",
    "index": "B",
    "title": "Grab the Candies",
    "statement": "Mihai and Bianca are playing with bags of candies. They have a row $a$ of $n$ bags of candies. The $i$-th bag has $a_i$ candies. The bags are given to the players in the order from the first bag to the $n$-th bag.\n\nIf a bag has an even number of candies, Mihai grabs the bag. Otherwise, Bianca grabs the bag. Once a bag is grabbed, the number of candies in it gets added to the total number of candies of the player that took it.\n\nMihai wants to show off, so he wants to reorder the array so that at any moment (except at the start when they both have no candies), Mihai will have \\textbf{strictly more} candies than Bianca. Help Mihai find out if such a reordering exists.",
    "tutorial": "Let $s_e$ be the total number of candies with all bags with an even number of candies, and $s_o$ - the total of all bags with an odd number of candies. If $s_e \\leq s_o$, then the answer is NO, because at the end Mihai (who takes only even numbers of candies) will have less candies than Bianca. Otherwise if $s_e > s_o$ the answer is YES. The construction is to simply put all even bags first, and then all odd bags: since all even bags come before all odd bags and $s_e>s_o$, at any point in time Mihai will have more candies than Bianca. The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    int x, odd = 0, even = 0;\n    for(int i = 0; i < n; i++)\n    {\n        cin >> x;\n        if(x%2 == 0)\n        {\n            even+=x;\n        }\n        else\n        {\n            odd+=x;\n        }\n    }\n    if(even > odd)\n    {\n        cout << \"YES\" << endl;\n    }\n    else\n    {\n        cout << \"NO\" << endl;\n    }\n}\n \nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n \n \n\n",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1807",
    "index": "C",
    "title": "Find and Replace",
    "statement": "You are given a string $s$ consisting of lowercase Latin characters. In an operation, you can take a character and replace \\textbf{all} occurrences of this character with $0$ or replace \\textbf{all} occurrences of this character with $1$.\n\nIs it possible to perform some number of moves so that the resulting string is an alternating binary string$^{\\dagger}$?\n\nFor example, consider the string $abacaba$. You can perform the following moves:\n\n- Replace $a$ with $0$. Now the string is $\\textcolor{red}{0}b\\textcolor{red}{0}c\\textcolor{red}{0}b\\textcolor{red}{0}$.\n- Replace $b$ with $1$. Now the string is ${0}\\textcolor{red}{1}{0}c{0}\\textcolor{red}{1}{0}$.\n- Replace $c$ with $1$. Now the string is ${0}{1}{0}\\textcolor{red}{1}{0}{1}{0}$. This is an alternating binary string.\n\n$^{\\dagger}$An alternating binary string is a string of $0$s and $1$s such that no two adjacent bits are equal. For example, $01010101$, $101$, $1$ are alternating binary strings, but $0110$, $0a0a0$, $10100$ are not.",
    "tutorial": "Let's solve a harder problem: given a string $s$ and a binary string $t$, can we make $s$ into $t$ using the find and replace operations? We can simply iterate through each character of $s$ and see the bit it has turned to in $t$ (that is, $s_i \\to t_i$ for each $i$). Keep track of each change, and see if there is some letter that needs to be turned into both $\\texttt{0}$ and $\\texttt{1}$. If there is some letter, it is impossible, since each operation requires changing all occurrences of a letter into the same bit. Otherwise, it is possible, and we can directly change each letter into the bit it needs to be. (See the implementation for a better understanding.) Now for this problem, since there are only two alternating binary strings of length $n$ ($\\texttt{01010...}$ and $\\texttt{10101...}$), we can simply check both. (Actually, we only have to check one - do you see why?) The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tint mp[26];\n\tfor (int i = 0; i < 26; i++) {\n\t\tmp[i] = -1;\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tint curr = (s[i] - 'a');\n\t\tif (mp[curr] == -1) {\n\t\t\tmp[curr] = (i % 2);\n\t\t}\n\t\telse {\n\t\t\tif (mp[curr] != (i % 2)) {cout << \"NO\\n\"; return;}\n\t\t}\n\t}\n\tcout << \"YES\\n\";\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1807",
    "index": "D",
    "title": "Odd Queries",
    "statement": "You have an array $a_1, a_2, \\dots, a_n$. Answer $q$ queries of the following form:\n\n- If we change all elements in the range $a_l, a_{l+1}, \\dots, a_r$ of the array to $k$, will the sum of the entire array be odd?\n\nNote that queries are \\textbf{independent} and do not affect future queries.",
    "tutorial": "Note that for each question, the resulting array is $[a_1, a_2, \\dots, a_{l-1}, k, \\dots, k, a_{r+1}, a_{r+2}, \\dots, a_n].$ So, the sum of the elements of the new array after each question is $a_1 + \\dots + a_{l-1} + (r-l+1) \\cdot k + a_{r+1} + \\dots + a_n.$ We can compute $a_1 + \\dots + a_{l-1}$ and $a_{r+1} + \\dots + a_n$ in $\\mathcal{O}(1)$ time by precomputing the sum of all prefixes and suffixes, or alternatively by using the prefix sums technique. So we can find the sum each time in $\\mathcal{O}(1)$ per question, and just check if it's odd or not. The time complexity is $\\mathcal{O}(n+q)$.",
    "code": "#include <iostream>\n \nusing namespace std;\nlong long n,a[200005],q,sum=0,pref[200005],t;\nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    cin>>t;\n    while(t--)\n    {\n        sum = 0;\n        cin >> n >> q;\n        for(int i=1;i<=n;i++){\n            cin >> a[i];\n            sum+=a[i];\n            pref[i]=pref[i-1];\n            pref[i]+=a[i];\n        }\n        for(int i = 0; i < q; i++){\n            long long l,r,k;\n            cin >> l >> r >> k;\n            long long ans = pref[n]-(pref[r]-pref[l-1])+k*(r-l+1);\n            if(ans%2==1){\n                cout<<\"YES\"<<endl;\n            }\n            else\n            {\n                cout<<\"NO\"<<endl;\n            }\n        }\n    }\n}\n \n\n",
    "tags": [
      "data structures",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1807",
    "index": "E",
    "title": "Interview",
    "statement": "This is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants.\n\nBefore the last stage of the exam, the director conducted an interview. He gave Gon $n$ piles of stones, the $i$-th pile having $a_i$ stones.\n\nEach stone is identical and weighs $1$ grams, except for one special stone that is part of an unknown pile and weighs $2$ grams.\n\n\\begin{center}\n{\\small A picture of the first test case. Pile $2$ has the special stone. The piles have weights of $1,3,3,4,5$, respectively.}\n\\end{center}\n\nGon can only ask the director questions of one kind: he can choose $k$ piles, and the director will tell him the total weight of the piles chosen. More formally, Gon can choose an integer $k$ ($1 \\leq k \\leq n$) and $k$ unique piles $p_1, p_2, \\dots, p_k$ ($1 \\leq p_i \\leq n$), and the director will return the total weight $m_{p_1} + m_{p_2} + \\dots + m_{p_k}$, where $m_i$ denotes the weight of pile $i$.\n\nGon is tasked with finding the pile that contains the special stone. However, the director is busy. Help Gon find this pile in at most $\\mathbf{30}$ queries.",
    "tutorial": "Consider this question: if we take some range $[a_l, \\dots, a_r]$ of piles, how do we know if it contains the special pile? If it doesn't contain the special pile, then the total weight should be $a_l + a_{l+1} + \\dots + a_r$ grams, since each stone weighs one gram. If it does contain the special pile, then the total weight should be $a_l + a_{l+1} + \\dots + a_r + 1$ grams, since each stone weighs one gram except for the special stone, which weighs two grams. Now we can binary search for the answer: first check the range $[a_1, \\dots, a_{\\frac{n}{2}}]$. If it has the special pile, then split it into two parts and check if one of them has the special stone; otherwise, check the other half. This will take at most $\\lceil \\log_2(2 \\cdot 10^5) \\rceil = 18$ queries, which is well below the limit of $30$. The time complexity is $\\mathcal{O}(n)$ (for reading the input).",
    "code": "#include <bits/stdc++.h>\nusing ll=long long;\nusing ld=long double;\nint const INF=1000000005;\nll const LINF=1000000000000000005;\nll const mod=1000000007;\nld const PI=3.14159265359;\nll const MAX_N=3e5+5;\nld const EPS=0.00000001;\n#pragma GCC optimize(\"O3\")\n#pragma GCC optimize(\"Ofast\")\n#define f first\n#define s second\n#define pb push_back\n#define mp make_pair\n#define endl '\\n'\n#define sz(a) (int)a.size()\n#define CODE_START  ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);\nusing namespace std;\nll t,n,a[2000005],pref[2000005];\nint32_t main(){\n//CODE_START;\n#ifdef LOCAL\n//ifstream cin(\"input.txt\");\n#endif\ncin>>t;\nwhile(t--){\n    cin>>n;\n    for(ll i=1;i<=n;i++)\n    {\n        cin>>a[i];\n        pref[i]=pref[i-1]+a[i];\n    }\n    ll l=1,r=n,ans=0;\n    while(l<=r){\n            ll mid=(l+r)/2;\n        cout<<\"? \"<<(mid-l+1)<<' ';\n        for(ll i=l;i<=mid;i++)\n        {\n            cout<<i<<' ';\n        }\n        cout<<endl<<flush;\n        ll x=0;\n        cin>>x;\n        if(x==pref[mid]-pref[l-1]){\n            l=mid+1;\n        }else {\n            r=mid-1;\n            ans=mid;\n        }\n    }\n    cout<<\"! \"<<ans<<endl<<flush;\n}\n}\n\n",
    "tags": [
      "binary search",
      "implementation",
      "interactive"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1807",
    "index": "F",
    "title": "Bouncy Ball",
    "statement": "You are given a room that can be represented by a $n \\times m$ grid. There is a ball at position $(i_1, j_1)$ (the intersection of row $i_1$ and column $j_1$), and it starts going diagonally in one of the four directions:\n\n- The ball is going down and right, denoted by $DR$; it means that after a step, the ball's location goes from $(i, j)$ to $(i+1, j+1)$.\n- The ball is going down and left, denoted by $DL$; it means that after a step, the ball's location goes from $(i, j)$ to $(i+1, j-1)$.\n- The ball is going up and right, denoted by $UR$; it means that after a step, the ball's location goes from $(i, j)$ to $(i-1, j+1)$.\n- The ball is going up and left, denoted by $UL$; it means that after a step, the ball's location goes from $(i, j)$ to $(i-1, j-1)$.\n\nAfter each step, the ball maintains its direction unless it hits a wall (that is, the direction takes it out of the room's bounds in the next step). In this case, the ball's direction gets flipped along the axis of the wall; if the ball hits a corner, both directions get flipped. Any instance of this is called a bounce. The ball never stops moving.\n\nIn the above example, the ball starts at $(1, 7)$ and goes $DL$ until it reaches the bottom wall, then it bounces and continues in the direction $UL$. After reaching the left wall, the ball bounces and continues to go in the direction $UR$. When the ball reaches the upper wall, it bounces and continues in the direction $DR$. After reaching the bottom-right corner, it bounces \\textbf{once} and continues in direction $UL$, and so on.\n\nYour task is to find how many bounces the ball will go through until it reaches cell $(i_2, j_2)$ in the room, or report that it never reaches cell $(i_2, j_2)$ by printing $-1$.\n\nNote that the ball first goes in a cell and only after that bounces if it needs to.",
    "tutorial": "We can see that there are at most $4\\cdot n \\cdot m$ states the ball can be in, because there are $n \\cdot m$ cells and $4$ states of direction. We can simulate the bouncing process, keeping count of the bounces until we arrive at the finish cell when we can output the answer, or we arrive at a previously visited state and end up in a loop, then we can output -1. Bonus: Can you prove there are at most $2\\cdot n \\cdot m$ states for any given starting position?",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n    int n, m, x1, y1, x2, y2;\n    string d_string;\n    cin >> n >> m >> x1 >> y1 >> x2 >> y2;\n    x1--;x2--;y1--;y2--;\n    cin >> d_string;\n    int d = (d_string[0] == 'U' ? 1+(d_string[1] == 'R' ? 2 : 0) : 0+(d_string[1] == 'R' ? 2 : 0));\n    bool vis[n][m][4];\n    memset(vis, false, sizeof(vis));\n    int i = x1, j = y1;\n    int bounces = 0;\n    while(!vis[i][j][d])\n    {\n        if(i == x2 && j == y2){cout << bounces << endl; return;}\n        int na = 0;\n        if(d%2 == 1 && i == 0){d-=1;na++;}\n        if(d%2 == 0 && i == n-1){d+=1;na++;}\n        if(d >= 2 && j == m-1){d-=2;na++;}\n        if(d < 2 && j == 0){d+=2;na++;}\n        bounces+=min(1, na);\n        if(vis[i][j][d])\n        {\n            break;\n        }\n        vis[i][j][d] = true;\n        if(d%2 == 1){i--;}else{i++;}\n        if(d >= 2){j++;}else{j--;}\n    }\n    cout << -1 << endl;\n}\n \nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1807",
    "index": "G1",
    "title": "Subsequence Addition (Easy Version)",
    "statement": "The only difference between the two versions is that in this version, the constraints are lower.\n\nInitially, array $a$ contains just the number $1$. You can perform several operations in order to change the array. In an operation, you can select some subsequence$^{\\dagger}$ of $a$ and add into $a$ an element equal to the sum of all elements of the subsequence.\n\nYou are given a final array $c$. Check if $c$ can be obtained from the initial array $a$ by performing some number (possibly 0) of operations on the initial array.\n\n$^{\\dagger}$ A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly zero, but not all) elements. In other words, select $k$ ($1 \\leq k \\leq |a|$) distinct indices $i_1, i_2, \\dots, i_k$ and insert anywhere into $a$ a new element with the value equal to $a_{i_1} + a_{i_2} + \\dots + a_{i_k}$.",
    "tutorial": "Firstly, let's note that it doesn't matter in what order we add the elements to the array, since if we can add an element in any position, if it's possible to get the said elements of the array, then we can obtain them in any order. Now, let's note that it's always optimal to obtain the needed elements in sorted order (since we only use smaller values in order to obtain the current one), so we will consider the array $c$ as sorted. If the first element of the array isn't $1$ then we immediately know such an array doesn't exist. Otherwise, we can use dynamic programming for finding out if the remaining $n - 1$ elements are obtainable. Let's denote $dp_s$ a boolean array which tells us whether sum $s$ is obtainable. Initially, $dp_1 = 1$ (since the first element is guaranteed to be $1$). We will go in increasing order of $c_i$ and if we calculated an element to be obtainable in the past, we update all obtainable values with the new $c_i$ value. We do this in $O(n \\cdot 5000)$, by going through all sums $s$ and updating $dp_s = dp_s | dp_{s - c_i}$ ($dp_s$ is true if it already was true, or if $dp_{s - c_i}$ was true and we add to that sum the new value $c_i$. The total time complexity of this solution is $O(n \\cdot 5000)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n \nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n);\n    for(int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    sort(all(a));\n    if(a[0] != 1) {\n        cout << \"NO\\n\";\n        return;\n    }\n    vector<int> dp(5005, 0);\n    dp[1] = 1;\n    for(int i = 1; i < n; ++i) {\n        if(!dp[a[i]]) {\n            cout << \"NO\\n\";\n            return;\n        }\n        for(int j = 5000; j >= a[i]; --j) {\n            dp[j] |= dp[j - a[i]];\n        }\n    }\n    cout << \"YES\\n\";\n}\n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}\n\n",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1807",
    "index": "G2",
    "title": "Subsequence Addition (Hard Version)",
    "statement": "The only difference between the two versions is that in this version, the constraints are higher.\n\nInitially, array $a$ contains just the number $1$. You can perform several operations in order to change the array. In an operation, you can select some subsequence$^{\\dagger}$ of $a$ and add into $a$ an element equal to the sum of all elements of the subsequence.\n\nYou are given a final array $c$. Check if $c$ can be obtained from the initial array $a$ by performing some number (possibly 0) of operations on the initial array.\n\n$^{\\dagger}$ A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly zero, but not all) elements. In other words, select $k$ ($1 \\leq k \\leq |a|$) distinct indices $i_1, i_2, \\dots, i_k$ and insert anywhere into $a$ a new element with the value equal to $a_{i_1} + a_{i_2} + \\dots + a_{i_k}$.",
    "tutorial": "Let's prove that for an array $a$ that was created by using a number of operations, with a sum of elements $s$ we can add into $a$ any number $x$ ($1 \\leq x \\leq s$). Suppose that it is true that in the array $a$ with some length $l$ we introduce a number $x$ ($1 \\leq x \\leq sum_a$). Then after introducing we can create using the initial elements of the array any number $b$ ($1 \\leq b \\leq sum_a$) and using the element $x$ and some subset of the initial elements we can create any number $b$ ($x \\leq b \\leq sum_a+x$), and because $x \\leq sum_a$ we proved that for the new array of length $l+1$ we can still create any number between $1$ and $sum_a+x$. Since it is true for the initial array, we can use induction and this fact to prove it is true for all arrays. So we just need to verify if our array satisfies this condition. We should sort the array and check for each $i$ ($2 \\leq i \\leq n$) if $c_i \\leq \\sum_{j = 1}^{i-1}c_j$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n \nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n);\n    for(int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    sort(all(a));\n    if(a[0] != 1) {\n        cout << \"NO\\n\";\n        return;\n    }\n    long long sum = a[0];\n    for(int i = 1; i < n; ++i) {\n        if(sum < a[i]) {\n            cout << \"NO\\n\";\n            return;\n        }\n        sum += a[i];\n    }\n    cout << \"YES\\n\";\n}\n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1808",
    "index": "A",
    "title": "Lucky Numbers",
    "statement": "Olympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets inexpensively.\n\nEach starship has a number —some positive integer $x$. Let's define the luckiness of a number $x$ as the difference between the largest and smallest digits of that number. For example, $142857$ has $8$ as its largest digit and $1$ as its smallest digit, so its luckiness is $8-1=7$. And the number $111$ has all digits equal to $1$, so its luckiness is zero.\n\nHateehc is a famous Martian blogger who often flies to different corners of the solar system. To release interesting videos even faster, he decided to buy himself a starship. When he came to the store, he saw starships with numbers from $l$ to $r$ inclusively. While in the store, Hateehc wanted to find a starship with the luckiest number.\n\nSince there are a lot of starships in the store, and Hateehc can't program, you have to help the blogger and write a program that answers his question.",
    "tutorial": "Let $r - l \\geq 100$. Then it is easy to see that there exists a number $k$ such that $l \\le k \\le r$, and $k \\equiv 90 \\mod 100$. Then the number $k$ is the answer. If $r - l < 100$, you can find the answer by trying all the numbers. Despite the impressive constant, from the theoretical point of view we obtain a solution with asymptotics $O(1)$ for the answer to the query.",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1808",
    "index": "B",
    "title": "Playing in a Casino",
    "statement": "Galaxy Luck, a well-known casino in the entire solar system, introduces a new card game.\n\nIn this game, there is a deck that consists of $n$ cards. Each card has $m$ numbers written on it. Each of the $n$ players receives exactly one card from the deck.\n\nThen all players play with each other in pairs, and each pair of players plays exactly once. Thus, if there are, for example, four players in total, then six games are played: the first against the second, the first against the third, the first against the fourth, the second against the third, the second against the fourth and the third against the fourth.\n\nEach of these games determines the winner in some way, but the rules are quite complicated, so we will not describe them here. All that matters is how many chips are paid out to the winner. Let the first player's card have the numbers $a_1, a_2, \\dots, a_m$, and the second player's card — $b_1, b_2, \\dots, b_m$. Then the winner of the game gets $|a_1 - b_1| + |a_2 - b_2| + \\dots + |a_m - b_m|$ chips from the total pot, where $|x|$ denotes the absolute value of $x$.\n\nTo determine the size of the total pot, it is necessary to calculate the winners' total winnings for all games. Since there can be many cards in a deck and many players, you have been assigned to write a program that does all the necessary calculations.",
    "tutorial": "You may notice that the problem can be solved independently for each column of the input matrix. The answer is then the sum $\\sum\\limits_{i = 1}^n \\sum\\limits_{j = i + 1}^n |a_i - a_j|$, where $a$ - array representing a column. Let's try to calculate this sum for each column. Let's sort all elements of the current column. Let's calculate the answer for some element in the sorted list. The answer for it will be $a_i \\cdot i - sum$, where $sum$ is the sum on the prefix. Why is this so? Because we say that this number is larger than the others and the modulus will then decompose as $a_i - a_j$, and this is already easy to count.",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1808",
    "index": "C",
    "title": "Unlucky Numbers",
    "statement": "{In this problem, unlike problem A, you need to look for \\textbf{unluckiest number}, not the luckiest one.}\n\n\\textbf{Note that the constraints of this problem differ from such in problem A.}\n\nOlympus City recently launched the production of personal starships. Now everyone on Mars can buy one and fly to other planets inexpensively.\n\nEach starship has a number —some positive integer $x$. Let's define the luckiness of a number $x$ as the difference between the largest and smallest digits of that number. For example, $142857$ has $8$ as its largest digit and $1$ as its smallest digit, so its luckiness is $8-1=7$. And the number $111$ has all digits equal to $1$, so its luckiness is zero.\n\nHateehc is a famous Martian blogger who often flies to different corners of the solar system. To release interesting videos even faster, he decided to buy himself a starship. When he came to the store, he saw starships with numbers from $l$ to $r$ inclusively. While in the store, Hateehc wanted to find a starship with the \\textbf{unluckiest} number.\n\nSince there are a lot of starships in the store, and Hateehc can't program, you have to help the blogger and write a program that answers his question.",
    "tutorial": "Check all pairs ($l$, $r$) - the minimum and maximum digits of the number from the answer. Discard the common prefix of $l$ and $r$. Now we are left with some digits $a$ and $b$ as the leftmost digits of the number, with $a$ < $b$. If $b - a \\geq 2$, then we can put $a + 1$ at the beginning of the number, and then put any digit from the interval $[l, r]$. Otherwise, we try $a$, and then always put the largest digit of $[l, r]$ that we can. Similarly, then try putting $b$, and then always put the smallest digit of $[l, r]$ you can. Of all $l$ and $r$, for which it is possible to construct a given number, choose such that $r - l$ is minimal, and the number constructed at these $l$ and $r$.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1808",
    "index": "D",
    "title": "Petya, Petya, Petr, and Palindromes",
    "statement": "Petya and his friend, the robot Petya++, have a common friend — the cyborg Petr#. Sometimes Petr# comes to the friends for a cup of tea and tells them interesting problems.\n\nToday, Petr# told them the following problem.\n\nA palindrome is a sequence that reads the same from left to right as from right to left. For example, $[38, 12, 8, 12, 38]$, $[1]$, and $[3, 8, 8, 3]$ are palindromes.\n\nLet's call the palindromicity of a sequence $a_1, a_2, \\dots, a_n$ the minimum count of elements that need to be replaced to make this sequence a palindrome. For example, the palindromicity of the sequence $[38, 12, 8, 38, 38]$ is $1$ since it is sufficient to replace the number $38$ at the fourth position with the number $12$. And the palindromicity of the sequence $[3, 3, 5, 5, 5]$ is two since you can replace the first two threes with fives, and the resulting sequence $[5, 5, 5, 5, 5]$ is a palindrome.\n\nGiven a sequence $a$ of length $n$, and an \\textbf{odd} integer $k$, you need to find the sum of palindromicity of all subarrays of length $k$, i. e., the sum of the palindromicity values for the sequences $a_i, a_{i+1}, \\dots, a_{i+k-1}$ for all $i$ from $1$ to $n-k+1$.\n\nThe students quickly solved the problem. Can you do it too?",
    "tutorial": "Let us see when $1$ is added to the palindrome. Let there be some string $s$ of odd length $k$, consider the index $i$ to the left of the central one. If this character and the corresponding one on the right side of the string are different, we can replace one of the characters with the other and get $+1$ to the answer. Now the problem is as follows: count the number of indices on all substring of length $k$ such that they differ from the corresponding character in that substring. Let's solve the inverse problem: count the number of indices for all substring of length $k$ such that the given symbol and its corresponding one are equal. Then simply subtract from the maximum possible number of differences the required number of matches. Try some symbol $c$ and count for it the number of matches in all substring. Create a new array $a$ of length $n$, that $a_i=1$ when $s_i=c$, otherwise $a_i=0$. Now we have to count the number of indices $i$ and $j$ such that $i<j$, $a_i \\cdot a_j=1$, $j-i < k$ and $(j-i)$ mod $2=0$ (i.e. the distance between indices is even). Let's fix some $j$ where $a_j=1$, then indexes $j-2$, $j-4$, etc. fit the parity condition. Then we can calculate prefix sums for each parity of indices. That is, $pf_{i,par}$ means the sum on prefix length $i$ over all indices with parity equal to $par$. Then $pf_{j-2,par}$, where $par=j$ $mod$ $2$ is subtracted from the answer for some fixed $j$. Total we get the solution for $O(n\\cdot maxA)$, where $maxA$ is the number of different characters of the string. To solve the problem faster, we will use the work from the previous solution. Write out separately for each character all its occurrences in the string. Let's go through the symbol and write out all positions with even and odd indices. Solve the problem for even ones (odd ones are solved similarly). We will maintain a sliding window, where the difference between right and left elements is no more than $k$. When we finish iterating after removing the left element, we will subtract the window length $-1$ from the answer, because for the left element of the window exactly as many elements have the same parity on the right at a distance of no more than $k$. P.S. The solution for $O(n\\cdot maxA)$ can also be reworked into $O(n \\sqrt{n})$ using the trick with <<heavy>> and <<light>> numbers.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1808",
    "index": "E1",
    "title": "Minibuses on Venus (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.}\n\nMaxim is a minibus driver on Venus.\n\nTo ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of $n$ digits. However, as we know, the residents of Venus use a numeral system with base $k$, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of $n$ integers from $0$ to $k-1$, inclusive.\n\nThe residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo $k$. For example, if $k=10$, then the ticket $7135$ is lucky because $7 + 1 + 5 \\equiv 3 \\pmod{10}$. On the other hand, the ticket $7136$ is not lucky because no digit is equal to the sum of the others modulo $10$.\n\nOnce, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number $m$.",
    "tutorial": "First, let's rephrase the problem condition a bit. A ticket number is lucky if ($a_i$ - the digit that stands at position $i$ in the number) is satisfied: $a_i \\equiv (a_1 + a_2 + \\ldots + a_{i-1} + a_{i+1} + \\ldots + a_{n-1} + a_n) \\pmod{k}$ Let $S$ be the sum of all digits of the number. Then we can rewrite the surprise condition: $a_i \\equiv S - a_i \\pmod{k}$ $2 \\cdot a_i \\equiv S \\pmod{k}$ Thus, if among the digits of the ticket there is such a digit $x$ that: $2 \\cdot x \\equiv S \\pmod{k}$ Then the ticket is lucky. Also note that there are $k^n$ numbers of tickets in total. Let's count how many nosurprising tickets exist. Then, by subtracting this number from $k^n$, we will get the answer to the original problem. So now our goal is to count the number of non-surprising tickets. Given a fixed sum $S$, there are numbers $x$ that: $2 \\cdot x \\equiv S \\pmod{k}$ Therefore, in order for a number with sum $S$ to be unlucky, it must not contain these digits. Let us fix what $S$ modulo $k$ will equal. Now, let's make a DP $f[i][sum]$, where: $i$ - index of the digit to be processed in the ticket $sum$ - the current sum of digits of the ticket, modulo $k$ The basis of DP - $f[0][0] = 1$. We will build transitions from the state $f[i][sum]$ by going through the digit $y$, which we will put at position $i$. Keep in mind that we cannot use such $y$ that: $2 \\cdot y \\equiv S \\pmod{k}$ Depending on $y$ we recalculate $sum$. The number of unlucky ticket numbers, with sum $S$ modulo $k$ will be stored in $f[n][S]$.",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1808",
    "index": "E2",
    "title": "Minibuses on Venus (medium version)",
    "statement": "\\textbf{This is the medium version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.}\n\nMaxim is a minibus driver on Venus.\n\nTo ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of $n$ digits. However, as we know, the residents of Venus use a numeral system with base $k$, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of $n$ integers from $0$ to $k-1$, inclusive.\n\nThe residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo $k$. For example, if $k=10$, then the ticket $7135$ is lucky because $7 + 1 + 5 \\equiv 3 \\pmod{10}$. On the other hand, the ticket $7136$ is not lucky because no digit is equal to the sum of the others modulo $10$.\n\nOnce, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number $m$.",
    "tutorial": "First, read the editorial of problem E1. This section is a continuation and improvement of ideas from the previous section. Let us improve the solution for $O(nk^3)$. To do this, note that the transitions from $i$ to $i + 1$ can be given by a matrix $g$ of size $k \\times k$. Then by multiplying $f[i]$ (i.e., multiplying exactly $1 \\times k$ matrix of the form $[f[i][0], f[i][1], \\ldots, f[i][k - 1]]$) by this $g$ matrix, we get $f[i + 1]$. Now note that for a fixed sum $S$ modulo $k$, the matrix $g$ will be the same for any $i$. Then let us take $g$ to the power of $n$. Then $f[n]$ can be obtained by calculating $f[0] \\cdot g^n$. We can use multiplication algorithm for $O(k^3 \\log n)$ to get the matrix powered $n$.",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dp",
      "matrices"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1808",
    "index": "E3",
    "title": "Minibuses on Venus (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the three versions is the constraints on $n$ and $k$. You can make hacks only if all versions of the problem are solved.}\n\nMaxim is a minibus driver on Venus.\n\nTo ride on Maxim's minibus, you need a ticket. Each ticket has a number consisting of $n$ digits. However, as we know, the residents of Venus use a numeral system with base $k$, rather than the decimal system. Therefore, the ticket number can be considered as a sequence of $n$ integers from $0$ to $k-1$, inclusive.\n\nThe residents of Venus consider a ticket to be lucky if there is a digit on it that is equal to the sum of the remaining digits, modulo $k$. For example, if $k=10$, then the ticket $7135$ is lucky because $7 + 1 + 5 \\equiv 3 \\pmod{10}$. On the other hand, the ticket $7136$ is not lucky because no digit is equal to the sum of the others modulo $10$.\n\nOnce, while on a trip, Maxim wondered: how many lucky tickets exist? At the same time, Maxim understands that this number can be very large, so he is interested only in the answer modulo some prime number $m$.",
    "tutorial": "First read the editorial for problems E1 and E2. This section is a continuation and improvement of ideas from previous sections. Let's calculate how many such digits $x$ can exist in total for a fixed $S$ modulo $k$ that: $2 \\cdot x \\equiv S \\pmod{k}$ $k$ is odd. Then there can exist exactly one such digit $x$ from $0$ to $k - 1$, provided that $S$ - is odd (and it will equal exactly $\\frac{S + k}{2}$). $k$ is even. Then there can be two such digits $x_1, x_2$ from $0$ to $k - 1$, provided that $S$ - is even (with $x_1 = \\frac{k}{2}, x_2 = \\frac{S + k}{2}$). Let's solve the problem when $k$ is odd. Calculate how many different $S$ exist that for them there exists a digit $x$ (denote the set of such $S$ as $cnt_1$), and calculate how many different $S$ exist that for them there is no such digit $x$ (denote the set of such $S$ as $cnt_0$). If $S$ enters $cnt_0$, then the number of unsurprising ticket numbers will be $k^{n-1}$ (Since the total numbers $k^n$ are exactly $\\frac{1}{k}$ of them will have some $S$ from $0$ to $k - 1$ modulo $k$). So it is sufficient to add $|cnt_0| \\cdot k^{n-1}$ to the number of unsurprising tickets. If $S$ enters $cnt_1$, let's use the following trick: subtract from each digit in the number $x$. Now we have reduced the original problem to the case where $x = 0$. Now let's count the DP $f[i][flag]$ - the number of unlucky numbers, where: $i$ - how many digits of the ticket we've already looked at $flag = 1$ if the current sum of digits is greater than zero, and $flag = 0$ otherwise. This DP can be counted in $O(\\log n)$, again using the binary exponentiation of the matrix $2 \\times 2$ (the content of the matrix is justified by the fact that the numbers must not contain $x = 0$): $\\begin{pmatrix} 0 & k - 1\\\\ 1 & k - 2 \\end{pmatrix}$ After calculating the DP, it is necessary to enumerate all possible variants of $x$ and variants of $S'$. If the condition is satisfied: $2 \\cdot x \\equiv (S' + x \\cdot n) \\pmod{k}$ Then we can add to the number of unsurprising numbers: $f[n][0]$ if $S' = 0$ $\\frac{f[n][1]}{k - 1}$ if $S' \\neq 0$ (note that division must be done modulo $m$). The reason for division is that $f[n][1]$ is the number of all numbers with $S' \\neq 0$, and we need the number of numbers with some particular sum of $S'$. The approach to solving for even $k$ will be almost identical to the approach for odd $k$. The difference will be that we can now have either two $x_1, x_2$ when $S$ is fixed, or none. When there are no $x$-ones, the solution is the same as the solution for $cnt_0$ of odd $k$. When there is $x_1, x_2$, we can see that they differ by $\\frac{k}{2}$. So let's again subtract $x_1$ from each digit in the number and then double each digit after that. That is, we now work with the numbers $0, 2, \\ldots, 2\\cdot (k - 2), 0, 2, \\ldots (k - 2)$. The matrix for DP transitions will now have the form: $\\begin{pmatrix} 0 & k - 2\\\\ 2 & k - 4 \\end{pmatrix}$ After calculating the DP, it is necessary to enumerate all matching pairs $x_1, x_2$ and variants of $S'$. If the condition is satisfied: $2 \\cdot x_1 \\equiv (S' + x_1 \\cdot n) \\pmod{k}$ Then we can add to the number of unsurprising numbers: $\\frac{f[n][0]}{2}$ if $S' = 0$ (note that division must be done modulo $m$). The division is justified by the fact that $f[n][0]$ is the number of all numbers with $S' = 0$, but now we have two different \"zero\" sums (since we have dominated all numbers by 2). $\\frac{f[n][1]}{k - 2}$ if $S' \\neq 0$ (note that division must be done modulo $m$). The reason for division is that $f[n][1]$ is the number of all numbers with $S' \\neq 0$, and we need the number of numbers with some particular sum of $S'$.",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1809",
    "index": "A",
    "title": "Garland",
    "statement": "You have a garland consisting of $4$ colored light bulbs, the color of the $i$-th light bulb is $s_i$.\n\nInitially, all the light bulbs are turned off. Your task is to turn all the light bulbs on. You can perform the following operation any number of times: select a light bulb and switch its state (turn it on if it was off, and turn it off if it was on). The only restriction on the above operation is that you can apply the operation to a light bulb only if the previous operation was applied to a light bulb of a different color (the first operation can be applied to any light bulb).\n\nCalculate the minimum number of operations to turn all the light bulbs on, or report that this is impossible.",
    "tutorial": "Note that there are only a few configuration classes: 1111, 1112, 1122, 1123 and 1234. Let's discuss each of them. If all $4$ bulbs are of the same color, then it is impossible to turn all the bulbs on, because after you switch one light bulb, it is impossible to turn the others on. If there is a color with $3$ bulbs, then it is impossible to turn all the bulbs on in $4$ operations, which means there is a bulb that turns on, turns off and then turns on again, i.e. the answer is at least $6$ operations. And there is a sequence of exactly $6$ operations (such an example was shown in the problem notes). For configurations like 1122 and 1123, it is enough to turn on the $1$ color bulbs not in a row (i.e. in order $[1, 2, 1, 2]$ for the first case and $[1, 2, 1, 3]$ for the second one). So the answer for such configurations is $4$. If all the bulbs are of different colors, then nothing prevents you from turning them all on in $4$ operations.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int tc;\n  cin >> tc;\n  while (tc--) {\n    string s;\n    cin >> s;\n    vector<int> cnt(10);\n    for (auto c : s) ++cnt[c - '0'];\n    int mx = *max_element(cnt.begin(), cnt.end());\n    if (mx == 4) cout << -1;\n    else if (mx == 3) cout << 6;\n    else cout << 4;\n    cout << '\\n';\n  }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1809",
    "index": "B",
    "title": "Points on Plane",
    "statement": "You are given a two-dimensional plane, and you need to place $n$ chips on it.\n\nYou can place a chip only at a point with integer coordinates. The cost of placing a chip at the point $(x, y)$ is equal to $|x| + |y|$ (where $|a|$ is the absolute value of $a$).\n\nThe cost of placing $n$ chips is equal to the \\textbf{maximum} among the costs of each chip.\n\nYou need to place $n$ chips on the plane in such a way that the Euclidean distance between each pair of chips is \\textbf{strictly greater} than $1$, and the cost is the minimum possible.",
    "tutorial": "Suppose, the answer is $k$. What's the maximum number of chips we can place? Firstly, the allowed points $(x, y)$ to place chips are such that $|x| + |y| \\le k$. We can group them by $x$-coordinate: for $x = k$ there is only one $y = 0$, for $x = k - 1$ possible $y$ are $-1, 0, 1$; for $x = k - 2$ possible $y$ are in segment $[-2, \\dots, 2]$ and so on. For $x = 0$ possible $y$ are in $[-k, \\dots, k]$. The negative $x$-s are the same. Let's calculate the maximum number of chips we can place at each \"row\": for $x = k$ it's $1$; for $x = k - 1$ there are three $y$-s, but since we can't place chips at the neighboring $y$-s, we can place at most $2$ chips; for $x = k - 2$ we have $5$ places, but can place only $3$ chips; for $x = 0$ we have $2k + 1$ places, but can occupy only $k + 1$ points. In total, for $x \\in [0, \\dots, k]$ we can place at most $1 + 2 + \\dots + (k + 1) = \\frac{(k + 1)(k + 2)}{2}$ chips. Analogically, for $x \\in [-k, \\dots, -1]$ we can place at most $1 + 2 + \\dots + k = \\frac{k (k + 1)}{2}$ chips. In total, we can place at most $\\frac{(k + 1)(k + 2)}{2} + \\frac{k (k + 1)}{2} = (k + 1)^2$ chips with cost at most $k$. Note that $(k + 1)^2$ can actually be reached since the distance between chips on the different rows is greater than $1$. So, to solve our task, it's enough to find minimum $k$ such that $(k + 1)^2 \\ge n$ that can be done with Binary Search. Or we can calculate $k = \\left\\lceil \\sqrt{n} \\right\\rceil - 1$. Note that $\\sqrt{n}$ can lose precision, since $n$ is cast to double before taking the square root (for example, $975461057789971042$ transforms to $9.754610577899711 \\cdot 10^{17} = 975461057789971100$ when converted to double). So you should either cast long long to long double (that consists of $80$ bits in some C++ compilers) or check value $k + 1$ as a possible answer.",
    "code": "import kotlin.math.sqrt\n\nfun main() {\n    repeat(readln().toInt()) {\n        val n = readln().toLong()\n        var ans = sqrt(n.toDouble()).toLong()\n        while (ans * ans > n)\n            ans--\n        while (ans * ans < n)\n            ans++\n        println(ans - 1)\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1809",
    "index": "C",
    "title": "Sum on Subarrays",
    "statement": "For an array $a = [a_1, a_2, \\dots, a_n]$, let's denote its subarray $a[l, r]$ as the array $[a_l, a_{l+1}, \\dots, a_r]$.\n\nFor example, the array $a = [1, -3, 1]$ has $6$ non-empty subarrays:\n\n- $a[1,1] = [1]$;\n- $a[1,2] = [1,-3]$;\n- $a[1,3] = [1,-3,1]$;\n- $a[2,2] = [-3]$;\n- $a[2,3] = [-3,1]$;\n- $a[3,3] = [1]$.\n\nYou are given two integers $n$ and $k$. Construct an array $a$ consisting of $n$ integers such that:\n\n- all elements of $a$ are from $-1000$ to $1000$;\n- $a$ has exactly $k$ subarrays with positive sums;\n- the rest $\\dfrac{(n+1) \\cdot n}{2}-k$ subarrays of $a$ have negative sums.",
    "tutorial": "There are many ways to solve this problem. I will describe the following recursive solution: if $k < n$, let's compose an array where every segment ending with the $k$-th element is positive, and every other segment is negative. This array can be $[-1, -1, -1, \\dots, 200, -400, -1, -1, -1]$, where $200$ is the $k$-th element of the array (note that when $k = 0$, $200$ doesn't belong to the array, so it consists of only negative numbers). but if $k \\ge n$, solve the same problem with $n-1$ and $k-n$ recursively, get an array of length $n-1$ with $k-n$ positive subarrays, and append $1000$ to it to make all $n$ segments ending with the last element positive.",
    "code": "def solve(n, k):\n    if n == 0:\n        return []\n    if k < n:\n        a = [-1 for i in range(n)]\n        if k > 0:\n            a[k - 1] = 200\n        a[k] = -400\n    else:\n        a = solve(n - 1, k - n)\n        a.append(1000)\n    return a\n\nt = int(input())\nfor i in range(t):\n    n, k = map(int, input().split())\n    b = solve(n, k)\n    print(*b)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1809",
    "index": "D",
    "title": "Binary String Sorting",
    "statement": "You are given a binary string $s$ consisting of only characters 0 and/or 1.\n\nYou can perform several operations on this string (possibly zero). There are two types of operations:\n\n- choose two consecutive elements and swap them. In order to perform this operation, you pay $10^{12}$ coins;\n- choose any element from the string and remove it. In order to perform this operation, you pay $10^{12}+1$ coins.\n\nYour task is to calculate the minimum number of coins required to sort the string $s$ in non-decreasing order (i. e. transform $s$ so that $s_1 \\le s_2 \\le \\dots \\le s_m$, where $m$ is the length of the string after applying all operations). An empty string is also considered sorted in non-decreasing order.",
    "tutorial": "Note that the price of operations is much greater than the difference between them. Therefore, first of all, we have to minimize the number of operations, and then maximize the number of operations of the first type. Swapping two elements if at least one of them will be deleted later is not optimal. Therefore, first let's delete some elements of the string, and then sort the remaining elements using swaps. The number of swaps for sorting is equal to the number of inversions (i. e. the number of pairs such that $s_j > s_i$ and $j < i$). From here we can notice that if the number of inversions is greater than $1$, then there is an element that produces at least $2$ inversions. So it is more profitable for us to remove it, to minimize the number of operations. From the above we get that the number of operations of the first type is at most $1$. If all operations are only of the second type, then we need to find a subsequence of the maximum length of the form 0000111111. To do this, we can iterate over the number of zeros that we include in the final string, and then add the number of ones from the remaining suffix of the string (that goes after the fixed number of zeros). If there is an operation of the first type, then it is enough to iterate over the pair that creates the inversion, to the left of it take all zeros, and to the right of it take all ones (you can notice that in fact it is enough to iterate over only a pair of neighboring elements of the string).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst long long pw10 = 1e12;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int tc;\n  cin >> tc;\n  while (tc--) {\n    string s;\n    cin >> s;\n    int n = s.size();\n    int cnt0 = 0, cnt1 = count(s.begin(), s.end(), '1');\n    long long ans = 1e18;\n    if (n == 1) ans = 0;\n    for (int i = 0; i < n - 1; ++i) {\n      cnt0 += s[i] == '0';\n      cnt1 -= s[i] == '1';\n      int k = cnt0 + cnt1 + (s[i] == '1') + (s[i + 1] == '0');\n      long long cur = (n - k) * (pw10 + 1);\n      if (s[i] > s[i + 1]) cur += pw10;\n      ans = min(ans, cur); \n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1809",
    "index": "E",
    "title": "Two Tanks",
    "statement": "There are two water tanks, the first one fits $a$ liters of water, the second one fits $b$ liters of water. The first tank has $c$ ($0 \\le c \\le a$) liters of water initially, the second tank has $d$ ($0 \\le d \\le b$) liters of water initially.\n\nYou want to perform $n$ operations on them. The $i$-th operation is specified by a single non-zero integer $v_i$. If $v_i > 0$, then you try to pour $v_i$ liters of water from the first tank into the second one. If $v_i < 0$, you try to pour $-v_i$ liters of water from the second tank to the first one.\n\nWhen you try to pour $x$ liters of water from the tank that has $y$ liters currently available to the tank that can fit $z$ more liters of water, the operation only moves $\\min(x, y, z)$ liters of water.\n\nFor all pairs of the initial volumes of water $(c, d)$ such that $0 \\le c \\le a$ and $0 \\le d \\le b$, calculate the volume of water in the first tank after all operations are performed.",
    "tutorial": "Consider a naive solution. Iterate over all pairs $(c, d)$ and apply all operations. The complexity is $O(a \\cdot b \\cdot n)$. The constraints obviously imply that it's too much. What can we cut from it? Well, surely $O(n)$ will still remain there. Both of $a$ and $b$ also should. So we can probably only hope to turn this $O(ab)$ into $O(a + b)$. Let's try that. Notice that no matter what operations are applied, $c + d$ never changes. You can also peek at the examples and see that the patterns are suspiciously diagonal-shaped in the matrix. Let's try to solve the problem by fixing $c + d$ and calculating the answer for all values of $c$. I will call the fixed $c + d$ variable $\\mathit{cd}$. Consider case where $\\mathit{cd} \\le a$ and $\\mathit{cd} \\le b$. Here, all $\\mathit{cd}$ can fit into both $a$ and $b$, so we can avoid caring about one restriction on the operations. We'll think what to do with large volumes later. If there are no operations, the answer for each initial $c$ is $c$ for all $c$ from $0$ to $\\mathit{cd}$. Now consider an operation $x$ for some $x > 0$. For $c = 0$, nothing changes. Actually, for all $c \\le x$ the result of the operation is the same as for $c = 0$. Hmm, but if the result is the same, it will remain the same until the end. Same from the other side. The answers for $x < 0$ and $d \\le -x$ also get merged together. To me it kind of looks like a primitive form of DSU on these volume states: you merge some prefix of the answers together and merge some suffix of the answers together. If the state was merged to either $c = 0$ or $d = 0$, then it's easy to calculate the actual answer for that state. What happens to the remaining states? Well, since they weren't merged anywhere, the operation for them was applied fully: if $x$ was requested, all $x$ was poured. How to deal with multiple operations then? I propose the following idea. When applying an operation, we only want to know which of the previously non-merged states become merged. Basically, we can squish all previous operations into one: just sum up the signed amounts of water. Since they all were applied fully to the non-merged states, it's completely valid. After the squish, check for the new merges. You can actually study the structure of the answers and see that they go like that: $[l, l, \\dots, l, l + 1, l + 2, \\dots, r - 1, r, \\dots, r, r]$ for some values of $l$ and $r$ such that $l \\le r$. It isn't that important, but it makes the code easier. You can basically calculate the length of the merged prefix, the length of the merged suffix, then calculate the answer at the end of the prefix in $O(n)$ and restore all answers from it. We neglected larger values of $\\mathit{cd}$ earlier, time to return to them. Another kind of limit to each operation is added: when $x$ extra water doesn't fit in another tank. Well, it doesn't change that much. It only makes more prefix/suffix merges. To come up with the exact formulas, I followed these points. Something merges on an operation $x$, when any of these holds: $c < x$ (not enough water in the first tank); $b - d < x$ (not enough space in the second tank); $d < -x$ (not enough water in the second tank); $a - c < -x$ (not enough space in the first tank). Replace all $d$ with $\\mathit{cd} - c$, and you get the constraints for prefix and suffix merges. Overall complexity: $O(n \\cdot (a + b))$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint n, a, b;\n\tscanf(\"%d%d%d\", &n, &a, &b);\n\tvector<int> v(n);\n\tforn(i, n) scanf(\"%d\", &v[i]);\n\tvector<vector<int>> ans(a + 1, vector<int>(b + 1));\n\tforn(cd, a + b + 1){\n\t\tint l = max(0, cd - b), r = min(a, cd);\n\t\tint sum = 0;\n\t\tfor (int x : v){\n\t\t\tsum += x;\n\t\t\tl = max({l, sum, cd + sum - b});\n\t\t\tr = min({r, a + sum, sum + cd});\n\t\t}\n\t\tif (l > r) l = r = max(0, cd - b);\n\t\tint res = l;\n\t\tfor (int x : v){\n\t\t\tif (x > 0)\n\t\t\t\tres -= min({res, x, b - (cd - res)});\n\t\t\telse\n\t\t\t\tres += min({cd - res, -x, a - res});\n\t\t}\n\t\tforn(c, cd + 1) if (c <= a && cd - c <= b){\n\t\t\tans[c][cd - c] = (c < l ? res : (c > r ? res + r - l : res + c - l));\n\t\t}\n\t}\n\tforn(i, a + 1){\n\t\tforn(j, b + 1)\n\t\t\tprintf(\"%d \", ans[i][j]);\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1809",
    "index": "F",
    "title": "Traveling in Berland",
    "statement": "There are $n$ cities in Berland, arranged in a circle and numbered from $1$ to $n$ in clockwise order.\n\nYou want to travel all over Berland, starting in some city, visiting all the other cities and returning to the starting city. Unfortunately, you can only drive along the Berland Ring Highway, which connects all $n$ cities. The road was designed by a very titled and respectable minister, so it is one-directional — it can only be traversed clockwise, only from the city $i$ to the city $(i \\bmod n) + 1$ (i.e. from $1$ to $2$, from $2$ in $3$, ..., from $n$ to $1$).\n\nThe fuel tank of your car holds up to $k$ liters of fuel. To drive from the $i$-th city to the next one, $a_i$ liters of fuel are needed (and are consumed in the process).\n\nEvery city has a fuel station; a liter of fuel in the $i$-th city costs $b_i$ burles. Refueling between cities is not allowed; if fuel has run out between cities, then your journey is considered incomplete.\n\nFor each city, calculate the minimum cost of the journey if you start and finish it in that city.",
    "tutorial": "The problem has a rather obvious naive solution in $O(n)$ for each starting city, but it's too slow. So we have to speed up this solution somehow. Binary lifting is one of the options, but here we have a problem that it is difficult to connect two consecutive groups of steps, because after the first group there is a certain amount of fuel left. Therefore, one of the solutions is to switch to such steps that $0$ liters of fuel remains after it. Let's consider one of such \"greedy\" steps. Suppose we are in the city $i$ with $0$ fuel, then the following situations are possible: $b_i=2$, let's buy exactly $a_i$ liters of fuel to reach the next city, then the step length is $1$ and the cost is $2a_i$; $b_i=1$ and $cnt=0$ (where $cnt$ is the maximum number such that $b_{i+1}=2$, $b_{i+2}=2$, ..., $b_{i+cnt}=2$, i.e. the number of consecutive cities with the cost $2$), let's buy exactly $a_i$ liters of fuel to reach the next city, then the step length is $1$ and the cost is $a_i$; $b_i=1$ and $cnt>0$, let's find a minimum $j$ such that $sum = a_i + a_{i+1} + \\dots + a_j \\ge k$ and $j \\le i + cnt$ (i.e. such $j$ that you can reach it by spending all $k$ of liters): $sum \\le k$, let's buy exactly $sum$ liters with the cost $1$ in the city $i$, then the step length is $j-i+1$ and the cost is $sum$; $sum > k$, let's buy $k$ liters with the cost $1$ in the city $i$, and the remainder of $sum - k$ liters with the cost $2$ in the city $j$, then the step length is $j-i+1$ and the cost is $k + 2(sum-k)$. $sum \\le k$, let's buy exactly $sum$ liters with the cost $1$ in the city $i$, then the step length is $j-i+1$ and the cost is $sum$; $sum > k$, let's buy $k$ liters with the cost $1$ in the city $i$, and the remainder of $sum - k$ liters with the cost $2$ in the city $j$, then the step length is $j-i+1$ and the cost is $k + 2(sum-k)$. Now using these types of steps, we maintain an important invariant - after each step, the amount of fuel is $0$. So we can easily calculate the total distance and cost for several consecutive steps. Which leads us to a solution using binary lifting: for each city $i$ calculate the length and cost of the path with $2^{pw}$ (for all $pw$ up to $\\log{n}$) greedy steps. And then, using this data, we can calculate the answer for each starting city in $O(\\log{n})$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nvoid solve(){\n\tint n, k;\n\tscanf(\"%d%d\", &n, &k);\n\tvector<int> a(n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tvector<int> b(n);\n\tforn(i, n) scanf(\"%d\", &b[i]);\n\t\n\tvector<long long> pr(2 * n + 1);\n\tforn(i, 2 * n) pr[i + 1] = pr[i] + a[i % n];\n\t\n\tvector<long long> dist(n);\n\tvector<long long> cost(n);\n\tint cnt = 0;\n\tfor (int i = 2 * n - 1; i >= 0; --i){\n\t\tif (i < n){\n\t\t\tif (b[i] == 2){\n\t\t\t\tdist[i] = 1;\n\t\t\t\tcost[i] = a[i] * 2;\n\t\t\t}\n\t\t\telse if (cnt == 0){\n\t\t\t\tdist[i] = 1;\n\t\t\t\tcost[i] = a[i];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tint j = lower_bound(pr.begin() + i, pr.begin() + i + cnt + 1, pr[i] + k) - pr.begin();\n\t\t\t\tassert(j > i);\n\t\t\t\tdist[i] = j - i;\n\t\t\t\tif (pr[j] - pr[i] <= k)\n\t\t\t\t\tcost[i] = pr[j] - pr[i];\n\t\t\t\telse\n\t\t\t\t\tcost[i] = 2 * (pr[j] - pr[i]) - k;\n\t\t\t}\n\t\t}\n\t\tif (b[i % n] == 2) ++cnt;\n\t\telse cnt = 0;\n\t}\n\t\n\tint pw = 0;\n\twhile ((1 << pw) <= n) ++pw;\n\t\n\tvector<vector<long long>> distk(pw, dist);\n\tvector<vector<long long>> costk(pw, cost);\n\tfor (int j = 1; j < pw; ++j) forn(i, n){\n\t\tdistk[j][i] = distk[j - 1][i] + distk[j - 1][(i + distk[j - 1][i]) % n];\n\t\tcostk[j][i] = costk[j - 1][i] + costk[j - 1][(i + distk[j - 1][i]) % n];\n\t}\n\t\n\tforn(i, n){\n\t\tint pos = i;\n\t\tlong long tot = 0;\n\t\tlong long ans = 0;\n\t\tfor (int j = pw - 1; j >= 0; --j) if (tot + distk[j][pos] <= n){\n\t\t\ttot += distk[j][pos];\n\t\t\tans += costk[j][pos];\n\t\t\tpos = (pos + distk[j][pos]) % n;\n\t\t}\n\t\tif (tot < n) ans += pr[i + n] - pr[i + tot];\n\t\tprintf(\"%lld \", ans);\n\t}\n\tputs(\"\");\n}\n\nint main(){\n\tint tc;\n\tscanf(\"%d\", &tc);\n\twhile (tc--) solve();\n}",
    "tags": [
      "binary search",
      "data structures",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1809",
    "index": "G",
    "title": "Prediction",
    "statement": "Consider a tournament with $n$ participants. The rating of the $i$-th participant is $a_i$.\n\nThe tournament will be organized as follows. First of all, organizers will assign each participant an index from $1$ to $n$. All indices will be unique. Let $p_i$ be the participant who gets the index $i$.\n\nThen, $n-1$ games will be held. In the first game, participants $p_1$ and $p_2$ will play. In the second game, the winner of the first game will play against $p_3$. In the third game, the winner of the second game will play against $p_4$, and so on — in the last game, the winner of the $(n-2)$-th game will play against $p_n$.\n\nMonocarp wants to predict the results of all $n-1$ games (of course, he will do the prediction only after the indices of the participants are assigned). He knows for sure that, when two participants with ratings $x$ and $y$ play, and $|x - y| > k$, the participant with the higher rating wins. But if $|x - y| \\le k$, any of the two participants may win.\n\nAmong all $n!$ ways to assign the indices to participants, calculate the number of ways to do this so that Monocarp can predict the results of \\textbf{all} $n-1$ games. Since the answer can be large, print it modulo $998244353$.",
    "tutorial": "We need some sort of better criterion other than \"all matches can be predicted\" first. Suppose the ratings of the participants are $r_1, r_2, \\dots, r_n$ in the order of their indices. Then, if all games are predictable, the $i$-th game should be won by the participant with the rating equal to $\\max \\limits_{j=1}^{i+1} r_j$; and in the $(i+1)$-th game, they will play against the participant with rating $r_{i+2}$. So, in order for each game to be predictable, the maximum on each prefix should be different from the next element by at least $k+1$. This is the criterion we will use. So, we will try to count the number of orderings meeting this condition. One very important observation we need to make is that, if we remove several participants with the lowest ratings from the ordering, that ordering still satisfies the condition (for each element, either the prefix before it is removed completely, or the maximum on it is unchanged). So, this allows us to construct the correct ordering by placing the sportsmen from the maximum rating to the minimum rating, and making sure that on every step, the order stays correct. Okay. Let's reverse the ratings array, and try to write the following dynamic programming: $dp_i$ is the number of correct orderings of the first $i$ sportsmen (the $i$ highest-rated sportsmen, since we reversed the ratings array). Let's try to place the next sportsman. We run into the following issue: for some orderings of the first $i$ sportsmen, it is possible to place the next one anywhere (these orderings are where the first sportsman in the ordering doesn't conflict with the sportsman we are trying to place); but for other orderings, some positions might be forbidden. And to keep track of which positions are forbidden, and for which sportsmen, we probably need some additional states for the dynamic programming, which we don't really want to since $O(n)$ states is probably the most we can allow. Okay, so let's avoid this issue entirely. We don't like the orderings where the next sportsman can't be placed anywhere, so let's find a way to \"ignore\" them: discard the previous definition of $dp_i$. Now, let $dp_i$ is the number of correct orderings of the $i$ highest-rated sportsmen where the first element in the ordering doesn't conflict with any of the elements we haven't placed yet; when we place the next sportsman, in case it becomes the first element and conflicts with some of the elements we haven't placed yet, we place those conflicting elements as well. So, this leads to the following transitions in the dynamic programming: if we place the $(i+1)$-th sportsman on any position other than the first one, there are $i$ ways to do it, and we transition from $dp_{i}$ to $dp_{i+1}$; otherwise, if we place the $(i+1)$-th sportsman on the first position, let $f(i+1)$ be the last sportsman \"conflicting\" with the sportsman $i+1$. Let's try placing all sportsmen from $i+2$ to $f(i+1)$ before placing the sportsman $i+1$. They cannot be placed on the first position (otherwise they will conflict either with each other or with the sportsman $i+1$), so the first one can be placed in $i$ ways, the second one - in $(i+1)$ ways, and so on; this product can be easily calculated in $O(1)$ by preparing factorials and inverse factorials. So, then we transition from $dp_i$ to $dp_{f(i+1)}$. There is a special case in our dynamic programming. It should start with $dp_1 = 1$, but what if the $1$-st sportsman conflicts with someone? Then the ordering of the first $i=1$ sportsmen is incorrect. In this case, the answer is $0$ since the $1$-st and the $2$-nd sportsmen are conflicting. Overall complexity of this solution is $O(n \\log MOD)$ or $O(n + \\log MOD)$ depending on your implementation.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n    return ((x + y) % MOD + MOD) % MOD;\n}\n\nint mul(int x, int y)\n{\n    return x * 1ll * y % MOD;   \n}\n\nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y)\n    {\n        if(y % 2 == 1) z = mul(z, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return z;\n}\n\nint inv(int x)\n{\n    return binpow(x, MOD - 2);    \n}\n\nint divide(int x, int y)\n{\n    return mul(x, inv(y));\n}\n\nint main()\n{\n    int n, k;\n    scanf(\"%d %d\", &n, &k);\n    vector<int> a(n);\n    for(int i = 0; i < n; i++)    \n        scanf(\"%d\", &a[i]);\n    \n    reverse(a.begin(), a.end());\n\n    vector<int> fact(n + 1);\n    fact[0] = 1;\n    for(int i = 1; i <= n; i++)\n        fact[i] = mul(fact[i - 1], i);\n\n    // for each player, we find the first player which doesn't conflict with them\n    vector<int> first_no_conflict(n);\n    for(int i = 0; i < n; i++)\n    {\n        if(i) first_no_conflict[i] = first_no_conflict[i - 1];\n        while(first_no_conflict[i] < n && a[first_no_conflict[i]] >= a[i] - k)\n            first_no_conflict[i]++;\n    }\n\n    vector<int> dp(n + 1);\n    if(a[0] - a[1] > k) dp[1] = 1;\n    for(int i = 1; i < n; i++)\n    {\n        // first choice: put a[i] on the first position\n        // then we put all which conflict with a[i] on any position other than 1\n        int no_of_conflicting = first_no_conflict[i] - i - 1;\n        // put all conflicting with a[i] on any position other than 1\n        // the first one chooses from i positions, the second - from i+1 positions, and so on\n        // so the number of ways is fact[i + no_of_conflicting - 1] / fact[i - 1]\n        dp[i + no_of_conflicting + 1] = add(dp[i + no_of_conflicting + 1], mul(dp[i], divide(fact[i + no_of_conflicting - 1], fact[i - 1])));\n\n        // second choice: put a[i] on any other position\n        dp[i + 1] = add(dp[i + 1], mul(dp[i], i));\n    }\n\n    printf(\"%d\\n\", dp[n]);\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1810",
    "index": "A",
    "title": "Beautiful Sequence",
    "statement": "A sequence of $m$ integers $a_{1}, a_{2}, \\ldots, a_{m}$ is good, if and only if there exists at least one $i$ ($1 \\le i \\le m$) such that $a_{i} = i$. For example, $[3,2,3]$ is a good sequence, since $a_{2} = 2$, $a_{3} = 3$, while $[3,1,1]$ is not a good sequence, since there is no $i$ such that $a_{i} = i$.\n\nA sequence $a$ is beautiful, if and only if there exists at least one subsequence of $a$ satisfying that this subsequence is good. For example, $[4,3,2]$ is a beautiful sequence, since its subsequence $[4,2]$ is good, while $[5,3,4]$ is not a beautiful sequence.\n\nA sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements.\n\nNow you are given a sequence, check whether it is beautiful or not.",
    "tutorial": "What is the necessary and sufficient condition? The necessary and sufficient condition for a beautiful sequence is that there exist one $i$, such that $a_{i} \\le i$. Just check the sequence for the condition.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint a[100005];\nvoid solve()\n{\n    int n;\n    scanf(\"%d\",&n);\n    for(int i  =1;i <= n;i++) scanf(\"%d\",&a[i]);\n    for(int i = 1;i <= n;i++) {\n        if(a[i] <= i) {\n            puts(\"YES\");\n            return;\n        }\n    }\n    puts(\"NO\");\n}\nint main()\n{\n    int t;scanf(\"%d\",&t);\n    while(t--) solve();\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1810",
    "index": "B",
    "title": "Candies",
    "statement": "This problem is about candy. Initially, you only have $1$ candy, and you want to have exactly $n$ candies.\n\nYou can use the two following spells in any order at most $40$ times in total.\n\n- Assume you have $x$ candies now. If you use the first spell, then $x$ candies become $2x-1$ candies.\n- Assume you have $x$ candies now. If you use the second spell, then $x$ candies become $2x+1$ candies.\n\nConstruct a sequence of spells, such that after using them in order, you will have \\textbf{exactly} $n$ candies, or determine it's impossible.",
    "tutorial": "How the binary representation changes after an operation? First, we notice that after each operation, the number of candies is always a odd number. So even numbers can not be achieved. Then consider how the binary representation changes for a odd number $x$, after turn it into $2x+1$ or $2x-1$. For the $2x + 1$ operation: $\\overline{\\dots 1}$ turns into $\\overline{\\dots 11}$. For the $2x + 1$ operation: $\\overline{\\dots 1}$ turns into $\\overline{\\dots 11}$. For the $2x - 1$ operation: $\\overline{\\dots 1}$ turns into $\\overline{\\dots 01}$. For the $2x - 1$ operation: $\\overline{\\dots 1}$ turns into $\\overline{\\dots 01}$. So, the operation is just insert a $0/1$ before the last digit. And the answer for an odd $n$ is just the binary representation of $n$, after removing the last digit.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid solve()\n{\n    int n;scanf(\"%d\",&n);\n    if(n % 2 == 0) {\n        puts(\"-1\");return;\n    }\n    vector<int> v;\n    int f = 0;\n    for(int i = 29;i >= 1;i--) {\n        if((n >> i) & 1) {\n            f = 1;\n            v.push_back(2);\n        }\n        else if(f) {\n            v.push_back(1);\n        }\n    }\n    printf(\"%d\\n\",v.size());\n    for(auto x : v) {\n        printf(\"%d \",x);\n    }\n    printf(\"\\n\");\n}\nint main()\n{\n    int t;scanf(\"%d\",&t);\n    while(t--) solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1810",
    "index": "C",
    "title": "Make It Permutation",
    "statement": "You have an integer array $a$ of length $n$. There are two kinds of operations you can make.\n\n- Remove an integer from $a$. This operation costs $c$.\n- Insert an arbitrary positive integer $x$ to any position of $a$ (to the front, to the back, or between any two consecutive elements). This operation costs $d$.\n\nYou want to make the final array a permutation of \\textbf{any} positive length. Please output the minimum cost of doing that. Note that you can make the array empty during the operations, but the final array must contain at least one integer.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Try the enumerate the length $n$ of permutation. There're too many lengths to be checked. How to decrease the amount of $n$? Firstly, we need to remove numbers such that each number appears at most once, this part of cost is unavoidable. Then, let's sort the array $a_{1},a_{2} \\dots a_{m}$ ($1\\le a_{i} < a_{2} < \\dots < a_{m}$). Secondly, assume we enumerate the length of the permutation $n$. We need to remove all the $a_{i}$ greater than $n$, and insert some numbers $x$ ($x \\le n$) but does not appear in the array $a$. We can find some $i$ such that $a_{i} \\le n < a_{i+1}$, the cost here is simply $(m-i)\\cdot a + (n - i)\\cdot b$. Here, $m$ is the length of array $a$, after removing the repeated numbers. However, $n$ can up to $10^9$ and can not be enumerated. But for all the $n \\in [a_{i} , a_{i+1})$, the smaller $n$ has a smaller cost. (see that $(m-i)\\cdot a$ do not change, and $(n-i)\\cdot b$ decreases). Thus, the possible $n$ can only be some $a_{i}$, and we can caculate the cost in $O(n)$ in total. Don't forget the special case: remove all the numbers and add a $1$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint p[100005];\ntypedef long long ll;\nvoid solve()\n{\n    int n,a,b;scanf(\"%d%d%d\",&n,&a,&b);\n    set<int> st;\n    ll sol = 0 , ans = 2e18;\n    for(int i = 1;i <= n;i++) {\n        int x;scanf(\"%d\",&x);\n        if(st.find(x) == st.end()) st.insert(x);\n        else sol += a;\n    }\n    int c = 0;\n    for(auto x : st) p[++c] = x;\n    for(int i = 1;i <= c;i++) {\n        ans = min(ans , 1LL*(p[i] - i)*b + 1LL*(c-i)*a);\n    }\n    ans = min(ans , 1LL*c*a + b) ;\n    printf(\"%lld\\n\",ans+sol);\n}\nint main()\n{\n    int t;scanf(\"%d\",&t);\n    while(t--) solve();\n}",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1810",
    "index": "D",
    "title": "Climbing the Tree",
    "statement": "The snails are climbing a tree. The tree height is $h$ meters, and snails start at position $0$.\n\nEach snail has two attributes $a$ and $b$ ($a > b$). Starting from the $1$-st day, one snail climbs the tree like this: during the daylight hours of the day, he climbs up $a$ meters; during the night, the snail rests, and he slides down $b$ meters. If on the $n$-th day, the snail reaches position $h$ for the first time (that is, the top of the tree), he will finish climbing, and we say that the snail spends $n$ days climbing the tree. Note that on the last day of climbing, the snail doesn't necessarily climb up $a$ meters, in case his distance to the top is smaller than $a$.\n\nUnfortunately, you don't know the exact tree height $h$ at first, but you know that $h$ is a positive integer. There are $q$ events of two kinds.\n\n- Event of type $1$: a snail with attributes $a$, $b$ comes and claims that he spent $n$ days climbing the tree. If this message contradicts previously adopted information (i. e. there is no tree for which all previously adopted statements and this one are true), ignore it. Otherwise, adopt it.\n- Event of type $2$: a snail with attributes $a$, $b$ comes and asks you how many days he will spend if he climbs the tree. You can only give the answer based on the information you have adopted so far. If you cannot determine the answer precisely, report that.\n\nYou need to deal with all the events in order.",
    "tutorial": "The possible $L$ is always an interval. How to maintain it? The main idea is to that for each $a,b,n$, the possible $L$ is a interval $[l,r]$. We will show how to calculate that. In the first $n-1$ days, the snail will climb $(n-1)\\cdot (a-b)$ meters. And in the daytime of the $n$-th day, the snail will climb $a$ meters. So after $n$ days, the snail climbs at most $(n-1)\\cdot (a-b) + a$ meters, which means $L \\le (n-1)\\cdot (a-b) + a$. Also, the snail can not reach $L$ before $n$ days, which means $L > (n-2)\\cdot (a-b) + a$. So $L \\in [(n-2)\\cdot (a-b) + a + 1 , (n-1)\\cdot (a-b) + a]$. $n=1$ is a special case, where $L \\in [1,a]$ . Now after each operation $1$, we can maintain a possible interval $[L_{min} , L_{max}]$. When a snail comes, we let the new $[L_{min}',L_{max}']$ be $[L_{min},L_{max}] \\cap [l,r]$, where $[l,r]$ is the possible interval for the new snail. If the new interval is empty, we ignore this information, otherwise adopt it. Now let's focus on another problem: for a fixed $L,a,b$, how to calculate the number of days the snail needs to climb? We can solve the equation $(n-2)(a-b) + a < L \\le (n-1)(a-b) + a$, and get $n - 2 < \\frac{L - a}{a - b} \\le n - 1$, which means $n$ equals to $\\lceil \\frac{L-a}{a-b} \\rceil + 1$. Still, special judge for $L \\le a$, where $n=1$ in this case. Then, for each query of type $2$, we just calculate the number of days we need for $L_{min}$ and $L_{max}$. If they are the same, output that number. Otherwise output $-1$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nvoid solve()\n{\n    int q;scanf(\"%d\",&q);\n    ll L = 1 , R = 1e18;\n    while(q--) {\n        int op;scanf(\"%d\",&op) ;\n        if(op == 1) {\n            int a,b,n;scanf(\"%d%d%d\",&a,&b,&n);\n            ll ql = 1LL*(n - 2)*(a - b) + a + 1, qr = 1LL*(n - 1)*(a - b) + a;\n            if(n == 1) ql = 1 , qr = a;\n            if(ql > R || qr < L) {\n                puts(\"0\");\n            }\n            else L = max(L , ql) , R = min(R , qr) , puts(\"1\");\n        }\n        else {\n            int a,b;scanf(\"%d%d\",&a,&b);\n            ll ans1 = max(1LL,(L - b - 1) / (a - b) + 1) , ans2 = max(1LL,(R - b - 1) / (a - b) + 1);\n            if(ans1 == ans2) printf(\"%lld\\n\",ans1);\n            else puts(\"-1\");\n        }\n    }\n    return;\n}\nint main()\n{\n    int t;scanf(\"%d\",&t);\n    while(t--) solve();\n}\n",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1810",
    "index": "E",
    "title": "Monsters",
    "statement": "There is an undirected graph with $n$ vertices and $m$ edges. Initially, for each vertex $i$, there is a monster with danger $a_{i}$ on that vertex. For a monster with danger $a_{i}$, you can defeat it if and only if you have defeated at least $a_{i}$ other monsters before.\n\nNow you want to defeat all the monsters. First, you choose some vertex $s$ and defeat the monster on that vertex (since you haven't defeated any monsters before, $a_{s}$ has to be $0$). Then, you can move through the edges. If you want to move from vertex $u$ to vertex $v$, then the following must hold: either the monster on vertex $v$ has been defeated before, or you can defeat it now. For the second case, you defeat the monster on vertex $v$ and reach vertex $v$.\n\nYou can pass the vertices and the edges any number of times. Determine whether you can defeat all the monsters or not.",
    "tutorial": "How to check whether it is possible to defeat all the monsters, starting from a fixed vertex $u$? Let $S(u)$ be the vertices set that can be reached, starting from vertex $u$. What's the relationship between $S(u)$ and $S(v)$, where $v\\in S(u)$? For some vertex set $T$, let's define $E(T)$ as the ''neighbours'' of vertex set $T$. Formally, $v \\in E(T)$ if and only if $v \\notin T$, but there exist some vertex $u$, such that there's an edge $(u,v)$ in the graph, and $u \\in T$. Now let's consider how to solve the problem for some fixed starting vertex $u$? Let's maintain the set $S(u)$ and $E(S(u))$. Initially, $S(u) = {u }$. We keep doing the procedure: choose a vertex $v \\in E(S(u))$ with minimal value $a_{v}$. If $a_{v} \\le |S(u)|$, we add $v$ into set $S(u)$, and update set $E(S(u))$ simultaneously. Since $S(u)$ is always connected during the procedure, we are actually doing such a thing: find a vertex $v$ that is ''reachable'' now with minimal value $a_{v}$, and try to defeat the monster on it. Our goal is to find some $u$ such that $|S(u)| = n$. Then let's move to a lemma: if $v \\in S(u)$, then $S(v) \\subseteq S(u)$. If it is not, consider the procedure above and the first time we add some vertex $x$ such that $x \\notin S(u)$ into $S(v)$. At this moment, $|S(v)| \\le |S(u)|$ must hold(since it's the first time we add some vertex not in $S(u)$). On the other side, $x \\in E(S(u))$ must hold, and hence $a_{x} > |S(u)| \\ge |S(v)|$. Thus, we can not add $x$ into $S(v)$. Then we can tell, if $|S(u)| < n$, then for $v \\in S(u)$, $|S(v)| < n$. So it's unnecessary to search starting from $v$. And we can construct such an algorithm: Search from $1,2,3,\\dots n$ in order, if some $i$ has been included in some $S(j)$ before, do not search from it. Surprisingly, this algorithm is correct. We can prove it's time complexity. For each vertex $v$, if $v \\in S(u)$ now, and when searching from vertex $u'$, $v$ is add into $S(u')$ again, then $|S(u')| > 2|S(u)|$. Thus, one vertex can not be visited more than $log(n)$ times, which means the time complexity is $O(nlog^2(n))$. This problem has many other methods to solve. This one I think is the easiest to implement.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint vis[200005];\nint n , m;\nvector<int> E[200005];\nint a[200005];\nint T = 1;\nbool span(int u)\n{\n    set<pair<int,int> > st;\n    st.insert(pair<int,int>{a[u] , u});\n    int amt = 0 , df = 0;\n    while(st.size()) {\n        auto pa = (*st.begin()) ; vis[pa.second] = u;\n        if(pa.first > df) {return (amt == n);}\n        st.erase(st.begin());\n        amt++ ; df++ ;\n        for(auto v : E[pa.second]) {\n            if(vis[v] < u) {\n                st.insert(pair<int,int>{a[v] , v});\n            }\n        }\n    }\n    return (amt == n);\n}\nvoid solve()\n{\n    scanf(\"%d%d\",&n,&m);\n    for(int i= 1;i <= n;i++) scanf(\"%d\",&a[i]) , vis[i] = 0, E[i].clear();\n    for(int i = 1;i <= m;i++) {\n        int u,v;scanf(\"%d%d\",&u,&v);E[u].push_back(v) ; E[v].push_back(u);\n    }\n    for(int i = 1;i <= n;i++) {\n        if(a[i] == 0 && !vis[i]) {\n            if(span(i)){puts(\"YES\");return;}\n        }\n    }\n    puts(\"NO\");\n}\nint main()\n{\n    int t;scanf(\"%d\",&t);\n    while(t--) solve();\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1810",
    "index": "F",
    "title": "M-tree",
    "statement": "A rooted tree is called good if every vertex of the tree either is a leaf (a vertex with no children) or has exactly $m$ children.\n\nFor a good tree, each leaf $u$ has a positive integer $c_{u}$ written on it, and we define the value of the leaf as $c_{u} + \\mathrm{dep}_{u}$, where $\\mathrm{dep}_{u}$ represents the number of edges of the path from vertex $u$ to the root (also known as the depth of $u$). The value of a good tree is the \\textbf{maximum} value of all its leaves.\n\nNow, you are given an array of $n$ integers $a_{1}, a_{2}, \\ldots, a_{n}$, which are the integers that should be written on the leaves. You need to construct a good tree with $n$ leaves and write the integers from the array $a$ to all the leaves. Formally, you should assign each leaf $u$ an index $b_{u}$, where $b$ is a permutation of length $n$, and represent that the integer written on leaf $u$ is $c_u = a_{b_{u}}$. Under these constraints, you need to \\textbf{minimize} the value of the good tree.\n\nYou have $q$ queries. Each query gives you $x$, $y$ and changes $a_{x}$ to $y$, and after that, you should output the minimum value of a good tree based on the current array $a$.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Can you solve a single query using binary search? How to check the answer? Try to find a closed formula for this problem. Let $num_{i}$ be the number of occurances of integer $i$ in the array $a$. To check whether the answer can be $\\le x$ or not, we can do the following greedy: Starting with a single vertex written $x$, which is the root. For each $i$(from large ones to small ones), if the number of current leaves is smaller than $num_{i}$, then we can not make the answer $\\le x$. Otherwise, let $num_{i}$ leaves stop, and other leaves ''grow'' $m$ children each(these vertices are no longer leaves, but their children are). We can discover that each round, the ''stopped'' vertices have $dep = x - i$, which represents their value is $x$. We can use the following code to calculate it. Since a negtive number multiplies $m$ is still a negtive number, the code can be as following: Find out something? The final $d$ is just $m^x - \\sum_{i=1}^{x}{num_{i} \\cdot m^i}$, which represents it's equivalent to checking $m^x \\ge \\sum_{i=1}^{n}{m^{a_{i}}}$! So now the answer is just $\\lceil log_{m}{\\sum_{i=1}^{n}{m^{a_{i}}}} \\rceil$. This is the highest bit plus one of $\\sum{m^{a_{i}}}$ in $m$-base representation(except for that it's just some $m^x$. In this case the answer is $x$ but not $x+1$). We can use a segment tree, supporting interval min/max query and interval covering to solve the question.",
    "code": "using namespace std;\nint n , m , q;\nconst int N = 2e5 + 40;\nint num[N];\nint a[N];\nint cov[N*4 + 5] , mx[N*4 + 5] , mn[N*4 + 5];\nvoid rec(int u)\n{\n    mx[u] = max(mx[u<<1|1] , mx[u<<1]) ; mn[u] = min(mn[u<<1|1] , mn[u<<1]);\n}\nvoid pd(int u)\n{\n    if(cov[u] != -1) {\n        cov[u<<1] = mn[u<<1] = mx[u<<1] = cov[u];\n        cov[u<<1|1] = mn[u<<1|1] = mx[u<<1|1] = cov[u];\n        cov[u] = -1;\n    }\n    return;\n}\nvoid build(int u,int l,int r)\n{\n    cov[u] = -1;\n    if(l == r) {mn[u] = mx[u] = num[l] ; return;}\n    build(u<<1 , l , (l + r >> 1)) ; build(u<<1|1 , (l + r >> 1) + 1 , r);\n    rec(u) ; return;\n}\nvoid modify(int u,int l,int r,int ql,int qr,int v)\n{\n    if(ql <= l && qr >= r) {\n        cov[u] = mn[u] = mx[u] = v; return;\n    }\n    pd(u);\n    int md = (l + r>> 1);\n    if(ql <= md) modify(u<<1 , l , md , ql , qr ,v);\n    if(qr > md) modify(u<<1|1 , md +1 , r , ql , qr , v);\n    rec(u);\n    return;\n}\n \nint qumax(int u,int l,int r,int ql)\n{\n    if(mn[u] == m - 1) return -1;\n    if(l == r) return l;\n    pd(u);\n    int md = (l + r>> 1);\n    if(ql > md) return qumax(u<<1|1 , md + 1 , r , ql);\n    if(ql == l) {\n        if(mn[u<<1] < m - 1) return qumax(u<<1 , l , md , ql);\n        return qumax(u<<1|1 , md + 1 , r , md + 1);\n    }\n    int w = qumax(u<<1 , l , md , ql) ;\n    if(w == -1) return qumax(u<<1|1 , md + 1 , r , md + 1);\n    return w;\n}\nint qumin(int u,int l,int r,int ql)\n{\n    if(mx[u] == 0) return -1;\n    if(l == r) return l;\n    pd(u);\n    int md = (l + r>> 1) ;\n    if(ql > md) return qumin(u<<1|1 , md + 1 , r , ql);\n    if(ql == l) {\n        if(mx[u<<1] > 0) return qumin(u<<1 , l , md , ql);\n        return qumin(u<<1|1 , md + 1 , r , md + 1);\n    }\n    int w = qumin(u<<1 , l , md , ql);\n    if(w == -1) return qumin(u<<1|1 , md + 1 , r , md + 1);\n    return w;\n}\n \nint qmax(int u,int l,int r,int ql,int qr)\n{\n    if(ql <= l && qr >= r) {\n        return mx[u];\n    }\n    pd(u);\n    int md = (l + r>> 1) , ans = 0;\n    if(ql <= md) ans = max(ans , qmax(u<<1 , l , md , ql , qr ));\n    if(qr > md) ans = max(ans , qmax(u<<1|1 , md +1 , r , ql , qr));\n    return ans;\n}\nint qmin(int u,int l,int r,int ql,int qr)\n{\n    if(ql <= l && qr >= r) {\n        return mn[u];\n    }\n    pd(u);\n    int md = (l + r>> 1) , ans = 1e9;\n    if(ql <= md) ans = min(ans , qmin(u<<1 , l , md , ql , qr ));\n    if(qr > md) ans = min(ans , qmin(u<<1|1 , md +1 , r , ql , qr));\n    return ans;\n}\nint ask(int u,int l,int r)\n{\n    if(l == r) return l;\n    int md = (l + r >> 1);\n    pd(u);\n    if(mx[u<<1|1] == 0) return ask(u<<1 , l , md);\n    return ask(u<<1|1 , md + 1 , r) ;\n}\nint get()\n{\n    int highbit = ask(1 , 1 , n+35);\n    if(highbit == 1 || qmax(1 , 1 , n+35 , 1 , highbit - 1) == 0) return highbit;\n    return highbit + 1;\n}\nvoid add(int u)\n{\n    int l = qumax(1 , 1 , n + 35 , u);\n    if(l > u) modify(1 , 1 , n+35 , u , l - 1 , 0) ;\n    modify(1 , 1 , n+35 , l , l , qmax(1 , 1 , n + 35 , l , l ) + 1);\n    return;\n}\nvoid sub(int u)\n{\n    int l = qumin(1 , 1 , n + 35 , u);\n    if(l > u) modify(1 , 1 , n+35 , u , l - 1 , m - 1) ;\n    modify(1 , 1 , n+35 , l , l , qmax(1 , 1 , n + 35 , l , l ) - 1);\n    return;\n}\nvoid solve()\n{\n    scanf(\"%d%d%d\",&n,&m,&q);\n    for(int i = 1;i <= n + 35;i++) num[i] = 0;\n    for(int i = 1;i <= n;i++) {\n        scanf(\"%d\",&a[i]);num[a[i]]++;\n    }\n    for(int i = 1;i <= n + 35;i++) {\n        num[i + 1] += num[i] / m;num[i] %= m;\n    }\n    build(1 , 1 , n + 35);\n    while(q--) {\n        int u , v;scanf(\"%d%d\",&u,&v);\n        sub(a[u]) ; a[u] = v; add(a[u]) ;\n        printf(\"%d%c\",get(), \" \\n\"[q == 0]);\n    }\n    return;\n}\nint main()\n{\n    int t;scanf(\"%d\",&t);\n    while(t--) solve();\n}\n",
    "tags": [
      "data structures",
      "math",
      "sortings",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1810",
    "index": "G",
    "title": "The Maximum Prefix",
    "statement": "You're going to generate an array $a$ with a length of at most $n$, where each $a_{i}$ equals either $1$ or $-1$.\n\nYou generate this array in the following way.\n\n- First, you choose some integer $k$ ($1\\le k \\le n$), which decides the length of $a$.\n- Then, for each $i$ ($1\\le i \\le k$), you set $a_{i} = 1$ with probability $p_{i}$, otherwise set $a_{i} = -1$ (with probability $1 - p_{i}$).\n\nAfter the array is generated, you calculate $s_{i} = a_{1} + a_{2} + a_{3}+ \\ldots + a_{i}$. Specially, $s_{0} = 0$. Then you let $S$ equal to $\\displaystyle \\max_{i=0}^{k}{s_{i}}$. That is, $S$ is the maximum prefix sum of the array $a$.\n\nYou are given $n+1$ integers $h_{0} , h_{1}, \\ldots ,h_{n}$. The score of an array $a$ with maximum prefix sum $S$ is $h_{S}$. Now, for each $k$, you want to know the expected score for an array of length $k$ modulo $10^9+7$.",
    "tutorial": "How to calculate the maximal prefix sum? One possible way is let $f_{n+1} = 0$ and $f_{i}=max(f_{i+1},0)+a_{i}$. Consider this method to find maximal prefix sum: let $f_{n+1} = 0$ and $f_{i}=max(f_{i+1},0)+a_{i}$. We can discover that the only influence $[a_{i+1},a_{i+2} \\dots a_{n}]$ has(to the whole array's maximal prefix sum) is its maximal prefix sum. Then we let $dp_{i,j}$ be : the expect score we can get, if we assume that the maximal prefix sum of $[a_{i+1},a_{i+2} \\dots a_{n}]$ is $j$ (Read the definition carefully). The answer for each $k$ is $dp_{k,0}$, since if the maximal prefix sum for $[a_{k+1},a_{k+2} \\dots a_{n}]$ is $0$, that is equivalent to removing them from the array. And also $dp_{0,j} = h_{j}$. And we have $dp_{i,j} = p_{i}\\cdot dp_{i-1,j+1} + (1 - p_{i})\\cdot dp_{i-1,max(j-1,0)}$. The first section represents chosing $a_{i} = 1$ and the second one represents chosing $a_{i} = -1$. We also have other solutions, using inclusion-exclusion or generate function. Actually all the testers' solutions differs from each other.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int mod = 1e9 + 7;\nconst int N = 5005;\nint p[N] , q[N];\nint n;\nint f[N][N];\nint h[N];\nint fpow(int a,int b)\n{\n    int ans = 1;\n    while(b){\n        if(b & 1) ans = 1LL*ans*a%mod;\n        a = 1LL*a*a%mod;b >>= 1;\n    }\n    return ans;\n}\nvoid solve()\n{\n    scanf(\"%d\",&n);\n    for(int i = 1;i <= n;i++) {\n        int a,b;scanf(\"%d%d\",&a,&b);\n        p[i] = 1LL*a*fpow(b , mod - 2) % mod;\n        q[i] = (1 - p[i] + mod) % mod;\n    }\n    for(int i = 0;i <= n;i++) scanf(\"%d\",&h[i]);\n    for(int i = 0;i <= n;i++) f[0][i] = h[i];\n    for(int i = 1;i <= n;i++) {\n        for(int j = 0;j <= n;j++) {\n            f[i][j] = (1LL*p[i]*f[i - 1][j + 1] + 1LL*q[i]*f[i - 1][max(0 , j - 1)] ) % mod;\n        }\n        printf(\"%d \",f[i][0]);\n    }\n    printf(\"\\n\");\n    return;\n}\nint main()\n{\n    int t;scanf(\"%d\",&t);\n    while(t--) solve();\n    return 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1810",
    "index": "H",
    "title": "Last Number",
    "statement": "You are given a multiset $S$. Initially, $S = \\{1,2,3, \\ldots, n\\}$.\n\nYou will perform the following operation $n-1$ times.\n\n- Choose the largest number $S_{\\text{max}}$ in $S$ and the smallest number $S_{\\text{min}}$ in $S$. Remove the two numbers from $S$, and add $S_{\\text{max}} - S_{\\text{min}}$ into $S$.\n\nIt's easy to show that there will be exactly one number left after $n-1$ operations. Output that number.",
    "tutorial": "Actually I don't know how to hint. Try to find some rules related to $\\frac{\\sqrt{5}+1}{2}$, fibnacci or similar Assume that the moment before the $x$-th operation(but after $x-1$-th), the first time we have $S_{max} \\le 2S_{min}$. Let's divide the operation into two part: before $x$ and equal or after $x$. Still, at the moment just before the $x$-th operation, let us sort the elements in the multiset in non-decreasing order, $S_{0},S_{1} \\dots S_{k}$. We will show that the answer is $S_{0}\\cdot (-1)^{k} + \\sum_{i=1}^{k}{S_{i}\\cdot (-1)^{i+1}}$. This lemma is based on the fact that, after each operation(which is after $x$-th), $S_{1}$ to $S_{k-1}$ will not change, $S_{k}$ is removed, and $S_{0}$ turn to $S_{k}-S_{0}$. Which also means $S_{k} - S_{0} \\le S_{1}$ always holds. At the very beginning, $S_{k} - S_{0} \\le S_{0} \\le S_{1}$ obviously holds. And we can observe that either $S_{k} = S_{k-1}$ or $S_{k-1} = S_{k} - 1$. When $S_{k-1} = S_{k}$, the new $S_{0}$ after two operations is equal to the old $S_{0}$. When $S_{k-1} = S_{k} - 1$, the new $S_{0}$ after two operations is equal to the old $S_{0}$ minus one. So if we write the $S_{0}$ as an array $t_{0} , t_{1} \\ldots t_{k}$ by time order, $t_{i+2} \\le t_{i}$ always holds. Thus, $t_{i} \\le S_{1}$ always holds. Let $d_{i}$ be the $S_{max}$ value in the $i$-th operation. Let's prove that before the $x$-th operation, $d_{i} = n-\\lceil \\frac{i}{\\phi} \\rceil + 1$, where $\\phi = \\frac{\\sqrt{5} + 1}{2}$. We prove this by Mathematical induction. One fact should be known that during these operations, $S_{min} = i$ always holds for the $i$-th operation(since $S_{max} - S_{min} > S_{min}$). For $i=1$, it is true because $d_{1} = n$ and $n - \\lceil \\frac{1}{\\phi} \\rceil + 1 = n$. Assume for $i\\le k$, it is true. Still use the fact that $d_{k+1} = d_{k}$ or $d_{k+1} = d_{k} + 1$. The necessary and sufficient condition for $d_{k+1} > d_{k}$ is all the numbers greater or equal to $d_{k}$ is ''used''. How many numbers are there? We have $n - d_{k} + 1$ numbers from the original multiset, and some numbers that occurs during the operations, which are the number of $j$ satisfying $d_{j} - j \\ge d_{k}$. Thus, $d_{k+1} > d_{k}$ is equivalent to: $\\space \\space \\space \\space \\sum_{j=1}^{k}{[d_{j} - j \\ge d_{k}]} + n - d_{k} + 1 = k$ $\\Leftrightarrow \\sum_{j=1}^{k}{[d_{j} - j \\ge d_{k}]} = k - \\lceil \\frac{k}{\\phi} \\rceil$ $\\Leftrightarrow \\sum_{j=1}^{k}{[d_{j} - j \\ge d_{k}]} = \\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor$ $\\Leftrightarrow \\sum_{j=1}^{k}{[\\lceil \\frac{j}{\\phi} + j \\rceil \\le \\lceil \\frac{k}{\\phi} \\rceil]} = \\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor$ $\\Leftrightarrow \\sum_{j=1}^{k}{[\\lceil \\frac{j(\\phi + 1)}{\\phi} \\rceil \\le \\lceil \\frac{k}{\\phi} \\rceil]} = \\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor$ Note that $\\frac{j(\\phi + 1)}{\\phi}$ is always increasing, which means that formula $\\lceil \\frac{j(\\phi + 1)}{\\phi} \\rceil \\le \\lceil \\frac{k}{\\phi} \\rceil$ holds for $j = \\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor$, but does not hold for $j = \\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor + 1$. The first equation, $\\lceil \\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor \\cdot \\frac{\\phi + 1}{\\phi} \\rceil \\le \\lceil \\frac{k}{\\phi} \\rceil$ always holds. Because $\\frac{\\phi - 1}{\\phi}\\cdot \\frac{\\phi + 1}{\\phi} = \\frac{1}{\\phi}$, and ofcourse $\\lfloor ka \\rfloor b \\le kab$. Let's do the research when the second equation does not hold. Let $m_{1} = \\lbrace \\frac{i(\\phi - 1)}{\\phi} \\rbrace$, and $m_{2} = \\lbrace \\frac{i}{\\phi} \\rbrace$ ($\\lbrace x \\rbrace = x - \\lfloor x \\rfloor$). Note that $m_{1} + m_{2} = 1$, since $\\lbrace \\frac{i(\\phi - 1)}{\\phi} \\rbrace = \\lbrace i - \\frac{i}{\\phi} \\rbrace$. The topic we are going to research is when $\\lceil (\\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor + 1) \\cdot \\frac{\\phi + 1}{\\phi}\\rceil > \\lceil \\frac{k}{\\phi} \\rceil$ hold(which also means, $d_{k+1} > d_{k}$). $\\Leftrightarrow \\lceil (\\frac{i(\\phi - 1)}{\\phi} - m_{1}) \\cdot \\frac{\\phi+1}{\\phi} + \\frac{\\phi + 1}{\\phi} \\rceil > \\lceil \\frac{i}{\\phi} \\rceil$ $\\Leftrightarrow \\lceil \\frac{i}{\\phi} - m_{1} \\cdot \\frac{\\phi+1}{\\phi} + \\frac{\\phi + 1}{\\phi} \\rceil > \\lceil \\frac{i}{\\phi} \\rceil$ $\\Leftrightarrow \\lceil \\frac{i}{\\phi} - (1 - m_{1}) \\cdot \\frac{\\phi+1}{\\phi} \\rceil > \\lceil \\frac{i}{\\phi} \\rceil$ $\\Leftrightarrow (1 - m_{1}) \\cdot \\frac{\\phi+1}{\\phi} > 1 - m_{2}$ $\\Leftrightarrow \\frac{\\phi+1}{\\phi} > \\frac{1}{m_{2}} - 1$ $\\Leftrightarrow m_{2} > \\frac{\\phi}{2\\phi + 1}$ Then let's focus on, if $d_{k+1} = n - \\lceil \\frac{k+1}{\\phi} \\rceil + 1$, when will $d_{k + 1} > d_{k}$ hold? It's easy to find when $m_{2} > 1 - \\frac{1}{\\phi}$, $d_{k+1} > d_{k}$ holds. And since $\\phi = \\frac{\\sqrt{5} + 1}{2}$, we can tell $\\frac{\\phi}{2\\phi + 1} = 1 - \\frac{1}{\\phi}$. Thus, we proved the topic, for all $k < x$(before the $x$-th operation), $d_{k} = n - \\lceil \\frac{k}{\\phi} \\rceil + 1$. Then, by solve $n - \\lceil \\frac{x}{\\phi} \\rceil + 1 \\le 2x$, we can get $x = \\lceil (n+1)\\frac{\\phi - 1}{\\phi} \\rceil$. Now let's prove for $k \\ge x$, $d_{k} = n - \\lceil \\frac{k}{\\phi} \\rceil + 1$ also holds ! Using the similar idea as lemma 2, find out when $d_{k + 1} > d_{k}$ holds. However, at this time, only $j \\le x - 1$ will contribute(since for those $j > x - 1$, according to lemma 1, they become the minimal one and do not contribute to anything). Similarly, that is $\\sum_{j=1}^{x - 1}{[d_{j} - j \\ge d_{k}]} = \\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor$. Seems to be different this time, but actually they are the same, because $\\lfloor \\frac{k(\\phi - 1)}{\\phi} \\rfloor \\le x - 1$ holds(the proving is easy, leave it as a exercise). This condition holds means that we can use the same method in lemma 2 to prove it. Till now, the lemmas told us the solving the problem is actually solving something like $\\sum{(-1)^{i} \\cdot (n- \\lceil \\frac{i}{\\phi} \\rceil + 1)}$. We can divide them into positive part and negtive part, and then solving $\\sum{\\lfloor C\\cdot i \\rfloor}$, where $i$ range from some $l$ to $r$, and $C$ is a irrational constant. Since $n$ is not very large, we can approximate $C$ by $\\frac{a}{b}$, where $a,b$ are integers, and turn it into a traditional task. (Maybe it is called floor sum or something like, I'm not sure about the algorithm's english name). The marvelous jiangly told me $a,b$ in long long range is enough. But the tester used int128. We can dig more about the $\\phi$. Let $b_{i} = S_{i+1} - S_{i}$ (sorted, before the $x$-th operation), and what we care is $b_{1} + b_{3} + b_{5}\\dots$. We can find that array $b$ is actually a consecutive substring of fibonacci string. More over, let $F_{n}$ be the starting point of array $b$ in the fibonacci string when the initial size is $n$, we have the conclusion for $n \\ge 5$: $F[5 \\dots inf] = [3,0],[4,1],[8,0],[12,1] \\dots [f_{i+3} + (-1)^{i+1} , 1 + (-1)^{i}]$, where $f_{i} = f_{i-1} + f_{i-2} , f_{1} = f_{2} = 1$ . $[r,l]$ represents a list of numbers $[r,r-1,r-2 \\dots l+1,l]$. Now the only left problem is to find the prefix sum of fibonacci string(of even positions, or of odd positions). This is quite a simple task by using any $log(n)$ or $log^2(n)$ solution.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint l[500];\nint fib[500];\nint evenfib[500];\nint getsum(int i,int n) ///1-index\n{\n    if(n == 0) return 0;\n    if(i <= 1) return fib[i];\n    if(n <= l[i - 2]) return getsum(i - 2,  n);\n    return fib[i - 2] + getsum(i - 1 , n - l[i - 2]);\n}\nint getsum2(int i,int n,int p) ///n = 2*k+p, 0-index\n{\n    if(i <= 0) return 0;\n    if(i <= 1) return 1^p;\n \n    if(n <= l[i - 2] - 1) return getsum2(i - 2 , n , p);\n    int L;\n    if(p) L = (l[i - 2] - !(l[i-2]&1));\n    else L = (l[i- 2] - (l[i - 2] & 1));\n    int ans ;\n    if(p) ans = fib[i - 2] - evenfib[i - 2];\n    else ans = evenfib[i - 2];\n    ans += getsum2(i - 1 , n - l[i - 2] , p ^ ((l[i - 2] & 1)));\n    return ans;\n}\nint getfib(int n) ///0-index\n{\n    if(n <= 0) return 0;\n    n++;\n    int ans = 0;\n    int i;\n    for(i = 0;l[i] <= n;i++) {\n        ans += fib[i] ; n -= l[i];\n    }\n    return ans + getsum(i , n);\n}\nint get_even(int n) ///n = 2*k\n{\n    n++;\n    int ans = 0;\n    int i , lbefore = 0;\n    for(i = 0;l[i] <= n;i++) {\n        if(lbefore) ans += fib[i] - evenfib[i];\n        else ans += evenfib[i];\n        lbefore ^= (l[i]&1);\n        n -= l[i];\n    }\n    if(n) ans += getsum2(i , n - 1, lbefore);\n    return ans;\n}\nconst double phi = (3 - sqrt(5)) / 2;\nconst double eps = 1e-6;\nint getstart(int n)\n{\n    if(n == 3) return 0;\n    if(n == 4) return 1;\n    n -= 4;\n    int i;\n    for(i = 1;1;i++) {\n        int lft ;\n        if(i & 1) lft = fib[i + 3] + 1;\n        else lft = fib[i + 3] - 1;\n        if(n <= lft) break;\n        n -= lft;\n    }\n    int start ;\n    if(i & 1) start = fib[i + 3] - n + 1;\n    else start = fib[i + 3] - n;\n    return start;\n}\ntypedef long long ll;\nconst int L = 95;\nint a[120] = {8,0,6,0,1,8,5,9,7,2,9,7,2,9,2,0,5,5,7,9,0,1,8,1,7,3,5,9,3,7,4,9,2,7,7,3,1,5,5,4,6,8,7,3,1,7,3,2,4,9,1,0,2,8,0,9,6,9,7,2,2,8,8,1,6,3,4,3,6,5,6,1,3,1,4,5,9,7,1,5,1,5,0,1,0,5,2,1,1,0,6,6,9,1,8,3};\nll b[120];\ndouble cal(int n)\n{\n    memset(b,0,sizeof(b));\n    for(int i = 0;i <= L;i++) b[i] = 1LL*n*a[i];\n    for(int i = 0;i <= L + 15;i++) {\n        b[i + 1] += (b[i] / 10) ; b[i] %= 10;\n    }\n    int ans = 0;\n    for(int i = L + 11;i >= L + 1;i--) ans = (ans * 10 + b[i]) ;\n    return ans;\n}\nvoid solve(int n)\n{\n    if(n <= 2) {puts(\"1\");return;}\n    int v = cal(n);\n    int len = n - v;v++;\n    int start = getstart(n);\n    int ans = 0;\n    if(len & 1) {\n        ans = v; ///[start + 1 , start + 3...start + len - 2]\n        if(start & 1) ans -= (get_even(start + len - 2) - get_even(start - 1));\n        else ans -= (getfib(start + len - 1) - get_even(start + len - 1) - getfib(start) + get_even(start));\n    }\n    else {\n        ans = getfib(start + len - 2) - getfib(start - 1);\n        ///[start + 1 , start + len - 3]\n        if(start & 1) ans -= (get_even(start + len - 3) - get_even(start - 1));\n        else ans -= (getfib(start + len - 2) - get_even(start + len - 2) - getfib(start) + get_even(start));\n    }\n    printf(\"%d\\n\",ans);return;\n}\nint main()\n{\n    l[0] = l[1] = 1;\n    fib[0] = 0 , fib[1] = 1;\n    evenfib[1] = 1;\n    for(int i = 2;l[i-1] <= 1000000000;i++) {\n        l[i] = l[i - 1] + l[i - 2];\n        fib[i] = fib[i - 1] + fib[i - 2];\n        if(l[i - 2] & 1) evenfib[i] = evenfib[i - 2] + fib[i - 1] - evenfib[i - 1];\n        else evenfib[i] = evenfib[i - 2] + evenfib[i - 1];\n    }\n \n    int t;scanf(\"%d\",&t);\n    while(t--) {\n        int n;scanf(\"%d\",&n);solve(n);\n    }\n    return 0;\n}\n",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1811",
    "index": "A",
    "title": "Insert Digit",
    "statement": "You have a \\textbf{positive} number of length $n$ and one additional digit.\n\nYou can insert this digit anywhere in the number, including at the beginning or at the end.\n\nYour task is to make the result as large as possible.\n\nFor example, you have the number $76543$, and the additional digit is $4$. Then the maximum number you can get is $765443$, and it can be obtained in two ways — by inserting a digit after the $3$th or after the $4$th digit of the number.",
    "tutorial": "Note that numbers of the same length are compared lexicographically. That is, until some index the numbers will match, and then the digit in our number should be greater. Let's write out the numbers $s_1, s_2, \\ldots s_i$ until $s_i \\ge d$. As soon as this condition is false or the line ends, insert the digit $d$. We got the lexicographically maximum number, which means just the maximum number.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nvoid solve() {\n    int n, d;\n    cin >> n >> d;\n    string s;\n    cin >> s;\n    for (int i = 0; i < n; ++i) {\n        if (s[i] - '0' >= d) {\n            cout << s[i];\n        } else {\n            cout << d;\n            for (int j = i; j < n; ++j) {\n                cout << s[j];\n            }\n            cout << '\\n';\n            return;\n        }\n    }\n    cout << d << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1811",
    "index": "B",
    "title": "Conveyor Belts",
    "statement": "Conveyor matrix $m_n$ is matrix of size $n \\times n$, where $n$ is an \\textbf{even} number. The matrix consists of concentric ribbons moving clockwise.\n\nIn other words, the conveyor matrix for $n = 2$ is simply a matrix $2 \\times 2$, whose cells form a cycle of length $4$ clockwise. For any natural $k \\ge 2$, the matrix $m_{2k}$ is obtained by adding to the matrix $m_{2k - 2}$ an outer layer forming a clockwise cycle.\n\n\\begin{center}\n{\\small The conveyor matrix $8 \\times 8$}.\n\\end{center}\n\nYou are standing in a cell with coordinates $x_1, y_1$ and you want to get into a cell with coordinates $x_2, y_2$. A cell has coordinates $x, y$ if it is located at the intersection of the $x$th row and the $y$th column.\n\nStanding on some cell, every second you will move to the cell next in the direction of movement of the tape on which you are. You can also move to a neighboring cell by spending one unit of energy. Movements happen instantly and you can make an unlimited number of them at any time.\n\nYour task is to find the minimum amount of energy that will have to be spent to get from the cell with coordinates $x_1, y_1$ to the cell with coordinates $x_2, y_2$.\n\nFor example, $n=8$ initially you are in a cell with coordinates $1,3$ and you want to get into a cell with coordinates $6, 4$. You can immediately make $2$ movements, once you are in a cell with coordinates $3, 3$, and then after $8$ seconds you will be in the right cell.",
    "tutorial": "Note that the conveyor matrix $n \\times n$ consists of $n$ cycles, through each of which we can move without wasting energy. Now you need to find the distance between the cycles where the start and end cells are located. In one step from any cycle, you can go either to the cycle that is closer to the edge of the matrix, or to the cycle that is further from the edge of the matrix. It turns out that it is enough to find on which cycles there are cells on the edge and take their difference modulo.",
    "code": "def layer(n, x, y):\n    return min([x, y, n + 1 - x, n + 1 - y])\n\n\ndef solve():\n    n, x1, y1, x2, y2 = map(int, input().split())\n    print(abs(layer(n, x1, y1) - layer(n, x2, y2)))\n\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1811",
    "index": "C",
    "title": "Restore the Array",
    "statement": "Kristina had an array $a$ of length $n$ consisting of non-negative integers.\n\nShe built a new array $b$ of length $n-1$, such that $b_i = \\max(a_i, a_{i+1})$ ($1 \\le i \\le n-1$).\n\nFor example, suppose Kristina had an array $a$ = [$3, 0, 4, 0, 5$] of length $5$. Then she did the following:\n\n- Calculated $b_1 = \\max(a_1, a_2) = \\max(3, 0) = 3$;\n- Calculated $b_2 = \\max(a_2, a_3) = \\max(0, 4) = 4$;\n- Calculated $b_3 = \\max(a_3, a_4) = \\max(4, 0) = 4$;\n- Calculated $b_4 = \\max(a_4, a_5) = \\max(0, 5) = 5$.\n\nAs a result, she got an array $b$ = [$3, 4, 4, 5$] of length $4$.You only know the array $b$. Find any matching array $a$ that Kristina may have originally had.",
    "tutorial": "To solve the problem, you can build an array $a$ as follows $a_1 = b_1$ $a_i = \\min(b_{i-1}, b_i)$ at $2 \\le i \\le n-1$ $a_n = b_{n-1}$ Let's show that from the constructed array $a$ we can get an array $B$ equal to the original array $b$: $B_1 = \\max(a_1, a_2) = \\max(b_1, \\min(b_1, b_2))$ If $b_1 \\gt b_2$, then $\\max(b_1, b_2) = b_1$ If $b_2 \\ge b_1$, then $\\max(b_1, b_1) = b_1$ So $B_1 = b_1$ If $b_1 \\gt b_2$, then $\\max(b_1, b_2) = b_1$ If $b_2 \\ge b_1$, then $\\max(b_1, b_1) = b_1$ So $B_1 = b_1$ $B_i = \\max(a_i, a_{i+1}) = \\max(\\min(b_{i-1}, b_i), \\min(b_i, b_{i+1}))$ at $2 \\le i \\le n-2$ If $b_{i+1} \\ge b_i$ and $b_{i-1} \\ge b_i$, then $\\max(\\min(b_{i-1}, b_i), \\min(b_i, b_{i+1}) = \\min(b_i, b_i) = b_i$ If $b_{i+1} \\ge b_i \\ge b_{i-1}$, then $\\max(b_{i-1}, b_i) = b_i$ If $b_{i-1} \\ge b_i \\ge b_{i+1}$, then $\\max(b_i, b_{i+1}) = b_i$ By the construction of the array $b$ it is not possible that $b_i \\gt b_{i+1}$ and $b_i \\gt b_{i-1}$. So $B_i = b_i$ If $b_{i+1} \\ge b_i$ and $b_{i-1} \\ge b_i$, then $\\max(\\min(b_{i-1}, b_i), \\min(b_i, b_{i+1}) = \\min(b_i, b_i) = b_i$ If $b_{i+1} \\ge b_i \\ge b_{i-1}$, then $\\max(b_{i-1}, b_i) = b_i$ If $b_{i-1} \\ge b_i \\ge b_{i+1}$, then $\\max(b_i, b_{i+1}) = b_i$ By the construction of the array $b$ it is not possible that $b_i \\gt b_{i+1}$ and $b_i \\gt b_{i-1}$. So $B_i = b_i$ $B_{n-1} = \\max(a_{n-1}, a_n) = \\max(\\min(b_{n-2}, b_{n-1}), b_{n-1})$ If $b_{n-2} \\gt b_{n-2}$, then $\\max(b_{n-1}, b_{n-1}) = b_{n-1}$ If $b_{n-1} \\ge b_{n-2}$, then $\\max(b_{n-2}, b_{n-1}) = b_{n-1}$ So $B_{n-1} = b_{n-1}$ If $b_{n-2} \\gt b_{n-2}$, then $\\max(b_{n-1}, b_{n-1}) = b_{n-1}$ If $b_{n-1} \\ge b_{n-2}$, then $\\max(b_{n-2}, b_{n-1}) = b_{n-1}$ We get that $B_i = b_i$ for $1 \\le i \\le n-1$, so $B = b$ and array $a$ is built correctly.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int>b(n-1), a;\n    for(int i = 0; i < n - 1; i++) cin >> b[i];\n    a.emplace_back(b[0]);\n    for(int i = 0; i < n - 2; i++){\n        a.emplace_back(min(b[i], b[i + 1]));\n    }\n    a.emplace_back(b[n - 2]);\n    for(auto &i : a) cout << i << ' ';\n    cout << \"\\n\";\n}\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1811",
    "index": "D",
    "title": "Umka and a Long Flight",
    "statement": "The girl Umka loves to travel and participate in math olympiads. One day she was flying by plane to the next olympiad and out of boredom explored a huge checkered sheet of paper.\n\nDenote the $n$-th Fibonacci number as $F_n = \\begin{cases} 1, & n = 0; \\\\ 1, & n = 1; \\\\ F_{n-2} + F_{n-1}, & n \\ge 2. \\end{cases}$\n\nA checkered rectangle with a height of $F_n$ and a width of $F_{n+1}$ is called a Fibonacci rectangle of order $n$.\n\nUmka has a Fibonacci rectangle of order $n$. Someone colored a cell in it at the intersection of the row $x$ and the column $y$.\n\nIt is necessary to cut this rectangle \\textbf{exactly} into $n+1$ squares in such way that\n\n- the painted cell was in a square with a side of $1$;\n- there was \\textbf{at most one} pair of squares with equal sides;\n- the side of each square was equal to a Fibonacci number.\n\nWill Umka be able to cut this rectangle in that way?",
    "tutorial": "$F_0^2 + F_1^2 +\\ldots + F_n^2 = F_n\\cdot F_{n+1}$, which can be proved by induction: $F_n\\cdot F_{n+1} = F_n\\cdot (F_{n-1}+F_n) = F_{n-1} \\cdot F_n + F_n^2$. If the partition exists, it has the form $[F_0, F_1, \\ldots, F_n]$, since the area of the rectangle with another partition will be greater than $F_n \\cdot F_{n+1}$. We will cut the rectangles in the order $F_n, F_{n-1}, \\ldots, F_0$. Denote the coordinates of the colored cell at the step $n$ as $\\langle x_n, y_n\\rangle$. If $F_{n-1} <y_n\\le F_n$ and $n> 1$, then there is no partition, since the square $F_n$ at any location overlaps the colored cell. Cut off the square $F_n$ from the right or left edge, depending on the location of the colored cell, that is, $\\langle x_{n-1}, y_{n-1} \\rangle = \\langle y_n, x_n\\rangle$ or $\\langle x_{n-1}, y_{n-1} \\rangle = \\langle y_n - F_n, x_n \\rangle$. Suppose that it was advantageous to cut it not from the edge, then it is necessary to cut the rectangles $z\\times F_n$ and $(F_{n-1}-z)\\times F_n$, where $1\\le z <F_{n+1}-F_n =F_{n-1}$ using the set $[F_0, F_1 \\ldots F_{n-1}]$. Then $F_{n-1}$ will not enter the partition, but $2\\cdot F_{n-2}^2 < (2F_{n-2}+F_{n-3})^2 + 1 = ( F_{n-2} + F_{n-1})^2 +1$, so $F_1^2 + F_2^2 + \\ldots +2 \\cdot F_{n-2}^2 < F_0^2 +F_1^2 +\\ldots+F_{n-1}^2 = F_{n-1} \\cdot F_n = z \\cdot F_n + (F_{n-1} - z) \\cdot F_n$. We came to a contradiction.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXN = 50;\n\nint fib[MAXN];\n\nvoid build() {\n\tfib[0] = fib[1] = 1;\n\tfor (int i = 2; i < MAXN; ++i)\n\t\tfib[i] = fib[i - 2] + fib[i - 1];\n}\n\nbool solve(int n, int x, int y) {\n\tif (n == 1) return true;\n\tif (fib[n - 1] <= y && y < fib[n])\n\t\treturn false;\n\tif (fib[n] <= y)\n\t\ty -= fib[n];\n\treturn solve(n - 1, y, x);\n}\n\nint main() {\n\tint t; cin >> t;\n\tbuild();\n\twhile (t--) {\n\t\tint n, x, y; cin >> n >> x >> y;\n\t\tcout << (solve(n, --x, --y) ? \"YES\" : \"NO\") << '\\n';\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1811",
    "index": "E",
    "title": "Living Sequence",
    "statement": "In Japan, the number $4$ reads like death, so Bob decided to build a live sequence. Living sequence $a$ contains all natural numbers that do not contain the digit $4$. $a = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, \\ldots]$.\n\nFor example, the number $1235$ is part of the sequence $a$, but the numbers $4321$, $443$ are not part of the sequence $a$.\n\nBob realized that he does not know how to quickly search for a particular number by the position $k$ in the sequence, so he asks for your help.\n\nFor example, if Bob wants to find the number at position $k = 4$ (indexing from $1$), you need to answer $a_k = 5$.",
    "tutorial": "Note that any number in the sequence can be made up of $9$ possible digits (all digits except $4$). Then let's find the first digit of the answer, notice that it is just $x$ or $x+1$, where $x \\cdot 9^{l-1} \\le k$ (where $l$ - the length of the number we're looking for) and $x$ - the maximum. Note that $x$ simply corresponds to a digit in the base-$9$ numeral system. Why is this so? Because without the first digit we can assemble any numbers with $9$ possible digits, and we can put the digits $0...x$ except $4$ in the first place. Thus, in the answer, the first digit will be $x$ if $x < 4$ and $x+1$ if $x \\ge 4$. Note that once the first digit is determined, the rest can be found the same way, since the prefix does not affect anything.",
    "code": "#include <iostream>\n#include <cmath>\n#include <cctype>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <deque>\n#include <stack>\n#include <unordered_set>\n#include <sstream>\n#include <cstring>\n#include <iomanip>\n#include <queue>\n#include <unordered_map>\n#include <random>\n#include <cfloat>\n#include <chrono>\n#include <bitset>\n#include <complex>\n#include <immintrin.h>\n\nint main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(0);\n\n    int32_t num_tests;\n    std::cin >> num_tests;\n\n    for(int32_t t = 0; t < num_tests; t++) {\n        int64_t k;\n        std::cin >> k;\n\n        std::vector<int32_t> digits;\n        while(k > 0) {\n            digits.push_back(k % 9);\n            k /= 9;\n        }\n        std::reverse(digits.begin(), digits.end());\n\n        for(int32_t i = 0; i < digits.size(); i++)\n            std::cout << (char)(digits[i] < 4 ? (digits[i] + '0') : (digits[i] + '1'));\n        std::cout << \"\\n\";\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1811",
    "index": "F",
    "title": "Is It Flower?",
    "statement": "Vlad found a flowerbed with graphs in his yard and decided to take one for himself. Later he found out that in addition to the usual graphs, $k$-flowers also grew on that flowerbed. A graph is called a $k$-flower if it consists of a simple cycle of length $k$, through each vertex of which passes its own simple cycle of length $k$ and these cycles do not intersect at the vertices. For example, $3$-flower looks like this:\n\nNote that $1$-flower and $2$-flower do not exist, since at least $3$ vertices are needed to form a cycle.\n\nVlad really liked the structure of the $k$-flowers and now he wants to find out if he was lucky to take one of them from the flowerbed.",
    "tutorial": "Note a few things: There are exactly $k^2$ vertices in the $k$-flower, since from each of the $k$ vertices of the main cycle comes another cycle of size $k$; in the $k$-flower, all vertices have degree $2$, except for the vertices of the main cycle, whose degrees are $4$; it follows that in $k$-flower $k^2 +k$ edges; The listed properties do not take into account only the connectivity of the graph and the sizes of our $k$ cycles. To check connectivity we run a bfs or dfs from any vertex and check that all vertices have been visited. To check the cycle lengths, we cut out the edges of the main one and make sure that the graph has fell apart into components of size $k$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint sz(int v, vector<vector<int>> &g, vector<bool> &used){\n    used[v] = true;\n    int s = 1;\n    for(int u: g[v]){\n        if(!used[u]) s += sz(u, g, used);\n    }\n    return s;\n}\n\nvoid remove(vector<int> &from, int x){\n    for(int &e: from){\n        if(e == x){\n            swap(e, from.back());\n            from.pop_back();\n            return;\n        }\n    }\n}\n\nvoid solve(int tc) {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> sl(n);\n    for(int i = 0; i < m; ++i){\n        int u, v;\n        cin >> u >> v;\n        sl[--u].emplace_back(--v);\n        sl[v].emplace_back(u);\n    }\n    int k = sqrt(n);\n    if(n != k * k || m != n + k){\n        cout << \"NO\";\n        return;\n    }\n    for(int i = 0; i < n; ++i){\n        if(sl[i].size() != 2 && sl[i].size() != 4){\n            cout << \"NO\";\n            return;\n        }\n    }\n    vector<bool> used(n);\n    if(sz(0, sl, used) != n){\n        cout << \"NO\";\n        return;\n    }\n    for(int i = 0; i < n; ++i){\n        if(sl[i].size() == 2) continue;\n        for(int j = 0; j < sl[i].size();){\n            int u = sl[i][j];\n            if(sl[u].size() > 2){\n                remove(sl[i], u);\n                remove(sl[u], i);\n            }\n            else{\n                j++;\n            }\n        }\n    }\n    used = vector<bool>(n);\n    for(int i = 0; i < n; ++i){\n        if(!used[i] && sz(i, sl, used) != k){\n            cout << \"NO\";\n            return;\n        }\n    }\n    cout << \"YES\";\n}\n\nbool multi = true;\n\nsigned main() {\n    cout.tie(nullptr);\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1811",
    "index": "G1",
    "title": "Vlad and the Nice Paths (easy version)",
    "statement": "\\textbf{This is an easy version of the problem, it differs from the hard one only by constraints on $n$ and $k$}.\n\nVlad found a row of $n$ tiles and the integer $k$. The tiles are indexed from left to right and the $i$-th tile has the color $c_i$. After a little thought, he decided what to do with it.\n\nYou can start from any tile and jump to any number of tiles \\textbf{right}, forming the path $p$. Let's call the path $p$ of length $m$ nice if:\n\n- $p$ can be divided into blocks of length exactly $k$, that is, $m$ is divisible by $k$;\n- $c_{p_1} = c_{p_2} = \\ldots = c_{p_k}$;\n- $c_{p_{k+1}} = c_{p_{k+2}} = \\ldots = c_{p_{2k}}$;\n- $\\ldots$\n- $c_{p_{m-k+1}} = c_{p_{m-k+2}} = \\ldots = c_{p_{m}}$;\n\nYour task is to find the number of nice paths of \\textbf{maximum} length. Since this number may be too large, print it modulo $10^9 + 7$.",
    "tutorial": "Let's use the dynamic programming. Let $dp[i][j]$ be the number of paths on the prefix $i$ of $j$ blocks of the same color. To make transitions in such dynamics, for the position $i$, we will iterate over the position $p$ in which the block started. Denote as $s$ the number of the same elements as $c_i$ and $c_p$ between them, then such a transition creates $dp[p-1][j-1] \\cdot C_{k-2}^{s}$ combinations. This solution works in $O(n^3)$ complexity.",
    "code": "M = 10 ** 9 + 7\n\n\ndef pw(a, n):\n    if n == 0:\n        return 1\n    b = pw(a, n // 2)\n    return b * b % M * (a if n % 2 == 1 else 1) % M\n\n\ndef obr(x):\n    return pw(x, M - 2)\n\n\ndef cnk(n, k):\n    return fact[n] * obr(fact[k]) % M * obr(fact[n - k]) % M\n\n\ndef solve():\n    n, k = map(int, input().split())\n    c = [-1] + [int(x) for x in input().split()]\n    if k == 1:\n        print(1)\n        return\n    dp = [[0] * (n // k + 1) for i in range(n + 1)]  # dp[i][j] = number for i prefix with j blocks\n    dp[0][0] = 1\n    for i in range(1, n + 1):\n        for j in range(0, n // k + 1):\n            if j > 0:\n                sz = 1\n                for s in range(i - 1, - 1, -1):\n                    if c[s] == c[i]:\n                        sz += 1\n                        if sz >= k:\n                            dp[i][j] += dp[s - 1][j - 1] * cnk(sz - 2, k - 2) % M\n                            dp[i][j] %= M\n            dp[i][j] += dp[i - 1][j]\n            dp[i][j] %= M\n    for j in range(n // k, -1, -1):\n        if dp[n][j] > 0:\n            print(dp[n][j])\n            return\n\n\nt = int(input())\nfact = [1] * 101\nfor i in range(1, 101):\n    fact[i] = fact[i - 1] * i % M\nfor _ in range(t):\n    solve()",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1811",
    "index": "G2",
    "title": "Vlad and the Nice Paths (hard version)",
    "statement": "\\textbf{This is hard version of the problem, it differs from the easy one only by constraints on $n$ and $k$}.\n\nVlad found a row of $n$ tiles and the integer $k$. The tiles are indexed from left to right and the $i$-th tile has the color $c_i$. After a little thought, he decided what to do with it.\n\nYou can start from any tile and jump to any number of tiles \\textbf{right}, forming the path $p$. Let's call the path $p$ of length $m$ nice if:\n\n- $p$ can be divided into blocks of length exactly $k$, that is, $m$ is divisible by $k$;\n- $c_{p_1} = c_{p_2} = \\ldots = c_{p_k}$;\n- $c_{p_{k+1}} = c_{p_{k+2}} = \\ldots = c_{p_{2k}}$;\n- $\\ldots$\n- $c_{p_{m-k+1}} = c_{p_{m-k+2}} = \\ldots = c_{p_{m}}$;\n\nYour task is to find the number of nice paths of \\textbf{maximum} length. Since this number may be too large, print it modulo $10^9 + 7$.",
    "tutorial": "To solve the hard version, let's modify the simple version solution. Note that the $j$ parameter can be discarded, since we only need paths of maximum length on each prefix. Now, as $dp[i]$, we denote a pair of the number of maximum paths and the number of blocks in them. For the position $i$, we will find the position closest to the left, from which we can start a block, and so we will find out what is the maximum for $i$. We will update $dp[i]$ until the maximum of the position being sorted is suitable for us.",
    "code": "from sys import stdin\ninput = lambda: stdin.readline().strip()\n\n\nM = 10 ** 9 + 7\ncnk = [[0] * (5000 + 1) for i in range(5000 + 1)]\n\n\ndef solve():\n    n, k = map(int, input().split())\n    c = [-1] + [int(x) for x in input().split()]\n    if k == 1:\n        print(1)\n        return\n    dp = [[0, 0] for i in range(n + 1)]  # dp[i] = [number, max] for i prefix\n    dp[0][0] = 1\n    for i in range(1, n + 1):\n        sz = 1\n        for s in range(i - 1, - 1, -1):\n            if c[s] == c[i]:\n                sz += 1\n                if sz == k:\n                    dp[i][1] = dp[s - 1][1] + 1\n                if sz >= k:\n                    if dp[s - 1][1] < dp[i][1] - 1:\n                        break\n                    dp[i][0] += dp[s - 1][0] * cnk[sz - 2][k - 2] % M\n                    dp[i][0] %= M\n        if dp[i][1] < dp[i - 1][1]:\n            dp[i] = [0, dp[i - 1][1]]\n        if dp[i][1] == dp[i - 1][1]:\n            dp[i][0] += dp[i - 1][0]\n            dp[i][0] %= M\n    print(dp[n][0])\n\n\nfor i in range(5000 + 1):\n    cnk[i][0] = 1\nfor i in range(1, 5000 + 1):\n    for j in range(1, i + 1):\n        cnk[i][j] = (cnk[i - 1][j] + cnk[i - 1][j - 1]) % M\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "binary search",
      "combinatorics",
      "data structures",
      "dp",
      "math",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1814",
    "index": "A",
    "title": "Coins",
    "statement": "In Berland, there are two types of coins, having denominations of $2$ and $k$ burles.\n\nYour task is to determine whether it is possible to represent $n$ burles in coins, i. e. whether there exist non-negative integers $x$ and $y$ such that $2 \\cdot x + k \\cdot y = n$.",
    "tutorial": "Note that $2$ coins with denomination $k$ can be replaced with $k$ coins with denomination $2$. So, if the answer exists, then there is also such a set of coins, where there is no more than one coin with denomination $k$. Therefore, it is enough to iterate through the number of coins with denomination $k$ (from $0$ to $1$) and check that the remaining number is non-negative and even (i. e. it can be represented as some number of coins with denomination $2$).",
    "code": "for _ in range(int(input())):\n\tn, k = map(int, input().split())\n\tfor x in range(2):\n\t\tif n - x * k >= 0 and (n - x * k) % 2 == 0:\n\t\t\tprint(\"YES\")\n\t\t\tbreak\n\telse:\n\t\tprint(\"NO\")",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1814",
    "index": "B",
    "title": "Long Legs",
    "statement": "A robot is placed in a cell $(0, 0)$ of an infinite grid. This robot has adjustable length legs. Initially, its legs have length $1$.\n\nLet the robot currently be in the cell $(x, y)$ and have legs of length $m$. In one move, it can perform one of the following three actions:\n\n- jump into the cell $(x + m, y)$;\n- jump into the cell $(x, y + m)$;\n- increase the length of the legs by $1$, i. e. set it to $m + 1$.\n\nWhat's the smallest number of moves robot has to make to reach a cell $(a, b)$?",
    "tutorial": "Let's fix the number of leg length increases we do. Let the final length be $k$. Notice that for all $i$ from $1$ to $k$ there is some time when the length is exactly $i$. Thus, we can perform jumps of form $(x, y) \\rightarrow (x + i, y)$ or $(x, y) \\rightarrow (x, y + i)$. What's the jumping strategy, then? Obviously, we can solve the problem independently for $a$ and $b$. Consider $a$. We would love to just make jumps of length $k$ as that's the maximum possible length. Unfortunately, that only works when $a$ is divisible by $k$. Otherwise, we are left with some remainder which is smaller than $k$. But we have already figured out how to jump to any value from $1$ to $k$. So, that only adds another jump. You can say that the total number of jumps is $\\lceil \\frac a k \\rceil$. Same for $b$. Finally, for a fixed $k$, the answer is $\\lceil \\frac a k \\rceil + \\lceil \\frac b k \\rceil + (k - 1)$. The constraints tell us that we are not allowed to iterate over all $k$ from $1$ to $\\max(a, b)$. It feels like huge $k$ will never be optimal, but let's try to base our intuition on something. Try to limit the options by studying the formula. Let's simplify. Assume $a = b$ and also get rid of the ceil. Not like that changes the formula a lot. Now it becomes $2 \\frac a k + (k - 1)$. We can see that when we increase $k$, $2 \\frac a k$ becomes smaller and $(k - 1)$ becomes larger. However, we care more about how fast they become smaller and larger. You can just guess or write down the derivative explicitly and figure out that the first term shrinks faster than the second term grows until around $\\sqrt a \\cdot c$ for some constant $c$ (apparently, $c = \\sqrt 2$). Thus, their sum decreases until then, then increases. Thus, you can search for the best $k$ around $\\sqrt a$ or $\\sqrt b$ or $\\sqrt{\\max(a, b)}$. It doesn't really matter, since, for implementation, you can basically try all $k$ until around $10^5$, which is safely enough.",
    "code": "for _ in range(int(input())):\n\ta, b = map(int, input().split())\n\tans = a + b\n\tfor m in range(1, 100000):\n\t\tans = min(ans, (a + m - 1) // m + (b + m - 1) // m + (m - 1))\n\tprint(ans)",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1814",
    "index": "C",
    "title": "Search in Parallel",
    "statement": "Suppose you have $n$ boxes. The $i$-th box contains infinitely many balls of color $i$. Sometimes you need to get a ball with some specific color; but you're too lazy to do it yourself.\n\nYou have bought two robots to retrieve the balls for you. Now you have to program them. In order to program the robots, you have to construct two lists $[a_1, a_2, \\dots, a_k]$ and $[b_1, b_2, \\dots, b_{n-k}]$, where the list $a$ represents the boxes assigned to the first robot, and the list $b$ represents the boxes assigned to the second robot. \\textbf{Every integer from $1$ to $n$ must be present in exactly one of these lists}.\n\nWhen you request a ball with color $x$, the robots work as follows. Each robot looks through the boxes that were assigned to that robot, in the order they appear in the list. The first robot spends $s_1$ seconds analyzing the contents of a box; the second robot spends $s_2$. As soon as one of the robots finds the box with balls of color $x$ (and analyzes its contents), the search ends. The search time is the number of seconds from the beginning of the search until one of the robots finishes analyzing the contents of the $x$-th box. If a robot analyzes the contents of all boxes assigned to it, it stops searching.\n\nFor example, suppose $s_1 = 2$, $s_2 = 3$, $a = [4, 1, 5, 3, 7]$, $b = [2, 6]$. If you request a ball with color $3$, the following happens:\n\n- initially, the first robot starts analyzing the box $4$, and the second robot starts analyzing the box $2$;\n- at the end of the $2$-nd second, the first robot finishes analyzing the box $4$. It is not the box you need, so the robot continues with the box $1$;\n- at the end of the $3$-rd second, the second robot finishes analyzing the box $2$. It is not the box you need, so the robot continues with the box $6$;\n- at the end of the $4$-th second, the first robot finishes analyzing the box $1$. It is not the box you need, so the robot continues with the box $5$;\n- at the end of the $6$-th second, the first robot finishes analyzing the box $5$. It is not the box you need, so the robot continues with the box $3$. At the same time, the second robot finishes analyzing the box $6$. It is not the box you need, and the second robot has analyzed all the boxes in its list, so that robot stops searching;\n- at the end of the $8$-th second, the first robot finishes analyzing the box $3$. It is the box you need, so the search ends;\n- so, the search time is $8$ seconds.\n\nYou know that you are going to request a ball of color $1$ $r_1$ times, a ball of color $2$ $r_2$ times, and so on. You want to construct the lists $a$ and $b$ for the robots in such a way that the total search time over all requests is the minimum possible.",
    "tutorial": "If the ball of color $x$ is present in the first list on position $i$, then it takes $i \\cdot t_1$ seconds to find it. The same for the second list: if color $x$ is on position $j$, it takes $j \\cdot t_2$ seconds to find it. So, for each position, we have a coefficient which will be multiplied by the number of times it is requested, and the total search time is the sum of these products for all positions. There is a classical problem of the form \"you are given two arrays $a_i$ and $b_i$, both of length $m$, consisting of non-negative integers; permute the elements of $a$ in such a way that $\\sum\\limits_{i=1}^{m} a_i \\cdot b_i$ is the minimum possible\". To solve this problem, you have to pair the maximum element of $a$ with the minimum element of $b$, the second maximum of $a$ with the second minimum element of $b$, and so on. We can reduce our problem to this one. For each of $2n$ positions in the lists, there is a coefficient; you have to assign the boxes from $1$ to $n$ to the positions so that the sum of $r_i$ multiplied by the coefficients for the positions is the minimum possible. This looks similar, but there are $2n$ positions and only $n$ boxes. To resolve this issue, we can try a lot of different approaches. I believe the easiest one is the following: initially, both lists are empty, and when want to add an element to one of these two lists, we choose the list such that the coefficient for the new position (which is $s_i \\cdot (1 + cnt_i)$, where $cnt_i$ is the number of elements we already added to the $i$-th list) is smaller. If for both lists, adding a new element has the same coefficient - it doesn't matter which one we choose. This greedy approach works because every time we add an element to the list, next time we'll add another one into the same list, the coefficient for that element will be greater. So, the problem can be solved in $O(n \\log n)$: first, we sort the boxes by the number of times they are requested (in non-ascending order), and then we put them into the two lists greedily, every time choosing the list such that the coefficient for the next element is smaller.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tvector<int> s(2);\n\t\tfor(int j = 0; j < 2; j++)\n\t\t\tscanf(\"%d\", &s[j]);\n\t\tvector<pair<int, int>> a(n);\n\t\tfor(int j = 0; j < n; j++)\n\t\t{\n\t\t\tscanf(\"%d\", &a[j].first);\n\t\t\ta[j].second = j + 1;\n\t\t}\n\t\tsort(a.begin(), a.end());\n\t\treverse(a.begin(), a.end());\n\t\tvector<vector<int>> lists(2);\n\t\tfor(int j = 0; j < n; j++)\n\t\t{\n\t\t\tint cost1 = s[0] * (lists[0].size() + 1);\n\t\t\tint cost2 = s[1] * (lists[1].size() + 1);\n\t\t\tif(cost1 < cost2)\n\t\t\t\tlists[0].push_back(a[j].second);\n\t\t\telse\n\t\t\t\tlists[1].push_back(a[j].second);\n\t\t}\n\t\tfor(int j = 0; j < 2; j++)\n\t\t{\n\t\t    cout << lists[j].size();\n\t\t    for(auto x : lists[j]) cout << \" \" << x;\n\t\t    cout << endl;\n\t\t}\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1814",
    "index": "D",
    "title": "Balancing Weapons",
    "statement": "You've got a job in a game studio that developed an online shooter, and your first big task is to help to balance weapons. The game has $n$ weapons: the $i$-th gun has an integer fire rate $f_i$ and an integer damage per bullet $d_i$. The $i$-th gun's total firepower is equal to $p_i = f_i \\cdot d_i$.\n\nYou have to modify the values $d_i$ of some guns in such a way that the new values $d_i$ will still be integers, and the firepower of all guns will become balanced. Given an integer $k$, the guns are said to be balanced if $\\max\\limits_{1 \\le i \\le n}{p_i} - \\min\\limits_{1 \\le i \\le n}{p_i} \\le k$.\n\nSince gamers that play your game don't like big changes, you need to change the values $d_i$ for the minimum possible number of guns. What is the minimum number of guns for which you have to change these values to make the guns balanced?\n\nNote that the new values $d_i$ must be integers greater than $0$.",
    "tutorial": "Note that the answer $n$ is always possible: for example, we can set $d_i = \\frac{\\prod{f_j}}{f_i}$, then $p_1 = \\dots = p_n = \\prod{f_j}$ and $\\max{p_i} - \\min{p_i} = 0$. If the answer is less than $n$ then there is at least one gun $id$ we won't change. It means that all other guns' firepower should be \"around\" $p_{id}$, i. e. $|p_i - p_{id}| \\le k$. So we can look at segment $[p_{id} - k, p_{id} + k]$ and, for each gun $i$, find what values $d'_i$ we should set to get into this segment. After that we can rephrase our task into the next one: we should choose segment $[l, l + k] \\subset [p_{id} - k, p_{id} + k]$ such that each gun occurs in $[l, l + k]$ at least once and the number of corresponding $d'_i$ that are equal to $d_i$ is maximum possible. It can be solved with two pointers technique. Note that there are at most three interesting values $d'_i$ we should consider: $v_1 = \\left\\lfloor \\frac{p_{id}}{f_i} \\right\\rfloor$, $v_2 = v_1 + 1$ and $v_3 = d_i$. For each unique value $v_j$ such that $v_j \\cdot f_i \\in [p_{id} - k, p_{id} + k]$ we can add an event $(i, c_j)$ in position $v_j f_i$, where $c_j$ is $1$ if $v_j = d_i$ or $0$ otherwise. Now, with two pointers technique, we can iterate over all subsegments of length $k + 1$ of segment $[p_{id} - k, p_{id} + k]$. To get the desired answer we should maintain the number of unique $i$ from events that are present in the subsegment and the sum $s$ of $c_j$ from that events. Since there is only one $c_j = 1$ for each gun $i$ then the sum $s$ of $c_j$ we have is equal exactly to the number of guns we shouldn't change. Then we take the maximum $mx$ over sums $s$ of all subsegments where all guns occur, and the answer for a fixed $p_{id}$ is $n - mx$. Let's iterate over all \"fixed\" $id$ and take the minimum from all $n - mx$: that will be the answer for the initial task. Checking answer for a fixed $id$ involves creating $3 n$ events and two pointers over segment $[p_{id} - k, p_{id} + k]$, so it takes $O(n + k)$ time and $O(n + k)$ space. So, the total complexity is $O(n^2 + n k)$ time and $O(n + k)$ space.",
    "code": "fun main() {\n    repeat(readln().toInt()) {\n        val (n, k) = readln().split(' ').map { it.toInt() }\n        val f = readln().split(' ').map { it.toLong() }\n        val d = readln().split(' ').map { it.toLong() }\n\n        fun checkAround(pos : Long) : Int {\n            val qs = Array(2 * k + 1) { MutableList(0) { 0 } }\n\n            fun inside(x : Long, pos: Long) = (pos - k <= x) && (x <= pos + k)\n            for (i in f.indices) {\n                var newD = maxOf(1L, pos / f[i])\n                if (newD != d[i] && newD + 1 != d[i] && inside(d[i] * f[i], pos)) {\n                    val id = (i + 1)\n                    qs[(d[i] * f[i] - pos + k).toInt()].add(id)\n                }\n                repeat(2) {\n                    if (inside(newD * f[i], pos)) {\n                        val id = if (newD == d[i]) (i + 1) else -(i + 1)\n                        qs[(newD * f[i] - pos + k).toInt()].add(id)\n                    }\n                    newD++\n                }\n                \n            }\n\n            val cntPerId = IntArray(n) { 0 }\n            var cntDistinct = 0\n            var cntGood = 0\n\n            fun addToSeg(cid : Int) {\n                val id = -1 + if (cid > 0) cid else -cid\n                val c = if (cid > 0) 1 else 0\n\n                if (cntPerId[id] == 0)\n                    cntDistinct++\n                cntPerId[id]++\n\n                cntGood += c\n            }\n            fun eraseFromSeg(cid : Int) {\n                val id = -1 + if (cid > 0) cid else -cid\n                val c = if (cid > 0) 1 else 0\n\n                cntPerId[id]--\n                if (cntPerId[id] == 0)\n                    cntDistinct--\n\n                cntGood -= c\n            }\n            var ans = 0\n            for (p in 0 until k)\n                qs[p].forEach { addToSeg(it) }\n            for (p in 0..k) {\n                qs[p + k].forEach { addToSeg(it) }\n                if (cntDistinct == n)\n                    ans = maxOf(ans, cntGood)\n                qs[p].forEach { eraseFromSeg(it) }\n            }\n            return n - ans\n        }\n\n        var ans = n\n        for (i in f.indices) {\n            ans = minOf(ans, checkAround(d[i] * f[i]))\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "math",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1814",
    "index": "E",
    "title": "Chain Chips",
    "statement": "You are given an undirected graph consisting of $n$ vertices and $n-1$ edges. The $i$-th edge has weight $a_i$; it connects the vertices $i$ and $i+1$.\n\nInitially, each vertex contains a chip. Each chip has an integer written on it; the integer written on the chip in the $i$-th vertex is $i$.\n\nIn one operation, you can choose a chip (if there are multiple chips in a single vertex, you may choose any one of them) and move it along one of the edges of the graph. The cost of this operation is equal to the weight of the edge.\n\nThe cost of the graph is the minimum cost of a sequence of such operations that meets the following condition:\n\n- after all operations are performed, each vertex contains exactly one chip, and the integer on each chip is \\textbf{not equal} to the index of the vertex where that chip is located.\n\nYou are given $q$ queries of the form:\n\n- $k$ $x$ — change the weight of the $k$-th edge (the one which connects the vertices $k$ and $k+1$) to $x$.\n\nAfter each query, print the cost of the graph. Note that you don't actually move any chips; when you compute the cost, the chips are on their initial positions.",
    "tutorial": "Let's try to analyze how many times we traverse each edge, in the style of \"Contribution to the Sum\" technique. For each edge, the number of times it is traversed must be even, since for every chip that goes from the part of the graph $[1..i]$ to the part $[i+1..n]$, there should be a chip that goes in the opposite direction (the number of chips on vertices $[1..n]$ should be unchanged). For each vertex, at least one incident edge should be traversed at least twice - otherwise, the chip from this vertex cannot be moved to any other vertex. We would also like to traverse the edges as rarely as possible. Is it possible to find an answer where, if we traverse any edge, we traverse it only twice? It turns out it is possible. Let's \"split\" the graph into several parts by removing the edges we don't traverse. If we don't break the constraint that each vertex has at least one incident edge which is traversed by some chip, then each part of the graph will contain at least two vertices. And in each part, we can make sure that each edge is traversed only twice as follows: let the part represent the segment $[l, r]$ of vertices; if we move the chip $r$ to the vertex $l$, the chip $l$ to the vertex $l+1$, the chip $l+1$ to the vertex $l+2$, ..., the chip $r-1$ to the vertex $r$, then every edge in that part will be traversed exactly twice. So, we have shown that if we pick a subset of edges which we traverse that meets the constraint on each vertex having an incident traversed edge, then it is enough to traverse each chosen edge only twice. Now the problem becomes the following: choose a subset of edges in such a way that every vertex has at least one incident chosen edge, minimize the total weight of this subset, and print the integer which is double that total weight. Since the structure of the graph is specific, we can run dynamic programming of the form $dp_{i,f}$ - the minimum total weight of the subset, if we considered the first $i$ edges, and $f$ is $0$ if we haven't taken the last edge, or $1$ if we have. Obviously, this dynamic programming works in $O(n)$, which is too slow because we have to process queries. We will employ a classical technique of storing the dynamic programming in segment tree: build a segment tree on $n-1$ leaves; in every vertex of the segment tree, we store a $2 \\times 2$ matrix $d$; if the segment represented by the node of the segment tree is $[l..r]$, then the value of $d[f_1][f_2]$ is the minimum total weight of the subset of edges between $l$ and $r$ such that among every pair of adjacent edges, at least one is chosen; $f_1$ and $f_2$ represent the status of the first/last edge on the segment, respectively. And when some element changes, we need to recalculate only $O(\\log n)$ nodes of the segment tree, so this solution works in $O(n \\log n + q \\log n)$, albeit with a very big constant factor. Implementation note: don't use dynamic-size arrays (like std::vector in C++) to store the values in the matrices, it might slow your solution very seriously. Instead, use static-size arrays.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long li;\n\nconst li INF = (li)(1e18);\nconst int N = 200043;\n\nstruct data\n{\n\tarray<array<long long, 2>, 2> d;\n\tdata() {\n\t    for(int i = 0; i < 2; i++)\n\t\t\tfor(int j = 0; j < 2; j++)\n\t\t\t\td[i][j] = INF;\n\t};\n\tdata(li x)\n\t{\n\t\tfor(int i = 0; i < 2; i++)\n\t\t\tfor(int j = 0; j < 2; j++)\n\t\t\t\td[i][j] = INF;\n\t\td[0][0] = 0;\n\t\td[1][1] = x;\n\t};\n\tdata(data l, data r)\n\t{\n\t\tfor(int i = 0; i < 2; i++)\n\t\t\tfor(int j = 0; j < 2; j++)\n\t\t\t\td[i][j] = INF;\n\t\tfor(int i = 0; i < 2; i++)\n\t\t\tfor(int j = 0; j < 2; j++)\n\t\t\t\tfor(int k = 0; k < 2; k++)\n\t\t\t\t\tfor(int x = 0; x < 2; x++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(j == 0 && k == 0) continue;\n\t\t\t\t\t\td[i][x] = min(d[i][x], l.d[i][j] + r.d[k][x]);\n\t\t\t\t\t}\n\t};\n};\n\ndata T[4 * N];\nli a[N];\n\nvoid recalc(int v)\n{\n\tT[v] = data(T[v * 2 + 1], T[v * 2 + 2]);\n}\n\nvoid build(int v, int l, int r)\n{\n\tif(l == r - 1) T[v] = data(a[l]);\n\telse\n\t{\n\t\tint m = (l + r) / 2;\n\t\tbuild(v * 2 + 1, l, m);\n\t\tbuild(v * 2 + 2, m, r);\n\t\trecalc(v);\n\t}\n}\n\nvoid upd(int v, int l, int r, int pos, li val)\n{\n\tif(l == r - 1)\n\t{\n\t\ta[l] = val;\n\t\tT[v] = data(a[l]);\n\t}\n\telse\n\t{\n\t\tint m = (l + r) / 2;\n\t\tif(pos < m)\n\t\t\tupd(v * 2 + 1, l, m, pos, val);\n\t\telse\n\t\t\tupd(v * 2 + 2, m, r, pos, val);\n\t\trecalc(v);\n\t}\n}\n\nint main()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n - 1; i++)\n\t{\n\t\tscanf(\"%lld\", &a[i]);\n\t}\n\tbuild(0, 0, n - 1);\n\tint q;\n\tscanf(\"%d\", &q);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tint x;\n\t\tli k;\n\t\tscanf(\"%d %lld\", &x, &k);\n\t\tupd(0, 0, n - 1, x - 1, k);\n\t\tprintf(\"%lld\\n\", T[0].d[1][1] * 2);\n\t}\n}",
    "tags": [
      "data structures",
      "dp",
      "matrices"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1814",
    "index": "F",
    "title": "Communication Towers",
    "statement": "There are $n$ communication towers, numbered from $1$ to $n$, and $m$ bidirectional wires between them. Each tower has a certain set of frequencies that it accepts, the $i$-th of them accepts frequencies from $l_i$ to $r_i$.\n\nLet's say that a tower $b$ is accessible from a tower $a$, if there exists a frequency $x$ and a sequence of towers $a=v_1, v_2, \\dots, v_k=b$, where consecutive towers in the sequence are directly connected by a wire, and each of them accepts frequency $x$. Note that accessibility is not transitive, i. e if $b$ is accessible from $a$ and $c$ is accessible from $b$, then $c$ may not be accessible from $a$.\n\nYour task is to determine the towers that are accessible from the $1$-st tower.",
    "tutorial": "Let's consider the sweep line approach by the value of the variable $x$; the vertex $i$ is active from the moment $l_i$ to the moment $r_i$. And we have to find vertices that are reachable in the graph of active vertices from the vertex $1$. So, we rephrased the problem as follows: there are vertices that are active at some moments, and we want to get some information about connectivity during each moment of time. This is a standard offline dynamic connectivity problem which can be solved with a divide-and-conquer approach described here. Now we are able to find the connectivity component of the $1$-th vertex for each value of $x$. It remains to understand how to combine answers for all values of $x$ fast enough. Let's try to visualize the components as vertices of a directed graph. We assign a vertex to each component, and when two components merge, we add two directed edges from the new vertex to the vertices corresponding to the components; and now we can use the reachability information in this graph. Each vertex of the original graph corresponds to one of the sinks in this graph; and sinks that correspond to the vertices of some component are reachable from the vertex corresponding to that component. To restore all the vertex indices later, we will mark all components containing the vertex $1$ while we run our dynamic connectivity approach. Then the vertex $v$ (of the original graph) is included in the answer if the vertex representing the component containing only the vertex $v$ is reachable from any of the marked vertices. Now, all you need to do is run DFS or BFS from all the marked vertices in the component graph.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(a) int((a).size())\n\nconst int N = 200002;\nconst int V = 50 * N;\n\nusing pt = pair<int, int>;\n\nint n, m;\npt a[N];\nvector<pt> t[4 * N];\nint p[N], rk[N], vs[N];\nint cntV;\npt g[V];\nbool ans[V];\n\nvoid upd(int v, int l, int r, int L, int R, pt e) {\n  if (L >= R) return;\n  if (l == L && r == R) {\n    t[v].push_back(e);\n    return;\n  }\n  int m = (l + r) / 2;\n  upd(v * 2 + 1, l, m, L, min(m, R), e);\n  upd(v * 2 + 2, m, r, max(m, L), R, e);\n}\n\nint k;\nint* ptr[V];\nint val[V];\n\nvoid upd(int &a, int b) {\n  ptr[k] = &a;\n  val[k] = a;\n  k += 1;\n  a = b;\n}\n\nint getp(int v) {\n  return p[v] == v ? v : getp(p[v]);\n}\n\nvoid unite(int v, int u) {\n  v = getp(v), u = getp(u);\n  if (v == u) return;\n  if (rk[v] > rk[u]) swap(v, u);\n  upd(p[v], u);\n  g[cntV] = {vs[v], vs[u]};\n  upd(vs[u], cntV++);\n  if (rk[v] == rk[u])\n    upd(rk[u], rk[u] + 1);\n}\n\nvoid solve(int v, int l, int r) {\n  int cur = k;\n  for (auto& [v, u] : t[v]) \n    unite(v, u);\n  if (l + 1 == r) {\n    ans[vs[getp(0)]] = 1;\n  } else {\n    int m = (l + r) / 2;\n    solve(v * 2 + 1, l, m);\n    solve(v * 2 + 2, m, r);\n  }\n  while (k > cur) {\n    k -= 1;\n    (*ptr[k]) = val[k];\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  \n  cin >> n >> m;\n  for (int i = 0; i < n; ++i)\n    cin >> a[i].first >> a[i].second;\n  for (int i = 0; i < m; ++i) {\n    int x, y;\n    cin >> x >> y;\n    --x; --y;\n    int L = max(a[x].first, a[y].first);\n    int R = min(a[x].second, a[y].second);\n    upd(0, 0, N, L, R + 1, {x, y});\n  }\n  \n  for (int i = 0; i < n; ++i) {\n    p[i] = i;\n    rk[i] = 1;\n    vs[i] = i;\n    g[i] = {-1, -1};\n  }\n  \n  cntV = n;\n  solve(0, 0, N);\n  \n  queue<int> q;\n  for (int i = 0; i < cntV; ++i) if (ans[i]) \n    q.push(i);\n  \n  while (!q.empty()) {\n    int v = q.front(); q.pop();\n    for (int u : {g[v].first, g[v].second}) {\n      if (u != -1 && !ans[u]) {\n        ans[u] = true;\n        q.push(u);\n      }\n    }\n  }\n  \n  for (int i = 0; i < n; ++i) if (ans[i])\n    cout << i + 1 << ' ';\n}",
    "tags": [
      "brute force",
      "divide and conquer",
      "dsu"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1815",
    "index": "A",
    "title": "Ian and Array Sorting",
    "statement": "To thank Ian, Mary gifted an array $a$ of length $n$ to Ian. To make himself look smart, he wants to make the array in non-decreasing order by doing the following finitely many times: he chooses two adjacent elements $a_i$ and $a_{i+1}$ ($1\\le i\\le n-1$), and increases both of them by $1$ or decreases both of them by $1$. Note that, the elements of the array \\textbf{can} become negative.\n\nAs a smart person, you notice that, there are some arrays such that Ian cannot make it become non-decreasing order! Therefore, you decide to write a program to determine if it is possible to make the array in non-decreasing order.",
    "tutorial": "Consider difference array $[a_2-a_1,a_3-a_2,...,a_n-a_{n-1}]$. If the original array is non-decreasing, what properties does the difference array have? Operations to the original array correspond to what operations in the difference array? We consider the difference array $b_i=a_{i+1}-a_i$ ($1\\le i\\le n-1$). Then the original array is non-decreasing if and only if all elements of the difference array is non-negative. We can see that either $b_i$ is increased by $1$ and $b_{i+2}$ is decreased by $1$ or vice versa for $1\\le i\\le n-3$, $b_2$ is increased or decreased by $1$ or $b_{n-2}$ is increased or decreased by $1$. If $n$ is odd, then $n-2$ is odd. What we can do is to increase $b_2$ and $b_{n-2}$ enough number of times, and then do $b_i$ increase by $1$ and $b_{i+2}$ decrease by $1$ or vice versa enough times to distribute the values to other elements of $b$. Doing this, we can make all of the elements of $b$ non-negative, which is what we want. So we output 'YES' no matter what for odd $n$. For even $n$, $n-2$ is even. So by increasing $b_2$ and $b_{n-2}$ enough number of times, then distributing, we can only ensure that the elements of $b$ with even indices are non-negative. Since the only operation that affects odd indices is increasing $b_i$ by $1$ and decreasing $b_{i+2}$ by $1$ or vice versa, we can see that the sum of the elements of $b$ with odd indices will not change. If the sum of the elements of $b$ with odd indices is at least $0$, we can distribute the values such that in the end, all of them are non-negative, so we should output 'YES'. But if the sum of elements of $b$ with odd indices is negative, there must exist a negative $b_i$ in the end, and we should output 'NO'.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n    int n;\n    cin >> n;\n    int arr[n];\n    long long int altsum=0;\n    for(int i=0;i<n;i++){\n        cin >> arr[i];\n        if(i%2==0){\n            altsum-=arr[i];\n        }\n        else{\n            altsum+=arr[i];\n        }\n    }\n    if(n%2==1||altsum>=0){\n        cout << \"YES\\n\";\n    }\n    else{\n        cout << \"NO\\n\";\n    }\n    return;\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL); cout.tie(NULL);\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1815",
    "index": "B",
    "title": "Sum Graph",
    "statement": "This is an interactive problem.\n\nThere is a hidden permutation $p_1, p_2, \\dots, p_n$.\n\nConsider an undirected graph with $n$ nodes only with no edges. You can make two types of queries:\n\n- Specify an integer $x$ satisfying $2 \\le x \\le 2n$. For all integers $i$ ($1 \\le i \\le n$) such that $1 \\le x-i \\le n$, an edge between node $i$ and node $x-i$ will be added.\n- Query the number of \\textbf{edges} in the shortest path between node $p_i$ and node $p_j$. As the answer to this question you will get the number of edges in the shortest path if such a path exists, or $-1$ if there is no such path.\n\nNote that you can make both types of queries in \\textbf{any} order.\n\nWithin $2n$ queries (including type $1$ and type $2$), guess two possible permutations, at least one of which is $p_1, p_2, \\dots, p_n$. You get accepted if at least one of the permutations is correct. You are allowed to guess the same permutation twice.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Consider using a type 1 operation on $x=n+1$ and $x=n+2$. What do you notice? The resulting graph, after performing type 1 operations according to hint 1, will be a chain (e.g. when $n=6$, it should look like $1 - 6 - 2 - 5 - 3 - 4$). Now, try to figure out a position $k$ such that node $p_k$ is one of the endpoints of the chain. Once you figure that out, how can you make use of this to solve the full problem? There are many ways to solve this problem. My original solution is rather difficult to implement correctly, and a bit complicated. During round testing, tester rsj found an alternative solution, which is, in my opinion, one that's a lot easier to understand and implement. Firstly, use a type 1 operation on $x=n+1$ and $x=n+2$ (or you can do $x=n$ and $x=n+1$). Then, the graph should look like a chain (e.g. when $n=6$, it should look like $1 - 6 - 2 - 5 - 3 - 4$). Note that there are actually two edges between each pair of directly connected nodes, but it is irrelevant to the task. Next, use a type 2 query on all pairs of $(1,i)$ where $2 \\le i \\le n$. Take the maximum of the query results. Let $k$ be one of the values such that the query result of $(1,k)$ is maximum among all $(1,i)$. It is easy to see that, node $p_k$ is one of the endpoints of the chain. Afterwards, use a type 2 query on all pairs of $(k,i)$ where $1 \\le i \\le n$ and $i \\ne k$. Since node $p_k$ is an endpoint of the chain, all the query results are distinct and you can recover the exact node that each query result corresponds to. A problem arises that it is unclear about which endpoint node $p_k$ actually is. But this issue can be solved easily: since the problem allows outputting two permutations that can be $p$, just try both endpoints and output the corresponding permutations. In total, $2$ type 1 operations and $2n-2$ type 2 operations are used, which sums up to $2n$ operations. As stated in the sample description, you don't even need any operations when $n=2$. It is also easy to see that the actual number of operations required is $2n-1$ since there is a pair of duplicate type 2 operations, but we allow duplicating the operation anyway. Try to solve the problem using at most $n + \\left \\lfloor \\frac{n}{2} \\right \\rfloor + 2$ queries. Refer to this comment. Thanks to -1e11 and FatihSolak for the solution. (To pass this problem using this solution, optimizations for $n=2$ are needed, as mentioned in the editorial section.) Another way of solving the harder version provided by sysia: refer to this comment.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve(int tc) {\n  int n; cin >> n;\n  cout << \"+ \" << n+1 << endl;\n  cout << \"+ \" << n+2 << endl;\n  int l = 1, r = n;\n  int ord[n+1];\n  for(int i=1; i<=n; i++) {\n    if(i & 1) ord[i] = l++;\n    else ord[i] = r--;\n  }\n  int dist1[n+1];\n  dist1[1] = 0;\n  int ma = 0, id;\n  for(int i=2; i<=n; i++) {\n    cout << \"? 1 \" << i << endl;\n    cin >> dist1[i];\n    if(dist1[i] > ma) {\n      ma = dist1[i];\n      id= i;\n    }\n  }\n  int p[n+1], q[n+1];\n  p[id] = ord[1];\n  q[id] = ord[n];\n  for(int i=1; i<=n; i++) {\n    if(i != id) {\n      cout << \"? \" << id << \" \" << i << endl;\n      int x;\n      cin >> x;\n      p[i] = ord[x+1];\n      q[i] = ord[n-x];\n    }\n  }\n  cout << \"!\";\n  for(int i=1; i<=n; i++) cout << \" \" << p[i];\n  for(int i=1; i<=n; i++) cout << \" \" << q[i];\n  cout << endl;\n\n}\nint32_t main() {\n  int t = 1; cin >> t;\n  for(int i=1; i<=t; i++) solve(i);\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "implementation",
      "interactive",
      "shortest paths",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1815",
    "index": "C",
    "title": "Between",
    "statement": "You are given an integer $n$, as well as $m$ pairs of integers $(a_i,b_i)$, where $1\\leq a_i , b_i \\leq n$, $a_i \\ne b_i$.\n\nYou want to construct a sequence satisfying the following requirements:\n\n- All elements in the sequence are integers between $1$ and $n$.\n- There is exactly one element with value $1$ in the sequence.\n- For each $i$ ($1 \\le i \\le m$), between any two elements (on different positions) in the sequence with value $a_i$, there is at least one element with value $b_i$.\n- The sequence constructed has the \\textbf{maximum} length among all possible sequences satisfying the above properties.\n\nSometimes, it is possible that such a sequence can be arbitrarily long, in which case you should output \"INFINITE\". Otherwise, you should output \"FINITE\" and the sequence itself. If there are multiple possible constructions that yield the maximum length, output any.",
    "tutorial": "Construct a graph with $n$ vertices and add a directed edge $a \\rightarrow b$ if between every two $a$ there must be a $b$. Let $v_a$ be the number of occurrences of $a$. The key observation is that if $a \\rightarrow b$, then $v_{a} \\leq v_{b} + 1$. Suppose $a_k \\rightarrow a_{k-1} \\rightarrow \\cdots a_1$ is a directed path, where $a_1 = 1$. Then since $v_1 = 1$, we must have $v_{a_i} \\leq i$. In other words, $v_s \\leq d_s$. where $d_s$ is one plus the length of the shortest directed path from $s$ to $1$. Therefore, the total array length does not exceed $\\sum_{i=1}^{n} d_i$. We claim that we can achieve this. It is easy to calculate the $d_s$ by a BFS. Let $T_i$ consists of vertices $x$ such that $v_x = s$. Let $M$ the largest value of $d_i$ among all $i \\in {1,2\\cdots n}$. Consider $[T_M] , [T_{M-1}][T_M] , [T_{M-2}][T_{M-1}][T_{M}],\\cdots [T_1][T_2][T_3]\\cdots [T_m]$ where for each $i$, vertices in various occurrences of $T_i$ must be arranged in the same order. It is easy to check that this construction satisfies all the constraints and achieve the upper bound $\\sum_{i=1}^{n} d_i$. Thus, this output is correct. The sequence can be arbitrarily long if and only if there is some $v$ that does not have a path directed to $1$. To see this, let $S$ be the set of vertices that do not have path directed to $1$, then the following construction gives an arbitrarily long output that satisfy all constraints: $1 [S][S][S]\\cdots$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n    int n,m;\n    cin >> n >> m;\n    vector <int> adj[n+1];\n    int occ[n+1];\n    occ[1]=1;\n    for(int i=0;i<m;i++){\n        int x,y;\n        cin >> x >> y;\n        adj[y].push_back(x);\n    }\n    for(int i=2;i<=n;i++){\n        occ[i]=0;\n    }\n    queue <int> bfs;\n    bfs.push(1);\n    while(bfs.size()>0){\n        int f=bfs.front();\n        bfs.pop();\n        for(int i=0;i<adj[f].size();i++){\n            if(occ[adj[f][i]]==0){\n                occ[adj[f][i]]=occ[f]+1;\n                bfs.push(adj[f][i]);\n            }\n        }\n    }\n    vector <int> v[n+1];\n    int ans=0;\n    for(int i=1;i<=n;i++){\n        if(occ[i]==0){\n            cout << \"INFINITE\\n\";\n            return;\n        }\n        v[occ[i]].push_back(i);\n        ans+=occ[i];\n    }\n    cout << \"FINITE\\n\" << ans << endl;\n    for(int i=n;i>=1;i--){\n        for(int j=n;j>=i;j--){\n        if(i%2!=j%2){\n            continue;\n        }\n        for(int k=0;k<v[j].size();k++){\n        cout << v[j][k] << ' ';\n    }\n    }\n    }\n    for(int i=2;i<=n;i++){\n        for(int j=n;j>=i;j--){\n        if(i%2!=j%2){\n            continue;\n        }\n        for(int k=0;k<v[j].size();k++){\n        cout << v[j][k] << ' ';\n    }\n    }\n    }\n    cout << endl;\n    return;\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1815",
    "index": "D",
    "title": "XOR Counting",
    "statement": "Given two positive integers $n$ and $m$. Find the sum of all possible values of $a_1\\bigoplus a_2\\bigoplus\\ldots\\bigoplus a_m$, where $a_1,a_2,\\ldots,a_m$ are non-negative integers such that $a_1+a_2+\\ldots+a_m=n$.\n\nNote that all possible values $a_1\\bigoplus a_2\\bigoplus\\ldots\\bigoplus a_m$ should be counted in the sum \\textbf{exactly once}.\n\nAs the answer may be too large, output your answer modulo $998244353$.\n\nHere, $\\bigoplus$ denotes the bitwise XOR operation.",
    "tutorial": "The cases when $m=1$ and $m\\ge3$ are relatively much easier than when $m=2$. When $m=2$, perform an $O(\\log n)$ DP on answer. Notice we have to DP another thing as well. What is it? If $m=1$, it is clear that we only can have $a_1=n$ so the answer is $n$. If $m\\ge3$, $\\left[x,\\frac{n-x}2,\\frac{n-x}2,0,0,...\\right]$ gives a xor of $x$, so all $x$ with the same parity as $n$ and at most $n$ can be achieved. Notice xor and sum are identical in terms of parity, and $a\\oplus b\\le a+b$. So these restrict that only values of $x$ that has same parity with $n$ and is at most $n$ is possible as a result of the xor. Therefore, we can use $O(1)$ to calculate the sum of all non-negative integers at most $n$ and have same parity as $n$. It remains to handle the case when $m=2$. We create the functions $f(n)$ and $g(n)$, where $f(n)$ is the sum of all possible values of the xor and $g(n)$ counts the number of all possible values of the xor. We then consider the following: If $n$ is odd, then one of $a_1,a_2$ is even and the other is odd. WLOG assume $a_1$ is even and $a_2$ is odd. Then we let $a_1'=\\frac{a_1}2$ and $a_2'=\\frac{a_2-1}2$. We can see that $a_1'+a_2'=\\frac{n-1}2$ and $a_1\\oplus a_2=2(a_1'\\oplus a_2')+1$. Hence we know that $g(n)=g\\left(\\frac{n-1}2\\right)$, and $f(n)=2f\\left(\\frac{n-1}2\\right)+g\\left(\\frac{n-1}2\\right)$. If $n$ is even, there are two cases. If $a_1$ and $a_2$ are both even, we let $a_1'=\\frac{a_1}2$ and $a_2'=\\frac{a_2}2$. We can see that $a_1'+a_2'=\\frac{n}2$ and $a_1\\oplus a_2=2(a_1'\\oplus a_2')$. If $a_1$ and $a_2$ are both odd, we let $a_1'=\\frac{a_1-1}2$ and $a_2'=\\frac{a_2-1}2$. We can see that $a_1'+a_2'=\\frac{n}2-1$ and $a_1\\oplus a_2=2(a_1'\\oplus a_2')$. Hence we know that $f(n)=2f\\left(\\frac{n}2\\right)+2f\\left(\\frac{n}2-1\\right)$, and $g(n)=g\\left(\\frac{n}2\\right)+g\\left(\\frac{n}2-1\\right)$. So we can simply DP. It can be seen that the time complexity is $O(\\log n)$ per test case, so we are done.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nunordered_map <long long int,long long int> npos,spos;\n\nconst int MOD=998244353;\n\nlong long int solve(long long int n){\n    if(npos[n]!=0){\n        return spos[n];\n    }\n    if(n%2==1){\n        solve(n/2);\n        npos[n]=npos[n/2];\n        spos[n]=spos[n/2]*2+npos[n/2];\n        spos[n]%=MOD;\n    }\n    else{\n        solve(n/2); solve(n/2-1);\n        npos[n]=npos[n/2]+npos[n/2-1];\n        spos[n]=(spos[n/2]+spos[n/2-1])*2;\n        spos[n]%=MOD;\n    }\n    return spos[n];\n}\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL); cout.tie(NULL);\n    npos[0]=1;\n    spos[0]=0;\n    int t;\n    cin >> t;\n    while(t--){\n        long long int n,m;\n        cin >> n >> m;\n        if(m==2){\n            cout << solve(n) << endl;\n        }\n        else if(m==1){\n            cout << n%MOD << endl;\n        }\n        else if(n%2==0){\n            cout << (((n/2)%MOD)*((n/2+1)%MOD))%MOD << endl;\n        }\n        else{\n            cout << (((n/2+1)%MOD)*((n/2+1)%MOD))%MOD << endl;\n        }\n    }\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1815",
    "index": "E",
    "title": "Bosco and Particle",
    "statement": "Bosco is studying the behaviour of particles. He decided to investigate on the peculiar behaviour of the so-called \"four-one-two\" particle. He does the following:\n\nThere is a line of length $n+1$, where the topmost point is position $0$ and bottommost is position $n+1$. The particle is initially (at time $t=0$) at position $0$ and heading downwards. The particle moves at the speed of $1$ unit per second. There are $n$ oscillators at positions $1,2,\\ldots,n$.\n\nEach oscillator can be described by a binary string. The initial state of each oscillator is the first character of its binary string. When the particle hits with an oscillator, the particle reverses its direction if its current state is $1$ and continues to move at the same direction if its current state is $0$, and that oscillator moves on to the next state (the next state of the last state is defined as the first state). Additionally, the particle always reverses its direction when it is at position $0$ or $n+1$ at time $t > 0$.\n\nBosco would like to know the cycle length of the movement of particle. The cycle length is defined as the minimum value of $c$ such that for any time $t \\ge 0$, the position of the particle at time $t$ is same as the position of the particle at time $t+c$. It can be proved that such value $c$ always exists. As he realises the answer might be too large, he asks you to output your answer modulo $998244353$.",
    "tutorial": "If the oscillator string is periodic, what should we do? Use the case when $n=1$ to help you calculate the answer. Observe that whole process is periodic. Note that the process is reversible. If you are in some state $s$, consisting of position of the particle and the current state position of each oscillator, you can decide the next state and the previous state. This implies the state transition graph is a permutation, so it decomposes into cycles. Firstly, we can easily see that removing cycles for the oscillator strings does not affect the answer. To help us calculating the answer easier, we have to remove cycle. You can remove cycle using any fast enough string algorithm such as KMP. It is not difficult to see that if all strings are non-periodic, then being periodic with respect to the particle position $x$ is the same as being periodic with respect to both $x$ and all oscillator states. Let $a_i$ be the number of times the particle hits oscillator $i$ when moving downwards and $b_i$ be the number of times the particle hits oscillator i when moving upwards in each cycle. For each oscillator $i$, consider the case when $n=1$ and oscillator $i$ is the only oscillator. Let $a'_i$ be the number of times the particle hits oscillator $i$ when moving downwards and $b'_i$ be the number of times the particle hits the oscillator $i$ when moving upwards in each cycle. Then we must have $a_i=ka'_i$ and $b_i=kb'_i$ for some positive integer k. Also, we must have $a_i=b_{i-1}$ as the number of times the particle goes from oscillator $i-1$ to oscillator $i$ is same as the number of times the particle goes from oscillator $i$ to oscillator $i-1$. It can be shown that the smallest integers $a_i$ and $b_i$ satisfying the above constraints must be the period. We can calculate the the smallest such integers, by factoring each $k$ and maintain the primes. In other words, we can separately consider the $p$-adic valuation of the $a'_i$'s and $b'_i$'s to get the $p$-adic valuation of $a_i$'s and $b_i$'s for each prime. Below is a visualisation: Notice the answer is $2(a_1+a_2+...+a_n+b_n)$, which can be easily calculated. So we are done.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nvector <int> prime;\nbool p[1000001];\n \nconst long long int mod=998244353;\n \nvoid init(){\n    p[1]=0;\n    for(int i=2;i<=1000000;i++){\n        p[i]=1;\n    }\n    for(int i=2;i<=1000000;i++){\n        if(p[i]){\n            prime.push_back(i);\n        }\n        for(int j=i;j<=1000000;j+=i){\n            p[j]=0;\n        }\n    }\n    return;\n}\n \nlong long int bigmod(long long int n,long long int k){\n    long long int pown=n,ans=1;\n    while(k>0){\n        if(k%2){\n            ans*=pown;\n            ans%=mod;\n        }\n        pown*=pown;\n        pown%=mod;\n        k/=2;\n    }\n    return ans;\n}\n \nint vp(long long int n,int p){\n    int ans=0;\n    if(n==0){\n        return 10000000;\n    }\n    while(n%p==0){\n        n/=p;\n        ans++;\n    }\n    return ans;\n}\n \nstring rpc(string str){\n    int i=0;\n    int len=str.length();\n    int j=-1;\n    int nextval[len];\n    nextval[i]=-1;\n    while (i<len){\n        if (j==-1||str[i]==str[j]){\n            i++;\n            j++;\n            nextval[i]=j;\n        }\n        else\n        j=nextval[j];\n    }\n    if ((len)%(len-nextval[len])==0) return str.substr(0,len-nextval[len]);\n    else return str;\n}\n \nint main(){\n    init();\n    int n;\n    cin >> n;\n    int lim=n;\n    pair<int,int> arr[n];\n    for(int i=0;i<n;i++){\n        string s;\n        cin >> s;\n        s=rpc(s);\n        int x=0,y=0,ptr=0;\n        bool b=true;\n        do{\n            if(b){\n                x++;\n            }\n            else{\n                y++;\n            }\n            if(s[ptr]=='0'){\n                b=1-b;\n            }\n            ptr++;\n            ptr%=s.length();\n        }while(!b||(ptr!=0));\n        arr[i]={x,y};\n        if(y==0&&lim==n){\n            lim=i;\n        }\n    }\n    long long int times[n+1];\n    for(int i=0;i<=n;i++){\n        times[i]=1;\n    }\n    for(int i=0;i<prime.size();i++){\n        int p=prime[i],curl=0,curr=0,difp[lim+1]={0};\n        for(int j=1;j<=lim;j++){\n            int l=vp(arr[j-1].first,p);\n            int r=vp(arr[j-1].second,p);\n            if(curr<l){\n                curl+=(l-curr);\n                curr=r;\n            }\n            else{\n                curr+=(r-l);\n            }\n            difp[j]=r-l;\n        }\n        int cur=curl;\n        for(int j=0;j<=lim;j++){\n            cur+=difp[j];\n            times[j]*=bigmod(p,cur);\n            times[j]%=mod;\n        }\n    }\n    long long int ans=0;\n    for(int i=0;i<=lim;i++){\n        ans+=times[i];\n        ans%=mod;\n    }\n    cout << (2*ans)%mod << endl;\n}",
    "tags": [
      "dp",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1815",
    "index": "F",
    "title": "OH NO1 (-2-3-4)",
    "statement": "You are given an undirected graph with $n$ vertices and $3m$ edges. The graph may contain multi-edges, but does not contain self-loops.\n\nThe graph satisfies the following property: the given edges can be divided into $m$ groups of $3$, such that each group is a triangle.\n\nA triangle is defined as three edges $(a,b)$, $(b,c)$ and $(c,a)$ for some three distinct vertices $a,b,c$ ($1 \\leq a,b,c \\leq n$).\n\nInitially, each vertex $v$ has a non-negative integer weight $a_v$. For every edge $(u,v)$ in the graph, you \\textbf{should} perform the following operation \\textbf{exactly once}:\n\n- Choose an integer $x$ between $1$ and $4$. Then increase both $a_u$ and $a_v$ by $x$.\n\nAfter performing all operations, the following requirement should be satisfied: if $u$ and $v$ are connected by an edge, then $a_u \\ne a_v$.\n\nIt can be proven this is always possible under the constraints of the task. Output a way to do so, by outputting the choice of $x$ for each edge. It is easy to see that the order of operations does not matter. If there are multiple valid answers, output any.",
    "tutorial": "Go through from vertex $1$ through $n$ and decided their final weights in this order. When deciding the weights for $v$ , make sure it is different from $w$ if $w < v$ and $v$ is adjacent to $w$. Ignore vertices $x$ where $x$ is adjacent to $v$ but have $x > v$. If there are at least $d+1$ options to take from, and $d$ of them are not available, then there is still some option to take. Let's try to decide the final weights of $1$ through $n$ in this order. For a triangle $a<b<c$, we call $a$ the first vertex, $b$ the second vertex, $c$ the third vertex. Consider each triangle individually, if we can achieve the following task then we are done: By only adjusting edges of this triangle: There is at least one option for the first vertex After fixing a particular option for the first vertex, there are at least two options for the the second vertex After fixing particular options for the first two vertices, there are at least three options for the third vertex To see this is enough: Suppose a vertex $v$ is in $A$ triangles as the first vertex, $B$ triangles as the second vertex, and $C$ triangles as the third vertex. It is not difficult to see $v$ have exactly $B + 2 \\times C$ neighbours that are of smaller index, and there are at least $B+ 2\\times C+ 1$ options. Finally, by using the following specific edge weights, the goal can be achieved: $1,4,4$ gives weights $5,5,8$ $2,3,3$ gives weights $5,5,6$ $3,2,2$ gives weights $5,5,4$ $1,4,3$ gives weights $5,4,7$ $2,3,2$ gives weights $5,4,5$ $3,2,1$ gives weights $5,4,3$ These numbers aren't exactly just completely random. You can see that they are composed of two components: A $(+1,-1,-1)$ part and a $(0,0,-1)$ part. Upto two copies of the first option and upto one copy of the second option have been used. There is also a simple solution in this specific case where $G$ consists of triangles and use only weights 1,2,3. This is a special case of 1-2-3 conjecture, which states that the above statement holds for arbitrary graph and using only the weights 1,2,3 (and no 4). Recently (March 2023) it has a claimed proof. The claimed algorithm is far from a linear time algorithm however.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define fi first\n#define se second\nconst ll mod=998244353;\nconst int N=2e6+1;\nll n,m;\nvector<pair<int,int> >adj[N];\narray<int,3>e[N];\narray<int,3>f[N];\nll a[N],b[N];\npair<int,int>vis[10000005];\nvoid solve(){\n    cin >> n >> m;\n    for(int i=1; i<=n ;i++){\n        adj[i].clear();\n    }\n    for(int i=1; i<=n ;i++){\n        cin >> a[i];\n    }\n    for(int i=1; i<=m ;i++){\n        for(int j=0; j<3 ;j++){\n        cin >> e[i][j];\n        adj[e[i][j]].push_back({i,j});\n    }\n        f[i][0]=3;\n        f[i][1]=1;\n        f[i][2]=1;\n        a[e[i][0]]+=f[i][0]+f[i][2];\n        a[e[i][1]]+=f[i][1]+f[i][0];\n        a[e[i][2]]+=f[i][2]+f[i][1];\n    }\n    for(int i=1; i<=n ;i++){\n        for(auto c:adj[i]){\n        for(int d=0; d<c.se ;d++){\n        vis[a[e[c.fi][d]]]={c.fi,d};\n    }\n    }\n        while(vis[a[i]].fi!=0){\n            int ed=vis[a[i]].fi;\n            if(i==e[ed][1]){\n                a[i]++;\n                a[e[ed][2]]++;\n                f[ed][1]++;\n            }\n            else{\n                a[i]+=2;\n\n                f[ed][0]--;\n                f[ed][1]++;\n                f[ed][2]++;\n            }\n        }\n\n        for(auto c:adj[i]){\n        for(int d=0; d<c.se ;d++){\n        vis[a[e[c.fi][d]]]={0,0};\n    }\n    }\n    }\n    for(int i=1; i<=m ;i++){\n        cout << f[i][0] << ' ' << f[i][1] << ' ' << f[i][2] << '\\n';\n    }\n}\nint main(){\n    ios::sync_with_stdio(false);cin.tie(0);\n    int t;cin >> t;while(t--) solve();\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1816",
    "index": "A",
    "title": "Ian Visits Mary",
    "statement": "Ian and Mary are frogs living on lattice points of the Cartesian coordinate plane, with Ian living on $(0,0)$ and Mary living on $(a,b)$.\n\nIan would like to visit Mary by jumping around the Cartesian coordinate plane. Every second, he jumps from his current position $(x_p, y_p)$ to another lattice point $(x_q, y_q)$, such that no lattice point other than $(x_p, y_p)$ and $(x_q, y_q)$ lies on the segment between point $(x_p, y_p)$ and point $(x_q, y_q)$.\n\nAs Ian wants to meet Mary as soon as possible, he wants to jump towards point $(a,b)$ using \\textbf{at most $2$ jumps}. Unfortunately, Ian is not good at maths. Can you help him?\n\nA lattice point is defined as a point with both the $x$-coordinate and $y$-coordinate being integers.",
    "tutorial": "Let us show that Ian can get to Mary within two moves. Indeed, consider $(x_1,y_1)$ and $(x_2,y_2)$ where $x_2-x_1=1$, since the value of the $x$-coordinates of a point lying on the segment joining $(x_1,y_1)$ and $(x_2,y_2)$, and is not at the endpoints, is strictly between $x_1$ and $x_2$, but there are no integers strictly between $x_1$ and $x_2$, the point must not be a lattice point. Similarly, no lattice points lie on the segment joining $(x_1,y_1)$ and $(x_2,y_2)$ with $y_2-y_1=1$ except for the endpoints. Therefore, Ian can jump from $(0,0)$ to $(x-1,1)$ to $(x,y)$. Originally, the problem asks you for the minimal amount of steps, which requires gcd. Since it would be too hard, we had a quite last-minute change to the current statement.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nvoid solve(){\n    int a,b;\n    cin >> a >> b;\n    cout << 2 << \"\\n\" << a-1 << ' ' << 1 << \"\\n\" << a << ' ' << b << \"\\n\";\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1816",
    "index": "B",
    "title": "Grid Reconstruction",
    "statement": "Consider a $2 \\times n$ grid, where $n$ is an \\textbf{even} integer. You may place the integers $1, 2, \\ldots, 2n$ on the grid, using each integer \\textbf{exactly once}.\n\nA path is a sequence of cells achieved by starting at $(1, 1)$, then repeatedly walking either downwards or to the right, and stopping when $(2, n)$ is reached. The path should not extend beyond the grid.\n\nThe cost of a path is the alternating sum of the numbers written on the cells in a path. That is, let the numbers written on the cells be $a_1, a_2, \\ldots, a_k$ (in the order that it is visited), the cost of the path is $a_1 - a_2 + a_3 - a_4 + \\ldots = \\sum_{i=1}^k a_i \\cdot (-1)^{i+1}$.\n\nConstruct a way to place the integers $1, 2, \\ldots, 2n$ on the grid, such that the minimum cost over all paths from $(1, 1)$ to $(2, n)$ is maximized. If there are multiple such grids that result in the maximum value, output any of them.",
    "tutorial": "Consider the parity (odd/even) of $i+j$. What do you observe? Observe that $a_{i,j}$ will be added if $(i+j)$ is even, and will be subtracted otherwise. This forms a checkered pattern. Obviously, it is optimal for all values that will be added to be strictly larger than all values that will be subtracted. Also, the difference between the value of adjacent grids should be almost equal (by some definition of almost). We construct array $a$ as follows: $a_{1,1} = 2n-1$ and $a_{2,n} = 2n$ For $2 \\leq i \\leq n$ and $i$ is even, $a_{1,i} = i$ and $a_{2,i-1} = i - 1$ For $2 \\leq i \\leq n$ and $i$ is odd, $a_{1,i} = n + i - 1$ and $a_{2,i-1} = n + (i - 1) - 1$ For example, when $n=10$, the output will be (This is a very informal proof. See \"Proof\" below for a formal proof.) First of all, due to the checkered pattern, $a_{1,1}, a_{2,2}, a_{1,3}, \\cdots, a_{2,n}$ should be filled with $n+1, n+2, n+3, \\cdots, 2n$, and $a_{2,1}, a_{1,2}, a_{2,3}, \\cdots, a_{1,n}$ should be filled with $1, 2, 3, \\cdots, n$. In particular, $a_{1,1}$ and $a_{2,n}$ should be $2n-1$ and $2n$. Next, as we are trying to maximise the minimum, the difference between paths shouldn't be large (since the minimum path will be smaller if the difference is larger). Notice that a path consists of a prefix of $a_1$ and a suffix of $a_2$, and the difference between $2$ adjacent paths is $\\pm (a_{1,k} - a_{2,k-1})$ (depending on the parity of $k$). It is optimal for the difference to be as small as possible (which is $1$). Finally, it is optimal that $a_{1,k} - a_{2,k-1}$ stays constant in the whole array. If they are different, the difference between $2$ paths (not adjacent) will be larger than $1$, which is suboptimal. Consider the cost of the top right path and bottom left path. The cost of the top right path is $a_{1,1} - a_{1,2} + a_{1,3} - \\cdots - a_{1,n} + a_{2,n}$. The cost of the bottom right path is $a_{1,1} - a_{2,1} + a_{2,2} - a_{2,3} + ... + a_{2,n}$. Summing both values, we get $a_{1,1} + a_{2,n} + ((a_{1,1} - a_{1,2} + a_{1,3} - a_{1,4} + ... - a_{1,n}) + (-a_{2,1} + a_{2,2} - a_{2,3} + ... + a_{2,n}))$ which is equal to $a_{1,1} + a_{2,n} + ((a_{1,1} + a_{2,2} + a_{1,3} + a_{2,4} + \\cdots + a_{2,n}) - (a_{2,1} + a_{1,2} + a_{2,3} + a_{1,4} + \\cdots + a_{1,n}))$ This value attains maximum when $a_{1,1} = 2n$, $a_{2,n} = 2n-1$, $(a_{1,1} + a_{2,2} + a_{1,3} + a_{2,4} + \\cdots + a_{2,n}) = ((n+1) + (n+2) + (n+3) + \\cdots + 2n)$ and $(a_{2,1} + a_{1,2} + a_{2,3} + a_{1,4} + \\cdots + a_{1,n}) = (1 + 2 + 3 + \\cdots + n)$, which is $(2n + (2n - 1) + (\\frac{(n)((n+1)+2n)}{2}) - (\\frac{(n)(1+n)}{2})) = (n^2 + 4n - 1)$. Therefore, the upper bound for the maximum cost is $\\lfloor \\frac{n^2 + 4n - 1}{2} \\rfloor = \\frac{1}{2}n^2 + 2n - 1$. We will now show that the construction above meets the upper bound. Let $P_k$ be the cost of the path $a_{1,1}, a_{1,2}, a_{1,3}, \\cdots, a_{1,k}, a_{2,k}, a_{2,k+1}, \\cdots, a_{2,n}$. Observe that $P_k - P_{k-1} = (-1)^k(a_{1,k} - a_{2,k-1}) = (-1)^k$, as the paths differ by exactly $2$ grids and $a_{1,k} - a_{2,k-1} = 1$ (from the above construction). Calculating $P$, $P_1 = (2n - 1) - 2 + (n + 2) - 4 + (n + 4) - \\cdots - (n - 2) + 2n = (2n - 1) + (n)(\\frac{n}{2} - 1) - n + 2n = \\frac{1}{2}n^2 + 2n - 1$ $P_2 = P_1 + (-1)^2 = \\frac{1}{2}n^2 + 2n$ $P_3 = P_2 + (-1)^3 = \\frac{1}{2}n^2 + 2n - 1$ $\\cdots$ Therefore, $min(P) = \\frac{1}{2}n^2 + 2n - 1$, which achieves the upper bound. Can you find a construction for a $n \\times n$ grid (and give a formal proof)? (We don't have a solution)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        \n        int ans[3][n + 1];\n        \n        ans[1][1] = 2 * n - 1;\n        ans[2][n] = 2 * n;\n\n        for (int i = 2; i <= n; i++) {\n            if (i % 2 == 0) {\n                ans[1][i] = i;\n                ans[2][i - 1] = i - 1;\n            } else {\n                ans[1][i] = n + (i - 1);\n                ans[2][i - 1] = n + (i - 1) - 1;\n            }\n        }\n\n        for (int i = 1; i <= 2; i++) {\n            for (int j = 1; j <= n; j++) {\n                cout << ans[i][j] << (j == n ? '\\n' : ' ');\n            }\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1817",
    "index": "A",
    "title": "Almost Increasing Subsequence",
    "statement": "A sequence is almost-increasing if it does not contain three \\textbf{consecutive} elements $x, y, z$ such that $x\\ge y\\ge z$.\n\nYou are given an array $a_1, a_2, \\dots, a_n$ and $q$ queries.\n\nEach query consists of two integers $1\\le l\\le r\\le n$. For each query, find the length of the longest almost-increasing subsequence of the subarray $a_l, a_{l+1}, \\dots, a_r$.\n\nA subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.",
    "tutorial": "It is not obvious how the condition in the statement for an almost-increasing subsequence can be turned into a fast data structure that can support queries. So instead of tackling the problem head on, let's try to make an upperbound for how many elements can be in the maximum length almost-increasing subsequence. Assume you're given a query about the subarray of the original array $[a_l, a_{l+1}, \\dots, a_r]$. Let's partition this array into decreasing subarrays. This means everytime when $a_i < a_{i+1}$ we place a cut between $a_i$ and $a_{i+1}$. For example, consider the array $[4,6,7,2,2,3]$, it will be cut into $[4], [6], [7, 2, 2], [3]$. All these small subarrays are non-increasing, which means that any subsequence of such a subarray is non-increasing. Because an almost-increasing subsequence cannot have three consecutive elements $x \\geq y \\geq z$, in each of the subarrays of our partition at most $2$ elements can be chosen to insert into our almost-increasing subsequence. Actually we can put exactly $\\min( \\text{|subarray|}, 2)$ elements of each subarray into the increasing subsequence, by taking the first and the last element of each subarray. This is valid, because the cuts for the partition were made at places where $a_i < a_{i+1}$, so every $b_i \\geq b_{i+1}$ in our candidate subsequence is preceded and followed by a $b_j < b_{j+1}$. By our upperbound, this construction is optimal. The sum, $\\sum_\\limits \\text{partition} \\min( \\text{|subarray|}, 2)$ can be calculated for one query in linear time, giving a $O(n q)$ solution. To optimize this, the sum $\\sum_\\limits \\text{partition} \\min( \\text{|subarray|}, 2)$ can be rewritten to $\\sum_\\limits \\text{partition}|\\text{subarray}| - |\\text{inner elements}|$, where inner elements of a subarray are all the elements that are not the first or last element. For such elements $a_i$, we know that $a_{i-1} \\geq a_i \\geq a_{i+1}$. The sum of lengths over the partition sums to $r-l+1$. So we're left with counting the number of special indices $l < i < r$ such that $a_{i-1} \\geq a_i \\geq a_{i+1}$. This can be done with $O(n)$ preprocessing and $O(1)$ queries using prefix sums. For a query we can output $r-l+1 - |\\textit{special} \\ \\text{indices}|$. There are some literal edgecases, where some care in the implementation is needed. The total time complexity is $O(n+q)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\ntypedef vector<int> vi;\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int n,q; cin >> n >> q;\n    vi a(n);\n    for(int& i : a) cin >> i;\n    vi p(n-1);\n    for(int i=1;i<n-1;++i) {\n        int downhill = a[i-1]>=a[i] and a[i]>=a[i+1];\n        p[i] = p[i-1] + downhill;\n    }\n    while(q--) {\n        int l,r; cin >> l >> r;\n        --l,--r;\n        if(l==r) {\n            cout << \"1\\n\";\n        } else {\n            int ans = (r-l+1) - p[r-1] + p[l];\n            cout << ans << '\\n';\n        }\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1817",
    "index": "B",
    "title": "Fish Graph",
    "statement": "You are given a simple undirected graph with $n$ nodes and $m$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $1$ to $n$.\n\nWe define a graph to be a Fish Graph if it contains a simple cycle with a special node $u$ belonging to the cycle. Apart from the edges in the cycle, the graph should have exactly $2$ extra edges. Both edges should connect to node $u$, but they should not be connected to any other node of the cycle.\n\nDetermine if the graph contains a subgraph that is a Fish Graph, and if so, find any such subgraph.\n\nIn this problem, we define a subgraph as a graph obtained by taking any subset of the edges of the original graph.\n\n\\begin{center}\n{\\small Visualization of example 1. The red edges form one possible subgraph that is a Fish Graph.}\n\\end{center}",
    "tutorial": "Problem idea: jeroenodb Preparation: jeroenodb Can you find a necessary condition for whether a Fish Subgraph exists? For the Fish Subgraph to exist, the graph must have a cycle with one node in the cycle having degree at least 4. When the necessary condition is satisfied, actually, you can always find a Fish Subgraph. Try to prove this, and see if your proof can be turned into an algorithm.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1817",
    "index": "B",
    "title": "Fish Graph",
    "statement": "You are given a simple undirected graph with $n$ nodes and $m$ edges. Note that the graph is not necessarily connected. The nodes are labeled from $1$ to $n$.\n\nWe define a graph to be a Fish Graph if it contains a simple cycle with a special node $u$ belonging to the cycle. Apart from the edges in the cycle, the graph should have exactly $2$ extra edges. Both edges should connect to node $u$, but they should not be connected to any other node of the cycle.\n\nDetermine if the graph contains a subgraph that is a Fish Graph, and if so, find any such subgraph.\n\nIn this problem, we define a subgraph as a graph obtained by taking any subset of the edges of the original graph.\n\n\\begin{center}\n{\\small Visualization of example 1. The red edges form one possible subgraph that is a Fish Graph.}\n\\end{center}",
    "tutorial": "Try to prove this, and see if your proof can be turned into an algorithm. Firstly, let's try to find some necessary conditions for a Fish Subgraph to exist. Because the Fish Graph has a cycle with two extra edges attached, the original must contain a cycle with a node in the cycle having degree at least 4. It turns out this condition is actually sufficient, let's prove this: So, assume a graph contains a cycle, and one of the nodes in the cycle has $deg(u) \\geq 4$. We will only look at this cycle, and two extra edges connected to the special node that are not cycle edges, and remove all the other edges from consideration. These two extra edges could have both endpoints inside the cycle, creating diagonal(s) and not the fins of the Fish Graph we want. If both edges don't form diagonals of the cycle, we've found a Fish Graph. Otherwise, let's label the nodes in the cycle $v_1 v_2 \\dots v_k$, and label the two extra edges $e_1$ and $e_2$. Look at the diagonal that connects nodes $v_1$ and $v_d$, with $d>2$ as small as possible. Using it, we find a smaller cycle $v_1 v_2 ... v_d$. To finish the proof, we notice that one of the edges from $\\{e_1,e_2\\}$ and the edge $v_1 v_k$ now have become free to use as fins of the Fish Graph, as they are no longer diagonals of the smaller cycle. $\\square$ This proof can be turned into an algorithm solving the problem. First off, we need to find any cycle with a node with degree $\\geq 4$. Let's brute force the node $u$, which must have degree $\\geq 4$. Then brute force the first edge of the cycle $uv$ (by looping over the adjacency list of node $u$). Now to find any cycle, it suffices to find a path from $v$ to $u$, temporarily deleting the edge $uv$. This can be done with DFS or BFS. When a cycle is found, all edges except $2$ extra edges can be removed from consideration, and the proof for sufficiency can be implemented to fix possible diagonals. For BFS it is even easier, because it already finds the shortest path from $u$ to $v$, making diagonals impossible. The time complexity will be $\\mathcal{O}(m \\cdot (n+m))$, because the algorithm loops over all edges, and does a graph traversal for each of them. Bonus: How do you make this algorithm $\\mathcal{O}(n+m)$?",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n#define all(x) begin(x),end(x)\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ntypedef pair<int,int> pi;\n\nvoid solve() {\n    int n,m; cin >> n >> m;\n    vvi adj(n);\n    while(m--) {\n        int u,v; cin >> u >> v;\n        --u,--v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    // find cycle and node with big degree.\n    for(int u=0;u<n;++u) if(adj[u].size()>=4) for(int v : adj[u]) {\n        // find path from u to v, without edge (u,v)\n        vi cur;\n        vi p;\n        vector<bool> vis(n);\n        auto dfs = [&](auto&& self, int at) -> void {\n            vis[at]=1;\n            cur.push_back(at);\n            if(at==v) {\n                p=cur;\n                return;\n            }\n            for(int to : adj[at]) if(!vis[to]) {\n                if(at==u and to==v) continue;\n                self(self,to);\n                if(!p.empty()) return;\n            }\n            cur.pop_back();\n        };\n        dfs(dfs,u);\n        if(p.empty()) continue;\n        // found cycle, with a node with degree >=4\n        vi extra = adj[u];\n        extra.resize(4);\n        int mn = p.size();\n        for(auto i : extra) {\n            auto it = find(all(p),i);\n            if(it!=p.begin()+1) {\n                mn = min(mn,int(it-p.begin())+1);\n            }\n        }\n        p.resize(mn);\n        partition(all(extra),[&](int i) {return count(all(p),i)==0;});\n        extra.resize(2);\n\n        cout << \"YES\\n\";\n        cout << p.size()+2 << '\\n';\n        auto out = [&](int a, int b) {cout << a+1 << ' ' << b+1 << '\\n';};\n        int prv=p.back();\n        for(auto i : p) {\n            out(i,prv);\n            prv=i;\n        }\n        out(u,extra[0]);\n        out(u,extra[1]);\n        return;\n    }\n\n    cout << \"NO\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t; cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1817",
    "index": "C",
    "title": "Similar Polynomials",
    "statement": "A polynomial $A(x)$ of degree $d$ is an expression of the form $A(x) = a_0 + a_1 x + a_2 x^2 + \\dots + a_d x^d$, where $a_i$ are integers, and $a_d \\neq 0$. Two polynomials $A(x)$ and $B(x)$ are called similar if there is an integer $s$ such that for any integer $x$ it holds that\n\n$$ B(x) \\equiv A(x+s) \\pmod{10^9+7}. $$\n\nFor two similar polynomials $A(x)$ and $B(x)$ of degree $d$, you're given their values in the points $x=0,1,\\dots, d$ modulo $10^9+7$.\n\nFind a value $s$ such that $B(x) \\equiv A(x+s) \\pmod{10^9+7}$ for all integers $x$.",
    "tutorial": "Not that if polynomials are equivalent, they must have the same leading coefficient $k$. Let $A(x) = \\dots + a x^{d-1} + k x^d$ and $B(x) = \\dots + b x^{d-1} + k x^d$. Then $B(x-s) = \\dots + (b-k s d)x^{d-1} + x^d.$ So, if $A(x)$ and $B(x)$ are equivalent, then $A(x) \\equiv B(x-s)$, where $a = b-k s d$, or $s = \\frac{b-a}{kd}$. General remark. On a more intuitive level, you can perceive $s$ as the value by which you should shift the argument of $A(x)$, so that the sums of roots of $A(x)$ and $B(x)$ coincide, as the coefficient near $x^{d-1}$ is just the negated sum of roots of the polynomials. Lagrange interpolation approach. Generally, if $f(x_0)=y_0, \\dots, f(x_d) = y_d$, it is possible to represent $f(x)$ as $f(x) = \\sum\\limits_{i=0}^d y_i \\prod\\limits_{j \\neq i} \\frac{x - x_j}{x_i - x_j}.$ From this, it is possible to find the coefficients near $x^d$ and $x^{d-1}$, that is a sum of corresponding coefficients in each individual summand. Altogether it sums up as $[x^{d}]f(x) = \\sum\\limits_{i=0}^d y_i \\prod\\limits_{j \\neq i} \\frac{1}{x_i - x_j} = \\sum\\limits_{i=0}^d y_i \\prod\\limits_{j \\neq i} \\frac{1}{i-j} = \\sum\\limits_{i=0}^d y_i \\frac{(-1)^{d-i}}{i! (d-i)!}$ Let's denote $c_i = \\frac{(-1)^{d-i}}{i! (d-i)!}$, then it simplifies a bit as $[x^d] f(x) = \\sum\\limits_{i=0}^d y_i c_i,$ and for the coefficient near $d-1$ we should note that $[x^{d-1}] (x-x_1) \\dots (x-x_d) = -(x_1 + \\dots + x_d)$, thus $[x^{d-1}]f(x) = -\\sum\\limits_{i=0}^d y_i c_i \\sum\\limits_{j \\neq i} j = -\\sum\\limits_{i=0}^d y_i c_i \\left(\\frac{d(d+1)}{2} - i\\right).$ Knowing the coefficients near $x^d$ and $x^{d-1}$ for both $A(x)$ and $B(x)$, it is easy to find $a=[x^{d-1}]A(x)$, $b=[x^{d-1}]B(x)$ and $k = [x^d] A(x) = [x^d] B(x)$, which in turn allow us to compute $s$ with the formula above. Finite differences approach. You can consider adjacent differences in values $\\Delta A(i) = A(i) - A(i+1)$. The result $\\Delta A(i)$ is a polynomial in $i$ that has a degree $d-1$. Taking the differences $d-1$ times, we get the values of $\\Delta^{d-1} A(x)$ and $\\Delta^{d-1} B(x)$ in $x=\\{0, 1\\}$. On the other hand, $\\Delta^{d-1} B(x) = \\Delta^{d-1} A(x+s)$, so you still need to find $s$, but $\\Delta^{d-1} A(x)$ and $\\Delta^{d-1} B(x)$ are the polynomials of degree $1$, which makes the whole problem trivial. Note: To compute $\\Delta^{d-1} A(0)$ and $\\Delta^{d-1} A(1)$ in $O(d)$, one can use the binomial formula: $\\Delta^k A(x) = \\sum\\limits_{i=0}^k (-1)^i \\binom{k}{i} A(x+i).$ Indeed, if we denote by $S$ an operator such that $S A(x) = A(x+1)$, then $\\Delta^k A(x)= (I-S)^k A(x)= \\sum\\limits_{i=0}^k (-1)^i \\binom{k}{i} S^i A(x) = \\sum\\limits_{i=0}^k (-1)^i \\binom{k}{i} A(x+i).$",
    "code": "\nconst int mod = 1e9 + 7;\n\nnamespace algebra {\n    const int maxn = 3e6 + 42;\n    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); \n\n    template<typename T>\n    T bpow(T x, size_t n) {\n        if(n == 0) {\n            return T(1);\n        } else {\n            auto t = bpow(x, n / 2);\n            t = t * t;\n            return n % 2 ? x * t : t;\n        }\n    }\n\n    const int m = mod;\n    struct modular {\n        int r;\n        constexpr modular(): r(0) {}\n        constexpr modular(int64_t rr): r(rr % m) {if(r < 0) r += m;}\n        modular inv() const {return bpow(*this, m - 2);}\n        modular operator - () const {return r ? m - r : 0;}\n        modular operator * (const modular &t) const {return (int64_t)r * t.r % m;}\n        modular operator / (const modular &t) const {return *this * t.inv();}\n        modular operator += (const modular &t) {r += t.r; if(r >= m) r -= m; return *this;}\n        modular operator -= (const modular &t) {r -= t.r; if(r < 0) r += m; return *this;}\n        modular operator + (const modular &t) const {return modular(*this) += t;}\n        modular operator - (const modular &t) const {return modular(*this) -= t;}\n        modular operator *= (const modular &t) {return *this = *this * t;}\n        modular operator /= (const modular &t) {return *this = *this / t;}\n        \n        bool operator == (const modular &t) const {return r == t.r;}\n        bool operator != (const modular &t) const {return r != t.r;}\n        bool operator < (const modular &t) const {return r < t.r;}\n        \n        explicit operator int() const {return r;}\n        int64_t rem() const {return 2 * r > m ? r - m : r;}\n    };\n    \n    istream& operator >> (istream &in, modular &x) {\n        return in >> x.r;\n    }\n    \n    ostream& operator << (ostream &out, modular const& x) {\n        return out << x.r;\n    }\n    \n    vector<modular> F(maxn), RF(maxn);\n    \n    template<typename T>\n    T fact(int n) {\n        static bool init = false;\n        if(!init) {\n            F[0] = T(1);\n            for(int i = 1; i < maxn; i++) {\n                F[i] = F[i - 1] * T(i);\n            }\n            init = true;\n        }\n        return F[n];\n    }\n    \n    template<typename T>\n    T rfact(int n) {\n        static bool init = false;\n        if(!init) {\n            RF[maxn - 1] = T(1) / fact<T>(maxn - 1);\n            for(int i = maxn - 2; i >= 0; i--) {\n                RF[i] = RF[i + 1] * T(i + 1);\n            }\n            init = true;\n        }\n        return RF[n];\n    }\n}\n\nusing namespace algebra;\n\nusing base = modular;\n\n\nvoid solve() {\n    int d;\n    cin >> d;\n    vector<base> A(d + 1), B(d + 1);\n    copy_n(istream_iterator<base>(cin), d + 1, begin(A));\n    copy_n(istream_iterator<base>(cin), d + 1, begin(B));\n    base s = 0, k2 = 0;\n    auto coef = [&](int i) {\n        return base((d - i) % 2 ? -1 : 1) * rfact<base>(i) * rfact<base>(d - i);\n    };\n    for(int i = 0; i <= d; i++) {\n        s += (A[i] - B[i]) * coef(i) * (d * (d + 1) / 2 - i);\n        k2 += (A[i] + B[i]) * coef(i);\n    }\n    s *= base(2) / (k2 * d);\n    cout << s << \"\\n\";\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1817",
    "index": "D",
    "title": "Toy Machine",
    "statement": "There is a toy machine with toys arranged in two rows of $n$ cells each ($n$ is odd).\n\n\\begin{center}\nInitial state for $n=9$.\n\\end{center}\n\nInitially, $n-2$ toys are placed in the non-corner cells of the top row. The bottom row is initially empty, and its leftmost, rightmost, and central cells are blocked. There are $4$ buttons to control the toy machine: left, right, up, and down marked by the letters L, R, U, and D correspondingly.\n\nWhen pressing L, R, U, or D, all the toys will be moved simultaneously in the corresponding direction and will only stop if they push into another toy, the wall or a blocked cell. Your goal is to move the $k$-th toy into the leftmost cell of the top row. The toys are numbered from $1$ to $n-2$ from left to right. Given $n$ and $k$, find a solution that uses at most $1\\,000\\,000$ button presses.\n\nTo test out the toy machine, a \\textbf{web page} is available that lets you play the game in real time.",
    "tutorial": "Problem idea: adamant Preparation: jeroenodb Instead of caring about the positions of all the toys, we only need to care about the position of the special toy with index $k$. The other toys can be treated as undistinguishable. The intended way of solving this problem is playing the game in the webpage, trying to come up with some simple combinations of operations that make the special toy move to another position in a predictable way. Using these building blocks in a smart way, finding a way to move the special toy to the topleft. As the size of the grid can be up to $100\\,000$ and we can make $1\\,000\\,000$ moves, we will be aiming for a solution which does a linear number of moves. There are lots of potential solutions which use a linear number of moves, here is a relatively painless one: Do casework on $k$: Case $1$: If $1 \\leq k < \\frac{n-1}{2}$, we initally make one $\\texttt{R}$ button press to align the toys with the right boundary. After this, there is an easy pattern to expose all the toys in the left halve, one by one: $\\texttt{DRURDRUR...}$ repeated. When the special toy is exposed, the repeating pattern is stopped, and $\\texttt{DL}$ are pressed. Toy $k$ will be moved to the topleft corner. Left halve solution for $n=15$. Case $2$: If $k = \\frac{n-1}{2}$, the puzzle can be solved in two moves: $\\texttt{DL}$. Solution for middle toy and $n=15$. Case $3$: If $\\frac{n-1}{2} < k \\leq n-2$, we try to reduce back to case $1$, by moving the special toy to the left halve, and ensuring that all other toys are in the top row. Using symmetry, we can apply case $1$ to $k^\\prime = n-1 - k$, but mirror all horizontal moves, to move the toy to the topright corner. The other toys are no longer all in the top row. To fix this, the last pattern we need is again $\\texttt{DRURDRUR...}$ repeated. After a while of repeating this, all toys will be in the right halve of the board, occupying the top and bottom row. To finish moving the special toy (which stayed in the topright corner), we do the buttons presses $\\texttt{LDRU}$. All toys end up in the top row, and the special toy will be at position $k_\\text{new} = \\frac{n-1}{2} - 1$, so this successfully reduces to case $1$. Full solution for right halve for $n=15$. How many moves does this take? In case $1$ the pattern $\\texttt{DRUR}$ needs to be repeated at most $\\approx \\frac{n}{2}$ times. In case $3$, we need to use the first pattern $\\frac{n}{2}$ times, and we use the second pattern $\\frac{n}{2}$ times. We reduce down to case $1$, but luckily the special toy is already close to the correct position, so only a constant number of extra moves are done. So in total, this solution uses $O(1) + \\max \\left( 4\\frac{n}{2}, 4 \\cdot 2 \\frac{n}{2} \\right) = 4n + O(1)$ moves. So this solution fits well within the constraints, although it is pretty wasteful. Bonus: Can you prove that the optimal number of moves needed in the worstcase (over all $k$) for a width of $n$ is $\\Omega(n)$? We only did some testing of small cases, with a bruteforce BFS solution, and found that the worstcase is around $n/2$ button presses.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nint main() {\n    int n,k; cin >> n >> k;\n    --k;\n    int half = (n-3)/2;\n    string res = \"\";\n    if(k==half) {\n        res = \"DL\";\n    } else {\n        while(true) {\n            if(k<half) {\n                res+=\"R\";\n                int need = half-1-k;\n                while(need--) {\n                    res+=\"DRUR\";\n                }\n                res+=\"DL\";\n                break;\n            } else {\n                int need = k-half-1;\n                while(need--) {\n                    res+=\"LDLU\";\n                }\n                res+=\"LDR\";\n                for(int i=0;i<half+1;++i) {\n                    res+=\"DRUR\";\n                }\n                res+=\"LDRU\"; \n                k = half-1;\n            }\n        }\n    }\n    cout << res << '\\n';\n}",
    "tags": [
      "constructive algorithms",
      "games",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1817",
    "index": "E",
    "title": "Half-sum",
    "statement": "You're given a multiset of non-negative integers $\\{a_1, a_2, \\dots, a_n\\}$.\n\nIn one step you take two elements $x$ and $y$ of the multiset, remove them and insert their mean value $\\frac{x + y}{2}$ back into the multiset.\n\nYou repeat the step described above until you are left with only two numbers $A$ and $B$. What is the maximum possible value of their absolute difference $|A-B|$?\n\nSince the answer is not an integer number, output it modulo $10^9+7$.",
    "tutorial": "Similar to the Huffman encoding, the process described in the statement can be represented as constructing a tree, in which on every step we take two trees with weights $a$ and $b$, and connect them with a shared root into a single tree with weight $\\frac{a+b}{2}$. In the end of the process, we have two trees with weights $A$ and $B$, and we want to maximize $|A-B|$. In these trees, let $h_i$ be the height of the leaf corresponding to $a_i$. Then $a_i$ contributes to the final answer with the coefficient either $2^{-h_i}$, or $-2^{-h_i}$, depending on which tree it is in. If we fix any set $\\{h_1, \\dots, h_n\\}$ and would need to distribute $a_1, \\dots, a_n$ between the heights, assuming $A < B$, it would always be better to send smaller numbers to the $A$-tree and bigger numbers to the $B$-tree, so that the positive impact belongs to bigger numbers and the negative impact belongs to the smaller numbers. That being said, if $a_1 \\leq a_2 \\leq \\dots \\leq a_n$, it is always optimal to choose a number $1 \\leq k < n$ and send $a_1, a_2, \\dots, a_k$ to the $A$-tree, while sending $a_{k+1}, a_{k+2}, \\dots, a_n$ to the $B$-tree. Now we need to understand, how to pick an optimal $k$ and how to construct optimal trees with a fixed $k$. Assume that $a_1, a_2, \\dots, a_k$ will all go to the $A$-tree, for which we want to minimize the weight. What is the optimal distribution of $h_1, h_2, \\dots, h_k$? Turns out, there always exists an optimal configuration, in which the constructed tree is very skewed, in a way that each vertex has at most $1$ child that is not a leaf. Indeed, consider a vertex $v$ which has two children $L$ and $R$, both of which have children of its own. Let $x$ be a leaf with the smallest weight in the whole sub-tree of $v$ (without loss of generality, assume that it's a descendant of $L$). If we swap $x$ with $R$, we will effectively swap coefficients with which $x$ and $R$ contribute to the weight of $A$ overall. In other words, if the initial contribution was $2^{-h_x} \\cdot x + 2^{-h_R} \\cdot R$, it will become $2^{-h_x} \\cdot R + 2^{-h_R} \\cdot x$. Note that $x \\leq R$ and $h_x > h_R$. As a consequence, the later sum is not worse than the former and it's always optimal to swap $x$ and $R$ due to the rearrangement inequality. Similar argument works for the tree $B$, except for we want to maximize sum in it, rather than minimize it. With this in mind, if the split is $a_1, a_2, \\dots, a_k$ and $a_{k+1}, a_{k+2}, \\dots, a_n$, then the heights are $1, 2, 3, \\dots, k-2, k-1, k-1$ for the first block, and similar (but reversed) for the second block. This allows us to find a specific value of $|A-B|$ for each specific $k$ in $O(n)$. How to improve from that? We suggest two possible approaches here. Divide and conquer approach. Assume that the optimal $k$ belongs to the interval $[l, r]$. In this case, all numbers outside the interval will have the same coefficients regardless of specific $k$, as long as $k$ itself is from the interval. This means that we can solve the problem with divide and conquer approach: Let $m = \\lfloor \\frac{r-l}{2}\\rfloor$; Find best $k$ recursively on $[l, m]$ and $[m, r]$; Compare them on the whole $[l; r]$, and return the best of them. Which makes overall $O(n \\log n)$ complexity. Alternative approach. Let's compare the distribution of coefficients for $|A|=k$ and $|A|=k-1$: $\\mathbf{|A| = k}$$-a_1 \\color{green}{2^{-1}}$$-a_2 \\color{green}{2^{-2}}$$\\dots$$-a_{k-2} \\color{green}{2^{-(k-2)}}$$-a_{k-1} \\color{red}{2^{-(k-1)}}$$-a_k \\color{red}{2^{-(k-1)}}$$a_{k+1} \\color{red}{2^{-(n-k-1)}}$$a_{k+2} \\color{green}{2^{-(n-k-1)}}$$\\dots$$a_{n-1} \\color{green}{2^{-2}}$$a_{n} \\color{green}{2^{-1}}$$\\mathbf{|A| = k-1}$$-a_1 \\color{green}{2^{-1}}$$-a_2 \\color{green}{2^{-2}}$$\\dots$$-a_{k-2} \\color{green}{2^{-(k-2)}}$$-a_{k-1} \\color{blue}{2^{-(k-2)}}$$a_k \\color{blue}{2^{-(n-k)}}$$a_{k+1} \\color{blue}{2^{-(n-k)}}$$a_{k+2} \\color{green}{2^{-(n-k-1)}}$$\\dots$$a_{n-1} \\color{green}{2^{-2}}$$a_{n} \\color{green}{2^{-1}}$ As you see, almost all coefficients stay the same, except for coefficients near $a_{k-1}$, $a_k$ and $a_{k+1}$: $\\mathbf{|A|=k}$$\\mathbf{|A|=k-1}$$a_{k-1} \\cdot \\square$$-2^{-(k-1)}$$-2^{-(k-2)}$$a_{k} \\cdot \\square$$-2^{-(k-1)}$$2^{-(n-k)}$$a_{k+1} \\cdot \\square$$2^{-(n-k-1)}$$2^{-(n-k)}$ Therefore, let $f(k)$ be the optimal answer for $|A|=k$, and let $\\alpha=k-1$, $\\beta=n-k$ we may say that $f(k) - f(k-1) = (a_{k+1}-a_k)2^{-\\beta} - (a_k - a_{k-1}) 2^{-\\alpha}.$ Or, multiplying it with $2^n$ we get $2^n[f(k) - f(k-1)] = (a_{k+1}-a_k)2^{k} - (a_k - a_{k-1}) 2^{n-k+1}.$ We can sum it up to get the difference between $f(k)$ and $f(j)$ for arbitrary $j < k$: $2^n [f(k) - f(j)] = (d_k 2^k + \\dots + d_{j+1} 2^{j+1}) - (d_{k-1}2^{n-(k-1)} + \\dots + d_j 2^{n-j}),$ where $d_i = a_{i+1} - a_i$. Then, assuming $d_k > 0$, we can bound it as $2^n [f(k) - f(j)] \\geq 2^k - 2^{n-j}\\max d_i = 2^k - 2^{n-j+\\log \\max d_i}.$ The later means that $f(k) > f(j)$ when $k + j > n + \\log \\max d_i$, which is the case when $k > \\frac{n}{2} + \\log \\max d_i$ and $j \\geq \\frac{n}{2}$. By the same argument, we may show that $f(k) > f(j)$ when $k < \\frac{n}{2} - \\log \\max d_i$ and $k < j < \\frac{n}{2}$. In other words, it means that one of the following holds for the value $k$, on which the maximum value of $f(k)$ is achieved: $k$ is the first position in the array, at which $d_k = a_{k+1} - a_k > 0$, $k$ is the last position in the array, at which $d_k = a_{k+1} - a_k > 0$, $k$ belongs to the segment $[\\frac{n}{2} - \\log \\max d_i, \\frac{n}{2} + \\log \\max d_i] \\subset [\\frac{n}{2}-30, \\frac{n}{2}+30]$. Therefore, there are at most $64$ positions of interest in the array which can be checked manually. Moreover, optimal value in the segment $[\\frac{n}{2}-30, \\frac{n}{2}+30]$ can be found by checking every possible position while ignoring all the elements outside of the segment (due to the result from the divide and conquer approach). This allows, assuming $a_1 \\leq a_2 \\leq \\dots \\leq a_n$, to resolve the problem in $O(n)$.",
    "code": "// split into 1, ..., k and k+1, ..., n\npair<int, istring> check_k(istring const& a, int k) {\n    int n = size(a);\n    istring A(n, 0), B(n, 0);\n    for(int i = 0; i < n; i++) {\n        if(i <= k) {\n            A[min(k, i + 1)] += a[i];\n        } else {\n            B[min(n - k - 2, n - i)] += a[i];\n        }\n    }\n    // multiply by 2^(n - i - 1) instead of dividing by 2^i\n    reverse(all(A));\n    reverse(all(B));\n    int carry = 0;\n    // subtract A from B and normalize base 2\n    for(int i = 0; i < n; i++) {\n        B[i] -= A[i] - carry;\n        carry = B[i] >> 1; // floor(B[i] / 2)\n        B[i] &= 1;\n    }\n    if(carry < 0) {\n        return {-1, {}}; // it's always possible to make it positive\n    }\n    while(carry) {\n        B.push_back(carry & 1);\n        carry >>= 1; \n    }\n    while(!B.empty() && B.back() == 0) {\n        B.pop_back();\n    }\n    reverse(all(B));\n    return {(int)size(B) - n, B};\n}\n\nconst int mod = 1e9 + 7;\n\nint bpow(int x, int n) {\n    if(!n) {\n        return 1;\n    } else if(n % 2) {\n        return int64_t(x) * bpow(x, n - 1) % mod;\n    } else {\n        return bpow(int64_t(x) * x % mod, n / 2);\n    }\n}\n\nint inv(int x) {\n    return bpow(x, mod - 2);\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    istring a(n, 0);\n    for(int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    sort(all(a));\n    auto cand = check_k(a, 0);\n    int cnt = 0;\n    for(int i = 1; i < n; i++) {\n        if(a[i] != a[i - 1]) {\n            cand = max(cand, check_k(a, i - 1));\n            cnt++;\n            if(cnt == 30) {\n                break;\n            }\n        }\n    }\n    cnt = 0;\n    istring b = a;\n    reverse(all(b));\n    for(int i = 1; i < n; i++) {\n        if(b[i] != b[i - 1]) {\n            cand = max(cand, check_k(a, n - i - 1));\n            cnt++;\n            if(cnt == 30) {\n                break;\n            }\n        }\n    }\n    auto [sz, ansf] = cand;\n    int ans = 0;\n    for(size_t i = 0; i < size(ansf); i++) {\n        ans = (ans + bpow(2, (mod - 1) + (sz - i)) * ansf[i]) % mod;\n    }\n    cout << ans << \"\\n\";\n}",
    "tags": [
      "brute force",
      "divide and conquer",
      "greedy"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1817",
    "index": "F",
    "title": "Entangled Substrings",
    "statement": "\\begin{quote}\nQuantum entanglement is when two particles link together in a certain way no matter how far apart they are in space.\n\\end{quote}\n\nYou are given a string $s$. A pair of its non-empty substrings $(a, b)$ is called entangled if there is a (possibly empty) link string $c$ such that:\n\n- Every occurrence of $a$ in $s$ is immediately followed by $cb$;\n- Every occurrence of $b$ in $s$ is immediately preceded by $ac$.\n\nIn other words, $a$ and $b$ occur in $s$ only as substrings of $acb$. Compute the total number of entangled pairs of substrings of $s$.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.",
    "tutorial": "Suffix automaton approach. For every substring $a$ of $s$ we can define the longest string $\\hat{a}$ such that $a$ only occurs in $s$ as a specific substring of $\\hat{a}$. To find $\\hat{a}$, we find the longest strings $x$ and $y$ such that the occurrences of $a$ are always preceded by $x$ and always succeeded by $y$. Then, we can say that $\\hat{a} = x a y$. If you're familiar with suffix structures you would recognize that in this terms, $xa$ is the longest string that belongs to the same state of the suffix automaton of $s$ as $a$. Knowing that, how would we find $\\hat{a} = x a y$? When we add a new character at the end of a substring, we make a transition in the suffix automaton via this character. Generally, if the state of the string $xa$ has transitions via two different characters, it would mean that the string $y$ is empty, as it means that different strings may succeed the occurrences of $xa$. Also, if the state is terminal, it would mean that the last occurrence of $xa$ is at the suffix of $s$ and it can not be succeeded by any non-empty string. If the state is not terminal, and its only transition is by a character $c$, it means that the string $xa$ is always succeeded by $c$. The facts above mean that to find $xay$, we may start with the state of the suffix automaton that corresponds to the string $a$, and then, while the state is non-terminal, and it only has a single out-going transition, we move to a next state via this transition. In the end, $xay$ would be the longest string of the state we ended up in. Now back to the problem. Note that if a string $a$ only occurs in $s$ as a substring of another string $t$, it means that $\\hat{a} = \\hat{t}$. In terms of the strings $a$, $b$ and $c$ from the statement it means that $\\hat{a} = \\hat{b} = \\widehat{acb}$. Assume that we grouped together the states of the suffix automaton that end up in the same state if you follow unique out-going transitions from them until you get into a state with two possible transitions, or a terminal state. Each group corresponds to a unique largest string such that any string that belongs to any state from the group only occurs in $s$ as a specific substring of the largest string. Note that for strings that belong to the same state of the suffix automaton, they also have the same string $y$. The length $|y|$ determines the unique position in which all the strings from the state occur in the largest string as set of nested suffixes. So, for the largest string $t$, their right position of occurrences will be $|t|-|y|$, and their lengths form the contiguous segment $[len(link(q)) + 1, len(q)]$. Thus, the whole problem reduces for each group of states to the following: We have a bunch of triplets $(l_1, l_2, r)$. Each triple denotes a set of segments $[l_1, r], [l_1 + 1, r], \\dots, [l_2, r]$. You need to count the number of non-overlapping pairs of segments. This can be done in $O(n \\log n)$ with the help of segment tree. Suffix array approach. There is an alternative solution using suffix arrays (suggested by Dario). Let $a_0, \\dots, a_{n-1}$ be the suffix array and $b_0, \\dots, b_{n-2}$ be the longest common prefix of adjacent elements of the suffix array. We say that $[l, r]$ is good for length $len$ if the positions $a[l, r]$ are exactly the occurrences of a sub-string of length $len$. This is equivalent to $b_{l-1}, b_r < len$ and $b_i \\geq len$ for all $l \\leq i < r$. There are at most $O(n)$ good intervals (an interval is good if it is good for any length). Indeed they are a subset of the sub-trees of the Cartesian tree of the array $b$. Now we iterate over the good intervals. Let $[l, r]$ be a good intervals for the lengths $[u, v]$. Consider a translation $t$ and check if by adding $t$ to all elements $a_l, a_{l+1}, .., a_r$ one gets a good interval. This can be checked in $O(1)$. This check can be done from $t=u$ to $t=v$ and one can stop as soon as a bad $t$ is found. If t is a good translation; then we can count in $O(1)$ the corresponding good pairs of sub-strings $A, B$. And this concludes the problem. It remains to perform quickly step 3. Given two good intervals $I, J$ we say that $J$ follows $I$ if $a[J]$ coincides with the array one obtains adding $1$ to all elements of $a[I]$. The \"following\" relationship creates a family of chains on the good intervals. One performs step 3 independently on the various chains.",
    "code": "map<char, int> to[maxn];\nint len[maxn], link[maxn];\nint last, sz = 1;\n\nvoid add_letter(char c) {\n    int p = last;\n    last = sz++;\n    len[last] = len[p] + 1;\n    for(; to[p][c] == 0; p = link[p]) {\n        to[p][c] = last;\n    }\n    int q = to[p][c];\n    if(q != last) {\n        if(len[q] == len[p] + 1) {\n            link[last] = q;\n        } else {\n            int cl = sz++;\n            len[cl] = len[p] + 1;\n            link[cl] = link[q];\n            to[cl] = to[q];\n            link[last] = link[q] = cl;\n            for(; to[p][c] == q; p = link[p]) {\n                to[p][c] = cl;\n            }\n        }\n    }\n}\n\nint term[maxn];\nint used[maxn], comp[maxn], dist[maxn];\nvector<int> in_comp[maxn];\n\nvoid dfs(int v = 0) {\n    comp[v] = v;\n    dist[v] = 0;\n    used[v] = 1;\n    for(auto [c, u]: to[v]) {\n        if(!used[u]) {\n            dfs(u);\n        }\n        if(to[v].size() == 1 && !term[v]) {\n            comp[v] = comp[u];\n            dist[v] = dist[u] + 1;\n        }\n    }\n    in_comp[comp[v]].push_back(v);\n}\n\nvoid solve() {\n    string s;\n    cin >> s;\n    for(auto c: s) {\n        add_letter(c);\n    }\n    for(int p = last; p; p = link[p]) {\n        term[p] = 1;\n    }\n    term[0] = 1;\n    dfs();\n    int64_t ans = 0;\n    for(int v = 0; v < sz; v++) {\n        if(in_comp[v].size()) {\n            int m = in_comp[v].size();\n            sort(all(in_comp[v]), [&](int a, int b) {\n                return dist[a] > dist[b];\n            });\n            vector<int64_t> A(m), B(m);\n            for(int i = 0; i < m; i++) {\n                int u = in_comp[v][i];\n                int L = dist[u];\n                int R = L + len[link[u]];\n                // L' must be larger than R\n                int cnt = len[u] - len[link[u]];\n                A[i] = (int64_t)cnt * L;\n                B[i] = cnt;\n                if(i > 0) {\n                    A[i] += A[i - 1];\n                    B[i] += B[i - 1];\n                }\n                auto it = upper_bound(all(in_comp[v]), R, [&](int R, int b) {\n                    return R > dist[b];\n                }) - begin(in_comp[v]);\n                if(it) {\n                    it--;\n                    ans += A[it] - B[it] * R;\n                }\n            }\n        }\n    }\n    cout << ans << \"\\n\";\n}",
    "tags": [
      "string suffix structures",
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1818",
    "index": "A",
    "title": "Politics",
    "statement": "In a debate club with $n$ members, including yourself (member $1$), there are $k$ opinions to be discussed in sequence. During each discussion, members express their agreement or disagreement with the opinion. Let's define $Y$ as the number of members who agree and $N$ as the number of members who disagree. After each discussion, members leave the club based on the following criteria:\n\n- If more members agree than disagree ($Y > N$), all members who disagreed leave the club.\n- If more members disagree than agree ($Y < N$), all members who agreed leave the club.\n- If there is a tie ($Y = N$), all members leave the club.\n\nAs the club president, your goal is to stay in the club and maximize the number of members remaining after the meeting. You have access to each member's stance on all $k$ opinions before the meeting starts, and you can expel any number of members (excluding yourself) before the meeting begins.\n\nDetermine the maximum number of members, including yourself, who can remain in the club after the meeting. You don't need to provide the specific expulsion strategy but only the maximum number of members that can stay. Ensure that you remain in the club after the meeting as well.",
    "tutorial": "The members that stay in the end must have the same take about each of the discussed opinions (if takes about some opinion differ for two members, at least one of them should have left during the discussion of that opinion). It means that the people that are left must all have the same takes as the president. On the other hand, all such people can stay if you expel everybody else in advance, so the problem just asks you to count the number of people with the same takes on all opinions as the president.",
    "code": "void solve() {\n    int n, k;\n    cin >> n >> k;\n    string t[n];\n    int ans = n;\n    for(int i = 0; i < n; i++) {\n        cin >> t[i];\n        if(t[i] != t[0]) {\n            ans--;\n        }\n    }\n    cout << ans << \"\\n\";\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1818",
    "index": "B",
    "title": "Indivisible",
    "statement": "You're given a positive integer $n$.\n\nFind a permutation $a_1, a_2, \\dots, a_n$ such that for any $1 \\leq l < r \\leq n$, the sum $a_l + a_{l+1} + \\dots + a_r$ is not divisible by $r-l+1$.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "If $n > 1$ is odd, there is no solution, as the sum of the whole array $\\frac{n(n+1)}{2}$ is always divisible by $n$. Otherwise, the solution is as follows: Start with the identity permutation $1, 2, \\dots, n$. Swap the adjacent pairs to get $2, 1, 4, 3, 6, 5, ..., n, n-1$. Indeed, consider the sum of a sub-array $a_l, \\dots, a_r$. There are $2$ cases: $l$ and $r$ have different parity: the sum is $\\frac{(r-l+1)(l+r)}{2}$ and its greatest common divisor with $r-l+1$ is $\\frac{r-l+1}{2}$, as $l+r$ is not divisible by $2$; $l$ and $r$ have the same parity: the sum is $\\frac{(r-l+1)(l+r)}{2}+1$ or $\\frac{(r-l+1)(l+r)}{2}-1$, depending on the parity. The first summand is divisible by $r-l+1$, as $l+r$ is even. So, the whole sum has the remainder $1$ or $-1$ modulo $r-l+1$, thus it can't be divisible by it.",
    "code": "void solve() {\n    int n;\n    cin >> n;\n    if(n == 1) {\n        cout << 1 << \"\\n\";\n    } else if(n % 2) {\n        cout << -1 << \"\\n\";\n    } else {\n        int a[n];\n        iota(a, a + n, 1);\n        for(int i = 0; i < n; i += 2) {\n            swap(a[i], a[i + 1]);\n        }\n        for(auto it: a) {\n            cout << it << ' ';\n        }\n        cout << \"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 900
  },
  {
    "contest_id": "1819",
    "index": "A",
    "title": "Constructive Problem",
    "statement": "As you know, any problem that does not require the use of complex data structures is considered constructive. You are offered to solve one of such problems.\n\nYou are given an array $a$ of $n$ non-negative integers. You are allowed to perform the following operation \\textbf{exactly once}: choose some non-empty subsegment $a_l, a_{l+1}, \\ldots, a_r$ of the array $a$ and a non-negative integer $k$, and assign value $k$ to all elements of the array on the chosen subsegment.\n\nThe task is to find out whether $\\operatorname{MEX}(a)$ can be increased by exactly one by performing such an operation. In other words, if before the operation $\\operatorname{MEX}(a) = m$ held, then after the operation it must hold that $\\operatorname{MEX}(a) = m + 1$.\n\nRecall that $\\operatorname{MEX}$ of a set of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $x$ which does not occur in the set $c$.",
    "tutorial": "Let the current value of mex equal to $m$ and the value of mex after performing operation equals to $m'$. It's easy to see that in the resulting array there should exist element equals to $m + 1$ (if it doesn't exist, the value of mex won't be equal to $m + 1$). Also notice that $k$ should be equal to $m$ because this value didn't appear in the array before the operation and must appear there after performing the operation. Consider the following cases. If there exists such $i$ that $a_i = m + 1$, let's find the minimum value $l$ and the maximum value $r$ such that $a_l = a_r = m + 1$. It's easy to see that the performed operation should cover these elements. We already know which value of $k$ to select. Now notice that there are no profits from using longer segments because $m'$ is already not greater than $m + 1$ (there are no elements equal to $m + 1$) and longer segments may make $m'$ less. If there is no such $i$ that $a_i = m$ but there exists $i$ such that $a_i > m + 1$, $m'$ is already not greater than $m + 1$. Similarly with the previous case, we can find any $i$ such that $a_i > m + 1$ and replace $a_i$ with $m$. In all other cases if there exist two indices $i \\ne j$ such that $a_i = a_j$, we can replace one of these elements with $m$. In this case we will make $m'$ equals to $m + 1$. If there are no such indices, $m$ equals to the length of the array and we cannot increment $m$. The only thing we have to do after considering cases is to check if the performed operation leads to correct value of $m'$. Time complexity: $\\mathcal{O}(n \\log n)$.",
    "code": "//  Nikita Golikov, 2023\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing uint = unsigned int;\nusing ll = long long;\nusing ull = unsigned long long;\n\n#ifdef GOLIKOV\n    #define debug(x) cerr << (#x) << \":\\t\" << (x) << endl\n#else\n    #define debug(x) 238;\n#endif\n\ntemplate <class A, class B>\nbool smin(A& x, B&& y) {\n  if (y < x) {\n    x = y;\n    return true;\n  }\n  return false;\n}\n\ntemplate <class A, class B>\nbool smax(A& x, B&& y) {\n  if (x < y) {\n    x = y;\n    return true;\n  }\n  return false;\n}\n\ntemplate <class T>\nint calcMex(vector<T> v) {\n  sort(v.begin(), v.end());\n  v.erase(unique(v.begin(), v.end()), v.end());\n  int n = int(v.size());\n  for (int i = 0; i < n; ++i) if (v[i] != i) return i;\n  return n;\n}\n\nbool solveTest() {\n  int n; cin >> n;\n  vector<int> a(n);\n  map<int, int> leftOcc, rightOcc;\n  for (int i = 0; i < n; ++i) {\n    cin >> a[i];\n    rightOcc[a[i]] = i;\n    if (!leftOcc.count(a[i])) leftOcc[a[i]] = i;\n  }\n  int mex = calcMex(a);\n  if (leftOcc.count(mex + 1)) {\n    int L = leftOcc[mex + 1], R = rightOcc[mex + 1];\n    for (int i = L; i <= R; ++i) {\n      a[i] = mex;\n    }\n    int mx = calcMex(a);\n    assert(mx <= mex + 1);\n    return mx == mex + 1;\n  }\n  for (int i = 0; i < n; ++i) {\n    assert(a[i] != mex);\n    if (a[i] > mex || (leftOcc[a[i]] != rightOcc[a[i]])) {\n      return true;\n    }\n  }\n  return false;\n}\n\nint main() {\n#ifdef GOLIKOV\n  assert(freopen(\"in\", \"rt\", stdin));\n  auto _clock_start = chrono::high_resolution_clock::now();\n#endif\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n\n  int t; cin >> t;\n  while (t--) {\n    cout << (solveTest() ? \"Yes\" : \"No\") << '\\n';\n  }\n\n#ifdef GOLIKOV\n  cerr << \"Executed in \" << chrono::duration_cast<chrono::milliseconds>(\n      chrono::high_resolution_clock::now()\n          - _clock_start).count() << \"ms.\" << endl;\n#endif\n  return 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1819",
    "index": "B",
    "title": "The Butcher",
    "statement": "Anton plays his favorite game \"Defense of The Ancients 2\" for his favorite hero — The Butcher. Now he wants to make his own dinner. To do this he will take a rectangle of height $h$ and width $w$, then make a vertical or horizontal cut so that both resulting parts have integer sides. After that, he will put one of the parts in the box and cut the other again, and so on.\n\nMore formally, a rectangle of size $h \\times w$ can be cut into two parts of sizes $x \\times w$ and $(h - x) \\times w$, where $x$ is an integer from $1$ to $(h - 1)$, or into two parts of sizes $h \\times y$ and $h \\times (w - y)$, where $y$ is an integer from $1$ to $(w - 1)$.\n\nHe will repeat this operation $n - 1$ times, and then put the remaining rectangle into the box too. Thus, the box will contain $n$ rectangles, of which $n - 1$ rectangles were put in the box as a result of the cuts, and the $n$-th rectangle is the one that the Butcher has left after all $n - 1$ cuts.\n\nUnfortunately, Butcher forgot the numbers $h$ and $w$, but he still has $n$ rectangles mixed in random order. Note that Butcher \\textbf{didn't rotate the rectangles}, but only shuffled them. Now he wants to know all possible pairs $(h, w)$ from which this set of rectangles can be obtained. And you have to help him do it!\n\nIt is guaranteed that there exists at least one pair $(h, w)$ from which this set of rectangles can be obtained.",
    "tutorial": "Note that we know the area of the original rectangle. This value can be calculated as the sum of the areas of the given rectangles. Now let's consider two similar cases: the first cut was horizontal or the first cut was vertical. We will present the solution for the first case, the second one is considered similarly. If the first cut was horizontal, then there exists a rectangle which width is equal to the width of the entire original rectangle. Moreover, it's easy to notice that this is a rectangle with the maximum width. Knowing the width and area, we also know the height of the rectangle we need. The only thing left is to come up with an algorithm that, for given $h$ and $w$, tells us whether it is possible to construct a rectangle with such dimensions. We will perform the following procedure: let us have a rectangle $\\{h', w'\\}$ for which $h' = h$ or $w' = w$ holds, and cut off our current rectangle with the rectangle $\\{h', w'\\}$. Formally, if $w' = w$, we will make $h -= h'$, if $h = h'$, we will make $w -= w'$. Note that this greedy algorithm is correct, since at each iteration we performed either a horizontal cut or a vertical cut. Thus, at each iteration of our algorithm, we should have only one option: to remove some rectangle corresponding to a vertical cut or to remove a rectangle corresponding to a horizontal cut. We can choose any of these rectangles. Having performed this algorithm in the case where the first cut was vertical and in the case where the first cut was horizontal, we will check both potential answers. Time complexity: $\\mathcal{O}(n \\log n)$.",
    "code": "//#pragma GCC target(\"trapv\")\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <string>\n#include <cmath>\n#include <map>\n#include <iostream>\n#include <list>\n#include <stack>\n#include <cassert>\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\n\n#define fastInp cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);\n\nconst ll INF = 1e9 * 1e9 + 100, SZ = 1100;\n\nll n;\nvector<pair<ll, ll>> vec;\nmap<ll, pair<ll, ll>> blocks;\n\npair<ll, ll> solve() {\n\tset<pair<ll, ll>> widest, longest;\n\n\tfor (size_t i = 0; i < vec.size(); i++) {\n\t\twidest.insert({ vec[i].first, i });\n\t\tlongest.insert({ vec[i].second, i });\n\n\t\tblocks[i] = vec[i];\n\t}\n\n\tpair<ll, ll> ans = { -1, -1 };\n\tbool mode = 0;\n\tll prevw = INF, prevh = INF, prv = -1;\n\tbool cringe = 0;\n\twhile (widest.size() != 0) {\n\t\tif (mode == 0) {\n\t\t\tll cur = (*widest.rbegin()).first, sum = 0;\n\t\t\tif (ans.second == -1) ans.second = cur;\n\t\t\tprv = blocks[(*widest.rbegin()).second].second;\n\n\t\t\twhile (widest.size() > 0 && (*widest.rbegin()).first == cur) {\n\t\t\t\tauto it = (--widest.end());\n\t\t\t\tlongest.erase({blocks[it->second].second, it->second });\n\t\t\t\tsum += blocks[it->second].second;\n\t\t\t\twidest.erase(it);\n\t\t\t}\n\n\t\t\tif (!cringe) ans.first = sum;\n\t\t\tprv = sum;\n\t\t\tif (prevw == INF) {\n\t\t\t\tprevh = cur;\n\t\t\t} else {\n\t\t\t\tprevw -= sum;\n\t\t\t\tif (prevh != cur) return { -1, -1 };\n\t\t\t}\n\t\t} else {\n\t\t\tll cur = (*longest.rbegin()).first, sum = 0;\n\t\t\tif (!cringe) {\n\t\t\t\tans.first = cur + prv;\n\t\t\t\tcringe = 1;\n\t\t\t}\n\n\t\t\twhile (longest.size() > 0 && (*longest.rbegin()).first == cur) {\n\t\t\t\tauto it = (--longest.end());\n\t\t\t\twidest.erase({ blocks[it->second].first, it->second });\n\t\t\t\tsum += blocks[it->second].first;\n\t\t\t\tlongest.erase(it);\n\t\t\t}\n\n\t\t\tif (prevw == INF) {\n\t\t\t\tprevw = cur;\n\t\t\t\tprevh -= sum;\n\t\t\t\tif (prevw != cur) return { -1, -1 };\n\t\t\t} else {\n\t\t\t\tprevh -= sum;\n\t\t\t\tif (prevw != cur) return { -1, -1 };\n\t\t\t}\n\t\t}\n\n\t\tmode ^= 1;\n\t}\n\n\tif (prevh == 0 || prevw == 0 || prevh == INF || prevw == INF) {\n\t\treturn ans;\n\t} else {\n\t\treturn { -1, -1 };\n\t}\n}\n\nsigned main() {\n\tfastInp;\n\n    ll t;\n    cin >> t;\n    \n    while (t--) {\n        vec.clear();\n        blocks.clear();\n    \tcin >> n;\n    \n    \tvec.resize(n);\n    \tfor (auto& c : vec) cin >> c.first >> c.second;\n    \n    \tvector<pair<ll, ll>> ans;\n    \n    \tans.push_back(solve());\n    \tswap(ans.back().first, ans.back().second);\n    \tif (ans.back().first == -1) ans.pop_back();\n    \n    \tfor (auto& c : vec) swap(c.first, c.second);\n    \n    \tans.push_back(solve());\n    \tif (ans.back().first == -1) ans.pop_back();\n    \n    \tif (ans.size() == 2 && ans[0] == ans[1]) {\n    \t\tans.pop_back();\n    \t}\n    \tcout << ans.size() << \"\\n\";\n    \n    \tfor (auto c : ans) cout << c.first << \" \" << c.second << \"\\n\";\n    }\n    \n\treturn 0;\n}",
    "tags": [
      "geometry",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1819",
    "index": "C",
    "title": "The Fox and the Complete Tree Traversal",
    "statement": "The fox Yae climbed the tree of the Sacred Sakura. A tree is a connected undirected graph that does not contain cycles.\n\nThe fox uses her magical powers to move around the tree. Yae can jump from vertex $v$ to another vertex $u$ if and only if the distance between these vertices does not exceed $2$. In other words, in one jump Yae can jump from vertex $v$ to vertex $u$ if vertices $v$ and $u$ are connected by an edge, or if there exists such vertex $w$ that vertices $v$ and $w$ are connected by an edge, and also vertices $u$ and $w$ are connected by an edge.\n\nAfter Yae was able to get the sakura petal, she wondered if there was a \\textbf{cyclic} route in the tree $v_1, v_2, \\ldots, v_n$ such that:\n\n- the fox can jump from vertex $v_i$ to vertex $v_{i + 1}$,\n- the fox can jump from vertex $v_n$ to vertex $v_1$,\n- all $v_i$ are pairwise distinct.\n\nHelp the fox determine if the required traversal exists.",
    "tutorial": "Note that if the tree contains the subgraph shown below, then there is no answer. To prove this it is enough to consider all possible cases for how a cyclic route can pass through the upper vertex and understand that it is impossible to construct such route. Let's assume that the tree does not contain the subgraph shown. It is easy to see that in this case, the tree can be represented as a path and vertices directly attached to it. To check that the tree can be represented in this way, we will find the diameter of the tree and check that all other vertices are directly connected to it. Now we need to learn how to build a cyclic route. Number the vertices of the diameter from $1$ to $k$ in the order of traversal of the diameter from one end to the other. Now let's build the route as follows. Firstly, visit vertex $1$, then visit all vertices not on the diameter attached to vertex $2$, then move to vertex $3$, then to all vertices not on the diameter attached to vertex $4$, and so on. When we reach the end of the diameter, we will visit all vertices of the diameter with even numbers, as well as all vertices of the tree not on the diameter attached to the vertices of the diameter with odd numbers. Now let's make the same route in the opposite direction along the diameter, but through vertices of a different parity, which reaches vertex $2$. Time complexity: $\\mathcal{O}(n)$.",
    "code": "// #pragma comment(linker, \"/stack:200000000\")\n// #pragma GCC optimize(\"Ofast,no-stack-protector\")\n// #pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native\")\n// #pragma GCC optimize(\"unroll-loops\")\n\n#include <stdio.h>\n#include <bits/stdc++.h>\n\n#ifdef PERVEEVM_LOCAL\n    #define debug(x) std::cerr << (#x) << \":\\t\" << (x) << std::endl\n#else\n    #define debug(x) 238\n#endif\n\n#define fastIO std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0)\n#define NAME \"File\"\n\nusing ll = long long;\nusing ld = long double;\n\n#ifdef PERVEEVM_LOCAL\n    std::mt19937 rnd(238);\n#else\n    std::mt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());\n#endif\n\ntemplate<typename T>\nbool smin(T& a, const T& b) {\n    if (b < a) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n\ntemplate<typename T>\nbool smax(T& a, const T& b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n\nconst double PI = atan2(0.0, -1.0);\nconst int INF = 0x3f3f3f3f;\nconst ll LINF = (ll)2e18;\nconst int N = 200100;\n\nstd::vector<int> g[N];\nint d[N], par[N];\nbool onDiameter[N];\n\nvoid dfs(int v, int p, int depth) {\n\td[v] = depth;\n\tpar[v] = p;\n\n\tfor (auto to : g[v]) {\n\t\tif (to != p) {\n\t\t\tdfs(to, v, depth + 1);\n\t\t}\n\t}\n}\n\nvoid run() {\n\tint n;\n\tscanf(\"%d\", &n);\n\n\tfor (int i = 0; i < n - 1; ++i) {\n\t\tint from, to;\n\t\tscanf(\"%d%d\", &from, &to);\n\t\tg[from - 1].push_back(to - 1);\n\t\tg[to - 1].push_back(from - 1);\n\t}    \n\n\tdfs(0, 0, 0);\n\tint v1 = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (d[i] > d[v1]) {\n\t\t\tv1 = i;\n\t\t}\n\t}\n\n\tdfs(v1, v1, 0);\n\tint v2 = v1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (d[i] > d[v2]) {\n\t\t\tv2 = i;\n\t\t}\n\t}\n\n\tstd::vector<int> diameter;\n\tfor (int v = v2; v != v1; v = par[v]) {\n\t\tonDiameter[v] = true;\n\t\tdiameter.push_back(v);\n\t}\n\tonDiameter[v1] = true;\n\tdiameter.push_back(v1);\n\tstd::reverse(diameter.begin(), diameter.end());\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (onDiameter[i]) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!onDiameter[par[i]]) {\n\t\t\tprintf(\"No\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprintf(\"Yes\\n\");\n\tstd::vector<int> ans;\n\tfor (int i = 0; i < (int)diameter.size(); i += 2) {\n\t\tans.push_back(diameter[i]);\n\t\tif (i + 1 != (int)diameter.size()) {\n\t\t\tfor (auto to : g[diameter[i + 1]]) {\n\t\t\t\tif (!onDiameter[to]) {\n\t\t\t\t\tans.push_back(to);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (diameter.size() % 2 == 0) {\n\t\tfor (int i = (int)diameter.size() - 1; i > 0; i -= 2) {\n\t\t\tans.push_back(diameter[i]);\n\t\t\tif (i - 1 >= 0) {\n\t\t\t\tfor (auto to : g[diameter[i - 1]]) {\n\t\t\t\t\tif (!onDiameter[to]) {\n\t\t\t\t\t\tans.push_back(to);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (int i = (int)diameter.size() - 1; i > 0; i -= 2) {\n\t\t\tans.push_back(diameter[i - 1]);\n\t\t\tif (i - 2 >= 0) {\n\t\t\t\tfor (auto to : g[diameter[i - 2]]) {\n\t\t\t\t\tif (!onDiameter[to]) {\n\t\t\t\t\t\tans.push_back(to);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tassert((int)ans.size() == n);\n\tfor (auto i : ans) {\n\t\tprintf(\"%d \", i + 1);\n\t}\n\tprintf(\"\\n\");\n}\n\nint main(void) {\n    // freopen(NAME\".in\", \"r\", stdin);\n    // freopen(NAME\".out\", \"w\", stdout);\n\n    #ifdef PERVEEVM_LOCAL\n        auto start = std::chrono::high_resolution_clock::now();\n    #endif\n\n    run();\n\n    #ifdef PERVEEVM_LOCAL\n        auto end = std::chrono::high_resolution_clock::now();\n        std::cerr << \"Execution time: \"\n                  << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()\n                  << \" ms\" << std::endl;\n    #endif\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1819",
    "index": "D",
    "title": "Misha and Apples",
    "statement": "Schoolboy Misha got tired of doing sports programming, so he decided to quit everything and go to the magical forest to sell magic apples.\n\nHis friend Danya came to the magical forest to visit Misha. What was his surprise when he found out that Misha found a lot of friends there, the same former sports programmers. And all of them, like Misha, have their own shop where they sell magic apples. To support his friends, who have changed their lives so drastically, he decided to buy up their entire assortment.\n\nThe buying process works as follows: in total there are $n$ stalls, numbered with integers from $1$ to $n$, and $m$ kinds of magic apples, numbered with integers from $1$ to $m$. Each shop sells some number of kinds of apples. Danya visits all the shops in order of increasing number, starting with the first one. Upon entering the shop he buys one magic apple of each kind sold in that shop and puts them in his backpack.\n\nHowever, magical apples wouldn't be magical if they were all right. The point is that when two apples of the same type end up together in the backpack, all of the apples in it magically disappear. Importantly, the disappearance happens after Danya has put the apples in the backpack and left the shop.\n\nUpon returning home, Danya realized that somewhere in the forest he had managed to lose his backpack. Unfortunately, for some shops Danya had forgotten what assortment of apples there was. Remembering only for some shops, what kinds of magical apples were sold in them, he wants to know what is the maximum number of apples he could have in his backpack after all his purchases at best.",
    "tutorial": "In this problem, we need to choose which types of apples will be sold in stores with $k_i = 0$. Let's fix some arrangement of apples and consider the last moment in it when the apples disappeared from the backpack. All the apples that we took after this moment will go into the final answer, and if there was also a store with $k_i = 0$ among these stores, then the answer is equal to $m$. Depending on the arrangement of apples, the moments of the last zeroing may change, so let's find all such moments of time after which disappearance may occur, and for all such moments, let's check if we can reach the end without zeroing, and if we can, then what is the maximum number of apples we can collect after that. Formally, let's calculate $\\mathrm{canZero}_i$ for all $0 \\leq i \\leq n$, equal to 1 if there is such an arrangement of apples that after purchases in stores on the segment $[1, i]$, the backpack will be empty, and 0 otherwise, with $\\mathrm{canZero}_0 = 1$. Also, let's calculate $\\mathrm{maxRemain}_i$ for all $0 \\leq i \\leq n$, equal to 0 if after passing on the segment $[i + 1, n]$ with an initially empty backpack, we are guaranteed to empty the backpack at least once, otherwise equal to $m$ if there is a store with $k_i = 0$ on this segment, otherwise equal to the total number of apples on this segment, with $\\mathrm{maxRemain}_n = 0$. The second array is easily calculated by definition. Let's consider one of the ways to build the first array. We will build it from left to right. If $k_i = 0$, then we can guarantee that the backpack will be empty after this store, so the value of $\\mathrm{canZero}_i$ for such $i$ is 1. Otherwise, consider all the apples in this store. After the $i$-th store, the apples will disappear if one of these apples was already in the backpack before. Let's find the maximum such $j < i$ that the store $j$ contains one of the apples in the store $i$, or $k_j = 0$. Now let's find the maximum such $s < j$ that $\\mathrm{canZero}_s = 1$. Then we check that there will be no disappearances on the segment $[s + 1, i - 1]$. In this case, $\\mathrm{canZero}_i = 1$, otherwise it is equal to 0. Then the answer will be $\\max\\limits_{\\mathrm{canZero}_i = 1} \\mathrm{maxRemain}_i$. Time complexity: $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#include <exception>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> apples(n);\n    for (int i = 0; i < n; ++i) {\n        int k;\n        cin >> k;\n        for (int j = 0; j < k; ++j) {\n            int x;\n            cin >> x;\n            apples[i].push_back(x);\n        }\n    }\n    // vector<int> last(m + 1, -1);\n    unordered_map<int, int> last;\n    auto get_last = [&](int i) {\n        if (!last.count(i)) {\n            return -1;\n        } else {\n            return last[i];\n        }\n    };\n    vector<char> can_zero(n + 1, false);\n    vector<int> prev(n + 1, 0);\n    can_zero[0] = true;\n    int oops = -1;\n    for (int i = 0; i < n; ++i) {\n        if (apples[i].empty()) {\n            can_zero[i + 1] = true;\n            last[0] = i;\n        } else {\n            int nearest_pair = get_last(0);\n            int new_oops = oops;\n            for (int x : apples[i]) {\n                nearest_pair = max(nearest_pair, get_last(x));\n                new_oops = max(new_oops, get_last(x));\n                last[x] = i;\n            }\n            if (nearest_pair != -1) {\n                int nearest_zero = prev[nearest_pair];\n                if (oops < nearest_zero) {\n                    can_zero[i + 1] = true;\n                }\n            }\n            oops = new_oops;\n        }\n        if (can_zero[i + 1]) {\n            prev[i + 1] = i + 1;\n        } else {\n            prev[i + 1] = prev[i];\n        }\n    }\n    // vector<char> used(m + 1, false);\n    unordered_set<int> used;\n    vector<int> max_cnt(n + 1, 0);\n    int current_cnt = 0;\n    for (int i = n - 1; i >= 0; --i) {\n        bool fail = false;\n        if (apples[i].empty()) {\n            used.insert(0);\n        }\n        for (int x : apples[i]) {\n            if (used.count(x)) {\n                fail = true;\n                break;\n            }\n            used.insert(x);\n            ++current_cnt;\n        }\n        if (fail) {\n            break;\n        }\n        if (used.count(0)) {\n            max_cnt[i] = m;\n        } else {\n            max_cnt[i] = current_cnt;\n        }\n    }\n    int ans = 0;\n    for (int i = 0; i <= n; ++i) {\n        if (can_zero[i]) {\n            ans = max(ans, max_cnt[i]);\n        }\n    }\n    cout << ans << '\\n';\n}\n\nint main() {\n    cin.tie(nullptr)->sync_with_stdio(false);\n    int t = 1;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1819",
    "index": "E",
    "title": "Roads in E City",
    "statement": "This is an interactive problem.\n\nAs is well known, the city \"E\" has never had its roads repaired in its a thousand and a half years old history. And only recently the city administration repaired some of them.\n\nIt is known that in total in the city \"E\" there are $n$ intersections and $m$ roads, which can be used in both directions, numbered with integers from $1$ to $m$. The $i$-th road connects intersections with numbers $a_i$ and $b_i$.\n\nAmong all $m$ roads, some subset of the roads has been repaired, but you do not know which one. The only information you could get from the city's road services is that you can get from any intersection to any other intersection by driving only on the roads that have been repaired.\n\nYou are a young entrepreneur, and decided to organize a delivery service of fresh raw meat in the city \"E\" (in this city such meat is called \"steaks\", it is very popular among the locals). You have already recruited a staff of couriers, but the couriers are willing to travel only on repaired roads. Now you have to find out which roads have already been repaired.\n\nThe city administration has given you the city for a period of time, so you can make different queries of one of three types:\n\n- Block the road with the number $x$. In this case, movement on the road for couriers will be forbidden. \\textbf{Initially all roads are unblocked}.\n- Unblock the road with the number $x$. In this case, couriers will be able to move on the road $x$ if it is repaired.\n- Try to deliver the order to the intersection with the number $y$. In this case, one of your couriers will start moving from intersection with number $s$ you don't know and deliver the order to intersection with number $y$ if there is a path on unblocked repaired roads from intersection $s$ to intersection $y$. It is guaranteed that intersection $s$ \\textbf{will be chosen beforehand}.\n\nUnfortunately, the city is placed at your complete disposal for a short period of time, so you can make no more than $100 \\cdot m$ requests.",
    "tutorial": "Let's consider city as a graph. We will call an edge good if the road is repaired, and bad if the road is not repaired. Since we know that we can reach any vertex from any other vertex using good edges, we will find the minimum spanning tree of the graph built on good edges. To do this, we will iterate through the edges one by one and check if the graph remains connected by good edges after removing that edge. If the graph remains connected, we will remove the edge. After this actions, only the good edges that form the minimum spanning tree of the graph will remain. Let's find out how to check if the graph remains connected after removing an edge. Suppose we are trying to remove an edge between vertices $A$ and $B$. If the graph remains connected after removing this edge, then the answer to any query will be $1$. Otherwise, the graph will be divided into 2 connected components. Let the starting vertex for the next query be $S$. This vertex will be in one of the two connected components. If we choose a random vertex from $A$ and $B$ as the finishing vertex, there will be no path between the starting and finishing vertices using good edges with probability $1/2$. Therefore, if we make $45$ such queries, then with probability $1/2^{45}$, start and finish will be in same components for all queries. In the remaining cases, there will be no path at least in one query, which will indicate that the graph will no longer be connected by good edges after removing the edge. This way, we can obtain the minimum spanning tree in $m \\cdot 47$ queries. After obtaining the minimum spanning tree, we will check if all other edges are good. Let's check the edge between vertices $C$ and $D$. We can find a path between vertices $C$ and $D$ in the minimum spanning tree, remove any edge from it, and then vertices $C$ and $D$ will be in different connected components. After that, we will add the edge $CD$, and using an algorithm similar to the previous one, we will check if the graph is connected by good edges. To do this, we will ask about a random vertex $C$ or $D$ 45 times. This way, we can find all other good edges in $m \\cdot 49$ queries.",
    "code": "#include <bits/stdc++.h>\n\n#define x first\n#define y second\n\nusing namespace std;\n\nmt19937 rnd;\n\nstruct solve {\n\nvector<pair<int, int>> r;\n\nvector<vector<pair<int, int>>> s;\n\nvector<int> ans;\n\nint n, m;\n\nstatic constexpr int rep = 45;\n\nint dfs(int a, int p, int b) {\n\tfor (auto i : s[a]) {\n\t\tif (i.x == b) {\n\t\t\treturn i.y;\n\t\t}\n\t\tif (i.x == p) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tint x = dfs(i.x, a, b);\n\n\t\tif (x != -1) {\n\t\t\treturn x;\n\t\t}\n\t}\n\treturn -1;\n}\n\nsolve() {\n\tcin >> n >> m;\n\tr.resize(m);\n\tfor (int i = 0; i < m; i++) {\n\t\tcin >> r[i].x >> r[i].y;\n\t\tr[i].x--;\n\t\tr[i].y--;\n\t}\n\n\ts.resize(n);\n\tans.resize(m, -1);\n\tint cnt = 0;\n\tfor (int i = 0; i < m; i++) {\n\t\trem(i);\n\t\tfor (int j = 0; j < rep; j++) {\n\t\t\tif (!ask_end(i)) {\n\t\t\t\tans[i] = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (ans[i] == 1) {\n\t\t\tadd(i);\n\t\t\tcnt++;\n\t\t\ts[r[i].x].emplace_back(r[i].y, i);\n\t\t\ts[r[i].y].emplace_back(r[i].x, i);\n\t\t}\n\t}\n\n\tassert(cnt == n - 1);\n\n\tfor (int i = 0; i < m; i++) {\n\t\tif (ans[i] != -1) continue;\n\t\tans[i] = 1;\n\n\t\tint c = dfs(r[i].x, -1, r[i].y);\n\t\trem(c);\n\t\tadd(i);\n\t\tfor (int j = 0; j < rep; j++) {\n\t\t\tif (!ask_end(i)) {\n\t\t\t\tans[i] = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\trem(i);\n\t\tadd(c);\n\t}\n\tcout << \"!\";\n\tfor (int i = 0; i < m; i++) {\n\t\tcout << ' ' << ans[i];\n\t}\n\tcout << endl;\n\tint x;\n\tcin >> x;\n\tif (x != 1) {\n\t\texit(1);\n\t}\n}\n\nvoid rem(int x) {\n\tcout << \"- \" << x + 1 << endl;\n}\n\nvoid add(int x) {\n\tcout << \"+ \" << x + 1 << endl;\n}\n\nbool ask(int a) {\n\tcout << \"? \" << a + 1 << endl;\n\t// cerr << \"? \" << a + 1 << endl;\n\tint x;\n\tcin >> x;\n\treturn x == 1;\n}\n\nbool ask_end(int i) {\n\t// cerr << \"ask_end \" << i << endl;\n\tint a = r[i].x;\n\tif (rnd() % 2) {\n\t\ta = r[i].y;\n\t}\n\treturn ask(a);\n}\n\n};\n\nint main() {\n\tint t;\n\tcin >> t;\n\tfor (int i = 0; i < t; i++) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "interactive",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1819",
    "index": "F",
    "title": "Willy-nilly, Crack, Into Release!",
    "statement": "You have long dreamed of working in a large IT company and finally got a job there. You have studied all existing modern technologies for a long time and are ready to apply all your knowledge in practice. But then you sit down at your desk and see a sheet of paper with the company's motto printed in large letters: abcdabcdabcdabcd....\n\nThe company's motto contains four main principles— a (Willi), b (Nilli), c (Crack), d (Release). Therefore, you consider strings of length $n$ consisting of these four Latin letters. \\textbf{Unordered} pairs of letters \"ab\", \"bc\", \"cd\", and \"da\" in this motto are adjacent, so we will call such pairs of symbols good. So, if you are given a string $s$ of length $n$, and it is known that the unordered pair of symbols $\\{ x, y \\}$ is good, then you can perform one of the following operations on the string:\n\n- if $s_n = x$, then you are allowed to replace this symbol with $y$,\n- if there exists $1 \\le i < n$ such that $s_i = x$ and $s_{i+1} = \\ldots = s_n = y$, then you are allowed to replace the $i$-th symbol of the string with $y$, and all subsequent symbols with $x$.\n\nFor example, the string bacdd can be replaced with one of the strings bacda, bacdc, or badcc, and the string aac can be replaced with aab or aad.\n\nA non-empty sequence of operations for the string $s$ will be called correct if the following two conditions are met:\n\n- after performing all operations, the string becomes $s$ again,\n- no string, except for $s$, will occur more than once during the operations. At the same time, the string $s$ can occur exactly twice - before the start of the operations and after performing all operations.\n\nNow we are ready to move on to the problem statement! You have a set of strings that is initially empty. Then, each of $q$ queries adds another string $t_i$ to the set, or removes the string $t_i$ from the set. After each query, you need to output the minimum and maximum size of a correct sequence of operations in which each word occurs at least once. The choice of the initial string $s$ is up to you.",
    "tutorial": "There are two ways to approach this problem. Let's start with a solution that does not involve associations with known images. Consider a cyclic sequence of strings that satisfies the condition of the problem. Consider the longest common prefix of all the strings in this sequence. It is not very interesting to us, since by definition it does not change with the operations. There are two cases. Either the sequence of operations has a length of $2$, when we perform some action and then immediately \"cancel\" it with a second action. This case is only possible if there are no more than two important strings in the set. In this case, the required condition can be easily checked in $\\mathcal{O}(n)$ time. Otherwise, our sequence consists of more than two operations and this is much more like a cycle. Let's say, for example, that the first non-constant character in the sequence of strings initially equals \"a\". Then after the first change it will be equal to either \"b\" or \"d\". Note that after this the first character will no longer be able to immediately turn into \"a\", since the only way to do this is to \"cancel\" the operation $\\ldots acccc\\ldots c \\to \\ldots caaaa\\ldots a$, but this is only possible in the first case. Thus, the first character will be required to go \"around the cycle\" $abcda$. This cycle can be divided into four segments based on the value of the first character of the string. In each of these segments, we are interested in the sequence of operations that transforms the string with the suffix $zx\\ldots x$ into a string that matches the original in the prefix, but its suffix is $zy \\ldots y$, where $x \\neq y \\neq z \\neq x$ and the pair of characters $\\{ x,y \\}$ is \"good\". With the help of a not very complicated analysis of cases, we can see that for each prefix we are interested in $6$ groups of paths that connect strings whose characters, except for the suffix being considered, match, and these paths visit all important strings with the prefix being considered. Within each group of paths, we are interested in the minimum and maximum path, respectively. Note that these values can be easily calculated using dynamic programming. We can calculate all these states in $\\mathcal{O}(4^n)$ time. Then we need to iterate over the length of the common prefix of all the strings and answer the query in $\\mathcal{O}(n)$ time. So far, we can only calculate the states of interest to us in some galactic time. But this is not entirely scary! Let's say, for example, that when we add or remove one string from the set of important strings, only $\\mathcal{O}(n)$ states change, since only the states responsible for the prefixes of the added/deleted string $s$ will change. To some extent, this is reminiscent of a segment tree, or rather, a quadtree. We just need to figure out how to get rid of the $\\mathcal{O}(4^n)$ term in the asymptotic complexity. But this is also simple. Let's notice that if there are no strings with the given prefix in the set of important strings, then the states responsible for this prefix will depend only on the length of the remaining suffix, and all these values can be precomputed in $O(n)$ time. Thus, we store a trie with strings from the queries, in each node of which we store the state of the dynamic programming, and in case we need the values of the dynamic programming from non-existent trie nodes during recalculation, we can replace them with precomputed values. Time complexity: $\\mathcal{O}(nq)$. The author's code is not very complicated, but if you suddenly want to understand it, I warn you that it uses several \"hacks\" of questionable justification. For example, instead of $6$ dynamic programming states, only $3$ really useful ones are stored there. The combinatorial structure MinMaxValue is used to simplify the support of simultaneous maximum and minimum values, and much more. I think that it will be especially useful for beginners to familiarize themselves with how to simplify their lives in implementing combinatorial problems. Now let's turn to the geometric interpretation of the problem. Imagine a square with a size of $(2^n-1) \\times (2^n-1)$. In its corners, we can draw squares with sizes of $(2^{n-1}-1 \\times 2^{n-1}-1)$ each. Let's say that strings starting with the character $a$ go to the upper-left square, strings starting with the character $b$ go to the upper-right, the character $c$ corresponds to the lower-right corner, and the character $d$ corresponds to the lower-left. Then we can divide the four resulting squares into four parts each in the same way and divide the strings by corners already by the second character, and so on. In the end, each string is associated with an integer point with coordinates from the interval $[0, 2^n-1]$. We also have lines from the drawn squares, which are naturally divided into vertical and horizontal segments of length $1$ each. This picture is useful because it depicts a graph whose vertices correspond to the strings being considered, and its edges connect pairs of strings that are obtained from each other by means of one move. Thus, looking at the picture, much of the structure of simple cycles in the problem being considered becomes clear and obvious, and with the help of such a picture it is much easier to describe the transitions in the dynamic programming and not get confused.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing pi = pair<int, int>;\nusing ll = long long;\n\nconst int Q = 1e5;\nconst int N = 20;\nconst int V = N*Q;\n\nconst ll LINF = 1e18;\n\nstruct MinMaxValue {\n    ll min_value;\n    ll max_value;\n\n    MinMaxValue operator * (const MinMaxValue& x) const {\n        if (x.max_value < 0 || max_value < 0) {\n            return MinMaxValue { 0, -1 };\n        }\n\n        return MinMaxValue {\n            .min_value = x.min_value + min_value,\n            .max_value = x.max_value + max_value\n        };\n    }\n\n    MinMaxValue operator + (const MinMaxValue& x) const {\n        if (x.max_value == -1) return *this;\n        if (max_value == -1) return x;\n\n        return MinMaxValue {\n            .min_value = min(x.min_value, min_value),\n            .max_value = max(x.max_value, max_value)\n        };\n    }\n\n    MinMaxValue& operator += (const MinMaxValue& x) {\n        return *this = *this + x;\n    }\n\n    void Reset() {\n        min_value = 0;\n        max_value = -1;\n    }\n};\n\nstruct {\n    MinMaxValue dig, ver, hor;\n    int cnt;\n    int go[4];\n} nd[V];\nint vc = 0;\nMinMaxValue dig[N+1], ver[N+1], hor[N+1];\n\nstd::set<ll> words;\n\nint NewVertex(int h) {\n    int* go = nd[vc].go;\n    go[0] = go[1] = go[2] = go[3] = -1;\n    nd[vc].dig = dig[h];\n    nd[vc].hor = hor[h];\n    nd[vc].ver = ver[h];\n    nd[vc].cnt = 0;\n    return vc++;\n}\n\ntuple<const MinMaxValue&, const MinMaxValue&, const MinMaxValue&, int> GetState(int v, int h) {\n    return v == -1 ? make_tuple(cref(dig[h]), cref(ver[h]), cref(hor[h]), 0)\n                   : make_tuple(cref(nd[v].dig), cref(nd[v].ver), cref(nd[v].hor), nd[v].cnt);\n}\n\nvoid Calculate(int v, int h, int corner) {\n    auto [dig0, ver0, hor0, cnt0] = GetState(nd[v].go[corner^0], h-1);\n    auto [dig1, ver1, hor1, cnt1] = GetState(nd[v].go[corner^1], h-1);\n    auto [dig2, ver2, hor2, cnt2] = GetState(nd[v].go[corner^2], h-1);\n    auto [dig3, ver3, hor3, cnt3] = GetState(nd[v].go[corner^3], h-1);\n\n    nd[v].cnt = cnt0 + cnt1 + cnt2 + cnt3;\n\n    nd[v].dig.Reset();\n    if (cnt0 == 0) nd[v].dig += hor2 * dig3 * ver1;\n    if (cnt3 == 0) nd[v].dig += ver2 * dig0 * hor1;\n\n    nd[v].hor = ver0 * dig2 * dig3 * ver1;\n    if (cnt2 + cnt3 == 0) nd[v].hor += hor0 * hor1;\n\n    nd[v].ver = hor0 * dig1 * dig3 * hor2;\n    if (cnt1 + cnt3 == 0) nd[v].ver += ver0 * ver2;\n}\n\nvoid UpdateCount(int v, int h, int corner, ll msk, ll msk_save) {\n    if (h == 0) {\n        if (nd[v].cnt == 0) {\n            words.insert(msk_save);\n        } else {\n            words.erase(msk_save);\n        }\n        nd[v].cnt ^= 1;\n    } else {\n        UpdateCount(nd[v].go[msk & 3], h-1, msk & 3, msk >> 2, msk_save);\n        Calculate(v, h, corner);\n    }\n}\n\nbool near_symbols[256][256];\n\nMinMaxValue GetAnswer(int h) {\n    int v = 0;\n\n    if (nd[v].cnt == 0) {\n        return MinMaxValue { .min_value = 2, .max_value = 4 * dig[h-1].max_value };\n    }\n\n    MinMaxValue res; res.Reset();\n\n    bool cycle_len2 = false;\n    if (nd[v].cnt <= 1) cycle_len2 = true;\n    if (nd[v].cnt == 2) {\n        string s, t;\n\n        for (ll msk =       *words.begin(); s.size() < h; msk >>= 2) s.push_back(\"abdc\"[msk & 3]);\n        for (ll msk = *next(words.begin()); t.size() < h; msk >>= 2) t.push_back(\"abdc\"[msk & 3]);\n        auto flag = near_symbols[s.back()][t.back()];\n\n        if (s.substr(0, h-1) == t.substr(0, h-1) && flag) {\n            cycle_len2 = true;\n        }\n\n        int s_suf = 0, t_suf = 0;\n        while (s_suf < h && s[h - s_suf - 1] == s.back()) ++s_suf;\n        while (t_suf < h && t[h - t_suf - 1] == t.back()) ++t_suf;\n\n        if (s_suf == t_suf && s_suf < h && flag && s.substr(0, h-s_suf-1) == t.substr(0, h-t_suf-1)\n                && s.back() == t[h - s_suf - 1]\n                && t.back() == s[h - t_suf - 1]) cycle_len2 = true;\n    }\n\n    if (cycle_len2) {\n        res.min_value = 2;\n        res.max_value = 2;\n    }\n\n    while (h != 0) {\n        const int v0 = nd[v].go[0], v1 = nd[v].go[1], v2 = nd[v].go[2], v3 = nd[v].go[3];\n        const auto& dig0 = get<0>(GetState(v0, h-1));\n        const auto& dig1 = get<0>(GetState(v1, h-1));\n        const auto& dig2 = get<0>(GetState(v2, h-1));\n        const auto& dig3 = get<0>(GetState(v3, h-1));\n\n        if(dig0.max_value > 0 && dig1.max_value > 0 && dig2.max_value > 0 && dig3.max_value > 0) {\n            res += dig0 * dig1 * dig2 * dig3;\n        }\n\n        --h;\n        if (v0 != -1 && nd[v0].cnt == nd[v].cnt) { v = v0; continue; }\n        if (v1 != -1 && nd[v1].cnt == nd[v].cnt) { v = v1; continue; }\n        if (v2 != -1 && nd[v2].cnt == nd[v].cnt) { v = v2; continue; }\n        if (v3 != -1 && nd[v3].cnt == nd[v].cnt) { v = v3; continue; }\n        break;\n    }\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n\n    int n, q; cin >> n >> q;\n    vector<ll> v(q);\n\n    for (int i = 0; i < 4; ++i) {\n        int j = (i + 1) % 4;\n        near_symbols['a' + i]['a' + j] = true;\n        near_symbols['a' + j]['a' + i] = true;\n    }\n\n    dig[0] = ver[0] = hor[0] = { 1, 1 };\n    for (int i = 1; i <= n; ++i) {\n        dig[i] = hor[i-1] * dig[i-1] * ver[i-1];\n        hor[i] = ver[i] = hor[i-1] * hor[i-1] + ver[i-1] * ver[i-1] * dig[i-1] * dig[i-1];\n    }\n\n    int m_root = NewVertex(n); // make_root\n    assert(m_root == 0);\n\n    for (int i = 0; i < q; ++i) {\n        string s; cin >> s;\n        for (int j = 0; j < n; ++j) {\n            v[i] += (s[j] == 'b' || s[j] == 'c' ? 1ll : 0) << (2*j);\n            v[i] += (s[j] == 'c' || s[j] == 'd' ? 2ll : 0) << (2*j);\n        }\n\n        int w = 0;\n        for (int j = 0; j < n; ++j) {\n            int& next = nd[w].go[(v[i] >> (2*j)) & 3];\n            if (next == -1) next = NewVertex(n-j-1);\n            w = next;\n        }\n    }\n\n    for (ll msk : v) {\n        UpdateCount(0, n, 0, msk, msk);\n        auto [a, b] = GetAnswer(n);\n\n        if (a > b) {\n            cout << -1 << '\\n';\n        } else {\n            cout << a << \" \" << b << '\\n';\n        }\n    }\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1820",
    "index": "A",
    "title": "Yura's New Name",
    "statement": "After holding one team contest, boy Yura got very tired and wanted to change his life and move to Japan. In honor of such a change, Yura changed his name to something nice.\n\nFascinated by this idea he already thought up a name $s$ consisting only of characters \"_\" and \"^\". But there's a problem — Yura likes smiley faces \"^_^\" and \"^^\". Therefore any character of the name must be a part of at least one such smiley. Note that only the \\textbf{consecutive} characters of the name can be a smiley face.\n\nMore formally, consider all occurrences of the strings \"^_^\" and \"^^\" in the string $s$. Then all such occurrences must cover the whole string $s$, possibly with intersections. For example, in the string \"^^__^_^^__^\" the characters at positions $3,4,9,10$ and $11$ are not contained inside any smileys, and the other characters at positions $1,2,5,6,7$ and $8$ are contained inside smileys.\n\nIn one operation Jura can insert one of the characters \"_\" and \"^\" into his name $s$ (you can insert it at any position in the string). He asks you to tell him the minimum number of operations you need to do to make the name fit Yura's criteria.",
    "tutorial": "Let's see that if initial name contains \"__\" as a substring, we have to add character \"^\" between these two characters because both smiley faces start and end with character \"^\" and don't contain \"__\" as a substring. Also let's see that the resulting name have to start and end with character \"^\" and it's length have to be at least two. To calculate the answer we have to count the number of indices $i$ such that $s_i = s_{i + 1} =$ \"_\". After that we have to increment the answer if the first character of the name equals to \"_\" and increment the answer if the last character of the name equals to \"_\". Also we shouldn't forget about the case when the initials name equals to \"^\" - in this case the answer equals to one. Time complexity: $\\mathcal{O}(\\lvert s \\rvert)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        string s;\n        cin >> s;\n        if (s == \"^\") {\n            cout << 1 << '\\n';\n            continue;\n        }\n        int ans = 0;\n        if (s[0] == '_')\n            ++ans;\n        if (s.back() == '_')\n            ++ans;\n        for (int i = 0; i < (int) s.size() - 1; ++i) {\n            if (s[i] == '_' && s[i + 1] == '_')\n                ++ans;\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1820",
    "index": "B",
    "title": "JoJo's Incredible Adventures",
    "statement": "Did you think there was going to be a JoJo legend here? But no, that was me, Dio!\n\nGiven a binary string $s$ of length $n$, consisting of characters 0 and 1. Let's build a \\textbf{square} table of size $n \\times n$, consisting of 0 and 1 characters as follows.\n\nIn the first row of the table write the original string $s$. In the second row of the table write cyclic shift of the string $s$ by one to the right. In the third row of the table, write the cyclic shift of line $s$ by two to the right. And so on. Thus, the row with number $k$ will contain a cyclic shift of string $s$ by $k$ to the right. The rows \\textbf{are numbered from $0$ to $n - 1$ top-to-bottom}.\n\nIn the resulting table we need to find the rectangle consisting only of ones that has the largest area.\n\nWe call a rectangle the set of all cells $(i, j)$ in the table, such that $x_1 \\le i \\le x_2$ and $y_1 \\le j \\le y_2$ for some integers $0 \\le x_1 \\le x_2 < n$ and $0 \\le y_1 \\le y_2 < n$.\n\nRecall that the cyclic shift of string $s$ by $k$ to the right is the string $s_{n-k+1} \\ldots s_n s_1 s_2 \\ldots s_{n-k}$. For example, the cyclic shift of the string \"01011\" by $0$ to the right is the string itself \"01011\", its cyclic shift by $3$ to the right is the string \"01101\".",
    "tutorial": "First of all, consider the cases if the given string consists only of ones and only of zeros. It's easy to see that answers for these cases are $n^2$ and $0$. In all other cases let's split all strings into segments that consist only of ones. Also if the first and the last characters of the string equals to \"1\", these two characters will be in one segment. In other words, the pair of ones will lay inside one group if there exists some cyclic shift that these two ones are consecutive. Let the maximum length of such segment be equal to $k$. Then it can be shown that the answer equals to $\\lfloor \\frac{k+1}{2} \\rfloor \\cdot \\lceil \\frac{k+1}{2} \\rceil$. We will proof this fact in such way. If there exists some rectangle of size $a \\times b$. Considering its first row, we can see that it has $a+b-1$ consecutive ones. But it means that $a+b \\leq k+1$. Without loss of generality, if $a \\le b$, we can do the following replacements: $a = \\lfloor \\frac{k+1}{2} \\rfloor - \\lambda$, $b = \\lceil \\frac{k+1}{2} \\rceil + \\lambda$. It means that $ab = \\lceil \\frac{k+1}{2} \\rceil \\cdot \\lfloor \\frac{k+1}{2} \\rfloor - \\lambda^2 \\le \\lceil \\frac{k+1}{2} \\rceil \\cdot \\lfloor \\frac{k+1}{2} \\rfloor$. Time complexity: $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        string s; cin >> s; s += s;\n        int k = 0, z = 0;\n        for (char c : s) {\n            z = c == '1' ? z+1 : 0;\n            k = max(k, z);\n        }\n        const int n = s.size() / 2;\n\n        if (k > n) {\n            cout << (ll)n*n << '\\n';\n        } else {\n            const ll side_a = (k+1)/2;\n            const ll side_b = (k+2)/2;\n            cout << side_a * side_b << '\\n';\n        }\n    }\n}",
    "tags": [
      "math",
      "strings",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1821",
    "index": "A",
    "title": "Matching",
    "statement": "An integer template is a string consisting of digits and/or question marks.\n\nA positive (strictly greater than $0$) integer matches the integer template if it is possible to replace every question mark in the template with a digit in such a way that we get the decimal representation of that integer \\textbf{without any leading zeroes}.\n\nFor example:\n\n- $42$ matches 4?;\n- $1337$ matches ????;\n- $1337$ matches 1?3?;\n- $1337$ matches 1337;\n- $3$ does not match ??;\n- $8$ does not match ???8;\n- $1337$ does not match 1?7.\n\nYou are given an integer template consisting of \\textbf{at most $5$ characters}. Calculate the number of positive (strictly greater than $0$) integers that match it.",
    "tutorial": "In a positive integer, the first digit is from $1$ to $9$, and every next digit can be any. This allows us to implement the following combinatorial approach: calculate the number of different values for the first digit, which is $0$ if the first character of $s$ is 0, $1$ if the first character of $s$ is any other digit, or $9$ if the first character of $s$ is ?; calculate the number of different values for each of the other digits, which is $1$ if the corresponding character of $s$ is a digit, or $10$ if it is ?; multiply all these values.",
    "code": "\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tstring s;\n\t\tcin >> s;\n\t\tint ans = 1;\n\t\tif(s[0] == '0') ans = 0;\n\t\tif(s[0] == '?') ans = 9;\n\t\tfor(int j = 1; j < s.size(); j++)\n\t\t\tif(s[j] == '?')\n\t\t\t\tans *= 10;\n\t\tcout << ans << endl;\n\t}\n}\n",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1821",
    "index": "B",
    "title": "Sort the Subarray",
    "statement": "Monocarp had an array $a$ consisting of $n$ integers. He has decided to choose two integers $l$ and $r$ such that $1 \\le l \\le r \\le n$, and then sort the subarray $a[l..r]$ (the subarray $a[l..r]$ is the part of the array $a$ containing the elements $a_l, a_{l+1}, a_{l+2}, \\dots, a_{r-1}, a_r$) in \\textbf{non-descending order}. After sorting the subarray, Monocarp has obtained a new array, which we denote as $a'$.\n\nFor example, if $a = [6, 7, 3, 4, 4, 6, 5]$, and Monocarp has chosen $l = 2, r = 5$, then $a' = [6, 3, 4, 4, 7, 6, 5]$.\n\nYou are given the arrays $a$ and $a'$. Find the integers $l$ and $r$ that Monocarp could have chosen. If there are multiple pairs of values $(l, r)$, find the one which \\textbf{corresponds to the longest subarray}.",
    "tutorial": "Let's find the leftmost and the rightmost position in which the arrays $a$ and $a'$ differ. Since only the elements in the chosen subsegment might change, the subarray we sorted should contain these two positions. Let's start with the subarray from the leftmost \"different\" position to the rightmost one, and then expand it to get the longest subarray which meets the conditions. Suppose we want to expand it to the left. Let the current left border be $L$; how to decide if we can make it $L-1$ or less? If $a'_L < a_{L-1}$, then we cannot include $L-1$ in the subarray we sort, since otherwise the order of these two elements would have changed. Otherwise, $a_{L-1}$ is not greater than any element in the subarray we have chosen, so we can include it and reduce $L$ by $1$. We do this until it's impossible to reduce $L$ further. The same goes for the right border: we expand it to the right until we find an element which is less than the previous element, and we cannot include this element in the subarray.",
    "code": "\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tvector<int> a(n);\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tscanf(\"%d\", &a[i]);\n\t\tvector<int> a1(n);\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tscanf(\"%d\", &a1[i]);\n\t\tint diffl = -1, diffr = -1;\n\t\tfor(int j = 0; j < n; j++)\n\t\t{\n\t\t\tif(a[j] != a1[j])\n\t\t\t{\n\t\t\t\tdiffr = j;\n\t\t\t\tif(diffl == -1)\n\t\t\t\t\tdiffl = j;\n\t\t\t}\n\t\t}\n\t\twhile(diffl > 0 && a1[diffl - 1] <= a1[diffl])\n\t\t\tdiffl--;\n\t\twhile(diffr < n - 1 && a1[diffr + 1] >= a1[diffr])\n\t\t\tdiffr++;\n\t\tprintf(\"%d %d\\n\", diffl + 1, diffr + 1);\n\t}\n}\n",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1821",
    "index": "C",
    "title": "Tear It Apart",
    "statement": "You are given a string $s$, consisting of lowercase Latin letters.\n\nIn one operation, you can select several (one or more) positions in it such that no two selected positions are adjacent to each other. Then you remove the letters on the selected positions from the string. The resulting parts are concatenated without changing their order.\n\nWhat is the smallest number of operations required to make all the letters in $s$ the same?",
    "tutorial": "The resulting string looks like a single letter repeated a number of times. That sounds too vague. Let's fix the exact letter $c$ that will be left. Since the size of the alphabet is only $26$, we can afford that. The letters now separate into letters $c$ and other letters. And all other letters can be treated as indistinguishable from each other. Let's make letter $c$ into a binary $1$ and any other letter into a binary $0$. Our goal is to remove all zeros from the string with the given operations. First, notice that it doesn't help you to removes ones. If some operation contains both ones and zeros, then taking ones out of it doesn't make any zeros in it adjacent. At the same time, these ones can only help you separate adjacent zeros later. Thus, we have some blocks of zeros, separated by the blocks of ones. We want to remove only zeros. Notice how these blocks can be solved completely independently of each other. If you solve block $1$ in $\\mathit{cnt}_1$ operations, block $2$ in $\\mathit{cnt}_2$ operations, ..., block $k$ in $\\mathit{cnt}_k$ operations, then you can solve the entire string in $\\max(\\mathit{cnt}_1, \\mathit{cnt}_2, \\dots, \\mathit{cnt}_k)$ operations. Since the blocks are separated by the blocks of ones, you can combine the first operations for all blocks into one big operation and so on. The only thing left is to calculate the number of operations for a single block. Let it have length $l$. Basically, in one operation, you can decrease its length to $\\lfloor \\frac l 2 \\rfloor$. You can see that the longer the block, the greater answer it has. So you can find the longest block first, then calculate the answer for it. You can either use this iterative formula or notice that it's a logarithm of $l$ in base $2$ and calculate that however you want. To find the lengths of the blocks of zeros, you can use two pointers. Overall complexity: $O(|\\mathit{AL}| \\cdot n)$ per testcase. This problem can also be solved in $O(n \\log n)$ on an arbitrarily large alphabet. Basically, when you fix a letter, you can tell the lengths of the blocks of other letters by looking at the occurrences of the letter. For occurrences $i_1, i_2, \\dots, i_k$, the lengths of the blocks are $i_1 - 1, i_2 - i_1, \\dots, i_k - i_{k-1}, n - i_{k}$. So we can calculate the answer for a letter in $O(\\mathit{number\\ of\\ its\\ occurrences})$. The total of that for all letters is $O(n)$.",
    "code": "\nfor _ in range(int(input())):\n\ts = input()\n\tn = len(s)\n\tans = n\n\tfor x in range(26):\n\t\tc = chr(x + ord('a'))\n\t\ti = 0\n\t\tcur = 0\n\t\twhile i < n:\n\t\t\tj = i\n\t\t\twhile j < n and (s[j] == c) == (s[i] == c):\n\t\t\t\tj += 1\n\t\t\tif s[i] != c:\n\t\t\t\tcur = max(cur, j - i)\n\t\t\ti = j\n\t\tif cur == 0:\n\t\t\tans = 0\n\t\t\tbreak\n\t\tpw = 0\n\t\twhile (1 << pw) <= cur:\n\t\t\tpw += 1\n\t\tans = min(ans, pw)\n\tprint(ans)\n",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1821",
    "index": "D",
    "title": "Black Cells",
    "statement": "You are playing with a really long strip consisting of $10^{18}$ white cells, numbered from left to right as $0$, $1$, $2$ and so on. You are controlling a special pointer that is initially in cell $0$. Also, you have a \"Shift\" button you can press and hold.\n\nIn one move, you can do one of three actions:\n\n- move the pointer to the right (from cell $x$ to cell $x + 1$);\n- press and hold the \"Shift\" button;\n- release the \"Shift\" button: the moment you release \"Shift\", all cells that were visited while \"Shift\" was pressed are colored in black.\n\n(Of course, you can't press Shift if you already hold it. Similarly, you can't release Shift if you haven't pressed it.)Your goal is to color at least $k$ cells, but there is a restriction: you are given $n$ segments $[l_i, r_i]$ — you can color cells only inside these segments, i. e. you can color the cell $x$ if and only if $l_i \\le x \\le r_i$ for some $i$.\n\nWhat is the minimum number of moves you need to make in order to color at least $k$ cells black?",
    "tutorial": "Let's look at what's happening in the task: in the end the pointer will move into some position $p$ and some segments on the prefix $[0, p]$ will be colored. Note that it's optimal to stop only inside some segment (or $l_i \\le p \\le r_i$ for some $i$), and if we colored $x$ segments (including the last segment $[l_i, p]$ that may be colored partially) the answer will be equal to $p + 2 \\cdot x$. Let's prove that it's not optimal to skip segments with length $len = r[i] - l[i] + 1 \\ge 2$. By contradiction, suppose the optimal answer $a$ has a skipped segment $[l_i, r_i]$. If we color that segment instead, we will make $2$ more moves for pressing and releasing Shift, but we can make at least $len$ right move less. So the new answer $a' = a + 2 - len \\le a$ - the contradiction. Now we are ready to write a solution. Let's iterate over $i$ - the last segment we will color (and therefore the segment where we stop). At first, let's imagine we colored the whole segment $[l_i, r_i]$ as well. Let $s$ be the total length of all segments on prefix $[0, r_i]$ that are longer than $1$ and $c$ be the number of segments of length $1$ on this prefix. There are three cases: if $s + c < k$, stopping inside the $i$-th segment is not enough; if $s < k$ but $s + c \\ge k$, we will color all \"long\" segments plus several short ones. The current answer will be equal to $r_i + 2 ((i - c) + (k - s))$, where $r_i$ is where we stop, $(i - c)$ is the number of long segments and $(k - s)$ is the number of short segments we need; if $s \\ge k$, then we don't need any short segments. More over, we can stop even before reaching $r_i$. So, the current answer will be equal to $r_i - (s - k) + 2 (i - c)$, where $r_i - (s - k)$ is the exact position to stop to get exactly $k$ black cells and $(i - c)$ is the number of long segments. The answer is the minimum among the answers we've got in the process. Since it's easy to update values $s$ and $c$ when we move from $i$ to $i + 1$, the total complexity is $O(n)$.",
    "code": "\nfun main() {\n    repeat(readln().toInt()) {\n        val (n, k) = readln().split(' ').map { it.toInt() }\n        val l = readln().split(' ').map { it.toInt() }\n        val r = readln().split(' ').map { it.toInt() }\n\n        var ans = 2e9.toInt()\n        var cntShort = 0\n        var lenLong = 0\n        for (i in 0 until n) {\n            val curLen = r[i] - l[i] + 1\n            if(curLen > 1)\n                lenLong += curLen\n            else\n                cntShort++\n\n            if (lenLong < k) {\n                if (lenLong + cntShort >= k) {\n                    val cntSegs = (i + 1 - cntShort) + (k - lenLong)\n                    ans = minOf(ans, r[i] + 2 * cntSegs)\n                }\n            }\n            else {\n                ans = minOf(ans, r[i] - (lenLong - k) + 2 * (i + 1 - cntShort))\n                break\n            }\n        }\n        if (ans == 2e9.toInt())\n            ans = -1\n        println(ans)\n    }\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1821",
    "index": "E",
    "title": "Rearrange Brackets",
    "statement": "A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example:\n\n- bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\");\n- bracket sequences \")(\", \"(\" and \")\" are not.\n\nYou are given a regular bracket sequence. In one move, you can remove a pair of \\textbf{adjacent} brackets such that the left one is an opening bracket and the right one is a closing bracket. Then concatenate the resulting parts without changing the order. The cost of this move is the number of brackets to the right of the right bracket of this pair.\n\nThe cost of the regular bracket sequence is the smallest total cost of the moves required to make the sequence empty.\n\nActually, you are not removing any brackets. Instead, you are given a regular bracket sequence and an integer $k$. You can perform the following operation \\textbf{at most $k$ times}:\n\n- extract some bracket from the sequence and insert it back at any position (between any two brackets, at the start or at the end; possibly, at the same place it was before).\n\nAfter all operations are performed, the bracket sequence has to be regular. What is the smallest possible cost of the resulting regular bracket sequence?",
    "tutorial": "First, let's define the cost of an RBS a bit clearer. The absolute smallest cost of removing each pair of brackets is the number of bracket pairs it's inside of. That can actually be achieved - just remove the pairs right to left (according to the positions of the opening brackets in pairs). So you can instead say that the total cost is the sum of balance values after all closing brackets. Or before all opening brackets - these are actually the same. From that, we can code a classic dp. Imagine we are not moving brackets, but instead doing that in two separate movements: put a bracket in some buffer and place it in the string. We'd love to use $\\mathit{dp}[\\mathit{pos}][\\mathit{open}][\\mathit{close}][\\mathit{moves}]$ - the smallest answer if we processed $\\mathit{pos}$ brackets, $\\mathit{open}$ opening brackets are in the buffer, $\\mathit{close}$ closing brackets in the buffer and $\\mathit{moves}$ are performed. Sadly, that doesn't really allow moving brackets to the left, since you would have to first place the bracket, then put in it the buffer. Does that actually break anything? Apparently, no. You can make these buffer states from $-k$ to $k$, and think of negative values as taking a loan. These states are enough to determine the current balance of the string. Thus, enough to both update the states and check if the string stops being an RBS after placing a closing bracket. Overall complexity: $O(nk^3)$. We can do it faster, but our proof isn't that convincing. Start by showing that there exists an optimal answer such that each move leaves the sequence an RBS. Consider a sequence of moves that ends up being an RBS. First, you can basically rearrange the moves (maybe adjusting the exact positions is required). Second, there exists a move that, performed first, leaves an RBS. Make it and propagate the proof. You can show that such a move exists by studying some cases. Then I found it more intuitive to switch to another representation - you can look at the forest induced by the bracket sequence. The roots of the trees in it are the topmost opening and closing brackets of the RBS. Their children are the inner topmost brackets for each of them, and so on. With that representation, the answer is actually the sum of depths of all vertices. Now for the moves. Let's move an opening bracket to the right. We won't move it after its corresponding closing bracket to not break an RBS. How will it change the tree? It will turn some children of the corresponding vertex into the children of its parent. Thus, it will decrease their depths by one, and the depths of their descendants as well. How about to the left? That will turn some children of its parent into its own children, increasing their depths (and the depths of their descendants) by one. Similar analysis can be performed for the closing brackets. The claim is that, in the optimal answer, you should only move opening brackets and only to the right. Then they decrease the answer independently of each other. It's pretty clear that the best position to move each bracket to is as much to the right as possible - place it next to its respective closing bracket. That will decrease the answer by the size of the subtree (excluding the vertex itself). Finally, we want to choose $k$ vertices that have the largest sum of their subtrees. That can be just done greedily - pick $k$ largest ones. You don't have to build the tree explicitly for that - the size of the subtree is half of the number of brackets between an opening bracket and a corresponding closing one. So, everything can be processed with a stack. Overall complexity: $O(n)$ or $O(n \\log n)$.",
    "code": "\nfor _ in range(int(input())):\n\tk = int(input())\n\ts = input()\n\tn = len(s)\n\tst = []\n\tcnt = [0 for i in range(n + 1)]\n\tans = 0\n\tfor i in range(n):\n\t\tif s[i] == '(':\n\t\t\tans += len(st)\n\t\t\tst.append(i)\n\t\telse:\n\t\t\tcnt[(i - st.pop()) // 2] += 1\n\tfor i in range(n, -1, -1):\n\t\tt = min(k, cnt[i])\n\t\tans -= t * i\n\t\tk -= t\n\tprint(ans)\n",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1821",
    "index": "F",
    "title": "Timber",
    "statement": "There is a beautiful alley with trees in front of a shopping mall. Unfortunately, it has to go to make space for the parking lot.\n\nThe trees on the alley all grow in a single line. There are $n$ spots for trees, index $0$ is the shopping mall, index $n+1$ is the road and indices from $1$ to $n$ are the spots for trees. Some of them are taken — there grow trees of the same height $k$. No more than one tree grows in each spot.\n\nWhen you chop down a tree in the spot $x$, you can make it fall either left or right. If it falls to the left, it takes up spots from $x-k$ to $x$, inclusive. If it falls to the right, it takes up spots from $x$ to $x+k$, inclusive.\n\nLet $m$ trees on the alley grow in some spots $x_1, x_2, \\dots, x_m$. Let an alley be called unfortunate if all $m$ trees can be chopped down in such a way that:\n\n- no tree falls on the shopping mall or the road;\n- each spot is taken up by no more than one fallen tree.\n\nCalculate the number of different unfortunate alleys with $m$ trees of height $k$. Two alleys are considered different if there is a spot $y$ such that a tree grows in $y$ on the first alley and doesn't grow in $y$ on the second alley.\n\nOutput the number modulo $998\\,244\\,353$.",
    "tutorial": "People say that this problem can be bashed with generating functions. Sadly, I know nothing about them, so I'll explain the more adhoc solution I managed to come up. Let's investigate the general form of some placement of trees. Imagine we fixed some position $x_1, x_2, \\dots, x_m$ for them. How to check if it's possible to cut them all down? Well, it's a simple greedy problem. Process trees left to right. If a tree can fall down to the left, make it fall to the left. Otherwise, if it can fall down to the right, make it fall to the right. Otherwise, no answer. Try a harder problem. Consider the spots the fallen trees take. How many constructions can these spots be induced by after the greedy algorithm is performed? First, these taken spots are actually segments of length $k+1$. Each tree can fall either from the left or the right side of the segment. To determine the answer, one has to look at the number of free spots to the left of each fallen tree. If there're at least $k$ free spots, then the tree can only fall from the left side of that segment. Otherwise, it can fall both ways. Thus, for $x$ trees that have less than $k$ free spots to the left of them, the answer is $2^x$. We can't really iterate over the constructions, so let's try yet another related problem. Would be cool if we could fix the exact number of trees that have more than $k$ free cells to the left of them. I don't really know how to do that. But I know how to fix at least the amount. Let that be at least $x$ trees. For $x$ trees, make their segments of length $2k+1$ - $k+1$ for the tree itself and $k$ extra cells to the left of it. For the rest $m-x$ trees, make their segments of length $k+1$. Then we have to place them on the given $n$ spots. The path is as follows. Rearrange the long and the short segments among each other - $\\binom{m}{x}$. Then use stars and bars to choose the amount of space between the segments - $\\binom{n-x\\cdot(2k+1)-(m-x)\\cdot(k+1)+m}{m}$. Finally, multiply by $2^{m-x}$ to fix the side for the short segments. Initially, we thought that we could just use PIE to calculate the exact answer from that - $\\sum\\limits_{x=0}^m f(x) \\cdot (-1)^x$. And the results of this formula coincided with the naive solution, so we thought that everything should be fine. But unfortunately, even though the formula is right, using PIE in the described way is incorrect. Let us show you the correct way. Let $F(x)$ be the number of ways to choose the segments for the trees in such a way that $x$ fixed segments are \"long\" (i. e. at least of length $2k+1$). To calculate $F(x)$, we use the familiar stars and bars concept: $\\binom{n-x\\cdot(2k+1)-(m-x)\\cdot(k+1)+m}{m}$ (we already had this formula earlier). Now, let $G(x)$ be the number of ways to choose the segments for the trees in such a way that $x$ fixed segments are \"long\", and all other segments are \"short\". The formula for $G(x)$ is a straightforward application of PIE: $G(x) = \\sum\\limits_{y=0}^{m-x} (-1)^y \\binom{m-x}{y} F(x+y)$, where we iterate on $y$ - the number of segments that should be short, but are definitely long. The answer to the problem can be calculated as $\\sum\\limits_{x=0}^{m} 2^{m-x} \\binom{m}{x} G(x)$ - we choose which $x$ segments are \"long\", and all others should be \"short\". Expanding $G(x)$ gives us the following formula: $\\sum\\limits_{x=0}^m \\sum\\limits_{y=0}^{m-x} (-1)^y 2^{m-x} \\binom{m}{x} \\binom{m-x}{y} F(x+y)$ which, after expanding binomial coefficients into factorials and getting rid of $(m-x)!$, becomes $\\sum\\limits_{x=0}^m \\sum\\limits_{y=0}^{m-x} (-1)^y 2^{m-x} \\frac{m!}{x! y! (m-x-y)!} F(x+y)$ We introduce the substitution variable $z = x + y$, and the formula becomes $\\sum\\limits_{z=0}^m \\sum\\limits_{y=0}^{z} (-1)^y 2^{m-z+y} \\frac{m!}{(z-y)! y! (m-z)!} F(z)$ By multiplying both the numerator and the denominator by $z!$, we then get $\\sum\\limits_{z=0}^m \\sum\\limits_{y=0}^{z} (-1)^y 2^{m-z+y} \\binom{m}{z} \\binom{z}{y} F(z)$ $\\sum\\limits_{z=0}^m \\binom{m}{z} 2^{m-z} F(z) \\sum\\limits_{y=0}^{z} (-2)^y \\binom{z}{y} F(z)$ And $\\sum\\limits_{y=0}^{z} (-2)^y \\binom{z}{y}$ is just $(1-2)^z$. Thus, the answer is equal to $\\sum\\limits_{z=0}^m (-1)^z \\binom{m}{z} 2^{m-z} F(z)$. Overall complexity: $O(n)$.",
    "code": "\n#include <bits/stdc++.h>\n \nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \n\nconst int MOD = 998244353;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\tif (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\n\nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n\nint binpow(int a, int b){\n\tint res = 1;\n\twhile (b){\n\t\tif (b & 1)\n\t\t\tres = mul(res, a);\n\t\ta = mul(a, a);\n\t\tb >>= 1;\n\t}\n\treturn res;\n}\n\nint main(){\n\tint n, m, k;\n\tscanf(\"%d%d%d\", &n, &m, &k);\n\t\n\tvector<int> fact(2 * n + 1), rfact(2 * n + 1);\n\tfact[0] = 1;\n\tfor (int i = 1; i <= 2 * n; ++i) fact[i] = mul(fact[i - 1], i);\n\trfact[2 * n] = binpow(fact[2 * n], MOD - 2);\n\tfor (int i = 2 * n - 1; i >= 0; --i) rfact[i] = mul(rfact[i + 1], i + 1);\n\tauto cnk = [&](int n, int k){\n\t\tif (k < 0 || n < 0 || k > n) return 0;\n\t\treturn mul(fact[n], mul(rfact[k], rfact[n - k]));\n\t};\n\tauto snb = [&](int n, int k){\n\t\treturn cnk(n + k, k);\n\t};\n\t\n\tint pw2 = 1;\n\tint ans = 0;\n\tfor (int i = m; i >= 0; --i){\n\t\tint cur = 0;\n\t\tif (n - (m - i) * 1ll * (k + 1) - i * 1ll * (2 * k + 1) >= 0)\n\t\t\tcur = mul(snb(n - (m - i) * (k + 1) - i * (2 * k + 1), m), mul(pw2, cnk(m, i)));\n\t\tans = add(ans, i & 1 ? -cur : cur);\n\t\tpw2 = mul(pw2, 2);\n\t}\n\t\n\tprintf(\"%d\\n\", ans);\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1822",
    "index": "A",
    "title": "TubeTube Feed",
    "statement": "Mushroom Filippov cooked himself a meal and while having his lunch, he decided to watch a video on TubeTube. He can not spend more than $t$ seconds for lunch, so he asks you for help with the selection of video.\n\nThe TubeTube feed is a list of $n$ videos, indexed from $1$ to $n$. The $i$-th video lasts $a_i$ seconds and has an entertainment value $b_i$. Initially, the feed is opened on the first video, and Mushroom can skip to the next video in $1$ second (if the next video exists). Mushroom can skip videos any number of times (including zero).\n\nHelp Mushroom choose \\textbf{one} video that he can open and watch in $t$ seconds. If there are several of them, he wants to choose the most entertaining one. Print the index of any appropriate video, or $-1$ if there is no such.",
    "tutorial": "This problem can be solved by going through all the options of the video that the Mushroom will choose to watch. Let the Mushroom choose the $i$-th video. He can view it if $a[i] + i - 1$ does not exceed $t$. Since he will have to spend $i - 1$ a second scrolling the TubeTube feed and $a[i]$ watching the video. As an answer, it is enough to choose a video with the maximum entertainment value from the appropriate ones.",
    "code": "def solve():\n    n, t = map(int, input().split())\n    a = [int(x) for x in input().split()]\n    b = [int(x) for x in input().split()]\n    bst = -2\n    for i in range(n):\n        if i + a[i] <= t and (bst == -2 or b[bst] < b[i]):\n            bst = i\n    print(bst + 1)\n \n \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1822",
    "index": "B",
    "title": "Karina and Array",
    "statement": "Karina has an array of $n$ integers $a_1, a_2, a_3, \\dots, a_n$. She loves multiplying numbers, so she decided that the beauty of a pair of numbers is their product. And the beauty of an array is the maximum beauty of a pair of \\textbf{adjacent} elements in the array.\n\nFor example, for $n = 4$, $a=[3, 5, 7, 4]$, the beauty of the array is $\\max$($3 \\cdot 5$, $5 \\cdot 7$, $7 \\cdot 4$) = $\\max$($15$, $35$, $28$) = $35$.\n\nKarina wants her array to be as beautiful as possible. In order to achieve her goal, she can remove some elements (possibly zero) from the array. After Karina removes all elements she wants to, the array must contain at least two elements.\n\nUnfortunately, Karina doesn't have enough time to do all her tasks, so she asks you to calculate the maximum beauty of the array that she can get by removing any number of elements (possibly zero).",
    "tutorial": "In the problem, we are not required to minimize the number of deletions, so we will search for the answer greedily. First, let's find two numbers in the array whose product is maximal. Note that the product of this pair of numbers will be the answer, since we can remove all elements from the array except this pair, then they will become neighboring. It is easy to see that the product of a pair of positive numbers is maximal when both numbers in the pair are maximal. So we need to consider the product of the two largest numbers. But it's worth remembering that the product of two negative numbers is positive, so the product of the two smallest numbers is also worth considering. The answer to the problem will be the maximum of these two products. To find the two largest and two smallest numbers, you can simply sort the array. The final asymptotics of the solution will be $O(n\\log n)$.",
    "code": "t = int(input())\n \nfor testCase in range(t):\n    n = int(input())\n    a = list(map(int, input().split(' ')))\n    a.sort()\n    print(max(a[0] * a[1], a[-1] * a[-2]))",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1822",
    "index": "C",
    "title": "Bun Lover",
    "statement": "Tema loves cinnabon rolls — buns with cinnabon and chocolate in the shape of a \"snail\".\n\nCinnabon rolls come in different sizes and are square when viewed from above. The most delicious part of a roll is the chocolate, which is poured in a thin layer over the cinnabon roll in the form of a spiral and around the bun, as in the following picture:\n\n\\begin{center}\n{\\small Cinnabon rolls of sizes 4, 5, 6}\n\\end{center}\n\nFor a cinnabon roll of size $n$, the length of the outer side of the square is $n$, and the length of the shortest vertical chocolate segment in the central part is one.\n\nFormally, the bun consists of two dough spirals separated by chocolate. A cinnabon roll of size $n + 1$ is obtained from a cinnabon roll of size $n$ by wrapping each of the dough spirals around the cinnabon roll for another layer.\n\n\\textbf{It is important that a cinnabon roll of size $n$ is defined in a unique way.}\n\nTema is interested in how much chocolate is in his cinnabon roll of size $n$. Since Tema has long stopped buying small cinnabon rolls, it is guaranteed that $n \\ge 4$.\n\nAnswer this non-obvious question by calculating the total length of the chocolate layer.",
    "tutorial": "Let's separate the complex chocolate layer into three simple parts. Now it is not difficult to calculate the total length of the three parts. The length of the light-yellow segment $1$. Length of the cyan polyline $1 + 2 + \\dots + n = \\dfrac{n \\cdot (n + 1)}{2}$. Length of the lilac polyline $1 + 2 + \\dots + (n + 1) = \\frac{(n + 1) \\cdot (n + 2)}{2}$. Total length of chocolate $\\dfrac{(n + 1) \\cdot (n + 2)}{2} + \\dfrac{n \\cdot (n + 1)}{2} + 1 = \\dfrac{(n + 1) \\cdot (n + 2) + n \\cdot (n + 1)}{2} + 1 = \\dfrac{2 \\cdot (n + 1)^2}{2} + 1 = (n + 1)^2 + 1$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define int long long\n\nint32_t main() {\n    int q;\n    cin >> q;\n    while (q--) {\n        int n;\n        cin >> n;\n        cout << ((n + 1) * n) + n + 2 << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1822",
    "index": "D",
    "title": "Super-Permutation",
    "statement": "A permutation is a sequence $n$ integers, where each integer from $1$ to $n$ appears exactly once. For example, $[1]$, $[3,5,2,1,4]$, $[1,3,2]$ are permutations, while $[2,3,2]$, $[4,3,1]$, $[0]$ are not.\n\nGiven a permutation $a$, we construct an array $b$, where $b_i = (a_1 + a_2 +~\\dots~+ a_i) \\bmod n$.\n\nA permutation of numbers $[a_1, a_2, \\dots, a_n]$ is called a super-permutation if $[b_1 + 1, b_2 + 1, \\dots, b_n + 1]$ is also a permutation of length $n$.\n\nGrisha became interested whether a super-permutation of length $n$ exists. Help him solve this non-trivial problem. Output any super-permutation of length $n$, if it exists. Otherwise, output $-1$.",
    "tutorial": "Let $k$ be the position of the number $n$ in the permutation $a$, that is, $a_k = n$, then if $k > 1$, then $b_k = (b_{k-1} + a_k) \\mod n = b_{k-1}$ therefore, $b$ is not a permutation, so $k = 1$. Now note that if $n > 1$ is odd, then $b_n = (a_1~+~a_2~+~\\dots~+~a_n) \\mod n = (1 +2 +~\\dots~+ n) \\mod n= n \\cdot\\frac{(n + 1)}{2} \\mod n = 0 = b_1$. So there is no answer. If $n$ is even, then one possible example would be $a = [n,~1,~n-2,~3,~n-4,~5,~\\dots,~n - 1,~2]$, since then $b = [0,~1,~n-1,~2,~n-2,~3,~n-3,~\\dots,~\\frac{n}{2}]$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int q;\n    cin >> q;\n    while (q--) {\n        int n;\n        cin >> n;\n        if (n == 1) {\n            cout << \"1\\n\";\n            continue;\n        }\n        if (n % 2) {\n            cout << \"-1\\n\";\n        } else {\n            for (int i = 0; i < n; ++i) {\n                if (i % 2) {\n                    cout << i << \" \";\n                } else {\n                    cout << n - i << \" \";\n                }\n            }\n            cout << \"\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1822",
    "index": "E",
    "title": "Making Anti-Palindromes",
    "statement": "You are given a string $s$, consisting of lowercase English letters. In one operation, you are allowed to swap any two characters of the string $s$.\n\nA string $s$ of length $n$ is called an anti-palindrome, if $s[i] \\ne s[n - i + 1]$ for every $i$ ($1 \\le i \\le n$). For example, the strings \"codeforces\", \"string\" are anti-palindromes, but the strings \"abacaba\", \"abc\", \"test\" are not.\n\nDetermine the minimum number of operations required to make the string $s$ an anti-palindrome, or output $-1$, if this is not possible.",
    "tutorial": "If $n$ is odd, then there is no solution, since $s[(n + 1) / 2] = s[(n + 1) - (n + 1) / 2]$. If $n$ is even, then all symbols are split into pairs $s[i], s[n + 1 - i]$. Let's denote the number of occurrences of the symbol $c$ as $cnt[c]$. Note that if $cnt[c] > n / 2$ for some $c$, then after applying the operations there will be a pair where both characters are equal to $c$, then it is impossible to make the string $s$ anti-palindrome. Otherwise, we will calculate $k$ - the number of pairs, where $s[i] = s[n + 1 - i]$, we will also find $m$ - the maximum number of pairs, where $s[i] = s[n + 1 - i] = c$, for all characters $c$. Let $x$ be a symbol for which the number of such pairs is equal to $m$. Note that $ans\\ge m$, because in one operation the number of pairs where $s[i] = s[n + 1 - i] = x$ cannot decrease by more than $1$. Also note that $ans \\ge \\lceil \\frac{k}{2} \\rceil$, because for each operation we reduce the number of pairs where $s[i] = s[n + 1 - i]$ by no more than $2$. It turns out that $ans = max(m, \\lceil \\frac{k}{2} \\rceil)$, to show this, you can act greedily - until $k > 0$: If $k=m$, then we find a pair $s[i] = s[n + 1 - i] = x$, since $cnt[x] \\le n / 2$, then there is a pair where $s[j] \\ne x$ and $s[n + 1 - j] \\ne x$. Then swap $s[i]$ and $s[j]$. Otherwise, find the pair $s[i] = s[n + 1 - i] = x$, and the pair $s[j] = s[n + 1 - j] \\ne x$. Then swap $s[i]$ and $s[j]$. It is not difficult to check that in both cases, $max(m, \\lceil k/2\\rceil)$ will decrease by exactly $1$, which means $ans$ is achieved with this algorithm.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve(int n, string & s) {\n    if (n % 2 == 1) {\n        cout << -1 << endl;\n        return;\n    }\n    vector<int> cnt(26);\n    for (int i = 0; i < n; ++i) {\n        ++cnt[s[i] - 'a'];\n    }\n    for (int i = 0; i < 26; ++i) {\n        if (cnt[i] * 2 > n) {\n            cout << -1 << endl;\n            return;\n        }\n    }\n    int pairs = 0;\n    vector<int> cnt_pairs(26);\n    for (int i = 0; i * 2 < n; ++i) {\n        if (s[i] == s[n - i - 1]) {\n           ++pairs;\n           ++cnt_pairs[s[i] - 'a'];\n        }\n    }\n    for (int i = 0; i < 26; ++i) {\n        if (cnt_pairs[i] * 2 > pairs) {\n            cout << cnt_pairs[i] << endl;\n            return;\n        }\n    }\n    cout << (pairs + 1) / 2 << endl;\n}\n\nint32_t main() {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        solve(n, s);\n    }\n}",
    "tags": [
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1822",
    "index": "F",
    "title": "Gardening Friends",
    "statement": "Two friends, Alisa and Yuki, planted a tree with $n$ vertices in their garden. A tree is an undirected graph without cycles, loops, or multiple edges. Each edge in this tree has a length of $k$. Initially, vertex $1$ is the root of the tree.\n\nAlisa and Yuki are growing the tree not just for fun, they want to sell it. The cost of the tree is defined as the maximum distance from the root to a vertex among all vertices of the tree. The distance between two vertices $u$ and $v$ is the sum of the lengths of the edges on the path from $u$ to $v$.\n\nThe girls took a course in gardening, so they know how to modify the tree. Alisa and Yuki can spend $c$ coins to shift the root of the tree to one of the \\textbf{neighbors of the current root}. This operation can be performed any number of times (possibly zero). Note that the structure of the tree is left unchanged; the only change is which vertex is the root.\n\nThe friends want to sell the tree with the maximum profit. The profit is defined as the difference between the cost of the tree and the total cost of operations. \\textbf{The profit is cost of the tree minus the total cost of operations}.\n\nHelp the girls and find the maximum profit they can get by applying operations to the tree any number of times (possibly zero).",
    "tutorial": "Let's first calculate its depth for each vertex. Let for a vertex $v$ its depth is $depth[v]$. All the values of $depth[v]$ can be calculated by a single depth-first search. We introduce several auxiliary quantities. Let for vertex $v$ the values $down_1[v], down_2[v]$ are the two largest distances to the leaves in the subtree of vertex $v$ of the source tree. We will also introduce the value $up[v]$ - the maximum distance to the leaf outside the subtree of the vertex $v$. The values of $down_1[v]$ and $down_2[v]$ are easily recalculated by walking up the tree from the bottom and maintaining two maximum distances to the leaves. Let $p$ be the ancestor of the vertex $v$. Then to recalculate $up[v]$, you need to go up to $p$ and find the maximum distance to a leaf outside the subtree $v$. If the leaf farthest from $p$ is in the subtree $v$, then you will need to take $down_2[p]$, otherwise $down_1[p]$. For $v$, we define the maximum distance to the leaf, as $dist[v] = max(down_1[v], up[v])$. Now let's calculate for each vertex $v$ the cost of the tree if $v$ becomes the root. It is not profitable for us to take extra steps, so the cost of operations will be equal to $c\\cdot depth[v]$. Then the cost of the tree will be equal to the value of $k\\cdot dist[v] - c\\cdot depth[v]$. It remains to go through all the vertices, take the maximum of the tree values and get an answer. It is easy to see that such a solution works for $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nstruct Value {\n    int64_t value = 0;\n    int vertex = 0;\n};\n\nvector<vector<int>> nei;\nvector<vector<int>> depth_vertex;\nvector<int> depth;\nvector<int> parent;\n\nvoid dfs(int v, int p = -1, int cnt = 0) {\n    depth_vertex[cnt].push_back(v);\n    depth[v] = cnt;\n    parent[v] = p;\n    for (int u : nei[v]) {\n        if (u == p) continue;\n        dfs(u, v, cnt + 1);\n    }\n}\n\nvoid solve() {\n    int n, root = 1;\n    int64_t k_wei, cost;\n    cin >> n >> k_wei >> cost;\n\n    nei.clear();\n    nei.resize(n + 1);\n    depth_vertex.clear();\n    depth_vertex.resize(n + 1);\n    depth.clear();\n    depth.resize(n + 1);\n    parent.clear();\n    parent.resize(n + 1);\n\n    for (int _ = 0; _ < n - 1; ++_) {\n        int u, v;\n        cin >> u >> v;\n        nei[u].push_back(v);\n        nei[v].push_back(u);\n    }\n\n    dfs(root);\n\n    vector<pair<Value, Value>> down(n + 1);\n\n    for (int tin = n; tin >= 0; --tin) {\n        for (int v : depth_vertex[tin]) {\n            for (int u : nei[v]) {\n                if (u == parent[v]) continue;\n                if (down[u].first.value + 1 > down[v].first.value) {\n                    down[v].first.value = down[u].first.value + 1;\n                    down[v].first.vertex = u;\n                }\n            }\n            for (int u : nei[v]) {\n                if (u == parent[v] || u == down[v].first.vertex) continue;\n                if (down[u].first.value + 1 > down[v].second.value) {\n                    down[v].second.value = down[u].first.value + 1;\n                }\n            }\n        }\n    }\n\n    vector<int64_t> up(n + 1, 0);\n\n    for (int tin = 1; tin <= n; ++tin) {\n        for (int v : depth_vertex[tin]) {\n            int p = parent[v];\n            up[v] = up[p] + 1;\n            if (down[p].first.vertex == v) {\n                up[v] = max(up[v], down[p].second.value + 1);\n            } else {\n                up[v] = max(up[v], down[p].first.value + 1);\n            }\n        }\n    }\n\n    int64_t ans = -1'000'000'000'000'000'002;\n\n    for (int v = 1; v <= n; ++v) {\n        ans = max(ans, k_wei * max(up[v], down[v].first.value) - cost * int64_t(depth[v]));\n    }\n\n    cout << ans << endl;\n\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    for (int _ = 1; _ <= t; ++_) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1822",
    "index": "G1",
    "title": "Magic Triples (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is that in this version, $a_i \\le 10^6$.}\n\nFor a given sequence of $n$ integers $a$, a triple $(i, j, k)$ is called magic if:\n\n- $1 \\le i, j, k \\le n$.\n- $i$, $j$, $k$ are pairwise distinct.\n- there exists a positive integer $b$ such that $a_i \\cdot b = a_j$ and $a_j \\cdot b = a_k$.\n\nKolya received a sequence of integers $a$ as a gift and now wants to count the number of magic triples for it. Help him with this task!\n\nNote that there are no constraints on the order of integers $i$, $j$ and $k$.",
    "tutorial": "Let $M = \\max {a_i}$, obviously $M\\le 10^6$, $cnt[x]$ - the number of occurrences of the number $x$ in the array $a$. Separately, let's count the number of magic triples for $b=1$. The total number of such triples will be $\\sum_{i=1}^{n}{(cnt[a_i] - 1) \\cdot (cnt[a_i] - 2)}$. Next, we will count $b\\ge 2$. Note that $a_i \\cdot b \\cdot b = a_k$, so $b \\le \\sqrt{a_k /a_i} \\le \\sqrt{M}$. Thus, after sorting through all possible $i$ from $1$ to $n$, as well as all $b\\le\\sqrt{M}$ and adding $cnt[a_i\\cdot b] \\cdot cnt[a_i\\cdot b\\cdot b]$ to the answer, we get a solution for $O(\\sqrt{M}\\cdot n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define int long long\n\nconst int MAX_VAL = 1e6;\n\nint cnt[MAX_VAL + 1];\n\nint32_t main() {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n            ++cnt[a[i]];\n        }\n        int ans = 0;\n        for (int i = 0; i < n; ++i) {\n            ans += (cnt[a[i]] - 1) * (cnt[a[i]] - 2);\n            for (int b = 2; a[i] * b * b <= MAX_VAL; ++b) {\n                ans += cnt[a[i] * b] * cnt[a[i] * b * b];\n            }\n        }\n        cout << ans << \"\\n\";\n        for (int i = 0; i < n; ++i) {\n            --cnt[a[i]];\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1822",
    "index": "G2",
    "title": "Magic Triples (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version, $a_i \\le 10^9$.}\n\nFor a given sequence of $n$ integers $a$, a triple $(i, j, k)$ is called magic if:\n\n- $1 \\le i, j, k \\le n$.\n- $i$, $j$, $k$ are pairwise distinct.\n- there exists a positive integer $b$ such that $a_i \\cdot b = a_j$ and $a_j \\cdot b = a_k$.\n\nKolya received a sequence of integers $a$ as a gift and now wants to count the number of magic triples for it. Help him with this task!\n\nNote that there are no constraints on the order of integers $i$, $j$ and $k$.",
    "tutorial": "Let $M = \\max {a_i}$, obviously $M \\le 10^9$, $cnt[x]$ - the number of occurrences of the number $x$ in the array $a$. Separately, let's count the number of magic triples for $b=1$. The total number of such triples will be $\\sum_{i=1}^{n}{(cnt[a_i] - 1) \\cdot (cnt[a_i] - 2)}$. Next, we will count $b \\ge 2$. We will iterate over $a_j$, if $a_j \\ge M ^ \\frac{2}{3}$, then $a_j \\cdot b = a_k \\le M$, then $b\\le M^\\frac{1}{3}$. Otherwise, $a_j \\le M^\\frac{2}{3}$, since $a_i \\cdot b = a_j$, then $b$ is a divisor of $a_j$, which means it is enough to iterate as $b$ the divisors of the number $a_j$, the divisors of such the numbers can be found for $O(M^\\frac{1}{3})$, which means the total complexity will be $O(n\\cdot M^\\frac{1}{3})$ if you use the hash table $cnt[x]$, or $O(n\\cdot M^\\frac{1}{3}\\cdot\\log{n})$ if you use std::map.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int K = 1e6;\nconst int MAX_VAL = 1e9;\n\nint32_t main() {\n    int t;\n    scanf(\"%d\", &t);\n    for (int _ = 0; _ < t; ++_) {\n        int n;\n        scanf(\"%d\", &n);\n        vector<int> a(n);\n        map<int, int> cnt;\n        for (int i = 0; i < n; ++i) {\n            scanf(\"%d\", &a[i]);\n            ++cnt[a[i]];\n        }\n        ll ans = 0;\n        for (int i = 0; i < n; ++i) {\n            ans += (ll)(cnt[a[i]] - 1) * (cnt[a[i]] - 2);\n        }\n        for (auto el : cnt) {\n            int num = el.first;\n            int val = el.second;\n            if (num > K) {\n                for (int b = 2; b * num <= MAX_VAL; ++b) {\n                    if (num % b == 0 && cnt.find(num / b) != cnt.end() && cnt.find(num * b) != cnt.end()) {\n                        ans += (ll)(cnt[num / b]) * (cnt[num * b]) * val;\n                    }\n                }\n            } else {\n                for (int b = 2; b * b <= num; ++b) {\n                    if (num % b == 0) {\n                        if ((ll)num * b <= (ll)MAX_VAL && cnt.find(num / b) != cnt.end() && cnt.find(num * b) != cnt.end()) {\n                            ans += (ll)(cnt[num / b]) * (cnt[num * b]) * val;\n                        }\n                        if (b * b != num) {\n                            if ((ll)num * num / b <= (ll)MAX_VAL && cnt.find(b) != cnt.end() && cnt.find(num / b * num) != cnt.end()) {\n                                ans += (ll)(cnt[b]) * (cnt[num / b * num]) * val;\n                            }\n                        }\n                    }\n                }\n                if (num > 1 && (ll)num * num <= (ll)MAX_VAL && cnt.find(1) != cnt.end() && cnt.find(num * num) != cnt.end()) {\n                    ans += (ll)(cnt[1]) * (cnt[num * num]) * val;\n                }\n            }\n        }\n        printf(\"%lld\\n\", ans);\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1823",
    "index": "A",
    "title": "A-characteristic",
    "statement": "Consider an array $a_1, a_2, \\dots, a_n$ consisting of numbers $1$ and $-1$. Define $A$-characteristic of this array as a number of pairs of indices $1 \\le i < j \\le n$, such that $a_i \\cdot a_j = 1$.\n\nFind any array $a$ with given length $n$ with $A$-characteristic equal to the given value $k$.",
    "tutorial": "Note that the $A$-characteristic depends only on the number of $1$-s. Let the number of $1$-s be equal to $x$, then the number of $-1$-s is equal to $n - x$, and the $A$-characteristic is equal to $f(x) = \\frac{(x - 1) \\cdot x}{ 2} + \\frac{(n - x - 1) \\cdot (n - x)}{2}$. Let's iterate over all $x$ from $0$ to $n$, and check if there is such $x$ that $f(x) = k$. Then print $x$ numbers $1$ and $n - x$ numbers $-1$.",
    "code": "for tt in range(int(input())):\n    n, k = map(int, input().split())\n    x = -1\n\n    for i in range(0, n + 1):\n        if i * (i - 1) / 2 + (n - i) * (n - i - 1) / 2 == k:\n            x = i\n\n    if x == -1:\n        print(\"NO\")\n    else:\n        print(\"YES\")\n        for i in range(0, n):\n            if i < x:\n                print(\"1 \", end = '')\n            else:\n                print(\"-1 \", end = '')\n        print(\"\")",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1823",
    "index": "B",
    "title": "Sort with Step",
    "statement": "Let's define a permutation of length $n$ as an array $p$ of length $n$, which contains every number from $1$ to $n$ exactly once.\n\nYou are given a permutation $p_1, p_2, \\dots, p_n$ and a number $k$. You need to sort this permutation in the ascending order. In order to do it, you can repeat the following operation any number of times (possibly, zero):\n\n- pick two elements of the permutation $p_i$ and $p_j$ such that $|i - j| = k$, and swap them.\n\nUnfortunately, some permutations can't be sorted with some fixed numbers $k$. For example, it's impossible to sort $[2, 4, 3, 1]$ with $k = 2$.\n\nThat's why, before starting the sorting, you can make at most one preliminary exchange:\n\n- choose any pair $p_i$ and $p_j$ and swap them.\n\nYour task is to:\n\n- check whether is it possible to sort the permutation \\textbf{without} any preliminary exchanges,\n- if it's not, check, whether is it possible to sort the permutation using exactly \\textbf{one} preliminary exchange.\n\nFor example, if $k = 2$ and permutation is $[2, 4, 3, 1]$, then you can make a preliminary exchange of $p_1$ and $p_4$, which will produce permutation $[1, 4, 3, 2]$, which is possible to sort with given $k$.",
    "tutorial": "Let's fix a number $0 \\le x < k$ and consider all indices $i$ such that $i \\bmod k = x$. Note that numbers in these positions can be reordered however we want, but they can't leave this set of positions, since $i \\bmod k$ stay the same. Moreover, in the sorted permutation these positions must contain numbers $j$ such that $(j - 1) \\bmod k = x$. In total, itm means that the permutation can be sorted if $(p[i] - 1) \\bmod k = i \\bmod k$ holds for all $i$. By preliminary exchange, we can swap two elements from different sets. Therefore, if the last equality fails for exactly two elements, they can be swapped, making sorting possible. Otherwise, the answer is $-1$.",
    "code": "for tt in range(int(input())):\n    n, k = map(int, input().split())\n    p = list(map(int, input().split()))\n    for i in range(0, n):\n        p[i] -= 1\n\n    bad = 0\n    for i in range(0, n):\n        if p[i] % k != i % k:\n            bad += 1\n\n    if bad == 0:\n        print(0)\n    elif bad == 2:\n        print(1)\n    else:\n        print(-1)",
    "tags": [
      "brute force",
      "math",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1823",
    "index": "C",
    "title": "Strongly Composite",
    "statement": "A prime number is an integer greater than $1$, which has exactly two divisors. For example, $7$ is a prime, since it has two divisors $\\{1, 7\\}$. A composite number is an integer greater than $1$, which has more than two different divisors.\n\nNote that the integer $1$ is neither prime nor composite.\n\nLet's look at some composite number $v$. It has several divisors: some divisors are prime, others are composite themselves. If the number of prime divisors of $v$ is \\textbf{less or equal} to the number of composite divisors, let's name $v$ as strongly composite.\n\nFor example, number $12$ has $6$ divisors: $\\{1, 2, 3, 4, 6, 12\\}$, two divisors $2$ and $3$ are prime, while three divisors $4$, $6$ and $12$ are composite. So, $12$ is strongly composite. Other examples of strongly composite numbers are $4$, $8$, $9$, $16$ and so on.\n\nOn the other side, divisors of $15$ are $\\{1, 3, 5, 15\\}$: $3$ and $5$ are prime, $15$ is composite. So, $15$ is not a strongly composite. Other examples are: $2$, $3$, $5$, $6$, $7$, $10$ and so on.\n\nYou are given $n$ integers $a_1, a_2, \\dots, a_n$ ($a_i > 1$). You have to build an array $b_1, b_2, \\dots, b_k$ such that following conditions are satisfied:\n\n- Product of all elements of array $a$ is equal to product of all elements of array $b$: $a_1 \\cdot a_2 \\cdot \\ldots \\cdot a_n = b_1 \\cdot b_2 \\cdot \\ldots \\cdot b_k$;\n- All elements of array $b$ are integers greater than $1$ and strongly composite;\n- The size $k$ of array $b$ is the maximum possible.\n\nFind the size $k$ of array $b$, or report, that there is no array $b$ satisfying the conditions.",
    "tutorial": "Let's understand criteria for a number $x$ being strongly composite. Let's factorize the number $x = {p_1}^{d_1} \\cdot {p_2}^{d_2} \\cdot \\dots \\cdot {p_m}^{d_m}$. The number of all divisors of $x$ is $D = \\prod\\limits_{i = 1}^{m} (d_i + 1)$. Since the number of prime divisors is $m$, then the number of composite divisors of $x$ is $D - m - 1$. Then a number $x$ is strongly composite if $m \\le D - m - 1$ or $2 \\cdot m + 1 \\le D$. Since $m$ is the number of $d_i + 1 \\ge 2$, then $D \\ge 2^m$. Consider a weakened condition for a strongly composite number: $2 \\cdot m + 1 \\le 2^m$. If $m = 1$, then the condition is satisfied only if $d_1 \\ge 2$. If $m = 2$, then the condition is satisfied only if $\\max{(d_1, d_2)} \\ge 2$. If $m \\ge 3$, then the condition is always satisfied. In summary, a number is not strongly composite if it is either a prime or the product of two distinct primes. Now let's solve the problem. Let's split all numbers into primes. Assume we have pairs $(p_i, c_i)$, where $p_i$ is a prime number and $c_i$ is the number of its occurrences. We can take either two same prime numbers or three of any prime numbers. The optimal strategy is to create the maximum number of pairs of same prime numbers $\\sum\\limits_i{\\left\\lfloor \\frac{c_i}{2} \\right\\rfloor}$, and when there will be only $r = \\sum\\limits_i{(c_i \\bmod 2)}$ different prime numbers remaining. We can merge these remaining primes in triples to get extra $\\left\\lfloor \\frac{r}{3} \\right\\rfloor$ strongly composite numbers. If, after merging triples, we have some primes left, we can add them to any already strongly composite number, and it won't change its total number. There were initially more complex version of this task. Can you solve it? You are given $n$ integers $a_1, a_2, \\dots, a_n$ ($a_i > 1$). You can perform the following operation with array $a$ any number of times: choose two indices $i$ and $j$ ($i < j$); choose two indices $i$ and $j$ ($i < j$); erase elements $a_i$ and $a_j$ from $a$; erase elements $a_i$ and $a_j$ from $a$; insert element $a_i \\cdot a_j$ in $a$. insert element $a_i \\cdot a_j$ in $a$. After performing one such operation, the length of $a$ decreases by one. Let's say that array $a$ is good, if it contains only strongly composite numbers. What is the minimum number of operation you need to perform to make array $a$ good?",
    "code": "def is_prime(x):\n    i = 2\n    while i * i <= x:\n        if x % i == 0:\n            return False\n        i += 1\n    return True\n\ndef is_strongly_composite(x):\n    m = []\n    i = 2\n    while i * i <= x:\n        while x % i == 0:\n            x = x // i\n            m.append(i)\n        i += 1\n    if not x == 1:\n        m.append(i)\n    return (len(m) >= 3 or (len(m) == 2 and m[0] == m[1]))\n\nfor tt in range(int(input())):\n    n = int(input())\n    lst = list(map(int, input().split()))\n    a = {}\n    for x in lst:\n        i = 2\n        while i * i <= x:\n            while x % i == 0:\n                x = x // i\n                if i in a:\n                    a[i] += 1\n                else:\n                    a[i] = 1\n            i += 1\n        if x != 1:\n            if x in a:\n                a[x] += 1\n            else:\n                a[x] = 1\n\n    res, rem = 0, 0\n\n    for num in a:\n        cnt = a[num]\n        res += cnt // 2\n        rem += cnt % 2\n\n    res += rem // 3\n    print(res)",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1823",
    "index": "D",
    "title": "Unique Palindromes",
    "statement": "A palindrome is a string that reads the same backwards as forwards. For example, the string abcba is palindrome, while the string abca is not.\n\nLet $p(t)$ be the number of unique palindromic substrings of string $t$, i. e. the number of substrings $t[l \\dots r]$ that are palindromes themselves. Even if some substring occurs in $t$ several times, it's counted exactly once. (The whole string $t$ is also counted as a substring of $t$).\n\nFor example, string $t$ $=$ abcbbcabcb has $p(t) = 6$ unique palindromic substrings: a, b, c, bb, bcb and cbbc.\n\nNow, let's define $p(s, m) = p(t)$ where $t = s[1 \\dots m]$. In other words, $p(s, m)$ is the number of palindromic substrings in the prefix of $s$ of length $m$. For example, $p($abcbbcabcb$, 5)$ $=$ $p($abcbb$) = 5$.\n\nYou are given an integer $n$ and $k$ \"conditions\" ($k \\le 20$). Let's say that string $s$, consisting of $n$ lowercase Latin letters, is \\textbf{good} if all $k$ conditions are satisfied \\textbf{at the same time}. A condition is a pair $(x_i, c_i)$ and have the following meaning:\n\n- $p(s, x_i) = c_i$, i. e. a prefix of $s$ of length $x_i$ contains exactly $c_i$ unique palindromic substrings.\n\nFind a good string $s$ or report that such $s$ doesn't exist.Look in Notes if you need further clarifications.",
    "tutorial": "Let us estimate the possible number of unique palindromes $P$: for $n = 1$: $P = 1$; for $n = 2$: $P = 2$ (in both cases: if symbols are equal and if not); for $n \\ge 3$: $3 \\le P \\le n$. Any combination of the first three characters gives $P = 3$. If you add a character to the string, $P$ will increase by either $0$ or $1$. This can be proven by contradiction. Assume $P_{new} - P_{old} \\ge 2$. Choose $2$ of any new palindromes. The shorter one is both a suffix and a prefix of the larger one (since both are palindromes), but we've added all the palindromes. So the smaller one was added earlier. An example of a string with $P = 3$: abcabc.... An example of a string with $P = n$: aaaaaa.... An example of a string with $P = 3$: abcabc.... An example of a string with $P = n$: aaaaaa.... By choosing the prefix of appropriate length that consists of a characters, we can achieve all the values of $3 \\le P \\le n$. Print $k - 3$ characters a and then characters abc until the end of the string. Let solve the initial task for $k > 1$ conditions. Firstly, we build the answer for the first condition. After that, assume we have answer for first $t$ conditions. If $c_{t + 1} - c_{t} > x_{t + 1} - x_{t}$, then we can't build an answer by lemma. Otherwise, we can do the following: take a symbol, that wasn't used and append it $c_{t + 1} - c_{t}$ times to answer; then append symbols ...abcabca.... The final string will look as following, where | symbol shows conditions boundaries: aaaaaaaaabcabcab|dddddcabcabca|eeebcab Note that, in order not to create unnecessary palindromes, if we finished the previous abcabc... block with some character (for example, a), the next abcabc... block should start with the next character (b). There were initially simpler version of this problem with $k = 1$, but it coincided with other problem. Also, how does checker in this problem works?",
    "code": "for tt in range(int(input())):\n    n, k = map(int, input().split())\n    x = list(map(int, input().split()))\n    c = list(map(int, input().split()))\n\n    if c[0] < 3 or c[0] > x[0]:\n        print(\"NO\")\n        continue\n\n    s = \"\"\n    cur = 'a'\n\n    for i in range(0, c[0] - 3):\n        s += \"a\"\n\n    for i in range(c[0] - 3, x[0]):\n        s += cur\n        cur = chr(ord(cur) + 1)\n        if cur == 'd':\n            cur = 'a'\n\n    good = True\n    for j in range(1, k):\n        dx = x[j] - x[j - 1]\n        dc = c[j] - c[j - 1]\n        if dc > dx:\n            good = False\n            break\n\n        for i in range(0, dc):\n            s += chr(ord('c') + j)\n        for i in range(dc, dx):\n            s += cur\n            cur = chr(ord(cur) + 1)\n            if cur == 'd':\n                cur = 'a'\n\n    if good:\n        print(\"YES\")\n        print(s)\n    else:\n        print(\"NO\")",
    "tags": [
      "constructive algorithms",
      "math",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1823",
    "index": "E",
    "title": "Removing Graph",
    "statement": "Alice and Bob are playing a game on a graph. They have an undirected graph without self-loops and multiple edges. All vertices of the graph have \\textbf{degree equal to $2$}. The graph may consist of several components. Note that if such graph has $n$ vertices, it will have exactly $n$ edges.\n\nAlice and Bob take turn. Alice goes first. In each turn, the player can choose $k$ ($l \\le k \\le r$; $l < r$) vertices that form \\textbf{a connected subgraph} and erase these vertices from the graph, including all incident edges.\n\nThe player who can't make a step loses.\n\nFor example, suppose they are playing on the given graph with given $l = 2$ and $r = 3$:\n\nA valid vertex set for Alice to choose at the first move is one of the following:\n\n- $\\{1, 2\\}$\n- $\\{1, 3\\}$\n- $\\{2, 3\\}$\n- $\\{4, 5\\}$\n- $\\{4, 6\\}$\n- $\\{5, 6\\}$\n- $\\{1, 2, 3\\}$\n- $\\{4, 5, 6\\}$\n\nSuppose, Alice chooses subgraph $\\{4, 6\\}$.Then a valid vertex set for Bob to choose at the first move is one of the following:\n\n- $\\{1, 2\\}$\n- $\\{1, 3\\}$\n- $\\{2, 3\\}$\n- $\\{1, 2, 3\\}$\n\nSuppose, Bob chooses subgraph $\\{1, 2, 3\\}$.Alice can't make a move, so she loses.\n\nYou are given a graph of size $n$ and integers $l$ and $r$. Who will win if both Alice and Bob play optimally.",
    "tutorial": "The solution requires knowledge of the Sprague-Grundy theory. Recall that $a \\oplus b$ means the bitwise exclusive or operation, and $\\operatorname{mex}(S)$ is equal to the minimum non-negative number that is not in the set $S$. The fact that $l \\neq r$ is important. The given graph is a set of cycles, and the game runs independently in each cycle. If we can calculate nim-value for a cycle of each size, then nim-value of the whole game is equal to XOR of these values. To calculate nim-value for the cycle of length $x$ ($cycle[x]$), we need to take $\\operatorname{mex}$ of nim-values from all transitions. But since all transitions transform a cycle to a chain, then we will calculate nim-values for chains as well, or $cycle[x] = \\operatorname{mex}(chain[x - r], chain[x - r + 1], \\dots, chain[x - l])$. To calculate nim-value for the chain $chain[x]$, we need to consider all possible transitions. We can either cut off from the end of the chain, or from the middle of the chain. In either case, we end up with two smaller chains (maybe one of them is empty), which are themselves independent games, so $chain[x] = \\operatorname{mex}{\\{chain[a] \\oplus chain[b] \\mid \\forall a, b \\ge 0 : x - r \\le a + b \\le x - l\\}}$. Implementing this directly requires $O(n^3)$ time. A more accurate implementation with recalculations requires $O(n^2)$ time. For a complete solution, something needs to be noticed in nim-values. Consider an example. Let $l = 4$, $r = 14$. index012345678910111213141516171819$chain$00001111222233334444$cycle$00001111222233334400$\\uparrow$$l + r$ $chain[x]$ on $[0, l - 1]$ is obviously equal to $0$; $chain[x] = \\left\\lfloor \\frac{x}{l} \\right\\rfloor$ on segment $[0, r + l - 1]$ (proof is below); $chain[x] > 0$ for all $x \\ge l$: since $l < r$ you can always split the chain $x$ in two equal chains $a$. This transition adds nim-value $chain[a] \\oplus chain[a] = 0$ into $\\operatorname{mex}$, that's why $chain[x] = \\operatorname{mex}{\\{\\dots\\}} > 0$. $cycle[x]$ is equal to $chain[x]$ up to $r + l - 1$: it's because $cycle[x]$ is equal to $\\operatorname{mex}{\\{chain[0], chain[1], \\dots, chain[x - l]\\}}$; $cycle[x] = 0$ for $x \\ge l + r$, it's because $chain[x] > 0$ for $x \\ge l$. So, if $x \\le r + l - 1$, then $cycle[x] = \\left\\lfloor \\frac{x}{l} \\right\\rfloor$, otherwise $cycle[x] = 0$. We have to calculate the sizes of all cycles in the graph and calculate XOR of those values. If it is zero, the winner is Bob, otherwise, winner is Alice. Let's prove that $chain[x] = \\left\\lfloor \\frac{x}{l} \\right\\rfloor$ on segment $[0, r + l - 1]$: $chain[x] \\ge \\left\\lfloor \\frac{x}{l} \\right\\rfloor$: there are transitions to pairs of chains $(a, b)$ where $a = 0$ and $b$ is any number from $[0, x - l]$. Their nim-value is equal to $chain[0] \\oplus chain[b]$ $=$ $chain[b]$, so $chain[x] \\ge \\operatorname{mex}{\\{chain[b] \\mid 0 \\le b \\le x - l\\}} = \\left\\lfloor \\frac{x}{l} \\right\\rfloor$. $chain[x]$ is exactly equal to $\\left\\lfloor \\frac{x}{l} \\right\\rfloor$: we can prove that for any pair of chains $(a, b)$ with $a + b \\le x - l$ value $chain[a] \\oplus chain[b]$ $\\le$ $\\left\\lfloor \\frac{x}{l} \\right\\rfloor - 1$: $chain[a] \\oplus chain[b] \\le chain[a] + chain[b] = \\left\\lfloor \\frac{a}{l} \\right\\rfloor + \\left\\lfloor \\frac{b}{l} \\right\\rfloor \\le \\left\\lfloor \\frac{a + b}{l} \\right\\rfloor \\le \\left\\lfloor \\frac{x - l}{l} \\right\\rfloor = \\left\\lfloor \\frac{x}{l} \\right\\rfloor - 1$ $chain[a] \\oplus chain[b] \\le chain[a] + chain[b] = \\left\\lfloor \\frac{a}{l} \\right\\rfloor + \\left\\lfloor \\frac{b}{l} \\right\\rfloor \\le \\left\\lfloor \\frac{a + b}{l} \\right\\rfloor \\le \\left\\lfloor \\frac{x - l}{l} \\right\\rfloor = \\left\\lfloor \\frac{x}{l} \\right\\rfloor - 1$",
    "code": "from sys import setrecursionlimit\nimport threading\n\ndef main():\n    n, l, r = map(int, input().split())\n\n    g = [[] for i in range(0, n)]\n    for i in range(0, n):\n        a, b = map(int, input().split())\n        a -= 1\n        b -= 1\n        g[a].append(b)\n        g[b].append(a)\n\n    res = 0\n    used = [False for i in range(0, n)]\n\n    def dfs(v):\n        used[v] = True\n        size = 1\n        for to in g[v]:\n            if not used[to]:\n                size += dfs(to)\n        return size\n\n    for i in range(0, n):\n        if not used[i]:\n            size = dfs(i)\n            if size <= l + r - 1:\n                res ^= size // l\n\n    if res:\n        print(\"Alice\")\n    else:\n        print(\"Bob\")\n\nsetrecursionlimit(10 ** 9)\nthreading.stack_size(2 ** 27)\nthread = threading.Thread(target=main)\nthread.start()",
    "tags": [
      "brute force",
      "dp",
      "games",
      "graphs",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1823",
    "index": "F",
    "title": "Random Walk",
    "statement": "You are given a tree consisting of $n$ vertices and $n - 1$ edges, and each vertex $v$ has a counter $c(v)$ assigned to it.\n\nInitially, there is a chip placed at vertex $s$ and all counters, except $c(s)$, are set to $0$; $c(s)$ is set to $1$.\n\nYour goal is to place the chip at vertex $t$. You can achieve it by a series of moves. Suppose right now the chip is placed at the vertex $v$. In one move, you do the following:\n\n- choose one of neighbors $to$ of vertex $v$ \\textbf{uniformly at random} ($to$ is neighbor of $v$ if and only if there is an edge $\\{v, to\\}$ in the tree);\n- move the chip to vertex $to$ and increase $c(to)$ by $1$;\n\nYou'll repeat the move above until you reach the vertex $t$.\n\nFor each vertex $v$ calculate the expected value of $c(v)$ modulo $998\\,244\\,353$.",
    "tutorial": "Let $deg(v)$ be the number of neighbors of vertex $v$. Let's fix a vertex $v$ and its neighboring vertices $c_1, \\dots, c_{deg(v)}$. According to the linearity of the expected values: $e_v = \\sum_{u \\in \\{c_1, \\dots, c_{deg(v)}\\}} \\frac{e_u}{deg(u)}$ Solution by Igor_Parfenov: Let's solve the subproblem: given a bamboo with vertices numbered in order from $1$ to $n$, and $s = 1$ and $t = n$. It is easy to see that the equation is satisfied by the expected values $\\{n - 1, 2 \\cdot (n - 2), 2 \\cdot (n - 3), \\dots , 6, 4, 2, 1\\}$. Now let's solve the problem. Consider the path from $s$ to $t$ (it is the only one in the tree). The chip must go through it, but at the vertices of the path, it can go to third-party vertices. Let us represent a tree as non-intersecting trees whose roots are vertices lying on the path from $s$ to $t$, and all other vertices do not lie on this path. Let's place the numbers $\\{n - 1, n - 2, \\dots, 2, 1, 0\\}$ at the vertices of the path. Let's now fix a tree rooted at vertex $v$ in the path, and let its number be equal to $x$. Then we can see that the equation is satisfied by the values of the mathematical expectation $e_u = x \\cdot deg(u)$. Separately, you need to make $e_t = 1$. Solution by adedalic: Let's take a path from $s$ to $t$ and call it $r_0, r_1, \\dots, r_k$, where $r_0 = s$ and $r_k = t$. Now we will assume that each of the vertices $r_i$ form its own rooted subtree. Consider a leaf $v$ in an arbitrary subtree: $e_v = \\frac{1}{deg(p)} e_p$, where $p$ is the ancestor of $v$. Now, by induction on the subtree size, we prove that for any vertex $v$ in any subtree $r_i$ the expected value is $e_v = \\frac{deg(v)}{deg(p)} e_p$. For the leafs, it's obvious. Further, by the inductive hypothesis: $e_v = \\sum_{to \\neq p}{\\frac{1}{deg(to)} e_{to}} + \\frac{1}{deg(p)} e_p = \\sum_{to \\neq p}{\\frac{deg(to)}{deg(to) \\cdot deg(v)} e_v} + \\frac{1}{deg(p)} e_p = \\frac{deg(v) - 1}{deg(v)} e_v + \\frac{1}{deg(p)} e_p$ $\\frac{1}{deg(v)} e_v = \\frac{1}{deg(p)} e_p \\leftrightarrow e_v = \\frac{deg(v)}{deg(p)} e_p$ Now consider the vertices on the path: $e_{r_0} = 1 + \\sum_{to \\neq r_1}{\\frac{1}{deg(to)} e_{to}} + \\frac{1}{deg(r_1)} e_{r_1} = 1 + \\frac{deg(r_0) - 1}{deg(r_0)} e_{r_0} + \\frac{1}{deg(r_1)} e_{r_1}$ $e_{r_0} = deg(r_0) \\left( 1 + \\frac{1}{deg(r_1)} e_{r_1} \\right)$ $e_{r_1} = \\frac{1}{deg(r_0)} e_{r_0} + \\sum_{to \\neq r_0; to \\neq r_2}{\\frac{1}{deg(to)} e_{to}} + \\frac{1}{deg(r_2)} e_{r_2} = \\left( 1 + \\frac{1}{deg(r_1)} e_{r_1} \\right) + \\frac{deg(r_1) - 2}{deg(r_1)} e_{r_1} + \\frac{1}{deg(r_2)} e_{r_2}$ $e_{r_1} = deg(r_1) \\left( 1 + \\frac{1}{deg(r_2)} e_{r_2} \\right)$ $e_{r_{k-1}} = deg(r_{k-1}) \\left( 1 + 0 \\right) = deg(r_{k - 1})$ $e_{r_{k-2}} = deg(r_{k-2}) \\left( 1 + \\frac{1}{deg(r_{k-1})} e_{r_{k-1}} \\right) = deg(r_{k-2}) (1 + 1) = 2 \\cdot deg(r_{k-2})$ $e_{r_{k-3}} = deg(r_{k-2}) \\left( 1 + 2 \\right) = 3 \\cdot deg(r_{k-2})$ $e_{r_{k-i}} = i \\cdot deg(r_{k-i})$ That's all. For any vertex $v$ in the subtree of $r_i$ we get $e_v = (k - i) \\cdot deg(v)$.",
    "code": "from sys import setrecursionlimit\nimport threading\n \nmod = 998244353\n \ndef main():\n    n, s, t = map(int, input().split())\n    s -= 1\n    t -= 1\n    \n    g = [[] for i in range(0, n)]\n    previous = [-1 for i in range(0, n)]\n    inPath = [False for i in range(0, n)]\n    res = [0 for i in range(0, n)]\n    \n    for i in range(0, n - 1):\n        a, b = map(int, input().split())\n        a -= 1\n        b -= 1\n        g[a].append(b)\n        g[b].append(a)\n    \n    def dfs(v, p):\n        for to in g[v]:\n            if to == p:\n                continue\n            previous[to] = v\n            dfs(to, v)\n    \n    def dfs2(v, p, k):\n        res[v] = k * len(g[v])\n        for to in g[v]:\n            if to == p:\n                continue\n            dfs2(to, v, k)\n    \n    dfs(s, -1)\n    \n    ptr = t\n    inPath[t] = True\n    \n    while ptr != s:\n        res[previous[ptr]] = res[ptr] + 2\n        ptr = previous[ptr]\n        inPath[ptr] = True\n    \n    for v in range(0, n):\n        if inPath[v]:\n            res[v] = res[v] // 2 * len(g[v])\n            for to in g[v]:\n                if not inPath[to]:\n                    dfs2(to, v, res[v] // len(g[v]))\n    \n    res[t] += 1\n    \n    for i in res:\n        print(i % mod, end = ' ')\n    print(\"\")\n \nsetrecursionlimit(10 ** 9)\nthreading.stack_size(2 ** 27)\nthread = threading.Thread(target=main)\nthread.start()",
    "tags": [
      "dp",
      "graphs",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1824",
    "index": "A",
    "title": "LuoTianyi and the Show",
    "statement": "There are $n$ people taking part in a show about VOCALOID. They will sit in the row of seats, numbered $1$ to $m$ from left to right.\n\nThe $n$ people come and sit in order. Each person occupies a seat in one of three ways:\n\n- Sit in the seat next to the left of the leftmost person who is already sitting, or if seat $1$ is taken, then leave the show. If there is no one currently sitting, sit in seat $m$.\n- Sit in the seat next to the right of the rightmost person who is already sitting, or if seat $m$ is taken, then leave the show. If there is no one currently sitting, sit in seat $1$.\n- Sit in the seat numbered $x_i$. If this seat is taken, then leave the show.\n\nNow you want to know what is the maximum number of people that can take a seat, if you can let people into the show in any order?",
    "tutorial": "First we can notice that, if someone with a specific favourite seat(i.e. not $-1$ nor $-2$) has got his seat taken by a $-1$ guy or a $-2$ guy, it's better to let the first man go first, and the $-1$ or $-2$ one go after him. Now, we know it's better to make those with a favourite seat go in first. After they have seated, now we consider filling the space between them with $-1$ and $-2$. It's easy to notice that we can find two non-overlapping prefix and suffix, and fill the blank seats in the prefix with $-1$, and the blanks in the suffix with $-2$. We now only need to find the answer greedily for each division point between the prefix and the suffix. The time complexity is $O(n)$.",
    "code": "// Problem: C. LuoTianyi and the Theater\n// Contest: Codeforces - test vocaloid cf round\n// URL: https://codeforces.com/gym/394370/problem/C\n// Memory Limit: 256 MB\n// Time Limit: 1000 ms\n// \n// Powered by CP Editor (https://cpeditor.org)\n\n//By: OIer rui_er\n#include <bits/stdc++.h>\n#define rep(x,y,z) for(int x=(y);x<=(z);x++)\n#define per(x,y,z) for(int x=(y);x>=(z);x--)\n#define debug(format...) fprintf(stderr, format)\n#define fileIO(s) do{freopen(s\".in\",\"r\",stdin);freopen(s\".out\",\"w\",stdout);}while(false)\nusing namespace std;\ntypedef long long ll;\nconst int N = 2e5+5;\n\nint T, n, m, a[N], buc[N];\ntemplate<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}\ntemplate<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}\n\nint main() {\n\tfor(scanf(\"%d\", &T); T; T--) {\n\t\tscanf(\"%d%d\", &n, &m);\n\t\trep(i, 1, n) scanf(\"%d\", &a[i]);\n\t\tint cntL = 0, cntR = 0;\n\t\trep(i, 1, n) {\n\t\t\tif(a[i] == -1) ++cntL;\n\t\t\telse if(a[i] == -2) ++cntR;\n\t\t\telse ++buc[a[i]];\n\t\t}\n\t\tint nowL = 0, nowR = 0, vis = 0;\n\t\trep(i, 1, m) {\n\t\t\tif(buc[i]) ++vis;\n\t\t\telse ++nowR;\n\t\t}\n\t\tint ans = max(cntL, cntR) + vis;\n\t\trep(i, 1, m) {\n\t\t\t// printf(\"%d : %d %d; %d %d; %d\n\", i, cntL, nowL, cntR, nowR, vis);\n\t\t\tif(buc[i]) chkmax(ans, min(cntL, nowL) + min(cntR, nowR) + vis);\n\t\t\telse ++nowL, --nowR;\n\t\t\t// printf(\" -> %d\n\", ans);\n\t\t}\n\t\tchkmin(ans, m);\n\t\tprintf(\"%d\n\", ans);\n\t\trep(i, 1, m) buc[i] = 0;\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1824",
    "index": "B2",
    "title": "LuoTianyi and the Floating Islands (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $k\\le n$. You can make hacks only if both versions of the problem are solved.}\n\n\\begin{center}\n{\\small Chtholly and the floating islands.}\n\\end{center}\n\nLuoTianyi now lives in a world with $n$ floating islands. The floating islands are connected by $n-1$ undirected air routes, and any two of them can reach each other by passing the routes. That means, the $n$ floating islands form a tree.\n\nOne day, LuoTianyi wants to meet her friends: Chtholly, Nephren, William, .... Totally, she wants to meet $k$ people. She doesn't know the exact positions of them, but she knows that they are in \\textbf{pairwise distinct} islands. She define an island is good if and only if the sum of the distances$^{\\dagger}$ from it to the islands with $k$ people is the minimal among all the $n$ islands.\n\nNow, LuoTianyi wants to know that, if the $k$ people are randomly set in $k$ distinct of the $n$ islands, then what is the expect number of the good islands? You just need to tell her the expect number modulo $10^9+7$.\n\n$^{\\dagger}$The distance between two islands is the minimum number of air routes you need to take to get from one island to the other.",
    "tutorial": "Call a node special if there is a person in it. When $k$ is odd, we find that there is only one node satisfying the conditions. $\\bf{Proof}.$ Assume distinct node $x$ and node $y$ are good nodes. Let $x$ be the root of the tree. Define $s_i$ as the number of special nodes in subtree $i$. Think about the process we move from $x$ to $y$. If we try to move the chosen node from its father to $i$, the variation of cost is $k-2s_i$. When move from $x$ to its son $i$ which $s_i$ is maximal, $k-2s_i\\geq 0$ is held (Otherwise, $x$ isn't a good node). And we can get $k-2s_i>0$ further because $k$ is odd and $2s_i$ is even. Since $\\min_{1\\leq j\\leq n}{k-2s_j}=k-2s_i$, we find $k-2s_j>0$ for all $j$. So $y$ can't be good node. Then think about the situation that $k$ is even. Choose a node as root arbitrarily. With the same method, we find that good nodes satisfy $2s_i=k$. It's also sufficient. Define $p_i$ as the possibility that $s_i=\\frac{k}{2}$, then the answer is $1+\\sum_{i=1}^{n}p_i$. Define $S_i$ as the size of subtree $i$. When $s_i=\\frac{k}{2}$, there are $\\frac{k}{2}$ special nodes in subtree $i$ and $\\frac{k}{2}$ in the other part. The number of ways to place special nodes is $\\binom{n}{k}$, and $\\binom{S_i}{\\frac{k}{2}}\\binom{n-S_i}{\\frac{k}{2}}$ of them satisfying the condition. So $p_i=\\dfrac{\\binom{S_i}{\\frac{k}{2}}\\binom{n-S_i}{\\frac{k}{2}}}{\\binom{n}{k}}$. So we can solve the problem in $O(n)$.",
    "code": "//Was yea ra,rra yea ra synk sphilar yor en me exec hymme METAFALICA waath!\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"unroll-loops\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native\")\n#include<bits/stdc++.h>\nusing namespace std;\n#define rg register\n#define ll long long\n#define ull unsigned ll\n#define lowbit(x) (x&(-x))\n#define djq 1000000007\nconst double eps=1e-10;\nconst short sint=0x3f3f;\nconst int inf=0x3f3f3f3f;\nconst ll linf=0x3f3f3f3f3f3f3f3f;\nconst double alpha=0.73;\nconst double PI=acos(-1);\ninline void file(){\n\tfreopen(\"1.in\",\"r\",stdin);\n\tfreopen(\"1.out\",\"w\",stdout);\n}\nchar buf[1<<21],*p1=buf,*p2=buf;\ninline int getc(){\n    return p1==p2&&(p2=(p1=buf)+fread(buf,1,(1<<20)+5,stdin),p1==p2)?EOF:*p1++;\n}\n//#define getc getchar\ninline ll read(){\n\trg ll ret=0,f=0;char ch=getc();\n    while(!isdigit(ch)){if(ch==EOF)exit(0);if(ch=='-')f=1;ch=getc();}\n    while(isdigit(ch)){ret=ret*10+ch-48;ch=getc();}\n    return f?-ret:ret;\n}\ninline void rdstr(char* s){\n\tchar ch=getc();\n\twhile(ch<33||ch>126) ch=getc();\n\twhile(ch>=33&&ch<=126) (*s++)=ch,ch=getc();\n}\n#define ep emplace\n#define epb emplace_back\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\n#define it iterator\n#define mkp make_pair\n#define naive return 0*puts(\"Yes\")\n#define angry return 0*puts(\"No\")\n#define fls fflush(stdout)\n#define rep(i,a) for(rg int i=1;i<=a;++i)\n#define per(i,a) for(rg int i=a;i;--i)\n#define rep0(i,a) for(rg int i=0;i<=a;++i)\n#define per0(i,a) for(rg int i=a;~i;--i)\n#define szf sizeof\ntypedef vector<int> vec;\ntypedef pair<int,int> pii;\nstruct point{ int x,y; point(int x=0,int y=0):x(x),y(y) {} inline bool operator<(const point& T)const{ return x^T.x?x<T.x:y<T.y; }; };\ninline int ksm(int base,int p){int ret=1;while(p){if(p&1)ret=1ll*ret*base%djq;base=1ll*base*base%djq,p>>=1;}return ret;}\ninline void pls(int& x,const int k){ x=(x+k>=djq?x+k-djq:x+k); }\ninline int add(const int a,const int b){ return a+b>=djq?a+b-djq:a+b; }\ninline void sub(int& x,const int k){ x=(x-k<0?x-k+djq:x-k); }\ninline int inc(const int a,const int b){ return a<b?a-b+djq:a-b; }\ninline void ckmn(int& x,const int k){ x=(k<x?k:x); }\ninline void ckmx(int& x,const int k){ x=(k>x?k:x); }\n \nconst int lim=2e5;\nint fac[200005],ifac[200005];\ninline int C(int n,int m){ return (m<=n&&m>=0&&n>=0)?1ll*fac[n]*ifac[m]%djq*ifac[n-m]%djq:0; }\nvoid initC(){\n\tfac[0]=ifac[0]=1;\n\trep(i,lim) fac[i]=1ll*fac[i-1]*i%djq;\n\tifac[lim]=ksm(fac[lim],djq-2);\n\tper(i,lim-1) ifac[i]=1ll*ifac[i+1]*(i+1)%djq;\n}\nint n,k,u,v,sz[200005];\nvec e[200005];\nvoid dfs(int x,int fa){\n\tsz[x]=1;\n\tfor(int y:e[x]) if(y^fa) dfs(y,x),sz[x]+=sz[y];\n}\nsigned main(){\n\t//file();\n\tinitC();\n\tn=read(),k=read();\n\trep(i,n-1) u=read(),v=read(),e[u].epb(v),e[v].epb(u);\n\tdfs(1,0);\n\tif(k&1) return 0*puts(\"1\");\n\telse{\n\t\tint ans=0;\n\t\tfor(rg int i=2;i<=n;++i) pls(ans,1ll*C(sz[i],k/2)*C(n-sz[i],k/2)%djq);\n\t\tans=1ll*ans*ksm(C(n,k),djq-2)%djq;\n\t\tpls(ans,1);\n\t\tprintf(\"%d\n\",ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1824",
    "index": "C",
    "title": "LuoTianyi and XOR-Tree",
    "statement": "LuoTianyi gives you a tree with values in its vertices, and the root of the tree is vertex $1$.\n\nIn one operation, you can change the value in one vertex to any non-negative integer.\n\nNow you need to find the minimum number of operations you need to perform to make each path from the root to leaf$^{\\dagger}$ has a bitwise XOR value of zero.\n\n$^{\\dagger}$A leaf in a rooted tree is a vertex that has exactly one neighbor and is not a root.",
    "tutorial": "Hint: Consider a brute force dynamic programming solution and try to optimize it. Denote the minimum number of operations needed to make every path from a leaf inside the subtree of $u$ to the root have the xor value of $w$ as $f_{u,w}$. Observe that for every $u$, there are only $2$ possible different values for $f_{u,w}$. This is because if $f_{u,w_1}-f_{u,w_2}>1$, we can use an operation of xor-ing $a_u$ with $w_1 \\ \\text{xor} \\ w_2$ to make all the xor values from $w_2$ to $w_1$, which takes $f_{u,w_2}+1$ steps instead of $f_{u,w_1}$. Now we only need to calculate $\\text{minn}_u=\\min f_{u,w}$, and the set $S_u$ of $w$ that makes $f_{u,w}$ minimum. We have $\\text{minn}_v=0$ and $S_v={\\text{the xor value from root to v}}$ for leaf $v$. It's trivial to calculate $\\text{minn}_u$. Note that $S_u$ contains of the numbers appearing the most times in the sets of $u$'s son. We can maintain $S_u$ using a map and merging it heuristically. Consider when merging sets into a new set $S'$. If every element of $S'$ appears only once in the original sets, then we keep $S'$ as the result, otherwise, brute force the whole set $S'$ and find the elements appearing the most times. For the second situation, every element's count of appearance is at least halved(those appearing once have $0$ and others have $1$ afterwards), so the number of brute force checking operations is $O(n\\log n)$. The final time complexity is $O(n\\log^2 n)$.",
    "code": "#include<iostream>\n#include<cstdio>\n#include<vector>\n#include<set>\n#include<algorithm>\n#include<map>\nusing namespace std;\nint n,a[100005];\nvector<int> e[100005];\nset<int> s[100005],stmp;\nint ans=0,sid[100005],stp=0;\nbool cmp(int x,int y)\n{\n\treturn (int)s[sid[x]].size()>(int)s[sid[y]].size();\n}\nvoid set_xor(int x,int y)\n{\n\tstmp.clear();\n\tset<int>::iterator it=s[x].begin();\n\twhile(it!=s[x].end())\n\tstmp.insert(y^(*(it++)));\n\ts[x]=stmp;\n\treturn ;\n}\nvoid dfs(int u,int f)\n{\n\tvector<int> v;\n\tfor(int i=0;i<(int)e[u].size();i++)\n\tif(e[u][i]!=f)\n\t{\n\t\tdfs(e[u][i],u);\n\t\tv.push_back(e[u][i]);\n\t}\n\tif((int)v.size()==0)\n\t{\n\t\tsid[u]=(++stp);\n\t\ts[sid[u]].insert(0);\n\t\treturn ;\n\t}\n\tsort(v.begin(),v.end(),cmp);\n\tint hv_tg=a[v[0]];\n\ta[v[0]]=0;\n\ta[u]^=hv_tg;\n\tbool flg=false;\n\tset<int> setchk;\n\tfor(int i=1;i<(int)v.size();i++)\n\t{\n\t\tint x=v[i];\n\t\tset_xor(sid[x],a[x]^hv_tg);\n\t\tset<int>::iterator it=s[sid[x]].begin();\n\t\twhile(it!=s[sid[x]].end())\n\t\t{\n\t\t\tint val=(*it); it++;\n\t\t\tif(s[sid[v[0]]].find(val)!=s[sid[v[0]]].end())\n\t\t\tflg=true;\n\t\t\tif(setchk.find(val)!=setchk.end())\n\t\t\tflg=true;\n\t\t\tsetchk.insert(val);\n\t\t}\n\t}\n\tif(flg==false)\n\t{\n\t\t//cout<<\"Node \"<<u<<\" \"<<(int)v.size()-1<<endl;\n\t\tans+=(int)v.size()-1;\n\t\tfor(int i=1;i<(int)v.size();i++)\n\t\t{\n\t\t\tint x=v[i];\n\t\t\tset<int>::iterator it=s[sid[x]].begin();\n\t\t\twhile(it!=s[sid[x]].end())\n\t\t\ts[sid[v[0]]].insert(*(it++));\n\t\t}\n\t\tsid[u]=sid[v[0]];\n\t\treturn ;\n\t}\n\tmap<int,int> h;\n\tfor(int i=0;i<(int)v.size();i++)\n\t{\n\t\tint x=v[i];\n\t\tset<int>::iterator it=s[sid[x]].begin();\n\t\twhile(it!=s[sid[x]].end())\n\t\th[*(it++)]++;\n\t}\n\tsid[u]=(++stp);\n\tint mx_app=0;\n\tmap<int,int>::iterator it=h.begin();\n\twhile(it!=h.end())\n\t{\n\t\tpair<int,int> p=(*it);\n\t\tif(p.second>mx_app)\n\t\t{\n\t\t\tmx_app=p.second;\n\t\t\ts[sid[u]].clear();\n\t\t}\n\t\tif(p.second==mx_app)\n\t\ts[sid[u]].insert(p.first);\n\t\tit++;\n\t}\n\tans+=(int)v.size()-mx_app;\n\treturn ;\n}\nint main()\n{\n\tscanf(\"%d\",&n);\n\tfor(int i=1;i<=n;i++)\n\tscanf(\"%d\",&a[i]);\n\tfor(int i=1;i<n;i++)\n\t{\n\t\tint u,v;\n\t\tscanf(\"%d%d\",&u,&v);\n\t\te[u].push_back(v);\n\t\te[v].push_back(u);\n\t}\n\tdfs(1,0);\n\tset_xor(sid[1],a[1]);\n\tif(s[sid[1]].find(0)==s[sid[1]].end())\n\tans++;\n\tprintf(\"%d\n\",ans);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "greedy",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1824",
    "index": "D",
    "title": "LuoTianyi and the Function",
    "statement": "LuoTianyi gives you an array $a$ of $n$ integers and the index begins from $1$.\n\nDefine $g(i,j)$ as follows:\n\n- $g(i,j)$ is the largest integer $x$ that satisfies $\\{a_p:i\\le p\\le j\\}\\subseteq\\{a_q:x\\le q\\le j\\}$ while $i \\le j$;\n- and $g(i,j)=0$ while $i>j$.\n\nThere are $q$ queries. For each query you are given four integers $l,r,x,y$, you need to calculate $\\sum\\limits_{i=l}^{r}\\sum\\limits_{j=x}^{y}g(i,j)$.",
    "tutorial": "Consider an alternative method of calculating $g$. Notice that $g(i,j)$ is the minimum of the last appearing position of all colors(let's call different values of $a_x$ colors for short) in the interval $[i,j]$. Consider the sequence from $a_n$ to $a_1$. Adding $a_i$ to the front of the sequence only affects the values $g(i,x)(i\\leq x<\\text{nxt}_i)$, where $\\text{nxt}_i$ is the next position after $i$ having the same $a$ value as it. Or it's to say to modify $g$ values in the submatrix of $[(1,i),(i,\\text{nxt}_i-1)]$ to $i$, which can be done in $O(n\\log^2 n)$, but it's not fast enough. Because the queries happen after all modifications take place, you can store the queries offline, and calculate a submatrix using $4$ queries of submatrixes having $(1,1)$ as the upper-left corner. Now we need to maintain a data structure that can: 1. set all values in an interval as a same value $x$, 2. query the history sum(sum of values on all previous editions). We can maintain the segments of adjacent positions with the same values, and turn the modification into 'range add' for a segment. An operation makes at most $O(1)$ new segments, and now there's only $O(n)$ range add modifications and $O(m)$ range history sum queries, now the problem can be solved in $O(n\\log n)$ time complexity with segment tree.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define N 1000005\n#define L long long\nint n,m,stt,a[N],nxt[N],siz[N],top,ll[N],rr[N],xx[N],yy[N];\nL out[N];\nstruct ds{\n\tL t[2][N],ta;\n\tinline void add(int op,int x,L v){while(x<=n) t[op][x]+=v,x+=(x&-x);}\n\tinline L ask(int op,int x){ta=0;while(x) ta+=t[op][x],x^=(x&-x);return ta;}\n\tvoid Add(int l,int r,L v){add(0,l,v),add(0,r+1,-v),add(1,l,v*(l-1)),add(1,r+1,-v*r);}\n\tL Ask(int l,int r){return r*ask(0,r)-(l-1)*ask(0,l-1)-ask(1,r)+ask(1,l-1);}\n} b1,b2;\nstruct node{int l,r,v;} st[N];\nstruct query{int id,op;} pl[2*N]; \nquery *v[N];\nsigned main(){\n\tios::sync_with_stdio(0),cin.tie(0),cout.tie(0);\n\tcin>>n>>m;\n\tfor(int i=1;i<=n;++i) cin>>a[i],siz[a[i]]=n+1;\n\tfor(int i=n;i>=1;--i) nxt[i]=siz[a[i]],siz[a[i]]=i;\n\tmemset(siz,0,sizeof siz);\n\tfor(int i=1;i<=m;++i){\n\t\tcin>>ll[i]>>rr[i]>>xx[i]>>yy[i];\n\t\tsiz[ll[i]]++,siz[rr[i]+1]++;\n\t}\n\tfor(int i=1;i<=n+1;++i) v[i]=pl+top,top+=siz[i];\n\tmemset(siz,0,sizeof siz);\n\tfor(int i=1;i<=m;++i) v[ll[i]][siz[ll[i]]++]=(query){i,1},v[rr[i]+1][siz[rr[i]+1]++]=(query){i,-1};\n\tfor(int i=n,l,r;i>=1;--i){\n\t\tl=i,r=nxt[i]-1;\n\t\twhile(stt&&r>=st[stt].r){\n\t\t\tnode &nw=st[stt];\n\t\t\tb1.Add(nw.l,nw.r,1ll*-i*nw.v),b2.Add(nw.l,nw.r,-nw.v);\n\t\t\tstt--;\n\t\t}\n\t\tif(stt&&st[stt].l<=r){\n\t\t\tnode &nw=st[stt];\n\t\t\tb1.Add(nw.l,r,1ll*-i*nw.v),b2.Add(nw.l,r,-nw.v);\n\t\t\tnw.l=r+1;\n\t\t}\n\t\tst[++stt]=(node){l,r,i};\n\t\tb1.Add(l,r,1ll*i*i),b2.Add(l,r,i);\n\t\tfor(int j=0;j<siz[i];++j) out[v[i][j].id]+=1ll*v[i][j].op*(b1.Ask(xx[v[i][j].id],yy[v[i][j].id])-1ll*(i-1)*b2.Ask(xx[v[i][j].id],yy[v[i][j].id]));\n\t}\n\tfor(int i=1;i<=m;++i) cout<<out[i]<<'\n';\n}",
    "tags": [
      "data structures"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1824",
    "index": "E",
    "title": "LuoTianyi and Cartridge",
    "statement": "LuoTianyi is watching the anime Made in Abyss. She finds that making a Cartridge is interesting. To describe the process of making a Cartridge more clearly, she abstracts the original problem and gives you the following problem.\n\nYou are given a tree $T$ consisting of $n$ vertices. Each vertex has values $a_i$ and $b_i$ and each edge has values $c_j$ and $d_j$.\n\nNow you are aim to build a \\textbf{tree} $T'$ as follows:\n\n- First, select $p$ vertices from $T$ ($p$ is a number chosen by yourself) as the vertex set $S'$ of $T'$.\n- Next, select $p-1$ edges from $T$ one by one (you cannot select one edge more than once).\n- May you have chosen the $j$-th edge connects vertices $x_j$ and $y_j$ with values $(c_j,d_j)$, then you can choose two vertices $u$ and $v$ in $S'$ that satisfy the edge $(x_j,y_j)$ is contained in the simple path from $u$ to $v$ in $T$, and link $u$ and $v$ in $T'$ by the edge with values $(c_j,d_j)$ ($u$ and $v$ shouldn't be contained in one connected component before in $T'$).\n\n\\begin{center}\n{\\small A tree with three vertices, $\\min(A,C)=1,B+D=7$, the cost is $7$.}\n\\end{center}\n\n\\begin{center}\n{\\small Selected vertices $2$ and $3$ as $S'$, used the edge $(1,2)$ with $c_j = 2$ and $d_j = 1$ to link this vertices, now $\\min(A,C)=2,B+D=4$, the cost is $8$.}\n\\end{center}\n\nLet $A$ be the minimum of values $a_i$ in $T'$ and $C$ be the minimum of values $c_i$ in $T'$. Let $B$ be the sum of $b_i$ in $T'$ and $D$ be the sum of values $d_i$ in $T'$. Let $\\min(A, C) \\cdot (B + D)$ be the cost of $T'$. You need to find the maximum possible cost of $T'$.",
    "tutorial": "Consider finding the maximum value of $B+D$ for every $\\min(A,C)$. Denote $\\min(A,C)$ as $x$. We call a vertex $u$ satisfying $a_u\\geq x$ or an edge satisfying $c_e\\geq x$ optional. Denote as $V$ the optional vertex set and as $E_0$ the optional edge set. Firstly, if all optional vertices are on the same side of an edge, this edge mustn't be chosen. Delete these edges from $E_0$ and we get the edge set $E$. Formally, an edge $e$ is in $E$ if and only if $c_e\\geq x$ and there exists $u,v$ so that $e$ is on the path between them. $\\bf{Lemma.}$ There exists an optimal $T_{\\text{ans}}=(V_\\text{ans},E_\\text{ans})$ that either $V=V_\\text{ans}$ or $E=E_\\text{ans}$. $\\bf{Proof.}$ Assume an optimal $T'=(V',E')$ with $V'\\neq V,E'\\neq E$. Choose an edge $e$ that is in $E$ but not in $E'$. Because $V'\\neq V$, there must exist two vertices $u,v$ on different sides of edge $e$ and $u\\in V',v\\notin V'$. Consider adding the edge $e$ and the vertex $v$ into our chosen tree, the resulting graph is obviously a tree. Note that $b_v,d_e\\geq 0$, so the resulting choice is no worse than $T'$. When we delete the edges in $E$ from the original tree, we get some connected components. Shrink one component into a single vertex to get $V'$, and then for all edges $(u,v)\\in E$, connect $u$'s and $v$'s component together in the new graph and get $E'$. Obviously, the new graph $T'=(V',E')$ is a tree. For any leaf vertex $u'$ on the new tree $T'$, there must exist a vertex $u$ in the component $u'$ that is chosen, otherwise the edge connecting to $u'$, let's say, $e'$ is not chosen either. Adding $u$ and $e'$ into our answer tree achieves a better answer. Assume that now we have chosen a vertex $u$ for every leaf $u'$, denote the set of chosen vertices as $V_x$. Consider an arbitary choice of vertex for components $V_c$ and edge choice $E_c$ satisfying $V_x\\subseteq V_c\\subseteq V,E_c\\subseteq E,|V_c|-1=|E_c|$. It's easy to prove that the choice is a legal answer, given the fact that every $e\\in E_c$ has at least one leaf component on each side and every leaf component contains a chosen vertex. Reconsider the lemma, and we can get a solution for a fixed $x$: Find $V,E$. Calculate the components and get $V',E'$. Find the vertex with the maximum $b$ in every leaf-component in $V'$ and get $V_x$. Let $m$ be $\\min(|V|,|E|+1)$, and $m'$ be $|V_x|$. Choose the vertices in $V\\setminus V_x$ with the first $m-m'$ largest $b$, and the edges in $E$ with the first $m-1$ largest $d$ and get the answer. Consider the process when $x$ gets larger, the sets $V,E$ get smaller and smaller while the components merge into each other. We use segment trees to maintain the $b$ value of the vertices and the $d$ value of the edges, when merging two components, we simply merge the two segment trees. The final time complexity is $O(n\\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int,int> pii;\nconst int MAXN = 2e5 + 5;\nconst int inf = 0x3f3f3f3f;\nconst ll linf = 0x3f3f3f3f3f3f3f3f;\n \nstruct Segment_Tree\n{\n\tstatic const int N = 1<<18, SIZ = N * 2 + 5;\n\tpii mx[SIZ];\n\tSegment_Tree(void){ clear();}\n\tvoid clear(void)\n\t{\n\t\tfor(int i=0; i<N; ++i)\n\t\t\tmx[N+i] = {-inf, i};\n\t\tfor(int i=N-1; i>=1; --i)\n\t\t\tmx[i] = max(mx[i<<1], mx[i<<1|1]);\n\t}\n\tvoid set(int i,int k)\n\t{\n\t\ti += N;\n\t\tmx[i].first = k;\n\t\twhile((i >>= 1) != 0)\n\t\t\tmx[i] = max(mx[i<<1], mx[i<<1|1]);\n\t}\n\tpii query(int l,int r)\n\t{\n\t\tpii res = {-inf, -inf};\n\t\tfor(l+=N-1, r+=N+1; l^r^1; l>>=1, r>>=1)\n\t\t{\n\t\t\tif(~l&1) res = max(res, mx[l^1]);\n\t\t\tif( r&1) res = max(res, mx[r^1]);\n\t\t}\n\t\treturn res;\n\t}\n}tree;\n \nstruct DS\n{\n\tmultiset<int> l,r;\n\tll sum;\n\tDS(void){ clear();}\n\tvoid clear(void){ l.clear(); r.clear(); sum = 0;}\n\tvoid insert(int x)\n\t{\n\t\tif(!r.size() || x < *r.begin()) l.emplace(x);\n\t\telse r.emplace(x), sum += x;\n\t}\n\tvoid erase(int x)\n\t{\n\t\tif(l.find(x) != l.end())\n\t\t\tl.erase(l.find(x));\n\t\telse\n\t\t\tr.erase(r.find(x)), sum -= x;\n\t}\n\tint size(void) const\n\t{\n\t\treturn (int)l.size() + (int)r.size();\n\t}\n\tll query(int k)\n\t{\n\t\twhile((int)r.size() > k)\n\t\t{\n\t\t\tint x = *r.begin(); r.erase(r.begin()); sum -= x;\n\t\t\tl.emplace(x);\n\t\t}\n\t\twhile((int)r.size() < k && l.size())\n\t\t{\n\t\t\tint x = *l.rbegin(); l.erase(prev(l.end()));\n\t\t\tr.emplace(x); sum += x;\n\t\t}\n\t\treturn sum;\n\t}\n};\n \narray<int,2> p[MAXN];\narray<int,4> es[MAXN];\n \nvector<pii> g[MAXN];\n \nint anc[MAXN], ancid[MAXN];\nvoid dfs_tree(int u,int fa)\n{\n\tfor(auto it: g[u]) if(it.first != fa)\n\t{\n\t\tint v = it.first;\n\t\tanc[v] = u;\n\t\tancid[v] = it.second;\n\t\tdfs_tree(v,u);\n\t}\n}\n \nint dfnl[MAXN], dfnr[MAXN], seq[MAXN], curdfn;\nvoid dfs_dfn(int u,int fa)\n{\n\tdfnl[u] = ++curdfn; seq[curdfn] = u;\n\tfor(auto it: g[u]) if(it.first != fa)\n\t\tdfs_dfn(it.first, u);\n\tdfnr[u] = curdfn;\n}\n \nint main(void)\n{\n\tint n;\n\tscanf(\"%d\",&n);\n\tfor(int i=1; i<=n; ++i)\n\t\tscanf(\"%d\",&p[i][0]);\n\tfor(int i=1; i<=n; ++i)\n\t\tscanf(\"%d\",&p[i][1]);\n\tfor(int i=1; i<n; ++i)\n\t\tfor(int &t: es[i])\n\t\t\tscanf(\"%d\",&t);\n\t\n\tvector<pii> vec;\n\tfor(int i=1; i<=n; ++i)\n\t\tvec.emplace_back(p[i][0], i << 1 | 0);\n\tfor(int i=1; i<n; ++i)\n\t{\n\t\tvec.emplace_back(es[i][2], i << 1 | 1);\n\t\t\n\t\tint u = es[i][0], v = es[i][1];\n\t\tg[u].emplace_back(v,i);\n\t\tg[v].emplace_back(u,i);\n\t}\n\t\n\tsort(vec.begin(), vec.end());\n\treverse(vec.begin(), vec.end());\n\t\n\tll ans = 0;\n\tvector<pii> eff;\n\t\n\tint cntp = 0, cnte = 0;\n\tll sump = 0, sume = 0;\n\tDS ds;\n\t\n\t// Part 1\n\t{\n\t\tint rt;\n\t\t{\n\t\t\tint i = 0;\n\t\t\twhile(vec[i].second % 2 == 1) ++i;\n\t\t\trt = vec[i].second >> 1;\n\t\t}\n\t\t\n\t\tanc[rt] = 0; ancid[rt] = 0;\n\t\tdfs_tree(rt,0);\n\t\t\n\t\tstatic int tage[MAXN];\n\t\t\n\t\tauto insert_edge = [&] (int i,int curval)\n\t\t{\n\t\t\tif(tage[i] != 3) return;\n//\t\t\tprintf(\"insert_edge %d\n\",i);\n\t\t\teff.emplace_back(curval, i << 1 | 1);\n\t\t\tds.insert(es[i][3]);\n\t\t\tcnte += 1;\n\t\t\tsume += es[i][3];\n\t\t};\n\t\tauto insert_node = [&] (int u,int curval)\n\t\t{\n//\t\t\tprintf(\"insert_node %d\n\",u);\n\t\t\teff.emplace_back(curval, u << 1 | 0);\n\t\t\tcntp += 1;\n\t\t\tsump += p[u][1];\n\t\t\t\n\t\t\twhile(u != rt && (tage[ancid[u]] & 1) == 0)\n\t\t\t{\n\t\t\t\ttage[ancid[u]] |= 1;\n\t\t\t\tinsert_edge(ancid[u], curval);\n\t\t\t\tu = anc[u];\n\t\t\t}\n\t\t};\n\t\t\n\t\tfor(auto t: vec)\n\t\t{\n\t\t\tint i = t.second >> 1, type = t.second & 1;\n\t\t\tif(type == 0)\n\t\t\t{\n\t\t\t\tinsert_node(i, t.first);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttage[i] |= 2;\n\t\t\t\tinsert_edge(i, t.first);\n\t\t\t}\n\t\t\t\n\t\t\tif(cntp >= 1 && cnte >= cntp - 1)\n\t\t\t{\n\t\t\t\tll cur = sump + ds.query(cntp - 1);\n\t\t\t\tans = max(ans, t.first * cur);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Part 2\n\t{\n\t\tint rtid, rt1, rt2;\n\t\t{\n\t\t\tint i = 0;\n\t\t\twhile(eff[i].second % 2 == 0) ++i;\n\t\t\trtid = eff[i].second >> 1;\n\t\t\trt1 = es[rtid][0];\n\t\t\trt2 = es[rtid][1];\n\t\t}\n\t\t\n\t\tdfs_dfn(rt1,rt2);\n\t\tdfs_dfn(rt2,rt1);\n\t\t\n\t\tcntp = cnte = sump = sume = 0;\n\t\tds.clear();\n\t\tmap<int,pii> seg;\n\t\tll has = 0;\n\t\t\n\t\tauto insert_seg = [&] (int l,int r)\n\t\t{\n\t\t\tauto it = seg.lower_bound(l);\n\t\t\tif(it != seg.end() && it -> second.first <= r) return;\n\t\t\tif(it != seg.begin())\n\t\t\t{\n\t\t\t\t--it;\n\t\t\t\tif(it -> second.first >= l)\n\t\t\t\t{\n\t\t\t\t\tint j = it -> second.second;\n\t\t\t\t\tseg.erase(it);\n\t\t\t\t\tds.insert(p[j][1]);\n\t\t\t\t\ttree.set(dfnl[j], p[j][1]);\n\t\t\t\t\thas -= p[j][1];\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tassert(tree.query(l,r).second != -inf);\n\t\t\tint j = seq[ tree.query(l,r).second ];\n\t\t\tds.erase(p[j][1]);\n\t\t\ttree.set(dfnl[j], -inf);\n\t\t\thas += p[j][1];\n\t\t\tseg[l] = {r, j};\n\t\t};\n\t\t\n\t\tfor(auto t: eff)\n\t\t{\n\t\t\tint i = t.second >> 1, type = t.second & 1;\n\t\t\tif(type == 0)\n\t\t\t{\n\t\t\t\tbool flag = [&] (void) -> bool\n\t\t\t\t{\n\t\t\t\t\tauto it = seg.upper_bound(dfnl[i]);\n\t\t\t\t\tif(it == seg.begin()) return 0;\n\t\t\t\t\t\n\t\t\t\t\t--it;\n\t\t\t\t\tif(it -> second.first < dfnl[i]) return 0;\n\t\t\t\t\t\n\t\t\t\t\tint j = it -> second.second;\n\t\t\t\t\tif(p[j][1] >= p[i][1]) return 0;\n\t\t\t\t\t\n\t\t\t\t\tds.insert(p[j][1]);\n\t\t\t\t\ttree.set(dfnl[j], p[j][1]);\n\t\t\t\t\tit -> second.second = i;\n\t\t\t\t\thas = has - p[j][1] + p[i][1];\n\t\t\t\t\treturn 1;\n\t\t\t\t}();\n\t\t\t\t\n\t\t\t\tif(!flag)\n\t\t\t\t{\n\t\t\t\t\tds.insert(p[i][1]);\n\t\t\t\t\ttree.set(dfnl[i], p[i][1]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t++cntp; sump += p[i][1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(i == rtid)\n\t\t\t\t{\n\t\t\t\t\tinsert_seg(dfnl[rt1], dfnr[rt1]);\n\t\t\t\t\tinsert_seg(dfnl[rt2], dfnr[rt2]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tint u = es[i][0], v = es[i][1];\n\t\t\t\t\tif(dfnl[u] < dfnl[v]) swap(u, v);\n\t\t\t\t\tinsert_seg(dfnl[u], dfnr[u]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t++cnte; sume += es[i][3];\n\t\t\t}\n\t\t\t\n\t\t\tif(cntp >= cnte + 1)\n\t\t\t{\n\t\t\t\tll cur = sume + has + ds.query(cnte + 1 - (int)seg.size());\n\t\t\t\tans = max(ans, t.first * cur);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprintf(\"%lld\n\",ans);\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1825",
    "index": "A",
    "title": "LuoTianyi and the Palindrome String",
    "statement": "LuoTianyi gives you \\textbf{a palindrome}$^{\\dagger}$ string $s$, and she wants you to find out the length of the longest non-empty subsequence$^{\\ddagger}$ of $s$ which is not a palindrome string. If there is no such subsequence, output $-1$ instead.\n\n$^{\\dagger}$ A palindrome is a string that reads the same backward as forward. For example, strings \"z\", \"aaa\", \"aba\", \"abccba\" are palindromes, but strings \"codeforces\", \"reality\", \"ab\" are not.\n\n$^{\\ddagger}$ A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from $b$. For example, strings \"a\", \"aaa\", \"bab\" are subsequences of string \"abaab\", but strings \"codeforces\", \"bbb\", \"h\" are not.",
    "tutorial": "Consider the substring of $s$ from the second character to the last, or $s_2s_3\\cdots s_n$. If it's not palindrome, then the answer must be $n-1$. What if it's palindrome? This implies that $s_2=s_n$, $s_3=s_{n-1}$, and so on. Meanwhile, the fact that $s$ is palindrome implies $s_1=s_n$, $s_2=s_{n-1}$, etc. So we get $s_1=s_n=s_2=s_{n-1}=\\cdots$ or that all characters in $s$ is the same. In this situation, every subsequence of $s$ is palindrome of course, so the answer should be $-1$.",
    "code": "#pragma GCC optimize(3,\"Ofast\",\"inline\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2\")\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n//#define ll int\n#define ft first\n#define sd second\n//#define endl '\n'\n#define pb push_back\n#define ll long long\n#define pll pair<ll,ll>\n#define no cout<<\"NO\"<<'\n'\n#define no_ cout<<\"No\"<<'\n'\n#define _no cout<<\"no\"<<'\n'\n#define lowbit(a) ((a)&-(a))\n#define yes cout<<\"YES\"<<'\n'\n#define yes_ cout<<\"Yes\"<<'\n'\n#define _yes cout<<\"yes\"<<'\n'\n#define ull unsigned long long\n#define all(x) x.begin(),x.end()\n#define nps fixed<<setprecision(10)<<\n#define mem(a,k) memset(a,k,sizeof(a))\n#define debug(x) cout<<#x<<\"=\"<<x<<endl\n#define rep(i,a,b) for(ll i=(a);i<=(b);i++)\n#define per(i,a,b) for(ll i=(a);i>=(b);i--)\nconst ll mod1=1e9+7;\nconst ll mod2=998244353;\nconst ll base=1610612741;\nconst ll INF=0x3f3f3f3f3f;\nconst ll inf=9223372036854775807;\nconst ll Z=mod2;\nconst ll mod=Z;\nusing namespace std;\nint ddir[2][2]={{0,1},{1,0}};\nint dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};\nint dir3[6][3]={{0,0,1},{0,0,-1},{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}};\nstruct custom_hash\n{\n    static ull splitmix64(ull x){x+=0x9e3779b97f4a7c15;x=(x^(x>>30))*0xbf58476d1ce4e5b9;x=(x^(x>>27))*0x94d049bb133111eb;return x^(x>>31);}\n    size_t operator()(ull x)const{static const ull FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();return splitmix64(x + FIXED_RANDOM);}\n    //unordered_map<ll,ll,custom_hash>mp;\n};\nstruct mint\n{\n    ll x;\n    mint(ll y = 0){if(y < 0 || y >= mod) y = (y%mod+mod)%mod; x = y;}\n    mint(const mint &ope) {x = ope.x;}\n    mint operator-(){return mint(-x);}\n    mint operator+(const mint &ope){return mint(x) += ope;}\n    mint operator-(const mint &ope){return mint(x) -= ope;}\n    mint operator*(const mint &ope){return mint(x) *= ope;}\n    mint operator/(const mint &ope){return mint(x) /= ope;}\n    mint& operator+=(const mint &ope){x += ope.x; if(x >= mod) x -= mod; return *this;}\n    mint& operator-=(const mint &ope){x += mod - ope.x; if(x >= mod) x -= mod; return *this;}\n    mint& operator*=(const mint &ope){ll tmp = x; tmp *= ope.x, tmp %= mod; x = tmp; return *this;}\n    mint& operator/=(const mint &ope){ll n = mod-2; mint mul = ope;while(n){if(n & 1) *this *= mul; mul *= mul; n >>= 1;}return *this;}\n    mint inverse(){return mint(1) / *this;}\n    bool operator ==(const mint &ope){return x == ope.x;}\n    bool operator !=(const mint &ope){return x != ope.x;}\n    bool operator <(const mint &ope)const{return x < ope.x;}\n};\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nll gcd(ll a,ll b){return __gcd(a,b);}\nll lcm(ll a,ll b){return a*b/__gcd(a,b);}\nll rnd(ll l,ll r){ll ans=uniform_int_distribution<ll>(l,r)(rng);return ans;}\nll qpow(ll a,ll b){ll res=1;while(b>0){if(b&1)res=res*a;a=a*a;b>>=1;}return res;}\nll qpow(ll a,ll b,ll m){a%=m;ll res=1;while(b>0){if(b&1)res=res*a%m;a=a*a%m;b>>=1;}return res;}\ndouble psqrt(double x,double y,double xx,double yy){double res=((x-xx)*(x-xx)+(y-yy)*(y-yy));return res;}\ndouble ssqrt(double x,double y,double xx,double yy){double res=sqrt(psqrt(x,y,xx,yy));return res;}\nll INV(ll x){return qpow(x,Z-2,Z);}\nvoid cominit(ll fac[],ll inv[]){fac[0]=1;rep(i,1,1000000)fac[i]=fac[i-1]*i%Z;\ninv[1000000]=INV(fac[1000000]);per(i,1000000-1,0)inv[i]=inv[i+1]*(i+1)%Z;}\nll t,n,m,k,tt,tp,res,sum,ans,cnt;\nconst ll N=1e6+5;\nll a[N],b[N];\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr),cout.tie(nullptr);\n    //IO\n    cin>>t;\n    while(t--)\n    {\n        string s;\n        cin>>s;\n        auto check=[&]()\n        {\n            for(int i=0;i<s.size()/2;++i)if(s[i]!=s[s.size()-i-1])return 0;\n            return 1;\n        };\n        if(!check())ans=s.size();\n        else if(s.size()>1)\n        {\n            s.pop_back();\n            if(!check())ans=s.size();\n            else ans=-1;\n        }\n        else ans=-1;\n        cout<<ans<<\"\n\";\n    }\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1825",
    "index": "B",
    "title": "LuoTianyi and the Table",
    "statement": "LuoTianyi gave an array $b$ of $n \\cdot m$ integers. She asks you to construct a table $a$ of size $n \\times m$, filled with these $n \\cdot m$ numbers, and each element of the array must be used \\textbf{exactly once}. Also she asked you to maximize the following value:\n\n\\begin{center}\n$\\sum\\limits_{i=1}^{n}\\sum\\limits_{j=1}^{m}\\left(\\max\\limits_{1 \\le x \\le i, 1 \\le y \\le j}a_{x,y}-\\min\\limits_{1 \\le x \\le i, 1 \\le y \\le j}a_{x,y}\\right)$\n\\end{center}\n\nThis means that we consider $n \\cdot m$ subtables with the upper left corner in $(1,1)$ and the bottom right corner in $(i, j)$ ($1 \\le i \\le n$, $1 \\le j \\le m$), for each such subtable calculate the difference of the maximum and minimum elements in it, then sum up all these differences. You should maximize the resulting sum.\n\nHelp her find the maximal possible value, you don't need to reconstruct the table itself.",
    "tutorial": "Assume that $n>m$. Greedily thinking, we want the maximum possible $a$ to appear as the maximum value of as many subtables as possible, meanwhile, we also want the minimum possible $a$ to appear as the minimum value of as many subtables as possible. This gives us two choices: making the upper-left square the minimum or the maximum. It's symmetrical so we'll only consider the minimum situation. Now all the subtables have the same minimum value, we want to maximize the number of subtables where the maximum $a$ appears as the maximum value. Placing it at $(1,2)$ and $(2,1)$ makes the number $n(m-1),m(n-1)$ each, because $n>m$, we have $m(n-1)>n(m-1)$, so we place the largest $a$ at $(2,1)$ and the second largest at $(1,2)$, the answer for this case is $m(n-1)\\times \\max+m\\times \\text{second max}-mn\\times\\min$.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nusing namespace std;\nconst int mxn=2e5+5;\nll a[mxn];\ninline void solve(){\n\tll n,m;\n\tcin>>n>>m;\n\tfor(int i=1;i<=n*m;++i)cin>>a[i];\n\tsort(a+1,a+n*m+1);\n\tif(n>m)swap(n,m);\n\tif(n==1)cout<<(m-1)*(a[n*m]-a[1])<<'\n';\n\telse{\n\t\tll ans1=(n*m-1)*(a[n*m])-a[1]*(n*(m-1))-a[2]*(n-1);\n\t\tll ans2=a[n*m]*(n*(m-1))+a[n*m-1]*(n-1)-a[1]*(n*m-1);\n\t\tcout<<max(ans1,ans2)<<'\n';\n\t}\n}\nint main(){\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tint T;cin>>T;\n\tfor(;T--;)solve();\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1826",
    "index": "A",
    "title": "Trust Nobody",
    "statement": "There is a group of $n$ people. Some of them might be liars, who \\textbf{always} tell lies. Other people \\textbf{always} tell the truth. The $i$-th person says \"There are at least $l_i$ liars amongst us\". Determine if what people are saying is contradictory, or if it is possible. If it is possible, output the number of liars in the group. If there are multiple possible answers, output any one of them.",
    "tutorial": "Let's iterate over the number $x$ of liars in the group. Now everyone, who says $l_i > x$ is a liar, and vice versa. Let's count the actual number of liars. If those numbers match, output the answer. Now that we've checked all possible $x$'s, we can safely output $-1$, since no number of liars is possible.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> l(n);\n    for (auto &i : l) {\n        cin >> i;\n    }\n    for (int cnt_liars = 0; cnt_liars <= n; ++cnt_liars) {\n        int actual = 0;\n        for (auto i : l) {\n            if (!(cnt_liars >= i)) {\n                ++actual;\n            }\n        }\n        if (actual == cnt_liars) {\n            cout << cnt_liars << '\\n';\n            return;\n        }\n    }\n    cout << \"-1\\n\";\n}\n \nsigned main() {\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1826",
    "index": "B",
    "title": "Lunatic Never Content",
    "statement": "You have an array $a$ of $n$ non-negative integers. Let's define $f(a, x) = [a_1 \\bmod x, a_2 \\bmod x, \\dots, a_n \\bmod x]$ for some positive integer $x$. Find the biggest $x$, such that $f(a, x)$ is a palindrome.\n\nHere, $a \\bmod x$ is the remainder of the integer division of $a$ by $x$.\n\nAn array is a palindrome if it reads the same backward as forward. More formally, an array $a$ of length $n$ is a palindrome if for every $i$ ($1 \\leq i \\leq n$) $a_i = a_{n - i + 1}$.",
    "tutorial": "For the sequence to be a palindrome, it has to satisfy $b_i = b_{n - i + 1}$. In our case $b_i = a_i \\pmod x$. We can rewrite the palindrome equation as $a_i \\pmod x = a_{n - i + 1} \\pmod x$. Moving all the terms to the left we get $a_i - a_{n - i + 1} \\equiv 0 \\pmod x$, which basically says $x$ divides $a_i - a_{n - i + 1}$. Now, how to find the biggest $x$, which satisfies all such conditions? Greatest common divisor of course! We just need to calculate the $GCD$ of the numbers $a_i - a_{n - i + 1}$ for all $i$. This results in a $O(n + log(10^9))$ solution, since computing the gcd of $n$ numbers up to $10^9$ takes exactly this much time. A useful assumption here is that $GCD(x, 0) = x$ for any number $x$. This holds true for standard template library implementations. And do not forget that this function should work correctly for negative numbers too. An easy trick here is to just use the absolute value of $a_i - a_{n - i + 1}$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (auto &i : a) cin >> i;\n    int ans = 0;\n    for (int i = 0; i < n; ++i) {\n        ans = __gcd(ans, abs(a[i] - a[n - i - 1]));\n    }\n    cout << ans << '\\n';\n}\n \nint main() {\n    cin.tie(0);\n    cout.tie(0);\n    ios_base::sync_with_stdio(0);\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1826",
    "index": "C",
    "title": "Dreaming of Freedom",
    "statement": "\\begin{quote}\nBecause to take away a man's freedom of choice, even his freedom to make the wrong choice, is to manipulate him as though he were a puppet and not a person.\n\\hfill — Madeleine L'Engle\n\\end{quote}\n\nThere are $n$ programmers choosing their favorite algorithm amongst $m$ different choice options. Before the first round, all $m$ options are available. In each round, every programmer makes a vote for one of the remaining algorithms. After the round, only the algorithms with the maximum number of votes remain. The voting process ends when there is only one option left. Determine whether the voting process can continue indefinitely or no matter how people vote, they will eventually choose a single option after some finite amount of rounds?",
    "tutorial": "First we need to notice, that in order to keep some amount of options indefinetely, this number has to be at least $2$ and divide $n$. Let's find the smallest such number $d$. Now, if $d \\leq m$, let's always vote for the first $d$ options evenly. In the other case $(d > m)$ each round would force us to to decrease the number of remaining options, so eventually it will become one. So the answer is YES if and only if $d > m$. Now on how to find the number $d$ fast. Since $d$ is a divisor of $n$ we can say, that $d$ is the smallest divisor of $n$ not equal to $1$. We can find the number $d$ using different approaches. A more straightforward one, is checking all the numbers from $2$ up to $\\sqrt{n}$. If no divisors found, then $n$ is prime and $d = n$. This results in a $O(t \\cdot \\sqrt{n})$ solution. The solution presented before is good, but not fast enough in some languages, like Python. We've decided not to cut it off to not make the problem heavy in IO. We can optimize it via finding the smallest divisor using the sieve of Eratosthenes. This would result in $O(nlogn)$ or even faster precomputation and $O(1)$ to answer a test case, so the total time complexity is $O(nlogn + t)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 1e6 + 100;\nvector<int> min_div(N);\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    cout << (n == 1 || min_div[n] > m ? \"YES\" : \"NO\") << '\\n';\n}\n \nint main() {\n    cin.tie(0);\n    cout.tie(0);\n    ios_base::sync_with_stdio(0);\n    for (int d = 2; d * d < N; ++d) {\n        if (min_div[d] == 0) {\n            min_div[d] = d;\n            for (int i = d * d; i < N; i += d) {\n                if (min_div[i] == 0) {\n                    min_div[i] = d;\n                }\n            }\n        }\n    }\n    for (int i = 1; i < N; ++i) {\n        if (min_div[i] == 0) {\n            min_div[i] = i;\n        }\n    }\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1826",
    "index": "D",
    "title": "Running Miles",
    "statement": "There is a street with $n$ sights, with sight number $i$ being $i$ miles from the beginning of the street. Sight number $i$ has beauty $b_i$. You want to start your morning jog $l$ miles and end it $r$ miles from the beginning of the street. By the time you run, you will see sights you run by (including sights at $l$ and $r$ miles from the start). You are interested in the $3$ most beautiful sights along your jog, but every mile you run, you get more and more tired.\n\nSo choose $l$ and $r$, such that there are at least $3$ sights you run by, and the sum of beauties of the $3$ most beautiful sights minus the distance in miles you have to run is maximized. More formally, choose $l$ and $r$, such that $b_{i_1} + b_{i_2} + b_{i_3} - (r - l)$ is maximum possible, where $i_1, i_2, i_3$ are the indices of the three maximum elements in range $[l, r]$.",
    "tutorial": "There is a fairly straightforward solution using DP, but I'll leave that for the comment section and present a very short and simple solution. First we need to notice, that at two of the maximums are at the ends of $[l, r]$, otherwise we can move one of the boundaries closer to the other and improve the answer. Using this observation we can reduce the problem to the following: choose three indices $l < m < r$, such that $b_l + b_m + b_r - (r - l)$ is maximum. Now, let's iterate over the middle index $m$ and rewrite the function as $b_m + (b_l + l) + (b_r - r)$. We can see, that values in the braces are pretty much independent - on of them depends only on the index $l$ and the second one depends only on the index $r$. So, for a given $m$ we can choose the numbers $l$ and $r$ greedily! To make it fast enough we can precalculate the prefix maximum for the array $b_l + l$ and the suffix maximum for array $b_r - r$. This results in a $O(n)$ time complexity solution.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> b(n);\n    for (auto &i : b) cin >> i;\n    vector<int> pref_mx(n), suff_mx(n);\n    for (int i = 0; i < n; ++i) {\n        pref_mx[i] = b[i] + i;\n        suff_mx[i] = b[i] - i;\n    }\n    for (int i = 1; i < n; ++i) {\n        pref_mx[i] = max(pref_mx[i], pref_mx[i - 1]);\n    }\n    for (int i = n - 2; i >= 0; --i) {\n        suff_mx[i] = max(suff_mx[i], suff_mx[i + 1]);\n    }\n    int ans = 0;\n    for (int m = 1; m < n - 1; ++m) {\n        ans = max(ans, b[m] + pref_mx[m - 1] + suff_mx[m + 1]);\n    }\n    cout << ans << '\\n';\n}\n \nint main() {\n    cin.tie(0);\n    cout.tie(0);\n    ios_base::sync_with_stdio(0);\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1826",
    "index": "E",
    "title": "Walk the Runway",
    "statement": "A fashion tour consists of $m$ identical runway shows in different cities. There are $n$ models willing to participate in the tour, numbered from $1$ to $n$. People in different cities have different views on the fashion industry, so they rate each model differently. In particular, people in city $i$ rate model $j$ with rating $r_{i, j}$.\n\nYou are to choose some number of $k$ models, and their order, let the chosen models have indices $j_1, j_2, \\dots, j_k$ in the chosen order. In each city, these $k$ models will walk the runway one after another in this order. To make the show exciting, in each city, the ratings of models should be strictly increasing in the order of their performance. More formally, for any city $i$ and index $t$ ($2 \\leq t \\leq k$), the ratings must satisfy $r_{i,j_{t - 1}} < r_{i,j_t}$.\n\nAfter all, the fashion industry is all about money, so choosing model $j$ to participate in the tour profits you $p_j$ money. Compute the maximum total profit you can make by choosing the models and their order while satisfying all the requirements.",
    "tutorial": "At first, let's define the relation between two models, that go one after another in the show. Their ratings must satisfy $r_{i, j} < r_{i, k}$ for all cities $i$. Now let's precompute this relations for all pairs of models naively in $O(n^2m)$, which is ok for now. Now, we have the relations \"model $i$ can go before model $j$\", let's build a graph of such relations. This graph has no cycles, since the ratings are strictly increasing. Now we can build the topological sorting of this graph and compute $dp_i =$ the biggest profit, if the last model is model $i$ in $O(n^2)$. Now, how to calculate this relation for all pairs of models fast enough? Let's process each city one by one and update the relations using bitsets! More formally, let's store a bitset of all the models, that can be before model $j$ in city $i$. If we process the models in order of increasing rating, we can update each models bitset of relations in $O(\\frac{n}{64})$, so the total time complexity would be $O(\\frac{n^2m}{64})$, which is fast enough.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing ll = long long;\nusing bs = bitset<5000>;\n \nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int m, n;\n    cin >> m >> n;\n    vector<ll> c(n);\n    for (auto &i : c) {\n        cin >> i;\n    }\n    vector<int> ind(n);\n    iota(ind.begin(), ind.end(), 0);\n    bs can_bs;\n    for (int i = 0; i < n; ++i) {\n        can_bs[i] = true;\n    }\n    vector<bs> can(n, can_bs);\n    for (int d = 0; d < m; ++d) {\n        vector<int> r(n);\n        for (auto &r : r) {\n            cin >> r;\n        }\n        sort(ind.begin(), ind.end(), [&](int i, int j) {\n            return r[i] < r[j];\n        });\n        bs prev;\n        for (int i = 0; i < n; ) {\n            int j = i;\n            while (j < n && r[ind[j]] == r[ind[i]]) {\n                can[ind[j]] &= prev;\n                ++j;\n            }\n            while (i < j) {\n                prev[ind[i]] = true;\n                ++i;\n            }\n        }\n    }\n    vector<ll> dp = c;\n    for (auto i : ind) {\n        for (int j = 0; j < n; ++j) {\n            if (can[i][j]) {\n                dp[i] = max(dp[i], c[i] + dp[j]);\n            }\n        }\n    }\n    cout << *max_element(dp.begin(), dp.end()) << '\\n';\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "dp",
      "graphs",
      "implementation",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1826",
    "index": "F",
    "title": "Fading into Fog",
    "statement": "\\textbf{This is an interactive problem.}\n\nThere are $n$ distinct hidden points with real coordinates on a two-dimensional Euclidean plane. In one query, you can ask some line $ax + by + c = 0$ and get the projections of all $n$ points to this line in some order. The given projections are not exact, please read the interaction section for more clarity.\n\nUsing the minimum number of queries, guess all $n$ points and output them in some order. Here minimality means the minimum number of queries required to solve any possible test case with $n$ points.\n\nThe hidden points are fixed in advance and do not change throughout the interaction. In other words, the interactor is not adaptive.\n\nA projection of point $A$ to line $ax + by + c = 0$ is the point on the line closest to $A$.",
    "tutorial": "At first let's query two non-parallel lines. In this general case building perpendicular lines from projections and intersecting them will give us $O(n^2)$ candidates for the answer. This gives us the intuition, that 2 queries isn't enough. Also, the constraint from the statement suggests, that asking $x = 0$ and $y = 0$ will guarantee, that no two candidates are closer, than $1$ from each other, which will come in handy later. Now let's prove we can solve the problem in 3 queries. Indeed, there will always some space between the candidates. A simple proof of that would go something like this: there are $O(n^2)$ candidates and $O(n^4)$ pairs of candidates; now we can sort the directional vectors by the angle, and there will be at least one angle of at least $\\frac{2\\pi}{O(n^4)}$ between some two neighbouring vectors by the pigeonhole principle, which is big enough. One way to choose such a line is by queriying random lines, till we find a good enough one, or query some constant amount of lines and choose the one with the biggest distance. Checking one line can be done in $O(n^2logn)$ with a simple sort. How many exactly do we need is an exercise to the reader, but it can be proven, that under the given constraints this number is $O(1)$. Now, when we have the line, let's query it and check all the candidates in $O(n^3)$ or $O(n^2logn)$ or even $O(n^2)$. It doesn't really affect the runtime. The total complexity is $O(n^2logn)$ per testcase.",
    "code": "#pragma GCC optimize(\"O3\", \"unroll-loops\")\n#pragma GCC target(\"sse4.2\")\n \n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <deque>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n#include <ext/random>\n \nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing pll = pair<ll, ll>;\nusing graph = vector<vector<int>>;\n \nconst ld eps = 1e-9;\nconst int mod = 1000000007;\nconst ll inf = 3000000000000000007ll;\n \n#define pb push_back\n#define pf push_front\n#define popb pop_back\n#define popf pop_front\n#define f first\n#define s second\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define by_key(...) [](const auto &a, const auto &b) { return a.__VA_ARGS__ < b.__VA_ARGS__; }\n \n#ifdef DEBUG\n    __gnu_cxx::sfmt19937 gen(857204);\n#else\n    __gnu_cxx::sfmt19937 gen(int(chrono::high_resolution_clock::now().time_since_epoch().count()));\n#endif\n \ntemplate<class T, class U> inline bool chmin(T &x, const U& y) { return y < x ? x = y, 1 : 0; }\ntemplate<class T, class U> inline bool chmax(T &x, const U& y) { return y > x ? x = y, 1 : 0; }\ntemplate<class T> inline int sz(const T &a) { return a.size(); }\ntemplate<class T> inline void sort(T &a) { sort(all(a)); }\ntemplate<class T> inline void rsort(T &a) { sort(rall(a)); }\ntemplate<class T> inline void reverse(T &a) { reverse(all(a)); }\ntemplate<class T> inline T sorted(T a) { sort(a); return a; }\n \nstruct InitIO {\n    InitIO() {\n        ios_base::sync_with_stdio(0);\n        cin.tie(0);\n        cout.tie(0);\n        cout << fixed << setprecision(12);\n    }\n    ~InitIO() {\n        #ifdef DEBUG\n            cerr << \"Runtime is: \" << clock() * 1.0 / CLOCKS_PER_SEC << endl;\n        #endif\n    }\n} Initter;\n \nvoid flush() { cout << flush; }\nvoid flushln() { cout << endl; }\nvoid println() { cout << '\\n'; }\ntemplate<class T> void print(const T &x) { cout << x; }\ntemplate<class T> void read(T &x) { cin >> x; }\ntemplate<class T, class ...U> void read(T &x, U& ... u) { read(x); read(u...); }\ntemplate<class T, class ...U> void print(const T &x, const U& ... u) { print(x); print(u...); }\ntemplate<class T, class ...U> void println(const T &x, const U& ... u) { print(x); println(u...); }\n \ntemplate<class T, class U> inline istream& operator>>(istream& str, pair<T, U> &p) { return str >> p.f >> p.s; }\ntemplate<class T> inline istream& operator>>(istream& str, vector<T> &a) { for (auto &i : a) str >> i; return str; }\n \n#ifdef DEBUG\n    namespace TypeTraits {\n        template<class T> constexpr bool IsString = false;\n        template<> constexpr bool IsString<string> = true;\n        template<class T, class = void> struct IsIterableStruct : false_type{};\n        template<class T>\n        struct IsIterableStruct<\n            T,\n            void_t<\n                decltype(begin(declval<T>())),\n                decltype(end(declval<T>()))\n            >\n        > : true_type{};\n        template<class T> constexpr bool IsIterable = IsIterableStruct<T>::value;\n        template<class T> constexpr bool NonStringIterable = !IsString<T> && IsIterable<T>;\n        template<class T> constexpr bool DoubleIterable = IsIterable<decltype(*begin(declval<T>()))>;\n    };\n    // Declaration (for cross-recursion)\n    template<class T>\n    auto pdbg(const T&x) -> enable_if_t<!TypeTraits::NonStringIterable<T>, string>;\n    string pdbg(const string &x);\n    template<class T>\n    auto pdbg(const T &x) -> enable_if_t<TypeTraits::NonStringIterable<T>, string>;\n    template<class T, class U>\n    string pdbg(const pair<T, U> &x);\n \n    // Implementation\n    template<class T>\n    auto pdbg(const T &x) -> enable_if_t<!TypeTraits::NonStringIterable<T>, string> {\n        stringstream ss;\n        ss << x;\n        return ss.str();\n    }\n    template<class T, class U>\n    string pdbg(const pair<T, U> &x) {\n        return \"{\" + pdbg(x.f) + \",\" + pdbg(x.s) + \"}\";\n    }\n    string pdbg(const string &x) {\n        return \"\\\"\" + x + \"\\\"\";\n    }\n    template<class T>\n    auto pdbg(const T &x) -> enable_if_t<TypeTraits::NonStringIterable<T>, string> {\n        auto begin = x.begin();\n        auto end = x.end();\n        string del = \"\";\n        if (TypeTraits::DoubleIterable<T>) {\n            del = \"\\n\";\n        }\n        string ans;\n        ans += \"{\" + del;\n        if (begin != end) ans += pdbg(*begin++);\n        while (begin != end) {\n            ans += \",\" + del + pdbg(*begin++);\n        }\n        ans += del + \"}\";\n        return ans;\n    }\n    template<class T> string dbgout(const T &x) { return pdbg(x); }\n    template<class T, class... U>\n    string dbgout(T const &t, const U &... u) {\n        string ans = pdbg(t);\n        ans += \", \";\n        ans += dbgout(u...);\n        return ans;\n    }\n    #define dbg(...) print(\"[\", #__VA_ARGS__, \"] = \", dbgout(__VA_ARGS__)), flushln()\n    #define msg(...) print(\"[\", __VA_ARGS__, \"]\"), flushln()\n#else\n    #define dbg(...) 0\n    #define msg(...) 0\n#endif\n \nbool eq(ld a, ld b) { return abs(a - b) < eps; }\n \nstruct vec {\n    ld x, y;\n    vec() {}\n    vec(ld x, ld y) { this->x = x; this->y = y; }\n    vec operator+=(const vec &v) { x += v.x; y += v.y; return *this; }\n    vec operator-=(const vec &v) { x -= v.x; y -= v.y; return *this; }\n    vec operator*=(ld k) { x *= k; y *= k; return *this; }\n    vec operator/=(ld k) { x /= k; y /= k; return *this; }\n    vec operator-() const { return vec(-x, -y); }\n    vec orth() const { return vec(-y, x); }\n    ld len2() const { return x * x + y * y; }\n    ld len() const { return sqrt(len2()); }\n    friend vec operator+(vec a, const vec &b) { return a += b; }\n    friend vec operator-(vec a, const vec &b) { return a -= b; }\n    friend vec operator*(vec a, const ld &k) { return a *= k; }\n    friend vec operator/(vec a, const ld &k) { return a /= k; }\n    friend ld operator*(const vec &a, const vec &b) { return a.x * b.x + a.y * b.y; }\n    friend ld operator/(const vec &a, const vec &b) { return a.x * b.y - a.y * b.x; }\n    vec rot(ld sina, ld cosa) { return orth() * sina + *this * cosa; }\n    vec rot(ld alpha) { return rot(sin(alpha), cos(alpha)); }\n    friend istream& operator>>(istream& str, vec &v) { return str >> v.x >> v.y; }\n    friend ostream& operator<<(ostream& str, const vec &v) { return str << v.x << ' ' << v.y; }\n    friend bool operator==(const vec &a, const vec &b) { return eq(a.x, b.x) && eq(a.y, b.y); }\n    friend bool operator!=(const vec &a, const vec &b) { return !(a == b); }\n    friend bool operator<(const vec &a, const vec &b) { return (eq(a.x, b.x) ? a.y < b.y : a.x < b.x); }\n};\n \nint n;\n \nvector<vec> query(ld a, ld b, ld c) {\n    println(\"? \", a, ' ', b, ' ', c);\n    flush();\n    vector<vec> ans(n);\n    read(ans);\n    return ans;\n}\n \nld rand(ld a, ld b) {\n    uniform_real_distribution<ld> uni(a, b);\n    return uni(gen);\n}\n \nvoid solve() {\n    read(n);\n    vector<ld> xs, ys;\n    for (auto [x, _] : query(0, 1, 0)) {\n        xs.pb(x);\n    }\n    for (auto [_, y] : query(1, 0, 0)) {\n        ys.pb(y);\n    }\n    ld a, b;\n    vec dir;\n    static const ld NOISE = 1e-4;\n    while (true) {\n        ld angle = rand(0, 3.1415);\n        a = sin(angle), b = cos(angle);\n        dir = vec(-b, a);\n        vector<vec> pt;\n        for (auto x : xs) {\n            for (auto y : ys) {\n                pt.pb(dir * (dir * vec(x, y)));\n            }\n        }\n        bool flag = true;\n        sort(pt);\n        for (int i = 0; i + 1 < sz(pt); ++i) {\n            if ((pt[i + 1] - pt[i]).len() < 6 * NOISE) {\n                flag = false;\n                break;\n            }\n        }\n        if (flag) {\n            break;\n        }\n    }\n    auto pr = query(a, b, 0);\n    vector<vec> ans;\n    for (auto x : xs) {\n        for (auto y : ys) {\n            vec check = dir * (dir * vec(x, y));\n            bool flag = false;\n            for (auto p : pr) {\n                if ((p - check).len() < 3 * NOISE) {\n                    flag = true;\n                }\n            }\n            if (flag) {\n                ans.pb({x, y});\n            }\n        }\n    }\n    print(\"! \");\n    for (auto p : ans) print(p, ' ');\n    flushln();\n}\n \nsigned main() {\n    int t;\n    read(t);\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "geometry",
      "interactive",
      "math",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1827",
    "index": "A",
    "title": "Counting Orders",
    "statement": "You are given two arrays $a$ and $b$ each consisting of $n$ integers. All elements of $a$ are pairwise distinct.\n\nFind the number of ways to reorder $a$ such that $a_i > b_i$ for all $1 \\le i \\le n$, modulo $10^9 + 7$.\n\nTwo ways of reordering are considered different if the resulting arrays are different.",
    "tutorial": "Sort the array $b$, and fix the values from $a_n$ to $a_1$. First, we can sort the array $b$, as it does not change the answer. Let's try to choose the values of $a$ from $a_n$ to $a_1$. How many ways are there to choose the value of $a_i$? The new $a_i$ must satisfies $a_i > b_i$. But some of the candidates are already chosen as $a_j$ for some $j > i$. However, since $a_j > b_j \\ge b_i$, we know that there are exactly $(n - i)$ candidates already chosen previously by all values of $j > i$. So, there are (number of $k$ such that $a_k > b_i$) $- (n - i)$ ways to choose the value of $a_i$. We can use two pointers or binary search to efficiently find the (number of $k$ such that $a_k > b_i$) for all $i$. Time complexity: $\\mathcal O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int MOD = 1e9 + 7;\n\nstruct testcase{\n    testcase(){\n        int n; cin >> n;\n        vector<int> a(n);\n        for (int i=0; i<n; i++) cin >> a[i];\n        sort(a.begin(), a.end());\n        vector<int> b(n);\n        for (int i=0; i<n; i++) cin >> b[i];\n        sort(b.begin(), b.end(), greater<>());\n        ll result = 1;\n        for (int i=0; i<n; i++){\n            int geq_count = a.size() - (upper_bound(a.begin(), a.end(), b[i]) - a.begin());\n            result = result * max(geq_count - i, 0) % MOD;\n        }\n        cout << result << \"\\n\";\n    }\n};\n\nsigned main(){\n    cin.tie(0)->sync_with_stdio(0);\n    int t; cin >> t;\n    while (t--) testcase();\n}",
    "tags": [
      "combinatorics",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1827",
    "index": "B2",
    "title": "Range Sorting (Hard Version)",
    "statement": "\\textbf{The only difference between this problem and the easy version is the constraints on $t$ and $n$.}\n\nYou are given an array $a$, consisting of $n$ distinct integers $a_1, a_2, \\ldots, a_n$.\n\nDefine the beauty of an array $p_1, p_2, \\ldots p_k$ as the minimum amount of time needed to sort this array using an arbitrary number of range-sort operations. In each range-sort operation, you will do the following:\n\n- Choose two integers $l$ and $r$ ($1 \\le l < r \\le k$).\n- Sort the subarray $p_l, p_{l + 1}, \\ldots, p_r$ in $r - l$ seconds.\n\nPlease calculate the sum of beauty over all subarrays of array $a$.\n\nA subarray of an array is defined as a sequence of consecutive elements of the array.",
    "tutorial": "What is the minimum cost to sort just one subarray? What happens when two operations intersect each other? When can we sort two adjacency ranges independently? Try to calculate the contribution of each position. Let $a[l..r]$ denotes the subarray $a_l,a_{l+1},\\ldots,a_r$. Observation 1: In an optimal sequence of operations for one subarray, there will be no two operations that intersect each other. In other words, a subarray will be divided into non-overlapping subarrays, and we will apply a range-sort operation to each subarray. Proof: Suppose there are two operations $[l_1,r_1]$ and $[l_2,r_2]$ that intersect each other, we can replace them with one operation $[\\min(l_1,l_2),\\max(r_1,r_2)]$ which does not increase the cost. Observation 2: Consider $k$ positions $l\\le i_1<i_2<\\ldots < i_k < r$, then we can sort subarrays $a[l..i_1],$ $a[i_1+1..i_2],$ $\\ldots,$ $a[i_k+1..r]$ independently iff $\\max(a[l..i_x])<\\min(a[i_x+1..r])$ for all $1\\le x\\le k$. Proof: The obvious necessary and sufficient condition required to sort subarrays $a[l..i_1],$ $a[i_1+1..i_2],$ $\\ldots,$ $a[i_k+1..r]$ independently is $\\max(a[i_{x-1}+1..i_x])<\\min(a[i_x+1..i_{x+1}])$ for all $1\\le x\\le k$, here we denote $x_0=l-1$ and $x_{k+1}=r$. It is not hard to prove that this condition is equal to the one stated above. With these observations, we can conclude that the answer for a subarray $a[l..r]$ equals the $r-l$ minus the number of positions $k$ such that $l\\le k\\lt r$ and $\\max(a[l..k])<\\min(a[k+1..r])$ $(*)$. Let us analyze how to calculate the sum of this value over all possible $l$ and $r$. Consider a position $i$ ($1\\le i\\le n$), let's count how many triplets $(l, k, r)$ satisfy $(*)$ and $min(a[k+1..r]) = a_i$. It means that $k$ must be the closest position to the left of $i$ satisfying $a_k<a_i$. Denotes $x$ as the closest position to the left of $k$ such that $a_x>a_i$, and $y$ as the closest position to the right of $i$ such that $a_y<a_i$. We can see that a triplet $(l, k, r)$ with $x<l\\le k$ and $i\\le r<y$ will match our condition. In other words, we will add to the answer $(k - x) \\cdot (y - i)$. In the easy version, we can find such values of $x, k, y$ for each $i$ in $\\mathcal{O}(n)$ and end up with a total complexity of $O(n^2)$. We can further optimize the algorithm by using sparse table and binary lifting and achieve a time complexity of $\\mathcal{O}(n \\log{n})$, which is enough to solve the hard version. There is an $\\mathcal{O}(n)$ solution described here. Solve the problem when the beauty of an array is (minimum time needed to sort)$^2$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 3e5 + 5;\n\nint n;\nint a[N];\n\npair <int, int> b[N];\n\nsigned main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0); cout.tie(0);\nint tests; cin >> tests; while (tests--){\n    cin >> n;\n    for (int i = 1; i <= n; i++){\n        cin >> a[i];\n    }\n\n    for (int i = 1; i <= n; i++){\n        b[i] = make_pair(a[i], i);\n    }\n    sort(b + 1, b + n + 1);\n\n    set <int> sttlo = {0, n + 1}, stthi = {0, n + 1};\n    for (int i = 1; i <= n; i++){\n        stthi.emplace(i);\n    }\n    long long ans = 0;\n    for (int len = 1; len <= n; len++){\n        ans += (long long)(len - 1) * (n - len + 1);\n    }\n    for (int i = 1; i <= n; i++){\n        int idx = b[i].se;\n        stthi.erase(idx); sttlo.emplace(idx);\n \n        int x2 = *stthi.lower_bound(idx);\n        int x1 = *prev(stthi.lower_bound(idx));\n        if (x2 == n + 1){\n            continue;\n        }\n        int x3 = *sttlo.lower_bound(x2);\n        ans -= (long long)(idx - x1) * (x3 - x2);\n    }\n    cout << ans << endl;\n}\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1827",
    "index": "C",
    "title": "Palindrome Partition",
    "statement": "A substring is a continuous and non-empty segment of letters from a given string, without any reorders.\n\nAn even palindrome is a string that reads the same backward as forward and has an even length. For example, strings \"zz\", \"abba\", \"abccba\" are even palindromes, but strings \"codeforces\", \"reality\", \"aba\", \"c\" are not.\n\nA beautiful string is an even palindrome or a string that can be partitioned into some smaller even palindromes.\n\nYou are given a string $s$, consisting of $n$ lowercase Latin letters. Count the number of \\textbf{beautiful substrings} of $s$.",
    "tutorial": "Try to construct beautiful string greedily. What happens when we have two even palindromes share one of their endpoints? For the simplicity of the solution, we will abbreviate even palindrome as evp. Lemma: Consider a beautiful string $t$, we can find the unique maximal partition for it by greedily choosing the smallest possible evp in each step from the left. Here maximal means maximum number of parts. Proof: Suppose $t[0..l)$ is smallest prefix which is an evp and $t[0..r)$ is the first part in the partition of $t$, here $t[l..r)$ mean substring $t_l t_{l+1}\\ldots t_{r-1}$. We consider two cases: $2l\\le r$: In this case, it is clear that $t[0..l)$, $t[l..r - l)$ and $t[r-l..r)$ are evps, so we can replace $t[0..r)$ with them. $2l>r$: In this case, due to the fact that $t[r-l..l)$ and $t[0..l)$ are evps, $t[0..2l-r)$ is also an evp, which contradicts to above assumption that $t[0..l)$ is the smallest. We can use dynamic programming to solve this problem. Let $dp_i$ be the number of beautiful substrings starting at $i$. For all $i$ from $n-1$ to $0$, if there are such $next_i$ satisfying $s[i..next_i)$ is the smallest evp beginning at $i$, then $dp_i=dp_{next_i}+1$, otherwise $dp_i=0$. The answer will be the sum of $dp_i$ from $0$ to $n-1$. To calculate the $next$ array, first, we use Manacher algorithm or hashing to find the maximum $pal_i$ satisfying $s[i-pal_i..i+pal_i)$ is an evp for each $i$. Then for all $0\\le i< n$, $next_i=2j-i$ where $j$ is smallest position such that $i<j$ and $j-pal_j\\le i$. The time complexity is $\\mathcal{O}(n \\log{n})$. Solve the problem in $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 500005;\nconst int LOG = 19;\n \nint n, pal[N], rmq[LOG][N], cnt[N];\nstring s;\n \nint main() {\n  cin.tie(0)->sync_with_stdio(0);\n  int t; cin >> t;\n  while (t--) {\n    cin >> n >> s;\n    for (int i = 0, l = 0, r = 0; i < n; i++) {\n      pal[i] = i >= r ? 0 : min(pal[l + r - i], r - i);\n      while (i + pal[i] < n && i - pal[i] - 1 >= 0\n      && s[i + pal[i]] == s[i - pal[i] - 1]) pal[i]++;\n      if (i + pal[i] > r) {\n        l = i - pal[i]; r = i + pal[i];\n      }\n    }\n    for (int i = 0; i < n; i++)\n      rmq[0][i] = i - pal[i];\n    for (int k = 1; k < LOG; k++)\n      for (int i = 0; i + (1 << k) <= n; i++)\n        rmq[k][i] = min(rmq[k - 1][i],\n        rmq[k - 1][i + (1 << (k - 1))]);\n    for (int i = 1; i <= n; i++)\n      cnt[i] = 0;\n    for (int i = 0; i < n; i++) {\n      int j = i + 1;\n      for (int k = LOG - 1; k >= 0; k--)\n        if (j + (1 << k) <= n && rmq[k][j] > i)\n          j += 1 << k;\n      if (2 * j - i <= n)\n        cnt[2 * j - i] += cnt[i] + 1;\n      \n    }\n    long long res = 0;\n    for (int i = 1; i <= n; i++)\n      res += cnt[i];\n    cout << res << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "hashing",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1827",
    "index": "D",
    "title": "Two Centroids",
    "statement": "You are given a tree (an undirected connected acyclic graph) which initially only contains vertex $1$. There will be several queries to the given tree. In the $i$-th query, vertex $i + 1$ will appear and be connected to vertex $p_i$ ($1 \\le p_i \\le i$).\n\nAfter each query, please find out the least number of operations required to make the current tree has \\textbf{two} centroids. In one operation, you can add \\textbf{one} vertex and \\textbf{one} edge to the tree such that it remains a tree.\n\nA vertex is called a centroid if its removal splits the tree into subtrees with at most $\\lfloor \\frac{n}{2} \\rfloor$ vertices each, with $n$ as the number of vertices of the tree. For example, the centroid of the following tree is $3$ because the biggest subtree after removing the centroid has $2$ vertices.\n\nIn the next tree, vertex $1$ and $2$ are both centroids.",
    "tutorial": "Is the answer related to the centroid of the current tree? How much the centroid will move after one query? Observation: The answer for the tree with $n$ vertices equals $n-2\\cdot mx$ where $mx$ is the largest subtree among the centroid's children. Lemma: After one query, the centroid will move at most one edge, and when the centroid move, the tree before the query already has two centroids. Proof: Suppose the tree before the query has $n$ vertices and the current centroid is $u$. Let $v_1, v_2,\\ldots,v_k$ are the children of $u$ and the next query vertex $x$ is in subtree $v_1$. Clearly, the centroid is either $u$ or in the subtree $v_1$. Consider the latter case, because the size of subtree $v_1$ does not greater than $\\lfloor \\frac{n}{2}\\rfloor$, the size of newly formed subtree including $u$ is greater or equal to $\\lceil \\frac{n}{2}\\rceil$. Moving one or more edges away from $v_1$ will increase the size of this new subtree by one or more, and the vertex can not become centroid because $\\lceil \\frac{n}{2}\\rceil+1>\\lfloor \\frac{n+1}{2}\\rfloor$. The second part is easy to deduce from the above proof. We will solve this problem offline. First, we compute the Euler tour of the final tree and use \"range add query\" data structures like Binary indexed tree (BIT) or Segment tree to maintain each subtree's size. We will maintain the size of the largest subtree among the centroid's children $mx$. In the case where the centroid does not move, we just update $mx$ with the size of the subtree including the newly added vertex, otherwise, we set $mx$ to $\\lfloor \\frac{n}{2}\\rfloor$ due to the lemma. The time complexity is $\\mathcal{O}(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 500005;\nconst int LOG = 19;\n\nvector<int> adj[N];\nint tin[N], tout[N], timer;\nint par[LOG][N], bit[N], dep[N];\n\nvoid dfs(int u) {\n  tin[u] = ++timer;\n  dep[u] = dep[par[0][u]] + 1;\n  for (int k = 1; k < LOG; k++)\n    par[k][u] = par[k - 1][par[k - 1][u]];\n  for (int v : adj[u]) dfs(v);\n  tout[u] = timer;  \n}\n\nvoid add(int u) {\n  for (int i = tin[u]; i < N; i += i & -i)\n    bit[i]++;\n}\n\nint get(int u) {\n  int res = 0;\n  for (int i = tout[u]; i > 0; i -= i & -i)\n    res += bit[i];\n  for (int i = tin[u] - 1; i > 0; i -= i & -i)\n    res -= bit[i];\n  return res;\n}\n\nint jump(int u, int d) {\n  for (int k = 0; k < LOG; k++)\n    if (d >> k & 1) u = par[k][u];\n  return u;\n}\n\nbool cover(int u, int v) {\n  return tin[u] <= tin[v] && tin[v] <= tout[u];\n}\n\nvoid solve() {\n  int n; cin >> n;\n  \n  /// reset\n  timer = 0;\n  for (int i = 1; i <= n; i++) {\n    bit[i] = 0; adj[i].clear();\n  }\n  \n  for (int i = 2; i <= n; i++) {\n    cin >> par[0][i];\n    adj[par[0][i]].push_back(i);\n  }\n  dfs(1); add(1);\n  int cen = 1, max_siz = 0;\n  for (int u = 2; u <= n; u++) {\n    add(u);\n    if (cover(cen, u)) {\n      int v = jump(u, dep[u] - dep[cen] - 1);\n      int siz = get(v);\n      if (siz >= (u + 1) / 2) {\n        cen = v; max_siz = u / 2;\n      } else max_siz = max(max_siz, siz);\n    } else {\n      int siz = get(cen);\n      if (siz < (u + 1) / 2) {\n        cen = par[0][cen]; max_siz = u / 2;\n      } else max_siz = max(max_siz, u - siz);\n    }\n    cout << u - 2 * max_siz << \" \\n\"[u == n];\n  }\n}\n\nint main() {\n  cin.tie(0)->sync_with_stdio(0);\n  int t; cin >> t;\n  while (t--) solve();\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1827",
    "index": "E",
    "title": "Bus Routes",
    "statement": "There is a country consisting of $n$ cities and $n - 1$ bidirectional roads connecting them such that we can travel between any two cities using these roads. In other words, these cities and roads form a tree.\n\nThere are $m$ bus routes connecting the cities together. A bus route between city $x$ and city $y$ allows you to travel between any two cities in the simple path between $x$ and $y$ with this route.\n\nDetermine if for every pair of cities $u$ and $v$, you can travel from $u$ to $v$ using at most two bus routes.",
    "tutorial": "You do not need to consider all pairs of nodes, only some of them will do. Find an equivalent condition of the statement. Let $S(u)$ be the set of all nodes reachable by u using at most one route. Consider all $S(l)$ where $l$ is a leaf in the tree. First, notice that for a pair of nodes $(u, v)$ such that $u$ is not a leaf, we can find a leaf $l$ such that path $(l, v)$ fully covers path $(u, v)$. Therefore, we only need to care about whether all pairs of leaves can reach each other using at most $2$ routes. Lemma The condition above is equivalent to: There exists a node $c$ such that $c$ can reach all leaves by using at most one route. Proof The necessity part is trivial, so let's prove the sufficiency part. Let the leaves of the tree be $l_1, l_2, \\ldots, l_m$. Let $S(u)$ be the induced subgraph of all nodes reachable by $u$ using at most one route. If $u$ and $v$ is reachable within two routes, then the intersection of $S(v)$ and $S(u)$ is non-empty. We need to prove that the intersection of all $S(l_i)$ is non-empty. If $l_i$, $l_j$, and $l_k$ are pairwise reachable within two paths, then the intersection of $S(l_i)$, $S(l_j)$, and $S(l_k)$ must be pairwise non-empty. Since the graph is a tree, it follows trivially that intersection of $S(l_i)$, $S(l_j)$, and $S(l_k)$ must be non-empty. We can generalize this to all leaves, thus proving the sufficiency part. To check if an answer exists or not, we can use this trick from ko_osaga to find how many $S(l_i)$ covers each node in $\\mathcal O(n)$. The answer is YES when there is a node $c$ that is covered by all $S(l_i)$. To find the two candidates when the answer is NO, notice that one of them is the first leaf $l_x$ such that there is no node $c$ that is covered by $S(l_1), \\ldots, S(l_x)$. We can find $l_x$ with binary search. To find the other one, root the tree at $l_x$ and define $lift_u$ as the lowest node reachable by $u$ using at most one route. The other candidate is a node $l_y$ such that $lift_{l_y}$ is not in $S(l_x)$. Time complexity: $\\mathcal O(n \\log n)$. Tester's solution: Root the tree at some non-leaf vertex. Define $lift_u$ as the lowest node (minimum depth) reachable by $u$ using at most one route. Take the node $v$ with the deepest (maximum depth) $lift_v$. Then the answer for this problem is $\\texttt{YES}$ iff for every leaf $l$, either $l$ lie in $lift_v$ 's subtree or $l$ has a path to $lift_v$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nconst ll INF = 1e18;\nconst int maxn = 2e6 + 10;\nconst int mod = 1e9 + 7;\nconst int mo = 998244353;\nusing pi = pair < ll, ll > ;\nusing vi = vector < ll > ;\nusing pii = pair < pair < ll, ll > , ll > ;\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nvector < int > G[maxn];\nint n, m;\nint h[maxn];\nint eu[maxn];\npair < int, int > rmq[maxn][21];\nint l = 0;\nint st[maxn];\nint out[maxn];\nint low[maxn];\npair < int, int > ed[maxn];\nint par[maxn];\nint ok[maxn];\nint d[maxn];\nvoid dfs(int u, int pa) {\n  eu[++l] = u;\n  st[u] = l;\n  for (auto v: G[u]) {\n    if (v == pa) continue;\n    par[v] = u;\n    h[v] = h[u] + 1;\n    dfs(v, u);\n    eu[++l] = u;\n  }\n  out[u] = l;\n}\nvoid init() {\n  for (int j = 1; (1 << j) <= l; j++) {\n    for (int i = 1; i <= l; i++) {\n      rmq[i][j] = min(rmq[i][j - 1], rmq[i + (1 << (j - 1))][j - 1]);\n    }\n  }\n}\nint LCA(int u, int v) {\n  if (st[u] > st[v]) {\n    swap(u, v);\n  }\n  int k = log2(st[v] - st[u] + 1);\n  return min(rmq[st[u]][k], rmq[st[v] - (1 << k) + 1][k]).second;\n}\nbool check(int u, int pa, int c) {\n  if (st[pa] <= st[c] && st[c] <= out[pa]) {\n    if (st[c] <= st[u] && st[u] <= out[c]) {\n      return true;\n    }\n    return false;\n  }\n  return false;\n}\nvoid solve() {\n  cin >> n >> m;\n  l = 0;\n  for (int i = 1; i <= n; i++) {\n    G[i].clear();\n  }\n  for (int i = 1; i < n; i++) {\n    int x, y;\n    cin >> x >> y;\n    G[x].push_back(y);\n    G[y].push_back(x);\n  }\n  dfs(1, -1);\n  for (int i = 1; i <= l; i++) {\n    rmq[i][0] = {st[eu[i]], eu[i]};\n  }\n  init();\n  for (int i = 1; i <= n; i++) {\n    low[i] = i;\n    ok[i] = 0;\n  }\n  for (int i = 1; i <= m; i++) {\n    int x, y;\n    cin >> x >> y;\n    ed[i] = {x, y};\n    int u = LCA(x, y);\n    if (h[low[x]] > h[u]) {\n      low[x] = u;\n    }\n    if (h[low[y]] > h[u]) {\n      low[y] = u;\n    }\n  }\n  int need = 0;\n  for (int i = 2; i <= n; i++) {\n    if (low[i] != 1 && G[i].size() == 1) {\n      if (need == 0 || h[low[need]] < h[low[i]]) {\n        need = i;\n      }\n    }\n  }\n  if (need == 0) {\n    cout << \"YES\\n\";\n    return;\n  }\n  for (int i = 1; i <= m; i++) {\n    int u = LCA(ed[i].first, ed[i].second);\n    if (G[ed[i].first].size() == 1 && check(ed[i].second, u, low[need])) {\n      ok[ed[i].first] = 1;\n    }\n    if (G[ed[i].second].size() == 1 && check(ed[i].first, u, low[need])) {\n      ok[ed[i].second] = 1;\n    }\n  }\n  for (int i = 1; i <= n; i++) {\n    if (G[i].size() == 1) {\n      if (st[low[need]] <= st[i] && st[i] <= out[low[need]]) {\n        continue;\n      }\n      if (ok[i] == 0) {\n        cout << \"NO\\n\";\n        cout << need << \" \" << i << \"\\n\";\n        return;\n      }\n    }\n  }\n  cout << \"YES\\n\";\n  return;\n}\nsigned main() {\n  cin.tie(0), cout.tie(0) -> sync_with_stdio(0);\n  int t;\n  cin >> t;\n  while (t--) solve();\n  return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1827",
    "index": "F",
    "title": "Copium Permutation",
    "statement": "You are given a permutation $a_1,a_2,\\ldots,a_n$ of the first $n$ positive integers. A subarray $[l,r]$ is called copium if we can rearrange it so that it becomes a sequence of consecutive integers, or more formally, if $$\\max(a_l,a_{l+1},\\ldots,a_r)-\\min(a_l,a_{l+1},\\ldots,a_r)=r-l$$ For each $k$ in the range $[0,n]$, print out the \\textbf{maximum} number of copium subarrays of $a$ over all ways of rearranging the last $n-k$ elements of $a$.",
    "tutorial": "Call the last $n-k$ elements as special numbers. Observation: In optimal rearrangement, every maximal segment of special numbers will be placed on consecutive positions in either ascending order or descending order. For simplicity, from now on we will call maximal segment of special number as maximal segment. For example, take a permutation $p=[7, 5, 8, 1, 4, 2, 6, 3]$ and $k=2$, the maximal segments are $[1, 4]$, $[6, 6]$ and $[8, 8]$. We divide the set of copium subarrays into three parts, one for those lie entirely on prefix $p[1..k]$, one for those lie entirely on suffix $p[k+1..n]$, and one for the rest. The number of subarrays in the first part can be calculated with the algorithm used in 526F - Pudding Monsters. The number of subarrays in the second part can be easily deduced from above observation. Define an array $good=[good_1,good_2,\\ldots,good_m]$ such that for each $i$: $good_i<good_{i+1}$ and subarray $p[good_i..k]$ contains consecutive nonspecial numbers. For example, take a permutation $p=[1, 5, 4,3,7,8,9,2,10,6]$ and $k=5$, then $good=[1, 4, 5]$. We will process $good$ array from right to left while adding special numbers from left to right. Let us consider $good_i$, first add all special numbers which are missing from subarray $[good_i, k]$ at the end of current permutation. If $[good_i, k]$ is not already copium, we increase our answer by one. Denote $mn_i$ and $mx_i$ as the minimum and maximum number in subarray $[good_i, k]$. Loot at two maximal segments, one contains $mn_i-1$ and one contains $mx_i+1$. We can place them here to increase the answer. For example, let $n=10$, $k=5$, $good_i=3$ and the current permutation $p=[1, 10, 4, 5, 7, 6]$. The two maximal segments are $[2, 3]$ and $[8, 9]$. We can place them like $[1, 10, 4, 5, 7, 6, 8, 9, 3, 2]$ to increase the answer by 4. Furthermore, we can see that three good positions $3$, $4$ and $5$ benefit from maximal segment $[8, 9]$. In general, consider consecutive good positions $good_i, good_{i+1},\\ldots, good_j$ satisfying $mx_i=mx_{i+1}=\\ldots=mx_j$, all of them can benefit from the same maximal segment if for all $i\\le x< j$, subarray $[good_x..good_{x+1}-1]$ is copium $(*)$. There is a similar condition when we consider consecutive good positions having the same $mn$. So the algorithm goes like this: For each value of $mn$ and $mx$, find the longest segment of good positions satisfying condition $(*)$, then multiply with the length of corresponding maximal segment and add to the answer. We will calculate the answer for each $k$ from $0$ to $n$ in this order. We will store the longest segment for each prefix of $mn$-equivalent and $mx$-equivalent positions. Note that when going from $k-1$ to $k$, only a suffix of $good$ will no longer be good, so we can manually delete them one by one from right to left, then add $k$. There will be at most $2$ good positions we need to consider. The first one, of course, is $k$. If $p_{k-1}<p_k$ or $p_{k-1}>p_k$, let $j$ be the last position satisfying $p_j>p_k$ or $p_j<p_k$, the second one is the first good position after $j$ and it satisfies a property: It must be the last position in the $mn$-equivalent or $mx$-equivalent positions. The proof is left as an exercise. Therefore, updating this position will not affect the positions behind it. The overall complexity is $\\mathcal{O}(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing ll = long long;\n\nconst int N = 200005;\nconst int LOG = 18;\n\nint n, a[N], pos[N];\nint lef[N], rig[N];\n\nvector<int> st_max, st_min;\n\nvoid connect(int x, int y) {\n  rig[x] = y; lef[y] = x;\n}\n\nstruct range_min {\n  vector<int> spt[LOG];\n  \n  void build() {\n    for (int k = 0; k < LOG; k++)\n      spt[k].resize(n + 1);\n    for (int i = 1; i <= n; i++)\n      spt[0][i] = pos[i];\n    for (int k = 1; k < LOG; k++)\n      for (int i = 1; i + (1 << k) <= n + 1; i++) {\n        spt[k][i] = min(spt[k - 1][i],\n        spt[k - 1][i + (1 << (k - 1))]);\n      }\n  }\n  \n  int get_min_pos(int l, int r) {\n    int k = __lg(r - l + 1);\n    return min(spt[k][l], spt[k][r - (1 << k) + 1]);\n  }\n} rmq;\n\nint get_min(int i) {\n  return a[*lower_bound(st_min.begin(), st_min.end(), i)];\n}\n\nint get_max(int i) {\n  return a[*lower_bound(st_max.begin(), st_max.end(), i)];\n}\n\nstruct segtree1 {\n#define il i * 2\n#define ir i * 2 + 1\n  struct node {\n    int val, cnt, tag;\n  };\n  \n  node tree[N * 4];\n  \n  void build(int i, int l, int r) {\n    tree[i] = {l, 1, 0};\n    if (l < r) {\n      int m = (l + r) / 2;\n      build(il, l, m);\n      build(ir, m + 1, r);\n    }\n  }\n  \n  void add(int i, int l, int r, int x, int y, int v) {  \n    if (l >= x && r <= y) {\n      tree[i].val += v; tree[i].tag += v; return;\n    }\n\n    int m = (l + r) / 2;\n    if (m >= x) add(il, l, m, x, y, v);\n    if (m < y) add(ir, m + 1, r, x, y, v);\n  \n    tree[i].val = tree[il].val;\n    tree[i].cnt = tree[il].cnt;\n\n    if (tree[i].val > tree[ir].val) {\n      tree[i].val = tree[ir].val;\n      tree[i].cnt = tree[ir].cnt;\n    } else if (tree[i].val == tree[ir].val)\n      tree[i].cnt += tree[ir].cnt;\n\n    tree[i].val += tree[i].tag;\n  }\n#undef il\n#undef ir\n} seg1;\n\nstruct copium {\n  int curr, maxx, type;\n  \n  copium() {}\n  \n  copium(int curr, int maxx, int type):\n  curr(curr), maxx(max(maxx, curr)), type(type) {}\n};\n\ncopium lmin[N], lmax[N];\nll prefix, middle, suffix;\n\n/// cancer\nvoid calc(int i, int j, bool recalc) {\n  int imin = get_min(i), imax = get_max(i);\n  int jmin = get_min(j), jmax = get_max(j);\n  int type;\n  if (recalc) {\n    middle -= 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);\n    middle -= 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1);\n  }\n  \n  if (imax == jmax) {\n    if (!recalc)\n      middle -= 1ll * lmax[i].maxx * (rig[imax] - imax - 1);\n      \n    if (jmin - imin == j - i) type = 0;\n    else if (imin + j - i == lef[jmin] + 1) type = 1;\n    else type = 2;\n    \n    if (type == 2) lmax[j] = copium(1, lmax[i].maxx, type);\n    else if (lmax[i].type == 0)\n      lmax[j] = copium(lmax[i].curr + 1, lmax[i].maxx, type);\n    else lmax[j] = copium(2, lmax[i].maxx, type);\n    \n  } else lmax[j] = {1, 1, 3};\n  if (imin == jmin) {\n    if (!recalc)\n      middle -= 1ll * lmin[i].maxx * (imin - lef[imin] - 1);\n      \n    if (imax - jmax == j - i) type = 0;\n    else if (imax + i - j == rig[jmax] - 1) type = 1;\n    else type = 2;\n    \n    if (type == 2) lmin[j] = copium(1, lmin[i].maxx, type);\n    else if (lmin[i].type == 0)\n      lmin[j] = copium(lmin[i].curr + 1, lmin[i].maxx, type);\n    else lmin[j] = copium(2, lmin[i].maxx, type);\n    \n  } else lmin[j] = {1, 1, 3};\n  \n  middle += 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);\n  middle += 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1);\n}\n\nint main() {\n  cin.tie(0)->sync_with_stdio(0);\n  int t; cin >> t;\n  while (t--) {\n    cin >> n;\n    for (int i = 1; i <= n; i++) {\n      cin >> a[i]; pos[a[i]] = i;\n      lef[i] = rig[i] = 0;\n    }\n    \n    st_min.assign(1, 0);\n    st_max.assign(1, 0);\n    \n    set<int> sorted;\n    sorted.insert(0);\n    sorted.insert(n + 1);\n    \n    prefix = 0;\n    suffix = 1ll * n * (n + 1) / 2;\n    middle = 0;\n    \n    // k = 0\n    cout << suffix << ' ';\n    \n    lef[n] = 0; rig[0] = n;\n    \n    seg1.build(1, 1, n); rmq.build();\n    \n    vector<int> good;\n    \n    for (int i = 1; i <= n; i++) {\n      \n      while (good.size()) { \n        int j = good.back();\n        int jmin = get_min(j), jmax = get_max(j);\n        \n        if (rmq.get_min_pos(min(jmin, a[i]), max(jmax, a[i])) < j) {\n          middle -= 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);\n          middle -= 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1);\n          good.pop_back();\n          if (good.size()) {\n            if (lmax[j].type < 3)\n              middle += 1ll * lmax[good.back()].maxx * (rig[jmax] - jmax - 1);\n            if (lmin[j].type < 3)\n              middle += 1ll * lmin[good.back()].maxx * (jmin - lef[jmin] - 1);\n          }\n        } else break;\n      }\n      \n      if (good.size()) {\n        int j = good.back();\n        int jmin = get_min(j), jmax = get_max(j);\n        middle -= 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);\n        middle -= 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1); \n      }\n      \n      auto it = sorted.upper_bound(a[i]);\n      suffix -= 1ll * (*it - a[i]) * (a[i] - *prev(it));\n      connect(*prev(it), a[i]); connect(a[i], *it);\n      sorted.insert(a[i]);\n      \n      while (st_max.size() > 1 && a[st_max.back()] < a[i]) {\n        seg1.add(1, 1, n, st_max[st_max.size() - 2] + 1,\n        st_max.back(), a[i] - a[st_max.back()]);\n        st_max.pop_back();\n      }\n      \n      while (st_min.size() > 1 && a[st_min.back()] > a[i]) {\n        seg1.add(1, 1, n, st_min[st_min.size() - 2] + 1,\n        st_min.back(), a[st_min.back()] - a[i]);\n        st_min.pop_back(); \n      }\n      \n      st_max.push_back(i); st_min.push_back(i);\n      \n      if (good.size()) {\n        int j = good.back();\n        int jmin = get_min(j), jmax = get_max(j);\n        middle += 1ll * lmax[j].maxx * (rig[jmax] - jmax - 1);\n        middle += 1ll * lmin[j].maxx * (jmin - lef[jmin] - 1); \n        calc(j, i, 0);\n      } else {\n        lmax[i] = lmin[i] = {1, 1, 3};\n        middle += rig[a[i]] - lef[a[i]] - 2;\n      }\n\n      good.push_back(i);\n      if (st_min.size() >= 2) {\n        int k = upper_bound(good.begin(), good.end(),\n        st_min[st_min.size() - 2]) - good.begin();\n        if (k > 0 && k < good.size())\n          calc(good[k - 1], good[k], 1);\n      }\n      if (st_max.size() >= 2) {\n        int k = upper_bound(good.begin(), good.end(),\n        st_max[st_max.size() - 2]) - good.begin();\n        if (k > 0 && k < good.size())\n          calc(good[k - 1], good[k], 1);\n      }\n      \n      cout << prefix + good.size() + middle + suffix << ' ';\n      \n      prefix += seg1.tree[1].cnt; \n    }\n    cout << '\\n';\n  }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1828",
    "index": "A",
    "title": "Divisible Array",
    "statement": "You are given a positive integer $n$. Please find an array $a_1, a_2, \\ldots, a_n$ that is perfect.\n\nA perfect array $a_1, a_2, \\ldots, a_n$ satisfies the following criteria:\n\n- $1 \\le a_i \\le 1000$ for all $1 \\le i \\le n$.\n- $a_i$ is divisible by $i$ for all $1 \\le i \\le n$.\n- $a_1 + a_2 + \\ldots + a_n$ is divisible by $n$.",
    "tutorial": "Remember the sum of the first $n$ positive integers? Every positive integer is divisible by $1$. Consider the array $a = \\left[1, 2, \\ldots, n\\right]$ that satisfies the second condition. It has the sum of $1 + 2 + \\dots + n = \\frac{n(n+1)}{2}$. One solution is to notice that if we double every element $(a=\\left[2, 4, 6, \\ldots, 2n\\right])$, the sum becomes $\\frac{n(n+1)}{2} \\times 2 = n(n + 1)$, which is divisible by $n$. Another solution is to increase the value of $a_1$ until the sum becomes divisible by $n$. This works because every integer is divisible by $1$, and we only need to increase $a_1$ by at most $n$. Time complexity: $\\mathcal{O}(n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define fi first\n#define se second\nconst int N=2e6+1;\nconst ll mod=998244353;\nll n,m;\nll a[N],b[N];\nvoid solve(){\n\tcin >> n;\n\tll s=0;\n\tfor(int i=n; i>=2 ;i--){\n\t\ta[i]=i;\n\t\ts=(s+i)%n;\n\t}\n\ta[1]=n-s;\n\tfor(int i=1; i<=n ;i++) cout << a[i] << ' ';\n\tcout << '\\n';\n}\nint main(){\n\tios::sync_with_stdio(false);cin.tie(0);\n\tint t;cin >> t;\n\twhile(t--){\n\t\tsolve();\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1828",
    "index": "B",
    "title": "Permutation Swap",
    "statement": "You are given an \\textbf{unsorted} permutation $p_1, p_2, \\ldots, p_n$. To sort the permutation, you choose a constant $k$ ($k \\ge 1$) and do some operations on the permutation. In one operation, you can choose two integers $i$, $j$ ($1 \\le j < i \\le n$) such that $i - j = k$, then swap $p_i$ and $p_j$.\n\nWhat is the \\textbf{maximum} value of $k$ that you can choose to sort the given permutation?\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2, 3, 1, 5, 4]$ is a permutation, but $[1, 2, 2]$ is not a permutation ($2$ appears twice in the array) and $[1, 3, 4]$ is also not a permutation ($n = 3$ but there is $4$ in the array).\n\nAn unsorted permutation $p$ is a permutation such that there is at least one position $i$ that satisfies $p_i \\ne i$.",
    "tutorial": "In order to move $p_i$ to its right position, what does the value of $k$ have to satisfy? In order to move $p_i$ to position $i$, it is easy to see that $|p_i - i|$ has to be divisible by $k$. So, $|p_1 - 1|, |p_2 - 2|, \\ldots, |p_n - n|$ has to be all divisible by $k$. The largest possible value of $k$ turns out to be the greatest common divisor of integers $|p_1 - 1|, |p_2 - 2|, \\ldots, |p_n - n|$. Time complexity: $\\mathcal{O}(n + \\log{n})$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nsigned main() {\n    \n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n \n    int t;\n    cin >> t;\n    while (t--) {\n    \tint n, res = 0;\n    \tcin >> n;\n    \tfor (int i = 1; i <= n; i++) {\n    \t\tint x; cin >> x;\n    \t\tres = __gcd(res, abs(x - i));\n    \t}\n    \tcout << res << \"\\n\";\n    }\n    \n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1829",
    "index": "A",
    "title": "Love Story",
    "statement": "Timur loves codeforces. That's why he has a string $s$ having length $10$ made containing only lowercase Latin letters. Timur wants to know how many indices string $s$ \\textbf{differs} from the string \"codeforces\".\n\nFor example string $s =$ \"{co\\textbf{ol}for\\textbf{s}e\\textbf{z}}\" differs from \"codeforces\" in $4$ indices, shown in bold.\n\nHelp Timur by finding the number of indices where string $s$ differs from \"codeforces\".\n\nNote that you can't reorder the characters in the string $s$.",
    "tutorial": "You need to implement what is written in the statement. You need to compare the given string $s$ with the string \"codeforces\" character by character, counting the number of differences. We know that the length of $s$ is $10$, so we can simply iterate through both strings and compare each character at the same index. If the characters are the same, we move on to the next index. If they are different, we count it as a difference and move on to the next index. Once we have compared all $10$ characters, we output the number of differences.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve()\n{\n    string s, c = \"codeforces\";\n    cin >> s;\n    int ans = 0;\n    for(int i = 0; i < 10; i++)\n    {\n        if(s[i] != c[i])\n        {\n            ans++;\n        }\n    }\n    cout << ans << endl;\n}\n\nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1829",
    "index": "B",
    "title": "Blank Space",
    "statement": "You are given a binary array $a$ of $n$ elements, a binary array is an array consisting only of $0$s and $1$s.\n\nA blank space is a segment of \\textbf{consecutive} elements consisting of only $0$s.\n\nYour task is to find the length of the longest blank space.",
    "tutorial": "We can iterate through the array $a$ and keep track of the length of the current blank space. Whenever we encounter a $0$, we increase the length of the current blank space, and whenever we encounter a $1$, we check if the current blank space is longer than the previous longest blank space. If it is, we update the length of the longest blank space. Finally, we return the length of the longest blank space. The time complexity of this algorithm is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    int a[n];\n    int cnt = 0, ans = 0;\n    for(int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n        if(a[i] == 0)\n        {\n            cnt++;\n        }\n        else\n        {\n            ans = max(ans, cnt);\n            cnt = 0;\n        }\n    }\n    cout << max(ans, cnt) << endl;\n}\n\nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1829",
    "index": "C",
    "title": "Mr. Perfectly Fine",
    "statement": "Victor wants to become \"Mr. Perfectly Fine\". For that, he needs to acquire a certain set of skills. More precisely, he has $2$ skills he needs to acquire.\n\nVictor has $n$ books. Reading book $i$ takes him $m_i$ minutes and will give him some (possibly none) of the required two skills, represented by a binary string of length $2$.\n\nWhat is the minimum amount of time required so that Victor acquires all of the two skills?",
    "tutorial": "You can classify the books into four types \"00\", \"01\", \"10\", \"11\". We will take a book of any type at most once and wont take a book that learns a single skill if that skill is already learned, so there are only two cases to look at We take the shortest \"01\" and the the shortest \"10\". We take the shortest \"11\". Out of these options, output the shortest one.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\n#define ll long long\n\n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n\n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nvoid solve() {\n    int n; cin >> n;\n    map<string, int> mp;\n    mp[\"00\"] = mp[\"01\"] = mp[\"10\"] = mp[\"11\"] = 1e9;\n    int ans = 1e9;\n    for(int i = 0; i < n; ++i) {\n        int x; cin >> x; string s; cin >> s;\n        mp[s] = min(mp[s], x);\n    }\n    if(min(mp[\"11\"], mp[\"10\"] + mp[\"01\"]) > (int)1e6) {\n        cout << \"-1\\n\";\n    } else {\n        cout << min(mp[\"11\"], mp[\"10\"] + mp[\"01\"]) << \"\\n\";\n    }\n}\n\nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1829",
    "index": "D",
    "title": "Gold Rush",
    "statement": "Initially you have a single pile with $n$ gold nuggets. In an operation you can do the following:\n\n- Take any pile and split it into two piles, so that one of the resulting piles has exactly twice as many gold nuggets as the other. (All piles should have an integer number of nuggets.)\n\n\\begin{center}\n{\\small One possible move is to take a pile of size $6$ and split it into piles of sizes $2$ and $4$, which is valid since $4$ is twice as large as $2$.}\n\\end{center}\n\nCan you make a pile with \\textbf{exactly} $m$ gold nuggets using zero or more operations?",
    "tutorial": "We can solve this problem recursively. Let the current pile have $n$ gold nuggets. If $n=m$, then we can make a pile with exactly $m$ gold nuggets by not doing any operations. If $n$ is not a multiple of $3$, then it is not possible to make a move, because after a move we split $n$ into $x$ and $2x$, so $n=x+2x=3x$ for some integer $x$, meaning $n$ has to be a multiple of $3$. Finally, if $n$ is a multiple of $3$, then we can split the pile into two piles with $\\frac{n}{3}$ and $\\frac{2n}{3}$ gold nuggets, and we can recursively check if we can make a pile with exactly $m$ gold nuggets. By the Master Theorem, the time complexity is $\\mathcal{O}(n^{\\log_32}) \\approx \\mathcal{O}(n^{0.631})$. Most compilers and languages optimize the recursion enough for this to pass comfortably. (The model solution in C++ runs in 15 milliseconds.)",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool ok(int n, int m) {\n\tif (n == m) {return true;}\n\telse if (n % 3 != 0) {return false;}\n\telse {return (ok(n / 3, m) || ok(2 * n / 3, m));}\n}\n\nvoid solve() {\n\tint n, m;\n\tcin >> n >> m;\n\tcout << (ok(n, m) ? \"YES\" : \"NO\") << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1829",
    "index": "E",
    "title": "The Lakes",
    "statement": "You are given an $n \\times m$ grid $a$ of non-negative integers. The value $a_{i,j}$ represents the depth of water at the $i$-th row and $j$-th column.\n\nA lake is a set of cells such that:\n\n- each cell in the set has $a_{i,j} > 0$, and\n- there exists a path between any pair of cells in the lake by going up, down, left, or right a number of times and without stepping on a cell with $a_{i,j} = 0$.\n\nThe volume of a lake is the sum of depths of all the cells in the lake.\n\nFind the largest volume of a lake in the grid.",
    "tutorial": "We can approach this problem using Depth First Search (DFS) or Breadth First Search (BFS) on the given grid. The idea is to consider each cell of the grid as a potential starting point for a lake, and explore all the cells reachable from it by only moving up, down, left or right, without stepping on any cell with depth $0$. If we reach a dead end, or a cell with depth $0$, we backtrack and try another direction. During this exploration, we keep track of the sum of depths of all the cells that we have visited. This sum gives us the volume of the current lake. When we have explored all the reachable cells from a starting point, we compare the volume of this lake with the maximum volume found so far, and update the maximum if necessary. To implement this approach, we can use a nested loop to iterate through all the cells of the grid. For each cell, we check if its depth is greater than $0$, and if it has not already been visited in a previous lake. If these conditions are satisfied, we start a DFS/BFS from this cell, and update the maximum volume found so far. See the implementation for more details. The time complexity is $\\mathcal{O}(mn)$.",
    "code": "#include <bits/stdc++.h>\n#define startt ios_base::sync_with_stdio(false);cin.tie(0);\ntypedef long long  ll;\nusing namespace std;\n#define vint vector<int>\n#define all(v) v.begin(), v.end()\n#define MOD 1000000007\n#define MOD2 998244353\n#define MX 1000000000\n#define MXL 1000000000000000000\n#define PI (ld)2*acos(0.0)\n#define pb push_back\n#define sc second\n#define fr first\n#define endl '\\n'\n#define ld long double\n#define NO cout << \"NO\" << endl\n#define YES cout << \"YES\" << endl\n\nint n, m;\nbool vis[1005][1005];\nint a[1005][1005];\n\nint dfs(int i, int j)\n{\n    vis[i][j] = true;\n    int ans = a[i][j];\n    if(i != 0 && a[i-1][j] != 0 && !vis[i-1][j])\n    {\n        ans+=dfs(i-1, j);\n    }\n    if(i != n-1 && a[i+1][j] != 0 && !vis[i+1][j])\n    {\n        ans+=dfs(i+1, j);\n    }\n    if(j != 0 && a[i][j-1] != 0 && !vis[i][j-1])\n    {\n        ans+=dfs(i, j-1);\n    }\n    if(j != m-1 && a[i][j+1] != 0 && !vis[i][j+1])\n    {\n        ans+=dfs(i, j+1);\n    }\n    return ans;\n}\n\nvoid solve()\n{\n    cin >> n >> m;\n    for(int i = 0; i < n; i++)\n    {\n        for(int j = 0; j < m; j++)\n        {\n            vis[i][j] = false;\n            cin >> a[i][j];\n        }\n    }\n    int ans = 0;\n    for(int i = 0; i < n; i++)\n    {\n        for(int j = 0; j < m; j++)\n        {\n            if(!vis[i][j] && a[i][j] != 0)\n            {\n                ans = max(ans, dfs(i, j));\n            }\n        }\n    }\n    cout << ans << endl;\n}\n\nint32_t main(){\n    startt\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1829",
    "index": "F",
    "title": "Forever Winter",
    "statement": "A snowflake graph is generated from two integers $x$ and $y$, both greater than $1$, as follows:\n\n- Start with one central vertex.\n- Connect $x$ new vertices to this central vertex.\n- Connect $y$ new vertices to \\textbf{each} of these $x$ vertices.\n\nFor example, below is a snowflake graph for $x=5$ and $y=3$. \\begin{center}\n{\\small The snowflake graph above has a central vertex $15$, then $x=5$ vertices attached to it ($3$, $6$, $7$, $8$, and $20$), and then $y=3$ vertices attached to each of those.}\n\\end{center}\n\nGiven a snowflake graph, determine the values of $x$ and $y$.",
    "tutorial": "The degree of a vertex is the number of vertices connected to it. We can count the degree of a vertex by seeing how many times it appears in the input. Let's count the degrees of the vertices in a snowflake graph. The starting vertex has degree $x$. Each of the $x$ newly-generated vertices has degree $y+1$ (they have $y$ new neighbors, along with the starting vertex). Each of the $x \\times y$ newly-generated vertices has degree $1$ (they are only connected to the previous vertex). CountDegree$1$$x$$x$$y+1$$xy$$1$ However, there is an edge case. If $x=y+1$, then the first two rows combine: CountDegree$x+1$$x = y + 1$$xy$$1$ The time complexity is $\\mathcal{O}(n+m)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 1000000007;\n\nvoid solve() {\n\tint n, m;\n\tcin >> n >> m;\n\tint cnt[n + 1];\n\tfor (int i = 1; i <= n; i++) {\n\t\tcnt[i] = 0;\n\t}\n\tfor (int i = 0; i < m; i++) {\n\t\tint u, v;\n\t\tcin >> u >> v;\n\t\tcnt[u]++;\n\t\tcnt[v]++;\n\t}\n\tmap<int, int> cnts;\n\tfor (int i = 1; i <= n; i++) {\n\t\tcnts[cnt[i]]++;\n\t}\n\tvector<int> v;\n\tfor (auto p : cnts) {\n\t\tv.push_back(p.second);\n\t}\n\tsort(v.begin(), v.end());\n\tif (v.size() == 3) {\n\t\tcout << v[1] << ' ' << v[2] / v[1] << '\\n';\n\t}\n\telse {\n\t\tcout << v[0] - 1 << ' ' << v[1] / (v[0] - 1) << '\\n';\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1829",
    "index": "G",
    "title": "Hits Different",
    "statement": "In a carnival game, there is a huge pyramid of cans with $2023$ rows, numbered in a regular pattern as shown.\n\n\\begin{center}\n{\\small If can $9^2$ is hit initially, then all cans colored red in the picture above would fall.}\n\\end{center}\n\nYou throw a ball at the pyramid, and it hits a single can with number $n^2$. This causes all cans that are stacked on top of this can to fall (that is, can $n^2$ falls, then the cans directly above $n^2$ fall, then the cans directly above those cans, and so on). For example, the picture above shows the cans that would fall if can $9^2$ is hit.\n\nWhat is the \\textbf{sum} of the numbers on all cans that fall? Recall that $n^2 = n \\times n$.",
    "tutorial": "There are many solutions which involve going row by row and using some complicated math formulas, but here is a solution that requires no formulas and is much quicker to code. The cans are hard to deal with, but if we replace them with a different shape, a diamond, we get the following: To avoid finding the row and column, we can instead iterate through the cells in order $1, 2, 3, \\dots$, that is, we go diagonal-by-diagonal in the grid above. Now, make a separate array $\\texttt{ans}$, and keep track of the answer for each cell from $1$ to $10^6$ as we find its prefix sum. This avoids having to do any complicated math or binary search to find the row and column for the prefix sum. See the implementation for more details. The time complexity is $\\mathcal{O}(n)$ precomputation with $\\mathcal{O}(1)$ per test case.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long ans[2000007];\nlong long a[1500][1500] = {}, curr = 1;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tcout << ans[n] << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\n\tfor (int i = 1; i < 1500; i++) {\n\t\tfor (int j = i - 1; j >= 1; j--) {\n\t\t\ta[j][i - j] = a[j - 1][i - j] + a[j][i - j - 1] - a[j - 1][i - j - 1] + curr * curr;\n\t\t\tans[curr] = a[j][i - j];\n\t\t\tcurr++;\n\t\t}\n\t}\n\t\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1829",
    "index": "H",
    "title": "Don't Blame Me",
    "statement": "Sadly, the problem setter couldn't think of an interesting story, thus he just asks you to solve the following problem.\n\nGiven an array $a$ consisting of $n$ positive integers, count the number of \\textbf{non-empty} subsequences for which the bitwise $\\mathsf{AND}$ of the elements in the subsequence has exactly $k$ set bits in its binary representation. The answer may be large, so output it modulo $10^9+7$.\n\nRecall that the subsequence of an array $a$ is a sequence that can be obtained from $a$ by removing some (possibly, zero) elements. For example, $[1, 2, 3]$, $[3]$, $[1, 3]$ are subsequences of $[1, 2, 3]$, but $[3, 2]$ and $[4, 5, 6]$ are not.\n\nNote that $\\mathsf{AND}$ represents the bitwise AND operation.",
    "tutorial": "We can notice that the numbers are pretty small (up to $63$) and the AND values will be up to $63$ as well. Thus, we can count the number of subsequences that have AND value equal to $x$ for all $x$ from $0$ to $63$. We can do this using dynamic programming. Let's denote $dp_{ij}$ as the number of subsequences using the first $i$ elements that have a total AND value of $j$. The transitions are quite simple. We can iterate over all $j$ values obtained previously and update the values respectively: We have three cases: The first case is when we don't use the $i$-th value. Here we just update the $dp_{ij}$ in the following way: $dp[i][j] = dp[i][j] + dp[i - 1][j]$. The second case is when we use the $i$-th value. Here we update the $dp[i][a[i] \\text{&} j]$ in the following way: $dp[i][a[i] \\text{&} j] = dp[i][a[i] \\text{&} j] + dp[i - 1][j]$. The third case is starting a new subsequence with just the $i$-th element. Thus, we update $dp[i][a[i]] = dp[i][a[i]] + 1$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nconst int mod = 1e9 + 7;\nvoid solve() {\n    int n, x; cin >> n >> x;\n    vector<int> a(n + 1);\n    vector<vector<int>> dp(n + 1, vector<int>(1 << 6, 0));\n    for(int i = 1; i <= n; ++i) {\n        cin >> a[i];\n        for(int mask = 0; mask < (1 << 6); ++mask) {\n            dp[i][mask] += dp[i - 1][mask];\n            if(dp[i][mask] >= mod) dp[i][mask] -= mod;\n            dp[i][mask & a[i]] += dp[i - 1][mask];\n            if(dp[i][mask & a[i]] >= mod) dp[i][mask & a[i]] -= mod;\n        }\n        dp[i][a[i]] = (dp[i][a[i]] + 1) % mod;\n    }\n    int ans = 0;\n    for(int mask = 0; mask < (1 << 6); ++mask) {\n        if(__builtin_popcount(mask) == x) {\n            ans = (ans + dp[n][mask]) % mod;\n        }\n    }\n    cout << ans << \"\\n\";\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1830",
    "index": "A",
    "title": "Copil Copac Draws Trees",
    "statement": "Copil Copac is given a list of $n-1$ edges describing a tree of $n$ vertices. He decides to draw it using the following algorithm:\n\n- Step $0$: Draws the first vertex (vertex $1$). Go to step $1$.\n- Step $1$: For every edge in the input, in order: if the edge connects an already drawn vertex $u$ to an undrawn vertex $v$, he will draw the undrawn vertex $v$ and the edge. After checking every edge, go to step $2$.\n- Step $2$: If all the vertices are drawn, terminate the algorithm. Else, go to step $1$.\n\nThe number of readings is defined as the number of times Copil Copac performs step $1$.\n\nFind the number of readings needed by Copil Copac to draw the tree.",
    "tutorial": "What is the answer if $n=3$? The previous case can be generalised to find the answer for any tree. This problem can be solved via dynamic programming. From here on out, step $1$ from the statement will be called a \"scan\". Let $dp[i]$ be the number of scans needed to activate node $i$, and $id[i]$ be the index (in the order from the input) of the edge which activated node $i$. Intially, since only $1$ is active, $dp[1]=1$ and $id[1]=0$. We will perform a dfs traversal starting from node $1$. When we process an edge $(u,v)$, one of the following two cases can happen: If $index((u,v)) \\ge id[u]$, we can visit $v$ in the same scan as $u$: $dp[v]=dp[u]$, $id[v]=index((u,v))$ If $index((u,v)) \\lt id[u]$, $v$ will be visited in the next scan after $dp[u]$: $dp[v]=dp[u]+1$, $id[v]=index((u,v))$ The answer is $max_{i=1}^n(dp[i])$. Time complexity per test case: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nconst int NMAX = 3e5 + 5, INF = 1e9;\n\nint n, f[NMAX], d[NMAX];\nstd :: vector < std :: pair < int, int > > G[NMAX];\n\nvoid DFS(int node, int t) {\n    f[node] = true;\n\n    for (int i = 0; i < G[node].size(); ++ i) {\n        int u = G[node][i].first, c = G[node][i].second;\n\n        if (f[u] == false) {\n            d[u] = (c < t) + d[node];\n            DFS(u, c);\n        }\n    }\n\n    return;\n}\n\nint main() {\n    std :: ios_base :: sync_with_stdio(false);\n    std :: cin.tie(nullptr);\n    \n    int tc;\n    \n    std :: cin >> tc;\n    \n    while (tc --) {\n        std :: cin >> n;\n    \n        for (int i = 1, u, v; i < n; ++ i) {\n            std :: cin >> u >> v;\n    \n            G[u].push_back({v, i});\n            G[v].push_back({u, i});\n        }\n        \n        for (int i = 1; i <= n; ++ i)\n            f[i] = false;\n    \n        d[1] = 0;\n        DFS(1, n);\n    \n        int Max = 0;\n    \n        for (int i = 1; i <= n; ++ i)\n            Max = std :: max(Max, d[i]);\n    \n        std :: cout << Max << \"\\n\";\n        \n        for (int i = 1; i <= n; ++ i)\n            G[i].clear();\n    }\n\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1830",
    "index": "B",
    "title": "The BOSS Can Count Pairs",
    "statement": "You are given two arrays $a$ and $b$, both of length $n$.\n\nYour task is to count the number of pairs of integers $(i,j)$ such that $1 \\leq i < j \\leq n$ and $a_i \\cdot a_j = b_i+b_j$.",
    "tutorial": "Since $b_i \\le n$ and $b_j \\le n$, $b_i+b_j = a_i \\cdot a_j \\le 2 \\cdot n$. Since $a_i \\cdot a_j \\le 2 \\cdot n$, then $\\min(a_i,a_j) \\le \\sqrt{2 \\cdot n}$. Since $b_i \\le n$ and $b_j \\le n$, $b_i+b_j = a_i \\cdot a_j \\le 2 \\cdot n$. Therefore, $\\min(a_i,a_j) \\le \\sqrt{2 \\cdot n}$. Let $lim=\\sqrt{2 \\cdot n}$ and $fr[a_i][b_i]$ be the number of pairs $(a_i,b_i)$ from the input such that $a_i \\le lim$. A pair $(i,j)$ is good if it satisfies $a_i \\cdot a_j=b_i+b_j$. Firstly, we'll count the number of good pairs $(i,j)$ such that $a_i=a_j$. Since $min(a_i,a_j) \\le lim$, we can see that $a_i=a_j \\le lim$. This sum can be written as: $\\frac{\\sum_{i=1}^{n}fr[a_i][a_i \\cdot a_i - b_i]-\\sum_{i=1}^{lim}fr[i][\\frac{i \\cdot i}{2}]}{2}$ The remaining good pairs will have $a_i \\neq a_j$, and instead of counting the pairs which have $i \\lt j$, we can count the pairs which have $a_i \\gt a_j$. Since $a_j=min(a_i,a_j)$, we can say that $a_j \\le lim$. Substituting $a_j$ for $j$, this second sum can be written as: $\\sum_{i=1}^n \\sum_{j=1}^{min(a_i-1,\\frac{2\\cdot n}{a_i})}fr[j][a_i \\cdot j-b_i]$ Since we've already established that $j \\le lim = \\sqrt{2 \\cdot n}$, calculating this sum takes $O(n\\sqrt{n})$ time. Be especially careful when calculating these sums, as $a_i \\cdot a_i - b_i$ and $a_i \\cdot j-b_i$ can end up being either negative or greater than $n$. Time complexity per testcase: $O(n \\sqrt n)$",
    "code": "\nfor _ in range(int(input())):\n    n = int(input())\n    \n    ta = list(map(int, input().split()))\n    tb = list(map(int, input().split()))\n    \n    a = [(x, y) for x, y in zip(ta, tb)]\n    a.sort()\n    \n    cnt = [0] * (2 * n + 1)\n    pr = 0\n    ans = 0\n    \n    for i in range(n):\n        if pr != a[i][0]:\n            pr = a[i][0]\n            \n            if pr * pr > 2 * n:\n                break\n                \n            cnt = [0] * (2 * n + 1)\n            for j in range(i + 1, n):\n                t = a[i][0] * a[j][0] - a[j][1]\n                if t >= 0 and t <= 2 * n:\n                    cnt[t] += 1\n        \n        ans += cnt[a[i][1]]\n        \n        if i + 1 < n:\n            t = a[i][0] * a[i + 1][0] - a[i + 1][1]\n            if t >= 0 and t <= 2 * n:\n                cnt[t] -= 1\n    \n    print(ans)\n",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1830",
    "index": "C",
    "title": "Hyperregular Bracket Strings",
    "statement": "You are given an integer $n$ and $k$ intervals. The $i$-th interval is $[l_i,r_i]$ where $1 \\leq l_i \\leq r_i \\leq n$.\n\nLet us call a \\textbf{regular} bracket sequence$^{\\dagger,\\ddagger}$ of length $n$ hyperregular if for each $i$ such that $1 \\leq i \\leq k$, the substring $\\overline{s_{l_i} s_{l_{i}+1} \\ldots s_{r_i}}$ is also a regular bracket sequence.\n\nYour task is to count the number of hyperregular bracket sequences. Since this number can be really large, you are only required to find it modulo $998\\,244\\,353$.\n\n$^\\dagger$ A bracket sequence is a string containing only the characters \"(\" and \")\".\n\n$^\\ddagger$ A bracket sequence is called regular if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), (()(())) and the empty string are regular, while )(, ((), and (()))( are not.",
    "tutorial": "While not necessarily a hint, this problem cannot be solved without knowing that there are $C_n=\\frac{1}{n+1}\\binom{2n}{n}$ Regular Bracket Strings of length $2 \\cdot n$. What's the answer if $q=1$? What's the answer if $q=2$ and the two intervals partially overlap? Based on the previous hint, we can get rid of all partially overlapping intervals. The remaining intervals will have a tree-like structure. Finding the tree is actually unnecessary and also very difficult. The brackets on the positions covered by the same subset of intervals must form an RBS. Hashing. Xor hashing specifically. First and foremost, the number of regular bracket strings of length $2 \\cdot n$ is equal to $C_n=\\frac{1}{n+1}\\binom{2n}{n}$. Secondly, for a bracket string $\\overline{s_1s_2 \\ldots s_k}$, let: $f(s_i) = \\begin{cases} 1, & \\text{if }s_i=\\text{'('} \\\\ -1, & \\text{if }s_i=\\text{')'} \\end{cases}$ $\\Delta_i=\\sum_{j=1}^i f(s_j)$ A bracket string $\\overline{s_1s_2 \\ldots s_k}$ is a regular bracket string if both of the following statements are true: $\\Delta_k=0$ $\\Delta_k=0$ $\\Delta_i \\ge 0, i=\\overline{1,k}$ $\\Delta_i \\ge 0, i=\\overline{1,k}$ From now on we'll call a set of indices $i_1 < i_2 < \\ldots < i_k$ a group if $\\overline{s_{i_1}s_{i_2}\\ldots s_{i_k}}$ must be an RBS. There are two main cases to consider, both of which can be proven with the aforementioned conditions for a string to be an RBS: Let's consider two intervals $[l_1,r_1]$ and $[l_2,r_2]$ such that $l_1 \\le l_2 \\le r_2 \\le r_1$. The two groups formed by these intervals are: $[l_2,r_2]$ $[l_1,l_2-1] \\cup [r_2+1,r_1]$ Let's consider two intervals $[l_1,r_1]$ and $[l_2,r_2]$ such that $l_1 \\lt l_2 \\le r_1 \\lt r_2$. The three groups formed by these two intervals are: $[l_1,l_2-1]$ $[l_2,r_1]$ $[r_1+1,r_2]$ By taking both of these cases into account, we can conclude that all indices $i_k$ covered by the same subset of intervals are part of the same group. Finding the subset of intervals which cover a certain index $i$ can be implemented using difference arrays and xor hashing. Each interval $[l_i,r_i]$ will be assigned a random 64-bit value $v_i$. The value of a subset of intervals $i_1,i_2,\\ldots,i_k$ is equal to $v_{i_1} \\wedge v_{i_2} \\wedge \\ldots \\wedge v_{i_k}$. For each interval $[l_i,r_i]$, $\\text{diff}[l_i] \\wedge = v_i$, $\\text{diff}[r_i+1] \\wedge = v_i$. The value of the subset of intervals which cover position $i$ is equal to $\\text{diff}[1] \\wedge \\text{diff}[2] \\wedge \\ldots \\wedge \\text{diff}[i]$. Time complexity: $O(maxn \\cdot log(mod))$ for precomputing every $C_n$, and $O(k\\cdot log(k))$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nconst int NMAX=3e5+5, MOD=998244353;\n\nmt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count());\nuniform_int_distribution<ll> rnd(0,LLONG_MAX);\n\nll fact[NMAX], invfact[NMAX], C[NMAX];\n\nll binPow(ll x, ll y){\n    ll ans=1;\n    for(;y ;y>>=1, x = x*x%MOD)\n        if(y&1)\n            ans = ans*x%MOD;\n    return ans;\n}\nmap<ll,ll> diff,freq;\nvoid add_interval(ll l, ll r){\n    ll Hash = rnd(gen);\n    diff[l] ^= Hash, diff[r+1] ^= Hash;\n}\nvoid tc(){\n    ll n,k;\n    cin>>n>>k;\n    diff.clear(), freq.clear();\n    add_interval(1,n); /// the initial string must be an RBS\n\n    for(ll i=0;i<k;i++){\n        ll l,r;\n        cin>>l>>r;\n        add_interval(l,r);\n    }\n    ll Hash = diff[1];\n\n    for(map<ll,ll> :: iterator it=next(diff.begin()); it!=diff.end(); it++){\n        freq[Hash] += it->first - prev(it)->first;\n        Hash ^= it->second;\n    }\n\n    ll ans=1;\n\n    for(const auto& it : freq)\n        ans=ans*C[it.second]%MOD;\n\n    cout<<ans<<'\\n';\n}\n\nint main()\n{\n    fact[0] = invfact[0] = 1;\n    for(ll i=1; i<NMAX; i++){\n        fact[i] = fact[i-1] * i % MOD;\n        invfact[i] = binPow(fact[i], MOD - 2);\n    }\n\n    for(ll i=0; i*2<NMAX; i++) C[i*2] = fact[i*2] * invfact[i] % MOD * invfact[i+1] % MOD;\n\n    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    ll t;\n    cin>>t;\n    while(t--)\n        tc();\n    return 0;\n}\n",
    "tags": [
      "combinatorics",
      "greedy",
      "hashing",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1830",
    "index": "D",
    "title": "Mex Tree",
    "statement": "You are given a tree with $n$ nodes. For each node, you either color it in $0$ or $1$.\n\nThe value of a path $(u,v)$ is equal to the MEX$^\\dagger$ of the colors of the nodes from the shortest path between $u$ and $v$.\n\nThe value of a coloring is equal to the sum of values of all paths $(u,v)$ such that $1 \\leq u \\leq v \\leq n$.\n\nWhat is the maximum possible value of any coloring of the tree?\n\n$^{\\dagger}$ The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$ because $0$, $1$, $2$, and $3$ belong to the array, but $4$ does not.",
    "tutorial": "Why is bipartite coloring not always optimal? How good is a bipartite coloring actually? Disclaimer: I ( tibinyte2006 ) wanted to cut $O(n \\sqrt{n})$ memory because I thought that setting 1024 MB memory limit would spoil the solution. So only blame me for this. We will do a complementary problem which is finding the minimum loss of a coloring. The initial cost is the maximum possible cost, $n \\cdot (n+1)$. If we analyze how good a bipartite coloring of the given tree is we can note that $loss \\le 2 \\cdot n$ Now suppose the tree has a connected component of size $k$. We can note that in such a coloring $loss \\ge \\frac{k \\cdot (k+1)}{2}$ By the $2$ claims above, we can note that in an optimal coloring, the maximum size $k$ of a connected component respects $\\frac{k \\cdot (k+1)}{2} \\le 2 \\cdot n$. Thus we can safely say $k \\le \\sqrt{4 \\cdot n}$. Now let $dp_{i,j,color}$ be the minimum loss if we color the subtree of $i$ and the connected component of vertex $i$ has size $j$. We can calculate this in a knapsack style by adding subtrees successively. The computation takes $O(n \\cdot \\sqrt{n})$ if we use the $7$-th trick from this blog. Now we are only left to optimize memory, since now it's $O(n \\cdot \\sqrt{n})$. We can directly apply this to get linear memory. However, the bound of $k \\le \\sqrt{4 \\cdot n}$ is overestimated, for $n=200000$ it can be proven that the worst case for $k$ is $258$. Assume have a connected component of size $k$ we want it to be colored $0$ across all optimal colorings. Then we can attach to each node some subtrees such that after flipping its whole subtree the total cost doesn't increase. We will assume all subtrees are leaves for simplicity. Doing such, we can get some inequalities about the number of leaves we need to attatch to each node. In a star tree, the number of leaves we should attatch to nodes has the smallest sum.",
    "code": "#include <bits/stdc++.h>\n#define int long long\n\nusing namespace std;\n\nconst int lim = 893;\nconst int inf = 1e16;\n\nstruct dp_state\n{\n    vector<int> a;\n    vector<int> b;\n    void init()\n    {\n        a.resize(lim + 1, inf);\n        b.resize(lim + 1, inf);\n        a[1] = 1;\n        b[1] = 2;\n    }\n};\n\nint32_t main()\n{\n    cin.tie(nullptr)->sync_with_stdio(false);\n    int q;\n    cin >> q;\n    while (q--)\n    {\n        int n;\n        cin >> n;\n        vector<vector<int>> g(n + 1);\n        vector<int> sz(n + 1);\n\n        for (int i = 1; i < n; ++i)\n        {\n            int x, y;\n            cin >> x >> y;\n            g[x].push_back(y);\n            g[y].push_back(x);\n        }\n\n        function<int(int, int)> shuffle_kids = [&](int node, int parent)\n        {\n            int sz = 1;\n            pair<int, int> best;\n            for (int i = 0; i < (int)g[node].size(); ++i)\n            {\n                if (g[node][i] != parent)\n                {\n                    int sz2 = shuffle_kids(g[node][i], node);\n\n                    best = max(best, {sz2, i});\n\n                    sz += sz2;\n                }\n            }\n            if (!g[node].empty())\n            {\n                swap(g[node][0], g[node][best.second]);\n            }\n            return sz;\n        };\n        shuffle_kids(1, 0);\n\n        vector<vector<int>> merged(2 * lim + 1, vector<int>(2, inf));\n\n        function<dp_state(int, int)> dfs = [&](int node, int parent)\n        {\n            dp_state dp;\n            sz[node] = 1;\n            bool hasinit = false;\n            for (auto i : g[node])\n            {\n                if (i != parent)\n                {\n                    dp_state qui = dfs(i, node);\n                    if (!hasinit)\n                    {\n                        dp.init();\n                        hasinit = true;\n                    }\n                    for (int j = 0; j <= min(sz[node], lim) + min(sz[i], lim); ++j)\n                    {\n                        merged[j][0] = merged[j][1] = inf;\n                    }\n                    for (int k = 1; k <= min(sz[node], lim); ++k)\n                    {\n                        for (int l = 1; l <= min(sz[i], lim); ++l)\n                        {\n                            merged[k][0] = min(merged[k][0], dp.a[k] + qui.b[l]);\n                            merged[k][1] = min(merged[k][1], dp.b[k] + qui.a[l]);\n                            merged[k + l][0] = min(merged[k + l][0], dp.a[k] + qui.a[l] + k * l);\n                            merged[k + l][1] = min(merged[k + l][1], dp.b[k] + qui.b[l] + k * l * 2);\n                        }\n                    }\n                    sz[node] += sz[i];\n                    for (int k = 1; k <= min(sz[node], lim); ++k)\n                    {\n                        dp.a[k] = merged[k][0];\n                        dp.b[k] = merged[k][1];\n                    }\n                }\n            }\n            if (!hasinit)\n            {\n                dp.init();\n                hasinit = true;\n            }\n            return dp;\n        };\n        dp_state dp = dfs(1, 0);\n        int ans = inf;\n        for (int i = 1; i <= lim; ++i)\n        {\n            ans = min(ans, dp.a[i]);\n            ans = min(ans, dp.b[i]);\n        }\n        cout << n * (n + 1) - ans << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1830",
    "index": "E",
    "title": "Bully Sort",
    "statement": "On a permutation $p$ of length $n$, we define a bully swap as follows:\n\n- Let $i$ be the index of the largest element $p_i$ such that $p_i \\neq i$.\n- Let $j$ be the index of the smallest element $p_j$ such that $i < j$.\n- Swap $p_i$ and $p_j$.\n\nWe define $f(p)$ as the number of bully swaps we need to perform until $p$ becomes sorted. Note that if $p$ is the identity permutation, $f(p)=0$.\n\nYou are given $n$ and a permutation $p$ of length $n$. You need to process the following $q$ updates.\n\nIn each update, you are given two integers $x$ and $y$. You will swap $p_x$ and $p_y$ and then find the value of $f(p)$.\n\nNote that the updates are persistent. Changes made to the permutation $p$ will apply when processing future updates.",
    "tutorial": "First of all, we notice that if some element moves left, it will never move right. Proving this is not hard, imagine $S$ to be the set of suffix minimas. Then if an element is in $S$ we know that $p_x \\le x$. Since after every bully swap an element cannot disappear from $S$ and after each bully swap, the $2$ swapped elements can only get closer to their desired position, we conclude the proof. Obviously, if an element moves right, it will never move left since it will continue to move right until it reaches its final position. By the $2$ claims above, we conclude that left and right movers are distinct. Now suppose we swap indicies $i$ and $j$ and note that such swap kills $2 \\cdot (j-i) - 1$ inversions and the left mover $j$ moves $j-i$ steps. Now the magic is that if we let $s$ be the sum over $2 \\cdot (i-p_i)$ for all left movers we have $s - ans = inversions$, thus our answer is just $s-inversions$. Now to handle the data structure part, we just need to be able to calculate inversions while being able to perform point updates. There are many ways to do this, for example for using a fenwick tree and a bitwise trie/ordered_set in $O(nlog^2n)$.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n#define ii pair<int,int>\n#define i4 tuple<int,int,int,int>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nstruct FEN{ //we want to count the reverse\n\tint arr[500005];\n\t\n\tvoid update(int i,int k){\n\t\ti=500005-i;\n\t\t\n\t\twhile (i<500005){\n\t\t\tarr[i]+=k;\n\t\t\ti+=i&-i;\n\t\t}\n\t}\n\t\n\tint query(int i){\n\t\ti=500005-i;\n\t\t\n\t\tint res=0;\n\t\twhile (i){\n\t\t\tres+=arr[i];\n\t\t\ti-=i&-i;\n\t\t}\n\t\treturn res;\n\t}\n} fen;\n\nint n,q;\nint arr[500005];\nlong long ans[50005];\n\nvoid dnc(int l,int r,vector<i4> upd,vector<i4> que){\n\tvector<i4> updl,updr;\n\tvector<i4> quel,quer;\n\t\n\tint m=l+r>>1;\n\t\n\tfor (auto [a,b,c,d]:upd){\n\t\tif (c<=m) updl.pub({a,b,c,d});\n\t\telse updr.pub({a,b,c,d});\n\t}\n\t\n\tfor (auto [a,b,c,d]:que){\n\t\tif (c<=m) quel.pub({a,b,c,d});\n\t\telse quer.pub({a,b,c,d});\n\t}\n\t\n\tint i=0;\n\tfor (auto it:quer){\n\t\twhile (i<sz(updl) && get<0>(updl[i])<get<0>(it)){\n\t\t\tfen.update(get<1>(updl[i]),get<3>(updl[i]));\n\t\t\ti++;\n\t\t}\n\t\t\n\t\tans[get<2>(it)]+=fen.query(get<1>(it))*get<3>(it);\n\t}\n\twhile (i){\n\t\ti--;\n\t\tfen.update(get<1>(updl[i]),-get<3>(updl[i]));\n\t}\n\t\n\tif (l!=m) dnc(l,m,updl,quel);\n\tif (m+1!=r) dnc(m+1,r,updr,quer);\n}\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tcin>>n>>q;\n\trep(x,1,n+1) cin>>arr[x];\n\t\n\tvector<i4> upd,que;\n\t\n\trep(x,1,n+1) upd.pub({x,arr[x],-1,1});\n\trep(x,1,n+1) que.pub({x,arr[x],0,-1});\n\trep(x,1,n+1) ans[0]+=abs(x-arr[x]);\n\t\n\trep(x,1,q+1){\n\t\tint a,b;\n\t\tcin>>a>>b;\n\t\t\n\t\tif (a==b) continue;\n\t\tif (arr[a]<arr[b]) ans[x]--;\n\t\telse ans[x]++;\n\t\t\n\t\tupd.pub({a,arr[a],x-1,-1});\n\t\tupd.pub({b,arr[b],x-1,-1});\n\t\tans[x]-=abs(a-arr[a])+abs(b-arr[b]);\n\t\t\n\t\tswap(arr[a],arr[b]);\n\t\t\n\t\tupd.pub({a,arr[a],x,1});\n\t\tupd.pub({b,arr[b],x,1});\n\t\tans[x]+=abs(a-arr[a])+abs(b-arr[b]);\n\t\t\n\t\tque.pub({b,arr[b],x,-2});\n\t\tque.pub({b,arr[a],x,2});\n\t\tque.pub({a,arr[b],x,2});\n\t\tque.pub({a,arr[a],x,-2});\n\t\t\n\t}\n\t\n\tsort(all(upd)),sort(all(que));\n\t\n\tdnc(-1,q,upd,que);\n\t\n\trep(x,1,q+1) ans[x]+=ans[x-1];\n\trep(x,1,q+1) cout<<ans[x]<<\" \"; cout<<endl;\n}\n",
    "tags": [
      "data structures",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1830",
    "index": "F",
    "title": "The Third Grace",
    "statement": "You are given $n$ intervals and $m$ points on the number line. The $i$-th intervals covers coordinates $[l_i,r_i]$ and the $i$-th point is on coordinate $i$ and has coefficient $p_i$.\n\nInitially, all points are not activated. You should choose a subset of the $m$ points to activate. For each of $n$ interval, we define its cost as:\n\n- $0$, if there are no activated points in the interval;\n- the coefficient of the activated point with the \\textbf{largest coordinate} within it, otherwise.\n\nYour task is to maximize the sum of the costs of all intervals by choosing which points to activate.",
    "tutorial": "Let $dp_i$ be the maximum sum of costs of activated points that are $< i$ over all states that has point $i$ activated. When we transition from $dp_i$ to $dp_j$, we need to add the cost contributed by point $i$. The number of ranges where point $i$ is the largest coordinate within it are the ranges $[l,r]$ which satisfy $l \\leq i \\leq r < j$. So we have $dp_j = \\max\\limits_{i < j}(dp_i + p_i \\cdot S_{i,j})$ where $S_{i,j}$ is the number of ranges $[l,r]$ which satisfy $l \\leq i \\leq r < j$. Now, we note that $S_{i,j} z$ With some work, we can get calculate this $dp$ in $O(n^2)$. But this will be too slow, let's try to speed this up. Let us define $dp_{i,j} = \\max\\limits_{k \\leq i}(dp_k + p_k \\cdot S_{k,j})$. We have $dp_{j-1,j}=dp_j$. Our goal is to go from (implictly) storing $dp_{i,i+1},dp_{i,i+2},\\ldots,dp_{i,n}$ to $dp_{i+1,i+2},dp_{i+1,i+3},\\ldots,dp_{i+1,n}$. As $dp_i + p_i \\cdot S_{i,j}$ looks like a linear function w.r.t. $S_{i,j}$, we can try to use convex hull data structures to maintain it. Let's figure out how $S_{i+1,j}$ relates to $S_{i,j}$. We need to subtract the number of ranges with $r=i$ and add the number of ranges with $l=i+1$ and $r < j$. This corresponds to $S_{i,*}$ and $S_{i+1,*}$ differing by amortized $O(1)$ suffix increment updates. Also, note that $S_{i,*}$ is non-decreasing. So we want to support the following data structure: Initially we have an arrays $A$ and $X$ that are both initially $0$. Handle the following updates: 1 m c $A_i \\gets \\max(A_i,m \\cdot X_i + c)$ for all $i$ 2 j k $X_i \\gets X_i + k$ for all $j \\leq i$. It is guaranteed that $X$ will always be non-decreasing. 3 i find $A_i$ This can be maintained in a lichao tree in $O(log ^2)$ time. In each lichao node, we need to store $s,m,e$, the start, middle and end indices and their corresponding $X$ values $X_s,X_m,X_e$ respectively. This way, we can support operations $1$ and $3$ already. To support operation $2$, note that in a lichao tree, you can use $O(log^2)$ time to push down all lines that covers a certain point (refer to https://codeforces.com/blog/entry/86731). This way, all lines in the li chao tree are in $[1,j)$ or $[j,n]$, so you can do lazy updates on both the coordinates of the lines and the $X$ values. The time complexity is $O(n \\log^2)$. There is another solution that works in $O(m \\log^3)$ that we are unable to optimize further yet. Let us flip the array so that the condition is on the activated point with the smallest coordinate. Then we have $dp_j = \\max\\limits_{i < j}(dp_i + p_j \\cdot S_{i,j})$ where $S_{i,j}$ counts the number of ranges $[l,r]$ such that $i< l \\leq j \\leq r$. Now, we want to store the linear function $dp_i + x \\cdot S_{i,j}$ in some sort of data structure so that we can evaluate the maximum value with $x=p_j$. Unfortunately, the value of $S_{i,j}$ can change by suffix additions, similar to above. But since $S_{i,j}$ is non-increasing here, that means the optimal $i$ that maximizes $dp_i + x \\cdot S_{i,j}$ decreases when $x$ increases. That is, for $l_1 \\leq r_1< l_2 \\leq r_2$ and we have two data structures that can get the maximum $f_j(x)=dp_i+x \\cdot S_{i,j}$ for $l_j \\leq i \\leq r_j$ respectively. We can combine these $2$ data structures to make it for $[l_1,r_1] \\cup [l_2,r_2]$ by binary searching the point $X$ where for all $x \\leq X$, $f_1(x) \\leq f_2(x)$ and for all $X \\leq x,f_1(x) \\geq f_2(x)$. Since querying this data structure takes $O(\\log n)$, it takes $O(\\log ^2)$ time to combine two such data structures. If we use a segment tree, we only need to rebuild $O(\\log^3)$ different data structures (the rest can be handled using lazy tags), giving us a time complexity of $O(\\log^3)$.",
    "code": "\n#include <bits/stdc++.h>\n#define all(x) (x).begin(),(x).end()\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\n//#define int ll\n#define sz(x) ((int)(x).size())\n\nusing pii = pair<ll,ll>;\nusing tii = tuple<int,int,int>;\n\nconst int nmax = 5e5 + 5, qmax = 2e6 + 5;\nconst ll inf = 1e18 + 5; \n\nstruct line {\n  ll m = 0, b = -inf;\n  ll operator()(const ll& x) const {\n     return m * x + b;\n  }\n  bool operator ==(const line& x) const { return m == x.m && b == x.b; }\n};\n\nint M;\n\nnamespace AINT {\n  struct Node {\n    int vl = 0, vmid = 0, vr = 0;\n    line val = line{0, -inf};\n    Node() {;}\n    void operator += (const int &x) { vl += x, vmid += x, vr += x; val.b -= val.m * x; }\n  } aint[qmax * 4];\n  int lazy[qmax * 4];\n  \n  void push(int node) {\n    lazy[2 * node] += lazy[node];\n    aint[2 * node] += lazy[node];\n    lazy[2 * node + 1] += lazy[node];\n    aint[2 * node + 1] += lazy[node];\n    lazy[node] = 0;\n  }\n  void pushline(line x, int node = 1, int cl = 0, int cr = M) {\n    bool l = x(aint[node].vl) > aint[node].val(aint[node].vl), m = x(aint[node].vmid) > aint[node].val(aint[node].vmid), r = x(aint[node].vr) > aint[node].val(aint[node].vr);\n    if(m) swap(x, aint[node].val);\n    if(cl == cr || x == line() || l == r) return;\n    \n    int mid = cl + cr >> 1;\n    push(node);\n    if(m != l) pushline(x, 2 * node, cl, mid);\n    else pushline(x, 2 * node + 1, mid + 1, cr);\n    return;\n  }\n  void add(int l, int node = 1, int cl = 0, int cr = M) {\n    if(cl >= l) {\n      lazy[node]++;\n      aint[node] += 1;\n      return;\n    }\n    if(cr < l) return;\n    int mid = cl + cr >> 1;\n    \n    push(node);\n    \n    pushline(aint[node].val, 2 * node, cl, mid);\n    pushline(aint[node].val, 2 * node + 1, mid + 1, cr);\n    aint[node].val = line{0, -inf};\n    \n    add(l, 2 * node, cl, mid);\n    add(l, 2 * node + 1, mid + 1, cr);\n    aint[node].vl = aint[2 * node].vl;\n    aint[node].vmid = aint[2 * node].vr;\n    aint[node].vr = aint[2 * node + 1].vr;\n  }\n  pii query(ll p, int node = 1, int cl = 0, int cr = M) {\n    if(cl == cr) return pii{aint[node].val(aint[node].vl), aint[node].vl};\n    int mid = cl + cr >> 1;\n    push(node);\n    auto [mxv, atrv] = p <= mid? query(p, 2 * node, cl, mid) : query(p, 2 * node + 1, mid + 1, cr);\n    return pii{max(mxv, aint[node].val(atrv)), atrv};\n  } \n  \n  void init(int node = 1, int cl = 0, int cr = M) {\n    aint[node] = Node();\n    lazy[node] = 0;\n    if(cl == cr) return;\n    int mid = cl + cr >> 1;\n    init(2 * node, cl, mid);\n    init(2 * node + 1, mid + 1, cr);\n    return;\n  }\n};\n\nvector<int> atraddp[qmax];\nll val[qmax];\n\nvoid testcase() {\n  int n, m;\n  cin >> n >> m;\n  M = m + 2;\n  for(int i = 0, l, r; i < n; i++) {\n    cin >> l >> r;\n    atraddp[l].emplace_back(r + 1);\n  }\n  for(int i = 1; i <= m; i++)\n    cin >> val[i];\n  \n  AINT::init();\n  AINT::pushline({0, 0});\n  \n  for(int i = 0; i < m + 2; i++) {\n    for(auto x : atraddp[i])\n      AINT::add(x);\n    auto [a, b] = AINT::query(i);\n    //cerr << a << ' ' << b << '\\n';\n    AINT::pushline({val[i], a - val[i] * b});\n  }\n  \n  for(int i = 0; i < m + 2; i++)\n    atraddp[i].clear();\n  \n  cout << AINT::query(m + 1).first << '\\n';\n}\n\nsigned main() {\n  cin.tie(0) -> sync_with_stdio(0);\n  int t;\n  cin >> t;\n  while(t--) testcase();\n  \n}\n\n/**\n      Anul asta se da centroid.\n-- Surse oficiale\n*/\n\n\n",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1831",
    "index": "A",
    "title": "Twin Permutations",
    "statement": "You are given a permutation$^\\dagger$ $a$ of length $n$.\n\nFind any permutation $b$ of length $n$ such that $a_1+b_1 \\le a_2+b_2 \\le a_3+b_3 \\le \\ldots \\le a_n+b_n$.\n\nIt can be proven that a permutation $b$ that satisfies the condition above always exists.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "If $a_i+b_i \\le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. Building on the idea from the first hint, can we build a permutation $b$ such that $a_1+b_1=a_2+b_2=\\ldots=a_n+b_n$? Since $a_i+b_i \\le a_{i+1}+b_{i+1}$, then $a_i+b_i$ can be equal to $a_{i+1}+b_{i+1}$. Therefore, any permutation $b$ which satisfies $a_1+b_1=a_2+b_2=\\ldots=a_n+b_n$ is a valid answer. If $b_i=n+1-a_i$, then: $b$ is a permutation; $a_1+b_1=a_2+b_2=\\ldots=a_n+b_n=n+1$ Consequently, $b=[n+1-a_1,n+1-a_2,\\ldots,n+1-a_i,\\ldots,n+1-a_n]$ is a valid answer. Time complexity per test case : $O(N)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\nvoid tc(){\n    ll n;\n    cin>>n;\n    for(ll i=0;i<n;i++){\n        ll x;\n        cin>>x;\n        cout<<n+1-x<<' ';\n    }\n    cout<<'\\n';\n}\nint main()\n{\n    ios_base::sync_with_stdio(false); cin.tie(0);\n    ll t; cin>>t; while(t--)\n        tc();\n    return 0;\n}\n\n",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1831",
    "index": "B",
    "title": "Array merging",
    "statement": "You are given two arrays $a$ and $b$ both of length $n$.\n\nYou will merge$^\\dagger$ these arrays forming another array $c$ of length $2 \\cdot n$. You have to find the maximum length of a subarray consisting of equal values across all arrays $c$ that could be obtained.\n\n$^\\dagger$ A merge of two arrays results in an array $c$ composed by successively taking the first element of either array (as long as that array is nonempty) and removing it. After this step, the element is appended to the back of $c$. We repeat this operation as long as we can (i.e. at least one array is nonempty).",
    "tutorial": "When we merge two arrays $a$ and $b$, we can force the resulting array to have $[a_{l_1},a_{l_1+1},\\ldots,a_{r_1},b_{l_2},b_{l_2+1},\\ldots,b_{r_1}]$ as a subarray, for some $1 \\le l_1 \\le r_1 \\le n$ and $1 \\le l_2 \\le r_2 \\le n$. If $a_{l_1}=b_{l_1}$, then we can achieve a contiguous sequence of $(r_1-l_1+1)+(r_2-l_2+1)$ equal elements in the resulting array. Let $max_a(x)$ be the length of the longest subarray from $a$ containing only elements equal to $x$. If $x$ doesn't appear in $a$, then $max_a(x)=0$. Similarly, let $max_b(x)$ be the length of the longest subarray from $b$ containing only elements equal to $x$. If $x$ doesn't appear in $b$, then $max_b(x)=0$. $max_a$ and $max_b$ can be computed in $O(N)$ by scanning the array while updating current maximal subarray. When merging two arrays, it is possible to force a particular subarray $[a_{l_1},a_{l_1+1},\\ldots,a_{r_1}]$ to be adjacent to another particular subarray $[b_{l_2},b_{l_2+1},\\ldots,b_{r_2}]$ in the merged array. We can construct the merged array as follows: $[a_1,a_2,\\ldots,a_{l_1-1}]+[b_1,b_2,\\ldots,b_{l_2-1}]+[a_{l_1},a_{l_1+1},\\ldots,a_{r_1},b_{l_2},b_{l_2+1},\\ldots,b_{r_2}]+[\\ldots]$ If $a_{l_1}=b_{l_2}$, then the merged array will have a subarray consisting of $(r_1-l_1+1)+(r_2-l_2+1)$ equal elements. Therefore, the answer is equal to: $max_{i=1}^{2 \\cdot n}(max_a(i)+max_b(i))$ Time complexity per testcase: $O(N)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint32_t main()\n{\n    cin.tie(nullptr)->sync_with_stdio(false);\n    int q;\n    cin >> q;\n    while (q--)\n    {\n        int n;\n        cin >> n;\n        vector<int> a(n + 1);\n        vector<int> b(n + 1);\n        for (int i = 1; i <= n; ++i)\n        {\n            cin >> a[i];\n        }\n        for (int i = 1; i <= n; ++i)\n        {\n            cin >> b[i];\n        }\n        vector<int> fa(n + n + 1);\n        vector<int> fb(n + n + 1);\n        int p = 1;\n        for (int i = 2; i <= n; ++i)\n        {\n            if (a[i] != a[i - 1])\n            {\n                fa[a[i - 1]] = max(fa[a[i - 1]], i - p);\n                p = i;\n            }\n        }\n        fa[a[n]] = max(fa[a[n]], n - p + 1);\n\n        p = 1;\n        for (int i = 2; i <= n; ++i)\n        {\n            if (b[i] != b[i - 1])\n            {\n                fb[b[i - 1]] = max(fb[b[i - 1]], i - p);\n                p = i;\n            }\n        }\n        fb[b[n]] = max(fb[b[n]], n - p + 1);\n\n        int ans = 0;\n        for (int i = 1; i <= n + n; ++i)\n        {\n            ans = max(ans, fa[i] + fb[i]);\n        }\n\n        cout << ans << '\\n';\n    }\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1832",
    "index": "A",
    "title": "New Palindrome",
    "statement": "A palindrome is a string that reads the same from left to right as from right to left. For example, abacaba, aaaa, abba, racecar are palindromes.\n\nYou are given a string $s$ consisting of lowercase Latin letters. The string $s$ is a palindrome.\n\nYou have to check whether it is possible to rearrange the letters in it to get \\textbf{another} palindrome (not equal to the given string $s$).",
    "tutorial": "Let's look at the first $\\left\\lfloor\\frac{|s|}{2}\\right\\rfloor$ characters. If all these characters are equal, then there is no way to get another palindrome. Otherwise, there are at least two different characters, you can swap them (and the characters symmetrical to them on the right half of the string), and get a palindrome different from the given one.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    string s;\n    cin >> s;\n    s = s.substr(0, s.size() / 2);\n    int k = unique(s.begin(), s.end()) - s.begin();\n    cout << (k == 1 ? \"NO\" : \"YES\") << '\\n';\n  }\n}",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1832",
    "index": "B",
    "title": "Maximum Sum",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$, where all elements are different.\n\nYou have to perform \\textbf{exactly} $k$ operations with it. During each operation, you do \\textbf{exactly one} of the following two actions (you choose which to do yourself):\n\n- find \\textbf{two minimum elements} in the array, and delete them;\n- find \\textbf{the maximum element} in the array, and delete it.\n\nYou have to calculate the maximum possible sum of elements in the resulting array.",
    "tutorial": "The first instinct is to implement a greedy solution which removes either two minimums or one maximum, according to which of the options removes elements with smaller sum. Unfortunately, this doesn't work even on the examples (hint to the participants of the round: if your solution gives a different answer on the examples, most probably you should try to find an error in your solution, not send messages to the author that their answers are definitely wrong). Okay, we need something other. Let's notice that the order of operations does not matter: deleting two minimums and then maximum is the same as choosing the other way around. So, we can iterate on the number of operations $m$ when we remove the two minimums; then the resulting array is the array $a$ from which we removed $2m$ minimums and $(k-m)$ maximums. How to quickly calculate the sum of remaining elements? First of all, sorting the original array $a$ won't hurt, since the minimums then will always be in the beginning of the array, and the maximums will be in the end. After the array $a$ is sorted, every operation either deletes two leftmost elements, or one rightmost element. So, if we remove $2m$ minimums and $(k-m)$ maximums, the elements that remain form the segment from the position $(2m+1)$ to the position $(n-(k-m))$ in the sorted array; and the sum on it can be computed in $O(1)$ with prefix sums. Time complexity: $O(n \\log n)$.",
    "code": "for _ in range(int(input())):\n\tn, k = map(int, input().split())\n\ta = sorted(list(map(int, input().split())))\n\tans = 0\n\tpr = [0] * (n + 1)\n\tfor i in range(n):\n\t\tpr[i + 1] = pr[i] + a[i]\n\tfor i in range(k + 1):\n\t\tans = max(ans, pr[n - (k - i)] - pr[2 * i])\n\tprint(ans)",
    "tags": [
      "brute force",
      "sortings",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1832",
    "index": "C",
    "title": "Contrast Value",
    "statement": "For an array of integers $[a_1, a_2, \\dots, a_n]$, let's call the value $|a_1-a_2|+|a_2-a_3|+\\cdots+|a_{n-1}-a_n|$ the contrast of the array. Note that the contrast of an array of size $1$ is equal to $0$.\n\nYou are given an array of integers $a$. Your task is to build an array of $b$ in such a way that all the following conditions are met:\n\n- $b$ is not empty, i.e there is at least one element;\n- $b$ is a subsequence of $a$, i.e $b$ can be produced by deleting some elements from $a$ (maybe zero);\n- the contrast of $b$ is equal to the contrast of $a$.\n\nWhat is the minimum possible size of the array $b$?",
    "tutorial": "Let's rephrase the problem in the following form: let the elements of the array be points on a coordinate line. Then the absolute difference between two adjacent elements of the array can be represented as the distance between two points, and the contrast of the entire array is equal to the total distance to visit all points in the given order. In this interpretation, it becomes obvious that removing any set of points does not increase contrast. Since the resulting contrast should be equal to the original one, we can only remove elements from the array that do not decrease the contrast. First of all, let's look at consecutive equal elements, it is obvious that you can delete all of them except one, and the contrast of the array will not change. In some languages, you can use a standard function to do this - for example, in C++ you can use unique. After that, let's look at such positions $i$ that $a_{i - 1} < a_i < a_{i + 1}$; you can delete the $i$-th element, because $|a_{i - 1} - a_i| + |a_i - a_{i + 1}| = |a_{i - 1} - a_{i + 1}|$. Similarly, for positions $i$, where $a_{i - 1} > a_i > a_{i + 1}$, the element can be removed. In all other cases, removing the element will decrease the contrast.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int& x : a) cin >> x;\n    n = unique(a.begin(), a.end()) - a.begin();\n    int ans = n;\n    for (int i = 0; i + 2 < n; ++i) {\n      ans -= (a[i] < a[i + 1] && a[i + 1] < a[i + 2]);\n      ans -= (a[i] > a[i + 1] && a[i + 1] > a[i + 2]);\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1832",
    "index": "D1",
    "title": "Red-Blue Operations (Easy Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the maximum values of $n$ and $q$}.\n\nYou are given an array, consisting of $n$ integers. Initially, all elements are red.\n\nYou can apply the following operation to the array multiple times. During the $i$-th operation, you select an element of the array; then:\n\n- if the element is red, it increases by $i$ and becomes blue;\n- if the element is blue, it decreases by $i$ and becomes red.\n\nThe operations are numbered from $1$, i. e. during the first operation some element is changed by $1$ and so on.\n\nYou are asked $q$ queries of the following form:\n\n- given an integer $k$, what can the largest minimum in the array be if you apply \\textbf{exactly} $k$ operations to it?\n\nNote that the operations don't affect the array between queries, all queries are asked on the initial array $a$.",
    "tutorial": "Let's try applying the operation to a single element multiple times. You can see that when you apply an operation an odd number of times, the element always gets larger. Alternatively, applying an operation an even amount of times always makes it smaller (or equal in case of $0$). Thus, generally, we would want to apply an odd number of operations to as many elements as we can. Let's start by investigating an easy case: $k \\le n$. Since there are so few operations, you can avoid subtracting from any element at all. Just one operation to each of $k$ elements. Which elements should get this operation? Obviously, $k$ smallest elements. If you don't pick at least one of them, it'll remain as the minimum of the array. If you do, the minimum will get larger than any of them. Another greedy idea is where to apply each operation to. We should add $k$ to the minimum element, $k-1$ to the second minimum and so on. You can show that it is always optimal by contradiction. What if $k > n$? Then we have to subtract from some elements. First, recognize that there's no more than one element that will become smaller in the optimal answer. Consider an answer where at least two elements get smaller and move the later operation from one to another. Now both of them become larger. Moreover, for parity reasons, if $k \\bmod 2 = n \\bmod 2$, you can increase all elements. Otherwise, you have to decrease exactly one. Another greedy idea. You somewhat want the pair of operations (increase, decrease) to change the element as small as possible. In particular, you can always make the change equal to $-1$. To show it, you can look at some decreasing operation such that an increasing operation goes right before it and they are applied to different elements. You can swap them. They remain the same types. However, both elements get only larger. In the end, all adjacent increasing and decreasing operations go to the same element. Now, let's think of the answer as the following sequence: adjacent pairs of (increase, decrease) and the separate increase operations that are applied no more than once to each element. Since all blocks do $-1$, only the values in the lone increase operations affect the answer value. Obviously, we would want these lone increases to be $k, k - 1, \\dots, k - t$, where $t$ is the number of changed elements ($n-1$ or $n$). Once again, you can show that you can always rearrange the operations to obtain that. Finally, the answer looks like this: add $k$ to the minimum, $k-1$ to the second minimum, $k - (n - (n + k) \\bmod 2) - 1$ to the maximum or the second maximum depending on the parity. Before that, add $-1$ to some elements. Since we know where to apply the last operations, let's apply them first. Then we want to apply $-1$'s to make the minimum as large as possible. Well, we should always apply it to the current maximum. First, the minimum would remain as the original minimum. Then all elements will become equal to it at some point. Then we will be spreading the $-1$'s equally among the elements. So every $n$ additional operations, the minimum will be decreasing by $1$. For the easy version, you can simulate this process. Sort the array, apply the last increase operations, find the minimum and the sum of the array, then calculate the result based on that. Let $a' = [a_1 + k, a_2 + k - 1, \\dots]$. Let $s = \\sum_{i = 1}^n (a' - \\min a')$. Then the first $s$ operations of $-1$ will not change the minimum. The rest $\\frac{k - (n - (n - k) \\bmod 2)}{2} - s$ operations will decrease it by $1$ every $n$ operations. So it will get decreased by $\\left\\lceil\\frac{\\max(0, \\frac{k - (n - (n - k) \\bmod 2)}{2} - s)}{n}\\right\\rceil$. Overall complexity: $O(n \\cdot q \\cdot \\log n)$.",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1832",
    "index": "D2",
    "title": "Red-Blue Operations (Hard Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the maximum values of $n$ and $q$}.\n\nYou are given an array, consisting of $n$ integers. Initially, all elements are red.\n\nYou can apply the following operation to the array multiple times. During the $i$-th operation, you select an element of the array; then:\n\n- if the element is red, it increases by $i$ and becomes blue;\n- if the element is blue, it decreases by $i$ and becomes red.\n\nThe operations are numbered from $1$, i. e. during the first operation some element is changed by $1$ and so on.\n\nYou are asked $q$ queries of the following form:\n\n- given an integer $k$, what can the largest minimum in the array be if you apply \\textbf{exactly} $k$ operations to it?\n\nNote that the operations don't affect the array between queries, all queries are asked on the initial array $a$.",
    "tutorial": "Read the editorial to the easy version to get the general idea of the solution. Now, we should only optimize the calculations. First, the sorting can obviously be done beforehand. Now we want to get the minimum and the sum after applying the last increase operations. Consider $(n + k) \\bmod 2 = 0$ and $k > n$, the other cases are similar. The minimum is that: $\\min_{i=1}^n a_i - (i - 1) + k = k + \\min_{i=1}^n a_i - (i - 1)$. Notice how the second part doesn't depend on $k$ and precalculate it. You can calculate prefix minimum array over $a'$. This surely helps with the case of $k < n$. The resulting minimum is $\\min(\\mathit{pref}_k + k, a_{k+1})$ (since $a$ is sorted, the first element after the changed prefix is the smallest). For $k \\bmod 2 = n \\bmod 2$, the minimum is $\\mathit{pref}_n + k$. For $k \\bmod 2 \\neq n \\bmod 2$, the minimum is $\\min(\\mathit{pref}_{n-1} + k, a_n)$. The sum is similar: $\\sum_{i=1}^n a_i - (i - 1) + k = n \\cdot k + \\sum_{i=1}^n a_i - (i - 1)$. As easy to precalculate. The rest is the same. Overall complexity: $O(n \\log n + q)$.",
    "code": "n, q = map(int, input().split())\na = list(map(int, input().split()))\na.sort()\npr = [10**9 for i in range(n + 1)]\nfor i in range(n):\n\tpr[i + 1] = min(pr[i], a[i] - i)\ns = sum(a) - n * (n - 1) // 2\nans = []\nfor k in map(int, input().split()):\n\tif k < n:\n\t\tans.append(min(pr[k] + k, a[k]))\n\t\tcontinue\n\tif k % 2 == n % 2:\n\t\tns = s - pr[n] * n\n\t\tans.append(pr[n] + k - (max(0, (k - n) // 2 - ns) + n - 1) // n)\n\telse:\n\t\tnmn = min(pr[n - 1], a[n - 1] - k)\n\t\tns = (s + (n - 1) - k) - nmn * n\n\t\tans.append(nmn + k - (max(0, (k - (n - 1)) // 2 - ns) + n - 1) // n)\nprint(*ans)",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1832",
    "index": "E",
    "title": "Combinatorics Problem",
    "statement": "Recall that the binomial coefficient $\\binom{x}{y}$ is calculated as follows ($x$ and $y$ are non-negative integers):\n\n- if $x < y$, then $\\binom{x}{y} = 0$;\n- otherwise, $\\binom{x}{y} = \\frac{x!}{y! \\cdot (x-y)!}$.\n\nYou are given an array $a_1, a_2, \\dots, a_n$ and an integer $k$. You have to calculate a new array $b_1, b_2, \\dots, b_n$, where\n\n- $b_1 = (\\binom{1}{k} \\cdot a_1) \\bmod 998244353$;\n- $b_2 = (\\binom{2}{k} \\cdot a_1 + \\binom{1}{k} \\cdot a_2) \\bmod 998244353$;\n- $b_3 = (\\binom{3}{k} \\cdot a_1 + \\binom{2}{k} \\cdot a_2 + \\binom{1}{k} \\cdot a_3) \\bmod 998244353$, and so on.\n\nFormally, $b_i = (\\sum\\limits_{j=1}^{i} \\binom{i - j + 1}{k} \\cdot a_j) \\bmod 998244353$.\n\n\\textbf{Note that the array is given in a modified way, and you have to output it in a modified way as well}.",
    "tutorial": "Unfortunately, it looks like the constraints were insufficient to cut the convolution solutions off. So it's possible to solve this problem using a very fast convolution implementation, but the model approach is different from that. One of the properties of Pascal's triangle states that $\\binom{x}{y} = \\binom{x-1}{y} + \\binom{x-1}{y-1}$. Using it, we can rewrite the formula for $b_i$ as follows: $b_i = (\\sum\\limits_{j=1}^{i} \\binom{i - j + 1}{k} \\cdot a_j)$ $b_i = (\\sum\\limits_{j=1}^{i} \\binom{i-j}{k} \\cdot a_j) + (\\sum\\limits_{j=1}^{i} \\binom{i-j}{k-1} \\cdot a_j)$ Now, the first sum is almost the same as $b_i$, but with $i$ decreased by $1$. So, it is just $b_{i-1}$. What does the second sum stand for? It's actually $b_{i-1}$, but calculated with $k-1$ instead of $k$. upd: The only exception is $k = 1$, for which the last term in the summation has coefficient $\\binom{0}{0} = 1$, that's why it is equal to $b_i$ calculated with $k = 0$, not $b_{i-1}$. Now, let $c_{i,j}$ be equal to the value of $b_i$ if we solve this problem with $k = j$. The formula transformations we used show us that $c_{i,j} = c_{i-1,j} + c_{i-1,j-1}$ (upd: When $j = 1$, the formula is $c_{i,j} = c_{i-1,j} + c_{i,j-1}$ instead), so we can use dynamic programming to calculate $c_{i,k}$ in $O(nk)$. But we need some base values for our dynamic programming. It's quite easy to see that $c_{0,j} = 0$; but what about $c_{i,0}$? $c_{i,0} = \\sum\\limits_{j=1}^{i} \\binom{i - j + 1}{0} \\cdot a_j$ And since $\\binom{i - j + 1}{0} = 1$, then $c_{i,0} = \\sum\\limits_{j=1}^{i} a_j$ So, in order to obtain $c_{i,0}$, we can just build prefix sums on the array $a$. In fact, it's possible to show that transitioning from the $j$-th layer of dynamic programming to the $(j+1)$-th is also just applying prefix sums; then the solution would become just replacing $a$ with prefix sums of $a$ exactly $k+1$ times. This observation was not needed to get AC, but it allows us to write a much shorter code. Solution complexity: $O(nk)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y, int mod = MOD)\n{\n\treturn ((x + y) % mod + mod) % mod;\n}\n\nint mul(int x, int y, int mod = MOD)\n{\n\treturn (x * 1ll * y) % mod;\n}\n\nint binpow(int x, int y, int mod = MOD)\n{\n\tint z = add(1, 0, mod);\n\twhile(y > 0)\n\t{\n\t\tif(y % 2 == 1) z = mul(z, x, mod);\n\t\ty /= 2;\n\t\tx = mul(x, x, mod);\n\t}\n\treturn z;\n}\n\nvector<int> psum(vector<int> v)\n{\n\tvector<int> ans(1, 0);\n\tfor(auto x : v) ans.push_back(add(ans.back(), x));\n\treturn ans;\n}\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tcin >> a[0];\n\tint x, y, m, k;\n\tcin >> x >> y >> m >> k;\n\tfor(int i = 1; i < n; i++)\n\t\ta[i] = add(mul(a[i - 1], x, m), y, m);\n\t\n\tfor(int i = 0; i <= k; i++)\n\t\ta = psum(a);\n\tlong long ans = 0;\n\t\n\tfor(int i = 1; i <= n; i++)\n\t\tans ^= (a[i + 1] * 1ll * i);\n\tcout << ans << endl;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1832",
    "index": "F",
    "title": "Zombies",
    "statement": "Polycarp plays a computer game in a post-apocalyptic setting. The zombies have taken over the world, and Polycarp with a small team of survivors is defending against hordes trying to invade their base. The zombies are invading for $x$ minutes starting from minute $0$. There are $n$ entrances to the base, and every minute one zombie attempts to enter through every entrance.\n\nThe survivors can defend the entrances against the zombies. There are two options:\n\n- manually — shoot the zombies coming through a certain entrance;\n- automatically — set up an electric fence on a certain entrance to fry the zombies.\n\nIf an entrance is defended either or both ways during some minute, no zombie goes through.\n\nEvery entrance is defended by a single dedicated survivor. The $i$-th entrance is defended manually from minute $l_i$ until minute $r_i$, non-inclusive — $[l_i, r_i)$.\n\nThere are $k$ generators that can be used to defend the entrances automatically. Every entrance should be connected to exactly one generator, but a generator can be connected to multiple entrances (or even none of them). Each generator will work for exactly $m$ \\textbf{consecutive} minutes. Polycarp can choose when to power on each generator independently of each other, the $m$ minute long interval should be fully inside the $[0, x)$ time interval.\n\nPolycarp is a weird gamer. He wants the game to be as difficult as possible for him. So he wants to connect each entrance to a generator and choose the time for each generator in such a way that as many zombies as possible enter the base. Please, help him to achieve that!",
    "tutorial": "First of all, let's rephrase the problem a bit. For each entrance, we will have two time segments: the segment when it is guarded, and the segment when the corresponding generator works. The zombies will arrive through that entrance at every moment not belonging to these two segments; so, if we want to maximize the number of zombies, we want to minimize the length of the unions of these pairs of segments for the entrances; and since the lengths of the segments are fixed, minimizing the union means maximizing the intersection. So, we need to choose the time segments for the generators and assign entrances to generators so that the sum of intersections of segment pairs for each entrance is the maximum possible. Okay, now we work with the sum of intersections. Suppose there are multiple generators (for which we have already chosen their time segments) and an entrance; is there an easy method how to choose the optimal generator for the entrance? In fact, there is. We need to look at the centers of all segments (both for the generators and the entrance), and choose the generator for which the distance from the center of the entrance-segment to the center of the segment from that generator is the minimum possible (this only works because all generators have the same working time). Mathematically, if the segments for the generators are denoted as $[L_j, R_j)$, and the segment borders for the entrance are $[l_j, r_j)$, we need to choose the generator that minimizes the value of $|(L_j + R_j) - (l_j + r_j)|$, since it also minimizes the distance between the centers of the segments. Do you see where this is going? In fact, this observation allows us to use exchange argument DP. Suppose the segments for the generators are already chosen; we can sort the entrances according to the values $(l_j + r_j)$ for each entrance, and then split the sorted order of entrances into several groups: all entrances in the first group are optimal to hook up to the first generator, all entrances in the second group are optimal to hook up to the second generator, and so on. But since the segments of the generators are not fixed, we will instead split the sorted order of the entrances into $k$ groups, and for each group, optimally choose the segment for the respective generator. So, this leads us to the following dynamic programming: $dp_{i,j}$ - the maximum possible sum of intersections if we have split the first $i$ entrances in sorted order into $j$ groups. The transitions in this dynamic programming are quite simple: we can just iterate on the next group, transitioning from $dp_{i,j}$ to $dp_{i',j+1}$. Unfortunately, there are still two issues with this solution: How to reduce the number of transitions from $O(n^3)$ to something like $O(n^2 \\log n)$ or $O(n^2)$? How to choose the best generator placement for a group of entrances, preferably either in $O(1)$ or $O(\\log n)$ per one segment of entrances? Okay, the solution to the first issue is not that difficult. Intuitively, it looks like the running time of this dynamic programming can be improved with some of the well-known DP optimizations. The two that probably come to mind first are divide-and-conquer optimization and aliens trick. Both of them seem to work, but unfortunately, we can prove only one of them (the proof is in the paragraph below). You can choose any of these two optimizations. Proof that D&C optimization works We can prove this via quadrangle inequality: let $cost[l..r]$ be the total intersection for the entrances from $l$ to $r$ if the generator for them is chosen optimally, and $opt[l..r]$ be the optimal starting moment of the generator for entrances from $l$ to $r$. We have to show that $cost[a..c] + cost[b..d] \\ge cost[a..d] + cost[b..c]$, where $a \\le b \\le c \\le d$. Suppose $opt[a..d] = opt[b..c]$. Then, if we take all entrances $[c+1..d]$ from the first group and add them to the second group, then choosing $opt[a..d]$ as the starting point for these two groups gives us the total intersection equal to exactly $cost[a..d] + cost[b..c]$. So, in this case, $cost[a..c] + cost[b..d] \\ge cost[a..d] + cost[b..c]$. Now suppose $opt[a..d] < opt[b..c]$ (the case $opt[a..d] > opt[b..c]$ is similar). Let's again try to move all entrances $[c+1..d]$ from the first group to the second group. If the resulting sum of intersections (without shifting the starting points for the generators) did not decrease, we have shown that $cost[a..c] + cost[b..d] \\ge cost[a..d] + cost[b..c]$. Otherwise, at least one entrance from $[c+1..d]$ is closer to $opt[a..d]$ than to $opt[b..c]$ (in terms of distance between the segment centers). This means that since the centers of the segments in $[b..c]$ are not greater than the center of the segments in $[c+1..d]$, then the segments from $[b..c]$ are also closer to $opt[a..d]$ than to $opt[b..c]$. So, the optimal starting moment for $[b..c]$ can be shifted to $opt[a..d]$, and we arrive at the case we analyzed in the previous paragraph. End of proof The solution to the second issue is a bit more complex. First of all, notice that the only possible starting moments for generators we are interested in are of the form $l_i$ and $r_i - m$, so there are only $2n$ of them. Then let's try to understand how to evaluate the sum of intersections for the generator starting at some fixed moment and a segment of entrances. The model solution does some very scary stuff with logarithmic data structures, but the participants of the round showed us a much easier way: create a $2n \\times n$ matrix, where the number in the cell $(i, j)$ is the intersection of the segment for the $i$-th starting moment of the generator, and the segment when the $j$-th entrance (in sorted order) is guarded; then, for a segment of entrances and a fixed starting moment of the generator, the total intersection can be calculated in $O(1)$ using prefix sums on this matrix. Unfortunately, trying each starting moment for every group of segments is still $O(n^3)$. But it can be improved using something like Knuth optimization: let $opt_{l,r}$ be the optimal starting point of the generator for the group of entrances $[l..r]$; then $opt_{l,r}$ is between $opt_{l,r-1}$ and $opt_{l+1,r}$, so calculating these optimal starting points in the style of Knuth optimization gives us $O(n^2)$. However, there's one last nasty surprise waiting for us: if we are not careful about choosing optimal starting moments, it's possible that $opt_{l,l} > opt_{l+1,l+1}$ (for example, if the segment for the entrance $l$ includes the segment for the generator $l+1$), which breaks the initialization of Knuth optimization. To resolve this issue, we can initialize the values of $opt_{l,l}$ in a monotonic way, choosing $opt_{l+1,l+1}$ only from values not less than $opt_{l,l}$. Implementing all of this results in a solution that works in $O(n^2 \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct seg{\n\tint l, r;\n};\n\nint n;\nvector<long long> dp_before, dp_cur;\nvector<vector<long long>> bst;\n\nvoid compute(int l, int r, int optl, int optr){\n\tif (l > r) return;\n\tint mid = (l + r) / 2;\n\tpair<long long, int> best = {-1, -1};\n\tfor (int k = optl; k <= min(mid, optr); k++)\n\t\tbest = max(best, {(k ? dp_before[k - 1] : 0) + bst[k][mid], k});\n\tdp_cur[mid] = best.first;\n\tint opt = best.second;\n\tcompute(l, mid - 1, optl, opt);\n\tcompute(mid + 1, r, opt, optr);\n}\n\nstruct node{\n    long long c0;\n    int c1;\n};\n\nvector<node> f;\n\nvoid update(int x, int a, int b){\n\tfor (int i = x; i < int(f.size()); i |= i + 1){\n\t\tf[i].c0 += b;\n\t\tf[i].c1 += a;\n\t}\n}\n\nvoid update(int l, int r, int a, int b){\n\tupdate(l, a, b);\n\tupdate(r, -a, -b);\n}\n\nlong long get(int pos, int x){\n\tlong long res = 0;\n\tfor (int i = x; i >= 0; i = (i & (i + 1)) - 1)\n\t\tres += f[i].c0 + f[i].c1 * 1ll * pos;\n\treturn res;\n}\n\nint main() {\n\tint k, x, m;\n\tscanf(\"%d%d%d%d\", &n, &k, &x, &m);\n\tvector<seg> a(n);\n\tforn(i, n) scanf(\"%d%d\", &a[i].l, &a[i].r);\n\tsort(a.begin(), a.end(), [&](const seg &a, const seg &b){\n\t\treturn a.l + a.r < b.l + b.r;\n\t});\n\t\n\tvector<int> pos;\n\tforn(i, n){\n\t\tpos.push_back(a[i].l);\n\t\tpos.push_back(a[i].r - m);\n\t}\n\tsort(pos.begin(), pos.end());\n\tpos.resize(unique(pos.begin(), pos.end()) - pos.begin());\n\tint cds = pos.size();\n\t\n\tvector<array<int, 4>> npos(n);\n\tforn(i, n){\n\t\tnpos[i][0] = lower_bound(pos.begin(), pos.end(), a[i].l - m) - pos.begin();\n\t\tnpos[i][1] = lower_bound(pos.begin(), pos.end(), a[i].l) - pos.begin();\n\t\tnpos[i][2] = lower_bound(pos.begin(), pos.end(), a[i].r - m) - pos.begin();\n\t\tnpos[i][3] = lower_bound(pos.begin(), pos.end(), a[i].r) - pos.begin();\n\t}\n\t\n\tvector<long long> pr(n + 1);\n\tforn(i, n) pr[i + 1] = pr[i] + x - (m + a[i].r - a[i].l);\n\t\n\tauto upd = [&](int i){\n\t\tif (a[i].r - a[i].l >= m){\n\t\t\tupdate(npos[i][0], npos[i][1], 1, m - a[i].l);\n\t\t\tupdate(npos[i][1], npos[i][2], 0, m);\n\t\t\tupdate(npos[i][2], npos[i][3], -1, a[i].r);\n\t\t}\n\t\telse{\n\t\t\tupdate(npos[i][0], npos[i][2], 1, m - a[i].l);\n\t\t\tupdate(npos[i][2], npos[i][1], 0, a[i].r - a[i].l);\n\t\t\tupdate(npos[i][1], npos[i][3], -1, a[i].r);\n\t\t}\n\t};\n\t\n\tbst.resize(n, vector<long long>(n, -1));\n\tvector<vector<int>> opt(n, vector<int>(n));\n\tforn(r, n) for (int l = r; l >= 0; --l){\n\t\tif (l == r) f.assign(cds, {0, 0});\n\t\tupd(l);\n\t\tint L = (l == r ? (l == 0 ? 0 : opt[l - 1][l - 1]) : opt[l][r - 1]);\n\t\tint R = (l == r ? int(pos.size()) - 1 : opt[l + 1][r]);\n\t\tfor (int k = L; k <= R; ++k){\n\t\t\tlong long cur = pr[r + 1] - pr[l] + get(pos[k], k);\n\t\t\tif (cur > bst[l][r]){\n\t\t\t\tbst[l][r] = cur;\n\t\t\t\topt[l][r] = k;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tdp_before.resize(n);\n\tdp_cur.resize(n);\n\tfor (int i = 0; i < n; i++)\n\t\tdp_before[i] = bst[0][i];\n\n\tfor (int i = 1; i < k; i++){\n\t\tcompute(0, n - 1, 0, n - 1);\n\t\tdp_before = dp_cur;\n\t}\n\t\n\tprintf(\"%lld\\n\", dp_before[n - 1]);\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1833",
    "index": "A",
    "title": "Musical Puzzle",
    "statement": "Vlad decided to compose a melody on his guitar. Let's represent the melody as a sequence of notes corresponding to the characters 'a', 'b', 'c', 'd', 'e', 'f', and 'g'.\n\nHowever, Vlad is not very experienced in playing the guitar and can only record \\textbf{exactly two} notes at a time. Vlad wants to obtain the melody $s$, and to do this, he can merge the recorded melodies together. In this case, the last sound of the first melody must match the first sound of the second melody.\n\nFor example, if Vlad recorded the melodies \"ab\" and \"ba\", he can merge them together and obtain the melody \"aba\", and then merge the result with \"ab\" to get \"abab\".\n\nHelp Vlad determine the \\textbf{minimum} number of melodies consisting of two notes that he needs to record in order to obtain the melody $s$.",
    "tutorial": "Let's construct the melody sequentially. In the first step, we can record the notes $s_1$ and $s_2$. In the next step, we need to record $s_2$ and $s_3$, because there must be a common symbol when gluing and so on. That is, we need to have recorded melodies $s_i$+$s_{i+1}$ for all $1 \\le i < n$. We only need to count how many different ones among them, because we don't need to record one melody twice.",
    "code": "def solve():\n    n = int(input())\n    s = input()\n    cnt = set()\n    for i in range(1, n):\n        cnt.add(s[i - 1] + s[i])\n    print(len(cnt))\n\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1833",
    "index": "B",
    "title": "Restore the Weather",
    "statement": "You are given an array $a$ containing the weather forecast for Berlandia for the last $n$ days. That is, $a_i$ — is the estimated air temperature on day $i$ ($1 \\le i \\le n$).\n\nYou are also given an array $b$ — the air temperature that was actually present on each of the days. However, all the values in array $b$ are mixed up.\n\nDetermine which day was which temperature, if you know that the weather never differs from the forecast by more than $k$ degrees. In other words, if on day $i$ the real air temperature was $c$, then the equality $|a_i - c| \\le k$ is always true.\n\nFor example, let an array $a$ = [$1, 3, 5, 3, 9$] of length $n = 5$ and $k = 2$ be given and an array $b$ = [$2, 5, 11, 2, 4$]. Then, so that the value of $b_i$ corresponds to the air temperature on day $i$, we can rearrange the elements of the array $b$ so: [$2, 2, 5, 4, 11$]. Indeed:\n\n- On the $1$st day, $|a_1 - b_1| = |1 - 2| = 1$, $1 \\le 2 = k$ is satisfied;\n- On the $2$nd day $|a_2 - b_2| = |3 - 2| = 1$, $1 \\le 2 = k$ is satisfied;\n- On the $3$rd day, $|a_3 - b_3| = |5 - 5| = 0$, $0 \\le 2 = k$ is satisfied;\n- On the $4$th day, $|a_4 - b_4| = |3 - 4| = 1$, $1 \\le 2 = k$ is satisfied;\n- On the $5$th day, $|a_5 - b_5| = |9 - 11| = 2$, $2 \\le 2 = k$ is satisfied.",
    "tutorial": "Let's solve the problem using a greedy algorithm. Based on the array $a$, form an array of pairs {temperature, day number} and sort it in ascending order of temperature. Also sort the array $b$ in ascending order. Now, the values $a[i].first$ and $b[i]$ are the predicted and real temperature on day $a[i].second$. Indeed, consider the minimum temperatures $b[1]$ and $a[1].first$. The difference between them is $t = |b[1] - a[1].first|$. If we consider the value $|b[i] - a[1].first|$ or $|b[1] - a[i].first|$ at $i \\gt 1$, there will be at least $t$ since $a[1] \\le a[i]$ and $b[1] \\le b[i]$. Since it is guaranteed that it is possible to rearrange the elements in the array $b$, and the elements $b[1]$ and $a[1].first$ have the smallest difference, it is definitely not greater than $k$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid  solve(){\n    int n, k;\n    cin >> n >> k;\n    vector<pair<int, int>>a(n);\n    vector<int>b(n), ans(n);\n    for(int i = 0; i < n; i++){\n        cin >> a[i].first;\n        a[i].second = i;\n    }\n    for(auto &i : b) cin >> i;\n    sort(b.begin(), b.end());\n    sort(a.begin(), a.end());\n\n    for(int i = 0; i < n; i++){\n        ans[a[i].second] = b[i];\n    }\n    for(auto &i : ans) cout << i << ' ';\n    cout << endl;\n}\nint main(){\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1833",
    "index": "C",
    "title": "Vlad Building Beautiful Array",
    "statement": "Vlad was given an array $a$ of $n$ positive integers. Now he wants to build a beautiful array $b$ of length $n$ from it.\n\nVlad considers an array beautiful if all the numbers in it are positive and have the same parity. That is, all numbers in the beautiful array are \\textbf{greater} than zero and are either all even or all odd.\n\nTo build the array $b$, Vlad can assign each $b_i$ either the value $a_i$ or $a_i - a_j$, where any $j$ from $1$ to $n$ can be chosen.\n\nTo avoid trying to do the impossible, Vlad asks you to determine whether it is possible to build a beautiful array $b$ of length $n$ using his array $a$.",
    "tutorial": "If all the numbers in the array already have the same parity, then for each $i$ it is sufficient to assign $b_i=a_i$. Otherwise, it is impossible to make all the numbers even by leaving them positive, because the parity changes only when subtracting an odd number, and we cannot make the minimum odd number an even number. It remains only to make all numbers odd, that is, subtract odd numbers from even numbers. This can be done if the minimum number in the array is odd, because we can subtract it from every even number.",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    a.sort()\n    if a[0] % 2 == 1:\n        print(\"YES\")\n        return\n    for i in range(n):\n        if a[i] % 2 == 1:\n            print(\"NO\")\n            return\n    print(\"YES\")\n\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1833",
    "index": "D",
    "title": "Flipper",
    "statement": "You are given a permutation $p$ of length $n$.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $\\{2,3,1,5,4\\}$ is a permutation, while $\\{1,2,2\\}$ is not (since $2$ appears twice), and $\\{1,3,4\\}$ is also not a permutation (as $n=3$, but the array contains $4$).\n\nTo the permutation $p$, you need to apply the following operation \\textbf{exactly once}:\n\n- First you choose a segment $[l, r]$ ($1 \\le l \\le r \\le n$, a segment is a continuous sequence of numbers $\\{p_l, p_{l+1}, \\ldots, p_{r-1}, p_r\\}$) and reverse it. Reversing a segment means swapping pairs of numbers $(p_l, p_r)$, $(p_{l+1}, p_{r-1})$, ..., $(p_{l + i}, p_{r - i})$ (where $l + i \\le r - i$).\n- Then you swap the prefix and suffix: $[r+1, n]$ and $[1, l - 1]$ (note that these segments may be empty).\n\nFor example, given $n = 5, p = \\{2, \\textcolor{blue}{3}, \\textcolor{blue}{1}, 5, 4\\}$, if you choose the segment $[l = 2, r = 3]$, after reversing the segment $p = \\{\\textcolor{green}{2}, \\textcolor{blue}{1}, \\textcolor{blue}{3}, \\textcolor{green}{5}, \\textcolor{green}{4}\\}$, then you swap the segments $[4, 5]$ and $[1, 1]$. Thus, $p = \\{\\textcolor{green}{5}, \\textcolor{green}{4}, 1, 3, \\textcolor{green}{2}\\}$. It can be shown that this is the maximum possible result for the given permutation.\n\nYou need to output the lexicographically \\textbf{maximum} permutation that can be obtained by applying the operation described \\textbf{exactly once}.\n\nA permutation $a$ is lexicographically greater than permutation $b$ if there exists an $i$ ($1 \\le i \\le n$) such that $a_j = b_j$ for $1 \\le j < i$ and $a_i > b_i$.",
    "tutorial": "In these constraints we could solve the problem for $O(n^2)$. Let us note that there can be no more than two candidates for the value $r$. Since the first number in the permutation will be either $p_{r+1}$ if $r < n$, or $p_r$ if $r = n$. Then let's go through the value of $r$ and choose the one in which the first number in the resulting permutation is as large as possible. Next, if $p_n = n$, then we can have two candidates for $r$ is $n, n-1$, but note that it is always advantageous to put $r = n$ in that case, since it will not spoil the answer. Then we can go through $l$ and get the solution by the square, but we can do something smarter. Notice now that the answer already contains all the numbers $p_i$ where $i > r$. And then we write $p_r, p_{r-1}, \\ldots, p_l$ where $l$ is still unknown, and then $p_1, p_2, \\ldots, p_{l-1}$. In that case, let's write $p_r$ as $l \\le r$ and then write $p_{r-1}, p_{r-2}, \\ldots$ as long as they are larger than $p_1$. Otherwise, we immediately determine the value of $l$ and finish the answer to the end. Thus, constructively we construct the maximal permutation.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\n\n\nvoid solve() {\n    int n; cin >> n;\n    vector<int> p(n);\n    for (auto &e : p) cin >> e;\n\n    int r = 0;\n    for (int i = 0; i < n; ++i) {\n        if (p[min(n-1, r+1)] <= p[min(n-1, i+1)]) {\n            r = i;\n        }\n    }\n    vector<int> ans;\n    for (int i = r + 1; i < n; ++i) ans.eb(p[i]);\n    ans.eb(p[r]);\n    for (int i = r-1; i >= 0; --i) {\n        if (p[i] > p[0]) {\n            ans.eb(p[i]);\n        } else {\n            for (int j = 0; j <= i; ++j) {\n                ans.eb(p[j]);\n            }\n            break;\n        }\n    }\n    for (auto e : ans) cout << e << ' ';\n    cout << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1833",
    "index": "E",
    "title": "Round Dance",
    "statement": "$n$ people came to the festival and decided to dance a few round dances. There are at least $2$ people in the round dance and each person has exactly two neighbors. If there are $2$ people in the round dance then they have the same neighbor on each side.\n\nYou decided to find out exactly how many dances there were. But each participant of the holiday remembered exactly \\textbf{one} neighbor. Your task is to determine what the minimum and maximum number of round dances could be.\n\nFor example, if there were $6$ people at the holiday, and the numbers of the neighbors they remembered are equal $[2, 1, 4, 3, 6, 5]$, then the \\textbf{minimum} number of round dances is$1$:\n\n- $1 - 2 - 3 - 4 - 5 - 6 - 1$\n\nand the \\textbf{maximum} is $3$:\n\n- $1 - 2 - 1$\n- $3 - 4 - 3$\n- $5 - 6 - 5$",
    "tutorial": "Let's build an undirected graph, draw the edges $i \\to a_i$. Let's split this graph into connectivity components, denote their number by $k$. There could not be more than $k$ round dances. Since the degree of each vertex is no more than two, the connectivity components are simple cycles and bamboos. If we connect the vertices of degree one in each bamboo, we get a partition into $k$ round dances. Now let's try to get the minimum number of round dances. Nothing can be done with cycles, and all bamboos can be combined into one. If you get $b$ bamboos and $c$ cycles, then the answer is $\\langle c + \\min(b, 1), c + b \\rangle$. Time complexity is $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <set>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\ntypedef long long ll;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    vector<set<int>> g(n);\n    vector<set<int>> neighbours(n);\n    vector<int> d(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n        a[i]--;\n        g[i].insert(a[i]);\n        g[a[i]].insert(i);\n    }\n    for (int i = 0; i < n; ++i) {\n        d[i] = g[i].size();\n    }\n    int bamboos = 0, cycles = 0;\n    vector<bool> vis(n);\n    for (int i = 0; i < n; ++i) {\n        if (!vis[i]) {\n            queue<int> q;\n            q.push(i);\n            vis[i] = true;\n            vector<int> component = {i};\n            while (!q.empty()) {\n                int u = q.front();\n                q.pop();\n                for (int v: g[u]) {\n                    if (!vis[v]) {\n                        vis[v] = true;\n                        q.push(v);\n                        component.push_back(v);\n                    }\n                }\n            }\n            bool bamboo = false;\n            for (int j: component) {\n                if (d[j] == 1) {\n                    bamboo = true;\n                    break;\n                }\n            }\n            if (bamboo) {\n                bamboos++;\n            } else {\n                cycles++;\n            }\n        }\n    }\n    cout << cycles + min(bamboos, 1) << ' ' << cycles + bamboos << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        solve();\n    }\n}",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1833",
    "index": "F",
    "title": "Ira and Flamenco",
    "statement": "Ira loves Spanish flamenco dance very much. She decided to start her own dance studio and found $n$ students, $i$th of whom has level $a_i$.\n\nIra can choose several of her students and set a dance with them. So she can set a huge number of dances, but she is only interested in magnificent dances. The dance is called magnificent if the following is true:\n\n- \\textbf{exactly} $m$ students participate in the dance;\n- levels of all dancers are \\textbf{pairwise distinct};\n- levels of every two dancers have an absolute difference \\textbf{strictly less} than $m$.\n\nFor example, if $m = 3$ and $a = [4, 2, 2, 3, 6]$, the following dances are magnificent (students participating in the dance are highlighted in red): $[\\textcolor{red}{4}, 2, \\textcolor{red}{2}, \\textcolor{red}{3}, 6]$, $[\\textcolor{red}{4}, \\textcolor{red}{2}, 2, \\textcolor{red}{3}, 6]$. At the same time dances $[\\textcolor{red}{4}, 2, 2, \\textcolor{red}{3}, 6]$, $[4, \\textcolor{red}{2}, \\textcolor{red}{2}, \\textcolor{red}{3}, 6]$, $[\\textcolor{red}{4}, 2, 2, \\textcolor{red}{3}, \\textcolor{red}{6}]$ are not magnificent.\n\nIn the dance $[\\textcolor{red}{4}, 2, 2, \\textcolor{red}{3}, 6]$ only $2$ students participate, although $m = 3$.\n\nThe dance $[4, \\textcolor{red}{2}, \\textcolor{red}{2}, \\textcolor{red}{3}, 6]$ involves students with levels $2$ and $2$, although levels of all dancers must be pairwise distinct.\n\nIn the dance $[\\textcolor{red}{4}, 2, 2, \\textcolor{red}{3}, \\textcolor{red}{6}]$ students with levels $3$ and $6$ participate, but $|3 - 6| = 3$, although $m = 3$.\n\nHelp Ira count the number of magnificent dances that she can set. Since this number can be very large, count it \\textbf{modulo} $10^9 + 7$. Two dances are considered different if the sets of students participating in them are different.",
    "tutorial": "Reformulate the definition of magnificent dance. A dance $[x_1, x_2, \\ldots, x_m]$ is called magnificent if there exists such a non-negative integer $d$ that $[x_1 - d, x_2 - d, \\ldots, x_m - d]$ forms a permutation. Let's build an array $b$ such that it is sorted, all the numbers in it are unique and each number from $a$ occurs in $b$. For each element $b_i$, set $c_i$ as its number of occurrences in the array $a$. This process is called coordinate compression. For example, if $a = [4, 1, 2, 2, 3]$, then $b = [1, 2, 3, 4]$, $c = [1, 2, 1, 1]$. Let the constructed array $b$ has length $k$. In every magnificent dance there is a dancer with a minimum level. Let's fix this minimal level in the array $b$, let its index be $i$, then the desired magnificent dance exists if $i + m \\le k$ and $b_{i + m} = b_i + m - 1$. If the desired magnificent dance exists, the number of such dances must be added to the answer, which is equal to $c_i \\cdot c_{i + 1} \\cdot \\ldots \\cdot c_{i + m}$. How to quickly calculate such a number? Let's build prefix products $p_i = c_1 \\cdot c_2 \\cdot \\ldots \\cdot p_{i - 1}$. Then by Fermat's small theorem $c_i \\cdot c_{i + 1} \\cdot \\ldots \\cdot c_{i + m} = p_{i + m} \\cdot p_i^{(10^9 + 7) - 2}$. Time complexity is $O(n \\log C)$. Let's build a segment tree on a product modulo. Time complexity is $O(n \\log n)$ and we don't use that the module is prime. We will use the idea of building a queue on two stacks, but we will support prefix products modulo in these stacks. Time complexity is $O(n)$ and we don't use that the module is prime.",
    "code": "/*\n         `)\n        _ \\\n      (( }/  ,_\n      )))__ /\n     (((---'\n       \\ '\n        )|____.---- )\n       / \\ `       (\n      / ' \\ `      )\n     /  '  \\  `   /\n    /   '       _/\n   /   _!____.-'\n  /_.-'/    \\\n     |`_    |`_\n*/\n#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef pair<int, int> ipair;\n\nconst int MAXN = 200200;\nconst int MAXK = MAXN;\nconst int MOD = 1000000007;\n\ninline int add(int a, int b) {\n\treturn (a + b >= MOD ? a + b - MOD : a + b);\n}\n\ninline int mul(int a, int b) {\n\treturn 1LL * a * b % MOD;\n}\n\nint n, m, k;\nint arr[MAXN], brr[MAXN], cnt[MAXK];\n\nvoid build() {\n\tsort(arr, arr + n);\n\tmemcpy(brr, arr, sizeof(int) * n);\n\tk = unique(arr, arr + n) - arr;\n\tfor (int j = 0; j < k; ++j)\n\t\tcnt[j] = upper_bound(brr, brr + n, arr[j]) - lower_bound(brr, brr + n, arr[j]);\n}\n\ninline void push(stack<ipair> &S, int x) {\n\tS.emplace(x, mul(x, S.empty() ? 1 : S.top().second));\n}\n\nint solve() {\n\tif (k < m) return 0;\n\tstack<ipair> S1, S2;\n\tfor (int j = 0; j < m; ++j)\n\t\tpush(S1, cnt[j]);\n\tint ans = 0;\n\tfor (int j = m; j <= k; ++j) {\n\t\tif (arr[j - 1] - arr[j - m] == m - 1)\n\t\t\tans = add(ans, mul(S1.empty() ? 1 : S1.top().second, S2.empty() ? 1 : S2.top().second));\n\t\tif (S2.empty()) {\n\t\t\tfor (; !S1.empty(); S1.pop())\n\t\t\t\tpush(S2, S1.top().first);\n\t\t}\n\t\tS2.pop();\n\t\tpush(S1, cnt[j]);\n\t}\n\treturn ans;\n}\n\nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tcin >> n >> m;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tcin >> arr[i];\n\t\tbuild();\n\t\tcout << solve() << endl;\n\t}\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "data structures",
      "implementation",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1833",
    "index": "G",
    "title": "Ksyusha and Chinchilla",
    "statement": "Ksyusha has a pet chinchilla, a tree on $n$ vertices and huge scissors. A tree is a connected graph without cycles. During a boring physics lesson Ksyusha thought about how to entertain her pet.\n\nChinchillas like to play with branches. A branch is a tree of $3$ vertices.\n\n\\begin{center}\n{\\small The branch looks like this.}\n\\end{center}\n\nA cut is the removal of some (not yet cut) edge in the tree. Ksyusha has plenty of free time, so she can afford to make enough cuts so that the tree splits into branches. In other words, after several (possibly zero) cuts, each vertex must belong to \\textbf{exactly one} branch.\n\nHelp Ksyusha choose the edges to be cut or tell that it is impossible.",
    "tutorial": "Let's hang the tree by the vertex $1$. This problem can be solved by dynamic programming. $dpc_v$ - the ability to cut a subtree of $v$ if the edges in all children of $v$ must be cut off. $dpo_v$ - the ability to cut a subtree of $v$ if exactly one edge needs to be saved from $v$ to the child. $dp_v$ - ability to cut a subtree of $v$ if an edge above $v$ is cut off. Obviously, the answer will be $dp_1$. Recalculation in such dynamics is offered to the reader as an exercise. There is a simpler greedy solution. Let's call light a vertex that is not a leaf and whose children are all leaves. Let's call heavy a vertex that is not a leaf and that has a light child. If there is a light vertex with at least three children, the desired cut does not exist. If the light vertex $v$ has exactly one child, we will cut off all children from its parent except $v$. If the light vertex $v$ has exactly two children, we cut the edge into the parent $v$. It is easy to understand that in this way the desired cut is restored uniquely. This problem can be solved by an elegant DFS, but the author considers BFS easier to understand. First, let's count the number of children and the number of light children for each vertex. We will store all light vertices in the queue and process them sequentially. Cutting edges will change the number of children and the number of light children at some vertices. It should be handled carefully. This solution works for $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef pair<int, int> ipair;\n\nconst int MAXN = 200200;\n\nint n;\nvector<ipair> gr[MAXN];\nvector<int> res;\nqueue<int> qu;\nint par[MAXN], ipar[MAXN], deg[MAXN], hard[MAXN];\n\nvoid init() {\n\tres.clear();\n\twhile (!qu.empty()) qu.pop();\n\tmemset(deg, 0, sizeof(int) * n);\n\tmemset(hard, 0, sizeof(int) * n);\n\tfor (int v = 0; v < n; ++v)\n\t\tgr[v].clear();\n}\n\nvoid dfs(int v, int p, int ip) {\n\tpar[v] = p;\n\tipar[v] = ip;\n\tfor (auto [u, i]: gr[v]) {\n\t\tif (u == p) continue;\n\t\tdfs(u, v, i);\n\t\t++deg[v];\n\t\thard[v] += (deg[u] > 0);\n\t}\n}\n\nvoid build() {\n\tdfs(0, -1, -1);\n}\n\nbool rempar(int v) {\n\tint u = par[v];\n\tif (u == -1) return true;\n\tpar[v] = -1;\n\tres.push_back(ipar[v]);\n\t--deg[u], --hard[u];\n\tif (deg[u]) {\n\t\tif (!hard[u]) qu.push(u);\n\t\treturn true;\n\t}\n\tif (par[u] == -1) return false;\n\t--hard[par[u]];\n\tif (!hard[par[u]]) qu.push(par[u]);\n\treturn true;\n}\n\nbool solve() {\n\tif (n % 3) return false;\n\tfor (int v = 0; v < n; ++v)\n\t\tif (!hard[v] && deg[v]) qu.push(v);\n\twhile (!qu.empty()) {\n\t\tint v = qu.front(); qu.pop();\n\t\tif (deg[v] > 2) return false;\n\t\tif (deg[v] == 2) {\n\t\t\tif (!rempar(v)) return false;\n\t\t} else if (deg[v] == 1) {\n\t\t\tif (par[v] == -1) return false;\n\t\t\tfor (auto [u, i]: gr[par[v]]) {\n\t\t\t\tif (u == par[par[v]] || u == v || par[u] == -1) continue;\n\t\t\t\tif (!deg[u]) return false;\n\t\t\t\tres.push_back(i);\n\t\t\t\tpar[u] = -1;\n\t\t\t}\n\t\t\tif (!rempar(par[v])) return false;\n\t\t}\n\t}\n\treturn true;\n}\n\nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tcin >> n, init();\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tint v, u; cin >> v >> u, --v, --u;\n\t\t\tgr[v].emplace_back(u, i);\n\t\t\tgr[u].emplace_back(v, i);\n\t\t}\n\t\tbuild();\n\t\tif (!solve()) {\n\t\t\tcout << -1 << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tcout << res.size() << endl;\n\t\tfor (int id: res)\n\t\t\tcout << id << ' ';\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "dsu",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1834",
    "index": "A",
    "title": "Unit Array",
    "statement": "Given an array $a$ of length $n$, which elements are equal to $-1$ and $1$. Let's call the array $a$ good if the following conditions are held at the same time:\n\n- $a_1 + a_2 + \\ldots + a_n \\ge 0$;\n- $a_1 \\cdot a_2 \\cdot \\ldots \\cdot a_n = 1$.\n\nIn one operation, you can select an arbitrary element of the array $a_i$ and change its value to the opposite. In other words, if $a_i = -1$, you can assign the value to $a_i := 1$, and if $a_i = 1$, then assign the value to $a_i := -1$.\n\nDetermine the minimum number of operations you need to perform to make the array $a$ good. It can be shown that this is always possible.",
    "tutorial": "First, let's make the sum of the array elements $\\ge 0$. To do this, we just need to change some $-1$ to $1$. The number of such replacements can be calculated using a formula or explicitly simulated. After that, there are two possible situations: either the product of all elements is equal to $1$, or the product of all elements is equal to $-1$. In the first case, we don't need to do anything else. In the second case, we need to replace one more $-1$ with $1$ (note that in this case the sum will remain $\\ge 0$).",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1834",
    "index": "B",
    "title": "Maximum Strength",
    "statement": "Fedya is playing a new game called \"The Legend of Link\", in which one of the character's abilities is to combine two materials into one weapon. Each material has its own strength, which can be represented by a positive integer $x$. The strength of the resulting weapon is determined as the sum of the absolute differences of the digits in the \\textbf{decimal} representation of the integers at each position.\n\nFormally, let the first material have strength $X = \\overline{x_{1}x_{2} \\ldots x_{n}}$, and the second material have strength $Y = \\overline{y_{1}y_{2} \\ldots y_{n}}$. Then the strength of the weapon is calculated as $|x_{1} - y_{1}| + |x_{2} - y_{2}| + \\ldots + |x_{n} - y_{n}|$. If the integers have different lengths, then the shorter integer is \\textbf{padded with leading zeros}.\n\nFedya has an unlimited supply of materials with all possible strengths from $L$ to $R$, inclusive. Help him find the maximum possible strength of the weapon he can obtain.\n\nAn integer $C = \\overline{c_{1}c_{2} \\ldots c_{k}}$ is defined as an integer obtained by sequentially writing the digits $c_1, c_2, \\ldots, c_k$ from left to right, i.e. $10^{k-1} \\cdot c_1 + 10^{k-2} \\cdot c_2 + \\ldots + c_k$.",
    "tutorial": "Let's add leading zeros to $L$ if necessary. Now we can represent the numbers $L$ and $R$ as their longest common prefix, the digit $k$ at which the values differ, and the remaining digits. After digit $k$, any digits can be placed, so it is advantageous to put $9$ in one number and $0$ in the other. Then the answer is equal to $(r_{k} - l_{k}) + 9 \\cdot (n - k)$. For example, it is achieved with numbers $A = \\overline{l_{1}l_{2} \\ldots l_{k} \\underbrace{99 \\ldots 9}_{n - k}}$ and $B = \\overline{r_{1}r_{2} \\ldots r_{k} \\underbrace{00 \\ldots 0}_{n - k}}$.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1834",
    "index": "C",
    "title": "Game with Reversing",
    "statement": "Alice and Bob are playing a game. They have two strings $S$ and $T$ of the same length $n$ consisting of lowercase latin letters. Players take turns alternately, with Alice going first.\n\nOn her turn, Alice chooses an integer $i$ from $1$ to $n$, one of the strings $S$ or $T$, and any lowercase latin letter $c$, and replaces the $i$-th symbol in the chosen string with the character $c$.\n\nOn his turn, Bob chooses one of the strings $S$ or $T$, and reverses it. More formally, Bob makes the replacement $S := \\operatorname{rev}(S)$ or $T := \\operatorname{rev}(T)$, where $\\operatorname{rev}(P) = P_n P_{n-1} \\ldots P_1$.\n\nThe game lasts until the strings $S$ and $T$ are equal. As soon as the strings become equal, the game \\textbf{ends instantly}.\n\nDefine the duration of the game as the total number of moves made by both players during the game. For example, if Alice made $2$ moves in total, and Bob made $1$ move, then the duration of this game is $3$.\n\nAlice's goal is to minimize the duration of the game, and Bob's goal is to maximize the duration of the game.\n\nWhat will be the duration of the game, if both players play optimally? It can be shown that the game will end in a finite number of turns.",
    "tutorial": "Let's show that the specific choice of a turn by Bob (which of the strings to reverse) does not affect Alice's strategy and therefore the answer to the problem. Reversing the string twice does not change anything $\\to$ we are only interested in the parity of the number of reverses for both strings. If Bob made an even number of moves in total, then the parity of the number of moves made by Bob with string $s$ coincides with the parity of the number of moves made by Bob with string $t \\to$ pairs of characters at the same indices, after all reverses, will be $(s_1, t_1), (s_2, t_2), \\ldots, (s_n, t_n)$, possibly in reverse order, but it doesn't matter. Here $s_1, \\ldots, s_n$ and $t_1, \\ldots, t_n$ are the original indices of the strings, which do not change with reversing. If Bob made an odd number of moves, then exactly one of the strings will be reversed, and the pairs of characters in the same indices will be: $(s_1, t_n), (s_2, t_{n-1}), \\ldots, (s_n, t_1)$ (or in reverse order). That is, the specific pairs of corresponding characters are determined only by the parity of the total number of moves made by Bob, and it does not matter which specific moves were made. Therefore, Alice can choose one of two strategies: Make $s_1 = t_1, s_2 = t_2, \\ldots, s_n = t_n$, and fix the end of the game when the number of moves made by Bob is even. Make $s_1 = t_n, s_2 = t_{n-1}, \\ldots, s_n = t_1$, and fix the end of the game when the number of moves made by Bob is odd. Let's count $cnt$ - the number of indices where $s$ and $t$ differ, and $cnt_{rev}$ - the number of indices where $s$ and $\\operatorname{rev}(t)$ differ. For the first strategy, Alice must make at least $cnt$ moves herself, and it is also necessary that the number of moves made by Bob is even $\\to$ it is easy to see that for this strategy the game will last $2 \\cdot cnt - cnt \\% 2$ moves. For the second strategy, everything is roughly similar: the game will last $2 \\cdot cnt_{rev} - (1 - cnt_{rev} \\% 2)$ moves, but the case $cnt_{rev} = 0$ needs to be handled separately. And the answer to the problem will be the minimum of these two values. Asymptotic: $O(n)$.",
    "tags": [
      "games",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1834",
    "index": "D",
    "title": "Survey in Class",
    "statement": "Zinaida Viktorovna has $n$ students in her history class. The homework for today included $m$ topics, but the students had little time to prepare, so $i$-th student learned only topics from $l_i$ to $r_i$ inclusive.\n\nAt the beginning of the lesson, each student holds their hand at $0$. The teacher wants to ask some topics. It goes like this:\n\n- The teacher asks the topic $k$.\n- If the student has learned topic $k$, then he raises his hand by $1$, otherwise he lower it by $1$.\n\nEach topic Zinaida Viktorovna can ask \\textbf{no more than one time}.\n\nFind the maximum difference of the heights of the highest and the lowest hand that can be in class after the survey.\n\nNote that the student's hand \\textbf{can go below $0$}.",
    "tutorial": "Let's fix the students who will end up with the highest and lowest hands. Then, to maximize the difference, we can ask all the topics that the student with the highest hand knows. Then the second student will raise his hand for each topic in the intersection of their segments, and lower for each topic that only the first student knows. That is, the problem is to find $2$ segments $a$ and $b$ such that the value of $|a| - |a |\\cap b|$ is maximal, since the answer is $2 \\cdot (|a| - |a \\cap b|)$. The segment $b$ can intersect the segment $a$ in four ways: intersect the beginning of $a$, intersect the end of $a$, be completely inside $a$, or not intersect it at all. So, if in the answer segment $b$ intersects the beginning of $a$, then you can choose the segment with the minimal right end as the segment $b$ - the intersection of such a segment with $a$ will be no greater than the intersection of $b$ with $a$. Similarly, for the right end, you can select the segment with the maximal left end. If the answer has one segment in another, then you can consider the shortest segment in the set as the inner segment. If the segments in the answer do not intersect, then the segment does not intersect one of the \"edge\" segments. Thus, to find the segment with which it has the minimum intersection for a given segment, you need to check 3 candidates: the shortest segment in the set, the segment with the minimal right end, and the one with the maximal left end. In total, to find the answer, you need to check $3n$ pairs of segments.",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1834",
    "index": "E",
    "title": "MEX of LCM",
    "statement": "You are given an array $a$ of length $n$. A \\textbf{positive} integer $x$ is called good if it is \\textbf{impossible} to find a subsegment$^{\\dagger}$ of the array such that the least common multiple of all its elements is equal to $x$.\n\nYou need to find the smallest good integer.\n\nA subsegment$^{\\dagger}$ of the array $a$ is a set of elements $a_l, a_{l + 1}, \\ldots, a_r$ for some $1 \\le l \\le r \\le n$. We will denote such subsegment as $[l, r]$.",
    "tutorial": "Notice that the MEX of $n^2$ numbers will not exceed $n^2+1$. Let's calculate all possible LCM values on segments that do not exceed $n^2$. To do this, we will iterate over the right endpoint of the segments and maintain a set of different LCM values on segments with such a right endpoint. Let these values be $x_1 < x_2 < \\ldots < x_k$. Then $k \\leq 1 + 2\\log_2n$, indeed, for each $1 \\leq i < k$, it is true that $x_{i+1}$ is divisible by $x_i$, and therefore $x_{i+1} \\geq 2x_i$, that is, $n^2 \\geq x^2 \\geq 2^{k-1}$, from which the required follows. That is, the values $x_1, \\ldots, x_k$ can be stored naively in some dynamic array. Now suppose we want to move the right endpoint, then the array $(x_1, \\ldots, x_k)$ should be replaced by $([x_1, a_r], \\ldots, [x_k, a_k], a_k)$ and remove values greater than $n^2+1$ from the new array, as well as get rid of duplicates. All these actions can be performed in $O(n \\log n)$ time, after which we just need to find the MEX among the known set of values. This solution can also serve as proof that the desired MEX does not exceed $n \\cdot (1 + 2 \\log_2 n)$, which is less than $10^9$ under the constraints of the problem. Thus, initially, we can only maintain numbers less than $10^9$ and not worry about overflows of a 64-bit integer type.",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1834",
    "index": "F",
    "title": "Typewriter",
    "statement": "Recently, Polycarp was given an unusual typewriter as a gift! Unfortunately, the typewriter was defective and had a rather strange design.\n\nThe typewriter consists of $n$ cells numbered from left to right from $1$ to $n$, and a carriage that moves over them. The typewriter cells contain $n$ \\textbf{distinct} integers from $1$ to $n$, and each cell $i$ initially contains the integer $p_i$. Before all actions, the carriage is at cell number $1$ and there is nothing in its buffer storage. The cell on which the carriage is located is called the \\textbf{current} cell.\n\nThe carriage can perform five types of operations:\n\n- Take the integer from the current cell, if it is not empty, and put it in the carriage buffer, if it is empty (this buffer can contain \\textbf{no more than one} integer).\n- Put the integer from the carriage buffer, if it is not empty, into the current cell, if it is empty.\n- Swap the number in the carriage buffer with the number in the current cell, if both the buffer and the cell contain integers.\n- Move the carriage from the current cell $i$ to cell $i + 1$ (if $i < n$), while the integer in the buffer is preserved.\n- Reset the carriage, i.e. move it to cell number $1$, while the integer in the buffer is preserved.\n\nPolycarp was very interested in this typewriter, so he asks you to help him understand it and will ask you $q$ queries of three types:\n\n- Perform a cyclic shift of the sequence $p$ to the left by $k_j$.\n- Perform a cyclic shift of the sequence $p$ to the right by $k_j$.\n- Reverse the sequence $p$.\n\nBefore and after each query, Polycarp wants to know what \\textbf{minimum} number of carriage resets is needed for the current sequence in order to distribute the numbers to their cells (so that the number $i$ ends up in cell number $i$).\n\nNote that Polycarp only wants to know the minimum number of carriage resets required to arrange the numbers in their places, but \\textbf{he does not actually distribute them}.\n\nHelp Polycarp find the answers to his queries!",
    "tutorial": "Let's solve the problem if there are no requests. The key object for us will be such cells that the number in them is less than the cell index. Note that for one carriage reset, we can transfer no more than one such number. So we have a lower bound on the answer. Let's build a graph with edges $i\\rightarrow a[i]$. Then it will break up into cycles. Let's find the first position where $a[i] \\neq i$, take a number from this position, shift it to $a[i]$, take a number from position $a[i]$, and so on. Then we will put the whole cycle in its place. How many carriage drops will there be? Exactly as many edges as there are such that $a[i] < i$. That is, the answer is exactly equal to the number of positions where $a[i] < i$. Let's learn how to solve for shifts. Let's find for each cell such positions of the beginning of the array that it will satisfy $a[i] < i$ in this configuration. It is easy to see that for a particular cell, such indexes will form a segment (possibly a prefix + suffix). Let's create a separate array and add one on these segments. Then in the i-th position there will be an answer if the array starts from the i-th cell. Now let's solve for an array flip. It is easy to see that for this you can simply maintain the entire previous structure, but with the inverted original configuration of cells. Asymptotic: $O(n + q)$.",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1835",
    "index": "A",
    "title": "k-th equality",
    "statement": "Consider all equalities of form $a + b = c$, where $a$ has $A$ digits, $b$ has $B$ digits, and $c$ has $C$ digits. All the numbers are \\textbf{positive} integers and are written without leading zeroes. Find the $k$-th lexicographically smallest equality when written as a string like above or determine that it does not exist.\n\nFor example, the first three equalities satisfying $A = 1$, $B = 1$, $C = 2$ are\n\n- $1 + 9 = 10$,\n- $2 + 8 = 10$,\n- $2 + 9 = 11$.\n\nAn equality $s$ is lexicographically smaller than an equality $t$ with the same lengths of the numbers if and only if the following holds:\n\n- in the first position where $s$ and $t$ differ, the equality $s$ has a smaller digit than the corresponding digit in $t$.",
    "tutorial": "The largest possible value for $a$ is $10^6 - 1$, so we can iterate over each possibility. When we fix $a$, we can find the range of values for $b$ such that $10^{C - 1} \\leq a + b < 10^C$, and $10^{B - 1} \\leq b < 10^B$. For each such value, we have a correct equality. We can easily find this range. We get that $\\max \\{ 10^{C - 1} - a, 10^{B - 1} \\} \\leq b < \\min \\{ 10^C - a, 10^B \\}$ and from this inequality, we know how many equations for the given $a$ we have. As we start by minimizing $a$, we can find its value for the $k$-th equation if we iterate from the smallest possible values of $a$. When we have fixed $a$ (or find out that there is no such equation), we iterate over all possible values of $b$ and check if the resulting $c$ has $C$ digits. The complexity is $\\mathcal{O}(10^A + 10^B)$.",
    "code": "#include <bits/stdc++.h>\n\nint power(int a, int e) {\n    if (e == 0) return 1;\n    return e == 1 ? a : a * power(a, e-1);\n}\n\nvoid answer(int a, int b) {\n    std::cout << a << \" + \" << b << \" = \" << a+b << std::endl;\n}\n\nint main() {\n    using ll = long long;\n    \n    int t;\n    std::cin >> t;\n    while (t--) {\n\n        int a, b, c;\n        ll k;\n        std::cin >> a >> b >> c >> k;\n        \n        bool good = false;\n    \n        for (int i = power(10, a-1); i < power(10, a); ++i) {\n            int left = std::max(power(10, b-1), power(10, c-1) - i);\n            int right = std::min(power(10, b)-1, power(10, c) - 1 - i);\n            if (left > right) continue;\n    \n            int have = right - left + 1;\n            if (k <= have) {\n                answer(i, left + k - 1);\n                good = true;\n                break;\n            }\n    \n            k -= have;\n        }\n    \n        if (!good) std::cout << \"-1\" << std::endl;\n    }\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1835",
    "index": "B",
    "title": "Lottery",
    "statement": "$n$ people indexed with integers from $1$ to $n$ came to take part in a lottery. Each received a ticket with an integer from $0$ to $m$.\n\nIn a lottery, one integer called target is drawn uniformly from $0$ to $m$. $k$ tickets (or less, if there are not enough participants) with the closest numbers to the target are declared the winners. In case of a draw, a ticket belonging to the person with a smaller index is declared a winner.\n\nBytek decided to take part in the lottery. He knows the values on the tickets of all previous participants. He can pick whatever value he wants on his ticket, but unfortunately, as he is the last one to receive it, he is indexed with an integer $n + 1$.\n\nBytek wants to win the lottery. Thus, he wants to know what he should pick to maximize the chance of winning. He wants to know the smallest integer in case there are many such integers. Your task is to find it and calculate his chance of winning.",
    "tutorial": "Let's assume that Bytek has selected a certain position $c$. Let the closest occupied position to the left be $d$, and the closest occupied position to the right be $e$. Let's denote the position of the $k$-th person to the left as $a$ and the $k$-th person to the right as $b$ (on the picture $k=3$). Note that for Bytek to win, the target position should be closer to him than $a$ and closer to him than $b$. So his winning range is in the interval $(\\frac{a+c}{2}, \\frac{b+c}{2})$. It will either have a length of $\\lfloor \\frac{b-a}{2}-1 \\rfloor$ or $\\lfloor \\frac{b-a}{2}-2 \\rfloor$, which depends only on whether he chooses an even or odd position relative to the people on positions $a$ and $b$. So the solution to the task was to consider each pair of people standing next to each other and see what happens if Bytek stands between them. To do this, we find the person $k$ positions to the left and $k$ positions to the right for Bytek and then check what the result will be if Bytek stands on the leftmost position inside this interval and what if Bytek stands on the second position from the left inside this interval. The other positions in this interval would give Bytek the same results but wouldn't be the leftmost. In addition, we should look at what would happen if Bytek stood in a position where someone is already standing (this may help if there is not enough space between consecutive people). There are also two more edge cases - from the left and the right. One of these cases is to look at what would happen if Bytek stands one or two positions in front of the $k$-th person from the left. This position would give Bytek the biggest winning range containing $0$. The other case is analogous from the right. The final complexity is $\\mathcal{O}(n)$ or $\\mathcal{O}(n \\log n)$ based on implementation.",
    "code": "#include <bits/stdc++.h>\n \n#define forr(i, n) for (int i = 0; i < n; i++)\n#define FOREACH(iter, coll) for (auto iter = coll.begin(); iter != coll.end(); ++iter)\n#define FOREACHR(iter, coll) for (auto iter = coll.rbegin(); iter != coll.rend(); ++iter)\n#define lbound(P, K, FUN) ({auto SSS=P, PPP = P-1, KKK=(K)+1; while(PPP+1!=KKK) {SSS = (PPP+(KKK-PPP)/2); if(FUN(SSS)) KKK = SSS; else PPP = SSS;} PPP; })\n#define testy()    \\\n    int _tests;    \\\n    cin >> _tests; \\\n    FOR(_test, 1, _tests)\n#define CLEAR(tab) memset(tab, 0, sizeof(tab))\n#define CONTAIN(el, coll) (coll.find(el) != coll.end())\n#define FOR(i, a, b) for (int i = a; i <= b; i++)\n#define FORD(i, a, b) for (int i = a; i >= b; i--)\n#define MP make_pair\n#define PB push_back\n#define ff first\n#define ss second\n#define deb(X) X;\n#define SIZE(coll) ((int)coll.size())\n \n#define M 1000000007\n#define INF 1000000007LL\n \nusing namespace std;\n \nlong long n, m, k;\nlong long poz_l, poz_p;\nvector<long long> v;\n \nlong long policz_ile(long long strzal)\n{\n    while (poz_l < n && v[poz_l] < strzal)\n        poz_l++;\n    while (poz_p < n && v[poz_p] <= strzal)\n        poz_p++;\n \n    long long pocz = poz_p < k ? 0 : (strzal + v[poz_p - k]) / 2 + 1;\n    long long kon = poz_l + k - 1 >= n ? m : (v[poz_l + k - 1] + strzal - 1) / 2;\n \n    return max(0ll, kon - pocz + 1);\n}\n \nint solve()\n{\n    cin >> n >> m >> k;\n    long long a;\n    forr(i, n)\n    {\n        cin >> a;\n        v.PB(a);\n    }\n    sort(v.begin(), v.end());\n    v.PB(m + 1);\n    long long res = policz_ile(0), best = 0;\n    forr(i, n)\n    {\n        long long pocz = i == 0 ? max(0ll, v[i] - 2) : max(v[i] - 2, v[i - 1] + 3);\n        long long kon = min(m, v[i] + 2);\n        for (long long s = pocz; s <= kon; s++)\n        {\n            long long ile = policz_ile(s);\n \n            if (ile > res)\n            {\n                res = ile;\n                best = s;\n            }\n        }\n    }\n    cout << res << \" \" << best << '\\n';\n \n    return 0;\n}\n \nint main()\n{\n    std::ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n \n    solve();\n \n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1835",
    "index": "C",
    "title": "Twin Clusters",
    "statement": "Famous worldwide astrophysicist Mleil waGrasse Tysok recently read about the existence of twin galaxy clusters. Before he shares this knowledge with the broader audience in his podcast called S.tarT-ok, he wants to prove their presence on his own. Mleil is aware that the vastness of the universe is astounding (almost as astounding as his observation skills) and decides to try his luck and find some new pair of twin clusters.\n\nTo do so, he used his TLEscope to observe a part of the night sky that was not yet examined by humanity in which there are exactly $2^{k + 1}$ galaxies in a row. $i$-th of them consist of exactly $0 \\le g_i < 4^k$ stars.\n\nA galaxy cluster is any non-empty contiguous segment of galaxies. Moreover, its' trait is said to be equal to the bitwise XOR of all values $g_i$ within this range.\n\nTwo galaxy clusters are considered twins if and only if they have the same traits and their corresponding segments are \\textbf{disjoint}.\n\nWrite a program that, for many scenarios, will read a description of a night sky part observed by Mleil and outputs a location of two intervals belonging to some twin clusters pair, or a single value $-1$ if no such pair exists.",
    "tutorial": "Deterministic solution: Let us first look for segments that zeros first $k$ (out of $2k$) bits. Since we have $n = 2^{k + 1}$, then we have $n + 1$ prefix xors of the array (along with en empty prefix). Let us look at the xor prefix modulo $2^k$. Each time we have a prefix xor that has already occurred before let us match it with this previous occurrence. We will find at least $2^k + 1$ such segments. Note that segments have pairwise different ends and pairwise different beginnings. Each of those segments generates some kind of xor value on the other $k$ bits. Since there is only $2^k$ different possible values, due to pigeon principle there will be two segments that generate same xor. We select those two intervals. If they are disjoint then we already found the answer. Otherwise the final answer will be the xor of those two segments (values that are covered only by one of them). It can be showed that we will obtain two disjoint, non-empty segments. Nondeterministic solution: If there are any duplicates in the array, then we can take two one-element arrays and obtain answer. From now on we will assume that no duplicates occur in the array. Let us observe that number of valid segments is equal to ${n \\choose 2} + n \\ge 2^{2k + 1}$ which is over twice larger than all possible xor values for a segment which is $2^{2k}$. This suggest, that chances of collision of two random segments is quite high. For simplicity let us assume there is exactly $2^{2k + 1}$ segments. Let us look at the final distribution over the xors used by segments. It can be showed by exchange argument, that the the distribution that needs the most random tosses to obtain collision is the one in which every xor value is used by exactly two segments. Since we choose segments randomly, by birthday paradox the expected time of obtaining a collision is around 2^k. Now there is a chance, that we will toss the same segment twice, but if we multiply the number of tossing by $\\log(n)$ then chance that we find two different segments is very high (in reality even less random choices are necessary). There is another issue, even if we find two different segments with the same xor values. They can use common elements. But then we can simply take only the elements that belong to the exactly one of them. Still if the segments had common end one of the obtained segments would be empty. To omit this issue let us see that the second obtained segment would have xor equal to $0$. So now we can take any prefix and corresponding suffix as an answer. Unfortunately this segment can have length $1$. But in this case the only element in the segment has to be equal to $0$. There must be at most one number $0$ in the array, so we can simply get rid of it (shorten the array by one). The analysis still holds (with some slight modifications).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve()\n{\n    int k, n;\n    scanf(\"%d\", &k);\n\n    n = 2 << k;\n\n    vector <long long> input(n + 1);\n    vector <int> memHighBits(1 << k, -1);\n    vector <pair <int, int> > memLowBits(1 << k, {-1, -1});\n    \n    auto addInterval = [&memLowBits, &input](int s, int e) {\n        const int remXor = input[e] ^ input[s - 1];\n        auto &[os, oe] = memLowBits[remXor];\n\n        if (os == -1) {\n            os = s, oe = e;\n            return false;\n        }\n\n        if (oe < s) {\n            printf(\"%d %d %d %d\\n\", os, oe, s, e);\n        } else {\n            printf(\"%d %d %d %d\\n\", min(s, os), max(s, os) - 1, oe + 1, e);\n        }\n\n        return true;\n    };\n\n    memHighBits[0] = 0;\n    for (int i = 1; i <= n; ++i) {\n        scanf(\"%lld\", &input[i]);\n        input[i] ^= input[i - 1];\n    }\n\n    for (int i = 1; i <= n; ++i) {\n        if (memHighBits[input[i] >> k] != -1) {\n            if (addInterval(memHighBits[input[i] >> k] + 1, i)) {\n                break;\n            }\n        }\n\n        memHighBits[input[i] >> k] = i;\n    }\n}\n\nint main()\n{\n    int cases;\n    scanf(\"%d\", &cases);\n\n    while (cases--) {\n        solve();\n    }\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "math",
      "probabilities"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1835",
    "index": "D",
    "title": "Doctor's Brown Hypothesis",
    "statement": "The rebels have been crushed in the most recent battle with the imperial forces, but there is a ray of new hope.\n\nMeanwhile, on one of the conquered planets, Luke was getting ready for an illegal street race (which should come as no surprise, given his family history). Luke arrived at the finish line with 88 miles per hour on his speedometer. After getting out of the car, he was greeted by a new reality. It turns out that the battle has not happened yet and will start in exactly $k$ hours.\n\nThe rebels have placed a single battleship on each of the $n$ planets. $m$ unidirectional wormholes connect the planets. Traversing each wormhole takes exactly one hour. Generals of the Imperium have planned the battle precisely, but their troops cannot dynamically adapt to changing circumstances. Because of this, it is enough for the rebels to move some ships around before the battle to confuse the enemy, secure victory and change the galaxy's fate.\n\nOwing to numerous strategical considerations, which we now omit, the rebels would like to choose two ships that will switch places so that both of them will be on the move for the whole time (exactly $k$ hours). In other words, rebels look for two planets, $x$ and $y$, such that paths of length $k$ exist from $x$ to $y$ and from $y$ to $x$.\n\nBecause of the limited fuel supply, choosing one ship would also be acceptable. This ship should fly through the wormholes for $k$ hours and then return to its initial planet.\n\nHow many ways are there to choose the ships for completing the mission?",
    "tutorial": "As both vertices must visit each other, they must be in the same strongly connected component. We can compute all SCC and solve for them independently. Further, we will assume that we are solving for a fixed SCC. The critical observation is that $n^3$ is enormous, and we can visit an entire graph. This gives us hope that if we fix a vertex $v$, we can represent all vertices that are reachable from it. If we compute the greatest common divisor of all cycles in our graph $g$, then all paths from a fixed vertex $s$ to a vertex $t$ have the same remainder modulo $g$. Moreover, we can always find such if we are looking for a long enough path and the correct remainder. It turns out that $n^3$ is a large enough bound for such paths. Now we have to find the greatest common divisor of all cycles in the graph. There are many ways (including linear), but we are going to present $\\mathcal{O}(n \\log n)$ here. First, find any cycle in the graph. As $g$ has to divide it, we just have to consider its divisors. We'll develop a quick way to find if a divisor $d$ divides $g$. To do this, we check if there is a colouring with colours from $0$ to $d - 1$, such that for every edge $\\langle u, v \\rangle$, $colour (v) = (colour (u) + 1) \\mod d$. We can check for such colouring with a simple DFS in a linear time. To obtain the right complexity, we'll only check prime divisors (and their powers, and take the least common multiple of the ones which divide $g$. Now we have to find all pairs $\\langle s, t \\rangle$ such that there are paths from $s$ to $t$ and from $t$ to $s$ of length $k$. We have two cases. Either $g | k$ and $colour(s) = colour(t)$ or $2 | g$ and $k = g / 2 \\mod g$ and $colour(s) = (colour(t) + g / 2) \\mod g$. After preprocessing, we can check both cases in $\\mathcal{O}(g)$ time. The final complexity is $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n)$ depending on the implementation.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n#define sz(s) (int)s.size()\n#define all(s) s.begin(), s.end()\n#define pb push_back\n#define FOR(i, n) for(int i = 0; i < n; i++)\n \nusing vi = vector<int>;\nusing vvi = vector<vi>;\n \nstruct SCC {\n    int cnt = 0;\n    vi vis, scc_nr;\n    vvi scc_list, DAG;\n \n    SCC(){}\n \n    SCC(vvi & G){\n        // G is 0 indexed!\n        int n = sz(G);\n        vvi G_rev(n);\n        vis = scc_nr = vi(n);\n \n        vi postorder;\n        for(int i = 0; i < n; i++)\n            if(!vis[i])\n                dfs_post(i, G, G_rev, postorder);\n        \n        vis = vi(n);\n        while(sz(postorder)){\n            auto akt = postorder.back();\n            postorder.pop_back();\n            if(!vis[akt]){\n                DAG.emplace_back();\n                scc_list.emplace_back();\n                dfs_rev(akt, G_rev);\n                cnt++;\n            }\n        }\n \n        // optional\n        for(int i = 0; i < sz(DAG); i++){\n            sort(all(DAG[i]));\n            DAG[i].resize(unique(all(DAG[i])) - DAG[i].begin());\n        }\n    }\n \n    void dfs_post(int start, vvi & G, vvi & G_rev, vi & postorder){\n        vis[start] = 1;\n        for(auto & u : G[start]){\n            G_rev[u].pb(start);\n            if(!vis[u])\n                dfs_post(u, G, G_rev, postorder);\n        }\n        \n        postorder.pb(start);\n    }\n \n    void dfs_rev(int start, vvi & G_rev){\n        vis[start] = true;\n        scc_list.back().pb(start);\n        scc_nr[start] = cnt;\n \n        for(auto & u : G_rev[start])\n            if(!vis[u])\n                dfs_rev(u, G_rev);\n            else if(scc_nr[u] != cnt)\n                DAG[scc_nr[u]].pb(cnt);\n    }\n};\n \nint main()\n{\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    long long n, m, k;\n    cin >> n >> m >> k;\n \n    vvi G(n);\n \n    set<pair<int, int>> edges;\n    for (int i = 0; i < m; i++)\n    {\n        int a, b;\n        cin >> a >> b;\n        a--, b--;\n        G[a].pb(b);\n        edges.insert({a, b});\n    }\n \n    SCC scc(G);\n    vi coloring(n, -1);\n \n    auto try_coloring = [&](int num_col, const vi& group)\n    {\n        vi visited;\n        function<bool(int)> dfs = [&](int start){\n            visited.pb(start);\n            \n            bool good_coloring = true;\n            for (auto & u : G[start])\n            {\n                if (scc.scc_nr[u] != scc.scc_nr[start])\n                {\n                    continue;\n                }\n                if (coloring[u] == -1)\n                {\n                    coloring[u] = (coloring[start] + 1) % num_col;\n                    good_coloring &= dfs(u);\n                }\n                else\n                {\n                    good_coloring &= coloring[u] == (coloring[start] + 1) % num_col;\n                }\n \n                if (not good_coloring)\n                {\n                    break;    \n                }\n            }\n \n            return good_coloring;\n        };\n \n        coloring[group[0]] = 0;\n        if (not dfs(group[0]))\n        {\n            for (auto & u : visited)\n            {\n                coloring[u] = -1;\n            }\n            return vvi();\n        }\n        else\n        {\n            vvi ret(num_col);\n            for (auto & u : visited)\n            {\n                ret[coloring[u]].push_back(u);\n            }\n            return ret;\n        }\n    };\n \n    long long ans = 0;\n    vi depths(n, -1);\n \n    for (vi& group : scc.scc_list)\n    {\n        n = sz(group);\n \n        if (n == 1 and edges.count({group[0], group[0]}) == 0)\n        {\n            continue;\n        }\n        int gcd = -1;\n        function<void(int)> dfs_depths = [&](int start)\n        {\n            for (auto & u : G[start])\n            {\n                if (scc.scc_nr[u] != scc.scc_nr[start])\n                {\n                    continue;\n                }\n \n                if (depths[u] == -1)\n                {\n                    depths[u] = depths[start] + 1;\n                    dfs_depths(u);\n                }\n                else {\n                    int diff = abs(depths[u] - (depths[start] + 1));\n                    if (diff)\n                    {\n                        if (gcd == -1)\n                        {\n                            gcd = diff;\n                        }\n                        else\n                        {\n                            gcd = __gcd(gcd, diff);\n                        }\n                    }\n                }\n            }\n        };\n \n        depths[group[0]] = 0;\n        dfs_depths(group[0]);\n        assert(gcd != -1);\n \n        vvi by_color = try_coloring(gcd, group);\n \n        assert(sz(by_color) != 0);\n        if (k % gcd == 0)\n        {\n            FOR (i, gcd)\n            {\n                ans += sz(by_color[i]) + 1ll * sz(by_color[i]) * (sz(by_color[i]) - 1) / 2;\n            }\n        }\n        else if (k % gcd * 2 == gcd)\n        {\n            FOR (i, gcd / 2)\n            {\n                ans += 1ll * sz(by_color[i]) * sz(by_color[i + gcd / 2]);\n            }\n        }\n    }\n    cout << ans << '\\n';\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1835",
    "index": "E",
    "title": "Old Mobile",
    "statement": "During the latest mission of the starship U.S.S. Coder, Captain Jan Bitovsky was accidentally teleported to the surface of an unknown planet.\n\nTrying to find his way back, Jan found an artifact from planet Earth's ancient civilization — a mobile device capable of interstellar calls created by Byterola. Unfortunately, there was another problem. Even though Jan, as a representative of humans, knew perfectly the old notation of the cell phone numbers, the symbols on the device's keyboard were completely worn down and invisible to the human eye. The old keyboards had exactly $m + 1$ buttons, one for each digit from the base $m$ numerical system, and one single backspace button allowing one to erase the last written digit (if nothing was written on the screen, then this button does nothing, but it's still counted as pressed).\n\nJan would like to communicate with his crew. He needs to type a certain number (also from the base $m$ numerical system, that is, digits from $0$ to $m - 1$). He wants to know the expected number of button presses necessary to contact the U.S.S. Coder. Jan always chooses the most optimal buttons based on his current knowledge. Buttons are indistinguishable until pressed. Help him!",
    "tutorial": "Let us make some observations. First of them is that if a phone number consists of two or more digits of the same kind then we will always pay exactly $1$ click for each but the first occurrence of it (it follows from the fact, that we have to already the key responsible for this digit). This is why we can reduce the problem to finding a solution for a phone number with unique digits. Secondly, since all the buttons are indistinguishable at the beginning then the order of digits in the input does not matter. This leads to the conclusion that what we want to compute is some kind of $dp[i][j]$, which stands for expected time of completing number if $i$ buttons that we have to eventually click are not yet discovered (good buttons), and $j$ buttons that we don't need are also not yet discovered (bad buttons). Unfortunately the BackSpace key and necessity of clearing incorrect prefix of the phone number complicates things significantly. We will create additional dimension of the $dp$ responsible for the state of the prefix and the information about if we have already clicked backspace. Those four states will be: $EMPTY$ - empty prefix of digits on the screen $GOOD$ - non empty, correct prefix of digits on the screen $BAD$ - non empty prefix that is not prefix of the phone number $BACKSPACE$ - when we have already found a backspace (we assume prefix is correct, or in other words paid in advance) Let us first compute $dp[i][j][BACKSPACE]$. If $i = 0$ then $dp[0][j][BACKSPACE] = 0$. Else we try to click new buttons. If we guess correctly exactly the next button then we get $dp[i][j][BACKSPACE] = 1 + dp[i - 1][j][BACKSPACE]$. Otherwise we could guess one of the remaining good buttons (with probability $\\frac{i - 1}{i + j}$. Since we already know backspace location, we can remove it and in future we will pay only $1$ for this digit. We hence get $3 + dp[i - 1][j][BACKSPACE]$ operations. Similarly if we guess bad button we get $dp[i][j][BACKSPACE] = 2 + dp[i][j - 1][BACKSPACE]$. Rest of the states can be computed using similar approach: $dp[i][j][GOOD]= \\begin{cases} 0, & \\text{if } i = 0 \\\\ 1 + dp[i - 1][j][GOOD], & \\text{when tossing exactly correct digit} \\\\ 3 + dp[i - 1][j][BAD], & \\text{for one of the remaining good digits} \\\\ & \\text{(in future we will have to remove it and use in correct place)} \\\\ 2 + dp[i][j - 1][BAD], & \\text{for guessing bad digit} \\\\ 2 + dp[i][j][BACKSPACE], & \\text{when clicking backspace button} \\\\ & \\text{(removing good digit from the prefix which we need to fix)} \\end{cases}$ $dp[i][j][BAD]= \\begin{cases} 3 + dp[i - 1][j][BAD], & \\text{when guessing any good digit} \\\\ 2 + dp[i][j - 1][BAD], & \\text{for bad digit} \\\\ dp[i][j][BACKSPACE], & \\text{when clicking backspace} \\\\ & \\text{(this click was paid in advance)} \\end{cases}$ $dp[i][j][EMPTY]= \\begin{cases} 1 + dp[i - 1][j][GOOD], & \\text{when tossing correct digit} \\\\ 3 + dp[i - 1][j][BAD], & \\text{when guessing other good digit} \\\\ 2 + dp[i][j - 1][BAD], & \\text{for bad digit} \\\\ 1 + dp[i][j][BACKSPACE], & \\text{when clicking backspace} \\end{cases}$ Even though transitions may look scary, they are similar for different dimensions and common implementation can be used.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconstexpr int MAX_M = 1000 + 7;\nconstexpr int PRECISION = 9;\nconstexpr long long MOD = 1e9 + 7;\n \nlong long mod_inv[MAX_M];\nlong long DP[MAX_M][MAX_M][2][2];\nlong long DPprob[MAX_M][MAX_M][2][2];\nbool updated[MAX_M][MAX_M][2][2];\n// DP[correct][incorrect][backspace][bad suffix]\n \nlong long calc_mod_inv(long long n)\n{\n    long long res = 1;\n    long long exp = MOD - 2;\n \n    while (exp)\n    {\n        if (exp & 1)\n        {\n            res = (res * n) % MOD;\n        }\n \n        exp >>= 1;\n        n = (n * n) % MOD;\n    }\n \n    return res;\n}\n \nvoid calc_DP(int digits, int needed)\n{\n    DP[0][0][0][0] = 0;\n    DPprob[0][0][0][0] = 1;\n \n    struct ID\n    {\n        int x, y, z, s;\n    };\n \n    queue <ID> dp_queue;\n    dp_queue.push({0, 0, 0, 0});\n \n    while(!dp_queue.empty())\n    {\n        auto [x, y, z, s] = dp_queue.front();\n        dp_queue.pop();\n \n        if (updated[x][y][z][s])\n        {\n            continue;\n        }\n \n        updated[x][y][z][s] = true;\n \n        long long left = digits + 1 - x - y - z;\n        long long corr = needed - x;\n        long long incorr = digits - needed - y;\n        long long prob = DPprob[x][y][z][s];\n \n        if (corr == 0 and s == 0)\n        {\n            // done\n            continue;\n        }\n \n        // correct suffix\n        if (s == 0)\n        {\n            if (corr > 0)\n            {\n                // found the one correct digit (no need to delete)\n                long long opt_prob = (prob * mod_inv[left]) % MOD;\n                DPprob[x + 1][y][z][0] = (DPprob[x + 1][y][z][0] + opt_prob) % MOD;\n                DP[x + 1][y][z][0] = (DP[x + 1][y][z][0] + DP[x][y][z][0] * mod_inv[left]) % MOD;\n \n                // found a needed but currently wrong digit (needs to be deleted)\n                if (corr > 1)\n                {\n                    if (z == 0) // if backspace is not known, the suffix is bad\n                    {\n                        long long opt_prob = ((prob * (corr - 1) % MOD) * mod_inv[left]) % MOD;\n                        DPprob[x + 1][y][z][1] = (DPprob[x + 1][y][z][1] + opt_prob) % MOD;\n \n                        DP[x + 1][y][z][1] = (DP[x + 1][y][z][1] + ((corr - 1) * mod_inv[left] % MOD) * DP[x][y][z][0] + 2 * opt_prob) % MOD;\n                        dp_queue.push({x + 1, y, z, 1});\n                    }\n                    else // if backspace is known, the suffix can be instantly repaired\n                    {\n                        long long opt_prob = ((prob * (corr - 1) % MOD) * mod_inv[left]) % MOD;\n                        DPprob[x + 1][y][z][0] = (DPprob[x + 1][y][z][0] + opt_prob) % MOD;\n                        DP[x + 1][y][z][0] = (DP[x + 1][y][z][0] + ((corr - 1) * mod_inv[left] % MOD) * DP[x][y][z][0] + 2 * opt_prob) % MOD;\n                    }\n                }\n \n                dp_queue.push({x + 1, y, z, 0});\n            }\n \n            if (incorr > 0)\n            {\n                // found an incorrect digit\n                if (z == 0)\n                {\n                    long long opt_prob = (prob * incorr % MOD) * mod_inv[left] % MOD;\n                    DPprob[x][y + 1][z][1] = (DPprob[x][y + 1][z][1] + opt_prob) % MOD;\n                    DP[x][y + 1][z][1] = (DP[x][y + 1][z][1] + (incorr * mod_inv[left] % MOD) * DP[x][y][z][0] + 2 * opt_prob) % MOD;\n                    dp_queue.push({x, y + 1, z, 1});\n                }\n                else // suffix can be repaired\n                {\n                    long long opt_prob = ((prob * incorr % MOD) * mod_inv[left]) % MOD;\n                    DPprob[x][y + 1][z][0] = (DPprob[x][y + 1][z][0] + opt_prob) % MOD;\n                    DP[x][y + 1][z][0] = (DP[x][y + 1][z][0] + (incorr * mod_inv[left] % MOD) * DP[x][y][z][0] + 2 * opt_prob) % MOD;\n                    dp_queue.push({x, y + 1, z, 0});\n                }\n            }\n \n            if (z == 0)\n            {\n                if (x > 0) // deleted correct digit\n                {\n                    long long opt_prob = prob * mod_inv[left] % MOD;\n                    DPprob[x][y][1][0] = (DPprob[x][y][1][0] + opt_prob) % MOD;\n                    DP[x][y][1][0] = (DP[x][y][1][0] + mod_inv[left] * DP[x][y][0][0] + 2 * opt_prob) % MOD;\n                }\n                else // deleted nothing\n                {\n                    long long opt_prob = prob * mod_inv[left] % MOD;\n                    DPprob[x][y][1][0] = (DPprob[x][y][1][0] + opt_prob) % MOD;\n                    DP[x][y][1][0] = (DP[x][y][1][0] + mod_inv[left] * DP[x][y][0][0] + opt_prob) % MOD;\n                }\n \n                dp_queue.push({x, y, 1, 0});\n            }\n        }\n \n        if (s == 1)\n        {\n            if (corr > 0)\n            {\n                // found a needed but currently wrong digit (needs to be deleted)\n                long long opt_prob = (prob * corr % MOD) * mod_inv[left] % MOD;\n                DPprob[x + 1][y][z][1] = (DPprob[x + 1][y][z][1] + opt_prob) % MOD;\n                DP[x + 1][y][z][1] = (DP[x + 1][y][z][1] + (corr * mod_inv[left] % MOD) * DP[x][y][z][1] + 2 * opt_prob) % MOD;\n                dp_queue.push({x + 1, y, z, 1});\n            }\n \n            if (incorr > 0)\n            {\n                // found an incorrect digit\n                long long opt_prob = (prob * incorr % MOD) * mod_inv[left] % MOD;\n                DPprob[x][y + 1][z][1] = (DPprob[x][y + 1][z][1] + opt_prob) % MOD;\n                DP[x][y + 1][z][1] = (DP[x][y + 1][z][1] + (incorr * mod_inv[left] % MOD) * DP[x][y][z][1] + 2 * opt_prob) % MOD;\n                dp_queue.push({x, y + 1, z, 1});\n            }\n \n            if (z == 0)\n            {\n                // deleted bad suffix\n                long long opt_prob = prob * mod_inv[left] % MOD;\n                DPprob[x][y][1][0] = (DPprob[x][y][1][0] + opt_prob) % MOD;\n                DP[x][y][1][0] = (DP[x][y][1][0] + mod_inv[left] * DP[x][y][0][1]) % MOD;\n                dp_queue.push({x, y, 1, 0});\n            }\n        }\n    }\n}\n \nint main()\n{\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n \n    mod_inv[0] = 1;\n    for (int i = 1; i < MAX_M; ++i) {\n        mod_inv[i] = calc_mod_inv(i);\n        assert (mod_inv[i] * i % MOD == 1);\n    }\n \n    int n, m;\n    cin >> n >> m;\n \n    set <int> different_digits;\n \n    for (int i = 0; i < n; ++i)\n    {\n        int p;\n        cin >> p;\n \n        different_digits.insert(p);\n    }\n \n    int needed = different_digits.size();\n \n    calc_DP(m, needed);\n \n    long long result = 0;\n \n    for (int i = 0; i <= MAX_M; ++i)\n    {\n        result = (result + DP[needed][i][0][0]) % MOD;\n        result = (result + DP[needed][i][1][0]) % MOD;\n    }\n \n    cout << (result + n) % MOD << \"\\n\";\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "probabilities"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1835",
    "index": "F",
    "title": "Good Graph",
    "statement": "You are given a bipartite graph $G$ with the vertex set in the left part $L$, in the right part $R$, and $m$ edges connecting these two sets. We know that $|L| = |R| = n$.\n\nFor any subset $S \\subseteq L$, let $N(S)$ denote the set of all neighbors of vertices in $S$. We say that a subset $S \\subseteq L$ in graph $G$ is tight if $|S| = |N(S)|$. We say that graph $G$ is good if $\\forall_{S \\subseteq L}, |S| \\leq |N(S)|$.\n\nYour task is to verify whether the graph is good and, if so, to optimize it. If the graph is not good, find a subset $S \\subseteq L$ such that $|S| > |N(S)|$. However, if the graph is good, your task is to find a good bipartite graph $G'$ with the same set of vertices $L \\cup R$, in which $\\forall_{S \\subseteq L}$, $S$ is tight in $G$ if and only if $S$ is tight in $G'$. If there are multiple such graphs, choose one with the smallest possible number of edges. If there are still multiple such graphs, print any.",
    "tutorial": "According to Hall's theorem, a graph is good if and only if a perfect matching exists. We run any reasonable algorithm to find a perfect matching (e.g. the Hopcroft-Karp's algorithm). We call the found matching $\\mathcal{M}$ (any perfect matching is fine). We look for a counterexample if we do not find a perfect matching. One way to find it is to run s similar DFS as in the Hopcroft-Karp algorithm from any unmatched vertex on the left side. As a reminder, we visit all neighbours of vertices on the left side and only the vertex with which we are matched for vertices on the right side. As we won't see any unmatched vertex on the right side (otherwise, we'd found an augmenting path), the set of visited vertices on the left side has fewer neighbours than its size - we found our counterexample. As our graph is good, we should examine the construction of tight sets. Lemma 1 Function $N(S)$ is submodular. Proof Consider two sets $A \\subseteq B$ and a vertex $v \\notin B$. For each vertex $u \\in N(B + v) \\setminus N(B)$, we know that $u \\in N(A + v)$ and $u \\notin N(A)$, thus, $u \\in N(A + v) \\setminus N(A)$. We conclude that $|N(B + v) \\setminus N(B)| \\leq |N(A + v) \\setminus N(A)|$; thus, the function is submodular. Lemma 2 Tight sets are closed under intersection and sum. Proof Consider two tight sets, $A$ and $B$. From Lemma 1, we get that $|A| + |B| = |N(A)| + |N(B)| \\geq |N(A \\cup B)| + |N(A \\cap B)| \\geq |A \\cup B| + |A \\cap B| = |A| + |B|$, where the last inequality results from the graph being good. As we get the same value on both sides, all inequalities become equalities. In particular, with the graph being good, we get that $|N(A \\cup B)| = |A \\cup B|$ and $|N(A \\cap B)| = |A \\cap B|$. That proves that sets $A \\cup B$, and $A \\cap B$ are tight. We define $T(v)$ as the minimal tight set containing vertex $v$. We know such a set exists as tight sets are closed under the intersection. From that, we can conclude that any tight set can be represented as a sum of minimal tight sets. Thus, we are only interested in keeping the same minimal tight sets. We can find the minimal tight sets using the same DFS algorithm as for finding a counterexample. As the graph is large, use bitsets to optimise it. To find the smallest graph, we analyse these sets in order of nondecreasing sizes. For simplicity, we erase duplicates. When we analyse the set, we distinguish the new vertices (the ones that haven't been touched yet). There is always a new vertex, as this is the minimal tight set for at least one vertex (and we removed duplicates). If there is only one new vertex $v$, we can add an edge from $v$ to $M(v)$. Otherwise, we have to connect these vertices $v_1, v_2, \\ldots, v_k$ into a cycle - we create edges $\\langle v_1, M(v_1) \\rangle, \\langle M(v_1), v_2, \\rangle \\ldots, \\langle v_k, M(v_k) \\rangle, \\langle M(v_k), v_1 \\rangle$. If we have less than $2 \\cdot k$ edges, then there exists a vertex $v_i$ with a degree equal to $1$ - we could pick this vertex, and it'd create a minimal tight set. We still have to handle other vertices in this (i.e. the ones which are not new). We pick a representative $v$ for our cycle, which will become a representative for this set. Similarly, we have a representative for other sets. We find a partition of these vertices into a minimal number of tight sets. We add an edge between these representatives and our vertex $v$. We use a similar argument as before - if we didn't add this edge, we would find different minimal tight sets. To handle representatives, we use a disjoint set union structure. The final complexity of this algorithm is $\\mathcal{O}(N^3 / 64)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forr(i, n) for (int i = 0; i < n; i++)\n#define FOREACH(iter, coll) for (auto iter = coll.begin(); iter != coll.end(); ++iter)\n#define FOREACHR(iter, coll) for (auto iter = coll.rbegin(); iter != coll.rend(); ++iter)\n#define lbound(P, K, FUN) ({auto SSS=P, PPP = P-1, KKK=(K)+1; while(PPP+1!=KKK) {SSS = (PPP+(KKK-PPP)/2); if(FUN(SSS)) KKK = SSS; else PPP = SSS;} PPP; })\n#define testy()    \\\n    int _tests;    \\\n    cin >> _tests; \\\n    FOR(_test, 1, _tests)\n#define CLEAR(tab) memset(tab, 0, sizeof(tab))\n#define CONTAIN(el, coll) (coll.find(el) != coll.end())\n#define FOR(i, a, b) for (int i = a; i <= b; i++)\n#define FORD(i, a, b) for (int i = a; i >= b; i--)\n#define MP make_pair\n#define PB push_back\n#define ff first\n#define ss second\n#define deb(X) X;\n#define SIZE(coll) ((int)coll.size())\n\nusing namespace std;\n\nconst int MXN = 1007;\nint n, m;\nvector<int> G[MXN];\nbitset<MXN> bs[MXN], edge[MXN];\n\n// MATCHING\n\nconst int MXM = 1007 * 2;\nint skojX[MXM], skojY[MXM];\nbool vis[MXM];\n\nbool dfs_m(int x)\n{\n    vis[x] = 1;\n    FOREACH(it, G[x])\n    if (!skojY[*it] || (!vis[skojY[*it]] && dfs_m(skojY[*it])))\n    {\n        skojX[x] = *it;\n        skojY[*it] = x;\n        return 1;\n    }\n    return 0;\n}\n\nbool skoj()\n{\n    int czy = 1;\n    int res = 0;\n    while (czy)\n    {\n        czy = 0;\n        CLEAR(vis);\n        FOR(i, 1, n)\n        if (!vis[i] && !skojX[i] && dfs_m(i))\n        {\n            czy = 1;\n            res++;\n        }\n    }\n    return res == n;\n}\n\n// END OF MATCHING\n\nvoid dfs(int nr, bitset<MXN> &visited, bitset<MXN> &to_visit)\n{\n    visited[nr] = 1;\n    to_visit[nr] = 0;\n    to_visit = to_visit | (edge[nr] & (~visited));\n    for (int i = to_visit._Find_first(); i < SIZE(to_visit); i = to_visit._Find_next(i))\n        dfs(i, visited, to_visit);\n}\n\nint solve()\n{\n    cin >> n >> m;\n    forr(i, m)\n    {\n        int a, b;\n        cin >> a >> b;\n        G[a].PB(b);\n    }\n\n    int rres = skoj();\n    if (rres)\n    {\n        FOR(i, 1, n)\n        {\n            for (auto j : G[i])\n            {\n                edge[i][skojY[j]] = 1;\n            }\n        }\n        unordered_map<bitset<MXN>, vector<int>> mapa;\n        vector<pair<int, int>> vec, res;\n        FOR(i, 1, n)\n        {\n            bitset<MXN> to_visit;\n            dfs(i, bs[i], to_visit);\n            mapa[bs[i]].PB(i);\n        }\n\n        for (auto p : mapa)\n        {\n            vector<int> l = p.ss;\n            vec.PB({bs[l[0]].count(), l[0]});\n            if (l.size() == 1)\n            {\n                res.PB({l[0], l[0]});\n                continue;\n            }\n            for (int i = 0; i < SIZE(l); i++)\n            {\n                res.PB({l[i], l[i]});\n                res.PB({l[i], l[(i + 1) % SIZE(l)]});\n            }\n        }\n        sort(vec.begin(), vec.end());\n        forr(i, SIZE(vec))\n        {\n            int nr = vec[i].ss;\n            bitset<MXN> b;\n            for (int j = i - 1; j >= 0; j--)\n                if (vec[j].ff < vec[i].ff)\n                {\n                    int nr2 = vec[j].ss;\n                    if (bs[nr][nr2] && !b[nr2])\n                    {\n                        b |= bs[nr2];\n                        res.PB({nr, nr2});\n                    }\n                }\n        }\n\n        cout << \"YES\" << '\\n';\n        cout << res.size() << '\\n';\n        for (auto p : res)\n            cout << p.ff << \" \" << p.ss + n << '\\n';\n    }\n    else\n    {\n        CLEAR(vis);\n        FOR(i, 1, n)\n        {\n            if (skojX[i] == 0)\n            {\n                dfs_m(i);\n                break;\n            }\n        }\n        vector<int> v;\n        FOR(i, 1, n)\n        {\n            if (vis[i])\n                v.PB(i);\n        }\n        cout << \"NO\" << '\\n';\n        cout << v.size() << '\\n';\n        for (auto el : v)\n            cout << el << \" \";\n        cout << '\\n';\n    }\n\n    return 0;\n}\n\nint main()\n{\n    std::ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n\n    solve();\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "graph matchings",
      "graphs",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1836",
    "index": "A",
    "title": "Destroyer",
    "statement": "John is a lead programmer on a destroyer belonging to the space navy of the Confederacy of Independent Operating Systems. One of his tasks is checking if the electronic brains of robots were damaged during battles.\n\nA standard test is to order the robots to form one or several lines, in each line the robots should stand one after another. After that, each robot reports the number of robots standing in front of it \\textbf{in its line}.\n\n\\begin{center}\n{\\small An example of robots' arrangement (the front of the lines is on the left). The robots report the numbers above.}\n\\end{center}\n\nThe $i$-th robot reported number $l_i$. Unfortunately, John does not know which line each robot stands in, and can't check the reported numbers. Please determine if it is possible to form the lines in such a way that all reported numbers are correct, or not.",
    "tutorial": "We can simplify the statement to the following - can we divide the input sequence into multiple arithmetic sequences starting with $0$ and a common difference equal to $1$? Note that for each such arithmetic sequence, if a number $x > 0$ belongs to it, then $x - 1$ must also be included in it. Thus, if we denote $cnt_x$ as the number of occurrences of $x$ in the input, we must have $cnt_x \\geq cnt_{x + 1}$ for each $x \\geq 0$. We can note that if such a condition is fulfilled, we can always divide the input into described arithmetic sequences. We can implement it straightforwardly in $\\mathcal{O}(N + L)$, where $L$ is the maximum value in the input.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 1e6;\n \nint main()\n{\n    int cases;\n    scanf(\"%d\", &cases);\n    \n    while (cases--) {\n    \tint n;\n    \tscanf (\"%d\", &n);\n    \t\n    \tvector <int> cnt(n + 1);\n    \tfor (int i = 0; i < n; i++) {\n    \t\tint d;\n    \t\tscanf(\"%d\", &d);\n    \t\tif (d < n) {\n        \t\tcnt[d]++;\n    \t\t} else {\n    \t\t    cnt[n] = N;\n    \t\t}\n    \t}\n    \t\n    \tbool good = true;\n    \tfor (int i = 1; i <= n; i++) if (cnt[i] > cnt[i-1]) {\n    \t    good = false;\n    \t    break;\n    \t}\n    \t\n    \tputs(good ? \"YES\" : \"NO\");\n    }\n}",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1836",
    "index": "B",
    "title": "Astrophysicists",
    "statement": "In many, many years, far, far away, there will be a launch of the first flight to Mars. To celebrate the success, $n$ astrophysicists working on the project will be given bonuses of a total value of $k$ gold coins.\n\nYou have to distribute the money among the astrophysicists, and to make it easier, you have to assign bonuses in silver coins. Each gold coin is worth $g$ silver coins, so you have to distribute all $k \\cdot g$ silver coins among $n$ people.\n\nUnfortunately, the company has some financial troubles right now. Therefore, instead of paying the number of silver coins written on the bonus, they decided to round this amount to the nearest integer number of gold coins.\n\nThe rounding procedure is as follows. If an astrophysicist has bonus equal to $x$ silver coins, and we denote $r = x \\bmod g$, then:\n\n- If $r \\geq \\lceil \\frac{g}{2} \\rceil$, the astrophysicist receives $x + (g - r)$ silver coins;\n- Otherwise, an astrophysicists receives $x - r$ silver coins.\n\nNote that due to rounding, the total sum of actually paid money is not, in general, equal to $k \\cdot g$ silver coins. The operation $a \\bmod b$ denotes the remainder of the division of $a$ by $b$. Sum of values before rounding \\textbf{has to be equal to $k \\cdot g$ silver coins}, but some workers can be assigned $0$ silver coins.You aim to distribute the bonuses so that the company saves as many silver coins due to rounding as possible. Please note that there is always a distribution in which the company spends no more than $k \\cdot g$ silver coins.",
    "tutorial": "Note that in the perfect world, we'd give each astrophysicist precisely $\\lfloor \\frac{G - 1}{2} \\rfloor$, and we'd spare $N \\cdot \\lfloor \\frac{G - 1}{2} \\rfloor$ silver coins. Unfortunately, two things may happen: First, we may run out of money. This is an easy case; it is enough to output $K \\cdot G$ if it is less than $\\lfloor \\frac{G - 1}{2} \\rfloor$. Second, we may have some money left. It turns out that an acceptable solution is to give everything to one astrophysicist. The intuition behind it is simple - we are only interested in bonus sizes modulo $G$, and by decreasing the bonus of one astrophysicist, we can get at most $1$ from another one, and by increasing it, we lose $\\lfloor \\frac{G - 1}{2} \\rfloor$. In both cases, it is not worth changing the value.Thus, we got a formula to calculate in $\\mathcal{O}(1)$. Thus, we got a formula to calculate in $\\mathcal{O}(1)$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \nint main()\n{\n\tint t;\n\tscanf (\"%d\", &t);\n\twhile (t--) {\n\t\tlong long n, k, g;\n\t\tscanf (\"%lld %lld %lld\", &n, &k, &g);\n \n\t\tlong long stolen = min((g - 1) / 2 * n, k * g);\n\t\tlong long rest = (k * g - stolen) % g;\n \n\t\tif (rest > 0) {\n\t\t    stolen -= (g - 1) / 2;\n\t\t    long long last = ((g - 1) / 2 + rest) % g;\n \n\t\t    if (last * 2 < g) {\n\t\t        stolen += last;\n\t\t    } else {\n\t\t        stolen -= g - last;\n\t\t    }\n\t\t}\n \n\t\tprintf (\"%lld\\n\", stolen);\n\t}\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1837",
    "index": "A",
    "title": "Grasshopper on a Line",
    "statement": "You are given two integers $x$ and $k$. Grasshopper starts in a point $0$ on an OX axis. In one move, it can jump some integer distance, \\textbf{that is not divisible by $k$}, to the left or to the right.\n\nWhat's the smallest number of moves it takes the grasshopper to reach point $x$? What are these moves? If there are multiple answers, print any of them.",
    "tutorial": "When $x$ is not divisible by $k$, the grasshopper can reach $x$ in just one jump. Otherwise, you can show that two jumps are always enough. For example, jumps $1$ and $x-1$. $1$ is not divisible by any $k > 1$. Also, $x$ and $x-1$ can't be divisible by any $k > 1$ at the same time. 1837B - Comparison String",
    "code": "for _ in range(int(input())):\n\tx, k = map(int, input().split())\n\tif x % k != 0:\n\t\tprint(1)\n\t\tprint(x)\n\telse:\n\t\tprint(2)\n\t\tprint(1, x - 1)",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1837",
    "index": "B",
    "title": "Comparison String",
    "statement": "You are given a string $s$ of length $n$, where each character is either < or >.\n\nAn array $a$ consisting of $n+1$ elements is compatible with the string $s$ if, for every $i$ from $1$ to $n$, the character $s_i$ represents the result of comparing $a_i$ and $a_{i+1}$, i. e.:\n\n- $s_i$ is < if and only if $a_i < a_{i+1}$;\n- $s_i$ is > if and only if $a_i > a_{i+1}$.\n\nFor example, the array $[1, 2, 5, 4, 2]$ is compatible with the string <<>>. There are other arrays with are compatible with that string, for example, $[13, 37, 42, 37, 13]$.\n\nThe \\textbf{cost} of the array is the number of different elements in it. For example, the cost of $[1, 2, 5, 4, 2]$ is $4$; the cost of $[13, 37, 42, 37, 13]$ is $3$.\n\nYou have to calculate the minimum cost among all arrays which are compatible with the given string $s$.",
    "tutorial": "Suppose there is a segment of length $k$ that consists of equal characters in $s$. This segment implies that there are at least $k+1$ distinct values in the answer: for example, if the segment consists of < signs, the first element should be less than the second element, the second element should be less than the third element, and so on, so the corresponding segment of the array $a$ contains at least $k+1$ different elements. So, the answer is at least $m+1$, where $m$ is the length of the longest segment of the string that consists of equal characters. Can we construct the array $a$ which will contain exactly $m+1$ distinct values? It turns out we can do it with the following greedy algorithm: let's use integers from $0$ to $m$ for our array $a$, and let's construct it from left to right; every time we place an element, we choose either the largest possible integer we can use (if the next character is >) or the smallest possible integer we can use (if the next character is <). For example, for the string <><<<>, the first $6$ elements of the array will be $[0, 3, 0, 1, 2, 3]$ (and we can use any integer from $0$ to $2$ in the last position). That way, whenever a segment of equal characters begins, the current value in the array will be either $m$ or $0$, and we will be able to decrease or increase it $m$ times, so we won't arrive at a situation where, for example, the current value is $0$ and we have to find a smaller integer. So, the problem basically reduces to finding the longest contiguous subsegment of equal characters in $s$. 1837C - Best Binary String",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        int ans = 1, cur = 1;\n        for(int i = 1; i < n; i++)\n        {\n            if(s[i] != s[i - 1]) cur = 1;\n            else cur++;\n            ans = max(ans, cur);\n        }\n        cout << ans + 1 << endl;\n    }    \n}",
    "tags": [
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1837",
    "index": "C",
    "title": "Best Binary String",
    "statement": "You are given a string $s$ consisting of the characters 0, 1 and/or ?. Let's call it a pattern.\n\nLet's say that the binary string (a string where each character is either 0 or 1) matches the pattern if you can replace each character ? with 0 or 1 (for each character, the choice is independent) so that the strings become equal. For example, 0010 matches ?01?, but 010 doesn't match 1??, ??, or ????.\n\nLet's define the cost of the binary string as the minimum number of operations of the form \"reverse an arbitrary contiguous substring of the string\" required to sort the string in non-descending order.\n\nYou have to find a binary string with the minimum possible cost among those that match the given pattern. If there are multiple answers, print any of them.",
    "tutorial": "First of all, let's try solving an easier problem - suppose we have a binary string, how many operations of the form \"reverse a substring\" do we have to perform so that it is sorted? To solve this problem, we need to consider substrings of the form 10 in the string (i. e. situations when a zero immediately follows a one). Sorted binary strings should not contain any such substrings, so our goal is to reduce the number of such strings to zero. Let's try to analyze how can we reduce the number of substrings equal to 10 by reversing a substring. Suppose that we want to \"remove\" a particular substring 10 from the string without causing any new ones to appear. We can reverse the substring that consists of the block of ones and the block of zeroes adjacent to each other; that way, after reversing the substring, these two blocks will be swapped; the block of zeroes will either merge with the block of zeroes to the left, or move to the beginning of the string; the block of ones will either merge with the block of ones to the right, or move to the end of the string. For example, if, in the string 0011101, you reverse the substring from the $3$-rd to the $6$-th position, you get 0001111, and you reduce the number of substrings 10 by one. What if we want to reduce this number by more than one in just one operation? Unfortunately, this is impossible. Suppose we want to affect two substrings 10 with one reverse operation. There will be a substring 01 between them, so, after reversing, it will turn into 10, and we'll reduce the number of substrings 10 only by one. The same when we try to affect three, four or more substrings 10. So, we can reduce the number of substrings 10 only by one in one operation. So, the answer to the problem \"count the number of operations required to sort the binary string\" is just the number of substrings 10. Okay, back to the original problem. Now we want to replace every question mark so that the resulting string contains as few substrings 10 as possible. You can use dynamic programming of the form $dp_{i,j}$ - the minimum number of substrings if we considered $i$ first characters of the string and the last of them was $j$. Or you can try the following greedy instead: go through the string from left to right, and whenever you encounter a question mark, replace it with the same character as the previous character in the string (if the string begins with a question mark, it should be replaced with 0). That way, you will create as few \"blocks\" of characters as possible, so the number of times when a block of 1's changes into a block of 0's will be as small as possible. 1837D - Bracket Coloring",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    string s;\n    cin >> s;\n    char x = '0';\n    for (auto& c : s) {\n      if (c == '?') c = x;\n      x = c;\n    }\n    cout << s << '\\n';\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1837",
    "index": "D",
    "title": "Bracket Coloring",
    "statement": "A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example:\n\n- the bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\");\n- the bracket sequences \")(\", \"(\" and \")\" are not.\n\nA bracket sequence is called beautiful if one of the following conditions is satisfied:\n\n- it is a regular bracket sequence;\n- if the order of the characters in this sequence is reversed, it becomes a regular bracket sequence.\n\nFor example, the bracket sequences \"()()\", \"(())\", \")))(((\", \"))()((\" are beautiful.\n\nYou are given a bracket sequence $s$. You have to color it in such a way that:\n\n- every bracket is colored into one color;\n- for every color, there is at least one bracket colored into that color;\n- for every color, if you write down the sequence of brackets having that color in the order they appear, you will get a beautiful bracket sequence.\n\nColor the given bracket sequence $s$ into the \\textbf{minimum} number of colors according to these constraints, or report that it is impossible.",
    "tutorial": "What properties do beautiful bracket sequences have? Well, each beautiful sequence is either an RBS (regular bracket sequence) or a reversed RBS. For RBS, the balance (the difference between the number of opening and closing brackets) is non-negative for every its prefix, and equal to zero at the end of the string. For a reversed RBS, the balance is non-positive for every prefix, and zero at the end of the string. So, every beautiful string has balance equal to $0$, and if the string $s$ has non-zero balance, it is impossible to color it. Let's consider the case when the balance of $s$ is $0$. Suppose we calculated the balance on every prefix of $s$, and split it into parts by cutting it along the positions where the balance is $0$. For example, the string (()())())( will be split into (()()), () and )(. For every part of the string we obtain, the balance in the end is equal to $0$, and the balance in the middle of the part is never equal to $0$ (since positions with balance equal to $0$ were the positions where we split the string). So, the balance is either positive in all positions of the part, or negative in all positions of the part; and every string we obtain from cutting $s$ into parts will be beautiful. A concatenation of two RBS'es is always an RBS. The same can be said about the strings which become RBS after reversing. So, for every part we obtain after cutting $s$ into parts, we can determine whether it is an RBS or a reversed RBS, concatenate all RBS'es into one big RBS (by coloring them into color $1$), and concatenate all reversed RBS'es into one string (by coloring them into color $2$). This construction shows that the maximum number of colors is $2$ and allows to obtain the coloring into two colors; so, all that's left to solve the problem is to check whether it's possible to use just one color (it is the case if and only if the given string $s$ is beautiful). 1837E - Playoff Fixing",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        vector<int> bal(n + 1);\n        for(int j = 0; j < n; j++)\n            if(s[j] == '(')\n                bal[j + 1] = bal[j] + 1;\n            else\n                bal[j + 1] = bal[j] - 1;\n\n        if(bal.back() != 0)\n            cout << -1 << endl;\n        else\n        {\n            if(*min_element(bal.begin(), bal.end()) == 0 || *max_element(bal.begin(), bal.end()) == 0)\n            {\n                cout << 1 << endl;\n                for(int j = 0; j < n; j++)\n                {\n                    if(j) cout << \" \";\n                    cout << 1;\n                }\n                cout << endl;\n            }\n            else\n            {\n                cout << 2 << endl;\n                vector<int> ans;\n                int cur = 0;\n                while(cur < n)\n                {\n                    int w = (s[cur] == '(' ? 1 : 2);\n                    do\n                    {\n                        cur++;\n                        ans.push_back(w);\n                    }\n                    while(bal[cur] != 0);\n                }\n                for(int j = 0; j < n; j++)\n                {\n                    if(j) cout << \" \";\n                    cout << ans[j];\n                }\n                cout << endl;\n            }\n        }\n    }    \n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1837",
    "index": "E",
    "title": "Playoff Fixing",
    "statement": "$2^k$ teams participate in a playoff tournament. The teams are numbered from $1$ to $2^k$, in order of decreasing strength. So, team $1$ is the strongest one, team $2^k$ is the weakest one. A team with a smaller number always defeats a team with a larger number.\n\nFirst of all, the teams are arranged in some order during a procedure called seeding. Each team is assigned another unique value from $1$ to $2^k$, called a seed, that represents its starting position in the playoff.\n\nThe tournament consists of $2^k - 1$ games. They are held as follows: the teams are split into pairs: team with seed $1$ plays against team with seed $2$, team with seed $3$ plays against team with seed $4$ (exactly in this order), and so on (so, $2^{k-1}$ games are played in that phase). When a team loses a game, it is eliminated.\n\nAfter that, only $2^{k-1}$ teams remain. If only one team remains, it is declared the champion; otherwise, $2^{k-2}$ games are played: in the first one of them, the winner of the game \"seed $1$ vs seed $2$\" plays against the winner of the game \"seed $3$ vs seed $4$\", then the winner of the game \"seed $5$ vs seed $6$\" plays against the winner of the game \"seed $7$ vs seed $8$\", and so on. This process repeats until only one team remains.\n\nAfter the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular:\n\n- the winner of the tournament gets place $1$;\n- the team eliminated in the finals gets place $2$;\n- both teams eliminated in the semifinals get place $3$;\n- all teams eliminated in the quarterfinals get place $5$;\n- all teams eliminated in the 1/8 finals get place $9$, and so on.\n\nNow that we established the rules, we do a little rigging. In particular, we want:\n\n- team $1$ (not team with seed $1$) to take place $1$;\n- team $2$ to take place $2$;\n- teams $3$ and $4$ to take place $3$;\n- teams from $5$ to $8$ to take place $5$, and so on.\n\nFor example, this picture describes one of the possible ways the tournament can go with $k = 3$, and the resulting places of the teams:\n\nSome seeds are already reserved for some teams (we are not the only ones rigging the tournament, apparently). We have to fill the rest of the seeds with the remaining teams to achieve the desired placements. How many ways are there to do that? Since that value might be large, print it modulo $998\\,244\\,353$.",
    "tutorial": "Let's investigate the structure of the tournament, starting from the first round. We know that teams from $2^{k-1}+1$ to $2^k$ have to lose during this round. At the same time, there are exactly $2^{k-1}$ losers in this round. So, every pairing has to look like this: a team from $1$ to $2^{k-1}$ versus a team from $2^{k-1}+1$ to $2^k$. Let's try to solve for zero reserved seeds - all $a_i = -1$. So, we only have to count the number of valid tournaments. Let's try to do that starting from the top. The winner is team $1$. The final is team $1$ against team $2$, but we have an option to choose their order in the finals. Next, the semifinal. One of teams $3$ and $4$ have to play against team $1$ and another one against team $2$. So we have the following options: choose a permutation of the losers on this stage, then choose the order of teams in every game. If we extrapolate that argument further, we will see that the stage with $2^i$ teams multiplies the answer by $2^{i-1}! \\cdot 2^{2^{i-1}}$ (arrange the losers, then fix the order in pairs). The product over all stages is the answer. In order to add the reserved seeds, we have to go back to solving bottom-up. Consider the first stage. We want to calculate its contribution to the answer, then promote the winners of each pair to the next stage and continue solving for $k = k - 1$. Some pairs have both teams reserved. If both or neither of the teams are from $1$ to $2^{k-1}$, then the answer is immediately $0$. Otherwise, the winner is known, so we can promote it further. Some pairs have no teams reserved. Here, we can pick the order of the teams (multiply the answer by $2$). And we basically know the winner as well - this is marked as $-1$. The loser is yet to be determined. Some pairs have one team reserved, and that team is from $1$ to $2^{k-1}$. That team has to win in this pair, so we know who to promote. We will determine the loser later as well. Finally, some pairs have one team reserved, and the team is from $2^{k-1}+1$ to $2^k$. We know the loser here, but the winner is marked $-1$. Still, we can promote this $-1$ further and deal with it on the later stages. How do we arrange the losers? Well, it's almost the same as in the case with zero reserved teams. There are some pairs that are missing losers, and there are loser teams yet to be placed. We only have to choose which team goes where. So, it's (the number of pairs with no reserved loser)!. Why can we promote the \"winner\" $-1$'s furthers without dealing with them immediately? Basically, that factorial term is the only place where we assign the numbers to teams. Obviously, we want to assign each team a number exactly once. And that happens only when the team loses. Once we assign some number to it, we can uniquely trace back to where this team started, since we fixed the order of each pair beforehand. We decrease $k$ until it's equal to $0$. The answer is still the product of the combinations for each stage. Overall complexity: $O(2^k)$. 1837F - Editorial for Two",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint main() {\n\tint k;\n\tscanf(\"%d\", &k);\n\tvector<int> a(1 << k);\n\tforn(i, 1 << k){\n\t\tscanf(\"%d\", &a[i]);\n\t\tif (a[i] != -1) --a[i];\n\t}\n\tint ans = 1;\n\tfor (int st = k - 1; st >= 0; --st){\n\t\tint big = 1 << st, fr = 0;\n\t\tvector<int> na(1 << st);\n\t\tforn(i, 1 << st){\n\t\t\tint mn = min(a[2 * i], a[2 * i + 1]);\n\t\t\tint mx = max(a[2 * i], a[2 * i + 1]);\n\t\t\tif (mn == -1){\n\t\t\t\tif (mx >= (1 << st)){\n\t\t\t\t\t--big;\n\t\t\t\t\tna[i] = -1;\n\t\t\t\t}\n\t\t\t\telse if (mx != -1){\n\t\t\t\t\tna[i] = mx;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tna[i] = -1;\n\t\t\t\t\t++fr;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif ((a[2 * i] < (1 << st)) == (a[2 * i + 1] < (1 << st))){\n\t\t\t\tputs(\"0\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tna[i] = mn;\n\t\t\t--big;\n\t\t}\n\t\tforn(_, fr) ans = ans * 2ll % MOD;\n\t\tfor (int i = 1; i <= big; ++i) ans = ans * 1ll * i % MOD;\n\t\ta = na;\n\t}\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "combinatorics",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1837",
    "index": "F",
    "title": "Editorial for Two",
    "statement": "Berland Intercollegiate Contest has just finished. Monocarp and Polycarp, as the jury, are going to conduct an editorial. Unfortunately, the time is limited, since they have to finish before the closing ceremony.\n\nThere were $n$ problems in the contest. The problems are numbered from $1$ to $n$. The editorial for the $i$-th problem takes $a_i$ minutes. Monocarp and Polycarp are going to conduct an editorial for exactly $k$ of the problems.\n\nThe editorial goes as follows. They have a full problemset of $n$ problems before them, in order. They remove $n - k$ problems without changing the order of the remaining $k$ problems. Then, Monocarp takes some prefix of these $k$ problems (possibly, an empty one or all problems). Polycarp takes the remaining suffix of them. After that, they go to different rooms and conduct editorials for their problems in parallel. So, the editorial takes as much time as the longer of these two does.\n\nPlease, help Monocarp and Polycarp to choose the problems and the split in such a way that the editorial finishes as early as possible. Print the duration of the editorial.",
    "tutorial": "In the problem, we are asked to first choose $k$ problems, then fix a split into a prefix and a suffix. But nothing stops us from doing that in reverse. Let's fix the split of an entire problemset first, then choose some $l$ ($0 \\le l \\le k$) and $l$ problems to the left of the split and the remaining $k - l$ problems to the right of it. That allows us to proceed with some polynomial solution already. Having fixed the split and $l$, we only have to find $l$ shortest editorials to the left and $k - l$ shortest editorials to the right. It's trivial to show that it's optimal. That can be done in $O(n^2 \\log n)$ easily or $O(n^2)$ if you think a bit more. That solution doesn't really help with the full one, so I won't elaborate. Next, when we see something along the lines of \"minimize the maximum\", we think about binary search. Let's try to apply it here. Binary search over the answer - now we want the sum of the left and the right parts of the split to be less than or equal to some fixed $x$. More specifically, there should exist some $l$ that the sum of $l$ smallest elements to the left is $\\le x$ and the sum of $k - l$ smallest elements to the right is $\\le x$. Let's say it differently. There should be at least $l$ elements to the left with their sum being $\\le x$, same to the right. And once more. The largest set with the sum $\\le x$ to the left is of size at least $l$, same to the right. But that doesn't really require that $l$ now, does it? Find the largest set with the sum $\\le x$ to the left and to the right. The sum of their sizes should be at least $k$. Let's calculate the size of this largest set for all prefixes and all suffixes of the array. Then we will be able to check the condition in $O(n)$. You can precalculate the sizes for all prefixes in $O(n \\log n)$. The idea is the following. Take the set for some prefix $i$. Add the $(i+1)$-st element to it. If its sum is $\\le x$, then it's the new set. Otherwise, keep removing the largest element from it until the sum becomes $\\le x$. That solution is $O(n \\log A \\log n)$, where $A$ is the sum of the array, so you should be careful with the constant factor. For example, doing it with a multiset or with a segment tree probably won't pass. priority_queue is fast enough, though. However, we can do it faster. Imagine a solution with the multiset. Let's replace it with a doubly-linked list. In particular, we want the following operations: insert an element in it; check and remove the last element from it. If we never removed any element, we would be able to determine where to insert each element. We can just precalculate that before the binary search in $O(n \\log n)$. For each element, find the largest element less than or equal to it and to the left of it. That would be the previous element when this one is inserted. When we remove elements, it can happen that this previous element was already removed when we attempt to insert this one. We can use the specificity of the problem to avoid that issue. Notice that if we removed an element less than or equal to the current one, then the current one could never be inside an optimal multiset. So we can just skip this element. To implement such a list, we can renumerate all elements into values from $0$ to $n-1$ (in order of $(\\mathit{value}, i)$). Then, for each $i$ store the value of the previous and the next elements existing in the list. For convenience, you can also add nodes $n$ and $n+1$, denoting the tail and the head of the list. Then insert and remove is just rearranging some links to the previous and the next elements. Overall complexity: $O(n \\log A)$ per testcase, where $A$ is the sum of the array.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--){\n\t\tint n, k;\n\t\tscanf(\"%d%d\", &n, &k);\n\t\tvector<int> a(n);\n\t\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\tvector<pair<int, int>> xs(n);\n\t\tforn(i, n) xs[i] = {a[i], i};\n\t\tsort(xs.begin(), xs.end());\n\t\tforn(i, n) a[i] = lower_bound(xs.begin(), xs.end(), make_pair(a[i], i)) - xs.begin();\n\t\t\n\t\tvector<int> lstpr(n), lstsu(n);\n\t\tforn(_, 2){\n\t\t\tset<int> cur;\n\t\t\tforn(i, n){\n\t\t\t\tauto it = cur.insert(a[i]).first;\n\t\t\t\tif (it == cur.begin())\n\t\t\t\t\tlstpr[i] = n;\n\t\t\t\telse\n\t\t\t\t\tlstpr[i] = *(--it);\n\t\t\t}\n\t\t\tswap(lstpr, lstsu);\n\t\t\treverse(a.begin(), a.end());\n\t\t}\n\t\t\n\t\tvector<int> pr(n + 1), su(n + 1);\n\t\tvector<int> prv(n + 2), nxt(n + 2);\n\t\t\n\t\tauto check = [&](long long x){\n\t\t\tforn(_, 2){\n\t\t\t\tint cnt = 0;\n\t\t\t\tprv[n + 1] = n;\n\t\t\t\tnxt[n] = n + 1;\n\t\t\t\tpr[0] = 0;\n\t\t\t\tint mn = 1e9;\n\t\t\t\tlong long cursum = 0;\n\t\t\t\tforn(i, n){\n\t\t\t\t\tif (mn < a[i]){\n\t\t\t\t\t\tpr[i + 1] = cnt;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tnxt[a[i]] = nxt[lstpr[i]];\n\t\t\t\t\tprv[nxt[a[i]]] = a[i];\n\t\t\t\t\tprv[a[i]] = lstpr[i];\n\t\t\t\t\tnxt[prv[a[i]]] = a[i];\n\t\t\t\t\tcursum += xs[a[i]].first;\n\t\t\t\t\t++cnt;\n\t\t\t\t\twhile (cursum > x){\n\t\t\t\t\t\tmn = min(mn, prv[n + 1]);\n\t\t\t\t\t\tcursum -= xs[prv[n + 1]].first;\n\t\t\t\t\t\tprv[n + 1] = prv[prv[n + 1]];\n\t\t\t\t\t\tnxt[prv[n + 1]] = n + 1;\n\t\t\t\t\t\t--cnt;\n\t\t\t\t\t}\n\t\t\t\t\tpr[i + 1] = cnt;\n\t\t\t\t}\n\t\t\t\treverse(a.begin(), a.end());\n\t\t\t\tswap(lstpr, lstsu);\n\t\t\t\tswap(pr, su);\n\t\t\t}\n\t\t\treverse(su.begin(), su.end());\n\t\t\tforn(i, n + 1) if (pr[i] + su[i] >= k) return true;\n\t\t\treturn false;\n\t\t};\n\t\t\n\t\tlong long l = 1, r = 0;\n\t\tfor (int x : a) r += xs[x].first;\n\t\tlong long res = 0;\n\t\twhile (l <= r){\n\t\t\tlong long m = (l + r) / 2;\n\t\t\tif (check(m)){\n\t\t\t\tres = m;\n\t\t\t\tr = m - 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tl = m + 1;\n\t\t\t}\n\t\t}\n\t\tprintf(\"%lld\\n\", res);\n\t}\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1838",
    "index": "A",
    "title": "Blackboard List",
    "statement": "Two integers were written on a blackboard. After that, the following step was carried out $n-2$ times:\n\n- Select any two integers on the board, and write the absolute value of their difference on the board.\n\nAfter this process was complete, the list of $n$ integers was shuffled. You are given the final list. Recover \\textbf{one} of the initial two numbers. You do \\textbf{not} need to recover the other one.\n\nYou are guaranteed that the input can be generated using the above process.",
    "tutorial": "Note that any negative integers on the board must have been one of the original two numbers, because the absolute difference between any two numbers is nonnegative. So, if there are any negative numbers, print one of those. If there are only nonnegative integers, note that the maximum number remains the same after performing an operation, because for nonnegative integers $a$, $b$, where $a \\le b$, we have $|a-b| = b - a \\le b$ Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\n    int t; cin >> t;\n    for(int tc = 1; tc <= t; ++tc) {\n\n        int n; cin >> n;\n        int mn = INT_MAX, mx = INT_MIN;\n\n        for(int i = 0; i < n; ++i) {\n            int x; cin >> x;\n            mn = min(mn, x);\n            mx = max(mx, x);\n        }\n\n        if(mn < 0) cout << mn << '\\n';\n        else cout << mx << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1838",
    "index": "B",
    "title": "Minimize Permutation Subarrays",
    "statement": "You are given a permutation $p$ of size $n$. You want to minimize the number of subarrays of $p$ that are permutations. In order to do so, you must perform the following operation \\textbf{exactly} once:\n\n- Select integers $i$, $j$, where $1 \\le i, j \\le n$, then\n- Swap $p_i$ and $p_j$.\n\nFor example, if $p = [5, 1, 4, 2, 3]$ and we choose $i = 2$, $j = 3$, the resulting array will be $[5, 4, 1, 2, 3]$. If instead we choose $i = j = 5$, the resulting array will be $[5, 1, 4, 2, 3]$.\n\nWhich choice of $i$ and $j$ will minimize the number of subarrays that are permutations?\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nAn array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "Let $\\mathrm{idx}_x$ be the position of the element $x$ in $p$, and consider what happens if $\\mathrm{idx}_n$ is in between $\\mathrm{idx}_1$ and $\\mathrm{idx}_2$. Notice that any subarray of size greater than $1$ that is a permutation must contain $\\mathrm{idx}_1$ and $\\mathrm{idx}_2$. So it must also contain every index in between, including $\\mathrm{idx}_n$. Therefore, $n$ is an element of the permutation subarray, so it must be of size at least $n$, and therefore must be the whole array. Therefore, if $\\mathrm{idx}_n$ is in between $\\mathrm{idx}_1$ and $\\mathrm{idx}_2$, the only subarrays that are permutations are $[\\mathrm{idx}_1, \\mathrm{idx}_1]$ and $[1, n]$. These two subarrays will always be permutations, so this is minimal. To achieve this, we have 3 cases: If $\\mathrm{idx}_n$ lies in between $\\mathrm{idx}_1$ and $\\mathrm{idx}_2$, swap $\\mathrm{idx}_1$ and $\\mathrm{idx}_2$. If $\\mathrm{idx}_n < \\mathrm{idx}_1, \\mathrm{idx}_2$, swap $\\mathrm{idx}_n$ with the smaller of $\\mathrm{idx}_1$, $\\mathrm{idx}_2$. If $\\mathrm{idx}_n > \\mathrm{idx}_1, \\mathrm{idx}_2$, swap $\\mathrm{idx}_n$ with the larger of $\\mathrm{idx}_1$, $\\mathrm{idx}_2$. In all three of these cases, after the swap, $\\mathrm{idx}_n$ will lie in between $\\mathrm{idx}_1$ and $\\mathrm{idx}_2$, minimizing the number of permutation subarrays. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define N 200010\n\nint idx[N];\n\nint main() {\n\n    int t; cin >> t;\n    for(int tc = 1; tc <= t; ++tc) {\n\n        int n; cin >> n;\n\n        for(int i = 1; i <= n; ++i) {\n            int x; cin >> x;\n            idx[x] = i;\n        }\n\n        if(idx[n] < min(idx[1], idx[2])) {\n            cout << idx[n] << ' ' << min(idx[1], idx[2]) << '\\n';\n        } else if(idx[n] > max(idx[1], idx[2])) {\n            cout << idx[n] << ' ' << max(idx[1], idx[2]) << '\\n';\n        } else {\n            cout << idx[1] << ' ' << idx[2] << '\\n';\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1838",
    "index": "C",
    "title": "No Prime Differences",
    "statement": "You are given integers $n$ and $m$. Fill an $n$ by $m$ grid with the integers $1$ through $n\\cdot m$, in such a way that for any two adjacent cells in the grid, the absolute difference of the values in those cells is not a prime number. Two cells in the grid are considered adjacent if they share a side.\n\nIt can be shown that under the given constraints, there is always a solution.",
    "tutorial": "Note that if we fill in the numbers in order from the top left to the bottom right, for example, for $n=5$, $m=7$, the only adjacent differences are $1$ and $m$. So if $m$ is not prime, this solves the problem. We'll now rearrange the rows so that it works regardless of whether $m$ is prime. Put the first $\\lfloor\\frac{n}{2}\\rfloor$ rows in rows $2$, $4$, $6$, ... and the last $\\lceil\\frac{n}{2}\\rceil$ rows in rows $1$, $3$, $5$, .... In the example above, this would give Note that because we are just rearranging the rows from the above solution, all of the horizontal differences are $1$, and the vertical differences are multiples of $m\\ge 4$. Therefore, as long as none of the vertical differences equal $m$ itself, they must be composite. Because $n\\ge 4$, no row is next to either of its original neighbors in this ordering, and therefore all vertical differences are greater than $m$, and thus composite. So we can use this final grid regardless of whether $m$ is prime. Complexity: $O(nm)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\n    int t; cin >> t;\n    for(int tc = 1; tc <= t; ++tc) {\n\n        int n, m; cin >> n >> m;\n\n        for(int i = 0; i < n; ++i) {\n            for(int j = 0; j < m; ++j) {\n                if(i % 2 == 0) cout << (n / 2 + i / 2) * m + j + 1 << ' ';\n                else cout << (i / 2) * m + j + 1 << ' ';\n            }\n            cout << '\\n';\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1838",
    "index": "D",
    "title": "Bracket Walk",
    "statement": "There is a string $s$ of length $n$ consisting of the characters '(' and ')'. You are walking on this string. You start by standing on top of the first character of $s$, and you want to make a sequence of moves such that you end on the $n$-th character. In one step, you can move one space to the left (if you are not standing on the first character), or one space to the right (if you are not standing on the last character). You may not stay in the same place, however you may visit any character, including the first and last character, \\textbf{any} number of times.\n\nAt each point in time, you write down the character you are currently standing on. We say the string is walkable if there exists some sequence of moves that take you from the first character to the last character, such that the string you write down is a regular bracket sequence.\n\nA regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences \"()()\", \"(())\" are regular (the resulting expressions are: \"(1)+(1)\", \"((1+1)+1)\"), and \")(\" and \"(\" are not.\n\n\\begin{center}\n{\\small One possible valid walk on $s=\\mathtt{(())()))}$. The red dot indicates your current position, and the red string indicates the string you have written down. Note that the red string is a regular bracket sequence at the end of the process.}\n\\end{center}\n\nYou are given $q$ queries. Each query flips the value of a character from '(' to ')' or vice versa. After each query, determine whether the string is walkable.\n\nQueries are \\textbf{cumulative}, so the effects of each query carry on to future queries.",
    "tutorial": "For a string to be walkable, we need $n$ to be even, because the parity of the balance factor changes on each move, and it has to be zero at the end of the process. So if $n$ is odd, the string is never walkable. Now, consider the set $A$ that contains all indices $i$ ($1$-indexed) satisfying one of the below conditions: $i$ is even and $s_i =$ '(' $i$ is odd and $s_i =$ ')' Now, consider a few cases: If $A$ is empty, then $s$ is of the form ()()()(), and is therefore trivially walkable by just moving to the right. If $\\min(A)$ is odd, then $s$ is of the form ()()()).... We can show that it is never walkable, because for every ')' in the first section ()()(), when we land on this ')' (before leaving this section of the string for the first time), the balance factor must be $0$. Therefore, when we try to move across the \"))\", the balance factor will go to $-1$, and the walk will no longer be valid. If $\\max(A)$ is even, then $s$ is of the form ....(()()(), and we can show that it is never walkable using a somewhat symmetric argument to the previous case, but considering the ending of the walk instead of the beginning. Otherwise, $\\min(A)$ is even and $\\max(A)$ is odd. We will prove that it is walkable. In this case, s is of the form ()()()((....))()(). To form a valid walk, keep moving to the right until you hit the \"((\", then alternate back and forth on the \"((\" $10^{18}$ times. After this, move to the right until you hit the \"))\". Note that during this process, the balance factor can never go negative, because it will always be at least $10^{18}-n$. Once you reach the \"))\", alternate back and forth on it until the balance factor hits $0$. Because n is even, this will happen on the rightmost character of the \"))\". At this point, just walk to the right until you hit the end, at which point the balance factor will once again be $0$. So we just need to maintain the set $A$ across all of the queries, and do these simple checks after each query to see if $s$ is walkable. Complexity: $O((n + q) log n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\n    int n, q; string s;\n    cin >> n >> q >> s;\n\n    set<int> a;\n\n    for(int i = 1; i <= n; ++i)\n        if((i % 2) != (s[i - 1] == '('))\n            a.insert(i);\n\n    while(q--) {\n        int i; cin >> i;\n\n        if(a.count(i)) a.erase(i);\n        else a.insert(i);\n\n        if(n % 2) cout << \"NO\\n\";\n        else if(a.size() && (*a.begin() % 2 || !(*a.rbegin() % 2))) cout << \"NO\\n\";\n        else cout << \"YES\\n\";\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1838",
    "index": "E",
    "title": "Count Supersequences",
    "statement": "You are given an array $a$ of $n$ integers, where all elements $a_i$ lie in the range $[1, k]$. How many different arrays $b$ of $m$ integers, where all elements $b_i$ lie in the range $[1, k]$, contain $a$ as a subsequence? Two arrays are considered different if they differ in at least one position.\n\nA sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements.\n\nSince the answer may be large, print it modulo $10^9 + 7$.",
    "tutorial": "Let's first consider a DP solution. Let $dp_{i,j}$ be the number of arrays of length $i$, such that the longest prefix of $a$ that appears as a subsequence of the array is of length $j$. To compute this DP, consider some cases. Let $b'$ be the subarray of the first $i$ elements of $b$, and $a'$ be the subarray of the first $j$ elements of $a$. Every subsequence of $b'$ that equals $a'$ includes position $i$ of $b'$: In this case, position $i$ must be part of the subsequence. This gives us $dp_{i-1, j-1}$ solutions. At least one subsequence of $b'$ that equals $a'$ doesn't include position $i$, and $j < n$: In this case, the value in position $i$ can be anything except for $a_{j+1}$, because that would create a subsequence of length $j+1$. So this gives us $(k-1)dp_{i-1, j}$ solutions. At least one subsequence of $b'$ that equals $a'$ doesn't include position $i$, and $j = n$: This is the same as the previous case, except we don't have a \"next\" element to worry about, so anything can go in position $i$, and there are $k\\cdot dp_{i-1, j}$ solutions. So the final equation for the DP comes out to $dp_{i,j} = \\begin{cases} dp_{i-1, j-1} + (k-1)dp_{i-1, j} & j < n \\\\ dp_{i-1, j-1} + k\\cdot dp_{i-1, j} & j = n \\end{cases}$ This would be $O(nm)$ to compute, so it will TLE. However, we can notice that the DP does not depend on $a$! This means we can change the $a_i$ values to anything we want, and it won't change the answer. To simplify the problem, let all $a_i = 1$. Now, the problem becomes, how many arrays of size $m$, consisting of the values $[1, k]$, contain at least $n$ ones? To compute this, let's find the number of arrays of size $m$ that contain less than $n$ ones, and subtract it from $k^m$, the total number of arrays. There are $\\binom{m}{i}(k-1)^{m-i}$ arrays that contain exactly $i$ ones, so the answer is $k^m - \\sum_{i=0}^{n-1} \\binom{m}{i}(k-1)^{m-i}$ We use fast exponentiation to compute the powers of $k-1$, and to compute the $\\binom{m}{i}$ values, we use the fact that $\\binom{m}{0} = 1$ and for $i \\ge 1$, $\\binom{m}{i} = \\frac{m(m-1)\\ldots(m-i+1)}{i(i-1)\\ldots 1} = \\frac{m - i + 1}{i}\\binom{m}{i - 1}$ So we can compute the first $n$ $\\binom{m}{i}$ values within the time limit. Complexity: $O(n \\log M)$ where $M = 10^9 + 7$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long int ll;\n\nll M = 1000000007;\n\nll pw(ll a, ll p) { return p ? pw(a * a % M, p / 2) * (p & 1 ? a : 1) % M : 1; }\n\nll inv(ll a) { return pw(a, M - 2); }\n\nint main() {\n\n    ll t; cin >> t;\n    for(ll tc = 1; tc <= t; ++tc) {\n\n        ll n, m, k, ai;\n        cin >> n >> m >> k;\n        for(ll i = 0; i < n; ++i) cin >> ai;\n\n        ll ans = pw(k, m), mCi = 1;\n\n        for(ll i = 0; i < n; ++i) {\n            ans = (ans + M - mCi * pw(k - 1, m - i) % M) % M;\n            mCi = mCi * (m - i) % M * inv(i + 1) % M;\n        }\n\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1838",
    "index": "F",
    "title": "Stuck Conveyor",
    "statement": "This is an interactive problem.\n\nThere is an $n$ by $n$ grid of conveyor belts, in positions $(1, 1)$ through $(n, n)$ of a coordinate plane. Every other square in the plane is empty. Each conveyor belt can be configured to move boxes up ('^'), down ('v'), left ('<'), or right ('>'). If a box moves onto an empty square, it stops moving.\n\nHowever, one of the $n^2$ belts is stuck, and will always move boxes in the same direction, no matter how it is configured. Your goal is to perform a series of tests to determine which conveyor belt is stuck, and the direction in which it sends items.\n\nTo achieve this, you can perform up to $25$ tests. In each test, you assign a direction to all $n^2$ belts, place a box on top of one of them, and then turn all of the conveyors on.\n\n\\begin{center}\n{\\small One possible result of a query with $n=4$. In this case, the box starts at $(2, 2)$. If there were no stuck conveyor, it would end up at $(5, 4)$, but because of the stuck '>' conveyor at $(3, 3)$, it enters an infinite loop.}\n\\end{center}\n\nThe conveyors move the box around too quickly for you to see, so the only information you receive from a test is whether the box eventually stopped moving, and if so, the coordinates of its final position.",
    "tutorial": "The key to our solution will be these two \"snake\" configurations: We will initially query the first snake with the box on the top left, and the second snake with the box on the bottom left (or bottom right, depending on parity of $n$). Note that these two snakes, with the box on the given starting positions, each form a single path such that the box visits all squares, and the second snake visits squares in the reverse order of the first. Now, consider some cases. If the stuck conveyor belt directs items to an empty square, then for both of the above configurations, the box will end up in that empty square. This cannot be the \"intended\" behavior for both of them, because the intended behavior for both of them is different. So in one snake, we will know that this is unintended behavior. Because each possible empty square is only adjacent to one belt, we know exactly which belt must have sent it there, and therefore which one is broken. If the stuck conveyor belt directs items to another belt, number the conveyor belts from $1$ to $n^2$ in the order they are visited by the first snake, and consider two subcases: If the other belt has a lower number than the stuck belt, then the box will enter an infinite loop for the first snake query, and will terminate for the second snake query. Since the opposite will happen in the other case, this allows us to distinguish these two subcases.Consider what happens if we ask the first snake query again, but place the box on belt $i$ instead of belt $1$. Assume the stuck belt is belt $j$. Because the stuck belt directs items to a belt with smaller number, if $i \\le j$, the box will hit the stuck belt, and enter an infinite loop. If $i > j$, the box will never encounter the stuck belt, so it will eventually reach the end of the snake and stop moving. So with one query, by checking whether the box enters an infinite loop, we can determine whether $i \\le j$ or $i > j$. This allows us to binary search for $j$ in $\\log (n^2)$ queries. Consider what happens if we ask the first snake query again, but place the box on belt $i$ instead of belt $1$. Assume the stuck belt is belt $j$. Because the stuck belt directs items to a belt with smaller number, if $i \\le j$, the box will hit the stuck belt, and enter an infinite loop. If $i > j$, the box will never encounter the stuck belt, so it will eventually reach the end of the snake and stop moving. So with one query, by checking whether the box enters an infinite loop, we can determine whether $i \\le j$ or $i > j$. This allows us to binary search for $j$ in $\\log (n^2)$ queries. The case where the other belt has a higher number than the stuck belt is analogous, using the second snake query rather than the first. So now, in all cases, we know which of the $n^2$ belts is stuck. In order to determine the direction in which it is stuck, we use one more query. Place the box on the stuck conveyor, and direct all belts in the same row or column as the stuck belt away from it (all other belts can be directed arbitrarily). Here is one example for $n=4$ where the stuck belt is $(2, 2)$: So we will get a different final position for the box for each of the four directions in which it could be stuck, and can recover the direction. The total number of queries for these steps is bounded by $2 + log(n^2) + 1$. Since $n \\le 100$, this is at most $17$. Complexity: $O(n^2 \\log (n^2))$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nchar grid[110][110];\nint n;\nvector<pair<int, int>> snake;\nmap<pair<int, int>, char> getChar = {\n    {{1, 0}, 'v'},\n    {{-1, 0}, '^'},\n    {{0, 1}, '>'},\n    {{0, -1}, '<'}\n};\n\npair<pair<int, int>, char> getBeltAndDir(pair<int, int> p) {\n    if(p.first == -1) return {p, 'X'};\n    pair<int, int> q = p;\n\n    if(p.first == 0) q.first++;\n    if(p.second == 0) q.second++;\n    if(p.first > n) q.first--;\n    if(p.second > n) q.second--;\n\n    return {q, getChar[{p.first - q.first, p.second - q.second}]};\n}\n\npair<pair<int, int>, char> query(int idx) {\n\n    cout << \"? \" << snake[idx].first << ' ' << snake[idx].second << endl;\n\n    for(int i = 1; i <= n; ++i) {\n        for(int j = 1; j <= n; ++j)\n            cout << grid[i][j];\n        cout << endl;\n    }\n\n    int i, j; cin >> i >> j;\n\n    return getBeltAndDir({i, j});\n}\n\nvoid fillGrid() {\n    for(int i = 0; i < n * n; ++i) {\n        int dx = snake[i + 1].first - snake[i].first;\n        int dy = snake[i + 1].second - snake[i].second;\n\n        grid[snake[i].first][snake[i].second] = getChar[{dx, dy}];\n    }\n}\n\nint main() {\n    cin >> n;\n\n    for(int i = 1; i <= n; ++i)\n        if(i % 2 == 0)\n            for(int j = n; j >= 1; --j)\n                snake.emplace_back(i, j);\n        else\n            for(int j = 1; j <= n; ++j)\n                snake.emplace_back(i, j);\n\n    snake.emplace_back(n + 1, (n % 2 ? n : 1));\n    fillGrid();\n\n    auto ans = query(0);\n\n    if(ans.second != 'X') {\n\n        snake.pop_back();\n        reverse(snake.begin(), snake.end());\n        snake.emplace_back(0, 1);\n        fillGrid();\n\n        ans = query(0);\n    }\n\n    if(ans.second == 'X') {\n\n        int id = 0;\n        for(int j = 13; j >= 0; --j)\n            if(id + (1 << j) < n * n && query(id + (1 << j)).second == 'X')\n                id += (1 << j);\n\n        ans.first = snake[id];\n\n        for(int i = 1; i <= n; ++i)\n            for(int j = 1; j <= n; ++j)\n                if(i < ans.first.first) grid[i][j] = '^';\n                else if(i > ans.first.first) grid[i][j] = 'v';\n                else grid[i][j] = j < ans.first.second ? '<' : '>';\n            \n        ans.second = query(id).second;\n    }\n\n    cout << \"! \" << ans.first.first << ' ' << ans.first.second << ' ' << ans.second << endl;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1839",
    "index": "A",
    "title": "The Good Array",
    "statement": "You are given two integers $n$ and $k$.\n\nAn array $a_1, a_2, \\ldots, a_n$ of length $n$, consisting of zeroes and ones is good if for \\textbf{all} integers $i$ from $1$ to $n$ \\textbf{both} of the following conditions are satisfied:\n\n- at least $\\lceil \\frac{i}{k} \\rceil$ of the first $i$ elements of $a$ are equal to $1$,\n- at least $\\lceil \\frac{i}{k} \\rceil$ of the last $i$ elements of $a$ are equal to $1$.\n\nHere, $\\lceil \\frac{i}{k} \\rceil$ denotes the result of division of $i$ by $k$, rounded up. For example, $\\lceil \\frac{6}{3} \\rceil = 2$, $\\lceil \\frac{11}{5} \\rceil = \\lceil 2.2 \\rceil = 3$ and $\\lceil \\frac{7}{4} \\rceil = \\lceil 1.75 \\rceil = 2$.\n\nFind the minimum possible number of ones in a good array.",
    "tutorial": "Let's find lower bound for answer. In any good array, there are at least $\\lceil \\frac{n - 1}{k} \\rceil$ ones among the first $n - 1$ elements. Also, $a_n$ is always $1$, as $\\lceil \\frac{1}{k} \\rceil = 1$. So there are at least $\\lceil \\frac{n - 1}{k} \\rceil + 1$ ones in any good array. This lower bound can always be achieved by placing ones on position $n$ and on positions $1 + k \\cdot x$ for all integers $x$ such that $0 \\le x \\le \\lfloor \\frac{n - 2}{k} \\rfloor = \\lceil \\frac{n - 1}{k} \\rceil - 1$. The answer to the probelm is $\\lceil \\frac{n - 1}{k} \\rceil + 1$.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1839",
    "index": "B",
    "title": "Lamps",
    "statement": "You have $n$ lamps, numbered by integers from $1$ to $n$. Each lamp $i$ has two integer parameters $a_i$ and $b_i$.\n\nAt each moment each lamp is \\textbf{in one of three states}: it may be turned on, turned off, or broken.\n\nInitially all lamps are turned off. In one operation you can select one lamp that is turned off and turn it on (you can't turn on broken lamps). You \\textbf{receive} $b_i$ points for turning lamp $i$ on. The following happens after each performed operation:\n\n- Let's denote the number of lamps that are turned on as $x$ (broken lamps \\textbf{do not count}). All lamps $i$ such that $a_i \\le x$ simultaneously break, whether they were turned on or off.\n\nPlease note that broken lamps never count as turned on and that after a turned on lamp breaks, you still keep points received for turning it on.\n\nYou can perform an arbitrary number of operations.\n\nFind the maximum number of points you can get.",
    "tutorial": "Let's denote number of lamps with $a_i = k$ as $c_k$. If $c_k \\ge k$ and you turn $k$ lamps with $a_i = k$ lamps on, all $c_k$ of them will break and you will not be able to receive points for the other $c_k - k$ lamps. If we denote values $b_i$ for all $i$ such that $a_i = k$ as $d_{k, 1}, d_{k, 2}, \\ldots, d_{k, c_k}$ ($d_{k, 1} \\ge d_{k, 2} \\ge \\ldots \\ge d_{k, c_k}$), then you can't get more than $s_k = d_{k, 1} + d_{k, 2} + \\ldots + d_{k, \\min(c_k, k)}$ points for lamps with $a_i = k$. So, the total number of points is not bigger than $s_1 + s_2 + \\ldots + s_n$. This bound can always be achieved in the following way: while there is at least one lamp that is not turned on and not broken, turn on the one with minimum $a_i$ (if there are multiple lamps with minimum $a_i$, choose the one with maximum $b_i$). This works because if at least $k$ lamps are turned on, then all lamps with $a_i \\lt k$ are already broken.",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1839",
    "index": "C",
    "title": "Insert Zero and Invert Prefix",
    "statement": "You have a sequence $a_1, a_2, \\ldots, a_n$ of length $n$, each element of which is either $0$ or $1$, and a sequence $b$, which is initially empty.\n\nYou are going to perform $n$ operations. On each of them you will increase the length of $b$ by $1$.\n\n- On the $i$-th operation you choose an integer $p$ between $0$ and $i-1$. You insert $0$ in the sequence $b$ on position $p+1$ (after the first $p$ elements), and then you invert the first $p$ elements of $b$.\n- More formally: let's denote the sequence $b$ before the $i$-th ($1 \\le i \\le n$) operation as $b_1, b_2, \\ldots, b_{i-1}$. On the $i$-th operation you choose an integer $p$ between $0$ and $i-1$ and replace $b$ with $\\overline{b_1}, \\overline{b_2}, \\ldots, \\overline{b_{p}}, 0, b_{p+1}, b_{p+2}, \\ldots, b_{i-1}$. Here, $\\overline{x}$ denotes the binary inversion. Hence, $\\overline{0} = 1$ and $\\overline{1} = 0$.\n\nYou can find examples of operations in the Notes section.\n\nDetermine if there exists a sequence of operations that makes $b$ equal to $a$. If such sequence of operations exists, find it.",
    "tutorial": "It's easy to see that last element of $b$ is always zero, so if $a_n$ is $1$, then the answer is \"NO\". It turns out that if $a_n$ is $0$, then answer is always \"YES\". First, let's try to get $b$ equal to array of form $[\\, \\overbrace{1, 1, \\ldots, 1}^{k}, 0 \\,]$ for some $k \\ge 0$. Further in the editorial I will call such arrays simple. We can insert zero before the first element $k$ times and then insert zero after the last element, inverting all previously inserted zeroes into ones. To get arbitrary $b$ with $b_n = 0$, you can notice that such array can always be divided into simple arrays. For example, array $[1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0]$ can be divided into $[1, 1, 0]$, $[0]$, $[1, 1, 1, 1, 0]$, $[1, 0]$. Also it's easy to see that if you can get array $a_1$ with sequence of operation $p_1$ and array $a_2$ with sequence of operations $p_2$, then you can get concatenation of arrays $a_1$ and $a_2$ by first performing all the operations from $p_2$ and then performing all the operations from $p_1$. So, the solution is as follows: If $a_n$ is $1$, output \"NO\". Otherwise, divide array $a$ into simple arrays of lengths $s_1, s_2, \\ldots, s_m$ ($s_1 + s_2 + \\ldots + s_m = n$). Then, you can get $b = a$ with sequence of operations $p = [\\, \\overbrace{0, 0, \\ldots, 0}^{s_m - 1}, s_m - 1, \\overbrace{0, 0, \\ldots, 0}^{s_{m-1} - 1}, s_{m-1} - 1, \\ldots, \\overbrace{0, 0, \\ldots, 0}^{s_1 - 1}, s_1 - 1]$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1839",
    "index": "D",
    "title": "Ball Sorting",
    "statement": "There are $n$ colorful balls arranged in a row. The balls are painted in $n$ distinct colors, denoted by numbers from $1$ to $n$. The $i$-th ball from the left is painted in color $c_i$. You want to reorder the balls so that the $i$-th ball from the left has color $i$. Additionally, you have $k \\ge 1$ balls of color $0$ that you can use in the reordering process.\n\nDue to the strange properties of the balls, they can be reordered only by performing the following operations:\n\n- Place a ball of color $0$ anywhere in the sequence (between any two consecutive balls, before the leftmost ball or after the rightmost ball) while keeping the relative order of other balls. You can perform this operation no more than $k$ times, because you have only $k$ balls of color $0$.\n- Choose any ball of \\textbf{non-zero} color such that at least one of the balls adjacent to him has color $0$, and move that ball (of non-zero color) anywhere in the sequence (between any two consecutive balls, before the leftmost ball or after the rightmost ball) while keeping the relative order of other balls. You can perform this operation as many times as you want, but for each operation you should pay $1$ coin.\n\nYou can perform these operations in any order. After the last operation, all balls of color $0$ magically disappear, leaving a sequence of $n$ balls of non-zero colors.\n\nWhat is the minimum amount of coins you should spend on the operations of the second type, so that the $i$-th ball from the left has color $i$ for all $i$ from $1$ to $n$ \\textbf{after the disappearance of all balls of color zero}? It can be shown that under the constraints of the problem, it is always possible to reorder the balls in the required way.\n\nSolve the problem for all $k$ from $1$ to $n$.",
    "tutorial": "Let's solve the problem for some fixed $k$. Consider the set $S$ of all balls that were never moved with operation of type $2$. Let's call balls from $S$ fixed and balls not from $S$ mobile. The relative order of fixed balls never changes, so their colors must form an increasing sequence. Let's define $f(S)$ as the number of segments of mobile balls that the fixed balls divide sequence into. For example, if $n = 6$ and $S = \\{ 3, 4, 6 \\}$, then these segments are $[1, 2], [5, 5]$ and $f(S)$ is equal to $2$. As every mobile ball has to be moved at least once, there must be at least one zero-colored ball in each such segment, whicn means that $f(S) \\le k$. Also, it means that we will need at least $n - |S|$ operations of type $2$. In fact, we can always place mobile balls at correct positions with exactly $n - |S|$ operations. The proof is left as exercise for reader. So the answer for $k$ is equal to minimum value of $n - |S|$ over all sets $S$ of balls such that $f(S) \\le k$ and the colors of balls in $S$ form an increasing sequence. This problem can be solved with dynamic programming: let $dp_{i, j}$ be maximum value of $|S|$ if only balls from $1$ to $i$ exist, ball $i$ belongs to $S$ and $f(S)$ is equal to $j$. To perform transitions from $dp_{i, j}$ you need to enumerate $t$ -the next ball from $S$ after $i$. Then, if $t = i + 1$, you transition to $dp_{t, j}$, otherwise you transition to $dp_{t, j + 1}$. After each transition $|S|$ increases by $1$, so you just update $dp_{t, j / j + 1}$ with value $dp_{i, j} + 1$. There are $O(n^2)$ states and at most $n$ transitions from each state, so the complexity is $O(n^3)$. Solution can be optimized to $O(n^2 \\log{n})$ with segment tree, but this was not required.",
    "tags": [
      "data structures",
      "dp",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1839",
    "index": "E",
    "title": "Decreasing Game",
    "statement": "\\textbf{This is an interactive problem.}\n\nConsider the following game for two players:\n\n- Initially, an array of integers $a_1, a_2, \\ldots, a_n$ of length $n$ is written on blackboard.\n- Game consists of rounds. On each round, the following happens:\n\n- The first player selects any $i$ such that $a_i \\gt 0$. If there is no such $i$, the first player loses the game (the second player wins) and game ends.\n- The second player selects any $j \\neq i$ such that $a_j \\gt 0$. If there is no such $j$, the second player loses the game (the first player wins) and game ends.\n- Let $d = \\min(a_i, a_j)$. The values of $a_i$ and $a_j$ are simultaneously decreased by $d$ and the next round starts.\n\nIt can be shown that game always ends after the finite number of rounds.\n\nYou have to select which player you will play for (first or second) and win the game.",
    "tutorial": "I claim that the second player wins if and only if array $a$ can be divided into two sets with equal sum, or, equivalently, there is a subset of $a$ with sum $\\frac{a_1 + a_2 + \\ldots + a_n}{2}$. The strategy for the second player in this case is quite simple: before the game starts, the second player splits $a$ into two parts with equal sum. On each round, if the first player selected $i$ from the first part, the second player selects $j$ from the second part. Otherwise, he selects $j$ from the first part. Before and after every round, sums of elements in both parts are equal, so if there is a positive element in one part, there is also a positive element in the other part. So the second player is always able to make a correct move. The strategy for the first player in the other case is even simplier: he can just make any correct move on each round. Why? Let's suppose the second player won the game, which lasted $k$ rounds, and elements selected by players on each round were $(i_1, j_1), (i_2, j_2), \\ldots, (i_k, j_k)$. After $k$-th round, all elements of $a$ are zeroes, otherwise the first player would still be able to make a correct move. Let's consider graph $G$ with set of vertices $V = \\{ 1, 2, \\ldots, n \\}$ and set of edges $E = \\{ (i_1, j_1), (i_2, j_2), \\ldots, (i_k, j_k) \\}$. It's easy to see that this graph is always a tree (proof left as exercise for reader; hint: after each round, at least one of $a_i$ and $a_j$ becomes zero). If graph is a tree, then it is bipartite, which means that its vertices can be divided into two sets such that each edge connects vertices from different sets. As each operation decreases $a_i$ and $a_j$ by same value, these two sets have the same sum of elements. So we have a contradiction.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy",
      "interactive"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1840",
    "index": "A",
    "title": "Cipher Shifer",
    "statement": "There is a string $a$ (unknown to you), consisting of lowercase Latin letters, encrypted according to the following rule into string $s$:\n\n- after each character of string $a$, an arbitrary (possibly zero) number of any lowercase Latin letters, different from the character itself, is added;\n- after each such addition, the character that we supplemented is added.\n\nYou are given string $s$, and you need to output the initial string $a$. In other words, you need to decrypt string $s$.\n\nNote that each string encrypted in this way is decrypted \\textbf{uniquely}.",
    "tutorial": "Note that during encryption, only characters different from $c$ are added after the character $c$. However, when the character $c$ is encrypted with different characters, another $c$ character is added to the string. This means that for decryption, we only need to read the characters of the string after $c$ until we find the first character equal to $c$. It signals the end of the block of characters that will be converted to the character $c$ during decryption. To decrypt the entire string, we decrypt the first character $s_1$. Let the next occurrence of the character $s_1$ be at position $pos_1$. Then the next character of the original string is $s_{pos_1 + 1}$. We apply the same algorithm to find the next paired character and so on.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t; cin >> t;\n    while (t--) {\n        int n; cin >> n;\n        string s; cin >> s;\n        int i = 0;\n        while (i < n) {\n            int start = i;\n            cout << s[i++];\n            while (s[i++] != s[start]);\n        }\n        cout << endl;\n    }\n}",
    "tags": [
      "implementation",
      "strings",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1840",
    "index": "B",
    "title": "Binary Cafe",
    "statement": "Once upon a time, Toma found himself in a binary cafe. It is a very popular and unusual place.\n\nThe cafe offers visitors $k$ different delicious desserts. The desserts are numbered from $0$ to $k-1$. The cost of the $i$-th dessert is $2^i$ coins, because it is a binary cafe! Toma is willing to spend no more than $n$ coins on tasting desserts. At the same time, he is not interested in buying any dessert more than once, because one is enough to evaluate the taste.\n\nIn how many different ways can he buy several desserts \\textbf{(possibly zero)} for tasting?",
    "tutorial": "On the one hand, if Tema had an infinite number of coins, he could buy any set of desserts offered in the coffee shop. This can be done in $2^k$ ways, since each of the desserts can either be taken or not taken. On the other hand, if the coffee shop offered an infinite number of desserts for tasting, Tema could spend any amount of coins he has - from $0$ to $n$. Each number of coins corresponds to its unique set of desserts, since any number $0 \\le k \\le n$ is uniquely represented as a sum of powers of two. Combining these two observations, we get the final answer - $min(2^k, n + 1)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint32_t main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, k;\n        cin >> n >> k;\n        k = min(k, 30);\n        cout << min(n, (1 << k) - 1) + 1 << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1840",
    "index": "C",
    "title": "Ski Resort",
    "statement": "Dima Vatrushin is a math teacher at school. He was sent on vacation for $n$ days for his good work. Dima has long dreamed of going to a ski resort, so he wants to allocate several \\textbf{consecutive days} and go skiing. Since the vacation requires careful preparation, he will only go for \\textbf{at least $k$ days}.\n\nYou are given an array $a$ containing the weather forecast at the resort. That is, on the $i$-th day, the temperature will be $a_i$ degrees.\n\nDima was born in Siberia, so he can go on vacation only if the temperature does not rise above $q$ degrees throughout the vacation.\n\nUnfortunately, Dima was so absorbed in abstract algebra that he forgot how to count. He asks you to help him and count the number of ways to choose vacation dates at the resort.",
    "tutorial": "To simplify the task, let's replace all numbers in the array $a$. If the value of $a_i$ is greater than $q$, then replace it with $0$. Otherwise, replace it with $1$. Now Dima can go on this day if $a_i = 1$. Therefore, we need to consider segments consisting only of $1$. Note that if the segment consists of less than $k$ ones, then Dima will not be able to go on these dates, so the segment can be ignored. For all remaining segments, we need to calculate the number of ways for Dima to choose travel dates on this segment. And for a segment of length $l$, the number of ways to choose a trip of at least length $k$ is $\\binom{l - k + 2}{l - k}$. The answer to the problem will be the sum of the number of ways to choose travel dates for all segments.",
    "code": "testCases = int(input())\n \nfor testCase in range(testCases):\n    n, k, q = map(int, input().split(' '))\n    a = list(map(int, input().split(' ')))\n    \n    ans = 0\n    len = 0\n    for i in range(n):\n        if a[i] <= q:\n            len += 1\n        else:\n            if len >= k:\n                ans += (len - k + 1) * (len - k + 2) // 2\n            len = 0\n    \n    if len >= k:\n        ans += (len - k + 1) * (len - k + 2) // 2\n    print(ans)",
    "tags": [
      "combinatorics",
      "math",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1840",
    "index": "D",
    "title": "Wooden Toy Festival",
    "statement": "In a small town, there is a workshop specializing in woodwork. Since the town is small, only \\textbf{three} carvers work there.\n\nSoon, a wooden toy festival is planned in the town. The workshop employees want to prepare for it.\n\nThey know that $n$ people will come to the workshop with a request to make a wooden toy. People are different and may want different toys. For simplicity, let's denote the pattern of the toy that the $i$-th person wants as $a_i$ ($1 \\le a_i \\le 10^9$).\n\nEach of the carvers can choose an integer pattern $x$ ($1 \\le x \\le 10^9$) in advance, \\textbf{different carvers can choose different patterns}. $x$ is the integer. During the preparation for the festival, the carvers will perfectly work out the technique of making the toy of the chosen pattern, which will allow them to cut it out of wood instantly. To make a toy of pattern $y$ for a carver who has chosen pattern $x$, it will take $|x - y|$ time, because the more the toy resembles the one he can make instantly, the faster the carver will cope with the work.\n\nOn the day of the festival, when the next person comes to the workshop with a request to make a wooden toy, the carvers can choose who will take on the job. At the same time, the carvers are very skilled people and can work on orders for different people \\textbf{simultaneously}.\n\nSince people don't like to wait, the carvers want to choose patterns for preparation in such a way that the \\textbf{maximum} waiting time over all people is as \\textbf{small} as possible.\n\nOutput the best maximum waiting time that the carvers can achieve.",
    "tutorial": "Let the carvers choose patterns $x_1$, $x_2$, $x_3$ for preparation. For definiteness, let us assume that $x_1 \\le x_2 \\le x_3$, otherwise we will renumber the carvers. When a person comes to the workshop with a request to make a toy of pattern $p$, the best solution is to give his order to the carver for whom $|x_i - p|$ is minimal. It follows that the first cutter will take orders for toys with patterns from $1$ to $\\dfrac{x_1 + x_2}{2}$, the second - for toys with patterns from $\\dfrac{x_1 + x_2}{2}$ to $\\dfrac{x_2 + x_3}{2}$, the third - for toys with patterns from $\\dfrac{x_2 + x_3}{2}$ to $10^9$. Therefore, if you look at the sorted array of patterns $a$, the first carver will make some prefix of toys, the third will make some suffix, and the remaining toys will be made by the second carver. Then the answer can be found by binary search. To check if the time $t$ is suitable, you need to give the maximum prefix of toys to the first carver and the maximum suffix of toys to the third carver, and then check that the patterns of the remaining toys are within a segment of length $2 \\cdot t$. The maximum prefix and maximum suffix can be found with a $\\mathcal{O}(n)$ pass through the array $a$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n        }\n        sort(a.begin(), a.end());\n        int l = -1, r = 1e9;\n        while (r - l > 1) {\n            int m = (l + r) >> 1;\n            int i = 0;\n            while (i + 1 < a.size() && a[i + 1] - a[0] <= 2 * m) {\n                ++i;\n            }\n            int j = n - 1;\n            while (j - 1 >= 0 && a.back() - a[j - 1] <= 2 * m) {\n                --j;\n            }\n            ++i; --j;\n            if (i > j || a[j] - a[i] <= 2 * m) {\n                r = m;\n            } else {\n                l = m;\n            }\n        }\n        cout << r << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1840",
    "index": "E",
    "title": "Character Blocking",
    "statement": "You are given two strings of equal length $s_1$ and $s_2$, consisting of lowercase Latin letters, and an integer $t$.\n\nYou need to answer $q$ queries, numbered from $1$ to $q$. The $i$-th query comes in the $i$-th second of time. Each query is one of three types:\n\n- block the characters at position $pos$ (indexed from $1$) in both strings for $t$ seconds;\n- swap two unblocked characters;\n- determine if the two strings are equal at the time of the query, ignoring blocked characters.\n\nNote that in queries of the second type, the characters being swapped can be from the same string or from $s_1$ and $s_2$.",
    "tutorial": "Two strings are equal if and only if there is no position $pos$ such that the characters at position $pos$ are not blocked and $s_1[pos] \\neq s_2[pos]$ (we will call such a position bad). We will use this observation to maintain the current number of bad positions, denoted by $cnt$. Let $I_{pos}$ be an indicator variable. $I_{pos} = 1$ if position $pos$ is bad, otherwise $I_{pos} = 0$. During an operation (blocking or swapping), we only need to subtract the indicator variables of all positions affected by the operation from $cnt$. There will be $\\mathcal{O}(1)$ of them. Then, we modify the string according to the operation and add new indicator variables to $cnt$. To correctly handle blocking queries, or more precisely, to unblock positions in time, we will use a queue. After each blocking query, we will add a pair of numbers to the queue. The first number of the pair is the position to unblock, and the second number is the time to unblock. Now, before each operation, we will unblock positions by looking at the head of the queue.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int x;\n    cin >> x;\n    while (x--) {\n        vector<string> s(2);\n        cin >> s[0] >> s[1];\n        int n = s[0].size();\n        int bad = 0;\n        for (int i = 0; i < n; ++i) {\n            if (s[0][i] != s[1][i]) {\n                ++bad;\n            }\n        }\n        int t, q;\n        cin >> t >> q;\n        queue<pair<int, int>> unblock;\n        for (int i = 0; i < q; ++i) {\n            while (!unblock.empty() && unblock.front().first == i) {\n                if (s[0][unblock.front().second] != s[1][unblock.front().second]) {\n                    ++bad;\n                }\n                unblock.pop();\n            }\n            int type;\n            cin >> type;\n            if (type == 1) {\n                int pos;\n                cin >> pos;\n                if (s[0][pos - 1] != s[1][pos - 1]) {\n                    --bad;\n                }\n                unblock.emplace(i + t, pos - 1);\n            } else if (type == 2) {\n                int num1, pos1, num2, pos2;\n                cin >> num1 >> pos1 >> num2 >> pos2;\n                --num1; --pos1; --num2; --pos2;\n                if (s[num1][pos1] != s[1 ^ num1][pos1]) {\n                    --bad;\n                }\n                if (s[num2][pos2] != s[1 ^ num2][pos2]) {\n                    --bad;\n                }\n                swap(s[num1][pos1], s[num2][pos2]);\n                if (s[num1][pos1] != s[1 ^ num1][pos1]) {\n                    ++bad;\n                }\n                if (s[num2][pos2] != s[1 ^ num2][pos2]) {\n                    ++bad;\n                }\n            } else {\n                cout << (!bad ? \"YES\" : \"NO\") << \"\\n\";\n            }\n        }\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "hashing",
      "implementation"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1840",
    "index": "F",
    "title": "Railguns",
    "statement": "Tema is playing a very interesting computer game.\n\nDuring the next mission, Tema's character found himself on an unfamiliar planet. Unlike Earth, this planet is flat and can be represented as an $n \\times m$ rectangle.\n\nTema's character is located at the point with coordinates $(0, 0)$. In order to successfully complete the mission, he needs to reach the point with coordinates $(n, m)$ alive.\n\nLet the character of the computer game be located at the coordinate $(i, j)$. Every second, \\textbf{starting from the first}, Tema can:\n\n- either use vertical hyperjump technology, after which his character will end up at coordinate $(i + 1, j)$ at the end of the second;\n- or use horizontal hyperjump technology, after which his character will end up at coordinate $(i, j + 1)$ at the end of the second;\n- or Tema can choose not to make a hyperjump, in which case his character will not move during this second;\n\nThe aliens that inhabit this planet are very dangerous and hostile. Therefore, they will shoot from their railguns $r$ times.\n\nEach shot completely penetrates one coordinate vertically or horizontally. If the character is in the line of its impact at the time of the shot \\textbf{(at the end of the second)}, he dies.\n\nSince Tema looked at the game's source code, he knows complete information about each shot — the time, the penetrated coordinate, and the direction of the shot.\n\nWhat is the \\textbf{minimum} time for the character to reach the desired point? If he is doomed to die and cannot reach the point with coordinates $(n, m)$, output $-1$.",
    "tutorial": "Let's first solve it in $\\mathcal{O}(nmt)$. This can be done using dynamic programming. $dp[i][j][k] = true$ if the character can be at coordinates $(i, j)$ at time $t$, otherwise $dp[i][j][k] = false$. Such dynamics can be easily recalculated: $dp[i][j][k] = dp[i - 1][j][k - 1] | dp[i][j - 1][k - 1] | dp[i][j][k - 1]$. If the cell is shot by one of the railguns at time $t$, then $dp[i][j][k] = false$. Now let's notice that if the character can reach the final point $(n, m)$, then he will have to stand still no more than $r$ times. To prove this, we can prove another statement: if the character can reach the final point along some trajectory, then for any such trajectory the character can stand still no more than $r$ times. And this statement can already be proven by mathematical induction. Thus, instead of the $dp[n][m][t]$ dynamics, we can calculate the $dp[n][m][r]$ dynamics, where the third parameter is the number of times the character stood still. The transitions here are made similarly.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0); cout.tie(0);\n    int q;\n    cin >> q;\n    while (q--) {\n        int n, m;\n        cin >> n >> m;\n        int r;\n        cin >> r;\n        bool free[n + 1][m + 1][r + 1];\n        for (int i = 0; i <= n; ++i) {\n            for (int j = 0; j <= m; ++j) {\n                for (int k = 0; k <= r; ++k) {\n                    free[i][j][k] = true;\n                }\n            }\n        }\n        for (int i = 0; i < r; ++i) {\n            int t, d, coord;\n            cin >> t >> d >> coord;\n            if (d == 1) {\n                for (int j = 0; j <= m; ++j) {\n                    if (0 <= t - coord - j && t - coord - j <= r) {\n                        free[coord][j][t - coord - j] = false;\n                    }\n                }\n            } else {\n                for (int j = 0; j <= n; ++j) {\n                    if (0 <= t - coord - j && t - coord - j <= r) {\n                        free[j][coord][t - coord - j] = false;\n                    }\n                }\n            }\n        }\n        bool dp[n + 1][m + 1][r + 1];\n        for (int i = 0; i <= n; ++i) {\n            for (int j = 0; j <= m; ++j) {\n                for (int k = 0; k <= r; ++k) {\n                    dp[i][j][k] = !(i || j || k);\n                    if (free[i][j][k]) {\n                        if (i && dp[i - 1][j][k]) {\n                            dp[i][j][k] = true;\n                        }\n                        if (j && dp[i][j - 1][k]) {\n                            dp[i][j][k] = true;\n                        }\n                        if (k && dp[i][j][k - 1]) {\n                            dp[i][j][k] = true;\n                        }\n                    }\n                }\n            }\n        }\n        int ans = -1;\n        for (int t = r; t >= 0; --t) {\n            if (dp[n][m][t]) {\n                ans = n + m + t;\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1840",
    "index": "G1",
    "title": "In Search of Truth (Easy Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the maximum number of queries. In this version, you are allowed to ask at most $2023$ queries.}\n\nThis is an interactive problem.\n\nYou are playing a game. The circle is divided into $n$ sectors, sectors are numbered from $1$ to $n$ in some order. You are in the adjacent room and do not know either the number of sectors or their numbers. There is also an arrow that initially points to some sector. Initially, the host tells you the number of the sector to which the arrow points. After that, you can ask the host to move the arrow $k$ sectors counterclockwise or clockwise at most $2023$ times. And each time you are told the number of the sector to which the arrow points.\n\nYour task is to determine the integer $n$ — the number of sectors in at most $2023$ queries.\n\nIt is guaranteed that $1 \\le n \\le 10^6$.",
    "tutorial": "Let $a_1, a_2, \\dots, a_n$ be the numbers of the sectors in clockwise order, and let the arrow initially point to the sector with number $a_1$. First, let's make $999$ queries of \"+ 1\", then we will know the numbers of $1000$ consecutive sectors. If $n < 1000$, then the number of the first query that gives the answer $a_1$ is the desired $n$. If we did not find $n$, this means that $n \\ge 1000$. Let's save $a_1, a_2, \\dots, a_{1000}$. Now we will make queries of \"+ 1000\" until we get one of the numbers $a_1, a_2, \\dots, a_{1000}$ as the answer. Note that we will need no more than $1000$ queries of this type, after which it is easy to determine the number $n$. Thus, we can determine the number $n$ in no more than $999 + 1000 = 1999 \\le 2023$ queries.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nconst int MAXN = 1e6 + 7;\n \nint pos[MAXN];\n \nint32_t main() {\n    int num;\n    cin >> num;\n    int ans = 0;\n    int cur = 1;\n    pos[num] = 1;\n    for (int i = 0; i < 1000; ++i) {\n        cout << '+' << \" \" << 1 << endl;\n        ++cur;\n        cin >> num;\n        if (pos[num]) {\n            cout << '!' << \" \" << cur - pos[num] << endl;\n            return 0;\n        }\n        pos[num] = cur;\n    }\n    while (true) {\n        cout << '+' << \" \" << 1000 << endl;\n        cur += 1000;\n        cin >> num;\n        if (pos[num]) {\n            cout << '!' << \" \" << cur - pos[num] << endl;\n            return 0;\n        }\n        pos[num] = cur;\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math",
      "meet-in-the-middle",
      "probabilities"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1840",
    "index": "G2",
    "title": "In Search of Truth (Hard Version)",
    "statement": "\\textbf{The only difference between easy and hard versions is the maximum number of queries. In this version, you are allowed to ask at most $1000$ queries.}\n\nThis is an interactive problem.\n\nYou are playing a game. The circle is divided into $n$ sectors, sectors are numbered from $1$ to $n$ in some order. You are in the adjacent room and do not know either the number of sectors or their numbers. There is also an arrow that initially points to some sector. Initially, the host tells you the number of the sector to which the arrow points. After that, you can ask the host to move the arrow $k$ sectors counterclockwise or clockwise at most $1000$ times. And each time you are told the number of the sector to which the arrow points.\n\nYour task is to determine the integer $n$ — the number of sectors in at most $1000$ queries.\n\nIt is guaranteed that $1 \\le n \\le 10^6$.",
    "tutorial": "Let's sample $n$ by making $k$ random queries \"+ x\" where we pick $x$ each time randomly between $1$ and $10^6$ and get $k$ random integers $n_1, n_2, \\dots, n_k$ in the range $[1, n]$ as the answers to the queries. Then, we can sample $n$ with $n_0 = max(n_1, n_2, \\dots, n_k)$. Now, we can assume that $n_0 \\le n \\le n_0 + d$ for some integer $d$. Let's talk about picking the right $d$ a bit later. Now we can perform an algorithm similar to G1 solution and determine $n$ within $2 \\cdot \\sqrt{d}$ queries. So, we have $1000$ queries in total, meaning that $2 \\cdot \\sqrt{d} + k$ is approximately equals to $1000$. Thus, for each $k$ we can find optimal $d = \\frac{1000 - k}{2}$, the probability that $n$ is not in the range $[n_0, n_0 + d]$ does not exceed $(\\frac{n - d}{n}) ^ k$ which is less than $8.5 \\cdot 10 ^{-18}$ for $k = 320$ and for each $1 \\le n \\le 10^6$. Therefore, by picking $k$ somewhere between $300$ and $400$, we can get a solution which passes a testcase with probability of $p \\ge 1 - 10 ^{-16}$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nconst int MAXN = 1e6 + 7;\n \nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n \nint pos[MAXN];\n \nconst int K = 400;\nconst int T = 300;\n \nint get() {\n    return rng() % MAXN;\n}\n \nint32_t main() {\n    int num;\n    cin >> num;\n    int start = num;\n    int cur_delta = 0;\n    int N0 = num;\n    for (int i = 0; i < K; ++i) {\n        int delta = get();\n        cout << '+' << \" \" << delta << endl;\n        cur_delta += delta;\n        cin >> num;\n        N0 = max(N0, num);\n    }\n    cout << '-' << \" \" << cur_delta << endl;\n    cin >> num;\n    cout << '+' << \" \" << N0 - 1 << endl;\n    cur_delta = N0 - 1;\n    cin >> num;\n    pos[num] = N0;\n    for (int i = 0; i < T; ++i) {\n        ++cur_delta;\n        cout << '+' << \" \" << 1 << endl;\n        cin >> num;\n        pos[num] = N0 + i + 1;\n        if (num == start) {\n            cout << '!' << \" \" << N0 + i << endl;\n            return 0;\n        }\n    }\n    cout << '-' << \" \" << cur_delta << endl;\n    cin >> num;\n    int ans = 0;\n    while (true) {\n        cout << '-' << \" \" << T << endl;\n        ans += T;\n        cin >> num;\n        if (pos[num]) {\n            cout << '!' << \" \" << ans + pos[num] - 1 << endl;\n            return 0;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math",
      "meet-in-the-middle",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1841",
    "index": "A",
    "title": "Game with Board",
    "statement": "Alice and Bob play a game. They have a blackboard; initially, there are $n$ integers written on it, and each integer is equal to $1$.\n\nAlice and Bob take turns; Alice goes first. On their turn, the player has to choose several (\\textbf{at least two}) \\textbf{equal} integers on the board, wipe them and write a new integer which is equal to their sum.\n\nFor example, if the board currently contains integers $\\{1, 1, 2, 2, 2, 3\\}$, then the following moves are possible:\n\n- choose two integers equal to $1$, wipe them and write an integer $2$, then the board becomes $\\{2, 2, 2, 2, 3\\}$;\n- choose two integers equal to $2$, wipe them and write an integer $4$, then the board becomes $\\{1, 1, 2, 3, 4\\}$;\n- choose three integers equal to $2$, wipe them and write an integer $6$, then the board becomes $\\{1, 1, 3, 6\\}$.\n\nIf a player cannot make a move (all integers on the board are different), that player \\textbf{wins the game}.\n\nDetermine who wins if both players play optimally.",
    "tutorial": "Let's try to find a winning strategy for Alice. We can force Bob into a situation where his only action will be to make a move that leaves Alice without any legal moves, so she will win. For example, Alice can start by merging $n-2$ ones, so the board will be $\\{1, 1, n-2\\}$ after her move. The only possible move for Bob is to merge the remaining $1$'s, and the board becomes $\\{2, n-2\\}$, and Alice wins. Unfortunately, this works only for $n \\ge 5$. Cases $n=2$, $n=3$, $n=4$ should be analyzed separately: if $n=2$, the only possible first move for Alice is to merge two $1$'s, and the board becomes $\\{2\\}$, so Bob wins; if $n=3$, Alice can transform the board either to $\\{3\\}$ or to $\\{1,2\\}$; in both cases, Bob instantly wins; if $n=4$, Alice can transform the board to $\\{4\\}$, $\\{1,3\\}$, or $\\{1,1,2\\}$. In the first two cases, Bob instantly wins. In the third case, the only possible response for Bob is to merge two $1$'s; the board becomes $\\{2,2\\}$. It's easy to see that after the only possible move for Alice, the board becomes $\\{4\\}$, and Bob wins. So, when $n \\ge 5$, Alice wins, and when $n \\le 4$, Bob wins.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    print('Alice' if n >= 5 else 'Bob')",
    "tags": [
      "constructive algorithms",
      "games"
    ],
    "rating": 800
  },
  {
    "contest_id": "1841",
    "index": "B",
    "title": "Keep it Beautiful",
    "statement": "The array $[a_1, a_2, \\dots, a_k]$ is called beautiful if it is possible to remove several (maybe zero) elements from the beginning of the array and insert all these elements to the back of the array in the same order in such a way that the resulting array is sorted in non-descending order.\n\nIn other words, the array $[a_1, a_2, \\dots, a_k]$ is beautiful if there exists an integer $i \\in [0, k-1]$ such that the array $[a_{i+1}, a_{i+2}, \\dots, a_{k-1}, a_k, a_1, a_2, \\dots, a_i]$ is sorted in non-descending order.\n\nFor example:\n\n- $[3, 7, 7, 9, 2, 3]$ is beautiful: we can remove four first elements and insert them to the back in the same order, and we get the array $[2, 3, 3, 7, 7, 9]$, which is sorted in non-descending order;\n- $[1, 2, 3, 4, 5]$ is beautiful: we can remove zero first elements and insert them to the back, and we get the array $[1, 2, 3, 4, 5]$, which is sorted in non-descending order;\n- $[5, 2, 2, 1]$ is not beautiful.\n\n\\textbf{Note that any array consisting of zero elements or one element is beautiful}.\n\nYou are given an array $a$, which is initially \\textbf{empty}. You have to process $q$ queries to it. During the $i$-th query, you will be given one integer $x_i$, and you have to do the following:\n\n- if you can append the integer $x_i$ to the \\textbf{back} of the array $a$ so that the array $a$ stays beautiful, you have to append it;\n- otherwise, do nothing.\n\nAfter each query, report whether you appended the given integer $x_i$, or not.",
    "tutorial": "First, notice that the given operation is a cyclic shift of the array. So we can treat the array as cyclic, meaning element $n$ is a neighbor of element $1$. Let's try to rephrase the condition for the beautiful array. What does it mean for the array to be sorted? For all $j$ from $1$ to $n-1$, $a_j \\le a_{j+1}$ should hold. If they do, then you can choose $i=0$ (leave the array as is). What if there are such $j$ that $a_j > a_{j+1}$? If there is only one such $j$, then we might still be able to fix the array: choose $i = j$. However, that will make a pair $a_n$ and $a_1$ cyclically shift into the array. So $a_n \\le a_1$ should hold. If there are at least two such $j$ or just one but $a_n > a_1$, then we can show that it's impossible to make the array sorted. Since there are at least two pairs of neighboring elements that are not sorted, at least one of them will still be in the array after any cyclic shift. Thus, we can maintain the number of such $j$ that $a_j > a_{j+1}$ and check if $a_n > a_1$ every time if the count is exactly $1$. Overall complexity: $O(q)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tq = int(input())\n\ta = []\n\tcnt = 0\n\tfor x in map(int, input().split()):\n\t\tnw_cnt = cnt + (len(a) > 0 and a[-1] > x)\n\t\tif nw_cnt == 0 or (nw_cnt == 1 and x <= a[0]):\n\t\t\ta.append(x)\n\t\t\tcnt = nw_cnt\n\t\t\tprint('1', end=\"\")\n\t\telse:\n\t\t\tprint('0', end=\"\")\n\tprint()",
    "tags": [
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1841",
    "index": "C",
    "title": "Ranom Numbers",
    "statement": "No, not \"random\" numbers.\n\nRanom digits are denoted by uppercase Latin letters from A to E. Moreover, the value of the letter A is $1$, B is $10$, C is $100$, D is $1000$, E is $10000$.\n\nA Ranom number is a sequence of Ranom digits. The value of the Ranom number is calculated as follows: the values of all digits are summed up, but some digits are taken with negative signs: a digit is taken with negative sign if there is a digit with a \\textbf{strictly greater} value to the right of it (not necessarily immediately after it); otherwise, that digit is taken with a positive sign.\n\nFor example, the value of the Ranom number DAAABDCA is $1000 - 1 - 1 - 1 - 10 + 1000 + 100 + 1 = 2088$.\n\nYou are given a Ranom number. You can change no more than one digit in it. Calculate the maximum possible value of the resulting number.",
    "tutorial": "There are two main solutions to this problem: dynamic programming and greedy. DP approach Reverse the string we were given, so that the sign of each digit depends on the maximum digit to the left of it (not to the right). Then, run the following dynamic programming: $dp_{i,j,k}$ is the maximum value of the number if we considered $i$ first characters, applied $k$ changes to them ($k$ is either $0$ or $1$), and the maximum character we encountered so far was $j$ ($j$ can have $5$ possible values). The transitions are fairly simple: when we consider the state $dp_{i,j,k}$, we can either leave the current character as it is, or, if $k = 0$, iterate on the replacement for the current character and use the replacement instead (then we go to the state with $k=1$). Note that this solution can also work if we can make more than one operation. This dynamic programming has $O(n \\cdot A \\cdot m)$ states (where $A$ is the number of different characters, and $m$ is the maximum number of changes we can make), and each state has no more than $A+1$ outgoing transitions. In this problem, $A = 5$ and $m = 1$, so this solution easily passes. Greedy approach Of course, we can try to iterate on every character and check all possible replacements for it, but quickly calculating the answer after replacement can be a bit difficult. Instead, we claim the following: it is optimal to consider at most $10$ positions to replace - the first and the last position of A, the first and the last position of B, and so on. That way, we have only $50$ different candidates for the answer, and we can check each of them in $O(n)$. How to prove that this is enough? When we replace a character, we either increase or decrease it. If we increase a character, it's easy to see why it's optimal to try only the first occurrence of each character - increasing a character may affect some characters to the left of it (turn them from positive to negative), and by picking the first occurrence of a character, we make sure that the number of characters transformed from positive to negative is as small as possible. Note that if the string has at least one character different from E, we can replace the first such character with E and increase the answer by at least $9000$ (this will be useful in the second part of the proof). Now suppose it's optimal to decrease a character, let's show that it's always optimal to choose the last occurrence of a character to decrease. Suppose we decreased a character, and it was not the last occurrence. This means that this character will be negative after replacement, so it should be negative before the replacement. The maximum value we can add to the answer by replacing a negative character with another negative character is $999$ (changing negative D to negative A), and we have already shown that we can add at least $9000$ by replacing the first non-E character in the string with E. So, if we decrease a character and it was not the last occurrence of that character, it's suboptimal.",
    "code": "def replace_char(s, i, c):\n    return s[:i] + c + s[i + 1:]\n    \ndef id(c):\n    return ord(c) - ord('A')\n    \ndef evaluate(s):\n    t = s[::-1]\n    ans = 0\n    max_id = -1\n    for x in t:\n        i = id(x)\n        if max_id > i:\n            ans -= 10 ** i\n        else:\n            ans += 10 ** i\n        max_id = max(max_id, i)\n    return ans\n\nt = int(input())\nfor i in range(t):\n    s = input()\n    candidates = []\n    for x in ['A', 'B', 'C', 'D', 'E']:\n        for y in ['A', 'B', 'C', 'D', 'E']:\n            if not (x in s):\n                continue\n            candidates.append(replace_char(s, s.find(x), y))\n            candidates.append(replace_char(s, s.rfind(x), y))\n    print(max(map(evaluate, candidates)))",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1841",
    "index": "D",
    "title": "Pairs of Segments",
    "statement": "Two segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect if there exists at least one $x$ such that $l_1 \\le x \\le r_1$ and $l_2 \\le x \\le r_2$.\n\nAn array of segments $[[l_1, r_1], [l_2, r_2], \\dots, [l_k, r_k]]$ is called \\textbf{beautiful} if $k$ is even, and is possible to split the elements of this array into $\\frac{k}{2}$ pairs in such a way that:\n\n- every element of the array belongs to exactly one of the pairs;\n- segments in each pair intersect with each other;\n- segments in different pairs do not intersect.\n\nFor example, the array $[[2, 4], [9, 12], [2, 4], [7, 7], [10, 13], [6, 8]]$ is beautiful, since it is possible to form $3$ pairs as follows:\n\n- the first element of the array (segment $[2, 4]$) and the third element of the array (segment $[2, 4]$);\n- the second element of the array (segment $[9, 12]$) and the fifth element of the array (segment $[10, 13]$);\n- the fourth element of the array (segment $[7, 7]$) and the sixth element of the array (segment $[6, 8]$).\n\nAs you can see, the segments in each pair intersect, and no segments from different pairs intersect.\n\nYou are given an array of $n$ segments $[[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]]$. You have to remove the minimum possible number of elements from this array so that the resulting array is beautiful.",
    "tutorial": "The resulting array should consist of pairs of intersecting segments, and no segments from different pairs should intersect. Let's suppose that segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect, and segments $[l_3, r_3]$ and $[l_4, r_4]$ intersect. How to check that no other pair of these four segments intersects? Instead of pairs of segments, let's work with the union of segments in each pair; no point should belong to more than one of these unions. Since segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect, their union is also a segment, and its endpoints are $[\\min(l_1, l_2), \\max(r_1, r_2)]$. So, if we transform each pair into a union, then the union-segments we got should not intersect. Thus, we can solve the problem as follows: for each pair of intersecting segments in the input, generate their union segment, and pick the maximum number of unions we can (these unions represent the pairs in the answer). It's quite easy to see that we won't pick a segment in two pairs simultaneously (the corresponding unions will intersect). Okay, now we have $O(n^2)$ union segments, how to pick the maximum number of them without having an intersection? This is a somewhat classical problem, there are many methods to solve it. The one used in the model solution is a greedy algorithm: sort the union segments according to their right border (in non-descending order), and pick segments greedily in sorted order, maintaining the right border of the last segment we picked. If the union segment we consider is fully after the right border of the last union we picked, then we add it to the answer; otherwise, we skip it. This approach works in $O(n^2 \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nbool comp(const pair<int, int>& a, const pair<int, int>& b)\n{\n\treturn a.second < b.second;\n}\n\nvoid solve()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<pair<int, int>> s(n);\n\tfor(int i = 0; i < n; i++)\n\t\tscanf(\"%d %d\", &s[i].first, &s[i].second);\n\t\n\tvector<pair<int, int>> pairs;\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = i + 1; j < n; j++)\n\t\t\tif(max(s[i].first, s[j].first) <= min(s[i].second, s[j].second))\n\t\t\t\tpairs.push_back(make_pair(min(s[i].first, s[j].first), max(s[i].second, s[j].second)));\n\t\t\t\n\tint cnt_pairs = 0;\n\tsort(pairs.begin(), pairs.end(), comp);\n\tint last_pos = -1;\n\tfor(auto x : pairs)\n\t\tif(x.first > last_pos)\n\t\t{\n\t\t\tcnt_pairs++;\n\t\t\tlast_pos = x.second;\n\t\t}\n\t\t\n\tprintf(\"%d\\n\", n - cnt_pairs * 2);\n}\n\nint main()\n{\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1841",
    "index": "E",
    "title": "Fill the Matrix",
    "statement": "There is a square matrix, consisting of $n$ rows and $n$ columns of cells, both numbered from $1$ to $n$. The cells are colored white or black. Cells from $1$ to $a_i$ are black, and cells from $a_i+1$ to $n$ are white, in the $i$-th column.\n\nYou want to place $m$ integers in the matrix, from $1$ to $m$. There are two rules:\n\n- each cell should contain at most one integer;\n- black cells should not contain integers.\n\nThe beauty of the matrix is the number of such $j$ that $j+1$ is written in the same row, in the next column as $j$ (in the neighbouring cell to the right).\n\nWhat's the maximum possible beauty of the matrix?",
    "tutorial": "Notice that the rows of the matrix are basically independent. When we fill the matrix with integers, the values from the rows are just added together. Moreover, in a single row, the segments of white cells separated by black cells are also independent in the same way. And how to solve the problem for one segment of white cells? Obviously, put the numbers one after another. Placing a non-zero amount of integers $k$ will yield the result of $k-1$. Thus, the answer is $\\sum_\\limits{i=1}^s k_i - 1$, where $s$ is the number of used segments. We know that the sum of $k_i$ is just $m$. So it becomes $m + \\sum_\\limits{i=1}^s -1 = m - s$. So, the problem asks us to minimize the number of used segments. In order to use the smallest number of segments, we should pick the longest ones. We only have to find them. In the worst case, there are $O(n^2)$ segments of white cells in the matrix. However, we can store them in a compressed form. Since their lengths are from $1$ to $n$, we can calculate how many segments of each length there are. Look at the matrix from the bottom to the top. First, there are some fully white rows. Then some black cell appears and splits the segment of length $n$ into two segments. Maybe more if there are more black cells in that row. After that the split segments behave independently of each other. Let's record these intervals of rows each segment exists at. So, let some segment exist from row $l$ to row $r$. What does that mean? This segment appeared because of some split at row $r$. At row $l$, some black cell appeared that split the segment in parts. If we knew the $r$ for the segment, we could've saved the information about it during the event at row $l$. So, we need a data structure that can support the following operations: find a segment that covers cell $x$; erase a segment; insert a segment. Additionally, that data structure should store a value associated with a segment. Thus, let's use a map. For a segment, which is a pair of integers, store another integer - the bottommost row this segment exists. Make events $(a_i, i)$ for each column $i$. Sort them and process in a non-increasing order. During the processing of the event, find the segment this black cell splits. Save the information about this segment. Then remove it and add two new segments (or less if some are empty): the one to the left and the one to the right. At the end, for each length from $1$ to $n$, we will have the number of segments of such length. In order to fill them with $m$ integers, start with the longest segments and use as many of each length as possible. So, while having $m$ more integers to place and $\\mathit{cnt}$ segments of length $\\mathit{len}$, you can use $\\min(\\lfloor \\frac{m}{\\mathit{len}} \\rfloor, cnt)$ of segments. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct seg{\n\tint l, r;\n};\n\nbool operator <(const seg &a, const seg &b){\n\treturn a.l < b.l;\n}\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--){\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tvector<int> a(n);\n\t\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\tlong long m;\n\t\tscanf(\"%lld\", &m);\n\t\tmap<seg, int> used;\n\t\tused[{0, n}] = n;\n\t\tvector<int> ord(n);\n\t\tiota(ord.begin(), ord.end(), 0);\n\t\tsort(ord.begin(), ord.end(), [&a](int x, int y){\n\t\t\treturn a[x] > a[y];\n\t\t});\n\t\tlong long ans = 0;\n\t\tint j = 0;\n\t\tvector<long long> cnt(n + 1);\n\t\tfor (int i = n; i >= 0; --i){\n\t\t\twhile (j < n && a[ord[j]] >= i){\n\t\t\t\tauto it = used.upper_bound({ord[j], -1});\n\t\t\t\t--it;\n\t\t\t\tauto tmp = it->first;\n\t\t\t\tcnt[tmp.r - tmp.l] += it->second - i;\n\t\t\t\tused.erase(it);\n\t\t\t\tif (tmp.l != ord[j])\n\t\t\t\t\tused[{tmp.l, ord[j]}] = i;\n\t\t\t\tif (tmp.r != ord[j] + 1)\n\t\t\t\t\tused[{ord[j] + 1, tmp.r}] = i;\n\t\t\t\t++j;\n\t\t\t}\n\t\t}\n\t\tfor (int i = n; i > 0; --i){\n\t\t\tlong long t = min(cnt[i], m / i);\n\t\t\tans += t * 1ll * (i - 1);\n\t\t\tm -= t * 1ll * i;\n\t\t\tif (t != cnt[i] && m > 0){\n\t\t\t\tans += m - 1;\n\t\t\t\tm = 0;\n\t\t\t}\n\t\t}\n\t\tprintf(\"%lld\\n\", ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1841",
    "index": "F",
    "title": "Monocarp and a Strategic Game",
    "statement": "Monocarp plays a strategic computer game in which he develops a city. The city is inhabited by creatures of four different races — humans, elves, orcs, and dwarves.\n\nEach inhabitant of the city has a happiness value, which is an integer. It depends on how many creatures of different races inhabit the city. Specifically, the happiness of each inhabitant is $0$ by default; it increases by $1$ for each \\textbf{other} creature of the same race and decreases by $1$ for each creature of a hostile race. Humans are hostile to orcs (and vice versa), and elves are hostile to dwarves (and vice versa).\n\nAt the beginning of the game, Monocarp's city is not inhabited by anyone. During the game, $n$ groups of creatures will come to his city, wishing to settle there. The $i$-th group consists of $a_i$ humans, $b_i$ orcs, $c_i$ elves, and $d_i$ dwarves. Each time, Monocarp can either accept the \\textbf{entire} group of creatures into the city, or reject the \\textbf{entire} group.\n\nThe game calculates Monocarp's score according to the following formula: $m + k$, where $m$ is the number of inhabitants in the city, and $k$ is the sum of the happiness values of all creatures in the city.\n\nHelp Monocarp earn the maximum possible number of points by the end of the game!",
    "tutorial": "Let's denote $a, b, c, d$ as the total number of humans, orcs, elves, and dwarves taken respectively. We calculate the contribution of humans and orcs to the final score. It will be $a(a-1) + b(b-1) - 2ab + a + b$, where $a(a-1) + b(b-1)$ is the contribution to the total happiness (and thus to the final score) for an increase of $1$ happiness point per inhabitant of the same race, $-2ab$ is the contribution to the total happiness decrease by $1$ point for each inhabitant of the hostile race, and the last two terms $a + b$ is the total number of humans and orcs, which contributes to the total score. Notice that $a(a-1) + b(b-1) - 2ab + a + b = (a-b)^2$. Similarly for the contribution of elves and dwarves. So we need to maximize the expression $(a-b)^2+(c-d)^2$. Let's say we have $n$ vectors, the $i$-th of which is equal to $(x_i; y_i) = (a_i - b_i; c_i - d_i)$. Then note that we want to select some subset of vectors among the $n$ vectors $(x_i; y_i)$, a subset $A$ such that the value of the function $x^2+y^2$ is maximum for the vector $(x, y)$ equal to the sum of the vectors of subset $A$. For each subset of vectors, we get a vector equal to the sum of the elements of the subset (vectors), let's denote the set of all such vectors as $S$. Then consider the $n$ line segments at the vertices $(0; 0)$ and $(x_i; y_i)$ and calculate their Minkowski sum. We get a convex polygon. Notice that all elements of $S$ are in it by the definition of the Minkowski sum. Also, each vertex of the resulting convex polygon is in $S$, which is also known from the properties of the sum. Note that due to the upward convexity of the function we want to maximize, it is enough for us to only consider the vertices of the resulting polygon, not all vectors from $S$. Thus, using a standard algorithm for calculating the Minkowski sum, we obtain the polygon of interest and calculate the values of the function at its vertices. We take the maximum from them. The total asymptotic time complexity is $O(n\\ln{n})$.",
    "code": "#include <iostream>\n#include <algorithm>\nusing namespace std;\n#define int long long\n#define x first\n#define y second\nconst int MAXN = 2e6 + 16;\nint a[MAXN], b[MAXN];\npair<int, int> v[MAXN];\nint section(pair<int, int> a) {\n    if (a.x > 0 && a.y >= 0)\n        return 0;\n    else if (a.x <= 0 && a.y > 0)\n        return 1;\n    else if (a.x < 0 && a.y <= 0)\n        return 2;\n    else\n        return 3;\n}\nbool cmp(pair<int, int> a, pair<int, int> b) {\n    if (section(a) != section(b))\n        return section(a) < section(b);\n    else\n        return (__int128)a.x * (__int128)b.y - (__int128)a.y * (__int128)b.x > 0;\n}\nvoid print(__int128 x) {\n    if (x < 0) {\n        putchar('-');\n        x = -x;\n    }\n    if (x > 9) print(x / 10);\n    putchar(x % 10 + '0');\n}\nsigned main() {\n    ios_base::sync_with_stdio(false);\n    \n    int n;\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n\t\tvector<int> t(4);\n\t\tfor(int j = 0; j < 4; j++)\n\t\t\tcin >> t[j];\n\t\ta[i] = t[0] - t[1];\n\t\tb[i] = t[2] - t[3];\n\t}\n    int it = 0;\n    __int128 sx = 0, sy = 0;\n    for (int i = 0; i < n; ++i) {\n        v[i << 1].x = a[it];\n        v[i << 1].y = b[it];\n        ++it;\n        v[i << 1 ^ 1].x = -v[i << 1].x;\n        v[i << 1 ^ 1].y = -v[i << 1].y;\n        if (!v[i << 1].x && !v[i << 1].y) {\n            --i, --n;\n            continue;\n        }\n        if (v[i << 1].y < 0 || (!v[i << 1].y && v[i << 1].x < 0))\n            sx += v[i << 1].x, sy += v[i << 1].y;\n    }\n    sort(v, v + 2 * n, cmp);\n    __int128 ans = sx * sx + sy * sy;\n    for (int i = 0; i < 2 * n; ++i) {\n        sx += v[i].x;\n        sy += v[i].y;\n        ans = std::max(ans, sx * sx + sy * sy);\n    }\n    print(ans);\n\n    return 0;\n}",
    "tags": [
      "geometry",
      "sortings",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1842",
    "index": "A",
    "title": "Tenzing and Tsondu",
    "statement": "\\begin{quote}\nTsondu always runs first! ! !\n\\end{quote}\n\nTsondu and Tenzing are playing a card game. Tsondu has $n$ monsters with ability values $a_1, a_2, \\ldots, a_n$ while Tenzing has $m$ monsters with ability values $b_1, b_2, \\ldots, b_m$.\n\nTsondu and Tenzing take turns making moves, with Tsondu going first. In each move, the current player chooses two monsters: one on their side and one on the other side. Then, these monsters will fight each other. Suppose the ability values for the chosen monsters are $x$ and $y$ respectively, then the ability values of the monsters will become $x-y$ and $y-x$ respectively. If the ability value of any monster is smaller than or equal to $0$, the monster dies.\n\nThe game ends when at least one player has no monsters left alive. The winner is the player with at least one monster left alive. If both players have no monsters left alive, the game ends in a draw.\n\nFind the result of the game when both players play optimally.",
    "tutorial": "Let's view it as when monsters $x$ and $y$ fight, their health changes into $\\max(x-y,0)$ and $\\max(y-x,0)$ respectively. So any monster with $0$ health is considered dead. Therefore, a player loses when the health of his monsters are all $0$. Notice that $\\max(x-y,0)=x-\\min(x,y)$ and $\\max(y-x,0)=y-\\min(x,y)$. Therefore, after each step, the sum of the health of monsters decrease by the same amount for both players. Therefore, we only need to know $\\sum a_i$ and $\\sum b_i$ to determine who wins. If $\\sum a_i > \\sum b_i$, Tsondu wins. Else if $\\sum a_i < \\sum b_i$, Tenzing wins. Else, it is a draw.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T--) {\n        int n, m, a[50], b[50];\n        long long sumA = 0, sumB = 0;\n        cin >> n >> m;\n        for (int i = 0; i < n; i++)\n            cin >> a[i], sumA += a[i];\n        for (int i = 0; i < m; i++)\n            cin >> b[i], sumB += b[i];\n        if (sumA > sumB) cout << \"Tsondu\\n\";\n        if (sumA < sumB) cout << \"Tenzing\\n\";\n        if (sumA == sumB) cout << \"Draw\\n\";\n    }\n}",
    "tags": [
      "games",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1842",
    "index": "B",
    "title": "Tenzing and Books",
    "statement": "Tenzing received $3n$ books from his fans. The books are arranged in $3$ stacks with $n$ books in each stack. Each book has a non-negative integer difficulty rating.\n\nTenzing wants to read some (possibly zero) books. At first, his knowledge is $0$.\n\nTo read the books, Tenzing will choose a non-empty stack, read the book on the top of the stack, and then discard the book. If Tenzing's knowledge is currently $u$, then his knowledge will become $u|v$ after reading a book with difficulty rating $v$. Here $|$ denotes the bitwise OR operation. Note that Tenzing can stop reading books whenever he wants.\n\nTenzing's favourite number is $x$. Can you help Tenzing check if it is possible for his knowledge to become $x$?",
    "tutorial": "Observe the bitwise OR: if a bit of the knowledge changes to $1$, it will never become $0$. It tells us, if a book has difficulty rating $y$, and $x|y \\neq x$, Tenzing will never read this book because it will change a $0$ bit in $x$ to $1$. We called a number $y$ valid if $x|y=x$. For each sequence, we can find a longest prefix of it such that all numbers in this prefix are valid. Find the bitwise OR of the three prefix and check whether it equals to $x$. Time complexity: $O(n)$ per test case. A naive approach is to enumerate the prefixes of the three stacks, which is an enumeration of $n^3$. For each stack, the bitwise OR of the prefix has at most $31$ different values (including empty prefix), because the bitwise OR of the prefix is non-decreasing, and each change will increase the number of 1s in binary. Since the number of 1s in binary cannot exceed $30$, it can be changed at most 30 times. Therefore, the enumeration is reduced to $\\min(n,31)^3$. In the worst case, the time complexity is $O(\\sum n * 31^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T--) {\n        int n, x, ai;\n        cin >> n >> x;\n        vector<int> pre[3];\n        for (int i = 0; i < 3; i++) {\n            int s = 0;\n            pre[i].push_back(s);\n            for (int j = 0; j < n; j++) {\n                cin >> ai;\n                if ((s | ai) != s)\n                    s |= ai, pre[i].push_back(s);\n            }\n        }\n        bool ans = 0;\n        for (int A : pre[0]) for (int B : pre[1]) for (int C : pre[2])\n            ans |= (A | B | C) == x;\n        cout << (ans ? \"YES\\n\" : \"NO\\n\");\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1842",
    "index": "C",
    "title": "Tenzing and Balls",
    "statement": "\\begin{quote}\nEnjoy erasing Tenzing, identified as Accepted!\n\\end{quote}\n\nTenzing has $n$ balls arranged in a line. The color of the $i$-th ball from the left is $a_i$.\n\nTenzing can do the following operation any number of times:\n\n- select $i$ and $j$ such that $1\\leq i < j \\leq |a|$ and $a_i=a_j$,\n- remove $a_i,a_{i+1},\\ldots,a_j$ from the array (and decrease the indices of all elements to the right of $a_j$ by $j-i+1$).\n\nTenzing wants to know the maximum number of balls he can remove.",
    "tutorial": "Let us write down the original index of each range we delete. Firstly, it is impossible to delete ranges $(a,c)$ and $(b,d)$ where $a<b<c<d$. Secondly, if we delete ranges $(a,d)$ and $(b,c)$ where $a<b<c<d$, we must have deleted range $(b,c)$ before deleting range $(a,d)$. Yet, the effect of deleting range $(b,c)$ and then $(a,d)$ is the same as only deleting $(a,d)$. Therefore, we can assume that in an optimal solution, the ranges we delete are all disjoint. Therefore, we want to find some disjoint range $[l_1,r_1],[l_2,r_2],...,[l_m,r_m]$ such that $a_{l_i}=a_{r_i}$ and $\\sum (r_i-l_i+1)$ is maximized. We can write a DP. $dp_i$ denotes the minimum number of points we do not delete when considering the subarray $a[1\\ldots i]$. We have $dp_i=\\min(dp_{i-1}+1,\\min\\{dp_j|a_{j+1}=a_i,j+1<i\\})$. This dp can be calculated in $O(n)$ since we can store for each $x$ what the minimum $dp_j$ which satisfy $a_{j+1}=x$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T--) {\n        const int N = 200000 + 5;\n        int n, a[N], dp[N], buc[N];\n        cin >> n;\n        dp[0] = 0;\n        for (int i = 1; i <= n; i++) buc[i] = 0x3f3f3f3f;\n        for (int i = 1; i <= n; i++) {\n            cin >> a[i];\n            dp[i] = min(dp[i - 1] + 1, buc[a[i]]);\n            buc[a[i]] = min(buc[a[i]], dp[i - 1]);\n        }\n        cout << n - dp[n] << '\\n';\n    }\n}",
    "tags": [
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1842",
    "index": "D",
    "title": "Tenzing and His Animal Friends ",
    "statement": "\\begin{quote}\nTell a story about me and my animal friends.\n\\end{quote}\n\nTenzing has $n$ animal friends. He numbers them from $1$ to $n$.\n\nOne day Tenzing wants to play with his animal friends. To do so, Tenzing will host several games.\n\nIn one game, he will choose a set $S$ which is a subset of $\\{1,2,3,...,n\\}$ and choose an integer $t$. Then, he will play the game with the animals in $S$ for $t$ minutes.\n\nBut there are some restrictions:\n\n- Tenzing loves friend $1$ very much, so $1$ must be an element of $S$.\n- Tenzing doesn't like friend $n$, so $n$ must not be an element of $S$.\n- There are m additional restrictions. The $i$-th special restriction is described by integers $u_i$, $v_i$ and $y_i$, suppose $x$ is the \\textbf{total} time that \\textbf{exactly} one of $u_i$ and $v_i$ is playing with Tenzing. Tenzing must ensure that $x$ is less or equal to $y_i$. Otherwise, there will be unhappiness.\n\nTenzing wants to know the maximum total time that he can play with his animal friends. Please find out the maximum total time that Tenzing can play with his animal friends and a way to organize the games that achieves this maximum total time, or report that he can play with his animal friends for an infinite amount of time. Also, Tenzing does not want to host so many games, so he will host at most $n^2$ games.",
    "tutorial": "Consider the restrictions on $u$, $v$, and $y$ as a weighted edge between $u$ and $v$ with weight $y$. Obviously, the final answer will not exceed the shortest path from $1$ to $n$. One possible approach to construct the solution is to start with the set ${1}$ and add vertices one by one. If $i$ is added to the set at time $T_i$, then we need to ensure that $|T_u-T_v|\\leq y$ for any edge between $u$ and $v$ in the set. This can be modeled as a system of difference constraints problem and solved using shortest path algorithms. To be more specific, we can add vertices in increasing order of their distances from $1$. The time for each set can be calculated as the difference between the distances from $1$ to the two adjacent vertices in the sorted order.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, m;\nlong long dis[100][100];\n\nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    cin >> n >> m;\n    memset(dis, 0x3f, sizeof dis);\n    while (m--) {\n        int u, v, w;\n        cin >> u >> v >> w, u--, v--;\n        dis[u][v] = dis[v][u] = w;\n    }\n    for (int i = 0; i < n; i++) dis[i][i] = 0;\n    for (int k = 0; k < n; k++)\n        for (int i = 0; i < n; i++)\n            for (int j = 0; j < n; j++)\n                dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);\n    if (dis[0][n - 1] > 1e18)\n        cout << \"inf\", exit(0);\n    int ord[100];\n    iota(ord, ord + n, 0);\n    sort(ord + 1, ord + n, [](int a, int b) {\n        return dis[0][a] < dis[0][b];\n    });\n    string s(n, '0');\n    vector<pair<string, int>> ans;\n    for (int i = 0; i < n - 1; i++) {\n        int u = ord[i], v = ord[i + 1];\n        s[u] = '1';\n        ans.emplace_back(s, dis[0][v] - dis[0][u]);\n        if (v == n - 1) break;\n    }\n    cout << dis[0][n - 1] << ' ' << ans.size() << '\\n';\n    for (auto [s, t] : ans)\n        cout << s << ' ' << t << '\\n';\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1842",
    "index": "E",
    "title": "Tenzing and Triangle",
    "statement": "There are $n$ \\textbf{pairwise-distinct} points and a line $x+y=k$ on a two-dimensional plane. The $i$-th point is at $(x_i,y_i)$. All points have non-negative coordinates and are strictly below the line. Alternatively, $0 \\leq x_i,y_i, x_i+y_i < k$.\n\nTenzing wants to erase all the points. He can perform the following two operations:\n\n- Draw triangle: Tenzing will choose two non-negative integers $a$, $b$ that satisfy $a+b<k$, then all points inside the triangle formed by lines $x=a$, $y=b$ and $x+y=k$ will be erased. It can be shown that this triangle is an isosceles right triangle. Let the side lengths of the triangle be $l$, $l$ and $\\sqrt 2 l$ respectively. Then, the cost of this operation is $l \\cdot A$.The blue area of the following picture describes the triangle with $a=1,b=1$ with cost $=1\\cdot A$.\n- Erase a specific point: Tenzing will choose an integer $i$ that satisfies $1 \\leq i \\leq n$ and erase the point $i$. The cost of this operation is $c_i$.\n\nHelp Tenzing find the minimum cost to erase all of the points.",
    "tutorial": "Observe that all triangles will be disjoint, if two triangle were not disjoint, we can merge them together to such that the cost used is less. Therefore, we can consider doing DP. The oblique side of the triangle is a segment on the line $y=k-x$. Therefore, we use the interval $[L,R]$ to represent the triangle with the upper left corner at $(L,k-L)$ and the lower right corner at $(R,k-R)$. First, suppose that all points will generate costs. After covering points with a triangle, the costs can be reduced. Let $f(L,R)$ represent the sum of costs of points covered by triangle $[L,R]$ minus $A\\times (R-L)$. We need to find several intervals $[l_1,r_1],[l_2,r_2],\\cdots,[l_m,r_m]$ without common parts and maximize $\\sum f(l_i,r_i)$. Let $dp_i$ represent the maximum value of $\\sum f(l_i,r_i)$ when considering the prefix $[1,i]$. There are two transitions: If $i$ is not covered by any interval, then $dp_i\\leftarrow dp_{i-1}$. If $i$ is covered by interval $[j+1,i]$, then $dp_i\\leftarrow dp_j+f(j+1,i)$. Enumerate from small to large for $i$, maintain $g_j=dp_j+f(j+1,i)$. When $i-1\\rightarrow i$, $g$ will change as follows: Subtract $A$ from $g_{0\\dots i-1}$. For each point $(x,k-i)$, add the cost of the point to $g_{0\\dots x}$. $g$ needs to support interval addition and global maximum value (assuming that illegal positions are 0), which can be achieved using a segment tree. Time complexity is $O((n+k)\\log k)$. Please first understand the approach in the tutorial. A triangle $[L, R]$ can cover a point $(x, y)$ iff $L\\le x$ and $k-y\\le R$. Therefore, point $(x,y)$ can be regarded as interval $[x,k-y]$. Now the problem is transformed into one where some intervals $[l,r]$ have a cost of $w$, and you can place some non-overlapping intervals. If $[l,r]$ is not included in any placed interval, then you need to pay a cost of $w$. Further transformation: you can pay a cost of $A$ to cover $[i,i+1]$, and for an interval $[l,r]$ with a cost of $w$, if interval $[l,r]$ is not completely covered, then you need to pay a cost of $w$. Try to use minimum cut to solve this problem: First establish a bipartite graph with $n$ left nodes representing the points in the original problem and $k$ right nodes representing intervals $[i,i+1]$. The source node is connected to each left node with an edge capacity equal to the node's cost. Each right node is connected to the sink node with an edge capacity of $A$. For each left node representing interval $[l,r]$, it is connected to right nodes $l,l+1,l+2,...,r-1$ with an edge capacity of infinity. According to the maximum flow minimum cut theorem, let's consider how to find the maximum flow of this graph. This is basically a maximum matching problem of a bipartite graph. Each left node can match an interval on the right side, and each node has matching frequency restriction. A greedy algorithm: First sort all intervals in increasing order of the right endpoint, then consider each interval in turn and match it with positions within the interval from left to right. Specifically, let $cnt_i$ represent how many times the $i$-th point on the right side can still be matched. Initially, $cnt_{0\\dots k-1}=A$. For each interval $[l,r]$ that can be matched at most $w$ times, each time find the smallest $i$ in $[l,r-1]$ such that $cnt_i\\ne 0$, and match $\\min(cnt_i,w)$ times with $i$. Use a Disjoint Set Union to query the smallest $i\\ge l$ such that $cnt_i\\ne 0$. The time complexity is $O(n\\alpha(n))$. The Method of Four Russians can also be used to achieve $O(n)$ time complexity. Divide the sequence into blocks of $64$, use bit operations and __builtin_ctzll for searching within the block, and use Disjoint Set Union to skip blocks where $cnt_i$ is all $0$. In this way, the union operation only needs $O(\\frac n{\\log n})$ times and the find operation only needs $O(n)$ times. It can be proved that in this case, the time complexity of Disjoint Set Union is $O(n)$ instead of $O(n\\alpha(n))$.",
    "code": "#include <bits/stdc++.h>\n\nstruct IO {\n    static const int inSZ = 1 << 17;\n    char inBuf[inSZ], *in1, *in2;\n    inline __attribute((always_inline))\n    int read() {\n        if(__builtin_expect(in1 > inBuf + inSZ - 32, 0)) {\n            auto len = in2 - in1;\n            memcpy(inBuf, in1, len);\n            in1 = inBuf, in2 = inBuf + len;\n            in2 += fread(in2, 1, inSZ - len, stdin);\n            if(in2 != inBuf + inSZ) *in2 = 0;\n        }\n        int res = 0;\n        unsigned char c = *in1++;\n        while(res = res * 10 + (c - 48), (c = *in1++) >= 48);\n        return res;\n    }\n    IO() {\n        in1 = inBuf;\n        in2 = in1 + fread(in1, 1, inSZ, stdin);\n    }\n} IO;\ninline int read() { return IO.read(); }\n\nusing namespace std;\n\nconst int N = 2e5 + 8, N2 = N / 64 + 8;\n\nint n, k, A, pts[N][3], buc[N], LW[N][2];\nint cnt[N], pa[N2], Rp[N];\nuint64_t mask[N2];\n\nint find(int x) {\n    return pa[x] < 0 ? x : pa[x] = find(pa[x]);\n}\n\nint main() {\n    n = read(), k = read(), A = read();\n    for (int i = 0; i < n; i++) {\n        pts[i][1] = read();\n        pts[i][0] = k - read();\n        pts[i][2] = read();\n        buc[pts[i][0]]++;\n    }\n    for (int i = 1; i <= k; i++) buc[i + 1] += buc[i];\n    for (int i = 0; i < n; i++) {\n        int t = --buc[pts[i][0]];\n        memcpy(LW[t], pts[i] + 1, 8);\n    }\n    for (int i = 0; i < k; i++) cnt[i] = A;\n    memset(mask, 0xff, sizeof mask);\n    memset(pa, -1, sizeof pa);\n    iota(Rp, Rp + N2, 0);\n    int ans = 0;\n    for (int r = 1; r <= k; r++)\n        for (int i = buc[r]; i < buc[r + 1]; i++) {\n            int l = LW[i][0], w = LW[i][1];\n            ans += w;\n            int lb = Rp[find(l >> 6)], rb = r >> 6;\n            auto S0 = mask[lb];\n            if (lb == l >> 6) S0 &= ~0ULL << (l & 63);\n            while (lb < rb) {\n                auto S = S0;\n                for (; S; S &= S - 1) {\n                    int p = lb * 64 + __builtin_ctzll(S);\n                    int tmp = min(w, cnt[p]);\n                    cnt[p] -= tmp, w -= tmp;\n                    if (!w) break;\n                }\n                mask[lb] ^= S0 ^ S;\n                if (!w) break;\n                int nxt = find(lb + 1);\n                if (!mask[lb]) {\n                    lb = find(lb);\n                    if (pa[nxt] > pa[lb]) swap(nxt, lb), Rp[nxt] = Rp[lb];\n                    pa[nxt] += pa[lb], pa[lb] = nxt;\n                }\n                lb = Rp[nxt], S0 = mask[lb];\n            }\n            if (w != 0 & lb == rb) {\n                S0 &= (1ULL << (r & 63)) - 1;\n                auto S = S0;\n                for (; S; S &= S - 1) {\n                    int p = lb * 64 + __builtin_ctzll(S);\n                    int tmp = min(w, cnt[p]);\n                    cnt[p] -= tmp, w -= tmp;\n                    if (!w) break;\n                }\n                mask[lb] ^= S0 ^ S;\n            }\n            ans -= w;\n        }\n    cout << ans << '\\n';\n}",
    "tags": [
      "data structures",
      "dp",
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1842",
    "index": "F",
    "title": "Tenzing and Tree",
    "statement": "Tenzing has an undirected tree of $n$ vertices.\n\nDefine the value of a tree with black and white vertices in the following way. The value of an edge is the absolute difference between the number of black nodes in the two components of the tree after deleting the edge. The value of the tree is the sum of values over all edges.\n\nFor all $k$ such that $0 \\leq k \\leq n$, Tenzing wants to know the maximum value of the tree when $k$ vertices are painted black and $n-k$ vertices are painted white.",
    "tutorial": "Let $root$ be the centroid of all black vertices and $size_i$ be the number of black vertices in the subtree of node $i$. Then the value is $\\sum_{i\\neq root} k-2\\cdot size_i=(n-1)\\cdot k-2\\cdot\\sum_{i\\neq root} size_i$. Consider painting node $i$ black, the total contributio to all of its ancestors is $2\\cdot depth_i$, where $depth_i$ is the distance from $root$ to $i$. Since we want to maximize the value, we can greedily select the node with the smallest $depth_i$. But how do we ensure that $root$ is the centroid after selecting other black vertices? We can simply take the maximum of all possible $root$ because if a node is not the centroid, some edges will have a negative weight, making it worse than the optimal answer. Enumerate all possible $root$ and use BFS to add vertices based on their distance to $root$. The complexity is $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5000 + 8;\n\nint n, ans[N];\nvector<int> G[N];\n\nvoid bfs(int u) {\n    static int q[N], dis[N];\n    memset(dis, -1, sizeof dis);\n    q[1] = u, dis[u] = 0;\n    for (int l = 1, r = 2; l < r; l++) {\n        u = q[l];\n        for (int v : G[u]) if (dis[v] < 0)\n            dis[v] = dis[u] + 1, q[r++] = v;\n    }\n    int sum = 0;\n    for (int i = 1; i <= n; i++) {\n        sum += dis[q[i]]; \n        ans[i] = max(ans[i], (n - 1) * i - sum * 2);\n    }\n}\nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    cin >> n;\n    for (int i = 0; i < n - 1; i++) {\n        int u, v;\n        cin >> u >> v, u--, v--;\n        G[u].push_back(v), G[v].push_back(u);\n    }\n    for (int i = 0; i < n; i++) bfs(i);\n    for (int i = 0; i <= n; i++)\n        cout << ans[i] << ' ';\n}",
    "tags": [
      "dfs and similar",
      "greedy",
      "shortest paths",
      "sortings",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1842",
    "index": "G",
    "title": "Tenzing and Random Operations",
    "statement": "\\begin{quote}\nYet another random problem.\n\\end{quote}\n\nTenzing has an array $a$ of length $n$ and an integer $v$.\n\nTenzing will perform the following operation $m$ times:\n\n- Choose an integer $i$ such that $1 \\leq i \\leq n$ uniformly at random.\n- For all $j$ such that $i \\leq j \\leq n$, set $a_j := a_j + v$.\n\nTenzing wants to know the expected value of $\\prod_{i=1}^n a_i$ after performing the $m$ operations, modulo $10^9+7$.\n\nFormally, let $M = 10^9+7$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output the integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Before starting to solve this problem, let's establish two basic properties: For two completely independent random variables $x_1,x_2$, we have $E(x_1x_2) = E(x_1)E(x_2)$. For $(a+b)\\times (c+d)$, we have $E((a+b)\\times (c+d)) = E(ac) + E(ad) + E(bc) + E(bd)$. Returning to this problem, let $x_{i,j}$ be a random variable: its value is $v$ when the $i$-th operation sets $a_j$ to $a_j + v$, otherwise it is $0$. Then note that the answer is the expected value of $\\prod_{i=1}^{n}(a_i+\\sum_{j=1}^{m}x_{j,i})$. Applying the second property above to split the product, each term is a product of some $a_i$ and $x$. Specifically, each term has $n$ factors, and for each $i\\in [1,n]$, either $a_i$ is one of its factors, or some $x_{j,i}$ is one of its factors. Let's investigate the expectation of a specific term. Note that if $i_1\\lt i_2$, then $E(x_{j,i_1}\\times x_{j,i_2}) = E(x_{j,i_1})\\times v$, that is, if $x_{j,i_1}$ is $0$ then the whole product is $0$, and if $x_{j,i_1}$ is $v$ then $x_{j,i_2}$ must be $v$. Therefore, for all the $x$ factors in a term, we categorize them by the first index, i.e. we group all $x_{j,...}$ into category $j$. For each category, we only need to focus on the first variable. If it's $v$, then the remaining variables take value $v$, otherwise the result is $0$. Note that the variables in different categories are completely independent (because their values are determined by operations in two different rounds), so the expected product of the variables in two categories can be split into the product of the expected products of the variables within each category. Our goal is to compute the expected sum of all the terms, which can be nicely combined with DP: Let $dp(i,j)$ be the value that we have determined the first $i$ factors of each term and there are $j$ categories that have appeared at least once (if adding the variable at position $i+1$ brings contribution $v$, otherwise the contribution is $\\frac{i+1}{n}\\times v$). The transition can be easily calculated with $O(1)$, depending on whether to append $a_{i+1}$ or $x_{...,i+1}$ to each term, and if it's the latter, we discuss whether the variable belongs to one of the $j$ categories that have appeared or the other $m-j$ categories. The time complexity is $O(n\\times \\min(n,m))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5000 + 8, P = 1e9 + 7;\n\nint n, m, v, a[N], coef[N], dp[N][N];\n\nlong long Pow(long long a, int n) {\n    long long r = 1;\n    while (n) {\n        if (n & 1) r = r * a % P;\n        a = a * a % P, n >>= 1;\n    }\n    return r;\n}\n\nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    cin >> n >> m >> v;\n    for (int i = 1; i <= n; i++) cin >> a[i];\n    dp[0][0] = 1;\n    for (int i = 1; i <= n; i++) {\n        auto coef = i * Pow(n, P - 2) % P * v % P;\n        for (int j = 0; j < i; j++) {\n            dp[i][j + 1] = dp[i - 1][j] * coef % P * (m - j) % P;\n            dp[i][j] = (dp[i][j] + dp[i - 1][j] * (a[i] + 1LL * j * v % P)) % P;\n        }\n    }\n    int ans = 0;\n    for (int i = 0; i <= n; i++)\n        (ans += dp[n][i]) %= P;\n    cout << ans << '\\n';\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1842",
    "index": "H",
    "title": "Tenzing and Random Real Numbers",
    "statement": "There are $n$ uniform random real variables between 0 and 1, inclusive, which are denoted as $x_1, x_2, \\ldots, x_n$.\n\nTenzing has $m$ conditions. Each condition has the form of $x_i+x_j\\le 1$ or $x_i+x_j\\ge 1$.\n\nTenzing wants to know the probability that all the conditions are satisfied, modulo $998~244~353$.\n\nFormally, let $M = 998~244~353$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output the integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Ignoring time complexity for now, how do we calculate the answer? The first step is to enumerate which variables are $<0.5$ and which variables are $>0.5$. Sort all variables $x_i$ by $\\min(x_i,1-x_i)$ and enumerate the sorted result (referring to the permutation). Suppose no variable equals $0.5$, because the probability of being equal to $0.5$ is $0$, variables less than $0.5$ are called white vertices, and those greater than $0.5$ are called black vertices. Each black and white coloring is equiprobable, so we can calculate the probability that satisfies all conditions for each black and white coloring, and then take the average. For two variables less than $0.5$, the condition of $\\le 1$ is always satisfied, and the condition of $\\ge 1$ is never satisfied. Therefore, we do not need to consider the conditions between same-colored points. The condition between white vertex $u$ and black vertex $v$, $x_u+x_v\\le 1$, is satisfied only when $x_u\\le 1-x_v$. Let $y_u=\\min(x_u,1-x_u)=\\begin{cases}x_u&(u\\text{ is white})\\\\1-x_u&(u\\text{ is black})\\end{cases}$, then $y_u$ can be regarded as a random variable in $[0,0.5)$, for $\\le 1$ condition, the white vertex's $y$ must be less than or equal to the black vertex's $y$, so we add an edge from the white vertex to the black vertex; for $\\ge 1$ condition, we add an edge from the black vertex to the white vertex. We get a directed graph that restricts the size relationship of $y_{1\\cdots n}$. Suppose that sorting $y_{1\\cdots n}$ from small to large is $y_{p_1},y_{p_2},\\cdots,y_{p_n}$, then each permutation $p$ is equiprobable, and this $p$ contributes if and only if it is a topological sort, so the probability that satisfies all conditions is the number of topological sorts divided by $n!$. Now the problem has been transformed into a counting problem. For each coloring, count the total number of topological sorts. Now we do not enumerate coloring directly but enumerate topological sorts directly by enumerating a permutation $p$ such that $y_{p_1}<y_{p_2}<\\cdots<y_{p_n}$ and count the number of colorings that satisfy the conditions. It can be found that $\\le 1$ condition limits variablesin in the front position of $p$ to be less than $0.5$, and $\\ge 1$ condition limits variables in the front position of $p$ to be greater than $0.5$. Then we can use bit-mask DP. Let $dp_{mask}$ represent that we have added all vertices in mask into topological sort. We enumerate new added vertex u for transition. If all variables with $\\le 1$ conditions between it are included in mask, it can be colored black; if all variables with $\\ge 1$ conditions between it are included in mask, it can be colored white. Time complexit is $O(2^nn)$.",
    "code": "#include <iostream>\n \nconst int P = 998244353;\n \nlong long Pow(long long a, int n) {\n    long long r = 1;\n    while (n) {\n        if (n & 1) r = r * a % P;\n        a = a * a % P, n >>= 1;\n    }\n    return r;\n}\ninline void inc(int& a, int b) {\n    if((a += b) >= P) a -= P;\n}\n \nint n, m, G[20][2], f[1 << 20];\n \nint main() {\n    std::cin >> n >> m;\n    while (m--) {\n        int t, i, j;\n        std::cin >> t >> i >> j;\n        i--, j--;\n        G[i][t] |= 1 << j;\n        G[j][t] |= 1 << i;\n    }\n    f[0] = 1;\n    for (int S = 0; S < 1 << n; S++)\n        for (int i = 0; i < n; i++) if (~S >> i & 1) {\n            if ((G[i][0] | S) == S) inc(f[S | 1 << i], f[S]);\n            if ((G[i][1] | S) == S) inc(f[S | 1 << i], f[S]);\n        }\n    long long t = 1;\n    for (int i = 1; i <= n; i++) t = t * i * 2 % P;\n    std::cout << f[(1 << n) - 1] * Pow(t, P - 2) % P << '\\n';\n}",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "math",
      "probabilities"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1842",
    "index": "I",
    "title": "Tenzing and Necklace",
    "statement": "\\begin{quote}\nbright, sunny and innocent......\n\\end{quote}\n\nTenzing has a beautiful necklace. The necklace consists of $n$ pearls numbered from $1$ to $n$ with a string connecting pearls $i$ and $(i \\text{ mod } n)+1$ for all $1 \\leq i \\leq n$.\n\nOne day Tenzing wants to cut the necklace into several parts by cutting some strings. But for each connected part of the necklace, there should not be more than $k$ pearls. The time needed to cut each string may not be the same. Tenzing needs to spend $a_i$ minutes cutting the string between pearls $i$ and $(i \\text{ mod } n)+1$.\n\nTenzing wants to know the minimum time in minutes to cut the necklace such that each connected part will not have more than $k$ pearls.",
    "tutorial": "How to solve it if you want to cut exactly $m$ edges ? DP+divide and conquer Add a constraint: \"you must cut off $m$ edges\". Consider enumerating the minimum cut edges from small to large. Suppose the minimum cut edge chosen is $a_1$, and the subsequent optimal solution is $a_2, a_3, ..., a_m$. If another minimum cut edge is selected: $b_1$, and the subsequent optimal solution is $b_2, b_3, ..., b_m$. Assume that $a_i<a_{i+1}, b_i<b_{i+1}, b_1>a_1$. The adjustment method is as follows: Find the smallest $i$ such that $b_i<a_i$, and find the first $j$ such that $b_j\\geq a_j$ after $i$, if it does not exist, let $j=m+1$. It can be observed that $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$ can be replaced with $(a_i,a_{i+1},a_{i+2},...,a_{j-1})$, which is still a valid solution. Moreover, the solution $(a_i,a_{i+1},a_{i+2},...,a_{j-1})$ can also be replaced with $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$, because $b_{i-1}\\geq a_{i-1}$ and $b_j\\geq a_j$. Since $a$ and $b$ are both optimal solutions with fixed $a_1$ and $b_1$, $w_{b_i}+w_{b_{i+1}}+...+w_{b_{j-1}}=w_{a_i}+w_{a_{i+1}}+...+w_{a_{j-1}}$. Therefore, replacing $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$ with $(a_i,a_{i+1},a_{i+2},...,a_{j-1})$ does not increase the total cost. Repeat the above adjustment until there is no $b_i<a_i$. Similarly, it can be proven that only adjusting $a_2,a_3,...,a_m$ is feasible, so that $\\forall_{1\\leq i\\leq m} b_i\\geq a_i$, and the total cost after adjustment remains unchanged. The adjustment method is as follows: Find the smallest $i$ such that $b_i> a_{i+1}$, and find the first $j$ such that $b_j\\leq a_{j+1}$ after $i$ (let $a_{m+1}=+\\infty$). $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$ can be replaced with $(a_{i+1},a_{i+2},a_{i+3},...,a_{j})$, which is still a valid solution. Moreover, the solution $(a_{i+1},a_{i+2},a_{i+3},...,a_{j})$ can also be replaced with $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$, because $b_{i-1}\\leq a_{i}$ and $b_j\\leq a_{j+1}$. Since $a$ and $b$ are both optimal solutions with fixed $a_1$ and $b_1$, $w_{b_i}+w_{b_{i+1}}+...+w_{b_{j-1}}=w_{a_{i+1}}+w_{a_{i+2}}+...+w_{a_j}$. Therefore, replacing $(b_i,b_{i+1},b_{i+2},...,b_{j-1})$ with $(a_{i+1},a_{i+2},a_{i+3},...,a_{j})$ does not increase the total cost. Similarly, it can be proven that only adjusting $a_2,a_3,...,a_m$ is feasible, so that $\\forall_{1\\leq i<m}a_i\\leq b_i\\leq a_{i+1}$, and the total cost after adjustment remains unchanged. The adjustment method is as follows: Find the smallest $j$ such that $b_j\\leq a_{j+1}$ (let $a_{m+1}=+\\infty$). It can be observed that $(a_{2},a_{3},a_{4},...,a_{j})$ can be replaced with $(b_1,b_{2},b_{3},...,b_{j-1})$, which is still a valid solution. Moreover, the solution $(b_1,b_{2},b_{3},...,b_{j-1})$ can also be replaced with $(a_{2},a_{3},a_{4},...,a_{j})$, because $b_j\\leq a_{j+1}$. Since $a$ is the optimal solution with fixed $a_1$ and $b_1$, $w_{b_1}+w_{b_{2}}+...+w_{b_{j-1}}\\geq w_{a_{2}}+w_{a_{3}}+...+w_{a_j}$. Therefore, replacing $(b_1,b_{2},b_{3},...,b_{j-1})$ with $(a_{2},a_{3},a_{4},...,a_{j})$ does not increase the total cost. Combining the above conclusions, we can obtain a solution that must cut off $m$ edges: Let $a_1=1$, find the optimal solution $a_1,a_2,a_3,...,a_m$. Then, it can be assumed that all $b_i$ satisfy $a_i\\leq b_i\\leq a_{i+1}$. A divide-and-conquer algorithm can be used. Let $solve((l_1,r_1),(l_2,r_2),(l_3,r_3),...,(l_m,r_m))$ represent the optimal solution for all $l_i\\leq b_i\\leq r_i$. If $l_1>r_1$, then we are done. Otherwise, let $x=\\lfloor\\frac{l_1+r_1}{2}\\rfloor$, we can use DP to calculate the cost and solution for $b_1=x$ in $O(\\sum r_i-l_i+1)$ time complexity. Then, recursively calculate $solve((l_1,b_1-1),(l_2,b_2),(l_3,b_3),...,(l_m,b_m))$ and $solve((b_1+1,r_1),(b_2,r_2),(b_3,r_3),...,(b_m,r_m))$. Time complexity analysis: $\\sum r_i-l_i+1=(\\sum r_i-l_i)+m$. If the sum of adjacent parts is $\\leq k$, it can be merged, but it is definitely not the optimal solution. Therefore, $m\\leq 2\\lceil\\frac{n}{k}\\rceil$. Assuming that the length of the first segment is $r_1-l_1+1=O(k)$, the time complexity is $O(n\\log k+mk)=O(n\\log k)$. Finally, we need to calculate the solution for all possible $m$ and take the $\\min$ as the final answer. After pruning the first edge, if the optimal solution requires cutting off $m'$ edges, similar to the previous proof, other solutions can be adjusted to satisfy $|m-m'|\\leq 1$ and the total cost does not increase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5e5 + 8;\n\nint n, K, a[N], pre[N * 2];\nlong long dp[N * 2], ans;\n\nvector<int> trim(vector<int> a, int L, int R) {\n    return vector(a.begin() + L, a.end() - R);\n}\nvector<int> init() {\n    static int q[N];\n    q[1] = 0;\n    for (int i = 1, l = 1, r = 1; i <= n; i++) {\n        if (q[l] < i - K) l++;\n        dp[i] = dp[q[l]] + a[i], pre[i] = q[l];\n        while (l <= r && dp[i] < dp[q[r]]) r--;\n        q[++r] = i;\n    }\n    ans = dp[n];\n    vector<int> res;\n    for (int i = n; i; i = pre[i]) res.push_back(i);\n    res.push_back(0), reverse(res.begin(), res.end());\n    return res;\n}\nvector<int> solve(int first, vector<int> L, vector<int> R) {\n    dp[first] = a[first];\n    int l = first, r = first;\n    long long val; int p;\n    auto checkMin = [&](int i) {\n        if (dp[i] < val) val = dp[i], p = i;\n    };\n    for (int i = 0; i < L.size(); i++) {\n        val = 1e18, p = 0;\n        for (int j = R[i]; j >= L[i]; j--) {\n            for (; r >= max(l, j - K); r--) checkMin(r + i);\n            dp[j + i + 1] = val + a[j];\n            pre[j + i + 1] = p;\n        }\n        l = L[i], r = R[i];\n    }\n    val = 1e18, p = 0;\n    for (int i = max(L.back(), n - K + first); i <= R.back(); i++)\n        checkMin(i + L.size());\n    ans = min(ans, val);\n    vector<int> res;\n    for (int i = L.size(); i; i--) res.push_back(p - i), p = pre[p];\n    reverse(res.begin(), res.end());\n    return res;\n}\nvoid divide(int l, int r, vector<int> L, vector<int> R) {\n    if (l > r) return;\n    int mid = (l + r) >> 1;\n    auto M = solve(mid, L, R);\n    divide(l, mid - 1, L, M), divide(mid + 1, r, M, R);\n}\nvoid divide(vector<int> p) {\n    p.push_back(n), divide(1, p[0], trim(p, 0, 1), trim(p, 1, 0));\n}\nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T--) {\n        cin >> n >> K;\n        for (int i = 1; i <= n; i++) cin >> a[i];\n        a[0] = a[n];\n        auto p = init();\n        divide(trim(p, 1, 1));\n        divide(solve(0, trim(p, 0, 1), trim(p, 1, 0)));\n        if ((p.size() - 2) * K >= n)\n            divide(solve(0, trim(p, 1, 2), trim(p, 2, 1)));\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "divide and conquer",
      "dp",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1843",
    "index": "A",
    "title": "Sasha and Array Coloring",
    "statement": "Sasha found an array $a$ consisting of $n$ integers and asked you to paint elements.\n\nYou have to paint each element of the array. You can use as many colors as you want, but each element should be painted into exactly one color, and for each color, there should be at least one element of that color.\n\nThe cost of one color is the value of $\\max(S) - \\min(S)$, where $S$ is the sequence of elements of that color. The cost of the whole coloring is the \\textbf{sum} of costs over all colors.\n\nFor example, suppose you have an array $a = [\\textcolor{red}{1}, \\textcolor{red}{5}, \\textcolor{blue}{6}, \\textcolor{blue}{3}, \\textcolor{red}{4}]$, and you painted its elements into two colors as follows: elements on positions $1$, $2$ and $5$ have color $1$; elements on positions $3$ and $4$ have color $2$. Then:\n\n- the cost of the color $1$ is $\\max([1, 5, 4]) - \\min([1, 5, 4]) = 5 - 1 = 4$;\n- the cost of the color $2$ is $\\max([6, 3]) - \\min([6, 3]) = 6 - 3 = 3$;\n- the total cost of the coloring is $7$.\n\nFor the given array $a$, you have to calculate the \\textbf{maximum} possible cost of the coloring.",
    "tutorial": "First, there exists an optimal answer, in which there are no more than two elements of each color. Proof: let there exist an optimal answer, in which there are more elements of some color than 2. Then, take the median among the elements of this color and paint in another new color in which no other elements are painted. Then the maximum and minimum among the original color will not change, and in the new color the answer is 0, so the answer remains the same. Also, if there are two colors with one element each, they can be combined into one, and the answer will not decrease. It turns out that the numbers are paired (probably except for one; we'll assume it's paired with itself). Sort the array, and then the answer is $\\sum_{pair_i < i} a_i - \\sum_{i < pair_i} a_i$ ($pair_i$ is the number that is paired with $i$-th). Therefore, in the first summand you should take $\\lfloor \\frac{n}{2} \\rfloor$ the largest, and in the second $\\lfloor \\frac{n}{2} \\rfloor$ of the smallest elements of the array. Total complexity: $O(n \\log n)$ for sorting.",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    a.sort()\n    ans = 0\n    for i in range(n // 2):\n        ans += a[-i-1] - a[i]\n    print(ans)\n    \n    \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1843",
    "index": "B",
    "title": "Long Long",
    "statement": "Today Alex was brought array $a_1, a_2, \\dots, a_n$ of length $n$. He can apply as many operations as he wants (including zero operations) to change the array elements.\n\nIn $1$ operation Alex can choose any $l$ and $r$ such that $1 \\leq l \\leq r \\leq n$, and multiply all elements of the array from $l$ to $r$ inclusive by $-1$. In other words, Alex can replace the subarray $[a_l, a_{l + 1}, \\dots, a_r]$ by $[-a_l, -a_{l + 1}, \\dots, -a_r]$ in $1$ operation.\n\nFor example, let $n = 5$, the array is $[1, -2, 0, 3, -1]$, $l = 2$ and $r = 4$, then after the operation the array will be $[1, 2, 0, -3, -1]$.\n\nAlex is late for school, so you should help him find the maximum possible sum of numbers in the array, which can be obtained by making any number of operations, as well as the minimum number of operations that must be done for this.",
    "tutorial": "We can delete all zeros from the array, and it won't affect on answer. Maximum sum is $\\sum_{i=1}^n |a_i|$. Minimum number of operations we should do - number of continuous subsequences with negative values of elements. Total complexity: $O(n)$",
    "code": "T = int(input())\nfor _ in range(T):\n    n = int(input())\n    a = list(map(int, input().split()))\n    \n    sum = 0\n    cnt = 0\n    open = False\n    for x in a:\n        sum += abs(x)\n        if x < 0 and not open:\n            open = True\n            cnt += 1\n        if x > 0:\n            open = False\n \n    print(sum, cnt)",
    "tags": [
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1843",
    "index": "C",
    "title": "Sum in Binary Tree",
    "statement": "Vanya really likes math. One day when he was solving another math problem, he came up with an interesting tree. This tree is built as follows.\n\nInitially, the tree has only one vertex with the number $1$ — the root of the tree. Then, Vanya adds two children to it, assigning them consecutive numbers — $2$ and $3$, respectively. After that, he will add children to the vertices in increasing order of their numbers, starting from $2$, assigning their children the minimum unused indices. As a result, Vanya will have an infinite tree with the root in the vertex $1$, where each vertex will have exactly two children, and the vertex numbers will be arranged sequentially by layers.\n\n\\begin{center}\n{\\small Part of Vanya's tree.}\n\\end{center}\n\nVanya wondered what the sum of the vertex numbers on the path from the vertex with number $1$ to the vertex with number $n$ in such a tree is equal to. Since Vanya doesn't like counting, he asked you to help him find this sum.",
    "tutorial": "It is easy to notice that the children of the vertex with number $u$ have numbers $2 \\cdot u$ and $2 \\cdot u + 1$. So, the ancestor of the vertex $u$ has the number $\\lfloor \\frac{u}{2} \\rfloor$. Note that based on this formula, the size of the path from the root to the vertex with number $n$ equals $\\lfloor \\log_2 n \\rfloor$. Therefore with given constraints we can write out the path to the root explicitly and calculate the sum of vertex numbers on it in $O(\\log n)$. Total complexity: $O(\\log n)$ for the test case.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    s = 0\n    while n >= 1:\n        s += n\n        n //= 2\n    print(s)",
    "tags": [
      "bitmasks",
      "combinatorics",
      "math",
      "trees"
    ],
    "rating": 800
  },
  {
    "contest_id": "1843",
    "index": "D",
    "title": "Apple Tree",
    "statement": "Timofey has an apple tree growing in his garden; it is a rooted tree of $n$ vertices with the root in vertex $1$ (the vertices are numbered from $1$ to $n$). A tree is a connected graph without loops and multiple edges.\n\nThis tree is very unusual — it grows with its root upwards. However, it's quite normal for programmer's trees.\n\nThe apple tree is quite young, so only two apples will grow on it. Apples will grow in certain vertices (these vertices may be the same). After the apples grow, Timofey starts shaking the apple tree until the apples fall. Each time Timofey shakes the apple tree, the following happens to each of the apples:\n\nLet the apple now be at vertex $u$.\n\n- If a vertex $u$ has a child, the apple moves to it (if there are several such vertices, the apple can move to any of them).\n- Otherwise, the apple falls from the tree.\n\nIt can be shown that after a finite time, both apples will fall from the tree.\n\nTimofey has $q$ assumptions in which vertices apples can grow. He assumes that apples can grow in vertices $x$ and $y$, and wants to know the number of pairs of vertices ($a$, $b$) from which apples can fall from the tree, where $a$ — the vertex from which an apple from vertex $x$ will fall, $b$ — the vertex from which an apple from vertex $y$ will fall. Help him do this.",
    "tutorial": "Let $cnt_v$ be the number of vertices from which an apple can fall if it is in the vertex $v$. Then the answer to the query is $cnt_v \\cdot cnt_u$. Note that the value of $cnt_v$ is equal to the number of leaves in the subtree of vertex $v$. Then, these values can be computed using the DFS or BFS. The value $cnt$ for a vertex will be equal to $1$ if this vertex is a leaf, otherwise it will be equal to the sum of these values for all children of the vertex. Total complexity: $O(n + q)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n \nvector<vector<int>> g;\nvector<ll> cnt;\n \nvoid dfs(int v, int p) {\n    if (g[v].size() == 1 && g[v][0] == p) {\n        cnt[v] = 1;\n    } else {\n        for (auto u : g[v]) {\n            if (u != p) {\n                dfs(u, v);\n                cnt[v] += cnt[u];\n            }\n        }\n    }\n}\n \nvoid solve() {\n    int n, q;\n    cin >> n;\n \n    g.assign(n, vector<int>());\n    \n    for (int i = 0; i < n - 1; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        g[u].push_back(v);\n        g[v].push_back(u);\n    }\n \n    cnt.assign(n, 0);\n    dfs(0, -1);\n \n    cin >> q;\n    for (int i = 0; i < q; i++) {\n        int c, k;\n        cin >> c >> k;\n        c--; k--;\n \n        ll res = cnt[c] * cnt[k];\n        cout << res << '\\n';\n    }\n}\n \nsigned main() {\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1843",
    "index": "E",
    "title": "Tracking Segments",
    "statement": "You are given an array $a$ consisting of $n$ zeros. You are also given a set of $m$ not necessarily different segments. Each segment is defined by two numbers $l_i$ and $r_i$ ($1 \\le l_i \\le r_i \\le n$) and represents a subarray $a_{l_i}, a_{l_i+1}, \\dots, a_{r_i}$ of the array $a$.\n\nLet's call the segment $l_i, r_i$ beautiful if the number of ones on this segment \\textbf{is strictly greater} than the number of zeros. For example, if $a = [1, 0, 1, 0, 1]$, then the segment $[1, 5]$ is beautiful (the number of ones is $3$, the number of zeros is $2$), but the segment $[3, 4]$ is not is beautiful (the number of ones is $1$, the number of zeros is $1$).\n\nYou also have $q$ changes. For each change you are given the number $1 \\le x \\le n$, which means that you must assign an element $a_x$ the value $1$.\n\nYou have to find the first change after which \\textbf{at least one} of $m$ given segments becomes beautiful, or report that none of them is beautiful after processing all $q$ changes.",
    "tutorial": "Let's use a binary search for an answer. It will work, because if some segment was good, then after one more change it will not be no longer good, and if all segments were bad, then if you remove the last change, they will remain bad. To check if there is a good segment for the prefix of changes, you can build the array obtained after these changes, and then count the prefix sums in $O(n)$. After that, you can go through all the segments and check for $O(1)$ for a segment whether it is a good or not. Total complexity: $O((n + m) \\cdot \\log q)$.",
    "code": "def solve():\n    n, m = map(int, input().split())\n    segs = []\n    for i in range(m):\n        l, r = map(int, input().split())\n        l -= 1\n        segs.append([l, r])\n    q = int(input())\n    ord = [0] * q\n    for i in range(q):\n        ord[i] = int(input())\n        ord[i] -= 1\n    l = 0\n    r = q + 1\n    while r - l > 1:\n        M = (l + r) // 2\n        cur = [0] * n\n        for i in range(M):\n            cur[ord[i]] = 1\n        pr = [0] * (n + 1)\n        for i in range(n):\n            pr[i+1] = pr[i] + cur[i]\n        ok = False\n        for i in segs:\n            if(pr[i[1]] - pr[i[0]] > (i[1] - i[0]) // 2):\n                ok = True\n                break\n        if ok:\n            r = M\n        else:\n            l = M\n    if r == q + 1:\n        r = -1\n    print(r)\n \ntc = int(input())\nfor T in range(tc):\n    solve()",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1843",
    "index": "F1",
    "title": "Omsk Metro (simple version)",
    "statement": "\\textbf{This is the simple version of the problem. The only difference between the simple and hard versions is that in this version $u = 1$.}\n\nAs is known, Omsk is the capital of Berland. Like any capital, Omsk has a well-developed metro system. The Omsk metro consists of a certain number of stations connected by tunnels, and between any two stations there is exactly one path that passes through each of the tunnels no more than once. In other words, the metro is a tree.\n\nTo develop the metro and attract residents, the following system is used in Omsk. Each station has its own weight $x \\in \\{-1, 1\\}$. If the station has a weight of $-1$, then when the station is visited by an Omsk resident, a fee of $1$ burle is charged. If the weight of the station is $1$, then the Omsk resident is rewarded with $1$ burle.\n\nOmsk Metro currently has only one station with number $1$ and weight $x = 1$. Every day, one of the following events occurs:\n\n- A new station with weight $x$ is added to the station with number $v_i$, and it is assigned a number that is one greater than the number of existing stations.\n- Alex, who lives in Omsk, wonders: is there a subsegment$\\dagger$ (possibly empty) of the path between vertices $u$ and $v$ such that, by traveling along it, exactly $k$ burles can be earned (if $k < 0$, this means that $k$ burles will have to be spent on travel). In other words, Alex is interested in whether there is such a subsegment of the path that the sum of the weights of the vertices in it is equal to $k$. Note that the subsegment can be empty, and then the sum is equal to $0$.\n\nYou are a friend of Alex, so your task is to answer Alex's questions.\n\n$\\dagger$Subsegment — continuous sequence of elements.",
    "tutorial": "Let $\\mathrm{mx}$ be the maximal sum on the path subsegment, $\\mathrm{mn}$ - the minimal sum on the path subsegment. Then it is said that a subsegment with sum $x$ exists if and only if $\\mathrm{mn} \\leq x \\leq \\mathrm{mx}$. Proof: Let us fix the subsegment with the minimum sum and the subsegment with the maximum sum. Now, we want to go from the first segment to the second one by consecutively removing or adding elements from the ends of the segment. Note that, due to the fact that $x \\in \\{-1, 1\\}$, for each such action, the sum on the segment will change by exactly $1$. In other words, no matter how we go from one segment to another, the sum will remain a discretely continuous value. Then, since this function takes values of the minimum and maximum sum, it also takes all values from the segment between them (by the intermediate value theorem). Thus, the set of all possible sums on the subsegments is the interval of integers between the minimum and maximum sum, from which the original assumption follows. Now, we have turned the problem down to finding the subsegment with the minimum and maximum sum on the path in the tree. Let $\\mathrm{mx}_u$ be the maximum sum on the subsegment on the path from $1$ to $u$, $\\mathrm{suf}_u$ - the maximum sum on the suffix of the path from $1$ to $u$, $p_u$ - the ancestor of vertex $u$, $x_u$ - its weight. Then $\\mathrm{suf}_u = \\max({0, \\mathrm{suf}_{p_u} + x_u})$, $\\mathrm{mx}_u = \\max({\\mathrm{mx}_{p_u}, \\mathrm{suf}_u})$. Thus, we have learned to calculate the necessary values for a vertex immediately at the moment of its addition, which allows us to solve the problem online (but it is not required in the problem itself). The values for the minimum are counted in the same way. Total complexity: $O(n)$.",
    "code": "class info:\n    mn_suf = 0\n    mx_suf = 0\n    mn_ans = 0\n    mx_ans = 0\n \ndef solve():\n    n = int(input())\n    \n    start = info()\n    start.mx_suf = start.mx_ans = 1\n    \n    st = [start]\n    for i in range(n):\n        com = input().split()\n        if (com[0] == '+'):\n            v = int(com[1]) - 1\n            x = int(com[2])\n \n            pref = st[v]\n            cur = info()\n \n            cur.mn_suf = min(0, pref.mn_suf + x)\n            cur.mx_suf = max(0, pref.mx_suf + x)\n            cur.mn_ans = min(pref.mn_ans, cur.mn_suf)\n            cur.mx_ans = max(pref.mx_ans, cur.mx_suf)\n \n            st.append(cur)\n        else:\n            v = int(com[2]) - 1\n            x = int(com[3])\n \n            if st[v].mn_ans <= x <= st[v].mx_ans:\n                print(\"Yes\")\n            else:\n                print(\"No\")\n \nt = int(input())\nfor testCase in range(t):\n    solve()",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1843",
    "index": "F2",
    "title": "Omsk Metro (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the simple and hard versions is that in this version $u$ can take any possible value.}\n\nAs is known, Omsk is the capital of Berland. Like any capital, Omsk has a well-developed metro system. The Omsk metro consists of a certain number of stations connected by tunnels, and between any two stations there is exactly one path that passes through each of the tunnels no more than once. In other words, the metro is a tree.\n\nTo develop the metro and attract residents, the following system is used in Omsk. Each station has its own weight $x \\in \\{-1, 1\\}$. If the station has a weight of $-1$, then when the station is visited by an Omsk resident, a fee of $1$ burle is charged. If the weight of the station is $1$, then the Omsk resident is rewarded with $1$ burle.\n\nOmsk Metro currently has only one station with number $1$ and weight $x = 1$. Every day, one of the following events occurs:\n\n- A new station with weight $x$ is added to the station with number $v_i$, and it is assigned a number that is one greater than the number of existing stations.\n- Alex, who lives in Omsk, wonders: is there a subsegment$\\dagger$ (possibly empty) of the path between vertices $u$ and $v$ such that, by traveling along it, exactly $k$ burles can be earned (if $k < 0$, this means that $k$ burles will have to be spent on travel). In other words, Alex is interested in whether there is such a subsegment of the path that the sum of the weights of the vertices in it is equal to $k$. Note that the subsegment can be empty, and then the sum is equal to $0$.\n\nYou are a friend of Alex, so your task is to answer Alex's questions.\n\n$\\dagger$Subsegment — continuous sequence of elements.",
    "tutorial": "Similarly to the problem F1, we need to be able to find a subsegment with maximum and minimum sum, but on an arbitrary path in the tree. To do this, we will use the technique of binary lifts. For each lift, we will store the maximum/minimum sum on the prefix and suffix, the sum of the subsegment and the maximum sum on the subsegment, as in the problem about the maximum sum on a subsegment of an array. Then, such values are easily can be recalculated by analogy with the recalculation from the problem F1. It is also worth noting that such binary lifts can also be constructed online, but this was not required in the problem. Then, all that remains is to go up from the ends of the path to their LCA, and then combine the answers of the vertical paths into the answer for the whole path. Total complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\n \nstruct info {\n    int sum, minPrefL, maxPrefL, minPrefR, maxPrefR, minSeg, maxSeg;\n \n    info(int el = 0) {\n        sum = el;\n        minSeg = minPrefL = minPrefR = min(el, 0);\n        maxSeg = maxPrefL = maxPrefR = max(el, 0);\n    }\n};\n \nstruct question {\n    int u, v, x;\n};\n \ninfo merge(info& a, info& b) {\n    info res;\n    res.sum = a.sum + b.sum;\n    res.minPrefL = min(a.minPrefL, a.sum + b.minPrefL);\n    res.maxPrefL = max(a.maxPrefL, a.sum + b.maxPrefL);\n    res.minPrefR = min(a.minPrefR + b.sum, b.minPrefR);\n    res.maxPrefR = max(a.maxPrefR + b.sum, b.maxPrefR);\n    res.minSeg = min({a.minSeg, b.minSeg, a.minPrefR + b.minPrefL});\n    res.maxSeg = max({a.maxSeg, b.maxSeg, a.maxPrefR + b.maxPrefL});\n    return res;\n}\n \nconst int MAXN = 200100;\nconst int lg = 17;\n \nint up[lg + 1][MAXN];\ninfo ans[lg + 1][MAXN];\nint d[MAXN];\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    for (int i = 0; i <= lg; i++) up[i][0] = 0;\n    ans[0][0] = info(1);\n    d[0] = 0;\n \n    int cur = 0;\n    for (int q = 0; q < n; q++) {\n        char c;\n        cin >> c;\n        if (c == '+') {\n            int v, x;\n            cin >> v >> x;\n            v--;\n            cur++;\n \n            d[cur] = d[v] + 1;\n \n            up[0][cur] = v;\n            for (int j = 0; j <= lg - 1; j++) up[j + 1][cur] = up[j][up[j][cur]];\n \n            ans[0][cur] = info(x);\n            for (int j = 0; j <= lg - 1; j++) ans[j + 1][cur] = merge(ans[j][cur], ans[j][up[j][cur]]);\n        } else {\n            int u, v, x;\n            cin >> u >> v >> x;\n            u--; v--;\n            \n            if (d[u] < d[v]) swap(u, v);\n \n            int dif = d[u] - d[v];\n            info a, b;\n            for (int i = lg; i >= 0; i--) {\n                if ((dif >> i) & 1) {\n                    a = merge(a, ans[i][u]);\n                    u = up[i][u];\n                }\n            }\n \n            if (u == v) {\n                a = merge(a, ans[0][u]);\n            } else {\n                for (int i = lg; i >= 0; i--) {\n                    if (up[i][u] != up[i][v]) {\n                        a = merge(a, ans[i][u]);\n                        u = up[i][u];\n                        b = merge(b, ans[i][v]);\n                        v = up[i][v];\n                    }\n                }\n \n                a = merge(a, ans[1][u]);\n                b = merge(b, ans[0][v]);\n            }\n \n            swap(b.minPrefL, b.minPrefR);\n            swap(b.maxPrefL, b.maxPrefR);\n \n            info res = merge(a, b);\n            if (res.minSeg <= x && x <= res.maxSeg) {\n                cout << \"Yes\\n\";\n            } else {\n                cout << \"No\\n\";\n            }\n        }\n    }\n}\n \nint main() {\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1844",
    "index": "A",
    "title": "Subtraction Game",
    "statement": "You are given two positive integers, $a$ and $b$ ($a < b$).\n\nFor some positive integer $n$, two players will play a game starting with a pile of $n$ stones. They take turns removing exactly $a$ or exactly $b$ stones from the pile. The player who is unable to make a move loses.\n\nFind a positive integer $n$ such that the second player to move in this game has a winning strategy. This means that no matter what moves the first player makes, the second player can carefully choose their moves (possibly depending on the first player's moves) to ensure they win.",
    "tutorial": "We present two approaches. Approach 1 If $a \\ge 2$, then $n = 1$ works. Else if $a = 1$ and $b \\ge 3$, $n = 2$ works. Otherwise, $a = 1$ and $b = 2$, so $n = 3$ works. Approach 2 Printing $a+b$ works because no matter what move the first player makes, the second player can respond with the opposite move. The time complexity is $\\mathcal{O}(1)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t,a,b;\n    scanf(\"%d\",&t);\n    while (t--) {\n        scanf(\"%d %d\",&a,&b);\n        printf(\"%d\\n\",a+b);\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "games"
    ],
    "rating": 800
  },
  {
    "contest_id": "1844",
    "index": "B",
    "title": "Permutations & Primes",
    "statement": "You are given a positive integer $n$.\n\nIn this problem, the $\\operatorname{MEX}$ of a collection of integers $c_1,c_2,\\dots,c_k$ is defined as the smallest \\textbf{positive} integer $x$ which does not occur in the collection $c$.\n\nThe primality of an array $a_1,\\dots,a_n$ is defined as the number of pairs $(l,r)$ such that $1 \\le l \\le r \\le n$ and $\\operatorname{MEX}(a_l,\\dots,a_r)$ is a prime number.\n\nFind any permutation of $1,2,\\dots,n$ with the maximum possible primality among all permutations of $1,2,\\dots,n$.\n\nNote:\n\n- A prime number is a number greater than or equal to $2$ that is not divisible by any positive integer except $1$ and itself. For example, $2,5,13$ are prime numbers, but $1$ and $6$ are not prime numbers.\n- A permutation of $1,2,\\dots,n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "The cases $n \\le 2$ can be handled separately. For $n \\ge 3$, any construction with $a_1 = 2, a_{\\lfloor (n+1)/2 \\rfloor} = 1, a_n = 3$ is optimal. We can prove this as follows: Note that since $2$ and $3$ are both prime, any $(l,r)$ with $l \\le \\left\\lfloor \\frac{n+1}{2} \\right\\rfloor \\le r$ has a prime $\\operatorname{MEX}(a_l,\\dots,a_r)$ except for possibly $(l,r) = (1,n)$, where $\\operatorname{MEX}(a_1,\\dots,a_n) = n+1$. Therefore the primality of this array is $\\left\\lfloor \\frac{n+1}{2} \\right\\rfloor \\cdot \\left\\lceil \\frac{n+1}{2} \\right\\rceil - [n+1\\text{ is not prime}]$, where $[P] = 1$ if proposition $P$ is true and $0$ if $P$ is false. On the other hand, for any permutation of $1,\\dots,n$, let $k$ be the index with $a_k = 1$. The primality of this array cannot exceed $k(n+1-k)-[n+1\\text{ is not prime}]$, since any pair $(l,r)$ with prime $\\operatorname{MEX}(a_l,\\dots,a_r) \\ge 2$ must satisfy $l \\le k \\le r$, and additionally $\\operatorname{MEX}(a_1,\\dots,a_n) = n+1$ no matter what the permutation is. The function $f(k) = k(n+1-k)$ is a quadratic which is maximized at $k = \\left\\lfloor \\frac{n+1}{2} \\right\\rfloor$, so $k(n+1-k)-[n+1\\text{ is not prime}] \\le \\left\\lfloor \\frac{n+1}{2} \\right\\rfloor \\cdot \\left\\lceil \\frac{n+1}{2} \\right\\rceil - [n+1\\text{ is not prime}]$ as required. The time complexity is $\\mathcal{O}(n)$ (note that we don't even need to sieve for primes!).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint a[200000];\nint main() {\n    int i;\n    int t,n;\n    scanf(\"%d\",&t);\n    while (t--) {\n        scanf(\"%d\",&n);\n        if (n == 1) printf(\"1\\n\");\n        else if (n == 2) printf(\"1 2\\n\");\n        else {\n            int c = 4;\n            fill(a,a+n,0);\n            a[0] = 2,a[n/2] = 1,a[n-1] = 3;\n            for (i = 0; i < n; i++) {\n                if (a[i] == 0) a[i] = c++;\n            }\n            for (i = 0; i < n; i++) printf(\"%d%c\",a[i],(i == n-1) ? '\\n':' ');\n        }\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1844",
    "index": "C",
    "title": "Particles",
    "statement": "You have discovered $n$ mysterious particles on a line with integer charges of $c_1,\\dots,c_n$. You have a device that allows you to perform the following operation:\n\n- Choose a particle and remove it from the line. The remaining particles will shift to fill in the gap that is created. If there were particles with charges $x$ and $y$ directly to the left and right of the removed particle, they combine into a single particle of charge $x+y$.\n\nFor example, if the line of particles had charges of $[-3,1,4,-1,5,-9]$, performing the operation on the $4$th particle will transform the line into $[-3,1,9,-9]$.\n\nIf we then use the device on the $1$st particle in this new line, the line will turn into $[1,9,-9]$.\n\nYou will perform operations until there is only one particle left. What is the maximum charge of this remaining particle that you can obtain?",
    "tutorial": "Consider the set of even-indexed particles and the set of odd-indexed particles. Observe that particles can only ever combine with other particles from the same set. It follows that the answer is at most $\\max\\left(\\sum_{\\text{odd }i} \\max(c_i,0),\\sum_{\\text{even }i} \\max(c_i,0)\\right).$ On the other hand, this bound is almost always obtainable. We can first perform the operation on all negatively charged particles in the same set as the desired final particle, then perform the operation on all the particles from the opposite set. There is a corner case where all particles are negative, where the answer is just $\\max(c_1,\\dots,c_n)$. The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int LLI;\n\nint c[200000];\nint main() {\n    int i;\n    int t,n;\n    scanf(\"%d\",&t);\n    while (t--) {\n        scanf(\"%d\",&n);\n        for (i = 0; i < n; i++) scanf(\"%d\",&c[i]);\n\n        int allneg = 1;\n        for (i = 0; i < n; i++) allneg &= (c[i] < 0);\n        if (allneg) printf(\"%d\\n\",*max_element(c,c+n));\n        else {\n            LLI ans1 = 0,ans2 = 0;\n            for (i = 0; i < n; i++) {\n                if (i & 1) ans1 += max(c[i],0);\n                else ans2 += max(c[i],0);\n            }\n            printf(\"%lld\\n\",max(ans1,ans2));\n        }\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1844",
    "index": "D",
    "title": "Row Major",
    "statement": "The row-major order of an $r \\times c$ grid of characters $A$ is the string obtained by concatenating all the rows, i.e. $$ A_{11}A_{12} \\dots A_{1c}A_{21}A_{22} \\dots A_{2c} \\dots A_{r1}A_{r2} \\dots A_{rc}. $$\n\nA grid of characters $A$ is bad if there are some two adjacent cells (cells sharing an edge) with the same character.\n\nYou are given a positive integer $n$. Consider all strings $s$ consisting of only lowercase Latin letters such that they are \\textbf{not} the row-major order of \\textbf{any} bad grid. Find any string with the minimum number of distinct characters among all such strings of length $n$.\n\nIt can be proven that at least one such string exists under the constraints of the problem.",
    "tutorial": "The condition is equivalent to a graph of pairs of characters in $s$ that need to be different. In graph-theoretic language, we need to find the chromatic number of this graph. By considering the $1 \\times n$ and $n \\times 1$ grids, there is an edge between character $u$ and $u+1$ for all $1 \\le u \\le n-1$. By considering a $\\frac{n}{d} \\times d$ grid (where $d$ divides $n$), there is an edge between character $u$ and $u+d$ for all $1 \\le u \\le n-d$ whenever $d$ divides $n$. Let $c$ be the smallest positive integer that does not divide $n$. There is an edge between every pair of the characters $1,\\dots,c$ (in graph-theoretic language, this is a clique), so the answer is at least $c$. On the other hand, consider the string obtained by letting $s_1,\\dots,s_c$ be all distinct characters and repeating this pattern periodically ($s_i = s_{i+c}$ for all $1 \\le i \\le n-c$). Any pair of equal characters have an index difference that is a multiple of $c$, say $kc$. But since $c$ does not divide $n$, $kc$ also does not divide $n$, so these characters are not connected by an edge. Therefore this construction gives a suitable string with $c$ distinct characters. The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nchar s[1000001];\nint main() {\n    int i;\n    int t,n;\n    scanf(\"%d\",&t);\n    while (t--) {\n        scanf(\"%d\",&n);\n        int c = 1;\n        while ((n % c) == 0) c++;\n        for (i = 0; i < n; i++) s[i] = 'a'+(i % c);\n        s[n] = '\\0';\n        printf(\"%s\\n\",s);\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1844",
    "index": "E",
    "title": "Great Grids",
    "statement": "An $n \\times m$ grid of characters is called great if it satisfies these three conditions:\n\n- Each character is either 'A', 'B', or 'C'.\n- Every $2 \\times 2$ contiguous subgrid contains all three different letters.\n- Any two cells that share a common edge contain different letters.\n\nLet $(x,y)$ denote the cell in the $x$-th row from the top and $y$-th column from the left.\n\nYou want to construct a great grid that satisfies $k$ constraints. Each constraint consists of two cells, $(x_{i,1},y_{i,1})$ and $(x_{i,2},y_{i,2})$, that share exactly one corner. You want your great grid to have the same letter in cells $(x_{i,1},y_{i,1})$ and $(x_{i,2},y_{i,2})$.\n\nDetermine whether there exists a great grid satisfying all the constraints.",
    "tutorial": "We present two approaches. Approach 1 Let the letters 'A', 'B', and 'C' correspond to the numbers $0$, $1$, and $2$ modulo $3$ respectively. Consider drawing an arrow between any two adjacent cells in a great grid pointing to the right or down, and label this arrow with the difference of the two cells modulo $3$. The conditions imply that all labels are $1$ or $2$, and in each contiguous $2 \\times 2$ subgrid, the top arrow has the same label as the bottom arrow, and the left arrow has the same label as the right arrow. Hence we can associate a type to each of $n-1$ rows and $m-1$ columns which is its label. A constraint for cells $(x,y)$ and $(x+1,y+1)$ means that row $x$ and column $y$ must have different labels, and a constraint for cells $(x,y+1)$ and $(x+1,y)$ means that row $x$ and $y$ must have the same label. These relations form a graph, and the problem reduces to a variant of $2$-colourability, which can be checked using DFS or a DSU. Approach 2 In a great grid, draw a '/' or '\\' for each $2 \\times 2$ subgrid connecting the equal letters. We can observe that these grids have a simple pattern: every two rows are either the same or opposite. Furthermore, any such pattern corresponds to a great grid (this can be proven with the idea in approach 1). We can associate a type to each row and column, a boolean variable $0$ or $1$, such that an entry is '/' or '\\' depending on whether the labels are the same or different. The constraints correspond to entries needing to be '/' or '\\', forming a graph of pairs of labels that must be the same or different. Thus the problem reduces to a variant of $2$-colourability, which can be checked using DFS or a DSU. The intended time complexity is $\\mathcal{O}(n+m+k)$, although slower implementations with complexities like $\\mathcal{O}(nm+k)$ or $\\mathcal{O}(k(n+m))$ can also pass.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef vector<pair<int,int> > vpii;\n#define mp make_pair\n#define pb push_back\n\nvpii adjList[4000];\nint colour[4000],bad = 0;\nint doDFS(int u,int c) {\n    if (colour[u] != -1) {\n        if (colour[u] != c) bad = 1;\n        return 0;\n    }\n    colour[u] = c;\n    for (auto [v,e]: adjList[u]) doDFS(v,c^e);\n    return 0;\n}\nint main() {\n    int i;\n    int t,n,m,k;\n    int x1,y1,x2,y2;\n    scanf(\"%d\",&t);\n    while (t--) {\n        scanf(\"%d %d %d\",&n,&m,&k);\n        for (i = 0; i < k; i++) {\n            scanf(\"%d %d %d %d\",&x1,&y1,&x2,&y2);\n            x1--,y1--,x2--,y2--;\n            adjList[min(x1,x2)].pb(mp(n+min(y1,y2),(x1+y1 != x2+y2)));\n            adjList[n+min(y1,y2)].pb(mp(min(x1,x2),(x1+y1 != x2+y2)));\n        }\n\n        fill(colour,colour+n+m,-1),bad = 0;\n        for (i = 0; i < n+m; i++) {\n            if (colour[i] == -1) doDFS(i,0);\n        }\n        printf(bad ? \"NO\\n\":\"YES\\n\");\n\n        for (i = 0; i < n+m; i++) adjList[i].clear();\n    }\n    return 0;\n}",
    "tags": [
      "2-sat",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1844",
    "index": "F1",
    "title": "Min Cost Permutation (Easy Version)",
    "statement": "\\textbf{The only difference between this problem and the hard version is the constraints on $t$ and $n$.}\n\nYou are given an array of $n$ positive integers $a_1,\\dots,a_n$, and a (possibly negative) integer $c$.\n\nAcross all permutations $b_1,\\dots,b_n$ of the array $a_1,\\dots,a_n$, consider the minimum possible value of $$\\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|.$$ Find the lexicographically smallest permutation $b$ of the array $a$ that achieves this minimum.\n\nA sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds:\n\n- $x$ is a prefix of $y$, but $x \\ne y$;\n- in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$.",
    "tutorial": "Let the cost of a permutation $b$ of $a$ be the value $\\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|$. When $c \\ge 0$, it can be proven that the minimum cost can be obtained by sorting $a$ in nondecreasing order. As sorting $a$ in nondecreasing order is also the lexicographically smallest array, this is the answer. Similarly, when $c < 0$, it can be proven that the minimum cost can be obtained by sorting $a$ in nonincreasing order. Furthermore, if we have fixed the values of $b_1,\\dots,b_k$ for some $1 \\le k < n$, then intuitively, one optimal permutation $b_{k+1},\\dots,b_n$ of the remaining elements is to sort them in nonincreasing order$^\\dagger$. To find the lexicographically smallest permutation, we can greedily loop through $k = 1,\\dots,n$, each time taking the smallest $b_k$ that does not increase the cost. If $a_k \\ge \\dots \\ge a_n$ are the unused elements sorted in nonincreasing order, then the condition we need to check to determine if setting $b_k := a_i$ is good is whether $|a_{i-1}-a_i-c|+|a_i-a_{i+1}-c|+|b_{k-1}-a_k-c| \\ge |a_{i-1}-a_{i+1}-c|+|b_{k-1}-a_i-c|+|a_i-a_k-c|\\quad(*)$ (with some adjustments in the corner cases when $k = 1$ or $i = k,n$). This condition $(*)$ can be checked in constant time, and we try $\\mathcal{O}(n)$ values of $i$ for each of the $\\mathcal{O}(n)$ values of $k$, so the time complexity is $\\mathcal{O}(n^2)$. The proofs of the claims used in this solution can be found at the end of the solution for the hard version. $^\\dagger$This is actually not true as stated (e.g. when $c = -1$ and we fix $b_1 = 2$, $[2,1,9,8]$ is better than $[2,9,8,1]$), but it turns out it is true for all states that the greedy algorithm can reach (i.e. in this example, the greedy algorithm could not have chosen $b_1 = 2$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int LLI;\n\nint a[200000];\nint main() {\n    int i,j;\n    int t,n,c;\n    scanf(\"%d\",&t);\n    while (t--) {\n        scanf(\"%d %d\",&n,&c);\n        for (i = 0; i < n; i++) scanf(\"%d\",&a[i]);\n        if (c >= 0) {\n            sort(a,a+n);\n            for (i = 0; i < n; i++) printf(\"%d%c\",a[i],(i == n-1) ? '\\n':' ');\n            continue;\n        }\n\n        sort(a,a+n,greater<int>());\n        for (i = 0; i < n; i++) {\n            for (j = n-1; j > i; j--) {\n                LLI diff = -abs(a[j]-a[j-1]-c);\n                if (j < n-1) {\n                    diff -= abs(a[j+1]-a[j]-c);\n                    diff += abs(a[j+1]-a[j-1]-c);\n                }\n                if (i == 0) diff += abs(a[i]-a[j]-c);\n                else {\n                    diff -= abs(a[i]-a[i-1]-c);\n                    diff += abs(a[i]-a[j]-c);\n                    diff += abs(a[j]-a[i-1]-c);\n                }\n                if (diff == 0) {\n                    for (; j > i; j--) swap(a[j],a[j-1]);\n                }\n            }\n        }\n        for (i = 0; i < n; i++) printf(\"%d%c\",a[i],(i == n-1) ? '\\n':' ');\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1844",
    "index": "F2",
    "title": "Min Cost Permutation (Hard Version)",
    "statement": "\\textbf{The only difference between this problem and the easy version is the constraints on $t$ and $n$.}\n\nYou are given an array of $n$ positive integers $a_1,\\dots,a_n$, and a (possibly negative) integer $c$.\n\nAcross all permutations $b_1,\\dots,b_n$ of the array $a_1,\\dots,a_n$, consider the minimum possible value of $$\\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|.$$ Find the lexicographically smallest permutation $b$ of the array $a$ that achieves this minimum.\n\nA sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds:\n\n- $x$ is a prefix of $y$, but $x \\ne y$;\n- in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$.",
    "tutorial": "Let $c < 0$. We now simplify condition $(*)$, which involves considering a few cases depending on the sign of the terms. It turns out that the condition is equivalent to ($a_{i-1}-a_{i+1} \\le |c|$ or $a_{i-1} = a_i$ or $a_i = a_{i+1}$) and ($b_{k-1}-a_i \\le |c|$) (for full details, see the overall proof below). Sort $a$ in nonincreasing order so that $a_1 \\ge a_2 \\ge \\dots \\ge a_n$. We can simulate the greedy algorithm from the easy version with the help of a linked list of the unused elements of $a$ and a set of $a_i$ which satisfy the first part of the condition, ($a_{i-1}-a_{i+1} \\le |c|$ or $a_{i-1} = a_i$ or $a_i = a_{i+1}$). Here, $a_{i-1}$ and $a_{i+1}$ actually refer to the closest unused elements of $a$, which are $a_i$'s left and right pointers in the linked list, respectively. Each time, we query the set for its smallest element $a_i$ that satisfies $a_i \\ge b_{k-1}-|c|$. If this element does not exist, then we take $a_i$ to be the largest element in the linked list. Then, we set $b_k := a_i$, delete $a_i$ from the linked list, and update the set with the left and right elements of $a_i$ if they now satisfy the condition. One small observation is that in the answer $b$, $b_1 = a_1$ and $b_n = a_n$. This may simplify the implementation since it means that some edge cases of $(*)$ actually don't need to be checked. It is also actually not necessary to check the $a_{i-1} = a_i$ or $a_i = a_{i+1}$ condition. The time complexity is $\\mathcal{O}(n \\log n)$. The case $n \\le 2$ is trivial. In the following, we only consider the case $c < 0$ and $n \\ge 3$. The case $c \\ge 0$ follows by symmetry (reverse the array). Let $c' := -c$ to reduce confusion with negative signs, and WLOG let $a_1 \\ge a_2 \\ge \\dots \\ge a_n$. Instead of considering $\\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|$, consider a permutation $b$ that minimizes the augmented cost $|b_1-b_n-c|+\\sum_{i=1}^{n-1} |b_{i+1}-b_i-c|$. By circular symmetry, WLOG rotate $b$ so that $b_n = a_n$. We will perform a sequence of steps to sort $b$ in nonincreasing order without ever increasing the augmented cost. Consider looking at $b_{n-1},b_{n-2},\\dots,b_1$ in order, such that when we look at $b_k$, we have the invariant that $b_{k+1} \\ge b_{k+2} \\ge \\dots \\ge b_n = a_n$. If $b_k \\ge b_{k+1}$, do not do anything. Otherwise, since $b_k \\ge a_n = b_n$, there exists an index $k+1 \\le i < n$ such that $b_i \\ge b_k \\ge b_{i+1}$. Consider deleting $b_k$ from the array and reinserting it between index $i$ and $i+1$. We have the following results: Claim 1: Deleting $b_k$ decreases the augmented cost by at least $c'$. Proof: Let $x := b_{k-1}-b_k$ (or $b_n-b_1$ if $k = 1$) and $y := b_{k+1}-b_k \\ge 0$. We need to check that $|x-y-c'|+c' \\le |x-c'|+|-y-c'|$, which follows from $|x-c'|+|-y-c'| = |x-c'|+y+c' \\ge |x-y-c'|+c'$ (we use the triangle inequality in the last step). Note that equality holds if and only if $x-c' \\le 0$, i.e. $b_{k-1}-b_k \\le c'$. Claim 2: Reinserting $b_k$ increases the augmented cost by at most $c'$. Proof: Let $x := b_i-b_k \\ge 0$ and $y := b_k-b_{i+1} \\ge 0$. We need to check that $|x-c'|+|y-c'| \\le |x+y-c'|+c'$. Consider four cases: If $x,y \\ge c'$, then $|x-c'|+|y-c'| = x+y-2c' < (x+y-c')+c' = |x+y-c'|+c'$. If $x \\ge c', y \\le c'$, then $|x-c'|+|y-c'| = x-y \\le (x+y-c')+c' = |x+y-c'|+c'$. If $x \\le c', y \\ge c'$, then $|x-c'|+|y-c'| = y-x \\le (x+y-c')+c' = |x+y-c'|+c'$. If $x,y \\le c'$, then $|x-c'|+|y-c'| = 2c'-x-y = (c'-x-y)+c' \\le |x+y-c'|+c'$. Note that equality holds if and only if $x = 0$ or $y = 0$ or $c'-x-y \\ge 0$, i.e. $b_i-b_{i+1} \\le c'$ or $b_i = b_k$ or $b_k = b_{i+1}$. Therefore, each step does not increase the augmented cost. After all the steps, $b$ will be sorted in nonincreasing order. Therefore, the smallest possible augmented cost is $|a_1-a_n-c|+\\sum_{i=1}^{n-1} |a_{i+1}-a_i-c|$. Now note that $|a_1-a_n-c| = (a_1-a_n)+c'$ is the maximum possible value of $|b_1-b_n-c|$! This means that the minimum cost cannot be less than the minimum augmented cost minus $(a_1-a_n)+c'$. It follows that the minimum cost is obtained by sorting $a$ in nonincreasing order, and furthermore, any optimal permutation $b$ satisfies $b_1 = a_1$ and $b_n = a_n$. Furthermore, suppose we have fixed $b_1,\\dots,b_k$ and also $b_n = a_n$. By a similar argument (looking at $b_{n-1},\\dots,b_{k+1}$ and reinserting them to the right), one optimal permutation $b_{k+1},\\dots,b_n$ of the remaining elements is to sort them in nonincreasing order. Our greedy algorithm can only reach states where the optimal remaining permutation satisfies $b_n = a_n$, so it is correct. Note that condition $(*)$ is similar to equality being achieved in both claim 1 and claim 2. It follows that $(*)$ is equivalent to ($a_{i-1}-a_{i+1} \\le |c|$ or $a_{i-1} = a_i$ or $a_i = a_{i+1}$) and ($b_{k-1}-a_i \\le |c|$) as claimed.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef pair<int,int> pii;\n#define mp make_pair\n\nint a[200000],b[200000],l[200000],r[200000];\nset<pii> S;\nint main() {\n    int i;\n    int t,n,c;\n    scanf(\"%d\",&t);\n    while (t--) {\n        scanf(\"%d %d\",&n,&c);\n        for (i = 0; i < n; i++) scanf(\"%d\",&a[i]);\n        if (c >= 0) {\n            sort(a,a+n);\n            for (i = 0; i < n; i++) printf(\"%d%c\",a[i],(i == n-1) ? '\\n':' ');\n            continue;\n        }\n\n        sort(a,a+n,greater<int>());\n        b[0] = a[0];\n        for (i = 0; i < n; i++) l[i] = (i+n-1) % n,r[i] = (i+1) % n;\n        for (i = 2; i < n-1; i++) {\n            if (a[l[i]]-a[r[i]] <= -c) S.insert(mp(a[i],i));\n        }\n        for (i = 1; i < n; i++) {\n            int u;\n            auto it = S.lower_bound(mp(b[i-1]+c,0));\n            if (it == S.end()) u = r[0];\n            else u = it->second,S.erase(it);\n            b[i] = a[u];\n            int x = l[u],y = r[u];\n            r[x] = y,l[y] = x;\n            S.erase(mp(a[x],x)),S.erase(mp(a[y],y));\n            if ((x != 0) && (l[x] != 0) && (r[x] != 0) && (a[l[x]]-a[r[x]] <= -c)) S.insert(mp(a[x],x));\n            if ((y != 0) && (l[y] != 0) && (r[y] != 0) && (a[l[y]]-a[r[y]] <= -c)) S.insert(mp(a[y],y));\n        }\n        for (i = 0; i < n; i++) printf(\"%d%c\",b[i],(i == n-1) ? '\\n':' ');\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1844",
    "index": "G",
    "title": "Tree Weights",
    "statement": "You are given a tree with $n$ nodes labelled $1,2,\\dots,n$. The $i$-th edge connects nodes $u_i$ and $v_i$ and has an unknown positive integer weight $w_i$. To help you figure out these weights, you are also given the distance $d_i$ between the nodes $i$ and $i+1$ for all $1 \\le i \\le n-1$ (the sum of the weights of the edges on the simple path between the nodes $i$ and $i+1$ in the tree).\n\nFind the weight of each edge. If there are multiple solutions, print any of them. If there are no weights $w_i$ consistent with the information, print a single integer $-1$.",
    "tutorial": "Let $x_u$ be the sum of the weights of the edges on the path from node $1$ to node $u$. We know that $x_1 = 0$ and $x_i + x_{i+1} - 2x_{\\text{lca}(i,i+1)} = d_i$ for all $1 \\le i \\le n-1$. This is a system of $n$ linear equations in $n$ variables. As $x_u$ should be integers, let's first solve this system modulo $2$. The $2x_{\\text{lca}(i,i+1)}$ term disappears, so we just have $x_{i+1} \\equiv d_i - x_i \\pmod 2$. Starting from $x_1 \\equiv 0 \\pmod 2$, this uniquely determines $x_2 \\pmod 2$, then $x_3 \\pmod 2$, and so on. Now that we know $x_1,\\dots,x_n \\pmod 2$, write $x_u = 2x_u' + b_u$ where $b_u$ is the first bit of $x_u$. We can rewrite our system of equations as $(2x_i'+b_i) + (2x_{i+1}'+b_{i+1}) - 2(2x_{\\text{lca}(i,i+1)}'+b_{\\text{lca}(i,i+1)}) = d_i$ $\\iff x_i' + x_{i+1}' - 2x_{\\text{lca}(i,i+1)}' = \\frac{1}{2}\\left(d_i-b_i-b_{i+1}+2b_{\\text{lca}(i,i+1)}\\right)$ which has the same form as the original system. Thus we can repeat this process to find $x_u' \\pmod 2$ (giving $x_u \\pmod 4$), then $x_u \\pmod 8$, and so on. Note that each bit of $x_u$ is uniquely determined. If a solution exists, it satisfies $0 \\le x_u \\le n \\cdot \\max d_i \\le 10^{17}$ for all $u$, so it suffices to repeat this process until we have found the first $57$ bits of $x_u$. Finally, we check that these $57$ bits correspond to a valid solution where all the original weights are positive. The time complexity is $\\mathcal{O}(n(\\log n + \\log \\max d_i))$, if the $\\text{lca}(i,i+1)$ are precomputed. Remark: This idea is related to the method of Hensel Lifting.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int LLI;\ntypedef vector<pair<int,int> > vpii;\n#define mp make_pair\n#define pb push_back\n\nvpii adjList[100000];\nLLI d[100000];\nint parent[100000][17],parenti[100000],depth[100000];\nint doDFS(int u,int p,int d) {\n    parent[u][0] = p,depth[u] = d;\n    for (auto [v,i]: adjList[u]) {\n        if (v != p) parenti[v] = i,doDFS(v,u,d+1);\n    }\n    return 0;\n}\nint logn;\nint lca(int u,int v) {\n    int i;\n    if (depth[u] < depth[v]) swap(u,v);\n    for (i = logn-1; i >= 0; i--) {\n        if ((parent[u][i] != -1) && (depth[parent[u][i]] >= depth[v])) u = parent[u][i];\n    }\n    if (u == v) return u;\n    for (i = logn-1; i >= 0; i--) {\n        if (parent[u][i] != parent[v][i]) u = parent[u][i],v = parent[v][i];\n    }\n    return parent[u][0];\n}\nint lcas[100000],bit[100000];\nLLI ans[100000],w[100000];\nint main() {\n    int i;\n    int n,u,v;\n    scanf(\"%d\",&n);\n    for (i = 0; i < n-1; i++) {\n        scanf(\"%d %d\",&u,&v);\n        u--,v--;\n        adjList[u].pb(mp(v,i));\n        adjList[v].pb(mp(u,i));\n    }\n    for (i = 0; i < n-1; i++) scanf(\"%lld\",&d[i]);\n\n    int j;\n    doDFS(0,-1,0);\n    for (i = 1; (1 << i) < n; i++) {\n        for (j = 0; j < n; j++) {\n            if (parent[j][i-1] != -1) parent[j][i] = parent[parent[j][i-1]][i-1];\n            else parent[j][i] = -1;\n        }\n    }\n    logn = i;\n    for (i = 0; i < n-1; i++) lcas[i] = lca(i,i+1);\n\n    for (i = 0; i < 57; i++) {\n        bit[0] = 0;\n        for (j = 0; j < n-1; j++) bit[j+1] = bit[j]^(d[j] & 1);\n        for (j = 0; j < n-1; j++) d[j] = (d[j]-bit[j]-bit[j+1]+2*bit[lcas[j]])/2;\n        for (j = 0; j < n; j++) ans[j] |= ((LLI) bit[j] << i);\n    }\n    for (i = 0; i < n-1; i++) {\n        if (d[i] != 0) {\n            printf(\"-1\\n\");\n            return 0;\n        }\n    }\n    for (i = 1; i < n; i++) {\n        w[parenti[i]] = ans[i]-ans[parent[i][0]];\n        if (w[parenti[i]] <= 0) {\n            printf(\"-1\\n\");\n            return 0;\n        }\n    }\n    for (i = 0; i < n-1; i++) printf(\"%lld\\n\",w[i]);\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "implementation",
      "math",
      "matrices",
      "number theory",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1844",
    "index": "H",
    "title": "Multiple of Three Cycles",
    "statement": "An array $a_1,\\dots,a_n$ of length $n$ is initially all blank. There are $n$ updates where one entry of $a$ is updated to some number, such that $a$ becomes a permutation of $1,2,\\dots,n$ after all the updates.\n\nAfter each update, find the number of ways (modulo $998\\,244\\,353$) to fill in the remaining blank entries of $a$ so that $a$ becomes a permutation of $1,2,\\dots,n$ and all cycle lengths in $a$ are multiples of $3$.\n\nA permutation of $1,2,\\dots,n$ is an array of length $n$ consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. A cycle in a permutation $a$ is a sequence of pairwise distinct integers $(i_1,\\dots,i_k)$ such that $i_2 = a_{i_1},i_3 = a_{i_2},\\dots,i_k = a_{i_{k-1}},i_1 = a_{i_k}$. The length of this cycle is the number $k$, which is a multiple of $3$ if and only if $k \\equiv 0 \\pmod 3$.",
    "tutorial": "The partially formed permutation is composed of several paths and cycles, and only the length of each path/cycle modulo $3$ matters. We can use a DSU to track the number of paths/cycles of each length $\\pmod 3$. If at any point a cycle whose length is not $\\equiv 0 \\pmod 3$ is formed, the answer is $0$. Thus, the problem reduces to the following: Given $a$ $1$s, $b$ $2$s, and $c$ $0$s, how many ways are there to build a permutation on these objects so that each cycle sums to a multiple of $3$? Let $f(a,b,c)$ be the answer to this problem. Note that $f(a,b,c) = (a+b+c)f(a,b,c-1)$ for $c > 0$, as there are $a+b+c$ ways to choose the next object of any $0$, and after merging this $0$ with its next object, there are $f(a,b,c-1)$ ways to build a permutation on the remaining objects. Repeatedly applying this recurrence gives $f(a,b,c) = \\frac{(a+b+c)!}{(a+b)!}f(a,b,0)$, so we can eliminate the $c$ parameter and multiply the answer by a factorial and inverse factorial in the end. Now let $f(a,b) = f(a,b,0)$. We have not one, but two recurrence relations $f(a,b)$ satisfies: $f(a,b) = bf(a-1,b-1,1) + (a-1)f(a-2,b+1) = b(a+b-1)f(a-1,b-1) + (a-1)f(a-2,b+1)$ when $a > 0$ (consider the next object of any $1$) $f(a,b) = af(a-1,b-1,1) + (b-1)f(a+1,b-2) = a(a+b-1)f(a-1,b-1) + (b-1)f(a+1,b-2)$ when $b > 0$ (consider the next object of any $2$) The key idea now is that because we have two equations relating the four values $f(a,b),f(a-1,b-1),f(a+2,b-1),f(a-1,b+2)$, given any two of these values, we can solve for the other two. For example, if we know $f(a,b)$ and $f(a-1,b-1)$, we can calculate $f(a-2,b+1) = \\frac{f(a,b)-b(a+b-1)f(a-1,b-1)}{a-1}$. Also note that the queried pairs $(a,b)$ can be visualized as a walk in the plane, where each pair does not differ from the previous pair by much. By using these recurrences carefully, it is possible to calculate $f(a,b)$ for all queries $(a,b)$ while calculating only $\\mathcal{O}(n)$ values of $f$. The details can be tricky. The author's solution does the following: First, reverse the order of the updates, possibly adding dummy updates if a cycle whose length is not $\\equiv 0 \\pmod 3$ is created early. Then we need to find $f(a_i,b_i)$ for a sequence of pairs $(a_1,b_1),(a_2,b_2),\\dots$ where $(a_1,b_1) = (0,0)$ and $(a_{i+1},b_{i+1})$ is one of $(a_i,b_i)$, $(a_i-1,b_i+2)$, $(a_i+2,b_i-1)$, or $(a_i+1,b_i+1)$ for all $i$. We loop through $i$ in order, maintaining two values $u := f(a_i,b_i)$ and $v := f(a_i+1,b_i+1)$ at all times. Whenever we need a transition of the form $(a_i,b_i) \\to (a_i-1,b_i+2)$, we use the recurrence $f(a_i+1,b_i+1) = (b_i+1)(a_i+b_i+1)f(a_i,b_i) + a_if(a_i-1,b_i+2)$ to solve for $f(a_i-1,b_i+2)$ (the new value of $u$), then use the recurrence $f(a_i,b_i+3) = a_i(a_i+b_i+2)f(a_i-1,b_i+2) + (b_i+2)f(a_i+1,b_i+1)$ to find $f(a_i,b_i+3)$ (the new value of $v$). The $(a_i,b_i) \\to (a_i+2,b_i-1)$ transition is similar. For $(a_i,b_i) \\to (a_i+1,b_i+1)$ transitions, do both of the previous types of transitions once. The time complexity of the main part of the problem is $\\mathcal{O}(N)$. The overall time complexity is $\\mathcal{O}(N\\alpha(N))$, dominated by the DSU operations. Remark 1: Since $1$s and $2$s behave symmetrically, $f(a,b,c) = f(b,a,c)$. Remark 2: The exponential generating function for $f(a,b)$ is $\\sum_{a \\ge 0}\\sum_{b \\ge 0} \\frac{f(a,b)}{a!b!}x^ay^b = (1-(x^3+3xy+y^3))^{-1/3}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int LLI;\n#define MOD 998244353\n\nint parent[300000],siz[300000];\nint find(int n) {\n    if (parent[n] != n) parent[n] = find(parent[n]);\n    return parent[n];\n}\nint queries[600000][3],ans[600000];\nint fact[300000],invfact[300000],invn[300000];\nint inv(int n) {\n    int e = MOD-2,r = 1;\n    while (e > 0) {\n        if (e & 1) r = ((LLI) r*n) % MOD;\n        e >>= 1;\n        n = ((LLI) n*n) % MOD;\n    }\n    return r;\n}\nint main() {\n    int i;\n    int n,x,y,bad = 1e9;\n    int num[3];\n    scanf(\"%d\",&n);\n    for (i = 0; i < n; i++) parent[i] = i,siz[i] = 1;\n    num[0] = 0,num[1] = n,num[2] = 0;\n    for (i = 0; i < n; i++) {\n        scanf(\"%d %d\",&x,&y);\n        x--,y--;\n        if (find(x) != find(y)) {\n            num[siz[find(x)] % 3]--;\n            num[siz[find(y)] % 3]--;\n            siz[find(y)] += siz[find(x)];\n            parent[find(x)] = find(y);\n            num[siz[find(y)] % 3]++;\n        }\n        else if ((siz[find(x)] % 3) == 0) num[0]--;\n        else if (bad == 1e9) bad = i;\n        copy(num,num+3,queries[i]);\n    }\n\n    fact[0] = 1;\n    for (i = 1; i < n; i++) fact[i] = ((LLI) i*fact[i-1]) % MOD;\n    invfact[n-1] = inv(fact[n-1]);\n    for (i = n-2; i >= 0; i--) invfact[i] = ((LLI) (i+1)*invfact[i+1]) % MOD;\n    for (i = 1; i < n; i++) invn[i] = ((LLI) invfact[i]*fact[i-1]) % MOD;\n\n    int m = n;\n    while (num[1]+num[2] > 0) {\n        int a = (num[1] > 0) ? 1:2;\n        num[a]--;\n        int b = (num[1] > 0) ? 1:2;\n        num[b]--;\n        num[(a+b) % 3]++;\n        copy(num,num+3,queries[m++]);\n    }\n    x = 1,y = 1;\n    int u = 1,v = 8;\n    auto f = [&]() {\n        assert(x > 0);\n        int nu = (((v-(((LLI) (y+1)*(x+y+1)) % MOD)*u) % MOD)*invn[x]) % MOD;\n        int nv = ((((LLI) x*(x+y+2)) % MOD)*nu+(LLI) (y+2)*v) % MOD;\n        x--,y += 2,u = nu,v = nv;\n        if (u < 0) u += MOD;\n        if (v < 0) v += MOD;\n    };\n    auto g = [&]() {\n        assert(y > 0);\n        int nu = (((v-(((LLI) (x+1)*(x+y+1)) % MOD)*u) % MOD)*invn[y]) % MOD;\n        int nv = ((((LLI) y*(x+y+2)) % MOD)*nu+(LLI) (x+2)*v) % MOD;\n        x += 2,y--,u = nu,v = nv;\n        if (u < 0) u += MOD;\n        if (v < 0) v += MOD;\n    };\n    for (i = m-1; i >= 0; i--) {\n        int a = queries[i][1],b = queries[i][2],c = queries[i][0];\n        if ((a == 0) && (b == 0)) ans[i] = 1;\n        else if ((a == x) && (b == y)) ans[i] = u;\n        else if ((a == x-1) && (b == y+2)) f(),ans[i] = u;\n        else if ((a == x+2) && (b == y-1)) g(),ans[i] = u;\n        else if ((a == x+1) && (b == y+1)) {\n            if (x > 0) f(),g(),ans[i] = u;\n            else g(),f(),ans[i] = u;\n        }\n        else assert(0);\n        ans[i] = ((LLI) ans[i]*fact[a+b+c]) % MOD;\n        ans[i] = ((LLI) ans[i]*invfact[a+b]) % MOD;\n    }\n    for (i = 0; i < n; i++) printf(\"%d\\n\",(i >= bad) ? 0:ans[i]);\n\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "dsu",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1845",
    "index": "A",
    "title": "Forbidden Integer",
    "statement": "You are given an integer $n$, which you want to obtain. You have an unlimited supply of every integer from $1$ to $k$, except integer $x$ (there are no integer $x$ at all).\n\nYou are allowed to take an arbitrary amount of each of these integers (possibly, zero). Can you make the sum of taken integers equal to $n$?\n\nIf there are multiple answers, print any of them.",
    "tutorial": "The problem is about considering the least amount of cases possible. I propose the following options. If $x \\neq 1$, then you can always print $n$ ones. So the answer is YES. If $k = 1$, then no integer is available, so the answer is NO. If $k = 2$, then only $2$ is available, so you can only collect even $n$. So if it's odd, the answer is NO. Otherwise, you can always collect $n$ with the following construction: if $n$ is even then take $2$, otherwise take $3$. Then take $\\lfloor \\frac{n}{2} \\rfloor - 1$ twos. You can see that an even $n$ only uses twos, so it fits the previous check. If it's odd, then $k$ is at least $3$, so $3$ is allowed to take. Overall complexity: $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn, k, x = map(int, input().split())\n\tif x != 1:\n\t\tprint(\"YES\")\n\t\tprint(n)\n\t\tprint(*([1] * n))\n\telif k == 1 or (k == 2 and n % 2 == 1):\n\t\tprint(\"NO\")\n\telse:\n\t\tprint(\"YES\")\n\t\tprint(n // 2)\n\t\tprint(*([3 if n % 2 == 1 else 2] + [2] * (n // 2 - 1)))",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1845",
    "index": "B",
    "title": "Come Together",
    "statement": "Bob and Carol hanged out with Alice the whole day, but now it's time to go home. Alice, Bob and Carol live on an infinite 2D grid in cells $A$, $B$, and $C$ respectively. Right now, all of them are in cell $A$.\n\nIf Bob (or Carol) is in some cell, he (she) can move to one of the neighboring cells. Two cells are called neighboring if they share a side. For example, the cell $(3, 5)$ has four neighboring cells: $(2, 5)$, $(4, 5)$, $(3, 6)$ and $(3, 4)$.\n\nBob wants to return to the cell $B$, Carol — to the cell $C$. Both of them want to go along the shortest path, i. e. along the path that consists of the minimum possible number of cells. But they would like to walk together as well.\n\nWhat is the maximum possible number of cells that Bob and Carol can walk together if each of them walks home using one of the shortest paths?",
    "tutorial": "Let $d(P_1, P_2)$ be the Manhattan distance between points $P_1 = (x_1, y_1)$ and $P_2 = (x_2, y_2)$. Then $d(P_1, P_2) = |x_1 - x_2| + |y_1 - y_2|$. Note that if you are going from $A$ to $B$ (or to $C$) along the shortest path, the Manhattan distance will be decreasing with each move. So Bob and Carol can walk together as along as they find the next cell that is closer to both $B$ and $C$. Now note that if they are in the bounding box of cells $B$ and $C$ then there are no such \"next cell\", since $d(X, B) + d(X, C)$ is constant and equal to $d(A, B)$ if $X$ is in the bounding box. In other words, Bob and Carol can walk together until they reach some cell $X$ inside the bounding box, where they split up. Finally, let's look at the total distance they will walk: from one side it's $d(A, B) + d(A, C)$. But from the other side it's $2 \\cdot d(A, X) + d(X, B) + d(X, C)$. So, $d(A, X) = \\frac{d(A, B) + d(A, C) - (d(X, B) + d(X, C))}{2}$ $\\frac{d(A, B) + d(A, C) - d(B, C)}{2} + 1$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\npt A, B, C;\n\ninline bool read() {\n\tif(!(cin >> A.x >> A.y))\n\t\treturn false;\n\tcin >> B.x >> B.y;\n\tcin >> C.x >> C.y;\n\treturn true;\n}\n\nint dist(const pt &A, const pt &B) {\n\treturn abs(A.x - B.x) + abs(A.y - B.y);\n}\n\ninline void solve() {\n\tcout << (dist(A, B) + dist(A, C) - dist(B, C)) / 2 + 1 << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1845",
    "index": "C",
    "title": "Strong Password",
    "statement": "Monocarp finally got the courage to register on ForceCoders. He came up with a handle but is still thinking about the password.\n\nHe wants his password to be as strong as possible, so he came up with the following criteria:\n\n- the length of the password should be exactly $m$;\n- the password should only consist of digits from $0$ to $9$;\n- the password should not appear in the password database (given as a string $s$) as a \\textbf{subsequence} (not necessarily contiguous).\n\nMonocarp also came up with two strings of length $m$: $l$ and $r$, both consisting only of digits from $0$ to $9$. He wants the $i$-th digit of his password to be between $l_i$ and $r_i$, inclusive.\n\nDoes there exist a password that fits all criteria?",
    "tutorial": "Consider the naive solution. You iterate over all password options that fit the criteria on $l$ and $r$ and check if they appear in $s$ as a subsequence. That check can be performed greedily: find the first occurrence of the first digit of the password, then find the first occurrence after it of the second digit of the password, and so on. If all digits are found, then it's present. Otherwise, it isn't. Notice how the checks from the $i$-th digit onwards only depend on the position of the $(i-1)$-st digit. Moreover, to have a lower probability to find these digits, we want the $(i-1)$-st digit to be as much to the right as possible. That leads us to the greedy solution to the full problem. Iterate over the first digit and choose the one that appears as much to the right as possible. Then the same for the second digit, and so on. If any digit is not found in the string after the starting position of the check, then the password that starts with the chosen digits is strong. So far, the solution sounds like $O(nmD)$, where $D$ is the number of digits (equal to $10$). Which is actually fine under these constraints, but we can do better. One option is to precalculate something to help us find the next occurrence of each digit. For example, that can be an array of positions of each digit. Then we can use lower_bound on it to find the next one. That would be $O(n + D + mD \\log n)$. Alternatively, you can calculate an array $\\mathit{next}[i][j]$ that stores the next occurrence of digit $j$ from position $i$. It's possible to calculate $\\mathit{next}[i]$ from $\\mathit{next}[i + 1]$. Notice that only $\\mathit{next}[i][s[i]]$ changes. So you can copy $\\mathit{next}[i + 1]$ into $\\mathit{next}[i]$ and set $\\mathit{next}[i][s[i]] = i$. Now you can just query the array by looking into the corresponding cells. That would be $O(nD + mD)$. Finally, let's analyze the complexity of the linear search better. So, for each digit, actually run a while loop that searches the string until it encounters that letter. We proposed that it is $O(nmD)$. Notice that if some iteration of the loop for the $i$-th digit passes a position $x$, then the digits from the $(i+1)$-st onwards won't look into it. So, such position can only be checked in $O(D)$ loops (all loops for the current digit). Thus, each of $n$ positions can only be accessed $O(D)$ times, making the solution $O(m + nD)$, which makes it the fastest of all our options. That is basically the same analysis as two pointers. $O(m)$ comes from the outer loop over digits that you can't really get rid of. However, you can say that $m \\le n$ ($m > n$ can be solved in $O(1)$), and call the solution $O(nD)$. Overall complexity: $O(m + nD)$ for each testcase.",
    "code": "import sys\nfor _ in range(int(sys.stdin.readline())):\n\ts = [int(c) for c in sys.stdin.readline().strip()]\n\tn = len(s)\n\tm = int(sys.stdin.readline())\n\tl = sys.stdin.readline()\n\tr = sys.stdin.readline()\n\tmx = 0\n\tfor i in range(m):\n\t\tli = int(l[i])\n\t\tri = int(r[i])\n\t\tnmx = mx\n\t\tfor c in range(li, ri + 1):\n\t\t\tcur = mx\n\t\t\twhile cur < n and s[cur] != c:\n\t\t\t\tcur += 1\n\t\t\tnmx = max(nmx, cur)\n\t\tmx = nmx + 1\n\tprint(\"YES\" if mx > n else \"NO\")",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1845",
    "index": "D",
    "title": "Rating System",
    "statement": "You are developing a rating system for an online game. Every time a player participates in a match, the player's rating changes depending on the results.\n\nInitially, the player's rating is $0$. There are $n$ matches; after the $i$-th match, the rating change is equal to $a_i$ (the rating increases by $a_i$ if $a_i$ is positive, or decreases by $|a_i|$ if it's negative. There are no zeros in the sequence $a$).\n\nThe system has an additional rule: for a fixed integer $k$, if a player's rating has reached the value $k$, it will never fall below it. Formally, if a player's rating at least $k$, and a rating change would make it less than $k$, then the rating will decrease \\textbf{to exactly $k$}.\n\nYour task is to determine the value $k$ in such a way that the player's rating after all $n$ matches is the maximum possible (among all integer values of $k$). If there are multiple possible answers, you can print any of them.",
    "tutorial": "Let's fix some $k$ and look at the first and the last moment when the rating should fall below $k$, but doesn't. After such moments, the rating is equal to $k$. So we can \"delete\" all changes (array elements) between those moments. And the remaining changes (to the left from the first moment and to the right from the last moment) can be considered without any additional constraints (the value of $k$ doesn't affect those changes). Using this fact, we can see that the total rating is not greater than the sum of the whole array minus some continuous segment. So the maximum possible final rating doesn't exceed the sum of the array minus the minimum sum segment (this segment can be empty, if all elements are positive). In fact, there is always such $k$ that provides such rating. Let the minimum sum segment be $[l; r]$, then $k$ is equal to the prefix sum from $1$-st to $(l-1)$-th positions of the array. The only remaining question is: why the rating after $r$-th match is equal to $k$? It can't fall below $k$ (since the rating is at least $k$ already); and if it is greater than $k$, then there is a positive suffix of the segment $[l; r]$, so we can remove it, and the sum of the segment would decrease. Which means the segment $[l; r]$ is not minimum sum segment, which contradicts the previous statement. So the rating after $r$-th match is equal to $k$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing li = long long;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    li delta = 0, ans = 0;\n    li sum = 0, mx = 0;\n    for (int i = 0; i < n; ++i) {\n      li x; cin >> x;\n      sum += x;\n      mx = max(mx, sum);\n      if (sum - mx < delta) {\n        delta = sum - mx;\n        ans = mx;\n      }\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "dsu",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1845",
    "index": "E",
    "title": "Boxes and Balls",
    "statement": "There are $n$ boxes placed in a line. The boxes are numbered from $1$ to $n$. Some boxes contain one ball inside of them, the rest are empty. At least one box contains a ball and at least one box is empty.\n\nIn one move, you \\textbf{have to} choose a box with a ball inside and an adjacent empty box and move the ball from one box into another. Boxes $i$ and $i+1$ for all $i$ from $1$ to $n-1$ are considered adjacent to each other. Boxes $1$ and $n$ are \\textbf{not adjacent}.\n\nHow many different arrangements of balls exist after \\textbf{exactly} $k$ moves are performed? Two arrangements are considered different if there is at least one such box that it contains a ball in one of them and doesn't contain a ball in the other one.\n\nSince the answer might be pretty large, print its remainder modulo $10^9+7$.",
    "tutorial": "Consider a harder problem. For each $k'$ from $0$ to $k$, what's the number of arrangements that have $k'$ as the smallest number of operations needed that obtain them? That would help us solve the full problem. You just have to sum up the answer for $k'$ such that they have the same parity as $k$ (since, once the arrangement is obtained, you can perform two moves on it and change nothing). Turns out, calculating the smallest number of operations for a fixed arrangement is not that hard. Let the initial arrangement have balls in boxes $c_1, c_2, \\dots, c_t$ for some $t$; the fixed arrangement have balls in boxes $d_1, d_2, \\dots, d_t$. Then the first ball in the fixed arrangement has to come from the box of the first ball in the initial one. And so on. So the answer is at least $\\sum\\limits_{i=1}^t |c_t - d_t|$. That estimate can be achieved. Just move the balls one by one from left to right. So that amount is actually the smallest possible. That can lead to a dynamic programming solution. Following this construction, let $\\mathit{dp}[i][j][k]$ be the number of ways to fill the first $i$ boxes with $j$ balls such that the smallest number of operations to move the first $j$ balls of the initial arrangement into their new boxes is $k$. The transitions are trivial. Either leave the $i$-th (all $0$-indexed) box empty and go to $\\mathit{dp}[i+1][j][k]$ or put a ball into it and go to $\\mathit{dp}[i+1][j+1][k + |i - c_j|]$. The answer will be in $\\mathit{dp}[n][t][k']$ for all $k'$ of the same parity as $k$. That solution is $O(n^2k)$ that is supposedly too much (although unfortunately can be squeezed if you try hard enough). That solution has surprisingly little to do with the full one but gives us some insight into the problem. For a faster solution, let's change the way we calculate the smallest number of operations. What is exactly $|c_t - d_t|$? Let $c_t > d_t$. Then on its path the ball crosses the spaces between boxes $c_t$ and $c_t-1$, $c_t-1$ and $c_t-2$, so on until $d_t+1$ and $d_t$. The amount is exactly $(c_t - d_t)$. Thus, we could instead calculate the number of balls that move across each space between the boxes along their paths and add up the values. Now it's some sort of balance. We could also denote balls going to the right as positive values and going to the left as negative values. Notice how if some ball moves from a box $i$ to a box $i-1$ in the optimal construction, then there is no ball that moves from $i-1$ to $i$. Just because the balls never cross each other paths. So the absolute value of the balance is still what we have to add up. Intuitively, the value for space between boxes $i$ and $i+1$ is equal to the signed difference between the initial number of balls to the left of it and the one in the current arrangement. If the numbers are different, then we move exactly this amount of ball from one side to another. Now we can pack it into another dynamic programming. Let $\\mathit{dp}[i][j][k]$ be the number of ways to fill the first $i$ boxes, such that the current balance is $j$ and the smallest number of operations to achieve that is $k$. The transitions are the following. If we place a ball into box $i$, the balance changes to $j + 1 - a_i$ ($a_i$ is whether there was a ball in box $i$ initially) and $|j + 1 - a_i|$ gets added to $k$. If we don't place a ball, the balance changes to $j - a_i$ and $|j - a_i|$ gets added to $k$. Notice that at the end the balance will be $0$ if and only if we placed as many boxes as there were initially. So, the answer will be in $\\mathit{dp}[n][0][k']$ for all $k'$ of the same parity as $k$. That solution is still $O(n^2k)$ and even worse in the way that $j$ can range from $-n$ to $n$, doubling the runtime. However, notice how $j$ can't change by more than $1$ on each step. At the same time, $|j|$ always gets added to $k$. Thus, to make $j$ equal to $0$ at the end, we would have to add $|j| + (|j| - 1) + (|j| - 2) + \\dots + 1$ to $k$. And since $k$ can't exceed $1500$, $|j|$ actually can't exceed $55$ (more or less $O(\\sqrt{k})$). So, that solution can be optimized to $O(nk^{1.5})$ by reducing the second dimension of the dynamic programming. In order to store values from $-x$ to $x$ in an array, shift them up by $x$. So the values become from $0$ to $2x$. In order to avoid $O(nk^{1.5})$ memory, instead of storing all $n$ layers of the dp, only store the current and the next one. That will make it $O(k^{1.5})$ memory. Overall complexity: $O(nk^{1.5})$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nconst int MOD = int(1e9) + 7;\n\nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\treturn a;\n}\n\nint main() {\n\tint n, k;\n\tscanf(\"%d%d\", &n, &k);\n\tvector<int> a(n);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tint lim = 1;\n\twhile (lim * (lim + 1) < k * 2) ++lim;\n\tvector<vector<vector<int>>> dp(2, vector<vector<int>>(2 * lim + 1, vector<int>(k + 1)));\n\tdp[0][lim][0] = 1;\n\tforn(ii, n){\n\t\tint i = ii & 1;\n\t\tint ni = i ^ 1;\n\t\tdp[ni] = vector<vector<int>>(2 * lim + 1, vector<int>(k + 1));\n\t\tforn(j, 2 * lim + 1) forn(t, k + 1) if (dp[i][j][t]){\n\t\t\tforn(z, 2){\n\t\t\t\tint nj = j + z - a[ii];\n\t\t\t\tint nt = t + abs(nj - lim);\n\t\t\t\tif (nt <= k) dp[ni][nj][nt] = add(dp[ni][nj][nt], dp[i][j][t]);\n\t\t\t}\n\t\t}\n\t}\n\tint ans = 0;\n\tfor (int t = k & 1; t <= k; t += 2)\n\t\tans = add(ans, dp[n & 1][lim][t]);\n\tprintf(\"%d\\n\", ans);\n\treturn 0;\n}",
    "tags": [
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1845",
    "index": "F",
    "title": "Swimmers in the Pool",
    "statement": "There is a pool of length $l$ where $n$ swimmers plan to swim. People start swimming at the same time (at the time moment $0$), but you can assume that they take different lanes, so they don't interfere with each other.\n\nEach person swims along the following route: they start at point $0$ and swim to point $l$ with constant speed (which is equal to $v_i$ units per second for the $i$-th swimmer). After reaching the point $l$, the swimmer instantly (in negligible time) turns back and starts swimming to the point $0$ with the same constant speed. After returning to the point $0$, the swimmer starts swimming to the point $l$, and so on.\n\nLet's say that some \\textbf{real} moment of time is a meeting moment if there are \\textbf{at least two} swimmers that are in the same point of the pool at that moment of time (that point may be $0$ or $l$ as well as any other real point inside the pool).\n\nThe pool will be open for $t$ seconds. You have to calculate the number of meeting moments while the pool is open. Since the answer may be very large, print it modulo $10^9 + 7$.",
    "tutorial": "Firstly, note that there are two different situations when some two swimmers meet: they either move in the same direction, or in opposite directions. Suppose, swimmers $i$ and $j$ meet while moving in the same direction. We can write some easy system of equation and get that they will meet each $\\frac{2l}{|v_i - v_j|}$ seconds. Analogically, if they meet while moving in the opposite directions, they will meet each $\\frac{2l}{v_i + v_j}$ seconds. Let's create array $w$ that will contain all possible values $|v_i \\pm v_j|$ exactly once. If $V = \\max{v_i}$ then values $w_i \\le 2V$ and we can calculate all of them using FFT fast multiplication two times: for sums $v_i + v_j$ and for differences $v_i - v_j$. Okay, we got all possible $w_i$, how to calculate the answer. For a fixed value $w_i$ meeting moments are $\\frac{2l \\cdot k}{w_i}$ for all $k$ in segment $[1, k_i]$. $k_i$ is the upper bound and can be calculated as $k_i = \\left\\lfloor \\frac{t \\cdot w_i}{2l} \\right\\rfloor$. We found that for each $w_i$ there are exactly $k_i$ meeting points, but since in one meeting moment more than two swimmers may meet we need to calculate each value $\\frac{2l \\cdot k}{w_i}$ exactly once. Note that $\\frac{2l \\cdot k_1}{w_i} = \\frac{2l \\cdot k_2}{w_j}$ iff $\\frac{k_1}{w_i} = \\frac{k_2}{w_j}$. And we can rephrase our task as following: calculate the number of unique fractions $\\frac{k}{w_i}$ where $1 \\le k \\le k_i$. The key idea here is to calculate only irreducible fractions. Suppose we have fractions $\\frac{1}{w_i}, \\frac{2}{w_i}, \\dots, \\frac{k_i}{w_i}$. Let's add to the answer only irreducible fractions among them (we will discuss how to do it later). For any other fraction $\\frac{k'}{w_i}$ $(k', w_i) = d > 1$ and $d$ is a divisor of $w_i$. If we fix some divisor $d$ of $w_i$ there will be exactly $\\left\\lfloor \\frac{k_i}{d} \\right\\rfloor$ fractions $\\frac{k'}{w_i}$ with $d | (k', w_i)$. Moreover, numerators will also form a segment $[1, \\frac{k_i}{d}]$. So, instead of calculating them now, we will just \"pass\" that task to $w_j = \\frac{w_i}{d}$. In total, we iterate $w_i$ in decreasing order, add only the number of irreducible fractions $\\frac{k}{w_i}$ to the answer. Then iterate over all divisors $d$ of $w_i$ and \"update\" value $k_j$ for $w_j = \\frac{w_i}{d}$ with value $\\frac{k_i}{d}$. How to calculate the number of irreducible fractions $\\frac{k}{w_i}$ with $1 \\le k \\le k_i$? With Möbius function, of course: $ir_i = \\sum_{d | w_i}{\\mu(d) \\left\\lfloor \\frac{k_i}{d} \\right\\rfloor}$ Both passing calculations and Möbius inversion works in $O(\\text{number of divisors}(w_i))$. And since we iterate over all $w_i \\le 2 V$, the total complexity is $O(V \\log V)$. Both FFT and next part works in $O(V \\log V)$, so the total complexity is $O(n + V \\log V)$. P.S.: If you note that if $w_j = \\frac{w_i}{d}$ then $k_j$ is always equal to $\\frac{k_i}{d}$ then you can not only simplify the part with \"passing down calculations\" but get rid of Möbius inversion at all, replacing it with Sieve-like two for-s iterations.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define forn(i, n) for(int i = 0; i < int(n); i++)\n#define sz(a) int((a).size())\n\n#define x first\n#define y second\n\ntypedef long long li;\ntypedef pair<int, int> pt;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \" \";\n\t\tout << v[i];\n\t}\n\treturn out;\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nconst int LOGN = 19;\nconst int N = (1 << LOGN) + 555;\n\nstruct comp {\n\tdouble x, y;\n\tcomp(double x = .0, double y = .0) : x(x), y(y) {}\n\tinline comp conj() { return comp(x, -y); }\n};\n\ninline comp operator +(const comp &a, const comp &b) {\n\treturn comp(a.x + b.x, a.y + b.y);\n}\n\ninline comp operator -(const comp &a, const comp &b) {\n\treturn comp(a.x - b.x, a.y - b.y);\n}\n\ninline comp operator *(const comp &a, const comp &b) {\n\treturn comp(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);\n}\n\ninline comp operator /(const comp &a, const double &b) {\n\treturn comp(a.x / b, a.y / b);\n}\n\nnamespace FFT {\n\tconst double PI = acosl(-1.0);\n\tvector<comp> w[LOGN];\n\tvector<int> rv;\n\n\tvoid precalc() {\n\t\tforn(st, LOGN) {\n\t\t\tw[st].resize(1 << st);\n\t\t\tforn(i, 1 << st) {\n\t\t\t\tdouble ang = PI / (1 << st) * i;\n\t\t\t\tw[st][i] = comp(cos(ang), sin(ang));\n\t\t\t}\n\t\t}\n\t\trv.assign(1 << LOGN, 0);\n\t    fore(i, 1, sz(rv))\n\t\t\trv[i] = (rv[i >> 1] >> 1) | ((i & 1) << (LOGN - 1));\n\t}\n\t\n\tinline void fft(comp a[N], int n, bool inv) {\n\t\tint ln = __builtin_ctz(n);\n\t\tforn(i, n) {\n\t        int ni = rv[i] >> (LOGN - ln);\n\t        if(i < ni) swap(a[i], a[ni]);\n\t    }\n\t\n\t\tfor(int st = 0; st < ln; st++) {\n\t\t\tint len = 1 << st;\n\t\t\tfor(int k = 0; k < n; k += (len << 1))\n\t\t\t\tfore(pos, k, k + len) {\n\t\t\t\t\tcomp l = a[pos];\n\t\t\t\t\tcomp r = a[pos + len] * w[st][pos - k];\n\t\t\t\t\t\n\t\t\t\t\ta[pos] = l + r;\n\t\t\t\t\ta[pos + len] = l - r;\n\t\t\t\t}\n\t\t}\n\t\n\t\tif(inv) {\n\t\t\tforn(i, n)\n\t\t\t\ta[i] = a[i] / n;\n\t\t\treverse(a + 1, a + n);\n\t\t}\n\t}\n\t\n\tcomp aa[N], bb[N], cc[N];\n\t\n\tinline void multiply(int a[N], int sza, int b[N], int szb, int c[N], int &szc) {\n\t\tint ln = 1;\n\t\twhile(ln < (sza + szb)) // sometimes works max(sza, szb)\n\t\t\tln <<= 1;\n\t\t\t\n\t\tforn(i, ln)\n\t\t\taa[i] = (i < sza ? a[i] : comp());\n\t\tforn(i, ln)\n\t\t\tbb[i] = (i < szb ? b[i] : comp());\n\t\t\t\n\t\tfft(aa, ln, false);\n\t\tfft(bb, ln, false);\n\t\t\n\t\tforn(i, ln)\n\t\t\tcc[i] = aa[i] * bb[i];\n\t\t\t\n\t\tfft(cc, ln, true);\n\t\t\n\t\tszc = ln;\n\t\tforn(i, szc)\n\t\t\tc[i] = int(cc[i].x + 0.5);\n\t}\n}\n\nconst int MOD = int(1e9) + 7;\nint norm(int a) {\n\twhile (a >= MOD)\n\t\ta -= MOD;\n\twhile (a < 0)\n\t\ta += MOD;\n\treturn a;\n}\nint mul(int a, int b) {\n\treturn int(a * 1ll * b % MOD);\n}\n\nli l, t;\nint n;\nvector<int> v;\n\ninline bool read() {\n\tif(!(cin >> l >> t >> n))\n\t\treturn false;\n\tv.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> v[i];\n\treturn true;\n}\n\nint mu[N], minD[N];\nvector<int> divs[N];\n\nvoid precalcDivs(int N) {\n\tfore (d, 1, N) {\n\t\tfor (int v = d; v < N; v += d)\n\t\t\tdivs[v].push_back(d);\n\t}\n\t\n\tmu[1] = 1;\n\tfore (d, 2, N) {\n\t\tif (minD[d] == 0)\n\t\t\tminD[d] = d;\n\t\t\n\t\tif (minD[d] != minD[d / minD[d]])\n\t\t\tmu[d] = -mu[d / minD[d]];\n\t\t\n\t\tfor (int v = 2 * d; v < N; v += d) {\n\t\t\tif (minD[v] == 0)\n\t\t\t\tminD[v] = d;\n\t\t}\n\t}\n}\n\nint vs[2][N], res[N], ps[N];\nli mxk[N];\n\ninline void solve() {\n\tFFT::precalc();\n\n\tfore (i, 0, n) {\n\t\tvs[0][v[i]] = 1;\n\t\tvs[1][v[i]] = 1;\n\t}\n\tint sz = 1 + *max_element(v.begin(), v.end());\n\t\n\tint szRes = 0;\n\tFFT::multiply(vs[0], sz, vs[1], sz, res, szRes);\n\t\n\tfore (i, 0, szRes) {\n\t\tif (!(i & 1) && vs[0][i >> 1] > 0)\n\t\t\tres[i]--;\n\t\tif (res[i] > 0) {\n\t\t\tps[i] = 1;\n\t\t}\n\t}\n\t\n\tmemset(vs[1], 0, sizeof vs[1]);\n\tfore (i, 0, n)\n\t\tvs[1][sz - 1 - v[i]] = 1;\n\tFFT::multiply(vs[0], sz, vs[1], sz, res, szRes);\n\t\n\tfore (i, sz, szRes) {\n\t\tif (res[i] > 0) {\n\t\t\tps[i - sz + 1] = 1;\n\t\t}\n\t}\n\t\n\tprecalcDivs(2 * sz);\n\t\n\tint ans = 0;\n\tfor (int i = N - 1; i > 0; i--) {\n\t\tif (ps[i] > 0)\n\t\t\tmxk[i] = max(mxk[i], t * 1ll * i / (2ll * l));\n\t\t\n\t\tfor (int d : divs[i]) {\n//\t\t\tans += mu[d] * (mxk[i] / d);\n\t\t\tans = norm(ans + mu[d] * int((mxk[i] / d) % MOD));\n\t\t\tmxk[i / d] = max(mxk[i / d], mxk[i] / d);\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1846",
    "index": "A",
    "title": "Rudolph and Cut the Rope ",
    "statement": "There are $n$ nails driven into the wall, the $i$-th nail is driven $a_i$ meters above the ground, one end of the $b_i$ meters long rope is tied to it. All nails hang at different heights one above the other. One candy is tied to all ropes at once. Candy is tied to end of a rope that is not tied to a nail.\n\nTo take the candy, you need to lower it to the ground. To do this, Rudolph can cut some ropes, one at a time. Help Rudolph find the minimum number of ropes that must be cut to get the candy.\n\nThe figure shows an example of the first test:",
    "tutorial": "In order for the candy to be on the ground, it is necessary that all the ropes touch the ground. This means that the length of all ropes must be greater than or equal to the height of the nails to which they are attached. That is, you need to cut all the ropes, the length of which is less than the height of their nail. Then the answer is equal to the number of elements that have $a_i>b_i$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\n\nint main() {\n\tint test_cases;\n\tcin >> test_cases;\n\n\tfor (int test_case = 0; test_case < test_cases; test_case++) {\n\t\tint n;\n\t\tcin >> n;\n\t\tint ans = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tint a, b;\n\t\t\tcin >> a >> b;\n\t\t\tif (a > b)\n\t\t\t\tans++;\n\t\t}\n\t\tcout << ans << endl;\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1846",
    "index": "B",
    "title": "Rudolph and Tic-Tac-Toe",
    "statement": "Rudolph invented the game of tic-tac-toe for three players. It has classic rules, except for the third player who plays with pluses. Rudolf has a $3 \\times 3$ field  — the result of the completed game. Each field cell contains either a cross, or a nought, or a plus sign, or nothing. The game is won by the player who makes a horizontal, vertical or diagonal row of $3$'s of their symbols.\n\nRudolph wants to find the result of the game. Either exactly one of the three players won or it ended in a draw. It is guaranteed that multiple players cannot win at the same time.",
    "tutorial": "To solve this problem, it is enough to check the equality of elements on each row, column and diagonal of three elements. If all three elements are equal and are not \".\", then the value of these elements is the answer. Note that a row of \".\" does not give you answer \".\". Statement does not say that the players have equal amount of moves, which means that one player can have several winning rows.",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n\n\nusing namespace std;\n\nint main() {\n\tint test_cases;\n\tcin >> test_cases;\n\tfor (int test_case = 0; test_case < test_cases; test_case++) {\n\t\tvector<string> v(3);\n\t\tfor (int i = 0; i < 3; i++)\n\t\t\tcin >> v[i];\n\t\tstring ans = \"DRAW\";\n\t\tfor(int i = 0; i < 3; i++) {\n\t\t\tif (v[i][0] == v[i][1] && v[i][1] == v[i][2] && v[i][0] != '.')\n\t\t\t\tans=v[i][0];\n\t\t}\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tif (v[0][i] == v[1][i] && v[1][i] == v[2][i] && v[0][i] != '.')\n\t\t\t\tans=v[0][i];\n\t\t}\n\t\tif (v[0][0] == v[1][1] && v[1][1] == v[2][2] && v[0][0] != '.')\n\t\t\tans=v[0][0];\n\t\tif (v[0][2] == v[1][1] && v[1][1] == v[2][0] && v[0][2] != '.')\n\t\t\tans=v[0][2];\n\t\tcout << ans << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1846",
    "index": "C",
    "title": "Rudolf and the Another Competition",
    "statement": "Rudolf has registered for a programming competition that will follow the rules of ICPC. The rules imply that for each solved problem, a participant gets $1$ point, and also incurs a penalty equal to the number of minutes passed from the beginning of the competition to the moment of solving the problem. In the final table, the participant with the most points is ranked higher, and in case of a tie in points, the participant with the lower penalty is ranked higher.\n\nIn total, $n$ participants have registered for the competition. Rudolf is a participant with index $1$. It is known that $m$ problems will be proposed. And the competition will last $h$ minutes.\n\nA powerful artificial intelligence has predicted the values $t_{i, j}$, which represent the number of minutes it will take for the $i$-th participant to solve the $j$-th problem.\n\nRudolf realized that the order of solving problems will affect the final result. For example, if $h = 120$, and the times to solve problems are [$20, 15, 110$], then if Rudolf solves the problems in the order:\n\n- ${3, 1, 2}$, then he will only solve the third problem and get $1$ point and $110$ penalty.\n- ${1, 2, 3}$, then he will solve the first problem after $20$ minutes from the start, the second one after $20+15=35$ minutes, and he will not have time to solve the third one. Thus, he will get $2$ points and $20+35=55$ penalty.\n- ${2, 1, 3}$, then he will solve the second problem after $15$ minutes from the start, the first one after $15+20=35$ minutes, and he will not have time to solve the third one. Thus, he will get $2$ points and $15+35=50$ penalty.\n\nRudolf became interested in what place he will take in the competition if each participant solves problems in the optimal order based on the predictions of the artificial intelligence. It will be assumed that in case of a tie in points and penalty, Rudolf will take the best place.",
    "tutorial": "First of all, it is necessary to determine the optimal order of solving problems for each participant. It is claimed that it is most optimal to solve problems in ascending order of their solution time. Let's prove this: Firstly, it is obvious that this strategy will allow solving the maximum number of problems. Secondly, this strategy will also result in the minimum total penalty time. Let's assume that the participant solves a total of $m$ problems. The solution time of the first problem will be added to the penalty time for all $m$ problems, the solution time of the second problem will be added to the penalty time for $m-1$ problems, and so on. Therefore, it is advantageous for the longest time to be added to the fewest number of problems. In other words, the problem with the longest solution time should be solved last. Then, the same reasoning is repeated for the remaining $m-1$ problems. Next, it is necessary to calculate the number of solved problems and the penalty time for each participant, based on the described strategy. To do this, sort the solution times of the problems for each participant and simulate the solving process. Finally, count the number of participants who outperform Rudolph in the results table. The overall time complexity is $O(n \\cdot m \\cdot \\log m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n\nusing namespace std;\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int ttt;\n    cin >> ttt;\n    while(ttt--){\n        int n, m, h;\n        cin >> n >> m >> h;\n        pair<int, long long> rud;\n        int ans = 1;\n        for(int i = 0; i < n; i++){\n            vector<int> cur(m);\n            for(int j = 0; j < m; j++){\n                cin >> cur[j];\n            }\n            std::sort(cur.begin(), cur.end());\n            int task_cnt = 0;\n            long long penalty = 0, sum = 0;\n            for(int j = 0; j < m; j++){\n                if (sum + cur[j] > h) break;\n                sum += cur[j];\n                penalty += sum;\n                task_cnt++;\n            }\n            if (i){\n                if (make_pair(-task_cnt, penalty) < rud) ans++;\n            } else rud = {-task_cnt, penalty};\n        }\n        cout << ans << '\\n';\n    }\n    return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1846",
    "index": "D",
    "title": "Rudolph and Christmas Tree",
    "statement": "Rudolph drew a beautiful Christmas tree and decided to print the picture. However, the ink in the cartridge often runs out at the most inconvenient moment. Therefore, Rudolph wants to calculate in advance how much green ink he will need.\n\nThe tree is a vertical trunk with \\textbf{identical} triangular branches at different heights. The thickness of the trunk is negligible.\n\nEach branch is an isosceles triangle with base $d$ and height $h$, whose base is perpendicular to the trunk. The triangles are arranged upward at an angle, and the trunk passes exactly in the middle. The base of the $i$-th triangle is located at a height of $y_i$.\n\nThe figure below shows an example of a tree with $d = 4, h = 2$ and three branches with bases at heights $[1, 4, 5]$.\n\nHelp Rudolph calculate the total area of the tree branches.",
    "tutorial": "Let's consider the triangles in ascending order of $y_i$. Let the current triangle have index $i$. There are two cases: The triangle does not intersect with the $(i+1)$-th triangle $(y_{i + 1} - y_i \\ge h)$. In this case, we simply add the area of the triangle to the answer. The area will be $\\frac{d \\cdot h}{2}$. The triangle intersects with the $(i+1)$-th triangle $(y_{i + 1} - y_i < h)$. We can add to the answer the area of the figure that does not belong to the intersection and move on to the next triangle. Note that this figure is a trapezoid with a lower base $d$ and height $h' = y_{i + 1} - y_i$. The upper base can be found based on the similarity of triangles. The heights of the triangles are in the ratio $k = \\frac{h - h'}{h}$. Then the upper base $d_{top} = d \\cdot k$. The area of the trapezoid is $h' \\cdot \\frac{d + d_{top}}{2}$. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    cout.precision(10); cout.setf(ios::fixed);\n    int ttt;\n    cin >> ttt;\n    while (ttt--) {\n        int n, d, h;\n        cin >> n >> d >> h;\n        vector<int> y(n);\n        for(int i = 0; i < n; i++){\n            cin >> y[i];\n        }\n        long double ans = (long double)d * h / 2.0;\n        for (int i = 0; i + 1 < n; ++i) {\n            if (y[i + 1] >= y[i] + h) ans += (long double)d * h / 2.0;\n            else{\n                long double d2 = (long double)d * (y[i] + h - y[i + 1]) / h;\n                long double nh = y[i + 1] - y[i];\n                ans += (d + d2) / 2.0 * nh;\n            }\n        }\n        cout << ans << '\\n';\n    }\n    return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "geometry",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1846",
    "index": "E1",
    "title": "Rudolf and Snowflakes (simple version)",
    "statement": "\\textbf{This is a simple version of the problem. The only difference is that in this version $n \\le 10^6$.}\n\nOne winter morning, Rudolf was looking thoughtfully out the window, watching the falling snowflakes. He quickly noticed a certain symmetry in the configuration of the snowflakes. And like a true mathematician, Rudolf came up with a mathematical model of a snowflake.\n\nHe defined a snowflake as an undirected graph constructed according to the following rules:\n\n- Initially, the graph has only one vertex.\n- Then, more vertices are added to the graph. The initial vertex is connected by edges to $k$ new vertices ($k > 1$).\n- Each vertex that is connected to only one other vertex is connected by edges to $k$ more new vertices. This step should be done \\textbf{at least once}.\n\nThe smallest possible snowflake for $k = 4$ is shown in the figure.\n\nAfter some mathematical research, Rudolf realized that such snowflakes may not have any number of vertices. Help Rudolf check if a snowflake with $n$ vertices can exist.",
    "tutorial": "For the current given constraint you can precalculate whether it is possible to obtain each $n$ for some $k$. To do this, we can iterate through all possible $2 \\le k \\le 10^6$ and for each of them calculate the values $1 + k + k^2$, $1 + k + k^2 + k^3$, ..., $1 + k + k^2 + k^3 + ... + k^p$, where $p$ is such that $1 \\le 1 + k + k^2 + k^3 + ... + k^p \\le 10^6$. For this version of problem it is enougth to calculete valuse for $p \\le 20$. Note that the minimum number of snowflake layers is $3$. Therefore, the calculations start from the value $1 + k + k^2$. We can store all the obtained values, for example, in a set. Alternatively, we can use an array called \"used\" and set the value $1$ in the array element with the corresponding index for each obtained value. It is better to perform this precalculation before iterating through the test cases. Then, for each test, we only need to read the value of $n$ and check if we have obtained it in the precalculation described above. The time complexity of the solution using a set is $O(\\sqrt n \\cdot p \\cdot \\log n + tc \\cdot \\log n$. The time complexity of the solution using the \"used\" array is $O(\\sqrt n \\cdot p + tc)$. Here $tc$ - number of test cases.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nusing LL = long long;\n\nset<long long> nums;\n\nint main() {\n\n    for (long long k = 2; k <= 1000; ++k) {\n        long long val = 1 + k;\n        long long p = k*k;\n        for (int cnt = 2; cnt <= 20; ++cnt) {\n            val += p;\n            if (val > 1e6) break;\n            nums.insert(val);            \n            p *= k;\n        }\n    }\n\n\n\n    int _ = 0, __ = 1;\n    cin >> __;\n\n    for (int _ = 0; _ < __; ++_) {\n        long long n;\n        cin >> n;\n        \n\n        if (nums.count(n)) cout << \"YES\" << endl;\n        else cout << \"NO\" << endl;\n\n    }\n\n\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1846",
    "index": "E2",
    "title": "Rudolf and Snowflakes (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $n \\le 10^{18}$.}\n\nOne winter morning, Rudolf was looking thoughtfully out the window, watching the falling snowflakes. He quickly noticed a certain symmetry in the configuration of the snowflakes. And like a true mathematician, Rudolf came up with a mathematical model of a snowflake.\n\nHe defined a snowflake as an undirected graph constructed according to the following rules:\n\n- Initially, the graph has only one vertex.\n- Then, more vertices are added to the graph. The initial vertex is connected by edges to $k$ new vertices ($k > 1$).\n- Each vertex that is connected to only one other vertex is connected by edges to $k$ more new vertices. This step should be done \\textbf{at least once}.\n\nThe smallest possible snowflake for $k = 4$ is shown in the figure.\n\nAfter some mathematical research, Rudolf realized that such snowflakes may not have any number of vertices. Help Rudolf check whether a snowflake with $n$ vertices can exist.",
    "tutorial": "On these constraints, it is also possible to precalculate whether it is possible to obtain certain values of $n$ for some $k$. To do this, we can iterate through all possible $2 \\le k \\le 10^6$ and for each of them calculate the values $1 + k + k^2$, $1 + k + k^2 + k^3$, ..., $1 + k + k^2 + k^3 + ... + k^p$, where $p$ is such that $1 \\le 1 + k + k^2 + k^3 + ... + k^p \\le 10^{18}$. However, in order to obtain all possible values of $n$, we would have to iterate through $k \\le 10^9$, which exceeds the time limits. Therefore, let's precalculate all possible values of $n$ that can be obtained for $3 \\le p \\le 63$. We will store all the obtained values, for example, in a set. We cannot use an array called \"used\" here due to the constraints on $n$. It is better to perform this precalculation before iterating through the test cases of the current test case. Next, for each test, we only need to read the value of $n$ and check if we obtained it in the aforementioned precalculation. If we obtained it, we output \"YES\" and move on to the next test. If we did not obtain it, we need to separately check if we could obtain this value for $p = 2$. To do this, we solve the quadratic equation $k^2 + k + 1 = n$. If it has integer roots that satisfy the problem's constraints ($k > 1$), then the answer is \"YES\". Otherwise, it is \"NO\". The time complexity of the solution is $O(\\sqrt[3] n \\cdot p \\cdot \\log n + tc \\cdot \\log n)$. Here, $tc$ is the number of tests in the test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nusing LL = long long;\n\nset<long long> nums;\n\nint main() {\n\n    for (long long k = 2; k <= 1000000; ++k) {\n        long long val = 1 + k;\n        long long p = k*k;\n        for (int cnt = 3; cnt <= 63; ++cnt) {\n            val += p;\n            if (val > 1e18) break;\n            nums.insert(val);\n            if (p > (long long)(1e18) / k) break;\n            p *= k;\n        }\n    }\n\n\n\n    int _ = 0, __ = 1;\n    cin >> __;\n\n    for (int _ = 0; _ < __; ++_) {\n        long long n;\n        cin >> n;\n        if (n < 3)\n        {\n            cout << \"NO\" << endl;\n            continue;\n        }\n        long long d = 4*n - 3;\n        long long sq = sqrt(d);\n        long long sqd = -1;\n        for (long long i = max(0ll, sq - 5); i <= sq + 5; ++i) {\n            if (i*i == d)\n            {\n                sqd = i;\n                break;\n            }\n        }\n        if (sqd != -1 && (sqd - 1) % 2 == 0 && (sqd - 1) / 2 > 1)\n        {\n            cout << \"YES\" << endl;\n            continue;\n        }\n\n        if (nums.count(n)) cout << \"YES\" << endl;\n        else cout << \"NO\" << endl;\n\n    }\n\n\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1846",
    "index": "F",
    "title": "Rudolph and Mimic",
    "statement": "\\textbf{This is an interactive task.}\n\nRudolph is a scientist who studies alien life forms. There is a room in front of Rudolph with $n$ different objects scattered around. Among the objects there is \\textbf{exactly one} amazing creature — a mimic that can turn into any object. He has already disguised himself in this room and Rudolph needs to find him by experiment.\n\nThe experiment takes place in several stages. At each stage, the following happens:\n\n- Rudolf looks at all the objects in the room and writes down their types. The type of each object is indicated by a number; there can be several objects of the same type.\n- After inspecting, Rudolph can point to an object that he thinks is a mimic. After that, the experiment ends. Rudolph only has one try, so if he is unsure of the mimic's position, he does the next step instead.\n- Rudolf can remove any number of objects from the room (possibly zero). Then Rudolf leaves the room and at this time all objects, including the mimic, \\textbf{are mixed} with each other, their order is changed, and the \\textbf{mimic can transform} into any other object (even one that is not in the room).\n- After this, Rudolf returns to the room and repeats the stage. The \\textbf{mimic may not change appearance}, but it can not remain a same object for more than two stages in a row.\n\nRudolf's task is to detect mimic in no more than \\textbf{five} stages.",
    "tutorial": "The strategy is to keep track of the number of objects of each type. When the number of objects of a certain type increases, that means the mimic has turned into an object of that type. Then you can delete all other objects. After the first such removal, all objects will become equal. Then, after maximum two stages, the mimic will be forced to turn into something else and it will be possible to unambiguously identify it. Let's consider the worst case, where the mimic does not change its appearance between the first and second stages. Then we do not remove any element with the first two requests. Between the second and third steps, the mimic will be forced to transform, and then we can remove all objects except for those that have the same type as the mimic. The mimic may not change between the third and fourth stages, but will be forced to transform between the fourth and fifth. Then we will be able to unambiguously determine the mimic, since before the transformation all objects were the same.",
    "code": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint main() {\n\tint test_cases;\n\tcin >> test_cases;\n\tfor (int test_case = 0; test_case < test_cases; test_case++) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> v(n);\n\t\tmap<int, int> m;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> v[i];\n\t\t\tm[v[i]]++;\n\t\t}\n\t\tvector<int> elements_to_erase;\n\t\tint ans;\n\t\tfor (int i = 0; i < 5; i++) {\n\t\t\tif (v.size() - elements_to_erase.size() == 1) {\n\t\t\t\tcout << \"! \" << ans << endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcout << \"- \" << elements_to_erase.size() << \" \";\n\t\t\tfor (int j = 0; j < elements_to_erase.size(); j++) {\n\t\t\t\tcout << elements_to_erase[j] << \" \";\n\t\t\t}\n\t\t\tcout << endl;\n\t\t\tvector<int> new_v;\n\t\t\tmap<int, int> new_m;\n\t\t\tfor (int j = 0; j < v.size() - elements_to_erase.size(); j++) {\n\t\t\t\tint x;\n\t\t\t\tcin >> x;\n\t\t\t\tnew_v.push_back(x);\n\t\t\t\tnew_m[x]++;\n\t\t\t}\n\t\t\telements_to_erase.clear();\n\t\t\tint tm = -1;\n\t\t\tfor (auto& k : new_m) {\n\t\t\t\tif (k.second > m[k.first]) {\n\t\t\t\t\ttm = k.first;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (tm != -1) {\n\t\t\t\tfor (int j = 0; j < new_v.size(); j++) {\n\t\t\t\t\tif (new_v[j] != tm)\n\t\t\t\t\t\telements_to_erase.push_back(j + 1);\n\t\t\t\t\telse\n\t\t\t\t\t\tans = j + 1;\n\t\t\t\t}\n\t\t\t\tm.clear();\n\t\t\t\tm[tm] = new_m[tm];\n\t\t\t}\n\t\t\tv = new_v;\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "interactive"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1846",
    "index": "G",
    "title": "Rudolf and CodeVid-23",
    "statement": "A new virus called \"CodeVid-23\" has spread among programmers. Rudolf, being a programmer, was not able to avoid it.\n\nThere are $n$ symptoms numbered from $1$ to $n$ that can appear when infected. Initially, Rudolf has some of them. He went to the pharmacy and bought $m$ medicines.\n\nFor each medicine, the number of days it needs to be taken is known, and the set of symptoms it removes. Unfortunately, medicines often have side effects. Therefore, for each medicine, the set of symptoms that appear when taking it is also known.\n\nAfter reading the instructions, Rudolf realized that taking more than one medicine at a time is very unhealthy.\n\nRudolph wants to be healed as soon as possible. Therefore, he asks you to calculate the minimum number of days to remove all symptoms, or to say that it is impossible.",
    "tutorial": "Let's denote Rudolf's state as a binary mask of length $n$ consisting of $0$ and $1$, similar to how it is given in the input data. Then each medicine transforms Rudolf from one state to another. Let's construct a weighted directed graph, where the vertices will represent all possible states of Rudolf. There will be $2^n$ such vertices. Two vertices will be connected by an edge if there exists a medicine that transforms Rudolf from the state corresponding to the first vertex to the state corresponding to the second vertex. The weight of the edge will be equal to the number of days that this medicine needs to be taken. Note that in this case, we simply need to find the shortest path in this graph from the vertex $s$, corresponding to the initial state of Rudolf, to the vertex $f$, corresponding to the state without symptoms. To find the shortest path in a weighted graph, we will use Dijkstra's algorithm. We will run it from the vertex $s$ and if, as a result, we visit the vertex $f$, output the distance to it, otherwise $-1$. The time complexity is $O(n \\cdot m \\cdot 2^n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int ttt;\n    cin >> ttt;\n    while (ttt--) {\n        int n, m;\n        cin >> n >> m;\n        bitset<10> tmp;\n        cin >> tmp;\n        int s = (int) tmp.to_ulong();\n        vector<pair<pair<int, int>, int>> edges(m);\n        for (int i = 0; i < m; i++) {\n            cin >> edges[i].second;\n            cin >> tmp;\n            edges[i].first.first = ((1 << n) - 1) ^ (int) tmp.to_ulong();\n            cin >> tmp;\n            edges[i].first.second = (int) tmp.to_ulong();\n        }\n        vector<int> dist(1 << n, INT_MAX);\n        dist[s] = 0;\n        set<pair<int, int>> q = {{0, s}};\n        while (!q.empty()) {\n            auto [d, v] = *q.begin();\n            q.erase(q.begin());\n            for (int i = 0; i < m; i++) {\n                int to = v & edges[i].first.first;\n                to |= edges[i].first.second;\n                if (dist[to] > d + edges[i].second) {\n                    q.erase({dist[to], to});\n                    dist[to] = d + edges[i].second;\n                    q.insert({dist[to], to});\n                }\n            }\n        }\n        if (dist[0] == INT_MAX) dist[0] = -1;\n        cout << dist[0] << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1847",
    "index": "A",
    "title": "The Man who became a God ",
    "statement": "Kars is tired and resentful of the narrow mindset of his village since they are content with staying where they are and are not trying to become the perfect life form. Being a top-notch inventor, Kars wishes to enhance his body and become the perfect life form. Unfortunately, $n$ of the villagers have become suspicious of his ideas. The $i$-th villager has a suspicion of $a_i$ on him. Individually each villager is scared of Kars, so they form into groups to be more powerful.\n\nThe power of the group of villagers from $l$ to $r$ be defined as $f(l,r)$ where\n\n$$f(l,r) = |a_l - a_{l+1}| + |a_{l + 1} - a_{l + 2}| + \\ldots + |a_{r-1} - a_r|.$$\n\nHere $|x-y|$ is the absolute value of $x-y$. A group with only one villager has a power of $0$.\n\nKars wants to break the villagers into exactly $k$ contiguous subgroups so that the sum of their power is minimized. Formally, he must find $k - 1$ positive integers $1 \\le r_1 < r_2 < \\ldots < r_{k - 1} < n$ such that $f(1, r_1) + f(r_1 + 1, r_2) + \\ldots + f(r_{k-1} + 1, n)$ is minimised. Help Kars in finding the minimum value of $f(1, r_1) + f(r_1 + 1, r_2) + \\ldots + f(r_{k-1} + 1, n)$.",
    "tutorial": "Let us find $f(1,n)$. Now, you need to divide the array into more $K-1$ parts. When you split an array $b$ of size $m$ into two parts, the suspicion changes from $f(1,m)$ to $f(1,i)+f(i+1,m)$ ($1 \\leq i < m$). Also, $f(1,m) = f(1,i) + |b_i - b_{i+1}| + f(i+1,m)$. Substituting this in previous change, we get $f(1,i) + |b_i - b_{i+1}| + f(i+1,m)$ changes to $f(1,i) + f(i+1,m)$. That is, $|b_i - b_{i+1}|$ gets subtracted. Now, to get minimum suspicion, we need to break the array $a$ at $i$ such that $|a_i-a_{i+1}|$ gets maximised. Now, we have array $dif$ of size $n-1$ where $dif_i = |a_{i+1} - a_i|$ ($1 \\leq i < n$). We can solve the problem using any of the two approaches. - Find the least element in $dif$ and remove that from $dif$ and add that element to the answer. Do this exactly $k-1$ times. Time complexity - $O(n^2)$. - We can sort $dif$ and don't take $k-1$ maximum elements (or take first $(n-1)-(k-1)$ elements. Time Complexity - $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define ull unsigned long long \n#define pb(e) push_back(e)\n#define sv(a) sort(a.begin(),a.end())\n#define sa(a,n) sort(a,a+n)\n#define mp(a,b) make_pair(a,b)\n#define all(x) x.begin(),x.end()\n\nvoid solve(){\n\tint n , k;\n\tcin >> n >> k;\n\tll arr[n];\n\tfor(int i = 0; i < n; i++)cin >> arr[i];\n\tvector<ll> v;\n\tll sum = 0;\n\tfor(int i = 1; i < n; i++){\n\t\tv.pb(abs(arr[i] - arr[i-1]));\n\t\tsum += v.back();\n\t}\n\tsort(all(v));\n\tfor(int groups = 1; groups < k; groups++){\n\t\tsum -= v.back();\n\t\tv.pop_back();\n\t}\n\tcout << sum << '\\n';\n}\n\nint main(){\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\n\tint t;cin >> t;while(t--)\n\tsolve();\n\treturn 0;\n}\n",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1847",
    "index": "B",
    "title": "Hamon Odyssey",
    "statement": "Jonathan is fighting against DIO's Vampire minions. There are $n$ of them with strengths $a_1, a_2, \\dots, a_n$. $\\def\\and {{\\,&\\,}}$\n\nDenote $(l, r)$ as the group consisting of the vampires with indices from $l$ to $r$. Jonathan realizes that the strength of any such group is in its weakest link, that is, the bitwise AND. More formally, the strength level of the group $(l, r)$ is defined as $$f(l,r) = a_l \\and a_{l+1} \\and a_{l+2} \\and \\ldots \\and a_r.$$ Here, $\\and$ denotes the bitwise AND operation.\n\nBecause Jonathan would like to defeat the vampire minions fast, he will divide the vampires into contiguous groups, such that each vampire is in \\textbf{exactly} one group, and the \\textbf{sum} of strengths of the groups is \\textbf{minimized}. Among all ways to divide the vampires, he would like to find the way with the \\textbf{maximum} number of groups.\n\nGiven the strengths of each of the $n$ vampires, find the \\textbf{maximum number} of groups among all possible ways to divide the vampires with the smallest sum of strengths.",
    "tutorial": "There are two cases in this problem. First, if $f(1,n) > 0$, then maximum number of groups becomes $1$. This is because there are some bits set in all the elements. Now, if we divide the array in more than one group, then these bits are taken more than once which will not give smallest AND. Second case is when $f(1,n) = 0$. This means the smallest AND is $0$. Now, we need to greedily divide the array into subarrays such that the AND of each subarray should be $0$. We keep taking elements in the subarray until the AND becomes $0$. When AND becomes $0$, we take remaining elements in the next subarray. If the last subarray has AND more than $0$, then we need to merge that subarray with the previous subarray. Time complexity - $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\nusing namespace std;\n#define ll long long\n#define ull unsigned long long \n#define pb(e) push_back(e)\n#define sv(a) sort(a.begin(),a.end())\n#define sa(a,n) sort(a,a+n)\n#define mp(a,b) make_pair(a,b)\n#define all(x) x.begin(),x.end()\n\nvoid solve(){\n\tint n;\n\tcin >> n;\n\tint arr[n];\n\tfor(int i = 0; i < n; i++)cin >> arr[i];\n\tint cur = arr[0];\n\tint part = 1;\n\tfor(int i = 0; i < n; i++){\n\t\tcur &= arr[i];\n\t\tif(cur == 0){\n\t\t\tif(i == n-1)break;\n\t\t\tpart++;\n\t\t\tcur = arr[i + 1];\n\t\t}\n\t}\n\tif(cur != 0)part--;\n\tpart = max(part,1);\n\tcout << part << '\\n';\n}\n\nint main(){\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\n\tint t;cin >> t;while(t--)\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1847",
    "index": "C",
    "title": "Vampiric Powers, anyone?",
    "statement": "DIO knows that the Stardust Crusaders have determined his location and will be coming to fight him. To foil their plans he decides to send out some Stand users to fight them. Initially, he summoned $n$ Stand users with him, the $i$-th one having a strength of $a_i$. Using his vampiric powers, he can do the following as many times as he wishes:\n\n- Let the \\textbf{current} number of Stand users be $m$.\n- DIO chooses an index $i$ ($1 \\le i \\le m$).\n- Then he summons a new Stand user, with index $m+1$ and strength given by: $$a_{m+1} = a_i \\oplus a_{i+1} \\oplus \\ldots \\oplus a_m,$$where the operator $\\oplus$ denotes the bitwise XOR operation.\n- Now, the number of Stand users becomes $m+1$.\n\nUnfortunately for DIO, by using Hermit Purple's divination powers, the Crusaders know that he is plotting this, and they also know the strengths of the original Stand users. Help the Crusaders find the maximum possible strength of a Stand user among all possible ways that DIO can summon.",
    "tutorial": "At the end of the array, you can only achieve xor of any subarray of the original array. Lets denote $f(u,v) =$ xor of all $a_i$ such that $min(u,v) \\leq i < max(u,v)$. In the first operation you add $f(n,i)$. I.e. $[u_1,v_1)=[n,i)$. It can be proven that $f(u_k,v_k) = f(v_{k-1},v_k)$ in the $k$-th operation which is a range. Suppose we have taken $k$ ranges that already satisfy this property. Now, I add a new $k+1$-th range. So, first I need to take the $k$-th range $f(u_k,v_k)$. Now I'm xoring it with the range $f(u_{k - 1}, v_{k - 1})$. As [ $u_k, v_k$) and [ $u_{k - 1}, v_{k - 1}$) share an endpoint, the result for these ranges will be a range. For two ranges $f(x,y)$ and $f(y,z)$, if the two ranges do not intersect, the result will be the sum of the two ranges $f(x,z)$. If the two ranges intersect, then the intersections will be cancelled out, and the result will be the difference $f(x,z)$. Now, we maintain a boolean array $b$ where $b_i$ is $1$ if there is some $j$ such that $a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_j = i$. Initially, $b$ is all $0$. We loop $j$ from $1$ to $n$ and check for each $k$ if $b_k=1$. If it is, then there is some position $p < j$ such that $a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_p = k$. If we take xor of range from $(p,j]$, then it will be $k \\oplus a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_j$ (as $a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_p$ gets cancelled). This $a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_j$ can be stored as we loop ahead. We are looping all possible prefix xors and not all prefix positions because $n$ is large. Time Complexity - $O(n \\cdot 2^8)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    int ntest;\n    cin >> ntest;\n    while (ntest--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (auto &i : a)\n            cin >> i;\n \n        int const max_value = 1 << 8;\n        vector<char> has_pref(max_value);\n        has_pref[0] = true;\n        int cur_xor = 0;\n        int ans = 0;\n        for (auto i : a) {\n            cur_xor ^= i;\n            for (int pref = 0; pref < max_value; ++pref) {\n                if (has_pref[pref]) {\n                    ans = max(ans, pref ^ cur_xor);\n                }\n            }\n            has_pref[cur_xor] = true;\n        }\n \n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1847",
    "index": "D",
    "title": "Professor Higashikata",
    "statement": "Josuke is tired of his peaceful life in Morioh. Following in his nephew Jotaro's footsteps, he decides to study hard and become a professor of computer science. While looking up competitive programming problems online, he comes across the following one:\n\nLet $s$ be a binary string of length $n$. An operation on $s$ is defined as choosing two distinct integers $i$ and $j$ ($1 \\leq i < j \\leq n$), and swapping the characters $s_i, s_j$.\n\nConsider the $m$ strings $t_1, t_2, \\ldots, t_m$, where $t_i$ is the substring $^\\dagger$ of $s$ from $l_i$ to $r_i$. Define $t(s) = t_1+t_2+\\ldots+t_m$ as the concatenation of the strings $t_i$ in that order.\n\nThere are $q$ updates to the string. In the $i$-th update $s_{x_i}$ gets flipped. That is if $s_{x_i}=1$, then $s_{x_i}$ becomes $0$ and vice versa. After each update, find the minimum number of \\textbf{operations one must perform on $s$} to make $t(s)$ lexicographically as large$^\\ddagger$ as possible.\n\nNote that no operation is actually performed. We are only interested in the number of operations.\n\nHelp Josuke in his dream by solving the problem for him.\n\n\\begin{center}\n——————————————————————\n\\end{center}\n\n$\\dagger$ A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\n$\\ddagger$ A string $a$ is lexicographically larger than a string $b$ of the same length if and only if the following holds:\n\n- in the first position where $a$ and $b$ differ, the string $a$ has a $1$, and the string $b$ has a $0$.",
    "tutorial": "Lets assume you know string $t$. String $t$ is made by positions in $s$. Lets denote $f(i) =$ position in $s$ from which $t_i$ is made. For maximising $t$ you need to make the starting elements in $t$ as large as possible. Now, to make $t$ lexicographically as large as possible, we need to swap positions in $s$. We can swap positions greedily. We first try making $s_{f(1)} = 1$. Then we try making $s_{f(2)} = 1$ and so on. Now, suppose for two indices $i$,$j$ ($1 \\leq i < j \\leq |t|$) such that $f(i) = f(j)$, we know that index $j$ is waste. $t$ is basically the preference of indices in $s$ which should be equal to $1$. If $s_{f(j)}$ is to be set $1$, then it would already be set $1$ because before setting $s_{f(j)}$ equal to $1$ we would have already set $s_{f(i)}$ equal to $1$ because $f(i)$ is equal to $f(j)$. Hence, for each index $i$ in $s$, we only add its first occurrence in $t$. This makes the size of $t$ bound by size of $s$. Now, this $t$ can be found using various pbds like set,dsu,segment tree,etc. Now, before answering the queries, we find the answer for the current string $s$. We know that there are $x$ ones and $n-x$ zeros in $s$. So, for each $i$ ($1 \\leq i \\leq min(x,|t|)$), we make $s_{f(i)} = 1$. Hence, the number of swaps needed will become number of positions $i$ ($1\\leq i \\leq min(x,|t|)$) such that $s_i=0$. Now, in each query, there is exactly one positions that is either getting flipped from $0$ to $1$ or from $1$ to $0$. That is, $x$ is either getting changed to $x+1$ or $x-1$. You already know the answer for $x$. Now, if $x$ is getting reduced, then you need to decrease the answer by one if $x <= |t|$ and $s_{f(x)}=0$. If $x$ is increasing by one, then you need to add one to the answer if $x < |t|$ and $s_{f(x+1)} = 0$. Time complexity - $O(n \\log n + q)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define ull unsigned long long \n#define pb(e) push_back(e)\n#define sv(a) sort(a.begin(),a.end())\n#define sa(a,n) sort(a,a+n)\n#define mp(a,b) make_pair(a,b)\n#define vf first\n#define vs second\n#define all(x) x.begin(),x.end()\n \nvoid solve(){\n\tint n , m , q;\n\tcin >> n >> m >> q;\n\tstring st;\n\tcin >> st;\n\tvector<pair<int,int>> ranges;\n\tfor(int i = 0; i < m; i++){\n\t\tint l , r;\n\t\tcin >> l >> r;\n\t\tl--;\n\t\tr--;\n\t\tranges.pb(mp(l,r));\n\t}\n\tset<int> s;\n\tfor(int i = 0; i < n; i++)s.insert(i);\n\tvector<int> v;\n\tint pos_in_v[n];\n\tmemset(pos_in_v,-1,sizeof pos_in_v);\n\tfor(int i = 0; i < m; i++){\n\t\tauto it = s.lower_bound(ranges[i].vf);\n\t\tvector<int> toerase;\n\t\twhile(it != s.end() && (*it) <= ranges[i].vs){\n\t\t\ttoerase.pb((*it));\n\t\t\tv.pb(toerase.back());\n\t\t\tpos_in_v[toerase.back()] = v.size()-1;\n\t\t\tit++;\n\t\t}\n\t\twhile(toerase.size()){\n\t\t\ts.erase(toerase.back());\n\t\t\ttoerase.pop_back();\n\t\t}\n\t}\n\tint cnt = 0;\n\tfor(int i = 0; i < n; i++){\n\t\tif(st[i] == '1')cnt++;\n\t}\n\tint ans = 0;\n\tfor(int i = 0; i < min(cnt , (int)v.size()); i++){\n\t\tif(st[v[i]] == '0')ans++;\n\t}\n\t\n\twhile(q--){\n\t\tint pos;\n\t\tcin >> pos;\n\t\tpos--;\n\t\tif(pos_in_v[pos] != -1 && pos_in_v[pos] < cnt){\n\t\t\tif(st[pos] == '0'){\n\t\t\t\tans--;\n\t\t\t}\n\t\t\telse ans++;\n\t\t}\n\t\tif(st[pos] == '0'){\n\t\t\tst[pos] = '1';\n\t\t\tcnt++;\n\t\t\tif(cnt <= v.size() && st[v[cnt-1]] == '0')ans++;\n\t\t}\n\t\telse {\n\t\t\tst[pos] = '0';\n\t\t\tif(cnt > 0 && cnt <= v.size() && st[v[cnt-1]] == '0')ans--;\n\t\t\tcnt--;\n\t\t}\n\t\tcout << ans << '\\n';\n\t}\n}\n \nint main(){\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\n\t//int t;cin >> t;while(t--)\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1847",
    "index": "E",
    "title": "Triangle Platinum?",
    "statement": "This is an interactive problem.\n\nMade in Heaven is a rather curious Stand. Of course, it is (arguably) the strongest Stand in existence, but it is also an ardent puzzle enjoyer. For example, it gave Qtaro the following problem recently:\n\nMade in Heaven has $n$ hidden integers $a_1, a_2, \\dots, a_n$ ($3 \\le n \\le 5000$, $1 \\le a_i \\le 4$). Qtaro must determine all the $a_i$ by asking Made in Heaven some queries of the following form:\n\n- In one query Qtaro is allowed to give Made in Heaven three \\textbf{distinct} indexes $i$, $j$ and $k$ ($1 \\leq i, j, k \\leq n$).\n- If $a_i, a_j, a_k$ form the sides of a non-degenerate triangle$^\\dagger$, Made in Heaven will respond with the area of this triangle.\n- Otherwise, Made in Heaven will respond with $0$.\n\nBy asking at most $5500$ such questions, Qtaro must either tell Made in Heaven all the values of the $a_i$, or report that it is \\textbf{not} possible to \\textbf{uniquely} determine them.\n\nUnfortunately due to the universe reboot, Qtaro is not as smart as Jotaro. Please help Qtaro solve Made In Heaven's problem.\n\n\\begin{center}\n——————————————————————\n\\end{center}\n\n$^\\dagger$ Three positive integers $a, b, c$ are said to form the sides of a non-degenerate triangle if and only if all of the following three inequalities hold:\n\n- $a+b > c$,\n- $b+c > a$,\n- $c+a > b$.",
    "tutorial": "First, notice that we can uniquely determine the multiset of numbers any three $a_i, a_j, a_k$ except for the collision between triples $(1, 4, 4)$ and $(2, 2, 3)$. The issue is that even if we know the multiset we cannot always uniquely determine $a_i, a_j, a_k$. But what if all the elements of the multiset are equal? Then each element obviously has to be equal to the value of the multiset. So if for some three distinct $i, j, k$ the area of $a_i, a_j, a_k$ is one of $\\sqrt{3}/4, \\sqrt{3}, 9\\sqrt{3}/4, 4\\sqrt{3}$, then they are all equal to $1, 2, 3$ or $4$ respectively, depending on the area. Let us say we knew that $a_i = a_j = a_k = C$ for some $C \\in [1, 4]$ after asking $q$ queries. By querying $(i, j, x)$ for every $x$ other than $i, j$ we can obtain the area of $C, C, a_x$ for each $x$. This will allow us to uniquely determine each $a_x$. But wait! There is an important edge case here. We also require $C, C, a_x$ to form a valid triangle. If $C \\geq 2$, this is not an issue because $2, 2, 4$ can be just assigned an area of \"$0$\" and we can still uniquely retrieve the values. So using this procedure, it takes us $q+n-3$ queries to determine all the values. The only possibility remaining is when $C = 1$. In this case, the issue is that only $[1, 1, 1]$ let us know the value of $a_x$. When $a_x > 1$, it's impossible to distinguish between $a_x = 2, 3, 4$. So if we asked all questions, we would know which indices have value $> 1$ and which indices have a value of $1$. Now if we could find two equal elements among these indices with value $> 1$, we can repeat a similar linear scan as above and find all values. But how do we find two equal values? Notice that every value is among $2, 3, 4$. So if we had $\\geq 4$ such indices with value $> 1$ some two of them would be equal, and we could find them by bruting queries of the form $(i, m_1, m_2)$ over all pairs of indices $m_1, m_2$ with value $> 1$. After this we can then again query all the other $> 1$ indices and find answer. This would take around $q+n'+2(n-n')-\\mathcal O(1)$ queries, where $n'$ is the number of ones. Unfortunately this would QLE if $n'$ were around $n/2$. How do we fix this? The answer is surprisingly simple. When we were finding indices with value $> 1$ we simply stop the minute we have at least $4$ such indices (it's ok even if we don't). Now we brute over all pairs. If we find two equal, we are done within at most $q+n+16$ queries. On the other hand if we cannot find two equal it means that we can never distinguish between them. This is because any query of the form $(1, x, y)$ where $x \\ne y$ are both $\\geq 2$ is always a degenerate query hence will have answer $0$. So if we do not find two equal, we will print $-1$. After all this work, there are still a few details left. First, $q$ must be small. Otherwise all the above work is useless. Second there should be three equal elements in the first place. The first observation is that if $n \\geq 9$ then by Piegonhole Principle, some $\\lceil n/4 \\rceil \\geq 3$ must be equal. So if $n \\geq 9$ then by bruting over all $1 \\leq i < j < k \\leq 9$ triples $(i, j, k)$ we can always find some three equal. Here we would have $q = {9 \\choose 3} = 84$ and we are asking at most $n+84+16$ queries, which fits comfortably. But what if $n < 9$? In this case we can simply brute all possible ${9 \\choose 3} = 84$ queries and then for each of the $4^n$ arrays possible check if the triples of that array match with the query answers obtained here. If there is exactly one such array, we have found it and we can print it, otherwise we print $-1$ because it is not possible to uniquely determine the values of the array. Notice that this takes at most $4^8 \\cdot {8 \\choose 3}$ operations, which is around $3.7 \\cdot 10^6$ which fits in the TL. This solves the problem. You might wonder why $5500$ queries were allowed even though the above solution does not use more than around $5100$ queries. This is because we allowed randomisation as a valid way of finding three equal values $a_i, a_j, a_k$. Suppose there are $c_1, c_2, c_3, c_4$ counts of $1, 2, 3, 4$ respectively. If we randomly queried a triple $(i, j, k)$ each time, the probability all would be equal is precisely: $\\frac{{c_1 \\choose 3}+{c_2 \\choose 3}+{c_3 \\choose 3}+{c_4 \\choose 3}}{{n \\choose 3}}$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define INF (int)1e18\n#define f first\n#define s second\n \nmt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());\nconst int N = 5005;\nint ans[N];\nint n;\nint dp[5][5][5];\nint holy[11][11][11];\n \nint area(int a, int b, int c){\n    if (a >= b + c) return 0;\n    if (b >= a + c) return 0;\n    if (c >= a + b) return 0;\n    \n    int s = (a + b + c);\n    return s * (s - 2 * a) * (s - 2 * b) * (s - 2 * c);\n}\n \nint query(int a, int b, int c){\n    cout << \"? \" << a << \" \" << b << \" \" << c << endl;\n    int ans; cin >> ans;\n    return ans;\n}\n \nvoid print(bool found = true){\n    if (!found){\n        cout << \"! -1\\n\";\n        exit(0);\n    } else {\n        cout << \"! \";\n        for (int i = 1; i <= n; i++) cout << ans[i] << \" \";\n        cout << endl;\n        exit(0);\n    }\n}\n \nbool works(){\n    for (int i = 1; i <= n; i++){\n        for (int j = i + 1; j <= n; j++){\n            for (int k = j + 1; k <= n; k++){\n                if (area(ans[i], ans[j], ans[k]) != holy[i][j][k])\n                    return false;\n            }\n        }\n    }\n    \n    return true;\n}\n \nvoid brutesmall(){\n    for (int i = 1; i <= n; i++){\n        for (int j = i + 1; j <= n; j++){\n            for (int k = j + 1; k <= n; k++){\n                holy[i][j][k] = query(i, j, k);\n            }\n        }\n    }\n    \n    int mask = 1 << (2 * n);\n    int lol = 0;\n    for (int i = 0; i < mask; i++){\n        int copy = i;\n        \n        for (int i = 1; i <= n; i++){\n            ans[i] = 1 + copy % 4;\n            copy /= 4;\n        }\n        \n        if (works()){\n            lol++;\n        }\n    }\n    \n    if (lol > 1) print(false);\n    \n    for (int i = 0; i < mask; i++){\n        int copy = i;\n        \n        for (int i = 1; i <= n; i++){\n            ans[i] = 1 + copy % 4;\n            copy /= 4;\n        }\n        \n        if (works()){\n            print();\n        }\n    }\n}\n \nvoid Solve() \n{\n    cin >> n;\n    \n    for (int i = 1; i <= 4; i++){\n        for (int j = 1; j <= 4; j++){\n            for (int k = 1; k <= 4; k++){\n                dp[i][j][k] = area(i, j, k);\n            }\n        }\n    }\n    \n    if (n < 9){\n        brutesmall();\n    }\n    \n    vector <int> tuple(4, -1);\n    while (true){\n        if (tuple[0] != -1) break;\n        int p1 = 1 + RNG() % n;\n        int p2 = 1 + RNG() % n;\n        int p3 = 1 + RNG() % n;\n        \n        if (p1 == p2 || p2 == p3 || p3 == p1) continue;\n        int ar = query(p1, p2, p3);\n        for (int j = 1; j <= 4; j++){\n            if (ar == dp[j][j][j]){\n                tuple[0] = p1;\n                tuple[1] = p2;\n                tuple[2] = p3;\n                tuple[3] = j;\n            }\n        }\n    }\n    \n    for (int i = 0; i < 3; i++) ans[tuple[i]] = tuple[3];\n    \n    if (tuple[3] == 1){\n        vector <int> nv;\n        for (int i = 1; i <= n; i++){\n            if (ans[i] > 0) continue;\n            \n            int fetch = query(tuple[0], tuple[1], i);\n            if (fetch == 0) {\n                nv.push_back(i);\n                if (nv.size() > 3) break;\n            } else {\n                ans[i] = 1;\n            }\n        }\n        \n        if (nv.size() == 0) print();\n        \n        vector <int> ntuple(3, -1);\n        for (int i1 = 0; i1 < nv.size(); i1++){\n            for (int i2 = i1 + 1; i2 < nv.size(); i2++){\n                int ok = query(tuple[0], nv[i1], nv[i2]);\n                \n                for (int j = 2; j <= 4; j++){\n                    if (ok == dp[1][j][j]){\n                        ntuple[0] = nv[i1];\n                        ntuple[1] = nv[i2];\n                        ntuple[2] = j;\n                    }\n                }\n            }\n        }\n        \n        if (ntuple[0] == -1) print(false);\n        ans[ntuple[0]] = ntuple[2];\n        ans[ntuple[1]] = ntuple[2];\n        \n        tuple[0] = ntuple[0];\n        tuple[1] = ntuple[1];\n        tuple[2] = -1;\n        tuple[3] = ntuple[2];\n    }\n    \n    for (int i = 1; i <= n; i++){\n        if (ans[i] > 0) continue;\n        \n        int fetch = query(tuple[0], tuple[1], i);\n        for (int j = 1; j <= 4; j++){\n            if (dp[tuple[3]][tuple[3]][j] == fetch)\n                ans[i] = j;\n        }\n    }\n    \n    print();\n}\n \nint32_t main() \n{\n    auto begin = std::chrono::high_resolution_clock::now();\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t = 1;\n //   cin >> t;\n    for(int i = 1; i <= t; i++) \n    {\n        Solve();\n    }\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "combinatorics",
      "implementation",
      "interactive",
      "math",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1847",
    "index": "F",
    "title": "The Boss's Identity",
    "statement": "While tracking Diavolo's origins, Giorno receives a secret code from Polnareff. The code can be represented as an infinite sequence of positive integers: $a_1, a_2, \\dots $. Giorno immediately sees the pattern behind the code. The first $n$ numbers $a_1, a_2, \\dots, a_n$ are \\textbf{given}. For $i > n$ the value of $a_i$ is $(a_{i-n}\\ |\\ a_{i-n+1})$, where $|$ denotes the bitwise OR operator.\n\nPieces of information about Diavolo are hidden in $q$ questions. Each question has a positive integer $v$ associated with it and its answer is the smallest index $i$ such that $a_i > v$. If no such $i$ exists, the answer is $-1$. Help Giorno in answering the questions!",
    "tutorial": "Lets start with an example of $n=5$. Let $a = [a,b,c,d,e]$ where $a$,$b$,$c$,$d$ and $e$ are variables. First $20$ elements of $a$ will be [$a$,$b$,$c$,$d$,$e$,$ab$,$bc$,$cd$,$de$,$abe$,$abc$,$bcd$,$cde$,$abde$,$abce$,$abcd$,$bcde$,$abcde$,$abcde$,$abcde$]. By removing and rearranging some elements we can get $b$$c$$d$$e$$\\bf{ab}$$bc$$cd$$de$$\\bf{eab}$$\\bf{abc}$$bcd$$cde$$\\bf{deab}$$\\bf{eabc}$$\\bf{abcd}$$bcde$ Here you can observe that each group will have a size of $n-1$. The next group will be the previous group, _or_ed with the element immediately before the first element (circularly). So we have the rule. Now let's solve the problem in binary (that is, every element is $0/1$). Let's take a look at the element $a$ in the rearranged version (the highlighted ones). If $a$ is $0$, it won't contribute anything to the subsequent groups, so we can ignore it. Otherwise, it will contribute by keeping moving to the right. This will end when it meets a cell in the group that is already $1$. And after that, we can drop the act of moving $a$. This algorithm can actually help us construct the whole array sparsely and incrementally. We can maintain the list of $1$ in the initial array, and then update the array by moving all of them to the right. That is, if we have one group, we can obtain the next group by moving the $1$. After that, we can drop moving some $1$ if it meets another $1$. The whole action is $O(n)$, as there are at most $n$ zeros to be updated. So for the original problem, first of all, we can repeat the above algorithm $bitlength=31$ times, that is, repeat the algorithm for each bit. Secondly, there are at most $O(\\log n)$ unique numbers for each position, so we can just find all $O(n \\log n)$ last positions of all numbers, and put them in a array. You can either find all $n \\log n$ unique positions in ascending order and or in random order and sort the array. Then using binary search we can answer each query. Time complexity of the former version is $O(n \\log n + q \\log(n \\log n))$ and the latter version is $O(n \\log n \\log(n \\log n) + q \\log(n \\log n))$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define ull unsigned long long \n#define pb(e) push_back(e)\n#define sv(a) sort(a.begin(),a.end())\n#define sa(a,n) sort(a,a+n)\n#define mp(a,b) make_pair(a,b)\n#define vf first\n#define vs second\n#define all(x) x.begin(),x.end()\n\nconst int B = 31;\n\nstruct item {\n\tll pos , bit, idx;\n};\n\nitem make(ll pos , ll bit , ll idx){\n\titem res;\n\tres.pos = pos;\n\tres.bit = bit;\n\tres.idx = idx;\n\treturn res;\n}\n\nvoid solve(){\n    int n;\n\tcin >> n;\n\tint qu;\n\tcin >> qu;\n\tint arr[n];\n\tfor(int i = 0; i < n; i++)cin >> arr[i];\n\tif(n == 1){\n\t\twhile(qu--){\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\tif(x < arr[0])cout << 1 << '\\n';\n\t\t\telse cout << -1 << '\\n';\n\t\t}\n\t\treturn;\n\t}\n\tvector<pair<ll,ll>> v;\n\tqueue<item> q;\n\tbool vis[n][B];\n\tmemset(vis,0,sizeof vis);\n\tfor(int i = 0; i < n; i++){\n\t\tfor(int j = 0; j < B; j++){\n\t\t\tif((arr[i] & (1 << j)) > 0){\n\t\t\t\tvis[i][j] = 1;\n\t\t\t}\n\t\t}\n\t\tv.pb(mp(i , arr[i]));\n\t}\n\tfor(int i = 0; i < n - 1; i++){\n\t\tv.pb(mp(n+i,arr[i]|arr[i+1]));\n\t}\n\tfor(int j = 0; j < B; j++){\n\t\tif(vis[n-1][j])q.push(make(n+n-1,j,0));\n\t}\n\tfor(int i = 0; i < n - 1; i++){\n\t\tfor(int j = 0; j < B; j++){\n\t\t\tif(vis[i][j])q.push(make(n+n+i,j,(i+1)%(n-1)));\n\t\t}\n\t}\n\tint val[n-1];\n\tfor(int i = 0; i < n-1; i++)val[i] = arr[i]|arr[i+1];\n\twhile(q.size()){\n\t\titem it = q.front();\n\t\tq.pop();\n\t\tif((val[it.idx] & (1 << it.bit)) > 0){\n\t\t\tcontinue;\n\t\t}\n\t\tval[it.idx] += (1 << it.bit);\n\t\tif(v.back().vf == it.pos){\n\t\t\tv.pop_back();\n\t\t}\n\t\tv.pb(mp(it.pos , val[it.idx]));\n\t\tq.push(make(it.pos + n , it.bit , (it.idx + 1)%(n-1)));\n\t}\n\t\n\t// first part gets over where v[i].first contains position in ascending order and v[i].second contains the value to what has become on that position.\n\t\n\t\n\tfor(int i = 1; i < v.size(); i++){\n\t\tv[i].vs = max(v[i].vs , v[i-1].vs);\n\t}\n\n\twhile(qu--){\n\t\tint x;\n\t\tcin >> x;\n\t\tll l = 0 , r = v.size()-1;\n\t\tll res = -1;\n\t\twhile(l <= r){\n\t\t\tint mid = (l + r)/2;\n\t\t\tif(v[mid].vs <= x){\n\t\t\t\tl = mid + 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tr = mid - 1;\n\t\t\t\tres = v[mid].vf+1;\n\t\t\t}\n\t\t}\n\t\tcout << res << '\\n';\n\t}\n}\n\nint main(){\nios_base::sync_with_stdio(false);\ncin.tie(NULL);\n\tint t;cin >> t;while(t--)\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "dfs and similar",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1848",
    "index": "A",
    "title": "Vika and Her Friends",
    "statement": "Vika and her friends went shopping in a mall, which can be represented as a rectangular grid of rooms with sides of length $n$ and $m$. Each room has coordinates $(a, b)$, where $1 \\le a \\le n, 1 \\le b \\le m$. Thus we call a hall with coordinates $(c, d)$ a neighbouring for it if $|a - c| + |b - d| = 1$.\n\nTired of empty fashion talks, Vika decided to sneak away unnoticed. But since she hasn't had a chance to visit one of the shops yet, she doesn't want to leave the mall. After a while, her friends noticed Vika's disappearance and started looking for her.\n\nCurrently, Vika is in a room with coordinates $(x, y)$, and her $k$ friends are in rooms with coordinates $(x_1, y_1)$, $(x_2, y_2)$, ... $, (x_k, y_k)$, respectively. The coordinates can coincide. Note that all the girls \\textbf{must} move to the neighbouring rooms.\n\nEvery minute, first Vika moves to one of the adjacent to the side rooms of her choice, and then each friend (\\textbf{seeing Vika's choice}) also chooses one of the adjacent rooms to move to.\n\nIf \\textbf{at the end of the minute} (that is, after all the girls have moved on to the neighbouring rooms) at least one friend is in the same room as Vika, she is caught and all the other friends are called.\n\nTell us, can Vika run away from her annoying friends forever, or will she have to continue listening to empty fashion talks after some time?",
    "tutorial": "Let's color the halls of a rectangle in a chess coloring. Then Vika will be able to escape from her friends infinitely only if none of her friends is on a cell of the same color as Vika. This observation seems intuitively clear, but let's formalize it. $\\Leftarrow)$ It is true, because if initially Vika and her friend were in halls of different colors, then after one move they will remain in halls of different colors. $\\Rightarrow)$ Let's choose any of the friends who is in a hall of the same color as Vika. We will show how the friend will act to catch Vika in a finite time. First, let's define a quantity that we will call the area to Vika: If Vika and the friend are in the same column, then the area to Vika is equal to the sum of the areas of all rows in the direction of Vika and the row where the friend is located. If Vika and the friend are in the same row, then the area to Vika is equal to the sum of the areas of all columns in the direction of Vika and the column where the friend is located. Otherwise, the area to Vika is equal to the area of the quadrant in which Vika is located relative to the friend. If Vika is in the same column as the friend. If Vika goes towards the friend, then the friend goes towards her, reducing the distance. If Vika goes in the opposite direction, then the friend also goes towards her, reducing the area to Vika. If Vika goes along the row, then the friend goes towards Vika along the column, which also reduces the area to Vika. If Vika is in the same row as the friend. If Vika goes towards the friend, then the friend goes towards her, reducing the distance. If Vika goes in the opposite direction, then the friend also goes towards her, reducing the area to Vika. If Vika goes along the column, then the friend goes towards Vika along the row, which also reduces the area to Vika. If Vika and the friend are in different rows and columns. If Vika goes towards the friend along the row, then the friend goes towards her along the column, reducing the distance. If Vika goes towards the friend along the column, then the friend goes towards her along the row, reducing the distance. If Vika goes away from the friend, then the friend makes a move in the same direction, thereby reducing the area to Vika.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nint32_t main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m, k;\n        cin >> n >> m >> k;\n        int x, y;\n        cin >> x >> y;\n        string ans = \"YES\\n\";\n        for (int i = 0; i < k; ++i) {\n            int xx, yy;\n            cin >> xx >> yy;\n            if ((x + y) % 2 == (xx + yy) % 2) {\n                ans = \"NO\\n\";\n            }\n        }\n        cout << ans;\n    }\n    return 0;\n}",
    "tags": [
      "games",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1848",
    "index": "B",
    "title": "Vika and the Bridge",
    "statement": "In the summer, Vika likes to visit her country house. There is everything for relaxation: comfortable swings, bicycles, and a river.\n\nThere is a wooden bridge over the river, consisting of $n$ planks. It is quite old and unattractive, so Vika decided to paint it. And in the shed, they just found cans of paint of $k$ colors.\n\nAfter painting each plank in one of $k$ colors, Vika was about to go swinging to take a break from work. However, she realized that the house was on the other side of the river, and the paint had not yet completely dried, so she could not walk on the bridge yet.\n\nIn order not to spoil the appearance of the bridge, Vika decided that she would still walk on it, but only stepping on planks of the same color. Otherwise, a small layer of paint on her sole will spoil the plank of another color. Vika also has a little paint left, but it will only be enough to repaint \\textbf{one} plank of the bridge.\n\nNow Vika is standing on the ground in front of the first plank. To walk across the bridge, she will choose some planks of the same color (after repainting), which have numbers $1 \\le i_1 < i_2 < \\ldots < i_m \\le n$ (planks are numbered from $1$ from left to right). Then Vika will have to cross $i_1 - 1, i_2 - i_1 - 1, i_3 - i_2 - 1, \\ldots, i_m - i_{m-1} - 1, n - i_m$ planks as a result of each of $m + 1$ steps.\n\nSince Vika is afraid of falling, she does not want to take too long steps. Help her and tell her the minimum possible maximum number of planks she will have to cross \\textbf{in one step}, if she can repaint one (\\textbf{or zero}) plank a different color while crossing the bridge.",
    "tutorial": "In a single linear pass through the array, let's calculate, for each color, the lengths of the two maximum steps between planks of that color. To do this, we will maintain when we last encountered that color. Now we need to consider that we can repaint one of the planks. Let's say we repaint a plank in color $c$. It is easy to notice that we should repaint the plank in the middle of the longest step between planks of color $c$. After all, if we don't repaint such a plank, we will still have to make that longest step. Therefore, the answer for a fixed color will be the maximum of two values: half the length of the longest step between planks of that color, and the length of the second largest step between planks of that color. Knowing the answer for each individual color, we can determine the answer to the problem. To do this, we just need to take the minimum of the answers for all colors.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, k;\n        cin >> n >> k;\n        vector<int> c(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> c[i];\n        }\n        vector<int> last(k, -1);\n        vector<int> max_step(k), max2_step(k);\n        for (int i = 0; i < n; ++i) {\n            int step = i - last[c[i] - 1];\n            if (step > max_step[c[i] - 1]) {\n                max2_step[c[i] - 1] = max_step[c[i] - 1];\n                max_step[c[i] - 1] = step;\n            } else if (step > max2_step[c[i] - 1]) {\n                max2_step[c[i] - 1] = step;\n            }\n            last[c[i] - 1] = i;\n        }\n        for (int i = 0; i < k; ++i) {\n            int step = n - last[i];\n            if (step > max_step[i]) {\n                max2_step[i] = max_step[i];\n                max_step[i] = step;\n            } else if (step > max2_step[i]) {\n                max2_step[i] = step;\n            }\n        }\n        int ans = 1e9;\n        for (int i = 0; i < k; ++i) {\n            ans = min(ans, max((max_step[i] + 1) / 2, max2_step[i]));\n        }\n        cout << ans - 1 << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1848",
    "index": "C",
    "title": "Vika and Price Tags",
    "statement": "Vika came to her favorite cosmetics store \"Golden Pear\". She noticed that the prices of $n$ items have changed since her last visit.\n\nShe decided to analyze how much the prices have changed and calculated the difference between the old and new prices for each of the $n$ items.\n\nVika enjoyed calculating the price differences and decided to continue this process.\n\nLet the old prices be represented as an array of non-negative integers $a$, and the new prices as an array of non-negative integers $b$. Both arrays have the same length $n$.\n\nIn one operation, Vika constructs a new array $c$ according to the following principle: $c_i = |a_i - b_i|$. Then, array $c$ renamed into array $b$, and array $b$ renamed into array $a$ at the same time, after which Vika repeats the operation with them.\n\nFor example, if $a = [1, 2, 3, 4, 5, 6, 7]$; $b = [7, 6, 5, 4, 3, 2, 1]$, then $c = [6, 4, 2, 0, 2, 4, 6]$. Then, $a = [7, 6, 5, 4, 3, 2, 1]$; $b = [6, 4, 2, 0, 2, 4, 6]$.\n\nVika decided to call a pair of arrays $a$, $b$ dull if after some number of such operations all elements of array $a$ become zeros.\n\nOutput \"YES\" if the original pair of arrays is dull, and \"NO\" otherwise.",
    "tutorial": "First of all, if $a_i$ and $b_i$ are both zero, then all numbers in the sequence will be zero. Otherwise, if one of the numbers $a_i, b_i$ is not zero, then if $a_i \\ge b_i$, after one operation, the sum $a_i - b_i + b_i = a_i$ will decrease relative to the original value, or if $b_i > a_i$, after two operations, the sum $b_i - a_i + a_i = b_i$ will also decrease relative to the original value. Since the sum of non-negative integers cannot decrease infinitely, eventually one of the numbers $a_i, b_i$ will become zero. Let the first such moment occur after $cnt_i$ operations. Then, notice that now zeros will alternate with a period of $3$. Therefore, in the problem, we need to check that all $cnt_i$ have the same remainder when divided by $3$. Thus, the problem reduces to finding $cnt_i$ for each pair of non-zero $a_i, b_i$ modulo $3$. Solution 1: Without loss of generality, assume $a_i \\ge b_i$, otherwise apply one operation. Then, the sequence of numbers will have the form: $(a_i, b_i, a_i - b_i, a_i - 2 \\cdot b_i, b_i, a_i - 3 \\cdot b_i, a_i - 4 \\cdot b_i, b_i, \\ldots)$. Let $a_i = k \\cdot b_i + r$. Then, using simple formulas, we can find the first moment when the neighboring pair of numbers becomes $r$ and $b_i$ in some order, and then simply find the answer for them. Thus, the problem can be solved using the generalized Euclidean algorithm. Solution 2: We will build the sequence from the end. Let's find the first moment when we obtain $0$. Before this zero, there is some number $d$. It can be easily proven that $d$ is exactly equal to $gcd(a_i, b_i)$. Now, let's divide each number in the sequence by $d$, and obtain a new sequence of numbers, where the last number is zero and the penultimate number is $1$. Then, let's denote even numbers as $0$ and odd numbers as $1$. In this way, the sequence can be uniquely reconstructed from the end: $(0, 1, 1, 0, 1, 1, 0, 1, 1, \\ldots)$. Thus, we can determine the remainder $cnt_i$ modulo $3$ by looking at the pair $(a_i / d, b_i / d)$ modulo $2$. The complexity of both solutions will be $O(n \\cdot \\log{a_i})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nint gcd(int a, int b) {\n    if (a == 0) {\n        return 0;\n    }\n    if (b == 0) {\n        return 1;\n    }\n    if (a >= b) {\n        int r = a % b;\n        int k = a / b;\n        if (k % 2 == 1) {\n            return gcd(b, r) + k + k / 2;\n        } else {\n            return gcd(r, b) + k + k / 2;\n        }\n    }\n    return 1 + gcd(b, abs(a - b));\n}\n \nint calc(int a, int b) {\n    if (a == 0) {\n        return 0;\n    }\n    if (b == 0) {\n        return 1;\n    }\n    return 1 + calc(b, abs(a - b));\n}\n \nint32_t main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        vector<int> b(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n        }\n        for (int i = 0; i < n; ++i) {\n            cin >> b[i];\n        }\n        set<int> cnt;\n        for (int i = 0; i < n; ++i) {\n            if (a[i] == 0 && b[i] == 0) {\n                continue;\n            }\n            cnt.insert(gcd(a[i], b[i]) % 3);\n        }\n        if (cnt.size() <= 1) {\n            cout << \"YES\" << endl;\n        } else {\n            cout << \"NO\" << endl;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1848",
    "index": "D",
    "title": "Vika and Bonuses",
    "statement": "A new bonus system has been introduced at Vika's favorite cosmetics store, \"Golden Pear\"!\n\nThe system works as follows: suppose a customer has $b$ bonuses. Before paying for the purchase, the customer can choose one of two options:\n\n- Get a discount equal to the current number of bonuses, while the bonuses are not deducted.\n- Accumulate an additional $x$ bonuses, where $x$ is the last digit of the number $b$. As a result, the customer's account will have $b+x$ bonuses.\n\nFor example, if a customer had $24$ bonuses, he can either get a discount of $24$ or accumulate an additional $4$ bonuses, after which his account will have $28$ bonuses.\n\nAt the moment, Vika has already accumulated $s$ bonuses.\n\nThe girl knows that during the remaining time of the bonus system, she will make $k$ more purchases at the \"Golden Pear\" store network.\n\nAfter familiarizing herself with the rules of the bonus system, Vika became interested in the maximum total discount she can get.\n\nHelp the girl answer this question.",
    "tutorial": "First, let's note that the optimal strategy for Vika will be to accumulate bonuses first and then only get the discount. This simple observation is proved by greedy considerations. Next, let's note that the last digit of the bonus number will either become zero after a few actions (in which case it makes no sense for Vika to accumulate more bonuses), or it will cycle through the digits $2$, $4$, $8$, $6$. To begin with, let's consider two options: whether Vika will accumulate bonuses at all or always choose the option to get the discount. In the second case, the answer is trivially calculated, but in the first case, we can use the above statement. Now let's consider four options for the last digit. With a fixed last digit, we can simulate the first actions until we reach that last digit. Then we need to determine how many times we will \"scroll\" through the digits $2$, $4$, $8$, $6$ for the best result. Let's say that at the moment of obtaining the desired last digit, Vika has accumulated $b$ bonuses and she can perform $a$ more actions. Then, if the cycle is \"scroll\" $x$ times, the discount will be $(b + 20 \\cdot x) \\cdot (a - x)$. This is a parabola equation. Its maximum can be found using the formula for the vertex of a parabola or by ternary search.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nint f(int s, int k) {\n    // (s + 20x) * (k - 4x)\n    // (-80)x^2 + (20k - 4s)x + (sk)\n    // -b/2a = (5k-s)/40\n    int x = (5 * k - s) / 40;\n    x = min(x, k / 4);\n    int res = s * k;\n    if (x > 0) {\n        res = max(res, (s + 20 * x) * (k - 4 * x));\n    }\n    x = min(x + 1, k / 4);\n    if (x > 0) {\n        res = max(res, (s + 20 * x) * (k - 4 * x));\n    }\n    return res;\n}\n \nint32_t main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int s, k;\n        cin >> s >> k;\n        int ans = s * k;\n        if (s % 10 == 5) {\n            ans = max(ans, (s + 5) * (k - 1));\n        } else if (s % 10) {\n            if (s % 2 == 1) {\n                s += s % 10;\n                --k;\n            }\n            for (int i = 0; i < 4; ++i) {\n                if (k > 0) {\n                    ans = max(ans, f(s, k));\n                }\n                s += s % 10;\n                --k;\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "math",
      "ternary search"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1848",
    "index": "E",
    "title": "Vika and Stone Skipping",
    "statement": "In Vika's hometown, Vladivostok, there is a beautiful sea.\n\nOften you can see kids skimming stones. This is the process of throwing a stone into the sea at a small angle, causing it to fly far and bounce several times off the water surface.\n\nVika has skimmed stones many times and knows that if you throw a stone from the shore perpendicular to the coastline with a force of $f$, it will first touch the water at a distance of $f$ from the shore, then bounce off and touch the water again at a distance of $f - 1$ from the previous point of contact. The stone will continue to fly in a straight line, reducing the distances between the points where it touches the water, until it falls into the sea.\n\nFormally, the points at which the stone touches the water surface will have the following coordinates: $f$, $f + (f - 1)$, $f + (f - 1) + (f - 2)$, ... , $f + (f - 1) + (f - 2) + \\ldots + 1$ (assuming that $0$ is the coordinate of the shoreline).\n\nOnce, while walking along the embankment of Vladivostok in the evening, Vika saw a group of guys skipping stones across the sea, launching them from the same point with different forces.\n\nShe became interested in what is the maximum number of guys who can launch a stone with their force $f_i$, so that all $f_i$ are \\textbf{different positive integers}, and all $n$ stones touched the water at the point with the coordinate $x$ (assuming that $0$ is the coordinate of the shoreline).\n\nAfter thinking a little, Vika answered her question. After that, she began to analyze how the answer to her question would change if she multiplied the coordinate $x$ by some positive integers $x_1$, $x_2$, ... , $x_q$, which she picked for analysis.\n\nVika finds it difficult to cope with such analysis on her own, so she turned to you for help.\n\nFormally, Vika is interested in the answer to her question for the coordinates $X_1 = x \\cdot x_1$, $X_2 = X_1 \\cdot x_2$, ... , $X_q = X_{q-1} \\cdot x_q$. Since the answer for such coordinates can be quite large, find it modulo $M$. \\textbf{It is guaranteed that $M$ is prime.}",
    "tutorial": "The key observation is that the answer for coordinate $x$ is the number of odd divisors of $x$. Let's prove this. Let's see how far a pebble will fly with force $f$, which touches the water $cnt$ times: $f + (f - 1) + \\ldots + (f - cnt + 1) = x$. If $cnt$ is even, then $x = (cnt / 2) \\cdot (2 \\cdot f - cnt + 1) = (p) \\cdot (2 \\cdot k + 1)$, where $p = cnt / 2, k = f - p$. In this case, the condition $f - cnt + 1 > 0$ is necessary, which is equivalent to $p \\le k$. If $cnt$ is odd, then $x = cnt \\cdot (f - (cnt - 1) / 2) = (2 \\cdot k + 1) \\cdot (p)$, where $p = (f - (cnt - 1) / 2), k = (cnt - 1) / 2$. Thus, the necessary condition $f - cnt + 1 > 0$ is equivalent to $p > k$. Therefore, for each odd divisor $2 \\cdot k + 1$ of the number $x$, we can uniquely associate one of the decomposition options, and hence the number of possible answers is exactly equal to the number of different odd divisors in the factorization of the number $x$. Using this observation, it is easy to obtain the answer. We will maintain the power of each prime number in the current coordinate. The answer is the product of (powers $+ 1$). In order to quickly understand how these quantities change, we will pre-calculate the factorization of all numbers from $1$ to $10^6$. Then the query can be processed by quickly recalculating the powers using the pre-calculated factorizations.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int K = 1e6;\n \n#define int long long\n \nint mod;\n \nint dp[K + 1];\nint cnt[K + 1];\n \nconst int MM = 3e6 + 7;\n \nint inv[MM];\n \nint cc = 0;\n \nint mul(int a, int b) {\n    int bb = b;\n    while (bb % mod == 0) {\n        ++cc;\n        bb /= mod;\n    }\n    return (a * (bb % mod)) % mod;\n}\n \nint dv(int a, int b) {\n    int bb = b;\n    while (bb % mod == 0) {\n        --cc;\n        bb /= mod;\n    }\n    return (a * inv[bb % mod]) % mod;\n}\n \n \nint32_t main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int x, q;\n    cin >> x >> q >> mod;\n    inv[1] = 1;\n    for (int i = 2; i < MM && i < mod; i++) {\n        inv[i] = mod - inv[mod % i] * (mod / i) % mod;\n    }\n    int y = x;\n    for (int i = 3; i <= K; i += 2) {\n        if (dp[i]) {\n            continue;\n        }\n        for (int j = i; j <= K; j += 2 * i) {\n            dp[j] = i;\n        }\n    }\n    int ans = 1;\n    while (x % 2 == 0) {\n        x /= 2;\n    }\n    for (int i = 3; i <= K; i += 2) {\n        while (x % i == 0) {\n            ans = dv(ans, cnt[i] + 1);\n            ++cnt[i];\n            ans = mul(ans, cnt[i] + 1);\n            x /= i;\n        }\n    }\n    int f = 1;\n    if (x > 1) {\n        ans = mul(ans, 2);\n    }\n    x = y;\n    for (int i = 0; i < q; ++i) {\n        int d;\n        cin >> d;\n        while (d % 2 == 0) {\n            d /= 2;\n        }\n        int k = d;\n        while (dp[k]) {\n            ans = dv(ans, cnt[dp[k]] + 1);\n            ++cnt[dp[k]];\n            ans = mul(ans, cnt[dp[k]] + 1);\n            k /= dp[k];\n        }\n        if (cc) {\n            cout << 0 << '\\n';\n        } else {\n            cout << ans << '\\n';\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1848",
    "index": "F",
    "title": "Vika and Wiki",
    "statement": "Recently, Vika was studying her favorite internet resource - Wikipedia.\n\nOn the expanses of Wikipedia, she read about an interesting mathematical operation bitwise XOR, denoted by $\\oplus$.\n\nVika began to study the properties of this mysterious operation. To do this, she took an array $a$ consisting of $n$ non-negative integers and applied the following operation to all its elements at the same time: $a_i = a_i \\oplus a_{(i+1) \\bmod n}$. Here $x \\bmod y$ denotes the remainder of dividing $x$ by $y$. The elements of the array are numbered starting from $0$.\n\nSince it is not enough to perform the above actions once for a complete study, Vika repeats them until the array $a$ becomes all zeros.\n\nDetermine how many of the above actions it will take to make all elements of the array $a$ zero. If this moment never comes, output $-1$.",
    "tutorial": "Let's denote $next(i, delta) = (i + delta \\bmod n) + 1$, and $a[cnt][i]$ represents the value of $a_i$ after $cnt$ operations. First, let's observe that if the array becomes all zeros, it will always remain all zeros. Therefore, we need to find the first moment in time when the array becomes all zeros. Furthermore, let's see how the array looks like after $2^t$ operations. We will prove by induction that $a[2^t][i] = a[0][i] \\oplus a[0][next(i, 2^t)]$ for each $i$. Indeed, for $t = 0$, this is true by definition, and for $t \\ge 1$: $a[2^t][i] = a[2^{t-1}][i] \\oplus a[2^{t-1}][next(i, 2^{t-1})] = a[0][i] \\oplus a[0][next(i, 2^{t-1})] \\oplus a[0][next(i, 2^{t-1})] \\oplus a[0][next(i, 2^t)] = a[0][i] \\oplus a[0][next(i, 2^t)]$. Thus, $a[n][i] = a[2^k][i] = a[0][i] \\oplus a[0][next(i, n)] = a[0][i] \\oplus a[0][i] = 0$, which means that after $n$ steps, the array becomes all zeros. Now, we want to find the minimum number of operations $c$ after which the array $a$ becomes all zeros, knowing that $c \\in [0, n]$. Let's check that $c \\le n / 2$, by explicitly constructing the array $a[n/2][i] = a[0][i] \\oplus a[0][next(i, n / 2)]$. The condition $c \\le n / 2$ is equivalent to all elements of the array $a[n/2][i]$ being zeros. The algorithm can be summarized as follows: Check if $a_i = a_{next(i, n/2)}$ for each $i$. If this is true, find the answer for the prefix of the array $a$ of length $n/2$. Otherwise, perform $n/2$ operations on the array $a$, specifically $a_i = a_i \\oplus a_{next(i, n / 2)}$. Now, the array satisfies the condition $a_i = a_{next(i, n/2)}$ for each $i$, so we only need to find the answer for its prefix of size $n/2$ and add $n/2$ to it. The overall complexity of the solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAXN = (1 << 20);\n \nint a[MAXN];\n \nint solve(int n) {\n    if (n == 1) {\n        if (a[0] == 0) {\n            return 0;\n        } else {\n            return 1;\n        }\n    }\n    int fl = true;\n    for (int i = 0; i < n / 2; ++i) {\n        if (a[i] != a[i + n / 2]) {\n            fl = false;\n        }\n    }\n    if (fl) {\n        return solve(n / 2);\n    }\n    for (int i = 0; i < n / 2; ++i) {\n        a[i] ^= a[i + n / 2];\n    }\n    return n / 2 + solve(n / 2);\n}\n \nint32_t main() {\n    int n;\n    scanf(\"%d\", &n);\n    for (int i = 0; i < n; ++i) {\n        scanf(\"%d\", &a[i]);\n    }\n    cout << solve(n) << endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "combinatorics",
      "divide and conquer",
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1849",
    "index": "A",
    "title": "Morning Sandwich",
    "statement": "Monocarp always starts his morning with a good ol' sandwich. Sandwiches Monocarp makes always consist of bread, cheese and/or ham.\n\nA sandwich always follows the formula:\n\n- a piece of bread\n- a slice of cheese or ham\n- a piece of bread\n- $\\dots$\n- a slice of cheese or ham\n- a piece of bread\n\nSo it always has bread on top and at the bottom, and it alternates between bread and filling, where filling is a slice of either cheese or ham. Each piece of bread and each slice of cheese or ham is called a layer.\n\nToday Monocarp woke up and discovered that he has $b$ pieces of bread, $c$ slices of cheese and $h$ slices of ham. What is the maximum number of layers his morning sandwich can have?",
    "tutorial": "Notice that the type of filling doesn't matter. We can treat both cheese and ham together as one filling, with quantity $c + h$. Then let's start building a sandwich layer by layer. Put a piece of bread. Then put a layer of filling and a piece of bread. Then another layer of filling and a piece of bread. Observe that you can add one layer of filling and one piece of bread until one of them runs out. After you've done that $k$ times, you placed $k + 1$ layers of bread and $k$ layers of filling. Thus, there are two general cases. If bread runs out first, then $k = b - 1$. Otherwise, $k = c + h$. The one that runs out first is the smaller of these two values. So the answer is $min(b - 1, c + h)$. Overall complexity: $O(1)$ per testcase.",
    "code": "\nfun main() = repeat(readLine()!!.toInt()) {\n\tval (b, c, h) = readLine()!!.split(' ').map { it.toInt() }\n\tprintln(minOf(b - 1, c + h) * 2 + 1)\n}\n",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1849",
    "index": "B",
    "title": "Monsters",
    "statement": "Monocarp is playing yet another computer game. And yet again, his character is killing some monsters. There are $n$ monsters, numbered from $1$ to $n$, and the $i$-th of them has $a_i$ health points initially.\n\nMonocarp's character has an ability that deals $k$ damage to the monster with the \\textbf{highest current health}. If there are several of them, \\textbf{the one with the smaller index is chosen}. If a monster's health becomes less than or equal to $0$ after Monocarp uses his ability, then it dies.\n\nMonocarp uses his ability until all monsters die. Your task is to determine the order in which monsters will die.",
    "tutorial": "Let's simulate the game process until the number of health points of each monster becomes $k$ or less. Then we can consider that the $i$-th monster has $a_i \\bmod k$ health instead of $a_i$ (except for the case when $a_i$ is divisible by $k$, then the remaining health is $k$, not $0$). Now, the health points of all monsters are from $1$ to $k$, so each time we damage a monster, we kill it. Therefore, monsters with $k$ health points will die first, then the ones with $k-1$ health points, and so on. So, let's sort the monsters by their remaining health points in descending order (don't forget that, if two monsters have the same health, then they should be compared by index). And the order you get after sorting is the answer to the problem.",
    "code": "\n#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n);\n    for (auto &x : a) {\n      cin >> x;\n      x %= k;\n      if (!x) x = k;\n    }\n    vector<int> ord(n);\n    iota(ord.begin(), ord.end(), 0);\n    stable_sort(ord.begin(), ord.end(), [&](int i, int j) {\n      return a[i] > a[j];\n    });\n    for (auto &x : ord) cout << x + 1 << ' ';\n    cout << endl;\n  }\n}\n",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1849",
    "index": "C",
    "title": "Binary String Copying",
    "statement": "You are given a string $s$ consisting of $n$ characters 0 and/or 1.\n\nYou make $m$ copies of this string, let the $i$-th copy be the string $t_i$. Then you perform exactly one operation on each of the copies: for the $i$-th copy, you sort its substring $[l_i; r_i]$ (the substring from the $l_i$-th character to the $r_i$-th character, both endpoints inclusive). \\textbf{Note that each operation affects only one copy, and each copy is affected by only one operation}.\n\nYour task is to calculate the number of different strings among $t_1, t_2, \\ldots, t_m$. Note that the initial string $s$ should be counted only if at least one of the copies stays the same after the operation.",
    "tutorial": "We can see that each modified copy is determined by only two integers $lb$ and $rb$ - the first position at which the character has changed and the last such position. If we can find such numbers for each of the copies, the number of different pairs will be the answer to the problem. Let $lf_i$ be the position of the nearest character 0 at the position $i$ or to the left of it, and $rg_i$ be the position of the nearest character 1 at the position $i$ or to the right of it. If the first character of the string $s$ is 1 then $lf_0 = -1$, otherwise $lf_0 = 0$. And if the last character of the string $s$ is 0, then $rg_{n - 1} = n$, otherwise $rg_{n - 1} = n - 1$. The values $lf$ and $rg$ can be calculated using simple dynamic programming, $lf$ is calculated from left to right, and $rg$ - from right to left. Then the numbers $lb$ and $rb$ we need are equal to $rg_l$ and $lf_r$, respectively. If $rg_l > lf_r$, then the changed segment is degenerate (and this means that the string does not change at all). We can define some special segment for this type of strings, for example, $(-1, -1)$. Otherwise, the segment $(rg_l, lf_r)$ of the string will change. Time complexity: $O(n \\log{n})$.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n, m;\n    string s;\n    cin >> n >> m >> s;\n    \n    vector<int> lf(n), rg(n);\n    lf[0] = -1;\n    for (int i = 0; i < n; ++i) {\n        if (i > 0) lf[i] = lf[i - 1];\n        if (s[i] == '0') lf[i] = i;\n    }\n    rg[n - 1] = n;\n    for (int i = n - 1; i >= 0; --i) {\n        if (i + 1 < n) rg[i] = rg[i + 1];\n        if (s[i] == '1') rg[i] = i;\n    }\n    \n    set<pair<int, int>> st;\n    for (int i = 0; i < m; ++i) {\n        int l, r;\n        cin >> l >> r;\n        int ll = rg[l - 1], rr = lf[r - 1];\n        if (ll > rr) {\n            st.insert({-1, -1});\n        } else {\n            st.insert({ll, rr});\n        }\n    }\n    \n    cout << st.size() << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif   \n    int t;\n    cin >> t;\n    while (t--) solve();\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "hashing",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1849",
    "index": "D",
    "title": "Array Painting",
    "statement": "You are given an array of $n$ integers, where each integer is either $0$, $1$, or $2$. Initially, each element of the array is blue.\n\nYour goal is to paint each element of the array red. In order to do so, you can perform operations of two types:\n\n- pay one coin to choose a blue element and paint it red;\n- choose a red element which is not equal to $0$ and a blue element \\textbf{adjacent} to it, decrease the chosen red element by $1$, and paint the chosen blue element red.\n\nWhat is the minimum number of coins you have to spend to achieve your goal?",
    "tutorial": "Suppose we used a second operation as follows: we decreased a red element $x$, and painted another element $y$ red. Let's then say that $x$ is the parent of $y$. Furthermore, let's say that the element $x$ controls the element $y$ if one of the two conditions applies: $x$ is the parent of $y$; $x$ controls the parent of $y$. Now, suppose we used coins to paint some elements red. For each of those elements, there exists a segment of red elements which it controls. So, the problem can actually be reformulated as follows: we want to split the given array into the minimum number of segments so that each segment can be painted using one coin. Let's call a segment of the array good if it can be painted using only one coin. To continue with our solution, we need the following property: if a segment is good, then its every subsegment is also good. This is kinda intuitive, but if you are interested in a formal proof, you can read the following paragraph. Formal proof: there are two main cases we need to consider: either the element that controls the main segment belongs to the subsegment we analyze, or it does not. In the first case, the proof is simple: we can paint all elements of the subsegment red using just one coin in the same way as we painted the whole segment, by starting from the element that controls it. In the second case, it is a bit more difficult, but instead of the element controlling the main segment, we can either start from the leftmost element of the subsegment, or from the rightmost element of the subsegment - depending on whether this subsegment is to the right or to the left of the element controlling the whole segment. This starting element will be painted red by spending a coin, and every other element of the subsegment can be painted red in the same way we painted the whole segment. Since if a segment is good, its every subsegment is also good, we can use the following greedy approach to solve the problem: start with the segment which contains only the first element of the array, and expand it to the right until it becomes bad. When the segment is no longer good, we need to start a new segment, which we will again expand to the right until it becomes bad, and so on. Then each element of the array will be considered only once. If we design a way to determine if the segment is still good when we add a new element to it in $O(1)$, our solution will work in $O(n)$. All that's left is to analyze how to check if the segment is good. There are multiple ways to do this. The way used in the model solution employs the following ideas: there cannot be any zeroes in the middle of the segment, since if we start painting red from the left of that zero, we cannot reach the elements to the right of that zero, and vice versa; if there are no zeroes in the middle, and at least one of the endpoints is not zero, the segment is good because we can just start from that endpoint and expand to the other endpoint; if there are no zeroes in the middle, and there is at least one element equal to $2$, we can start by painting that element red and expand to the left and to the right of it until we arrive at the borders of the segment; and if there are zeroes at both endpoints, but all other elements are $1$'s, it's easy to see that paining the whole segment using only one coin is impossible: the sum of elements on the segment is $k-2$, where $k$ is the length of the segment, but we need to paint at least $k-1$ elements red without spending coins. All of these ideas allow us to verify that the segment is good using just a couple if-statements. Solution complexity: $O(n)$.",
    "code": "\nn = int(input())\na = list(map(int, input().split()))\n\nans = 0\nl = 0\nwhile l < n:\n    r = l + 1\n    hasTwo = (a[l] == 2)\n    hasMiddleZero = False\n    while r < n:\n        if r - 1 > l and a[r - 1] == 0:\n            hasMiddleZero = True\n        if a[r] == 2:\n            hasTwo = True\n        good = (not hasMiddleZero) and (hasTwo or a[l] != 0 or a[r] != 0)\n        if not good:\n            break\n        r += 1\n    l = r\n    ans += 1\n    \nprint(ans)\n",
    "tags": [
      "constructive algorithms",
      "greedy",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1849",
    "index": "E",
    "title": "Max to the Right of Min",
    "statement": "You are given a permutation $p$ of length $n$ — an array, consisting of integers from $1$ to $n$, all distinct.\n\nLet $p_{l,r}$ denote a subarray — an array formed by writing down elements from index $l$ to index $r$, inclusive.\n\nLet $\\mathit{maxpos}_{l,r}$ denote the \\textbf{index} of the maximum element on $p_{l,r}$. Similarly, let $\\mathit{minpos}_{l,r}$ denote the index of the minimum element on it.\n\nCalculate the number of subarrays $p_{l,r}$ such that $\\mathit{maxpos}_{l,r} > \\mathit{minpos}_{l,r}$.",
    "tutorial": "The problem was originally prepared as part of the lecture on a monotonic stack. Thus, I will omit its explanation. First, recall a common technique of counting all segments satisfying some property. You can count the segments that have the same right border at the same time. Consider all segments $[l, r]$ with a fixed $r$. How do the minimums and the maximums on them change from each other? If you look at the segments in the order of decreasing $l$, we can write down the sequence of the following events: the minimum becomes smaller or the maximum becomes larger. In fact, we can maintain both of these types with two monotonic stacks. Now, which $l$ correspond to good segments with regard to the events? Consider two adjacent events $(i_1, t_1)$ and $(i_2, t_2)$, where $i_j$ is the index of the event and $t_j$ is the type ($0$ for min, $1$ for max). It's easy to see that if $t_2 = 0$, then all segments that have $l$ from $i_1 + 1$ to $i_2$ are good. It means that, while going from right to left, the last event we encountered was the minimum getting smaller. Thus, the index of the minimum becomes to the left from the index of the maximum. As for the implementation, we will maintain these events in a set of pairs: (index of the event, type of the event). This way, it's not that hard to maintain the sum of distances from each event of type $0$ to the left to the previous event. When you erase an event, only a few distances can be affected: the distance from the next one to the current one, from the current one to the previous one and the newly created distance from the next one to the previous one. Just check for the types. When you add an event, you only add it to the very end of the set, so it's trivial to recalculate. That will be $O(n \\log n)$ just from the set, the monotonic stacks by themselves are linear. You can optimize this solution to $O(n)$ by using a doubly-linked list, but it really was not necessary for the problem. There's also a different solution for which you can maintain the intervals of good values $l$ explicitly. First, compress them in such a way that the segments don't touch at borders. Now, you can notice that by going from $r$ to $r+1$ we can only affect the rightmost ones of them: possibly remove some, then change the last one and add a new one. So we can actually simulate this behavior with another stack. The details are left as an exercise to a reader. With the correct implementation, this solution will be $O(n)$.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nbool comp(const pair<int, int> &a, const pair<int, int> &b){\n    return a.second < b.second;\n}\n\nint main(){\n    int n;\n    scanf(\"%d\", &n);\n    vector<pair<int, int>> stmn, stmx;\n    stmn.push_back({-1, -1});\n    stmx.push_back({n, -1});\n    long long ans = 0;\n    int len = 0;\n    set<pair<int, int>> cur;\n    cur.insert({-1, 0});\n    cur.insert({-1, 1});\n    for (int i = 0; i < n; ++i){\n        int x;\n        scanf(\"%d\", &x);\n        --x;\n        \n        while (stmn.back().first > x){\n            auto it = cur.lower_bound({stmn.back().second, 0});\n            auto me = it;\n            auto prv = it; --prv;\n            ++it;\n            len -= me->first - prv->first;\n            if (it != cur.end() && it->second == 0)\n                len += it->first - prv->first;\n            cur.erase(me);\n            stmn.pop_back();\n        }\n        len += i - cur.rbegin()->first;\n        cur.insert({i, 0});\n        stmn.push_back({x, i});\n        \n        while (stmx.back().first < x){\n            auto it = cur.lower_bound({stmx.back().second, 1});\n            auto me = it;\n            auto prv = it; --prv;\n            ++it;\n            if (it != cur.end() && it->second == 0)\n                len += me->first - prv->first;\n            cur.erase(me);\n            stmx.pop_back();\n        }\n        cur.insert({i, 1});\n        stmx.push_back({x, i});\n        \n        ans += len;\n    }\n    printf(\"%lld\\n\", ans - n);\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dp",
      "dsu",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1849",
    "index": "F",
    "title": "XOR Partition",
    "statement": "For a set of integers $S$, let's define its cost as the minimum value of $x \\oplus y$ among all pairs of \\textbf{different} integers from the set (here, $\\oplus$ denotes bitwise XOR). If there are less than two elements in the set, its cost is equal to $2^{30}$.\n\nYou are given a set of integers $\\{a_1, a_2, \\dots, a_n\\}$. You have to partition it into two sets $S_1$ and $S_2$ in such a way that every element of the given set belongs to exactly one of these two sets. The value of the partition is the \\textbf{minimum} among the costs of $S_1$ and $S_2$.\n\nFind the partition with the \\textbf{maximum} possible value.",
    "tutorial": "Disclaimer: the model solution to this problem is a bit more complicated than most of the solutions written by participants, but I will still use it for the editorial so that I can explain some of the classical techniques appearing in it. Suppose we have built a graph on $n$ vertices, where each pair of vertices is connected by an edge, and the weight of the edge connecting $i$ with $j$ is $a_i \\oplus a_j$. If we treat the partition of the set as a coloring of this graph, then the cost of the partition is equal to the minimum weight of an edge connecting two vertices of the same color. So, suppose we want to check that the answer is at least $x$. It means that every edge with weight less than $x$ should connect two vertices of different colors; so, the graph where we erase all edges with weight greater than or equal to $x$ should be bipartite. This allows us to write a binary search solution if we somehow understand how to construct the graph and check that it is bipartite implicitly, but this is not the way the model solution goes. Instead, suppose we do the following greedy. Initially, let the graph be empty. Then, we add all edges with weight $1$, and check if it is bipartite. Then, we add all edges with weight $2$, and check if it is bipartite. And so on, until the graph is no longer bipartite. Of course, there are $O(n^2)$ edges, so this is too slow. But in fact, we don't need all the edges for this graph. Some of the edges we added didn't really affect the coloring of the graph: if, in this process, we add an edge which connects two vertices from the same component, one of the following two things happens: if it connects two vertices of the same color, then the graph is no longer bipartite; otherwise, this edge actually does not change anything in the coloring. Now, suppose we stop before making the graph non-bipartite. It means if an edge we added was connecting two vertices from the same component, that edge was actually redundant. Let's take a look again at what we're actually doing. Initially, the graph is empty. Then, we consider all possible edges in ascending order of their weights; if an edge connects two vertices in different components, it should be added to the graph (and it affects the coloring), otherwise, it does not matter (unless it makes us stop the algorithm, since the graph is no longer bipartite). Doesn't it sound familiar? Yup, it is almost like Kruskal's algorithm. And in fact, the problem can be solved as follows: build any MST of this graph, and use it to form the two-coloring (paint the vertices in such a way that every edge from MST connects two vertices of different colors). The paragraph below contains the formal proof that this coloring is optimal; feel free to skip it if you're not interested in the strict proof. Formal proof: suppose that, if we color the vertices using the MST, we get an answer equal to $x$. This means that there are two vertices $i$ and $j$ such that their colors are the same, and $a_i \\oplus a_j = x$. Let us consider the cycle formed by the edge from $i$ to $j$ and the path from $j$ to $i$ in the MST. Since these two vertices have the same colors, this cycle contains an odd number of edges - so, at least one edge on this cycle will connect vertices of the same color no matter how we paint the graph. And there are no edges on this cycle with weight greater than $x$ - otherwise, that edge would be replaced by the edge $(i,j)$ in the MST. So, at least one edge with weight $\\le x$ will be connecting two vertices of the same color, and thus the answer cannot be greater than $x$. Okay, now we have to actually build the MST in this graph. XOR-MST is a fairly classical problem (it was even used in one of the previous Educational Rounds several years ago). I know two different solutions to it: the one based on Boruvka's algorithm and the D&C + trie merging method. I will describe the former one. The classical Boruvka's algorithm is one of the algorithms of finding a minimum spanning tree. It begins with a graph containing no edges, and performs several iterations until it becomes connected. On each iteration, the algorithm considers each component of the graph and adds the minimum edge connecting any vertex from this component with any vertex outside this component (these edges are added at the same time for all components of the graph, so be careful about creating a cycle or adding the same edge twice; different methods can be used to prevent this - in the model solution, I memorize the edges I want to add on each iteration, then use a DSU to actually check which ones should be added without causing a cycle to appear). During each iteration of the algorithm, the number of components decreases to at least half of the original number, so the algorithm works in $O(I \\log n)$, where $I$ is the complexity of one iteration. Usually, $I$ is $O(m)$ since we need to consider each edge of the graph twice; but in this problem, we can perform one iteration of Boruvka's algorithm much faster, in $O(n \\log A)$, where $A$ is the constraint on the numbers in the input. It can be done as follows: maintain a trie data structure which stores all values of $a_i$ and allows processing a query \"given an integer $x$, find the value $y$ in the data structure such that $x \\oplus y$ is the minimum possible\" (this can be done with a trie descent). When we consider a component and try to find the minimum edge leading outside of it, we first delete all vertices belonging to this component from the data structure; then, for each vertex from the component, find the best vertex in the data structure; and then, insert all vertices back. That way, a component of size $V$ will be processed in $O(V \\log A)$, and the total time for one iteration is $O(n \\log A)$. All of this results in a solution with complexity $O(n \\log n \\log A)$.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define pb push_back\n#define mp make_pair\n#define forn(i, n) for (int i = 0; i < (int)(n); ++i)\ntypedef long long LL;\ntypedef pair<int, int> PII;\n\nconst int N = 200000;\nconst int NODES = 32 * N;\nconst int INF = int(2e9);\n\nint n;\nint a[N];\nint nx[NODES][2], cnt[NODES], fn[NODES];\nint nodeCount = 1;\n\nvoid addInt(int x, int pos) {\n    int ind = 0;\n    for (int i = 29; i >= 0; --i) {\n        int bit = (x >> i) & 1;\n        if (nx[ind][bit] == 0) {\n            nx[ind][bit] = nodeCount++;\n        }\n        ind = nx[ind][bit];\n        ++cnt[ind];\n    }\n    fn[ind] = pos;\n}\n\nvoid addInt(int x) {\n    int ind = 0;\n    for (int i = 29; i >= 0; --i) {\n        int bit = (x >> i) & 1;\n        ind = nx[ind][bit];\n        ++cnt[ind];\n    }\n}\n\nvoid removeInt(int x) {\n    int ind = 0;\n    for (int i = 29; i >= 0; --i) {\n        int bit = (x >> i) & 1;\n        ind = nx[ind][bit];\n        --cnt[ind];\n    }\n}\n\nPII findXor(int x) {\n    int ind = 0, res = 0;\n    for (int i = 29; i >= 0; --i) {\n        int bit = (x >> i) & 1;\n        if (cnt[nx[ind][bit]]) {\n            ind = nx[ind][bit];\n        } else {\n            ind = nx[ind][bit ^ 1];\n            res |= 1 << i;\n        }\n    }\n    return mp(res, fn[ind]);\n}\n\nint par[200000], ra[200000];\n\nvoid dsuInit() {\n    forn(i, n) par[i] = i, ra[i] = 1;\n}\n\nint dsuParent(int v) {\n    if (v == par[v]) return v;\n    return par[v] = dsuParent(par[v]);\n}\n\nint dsuMerge(int u, int v) {\n    u = dsuParent(u);\n    v = dsuParent(v);\n    if (u == v) return 0;\n    if (ra[u] < ra[v]) swap(u, v);\n    par[v] = u;\n    ra[u] += ra[v];\n    return 1;\n}\n\nvector<int> v[200000];\nvector<pair<int, PII> > toMerge;\nvector<int> g[200000];\nint color[200000];\n\nvoid coloring(int x, int c){\n\tif(color[x] != -1) return;\n\tcolor[x] = c;\n\tfor(auto y : g[x]) coloring(y, c ^ 1);\n}\n\nint main() {\n    scanf(\"%d\", &n);\n    forn(i, n) scanf(\"%d\", a + i);\n    forn(i, n) addInt(a[i], i);\n    dsuInit();\n    for (int merges = 0; merges < n - 1; ) {\n        forn(i, n) v[i].clear();\n        forn(i, n) v[dsuParent(i)].pb(i);\n        toMerge.clear();\n        forn(i, n) if (!v[i].empty()) {\n            for (int x : v[i]) {\n                removeInt(a[x]);\n            }\n            pair<pair<int, int>, int> res = mp(mp(INF, INF), INF);\n            for (int x : v[i]) {\n                res = min(res, mp(findXor(a[x]), x));\n            }\n            toMerge.pb(mp(res.first.first, mp(res.second, res.first.second)));\n            for (int x : v[i]) {\n                addInt(a[x]);\n            }\n        }\n        for (auto p : toMerge) {\n            if (dsuMerge(p.second.first, p.second.second)) {\n                ++merges;\n\t\t\t\tg[p.second.first].pb(p.second.second);\n\t\t\t\tg[p.second.second].pb(p.second.first);\n            }\n        }\n    }\n\tforn(i, n) color[i] = -1;\n\tcoloring(0, 1);\n\tforn(i, n) printf(\"%d\", color[i]);\n\tputs(\"\");\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "divide and conquer",
      "greedy",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1850",
    "index": "A",
    "title": "To My Critics",
    "statement": "Suneet has three digits $a$, $b$, and $c$.\n\nSince math isn't his strongest point, he asks you to determine if you can choose any two digits to make a sum greater or equal to $10$.\n\nOutput \"YES\" if there is such a pair, and \"NO\" otherwise.",
    "tutorial": "One way to solve the problem is to check if $a + b + c - min(a, b, c) \\geq 10$ using an if statement.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n    int a, b, c;\n    cin >> a >> b >> c;\n    cout << (a+b+c-min({a,b,c}) >= 10 ? \"YES\\n\" : \"NO\\n\");\n    \n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        solve();\n    }\n}\n \n\n",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1850",
    "index": "B",
    "title": "Ten Words of Wisdom",
    "statement": "In the game show \"Ten Words of Wisdom\", there are $n$ participants numbered from $1$ to $n$, each of whom submits one response. The $i$-th response is $a_i$ words long and has quality $b_i$. No two responses have the same quality, and at least one response has length at most $10$.\n\nThe winner of the show is the response which has the highest quality out of all responses that are not longer than $10$ words. Which response is the winner?",
    "tutorial": "Let's iterate through all responses: if it has $> 10$ words, ignore it. Otherwise, keep track of the maximum quality and its index, and update it as we go along. Then output the index with maximum quality. The time complexity is $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tint winner = -1, best_score = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tif (b > best_score && a <= 10) {winner = i; best_score = b;}\n\t}\n\tcout << winner << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1850",
    "index": "C",
    "title": "Word on the Paper",
    "statement": "On an $8 \\times 8$ grid of dots, a word consisting of lowercase Latin letters is written vertically in one column, from top to bottom. What is it?",
    "tutorial": "You can iterate through the grid and then once you find a letter, iterate downwards until you get the whole word. However there is an approach that is even faster to code: just input each character, and output it if it is not a dot. This works because we will input the characters in the same order from top to bottom. The complexity is $\\mathcal{O}(1)$ regardless.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nvoid solve() {\n\tfor (int r = 0; r < 8; r++) {\n\t\tfor (int c = 0; c < 8; c++) {\n\t\t\tchar x;\n\t\t\tcin >> x;\n\t\t\tif (x != '.') {cout << x;}\n\t\t}\n\t}\t\n\tcout << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1850",
    "index": "D",
    "title": "Balanced Round",
    "statement": "You are the author of a Codeforces round and have prepared $n$ problems you are going to set, problem $i$ having difficulty $a_i$. You will do the following process:\n\n- remove some (possibly zero) problems from the list;\n- rearrange the remaining problems in any order you wish.\n\nA round is considered balanced if and only if the absolute difference between the difficulty of any two consecutive problems is at most $k$ (less or equal than $k$).\n\nWhat is the minimum number of problems you have to remove so that an arrangement of problems is balanced?",
    "tutorial": "Let's calculate the maximum number of problems we can take, and the answer will be $n$ subtracted by that count. An arrangement that always minimizes the absolute difference between adjacent pairs is the array in sorted order. What we notice, is that if the array is sorted, we will always take a subarray (all taken elements will be consecutive). So, the problem converts to finding the largest subarray for which $a_i - a_{i-1} \\leq k$. It's easy to see that all the subarrays are totally different (don't share any intersection of elements), thus, we can maintain a count variable of the current number of elements in the current subarray, and iterate through array elements from left to right. If we currently are at $i$ and $a_i - a_{i-1} > k$ then we just set the count to $1$ since we know a new subarray starts, otherwise, we just increase our count by $1$. The answer will be $n$ subtracted by the largest value that our count has achieved.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n \nvoid solve() {\n    int n, k; cin >> n >> k;\n    vector<int> a(n);\n    for(int i = 0; i < n; ++i) cin >> a[i];    \n    sort(all(a));\n    int cnt = 1, ans = 1;\n    for(int i = 1; i < n; ++i) {\n        if(a[i] - a[i - 1] > k) {\n            cnt = 1;\n        } else {\n            ++cnt;\n        }\n        ans = max(ans, cnt);\n    }\n    cout << n - ans << '\\n';\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}\n\n",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1850",
    "index": "E",
    "title": "Cardboard for Pictures",
    "statement": "Mircea has $n$ pictures. The $i$-th picture is a square with a side length of $s_i$ centimeters.\n\nHe mounted each picture on a square piece of cardboard so that each picture has a border of $w$ centimeters of cardboard on all sides. In total, he used $c$ square centimeters of cardboard. Given the picture sizes and the value $c$, can you find the value of $w$?\n\n\\begin{center}\n{\\small A picture of the first test case. Here $c = 50 = 5^2 + 4^2 + 3^2$, so $w=1$ is the answer.}\n\\end{center}\n\nPlease note that the piece of cardboard goes behind each picture, not just the border.",
    "tutorial": "The key idea is to binary search on the answer. If you don't know what that is, you should read this Codeforces EDU article. Let's make a function $f(x)$, which tells us the total area of cardboard if we use a width of $x$. Then you can see that we can calculate $f(x)$ in $\\mathcal{O}(n)$ time as $(a_1 + 2x)^2 + (a_2 + 2x)^2 + \\dots + (a_n + 2x)^2$, because the side length of the $i$-th cardboard is $a_i + 2x$. So this means that now we can binary search on the answer: let's find the largest $w$ so that $f(w) \\leq c$. The maximum theoretical value of $w$ can be seen not to exceed $10^9$, since $c$ is not more than $10^{18}$ (you can set an even lower bound). A quick note about implementation: the value of $f(x)$ can exceed 64-bit numbers, so you need to exit the function as soon as you get a value greater than $c$, or else you risk overflow. So the time complexity is $\\mathcal{O}(n \\log(10^9))$ per test case, which is equal to $\\mathcal{O}(n)$ with some constant factor. It's not that big to make it fail. You can also use the quadratic formula, but be careful about implementation of square root and precision issues.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n \n#define int long long\n \nvoid solve() {\n    int n, c; cin >> n >> c;\n    vector<int> a(n);\n    for(int i = 0; i < n; ++i) cin >> a[i];\n    int l = 1, r = 1e9;\n    while(l <= r) {\n        int mid = l + (r - l) / 2;\n        int sumall = 0;\n        for(int i = 0; i < n; ++i) {\n            sumall += (a[i] + 2 * mid) * (a[i] + 2 * mid);\n            if(sumall > c) break;\n        }\n        if(sumall == c) {\n            cout << mid << \"\\n\";\n            return;\n        }\n        if(sumall > c) {\n            r = mid - 1;\n        } else {\n            l = mid + 1;\n        }\n    }\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}\n\n",
    "tags": [
      "binary search",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1850",
    "index": "F",
    "title": "We Were Both Children",
    "statement": "Mihai and Slavic were looking at a group of $n$ frogs, numbered from $1$ to $n$, all initially located at point $0$. Frog $i$ has a hop length of $a_i$.\n\nEach second, frog $i$ hops $a_i$ units forward. Before any frogs start hopping, Slavic and Mihai can place \\textbf{exactly one} trap in a coordinate in order to catch all frogs that will ever pass through the corresponding coordinate.\n\nHowever, the children can't go far away from their home so they can only place a trap in the first $n$ points (that is, in a point with a coordinate between $1$ and $n$) and the children can't place a trap in point $0$ since they are scared of frogs.\n\nCan you help Slavic and Mihai find out what is the maximum number of frogs they can catch using a trap?",
    "tutorial": "We disregard any $a_i$ larger than $n$ since we can't catch them anyway. We keep in $cnt_i$ how many frogs we have for each hop distance. We go through each $i$ from $1$ to $n$ and add $cnt_i$ to every multiple of $i$ smaller or equal to $n$. This action is a harmonic series and takes $O(nlogn)$ time. We go through all from $1$ to $n$ and take the maximum.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n \nvoid solve() {\n    int n; cin >> n;\n    vector<ll> cnt(n + 1, 0), mx(n + 1, 0);\n    for(int i = 0; i < n; ++i) {\n        int x; cin >> x;\n        if(x <= n) ++cnt[x];\n    }\n    for(int i = 1; i <= n; ++i) {\n        for(int j = i; j <= n; j += i) mx[j] += cnt[i];\n    }\n    cout << *max_element(all(mx)) << \"\\n\";\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}\n\n",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1850",
    "index": "G",
    "title": "The Morning Star",
    "statement": "A compass points directly toward the morning star. It can only point in one of eight directions: the four cardinal directions (N, S, E, W) or some combination (NW, NE, SW, SE). Otherwise, it will break.\n\n\\begin{center}\n{\\small The directions the compass can point.}\n\\end{center}\n\nThere are $n$ distinct points with integer coordinates on a plane. How many ways can you put a compass at one point and the morning star at another so that the compass does not break?",
    "tutorial": "Let's look at four directions of the line connecting the compass and morning star: vertical, horizontal, with slope $1$ (looks like /), and with slope $-1$ (looks like \\). vertical: the two points need to have the same $y$-coordinate. If there are $k$ points with the same $y$-coordinate, then how many pairs are possible for the morning star and compass? Well, there are $k$ possibilities for the compass, and $k-1$ for the morning star, so there are a total of $k(k-1)$ valid pairs. In this case, we can use a data structure like a C++ map to count the number of points at each $y$-coordinate, and add $k(k-1)$ to the total for each $k$ in the map. horizontal: the two points need to have the same $x$-coordinate. Similarly, we count pairs with the same $x$-coordinate using a map. slope $1$: note that all lines of this form can be written as $x-y=c$ for a constant $c$. (Draw some examples out for $c=-1, 0, 1$.) So we can use a map to count values of $x-y$, and add to the total. slope $-1$: similarly, all such lines can be written as $x+y=c$ for a constant $c$.",
    "code": "#include <bits/stdc++.h>\n#define startt ios_base::sync_with_stdio(false);cin.tie(0);\ntypedef long long  ll;\nusing namespace std;\n#define vint vector<int>\n#define all(v) v.begin(), v.end()\n#define int long long\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    map<int, int> up, side, diag1, diag2;\n    int ans = 0;\n    for(int i = 0; i < n; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n        up[x]++;\n        side[y]++;\n        diag1[x-y]++;\n        diag2[x+y]++;\n    }\n    for(auto x : up)\n    {\n        ans+=x.second*(x.second-1);\n    }\n    for(auto x : side)\n    {\n        ans+=x.second*(x.second-1);\n    }\n    for(auto x : diag1)\n    {\n        ans+=x.second*(x.second-1);\n    }for(auto x : diag2)\n    {\n        ans+=x.second*(x.second-1);\n    }\n    cout << ans << endl;\n}\n \nint32_t main(){\n    startt\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n \n \n \n\n",
    "tags": [
      "combinatorics",
      "data structures",
      "geometry",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1850",
    "index": "H",
    "title": "The Third Letter",
    "statement": "In order to win his toughest battle, Mircea came up with a great strategy for his army. He has $n$ soldiers and decided to arrange them in a certain way in camps. Each soldier has to belong to exactly one camp, and there is one camp at each integer point on the $x$-axis (at points $\\cdots, -2, -1, 0, 1, 2, \\cdots$).\n\nThe strategy consists of $m$ conditions. Condition $i$ tells that soldier $a_i$ should belong to a camp that is situated $d_i$ meters in front of the camp that person $b_i$ belongs to. (If $d_i < 0$, then $a_i$'s camp should be $-d_i$ meters behind $b_i$'s camp.)\n\nNow, Mircea wonders if there exists a partition of soldiers that respects the condition and he asks for your help! Answer \"YES\" if there is a partition of the $n$ soldiers that satisfies \\textbf{all} of the $m$ conditions and \"NO\" otherwise.\n\nNote that two different soldiers \\textbf{may} be placed in the same camp.",
    "tutorial": "We can view the conditions and soldiers as a directed graph. The soldiers represent nodes and the conditions represent directed edges. Saying $a_i$ should be $d_i$ meters in front of $b_i$ is equivalent to adding two weighted directed edges: An edge from $a_i$ to $b_i$ with weight $d_i$. An edge from $b_i$ to $a_i$ with weight $-d_i$. Now, we iterate over all $n$ soldiers, and do a standard dfs whenever we encounter an unvisited soldier, assigning coordinates respecting the weights of the edges. That is, for the first soldier in the set we can just set his coordinate to $0$, then for every neighbor we visit we set it's coordinate to the coordinate of the current node added by the weight of the edge between it and its neighbor. Finally, we check at the end if all of the $m$ conditions are satisfied.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n \n#define int long long\nconst int N = 2e5 + 5;\nvector<pair<int, int>> adj[N];\nint val[N], vis[N];\nvoid dfs(int u) {\n    vis[u] = 1;\n    for(auto x: adj[u]) {\n        int v = x.first, w = x.second;\n        if(!vis[v]) {\n            val[v] = val[u] + w;\n            dfs(v);\n        }\n    }\n}\nvoid solve() {\n    int n, m; cin >> n >> m;\n    for(int i = 1; i <= n; ++i) {\n        adj[i].clear();\n        vis[i] = 0, val[i] = 0;\n    }\n    vector<array<int, 3>> c;\n    for(int i = 1; i <= m; ++i) {\n        int a, b, d; cin >> a >> b >> d;\n        adj[a].pb({b, d});\n        adj[b].pb({a, -d}); \n        c.pb({a, b, d});  \n    }\n    for(int i = 1; i <= n; ++i) {\n        if(!vis[i]) dfs(i);\n    }\n    for(int i = 1; i <= m; ++i) {\n        int a = c[i - 1][0], b = c[i - 1][1], d = c[i - 1][2];\n        if(val[a] + d != val[b]) {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    cout << \"YES\\n\";\n}   \n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}\n\n",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1851",
    "index": "A",
    "title": "Escalator Conversations",
    "statement": "One day, Vlad became curious about who he can have a conversation with on the escalator in the subway. There are a total of $n$ passengers. The escalator has a total of $m$ steps, all steps indexed from $1$ to $m$ and $i$-th step has height $i \\cdot k$.\n\nVlad's height is $H$ centimeters. Two people with heights $a$ and $b$ can have a conversation on the escalator if they are standing on \\textbf{different} steps and the height difference between them is equal to the height difference between the steps.\n\nFor example, if two people have heights $170$ and $180$ centimeters, and $m = 10, k = 5$, then they can stand on steps numbered $7$ and $5$, where the height difference between the steps is equal to the height difference between the two people: $k \\cdot 2 = 5 \\cdot 2 = 10 = 180 - 170$. There are other possible ways.\n\nGiven an array $h$ of size $n$, where $h_i$ represents the height of the $i$-th person. Vlad is interested in how many people he can have a conversation with on the escalator \\textbf{individually}.\n\nFor example, if $n = 5, m = 3, k = 3, H = 11$, and $h = [5, 4, 14, 18, 2]$, Vlad can have a conversation with the person with height $5$ (Vlad will stand on step $1$, and the other person will stand on step $3$) and with the person with height $14$ (for example, Vlad can stand on step $3$, and the other person will stand on step $2$). Vlad cannot have a conversation with the person with height $2$ because even if they stand on the extreme steps of the escalator, the height difference between them will be $6$, while their height difference is $9$. Vlad cannot have a conversation with the rest of the people on the escalator, so the answer for this example is $2$.",
    "tutorial": "For each person in the array $h$, we will check the conditions. First, the height should not be the same as Vlad's height, then their difference should be divisible by $k$, and finally, the difference between the extreme steps should not exceed the difference in height. If these requirements are met, there will be steps where Vlad can talk to a person with that height.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define sz(v) (int)v.size()\n#define all(v) v.begin(),v.end()\n#define eb emplace_back\n\n\n\nvoid solve() {\n    int n,m,k,H; cin >> n >> m >> k >> H;\n    int ans = 0;\n    forn(i, n) {\n        int x; cin >> x;\n        ans += (H != x) && abs(H - x) % k == 0 && abs(H-x) <= (m-1) * k;\n    }\n    cout << ans << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n\n    forn(tt, t) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1851",
    "index": "B",
    "title": "Parity Sort",
    "statement": "You have an array of integers $a$ of length $n$. You can apply the following operation to the given array:\n\n- Swap two elements $a_i$ and $a_j$ such that $i \\neq j$, $a_i$ and $a_j$ are either \\textbf{both} even or \\textbf{both} odd.\n\nDetermine whether it is possible to sort the array in non-decreasing order by performing the operation any number of times (possibly zero).\n\nFor example, let $a$ = [$7, 10, 1, 3, 2$]. Then we can perform $3$ operations to sort the array:\n\n- Swap $a_3 = 1$ and $a_1 = 7$, since $1$ and $7$ are odd. We get $a$ = [$1, 10, 7, 3, 2$];\n- Swap $a_2 = 10$ and $a_5 = 2$, since $10$ and $2$ are even. We get $a$ = [$1, 2, 7, 3, 10$];\n- Swap $a_4 = 3$ and $a_3 = 7$, since $3$ and $7$ are odd. We get $a$ = [$1, 2, 3, 7, 10$].",
    "tutorial": "Let's copy array $a$ to array $b$. Then sort array $b$. Let's check that for each $1 \\le i \\le n$ it is satisfied that $(a_i \\bmod 2) = (b_i \\bmod 2)$, where $\\bmod$ is the operation of taking the remainder from division. In other words, we need to check that in the sorted array $b$, the element at the $i$-th position has the same parity as the element at the $i$-th position in the unsorted array $a$. This is true because any array can be sorted using at most $n^2$ operations, in which any two elements are swapped. Consequently, if the parity of the elements in the sorted array is preserved, then the even and odd subsequences of the elements can be sorted separately, and the answer is YES. If the parity of the elements is not preserved after sorting, the answer is NO.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nbool solve(){\n    int n;\n    cin >> n;\n    vector<int>a(n), b(n);\n    for(int i = 0; i < n; i++){\n        cin >> a[i];\n        b[i] = a[i];\n    }\n    sort(b.begin(), b.end());\n    for(int i = 0; i < n; i++){\n        if((a[i] % 2) != (b[i] % 2)) return false;\n    }\n    return true;\n\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        cout << (solve() ? \"YES\" : \"NO\") << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1851",
    "index": "C",
    "title": "Tiles Comeback",
    "statement": "Vlad remembered that he had a series of $n$ tiles and a number $k$. The tiles were numbered from left to right, and the $i$-th tile had colour $c_i$.\n\nIf you stand on the \\textbf{first} tile and start jumping any number of tiles \\textbf{right}, you can get a path of length $p$. The length of the path is the number of tiles you stood on.\n\nVlad wants to see if it is possible to get a path of length $p$ such that:\n\n- it ends at tile with index $n$;\n- $p$ is divisible by $k$\n- the path is divided into blocks of length exactly $k$ each;\n- tiles in each block have the same colour, the colors in adjacent blocks are not necessarily different.\n\nFor example, let $n = 14$, $k = 3$.\n\nThe colours of the tiles are contained in the array $c$ = [$\\textcolor{red}{1}, \\textcolor{violet}{2}, \\textcolor{red}{1}, \\textcolor{red}{1}, \\textcolor{gray}{7}, \\textcolor{orange}{5}, \\textcolor{green}{3}, \\textcolor{green}{3}, \\textcolor{red}{1}, \\textcolor{green}{3}, \\textcolor{blue}{4}, \\textcolor{blue}{4}, \\textcolor{violet}{2}, \\textcolor{blue}{4}$]. Then we can construct a path of length $6$ consisting of $2$ blocks:\n\n$\\textcolor{red}{c_1} \\rightarrow \\textcolor{red}{c_3} \\rightarrow \\textcolor{red}{c_4} \\rightarrow \\textcolor{blue}{c_{11}} \\rightarrow \\textcolor{blue}{c_{12}} \\rightarrow \\textcolor{blue}{c_{14}}$\n\nAll tiles from the $1$-st block will have colour $\\textcolor{red}{\\textbf{1}}$, from the $2$-nd block will have colour $\\textcolor{blue}{\\textbf{4}}$.\n\nIt is also possible to construct a path of length $9$ in this example, in which all tiles from the $1$-st block will have colour $\\textcolor{red}{\\textbf{1}}$, from the $2$-nd block will have colour $\\textcolor{green}{\\textbf{3}}$, and from the $3$-rd block will have colour $\\textcolor{blue}{\\textbf{4}}$.",
    "tutorial": "Since the path must start in the first tile and end in the last tile, it is enough to construct a path consisting of $1$ or $2$ blocks of length $k$ to solve the problem. If $c_1 = c_n$, then we need to check that there are $k-2$ tiles of colour $c_0$ between the first and the last tile. If this condition is satisfied, then the tiles that are found together with the first and the last tile form the path $p$, and the answer is - YES. Otherwise - the answer is NO. If $c_1 \\neq c_n$ we can solve the problem by the method of two pointers: let's move from the two ends of the array $c$ to the middle, counting the number of tiles of colour $c_1$ on the left and tiles of colour $c_n$ on the right. If the pointers meet no later than $k$ tiles of the desired colours are found on both sides, the answer is - YES, otherwise - NO.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nbool solve(){\n    int n, k;\n    cin >> n >> k;\n    vector<int>c(n);\n    for(int i = 0; i < n; i++) cin >> c[i];\n    int left = 0, right = 0, i = 0, j = n - 1;\n    int k_left = k, k_right = k;\n\n    if (c[0] == c[n - 1]){\n        k_left = k / 2;\n        k_right = k - k_left;\n    }\n    for(; i < n && left < k_left; i++){\n        if(c[i] == c[0]) left++;\n    }\n    for(; j >= 0 && right < k_right; j--){\n        if(c[j] == c[n - 1]) right++;\n    }\n    return (i - 1) < (j + 1);\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        cout << (solve() ? \"YES\" : \"NO\") << \"\\n\";\n    }\n\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1851",
    "index": "D",
    "title": "Prefix Permutation Sums",
    "statement": "Your friends have an array of $n$ elements, calculated its array of prefix sums and passed it to you, accidentally losing one element during the transfer. Your task is to find out if the given array can matches \\textbf{permutation}.\n\nA permutation of $n$ elements is an array of $n$ numbers from $1$ to $n$ such that each number occurs exactly \\textbf{one} times in it.\n\nThe array of prefix sums of the array $a$ — is such an array $b$ that $b_i = \\sum_{j=1}^i a_j, 1 \\le i \\le n$.\n\nFor example, the original permutation was $[1, 5, 2, 4, 3]$. Its array of prefix sums — $[1, 6, 8, 12, 15]$. Having lost one element, you can get, for example, arrays $[6, 8, 12, 15]$ or $[1, 6, 8, 15]$.\n\nIt can also be shown that the array $[1, 2, 100]$ does not correspond to any permutation.",
    "tutorial": "To begin with, let's learn how to reconstruct an array from its prefix sum array. This can be done by calculating the differences between adjacent elements. If the element $\\frac{n * (n + 1)}{2}$ is missing from the array, we will add it and check if the array corresponds to some permutation. Otherwise, there is a missing element in the middle or at the beginning of the array. Let's count the occurrences of each difference between adjacent elements. Obviously, we should have one extra number and $2$ missing numbers. If the count of differences occurring at least $2$ times is at least $2$, the answer is $NO$. The answer is also $NO$ if any difference occurs at least $3$ times. Otherwise, we check that exactly $2$ distinct numbers are missing, and their sum is equal to the only duplicate.",
    "code": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n\nusing namespace std;\n\ntypedef long long ll;\n\nll n;\n\nbool isPermutation(vector<ll> a) {\n    for (int i = 0; i < n; ++i) {\n        if (a[i] <= 0 || a[i] > n) {\n            return false;\n        }\n    }\n    set<ll> s(a.begin(), a.end());\n    return s.size() == n;\n}\n\nvector<ll> prefSumToArray(vector<ll> p) {\n    vector<ll> res(n);\n    res[0] = p[0];\n    for (int i = 1; i < n; ++i) {\n        res[i] = p[i] - p[i - 1];\n    }\n    return res;\n}\n\nvoid solve() {\n    cin >> n;\n    vector<ll> a(n - 1);\n    for (int i = 0; i + 1 < n; ++i) {\n        cin >> a[i];\n    }\n    ll x = n * (n + 1) / 2;\n    if (a.back() != x) {\n        a.push_back(x);\n        vector<ll> b = prefSumToArray(a);\n        if (isPermutation(b)) {\n            cout << \"YES\\n\";\n        } else {\n            cout << \"NO\\n\";\n        }\n        return;\n    }\n    map<ll, int> cnt;\n    cnt[a[0]]++;\n    for (int i = 1; i < n - 1; ++i) {\n        cnt[a[i] - a[i - 1]]++;\n    }\n    vector<int> cntGt1;\n    for (auto p: cnt) {\n        if (p.second > 1) {\n            cntGt1.push_back(p.first);\n        }\n    }\n    if (cntGt1.size() > 1) {\n        cout << \"NO\\n\";\n        return;\n    }\n    if (cntGt1.size() == 1) {\n        int x1 = cntGt1[0];\n        if (cnt[x1] > 2) {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    vector<int> cnt0;\n    for (int i = 1; i <= n; ++i) {\n        if (cnt[i] == 0) {\n            cnt0.push_back(i);\n        }\n    }\n    if (cnt0.size() != 2) {\n        cout << \"NO\\n\";\n        return;\n    }\n    cout << \"YES\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0), cout.tie(0);\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1851",
    "index": "E",
    "title": "Nastya and Potions",
    "statement": "Alchemist Nastya loves mixing potions. There are a total of $n$ types of potions, and one potion of type $i$ can be bought for $c_i$ coins.\n\nAny kind of potions can be obtained in no more than one way, by mixing from several others. The potions used in the mixing process will be \\textbf{consumed}. Moreover, no potion can be obtained from itself through one or more mixing processes.\n\nAs an experienced alchemist, Nastya has an \\textbf{unlimited} supply of $k$ types of potions $p_1, p_2, \\dots, p_k$, but she doesn't know which one she wants to obtain next. To decide, she asks you to find, for each $1 \\le i \\le n$, the minimum number of coins she needs to spend to obtain a potion of type $i$ next.",
    "tutorial": "To begin with, let's note that potions of types $p1, p2, \\dots, p_k$ are essentially free, so we can replace their costs with $0$. Let $ans[i]$ be the answer for the $i$-th potion. Each potion can be obtained in one of two ways: by buying it or by mixing it from other potions. For mixing, we obtain all the required potions at the minimum cost. That is, if there is a way to mix a potion of type $i$, then the answer for it is either $c_i$ or the sum of answers for all $e_i$. Since the graph in the problem does not have cycles, this can be done by a simple depth-first search.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n\nusing namespace std;\n\nvector<int> dp;\nvector<bool> used;\nvector<vector<int>> sl;\n\nint get(int v){\n    if(used[v]){\n        return dp[v];\n    }\n    used[v] = true;\n    int s = 0;\n    for(int u: sl[v]){\n        s += get(u);\n    }\n    if(!sl[v].empty()) dp[v] = min(dp[v], s);\n    return dp[v];\n}\n\nvoid solve(int tc) {\n    int n, k;\n    cin >> n >> k;\n    dp.resize(n);\n    used.assign(n, false);\n    sl.assign(n, vector<int>(0));\n    for(int &e: dp) cin >> e;\n    for(int i = 0; i < k; ++i){\n        int e;\n        cin >> e;\n        dp[--e] = 0;\n    }\n    for(int i = 0; i < n; ++i){\n        int m;\n        cin >> m;\n        sl[i].resize(m);\n        for(int &e: sl[i]){\n            cin >> e;\n            --e;\n        }\n    }\n    for(int i = 0; i < n; ++i){\n        get(i);\n    }\n    for(int e: dp) cout << e << \" \";\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if(multi) cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1851",
    "index": "F",
    "title": "Lisa and the Martians",
    "statement": "Lisa was kidnapped by martians! It okay, because she has watched a lot of TV shows about aliens, so she knows what awaits her. Let's call integer martian if it is \\textbf{a non-negative integer} and \\textbf{strictly less than} $2^k$, for example, when $k = 12$, the numbers $51$, $1960$, $0$ are martian, and the numbers $\\pi$, $-1$, $\\frac{21}{8}$, $4096$ are not.\n\nThe aliens will give Lisa $n$ martian numbers $a_1, a_2, \\ldots, a_n$. Then they will ask her to name any martian number $x$. After that, Lisa will select a pair of numbers $a_i, a_j$ ($i \\neq j$) in the given sequence and count $(a_i \\oplus x) \\& (a_j \\oplus x)$. The operation $\\oplus$ means Bitwise exclusive OR, the operation $\\&$ means Bitwise And. For example, $(5 \\oplus 17) \\& (23 \\oplus 17) = (00101_2 \\oplus 10001_2) \\& (10111_2 \\oplus 10001_2) = 10100_2 \\& 00110_2 = 00100_2 = 4$.\n\nLisa is sure that the higher the calculated value, the higher her chances of returning home. Help the girl choose such $i, j, x$ that maximize the calculated value.",
    "tutorial": "Solution 1. Let's use the data structure called a bitwise trie. Fix some $a_i$, where all $a_j$ for $j < i$ have already been added to the trie. We will iterate over the bits in $a_i$ from the $(k - 1)$-th bit to the $0$-th bit. Since $2^t > 2^{t - 1} + 2^{t - 2} + \\ldots + 2 + 1$, if there exists $a_j$ with the same bit at the corresponding position in $a_i$, we will go into that branch of the trie and append $1 - b$ to the corresponding bit $x$. Otherwise, our path is uniquely determined. When we reach a leaf, the bits on the path will correspond to the optimal number $a_j$ for $a_i$. The complexity of this solution is $O(n k)$. Solution 2. Sort $a_1, a_2, \\ldots, a_n$ in non-decreasing order. We will prove that the answer is some pair of adjacent numbers. Let the answer be numbers $a_i, a_j$ ($j - i > 1$). If $a_i = a_j$, then $a_i = a_{i + 1}$. Otherwise, they have a common prefix of bits, after which there is a differing bit. That is, at some position $t$, $a_i$ has a $0$ and $a_j$ has a $1$. Since $j - i > 1$, $a_{i + 1}$ can have either $0$ or $1$ at this position, but in the first case it is more advantageous to choose $a_i, a_{i + 1}$ as the answer, and in the second case it is more advantageous to choose $a_{i + 1}, a_j$ as the answer. The complexity of this solution is $O(n \\log n)$. Solution 3 (secret). The problem can be easily reduced to finding a pair of numbers with the minimum $\\oplus$. If you don't know about the bitwise trie and the sorting trick, such a problem can be solved using AVX instructions. The complexity of this solution is $O(\\frac{n^2}{2 \\cdot 8})$.",
    "code": "#include <bits/stdc++.h>\n#define all(arr) arr.begin(), arr.end()\n\nusing namespace std;\n\nconst int MAXN = 200200;\nconst int MAXK = 30;\nconst int MAXMEM = MAXN * MAXK;\n\nmt19937 rng(07062006);\n\nstruct node {\n\tnode *chi[2] {nullptr};\n\tint sz = 0, id = -1;\n};\n\nint n, k;\nint arr[MAXN];\nnode *mem = new node[MAXMEM];\nnode *root, *mpos;\n\nvoid add_num(node* &v, int val, int i, int id) {\n\tif (v == nullptr) *(v = mpos++) = node();\n\tv->sz++;\n\tif (i == -1) {\n\t\tv->id = id;\n\t\treturn;\n\t}\n\tadd_num(v->chi[val >> i & 1], val, i - 1, id);\n}\n\nint down(node *v, int val, int i, int &x, int &jans) {\n\tif (i == -1) {\n\t\tjans = v->id;\n\t\treturn 0;\n\t}\n\tint b = val >> i & 1;\n\tif (v->chi[b])\n\t\treturn down(v->chi[b], val, i - 1, x ^= ((1 ^ b) << i), jans) | (1 << i);\n\treturn down(v->chi[b ^ 1], val, i - 1, x ^= ((rng() & 1) << i), jans);\n}\n\nvoid build() {\n\troot = nullptr;\n\tmpos = mem;\n\tadd_num(root, *arr, k - 1, 0);\n}\n\ntuple<int, int, int> solve() {\n\tint ians = 0, jans = 1, xans = 0;\n\tfor (int i = 1; i < n; ++i) {\n\t\tint x = 0, j = -1;\n\t\tint cur = down(root, arr[i], k - 1, x, j);\n\t\tif (cur > ((arr[ians] ^ xans) & (arr[jans] ^ xans)))\n\t\t\tians = j, jans = i, xans = x;\n\t\tadd_num(root, arr[i], k - 1, i);\n\t}\n\treturn {ians, jans, xans};\n}\n\nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tcin >> n >> k;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tcin >> arr[i];\n\t\tbuild();\n\t\tauto [ians, jans, xans] = solve();\n\t\tcout << ++ians << ' ' << ++jans << ' ' << xans << endl;\n\t}\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "math",
      "strings",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1851",
    "index": "G",
    "title": "Vlad and the Mountains",
    "statement": "Vlad decided to go on a trip to the mountains. He plans to move between $n$ mountains, some of which are connected by roads. The $i$-th mountain has a height of $h_i$.\n\nIf there is a road between mountains $i$ and $j$, Vlad can move from mountain $i$ to mountain $j$ by spending $h_j - h_i$ units of energy. If his energy drops below zero during the transition, he will not be able to move from mountain $i$ to mountain $j$. Note that $h_j - h_i$ can be negative and then the energy will be restored.\n\nVlad wants to consider different route options, so he asks you to answer the following queries: is it possible to construct some route starting at mountain $a$ and ending at mountain $b$, given that he initially has $e$ units of energy?",
    "tutorial": "Let's consider the change in energy when traveling from $i \\rightarrow j \\rightarrow k$, $h_i - h_j + h_j - h_k = h_i - h_k$, it can be seen that this is the difference between the heights of the first and last mountains on the path. In other words, from vertex $a$, it is possible to reach any vertex for which there is a path that does not pass through vertices with a height greater than $h_a+e$. Therefore, for each query, it is necessary to construct a component from vertex $a$, in which all vertices with a height not greater than $h_a + e$ are included, and check if vertex $b$ lies within it. To do this efficiently, let's sort the queries by $h_a + e$, and the edges of the graph by $\\max(h_u, h_v)$, and maintain a disjoint set data structure (DSU). Before each query, add all edges that have not been added yet and their $\\max(h_u, h_v)$ is not greater than $h_a+e$ for that specific query. After this, it remains to only check if vertices $a$ and $b$ belong to the same connected component.",
    "code": "#include <bits/stdc++.h>\n\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nstruct dsu{\n    vector<int> p, lvl;\n\n    dsu(int n){\n        p.resize(n);\n        lvl.assign(n, 0);\n        iota(all(p), 0);\n    }\n\n    int get(int i){\n        if(i == p[i]) return i;\n        return p[i] = get(p[i]);\n    }\n\n    bool unite(int a, int b){\n        a = get(a);\n        b = get(b);\n        if(a == b){\n            return false;\n        }\n        if(lvl[a] < lvl[b])swap(a, b);\n        p[b] = a;\n        if(lvl[a] == lvl[b]){\n            ++lvl[a];\n        }\n        return true;\n    }\n\n    bool reachable(int a, int b){\n        return get(a) == get(b);\n    }\n};\n\nvoid solve(int tc) {\n    int n, m;\n    cin >> n >> m;\n    vector<pair<int, int>> h(n);\n    for(auto &e: h) cin >> e.x;\n    for(int i = 0; i < n; ++i){\n        h[i].y = i;\n    }\n    dsu graph(n);\n    vector<vector<int>> sl(n);\n    for(int i = 0; i < m; ++i){\n        int u, v;\n        cin >> u >> v;\n        --u, --v;\n        if(h[u].x > h[v].x) sl[u].emplace_back(v);\n        else sl[v].emplace_back(u);\n    }\n    int q;\n    cin >> q;\n    vector<pair<pair<int, int>, pair<int, int>>> req(q);\n    for(auto &e: req){\n        cin >> e.y.x >> e.y.y >> e.x.x;\n        --e.y.x, --e.y.y;\n        e.x.x += h[e.y.x].x;\n    }\n    for(int i = 0; i < q; ++i){\n        req[i].x.y = i;\n    }\n\n    sort(all(h));\n    sort(all(req));\n    vector<bool> ans(q);\n    int j = 0;\n    for(auto e: req){\n        while (j < n && h[j].x <= e.x.x) {\n            for(int u: sl[h[j].y]){\n                graph.unite(h[j].y, u);\n            }\n            ++j;\n        }\n        ans[e.x.y] = graph.reachable(e.y.x, e.y.y);\n    }\n    for(bool e: ans) cout << (e? \"YES\": \"NO\") << \"\\n\";\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if(multi) cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        if(i < t) cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dsu",
      "graphs",
      "implementation",
      "sortings",
      "trees",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1852",
    "index": "A",
    "title": "Ntarsis' Set",
    "statement": "Ntarsis has been given a set $S$, initially containing integers $1, 2, 3, \\ldots, 10^{1000}$ in sorted order. Every day, he will remove the $a_1$-th, $a_2$-th, $\\ldots$, $a_n$-th smallest numbers in $S$ \\textbf{simultaneously}.\n\nWhat is the smallest element in $S$ after $k$ days?",
    "tutorial": "Suppose that the numbers are arranged in a line in increasing order. Take a look at each number $x$ before some day. If it isn't deleted on that day, what new position does it occupy, and how is that impacted by its previous position? If $x$ is between $a_i$ and $a_{i+1}$, it will move to a new position of $x-i$, since $i$ positions before it are deleted. Take this observation, and apply it to simulate the process backwards. Suppose the numbers are arranged in a line in increasing order. Consider simulating backwards; instead of deleting the numbers at positions $a_1,a_2,\\ldots,a_n$ in each operation, then checking the first number after $k$ operations, we start with the number $1$ at the front, try to insert zeroes right after positions $a_1-1, a_2-2, \\ldots, a_{n}-n$ in each operation so that the zeroes will occupy positions $a_1, a_2, \\ldots, a_n$ after the insertion, and after $k$ insertions, we will check the position that $1$ will end up at. If $a_1$ is not equal to $1$, the answer is $1$. Otherwise, each insertion can be processed in $O(1)$ if we keep track of how many of $a_1-1, a_{2}-2,\\ldots,a_{n}-n$ are before the current position $x$ of $1$; if $a_1-1$ through $a_i-i$ are before $x$, then we will insert $i$ zeroes before $x$. The time complexity is $O(n+k)$ per test case. The editorial code additionally processes every insertion with the same $i$ value in $O(1)$, for $O(n)$ overall complexity. There are alternative solutions using binary search with complexity $O(k\\log nk)$ or $O(k\\log n\\log nk)$, and we allowed them to pass. In fact, this problem was originally proposed with $k \\leq 10^9$ but we lowered the constraints.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nconst int inf = 1e9+10;\nconst ll inf_ll = 1e18+10;\n#define all(x) (x).begin(), (x).end()\n#define pb push_back\n#define cmax(x, y) (x = max(x, y))\n#define cmin(x, y) (x = min(x, y))\n\n#ifndef LOCAL\n#define debug(...) 0\n#else\n#include \"../../debug.cpp\"\n#endif\n\nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int t; cin >> t;\n    while (t--) {\n        ll n, k; cin >> n >> k;\n        vector<ll> a(n);\n        for (int i = 0; i < n; i++)\n            cin >> a[i];\n\n        ll j = 0, x = 1;\n        while (k--) {\n            while (j < n && a[j] <= x+j)\n                j++;\n            x += j;\n        }\n\n        cout << x << \"\\n\";\n    }\n}",
    "tags": [
      "binary search",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1852",
    "index": "B",
    "title": "Imbalanced Arrays",
    "statement": "Ntarsis has come up with an array $a$ of $n$ non-negative integers.\n\nCall an array $b$ of $n$ integers imbalanced if it satisfies the following:\n\n- $-n\\le b_i\\le n$, $b_i \\ne 0$,\n- there are no two indices $(i, j)$ ($1 \\le i, j \\le n$) such that $b_i + b_j = 0$,\n- for each $1 \\leq i \\leq n$, there are \\textbf{exactly} $a_i$ indices $j$ ($1 \\le j \\le n$) such that $b_i+b_j>0$, where $i$ and $j$ are not necessarily distinct.\n\nGiven the array $a$, Ntarsis wants you to construct some imbalanced array. Help him solve this task, or determine it is impossible.",
    "tutorial": "You can solve the problem by picking one number from each pair $(n, -n)$, $(n - 1, -n + 1) \\dots$, $(1, -1)$. $b_i > b_j$ implies $a_i > a_j$. First, try to determine one index in $O(n)$, or determine if that's impossible. Sort the array $a$ to optimize the $O(n^2)$ solution. At the start, let $x$ be an index such that $b_x$ has the greatest absolute value. If $b_x$ is negative, we have $a_x=0$, and else $a_x=n$. Moreover, we can't have $a_y=0,a_z=n$ for any indices $y$ and $z$, because that implies $b_y+b_z$ is both positive and negative, contradiction. Hence, the necessary and sufficient condition to check if we can determine an element in array $b$ with maximum absolute value is (there exists an element of array $a$ equal to $0$) xor (there exists an element of array $a$ equal to $n$). Then, we can remove that element and re-calculate the $a$ array, leading to an $O(n^2)$ solution. If the check fails at any moment, there is no valid solution. To optimize it further, note that we can sort array $a$ at the start and keep track of them in a deque-like structure. We only need to check the front and end of the deque to see if our key condition holds. Finally, we can use a variable to record the number of positive elements deleted so far and subtract it from the front and end of the deque when checking our condition, so that each check is $O(1)$. The overall complexity becomes $O(n\\log n)$ due to sorting.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n, ans[100010];\nvector<pair<int,int>> arr;\n\nvoid solve() {\n    cin >> n;\n    arr.resize(n);\n    for (int i = 0; i < n; i++) {\n        cin >> arr[i].first;\n        arr[i].second = i;\n    }\n    sort(arr.begin(), arr.end());\n    int l = 0, r = n - 1, sz = n;\n    while (l <= r) {\n        if ((arr[r].first == n - l) ^ (arr[l].first == n - 1 - r)) {\n            if (arr[r].first == n - l) {\n                ans[arr[r--].second] = sz--;\n            }\n            else {\n                ans[arr[l++].second] = -(sz--);\n            }\n        }\n        else {\n            cout << \"NO\" << \"\\n\";\n            return;\n        }\n    }\n    cout << \"YES\" << \"\\n\";\n    for (int i = 0; i < n; i++) cout << ans[i] << \" \";\n    cout << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(nullptr);\n\n    int t; cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1852",
    "index": "C",
    "title": "Ina of the Mountain",
    "statement": "To prepare her \"Takodachi\" dumbo octopuses for world domination, Ninomae Ina'nis, a.k.a. Ina of the Mountain, orders Hoshimachi Suisei to throw boulders at them. Ina asks you, Kiryu Coco, to help choose where the boulders are thrown.\n\nThere are $n$ octopuses on a single-file trail on Ina's mountain, numbered $1, 2, \\ldots, n$. The $i$-th octopus has a certain initial health value $a_i$, where $1 \\leq a_i \\leq k$.\n\nEach boulder crushes consecutive octopuses with indexes $l, l+1, \\ldots, r$, where $1 \\leq l \\leq r \\leq n$. You can choose the numbers $l$ and $r$ arbitrarily for each boulder.\n\nFor each boulder, the health value of each octopus the boulder crushes is reduced by $1$. However, as octopuses are immortal, once they reach a health value of $0$, they will immediately regenerate to a health value of $k$.\n\nGiven the octopuses' initial health values, find the \\textbf{minimum} number of boulders that need to be thrown to make the health of all octopuses equal to $k$.",
    "tutorial": "Suppose you knew in advance how many times each octopus will regenerate. Could you solve the problem then? To make things easier, replace health values of $k$ with health values of $0$, so the goal is to reach $0$ health. Regeneration is now from $0$, which was formerly $k$, to $k-1$, instead of $1$ to $k$, which is now $1$ to $0$. For clarity, create a new array $b$ such that $b[i] = a[i] \\% k$. Now, instead of letting health values wrap around, we can just initially give each octopus a multiple of $k$ more health. For example, if $k=3$ and an octopus with initially $2$ health regenerates twice, we can pretend it initially had $2 + 2 \\cdot 3 = 8$ health. Create a new array $c$ storing these new healths. Since all healths will reach $0$, it also represents the number of boulders that will hit each octopus. To find the minimum number of boulder throws, represent the health values with a histogram, where the heights of blocks are equal to the values of $c$: Then, erase all vertical borders between blocks. The resulting segments each represent a boulder throw: Intuitively, this should minimize the number of boulders, since any sequence of boulder throws should be rearrangeable into horizontal segments covering this histogram. We can easily calculate the number of boulders as the sum of all positive adjacent differences, treating the far left and far right as having health $0$. Formally, pad $c$ with an extra $0$ to the left and right (i.e. $c[0] = c[n+1] = 0$) and let the adjacent differences be $d[i] = c[i+1]-c[i]$. We claim the minimum number of boulder throws is $\\mathrm{throws} = \\sum_{i=0}^n{\\max\\{d[i],0\\}}$. This many is necessary, since if $d[i]$ is positive, octopus $i+1$ gets crushed $d[i]$ more times than octopus $i$, so at least $d[i]$ boulders' ranges have left endpoint $l = i+1$. This many is necessary, since if $d[i]$ is positive, octopus $i+1$ gets crushed $d[i]$ more times than octopus $i$, so at least $d[i]$ boulders' ranges have left endpoint $l = i+1$. This many is achievable, as depicted above. Crush all octopuses with the highest health exactly once (crushing consecutive octopuses with the same boulder), then all octopuses with the new highest health, and so on. Each boulder's range's left endpoint corresponds with part of a positive adjacent difference. This many is achievable, as depicted above. Crush all octopuses with the highest health exactly once (crushing consecutive octopuses with the same boulder), then all octopuses with the new highest health, and so on. Each boulder's range's left endpoint corresponds with part of a positive adjacent difference. Can you figure out an $O(n^2)$ solution? And can you improve on it? Suppose you already had the optimal solution for the subarray $a[1 \\ldots i]$. How could you extend it to $a[1 \\ldots i+1]$? Read the solution in Hint One before continuing with this tutorial; it provides important definitions. To reduce the number of possibilities for each $c[i]$, we prove the following lemma: There exists an optimal choice of $c$ (minimizing $\\mathrm{throws}$) where all differences between adjacent $c[i]$ have absolute value less than $k$. Intuitively, this is because we can decrease a $c[i]$ by $k$. Formally: We can prove this using a monovariant on the sum of all values in $c$. Start with an optimal choice of $c$. If there does not exist an $i$ with $\\lvert d[i]\\rvert \\geq k$, we are done. Otherwise, choose one such $i$. Without loss of generality, we can assume $d[i]$ is positive, as the problem is symmetrical when flipped horizontally. Now, decrease $c[i+1]$ by $k$. This decreases $d[i]$ by $k$ to a still-positive value, which decreases $\\mathrm{throws}$ by $k$. This also increases $d[i+1]$ by $k$, which increases $\\mathrm{throws}$ by at most $k$. Thus, $\\mathrm{throws}$ does not increase, so the new $c$ is still optimal. We can apply this operation repeatedly on any optimal solution until we do not have any more differences with absolute value $\\geq k$. Since each operation decreases the sum of values in $c$ by $k$, this algorithm terminates since the sum of values in $c$ is finite. By the previous lemma, if we have determined $c[i]$, there are at most $2$ choices for $c[i+1]$. (There is $1$ choice when $b[i] = b[i+1]$, resulting in $d[i] = 0$, $c[i] = c[i+1]$, effectively merging the two octopuses.) We can visualize this as a DAG in the 2D plane over all points $(i,c[i])$ (over all possible choices of $c[i]$). Each point points to the points in the next column that are the closest above and below (if it exists), forming a grid-like shape. Our goal is to find a path of minimum cost from $(0,0)$ to $(n+1,0)$. This is the DAG for the second testcase in samples: Call each time we choose a $c[i+1] > c[i]$ (i.e. positive $d[i]$) an ascent. Note that the number of ascents is fixed because each nonzero $d[i]$ is either $x$ or $x+k$ for some fixed negative $x$, and there must be a fixed number of $+k$'s to make the total change from $c[0]$ to $c[n+1]$ zero. Each ascent brings the path up to the next \"row\" of descents. Since these rows slope downwards, the $j$th ascent must take place at or before some index $i_j$, because otherwise $c[i_j+1]$ would be negative. We can use the following strategy to find a path which we claim is optimal: If we can descend, then we descend. Otherwise, either we ascend, or alternatively, we change a previous descent into an ascent so we can descend here. (This can be further simplified by having a hypothetical \"descent\" here, so you do not need to compare two possibilities in the implementation.) Now, the best such location for an ascent is the one with minimum cost. We show how to improve (or preserve the optimality of) any other path into the one chosen by this strategy. Index the ascents by the order they are chosen by the strategy, not in left-to-right order. Let $j$ be the index of first ascent this strategy chooses that is not in the compared path. Besides the $j-1$ matching ascents, the compared path must contain at least $1$ more ascent at or before $i_j$, and because of how the strategy chooses ascents, said ascent(s) must have cost no less than the strategy's $j$th ascent. Any can be changed to match the strategy, since the matching ascents already guarantee that each of the first $j-1$ ascents in left-to-right order happens early enough. Repeating the above operation will obtain the strategy's path. We can implement the above strategy with a priority queue, where for each descent we push on the cost of the corresponding ascent, and when an ascent is required, we then pop off the minimum element. In particular, if $b[i] < b[i+1]$, then the corresponding ascent has cost $b[i+1]-b[i]$, while if $b[i] > b[i+1]$, it has cost $b[i+1]-b[i]+k$. Also, since the bottom of the DAG corresponds to $c[i] = b[i]$, an ascent is required exactly when $b[i] < b[i+1]$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tpriority_queue<int, vector<int>, greater<int>> differences;\n\tint previous = 0;\n\tll ans = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tint x;\n\t\tcin >> x;\n\t\tx %= k;\n\t\tif (x > previous) {\n\t\t\tdifferences.push(x - previous);\n\t\t\tans += differences.top();\n  \t\t\tdifferences.pop();\n\t\t} else {\n  \t\t\tdifferences.push(k + x - previous);\n\t\t}\n\t\tprevious = x;\n  \t}\n  \tcout << ans << \"\\n\";\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1852",
    "index": "D",
    "title": "Miriany and Matchstick",
    "statement": "Miriany's matchstick is a $2 \\times n$ grid that needs to be filled with characters A or B.\n\nHe has already filled in the first row of the grid and would like you to fill in the second row. You must do so in a way such that the number of adjacent pairs of cells with different characters$^\\dagger$ is equal to $k$. If it is impossible, report so.\n\n$^\\dagger$ An adjacent pair of cells with different characters is a pair of cells $(r_1, c_1)$ and $(r_2, c_2)$ ($1 \\le r_1, r_2 \\le 2$, $1 \\le c_1, c_2 \\le n$) such that $|r_1 - r_2| + |c_1 - c_2| = 1$ and the characters in $(r_1, c_1)$ and $(r_2, c_2)$ are different.",
    "tutorial": "Solve the samples for all values of $k$. What does constructing a second row from left to right look like? How does knowing the possible $k$ for any first row help you construct a second row? Apply dynamic programming to calculate the possible $k$, and use the information in the DP to construct a solution. Call the number of adjacent pairs of cells with different characters the cost. If we construct the second row from left to right, the amount each character adds to the cost only depends on the previous character. Thus, we can represent the problem with a DAG whose vertices represent choices for each character and whose edges represent the cost of choosing two adjacent characters. Our goal is to find a path starting from the far left and ending at the far right of cost $k$. For example, below is the DAG for the third testcase in the sample. (For convenience, we include the cost of cells in the top row with the corresponding cells in the bottom row.) A general way to find such a path is as follows: For each vertex, store all possible costs of a path starting from the far left and ending at that vertex, which can be calculated with dynamic programming. Then we construct our path backwards from the right. For each candidate previous vertex, we check that the constructed path's cost plus the cost of the edge from this vertex plus some stored cost in this vertex equals $k$, in which case we know that some completion of the path from the far left to this vertex exists and we can choose this vertex. Naively calculating this DP would require $O(n)$ time per operation. However, intuitively, each set of possible costs should contain almost all values between its minimum and maximum, and experiments suggest it always consists of at most two intervals. We will first formalize the DP and then prove this observation. Let $\\mathrm{dp}_A[i]$ store the set of possible values of $k$ when the grid is truncated to the first $i$ columns and the last character in the second row is $A$. Define $\\mathrm{dp}_B[i]$ similarly. Using the notation $[\\mathrm{true}] = 1$, $[\\mathrm{false}] = 0$, $S+x = \\{s+x \\mid s \\in S\\}$, we have the recurrences $\\begin{align*} \\mathrm{dp}_A[i] &= \\mathrm{dp}_A[i-1]\\cup(\\mathrm{dp}_B[i-1]+1)+[s_i \\ne A]+[s_i \\ne s_{i-1}] \\\\ \\mathrm{dp}_B[i] &= \\mathrm{dp}_B[i-1]\\cup(\\mathrm{dp}_A[i-1]+1)+[s_i \\ne B]+[s_i \\ne s_{i-1}] \\end{align*}$ with initial values $\\mathrm{dp}_A[1] = [s_1 \\ne A]$ and $\\mathrm{dp}_B[1] = [s_1 \\ne B]$. Now either we hope that each set consists of $O(1)$ intervals, or we have to prove that each set indeed consists of at most two intervals: We will use induction to prove that the following stronger property holds for all $i \\ge 2$: $\\mathrm{dp}_A[i]$ and $\\mathrm{dp}_B[i]$ are overlapping intervals, except that possibly one (non-endpoint) value $v$ is missing from one interval, but in that case either $v-1$ or $v+1$ is present in the other interval. ($i = 1$ must be treated separately, but it can easily be checked.) Base case. To prove this holds for $i = 2$, WLOG let $s_1 = A$ so $\\mathrm{dp}_A[1] = \\{0\\}$ and $\\mathrm{dp}_B[1] = \\{1\\}$. If $s_2 = A$, then $\\begin{align*} \\mathrm{dp}_A[2] &= \\{0\\}\\cup(\\{1\\}+1)+0+0 = \\{0,2\\} \\\\ \\mathrm{dp}_B[2] &= \\{1\\}\\cup(\\{0\\}+1)+1+0 = \\{2\\} \\end{align*}$ which satisfies the property with $v = 1$. If $s_2 = B$, then $\\begin{align*} \\mathrm{dp}_A[2] &= \\{0\\}\\cup(\\{1\\}+1)+1+1 = \\{2,4\\} \\\\ \\mathrm{dp}_B[2] &= \\{1\\}\\cup(\\{0\\}+1)+0+1 = \\{2\\} \\end{align*}$ which satisfies the property with $v = 3$. Induction step. Suppose the property holds for $i-1$. Since the conditions of the property only depend on relative positions, for convenience we shift the sets $\\mathrm{dp}_A[i]$ and $\\mathrm{dp}_B[i]$ left by $h = [s_i \\ne A]+[s_i \\ne s_{i-1}]$ to get $\\begin{align*} \\mathrm{dp}'_A[i] &= \\mathrm{dp}_A[i]-h = \\mathrm{dp}_A[i-1]\\cup(\\mathrm{dp}_B[i-1]+1) \\\\ \\mathrm{dp}'_B[i] &= \\mathrm{dp}_B[i]-h = \\mathrm{dp}_B[i-1]\\cup(\\mathrm{dp}_A[i-1]+1)+(s_i = A\\ ?\\ 1 : -1). \\end{align*}$ If the property holds for $\\mathrm{dp}'$, then it holds for $\\mathrm{dp}$. First, we show that a missing value in $\\mathrm{dp}'_A[i]$ or $\\mathrm{dp}'_B[i]$ can only come directly from a missing value in $\\mathrm{dp}_A[i-1]$ or $\\mathrm{dp}_B[i-1]$ and not from the union operation merging two non-adjacent intervals. This is true because $\\mathrm{dp}_A[i-1]$ and $\\mathrm{dp}_B[i-1]$ overlap, so even after $1$ is added to either, they are still at least adjacent. If a value $v$ is missing, WLOG let it be missing from $\\mathrm{dp}_A[i-1]$. If $v+1 \\in \\mathrm{dp}_B[i-1]$, then $\\mathrm{dp}'_A[i]$ may be missing $v$ while $\\mathrm{dp}'_B[i]$ does not miss any value. Also, since $v-1$ is adjacent to the missing value (which isn't an endpoint), it is in $\\mathrm{dp}_A[i-1]$, so either $v+1$ or $v-1$ is in $\\mathrm{dp}'_B[i]$. This also guarantees the intervals overlap, satisfying the property for $i$. If $v+1 \\in \\mathrm{dp}_B[i-1]$, then $\\mathrm{dp}'_A[i]$ may be missing $v$ while $\\mathrm{dp}'_B[i]$ does not miss any value. Also, since $v-1$ is adjacent to the missing value (which isn't an endpoint), it is in $\\mathrm{dp}_A[i-1]$, so either $v+1$ or $v-1$ is in $\\mathrm{dp}'_B[i]$. This also guarantees the intervals overlap, satisfying the property for $i$. The case for $v-1 \\in \\mathrm{dp}_B[i-1]$ is very similar. $\\mathrm{dp}'_B[i]$ may be missing either $v$ or $v+2$, and since $v+1 \\in \\mathrm{dp}_A[i-1]$, $v+1$ is in $\\mathrm{dp}'_A[i]$. The case for $v-1 \\in \\mathrm{dp}_B[i-1]$ is very similar. $\\mathrm{dp}'_B[i]$ may be missing either $v$ or $v+2$, and since $v+1 \\in \\mathrm{dp}_A[i-1]$, $v+1$ is in $\\mathrm{dp}'_A[i]$. If no value is missing, let $x$ be a common value in both $\\mathrm{dp}_A[i-1]$ and $\\mathrm{dp}_B[i-1]$. Then, $\\mathrm{dp}'_A[i] \\supseteq \\{x,x+1\\}$ and $\\mathrm{dp}'_B[i]$ is a superset of either $\\{x-1,x\\}$ or $\\{x+1,x+2\\}$, so the intervals overlap. To find the union of two sets of intervals, sort them by left endpoint and merge adjacent overlapping intervals. After computing the DP, apply the aforementioned backwards construction to obtain a valid second row. Below is a visualization of solving the third testcase in the sample. Generate your own here!",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define all(x) (x).begin(), (x).end()\n\nstruct state {\n\n    // represents a set of integers compressed as a vector\n    // of non-overlapping intervals [l, r]\n\n    basic_string<array<int, 2>> a;\n\n    // add d to everything in the set\n    friend state add(state x, int d) {\n        for (auto& [l, r] : x.a)\n            l += d, r += d;\n        return x;\n    }\n\n    // union of two sets of integers\n    friend state unite(state x, state y) {\n        state z;\n        merge(all(x.a), all(y.a), back_inserter(z.a));\n        int j = 0;\n        for (int i = 1; i < z.a.size(); i++) {\n            if (z.a[i][0] <= z.a[j][1]+1)\n                z.a[j][1] = max(z.a[j][1], z.a[i][1]);\n            else\n                z.a[++j] = z.a[i];\n        }\n        z.a.erase(z.a.begin() + j + 1, z.a.end());\n        return z;\n    }\n\n    // whether integer k is in the set\n    friend bool contains(state x, int k) {\n        for (auto& [l, r] : x.a)\n            if (k >= l && k <= r)\n                return true;\n        return false;\n    }\n};\n\n// set containing only one integer d\nstate from_constant(int d) {\n    return state({{{d, d}}});\n}\n\nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int t; cin >> t;\n    while (t--) {\n        int n, k; cin >> n >> k;\n        string s; cin >> s;\n\n        vector<array<state, 2>> dp(n);\n\n        dp[0][0] = from_constant(s[0] != 'A');\n        dp[0][1] = from_constant(s[0] != 'B');\n\n        for (int i = 1; i < n; i++) {\n            dp[i][0] = add(unite(dp[i-1][0], add(dp[i-1][1], 1)), (s[i] != 'A') + (s[i] != s[i-1]));\n            dp[i][1] = add(unite(dp[i-1][1], add(dp[i-1][0], 1)), (s[i] != 'B') + (s[i] != s[i-1]));\n        }\n\n        if (!(contains(dp[n-1][0], k) || contains(dp[n-1][1], k))) {\n            cout << \"NO\\n\";\n            continue;\n        }\n\n        string ans;\n\n        for (int i = n-1; i >= 0; i--) {\n            char c = contains(dp[i][0], k - (i == n-1 ? 0 : (ans.back() != 'A'))) ? 'A' : 'B';\n            k -= (c != s[i]);\n            if (i > 0)\n                k -= (s[i] != s[i-1]);\n            if (i < n-1)\n                k -= (c != ans.back());\n            ans += c;\n        }\n\n        reverse(all(ans));\n        cout << \"YES\\n\" << ans << \"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1852",
    "index": "E",
    "title": "Rivalries",
    "statement": "Ntarsis has an array $a$ of length $n$.\n\nThe power of a subarray $a_l \\dots a_r$ ($1 \\leq l \\leq r \\leq n$) is defined as:\n\n- The largest value $x$ such that $a_l \\dots a_r$ contains $x$ and neither $a_1 \\dots a_{l-1}$ nor $a_{r+1} \\dots a_n$ contains $x$.\n- If no such $x$ exists, the power is $0$.\n\nCall an array $b$ a rival to $a$ if the following holds:\n\n- The length of both $a$ and $b$ are equal to some $n$.\n- Over all $l, r$ where $1 \\leq l \\leq r \\leq n$, the power of $a_l \\dots a_r$ equals the power of $b_l \\dots b_r$.\n- The elements of $b$ are positive.\n\nNtarsis wants you to find a rival $b$ to $a$ such that the sum of $b_i$ over $1 \\leq i \\leq n$ is maximized. Help him with this task!",
    "tutorial": "For each distinct value, only the leftmost and rightmost positions actually have an effect on the power. Think of each distinct value as an interval corresponding to its leftmost and rightmost positions, and let that distinct value be the value of its interval. If interval $x$ strictly contains an interval $y$ with greater value, then $x$ will not have an effect on the power and it can be discarded. In order to not change the power, we can only add intervals that strictly contain an interval with greater value. Afterwards, if $i$ is not the endpoint of an interval, $b_i$ equals the largest value of an interval containing $i$. There will only be at most one interval that we have to add. Assume that there are multiple intervals that we can add without changing the answer. In this case it is easy to see that its more optimal to combine the interval with smaller value into the interval with larger value. Thus, it is never optimal to add multiple intervals. Read the hints. We can remove all intervals that will not affect the power by iterating over them in decreasing order of value and maintain a segment tree that stores for each left endpoint of any processed intervals, the right endpoint that corresponds to it. Checking if an interval is strictly contained then becomes a range minimum query. Assume that we know the value $x$ of the interval that we want to add. We can immediately fill the value for the interior of all intervals that correspond to a value greater than $x$. However, we also have to guarantee that $x$ is strictly contained by an interval with greater value, so we can try each interval to contain $x$. If are no unfilled indices the left or right side of the interval, then we want to replace the smallest filled on either side value with $x$. Otherwise, we can just fill in all the unfilled indices with $x$. Note that it is also possible for $x$ to not be able to be contained by any interval. Thus, we can just try every possible $x$ in decreasing order and maintain the filled indices as we iterate. There are only at most $n$ values of $x$ to check, which is just the set of $a_i - 1$ that does not appear in $a$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define pb push_back\n#define ff first\n#define ss second\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\n\nconst int INF = 1e9 + 1;\n\nvoid setIO() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n}\n\npii seg[400005];\nint n;\n\nvoid build(int l = 0, int r = n - 1, int cur = 0){\n    seg[cur] = {INF, INF};\n    if(l == r) return;\n    int mid = (l + r)/2;\n    build(l, mid, cur*2 + 1);\n    build(mid + 1, r, cur*2 + 2);\n}\n\nvoid update(int x, int v, int l = 0, int r = n - 1, int cur = 0){\n    if(l == r){\n        seg[cur] = {v, l};\n        return;\n    }\n    int mid = (l + r)/2;\n    if(x <= mid) update(x, v, l, mid, cur*2 + 1);\n    else update(x, v, mid + 1, r, cur*2 + 2);\n    seg[cur] = min(seg[cur*2 + 1], seg[cur*2 + 2]);\n}\n\npii query(int l, int r, int ul = 0, int ur = n - 1, int cur = 0){\n    if(l <= ul && ur <= r) return seg[cur];\n    if(l > r || ur < l || ul > r) return {INF, INF};\n    int mid = (ul + ur)/2;\n    return min(query(l, r, ul, mid, cur*2 + 1), query(l, r, mid + 1, ur, cur*2 + 2));\n}\n\nint main(){\n    setIO();\n    int t;\n    cin >> t;\n    for(int tt = 1; tt <= t; tt++){\n        cin >> n;\n        map<int, vector<int>> m;\n        int arr[n];\n        for(int i = 0; i < n; i++){\n            cin >> arr[i];\n            m[arr[i]].pb(i);\n        }\n        vector<int> rel; //relevant numbers\n        for(auto &i : m){\n            rel.pb(i.ff);\n            for(int j = 1; j < i.ss.size() - 1; j++){\n                arr[i.ss[j]] = 0;\n            }\n        }\n        reverse(rel.begin(), rel.end());\n        vector<int> nw;\n        build();\n        for(int i : rel){\n            int l = m[i].front(), r = m[i].back();\n            if(query(l, r).ff <= r){\n                arr[l] = arr[r] = 0;\n            } else {\n                update(l, r);\n                nw.pb(i);\n            }\n        }\n        swap(rel, nw);\n        set<int> s;\n        for(int i = 0; i < n; i++) if(!arr[i]) s.insert(i);\n        vector<int> vals; //possible target values\n        for(int i = rel.size() - 1; i >= 0; i--){\n            if(i == rel.size() - 1 || rel[i] - 1 != rel[i + 1]){\n                vals.pb(rel[i] - 1);\n            }\n        }\n        ll sum = 0, mx = 0, mxval = 0;\n        int lex = -1, rex = -1;\n        build();\n        for(int i = 0; i < n; i++) if(!arr[i]) update(i, -1);\n        reverse(vals.begin(), vals.end());\n        queue<pii> upd;\n        int ind = 0;\n        //try to add an interval with value i\n        for(int i : vals){\n            vector<int> nxt;\n            //try filling in all intervals > i\n            while(ind < rel.size() && rel[ind] > i){\n                int l = m[rel[ind]].front(), r = m[rel[ind]].back();\n                set<int>::iterator it = s.lower_bound(l);\n                while(it != s.end() && *it < r){\n                    sum += rel[ind];\n                    update(*it, rel[ind]);\n                    upd.push({*it, rel[ind]});\n                    it = s.erase(it);\n                }\n                nxt.pb(rel[ind++]);\n            }\n            //try each necessary interval to be strictly contained by i\n            for(int j : nxt){\n                int l = m[j].front(), r = m[j].back();\n                if(s.size() && 0 < l && r < n - 1){\n                    //find which indeces on each side to replace with i\n                    pii rnw = query(r + 1, n);\n                    pii lnw = query(0, l - 1);\n                    if(rnw.ff == INF || lnw.ff == INF) continue;\n                    ll add = (ll)i*s.size() + (rnw.ff == -1 ? 0 : i - rnw.ff) + (lnw.ff == -1 ? 0 : i - lnw.ff);\n                    if(i && sum + add > mx){\n                        mx = sum + add;\n                        mxval = i;\n                        lex = (lnw.ff == -1 ? -1 : lnw.ss);\n                        rex = (rnw.ff == -1 ? -1 : rnw.ss);\n                        //it is optimal to fill in all intervals > i\n                        while(!upd.empty()){\n                            arr[upd.front().ff] = upd.front().ss;\n                            upd.pop();\n                        }\n                    }\n                }\n            }\n        }\n        //don't want to add any intervals\n        if(s.size() == 0 && sum > mx){\n            mx = sum;\n            lex = rex = -1;\n            //it is optimal to fill in all remaining intervals\n            while(!upd.empty()){\n                arr[upd.front().ff] = upd.front().ss;\n                upd.pop();\n            }\n        }\n        if(lex != -1) arr[lex] = 0;\n        if(rex != -1) arr[rex] = 0;\n        for(int i = 0; i < n; i++) cout << (arr[i] ? arr[i] : mxval) << \" \";\n        cout << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1852",
    "index": "F",
    "title": "Panda Meetups",
    "statement": "The red pandas are in town to meet their relatives, the blue pandas! The town is modeled by a number line.\n\nThe pandas have already planned their meetup, but the schedule keeps changing. You are given $q$ updates of the form x t c.\n\n- If $c < 0$, it means $|c|$ more \\textbf{red} pandas enter the number line at position $x$ and time $t$. Then, each unit of time, they can each independently move one unit in either direction across the number line, or \\textbf{not move at all}.\n- If $c > 0$, it means that $c$ more \\textbf{blue} pandas check position $x$ for red pandas at time $t$. If a blue panda does not meet a red panda at that specific location and time, they dejectedly leave the number line right away. If there is a red panda at a position at the same time a blue panda checks it, they form a friendship and leave the number line. Each red panda can form a friendship with \\textbf{at most one} blue panda and vice versa.\n\nThe updates will be given in order of \\textbf{non-decreasing} $x$ values. After each update, please print the maximum number of friendships if the red pandas move in an optimal order based on all the updates given in the input above (and including) this update.\n\nThe order in which a red panda moves can change between updates.",
    "tutorial": "If we want to answer one of the questions (say, the question involving all the events) in polynomial time, how do we do it? Construct a network with edges from the source to each of the red panda events with capacities equal to the number of red pandas, edges from red panda events to blue panda events with innite capacities if the red pandas can catch the corresponding blue pandas, and edges from each of the blue panda events to the sink with capacities equal to the number of blue pandas. The next step is to use the max-flow min-cut theorem: the maximum flow is equal to the minimum number of red pandas plus blue pandas we need to remove from the graph such that no remaining red panda can reach any remaining blue panda. How do we go from here? For any cut, consider the region of the $x$-$t$ plane reachable by the remaining red pandas. No remaining blue pandas can lie in this region, and its border is a polyline that intersects each vertical line in the $x$-$t$ plane exactly once. Furthermore, the slope of every segment in this polyline has slope plus or minus $1$. Conversely, we can associate every polyline satisfying this condition with a cut; we just need to remove every red panda lying below the polyline and every blue panda lying on or above the polyline. Now, figure out how to answer the queries online. Read the hints to understand the solution better. We can answer the queries online. For each $x$-coordinate $x$, maintain a treap that stores for every $x$-coordinate, the minimum cut $dp[x][t]$ associated with a polyline satisfying the condition above that starts at $x = -\\infty$ and ends at $(x, t)$ when only considering events with $x$-coordinate at most $x$. When transitioning from to $x$ to $x+1$, we need to set for every $dp[x+1][t] = min(dp[x][t-1], dp[x][t], dp[x][t+1])$ for every $t$. To do this quickly, we maintain the values of $t$ where $dp[x][t+1] - dp[x][t] \\neq 0$ in increasing order, of which there are at most $n$. When $x$ increases by one, each value of increases or decreases by one, depending on the sign of $dp[x][t+1]-dp[x][t]$, and some of the values of $t$ merge, decreasing the size of our treap. As long as we can process each merge in $\\log n$ time, our solution will run in $O(n\\log n)$ total time. When processing an event, we need to increase all $dp$ values in a suffix for red panda events, and all $dp$ values in a prefix for blue panda events. To answer a query, we just need to return the minimum prefix sum in our treap.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define pb push_back\n#define ff first\n#define ss second\n\ntypedef long long ll;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\n\nconst int INF = 1e9 + 1;\n\nvoid setIO() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n}\n\nstruct node {\n    //mnpos - leftmost negative \n    //mxpos - rightmost positive\n    int pos, tag, mnpos, mxpos;\n    //minimum distance\n    pair<int, pii> mndif;\n    ll sum, pre, val;\n    int weight;\n\n    node(){}\n\n    node(int pos_, ll val_){\n        pos = pos_;\n        val = val_;\n        sum = val;\n        pre = min((ll)0, val);\n        mxpos = -INF;\n        mnpos = INF;\n        mndif = {INF, {INF, INF}};\n        if(val > 0) mxpos = pos;\n        if(val < 0) mnpos = pos;\n        tag = 0;\n        weight = rand();\n    }\n};\n\nint sz = 1;\nnode treap[1000005];\nint left0[1000005];\nint right0[1000005];\n\nint newnode(int pos, ll val){\n    treap[sz] = node(pos, val);\n    return sz++;\n}\n\npair<int, pii> comb(int a, int b){\n    if(a == -INF || b == INF) return {INF, {INF, INF}};\n    return {b - a, {a, b}};\n}\n\nvoid pull(int x){\n    treap[x].sum = treap[x].val;\n    treap[x].pre = min((ll)0, treap[x].val);\n    treap[x].mxpos = -INF;\n    treap[x].mnpos = INF;\n    treap[x].mndif = {INF, {INF, INF}};\n    if(treap[x].val > 0) treap[x].mxpos = treap[x].pos;\n    if(treap[x].val < 0) treap[x].mnpos = treap[x].pos;\n    if(left0[x]){\n        treap[x].mndif = min(treap[x].mndif, treap[left0[x]].mndif);\n        treap[x].mndif = min(treap[x].mndif, comb(treap[left0[x]].mxpos, treap[x].mnpos));\n        treap[x].mnpos = min(treap[x].mnpos, treap[left0[x]].mnpos);\n        treap[x].mxpos = max(treap[x].mxpos, treap[left0[x]].mxpos);\n        treap[x].pre = min(treap[left0[x]].pre, treap[left0[x]].sum + treap[x].pre);\n        treap[x].sum += treap[left0[x]].sum; \n    }\n    if(right0[x]){\n        treap[x].mndif = min(treap[x].mndif, treap[right0[x]].mndif);\n        treap[x].mndif = min(treap[x].mndif, comb(treap[x].mxpos, treap[right0[x]].mnpos));\n        treap[x].mnpos = min(treap[x].mnpos, treap[right0[x]].mnpos);\n        treap[x].mxpos = max(treap[x].mxpos, treap[right0[x]].mxpos);\n        treap[x].pre = min(treap[x].pre, treap[x].sum + treap[right0[x]].pre);\n        treap[x].sum += treap[right0[x]].sum;\n    }\n}\n\nint move(node& x, int shift){\n    int ret = x.pos;\n    if(x.val < 0) ret -= shift;\n    if(x.val > 0) ret += shift;\n    return ret;\n}\n\nvoid apply(int x, int tag){\n    treap[x].pos = move(treap[x], tag);\n    treap[x].tag += tag;\n    if(treap[x].mnpos != INF) treap[x].mnpos -= tag;\n    if(treap[x].mxpos != -INF) treap[x].mxpos += tag;\n    if(treap[x].mndif.ff != INF){\n        treap[x].mndif.ff -= 2*tag;\n        treap[x].mndif.ss.ff += tag;\n        treap[x].mndif.ss.ss -= tag;\n    }\n}\n\nvoid push(int x){\n    if(!treap[x].tag) return;\n    if(left0[x]) apply(left0[x], treap[x].tag);\n    if(right0[x]) apply(right0[x], treap[x].tag);\n    treap[x].tag = 0;\n}\n\nint merge(int a, int b){\n    if(!a) return b;\n    if(!b) return a;\n    if(treap[a].weight < treap[b].weight){ \n        push(a);\n        right0[a] = merge(right0[a], b);\n        pull(a);\n        return a;\n    } else {\n        push(b);\n        left0[b] = merge(a, left0[b]);\n        pull(b);\n        return b;\n    }\n}\n\n//splits rt's tree into [0, k) [k, INF)\npair<int, int> split(int x, int k){\n    if(!x) return pair<int, int>{0, 0};\n    push(x);\n    pair<int, int> ret;\n    if(treap[x].pos < k){\n        ret = split(right0[x], k);\n        right0[x] = ret.first;\n        ret.first = x;\n    } else {\n        ret = split(left0[x], k);\n        left0[x] = ret.second;\n        ret.second = x;\n    }\n    pull(x);\n    return ret;\n}\n\nint rt = 0;\n\nvoid erase(int x){\n    pair<int, int> a = split(rt, x);\n    pair<int, int> b = split(a.second, x + 1);\n    rt = merge(a.first, b.second);\n}\n\n//position, value\nvoid insert(int a, ll b){\n    if(!rt){\n        rt = newnode(a, b);\n        return;\n    }\n    pair<int, int> nw = split(rt, a);\n    rt = merge(nw.first, merge(newnode(a, b), nw.second));\n}\n\n//value\nll query(int x){\n    pair<int, int> a = split(rt, x);\n    pair<int, int> b = split(a.second, x + 1); \n    ll ret = (b.first ? treap[b.first].val : 0);\n    rt = merge(a.first, merge(b.first, b.second));\n    return ret;\n}\n\nint main(){\n    setIO();\n    int n;\n    cin >> n;\n    int prv = 0;\n    ll st = 0;\n    for(int i = 1; i <= n; i++){\n        int x, t, c;\n        cin >> x >> t >> c;\n        int dif = x - prv;\n        //remove overlap\n        while(rt && treap[rt].mndif.ff <= 2*dif){\n            pair<int, pii> x = treap[rt].mndif;\n            ll a = query(x.ss.ff), b = query(x.ss.ss);\n            ll sub = min(a, -b);\n            erase(x.ss.ff);\n            erase(x.ss.ss);\n            a -= sub, b += sub;\n            if(a != 0) insert(x.ss.ff, a);\n            if(b != 0) insert(x.ss.ss, b);\n        }\n        //shift everything\n        if(rt){\n            treap[rt].pos = move(treap[rt], dif);\n            treap[rt].tag += dif;\n            if(treap[rt].mnpos != INF) treap[rt].mnpos -= dif;\n            if(treap[rt].mxpos != -INF) treap[rt].mxpos += dif;\n            if(treap[rt].mndif.ff != INF){\n                treap[rt].mndif.ff -= 2*dif;\n                treap[rt].mndif.ss.ff += dif;\n                treap[rt].mndif.ss.ss -= dif;\n            }\n        }\n        ll cur = query(t + 1);\n        if(cur != 0) erase(t + 1);\n        if(cur - c != 0) insert(t + 1, cur - c);\n        if(c > 0) st += c;\n        cout << st + (!rt ? 0 : treap[rt].pre) << endl;\n        prv = x;\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "flows"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1853",
    "index": "A",
    "title": "Desorting",
    "statement": "Call an array $a$ of length $n$ sorted if $a_1 \\leq a_2 \\leq \\ldots \\leq a_{n-1} \\leq a_n$.\n\nNtarsis has an array $a$ of length $n$.\n\nHe is allowed to perform one type of operation on it (zero or more times):\n\n- Choose an index $i$ ($1 \\leq i \\leq n-1$).\n- Add $1$ to $a_1, a_2, \\ldots, a_i$.\n- Subtract $1$ from $a_{i+1}, a_{i+2}, \\ldots, a_n$.\n\nThe values of $a$ can be negative after an operation.\n\nDetermine the minimum operations needed to make $a$ \\textbf{not sorted}.",
    "tutorial": "To make $a$ not sorted, we just need to pick one index $i$ so $a_i > a_{i + 1}$. How do we do this? To make $a$ not sorted, we just have to make $a_i > a_{i + 1}$ for one $i$. In one operation, we can reduce the gap between two adjacent elements $i, i + 1$ by $2$ by adding $1$ to $1 \\dots i$ and subtracting $1$ from ${i + 1} \\dots n$. It is clearly optimal to pick the smallest gap between a pair of adjacent elements to minimize the number of operations we have to do. If we have $a_i = x, a_{i + 1} = y$, we can make $x > y$ within $\\lfloor \\frac{(y - x)}{2} \\rfloor + 1$ operations. Thus, we can just go through $a$, find the minimum difference gap, and calculate the minimum operations using the above formula. Note that if $a$ is not sorted, we can just output $0$. The time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n#include <numeric>\nusing namespace std;\n \nint main(){\n \n    ios::sync_with_stdio(false);\n    cin.tie(0);\n \n    int T; cin >> T;\n \n    while (T--) {\n \n        int n; cin >> n;\n        vector<int> nums(n);\n        int diff = 1e9;\n        bool sorted = true;\n        for (int i = 0; i < n; i++) {\n            cin >> nums[i];\n            if (i > 0) {\n                diff = min(nums[i] - nums[i - 1], diff);\n                sorted &= nums[i] >= nums[i - 1];\n            }\n        }\n        \n        if (!sorted) {\n            cout << 0 << endl;\n            continue;\n        }\n    \n        cout << diff/2 + 1 << endl;\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1853",
    "index": "B",
    "title": "Fibonaccharsis",
    "statement": "Ntarsis has received two integers $n$ and $k$ for his birthday. He wonders how many fibonacci-like sequences of length $k$ can be formed with \\textbf{$n$ as the $k$-th element} of the sequence.\n\nA sequence of \\textbf{non-decreasing non-negative} integers is considered fibonacci-like if $f_i = f_{i-1} + f_{i-2}$ for all $i > 2$, where $f_i$ denotes the $i$-th element in the sequence. Note that $f_1$ and $f_2$ can be arbitrary.\n\nFor example, sequences such as $[4,5,9,14]$ and $[0,1,1]$ are considered fibonacci-like sequences, while $[0,0,0,1,1]$, $[1, 2, 1, 3]$, and $[-1,-1,-2]$ are not: the first two do not always satisfy $f_i = f_{i-1} + f_{i-2}$, the latter does not satisfy that the elements are non-negative.\n\nImpress Ntarsis by helping him with this task.",
    "tutorial": "Can a sequence involving $n$, which is up to $10^5$, really have up to $10^9$ terms? The terms of the fibonacci sequence will increase exponentially. This is quite intuitive, but mathematically, fibonnaci-like sequences will increase at a rate of phi to the power of $n$, where phi (the golden ratio) is about $1.618$. Thus, the maximum number of terms a sequence can have before it reaches $10^9$, or the maximum value of $n$, is pretty small (around $\\log n$). Instead of trying to fix the first two elements of the sequence and counting how many sequences $s$ will have $s_k = n$, note that we already have $n$ fixed. If we loop over the $k-1$th element of the sequence, the sequence is still fixed. If we know the $x$th element and $x-1$th element of $s$, we can find that $s_{x - 2} = s_{x} - s_{x - 1}$. Thus, we can just go backwards and simulate for $k$ iterations in $O(\\log n)$ since $k$ is small, breaking at any point if the current sequence is not fibonnaci-like (there are negative elements or it is not strictly increasing). Otherwise, we add $1$ to our answer. The time complexity is $O(n \\cdot \\log n)$. Bonus: Solve for $n, k \\leq 10^9$ Analysis by awesomeguy856 $f[k] = F_{k-2}f[0]+F_{k-1}f[1]$ By the Extended Euclidean Algorithm, we can find one integral solution for this equation, since $\\gcd (F_{k-2}, F_{k-1}) = 1 | f[k].$ Let this solution be $(f[0], f[1]) = (x, y).$ Then all other integral solutions are in the form $(x+cF_{k-1}, y-cF_{k-2}),$ for $c \\in Z$ so we can find all valid solutions by binary search on $f[1],f[0] \\geq 0$ and $f[1]>f[0]$, or just by some calculations.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    int T; cin >> T;\n    \n    while (T--) {\n \n        int n; int k;\n        cin >> n >> k;\n     \n        int ans = 0;\n     \n        for (int i = 1; i <= n; i++) {\n            int second = n; //xth element where x is k\n            int first = i; //fixing x-1th element where x is k-1\n            bool valid_seq = true;\n            for (int j = 0; j < k - 2; j++) {\n                //for s_x and s_x-1, s_x-2 = s_x - s_x-1\n                int fx = first;\n                first = second - fx;\n                second = fx;\n                valid_seq &= first <= second;\n                valid_seq &= min(first, second) >= 0;\n                if (!valid_seq) break; //break if the sequence is not fibonacci-like\n            }\n            if (valid_seq) ans++;\n        }\n \n        cout << ans << endl;\n    }\n \n}",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1854",
    "index": "A1",
    "title": "Dual (Easy Version)",
    "statement": "\\begin{quote}\nPopskyy & tiasu - Dual\n\\hfill ⠀\n\\end{quote}\n\n\\textbf{The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.}\n\nYou are given an array $a_1, a_2,\\dots, a_n$ of integers (positive, negative or $0$). You can perform multiple operations on the array (possibly $0$ operations).\n\nIn one operation, you choose $i, j$ ($1 \\leq i, j \\leq n$, they can be equal) and set $a_i := a_i + a_j$ (i.e., add $a_j$ to $a_i$).\n\nMake the array non-decreasing (i.e., $a_i \\leq a_{i+1}$ for $1 \\leq i \\leq n-1$) in at most $50$ operations. You do not need to minimize the number of operations.",
    "tutorial": "There are several solutions to the easy version. In any case, how to get $a_i \\leq a_{i+1}$? For example, you can try making $a_{i+1}$ bigger using a positive element. What to do if all the elements are negative? If all the elements are negative, you can win in $n-1$ moves. If there is a positive element, you can try to make $a_1 \\leq a_2$, then $a_2 \\leq a_3$, etc. Make a big positive element using moves $(i, i)$, then make $a_2$ bigger. If all the elements are negative, you can make suffix sums (they are nondecreasing) with moves $(n-1, n), (n-2, n-1), \\dots$ If there is at least one positive element $a_x$, make $a_x > 20$ using $5$ moves $(x, x)$; make $a_2$ the biggest element using $2$ moves $(2, x)$; make $a_3$ the biggest element using $2$ moves $(3, 2)$; ... This strategy requires $5 + 2(n-1) \\leq 43$ moves. Complexity: $O(n)$",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1854",
    "index": "A2",
    "title": "Dual (Hard Version)",
    "statement": "\\begin{quote}\nPopskyy & tiasu - Dual\n\\hfill ⠀\n\\end{quote}\n\n\\textbf{The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.}\n\nYou are given an array $a_1, a_2,\\dots, a_n$ of integers (positive, negative or $0$). You can perform multiple operations on the array (possibly $0$ operations).\n\nIn one operation, you choose $i, j$ ($1 \\leq i, j \\leq n$, they can be equal) and set $a_i := a_i + a_j$ (i.e., add $a_j$ to $a_i$).\n\nMake the array non-decreasing (i.e., $a_i \\leq a_{i+1}$ for $1 \\leq i \\leq n-1$) in at most $31$ operations. You do not need to minimize the number of operations.",
    "tutorial": "The hints and the solution continue from the easy version. You can win in $n-1$ moves if all the elements are negative, but also if all the elements are positive. Again, make a big positive / negative element, then use it to make everything positive / negative. In how many moves can you either make everything positive or make everything negative? Assume the positive elements are at least as many as the negative elements. Can you win in $34$ moves? The bottleneck is making the big positive element. Is it always necessary? Can you find a better bound on the \"best\" number of moves? If you either make everything positive or make everything negative, you can win in $n-1 \\leq 19$ moves by making prefix sums or suffix sums, respectively. So, you have to reach one of these configurations in $12$ moves. How to make everything positive? First, you create a big element with the maximum absolute value (this requires $x_1$ moves), then you add it to every negative element (this requires $x_2$ moves). $y_1$ and $y_2$ are defined similarly in the negative case. So, one of $x_1$ and $y_1$ is $0$ (because the element with the maximum absolute value at the beginning is either positive or negative), and the other one is $\\leq 5$ (because you can make $|a_i| \\geq 32$ in $5$ moves); $x_2$ is the number of negative elements, $y_2$ is the number of positive elements. So, $x_2 + y_2 \\leq n \\leq 20$. Therefore, you need additional $\\min(x_1 + x_2, y_1 + y_2)$ moves. Since $x_1 + x_2 + y_1 + y_2 \\leq 25$, $\\min(x_1 + x_2, y_1 + y_2) \\leq \\lfloor \\frac{25}{2} \\rfloor = 12$, as we wanted. Now you can simulate the process in both cases (positive and negative), and choose one that requires $\\leq 31$ moves in total. Complexity: $O(n)$",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1854",
    "index": "B",
    "title": "Earn or Unlock",
    "statement": "Andrea is playing the game Tanto Cuore.\n\nHe has a deck of $n$ cards with values $a_1, \\ldots, a_n$ from top to bottom. Each card can be either locked or unlocked. Initially, only the topmost card is unlocked.\n\nThe game proceeds in turns. In each turn, Andrea chooses an unlocked card in the deck — the value written on the card is $v$ — and performs exactly one of the following two operations:\n\n- Unlock the first $v$ \\textbf{locked} cards in the deck from the top. If there are less than $v$ locked cards in the deck, then unlock all the locked cards.\n- Earn $v$ \\underline{victory points}.\n\nIn both cases, after performing the operation, he removes the card from the deck.The game ends when all the cards remaining in the deck are locked, or there are no more cards in the deck.\n\nWhat is the maximum number of victory points Andrea can earn?",
    "tutorial": "The order of used cards doesn't matter. So, you can assume you always use the card on the top. Suppose that you unlock $x$ cards in total. How many points can you get? If you unlock $x$ cards, it means you end up making moves with the first $x$ cards. So, you know the total number of (cards + points) that you get. If you unlock $x$ cards, the number of points is uniquely determined. It's convenient to assume that $x \\leq 2n$ and the cards $n+1, \\dots, 2n$ have value $0$. Now you have to determine the unlockable prefixes of cards (i.e., the values of $x$ you can reach). It looks similar to knapsack. You can optimize the solution using a bitset. Be careful not to use locked cards. First, note that the order of used cards doesn't matter. If you use at least once a card that is not on the top on the deck, you can prove that using the cards in order (from the top) would give the same number of victory points. Let's add $n$ cards with value $0$ at the end of the deck. Then, it's optimal to unlock $x \\leq 2n$ cards, and use cards $1, \\dots, x$, getting $a_1 + \\dots + a_x - x + 1$ points. Let's find the reachable $x$. Let $dp_i$ be a bitset that stores the reachable $x$ after using the first $i$ cards. Base case: $dp_{0,1} = 1$. Base case: $dp_{0,1} = 1$. Transitions: first, $dp_{i}$ |= $dp_{i-1}$ << $a_i$. If $dp_{i,i} = 1$, you can update the answer with $a_1 + \\dots + a_i - i + 1$, but you can't unlock any other card, so you have to set $dp_{i,i} = 0$ before transitioning to $i+1$. Transitions: first, $dp_{i}$ |= $dp_{i-1}$ << $a_i$. If $dp_{i,i} = 1$, you can update the answer with $a_1 + \\dots + a_i - i + 1$, but you can't unlock any other card, so you have to set $dp_{i,i} = 0$ before transitioning to $i+1$. Complexity: $O(n^2/w)$",
    "tags": [
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1854",
    "index": "C",
    "title": "Expected Destruction",
    "statement": "You have a set $S$ of $n$ distinct integers between $1$ and $m$.\n\nEach second you do the following steps:\n\n- Pick an element $x$ in $S$ uniformly at random.\n- Remove $x$ from $S$.\n- If $x+1 \\leq m$ and $x+1$ is not in $S$, add $x+1$ to $S$.\n\nWhat is the expected number of seconds until $S$ is empty?\n\nOutput the answer modulo $1\\,000\\,000\\,007$.\n\nFormally, let $P = 1\\,000\\,000\\,007$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{a}{b}$, where $a$ and $b$ are integers and $b \\not \\equiv 0 \\pmod{P}$. Output the integer equal to $a \\cdot b^{-1} \\bmod P$. In other words, output an integer $z$ such that $0 \\le z < P$ and $z \\cdot b \\equiv a \\pmod{P}$.",
    "tutorial": "Consider $n$ blocks in positions $S_1, S_2, \\dots, S_n$. After how much time does block $x$ disappear? It may be convenient to put a fake \"static\" block in position $m+1$. Block $x$ disappears when it reaches block $x+1$. But what if block $x+1$ disappears before block $x$? From the perspective of block $x$, it's convenient to assume that block $x+1$ never disappears: when it touches another block $y$, it's $y$ that disappears. When you consider the pair of blocks $x, x+1$, the other blocks don't really matter, and you can use linearity of expectation to calculate the contribution of each pair independently. A reasonable interpretation is given by considering an $(n+1) \\times (m+1)$ grid, where the $i$-th row initially contains a block in column $S_i$. Then, you are calculating the expected time required for the blocks $1, \\dots, m$ to have another block immediately below them (in the same column). Blocks $x, x+1$ both move with probability $1/2$, unless block $x+1$ has reached position $m+1$. $dp_{i,j} =$ expected number of moves of block $x$ before it disappears, if the block $x$ is in position $i$ and the block $x+1$ is in position $j$. Consider an $(n+1) \\times (m+1)$ grid, where the $i$-th row initially contains a block in column $S_i$, and row $n+1$ contains a block in column $m+1$. The set is empty if all the blocks are in column $m+1$; i.e., if every block has reached the block in the following row. Every \"connected component\" of blocks (except the last one) represents an element in the set. These components move equiprobably. Let's calculate the expected time required for the block in row $x$ to \"reach\" the block in row $x+1$. If you consider a single pair of blocks, every block moves with probability $1/2$, unless block $x+1$ is in column $m+1$. So, you can calculate $dp_{i,j} =$ expected number of moves of the block $x$ before it reaches the block $x+1$, if the block $x$ is in position $i$ and the block $x+1$ is in position $j$. The base cases are $dp_{i,m+1} = (m+1)-i$ (because only the block $x$ can move) and $dp_{i,i} = 0$ (because block $x$ has already reached block $x+1$). In the other cases, $dp_{i,j} = ((dp_{i+1,j} + 1) + dp_{i,j+1})/2$. By linearity of expectation, the answer is the sum of $dp_{S_i, S_{i+1}}$. Complexity: $O(m^2)$",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1854",
    "index": "D",
    "title": "Michael and Hotel",
    "statement": "Michael and Brian are stuck in a hotel with $n$ rooms, numbered from $1$ to $n$, and need to find each other. But this hotel's doors are all locked and the only way of getting around is by using the teleporters in each room. Room $i$ has a teleporter that will take you to room $a_i$ (it might be that $a_i = i$). But they don't know the values of $a_1,a_2, \\dots, a_n$.\n\nInstead, they can call up the front desk to ask queries. In one query, they give a room $u$, a positive integer $k$, and a set of rooms $S$. The hotel concierge answers whether a person starting in room $u$, and using the teleporters $k$ times, ends up in a room in $S$.\n\nBrian is in room $1$. Michael wants to know the set $A$ of rooms so that if he starts in one of those rooms they can use the teleporters to meet up. He can ask at most $2000$ queries.\n\nThe values $a_1, a_2, \\dots, a_n$ are fixed before the start of the interaction and do not depend on your queries. In other words, the interactor is not adaptive.",
    "tutorial": "You can find any $a_i$ in $9$ queries. Find the nodes in the cycle in the component with node $1$. What happens if you know the whole cycle? Suppose you already know some nodes in the cycle. Can you find other nodes faster? Can you \"double\" the number of nodes in the cycle? The component with node $1$ contains a cycle. If you know the whole cycle (of length $x$), you can win in $n-x$ queries by asking for each node if it ends up in the cycle after $n$ moves. You can get a node in the cycle in $9$ queries, doing a binary search on the $n$-th successor of node $1$. How to find the rest of the cycle? First, find $k$ nodes in the cycle, doing a binary search on the successor of the last node found. These nodes make a set $C$. Then, check for each node if it's \"sufficiently close\" to $C$, by asking $(i, k, C)$. Now, you know either $2k$ nodes in the cycle, or the whole cycle. Repeat until you get the whole cycle. If you choose $k = 63$, you spend at most $9 \\cdot 63 + (500 - 63) + (500 - 126) + (500 - 252) + (500 - 252) = 1874$ queries.",
    "tags": [
      "binary search",
      "interactive",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1854",
    "index": "E",
    "title": "Game Bundles",
    "statement": "Rishi is developing games in the 2D metaverse and wants to offer game bundles to his customers. Each game has an associated enjoyment value. A game bundle consists of a subset of games whose total enjoyment value adds up to $60$.\n\nYour task is to choose $k$ games, where $1 \\leq k \\leq 60$, along with their respective enjoyment values $a_1, a_2, \\dots, a_k$, in such a way that exactly $m$ distinct game bundles can be formed.",
    "tutorial": "Go for a randomized approach. Many ones are useful. Either you go for a greedy or for a backpack. We describe a randomized solution that solves the problem for $m$ up to $10^{11}$ (and, with some additional care, may be able to solve also $m$ up to $10^{12}$). We decided to give the problem with the smaller constraint $m\\le 10^{10}$ to make the problem more accessible and because there may be some rare cases below $10^{11}$ for which our solution is too slow (even though we could not find any). We don't know any provably correct solution, if you have one we would be curious to see it. We expect to see many different solutions for this problem. Main idea: Choose suitably the values $a_1, a_2, \\dots, a_h$ that belong to $[1,29]$ and then find $a_{h+1}, a_{h+2},\\dots,a_k$ in $[31,60]$ by solving a backpack-like problem. Let us describe more precisely the main idea. Assume that $a_1, a_2, \\dots, a_h\\le 30$ are fixed and they satisfy $a_1+a_2+\\cdots+a_h<60$. For any $s=0,1,2,\\dots,29$, let $f(s)$ be the number of subsets $I\\subseteq{1,2,\\dots,h}$ so that $\\sum_{i\\in I}a_i=s$. If we can find some values $0\\le s_1,s_2,\\dots,s_{k-h}\\le 29$ so that $f(s_1)+f(s_2)+\\cdots+f(s_{k-h})=s$, then by setting $a_{h+i} = 60-s_i$ for $i=1,2,\\dots, k-h$ we have found a valid solution to the problem. There are two main difficulties: How can we find $s_1, s_2,\\dots, s_{k-h}$? How should we choose $a_1, a_2,\\dots, a_h$? Since it is important to get a good intuitive understanding of the computational complexity of the algorithm, let us say now that we will choose $h\\le 44$ and (accordingly) $k-h=16$. These values are flexible (the solution would still work with $h\\le 45$ and $k-h=45$ for example). We will say something more about the choice of these values when we will describe how $a_1,a_2,\\dots, a_h$ shall be chosen. The backpack problem to find $s_1, s_2,\\dots, s_{k-h}$. The naive way to find $s_1,\\dots, s_{k-h}$ would be to try all of them. There are $\\binom{k-h + 29}{29}$ possible ways (up to order, which does not matter). Since $k-h=16$ this number is $\\approx 2\\cdot 10^{11}$ which is too much to fit in the time limit. To speed up the process, we will do as follows. Partition randomly $A\\cup B={0,1,\\dots, 29}$ into two sets of size $15$. We iterate over all possible $s_1, s_2, \\dots, s_{(k-h)/2}\\in A$ and over all possible $s_{(k-h)/2+1},\\dots, s_{k-h}\\in B$ and check whether the sum of one choice from the first group and one choice from the second group yields the result. This is a standard optimization for the subset sum problem. What is its complexity? It can be implemented in linear time in the size of the two groups we have to iterate over, which have size $\\binom{(k-h)/2+15}{15}\\approx 5\\cdot 10^5$. Notice that in this faster way we will not visit all the $\\binom{k-h+29}{29}$ possible choices $s_1,s_2,\\dots, s_{k-h}$ because we are assuming that exactly half of them belong to $A$ and exactly half of them belong to $B$. This is not a big deal because with sufficiently high probability we will find a solution in any case. The choice of $a_1, a_2,\\dots, a_{h}$. It remains to decide how we should select $a_1, a_2, \\dots, a_{h}$. The following choice works: Approximately the first $\\log_2(m)$ values are set equal to $1$. Five additional values are chosen randomly from $[1, 6]$ so that the total sum stays below $60$. One should repeat the whole process until a solution is found. Some intuition on the construction. The choice of $a_1, \\dots, a_{h}$ may seem arbitrary; let us try to justify it. The goal is to generate a set of values $f(0), f(1),\\dots, f(29)$ that are simultaneously ``random enough'' and with size smaller but comparable to $m$. These two conditions are necessary to expect that the backpacking problem finds a solution with high enough probability. If $a_1=a_2=\\cdots=a_{h}=1$, then $f(s) = \\binom{k-h}{s}$ and these numbers have size comparable to $m$ if $2^{h}$ is comparable to $m$. This observation explains why we start with approximately $\\log_2(m)$ ones. The issue is that we need some flexibility in the process as we may need to repeat it many times, this flexibility is provided by the addition of some additional random elements which don't change the magnitude of the values $f(0), f(1), \\dots, f(29)$ but that modify them as much as possible (if we added a large number it would not affect many $f(s)$ and thus it would not be very useful).",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1854",
    "index": "F",
    "title": "Mark and Spaceship",
    "statement": "Mark loves to move fast. So he made a spaceship that works in $4$-dimensional space.\n\nHe wants to use the spaceship to complete missions as fast as possible. In each mission, the spaceship starts at $(0, 0, 0, 0)$ and needs to end up at $(a, b, c, d)$. To do this, he instructs the spaceship's computer to execute a series of moves, where each move is a unit step in one of the eight cardinal directions: $(\\pm 1, 0, 0, 0)$, $(0, \\pm 1, 0, 0)$, $(0, 0, \\pm 1, 0)$, $(0, 0, 0, \\pm 1)$.\n\nUnfortunately, he also moved fast when building the spaceship, so there is a bug in the spaceship's code. The first move will be executed once, the second move will be executed twice, the third move will be executed thrice, and so on. In general, the $i$-th move will be executed $i$ times.\n\nFor any four integers $a, b, c, d$, let $f(a, b, c, d)$ be the minimum number of moves of a mission that ends up at $(a, b, c, d)$. Compute the sum of $f(a, b, c, d)$ over all points (with integer coordinates) such that $-A\\le a\\le A$, $-B\\le b\\le B$, $-C\\le c\\le C$, $-D\\le d\\le D$.",
    "tutorial": "Solve the 2d version first. The 4d version is not too different from the 2d one. Find all the points such that the expected number of necessary moves is wrong. Let us begin by cpnsidering the $2$-dimensional version of the problem. The solution to this simpler version provides the idea of the approach for the $4$-dimensional version. We want to reach $(a, b)$. Can we do it with exactly $k$ moves? Two simple necessary conditions are: $|a|+|b|\\le 1 + 2 + \\cdots + k$, $a+b$ and $1 + 2 + \\cdots + k$ shall have the same parity. It turns out that this two conditions are also sufficient! One can prove it by induction on $k$ as follows. If $k=0$ or $k=1$ or $k=2$ the statement is simple, thus we may assume $k\\ge 3$. Without loss of generality we may assume $0\\le a\\le b$. If $|a|+|b-k| \\le 1 + 2 + \\cdots + k-1$, then the statement follows by inductive hypothesis. Assume by contradiction that such inequality is false. If $b\\ge k$ then we have a contradiction because $|a|+|b-k| = |a|+|b|-k \\le (1 + 2 + \\cdots + k) - k$. Otherwise $b < k$ and the contradiction is $|a|+|b-k| = a + k-b \\le k \\le 1 + 2 + \\cdots + k-1$. Hence, we have shown: Lemma 1: The point $(a, b)$ is reachable with exactly $k$ moves if and only if $|a|+|b| \\le 1 + 2 + \\cdots + k$ and $a+b$ has the same parity of $1+2+\\cdots + k$. One may expect statement analogous to the one of Lemma 1 to hold also when there are $4$ coordinates. It does not, but it almost does and this is the crucial idea of the solution. More precisely, the number of counter examples to such statement is rather small and we can find all of them. This is the intuition behind the following definition. Definition: For $k\\ge 0$, let $A_k$ be the set of points $(a, b, c, d)$ such that $|a|+|b|+|c|+|d|\\le 1 + 2 + \\cdots + k$ and $a+b+c+d$ has the same parity of $1 + 2 + \\cdots + k$ but $(a, b, c, d)$ is not reachable with exactly $k$ moves. As an immediate consequence of the definition, we have Observation: The point $(a, b, c, d)$ is reachable with exactly $k$ moves if and only if $|a|+|b|+|c|+|d| \\le 1 + 2 + \\dots + k$ and $a+b+c+d$ has the same parity of $1+2+\\cdots + k$ and $(a, b, c, d)\\not\\in A_k$. Thanks to this observation, if one is able to efficiently find $A_k$ for all interesting values of $k$, then solving the problem is (comparatively) easy. The following lemma is our main tool for this purpose. Lemma 2: Assume that $(a, b, c, d) \\in A_k$ with $0\\le a\\le b\\le c\\le d$. Then, either $k\\le 6$ or $(a, b, c, d - k) \\in A_{k-1}$. Proof: The strategy is the same adopted to show Lemma 1. In some sense, we are saying that the inductive step works also in dimension $4$, but the base cases don't. If $|a|+|b|+|c|+|d-k|\\le 1 + 2 + \\cdots + k-1$, then it must be $(a, b, c, d-k)\\in A_{k-1}$ because if $(a, b, c, d-k$ were reachable with $k-1$ moves then $(a, b, c, d)$ were reachable with $k$ and we know that this is not true. Assume by contradiction that $|a|+|b|+|c|+|d-k|> 1 + 2 + \\cdots + k-1$. If $d\\ge k$ then we reach the contradiction $|a|+|b|+|c|+|d-k| = a+b+c+d-k \\le (1 + 2 + \\dots + k) - k$. Otherwise, $d < k$ and thus we reach the contradiction $|a|+|b|+|c|+|d-k| = a+b+c+k-d\\le a+b+k\\le 3k-2\\le 1 + 2 + \\dots + k-1$ (for $k\\ge 7$). We can now describe the solution. Assume that we know $A_{k-1}$. First of all, notice that it is then possible to determine in $O(1)$ whether a point belongs to $A_k$ or not. To generate a list of candidate elements for $A_k$ we proceed as follows: If $k\\le 6$, we simply iterate over all points with $|a|+|b|+|c|+|d|\\le 1 + 2 + \\cdots + k$. Otherwise, we iterate over the points in $A_{k-1}$ and we consider as candidate elements for $A_k$ the points that can be obtained by changing the value of one coordinate by $k$. Thanks to Lemma 2, we know that this process finds all the elements in $A_k$. Once $A_0, A_1, A_2, A_3,\\dots$ are known, the problem boils down to a (relatively) simple counting argument that we skip. One can verify that to handle correctly all points with coordinates up to $1000$ it is necessary to compute $A_k$ for $0\\le k \\le 62$. One additional cheap trick is required to make $A_k$ sufficiently small and get a sufficiently fast solution. Given $(a, b, c, d)$, the instance of the problem is equivalent if we change the signs of the coordinates or we change the order of the coordinates. Hence we shall always ``normalize'' the point so that $0\\le a \\le b\\le c\\le d$. If we do this consistently everywhere in the process, the solution becomes an order of magnitude faster. In particular, this trick guarantees $|A_k|\\le 5000$ for all $0\\le k\\le 62$. Bonus question: Find an explicit closed form for the elements in $A_k$ for any $k$. (in this way one can solve the problem also with larger constraints on $A, B, C, D$; but it is tedious)",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1855",
    "index": "A",
    "title": "Dalton the Teacher",
    "statement": "Dalton is the teacher of a class with $n$ students, numbered from $1$ to $n$. The classroom contains $n$ chairs, also numbered from $1$ to $n$. Initially student $i$ is seated on chair $p_i$. It is guaranteed that $p_1,p_2,\\dots, p_n$ is a permutation of length $n$.\n\nA student is happy if his/her number is different from the number of his/her chair. In order to make all of his students happy, Dalton can repeatedly perform the following operation: choose two distinct students and swap their chairs. What is the minimum number of moves required to make all the students happy? One can show that, under the constraints of this problem, it is possible to make all the students happy with a finite number of moves.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "What's the most efficient way to make the sad students happy? In most cases, you can make $2$ sad students happy in $1$ move. Let $s$ be the number of sad students at the beginning. The answer is $\\lceil \\frac{s}{2} \\rceil$. In one move, you can make at most $2$ sad students happy (because you can change the position of at most two students), so you need at least $\\lceil \\frac{s}{2} \\rceil$ moves. In fact, you can make everyone happy in exactly $\\lceil \\frac{s}{2} \\rceil$ moves: while there are at least $2$ sad students, you can swap them and both of them will be happy; if there is exactly $1$ sad student left, you can swap it with any other student. Complexity: $O(n)$",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1855",
    "index": "B",
    "title": "Longest Divisors Interval",
    "statement": "Given a positive integer $n$, find the maximum size of an interval $[l, r]$ of positive integers such that, for every $i$ in the interval (i.e., $l \\leq i \\leq r$), $n$ is a multiple of $i$.\n\nGiven two integers $l\\le r$, the size of the interval $[l, r]$ is $r-l+1$ (i.e., it coincides with the number of integers belonging to the interval).",
    "tutorial": "What's the answer if $n$ is odd? Try to generalize Hint 1. What's the answer if $n$ is not a multiple of $3$? If the answer is not a multiple of $x$, the answer is $< x$. If the answer is a multiple of $1, \\dots, x$, the answer is $\\geq x$. Suppose you find a valid interval $[l, r]$. Note that the interval $[l, r]$ contains at least one multiple of $x$ for each $1 \\leq x \\leq r-l+1$ (you can find it out by looking at the values in $[l, r]$ modulo $x$). Then, the interval $[1, r-l+1]$ is also valid and has the same length. So, it's enough to check intervals with $l = 1$, i.e., find the smallest $x$ that does not divide $n$. The answer is $x-1$. Complexity: $O(\\log(\\max n))$",
    "tags": [
      "brute force",
      "combinatorics",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1856",
    "index": "A",
    "title": "Tales of a Sort",
    "statement": "Alphen has an array of positive integers $a$ of length $n$.\n\nAlphen can perform the following operation:\n\n- For \\textbf{all} $i$ from $1$ to $n$, replace $a_i$ with $\\max(0, a_i - 1)$.\n\nAlphen will perform the above operation until $a$ is sorted, that is $a$ satisfies $a_1 \\leq a_2 \\leq \\ldots \\leq a_n$. How many operations will Alphen perform? Under the constraints of the problem, it can be proven that Alphen will perform a finite number of operations.",
    "tutorial": "Suppose we have performed $k$ operations and have gotten the array $b$. Then $b_i := \\max(0, a_i - k)$ for all $i$ from $1$ to $n$. If $b$ is sorted, then $b_i \\le b_{i + 1}$ for all $i$ from $1$ to $n - 1$. In other words, $\\max(0, a_i - k) \\le \\max(0, a_{i + 1} - k)$. Let's find for which $k$ this inequality holds. Suppose $a_i \\le a_{i + 1}$. Then $\\max(0, a_i - k) \\le \\max(0, a_{i + 1} - k)$ is true for any $k \\ge 0$. Now suppose $a_i > a_{i + 1}$. Then $\\max(0, a_i - k) \\le \\max(0, a_{i + 1} - k)$ is true only if $k \\ge a_i$. For the array to be sorted after $k$ operations, $\\max(0, a_i - k) \\le \\max(0, a_{i + 1} - k)$ must hold for all $1 \\le i < n$. From the statements above, we can see that the smallest $k$ for which this is true is equal to the maximum value of $a_{i}$ over all $1 \\le i < n$ such that $a_{i} > a_{i + 1}$. If no such $i$ exists, the answer is $0$, since the array is already sorted. Complexity: $\\mathcal{O}(n)$ Note: there are at least two other solutions: The solution above is also equivalent to finding the maximum value of $a_{i}$ over all $1 \\le i < j \\le n$ such that $a_i > a_j$, which leads to a $\\mathcal{O}(n^2)$ solution. Alternatively, you can do binary search on the answer to get a $\\mathcal{O}(n \\log A)$ solution, where $A$ is the maximum possible value of $a_i$.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector<int> a(n);\n    for (int i = 0; i < n; i++) cin >> a[i];\n    \n    int ans = 0;\n    for (int i = 0; i < n - 1; i++) {\n        if (a[i] > a[i + 1]) {\n            ans = max(ans, a[i]);\n        }\n    }\n    \n    cout << ans << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1856",
    "index": "B",
    "title": "Good Arrays",
    "statement": "You are given an array of \\textbf{positive} integers $a$ of length $n$.\n\nLet's call an array of \\textbf{positive} integers $b$ of length $n$ good if:\n\n- $a_i \\neq b_i$ for \\textbf{all} $i$ from $1$ to $n$,\n- $a_1 + a_2 +\\ldots + a_n = b_1 + b_2 + \\ldots + b_n$.\n\nDoes a good array exist?",
    "tutorial": "Suppose $b$ didn't have to consist of only positive integers. Then, one simple strategy would be to to decrease each of $a_2, a_3, \\ldots a_n$ by $1$ and increase $a_1$ by $n - 1$. Except for $n = 1$, when it is impossible to get a good array. When $b$ has to consist of only positive integers, we can't decrease elements that are equal to $1$. But to make $b_i \\neq a_i$, we also have to increase them by at least $1$. Let $cnt_1$ be the number of elements in $a$ that are equal to $1$. To not change the sum of the array, we have to decrease the other $n - cnt_1$ elements by at least $cnt_1$. For this to be possible, their sum must be equal to at least $(n - cnt_1) + cnt_1 = n$, since each of the $n - cnt_1$ elements must remain positive. So, $a_1 + a_2 + \\ldots + a_n$ has to be equal to at least $cnt_1 + (n - cnt_1) + cnt_1 = cnt_1 + n$. So, if $a_1 + \\ldots + a_n < cnt_1 + n$, a good array doesn't exist. If $n = 1$, a good array also doesn't exist. Now suppose $a_1 + \\ldots + a_n \\ge cnt_1 + n$ and $n \\neq 1$. We will prove that if this is the case, a good array must exist. If $cnt_1 \\le \\frac{n}{2}$, we increase all $a_i = 1$ by $1$ and decrease $cnt_1$ elements that are $\\ge 2$ by $1$ and apply the simple strategy described above for the other $n - 2 \\cdot cnt_1$ elements $\\ge 2$, so in this case, a good array exists. If $cnt_1 > \\frac{n}{2}$, we increase all $a_i = 1$ by $1$ and decrease each element $\\ge 2$ by at least $1$, so $b_i \\neq a_i$ holds for all $1 \\le i \\le n$, so in this case, a good array also exists. Complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector<int> a(n);\n    for (int i = 0; i < n; i++) cin >> a[i];\n    \n    ll sum_a = 0, cnt_1 = 0;\n    for (int x: a) {\n        sum_a += x;\n        if (x == 1) cnt_1++;\n    }\n    \n    if (sum_a >= cnt_1 + n && n > 1) {\n        cout << \"YES\" << nl;\n    } else {\n        cout << \"NO\" << nl;\n    }\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1856",
    "index": "C",
    "title": "To Become Max",
    "statement": "You are given an array of integers $a$ of length $n$.\n\nIn one operation you:\n\n- Choose an index $i$ such that $1 \\le i \\le n - 1$ and $a_i \\le a_{i + 1}$.\n- Increase $a_i$ by $1$.\n\nFind the maximum possible value of $\\max(a_1, a_2, \\ldots a_n)$ that you can get after performing this operation at most $k$ times.",
    "tutorial": "We will do binary search on the answer. The lower bound can be set to $0$, while $\\max(a_1, \\ldots a_n) + k$ is clearly enough for the upper bound. Let $b$ be some resulting array after performing at most $k$ operations. Suppose for some $x$ we want to check if we can get $\\max(b_1, \\ldots b_n) \\ge x$ in at most $k$ operations. That is, there must exist some index $i$ such that $b_i \\ge x$. So, let's iterate $i$ from $1$ to $n$ and check if it possible to have $b_i \\ge x$ in at most $k$ operations. Let $f(i, y)$ be the minimum number of operations needed to make $b_i \\ge y$. Then: $f(i, y) = 0$ for all $y \\le a_i$, $f(i, y) = y - a_i + f(i + 1, y - 1)$ for all $1 \\le i < n$ and $y > a_i$, $f(i, y) = +\\infty$ for $i = n$ and all $y > a_i$. It is easy to see that calculating $f(i, x)$ takes $\\mathcal{O}(n)$ time for one call in the worst case. Thus, our check consists of comparing $f(i, x)$ and $k$ for all $i$ from $1$ to $n$. If at least one of the values is $\\le k$, it is possible to have some $b_i \\ge x$ in at most $k$ operations and we increase the lower bound in the binary search after updating the current answer. Otherwise, it is impossible and we decrease the upper bound. Complexity: $\\mathcal{O}(n^2 \\cdot \\log A)$, where A is the maximum possible value of $a_i$ and $k$. Notes: You can get a $\\mathcal{O}(n^2 \\cdot \\log n)$ solution by setting the lower bound in the binary search to $\\max(a_1, \\ldots, a_n)$ and the upper bound to $\\max(a_1, \\ldots, a_n) + n$. There exists a $\\mathcal{O}(n^2)$ dp solution that relies on the fact that the answer lies in the range $[ \\max(a_1, \\ldots, a_n); \\max(a_1, \\ldots, a_n) + n ]$",
    "code": "#include <bits/stdc++.h>\n \n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n \nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n \nusing namespace std;\n \nvoid solve() {\n    ll n, k;\n    cin >> n >> k;\n    \n    vector<ll> a(n);\n    for (int i = 0; i < n; i++) cin >> a[i];\n    \n    ll lb = 0, ub = *max_element(all(a)) + k, ans = 0;\n    while (lb <= ub) {\n        ll tm = (lb + ub) / 2;\n        bool good = false;\n        \n        for (int i = 0; i < n; i++) {\n            vector<ll> min_needed(n);\n            min_needed[i] = tm;\n            \n            ll c_used = 0;\n            for (int j = i; j < n; j++) {\n                if (min_needed[j] <= a[j]) break;\n                \n                if (j + 1 >= n) {\n                    c_used = k + 1;\n                    break;\n                }\n                \n                c_used += min_needed[j] - a[j];\n                min_needed[j + 1] = max(0LL, min_needed[j] - 1);\n            }\n            \n            if (c_used <= k) good = true;\n        }\n        \n        if (good) {\n            ans = tm;\n            lb = tm + 1;\n        } else {\n            ub = tm - 1;\n        }\n    }\n    \n    cout << ans << nl;\n}\n \nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\t\n\tint T;\n\tcin >> T;\n\twhile (T--) solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1856",
    "index": "D",
    "title": "More Wrong",
    "statement": "\\textbf{This is an interactive problem.}\n\nThe jury has hidden a permutation$^\\dagger$ $p$ of length $n$.\n\nIn one query, you can pick two integers $l$ and $r$ ($1 \\le l < r \\le n$) by paying $(r - l)^2$ coins. In return, you will be given the number of inversions$^\\ddagger$ in the subarray $[p_l, p_{l + 1}, \\ldots p_r]$.\n\nFind the index of the maximum element in $p$ by spending at most $5 \\cdot n^2$ coins.\n\n\\textbf{Note: the grader is not adaptive}: the permutation is fixed before any queries are made.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^\\ddagger$ The number of inversions in an array is the number of pairs of indices $(i,j)$ such that $i < j$ and $a_i > a_j$. For example, the array $[10,2,6,3]$ contains $4$ inversions. The inversions are $(1,2),(1,3),(1,4)$, and $(3,4)$.",
    "tutorial": "Let $q(l, r)$ be be the number of inversions in the subarray $[p_l, p_{l + 1}, \\ldots p_r]$. If $l = r$, we have $q(l, r) = 0$, otherwise, $q(l, r) =$ is equal to the result of the query \"? l r\". Let $f(l, r)$ calculate the index of the maximum value in $p_l, p_{l+1}, \\ldots, p_r$. If $l = r$, we have $f(l, r) = l$. Suppose $l < r$. Let $i := f(l, m)$ and $j := f(m + 1, r)$, where $m := \\lfloor \\frac{l + r}{2} \\rfloor$. Let's compare $q(l, j - 1)$ and $q(l, j)$. If they are equal, $p_j$ is greater than all the elements in the subarray $[p_l, p_{l + 1}, \\ldots, p_m]$, so $f(l, r) = j$. If $q(l, j - 1) < q(l, j)$, $p_j$ is not greater that all the elements in the subarray $[p_l, p_{l + 1}, \\ldots, p_m]$, and thus, the maximum on the whole subarray is $p_i$, so $f(l, r) = i$. Note that the case $q(l, j - 1) > q(l, j)$ is impossible, since all inversions in the subarray $[p_l, p_{l + 1}, \\ldots, p_{j - 1}]$ remain as inversions for the subarray $[p_l, p_{l + 1}, \\ldots, p_j]$. To find the values of $q(l, j - 1)$ and $q(l, j)$, we will use $(j - 1 - l)^2 + (j - l)^2 \\le (r - l)^2 + (r - l)^2 = 2 \\cdot (r - l)^2$ coins. Let $g_n$ be the number of coins needed to find the maximum on a subarray of length $n$. We will prove by induction that $g_n \\le 4 \\cdot n^2$ for all natural $n$. Base case: $n = 1$, $g_1 := 0 \\le 4 \\cdot n^2 = 4$. Induction step: let $m := \\lceil \\frac{n}{2} \\rceil$. From the statements above, we have: $g_n \\le 2 \\cdot (n - 1)^2 + g_{m} + g_{n - m} \\le$ $2 \\cdot (n - 1)^2 + 4 \\cdot (m^2 + (n - m)^2) =$ $6n^2 + 8m^2 + 2 - 8nm - 4n =$ $4n^2 + 2 \\cdot (n^2 - 4nm + 4m^2) + 2 - 4n =$ $4n^2 + 2 \\cdot (n - 2m)^2 + 2 - 4n \\le$ $4n^2 + 2 \\cdot 1 + 2 - 4n =$ $4n^2 + 4 - 4n \\le 4n^2$ Thus, to calculate $f(1, n)$, the answer to our problem, we will use $g_n \\le 4 \\cdot n^2$ coins, which comfortably fits into the problem's $5 \\cdot n^2$ coin limit. Complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nint query(int l, int r) {\n    if (l == r) return 0;\n    cout << \"? \" << l << ' ' << r << endl;\n    \n    int res;\n    cin >> res;\n    return res;\n}\n\n// Finds max on p[l; r]\nint solve(int l, int r) {\n    if (l == r) return l;\n    \n    int m = (l + r) / 2;\n    int a = solve(l, m);\n    int b = solve(m + 1, r);\n    \n    int r1, r2;\n    r1 = query(a, b - 1);\n    r2 = query(a, b);\n    \n    if (r1 == r2) {\n        return b;\n    } else {\n        return a;\n    }\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    int ans = solve(1, n);\n    cout << \"! \" << ans << endl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "divide and conquer",
      "interactive"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1856",
    "index": "E1",
    "title": "PermuTree (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The differences between the two versions are the constraint on $n$ and the time limit. You can make hacks only if both versions of the problem are solved.}\n\nYou are given a tree with $n$ vertices rooted at vertex $1$.\n\nFor some permutation$^\\dagger$ $a$ of length $n$, let $f(a)$ be the number of pairs of vertices $(u, v)$ such that $a_u < a_{\\operatorname{lca}(u, v)} < a_v$. Here, $\\operatorname{lca}(u,v)$ denotes the lowest common ancestor of vertices $u$ and $v$.\n\nFind the maximum possible value of $f(a)$ over all permutations $a$ of length $n$.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Let's consider the subproblem of maximizing the number of suitable pairs for some fixed $\\operatorname{lca}(u, v) = x$. Then, we want to maximize the number of pairs $(u, v)$ such that $a_u < a_x < a_v$ and $u$ and $v$ are in different subtrees of $x$. So for each subtree of $x$, we only care about the number of vertices with $a_v > a_{x}$ and about the number of vertices with $a_v < a_x$. Suppose vertex $x$ has $m$ subtrees and the $i$-th of them has $s_i$ vertices in it and $b_i$ vertices less with $a_v < a_x$. We will prove later that a suitable permutation $a$ exists for all possible correct values of $b_i$ (that is $0 \\le b_i \\le s_i$). Then, the total number of suitable pairs (and the value we are trying to maximize) is equal to: $(s_1 - b_1) \\cdot(0 + b_2 + \\ldots + b_m) + (s_2 - b_2) \\cdot(b_1 + 0 + \\ldots + b_m) + \\ldots + (s_m - b_m) \\cdot(b_1 + b_2 + \\ldots + 0)$. Let $dp[i][B]$ be the maximum possible number of suitable pairs such that $u$ and $v$ lie in the first $i$ subtrees and $b_1 + b_2 + \\cdots + b_i = B$ ($0 \\le b_j \\le s_j$ for all $1 \\le j \\le i$). Also define $S_i := s_1 + s_2 + \\ldots + s_i$. Then: $dp[1][B] := 0$ for $0 \\le B \\le s_1$. $dp[i][B] := \\max\\limits_{\\max(0, B - S_{i-1}) \\le b_i \\le \\min(s_i, B)}{(dp[i - 1][B - b_i] + b_i \\cdot (S_{i-1} - (B - b_i)) + (s_i - b_i) \\cdot (B - b_i))}$ for $2 \\le i \\le m$ and $0 \\le B \\le S_{i}$. In the statement above: The limits for $b_i$ are $\\max(0, B - S_{i-1}) \\le b_i \\le \\min(s_i, B)$ because: $0 \\le b_i \\le s_i$ must hold, $0 \\le B - b_i \\le S_{i - 1}$ must hold. $0 \\le b_i \\le s_i$ must hold, $0 \\le B - b_i \\le S_{i - 1}$ must hold. $dp[i - 1][B - b_i]$ is the number of suitable pairs $(u, v)$ in the first $i - 1$ subtrees. $b_i \\cdot (S_{i-1} - (B - b_i))$ is the number of suitable pairs $(u, v)$ where $u$ lies in the $i$-th subtree and $v$ lies in the first $i - 1$ subtrees. $(s_i - b_i) \\cdot (B - b_i)$ is the number of suitable pairs $(u, v)$ where $v$ lies in the $i$-th subtree and $u$ lies in the first $i - 1$ subtrees. The maximum possible number of suitable pairs is equal to $\\max\\limits_{0 \\le B \\le S_m}{dp[m][B]}$. Let's calculate the complexity of this dynamic programming subproblem. To do that, it's easier to consider iterating over $b_i$ and then iterating over all suitable values of $B$. Then, from the condition $0 \\le b_i \\le s_i$ we get $s_i + 1$ values of $b_i$, and from the condition $0 \\le B - b_i \\le S_{i - 1} \\implies b_i \\le B \\le b_i + S_{i - 1}$ we get $S_{i - 1} + 1$ suitable values of $B$ for each $b_i$. Taking into account that the $dp[i][B]$ array has $m \\cdot (S_m + 1)$ values, adding everything up, the number of \"operations\" we get is equal to: $m \\cdot (S_m + 1) + (s_2 + 1) \\cdot (S_1 + 1) + (s_3 + 1) \\cdot (S_2 + 1) + \\ldots + (s_m + 1) \\cdot (S_{m - 1} + 1) =$ $m \\cdot (S_m + 1) + (s_2 \\cdot S_1 + s_3 \\cdot S_2 + \\ldots + s_m \\cdot S_{m-1}) + (s2 + \\ldots + s_m) + (S_1 + \\ldots + S_{m-1}) + (m - 1) \\le$ $m \\cdot S_m + m + (s_2 \\cdot S_1 + s_3 \\cdot S_2 + \\ldots + s_m \\cdot S_{m-1}) + S_m + (m - 1) \\cdot S_m + m =$ $2m \\cdot (S_m + 1) + (s_2 \\cdot S_1 + s_3 \\cdot S_2 + \\ldots + s_m \\cdot S_{m-1}) \\le$ $2mn + (s_2 \\cdot S_1 + s_3 \\cdot S_2 + \\ldots + s_m \\cdot S_{m-1})$ Returning to the original problem, let's solve the subproblem for each $x$ from $1$ to $n$ and add up the results. This is the upper bound on the answer, and we will prove a bit later that a suitable permutation $a$ exists. Let's change our notation a bit: $m_x$ is the number of subtrees of vertex $x$. $s_{x,i}$ is the size of the $i$-th subtree of vertex $x$. $S_{x,i}$ is equal to $s_{x,1} + s_{x,2} + \\ldots + s_{x,i}$. $b_{x,i}$ is the number of vertices in the $i$-th subtree for which $a_v < a_x$. Adding up the number of \"operations\" for all subproblems, we get: $\\displaystyle\\sum_{x=1} ^{n} (2m_xn + s_{x,2} \\cdot S_{x,1} + s_{x,3} \\cdot S_{x,2} + \\ldots + s_{x,m_x} \\cdot S_{x,m_x-1}) =$ $2n \\cdot (n - 1) + \\displaystyle\\sum_{x=1} ^{n} (s_{x,2} \\cdot S_{x,1} + s_{x,3} \\cdot S_{x,2} + \\ldots + s_{x,m_x} \\cdot S_{x,m_x-1})$ Consider an undirected graph with $n$ vertices where there are initially no edges. You can think of the value of $s_{x,j} \\cdot S_{x,j-1}$ as the number of edges added between each vertex of the first $j-1$ subtrees of $x$ and the $j$-th subtree of $x$. Since each pair of $(x, j)$ accounts for a unique set of edges of size $s_{x,j} \\cdot S_{x,j-1}$, the sum $\\sum_{x=1} ^{n} (\\ldots)$ can be bounded above by $\\frac{n \\cdot (n - 1)}{2}$, the maximum number of unique edges in a graph with $n$ vertices: $2n \\cdot (n - 1) + \\displaystyle\\sum_{x=1} ^{n} (s_{x,2} \\cdot S_{x,1} + s_{x,3} \\cdot S_{x,2} + \\ldots + s_{x,m_x} \\cdot S_{x,m_x-1}) \\le$ $2n \\cdot (n - 1) + \\frac{n \\cdot (n - 1)}{2}$ So we get a complexity of $\\mathcal{O}(n^2)$. You can read more about this complexity analysis in section 7 of this Codeforces blog. We solve independently for each value of $\\operatorname{lca}(u,v)$ and add up the answers to get an upper bound for $f(a)$. We will prove by constructing $a$ that this bound is achievable. Let $g(x, L)$ be a function that takes a vertex $x$ and a set of integers $L$, assigns some value from $L$ to $a_x$, and then calls $g(y, L_y)$ for all children of $x$ (direct descendants), where the sets $L_y$ do not intersect and their union is equal to $L \\setminus \\{ a_x \\}$. How it works: Let $y_{1}, \\ldots y_{m_x}$ be the children of vertex $x$ and $L_{y_i}$ initially be empty sets. Suppose that for vertex $x$ it is optimal to have the values of $b_{x,1}, b_{x,2}, \\ldots, b_{x,m_x}$ be equal to $c_1, c_2, \\ldots, c_{m_x}$ respectively. For each $i$ from $1$ to $m_x$, take the $c_i$ smallest values from $L$, remove them from $L$, and add them to the set $L_{y_i}$. Set $a_x$ to the smallest value in $L$ and remove it from the set. For each $i$ from $1$ to $m_x$, take the $s_i - c_i$ smallest values from $L$, remove them from $L$, and add them to the set $L_{y_i}$. For each $i$ from $1$ to $m_x$, call $g(y_i, L_{y_i})$. Calling $g(x, \\{1, 2, \\ldots n \\})$ constructs an optimal permutation $a$ for the given tree. Complexity: $\\mathcal{O}(n^2)$ Note: you can change $dp[i][B]$ to $dp[B]$ and iterate $B$ from $S_i$ to $0$. This improves the memory usage, but does not change the time complexity.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int maxn = 1000000;\n\nvector<int> g[maxn];\nint s[maxn];\nll ans = 0;\n\nvoid dfs(int v, int p = -1) {\n    vector<ll> a;\n    s[v] = 1;\n    \n    for (int u: g[v]) {\n        if (u == p) continue;\n        dfs(u, v);\n        s[v] += s[u];\n        \n        a.push_back(s[u]);\n    }\n    \n    vector<ll> dp(s[v]);\n    ll cs = 0;\n    for (int x: a) {\n        for (ll i = cs + x; i >= 0; i--) {\n            for (ll pr = min(cs, i); pr >= max(0LL, i - x); pr--) {\n                ll j = i - pr;\n                dp[i] = max(dp[i], dp[pr] + j * (cs - pr) + pr * (x - j));\n            }\n        } \n        cs += x;\n    }\n    \n    ans += *max_element(all(dp));\n    dp.clear();\n    a.clear();\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int n;\n    cin >> n;\n    for (int i = 1; i < n; i++) {\n        int x;\n        cin >> x;\n        g[x - 1].push_back(i);\n    }\n    \n    dfs(0);\n    \n    cout << ans << nl;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1856",
    "index": "E2",
    "title": "PermuTree (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The differences between the two versions are the constraint on $n$ and the time limit. You can make hacks only if both versions of the problem are solved.}\n\nYou are given a tree with $n$ vertices rooted at vertex $1$.\n\nFor some permutation$^\\dagger$ $a$ of length $n$, let $f(a)$ be the number of pairs of vertices $(u, v)$ such that $a_u < a_{\\operatorname{lca}(u, v)} < a_v$. Here, $\\operatorname{lca}(u,v)$ denotes the lowest common ancestor of vertices $u$ and $v$.\n\nFind the maximum possible value of $f(a)$ over all permutations $a$ of length $n$.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "First of all, the most important takeaways from the editorial for the easy version: For each $x$ from $1$ to $n$, you can solve $n$ independent subproblems of maximizing the number of suitable pairs for a fixed value of $\\operatorname{lca}(u, v) = x$, and then add up the results to get the final answer. For each subproblem, the number of suitable pairs of vertices can be calculate based on the sizes of all the child subtrees $s_{x,i}$ and the number of vertices with $a_v < a_x$ in each of them, which we will call $b_{x,i}$. Consider the subproblem for some $x$. Let $m_x$ be the number of child subtrees of vertex $x$. Suppose some optimal values of $b_{x,1}, b_{x,2}, \\ldots b_{x,m_x}$ that maximize the number of suitable pairs are $c_1, c_2, \\ldots c_{m_x}$ respectively. Claim: there exists an optimal solution where $c_i = 0$ or $c_i = s_{x,i}$ for all $i$ from $1$ to $m_x$. Proof: let's consider some optimal solution $c_1, c_2, \\ldots c_{m_x}$ where $0 < c_i < s_{x,i}$ for some $i$. Suppose $D$ is the number of suitable pairs of vertices such that both $u$ and $v$ don't lie in the $i$-th child's subtree. Then, the total number of suitable pairs is equal to: $D + c_i \\cdot \\sum_{j \\neq i}{(s_{x, j} - c_j)} + (s_{x, i} - c_i) \\cdot \\sum_{j \\neq i} c_j$ $D + c_i \\cdot C_1 + (s_{x, i} - c_i) \\cdot C_2 =$ $(D + C_2 \\cdot s_{x,i}) + c_i \\cdot (C_1 - C_2)$ The values of $(D + C_2 \\cdot s_{x,i})$, $C_1$, and $C_2$ don't depend on the value of $c_i$, so we can freely change it to anything from $[0; s_{x, i}]$ to maximize the value of the formula. So: If $C_1 \\ge C_2$, the value of the formula will not decrease if we set $c_i$ to $s_{x,i}$. If $C_1 \\le C_2$, the value of the formula will not decrease if we set $c_i$ to $0$. Since at least one of this conditions has to be true, we can always take some optimal solution with $k$ indices such that $0 < c_i < s_{x, i}$ and get an optimal solution with $k - 1$ such indices. We repeat this process until $k$ becomes $0$, which means that $c_i = 0$ or $c_i = s_{x, i}$ for all $i$ from $1$ to $m_x$, as was stated in the claim. Consider an optimal solution $c_1, c_2, \\ldots c_{m_x}$ where $c_i$ is equal to either $0$ or $s_{i, x}$. Let $S_1$ be the sum of $s_{i, x}$ over all $i$ such that $c_i = 0$ and $S_2$ be the sum of $s_{i, x}$ over all $i$ such that $c_i = s_{x, i}$. Then, the number of suitable pairs is equal to: $S_1 \\cdot S_2$ If we define $S$ as $s_{x, 1} + s_{x, 2} + \\ldots s_{x,m_x}$, we can see that $S_2$ is equal to $S - S_1$, so we are actually maximizing the value of: $S_1 \\cdot (S - S_1)$ To do this, we can iterate $S_1$ from $0$ to $S$, find if it is possible to choose some subset of indices $I \\subseteq \\{1, 2, \\ldots, m_x \\}$ such that $\\displaystyle\\sum_{i \\in I}{s_{x,i}} = S_1$, and update the current best answer if such a set $I$ exists. Doing this efficiently is known as the subset sum problem (or some variation of it). One of the simplest ways to solve it in this particular case with a $\\mathcal{O}(m_x \\cdot S)$ dynamic programming solution: $dp[j][S_1]$ is equal to $1$ if there exists a set of indices $I \\subseteq \\{ 1, 2, \\ldots, j \\}$ such that $\\displaystyle\\sum_{i \\in I}{s_{x,i}} = S_1$ and is equal to $0$ otherwise. We will proceed to optimize it. The first standard optimization will bring the complexity down to $\\mathcal{O}(S \\sqrt S)$, you can read about it in Section 3 of this Codeforces blog or in the \"Subset Sum Speedup 1\" section of this Codeforces blog. Since we are trying to maximize the value of $S_1 \\cdot (S - S_1)$, the optimal choice will also minimize the value of $| (S - S_1) - S_1 | = | S - 2S_1 |$. Claim: denote $\\max(s_{x,1}, \\ldots, s_{x,m_x})$ as $M_x$. If $M_x \\ge \\frac{S}{2}$, the smallest possible value of $| S - 2S_1 |$ is achieved with $S_1 = M_x$ or $S_1 = S - M_x$. Proof: it is clearly possible to get $S_1 = M_x$. Suppose it is possible to get some value of $S_1$ in the segment $[S - M_x + 1; M_x - 1]$. Then, $M_x$ did not contribute to the sum $S_1$, and so $S_1 + M_x$ can't exceed $S$. But $S_1 + M_x \\ge S - M_x + 1 + M_x = S + 1$, so we get a contradiction, hence it is not possible to get some $S_1 \\in [S - M_x + 1; M_x - 1]$. So if we have $M_x \\ge \\frac{S}{2}$, we actually don't have to run the dynamic programming part. We will now analyze the complexity of the solution with this optimization. Let's now define $S_x$ as $s_{x, 1} + \\ldots + s_{x, m_x}$. Let's also call a vertex $x$ heavy if $M_x \\ge \\frac{S_x}{2}$ and light otherwise. Suppose that vertex $x$ has $k$ light ancestors on it's path to the root: Every subtree of a light vertex $v$ has at most $\\frac{S_v}{2}$ vertices in it. Every subtree of a heavy vertex $v$ has at most $S_v - 1$ vertices in it. For each $k$ from $0$ to $n$, let $L_k$ be the set of light vertices with exactly $k$ light ancestors (a vertex doesn't count as it's own ancestor): Note that if two light vertices $u$ and $v$ are in the same set $L_k$, one can't be the ancestor of the other. So, the sum $\\sum_{x \\in L_{k}} S_x$ does not exceed $n$. $S_x \\le \\frac{n}{2^k}$ for all $x \\in L_{k}$. For some $k$, let's calculate the total number of \"operations\" taken in the dynamic programming part for all $x \\in L_k$. To do that, we: Iterate over the number of vertices in the set $L_{k}$, let's call it $p$, from $0$ to $n$. Let $d_1, d_2, \\ldots, d_p$ be the sizes of the subtrees of vertices in $L_{k}$. Then we need to maximize the value of: $d_1 \\sqrt d_1 + d_2 \\sqrt d_2 + \\ldots + d_p \\sqrt d_p$ over all $d_1, d_2, \\ldots, d_p$ such that $1 \\le d_n \\le \\frac{n}{2^k}$ and $d_1 + \\ldots + d_n \\le n$. $d_1 \\sqrt d_1 + d_2 \\sqrt d_2 + \\ldots + d_p \\sqrt d_p$ You might have noticed that the above process can be simplified by allowing $d_i$ to be equal to $0$. In that case, the number of vertices $p$ is equal to the number of positive integers in $d_1, d_2, \\ldots, d_n$, and we need to maximize: $d_1 \\sqrt d_1 + d_2 \\sqrt d_2 + \\ldots + d_n \\sqrt d_n$ over all integer $d_1, d_2, \\ldots , d_n$ such that $0 \\le d_n \\le \\frac{n}{2^k}$ and $d_1 + \\ldots + d_n \\le n$. Let $t := \\left\\lfloor \\frac{n}{2^k} \\right\\rfloor$. We'll assume $t \\ge 1$, otherwise, $d_i$ is equal to $0$ for all $1 \\le i \\le n$ and the sum is always equal to $0$. Lemma 1: it is optimal to have $d_1 + d_2 + \\ldots + d_n = n$. Proof: if we can increase some $d_i$, it is clearly optimal to do so. Lemma 2: suppose the maximum is achieved on the set of values $e_1, e_2, \\ldots, e_n$. Then there does not exist a pair of indices $i$ and $j$ such that $0 < e_i \\le e_j < t$. Proof: define $f(x) := \\left( x + 1 \\right) \\sqrt {x + 1} - x \\sqrt x$. Note that $f(x)$ is a monotonically increasing function for all $x \\ge 0$. You can prove it by, for example, analyzing it's derivative: $\\frac{3}{2} (\\sqrt {x + 1} - \\sqrt x)$. If we decrease $e_i$ by $1$ and increase $e_j$ by $1$, the sum changes by: $(e_j + 1) \\sqrt {e_j + 1} + (e_i - 1) \\sqrt {e_i - 1} - e_j \\sqrt e_j - e_i \\sqrt e_i =$ $f(e_j) - f(e_i - 1) > 0$ By doing this, we haven't broken any constraints on the values of $e_i$, but have increased the total sum, so the previous values of $e$ couldn't have been optimal. This lemma gives us the nice property that the optimal values of $e_1, e_2, \\ldots, e_n$ look something like $t, \\ldots, t, y, 0, \\ldots, 0$; where $0 < y < t$. With this we can conclude that the total number of \"operations\" performed for all vertices in $L_k$ is at most: $\\left\\lceil \\frac{n}{t} \\right\\rceil \\cdot t \\sqrt t \\le \\left( \\frac{n}{t} + 1 \\right) \\cdot t \\sqrt t \\le (n + t) \\sqrt t \\le 2n \\sqrt t$ Adding this up over all $k$ with $t \\ge 1$, we get: $2n \\cdot \\left(\\sqrt{\\left\\lfloor \\frac{n}{1} \\right\\rfloor} + \\sqrt{\\left\\lfloor \\frac{n}{2} \\right\\rfloor} + \\sqrt{\\left\\lfloor \\frac{n}{4} \\right\\rfloor} + \\sqrt{\\left\\lfloor \\frac{n}{8} \\right\\rfloor} + \\ldots + 1 \\right) \\le$ $2n \\cdot \\left( \\sqrt{\\frac{n}{1}} + \\sqrt{\\frac{n}{2}} + \\sqrt{\\frac{n}{4}} + \\sqrt{\\frac{n}{8}} + \\ldots \\right) =$ $2n \\sqrt n \\cdot \\left(1 + \\frac{1}{\\sqrt{2}} + \\frac{1}{\\sqrt{4}} + \\frac{1}{\\sqrt{8}} + \\ldots \\right)$ We can notice that the sum in the brackets in bounded by the sum of an infinite geometric progression with a sum of $\\frac{\\sqrt{2}}{\\sqrt{2} - 1} \\le 4$, so the total sum is: $\\le 2n \\sqrt n \\cdot 4 = 8n \\sqrt n = \\mathcal{O}(n \\sqrt n)$ Finally, we will also use bitsets to speed up our dynamic programming part and bring the complexity down to $\\mathcal{O}(\\frac{n \\sqrt n}{w})$, where $w$ is the word size, usually $32$ or $64$. You can learn about bitsets in this Codeforces blog. To get a simple variable length bitset in C++, refer to this comment. Complexity: $\\mathcal{O}(\\frac{n \\sqrt n}{w})$.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n#define gsize(x) (int)((x).size())\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int maxn = 1000000;\n\nvector<int> g[maxn];\nint s[maxn];\nll ans = 0;\nvector<ll> b;\nll closest;\n\ntemplate <int len = 1>\nvoid subset_sum(int n) {\n    if (n >= len) {\n        subset_sum<std::min(len*2, maxn)>(n);\n        return;\n    }\n    \n    bitset<len> dp;\n    \n    dp[0] = 1;\n    for (ll x: b) {\n        dp = dp | (dp << x);\n    }\n    \n    ll cv = n;\n    closest = 0;\n    for (int i = 0; i <= n; i++) {\n        if (dp[i] && abs(i - (n - i)) < cv) {\n            closest = i;\n            cv = abs(i - (n - i));\n        }\n    }\n}\n\nll solve(vector<ll> &a) {\n    if (a.empty()) return 0;\n    \n    sort(allr(a));\n    ll cs = 0;\n    for (ll x: a) cs += x;\n    \n    if (a[0] * 2 >= cs) {\n        return a[0];\n    }\n    \n    int n = gsize(a);\n    a.push_back(0);\n    \n    b.clear();\n    int pi = 0;\n    for (int i = 1; i <= n; i++) {\n        if (a[i] != a[i - 1]) {\n            ll cnt = i - pi;\n            ll x = a[i - 1];\n            \n            ll j = 1;\n            while (j < cnt) {\n                b.push_back(x * j);\n                cnt -= j;\n                j *= 2;\n            }            \n            b.push_back(x * cnt);\n\n            pi = i;\n        }\n    }\n    \n    subset_sum(cs);\n    return closest;\n}\n\nvoid dfs(int v, int p = -1) {\n    vector<ll> a;\n    s[v] = 1;\n    \n    for (int u: g[v]) {\n        if (u == p) continue;\n        dfs(u, v);\n        s[v] += s[u];\n        \n        a.push_back(s[u]);\n    }\n    \n    ll x = solve(a);\n    ans += x * (s[v] - 1 - x);\n    a.clear();\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int n;\n    cin >> n;\n    for (int i = 1; i < n; i++) {\n        int x;\n        cin >> x;\n        g[x - 1].push_back(i);\n    }\n    \n    dfs(0);\n    \n    cout << ans << nl;\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "fft",
      "greedy",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1857",
    "index": "A",
    "title": "Array Coloring",
    "statement": "You are given an array consisting of $n$ integers. Your task is to determine whether it is possible to color all its elements in two colors in such a way that the sums of the elements of both colors have the same parity and each color has at least one element colored.\n\nFor example, if the array is [$1,2,4,3,2,3,5,4$], we can color it as follows: [$\\textcolor{blue}{1},\\textcolor{blue}{2},\\textcolor{red}{4},\\textcolor{blue}{3},\\textcolor{red}{2},\\textcolor{red}{3},\\textcolor{red}{5},\\textcolor{red}{4}$], where the sum of the blue elements is $6$ and the sum of the red elements is $18$.",
    "tutorial": "Let's analyze the impact of adding odd or even numbers to a set with sum $S$: If you add an even element to the set, the parity of $S$ remains unchanged. If you add an odd element to the set, the parity of $S$ changes. Based on this observation, let's focus on the coloring of odd elements in the array. The number of odd elements colored in blue and the number of odd elements colored in red must have the same parity for a valid coloring. This is because we need to divide the odd elements into two parts (blue and red). To achieve the same parity for both blue and red odd elements, the total number of odd elements in the array must be even. If it is not even, we won't be able to create two sets with the same parity. Hence, the answer is \"YES\" if the number of odd elements in the array is even, and \"NO\" otherwise.",
    "code": "for i in range(int(input())):\n    n=int(input())\n    a=[*map(int,input().split())]\n    cnt=0\n    for i in range(n):\n        if a[i]%2!=0:cnt+=1\n    if cnt%2==0:print('YES')\n    else:print('NO')",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1857",
    "index": "B",
    "title": "Maximum Rounding",
    "statement": "Given a natural number $x$. You can perform the following operation:\n\n- choose a positive integer $k$ and round $x$ to the $k$-th digit\n\nNote that the positions are numbered from right to left, starting from zero. If the number has $k$ digits, it is considered that the digit at the $k$-th position is equal to $0$.\n\nThe rounding is done as follows:\n\n- if the digit at the $(k-1)$-th position is greater than or equal to $5$, then the digit at the $k$-th position is increased by $1$, otherwise the digit at the $k$-th position remains unchanged (mathematical rounding is used).\n- if before the operations the digit at the $k$-th position was $9$, and it should be increased by $1$, then we search for the least position $k'$ ($k'>k$), where the digit at the $k'$-th position is less than $9$ and add $1$ to the digit at the $k'$-th position. Then we assign $k=k'$.\n- after that, all digits which positions are less than $k$ are replaced with zeros.\n\nYour task is to make $x$ as large as possible, if you can perform the operation as many times as you want.\n\nFor example, if $x$ is equal to $3451$, then if you choose consecutively:\n\n- $k=1$, then after the operation $x$ will become $3450$\n- $k=2$, then after the operation $x$ will become $3500$\n- $k=3$, then after the operation $x$ will become $4000$\n- $k=4$, then after the operation $x$ will become $0$\n\nTo maximize the answer, you need to choose $k=2$ first, and then $k=3$, then the number will become $4000$.",
    "tutorial": "First, sorry for the unclear statement. We have rewritten it for several times and have chosen the best one. Let's define $n$ as the length of the $x$. Notice, that after applying the rounding to $k$, all the digits to the right of $k$ become $0$. If the $k$-th digit is less than $5$, after the rounding it'll only worsen the answer. On the other side, if the $k$-th digit is not less than $5$, than rounding to the $k$-th digit always leads to better answer, because after the operation $x$ will increase. From these observations, we can come up with the following greedy algorithm: look through all $k$ from $1$ to $n$, and if the $k$-th digit is not less than $5$, we use the rounding operation adding one to the ($k+1$)-th digit. And don't worry if that digit which must be increased by one is $9$, because in such case we always use the rounding operation on the next step.",
    "code": "for i in range(int(input())):\n    s=[0]+[*map(int,list(input()))]\n    k=len(s)\n    for i in range(len(s)-1,0,-1):\n        if s[i]>4:s[i-1]+=1;k=i\n    if s[0]!=0:print(s[0],end='')\n    s=[*map(str,s)]\n    print(''.join(s[1:k]+['0']*(len(s)-k)))",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1857",
    "index": "C",
    "title": "Assembly via Minimums",
    "statement": "Sasha has an array $a$ of $n$ integers. He got bored and for all $i$, $j$ ($i < j$), he wrote down the minimum value of $a_i$ and $a_j$. He obtained a new array $b$ of size $\\frac{n\\cdot (n-1)}{2}$.\n\nFor example, if $a=$ [$2,3,5,1$], he would write [$\\min(2, 3), \\min(2, 5), \\min(2, 1), \\min(3, 5), \\min(3, 1), min(5, 1)$] $=$ [$2, 2, 1, 3, 1, 1$].\n\nThen, he randomly \\textbf{shuffled} all the elements of the array $b$.\n\nUnfortunately, he forgot the array $a$, and your task is to restore any possible array $a$ from which the array $b$ could have been obtained.\n\n\\textbf{The elements of array $a$ should be in the range $[-10^9,10^9]$}.",
    "tutorial": "Suppose we have an array $a$ that we want to construct, with elements $a_1, a_2, \\dots, a_n$. To simplify the process, let's assume that the elements of $a$ are sorted in non-decreasing order, meaning $a_1 \\le a_2 \\le \\dots \\le a_n$. Let's start with $a_1$. Since the elements of $a$ are sorted, the pairs $(a_1, a_2), (a_1, a_3), \\dots, (a_1, a_n)$ will have $a_1$ as the smallest element in each pair. Therefore, the number of occurrences of $a_1$ in array $b$ will be $n-1$. Moving on to $a_2$, we already know that $a_1$ appears $n-1$ times in $b$. Since the elements of $a$ are sorted, all pairs involving $a_2$ will have $a_2$ as the second smallest element. This means $a_2$ will appear $n-2$ times in array $b$. We continue this process for each element $a_i$ in $a$. The number of occurrences of $a_i$ in array $b$ will be $n-i$. We can't determine the exact value of $a_n$ , because it won't be written to array b. Therefore, for $a_n$ we can choose any number in the range $[a_{n-1};10^9]$. In case there are multiple elements $b_i$ in array $b$ that satisfy the condition for a particular $a_i$, we choose the smallest $b_i$. This greedy approach works, because we are constructing $a$ in non-decreasing order. The complexity is $O(n^2 \\log n)$.",
    "code": "for _ in range(int(input())):\n    n=int(input())\n    l=sorted(map(int,input().split()))\n    j=0\n    for i in range(n-1,0,-1):\n        print(l[j],end=' ')\n        j+=i\n    print(l[-1])",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1857",
    "index": "D",
    "title": "Strong Vertices",
    "statement": "Given two arrays $a$ and $b$, both of length $n$. Elements of both arrays indexed from $1$ to $n$. You are constructing a directed graph, where edge from $u$ to $v$ ($u\\neq v$) exists if $a_u-a_v \\ge b_u-b_v$.\n\nA vertex $V$ is called strong if there exists a path from $V$ to all other vertices.\n\nA path in a directed graph is a chain of several vertices, connected by edges, such that moving from the vertex $u$, along the directions of the edges, the vertex $v$ can be reached.\n\nYour task is to find all strong vertices.\n\nFor example, if $a=[3,1,2,4]$ and $b=[4,3,2,1]$, the graph will look like this:\n\n\\begin{center}\n{\\small The graph has only one strong vertex with number $4$}\n\\end{center}",
    "tutorial": "The first step is to modify the inequality. $a_u-a_v \\geq b_u-b_v \\Leftrightarrow a_u-b_u \\geq a_v-b_v$. We can create a new array $c$, where $c_i=a_i-b_i$ and our inequality is transformed to $c_u\\geq c_v$. Suppose the set $p_1,\\dots p_m$ is the set of such vertices $v$ that $c_v$ is maximum possible. From each $p_i$ there will be a path to all other vertices, because $c_{p_i}$ is not less than any other $c_u$, so the set $p$ is guaranteed will be in our answer. Now the question is whether there are other vertices in our answer? Let's prove that from any such vertex $v$, that is not maximum, there is no path to any vertex from $p$. The first observation, that there is no edge between $v$ and any $p_i$. So the path must go through other vertices. But even if there exist a path to another vertex $u$, $c_u$ will be still less that $c_{p_i}$, so it is impossible to get any $p_i$. In such way we proved that the answer will always be the set of such $v$, that $c_v$ is maximized. The complexity is $O(n)$.",
    "code": "for _ in range(int(input())):\n    n=int(input())\n    a=[*map(int,input().split())]\n    b=[*map(int,input().split())]\n    c=[a[i]-b[i] for i in range(n)]\n    mx=max(c)\n    ans=[]\n    for i in range(n):\n        if c[i]==mx:ans.append(i+1)\n    print(len(ans))\n    print(*ans)",
    "tags": [
      "math",
      "sortings",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1857",
    "index": "E",
    "title": "Power of Points",
    "statement": "You are given $n$ points with integer coordinates $x_1,\\dots x_n$, which lie on a number line.\n\nFor some integer $s$, we construct segments [$s,x_1$], [$s,x_2$], $\\dots$, [$s,x_n$]. Note that if $x_i<s$, then the segment will look like [$x_i,s$]. The segment [$a, b$] covers all integer points $a, a+1, a+2, \\dots, b$.\n\nWe define the power of a point $p$ as the number of segments that intersect the point with coordinate $p$, denoted as $f_p$.\n\nYour task is to compute $\\sum\\limits_{p=1}^{10^9}f_p$ for each $s \\in \\{x_1,\\dots,x_n\\}$, i.e., the sum of $f_p$ for all integer points from $1$ to $10^9$.\n\nFor example, if the initial coordinates are $[1,2,5,7,1]$ and we choose $s=5$, then the segments will be: $[1,5]$,$[2,5]$,$[5,5]$,$[5,7]$,$[1,5]$. And the powers of the points will be: $f_1=2, f_2=3, f_3=3, f_4=3, f_5=5, f_6=1, f_7=1, f_8=0, \\dots, f_{10^9}=0$. Their sum is $2+3+3+3+5+1+1=18$.",
    "tutorial": "If we have the segments $[l_1,r_1],\\dots,[l_n,r_n]$, the sum of $f_p$ is the sum of the segments' lengths. That's because a segment $[a,b]$ intersect exactly $b-a+1$ points. Now we can find the answer for fixed $s$ in $O(N)$. How to do it more efficiently? Let's sort the given points so that $x_1\\le x_2\\le \\dots \\le x_n$. Processing $s=x_i$ we get that for all $j\\le i$ the segments are $[x_j,s]$ and for all $j>i$ the segments are $[s,x_j]$. We need to summarize their lengths. Formally we need to calculate $\\sum\\limits_{j=1}^{i}(s-x_j+1)+\\sum\\limits_{j=i+1}^{n}(x_j-s+1)=$ $n+s \\cdot i-\\sum\\limits_{j=1}^{i}x_j+\\sum\\limits_{j=i+1}^{n}x_j -s(n-i)=$ $n+s(2\\cdot i-n)-\\sum\\limits_{j=1}^{i}x_j+\\sum\\limits_{j=i+1}^{n}x_j$ We can maintain the sum of coordinates on the prefix and suffix, and calculate this formula for fixed $s$ in $O(1)$. The total complexity is $O(n\\log n)$.",
    "code": "for i in range(int(input())):\n    n=int(input())\n    a=sorted([(b,i)for i,b in enumerate(map(int,input().split()))])\n    ans=[0]*n\n    s1=0\n    s2=sum(a[i][0] for i in range(n))\n    for i in range(n):\n        ans[a[i][1]]=s2-a[i][0]*(n-i)+n-i+a[i][0]*i-s1+i\n        s1+=a[i][0]\n        s2-=a[i][0]\n    print(*ans)",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1857",
    "index": "F",
    "title": "Sum and Product",
    "statement": "You have an array $a$ of length $n$.\n\nYour task is to answer $q$ queries: given $x,y$, find the number of pairs $i$ and $j$ ($1 \\le i < j \\le n$) that both $a_i + a_j = x$ and $a_i \\cdot a_j = y$.\n\nThat is, for the array $[1,3,2]$ and asking for $x=3,y=2$ the answer is $1$:\n\n- $i=1$ and $j=2$ fail because $1 + 3 = 4$ and not $3,$ also $1 \\cdot 3=3$ and not $2$;\n- $i=1$ and $j=3$ satisfies both conditions;\n- $i=2$ and $j=3$ fail because $3 + 2 = 5$ and not $3,$ also $3 \\cdot 2=6$ and not $2$;",
    "tutorial": "The system of equations in the statement resembles Vieta's formula for quadratic equations. If we have $\\begin{cases} a_i + a_j = b \\\\ a_i \\cdot a_j = c \\end{cases}$ To find the roots of the quadratic equation, we can use the discriminant formula, $D = b^2 - 4ac$. The roots will then be $x_1 = \\frac{b - \\sqrt{D}}{2}$ and $x_2 = \\frac{b + \\sqrt{D}}{2}$. Once we have the potential integer values for $a_i$ and $a_j$, we can calculate the number of pairs by multiplying the number of occurrences, respectively. However, remember to consider some special cases: If $D < 0$, the equation won't have real roots. If $D = 0$, then $x_1 = x_2$, the formula for counting pairs in this case is different. The complexity of this solution is $O((n + q) \\log n)$, using maps to store integer occurrences.",
    "code": "from collections import Counter\nfrom math import sqrt\n \nfor _ in range(int(input())):\n    n=int(input())\n    a=[*map(int,input().split())]\n    d=Counter(map(str,a))\n    for i in range(int(input())):\n        x,y=map(int,input().split())\n        if x*x-4*y<0:print(0);continue\n        D=int(sqrt(x*x-4*y))\n        x1=(x+D)//2\n        x2=(x-D)//2\n        if x1+x2!=x or x1*x2!=y:print(0);continue\n        if x1!=x2:print(d[str(x1)]*d[str(x2)])\n        else:print(d[str(x1)]*(d[str(x1)]-1)//2)",
    "tags": [
      "binary search",
      "data structures",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1857",
    "index": "G",
    "title": "Counting Graphs",
    "statement": "Given a tree consisting of $n$ vertices. A tree is a connected undirected graph without cycles. Each edge of the tree has its weight, $w_i$.\n\nYour task is to count the number of different graphs that satisfy all four conditions:\n\n- The graph does not have self-loops and multiple edges.\n- The weights on the edges of the graph are integers and do not exceed $S$.\n- The graph has \\textbf{exactly one} minimum spanning tree.\n- The minimum spanning tree of the graph is the given tree.\n\nTwo graphs are considered different if their sets of edges are different, taking into account the weights of the edges.\n\nThe answer can be large, output it modulo $998244353$.",
    "tutorial": "The first observation is that the graphs will consist of $n$ vertices because the MST is fixed. Hence, the graphs will look like the given tree with some new vertices connected. The next step is to determine the possible weights of a new edge between vertices $u$ and $v$. Let $P(u,v)$ be the maximum weight on the simple path from $u$ to $v$. I assume that we can add a new edge between vertices $u$ and $v$ with any weight in the range $[P(u,v)+1,S]$. This becomes clear when we consider some examples. If the edge has a weight less or equal than $P(u,v)$, the MST will change by taking the new edge instead of the edge with the maximal weight on the path. Notice that if we add a new edge, and it doesn't affect the MST, we can add one more edge independently from the previous. So now the task is to calculate $\\prod\\limits_{1\\le u < v \\le n}{} (S-P(u,v)+1)$, because for each pair of vertices, we can assign a new weight from the range, which gives us $S-P(u,v)$ cases, or we can choose not to add any edge, which is one more case. Now, let's discuss how to calculate the formula efficiently: Sort the given edges in ascending order according to their weights: $w_1\\le w_2\\le \\dots \\le w_{n-1}$. We'll begin from the graph without edges, and add new ones step by step. Suppose, we already added all the edges up to $u_i,v_i,w_i$. Now, we want to add the $i$-th one. Notice that $w_i$ is greater than any of the weights before, and $u_i$ and $v_i$ are from different components. After adding the edge, we need to calculate the number of paths that go through this edge. If we know the sizes of the components containing $u_i$ and $v_i$, denoted as $s_u$ and $s_v$ respectively, then there exist $s_u\\cdot s_v-1$ paths through edge $u_i,v_i$ without including the path formed by these two vertices. We know the number of paths, and on each of these paths, we can determine the weight we can put on the edge. Thus, we need to multiply answer by $(S-w_i+1)^{s_u\\cdot s_v-1}$, using binary exponentiation. To add edges and find the sizes of the components efficiently, you can use DSU (Disjoint Set Union). The complexity of this approach is $O(n\\log n)$.",
    "code": "mod=998244353\ndef find_(v):\n    stack=[v]\n    while dsu[v]!=v:\n        stack.append(dsu[v])\n        v=stack[-1]\n    while stack:\n        dsu[stack[-1]]=dsu[v]\n        v=stack.pop()\n    return dsu[v]\n \nfor i in range(int(input())):\n    n,S=map(int,input().split())\n    l=[tuple(map(int,input().split()))for i in range(n-1)]\n    l.sort(key=lambda x:x[2])\n    ans=1\n    dsu=[i for i in range(n)]\n    coun=[1]*n\n    for a,b,c in l:\n        a-=1;b-=1\n        if find_(a)!=find_(b):\n            ans=ans*pow(S-c+1,coun[dsu[a]]*coun[dsu[b]]-1,mod)\n            ans%=mod\n            coun[dsu[a]]+=coun[dsu[b]]\n            coun[dsu[b]]=0\n            dsu[b]=dsu[a]\n    print(ans)",
    "tags": [
      "combinatorics",
      "divide and conquer",
      "dsu",
      "graphs",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1858",
    "index": "A",
    "title": "Buttons",
    "statement": "Anna and Katie ended up in a secret laboratory.\n\nThere are $a+b+c$ buttons in the laboratory. It turned out that $a$ buttons can only be pressed by Anna, $b$ buttons can only be pressed by Katie, and $c$ buttons can be pressed by either of them. Anna and Katie decided to play a game, taking turns pressing these buttons. Anna makes the first turn. Each button can be pressed at most once, so at some point, one of the girls will not be able to make her turn.\n\nThe girl who cannot press a button loses. Determine who will win if both girls play optimally.",
    "tutorial": "On each turn, the current player gets rid of one of the buttons available to them. At the same time, if you press the \"common\" button, the enemy will not be able to press it as well. Since each player wants to leave their opponent without buttons to press before they run out of those themselves, they will click on the \"common\" buttons as long as there is at least one available. The number of the player who clicks on their (not the general) button first depends on $c$. It can be noticed that this player will win if and only if they have strictly more buttons than their opponent.",
    "code": "t = int(input())\nfor i in range(t):\n    a, b, c = map(int, input().split())\n    if c % 2 == 0:\n        if a > b:\n            print(\"First\")\n        else:\n            print(\"Second\")\n    else:\n        if b > a:\n            print(\"Second\")\n        else:\n            print(\"First\")",
    "tags": [
      "games",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1858",
    "index": "B",
    "title": "The Walkway",
    "statement": "There are $n$ benches near the Main Walkway in Summer Infomatics School. These benches are numbered by integers from $1$ to $n$ in order they follow. Also there are $m$ cookie sellers near the Walkway. The $i$-th ($1 \\le i \\le m$) cookie sellers is located near the $s_i$-th bench.\n\nPetya is standing in the beginning of the Walkway. He will pass near all benches starting from the $1$-st bench and ending with the $n$-th bench. Petya passes the distance between two consecutive benches in $1$ minute. He has a knapsack with an infinite amount of cookies. Petya is going to eat cookies from his knapsack and buy them from cookie sellers during the walk.\n\nPetya eats cookies only near the benches according to the following rule: he will eat the cookie near the $i$-th ($1 \\le i \\le n$) bench if and only if \\textbf{at least one} of the following conditions holds:\n\n- There is a cookie seller near the $i$-th bench. Then Petya will buy a cookie from cookie seller and eat it immediately.\n- Petya has not yet eaten a cookie. Then Petya will take a cookie from his knapsack and eat it immediately.\n- At least $d$ minutes passed since Petya ate the previous cookie. In other words, Petya has not eaten a cookie near the benches $i-1, i-2, \\ldots, \\max(i-d+1, 1)$. Then Petya will take a cookie from his knapsack and eat it immediately.\n\nYou may assume that Petya eats cookies instantly. Petya will not eat two or more cookies near the same bench.\n\nYou want to \\textbf{minimize} the number of cookies Petya will eat during his walk. In order to do this, you will ask the administration of the Summer Informatics School to remove \\textbf{exactly one} cookie seller from the Walkway before Petya starts his walk.\n\nPlease determine the minimum possible number of cookies Petya can eat after removing exactly one cookie seller. Also determine the number of cookie sellers, such that if you remove one of them, Petya will eat the minimum possible number of cookies.",
    "tutorial": "First, let's calculate how many cookies Petya will eat if we don't remove the cookie sellers at all (we will later refer to this value as $res$). Note that since the cookie sellers reset the time elapsed since the last eaten cookie, the number of cookies eaten on all segments between adjacent cookie sellers are counted independently. Therefore, we can easily calculate $res$: let's iterate through the cookie sellers from $1$ to $m-1$. For each of them, we should add the number $\\left( \\left\\lfloor\\frac{s_{i+1}-s_{i}-1}{d}\\right\\rfloor + 1 \\right)$ to $res$. We should also carefully take into account the cookies that Petya will eat on the segments $[1;s_{1}-1]$ and $[s_{m}, n]$ (it might help to assume that there are two more cookie sellers at positions $1-d$ and $n+1$). In order to find the minimum possible number of cookies eaten by Petya, we will fix the cookie seller that we remove. Let it be the cookie seller $i$. Then the number of cookies eaten by Petya will be $res - \\left\\lfloor\\frac{s_{i}-s_{i-1}-1}{d}\\right\\rfloor - \\left\\lfloor\\frac{s_{i+1}-s_{i}-1}{d}\\right\\rfloor + \\left\\lfloor\\frac{s_{i+1}-s_{i-1}-1}{d}\\right\\rfloor - 1$ The final complexity of the solution is $\\mathcal{O}(m)$ (because array $s$ is sorted in the input).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint solve(int d, vector<int> x)\n{\n    int ans = 0;\n    for (int i = 1; i < x.size(); i++)\n    {\n        ans += (x[i] - x[i - 1] - 1) / d;\n    }\n    ans += int(x.size()) - 2;\n    return ans;\n}\n\nvoid solve()\n{\n    #define tests\n\n    int n, m, d;\n    cin >> n >> m >> d;\n    vector<int> r(m);\n    for (int i = 0; i < m; i++) cin >> r[i];\n    r.insert(r.begin(), 1 - d);\n    r.push_back(n + 1);\n\n    int ans = 2e9;\n    vector<int> res;\n    for (int i = 1; i <= m; i++)\n    {\n        int A = r[i] - r[i - 1] - 1;\n        int B = r[i + 1] - r[i] - 1;\n        int C = r[i + 1] - r[i - 1] - 1;\n        int D = C / d - (A / d + B / d);\n        if (D < ans)\n        {\n            ans = D;\n            res.clear();\n        }\n        if (D == ans)\n        {\n            res.push_back(r[i]);\n        }\n    }\n    cout << ans + solve(d, r) - 1 << ' ' << res.size() << endl;\n}\n\nint main()\n{\n    int t = 1;\n    #ifdef tests\n    cin >> t;\n    #endif\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1858",
    "index": "C",
    "title": "Yet Another Permutation Problem",
    "statement": "Alex got a new game called \"GCD permutations\" as a birthday present. Each round of this game proceeds as follows:\n\n- First, Alex chooses a permutation$^{\\dagger}$ $a_1, a_2, \\ldots, a_n$ of integers from $1$ to $n$.\n- Then, for each $i$ from $1$ to $n$, an integer $d_i = \\gcd(a_i, a_{(i \\bmod n) + 1})$ is calculated.\n- The score of the round is the number of distinct numbers among $d_1, d_2, \\ldots, d_n$.\n\nAlex has already played several rounds so he decided to find a permutation $a_1, a_2, \\ldots, a_n$ such that its score is as large as possible.\n\nRecall that $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of numbers $x$ and $y$, and $x \\bmod y$ denotes the remainder of dividing $x$ by $y$.\n\n$^{\\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "It is impossible to get $d_i = \\gcd(a_i, a_{(i\\mod n) + 1}) > \\left\\lfloor \\frac{n}{2}\\right\\rfloor$: otherwise, at least one of the numbers in $a$ would be divisible by $d_i$ and would be greater than $d_i$ at the same time, so it would be at least $2 \\cdot d_i$, which is greater than $n$. Therefore, the maximum possible score is no more than $\\left\\lfloor\\frac{n}{2}\\right\\rfloor$. Actually, we can always get a score equal to $\\left\\lfloor\\frac{n}{2}\\right\\rfloor$. How do we get such score? Let's set $a_1= 1$. After that, we put the powers of $2$ less or equal $n$ sequentially. Then we put $3$ and powers of $2$ multiplied by $3$, then $5$ and so on (for example, for $n=12$, we will get an array $a=[1,2,4,8,3,6,12,5,10,7,9,11]$). Then, for each number $a_i = x \\leq \\lfloor \\frac{n}{2} \\rfloor$, the next number will be $a_{(i\\bmod n) + 1} = x \\cdot 2 \\leq n$. Their $\\gcd$ will be exactly $x$, so there will be a pair of adjacent elements of $a$ with greatest common divisor equal to $x$ for all $1 \\leq x \\leq \\lfloor\\frac{n}{2}\\rfloor$.",
    "code": "#include<iostream>\n#include<vector>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        int cur = 0;\n        for (int i = 1; i <= n; i += 2) {\n            for (int j = i; j <= n; j *= 2) {\n                a[cur++] = j;\n            }\n        }\n        for (int i = 0; i<n; ++i) {\n            cout << a[i] << \" \";\n        }\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1858",
    "index": "D",
    "title": "Trees and Segments",
    "statement": "The teachers of the Summer Informatics School decided to plant $n$ trees in a row, and it was decided to plant only oaks and firs. To do this, they made a plan, which can be represented as a binary string $s$ of length $n$. If $s_i = 0$, then the $i$-th tree in the row should be an oak, and if $s_i = 1$, then the $i$-th tree in the row should be a fir.\n\nThe day of tree planting is tomorrow, and the day after tomorrow an inspector will come to the School. The inspector loves nature very much, and he will evaluate the beauty of the row as follows:\n\n- First, he will calculate $l_0$ as the maximum number of consecutive oaks in the row (the maximum substring consisting of zeros in the plan $s$). If there are no oaks in the row, then $l_0 = 0$.\n- Then, he will calculate $l_1$ as the maximum number of consecutive firs in the row (the maximum substring consisting of ones in the plan $s$). If there are no firs in the row, then $l_1 = 0$.\n- Finally, he will calculate the beauty of the row as $a \\cdot l_0 + l_1$ for some $a$ — the inspector's favourite number.\n\nThe teachers know the value of the parameter $a$, but for security reasons they cannot tell it to you. They only told you that $a$ is an integer from $1$ to $n$.\n\nSince the trees have not yet been planted, the teachers decided to change the type of no more than $k$ trees to the opposite (i.e., change $s_i$ from $0$ to $1$ or from $1$ to $0$ in the plan) in order to maximize the beauty of the row of trees according to the inspector.\n\nFor each integer $j$ from $1$ to $n$ answer the following question \\textbf{independently}:\n\n- What is the maximum beauty of the row of trees that the teachers can achieve by changing the type of no more than $k$ trees if the inspector's favourite number $a$ is equal to $j$?",
    "tutorial": "There are many various dynamic programming solutions of this problem. We will describe one of them. Let's calculate the dynamics $pref_{i, \\ j}$ = the length of the longest subsegment of zeros that can be obtained on the prefix up to $i$, which ends at index $i$ and costs exactly $j$ operations. Similarly, $suf_{i, \\ j}$ is the length of the longest subsegment of zeros on the suffix starting at $i$, which starts at index $i$ and costs exactly $j$ operations. Such dynamics can be easily computed: $pref_{i, \\ j} = \\left\\{ \\begin{array} \\\\ pref_{i - 1, \\ j} + 1 & \\text{if} & s_i = 0 \\\\ pref_{i - 1, \\ j - 1} + 1 & \\text{if} & s_i = 1 & \\text{and} & j > 0 \\\\ 0 & \\text{otherwise} \\end{array}\\right.$ Now let's consider a subsegment [$l, \\ r]$ that we want to convert into a segment of ones. We can easily calculate the number of operations $x$ that we will need (we'll just need to calculate the number of zeros in such a segment). Now, calculate the new dynamics $dp_{len}$ for the length $len = r - l + 1$ of the segment of ones, which equals the maximum length of a subsegment of zeros that we can obtain. Update this value with $\\max(pref_{l - 1, k - x}, suf_{r + 1, k - x})$. Then, to answer the question for a fixed number $a$, we can iterate over the length $len$ of the segment of ones that will be in our answer and update the answer with the value $a \\cdot dp_{len} + len$, if there exists a value for $len$ in the dynamics $dp$. The complexity is $O(nk + n^2)$. Solutions with complexity $O(nk \\log n)$ and $O(nk)$ using various optimizations of the dynamics (convex hull trick, D&C) also exist.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve();\n\ntemplate<typename ...Args>\nvoid println(Args... args) {\n    apply([](auto &&... args) { ((cout << args << ' '), ...); }, tuple(args...));\n    cout << '\\n';\n}\n\nint32_t main() {\n    cin.tie(nullptr);\n    ios_base::sync_with_stdio(false);\n    int t = 1;\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        solve();\n    }\n    return 0;\n}\n\nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    string s;\n    cin >> s;\n    vector<int> max0by1(n + 1, -1e9);\n    vector<vector<int>> max0pref(n + 1, vector<int>(n + 1));\n    vector<vector<int>> max0suf(n + 1, vector<int>(n + 1));\n    for (int l = 0; l < n; ++l) {\n        int cnt1 = 0;\n        for (int r = l + 1; r <= n; ++r) {\n            cnt1 += s[r - 1] == '1';\n            max0pref[r][cnt1] = max(max0pref[r][cnt1], r - l);\n            max0suf[l][cnt1] = max(max0suf[l][cnt1], r - l);\n        }\n    }\n    for (int r = 0; r <= n; ++r) {\n        for (int cnt = 0; cnt <= n; ++cnt) {\n            if (r) max0pref[r][cnt] = max(max0pref[r][cnt], max0pref[r - 1][cnt]);\n            if (cnt) max0pref[r][cnt] = max(max0pref[r][cnt], max0pref[r][cnt - 1]);\n        }\n    }\n    for (int l = n; l >= 0; --l) {\n        for (int cnt = 0; cnt <= n; ++cnt) {\n            if (l + 1 <= n) max0suf[l][cnt] = max(max0suf[l][cnt], max0suf[l + 1][cnt]);\n            if (cnt) max0suf[l][cnt] = max(max0suf[l][cnt], max0suf[l][cnt - 1]);\n        }\n    }\n    vector<int> ans(n + 1, -1e9);\n    for (int l = 0; l < n; ++l) {\n        int cnt0 = 0;\n        for (int r = l; r <= n; ++r) {\n            if (r > l) cnt0 += s[r - 1] == '0';\n            if (cnt0 > k) break;\n            max0by1[r - l] = max(max0by1[r - l], max0pref[l][k - cnt0]);\n            max0by1[r - l] = max(max0by1[r - l], max0suf[r][k - cnt0]);\n        }\n    }\n    for (int i = 0; i <= n; ++i) {\n        for (int a = 1; a <= n; ++a) ans[a] = max(ans[a], i + max0by1[i] * a);\n    }\n    for (int i = 1; i <= n; ++i) cout << ans[i] << ' ';\n    cout << '\\n';\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1858",
    "index": "E2",
    "title": "Rollbacks (Hard Version)",
    "statement": "This is a hard version of this problem. The only difference between the versions is that you have to solve the hard version in online mode. You can make hacks only if both versions of the problem are solved.\n\nYou have an array $a$, which is initially empty. You need to process queries of the following types:\n\n- + $x$ — add the integer $x$ to the end of the array $a$.\n- - $k$ — remove the last $k$ numbers from the array $a$.\n- ! — roll back the last active change (i.e., make the array $a$ the way it was before the change). In this problem, only queries of the first two types (+ and -) are considered as changes.\n- ? — find the number of distinct numbers in the array $a$.",
    "tutorial": "First, let's learn how to solve the problem without rollbacks. Let $b$ be an array of the same length as $a$, where $b_i=1$ if $i$ is the minimum position at which the number $a_i$ is in the array $a$, and $b_i=0$ otherwise. Then the number of different numbers in the array $a$ is equal to the sum of all the elements of the array $b$. The $b$ array can be maintained using a Fenwick tree, a segment tree, or any other data structure that supports point updates and range sum queries. The author's solution uses the Fenwick tree. Let's use the method that is often used when implementing a stack or a deque: we create a large array $A$ and at each moment we store the index of the last \"existing\" element $r$ (this is just the size of the array $a$ at this moment). The array $a$ itself will be a prefix of $A$, that is, $a_{i}=A_{i}$ for $i\\leq len(a)$. Also, for each value $val$ we maintain std::set of indexes on which the $val$ value is located in the $A$ array (in $A$, not in $a$). Then for the operation of removing $k$ elements from the end of the array $a$, it is enough to reduce the value of the index $r$ by $k$. This operation works in $O(1)$. When adding one element $x$ to the end of the array, we need to check if it has been encountered before, and change one element in the Fenwick tree accordingly. This can be done in $O(\\log{q})$ using std::set for the corresponding value. You also need to increase $r$ by 1, assign $A_{r} =x$ after that, and update the corresponding std::set. This operation works for $O(\\log{q})$. In order to find the number of different numbers in $a$, we need to find the sum in the Fenwick tree on the prefix of length $r$ in the array $b$. This operation works in $O(\\log{q})$. Now, we need to learn how to roll back operations. Note that we perform the deletion operation in $O(1)$, and the addition operation in $O(\\log{q})$, so we can roll back these operations with the same asymptotics. We can just store a stack of all changes, and remember everything that we changed during the operations. The final asymptotics is $O(q\\log{q})$. Note: At about 20 minutes into the round one of our testers (SomethingNew) came up with a linear solution for problem E2, and jiangly implemented the same solution shortly after the contest! For further details, see 219001999. The main idea (as jiangly pointed out in the comments) is that we can use prefix sums instead of the Fenwick tree.",
    "code": "#include <bits/stdc++.h>\n \nusing i64 = long long;\n \nconstexpr int N = 1 << 20;\n \nint main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n    \n    int q;\n    std::cin >> q;\n    \n    std::vector<int> pos(N, q);\n    int n = 0;\n    \n    std::vector<std::array<int, 5>> a;\n    std::vector<int> b(q), c(q + 1);\n    c[q] = n;\n    std::vector<int> s(q + 1);\n    \n    for (int i = 0; i < q; i++) {\n        char o;\n        std::cin >> o;\n        if (o == '+') {\n            int x;\n            std::cin >> x;\n            a.push_back({x, pos[x], b[n], pos[b[n]], s[n + 1]});\n            if (pos[b[n]] == n) {\n                c[pos[b[n]]] -= 1;\n                pos[b[n]] = q;\n                c[pos[b[n]]] += 1;\n            }\n            if (pos[x] > n) {\n                c[pos[x]] -= 1;\n                pos[x] = n;\n                c[pos[x]] += 1;\n            }\n            s[n + 1] = s[n] + c[n];\n            b[n] = x;\n            n += 1;\n        } else if (o == '-') {\n            int k;\n            std::cin >> k;\n            n -= k;\n            a.push_back({-1, k});\n        } else if (o == '?') {\n            int ans = s[n];\n            std::cout << ans << std::endl;\n        } else {\n            auto [x, y, z, w, t] = a.back();\n            a.pop_back();\n            \n            if (x == -1) {\n                n += y;\n            } else {\n                n -= 1;\n                b[n] = z;\n                s[n + 1] = t;\n                if (pos[x] != y) {\n                    c[pos[x]] -= 1;\n                    pos[x] = y;\n                    c[pos[x]] += 1;\n                }\n                if (pos[z] != w) {\n                    c[pos[z]] -= 1;\n                    pos[z] = w;\n                    c[pos[z]] += 1;\n                }\n            }\n        }\n    }\n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "interactive",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1859",
    "index": "A",
    "title": "United We Stand",
    "statement": "Given an array $a$ of length $n$, containing integers. And there are two initially empty arrays $b$ and $c$. You need to add each element of array $a$ to \\textbf{exactly one} of the arrays $b$ or $c$, in order to satisfy the following conditions:\n\n- Both arrays $b$ and $c$ are non-empty. More formally, let $l_b$ be the length of array $b$, and $l_c$ be the length of array $c$. Then $l_b, l_c \\ge 1$.\n- For any two indices $i$ and $j$ ($1 \\le i \\le l_b, 1 \\le j \\le l_c$), $c_j$ \\textbf{is not} a divisor of $b_i$.\n\nOutput the arrays $b$ and $c$ that can be obtained, or output $-1$ if they do not exist.",
    "tutorial": "What does it mean that $A$ divides $B$? First, if all numbers are equal, then there is no answer (since $a$ is divisible by $a$, if both arrays are non-empty, then $c_1$ is a divisor of $b_1$). Second, if $a$ is divisible by $b$ and they are both natural numbers, then the following equality holds: $b \\le a$ (by definition, if $a$ is divisible by $b$, then $a$ can be represented as $k \\dot b$, where $k$ is a natural number). Now we can place all instances of the smallest number into $b$, and all other numbers into $c$. It can be seen that such a construction always gives a valid answer.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\n \nvoid solve() {\n\tint n = 0; cin >> n; \n\tvector<int> inp; inp.assign(n, 0);\n\tfor (auto& x : inp) cin >> x;\n\tsort(inp.begin(), inp.end());\n\tif (inp.back() == inp[0]) {\n\t\tcout << \"-1\\n\";\n\t\treturn;\n\t}\n\telse {\n\t\tint it = 0;\n\t\twhile (inp[it] == inp[0]) it++;\n\t\tcout << it << \" \" << n - it << \"\\n\";\n\t\tfor (int j = 0; j < it; ++j) cout << inp[j] << \" \";\n\t\tfor (int j = it; j < n; ++j) cout << inp[j] << \" \";\n\t}\n}\n \nint main() {\n\tint t = 0; cin >> t;\n\twhile (t--) solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1859",
    "index": "B",
    "title": "Olya and Game with Arrays",
    "statement": "Artem suggested a game to the girl Olya. There is a list of $n$ arrays, where the $i$-th array contains $m_i \\ge 2$ positive integers $a_{i,1}, a_{i,2}, \\ldots, a_{i,m_i}$.\n\nOlya can move \\textbf{at most one} (possibly $0$) integer from \\textbf{each} array to another array. Note that integers can be moved from one array only once, but integers can be added to one array \\textbf{multiple times}, and all the movements are done \\textbf{at the same time}.\n\nThe beauty of the list of arrays is defined as the sum $\\sum_{i=1}^n \\min_{j=1}^{m_i} a_{i,j}$. In other words, for each array, we find the minimum value in it and then sum up these values.\n\nThe goal of the game is to maximize the beauty of the list of arrays. Help Olya win this challenging game!",
    "tutorial": "Do all numbers in a single array really matter? If only the first minimum and the second minimum matter, what is the only way to increase a single array's beauty? What can we say about the array which will have the smallest number in the end? To increase the answer for each array separately, it is necessary to move the minimum to another array. Then, notice that it is optimal to move all the minimums to one array. Let's figure out which array. After moving the minimum from an array, the second minimum in the original array becomes the new minimum. Then, it is easy to notice that it is optimal to move all the minimums to the array with the smallest second minimum. After all the movements, we will have one array where the minimum element is the smallest number among all the arrays, and $n-1$ arrays where the minimum element is the second minimum in the original array. Therefore, the answer to the problem will be $M + K - S$, where $M$ is the minimum element among all the arrays, $K$ is the sum of all the second minimums, and $S$ is the smallest second minimum.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n \nusing namespace std;\n \n#define all(v) v.begin(), v.end()\n \ntypedef long long ll;\n \nconst int INF = 1e9 + 7;\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    int minn = INF;\n    vector<int> min2;\n    for (int i = 0 ; i < n ; i++) {\n        int m;\n        cin >> m;\n        vector<int> v(m);\n        for (auto &el : v) cin >> el;\n \n        int minel = *min_element(all(v));\n        minn = min(minn, minel);\n        v.erase(find(all(v), minel));\n        min2.push_back(*min_element(all(v)));\n    }\n    cout << minn + (ll) accumulate(all(min2), 0ll) - *min_element(all(min2)) << \"\\n\";\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n \n#ifdef LOCAL\n    freopen(\"a.in\", \"r\", stdin);\n#endif\n \n    int t = 1;\n    cin >> t;\n    while (t--)\n        solve();\n \n    return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1859",
    "index": "C",
    "title": "Another Permutation Problem",
    "statement": "Andrey is just starting to come up with problems, and it's difficult for him. That's why he came up with a strange problem about permutations$^{\\dagger}$ and asks you to solve it. Can you do it?\n\nLet's call the cost of a permutation $p$ of length $n$ the value of the expression:\n\n\\begin{center}\n$(\\sum_{i = 1}^{n} p_i \\cdot i) - (\\max_{j = 1}^{n} p_j \\cdot j)$.\n\\end{center}\n\nFind the maximum cost among all permutations of length $n$.\n\n$^{\\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "What if we fix the maximum element in the resulting array? Try using greedy. Optimize the log factor away by noticing a certain fact. Let's fix the maximum element in an array - let it be $M$. Now, let's iterate from $n$ to $1$. Let the current chosen number be $i$. I claim that if we maintain the remaining available numbers to multiply by, then it is optimal to take the maximum such number $x$ that $x * i \\le M$. Proof: let's say that this is not correct. Then, let's say that we pair $i$ with another number $x1$, and $x$ gets paired with some other number $i1$. Then, $i1 < i$, because it was chosen later, and $x1 < x$ (otherwise $i * x1 > M$). Now let's swap $x$ with $x1$. The sum is increased by $i * x - i * x1 - i1 * x + i1 * x1 = (i - i1)(x - x1) > 0$, and all of the numbers are less or equal to $M$. Now the task can be solved in $O(N^3logN)$ by simply iterating on the maximum from $N^2$ to $1$, while maintaining the remaining numbers with a set. In order to squeeze it in the TL, you can only consider such maximums that they can be represented as $i * j, 1 \\le i, j \\le n$. In order to optimize it to $O(N^3)$, let's notice that for each number $x$, it can be paired with any number from $1$ to $\\frac{M} {x}$. Now just maintain a stack of all available elements at the current moment, add all numbers that possible, and pop the maximum number for all $i$ from $1$ to $N$.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <set>\n#include <stack>\n#include <vector>\nusing namespace std;\nvoid solve() {\n\tint N = 0; cin >> N;\n\tint ans = 0;\n\tvector<int> pr;\n\tpr.assign(N * N, -1);\n\tfor (int i = 1; i <= N; ++i) {\n\t\tfor (int j = 1; j <= N; ++j) {\n\t\t\tpr[i * j - 1] = 1;\n\t\t}\n\t}\n\tfor (int mx = N * N; mx >= 1; --mx) {\n\t\tif (pr[mx - 1] == -1) continue;\n\t\tvector<vector<int>> a;\n\t\tint curans = -mx;\n\t\tbool br = false;\n\t\ta.assign(N, vector<int>());\n\t\tfor (int j = N; j >= 1; --j) {\n\t\t\tint num = min(mx / j, N);\n\t\t\tif (num < 1) {\n\t\t\t\tbr = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ta[num - 1].push_back(j);\n\t\t}\n\t\tif (br) break;\n\t\tstack<int> s;\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\ts.push(i + 1);\n\t\t\tbool brk = false;\n\t\t\tfor (auto x : a[i]) {\n\t\t\t\tif (s.empty()) {\n\t\t\t\t\tbrk = true; break;\n\t\t\t\t}\n\t\t\t\tcurans += s.top() * x;\n\t\t\t\ts.pop();\n\t\t\t}\n\t\t\tif (brk) break;\n\t\t}\n\t\tans = max(ans, curans);\n\t}\n\tcout << ans << \"\\n\";\n}\n \nint main() {\n\tios_base::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint t = 0; cin >> t;\n\twhile (t--) solve();\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1859",
    "index": "D",
    "title": "Andrey and Escape from Capygrad",
    "statement": "An incident occurred in Capygrad, the capital of Tyagoland, where all the capybaras in the city went crazy and started throwing mandarins. Andrey was forced to escape from the city as far as possible, using portals.\n\nTyagoland is represented by a number line, and the city of Capygrad is located at point $0$. There are $n$ portals all over Tyagoland, each of which is characterised by four integers $l_i$, $r_i$, $a_i$ and $b_i$ ($1 \\le l_i \\le a_i \\le b_i \\le r_i \\le 10^9$). Note that the segment $[a_i, b_i]$ \\textbf{is contained} in the segment $[l_i, r_i]$.\n\nIf Andrey is on the segment $[l_i, r_i]$, then the portal can teleport him to any point on the segment $[a_i, b_i]$. Andrey has a pass that allows him to use the portals an unlimited number of times.\n\nAndrey thinks that the point $x$ is on the segment $[l, r]$ if the inequality $l \\le x \\le r$ is satisfied.\n\nAndrey has $q$ options for where to start his escape, each option is characterized by a single integer $x_i$ — the starting position of the escape. He wants to escape from Capygrad as far as possible (to the point with the maximum possible coordinate). Help Andrey determine how far he could escape from Capygrad, starting at each of the $q$ positions.",
    "tutorial": "What if we use greedy a bit? Where it is always beneficial to teleport? Use scanline Statement: It is always beneficial to teleport to point $b_i$. Proof: Let's assume that we were able to teleport from point $X$ to the right of $b_i$, but not from $b_i$. Then we used some segment $A$ that covers point $X$, but does not cover point $b$, and ends to the right of $b$. This is a contradiction. Let $ans_i$ be the maximum coordinate we can reach while being on segment $i$, and let $p_j$ be the answer to the $j$-th query. Then we notice that the answer to query $p_j = \\max(x_j, \\max_{i = 1}^n {ans_i \\vert l_i \\le x_j \\le r_i})$. We will use the scanline method from the end. Events: $l_i$, $b_i$, $r_i$, $x_j$. We notice that events of type $r_i$ are not important to us when scanning from the end (according to statement number 1). It is important for us that we process events of type $b_i$ first, then events of type $x_j$, and then events of type $l_i$ (closing the segment in the scanline). We will go through the events of the scanline, processing them in the order of $b_i$, then events of type $x_j$, and then events of type $l_i$. We assume that there is a data structure that allows us to add elements, remove elements, and quickly output the maximum. For each event of type $b_i$, update the value of $ans_i$ - take the maximum value of $ans$ of all open segments from the structure. For each event of type $b_i$, update the value of $ans_i$ - take the maximum value of $ans$ of all open segments from the structure. For each event of type $x_j$, update the value of $p_j$ - take the maximum value of $ans$ of all open segments from the structure, as well as $x_j$. For each event of type $x_j$, update the value of $p_j$ - take the maximum value of $ans$ of all open segments from the structure, as well as $x_j$. For each event of type $l_i$, remove $ans_i$ from the structure. For each event of type $l_i$, remove $ans_i$ from the structure. We notice that to solve this problem, we can use the std::multiset} container, which automatically sorts elements in ascending order. We can store in $multiset$ $ans_i$ of all open segments. And then, when processing events, extract the maximum from $multiset$, all operations are performed in $O(\\log n)$. This allows us to solve the problem in $O((n + q) \\log n)$ time and $O(n)$ memory.",
    "code": "#include <iostream>\n#include <vector>\n#include <set>\n#include <iomanip>\n#include <cmath>\n#include <algorithm>\n#include <map>\n#include <stack>\n#include <cassert>\n#include <unordered_map>\n#include <bitset>\n#include <random>\n#include <unordered_set>\n#include <chrono>\n \nusing namespace std;\n \n#define all(a) a.begin(), a.end()\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    vector<int> ans(n);\n    vector<tuple<int, int, int>> events;\n    for (int i = 0 ; i < n ; i++) {\n        int l, r, a, b;\n        cin >> l >> r >> a >> b;\n        ans[i] = b;\n        events.emplace_back(b, 1, i);\n        events.emplace_back(l, -1, i);\n    }\n    int q;\n    cin >> q;\n    vector<int> queries(q);\n    for (int i = 0 ; i < q ; i++) {\n        int x;\n        cin >> x;\n        queries[i] = x;\n        events.emplace_back(x, 0, i);\n    }\n \n    sort(all(events));\n    reverse(all(events));\n    multiset<int> s;\n    for (auto [x, type, ind] : events) {\n        if (type == 1) {\n            if (!s.empty()) {\n                ans[ind] = *s.rbegin();\n            }\n            s.insert(ans[ind]);\n        } else if (type == 0) {\n            if (!s.empty()) {\n                queries[ind] = max(queries[ind], *s.rbegin());\n            }\n        } else {\n            s.extract(ans[ind]);\n        }\n    }\n \n    for (auto el : queries)\n        cout << el << \" \";\n    cout << \"\\n\";\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int t = 1;\n    cin >> t;\n    while (t--)\n        solve();\n \n    return 0;\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "dsu",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1859",
    "index": "E",
    "title": "Maximum Monogonosity",
    "statement": "You are given an array $a$ of length $n$ and an array $b$ of length $n$. The cost of a segment $[l, r]$, $1 \\le l \\le r \\le n$, is defined as $|b_l - a_r| + |b_r - a_l|$.\n\nRecall that two segments $[l_1, r_1]$, $1 \\le l_1 \\le r_1 \\le n$, and $[l_2, r_2]$, $1 \\le l_2 \\le r_2 \\le n$, are non-intersecting if one of the following conditions is satisfied: $r_1 < l_2$ or $r_2 < l_1$.\n\nThe length of a segment $[l, r]$, $1 \\le l \\le r \\le n$, is defined as $r - l + 1$.\n\nFind the maximum possible sum of costs of non-intersecting segments $[l_j, r_j]$, $1 \\le l_j \\le r_j \\le n$, whose total length is equal to $k$.",
    "tutorial": "Maybe we can relax some conditions? Do we really need to always correctly calculate all sums? Optimize the obvious dp. Let's call the value of a segment $[l; r]$ $f(l, r) = abs(a_l - b_r) + abs(a_r - b_l)$. Let's write $dp[n1][k1]$ - maximum value of segments of total length $k1$ that end before $n1$. The obvious way to recalc is the following: $dp[n1][k1] = max(dp[n1 - 1][k1], dp[n1 - l][k1 - l] + f(n1 - l + 1, n1), 1 \\le l \\le k1)$. This works in $O(NK^2)$ and is too slow. Now let's consider the following: instead of getting the absolute value of segment $[l; r]$, we consider the maximum of the following four combinations: $b_l - a_r + b_r - a_l$, $b_l - a_r - b_r + a_l$, $-b_l + a_r + b_r - a_l$, $-b_l + a_r - b_r + a_l$. We can see that this always gives us the correct answer to the absolute value, since we check all of the possibilities. Now we can look at out dp states as a table, and notice that we recalc over the diagonal (we recalc over all states that have the same value of n1 - k1). Now, for each \"diagonal\", we maintain four maximum combinations: $dp[n1][k1] + b_{k1} + a_{k1}, dp[n1][k1] - b_{k1} + a_{k1}, dp[n1][k1] + b_{k1} - a_{k1}, dp[n1][k1] - b_{k1} - a_{k1}$, and when we want to recalc state $dp[n2][k2]$, we just consider all of the four possibilities.",
    "code": "#include <iostream>\n#include <vector>\nusing namespace std;\nconst long long INF = 1e18;\n#define int long long\n \nvoid solve() {\n\tint N = 0, K = 0; cin >> N >> K;\n\tvector<int> a;\n\tvector<int> b;\n\ta.assign(N, 0);\n\tb.assign(N, 0);\n\tfor (int i = 0; i < N; ++i) {\n\t\tcin >> a[i];\n\t}\n\tfor (int i = 0; i < N; ++i) {\n\t\tcin >> b[i];\n\t}\n\tvector<long long> mx1; // max of (b_l + a_l) + corresponding dp\n\tvector<long long> mx2; // max of (b_l - a_l) + corresponding dp\n\tvector<long long> mn1; // min of (b_l + a_l) + corresponding dp\n\tvector<long long> mn2; // min of (b_l - a_l) + corresponding dp\n\tvector<vector<long long>> dp;\n\tmx1.assign(N + 1, -INF); mx2.assign(N + 1, -INF);\n\tmn1.assign(N + 1, INF); mn2.assign(N + 1, INF);\n\tdp.assign(N + 1, vector<long long>(K + 1, 0));\n\tfor (int i = 0; i <= N; ++i) {\n\t\tfor (int j = 0; j <= min(i, K); ++j) {\n\t\t\tif (i != 0) dp[i][j] = dp[i - 1][j];\n\t\t\tint diag_val = i - j;\n\t\t\tif (i != 0) {\n\t\t\t\tdp[i][j] = max(dp[i][j], b[i - 1] + a[i - 1] - mn1[diag_val]);\n\t\t\t\tdp[i][j] = max(dp[i][j], -b[i - 1] - a[i - 1] + mx1[diag_val]);\n\t\t\t\tdp[i][j] = max(dp[i][j], a[i - 1] - b[i - 1] - mn2[diag_val]);\n\t\t\t\tdp[i][j] = max(dp[i][j], b[i - 1] - a[i - 1] + mx2[diag_val]);\n\t\t\t}\n\t\t\tif (i != N) {\n\t\t\t\tmn1[diag_val] = min(mn1[diag_val], b[i] + a[i] - dp[i][j]);\n\t\t\t\tmx1[diag_val] = max(mx1[diag_val], b[i] + a[i] + dp[i][j]);\n\t\t\t\tmn2[diag_val] = min(mn2[diag_val], b[i] - a[i] - dp[i][j]);\n\t\t\t\tmx2[diag_val] = max(mx2[diag_val], b[i] - a[i] + dp[i][j]);\n\t\t\t}\n\t\t}\n\t}\n\tcout << dp[N][K] << \"\\n\";\n}\n \n \nsigned main() {\n\tint T = 1;\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}\n \n",
    "tags": [
      "brute force",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1859",
    "index": "F",
    "title": "Teleportation in Byteland",
    "statement": "There are $n$ cities in Byteland, some of which are connected by roads, which can be traversed in any direction. The $i$-th road has its own hardness parameter $w_i$. Time spent on traversing a road with its hardness equal to $w_i$ is $\\lceil\\frac{w_i}{c}\\rceil$, where $c$ is the current driving skill.\n\nThe travel network of Byteland is a tree. In other words, between any pair of cities, there is exactly one path that passes through each city at most once.\n\nIn some cities you can visit driving courses. A single course takes $T$ time to complete, and after completing the course the driver's skill $c$ is increased by $2$ times. Notice that the time $T$ required to complete a course is the same in all cities, and courses can be completed in the same city more than once.\n\nYou need to answer the $q$ queries: what is the minimum time it takes to get from the city $a$ to city $b$ if you start the travelling with driving skill $c = 1$?",
    "tutorial": "How many times do we really need to take driving courses? Can you think how would an optimal answer path look like? Can you recalculate the distances required to get to a city from every vertex? Root the tree arbitrarily. First, we can notice that there is no need to take driving courses more than $log{maxW}$ times. Now, let's iterate for the number of driving courses we take from $0$ to $20$ ($2^{20} > 1000000$). For each number we solve separately. Let us fix the number of taken as $q$. Now the path looks like the following: we go over the simple path, then we veer off to take courses in some town, then we come back to the path and finish it. Let's call $d[x]$ the minimum distance required to get from $x$ to a town which offers driving courses and then come back to the same town. We can recalculate $d[x]$ with multi-source BFS. Now, let's look at the vertex $v1$ on the path, from which we will start going off the path. Then, the cost of the path is $d[v1]$ + distance from $a$ to $v1$ on the original edges (with $c = 1$) + distance from $v1$ to $b$ on the modified edges(with $c = 2^{q}$). Now let's look at some cases, let $LCA$ be the LCA of $a$ and $b$, $h1[x]$ - the sum of all original edges from the root downwards to $x$, $h2[x]$ - the sum of all modified edges from the root downwards to $x$. If $v1$ is between $LCA$ and $a$, the cost is $h1[a] - h1[v1] + d1[v1] - h2[LCA] + h2[v1] + h2[b] - h2[LCA]$. If $v1$ is between $LCA$ and $a$, the cost is $h1[a] - h1[LCA] + h1[v1] - h1[LCA] + d1[v1] + h2[b] - h2[v1]$. Now we simply need to consider the terms which depend only on $v1$, and then we need to take the maximum value on a path. For that we can use binary lifting, and for LCA as well.",
    "code": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <cmath>\n#include <stack>\n#include <deque>\n#include <string>\n#include <ctime>\n#include <bitset>\n#include <queue>\n#include <cassert>\n#include<unordered_set>\n#include<unordered_map>\n#include<string.h>\n#include <random>\n#include <chrono>\n#include <math.h>\nusing namespace std;\n#define pi pair<int, int>\n#define ll long long\n#define pll pair<ll, ll>\nconst ll INF = 1e18;\nvector<vector<pi>> g;\nvector<int> is_special;\nvector<vector<int>> bin_lift;\nvector<vector<pi>> new_g;\nvector<int> tin;\nvector<int> tout;\nvector<ll> ans;\nvector<pi> req;\nvector<ll> h_orig;\nvector<ll> h_new;\nvector<ll> d;\nvector<bool> used_bfs;\nvector<vector<pll>> bin_lift_2;\nvector<int> lc;\nvector<int> top_order;\nvector<pair<int, int>> pr;\nint TIMER = 0;\nvoid DFS(int v, int p) {\n    top_order.push_back(v);\n    tin[v] = TIMER++;\n    bin_lift[v][0] = p;\n    for (int i = 1; i < 17; ++i) {\n        if (bin_lift[v][i - 1] == -1) break;\n        bin_lift[v][i] = bin_lift[bin_lift[v][i - 1]][i - 1];\n    }\n    for (auto& x : g[v]) {\n        if (x.first == p) {\n            pr.push_back(x);\n            continue;\n        }\n    }\n    for (auto& x : g[v]) {\n        if (x.first == p) continue;\n        h_orig[x.first] = h_orig[v] + x.second;\n        DFS(x.first, v);\n    }\n    tout[v] = TIMER;\n}\nvoid BFS(int N) {\n    priority_queue<pll> q;\n    for (int i = 0; i < N; ++i) {\n        if (is_special[i]) {\n            q.push({ -0, i });\n            d[i] = 0;\n        }\n    }\n    while (!q.empty()) {\n        int v = q.top().second; q.pop();\n        if (used_bfs[v]) continue;\n        used_bfs[v] = true;\n        for (auto& x : new_g[v]) {\n            if (d[x.first] > d[v] + x.second) {\n                d[x.first] = d[v] + x.second;\n                q.push({ -d[x.first], x.first });\n            }\n        }\n    }\n}\ninline bool isIn(int a, int b) {\n    return tin[a] <= tin[b] && tout[a] >= tout[b];\n}\nint gLCA(int a, int b) {\n    if (isIn(a, b)) return a;\n    if (isIn(b, a)) return b;\n    int cB = b;\n    for (int i = 16; i >= 0; --i) {\n        if (bin_lift[cB][i] == -1) continue;\n        if (!isIn(bin_lift[cB][i], a)) cB = bin_lift[cB][i];\n    }\n    return bin_lift[cB][0];\n}\nll g1(int a, int LCA) {\n    ll mn = d[a] + h_new[a] - h_orig[a];\n    int cK = a;\n    for (int i = 16; i >= 0; --i) {\n        if (bin_lift[cK][i] == -1) continue;\n        if (!isIn(LCA, bin_lift[cK][i])) continue;\n        mn = min(mn, bin_lift_2[cK][i].first);\n        cK = bin_lift[cK][i];\n    }\n    return mn;\n}\nll g2(int a, int LCA) {\n    ll mn = d[a] + h_orig[a] - h_new[a];\n    int cK = a;\n    for (int i = 16; i >= 0; --i) {\n        if (bin_lift[cK][i] == -1) continue;\n        if (!isIn(LCA, bin_lift[cK][i])) continue;\n        mn = min(mn, bin_lift_2[cK][i].second);\n        cK = bin_lift[cK][i];\n    }\n    return mn;\n}\nvoid solve() {\n    top_order.clear();\n    pr.clear();\n    int N = 0, T = 0; cin >> N >> T;\n    g.assign(N, vector<pi>());\n    for (int j = 0; j < N - 1; ++j) {\n        int u = 0, v = 0, w = 0; cin >> u >> v >> w;\n        u--; v--;\n        g[u].push_back({ v, w }); g[v].push_back({ u, w });\n    }\n    is_special.assign(N, 0);\n    string s = \"\"; cin >> s;\n    for (int i = 0; i < N; ++i) is_special[i] = s[i] - '0';\n    tin.assign(N, 0); tout.assign(N, 0);\n    bin_lift.assign(N, vector<int>(17, -1));\n    TIMER = 0;\n    h_orig.assign(N, 0);\n    DFS(0, -1);\n    int Q = 0; cin >> Q;\n    ans.assign(Q, INF);\n    req.clear();\n    lc.clear();\n    for (int j = 0; j < Q; ++j) {\n        int u = 0, v = 0; cin >> u >> v;\n        u--; v--;\n        req.push_back({ u, v });\n        lc.push_back(gLCA(u, v));\n    }\n    bin_lift_2.assign(N, vector<pll>(17, pll(INF, INF)));\n    h_new.assign(N, 0);\n    for (ll level = 1; level <= 20; ++level) {\n        const int w = (1ll << level);\n        new_g.assign(N, vector<pi>());\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j < g[i].size(); ++j) {\n                new_g[i].push_back({ g[i][j].first, g[i][j].second + ((g[i][j].second + w - 1) / w) });\n            }\n        }\n        d.assign(N, INF);\n        used_bfs.assign(N, false);\n        BFS(N);\n        h_new[0] = 0;\n        for (int n = 1; n < N; ++n) {\n            h_new[top_order[n]] = h_new[pr[n - 1].first] + (pr[n - 1].second + w - 1) / w;\n            int p = pr[n - 1].first;\n            int v = top_order[n];\n            bin_lift_2[v][0] = { d[p] + h_new[p] - h_orig[p], d[p] + h_orig[p] - h_new[p] };\n            for (int i = 1; i < 17; ++i) {\n                if (bin_lift[v][i] == -1) break;\n                bin_lift_2[v][i].first = min(bin_lift_2[v][i - 1].first, bin_lift_2[bin_lift[v][i - 1]][i - 1].first);\n                bin_lift_2[v][i].second = min(bin_lift_2[v][i - 1].second, bin_lift_2[bin_lift[v][i - 1]][i - 1].second);\n            }\n        }\n        for (int j = 0; j < Q; ++j) {\n            int a1 = req[j].first; int b1 = req[j].second;\n            int LCA = lc[j];\n            ans[j] = min(ans[j], g1(a1, LCA) + h_orig[a1] - h_new[LCA] + h_new[b1] - h_new[LCA] + level * T);\n            ans[j] = min(ans[j], g2(b1, LCA) + h_orig[a1] - h_orig[LCA] - h_orig[LCA] + h_new[b1] + level * T);\n        }\n    }\n    for (int i = 0; i < Q; ++i) {\n        ans[i] = min(ans[i], h_orig[req[i].first] + h_orig[req[i].second] - 2 * h_orig[lc[i]]);\n        cout << ans[i] << \"\\n\";\n    }\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    cout << setprecision(12);\n    int T = 1;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1860",
    "index": "A",
    "title": "Not a Substring",
    "statement": "A bracket sequence is a string consisting of characters '(' and/or ')'. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example:\n\n- bracket sequences \"()()\" and \"(())\" are regular (they can be transformed into \"(1)+(1)\" and \"((1+1)+1)\", respectively);\n- bracket sequences \")(\", \"(\" and \")\" are not regular.\n\nYou are given a bracket sequence $s$; let's define its length as $n$. Your task is to find a regular bracket sequence $t$ of length $2n$ such that $s$ \\textbf{does not} occur in $t$ as a \\textbf{contiguous substring}, or report that there is no such sequence.",
    "tutorial": "Let's consider the following two cases: the string $s$ contains two consecutive equal characters, for example, \")(((\" or \"())\". In this case, we can choose a string $t$ of the form \"()()()\", since it does not contain a substring of two equal characters, therefore $s$ is not a substring of $t$; in the string $s$, all adjacent characters are different, i.e., it is alternating. In this case, we can choose a string $t$ of the form \"((()))\", since here the length of the longest alternating substring is $2$. The only alternating substring it contains is \"()\", which is a part of every regular bracket sequence. Thus, it is sufficient to consider the answer among only two candidates - \"()()()\" and \"((()))\" of length $2n$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n\tstring s;\n\tcin >> s;\n\tint n = s.size();\n\tstring a, b;\n\tfor (int i = 0; i < 2 * n; ++i) {\n\t  a += \"()\"[i & 1];\n\t  b += \")(\"[i < n];\n\t}\n\tif (a.find(s) == string::npos) {\n\t  cout << \"YES\\n\" << a << '\\n';\n\t} else if (b.find(s) == string::npos) {\n\t  cout << \"YES\\n\" << b << '\\n';\n\t} else {\n\t  cout << \"NO\\n\";\n\t}\n  }\n}",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1860",
    "index": "B",
    "title": "Fancy Coins",
    "statement": "Monocarp is going to make a purchase with cost of exactly $m$ burles.\n\nHe has two types of coins, in the following quantities:\n\n- coins worth $1$ burle: $a_1$ regular coins and infinitely many fancy coins;\n- coins worth $k$ burles: $a_k$ regular coins and infinitely many fancy coins.\n\nMonocarp wants to make his purchase in such a way that there's \\textbf{no change} — the total worth of provided coins is \\textbf{exactly} $m$. He can use both regular and fancy coins. However, he wants to spend as little fancy coins as possible.\n\nWhat's the smallest total number of fancy coins he can use to make a purchase?",
    "tutorial": "There are two ways to approach this problem: a mathematical way and an algorithmic way. Approach 1 Let's start by looking at the possible ways to represent $m$ burles with our coins. For example, we could try to use as many coins of value $k$ as possible: then, the number of coins of value $k$ will be $\\lfloor\\frac{m}{k}\\rfloor$, and the number of coins of value $1$ will be $m \\bmod k$. Now suppose it's not optimal to use that many coins of value $k$; what if it's better to use more coins of value $1$ and fewer coins of value $k$? Well, we can still start with using $\\lfloor\\frac{m}{k}\\rfloor$ coins of value $k$ and $m \\bmod k$ coins of value $1$, and then try to replace one coin of value $k$ with $k$ coins of value $1$ several times (maybe zero). How many times should we do this, and when should we stop to get an optimal solution? Well, firstly, let's make sure that we have already taken as many regular coins as possible. Then, if we have at least $k$ leftover coins of value $1$ which are regular (not fancy), and we have taken at least one fancy coin of value $k$, it's better to replace that coin. It's easy to see that there's no need for any replacements if that's not the case: if we don't have $k$ regular coins which are currently unused, then at least one of the replacement coins will be fancy; and if the coin of value $k$ we want to replace is not fancy, why replacing it at all? So, we could write a while-loop that keeps track how many coins of which types we have taken, and replaces one fancy coin of value $k$ with $k$ regular coins of value $1$ until it's impossible. Unfortunately, this is too slow. But instead of running this loop, we can calculate the number of times we make that replacement in $O(1)$: it is the minimum of the number of regular coins of value $1$ we aren't using, divided by $k$, and the number of fancy coins of value $k$ we are using. So, the outline of the solution is the following: start by taking as many coins of value $k$ as possible, and calculate how many coins of which value we have taken; calculate how many regular and fancy coins of both types we have taken; calculate how many \"replacements\" (discard one fancy coin of value $k$, add $k$ regular coins of value $1$) we can make. Approach 2 The second approach also starts with analyzing how many coins of value $1$ and how many coins of value $k$ we can take. The minimum number of coins of value $k$ we can take is $0$, and the maximum number of such coins is $\\lfloor\\frac{m}{k}\\rfloor$. Let $f(x)$ denote the number of fancy coins we use, if we take exactly $x$ coins of value $k$. This function can easily be calculated because we know how many coins of both types we take, if $x$ is fixed. We need to find the minimum of this function on $[0, \\lfloor\\frac{m}{k}\\rfloor]$. How does $f(x + 1) - f(x)$ behave? The meaning of going from $f(x)$ to $f(x + 1)$ is just replacing $k$ coins of value $1$ with one coin of value $k$. When we increase $x$, obviously, we should try to discard fancy coins of value $1$ first, then regular coins of value $1$ (and the number of fancy coins we will discard will never increase when we increase $x$). Similarly, we should try to take regular coins of value $k$ first, then fancy ones (and the number of fancy coins we take will never decrease when we increase $x$). So, the value of $f(x+1) - f(x)$ does not decrease when $x$ increases. All of this means that the minimum value of $f(x)$ can be found using ternary search.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tint m, k, a1, ak;\n\t\tcin >> m >> k >> a1 >> ak;\n\t\t// function which calculates the number of fancy coins taken\n\t\t// if we take exactly x coins of value k\n\t\tauto f = [m, k, a1, ak](int x)\n\t\t{\n\t\t\tint taken_1 = m - k * x;\n\t\t\treturn max(0, taken_1 - a1) + max(0, x - ak);\n\t\t};\n\t\t\n\t\tint lf = 0;\n\t\tint rg = m / k;\n\t\twhile(rg - lf > 2)\n\t\t{\n\t\t\tint mid = (lf + rg) / 2;\n\t\t\tif(f(mid) < f(mid + 1))\n\t\t\t\trg = mid + 1;\n\t\t\telse\n\t\t\t\tlf = mid;\n\t\t}\n\t\tint ans = 1e9;\n\t\tfor(int i = lf; i <= rg; i++) ans = min(ans, f(i));\n\t\tcout << ans << endl;\n\t}\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1860",
    "index": "C",
    "title": "Game on Permutation",
    "statement": "Alice and Bob are playing a game. They have a permutation $p$ of size $n$ (a permutation of size $n$ is an array of size $n$ where each element from $1$ to $n$ occurs exactly once). They also have a chip, which can be placed on any element of the permutation.\n\nAlice and Bob make alternating moves: Alice makes the first move, then Bob makes the second move, then Alice makes the third move, and so on. During the first move, Alice chooses any element of the permutation and places the chip on that element. During each of the next moves, the current player \\textbf{has to} move the chip to any element that is simultaneously to the left and strictly less than the current element (i. e. if the chip is on the $i$-th element, it can be moved to the $j$-th element if $j < i$ and $p_j < p_i$). If a player cannot make a move (it is impossible to move the chip according to the rules of the game), that player \\textbf{wins} the game.\n\nLet's say that the $i$-th element of the permutation is \\textbf{lucky} if the following condition holds:\n\n- if Alice places the chip on the $i$-th element during her first move, she can win the game no matter how Bob plays (i. e. she has a winning strategy).\n\nYou have to calculate the number of lucky elements in the permutation.",
    "tutorial": "For each position $i$, let's determine its status: whether this position is winning or losing for the player who moved the chip into that position. Since a player can only move a chip into a position with smaller index, we can determine the statuses of positions in the order from $1$ to $n$. You can treat it as dynamic programming. If there is no such $j$ that $j < i$ and $p_j < p_i$, then this position is a losing one, because the other player cannot make a move, which means they win (and the player who placed the chip in that position loses). Otherwise, the other player can make a move. And we already know whether the player wins if they place a chip for all previous positions. If there exists a position $j$ where a move can be made and $j$ is a winning position, then $i$ is a losing one (because our opponent will move there). Otherwise, $i$ is a winning position. Thus, we have a solution with a time complexity of $O(n^2)$, for each position $i$, we need to iterate through all possible transitions $j$. However, we can notice that we are only interested in two simple properties to determine the status of each position: whether a move can be made from the current position, and whether a move can be made into a winning position. The first property can be easily checked if we maintain the minimum element up to the current position $i$, let's call it $mn$. And for the second property, it is sufficient to maintain the minimum element among winning positions, let's call it $mnWin$. Then, position $i$ is winning if $mn < p_i$ and $mnWin > p_i$. Thus, the time complexity of the solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    int ans = 0;\n    int mn = n + 1, mnWin = n + 1;\n    while (n--) {\n      int x;\n      cin >> x;\n      if (mn < x && x < mnWin) {\n      \tans += 1;\n      \tmnWin = x;\n      }\n      mn = min(mn, x);\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "data structures",
      "dp",
      "games",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1860",
    "index": "D",
    "title": "Balanced String",
    "statement": "You are given a binary string $s$ (a binary string is a string consisting of characters 0 and/or 1).\n\nLet's call a binary string \\textbf{balanced} if the number of subsequences 01 (the number of indices $i$ and $j$ such that $1 \\le i < j \\le n$, $s_i=0$ and $s_j=1$) equals to the number of subsequences 10 (the number of indices $k$ and $l$ such that $1 \\le k < l \\le n$, $s_k=1$ and $s_l=0$) in it.\n\nFor example, the string 1000110 is balanced, because both the number of subsequences 01 and the number of subsequences 10 are equal to $6$. On the other hand, 11010 is not balanced, because the number of subsequences 01 is $1$, but the number of subsequences 10 is $5$.\n\nYou can perform the following operation any number of times: choose two characters in $s$ and swap them. Your task is to calculate the minimum number of operations to make the string $s$ balanced.",
    "tutorial": "Let's calculate the following dynamic programming: $dp_{i, cnt0, cnt01}$ - the minimum number of changes in string $s$ if we consider only $i$ first characters of it, the number of characters 0 on that prefix is $cnt0$, and the number of subsequences 01 on that prefix is equal to $cnt01$. The transitions are pretty simple. Let's look at the transitions according to the character we are trying to place at the next position: if it is 0, then there is transition from the state $(i, cnt0, cnt01)$ to the state $(i + 1, cnt0 + 1, cnt01)$ and the value of $dp$ depends on $s_i$ (the value stays the same if $s_i=0$, and increases by $1$ otherwise); if it is 1, then there is transition from the state $(i, cnt0, cnt01)$ to the state $(i + 1, cnt0, cnt01 + cnt0)$, and the value of $dp$ depends on $s_i$ (the value stays the same if $s_i=1$ and increases by $1$ otherwise). So, this dynamic programming works in $O(n^4)$. It remains us to get the answer to the problem from that dynamic programming. It is stored in $dp_{n, cnt0, need}$, where $cnt0$ is equal to the number of characters 0 in the string $s$, and $need=\\frac{cnt0 \\cdot cnt1}{2}$ (because the number of subsequences 01 should be equal to the number of subsequences 10). But our dynamic programming stores the number of changes in the string, and the problems asks for the minimum number of swaps. However, we can easily get it from the $dp$ value. Since the amounts of zeroes and ones are fixed in the string, then the number of changes from 0 to 1 equals to the number of changes from 1 to 0 and we can pair them up. So, the answer to the problem is the half of the $dp$ value.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing li = long long;\n \nconst int N = 111;\n \nint n;\nstring s;\nint dp[2][N][N * N];\n \nint main() {\n  cin >> s;\n  n = s.size();\n  dp[0][0][0] = 0;\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j <= i + 1; ++j) {\n      for (int cnt = 0; cnt <= j * (i + 1 - j); ++cnt) {\n        dp[1][j][cnt] = n;   \n      }\n    }\n    for (int j = 0; j <= i; ++j) {\n      for (int cnt = 0; cnt <= j * (i - j); ++cnt) {\n        dp[1][j + 1][cnt] = min(dp[1][j + 1][cnt], dp[0][j][cnt] + (s[i] != '0'));\n        dp[1][j][cnt + j] = min(dp[1][j][cnt + j], dp[0][j][cnt] + (s[i] != '1'));\n      }\n    } \n    swap(dp[0], dp[1]);\n  }\n  int cnt0 = count(s.begin(), s.end(), '0');\n  cout << dp[0][cnt0][cnt0 * (n - cnt0) / 2] / 2 << '\\n';\n}",
    "tags": [
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1860",
    "index": "E",
    "title": "Fast Travel Text Editor",
    "statement": "You are given a string $s$, consisting of lowercase Latin letters.\n\nThere's a cursor, initially placed between two adjacent letters of the string. The cursor can't be placed before the first or after the last letter.\n\nIn one move, you can perform one of three actions:\n\n- move a cursor one position to the left (if that doesn't place it before the first letter);\n- move a cursor one position to the right (if that doesn't place it after the last letter);\n- let $x$ be the letter immediately to the left of the cursor, and $y$ be the letter immediately to the right of the cursor. Choose any pair of \\textbf{adjacent} letters in the string such that the \\textbf{left} of them is $x$ and the \\textbf{right} of them is $y$, and move the cursor to the position between these two letters.\n\nYou are asked $m$ queries. In each query, you are given two integers $f$ and $t$, which correspond to two valid positions of the cursor in the string. In response to the query, you have to calculate the minimum number of operations required to move the cursor from position $f$ to position $t$.",
    "tutorial": "Let's start with the easiest slow solution. We can basically treat the problem as a graph one. There are $n-1$ vertices and the operations represent edges: from $i$ to $i+1$, from $i+1$ to $i$ and from $i$ to $j$ if $s_i = s_j$ and $s_{i+1} = s_{j+1}$. Then, for a query, we can run any algorithm that finds the shortest path. For example, BFS. That will be $n^2$ per query in the worst case, because the third type of actions produces a lot of edges. Let's try to optimize the third action. If you look at the edges between all positions linked by the third action, they just form cliques. So the distance between every pair of vertices should be equal to $1$. Instead of having a lot of edges, we can add a dummy vertex that simulates this behavior. For example, add a directed edge from each vertex in the clique to the dummy vertex of weight $1$ and a directed edge back of weight $0$. Now, you can travel from one vertex to another in the clique in $1$, but only use $O(n)$ edges in total. Thus, the BFS for each query will be linear. Well, a couple of things are wrong with that statement... First, not a regular BFS, of course, but a 0-1 BFS now, since there are edges of weight $0$. Second, there are also some dummy vertices. How many of them? Each clique is induced by all positions that have the same letters to the left and to the right of them. So, there are $|A|^2$ options, where $|A| = 26$, and $n + |A|^2$ vertices in total. To optimize further, let's investigate the structure of the path. There are trivial paths: they just go left or right without using the third action. We can initialize the answer with them. Otherwise, a path uses the jump to the dummy node at least once. Let that node be $s$. So, the path looks like $f \\rightarrow s$, then $s \\rightarrow t$. Let's use the fact that there are not that many candidates for $s$. We can iterate over $s$ and update the answer with each of them. If the optimal path goes through any of them, we will find it. And calculating $f \\rightarrow s$ or $s \\rightarrow t$ is way easier. First, $f \\rightarrow s$ is the same as $s \\rightarrow f$ in a transposed graph (all edges are reversed). Second, we can calculate the shortest path from $s$ to all vertices with a single 0-1 BFS. Thus, we get a solution in $O(|A|^2 \\cdot (n + |A|^2 + q))$. We can either run $|A|^2$ BFS's before reading the queries and save the results, using $O(|A|^2 \\cdot n)$ memory. Alternatively, we can read the queries, then run each BFS and update the answer with its results immediately for $O(n + |A|^2)$ memory. The second option will generally also be faster by a constant factor, since there are fewer cache misses.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nconst int INF = 1e9;\nconst int AL = 26;\n \nstruct query{\n\tint f, t, ans;\n};\n \nstruct edge{\n\tint u, w;\n};\n \nint main() {\n\tcin.tie(0);\n\tiostream::sync_with_stdio(false);\n\tstring s;\n\tcin >> s;\n\tint n = s.size();\n\t\n\tint m;\n\tcin >> m;\n\tvector<query> a(m);\n\tforn(i, m){\n\t\tcin >> a[i].f >> a[i].t;\n\t\t--a[i].f, --a[i].t;\n\t\ta[i].ans = abs(a[i].f - a[i].t);\n\t}\n\t\n\tint k = n - 1 + AL * AL;\n\tvector<vector<edge>> g(k);\n\tforn(i, n - 1){\n\t\tint j = n - 1 + (s[i] - 'a') * AL + (s[i + 1] - 'a');\n\t\tg[i].push_back({j, 0});\n\t\tg[j].push_back({i, 1});\n\t\tif (i > 0){\n\t\t\tg[i].push_back({i - 1, 1});\n\t\t\tg[i - 1].push_back({i, 1});\n\t\t}\n\t}\n\t\n\tfor (int st = n - 1; st < k; ++st){\n\t\tvector<int> d(k, INF);\n\t\td[st] = 0;\n\t\tdeque<int> q;\n\t\tq.push_back(st);\n\t\twhile (!q.empty()){\n\t\t\tint v = q.front();\n\t\t\tq.pop_front();\n\t\t\tfor (auto it : g[v]){\n\t\t\t\tif (d[it.u] <= d[v] + it.w) continue;\n\t\t\t\td[it.u] = d[v] + it.w;\n\t\t\t\tif (it.w == 0) q.push_front(it.u);\n\t\t\t\telse q.push_back(it.u);\n\t\t\t}\n\t\t}\n\t\tforn(i, m){\n\t\t\ta[i].ans = min(a[i].ans, d[a[i].f] + d[a[i].t] - 1);\n\t\t}\n\t}\n\t\n\tforn(i, m) cout << a[i].ans << '\\n';\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1860",
    "index": "F",
    "title": "Evaluate RBS",
    "statement": "You are given $2n$ tuples of values $(a, b, c)$, where $a$ and $b$ are positive integers and $c$ is a bracket '(' or ')'. Exactly $n$ tuples have $c = $'(' and the other $n$ tuples have $c =$ ')'.\n\nYou are asked to choose two positive values $x$ and $y$ ($x > 0$ and $y > 0$; \\textbf{not necessarily integers}) and sort the tuples in the increasing value of $a \\cdot x + b \\cdot y$. If several tuples have the same value, you can place them in any order among themselves.\n\nIs it possible to choose such $x$ and $y$ that taking brackets $c$ from the tuples in the resulting order produces a regular bracket sequence?\n\nA regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence.",
    "tutorial": "Think of this as a geometry problem. If that's a revelation for you, don't worry, you'll start seeing it with more experience. We have some points $(a, b)$, are asked to choose a vector $(x, y)$ and sort the points by a dot product of $(a, b)$ and $(x, y)$. What exactly is a dot product? Well, $A \\cdot B = |A| \\cdot |B| \\cdot \\cos \\alpha$. Obviously, $(a, b)$ will always be the same length no matter what $(x, y)$ we choose. At the same time, the length of $(x, y)$ will also be the same for a fixed $(x, y)$. So, a dot product only depends on an angle between $(x, y)$ and $(a, b)$. Thus, the vector $(x, y)$ can always be a unit one. Imagine iterating over all vectors $(x, y)$ in the increasing order of their angle. Consider a pair of different points $(a_1, b_1)$ and $(a_2, b_2)$. When does one go before the other in the order? We can compare their angles to $(x, y)$. So, if we keep rotating $(x, y)$, the order of two points will be changing when their angles to $(x, y)$ are the same. That happens exactly twice, and both events correspond to the opposite vectors. Both of them lie on the line perpendicular to the one $(a_1, b_1)$ and $(a_2, b_2)$ are on. Now imagine that rotating $(x, y)$ idea as an actual algorithm. We'd want to iterate over all $(x, y)$ while maintaining the order of points. When we encounter $(x, y)$ on a line where two points swap, we swap. For each $(x, y)$ we check if current order of points produces an RBS. For points with the same dot product (so when $(x, y)$ is on a line where these swap), we arrange them in such an order that the opening bracket goes first, then the closing bracket. That must be pretty obvious from any RBS intuition. Obviously, we don't care about all $(x, y)$ (also there are infinitely many of them). We only care about ones where something happens. Now, that algorithm is called a radial sweepline. Very commonly not the prettiest thing to code, but I'll share some implementation details that help with this one. I'll also call vectors $(x, y)$ events from now on sometimes. First, generate all interesting $(x, y)$, arrange them by their angle and save what happens for each of them. Get rid of pairs with non-positive $x$ or $y$. Now, arranging by angle can be done with just a cross product. Also, with that, you don't even have to normalize the vectors. You can use a map from points to events with a comparator using cross product (and no additional tie-breaks). Second, instead of swapping pairs one by one on each angle (which might turn very annoying very fast), let's process them all in bulk. When there are multiple pairs of points swapping on the same angle, extract all of them from the current order, sort them on their own and insert them back. Notice that it doesn't produce exactly the same outcome. It rearranges the points as if all points with equal dot product are free among each other until the next event. However, if we turn $(x, y)$ just a bit further, they will get in their true places. But our algorithm will just skip to the next event without fixing the order. It's actually quite easy to fix the issue. Along with sorting points that swap on the current event, take also points that had to be swapped on the previous event. Sort them all together. That won't increase the complexity (however, will increase the constant factor), but will fix the order of the previous event points. The sorting is best done with an inverse permutation of the order. For each point, remember its current place in the order. Now, we can find where each point is, and we can easily update the inverse permutation after the rearrangement. Since every pair of point appears at most $O(1)$ times, the total size of arrays to sort is $O(n^2)$. Finally, how to check for an RBS every time? We can't afford $O(n)$, so we must maintain something. For a sequence to be an RBS, all prefix balances of brackets should be non-negative (since we are already guaranteed by the input that the final balance is $0$). The idea is easy. Notice how the points that are swapped on each event actually represent some segments of the order. And all swaps are performed within these segments. Thus, the prefix balances are only updated for the positions of the swapping points. Basically, we can maintain the entire array of the prefix balances and the number of negative elements in it. On each event, recalculate its entire parts corresponding to the positions of the sorted points. If the number of negative elements becomes $0$, then we found the answer. Overall complexity: $O(n^2 \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nconst int INF = 1e9;\n \nstruct bracket{\n\tint a, b, c;\n};\n \nstruct point{\n\tint x, y;\n};\n \nlong long cross(const point &a, const point &b){\n\treturn a.x * 1ll * b.y - a.y * 1ll * b.x;\n}\n \nlong long dot(const point &a, const bracket &b){\n\treturn a.x * 1ll * b.a + a.y * 1ll * b.b;\n}\n \nbool operator <(const point &a, const point &b){\n\treturn cross(a, b) > 0;\n}\n \nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--){\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<bracket> val;\n\t\tforn(i, 2 * n){\n\t\t\tint a, b;\n\t\t\tstring c;\n\t\t\tcin >> a >> b >> c;\n\t\t\tval.push_back({a, b, c[0] == '(' ? 1 : -1});\n\t\t}\n\t\tmap<point, vector<int>> opts;\n\t\tforn(i, 2 * n) forn(j, 2 * n){\n\t\t\tint dx = val[i].b - val[j].b;\n\t\t\tint dy = val[j].a - val[i].a;\n\t\t\tif (dx <= 0 || dy <= 0) continue;\n\t\t\topts[{dx, dy}].push_back(i);\n\t\t\topts[{dx, dy}].push_back(j);\n\t\t}\n\t\topts[{1, INF}];\n\t\tvector<int> ord(2 * n), rord(2 * n);\n\t\tiota(ord.begin(), ord.end(), 0);\n\t\tsort(ord.begin(), ord.end(), [&](int i, int j){\n\t\t\tlong long di = dot({INF, 1}, val[i]);\n\t\t\tlong long dj = dot({INF, 1}, val[j]);\n\t\t\tif (di != dj) return di < dj;\n\t\t\treturn val[i].c > val[j].c;\n\t\t});\n\t\tforn(i, 2 * n) rord[ord[i]] = i;\n\t\tint neg = 0, cur = 0;\n\t\tvector<int> bal(1, 0);\n\t\tfor (int i : ord){\n\t\t\tcur += val[i].c;\n\t\t\tbal.push_back(cur);\n\t\t\tneg += cur < 0;\n\t\t}\n\t\tbool ans = neg == 0;\n\t\tvector<int> prv;\n\t\tfor (auto it : opts){\n\t\t\tvector<int> tot = prv;\n\t\t\tfor (int x : it.second) tot.push_back(x);\n\t\t\tsort(tot.begin(), tot.end(), [&](int i, int j){\n\t\t\t\treturn rord[i] < rord[j];\n\t\t\t});\n\t\t\ttot.resize(unique(tot.begin(), tot.end()) - tot.begin());\n\t\t\tfor (int x : tot) neg -= bal[rord[x] + 1] < 0;\n\t\t\tvector<int> tmp = tot;\n\t\t\tsort(tot.begin(), tot.end(), [&](int i, int j){\n\t\t\t\tlong long di = dot(it.first, val[i]);\n\t\t\t\tlong long dj = dot(it.first, val[j]);\n\t\t\t\tif (di != dj) return di < dj;\n\t\t\t\treturn val[i].c > val[j].c;\n\t\t\t});\n\t\t\tvector<int> nrord(tot.size());\n\t\t\tforn(i, tot.size()) nrord[i] = rord[tmp[i]];\n\t\t\tforn(i, tot.size()) rord[tot[i]] = nrord[i];\n\t\t\tfor (int x : tot){\n\t\t\t\tbal[rord[x] + 1] = bal[rord[x]] + val[x].c;\n\t\t\t\tneg += bal[rord[x] + 1] < 0;\n\t\t\t}\n\t\t\tif (neg == 0){\n\t\t\t\tans = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprv = it.second;\n\t\t}\n\t\tputs(ans ? \"YES\" : \"NO\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "geometry",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1861",
    "index": "A",
    "title": "Prime Deletion",
    "statement": "A prime number is a positive integer that has exactly two different positive divisors: $1$ and the integer itself. For example, $2$, $3$, $13$ and $101$ are prime numbers; $1$, $4$, $6$ and $42$ are not.\n\nYou are given a sequence of digits from $1$ to $9$, in which \\textbf{every digit from $1$ to $9$ appears exactly once}.\n\nYou are allowed to do the following operation \\textbf{several (maybe zero) times}: choose any digit from the sequence and delete it. \\textbf{However, you cannot perform this operation if the sequence consists of only two digits.}\n\nYour goal is to obtain a sequence which represents a prime number. Note that you cannot reorder the digits in the sequence.\n\nPrint the resulting sequence, or report that it is impossible to perform the operations so that the resulting sequence is a prime number.",
    "tutorial": "There are many possible approaches to this problem. For example, you could use brute force to solve it: iterate on every integer from $1$, check that it is a prime number by iterating on its divisors, and check that it appears as a subsequence in the given digit sequence. If you find the answer, break the loop and print the number you found. But that's a bit lengthy to code. Let's try something different. We can try looking for a small set of primes such that at least one of the primes from that set appears in the given sequence. Let's try short primes, they are easier to work with. If there exist two prime numbers of length $2$ consisting of digits $x$ and $y$, one of them is $xy$, and the other of them is $yx$, then one of them will definitely appear in our sequence. If $x$ comes earlier than $y$, then $xy$ appears in the sequence, otherwise it's $yx$. Thankfully, it's possible to find these two primes. For example, you can use $13$ and $31$; one of them will definitely appear in the sequence. So, the easiest solution is to find whether $1$ is earlier than $3$ in the sequence. If $1$ is earlier, then $13$ is the answer, otherwise it's $31$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tstring s;\n\t\tcin >> s;\n\t\tif(s.find(\"1\") < s.find(\"3\"))\n\t\t\tcout << 13;\n\t\telse\n\t\t\tcout << 31;\n\t\tcout << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1861",
    "index": "B",
    "title": "Two Binary Strings",
    "statement": "You are given two strings $a$ and $b$ of equal length, consisting of only characters 0 and/or 1; both strings start with character 0 and end with character 1.\n\nYou can perform the following operation any number of times (possibly zero):\n\n- choose one of the strings and two \\textbf{equal} characters in it; then turn all characters between them into those characters.\n\nFormally, you choose one of these two strings (let the chosen string be $s$), then pick two integers $l$ and $r$ such that $1 \\le l < r \\le |s|$ and $s_l = s_r$, then replace every character $s_i$ such that $l < i < r$ with $s_l$.\n\nFor example, if the chosen string is 010101, you can transform it into one of the following strings by applying one operation:\n\n- 000101 if you choose $l = 1$ and $r = 3$;\n- 000001 if you choose $l = 1$ and $r = 5$;\n- 010001 if you choose $l = 3$ and $r = 5$;\n- 010111 if you choose $l = 4$ and $r = 6$;\n- 011111 if you choose $l = 2$ and $r = 6$;\n- 011101 if you choose $l = 2$ and $r = 4$.\n\nYou have to determine if it's possible to make the given strings equal by applying this operation any number of times.",
    "tutorial": "If the answer is YES, we can always bring both strings to the form $00 \\dots 01 \\dots 11$ (some prefix consists of zeros, some suffix consists of ones, and all zeroes are before all ones). It's true because after we make both strings equal, we can apply another operation with $l = i, r = |a|$, where $i$ is the minimum index where both strings have $1$ after we made them equal. For example, in the first test case, the strings are equal to $01110001$ after applying all operations considered in the statement. We can turn them into the string $01111111$ by applying operation with $l = 2, r = 8$. Okay, now let's try to find out when we can transform a string into the form $00 \\dots 0011 \\dots 11$. We claim that it's possible to transform the string $s$ into the form \"$i$ first elements are zeroes, all the remaining elements are ones\" if and only if $s_i = 0$ and $s_{i+1} = 1$: if $s_i = 0$ and $s_{i+1} = 1$, we can apply two operations with $l = 1, r = i$ and $l = i+1, r = |s|$, and the string turns into the form \"$i$ first elements are zeroes, all the remaining elements are ones\"; however, if that's not the case, then either $s_i = s_{i+1}$, or $s_i = 1$ and $s_{i+1} = 0$. In the former case, we need to change one of these two elements; but since they are equal and adjacent, every operation on them will affect them both, so it's impossible to change only one of them. In the latter case, we need to set either $s_i$ to $0$ or $s_{i+1}$ to $1$ first; and when we do it, the elements become equal, and every operation on them will affect them both. So, it's impossible to bring the string into the form \"$i$ first elements are zeroes, all the remaining elements are ones\". So, the answer is YES if there is an index $i$ such that $a_i = b_i = 0$ and $a_{i+1} = b_{i+1} = 1$. Otherwise, the answer is NO.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        string a, b;\n        cin >> a >> b;\n        bool ok = false;\n        for (int i = 0; i + 1 < a.size(); ++i) {\n            if (a[i] == b[i] && a[i] == '0' && a[i + 1] == b[i + 1] && a[i + 1] == '1') {\n                ok = true;\n            }\n        }\n        \n        if (ok) \n            puts(\"YES\");\n        else\n            puts(\"NO\");\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1861",
    "index": "C",
    "title": "Queries for the Array",
    "statement": "Monocarp had an array $a$ consisting of integers. Initially, \\textbf{this array was empty}.\n\nMonocarp performed three types of queries to this array:\n\n- choose an integer and append it \\textbf{to the end of the array}. Each time Monocarp performed a query of this type, he wrote out a character +;\n- remove \\textbf{the last element} from the array. Each time Monocarp performed a query of this type, he wrote out a character -. Monocarp never performed this query on an empty array;\n- check if the array is sorted in non-descending order, i.,e. $a_1 \\le a_2 \\le \\dots \\le a_k$, where $k$ is the number of elements in the array currently. \\textbf{Every array with less than $2$ elements is considered sorted}. If the array was sorted by the time Monocarp was performing that query, he wrote out a character 1. Otherwise, he wrote out a character 0.\n\nYou are given a sequence $s$ of $q$ characters 0, 1, + and/or -. These are the characters that were written out by Monocarp, given in the exact order he wrote them out.\n\nYou have to check if this sequence is consistent, i. e. it was possible for Monocarp to perform the queries so that the sequence of characters he wrote out is exactly $s$.",
    "tutorial": "First of all, let's analyze which situations cause the answer to be NO. There are two types: if the number of elements in the array is currently less than $2$, the array is definitely sorted. So, if we get a 0 and the number of elements is $0$ or $1$, the answer is NO; if the array is sorted, but some prefix of it (maybe coinciding with the whole array) is not sorted, this is also a NO. These are the only two situations that cause a NO. We can prove that if none of this occurs, the answer is YES, using the following construction: every time there is a + query, we will add $1$ to the array; every time there is a 0 query, and the current array is sorted, we will change the last element of the array to $0$ (and assume we added $0$ instead of $1$ in the query it was added). That way, we can ensure that the array stays sorted as long as possible. The only cases when this construction doesn't work are: we try to change an element to $0$, but there is no such element (the array is empty), or the array stays sorted after the change (we change the first element). This is exactly when a query 0 appears and the current number of elements is less than $2$; we change an element to $0$, and it makes the current array non-sorted, but it has to be sorted due to a query of type 1 affecting it. This is exactly when we have a sorted array with a non-sorted prefix. Okay, now we have to check these two conditions somehow. The first one is quite easy: just keep track of the number of elements in the array; every time you process +, increase it; every time you process -, decrease it; every time you process 0, check the number of elements. The second condition is tricky. There are many approaches on how to handle it; I will describe two of them. Approach $1$ (Roms) We are interested in a situation when a sorted array has an unsorted prefix. Suppose there is a state of our array when this happens. In case when this array has multiple prefixes for which we know that they are sorted, which one should we choose? It should be the longest sorted prefix, because we want an unsorted prefix to be shorter (or have the same length). And among all non-sorted prefixes, we are interested in the shortest one, for the same reason. So, let's go over the queries and keep track of the shortest non-sorted prefix and the longest sorted prefix of our array. Let's analyze how our queries affect these two values. when we append a new element (query of type +), we no longer know that the current array is sorted, but its longest sorted prefix stays the same, and its shortest non-sorted prefix also stays the same. So, we don't need to update these values; when we delete the last element (query of type -), the length of the sorted prefix might change. If it was equal to the number of elements before the query, it should decrease by $1$, because the last element on that prefix was deleted, and the prefix no longer exists. As for the length of the shortest unsorted prefix, if it was equal to the number of elements in the array before the query, it should be set to $0$ - because maybe the last element of the array made the array unsorted, and we don't know anything about the prefixes before it. when we process a query of type 0 or 1, we should update the shortest non-sorted prefix or the longest sorted prefix accordingly. After each query, we can just check that the longest sorted prefix is shorter than the shortest non-sorted prefix (or one of them doesn't exist). Approach $2$ (BledDest) BledDest is a graph theory lunatic, so naturally, he designed a graph-related solution to this problem. Let's visualize all states of the array using a rooted tree. Every moment of time after a query corresponds to some vertex in this tree, and one vertex $x$ is a parent of another vertex $y$ if the array in the state represented by $x$ is the same as the array represented by $y$, but without the last element. For example, if the string of queries is ++-++---+-+, the tree looks like this (the labels on the vertices correspond to the number of queries after which the array is in that state): This tree can be constructed from the query string as follows. Start with the root vertex, which represents the state when the array is empty. Every time you get a query +, you need to go down the tree. You create a new vertex to go into, because if you go down the tree to an existing vertex, it means that the states will coincide - and the arrays in these two states are not necessarily similar. If you get a query -, you go up the tree - so you either maintain the current path in the tree in a stack, or store a parent for each vertex, to know where to go when you go up. Okay, now what about queries of type 0 and 1? Every time we process such a query, we mark the current vertex to remember that it has a 0 or a 1 in it. For example, you can store two boolean arrays that give you the information whether a vertex is marked with 0 and whether a vertex is marked with 1. So, how does this tree help us in solving the problem? Recall what we're trying to check: we want to find out if a sorted array has a non-sorted prefix. In terms of our tree, it means that a vertex marked with 0 has an ancestor (possibly itself) marked with 1. To check that in $O(n)$, you can, for example, run a series of DFS traversals from all vertices marked with 1 and make sure that you don't visit any vertices marked with 0. Or you could do it in a single DFS (as the model solution does) which, for each vertex in the tree, computes if it has a vertex marked with 0 in its subtree.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nvector<int> has0, has1;\nvector<vector<int>> g;\n \nbool ans;\n \nbool dfs(int x, int d)\n{\n\tif(has0[x] && (has1[x] || d <= 1))\n\t\tans = false;\n\tbool res = false;\n\tfor(auto y : g[x])\n\t\tres |= dfs(y, d + 1);\n\tif(has0[x] && res)\n\t\tans = false;\n\treturn res || has1[x];\n}\n \nvoid solve()\n{\n\tans = true;\n\thas0.push_back(0);\n\thas1.push_back(0);\n\tg.push_back(vector<int>());\n\tint ts = 1;\n\t\n\tstring s;\n\tcin >> s;\n\tvector<int> st = {0};\n\tfor(auto x : s)\n\t{\n\t\tint cur = st.back();\n\t\tif(x == '0')\n\t\t\thas0[cur] = 1;\n\t\tif(x == '1')\n\t\t\thas1[cur] = 1;\n\t\tif(x == '+')\n\t\t{\n\t\t\tg[cur].push_back(ts);\n\t\t\tst.push_back(ts);\n\t\t\tts++;\n\t\t\thas0.push_back(0);\n\t\t\thas1.push_back(0);\n\t\t\tg.push_back(vector<int>());\n\t\t}\n\t\tif(x == '-')\n\t\t\tst.pop_back();\n\t}\n\t\n\tdfs(0, 0);\n\tcout << (ans ? \"YES\\n\" : \"NO\\n\");\n\t\n\thas0.clear();\n\thas1.clear();\n\tg.clear();\n}\n \nint main()\n{\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t\tsolve();\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "implementation",
      "strings",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1861",
    "index": "D",
    "title": "Sorting By Multiplication",
    "statement": "You are given an array $a$ of length $n$, consisting of \\textbf{positive integers}.\n\nYou can perform the following operation on this array any number of times (possibly zero):\n\n- choose three integers $l$, $r$ and $x$ such that $1 \\le l \\le r \\le n$, and multiply every $a_i$ such that $l \\le i \\le r$ by $x$.\n\nNote that you can choose \\textbf{any} integer as $x$, it doesn't have to be positive.\n\nYou have to calculate the minimum number of operations to make the array $a$ sorted in \\textbf{strictly ascending} order (i. e. the condition $a_1 < a_2 < \\dots < a_n$ must be satisfied).",
    "tutorial": "At first, let's figure out which multiplications by negative values we perform. After a few multiplications, some subarrays of the array $a$ might become negative. If there is more than one such negative subarray (and there are non-negative elements between them), then the array cannot be sorted by multiplication by non-negative values. If there is one such subarray, then it must be a prefix of the array. Let's try solving this problem in $O(n^2)$. Let's iterate over the length of the negative prefix and solve the problem for some fixed negative prefix. Make all the elements on this prefix negative (for example, by multiplying by $-1$), and then iterate over indices of the array in ascending order. If $a_i < a_{i + 1}$ (where $i$ is the current index), then we just go to the next index. Otherwise, we can always multiply the prefix (if $a_i < 0$) or the suffix (if $a_i > 0$) by some positive value so that the prefix $a_1, \\dots, a_i, a_{i + 1}$ becomes sorted. Note that if we fixed the negative prefix, we cannot restore the condition $a_i < a_{i+1}$ on multiple indices $i$ with just one operation. For example, if $a_i, a_{i+1}, a_j$ and $a_{j+1}$ are all positive, $a_i \\ge a_{i+1}$ and $a_j \\ge a_{j+1}$, we need at least two operations to ensure that $a_i < a_{i+1}$ and $a_j < a_{j+1}$. In the first operation, we should choose $l = i+1$, and in the second operation, we should choose $l = j+1$, so that both $a_{i+1}$ becomes greater than $a_i$ and $a_{j+1}$ becomes greater than $a_j$. For example, if the array $a$ is $[-1, -2, -3, 2, 1, 3]$ (after we fixed that the first $3$ elements will be negative). we perform the following sequence of actions: $i = 1$, $a_1 \\ge a_2$ and $a_1 < 0$, so we just multiply the prefix $a_1, \\dots, a_1$ by some positive value (for example $4$); after that the current array $a = [-4, -2, -3, 2, 1, 3]$; $i = 2$, $a_2 \\ge a_3$ and $a_2 < 0$, so we just multiply the prefix $a_1, \\dots, a_2$ by some positive value (for example $2$); after that the current array $a = [-8, -4, -3, 2, 1, 3]$; $i = 3$, $a_3 < a_4$ so we just go to the next index; $i = 4$, $a_4 \\ge a_5$ and $a_4 > 0$, so we just multiply the suffix $a_5, \\dots, a_6$ by some positive value (for example $10$); after that, the current array $a = [-8, -4, -3, 2, 10, 30]$; $i = 5$, $a_5 < a_6$ so we just go to the next index; $i = 6$, so the array is sorted. To solve the problem in $O(n)$, we need the following observation: if the negative prefix has length $x$, we perform the operations in two cases: if $a_i \\le a_{i+1}$ (in the original array) and $i+1 \\le x$; if $a_i \\ge a_{i+1}$ and $i \\ge x$. So, we can iterate on the length of negative prefix $x$ and maintain the number of indices $i$ such that $a_{i-1} \\le a_i$ and $i < x$; and the number of indices $j$ such that $a_{j} \\ge a_{j+1}$ and $j \\ge x$. Don't forget the case when $x = 0$, then we don't need an extra operation to make the prefix negative.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 200 * 1000 + 5;\n \nint t;\nint n;\nint a[N];\n \nint main() {\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc){\n    \tcin >> n;\n    \tfor (int i = 0; i < n; ++i)\n    \t    cin >> a[i];\n    \t\n    \tint cnt = 0;\n    \tfor (int i = 1; i < n; ++i)\n    \t    cnt += (a[i - 1] >= a[i]);\n    \t    \n    \tint res = n, cnt2 = 0;\n        for (int i = 0; i <= n; ++i) {\n            bool isMultipliedByNegative = (i > 0);\n            res = min(res, isMultipliedByNegative + cnt + cnt2);\n            \n            if (i + 1 < n)\n                cnt -= (a[i] >= a[i + 1]);\n            if (i > 0)\n                cnt2 += (a[i - 1] <= a[i]);\n        }\n        \n        cout << res << endl;\n    }\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1861",
    "index": "E",
    "title": "Non-Intersecting Subpermutations",
    "statement": "You are given two integers $n$ and $k$.\n\nFor an array of length $n$, let's define its cost as the maximum number of contiguous subarrays of this array that can be chosen so that:\n\n- each element belongs to at most one subarray;\n- the length of each subarray is exactly $k$;\n- each subarray contains each integer from $1$ to $k$ exactly once.\n\nFor example, if $n = 10$, $k = 3$ and the array is $[1, 2, 1, 3, 2, 3, 2, 3, 1, 3]$, its cost is $2$ because, for example, we can choose the subarrays from the $2$-nd element to the $4$-th element and from the $7$-th element to the $9$-th element, and we can show that it's impossible to choose more than $2$ subarrays.\n\nCalculate the sum of costs over all arrays of length $n$ consisting of integers from $1$ to $k$, and print it modulo $998244353$.",
    "tutorial": "Let's try to solve another problem first: we are given an array and a value of $k$, we need to compute its cost. How can we do it? We can solve it greedily: find the leftmost subarray of length $k$ that contains all values from $1$ to $k$ and doesn't intersect with previously added subarrays, add it to the answer, rinse and repeat. How do we search for the subarray with $k$ distinct values? Let's go through the array from left to right and maintain the maximum number of last elements that are distinct, i. e. the longest suffix that consists of pairwise distinct elements. When this number of elements reaches $k$, we add $1$ to the cost of the array, and drop the number of pairwise distinct elements on suffix to $0$ (because we can't reuse them). When we meet an element that already belongs to the longest suffix we maintain, we need to shorten this suffix (it should start right after the last occurrence of that element). Okay. Now back to the original problem. Let's try to design a dynamic programming solution that will use the number of last distinct elements we can use as one of the states. For example, it could be something like this: $dp_{i,x,c}$ - how many arrays of length $i$ exist such that the number of elements on the suffix we can use is $x$, and the current cost of the array is $c$?; The transitions can be done as follows. When we transition from $dp_{i,x,c}$ to $dp_{i+1,x',c'}$, we need to consider two cases: the new element does not appear among the last $x$ elements. The number of ways to choose it is $(k-x)$, and we transition either to $dp_{i+1,x+1,c}$, or to $dp_{i+1,0,c+1}$ (the latter transition is used when $x = k - 1$, since we increase the cost by $1$ and cannot reuse the elements); the new element appears among the last $x$ elements. Let's iterate which of them is that element: let it be the $j$-th element from the back, then the current number of elements we can use becomes $j$, and we transition to $dp_{i+1,j,c}$. However, this is $O(n^2 \\cdot k)$, since the number of states is $O(n^2)$ (the second state is up to $k$, the third state is up to $\\frac{n}{k}$). Let's optimize it to $O(n^2)$. The transitions that actually make our solution slow are the transitions of the second type. Let's look at them in detail. From $dp_{i,x,c}$, there are transitions of the second type to every state $dp_{i+1,j,c}$ such that $j \\le x$, and in every such transition, the new element is chosen uniquely (so they have the same coefficient equal to $1$). This means that we can compute all of those transitions efficiently using partial sums: the difference between the value of $dp_{i+1,j,c}$ and the value of $dp_{i+1,j+1,c}$ (if we don't consider the transitions of the first type) is just $dp_{i,j,c}$. So, all transitions of the second type can be handled in $O(n^2)$, and there are only $O(n^2)$ transitions of the first type. This is enough to solve the problem, but I want to add one final touch that allows to implement the solution much easier. We don't actually need the third state. We can use Contribution To The Sum technique: let's rewrite our dynamic programming without the third state, and every time we try to increase the second state to $k$, instead of increasing the third state, we calculate how many arrays have this subarray contributing to the cost. This is just the current value of dynamic programming, multiplied by the number of ways we can choose the remaining elements (which is $k^{n-i-1}$). That way, the implementation becomes much simpler, and the complexity of the solution is now $O(nk)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\n \nint add(int x, int y)\n{\n\tx += y;\n\twhile(x >= MOD) x -= MOD;\n\twhile(x < 0) x += MOD;\n\treturn x;\n}\n \nint sub(int x, int y)\n{\n\treturn add(x, -y);\n}\n \nint mul(int x, int y)\n{\n\treturn (x * 1ll * y) % MOD;\n}\n \nint binpow(int x, int y)\n{\n\tint z = 1;\n\twhile(y > 0)\n\t{\n\t\tif(y & 1) z = mul(z, x);\n\t\tx = mul(x, x);\n\t\ty /= 2;\n\t}\n\treturn z;\n}\n \nint main()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tint ans = 0;\n\tvector<vector<int>> dp(n + 1, vector<int>(k, 0));\n\tdp[0][0] = 1;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tint cur = 0;\n\t\tfor(int j = k - 1; j >= 1; j--)\n\t\t{\n\t\t\tcur = add(cur, dp[i][j]);\n\t\t\tdp[i + 1][j] = cur;\n\t\t}\n\t\tfor(int j = k - 1; j >= 0; j--)\n\t\t{\n\t\t\tint nxt = (j + 1) % k;\n\t\t\tdp[i + 1][nxt] = add(dp[i + 1][nxt], mul(dp[i][j], k - j));\n\t\t}\n\t\tans = add(ans, mul(dp[i + 1][0], binpow(k, n - (i + 1))));\n\t}\n\tcout << ans << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1861",
    "index": "F",
    "title": "Four Suits",
    "statement": "The game of Berland poker is played as follows. There are $n+1$ people: $n$ players, numbered from $1$ to $n$, and the dealer. The dealer has a deck which contains cards of four different suits (the number of cards of each suit \\textbf{is not necessarily the same}); the number of cards in the deck is divisible by $n$. The dealer gives all cards to the players, so that \\textbf{every player receives the same number of cards, and the whole deck is used}.\n\nAfter the cards are dealt, every player chooses one of four suits (independently) and discards all cards from their hand which do not belong to their chosen suit. The winner of the game is the player with the maximum number of cards left in their hand. The number of points the winner receives is $x - y$, where $x$ is the number of cards in the winner's hand, and $y$ is the maximum number of cards among all \\textbf{other} players; everyone else receives $0$ points. Note that it means that \\textbf{if there are multiple players with the maximum number of cards}, everyone receives $0$ points.\n\nSince every player wants to maximize their odds to win, \\textbf{they will choose a suit with the maximum number of cards in their hand}.\n\nMonocarp is the dealer. He has already given some cards to the players; the $i$-th player received $a_{i,j}$ cards of suit $j$. Note that \\textbf{the number of cards in players' hands don't have to be the same at this moment}. Monocarp has $b_1, b_2, b_3, b_4$ cards of suit $1, 2, 3, 4$ respectively left in his deck. He has to give them to the players so that, after all cards are dealt, every player has the same number of cards.\n\nFor each player, calculate the maximum number of points they can receive among all ways to deal the remaining cards according to the rules of the game.",
    "tutorial": "As far as I am concerned, fully greedy solutions don't work in this problem. However, we can try employing some greedy ideas. First of all, let's calculate how many cards each player should receive. I will call it $remain_i$ for the $i$-th player. Suppose we want to maximize the answer for the $i$-th player. Let's iterate on the suit $j$ for which that player will have the maximum number of cards. We can assign as many cards of suit $j$ as possible from the deck to the $i$-th player: suppose we have given a card of suit $j$ to another player, and a card of another suit to the $i$-th player. If we exchange them, the answer won't become worse. Okay, now we want to find the minimum possible maximum number of cards (after the players discard some of their cards) that the other players can have. Let's suppose it's $x$. There should be a way to assign the remaining cards from the deck so that every player $k$ gets exactly $remain_k$ cards, and no player has more than $x$ cards in any suit (except for the $i$-th player). The good thing is that if it's possible to assign cards for some value of $x$, it's also possible for $x+1$. So, we can find this $x$ with binary search. Now we have to solve the following problem: check if there exists an assignment of cards from the deck for a particular $x$. We can model it using maximum flow: create a network with a source, sink, a vertex for every player except for $i$, and a vertex for every suit; for every suit, create a directed edge from the source to that suit with capacity equal to the number of cards of that suit left in the deck (don't forget that we greedily assigned some cards to the $i$-th player!); for every player $k$ except $i = k$, create a directed edge from that player to the sink with capacity equal to $remain_k$; for every suit and every player except $i$, create a directed edge from the suit to the player with capacity equal to the maximum number of cards of that suit the player can receive; check that the maximum flow in this network saturates all edges going into the sink (i. e. is equal to the sum of $remain_k$ for all players except the $i$-th one). However, simply building this network is too slow, let alone finding the maximum flow in it. We need something faster. If you're thinking about using Hall's theorem, then unfortunately, it doesn't work since it cannot handle the constraint on $x$. But you're thinking in the right direction. Let's try to find the minimum cut in this network. To do this, iterate on the $mask$ of the suits that will be in the set $S$ in the minimum cut, add the capacities of other suits to the value of the cut, and for every player, determine if it's better to have them in the set $S$ or in the set $T$ of the cut. The key thing is that if we fix the mask of suits and the value of $x$, it is uniquely determined. Let the number of suits in the mask be $suits$, and the total number of cards the $k$-th player has from those suits be $alreadyHas_{mask,k}$. The total capacity of all edges going into the $k$-th player that we need to cut is $suits \\cdot x - alreadyHas_{mask,k}$, and the capacity of the outgoing edge is $remain_k$. So, the value the $k$-th player adds to the cut is $\\min(remain_k, suits \\cdot x - alreadyHas_{mask,k})$, and we need to compute the sum of these values for all players (except for the player $i$) efficiently. This is basically the outline of the solution. Now the implementation part follows. To be honest, I think that the model solution is a bit too complicated, some solutions I've seen during the contest are shorter and cleaner. But I will explain it nevertheless. For every $mask$ and every value of $x$, let's try to find the sum of $\\min(suits \\cdot x - alreadyHas_{mask,k}, remain_k)$ over all players. To do this, for every player, find the maximum value of $x$ such that $suits \\cdot x - alreadyHas_{mask,k}$ is less than $remain_k$. For the value of $x$ not greater than this value, the player adds $suits \\cdot x - alreadyHas_{mask,k}$ to the cut; for greater values, the player adds $remain_k$. Both of those are linear functions, and for every $x$, we can compute the sum of those linear functions for all players using difference arrays. I calculate these sums of linear functions in all values of $x$ up to $2 \\cdot 10^6$, because there might be situations when a player has more than $10^6$ cards of a particular suit. That way, when we want to compute the minimum cut for the $i$-th player, chosen mask of suits and the value of $x$, we can use the already computed sum of those functions to find the total value all players add to the cut, and then subtract the value that the $i$-th player added (since we need to discard that player from the network). The rest of the implementation is fairly straightforward, you can see the reference code for details (I hope I commented it well enough). One final note: when choosing the left border for binary search, I compute the maximum number of cards among all suits that the other players have, to make sure that I don't choose the value of $x$ that leads to edges having negative capacity in the network. But I think it's not actually required, so you can try discarding it from the solution. The model implementation works in something like $O(2^K \\cdot (n \\cdot K + A))$ for precalculation of linear functions plus $O(n \\cdot 2^K \\cdot K^2 \\cdot \\log A)$ for actually solving the problem, where $A$ is the maximum number of cards of a particular suit a player can have ($A \\le 2 \\cdot 10^6$).",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int K = 4;\nconst int N = 2 * int(1e6) + 43;\n \npair<long long, long long> operator+(const pair<long long, long long>& a, const pair<long long, long long>& b)\n{\n\treturn make_pair(a.first + b.first, a.second + b.second);\n}\n \npair<long long, long long> operator-(const pair<long long, long long>& a, const pair<long long, long long>& b)\n{\n\treturn make_pair(a.first - b.first, a.second - b.second);\n}\n \n// prefix sums for an array of pairs\nvector<pair<long long, long long>> pref_sums(const vector<pair<long long, long long>>& a)\n{\n\tint n = a.size();\n\tvector<pair<long long, long long>> ans(n);\n\tans[0] = a[0];\n\tfor(int i = 1; i < n; i++)\n\t\tans[i] = ans[i - 1] + a[i];\n\treturn ans;\n}\n \n// for an array of pairs denoting linear functions, evaluate\n// them in the corresponding points\nvector<long long> eval(const vector<pair<long long, long long>>& a)\n{\n\tint n = a.size();\n\tvector<long long> ans(n);\n\tfor(int i = 0; i < n; i++)\n\t\tans[i] = a[i].first * i + a[i].second;\n\treturn ans;\n}\n \nvoid solve()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<vector<int>> a(n, vector<int>(K));\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < K; j++)\n\t\t\tscanf(\"%d\", &a[i][j]);\n\tvector<int> b(K);\n\tfor(int i = 0; i < K; i++)\n\t\tscanf(\"%d\", &b[i]);\n\t\n\tint deck_size = 0;\n\tfor(int i = 0; i < K; i++)\n\t\tdeck_size += b[i];\n\t\n\t// calculate the remaining number of cards for each player\n\tlong long full = deck_size;\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < K; j++)\n\t\t\tfull += a[i][j];\n\tvector<int> remain(n, full / n);\n\tfor(int i = 0; i < n; i++)\n\t\tfor(int j = 0; j < K; j++)\n\t\t\tremain[i] -= a[i][j];\n\t\n\t// for every player, calculate the maximum number of cards\n\t// they already have among all suits\n\t// and store it in a multiset\n\tvector<int> min_val(n);\n\tfor(int i = 0; i < n; i++)\n\t\tmin_val[i] = *max_element(a[i].begin(), a[i].end());\n\tmultiset<int> min_vals;\n\tfor(int i = 0; i < n; i++)\n\t\tmin_vals.insert(min_val[i]);\n\t\n\t// for every mask of suits and every player, calculate\n\t// the number of cards in those suits they already have\n\tvector<vector<int>> already_has(1 << K, vector<int>(n));\n\tfor(int mask = 0; mask < (1 << K); mask++)\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tfor(int j = 0; j < K; j++)\n\t\t\t\tif(mask & (1 << j))\n\t\t\t\t\talready_has[mask][i] += a[i][j];\n\t// for every mask of suits and every player, calculate the\n\t// maximum value of x such that if that player can receive \n\t// no more than x cards in each suit, the vertex of that\n\t// player should belong to T in the cut\n\tvector<vector<int>> max_x(1 << K, vector<int>(n));\n\tfor(int mask = 0; mask < (1 << K); mask++)\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\tint suits = __builtin_popcount(mask);\n\t\t\tif (suits == 0) max_x[mask][i] = N - 2;\n\t\t\telse\n\t\t\t{\n\t\t\t\t// incoming edges have capacity of\n\t\t\t\t// x - a[i][j]\n\t\t\t\tint incoming = -already_has[mask][i];\n\t\t\t\t// outgoing edge has capacity of remain[i]\n\t\t\t\t// find the maximum x such that\n\t\t\t\t// suits * x + incoming < remains[i]\n\t\t\t\tint x = (remain[i] - incoming) / suits;\n\t\t\t\tx = min(x, N - 2);\n\t\t\t\tmax_x[mask][i] = x;\n\t\t\t}\n\t\t}\n\t\n\t// for every mask and for all players, calculate the sum of \n\t// values they add to the cut if they can have no more than\n\t// x cards of each suit in the mask\n\tvector<vector<long long>> add_to_cut(1 << K, vector<long long>(N));\n\tfor(int mask = 0; mask < (1 << K); mask++)\n\t{\n\t\tint suits = __builtin_popcount(mask);\n\t\tvector<pair<long long, long long>> aux(N);\n\t\tfor(int i = 0; i < n; i++)\n\t\t{\n\t\t\t// for the i-th player, they add remains[i] to\n\t\t\t// the minimum cut if x > max_x[mask][i]\n\t\t\t// otherwise, they add\n\t\t\t// suits * x - already_has[mask][i]\n\t\t\tint incoming = -already_has[mask][i];\n\t\t\t// add [suits * x - incoming] on segment [0, max_x]\n\t\t\tint x = max_x[mask][i];\n\t\t\tpair<long long, long long> f1 = {suits, incoming};\n\t\t\taux[0] = aux[0] + f1;\n\t\t\taux[x + 1] = aux[x + 1] - f1;\n\t\t\t// add remain[i] on [max_x + 1, N)\n\t\t\tpair<long long, long long> f2 = {0, remain[i]};\n\t\t\taux[x + 1] = aux[x + 1] + f2;\n\t\t\taux[N - 1] = aux[N - 1] - f2;\n\t\t}\n\t\t// sum up those functions and evaluate them\n\t\tadd_to_cut[mask] = eval(pref_sums(aux));\n\t}\n\t\n\t// now we're ready to solve the problem!\n\tvector<int> ans(n);\n\t// iterate on the player we want to maximize\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\t// iterate on the suits they will maximize\n\t\tfor(int j = 0; j < K; j++)\n\t\t{\n\t\t\tint d = min(remain[i], b[j]);\n\t\t\tint max_cards = a[i][j] + d;\n\t\t\tb[j] -= d;\n\t\t\t// find the maximum current score over all others\n\t\t\tmin_vals.erase(min_vals.find(min_val[i]));\n\t\t\tint max_rival = *min_vals.rbegin();\n\t\t\tmin_vals.insert(min_val[i]);\n\t\t\tif(max_rival >= max_cards)\n\t\t\t\tans[i] = max(ans[i], 0);\n\t\t\telse\n\t\t\t{\n\t\t\t\t// binary search on the maximum cards over all\n\t\t\t\t// opponents\n\t\t\t\tint L = max_rival - 1;\n\t\t\t\tint R = max_cards;\n\t\t\t\twhile(R - L > 1)\n\t\t\t\t{\n\t\t\t\t\tint mid = (L + R) / 2;\n\t\t\t\t\tlong long min_cut = 1e18;\n\t\t\t\t\tlong long req_flow = deck_size - remain[i];\n\t\t\t\t\t// iterate on the mask of suit vertices\n\t\t\t\t\t// which belong to S\n\t\t\t\t\tfor(int mask = 0; mask < (1 << K); mask++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint suits = __builtin_popcount(mask);\n\t\t\t\t\t\tlong long cur_cut = 0;\n\t\t\t\t\t\tfor(int z = 0; z < K; z++)\n\t\t\t\t\t\t\tif(!(mask & (1 << z)))\n\t\t\t\t\t\t\t\tcur_cut += b[z];\n\t\t\t\t\t\tcur_cut += add_to_cut[mask][mid];\n\t\t\t\t\t\t// don't forget to discard our player\n\t\t\t\t\t\t// from the flow network!\n\t\t\t\t\t\tif(mid > max_x[mask][i])\n\t\t\t\t\t\t\tcur_cut -= remain[i];\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlong long add = mid * suits - already_has[mask][i];\n\t\t\t\t\t\t\tcur_cut -= add;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmin_cut = min(min_cut, cur_cut);\n\t\t\t\t\t}\n\t\t\t\t\tif(min_cut < req_flow)\n\t\t\t\t\t\tL = mid;\n\t\t\t\t\telse\n\t\t\t\t\t\tR = mid;\n\t\t\t\t}\n\t\t\t\tans[i] = max(ans[i], max_cards - R);\n\t\t\t}\n\t\t\tb[j] += d;\n\t\t}\n\t}\n\t\n\tfor(int i = 0; i < n; i++)\n\t\tprintf(\"%d \", ans[i]);\n\tputs(\"\");\n}\n \nint main()\n{\n\tint t = 1;\n\tfor(int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "flows",
      "greedy"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1862",
    "index": "A",
    "title": "Gift Carpet",
    "statement": "Recently, Tema and Vika celebrated Family Day. Their friend Arina gave them a carpet, which can be represented as an $n \\cdot m$ table of lowercase Latin letters.\n\nVika hasn't seen the gift yet, but Tema knows what kind of carpets she likes. Vika will like the carpet if she can read her name on. She reads column by column from left to right and chooses one or zero letters from current column.\n\nFormally, the girl will like the carpet if it is possible to select four distinct columns in order from left to right such that the first column contains \"v\", the second one contains \"i\", the third one contains \"k\", and the fourth one contains \"a\".\n\nHelp Tema understand in advance whether Vika will like Arina's gift.",
    "tutorial": "Note that if the answer is <<YES>>, then there exists a reading of the word <<vika>> in which the leftmost letter <<v>> is included. Among such readings, we can also consider the one in which the leftmost letter <<i>> is included, which is located to the right of the first occurrence of <<v>>. Similarly, we can do the same for the remaining letters. Therefore, it is sufficient to greedily search for the characters in order. Let's store the input data in a 2D array and process it by going through the columns from left to right. First, we will search for the character <<v>> by iterating through all the characters in each processed column. Once we find the character <<v>>, we will similarly search for the character <<i>> and so on.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nint32_t main() {\n    int q;\n    cin >> q;\n    while (q--) {\n        int n, m;\n        cin >> n >> m;\n        vector<string> carpet(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> carpet[i];\n        }\n        string vika = \"vika\";\n        int fnd = 0;\n        for (int i = 0; i < m; ++i) {\n            bool check = false;\n            for (int j = 0; j < n; ++j) {\n                if (carpet[j][i] == vika[fnd]) {\n                    check = true;\n                }\n            }\n            if (check) {\n                ++fnd;\n                if (fnd == 4) {\n                    break;\n                }\n            }\n        }\n        if (fnd == 4) {\n            cout << \"YES\\n\";\n        } else {\n            cout << \"NO\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1862",
    "index": "B",
    "title": "Sequence Game",
    "statement": "Tema and Vika are playing the following game.\n\nFirst, Vika comes up with a sequence of positive integers $a$ of length $m$ and writes it down on a piece of paper. Then she takes a new piece of paper and writes down the sequence $b$ according to the following rule:\n\n- First, she writes down $a_1$.\n- Then, she writes down only those $a_i$ ($2 \\le i \\le m$) such that $a_{i - 1} \\le a_i$. Let the length of this sequence be denoted as $n$.\n\nFor example, from the sequence $a=[4, 3, 2, 6, 3, 3]$, Vika will obtain the sequence $b=[4, 6, 3]$.\n\nShe then gives the piece of paper with the sequence $b$ to Tema. He, in turn, tries to guess the sequence $a$.\n\nTema considers winning in such a game highly unlikely, but still wants to find at least one sequence $a$ that could have been originally chosen by Vika. Help him and output any such sequence.\n\n\\textbf{Note that the length of the sequence you output should not exceed the input sequence length by more than two times.}",
    "tutorial": "Let's compare each pair of adjacent numbers. If the left number is smaller than the right number, then the right number is at least $2$. We will insert $1$ between them. Now, for each pair of numbers, it is true that either these two numbers were originally in the sequence, or one of them is $1$. In this case, if two numbers were originally in the sequence, then the left number is not smaller than the right number. If the left number is $1$, then it is smaller than the right number, since the right number was at least $2$. If the right number is $1$, then the left number in the pair is not smaller than the right number. We have checked all cases. It is evident that such a sequence is valid, as Vika would have only removed all the $1$ we added and nothing more.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nint32_t main() {\n    int q;\n    cin >> q;\n    while (q--) {\n        int n;\n        cin >> n;\n        vector<int> a;\n        for (int i = 0; i < n; ++i) {\n            int x;\n            cin >> x;\n            if (i && a.back() > x) {\n                a.push_back(1);\n            }\n            a.push_back(x);\n        }\n        cout << a.size() << \"\\n\";\n        for (int el : a)\n            cout << el << \" \";\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1862",
    "index": "C",
    "title": "Flower City Fence",
    "statement": "Anya lives in the Flower City. By order of the city mayor, she has to build a fence for herself.\n\nThe fence consists of $n$ planks, each with a height of $a_i$ meters. According to the order, the heights of the planks must \\textbf{not increase}. In other words, it is true that $a_i \\ge a_j$ for all $i < j$.\n\nAnya became curious whether her fence is symmetrical with respect to the diagonal. In other words, will she get the same fence if she lays all the planks horizontally in the same order.\n\nFor example, for $n = 5$, $a = [5, 4, 3, 2, 1]$, the fence is symmetrical. Because if all the planks are laid horizontally, the fence will be $[5, 4, 3, 2, 1]$, as shown in the diagram.\n\n\\begin{center}\n{\\small On the left is the fence $[5, 4, 3, 2, 1]$, on the right is the same fence laid horizontally}\n\\end{center}\n\nBut for $n = 3$, $a = [4, 2, 1]$, the fence is not symmetrical. Because if all the planks are laid horizontally, the fence will be $[3, 2, 1, 1]$, as shown in the diagram.\n\n\\begin{center}\n{\\small On the left is the fence $[4, 2, 1]$, on the right is the same fence laid horizontally}\n\\end{center}\n\nHelp Anya and determine whether her fence is symmetrical.",
    "tutorial": "Obviously, if $a_1 \\neq n$, then this fence is not symmetric, because the fence $a$ has a length of $n$, while the horizontally laid fence has a length of $a_1 \\neq n$. Now let's build a fence $b$ using horizontal boards that would match the original fence $a$. And let's check if the arrays $a$ and $b$ are equal. If they are equal, then the fence is symmetric; otherwise, it is not. There won't be any memory issues since all $a_i \\le n$, which means the length of array $b$ does not exceed $n$.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> a(n + 1);\n        for (int i = 1; i <= n; i++) {\n            cin >> a[i];\n        }\n        if (a[1] != n) {\n            cout << \"NO\" << '\\n';\n            continue;\n        }\n        vector<int> b;\n        for (int i = n; i >= 1; i--) {\n            while (b.size() < a[i]) {\n                b.push_back(i);\n            }\n        }\n        bool meow = true;\n        for (int i = 1; i <= n; i++) {\n            if (a[i] != b[i - 1]) {\n                cout << \"NO\" << '\\n';\n                meow = false;\n                break;\n            }\n        }\n        if (meow) {\n            cout << \"YES\" << '\\n';\n        }\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1862",
    "index": "D",
    "title": "Ice Cream Balls",
    "statement": "Tema decided to improve his ice cream making skills. He has already learned how to make ice cream in a cone \\textbf{using exactly two} balls.\n\nBefore his ice cream obsession, Tema was interested in mathematics. Therefore, he is curious about the \\textbf{minimum} number of balls he needs to have in order to make \\textbf{exactly} $n$ \\textbf{different} types of ice cream.\n\nThere are plenty possible ice cream flavours: $1, 2, 3, \\dots$. Tema can make two-balls ice cream with any flavours (probably the same).\n\nTwo ice creams are considered different if their sets of ball flavours are different. For example, $\\{1, 2\\} = \\{2, 1\\}$, but $\\{1, 1\\} \\neq \\{1, 2\\}$.\n\nFor example, having the following ice cream balls: $\\{1, 1, 2\\}$, Tema can make only two types of ice cream: $\\{1, 1\\}$ and $\\{1, 2\\}$.\n\n\\textbf{Note, that Tema do not need to make all the ice cream cones at the same time. This means that he making ice cream cones independently. Also in order to make a following cone $\\{x, x\\}$ for some $x$, Tema needs at least $2$ balls of type $x$}.\n\nHelp Tema answer this question. It can be shown that answer always exist.",
    "tutorial": "First, let's note that having more than two balls of the same type is meaningless. Let's denote $x$ as the number of flavours of balls represented by two instances of each ball. Let $y$ denote the number of flavours represented by a single instance. Let's calculate the number of different ways to make an ice cream from these balls: we can make $x$ ice creams from balls of the same flavour and $\\dfrac{(x + y) \\cdot (x + y - 1)}{2}$ ice creams from balls of different flavours. In the problem, we are asked to select balls in such a way that $x + \\dfrac{(x + y) \\cdot (x + y - 1)}{2} = n$. Note that for a fixed sum of $x + y$, we can uniquely determine $x$ and therefore $y$ (or determine that there is no solution for that sum). Let's assume we have found an answer with a minimum sum of $x + y = k$. This means $\\dfrac{k \\cdot (k - 1)}{2} \\leq n \\leq \\dfrac{k \\cdot (k - 1)}{2} + k$. Moreover, if we find an answer with a sum of $x + y = k + 1$, then $k + \\dfrac{k \\cdot (k - 1)}{2} \\leq n \\leq k + \\dfrac{k \\cdot (k - 1)}{2} + k + 1$. From this, we can see that this is only possible when $n = k + \\dfrac{k \\cdot (k - 1)}{2}$. It is also evident that there are no answers with a sum greater than $k + 2$. Now, all we need to do is perform a binary search on the sum of $x + y$ and then determine $x$ and $y$. And don't forget to consider the case when two sums of $x + y$ may be suitable, in order to choose the one with the fewest number of balls.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nint32_t main() {\n    int q;\n    cin >> q;\n    while (q--) {\n        int n;\n        cin >> n;\n        int l = 0, r = min<int>(2e9, 2 * n);\n        while (r - l > 1) {\n            int m = (l + r) >> 1;\n            // m = x + y, answer = x + 2 * y\n            if (m * (m - 1) / 2 + m < n) {\n                l = m;\n            } else {\n                r = m;\n            }\n        }\n        int y = n - r * (r - 1) / 2;\n        if ((r + 1) * r / 2 <= n) {\n            cout << min(r + y, r + 1 + n - (r + 1) * r / 2) << \"\\n\";\n        } else {\n            cout << r + y << \"\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1862",
    "index": "E",
    "title": "Kolya and Movie Theatre",
    "statement": "Recently, Kolya found out that a new movie theatre is going to be opened in his city soon, which will show a new movie every day for $n$ days. So, on the day with the number $1 \\le i \\le n$, the movie theatre will show the premiere of the $i$-th movie. Also, Kolya found out the schedule of the movies and assigned the entertainment value to each movie, denoted by $a_i$.\n\nHowever, the longer Kolya stays without visiting a movie theatre, the larger the decrease in entertainment value of the next movie. That decrease is equivalent to $d \\cdot cnt$, where $d$ is a predetermined value and $cnt$ is the number of days since the last visit to the movie theatre. It is also known that Kolya managed to visit another movie theatre a day before the new one opened — the day with the number $0$. \\textbf{So if we visit the movie theatre the first time on the day with the number $i$, then $cnt$ — the number of days since the last visit to the movie theatre will be equal to $i$}.\n\nFor example, if $d = 2$ and $a = [3, 2, 5, 4, 6]$, then by visiting movies with indices $1$ and $3$, $cnt$ value for the day $1$ will be equal to $1 - 0 = 1$ and $cnt$ value for the day $3$ will be $3 - 1 = 2$, so the total entertainment value of the movies will be $a_1 - d \\cdot 1 + a_3 - d \\cdot 2 = 3 - 2 \\cdot 1 + 5 - 2 \\cdot 2 = 2$.\n\nUnfortunately, Kolya only has time to visit \\textbf{at most $m$ movies}. Help him create a plan to visit the cinema in such a way that the total entertainment value of all the movies he visits is maximized.",
    "tutorial": "Let's notice that if we visit the cinema on days with numbers $i_1, i_2, \\ldots, i_k$, the total entertainment value of the visited movies will be equal to $(a_{i_1} - d \\cdot i_1) + (a_{i_2} - d \\cdot (i_2 - i_1)) + \\ldots + (a_{i_k} - d \\cdot (i_k - i_{k-1})) = (a_{i_1} + a_{i_2} + \\ldots + a_{i_k}) - d \\cdot i_k$. Thus, it is sufficient to iterate over the day when Kolya will visit the cinema for the last time - $i_k$, and maintain the maximum $m - 1$ non-negative elements on the prefix $[1, i_k - 1]$. This can be done, for example, using std::multiset. The total complexity of the solution will be $O(n \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nint32_t main() {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        int n, m, d;\n        cin >> n >> m >> d;\n        vector<int> a(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n        }\n        int ans = 0;\n        set<pair<int, int>> s;\n        int sum = 0;\n        for (int i = 0; i < n; ++i) {\n            int cur = sum + a[i] - d * (i + 1);\n            ans = max(ans, cur);\n            if (a[i] > 0) {\n                s.insert({a[i], i});\n                sum += a[i];\n                if (s.size() >= m) {\n                    sum -= (s.begin()->first);\n                    s.erase(s.begin());\n                }\n            }\n        }\n        cout << ans << endl;\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1862",
    "index": "F",
    "title": "Magic Will Save the World",
    "statement": "A portal of dark forces has opened at the border of worlds, and now the whole world is under a terrible threat. To close the portal and save the world, you need to defeat $n$ monsters that emerge from the portal one after another.\n\nOnly the sorceress Vika can handle this. She possesses two magical powers — water magic and fire magic. In one second, Vika can generate $w$ units of water mana and $f$ units of fire mana. She will need mana to cast spells. Initially Vika have $0$ units of water mana and $0$ units of fire mana.\n\nEach of the $n$ monsters that emerge from the portal has its own strength, expressed as a positive integer. To defeat the $i$-th monster with strength $s_i$, Vika needs to cast a water spell or a fire spell of at least the same strength. In other words, Vika can spend at least $s_i$ units of water mana on a water spell, or at least $s_i$ units of fire mana on a fire spell.\n\nVika can create and cast spells instantly. Vika can cast an unlimited number of spells every second as long she has enough mana for that.\n\nThe sorceress wants to save the world as quickly as possible, so tell her how much time she will need.",
    "tutorial": "First, let's note that Vika can defeat all the monsters at once, in the last second. There is no point in spending mana gradually. Now, let's say we know how many seconds Vika will accumulate mana before spending it. Then we also know how much mana she will have accumulated by that time. How should she spend it? Note that the total strength of the monsters is given to us. Therefore, it is enough for us to spend as much of the available water mana as possible, so that there is enough fire mana left for the remaining monsters. This is a well-known knapsack problem. Finally, let's note that we don't need to iterate over the number of seconds and build the knapsack each time. It is enough to build it initially, and then iterate over how much water mana we will spend and whether we will have enough fire mana left for the rest.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nint32_t main() {\n    int q;\n    cin >> q;\n    while (q--) {\n        int w, f, n;\n        cin >> w >> f >> n;\n        vector<int> s(n);\n        int sum_s = 0;\n        for (int i = 0; i < n; ++i) {\n            cin >> s[i];\n            sum_s += s[i];\n        }\n        vector<bool> dp(sum_s + 1);\n        dp[0] = true;\n        for (int i = 0; i < n; ++i) {\n            for (int w = sum_s; w - s[i] >= 0; --w) {\n                dp[w] = dp[w] || dp[w - s[i]];\n            }\n        }\n        int ans = 2e9;\n        for (int i = 0; i <= sum_s; ++i) {\n            if (dp[i]) {\n                ans = min(ans, max((i + w - 1) / w, (sum_s - i + f - 1) / f));\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1862",
    "index": "G",
    "title": "The Great Equalizer",
    "statement": "Tema bought an old device with a small screen and a worn-out inscription \"The Great Equalizer\" on the side.\n\nThe seller said that the device needs to be given an array $a$ of integers as input, after which \"The Great Equalizer\" will work as follows:\n\n- Sort the current array in non-decreasing order and remove duplicate elements leaving only one occurrence of each element.\n- If the current length of the array is equal to $1$, the device stops working and outputs the single number in the array — output value of the device.\n- Add an arithmetic progression {$n,\\ n - 1,\\ n - 2,\\ \\ldots,\\ 1$} to the current array, where $n$ is the length of the current array. In other words, $n - i$ is added to the $i$-th element of the array, when indexed from zero.\n- Go to the first step.\n\nTo test the operation of the device, Tema came up with a certain array of integers $a$, and then wanted to perform $q$ operations on the array $a$ of the following type:\n\n- Assign the value $x$ ($1 \\le x \\le 10^9$) to the element $a_i$ ($1 \\le i \\le n$).\n- Give the array $a$ as input to the device and find out the result of the device's operation, \\textbf{while the array $a$ remains unchanged during the operation of the device}.\n\nHelp Tema find out the output values of the device after each operation.",
    "tutorial": "Let's take a look at the maximum difference between adjacent numbers in a sorted sequence. Each cycle it decreases by $1$. This helps us understand the main observation: the answer for the sequence is the maximum number in it + the maximum difference between adjacent numbers in sorted order. To answer queries, it is sufficient to maintain these two values. To maintain the maximum number, we will store the numbers in std::multiset. And to maintain the maximum difference, we will maintain std::multiset of differences. When replacing a number, we will remove the old number and replace the difference between it and its neighbors with the difference between the neighbors. Then we will add the new number and replace the difference between its neighbors with the difference between the added number and each of the neighbors. All of this is implemented through working with std::multiset, which you can see, for example, in the author's solution.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        scanf(\"%d\", &n);\n        vector<int> a(n);\n        for (int i = 0; i < n; ++i) {\n            scanf(\"%d\", &a[i]);\n        }\n        if (n == 1) {\n            int q;\n            scanf(\"%d\", &q);\n            while (q--) {\n                int pos, val;\n                scanf(\"%d %d\", &pos, &val);\n                cout << val << \" \";\n            }\n            cout << \"\\n\";\n            continue;\n        }\n        multiset<int> aset;\n        for (int i = 0; i < n; ++i) {\n            aset.insert(a[i]);\n        }\n        multiset<int> deltas;\n        for (auto it = ++aset.begin(); it != aset.end(); ++it) {\n            auto prev = it;\n            --prev;\n            deltas.insert(*it - *prev);\n        }\n        int q;\n        scanf(\"%d\", &q);\n        while (q--) {\n            int pos, val;\n            scanf(\"%d %d\", &pos, &val);\n            auto it = aset.find(a[pos - 1]);\n            auto nxt = it, prev = it;\n            ++nxt; --prev;\n            if (it == aset.begin()) {\n                deltas.erase(deltas.find(*nxt - *it));\n            } else if (it == --aset.end()) {\n                deltas.erase(deltas.find(*it - *prev));\n            } else {\n                deltas.erase(deltas.find(*nxt - *it));\n                deltas.erase(deltas.find(*it - *prev));\n                deltas.insert(*nxt - *prev);\n            }\n            aset.erase(it);\n            aset.insert(val);\n            it = aset.find(val);\n            nxt = it, prev = it;\n            ++nxt; --prev;\n            if (it == aset.begin()) {\n                deltas.insert(*nxt - *it);\n            } else if (it == --aset.end()) {\n                deltas.insert(*it - *prev);\n            } else {\n                deltas.insert(*nxt - *it);\n                deltas.insert(*it - *prev);\n                deltas.erase(deltas.find(*nxt - *prev));\n            }\n            a[pos - 1] = val;\n            cout << *--aset.end() + *--deltas.end() << \" \";\n        }\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "math",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1863",
    "index": "A",
    "title": "Channel",
    "statement": "Petya is an administrator of a channel in one of the messengers. A total of $n$ people are subscribed to his channel, and Petya is not considered a subscriber.\n\nPetya has published a new post on the channel. At the moment of the publication, there were $a$ subscribers online. We assume that every subscriber always reads all posts in the channel if they are online.\n\nAfter this, Petya starts monitoring the number of subscribers online. He consecutively receives $q$ notifications of the form \"a subscriber went offline\" or \"a subscriber went online\". Petya does not know which exact subscriber goes online or offline. It is guaranteed that such a sequence of notifications could have indeed been received.\n\nPetya wonders if all of his subscribers have read the new post. Help him by determining one of the following:\n\n- it is impossible that all $n$ subscribers have read the post;\n- it is possible that all $n$ subscribers have read the post;\n- it is guaranteed that all $n$ subscribers have read the post.",
    "tutorial": "Let $p$ be the total number of + signs in the notification string. If $a + p < n$, then the answer is clearly \"NO\". Now let's look at the current number of users online. Initially there are $a$ of them. Each notification either increases this number by $1$, or decreases it by $1$. If at some moment of time the number of users online is $n$, then all users are online, thus, everyone must have read the post. The answer is \"YES\" in this case. Otherwise the answer is \"MAYBE\". Indeed, suppose that the number of users online never hits $n$, but $a + p \\ge n$. On the one hand, if the first $(n - a)$ notifications of the + type correspond to new users, then all subscribers will have read the post. On the other hand, a situation when the $n$-th user never log in is also possible.",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1863",
    "index": "B",
    "title": "Split Sort",
    "statement": "You are given a permutation$^{\\dagger}$ $p_1, p_2, \\ldots, p_n$ of integers $1$ to $n$.\n\nYou can change the current permutation by applying the following operation several (possibly, zero) times:\n\n- choose some $x$ ($2 \\le x \\le n$);\n- create a new permutation by:\n\n- first, writing down all elements of $p$ that are less than $x$, without changing their order;\n- second, writing down all elements of $p$ that are greater than or equal to $x$, without changing their order;\n\n- replace $p$ with the newly created permutation.\n\nFor example, if the permutation used to be $[6, 4, 3, 5, 2, 1]$ and you choose $x = 4$, then you will first write down $[3, 2, 1]$, then append this with $[6, 4, 5]$. So the initial permutation will be replaced by $[3, 2, 1, 6, 4, 5]$.\n\nFind the minimum number of operations you need to achieve $p_i = i$ for $i = 1, 2, \\ldots, n$. We can show that it is always possible to do so.\n\n$^{\\dagger}$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "For every $k$ such that $a_i = k$, $a_j = k + 1$ and $i > j$ we have to choose $x = k + 1$ at least once for these elements to be in the correct order. It is easy to see that if we choose all such $x = k + 1$ for all such $k$ exactly once in any order, we will get the identity permutation.",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1863",
    "index": "C",
    "title": "MEX Repetition",
    "statement": "You are given an array $a_1,a_2,\\ldots, a_n$ of \\textbf{pairwise distinct} integers from $0$ to $n$. Consider the following operation:\n\n- consecutively for each $i$ from $1$ to $n$ in this order, replace $a_i$ with $\\operatorname{MEX}(a_1, a_2, \\ldots, a_n)$.\n\nHere $\\operatorname{MEX}$ of a collection of integers $c_1, c_2, \\ldots, c_m$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $c$. For example, $\\operatorname{MEX}(0, 2, 2, 1, 4) = 3$ and $\\operatorname{MEX}(1, 2) = 0$.\n\nPrint the array after applying $k$ such operations.",
    "tutorial": "Append the initial array $a_1, \\ldots, a_n$ with $a_{n+1} = \\operatorname{MEX}(a_1, \\ldots, a_n)$. It is easy to see that $a_1, \\ldots, a_{n+1}$ is a permutation of $0, 1, \\ldots, n$. In this case setting $a_i = \\operatorname{MEX}(a_1, \\ldots, a_n)$ is basically equivalent $a_i = a_{n+1}$, but after this the new $\\operatorname{MEX}(a_1, \\ldots, a_n)$ is changed. In fact, it becomes equal to the old value of $a_i$, since this value is not now present in the array. In other words, performing the operation on $a_i$ is equivalent to swapping $a_i$ and $a_{n+1}$. Performing the operation on $i = 1, 2, \\ldots, n$ can be viewed as $n$ swaps. It means that the array changes from $[a_1, a_2, \\ldots, a_{n+1}]$ to $[a_{n+1}, a_1, a_2, \\ldots, a_n]$, i. e. we simply perform the cyclic shift to the right. To finish up the solution, first, calculate $a_{n+1} = \\operatorname{MEX}(a_1, \\ldots, a_n)$ (you can do so, for example, by setting $a_{n+1} = \\frac{n(n+1)}{2} - \\sum\\limits_{i=1}^{n} a_i$). Second, calculate $k \\% (n+1)$ and then perform the cyclic shift in $O(n)$.",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1863",
    "index": "D",
    "title": "Two-Colored Dominoes",
    "statement": "There is an $n\\times m$ board divided into cells. There are also some dominoes on this board. Each domino covers two adjacent cells (that is, two cells that share a side), and no two dominoes overlap.\n\nPiet thinks that this board is too boring and it needs to be painted. He will paint the cells of the dominoes black and white. He calls the painting beautiful if all of the following conditions hold:\n\n- for each domino, one of its cells is painted white and the other is painted black;\n- for each row, the number of black cells in this row equals the number of white cells in this row;\n- for each column, the number of black cells in this column equals the number of white cells in this column.\n\nNote that the cells that are not covered by dominoes are not painted at all, they are counted as neither black nor white.\n\nHelp Piet produce a beautiful painting or tell that it is impossible.",
    "tutorial": "Let's consider the requirement on the rows. Clearly, all horizontal dominoes (since each of them has $1$ black and $1$ white cell) do not influence the black-white balance for the rows. Thus, we are only interested in vertical dominoes. Consider the first row and the vertical dominoes that intersect this row. Their number has to be even, otherwise, the first row has an odd number of cells covered by dominoes and the solution is clearly impossible. But if there is an even number of such dominoes, we have to paint half of them black-white, and half of them white-black. What's more, it doesn't actually matter the exact order we paint them in, because vertical dominoes do not affect the columns' balance and we will not influence the balance of the second row anyway. So we can freely paint them however we like. The same logic applies for rows $2, \\ldots, n$. Now we turn to horizontal dominoes. In the first row, there once again has to be an even number of dominoes which intersect this column. And we can paint half them black-white, and half of them white-black, and it doesn't matter which exact way we choose. Do the same for columns $2, \\ldots, m$.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1863",
    "index": "E",
    "title": "Speedrun",
    "statement": "You are playing a video game. The game has $n$ quests that need to be completed. However, the $j$-th quest can only be completed at the beginning of hour $h_j$ of a game day. The game day is $k$ hours long. The hours of each game day are numbered $0, 1, \\ldots, k - 1$. After the first day ends, a new one starts, and so on.\n\nAlso, there are dependencies between the quests, that is, for some pairs $(a_i, b_i)$ the $b_i$-th quest can only be completed after the $a_i$-th quest. It is guaranteed that there are \\textbf{no circular dependencies}, as otherwise the game would be unbeatable and nobody would play it.\n\nYou are skilled enough to complete any number of quests in a negligible amount of time (i. e. you can complete any number of quests at the beginning of the same hour, even if there are dependencies between them). You want to complete all quests as fast as possible. To do this, you can complete the quests in any valid order. The completion time is equal to the difference between the time of completing the last quest and the time of completing the first quest in this order.\n\nFind the least amount of time you need to complete the game.",
    "tutorial": "First of all, assume that the first quest we complete is at the hour $x$. We can assume that $0\\leq x < k$, as increasing it by $k$ just shifts all the times by $k$. In this case one can greedily find the completion times for all the quests: essentially, for every quest $v$, if we know that the quests it depends on are completed at hours $c_1$, ..., $c_d$, then the quest $v$ cannot be completed earlier than $\\max(c_1, \\ldots, c_d)$. So if we define $f(x, y)$ to be the smallest $z\\geq x$ such that $z\\equiv y\\pmod{k}$, then the completion time of $v$ is $f(\\max(c_1, \\ldots, c_d), h_v)$. If the quest $v$ does not depend on anything, then, obviously, the time if simply $f(x, h_v)$. The problem is that we don't know which starting time $x$ is optimal. On the other hand, we know that it can be assumed to be from $[0, k)$. Also, there is no sense in $x$ not being $h_v$ for any quest $v$ without incoming dependencies. So we can do the following: first assume that $x = 0$ and find all the completion times for the quests, denote them by $c_i$. Then consequently increase $x$ until it becomes $k$. Sometimes $x$ becomes equal to some $h_v$ where $v$ is a quest that could theoretically be completed first. At these moments we know that the answer is no more than $\\max c_i - x$. When we increase $x$ again, such quests can no longer have $c_i = x$, and thus some values $c_i$ increase by some multiple of $k$. However, for $x = k$ all $c_i$ are exactly $k$ more than when $x = 0$. Therefore, each value of $c_i$ in this process increases exactly once and exactly by $k$. Now there are two ways to finish the solution. Sort all events of type \"some $c_i$, where quest $i$ doesn't have incoming dependencies, increase by $k$\". For each such event, we run DFS from such vertices to see if some the quests depending on them must also be completed $k$ hours later. One can see that this DFS will be run from each vertex exactly once throughout the process, thus resulting in $O(n + m)$ time complexity. When building all $c_i$ the first time, also find for each vertex $v$ the first $x$ when its $c_v$ must change. If we denote it with $w_v$ then it can be expressed as $\\max\\{w_u\\,\\colon\\,u\\to v, c_u + k > c_v\\}$. Then sort all events of type \"some $c_i$, where quest $i$ may or may not have incoming dependencies, increase by $k$\". In both approaches one can easily maintain $\\max c_i$ as this value can only increase.",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1863",
    "index": "F",
    "title": "Divide, XOR, and Conquer",
    "statement": "You are given an array of $n$ integers $a_1, a_2, \\ldots, a_n$.\n\nIn one operation you split the array into two parts: a non-empty prefix and a non-empty suffix. The value of each part is the bitwise XOR of all elements in it. Next, discard the part with the smaller value. If both parts have equal values, you can choose which one to discard. Replace the array with the remaining part.\n\nThe operations are being performed until the length of the array becomes $1$. For each $i$ ($1 \\le i \\le n$), determine whether it is possible to achieve the state when only the $i$-th element (with respect to the original numbering) remains.\n\nFormally, you have two numbers $l$ and $r$, initially $l = 1$ and $r = n$. The current state of the array is $[a_l, a_{l+1}, \\ldots, a_r]$.\n\nAs long as $l < r$, you apply the following operation:\n\n- Choose an arbitrary $k$ from the set $\\{l, l + 1, \\ldots, r - 1\\}$. Denote $x = a_l \\oplus a_{l + 1} \\oplus \\ldots \\oplus a_k$ and $y = a_{k + 1} \\oplus a_{k + 2} \\oplus \\ldots \\oplus a_{r}$, where $\\oplus$ denotes the bitwise XOR operation.\n- If $x < y$, set $l = k + 1$.\n- If $x > y$, set $r = k$.\n- If $x = y$, either set $l = k + 1$, or set $r = k$.\n\nFor each $i$ ($1 \\le i \\le n$), determine whether it is possible to achieve $l = r = i$.",
    "tutorial": "Let $s = a_l \\oplus a_{l + 1} \\oplus \\ldots \\oplus a_r$, $x = a_l \\oplus a_{l + 1} \\oplus \\ldots \\oplus a_k$, $y = a_{k + 1} \\oplus a_{k + 2} \\oplus \\ldots \\oplus a_{r}$. If $s$ is zero, than we can choose any $k$ and any side because $s = x \\oplus y = 0 \\implies x = y$. If $s$ is not zero we can choose such $k$ for the left side that the most significant bit of $s$ is the same as the most significant bit of $x$ because $y = s \\oplus x$ does not have this bit, and therefore less than $x$. Same for the right side. We will iterate over all subarrays in non-increasing order of length and will calculate two set of bits $mask\\_start_i$ and $mask\\_end_i$ for each position of array - bits, one of which must contain the XOR of subarray numbers to start/end at that position. To check that we can achieve $l$, $r$ we need to check that $s \\land mask\\_start_l > 0$ or $s \\land mask\\_end_r > 0$ or any segment can start/end in these positions, since there was a segment with zero XOR with such start/end. If we can achieve $[l; r]$ than: if $s \\neq 0$ add the most significant bit of $s$ to $mask\\_start_l$ and $mask\\_end_r$; if $s = 0$ remember that any subarray of shorter length can start/end at these positions. The time complexity is $O(n^2)$, the space complexity is $O(n)$.",
    "tags": [
      "bitmasks",
      "dp",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1863",
    "index": "G",
    "title": "Swaps",
    "statement": "You are given an array of integers $a_1, a_2, \\dots, a_n$ ($1 \\le a_i \\le n$). You can perform the following operation several (possibly, zero) times:\n\n- pick an arbitrary $i$ and perform swap$(a_i, a_{a_i})$.\n\nHow many distinct arrays is it possible to attain? Output the answer modulo $(10^9 + 7)$.",
    "tutorial": "Consider a directed graph with $n$ vertices, where for each vertex $i$ there is an edge $i\\to a_i$. This is a functional graph, that is, every vertex has exactly one edge outgoing from it. Let's see how our operations affect the graph. We will write $u\\to v$ to illustrate the fact that $a_u = v$. Call the operation $\\mathrm{swap}(a_i, a_{a_i})$ picking vertex $i$. We can assume that we never picked such $u$ that the operation didn't change the permutation, that is, $u\\to v\\to v$. We will mark some edges in the graph as bold. Initially no edge is bold. When we pick vertex $v$, one of the following can happen: If no bold edges pass into $v$, go along the bold edges until we can. Let's say the vertex we reached is $u$. Then mark the edge from $u$ bold. If $v$ has an incoming bold edge, do nothing. At every moment of time, the graph corresponds to the permutation in the following way: if $v$ has an incoming bold edge then $a_v = v$, otherwise, if $u$ is the vertex we reach by going from $v$ along the bold edges, and $u\\to w$, then $a_v = w$. Also, one can see that according to the algorithm of making edges bold no vertex ever has more than one incoming bold edge. It is clear that each valid subset of bold edges corresponds to a unique permutation. However, one can see that the same permutation can correspond to multiple subsets. In particular, for a component of the graph, if $a_v = v$ for all vertices of the cycle in this component, then the boldness of all edges outside the cycle is uniquely determined, but for the edges of the cycle any subset of these edges that doesn't include exactly one of them corresponds to this permutation. To avoid this uncertainty, we say that this permutation will correspond to the subset of bold edges where all the edges from the cycle are bold (this is an invalid subset, because there is no sequence of operations that would mark it bold). Now we want to calculate the number of possible subsets of bold edges. Each vertex can have either no incoming bold edges (there is $1$ way to do this) or any one of them can be bold ($\\mathrm{in}_v$ ways to do this for vertex $v$). So the answer could be just $\\prod_{v}(\\mathrm{in}_v + 1)$. However, since some of the configurations are invalid, we need to modify the answer. In particular, consider any cycle $c_1\\to\\ldots\\to c_k\\to c_1$. All excluded subsets of edges correspond to exactly one of $c_{i+1}$ having either no bold edge incoming, or any edge except $c_i\\to c_{i+1}$. Therefore, the number of ways to choose the bold edges among the ones incoming to this cycle is $\\prod_{i=1}^k(\\mathrm{in}_{c_i} + 1) - \\sum_{i=1}^k\\mathrm{in}_{c_i}.$ Thus, the final answer is $\\prod_{\\text{cycles}}\\left(\\prod_{i=1}^k(\\mathrm{in}_{c_i} + 1) - \\sum_{i=1}^k\\mathrm{in}_{c_i}\\right)\\cdot\\prod_{\\text{other }v}(\\mathrm{in}_v + 1).$",
    "tags": [
      "combinatorics",
      "dp",
      "graphs",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1863",
    "index": "H",
    "title": "Goldberg Machine 3",
    "statement": "There is a complete rooted binary tree, that is, a rooted tree in which each vertex has either $0$ or $2$ children. The root of the tree is vertex $1$. A node without children is called a leaf. Each leaf has a hunger value, we denote the hunger value of leaf $v$ by $h_v$.\n\nEach inner vertex of the tree has a selector pointing to one of the children of the vertex.\n\nThis tree accepts cookies. Before launching the process you can choose the initial state of each selector individually. The process is as follows:\n\n- Initially there are no cookies in vertices.\n- You insert cookies into the root one by one.\n- As long as the cookie is not in a leaf, it falls to the child defined by the selector in the current vertex. This selector then changes its state to the opposite one, i. e. it starts pointing to the other child of the vertex.\n- You stop inserting cookies when each leaf $v$ has at least $h_v$ cookies in it. In this case, we say that the tree is filled up.\n\nYou have $q$ queries. Each query changes the value of $h_v$ for some leaf $v$. You need to print $q + 1$ numbers, the $i$-th of them being the minimum number of cookies required to fill up the machine after $(i - 1)$ updates if you can pick any initial state for every selector. Since these numbers may be very large, print the answers modulo $998\\,244\\,353$.\n\nPlease note that you can choose the initial state of all selectors independently between queries. However, the queries themselves are not independent: when answering the $i$-th query, you should also consider the effect of queries $1, 2, \\ldots, i - 1$.",
    "tutorial": "Let's consider a dynamic programming approach: for leaves, set $dp_v = a_v$, and for an internal vertex $v$ with children $u$ and $w$, set $dp_v = 2 \\max(dp_u, dp_w)-[dp_u \\neq dp_w]$ we use an indicator notation $[\\ldots]$. Let $d_v = dp_v - 1$, then the update becomes $d_v = 2 \\max(d_u, d_w) + [d_u = d_w]$. Let $h_v$ denote the distance from the root to $v$, and $D_v = d_v \\cdot 2^{h_v}$. Then $D_v = \\max(D_u, D_w) + 2^{h_v} [D_u = D_w]$. Notice that the binary representation of $D_v$ contains at most $\\log_2 A + \\log_2 n$ ones ($A = \\max a_i$). This can be easily proven by induction: suppose the minimum size of a tree that can result in $D_v$ having $k$ ones is $f(k)$. Then, $f(k) = 1$ when $k \\le \\log_2 A$, and $f(k) \\ge 2f(k - 1)$ otherwise, since $D_v$ must be constructed from equal $Du$ and $Dw$ from independent subtrees. We'll maintain a set $S$ of pairs $(v, D)$, where $D$ is a lower bound on $D_v$. Initially, put pairs $(v,(a_v - 1)\\cdot 2^{h_v})$ into $S$ for all leaves with $a_v > 0$, and if there are $(v, D)$ and $(u, D)$ in $S$ ($v \\neq u$), put $(w, D + 2^{h_w})$ into $S$, where $w = \\text{lca}(v, u)$. The answer is $1 +$ the maximum $D$ among all pairs in $S$ (if $S$ is empty, the answer is obviously $0$). Start with an empty $S$ and add all the leaves to it. A new pair $(v, D)$ can create at most one new lca with pairs $(u, D)$, and at most one new pair $(w, D + 2^k)$, where $k$ is necessarily a new bit. The process of creating new pairs continues, but it will finish in $O(\\log A + \\log n)$ iterations since there cannot be more bits. Different $D$ values can be stored in a trie based on bit positions from most significant to least significant (or by some hashing), and vertex sets in the trie nodes can be stored in the order of entry time. To change $a_v$, remove the old pair from $S$ (similarly to adding) and add the new one. All together requires $O(\\log n \\cdot (\\log A + \\log n))$ operations.",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1863",
    "index": "I",
    "title": "Redundant Routes",
    "statement": "You are given a tree with $n$ vertices labeled $1, 2, \\ldots, n$. The length of a simple path in the tree is the number of vertices in it.\n\nYou are to select a set of simple paths of length at least $2$ each, but you cannot simultaneously select two distinct paths contained one in another. Find the largest possible size of such a set.\n\nFormally, a set $S$ of vertices is called a route if it contains \\textbf{at least two vertices} and coincides with the set of vertices of a simple path in the tree. A collection of distinct routes is called a timetable. A route $S$ in a timetable $T$ is called redundant if there is a different route $S' \\in T$ such that $S \\subset S'$. A timetable is called efficient if it contains no redundant routes. Find the largest possible number of routes in an efficient timetable.",
    "tutorial": "Let's call two paths adjacent if one can be obtained from the other by adding an edge to one end and removing an edge from the other end. Proposition. There exists an optimal solution in which each pair of adjacent paths is either simultaneously chosen or simultaneously not chosen. Proof. Consider an optimal solution that maximizes the total length of paths in it. Let's assume that in such a solution, we have taken some path $ab$, but its adjacent path $cd$ is not included (here, assume $a \\not\\in cd$ and $d \\not\\in ab$). Why can't we add $cd$? If $cd$ contains a shorter path, it must end at $d$ (since all other paths are also contained in $ab$). In that case, we can extend the shorter path $ed$ to $cd$, which contradicts the maximization of the sum of lengths. If $cd$ is contained within a longer path, it must start at $c$ (since all other paths are also contained in $ab$). In this case, we can extend $ab$. In the rooted tree, we'll call a class vertical if it contains at least one vertical path. To reduce the number of vertical classes, we'll root the tree by the midpoint of its diameter (if the diameter is of odd length, consider the root as an edge). Now, all vertical paths of the same length are equivalent (since a vertical path can always be moved to another subtree of the root). Thus, for each length, there is at most one vertical class. How do we determine if a path belongs to some vertical class? We'll attempt to greedily pull the path: first lower one end of the path to the deepest available vertex, then the other end, and so on. In the end, either the path becomes vertical or we encounter an obstacle of the following form: the endpoints are in non-intersecting subtrees of the same depth $h$, whose roots are at distance $d$ apart, and the path length is $h + d$. Moreover, any such pair of subtrees describes a non-vertical class of paths, and no other classes exist, as paths from a non-vertical class must hit such an obstacle. Note. A class doesn't necessarily consist of all paths between subtrees of length $h + d$. This is because an obstacle might exist lower down for some of these paths. Nonetheless, at least one representative for any pair of subtrees will definitely exist (for instance, the root of one subtree and the deepest leaf of the other). Let's define non-vertical classes with a pair of root vertices of subtrees $(v, u)$ (with the convention $tin(v) < tin(u)$), and define the class length as $L(v, u) = h + d$. We'll introduce a forest structure on non-vertical classes: a pair $(v, u)$ is an ancestor of $(v', u')$ if $v$ is an ancestor of $v'$ and $u$ is an ancestor of $u'$. All classes, together with this forest, can be constructed using DFS in $O(n^2)$ time, simultaneously traversing $v$ and $u$. Moreover, we can quickly compute the size of each such class. Let $S(v, u)$ denote the number of all paths of length $L(v, u)$ between subtrees $v$ and $u$. Then, the size of class $N(v, u)$ is $S(v, u) - \\sum_{(v', u')} N(v', u')$, where the summation is over all classes $(v', u')$ that are proper descendants of $(v, u)$ such that $L(v', u') = L(v, u)$. Thus, we need to compute all $S(v, u)$. If we compute this for each class in $O(h)$ time, the total time will be $O(n^2)$ (exercise for the reader). Which non-vertical classes can't be taken simultaneously? If between classes $a = (v, u)$ and $b = (v', u')$ neither is an ancestor of the other, then nested paths can't exist in them (due to the construction of the forest, there's a branching somewhere that's common to all paths). Proposition. Let class $a$ be an ancestor of class $b$. Then, a pair of nested paths between them can exist if and only if for all classes $c$ on the path between $a$ and $b$ (including $b$ but excluding $a$), $L(c) > L(a)$. Proof. Paths within $b$ cannot come out of subtrees $v', u'$. If $L(a) \\leq L(b)$, then a path of length $L(a)$ containing something from $b$ must also go between subtrees $v', u'$, but it can't extend beyond subtrees $v, u$ (since shorter paths from $b$ can't). Thus, it can't belong to $a$. Otherwise, if we attempt to pull a path of length $L(a)$ nested within $b$ upwards until encountering an obstacle at $a$, this can only happen if $a$ is the first significant obstacle. How do we include vertical classes? Clearly, we can take at most one vertical class. Using similar reasoning as above, if $a$ is a non-vertical class and $\\ell$ is the length of a vertical class, then $a$ can be taken with a vertical class if there are no classes $c$ among the ancestors of $a$ (including $a$) with $L(c) \\leq \\ell$. Constructing a bamboo structure out of all vertical classes (shorter classes on top) and attaching the roots from the forest of non-vertical classes at the bottom of this bamboo, the criterion remains the same as in the proposition. Now we can forget about the original problem and solve a new one: given a rooted tree, with numbers $L_v$ and $N_v$ assigned to each vertex, we need to select a set of vertices to maximize the sum of $N_v$, while satisfying the criterion. Consider the vertex $v$ with the minimum $L_v$ among all vertices (considering the deepest among such vertices, if there are several options). It's easy to see that: Vertices outside the subtree rooted at $v$ cannot prevent us from choosing vertices within the subtree rooted at $v$. If we choose $v$, we can't choose anything else in its subtree. Divide the set of all vertices $V$ into $T_v - v$ and $V - T_v$, where $T_v$ is the subtree rooted at $v$, and solve the problem independently for them. The final answer will be $ans(V - T_v) + \\max(N_v, ans(T_v))$. This process can be conveniently done in reverse, for instance, using DSU. It's also possible to carefully determine, during the forest construction, which components will merge, and solve the problem in $O(n^2)$ time using just bucket sort without any additional data structures or sorting.",
    "tags": [
      "constructive algorithms",
      "dp",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1864",
    "index": "A",
    "title": "Increasing and Decreasing",
    "statement": "You are given three integers $x$, $y$, and $n$.\n\nYour task is to construct an array $a$ consisting of $n$ integers which satisfies the following conditions:\n\n- $a_1=x$, $a_n=y$;\n- $a$ is \\textbf{strictly} increasing (i.e. $a_1 < a_2 < \\ldots < a_n$);\n- if we denote $b_i=a_{i+1}-a_{i}$ for $1 \\leq i \\leq n-1$, then $b$ is \\textbf{strictly} decreasing (i.e. $b_1 > b_2 > \\ldots > b_{n-1}$).\n\nIf there is no such array $a$, print a single integer $-1$.",
    "tutorial": "We use the following greedy construction: For all $i$ ($1<i<n$), set $a_i=a_{i+1}-(n-i)$. If $a_2-a_1 \\geq n-1$, we've found a solution, otherwise there is no solution. Proof. Assume there's a solution which includes an index $i$ ($1<i<n$) such that $a_{i+1}-a_i>n-i$. We can make $a_j:=a_j+\\Delta$ for all $j$ ($2 \\le j \\le i$), where $\\Delta=a_{i+1}-a_i-(n-i)$. After several processes like this, we get a solution the same as greedy construction gives. This leads to a contradiction.",
    "code": "#include <bits/stdc++.h>\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (int)(a).size()\n#define pb push_back\n#define mp make_pair\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\n\nint main() {\n\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int tt;\n    cin >> tt;\n    while (tt--) {\n        int x, y, n;\n        cin >> x >> y >> n;\n        vector<int> a(n);\n        a[0] = x, a[n - 1] = y;\n        int d = 1;\n        for (int i = n - 2; i >= 1; --i) {\n            a[i] = a[i + 1] - d;\n            ++d;\n        }\n        bool ok = true;\n        for (int i = 0; i + 1 < n; ++i) {\n            if (a[i + 1] <= a[i]) {\n                ok = false;\n            }\n        }\n        for (int i = 0; i + 2 < n; ++i) {\n            int p = a[i + 1] - a[i];\n            int q = a[i + 2] - a[i + 1];\n            if (p <= q) {\n                ok = false;\n            }\n        }\n        if (!ok) {\n            cout << \"-1\\n\";\n            continue;\n        }\n        for (int i = 0; i < n; ++i) {\n            cout << a[i] << \" \";\n        }\n        cout << \"\\n\";\n    }\n\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1864",
    "index": "B",
    "title": "Swap and Reverse",
    "statement": "You are given a string $s$ of length $n$ consisting of lowercase English letters, and an integer $k$. In one step you can perform \\textbf{any one} of the two operations below:\n\n- Pick an index $i$ ($1 \\le i \\le n - 2$) and swap $s_{i}$ and $s_{i+2}$.\n- Pick an index $i$ ($1 \\le i \\le n-k+1$) and reverse the order of letters formed by the range $[i,i+k-1]$ of the string. Formally, if the string currently is equal to $s_1\\ldots s_{i-1}s_is_{i+1}\\ldots s_{i+k-2}s_{i+k-1}s_{i+k}\\ldots s_{n-1}s_n$, change it to $s_1\\ldots s_{i-1}s_{i+k-1}s_{i+k-2}\\ldots s_{i+1}s_is_{i+k}\\ldots s_{n-1}s_n$.\n\nYou can make as many steps as you want (possibly, zero). Your task is to find the lexicographically \\textbf{smallest} string you can obtain after some number of steps.\n\nA string $a$ is lexicographically smaller than a string $b$ of the same length if and only if the following holds:\n\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "By the first kind of operation, we already know that every odd index (same for the even ones) can be swapped with each other freely. Therefore, let us write down the values of the indices modulo $2$. For example, if $n$ is $10$, the indices modulo $2$ are $[1,0,1,0,1,0,1,0,1,0]$. Now, we consider the two cases. When $k$ is odd. We can find out that after reversing any subarray of length $k$, the indices modulo $2$ do not change. So in this case, any series of the second operation is identical to some series of the first operation. Therefore, you should sort the odd indices and the even indices separately, and output the result of merging them into one string. When $k$ is even. Let us observe how we can swap two adjacent indices in this case. First, reverse $[i,i+k-1]$, and then reverse $[i+1,i+k]$. If we do this on $[1,0,1,0,1,0,1,0,1,0]$, assuming $i=1$ and $k=6$, the indices modulo $2$ turn into $[0,1,0,1,0,1,1,0,1,0]$, and then $[0,1,1,0,1,0,1,0,1,0]$. Using these two steps and some series of the first operation, we can see that we can swap any two adjacent indices as a result. And such a series of operation is always possible, as $k<n$. Therefore, we can sort the entire string, and output the result. Try to solve the problem if $n = k$ was allowed.",
    "code": "\n#include <bits/stdc++.h>\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (int)(a).size()\n#define pb push_back\n#define mp make_pair\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\n\nint main() {\n\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int tt;\n    cin >> tt;\n    while (tt--) {\n        int n, k;\n        cin >> n >> k;\n        string s;\n        cin >> s;\n        vector<char> odd, even;\n        for (int i = 0; i < n; ++i) {\n            if (i % 2 == 0) {\n                even.pb(s[i]);\n            } else {\n                odd.pb(s[i]);\n            }\n        }\n        sort(all(even));\n        sort(all(odd));\n        string ans1 = \"\";\n        for (int i = 0, j = 0; i < sz(even) || j < sz(odd); ++i, ++j) {\n            if (i < sz(even)) {\n                ans1 += even[i];\n            }\n            if (j < sz(odd)) {\n                ans1 += odd[i];\n            }\n        }\n        if (k % 2 == 0) {\n            sort(all(s));\n            cout << s << \"\\n\";\n            continue;\n        }\n        cout << ans1 << \"\\n\";\n    }\n\n}\n\n",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1864",
    "index": "C",
    "title": "Divisor Chain",
    "statement": "You are given an integer $x$. Your task is to reduce $x$ to $1$.\n\nTo do that, you can do the following operation:\n\n- select a divisor $d$ of $x$, then change $x$ to $x-d$, i.e. reduce $x$ by $d$. (We say that $d$ is a divisor of $x$ if $d$ is an positive integer and there exists an integer $q$ such that $x = d \\cdot q$.)\n\nThere is an additional constraint: you \\textbf{cannot} select the same value of $d$ \\textbf{more than twice}.\n\nFor example, for $x=5$, the following scheme is \\textbf{invalid} because $1$ is selected more than twice: $5\\xrightarrow{-1}4\\xrightarrow{-1}3\\xrightarrow{-1}2\\xrightarrow{-1}1$. The following scheme is however a valid one: $5\\xrightarrow{-1}4\\xrightarrow{-2}2\\xrightarrow{-1}1$.\n\nOutput any scheme which reduces $x$ to $1$ with at most $1000$ operations. It can be proved that such a scheme always exists.",
    "tutorial": "Let us divide the task into two steps, on each step we will use each divisor at most once. For convenience, let us denote $L$ as the largest value, such that $2^L \\le x$ holds. The two steps are as follows. Reduce $x$ to $2^L$. Given any integer $x$, we can see that its lowest significant bit is a divisor of $x$. If $x$ has more than one bit, we can repeatedly subtract the value corresponding to the lowest significant bit of $x$. When $x$ finally has only one bit, finish the first step. In this step, we have only used each significant bit of $x$ at most once. Reduce $2^L$ to $1$. We can find a way to reduce $2^L$ to $1$ by using each bit exactly once. Formally, if $k \\ge 0$, then $2^{k+1}-2^k=2^k$, and $2^k$ is a divisor of $2^{k+1}$. Thus, by subtracting $2^{L-1},2^{L-2},\\ldots,1$ in order, we reach $1$ from $2^L$ by using each bit from the $0$-th bit to the $(L-1)$-st bit exactly once. As a result, we can reduce $x$ to $1$ by using each power of $2$ at most twice (once from the first step, once from the second step). Since we used each bit at most twice, the time complexity for solving one test case is $O(\\log x)$. Due to the lenient constraints, some solutions with $O(\\sqrt x)$ time complexity should pass as well (as long as they fit into the $1000$ operations limit).",
    "code": "\n#include <bits/stdc++.h>\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (int)(a).size()\n#define pb push_back\n#define mp make_pair\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\n\nbool bit(int mask, int pos) {\n    return (mask >> pos) & 1;\n}\n\nint main() {\n\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int tt;\n    cin >> tt;\n    while (tt--) {\n        int x;\n        cin >> x;\n        int p;\n        vector<int> ans;\n        ans.pb(x);\n        for (int i = 0; ; ++i) {\n            if (bit(x, i)) {\n                if (x == (1 << i)) {\n                    p = i;\n                    break;\n                }\n                x -= (1 << i);\n                ans.pb(x);\n            }\n        }\n        while (p > 0) {\n            x -= (1 << (p - 1));\n            ans.pb(x);\n            --p;\n        }\n        cout << sz(ans) << \"\\n\";\n        for (int y : ans) {\n            cout << y << \" \";\n        }\n        cout << \"\\n\";\n    }\n\n}\n",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1864",
    "index": "D",
    "title": "Matrix Cascade",
    "statement": "There is a matrix of size $n \\times n$ which consists of 0s and 1s. The rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. The cell at the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$.\n\nAquaMoon wants to turn all elements of the matrix to 0s. In one step she can perform the following operation:\n\n- Select an arbitrary cell, let it be $(i, j)$, then invert the element in $(i, j)$ and also invert all elements in cells $(x, y)$ for $x > i$ and $x - i \\ge \\left|y - j\\right|$. To invert a value means to change it to the opposite: 0 changes to 1, 1 changes to 0.\n\nHelp AquaMoon determine the minimum number of steps she need to perform to turn all elements of the matrix to 0s. We can show that an answer always exists.",
    "tutorial": "Firstly, the first row has some elements that are $\\text{1}$ s and some elements that are $\\text{0}$ s. The elements that are $\\text{1}$ can only be turned into $\\text{0}$ by operating on the corresponding cell an odd number of times, and the elements that are $\\text{0}$ can only be turned into $\\text{0}$ by operating on the corresponding cell an even number of times. Two operations on the same cell are equivalent to no operation, so only one operation is performed on the corresponding cell of the element that is $\\text{1}$ in the first row. Thus, the operation on the first row is deterministic. Subsequent rows are affected by the operations in the first row, so it is sufficient to proceed to consider rows $2$ to $n$ in the same way. Now consider how to quickly deal with the effect of the preceding rows on the following rows. An operation on position $(x,y)$ will simultaneously invert all the elements from column $y-1$ to column $y+1$ in row $x+1$, and from column $y-2$ to column $y+2$ in row $x+2$, and son on. Thus, the elements being inverted are exactly the portion of the matrix sandwiched between lines passing through $(x,y)$ with slopes $1$ and $-1$. Let $b$ denote the effect of the line with slope $1$ from all predecing rows, and let $c$ denote the effect of the line with slope $-1$ from all preceding rows. % To optimize complexity, $b$, $c$ are both obtained using difference arrays to the current line using prefix sums to obtain the $b,c$ values at that time. After an operation on $(i,j)$, $b[i+1][j-1]$ is marked, and $c[i+1][j+2]$ is marked. Next, $b[i][j]$ inherits $b[i-1][j+1]$, and $c[i][j]$ inherits $c[i-1][j-1]$. For the current row, the effect of the previous rows is obtained by maintaining the prefix sums on $b$ and $c$. The total complexity is $O(n^2)$.",
    "code": "\n#include <bits/stdc++.h>\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (int)(a).size()\n#define pb push_back\n#define mp make_pair\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\n\nint main() {\n\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int tt;\n    cin >> tt;\n    \n    while (tt--) {\n        int n;\n        cin >> n;\n        vector<string> a(n);\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n        }\n        int ans = 0;\n        vector<vector<int> > val(n, vector<int>(n, 0));\n        vector<vector<int> > sum(n, vector<int>(n, 0));\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if (i == 0) {\n    \n                } else if (i == 1) {\n                    for (int k = max(0, j - 1); k <= min(j + 1, n - 1); ++k) {\n                        sum[i][j] ^= sum[i - 1][k];\n                    }\n                } else {\n                    if (j == 0) {\n                        sum[i][j] ^= sum[i - 2][j];\n                    } else {\n                        sum[i][j] ^= sum[i - 1][j - 1];\n                    }\n                    if (j == n - 1) {\n                        sum[i][j] ^= sum[i - 2][j];\n                    } else {\n                        sum[i][j] ^= sum[i - 1][j + 1];\n                    }\n                    sum[i][j] ^= sum[i - 2][j];\n                    sum[i][j] ^= val[i - 1][j];\n                }\n                if (sum[i][j] ^ (a[i][j] - '0')) {\n                    ++ans;\n                    sum[i][j] ^= 1;\n                    val[i][j] = 1;\n                }\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1864",
    "index": "E",
    "title": "Guess Game",
    "statement": "Carol has a sequence $s$ of $n$ non-negative integers. She wants to play the \"Guess Game\" with Alice and Bob.\n\nTo play the game, Carol will \\textbf{randomly} select two integer indices $i_a$ and $i_b$ within the range $[1, n]$, and set $a=s_{i_a}$, $b=s_{i_b}$. Please note that $i_a$ and $i_b$ may coincide.\n\nCarol will tell:\n\n- the value of $a$ to Alice;\n- the value of $b$ to Bob;\n- the value of $a \\mid b$ to both Alice and Bob, where $|$ denotes the bitwise OR operation.\n\nPlease note that Carol will \\textbf{not} tell any information about $s$ to either Alice or Bob.\n\nThen the guessing starts. The two players take turns making guesses, with Alice starting first. The goal of both players is to establish which of the following is true: $a < b$, $a > b$, or $a = b$.\n\nIn their turn, a player can do one of the following two things:\n\n- say \"I don't know\", and pass the turn to the other player;\n- say \"I know\", followed by the answer \"$a<b$\", \"$a>b$\", or \"$a=b$\"; then the game ends.\n\nAlice and Bob hear what each other says, and can use this information to deduce the answer. Both Alice and Bob are smart enough and only say \"I know\" when they are completely sure.\n\nYou need to calculate the expected value of the number of turns taken by players in the game. Output the answer modulo $998\\,244\\,353$.\n\nFormally, let $M = 998\\,244\\,353$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "First, let's analize a single game for fixed $a$, $b$, and how many turns it takes. Consider the binary representation of $a \\mid b$. We consider bits from highest to lowest. For bits with a value of $0$, we can ignore it because it firmly tells us that both bits of $a$ and $b$ are $0$. For convenience, we assume that all bits of $a \\mid b$ are $1$. In the first round, if the highest bit of $a$ is $0$, then Alice can immediately say that $a<b$. Otherwise, in the second round of the game, Bob knows that the highest bit of $a$ is not $0$. If the highest or the second highest bit of b is $0$, then Bob can immediately say that $a>b$. Otherwise, in the third round of the game, Alice knows that the highest and the second highest bits of $b$ are not $0$, and so on. Consider only set bits in $a \\mid b$. Let's enumerate these bits from highest to lowest. After some observation, we can conclude that: If $a<b$ and the $i$-th bit in $a$ is zero, then the answer is $i+1-(i\\%2 == 1)$; If $a=b$, then the answer is $k+1$, where $k$ is the number of set bits in $a \\mid b$; If $a>b$ and the $i$-th bit in $b$ is zero, then the answer is $i+(i\\%2 == 1)$. Now that we have a brute force algorithm for $O (n^2 \\log A)$, how can we optimize it? We can build a bit trie and traverse all nodes. We can easily calculate the number of $1$s that pass from a node to the root node, as well as the number of numbers prefixed with it and followed by $0$ (or $1$). Use this information to calculate the answer.",
    "code": "#include <bits/stdc++.h>\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (int)(a).size()\n#define pb push_back\n#define mp make_pair\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\n\nstruct node {\n    int to[2];\n    int cnt;\n    node() {\n        to[0] = to[1] = -1;\n        cnt = 0;\n    }\n};\n\nbool bit(int mask, int pos) {\n    return (mask >> pos) & 1;\n}\n\nvector<node> t;\n\nvoid add(int x) {\n    int v = 0;\n    for (int i = 29; i >= 0; --i) {\n        int b = bit(x, i);\n        if (t[v].to[b] == -1) {\n            t[v].to[b] = sz(t);\n            t.pb(node());\n        }\n        ++t[v].cnt;\n        v = t[v].to[b];\n    }\n    ++t[v].cnt;\n}\n\nconst int mod = 998244353;\n\nvoid mul(int& a, int b) {\n    ll c = ll(a) * b;\n    if (c >= mod) {\n        c %= mod;\n    }\n    a = c;\n}\n\nint binpow(int a, int n) {\n    int ans = 1;\n    while (n) {\n        if (n & 1) {\n            mul(ans, a);\n        }\n        mul(a, a);\n        n >>= 1;\n    }\n    return ans;\n}\n\nvoid solve(int v, int k, ll& ans) {\n    if (t[v].to[0] != -1 && t[v].to[1] != -1) {\n        ll i = k + 1;\n        ans += (2 * (i / 2) + 1) * t[t[v].to[0]].cnt * t[t[v].to[1]].cnt;\n        ans += 2 * ((i + 1) / 2) * t[t[v].to[0]].cnt * t[t[v].to[1]].cnt;\n    }\n    if (t[v].to[0] == -1 && t[v].to[1] == -1) {\n        ll i = k + 1;\n        ans += i * t[v].cnt * t[v].cnt;\n    }\n    if (t[v].to[0] != -1) {\n        solve(t[v].to[0], k, ans);\n    }\n    if (t[v].to[1] != -1) {\n        solve(t[v].to[1], k + 1, ans);\n    }\n}\n\nint main() {\n\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int tt;\n    cin >> tt;\n    while (tt--) {\n        t.clear();\n        t.pb(node());\n        int n;\n        cin >> n;\n        for (int i = 0; i < n; ++i) {\n            int a;\n            cin >> a;\n            add(a);\n        }\n        ll x = 0;\n        solve(0, 0, x);\n        int ans = x % mod;\n        mul(ans, binpow(n, mod - 2));\n        mul(ans, binpow(n, mod - 2));\n        cout << ans << \"\\n\";\n    }\n\n}\n",
    "tags": [
      "bitmasks",
      "data structures",
      "games",
      "math",
      "probabilities",
      "sortings",
      "strings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1864",
    "index": "F",
    "title": "Exotic Queries",
    "statement": "AquaMoon gives RiverHamster a sequence of integers $a_1,a_2,\\dots,a_n$, and RiverHamster gives you $q$ queries. Each query is expressed by two integers $l$ and $r$.\n\nFor each query independently, you can take any continuous segment of the sequence and subtract an identical non-negative value from all the numbers of this segment. You can do so multiple (possibly, zero) times. However, you may not choose two intersecting segments which are not included in one another. Your goal is to convert to $0$ all numbers whose initial \\textbf{value} was within the range $[l, r]$. You must do so in the minimum number of operations.\n\nPlease note that the queries are independent, the numbers in the array are restored to their initial values between the queries.\n\nFormally, for each query, you are to find the smallest $m$ such that there exists a sequence $\\{(x_j,y_j,z_j)\\}_{j=1}^{m}$ satisfying the following conditions:\n\n- for any $1 \\le j \\leq m$, $z_j \\ge 0$ and $1 \\le x_j \\le y_j \\leq n$ (here $[x_j, y_j]$ correspond to the segment of the sequence);\n- for any $1 \\le j < k \\le m$, it is true that $[x_j,y_j]\\subseteq[x_{k},y_{k}]$, or $[x_k,y_k]\\subseteq[x_{j},y_{j}]$, or $[x_j,y_j]\\cap[x_{k},y_{k}]=\\varnothing$;\n- for any $1 \\le i \\le n$, such that $l \\le a_i \\leq r$, it is true that $${\\large a_i = \\sum\\limits_{\\substack {1 \\le j \\le m \\\\ x_j \\le i \\le y_j}} z_j. }$$",
    "tutorial": "The final solution is irrelevant to Cartesian trees. First, we consider only the sequence of elements to be manipulated. We claim that it is optimal to operate on the whole sequence so that the minimum elements are all decreased to $0$, and then solve the problem on the segments separated by the $0$s recursively. A straightforward corollary of the claim is that two equal elements between which there are no smaller elements are handled in a single operation, so the final answer is $\\ell$ (the number of elements to be manipulated) minus the number of such adjacent pairs. Proof: Define $S(l, r)$ to be the answer for the segment $[l, r]$. Do induction on the length of the segment. If the first operation does not manipulate the whole segment, the segment will be separated into several independent parts by the first operation, for the non-inclusive operations cannot intersect, and the final answer, which is the sum of $S$ of the parts, will not be less than the initial answer according to the corollary, for some of the equal pairs are separated. Now the original problem is converted into a data structure task. Consider all adjacent equal pairs $(l, r)$, and $m$ is the maximum element between $(l, r)$, $m < a_l$. $(l, r)$ decrease the answer if and only if $m < L \\le a_l = a_r \\le R$, which can be easily calculated with a segment tree and sweeping lines.",
    "code": "\n#include <bits/stdc++.h>\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (int)(a).size()\n#define pb push_back\n#define mp make_pair\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\n\nvector<int> sum;\nint N;\n\nvoid updSumTree(int pos) {\n    for (pos += N; pos; pos >>= 1) {\n        ++sum[pos];\n    }\n}\n\nint getSumTree(int l, int r) {\n    int ans = 0;\n    for (l += N, r += N; l <= r; l = (l + 1) >> 1, r = (r &mdash; 1) >> 1) {\n        if (l & 1) {\n            ans += sum[l];\n        }\n        if (!(r & 1)) {\n            ans += sum[r];\n        }\n    }\n    return ans;\n}\n\nvector<int> t;\nint n;\n\nvoid updTree(int pos, int val) {\n    for (pos += n; pos; pos >>= 1) {\n        t[pos] = max(t[pos], val);\n    }\n}\n\nint getTree(int l, int r) {\n    int ans = 0;\n    for (l += n, r += n; l <= r; l = (l + 1) >> 1, r = (r &mdash; 1) >> 1) {\n        if (l & 1) {\n            ans = max(ans, t[l]);\n        }\n        if (!(r & 1)) {\n            ans = max(ans, t[r]);\n        }\n    }\n    return ans;\n}\n\nconst int nmax = 1e6 + 100;\n\nvector<int> pos[nmax];\nint cnt[nmax];\nint distinct[nmax];\n\nstruct query {\n    int l, r, id;\n    bool operator<(const query& other) const {\n        return l < other.l;\n    }\n};\n\nint main() {\n\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int q;\n    cin >> n >> q;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    \n    t.assign(4 * n, 0);\n    \n    for (int i = 0; i < n; ++i) {\n        pos[a[i]].pb(i);\n    }\n    \n    vector<pii> pts;\n    for (int x = 1; x <= n; ++x) {\n        for (int i = 0; i + 1 < sz(pos[x]); ++i) {\n            int lf = pos[x][i], rg = pos[x][i + 1];\n            ++lf, --rg;\n            if (lf > rg) {\n                continue;\n            }\n            int y = getTree(lf, rg);\n            //cout << x << \" \" << y << endl;\n            if (y == 0) {\n                continue;\n            }\n            pts.pb({n - y, x});\n        }\n        for (int p : pos[x]) {\n            updTree(p, x);\n        }\n    }\n    \n    cnt[0] = 0;\n    distinct[0] = 0;\n    for (int x = 1; x <= n; ++x) {\n        cnt[x] = cnt[x - 1] + sz(pos[x]);\n        distinct[x] = distinct[x - 1] + (!pos[x].empty());\n    }\n    \n    sort(all(pts));\n    int ptr = 0;\n    \n    vector<query> queries(q);\n    vector<int> ans(q);\n    for (int i = 0; i < q; ++i) {\n        int l, r;\n        cin >> l >> r;\n        queries[i] = {n - l, r, i};\n        ans[i] = distinct[r] - distinct[l - 1];\n    }\n    \n    sort(all(queries));\n    \n    N = n + 1;\n    sum.assign(2 * N, 0);\n\n\n    for (int i = 0; i < q; ++i) {\n        while (ptr < sz(pts) && pts[ptr].first <= queries[i].l) {\n            updSumTree(pts[ptr].second);\n            ++ptr;\n        }\n        ans[queries[i].id] += getSumTree(0, queries[i].r);\n    }\n    \n    for (int i = 0; i < q; ++i) {\n        cout << ans[i] << \"\\n\";\n    }\n\n}\n",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1864",
    "index": "G",
    "title": "Magic Square",
    "statement": "Aquamoon has a Rubik's Square which can be seen as an $n \\times n$ matrix, the elements of the matrix constitute a permutation of numbers $1, \\ldots, n^2$.\n\nAquamoon can perform two operations on the matrix:\n\n- Row shift, i.e. shift an entire row of the matrix several positions (at least $1$ and at most $n-1$) to the right. The elements that come out of the right border of the matrix are moved to the beginning of the row. For example, shifting a row $\\begin{pmatrix} a & b & c \\end{pmatrix}$ by $2$ positions would result in $\\begin{pmatrix} b & c & a \\end{pmatrix}$;\n- Column shift, i.e. shift an entire column of the matrix several positions (at least $1$ and at most $n-1$) downwards. The elements that come out of the lower border of the matrix are moved to the beginning of the column. For example, shifting a column $\\begin{pmatrix} a \\\\ b \\\\ c \\end{pmatrix}$ by $2$ positions would result in $\\begin{pmatrix} b\\\\c\\\\a \\end{pmatrix}$.\n\nThe rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. The cell at the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$.\n\nAquamoon can perform several (possibly, zero) operations, but she has to obey the following restrictions:\n\n- each row and each column can be shifted at most once;\n- each integer of the matrix can be moved at most twice;\n- the offsets of any two integers moved twice cannot be the same. Formally, if integers $a$ and $b$ have been moved twice, assuming $a$ has changed its position from $(x_1,y_1)$ to $(x_2,y_2)$, and $b$ has changed its position from $(x_3,y_3)$ to $(x_4,y_4)$, then $x_2-x_1 \\not\\equiv x_4-x_3 \\pmod{n}$ or $y_2-y_1 \\not\\equiv y_4-y_3 \\pmod{n}$.\n\nAquamoon wonders in how many ways she can transform the Rubik's Square from the given initial state to a given target state. Two ways are considered different if the sequences of applied operations are different. Since the answer can be very large, print the result modulo $998\\,244\\,353$.",
    "tutorial": "Theorem 1: After a row shift, all numbers moved are in the correct column. Proof 1: Suppose a number moved after a row shift is not in the correct column, if it is not in the correct row, it needs at least two more moves to its target position, otherwise it needs at least three more moves because the row cannot be shifted again. Also, after a column shift, all numbers moved are in the correct row. Theorem 2: If both row shift and column shift are performed, two rows cannot have equal shift distance. Proof 2: If row $i$ is shifted by $x$ and column $j$ is shifted by $y$, regardless of their order, then there is a number with offset $(y, x)$. If row $i_1$ and row $i_2$ are shifted by $x$ and column $j$ is shifted by $y$, regardless of their order, then there are two numbers with the same offset $(y, x)$ (if two number coincide, it was moved at least three times). In the same way, if both row shift and column shift are performed, two columns cannot have equal shift distance. If after a row shift, all numbers moved are in the correct column, we call such rows available. Similarly, if after a column shift, all numbers moved are in the correct row, we call such columns available. Theorem 3: If there is an available row and an available column at the same time, then there is no solution. Proof 3: If row $i$ can be shifted by $x$ and column $j$ can be shifted by $y$, the number in $(i, j)$ has offset $(y, x)$. Assume that the number in $(i, j)$ is moved to $(i+y, j)$ and then to $(i+y, j+x)$. Row $i+y$ is shifted by $x$, no other row can be shifted by $x$. Consider the number in $(i,j+1)$, it needs to be shifted by $x$ in some row, so it must be moved to row $i+y$ before row $i+y$ shifts. Then the numbers in $(i, j)$ and $(i+1, j)$ have the same offset $(y, x)$. Similarly, if the number in $(i, j)$ is moved to $(i, j+x)$ and then to $(i+y, j+x)$, there is no solution. We can use the following method to solve this problem: For each row and each column, check if it is available. If there are both available rows and available columns, there is no solution. If no rows or columns are available, the matrix is already equal to the target one, or there is no solution. If there are only available rows or available columns, their order doesn't matter, so if there $s$ choices, the answer should be multiplied by $s!$. Apply all available operations and check again. Total complexity: $O(n^3)$ or $O(n^2)$ if maintaining row/column offsets in each row/column.",
    "code": "#include <bits/stdc++.h>\n\n#define all(a) (a).begin(), (a).end()\n#define sz(a) (int)(a).size()\n#define pb push_back\n#define mp make_pair\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\n\nconst int mod = 998244353;\nconst int nmax = 600;\n\nint fact[nmax];\n\nint main() {\n\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    fact[0] = 1;\n    for (int i = 1; i < nmax; ++i) {\n        fact[i] = ll(fact[i - 1]) * i % mod;\n    }\n    \n    int tt;\n    cin >> tt;\n    \n    while (tt--) {\n        int n;\n        cin >> n;\n        vector<vector<int> > a(n, vector<int>(n));\n        set<int> seta;\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cin >> a[i][j];\n                seta.insert(a[i][j]);\n            }\n        }\n        assert(sz(seta) == n * n);\n    \n        vector<vector<int> > b(n, vector<int>(n));\n        set<int> setb;\n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                cin >> b[i][j];\n                setb.insert(b[i][j]);\n            }\n        }\n        assert(sz(setb) == n * n);\n        assert(seta == setb);\n        vector<int> vct;\n        for (int x : seta) {\n            vct.pb(x);\n        }\n    \n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                a[i][j] = lower_bound(all(vct), a[i][j]) - vct.begin();\n                b[i][j] = lower_bound(all(vct), b[i][j]) - vct.begin();\n            }\n        }\n    \n        vector<pii> posa(n * n);\n        vector<pii> posb(n * n);\n    \n        set<pii> off;\n    \n        for (int i = 0; i < n; ++i) {\n            for (int j = 0; j < n; ++j) {\n                posa[a[i][j]] = {i, j};\n                posb[b[i][j]] = {i, j};\n            }\n        }\n        bool valid = true;\n        for (int x = 0; x < n * n; ++x) {\n            pii p = posa[x], q = posb[x];\n            if (p.first != q.first && p.second != q.second) {\n                pii s = {(q.first - p.first + n) % n, (q.second - p.second + n) % n};\n                if (off.count(s)) {\n                    valid = false;\n                } else {\n                    off.insert(s);\n                }\n            }\n        }\n        if (!valid) {\n            cout << \"0\\n\";\n            continue;\n        }\n    \n        int cnt = 0;\n        ll ans = 1;\n    \n        while (a != b) {\n            vector<pii> rows;\n            for (int i = 0; i < n; ++i) {\n                int shift = posb[a[i][0]].second;\n                bool ok = true;\n                for (int j = 0; j < n; ++j) {\n                    int x = a[i][j];\n                    if (posb[x].second != (j + shift) % n) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok && shift) {\n                    rows.pb({i, shift});\n                }\n            }\n            vector<pii> cols;\n            for (int j = 0; j < n; ++j) {\n                int shift = posb[a[0][j]].first;\n                bool ok = true;\n                for (int i = 0; i < n; ++i) {\n                    int x = a[i][j];\n                    if (posb[x].first != (i + shift) % n) {\n                        ok = false;\n                        break;\n                    }\n                }\n                if (ok && shift) {\n                    cols.pb({j, shift});\n                }\n            }\n            if (cols.empty() && rows.empty()) {\n                valid = false;\n                break;\n            }\n            if (!(cols.empty() ^ rows.empty())) {\n                valid = false;\n                break;\n            }\n            if (!rows.empty()) {\n                cnt += sz(rows);\n                ans *= fact[sz(rows)];\n                ans %= mod;\n                for (pii p : rows) {\n                    int i = p.first;\n                    int shift = p.second;\n                    vector<int> v = a[i];\n                    for (int j = 0; j < n; ++j) {\n                        int x = v[j];\n                        a[i][(j + shift) % n] = x;\n                        posa[x] = {i, (j + shift) % n};\n                    }\n                }\n            } else {\n                cnt += sz(cols);\n                ans *= fact[sz(cols)];\n                ans %= mod;\n                for (pii p : cols) {\n                    int j = p.first;\n                    int shift = p.second;\n                    vector<int> v;\n                    for (int i = 0; i < n; ++i) {\n                        v.pb(a[i][j]);\n                    }\n                    for (int i = 0; i < n; ++i) {\n                        int x = v[i];\n                        a[(i + shift) % n][j] = x;\n                        posa[x] = {(i + shift) % n, j};\n                    }\n                }\n            }\n        }\n        if (!valid) {\n            cout << \"0\\n\";\n            continue;\n        }\n        cout << ans << '\\n';\n        // cout << cnt << \" \" << ans << \"\\n\";\n    }\n\n}\n",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1864",
    "index": "H",
    "title": "Asterism Stream",
    "statement": "Bogocubic is playing a game with amenotiomoi. First, Bogocubic fixed an integer $n$, and then he gave amenotiomoi an integer $x$ which is initially equal to $1$.\n\nIn one move amenotiomoi performs \\textbf{one} of the following operations with the same probability:\n\n- increase $x$ by $1$;\n- multiply $x$ by $2$.\n\nBogocubic wants to find the expected number of moves amenotiomoi has to do to make $x$ greater than or equal to $n$. Help him find this number modulo $998\\,244\\,353$.\n\nFormally, let $M = 998\\,244\\,353$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $y$ that $0 \\le y < M$ and $y \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Here is a basic $\\Theta(n)$ dp solution. Before that let $k = \\frac{1}{2}$. At the same time, because a special geometric sequence $f(x)=ak^{bx}$ will be frequently used next, it is defined as $\\{a,b\\}$. Let $f(x)$ be the expected number of moves needed if we start with $x$. Obviously, there is the following formula: $f(x)=\\begin{cases}0&n\\leqslant x\\\\k(f(x+1)+f(2x))+1&x<n\\end{cases}$ It's easy to see that for the interval $[n, 2n]$ value of $f(x)$ is $0$. If for an interval $[2l,2r]$, it can already be represented by the sum of several ${a,b}$, then it can be represented by a small number of new $\\{a,b\\}$ for all $f(x)$, where $x\\in[l,r]$ First there is $f(r)=kf(r+1)+kf(2r)+1$. So, $r-1$ can be represented as $f(r-1)=k^2f(r+1)+ kf(2r-2)+k^2f(2r)+k+1$. By analogy, one can get $f(r-x)=k^{x+1}f(r+1)+\\sum\\limits_{i=0}^xk^{i+1}f(2r-2x+2i)+\\sum\\limits_{i=0}^xk^i$ by substitution, it can be shown as $f(x)=k^{r-x+1}f(r+1)+\\sum\\limits_{i=0}^{r-x}k^{i+1}f(2x+2i)+\\sum\\limits_{i=0}^{r-x}k^i$ Because $\\{a,b\\}$ of the interval where $f(r+1)$ is already known, the value of $f(r+1)$ can be calculated quickly. So, the first term of $f(x)$ can be represented as below: $k^{r-x+1}f(r+1)=k^{r+1}f(r+1) \\cdot k^{-x}=\\{k^{r+1}f(r+1),-1\\}$ Then the last term of $f(x)$, $\\sum\\limits_{i=0}^{r-x}k^i$ is sum of an ordinary geometric sequence. So, after applying the formula it can represented as $\\{2,0\\}+\\{-k^r,-1\\}$. For the second term $\\sum\\limits_{i=0}^{r-x}k^{i+1}f(2x+2i)$, it has been assumed that $f(2x+2i)$ is $\\sum\\{a,b\\}$, so split it into the following form (the derivation process depends on $k^{2b+1}\\neq1$): $\\!\\begin{aligned} \\sum\\limits_{i=0}^{r-x}k^{i+1}f(2x+2i)&=\\sum\\limits_{i=0}^{r-x}k^{i+1}\\sum\\limits_f\\{a,b\\}\\\\ &=\\sum\\limits_{i=0}^{r-x}k^{i+1}\\sum\\limits_fak^{b(2x+2i)}\\\\ &=\\sum\\limits_f\\sum\\limits_{i=0}^{r-x}k^{i+1}ak^{b(2x+2i)}\\\\ &=\\sum\\limits_f\\sum\\limits_{i=0}^{r-x}ak^{2bx+1} \\cdot k^{i+2bi}\\\\ &=\\sum\\limits_fak^{2bx+1}\\sum\\limits_{i=0}^{r-x}(k^{2b+1})^i\\\\ &=\\sum\\limits_fak^{2bx+1}\\cdot\\frac{k^{(2b+1)(r-x+1)}-1}{k^{2b+1}-1}\\\\ &=\\sum\\limits_f\\frac{ak^{(2b+1)(n+1)+1}}{k^{2b+1}-1}\\cdot k^{-x}+\\frac{-ak}{k^{2b+1}-1}\\cdot k^{2bx}\\\\ &=\\sum\\limits_f\\{\\frac{ak^{(2b+1)(n+1)+1}}{k^{2b+1}-1},-1\\}+\\{\\frac{-ak}{k^{2b+1}-1},2b\\} \\end{aligned}$ Because of the obvious combination law $\\{a,b\\}+\\{c,b\\}=\\{a+c,b\\}$, the number of its geometric series is linear with the number of recursions. For $x\\in[n,2n], f(x)=0$, which can be represented as $f(x)=\\{0,0\\}$, so this recursive rule can always be used, Until the $x\\in[1,1]$ is obtained, to get the result. The complexity varies depending on the implementation $\\Theta(T\\log^3n)$ or $\\Theta(T\\log^2n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#pragma GCC optimize(\"Ofast\", \"inline\", \"-ffast-math\")\n#pragma GCC target(\"avx,sse2,sse3,sse4,mmx\")\n#define int long long\nconst int MOD = 998244353;\nint n, k;\nlong long power(int x, int p)\n{\n    if (p < 0)\n        return power(power(x, MOD - 2), -p);\n    int answer = 1;\n    x %= MOD;\n    while (p)\n    {\n        if (p & 1)\n            answer = answer * x % MOD;\n        x = x * x % MOD;\n        p >>= 1;\n    }\n    return answer;\n}\nvoid Delta()\n{\n    cin >> n;\n    k = power(2, MOD - 2);\n    int l = n, r = max(1ll, (n - 1) * 2), n0 = 0, s;\n    vector<int> Q;\n    while (l > 1)\n    {\n        vector<int> P;\n        l = (l + 1) / 2;\n        r /= 2;\n        s = n0;\n        for (int i = 0, t = k - 1; i < (int)Q.size(); ++i)\n        {\n            s = (s + Q[i] * power(power(k, -(1ll << i)), r + 1)) % MOD;\n            t = t * t % MOD;\n        }\n        P.push_back(((power(k, r + 1) * s - power(k, r)) % MOD + MOD) % MOD);\n        for (int i = 0; i < (int)Q.size(); ++i)\n        {\n            P[0] += power(power(k, 1 - (1ll << (i + 1))) - 1, MOD - 2) * Q[i] % MOD * power(power(k, 1 - (1ll << (i + 1))), r + 1) % MOD * k % MOD;\n            P.push_back(((MOD - Q[i] * k % MOD * power(power(k, 1 - (1ll << (i + 1))) - 1, MOD - 2) % MOD) % MOD + MOD) % MOD);\n        }\n        P[0] += (MOD - n0) * power(k, r + 1) % MOD;\n        for (int &i : P)\n            i %= MOD;\n        Q = P;\n        n0 += 2;\n    }\n    s = n0;\n    for (int i = 0, t = k - 1; i < (int)Q.size(); ++i)\n    {\n        s = (s + Q[i] * power(power(k, -(1ll << i)), 1)) % MOD;\n        t = t * t % MOD;\n    }\n    cout << s << endl;\n}\nsigned main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int T;\n    cin >> T;\n    while (T--)\n        Delta();\n}\n\n",
    "tags": [
      "dp",
      "math",
      "matrices"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1864",
    "index": "I",
    "title": "Future Dominators",
    "statement": "Dhruvil and amenotiomoi are sitting in different countries and chatting online. Initially, amenotiomoi has an empty board of size $n \\times n$, and Dhruvil has a sequence of integers $1, 2, \\ldots, n^2$, each number occurring exactly once. The numbers may be placed in the cells of the board, each cell is either empty or contains exactly one number.\n\nThe current state of the board is called \\textbf{good}, if there is a way of placing the remaining numbers in empty cells so that all numbers except $1$ have a neighbor with a smaller value. Two cells are neighbors if they share an edge.\n\nThe rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. The cell at the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$.\n\nTo chat, amenotiomoi asks $q$ queries to Dhruvil. Each time he provides Dhruvil with an empty cell $(x, y)$. Dhruvil has to place one of the remaining numbers in this cell so that the board is still good. Among all ways to do this, he chooses the largest possible number he can place and sends this number to amenotiomoi as the answer to the query.\n\nSince amenotiomoi knows the correct answer every time, he tells Dhruvil $(x \\oplus k,y \\oplus k)$ instead of $(x, y)$, where $k$ is the answer for the previous query. If amenotiomoi is sending the first query, he considers $k = 0$. Each time Dhruvil has to decode the query and send the answer to amenotiomoi. Here $\\oplus$ denotes the bitwise XOR operation.\n\nHelp Dhruvil reply to all amenotiomoi's queries.",
    "tutorial": "This problem is based on a method of online edge deletion and querying connectivity of a planar graph. Firstly, if this vertex is not an articulation point, it will not cause any change in connectivity. Therefore, the algorithm needs to determine whether a certain vertex is an articulation point. Thinking about using a data structure called union-find to keep track of the deleted points, we can identify a clear condition: if a vertex has two neighbors with the same union-find value among its $8$-connected neighbors, then it becomes an articulation point. This is easy to understand: When the values in the union-find are the same, it means there's a loop forming, and this messes up how things are connected inside and outside the loop. But if all the values in the union-find are different, no loops will form, and we can find a way to connect these points to each other. For points which are not articulation points, the greedy way to do it is to put the biggest number in the component of points that are already connected. This helps keep things organized and efficient. Now, let's think about the case of articulation points. If we've already decided to put a $1$ in the connected group before the articulation point, it's pretty clear that, in order to get the largest overall value, we should put the $1$ in the smallest connected component. And the remaining connected components will then share the largest value. In other words, when we pick the largest number for one component, the largest numbers for the other components will decrease at the same time. If we're sure that a particular component won't have the number $1$ placed in it, then the point we're looking at can only hold the value which is one more than the maximum value in the connected component formed by removing this point. It might sound a bit complicated, but I'll show you a picture to make it clearer. In simpler words, the value we put in that point is fixed. It's just the right amount to make sure it matches the sum of all the values in the connected group above it, instead of picking the smallest group. To make this work, we have to keep track of where the smallest value is located inside that connected component. The method we discussed is quite slow, around $O(n^3)$. Now, let's talk about how to make it much faster, around $O(n^2 log n)$. Firstly, for every cell, we keep a pointer that points to the information about its connected component. So, whenever we update any cell, the entire connected component gets updated automatically. When dealing with articulation points, it's important to quickly update the pointer information. One effective way is to use a clever merging technique. This involves simultaneously performing a breadth-first search on multiple connected components. If only one connected component remains incomplete in the search, we immediately stop all calculations. One of the things we need to do is to launch the BFS from the new connected components which arise after fixing a certain cell. In particular, we don't want to launch two parallel BFS which start in different cells but sooner or later are merged into one component. So among the $4$ side-neighbors of the cell being fixed, we need to segregate them based on the remaining connectivity, considering the removal of the current cell. To facilitate this segregation, we examine the 8 corner- or side-neighbors and analyze their DSU values. For instance, if all these DSU values are distinct from each other, it implies that the empty neighboring cells belong to a unified component. Conversely, if certain DSU values occur multiple times, it signifies the existence of a planar cycle that becomes linked through the cell being fixed. Consequently, cells within and outside this cycle must be assigned to separate connected components. To manage this, we iterate through pairs of $8-$neighbors sharing the same DSU value and classify the $4-$neighbors into those situated within the cycle and those outside it. During the pointer update process, we handle smaller connected components by updating their pointers in a straightforward manner. For larger connected components, we retain their original pointers and make necessary adjustments. It's easy to show that this approach updates pointers efficiently (each time a connected group is encountered in the search, its size at least doubles). This helps us achieve a time complexity of $O(n^2 log n)$. Next, we also need to determine whether two cells are part of the same connected component. This is necessary for calculating the situation represented in the previous image. This step is quite simple because we ensured earlier that pointers of different connected components are always different. So, all we need to do is compare the pointer values to check if two cells belong to the same connected component. For the connected components that share the largest value, there are several ways to handle them. One approach is to use the *int data type for the maximum value, so changing one value directly changes the shared value. Another method is to use a vector to store the pointers that share the value, and when updating, you iterate through this vector to update them. It's easy to prove that the maximum shared values can only exist in a maximum of $O(1)$ components simultaneously. This is because they only arise when cutting an articulation point in a connected component where the value is not $1$, and these components cannot merge together. So, the total time complexity will be $O(n^2logn)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#pragma GCC optimize(\"Ofast\",\"inline\",\"-ffast-math\")\n#pragma GCC target(\"avx,sse2,sse3,sse4,mmx\")\nstruct node {\n   int mx,sz;bool bg;\n   pair<int,int> mn;\n   vector<node*> cp;\n   void cln(){for(node* i:cp)i->cp.erase(find(i->cp.begin(),i->cp.end(),this));cp.clear();}\n   void fresh() {\n      if(!bg) return;\n      bg=false;int sum=0;node* lt=nullptr;\n      for(node* i:cp)if(i->bg){lt=i;sum++;}\n      if(sum==1){lt->mx=lt->sz;lt->bg=false;lt->cln();}\n   }\n   ~node(){cln();}\n};\nint prevAns;\npair<int,int> fa[1002][1002];\npair<int,int> getfa(pair<int,int> x) {\n   if(fa[x.first][x.second]==x) return x;\n   return fa[x.first][x.second]=getfa(fa[x.first][x.second]);\n}\nvoid merge(pair<int,int> x,pair<int,int> y) {\n   pair<int,int> t=getfa(x);\n   fa[t.first][t.second]=getfa(y);\n}\n\nint n,q;\nnode* bk[1002][1002];\nbool vis[1002][1002];\nvector<pair<int,int>> dxy={{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}},xy={{-1,0},{0,1},{1,0},{0,-1}};\nvoid Delta() {\n   cin >> n >> q;\n   bk[1][1]=new node{n*n,n*n,false,{0,0},{}};\n   for(int i=0;i<=n+1;++i)\n      for(int j=0;j<=n+1;++j) {\n         fa[i][j]={i,j};\n         if(i==0||j==0||i==n+1||j==n+1) {\n            fa[i][j]={0,0};\n            vis[i][j]=true;\n            bk[i][j]=nullptr;\n         } else {\n            bk[i][j]=bk[1][1];\n            vis[i][j]=false;\n         }\n      }\n   prevAns=0;\n   while(q--) {\n      int x,y,cnt=1;cin >> x >> y;\n      x^=prevAns;\n      y^=prevAns;\n      pair<int,int> Q[8];\n      int P[4]={0,0,0,0};\n      for(int i=0;i<8;++i)\n         Q[i]=getfa({x+dxy[i].first,y+dxy[i].second});\n      for(int i=0;i<8;++i)\n         for(int j=1;j<8;++j)\n            if(Q[i]==Q[(i+j)%8]) {\n               cnt++;\n               for(int k=(i+1)%8;k!=(i+j)%8;k=(k+1)%8)\n                  if(k%2==1)\n                     P[k/2]+=1ll<<cnt;\n               break;\n            }\n      vis[x][y]=true;\n      for(pair<int,int> i:dxy)\n         if(vis[x+i.first][y+i.second])\n            merge({x,y},{x+i.first,y+i.second});\n      bk[x][y]->fresh();\n      if((P[0]&P[1]&P[2]&P[3])==max({P[0],P[1],P[2],P[3]})) {\n         prevAns=bk[x][y]->mx;\n         cout << prevAns << ' ';\n         bk[x][y]->mx--;bk[x][y]->sz--;\n         for(node* i:bk[x][y]->cp) i->mx--;\n         if(bk[x][y]->sz==0) delete bk[x][y];\n      } else {\n         vector<pair<int,int>> s[4];\n         queue<pair<int,int>> q[4];\n         pair<int,int> id[4];\n         int cnt,dc=0;\n         {\n            vector<int> R;\n            for(int i=0;i<4;++i) R.push_back(P[i]);\n            sort(R.begin(),R.end());\n            R.resize(unique(R.begin(),R.end())-R.begin());\n            cnt=R.size();\n            for(int i=0;i<4;++i)\n               P[i]=lower_bound(R.begin(),R.end(),P[i])-R.begin();\n         }\n         for(int i=0;i<cnt;++i) {\n            for(int j=0;j<4;++j)\n               if(P[j]==i&&!vis[x+xy[j].first][y+xy[j].second]) {\n                  id[i]={x+xy[j].first,y+xy[j].second};\n                  if(!vis[id[i].first][id[i].second]) {\n                     q[i].push(id[i]);\n                     s[i].push_back(id[i]);\n                     vis[id[i].first][id[i].second]=true;\n                     dc++;\n                  }\n                  break;\n               }\n         }\n         while(dc>1)\n            for(int i=0;i<4;++i)\n               if(q[i].size()!=0) {\n                  pair<int,int> t=q[i].front();q[i].pop();\n                  for(int j=0;j<4;++j) {\n                     pair<int,int> p={t.first+xy[j].first,t.second+xy[j].second};\n                     if(!vis[p.first][p.second]) {\n                        q[i].push(p);s[i].push_back(p);\n                        vis[p.first][p.second]=true;\n                     }\n                  }\n                  if(q[i].empty()) --dc;\n               }\n         vector<int> sm,bg;node* tp[4];\n         if(bk[x][y]->mx==bk[x][y]->sz) {\n            if(dc==1) {\n               for(int i=0;i<4;++i)\n                  if(!q[i].empty()) bg.push_back(i);\n                  else if(!s[i].empty()) sm.push_back(i);\n               for(int i:sm) {\n                  tp[i]=new node{bk[x][y]->mx,(int)s[i].size(),false,{x,y},{}};\n                  for(pair<int,int> j:s[i])\n                     bk[j.first][j.second]=tp[i];\n               }\n               for(int i:sm) {\n                  for(int j:sm)\n                     if(i!=j) tp[i]->cp.push_back(tp[j]);\n                  bk[x][y]->sz-=s[i].size();\n               }\n               prevAns=bk[x][y]->sz;\n               cout<< prevAns << ' ';\n               bk[x][y]->sz--;bk[x][y]->mx=bk[x][y]->sz;\n            } else {\n               int mxz=0;\n               for(int i=0;i<4;++i)\n                  if(!s[i].empty()) {\n                     sm.push_back(i);\n                     mxz=max(mxz,(int)s[i].size());\n                  }\n               prevAns=mxz+1;\n               cout << prevAns << ' ';\n               for(int i:sm) {\n                  tp[i]=new node{bk[x][y]->mx,(int)s[i].size(),(int)s[i].size()==mxz,{x,y},{}};\n                  for(pair<int,int> j:s[i])\n                     bk[j.first][j.second]=tp[i];\n               }\n               for(int i:sm)\n                  for(int j:sm)\n                     if(i!=j) tp[i]->cp.push_back(tp[j]);\n               delete bk[x][y];\n            }\n         } else {\n            vector<node*> ar;vector<int> lt,ult;\n            if(dc==1) {\n               int sult=1,ty=bk[x][y]->mx;\n               pair<int,int> pmn=bk[x][y]->mn;\n               bk[x][y]->mn={x,y};bk[x][y]->sz--;\n               for(int i=0;i<4;++i)\n                  if(!s[i].empty()) {\n                     if(!q[i].empty()) {\n                        bg.push_back(i);\n                        tp[i]=bk[x][y];\n                     }\n                     else {\n                        tp[i]=new node{bk[x][y]->mx,(int)s[i].size(),false,{x,y},{}};\n                        sm.push_back(i);\n                        bk[x][y]->sz-=(int)s[i].size();\n                        for(pair<int,int> j:s[i])\n                           bk[j.first][j.second]=tp[i];\n                     }\n                  }\n               pair<int,int> tmp=pmn;\n               for(pair<int,int> i:xy) {\n                  node* t=bk[i.first+tmp.first][i.second+tmp.second];\n                  if(t!=nullptr&&pair<int,int>{i.first+tmp.first,i.second+tmp.second}!=pair<int,int>{x,y}) {\n                     ar.push_back(t);\n                  }\n               }\n               vector<node*> cp=bk[x][y]->cp;\n               for(node* i:cp) i->cp.erase(find(i->cp.begin(),i->cp.end(),bk[x][y]));\n               bk[x][y]->cp.clear();\n               for(int i=0;i<4;++i) {\n                  if(!s[i].empty()) {\n                     if(id[i]==tmp||find(ar.begin(),ar.end(),bk[id[i].first][id[i].second])!=ar.end()) {\n                        tp[i]->mn=pmn;\n                        lt.push_back(i);\n                     } else {\n                        ult.push_back(i);\n                        sult+=tp[i]->sz;\n                     }\n                  }\n               }\n               for(int i:ult)\n                  for(int j:ult)\n                     if(i!=j) tp[i]->cp.push_back(tp[j]);\n               for(node* i:cp) {\n                  for(int j:lt) {\n                     i->cp.push_back(tp[j]);\n                     tp[j]->cp.push_back(i);\n                  }\n                  i->mx-=sult;\n               }\n               prevAns=ty-sult+1;\n               cout << prevAns << ' ';\n               for(int i:lt) {\n                  for(int j:lt)\n                     if(i!=j) tp[i]->cp.push_back(tp[j]);\n                  tp[i]->mx-=sult;\n               }\n            } else {\n               pair<int,int> pmn=bk[x][y]->mn;\n               int sult=1;\n               for(int i=0;i<4;++i)\n                  if(!s[i].empty()) {\n                     tp[i]=new node{bk[x][y]->mx,(int)s[i].size(),false,{x,y},{}};\n                     for(pair<int,int> j:s[i])\n                        bk[j.first][j.second]=tp[i];\n                  }\n               pair<int,int> tmp=bk[x][y]->mn;\n               for(pair<int,int> i:xy) {\n                  node* t=bk[i.first+tmp.first][i.second+tmp.second];\n                  if(t!=nullptr&&pair<int,int>{i.first+tmp.first,i.second+tmp.second}!=pair<int,int>{x,y})\n                     ar.push_back(t);\n               }\n               for(int i=0;i<4;++i)\n                  if(!s[i].empty()) {\n                     if(id[i]==tmp||find(ar.begin(),ar.end(),bk[id[i].first][id[i].second])!=ar.end()) {\n                        tp[i]->mn=pmn;\n                        lt.push_back(i);\n                     } else {\n                        ult.push_back(i);\n                        sult+=(int)s[i].size();\n                     }\n                  }\n               for(int i:ult)\n                  for(int j:ult)\n                     if(i!=j) tp[i]->cp.push_back(tp[j]);\n               for(node* i:bk[x][y]->cp) {\n                  for(int j:lt) {\n                     i->cp.push_back(tp[j]);\n                     tp[j]->cp.push_back(i);\n                  }\n                  i->mx-=sult;\n               }\n               for(int i:lt) {\n                  for(int j:lt)\n                     if(i!=j) tp[i]->cp.push_back(tp[j]);\n                  tp[i]->mx-=sult;\n               }\n               prevAns=bk[x][y]->mx-sult+1;\n               cout << prevAns << ' ';\n               delete bk[x][y];\n            }\n         }\n         for(int i=0;i<4;++i)\n            for(pair<int,int> j:s[i])\n               vis[j.first][j.second]=false;\n      }\n      bk[x][y]=nullptr;\n   }\n   set<node*> _;\n   for(int i=1;i<=n;++i)\n      for(int j=1;j<=n;++j)\n         _.insert(bk[i][j]);\n   for(node* i:_)\n      if(i!=nullptr) delete i;\n   cout << endl;\n}\nsigned main() {\n   ios_base::sync_with_stdio(0);\n   cin.tie(0);cout.tie(0);\n   int T;cin >> T;\n   while(T--) Delta();\n}\n",
    "tags": [
      "graphs",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1866",
    "index": "A",
    "title": "Ambitious Kid",
    "statement": "Chaneka, Pak Chanek's child, is an ambitious kid, so Pak Chanek gives her the following problem to test her ambition.\n\nGiven an array of integers $[A_1, A_2, A_3, \\ldots, A_N]$. In one operation, Chaneka can choose one element, then increase or decrease the element's value by $1$. Chaneka can do that operation multiple times, even for different elements.\n\nWhat is the minimum number of operations that must be done to make it such that $A_1 \\times A_2 \\times A_3 \\times \\ldots \\times A_N = 0$?",
    "tutorial": "In order to have the product of all elements be $0$, at least one element must be $0$. For each element $A_i$, the minimum number of operations to turn it into $0$ is $|A_i|$. Therefore, the minimum number of operations to turn at least one element into $0$ is the minimum value of $|A_i|$ out of all elements. Time complexity: $O(N)$",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1866",
    "index": "B",
    "title": "Battling with Numbers",
    "statement": "On the trip to campus during the mid semester exam period, Chaneka thinks of two positive integers $X$ and $Y$. Since the two integers can be very big, both are represented using their prime factorisations, such that:\n\n- $X=A_1^{B_1}\\times A_2^{B_2}\\times\\ldots\\times A_N^{B_N}$ (each $A_i$ is prime, each $B_i$ is positive, and $A_1<A_2<\\ldots<A_N$)\n- $Y=C_1^{D_1}\\times C_2^{D_2}\\times\\ldots\\times C_M^{D_M}$ (each $C_j$ is prime, each $D_j$ is positive, and $C_1<C_2<\\ldots<C_M$)\n\nChaneka ponders about these two integers for too long throughout the trip, so Chaneka's friend commands her \"Gece, deh!\" (move fast) in order to not be late for the exam.\n\nBecause of that command, Chaneka comes up with a problem, how many pairs of positive integers $p$ and $q$ such that $\\text{LCM}(p, q) = X$ and $\\text{GCD}(p, q) = Y$. Since the answer can be very big, output the answer modulo $998\\,244\\,353$.\n\nNotes:\n\n- $\\text{LCM}(p, q)$ is the smallest positive integer that is simultaneously divisible by $p$ and $q$.\n- $\\text{GCD}(p, q)$ is the biggest positive integer that simultaneously divides $p$ and $q$.",
    "tutorial": "For a prime $k$, let $f_k(w)$ be the exponent of $k$ in the factorisation of $w$. In particular, if the factorisation of $w$ does not contain $k$, then $f_k(w)=0$. We can obtain that for any prime $k$, it holds that: $f_k(X)=f_k(\\text{LCM}(p,q))=\\max(f_k(p),f_k(q))$ $f_k(Y)=f_k(\\text{GCD}(p,q))=\\min(f_k(p),f_k(q))$ For each prime $k$, there are three cases: If $f_k(X)<f_k(Y)$, then it is impossible to assign the exponents since $\\max(f_k(p),f_k(q))<\\min(f_k(p),f_k(q))$ cannot be satsified. If $f_k(X)=f_k(Y)$, then there is only one way to assign the exponents, which is $f_k(p)=f_k(q)=f_k(X)$. If $f_k(X)>f_k(Y)$, then there are two ways to assign the exponents, which are the following: $f_k(p)=f_k(X)$, $f_k(q)=f_k(Y)$ $f_k(p)=f_k(Y)$, $f_k(q)=f_k(X)$ $f_k(p)=f_k(X)$, $f_k(q)=f_k(Y)$ $f_k(p)=f_k(Y)$, $f_k(q)=f_k(X)$ This means, if there is at least one prime $k$ such that $f_k(X)<f_k(Y)$, the answer is $0$. Otherwise, the answer is $2$ to the power of the number of primes $k$ such that $f_k(X)>f_k(Y)$. To maintain the values of $f_k(X)$ and $f_k(Y)$, you can use two pointers, the map data structure, or other methods. Time complexity: $O(N)$",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1866",
    "index": "C",
    "title": "Completely Searching for Inversions",
    "statement": "Pak Chanek has a directed acyclic graph (a directed graph that does not have any cycles) containing $N$ vertices. Vertex $i$ has $S_i$ edges directed away from that vertex. The $j$-th edge of vertex $i$ that is directed away from it, is directed towards vertex $L_{i,j}$ and has an integer $W_{i,j}$ ($0\\leq W_{i,j}\\leq1$). Another information about the graph is that the graph is shaped in such a way such that each vertex can be reached from vertex $1$ via zero or more directed edges.\n\nPak Chanek has an array $Z$ that is initially empty.\n\nPak Chanek defines the function dfs as follows:\n\n\\begin{verbatim}\n// dfs from vertex i\nvoid dfs(int i) {\n// iterate each edge of vertex i that is directed away from it\nfor(int j = 1; j <= S[i]; j++) {\nZ.push_back(W[i][j]); // add the integer in the edge to the end of Z\ndfs(L[i][j]); // recurse to the next vertex\n}\n}\n\n\\end{verbatim}\n\nNote that the function does not keep track of which vertices have been visited, so each vertex can be processed more than once.\n\nLet's say Pak Chanek does dfs(1) once. After that, Pak Chanek will get an array $Z$ containing some elements $0$ or $1$. Define an inversion in array $Z$ as a pair of indices $(x, y)$ ($x < y$) such that $Z_x > Z_y$. How many different inversions in $Z$ are there if Pak Chanek does dfs(1) once? Since the answer can be very big, output the answer modulo $998\\,244\\,353$.",
    "tutorial": "Note that during the entire process, each time we do dfs(x) for the same value of $x$, the sequence of values appended to the end of $Z$ is always the same. So, for each vertex $x$, we want to obtain some properties about the sequence of values that will be appended if we do dfs(x). Since we want to calculate the number of inversions in a sequence of $0$ and $1$ elements, for each $x$, we want to calculate: $f_0[x]$: the number of $0$ elements appended. $f_1[x]$: the number of $1$ elements appended. $\\text{inv}[x]$: the number of inversions completely within the sequence appended. Then, we can solve the problem using dynamic programming on directed acyclic graph. For a vertex $x$, we iterate each vertex $y$ that it is directed towards (following the order given in the input). If the integer in the current edge is $w$, then we temporarily add $f_w[y]$ by $1$ and if $w=1$, then we temporarily add $\\text{inv}[y]$ by $f_0[y]$. Then, we do the following transitions: Add $\\text{inv}[x]$ by $\\text{inv}[y]+f_1(x)\\times f_0(y)$. Add $f_0[x]$ by $f_0[y]$. Add $f_1[x]$ by $f_1[y]$. The answer is $\\text{inv}[1]$. Time complexity: $O(N+\\sum S)$",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1866",
    "index": "D",
    "title": "Digital Wallet",
    "statement": "There are $N$ arrays, each array has $M$ positive integer elements The $j$-th element of the $i$-th array is $A_{i,j}$.\n\nInitially, Chaneka's digital wallet contains $0$ money. Given an integer $K$. Chaneka will do $M-K+1$ operations. In the $p$-th operation, Chaneka does the following procedure:\n\n- Choose any array. Let's say Chaneka chooses the $x$-th array.\n- Choose an index $y$ in that array such that $p \\leq y \\leq p+K-1$.\n- Add the value of $A_{x, y}$ to the total money in the wallet.\n- Change the value of $A_{x, y}$ into $0$.\n\nDetermine the maximum total money that can be earned!",
    "tutorial": "First, notice that since the initial value of all elements are positive, it is always optimal to always choose an element that has not been chosen before in each operation. Let's look at the $N$ arrays as a grid of $N$ rows and $M$ columns. We can solve this problem by iterating each column from left to right and using dynamic programming. Define the following: $\\text{dp}[i][j]$: the maximum money Chaneka can earn by only taking the elements of the first $i$ columns in $j$ operations. When we iterate a new column $i$, we can choose to choose $c$ elements in that column for some value $c$ ($0\\leq c\\leq N$). If we choose to choose $c$ elements in that column, it is always the most optimal to choose the $c$ biggest elements in that column. Notice that if we only consider the first $i$ columns, in the optimal strategy, we must do a minimum of $i-K+1$ operations and a maximum of $i$ operations. So there are only a maximum of $K$ different values of $j$ we need to consider when calculating all values of $\\text{dp}[i][j]$ for each new column $i$. For each $\\text{dp}[i][j]$, there are only $N+1$ possibilities for the number of elements we choose in column $i$, and each of them can be handled in $O(1)$. Time complexity: $O(NMK)$",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1866",
    "index": "E",
    "title": "Elevators of Tamem",
    "statement": "There is a building named Taman Membeku (shortened as Tamem). The building has $N$ floors numbered from $1$ to $N$ from bottom to top. The only way to move between floors in the building is to use elevators. There are $3$ elevators available in Tamem, namely elevators $1$, $2$, and $3$.\n\nPak Chanek works as an elevator operator in Tamem. Pak Chanek will work for $Q$ days. Initially, each elevator is in floor $1$ and all elevators are on. On each day, exactly one of the following will happen:\n\n- 1 x y – There is a person currently in floor $x$ who wants to go to floor $y$. ($1\\leq x,y\\leq N$; $x\\neq y$)\n- 2 p – Elevator $p$ changes state \\textbf{at the start of the day}. If previously it is on, then it will turn off. If previously it is off, then it will turn on. ($1\\leq p\\leq3$)\n\nFor each day, Pak Chanek can control the movement of all elevators as he pleases. However, for each day where there is a person currently in floor $x$ who wants to go to floor $y$, among all elevator movements done by Pak Chanek, the following must happen:\n\n- One elevator moves to floor $x$.\n- The person gets into the elevator.\n- The elevator moves to floor $y$.\n- The person gets out of the elevator.\n\nFor each day, Pak Chanek can only move the elevators that are currently on. Note that, since a change in state happens at the start of the day, this means that an elevator that turns off on some day starts becoming unusable from that day itself. Conversely, an elevator that turns on on some day starts becoming usable from that day itself.\n\nIt is known that the electricity fee for each day is different. More specifically, on the $j$-th day, the fee needed to move one elevator up or down by one floor is $A_j$.\n\nFrom the start, Pak Chanek already knows the electricity fees and the sequence of events that will happen on the $Q$ days, so Pak Chanek can operate the elevators strategically. What is the minimum possible electricity fee to fulfill all needs of the people who want to move between floors in Tamem? Note: in the end, each elevator does not have to go back to floor $1$.",
    "tutorial": "First, let's solve the problem if there are no events of type $2$. We can solve this problem using dynamic programming. First, define: $\\text{enter}[e]$: the initial floor of the person in the $e$-th event. $\\text{exit}[e]$: the desired floor of the person in the $e$-th event. Then, define $\\text{dp}[i][j][k]$ as the minimum electricity fee if: Elevator $1$ last moved at the $i$-th event (last at floor $\\text{exit}[i]$). Elevator $2$ last moved at the $j$-th event (last at floor $\\text{exit}[j]$). Elevator $3$ last moved at the $k$-th event (last at floor $\\text{exit}[k]$). Let's say we have handled all events from the $1$-st to the ($e-1$)-th and now we want to handle the $e$-th event. This means the electricity fee for the the current condition is a value of $\\text{dp}[i][j][k]$ with $\\max(i,j,k)=e-1$ and we want to choose one elevator to handle the $e$-th event. If we choose elevator $1$, then it can move between the $i$-th day and $e$-th day to prepare for the person in the $e$-th event. So the minimum electricity fee for elevator $1$ to handle this is $|\\text{exit}[i]-\\text{enter}[e]|\\times\\min(A_i,A_{i+1},\\ldots,A_e)+|\\text{enter}[e]-\\text{exit}[e]|\\times A_e$. So we add that value with $\\text{dp}[i][j][k]$ for a candidate value of $\\text{dp}[e][j][k]$. We do a similar thing for elevators $2$ and $3$. Since we can precompute all values of $\\min(A_i,A_{i+1},\\ldots,A_e)$ naively, we can do the transition of each state in $O(1)$. In order to handle the events of type $2$, we can just write down the electricity fee for each elevator in each day. If that elevator is off on that day, we set the electricity fee of that elevator to be $\\infty$. Time complexity: $O(Q^3)$",
    "tags": [
      "dp"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1866",
    "index": "F",
    "title": "Freak Joker Process",
    "statement": "After the success of the basketball teams formed and trained by Pak Chanek last year (Basketball Together), Pak Chanek wants to measure the performance of each player that is considered as a superstar.\n\nThere are $N$ superstar players that have been trained by Pak Chanek. At the end of the season, some calculations will be made on the performance of the $N$ players using an international method. Each player has two values $A_i$ and $B_i$ where each represents the offensive and defensive value of that player.\n\nDefine $\\text{RankA}(i)$ as the offensive ranking of the $i$-th player, whose value is $c+1$ with $c$ here representing the number of $j$ ($1 \\leq j \\leq N$) such that $A_j>A_i$. Define $\\text{RankB}(i)$ as the defensive ranking of the $i$-th player, whose value is $c+1$ with $c$ here representing the number of $j$ ($1 \\leq j \\leq N$) such that $B_j>B_i$.\n\nDefine $\\text{RankOverall}(i)$ as the overall ranking of the $i$-th player, whose value is $c+1$ with $c$ here representing the number of $j$ ($1 \\leq j \\leq N$) such that $\\text{RankA}(j)+\\text{RankB}(j)<\\text{RankA}(i)+\\text{RankB}(i)$.\n\nDuring the next $Q$ days, exactly one event will happen on each day. Each event is one of the three following possibilities:\n\n- 1 k c – If $c$ is +, then $A_k$ increases by $1$. If $c$ is -, then $A_k$ decreases by $1$. ($1\\leq k\\leq N$; $c$ is + or -)\n- 2 k c – If $c$ is +, then $B_k$ increases by $1$. If $c$ is -, then $B_k$ decreases by $1$. ($1\\leq k\\leq N$; $c$ is + or -)\n- 3 k – Pak Chanek wants to know the value of $\\text{RankOverall}(k)$ at that moment. ($1\\leq k\\leq N$)",
    "tutorial": "We can solve this problem using square root decomposition. First we group the events into $\\sqrt Q$ blocks of sizes $\\sqrt Q$ and solve for each block independently. For the start of each block, we can calculate all values of $A$ and $B$ easily. Additionally, we can calculate: $\\text{biggerA}[x]$: the number of values of $A$ bigger than $x$. $\\text{biggerB}[x]$: the number of values of $B$ bigger than $x$. So, $\\text{RankA}(i)=\\text{biggerA}[A_i]+1$ and $\\text{RankB}(i)=\\text{biggerB}[B_i]+1$. Notice that if we increase or decrease a value of $A$ by $1$, only one value of $\\text{biggerA}$ changes. This means, the values of $\\text{RankA}$ that change are only the changed $A$ value itself and a group of players with the same value of $A$. The same thing also applies for $B$, $\\text{biggerB}$ and $\\text{RankB}$. For a single block, let's simulate the changes in $A$ and $B$ and keep track of which players change value at least once in the block. Additionally, keep track of which indices in $\\text{biggerA}$ and $\\text{biggerB}$ change at least once in the block and denote these indices as special values in each of $\\text{biggerA}$ and $\\text{biggerB}$. For a single block, let's group the players into several types: A blue player is a player that changes value at least once in the block. An orange player is a non-blue player that has both of its $A$ and $B$ values as special values in each of $\\text{biggerA}$ and $\\text{biggerB}$. A yellow player is a non-blue player that has exactly one of its $A$ and $B$ values as a special value in $\\text{biggerA}$ or $\\text{biggerB}$ respectively. The rest are white players. Notice that there are at most $\\sqrt Q$ blue players and at most $\\sqrt Q$ special values in each of $\\text{biggerA}$ and $\\text{biggerB}$. Before simulating the events in the block, we must do some precomputations. For orange and white players only, calculate the following: $\\text{smallerOverall}[x]$: the number of orange and white players with $\\text{RankA}+\\text{RankB}<x$. In order to maintain the value above, for orange players, calculate the following: $\\text{cnt}[i][j]$: the number of orange players whose values of $A$ and $B$ are the $i$-th and $j$-th special values in $\\text{biggerA}$ and $\\text{biggerB}$ respectively. For each special value in $\\text{biggerA}$, consider every yellow player that has that value of $A$. Notice that their values of $\\text{RankB}$ will not change in the block. So we can precompute their values of $\\text{RankB}$ and maintain them in a sorted array. We do a similar thing for the special values in $\\text{biggerB}$ and their yellow players. After doing all those precomputations, we simulate each event in the block. We do each change while maintaining all values of $A$, $B$, $\\text{biggerA}$, $\\text{biggerB}$, and $\\text{smallerOverall}$. To maintain $\\text{smallerOverall}$ while considering orange players, notice that we can update it naively using the values of $\\text{cnt}$ since there are at most $\\sqrt Q$ different values of $\\text{RankA}+\\text{RankB}$ of orange players that change in each change event (because there are at most $\\sqrt Q$ special values) and each change in $\\text{RankA}+\\text{RankB}$ only changes one value of $\\text{smallerOverall}$. For each query event asking $\\text{RankOverall}(k)$, do the following: Calculate $w=\\text{RankA}(k)+\\text{RankB}(k)$. For each blue player, calculate its $\\text{RankA}+\\text{RankB}$ and check if its value is smaller than $w$. For the orange and white players, just use the value of $\\text{smallerOverall}(w)$. For the yellow players, for each special value, use binary search to find the number of players with $\\text{RankA}+\\text{RankB}<w$ (use $\\text{RankB}<w-\\text{RankA}$ for the special values in $\\text{biggerA}$). The value of $\\text{RankOverall}(k)$ can be calculated using all values above. Notice that there is a log factor for sorting and binary search. Time complexity: $O((N+Q)\\sqrt{Q}\\log N)$ Note: There is a $O((N+Q)\\sqrt{Q})$ solution but the implementation sounds very heavy and tedious so it is not necessary to get accepted.",
    "tags": [
      "binary search",
      "data structures",
      "sortings"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1866",
    "index": "G",
    "title": "Grouped Carriages",
    "statement": "Pak Chanek observes that the carriages of a train is always full on morning departure hours and afternoon departure hours. Therefore, the balance between carriages is needed so that it is not too crowded in only a few carriages.\n\nA train contains $N$ carriages that are numbered from $1$ to $N$ from left to right. Carriage $i$ initially contains $A_i$ passengers. All carriages are connected by carriage doors, namely for each $i$ ($1\\leq i\\leq N-1$), carriage $i$ and carriage $i+1$ are connected by a two-way door.\n\nEach passenger can move between carriages, but train regulation regulates that for each $i$, a passenger that \\textbf{starts from carriage $i$} cannot go through more than $D_i$ doors.\n\nDefine $Z$ as the most number of passengers in one same carriage after moving. Pak Chanek asks, what is the minimum possible value of $Z$?",
    "tutorial": "Suppose we set the maximum number of passengers in the same carriage to be at most $Z$. If there is a valid strategy to fit the constraint, doing the same strategy for every maximum number of passengers in the same carriage that is greater than $Z$ is also possible. Hence, we can try to find the answer by doing binary search the answer. Note that a passenger from carriage $i$ can move to carriage $j$ as long as $i-D_i \\leq j \\leq i+D_i$. So for each initial carriage $i$, create a segment $[i-D_i,i+D_i]$. Suppose we try to find a valid strategy for moving the passengers with the constraint that the maximum number of passengers in the same carriage is at most $Z$. We can solve this greedily. Iterate the destination carriages from left to right to be filled with passengers. The initial carriages that can fill the current carriage are only the ones whose segments contain the current carriage. Note that it is always optimal to take passengers from the segments with the smallest right endpoints first. We take the passengers until the current destination carriage reaches $Z$ passengers or there are no more segments to take from. If there exists a non-empty segment of an initial carriage that cannot donate its passengers anywhere, then it is impossible. We can do something like line sweep and prioritise the segments based on their right endpoints using priority queue or other data structures. Time complexity: $O(N\\log N\\log\\max(A))$",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "flows",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1866",
    "index": "H",
    "title": "Happy Sets",
    "statement": "Define a set $A$ as a child of set $B$ if and only if for each element of value $x$ that is in $A$, there exists an element of value $x+1$ that is in $B$.\n\nGiven integers $N$ and $K$. In order to make Chaneka happy, you must find the number of different arrays containing $N$ sets $[S_1, S_2, S_3, \\ldots, S_N]$ such that: - Each set can only contain zero or more different integers from $1$ to $K$. - There exists a way to rearrange the order of the array of sets into $[S'_1, S'_2, S'_3, \\ldots, S'_N]$ such that $S'_i$ is a child of $S'_{i+1}$ for each $1\\leq i\\leq N-1$.\n\nPrint the answer modulo $998\\,244\\,353$.\n\nTwo sets are considered different if and only if there is at least one value that only occurs in one of the two sets.\n\nTwo arrays of sets are considered different if and only if there is at least one index $i$ such that the sets at index $i$ in the two arrays are different.",
    "tutorial": "First, consider all possible arrays $S'$ (the array of sets after rearranging). For each valid $S'$, we want to find the number of ways to shuffle it. The answer to the original problem is equal to the sum of ways to shuffle each possible $S'$, since for each shuffled $S'$ it can be shown that there is only one way to rearrange it into a valid $S'$. Notice that a valid $S'$ always consists of a group of empty sets and a group of pairwise distinct non-empty sets. That means, if there are $e$ empty sets, then there are $\\frac{N!}{e!}$ ways to shuffle $S'$. From the knowledge above, we can group all possible valid arrays $S'$ into groups based on the number of empty sets and count the number of valid arrays $S'$ in each group. Then for each group, multiply the number of valid arrays $S'$ by the number of ways to shuffle $S'$ for that number of empty sets, then add it to the answer. Now, define $f(e)$ as the number of valid arrays $S'$ with exactly $e$ empty sets. Define $g(e)$ as the number of valid arrays $S'$ with at least $e$ empty sets. We get that $f(e)=g(e)-g(e+1)$. Let's calculate $g(e)$. For an array of sets $S'$, we can consider it as a set of pairs $(p,x)$, where each pair $(p,x)$ denotes that $S'_p$ contains $x$. Notice that for some value $x$: $(N-1,x-1)$ can only exist if $(N,x)$ exists. $(N-2,x-2)$ can only exist if $(N-1,x-1)$ exists. $(N-3,x-3)$ can only exist if $(N-2,x-2)$ exists. And so on. Therefore, we can group the possible pairs into groups $[(N,x),(N-1,x-1),(N-2,x-2),\\ldots]$ and for every group, if it has $c$ pairs, then there are only $c+1$ configurations for that group (only the first $i$ pairs exist for every $0\\leq i\\leq c$). The total number of configurations is the product of $c+1$ for every group. Consider the size of each group. There are only $K$ groups, each starts with $(N,x)$ for every $1\\leq x\\leq K$. The group that starts with $(N,x)$ has $\\min(x,N-e)$ possible pairs. That means, the size of each group is $[1,2,3,\\ldots,N-e-2,N-e-1,N-e,N-e,N-e,\\ldots]$. Therefore, $g(e)=(N-e+1)!(N-e+1)^{(K-(N-e))}$. We can calculate all values of $g(e)$ using factorial precomputation and binary exponentiation. Time complexity: $O(N\\log K)$",
    "tags": [
      "combinatorics"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1866",
    "index": "I",
    "title": "Imagination Castle",
    "statement": "Given a chessboard of size $N \\times M$ ($N$ rows and $M$ columns). Each row is numbered from $1$ to $N$ from top to bottom and each column is numbered from $1$ to $M$ from left to right. The tile in row $r$ and column $c$ is denoted as $(r,c)$. There exists $K$ distinct special tiles on the chessboard with the $i$-th special tile being tile $(X_i,Y_i)$. It is guaranteed that tile $(1,1)$ is not a special tile.\n\nA new chess piece has been invented, which is the castle. The castle moves similarly to a rook in regular chess, but slightly differently. In one move, a castle that is on some tile can only move to another tile in the same row or in the same column, but only in the right direction or the down direction. Formally, in one move, the castle on tile $(r,c)$ can only move to tile $(r',c')$ if and only if one of the following two conditions is satisfied:\n\n- $r'=r$ and $c'>c$.\n- $c'=c$ and $r'>r$.\n\nChaneka and Bhinneka will play a game. In the beginning of the game, there is a castle in tile $(1,1)$. The two players will play alternatingly with Chaneka going first. In one turn, the player on that turn must move the castle following the movement rules of the castle.\n\nIf a player moves the castle to a special tile on her turn, then that player wins the game and the game ends. If on a turn, the castle cannot be moved, the player on that turn loses and the game ends.\n\nGiven the size of the board and the locations of each special tile. Determine the winner of this game if Chaneka and Bhinneka plays optimally.",
    "tutorial": "Define a winning tile as a tile where if a player starts a turn with the castle in that tile, she will have a strategy to win. Define a losing tile as a tile where if a player starts a turn with the castle in that tile, no matter what she does, the other player will always have a strategy to win. We can see each special tile as a losing tile. We can solve the problem by finding which tiles are the losing tiles. We can do that by doing \"backtrack\" from the bottom right corner of the board. Maintain a pointer $(r,c)$ which means that we have solved all tiles $(r',c')$ with $r'>r$ or $c'>c$. So initially, $(r,c)=(N,M)$ (no tiles are solved). There are three cases for each iteration of the pointer: If there is at least one special tile $(r',c')$ satisfying $r'=r$ and $c'\\geq c$, then all non-special tiles $(r' ',c' ')$ satisfying $r' '=r$ and $c' '<c$ are winning tiles. Then, move $(r,c)$ one step up. If there is at least one special tile $(r',c')$ satisfying $c'=c$ and $r'\\geq r$, then all non-special tiles $(r' ',c' ')$ satisfying $c' '=c$ and $r' '<r$ are winning tiles. Then, move $(r,c)$ one step to the left. If neither of the cases above holds, then $(r,c)$ itself is a losing tile and all non-special tiles $(r' ',c' ')$ satisfying one of the following is a winning tile: $r' '=r$ and $c' '<c$ $c' '=c$ and $r' '<r$ Then, move $(r,c)$ one step up and to the left. $r' '=r$ and $c' '<c$ $c' '=c$ and $r' '<r$ Chaneka wins if $(1,1)$ is a winning tile. Bhinneka wins if $(1,1)$ is a losing tile. Time complexity: $O(N+M+K)$",
    "tags": [
      "dp",
      "games",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1866",
    "index": "J",
    "title": "Jackets and Packets",
    "statement": "Pak Chanek has $N$ jackets that are stored in a wardrobe. Pak Chanek's wardrobe has enough room for two stacks of jackets, namely the left stack and the right stack. Initially, all $N$ jackets are in the left stack, while the right stack is empty. Initially, the $i$-th jacket from the top of the left stack has colour $C_i$.\n\nPak Chanek wants to pack all of those jackets into some packets, such that the jackets in the same packet has the same colour. However, it is possible for two jackets with the same colour to be in different packets.\n\nPak Chanek can do two kinds of operations:\n\n- Pak Chanek can pick \\textbf{any number of jackets from the top} from \\textbf{one stack} as long as the colour is the same, then take those jackets out of the stack and pack them into a packet. This packing operation takes $X$ minutes, no matter how many jackets are packed.\n- Pak Chanek can move \\textbf{one topmost jacket} from one stack to the top of the other stack (\\textbf{possibly right to left or left to right}). This moving operation takes $Y$ minutes.\n\nDetermine the minimum time to pack all jackets!",
    "tutorial": "Instead of looking at the two stacks as two separate arrays, consider them as a single array $A$ whose elements are the colours of the jackets in the right stack from bottom to top, then the colours of the jackets in the left stack from top to bottom. Also maintain a pointer that indicates the separation point between the right and left stack parts of the the array (the pointer is located at the gap between two adjacent elements instead of at an element). So, $A$ is initially equal to $C$ with the pointer located directly to the left of the leftmost element. Notice that a movement operation is equivalent to moving the pointer one step to the left or right. A packing operation is equivalent to erasing a contiguous group of elements of the same value directly to the left or to the right of the pointer. We can solve this problem using dynamic programming. Define the following values: $\\text{dp}[l][r]$: the minimum time to erase all elements if the array is $A[l..r]$ and the pointer is located directly to the left of the leftmost element. Now, consider the two transition cases for $\\text{dp}[l][r]$. If $A_l$ does not get erased in the same operation as $A_r$, then optimally, there must be a prefix of $A[l..r]$ (let's say it is $A[l..p]$) that gets entirely erased before doing anything with the rest of $A[l..r]$. For a particular partition of prefix, we must solve for that prefix, then solve for the rest. So to calculate for this case, we must find the minimum of all values of $\\text{dp}[l][p]+\\text{dp}[p+1][r]$. If $A_l$ gets erased in the same operation as $A_r$ (can only happen when $A_l=A_r$), then there must be a set of disjoint segments entirely within segment $[l,r]$ where every single one of those segment gets entirely erased before the one single packing operation that simultaneously erases $A_l$ and $A_r$. It must hold that every element outside of the segments has the same value as $A_l$ and $A_r$. For the case above, notice that in the optimal way, we repeatedly iterate the pointer directly to the left of each segment and completely erase the segment before going for the next segment. After all that, we can choose to move the pointer either directly to the left of $A_l$ or to the right of $A_r$, then erase the rest of $A[l..r]$ in one packing operation. To handle this, we define two new DP values for the case where $A_l$ and $A_r$ get erased in the same operation: $\\text{dpA}[l][r]$: the minimum time for this case if after erasing the last segment, the pointer moves to the right of $A_r$. $\\text{dpB}[l][r]$: the minimum time for this case if after erasing the last segment, the pointer moves to the left of $A_l$. The transitions for $\\text{dpA}$ are: If all elements of $A[l..r]$ have the same value, then $\\text{dpA}[l][r]=Y\\times(r-l+1)+X$ (the pointer moves to the very right, then erases all elements). Else, then we check every possible index $p$ for the next index in $A[l..r]$ not in the set of segments after $l$. So $\\text{dpA}[l][r]$ is the minimum of $Y+\\text{dpA}[l+1][r]$ and all values of $Y+\\text{dp}[l+1][p-1]+\\text{dpA}[p][r]$ for all $A_p=A_l$ (the pointer moves one step to the right, then solves $A[l+1..p-1]$, then continues to solve the rest of $A[l..r]$ knowing that $A_l$ will get erased along with $A_r$ in the end). The transitions for $\\text{dpB}$ are: If all elements of $A[l..r]$ have the same value, then $\\text{dpB}[l][r]=X$ (the pointer moves to the very left, then erases all elements). Else, then we check every possible index $p$ for the next index in $A[l..r]$ not in the set of segments after $l$. So $\\text{dpB}[l][r]$ is the minimum of $Y\\times2+\\text{dpB}[l+1][r]$ and all values of $Y\\times2+\\text{dp}[l+1][p-1]+\\text{dpB}[p][r]$ for all $A_p=A_l$ (the pointer moves one step to the right, then solves $A[l+1..p-1]$, then continues to solve the rest of $A[l..r]$, then moves the pointer all the way to the left passing through $A_l$ once again, before erasing the initial $A_l$ and $A_r$ in one packing operation). Time complexity: $O(N^3)$",
    "tags": [
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1866",
    "index": "K",
    "title": "Keen Tree Calculation",
    "statement": "There is a tree of $N$ vertices and $N-1$ edges. The $i$-th edge connects vertices $U_i$ and $V_i$ and has a length of $W_i$.\n\nChaneka, the owner of the tree, asks you $Q$ times. For the $j$-th question, the following is the question format:\n\n- $X_j$ $K_j$ – If each edge that contains vertex $X_j$ has its length multiplied by $K_j$, what is the diameter of the tree?\n\nNotes:\n\n- Each of Chaneka's question is \\textbf{independent}, which means the changes in edge length do not influence the next questions.\n- The diameter of a tree is the maximum possible distance between two different vertices in the tree.",
    "tutorial": "First, calculate the diameter of the initial tree. For a question involving some vertex $p$. There are only two cases to consider: The diameter is the same as the diameter of the initial tree. The diameter goes through vertex $p$. If the diameter goes through vertex $p$, then the diameter consists of two paths, each of them is from vertex $p$ to some other vertex, but the vertex immediately next to vertex $p$ in the two paths must be different. Consider a vertex $p$. Let $q_1,q_2,q_3,\\ldots,q_{\\text{deg}[p]}$ be the vertices adjacent to $p$ with $\\text{deg}[p]$ being the degree of $p$. For each $q_i$, calculate: $m_i$: The length of the edge connecting vertices $p$ and $q_i$. $c_i$: The maximum length of a path from $q_i$ to another vertex that does not pass through $p$. All values of $c_i$ can be calculated using dynamic programming on tree with rerooting. Notice that for a query involving vertex $p$ with a multiplier of $x$. The diameter that goes through vertex $p$ is the sum of the two biggest values of $m_i\\times x+c_i$. From this knowledge, we can consider each vertex $q_i$ as a line equation of $y=m_i\\times x+c_i$. In order to be able to find the biggest value of $m_i\\times x+c_i$ for any $x$, we maintain the maximum convex hull out of all those lines and we answer each query using binary search. In order to be able to find the second biggest value of $m_i\\times x+c_i$ for any $x$, we maintain several more convex hulls. Let $h_1,h_2,h_3,\\ldots$ be the indices of the lines in the maximum convex hull sorted from the smallest $m$ to the biggest $m$. Then, for each $h_j$, we maintain a new maximum convex hull out of all lines $i$ with $m_{h_{j-1}}\\leq m_i\\leq m_{h_{j+1}}$ other than line $h_j$. We do that to maintain the candidate lines of the second biggest value if the biggest value is taken from line $h_j$. This can be done because lines $h_{j-1}$ and $h_{j+1}$ are two of the candidate lines, so the only other possible candidate lines that can produce bigger values in this particular location are lines $i$ with $m_{h_{j-1}}\\leq m_i\\leq m_{h_{j+1}}$. Each line can only be in at most three different convex hulls, so the total number of lines to be considered in the making of all convex hulls for vertex $p$ is $O(\\text{deg}[p]$). So in total, for all vertices $p$, the total number of lines is $O(N)$. Time complexity: $O((N+Q)\\log N)$",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "geometry",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1866",
    "index": "L",
    "title": "Lihmuf Balling",
    "statement": "After working at a factory (Lihmuf Sorting), Lihmuf wants to play a game with his good friend, Pak Chanek. There are $N$ boxes numbered from $1$ to $N$. The $i$-th box contains $i$ balls. Pak Chanek and Lihmuf will play a game using those boxes.\n\nThere will be $N$ turns numbered from $1$ to $N$. On each turn, Pak Chanek chooses one box and takes all balls from that box, then Lihmuf does the same thing for one box he chooses (it is possible that the two chosen boxes are the same).\n\nGiven an integer $M$. Before the game begins, Lihmuf must choose an integer $K$ satisfying $1 \\leq K \\leq M$. It is known that on the $j$-th turn, Pak Chanek will choose the $j$-th box, while Lihmuf will choose the $y$-th box, with $y=((j \\times K - 1) \\bmod N) + 1$. Help Lihmuf choose the correct value of $K$ so that he will get as many balls as possible! If there are more than one possible values of $K$ that result in the maximum total balls, find the minimum such value of $K$.\n\nKeep in mind that each box can be chosen more than once, but after a box is chosen for the first time, the box becomes empty.",
    "tutorial": "To solve this, we just need to find the total number of balls Lihmuf will earn for each possible value of $K$ from $1$ to $M$. If $K=1$, then Lihmuf gets $0$ balls. If $K>1$ and $K$ is a factor of $N$, then Lihmuf will get all balls in the boxes with indices that are multiples of $K$. If $K$ is not coprime to $N$, then Lihmuf can only possibly get the balls in the boxes with indices that are multiples of a factor of $N$ greater than $1$, which is already covered by the case above, so this is always not optimal. Then, that leaves us with the case where $K>1$ and $K$ is coprime to $N$. Notice that in this case, Lihmuf will access each box exactly once. For this case, consider the sequence of indices of the boxes accessed by Lihmuf. We can group this sequence into exactly $K$ groups, where each group consists of a sequence of indices $c$, $c+K$, $c+2K$, $c+3K$, and so on for some value $1\\leq c\\leq K$. For each group, while Lihmuf is accessing the boxes in the group, at the same time, Pak Chanek is accessing boxes $d$, $d+1$, $d+2$, $d+3$, and so on for some value $d$. For this case, since $K>1$, that means at some point, Lihmuf will overtake Pak Chanek in the index of the box he accesses. That happens once $c+K\\times p>d+p$ for some $p\\geq0$. From that point on, Lihmuf will get all balls in the boxes he accesses in that group. The number of balls earned by Lihmuf in each group can be calculated in $O(1)$ using simple math and using the formula for the sum of an arithmetic sequence. The total time complexity to calculate for a single value of $K$ is $O(K)$, so the total time complexity is $O(M^2)$. Time complexity: $O(M^2)$",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1866",
    "index": "M",
    "title": "Mighty Rock Tower",
    "statement": "Pak Chanek comes up with an idea in the midst of boredom to play a game. The game is a rock tower game. There is a big rock that is used as a base. There are also $N$ small identical rocks that Pak Chanek will use to build a rock tower with a height of $N$ above the base rock.\n\nInitially, there are no small rocks that are located above the base rock. In other words, the height of the tower above the base rock is initially $0$. In one move, Pak Chanek can place one small rock onto the top of the tower which makes the height of the tower above the base rock increase by $1$. Each time Pak Chanek place one small rock, the following will happen after the small rock is placed:\n\n- Let's say $x$ is the height of the tower above the base rock \\textbf{right after the small rock is placed}.\n- There is a probability of $P_x$ percent that the topmost rock falls.\n- If $x \\geq 2$ and the topmost rock falls, then there is another probability of $P_x$ percent that the $2$-nd topmost rock also falls.\n- If $x \\geq 3$ and the $2$-nd topmost rock falls, then there is another probability of $P_x$ percent that the $3$-rd topmost rock also falls.\n- If $x \\geq 4$ and the $3$-rd topmost rock falls, then there is another probability of $P_x$ percent that the $4$-th topmost rock also falls.\n- And so on.\n\nIf the tower successfully reaches a height of $N$ without any rocks falling after that, then the game is ended.\n\nIf given an integer array $[P_1, P_2, \\ldots, P_N]$, what is the expected value of the number of moves that Pak Chanek needs to do to end the game? It can be proven that the expected value can be represented as an simple fraction $\\frac{P}{Q}$ where $Q$ is coprime to $998\\,244\\,353$. Output the value of $P \\times Q^{-1}$ modulo $998\\,244\\,353$.",
    "tutorial": "Let $f(x)$ be the the expected number of moves to turn a tower of height $x-1$ into $x$. In order to calculate that, let's say the tower's current height is $x-1$ and we want to make it into $x$. If we place one small rock, then the following cases can happen: With a probability of $(P_x\\%)^k(1-P_x\\%)$, exactly $k$ rocks fall for some $0\\leq k\\leq x-1$. With a probability of $(P_x\\%)^x$, exactly $x$ rocks fall. After moving once, if exactly $k$ rocks fall for some $1\\leq k\\leq x$, then the expected number of moves to make the height of the tower become $x$ is $f(x)+f(x-1)+f(x-2)+\\ldots+f(x-k+1)$. From the knowledge above, we get the following formula: $f(x)=1+(P_x\\%)^x(f(x)+f(x-1)+\\ldots+f(1))$$+\\sum_{k=1}^{x-1}(P_x\\%)^k(1-P_x\\%)(f(x)+f(x-1)+\\ldots+f(x-k+1))$ If we split each term of $f$ and count the contribution for each of them in the sum, then we will get the following: $f(x)=1+\\sum_{k=1}^x(P_x\\%)^kf(x-k+1)$ $f(x)=1+(P_x\\%)f(x)+\\sum_{k=2}^x(P_x\\%)^kf(x-k+1)$ $(1-P_x\\%)f(x)=1+\\sum_{k=2}^x(P_x\\%)^kf(x-k+1)$ $f(x)=\\frac{1+\\sum_{k=2}^x(P_x\\%)^kf(x-k+1)}{1-P_x\\%}$ Now, we must know how to calculate $\\sum_{k=2}^x(P_x\\%)^kf(x-k+1)$ quickly. Notice that there are only $100$ possible different values of $P_x$. So we can precompute the values $S$ with $S_{i,j}=\\sum_{k=2}^j(i\\%)^kf(j-k+1)$ for every $0\\leq i\\leq99$. We can calculate each value in $O(1)$ from each previous value if we precompute the values of $i\\%$ for every $0\\leq i\\leq99$. The answer to the original problem is $f(1)+f(2)+f(3)+\\ldots+f(N)$. Time complexity: $O(N\\max(P))$",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1867",
    "index": "A",
    "title": "green_gold_dog, array and permutation",
    "statement": "green_gold_dog has an array $a$ of length $n$, and he wants to find a permutation $b$ of length $n$ such that the number of distinct numbers in the element-wise difference between array $a$ and permutation $b$ is maximized.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation (as $2$ appears twice in the array) and $[1,3,4]$ is also not a permutation (as $n=3$, but $4$ appears in the array).\n\nThe element-wise difference between two arrays $a$ and $b$ of length $n$ is an array $c$ of length $n$, where $c_i$ = $a_i - b_i$ ($1 \\leq i \\leq n$).",
    "tutorial": "Let's subtract $n$ from the minimum number, subtract $n - 1$ from the second minimum, $n - 2$ from the third $\\ldots$, and subtract $1$ from the maximum. Then the number of distinct elements will be $n$. Obviously, it is impossible to achieve a better result. Let's prove that the number of distinct elements will be equal to $n$. Suppose $c_i = c_j$, then without loss of generality, let's say that $b_i > b_j$, then $a_i \\leq a_j$, which means $c_i = a_i - b_i$ < $a_j - b_j = c_j$. Contradiction. Time Complexity: $O(n \\log n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\n\nvoid solve() {\n\tll n;\n\tcin >> n;\n\tvector<pair<ll, ll>> arr(n);\n\tfor (ll i = 0; i < n; i++) {\n\t\tll x;\n\t\tcin >> x;\n\t\tarr[i].first = x;\n\t\tarr[i].second = i;\n\t}\n\tvector<ll> ans(n);\n\tsort(arr.begin(), arr.end());\n\treverse(arr.begin(),arr.end());\n\tfor (ll i = 0; i < n; i++) {\n\t\tans[arr[i].second] = i + 1;\n\t}\n\tfor (auto i : ans) {\n\t\tcout << i << ' ';\n\t}\n\tcout << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n\tll t = 1;\n\tcin >> t;\n\tfor (ll i = 0; i < t; i++) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1867",
    "index": "B",
    "title": "XOR Palindromes",
    "statement": "You are given a binary string $s$ of length $n$ (a string that consists only of $0$ and $1$). A number $x$ is good if there exists a binary string $l$ of length $n$, containing $x$ ones, such that if each symbol $s_i$ is replaced by $s_i \\oplus l_i$ (where $\\oplus$ denotes the bitwise XOR operation), then the string $s$ becomes a palindrome.\n\nYou need to output a binary string $t$ of length $n+1$, where $t_i$ ($0 \\leq i \\leq n$) is equal to $1$ if number $i$ is good, and $0$ otherwise.\n\nA palindrome is a string that reads the same from left to right as from right to left. For example, 01010, 1111, 0110 are palindromes.",
    "tutorial": "Firstly, a string is a palindrome if and only if for any $i$ ($1 \\leq i \\leq n$) $s_i = s_{n-i+1}$ (because when reversed, $s_i$ becomes $s_{n-i+1}$). We can divide the characters into pairs, where each pair consists of $s_i$ and $s_{n-i+1}$. If $s_i = s_{n-i+1}$, then we need to have $l_i = l_{n-i+1}$ in order to obtain equal elements after XOR. Therefore, either $l_i = l_{n-i+1} = 0$ (with $0$ ones) or $l_i = l_{n-i+1} = 1$ (with $2$ ones). If $s_i \\neq s_{n-i+1}$, then $l_i \\neq l_{n-i+1}$ must hold ($1$ one in any case). Additionally, if $n$ is odd, then $l_{n/2+1}$ can be either $0$ or $1$ (with $0$ or $1$ ones). We can iterate over the number of pairs where $l_i = l_{n-i+1}$ will have two ones, as well as whether there will be a one in the center or not. This way, we can obtain all possible numbers of ones in $l$, i.e., all good $i$. Time Complexity: $O(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        string t(n+1,'0');\n        int ans = 0;\n        int max_1 = 0;\n        int max_2 = 0;\n        for(int i = 0;i <= n/2-1;++i)\n        {\n            if(s[i] == s[n-i-1])\n                max_2++;\n            else\n                ans++;\n        }\n        if(n%2 == 1)\n            max_1++;\n        for(int j = 0;j <= max_2;++j)\n        {\n            for(int k = 0;k <= max_1;++k)\n            {\n                t[ans + j*2 + k] = '1';\n            }\n        }\n        cout << t << \"\\n\";\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1867",
    "index": "C",
    "title": "Salyg1n and the MEX Game",
    "statement": "\\textbf{This is an interactive problem!}\n\nsalyg1n gave Alice a set $S$ of $n$ distinct integers $s_1, s_2, \\ldots, s_n$ ($0 \\leq s_i \\leq 10^9$). Alice decided to play a game with this set against Bob. The rules of the game are as follows:\n\n- Players take turns, with Alice going first.\n- In one move, Alice adds one number $x$ ($0 \\leq x \\leq 10^9$) to the set $S$. The set $S$ must not contain the number $x$ at the time of the move.\n- In one move, Bob removes one number $y$ from the set $S$. The set $S$ must contain the number $y$ at the time of the move. Additionally, the number $y$ must be \\textbf{strictly smaller} than the last number added by Alice.\n- The game ends when Bob cannot make a move or after $2 \\cdot n + 1$ moves (in which case Alice's move will be the last one).\n- The result of the game is $\\operatorname{MEX}\\dagger(S)$ ($S$ at the end of the game).\n- Alice aims to maximize the result, while Bob aims to minimize it.\n\nLet $R$ be the result when both players play optimally. \\textbf{In this problem, you play as Alice against the jury program playing as Bob.} Your task is to implement a strategy for Alice such that the result of the game is always at least $R$.\n\n$\\dagger$ $\\operatorname{MEX}$ of a set of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $x$ which does not occur in the set $c$. For example, $\\operatorname{MEX}(\\{0, 1, 2, 4\\})$ $=$ $3$.",
    "tutorial": "The correct strategy for Alice is to add the number $\\operatorname{MEX}(S)$ to the set $S$ on the first move, and add the last removed number on the remaining moves. Let m = $\\operatorname{MEX}(S \\cup {\\operatorname{MEX}(S)})$, at the start of the game. In other words, m is equal to the second $\\operatorname{MEX}$ of the set $S$. $m \\geq 1$. Notice that after the first move, $\\operatorname{MEX}(S) = m$, and no matter what Bob removes, we will return that number to the set, so the result of the game will always be equal to $m$. Let's prove that with Bob's optimal play, we cannot achieve a result greater than m. Notice that the $\\operatorname{MEX}$ of a set is the largest number k such that all numbers from $0$ to $k-1$ inclusive are present in the set. Let $p_i$ be the number of numbers from $0$ to $i-1$ inclusive that appear in the set $S$. Then $\\operatorname{MEX}(S)$ is equal to the maximum $i$ such that $p_i = i$. If Bob removes the number $y$ during his turn, he decreases all values $p_i$ where $i > y$ by $1$. So, if $y = \\operatorname{min}(S)$, Bob decreases all non-zero values $p_i$ by $1$. Alice can increase some values $p_i$ by $1$ during her turn. Therefore, after Alice's first move, $\\operatorname{MEX}(S)$ will no longer increase if Bob keeps removing the minimum, because no non-zero values of $p_i$ will increase (Bob decreases them by $1$, and Alice increases them by at most $1$). It is obvious that in order to maximize $\\operatorname{MEX}(S)$ after the first move, Alice needs to add the number $\\operatorname{MEX}(S)$ to the set $S$. We have proven that $R \\leq m$ and provided a strategy that achieves a result of $m$. Time Complexity: $O(n)$ per test case.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> s(n);\n\tfor (int i = 0; i < n; ++i)\n\t\tcin >> s[i];\n\tint mex = -1;\n\tfor (int i = 0; i < n; ++i) {\n\t\tif (i == 0 && s[i] != 0) {\n\t\t\tmex = 0;\n\t\t\tbreak;\n\t\t}\n\t\tif (i > 0 && s[i] != s[i - 1] + 1) {\n\t\t\tmex = s[i - 1] + 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (mex == -1)\n\t\tmex = s[n - 1] + 1;\n\tcout << mex << endl;\n\tint y;\n\tcin >> y;\n\twhile (y != -1) {\n\t\tcout << y << endl;\n\t\tcin >> y;\n\t}\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "games",
      "greedy",
      "interactive"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1867",
    "index": "D",
    "title": "Cyclic Operations",
    "statement": "Egor has an array $a$ of length $n$, initially consisting of zeros. However, he wanted to turn it into another array $b$ of length $n$.\n\nSince Egor doesn't take easy paths, only the following operation can be used (possibly zero or several times):\n\n- choose an array $l$ of length $k$ ($1 \\leq l_i \\leq n$, all $l_i$ are \\textbf{distinct}) and change each element $a_{l_i}$ to $l_{(i\\%k)+1}$ ($1 \\leq i \\leq k$).\n\nHe became interested in whether it is possible to get the array $b$ using only these operations. Since Egor is still a beginner programmer, he asked you to help him solve this problem.\n\nThe operation $\\%$ means taking the remainder, that is, $a\\%b$ is equal to the remainder of dividing the number $a$ by the number $b$.",
    "tutorial": "If $k = 1$, then we can change $b_i$ to $i$, so the answer is YES only if $b_i = i$, otherwise the answer is NO. Otherwise, let's build an undirected graph with $n$ vertices and edges ($i, b_i$). Any component of this graph will look like a cycle (possibly of size $1$) to each vertex of which a tree is attached (possibly empty). Let's assume that there are $x$ vertices in a component, then there are also $x$ edges in it (since each vertex has exactly one outgoing edge). We can construct a depth-first search (DFS) tree for this component, which will have $x - 1$ edges. Now, when we add the remaining edge ($u, v$), a cycle is formed in the component (formed by the edge ($u, v$) and the path between $u$ and $v$ in the DFS tree). Each vertex will have a tree attached to it, because before adding the edge, we had a tree. Now it is claimed that if the cycle in each component has a size exactly $k$, then the answer is YES, otherwise NO. Let's first consider the situation where the size of the cycle in some component is not $k$. Let the cycle contain vertices $v_1, v_2, \\cdots, v_x$ in that order. Now let's look at the last operation in which one of the $l_i$ was equal to some element from the cycle. If the size of the cycle is less than $k$, then in the last operation there will be at least one vertex not from the cycle, which means that at least one vertex from the cycle will be replaced by a number that is not the next vertex in the cycle, which is incorrect because each vertex from the cycle should be replaced by the next vertex after it. If the size of the cycle is greater than $k$, then we will have a vertex from the cycle that will be replaced by a vertex that is not the next vertex in the cycle (otherwise we would have used all the vertices of the cycle, and there are more than $k$ of them). Therefore, in any case, there is no valid last operation with vertices from the cycle, so the answer is NO. If the size of the cycle in a component is equal to $k$, then we can apply the following algorithm: While there is at least one vertex $v$ in the component that is a leaf, we will perform the operation with $l = [v, b_v, b_{b_v}, \\cdots]$ (all elements are distinct because we will enter the cycle and it has a size of $k$). After this operation, we will have $a_v = b_v$, and we can remove vertex $v$ (it had only $1$ outgoing edge). When only the cycle remains, we can apply the operation for the vertices in the cycle, preserving the order, and then for all vertices in the component, we will have $a_v = b_v$. By doing this for all components, we will get $a = b$, which is what we wanted, so the answer is YES. Time Complexity: $O(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int n,k;\n        cin >> n >> k;\n        int b[n];\n        int vis[n];\n        for(int j = 0;j < n;++j)\n        {\n            cin >> b[j];\n            vis[j] = 0;\n        }\n        if(k == 1)\n        {\n            int no = 0;\n            for(int j = 0;j < n;++j)\n            {\n                if(b[j] != j+1)\n                {\n                    no = 1;\n                }\n            }\n            cout << (no ? \"NO\\n\" : \"YES\\n\");\n            continue;\n        }\n        int num[n];\n        int no = 0;\n        int tgr = 1;\n        for(int j = 0;j < n;++j)\n        {\n            if(!vis[j])\n            {\n                int ind = j;\n                int cnum = 0;\n                while(!vis[ind])\n                {\n                    vis[ind] = tgr;\n                    num[ind] = cnum++;\n                    ind = b[ind]-1;\n                }\n                if(vis[ind] != tgr)\n                {\n                    tgr++;\n                    continue;\n                }\n                if(cnum-num[ind] != k)\n                {\n                    no = 1;\n                    break;\n                }\n                tgr++;\n            }\n        }\n        cout << (no ? \"NO\\n\" : \"YES\\n\");\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1867",
    "index": "E1",
    "title": "Salyg1n and Array (simple version)",
    "statement": "\\textbf{This is the simple version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 100 queries. You can make hacks only if both versions of the problem are solved.}\n\n\\textbf{This is an interactive problem!}\n\nsalyg1n has given you a positive integer $k$ and wants to play a game with you. He has chosen an array of $n$ integers $a_1, a_2, \\ldots, a_n$ ($1 \\leq a_i \\leq 10^9$). You must print $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n$, where $\\oplus$ denotes the bitwise XOR operation. You can make queries of the following type:\n\n- $?$ $i$: in response to this query, you will receive $a_i \\oplus a_{i + 1} \\oplus \\ldots \\oplus a_{i + k - 1}$. Also, after this query, the subarray $a_i, a_{i + 1}, \\ldots, a_{i + k - 1}$ will be reversed, i.e., the chosen array $a$ will become: $a_1, a_2, \\ldots a_{i - 1}, a_{i + k - 1}, a_{i + k - 2}, \\ldots, a_{i + 1}, a_i, a_{i + k}, \\ldots, a_n$.\n\nYou can make no more than $100$ queries to answer the problem.",
    "tutorial": "Let's make queries to subarrays starting at positions $1$, $k + 1$, $2k + 1$, $\\ldots$ $m \\cdot k + 1$, as long as these queries are valid, meaning their right boundary does not exceed $n$. Let's save the $\\operatorname{XOR}$ of all the answers to these queries. We will call these queries primary. Now, we will shift the last subarray of the query one unit to the right and make a new query, as long as the right boundary does not exceed $n$. We will call these queries secondary. It is claimed that the $\\operatorname{XOR}$ of the entire array will be equal to the $\\operatorname{XOR}$ of all the queries. Let's prove this. Let $i$ be the position at which the first secondary query starts. Notice that after this query, the subarray [$i$; $i + k - 2$] will turn into the subarray [$i + 1$; $i + k - 1$] and reverse. After the next query, the same thing will happen, the subarray will shift one unit to the right and reverse. Therefore, the prefixes of length $k-1$ of each secondary query will be the same, up to the reversal, which does not affect the $\\operatorname{XOR}$. Since the number of secondary queries is equal to $n \\operatorname{mod} k$, which is an even number, the $\\operatorname{XOR}$ of these prefixes will not affect the $\\operatorname{XOR}$ of all the secondary queries, which will therefore be equal to the $\\operatorname{XOR}$ of the elements [$a_{i + k - 1}$; $a_n$], that is, all the elements that we did not consider in the primary queries. The number of primary queries is equal to $\\lfloor \\frac{n}{k} \\rfloor \\leq k \\leq 50$, since $n \\leq k^2 \\leq 2500$. The number of secondary queries is equal to $n \\operatorname{mod} k < k <= 50$, since $k^2 \\leq 2500$. The total number of queries does not exceed $100$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint ask(int i) {\n\tcout << \"? \" << i << endl;\n\tint x;\n\tcin >> x;\n\treturn x;\n}\n\nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tint res = 0;\n\tint i;\n\tfor (i = 1; i + k - 1 <= n; i += k)\n\t    res ^= ask(i);\n\tfor (; i <= n; ++i)\n\t    res ^= ask(i - k + 1);\n\tcout << \"! \" << res << endl;\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1867",
    "index": "E2",
    "title": "Salyg1n and Array (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 57 queries. You can make hacks only if both versions of the problem are solved.}\n\n\\textbf{This is an interactive problem!}\n\nsalyg1n has given you a positive integer $k$ and wants to play a game with you. He has chosen an array of $n$ integers $a_1, a_2, \\ldots, a_n$ ($1 \\leq a_i \\leq 10^9$). You must print $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n$, where $\\oplus$ denotes the bitwise XOR operation. You can make queries of the following type:\n\n- $?$ $i$: in response to this query, you will receive $a_i \\oplus a_{i + 1} \\oplus \\ldots \\oplus a_{i + k - 1}$. Also, after this query, the subarray $a_i, a_{i + 1}, \\ldots, a_{i + k - 1}$ will be reversed, i.e., the chosen array $a$ will become: $a_1, a_2, \\ldots a_{i - 1}, a_{i + k - 1}, a_{i + k - 2}, \\ldots, a_{i + 1}, a_i, a_{i + k}, \\ldots, a_n$.\n\nYou can make no more than $57$ queries to answer the problem.",
    "tutorial": "Let's make queries to subarrays starting at positions $1$, $k + 1$, $2k + 1$, $\\ldots$ $m \\cdot k + 1$, such that the size of the uncovered part is greater than $2 \\cdot k$ and not greater than $3 \\cdot k$. In other words, $2 \\cdot k < n - (m + 1) \\cdot k \\le 3 \\cdot k$. Let's keep the $\\operatorname{XOR}$ of all the answers to these queries. We will call these queries primary. Let the size of the remaining (uncovered) part be $x$ ($2 \\cdot k < x \\le 3 \\cdot k$). Let's learn how to solve the problem for an array of size $x$ in three queries. If $x = 3 \\cdot k$, simply make queries to positions $1$, $k + 1$, $2 \\cdot k + 1$. Otherwise, let $y = x - k$. Note that $y$ is even, since $x$ and $k$ are even. Make queries at positions $1$, $1 + \\frac{y}{2}$, $1 + y$. Note that after this query, the subarray [$1$; $k - \\frac{y}{2}$] will turn into the subarray [$y/2 + 1$; $k$] and reverse. After the next query, the same thing will happen, the subarray will shift one unit to the right and reverse. Therefore, the prefixes of length $k - \\frac{y}{2}$ for each query are the same, up to the reversal, which does not affect the $\\operatorname{XOR}$. Since the number of queries in the second group is $3$, which is an odd number, the $\\operatorname{XOR}$ of these prefixes will be taken into account exactly once in the $\\operatorname{XOR}$ of all the queries, which will therefore be equal to the $\\operatorname{XOR}$ of the elements. The number of primary queries does not exceed $\\lfloor \\frac{n}{k} \\rfloor \\leq k \\leq 50$, since $n \\leq k^2 \\leq 2500$. The total number of queries does not exceed $53$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint ask(int i) {\n\tcout << \"? \" << i << endl;\n\tint x;\n\tcin >> x;\n\treturn x;\n}\n\nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tint res = 0;\n\tint i;\n\tfor (i = 1; n - i + 1 >= 2 * k; i += k)\n\t\tres ^= ask(i);\n\tif (n - i + 1 == k) {\n\t\tres ^= ask(i);\n\t\tcout << \"! \" << res << endl;\n\t\treturn;\n\t}\n\tint y = (n - i + 1 - k) / 2;\n\tres ^= ask(i);\n\tres ^= ask(i + y);\n\tres ^= ask(i + 2 * y);\n\tcout << \"! \" << res << endl;\n}\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "interactive"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1867",
    "index": "F",
    "title": "Most Different Tree",
    "statement": "Given a tree with $n$ vertices rooted at vertex $1$, denote it as $G$. Also denote $P(G)$ as the multiset of subtrees of all vertices in tree $G$. You need to find a tree $G'$ of size $n$ rooted at vertex $1$ such that the number of subtrees in $P(G')$ that are isomorphic to any subtree in $P(G)$ is minimized.\n\nA subtree of vertex $v$ is a graph that contains all vertices for which vertex $v$ lies on the path from the root of the tree to itself, as well as all edges between these vertices.\n\nTwo rooted trees are considered isomorphic if it is possible to relabel the vertices of one of them so that it becomes equal to the other, with the root of the first tree receiving the number of the root of the second tree.",
    "tutorial": "Here we say that the answer for tree $G'$ is the number of subtrees in $P(G')$ that have an isomorphic subtree in $P(G)$. Let's find a tree $T$ of minimum size that has no isomorphic tree in $P(G)$. Let the size of tree $T$ be $x$. Then take a chain of size $n - x$, and let the root of $T$ be the kid of the last vertex on the chain. We say that this is the tree $G'$ we were looking for (with the root of $G'$ being the first vertex of the chain). The number of matching subtrees will be at most $x - 1$, since all subtrees of the vertices on the chain and the subtree $T$ itself will not have isomorphic trees in $P(G)$, because $T$ lies entirely in them, and $T$ has no isomorphic tree in $P(G)$. Therefore, the answer is not greater than $n - (n - x) - 1 = x - 1$. Let's prove why the answer cannot be less than $x - 1$: suppose there exists a tree $G*$ for which the answer is less than $x - 1$. Let's find a subtree of minimum size whose size is at least $x$ (it always exists, since we can take the entire tree for example). In this subtree, there are at least $x - 1$ other subtrees, whose sizes are less than $x$ (because in the previous step we chose a subtree of minimum size not less than $x$). And since all trees of size less than $x$ have isomorphic trees in $P(G)$ (by definition $T$ is the tree of minimum size that has no isomorphic tree in $P(G)$ and its size is $x$), the number of matching subtrees in tree $G*$ is at least $x - 1$, which is a contradiction. Therefore in our case the answer is $x - 1$. Now let's solve the second part of the problem - finding $T$. To do this, let's first find all trees of size 1, then of size 2, then 3, 4 and so on until we find a tree that has no isomorphic subtree in $P(G)$. One can see that if we generate all trees of size up to 15 we will definitely find $T$ there. Within each size, let's number the trees in the order in which we've generated them. To find all trees of size $x$ if we are given all trees of size $x - 1$ and smaller, let's say that the sizes of the children of the root of the tree we generate must not decrease, and if the sizes are the same, their positions in the order must not decrease. Then, we can iterate over the first child, then among the smaller and suitable ones, the second child, then the third, and so on until the total size of the tree becomes exactly $x$. This way, we will enumerate all trees of size $x$ in complexity of their total number (since we will not consider any tree twice and will not consider any extra trees). Let's do this until we find a tree that is not in $P(G)$. Hashes can be used to compare trees for isomorphism. For more details, read the blog post Time Complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAXSZ = 15;\n\nvoid rec(int ns, int last, vector<int>& now, vector<vector<int>>& aint, vector<int>& col, vector<int>& sz, int& ss, int sns) {\n    if (ss < 0) {\n        return;\n    }\n\tif (ns == 0) {\n\t\tcol.back()++;\n\t\taint.push_back(now);\n\t\tss -= sns;\n\t\treturn;\n\t}\n\tfor (int i = min(last, col[ns] - 1); i >= 0; i--) {\n\t\tnow.push_back(i);\n\t\trec(ns - sz[i], i, now, aint, col, sz, ss, sns);\n\t\tnow.pop_back();\n\t}\n}\n\nvoid dfs(int v, int p, vector<vector<int>>& arr, vector<int>& num, map<vector<int>, int>& m, vector<int>& sz) {\n\tvector<int> now;\n\tsz[v] = 1;\n\tfor (auto i : arr[v]) {\n\t\tif (i != p) {\n\t\t\tdfs(i, v, arr, num, m, sz);\n\t\t\tsz[v] += sz[i];\n\t\t\tif (sz[v] <= MAXSZ) {\n\t\t\t    now.push_back(num[i]);\n\t\t\t}\n\t\t}\n\t}\n\tif (sz[v] > MAXSZ) {\n\t\tnum[v] = -1;\n\t\treturn;\n\t}\n\tstable_sort(now.begin(), now.end());\n\treverse(now.begin(), now.end());\n\tnum[v] = m[now] - 1;\n}\n\nvoid dfs2(int x, int p, vector<vector<int>>& aint, vector<int>& ans) {\n\tif (p >= 0) {\n\t\tans.push_back(p);\n\t}\n\tint now = ans.size();\n\tfor (auto i : aint[x]) {\n\t\tdfs2(i, now, aint, ans);\n\t}\n}\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<vector<int>> aint(1);\n\tvector<vector<int>> arr(n);\n\tfor (int i = 1; i < n; i++) {\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\ta--;\n\t\tb--;\n\t\tarr[a].push_back(b);\n\t\tarr[b].push_back(a);\n\t}\n\tmap<vector<int>, int> m;\n\tvector<int> col(1, 0), sz(1, 1);\n\tcol.push_back(1);\n\tfor (int i = 2; i <= MAXSZ; i++) {\n\t\tvector<int> now;\n\t\tcol.push_back(col.back());\n\t\tint ss = n;\n\t\trec(i - 1, aint.size() - 1, now, aint, col, sz, ss, i);\n\t\twhile (sz.size() < col.back()) {\n\t\t\tsz.push_back(i);\n\t\t}\n\t\tif (ss < 0) {\n\t\t    break;\n\t\t}\n\t}\n\tfor (int i = 0; i < col.back(); i++) {\n\t\tm[aint[i]] = i + 1;\n\t}\n\tvector<int> num(n), szi(n, 1);\n\tdfs(0, 0, arr, num, m, szi);\n\tset<int> s;\n\tfor (int i = 0; i < col.back(); i++) {\n\t\ts.insert(i);\n\t}\n\tfor (auto i : num) {\n\t\ts.erase(i);\n\t}\n\tint x = *s.begin();\n\tvector<int> ans;\n\tif (sz[x] > n) {\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (auto j : arr[i]) {\n\t\t\t\tif (i < j) {\n\t\t\t\t\tcout << i + 1 << ' ' << j + 1 << '\\n';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\tfor (int i = 0; i < n - sz[x] - 1; i++) {\n\t\tans.push_back(i);\n\t}\n\tdfs2(x, n - sz[x] - 1, aint, ans);\n\tfor (int i = 0; i < ans.size(); i++) {\n\t\tcout << ans[i] + 1 << ' ' << i + 2 << '\\n';\n\t}\n}\n\nint main() {\n    \tios_base::sync_with_stdio(false);\n    \tcin.tie(0);\n    \tcout.tie(0);\n\tint t = 1;\n\t//cin >> t;\n\tfor (int i = 0; i < t; i++) {\n\t\tsolve();\n\t}\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "hashing"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1868",
    "index": "A",
    "title": "Fill in the Matrix",
    "statement": "There is an empty matrix $M$ of size $n\\times m$.\n\nZhongkao examination is over, and Daniel would like to do some puzzle games. He is going to fill in the matrix $M$ using permutations of length $m$. That is, each row of $M$ must be a permutation of length $m^\\dagger$.\n\nDefine the value of the $i$-th column in $M$ as $v_i=\\operatorname{MEX}(M_{1,i},M_{2,i},\\ldots,M_{n,i})^\\ddagger$. Since Daniel likes diversity, the beauty of $M$ is $s=\\operatorname{MEX}(v_1,v_2,\\cdots,v_m)$.\n\nYou have to help Daniel fill in the matrix $M$ and \\textbf{maximize} its beauty.\n\n$^\\dagger$ A permutation of length $m$ is an array consisting of $m$ distinct integers from $0$ to $m-1$ in arbitrary order. For example, $[1,2,0,4,3]$ is a permutation, but $[0,1,1]$ is not a permutation ($1$ appears twice in the array), and $[0,1,3]$ is also not a permutation ($m-1=2$ but there is $3$ in the array).\n\n$^\\ddagger$ The $\\operatorname{MEX}$ of an array is the smallest non-negative integer that does not belong to the array. For example, $\\operatorname{MEX}(2,2,1)=0$ because $0$ does not belong to the array, and $\\operatorname{MEX}(0,3,1,2)=4$ because $0$, $1$, $2$ and $3$ appear in the array, but $4$ does not.",
    "tutorial": "On one hand, the matrix $M$ has $n$ rows, so the maxmium $v_i$ does not exceed $\\operatorname{MEX}(0,1,\\cdots,n-1)=n$, and $s$ does not exceed $n+1$. On the other hand, the matrix $M$ has $m$ columns, and there are only $m$ numbers in the array $v$, so $s$ must not exceed $m$. Therefore, the upper bound of $s$ is $\\min(n+1,m)$. How can we reach the upper bound? If $m=1$, then the only possible $M=\\begin{pmatrix} 0\\\\ 0\\\\ \\vdots\\\\ 0 \\end{pmatrix}$, in this case, $v_1=1$, so $s$ must be $0$, which unfortunately cannot reach the upper bound. Sadly, many participants failed on pretest 2 because of it. I've added this test to examples:) If $m>1$, let's construct the $M$ in two cases: Case 1. $m\\ge n+1$.In this case, we can construct $M$ like following: $M= \\begin{pmatrix} 0&1&\\cdots&m-2&m-1\\\\ 1&2&\\cdots&m-1&0\\\\ 2&3&\\cdots&0&1\\\\ \\vdots&\\vdots&\\ddots&\\vdots&\\vdots\\\\ n-1&n&\\cdots &n-3 & n-2 \\end{pmatrix}$ More formally, $M_{i,j}=(i+j-1)\\bmod m$. Note that in this case $n-1< m-1$, so we have $v_1=n$, $v_2=v_{3}=\\cdots=v_{m-n-1}=0$, $v_{m-n}=1,v_{m-n+1}=2,\\cdots,v_m=n-1$. Then $s=n+1$, which reaches the upper bound. In this case, we can construct $M$ like following: $M= \\begin{pmatrix} 0&1&\\cdots&m-2&m-1\\\\ 1&2&\\cdots&m-1&0\\\\ 2&3&\\cdots&0&1\\\\ \\vdots&\\vdots&\\ddots&\\vdots&\\vdots\\\\ n-1&n&\\cdots &n-3 & n-2 \\end{pmatrix}$ More formally, $M_{i,j}=(i+j-1)\\bmod m$. Note that in this case $n-1< m-1$, so we have $v_1=n$, $v_2=v_{3}=\\cdots=v_{m-n-1}=0$, $v_{m-n}=1,v_{m-n+1}=2,\\cdots,v_m=n-1$. Then $s=n+1$, which reaches the upper bound. Case 2. $m<n+1$.In this case, we can construct $M$ like following: $M= \\begin{pmatrix} 0&1&\\cdots&m-2&m-1\\\\ 1&2&\\cdots&m-1&0\\\\ 2&3&\\cdots&0&1\\\\ \\vdots&\\vdots&\\ddots&\\vdots&\\vdots\\\\ m-2&m-1&\\cdots &m-4 & m-3\\\\ 0&1&\\cdots&m-2&m-1\\\\ 0&1&\\cdots&m-2&m-1\\\\ \\vdots&\\vdots&\\ddots&\\vdots&\\vdots\\\\ 0&1&\\cdots&m-2&m-1\\\\ \\end{pmatrix}$ More formally, for $1\\le j\\le m-1$, $M_{i,j}=(i+j-1)\\bmod m$, for $m\\le j\\le n$, $M_{i,j}=(j-1)\\bmod m$. Note that $m>1$, and $m-2\\ge 0$. Similarly to case 1 we can get $s=m$, which also reaches the upper bound. In this case, we can construct $M$ like following: $M= \\begin{pmatrix} 0&1&\\cdots&m-2&m-1\\\\ 1&2&\\cdots&m-1&0\\\\ 2&3&\\cdots&0&1\\\\ \\vdots&\\vdots&\\ddots&\\vdots&\\vdots\\\\ m-2&m-1&\\cdots &m-4 & m-3\\\\ 0&1&\\cdots&m-2&m-1\\\\ 0&1&\\cdots&m-2&m-1\\\\ \\vdots&\\vdots&\\ddots&\\vdots&\\vdots\\\\ 0&1&\\cdots&m-2&m-1\\\\ \\end{pmatrix}$ More formally, for $1\\le j\\le m-1$, $M_{i,j}=(i+j-1)\\bmod m$, for $m\\le j\\le n$, $M_{i,j}=(j-1)\\bmod m$. Note that $m>1$, and $m-2\\ge 0$. Similarly to case 1 we can get $s=m$, which also reaches the upper bound. Time Complexity: $\\mathcal{O}(n\\cdot m)$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define all(s) s.begin(), s.end()\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\n\nconst int _N = 1e5 + 5;\n\nint T;\n\nvoid solve() {\n\tint n, m;\n\tcin >> n >> m;\n\tif (m == 1) cout << 0 << '\\n';\n\telse if (n > m - 1) cout << m << '\\n';\n\telse cout << n + 1 << '\\n';\n\tfor (int i = 0; i < min(m - 1, n); i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tcout << (j + i) % m << ' ';\n\t\t}\n\t\tcout << '\\n';\n\t}\n\tif (n > m - 1) {\n\t\tfor (int i = m - 1; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tcout << j << ' ';\n\t\t\t}\n\t\t\tcout << '\\n';\n\t\t}\n\t}\n\treturn;\n}\n\nint main() {\n\tios::sync_with_stdio(false), cin.tie(0), cout.tie(0);\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1868",
    "index": "B1",
    "title": "Candy Party (Easy Version)",
    "statement": "{This is the easy version of the problem. The only difference is that in this version everyone must give candies to \\textbf{exactly one} person and receive candies from \\textbf{exactly one} person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions of the problem are solved.}\n\nAfter Zhongkao examination, Daniel and his friends are going to have a party. Everyone will come with some candies.\n\nThere will be $n$ people at the party. Initially, the $i$-th person has $a_i$ candies. During the party, they will swap their candies. To do this, they will line up \\textbf{in an arbitrary order} and everyone will do the following \\textbf{exactly once}:\n\n- Choose an integer $p$ ($1 \\le p \\le n$) and a \\textbf{non-negative} integer $x$, then give his $2^{x}$ candies to the $p$-th person. Note that one \\textbf{cannot} give more candies than currently he has (he might receive candies from someone else before) and he \\textbf{cannot} give candies to himself.\n\nDaniel likes fairness, so he will be happy if and only if everyone receives candies from \\textbf{exactly one person}. Meanwhile, his friend Tom likes average, so he will be happy if and only if all the people have the same number of candies after all swaps.\n\nDetermine whether there exists a way to swap candies, so that both Daniel and Tom will be happy after the swaps.",
    "tutorial": "Denote $s$ as $\\frac{1}{n}\\sum_{i=1}^n a_i$. If $s$ is not an integer, then it will be impossible to make all people have the same number of candies, so the answer is \"No\". Since a person gives candies to and receives candies from exactly one person, suppose he gives away $2^x$ candies and receives $2^y$ candies, then we get this equation: $a_i-2^{x_i}+2^{y_i}=s.$ If $s=a_i$, there is an infinite set of solutions: $x_i=y_i$. Otherwise, $s\\ne a_i$, then we have $a_i-s=2^{x_i}-2^{y_i}$. For different pairs $(x, y)$ ($x\\ne y$), the values of $2^x - 2^y$ are pairwise different, so there will be at most $1$ solution to this equation. Thus, if there exists a possible solution, the number of candies each person receives and gives away is determined for $a_i\\ne s$. If an equation has no solution, then obviously the answer is \"No\". Otherwise, let's maintain two multisets $S$ and $T$. For each person, let's add $x_i$ to $S$ and $y_i$ to $T$. Omitting the condition \"one cannot give more candies than currently he has\" $(1)$, we can claim that the answer is \"Yes\" if and only if $S=T$. The proof is left to readers as an exercise. :) Now let's think about the condition $(1)$. Build a directed graph with $n$ nodes. For two persons $i$ and $j$, if person $i$ gives $x>0$ candies to person $j$, then we add an edge from node $i$ to node $j$ with weight $x$. All nodes with $a_i\\ne s$ must have exactly $1$ in degree and $1$ out degree. So the graph must consist of several cycles. Let's prove that we can always choose a starting point properly for any cycle, so that the condition $(1)$ is satisfied. Pick the largest $a_i$ in the cycle, and we must have $a_i>s$. Suppose the $i$-th person gives candies to the $j$-th person ($1\\le a_j\\le a_i$, $x_i\\ne x_j$), then we have: $a_i-2^{x_i}+2^{y_i}=s,\\tag{2}$ $a_j-2^{x_j}+2^{x_i}=s,\\tag{3}$ Suppose $a_i<2^{x_i}$, then we must have $y_i<x_i$, so $2^{y_i}\\le 2^{x_i}/2$. If $x_i<x_j$, that is, $2\\cdot 2^{x_i}\\le 2^{x_j}$: $\\begin{aligned} (2)-(3)&\\implies a_i-a_j-2^{x_i}+2^{x_j}+2^{y_i}-2^{x_i}=0\\\\ &\\implies a_i-a_j+\\underbrace{(2^{x_j}-2\\cdot 2^{x_i})+2^{y_i}}_{>0}=0\\\\ &\\implies a_i<a_j, \\end{aligned}$ Similarly we can prove that when $x_i>x_j$, $a_j<0$. In both cases the condition $1\\le a_j\\le a_i$ has been violated. So we proved that $a_i-2^{x_i}>0$. Thus, we proved the the claim. And we can easily add those nodes with $a_i=s$ into cycles: suppose the node is $p$, if there is an edge $a\\to b$ with weight $w$, we add two edge $a\\to p$ and $p\\to b$, both weights are $w$, and delect the original edge $a\\to b$. So we can solve this problem by simply maintaining $S$ and $T$, which can be done in $\\mathcal{O}(n\\log V)$. $\\mathcal{O}(n\\log^2 V)$ solutions can fit in the TL well, too.",
    "code": "#include <bits/stdc++.h>\n#define all(s) s.begin(), s.end()\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\n\nconst int _N = 1e5 + 5;\n\nint T;\n\nvoid solve() {\n\tint n; cin >> n;\n\tvector<ll> a(n); ll sum = 0;\n\tfor (int i = 0; i < n; i++) cin >> a[i], sum += a[i];\n\tif (sum % n) return cout << \"No\" << '\\n', void();\n\tsum /= n;\n\tvector<int> bit(31, 0);\n\tauto lowbit = [](int x) {\n\t    return x & (-x);\n\t};\n\tfor (int i = 0; i < n; i++) {\n\t\tif (a[i] == sum) continue;\n\t\tint d = abs(a[i] - sum);\n\t\tint p = lowbit(d);\n\t\tint e = d + p;\n\t\tif (__builtin_popcount(e) == 1) {\n\t\t    if (a[i] > sum) bit[__lg(e)]++, bit[__lg(p)]--;\n\t\t    else bit[__lg(e)]--, bit[__lg(p)]++;\n\t\t} else {\n\t\t    cout << \"No\" << '\\n';\n\t\t    return;\n\t\t}\n\t}\n\tfor (int i = 0; i < 31; i++) {\n\t\tif (bit[i]) {\n\t\t\tcout << \"No\" << '\\n';\n\t\t\treturn;\n\t\t}\n\t}\n\tcout << \"Yes\" << '\\n';\n\treturn;\n}\n\nint main() {\n\tios::sync_with_stdio(false), cin.tie(0), cout.tie(0);\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "graphs",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1868",
    "index": "B2",
    "title": "Candy Party (Hard Version)",
    "statement": "{This is the hard version of the problem. The only difference is that in this version everyone must give candies to \\textbf{no more than one} person and receive candies from \\textbf{no more than one} person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions of the problem are solved.}\n\nAfter Zhongkao examination, Daniel and his friends are going to have a party. Everyone will come with some candies.\n\nThere will be $n$ people at the party. Initially, the $i$-th person has $a_i$ candies. During the party, they will swap their candies. To do this, they will line up \\textbf{in an arbitrary order} and everyone will do the following \\textbf{no more than once}:\n\n- Choose an integer $p$ ($1 \\le p \\le n$) and a \\textbf{non-negative} integer $x$, then give his $2^{x}$ candies to the $p$-th person. Note that one \\textbf{cannot} give more candies than currently he has (he might receive candies from someone else before) and he \\textbf{cannot} give candies to himself.\n\nDaniel likes fairness, so he will be happy if and only if everyone receives candies from \\textbf{no more than one person}. Meanwhile, his friend Tom likes average, so he will be happy if and only if all the people have the same number of candies after all swaps.\n\nDetermine whether there exists a way to swap candies, so that both Daniel and Tom will be happy after the swaps.",
    "tutorial": "Read the tutorial for D1 first. Consider the graph we built in this version. It should only consist of chains and cycles. For the start nodes of chains and the end nodes of chains, $|a_i-s|=2^d$ must hold. Thus, for $|a_i-s|\\ne 2^d$, we sill have only one way to decide the number of candies given away and received (the same as D1). However, for $|a_i-s|=2^d$, we have two ways: the same way as D1 (use the equation $a_i-2^{x_i}+2^{y_i}=s$); let this person be the start or end node of chains, that is, $a_i-2^{x_i}=s$ or $a_i-2^{x_i}=s$. (Suppose $2^{x_i}$ is the number of candies he gives away or receives) Again, let's omit those nodes with $|a_i-s|=2^d$ first. Then we can similarly maintain two sets $S$ and $T$ to D1. Let $cntS_i$ be the number of $i$-s in set $S$ and $cntT_i$ be the number of $i$-s in $T$. Note that now we omit nodes with $|s-a_i|=2^d$ when maintaining both sets. Let $cntDS_k$ be the number of nodes with $a_i-s=2^k$ and $cntDT_i$ be the number of nodes with $s-a_i=2^{k}$. For nodes with $|a_i-s|=2^{x_i}$, the two ways are: $a_i-2^{x_i}=s$, or $a_i+2^{x_i}=s$; $a_i+2^{x_i}-2^{x_i+1}=s$, or $a_i-2^{x_i-1}+2^{x_i}$. To make the two sets $S$ and $T$ equal, we must make $cntS_k=cntT_k$ for all $0\\le k\\le 30$. Now consider nodes with $|a_i-s|=2^d$. We can determine bit-by-bit. Let's start from the first bit. Consider $cntDS_i$: if we choose $x\\le cntDS_i$ elements to use the first way, then: $cntS_i:=cntS_i+x$; $cntS_{i+1}:=cntS_{i+1}+x$; $cntT_i:=cntT_i+(cntDS_i-x)$. Consider $cntDT_i$: if we choose $x\\le cntDT_i$ elements to use the first way, then: $cntT_i:=cntT_i+x$; $cntT_{i-1}:=cntT_{i-1}+x$; $cntT_i:=cntT_i+(cntDT_i-x)$. Let's consider the highest bit. All elements in $cntDS_i$ must be chosen the second way ($x=0$), otherwise, it will influence $cntS_{i+1}$. Then we can determine the $x$ for $cntDT_i$, then $cntDS_{i-1},cntDT_{i-1},...,cntDS_0,cntDT_0$. At last, we check if $cntS_0=cntT_0$ (we have made $cntS_i=cntT_i$ for all $i>0$). If so, the answer is \"Yes\", otherwise the answer is \"No\".",
    "code": "#include <bits/stdc++.h>\n#define all(s) s.begin(), s.end()\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\n\nconst int _N = 1e5 + 5;\n\nint T;\n\nvoid solve() {\n\tint n; cin >> n;\n\tvector<ll> a(n); ll sum = 0;\n\tfor (int i = 0; i < n; i++) cin >> a[i], sum += a[i];\n\tif (sum % n) return cout << \"No\" << '\\n', void();\n\tsum /= n;\n\tvector<int> bit(31, 0), pow1(31, 0), pow2(31, 0);\n\tfor (int i = 0; i < n; i++) {\n\t\tint flag = 0;\n\t\tif (a[i] == sum) continue;\n\t\tfor (int j = 0; j < 31; j++) {\n\t\t\tif (a[i] + (1 << j) == sum) {\n\t\t\t\tpow1[j]++;\n\t\t\t\tflag = 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (a[i] - (1 << j) == sum) {\n\t\t\t\tpow2[j]++;\n\t\t\t\tflag = 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flag) continue;\n\t\tflag = 0;\n\t\tfor (int j = 0; j < 31; j++) {\n\t\t\tfor (int k = 0; k < 31; k++) {\n\t\t\t    if (a[i] + (1 << j) - (1 << k) == sum) {\n\t\t\t        flag = 1;\n\t\t\t        bit[j]++;\n\t\t\t        bit[k]--;\n\t\t\t    }\n\t\t\t}\n\t\t}\n\t\tif (!flag) {\n\t\t\tcout << \"No\" << '\\n';\n\t\t\treturn;\n\t\t}\n\t}\n\tfor (int i = 30; i >= 0; i--) {\n\t\tbit[i] += (pow1[i] - pow2[i]);\n\t\tif (i == 0) break;\n\t\tif (bit[i] < 0) {\n\t\t\tpow1[i - 1] -= -bit[i];\n\t\t\tbit[i - 1] -= -bit[i];\n\t\t\tif (pow1[i - 1] < 0) {\n\t\t\t\tcout << \"No\" << '\\n';\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\tpow2[i - 1] -= bit[i];\n\t\t\tbit[i - 1] += bit[i];\n\t\t\tif (pow2[i - 1] < 0) {\n\t\t\t\tcout << \"No\" << '\\n';\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tif (bit[0] == 0) cout << \"Yes\" << '\\n';\n\telse cout << \"No\" << '\\n';\n\treturn;\n}\n\nint main() {\n\tios::sync_with_stdio(false), cin.tie(0), cout.tie(0);\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1868",
    "index": "C",
    "title": "Travel Plan",
    "statement": "During the summer vacation after Zhongkao examination, Tom and Daniel are planning to go traveling.\n\nThere are $n$ cities in their country, numbered from $1$ to $n$. And the traffic system in the country is very special. For each city $i$ ($1 \\le i \\le n$), there is\n\n- a road between city $i$ and $2i$, if $2i\\le n$;\n- a road between city $i$ and $2i+1$, if $2i+1\\le n$.\n\nMaking a travel plan, Daniel chooses some integer value between $1$ and $m$ for each city, for the $i$-th city we denote it by $a_i$.\n\nLet $s_{i,j}$ be the maximum value of cities in the simple$^\\dagger$ path between cities $i$ and $j$. The score of the travel plan is $\\sum_{i=1}^n\\sum_{j=i}^n s_{i,j}$.\n\nTom wants to know the sum of scores of all possible travel plans. Daniel asks you to help him find it. You just need to tell him the answer modulo $998\\,244\\,353$.\n\n$^\\dagger$ A simple path between cities $x$ and $y$ is a path between them that passes through each city at most once.",
    "tutorial": "For any path of length $t$, the number of assignments in which the maximum value of cities is no bigger than $k$ is $k^t$. As a result, the number of assignments in which the maximum value of cities is exactly $k$ is $k^t-(k-1)^t$, while the sum of the maximum value of cities in all assignments is $\\sum_{k=1}^m(k^t-(k-1)^t)k$. We can solve this in $\\mathcal O(m\\log n)$. Then, we need to calculate the number of paths of length $t$ for each $t$. Claim. There are $\\mathcal O(\\log n)$ different subtrees in this tree. Proof. It's easy to see that this tree can be seen as a full binary tree with one row of extra leaves. Let the number of leaves in each subtree be $lf_i$. If $lf_i=2^p$, the subtree of $i$ is a full binary tree with depth $p$. Also, for each subtree satisfying $lf_i\\neq 2^p$, either $lf_{2i}=2^{p'}$ or $lf_{2i+1}=2^{p'}$, which means that for each depth, there is at most one subtree satisfying $lf_i\\neq2^p$. As the depth of the whole tree is $\\mathcal O(\\log n)$, the total number of different subtrees is also $\\mathcal O(\\log n)$. Then, let $dp_{i,j}$ stand for the number of paths length $j$ in a subtree with $i$ vertices, and $f_{i,j}$ stand for the number of paths with one end being $i$ and length $j$ in a subtree with $i$ vertices. We can simply do a memorization search to solve this part in $\\mathcal O(\\log^3 n)$. To optimize the first part, we can transform the formula to $m^t\\times m-\\sum_{k=1}^{m-1}k^t$. For the second part, we can use interpolation, dp, or polynomial to solve this in $\\mathcal O(\\log n)$ or $\\mathcal O(\\log^2 n)$. To optimize the second part, we can divide the paths into three types: no end on the extra leaves, one end on the extra leaves, and two ends on the extra leaves. For the first two types, we can simply see the paths as going up and going down so we can enumerate the distance going up and down. Then we can calculate them in $\\mathcal O(\\log^2 n)$. For the third part, a dp just like the above will work. The only difference is that only one $f_{i,j}$ is not $0$ under this circumstance and we can solve it in $\\mathcal O(\\log^2 n)$. It's also possible to solve this second part in $\\mathcal O(\\log n)$ by further optimization of the calculation of the three types of paths. $\\mathcal O(\\sum(m\\log n+\\log^3n))$ solution by programpiggy: $\\mathcal O(\\sum \\log^3n)$ solution by sszcdjr: $\\mathcal O(\\sum \\log^2n)$ solution by sszcdjr: $\\mathcal O(\\sum m\\log n)$ solution by ling_luo:",
    "code": "#include <bits/stdc++.h>\n#define rep(i,n) for(int i=0,_##i##__end=(n);i<_##i##__end;++i)\n#define rep1(i,n) for(int i=1,_##i##__end=(n);i<=_##i##__end;++i)\n#define mp make_pair\n#define fi first\n#define se second\ntypedef long long ll;\nusing namespace std;\nconst ll mod1=998244353;\nint t;\nll n;\nint m;\nll qkpw(ll a,ll b)\n{\n\tll ret=1;\n\twhile(b)\n\t{\n\t\tif(b&1) ret=ret*a%mod1;\n\t\ta=a*a%mod1;\n\t\tb>>=1;\n\t}\n\treturn ret;\n}\nll val_full[114];\nll val_link[114];\npair<ll,ll> realget(ll P,unsigned long long c)\n{\n\tif((c&(c+1))==0)\n\treturn mp(val_link[bit_width(c)-1],val_full[bit_width(c)-1]);\n\tif(c==2)\n\treturn mp((P*P+P)%mod1,(P*P+P+P)%mod1);\n\tif(c&(bit_floor(c)>>1))\n\t{\n\t\tpair<ll,ll> A=realget(P,bit_floor(c)-1),B=realget(P,c-bit_floor(c));\n\t\treturn mp((A.fi+B.fi+1)*P%mod1,(A.se+B.se+(1+A.fi)*(1+B.fi)%mod1*P)%mod1);\n\t}\n\tpair<ll,ll> A=realget(P,c-(bit_floor(c)>>1)),B=realget(P,(bit_floor(c)>>1)-1);\n\treturn mp((A.fi+B.fi+1)*P%mod1,(A.se+B.se+(1+A.fi)*(1+B.fi)%mod1*P)%mod1);\n}\nll get_value(ll P,ll c)\n{\n\tval_full[0]=P;val_link[0]=P;\n\trep1(i,64)\n\t{\n\t\tval_full[i]=(val_full[i-1]*2+(1+val_link[i-1])*(1+val_link[i-1])%mod1*P)%mod1;\n\t\tval_link[i]=((val_link[i-1]*2+1)*P)%mod1;\n\t}\n\treturn realget(P,c).second;\n}\nvoid Q()\n{\n\tcin>>n>>m;\n\tll cur=((n%mod1)*(n%mod1+1)/2%mod1)*qkpw(m,n+1)%mod1;\n\tll INV_M=qkpw(m,mod1-2);\n\trep(i,m) cur=(cur-qkpw(m,n)*get_value(i*INV_M%mod1,n)%mod1+mod1)%mod1;\n\tcout<<cur<<endl;\n}\nint main()\n{\n\tcin>>t;while(t--)Q();\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1868",
    "index": "D",
    "title": "Flower-like Pseudotree",
    "statement": "A pseudotree is a connected graph which has \\textbf{exactly one} cycle and \\textbf{no} self-loops. Note that a pseudotree \\textbf{may contain multiple-edges}. It can be shown that a pseudotree with $n$ vertices always contains $n$ edges.\n\nAfter deleting all edges on the cycle in the pseudotree, a forest$^{\\dagger}$ will be formed. It can be shown that each tree in the forest will contain exactly one vertex which is on cycle before removing the edges. If all trees in the forest have the same depth$^{\\ddagger}$ when picking the vertex on cycle as root, we call the original pseudotree flower-like.\n\nOur friend sszcdjr, had a flower-like pseudotree with $n$ vertices and $n$ edges. However, he forgot all the edges in the pseudotree. Fortunately, he still remembers the degrees of vertices. Specifically, the degree of the $i$-th vertex is $d_i$.\n\nYou have to help sszcdjr construct a possible flower-like pseudotree with $n$ vertices, where the degree of the $i$-th vertex is \\textbf{exactly} $d_i$, or tell him that it is impossible.\n\n$^{\\dagger}$ A forest is a graph in which all connectivity components are trees. A connected graph without cycles and self-loops is called a tree.\n\n$^{\\ddagger}$ The depth of a tree with a root is the maximum distance from the root to the vertex of this tree.",
    "tutorial": "If $\\sum_{i=1}^n d_i\\neq 2n$, it's obviously impossible to construct a flower-like psuedotree. So let's just consider the situation when $\\sum_{i=1}^n d_i=2n$. Sort $d_i$ from largest to smallest. If $d_1=d_2=\\dots=d_n=2$, we can simply construct a cycle. Otherwise $d_1>2$, in which case there must be at least two $d_i>2$ and the vertices on the cycle must satisfy $d_i>2$. Ignore all vertices with $d_i=1$ as we can just hang them under all the other vertices. The following pictures don't show vertices with $d_i=1$ and the edges with weight $2$ are two multi-edges. Let $cnt$ be the number of vertices with $d_i>1$. If $cnt$ is even, we can make a cycle using $d_1$ and $d_2$, with two chains of equal length hanging from $d_1$ and $d_2$. The multi-edges have a number $2$ on them. If $cnt$ is odd and $d_1>3$, it's easy to see that we can hang two vertices below $d_1$ to transform it to the situation where $cnt$ is even. However, we need at least $5$ vertices to make the psuedotree flower-like, which means that $cnt\\geq5$ must be satisfied. (In the picture, at least vertices $1\\sim5$ are needed.) If $cnt$ is odd, $d_1>3$ and $cnt=3$, it's impossible for us to simply build a cycle length $2$. Thus, we can try to put $d_1,d_2,d_3$ in one cycle and the condition is $d_3>2$. If $cnt$ is odd and $d_1=3$, it's impossible for us to do the operation above, because we can't hang two vertices under $d_1$. It's easy to see that we can't balance the two trees if $d_3=2$. For $d_3=3$, we can hang $d_3,d_4$ under $d_1,d_2$, $d_5,d_6$ under $d_3$ and $d_7$ under $d_4$ to make the psuedotree flower-like. However, we need at least $7$ vertices to make it balanced, which means $cnt\\geq7$ must be satisfied. If $cnt$ is odd, $d_1=3$ and $cnt=5$, there are three cases: $d_1=d_2=d_3=3,d_4=d_5=2$: It can be proven that there isn't such a psuedotree. $d_1=d_2=d_3=d_4=3,d_5=2$: It can be proven that there isn't such a psuedotree. $d_1=d_2=d_3=d_4=d_5=3$: We can simply build a cycle of length $5$. If $cnt$ is odd, $d_1=3$ and $cnt=3$, there's only one case: $d_1=d_2=d_3=3$: We can simply build a cycle of length $3$. The total complexity depends on the sorting part, which is $\\mathcal O(n\\log n)$ if you use std::sort or std::stable_sort, and $\\mathcal O(n)$ if you use bucket sorting.",
    "code": "#include <bits/stdc++.h>\n#define int long long\n#define double long double\nusing namespace std;\nstruct node{\n\tint d,pos;\n}a[1000005];\nbool cmp(node x,node y){\n\treturn x.d>y.d;\n}\nvoid pe(int x,int y){\n\tcout<<a[x].pos<<\" \"<<a[y].pos<<\"\\n\";\n}\nsigned main(){\n\tios::sync_with_stdio(false);\n\tcin.tie(0),cout.tie(0);\n\tint t; cin>>t;\n\twhile(t--){\n\t\tint n,tot=0; cin>>n; for(int i=1;i<=n;i++) cin>>a[i].d,a[i].pos=i,tot+=a[i].d;\n\t\tif(tot!=2*n){\n\t\t\tcout<<\"No\\n\"; continue;\n\t\t}\n\t\tif(n==1){\n\t\t\tcout<<\"No\\n\"; continue;\n\t\t}\n\t\tsort(a+1,a+n+1,cmp);\n\t\tif(a[1].d==2){\n\t\t\tcout<<\"Yes\\n\";\n\t\t\tfor(int i=1;i<=n;i++) pe(i,i%n+1);\n\t\t\tcontinue;\n\t\t}\n\t\tif(a[2].d==2){\n\t\t\tcout<<\"No\\n\"; continue;\n\t\t}\n\t\tint cntb=0;\n\t\tfor(int i=3;i<=n;i++) cntb+=(a[i].d>1);\n\t\tint num[n+1]; for(int i=1;i<=n;i++) num[i]=a[i].d;\n\t\tif(!(cntb&1)){\n\t\t\tcout<<\"Yes\\n\";\n\t\t\tpe(1,2),pe(1,2);\n\t\t\tnum[1]-=2,num[2]-=2;\n\t\t\tfor(int i=3;i<=cntb+2;i++) pe(i,i-2),num[i]--,num[i-2]--;\n\t\t\tint it=1;\n\t\t\tfor(int i=cntb+3;i<=n;i++){\n\t\t\t\twhile(!num[it]) it++;\n\t\t\t\tnum[it]--,pe(i,it);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif(a[1].d==3){\n\t\t\tif(a[3].d==2){\n\t\t\t\tcout<<\"No\\n\"; continue;\n\t\t\t}\n\t\t\tif(cntb==1){\n\t\t\t\tcout<<\"Yes\\n\";\n\t\t\t\tpe(1,2),pe(2,3),pe(3,1);\n\t\t\t\tpe(1,4),pe(2,5),pe(3,6);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(a[5].d==2&&cntb==3){\n\t\t\t\tcout<<\"No\\n\"; continue;\n\t\t\t}\n\t\t\tif(cntb==3){\n\t\t\t\tcout<<\"Yes\\n\";\n\t\t\t\tpe(1,2),pe(2,3),pe(3,4),pe(4,5),pe(5,1);\n\t\t\t\tpe(1,6),pe(2,7),pe(3,8),pe(4,9),pe(5,10);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcout<<\"Yes\\n\";\n\t\t\tpe(1,2),pe(1,2),pe(1,3),pe(2,4),pe(3,5),pe(3,6),pe(4,7);\n\t\t\tnum[1]-=3,num[2]-=3,num[3]-=3,num[4]-=2,num[5]--,num[6]--,num[7]--;\n\t\t\tfor(int i=8;i<=cntb+2;i++) pe(i-2,i),num[i]--,num[i-2]--;\n\t\t\tint it=1;\n\t\t\tfor(int i=cntb+3;i<=n;i++){\n\t\t\t\twhile(!num[it]) it++;\n\t\t\t\tnum[it]--,pe(i,it);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\telse{\n\t\t\tif(a[3].d==2&&cntb==1){\n\t\t\t\tcout<<\"No\\n\"; continue;\n\t\t\t}\n\t\t\tif(cntb==1){\n\t\t\t\tcout<<\"Yes\\n\";\n\t\t\t\tpe(1,2),pe(2,3),pe(3,1);\n\t\t\t\tnum[1]-=2,num[2]-=2,num[3]-=2;\n\t\t\t\tint it=1;\n\t\t\t\tfor(int i=4;i<=n;i++){\n\t\t\t\t\twhile(!num[it]) it++;\n\t\t\t\t\tnum[it]--,pe(i,it);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcout<<\"Yes\\n\";\n\t\t\tpe(1,2),pe(1,2),pe(1,3),pe(1,4),pe(2,5);\n\t\t\tnum[1]-=4,num[2]-=3,num[3]-=1,num[4]-=1,num[5]-=1;\n\t\t\tfor(int i=6;i<=cntb+2;i++) pe(i,i-2),num[i]--,num[i-2]--;\n\t\t\tint it=1;\n\t\t\tfor(int i=cntb+3;i<=n;i++){\n\t\t\t\twhile(!num[it]) it++;\n\t\t\t\tnum[it]--,pe(i,it);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1868",
    "index": "E",
    "title": "Min-Sum-Max",
    "statement": "Tom is waiting for his results of Zhongkao examination. To ease the tense atmosphere, his friend, Daniel, decided to play a game with him. This game is called \"Divide the Array\".\n\nThe game is about the array $a$ consisting of $n$ integers. Denote $[l,r]$ as the subsegment consisting of integers $a_l,a_{l+1},\\ldots,a_r$.\n\nTom will divide the array into contiguous subsegments $[l_1,r_1],[l_2,r_2],\\ldots,[l_m,r_m]$, such that each integer is in exactly one subsegment. More formally:\n\n- For all $1\\le i\\le m$, $1\\le l_i\\le r_i\\le n$;\n- $l_1=1$, $r_m=n$;\n- For all $1< i\\le m$, $l_i=r_{i-1}+1$.\n\nDenote $s_{i}=\\sum_{k=l_i}^{r_i} a_k$, that is, $s_i$ is the sum of integers in the $i$-th subsegment. For all $1\\le i\\le j\\le m$, the following condition must hold:\n\n$$ \\min_{i\\le k\\le j} s_k \\le \\sum_{k=i}^j s_k \\le \\max_{i\\le k\\le j} s_k. $$\n\nTom believes that the more subsegments the array $a$ is divided into, the better results he will get. So he asks Daniel to find the \\textbf{maximum} number of subsegments among all possible ways to divide the array $a$. You have to help him find it.",
    "tutorial": "Let $s$ be the suffix sum array of array $a$. That is, $s_i=\\sum_{j=1}^ia_i$ and $s_0=0$. Let the partition point of the array be $r_0,r_1,\\dots,r_m$, where $r_0=0$ and $r_m=n$. Pick one of the maximums of $s_{r_0},s_{r_1},\\dots,s_{r_m}$ and let it be $s_{r_x}$. Similarly, let the minimum be $s_{r_y}$. If $|x-y|\\geq 2$, there must be some $k$ ($k<x<y$) which satisfies that $s_{r_k}=s_{r_x}$ or $s_{r_k}=s_{r_y}$, or it's easy to see that the subsegment $[x+1,y]$ is invalid. Using the induction method, we can show that there exists a pair $(i,i+1)$ such that $s_{r_i}$ and $s_{r_{i+1}}$ are the maximum and the minimum in a valid subsegment in a partition. As a result, after enumerating $r_i,r_{i+1}$, the two parts $[1,r_i]$ and $[r_{i+1},n]$ are separate subproblems with constraints $s_{r_i}\\leq r_t\\leq s_{r_{i+1}}$. Let $dp_{i,j,k,l}$ be the maximum number of $r_t$ we can select in the segment $[i,j]$ with all $k\\leq s_{r_t}\\leq l$ and positions $i,j$ must be selected. Enumerate the maximum and minimum $s_{r_t}$ in all the selected $r_t$ and let them be $s_x$ and $s_y$. Then we get the transitions: $\\forall k\\le s_x,l\\ge s_y,dp_{i,j,k,l}\\gets dp_{i,x,s_x,s_y}+dp_{y,j,s_x,s_y}$ After compressing the coordinates of the array $s$ and changing the meaning of $k,l$ to the $k$-th,$l$-th small $s_i$ after coordinate compression, we can solve this problem in $\\mathcal{O}(n^6)$, and $\\mathcal{O}(n^4)$ with 2D prefix maximum. Consider the optimization. It's easy to see that the states used in the transformation all satisfy $k=s_i$ or $l=s_i$ or $k=s_j$ or $l=s_j$. Let's replace $dp_{i,j,s_i,k}$ by $f_{i,j,k}$ and replace $dp_{i,j,k,s_i}$ by $g_{i,j,k}$, and the transitions only relieve on $f_{i,j,k}$ and $g_{i,j,k}$, so the number of states was reduced to $\\mathcal{O}(n^3)$. Consider the transitions of $f_{i,j,k}$ as $g_{i,j,k}$ is similar. Since the minimum $s_{r_t}$ is greater than $s_i$ and the position $i$ must be selected, the minimum $s_{r_t}$ is $s_i$. Enumerate $x$ and let $s_x$ be the maximum $s_{r_t}$. We need to find the best position $y$ where $s_y$ is minimum, i.e. $s_y=s_i$ and transform the segment $[i,x],[y,j]$ or $[i,y],[x,j]$ to $[i,j]$. It's easy to see that selecting the first $s_y=s_i$ on the left/right of $x$ is always the best choice. Let $y_1,y_2$ be the first on the left/right, then the transitions are: $\\forall k\\ge s_x$ $f_{i,j,k}\\leftarrow\\max\\{f_{i,y_1,s_x}+g_{x,j,s_i}\\}$ $f_{i,j,k}\\leftarrow\\max\\{f_{i,x,s_x}+f_{y_2,j,s_x}\\}$ Thus, the total time complexity is $\\mathcal{O}(n^3)$ per test case.",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <set>\n#include <map>\n#include <math.h>\n#include <iomanip>\n#include <bitset>\n#include <random>\n#include <ctime>\n#include <string_view>\n#include <queue>\n#include <cassert>\n\nusing namespace std;\n\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define pb emplace_back\n#define ll long long\n#define mp make_pair\n#define pii pair<int, int>\n#define ld long double\n\nconst int INF = 1e9 + 1;\nconst ll INFLL = 1e18;\n\nbool contains(ll x, ll l, ll r) {\n    return (x >= l) && (x <= r);\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<ll> a(n + 1);\n    for (int i = 1; i <= n; i++) cin >> a[i];\n    if (n == 1) {\n        cout << 1 << \"\\n\";\n        return;\n    }\n    vector<ll> pr(n + 1);\n    for (int i = 0; i < n; i++) pr[i + 1] = pr[i] + a[i + 1];\n    vector<vector<vector<int>>> dp_leftmin(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF)));\n    vector<vector<vector<int>>> dp_leftmax(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF)));\n    vector<vector<vector<int>>> dp_rightmin(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF)));\n    vector<vector<vector<int>>> dp_rightmax(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF)));\n    vector<pair<ll, int>> b(n + 1);\n    for (int i = 0; i <= n; i++) b[i] = mp(pr[i], i);\n    sort(all(b));\n    vector<vector<int>> next_left(n + 1, vector<int>(n + 1, -1));\n    vector<vector<int>> next_right(n + 1, vector<int>(n + 1, -1));\n    for (int i = 0; i <= n; i++) {\n        int prev = -1;\n        for (int j = 0; j <= n; j++) {\n            next_left[i][j] = prev;\n            if (pr[j] == pr[i]) prev = j;\n        }\n        prev = n + 1;\n        for (int j = n; j >= 0; j--) {\n            next_right[i][j] = prev;\n            if (pr[j] == pr[i]) prev = j;\n        }\n    }\n    for (int len = 0; len <= n; len++) {\n        for (int i = 0; i <= n && i + len <= n; i++) {\n            int j = i + len;\n            for (int k = 0; k <= n; k++) {\n                if (contains(pr[i], pr[i], pr[k]) && contains(pr[j], pr[i], pr[k])) dp_leftmin[i][j][k] = min(len, 1);\n                if (contains(pr[i], pr[k], pr[i]) && contains(pr[j], pr[k], pr[i])) dp_leftmax[i][j][k] = min(len, 1);\n                if (contains(pr[i], pr[j], pr[k]) && contains(pr[j], pr[j], pr[k])) dp_rightmin[i][j][k] = min(len, 1);\n                if (contains(pr[i], pr[k], pr[j]) && contains(pr[j], pr[k], pr[j])) dp_rightmax[i][j][k] = min(len, 1);\n            }\n            if (len <= 1) continue;\n            for (int x = i; x <= j; x++) {\n                if (next_left[i][x] >= i) {\n                    int y = next_left[i][x];\n                    if (pr[x] >= pr[i]) dp_leftmin[i][j][x] = max(dp_leftmin[i][j][x], dp_leftmin[i][y][x] + dp_leftmax[x][j][i] + 1);\n                    if (pr[x] <= pr[i]) dp_leftmax[i][j][x] = max(dp_leftmax[i][j][x], dp_leftmax[i][y][x] + dp_leftmin[x][j][i] + 1);\n                }\n                if (next_left[j][x] >= i) {\n                    int y = next_left[j][x];\n                    if (pr[x] >= pr[j]) dp_rightmin[i][j][x] = max(dp_rightmin[i][j][x], dp_rightmin[x][j][x] + dp_rightmin[i][y][x] + 1);\n                    if (pr[x] <= pr[j]) dp_rightmax[i][j][x] = max(dp_rightmax[i][j][x], dp_rightmax[x][j][x] + dp_rightmax[i][y][x] + 1);\n                }\n                if (next_right[i][x] <= j) {\n                    int y = next_right[i][x];\n                    if (pr[x] >= pr[i]) dp_leftmin[i][j][x] = max(dp_leftmin[i][j][x], dp_leftmin[i][x][x] + dp_leftmin[y][j][x] + 1);\n                    if (pr[x] <= pr[i]) dp_leftmax[i][j][x] = max(dp_leftmax[i][j][x], dp_leftmax[i][x][x] + dp_leftmax[y][j][x] + 1);\n                }\n                if (next_right[j][x] <= j) {\n                    int y = next_right[j][x];\n                    if (pr[x] >= pr[j]) dp_rightmin[i][j][x] = max(dp_rightmin[i][j][x], dp_rightmin[y][j][x] + dp_rightmax[i][x][j] + 1);\n                    if (pr[x] <= pr[j]) dp_rightmax[i][j][x] = max(dp_rightmax[i][j][x], dp_rightmax[y][j][x] + dp_rightmin[i][x][j] + 1);\n                }\n            }\n            int mx_left = -INF;\n            int mx_right = -INF;\n            for (int k = 0; k <= n; k++) {\n                int p = k;\n                while (p <= n && b[p].fi == b[k].fi) {\n                    mx_left = max(mx_left, dp_leftmin[i][j][b[p].se]);\n                    mx_right = max(mx_right, dp_rightmin[i][j][b[p].se]);\n                    p++;\n                }\n                for (int l = k; l < p; l++) {\n                    dp_leftmin[i][j][b[l].se] = mx_left;\n                    dp_rightmin[i][j][b[l].se] = mx_right;\n                }\n                k = p - 1;\n            }\n            mx_left = -INF;\n            mx_right = -INF;\n            for (int k = n; k >= 0; k--) {\n                int p = k;\n                while (p >= 0 && b[p].fi == b[k].fi) {\n                    mx_left = max(mx_left, dp_leftmax[i][j][b[p].se]);\n                    mx_right = max(mx_right, dp_rightmax[i][j][b[p].se]);\n                    p--;\n                }\n                for (int l = k; l > p; l--) {\n                    dp_leftmax[i][j][b[l].se] = mx_left;\n                    dp_rightmax[i][j][b[l].se] = mx_right;\n                }\n                k = p + 1;\n            }\n        }\n    }\n    int ans = -INF;\n    ans = max(ans, dp_leftmin[0][n][n]);\n    ans = max(ans, dp_leftmax[0][n][n]);\n    for (int x = 0; x <= n; x++) {\n        for (int y = x + 1; y <= n; y++) {\n            ans = max(ans, dp_rightmin[0][x][y] + dp_leftmax[y][n][x] + 1);\n            ans = max(ans, dp_rightmax[0][x][y] + dp_leftmin[y][n][x] + 1);\n        }\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    #ifdef LOCAL\n        freopen(\"input\", \"r\", stdin);\n        freopen(\"output\", \"w\", stdout);\n    #else \n        ios_base::sync_with_stdio(0);\n        cin.tie(0);\n        cout.tie(0);\n    #endif\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1868",
    "index": "F",
    "title": "LIS?",
    "statement": "Entering senior high school life, Tom is attracted by LIS problems, not only the Longest Increasing Subsequence problem, but also the Largest Interval Sum problem. Now he gets a really interesting problem from his friend Daniel. However, it seems too hard for him to solve it, so he asks you for help.\n\nGiven an array $a$ consisting of $n$ integers.\n\nIn one operation, you do the following:\n\n- Select an interval $[l,r]$ ($1\\le l\\le r\\le n$), such that the sum of the interval is the largest among \\textbf{all intervals} in the array $a$. More formally, $\\displaystyle\\sum_{i=l}^r a_i=\\max_{1\\le l'\\le r'\\le n}\\sum_{i=l'}^{r'} a_i$.\n- Then subtract $1$ from all elements $a_l,a_{l+1},\\ldots,a_r$.\n\nFind the minimum number of operations you need to perform to make $a_i<0$ for every $1\\le i\\le n$.",
    "tutorial": "Call an interval candidate good if and only if it has no prefixes or suffixes with sum $<0$. For a candidate good interval $[l,r]$, if there is no $l'<l$ or $r'>r$ such that $[l',r]$, $[l,r']$ or $[l',r']$ is also a candidate good interval, we call it good interval. It's easy to show that all intervals which satisfy the condition in the statement are candidate good intervals and at least one of them is a good interval. Lemma 1. For two good intervals $[l_1,r_1]$ and $[l_2,r_2]$, they will never intersect. More formally: either $r_1<l_2$ or $r_2<l_1$; or $l_2 \\le l_1\\le r_1\\le r_2$. Greedy Algorithm. In each operation, we choose one good interval that satisfies the condition in the statement. This will give the minimum answer. Following our process of the greedy algorithm, it's easy to see that the intervals on which we perform operations each time will form a tree structure. If we do the operation on one such interval, then one of the following happens: The interval remains good; The interval is no longer good, and we can split it into several good intervals. In the first case, we can keep doing operations on this interval without thinking whether it will have the largest sum among all intervals since it remains good, and all good intervals must be split into shorter good intervals unless it has length $1$. In this case, we can simply do the operations until the only element falls $\\le0$. In the second case, let $(L_i,d)$ means that if all the elements in the interval decrease $d$ ($d$ is the smallest integer which meets with the following), then $s(L_i,r)>s(l,r)$. That is, $d=\\min_{l <l'\\le r}\\frac{s_r-s_{l'-1}}{r-l'},$ Have you noticed that it is very similar to the slope between points $(l'-1,s_{l'-1})$ and $(r,s_r)$ on a 2-D plane? So what we need to find is just the first point before $(r,s_r)$ (after $(l,s_l)$) in the convex hull for points $(l,s_l),(l+1,s_{l+1}),...,(r,r_s)$. To find it, we can use a segment tree to directly maintain the convex hull for certain intervals, each time we query $\\mathcal{O}(\\log n)$ intervals and do ternary search on the convex hull of each interval. This step will cost $\\mathcal{O}(\\log^2 n)$. In each split, the number of good intervals increases $1$, so we do at most $n$ splits. Overall time complexity is $\\mathcal{O}(n\\log^2 n)$.",
    "code": "/*  \n  hmz is cute!\n--------------------------------------------\n  You've got to have faith\n  Don't let them cut you down cut you down once more\n*/\n//#pragma GCC optimize(\"Ofast,no-stack-protector\")\n//#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n#include<bits/stdc++.h>\nusing namespace std;\n#define TY long long\n#define IL inline\n#define umap unordered_map\n#define ull unsigned long long\n#define pq priority_queue\n#define mp make_pair\n#define pb push_back\n#define mod (TY)(1e9+7)\n#define MAXN 500005\n#define MAXM 200005\n#define MAXK 27\n#define INF (TY)(1e9)\n#define block 300\n#define For(i,a,b) for(TY i=(a);i<=(b);++i)\n#define FOR(i,a,b) for(TY i=(a);i<(b);++i)\n#define Rof(i,a,b) for(TY i=(a);i>=(b);--i)\n#define ROF(i,a,b) for(TY i=(a);i>(b);--i)\nIL TY qr(){\n\tTY x=0,f=1;char op=getchar();\n\tfor(;op<'0'||op>'9';op=getchar())if(op=='-')f=-1;\n\tfor(;op>='0'&&op<='9';op=getchar())x=x*10+(op^48);\n\treturn x*f;\n}IL bool ischar(char op){\n\tif(op>='a'&&op<='z')return true;\n\tif(op>='A'&&op<='Z')return true;\n\treturn false;\n}IL char getc(){\n\tchar op=getchar();\n\twhile(!ischar(op))op=getchar();\n\treturn op;\n}IL string qs(){\n\tstring op=\"\";char u=getchar();\n\twhile(!ischar(u))u=getchar();\n\twhile(ischar(u))op+=u,u=getchar();\n\treturn op;\n}IL void qw(long long x){\n\tif(!x){putchar('0');return;}\n\tif(x<0)putchar('-'),x=-x;\n\tif(x>=10)qw(x/10);putchar(x%10+'0');\n}IL void qw(long long x,char op){qw(x),putchar(op);}\nIL void ws(string s){FOR(i,0,s.size())putchar(s[i]);}\nIL TY Ceil(TY a,TY b){return a/b+(a%b!=0);}\nIL TY Mod(TY a){return (a>=mod?a-mod:a);}\nIL TY Abs(TY a,TY b){return a>b?a-b:b-a;}\nIL TY Pow(TY a,TY b){\n\tTY ans=1,base=a;\n\twhile(b){\n\t\tif(b&1)ans=ans*base%mod;\n\t\tbase=base*base%mod;b>>=1;\n\t}return ans;\n}TY n,a[MAXN],b[MAXN],sum[MAXN],lenx[MAXN],leny[MAXN],ans;\nvector<signed> e1[MAXN],e2[MAXN],HH;\nTY Sum[MAXN],SSum[MAXN];\nbool vis[MAXN];\nsigned L[MAXN],R[MAXN],LL[MAXN],RR[MAXN],ok[MAXN],nxtx[MAXN],nxty[MAXN];\nstruct node{TY l,r,tag,op;};queue<node> q;\nIL void init(TY l,TY r,TY tag){\n    For(i,l,r)e1[i].clear(),e2[i].clear();\n    vector<pair<TY,TY> > pre,nxt;\n    For(i,l,r){\n        while(!pre.empty()){\n            TY ch=(pre.back().second*-1+tag)*(i-pre.back().first)+sum[i]-sum[pre.back().first];\n            if(ch<0){\n                nxtx[pre.back().first]=i;\n                pre.pop_back();continue;\n            }else{\n                lenx[i]=pre.back().second+Ceil(ch+1,i-pre.back().first);\n                pre.push_back({i,pre.back().second+Ceil(ch+1,i-pre.back().first)});\n                break;\n            }\n        }if(pre.empty()){\n            lenx[i]=Ceil(sum[i]-sum[l-1]+tag*(i-l+1)+1,i-l+1);\n            pre.push_back({i,Ceil(sum[i]-sum[l-1]+tag*(i-l+1)+1,i-l+1)});\n        }\n    }while(!pre.empty())nxtx[pre.back().first]=r+1,pre.pop_back();\n    Rof(i,r,l){\n        while(!nxt.empty()){\n            TY ch=(nxt.back().second*-1+tag)*(nxt.back().first-i)-sum[i-1]+sum[nxt.back().first-1];\n            if(ch<0){\n                nxty[nxt.back().first]=i;\n                nxt.pop_back();continue;\n            }else{\n                leny[i]=nxt.back().second+Ceil(ch+1,nxt.back().first-i);\n                nxt.push_back({i,nxt.back().second+Ceil(ch+1,nxt.back().first-i)});\n                break;\n            }\n        }if(nxt.empty()){\n            leny[i]=Ceil(sum[r]-sum[i-1]+tag*(r-i+1)+1,r-i+1);\n            nxt.push_back({i,Ceil(sum[r]-sum[i-1]+tag*(r-i+1)+1,r-i+1)});\n        }\n    }while(!nxt.empty())nxty[nxt.back().first]=l-1,nxt.pop_back();\n    For(i,l,r)if(nxtx[i]!=r+1)e1[nxtx[i]].pb(i);\n    Rof(i,r,l)if(nxty[i]!=l-1)e2[nxty[i]].pb(i);\n}int main(){\n    //freopen(\"data.in\",\"r\",stdin);\n    /* init */\n    n=qr();For(i,1,n)a[i]=qr(),sum[i]=sum[i-1]+a[i];\n    q.push({1,n,0,0});\n    while(!q.empty()){\n        TY l=q.front().l,r=q.front().r,tag=q.front().tag,op=q.front().op;\n        if(l>r||l<=0||r>n)continue;\n        q.pop();\n        if(op==0){\n            vector<pair<TY,TY> > tmp;\n            TY c=0;TY lst=-1;\n            For(i,l,r)b[i]=a[i]+tag;\n            For(i,l,r){\n                if((b[i]>=0)!=lst){\n                    lst=(b[i]>=0);\n                    ++c;L[c]=R[c]=i;\n                    Sum[c]=b[i];\n                }else R[c]=i,Sum[c]+=b[i];\n            }For(i,1,c)LL[i]=i,RR[i]=i,SSum[i]=Sum[i],ok[i]=0,vis[i]=1;\n            Sum[c+1]=0;RR[c+1]=INF;\n            For(i,1,c)if(Sum[i]<0){\n                ok[i]=(Sum[i-1]+Sum[i]>=0)+(Sum[i+1]+Sum[i]>=0);\n                if(ok[i]==2)HH.pb(i),ok[i]=INF;\n            }else{\n                ok[i]=(Sum[i-1]+Sum[i]<0)+(Sum[i+1]+Sum[i]<0);\n                if(ok[i]==2)HH.pb(i),ok[i]=INF;\n            }while(!HH.empty()){\n                TY now=HH.back(),nowL=LL[now],nowR=RR[now];\n                TY k=SSum[nowL]+SSum[nowL-1]+SSum[nowR+1],pre=LL[LL[nowL-1]-1],nxt=RR[nowR+1]+1;\n                HH.pop_back();\n                if(SSum[nowL]>=0){\n                    if(pre>=1&&nxt<=c){\n                        ok[LL[nowL-1]]=(k+SSum[pre]>=0)+(k+SSum[nxt]>=0);\n                        if(ok[LL[nowL-1]]==2)HH.pb(LL[nowL-1]),ok[LL[nowL-1]]=INF;\n                    }else ok[LL[nowL-1]]=INF;\n                    if(pre>=1){\n                        ok[pre]+=-(SSum[nowL-1]+SSum[pre]<0)+(SSum[pre]+k<0);\n                        if(ok[pre]==2&&SSum[nowL-1]+SSum[pre]>=0)HH.pb(pre),ok[pre]=INF;\n                    }if(nxt<=c){\n                        ok[nxt]+=-(SSum[nowR+1]+SSum[nxt]<0)+(SSum[nxt]+k<0);\n                        if(ok[nxt]==2&&SSum[nowR+1]+SSum[nxt]>=0)HH.pb(nxt),ok[nxt]=INF;\n                    }\n                }else{\n                    if(pre>=1&&nxt<=c){\n                        ok[LL[nowL-1]]=(k+SSum[pre]<0)+(k+SSum[nxt]<0);\n                        if(ok[LL[nowL-1]]==2)HH.pb(LL[nowL-1]),ok[LL[nowL-1]]=INF;\n                    }else ok[LL[nowL-1]]=INF;\n                    if(pre>=1){\n                        ok[pre]+=-(SSum[nowL-1]+SSum[pre]>=0)+(SSum[pre]+k>=0);\n                        if(ok[pre]==2&&SSum[nowL-1]+SSum[pre]<0)HH.pb(pre),ok[pre]=INF;\n                    }if(nxt<=c){\n                        ok[nxt]+=-(SSum[nowR+1]+SSum[nxt]>=0)+(SSum[nxt]+k>=0);\n                        if(ok[nxt]==2&&SSum[nowR+1]+SSum[nxt]<0)HH.pb(nxt),ok[nxt]=INF;\n                    }\n                }SSum[LL[nowL-1]]=SSum[RR[nowR+1]]=k;\n                RR[LL[nowL-1]]=RR[nowR+1];\n                LL[RR[nowR+1]]=LL[nowL-1];\n            }Rof(i,c,1)if(Sum[i]>=0&&vis[i]){\n                Rof(j,i,LL[i])vis[j]=0;\n                tmp.pb({L[LL[i]],R[RR[i]]});\n            }Rof(i,tmp.size()-1,0)q.push({tmp[i].first,tmp[i].second,tag,1});\n        }else{\n            if(l==r){\n                ans+=a[l]+tag+1;\n                continue;\n            }queue<TY> fir,sec;\n            init(l,r,tag);\n            For(i,l,r)if(nxtx[i]==r+1)fir.push(i);\n            Rof(i,r,l)if(nxty[i]==l-1)sec.push(i);\n            TY lstl=l,lstr=r,lstcnt=0;\n            while(lstl<lstr){\n                while(!fir.empty()&&(lstl>fir.front()||fir.front()>lstr))fir.pop();\n                while(!sec.empty()&&(lstl>sec.front()||sec.front()>lstr))sec.pop();\n                TY id1=(fir.empty()?INF:fir.front()),id2=(sec.empty()?INF:sec.front());\n                TY cnt1=(id1==INF?INF:lenx[id1]-lstcnt);\n                TY cnt2=(id2==INF?INF:leny[id2]-lstcnt);\n                if(cnt1<=cnt2){\n                    fir.pop();\n                    lstcnt=lenx[id1];\n                    For(j,lstl,id1){FOR(i,0,e2[j].size())sec.push(e2[j][i]);e2[j].clear();}\n                    q.push({lstl,id1,-lstcnt+tag,0});\n                    lstl=id1+1;\n                }else{\n                    sec.pop();\n                    lstcnt=leny[id2];\n                    Rof(j,lstr,id2){FOR(i,0,e1[j].size())fir.push(e1[j][i]);e1[j].clear();}\n                    q.push({id2,lstr,-lstcnt+tag,0});\n                    lstr=id2-1;\n                }\n            }if(lstl==lstr)q.push({lstl,lstl,-lstcnt+tag,1});\n            ans+=lstcnt;\n        }\n    }qw(ans);\n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1869",
    "index": "A",
    "title": "Make It Zero",
    "statement": "During Zhongkao examination, Reycloer met an interesting problem, but he cannot come up with a solution immediately. Time is running out! Please help him.\n\nInitially, you are given an array $a$ consisting of $n \\ge 2$ integers, and you want to change all elements in it to $0$.\n\nIn one operation, you select two indices $l$ and $r$ ($1\\le l\\le r\\le n$) and do the following:\n\n- Let $s=a_l\\oplus a_{l+1}\\oplus \\ldots \\oplus a_r$, where $\\oplus$ denotes the bitwise XOR operation;\n- Then, for all $l\\le i\\le r$, replace $a_i$ with $s$.\n\nYou can use the operation above in any order at most $8$ times in total.\n\nFind a sequence of operations, such that after performing the operations in order, all elements in $a$ are equal to $0$. It can be proven that the solution always exists.",
    "tutorial": "Note that $\\underbrace{x\\oplus x\\oplus \\cdots\\oplus x}_{\\text{even times}}=0,$ So if $r-l+1$ is even, after performing the operation on $[l,r]$ twice, the subarray $a[l;r]$ will all become $0$. When $n$ is even, we can perform the operation on $[1,n]$ twice. When $n$ is odd, we can perform the operation on $[1,n-1]$ twice. After that the array becomes $[0,0,\\ldots,0,a_n]$. Then perform the operation on $[n-1,n]$ twice. Time Complexity: $\\mathcal{O}(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define all(s) s.begin(), s.end()\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\n\nconst int _N = 1e5 + 5;\n\nint T;\n\nvoid solve() {\n\tint n; cin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; i++) cin >> a[i];\n\tif (n & 1) {\n\t\tcout << \"4\" << '\\n';\n\t\tcout << \"1 \" << n - 1 << '\\n';\n\t\tcout << \"1 \" << n - 1 << '\\n';\n\t\tcout << n - 1 << ' ' << n << '\\n';\n\t\tcout << n - 1 << ' ' << n << '\\n';\n\t} else {\n\t\tcout << \"2\" << '\\n';\n\t\tcout << \"1 \" << n << '\\n';\n\t\tcout << \"1 \" << n << '\\n';\n\t}\n\treturn;\n}\n\nint main() {\n\tios::sync_with_stdio(false), cin.tie(0), cout.tie(0);\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 900
  },
  {
    "contest_id": "1869",
    "index": "B",
    "title": "2D Traveling",
    "statement": "Piggy lives on an infinite plane with the Cartesian coordinate system on it.\n\nThere are $n$ cities on the plane, numbered from $1$ to $n$, and the first $k$ cities are defined as major cities. The coordinates of the $i$-th city are $(x_i,y_i)$.\n\nPiggy, as a well-experienced traveller, wants to have a relaxing trip after Zhongkao examination. Currently, he is in city $a$, and he wants to travel to city $b$ by air. You can fly between any two cities, and you can visit several cities in any order while travelling, but the final destination must be city $b$.\n\nBecause of active trade between major cities, it's possible to travel by plane between them for free. Formally, the price of an air ticket $f(i,j)$ between two cities $i$ and $j$ is defined as follows:\n\n$$ f(i,j)= \\begin{cases} 0, & \\text{if cities }i \\text{ and }j \\text{ are both major cities} \\\\ |x_i-x_j|+|y_i-y_j|, & \\text{otherwise} \\end{cases} $$\n\nPiggy doesn't want to save time, but he wants to save money. So you need to tell him the \\textbf{minimum} value of the total cost of all air tickets if he can take any number of flights.",
    "tutorial": "First of all, it's easy to see that if there are no major cities, the minimum value of the total cost should be $|x_a-x_b|+|y_a-y_b|$ - the optimal choice is to fly directly from city $a$ to city $b$. Claim. Piggy will pass through a maximum of $2$ major cities. Proof. If he passes through $3$ or more major cities in a row, then he can fly directly from the first one to the last one. If he passes through $2$ major cities and passes an ordinary city between them, the cost must be higher than flying directly between these two major cities. So the optimal choice always consists of no more than $2$ major cities, and they are in a row. Thus, you can express the optimal choice as $a(\\to s)(\\to t)\\to b$, where $s$ and $t$ are both major cities. If you naively enumerate $s$ and $t$, the total complexity of the solution will be $\\mathcal O(k^2)$. But after seeing that $s$ and $t$ work independently, we can enumerate them separately. The total complexity decreases to $\\mathcal O(n+k)$.",
    "code": "#include <bits/stdc++.h>\n#define all(s) s.begin(), s.end()\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\n\nconst int _N = 1e5 + 5;\n\nint T;\n\nvoid solve() {\n\tint n, k, s, t; cin >> n >> k >> s >> t;\n\tvector<int> x(n + 1), y(n + 1);\n\tfor (int i = 1; i <= n; i++) cin >> x[i] >> y[i];\n\tll ans = llabs(x[s] - x[t]) + llabs(y[s] - y[t]);\n\tll mins = LLONG_MAX / 2, mint = LLONG_MAX / 2;\n\tfor (int i = 1; i <= k; i++) {\n\t\tmins = min(mins, llabs(x[s] - x[i]) + llabs(y[s] - y[i]));\n\t\tmint = min(mint, llabs(x[t] - x[i]) + llabs(y[t] - y[i]));\n\t}\n\tans = min(ans, mins + mint);\n\tcout << ans << '\\n';\n\treturn;\n}\n\nint main() {\n\tios::sync_with_stdio(false), cin.tie(0), cout.tie(0);\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "geometry",
      "math",
      "shortest paths",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1870",
    "index": "A",
    "title": "MEXanized Array",
    "statement": "You are given three non-negative integers $n$, $k$, and $x$. Find the maximum possible sum of elements in an array consisting of non-negative integers, which has $n$ elements, its MEX is equal to $k$, and all its elements do not exceed $x$. If such an array does not exist, output $-1$.\n\nThe MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.",
    "tutorial": "Note that if $min(n, x+1) < k$, then the answer is $-1$. Otherwise, there are two cases: If $k=x$, then the suitable array looks like $[0, 1, 2, \\dots, k-1, \\dots, k-1]$. If $k=x$, then the suitable array looks like $[0, 1, 2, \\dots, k-1, \\dots, k-1]$. If $k \\ne x$, then the suitable array looks like $[0, 1, 2, \\dots, k-1, x, \\dots, x]$. If $k \\ne x$, then the suitable array looks like $[0, 1, 2, \\dots, k-1, x, \\dots, x]$. In both cases, we can construct the array and calculate its sum in linear time. The overall complexity is $O(n \\cdot t)$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1870",
    "index": "B",
    "title": "Friendly Arrays",
    "statement": "You are given two arrays of integers — $a_1, \\ldots, a_n$ of length $n$, and $b_1, \\ldots, b_m$ of length $m$. You can choose any element $b_j$ from array $b$ ($1 \\leq j \\leq m$), and for \\textbf{all} $1 \\leq i \\leq n$ perform $a_i = a_i | b_j$. You can perform any number of such operations.\n\nAfter all the operations, the value of $x = a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n$ will be calculated. Find the minimum and maximum values of $x$ that could be obtained after performing any set of operations.\n\nAbove, $|$ is the bitwise OR operation, and $\\oplus$ is the bitwise XOR operation.",
    "tutorial": "Note that after performing the operation on $b_j$, which has some bit set to 1, this bit will become 1 for all numbers in $a$ (and will remain so, as a bit cannot change from 1 to 0 in the result of an OR operation). If $n$ is even, then in the final XOR, this bit will become 0, as it will be equal to the XOR of an even number of ones. If $n$ is odd, then this bit will be 1 in the final XOR. Therefore, if $n$ is even, by performing the operation on $b_j$, we set all the bits that are 1 in $b_j$ to 0 in the final XOR. If $n$ is odd, we do the opposite and set these bits to 1. So, if $n$ is even, the XOR does not increase when applying the operation, which means that to obtain the minimum possible XOR, we need to apply the operation to all the numbers in $b$, and the maximum XOR will be the original XOR. For odd $n$, it is the opposite: the minimum is the original XOR, and the maximum is obtained after applying the operation to all elements in $b$. To apply the operation to all elements in $b$, it is sufficient to calculate their bitwise OR and apply the operation to the array $a$ with it.",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1870",
    "index": "C",
    "title": "Colorful Table",
    "statement": "You are given two integers $n$ and $k$. You are also given an array of integers $a_1, a_2, \\ldots, a_n$ of size $n$. It is known that for all $1 \\leq i \\leq n$, $1 \\leq a_i \\leq k$.\n\nDefine a two-dimensional array $b$ of size $n \\times n$ as follows: $b_{i, j} = \\min(a_i, a_j)$. Represent array $b$ as a square, where the upper left cell is $b_{1, 1}$, rows are numbered from top to bottom from $1$ to $n$, and columns are numbered from left to right from $1$ to $n$. Let the color of a cell be the number written in it (for a cell with coordinates $(i, j)$, this is $b_{i, j}$).\n\nFor each color from $1$ to $k$, find the smallest rectangle in the array $b$ containing all cells of this color. Output the sum of width and height of this rectangle.",
    "tutorial": "Let's fix the color $x$ for which we will calculate the answer. If there is no $a_i = x$, then there will be no cells of color $x$, and the answer is $0$. Otherwise, there is at least one cell of color $x$. To find the minimum rectangle containing all cells of this color, we need to find the topmost, bottommost, leftmost, and rightmost cells of this color in the array $b$. Let's find the prefix in $a$ of the maximum length, where all numbers are strictly less than $x$. Let the length of this prefix be $L$. Then in the first $L$ rows and columns of the array $b$, there will be no cells of color $x$, because for all these cells, the formula $b_{i, j} = min(a_i, a_j)$ will have a number from the prefix, and all numbers on it are less than $x$. In the $L+1$-th row and $L+1$-th column, there will be cells of color $x$, because $a_{L+1} \\geq x$. Thus, we have found the topmost and leftmost cells of color $x$. To find the bottom and right cells, we need to find the longest suffix where all numbers are less than $x$. Now we need to learn how to quickly find prefixes and suffixes for all colors. Notice that the prefix for color $x$ is not shorter than the prefix for color $x + 1$, so all prefixes can be calculated in just one pass through the array, similarly for suffixes.",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1870",
    "index": "D",
    "title": "Prefix Purchase",
    "statement": "You have an array $a$ of size $n$, initially filled with zeros ($a_1 = a_2 = \\ldots = a_n = 0$). You also have an array of integers $c$ of size $n$.\n\nInitially, you have $k$ coins. By paying $c_i$ coins, you can add $1$ to all elements of the array $a$ from the first to the $i$-th element ($a_j \\mathrel{+}= 1$ for all $1 \\leq j \\leq i$). You can buy any $c_i$ any number of times. A purchase is only possible if $k \\geq c_i$, meaning that at any moment $k \\geq 0$ must hold true.\n\nFind the lexicographically largest array $a$ that can be obtained.\n\nAn array $a$ is lexicographically smaller than an array $b$ of the same length if and only if in the first position where $a$ and $b$ differ, the element in array $a$ is smaller than the corresponding element in $b$.",
    "tutorial": "Note that if there is a prefix for which there is a longer prefix that costs less, then it is useless to buy the shorter prefix. All its purchases can be replaced with purchases of the longer prefix, and the answer will only improve. Therefore, we can replace each $c_i$ with the minimum $c_j$ among $i \\leq j \\leq n$ (the minimum price of a prefix of length at least $i$). After this, we will have $c_i \\leq c_{i+1}$. Now let's solve the problem greedily. We want to maximize the first element of the resulting array. It will be equal to $k / c_1$, since we cannot buy more prefixes of length $1$ ($c_1$ is the smallest price). After buying $k / c_1$ prefixes of length $1$, we will have some coins left. Now we can replace some purchases of $c_1$ with purchases of longer prefixes to improve the answer. How much will it cost to replace $c_1$ with $c_i$? It will cost $c_i - c_1$ coins. Moreover, note that to replace $c_1$ with $c_i$, we can sequentially replace $c_1$ with $c_2$, $c_2$ with $c_3$, $\\ldots$, $c_{i-1}$ with $c_i$ (since $c_1 \\leq c_2 \\leq \\ldots \\leq c_i$). This means that we can make only replacements of purchases of $c_{i-1}$ with purchases of $c_i$. Let's say we have maximized the first $i-1$ elements of the answer, and we have $x$ coins left. Now we want to replace some purchases of $c_{i-1}$ with $c_i$. How many replacements can we make? We can afford to make no more than $\\frac{x}{c_i - c_{i-1}}$ replacements (if $c_{i-1} = c_i$, then we can replace all $c_{i-1}$), and we cannot replace more purchases than we have made, so no more than $a_{i-1}$ replacements (this is the number of purchases of $c_{i-1}$). Therefore, $a_i = \\min(a_{i-1}, \\frac{x}{c_i - c_{i-1}})$, as we want to maximize $a_i$. Finally, subtract the cost of replacements from the number of coins and move on to $c_{i+1}$.",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1870",
    "index": "E",
    "title": "Another MEX Problem",
    "statement": "You are given an array of integers $a$ of size $n$. You can choose a set of non-overlapping subarrays of the given array (note that some elements may be not included in any subarray, this is allowed). For each selected subarray, calculate the MEX of its elements, and then calculate the bitwise XOR of all the obtained MEX values. What is the maximum bitwise XOR that can be obtained?\n\nThe MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.",
    "tutorial": "Let's solve the problem using dynamic programming, let's store $dp[i][j]$ such that $dp[i][j]=1$ if it is possible to obtain an $XOR$ of $MEX$ values from the prefix up to $i$ (excluding $i$) equal to $j$, and $0$ otherwise. Notice that the answer cannot be greater than $n$. Therefore, the size of this two-dimensional array is $O(n^2)$. Let's learn how to solve this in $O(n^3)$: We iterate over $l$ from $1$ to $n$, and inside that, we iterate over $r$ from $l$ to $n$, maintaining the value $x=MEX([a_l, a_{l+1}, \\dots, a_r])$. Then, for all $j$ from $0$ to $n$, we update $dp[r+1][j \\oplus x]=1$ if $dp[l][j]=1$. This way, we update based on the case when the resulting set includes the set $[a_l, a_{l+1}, \\dots, a_r]$. We also need to update if $dp[l][x]=1$, we assign $dp[l+1][x]=1$. This accounts for the case when we do not include $a_l$ in the answer. Let's define $MEX(l, r) = MEX([a_l, a_{l+1}, \\dots, a_r])$, this will make the following text clearer. Let's consider the segment $l, r$. Notice that if there exist $l_2$ and $r_2$ ($l \\leq l_2 \\leq r_2 \\leq r$) such that $l_2 \\ne l$ or $r_2 \\ne r$ and $MEX(l, r)=MEX(l_2, r_2)$, then we can take the segment $l_2, r_2$ instead of the segment $l, r$ in the set of $MEX$ values, and the answer will remain the same. If, however, there is no such segment $l_2, r_2$ for the segment $l, r$, then we call this segment $l, r$ irreplaceable. Now let's prove that there are no more than $n \\cdot 2$ irreplaceable segments. For each irreplaceable segment, let's look at the larger element of the pair $a_l, a_r$, let's assume $a_l$ is larger (the other case is symmetric). Now, let's prove that there is at most one segment where $a_l$ is the left element and $a_l \\geq a_r$, by contradiction: Suppose there are at least 2 such segments, let's call their right boundaries $r_1, r_2$ ($r_1 < r_2$). Notice that $MEX(l, r_1) > a_l$, otherwise the segment $l, r_1$ would not be irreplaceable (we could remove $a_l$). Since $a_l \\geq a_{r_2}$, then $MEX(l, r_1) > a_{r_2}$. It is obvious that $a_{r_2}$ appears among the elements $[a_l, \\dots, a_{r_1}]$, and therefore $MEX(l, r_2-1) = MEX(l, r_2)$, which means that the segment $l, r_2$ is not irreplaceable, contradiction. For each $a_i$, there is at most one irreplaceable segment where it is the smaller of the two extremes, and at most one where it is the larger. Therefore, the total number of irreplaceable segments is no more than $2 \\cdot n$. Let's update the DP only through the irreplaceable segments, then the solution works in $O(n^2+n \\cdot C)$ time, where $C$ is the number of irreplaceable segments. However, we have already proven that $C\\leq 2n$, so the overall time complexity is $O(n^2)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1870",
    "index": "F",
    "title": "Lazy Numbers",
    "statement": "You are given positive integers $n$ and $k$. For each number from $1$ to $n$, we write its representation in the number system with base $k$ (without leading zeros) and then sort the resulting array in lexicographic order as strings. In the sorted array, we number the elements from $1$ to $n$ (i.e., indexing starts from $1$). Find the number of values $i$ such that the representation of number $i$ is at the $i$-th position in the sorted array of representations.\n\nExamples of representations: $1$ in any number system is equal to $1$, $7$ with $k = 3$ is written as $21$, and $81$ with $k = 9$ is written as $100$.",
    "tutorial": "Let's store all the number entries in a trie. Consider two traversals of this trie - depth-first search (DFS) and breadth-first search (BFS). In both traversals, we go to the children of a node in ascending order of the number on the edge (in the trie). Let the index of the node representing the number $x$ in the DFS traversal be $dfs(x)$, and in the BFS traversal be $bfs(x)$. Then notice that $x = bfs(x)$, as in BFS on the trie, we simply look at all the number entries with a certain length in order (lengths are concidered in increasing order). On the other hand, $dfs(x)$ is the index of the number entry $x$ in the sorted array. Therefore, we want to calculate the number of $x$ for which $dfs(x) = bfs(x)$. Let's fix a layer in the trie, meaning we only consider numbers with a fixed, equal length of representation. Then let's look at $dfs(x) - bfs(x)$ for the numbers in this layer. Notice that for two numbers $y$ and $y + 1$ in this layer, it holds that $bfs(y + 1) - bfs(y) = 1$, and $dfs(y + 1) - dfs(y) \\geq 1$. This means that for a fixed layer, the function $dfs(x) - bfs(x)$ is non-decreasing. Therefore, we can find the $0$ of this function using binary search on each layer. Now let's learn how to calculate $dfs(x) - bfs(x)$. $bfs(x) = x$, which we can calculate. To find $dfs(x)$, we can traverse up from the trie node corresponding to $x$, and at each step, add the sizes of the subtrees that we have traversed in DFS before the subtree with the node $x$. The trie has a depth of $O(\\log(n))$, binary search takes the same time, so the overall asymptotic complexity of the solution is $O(\\log^3(n))$. I apologize for the issues some participants faced with the time limit, if they implemented the author's idea suboptimally.",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1870",
    "index": "G",
    "title": "MEXanization",
    "statement": "Let's define $f(S)$. Let $S$ be a multiset (i.e., it can contain repeated elements) of non-negative integers. In one operation, you can choose any non-empty subset of $S$ (which can also contain repeated elements), remove this subset (all elements in it) from $S$, and add the MEX of the removed subset to $S$. You can perform any number of such operations. After all the operations, $S$ should contain exactly $1$ number. $f(S)$ is the largest number that could remain in $S$ after any sequence of operations.\n\nYou are given an array of non-negative integers $a$ of length $n$. For each of its $n$ prefixes, calculate $f(S)$ if $S$ is the corresponding prefix (for the $i$-th prefix, $S$ consists of the first $i$ elements of array $a$).\n\nThe MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.",
    "tutorial": "Let's start by introducing a more convenient way to store numbers - an array $cnt$, where $cnt[x]$ represents the number of occurrences of $x$ in the prefix for which we are finding the answer. All $x$ such that $x > n$ will be added to $cnt[0]$ because applying the operation to ${x}$ in such cases is optimal. Let's introduce a few array operations that will be sufficient to solve the problem. Create the number $x$. Apply the operation to the set of numbers ${0, 1, 2, \\dots, x-1}$. In terms of the array $cnt$, this is equivalent to subtracting $1$ from the range $0$ to $x-1$ and adding $1$ to $cnt[x]$. Turn the number $x$ into $0$. To do this, apply the operation to ${x}$. In terms of the array $cnt$, this is equivalent to subtracting $1$ from $cnt[x]$ and adding $1$ to $cnt[0]$. Create the number $x$ and clear the multiset. This is the same as creating the number $x$, but we apply the operation to all other numbers, leaving only the single number $x$ (or a larger number) in the set. It can be proven that by using only operations of this kind, we can always obtain the optimal answer. Now we can forget about the original condition and solve the problem for the array. Let's learn how to check if it is possible to create the number $k$ and clear the multiset: First, let's try to create the number $k$. If it is possible, the answer is yes. Otherwise, we look at the rightmost number that is missing (or in other words, the rightmost $0$). We try to create it, and now we need to find the rightmost element $\\leq 1$ to the left of it, and so on. To implement this, we need to maintain a number $p$ such that we subtract $p$ from all elements in the prefix (initially $p=1$), iterate through the array from right to left, and if $cnt[i]<p$, assign $p \\mathrel{{+}{=}} (p-cnt[i])$. When we reach zero, $p$ may be greater than $cnt[0]$, in which case we need to use the operation to turn any number into $0$. To do this, simply check that the remaining number of elements in the array is greater than or equal to $p$. This currently works in $O(k)$ time, which is not very efficient. Optimization techniques: First, let's maintain the sum of elements $sm$ and as soon as it becomes negative, terminate the process. To achieve this, when subtracting $p-cnt[i]$ from $p$, let's subtract $(p-cnt[i])\\cdot(i-1)$ from $sm$. Now let's use a bottom-up segment tree to find the nearest number smaller than $p$ to the left in $O(\\log(i))$ time. Now let's notice that when we update through $cnt[i]$, we subtract at least $i-1$ from $sm$, so there can't be more than $O(\\sqrt{n})$ different values of $i$ through which we will update. Now we can answer for a specific $k$ in $O(\\sqrt{n} \\cdot \\log(n))$ time, but in reality, the complexity is $O(\\sqrt{n})$ (due to the peculiarities of the bottom-up segment tree), and the authors have a proof for this, but they are afraid that you will find an error in it, so they decided not to provide it(we will add proof later). Now let's see how to solve the full problem: Initially, the answer is $0$, and we notice that it does not decrease. So after each addition, we will check if it is possible to increase the answer and increase it as long as possible. The answer cannot exceed $n$, so we will perform no more than $2 \\cdot n$ checks. Overall, the solution works in $O(n \\cdot \\sqrt{n})$ time. That's how it is. Let's consider that in our query, the segment tree processed $k$ nodes $[x_1, x_2, \\dots, x_k]$ from the bottom. Then, the number of operations is the sum of $dist(x_i, x_{i+1})$ for $i$ from 1 to $k-1$, and $dist(0, x_1)$, where $dist$ represents the length of the path between nodes in the segment tree. Now, let's notice that for the query $dist(a, b)$, we enter the segment tree node responsible for a block of length $2^t$ only if $a$ and $b$ are in different blocks of length $2^{t-1}$, which is logical. Also, let's notice that this doesn't happen very often, specifically, the numbers $[x_1, x_2, \\dots, x_k]$ can be part of a maximum of $\\sqrt{\\frac{n}{2^t}}$ blocks of length $2^t$ (asymptotically). Therefore, the sum of all queries is asymptotically equal to the sum of $\\sqrt{\\frac{n}{2^t}}$ for $t$ from 0 to 20, which is a geometric progression with a ratio of $\\frac{1}{\\sqrt{2}}$. Hence, the sum is asymptotically equal to $\\sqrt{n}$. Proof completed.",
    "tags": [
      "data structures"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1870",
    "index": "H",
    "title": "Standard Graph Problem",
    "statement": "You are given a weighted directed graph with $n$ vertices and $m$ edges. Each vertex in the graph can be either highlighted or normal. Initially, all vertices are normal. The cost of the graph is defined as the minimum sum of edge weights that need to be selected so that from each normal vertex one can reach at least one highlighted vertex using the selected edges only. If it is not possible to select the edges, the cost is $-1$ instead.\n\nYour task is to compute the cost of the graph after each of the $q$ queries. The queries can be of two types:\n\n- $+\\;v_i$ makes vertex $v_i$ highlighted; it is guaranteed that the vertex is normal before the query.\n- $-\\;v_i$ makes vertex $v_i$ normal; it is guaranteed that the vertex is highlighted before the query.\n\nOutput the cost of the graph after each of the $q$ queries.",
    "tutorial": "Let's unfold all the edges, now we need to ensure that all regular vertices are reachable from the selected vertices. First, you should familiarize yourself with the algorithm for finding the ordered minimum spanning tree, also known as the Edmonds' algorithm (I will refer to his work here and without knowledge of it, the solution cannot be understood). Next, it is worth noting that the compressions in the process of this algorithm (almost) do not depend on the root, and all compressions can be performed as if there is no root (previously creating dummy edges from $i$ to $i+1$ for $i$ from $1$ to $n-1$ and from vertex $n$ to vertex $1$ with a cost of $n * max(a_i)+1$). Then, after all the compressions, only one vertex will remain. Note that the difference from Edmonds' algorithm is that if at any step of the algorithm the minimum edge from a vertex leads to the root, compression is not necessary. So, let's maintain a tree in which each vertex corresponds to its corresponding compressed vertex or to the original vertex, and the children of vertex $v$ are all the vertices that we compressed to obtain vertex $v$. It is implied that with each compression, we create a new vertex. Let's call the cost of vertex $v$ the minimum cost of an edge leaving vertex $v$ in the process of Edmonds' algorithm (taking into account changes in edge costs during compression in Edmonds' algorithm). Then we need to maintain the sum of the costs of the vertices in the tree, in the subtrees of which there are no selected vertices (where the selected vertices can only be leaves). This can be easily done using a segment tree.",
    "tags": [
      "data structures",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1872",
    "index": "A",
    "title": "Two Vessels",
    "statement": "You have two vessels with water. The first vessel contains $a$ grams of water, and the second vessel contains $b$ grams of water. Both vessels are very large and can hold any amount of water.\n\nYou also have an empty cup that can hold \\textbf{up to} $c$ grams of water.\n\nIn one move, you can scoop \\textbf{up to} $c$ grams of water from any vessel and pour it into \\textbf{the other} vessel. Note that the mass of water poured in one move \\textbf{does not have to be an integer}.\n\nWhat is the minimum number of moves required to make the masses of water in the vessels equal? Note that you cannot perform any actions other than the described moves.",
    "tutorial": "Let $d = a - b$, the difference in masses of water in the vessels. Our goal is to make $d$ equal to $0$. Note that with one pouring, we can add any number from the range $[-2 \\cdot c; 2 \\cdot c]$ to $d$. Therefore, the answer to the problem will be $\\lceil \\frac{|d|}{2 \\cdot c} \\rceil$.",
    "code": "for _ in range(int(input())):\n    a, b, c = map(int, input().split())\n    print((abs(a - b) + 2 * c - 1) // (2 * c))",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1872",
    "index": "B",
    "title": "The Corridor or There and Back Again",
    "statement": "You are in a corridor that extends infinitely to the right, divided into square rooms. You start in room $1$, proceed to room $k$, and then return to room $1$. You can choose the value of $k$. Moving to an adjacent room takes $1$ second.\n\nAdditionally, there are $n$ traps in the corridor: the $i$-th trap is located in room $d_i$ and will be activated $s_i$ seconds \\textbf{after you enter the room} $\\boldsymbol{d_i}$. Once a trap is activated, you cannot enter or exit a room with that trap.\n\n\\begin{center}\n{\\small A schematic representation of a possible corridor and your path to room $k$ and back.}\n\\end{center}\n\nDetermine the maximum value of $k$ that allows you to travel from room $1$ to room $k$ and then return to room $1$ safely.\n\nFor instance, if $n=1$ and $d_1=2, s_1=2$, you can proceed to room $k=2$ and return safely (the trap will activate at the moment $1+s_1=1+2=3$, it can't prevent you to return back). But if you attempt to reach room $k=3$, the trap will activate at the moment $1+s_1=1+2=3$, preventing your return (you would attempt to enter room $2$ on your way back at second $3$, but the activated trap would block you). Any larger value for $k$ is also not feasible. Thus, the answer is $k=2$.",
    "tutorial": "Let's see when we can reach room $k$ and return back. In this case, the time difference between entering and exiting room $1 \\le x \\le k$ is equal to $2 \\cdot (k - x)$. Therefore, it is necessary for all traps to satisfy: $s_i > 2 \\cdot (k - d_i)$. Now we need to find the maximum $k$ that satisfies these conditions. To do this, we can either iterate through all $k$ from $1$ to $300$, or use binary search for the answer, or notice that $s_i > 2 \\cdot (k - d_i) \\to s_i + 2 \\cdot d_i > 2 \\cdot k \\to d_i + \\frac{s_i}{2} > k \\to d_i + \\frac{s_i - 1}{2} \\geq k$",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    ans = 2 * 10 ** 9\n    for i in range(n):\n        d, s = map(int, input().split())\n        ans = min(ans, d + (s - 1) // 2)\n    print(ans)",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1872",
    "index": "C",
    "title": "Non-coprime Split",
    "statement": "You are given two integers $l \\le r$. You need to find \\textbf{positive} integers $a$ and $b$ such that the following conditions are simultaneously satisfied:\n\n- $l \\le a + b \\le r$\n- $\\gcd(a, b) \\neq 1$\n\nor report that they do not exist.\n\n$\\gcd(a, b)$ denotes the greatest common divisor of numbers $a$ and $b$. For example, $\\gcd(6, 9) = 3$, $\\gcd(8, 9) = 1$, $\\gcd(4, 2) = 2$.",
    "tutorial": "To begin with, let's learn how to solve the problem when $l = r$. In other words, we need to find a value $1 \\le a < l$ such that $\\gcd(a, l - a) \\neq 1$. Notice that $\\gcd(a, l - a) = \\gcd(a, l)$. Then it is easy to see that if $l$ is prime, then $\\gcd(a, l) = 1$ for any $1 \\le a < l$, otherwise any divisor of $l$ (except $1$ and $l$) will work as $a$. Thus, we can solve the problem when $l = r$ using the standard algorithm for primality testing in $O(\\sqrt{r})$ time. Next, we can solve the problem in several ways: Sequentially check for primality all numbers from $l$ to $r$, and stop and output the answer as soon as we find the first composite number. This works faster than $O(r \\sqrt r)$ because there are no two adjacent prime numbers starting from $3$, so the answer will be found very quickly. Handle the case $l = r$ separately. Also, separately consider the case $r \\le 3$, in which the answer is $-1$. Otherwise, notice that since there are at least $2$ numbers in the interval $[l, r]$, there must be an even number in this interval. And for $r \\ge 4$, the maximum even number in the interval, $s$, will be $\\ge 4$, so for example, $a = \\frac{s}{2}, b = \\frac{s}{2}$ will be a valid answer. To find the maximum even number in the interval $l < r$, we can use the formula $r - r \\% 2$.",
    "code": "def min_divisor(n):\n    for d in range(2, round(n ** 0.5) + 1):\n        if n % d == 0:\n            return d\n    return n\n \n \nfor _ in range(int(input())):\n    l, r = map(int, input().split())\n    for x in range(l, r + 1):\n        md = min_divisor(x)\n        if md != x:\n            print(md, x - md)\n            break\n    else:\n        print(-1)",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1872",
    "index": "D",
    "title": "Plus Minus Permutation",
    "statement": "You are given $3$ integers — $n$, $x$, $y$. Let's call the score of a permutation$^\\dagger$ $p_1, \\ldots, p_n$ the following value:\n\n$$(p_{1 \\cdot x} + p_{2 \\cdot x} + \\ldots + p_{\\lfloor \\frac{n}{x} \\rfloor \\cdot x}) - (p_{1 \\cdot y} + p_{2 \\cdot y} + \\ldots + p_{\\lfloor \\frac{n}{y} \\rfloor \\cdot y})$$\n\nIn other words, the score of a permutation is the sum of $p_i$ for all indices $i$ divisible by $x$, minus the sum of $p_i$ for all indices $i$ divisible by $y$.\n\nYou need to find the maximum possible score among all permutations of length $n$.\n\nFor example, if $n = 7$, $x = 2$, $y = 3$, the maximum score is achieved by the permutation $[2,\\textcolor{red}{\\underline{\\color{black}{6}}},\\textcolor{blue}{\\underline{\\color{black}{1}}},\\textcolor{red}{\\underline{\\color{black}{7}}},5,\\textcolor{blue}{\\underline{\\color{red}{\\underline{\\textcolor{black}{4}}}}},3]$ and is equal to $(6 + 7 + 4) - (1 + 4) = 17 - 5 = 12$.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation (the number $2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$, but the array contains $4$).",
    "tutorial": "Let's call a number red if it is divisible by $x$. Let's call a number blue if it is divisible by $y$. Let's call a number purple if it is both red and blue at the same time. The score of a permutation, by definition, is the sum of $p_i$ for all red numbers $i$ from $1$ to $n$, minus the sum of $p_i$ for all blue numbers $i$ from $1$ to $n$. It is easy to see that $p_i$ at purple indices $i$ does not affect the score of the permutation: they are included in the sum once with a plus sign and once with a minus sign. Therefore, the score of the permutation is the sum of $p_i$ for \"red but not purple indices\" minus the sum of $p_i$ for \"blue but not purple indices\". Notice that the set of \"red but not purple indices\" and the set of \"blue but not purple indices\" cannot intersect, because if they had a common index, it would be purple. Therefore, it is obviously optimal to place the largest numbers possible on \"red but not purple indices\" and the smallest numbers possible on \"blue but not purple indices\". To calculate the number of indices that are \"red but not purple\", we can calculate the number of red indices and subtract the number of purple indices. The number of red indices is $\\lfloor \\frac{n}{x} \\rfloor$, and the number of blue indices is calculated similarly. To calculate the number of purple indices, we need to notice that the condition \"index is divisible by both $x$ and $y$\" is equivalent to \"index is divisible by $\\operatorname{lcm}(x, y)$\", where $\\operatorname{lcm}$ denotes the least common multiple. Therefore, the number of purple indices is $\\lfloor \\frac{n}{\\operatorname{lcm}(x, y)} \\rfloor$. Let $R$ be the number of \"red but not purple\" indices, and let $B$ be the number of \"blue but not purple\" indices. Then it is not difficult to see that the maximum score is $(n + (n - 1) + \\ldots + (n - (R - 1)) - (1 + 2 + \\ldots + B)$. To quickly find this sum, we can use the formula for the sum of an arithmetic progression: $l + (l + 1) + \\ldots + r = \\frac{(l + r) \\cdot (r - l + 1)}{2}$",
    "code": "from math import gcd\n \n \ndef lcm(a, b):\n    return a * b // gcd(a, b)\n \n \ndef range_sum(l, r):\n    if l > r:\n        return 0\n    return (l + r) * (r - l + 1) // 2\n \n \nfor _ in range(int(input())):\n    n, x, y = map(int, input().split())\n    l = lcm(x, y)\n    plus = n // x - n // l\n    minus = n // y - n // l\n    print(range_sum(n - plus + 1, n) - range_sum(1, minus))",
    "tags": [
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1872",
    "index": "E",
    "title": "Data Structures Fan",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$, as well as a binary string$^{\\dagger}$ $s$ consisting of $n$ characters.\n\nAugustin is a big fan of data structures. Therefore, he asked you to implement a data structure that can answer $q$ queries. There are two types of queries:\n\n- \"1 $l$ $r$\" ($1\\le l \\le r \\le n$) — replace each character $s_i$ for $l \\le i \\le r$ with its opposite. That is, replace all $0$ with $1$ and all $1$ with $0$.\n- \"2 $g$\" ($g \\in \\{0, 1\\}$) — calculate the value of the bitwise XOR of the numbers $a_i$ for all indices $i$ such that $s_i = g$. Note that the $\\operatorname{XOR}$ of an empty set of numbers is considered to be equal to $0$.\n\nPlease help Augustin to answer all the queries!\n\nFor example, if $n = 4$, $a = [1, 2, 3, 6]$, $s = 1001$, consider the following series of queries:\n\n- \"2 $0$\" — we are interested in the indices $i$ for which $s_i = \\tt{0}$, since $s = \\tt{1001}$, these are the indices $2$ and $3$, so the answer to the query will be $a_2 \\oplus a_3 = 2 \\oplus 3 = 1$.\n- \"1 $1$ $3$\" — we need to replace the characters $s_1, s_2, s_3$ with their opposites, so before the query $s = \\tt{1001}$, and after the query: $s = \\tt{0111}$.\n- \"2 $1$\" — we are interested in the indices $i$ for which $s_i = \\tt{1}$, since $s = \\tt{0111}$, these are the indices $2$, $3$, and $4$, so the answer to the query will be $a_2 \\oplus a_3 \\oplus a_4 = 2 \\oplus 3 \\oplus 6 = 7$.\n- \"1 $2$ $4$\" — $s = \\tt{0111}$ $\\to$ $s = \\tt{0000}$.\n- \"2 $1$\" — $s = \\tt{0000}$, there are no indices with $s_i = \\tt{1}$, so since the $\\operatorname{XOR}$ of an empty set of numbers is considered to be equal to $0$, the answer to this query is $0$.\n\n$^{\\dagger}$ A binary string is a string containing only characters $0$ or $1$.",
    "tutorial": "Of course this problem has solutions that use data structures. For example, you can use a segment tree with range updates to solve it in $O((n + q) \\log n)$ time, or you can use a square root decomposition to solve it in $O((n + q) \\sqrt{n})$ time. However, of course, we do not expect participants in Div3 to have knowledge of these advanced data structures, so there is a simpler solution. We will store 2 variables: $X_0, X_1$, which represent the XOR of all numbers from group $0$ and group $1$, respectively. When answering a query of type 2, we will simply output either $X_0$ or $X_1$. Now we need to understand how to update $X_0$ and $X_1$ after receiving a query of type 1. Let's first solve a simplified version: suppose that in type 1 queries, only a single character of the string $s$ is inverted, i.e., $l = r$ in all type 1 queries. Let's see how $X_0$ and $X_1$ change after this query. If $s_i$ was $0$ and became $1$, then the number $a_i$ will be removed from group $0$. So, we need to invert \"XOR $a_i$\" from $X_0$. Since XOR is its own inverse operation ($w \\oplus w = 0$), we can do this with $X_0 = X_0 \\oplus a_i$. And in $X_1$, we need to add the number $a_i$, since now $s_i = 1$. And we can do this with $X_1 = X_1 \\oplus a_i$. The same thing happens if $s_i$ was $1$. This is the key observation: when we invert $s_i$, $X_0$ and $X_1$ change in the same way, regardless of whether this inversion was from $0$ to $1$ or from $1$ to $0$. Therefore, to update $X_0$ and $X_1$ after a query of type 1 with parameters $l, r$, we need to do this: $X_0 = X_0 \\oplus (a_l \\oplus \\ldots \\oplus a_r)$, and the same for $X_1$. To quickly find the XOR value on a subsegment of the array $a$, we can use a prefix XOR array. If $p_i = a_1 \\oplus \\ldots a_i$, then: $a_l \\oplus \\ldots \\oplus a_r = p_r \\oplus p_{l-1}$.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    s = input()\n    q = int(input())\n    ans = [0, 0]\n    a = [0] + a\n    s = '0' + s\n    pref = [0] * (n + 1)\n    for i in range(1, n + 1):\n        ans[int(s[i])] ^= a[i]\n        pref[i] = pref[i - 1] ^ a[i]\n    massxor = 0\n    for __ in range(q):\n        query = list(map(int, input().split()))\n        tp = query[0]\n        if tp == 1:\n            l = query[1]\n            r = query[2]\n            massxor ^= pref[r] ^ pref[l - 1]\n        else:\n            g = query[1]\n            print(massxor ^ ans[g])",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1872",
    "index": "F",
    "title": "Selling a Menagerie",
    "statement": "You are the owner of a menagerie consisting of $n$ animals numbered from $1$ to $n$. However, maintaining the menagerie is quite expensive, so you have decided to sell it!\n\nIt is known that each animal is afraid of exactly one other animal. More precisely, animal $i$ is afraid of animal $a_i$ ($a_i \\neq i$). Also, the cost of each animal is known, for animal $i$ it is equal to $c_i$.\n\nYou will sell all your animals in some fixed order. Formally, you will need to choose some permutation$^\\dagger$ $p_1, p_2, \\ldots, p_n$, and sell animal $p_1$ first, then animal $p_2$, and so on, selling animal $p_n$ last.\n\nWhen you sell animal $i$, there are two possible outcomes:\n\n- If animal $a_i$ was sold \\textbf{before} animal $i$, you receive $c_i$ money for selling animal $i$.\n- If animal $a_i$ was \\textbf{not} sold \\textbf{before} animal $i$, you receive $2 \\cdot c_i$ money for selling animal $i$. (Surprisingly, animals that are currently afraid are more valuable).\n\nYour task is to choose the order of selling the animals in order to maximize the total profit.\n\nFor example, if $a = [3, 4, 4, 1, 3]$, $c = [3, 4, 5, 6, 7]$, and the permutation you choose is $[4, 2, 5, 1, 3]$, then:\n\n- The first animal to be sold is animal $4$. Animal $a_4 = 1$ was not sold before, so you receive $2 \\cdot c_4 = 12$ money for selling it.\n- The second animal to be sold is animal $2$. Animal $a_2 = 4$ was sold before, so you receive $c_2 = 4$ money for selling it.\n- The third animal to be sold is animal $5$. Animal $a_5 = 3$ was not sold before, so you receive $2 \\cdot c_5 = 14$ money for selling it.\n- The fourth animal to be sold is animal $1$. Animal $a_1 = 3$ was not sold before, so you receive $2 \\cdot c_1 = 6$ money for selling it.\n- The fifth animal to be sold is animal $3$. Animal $a_3 = 4$ was sold before, so you receive $c_3 = 5$ money for selling it.\n\nYour total profit, with this choice of permutation, is $12 + 4 + 14 + 6 + 5 = 41$. Note that $41$ is \\textbf{not} the maximum possible profit in this example.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$, but $4$ is present in the array).",
    "tutorial": "Simple greedy observation: if at some point in time there exists an animal $i$ such that no one fears it (there is no index $a_j = i$), then it is optimal to sell that animal first. Let's iteratively sell such animals as long as they exist. After selling animal $i$, we must additionally check if animal $a_i$ has become such that no one fears it, and if so, add it to the list for sale. What will we get when we sell all such animals? Note that when there are no such animals left, $a_i$ will form a permutation, as each animal must be feared by at least one other animal. As it is known, a permutation consists of cycles of the form $i \\to a_i \\to a_{a_i} \\to \\ldots \\to i$. Obviously, for each cycle we must solve the problem independently, and then combine the answers in any order. Note that if we sell animals in the order of the cycle, we will only receive a single payment for the last animal sold. At the same time, it is not possible to obtain double payment for all animals in any case: the last animal sold from the cycle will always be sold for a single payment. Therefore, it is optimal to sell all animals in the order of the cycle so that the animal with the minimum cost ends up being the last in this order. You can see the implementation details in the code.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    c = list(map(int, input().split()))\n    sons = [0] * n\n    for i in range(n):\n        a[i] -= 1\n        sons[a[i]] += 1\n    q = []\n    for i in range(n):\n        if sons[i] == 0:\n            q.append(i)\n    ans = []\n    added = [0] * n\n    while q:\n        v = q.pop()\n        ans.append(v)\n        added[v] = 1\n        sons[a[v]] -= 1\n        if sons[a[v]] == 0:\n            q.append(a[v])\n    for v in range(n):\n        if not added[v]:\n            v2 = a[v]\n            cycle = [v]\n            while v2 != v:\n                cycle.append(v2)\n                v2 = a[v2]\n            minc = 10 ** 9\n            for u in cycle:\n                added[u] = 1\n                minc = min(minc, c[u])\n            for i in range(len(cycle)):\n                if c[cycle[i]] == minc:\n                    ans += cycle[i + 1:]\n                    ans += cycle[:i + 1]\n                    break\n    print(*map(lambda x: x + 1, ans))",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1872",
    "index": "G",
    "title": "Replace With Product",
    "statement": "Given an array $a$ of $n$ positive integers. You need to perform the following operation \\textbf{exactly} once:\n\n- Choose $2$ integers $l$ and $r$ ($1 \\le l \\le r \\le n$) and replace the subarray $a[l \\ldots r]$ with the single element: the product of all elements in the subarray $(a_l \\cdot \\ldots \\cdot a_r)$.\n\nFor example, if an operation with parameters $l = 2, r = 4$ is applied to the array $[5, 4, 3, 2, 1]$, the array will turn into $[5, 24, 1]$.\n\nYour task is to maximize the sum of the array after applying this operation. Find the optimal subarray to apply this operation.",
    "tutorial": "Key observation: if the product of all elements in the array is sufficiently large, it is always optimal to perform the operation on the entire array, except for a possible prefix/suffix consisting of ones. You can estimate sufficiently large, for example, with the number $2^{60}$ (in reality, $2 \\cdot n$ will be sufficient). There won't be a proof, but that's how it is. Now the problem reduces to the case where the product of the array is not greater than $2^{60}$. This means that the number of array elements that are $> 1$ is at most $60$. Notice that in an optimal segment, there won't be a situation where the left/right element is equal to $1$, because then we can move that boundary and the sum will increase by $1$. Therefore, both the start and end of the segment must be in non-ones elements. This means that there are at most $60^2$ interesting segment options. We can explicitly iterate through all of them and choose the best one. Use prefix products and sums to quickly estimate the value of a specific segment.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    MAXP = 2 * n\n    prod = 1\n    for x in a:\n        prod *= x\n        if prod > MAXP:\n            break\n    if prod > MAXP:\n        l = 0\n        r = n - 1\n        while l < n and a[l] == 1:\n            l += 1\n        while r >= 0 and a[r] == 1:\n            r -= 1\n        print(l + 1, r + 1)\n        continue\n    not1 = []\n    for i in range(n):\n        if a[i] > 1:\n            not1.append(i)\n    maxval = 0\n    l = 0\n    r = 0\n    for x in range(len(not1)):\n        p = 1\n        s = 0\n        for y in range(x, len(not1)):\n            i = not1[x]\n            j = not1[y]\n            p *= a[j]\n            s += a[j] - 1\n            if maxval <= p - s - (j - i + 1):\n                maxval = p - s - (j - i + 1)\n                l = i\n                r = j\n    print(l + 1, r + 1)",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1873",
    "index": "A",
    "title": "Short Sort",
    "statement": "There are three cards with letters $a$, $b$, $c$ placed in a row in some order. You can do the following operation \\textbf{at most once}:\n\n- Pick two cards, and swap them.\n\nIs it possible that the row becomes $abc$ after the operation? Output \"YES\" if it is possible, and \"NO\" otherwise.",
    "tutorial": "There are only $6$ possible input strings, and they are all given in the input, so you can just output NO if $s$ is $\\texttt{bca}$ or $\\texttt{cab}$ and YES otherwise. Another way to solve it is to count the number of letters in the wrong position. A swap changes $2$ letters, so if at most two letters are in the wrong position, then it's possible, otherwise it's not possible. Of course, you can also brute force all possible swaps and check if it works.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nstring alph = \"abc\";\n \nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tint cnt = 0;\n\tfor (int i = 0; i < 3; i++) {\n\t\tcnt += (s[i] != alph[i]);\n\t}\n\tcout << (cnt <= 2 ? \"YES\\n\" : \"NO\\n\");\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1873",
    "index": "B",
    "title": "Good Kid",
    "statement": "Slavic is preparing a present for a friend's birthday. He has an array $a$ of $n$ digits and the present will be the product of all these digits. Because Slavic is a good kid who wants to make the biggest product possible, he wants to add $1$ to exactly one of his digits.\n\nWhat is the maximum product Slavic can make?",
    "tutorial": "Just brute force all possibilties for the digit to increase, and check the product each time. The complexity is $\\mathcal{O}(n^2)$ per testcase. You can make it faster if you notice that it's always optimal to increase the smallest digit (why?), but it wasn't necessary to pass.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    int ans = 1;\n    for(int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n    }\n    sort(a.begin(), a.end());\n    a[0]++;\n    for(int i = 0; i < n; i++)\n    {\n        ans*=a[i];\n    }\n    cout << ans << endl;\n}\n \nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n \n ",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1873",
    "index": "C",
    "title": "Target Practice",
    "statement": "A $10 \\times 10$ target is made out of five \"rings\" as shown. Each ring has a different point value: the outermost ring — 1 point, the next ring — 2 points, ..., the center ring — 5 points.\n\nVlad fired several arrows at the target. Help him determine how many points he got.",
    "tutorial": "You can just hardcode the values in the array below, and iterate through the grid; if it is an $\\texttt{X}$, we add the value to our total. See the implementation for more details. $\\begin{bmatrix} 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\\\ 1 & 2 & 2 & 2 & 2 & 2 & 2 & 2 & 2 & 1 \\\\ 1 & 2 & 3 & 3 & 3 & 3 & 3 & 3 & 2 & 1 \\\\ 1 & 2 & 3 & 4 & 4 & 4 & 4 & 3 & 2 & 1 \\\\ 1 & 2 & 3 & 4 & 5 & 5 & 4 & 3 & 2 & 1 \\\\ 1 & 2 & 3 & 4 & 5 & 5 & 4 & 3 & 2 & 1 \\\\ 1 & 2 & 3 & 4 & 4 & 4 & 4 & 3 & 2 & 1 \\\\ 1 & 2 & 3 & 3 & 3 & 3 & 3 & 3 & 2 & 1 \\\\ 1 & 2 & 2 & 2 & 2 & 2 & 2 & 2 & 2 & 1 \\\\ 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\\\ \\end{bmatrix}$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200007;\nconst int MOD = 1000000007;\n \nint score[10][10] = {\n\t{1,1,1,1,1,1,1,1,1,1},\n\t{1,2,2,2,2,2,2,2,2,1},\n\t{1,2,3,3,3,3,3,3,2,1},\n\t{1,2,3,4,4,4,4,3,2,1},\n\t{1,2,3,4,5,5,4,3,2,1},\n\t{1,2,3,4,5,5,4,3,2,1},\n\t{1,2,3,4,4,4,4,3,2,1},\n\t{1,2,3,3,3,3,3,3,2,1},\n\t{1,2,2,2,2,2,2,2,2,1},\n\t{1,1,1,1,1,1,1,1,1,1}\n};\n \nvoid solve() {\n\tint ans = 0;\n\tfor (int i = 0; i < 10; i++) {\n\t\tfor (int j = 0; j < 10; j++) {\n\t\t\tchar c;\n\t\t\tcin >> c;\n\t\t\tif (c == 'X') {ans += score[i][j];}\n\t\t}\n\t}\n\tcout << ans << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1873",
    "index": "D",
    "title": "1D Eraser",
    "statement": "You are given a strip of paper $s$ that is $n$ cells long. Each cell is either black or white. In an operation you can take any $k$ consecutive cells and make them all white.\n\nFind the minimum number of operations needed to remove all black cells.",
    "tutorial": "The key idea is greedy. Let's go from the left to the right, and if the current cell is black, we should use the operation starting at this cell (it may go off the strip, but that's okay, we can always shift it leftwards to contain all the cells we need it to). We can implement this in $\\mathcal{O}(n)$: iterate from left to right with a variable $i$, and when you see a black cell, you should skip the next $k-1$ cells (because the eraser will take care of them) and increase the number of operations by $1$. The answer is the total number of operations. Why does it work? Notice the order of operations doesn't matter. Consider the leftmost black cell we erase. It means none of the cells to its right are black. So it doesn't make sense to use the operation on any of the cells to its right, since they are already white. It is at least as good to use the operation starting at this cell and to the $k-1$ cells on the left, since we may or may not hit another black cell.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tstring s;\n\tcin >> s;\n\tint res = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] == 'B') {\n\t\t\tres++; i += k - 1;\n\t\t}\n\t}\n\tcout << res << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1873",
    "index": "E",
    "title": "Building an Aquarium",
    "statement": "You love fish, that's why you have decided to build an aquarium. You have a piece of coral made of $n$ columns, the $i$-th of which is $a_i$ units tall. Afterwards, you will build a tank around the coral as follows:\n\n- Pick an integer $h \\geq 1$ — the height of the tank. Build walls of height $h$ on either side of the tank.\n- Then, fill the tank up with water so that the height of each column is $h$, unless the coral is taller than $h$; then no water should be added to this column.\n\nFor example, with $a=[3,1,2,4,6,2,5]$ and a height of $h=4$, you will end up using a total of $w=8$ units of water, as shown. You can use at most $x$ units of water to fill up the tank, but you want to build the biggest tank possible. What is the largest value of $h$ you can select?",
    "tutorial": "We need to find the maximum height with a certain upper bound - this is a tell-tale sign of binary search. If you don't know what that is, you should read this Codeforces EDU article. For a given value of $h$, in the $i$-th column we will need $h - a_i$ units of water if $h \\geq a_i$, or $0$ units otherwise. (This is equal to $\\max(h - a_i, 0)$, why?) So we can compute the amount of water for all $n$ columns by simply iterating through and summing the total amount of water needed for each column, and see if it's not larger than $x$. Then you can binary search on the optimal value of $h$. The model solution uses the starting bounds $l = 0$, $r = 2a_i + \\varepsilon$, because the optimal height could be $a_i + x$. So the complexity is $\\mathcal{O}(n \\log a_i)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tint n;\n\tlong long x;\n\tcin >> n >> x;\n\tlong long a[n];\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> a[i];\n\t}\n\tlong long lo = 0, hi = 2'000'000'007;\n\twhile (lo < hi) {\n\t\tlong long mid = lo + (hi - lo + 1) / 2;\n\t\tlong long tot = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\ttot += max(mid - a[i], 0LL);\n\t\t}\n\t\tif (tot <= x) {lo = mid;} \n\t\telse {hi = mid - 1;}\n\t}\n\tcout << lo << endl;\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "binary search",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1873",
    "index": "F",
    "title": "Money Trees",
    "statement": "Luca is in front of a row of $n$ trees. The $i$-th tree has $a_i$ fruit and height $h_i$.\n\nHe wants to choose a contiguous subarray of the array $[h_l, h_{l+1}, \\dots, h_r]$ such that for each $i$ ($l \\leq i < r$), \\textbf{$h_i$ is divisible$^{\\dagger}$ by $h_{i+1}$}. He will collect all the fruit from each of the trees in the subarray (that is, he will collect $a_l + a_{l+1} + \\dots + a_r$ fruits). However, if he collects more than $k$ fruits in total, he will get caught.\n\nWhat is the maximum length of a subarray Luca can choose so he doesn't get caught?\n\n$^{\\dagger}$ $x$ is divisible by $y$ if the ratio $\\frac{x}{y}$ is an integer.",
    "tutorial": "Let's compute $len_l$ for each $l \\leq n$, the maximum $r$ such that the subarray $[h_l \\dots h_r]$ satisfies the height divisibility condition. Now let's do a binary search on the $size$ of the segment, where we check every $i$ such that $len_i \\geq i+size-1$. Check the sum between $i$ and $i+size-1$ using a prefix sum. If it is smaller or equal to $k$, we update the lower bound of the binary search, otherwise, if we find no such $i$ for this $size$ then we update the upper bound. Final complexity $O(n logn)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 200'000;\n \nint n, k;\nint a[N+5], h[N+5], pref[N+5], length[N+5];\n \nbool get(int dist)\n{\n    bool found = false;\n    for(int i = 0; i < n-dist+1; i++)\n    {\n        if(length[i] < dist){continue;}\n        int sum = pref[i+dist]-pref[i];\n        if(sum <= k)\n        {\n            found = true;\n            break;\n        }\n    }\n    return found;\n}\n \nvoid solve()\n{\n    pref[0] = 0;\n    cin >> n >> k;\n    for(int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n        pref[i+1] = pref[i]+a[i];\n    }\n    for(int i = 0; i < n; i++)\n    {\n        cin >> h[i];\n    }\n    length[n-1] = 1;\n    for(int i = n-2; i >= 0; i--)\n    {\n        if(h[i]%h[i+1] == 0)\n        {\n            length[i] = length[i+1]+1;\n        }\n        else\n        {\n            length[i] = 1;\n        }\n    }\n    int l = 1, r = N;\n    while(l <= r)\n    {\n        int mid = (l+r)/2;\n        if(get(mid))\n        {\n            l = mid+1;\n        }\n        else\n        {\n            r = mid-1;\n        }\n    }\n    cout << r << endl;\n}\n \nint main() {\n    int t = 1;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}\n\n",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1873",
    "index": "G",
    "title": "ABBC or BACB",
    "statement": "You are given a string $s$ made up of characters $A$ and $B$. Initially you have no coins. You can perform two types of operations:\n\n- Pick a substring$^\\dagger$ $AB$, change it to $BC$, and get a coin.\n- Pick a substring$^\\dagger$ $BA$, change it to $CB$, and get a coin.\n\nWhat is the most number of coins you can obtain?$^\\dagger$ A substring of length $2$ is a sequence of two adjacent characters of a string.",
    "tutorial": "Preface Before we get into the editorial, I want to make a note that this type of problem is not traditional for Div. 4 on purpose, and is a lot more ad-hoc than usual. My goal was to make a sort of \"introductory\" ad-hoc problem, and I hope you enjoyed it. The editorial is a bit long, mainly because I want to go into a lot of detail regarding how to approach such ad-hoc problems, since usually most Div. 4 problems are unlike this, and instead focused on noticing and implementing the correct algorithm. I don't think anyone solving the problem will actually go through all this detail explicitly, but I wanted to provide a very explicit walk-through for anyone not knowing how to start. But I think ad-hoc skills are important for Codeforces especially, hence this problem. Maybe you'll see more soon. ;) Let's think about how we can repeatedly use the operations first. If we have a string $\\texttt{AAAB}$, then we can do the operations $\\texttt{AAAB} \\to \\texttt{AABC} \\to \\texttt{ABCC} \\to \\texttt{BCCC}$. Similarly, if we have a string $\\texttt{BAAA}$, then we can do the operations $\\texttt{BAAA} \\to \\texttt{CBAA} \\to \\texttt{CCBA} \\to \\texttt{CCCB}$. In a sense, it's useful to think of the $\\texttt{B}$ as \"eating\" the $\\texttt{A}$s in a sense: whenever a $\\texttt{B}$ is next to an $\\texttt{A}$, it eats covers it and eats it, and then it moves on. Note that $\\texttt{B}$ cannot eat $\\texttt{C}$s. Let's replace the characters as follows: replace $\\texttt{A}$ with $\\texttt{.}$ and $\\texttt{C}$ with $\\texttt{_}$. Then, it's much clear what is going on. Here is a series of moves on the string $\\texttt{BAAABA}$, which becomes $\\texttt{B...B.}$ after the replacing: $\\texttt{B...B.} \\to \\texttt{_B..B.} \\to \\texttt{__B.B.} \\to \\texttt{___BB.} \\to \\texttt{___B_B}$ Now you can see how each $\\texttt{B}$ is eating all the dots in one direction (it can't travel over blank spaces represented by $\\texttt{_} = \\texttt{C}$). Okay, we have this intuition, how to solve the problem now? We need to eat the maximum number of dots ($\\texttt{A}$s in the original string), since $\\texttt{B}$s cannot eat anything else. Note that for each $\\texttt{B}$, it can eat all the $\\texttt{A}$s to its left or to its right, but not both; one it leaves its original spot, it is stuck on that side: $\\texttt{..B.} \\to \\texttt{.B_.} \\to \\texttt{B__.}$ This is where our original string comes into play. Suppose our original string starts with $\\texttt{B}$, so it must be of the form $\\texttt{B} \\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\texttt{B} \\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\texttt{B} \\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\dots$ $\\dots\\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\texttt{B} \\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\texttt{B} \\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\texttt{B}$ So we only have to look at the case where our string starts and ends with $\\texttt{A}$, meaning our string looks something like: $\\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\texttt{B} \\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\dots \\,\\,\\,\\,\\,\\,\\,\\, \\texttt{B} \\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0}$ $\\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0} \\texttt{B} \\texttt{B} \\underbrace{\\texttt{A} \\dots \\texttt{A}}_{\\text{some number, possibly } 0}$ What's the only other case? Start and end with $\\texttt{A}$, and there are no two $\\texttt{B}$s next to each other. In this case, you can see there is one more \"group\" of $\\texttt{A}$s than there are $\\texttt{B}$s, but each $\\texttt{B}$ can only get one group of $\\texttt{A}$s. So we won't be able to get all of them. What's the best we can do? Note that each $\\texttt{B}$ can only get one group, if it goes left or right, so we can get all $\\texttt{A}$s except one group. Now the answer is simply greedy: it is the total number of $\\texttt{A}$s, minus the smallest group (since we want to get the most number of coins, we will take groups as large as possible). You can also envision this as a sort of greedy: each $\\texttt{B}$ takes the largest group available, and we stop once no more $\\texttt{B}$s are free. The time complexity for finding groups is $\\mathcal{O}(n)$, so the whole solution runs in that time as well.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tint n = s.length(), cnt = 0;\n\tbool all = (s[0] == 'B' || s[n - 1] == 'B');\n\tfor (int i = 0; i < n - 1; i++) {\n\t\tif (s[i] == s[i + 1] && s[i] == 'B') {all = true;}\n\t}\n\tvector<int> lens;\n\tint curr = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (s[i] == 'A') {curr++;}\n\t\telse {\n\t\t\tif (curr != 0) {lens.push_back(curr);}\n\t\t\tcurr = 0;\n\t\t}\n\t}\n\tif (curr != 0) {lens.push_back(curr);}\n\tsort(lens.begin(), lens.end());\n\t\n\tif (lens.empty()) {cout << 0 << '\\n'; return;}\n\t\n\tint tot = 0;\n\tif (all) {tot += lens[0];}\n\tfor (int i = 1; i < lens.size(); i++) {\n\t\ttot += lens[i];\n\t}\n\tcout << tot << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1873",
    "index": "H",
    "title": "Mad City",
    "statement": "Marcel and Valeriu are in the mad city, which is represented by $n$ buildings with $n$ two-way roads between them.\n\nMarcel and Valeriu start at buildings $a$ and $b$ respectively. Marcel wants to catch Valeriu, in other words, be in the same building as him or meet on the same road.\n\nDuring each move, they choose to go to an adjacent building of their current one or stay in the same building. Because Valeriu knows Marcel so well, Valeriu can predict where Marcel will go in the next move. Valeriu can use this information to make his move. They start and end the move at the same time.\n\nIt is guaranteed that any pair of buildings is connected by some path and there is at most one road between any pair of buildings.\n\nAssuming both players play optimally, answer if Valeriu has a strategy to indefinitely escape Marcel.",
    "tutorial": "Because we have a tree with an additional edge, our graph has exactly one cycle. If Marcel and Valeriu share the same starting building then the answer is \"NO\". If we do a depth-first search from Valeriu's node, when we encounter an already visited node that is not the current node's parent, the node is part of the cycle. Moreover, it's the node where Valeriu enters the cycle. Valeriu can escape Marcel forever if and only if he reaches this node before Marcel can. This is because if Valeriu is in a cycle then he always has $2$ choices of buildings where he would run that still keep him in the cycle. Marcel can only be in one building at any given time and Valeriu knows Marcel's next move, which means Valeriu can always escape him. So it just remains to check with a breadth-first search or a depth-first search if Marcel arrives at Valeriu's entry node after Valeriu.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 200005;\n \nvector<int> adj[N];\nvector<bool> vis(N);\n \nint entry_node = -1;\nvector<int> path;\n \nbool dfs1(int u, int p)\n{\n    vis[u] = true;\n    for(auto v : adj[u])\n    {\n        if(v != p && vis[v])\n        {\n            entry_node = v;\n            return true;\n        }\n        else if(v != p && !vis[v])\n        {\n            if(dfs1(v, u))\n            {\n                return true;\n            }\n        }\n    }\n    return false;\n}\n \nint dfs2(int u)\n{\n    vis[u] = true;\n    int distbruh = N;\n    for(auto v : adj[u])\n    {\n        if(v == entry_node)\n        {\n            return 1;\n        }\n        if(!vis[v])\n        {\n            int dist = dfs2(v)+1;\n            distbruh = min(dist, distbruh);\n        }\n    }\n    return distbruh;\n}\n \nvoid solve()\n{\n    int n, a, b;\n    cin >> n >> a >> b;\n    for(int i = 0; i < n; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    dfs1(b, -1);\n    vis.assign(n+1, false);\n    int distMarcel = N, distValeriu = 0;\n    if(entry_node == a)\n    {\n        distMarcel = 0;\n    }\n    else\n    {\n        distMarcel = dfs2(a);\n    }\n    vis.assign(n+1, false);\n    if(entry_node == b)\n    {\n        distValeriu = 0;\n    }\n    else\n    {\n        distValeriu = dfs2(b);\n    }\n    if(distValeriu < distMarcel)\n    {\n        cout << \"YES\" << endl;\n    }\n    else\n    {\n        cout << \"NO\" << endl;\n    }\n    for(int i = 1; i <= n; i++)\n    {\n        adj[i].clear();\n        vis[i] = false;\n    }\n}\n \nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n \n\n",
    "tags": [
      "dfs and similar",
      "dsu",
      "games",
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1874",
    "index": "A",
    "title": "Jellyfish and Game",
    "statement": "Jellyfish has $n$ green apples with values $a_1, a_2, \\dots, a_n$ and Gellyfish has $m$ green apples with values $b_1,b_2,\\ldots,b_m$.\n\nThey will play a game with $k$ rounds. For $i=1,2,\\ldots,k$ in this order, they will perform the following actions:\n\n- If $i$ is odd, Jellyfish can choose to swap one of her apples with one of Gellyfish's apples or do nothing.\n- If $i$ is even, Gellyfish can choose to swap one of his apples with one of Jellyfish's apples or do nothing.\n\nBoth players want to maximize the sum of the values of their apples.\n\nSince you are one of the smartest people in the world, Jellyfish wants you to tell her the final sum of the value of her apples after all $k$ rounds of the game. Assume that both Jellyfish and Gellyfish play optimally to maximize the sum of values of their apples.",
    "tutorial": "Let us define $\\min(a)$ to be the minimum value of $a$ in the current round, $\\max(a)$ to be the maximum value of $a$ in the current round, $\\min(b)$ to be the minimum value of $b$ in the current round, $\\max(b)$ to be the maximum value of $b$ in the current round, $\\text{MIN}$ to be the minimum value of all the apples, $\\text{MAX}$ to be the maximum value of all the apples. By greedy and induction, we would come to the following conclusion: If Jellyfish is the one operating this round: If $\\min(a) < \\max(b)$, she will swap this two apples, otherwise she will do nothing. If Gellyfish is the one operating this round: If $\\max(a) > \\min(b)$, he will swap this two apples, otherwise she will do nothing. We consider who $\\text{MAX}$ and $\\text{MIN}$ will belong to after the first round. In the first round: If $\\max(a) < \\max(b)$, $\\text{MAX} = \\max(b)$. And because $\\min(a) < \\max(b)$, Jellyfish will swap this two apples. So $\\text{MAX}$ belongs to Jellyfish. If $\\max(a) > \\max(b)$, $\\text{MAX} = \\max(a)$. If $\\min(a)=\\max(a)$, then $\\min(a) > \\max(b)$, Jellyfish will do nothing. Otherwise Jellyfish won't swap the apple with value $\\text{MAX}$. In conclusion $\\text{MAX}$ belongs to Jellyfish We can also show that $\\text{MIN}$ belongs to Gellyfish, and the proof is symmetric with the above. So in the second round, $\\min(b) = \\text{MIN}, \\max(a) = \\text{MAX}$, We have $\\text{MIN}<\\text{MAX}$. So Gellyfish will swap this two apples, in the third round, $\\min(a)=\\text{MIN}, \\max(b) = \\text{MAX}$, Jellyfish will swap this two apples. So after the first round, the game will go two rounds at a time, with two people swapping two apples with the minimum value and the maximum value back and forth. So we only need to know the answer for $k = 1$ and $k = 2$. Time complexity: $O(n + m)$ per test case. Memory complexity: $O(n + m)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1000 + 5;\nint n = 0, m = 0, k = 0, x = 0, y = 0, a[N] = {}, b[N] = {};\n\ninline void solve(){\n\tscanf(\"%d %d %d\", &n, &m, &k); k --;\n\tfor(int i = 0 ; i < n ; i ++) scanf(\"%d\", &a[i]);\n\tfor(int i = 0 ; i < m ; i ++) scanf(\"%d\", &b[i]);\n\tx = y = 0;\n\tfor(int i = 1 ; i < n ; i ++) if(a[i] < a[x]) x = i;\n\tfor(int i = 1 ; i < m ; i ++) if(b[i] > b[y]) y = i;\n\tif(b[y] > a[x]) swap(a[x], b[y]);\n\tif(k & 1){\n\t\tx = 0, y = 0;\n\t\tfor(int i = 1 ; i < n ; i ++) if(a[i] > a[x]) x = i;\n\t\tfor(int i = 1 ; i < m ; i ++) if(b[i] < b[y]) y = i;\n\t\tswap(a[x], b[y]);\n\t}\n\tlong long ans = 0;\n\tfor(int i = 0 ; i < n ; i ++) ans += a[i];\n\tprintf(\"%lld\\n\", ans);\n\t\n}\n\nint T = 0;\n\nint main(){\n\tscanf(\"%d\", &T);\n\tfor(int i = 0 ; i < T ; i ++) solve();\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "games",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1874",
    "index": "B",
    "title": "Jellyfish and Math",
    "statement": "Jellyfish is given the non-negative integers $a$, $b$, $c$, $d$ and $m$. Initially $(x,y)=(a,b)$. Jellyfish wants to do several operations so that $(x,y)=(c,d)$.\n\nFor each operation, she can do one of the following:\n\n- $x := x\\,\\&\\,y$,\n- $x := x\\,|\\,y$,\n- $y := x \\oplus y$,\n- $y := y \\oplus m$.\n\nHere $\\&$ denotes the bitwise AND operation, $|$ denotes the bitwise OR operation and $\\oplus$ denotes the bitwise XOR operation.\n\nNow Jellyfish asks you for the minimum number of operations such that $(x,y)=(c,d)$.",
    "tutorial": "First of all, since $\\text{and}, \\text{or}, \\text{xor}$ are all bitwise operations, each bit is independent of the other. We define $a_i$ as the $i$-th bit of $a$, $b_i$ as the $i$-th bit of $b$, $c_i$ as the $i$-th bit of $c$, $d_i$ as the $i$-th bit of $d$, $m_i$ as the $i$-th bit of $m$, $x_i$ as the $i$-th bit of $x$, $y_i$ as the $i$-th bit of $y$. (in binary) Lemma. For all $i \\neq j$, if $(a_i, b_i, m_i) = (a_j, b_j, m_j)$ and $(c_i, d_i) \\neq (c_j, d_j)$, the goal cannot be achieved. Proof. Because after every operation we will have $(x_i, y_i) = (x_j, y_j)$, so we can't achieve he goal. Since $(a_i, b_i, m_i)$ has only $2^3=8$ cases, and $(c_i, d_i)$ has only $2^2=4$ cases, and there are some $(0/1, 0/1, 0/1)$ that do not appear in $\\{(a_i, b_i, m_i)\\ |\\ 0 \\leq i \\leq \\log \\max(a, b, c, d, m)\\}$, so there are only $(4+1)^8<4\\times 10^5$ cases in this problem. We can use BFS(breadth-first search) for preprocessing. Time complexity: $O(5^8)$ for preprocessing and $O(\\log \\max(a, b, c, d, m))$ per test case. Memory complexity: $O(5^8)$ for preprocessing and $O(1)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int S = 4e5 + 5, Inf = 0x3f3f3f3f;\nint pw5[10] = {}, dp[S] = {};\nqueue<int> Q;\n\ninline void checkmin(int &x, int y){\n\tif(y < x) x = y;\n}\n\ninline int w(int mask, int i){\n\treturn (mask / pw5[i]) % 5;\n}\n\ninline int f(int a, int b, int m){\n\treturn (a << 2) | (b << 1) | m;\n}\n\ninline int g(int c, int d){\n\treturn (c << 1) | d;\n}\n\ninline int work(int mask, int opt){\n\tint ret = 0;\n\tfor(int a = 0 ; a < 2 ; a ++) for(int b = 0 ; b < 2 ; b ++) for(int m = 0 ; m < 2 ; m ++){\n\t\tint x = w(mask, f(a, b, m)), c = x >> 1, d = x & 1;\n\t\tif(opt == 1) c = c & d;\n\t\telse if(opt == 2) c = c | d;\n\t\telse if(opt == 3) d = c ^ d;\n\t\telse d = m ^ d;\n\t\tret += pw5[f(a, b, m)] * g(c, d);\n\t}\n\treturn ret;\n}\n\ninline void init(){\n\tpw5[0] = 1;\n\tfor(int i = 1 ; i <= 8 ; i ++) pw5[i] = pw5[i - 1] * 5;\n\tmemset(dp, 0x3f, sizeof(dp));\n\tint mask = 0;\n\tfor(int a = 0 ; a < 2 ; a ++) for(int b = 0 ; b < 2 ; b ++) for(int m = 0 ; m < 2 ; m ++) mask += pw5[f(a, b, m)] * g(a, b);\n\tdp[mask] = 0, Q.push(mask);\n\twhile(Q.size()){\n\t\tint s = Q.front(); Q.pop();\n\t\tfor(int opt = 0 ; opt < 4 ; opt ++){\n\t\t\tint t = work(s, opt);\n\t\t\tif(dp[t] == Inf) dp[t] = dp[s] + 1, Q.push(t);\n\t\t}\n\t}\n\tfor(int mask = 0 ; mask < pw5[8] ; mask ++) for(int i = 0 ; i < 8 ; i ++) if(w(mask, i) == 4){\n\t\tfor(int x = 1 ; x <= 4 ; x ++) checkmin(dp[mask], dp[mask - x * pw5[i]]);\n\t\tbreak;\n\t}\n}\n\ninline void solve(){\n\tint A = 0, B = 0, C = 0, D = 0, M = 0, mask = pw5[8] - 1;\n\tscanf(\"%d %d %d %d %d\", &A, &B, &C, &D, &M);\n\tfor(int i = 0 ; i < 30 ; i ++){\n\t\tint a = (A >> i) & 1, b = (B >> i) & 1, c = (C >> i) & 1, d = (D >> i) & 1, m = (M >> i) & 1;\n\t\tif(w(mask, f(a, b, m)) == 4) mask -= (4 - g(c, d)) * pw5[f(a, b, m)];\n\t\telse if(w(mask, f(a, b, m)) != g(c, d)){\n\t\t\tprintf(\"-1\\n\");\n\t\t\treturn;\n\t\t}\n\t}\n\tprintf(\"%d\\n\", (dp[mask] < Inf) ? dp[mask] : -1);\n}\n\nint T = 0;\n\nint main(){\n\tinit();\n\tscanf(\"%d\", &T);\n\tfor(int i = 0 ; i < T ; i ++) solve();\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1874",
    "index": "C",
    "title": "Jellyfish and EVA",
    "statement": "Monsters have invaded the town again! Asuka invites her good friend, Jellyfish, to drive EVA with her.\n\nThere are $n$ cities in the town. All the monsters are in city $n$. Jellyfish and Asuka are currently in city $1$ and need to move to city $n$ to defeat the monsters.\n\nThere are $m$ roads. The $i$-th road allows one to travel from city $a_i$ to city $b_i$. All the roads are \\textbf{directed}. That is, one cannot travel from city $b_i$ to $a_i$ using the $i$-th road. Interestingly, all roads satisfy $a_i<b_i$.\n\nDriving EVA requires two people to work together. However, Asuka and Jellyfish have not done any training together before.\n\nSuppose that EVA is currently in city $u$. Jellyfish and Asuka will both choose an undestroyed road that starts at city $u$. Suppose Jellyfish and Asuka choose roads that end at cities $v_1$ and $v_2$ respectively. If $v_1 = v_2$, EVA moves to city $v_1$ successfully. Otherwise, EVA stays in city $u$ and both roads that they have chosen will be destroyed.\n\nIt is possible that EVA is currently in city $u$ ($u \\neq n$) and there are no undestroyed roads that start at city $u$. In that case, the mission will be a failure. Otherwise, if they reach city $n$ in the end, the mission is considered a success.\n\nEvery time they choose the roads, Jellyfish knows that Asuka will choose a road randomly. Now, Jellyfish wants to know, if she chooses the roads optimally, what is the maximum probability of the mission being successful.",
    "tutorial": "Let's solve this problem by dynamic programming, Let $f_u$ represents the max probability of reaching city $n$ starting from city $u$. The problem is how to transition. for city $u$, we assume that there are $d$ roads from city $u$, the $i$-th road from city $u$ is to city $v_i$. Let's sort $v$ by using $f_v$ as the keyword, with $v$ with the larger $f_v$ coming first. Let's define an array $a$ of $d$ elements equals to $[f_{v_1}, f_{v_2}, \\dots, f_{v_d}]$, according to the definition, $a$ is non-increasing. That is, next we want to find an optimal solution such that the probability of going to city $v_i$ is $p_i$, maximizing the value of $\\sum_{i=1}^d{a_i \\times p_i}$. Tips: the sum of $p_i$ may not be $1$, because it is possible to stay at city $u$ when $d$ is even. For two choices of $p$, $p_1$ and $p_2$, Sometimes we can't which is better, for example: $p_1 = [0.6, 0.2, 0.2], p_2 = [0.5, 0.5, 0]$ when $a=[1.0, 0.2, 0.2]$, $p_1$ is better than $p_2$. But when $a = [1.0, 0.8, 0]$, $p_2$ is better than $p_1$. Tips. In fact, when $d=3$, $p$ has only one choice $[\\frac 1 3, \\frac 1 3, \\frac 1 3]$, the above is just a hypothetical to illustrate the problem. So when can we say, $p_1$ is always not worse than $p_2$? Lemma. If there are two arrays $p_1$ and $p_2$, satisfying $\\forall i \\leq d, \\sum_{j=1}^i{p_1}_j \\geq \\sum_{j=1}^i{p_2}_j$, $p_1$ is always not worse than $p_2$. Proof. Let's consider $a_{d+1}$ as $0$ and define $a'_i = a_i - a_{i+1}$, ${p_1'}_i = \\sum_{j=1}^i{p_1}_j$ and ${p_2'}_i = \\sum_{j=1}^i{p_2}_j$, then $\\sum_{i=1}^d a_i \\times {p_1}_i = \\sum_{i=1}^d a'_i \\times {p_1'}_i, \\sum_{i=1}^d a_i \\times {p_2}_i = \\sum_{i=1}^d a'_i \\times {p_2'}_i$, Because $a$ is non-increasing, so $a'_i \\geq 0$, and we have $\\forall i \\leq d, {p_1}_i \\geq {p_2}_i$, so $\\sum_{i=1}^d a_i \\times {p_1}_i \\geq \\sum_{i=1}^d a_i \\times {p_2}_i$. Now the problem is, there is whether an array $p$ not worse than any other arrays for for all $d$. For $d = 1$, $p = [1.0]$ satisfies the condition. For $d = 2$, $p = [0.5, 0]$ satisfies the condition. What about $d>2$ ? After they choose the roads for the first time, The size of the problem will become $d - 2$. For example, when $d = 4$, Let's assume Jellyfish choose $v_1$ for the first time, then there will be $4$ situations: When Asuka chooses $v_1$ they will go to $v_1$. When Asuka chooses $v_2$, the problem changes into the subproblem with $[v_3, v_4]$. When Asuka chooses $v_3$, the problem changes into the subproblem with $[v_2, v_4]$. When Asuka chooses $v_4$, the problem changes into the subproblem with $[v_2, v_3]$. By calculating, $p = [0.25, 0.25, 0.125, 0]$, it also satisfies the condition. Let's define $g_k$ as the best array $p$ when $d=k$, $g'_k$ as the the probabilities of going to cities except the city Jellyfish choose for the first time. By recursion, we can get $g'_k$ from $g_{k-2}$. After that, we insert $\\frac 1 k$ into $g'_k$, keeping it non-increasing, we will get $g_k$. By calculating, we will find $\\frac 1 k$ is always the first element in $g_k$. So when $k > 2$, we have the following transition: $g_{k, 1} = \\frac 1 k$ $g_{k, 1} = \\frac 1 k$ $\\forall 1 < i \\leq k, g_{k, i} = g_{k-2, i - 2} \\times \\frac {i - 2} k + g_{k-2, i - 1} \\times \\frac {k - i} k$ $\\forall 1 < i \\leq k, g_{k, i} = g_{k-2, i - 2} \\times \\frac {i - 2} k + g_{k-2, i - 1} \\times \\frac {k - i} k$ In the above we consider $g_{k, x}$ as $0$ for all $x = 0$ or $x > k$. Because $g_{k-2}$ satisfies the condition, by greedy and induction we can show that $g_k$ satisfies the condition. Time complexity: $O(\\max(n)^2)$ for preprocessing and $O(m \\log n)$ per test case. Memory complexity: $O(\\max(n)^2)$ for preprocessing and $O(m)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5000 + 5;\nint n = 5000, m = 0;\nvector<vector<int> > G(N), Gx(N);\nlong double f[N] = {}, g[N][N] = {};\n\ninline bool cmp(int u, int v){\n\treturn f[u] > f[v];\n}\n\ninline void work(int u){\n\tif(u == n){\n\t\tf[u] = 1.00;\n\t\treturn;\n\t}\n\tsort(G[u].begin(), G[u].end(), cmp);\n\tint k = G[u].size();\n\tfor(int i = 0 ; i < k ; i ++){\n\t\tint v = G[u][i];\n\t\tf[u] += f[v] * g[k][i + 1];\n\t}\n}\n\ninline void init(){\n\tfor(int u = 1 ; u <= n ; u ++){\n\t\tf[u] = 0.00;\n\t\tG[u].clear(), Gx[u].clear();\n\t}\n\tn = m = 0;\n}\n\ninline void solve(){\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 1, u = 0, v = 0 ; i <= m ; i ++){\n\t\tscanf(\"%d %d\", &u, &v);\n\t\tif(u != n){\n\t\t\tG[u].push_back(v);\n\t\t\tGx[v].push_back(u);\n\t\t}\n\t}\n\tfor(int u = n ; u >= 1 ; u --) work(u);\n\tprintf(\"%.12Lf\\n\", f[1]);\n}\n\nint T = 0;\n\nint main(){\n\tfor(int i = 1 ; i <= n ; i += 2) for(int j = 1 ; j <= i ; j ++) g[i][j] = 1.00 / i;\n\tfor(int i = 2 ; i <= n ; i += 2){\n\t\tg[i][1] = 1.00;\n\t\tfor(int j = 1 ; j <= i ; j ++) g[i][j] /= i;\n\t\tif(i + 2 <= n) for(int j = 1 ; j <= i ; j ++) g[i + 2][j + 1] += g[i][j] * (i - j + 1), g[i + 2][j + 2] += g[i][j] * j;\n\t}\n\tscanf(\"%d\", &T);\n\tfor(int i = 1 ; i <= T ; i ++) init(), solve();\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "graphs",
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1874",
    "index": "D",
    "title": "Jellyfish and Miku",
    "statement": "There are $n + 1$ cities with numbers from $0$ to $n$, connected by $n$ roads. The $i$-th $(1 \\leq i \\leq n)$ road connects city $i-1$ and city $i$ bi-directionally. After Jellyfish flew back to city $0$, she found out that she had left her Miku fufu in city $n$.\n\nEach road has a \\textbf{positive integer} level of beauty. Denote the beauty of the $i$-th road as $a_i$.\n\nJellyfish is trying to find her fufu. Because of her poor sense of direction, she doesn't know which way to go. Every day, she randomly chooses a road connected to the city she currently is in and traverses it. Let $s$ be the sum of the beauty of the roads connected to the current city. For each road connected to the current city, Jellyfish will traverse the road with a probability of $\\frac x s$, where $x$ is the beauty of the road, reaching the city on the other side of the road.\n\nJellyfish will start at city $0$, and she will get only her fufu back when she reaches city $n$.\n\nYou want to choose the beauty of the roads such that the expected number of days Jellyfish takes to find her fufu will be the minimum possible. However, due to limited funding, the sum of beauties of all roads must be less than or equal to $m$.\n\nFind the minimum expected number of days Jellyfish needs to get her fufu back if the beauty of the roads is chosen optimally.",
    "tutorial": "Let's assume that $a$ is given. We can use dynamic programming to solve the problem. Let's define $f_i$ as the expected number of days Jellyfish needs to reach city $i$ from city $0$. We will have: $f_0=0, f_1=1$ $f_0=0, f_1=1$ $\\forall i > 1, f_i=f_{i-1}+1+\\frac {a_{i-1}} {a_{i-1}+a_i} \\times (f_i - f_{i-2})$ $\\forall i > 1, f_i=f_{i-1}+1+\\frac {a_{i-1}} {a_{i-1}+a_i} \\times (f_i - f_{i-2})$ Let's make it better: $f_i = f_{i-1} + 1 + \\frac {a_{i-1}} {a_i} \\times (f_{i-1}-f_{i-2}+1)$ What does this inspire us to do? Let's define $g_i=f_i-f_{i-1}$, then we will get: $g_1=1$ $g_1=1$ $\\forall i > 1, g_i = 1 + \\frac {a_{i-1}} {a_i} \\times (g_{i-1}+1)$ $\\forall i > 1, g_i = 1 + \\frac {a_{i-1}} {a_i} \\times (g_{i-1}+1)$ By induction, we will find $g_i = 1 + 2 \\times \\sum_{j=1}^{i-1} \\frac {a_j} {a_i}$. According to the definition, $f_n = \\sum_{i=1}^n g_n = n + 2 \\times \\sum_{i=1}^n\\sum_{j=1}^{i-1} \\frac{a_j}{a_i}$. Then we can use dynamic programming to solve the problem itself. Let's define $s_i = \\sum_{j=1}^i a_j$, then $f_n = n + 2 \\times \\sum_{i=1}^n \\frac{s_{i-1}}{a_i}$. Let's define $dp_{i, x}$ as the minimum value of $\\sum_{i=1}^n \\frac{s_{i-1}}{a_i}$ when $s_i = x$. We transit by enumerating the values of $a_{i+1}$, The transition is: $dp_{i+1, x+y} \\leftarrow dp_{i, x} + \\frac x y$. But the time complexity is $O(n m^2)$, how can it becomes faster? Let's take a closer look at $\\sum_{i=1}^n\\sum_{j=1}^{i-1} \\frac{a_j}{a_i}$. If there exists $i < n$ satisfying $a_i > a_{i+1}$. We can swap $a_i$ and $a_{i+1}$, the answer will be better! so $a$ is a non-decreasing array, which means $a_i \\leq \\frac m {n - i + 1}$. Because $\\sum_{i=1}^n \\frac n i$ is $O(n \\log n)$, so if we only enumerate the possible values of $a_i$ the time complexity will be $O(m^2 \\log m)$. Time complexity: $O(m^2 \\log m)$ Memory complexity: $O(nm)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 3000 + 5;\nconst long double Inf = 1e18;\nint n = 0, m = 0;\nlong double dp[N][N] = {};\n\nint main(){\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int i = 0 ; i <= n ; i ++) for(int x = 0 ; x <= m ; x ++) dp[i][x] = Inf;\n\tdp[0][0] = 0.00;\n\tfor(int i = 1 ; i <= n ; i ++) for(int x = 0 ; x <= m ; x ++) for(int y = 1 ; x + y * (n - i + 1) <= m ; y ++) dp[i][x + y] = min(dp[i][x + y], dp[i - 1][x] + 1.00 * x / y);\n\tprintf(\"%.12Lf\", 2 * dp[n][m] + n);\n\treturn 0;\n}\n",
    "tags": [
      "divide and conquer",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1874",
    "index": "E",
    "title": "Jellyfish and Hack",
    "statement": "It is well known that quick sort works by randomly selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. But Jellyfish thinks that choosing a random element is just a waste of time, so she always chooses the first element to be the pivot. The time her code needs to run can be calculated by the following pseudocode:\n\n\\begin{verbatim}\nfunction fun(A)\nif A.length > 0\nlet L[1 ... L.length] and R[1 ... R.length] be new arrays\nL.length = R.length = 0\nfor i = 2 to A.length\nif A[i] < A[1]\nL.length = L.length + 1\nL[L.length] = A[i]\nelse\nR.length = R.length + 1\nR[R.length] = A[i]\nreturn A.length + fun(L) + fun(R)\nelse\nreturn 0\n\\end{verbatim}\n\nNow you want to show her that her code is slow. When the function $\\mathrm{fun(A)}$ is greater than or equal to $lim$, her code will get $\\text{Time Limit Exceeded}$. You want to know how many distinct permutations $P$ of $[1, 2, \\dots, n]$ satisfies $\\mathrm{fun(P)} \\geq lim$. Because the answer may be large, you will only need to find the answer modulo $10^9+7$.",
    "tutorial": "Firstly, if $lim > \\frac {n(n+1)} 2$, the answer will be $0$. So we only need to solve the problem which satisfies $lim \\leq \\frac{n(n+1)} 2$. We can use dynamic programming to solve the problem: Let's define $dp_{i, a}$ means the number of the permutations $P$ of $[1, 2, \\dots, i]$, satisfying $\\mathrm{fun(P)} = a$. Since only relative rankings are useful, we have the following transition: $dp_{0, 0} = 1$ $dp_{0, 0} = 1$ $\\forall i > 0, dp_{i, a} = \\sum_{j=1}^i \\binom {i-1} {j-1} \\sum_{b=0}^{a - i} dp_{j - 1, b} \\times dp_{i - j, a - b - i}$ $\\forall i > 0, dp_{i, a} = \\sum_{j=1}^i \\binom {i-1} {j-1} \\sum_{b=0}^{a - i} dp_{j - 1, b} \\times dp_{i - j, a - b - i}$ The time complexity is $O(n^6)$, because $a \\leq \\frac {i(i+1)} 2$, how can it becomes faster? FFT (Fast Fourier Transform) might come to mind first. If we use FFT instead of enumerating $t$, The time complexity will become $O(n^4 \\log n)$. This is not enough because $n$ is large and $10^9+7$ is not a modulus suitable for NTT (Number-theoretic Transform). Tips. Also, if you use divide and conquer and FFT, The time complexity will be $O(n^3 \\text{poly}(\\log n))$, but because FFT have a big constant factor, this still can't pass the problem. But we can do something similar to what the FFT does. We define $F_i = \\sum_{a=1}^{\\frac {n(n + 1)} 2} dp_{i, a} \\times x^a$, then we will have the following transition: $F_0=1$ $F_0=1$ $F_i = x^i \\times \\sum_{j=1}^i \\binom{i - 1}{j - 1} F_{j-1} \\times F_{i-j}$ $F_i = x^i \\times \\sum_{j=1}^i \\binom{i - 1}{j - 1} F_{j-1} \\times F_{i-j}$ For all $1 \\leq i \\leq n$, The degree of $F_i$ won't exceed $\\frac {n(n+1)} 2$. So if we have $\\frac{n(n+1)} 2 + 1$ points on $F_n$, We can get $F_n$ by in time complexity $O(n^4)$ using Lagrange Interpolation. The only thing we need to do is the dot product of the functions, so the time complexity of the transition is also $O(n^4)$. Time complexity: $O(n^4)$ Memory complexity: $O(n^3)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nconst ll N = 200 + 5, Mod = 1e9 + 7;\n\ninline ll power(ll x, ll y){\n\tll ret = 1;\n\twhile(y){\n\t\tif(y & 1) ret = ret * x % Mod;\n\t\tx = x * x % Mod, y >>= 1;\n\t}\n\treturn ret;\n}\n\nll n = 0, k = 0, lim = 0;\nll C[N][N] = {}, pw[N * N][N] = {}, iv[N * N] = {}, ifac[N * N] = {}, dp[N][N * N] = {};\nll a[N * N] = {}, b[N * N] = {}, ans = 0;\n\nint main(){\n\tscanf(\"%lld %lld\", &n, &k); lim = n * (n + 1) / 2;\n\tfor(ll i = 0 ; i <= n ; i ++){\n\t\tC[i][0] = 1;\n\t\tfor(ll j = 1 ; j <= i ; j ++) C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % Mod;\n\t}\n\tifac[0] = 1;\n\tfor(ll x = 0 ; x <= lim ; x ++){\n\t\tpw[x][0] = 1;\n\t\tif(x) iv[x] = power(x, Mod - 2), ifac[x] = ifac[x - 1] * iv[x] % Mod;\n\t\tfor(ll i = 1 ; i <= n ; i ++) pw[x][i] = pw[x][i - 1] * x % Mod;\n\t}\n\tfor(ll x = 0 ; x <= lim ; x ++) dp[0][x] = 1;\n\tfor(ll i = 1 ; i <= n ; i ++){\n\t\tfor(ll j = 0 ; j < i ; j ++) for(ll x = 0 ; x <= lim ; x ++) dp[i][x] = (dp[i][x] + dp[j][x] * dp[i - 1 - j][x] % Mod * C[i - 1][j]) % Mod;\n\t\tfor(ll x = 0 ; x <= lim ; x ++) dp[i][x] = dp[i][x] * pw[x][i] % Mod;\n\t}\n\ta[0] = 1;\n\tfor(ll i = 0 ; i <= lim ; i ++){\n\t\tfor(ll x = lim ; x >= 1 ; x --) a[x] = (a[x - 1] + a[x] * (Mod - i)) % Mod;\n\t\ta[0] = a[0] * (Mod - i) % Mod;\n\t}\n\tfor(ll i = 1 ; i <= lim ; i ++) if(dp[n][i]){\n\t\tll w = dp[n][i] * ifac[i] % Mod * ifac[lim - i] % Mod;\n\t\tif((lim - i) & 1) w = Mod - w;\n\t\tb[0] = a[0] * (Mod - iv[i]) % Mod;\n\t\tfor(ll x = 1 ; x <= lim ; x ++) b[x] = (a[x] - b[x - 1] + Mod) * (Mod - iv[i]) % Mod;\n\t\tfor(ll x = k ; x <= lim ; x ++) ans = (ans + b[x] * w) % Mod;\n\t}\n\tprintf(\"%lld\\n\", ans);\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1874",
    "index": "F",
    "title": "Jellyfish and OEIS",
    "statement": "Jellyfish always uses OEIS to solve math problems, but now she finds a problem that cannot be solved by OEIS:\n\nCount the number of permutations $p$ of $[1, 2, \\dots, n]$ such that for all $(l, r)$ such that $l \\leq r \\leq m_l$, the subarray $[p_l, p_{l+1}, \\dots, p_r]$ is not a permutation of $[l, l+1, \\dots, r]$.\n\nSince the answer may be large, you only need to find the answer modulo $10^9+7$.",
    "tutorial": "Let's call a section $[l, r]$ bad if $[p_l, p_{l+1}, \\dots, p_{r-1}, p_r]$ is a permutation of $[l, l + 1, \\dots, r - 1, r]$ and $l \\leq r \\leq m_l$. Let's call a section $[l, r]$ primitive if it's a bad section and there are no section $[l', r']$ satisfying $[l', r']$ is also a bad section and $[l, r]$ covers $[l', r']$. Lemma. For all primitive sections, none two of them intersect. Proof. If $[l_1, r_1]$ is a bad section, $[l_2, r_2]$ is a bad section and $l_1 < l_2 < r_1 < r_2$, the section $[l_2, r_1]$ will also be a bad section, but both $[l_1, r_1]$ and $[l_2, r_2]$ covers $[l_2, r_1]$, so $[l_1, r_1]$ and $[l_2, r_2]$ can't be primitive at the same time. Let's use the principle of inclusion-exclusion and dynamic programming to solve the problem. Let's define $f(l, r)$ as the number of $p_l, p_{l+1}, \\dots, p_{r-1}, p_r$ which is a primitive section. By the principle of inclusion-exclusion, we count the ways to fix $k$ primitive sections in range $[l, r]$, and arrange the rest arbitrarily. Then we can define $g_{1/2}(l, r, x)$ as the number of ways to fix $k$ ($k$ is odd/even) primitive sections in range $[l, r]$, and the number of the positions which doesn't cover by any primitive section is $x$. Finally we define $g(l, r, x) = g_2(l, r, x) - g_1(l, r, x)$, We will have the following transition: $\\forall l \\leq r \\leq m_l, f(l, r) = \\sum_{x=0}^{r-l+1} g(l, r, x) \\times x! + f(l, r)$ $\\forall l \\leq r \\leq m_l, f(l, r) = \\sum_{x=0}^{r-l+1} g(l, r, x) \\times x! + f(l, r)$ $g(l, r, x) = g(l, r - 1, x - 1) - \\sum_{mid=l}^r g(l, mid - 1, x )\\times f(mid, r)$ $g(l, r, x) = g(l, r - 1, x - 1) - \\sum_{mid=l}^r g(l, mid - 1, x )\\times f(mid, r)$ Tips. In the transition of $f(l, r)$, We add $f(l, r)$ because $f(l, r)$ contributes to $g(l, r, 0)$, but it should not contribute to $f(l, r)$, This problem can be solved by ordering the transitions. According to the definition, $\\sum_{x=0}^{n} g(1, n, x) \\times x!$ is the answer. Time complexity: $O(n^4)$ Memory complexity: $O(n^3)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nconst ll N = 200 + 5, Mod = 1e9 + 7;\nll n = 0, m[N] = {}, fac[N] = {}, f[N][N] = {}, g[N][N][N] = {};\n\nint main(){\n\tscanf(\"%lld\", &n);\n\tfor(ll i = 1 ; i <= n ; i ++) scanf(\"%lld\", &m[i]);\n\tif(m[1] == n){\n\t\tprintf(\"0\");\n\t\treturn 0;\n\t}\n\tfac[0] = 1;\n\tfor(ll i = 1 ; i <= n ; i ++) fac[i] = fac[i - 1] * i % Mod;\n\tfor(ll i = 1 ; i <= n ; i ++) g[i][i - 1][0] = 1;\n\tfor(ll l = n ; l >= 1 ; l --) for(ll r = l ; r <= n ; r ++){\n\t\tfor(ll x = 1 ; x <= r - l + 1 ; x ++) g[l][r][x] = g[l][r - 1][x - 1];\n\t\tfor(ll mid = l ; mid < r ; mid ++) if(r <= m[mid + 1]) for(ll x = 0 ; x <= mid - l + 1 ; x ++) g[l][r][x] = (g[l][r][x] + g[l][mid][x] * (Mod - f[mid + 1][r])) % Mod;\n\t\tfor(ll x = 0 ; x <= r - l + 1 ; x ++) f[l][r] = (f[l][r] + g[l][r][x] * fac[x]) % Mod;\n\t\tif(r <= m[l]) g[l][r][0] = (g[l][r][0] + (Mod - f[l][r])) % Mod;\n\t}\n\tprintf(\"%lld\", f[1][n]);\n\treturn 0;\n}\n",
    "tags": [
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1874",
    "index": "G",
    "title": "Jellyfish and Inscryption",
    "statement": "Jellyfish loves playing a game called \"Inscryption\" which is played on a directed acyclic graph with $n$ vertices and $m$ edges. All edges $a \\to b$ satisfy $a < b$.\n\nYou need to move from vertex $1$ to vertex $n$ along the directed edges, and then fight with the final boss.\n\nYou will collect \\textbf{cards} and \\textbf{props} in the process.\n\nEach \\textbf{card} has two attributes: HP and damage. If a \\textbf{card's} HP is $a$ and its damage is $b$, then the power of the \\textbf{card} is $a \\times b$.\n\nEach \\textbf{prop} has only one attribute: power.\n\nIn addition to vertex $1$ and vertex $n$, there are some vertices that trigger special events. The special events are:\n\n- You will get a \\textbf{card} with $a$ HP, and $b$ damage.\n- If you have at least one \\textbf{card}, choose one of your \\textbf{cards} and increase its HP by $x$.\n- If you have at least one \\textbf{card}, choose one of your \\textbf{cards} and increase its damage by $y$.\n- You will get a \\textbf{prop} with $w$ power.\n\nWhen you get to vertex $n$, you can choose \\textbf{at most one} of your \\textbf{cards} and multiply its damage by $10^9$.\n\nThe final boss is very strong, so you want to maximize the sum of the power of all your \\textbf{cards} and \\textbf{props}. Find the maximum possible sum of power of all your \\textbf{cards} and \\textbf{props} if you play the game optimally.",
    "tutorial": "For convenience, let's define $k = \\max(a, b, x, y)$, use operation 1 for \"You will get a card with $a$ HP, and $b$ damage\", operation 2 for \"If you have at least one card, choose one of your cards and increase its HP by $x$\" and operation 3 for \"If you have at least one card, choose one of your cards and increase its damage by $y$\", operation 4 for \"You will get a prop with $w$ power\", operation 5 for \"You can choose at most one of your cards and multiply its damage by $10^9$\", \"the $i$-th card\" for the card we get from vertex $i$ (It must be operation 1 on vertex $i$), \"do operation 2/3/5 onto card $i$\" for \"When we do this operation 2/3/5, we will choose the card $i$ and increase his HP or damage\". Let us consider the problem without the operation 5, what's the maximum possible answer. If you want to maximize the the sum of the power of your cards, the answer will not exceeding $(100 \\times 200)^2 = 4 \\times 10^8$; If you you want to maximize the the sum of the power of your props, the answer will not exceeding $200 \\times 10^6 = 2 \\times 10^8$. Because $4 \\times 10^8 + 2 \\times 10^8 = 6 \\times 10^8 < 10^9$, so the operation $n$ is the most important. Let's called the card we wil do the operation 5 onto it the \"flash card\". Let's use meet-in-the-middle, the problem is divided into two subproblems - the game before we get the flash card and the game after we get the flash card. It's a easy problem, we can use dynamic programming to solve this problem. Since the most important thing is the HP and damage of the flash card, so we define the following dynamic programming state: $dp_b(u, a)$ means we are current at vertex $u$, the current HP of the flash card is $a$, the maximum damage of the flash card. $dp_c(u, a)$ means we are current at vertex $u$, the current HP of the flash card is $a$, the damage of the flash card is $dp_b(u, a)$, the maximum sum of the power of all the other cards and props. Since $a \\leq nk$, the time complexity of the transition is $O(m \\times n \\times k)$. This is the key of the problem, and since it's much more difficult, we first consider the subproblems of this problem. Lemma. We will do all the operation 2 onto one of the cards, symmetrically we will also do all the operation 3 onto one of the cards. Proof. We consider a sequence of operations, let's consider if we do all the operation 1 on the card with the max damage after doing all the operation 2, the answer won't be worse, we can do all the operation 1 onto this card instead, then we make a symmetrical adjustment, the answer won't be worse, and all the operation 2 is done onto one of the cards, all the operation 3 is done onto one of the cards. It's similar to the subproblem I. If we say subproblem I is like a \"global max value\", then subproblem II is like a \"prefix max value\". Let's define $p_i$ means we will do the operation 2/3 on vertex $i$ onto the $p_i$-th card. Lemma1. If there is a operation 2 on vertex $i$ and a operation 2 on vertex $j$, if $p_i < j < i$, we will have $p_j = p_i$. Proof. Let's consider the final HP and damage of the cards after all the operations. Because we do the operation 2 on vertex $i$ onto the $p_i$-th card, for all $i' < i$, the damage of the $i'$-th card is not larger than the $p_i$-th card. So for $j$, if we don't do the operation 2 on vertex j onto the $p_i$-th card, we can do it onto the $p_i$-th card instead, the answer won't be worse. Symmetrically, Lemma1 is also correct for operation 3. Now we can use dynamic programming to solve the problem, we define the following dynamic programming state: $f(u, a, b)$ means we are current at vertex $u$, we will do the next several operation 3 onto a card with $a$ HP after all the operations and we will do the next several operation 2 onto a card with $b$ damage after all the operations, and this two cards are not the same. $g(u, a, b)$ means we are current at vertex $u$, We will do the next several operation 2 and operation 3 onto a card currently having $a$ HP and $b$ damage. The time complexity is $O(m \\times n^2 \\times k^2)$, but it's not enough. Lemma2. If a card has $a$ HP and $b$ damage after all the operations and it's not the flash card, $\\min(a, b) \\leq k$. Proof. If we use this card as the flash card instead of the last one, and do all the operations done onto the last flash card onto this card, the power of the flash card will be larger. So it won't exist in this half problem. Now the time complexity becomes $O(m \\times n \\times k^2)$, it's still not enough. Lemma3. Let's define $A$ as the maximum HP of all the cards except the flash card after all the operations, $B$ as the maximum damage of all the cards except the flash card after all the operations, $\\min(A, B) \\leq k$. Proof. Let's assume that the $i$-th card has $A$ HP after all the operations, the $j$-th card has $B$ damage after all the operations and $A > k, B > k$. If $i = j$, it conflicts with Lemma 2; If $i < j$, because of the Lemma 2, the HP of the $j$-th card after all the operations won't exceed $k$, let's use $A'$ as the HP of the $j$-th card after all the operations, and $B > k$, so we have done some operation 3 onto the $j$-th card. But because $A > k \\geq A'$, if we do these operations onto the $i$-th card, the answer will be better; If $i > j$, it's symmetric with $i < j$. But we can make the dynamic programming state better: $f(u, a, b)$ means we are current at vertex $u$, we will do the next several operation 3 onto a card with $a$ HP after all the operations and we will do the next several operation 2 onto a card with $b$ damage after all the operations, and this two cards are not the same. $f(u, a, b)$ means we are current at vertex $u$, we will do the next several operation 3 onto a card with $a$ HP after all the operations and we will do the next several operation 2 onto a card with $b$ damage after all the operations, and this two cards are not the same. $g_a(u, a, a')$ means we are current at vertex $u$, we will do the next several operation 3 onto a card with $a$ HP after all the operations, we will do the next several operation 2 onto a card and totally increase $a'$ HP in the next several operations to reach it's HP after all the operations. $g_a(u, a, a')$ means we are current at vertex $u$, we will do the next several operation 3 onto a card with $a$ HP after all the operations, we will do the next several operation 2 onto a card and totally increase $a'$ HP in the next several operations to reach it's HP after all the operations. $g_b(u, b, b')$ it's symmetric with $g_a$, just swap \"HP\" and \"damage\". $g_b(u, b, b')$ it's symmetric with $g_a$, just swap \"HP\" and \"damage\". Let's define $A$ as the maximum HP of all the cards except the flash card after all the operations, $B$ as the maximum damage of all the cards except the flash card after all the operations. We will find the $a, a', b, b'$ in $f, g_a, g_b$ is $O(k)$ because if $A \\leq k$, using $g_a$ we can get the right answer, if $B \\leq k$, using $g_b$ we can get the right answer. the time complexity of the transition is $O(m \\times k^2)$. The transition is very complex, you can see more details in my code : ) In my code, I use $g(u)$ to make the transition better. When $a'$ or $b'$ reaches $0$, we reaches the vertex $u$ and there is a operation 1 on vertex $u$, I don't enumerate the value of the next $a$ and $b$ while transiting. I transit it to $g(u)$ first, and enumerate the value of the next $a$ and $b$ together. Since the path is a chain, and we use dynamic programming to solve the problem. There's no difference whether the graph is a chain. Time complexity: $O(m(nk+k^2))$ Memory complexity: $O(n^2k+nk^2)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nconst int N = 200 + 5;\nconst ll lim = 1e9;\n\ninline void checkmax(int &x, int y){\n\tif(y > x) x = y;\n}\n\ninline void checkmax(ll &x, ll y){\n\tif(y > x) x = y;\n}\n\ninline void checkmax(pair<int, int> &x, pair<int, int> y){\n\tif(y > x) x = y;\n}\n\nint n = 0, m = 0, k = 0, opt[N] = {}, a[N] = {}, b[N] = {}, w[N] = {};\nint f[N][N][N] = {}, g[N] = {}, g_a[N][N][N] = {}, g_b[N][N][N] = {};\npair<int, int> dp[N][N * N] = {};\nvector<vector<int> > G(N);\n\nint main(){\n\tscanf(\"%d %d\", &n, &m);\n\tfor(int u = 1 ; u <= n ; u ++){\n\t\tscanf(\"%d\", &opt[u]);\n\t\tif(opt[u] == 1) scanf(\"%d %d\", &a[u], &b[u]);\n\t\telse if(opt[u] == 2) scanf(\"%d\", &a[u]);\n\t\telse if(opt[u] == 3) scanf(\"%d\", &b[u]);\n\t\telse if(opt[u] == 4) scanf(\"%d\", &w[u]);\n\t\tk = max(k, max(a[u], b[u]));\n\t}\n\tfor(int i = 1, u = 0, v = 0 ; i <= m ; i ++){\n\t\tscanf(\"%d %d\", &u, &v);\n\t\tG[u].push_back(v);\n\t}\n\tmemset(f, -1, sizeof(f));\n\tmemset(g, -1, sizeof(g)), memset(g_a, -1, sizeof(g_a)), memset(g_b, -1, sizeof(g_b));\n\tmemset(dp, -1, sizeof(dp));\n\tf[1][0][0] = 0;\n\tfor(int u = 1 ; u <= n ; u ++){\n\t\tif(opt[u] == 1 && g[u] != -1){\n\t\t\tfor(int x = a[u] ; x <= k ; x ++) checkmax(g_a[u][x][x - a[u]], g[u] + x * b[u]);\n\t\t\tfor(int x = b[u] ; x <= k ; x ++) checkmax(g_b[u][x][x - b[u]], g[u] + x * a[u]);\n\t\t\tcheckmax(dp[u][a[u]], make_pair(b[u], g[u]));\n\t\t}\n\t\tfor(int v : G[u]){\n\t\t\tif(opt[v] == 1){\n\t\t\t\tfor(int x = 0 ; x <= k ; x ++) for(int y = 0 ; y <= k ; y ++){\n\t\t\t\t\tif(f[u][x][y] != -1){\n\t\t\t\t\t\tcheckmax(f[v][max(x, a[v])][max(y, b[v])], f[u][x][y] + a[v] * b[v]);\n\t\t\t\t\t\tcheckmax(g[v], f[u][x][y]);\n\t\t\t\t\t}\n\t\t\t\t\tif(g_a[u][x][y] != -1){\n\t\t\t\t\t\tcheckmax(g_a[v][max(x, a[v])][y], g_a[u][x][y] + a[v] * b[v]);\n\t\t\t\t\t\tif(!y){\n\t\t\t\t\t\t\tcheckmax(g[v], g_a[u][x][y]);\n\t\t\t\t\t\t\tcheckmax(f[v][x][b[v]], g_a[u][x][y] + a[v] * b[v]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(g_b[u][x][y] != -1){\n\t\t\t\t\t\tcheckmax(g_b[v][max(x, b[v])][y], g_b[u][x][y] + a[v] * b[v]);\n\t\t\t\t\t\tif(!y){\n\t\t\t\t\t\t\tcheckmax(g[v], g_b[u][x][y]);\n\t\t\t\t\t\t\tcheckmax(f[v][a[v]][x], g_b[u][x][y] + a[v] * b[v]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor(int x = 0 ; x <= n * k ; x ++) if(dp[u][x] != make_pair(-1, -1)){\n\t\t\t\t\tint y = dp[u][x].first, z = dp[u][x].second;\n\t\t\t\t\tcheckmax(dp[v][x], make_pair(y, z + a[v] * b[v]));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(opt[v] == 2){\n\t\t\t\tfor(int x = 0 ; x <= k ; x ++) for(int y = 0 ; y <= k ; y ++){\n\t\t\t\t\tif(f[u][x][y] != -1) checkmax(f[v][x][y], f[u][x][y] + a[v] * y);\n\t\t\t\t\tif(g_a[u][x][y] != -1 && y >= a[v]) checkmax(g_a[v][x][y - a[v]], g_a[u][x][y]);\n\t\t\t\t\tif(g_b[u][x][y] != -1) checkmax(g_b[v][x][y], g_b[u][x][y] + a[v] * x);\n\t\t\t\t}\n\t\t\t\tfor(int x = 0 ; x <= n * k ; x ++) if(dp[u][x] != make_pair(-1, -1)){\n\t\t\t\t\tint y = dp[u][x].first, z = dp[u][x].second;\n\t\t\t\t\tcheckmax(dp[v][x + a[v]], make_pair(y, z));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(opt[v] == 3){\n\t\t\t\tfor(int x = 0 ; x <= k ; x ++) for(int y = 0 ; y <= k ; y ++){\n\t\t\t\t\tif(f[u][x][y] != -1) checkmax(f[v][x][y], f[u][x][y] + x * b[v]);\n\t\t\t\t\tif(g_a[u][x][y] != -1) checkmax(g_a[v][x][y], g_a[u][x][y] + x * b[v]);\n\t\t\t\t\tif(g_b[u][x][y] != -1 && y >= b[v]) checkmax(g_b[v][x][y - b[v]], g_b[u][x][y]);\n\t\t\t\t}\n\t\t\t\tfor(int x = 0 ; x <= n * k ; x ++) if(dp[u][x] != make_pair(-1, -1)){\n\t\t\t\t\tint y = dp[u][x].first, z = dp[u][x].second;\n\t\t\t\t\tcheckmax(dp[v][x], make_pair(y + b[v], z));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfor(int x = 0 ; x <= k ; x ++) for(int y = 0 ; y <= k ; y ++){\n\t\t\t\t\tif(f[u][x][y] != -1) checkmax(f[v][x][y], f[u][x][y] + w[v]);\n\t\t\t\t\tif(g_a[u][x][y] != -1) checkmax(g_a[v][x][y], g_a[u][x][y] + w[v]);\n\t\t\t\t\tif(g_b[u][x][y] != -1) checkmax(g_b[v][x][y - b[v]], g_b[u][x][y] + w[v]);\n\t\t\t\t}\n\t\t\t\tfor(int x = 0 ; x <= n * k ; x ++) if(dp[u][x] != make_pair(-1, -1)){\n\t\t\t\t\tint y = dp[u][x].first, z = dp[u][x].second;\n\t\t\t\t\tcheckmax(dp[v][x], make_pair(y, z + w[v]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tll ans = f[n][0][0];\n\tfor(int x = 0 ; x <= n * k ; x ++) if(dp[n][x] != make_pair(-1, -1)){\n\t\tint y = dp[n][x].first, z = dp[n][x].second;\n\t\tcheckmax(ans, lim * x * y + z);\n\t}\n\tprintf(\"%lld\", ans);\n\treturn 0;\n}\n",
    "tags": [
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1875",
    "index": "A",
    "title": "Jellyfish and Undertale",
    "statement": "Flowey has planted a bomb in Snowdin!\n\nThe bomb has a timer that is initially set to $b$. Every second, the timer will decrease by $1$. When the timer reaches $0$, the bomb will explode! To give the residents of Snowdin enough time to evacuate, you will need to delay the bomb from exploding for as long as possible.\n\nYou have $n$ tools. Each tool can only be used \\textbf{at most} once. If you use the $i$-th tool, the timer will increase by $x_i$. However, if the timer is changed to an integer larger than $a$, the timer will be set to $a$ due to a bug.\n\nMore specifically, the following events will happen every second in the following order:\n\n- You will choose some (possibly none) of your tools that have not been used before. If you choose the $i$-th tool, and the bomb's timer is currently set to $c$, the timer will be changed to $\\min(c + x_i, a)$.\n- The timer decreases by $1$.\n- If the timer reaches $0$, the bomb explodes.\n\nJellyfish now wants to know the maximum time in seconds until the bomb explodes if the tools are used optimally.",
    "tutorial": "We can use one tool each time the timer reaches to $1$, then the answer will be $\\sum_{i=1}^n \\min(a - 1, x_i) + b$. This can prove to be optimal. Because for each tool, if we use it when the timer is $c$, its contribution to the answer is $\\min(x_i, a - c)$. We can't use the tool when the timer is less than or equal to $0$ because the bomb will explode before that, so $c=1$ is the optimal. Time complexity: $O(n)$ per test case. Memory complexity: $O(1)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n = 0, a = 0, b = 0;\nlong long ans = 0;\n\ninline void solve(){\n\tscanf(\"%d %d %d\", &a, &b, &n);\n\tans = b;\n\tfor(int i = 0, x = 0 ; i < n ; i ++){\n\t\tscanf(\"%d\", &x);\n\t\tans += min(a - 1, x);\n\t}\n\tprintf(\"%lld\\n\", ans);\n}\n\nint T = 0;\n\nint main(){\n\tscanf(\"%d\", &T);\n\tfor(int i = 0 ; i < T ; i ++) solve();\n\treturn 0;\n}\n",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1875",
    "index": "C",
    "title": "Jellyfish and Green Apple",
    "statement": "Jellyfish has $n$ green apple pieces. Each green apple piece weighs $1~\\text{kg}$. Jellyfish wants to divide these green apple pieces \\textbf{equally} among $m$ people.\n\nJellyfish has a magic knife. Each time Jellyfish can choose one piece of green apple and divide it into two smaller pieces, with each piece having half the weight of the original piece.\n\nJellyfish wants to know the minimum number of operations needed such that she can divide the green apple pieces such that the total weight of apple pieces received by each person is the same.",
    "tutorial": "Firstly, if $n \\geq m$, we can make the problem transform $n < m$ by giving each person an apple at a time until there are not enough apples. We can calculate the mass of apples that each person ends up with as $\\frac n m$. Since it's cut in half every time, if $\\frac m {\\gcd(n, m)}$ is not an integral power of $2$, there's no solution. Since the number of apple pieces is added to exactly $1$ for each cut, So we just need to minimize the final number of apple pieces. As the problem is transformed, $\\frac n m$ is less than $1$, and $\\frac m {\\gcd(n, m)}$ is an integral power of $2$. So we can uniquely find a set of positive integers $S$ satisfying $\\frac n m = \\sum_{i \\in S} \\frac 1 {2^i}$. And this method can be proven to be optimal, if we find another multiset $T$ satisfying $S \\neq T$, for every element $x$ that appears twice or more, We can make the answer better by removing two $x$ at a time from $T$ and adding one $x - 1$ to $T$. By repeating this process, eventually $T$ will become $S$. We can use $\\text{std::__builtin_popcount()}$ to get $|S|$, the answer is $m \\times |S|-n$. Time complexity: $O(\\log m)$ per test case. Memory complexity: $O(1)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n = 0, m = 0;\n\ninline void solve(){\n\tscanf(\"%d %d\", &n, &m); n %= m;\n\tint a = n / __gcd(n, m), b = m / __gcd(n, m);\n\tif(__builtin_popcount(b) > 1) printf(\"-1\\n\");\n\telse printf(\"%lld\\n\", 1ll * __builtin_popcount(a) * m - n);\n}\n\nint T = 0;\n\nint main(){\n\tscanf(\"%d\", &T);\n\tfor(int i = 0 ; i < T ; i ++) solve();\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1875",
    "index": "D",
    "title": "Jellyfish and Mex",
    "statement": "You are given an array of $n$ nonnegative integers $a_1, a_2, \\dots, a_n$.\n\nLet $m$ be a variable that is initialized to $0$, Jellyfish will perform the following operation $n$ times:\n\n- select an index $i$ ($1 \\leq i \\leq |a|$) and delete $a_i$ from $a$.\n- add $\\operatorname{MEX}(a)^{\\dagger}$ to $m$.\n\nNow Jellyfish wants to know the minimum possible final value of $m$ if he performs all the operations optimally.\n\n$^{\\dagger}$ The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$ because $0$, $1$, $2$, and $3$ belong to the array, but $4$ does not.",
    "tutorial": "We only care about the operation before $\\text{MEX}(a)$ reaches $0$, because after that, $m$ will never change. Lemma. Before $\\text{MEX}(a)$ reaches $0$, we will choose a positive integer $x$ at a time that satisfies $x < \\text{MEX}(a)$, and delete all $x$ from $a$, the $\\text{MEX}(a)$ will become $x$. Proof. Because if $x > \\text{MEX}(a)$, we can place this operation after the $\\text{MEX}(a)$ becomes $0$, if we don't delete all of $x$, $\\text{MEX}(a)$ won't change, we can also put this operation later. So before $\\text{MEX}(a)$ reaches $0$, the $x$ we delete is non-increasing. It means we can solve this problem by dynamic programming. Let $dp_i$ represents when $\\text{MEX}(a)=i$, and we haven't delete any $x$ satisfying $x < i$,the minimum value of $m$. Let $c_i$ represents the number of times $i$ appears in $a$, the transition is: $\\forall j < i, dp_j \\leftarrow dp_i + i \\times (c_j - 1) + j$. Time complexity: $O(n^2)$ per test case. Memory complexity: $O(n)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nconst ll N = 5000 + 5, Inf = 0x3f3f3f3f3f3f3f3f;\nll n = 0, m = 0, a[N] = {}, dp[N] = {};\n\ninline void init(){\n\tfor(ll i = 0 ; i <= n ; i ++) a[i] = 0, dp[i] = Inf;\n\tn = m = 0;\n}\n\ninline void solve(){\n\tscanf(\"%lld\", &n);\n\tfor(ll i = 1, x = 0 ; i <= n ; i ++){\n\t\tscanf(\"%lld\", &x);\n\t\tif(x < n) a[x] ++;\n\t}\n\twhile(a[m]) m ++;\n\tdp[m] = 0;\n\tfor(ll i = m ; i >= 1 ; i --) for(ll j = 0 ; j < i ; j ++) dp[j] = min(dp[j], dp[i] + i * a[j]);\n\tprintf(\"%lld\\n\", dp[0] - m);\n}\n\nll T = 0;\n\nint main(){\n\tmemset(dp, 0x3f, sizeof(dp));\n\tscanf(\"%lld\", &T);\n\tfor(ll i = 0 ; i < T ; i ++) init(), solve();\n\treturn 0;\n}\n",
    "tags": [
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1876",
    "index": "A",
    "title": "Helmets in Night Light",
    "statement": "Pak Chanek is the chief of a village named Khuntien. On one night filled with lights, Pak Chanek has a sudden and important announcement that needs to be notified to all of the $n$ residents in Khuntien.\n\nFirst, Pak Chanek shares the announcement directly to one or more residents with a cost of $p$ for each person. After that, the residents can share the announcement to other residents using a magical helmet-shaped device. However, there is a cost for using the helmet-shaped device. For each $i$, if the $i$-th resident has got the announcement at least once (either directly from Pak Chanek or from another resident), he/she can share the announcement to at most $a_i$ other residents with a cost of $b_i$ \\textbf{for each share}.\n\nIf Pak Chanek can also control how the residents share the announcement to other residents, what is the minimum cost for Pak Chanek to notify all $n$ residents of Khuntien about the announcement?",
    "tutorial": "Notice that since there are $n$ residents, there must be $n$ shares. There are two types of shares. A share directly by Pak Chanek to a resident, and a share by a resident to another resident. A share by Pak Chanek is unlimited, while a share by a resident is limited by $a_i$. So there are unlimited shares with cost $p$ and for each $i$, there are $a_i$ shares with cost $b_i$. In the beginning, no residents are notified about the announcement, so Pak Chanek must share once to some resident in the beginning. After that, since there are $n-1$ residents remaining, there must be $n-1$ shares. Theoretically, the lowerbound of the minimum cost is the $n-1$ cheapest shares (including Pak Chanek's shares). Turns out, there is always a strategy to use the $n-1$ cheapest shares to notify all $n$ residents after the first share by Pak Chanek. The strategy is we share the announcement to the residents with the smallest values of $b_i$ first. Using the fact that $a_i\\geq1$, we can deduce that we will always have a resident with an available share. We can solve this using a simple sorting or a priority queue. Keep in mind about the unlimited shares with cost $p$. Time complexity for each test case: $O(n\\log n)$",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1876",
    "index": "B",
    "title": "Effects of Anti Pimples",
    "statement": "Chaneka has an array $[a_1,a_2,\\ldots,a_n]$. Initially, all elements are white. Chaneka will choose one or more different indices and colour the elements at those chosen indices black. Then, she will choose all white elements whose indices are multiples of the index of \\textbf{at least one} black element and colour those elements green. After that, her score is the \\textbf{maximum} value of $a_i$ out of all black and green elements.\n\nThere are $2^n-1$ ways for Chaneka to choose the black indices. Find the sum of scores for all possible ways Chaneka can choose the black indices. Since the answer can be very big, print the answer modulo $998\\,244\\,353$.",
    "tutorial": "For some value $w$, let $f(w)$ be the number of different ways to choose the black indices such that the score is exactly $w$ and let $g(w)$ be the number of different ways to choose the black indices such that the score is at most $w$. Then $f(w) = g(w) - g(w-1)$. Let's try to calculate $g(w)$. First, group the elements in $a$ into two groups, with group 1 containing elements with values greater than $w$ and group 2 containing elements with values not greater than $w$. Notice that the only requirement we must satisfy is to not make any group 1 element black or green and we can do anything to the group 2 elements. In order to make sure that no group 1 element is black or green, we must make sure that no black index we choose is a factor of at least one group 1 index. This means, we just need calculate some value $c$ that represents the number of different indices that is a factor at least one group 1 index, then the value of $g(w)$ is $2^{n-c}-1$. The answer to the original problem is the sum of $f(w)\\cdot w$ for all possible values $w$. However, we just care about the values $w$ such that $f(w)\\neq0$, which only happens if $w$ is equal to the value of some element of $a$. In order to calculate $g(w)$ for all desired values of $w$, we need to iterate the elements of $a$ from the biggest value to the smallest value. Each element we iterate, we iterate every index that is a factor of the index of the current element and mark those indices as group 1 while we keep track of the value of $c$. The total number of iterations is the total number of factors for every index, which is $n\\log n$. Time Complexity: $O(n\\log n)$",
    "tags": [
      "combinatorics",
      "number theory",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1876",
    "index": "C",
    "title": "Autosynthesis",
    "statement": "Chaneka writes down an array $a$ of $n$ positive integer elements. Initially, all elements are not circled. In one operation, Chaneka can circle an element. It is possible to circle the same element more than once.\n\nAfter doing all operations, Chaneka makes a sequence $r$ consisting of all \\textbf{uncircled} elements of $a$ following the order of their indices.\n\nChaneka also makes another sequence $p$ such that its length is equal to the number of operations performed and $p_i$ is the \\textbf{index} of the element that is circled in the $i$-th operation.\n\nChaneka wants to do several operations such that sequence $r$ is equal to sequence $p$. Help her achieve this, or report if it is impossible! Note that if there are multiple solutions, you can print any of them.",
    "tutorial": "Let's say we have coloured each element of $a$ into black or white and we want to find a sequence of operations that results in all black elements being circles and all white elements being uncircled. Notice that such a sequence exists if and only if the following holds: For each black element, there must exist at least one white element with a value equal to the index of that black element. (There must be a value in $p$ that circles that black element) For each white element, there cannot be any white element with a value equal to the index of that black element. (There cannot be a value in $p$ that circles that white element) Construct a directed graph of $n$ vertices and $n$ directed edges. Each edge $i$ is from vertex $i$ to vertex $a_i$. For an edge from $x$ to $y$, define $x$ as a child of $y$ and define $y$ as a parent of $x$. Notice that each vertex only has exactly one parent. This means that each connected component in the graph looks like a directed rooted tree with a cycle of arbitrary size at the root. Let each vertex $i$ represent whether element $a_i$ is white or black. From the knowledge above, we can get the following for determining the colour of a certain vertex: If it has at least one white child, then it must be black. If it has no white children, then it must be white. This means we can determine the colour of a vertex once we have determined the colours of its children. Additionally, once there is at least one white child, we can guarantee the vertex to be black. We can solve this by maintaining a queue. First, fill the queue with each vertex with no children ($0$ indegree). When we process a vertex in the queue, determine the colour using the rules above, and then decrease the indegree of its parent (as if the current processed vertex is deleted from the graph). If the indegree of the parent reaches $0$, add the parent to the queue. In particular, if the current vertex is white, we can immediately determine the colour of the parent to be black and add it to the queue as well. The process stops once there are no vertices left with $0$ indegrees and none of the remaining vertices has a white child. Because of the special structure of the graph, once this happens, the remaining graph only contains zero or more disjoint cycles. Let's solve each cycle independently. Notice that if a cycle is of even length, we can colour its vertices black and white alternatingly. However, if a cycle is of odd length, it is impossible to colour it. Time complexity: $O(n)$",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1876",
    "index": "D",
    "title": "Lexichromatography",
    "statement": "Pak Chanek loves his faculty, the Faculty of Computer Science, University of Indonesia (Fasilkom). He wants to play with the colours of the faculty's logo, blue and red.\n\nThere is an array $a$ consisting of $n$ elements, element $i$ has a value of $a_i$. Pak Chanek wants to colour each element in the array blue or red such that these following conditions are satisfied:\n\n- If all blue elements are formed into a subsequence$^\\dagger$ and so are all the red elements, the blue subsequence is strictly less than the red subsequence lexicographically$^\\ddagger$.\n- Array $a$ does not have \\textbf{any subarray} that is imbalanced. A subarray is imbalanced if and only if there is a value $k$ such that the absolute difference between the number of blue elements with value $k$ and the number of red elements with value $k$ in this subarray is $2$ or more.\n- Note that it is possible to colour every element of the array the same colour.\n\nHow many different colourings satisfy all those conditions? Since the answer can be very big, print the answer modulo $998\\,244\\,353$. Two colourings are different if and only if there is at least one element that is blue in one colouring, but red in the other.\n\n$^\\dagger$ A subsequence of an array is a sequence that can be obtained from the array by deleting some elements (possibly none), without changing the order of the remaining elements.\n\n$^\\ddagger$ Let $p$ and $q$ be two different sequences. Sequence $p$ is said to be lexicographically less than sequence $q$ if and only if $p$ is a prefix of $q$ or there is an index $i$ such that $p_j=q_j$ holds for every $1\\leq j<i$, and $p_i<q_i$. In particular, an empty sequence is always lexicographically less than any non-empty sequence.",
    "tutorial": "There are two conditions in the problem. The lexicography condition and the imbalanced subarrays condition. Let's look at the imbalanced subarrays condition. Consider some value $k$ and consider all elements in $a$ with a value of $k$. In order to satisfy this condition, those elements must be coloured blue and red alternatingly from left to right. So for each value $k$ that is present in $a$, there are $2$ ways to colour its elements, either starting from blue or starting from red. This means, if we ignore the lexicography condition, the number of colourings is $2^c$ with $c$ representing the number of different values in $a$. From now on, we are only considering the colourings that satisfy the imbalanced subarray condition. Define the following: $\\text{less}$: the number of colourings with the blue subsequence less than the red subsequence lexicographically. $\\text{equal}$: the number of colourings with the blue subsequence equal to the red subsequence. $\\text{more}$: the number of colourings with the blue subsequence bigger than the red subsequence lexicographically. We can get that $\\text{less}+\\text{equal}+\\text{more}=2^c$. Furthermore, we can get that $\\text{less}=\\text{more}$ since we can always flip the colouring to get the opposite one. Therefore, $\\text{less}=\\frac{2^c-\\text{equal}}{2}$. Now, let's calculate the value of $\\text{equal}$. Iterate the array from left to right while simultaneously maintaining both the blue and red subsequences. During the iteration, we want both subsequences to be equal. For the first element, we can colour it either red or blue, and put the value of that element into its corresponding subsequence. We iterate each element but we stop the next time both subsequences have the same length. So if we colour the first element blue, then the blue subsequence will be longer than the red one throughout this process, until both subsequences have equal lengths. For each of the next elements, there are a few cases: If we have not found an element with this value before, we must put the element in the currently longer subsequence. (If we put it in the shorter subsequence it will not match with the corresponding element in the longer subsequence. If we have found an element with this value before, it must be the opposite colour than the previous one. This means we must put it in the shorter subsequence. If the corresponding element in the longer subsequence does not match, then $\\text{equal}=0$. Otherwise, we can continue the process. Once both subsequences have equal lengths, let's say we ignore all of the previous elements and the currently built subsequences and assume we continue iterating the array while forgetting about all things we did before. We cannot actually do this to calculate $\\text{equal}$ properly, but we will get to that later. Notice that continuing the iteration now is just like how we start in the beginning. We can choose the colour of the first element and every other element after that is forced until both subsequences have the same length. We continue doing this repeatedly until the end of $a$. If at the end of $a$, the lengths of both subsequences are different or we hit the $\\text{equal}=0$ case at least once, then $\\text{equal}=0$. Otherwise, from our assumption above, we can deduce that each time we add an element when both subsequences have equal lengths, we can freely choose the colour of that element. We can split $a$ into several sections where the sections are separated by the times both subsequences have the same length. Using our assumption above, the number of colourings is $2^d$ with $d$ being the number of sections, because there are $2$ starting colours we can choose for each section. However, as we have said before, when starting a new section, we cannot completely ignore the previous sections. Since the colouring of the elements with the same value must be alternating, two sections that have at least one common value must have the same starting colour. This means we can construct a graph of sections and connect the sections that have a common value with edges. Then, the true value of $\\text{equal}$ is $2^{d'}$ with $d'$ being the number of connected components. Time complexity: $O(n)$",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dsu",
      "graphs",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1876",
    "index": "E",
    "title": "Ball-Stackable",
    "statement": "With a problem title like that, there is no way this is going to be a graph problem.\n\nChaneka has a graph with $n$ vertices and $n-1$ edges. Some of the edges are directed and some of the edges are undirected. Edge $i$ connects vertex $u_i$ to vertex $v_i$. If $t_i=0$, edge $i$ is undirected. If $t_i=1$, edge $i$ is directed in the direction from $u_i$ to $v_i$. It is known that if you make all edges undirected, the graph becomes a tree$^\\dagger$.\n\nChaneka wants to direct all undirected edges and colour each edge (different edges can have the same colour).\n\nAfter doing that, suppose Chaneka starts a walk from an arbitrary vertex $x$ to an arbitrary vertex $y$ (it is possible that $x=y$) going through one or more edges. She is allowed to go through each edge either following the direction or opposite to the direction of the edge. She is also allowed to visit a vertex or an edge more than once. During the walk, Chaneka maintains a stack of balls that is initially empty before the walk. Each time Chaneka goes through an edge, she does the following:\n\n- If Chaneka goes through it in the right direction, she puts a new ball with a colour that is the same as the edge's colour to the top of the stack.\n- If Chaneka goes through it in the opposite direction, she removes the ball that is on the top of the stack.\n\nA walk is \\textbf{stackable} if and only if the stack is not empty before each time Chaneka goes through an edge in the opposite direction.\n\nA walk is \\textbf{ball-stackable} if and only if it is stackable and each time Chaneka goes through an edge in the opposite direction, the colour of the ball removed from the stack is the same as the colour of the edge traversed.\n\nIs it possible to direct all undirected edges and colour each edge such that all stackable walks are also ball-stackable? If it is possible, find a construction example that uses the \\textbf{maximum number of different colours} among all valid ways of directing and colouring. If there are multiple such solutions, output any of them.\n\n$^\\dagger$ A tree is a connected graph with no cycles.",
    "tutorial": "Let's try to solve the problem if all edges are directed. First, assign some arbitrary vertex $x$ as the root of the tree. Consider all walks that start from $x$. Notice that for a fixed vertex $y$, no matter how Chaneka walks from $x$, when she reaches $y$, the number of balls in the stack will always be the same. More precisely, if in the shortest path from $x$ to $y$ there are $c_1$ edges in the right direction and $c_2$ edges in the opposite direction, then the size of the stack in $y$ is $c_1-c_2$. For some root $x$, let's calculate the stack size of every vertex using DFS. What happens if the stack size that is calculated is negative? This conflicts with our logic, but let's ignore them for now. Next, find a vertex with the minimum stack size (including negative stack sizes). Then, assign this a the new root $x$ and do the same process to recalculate every stack size. Because of the way we choose the new $x$, the newly recalculated stack sizes will always be non-negative. Consider a path from this root to some other vertex and go through that path while maintaining a stack of colourful balls. Each time we go through an edge in the right direction, we add a new ball to the stack, so we have an opportunity to use a new colour for the edge (and simultaneously for the new ball). Each time we go through an edge in the opposite direction, we remove the ball at the top of the stack, so we must colour the edge to be equal to some ball we added before (the colour of some previous edge). We can simulate every path from this root to every other vertex by doing DFS once while maintaining a stack. Using the rules above, we get the rules for colouring the edges of the graph. In fact, simulating every path from this single root already solves the problem with all directed edges, because there are no other relationships between two edges that must have the same colour that we have not considered. Remember that we do not have to worry about removing from an empty stack because of how we smartly choose the root. Notice that using the rules above, each edge that is directed away from the root contributes to add one new different colour to the colouring while each edge that is directed towards the root does not add any new colour. This means we just want to maximize the total number of edges that is directed away from the root. We can expand this idea for the original problem with undirected edges. We need to find a root, then direct all undirected edges away from that root such that the number of edges directed away from that root is as many as possible. This is equivalent to finding a vertex such that the number of directed edges (ignoring all undirected edges) that is directed away from that vertex is maximum. This vertex can be found using a simple DFS. Furthermore, choosing such a vertex will automatically eliminates negative stack sizes if we set it as the root. Once we find the optimal root and direct the undirected edges, we just do a simulation DFS like above to determine the colouring. Time complexity: $O(n)$",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1876",
    "index": "F",
    "title": "Indefinite Clownfish",
    "statement": "Pak Chanek has just bought an empty fish tank and he has been dreaming to fill it with his favourite kind of fish, clownfish. Pak Chanek likes clownfish because of their ability to change their genders on demand. Because of the size of his fish tank, Pak Chanek wants to buy exactly $k$ clownfish to fill the tank.\n\nPak Chanek goes to the local fish shop. The shop provides $n$ clownfish numbered from $1$ to $n$, with clownfish $i$ having a size of $a_i$. Initially, every clownfish in the store does not have an assigned gender, but has the ability to be assigned to two possible clownfish genders, female or male.\n\nThe store has a procedure which Pak Chanek should follow to buy clownfish. The shop owner will point at each clownfish sequentially from $1$ to $n$ and for each clownfish, she asks Pak Chanek whether to buy it or not. Each time Pak Chanek is asked, he must declare whether to buy the currently asked clownfish or not, before the shop owner moves on to the next clownfish. If Pak Chanek declares to buy the currently asked clownfish, he must also declare the gender to be assigned to that clownfish immediately. When assigning the gender for the currently asked clownfish, the following conditions must be satisfied:\n\n- If Pak Chanek assigns it to be female and he has bought a female clownfish before, then the size of the current one must be exactly $1$ \\textbf{bigger} than the last female one.\n- If Pak Chanek assigns it to be male and he has bought a male clownfish before, then the size of the current one must be exactly $1$ \\textbf{smaller} than the last male one.\n\nPak Chanek wants to buy exactly $k$ clownfish such that:\n\n- There is at least one female clownfish and one male clownfish.\n- Among the $k$ clownfish Pak Chanek buys, the mean size of the female clownfish is equal to the mean size of the male clownfish.\n\nLet $l$ and $r$ respectively be the minimum and maximum \\textbf{index} of a clownfish Pak Chanek buys. What is the minimum possible value of $r-l$?",
    "tutorial": "We want to find two disjoint subsequences (for the females and the males) such that: The female subsequence contains consecutively increasing values. The male subsequence contains consecutively decreasing values The total length is exactly $k$. The mean values of both subsequences are the same. For a group of consecutive values with minimum value $\\text{min}$ and maximum value $\\text{max}$, the mean is $\\frac{\\text{max}+\\text{min}}{2}$. So we must make both values of $\\text{max}+\\text{min}$ the same. We can obtain that since both means are equal, the two subsequences must contain at least one common value. And a common value can only occur twice in the entirety of the two subsequences. For a way to choose the two subsequences, let $x$ be a common value of the two subsequences such that the difference in indices of its two occurences is minimum. Let $p$ and $q$ be the indices of the left and right occurences of $x$ respectively. There are two cases, either the $p$ is female and $q$ is male, or vice versa. If the $p$ is female, the following must be true: To the left $p$, in decreasing indices, the chosen subsequence (the female one) has the values $x-1$, $x-2$, $x-3$, and so on. To the right of $q$, in increasing indices, the chosen subsequence (the male one) has the values $x-1$, $x-2$, $x-3$, and so on. How about the values in the chosen subsequences that are bigger than $x$? Would they conflict in the indices between $p$ and $q$? Well, since we choose $x$ with the minimum difference in indices of its two occurences, then all values bigger than $x$ in the chosen subsequences that are located between $p$ and $q$ are either only from the female subsequence or only from the male subsequence. So, we only need to consider where for a fixed index that is either $p$ or $q$: To the left of that index, in decreasing indices, the chosen subsequence (the male one) has the values $x+1$, $x+2$, $x+3$, and so on. To the right of that index, in increasing indices, the chosen subsequence (the female one) has the values $x+1$, $x+2$, $x+3$, and so on. That means, if $p$ is female, there are two cases (either choosing the index to be $p$ or $q$). If $p$ is male, a similar thing also applies, but the roles of the values smaller than $x$ and the values bigger than $x$ are switched, so there are also two cases. So there are only four cases in total. Notice that in each of the four cases, we can see it as having a pair of indices $(p, q)$ with the same value and having four legs of consecutive values coming out of it in four different directions. Notice that the elements in different legs can never conflict with each other. Each leg is independent. Let's group the four legs into two groups, the two left legs and the two right legs. Next, define $\\text{min}_f$ and $\\text{max}_f$ as the minimum and maximum value in the female subsequence and define $\\text{min}_m$ and $\\text{max}_m$ as the minimum and maximum value in the male subsequence. It must hold that $\\text{max}_f+\\text{min}_f=\\text{max}_m+\\text{min}_m$. So $\\text{max}_m-\\text{min}_f=\\text{max}_f-\\text{min}_m$. Notice that $\\text{max}_m-\\text{min}_f$ is the total number of elements in the two left legs and $\\text{max}_f-\\text{min}_m$ is the total number of elements in the two right legs if we exclude $p$ and $q$. Since we want to make the number of elements in the two groups the same, each group must contain exactly $\\frac{k-2}{2}$ elements. This means if $k$ is odd, it is impossible. We obtain that we can handle the two groups independently. We just need to make sure the number of elements in one group is exactly $\\frac{k-2}{2}$. We want to minimise the value of $r-l$. This means, we want to maximise $l$ in the left group and minimise $r$ in the right group. These two tasks are equivalent, just mirrored. To solve this, let's construct a graph using the array. Each element $a_i$ in the array has four parents: The rightmost element to the left of it with value $a_i-1$. The rightmost element to the left of it with value $a_i+1$. The leftmost element to the right of it with value $a_i-1$. The leftmost element to the right of it with value $a_i+1$. For each type of parent, construct the binary lifting for it so that for each element, we can get its $d$-th parent of a certain for any value of $d$ in $O(\\log n)$. Using this, in order to calculate the maximum value of $l$ of the left group, we can do a binary search to find the optimal number of elements in each of the two left legs. We do the same thing for the right group. We do this for each of the four cases to finally find the minimum value of $r-l$ for a particular pair of $(p, q)$. We do that entire process repeatedly for all pairs of adjacent occurences of the same value. Time complexity: $O(n\\log^2n)$",
    "tags": [
      "binary search",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1876",
    "index": "G",
    "title": "Clubstep",
    "statement": "There is an extremely hard video game that is one of Chaneka's favourite video games. One of the hardest levels in the game is called Clubstep. Clubstep consists of $n$ parts, numbered from $1$ to $n$. Chaneka has practised the level a good amount, so currently, her familiarity value with each part $i$ is $a_i$.\n\nAfter this, Chaneka can do several (possibly zero) attempts on Clubstep. In each attempt, she dies on one of the $n$ parts. If an attempt dies on part $p$, that means it only successfully passes through every part $k$ for all $1 \\leq k \\leq p-1$ and it does not reach any part $k$ for all $p+1 \\leq k \\leq n$. An attempt that dies on part $p$ takes $p$ seconds.\n\nIt is known that Chaneka improves much more on the part she dies on than anything else. It is also known that during an attempt, Chaneka does not get to practise that much on the parts she does not reach. So, the effect of an attempt that dies on part $p$ is as follows:\n\n- Chaneka's familiarity value with part $p$ increases by $2$.\n- Chaneka's familiarity value with each part $k$ for all $1 \\leq k \\leq p-1$ increases by $1$.\n\nThere will be $q$ questions. For the $j$-th question, you are given three integers $l_j$, $r_j$, and $x_j$. Then, you are asked to find out the \\textbf{minimum time} (in seconds) for Chaneka to make it such that the familiarity value for every part $p$ ($l_j \\leq p \\leq r_j$) is at least $x_j$.Note that each question is independent, so the attempt Chaneka does on a question does not affect the familiarity values of any other questions.",
    "tutorial": "Let's try to solve a single query $(l,r,x)$ in $O(n)$. It is clear that in the optimal strategy, we do not want to do any attempts that die on parts to the left of $l$ or to the right of $r$. There are two cases: If $a_r\\geq x$, then we can ignore index $r$ and solve the query for $(l,r-1,x)$. If $a_r<x$, then it is optimal to do $\\lceil\\frac{x-a_r}{2}\\rceil$ attempts that die on part $r$. This takes $r\\cdot\\lceil\\frac{x-a_r}{2}\\rceil$ seconds and will make all indices from $1$ to $r-1$ increase by $\\lceil\\frac{x-a_r}{2}\\rceil$. After doing that, it is equivalent to ignoring index $r$ and solving the query for $(l,r-1,x-\\lceil\\frac{x-a_r}{2}\\rceil)$. For now, let's ignore $l$ and focus on $(r,x)$. For some pair $(r,x)$, there are two cases it can recurse into. We mainly care about the second case since it is the only one that contributes to the total time. For some pair $(r,x)$ of a query, we can turn it into $(r,x)$ where $r'$ ($r'\\leq r$) is the rightmost index with $a_{r'}<x$. For some pair $(r,x)$ with $a_r<x$, we can see it as the pair recursing immediately to $(r',x-\\lceil\\frac{x-a_r}{2}\\rceil)$ where $r'$ ($r'<r$) is the rightmost index with $a_{r'}<x-\\lceil\\frac{x-a_r}{2}\\rceil$. We want to maintain all important pairs $(r,x)$ that are needed to answer all queries. Two pairs with the same values of $r$ and $x$ that comes from different queries can be treated as the same pair. Let's imagine a process to calculate all important pairs $(r,x)$. To do this, we iterate $r$ from $n$ to $1$ while maintaining all of the current important values of $x$, including the ones not bigger than $a_r$. Each iteration, we just modify the values of $x$ from the previous iteration. For each $r$, we first add new values of $x$ for all queries with this current value of $r$. Then, the important pairs $(r,x)$ for this value of $r$ are all current values of $x$ that are greater than $a_r$. And those values of $x$ are the values of $x$ which will get updated (changed into $x-\\lceil\\frac{x-a_r}{2}\\rceil$) for the next iteration. If more than one value of $x$ updates into the same value, they merge and the number of values decreases. Using the logic of the process above, it can be obtained that the total number of important pairs $(r,x)$ is $O(n+q\\log\\max(x))$. Proof. Notice that the number of important pairs is about equal to the number of updates to the value of $x$ in all iterations. Let's calculate the total number of updates. Instead of looking at the values of $x$ that we maintain, let's sort those values and look at the gaps between adjacent values. For a value of $r$, the value of $a_r$ lies in one of the gaps. Then, that gap and all gaps located to the right of it in the number line will get updated. The gap that contains $a_r$ can change arbitrarily, but each gap that is to the right of that gap will have its length divided by $2$, either floored or ceilinged. This means, each gap can only have $\\log\\max(x)$ updates before having a length of $1$. Then, its length can get ceilinged multiple times before getting floored to $0$. When its length becomes $0$, the two values at the endpoints of the gap will merge. It may look like there can be many updates because a length of $1$ can be ceilinged multiple times. However, for every gap having its length divided by $2$ in an iteration, the case where a length of $1$ gets ceilinged cannot happen on two adjacent gaps, so if there are $c$ gaps updated, that particular case can only happen on $\\lceil\\frac{c}{2}\\rceil$ gaps. That means, the total number of updates is about two times the total number of times a gap gets its length decreased, plus the total number of gaps that contains $a_r$. Therefore, the total number of important pairs is $O(n+q\\log\\max(x))$. $\\blacksquare$ Knowing that, we can calculate all important pairs quickly using a stack and a priority queue. The stack maintains the current values of $x$ that have already been updated at least once. The priority queue only maintains new values of $x$ that have not been updated yet. In each iteration, we only process several values at the top of the stack and at the top of the priority queue, then each of those gets pushed into the stack with their new values, without changes in their order. The total number of operations in the stack is equal to the number of important pairs, but the total number of changes in the priority queue is only equal to the number of queries. So the total complexity of this is $O(n+q(\\log\\max(x)+\\log n))$. While calculating all important pairs, we can simultaneously construct a tree of pairs where the parent of each pair $(r,x)$ is its corresponding pair $(r',x-\\lceil\\frac{x-a_r}{2}\\rceil)$. We can solve each query using a simple binary lifting in the tree, but that would be too slow since there are $O(n+q\\log\\max(x))$ vertices. Instead, we can do a DFS traversal from the root while maintaining a stack of the values of $r$ in the DFS recursion. Solving a query in a vertex is just doing a binary search in the stack. So the total complexity of answering all queries is $O(n+(q\\log\\max(x)+\\log n))$. Time complexity: $O(n+(q\\log\\max(x)+\\log n))$",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1877",
    "index": "A",
    "title": "Goals of Victory",
    "statement": "There are $n$ teams in a football tournament. Each pair of teams match up once. After every match, Pak Chanek receives two integers as the result of the match, the number of goals the two teams score during the match. The efficiency of a team is equal to the total number of goals the team scores in each of its matches minus the total number of goals scored by the opponent in each of its matches.\n\nAfter the tournament ends, Pak Dengklek counts the efficiency of every team. Turns out that he forgot about the efficiency of one of the teams. Given the efficiency of $n-1$ teams $a_1,a_2,a_3,\\ldots,a_{n-1}$. What is the efficiency of the missing team? It can be shown that the efficiency of the missing team can be uniquely determined.",
    "tutorial": "Notice that each goal increases the efficiency of the team that scores by $1$. But it also simultaneously decreases the efficiency of the opposite team by $1$. This means, if we maintain the sum of efficiency for all teams, each goal does not change the sum. Therefore, the sum must be $0$. In order to make the sum to be $0$, the efficiency of the missing team must be equal to the sum of efficiency of the other $n-1$ teams, multiplied by $-1$. Time complexity for each test case: $O(n)$",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1877",
    "index": "C",
    "title": "Joyboard",
    "statement": "Chaneka, a gamer kid, invented a new gaming controller called joyboard. Interestingly, the joyboard she invented can only be used to play one game.\n\nThe joyboard has a screen containing $n+1$ slots numbered from $1$ to $n+1$ from left to right. The $n+1$ slots are going to be filled with an array of non-negative integers $[a_1,a_2,a_3,\\ldots,a_{n+1}]$. Chaneka, as the player, must assign $a_{n+1}$ with an integer between $0$ and $m$ inclusive. Then, for each $i$ from $n$ to $1$, the value of $a_i$ will be equal to the \\textbf{remainder} of dividing $a_{i+1}$ (the adjacent value to the right) by $i$. In other words, $a_i = a_{i + 1} \\bmod i$.\n\nChaneka wants it such that after every slot is assigned with an integer, there are exactly $k$ distinct values in the entire screen (among all $n+1$ slots). How many valid ways are there for assigning a non-negative integer into slot $n+1$?",
    "tutorial": "There are only a few cases. If $a_{n+1}=0$, then every value of $a_i$ is $0$. So there is only $1$ distinct value. If $1\\leq a_{n+1}\\leq n$, then there exists an index $p$ ($p=a_{n+1}$) such that $a_i=a_{n+1}$ for all indices $p+1\\leq i\\leq n+1$ and $a_i=0$ for all $1\\leq i\\leq p$. So there are $2$ distinct values. If $a_{n+1}>n$ and $a_{n+1}$ is divisible by $n$, then $a_n=0$ and all values to the left of that are also $0$. So there are $2$ distinct values. If $a_{n+1}>n$ and $a_{n+1}$ is not divisible by $n$, then $1\\leq a_n\\leq n-1$. This is is equivalent to case 2, which means that there are $2$ distinct values from index $1$ to $n$. So in total, there are $3$ distinct values. So the number of ways is as follows: If $k=1$, there is always $1$ way, since $m\\geq0$. If $k=2$ and $m\\leq n$, there are $m$ ways. If $k=2$ and $m>n$, there are $n+\\lfloor\\frac{m-n}{n}\\rfloor$. If $k=3$ and $m\\leq n$, there are $0$ ways. If $k=3$ and $m>n$, there are $m-n-\\lfloor\\frac{m-n}{n}\\rfloor$. If $k>3$, there are $0$ ways. Time complexity for each test case: $O(1)$",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1878",
    "index": "A",
    "title": "How Much Does Daytona Cost?",
    "statement": "We define an integer to be the most common on a subsegment, if its number of occurrences on that subsegment is larger than the number of occurrences of any other integer in that subsegment. A subsegment of an array is a consecutive segment of elements in the array $a$.\n\nGiven an array $a$ of size $n$, and an integer $k$, determine if there exists a non-empty subsegment of $a$ where $k$ is the most common element.",
    "tutorial": "It's enough to check if there even exists the element equals to $K$, since $K$ is obviously the most common element in the subsegment of length $1$ which contains it.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n\tint t; //read the number of test cases\n\tcin >> t;\n\twhile(t--){\n\t\tint n, k;\n\t\tcin >> n >> k; //read n and k\n\t\tbool ys=0; //bool value if true then there exists a subsegment which satisfies the condition, else it doesn't exist\n\t\tfor(int i=0; i< n; i++){\n\t\t\tint a; //read the i-th element of the array\n\t\t\tcin >> a;\n\t\t\tif(a==k)ys=1; //if the element is equal to k, then the subsegment [i, i] has the most common element equal to k\n\t\t}\n\t\tif(ys)cout << \"YES\\n\"; //output the answer\n\t\telse cout << \"NO\\n\";\n\t}\n}\n",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1878",
    "index": "B",
    "title": "Aleksa and Stack",
    "statement": "After the Serbian Informatics Olympiad, Aleksa was very sad, because he didn't win a medal (he didn't know stack), so Vasilije came to give him an easy problem, just to make his day better.\n\nVasilije gave Aleksa a positive integer $n$ ($n \\ge 3$) and asked him to construct a strictly increasing array of size $n$ of positive integers, such that\n\n- $3\\cdot a_{i+2}$ is not divisible by $a_i+a_{i+1}$ for each $i$ ($1\\le i \\le n-2$).\n\nNote that a strictly increasing array $a$ of size $n$ is an array where $a_i < a_{i+1}$ for each $i$ ($1 \\le i \\le n-1$).Since Aleksa thinks he is a bad programmer now, he asked you to help him find such an array.",
    "tutorial": "There are many solutions to this problem, but the intended one is the following: By selecting the first $n$ odd positive integers $1, 3, 5, \\dots, 2n - 1$, we find that $3\\cdot a_{i + 2}$ is also an odd number, while the number $a_i + a_{i + 1}$ is even, and an odd number can never be divisible by an even number, so the construction is correct. Time complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n\tint t; //read the number of test cases\n\tcin >> t;\n\twhile(t--){\n\t\tint n; //read n\n\t\tcin >> n;\n\t\tfor(int i=0; i< n; i++)cout << i*2+1 << \" \"; //write the first n odd numbers in order\n\t\tcout << '\\n';\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1878",
    "index": "C",
    "title": "Vasilije in Cacak",
    "statement": "Aca and Milovan, two fellow competitive programmers, decided to give Vasilije a problem to test his skills.\n\nVasilije is given three positive integers: $n$, $k$, and $x$, and he has to determine if he can choose $k$ distinct integers between $1$ and $n$, such that their sum is equal to $x$.\n\nSince Vasilije is now in the weirdest city in Serbia where Aca and Milovan live, Cacak, the problem seems weird to him. So he needs your help with this problem.",
    "tutorial": "It is clear that the minimum sum is obtained for the numbers $1, 2, 3, \\dots, k$, and its value is $\\frac{k\\cdot(k+1)}{2}$ (the sum of the first $k$ natural numbers). Furthermore, it is evident that the maximum sum is achieved for the numbers $n, n-1, n-2, \\dots, n-k+1$, and its value is $\\frac{n\\cdot(n+1)-(n-k)\\cdot(n-k+1)}{2}$ (the sum of all numbers from $1$ to $n$ minus the sum of all numbers from $1$ to $n-x$ elements). Let's prove that among any $k$ numbers (whose sum is not maximal), there exists a number $a < n$ such that $a+1$ is not among those $k$ numbers. Let's assume the opposite, that is, there exist $k$ numbers whose sum is not maximal, and for each of those $k$ numbers, $k + 1$ is also among those numbers. Let $v$ be the smallest among them. Consequently, $v + 1$ is also among these $k$ numbers. Since $v + 1$ is in these $k$ numbers, then $v + 2$ is also among these $k$ numbers. Similarly, we can conclude that $v, v + 1, v + 2, v + 3, \\dots$ are all among these $k$ numbers. However, since we have $k$ of them, these are the $k$ numbers that would yield the maximum sum ($n, n-1, n-2, \\dots, n-k+1$). This is a contradiction! So, among any $k$ numbers (whose sum is not maximal), there exists a number $a < n$ such that $a+1$ is not among those $k$ numbers. Based on this, starting from the minimum sum $S$, we can obtain $S + 1$ (by replacing the number $a$ with $a + 1$, the sum increases by $1$), then from the sum $S + 1$, we obtain the sum $S + 2$, and so on. Therefore, by applying the principle of mathematical induction, we can obtain any sum that is greater than or equal to minumum sum and less than or equal to maximum sum.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main(){\n\tint t; //read the number of test cases\n\tcin >> t;\n\twhile(t--){\n\t\tlong long n, x, k; //read n, x, k for each test case\n\t\tcin >> n >> x >> k;\n\t\tif(2*k>=x*(x+1) && 2*k<=n*(n+1)-(n-x)*(n-x+1)){ //check if k is between the minimum and maximum sum \n\t\t\tcout << \"YES\\n\";\n\t\t}\n\t\telse cout << \"NO\\n\";\n\t}\t\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1878",
    "index": "D",
    "title": "Reverse Madness",
    "statement": "You are given a string $s$ of length $n$, containing lowercase Latin letters.\n\nNext you will be given a positive integer $k$ and two arrays, $l$ and $r$ of length $k$.\n\nIt is guaranteed that the following conditions hold for these 2 arrays:\n\n- $l_1 = 1$;\n- $r_k = n$;\n- $l_i \\le r_i$, for each positive integer $i$ such that $1 \\le i \\le k$;\n- $l_i = r_{i-1}+1$, for each positive integer $i$ such that $2 \\le i \\le k$;\n\nNow you will be given a positive integer $q$ which represents the number of modifications you need to do on $s$.\n\nEach modification is defined with one positive integer $x$:\n\n- Find an index $i$ such that $l_i \\le x \\le r_i$ (notice that such $i$ is unique).\n- Let $a=\\min(x, r_i+l_i-x)$ and let $b=\\max(x, r_i+l_i-x)$.\n- Reverse the substring of $s$ from index $a$ to index $b$.\n\nReversing the substring $[a, b]$ of a string $s$ means to make $s$ equal to $s_1, s_2, \\dots, s_{a-1},\\ s_b, s_{b-1}, \\dots, s_{a+1}, s_a,\\ s_{b+1}, s_{b+2}, \\dots, s_{n-1}, s_n$.\n\nPrint $s$ after the last modification is finished.",
    "tutorial": "Observation 1: if we look at [$l_i, r_i$] as subsegments for each $i$, notice that they are disjoint, and that two modifications do not interfere with each other if they are from different subsegments. Because of this observation we can basically treat subsegments as separate test cases. Now, without loss of generality, because of the first observation, we can consider the same problem but with $l_1=1$ and $r_1=n$. It is easy to see that the modifications $x$ and $n-x+1$ are equivalent, because the first one will reverse the subsegment [$\\min(x, n-x+1), \\max(x, n-x+1)$], and the second one will do the same thing. Using this we can consider without loss of generality for all modifications the following holds true: $2\\cdot x_i \\le n$. Now try visualizing the modifications: if $x=1$ then we reverse the whole string. if $x=2$ then we reverse the whole string except the first and the last element. if $x=3$ then we reverse the whole string except the first two and last two elements. We can logically conclude that the modifications are symmetrical with respect to the middle of the string. From this symmetry, we can conclude that if a modification \"touches\" index $i$ it also touches index $n-i+1$, and also because of the symmetry, $i$ will always be swapped with $n-i+1$, and no other index. This means that the order of modifications doesn't matter, because for each index it only matters how many modifications affect it. Another thing to note is that for a given index $i$, all modifications such that $x \\le i$ affect this index. This gives us the following solution: Let's store the number of modifications for each index in an array, and if $x> \\frac{n}{2}$ then store it as $n-x+1$. Next we just iterate over the array while maintaining the sum of the number of operations, and if it's odd we swap elements $i$ and $n-i+1$, else we just continue iterating.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main(){\n\tint t; //number of test cases\n\tcin >> t;\n\twhile(t--){\n\t\tint n, k; //read the input\n\t\tcin >> n >> k;\n\t\tstring s;\n\t\tcin >> s;\n\t\tint a[k]; int b[k];\n\t\tfor(int i=0; i< k; i++){cin >> a[i]; a[i]--;}\n\t\tfor(int i=0; i< k; i++){cin >> b[i]; b[i]--;}\n\t\tint q;\n\t\tcin >> q;\n\t\tint cnt[n+1]={0}; //read and preprocess queries\n\t\tfor(int i=0; i< q; i++){\n\t\t\tint x; cin >> x; cnt[x-1]++;\n\t\t}\n\t\tstring ans=\"\";\n\t\tfor(int i=0; i<k; i++){ //treat each interval as a seperate test case\n\t\t\tstring s1=s.substr(a[i], b[i]-a[i]+1);\n\t\t\tint sum=0;\n\t\t\tint l=a[i];\n\t\t\tint r=b[i];\n\t\t\tfor(int j=l; j<=(l+r)/2; j++){\n\t\t\t\tsum+=cnt[j]+cnt[r-j+l];\n\t\t\t\tif(sum&1)swap(s1[j-l], s1[r-j]);\n\t\t\t}\n\t\t\tans+=s1;\n\t\t}\n\t\tcout << ans << '\\n';\n\t}\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1878",
    "index": "E",
    "title": "Iva & Pav",
    "statement": "Iva and Pav are a famous Serbian competitive programming couple. In Serbia, they call Pav \"papuca\" and that's why he will make all of Iva's wishes come true.\n\nIva gave Pav an array $a$ of $n$ elements.\n\nLet's define $f(l, r) = a_l \\ \\& \\ a_{l+1} \\ \\& \\dots \\& \\ a_r$ (here $\\&$ denotes the bitwise AND operation).\n\n\\textbf{Note that} $f(l, r)$ \\textbf{is not defined when} $l>r$.\n\nIva also gave Pav $q$ queries.\n\nEach query consists of 2 numbers, $k$ and $l$, and she wants Pav to find the largest index $r$ ($l \\le r \\le n$), such that $f(l, r) \\ge k$.\n\nPav wants to solve this problem fast because he doesn't want to upset Iva. He needs your help.",
    "tutorial": "We can, for each bit, calculate the prefix sums of the array ($pref[i][j]$ is the number of occurrences of the $j$-th bit in the first $i$ elements of the array. This can be calculated in $\\mathcal{O}(n \\log(max(a)))$. We know that if $pref[r][j] - pref[l - 1][j] = r - l + 1$, then the $j$-th bit is present in all elements of the subsegment [$l, r$] of the array $a$, which means the value of $f(l, r)$ is equal to the sum of all bits for which this condition is true on the subsegment from $l$ to $r$, and we can calculate that in $\\mathcal{O}(\\log(max(a)))$. Next, for each query, we can use binary search to find $r$, by calculating $f(l, mid)$. If $f(l, r) \\ge k$ then we found an index for which the condition is true, so we move the left to $mid + 1$, else we move the right to $mid-1$. This solution works in $\\mathcal{O}(Q\\cdot\\log(N)\\cdot\\log(max(a)))$ which is around $4\\cdot10^7$ operations, with a low constant factor. It is possible to optimize the solution even more by using sparse tables, to calculate $f(l, r)$ in $\\mathcal{O}(1)$ therefore removing the $\\log(max(a))$ factor, but we think that sparse tables are a little bit too advanced of a topic for div3 E, so we didn't make that solution necessary.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n \n \nconst int N =200003;\nconst int bits=30;\nint pref[N][bits];\nint a[N];\nvoid Buildprefix(int n){ //Builds the prefix sums for each bit\n    for(int i=0; i< n; i++){\n        for(int j=0; j<30; j++){\n            if(a[i]&(1<<j)){\n                pref[i+1][j]=pref[i][j]+1;\n            }\n            else{\n                pref[i+1][j]=pref[i][j];\n            }\n        }\n    }\n}\nvoid solve(){\n    int n;\n    cin >> n;\n    for(int i=0; i< n; i++){\n        cin >> a[i];\n    }\n    Buildprefix(n);\n    int q;\n    cin >> q;\n    while(q--){\n        int l, k;\n        cin >> l >> k;\n        if(a[l-1]<k){\n            cout << -1 << '\\n';\n            continue;\n        }\n        int lo=l;\n        int hi=n;\n        int ans=l;\n        while(lo<=hi){\n            int s=(lo+hi)/2;\n            int num=0;\n            for(int j=0; j< bits; j++){\n                if(pref[s][j]-pref[l-1][j]==s-l+1){\n                    num+=(1<<j);\n                }\n            }\n            if(num>=k){\n                lo=s+1;\n                ans=max(ans, s);\n            }\n            else hi=s-1;\n        }\n        cout << ans << '\\n';\n    }\n}\n \nint main(){\n    int t = 1;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1878",
    "index": "F",
    "title": "Vasilije Loves Number Theory",
    "statement": "Vasilije is a smart student and his discrete mathematics teacher Sonja taught him number theory very well.\n\nHe gave Ognjen a positive integer $n$.\n\nDenote $d(n)$ as the number of positive integer divisors of $n$, and denote $gcd(a, b)$ as the largest integer $g$ such that $a$ is divisible by $g$ and $b$ is divisible by $g$.\n\nAfter that, he gave Ognjen $q$ queries, and there are $2$ types of queries.\n\n- $1$, $x$ — set $n$ to $n \\cdot x$, and then answer the following question: does there exist a positive integer $a$ such that $gcd(a, n) = 1$, and $d(n \\cdot a) = n$?\n- $2$ — reset $n$ to its initial value (before any queries).\n\nNote that $n$ \\textbf{does not} get back to its initial value after the \\textbf{type 1} query.\n\nSince Ognjen is afraid of number theory, Vasilije promised him that \\textbf{after each query}, $d(n) \\le 10^9$, however, even with that constraint, he still needs your help with this problem.",
    "tutorial": "Answer: a solution exists if and only if $d(n)$ divides $n$. Proof: consider the prime factorization of the number $n = p_1^{\\alpha_1} \\cdot p_2^{\\alpha_2} \\cdots p_k^{\\alpha_k}$, where $p_i$ represents the $i$-th prime number, and $\\alpha_i$ represents the highest power of the $i$-th prime number such that $p_i^{\\alpha_i}$ divides $n$. Knowing this we can calculate the number of divisors of $n$ with the following formula: $d(n) = (\\alpha_1+1) \\cdot (\\alpha_2+1) \\cdots (\\alpha_k+1)$. Let's now consider the operations we are performing. We are multiplying the number $n$ by a number $a$ that has no common prime factors with $n$ (condition $gcd(a, n) = 1$). Multiplying $n$ by any integer will only bring new prime factors to $n$, which means that we can not change what is already in the brackets of the formula for the number of divisors $d(n)$, but we can add new brackets. Therefore, $d(n)$ will always be a divisor of the number $d(n\\cdot a)$. So, we can write $d(n \\cdot a) = v \\cdot d(n)$. In order to achieve $d(n \\cdot a) = n$, we must also have $v \\cdot d(n) = n$. Therefore, it is necessary for $d(n)$ to be a divisor of $n$. Let's show that this is also sufficient. Let's denote $k = \\frac{n}{d(n)}$. Choose any prime number $p$ that is not a factor of $n$ (such a prime exists because there are infinitely many prime numbers, while $n$ has a finite number of prime factors). By multiplying $n$ by $a = p^{k-1}$, we obtain $d(n\\cdot a) = d(n) \\cdot k = n$. Using this fact, we just need to efficiently check whether $d(n)$ divides $n$ after each type 1 query. How do we do this? First we pre-calculate for each positive integer less than $10^6$ its smallest prime factor. This allows us to factorize all numbers smaller than or equal to $10^6$ in logarithmic time. We also factorize $n$ and find its number of divisors using the formula mentioned above, and store for each prime factor its highest power which still divides $n$. We can do this using an array, or using a map, either way, let's call this structure $power$. Now we need to deal with the queries: For type 2 query we just need to reset everything. For the first query, we factorize $x$ in $\\mathcal{O}(\\log{x})$ operations and let $x = r_1^{\\beta_1} \\cdot r_2^{\\beta_2} \\cdots r_\\ell^{\\beta_\\ell}$ be the factorization of the number $x$. We update the $d(n)$ by doing the following: for each prime $r_i$ in $x$, divide $d(n)$ by $power[r_i]+1$, then add $\\beta_i$ to $power[r_i]$, and then multiply $d(n)$ by $power[r_i]+1$. After we calculate $d(n)$, we should check if $n$ is divisible by it. We can do this in 2 ways: Solution 1: We do this by multiplying the value of all previous type $1$ queries (after the last type $2$ query), and the value of the starting $n$ by modulo $d(n)$, because $n$ can get really large, and we can't store it in a 64-bit integer. If the value mod $d(n)$ is $0$, then its divisible and the answer to our query is \"YES\", else it is \"NO\". Time complexity $\\mathcal{O}(Q \\cdot (Q + \\log{x}) + \\log{n})$. Solution 2: This solution is even faster, but it might be harder to implement, and that's why we didn't make it necessary. Instead of storing queries, we just need to use another map to store the prime divisors of $d(n)$, now we can compare each prime divisor and its power for $d(n)$ and for the product of $n$ and all queries after the last reset. Now for each prime in $d(n)$, the power of that prime has to be smaller or equal to than the power of that prime in the product of $n$ and queries. Since $d(n) \\le 10^9$, the map for $d(n)$ will have at most $\\log(max(d(n))$ entries, so this solution runs in $\\mathcal{O}(Q \\cdot (\\log(max(d(n)) \\cdot log(log(max(d(n))) + \\log(x))+ t \\cdot \\log(n))$.",
    "code": "#include <bits/stdc++.h>\n\nusing ll = long long;\nusing namespace std;\n\nconst int N = 1000003;\nmap<int, int> powers; //key is a prime number, value is te highest powert\nmap<int, int> original_divisors; //same as map powers but isn't updated during queries, it's used to reset the powers\nint smallest_divisor[N]; //precalculated smallest divisors to make factorization O(logx) \nbool mark[N]; //marks numbers which aren't prime (used for sieve)\nll divisor_count = 1; //the number of divisors (updated during queries)\n\nvoid prime(){ //calculates the smallers divisor for each number from 1 to N (sieve of erathosetenes)\n\tsmallest_divisor[1]=1;\n\tsmallest_divisor[2]=2;\n\tfor(int i=4; i<N; i+=2){\n\t\tmark[i]=true;\n\t\tsmallest_divisor[i]=2;\n\t}\t\n\tfor(int i=3; i<N; i+=2){\n\t\tif(!mark[i]){\n\t\t\tsmallest_divisor[i]=i;\n\t\t\tfor(ll j = i*1ll*i; j<N; j+=2*i){\n\t\t\t\tif(!mark[j]){\n\t\t\t\t\tsmallest_divisor[j]=i;\n\t\t\t\t\tmark[j]=1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n//a function for factorizing a number (used to process queries and factorize n in the beginning)\n//it also updates the highest prime which divides n (powers map), and the number of divisors of n (divisor_count)\nvoid factorize(int x){ \n\tint p=0;\n\tint current_divisor = 1;\n\twhile(x>1){ //while x has non 1 divisors, divide it by it's smallest divisor which isn't 1(smallers divisor if always prime)\n\t\tif(smallest_divisor[x]!=current_divisor){\n\t\t\tif(p>0){\n\t\t\t\tdivisor_count/=powers[current_divisor]+1;\n\t\t\t\tpowers[current_divisor]+=p;\n\t\t\t\tdivisor_count*=powers[current_divisor]+1;\n\t\t\t}\n\t\t\tp=1;\n\t\t\tcurrent_divisor=smallest_divisor[x];\n\t\t}\n\t\telse{\n\t\t\tp++;\n\t\t}\n\t\tx/=smallest_divisor[x];\n\t}\n\tif(p>0){\n\t\tdivisor_count/=powers[current_divisor]+1;\n\t\tpowers[current_divisor]+=p;\n\t\tdivisor_count*=powers[current_divisor]+1;\n\t}\n\treturn;\n}\n\nint main(){\n\tprime(); //precalculate smallest divisors\n\tint t;\n\tcin >> t;\n\twhile(t--){\n\t    //read n and q\n    \tint n; int q;\n    \tcin >> n >> q;\n    \t//factorize n\n    \tfactorize(n);\n    \t//since factorize updates the powers map, update the origional_divisors map too\n    \tfor(auto prime : powers){\n    \t\toriginal_divisors[prime.first]=prime.second;\n    \t}\n    \tint original_divisor_count = divisor_count; //since factorize updates the divisor_count we update the original_divisor_count too\n    \tvector<int> queries; //storing previous queries\n    \t//processing queries\n    \twhile(q--){\n    \t\tint query_type;\n    \t\tcin >> query_type;\n    \t\tif(query_type==1){ //query of type 1 (multiply n by x)\n    \t\t\tint x;\n    \t\t\tcin >> x;\n    \t\t\tfactorize(x); //factorize x, update the powers map, and the number of divisors\n    \t\t\tqueries.push_back(x); //add x to the list of previous queries\n    \t\t\tll num=n;\n    \t\t\tfor(int query : queries){ //check if the product of all previous queries and n is divisible by d(n)\n    \t\t\t\tnum*=query;\n    \t\t\t\tnum%=divisor_count;\n    \t\t\t}\n    \t\t\tif(num==0){ //if it is the answer is yes else the answer is no\n    \t\t\t\tcout << \"YES\\n\";\n    \t\t\t}\n    \t\t\telse cout << \"NO\\n\";\n    \t\t}\n    \t\telse{ //here we should reset everything related to the type 1 query\n    \t\t\tpowers.clear(); //clear the powers map and set it to original divisors and powers\n    \t\t\tfor(auto original_div : original_divisors){\n    \t\t\t\tpowers[original_div.first]=original_div.second;\n    \t\t\t}\n    \t\t\tdivisor_count=original_divisor_count; //restart the divisor_count\n    \t\t\tqueries.clear(); //clear the queries (since we only need the queries since the previous type 2 query)\n    \t\t}\n    \t}\n    \toriginal_divisors.clear();\n    \tpowers.clear();\n    \tdivisor_count=1;\n    \toriginal_divisor_count =1;\n    \tif(t) cout << \"\\n\";\n\t}\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1878",
    "index": "G",
    "title": "wxhtzdy ORO Tree",
    "statement": "After (finally) qualifying for the IOI 2023, wxhtzdy was very happy, so he decided to do what most competitive programmers do: trying to guess the problems that will be on IOI. During this process, he accidentally made a problem, which he thought was really cool.\n\nYou are given a tree (a connected acyclic graph) with $n$ vertices and $n-1$ edges. Vertex $i$ ($1 \\le i \\le n$) has a value $a_i$.\n\nLets' define $g(u, v)$ as the bitwise or of the values of all vertices on the shortest path from $u$ to $v$. For example, let's say that we want to calculate $g(3, 4)$, on the tree from the first test case in the example. On the path from $3$ to $4$ are vertices $3$, $1$, $4$. Then, $g(3, 4) = a_3 \\ | \\ a_1 \\ | \\ a_4$ (here, $|$ represents the bitwise OR operation).\n\nAlso, you are given $q$ queries, and each query looks like this:\n\nYou are given $x$ and $y$. Let's consider all vertices $z$ such that $z$ is on the shortest path from $x$ to $y$ (inclusive).\n\nLets define the niceness of a vertex $z$ as the sum of the number of non-zero bits in $g(x, z)$ and the number of non-zero bits in $g(y, z)$. You need to find the maximum niceness among all vertices $z$ on the shortest path from $x$ to $y$.\n\nSince his brain is really tired after solving an output only problem on SIO (he had to do it to qualify for the IOI), he wants your help with this problem.",
    "tutorial": "Observation 1: it's enough to only consider $2 \\cdot \\log(max(a))$ vertices on the shortest path from $x$ to $y$ as candidates for $z$ for each query. Why? Because at most $\\log(max(a))$ vertices can add a bit to $g(x, z)$ and we only need to maximize the number of bits in $g(x, z)$ + the number of bits in $g(y, z)$, and all the other vertices will not contribute to the sum at all so we don't even need to consider them for $z$. Now we need to find those vertices. We know that for each bit, the vertex which we will consider can give this bit to $g(x, z)$ will be the closest one to vertex $x$ (on the path from $x$ to $y$). How do we find these vertices qucikly? First let's arbitrarily root the tree. Now let's precalculate for each vertex and bit $cnt[vertex][bit]$ as the number of vertices on the path from the root to this vertex which have this bit set in their value. Then for each bit, we can binary search to find it's first occurenece on the path from $x$ to $y$, and the path from $y$ to $x$. We do binary search by taking $mid$ from vertex $x$ to vertex $y$ and calculating the number of vertices which have the current bit set, by using the $cnt$ matrix combined with range minimum query or binary lifting to find the lowest common ancestor. We are searching for the first position where the number of those is >0. Once we find all the vertices, we can for each of those, in $O(log(max(a))$, calculate it's niceness, and take the maximum out of those. Time complexity: $O(q \\cdot (\\log n + \\log(max(a)) \\cdot \\log n)$.",
    "code": "#include <bits/stdc++.h>\n#define f first\n#define s second\nusing namespace std;\n#define int long long\nconst int maxn = 2e5 + 69;\nconst int k = 19;\nconst int bits = 30;\nvector<int> g[maxn];\nint n, q, a[maxn], up[maxn][k], tin[maxn], tout[maxn], timer, d[maxn];\nint r[maxn][k];\nint bst[maxn][bits];\nvoid dfs(int v, int p, vector<int> b) {\n\ttin[v] = ++timer;\n\tup[v][0] = p;\n\tr[v][0] = a[p];\n\td[v] = d[p] + 1;\n\tfor (int i = 0;i < bits;i++) {\n\t\tbst[v][i] = b[i];\n\t\tif (a[v] & (1 << i))\n\t\t\tb[i] = v;\n\t}\n\tfor (int i = 1;i < k;i++) {\n\t\tup[v][i] = up[up[v][i - 1]][i - 1];\n\t\tr[v][i] = r[v][i - 1] | r[up[v][i - 1]][i - 1];\n\t}\n\tfor (auto u : g[v]) {\n\t\tif (u != p)\n\t\t\tdfs(u, v, b);\n\t}\n\ttout[v] = timer;\n}\n\nbool is_anc(int u, int v) {\n\treturn tin[u] <= tin[v] && tout[u] >= tout[v];\n}\n\nint lca(int u, int v) {\n\tif(is_anc(u, v))\n\t\treturn u;\n\telse if(is_anc(v, u))\n\t\treturn v;\n\tfor (int i = k - 1;i >= 0;i--) {\n\t\tif (!is_anc(up[u][i], v) && up[u][i] > 0)\n\t\t\tu = up[u][i];\n\t}\n\treturn up[u][0];\n}\n\nint OR(int u, int dis) {\n\tint res = a[u];\n\tfor (int j = 0;j < bits;j++) {\n\t\tif (dis & (1 << j)) {\n\t\t\tres |= r[u][j];\n\t\t\tu = up[u][j];\n\t\t}\n\t}\n\treturn res;\n}\n\nint Qry(int u, int v) {\n\tint lc = lca(u, v);\n\treturn OR(u, d[u] - d[lc]) | OR(v, d[v] - d[lc]);\n}\n\nsigned main()\n{\n\tint tt = 1;\n\tcin >> tt;\n\twhile(tt--) {\n\t\tcin >> n;\n\t\ttimer = 0;\n\t\tfor (int i = 1;i <= n;i++)\n            g[i].clear();\n\t\tfor (int i = 1;i <= n;i++)\n\t\t\tcin >> a[i];\n\t\tfor (int i = 1;i <= n - 1;i++) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y;\n\t\t\tg[x].push_back(y);\n\t\t\tg[y].push_back(x);\n\t\t}\n\t\tvector<int> temp(30, -1);\n\t\tdfs(1, 0, temp);\n\t\tcin >> q;\n\t\tfor (int i = 1;i <= q;i++) {\n\t\t\tint x, y;\n\t\t\tcin >> x >> y;\n\t\t\tint LCA = lca(x, y);\n\t\t\tvector<int> t;\n\t\t\tt.push_back(x);\n\t\t\tt.push_back(y);\n\t\t\tfor (int i = 0;i < bits;i++) {\n\t\t\t\tif (bst[x][i] != -1 && is_anc(LCA, bst[x][i]))\n\t\t\t\t\tt.push_back(bst[x][i]);\n\t\t\t\tif (bst[y][i] != -1 && is_anc(LCA, bst[y][i]))\n\t\t\t\t\tt.push_back(bst[y][i]);\n\t\t\t}\n\t\t\tint ans =  __builtin_popcount(a[x]) + __builtin_popcount(a[y]);\n\t\t\tfor (auto p : t) {\n\t\t\t\tint x1 = a[x], x2 = a[y];\n\t\t\t\tx1 |= Qry(x, p);\n\t\t\t\tx2 |= Qry(y, p);\n\t\t\t\tans = max(ans, 1ll * __builtin_popcount(x1) + __builtin_popcount(x2));\n\t\t\t}\n\t\t\tcout << ans << \" \";\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n   return 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "data structures",
      "dfs and similar",
      "implementation",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1879",
    "index": "A",
    "title": "Rigged!",
    "statement": "Monocarp organizes a weightlifting competition. There are $n$ athletes participating in the competition, the $i$-th athlete has strength $s_i$ and endurance $e_i$. The $1$-st athlete is Monocarp's friend Polycarp, and Monocarp really wants Polycarp to win.\n\nThe competition will be conducted as follows. The jury will choose a positive \\textbf{(greater than zero)} integer $w$, which denotes the weight of the barbell that will be used in the competition. The goal for each athlete is to lift the barbell as many times as possible. The athlete who lifts the barbell the most amount of times will be declared the winner \\textbf{(if there are multiple such athletes — there's no winner)}.\n\nIf the barbell's weight $w$ is \\textbf{strictly greater} than the strength of the $i$-th athlete $s_i$, then the $i$-th athlete will be unable to lift the barbell even one single time. Otherwise, the $i$-th athlete will be able to lift the barbell, and the number of times he does it will be equal to his endurance $e_i$.\n\nFor example, suppose there are $4$ athletes with parameters $s_1 = 7, e_1 = 4$; $s_2 = 9, e_2 = 3$; $s_3 = 4, e_3 = 6$; $s_4 = 2, e_4 = 2$. If the weight of the barbell is $5$, then:\n\n- the first athlete will be able to lift the barbell $4$ times;\n- the second athlete will be able to lift the barbell $3$ times;\n- the third athlete will be unable to lift the barbell;\n- the fourth athlete will be unable to lift the barbell.\n\nMonocarp wants to choose $w$ in such a way that Polycarp (the $1$-st athlete) wins the competition. Help him to choose the value of $w$, or report that it is impossible.",
    "tutorial": "Let's figure out the optimal value of $w$. If $w > s_1$, then Polycarp cannot lift the barbell. If $w < s_1$, then some athletes having less strength than Polycarp might be able to lift the barbell. So the optimal value of $w$ is $s_1$. All that's left to do is check that there are such athletes who are able to lift weight $w$ greater than or equal to $e_1$ times. If such athletes exist, then the answer is $-1$. Otherwise, the answer is $s_1$.",
    "code": "\n#include <bits/stdc++.h>\n \nusing namespace std;\n\nconst int N = 109;\n\nint t;\nint n;\nint s[N], e[N];\n \nint main() {\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        cin >> n;\n        for (int i = 0; i < n; ++i) {\n            cin >> s[i] >> e[i];\n        }\n        \n        bool ok = true;\n        for (int i = 1; i < n; ++i) \n            if (s[i] >= s[0] && e[i] >= e[0])\n                ok = false;\n        \n        if (!ok) {\n            puts(\"-1\");\n            continue;\n        }\n        \n        cout << s[0] << endl;\n    }\n    return 0;\n}\n\n",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1879",
    "index": "B",
    "title": "Chips on the Board",
    "statement": "You are given a board of size $n \\times n$ ($n$ rows and $n$ colums) and two arrays of positive integers $a$ and $b$ of size $n$.\n\nYour task is to place the chips on this board so that the following condition is satisfied for every cell $(i, j)$:\n\n- there exists at least one chip in the same column or in the same row as the cell $(i, j)$. I. e. there exists a cell $(x, y)$ such that there is a chip in that cell, and either $x = i$ or $y = j$ (or both).\n\nThe cost of putting a chip in the cell $(i, j)$ is equal to $a_i + b_j$.\n\nFor example, for $n=3$, $a=[1, 4, 1]$ and $b=[3, 2, 2]$. One of the possible chip placements is as follows:\n\n\\begin{center}\n{\\small White squares are empty}\n\\end{center}\n\nThe total cost of that placement is $(1+3) + (1+2) + (1+2) = 10$.\n\nCalculate the minimum possible total cost of putting chips according to the rules above.",
    "tutorial": "Let's note that to maintain the rule for all cells in a certain row, one of two conditions must hold: either the row contains at least one chip, or each column contains at least one chip. Let's apply this observation to all rows of the board. If we consider all rows, this observation means that the placement of chips satisfies the rule if either each row contains at least one chip, or each column contains at least one chip. Let's consider the case when each row contains at least one chip. Since we want to calculate the minimum total cost of placement, each row needs exactly one chip. Now we have to determine where exactly in each row the chip is placed. Since the cost of a chip in the $i$-th row and $j$-th column is equal to $a_i + b_j$, to minimize the cost, we have to choose the minimum value of $b_j$. Applying this to all rows, we obtain that the total cost is equal to $\\sum\\limits_{i=1}^{n} (a_i + mnB)$, where $mnB$ is the minimum element in the array $b$. Similar reasoning can be applied to the case when there is a chip in each column. In this case, the total cost is equal to $\\sum\\limits_{j=1}^{n} (mnA + b_j)$, where $mnA$ is the minimum element in the array $a$. The answer to the problem is the minimum of the two values described above.",
    "code": "\n#include <bits/stdc++.h>\n \nusing namespace std;\n\nusing li = long long;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<li> a(n), b(n);\n    for (auto& x : a) cin >> x;\n    for (auto& x : b) cin >> x;\n    li mnA = *min_element(a.begin(), a.end());\n    li sA = accumulate(a.begin(), a.end(), 0LL);\n    li mnB = *min_element(b.begin(), b.end());\n    li sB = accumulate(b.begin(), b.end(), 0LL);\n    li ans = min(mnA * n + sB, mnB * n + sA);\n    cout << ans << '\\n';\n  }\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "1879",
    "index": "C",
    "title": "Make it Alternating",
    "statement": "You are given a binary string $s$. A binary string is a string consisting of characters 0 and/or 1.\n\nYou can perform the following operation on $s$ any number of times \\textbf{(even zero)}:\n\n- choose an integer $i$ such that $1 \\le i \\le |s|$, then erase the character $s_i$.\n\nYou have to make $s$ alternating, i. e. after you perform the operations, every two adjacent characters in $s$ should be different.\n\nYour goal is to calculate two values:\n\n- the minimum number of operations required to make $s$ alternating;\n- the number of different \\textbf{shortest} sequences of operations that make $s$ alternating. Two sequences of operations are different if in at least one operation, the chosen integer $i$ is different in these two sequences.",
    "tutorial": "Firstly, let's divide the string $s$ into blocks of equal characters. For example, if $s = 000100111$, then we divide it into four blocks: $000$, $1$, $00$, $111$. Let's denote the length of $i$-th block as $len_i$, and the number of blocks as $k$. To obtain the longest alternating string we can get, we should choose exactly one character from each block and delete all other characters (we cannot leave two or more characters from the same block). Now let's calculate the number of ways to choose characters that stay after string $s$ become alternating. In the first block of length $len_1$, there are $len_1$ ways to choose that element; in the second block, there are $len_2$ ways, and so on. So the final number of ways is equal to $\\prod_{i=1}^{k} len_i$. For example, let's consider the string $s = 00011$. This string is divided into two blocks $000$ and $11$, so the number of ways if $len_1 \\cdot len_2 = 2 \\cdot 3 = 6$: 00011; 00011; 00011; 00011; 00011; 00011. However, we have chosen the characters that remain, but we need to choose the characters we erase and the order in which we erase them. Since choosing the characters that remain is basically the same as choosing the characters that get erased, we only have to choose the order in which the character get erased. The number of characters we erase is $n-k$, so the number of ways to order them is equal to the number of permutations of length $(n-k)$. For example, let's consider that the string $s = 001100$ and the chosen indices to erase are 1, 4 and 5. Then there are $3! = 6$ ways to choose the order of them: 1, 4, 5; 1, 5, 4; 4, 1, 5; 4, 5, 1; 5, 1, 4; 5, 4, 1. Note that after we delete a character from the string, the indices of other characters might change, but it doesn't actually matter. So, the final answer is: the number of operations we perform is $n - k$; and the number of shortest sequences of operations is $\\prod_{i=1}^{k} len_i \\cdot (n-k)!$.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998'244'353;\n\nvoid upd(int &a, int b) {\n    a = (a * 1LL * b) % MOD;\n}\n\n\nint t;\nstring s;\n\nint main() {\n\tcin >> t;\n\tfor (int tc = 0; tc < t; ++tc) {\n\t    cin >> s;\n\t    int res = 1;\n\t    int k = s.size();\n\t    int n = s.size();\n\t    for (int l = 0; l < n; ) {\n\t        int r = l + 1;\n\t        while(r < n && s[l] == s[r])\n\t            ++r;\n            upd(res, r - l);\n            --k;\n            l = r;\n\t    }\n\t    \n\t    for (int i = 1; i <= k; ++i)\n\t        upd(res, i);\n        cout << k << ' ' << res << endl;\n\t}\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1879",
    "index": "D",
    "title": "Sum of XOR Functions",
    "statement": "You are given an array $a$ of length $n$ consisting of non-negative integers.\n\nYou have to calculate the value of $\\sum_{l=1}^{n} \\sum_{r=l}^{n} f(l, r) \\cdot (r - l + 1)$, where $f(l, r)$ is $a_l \\oplus a_{l+1} \\oplus \\dots \\oplus a_{r-1} \\oplus a_r$ (the character $\\oplus$ denotes bitwise XOR).\n\nSince the answer can be very large, print it modulo $998244353$.",
    "tutorial": "Let's solve this problem for each bit separately. When we fix a bit (let's denote it as $b$), all we have to do is solve the original problem for a binary string (let's denote this string as $s$). Note that if there is an odd number of $1$'s on a segment, the value of XOR on the segment is $1$, otherwise it's $0$. So, for a fixed bit $b$, we have to calculate $\\sum_{l=1}^{n} \\sum_{r=l}^{n} g(l, r) \\cdot (r - l + 1)$, where $g(l, r) = 1$ if the number of character 1 in substring $s_l, s_{l + 1}, \\dots, s_r$ is odd, otherwise $g(l, r) = 0$. Now let's figure out how to solve this problem if the right border of substrings is fixed (let's denote it as $r$). Let's denote a function (which we call $pref(x)$) that is equal to the number of $1$'s on the prefix of length $x$ modulo $2$. So, if there is an even number of $1$'s among the first $x$ characters, then $pref(x) = 0$, otherwise $pref(x) = 1$. If we fix the right border of a substring $r$ is fixed, we need to consider such left borders $l$ that $l < r$ and $pref(l) + pref(r) = 1$. We have to maintain the number of such left borders (let it be $cnt_i$ for borders which have $pref(l) = i$) and their total sum (let it be $sumOfL_i$ for borders which have $pref(l) = i$). These values can be easily maintained as we iterate on $r$. Why do we need these values? We can calculate the value of $\\sum_{l=1}^{r} g(l, r) \\cdot (r - l + 1)$ for a fixed right border $r$, if we denote the length of the segment $(r - l + 1)$ as the difference between the right border and the left border (we can discard $1$ from this formula if we treat $l$ as an inclusive border, and $r$ as an exclusive border). So, $\\sum_{l=1}^{r} g(l, r) \\cdot (r - l + 1)$ can be rephrased as the difference between the sum of right borders of those segments (which is equal to $r$ multiplied by the number of different left borders) and the sum of left borders of these segments (which is maintained in $sumOfL$). Now we just need to iterate on the right border and sum this up while maintaining the values of $cnt_i$ and $sumOfL_i$. Don't forget that we solved the problem only for the bit $b$, we need to combine the results for every bit later (and make sure that we multiply the result for the $b$-th bit by $2^b$). Overall complexity is $O(n \\log A)$, where $A$ is the constraint on the values in the array.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 300005;\nconst int MOD = 998244353;\nint n;\nint a[N];\n\nvoid add(int &a, int b) {\n    a += b;\n    if (a >= MOD)\n        a -= MOD;\n}\n\nint sum(int a, int b) {\n    a += b;\n    if (a >= MOD)\n        a -= MOD;\n    if (a < 0)\n        a += MOD;\n    return a;\n}\n\nint mul(int a, int b) {\n    return (a * 1LL * b) % MOD;\n}\n\nint main() {\n    cin >> n;\n    for (int i = 0; i < n; ++i)\n        cin >> a[i];\n    \n    int res = 0;    \n    for (int b = 0; b < 30; ++b) {\n        int cur = 0;\n        vector <int> cnt(2);\n        vector <int> sumOfL(2);\n        cnt[0] = 1;\n        int x = 0;\n        for (int i = 0; i < n; ++i) {\n            x ^= ((a[i] >> b) & 1);\n            int sumOfR = mul(cnt[x ^ 1], i + 1);\n            add(cur, sum(sumOfR, -sumOfL[x ^ 1]));\n            \n            ++cnt[x];\n            add(sumOfL[x], i + 1);\n        }\n        \n        add(res, mul(1 << b, cur));\n    }\n    \n    cout << res << endl;\n}\n",
    "tags": [
      "bitmasks",
      "combinatorics",
      "divide and conquer",
      "dp",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1879",
    "index": "E",
    "title": "Interactive Game with Coloring",
    "statement": "\\textbf{This is an interactive problem. Remember to flush your output while communicating with the testing program.} You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.\n\nYou are given a tree on $n$ vertices; vertex $1$ is the root of the tree. For every $i \\in [2, n]$, the parent of the $i$-th vertex is $p_i$, and $p_i < i$.\n\nYou have to color all edges of the tree using the \\textbf{minimum possible number of colors} such that you can win the game on that tree (every edge should be painted into exactly one color).\n\nThe game we're going to play will be conducted as follows. After you paint the edges and print their colors, the jury will place a chip into one of the vertices of the tree (except for the root). Your goal is to move this chip to the root in exactly $d$ moves, where $d$ is the distance from the root to that vertex (the distance is equal to the number of edges on the path). If the chip reaches the root in $d$ moves, you win. Otherwise, you lose.\n\nThe jury won't tell you where the chip is located. You won't even know the value of $d$ in advance. However, at the start of each move, you will be told how many edges of each color are incident to the current vertex (this includes both the edge leading up the tree and the edges leading away from the root). You have to choose one of these colors, and the chip will be moved along the edge of the chosen color (if there are multiple edges with that color incident to the current vertex, the jury gets to choose one of them). After the chip is moved, you will be told the same information about the current vertex again, and the game continues, until you either reach the root, or you make $d$ moves without reaching the root.\n\n\\textbf{The interactor for this problem is adaptive}. It means that both the starting vertex and the current vertex are \\textbf{not fixed} and may change \"on the run\" depending on the output of your program. However, the state of the game will always be consistent with the information you are given: \\textbf{there will always be at least one starting vertex and at least one path of your chip from that vertex consistent with both the information about the colors you receive and the colors you've chosen during the moves}.",
    "tutorial": "First of all, we need to analyze how we can win the game. Since we have to reach the root from a vertex with distance $d$ in exactly $d$ moves, every move we make should be towards the root. So, for each vertex, knowing the colors of adjacent edges, we need to uniquely determine the color we choose to go up. This means that the color of the edge leading up must be different from the colors of the edges going down (otherwise the jury might move the chip down when we're trying to go up). Let's try to estimate the maximum number of colors we have to use. In fact, we don't need more than three colors. We can use the following recursive coloring strategy, for example: if an edge connecting $i$ with $p_i$ has color $x$, then all other edges incident to $i$ should have color $x \\bmod 3 + 1$. So, if a vertex is adjacent to edges with colors $1$ and $2$, the edge with color $1$ leads up; if the colors are $2$ and $3$, the edge with color $2$ leads up, and so on. So, we don't need to use more than $3$ colors. Let's figure out when we can use less than $3$ colors. The case $k=1$ is pretty simple: it's if and only if all vertices from $2$ to $n$ are the children of the root, because otherwise some vertex will have more than $1$ adjacent edge (and it's impossible to choose the edge going up for that vertex). The case $k = 2$ is a bit more challenging. If an edge from $i$ to $p_i$ has color $1$, then all other edges incident to $i$ should have color $2$, and vice versa. So, for every vertex which has $0$ or $2+$ children, the edge different from all of the other edges leads to the root. But for vertices having exactly one child, we cannot easily distinguish between the color going up and the color going down. So let's make sure that for every such vertex, the edge that leads up has the same color. So, here are the constraints on the edges we need to ensure so that a $2$-coloring allows us to win the game: for every vertex, every edge going down from it must have a different color than the edge going up; for every vertex with exactly $1$ child, the color of the edge leading up must be the same. There are a few ways to enforce these two constraints, but in my opinion, the most straightforward of them is to use bipartite coloring. Create a graph where each edge is represented by a vertex. The first condition can be modeled if, for each vertex of the tree, we add edges from the vertex representing the edge going up to vertices representing all other edges. The second condition is also quite easy to model: create an auxiliary vertex in the graph, and for every vertex having exactly one child in the tree, connect the vertex representing its parent-edge with that auxiliary vertex. If the resulting graph is bipartite, then its $2$-coloring can be used to choose the colors for the edges of the tree.",
    "code": "\n#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 123;\n\nint n;\nint color[N];\nint countColors[N][N];\nint p[N];\nvector<int> g[N];\nint deg[N];\n\nvoid add_edge(int x, int y)\n{\n\tg[x].push_back(y);\n\tg[y].push_back(x);\n}\n\nbool tryTwoColors()\n{\n\tint v1 = n + 1;\n\tint v2 = n + 2;\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tif(p[i] != 1)\n\t\t{\n\t\t\tadd_edge(i, p[i]);\n\t\t}\n\t}\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tif(deg[i] == 1)\n\t\t\tadd_edge(i, v1);\n\t}\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tif(p[i] != 1 && deg[p[i]] == 1)\n\t\t\tadd_edge(i, v2);\n\t}\n\tadd_edge(v1, v2);\n\tbool bad = false;\n\tfor(int i = 2; i <= n + 2; i++)\n\t\tif(color[i] == 0)\n\t\t{\n\t\t\tcolor[i] = 1;\n\t\t\tqueue<int> q;\n\t\t\tq.push(i);\n\t\t\twhile(!q.empty())\n\t\t\t{\n\t\t\t\tint k = q.front();\n\t\t\t\tq.pop();\n\t\t\t\tfor(auto y : g[k])\n\t\t\t\t{\n\t\t\t\t\tif(color[y] == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcolor[y] = 3 - color[k];\n\t\t\t\t\t\tq.push(y);\n\t\t\t\t\t}\n\t\t\t\t\telse if(color[y] == color[k])\n\t\t\t\t\t\tbad = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tif(bad)\n\t\tfor(int i = 2; i <= n + 2; i++)\n\t\t\tcolor[i] = 0;\n\treturn !bad;\n}\n\nvoid tryThreeColors()\n{\n\tfor(int i = 2; i <= n; i++)\n\t\tif(p[i] == 1)\n\t\t\tcolor[i] = 1;\n\t\telse\n\t\t\tcolor[i] = (color[p[i]] % 3) + 1;\n}\n\nint findVertex(const vector<int>& colors)\n{\n\tint s = colors.size();\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tif(vector<int>(countColors[i], countColors[i] + s) == colors)\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\nint main()\n{\n\tcin >> n;\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tcin >> p[i];\n\t\tdeg[p[i]]++;\n\t}\n\t\n\tif(*max_element(p + 2, p + n + 1) == 1)\n\t{\n\t\tfor(int i = 2; i <= n; i++)\n\t\t\tcolor[i] = 1;\n\t}\n\telse if (!tryTwoColors())\n\t\ttryThreeColors();\n\t\n\tint colorsUsed = *max_element(color + 2, color + n + 1);\n\t\n\tcout << colorsUsed << endl;\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tcout << color[i];\n\t\tif(i == n) cout << endl;\n\t\telse cout << \" \";\n\t}\n\tcout.flush();\n\t\n\tfor(int i = 2; i <= n; i++)\n\t{\n\t\tcountColors[i][color[i]]++;\n\t\tcountColors[p[i]][color[i]]++;\n\t}\n\t\n\twhile(true)\n\t{\n\t\tint resp;\n\t\tcin >> resp;\n\t\tif(resp == -1 || resp == 1)\n\t\t\texit(0);\n\t\tvector<int> counts(colorsUsed + 1);\n\t\tfor(int i = 1; i <= colorsUsed; i++)\n\t\t\tcin >> counts[i];\n\t\tint v = findVertex(counts);\n\t\tassert(v != -1);\n\t\tcout << color[v] << endl;\n\t\tcout.flush();\n\t}\n}\n\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "implementation",
      "interactive",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1879",
    "index": "F",
    "title": "Last Man Standing",
    "statement": "There are $n$ heroes in a videogame. Each hero has some health value $h$ and initial armor value $a$. Let the current value of armor be $a_{\\mathit{cur}}$, initially equal to $a$.\n\nWhen $x$ points of damage are inflicted on a hero, the following happens: if $x < a_{\\mathit{cur}}$, then $x$ gets subtracted from $a_{\\mathit{cur}}$; otherwise, $1$ gets subtracted from $h$ and $a_{\\mathit{cur}}$ gets assigned back to $a$.\n\nIn the start of the game, you choose the value $x$ (an integer strictly greater than $0$, arbitrarily large). Then you keep attacking all heroes in rounds: in one round, you inflict $x$ points of damage to all alive heroes. A hero dies when his health becomes $0$. The game ends when all heroes are dead.\n\nThe last hero to die earns the number of points, equal to the number of rounds he was the only hero alive. The other heroes get $0$ points. In particular, if the last round ends with multiple heroes dying, then every hero gets $0$ points.\n\nThe game is played for every possible $x$ (from $1$ to infinity). The points are reset between the games. What's the maximum number of points each hero has had?",
    "tutorial": "For each $x$, we can easily tell how many rounds each hero will last. That is equal to $\\lceil \\frac{a}{x} \\rceil \\cdot h$. The last hero to die is the one with the maximum of this value. And the number of rounds he will be the only hero alive is determined by the second maximum. Also notice that all $x$ that are greater or equal to the maximum of $a$ behave the same. In one round, all heroes just lose one point of health. Thus, it only makes sense to calculate the answer for all $x$ from $1$ to $\\max{a}$. The problem currently is the following: for each $x$ from $1$ to $\\max{a}$, find the index and the value of the maximum and the value of the second maximum of $\\lceil \\frac{a}{x} \\rceil \\cdot h$. Let's group all heroes by the value of $c = \\lceil \\frac{a}{x} \\rceil$. The values of $a$ for the heroes in the group form a segment from $x \\cdot (c - 1) + 1$ to $x \\cdot c$. From each group, we only care about the maximum and the second maximum over $h$. Thus, if we can extract the maximum and the second maximum in $O(1)$, the solution will be $O(a \\log a)$ because of the harmonic series (iterating over $x$, then over $\\lceil \\frac{a}{x} \\rceil$). First, for each $a$, find the maximum and the second maximum of $h$. To query the maximum on a segment, we can use a sparse table. Apparently, we can modify it to query the second maximum as well. Store a tuple of (value of maximum, index of maximum, value of the second maximum). To merge two segments, we compare if the indices of the maximums are the same. They can possibly be the same because we often query intersecting segments in the sparse table. If they are, the second maximum is the largest of the respective second maximums. If they aren't, let the first node has a large or equal value of maximum. Then the second maximum is the larger of the second maximum of the first node and the maximum of the second node. Overall complexity: $O(n + a \\log a)$ time and memory per testcase.",
    "code": "\n#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--){\n\t\tint n;\n\t\tscanf(\"%d\", &n);\n\t\tvector<int> h(n), a(n);\n\t\tforn(i, n) scanf(\"%d\", &h[i]);\n\t\tforn(i, n) scanf(\"%d\", &a[i]);\n\t\tint mxa = *max_element(a.begin(), a.end()) + 1;\n\t\t\n\t\tint l = mxa == 1 ? 0 : (__lg(mxa - 1) + 1);\n\t\tvector<vector<pair<int, int>>> st(l, vector<pair<int, int>>(mxa, make_pair(0, -1)));\n\t\tvector<vector<int>> st2(l, vector<int>(mxa));\n\t\tforn(i, n){\n\t\t\tif (h[i] > st[0][a[i]].first){\n\t\t\t\tst2[0][a[i]] = st[0][a[i]].first;\n\t\t\t\tst[0][a[i]] = {h[i], i};\n\t\t\t}\n\t\t\telse if (h[i] > st2[0][a[i]]){\n\t\t\t\tst2[0][a[i]] = h[i];\n\t\t\t}\n\t\t}\n\t\t\n\t\tauto combine = [&st, &st2](int i, int x, int y){\n\t\t\tint mx = max(st[i][x].first, st[i][y].first);\n\t\t\tif (mx == st[i][x].first)\n\t\t\t\treturn max(st2[i][x], st[i][y].first);\n\t\t\treturn max(st[i][x].first, st2[i][y]);\n\t\t};\n\t\t\n\t\tfor (int j = 1; j < l; ++j) forn(i, mxa){\n\t\t\tif (i + (1 << (j - 1)) < mxa){\n\t\t\t\tst[j][i] = max(st[j - 1][i], st[j - 1][i + (1 << (j - 1))]);\n\t\t\t\tst2[j][i] = combine(j - 1, i, i + (1 << (j - 1)));\n\t\t\t}\n\t\t\telse{\n\t\t\t\tst[j][i] = st[j - 1][i];\n\t\t\t\tst2[j][i] = st2[j - 1][i];\n\t\t\t}\n\t\t}\n\t\tvector<int> pw(mxa + 1);\n\t\tfor (int i = 2; i <= mxa; ++i) pw[i] = pw[i / 2] + 1;\n\t\t\n\t\tauto getmx = [&st, &pw](int l, int r){\n\t\t\tint len = pw[r - l];\n\t\t\treturn max(st[len][l], st[len][r - (1 << len)]);\n\t\t};\n\t\tauto getmx2 = [&st, &st2, &pw, &combine](int l, int r){\n\t\t\tint len = pw[r - l];\n\t\t\tif (st[len][l].second != st[len][r - (1 << len)].second)\n\t\t\t\treturn combine(len, l, r - (1 << len));\n\t\t\treturn max(st2[len][l], st2[len][r - (1 << len)]);\n\t\t};\n\t\t\n\t\tvector<long long> svmx(mxa), svmx2(mxa);\n\t\tvector<int> svwho(mxa, -1);\n\t\tfor (int x = 1; x < mxa; ++x){\n\t\t\tfor (int l = 1; l < mxa; l += x){\n\t\t\t\tint r = min(mxa, l + x);\n\t\t\t\tint ac = (l - 1) / x + 1;\n\t\t\t\tauto tmp = getmx(l, r);\n\t\t\t\tlong long mx = tmp.first * 1ll * ac;\n\t\t\t\tint who = tmp.second;\n\t\t\t\tlong long mx2 = getmx2(l, r) * 1ll * ac;\n\t\t\t\tif (who == -1) continue;\n\t\t\t\tif (mx > svmx[x]){\n\t\t\t\t\tsvmx2[x] = svmx[x];\n\t\t\t\t\tsvmx[x] = mx;\n\t\t\t\t\tsvwho[x] = who;\n\t\t\t\t}\n\t\t\t\telse if (mx > svmx2[x]){\n\t\t\t\t\tsvmx2[x] = mx;\n\t\t\t\t}\n\t\t\t\tsvmx2[x] = max(svmx2[x], mx2);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvector<long long> ans(n);\n\t\tforn(i, mxa) if (svwho[i] != -1)\n\t\t\tans[svwho[i]] = max(ans[svwho[i]], svmx[i] - svmx2[i]);\n\t\t\n\t\tforn(i, n) printf(\"%lld \", ans[i]);\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}\n\n",
    "tags": [
      "brute force",
      "data structures",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1881",
    "index": "A",
    "title": "Don't Try to Count",
    "statement": "Given a string $x$ of length $n$ and a string $s$ of length $m$ ($n \\cdot m \\le 25$), consisting of lowercase Latin letters, you can apply any number of operations to the string $x$.\n\nIn one operation, you append the current value of $x$ to the end of the string $x$. Note that the value of $x$ will change after this.\n\nFor example, if $x =$\"aba\", then after applying operations, $x$ will change as follows: \"aba\" $\\rightarrow$ \"abaaba\" $\\rightarrow$ \"abaabaabaaba\".\n\nAfter what \\textbf{minimum} number of operations $s$ will appear in $x$ as a substring? A substring of a string is defined as a \\textbf{contiguous} segment of it.",
    "tutorial": "Note that the answer is always not greater than $5$. When $n=1$, $m=25$, the answer is either $5$ or $-1$, it is easy to see that the answer cannot be greater. This allows us to simply iterate over the number of operations, each time checking if $s$ occurs in $x$. The time complexity of this solution is $O(2^5\\cdot n \\cdot m)$.",
    "code": "def solve():\n    n, m = map(int, input().split())\n    x = input()\n    s = input()\n    for i in range(6):\n        if s in x:\n            print(i)\n            return\n        x += x\n    print(-1)\n\n\nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1881",
    "index": "B",
    "title": "Three Threadlets",
    "statement": "Once upon a time, bartender Decim found three threadlets and a pair of scissors.\n\nIn one operation, Decim chooses any threadlet and cuts it into two threadlets, whose lengths are \\textbf{positive integers} and their sum is \\textbf{equal} to the length of the threadlet being cut.\n\nFor example, he can cut a threadlet of length $5$ into threadlets of lengths $2$ and $3$, but he cannot cut it into threadlets of lengths $2.5$ and $2.5$, or lengths $0$ and $5$, or lengths $3$ and $4$.\n\nDecim can perform \\textbf{at most} three operations. He is allowed to cut the threadlets obtained from previous cuts. Will he be able to make all the threadlets of equal length?",
    "tutorial": "If the lengths of the threadlets are equal, the answer is \"YES\". Otherwise, let's denote the length of the minimum threadlet as $a$. If we cut it, we will have only two operations, which is not enough. Therefore, the desired length should be equal to $a$. If $b$ or $c$ are not divisible by $a$, the answer is \"NO\". Otherwise, we will check if $\\frac{b}{a} - 1 + \\frac{c}{a} - 1 \\le 3$.",
    "code": "for _ in range(int(input())):\n    a, b, c = sorted(map(int, input().split()))\n    if a == b and b == c:\n        print('YES')\n    elif b % a == 0 and c % a == 0 and (b // a - 1) + (c // a - 1) <= 3:\n        print('YES')\n    else:\n        print('NO')",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1881",
    "index": "C",
    "title": "Perfect Square",
    "statement": "Kristina has a matrix of size $n$ by $n$, filled with lowercase Latin letters. The value of $n$ is \\textbf{even}.\n\nShe wants to change some characters so that her matrix becomes a perfect square. A matrix is called a perfect square if it remains unchanged when rotated $90^\\circ$ clockwise \\textbf{once}.\n\nHere is an example of rotating a matrix by $90^\\circ$:\n\nIn one operation, Kristina can choose any cell and replace its value with the next character in the alphabet. If the character is equal to \"z\", its value \\textbf{does not change}.\n\nFind the \\textbf{minimum} number of operations required to make the matrix a perfect square.\n\nFor example, if the $4$ by $4$ matrix looks like this:\n\n$$\\matrix{ a & b & b & a \\cr b & c & \\textbf{b} & b \\cr b & c & c & b\\cr a & b & b & a \\cr }$$\n\nthen it is enough to apply $1$ operation to the letter \\textbf{b}, highlighted in bold.",
    "tutorial": "When rotating a matrix of size $n$ by $n$ by $90$ degrees: element $a[i][j]$ takes the position of element $a[j][n - 1 - i]$; element $a[n - 1 - j][i]$ takes the position of element $a[i][j]$; element $a[n - 1 - i][n - 1 - j]$ takes the position of element $a[n - 1 - j][i]$. In order for the matrix to be a perfect square, the symbols at all of these positions must be equal. Since we can only maximize a symbol, we do the following: Among these 4 symbols, let's find the lexicographically maximal one, that is, the one that is in the alphabet not before all the others; For all characters that are not equal to the maximum, calculate the number of operations that must be applied to them to make them equal to the maximum character. This number of operations is equal to the difference of positions of symbols in the alphabet.",
    "code": "#include <bits/stdc++.h>\n#define all(arr) arr.begin(), arr.end()\n\nusing namespace std;\n\nconst int MAXN = 1010;\n\nint n;\nstring A[MAXN];\n\nint solve() {\n    int ans = 0;\n    for (int i = 0; i * 2 < n; ++i)\n        for (int j = 0; j * 2 < n; ++j) {\n            vector<char> M {A[i][j], A[n - 1 - j][i], A[n - 1 - i][n - 1 - j], A[j][n - 1 - i]};\n            char c = *max_element(all(M));\n            for(char e: M)\n                ans += c - e;\n        }\n    return ans;\n}\n\nint main() {\n    int t; cin >> t;\n    while (t--) {\n        cin >> n;\n        for (int i = 0; i < n; ++i)\n            cin >> A[i];\n        cout << solve() << endl;\n    }\n}",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1881",
    "index": "D",
    "title": "Divide and Equalize",
    "statement": "You are given an array $a$ consisting of $n$ positive integers. You can perform the following operation on it:\n\n- Choose a pair of elements $a_i$ and $a_j$ ($1 \\le i, j \\le n$ and $i \\neq j$);\n- Choose one of the divisors of the integer $a_i$, i.e., an integer $x$ such that $a_i \\bmod x = 0$;\n- Replace $a_i$ with $\\frac{a_i}{x}$ and $a_j$ with $a_j \\cdot x$.\n\nDetermine whether it is possible to make all elements in the array the same by applying the operation a certain number of times (possibly zero).For example, let's consider the array $a$ = [$100, 2, 50, 10, 1$] with $5$ elements. Perform two operations on it:\n\n- Choose $a_3 = 50$ and $a_2 = 2$, $x = 5$. Replace $a_3$ with $\\frac{a_3}{x} = \\frac{50}{5} = 10$, and $a_2$ with $a_2 \\cdot x = 2 \\cdot 5 = 10$. The resulting array is $a$ = [$100, 10, 10, 10, 1$];\n- Choose $a_1 = 100$ and $a_5 = 1$, $x = 10$. Replace $a_1$ with $\\frac{a_1}{x} = \\frac{100}{10} = 10$, and $a_5$ with $a_5 \\cdot x = 1 \\cdot 10 = 10$. The resulting array is $a$ = [$10, 10, 10, 10, 10$].\n\nAfter performing these operations, all elements in the array $a$ become equal to $10$.",
    "tutorial": "To solve the problem, we need to decompose all numbers in the array into prime divisors. After that, let's calculate the number of each divisor, summarizing the decompositions of all numbers. If each divisor enters $k\\cdot n$ times, where $k$ is a natural number, then we can equalize all the numbers in the array: we will sequentially apply the operation so that each number consists of the same set of prime divisors. If some divisor enters a different number of times, then it will not be possible to equalize the numbers in the array.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int maxv = 1000000;\n\nvoid add_divs(int x, map<int, int>&divs){\n    int i = 2;\n    while(i * i <= x){\n        while (x % i == 0){\n            divs[i]++;\n            x /= i;\n        }\n        i++;\n    }\n    if(x > 1) divs[x]++;\n}\n\nbool solve(){\n    int n;\n    cin >> n;\n    vector<int>a(n);\n    map<int, int> divs;\n    for(int i = 0; i < n; i++) {\n        cin >> a[i];\n        add_divs(a[i], divs);\n    }\n    for(auto e: divs){\n        if(e.second % n != 0) return false;\n    }\n    return true;\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while(t--) {\n        cout << (solve() ? \"YES\" : \"NO\") << \"\\n\";\n    }\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1881",
    "index": "E",
    "title": "Block Sequence",
    "statement": "Given a sequence of integers $a$ of length $n$.\n\nA sequence is called beautiful if it has the form of a series of blocks, each starting with its length, i.e., first comes the length of the block, and then its elements. For example, the sequences [$\\textcolor{red}{3},\\ \\textcolor{red}{3},\\ \\textcolor{red}{4},\\ \\textcolor{red}{5},\\ \\textcolor{green}{2},\\ \\textcolor{green}{6},\\ \\textcolor{green}{1}$] and [$\\textcolor{red}{1},\\ \\textcolor{red}{8},\\ \\textcolor{green}{4},\\ \\textcolor{green}{5},\\ \\textcolor{green}{2},\\ \\textcolor{green}{6},\\ \\textcolor{green}{1}$] are beautiful (different blocks are colored differently), while [$1$], [$1,\\ 4,\\ 3$], [$3,\\ 2,\\ 1$] are not.\n\nIn one operation, you can remove any element from the sequence. What is the minimum number of operations required to make the given sequence beautiful?",
    "tutorial": "Let's use the dynamic programming approach: let $dp[i]$ be the number of operations required to make the segment from $i$ to $n$ beautiful. There are two possible ways to achieve this: Remove the element at position $i$ and make the segment from $i + 1$ to $n$ beautiful, then $dp[i] = dp[i+1] + 1$; Make the segment from $i + a_i + 1$ to $n$ beautiful, then $dp[i] = dp[i + a_i + 1]$ (cases where $i + a_i + 1 > n$ need to be handled separately).",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    dp = [n + 1] * n\n\n    def get(pos):\n        if pos > n:\n            return n + 1\n        if pos == n:\n            return 0\n        return dp[pos]\n\n    dp[-1] = 1\n    for i in range(n - 2, -1, -1):\n        dp[i] = min(dp[i + 1] + 1, get(i + a[i] + 1))\n    print(dp[0])\n\n\nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "dp"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1881",
    "index": "F",
    "title": "Minimum Maximum Distance",
    "statement": "You have a tree with $n$ vertices, some of which are marked. A tree is a connected undirected graph without cycles.\n\nLet $f_i$ denote the maximum distance from vertex $i$ to any of the marked vertices.\n\nYour task is to find the minimum value of $f_i$ among all vertices.\n\nFor example, in the tree shown in the example, vertices $2$, $6$, and $7$ are marked. Then the array $f(i) = [2, 3, 2, 4, 4, 3, 3]$. The minimum $f_i$ is for vertices $1$ and $3$.",
    "tutorial": "Let's run a breadth-first traversal from any labeled vertex $v_1$ and find the farthest other labeled vertex $v_2$ from it. Then we run a traversal from $v_2$ and find the farthest labeled vertex $v_3$ from it (it may coincide with $v_1$). Then the answer is $\\lceil \\frac{d}{2} \\rceil$, where $d$ is the distance between $v_2$ and $v_3$. It is worth considering separately the case when there is only one labeled vertex in the tree. Then the answer is $0$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nvector<vector<int>> g;\n\nvoid dfs(int v, int p, vector<int> &d){\n\tif(p != -1) d[v] = d[p] + 1;\n\tfor(int u: g[v]){\n\t\tif(u != p){\n\t\t\tdfs(u, v, d);\n\t\t}\n\t}\n}\n\nint main(){\n    int t;\n\tcin>>t;\n\twhile(t--){\n\t    int k;\n\t\tcin>>n>>k;\n\t\tg.assign(n, vector<int>(0));\n\t\tvector<int> marked(k);\n\t\tfor(int &e: marked) cin >> e, --e;\n\t\tfor(int i=1;i<n;i++){\n\t\t\tint u, v;\n\t\t\tcin >> u >> v;\n\t\t\t--u, --v;\n\t\t\tg[u].push_back(v);\n\t\t\tg[v].push_back(u);\n\t\t}\n\t\tif(k==1){\n\t\t\tcout<<0<<\"\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tvector<int> d1(n);\n\t\tdfs(marked[0], -1, d1);\n\t\tint mx = marked[0];\n\t\tfor(int e: marked){\n\t\t    if(d1[e] > d1[mx]) mx = e;\n\t\t}\n\t\tvector<int> d2(n);\n\t\tdfs(mx, -1, d2);\n\t\tmx = marked[0];\n\t\tfor(int e: marked){\n\t\t    if(d2[e] > d2[mx]) mx = e;\n\t\t}\n\t\tcout << (d2[mx] + 1) / 2 << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1881",
    "index": "G",
    "title": "Anya and the Mysterious String",
    "statement": "Anya received a string $s$ of length $n$ brought from Rome. The string $s$ consists of lowercase Latin letters and at first glance does not raise any suspicions. An instruction was attached to the string.\n\nStart of the instruction.\n\nA palindrome is a string that reads the same from left to right and right to left. For example, the strings \"anna\", \"aboba\", \"level\" are palindromes, while the strings \"gorilla\", \"banan\", \"off\" are not.\n\nA substring $[l \\ldots r]$ of string $s$ is a string $s_l s_{l+1} \\ldots s_{r-1} s_r$. For example, the substring $[4 \\ldots 6]$ of the string \"generation\" is the string \"era\".\n\nA string is called beautiful if it \\textbf{does not} contain a substring of length \\textbf{at least} two that is a palindrome. For example, the strings \"fox\", \"abcdef\", and \"yioy\" are beautiful, while the strings \"xyxx\", \"yikjkitrb\" are not.\n\nWhen an integer $x$ is added to the character $s_i$, it is replaced $x$ times with the \\textbf{next} character in the alphabet, with \"z\" being replaced by \"a\".\n\nWhen an integer $x$ is added to the substring $[l, r]$ of string $s$, it becomes the string $s_1 s_2 \\ldots s_{l-1} (s_l + x) (s_{l+1} + x) \\ldots (s_{r-1} + x) (s_r + x) s_{r+1} \\ldots s_n$. For example, when the substring $[2, 4]$ of the string \"abazaba\" is added with the number $6$, the resulting string is \"ahgfaba\".\n\nEnd of the instruction.\n\nAfter reading the instruction, Anya resigned herself to the fact that she has to answer $m$ queries. The queries can be of two types:\n\n- Add the number $x$ to the substring $[l \\ldots r]$ of string $s$.\n- Determine whether the substring $[l \\ldots r]$ of string $s$ is beautiful.",
    "tutorial": "Let's make two obvious observations about palindromes of length at least $2$: Palindromes of length $2n$ contain a palindrome substring $[n \\ldots n + 1]$; Palindromes of length $2n + 1$ contain a palindrome substring $[n \\ldots n + 2]$. Now we need to learn how to track only palindromes of length $2$ and $3$. Let's call an index bad if a palindrome of length $2$ starts from it, and terrible if a palindrome of length $3$ starts from it. We will store the bad and terrible indices in a pair of std::set. Let's assume that there are no modification queries and we need to check the substring $[l \\ldots r]$ for beauty. If there exists a bad index $i$ ($l \\le i \\le r - 1$) or a terrible index $j$ ($l \\le j \\le r - 2$), then the substring is not beautiful; otherwise, it is beautiful. This can be checked using binary search on the set. Now let's learn how to make modifications. Notice that palindromes do not appear or disappear inside a segment, but they can appear or disappear at its boundaries. Let's use a data structure that can add values on a segment and retrieve a value at a point. If such a structure exists, we will add $x \\mod 26$ to the segment $[l \\ldots r]$, and then process the nearest $10$ indices to $l$ and the nearest $10$ indices to $r$. We can describe more precisely which bad and terrible indices should be processed, but the author is lazy it does not affect the solution, because the number of such indices is still $O(1)$. When processing the indices, we use point queries and insertion/deletion operations in std::set. Now we need to implement such a data structure. The author suggests using a Fenwick tree on a difference array. A segment tree with lazy propagation will also work. This gives a solution with $O((n + q) \\log n)$ time complexity.",
    "code": "#include <iostream>\n#include <string>\n#include <set>\n#include <cstring>\n#define int long long\n\nusing namespace std;\n\nconst int L = 26;\nconst int MAXN = 200200;\n\nint n, m;\nstring s;\nset<int> M2, M3;\nint fen[MAXN];\n\nvoid fenadd(int i, int x) {\n\tx = (x % L + L) % L;\n\tfor (; i < n; i |= (i + 1))\n\t\tfen[i] = (fen[i] + x) % L;\n}\n\nint fenget(int i) {\n\tint ans = 0;\n\tfor (; i >= 0; i = (i & (i + 1)) - 1)\n\t\tans = (ans + fen[i]) % L;\n\treturn ans;\n}\n\nvoid relax(int l, int r) {\n\tl = max(l, 0LL);\n\tr = min(r, n);\n\tfor (int i = l; i + 1 < r; ++i) {\n\t\tint c1 = fenget(i);\n\t\tint c2 = fenget(i + 1);\n\n\t\tif (c1 == c2) M2.insert(i);\n\t\telse M2.erase(i);\n\n\t\tif (i + 2 >= r) continue;\n\n\t\tint c3 = fenget(i + 2);\n\t\tif (c1 == c3) M3.insert(i);\n\t\telse M3.erase(i);\n\t}\n}\n\nvoid build() {\n\tM2.clear();\n\tM3.clear();\n\tmemset(fen, 0, n * sizeof(int));\n\tfenadd(0, s[0] - 'a');\n\tfor (int i = 1; i < n; ++i) {\n\t\tfenadd(i, s[i] - s[i - 1] + L);\n\t}\n\tfor (int i = 0; i + 1 < n; ++i) {\n\t\tif (s[i] == s[i + 1]) M2.insert(i);\n\t\tif (i + 2 < n && s[i] == s[i + 2]) M3.insert(i);\n\t}\n}\n\nvoid update(int l, int r, int x) {\n\tfenadd(l, x);\n\trelax(l - 5, l + 5);\n\tfenadd(r, L - x);\n\trelax(r - 5, r + 5);\n}\n\nbool query(int l, int r) {\n\tauto it = M2.lower_bound(l);\n\tif (it != M2.end() && *it + 1 < r) return false;\n\tit = M3.lower_bound(l);\n\tif (it != M3.end() && *it + 2 < r) return false;\n\treturn true;\n}\n\nsigned main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tcin >> n >> m >> s;\n\t\tbuild();\n\t\twhile (m--) {\n\t\t\tint tp, l, r; cin >> tp >> l >> r, --l;\n\t\t\tif (tp == 1) {\n\t\t\t\tint x; cin >> x;\n\t\t\t\tupdate(l, r, x);\n\t\t\t} else {\n\t\t\t\tcout << (query(l, r) ? \"YES\" : \"NO\") << '\\n';\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1882",
    "index": "A",
    "title": "Increasing Sequence",
    "statement": "You are given a sequence $a_{1}, a_{2}, \\ldots, a_{n}$. A sequence $b_{1}, b_{2}, \\ldots, b_{n}$ is called good, if it satisfies all of the following conditions:\n\n- $b_{i}$ is a positive integer for $i = 1, 2, \\ldots, n$;\n- $b_{i} \\neq a_{i}$ for $i = 1, 2, \\ldots, n$;\n- $b_{1} < b_{2} < \\ldots < b_{n}$.\n\nFind the minimum value of $b_{n}$ among all good sequences $b_{1}, b_{2}, \\ldots, b_{n}$.",
    "tutorial": "Greedy solution. Continue constructing $b$ as small as possible. If $a_{1} = 1$, $b_{1} = 2$. Else, $b_{1} = 1$. For $i \\ge 2$, if $a_{i} = b_{i-1} + 1$, $b_{i} = b_{i-1} + 2$. Else, $b_{i} = b_{i-1} + 1$. $b_{n}$ calculated by this process is the answer. Time complexity is $\\mathcal{O}(n)$ per test case.",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1882",
    "index": "B",
    "title": "Sets and Union",
    "statement": "You have $n$ sets of integers $S_{1}, S_{2}, \\ldots, S_{n}$. We call a set $S$ attainable, if it is possible to choose some (possibly, none) of the sets $S_{1}, S_{2}, \\ldots, S_{n}$ so that $S$ is equal to their union$^{\\dagger}$. If you choose none of $S_{1}, S_{2}, \\ldots, S_{n}$, their union is an empty set.\n\nFind the maximum number of elements in an attainable $S$ such that $S \\neq S_{1} \\cup S_{2} \\cup \\ldots \\cup S_{n}$.\n\n$^{\\dagger}$ The union of sets $A_1, A_2, \\ldots, A_k$ is defined as the set of elements present in at least one of these sets. It is denoted by $A_1 \\cup A_2 \\cup \\ldots \\cup A_k$. For example, $\\{2, 4, 6\\} \\cup \\{2, 3\\} \\cup \\{3, 6, 7\\} = \\{2, 3, 4, 6, 7\\}$.",
    "tutorial": "Sorry for everyone who got FSTs :( We tried our best to make pretest strong especially for this problem, but it wasn't enough. Denote $T = S_{1} \\cup S_{2} \\cup \\cdots \\cup S_{n}$, then $S \\subset T$. Since $S \\neq T$, $i \\in T$ and $i \\notin S$ for some $i$. Given an integer $i$, can you calculate the maximum size of $S$, such that $i \\notin S$? $i \\in T$ and $i \\notin S$ for some $i$. Here $1 \\le i \\le 50$. For fixed $i$, select of all the sets among $S_{1}, S_{2}, \\cdots, S_{n}$ which don't contain $i$. Size of their union will be the maximum size of $S$ such that $i \\notin S$. If we do this for all $i$ in $T$, maximum of them is the answer. Time complexity is $\\mathcal{O} \\left( N \\cdot \\max \\left( s_{i, j} \\right) ^{2}\\right)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1882",
    "index": "C",
    "title": "Card Game",
    "statement": "There are $n$ cards stacked in a deck. Initially, $a_{i}$ is written on the $i$-th card from the top. The value written on a card does not change.\n\nYou will play a game. Initially your score is $0$. In each turn, you can do \\textbf{one} of the following operations:\n\n- Choose an odd$^{\\dagger}$ positive integer $i$, which is not greater than the number of cards left in the deck. Remove the $i$-th card from the top of the deck \\textbf{and add the number written on the card to your score}. The remaining cards will be reindexed starting from the top.\n- Choose an even$^{\\ddagger}$ positive integer $i$, which is not greater than the number of cards left in the deck. Remove the $i$-th card from the top of the deck. The remaining cards will be reindexed starting from the top.\n- End the game. You can end the game whenever you want, you \\textbf{do not} have to remove all cards from the initial deck.\n\nWhat is the maximum score you can get when the game ends?\n\n$^{\\dagger}$ An integer $i$ is odd, if there exists an integer $k$ such that $i = 2k + 1$.\n\n$^{\\ddagger}$ An integer $i$ is even, if there exists an integer $k$ such that $i = 2k$.",
    "tutorial": "Fix the topmost card you'll pick in the initial deck. Let's denote $i$-th card in the initial deck as card $i$. Let the topmost card you'll pick in the initial deck as card $i$. For all cards under card $i$ in initial deck, you can choose all and only cards with the positive value at odd index. Proof: Here is the strategy. Before you pick card $i$, if positive card(under card $i$ in initial deck) in odd index exists, choose it. Repeat this until all positive cards(under card $i$ in initial deck) are in even index. Then if you choose card $i$, all index of positive cards(under card $i$ in initial deck) will be decreased by $1$, and will become odd. Now, choose them from the bottom to top, so that the choosing won't change the other positive cards' index. Denote $prf_{j}$ as the sum of positive numbers among $a_{j}, a_{j+1}, \\cdots, a_{n}$, and $prf_{n+1} = 0$. Since $prf_{j} = prf_{j+1} + \\max \\left( 0, a_{j}\\right)$, $prf$ can be calculated in $\\mathcal{O}(n)$. You should necessarily pick card $i$ in index of $i$, and can pick all positive cards under card $i$ in initial deck, so your maximum final score will be $(i \\% 2 == 1 ? a_{i} : 0) + prf_{i+1}$. The answer is $\\max \\left( (i \\% 2 == 1 ? a_{i} : 0) + prf_{i+1} \\, | \\, 1 \\le i \\le n \\right)$. There are lots of other solutions too.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1882",
    "index": "D",
    "title": "Tree XOR",
    "statement": "You are given a tree with $n$ vertices labeled from $1$ to $n$. An integer $a_{i}$ is written on vertex $i$ for $i = 1, 2, \\ldots, n$. You want to make all $a_{i}$ equal by performing some (possibly, zero) spells.\n\nSuppose you root the tree at some vertex. On each spell, you can select any vertex $v$ and any non-negative integer $c$. Then for all vertices $i$ in the subtree$^{\\dagger}$ of $v$, replace $a_{i}$ with $a_{i} \\oplus c$. The cost of this spell is $s \\cdot c$, where $s$ is the number of vertices in the subtree. Here $\\oplus$ denotes the bitwise XOR operation.\n\nLet $m_r$ be the minimum possible total cost required to make all $a_i$ equal, if vertex $r$ is chosen as the root of the tree. Find $m_{1}, m_{2}, \\ldots, m_{n}$.\n\n$^{\\dagger}$ Suppose vertex $r$ is chosen as the root of the tree. Then vertex $i$ belongs to the subtree of $v$ if the simple path from $i$ to $r$ contains $v$.",
    "tutorial": "Try to solve the problem for single root. For any vertex $v$ which isn't the root, denote $par_{v}$ as the parent of $v$. Then value of $a_{v} \\oplus a_{par_{v}}$ only changes if we perform the operation on $v$. Since $x_{1} \\oplus x_{2} \\oplus \\cdots \\oplus x_{m} \\le x_{1} + x_{2} + \\cdots + x_{m}$ for any numbers $x_{1}, x_{2}, \\cdots, x_{m}$, we can assume that there is at most operation performed in same vertex. Let's solve the problem for single root first. Denote the operation in the statement as $op(v, c)$, and size of $v$'s subtree as $s_{v}$. The goal is to make $a_{v} \\oplus a_{par_{v}} = 0$ for every non-root vertex $v$. This value is changed only when we select $v$. To make $a_{v} \\oplus a_{par_{v}}$ to $0$, we should perform $op \\left( v, a_{v} \\oplus a_{par_{v}} \\right)$ (Look Hint 3). Therefore, the answer sill be $\\sum_{i != root} s_{i} \\times (a_{i} \\oplus a_{par_{i}})$. Now our task is to calculate this for all roots. This can be done by lots of ways, and the following algorithm is one way. Calculate the answer for $1$ as root first in $\\mathcal{O}(n)$. Now, we will traverse the tree starting at vertex $1$ and keep updating the answer. If root changes from $q$ to $r$ ($q$ and $r$ are adjacent), every vertex except $q$ and $r$ will have same parents and subtree size, so will contribute same to the answer, so we only need to consider $q$ and $r$ to calculate the change. Edge connecting $q$ and $r$ will divide the tree into parts: each of size $X$ and $Y$. If root changes $q$ to $r$, $Y \\times (a_{q} \\oplus a_{r})$ will be subtracted, and $X \\times (a_{q} \\oplus a_{r})$ will be added to the answer. $X$ and $Y$ can be pre-calculated in $\\mathcal{O}(n)$, so this update costs $\\mathcal{O}(1)$. Since changing root into the adjacent vertex costs $\\mathcal{O}(1)$, answer for all roots can be calculated in $\\mathcal{O}(n)$.",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1882",
    "index": "E1",
    "title": "Two Permutations (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the two versions is that you do not have to minimize the number of operations in this version. You can make hacks only if both versions of the problem are solved.}\n\nYou have two permutations$^{\\dagger}$ $p_{1}, p_{2}, \\ldots, p_{n}$ (of integers $1$ to $n$) and $q_{1}, q_{2}, \\ldots, q_{m}$ (of integers $1$ to $m$). Initially $p_{i}=a_{i}$ for $i=1, 2, \\ldots, n$, and $q_{j} = b_{j}$ for $j = 1, 2, \\ldots, m$. You can apply the following operation on the permutations several (possibly, zero) times.\n\nIn one operation, $p$ and $q$ will change according to the following three steps:\n\n- You choose integers $i$, $j$ which satisfy $1 \\le i \\le n$ and $1 \\le j \\le m$.\n- Permutation $p$ is partitioned into three parts using $p_i$ as a pivot: the left part is formed by elements $p_1, p_2, \\ldots, p_{i-1}$ (this part may be empty), the middle part is the single element $p_i$, and the right part is $p_{i+1}, p_{i+2}, \\ldots, p_n$ (this part may be empty). To proceed, swap the left and the right parts of this partition. Formally, after this step, $p$ will become $p_{i+1}, p_{i+2}, \\ldots, p_{n}, p_{i}, p_{1}, p_{2}, \\ldots, p_{i-1}$. The elements of the newly formed $p$ will be reindexed starting from $1$.\n- Perform the same transformation on $q$ with index $j$. Formally, after this step, $q$ will become $q_{j+1}, q_{j+2}, \\ldots, q_{m}, q_{j}, q_{1}, q_{2}, \\ldots, q_{j-1}$. The elements of the newly formed $q$ will be reindexed starting from $1$.\n\nYour goal is to simultaneously make $p_{i}=i$ for $i=1, 2, \\ldots, n$, and $q_{j} = j$ for $j = 1, 2, \\ldots, m$.\n\nFind any valid way to achieve the goal using at most $10\\,000$ operations, or say that none exists. Please note that you \\textbf{do not have to} minimize the number of operations.\n\nIt can be proved that if it is possible to achieve the goal, then there exists a way to do so using at most $10\\,000$ operations.\n\n$^{\\dagger}$ A permutation of length $k$ is an array consisting of $k$ distinct integers from $1$ to $k$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($k=3$ but there is $4$ in the array).",
    "tutorial": "Let's think two permutations independently. The goal is to make sequence of operations for each permutation which have same parity of number of operations. Try to sort single permutation of length $N$, using at most $3N$ operations. It is always possible. If the permutation's length is odd, you can perform operation at index $1$ for $N$ times and return to the same permutation. If the permutation's length is even, the parity of inversion number changes in each operations. Hints above were the summary of the tutorial. Please check them. First, let's do Hint 2. There are lots of ways to do this, and I'd like to introduce one which I thought first. It is possible to swap two elements using $3$ operations. Let's denote the two elements as $x$ and $y$, and permutation as $[[ A ] x [ B ] y [ C ]]$ ($[ A ], [ B ], [ C ]$ are subarrays). Then: Perform the operation at $x$. Permutation becomes $[[ B ] y [ C ] x [ A ]]$. Perform the operation at $y$. Permutation becomes $[[ C ] x [ A ] y [ B ]]$. Perform the operation at $x$. Permutation becomes $[[ A ] y [ B ] x [ C ]]$. Using this, we can sort the single permutation of length $N$ using at most $3N$ operations, since we can sort the permutation by $N$ swaps. If this requires same parity of number of operations for $p$ and $q$, the problem is solved. At most $3 \\max(m, n)$ operations are used. Else, if $n$ or $m$ is odd, we can make the parity equal by method provided in Hint 3. At most $4 \\max(m, n)$ operations are used. Else, then $n$ and $m$ is both even. In this case, it's impossible because of Hint 4. The overall time complexity is $\\mathcal{O}(n + m)$ in this solution. Lastly, here is the proof of Hint 4. Proof: Let's consider the permutation of length $N$($N$ is even). Denote the permutation as $[[ A ] x [ B ]]$, and the length of $[ A ]$ and $[ B ]$ as $n_{A}$ and $n_{B}$. Here $n_{A} + n_{B} = N-1$ so one of $n_{A}$ and $n_{B}$ is even and one of them is odd. Permutation becomes $[[ B ] x [ A ]]$ after the operation. First, the parity of inversion number from two elements of $[ A ]$ or two elements of $[ B ]$ doesn't change, because their order inside doesn't change. Second, the parity of inversion number from one element of $[ A ]$ and one element of $[ B ]$ doesn't change, because sum of them are $n_{A} \\times n_{B}$, which is even. Third, the parity of inversion number from $x$ and one element of $[ A ]$ or $[ B ]$ changes, because sum of them are $n_{A} + n_{B}$, which is odd. If we add these three, we can lead to the conclusion that the parity of inversion number must change. The text may look a bit complicated, but it will not be that hard if you write them in your own :)",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1882",
    "index": "E2",
    "title": "Two Permutations (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the two versions is that you have to minimize the number of operations in this version. You can make hacks only if both versions of the problem are solved.}\n\nYou have two permutations$^{\\dagger}$ $p_{1}, p_{2}, \\ldots, p_{n}$ (of integers $1$ to $n$) and $q_{1}, q_{2}, \\ldots, q_{m}$ (of integers $1$ to $m$). Initially $p_{i}=a_{i}$ for $i=1, 2, \\ldots, n$, and $q_{j} = b_{j}$ for $j = 1, 2, \\ldots, m$. You can apply the following operation on the permutations several (possibly, zero) times.\n\nIn one operation, $p$ and $q$ will change according to the following three steps:\n\n- You choose integers $i$, $j$ which satisfy $1 \\le i \\le n$ and $1 \\le j \\le m$.\n- Permutation $p$ is partitioned into three parts using $p_i$ as a pivot: the left part is formed by elements $p_1, p_2, \\ldots, p_{i-1}$ (this part may be empty), the middle part is the single element $p_i$, and the right part is $p_{i+1}, p_{i+2}, \\ldots, p_n$ (this part may be empty). To proceed, swap the left and the right parts of this partition. Formally, after this step, $p$ will become $p_{i+1}, p_{i+2}, \\ldots, p_{n}, p_{i}, p_{1}, p_{2}, \\ldots, p_{i-1}$. The elements of the newly formed $p$ will be reindexed starting from $1$.\n- Perform the same transformation on $q$ with index $j$. Formally, after this step, $q$ will become $q_{j+1}, q_{j+2}, \\ldots, q_{m}, q_{j}, q_{1}, q_{2}, \\ldots, q_{j-1}$. The elements of the newly formed $q$ will be reindexed starting from $1$.\n\nYour goal is to simultaneously make $p_{i}=i$ for $i=1, 2, \\ldots, n$, and $q_{j} = j$ for $j = 1, 2, \\ldots, m$.\n\nFind any way to achieve the goal \\textbf{using the minimum number of operations possible}, or say that none exists. Please note that you \\textbf{have to} minimize the number of operations.\n\n$^{\\dagger}$ A permutation of length $k$ is an array consisting of $k$ distinct integers from $1$ to $k$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($k=3$ but there is $4$ in the array).",
    "tutorial": "The solution is completely different from E1. A brilliant idea is required. Maybe the fact that checker is implemented in linear time might be the hint. Find a way changing the operation to 'swap'. Add an extra character. Add an extra character '$X$' in front of the permutation. Here position of $X$ won't be changed by the operation, and will always locate at left of $p_{1}$. Then in each operation, the permutation will change as: $[X [ A ] c [ B ]] \\rightarrow [X [ B ] c [ A ]]$. Now, let's consider the array made by $X$ and permutation as circular. This is possible because $X$ is always in left of $1$st element, so it marks the start of the permutation. Then $[X [ B ] c [ A ]]$ is equivalent with $[c [ A ] X [ B ]]$. Then the operation is: $[X [ A ] c [ B ]] \\rightarrow [c [ A ] X [ B ]]$, which is same with swapping $X$ and $c$. Now we need to calculate the minimum odd number of swaps and even number of swaps(of $X$ and any element) each, turning $[X\\,p_{1}\\,p_{2}\\,\\cdots\\,p_{n}]$ to one of $[X\\,1\\,2\\,\\cdots\\,n]$, $[n\\,X\\,1\\,2\\,\\cdots\\,(n-1)]$, $[(n-1)\\,n\\,X\\,1\\,\\cdots\\,(n-2)]$, $\\cdots$, $[1\\,2\\,\\cdots\\,n\\,X]$. To calculate the minimum number of swaps required to turn $[X\\,p_{1}\\,p_{2}\\,\\cdots\\,p_{n}]$ to the given array, first renumber the initial array to $[X\\,1\\,2\\,\\cdots\\,n]$, then change the given array in the same correspondence. Do permutation cycle decomposition. Then the answer is (sum of (size + 1) for cycles which have size $\\ge$ 2 and don't contain $X$) + ($X$'s cycle size $-$ 1). This can be proven easily by counting the number of elements which go into the proper place in each operations. Calculate this for all $[X\\,1\\,2\\,\\cdots\\,n]$, $[n\\,X\\,1\\,2\\,\\cdots\\,(n-1)]$, $[(n-1)\\,n\\,X\\,1\\,\\cdots\\,(n-2)]$, $\\cdots$, $[1\\,2\\,\\cdots\\,n\\,X]$. Since we can't make the same array using different parity of number of swaps, we can achieve the goal by calculating the minimum odd number and minimum even number each. The overall time complexity is $O(n^{2}+m^{2})$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1883",
    "index": "A",
    "title": "Morning",
    "statement": "You are given a four-digit pin code consisting of digits from $0$ to $9$ that needs to be entered. Initially, the cursor points to the digit $1$. In one second, you can perform exactly one of the following two actions:\n\n- Press the cursor to display the current digit,\n- Move the cursor to any adjacent digit.\n\nThe image above shows the device you are using to enter the pin code. For example, for the digit $5$, the adjacent digits are $4$ and $6$, and for the digit $0$, there is only one adjacent digit, $9$.\n\nDetermine the minimum number of seconds required to enter the given four-digit pin code.",
    "tutorial": "Let's represent our pin code as a set of digits $a$, $b$, $c$, $d$. Replace all $0$s with $10$ and notice that the answer is equal to $|a - 1|$ + $|b - a|$ + $|c - b|$ + $|d - c|$.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1883",
    "index": "B",
    "title": "Chemistry",
    "statement": "You are given a string $s$ of length $n$, consisting of lowercase Latin letters, and an integer $k$.\n\nYou need to check if it is possible to remove \\textbf{exactly} $k$ characters from the string $s$ in such a way that the remaining characters can be rearranged to form a palindrome. Note that you can reorder the remaining characters in any way.\n\nA palindrome is a string that reads the same forwards and backwards. For example, the strings \"z\", \"aaa\", \"aba\", \"abccba\" are palindromes, while the strings \"codeforces\", \"reality\", \"ab\" are not.",
    "tutorial": "Let's remember under what conditions we can rearrange the letters of a word to form a palindrome. This can be done if the number of letters with odd occurrences is not greater than $1$. In our problem, it is sufficient to check that the number of letters with odd occurrences (denoted as $x$) is not greater than $k + 1$. Let's prove this fact. If $x > k + 1$, then it is definitely impossible to obtain the answer, because with $k$ operations we cannot make the number of letters with odd occurrences not greater than $1$. On the other hand, we can simply remove the character with an odd number of occurrences on each removal iteration and decrease the number of odd occurrences. If there are no such characters, we can choose any character and remove it, thus having $1$ character with an odd occurrence.",
    "tags": [
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1883",
    "index": "C",
    "title": "Raspberries",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$ and a number $k$ ($2 \\leq k \\leq 5$). In one operation, you can do the following:\n\n- Choose an index $1 \\leq i \\leq n$,\n- Set $a_i = a_i + 1$.\n\nFind the minimum number of operations needed to make the product of all the numbers in the array $a_1 \\cdot a_2 \\cdot \\ldots \\cdot a_n$ divisible by $k$.",
    "tutorial": "Let's notice that if $k = 2, 3, 5$, since these are prime numbers, the product of the numbers will be divisible by $k$ if any number in the array is divisible by $k$. From this, we can conclude that it is advantageous to perform operations only on one number. If $k = 4$, we have several cases, and we need to take the minimum among them. Again, we can perform operations on one number and make it divisible by $4$, or we need to perform operations such that there are two even numbers in the array (there is a special case when $n = 1$). To have two even numbers, let's count the number of even numbers in the original array as $cnt$, and if $2 \\leq n$, we can say that the answer is $\\max(0, 2 - cnt)$.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1883",
    "index": "D",
    "title": "In Love",
    "statement": "Initially, you have an empty multiset of segments. You need to process $q$ operations of two types:\n\n- $+$ $l$ $r$ — Add the segment $(l, r)$ to the multiset,\n- $-$ $l$ $r$ — Remove \\textbf{exactly} one segment $(l, r)$ from the multiset. It is guaranteed that this segment exists in the multiset.\n\nAfter each operation, you need to determine if there exists a pair of segments in the multiset that do not intersect. A pair of segments $(l, r)$ and $(a, b)$ do not intersect if there does not exist a point $x$ such that $l \\leq x \\leq r$ and $a \\leq x \\leq b$.",
    "tutorial": "Let's learn how to solve the problem for a fixed set. The claim is that if the answer exists, we can take the segment with the minimum right boundary and the maximum left boundary (let's denote these boundaries as $r$ and $l$). Therefore, if $r < l$, it is obvious that this pair of segments is suitable for us. Otherwise, all pairs of segments intersect because they have common points in the range $l \\ldots r$. Now let's maintain all our operations. For this, we can simply store a multiset of left and right boundaries. With the help of this multiset, we can find the minimum and maximum elements of any of these sets in $O(1)$. The addition and removal operations are also supported by this container.",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1883",
    "index": "E",
    "title": "Look Back",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$. You need to make it non-decreasing with the minimum number of operations. In one operation, you do the following:\n\n- Choose an index $1 \\leq i \\leq n$,\n- Set $a_i = a_i \\cdot 2$.\n\nAn array $b_1, b_2, \\ldots, b_n$ is non-decreasing if $b_i \\leq b_{i+1}$ for all $1 \\leq i < n$.",
    "tutorial": "Let's come up with a naive solution - we could go from left to right and multiply the element at index $i$ by $2$ until it is greater than or equal to the previous element. But this solution will take a long time, as the numbers can become on the order of $2^n$ during the operations. Let's not explicitly multiply our numbers by $2$, but represent each element as the product $a_i \\cdot 2^{x_i}$, where $x_i$ is the power to which we multiplied. Let's say we have calculated the value of $x_{i - 1}$, and now we want to calculate $x_i$. We have two cases: If $a_{i - 1} \\leq a_i$: Then we can say that $x_i = x_{i - 1}$ and subtract $1$ until $x_i > 0$ and $a_{i - 1} \\cdot 2 \\leq a_i$. If $a_{i - 1} > a_i$: Then we can say that $x_i = x_{i - 1}$ and add $1$ until $a_i \\cdot 2 < a_{i - 1}$. Note that we do not want to change the values of the array $a$ to avoid getting large numbers later, so we use additional variables for this.",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1883",
    "index": "F",
    "title": "You Are So Beautiful",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$. Calculate the number of \\textbf{subarrays} of this array $1 \\leq l \\leq r \\leq n$, such that:\n\n- The array $b = [a_l, a_{l+1}, \\ldots, a_r]$ occurs in the array $a$ as a \\textbf{subsequence} exactly once. In other words, there is exactly one way to select a set of indices $1 \\leq i_1 < i_2 < \\ldots < i_{r - l + 1} \\leq n$, such that $b_j = a_{i_j}$ for all $1 \\leq j \\leq r - l + 1$.",
    "tutorial": "Note that a subarray suits us if $a_l$ is the leftmost occurrence of the number $a_l$ in the array and $a_r$ is the rightmost occurrence of the number $a_r$ in the array. Let's create an array $b_r$ filled with zeros and set $b_r = 1$ if $a_r$ is the rightmost occurrence of the number $a_r$ in the array (this can be done using sets or dictionaries). Now we need to consider all suitable left boundaries and see how many suitable right boundaries we have on the suffix, either by precomputing a suffix sum or by simply maintaining a variable while traversing from left to right.",
    "tags": [
      "data structures"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1883",
    "index": "G2",
    "title": "Dances (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $m \\leq 10^9$.}\n\nYou are given two arrays of integers $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_n$. Before applying any operations, you can reorder the elements of each array as you wish. Then, in one operation, you will perform both of the following actions, if the arrays are not empty:\n\n- Choose any element from array $a$ and remove it (all remaining elements are shifted to a new array $a$),\n- Choose any element from array $b$ and remove it (all remaining elements are shifted to a new array $b$).\n\nLet $k$ be the final size of both arrays. You need to find the minimum number of operations required to satisfy $a_i < b_i$ for all $1 \\leq i \\leq k$.\n\nThis problem was too easy, so the problem author decided to make it more challenging. You are also given a positive integer $m$. Now, you need to find the sum of answers to the problem for $m$ pairs of arrays $(c[i], b)$, where $1 \\leq i \\leq m$. Array $c[i]$ is obtained from $a$ as follows:\n\n- $c[i]_1 = i$,\n- $c[i]_j = a_j$, for $2 \\leq j \\leq n$.",
    "tutorial": "Let's learn how to solve the problem for a fixed value of $a_1$. Notice that we can perform a binary search on the answer. Let's learn how to check if we can remove $k$ elements from both arrays such that $a_i < b_i$ holds for the remaining elements. It will be advantageous to sort both arrays, remove the $k$ largest elements from the first array, and the $k$ smallest elements from the second array, and then simply check if the condition holds for our pair of arrays. Thus, for a fixed value of $a_1$, we can solve the problem in $O(n \\log n)$. Let $f(i)$ be the answer to the problem for $a_1 = i$. We make the following observation - there exists a value $x$ such that: $f(1) = f(2) = \\ldots = f(x) = f(x + 1) - 1 = f(x + 2) - 1 = \\ldots = f(\\inf) - 1$. Indeed, changing one element of array $a$ cannot worsen the answer by more than $1$. Then, we can use binary search to find this value $x$. The overall complexity is $O(n \\log n \\log m)$.",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1884",
    "index": "A",
    "title": "Simple Design",
    "statement": "A positive integer is called $k$-beautiful, if the digit sum of the decimal representation of this number is divisible by $k^{\\dagger}$. For example, $9272$ is $5$-beautiful, since the digit sum of $9272$ is $9 + 2 + 7 + 2 = 20$.\n\nYou are given two integers $x$ and $k$. Please find the smallest integer $y \\ge x$ which is $k$-beautiful.\n\n$^{\\dagger}$ An integer $n$ is divisible by $k$ if there exists an integer $m$ such that $n = k \\cdot m$.",
    "tutorial": "Let $y$ be the answer to the problem. Note that $y - x \\leq 18$ and the problem can be solved by brute force. We will prove this fact. If the difference between two numbers is greater than $18$, then there will definitely be a sequence of $10$ numbers where only the last digit differs. Therefore, if the sum of the digits of a number with the last digit $0$ is equal to $x$, then there were sums of digits equal to $x, x + 1, \\ldots, x + 9$. Here, there are exactly $10$ consecutive numbers and for each $k$ from $1$ to $10$, there exists a number from this range that is divisible by $k$.",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1884",
    "index": "B",
    "title": "Haunted House",
    "statement": "You are given a number in binary representation consisting of exactly $n$ bits, possibly, with leading zeroes. For example, for $n = 5$ the number $6$ will be given as $00110$, and for $n = 4$ the number $9$ will be given as $1001$.\n\nLet's fix some integer $i$ such that $1 \\le i \\le n$. In one operation you can swap any two adjacent bits in the binary representation. Your goal is to find the smallest number of operations you are required to perform to make the number divisible by $2^i$, or say that it is impossible.\n\nPlease note that for each $1 \\le i \\le n$ you are solving the problem independently.",
    "tutorial": "In order for a number to be divisible by $2^i$, the last $i$ bits of its binary representation must be equal to $0$. For convenience, let's reverse the binary representation of the number so that our operations aim to zero out the first $i$ bits. Let $zero$ be the number of bits equal to $0$ in the original string. If $i > zero$, it is obvious that the answer is $-1$ since our operations do not change the number of zeros and ones in the number. Otherwise, the answer exists, and we will learn how to calculate the minimum number of operations. Consider all $j \\leq i$, where $s_j = 1$. We need to remove these ones from our prefix by replacing them with the nearest zeros after position $i$. We will traverse the string from left to right, keeping track of the number of ones in our prefix (denoted as $cnt$) and the sum of their positions (denoted as $sum\\_one$). We also need to maintain the sum of the nearest $cnt$ positions of zeros after our element $i$ (denoted as $sum\\_zero$). This can be done using a pointer. The answer is $sum\\_zero - sum\\_one$. This is both a lower bound estimate and can be greedily shown how to obtain this answer in such a number of operations. First, let's place all the ones at the end of our prefix. We will place the rightmost one at position $i$ and so on. This can be done in $\\sum\\limits_{j=i - cnt + 1}^i (j - pos)$ operations, where $pos$ is the position of the corresponding one, which in general is actually $= -sum\\_one + \\sum\\limits_{j = i - cnt + 1}^i j$. Now we want to place zeros at these positions, and we will do this greedily $cnt$ times, performing $\\sum\\limits_{j=i - cnt + 1}^i (pos - j)$ operations, where $pos$ is the position of $0$. Again, the total is $= sum\\_zero - \\sum\\limits_{j = i - cnt + 1}^i j$. Our answer is the sum of these two, which is $sum\\_zero - sum\\_one$.",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1884",
    "index": "C",
    "title": "Medium Design",
    "statement": "The array $a_1, a_2, \\ldots, a_m$ is initially filled with zeroes. You are given $n$ pairwise distinct segments $1 \\le l_i \\le r_i \\le m$. You have to select an arbitrary subset of these segments (in particular, you may select an empty set). Next, you do the following:\n\n- For each $i = 1, 2, \\ldots, n$, if the segment $(l_i, r_i)$ has been selected to the subset, then for each index $l_i \\le j \\le r_i$ you increase $a_j$ by $1$ (i. e. $a_j$ is replaced by $a_j + 1$). If the segment $(l_i, r_i)$ has not been selected, the array does not change.\n- Next (after processing all values of $i = 1, 2, \\ldots, n$), you compute $\\max(a)$ as the maximum value among all elements of $a$. Analogously, compute $\\min(a)$ as the minimum value.\n- Finally, the cost of the selected subset of segments is declared as $\\max(a) - \\min(a)$.\n\nPlease, find the maximum cost among all subsets of segments.",
    "tutorial": "Let $x$ be the position of the maximum element in the array $a$ in the optimal answer. Notice that in this case, we can select all the segments where $l \\leq x \\leq r$, because if the position of the minimum element is outside of this segment, we increase the answer by $+1$, and if it is inside, we do not worsen the answer. From this, it follows that the minimum will either occur at position $1$ or at position $m$. We can then consider the segments that do not contain position $1$ (similarly, we can do the same for $m$) and find the position that is covered by the largest number of such segments. This can be done using a line sweep algorithm. A segment $(l, r)$ corresponds to two events: $(l, 0)$ - the segment opens, and $(r, 1)$ - the segment closes. We sort these events and iterate through them, keeping track of the number of open segments at each moment. The maximum value among these quantities is what we need. The solution works in $O(n \\log n)$ time.",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1884",
    "index": "D",
    "title": "Counting Rhyme",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$.\n\nA pair of integers $(i, j)$, such that $1 \\le i < j \\le n$, is called good, if there \\textbf{does not exist} an integer $k$ ($1 \\le k \\le n$) such that $a_i$ is divisible by $a_k$ and $a_j$ is divisible by $a_k$ at the same time.\n\nPlease, find the number of good pairs.",
    "tutorial": "Note that if $a_i$ is divisible by $a_k$ and $a_j$ is divisible by $a_k$, then $\\gcd(a_i, a_j)$ is divisible by $a_k$. Let's calculate the number of pairs from the array for each $g$, such that the $\\gcd$ is equal to $g$. To do this, we will create $dp_g$ - the number of pairs in the array with $\\gcd$ equal to $g$. For this, we will need an array of counts - $cnt_x$, the number of occurrences of the number $x$ in the array. To calculate $dp_g$, we need to know how many numbers are divisible by $g$, specifically the sum $s = cnt_g + cnt_{2g} + \\ldots + cnt_{kg}$, where $kg \\leq n$. Therefore, the number of pairs with $\\gcd$ equal to $g$ is $\\frac{s \\cdot (s - 1)}{2}$. However, not all of them have $\\gcd$ equal to $g$, it can be equal to a number that is a multiple of $g$. Therefore, $dp_g = \\frac{s \\cdot (s - 1)}{2} - dp_{2g} - \\ldots - dp_{kg}$. This dynamic programming can be calculated in $O(n \\log n)$ time. Now let's understand which $\\gcd$ values are not suitable. If there is a number $x$ in the array (i.e., $cnt_x > 0$), then all $g$ multiples of $x$ are not suitable. This can also be calculated in $O(n \\log n)$ time. Finally, we just need to sum up all the $dp_g$ values, where the number $g$ is not divisible by any number in the array.",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1884",
    "index": "E",
    "title": "Hard Design",
    "statement": "Consider an array of integers $b_0, b_1, \\ldots, b_{n-1}$. Your goal is to make all its elements equal. To do so, you can perform the following operation several (possibly, zero) times:\n\n- Pick a pair of indices $0 \\le l \\le r \\le n-1$, then for each $l \\le i \\le r$ increase $b_i$ by $1$ (i. e. replace $b_i$ with $b_i + 1$).\n- After performing this operation you receive $(r - l + 1)^2$ coins.\n\nThe value $f(b)$ is defined as a pair of integers $(cnt, cost)$, where $cnt$ is the \\textbf{smallest} number of operations required to make all elements of the array equal, and $cost$ is the \\textbf{largest} total number of coins you can receive among all possible ways to make all elements equal within $cnt$ operations. In other words, first, you need to minimize the number of operations, second, you need to maximize the total number of coins you receive.\n\nYou are given an array of integers $a_0, a_1, \\ldots, a_{n-1}$. Please, find the value of $f$ for all cyclic shifts of $a$.\n\nFormally, for each $0 \\le i \\le n-1$ you need to do the following:\n\n- Let $c_j = a_{(j + i) \\pmod{n}}$ for each $0 \\le j \\le n-1$.\n- Find $f(c)$. Since $cost$ can be very large, output it modulo $(10^9 + 7)$.\n\nPlease note that under a fixed $cnt$ you need to maximize the total number of coins $cost$, not its remainder modulo $(10^9 + 7)$.",
    "tutorial": "Let's learn how to solve a problem for a given array. Notice that we want to make all elements equal to the maximum value in the array. For convenience, let's solve a similar problem that is easier to implement. We'll create an array $b_i = \\max(a) - a_i$. Then, instead of performing an addition operation, we'll perform a subtraction operation by $-1$ on a range, aiming to make all elements of the array equal to $0$. Let $pos$ be the position of the minimum element in the array $b$. We can apply the operation $b_{pos}$ times on the entire array, and then recursively solve the problem for the left and right parts relative to the position $pos$. However, this doesn't help us solve the problem for all shifts. Let's find the nearest element less than or equal to each element on the left (denoted as $l_i$) and the nearest element less than each element on the right (denoted as $r_i$) - this can be done using linear algorithms. Then, we can observe that when we consider the subarray $l_i + 1 \\ldots r_i - 1$ in our recursive solution, we add to the answer a value equal to $b_i - \\max(b_{l_i}, b_{r_i})$. We have found a solution to the problem in $O(n)$ time for a fixed array $a$. If we consider all shifts of the array, the nearest elements on the left/right either remain unchanged or simply do not exist, in which case we consider their values to be $0$. Therefore, if we fix the position $i$ (want to determine how much it affects the answer for each position in the array), we have three shift ranges for which we can add different values. Hence, we have $O(n)$ ranges on which we need to add certain values. Since we don't have to make these additions immediately, we can create an array $add_i$ - the value that needs to be added to all elements starting from position $i$. Then, adding the number $x$ on the range $l \\ldots r$ changes this array as follows: $add_l = add_l + x$, $add_{r + 1} = add_{r + 1} - x$. The answer to the problem is $ans_i = \\sum\\limits_{j=1}^i add_i$. This subproblem can be solved in $O(n)$ time. Next, we need to learn how to calculate the total cost. The approach will be similar, but now we need to add a more complex function. If both nearest elements are within a shift range, we will add $(r_i - l_i - 1)^2 \\cdot (b_i - \\max(b_{l_i}, b_{r_i})$ - a fixed number. If there is no nearest element on the left/right, we will add a value of the form $(r_i - s + 1)^2 \\cdot (b_i - b_{r_i})$ or $(s + n - i + 1)^2 \\cdot (b_i - b_{l_i})$, where $s$ is the index of the start of the shift position. Both cases can be solved similarly. If we expand the brackets, we get an expression of the form $a \\cdot s^2 + b \\cdot s + c$, where $a, b, c$ are known coefficients. Let's represent the answer for a fixed shift in this form, and we need to find the value of each coefficient, which is simply adding a fixed number on a range, as we discussed in the previous paragraph. This can also be solved in $O(n)$ time.",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1886",
    "index": "A",
    "title": "Sum of Three",
    "statement": "Monocarp has an integer $n$.\n\nHe wants to represent his number as a sum of three \\textbf{distinct} positive integers $x$, $y$, and $z$. Additionally, Monocarp wants none of the numbers $x$, $y$, and $z$ to be divisible by $3$.\n\nYour task is to help Monocarp to find any valid triplet of distinct positive integers $x$, $y$, and $z$, or report that such a triplet does not exist.",
    "tutorial": "You can solve this problem with some case analysis, but I'll describe another solution. Suppose we want to iterate on every $x$, and then on every $y$, and then calculate $z$ and check that everything's OK. Obviously, this is too slow. But we can speed this up: we don't have to iterate on all possible values of $x$ and $y$. Suppose $x < y < z$; then, if $x \\ge 4$, we can decrease $x$ by $3$ and increase $z$ by $3$, until $x$ becomes either $1$ or $2$. The same goes for $y$: if $y \\ge 7$, we can decrease it by $3$ and increase $z$ by $3$, until $y < 7$. So, we only have to iterate on $x$ up to $2$, and on $y$ up to $5$. This yields a solution in $O(1)$. You don't have to iterate on $x$ up to exactly $2$ and on $y$ up to exactly $5$, just use an upper bound for which you don't check too many possible triples of $x$, $y$ and $z$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\n\ninline void read() {\n\tcin >> n;\n}\n\ninline void solve() {\n\tfor (int x = 1; x <= 20; x++) {\n\t    for (int y = 1; y <= 20; y++) {\n\t        if (x + y >= n || x == y) continue;\n\t        int z = n - x - y;\n\t        if (z == x || z == y) continue;\n\t        if (x % 3 == 0 || y % 3 == 0 || z % 3 == 0) {\n\t            continue;\n\t        }\n\t        puts(\"YES\");\n\t        cout << x << ' ' << y << ' ' << z << endl;\n\t        return;\n\t    }\n\t}\n\tputs(\"NO\");\n}\n\nint main () {\n    int t;\n    cin >> t;\n    while (t--){\n        read();\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1886",
    "index": "B",
    "title": "Fear of the Dark",
    "statement": "Monocarp tries to get home from work. He is currently at the point $O = (0, 0)$ of a two-dimensional plane; his house is at the point $P = (P_x, P_y)$.\n\nUnfortunately, it is late in the evening, so it is very dark. Monocarp is afraid of the darkness. He would like to go home along a path illuminated by something.\n\nThankfully, there are two lanterns, located in the points $A = (A_x, A_y)$ and $B = (B_x, B_y)$. You can choose any non-negative number $w$ and set the power of \\textbf{both} lanterns to $w$. If a lantern's power is set to $w$, it illuminates a circle of radius $w$ centered at the lantern location (including the borders of the circle).\n\nYou have to choose the minimum non-negative value $w$ for the power of the lanterns in such a way that \\textbf{there is a path from the point $O$ to the point $P$ which is completely illuminated}. You may assume that the lanterns don't interfere with Monocarp's movement.\n\n\\begin{center}\n{\\small The picture for the first two test cases}\n\\end{center}",
    "tutorial": "There are only two major cases: both points $O$ and $P$ lie inside the same circle, or the point $O$ lies inside one of the circles and $P$ lies inside the other circle. Let's denote the distance between the points $P$ and $Q$ as $d(P, Q)$. Let's look at the first case, when the points $O$ and $P$ lie inside the circle centered at $A$. In that case, inequalities $d(O, A) \\le R$ and $d(P, A) \\le R$ must be satisfied. Therefore, the minimum possible radius for that case is equal to $\\max(d(O, A), d(P, A))$. Similarly, for the circle centered at $B$, the minimum possible radius for that case is equal to $\\max(d(O, B), d(P, B))$. Let's look at the second case, when the point $O$ lies inside the circle centered at $A$ and the point $P$ lies inside the circle centered at $B$. In that case, inequalities $d(O, A) \\le R$ and $d(P, B) \\le R$ must be satisfied. But there is one extra constraint: the circles must intersect, because there is should an illuminated path from one circle to another. This adds one more inequality - $d(A, B) \\le 2R$. Therefore, the minimum possible radius for that case is equal to $\\max\\left(d(O, A), d(P, B), \\frac{d(A, B)}{2}\\right)$. Similarly, when $O$ lies inside the circle centered at $B$ and $P$ lies inside the circle centered at $A$, the minimum possible radius for that case is equal to $\\max\\left(d(O, B), d(P, A), \\frac{d(A, B)}{2}\\right)$. So the answer to the problem is the minimum among aforementioned cases.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  auto dist = [](int x1, int y1, int x2, int y2) {\n    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n  };\n \n  int t;\n  cin >> t;\n  while (t--) {\n    int px, py, ax, ay, bx, by;\n    cin >> px >> py >> ax >> ay >> bx >> by;\n    double pa = dist(px, py, ax, ay), pb = dist(px, py, bx, by);\n    double oa = dist(0, 0, ax, ay), ob = dist(0, 0, bx, by);\n    double ab = dist(ax, ay, bx, by);\n    double ans = 1e9;\n    ans = min(ans, max(pa, oa));\n    ans = min(ans, max(pb, ob));\n    ans = min(ans, max({ab / 2, pa, ob}));\n    ans = min(ans, max({ab / 2, pb, oa}));\n    cout << setprecision(10) << fixed << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "geometry",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1886",
    "index": "C",
    "title": "Decreasing String",
    "statement": "Recall that string $a$ is lexicographically smaller than string $b$ if $a$ is a prefix of $b$ (and $a \\ne b$), or there exists an index $i$ ($1 \\le i \\le \\min(|a|, |b|)$) such that $a_i < b_i$, and for any index $j$ ($1 \\le j < i$) $a_j = b_j$.\n\nConsider a sequence of strings $s_1, s_2, \\dots, s_n$, each consisting of lowercase Latin letters. String $s_1$ is given explicitly, and all other strings are generated according to the following rule: to obtain the string $s_i$, a character is removed from string $s_{i-1}$ in such a way that string $s_i$ is lexicographically minimal.\n\nFor example, if $s_1 = \\mathrm{dacb}$, then string $s_2 = \\mathrm{acb}$, string $s_3 = \\mathrm{ab}$, string $s_4 = \\mathrm{a}$.\n\nAfter that, we obtain the string $S = s_1 + s_2 + \\dots + s_n$ ($S$ is the concatenation of all strings $s_1, s_2, \\dots, s_n$).\n\nYou need to output the character in position $pos$ of the string $S$ (i. e. the character $S_{pos}$).",
    "tutorial": "Let's analyze in which order the characters should be removed from the given string. Suppose we want to remove a character so that the resulting string is lexicographically smallest. We can show that the best option is to find the leftmost pair of adjacent characters $S_i, S_{i+1}$ such that $S_i > S_{i+1}$: removing $S_i$ will decrease the character on that position; if you remove some character to the right of $S_i$, the $i$-th character won't decrease; and if you remove some character to the left of $S_i$, you might accidentally increase some character before the $i$-th position (we chose the leftmost such pair, so the prefix until the $i$-th character is non-decreasing). If there is no such pair of adjacent characters, you should remove the last character of the string. Unfortunately, implementing it naively is too slow (the solution will work in $O(n^2)$). Thankfully, there is a way to determine in which all characters are removed in $O(n)$. Maintain a stack of characters (initially empty) and iterate over the string from left to right. When you encounter a character, if the stack is empty or the character on top of the stack is not greater than the current one, you don't have to remove anything, just push the new character into the stack. But if the character on top of the stack is greater than the new one, then we have found a pair of adjacent characters which meets the condition; so, the character on top of the stack is the next to remove. Pop the topmost element of the stack. Note that we don't push the new character into the stack yet, because the next element on top of the stack might still be greater - in that case, this is the next character to remove (and we pop it), and so on. In the end, the character in the stack will be non-descending from the bottom of the stack to the top, and we should remove them from top to bottom. That's how we can find in which order characters are removed. The rest is quite easy: locate in which of the strings $s_1, s_2, \\dots, s_n$ the position $pos$ occurs, remove the required number of characters, and print the corresponding character of the resulting string. Minor detail which can make the implementation easier: if you append some character which is less than a to the end of the given string, you don't have to consider the case when there's no pair of adjacent characters $S_i > S_{i+1}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200000;\n\nint t;\n\nint main() {\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        string s;\n        long long pos;\n        cin >> s >> pos;\n        --pos;\n        \n        int curLen = s.size();\n        vector <char> st;\n        bool ok = pos < curLen;\n        s += '$';\n        \n        for (auto c : s) {\n            while (!ok && st.size() > 0 && st.back() > c) {\n                pos -= curLen;\n                --curLen;\n                st.pop_back();\n                \n                if(pos < curLen) \n                    ok = true;\n            }\n            st.push_back(c);\n        }\n        \n        cout << st[pos];\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1886",
    "index": "D",
    "title": "Monocarp and the Set",
    "statement": "Monocarp has $n$ numbers $1, 2, \\dots, n$ and a set (initially empty). He adds his numbers to this set $n$ times in some order. During each step, he adds a new number (which has not been present in the set before). In other words, the sequence of added numbers is a permutation of length $n$.\n\nEvery time Monocarp adds an element into the set \\textbf{except for the first time}, he writes out a character:\n\n- if the element Monocarp is trying to insert becomes the maximum element in the set, Monocarp writes out the character >;\n- if the element Monocarp is trying to insert becomes the minimum element in the set, Monocarp writes out the character <;\n- if none of the above, Monocarp writes out the character ?.\n\nYou are given a string $s$ of $n-1$ characters, which represents the characters written out by Monocarp (in the order he wrote them out). You have to process $m$ queries to the string. Each query has the following format:\n\n- $i$ $c$ — replace $s_i$ with the character $c$.\n\nBoth before processing the queries and after each query, you have to calculate the number of different ways to order the integers $1, 2, 3, \\dots, n$ such that, if Monocarp inserts the integers into the set in that order, he gets the string $s$. Since the answers might be large, print them modulo $998244353$.",
    "tutorial": "The key observation to this problem is that it's much easier to consider the process in reverse. Suppose Monocarp has a set of integers $1, 2, \\dots, n$, and starts removing elements from it one by one. During the $i$-th deletion, if $s_{n-i}$ is <, he removes the minimum element; if $s_{n-i}$ is >, he removes the maximum element; and if $s_{n-i}$ is ?, he removes any element which is neither the minimum nor the maximum. If you consider the process backwards, it's quite easy to see that it doesn't actually matter which numbers are present in the set; we are interested only in their quantity. So, for each action, we can choose an element to remove independently: if $s_{n-i}$ is < or >, there is only one way, otherwise, there are $k-2$ ways, where $k$ is the number of elements in the set (for the $i$-th deletion operation, it is $n-i+1$). So, the answer to the problem is the product of $j-1$ for every character $s_j$ that is equal to ?. To recalculate the answer efficiently when you change a character, you can use one of the following options: build a segment tree with operation \"product on segment modulo $998244353$\"; or use modular inverse to maintain division operations. Note that sometimes you have to \"divide by zero\", i. e. remove the zero from the product (when $s_1$ changes from ? to another character); to handle it, you can store the product for every $s_i$ from $2$ to $n-1$, and explicitly multiply it by $0$ before printing when $s_1$ is ?.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nconst int N = 300009;\n\nint bp(int a, int n) {\n    int res = 1;\n    while(n > 0) {\n        if (n & 1)\n            res = (res * 1LL * a) % MOD;\n        a = (a * 1LL * a) % MOD;\n        n >>= 1;\n    }\n    return res;\n}\n\nint n, m;\nstring s;\nint inv[N];\n\nvoid upd(int &res, int x) {\n    res = (res * 1LL * x) % MOD;\n}\n\nint main() {\n    inv[1] = 1;\n    for (int i = 2; i < N; ++i){\n\t    inv[i] = bp(i, MOD - 2);\n    }\n    \n    cin >> n >> m >> s;\n    \n    int res = 1, k = n;\n    bool isZero = false;\n    for (int i = 0; i < s.size(); ++i) \n        if (s[i] == '?') {\n            if (i == 0) {\n                isZero = true;\n            } else {\n                upd(res, i);\n            }\n        }\n    \n    cout << (isZero? 0 : res) << endl;\n    \n    for(int i = 0; i < m; ++i) {\n        int pos;\n        char c;\n        cin >> pos >> c;\n        --pos;\n        \n        if (s[pos] == '?' && (c == '<' || c == '>')) {\n            if (pos == 0)\n                isZero = false;\n            else\n                upd(res, inv[pos]);\n        } else if ((s[pos] == '<' || s[pos] == '>') && c == '?') {\n            if (pos == 0)\n                isZero = true;\n            else\n                upd(res, pos);\n        }\n        \n        s[pos] = c;\n        cout << (isZero? 0 : res) << endl;\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1886",
    "index": "E",
    "title": "I Wanna be the Team Leader",
    "statement": "Monocarp is a team leader in a massive IT company.\n\nThere are $m$ projects his team of programmers has to complete, numbered from $1$ to $m$. The $i$-th project has a difficulty level $b_i$.\n\nThere are $n$ programmers in the team, numbered from $1$ to $n$. The $j$-th programmer has a stress tolerance level $a_j$.\n\nMonocarp wants to assign the programmers to the projects in such a way that:\n\n- each programmer is assigned to no more than one project;\n- each project has at least one programmer assigned to it;\n- let $k$ programmers be assigned to the $i$-th project; then all the assigned programmers have to have a stress tolerance level greater than or equal to $\\frac{b_i}{k}$.\n\nHelp Monocarp to find a valid assignment. If there are multiple answers, print any of them.",
    "tutorial": "Let's start by arranging the programmers in the increasing order of their stress tolerance level. Not obvious what it achieves at first, but it always helps to sort, doesn't it? Now, consider some assignment of the programmers to the projects. Notice how it's always optimal to take the suffix of the programmers. If there is a valid answer which is not a suffix, then you can always take drop the weakest programmer and replace him with the strongest non-taken one, and the answer will still be valid. We can actually propagate the argument further. It's also always optimal for each project to have assigned a segment of programmers. Look at the weakest taken programmer again and think about the project he's assigned to. All that matters for the project is the number of other programmers assigned to it. So, you can safely replace the current assigned programmers with the same count of the next weakest ones. You can do it by swapping the assigned projects of the adjacent programmers. This way, every swap can only make any other project's weakest programmer stronger. Thus, we can actually build the answer the following way. Choose a project and assign the shortest possible suffix of non-taken programmers to it. We just have to determine the order of the projects to take. Well, let's use dynamic programming for that. Let $\\mathit{dp}[\\mathit{mask}]$ be the shortest suffix of the programmers that can be assigned to the projects from $\\mathit{mask}$. For a transition, just choose one of the projects that isn't in $\\mathit{mask}$ and find the shortest segment of programmers starting from $\\mathit{dp}[\\mathit{mask}]$. How to find this shortest suffix fast enough? You can precompute it before calculating the dynamic programming. For each project and each starting index, you can calculate the shortest suffix with two pointers. Overall complexity: $O(nm + m2^m)$.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nint main() {\n\tint n, m;\n\tscanf(\"%d%d\", &n, &m);\n\tvector<int> a(n), b(m);\n\tforn(i, n) scanf(\"%d\", &a[i]);\n\tforn(i, m) scanf(\"%d\", &b[i]);\n\tvector<int> ord(n);\n\tiota(ord.begin(), ord.end(), 0);\n\tsort(ord.begin(), ord.end(), [&a](int i, int j){\n\t\treturn a[i] > a[j];\n\t});\n\tvector<vector<int>> mn(m, vector<int>(n + 2));\n\tforn(i, m){\n\t\tint r = 0;\n\t\tforn(l, n + 2){\n\t\t\tr = min(n + 1, max(r, l + 1));\n\t\t\twhile (r <= n && a[ord[r - 1]] * (r - l) < b[i]) ++r;\n\t\t\tmn[i][l] = r;\n\t\t}\n\t}\n\tvector<int> dp(1 << m, n + 1);\n\tdp[0] = 0;\n\tvector<int> p(1 << m, -1);\n\tforn(mask, 1 << m) forn(i, m) if (!((mask >> i) & 1) && dp[mask | (1 << i)] > mn[i][dp[mask]]){\n\t\tdp[mask | (1 << i)] = mn[i][dp[mask]];\n\t\tp[mask | (1 << i)] = mask;\n\t}\n\tint mask = (1 << m) - 1;\n\tif (dp[mask] > n){\n\t\tputs(\"NO\");\n\t\treturn 0;\n\t}\n\tputs(\"YES\");\n\tvector<vector<int>> ans(n);\n\tforn(_, m){\n\t\tint i = __builtin_ctz(mask ^ p[mask]);\n\t\tfor (int j = dp[p[mask]]; j < dp[mask]; ++j)\n\t\t\tans[i].push_back(ord[j]);\n\t\tmask = p[mask];\n\t}\n\tforn(i, m){\n\t\tprintf(\"%d\", int(ans[i].size()));\n\t\tfor (int x : ans[i]) printf(\" %d\", x + 1);\n\t\tputs(\"\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1886",
    "index": "F",
    "title": "Diamond Theft",
    "statement": "Monocarp is the most famous thief in Berland. This time, he decided to steal two diamonds. Unfortunately for Monocarp, there are $n$ cameras monitoring the diamonds. Each camera has two parameters, $t_i$ and $s_i$. The first parameter determines whether the camera is monitoring the first diamond only ($t_i=1$), the second diamond only ($t_i=2$), or both diamonds ($t_i=3$). The second parameter determines the number of seconds the camera will be disabled after it is hacked.\n\nEvery second, Monocarp can perform one of the following three actions:\n\n- do nothing;\n- choose a camera and hack it; if Monocarp hacks the $i$-th camera, it will be disabled for the next $s_i$ seconds (if the current second is the $T$-th one, the camera will be disabled from the $(T+1)$-th to the $(T+s_i)$-th second, inclusive);\n- steal a diamond if all cameras monitoring it are currently disabled. Monocarp cannot steal the second diamond if he hasn't stolen the first diamond yet.\n\nNote that Monocarp can hack a camera multiple times, even if it is currently disabled.\n\nYour task is to determine the minimum time it will take Monocarp to steal both diamonds, \\textbf{beginning with the first diamond}, or report that it is impossible.",
    "tutorial": "In this editorial, we will denote the number of cameras of type $i$ as $k_i$. Without loss of generality, we can assume that our sequence of actions will look as follows: hack all cameras of type $1$, some cameras of type $2$ and all cameras of type $3$ in some order (let's call it the first block of actions); steal the first diamond; hack the remaining cameras of type $2$ and some cameras of type $3$ (the second block of actions); steal the second diamond. Note that we don't hack the same camera of type $1$ or $2$ twice (this is just suboptimal), but some cameras of type $3$ will be hacked twice. We have to minimize the number of cameras of type $3$ which will be hacked twice. Let's iterate on the number of actions we make after stealing the first diamond (denote it by $len$), and then iterate on the number of cameras of type $2$ in the first block (denote it by $i$). Then, the number of cameras of type $2$ we hack in the second block will be $k_2 - i$, and the number of cameras of type $3$ we hack in the second block is $len - (k_2 - i) - 1$. Since this is also the number of cameras of type $3$ we hack twice, we have to minimize this number. Note that the length of the first block is also fixed: it should be $k_1 + k_3 + i$. Suppose we fixed which cameras of type $2$ and $3$ go to the second block, and which don't. For each block, we will store a special data structure that, for every $x$ from $0$ to the length of the block, calculates the value of $d_x - x$, where $d_x$ is the number of cameras which have to be hacked during the last $x$ actions in the block. Using something like Hall's theorem, we can prove that if every value of $d_x - x$ for every block is non-positive, there exists a way to hack all cameras in time. This can be efficiently modeled with a segment tree. All cameras of type $1$ should be inserted into the data structure for the first block. For the cameras of type $2$, we either insert them into the second block, or insert them into the first block while subtracting $len$ from their values of $s_j$. For the cameras of type $3$, we either insert them into both blocks, or insert them into the first block while subtracting $len$ from their values of $s_j$. Among all cameras of type $2$, which ones should belong to the first block, and which ones - to the second block? It's quite easy to see that the \"longest\" cameras of type $2$ should be in the first block. Unfortunately, with cameras of type $3$, it's a bit more tricky. First, let's insert all cameras of type $1$ into the first block and all cameras of type $2$ into the blocks chosen for them. Then sort all cameras of type $3$ (in ascending order of their $s_j$ values) and use the following greedy approach: if a camera can be inserted into the first block after we subtract $len$ from its $s_j$, we insert it there; otherwise, we insert it into both blocks without subtraction. This greedy approach can be proved using something like exchange argument: if we skipped some camera which could be inserted into the first block, and chose some other camera for the same slot, they can be \"swapped\". So, all cameras of type $3$ are partitioned into two types. After you've done inserting cameras into the respective blocks, check that everything's fine. This works in something like $O(n^3 \\log n)$. Unfortunately, it is too slow. To speed this up, let's use the following strategy: iterate on the value of $len$, then try solving the problem for $i=0$ (i. e. all cameras of type $2$ are initially in the second block). If it fails, we can try increasing $i$, shifting a camera of type $2$ from the second block to the first block and rebuilding the partition of cameras of type $3$, instead of starting it from scratch. But how do we rebuild the partition of cameras of type $3$? We can use the following strategy. Store a set of cameras of type $3$ (sorted by their $s_j$) which are inserted only into the first block. While the first block is not OK (i. e. there exists some value of $x$ such that $d_x - x$ is positive), we will find the minimum $x$ such that $d_x - x$ is positive, and try to decrease it as follows: search for the camera of type $3$ which belongs only to the first block, has $s_j - len \\le x$, and has the maximum $s_j$ among all such cameras. This is the camera which should be moved in the partition (i. e. instead of storing it in the first block, we store it in both blocks). Note that you might need to repeat this process (i. e. when you move a camera of type $2$ to the first block, it can force multiple cameras of type $3$ into the second block). Thus, our solution now works in $O(n^2 \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 3003;\n \nint n;\nint k[4];\nvector<int> a[4];\n \nstruct segtree {\n  int sz;\n  int tot;\n  vector<int> t, p;\n  \n  segtree(int sz) : sz(sz) {\n    tot = 0;\n    t = vector<int>(4 * sz);\n    p = vector<int>(4 * sz);\n    build(0, 0, sz);\n  }\n  \n  void build(int v, int l, int r) {\n    if (l + 1 == r) {\n      t[v] = -l;\n      return;\n    }\n    int m = (l + r) / 2;\n    build(v * 2 + 1, l, m);\n    build(v * 2 + 2, m, r);\n    t[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n  }\n  \n  void push(int v) {\n    if (p[v] == 0) return;\n    if (v + 1 < 2 * sz) {\n      t[v * 2 + 1] += p[v];\n      p[v * 2 + 1] += p[v];\n      t[v * 2 + 2] += p[v];\n      p[v * 2 + 2] += p[v];\n      p[v] = 0;\n    }\n  } \n  \n  void upd(int v, int l, int r, int L, int R, int x) {\n    if (L >= R) return;\n    if (l == L && r == R) {\n      t[v] += x;\n      p[v] += x;\n      return;\n    }\n    push(v);\n    int m = (l + r) / 2;\n    upd(v * 2 + 1, l, m, L, min(m, R), x);\n    upd(v * 2 + 2, m, r, max(L, m), R, x);\n    t[v] = max(t[v * 2 + 1], t[v * 2 + 2]);\n  }\n  \n  void upd(int pos, int x) { \n    tot += x;\n    upd(0, 0, sz, max(0, pos), sz, x);\n  }\n  \n  int get(int v, int l, int r, int L, int R) {\n    if (L >= R) return -1e9;\n    if (l == L && r == R) return t[v];\n    push(v);\n    int m = (l + r) / 2;\n    return max(\n      get(v * 2 + 1, l, m, L, min(m, R)),\n      get(v * 2 + 2, m, r, max(L, m), R)\n    );\n  }\n  \n  int get(int L) {\n    return get(0, 0, sz, max(0, L), sz);\n  }\n  \n  int getBad(int v, int l, int r) {\n    if (t[v] <= 0) return -1;\n    if (l + 1 == r) return l;\n    push(v);\n    int m = (l + r) / 2;\n    if (t[v * 2 + 1] > 0) {\n      return getBad(v * 2 + 1, l, m);\n    } else {\n      return getBad(v * 2 + 2, m, r);\n    }\n  }\n  \n  int getBad() {\n    return getBad(0, 0, sz);\n  }\n};  \n \nint main() {\n  cin >> n;\n  int sz = 1;\n  for (int i = 0; i < n; ++i) {\n    int t, s;\n    cin >> t >> s;\n    a[t].push_back(s);\n    sz = max(sz, s + 1);\n  }\n  for (int t = 1; t < 4; ++t) {\n    sort(a[t].begin(), a[t].end());\n    k[t] = a[t].size();\n  }\n  reverse(a[2].begin(), a[2].end());\n  int ans = 1e4;\n  for (int len = 1; len <= k[2] + k[3] + 1; ++len) {\n    segtree L(sz), R(sz);\n    multiset<int> used;\n    for (int x : a[1]) L.upd(x, +1);\n    for (int x : a[2]) R.upd(x, +1);\n    for (int x : a[3]) {\n      L.upd(x - len, +1);\n      if (L.t[0] <= 0) {\n        used.insert(x - len);\n      } else {\n        L.upd(x - len, -1);\n        L.upd(x, +1);\n        R.upd(x, +1);\n      }\n    }\n    for (int i = 0; i <= k[2]; ++i) {\n      if (L.t[0] <= 0 && R.t[0] <= 0 && R.tot + 1 <= len)\n        ans = min(ans, n + (k[3] - (int)used.size()) + 2); \n      if (i == k[2]) break;\n      R.upd(a[2][i], -1);\n      L.upd(a[2][i] - len, +1);\n      int pos;\n      while ((pos = L.getBad()) != -1) {\n        auto it = used.upper_bound(pos);\n        if (it == used.begin()) break;\n        --it;\n        L.upd(*it, -1);\n        L.upd(*it + len, +1);\n        R.upd(*it + len, +1);\n        used.erase(it);\n      }\n    }\n  }\n  if (ans == 1e4) ans = -1;\n  cout << ans << '\\n';\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1887",
    "index": "B",
    "title": "Time Travel",
    "statement": "Berland is a country with ancient history, where roads were built and destroyed for centuries. It is known that there always were $n$ cities in Berland. You also have records of $t$ key moments in the history of the country, numbered from $1$ to $t$. Each record contains a list of \\textbf{bidirectional} roads between some pairs of cities, which could be used for travel in Berland at a specific moment in time.\n\nYou have discovered a time machine that transports you between key moments. Unfortunately, you cannot choose what point in time to end up at, but you know the order consisting of $k$ moments in time $a_{i}$, in which the machine will transport you. Since there is little time between the travels, when you find yourself in the next key moment in time (\\textbf{including after the last time travel}), you can travel on at most one existing road at that moment, coming out from the city you were in before time travel.\n\nCurrently, you are in city $1$, and the time machine has already transported you to moment $a_{1}$. You want to reach city $n$ as quickly as possible. Determine the minimum number of time travels, \\textbf{including the first one}, that you need to make in order to reach city $n$.",
    "tutorial": "Let $d_{v}$ denote the minimum number of moves required to reach vertex $v$. Initially, $d_{v} = \\infty$ for all vertices except $1$, where $d_{1} = 0$. We will gradually mark the vertices for which we know the optimal answer. Similar to Dijkstra's algorithm, at each iteration, we will select the vertex $v$ with the minimum value of $d_{v}$ among the unmarked vertices. We will mark it and relax its neighbors: let $(v, u)$ be an edge belonging to record $x$, we will find the minimum index $i$ such that $d_{v} < i$ and $a_{i} = x$, then $d_{u} = \\min(d_{u}, i)$. We can find $i$ using binary search, by saving the indices of occurrences in $a$ for each time moments. The time complexity of the solution is $O(m (\\log k + \\log n))$.",
    "tags": [
      "binary search",
      "graphs",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1887",
    "index": "C",
    "title": "Minimum Array",
    "statement": "Given an array $a$ of length $n$ consisting of integers. Then the following operation is sequentially applied to it $q$ times:\n\n- Choose indices $l$ and $r$ ($1 \\le l \\le r \\le n$) and an integer $x$;\n- Add $x$ to all elements of the array $a$ in the segment $[l, r]$. More formally, assign $a_i := a_i + x$ for all $l \\le i \\le r$.\n\nLet $b_j$ be the array $a$ obtained after applying the first $j$ operations ($0 \\le j \\le q$). Note that $b_0$ is the array $a$ before applying any operations.\n\nYou need to find the lexicographically minimum$^{\\dagger}$ array among all arrays $b_j$.\n\n$^{\\dagger}$An array $x$ is lexicographically smaller than array $y$ if there is an index $i$ such that $x_i < y_i$, and $x_j = y_j$ for all $j < i$. In other words, for the first index $i$ where the arrays differ, $x_i < y_i$.",
    "tutorial": "Let $u$ be a difference array of an array $v$, i.e. $u_0 = v_0$, $u_i = v_i - v_{i-1}$ for all $i \\ge 1$. Note that minimizing an array is equivalent to minimizing its difference array. Let's see how the difference array changes: when asked, adding the number $add$ on the segment $[l; r]$ only 2 elements are updated in it: $add$ is added to the $l$th index, and $add$ is subtracted from the $r+1$th index. Let's learn how to compare difference arrays after the $j$th and $i$th queries ($j < i$). Let's consider an auxiliary array, which is a union of changes in the difference array for all queries with numbers from $j+1$ to $i$ inclusive. Consider in this auxiliary array the minimum non-zero element by index. Note that if it is negative, then the difference array after the $i$th query will be smaller than after the $j$th one, and if it is positive, then it will be larger. Let's go through the queries and maintain the number of the minimum difference array. Let the current minimum difference array after request be number $j$. Since changes to the difference array occur only in two indexes, we can maintain them in a dictionary containing changes to the difference array by index. When we want to process the next request, we update the values in the dictionary using two keys. After the change, you need to check the sign of the minimum non-zero element by index: If it is negative, then this means that the current request has updated the minimum, and we clear the dictionary so that we can now store changes relative to this request in it. If it is positive, then we leave the dictionary the same and continue to change it in subsequent queries. As a result, using the found index of the minimum difference array, we restore the array itself.",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "data structures",
      "greedy",
      "hashing",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1887",
    "index": "D",
    "title": "Split",
    "statement": "Let's call an array $b_1, b_2, \\ldots, b_m$ ($m \\ge 2$) good if it can be split into two parts such that all elements in the left part are strictly smaller than all elements in the right part. In other words, there must exist an index $1 \\le i < m$ such that every element from $b_1, \\ldots, b_i$ is strictly smaller than every element from $b_{i+1}, \\ldots, b_m$.\n\nGiven an array $a_1, a_2, \\ldots a_n$ consisting of \\textbf{distinct} integers from $1$ to $n$. There are $q$ queries. Each query consists of two numbers $l$ and $r$. For each query, determine whether the array $a_l, a_{l+1}, \\ldots, a_r$ is good.",
    "tutorial": "Let's fix element $i$. Let's find all intervals $[l, r]$ for which this element can be the maximum in the left part of a valid cut. Let $x_l$ be the nearest element to the left of $i$ greater than $a_i$, and $x_r$ be the nearest element to the right of $i$ greater than $a_i$. Then, for $i$ to be the maximum element in the left part of the cut, the following conditions must be satisfied: $\\begin{cases} x_l < l \\le i\\\\ x_r \\le r \\end{cases}$ But these conditions are obviously not enough, as we need to guarantee that all elements in the right part of the cut are greater than all elements in the left part of the cut. However, since $i$ is the maximum element in the left part of the cut, it is sufficient for all elements in the right part of the cut to be greater than $a_i$. Therefore, if $y_r$ is the nearest element to the right of $x_r$ smaller than $a_i$, then $r \\le y_r$. Thus, element $i$ can be the maximum element in the left part of the cut of interval $[l, r]$ $\\Longleftrightarrow$ the following conditions are satisfied: $\\begin{cases} x_l < l \\le i\\\\ x_r \\le r < y \\end{cases}$ For each element $i$, we can find $x_l$, $x_r$, and $y$ in $\\mathcal{O}(\\log n)$ time. This can be done, for example, using a segment tree or std::set if the elements are iterated in ascending order. It only remains to notice that if we consider the queries $[l, r]$ as points $(l, r)$, then each element $i$ makes all points in some rectangle good. Thus, the problem reduces to checking whether a point lies in one of the rectangles. This is a classic problem that can be solved using sweep line and, for example, a segment tree. We obtained a solution with a time complexity of $\\mathcal{O}(n\\log n)$.",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dsu",
      "math",
      "trees",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1887",
    "index": "E",
    "title": "Good Colorings",
    "statement": "Alice suggested Bob to play a game. Bob didn't like this idea, but he couldn't refuse Alice, so he asked you to write a program that would play instead of him.\n\nThe game starts with Alice taking out a grid sheet of size $n \\times n$, the cells of which are \\textbf{initially not colored}. After that she colors some $2n$ cells with colors $1,2,\\ldots, 2n$, respectively, and informs Bob about these cells.\n\nIn one move, Bob can point to a cell that has not been colored yet and ask Alice to color that cell. Alice colors that cell with one of the $2n$ colors of her choice, informing Bob of the chosen color. Bob can make no more than $10$ moves, after which he needs to find a good set of four cells.\n\nA set of four cells is considered good if the following conditions are met:\n\n- All the cells in the set are colored;\n- No two cells in the set are colored with the same color;\n- The centers of the cells form a rectangle with sides parallel to the grid lines.",
    "tutorial": "Let's consider a bipartite graph with $n$ rows and $n$ columns. The cells will correspond to the edges. According to the problem statement, we need to find a pair of rows $\\{ u, v \\}$ and a pair of columns $\\{ x, y \\}$ such that cells $(u,x), (u,y), (v, x), (v, y)$ have different colors. Notice that in graph terms, this means that we need to find a cycle of length $4$ with different colors. According to the problem statement, we have $2n$ edges with pairwise distinct colors in a graph with $2n$ vertices. This means that there must exist a cycle of length $2k$ with different colors. Let this cycle be $(v_1, v_2, \\ldots, v_{2k})$. Mentally construct the edges $(v_2, v_{2k-1}), (v_3, v_{2k-2}), \\ldots, (v_{k-1}, v_{k+2})$. These edges divide our cycle into $k-1$ cycles of length $4$ and are part of the complete bipartite graph. It is claimed that one of these cycles will definitely have different colors. To find it, we apply the binary search technique. Ask for the color of the edge that divides this cycle approximately in half. Its color will either not match any of the edges from the left half or all of the edges from the right half. In each of these cases, we managed to find a cycle with half the length. After $\\lceil log_2(k-1) \\rceil \\le 10$ queries, we will find a cycle of length $4$ with different colors, and therefore the desired set of four cells.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "graphs",
      "interactive"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1887",
    "index": "F",
    "title": "Minimum Segments",
    "statement": "You had a sequence $a_1, a_2, \\ldots, a_n$ consisting of integers from $1$ to $n$, not necessarily distinct. For some unknown reason, you decided to calculate the following characteristic of the sequence:\n\n- Let $r_i$ ($1 \\le i \\le n$) be the smallest $j \\ge i$ such that on the subsegment $a_i, a_{i+1}, \\ldots, a_j$ all distinct numbers from the sequence $a$ appear. More formally, for any $k \\in [1, n]$, there exists $l \\in [i, j]$ such that $a_k = a_l$. If such $j$ does not exist, $r_i$ is considered to be equal to $n+1$.\n- The characteristic of the sequence $a$ is defined as the sequence $r_1, r_2, \\ldots, r_n$.\n\nUnfortunately, the sequence $a$ got lost, but you still have its characteristic $r$. You want to reconstruct any sequence $a$ that matches the characteristic, or determine that there is an error in the characteristic and such a sequence does not exist.",
    "tutorial": "Let's consider a sequence $a_1, a_2, \\ldots, a_n$. Let $nxt_i$ be the smallest $j > i$ such that $a_j = a_i$, or $n+1$ if such $j$ does not exist. It is claimed that the characteristic of the sequence can be uniquely determined from the values of $nxt_1, nxt_2, \\ldots, nxt_n$. Let's write down the conditions on $nxt_i$ that we can obtain from the characteristic $r_1, r_2, \\ldots, r_n$: $nxt_n=n+1$. If $r_i=r_{i+1}$, then $nxt_i \\in [i+1, r_i]$, since the number $a_i$ appears on the subsegment $[i+1,r_i]$. If $r_i < r_{i+1}$, then $nxt_i = r_{i+1}$, since we need to extend the segment to the nearest occurrence of the number $a_i$. For each $i > r_1$, there exists $j$ such that $nxt_j=i$, since the first occurrence of each number is on the subsegment $[1, r_1]$. All $nxt_i \\le n$ are distinct, since each element can have at most one nearest equal element on its left. We want to construct the array $nxt$ that satisfies these conditions. We have some values of $nxt_i$ that we already know, as well as values of $nxt_i$ that should lie in the intervals $[i+1,r_{i+1}]$. Note that the left and right boundaries of these intervals are non-decreasing, so if condition 4 did not exist, we could greedily assign values to $nxt_i$, moving through the intervals in descending order and assigning the largest unused value of $nxt_i$ that lies in the interval. Let's fix $k$ as the number of intervals in which we will choose the number $n+1$. Obviously, it is more advantageous to place $n+1$ in the $k$ rightmost intervals, as all intervals in which $n+1$ can be placed are nested within each other. After that, we can greedily assign the largest possible values of $nxt_i$ to the intervals from right to left, thus obtaining an answer with the maximum number of $nxt_i \\in [r_1+1, n]$ for a given $k$. If we manage to cover all numbers from $[r_1+1, n]$, then we have found a suitable sequence $nxt$. Thus, we have a solution with $O(n^2)$ complexity: we iterate over $k$ and solve it greedily. Let's learn how to optimize it. Let's find the smallest $k$ for which there is an answer without considering condition 4. Note that as $k$ increases, the number of $nxt_i \\in [r_1+1, n]$ obtained by the greedy algorithm does not increase, so it is sufficient to run it for the minimum $k$ and check if condition 4 is satisfied for the obtained greedy algorithm answer for this $k$. After we find the array $nxt$, it is easy to obtain the array $a$ from it.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1889",
    "index": "A",
    "title": "Qingshan Loves Strings 2",
    "statement": "Qingshan has a string $s$ which only contains $0$ and $1$.\n\nA string $a$ of length $k$ is good if and only if\n\n- $a_i \\ne a_{k-i+1}$ for all $i=1,2,\\ldots,k$.\n\n{\\small For Div. 2 contestants, note that this condition is different from the condition in problem B.}\n\nFor example, $10$, $1010$, $111000$ are good, while $11$, $101$, $001$, $001100$ are not good.\n\nQingshan wants to make $s$ good. To do this, she can do the following operation \\textbf{at most} $300$ times (possibly, zero):\n\n- insert $01$ to any position of $s$ (getting a new $s$).\n\nPlease tell Qingshan if it is possible to make $s$ good. If it is possible, print a sequence of operations that makes $s$ good.",
    "tutorial": "First, there is no solution when the number of 0's and 1's are different. Otherwise, the construction follows: If the $s_1 \\ne s_n$ now, we can ignore $s_1$ and $s_n$, and consider $s_{2..n-1}$ as a new $s$. If $s$ is empty, the algorithm ends. Now $s_1=s_n$. If they are 1, insert 01 to the front; otherwise, insert 01 to the end. Look at this example: \"110010\" \"1001\" \"011001\" \"1100\" \"10\" \"\" This operation is actually equivalent to moving the last 1 to the front or moving the first 0 to the end. For example, in step 2 to 4 above, we succeed moving the last 1 to the front. So in the worst case, every character in the string are moved, and we need $n$ moves. Actually, we don't need $n$ moves but $n/2$ moves. Because for the 0 and 1 deleted in the same operation, at most one of them need to be moved. Time complexity $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nbool ok(std::string s) {\n  for (size_t i = 1; i < s.length(); ++i)\n    if (s[i] == s[i - 1])\n      return false;\n  return true;\n}\n\n\nstd::string s;\nvoid solve() {\n  int n; std::cin >> n;\n  std::cin >> s;\n  int cnt0 = 0, cnt1 = 0;\n  for (int i = 0; i < s.length(); ++i) {\n    cnt0 += s[i] == '0';\n    cnt1 += s[i] == '1';\n  }\n  if (cnt0 != cnt1) {\n    std::cout << -1 << std::endl;\n    return;\n  }\n  std::vector<int> z;\n  std::deque<char> q;\n  for (int i = 0; i < s.length(); ++i)\n    q.push_back(s[i]);\n  \n  int d = 0;\n  while (!q.empty()) {\n    if (q.front() == q.back()) {\n      if (q.front() == '0') {\n        q.push_back('0');\n        q.push_back('1');\n        z.push_back(n - d);\n      } else {\n        q.push_front('1');\n        q.push_front('0');\n        z.push_back(0 + d);\n      }\n      n += 2;\n    }\n    while (!q.empty() && q.front() != q.back()) {\n      q.pop_back();\n      q.pop_front();\n      ++d;\n    }\n  }\n\n  std::cout << z.size() << std::endl;\n  for (int i = 0; i < z.size(); ++i) {\n    std::cout << z[i];\n    if (i + 1 == z.size()) std::cout << std::endl;\n    else std::cout << \" \";\n  }\n}\n\nint main() {\n  int t;\n  std::cin >> t;\n  while (t--) solve();\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1889",
    "index": "B",
    "title": "Doremy's Connecting Plan",
    "statement": "Doremy lives in a country consisting of $n$ cities numbered from $1$ to $n$, with $a_i$ people living in the $i$-th city. It can be modeled as an undirected graph with $n$ nodes.\n\nInitially, there are no edges in the graph. Now Doremy wants to make the graph connected.\n\nTo do this, she can add an edge between $i$ and $j$ if\n\n$$ \\sum_{k \\in S} a_k \\ge i\\cdot j \\cdot c, $$\n\nwhere $S$ is the set of all the nodes that are currently in the same connected component of either $i$ or $j$, and $c$ is a given constant.\n\nCan Doremy make the graph connected?\n\nTwo nodes $(i, j)$ are in the same connected component if there exists a path from $i$ to $j$. A graph is connected if all its nodes are in the same connected component.",
    "tutorial": "First, we can just solve $c=1$. Because letting $a_i' = \\frac{a_i}{c}$ reduces $c\\ne 1$ to $c=1$. For convenience, let $s_i = \\sum a_j$, where $j$ is currently connected with $i$. Let's see if you can add an edge between $i$ and $j$ ($i \\ne 1, j \\ne 1$) right now, it means $s_i + s_j \\ge i \\cdot j \\ge i+j$ This actually implies at least one of $s_i \\ge i$ and $s_j \\ge j$ holds (otherwise $s_i + s_j < i + j$). WLOG, let $s_i \\ge i$ be true. Therefore $s_i + s_1 \\ge 1 \\cdot i$, which means you can add an edge between $1$ and $i$. Moreover, adding a new edge does not cause other edges that can be added to become unable to be added. So it's always good to add the edge between $1$ and $i$. Now we only need to decide the order. Consider this inequality $s_i + s_1 \\ge 1 \\cdot i$. You can see that larger $s_i - i$ is, faster node $i$ is able to be linked with $1$. So we can sort $i$ by $a_i-i$ in descending order, and that is the order we need. Time complexity $O(n \\log n)$. Bonus: Time complexity can be $O(n)$ based on this observation: If you link $(1,i)$, then any $j < i$ can be linked to $1$.",
    "code": "#include<bits/stdc++.h>\nusing i64 = long long;\nusing namespace std;\nconst int N = 5e5 + 7;\nint T, n, C, p[N]; i64 a[N];\nvoid solve () {\n\tcin >> n >> C;\n\tfor (int i = 1; i <= n; i ++) cin >> a[i];\n\tiota (p + 1, p + n + 1, 1);\n\tsort (p + 1, p + n + 1, [&] (const int &u, const int &v) {\n\t\treturn 1ll * u * C - a[u] < 1ll * v * C - a[v];\n\t});\n\ti64 now = a[1];\n\tfor (int i = 1, u; i <= n; i ++) {\n\t\tu = p[i];\n\t\tif (u == 1) continue;\n\t\tif (1ll * u * C > now + a[u]) return cout << \"No\\n\", void ();\n\t\tnow += a[u];\n\t}\n\treturn cout << \"Yes\\n\", void ();\n}\nint main () {\n\tios :: sync_with_stdio (false); cin.tie (0); cout.tie (0);\n\tcin >> T; while (T --) solve ();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1889",
    "index": "C1",
    "title": "Doremy's Drying Plan (Easy Version)",
    "statement": "\\textbf{The only differences between the two versions of this problem are the constraint on $k$, the time limit and the memory limit. You can make hacks only if all versions of the problem are solved.}\n\nDoremy lives in a rainy country consisting of $n$ cities numbered from $1$ to $n$.\n\nThe weather broadcast predicted the distribution of rain in the next $m$ days. In the $i$-th day, it will rain in the cities in the interval $[l_i, r_i]$. A city is called dry if it will never rain in that city in the next $m$ days.\n\nIt turns out that Doremy has a special power. She can choose $k$ days (in the easy version, $k = 2$), and during these days it will not rain. Doremy wants to calculate the maximum number of dry cities after using the special power.",
    "tutorial": "We consider a brute force solution first. At the beginning, we calculate number of intervals that cover position $i$ for each $i=1,2,\\ldots,n$ by prefix sum. Now we can know the number uncovered positions. Let it be $A$. Then we need to calculate the number of new uncovered position after removing two intervals. Let it be $B$. So the answer in the end is $A + \\max B$. For calculating $B$, let's enumerate two intervals $I_1,I_2$. If they have no intersection, $B$ is equal to the number of positions that are covered exactly once in interval $I_1$ and $I_2$; If they have intersection. Let the intersection be $J$ (It is an interval). $B$ is equal to the number of positions that are covered exactly once in interval $I_1$ and $I_2$ plus the number of positions that are covered exactly twice in interval $J$; The algorithm can be done in $O(n+m^2)$ time by prefix sum. For optimization, we should notice that: In the \"no intersection\" case, we can just simply pick two best intervals. In the \"intersection\" case, there are at most $n$ useful interval pairs. The proof and algorithm goes: for each position $i$, if it is covered by exactly $2$ intervals, then this interval pair is useful and may update the answer. Great, but for code implementation, how do we find those interval pairs? For each interval $[l,r]$, we consider it as two events (like difference and prefix sum): it appears at position $l$, and disappears at position $r+1$. That way, set or just array is able to handle. Time complexity $O(n+m)$.",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1889",
    "index": "C2",
    "title": "Doremy's Drying Plan (Hard Version)",
    "statement": "\\textbf{The only differences between the two versions of this problem are the constraint on $k$, the time limit and the memory limit. You can make hacks only if all versions of the problem are solved.}\n\nDoremy lives in a rainy country consisting of $n$ cities numbered from $1$ to $n$.\n\nThe weather broadcast predicted the distribution of rain in the next $m$ days. In the $i$-th day, it will rain in the cities in the interval $[l_i, r_i]$. A city is called dry if it will never rain in that city in the next $m$ days.\n\nIt turns out that Doremy has a special power. She can choose $k$ days, and during these days it will not rain. Doremy wants to calculate the maximum number of dry cities after using the special power.",
    "tutorial": "$k$ is bigger in this version. However, it is still small, which leads us to a DP approach. Let $dp_{i,j}$ be the number of uncovered positions in $[1,i]$, and the last uncovered position is $i$, and the number of deleted intervals is $j$. For transition, we need to get all the intervals that covers position $i$. We've mentioned this in the editorial of the easy version. Let's iterate the last uncovered position $t$, and calculate the number of intervals that need to be deleted in this transition. Let it be $d_t$ and it is the number of interval $[l,r]$ such that $t < l \\le i \\le r$. Check this for example: And the transition goes: $dp_{i,j} \\gets 1 + \\max_{t=0}^{i-1} dp_{t,j-d_t}$ The time complexity is $O(n^2k)$ now. We need to speed the transition up. Note that $d_t$ is increasing while $t$ is decreasing, and $d_t$ is at most $k$. It actually splits the transition interval $[0,i-1]$ into at most $k+1$ intervals $[s_0,s_1],[s_1+1,s_2],\\cdots,[s_{l-1} + 1,s_l]$ such that $0=s_0 \\le s_1 < s_2 < \\cdots < s_l = i - 1$ and for $t$ in the same interval, $d_t$ is the same. So the sparse table can be used for transition. Time complexity $O(nk^2)$. Memory complexity $O(kn\\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define debug(...) fprintf(stderr, __VA_ARGS__)\n#define LL long long\n\nconst int MX = 2e5 + 23;\nconst int INF = 1e9;\n\nvoid chkmax(int &x, int y) {\n  x = std::max(x, y);\n}\n\nstruct Interval {\n  int l, r;\n} I[MX];\n\nbool cmp(int x, int y) {\n  return I[x].l > I[y].l;\n}\n\nstd::vector<int> add[MX], del[MX];\nint n, m, k, ban[MX];\n\nint st[21][MX][18], lg[MX];\n\nint query(int d, int l, int r) {\n  int len = lg[r - l + 1];\n  return std::max(st[d][l][len], st[d][r - (1 << len) + 1][len]);\n}\n\nvoid change(int d, int p, int val) {\n  chkmax(st[d][p][0], val);\n  for (int i = 1; p - (1 << i) + 1 >= 0; ++i) {\n    st[d][p - (1 << i) + 1][i] = std::max(\n          st[d][p - (1 << i) + 1][i - 1],\n          st[d][p - (1 << (i - 1)) + 1][i - 1]);\n  }\n}\n\nvoid init() {\n  lg[0] = -1;\n  for (int i = 1; i <= n + 1; ++i)\n    lg[i] = lg[i - 1] + ((i & -i) == i); \n  for (int i = 1; i <= m; ++i) ban[i] = false;\n  for (int i = 1; i <= n + 1; ++i) {\n    add[i].clear();\n    del[i].clear();\n  }\n  for (int i = 0; i <= k; ++i)\n    for (int j = 0; j <= n; ++j)\n      for (int _k = 0; _k < 18; ++_k)\n        st[i][j][_k] = -INF;\n}\n\nvoid solve() {\n  scanf(\"%d%d%d\", &n, &m, &k);\n  init();\n  for (int i = 1; i <= m; ++i) {\n    int l, r;\n    scanf(\"%d%d\", &l, &r);\n    I[i] = (Interval){l, r};\n    add[l].push_back(i);\n    del[r + 1].push_back(i);\n  }\n  \n  std::vector<int> cur, tmp;\n\n  change(0, 0, 0);\n  \n  int uncover = 0, ans = 0;\n  int cnti = 0;\n  for (int i = 1; i <= n; ++i) {\n    for (auto j : add[i]) {\n      cur.push_back(j);\n      ++cnti;\n    }\n\n    for (auto j : del[i]) {\n      ban[j] = true;\n      --cnti;\n    }\n\n    if (cnti > k) {\n      for (int j = 0; j <= k; ++j)\n        change(j, i, -INF);\n      continue;\n    }\n\n    tmp.clear();\n    for (auto j : cur) {\n      if (!ban[j]) {\n        tmp.push_back(j);\n      }\n    }\n    cur = tmp;\n    std::sort(cur.begin(), cur.end(), cmp);\n    \n    if (cur.empty()) {\n      for (int j = 0; j <= k; ++j)\n        change(j, i, -INF);\n      ++uncover;\n      continue;\n    }\n    \n    if (I[cur[0]].l <= i - 1)\n      for (int g = 0; g <= k; ++g) {\n        int z = query(g, I[cur[0]].l, i - 1);\n        chkmax(ans, z + 1);\n        change(g, i, z + 1);\n      }\n    else {\n      for (int g = 0; g <= k; ++g) {\n        change(g, i, -INF);\n      }\n    }\n    int cp = I[cur[0]].l - 1;\n    \n\n    for (int j = 0; j < cur.size(); ++j) {\n      if (j + 1 != cur.size() && I[cur[j]].l == I[cur[j + 1]].l)\n        continue;\n      int np = (j + 1 == cur.size() ? 0 : I[cur[j + 1]].l);\n      for (int g = j + 1; g <= k; ++g) {\n        int z = query(g - (j + 1), np, cp);\n        chkmax(ans, z + 1);\n        change(g, i, z + 1);\n        // change(root[g], i, z + 1);\n      }\n      cp = np - 1;\n    }\n  }\n  printf(\"%d\\n\", ans + uncover);\n}\n\nint main() {\n  int t; scanf(\"%d\", &t);\n\n  while (t--) solve();\n  return 0;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1889",
    "index": "D",
    "title": "Game of Stacks",
    "statement": "You have $n$ stacks $r_1,r_2,\\ldots,r_n$. Each stack contains some positive integers ranging from $1$ to $n$.\n\nDefine the following functions:\n\n\\begin{verbatim}\nfunction init(pos):\nstacks := an array that contains n stacks r[1], r[2], ..., r[n]\nreturn get(stacks, pos)\n\nfunction get(stacks, pos):\nif stacks[pos] is empty:\nreturn pos\nelse:\nnew_pos := the top element of stacks[pos]\npop the top element of stacks[pos]\nreturn get(stacks, new_pos)\n\n\\end{verbatim}\n\nYou want to know the values returned by $init(1), init(2), \\ldots, init(n)$.\n\nNote that, during these calls, the stacks $r_1,r_2,\\ldots,r_n$ don't change, so the calls $init(1), init(2), \\ldots, init(n)$ are independent.",
    "tutorial": "Let's first consider an easy version of the problem: what if there is only one element in each stack? Let $p_i$ be the element in stack $i$. If we link $i \\to p_i$, these edges will form several directed pseudo trees. For each pseudo tree, there is a cycle. It's not hard to find that those cycles actually can be ignored, because if we go on the cycle, we will come back to the first node on the cycle and the cycle will be eliminated. After deleting (the edges) on the cycle, there are only trees left. Thus the root of each tree is the answer of nodes on the tree. When it comes back to the original problem, similarly, let $p_i$ be the top element of stack $i$. The rest are the same - cycles can be eliminated. In this case, we should run cycle elimination process many times until there is no cycle in the graph. Time complexity $O(n+\\sum k)$.",
    "code": "#include<stack>\n#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\nusing namespace std;\nconst int maxn=100005;\nstack<int>s[maxn];\nint re[maxn],st[maxn],vis[maxn],tp;\nint dfs(int u){\n    if(re[u])\n        return re[u];\n    if(s[u].empty())\n        return u;\n    if(vis[u]){\n        st[tp+1]=0;\n        while(st[tp+1]!=u){\n            s[st[tp]].pop();\n            vis[st[tp]]=0;\n            --tp;\n        }\n        return dfs(u);\n    }\n    st[vis[u]=++tp]=u;\n    return dfs(s[u].top());\n}\nint main(){\n    int n;scanf(\"%d\",&n);\n    for(int i=1;i<=n;++i){\n        int k;scanf(\"%d\",&k);\n        while(k--){\n            int c;scanf(\"%d\",&c);\n            s[i].push(c);\n        }\n    }\n    for(int i=1;i<=n;++i){\n        tp=0;int ok=dfs(i);\n        for(int j=1;j<=tp;++j)\n            re[st[j]]=ok;\n        printf(\"%d%c\",ok,\" \\n\"[i==n]);\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1889",
    "index": "E",
    "title": "Doremy's Swapping Trees",
    "statement": "Consider two undirected graphs $G_1$ and $G_2$. Every node in $G_1$ and in $G_2$ has a label. Doremy calls $G_1$ and $G_2$ similar if and only if:\n\n- The labels in $G_1$ are distinct, and the labels in $G_2$ are distinct.\n- The set $S$ of labels in $G_1$ coincides with the set of labels in $G_2$.\n- For every pair of two distinct labels $u$ and $v$ in $S$, the corresponding nodes are in the same connected component in $G_1$ if and only if they are in the same connected component in $G_2$.\n\nNow Doremy gives you two trees $T_1$ and $T_2$ with $n$ nodes, labeled from $1$ to $n$. You can do the following operation any number of times:\n\n- Choose an edge set $E_1$ from $T_1$ and an edge set $E_2$ from $T_2$, such that $\\overline{E_1}$ and $\\overline{E_2}$ are similar. Here $\\overline{E}$ represents the graph which is given by only reserving the edge set $E$ from $T$ (i.e., the edge-induced subgraph). In other words, $\\overline{E}$ is obtained from $T$ by removing all edges not included in $E$ and further removing all isolated vertices.\n- Swap the edge set $E_1$ in $T_1$ with the edge set $E_2$ in $T_2$.\n\nNow Doremy is wondering how many distinct $T_1$ you can get after any number of operations. Can you help her find the answer? Output the answer modulo $10^9+7$.",
    "tutorial": "We can construct a new directed graph, where we can consider each edge in $T_1$ and $T_2$ as a node. Let the node representing the edge $(u,v)$ in tree $T_i$ be $N(u,v,T_i)$. For each node $N(u,v,T_1)$, let the simple path between $u$ and $v$ in $T_2$ be $(u_1,v_1),\\dots,(u_m,v_m)$, and for all $1\\le i\\le m$ we add an edge from $N(T_1,u,v)$ to $N(T_2,u_i,v_i)$ in the new graph. And for each node $N(u,v,T_2)$, let the simple path between $u$ and $v$ in $T_1$ be $(u_1,v_1),\\dots,(u_m,v_m)$, and for all $1\\le i\\le m$ we add an edge from $N(T_2,u,v)$ to $N(T_1,u_i,v_i)$ in the new graph. Then we calculate the number of strongly connected components with the size bigger than $2$ in the new graph. If it is $t$, the answer is $2^t$. To reduce the time complexity to $O(n\\log n)$, we need to build the new graph with binary lifting or heavy-light decomposition or centroid decomposition or something like those. More specifically, we just build the data structure as normal, but replace the \"modify\" operation with \"add edge\" operation, which allows us to add edges from one node to a range of nodes with low time complexity. Proof: it is obviously that the edge set we choose in each operation must be a closed subgraph in the new graph. And at the same time, it can be easily proved that every closed subgraph in the new graph is a valid edge set. The another thing we need to prove is that the set of valid closed subgraph won't change after an operation. We can easily prove this by the relationship between the number of edges and the number of nodes in a tree.",
    "code": "#include<vector>\n#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\nusing namespace std;\nconst int maxn=100005;\nstruct Edge{\n    int v,nt;\n    Edge(int v=0,int nt=0):\n        v(v),nt(nt){}\n}eG[maxn*160];\nint hdG[maxn*40],numG;\nvoid qwqG(int u,int v){\n    eG[++numG]=Edge(v,hdG[u]);hdG[u]=numG;\n}\nint tot;\nstruct AnTree{\n    struct Edge{\n        int v,nt;\n        Edge(int v=0,int nt=0):\n            v(v),nt(nt){}\n    }e[maxn*2];\n    int hd[maxn],num;\n    void qwq(int u,int v){\n        e[++num]=Edge(v,hd[u]),hd[u]=num;\n    }\n    int n;\n    void init(int n){\n        this->n=n;\n        for(int i=1;i<n;++i){\n            int u,v;\n            scanf(\"%d%d\",&u,&v);\n            qwq(u,v);qwq(v,u);\n        }\n    }\n    int pa[maxn][20],id[maxn][20],dp[maxn];\n    void dfs(int u,int p){\n        if(p==0)dp[u]=0;\n        for(int i=1;(1<<i)<=dp[u];++i)\n            pa[u][i]=pa[pa[u][i-1]][i-1];\n        for(int i=hd[u];i;i=e[i].nt){\n            int v=e[i].v;\n            if(v==p)continue;\n            dp[v]=dp[u]+1;\n            pa[v][0]=u;\n            id[v][0]=++tot;\n            dfs(v,u);\n        }\n    }\n    int getid(int u,int d){\n        int&re=id[u][d];\n        if(re)return re;\n        re=++tot;\n        qwqG(re,getid(u,d-1));\n        qwqG(re,getid(pa[u][d-1],d-1));\n        return re;\n    }\n    void link(int x,int u,int v){\n        if(dp[u]<dp[v])swap(u,v);\n        for(int t=dp[u]-dp[v],cn=0;t;t>>=1,++cn)\n            if(t&1)qwqG(x,getid(u,cn)),u=pa[u][cn];\n        if(u==v)return;\n        int t=0;while(dp[u]>>t)++t;\n        while(t--){\n            if(pa[u][t]!=pa[v][t]){\n                qwqG(x,getid(u,t));\n                qwqG(x,getid(v,t));\n                u=pa[u][t];v=pa[v][t];\n            }\n        }\n        qwqG(x,getid(u,0));\n        qwqG(x,getid(v,0));\n    }\n    void erase(void){\n        for(int i=1;i<=n;++i){\n            hd[i]=0,dp[i]=0;int j=0;\n            while(pa[i][j])pa[i][j++]=0;\n            j=0;while(id[i][j])id[i][j++]=0;\n        }\n        num=0;\n    }\n    int parent(int u){\n        return pa[u][0];\n    }\n    int identity(int u){\n        return id[u][0];\n    }\n}T1,T2;\nint dfn[maxn*40],low[maxn*40],cnt;\nint st[maxn*40],tp,in[maxn*40];\nint scc[maxn*40],scn;\nint vis[maxn*40];\nvoid tarjan(int u){\n    dfn[u]=low[u]=++cnt;\n    in[st[++tp]=u]=true;\n    for(int i=hdG[u];i;i=eG[i].nt){\n        int v=eG[i].v;\n        if(!dfn[v]){\n            tarjan(v);\n            low[u]=min(low[u],low[v]);\n        }\n        else if(in[v])\n            low[u]=min(low[u],dfn[v]);\n    }\n    if(dfn[u]==low[u]){\n        ++scn;\n        st[tp+1]=0;\n        while(st[tp+1]!=u){\n            in[st[tp]]=false;\n            scc[st[tp]]=scn;\n            --tp;\n        }\n    }\n}\nconst int mod=1e9+7;\nint power(int a,int x){\n    int re=1;\n    while(x){\n        if(x&1)re=1ll*re*a%mod;\n        a=1ll*a*a%mod,x>>=1;\n    }\n    return re;\n}\nvoid solve(void){\n    int n;scanf(\"%d\",&n);\n    T1.init(n);T2.init(n);\n    T1.dfs(1,0);T2.dfs(1,0);\n    int rec=tot;\n    for(int i=2;i<=n;++i){\n        T2.link(T1.identity(i),i,T1.parent(i));\n        T1.link(T2.identity(i),i,T2.parent(i));\n    }\n    for(int i=1;i<=tot;++i)\n        if(!dfn[i])tarjan(i);\n    for(int i=1;i<=rec;++i)\n        ++vis[scc[i]];\n    int ANS=0;\n    for(int i=1;i<=scn;++i){\n        if(vis[i])++ANS;\n        vis[i]=0;\n    }\n    for(int u=1;u<=rec;++u){\n        if(eG[hdG[u]].nt==0){\n            int v=eG[hdG[u]].v;\n            if(u<v&&eG[hdG[v]].nt==0){\n                if(eG[hdG[v]].v==u){\n                    --ANS;\n                }\n            }\n        }\n    }\n    ANS=power(2,ANS);\n    printf(\"%d\\n\",ANS);\n    for(int i=1;i<=tot;++i){\n        hdG[i]=0;\n        dfn[i]=low[i]=scc[i]=0;\n    }\n    tot=cnt=scn=numG=0;\n    T1.erase();T2.erase();\n}\nint main(){\n    // freopen(\"test\",\"r\",stdin);\n    // freopen(\"out\",\"w\",stdout);\n    int T;scanf(\"%d\",&T);\n    while(T--)solve();\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1889",
    "index": "F",
    "title": "Doremy's Average Tree",
    "statement": "Doremy has a rooted tree of size $n$ whose root is vertex $r$. Initially there is a number $w_i$ written on vertex $i$. Doremy can use her power to perform this operation \\textbf{at most} $k$ times:\n\n- Choose a vertex $x$ ($1 \\leq x \\leq n$).\n- Let $s = \\frac{1}{|T|}\\sum_{i \\in T} w_i$ where $T$ is the set of all vertices in $x$'s subtree.\n- For all $i \\in T$, assign $w_i := s$.\n\nDoremy wants to know what is the lexicographically smallest$^\\dagger$ array $w$ after performing all the operations. Can you help her?\n\nIf there are multiple answers, you may output any one.\n\n$^\\dagger$ For arrays $a$ and $b$ both of length $n$, $a$ is lexicographically smaller than $b$ if and only if there exist an index $i$ ($1 \\leq i \\le n$) such that $a_i < b_i$ and for all indices $j$ such that $j<i$, $a_j=b_j$ is satisfied.",
    "tutorial": "Let $f_{i,j}$ be the array with the smallest lexicographical order if you do at most $j$ operations in the subtree of $i$ (only consisting of the elements in the subtree of $i$). Let $g_{i,j}$ be the first position $k$ where $f_{i,j}[k]$ is different from $f_{i,j-1}[k]$. To get the answer, we just need to calculate $g_{i,j}$ which gives us enough information to compare the lexicographical order between two choice. At the same time we need to record the first number of $f_{i,j}$ (let the number be $t$) and its label, and the first number in $f_{i,j}$ such that it is different from $t$ and its label, which gives us enough information to decide whether to do an operation on $i$. The time complexity is $O(nk)$.",
    "code": "#include<cstdio>\n#include<cstring>\n#include<iostream>\n#include<algorithm>\n#define ch() getchar()\n#define pc(x) putchar(x)\nusing namespace std;\ntemplate<typename T>void read(T&x){\n\tstatic char c;static int f;\n\tfor(f=1,c=ch();c<'0'||c>'9';c=ch())if(c=='-')f=-f;\n\tfor(x=0;c>='0'&&c<='9';c=ch()){x=x*10+(c&15);}x*=f;\n}\ntemplate<typename T>void write(T x){\n\tstatic char q[64];int cnt=0;\n\tif(x==0)return pc('0'),void();\n\tif(x<0)pc('-'),x=-x;\n\twhile(x)q[cnt++]=x%10+'0',x/=10;\n\twhile(cnt--)pc(q[cnt]);\n}\nlong long gcd(long long a,long long b){\n\tif(b==0)return a;\n\treturn gcd(b,a%b);\n}\nstruct Frac{\n\tlong long a;\n\tint b;// a/b\n\tFrac(long long a=0,int b=1):\n\t\ta(a),b(b){}\n\tbool operator < (const Frac o)const{\n\t\treturn a*o.b<o.a*b;\n\t}\n\tbool operator > (const Frac o)const{\n\t\treturn a*o.b>o.a*b;\n\t}\n\tbool operator == (const Frac o)const{\n\t\treturn a*o.b==o.a*b;\n\t}\n\tvoid output(){\n\t\tprintf(\"%lld/%d\",a,b);\n\t}\n};\nconst int inf=0x3f3f3f3f;\nstruct Val{\n\tint p1,p2;Frac v1,v2;\n\tVal(int p1=inf,int p2=inf,Frac v1=Frac(),Frac v2=Frac()):\n\t\tp1(p1),p2(p2),v1(v1),v2(v2){}\n\tvoid output(void){\n\t\tprintf(\"%d : \",p1);v1.output();puts(\"\");\n\t\tprintf(\"%d : \",p2);v2.output();puts(\"\\n\");\n\t}\n};\nVal Comb(Val A,Val B){\n\tif(A.p1>B.p1)swap(A,B);\n\tif(B.v1==A.v1)\n\t\treturn Val(A.p1,A.p2<B.p2?A.p2:B.p2,A.v1,A.p2<B.p2?A.v2:B.v2);\n\treturn Val(A.p1,A.p2<B.p1?A.p2:B.p1,A.v1,A.p2<B.p1?A.v2:B.v1);\n}\nconst int maxn=10005,maxk=505;\nstruct Edge{\n\tint v,nt;\n\tEdge(int v=0,int nt=0):\n\t\tv(v),nt(nt){}\n}e[maxn*2];\nint hd[maxn],num;\nvoid qwq(int u,int v){\n\te[++num]=Edge(v,hd[u]),hd[u]=num;\n}\nlong long sm[maxn];int sz[maxn];\nint dp[maxn][maxk],wp[maxn][maxk],k,n;\nVal va[maxn][maxk];\nvoid Merge(int x,int l,int r,int L,int R){\n\twp[x][0]=0;\n\tva[x][0]=Comb(va[l][0],va[r][0]);\n\tL=min(L,k);R=min(R,k);\n\tint up=min(L+R,k);\n\tfor(int i=1;i<=up;++i){\n\t\tint t=wp[x][i]=min(L,i),cl=inf,cr=inf;\n\t\twhile(t>0&&i-t<R){\n\t\t\tcl=min(cl,dp[l][t]);--t;\n\t\t\tcr=min(cr,dp[r][i-t]);\n\t\t\tif(cr<cl)wp[x][i]=t,cl=cr=inf;\n\t\t}\n\t\tt=wp[x][i-1];cl=cr=inf;\n\t\tif(wp[x][i-1]<wp[x][i]){\n\t\t\twhile(t<wp[x][i])cl=min(cl,dp[l][++t]);\n\t\t\tdp[x][i]=cl;\n\t\t}\n\t\telse{\n\t\t\twhile(i-t-1<i-wp[x][i])cr=min(cr,dp[r][i-(t--)]);\n\t\t\tdp[x][i]=cr;\n\t\t}\n\t\tva[x][i]=Comb(va[l][wp[x][i]],va[r][i-wp[x][i]]);\n\t}\n}\nint MN[maxn],rsz[maxn];\nlong long val[maxn];\nvoid dfs(int u,int p){\n\tint l=0,fa=0;sm[u]=val[u];\n\tsz[u]=0;rsz[u]=1;MN[u]=0;\n\tfor(int i=hd[u];i;i=e[i].nt){\n\t\tint v=e[i].v;\n\t\tif(v==p){fa=i;continue;}dfs(v,u);\n\t\tMerge(i,i^1,l,sz[v],sz[u]);\n\t\tsm[u]+=sm[v],sz[u]+=sz[v];\n\t\trsz[u]+=rsz[v];\n\t\tl=i;\n\t}\n\tif(sz[u]==0){\n\t\t++sz[u];MN[u]=1;\n\t\tva[fa][0]=va[fa][1]=Val(u,inf,val[u]);\n\t\tdp[fa][1]=inf;\n\t}\n\telse{\n\t\tint up=min(sz[u],k);\n\t\tfor(int i=0;i<=up;++i)\n\t\t\tva[fa][i]=Comb(va[l][i],Val(u,inf,val[u])),dp[fa][i]=dp[l][i];\n\t\tFrac tmp(sm[u],rsz[u]);\n\t\tfor(int i=1;i<=up;++i)\n\t\t\tif(va[fa][i].v1>tmp||(va[fa][i].v1==tmp&&va[fa][i].v2>tmp))\n\t\t\t\tva[fa][i]=Val(va[fa][i].p1,inf,tmp),MN[u]=i;\n\t\tif(MN[u]){\n\t\t\tif(va[fa][0].v1==va[fa][1].v1)\n\t\t\t\tdp[fa][1]=va[fa][0].p2;\n\t\t\telse\n\t\t\t\tdp[fa][1]=va[fa][0].p1;\n\t\t\tfor(int i=2;i<=MN[u];++i)\n\t\t\t\tdp[fa][i]=inf;\n\t\t\tif(MN[u]<up){\n\t\t\t\tif(va[fa][MN[u]].v1==va[fa][MN[u]+1].v1)\n\t\t\t\t\tdp[fa][MN[u]+1]=va[fa][MN[u]+1].p2;\n\t\t\t\telse\n\t\t\t\t\tdp[fa][MN[u]+1]=va[fa][MN[u]+1].p1;\n\t\t\t}\n\t\t}\n\t}/*\n\tint up=min(sz[u],k);\n\tprintf(\"%d MN:%d\\n\",u,MN[u]);\n\tfor(int i=1;i<=up;++i)\n\t\tprintf(\"dp %d = %d\\n\",i,dp[fa][i]);*/\n}\nint st[maxn],ts;\nint que[maxn],cnt;\nvoid solve(int u,int p,int sk){\n\tif(sk==0)return;sk=min(sk,sz[u]);\n\tif(sk<=MN[u])return st[++ts]=u,void();\n\tint tnc=cnt;\n\tfor(int i=hd[u];i;i=e[i].nt){\n\t\tint v=e[i].v;\n\t\tif(v==p)continue;\n\t\tque[cnt++]=i;\n\t}\n\tfor(int j=cnt-1;j>=tnc;--j){\n\t\tint i=que[j];\n\t\tsolve(e[i].v,u,wp[i][sk]);\n\t\tsk-=wp[i][sk];\n\t}\n}\nvoid imple(void){\n\tint r;\n\tread(n),read(r),read(k);\n\tfor(int i=1;i<=n;++i)\n\t\tread(val[i]);\n\tqwq(r,0);\n\tfor(int i=1;i<n;++i){\n\t\tint u,v;read(u),read(v);\n\t\tqwq(u,v);qwq(v,u);\n\t}\n\tdfs(r,0);\n\tsolve(r,0,k);\n\tprintf(\"%d\\n\",ts);\n\tfor(int i=1;i<=ts;++i)\n\t\tprintf(\"%d%c\",st[i],\" \\n\"[i==ts]);\n\tfor(int i=0;i<=n;++i)hd[i]=0;\n\tnum=cnt=ts=0;\n}\nint main(){\n\t// freopen(\"test\",\"r\",stdin);\n\tint T;read(T);\n\twhile(T--)imple();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1890",
    "index": "A",
    "title": "Doremy's Paint 3",
    "statement": "An array $b_1, b_2, \\ldots, b_n$ of positive integers is good if all the sums of two adjacent elements are equal to the same value. More formally, the array is good if there exists a $k$ such that $b_1 + b_2 = b_2 + b_3 = \\ldots = b_{n-1} + b_n = k$.\n\nDoremy has an array $a$ of length $n$. Now Doremy can permute its elements (change their order) however she wants. Determine if she can make the array good.",
    "tutorial": "Statement says $b_1 + b_2 = b_2 + b_3 = \\ldots = b_{n-1} + b_n = k$. Let's write it as $b_i + b_{i+1} = b_{i+1} + b_{i+2}$. This is just $b_i = b_{i+2}$, which means the positions with the same parity should contain same value. $b_1 = b_3 = b_5 = \\cdots \\\\ b_2 = b_4 = b_6 = \\cdots$ We know that there are $\\lceil \\frac{n}{2} \\rceil$ odd numbers and $\\lfloor \\frac{n}{2}\\rfloor$ even numbers in $[1,n]$. Therefore, if and only if we can find $\\lfloor \\frac{n}{2}\\rfloor$ same numbers, and the remaining are also the same numbers, the answer is YES. All cases can be classified into these categories: All numbers are the same, like $[3,3,3,3,3,3]$. The answer is YES. There are two different numbers, like $[1,2,1,2,1]$. The answer is YES if and only if one of the number appears exactly $\\lfloor \\frac{n}{2}\\rfloor$ times. For example $[1,2,1,2,1]$ and $[2,3,2,3]$ are YES while $[1,1,1,2]$ and $[3,3,3,3,4,4]$ is NO. There are three or more different numbers, like $[1,2,3,2,3]$. The answer is NO. Time complexity $O(n)$.",
    "code": "// Time complexity O(nlogn) because of map\n#include <bits/stdc++.h>\n\nconst int MX = 100 + 5;\n\nint main() {\n  int t;\n  std::cin >> t;\n  while (t--) {\n    int n;\n    std::cin >> n;\n    std::map<int ,int> occ;\n    for (int i = 1; i <= n; ++i) {\n      int x;\n      std::cin >> x;\n      occ[x]++;\n    }\n    if (occ.size() >= 3) puts(\"No\");\n    else {\n      if (std::abs(occ.begin()->second - occ.rbegin()->second) <= 1) {\n        puts(\"Yes\");\n      } else {\n        puts(\"No\");\n      }\n    }\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1890",
    "index": "B",
    "title": "Qingshan Loves Strings",
    "statement": "Qingshan has a string $s$, while Daniel has a string $t$. Both strings only contain $0$ and $1$.\n\nA string $a$ of length $k$ is good if and only if\n\n- $a_i \\ne a_{i+1}$ for all $i=1,2,\\ldots,k-1$.\n\nFor example, $1$, $101$, $0101$ are good, while $11$, $1001$, $001100$ are not good.\n\nQingshan wants to make $s$ good. To do this, she can do the following operation any number of times (possibly, zero):\n\n- insert $t$ to any position of $s$ (getting a new $s$).\n\nPlease tell Qingshan if it is possible to make $s$ good.",
    "tutorial": "There are three circumstances where the answer is \"Yes\". $s$ is good initially. $t$ is good, $t=$ \"10...01\", and there is no substring 11 in $s$. $t$ is good, $t=$ \"01...10\", and there is no substring 00 in $s$.",
    "code": "#include <bits/stdc++.h>\n\nbool ok(std::string s) {\n  for (size_t i = 1; i < s.length(); ++i)\n    if (s[i] == s[i - 1])\n      return false;\n  return true;\n}\n\nvoid solve() {\n  std::string s, t;\n  int l1, l2;\n  std::cin >> l1 >> l2;\n  std::cin >> s >> t;\n  if (ok(s)) {\n    std::cout << \"Yes\" << std::endl;\n    return;\n  }\n\n  if (!ok(t) || *t.begin() != *t.rbegin()) {\n    std::cout << \"No\" << std::endl;\n    return;\n  }\n\n  int zz = 0, oo = 0;\n  for (size_t i = 1; i < s.length(); ++i) {\n    if (s[i] == s[i - 1]) {\n      if (s[i] == '0') zz = true;\n      if (s[i] == '1') oo = true;\n    }\n  }\n\n  if (zz && t[0] == '0') {\n    std::cout << \"No\" << std::endl;\n    return;\n  }\n  if (oo && t[0] == '1') {\n    std::cout << \"No\" << std::endl;\n    return;\n  }  \n\n  std::cout << \"Yes\" << std::endl;\n  return;\n}\n\nint main() {\n  int t;\n  std::cin >> t;\n  while (t--) solve();\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1891",
    "index": "A",
    "title": "Sorting with Twos",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$. In one operation, you do the following:\n\n- Choose a non-negative integer $m$, such that $2^m \\leq n$.\n- Subtract $1$ from $a_i$ for all integers $i$, such that $1 \\leq i \\leq 2^m$.\n\nCan you sort the array in non-decreasing order by performing some number (possibly zero) of operations?\n\nAn array is considered non-decreasing if $a_i \\leq a_{i + 1}$ for all integers $i$ such that $1 \\leq i \\leq n - 1$.",
    "tutorial": "Look at the difference array $b$. $b_i$ = $a_{i + 1} - a_{i}$ for each $i < n$. If array is sorted, its difference array has all of its elements non-negative. And operation is adding $1$ to $b_i$ if $i$ is a power of $2$. So look at difference array. If there is such $i$ that $i$ is not a power of $2$ and $b_i < 0$ then answer is <<NO>>. Else answer is <<YES>>. Time complexity: $O(n)$.",
    "tags": [
      "constructive algorithms",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1891",
    "index": "B",
    "title": "Deja Vu",
    "statement": "You are given an array $a$ of length $n$, consisting of positive integers, and an array $x$ of length $q$, also consisting of positive integers.\n\nThere are $q$ modification. On the $i$-th modification ($1 \\leq i \\leq q$), for each $j$ ($1 \\leq j \\leq n$), such that $a_j$ is divisible by $2^{x_i}$, you add $2^{x_i-1}$ to $a_j$. \\textbf{Note that} $x_i$ ($1 \\leq x_i \\leq 30$) is \\textbf{a positive integer not exceeding 30}.\n\nAfter \\textbf{all} modification queries, you need to output the final array.",
    "tutorial": "Let a number be divisible by $2^x$. Then after applying the operation it is no longer divisible by $2^x$. From this we can conclude that if we apply the operation $x_i$, and there is such an operation $j<i$ that $x_j < x_i$, then the operation $x_i$ does not change the array. So, it is useless and can be simply not processed. Then we will maintain the minimum of the processed $x$. If the new operation is smaller than the minimum processed one, we will process the operation and update it. Otherwise we just won't do anything. Since the minimum processed will decrease at most $30$ times, the time complexity is $O(30 \\cdot n)$.",
    "tags": [
      "brute force",
      "math",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1891",
    "index": "C",
    "title": "Smilo and Monsters",
    "statement": "A boy called Smilo is playing a new game! In the game, there are $n$ hordes of monsters, and the $i$-th horde contains $a_i$ monsters. The goal of the game is to destroy all the monsters. To do this, you have two types of attacks and a combo counter $x$, initially set to $0$:\n\n- The first type: you choose a number $i$ from $1$ to $n$, such that there is at least one monster left in the horde with the number $i$. Then, you kill one monster from horde number $i$, and the combo counter $x$ increases by $1$.\n- The second type: you choose a number $i$ from $1$ to $n$, such that there are at least $x$ monsters left in the horde with number $i$. Then, you use an ultimate attack and kill $x$ monsters from the horde with number $i$. After that, $x$ is reset to zero.\n\nYour task is to destroy all of the monsters, meaning that there should be no monsters left in any of the hordes. Smilo wants to win as quickly as possible, so he wants to the minimum number of attacks required to win the game.",
    "tutorial": "Note that if the second operation were free, we would need $\\lceil \\frac{sum}{2} \\rceil$ operations to get rid of all the monsters. Indeed, when we kill one monster, we can kill a second monster for free with a second operation. But the second operation is not free. So we need to use the second operation as little as possible. To do this, we need to apply ultimates (second attack) on the current largest horde by number of monsters, when the combo counter reaches the size of the largest horde. And we apply the first attack on the smallest hordes. This is so because the combo counter allows us to defeat $\\lceil \\frac{sum}{2} \\rceil$ monsters. But since we can't apply this operation on several hordes at once, we need to keep the number of hordes on which we apply these attacks of the second type as small as possible. Then we can use the greedy algorithm described above. Formally, we need to keep a sorted array and store two pointers: pointer $i$ - to the smallest horde, $j$ - to the largest horde. Until $i$ is equal to $j$: if after destroying all horde $i$ we can't kill horde $j$ with ultimates, we destroy horde $i$, increase pointer $i$ by $1$ and increase combo counter $x$ by $a$[$i$]. Otherwise, hit the horde $i$ so many times that the combo counter $x$ becomes $a$[$j$]. Then apply a second attack on horde $j$, reduce horde $j$'s counter by $1$, reduce $a$[$i$], and nullify the combo counter. When $i$ becomes equal to $j$, you just need to apply the first attack the right number of times to finish with ultimates (or not if $a$[$i$] $=$ $1$). Total complexity $O$($nlogn$).",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1891",
    "index": "D",
    "title": "Suspicious logarithms",
    "statement": "Let $f$($x$) be the floor of the binary logarithm of $x$. In other words, $f$($x$) is largest non-negative integer $y$, such that $2^y$ does not exceed $x$.\n\nLet $g$($x$) be the floor of the logarithm of $x$ with base $f$($x$). In other words, $g$($x$) is the largest non-negative integer $z$, such that ${f(x)}^{z}$ does not exceed $x$.\n\nYou are given $q$ queries. The $i$-th query consists of two integers $l_i$ and $r_i$. The answer to the query is the sum of $g$($k$) across all integers $k$, such that $l_i \\leq k \\leq r_i$. Since the answers might be large, print them modulo ${10^9 + 7}$.",
    "tutorial": "First, let us estimate the number of such $i$ that $g(i) \\neq g(i+1)$. This can happen if $f(i) \\neq f(i+1)$, but it happens rarely (about $log n$ times). And if f(i) is equal, we can see that $f(i) \\geq 2$ for any $4 \\leq i$, and on a segment with equal $f(i)$ transitions will be $O(log n)$, where $n$ is the length of the segment. That is, there are $O(log n)$ segments with equal $f(i)$, and on each segment there are at most $O(log n)$ transitions. Then there are a total of $O({log}^{2} {C})$ transitions, where $C$ is the maximum value of $i$ in the problem. In fact, in reality, there are even fewer transitions - something like $60$. Now we can suppose all such $i$ that $g(i) \\neq g(i+1)$, and by passing over them we can consider the sum of $g(i)$ for all $i \\leq r$. Or you can write a binary search and read the answer even faster.",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1891",
    "index": "E",
    "title": "Brukhovich and Exams",
    "statement": "The boy Smilo is learning algorithms with a teacher named Brukhovich.\n\nOver the course of the year, Brukhovich will administer $n$ exams. For each exam, its difficulty $a_i$ is known, which is a non-negative integer.\n\nSmilo doesn't like when the greatest common divisor of the difficulties of two consecutive exams is equal to $1$. Therefore, he considers the sadness of the academic year to be the number of such pairs of exams. More formally, the sadness is the number of indices $i$ ($1 \\leq i \\leq n - 1$) such that $gcd(a_i, a_{i+1}) = 1$, where $gcd(x, y)$ is the greatest common divisor of integers $x$ and $y$.\n\nBrukhovich wants to minimize the sadness of the year of Smilo. To do this, he can set the difficulty of any exam to $0$. However, Brukhovich doesn't want to make his students' lives too easy. Therefore, he will perform this action no more than $k$ times.\n\nHelp Smilo determine the minimum sadness that Brukhovich can achieve if he performs no more than $k$ operations.\n\nAs a reminder, the greatest common divisor (GCD) of two non-negative integers $x$ and $y$ is the maximum integer that is a divisor of both $x$ and $y$ and is denoted as $gcd(x, y)$. In particular, $gcd(x, 0) = gcd(0, x) = x$ for any non-negative integer $x$.",
    "tutorial": "Consider that every $a_i \\neq 1$. Then, we can split our array into blocks in which each adjacent element has $gcd = 1$. For example, consider $a =$[$2$, $3$, $4$, $5$, $5$, $6$, $7$], then the array divides into two blocks: [$2$, $3$, $4$, $5$] and [$5$, $6$, $7$]. Notice that if the lenght of a block is $len$, then it gives $len - 1$ sadness to Smilo. Also notice that we can reduce sadness by two using only one operation: we can, for instance, nullify the second element in a block (if the length of the block is more than two). For illustration, if we nullify the second element in block [$5$, $6$, $7$], the sadness will decrease by two, and the block will be splitted into [$5$], [$0$], [$7$] with zero sadness in each block. If the size of a block is exactly two, we can decrease the sadness by one using one operation. Then notice that while we are having at least one block, which lenght is at least $3$, we can decrease sadness by $2$. Otherwise, we can decrease sadness at most by $1$. Unfortunately, we have ones in our array. In this case our algorithm won't work, since in order to make pair [$1$, $1$] good, we will have to nullify both elements. Then let's slightly modify the algorithm: we will put consecutive ones in different blocks. For example, if $a =$[$1$, $1$, $1$, $3$, $4$, $4$, $1$], then our array will be splitted into 4 blocks: [$1$, $1$, $1$], [$3$, $4$], [$4$], [$1$]. Now notice that if the block of ones is located at the edge of our array, then the sadness will decrease by $len$ using $len$ operations ($len$ is the lenght of the block). Otherwise, sadness will decrease by $len + 1$ using $len$ operations. The final solution becomes obvious. Firstly, we should nullify the elements in non-ones blocks (if possible) in order to decrease sadness by $2$ each operation. Then we need to nullify whole blocks of ones (which are not on the edge of the array) in ascending order of lenght. And finally, we need to use remaining operations to reduce sadness by one each operation. The complexity is $O$($nlogn$).",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1891",
    "index": "F",
    "title": "A Growing Tree",
    "statement": "You are given a rooted tree with the root at vertex $1$, initially consisting of a single vertex. Each vertex has a numerical value, initially set to $0$. There are also $q$ queries of two types:\n\n- The first type: add a child vertex with the number $sz + 1$ to vertex $v$, where $sz$ is the current size of the tree. The numerical value of the new vertex will be $0$.\n- The second type: add $x$ to the numerical values of all vertices in the subtree of vertex $v$.\n\nAfter all queries, output the numerical value of all of the vertices in the final tree.",
    "tutorial": "Let's parse all the queries and build the tree. We can easily support subtree addition queries using segment tree on Euler tour of the tree. And when we add new vertex, we just need to set its value to zero. How to do it? You can get the value in this vertex now (by get query from the segment tree), let it be $x$. Then you add $-x$ to its value. You can also use Fenwick tree to handle range add point get queries. Time complexity: $O(q log q)$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1893",
    "index": "A",
    "title": "Anonymous Informant",
    "statement": "You are given an array $b_1, b_2, \\ldots, b_n$.\n\nAn anonymous informant has told you that the array $b$ was obtained as follows: initially, there existed an array $a_1, a_2, \\ldots, a_n$, after which the following two-component operation was performed $k$ times:\n\n- A fixed point$^{\\dagger}$ $x$ of the array $a$ was chosen.\n- Then, the array $a$ was cyclically shifted to the left$^{\\ddagger}$ exactly $x$ times.\n\nAs a result of $k$ such operations, the array $b_1, b_2, \\ldots, b_n$ was obtained. You want to check if the words of the anonymous informant can be true or if they are guaranteed to be false.\n\n$^{\\dagger}$A number $x$ is called a fixed point of the array $a_1, a_2, \\ldots, a_n$ if $1 \\leq x \\leq n$ and $a_x = x$.\n\n$^{\\ddagger}$A cyclic left shift of the array $a_1, a_2, \\ldots, a_n$ is the array $a_2, \\ldots, a_n, a_1$.",
    "tutorial": "The key idea is that after applying an operation with the number $x$, the last element of the resulting array will be equal to $x$. Since after $x$ cyclic shifts, the array $[a_1, a_2, \\ldots, a_n]$ will become $[a_{x+1}, \\ldots, a_n, a_1, \\ldots, a_x]$, and $a_x = x$, as $x$ was a fixed point of the array $a$. From this idea, we can deduce that the operation can always be undone in at most one way: we need to look at the last element ($a_n$), and if $a_n > n$, it is not possible to undo the operation. Otherwise, we need to cyclically shift the array to the right $a_n$ times. Therefore, the solution to the problem will be to undo the operation on the array by $1$ step $k$ times. If at any point it becomes impossible to undo the operation, the answer is \"No\". Otherwise, the answer is \"Yes\". To avoid explicitly shifting the array, we can store a variable $s$ representing the index of the initial element, indicating that the current array is equal to $[a_s, a_{s+1}, \\ldots, a_n, a_1, \\ldots, a_{s-1}]$. When cyclically shifting the array to the right by $x$, $s$ decreases by $x$, initially $s = 1$. Also, since $k$ in the problem can be up to $10^9$, simulating $k$ undo operations would be very time-consuming. However, we can notice that if we manage to undo the operation $n$ times without breaking anything, we have entered a cycle. Therefore, if we successfully undo the operation $n$ times, the answer is definitely \"Yes\". In other words, it was sufficient to do k = min(k, n). Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n  int n, k;\n  cin >> n >> k;\n  vector<int> a(n);\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n  }\n  k = min(k, n);\n  int last = n - 1;\n  for (int _ = 0; _ < k; _++) {\n    if (a[last] > n) {\n      cout << \"No\\n\";\n      return;\n    }\n    last += n - a[last];\n    if (last >= n) {\n      last -= n;\n    }\n  }\n  cout << \"Yes\\n\";\n}\n \nsigned main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1893",
    "index": "B",
    "title": "Neutral Tonality",
    "statement": "You are given an array $a$ consisting of $n$ integers, as well as an array $b$ consisting of $m$ integers.\n\nLet $\\text{LIS}(c)$ denote the length of the longest increasing subsequence of array $c$. For example, $\\text{LIS}([2, \\underline{1}, 1, \\underline{3}])$ = $2$, $\\text{LIS}([\\underline{1}, \\underline{7}, \\underline{9}])$ = $3$, $\\text{LIS}([3, \\underline{1}, \\underline{2}, \\underline{4}])$ = $3$.\n\nYou need to insert the numbers $b_1, b_2, \\ldots, b_m$ into the array $a$, at any positions, in any order. Let the resulting array be $c_1, c_2, \\ldots, c_{n+m}$. You need to choose the positions for insertion in order to \\textbf{minimize} $\\text{LIS}(c)$.\n\nFormally, you need to find an array $c_1, c_2, \\ldots, c_{n+m}$ that simultaneously satisfies the following conditions:\n\n- The array $a_1, a_2, \\ldots, a_n$ is a subsequence of the array $c_1, c_2, \\ldots, c_{n+m}$.\n- The array $c_1, c_2, \\ldots, c_{n+m}$ consists of the numbers $a_1, a_2, \\ldots, a_n, b_1, b_2, \\ldots, b_m$, possibly rearranged.\n- The value of $\\text{LIS}(c)$ is the \\textbf{minimum} possible among all suitable arrays $c$.",
    "tutorial": "First observation: $\\text{LIS}(c) \\geq \\text{LIS}(a)$. This is true because the array $c$ will always contain $a$ as a subsequence, and therefore any subsequence of $a$ as well. Notice that it is always possible to achieve $\\text{LIS}(c) \\leq \\text{LIS}(a) + 1$. Let $b_1 \\geq \\ldots \\geq b_m$. This can be achieved by inserting $b_1, \\ldots, b_m$ in a non-increasing order at any positions in the array $a$, because in this case, any increasing subsequence of $c$ can have at most one element from the array $b$, which means $\\text{LIS}(c) \\leq \\text{LIS}(a) + 1$. Therefore, we need to understand when we can achieve $\\text{LIS}(c) = \\text{LIS}(a)$. It turns out that this can always be achieved! Let's understand how to insert one number ($x$) into the array while preserving $\\text{LIS}(a)$. If $x < \\min(a_1, \\ldots, a_n)$, then we insert $x$ at the end of the array $a$, so that $x$ cannot be present in any increasing subsequence of length at least $2$, and $\\text{LIS}(a)$ will not increase. Otherwise, we can insert $x$ before the first index $i$ such that $x \\geq a_i$. Then, both $x$ and $a_i$ cannot be present in the same increasing subsequence. However, in any increasing subsequence where $x$ is present, we can replace $x$ with $a_i$ and the subsequence will still remain increasing. Thus, $\\text{LIS}(a)$ will not increase. Now we can apply this solution $m$ times, inserting the numbers $b_1 \\geq b_2 \\geq \\ldots \\geq b_m$ one by one. The final algorithm turns out to be surprisingly simple and similar to the merge(a, b) function. Specifically, iterate on arrays $a$ and $b$ with two pointers, at each step adding the larger of the two numbers ($a_i$ or $b_j$) to the answer and moving the corresponding pointer. Time complexity: $O(n + m \\log m)$",
    "code": "#include <bits/stdc++.h>\n \n#define pb push_back\n#define all(x) x.begin(), (x).end()\n#define rall(x) x.rbegin(), (x).rend()\nusing namespace std;\n \nvoid solve() {\n  int n, m;\n  cin >> n >> m;\n  vector<int> a(n), b(m), c(n + m);\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n  }\n  for (int i = 0; i < m; i++) {\n    cin >> b[i];\n  }\n  sort(rall(b));\n  merge(all(a), all(b), c.begin(), greater<int>());\n  for (int i = 0; i < n + m; i++) {\n    cout << c[i] << ' ';\n  }\n  cout << '\\n';\n}\n \nsigned main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1893",
    "index": "C",
    "title": "Freedom of Choice",
    "statement": "Let's define the anti-beauty of a multiset $\\{b_1, b_2, \\ldots, b_{len}\\}$ as the number of occurrences of the number $len$ in the multiset.\n\nYou are given $m$ multisets, where the $i$-th multiset contains $n_i$ distinct elements, specifically: $c_{i, 1}$ copies of the number $a_{i,1}$, $c_{i, 2}$ copies of the number $a_{i,2}, \\ldots, c_{i, n_i}$ copies of the number $a_{i, n_i}$. It is guaranteed that $a_{i, 1} < a_{i, 2} < \\ldots < a_{i, n_i}$. You are also given numbers $l_1, l_2, \\ldots, l_m$ and $r_1, r_2, \\ldots, r_m$ such that $1 \\le l_i \\le r_i \\le c_{i, 1} + \\ldots + c_{i, n_i}$.\n\nLet's create a multiset $X$, initially empty. Then, for each $i$ from $1$ to $m$, you must perform the following action \\textbf{exactly once}:\n\n- Choose some $v_i$ such that $l_i \\le v_i \\le r_i$\n- Choose any $v_i$ numbers from the $i$-th multiset and add them to the multiset $X$.\n\nYou need to choose $v_1, \\ldots, v_m$ and the added numbers in such a way that the resulting multiset $X$ has the \\textbf{minimum possible} anti-beauty.",
    "tutorial": "Note that after performing all operations, the multiset $X$ can have any integer size from $\\sum l_i$ to $\\sum r_i$. And the number of distinct numbers that can potentially be in $X$ is definitely not greater than $\\sum n_i$. Therefore, if $\\sum r_i - \\sum l_i > \\sum n_i$, there will always be a number from $\\sum l_i$ to $\\sum r_i$ that is not present in any of the $m$ given multisets, and thus will not be in $X$. By making $X$ of such size, we will have the anti-beauty of $X$ equal to $0$, which is the minimum achievable anti-beauty. So, if $\\sum r_i - \\sum l_i > \\sum n_i$, we can output $0$ and terminate. Then we solve the problem under the condition $\\sum r_i - \\sum l_i \\leq \\sum n_i$. $\\sum n_i$ is limited to $10^5$. Therefore, we can explicitly iterate through all possible sizes of the multiset $X$, from $\\sum l_i$ to $\\sum r_i$, and for a fixed size $s$, determine the minimum anti-beauty if $X$ has size $s$. Then we take the minimum of these values as the answer. For a fixed size $s$, to minimize the anti-beauty, we want to include as many numbers not equal to $s$ in $X$ as possible. For the multisets where $s$ is not present, we want to take $r_i$. To calculate this sum, we can take the sum of all $r_i$ and subtract from it the sum of $r_i$ for the multisets in which $s$ is present. And for those multisets where $s$ is present, we can explicitly iterate through them and use simple formulas to calculate how many $s$ we are obligated to take from each multiset. This will take at most $O(\\sum n_i)$. For specific formulas, refer to the code.",
    "code": "#include <bits/stdc++.h>\n \n#define pb push_back\n#define int long long\n#define all(x) x.begin(), (x).end()\nusing namespace std;\n \nvoid solve() {\n  int m;\n  cin >> m;\n  vector<int> n(m), l(m), r(m);\n  vector<vector<int>> a(m);\n  vector<vector<int>> c(m);\n  vector<int> sumc(m);\n  int suml = 0, sumr = 0, sumn = 0;\n  for (int i = 0; i < m; i++) {\n    cin >> n[i] >> l[i] >> r[i];\n    sumn += n[i];\n    suml += l[i];\n    sumr += r[i];\n    a[i].resize(n[i]);\n    for (int j = 0; j < n[i]; j++) {\n      cin >> a[i][j];\n    }\n    c[i].resize(n[i]);\n    for (int j = 0; j < n[i]; j++) {\n      cin >> c[i][j];\n      sumc[i] += c[i][j];\n    }\n  }\n  \n  if (sumr - suml > sumn) {\n    cout << \"0\\n\";\n    return;\n  }\n \n  map<int, int> sumr_a;\n  map<int, vector<pair<int, int>>> indexes;\n  for (int i = 0; i < m; i++) {\n    for (int j = 0; j < n[i]; j++) {\n      sumr_a[a[i][j]] += r[i];\n      indexes[a[i][j]].pb({i, j});\n    }\n  }\n \n  int ans = (int) 2e18;\n  for (int len = suml; len <= sumr; len++) {\n    int xsize = 0, must_len = 0;\n    xsize += sumr - sumr_a[len];\n    for (auto &[i, pos] : indexes[len]) {\n      int cnt_not_len = sumc[i] - c[i][pos];\n      if (cnt_not_len < l[i]) {\n        xsize += l[i];\n        must_len += l[i] - cnt_not_len;\n      } else {\n        xsize += min(cnt_not_len, r[i]);\n      }\n    }\n    ans = min(ans, must_len + max(0LL, len - xsize));\n  }\n  cout << ans << '\\n';\n}\n \nsigned main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1893",
    "index": "D",
    "title": "Colorful Constructive",
    "statement": "You have $n$ colored cubes, the $i$-th cube has color $a_i$.\n\nYou need to distribute all the cubes on shelves. There are a total of $m$ shelves, the $i$-th shelf can hold $s_i$ cubes. Also, $s_1 + s_2 + \\ldots + s_m = n$.\n\nSuppose on a shelf of size $k$ there are cubes of colors $c_1, c_2, \\ldots, c_k$, \\textbf{in this order}. Then we define the colorfulness of the shelf as the minimum distance between two different cubes of the same color on the shelf. If all the cubes on the shelf have different colors, then the colorfulness is considered to be equal to the size of the shelf, that is, the number $k$.\n\nMore formally, the colorfulness of $c_1, c_2, \\ldots, c_k$ is defined as follows:\n\n- If all the colors $c_1, c_2, \\ldots, c_k$ are different, the colorfulness is considered to be $k$.\n- Otherwise, the colorfulness is considered to be the smallest integer $x \\geq 1$ such that there exists an index $i$ $(1 \\le i \\le k - x)$ such that $c_i = c_{i+x}$.\n\nFor each shelf, you are given the minimum required colorfulness, that is, you are given numbers $d_1, d_2, \\ldots, d_m$, which mean that shelf $i$ must have a colorfulness $\\geq d_i$ for all $i$.\n\nDistribute the available cubes among the shelves to ensure the required colorfulness, or report that it is impossible.",
    "tutorial": "Let's try to come up with a condition equivalent to \"A set of cubes $a_1, \\ldots, a_n$ can be distributed on a shelf of size $n$ such that the colorfulness of the shelf is $\\geq d$\" in such a way that this condition can be conveniently combined for $m$ shelves. Let's find the necessary condition (the condition that must be satisfied) if the set of cubes $a_1 \\ldots a_n$ can be correctly placed on a shelf with parameters $(n, d)$. In such an arrangement, every $\\leq d$ adjacent cubes must have different colors. This means that we can divide the shelf into subsegments as follows: $(a_1, \\ldots, a_d), (a_{d+1}, \\ldots, a_{2d}), \\ldots, (a_{d \\cdot (\\lfloor \\frac{n}{d} \\rfloor - 1) + 1}, \\ldots, a_{d \\cdot \\lfloor \\frac{n}{d} \\rfloor}), (a_{d \\cdot \\lfloor \\frac{n}{d} \\rfloor + 1}, \\ldots, a_{n})$ such that the colors of all cubes in each subsegment are different. From this, the necessary condition follows: \"The set of cubes $a_1, \\ldots, a_n$ can be divided into $\\lfloor \\frac{n}{d} \\rfloor$ groups of size $d$, as well as a group of size $n \\mod d$, such that the colors of all cubes in each group are different.\" It turns out that this same condition is also sufficient! We will show this by presenting a way to place all the cubes from the \"$\\lfloor \\frac{n}{d} \\rfloor$ groups of size $d$, and the group of size $n \\mod d$ (where the colors of all cubes in each group are different)\" on a shelf of size $n$ such that the colorfulness of the shelf is $\\geq d$. How to do it: place the cubes from the group of size $n \\mod d$ in the first positions. Then consider the groups of size $d$ in any order. Place the cubes whose colors are already present in the previously placed array at the same indices as in the previous array, at a distance of $d$, and place the rest of the cubes however you like. It is easy to see that in this construction, the distance between any two identical colors is at least $d$. Example for understanding: let $d = 3$ and the given groups be: $[1, 2, 3], [3, 4, 5], [1, 3, 4], [1, 2]$. Then we proceed as follows: first, place $[1, 2]$. Then we want to add the group $[1, 2, 3]$: $[1, 2, ?, ?, ?]$. The elements $1$ and $2$ were present in the previous array, so we place them at a distance of $d = 3$ from the previous occurrences: $[1, 2, ?, 1, 2]$. Fill in the remaining element: $[1, 2, 3, 1, 2]$. Now append $[3, 4, 5]$: $[1, 2, 3, 1, 2, ?, ?, ?]$. The element $3$ is present in the previous array, so we place it: $[1, 2, 3, 1, 2, 3, ?, ?]$. Fill in the remaining elements in any order: $[1, 2, 3, 1, 2, 3, 4, 5]$. After that, append the group $[1, 3, 4]$ and obtain the final arrangement: $[1, 2, 3, 1, 2, 3, 4, 5, 3, 4, 1]$. The colorfulness is $\\geq 3$. What to do with this information now? If we replace the conditions for all $m$ shelves with equivalent ones, we get: \"The cubes can be placed on shelves $(s_1, d_1), \\ldots, (s_m, d_m)$\" is equivalent to \"The cubes can be divided into groups of sizes $[\\underbrace{d_1, \\ldots, d_1}_{\\lfloor \\frac{s_1}{d_1} \\rfloor}, s_1\\mod d_1, \\ldots, \\underbrace{d_m, \\ldots, d_m}_{\\lfloor \\frac{s_m}{d_m} \\rfloor}, s_m \\mod d_m]$, such that all colors are different in each group.\" Thus, we have reduced the problem to a simpler one: given $a_1, \\ldots, a_n$ and a set $w_1, \\ldots, w_k$ with a sum of $n$. We need to divide the numbers $a_1, \\ldots, a_n$ into arrays of sizes $w_1, \\ldots, w_k$ such that all numbers in each array are different. This problem can be solved using a simple greedy algorithm. Let $[a_1, \\ldots, a_n]$ consist of $cnt_1$ copies of element $b_1$, $cnt_2$ copies of element $b_2$, ..., $cnt_t$ copies of element $b_t$ ($\\sum cnt_i = n$). Then we consider the elements $b_1, \\ldots, b_t$ in any order and place all copies of the current element in arrays of the largest length. If there are fewer arrays with non-zero length remaining than $cnt_i$, there is no solution. After adding, the length of the arrays in which the number was added decreases by $1$. It is easy to see that if we obtain a solution, then the numbers in all arrays will indeed be different. This solution can be easily implemented using std::set. The correctness of the greedy algorithm follows from the fact that if there are two arrays of lengths $n_1 > n_2$ consisting of different numbers, then in the array of length $n_1$, there must be some number that is not present in the array of length $n_2$, so any number from the array of length $n_2$ can be swapped with someone from the array of length $n_1$ to maintain the property that the numbers in both arrays are different. From this, it follows that if we have some solution to the problem and a fixed element, we can obtain a solution in which this fixed element is only present in the largest arrays, which proves our solution. Second solution: Ultra Greedy Algorithm. We go through shelves and places on the shelf, and at each moment we place a cube of a color that occurs the most times among the remaining cubes, naturally excluding colors that would break the condition of having different colors (i.e., excluding colors other than the {$\\max(0, d_i - 1)$} colors of the previous cubes on this shelf). The proof of why this solution works will remain behind the scenes.",
    "code": "#include <bits/stdc++.h>\n \n#define pb push_back\n#define all(x) x.begin(), (x).end()\n#define rall(x) x.rbegin(), (x).rend()\nusing namespace std;\n \nvoid solve() {\n  int n, m;\n  cin >> n >> m;\n  vector<int> a(n);\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n  }\n  vector<int> s(m), d(m);\n  for (int i = 0; i < m; i++) {\n    cin >> s[i];\n  }\n  for (int i = 0; i < m; i++) {\n    cin >> d[i];\n  }\n  vector<int> cnt(n + 1);\n  for (int i = 0; i < n; i++) {\n    cnt[a[i]]++;\n  }\n \n  set<pair<int, int>> cubes;\n  for (int x = 1; x <= n; x++) {\n    if (cnt[x] == 0) continue;\n    cubes.insert({cnt[x], x});\n  }\n \n  vector<vector<int>> ans(m);\n \n  for (int i = 0; i < m; i++) {\n    ans[i].assign(s[i], 0);\n    for (int j = 0; j < s[i]; j++) {\n      if (j >= d[i]) {\n        if (cnt[ans[i][j - d[i]]] > 0) {\n          cubes.insert({cnt[ans[i][j - d[i]]], ans[i][j - d[i]]});\n        }\n      }\n      if (cubes.empty()) {\n        cout << \"-1\\n\";\n        return;\n      }\n      ans[i][j] = (*cubes.rbegin()).second;\n      cubes.erase(*cubes.rbegin());\n      cnt[ans[i][j]]--;\n    }\n    for (int j = s[i]; j < s[i] + d[i]; j++) {\n      if (cnt[ans[i][j - d[i]]] > 0) {\n        cubes.insert({cnt[ans[i][j - d[i]]], ans[i][j - d[i]]});\n      }\n    }\n  }\n \n  for (int i = 0; i < m; i++) {\n    for (int j = 0; j < s[i]; j++) {\n      cout << ans[i][j] << ' ';\n    }\n    cout << '\\n';\n  }\n \n}\n \n \nsigned main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1893",
    "index": "E",
    "title": "Cacti Symphony",
    "statement": "You are given an undirected connected graph in which any two distinct simple cycles \\textbf{do not have} common vertices. Since the graph can be very large, it is given to you in a compressed form: for each edge, you are also given a number $d$, which indicates that there are $d$ additional vertices on this edge.\n\nYou need to assign a weight to each vertex and each edge of the graph — an integer from $1$ to $3$.\n\nAn edge of the graph is called good if the bitwise XOR of the weights of its adjacent vertices is \\textbf{not equal to} $0$ and \\textbf{not equal to} the weight of that edge.\n\nSimilarly, a vertex of the graph is called good if the bitwise XOR of the weights of its adjacent edges is \\textbf{not equal to} $0$ and \\textbf{not equal to} the weight of that vertex.\n\nYou need to determine how many ways there are to assign weights to the vertices and edges of the graph so that all vertices and edges are good. Since the answer can be quite large, you need to calculate the remainder of the answer divided by $998\\,244\\,353$.",
    "tutorial": "First observation: for each edge, the vertices connected by it have different weights, otherwise the XOR of the weights of the adjacent vertices of this edge is equal to $0$. Second observation: for each edge, one of its adjacent vertices has a weight equal to the weight of the edge, since $1 \\oplus 2 \\oplus 3 = 0$. From these two observations, it follows that each edge has the same weight as EXACTLY one of the vertices it is connected to. Let's say that a vertex controls all the adjacent edges with the same weight. Then each edge is controlled by exactly one vertex. Third observation: if a vertex has an even degree, then the number of edges controlled by it must be odd, and this is a sufficient condition for the vertex to be good. Fourth observation: if a vertex has an odd degree, then the number of edges controlled by it must be even, and this is a sufficient condition for the vertex to be good. Therefore, in order for all vertices to be good, it is necessary to choose who controls each edge in such a way that the parity of the vertex degree and the parity of the number of edges controlled by it are different. And in order for all edges to be good, it is necessary to assign weights from $1$ to $3$ to the vertices in such a way that no two adjacent vertices have the same weight. The weight of each edge will then be equal to the weight of the vertex it is controlled by. Now the problem is divided into two independent parts: finding the number of ways to assign weights to the vertices, and finding the number of ways to orient the edges. The answer to the original problem will be the product of the answers to these two parts. How many ways are there to color the vertices with $3$ colors, such that two adjacent vertices are colored differently? How many ways are there to orient the edges, such that a vertex with an even degree has an odd number of outgoing edges, and a vertex with an odd degree has an even number of outgoing edges? Solution to problem 1: note that if there is a bridge in the graph $G$, and it divides the graph into graphs $G1$ and $G2$, then the answer for $G$ is the product of the answers for $G1$ and $G2$ multiplied by $\\frac{2}{3}$. Then we can identify all the bridges, and since the graph is a vertex cactus, after removing the bridges, the graph will be divided into cycle components. For a cycle of length $n$, the number of ways to color the vertices can be calculated using simple dynamic programming: $dp_1 = 3, dp_3 = 6, dp_4 = 18, dp_n = dp_{n - 1} + 2 \\cdot dp_{n - 2}$. To prove this dynamic programming, consider any two vertices that are one apart in a cycle of length $n$. If they have the same color, then the vertex between them has $2$ possible colors, and the rest have $dp_{n-2}$ possibilities. If they have different colors, then there are $dp_{n-1}$ possibilities. Knowing the transition formula, we can notice that $dp_n = 2^n + 2 \\cdot (-1)^n$. This formula can be trivially proved by induction. Solution to problem 2: we will solve the same problem, but requiring that each vertex has an odd number of outgoing edges (if we invert all the edges in such a graph, we will get what is required). If $n$ and $m$ have different parity, then the answer is $0$, since the sum of $n$ odd numbers, which are the degrees of the vertices, must be equal to $m$. Otherwise, the answer is $2^{number of cycles}$. At any moment, we can remove any leaf, as it does not solve anything. We will remove the leaves as long as they exist. After this, one of the cycles in the graph will be a \"leaf\" - connected only to one other cycle. For all vertices of this cycle, the necessary parities of the degrees are known. Choose any edge of the cycle and orient it (there are $2$ ways to orient it, both will work). After that, all other edges in the cycle are oriented uniquely. After that, the bridge between this cycle and the other one is also uniquely oriented. Now we have one less cycle, and we also know all the necessary parities of the vertices (the parity changes for the vertex where the bridge came in). In this way, we can gradually reduce the number of cycles. With each removal of a cycle, the answer is multiplied by $2$, since there are $2$ ways to orient the edge in the cycle. In the end, we get $2^{number of cycles}$ ways. The final answer to the problem if $n$ and $m$ have same parity is: $ans = \\frac{2}{3}^{number of bridges} \\cdot 2^{number of cycles} \\cdot (2^{c_1} + 2 \\cdot (-1)^{c_1}) \\cdot \\ldots \\cdot (2^{c_k} + 2 \\cdot (-1)^{c_k})$ where $c_1, \\ldots, c_k$ are the sizes of cycles (cycle can be a single vertice if it did not lie on any other cycle, and $c_i = 0$ in this case).",
    "code": "#include <bits/stdc++.h>\n \ntypedef long long ll;\n#define pb push_back\n \nusing namespace std;\n \nconst int M = 998244353;\nconst int N = 500500;\nvector<pair<int, int>> g[N];\nset<int> bridgesV[N];\nbitset<N> used;\nint h[N], d[N];\nll bridges = 0;\nll solo = 0;\n \nint binpow(ll a, ll x) {\n  ll ans = 1;\n  while (x) {\n    if (x % 2) {\n      ans *= a;\n      ans %= M;\n    }\n    a *= a;\n    a %= M;\n    x /= 2;\n  }\n  return (int) ans;\n}\n \nvoid dfs(int v, int p = -1) {\n  if (p != -1) {\n    d[v] = h[p] + 1;\n    h[v] = h[p] + 1;\n  }\n  used[v] = true;\n  for (auto &[u, w] : g[v]) {\n    if (u == p) continue;\n    if (!used[u]) {\n      dfs(u, v);\n      d[v] = min(d[v], d[u]);\n      if (h[v] < d[u]) {\n        bridgesV[v].insert(u);\n        bridgesV[u].insert(v);\n        bridges += w + 1;\n        solo += w;\n      }\n    } else {\n      d[v] = min(d[v], h[u]);\n    }\n  }\n}\n \nint calc_dp(ll n) {\n  n %= (M - 1);\n  if (n == 1) return 3;\n  if (n == 2) return 0;\n  int val = binpow(2, n);\n  if (n % 2 == 1) {\n    val += M - 2;\n  } else {\n    val += 2;\n  }\n  val %= M;\n  return val;\n}\n \nsigned main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int n, m;\n  cin >> n >> m;\n  for (int i = 0; i < m; i++) {\n    int a, b, w;\n    cin >> a >> b >> w;\n    a--;\n    b--;\n    g[a].pb({b, w});\n    g[b].pb({a, w});\n  }\n  if (n % 2 != m % 2) {\n    cout << \"0\\n\";\n    return 0;\n  }\n  dfs(0);\n  used.reset();\n \n  ll ans = 1;\n  for (int v = 0; v < n; v++) {\n    if (!used[v]) {\n      ll cs = 0;\n      vector<int> q = {v};\n      used[v] = true;\n      while (!q.empty()) {\n        int u = q.back();\n        q.pop_back();\n        for (auto &[uu, w] : g[u]) {\n          if (bridgesV[u].find(uu) != bridgesV[u].end()) continue;\n          cs += w + 1;\n          if (!used[uu]) {\n            used[uu] = true;\n            q.pb(uu);\n          }\n        }\n      }\n      cs /= 2;\n      cs = max(cs, 1LL);\n      ans *= calc_dp(cs);\n      ans %= M;\n    }\n  }\n  ans *= binpow(3, solo);\n  ans %= M;\n  int w = (2 * binpow(3, M - 2)) % M;\n  ans *= binpow(w, bridges);\n  ans %= M;\n  int cycles = (m + 1) - n;\n  ans *= binpow(2, cycles);\n  ans %= M;\n  cout << ans << '\\n';\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1894",
    "index": "A",
    "title": "Secret Sport",
    "statement": "Let's consider a game in which two players, A and B, participate. This game is characterized by two positive integers, $X$ and $Y$.\n\nThe game consists of sets, and each set consists of plays. In each play, \\textbf{exactly one} of the players, either A or B, wins. A set ends \\textbf{exactly} when one of the players reaches $X$ wins in the plays of that set. This player is declared the winner of the set. The players play sets until one of them reaches $Y$ wins in the sets. After that, the game ends, and this player is declared the winner of the entire game.\n\nYou have just watched a game but didn't notice who was declared the winner. You remember that during the game, $n$ plays were played, and you know which player won each play. However, you \\textbf{do not know} the values of $X$ and $Y$. Based on the available information, determine who won the entire game — A or B. If there is not enough information to determine the winner, you should also report it.",
    "tutorial": "The winner will be the player who wins the last play. This is true because the winner will be the player who wins the last set, because, if this were not the case, the last set would not be played. And in a set, the player who wins the last play wins, because if this were not the case, the last play would not be played.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n  int n;\n  cin >> n;\n  string s;\n  cin >> s;\n  cout << s.back() << '\\n';\n}\n \nsigned main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1894",
    "index": "B",
    "title": "Two Out of Three",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$. You need to find an array $b_1, b_2, \\ldots, b_n$ consisting of numbers $1$, $2$, $3$ such that \\textbf{exactly two} out of the following three conditions are satisfied:\n\n- There exist indices $1 \\leq i, j \\leq n$ such that $a_i = a_j$, $b_i = 1$, $b_j = 2$.\n- There exist indices $1 \\leq i, j \\leq n$ such that $a_i = a_j$, $b_i = 1$, $b_j = 3$.\n- There exist indices $1 \\leq i, j \\leq n$ such that $a_i = a_j$, $b_i = 2$, $b_j = 3$.\n\nIf such an array does not exist, you should report it.",
    "tutorial": "By symmetry, it doesn't matter which two conditions are satisfied. Let's assume it's the conditions $(1, 2)$ and $(1, 3)$. Then the elements with $b_i = 2$ and the elements with $b_i = 3$ should not intersect. Therefore, it is sufficient to assign $b_i = 2$ and $b_i = 3$ to only one element that is common with the elements of the form $b_i = 1$ in order to satisfy the conditions $(1, 2)$ and $(1, 3)$. And these elements must be distinct in order to not satisfy the condition $(2, 3)$. Thus, we obtain the necessary condition for the existence of an answer: the array must have at least two elements that occur more than once. It is easy to see that this condition is also sufficient by constructing an example: let $x, y$ be two numbers that occur more than once in the array. Then we can assign $a_i = x \\to b_i = 2$ to one of the occurrences, $a_i = y \\to b_i = 3$ to one of the occurrence, and assign $b_i = 1$ to all other numbers, and this will be a suitable answer.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nconst int N = 100;\n \nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  for (int i = 0; i < n; i++) {\n    cin >> a[i];\n  }\n  vector<int> b(n, 1);\n  vector<vector<int>> inds(N + 1);\n  for (int i = 0; i < n; i++) {\n    inds[a[i]].push_back(i);\n  }\n  int k = 2;\n  for (int x = 1; x <= N; x++) {\n    if ((int) inds[x].size() >= 2) {\n      b[inds[x][0]] = k;\n      k++;\n      if (k > 3) {\n        break;\n      }\n    }\n  }\n  if (k <= 3) {\n    cout << \"-1\\n\";\n  } else {\n    for (int i = 0; i < n; i++) {\n      cout << b[i] << ' ';\n    }\n    cout << '\\n';\n  }\n}\n \nsigned main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  cout.tie(nullptr);\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1895",
    "index": "A",
    "title": "Treasure Chest",
    "statement": "Monocarp has found a treasure map. The map represents the treasure location as an OX axis. Monocarp is at $0$, the treasure chest is at $x$, the key to the chest is at $y$.\n\nObviously, Monocarp wants to open the chest. He can perform the following actions:\n\n- go $1$ to the left or $1$ to the right (spending $1$ second);\n- pick the key or the chest up if he is in the same point as that object (spending $0$ seconds);\n- put the chest down in his current point (spending $0$ seconds);\n- open the chest if he's in the same point as the chest and has picked the key up (spending $0$ seconds).\n\nMonocarp can carry the chest, but the chest is pretty heavy. He knows that he can carry it for at most $k$ seconds in total (putting it down and picking it back up doesn't reset his stamina).\n\nWhat's the smallest time required for Monocarp to open the chest?",
    "tutorial": "Let's consider two cases: If $y < x$, then the answer is $x$, because we need to reach the chest and we can take the key on the way. If $y > x$, then the optimal option would be to bring the chest directly to the key. However, this is not always possible due to the value of $k$. If $y - x \\le k$, then we can do it and the answer is $y$. Otherwise, the answer is $y + y - (x + d)$, where $d$ is the time we carried the chest, and $y - (x + d)$ is the time to return from the key to the chest back. From here, we can see that this value is minimum when $d=k$. Thus, the answer is $y + y - (x + k)$.",
    "code": "for _ in range(int(input())):\n    x, y, k = map(int, input().split())\n    if y < x:\n      print(x)\n    else:\n      print(y + max(0, y - x - k))",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1895",
    "index": "B",
    "title": "Points and Minimum Distance",
    "statement": "You are given a sequence of integers $a$ of length $2n$. You have to split these $2n$ integers into $n$ pairs; each pair will represent the coordinates of a point on a plane. Each number from the sequence $a$ should become the $x$ or $y$ coordinate of exactly one point. Note that some points can be equal.\n\nAfter the points are formed, you have to choose a path $s$ that starts from one of these points, ends at one of these points, and visits all $n$ points at least once.\n\nThe length of path $s$ is the sum of distances between all adjacent points on the path. In this problem, the distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is defined as $|x_1-x_2| + |y_1-y_2|$.\n\nYour task is to form $n$ points and choose a path $s$ in such a way that the length of path $s$ is minimized.",
    "tutorial": "Since the order of $a_i$ does not matter, let's sort them for convenience. Let's treat the resulting path as two one-dimensional paths: one path $x_1 \\rightarrow x_2 \\rightarrow \\dots \\rightarrow x_n$ and one path $y_1 \\rightarrow y_2 \\rightarrow \\dots \\rightarrow y_n$. The length of the path $s$ is equal to the sum of lengths of these two paths. If we fix which integers are $x$-coordinates and which integers are $y$-coordinates, it's quite easy to see that it is optimal to place both $[x_1, x_2, \\dots, x_n]$ and $[y_1, y_2, \\dots, y_n]$ in sorted order: the length of the path visiting both $\\min x_i$ and $\\max x_i$ should be at least $\\max x_i - \\min x_i$, and sorting gives exactly that result; the same with $y$-coordinates. Okay, then, how do we choose which integers are $x$-coordinates and which integers are $y$-coordinates? The total length of the path $s$ will be equal to $\\max x_i - \\min x_i + \\max y_i - \\min y_i$; one of the minimums will be equal to the value of $a_1$; one of the maximums will be equal to the value of $a_{2n}$; so we need to consider the remaining minimum and maximum. The minimum coordinate of any type should be less than or equal to at least $n - 1$ elements. Similarly, the maximum coordinate should be greater than or equal to at least $n-1$ elements. So, the second minimum (the minimum which is not $a_1$) is at most $a_{n+1}$, the second maximum is at least $a_n$, and the length of the path is at least $a_{2n} - a_1 + a_n - a_{n+1}$. And it is possible to reach this bound: take the first $n$ values in $a$ as $x$-coordinates, and the last $n$ values as $y$-coordinates.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n;\nvector<int> a;\n\ninline void read() {\n  cin >> n;\n  a.clear();\n  for (int i = 0; i < 2 * n; i++) {\n      int x;\n      cin >> x;\n      a.pb(x);\n  }\n}\ninline void solve() {\n    sort(all(a));\n    vector<pair<int, int> > pts;\n    for (int i = 0; i < n; i++) {\n        pts.pb(mp(a[i], a[i + n]));\n    }\n    int ans = 0;\n    for (int i = 1; i < n; i++) {\n        ans += abs(pts[i].ft - pts[i - 1].ft) + abs(pts[i].sc - pts[i - 1].sc);\n    }\n    cout << ans << endl;\n    for (int i = 0; i < n; i++) {\n        cout << pts[i].ft << ' ' << pts[i].sc << endl;\n    }\n}\n \nint main () {\n    int t;\n    cin >> t;\n    while (t--){\n        read();\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1895",
    "index": "C",
    "title": "Torn Lucky Ticket",
    "statement": "A ticket is a non-empty string of digits from $1$ to $9$.\n\nA lucky ticket is such a ticket that:\n\n- it has an even length;\n- the sum of digits in the first half is equal to the sum of digits in the second half.\n\nYou are given $n$ ticket pieces $s_1, s_2, \\dots, s_n$. How many pairs $(i, j)$ (for $1 \\le i, j \\le n$) are there such that $s_i + s_j$ is a lucky ticket? Note that it's possible that $i=j$.\n\nHere, the + operator denotes the concatenation of the two strings. For example, if $s_i$ is 13, and $s_j$ is 37, then $s_i + s_j$ is 1337.",
    "tutorial": "There is an obvious $O(n^2)$ approach: iterate over the first part, the second part and check the sum. In order to improve it, let's try to get rid of the second iteration. Consider the case where the first part is longer or equal than the second part. So, we still iterate over the first part in $O(n)$. However, instead of iterating over the exact second part, let's just iterate over its length. Now, we know the total length of the parts, but not their sums of digits. Hmm, not exactly. By fixing the longer part, we actually know what the required sum of each half should be. It's fully inside the first part. However, this first part also contains some digits that belong to the second half. So, if the sum of the second part was $s$, the total sum of the second half would be these digits plus $s$. Let $l$ be the total length of the ticket: the length of the fixed first part plus the fixed length of the second part. Let $\\mathit{sum}_l$ be the sum of the first $\\frac{l}{2}$ digits of the first part, and $\\mathit{sum}_r$ be the sum of its remaining digits. Then $\\mathit{sum}_l = \\mathit{sum}_r + s$. Rewrite into $\\mathit{sum}_l - \\mathit{sum}_r = s$. Thus, we just know what should be the sum of the second half. And every ticket part that is exactly of the fixed length and has sum exactly $\\mathit{sum}_l - \\mathit{sum}_r$ will form a lucky ticket with the fixed part. So, we have to precalculate $\\mathit{cnt}[l][s]$, which is the number of ticket parts that have length $l$ and sum $s$, and use that structure to speed up the solution. The mirror case, where the second part is strictly longer than the first part, can be handled similarly. Overall complexity: $O(n)$.",
    "code": "n = int(input())\ns = input().split()\nans = 0\ncnt = [[0 for k in range(46)] for k in range(6)]\nfor y in s:\n    cnt[len(y)][sum([int(c) for c in y])] += 1\nfor L in s:\n    for lenr in range(len(L) % 2, len(L) + 1, 2):\n        l = len(L) + lenr\n        suml = sum([int(c) for c in L[:l // 2]])\n        sumr = sum([int(c) for c in L[l // 2:]])\n        if suml - sumr >= 0:\n            ans += cnt[lenr][suml - sumr]\nfor R in s:\n    for lenl in range(len(R) % 2, len(R), 2):\n        l = len(R) + lenl\n        suml = sum([int(c) for c in R[-l // 2:]])\n        sumr = sum([int(c) for c in R[:-l // 2]])\n        if suml - sumr >= 0:\n            ans += cnt[lenl][suml - sumr]\nprint(ans)",
    "tags": [
      "brute force",
      "dp",
      "hashing",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1895",
    "index": "D",
    "title": "XOR Construction",
    "statement": "You are given $n-1$ integers $a_1, a_2, \\dots, a_{n-1}$.\n\nYour task is to construct an array $b_1, b_2, \\dots, b_n$ such that:\n\n- every integer from $0$ to $n-1$ appears in $b$ exactly once;\n- for every $i$ from $1$ to $n-1$, $b_i \\oplus b_{i+1} = a_i$ (where $\\oplus$ denotes the bitwise XOR operator).",
    "tutorial": "We can see that the first element of the array $b$ determines all other values, $b_{i + 1} = b_1 \\oplus a_1 \\cdots \\oplus a_i$. So let's iterate over the value of $b_1$. For every value of $b_1$, we need to check whether it produces correct permutation or not (i. e. all $b_i < n$). To do it in a fast way, we can generate an array $c$, where $c_i$ is the XOR of the first $i$ element of the array $a$ (i.e. $c_i = a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_i$ and $c_0 = 0$). We can see that $b_{i + 1} = b_1 \\oplus c_i$. Let's store all values of $c_i$ in a binary trie. To check that $b_1$ produces an array where all elements are less than $n$, we can calculate the maximum value of $b_1 \\oplus c_i$ using descending on the trie. If the maximum is less than $n$, then it's a valid first element of the permutation. Note that we don't actually need to check that the minimum is exactly $0$ and all elements are distinct: we are guaranteed that the answer exists, so all values $[0, c_1, c_2, c_3, \\dots, c_{n-1}]$ are pairwise distinct, and no matter which $b_1$ we choose, all $b_i$ will also be pairwise distinct.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nconst int LOG = 20;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  for (int i = 1; i < n; ++i) {\n    cin >> a[i];\n    a[i] ^= a[i - 1];\n  }\n  vector<array<int, 2>> t({{-1, -1}});\n  auto add = [&](int x) {\n    int v = 0;\n    for (int i = LOG - 1; i >= 0; --i) {\n      int j = (x >> i) & 1;\n      if (t[v][j] == -1) {\n        t[v][j] = t.size();\n        t.push_back({-1, -1});\n      }\n      v = t[v][j];\n    }\n  };  \n  for (int x : a) add(x);\n  auto get = [&](int x) {\n    int v = 0;\n    for (int i = LOG - 1; i >= 0; --i) {\n      int j = (x >> i) & 1;\n      if (t[v][j ^ 1] != -1) j ^= 1;\n      x ^= j << i;\n      v = t[v][j];\n    }\n    return x;\n  };\n  for (int x = 0; x < n; ++x) {\n    if (get(x) == n - 1) {\n      for (int i : a) cout << (x ^ i) << ' ';\n      break;\n    }\n  }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "data structures",
      "math",
      "string suffix structures",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1895",
    "index": "E",
    "title": "Infinite Card Game",
    "statement": "Monocarp and Bicarp are playing a card game. Each card has two parameters: an attack value and a defence value. A card $s$ beats another card $t$ if the attack of $s$ is strictly greater than the defence of $t$.\n\nMonocarp has $n$ cards, the $i$-th of them has an attack value of $\\mathit{ax}_i$ and a defence value of $\\mathit{ay}_i$. Bicarp has $m$ cards, the $j$-th of them has an attack value of $\\mathit{bx}_j$ and a defence value of $\\mathit{by}_j$.\n\nOn the first move, Monocarp chooses one of his cards and plays it. Bicarp has to respond with his own card that beats that card. After that, Monocarp has to respond with a card that beats Bicarp's card. After that, it's Bicarp's turn, and so forth.\n\n\\textbf{After a card is beaten, it returns to the hand of the player who played it.} It implies that each player always has the same set of cards to play as at the start of the game. The game ends when the current player has no cards that beat the card which their opponent just played, and the current player loses.\n\nIf the game lasts for $100^{500}$ moves, it's declared a draw.\n\nBoth Monocarp and Bicarp play optimally. That is, if a player has a winning strategy regardless of his opponent's moves, he plays for a win. Otherwise, if he has a drawing strategy, he plays for a draw.\n\nYou are asked to calculate three values:\n\n- the number of Monocarp's starting moves that result in a win for Monocarp;\n- the number of Monocarp's starting moves that result in a draw;\n- the number of Monocarp's starting moves that result in a win for Bicarp.",
    "tutorial": "Let's restate the game in game theory terms. The state of the game can be just the card that is currently on top, since none of the previously played cards matter. A move is still a card beating another card, so these are the edges of the game graph. Now we can solve this as a general game. Mark all trivial winning and losing states and determine the outcome for all other states with a DFS/BFS on a transposed game graph. Unfortunately, there are $O(n^2)$ edges in the graph, so we can't quite do it as is. There are multiple ways to optimize that, I'll describe the smartest one, in my opinion. Notice that, after a card beats another card, its attack doesn't matter at all. It's only health that's relevant. And the larger the health is, the fewer responses the opponent has. In particular, we use the fact that the sets of the responses can either coincide or be included one into another. So, there is always the best response for each card (or multiple equally good ones). That is just the card with the largest health among the ones that beat the current one. To find this card, you can sort them by their attack value and find a prefix/suffix health maximum. This massively reduces the number of edges. Now, each state has at most one outgoing edge. Zero edges mean that the card is winning, since there is no card to beat it. For these states, we can tell the winner. The rest of the states either reach these marked ones, thus, can be deduced, or form a closed loop among each other, making the outcome a draw (since there is always a response for each move). Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "//\n\n#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct card{\n  int x, y;\n  card() {}\n  card(int x, int y) : x(x), y(y) {}\n};\n\nvoid dfs(int v, const vector<int> &g, vector<int> &res, vector<char> &used){\n  if (used[v]) return;\n  used[v] = true;\n  dfs(g[v], g, res, used);\n  res[v] = -res[g[v]];\n}\n\nvoid solve(){\n  vector<vector<card>> a(2);\n  vector<vector<int>> prpos(2);\n  forn(z, 2){\n    int n;\n    scanf(\"%d\", &n);\n    a[z].resize(n);\n    forn(i, n) scanf(\"%d\", &a[z][i].x);\n    forn(i, n) scanf(\"%d\", &a[z][i].y);\n    sort(a[z].begin(), a[z].end(), [](const card &a, const card &b){\n      return a.x > b.x;\n    });\n    prpos[z].resize(n + 1, -1);\n    forn(i, n){\n      if (prpos[z][i] == -1 || a[z][i].y > a[z][prpos[z][i]].y)\n        prpos[z][i + 1] = i;\n      else\n        prpos[z][i + 1] = prpos[z][i];\n    }\n  }\n  int n = a[0].size();\n  vector<int> g(n + a[1].size());\n  forn(z, 2) forn(i, a[z].size()){\n    int cnt = lower_bound(a[z ^ 1].begin(), a[z ^ 1].end(), card(a[z][i].y, -1), [](const card &a, const card &b){\n      return a.x > b.x;\n    }) - a[z ^ 1].begin();\n    g[i + z * n] = prpos[z ^ 1][cnt] == -1 ? -1 : prpos[z ^ 1][cnt] + (z ^ 1) * n;\n  }\n  vector<int> res(g.size());\n  vector<char> used(g.size());\n  forn(i, g.size()) if (g[i] == -1) res[i] = 1, used[i] = true;\n  int w = 0, l = 0;\n  forn(i, n){\n    if (!used[i]) dfs(i, g, res, used);\n    w += res[i] == 1;\n    l += res[i] == -1;\n  }\n  printf(\"%d %d %d\\n\", w, n - l - w, l);\n}\n\nint main(){\n  int t;\n  scanf(\"%d\", &t);\n  while (t--) solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "games",
      "graphs",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1895",
    "index": "F",
    "title": "Fancy Arrays",
    "statement": "Let's call an array $a$ of $n$ non-negative integers fancy if the following conditions hold:\n\n- at least one from the numbers $x$, $x + 1$, ..., $x+k-1$ appears in the array;\n- consecutive elements of the array differ by at most $k$ (i.e. $|a_i-a_{i-1}| \\le k$ for each $i \\in [2, n]$).\n\nYou are given $n$, $x$ and $k$. Your task is to calculate the number of fancy arrays of length $n$. Since the answer can be large, print it modulo $10^9+7$.",
    "tutorial": "It is difficult to directly calculate the number of arrays that satisfy both conditions. So let's calculate the opposite value - the number of arrays, where only the second condition is holds, and the first is necessarily violated. Using the fact that the array can contain integers from two sets $[0, x)$ and $[x + k, \\infty)$. We can notice that the array can consist of elements from only one set, but not both (because the difference between elements from different sets is at least $k+1$ which violates the second condition). So the answer to the problem is $f(0, M) - f(0, x-1) - f(x+k, M)$, where $f(l, r)$ is the number of arrays of length $n$ that satisfy the second condition and elements in range from $l$ to $r$, and $M$ is some big constant (let it be equal to $10^{100}$). Let's take a closer look at the function $f(l, r)$. We can represent the required array $a$ as integer $a_1$ and an array of $n-1$ differences $\\Delta_i=a_{i+1}-a_1$. There are $(2k+1)^{n-1}$ differences arrays in total, because of the second condition. Let $cnt(l, r, \\Delta)$ be the number of valid $a_1$ for the given array $\\Delta$ ($a_1$ is valid if it's produces array $a$, where all elements from $l$ to $r$). Using such a representation we can see that $f(l, r) = \\sum\\limits_{\\Delta} cnt(l, r, \\Delta)$. Moreover, let $mn$ be the minimum value in $\\Delta$ and $mx$ be the maximum value in $\\Delta$, then $cnt(l, r, \\Delta)$ is equal to $\\max(0, (r - l) - (mx - mn))$. It is difficult to calculate the values of $f(0, M)$ and $f(x+k, M)$ independently, because we can't iterate over all arrays $\\Delta$. Luckily, our goal is to calculate their difference. Since the value of $M$ is big enough, we can say that $cnt$ of any $\\Delta$ is positive. So we can represent $f(0, M) - f(x+k, M)$ as $\\sum\\limits_{\\Delta} cnt(0, M, \\Delta) - \\sum\\limits_{\\Delta} cnt(x+k, M, \\Delta)$ $\\sum\\limits_{\\Delta} (M - 0) - (mx - mn) - \\sum\\limits_{\\Delta} (M - (x+k)) - (mx - mn))$ $\\sum\\limits_{\\Delta} ((M - 0) - (mx - mn)) - ((M - (x + k)) - (mx - mn))$ $f(0, M) - f(x+k, M) = \\sum\\limits_{\\Delta} x+k$ It remains us to calculate the value of $f(0, x-1)$. We can do it using simple dynamic programming $dp_{i, j}$ - the number of arrays of length $i$ if the last element is $j$. The transition from $(i, y)$ to $(i + 1, z)$ can be made if $|y - z| \\le k$. And the answer is equal to the sum of $dp_{n, j}$ for each $j \\in [0, x)$ Such dynamic programming works in $O(nx)$, but $n$ is too big for this solution. However, thanks to fairly simple transitions, we can represent it as matrix multiplication. Using fast matrix exponentiation, we can calculate it in $O(x^3\\log(n))$. The total answer is $(x+k)(2k+1)^{n-1} - f(0, x - 1)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int MOD = 1e9 + 7;\nconst int N = 40;\n\nusing mat = array<array<int, N>, N>;\n\nint add(int x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n  if (x < 0) x += MOD;\n  return x;\n}\n\nint mul(int x, int y) {\n  return x * 1LL * y % MOD;\n}\n\nmat mul(mat x, mat y) {\n  mat res;\n  forn(i, N) forn(j, N) res[i][j] = 0;\n  forn(i, N) forn(j, N) forn(k, N)\n    res[i][j] = add(res[i][j], mul(x[i][k], y[k][j]));\n  return res;\n}\n\ntemplate<class T>\nT binpow(T x, int y, T e) {\n  T res = e;\n  while (y) {\n    if (y & 1) res = mul(res, x);\n    x = mul(x, x);\n    y >>= 1;\n  }\n  return res;\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, x, k;\n    cin >> n >> x >> k;\n    mat a, e;\n    forn(i, N) forn(j, N) a[i][j] = (i < x && abs(i - j) <= k);\n    forn(i, N) forn(j, N) e[i][j] = (i == j);\n    mat b = binpow(a, n - 1, e);\n    int ans = mul(x + k, binpow(2 * k + 1, n - 1, 1));\n    forn(i, x) forn(j, x) ans = add(ans, -b[i][j]);\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "matrices"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1895",
    "index": "G",
    "title": "Two Characters, Two Colors",
    "statement": "You are given a string consisting of characters 0 and/or 1. You have to paint every character of this string into one of two colors, red or blue.\n\nIf you paint the $i$-th character red, you get $r_i$ coins. If you paint it blue, you get $b_i$ coins.\n\nAfter coloring the string, you remove every \\textbf{blue} character from it, and count the number of inversions in the resulting string (i. e. the number of pairs of characters such that the left character in the pair is 1, and the right character in the pair is 0). For each inversion, you have to pay $1$ coin.\n\nWhat is the maximum number of coins you can earn?",
    "tutorial": "This problem requires partitioning some object into two parts, and imposes different costs depending on how we perform the partition. Let's try to model it with minimum cuts. Create a flow network with $n+2$ vertices: a vertex for every character of the string, a source and a sink. Using the edges of the network, we will try to model the following: if we paint the $i$-th character red, we lose $b_i$ coins (we can treat it as always gaining $r_i + b_i$ coins no matter what, and then losing coins instead of earning them for coloring the characters); if we paint the $i$-th character blue, we lose $r_i$ coins (the same applies here); if $i < j$, $s_i = 1$, $s_j = 0$ and both $s_i$ and $s_j$ are red, we lose $1$ coin. To model the third constraint, let's say that the vertices representing $1$'s are red if they belong to the set $S$ in the cut, or blue if they belong to $T$. For the vertices representing $0$'s, this will be the opposite: they will be red if they belong to the set $T$, or blue if they belong to the set $S$. So, if we add a directed edge with capacity $1$ from $i$ to $j$ when $s_i = 1$, $s_j = 0$ and $i < j$, this edge will be cut exactly when both $s_i$ and $s_j$ are red, and they create an inversion. To model the second constraint, for vertices representing $1$'s, add an incoming edge from the source with capacity $r_i$, and an outgoing edge to the sink with capacity $b_i$. For vertices representing $0$'s, this will be vice versa (since red vertices representing $0$'s belong to $T$, the edge from the source to that vertex should have capacity $b_i$, not $r_i$). Now we got ourselves a flow network. The answer to the problem will be $\\sum\\limits_{i=1}^{n} (r_i + b_i) - mincut$, where $mincut$ is the minimum cut in this network. But instead of searching for the minimum cut, we will try to calculate the maximum flow. We are going to do it greedily. Let's process the vertices of the network, from the vertex representing the $1$-st character to the vertex representing the $n$-th character. Every time, we will try to push as much flow as possible through the current vertex. When processing a vertex, first of all, let's try to push $\\min(r_i, b_i)$ flow through the edges connecting the source and the sink with it. Then, if it is a vertex with a character of type $1$, let's remember that we can push $r_i - \\min(r_i, b_i)$ flow through it to successive vertices of type $0$ (let's call this excess flow for that vertex). And if it is a vertex representing a character of type $0$, let's try to push at most $r_i - \\min(r_i, b_i)$ flow into it from the vertices of type $1$ we processed earlier (but no more than $1$ unit of flow from each vertex). But when we process a vertex of type $0$, how do we choose from which vertices of type $1$ we take the flow? It can be shown that we can take $1$ unit of flow from the vertices with the maximum amount of excess flow (the formal proof is kinda long, but the main idea is that every optimal flow assignment can be transformed into the one working in this greedy way without breaking anything). So, to recap, when we process a vertex of type $1$, we remember that it has some excess flow. And when we process a vertex of type $0$, we take $1$ unit of excess flow from several vertices with the maximum amount of excess flow. So, we need a data structure that allows us to process the following queries: add an integer; calculate the number of positive integers in the structure; subtract $1$ from $k$ maximum integers in the structure. Model implementation of this data structure is kinda long (there are easier ways to do it), but I will describe it nevertheless. We will use an explicit-key treap which stores two values in each vertex - an integer belonging to the structure and the quantity of that integer in the structure (so, it's kinda like a map which counts the number of occurrences of each integer). This treap has to support adding $-1$ to all values in some subtree (with lazy propagation). Most operations with it are fairly straightforward, but how do we actually subtract $1$ from $k$ maximum values in the tree? We will do it in the following way: split the treap to extract $k$ maximum elements (let's denote the first treap as the part without $k$ maximums, and the second treap as the part with those $k$ maximums); add $-1$ to the values in the second treap; while the minimum element in the second treap is not greater than the maximum element in the first treap, remove the minimum from the second treap and insert it into the first treap; merge the treaps. It's quite easy to see that if you store the pairs of the form \"element, the number of its occurrences\" in the treap, the third step will require moving at most $2$ elements. And the resulting complexity of every operation with this data structure becomes $O(\\log n)$, so the whole solution works in $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nmt19937 rnd(42);\n\nstruct node\n{\n  long long x;\n  int y;\n  int cnt;\n  int sum;\n  int push;\n  node* l;\n  node* r;\n  node() {};\n  node(long long x, int y, int cnt, int sum, int push, node* l, node* r) : x(x), y(y), cnt(cnt), sum(sum), push(push), l(l), r(r) {};\n};\n\ntypedef node* treap;\ntypedef pair<treap, treap> ptt;\n\nint getSum(treap t)\n{\n  return (t ? t->sum : 0);\n}\n\nint getCnt(treap t)\n{\n  return (t ? t->cnt : 0);\n}\n\ntreap fix(treap t)\n{\n  if(!t) return t;\n  int p = t->push;\n  if(p != 0)\n  {\n    if(t->l) t->l->push += p;\n    if(t->r) t->r->push += p;\n    t->x += p;\n    t->push = 0;\n  }\n  t->sum = getSum(t->l) + t->cnt + getSum(t->r);\n  return t;\n}\n\ntreap merge(treap a, treap b)\n{\n  a = fix(a);\n  b = fix(b);\n  if(!a) return b;\n  if(!b) return a;\n  if(a->y > b->y)\n  {\n    a->r = merge(a->r, b);\n    return fix(a);\n  }\n  else\n  {\n    b->l = merge(a, b->l);\n    return fix(b);\n  }\n}\n\nbool hasKey(treap t, long long x)\n{\n  t = fix(t);\n  if(!t) return false;\n  if(t->x == x) return true;\n  if(t->x < x) return hasKey(t->r, x);\n  return hasKey(t->l, x);\n}\n\nptt splitKey(treap t, long long x)\n{\n  t = fix(t);\n  if(!t) return make_pair(t, t);\n  if(t->x < x)\n  {\n    ptt p = splitKey(t->r, x);\n    t->r = p.first;\n    return make_pair(fix(t), p.second);\n  }\n  else\n  {\n    ptt p = splitKey(t->l, x);\n    t->l = p.second;\n    return make_pair(p.first, fix(t));\n  }\n}\n\nlong long kthMax(treap t, int k)\n{\n  t = fix(t);\n  if(!t) return -1;\n  int sumR = getSum(t->r);\n  if(sumR >= k) return kthMax(t->r, k);\n  if(sumR + t->cnt >= k) return t->x;\n  return kthMax(t->l, k - sumR - t->cnt);\n}\n\nint getCntByKey(treap t, long long x)\n{\n  t = fix(t);\n  if(!t) return 0;\n  if(t->x == x) return t->cnt;\n  if(t->x > x) return getCntByKey(t->l, x);\n  return getCntByKey(t->r, x);\n}\n\ntreap increaseKey(treap t, long long x, int cnt)\n{\n  t = fix(t);\n  if(!t) return t;\n  if(t->x == x)\n  {\n    t->cnt += cnt;\n  }\n  else if(t->x > x)\n  {\n    t->l = increaseKey(t->l, x, cnt);\n  }\n  else\n  {\n    t->r = increaseKey(t->r, x, cnt);\n  }\n  return fix(t);\n}\n\ntreap insert(treap t, long long x, int y, int cnt)\n{\n  t = fix(t);\n  if(!t || t->y < y)\n  {\n    ptt p = splitKey(t, x);\n    treap res = new node(x, y, cnt, cnt, 0, p.first, p.second);\n    return fix(res);\n  }\n  if(t->x > x)\n    t->l = insert(t->l, x, y, cnt);\n  else\n    t->r = insert(t->r, x, y, cnt);\n  return fix(t);\n}\n\ntreap insertMain(treap t, long long x, int cnt)\n{\n  if(hasKey(t, x))\n    return increaseKey(t, x, cnt);\n  else\n    return insert(t, x, rnd(), cnt);\n}\n\ntreap eraseKey(treap t, long long x)\n{\n  t = fix(t);\n  if(!t) return NULL;\n  if(t->x > x)\n  {\n    t->l = eraseKey(t->l, x);\n    return fix(t);\n  }\n  if(t->x < x)\n  {\n    t->r = eraseKey(t->r, x);\n    return fix(t);\n  }\n  treap tnew = merge(t->l, t->r);\n  delete t;\n  return tnew;\n}\n\nptt splitSum(treap t, int k)\n{\n  t = fix(t);\n  if(!t) return make_pair(t, t);\n  if(k == 0) return make_pair(t, treap(NULL));\n  long long x = kthMax(t, k);\n  int cnt = getCntByKey(t, x);\n  t = eraseKey(t, x);\n  ptt p = splitKey(t, x);\n  k -= getSum(p.second);\n  if(k > 0) p.second = merge(new node(x, rnd(), k, k, 0, NULL, NULL), p.second);\n  if(k < cnt) p.first = merge(p.first, new node(x, rnd(), cnt - k, cnt - k, 0, NULL, NULL));\n  return p;\n}\n\nlong long minKey(treap t)\n{\n  t = fix(t);\n  if(!t) return 1e18;\n  if(t->l) return minKey(t->l);\n  return t->x;\n}\n\ntreap decreaseUpToKLargest(treap t, int k, int& res)\n{\n  if(!k) return t;\n  t = fix(t);\n  k = min(k, getSum(t));\n  res = k;\n  ptt p = splitSum(t, k);\n  if(p.second)\n  {\n    p.second->push--;\n    for(int i = 0; i < 2; i++)\n    {\n        long long x = minKey(p.second);\n        int cntMin = getCntByKey(p.second, x);\n        p.second = eraseKey(p.second, x);\n        if(x != 0 && cntMin != 0)\n          p.first = insertMain(p.first, x, cntMin);\n    }\n  }\n  return merge(p.first, p.second);\n}\n\nvoid destroy(treap t)\n{\n  if(!t) return;\n  if(t->l) destroy(t->l);\n  if(t->r) destroy(t->r);\n  delete t;\n}\n\nvoid solve()\n{\n  int n;\n  cin >> n;\n  string s;\n  cin >> s;\n  vector<long long> r(n), b(n);\n  for(int i = 0; i < n; i++) cin >> r[i];\n  for(int i = 0; i < n; i++) cin >> b[i];\n  long long sum = 0;\n  for(int i = 0; i < n; i++) sum += r[i] + b[i];\n  long long flow = 0;\n  treap t = NULL;\n  for(int i = 0; i < n; i++)\n  {\n    long long d = min(r[i], b[i]);\n    flow += d;\n    r[i] -= d;\n    b[i] -= d;\n    if(s[i] == '0')\n    {\n      int add = 0;\n      if(r[i] > 1e9) r[i] = 1e9;\n      t = decreaseUpToKLargest(t, r[i], add);\n      flow += add;\n    }\n    else\n    {\n      if(r[i] != 0) t = insertMain(t, r[i], 1);\n    }\n  }\n  cout << sum - flow << endl;\n}\n\nint main()\n{\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t;\n  cin >> t;\n  for(int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "flows",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1896",
    "index": "A",
    "title": "Jagged Swaps",
    "statement": "You are given a permutation$^\\dagger$ $a$ of size $n$. You can do the following operation\n\n- Select an index $i$ from $2$ to $n - 1$ such that $a_{i - 1} < a_i$ and $a_i > a_{i+1}$. Swap $a_i$ and $a_{i+1}$.\n\nDetermine whether it is possible to sort the permutation after a finite number of operations.\n\n$^\\dagger$ A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Look at the samples. Observe that since we are only allowed to choose $i \\ge 2$ to swap $a_i$ and $a_{i+1}$, it means that $a_1$ cannot be modified by the operation. Hence, $a_1 = 1$ must hold. We can prove that as long as $a_1 = 1$, we will be able to sort the array. Consider the largest element of the array. Let its index be $i$. Our objective is to move $a_i$ to the end of the array. If $i = n$, it means that the largest element is already at the end. Otherwise, since $a_i$ is the largest element, this means that $a_{i-1} < a_i$ and $a_i > a_{i+1}$. Hence, we can do an operation on index $i$ and move the largest element one step closer to the end. We repeatedly do the operation until we finally move the largest element to the end of the array. Then, we can pretend that the largest element does not exist and do the same algorithm for the prefix of size $n - 1$. Hence, we will able to sort the array by doing this repeatedly.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef vector <ll> vi;\nint main() {\n    int t;\n    cin >> t;\n    while (t --> 0) {\n        int n;\n        cin >> n;\n        vi arr(n);\n        for (int i = 0; i < n; i++) {\n            cin >> arr[i];\n        }\n        if (arr[0] == 1) {\n            cout << \"YES\";\n        } else {\n            cout << \"NO\";\n        }\n        cout << '\\n';\n    }\n}",
    "tags": [
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1896",
    "index": "B",
    "title": "AB Flipping",
    "statement": "You are given a string $s$ of length $n$ consisting of characters $A$ and $B$. You are allowed to do the following operation:\n\n- Choose an index $1 \\le i \\le n - 1$ such that $s_i = A$ and $s_{i + 1} = B$. Then, swap $s_i$ and $s_{i+1}$.\n\nYou are only allowed to do the operation \\textbf{at most once} for each index $1 \\le i \\le n - 1$. However, you can do it in any order you want. Find the maximum number of operations that you can carry out.",
    "tutorial": "What happens when $s$ starts with some $\\texttt{B}$ and ends with some $\\texttt{A}$? If the string consists of only $\\texttt{A}$ or only $\\texttt{B}$, no operations can be done and hence the answer is $0$. Otherwise, let $x$ be the smallest index where $s_x = \\texttt{A}$ and $y$ be the largest index where $x_y = \\texttt{B}$. If $x > y$, this means that the string is of the form $s=\\texttt{B}\\ldots\\texttt{BA}\\ldots\\texttt{A}$. Since all the $\\texttt{B}$ are before the $\\texttt{A}$, no operation can be done and hence the answer is also $0$. Now, we are left with the case where $x < y$. Note that $s[1,x-1] = \\texttt{B}\\ldots\\texttt{B}$ and $s[y+1,n] = \\texttt{A}\\ldots\\texttt{A}$ by definition. Since the operation moves $\\texttt{A}$ to the right and $\\texttt{B}$ to the left, this means that $s[1,x - 1]$ will always consist of all $\\texttt{B}$ and $s[y + 1, n]$ will always consist of all $\\texttt{A}$. Hence, no operation can be done from index $1$ to $x - 1$ as well as from index $y$ to $n - 1$. The remaining indices where an operation could be done are from $x$ to $y - 1$. It can be proven that all $y - x$ operations can be done if their order is chosen optimally. Let array $b$ store the indices of $s$ between $x$ and $y$ that contain $\\texttt{B}$ in increasing order. In other words, $x < b_1 < b_2 < \\ldots < b_k = y$ and $b_i = \\texttt{B}$, where $k$ is the number of occurences of $\\texttt{B}$ between $x$ and $y$. For convenience, we let $b_0 = x$. Then, we do the operations in the following order: $b_1 - 1, b_1 - 2, \\ldots, b_0 + 1, b_0,$ $b_2 - 1, b_2 - 2, \\ldots, b_1 + 1, b_1,$ $b_3 - 1, b_3 - 2, \\ldots, b_2 + 1, b_2,$ $\\vdots$ $b_k - 1, b_k - 2, \\ldots, b_{k - 1} + 1, b_k$ It can be seen that the above ordering does operation on all indices between $x$ and $y - 1$. To see why all of the operations are valid, we look at each row separately. Each row starts with $b_i - 1$, which is valid as $s_{b_i} = \\texttt{B}$ and $s_{b_i - 1} = \\texttt{A}$ (assuming that it is not the last operation of the row). Then, the following operations in the same row move $\\texttt{B}$ to the left until position $b_{i - 1}$. To see why the last operation of the row is valid as well, even though $s_{b_{i - 1}}$ might be equal to $\\texttt{B}$ initially by definition, either $i = 1$ which means that $s_{b_0} = s_x = \\texttt{A}$, or an operation was done on index $b_{i - 1} - 1$ in the previous row which moved $\\texttt{A}$ to index $b_{i - 1}$. Hence, all operations are valid.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nchar s[200005];\n \nsigned main() {\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0); cout.tie(0);\n\tint tc, n; cin >> tc;\n\twhile (tc--) {\n\t\tcin >> n; s[n + 1] = 'C';\n\t\tfor (int i = 1; i <= n; ++i) cin >> s[i];\n\t\tint pt1 = 1, pt2 = 1, ans = 0;\n\t\twhile (s[pt1] == 'B') ++pt1, ++pt2;\n\t\twhile (pt1 <= n) {\n\t\t\tint cntA = 0, cntB = 0;\n\t\t\twhile (s[pt2] == 'A') ++pt2, ++cntA;\n\t\t\twhile (s[pt2] == 'B') ++pt2, ++cntB;\n\t\t\tif (s[pt2 - 1] == 'B') ans += pt2 - pt1 - 1;\n\t\t\tif (cntB) pt1 = pt2 - 1;\n\t\t\telse break;\n\t\t}\n\t\tcout << ans << '\\n';\n\t}\n}",
    "tags": [
      "greedy",
      "strings",
      "two pointers"
    ],
    "rating": 900
  },
  {
    "contest_id": "1896",
    "index": "C",
    "title": "Matching Arrays",
    "statement": "You are given two arrays $a$ and $b$ of size $n$. The beauty of the arrays $a$ and $b$ is the number of indices $i$ such that $a_i > b_i$.\n\nYou are also given an integer $x$. Determine whether it is possible to rearrange the elements of $b$ such that the beauty of the arrays becomes $x$. If it is possible, output one valid rearrangement of $b$.",
    "tutorial": "Consider a greedy algorithm. For simplicity, assume that both arrays $a$ and $b$ are sorted in increasing order. The final answer can be obtained by permuting the answer array using the same permutation to permute sorted array $a$ to the original array $a$. Claim: If the rearrangement $b_{x + 1}, b_{x + 2}, \\ldots, b_n, b_1, b_2, \\ldots, b_x$ does not have beauty $x$, it is not possible to rearrange $b$ to make the beauty equals to $x$. Proof: Suppose there exists an alternative rearrangement different from above represented by permutation $p$ where $b_{p_1}, b_{p_2}, \\ldots, b_{p_n}$ results in a beauty of $x$. Let array $q$ represent the $x$ indices where $a_i > b_{p_i}$ in increasing order. In other words, $1 \\le q_1 < q_2 < \\ldots < q_x \\le n$ and $a_{q_i} > b_{p_{q_i}}$. Let $i$ be the largest index where $q_i \\neq n - i + 1$ ($q_i < n - i + 1$ also holds due to strict inequality above). We know that $a_{q_i} > b_{p_{q_i}}$ and $a_{n - i + 1} \\le b_{p_{n - i + 1}}$. Since $a$ is sorted and $q_i < n - i + 1$, we have $a_{q_i} \\le a_{n - i + 1}$, and hence, $a_{n - i + 1} > b_{p_{q_i}}$ and $a_{q_i} \\le b_{p_{n - i + 1}}$. This means that we can swap $p_{q_i}$ with $p_{n - i + 1}$ without changing the beauty of the array, while allowing $q_i = n - i + 1$. Hence, by doing the swapping repeatedly, we will get $q_i = n - i + 1$ for all $i$ between 1 and $x$. An alternative interpretation to the result above is that we managed to obtain a solution where for all $i$ between $1$ and $n - x$, we have $a_i \\le b_{p_i}$. On the other hand, for all $i$ between $n - x + 1$ and $n$, we have $a_i > b_{p_i}$. Let $i$ be the largest index between $1$ and $n - x$ where $p_i \\neq i + x$ ($p_i < i + x$ due to maximality). Then, let $j$ be the index where $p_j = i + x$. Consider two cases: $j \\le n - x$. Since $i$ is the largest index where $p_i \\neq i + x$, this means that $j < i$ and hence $a_j \\le a_i$. We have $a_i \\le b_{p_i} \\le b_{i + x} = b_{p_j}$ and $a_j \\le a_i \\le b_{p_i}$. Hence, we can swap $p_i$ and $p_j$ without changing the beauty of the array, while allowing $p_i = i + x$. $j > n - x$. We have $a_i \\le b_{p_i} \\le b_{i + x} = b_{p_j}$ and $a_j > b_{p_j} = b_{i + x} > b_{p_i}$. Hence, we can swap $p_i$ and $p_j$ without changing the beauty of the array, while allowing $p_i = i + x$. By repeating the above repeatedly, we can obtain a solution where $p_i = i + x$ for all $i$ between $1$ and $n - x$. Let $i$ be the smallest index between $n - x + 1$ and $n$ where $p_i \\neq i - n + x$ ($p_i > i - n + x$ by minimality). Then, let $j$ be the index where $p_j = i - n + x$. Note that $j > n - x$ as well since $p_i = i + x$ for all $i$ between $1$ and $n - x$. Since $i$ is the smallest index where $p_i \\neq i - n + x$, this means that $i < j$ and hence $a_i \\le a_j$. We have $a_i > b_{p_i} \\ge b_{i - n + x} = b_{p_j}$ and $a_j \\ge a_i > b_{p_i}$. Hence, we can swap $p_i$ and $p_j$ without changing the beauty of the array, while allowing $p_i = i - n + x$. By doing this repeatedly, we can obtain a solution where $p_i = i - n + x$ for all $i$ between $n - x + 1$ and $n$. Now, $p = [x + 1, x + 1, \\ldots, n, 1, 2, \\ldots, x]$, which matches the rearrangement in our claim.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n \n#define REP(i, s, e) for (int i = (s); i < (e); i++)\n#define RREP(i, s, e) for (int i = (s); i >= (e); i--)\n \nconst int INF = 1000000005;\nconst int MAXN = 200005;\n \nint t;\nint n, x;\nint a[MAXN], b[MAXN], aid[MAXN];\nint ans[MAXN];\n \nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    cin >> t;\n    while (t--) {\n        cin >> n >> x;\n        REP (i, 0, n) {\n            cin >> a[i];\n        }\n        REP (i, 0, n) {\n            cin >> b[i];\n        }\n        iota(aid, aid + n, 0);\n        sort(aid, aid + n, [&] (int l, int r) {\n                return a[l] < a[r];\n                });\n        sort(b, b + n);\n        REP (i, 0, x) {\n            ans[aid[n - x + i]] = b[i];\n        }\n        REP (i, x, n) {\n            ans[aid[i - x]] = b[i];\n        }\n        REP (i, 0, n) {\n            x -= a[i] > ans[i];\n        }\n        if (x == 0) {\n            cout << \"YES\\n\";\n            REP (i, 0, n) {\n                cout << ans[i] << ' ';\n            }\n            cout << '\\n';\n        } else {\n            cout << \"NO\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1896",
    "index": "D",
    "title": "Ones and Twos",
    "statement": "You are given a $1$-indexed array $a$ of length $n$ where each element is $1$ or $2$.\n\nProcess $q$ queries of the following two types:\n\n- \"1 s\": check if there exists a subarray$^{\\dagger}$ of $a$ whose sum equals to $s$.\n- \"2 i v\": change $a_i$ to $v$.\n\n$^{\\dagger}$ An array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.",
    "tutorial": "Consider some small examples and write down every possible value of subarray sums. Can you see some patterns? Denote $s[l,r]$ as the sum of subarray from $l$ to $r$. Claim: If there is any subarray with sum $v\\ge 2$, we can find a subarray with sum $v-2$. Proof: Suppose $s[l,r]=v$, consider 3 cases: $a[l]=2$, we have $s[l+1,r]=v-2$. $a[r]=2$, we have $s[l,r-1]=v-2$. $a[l]=a[r]=1$, we have $s[l+1,r-1]=v-2$. So to check if there exists a subarray whose sum equals $v$, we can find the maximum subarray sum having the same parity with $v$ and compare it with $v$. The case where $(s[1,n]-v)\\%2=0$ is obvious, suppose the opposite happens. If array $a$ is full of $2$-s, the answer is $\\texttt{NO}$. Otherwise, let $x$ and $y$ be the positions of the first $1$ and last $1$ in $a$. Any subarray with $l\\le x\\le y\\le r$ will have a different parity with $v$. So we will compare $\\max(s[x+1, n],s[1,y-1])$ with $v$ to get the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    int t; cin >> t;\n    while (t--) {\n        int n, q; cin >> n >> q;\n        vector<int> a(n);\n        set<int> pos;\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n            if (a[i] == 1) pos.insert(i);\n        }\n        while (q--) {\n            int cmd; cin >> cmd;\n            if (cmd == 1) {\n                int v; cin >> v;\n                int num = pos.size();\n                if ((v - num) & 1) {\n                    if (num == 0) cout << \"NO\";\n                    else {\n                        int s1 = 2 * *pos.rbegin() - (num - 1);\n                        int s2 = 2 * (n - *pos.begin() - 1) - (num - 1);\n                        if (v <= max(s1, s2)) cout << \"YES\";\n                        else cout << \"NO\";\n                    }\n                } else {\n                    if (v <= 2 * n - num) cout << \"YES\";\n                    else cout << \"NO\";\n                }\n                cout << '\\n';\n            } else {\n                int i; cin >> i; i--;\n                pos.erase(i);\n                cin >> a[i];\n                if (a[i] == 1) pos.insert(i);\n            }\n        }\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "math",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1896",
    "index": "E",
    "title": "Permutation Sorting",
    "statement": "You are given a permutation$^\\dagger$ $a$ of size $n$. We call an index $i$ good if $a_i=i$ is satisfied. After each second, we rotate all indices that are not good to the right by one position. Formally,\n\n- Let $s_1,s_2,\\ldots,s_k$ be the indices of $a$ that are \\textbf{not} good in increasing order. That is, $s_j < s_{j+1}$ and if index $i$ is not good, then there exists $j$ such that $s_j=i$.\n- For each $i$ from $1$ to $k$, we assign $a_{s_{(i \\% k+1)}} := a_{s_i}$ all at once.\n\nFor each $i$ from $1$ to $n$, find the first time that index $i$ becomes good.\n\n$^\\dagger$ A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "For each index $i$ from $1$ to $n$, let $h_i$ denote the number of cyclic shifts needed to move $a_i$ to its correct spot. In other words, $h_i$ is the minimum value such that $(i + h_i - 1)\\ \\%\\ n + 1 = a_i$. How can we get the answer from $h_i$? For convenience, we will assume that the array is cyclic, so $a_j = a_{(j - 1)\\ \\%\\ n + 1}$. The answer for each index $i$ from $1$ to $n$ is $h_i$ (defined in hint 1) minus the number of indices $j$ where $i < j < i + h_i$ and $i < a_j < i + h_i$ (or $i < a_j + n < i + h_i$ to handle cyclic case when $i + h_i > n$). This is because the value that we are calculating is equal to the number of positions that $a_i$ will skip during the rotation as the index is already good. To calculate the above value, it is convenient to define an array $b$ of size $2n$ where $b_i = a_i$ for all $i$ between $1$ to $n$, and $b_i = a_{i - n} + n$ for all $i$ between $n + 1$ to $2n$ to handle cyclicity. We will loop from $i = 2n$ to $i = 1$, and do a point increment to position $a_i$ if $a_i \\ge i$, otherwise, do a point increment to position $a_i + n$. Then, to get the answer for index $i$, we do a range sum query from $i + 1$ to $i + h_i - 1$. Point increment and range sum query can be done using a binary indexed tree in $O(\\log n)$ time per query/update. Hence, the problem can be solved in $O(n\\log n)$ time.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n \n#define REP(i, s, e) for (int i = (s); i < (e); i++)\n#define RREP(i, s, e) for (int i = (s); i >= (e); i--)\n#define ALL(_a) _a.begin(), _a.end()\n#define SZ(_a) (int) _a.size()\n \nconst int INF = 1000000005;\nconst int MAXN = 1000005;\n \nint t;\nint n;\nint p[MAXN];\nint ans[MAXN];\n \nint fw[MAXN * 2];\nvoid incre(int i, int x) {\n    for (; i <= 2 * n; i += i & -i) {\n        fw[i] += x;\n    }\n}\nint qsm(int i) {\n    int res = 0;\n    for (; i > 0; i -= i & -i) {\n        res += fw[i];\n    }\n    return res;\n}\ninline int qsm(int s, int e) {\n    return qsm(e) - qsm(s - 1);\n}\n \nint main() {\n#ifndef DEBUG\n    ios::sync_with_stdio(0), cin.tie(0);\n#endif\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        REP (i, 1, n + 1) {\n            cin >> p[i];\n        }\n        REP (i, 0, 2 * n + 5) {\n            fw[i] = 0;\n        }\n        vector<pair<int, int>> rgs;\n        REP (i, 1, n + 1) {\n            if (i <= p[i]) {\n                rgs.push_back({i, p[i]});\n                rgs.push_back({i + n, p[i] + n});\n            } else {\n                rgs.push_back({i, p[i] + n});\n            }\n        }\n        sort(ALL(rgs), greater<pair<int, int>>());\n        for (auto [l, r] : rgs) {\n            if (l <= n) {\n                ans[p[l]] = r - l - qsm(l, r);\n            }\n            incre(r, 1);\n        }\n        REP (i, 1, n + 1) {\n            cout << ans[i] << ' ';\n        }\n        cout << '\\n';\n    }\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1896",
    "index": "F",
    "title": "Bracket Xoring",
    "statement": "You are given a binary string $s$ of length $2n$ where each element is $\\mathtt{0}$ or $\\mathtt{1}$. You can do the following operation:\n\n- Choose a balanced bracket sequence$^\\dagger$ $b$ of length $2n$.\n- For every index $i$ from $1$ to $2n$ in order, where $b_i$ is an open bracket, let $p_i$ denote the minimum index such that $b[i,p_i]$ is a balanced bracket sequence. Then, we perform a range toggle operation$^\\ddagger$ from $i$ to $p_i$ on $s$. Note that since a balanced bracket sequence of length $2n$ will have $n$ open brackets, we will do $n$ range toggle operations on $s$.\n\nYour task is to find a sequence of no more than $10$ operations that changes all elements of $s$ to $\\mathtt{0}$, or determine that it is impossible to do so. Note that you do \\textbf{not} have to minimize the number of operations.\n\nUnder the given constraints, it can be proven that if it is possible to change all elements of $s$ to $\\mathtt{0}$, there exists a way that requires no more than $10$ operations.\n\n$^\\dagger$ A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters $+$ and $1$. For example, sequences \"(())()\", \"()\", and \"(()(()))\" are balanced, while \")(\", \"(()\", and \"(()))(\" are not.\n\n$^\\ddagger$ If we perform a range toggle operation from $l$ to $r$ on a binary string $s$, then we toggle all values of $s_i$ such that $l \\leq i \\leq r$. If $s_i$ is toggled, we will set $s_i := \\mathtt{0}$ if $s_i = \\mathtt{1}$ or vice versa. For example, if $s=\\mathtt{1000101}$ and we perform a range toggle operation from $3$ to $5$, $s$ will be changed to $s=\\mathtt{1011001}$.",
    "tutorial": "The operation is equivalent to toggling $s$ at every odd $i$ where $b_i$ is an open bracket and every even $i$ where $b_i$ is a closed bracket. Suppose there are $x$ open brackets and $y$ close brackets between positions $1$ and $i$. Note that $x \\ge y$ by definition of balanced bracket sequences. - Case 1: $b_i$ is an open bracket. Position $i$ will be toggled exactly $x - y$ times as $y$ of the open brackets will be matched before position $i$, and the remaining $x - y$ open brackets will only be matched after position $i$. This means that position $i$ will be toggled only if $x - y$ is odd, and hence, $x - y + 2y = x + y = i$ must be odd as well. - Case 2: $b_i$ is a close bracket. Position $i$ will be toggled exactly $x - y + 1$ times as $y - 1$ of the open brackets will be matched before $i$, $1$ of the open bracket will be matched with position $i$, and the remaining $x - y$ open brackets will be matched after position $i$. This means that position $i$ will be toggled only if $x - y$ is even, and hence, $x - y + 2y = x + y = i$ must be even as well. Every operation will always toggle $s_1$ and $s_n$. Furthermore, every operation will always toggle an even number of positions. If $s$ is toggled at an open bracket, $s$ will be toggled at its matching close bracket as well. If $s_1 \\neq s_n$ or there is an odd number of $\\texttt{1}$s in $s$, it is not possible to change all elements of $s$ to $\\texttt{0}$. Otherwise, it is always possible. If it is possible to change all elements of $s$ to $\\texttt{0}$, at most $3$ operations are needed. From hint 3, we know the cases where it is impossible to change all elements of $s$ to $\\texttt{0}$. We will now only consider the case where it is possible to change all elements of $s$ to $\\texttt{0}$. Using hint 1, we can easily check whether it is possible to change all elements of $s$ to $\\texttt{0}$ using only one operation by first constructing the bracket sequence and then checking whether the resultant bracket sequence is balanced. From now on, we will assume that it is not possible to change all elements of $s$ to $\\texttt{0}$ using one operation. Suppose $s_1 = s_n = \\texttt{1}$. We know from hint 2 that each operation will always toggle $s_1$ and $s_n$, so since it is not possible to change all elements of $s$ to $\\texttt{0}$ using one operation, we will need three operations. If we let the first operation be $b=\\texttt{(()()}\\ldots\\texttt{()())}$, $s_1$ and $s_n$ will be toggled while the remaining elements stay the same. Now, $s_1 = s_n = \\texttt{0}$, so if we can solve this case using only two operations, it means that we can solve the $s_1 = s_n = \\texttt{1}$ case using only three operations. To solve the final case where $s_1 = s_n = \\texttt{0}$, we will look at a special balanced bracket sequences $b = \\texttt{(()()}\\ldots\\texttt{()())}$. Notice that if we do an operation using this bracket sequence, only $s_1$ and $s_n$ will be toggled. Suppose there exist an index $i$ between $2$ and $2n - 2$ where we want to toggle both $s_i$ and $s_{i + 1}$. We can take the special balanced bracket sequence $b = \\texttt{(()()}\\ldots\\texttt{()())}$, then swap $b_i$ and $b_{i + 1}$. This will always result in a balanced bracket sequence that will toggle $s_1$, $s_n$, as well as the desired $s_i$ and $s_{i + 1}$. This will allow us to change all elements of $s$ to $\\texttt{0}$ in $2n$ moves as we can scan from $i = 2$ to $i = 2n - 2$ and do an operation toggling $s_i$ and $s_{i+1}$ if $s_i = \\texttt{1}$. Since there is an even number of $\\texttt{1}$s in $s$ from hint 3, toggling adjacent positions will always change all elements of $s$ to $\\texttt{0}$. To reduce the number of operations from $2n$ to $2$, notice that a lot of the operations can be parallelized into a single operation. Let $A_0$ represent the set of even indices between $2$ and $2n - 2$ where we want to toggle $s_i$ and $s_{i + 1}$. Similarly, let $A_1$ represent the set of odd indices between $2$ and $2n - 2$ where we want to toggle $s_i$ and $s_{i + 1}$. In a single operation, we can take the special balanced bracket sequence $b = \\texttt{(()()}\\ldots\\texttt{()())}$, and swap $b_i$ and $b_{i + 1}$ for all $i$ that is in the set $A_0$. Since $A_0$ only contains even indices, the swaps are non-intersecting, and hence, the resultant bracket sequence will still be balanced and $s_1$, $s_n$, as well as $s_i$ and $s_{i + 1}$ will be toggled for all the desired even indices $i$. We can use the same strategy with $A_1$, starting with the same special balanced bracket sequence and then swapping $b_i$ and $b_{i + 1}$ for all $i$ that is in set $A_1$. Hence, after using these two operations, all elements of $s$ will change to $\\texttt{0}$. We will demonstrate a way to use $2$ bracket sequence to solve any binary string whose first and last element is $\\texttt{0}$ and who also has an even number of $\\texttt{1}$s. Defined the balance of an (incomplete) bracket sequence as the number of open brackets minus the number of closed brakcets. For example, ((() has balance $2$, (()()(( has balance $3$ and () has balance $0$. Using hint $1$ we can see that the resulting binary string will contain 0 at position $i$ iff the character at position $i$ in both bracket sequences is the same. Suppose the balance of your current bracket sequences is $(a,b)$. You can change it $(a\\pm 1, b\\pm 1)$. If both $\\pm$ have the same parity, then the resulting binary string will contain $\\texttt{0}$ at that position. Now, we will demonstrate a greedy algorithm. $(0,0) \\to (1,1) \\to (0,2),(2,2) \\to (1,3),(1,1) \\to (0,2),(2,2) \\to \\ldots \\to (1,1) \\to (0,0)$ One can show by a simple parity argument that the second last balance must necessarily be $(1,1)$ since the number of $\\texttt{1}$s in the string is even. Similar to solution 2, we will demonstrate a way to use $2$ bracket sequence to solve any binary string whose first and last element is $\\texttt{0}$ and who also has an even number of $\\texttt{1}$s. Using the same greedy argument in solution 2 (or by guessing), we know that we can always use two bracket sequences where the number of open brackets minus the number of close brackets is always between $0$ and $3$ for all prefixes of the bracket sequence. For convenience, we will define \"balance\" as the number of open brackets minus the number of close brackets. Hence, we can do dynamic programming using the states $dp[i][balance1][balance2]$ which returns whether it is possible to create two bracket sequences $b1$ and $b2$ of length $i$ such that the balance of $b1$ and $b2$ are $balance1$ and $balance2$ respectively and $s[1, i]$ becomes all $\\mathtt{0}$. The transition can be done by making sure that the balances stay between $0$ and $3$ and that $b1_i \\neq b2_i$ if $s_i=\\mathtt{1}$ and vice versa.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(int n, string s) {\n\tvector<int> a;\n\tfor (char &i : s) {\n\t\ta.push_back(i & 1);\n\t}\n\t\n\tif (a.front() != a.back()) {\n\t\tcout << -1 << endl;\n\t\treturn ;\n\t}\n\t\n\tif (count(a.begin(), a.end(), 1) % 2) {\n\t\tcout << -1 << endl;\n\t\treturn ;\n\t}\n\t\n\tbool flipped = false;\n\tif (a.front() == 1 && a.back() == 1) {\n\t\tfor (int &i : a) i ^= 1;\n\t\tflipped = true;\n\t}\n\t\n\tstring l(2 * n, '-'), r(2 * n, '-');\n\tint cnt = 0;\n\tfor (int i = 0; i < 2 * n; i++) {\n\t\tif (a[i]) {\n\t\t\tl[i] = (cnt) ? '(' : ')';\n\t\t\tr[i] = (cnt ^ 1) ? '(' : ')';\n\t\t\tcnt ^= 1;\n\t\t}\n\t}\n\t\n\tint tot = count(a.begin(), a.end(), 0) / 2;\n\tcnt = 0;\n\tfor (int i = 0; i < 2 * n; i++) {\n\t\tif (!a[i]) {\n\t\t\tif (cnt < tot) l[i] = '(', r[i] = '(';\n\t\t\telse l[i] = ')', r[i] = ')';\n\t\t\tcnt++;\n\t\t}\n\t}\n\t\n\tif (flipped) {\n\t\tcout << 3 << endl;\n\t\tcout << l << endl;\n\t\tcout << r << endl;\n\t\tfor (int i = 0; i < n; i++) cout << \"()\";\n\t\tcout << endl;\n\t} else {\n\t\tcout << 2 << endl;\n\t\tcout << l << endl;\n\t\tcout << r << endl;\n\t}\n}\n\nint main() {\t\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tstring s;\n\t\tcin >> s;\n\t\tsolve(n, s);\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1896",
    "index": "G",
    "title": "Pepe Racing",
    "statement": "This is an interactive problem.\n\nThere are $n^2$ pepes labeled $1, 2, \\ldots, n^2$ with \\textbf{pairwise distinct} speeds. You would like to set up some races to find out the relative speed of these pepes.\n\nIn one race, you can choose exactly $n$ distinct pepes and make them race against each other. After each race, you will only know the \\textbf{fastest} pepe of these $n$ pepes.\n\nCan you order the $n^2-n+1$ fastest pepes in \\textbf{at most} $2n^2 - 2n + 1$ races? Note that the slowest $n - 1$ pepes are indistinguishable from each other.\n\nNote that the interactor is \\textbf{adaptive}. That is, the relative speeds of the pepes are not fixed in the beginning and may depend on your queries. But it is guaranteed that at any moment there is at least one initial configuration of pepes such that all the answers to the queries are consistent.",
    "tutorial": "Find the fastest pepe in $n + 1$ queries. Divide $n^2$ pepes into $n$ groups $G_1, G_2, \\dots, G_n$. For each group $G_i$, use $1$ query to find the fastest pepe in the group, let's call him the head of $G_i$. Finally, use $1$ query to find the fastest pepe of all the heads. After knowing the fastest pepe, find the second fastest pepe in $n + 1$ queries. Just remove the fastest pepe and repeat the process from hint 1. One of the groups will have size $n - 1$, but we can \"steal\" one non-head pepe from another already-queried group. Note that the above process for Hint 2 uses a lot of repeated queries. Can we optimize it to $2$ queries? Assume that the fastest pepe is the head of $G_i$. After removing him, we can recalculate the head of $G_i$ using $1$ query similar to hint 2. Then, use the second query on all the heads, similar to the last query of hint 1. Solve the problem using $2n^2 - n + 1$ queries. Our algorithm has three phases: Phase 1: Divide $n^2$ pepes into $n$ groups $G_1, G_2, \\dots, G_n$. For each group $G_i$, use $1$ query to find the fastest pepe in the group, let's call this guy the head of $G_i$. Phase 2: Until there are $2n - 1$ pepes, repeat these two steps: Use $1$ query to find the fastest pepe of the heads of all groups, then remove him. Assume that this pepe is the head of $G_i$. Steal non-head pepes from other groups so that $|G_i| = n$, then use $1$ query to recalculate its head. Use $1$ query to find the fastest pepe of the heads of all groups, then remove him. Assume that this pepe is the head of $G_i$. Steal non-head pepes from other groups so that $|G_i| = n$, then use $1$ query to recalculate its head. Phase 3: Until there are $n - 1$ pepes, repeatedly find the fastest pepe using $2$ queries (or $1$ if there are only $n$ pepes left), then remove him. Total number of queries is $n + 2(n^2 - 2n + 1) + 2(n - 1) + 1 = 2n^2 - n + 1$. Call a pepe slow if it does not belong in the fastest $n^2 - n + 1$ pepes. Note that there are $n - 1$ slow pepes, and we do not care for their relative speed. After each query, we know that the fastest pepe cannot be slow. We use the algorithm in hint 4 until there are $2n - 1$ pepes left. Since the head of $n$ groups cannot be slow, we are left with exactly $(2n - 1) - n = n - 1$ candidates for slow pepes. Once we determine the $n - 1$ slow pepes, we only need to find the ranking of the other $n$ pepes, which can be done using $n - 1$ queries. Total number of queries is $n + 2(n^2 - 2n + 1) + (n - 1) = 2n^2 - 2n + 1$. We will try to decrease the number of queries based on the fact that we can omit one query for recalculation when the size of a group decreases from $2$ to $1$. We modify the algorithm in hint 4 to maintain an invariant: $|G_i| - |G_j| \\le 1$ $\\forall \\, 1 \\le i < j \\le n$. In other words, we want to make the sizes of these groups as balanced as possible. To maintain this, whenever we have $|G_j| - |G_i| = 2$ after removing some pepe, we can transfer any non-head pepe from $G_j$ to $G_i$ to balance these groups out. Next, to recalculate the head of $G_i$, we will \"borrow\" instead of \"steal\" from other groups. If the fastest pepe is borrowed from $G_j$, then we transfer a random non-head pepe in $G_i$ back to $G_j$. This works since the head of $G_j$ is faster than the head of $G_i$, which in turn is faster than the random pepe. Finally, when there are $2n$ pepes left, all groups have the size of $2$, and we only need to use $1$ query for each pepe from later on. Total number of queries is $n + 2(n^2 - 2n) + (n + 1) = 2n^2 - 2n + 1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nint n;\nvector<int> v[25];\n\nint ask(vector<int> v){\n\tcout<<\"? \"; for (auto it:v) cout<<it<<\" \"; cout<<endl;\n\tint res; cin>>res;\n\treturn res;\n}\n\nvector<int> fix(vector<int> v){\n\tint t=ask(v);\n\trep(x,0,n) if (v[x]==t) swap(v[0],v[x]);\n\treturn v;\n}\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tint TC;\n\tcin>>TC;\n\twhile (TC--){\n\t\tcin>>n;\n\t\trep(x,0,n){\n\t\t\tv[x].clear();\n\t\t\trep(y,1,n+1) v[x].pub(x*n+y);\n\t\t}\n\t\t\n\t\trep(x,0,n) v[x]=fix(v[x]);\n\t\t\n\t\tvector<int> ans;\n\t\trep(x,0,n*n-2*n+1){\n\t\t\tvector<int> t;\n\t\t\trep(x,0,n) t.pub(v[x][0]);\n\t\t\tint best=ask(t);\n\t\t\t\n\t\t\tint idx=-1;\n\t\t\trep(x,0,n) if (t[x]==best) idx=x;\n\t\t\t\n\t\t\tans.pub(best);\n\t\t\tv[idx].erase(v[idx].begin());\n\t\t\t\n\t\t\trep(x,0,n) if (x!=idx){\n\t\t\t\twhile (sz(v[x])>1 && sz(v[idx])<n){\n\t\t\t\t\tv[idx].pub(v[x].back());\n\t\t\t\t\tv[x].pob();\n\t\t\t\t}\n\t\t\t}\n\t\t\tv[idx]=fix(v[idx]);\n\t\t}\n\t\t\n\t\tvector<int> a,b;\n\t\trep(x,0,n){\n\t\t\trep(y,0,sz(v[x])){\n\t\t\t\tif (y==0) a.pub(v[x][y]);\n\t\t\t\telse b.pub(v[x][y]);\n\t\t\t}\n\t\t}\n\t\tset<int> bad=set<int>(all(b));\n\t\t\n\t\trep(x,0,n-1){\n\t\t\ta=fix(a);\n\t\t\tans.pub(a[0]);\n\t\t\ta.erase(a.begin());\n\t\t\ta.pub(b.back()); b.pob();\n\t\t}\n\t\t\n\t\tfor (auto it:a) if (!bad.count(it)) ans.pub(it);\n\t\t\n\t\tcout<<\"! \"; for (auto it:ans) cout<<it<<\" \"; cout<<endl;\n\t}\n\t\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "interactive",
      "sortings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1896",
    "index": "H2",
    "title": "Cyclic Hamming (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $k$. You can make hacks only if all versions of the problem are solved.}\n\nIn this statement, all strings are $0$-indexed.\n\nFor two strings $a$, $b$ of the same length $p$, we define the following definitions:\n\n- The hamming distance between $a$ and $b$, denoted as $h(a, b)$, is defined as the number of positions $i$ such that $0 \\le i < p$ and $a_i \\ne b_i$.\n- $b$ is a cyclic shift of $a$ if there exists some $0 \\leq k < p$ such that $b_{(i+k) \\bmod p} = a_i$ for all $0 \\le i < p$. Here $x \\bmod y$ denotes the remainder from dividing $x$ by $y$.\n\nYou are given two binary strings $s$ and $t$ of length $2^{k+1}$ each. Both strings may contain missing characters (denoted by the character '?'). Your task is to count the number of ways to replace the missing characters in both strings with the characters '0' or '1' such that:\n\n- Each string $s$ and $t$ contains exactly $2^k$ occurrences of each character '0' and '1'\n- $h(s, c) \\ge 2^k$ for all strings $c$ that is a cyclic shift of $t$.\n\nAs the result can be very large, you should print the value modulo $998\\,244\\,353$.",
    "tutorial": "For any $c$ which is a cyclic shift of $t$, what will happen if $h(s,c)>2^k$? Try finding some useful relationship between $1$-s of $s$ and $1$-s of $c$. There are exactly $n/2$ positions $i$ such that $s[i]=c[i]=1$. Think about polynomial multiplication. Consider $S\\cdot T$, where $S=\\sum s[i]x^i$ and $T=\\sum t[2n-i-1]x^i$ (reversed coefficients). What are some properties that the coefficients of $S\\cdot T$ tell us? Denote $A=S\\cdot T$, we have $A[x^i]+A[x^{i+2n}]=n/2$. Try factoring $S\\cdot T$ into some irreducible polynomials. Sort $0,1,\\ldots,2n-1$ based on their bit-reversal values and build a binary tree on top of it. What condition should be satisfied on each level of the tree? Consider the polynomial product $A=S\\cdot T$, where $S=\\sum s[i]x^i$ and $T=\\sum t[2n-i-1]x^i$ (reversed coefficients). Claim 1. For all $0\\le i<2n$, we have $A[x^i]+A[x^{i+2n}]=n/2$, where $A[x^k]$ denote the coefficient of $x^k$ in $A$. Claim 2. We can express $A=(x+1)(x^2+1)(x^4+1)\\ldots (x^n+1)(n/2+C(x-1))$ where $C$ is some polynomial with degree not greater than $2n-2$. $\\begin{align} &(x+1)(x^2+1)(x^4+1)\\ldots (x^n+1)(n/2+C(x-1))\\\\ =\\ &C(x^{2n}-1)+n/2\\cdot (x^0+x^1+x^2+\\ldots+x^{2n-1}) \\end{align}$ It is easy to see that this satisfies claim 1. Claim 3. Since $x^{2^p}+1$ is cyclotomic polynomial and hence irreducible for all $p$, each factor in $x+1,x^2+1,\\ldots,x^n+1$ must divide at least one of $S$ and $T$. And under the constraints that each of $s$ and $t$ must have exactly $n$ $1$-s, this condition is also sufficient. Let $A=(x+1)(x^2+1)(x^4+1)\\ldots (x^n+1)\\cdot D$. We have $A(1)=n^2$, hence $D(1)=n/2$, which means that $D$ has the form of $n/2+C(x-1)$. Therefore $A$ satisfies claim 2. Recall $n=2^k$, define $f_s(mask)$ ($0\\le mask<2n$) as the number of string $s$ such that for each $p$ where $p$-th bit of $mask$ is on, $S$ is divisible by $x^{p}+1$. Define $f_t$ similarly for $T$. Define $f^{\\prime}_t$ such that $f^{\\prime}_t(mask)=f_t(mask\\oplus (2n-1))$ where $\\oplus$ denotes bitwise XOR. The answer to the problem is $\\displaystyle\\sum_{mask} f_s(mask)\\cdot \\mu(f^{\\prime}_t(mask))$ where $\\mu$ denote Mobius transform. The reason we need Mobius transform is that $mask_s$ does not represent all divisors, just a subset of it. Let rearrange elements of $s$ into a new array $s^{\\prime}$ so that $s^{\\prime}[\\text{reverse_bit}(i)]=s[i]$ (for example, with $n=8$, the new order will be $[0,8,4,12,2,6,10,14,1,9,5,13,3,11,7,15]$). Construct a perfect binary tree based on the array $s^{\\prime}$. This binary will have $k+2$ levels from $0$ to $k+1$, starting at the root. Claim 4. $S$ is divisible by $x^{2^p}+1$ if only if for every tree node at $p$-th level, the number of $1$-s of $s^{\\prime}$ under both children are equal (the proof is left as an exercise for readers). Group the positions by the remainder when divided by $2^p$, find the necessary condition for each group, and consider its position on the tree. Consider the following dynamic programming: $dp_s[i][mask][num]$, where the levels in $mask$ satisfy claim 4 and $num$ is the number of $1$-s under $i$-th node on the tree. Denote $l$ as level of $i$-th node, transitions are: $dp_s[i][mask][num_1+num_2]\\text{ += }dp_s[2i][mask][num_1]\\cdot dp_s[2i+1][mask][num_2]$ $dp_s[i][mask+2^l][2\\cdot num]\\text{ += }dp_s[2i][mask][num]\\cdot dp_s[2i+1][mask][num]$ The above dp took $\\mathcal{O}(n^3)$, which is sufficient to solve the easy version. To solve the hard version, we will optimize the above transitions: The first transition is actually the convolution of $dp_s[2i][mask]$ and $dp_s[2i+1][mask]$, we can use FFT to optimize it. In the second transition, because $num$ is multiplied by $2$ every time, we can omit it and just make the transition to $dp_s[i][mask+2^l][num]$, reduce the length of $dp_s[i][mask+2^l]$ by two. By careful analysis, we can show that the time complexity is now $\\mathcal{O}(3^k\\cdot k)$ (recall $n=2^k$) with a fair constant factor, which solved the hard version.",
    "tags": [
      "brute force",
      "dp",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1898",
    "index": "A",
    "title": "Milica and String",
    "statement": "Milica has a string $s$ of length $n$, consisting only of characters A and B. She wants to modify $s$ so it contains \\textbf{exactly} $k$ instances of B. In one operation, she can do the following:\n\n- Select an integer $i$ ($1 \\leq i \\leq n$) and a character $c$ ($c$ is equal to either A or B).\n- Then, replace \\textbf{each} of the first $i$ characters of string $s$ (that is, characters $s_1, s_2, \\ldots, s_i$) with $c$.\n\nMilica does not want to perform too many operations in order not to waste too much time on them.\n\nShe asks you to find the minimum number of operations required to modify $s$ so it contains exactly $k$ instances of B. She also wants you to find these operations (that is, integer $i$ and character $c$ selected in each operation).",
    "tutorial": "In one move, Milica can replace the whole string with $\\texttt{AA} \\ldots \\texttt{A}$. In her second move, she can replace a prefix of length $k$ with $\\texttt{BB} \\ldots \\texttt{B}$. The process takes no more than $2$ operations. The question remains - when can we do better? In the hint section, we showed that the minimum number of operations is $0$, $1$, or $2$. We have $3$ cases: No operations are needed if $s$ already contains $k$ characters $\\texttt{B}$. No operations are needed if $s$ already contains $k$ characters $\\texttt{B}$. Else, we can use brute force to check if changing some prefix leads to $s$ having $k$ $\\texttt{B}$s. If we find such a prefix, we print it as the answer, and use only one operation. There are $O(n)$ possibilities. Implementing them takes $O(n)$ or $O(n^2)$ time. Else, we can use brute force to check if changing some prefix leads to $s$ having $k$ $\\texttt{B}$s. If we find such a prefix, we print it as the answer, and use only one operation. There are $O(n)$ possibilities. Implementing them takes $O(n)$ or $O(n^2)$ time. Else, we use the two operations described in the hint section. Else, we use the two operations described in the hint section. A fun fact is that only one operation is enough. Can you prove it?",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1898",
    "index": "B",
    "title": "Milena and Admirer",
    "statement": "Milena has received an array of integers $a_1, a_2, \\ldots, a_n$ of length $n$ from a secret admirer. She thinks that making it non-decreasing should help her identify the secret admirer.\n\nShe can use the following operation to make this array non-decreasing:\n\n- Select an element $a_i$ of array $a$ and an integer $x$ such that $1 \\le x < a_i$. Then, replace $a_i$ by two elements $x$ and $a_i - x$ in array $a$. New elements ($x$ and $a_i - x$) are placed in the array $a$ in this order instead of $a_i$.More formally, let $a_1, a_2, \\ldots, a_i, \\ldots, a_k$ be an array $a$ before the operation. After the operation, it becomes equal to $a_1, a_2, \\ldots, a_{i-1}, x, a_i - x, a_{i+1}, \\ldots, a_k$. Note that the length of $a$ increases by $1$ on each operation.\n\nMilena can perform this operation multiple times (possibly zero). She wants you to determine the minimum number of times she should perform this operation to make array $a$ non-decreasing.\n\nAn array $x_1, x_2, \\ldots, x_k$ of length $k$ is called non-decreasing if $x_i \\le x_{i+1}$ for all $1 \\le i < k$.",
    "tutorial": "Try a greedy approach. That is, split each $a_i$ only as many times as necessary (and try to create almost equal parts). We will iterate over the array from right to left. Then, as described in the hint section, we will split the current $a_i$ and create almost equal parts. For example, $5$ split into three parts forms the subarray $[1,2,2]$. Splitting $8$ into four parts forms the subarray $[2,2,2,2]$. Notice that the subarrays must be sorted. Because we want to perform as few splits as possible, the rightmost endpoint value should be as high as possible (as long as it is lower than or equal to the leftmost endpoint of the splitting of $a_{i+1}$ if it exists). When we iterate over the array, it is enough to set the current $a_i$ to the leftmost endpoint of the splitting (the smallest current value). It will help to calculate the optimal splitting of $a_{i-1}$. For the current $a_i$, we want to find the least $k$ such that we can split $a_{i-1}$ into $k$ parts so the rightmost endpoint is less than or equal to $a_i$. More formally, we want $\\lceil \\frac{a_{i-1}}{k} \\rceil \\leq a_i$ to hold. Afterwards, we set $a_{i-1}$ to $\\lfloor \\frac{a_{i-1}}{k} \\rfloor$ and continue with our algorithm. The simplest way to find the desired $k$ is to apply the following formula: $k=\\lceil \\frac{a_{i-1}}{a_i} \\rceil$ The answer is the sum over all $k-1$. There are $q \\leq 2\\cdot 10^5$ queries: given an index $i$ and an integer $x>1$, set $a_i := \\lceil \\frac{a_i}{x} \\rceil$. Modify the array and print the answer to the original problem. Please note that the queries stack.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1898",
    "index": "C",
    "title": "Colorful Grid",
    "statement": "Elena has a grid formed by $n$ horizontal lines and $m$ vertical lines. The horizontal lines are numbered by integers from $1$ to $n$ from top to bottom. The vertical lines are numbered by integers from $1$ to $m$ from left to right. For each $x$ and $y$ ($1 \\leq x \\leq n$, $1 \\leq y \\leq m$), the notation $(x, y)$ denotes the point at the intersection of the $x$-th horizontal line and $y$-th vertical line.\n\nTwo points $(x_1,y_1)$ and $(x_2,y_2)$ are adjacent if and only if $|x_1-x_2| + |y_1-y_2| = 1$.\n\n\\begin{center}\n{\\small The grid formed by $n=4$ horizontal lines and $m=5$ vertical lines.}\n\\end{center}\n\nElena calls a sequence of points $p_1, p_2, \\ldots, p_g$ of length $g$ a walk if and only if all the following conditions hold:\n\n- The first point $p_1$ in this sequence is $(1, 1)$.\n- The last point $p_g$ in this sequence is $(n, m)$.\n- For each $1 \\le i < g$, the points $p_i$ and $p_{i+1}$ are adjacent.\n\nNote that the walk may contain the same point more than once. In particular, it may contain point $(1, 1)$ or $(n, m)$ multiple times.\n\nThere are $n(m-1)+(n-1)m$ segments connecting the adjacent points in Elena's grid. Elena wants to color each of these segments in blue or red color so that there exists a walk $p_1, p_2, \\ldots, p_{k+1}$ of length $k+1$ such that\n\n- out of $k$ segments connecting two consecutive points in this walk, no two consecutive segments have the same color (in other words, for each $1 \\le i < k$, the color of the segment between points $p_i$ and $p_{i+1}$ differs from the color of the segment between points $p_{i+1}$ and $p_{i+2}$).\n\nPlease find any such coloring or report that there is no such coloring.",
    "tutorial": "The solution does not exist only for \"small\" $k$ or when $n+m-k$ is an odd integer. Try to find a construction otherwise. Read the hint for the condition of the solution's existence. We present a single construction that solves the problem for each valid $k$. One can verify that the pattern holds in general. How would you write a checker? That is, how would you check that a valid walk of length $k+1$ exists in the given grid (with all the edges colored beforehand)?",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1898",
    "index": "D",
    "title": "Absolute Beauty",
    "statement": "Kirill has two integer arrays $a_1,a_2,\\ldots,a_n$ and $b_1,b_2,\\ldots,b_n$ of length $n$. He defines the absolute beauty of the array $b$ as $$\\sum_{i=1}^{n} |a_i - b_i|.$$ Here, $|x|$ denotes the absolute value of $x$.\n\nKirill can perform the following operation \\textbf{at most once}:\n\n- select two indices $i$ and $j$ ($1 \\leq i < j \\leq n$) and swap the values of $b_i$ and $b_j$.\n\nHelp him find the maximum possible absolute beauty of the array $b$ after performing \\textbf{at most one} swap.",
    "tutorial": "If $a_i > b_i$, swap them. Imagine the pairs $(a_i,b_i)$ as intervals. How can we visualize the problem? The pair $(a_i,b_i)$ represents some interval, and $|a_i - b_i|$ is its length. Let us try to maximize the sum of the intervals' lengths. We present three cases of what a swap does to two arbitrary intervals. Notice how the sum of the lengths increases only in the first case. We want the distance between the first interval's right endpoint and the second interval's left endpoint to be as large as possible. So we choose integers $i$ and $j$ such that $i \\neq j$ and $a_j - b_i$ is maximized. We add twice the value, if it is positive, to the original absolute beauty. If the value is $0$ or negative, we simply do nothing. To quickly find the maximum of $a_j - b_i$ over all $i$ and $j$, we find the maximum of $a_1,a_2,\\ldots a_n$ and the minimum of $b_1,b_2, \\ldots b_n$. Subtracting the two extremum values produces the desired result. How to handle point updates? (change a single value in either $a$ or $b$, and print the answer after each query.)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1898",
    "index": "E",
    "title": "Sofia and Strings",
    "statement": "Sofia has a string $s$ of length $n$, consisting only of lowercase English letters. She can perform operations of the following types with this string.\n\n- Select an index $1 \\le i \\le |s|$ and remove the character $s_i$ from the string.\n- Select a pair of indices $(l, r)$ ($1 \\le l \\le r \\le |s|$) and sort the substring $s_{l} s_{l+1} \\ldots s_r$ in alphabetical order.\n\nHere, $|s|$ denotes the current length of $s$. In particular, $|s| = n$ before the first operation. For example, if $s = \\mathtt{sofia}$, then performing the operation of the first type with $i=4$ results in $s$ becoming $\\mathtt{sofa}$, and performing the operation of the second type with $(l, r) = (2, 4)$ after that results in $s$ becoming $\\mathtt{safo}$.Sofia wants to obtain the string $t$ of length $m$ after performing zero or more operations on string $s$ as described above. Please determine whether it is possible or not.",
    "tutorial": "Notice how sorting only the substrings of length $2$ is enough. Try a greedy approach. We sort only the substrings of length $2$. We can swap two adjacent characters if the first is greater than or equal to the second. Let us fix some character $s_i$ and presume we want to change its position to $j$. We have to perform the described swaps if they are possible. More formally: if $j<i$, then every character in the segment $s_j s_{j+1} \\ldots s_{i-1}$ must be greater than or equal to $s_i$; if $i<j$, then every character in the segment $s_{i+1} s_{i+2} \\ldots s_j$ must be smaller than or equal to $s_i$. We want to reorder the string $s$ and get the string $s'$. Then, we check if we can delete some characters in $s'$ to achieve $t$. In other words, we want $t$ to be a subsequence of $s'$. A general algorithm that checks if the string $a$ is a subsequence of the string $b$ is as follows. We iterate through $a$, and for each character, we find its first next appearance in $b$. If such a character does not exist, we conclude that $a$ is not a subsequence of $b$. If we complete the iteration gracefully, then $a$ is a subsequence of $b$. We will try to check if $t$ is a subsequence of $s$, but we allow ourselves to modify $s$ along the way. We maintain $26$ queues for positions of each lowercase English letter in the string $s$. We iterate through the string $t$, and for every character $t_i$, we try to move the first available equivalent character in $s$ to position $i$. In other words, at every moment, the prefix of string $s$ is equal to the prefix of string $t$ (if possible). For the current character $t_i$ and the corresponding $s_j$, prefixes $t_1t_2\\dots t_{i-1}$ and $s_1s_2\\dots s_{i-1}$ are the same, which means that $j\\geq i$. To move $s_j$ to position $i$, we need to delete all characters between $s_i$ and $s_j$ that are smaller than $s_j$. We will delete them and all characters from the current prefix $s_1s_2\\dots s_{i-1}$ from the queues because they are no longer candidates for $s_j$. By doing so, $s_j$ will be the first character in the corresponding queue. If at some moment in our greedy algorithm, the queue we are looking for becomes empty, then the answer is \"NO\". Otherwise, we will make the prefix $s_1s_2\\dots s_m$ equal to the $t$ and delete the remaining characters from $s$. Why is this greedy approach optimal? Let's suppose for some character $t_{i_1}$ we chose $s_{j_1}$ and for $t_{i_2}$ we chose $s_{j_2}$, such that $i_1< i_2$, $j_1>j_2$ and $t_{i_1}=t_{i_2}=s_{j_1}=s_{j_2}$. We need to prove that if we can move $s_{j_1}$ to position $i_1$ and $t_{i_2}$ to position $i_2$, when we can move $s_{j_2}$ to $i_1$ and $s_{j_1}$ to $i_2$. In the moment when we chose $s_{j_1}$, prefixes $t_1t_2\\dots t_{i_1-1}$ and $s_1s_2\\dots s_{i_1-1}$ are the same, so $j_1\\geq i_1$. Similarly, $j_2\\geq i_2$, which means the only possibility is $i_1<i_2\\leq j_2<j_1$. If we can move $s_{j_1}$ to position $i_1$, than we can also move $s_{j_2}$ to $i_1$ because $s_{j_1}=s_{j_2}$ and $j_2<j_1$. Also, if we can move $s_{j_1}$ to $i_1$, than we can move $s_{j_1}$ to $i_2$ because $i_1<i_2$, from which it follows that we can move $s_{j_2}$ to $i_2$, because $s_{j_2}=s_{j_1}$ and $j_2<j_1$. The overall complexity is $O(\\alpha \\cdot (n+m))$, where $\\alpha$ is the alphabet size ($\\alpha=26$ in this problem). Solve the problem when the size of the alphabet is arbitrary (up to $n$).",
    "tags": [
      "data structures",
      "greedy",
      "sortings",
      "strings",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1898",
    "index": "F",
    "title": "Vova Escapes the Matrix",
    "statement": "Following a world tour, Vova got himself trapped inside an $n \\times m$ matrix. Rows of this matrix are numbered by integers from $1$ to $n$ from top to bottom, and the columns are numbered by integers from $1$ to $m$ from left to right. The cell $(i, j)$ is the cell on the intersection of row $i$ and column $j$ for $1 \\leq i \\leq n$ and $1 \\leq j \\leq m$.\n\nSome cells of this matrix are blocked by obstacles, while all other cells are empty. Vova occupies one of the empty cells. It is guaranteed that cells $(1, 1)$, $(1, m)$, $(n, 1)$, $(n, m)$ (that is, corners of the matrix) are blocked.\n\nVova can move from one empty cell to another empty cell if they share a side. Vova can escape the matrix from any empty cell on the boundary of the matrix; these cells are called exits.\n\nVova defines the type of the matrix based on the number of exits he can use to escape the matrix:\n\n- The $1$-st type: matrices with no exits he can use to escape.\n- The $2$-nd type: matrices with exactly one exit he can use to escape.\n- The $3$-rd type: matrices with multiple (two or more) exits he can use to escape.\n\nBefore Vova starts moving, Misha can create more obstacles to block more cells. However, he cannot change the type of the matrix. What is the maximum number of cells Misha can block, so that the type of the matrix remains the same? Misha cannot block the cell Vova is currently standing on.",
    "tutorial": "To solve the problem for matrices of $3$-rd type, find the shortest path to $2$ closest exits with a modification of BFS. Block all cells not belonging to the path with obstacles. For a matrix of type $1$, Misha can block all empty cells (except the one Vova stands on). For a matrix of type $2$, Misha finds the shortest path to some exit with a single BFS and then blocks every other cell. Matrices of type $3$ are more complicated. We want to find two shortest paths to the two closest exits and block the remaining empty cells. But, notice how the paths will likely share their beginnings. We do not have to count those cells twice. Let's take a look at the junction where the two paths merge. If we first fix the junction, finding the shortest path to Vova can be done by running a single BFS and precalculating the shortest distances from each cell to Vova. Finding the shortest path from the junction to the two closest exits can also be done with BFS and precalculation. We modify the BFS, making it multi-source, with a source in each exit. Also, we will allow each cell to be visited twice (but by different exits). We will need to maintain the following data for each cell: How many times was it visited; The last exit/source that visited it; The sum of paths from all exits/sources that visited the cell so far. Running the BFS with proper implementation produces the answer. When everything said is precalculated, we fix the junction in $O(nm)$ ways (each empty cell can be a valid junction), and then calculate the shortest path from Vova to the two closest cells in $O(1)$ per junction. Total complexity is $O(nm)$. Solve the problem with LCA, or report that such a solution does not exist.",
    "tags": [
      "brute force",
      "dfs and similar",
      "divide and conquer",
      "shortest paths"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1899",
    "index": "A",
    "title": "Game with Integers",
    "statement": "Vanya and Vova are playing a game. Players are given an integer $n$. On their turn, the player can add $1$ to the current integer or subtract $1$. The players take turns; Vanya starts. If \\textbf{after} Vanya's move the integer is divisible by $3$, then he wins. If $10$ moves have passed and Vanya has not won, then Vova wins.\n\nWrite a program that, based on the integer $n$, determines who will win if both players play optimally.",
    "tutorial": "Consider the remainder from dividing $n$ by $3$ before the first move. If it is equal to $1$ or $2$, then Vanya can make the number $n$ divisible by $3$ after the first move, i.e. he wins. Let the remainder be $0$, then Vanya must change the number after which it will not be divisible by $3$. Then Vova can do the same operation as Vanya and make it divisible by $3$ again. This will go on indefinitely, so Vova wins.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    if (n % 3) {\n        cout << \"First\\n\";\n    } else {\n        cout << \"Second\\n\";\n    }\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "games",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1899",
    "index": "B",
    "title": "250 Thousand Tons of TNT",
    "statement": "Alex is participating in the filming of another video of BrMeast, and BrMeast asked Alex to prepare 250 thousand tons of TNT, but Alex didn't hear him well, so he prepared $n$ boxes and arranged them in a row waiting for trucks. The $i$-th box from the left weighs $a_i$ tons.\n\nAll trucks that Alex is going to use hold the same number of boxes, denoted by $k$. Loading happens the following way:\n\n- The first $k$ boxes goes to the first truck,\n- The second $k$ boxes goes to the second truck,\n- $\\dotsb$\n- The last $k$ boxes goes to the $\\frac{n}{k}$-th truck.\n\nUpon loading is completed, each truck must have \\textbf{exactly} $k$ boxes. In other words, if at some point it is not possible to load exactly $k$ boxes into the truck, then the loading option with that $k$ is not possible.\n\nAlex hates justice, so he wants the maximum absolute difference between the total weights of two trucks to be as great as possible. If there is only one truck, this value is $0$.\n\nAlex has quite a lot of connections, so for every $1 \\leq k \\leq n$, he can find a company such that each of its trucks can hold exactly $k$ boxes. Print the maximum absolute difference between the total weights of any two trucks.",
    "tutorial": "Solution #1: Since $k$ is a divisor of $n$, there are $O(\\sqrt[3]{n})$ such $k$. We can enumerate all k, calculate a given value in $O(n)$, and take the maximum of them. Total complexity - $O(n \\cdot \\sqrt[3]{n})$. Solution #2: Without using the fact that $k$ is a divisor of $n$, we can simply loop over $k$ and then calculate the values using prefix sums, and at the end check that there are exactly $k$ elements in each segment. Such a solution works in $O(\\frac{n}{1} + \\frac{n}{2} + \\frac{n}{3} + \\cdots + \\frac{n}{n}) = O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\n#define all(x) x.begin(), x.end()\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) cin >> a[i];\n    ll ans = -1;\n    for (int d = 1; d <= n; ++d) {\n        if (n % d == 0) {\n            ll mx = -1e18, mn = 1e18;\n            for (int i = 0; i < n; i += d) {\n                ll sm = 0;\n                for (int j = i; j < i + d; ++j) {\n                    sm += a[j];\n                }\n                mx = max(mx, sm);\n                mn = min(mn, sm);\n            }\n            ans = max(ans, mx - mn);\n        }\n    }\n    cout << ans << '\\n';\n}\n \nint32_t main() {\n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "brute force",
      "implementation",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1899",
    "index": "C",
    "title": "Yarik and Array",
    "statement": "A subarray is a continuous part of array.\n\nYarik recently found an array $a$ of $n$ elements and became very interested in finding the maximum sum of a \\textbf{non empty} subarray. However, Yarik doesn't like consecutive integers with the same parity, so the subarray he chooses must have alternating parities for adjacent elements.\n\nFor example, $[1, 2, 3]$ is acceptable, but $[1, 2, 4]$ is not, as $2$ and $4$ are both even and adjacent.\n\nYou need to help Yarik by finding the maximum sum of such a subarray.",
    "tutorial": "There are \"bad\" positions in the array, i.e., those on which two numbers of the same parity are next to each other. Note that all matching segments cannot contain such positions, in other words, we need to solve the problem of finding a sub segment with maximal sum on some number of non-intersecting sub segments of the array, the boundaries of which are between two neighboring elements of the same parity. The problem of finding a sub segment with maximal sum can be solved using the classical algorithm with keeping minimal prefix sum on the prefix. The problem can be solved in a single pass over the array by simply dropping the keeped values when we are in a bad position. Total complexity - $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    int ans = a[0];\n    int mn = min(0, a[0]), sum = a[0];\n    for (int i = 1; i < n; ++i) {\n        if (abs(a[i] % 2) == abs(a[i - 1] % 2)) {\n            mn = 0;\n            sum = 0;\n        }\n        sum += a[i];\n        ans = max(ans, sum - mn);\n        mn = min(mn, sum);\n    }\n    cout << ans << endl;\n}\n \nint main() {\n    int tc = 1;\n    cin >> tc;\n    for (int t = 1; t <= tc; t++) {\n        solve();\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1899",
    "index": "D",
    "title": "Yarik and Musical Notes",
    "statement": "Yarik is a big fan of many kinds of music. But Yarik loves not only listening to music but also writing it. He likes electronic music most of all, so he has created his own system of music notes, which, in his opinion, is best for it.\n\nSince Yarik also likes informatics, in his system notes are denoted by integers of $2^k$, where $k \\ge 1$ — a positive integer. But, as you know, you can't use just notes to write music, so Yarik uses combinations of two notes. The combination of two notes $(a, b)$, where $a = 2^k$ and $b = 2^l$, he denotes by the integer $a^b$.\n\nFor example, if $a = 8 = 2^3$, $b = 4 = 2^2$, then the combination $(a, b)$ is denoted by the integer $a^b = 8^4 = 4096$. Note that different combinations can have the same notation, e.g., the combination $(64, 2)$ is also denoted by the integer $4096 = 64^2$.\n\nYarik has already chosen $n$ notes that he wants to use in his new melody. However, since their integers can be very large, he has written them down as an array $a$ of length $n$, then the note $i$ is $b_i = 2^{a_i}$. The integers in array $a$ can be repeated.\n\nThe melody will consist of several combinations of two notes. Yarik was wondering how many pairs of notes $b_i, b_j$ $(i < j)$ exist such that the combination $(b_i, b_j)$ is equal to the combination $(b_j, b_i)$. In other words, he wants to count the number of pairs $(i, j)$ $(i < j)$ such that $b_i^{b_j} = b_j^{b_i}$. Help him find the number of such pairs.",
    "tutorial": "The problem requires to count the number of pairs of indices $(i, j)$ ($i < j$) such that $(2^a)^{(2^b)} = (2^b)^{(2^a)}$, where $a = b_i, b = b_j$. Obviously, when $a = b$ this equality is satisfied. Let $a \\neq b$, then rewrite the equality: $(2^a)^{(2^b)} = (2^b)^{(2^a)} \\Leftrightarrow 2^{(a \\cdot 2^b)} = 2^{(b \\cdot 2^a)} \\Leftrightarrow a \\cdot 2^b = b \\cdot 2^a \\Leftrightarrow \\frac{a}{b} = \\frac{2^a}{2^b}$. Obviously, $a$ and $b$ must differ by powers of two, otherwise the equality cannot be satisfied, since the ratio of powers of two is on the right. Without loss of generality, suppose that $b = a \\cdot 2^k$ ($k > 0$), then the equation takes the form $\\frac{a}{a \\cdot 2^k} = \\frac{2^a}{2^{a \\cdot 2^k}} \\Leftrightarrow \\frac{1}{2^k} = \\frac{1}{2^{(2^k - 1)a}} \\Leftrightarrow 2^k = 2^{(2^k - 1)a}$. If $k = 1$, then $a = 1$, $b = 2$. If $k > 1$, then $2^k - 1 > k$, and so the equality cannot be satisfied. Thus, the only possible cases where the equality is satisfied are if $b_i = b_j$ or $b_i = 1, b_j = 2$ (and vice versa). The number of such pairs can be counted for $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int& x : a) cin >> x;\n\tll ans = 0;\n\tmap<int, int> cnt;\n\tfor (int i = 0; i < n; i++) {\n\t\tans += cnt[a[i]];\n\t\tif (a[i] == 1) ans += cnt[2];\n\t\telse if (a[i] == 2) ans += cnt[1];\n\t\tcnt[a[i]]++;\n\t}\n\tcout << ans << \"\\n\";\n}\n \nsigned main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) solve();\n}",
    "tags": [
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1899",
    "index": "E",
    "title": "Queue Sort",
    "statement": "Vlad found an array $a$ of $n$ integers and decided to sort it in non-decreasing order.\n\nTo do this, Vlad can apply the following operation any number of times:\n\n- Extract the first element of the array and insert it at the end;\n- Swap \\textbf{that} element with the previous one until it becomes the first or until it becomes \\textbf{strictly} greater than the previous one.\n\nNote that both actions are part of the operation, and for one operation, you \\textbf{must} apply both actions.\n\nFor example, if you apply the operation to the array [$4, 3, 1, 2, 6, 4$], it will change as follows:\n\n- [$\\textcolor{red}{4}, 3, 1, 2, 6, 4$];\n- [$3, 1, 2, 6, 4, \\textcolor{red}{4}$];\n- [$3, 1, 2, 6, \\textcolor{red}{4}, 4$];\n- [$3, 1, 2, \\textcolor{red}{4}, 6, 4$].\n\nVlad doesn't have time to perform all the operations, so he asks you to determine the minimum number of operations required to sort the array or report that it is impossible.",
    "tutorial": "Consider the position of the first minimum in the array, let it be equal to $k$. All elements standing on positions smaller than $k$ are strictly greater, so we must apply operations to them, because otherwise the array will not be sorted. Suppose we have applied operations to all such elements, they have taken some positions after $k$ (since they are strictly greater than the minimum), i.e. now the minimum element that moved from position $k$ is at the beginning of the array. If we apply the operation to it, it will return to its current position, since it is less than or equal to all elements of the array, i.e. the array will not change. Thus, after the array has its minimum at the beginning, it is useless to apply operations, and all the operations applied before that will move the element from the beginning of the array to some position after the position of the first minimum. Then, if the part of the array after the position $k$ is not sorted, the answer is $-1$, because it is impossible to change the order of elements in it. Otherwise, the answer is equal to the number of elements standing before the first minimum, since the operation must be applied to them and they will be in the right place in the right part. Total complexity - $O(n)$.",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    fm = 0\n    for i in range(n):\n        if a[i] < a[fm]:\n            fm = i\n    for i in range(fm + 1, n):\n        if a[i] < a[i - 1]:\n            print(-1)\n            return\n    print(fm)\n \n \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1899",
    "index": "F",
    "title": "Alex's whims",
    "statement": "Tree is a connected graph without cycles. It can be shown that any tree of $n$ vertices has exactly $n - 1$ edges.\n\nLeaf is a vertex in the tree with exactly one edge connected to it.\n\nDistance between two vertices $u$ and $v$ in a tree is the minimum number of edges that must be passed to come from vertex $u$ to vertex $v$.\n\nAlex's birthday is coming up, and Timofey would like to gift him a tree of $n$ vertices. However, Alex is a very moody boy. Every day for $q$ days, he will choose an integer, denoted by the integer chosen on the $i$-th day by $d_i$. If on the $i$-th day there are not two leaves in the tree at a distance \\textbf{exactly} $d_i$, Alex will be disappointed.\n\nTimofey decides to gift Alex a designer so that he can change his tree as he wants. Timofey knows that Alex is also lazy (a disaster, not a human being), so at the beginning of every day, he can perform \\textbf{no more} than one operation of the following kind:\n\n- Choose vertices $u$, $v_1$, and $v_2$ such that there is an edge between $u$ and $v_1$ and no edge between $u$ and $v_2$. Then remove the edge between $u$ and $v_1$ and add an edge between $u$ and $v_2$. This operation \\textbf{cannot} be performed if the graph is no longer a tree after it.\n\nSomehow Timofey managed to find out all the $d_i$. After that, he had another brilliant idea — just in case, make an instruction manual for the set, one that Alex wouldn't be disappointed.\n\nTimofey is not as lazy as Alex, but when he saw the integer $n$, he quickly lost the desire to develop the instruction and the original tree, so he assigned this task to you. It can be shown that a tree and a sequence of operations satisfying the described conditions always exist.\n\nHere is an example of an operation where vertices were selected: $u$ — $6$, $v_1$ — $1$, $v_2$ — $4$.",
    "tutorial": "This problem can be solved in several similar ways, one of them is given below. First, it is most convenient to take a bamboo - vertices from $1$ to $n$ connected in order. Then, we will maintain the following construction. At each moment of time, vertices $1$ and $2$ will be connected by an edge, from vertex $2$ there will be at most two branches, which are sequentially connected vertices (bamboo). Thus, at any given time there will be at most three leaves in the tree, one of which is vertex $1$. We will maintain vertices from two branches in two arrays. Then, let the current number from the query be $d$. If the distance from any of the leaves to vertex $1$ is $d$, we don't need to perform the operation. Otherwise, let's do the operation so that the distance from a leaf from, for example, the first branch to vertex $1$ is equal to $d$. If the current distance is greater than $d$, then we remove the extra vertices to the end of the second branch, and otherwise we add the necessary ones from the end of the second branch. Thus, after each operation, the distance from vertex $1$ to some of the sheets will be equal to $d$. Transformations can be done by completely moving vertices, then the total complexity - $O(nq)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> b1, b2;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tb1.push_back(i);\n\t\t}\n\t\tb2.push_back(1);\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tcout << i << ' ' << i + 1 << endl;\n\t\t}\n\t\tint q;\n\t\tcin >> q;\n\t\twhile (q--) {\n\t\t\tint d;\n\t\t\tcin >> d;\n\t\t\td++;\n\t\t\tif (b1.size() == d) {\n\t\t\t\tcout << \"-1 -1 -1\\n\";\n\t\t\t} else if (b1.size() < d) {\n\t\t\t\td = d - b1.size();\n\t\t\t\tvector<int> qq(b2.end() - d, b2.end());\n\t\t\t\tint u = b2[b2.size() - d];\n\t\t\t\tint v1 = b2[b2.size() - d - 1];\n\t\t\t\tint v2 = b1.back();\n\t\t\t\tcout << u + 1 << ' ' << v1 + 1 << ' ' << v2 + 1 << '\\n';\n\t\t\t\tfor (int i = 0; i < d; ++i) b2.pop_back();\n\t\t\t\tfor (auto i : qq) b1.push_back(i);\n\t\t\t} else {\n\t\t\t\td = b1.size() - d;\n\t\t\t\tvector<int> qq(b1.end() - d, b1.end());\n\t\t\t\tint u = b1[b1.size() - d];\n\t\t\t\tint v1 = b1[b1.size() - d - 1];\n\t\t\t\tint v2 = b2.back();\n\t\t\t\tcout << u + 1 << ' ' << v1 + 1 << ' ' << v2 + 1 << '\\n';\n\t\t\t\tfor (int i = 0; i < d; ++i) b1.pop_back();\n\t\t\t\tfor (auto i : qq) b2.push_back(i);\n\t\t\t}\n\t\t}\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "shortest paths",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1899",
    "index": "G",
    "title": "Unusual Entertainment",
    "statement": "A tree is a connected graph without cycles.\n\nA permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[5, 1, 3, 2, 4]$ is a permutation, but $[2, 1, 1]$ is not a permutation (as $1$ appears twice in the array) and $[1, 3, 2, 5]$ is also not a permutation (as $n = 4$, but $5$ is present in the array).\n\nAfter a failed shoot in the BrMeast video, Alex fell into depression. Even his birthday did not make him happy. However, after receiving a gift from Timofey, Alex's mood suddenly improved. Now he spent days playing with the gifted constructor. Recently, he came up with an unusual entertainment.\n\nAlex builds a tree from his constructor, consisting of $n$ vertices numbered from $1$ to $n$, with the root at vertex $1$. Then he writes down each integer from $1$ to $n$ in some order, obtaining a permutation $p$. After that, Alex comes up with $q$ triples of integers $l, r, x$. For each triple, he tries to determine if there is at least one descendant of vertex $x$ among the vertices $p_l, p_{l+1}, \\ldots, p_r$.\n\nA vertex $u$ is a descendant of vertex $v$ if and only if $\\mathrm{dist}(1, v) + \\mathrm{dist}(v, u) = \\mathrm{dist}(1, u)$, where $\\mathrm{dist}(a, b)$ is the distance between vertices $a$ and $b$. In other words, vertex $v$ must be on the path from the root to vertex $u$.\n\nAlex told Zakhar about this entertainment. Now Alex tells his friend $q$ triples as described above, hoping that Zakhar can check for the presence of a descendant. Zakhar is very sleepy, so he turned to you for help. Help Zakhar answer all of Alex's questions and finally go to sleep.",
    "tutorial": "Let's start the depth-first search from vertex $1$ and write out the entry and exit times for each vertex. Then, the fact that vertex $b$ is a descendant of vertex $a$ is equivalent to the fact that $\\mathrm{tin}[a] \\leq \\mathrm{tin}[b] \\leq \\mathrm{tout}[b] \\leq \\mathrm{tout}[b] \\leq \\mathrm{tout}[a]$, where $\\mathrm{tin}$ and $\\mathrm{tout}$ - entry and exit times, respectively. Then, let us create an array $a$, where $a_i = \\mathrm{tin}[p_i]$, then the problem is reduced to checking that on the segment c $l$ through $r$ in array $a$ there is at least one number belonging to the segment $[\\mathrm{tin}[x]; \\mathrm{tout}[x]]$. This can be done, for example, using Merge Sort Tree, then the total complexity will be $O(n \\log n + q \\log^ 2 n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define sz(x) (int)x.size()\n#define all(x) x.begin(), x.end()\n \nstruct SegmentTree {\n    int n;\n    vector<vector<int>> tree;\n \n    void build(vector<int> &a, int x, int l, int r) {\n        if (l + 1 == r) {\n            tree[x] = {a[l]};\n            return;\n        }\n \n        int m = (l + r) / 2;\n        build(a, 2 * x + 1, l, m);\n        build(a, 2 * x + 2, m, r);\n        merge(all(tree[2 * x + 1]), all(tree[2 * x + 2]), back_inserter(tree[x]));\n    }\n \n    SegmentTree(vector<int>& a) : n(a.size()) {\n        int SIZE = 1 << (__lg(n) + bool(__builtin_popcount(n) - 1));\n        tree.resize(2 * SIZE - 1);\n        build(a, 0, 0, n);\n    }\n \n    int count(int lq, int rq, int mn, int mx, int x, int l, int r) {\n        if (rq <= l || r <= lq) return 0;\n        if (lq <= l && r <= rq) return lower_bound(all(tree[x]), mx) - lower_bound(all(tree[x]), mn);\n \n        int m = (l + r) / 2;\n        int a = count(lq, rq, mn, mx, 2 * x + 1, l, m);\n        int b = count(lq, rq, mn, mx, 2 * x + 2, m, r);\n        return a + b;\n    }\n \n    int count(int lq, int rq, int mn, int mx) {\n        return count(lq, rq, mn, mx, 0, 0, n);\n    }\n};\n \nvector<vector<int>> g;\n \nvector<int> tin, tout;\nint timer;\nvoid dfs(int v, int p) {\n    tin[v] = timer++;\n    for (auto u : g[v]) {\n        if (u != p) {\n            dfs(u, v);\n        }\n    }\n    tout[v] = timer;\n}\n \nvoid solve() {\n    int n, q;\n    cin >> n >> q;\n    \n    g.assign(n, vector<int>());\n    for (int i = 0; i < n - 1; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--; v--;\n        g[u].push_back(v);\n        g[v].push_back(u);\n    }\n \n    timer = 0;\n    tin.resize(n);\n    tout.resize(n);\n    dfs(0, -1);\n    \n    vector<int> p(n);\n    for (int i = 0; i < n; i++) cin >> p[i];\n \n    vector<int> a(n);\n    for (int i = 0; i < n; i++) a[i] = tin[p[i] - 1];\n    SegmentTree ST(a);\n \n    for (int i = 0; i < q; i++) {\n        int l, r, x;\n        cin >> l >> r >> x;\n        l--; x--;\n        if (ST.count(l, r, tin[x], tout[x])) {\n            cout << \"YES\\n\";\n        } else {\n            cout << \"NO\\n\";\n        }\n    }\n}\n \nint main() {\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        solve();\n        if(tests > 0) cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "shortest paths",
      "sortings",
      "trees",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1900",
    "index": "A",
    "title": "Cover in Water",
    "statement": "Filip has a row of cells, some of which are blocked, and some are empty. He wants all empty cells to have water in them. He has two actions at his disposal:\n\n- $1$ — place water in an empty cell.\n- $2$ — remove water from a cell and place it in any other empty cell.\n\nIf at some moment cell $i$ ($2 \\le i \\le n-1$) is empty and both cells $i-1$ and $i+1$ contains water, then it becomes filled with water.\n\nFind the minimum number of times he needs to perform action $1$ in order to fill all empty cells with water.\n\nNote that you don't need to minimize the use of action $2$. Note that blocked cells neither contain water nor can Filip place water in them.",
    "tutorial": "Assume that cells $i-1$, $i$, and $i+1$ are covered in water. What happens if you remove water from cell $i$? The water at position $i$ is replaced as both cells $i-1$ and $i+1$ have water in them. Read the hints. If there are 3 consecutive empty cells $i-1$, $i$, $i+1$, we can place water in cells $i-1$ and $i+1$ and then move water from cell $i$ to all other cells. If there are no such cells, we have to place water on every empty cell. So if we find substring ''...'' in the array, the answer is $2$, otherwise the answer is the number of empty cells. Time and memory complexities are $O(N)$. Solve the problem if it is required that each cell is filled with water, or next to at least $1$ cell that is filled with water.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1900",
    "index": "B",
    "title": "Laura and Operations",
    "statement": "Laura is a girl who does not like combinatorics. Nemanja will try to convince her otherwise.\n\nNemanja wrote some digits on the board. All of them are either $1$, $2$, or $3$. The number of digits $1$ is $a$. The number of digits $2$ is $b$ and the number of digits $3$ is $c$. He told Laura that in one operation she can do the following:\n\n- Select two different digits and erase them from the board. After that, write the digit ($1$, $2$, or $3$) different from both erased digits.\n\nFor example, let the digits be $1$, $1$, $1$, $2$, $3$, $3$. She can choose digits $1$ and $3$ and erase them. Then the board will look like this $1$, $1$, $2$, $3$. After that, she has to write another digit $2$, so at the end of the operation, the board will look like $1$, $1$, $2$, $3$, $2$.\n\nNemanja asked her whether it was possible for only digits of one type to remain written on the board after some operations. If so, which digits can they be?\n\nLaura was unable to solve this problem and asked you for help. As an award for helping her, she will convince Nemanja to give you some points.",
    "tutorial": "Check if only digits $1$ can remain. The situation is similar for checking if only digits $2$ or only digits $3$ can remain. Try to find something that stays the same after each operation. Look at the parity of the numbers. The parity of each number changes after an operation. That means that if $2$ numbers have the same parity, they will always have the same parity. If they had different parity, their parities stay different. Read the hints. If the parity of $b$ and $c$ is not the same, then it is impossible for only digits $1$ to remain on the board, as it would require $b = c = 0$. Otherwise, the following construction will leave only digits $1$ on the board. First remove digits $2$ and $3$ and write digit $1$ while $b>0$ and $c>0$. If $b=c$, then we are done. Otherwise, without loss of generality assume $b>c$. That means that after the operations $c=0$ and $b$ is even (Because $b$ and $c$ are the same parity). Now we perform the following $2$ operations $\\frac{b}{2}$ times to get only digits $1$ left. Remove digits $1$ and $2$ and add digit $3$. After that remove digits $2$ and $3$ and add digit $1$. An effective change of these $2$ operations is the reduction of $b$ by $2$. Time and memory complexities are $O(1)$. Come up with a problem that uses a similar idea and try to solve it. A lot of beginner problems use a similar idea.",
    "tags": [
      "dp",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1900",
    "index": "C",
    "title": "Anji's Binary Tree",
    "statement": "Keksic keeps getting left on seen by Anji. Through a mutual friend, he's figured out that Anji really likes binary trees and decided to solve her problem in order to get her attention.\n\nAnji has given Keksic a binary tree with $n$ vertices. Vertex $1$ is the root and does not have a parent. All other vertices have exactly one parent. Each vertex can have up to $2$ children, a left child, and a right child. For each vertex, Anji tells Keksic index of both its left and its right child or tells him that they do not exist.\n\nAdditionally, each of the vertices has a letter $s_i$ on it, which is either 'U', 'L' or 'R'.\n\nKeksic begins his journey on the root, and in each move he does the following:\n\n- If the letter on his current vertex is 'U', he moves to its parent. If it doesn't exist, he does nothing.\n- If the letter on his current vertex is 'L', he moves to its left child. If it doesn't exist, he does nothing.\n- If the letter on his current vertex is 'R', he moves to its right child. If it doesn't exist, he does nothing.\n\nBefore his journey, he can perform the following operations: choose any node, and replace the letter written on it with another one. You are interested in the minimal number of operations he needs to do before his journey, such that when he starts his journey, he will reach a leaf at some point. A leaf is a vertex that has no children. It does not matter which leaf he reaches. Note that it does not matter whether he will stay in the leaf, he just needs to move to it. Additionally, note that it does not matter how many times he needs to move before reaching a leaf.\n\nHelp Keksic solve Anji's tree so that he can win her heart, and make her come to Čačak.",
    "tutorial": "Solve the problem if all of the characters on vertices are 'U'. We can run DFS from the root. Using it we can calculate the number of edges that we have to traverse to get to every edge. Just output the smallest value among all the leaves. Modify the DFS such that it takes into account that traversing some edges does not require an operation. Add weights to the edges. Read the hints. We will make edges from a vertex to its children. The weight of that edge will be $1$ unless one of the following holds: The weight of an edge between a vertex and its left child will be $0$ if the letter written on that vertex is 'L'. The weight of an edge between a vertex and its left child will be $0$ if the letter written on that vertex is 'L'. The weight of an edge between a vertex and its right child will be $0$ if the letter written on that vertex is 'R'. The weight of an edge between a vertex and its right child will be $0$ if the letter written on that vertex is 'R'. Now we run a modified DFS to find the distance of each vertex from the root, but with weighted edges. We output the minimal value among all the leaves. Time and memory complexities are $O(N)$. Solve the problem if after reaching a leaf, Keksic can teleport to any other leaf that he chooses and then needs to get back to the root, or report that it is impossible for him to complete such a travel.",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1900",
    "index": "D",
    "title": "Small GCD",
    "statement": "Let $a$, $b$, and $c$ be integers. We define function $f(a, b, c)$ as follows:\n\nOrder the numbers $a$, $b$, $c$ in such a way that $a \\le b \\le c$. Then return $\\gcd(a, b)$, where $\\gcd(a, b)$ denotes the greatest common divisor (GCD) of integers $a$ and $b$.\n\nSo basically, we take the $\\gcd$ of the $2$ smaller values and ignore the biggest one.\n\nYou are given an array $a$ of $n$ elements. Compute the sum of $f(a_i, a_j, a_k)$ for each $i$, $j$, $k$, such that $1 \\le i < j < k \\le n$.\n\nMore formally, compute $$\\sum_{i = 1}^n \\sum_{j = i+1}^n \\sum_{k =j +1}^n f(a_i, a_j, a_k).$$",
    "tutorial": "Let $m$ be the biggest value in the array. Calculate array $x$ such that $x_i$ ($1 \\le i \\le m$) is the number of triples which have $\\gcd$ of $i$. Then the answer is the sum of $i \\cdot x_i$ over all $i$ ($1 \\le i \\le m$). Value of $\\lfloor \\frac{m}{1} \\rfloor + \\lfloor \\frac{m}{2} \\rfloor + \\lfloor \\frac{m}{3} \\rfloor + \\ldots + \\lfloor \\frac{m}{m} \\rfloor$ is around $m log m$. We calculate $x_i$ from $x_m$ to $x_1$. For some $i$, we can first calculate the number of triples that have a value of function $f$ that is an integer multiple of $i$, and then from it subtract $x_{2i}, x_{3i}, x_{4i} \\ldots$. Because of the previous hint, the subtractions will be quite fast. Now the question is how to calculate the number of triples that have a value of function $f$ that is an integer multiple of $i$. Numbers up to $100\\,000$ can have at most $128$ divisors. As the order in which numbers are given does not matter, we can sort the array. Now for each number $d$ ($1 \\le d \\le M$) store indices of all numbers that are divisible by $d$ in an array of vectors. Now we will for each number $d$ ($1 \\le d \\le m$) count the number of triples. To find the number of triples that have a gcd value that is an integer multiple of $d$, we can do the following. We go over the index of the number that will be value $b$ in the function. We can utilize the vectors we calculated in the previous step for that. Say that the current index is $i$. Then for value $c$ we can pick any number with an index larger than $i$ as the array is sorted. For value $a$, we can pick any of the numbers divisible by $d$ with an index less than $i$, the number of which we can get from the vector. By multiplying those $2$ numbers we get the number of triples that have $a_i$ as their middle value. As numbers can have up to $128$ divisors, the step above is quite fast. Total time complexity is $O(m log m + n log n + 128 \\cdot n)$. Total memory complexity is $O(m + 128 \\cdot n)$. Solve the problem if $f(a,b,c) = \\gcd (a,c)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1900",
    "index": "E",
    "title": "Transitive Graph",
    "statement": "You are given a \\textbf{directed} graph $G$ with $n$ vertices and $m$ edges between them.\n\nInitially, graph $H$ is the same as graph $G$. Then you decided to perform the following actions:\n\n- If there exists a triple of vertices $a$, $b$, $c$ of $H$, such that there is an edge from $a$ to $b$ and an edge from $b$ to $c$, but there is no edge from $a$ to $c$, add an edge from $a$ to $c$.\n- Repeat the previous step as long as there are such triples.\n\nNote that the number of edges in $H$ can be up to $n^2$ after performing the actions.\n\nYou also wrote some values on vertices of graph $H$. More precisely, vertex $i$ has the value of $a_i$ written on it.\n\nConsider a simple path consisting of $k$ \\textbf{distinct} vertices with indexes $v_1, v_2, \\ldots, v_k$. The length of such a path is $k$. The value of that path is defined as $\\sum_{i = 1}^k a_{v_i}$.\n\nA simple path is considered the longest if there is no other simple path in the graph with greater length.\n\nAmong all the longest simple paths in $H$, find the one with the smallest value.",
    "tutorial": "Try to simplify graph $H$. Look at strongly connected components of $G$, and what happens with them. Use dp to find the answer. The main observation is what $H$ looks like. All the strongly connected components (SCC) in $G$ will become fully connected subgraphs in $H$. Secondly, take any two vertices $a$ and $b$ such that $a$ and $b$ are not in the same SCC. We can let $S_a$ be a set of vertices that are in the same SCC as $a$ ($a$ included). Similarly, $S_b$ is a set of vertices that are in the same SCC as $b$. If there is an edge going from $a$ to $b$, then for any two vertices $x$ and $y$ such that $x$ belongs to $S_a$ and $y$ belongs to $S_b$, there is an edge going from $x$ to $y$. Both of the previously stated facts about the graph can be proven by induction. Now, let's say that there is the longest path that goes through at least one vertex of an SCC. Then that path goes through all the vertices in the SCC, due to all vertices in SCC being connected to the same vertices outside the SCC and due to the fact that SCC is a complete subgraph. Now we can construct the graph $H'$. Each of the SCCs from $H$ will be a vertex in $H'$. The number on the vertex will be equal to the sum of all numbers on the vertices of the SCC that it was constructed from. Edges between two new vertexes will be added if there is an edge between their original SCCs. The edge will have a weight equal to the size of the SCC that it is going into. An additional vertex will be added at index $0$ and an edge will be made between it and all other vertices with $0$ ingoing edges. Weight will be determined based on the size of the SCC of the vertex that the edge is going into. Due to the previous observations, the answer for the $H'$ will be the same as the answer for the $H$. However, notice that $H'$ is a DAG. That means that the answer for it can be computed using DP after topological ordering. Total time and memory complexity is $O(n)$. We will define the value of the path as the biggest value of a vertex on the path. Among the values of all the longest paths, find the median one. It is guaranteed that there are at most $10^{18}$ longest paths starting from each node. (So basically, you can ignore overflow in the number of paths) The rest of the constraints are the same.",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1900",
    "index": "F",
    "title": "Local Deletions",
    "statement": "For an array $b_1, b_2, \\ldots, b_m$, for some $i$ ($1 < i < m$), element $b_i$ is said to be a local minimum if $b_i < b_{i-1}$ and $b_i < b_{i+1}$. Element $b_1$ is said to be a local minimum if $b_1 < b_2$. Element $b_m$ is said to be a local minimum if $b_m < b_{m-1}$.\n\nFor an array $b_1, b_2, \\ldots, b_m$, for some $i$ ($1 < i < m$), element $b_i$ is said to be a local maximum if $b_i > b_{i-1}$ and $b_i > b_{i+1}$. Element $b_1$ is said to be a local maximum if $b_1 > b_2$. Element $b_m$ is said to be a local maximum if $b_m > b_{m-1}$.\n\nLet $x$ be an array of distinct elements. We define two operations on it:\n\n- $1$ — delete all elements from $x$ that are \\textbf{not} local minima.\n- $2$ — delete all elements from $x$ that are \\textbf{not} local maxima.\n\nDefine $f(x)$ as follows. Repeat operations $1, 2, 1, 2, \\ldots$ in that order until you get only one element left in the array. Return that element.\n\nFor example, take an array $[1,3,2]$. We will first do type $1$ operation and get $[1, 2]$. Then we will perform type $2$ operation and get $[2]$. Therefore, $f([1,3,2]) = 2$.\n\nYou are given a permutation$^\\dagger$ $a$ of size $n$ and $q$ queries. Each query consists of two integers $l$ and $r$ such that $1 \\le l \\le r \\le n$. The query asks you to compute $f([a_l, a_{l+1}, \\ldots, a_r])$.\n\n$^\\dagger$ A permutation of length $n$ is an array of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$, but there is $4$ in the array).",
    "tutorial": "Solve the problem for $q=1$. We can just simulate the process. Each operation removes at least half of the elements, meaning that we will perform at most $log n$ operations. Solve the problem if each $l_i = 1$. So basically, solve the problem for each prefix. Keep values that are in the array after $1$, $2$, $3$, $\\cdots$, $log n$ operations. Let's call those array's layers. Layer $0$ is an array after $0$ operations, layer $1$ after $1$ operation, and so on. When we add a value to the end of the layer, only $1$ number that was previously local extreme (local minimum or maximum, depending on layer) might unbecome local extreme if the new value becomes local extreme. So we can just propagate this update to all layers. Try to simulate the process of updating described in hint $4$. Also, notice that if the array is longer than $3$, we can handle prefix and suffix updates separately. Read the hints. Now we will precompute and store the array after each operation on the entire permutation. We will call those array layers. We can now solve queries in $O(log n)$. If a query involves a small number of elements, we can just brute force it. Otherwise, we do the following: Now let's define our queries a bit differently. We are given some array $x$, which will be a subarray of some layer, and $2$ values, $a$ and $b$. We will get array $y$ by appending $a$ to the start of $x$ and appending $b$ to the end of $x$. We are interested in the value of $f$($y$). It is easy to see that all queries involving $3$ or more elements can be converted into the modified query. If $|y|$ is small, we can just brute force it. Otherwise, we can transform it into a query on the next layer in constant time, or in $O(log n)$. Now, the first thing to notice is that all elements in $x$ that are neither first nor last will be deleted only if they were deleted when we performed operations on the whole permutation. That means that they will represent some interval on the next layer, let's call it $z$. (That interval can be found either with binary search or in $O(1)$ with precomputation) It holds that $|z|$ is around half of $|x|$. Now, notice that among $a$ and the first element of $x$, there has to be at least one deletion. The same goes for the last element of $x$ and $b$. So now we have transformed the query onto the next level in $O(1)$, or $O(log n)$. As we will do at most $O(log n)$ such transformations, the complexity of a single query is either $O(log n)$ or $O(log^2 n)$ depending on the way we find the next interval, both of which should be fast enough to pass. Total time complexity: $O(n + q log n)$ or $O(n + q log^2 n)$. Total memory complexity: $O(n+q)$ 2103D - Local Construction",
    "tags": [
      "binary search",
      "data structures",
      "implementation"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1901",
    "index": "A",
    "title": "Line Trip",
    "statement": "There is a road, which can be represented as a number line. You are located in the point $0$ of the number line, and you want to travel from the point $0$ to the point $x$, and back to the point $0$.\n\nYou travel by car, which spends $1$ liter of gasoline per $1$ unit of distance travelled. When you start at the point $0$, your car is fully fueled (its gas tank contains the maximum possible amount of fuel).\n\nThere are $n$ gas stations, located in points $a_1, a_2, \\dots, a_n$. When you arrive at a gas station, you fully refuel your car. \\textbf{Note that you can refuel only at gas stations, and there are no gas stations in points $0$ and $x$}.\n\nYou have to calculate the minimum possible volume of the gas tank in your car (in liters) that will allow you to travel from the point $0$ to the point $x$ and back to the point $0$.",
    "tutorial": "We can iterate over the volume of the gas tank from $1$ to $\\infty$ (in fact $200$ is enough due to problem limitations) and check whether it's enough to travel from the point $0$ to the point $x$, and back. Let the volume be $V$, then all the following inequalities (which correspond to the ability to travel from the current gas station, having a full tank, to the next one) must be met: $a_1 - 0 \\le V$, $a_2 - a_1 \\le V$, ..., $a_n - a_{n-1} \\le V$, and $2(x - a_n) \\le V$ (the multiplier $2$ because there is no gas station at $x$, and we have to go from $a_n$ to $x$ and back without refueling). If all these conditions hold, then $V$ can be the answer. However, we can notice that the minimum value of $V$ that is sufficient for the travel is just the maximum of the left sides of inequalities written above. In other words, the answer to the problem is $\\max(a_1, a_2 - a_1, \\dots, a_n - a_{n-1}, 2(x-a_n))$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, x;\n    cin >> n >> x;\n    int prev = 0, ans = 0;\n    for (int i = 0; i < n; ++i) {\n      int a; cin >> a;\n      ans = max(ans, a - prev);\n      prev = a;\n    }\n    ans = max(ans, 2 * (x - prev));\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1901",
    "index": "B",
    "title": "Chip and Ribbon",
    "statement": "There is a ribbon divided into $n$ cells, numbered from $1$ to $n$ from left to right. Initially, an integer $0$ is written in each cell.\n\nMonocarp plays a game with a chip. The game consists of several turns. During the first turn, Monocarp places the chip in the $1$-st cell of the ribbon. During each turn \\textbf{except for the first turn}, Monocarp does \\textbf{exactly one} of the two following actions:\n\n- move the chip to the next cell (i. e. if the chip is in the cell $i$, it is moved to the cell $i+1$). This action is impossible if the chip is in the last cell;\n- choose any cell $x$ and teleport the chip into that cell. \\textbf{It is possible to choose the cell where the chip is currently located}.\n\nAt the end of each turn, the integer written in the cell with the chip is increased by $1$.\n\nMonocarp's goal is to make some turns so that the $1$-st cell contains the integer $c_1$, the $2$-nd cell contains the integer $c_2$, ..., the $n$-th cell contains the integer $c_n$. He wants to teleport the chip as few times as possible.\n\nHelp Monocarp calculate the minimum number of times he has to teleport the chip.",
    "tutorial": "At first, let's change the statement a bit: instead of teleporting our chip into cell $x$, we create a new chip in cell $x$ (it means that the chip does not disappear from the cell where it was located). And when we want to move a chip, we move any chip to the next cell. Then, $c_i$ will be the number of times a chip appeared in the cell $i$, and the problem will be the same: ensure the condition on each $c_i$ by \"creating\" the minimum number of chips. Let's look at value of $c_1$. If $c_1 > 1$, we have to create at least $c_1 - 1$ new chips in cell $1$. Let's create that number of chips in that cell. Then, let's see how we move chips from the cell $i$ to the cell $(i+1)$. If $c_i \\ge c_{i+1}$, then all chips that appeared in the cell $(i+1)$ could be moved from the $i$-th cell, so we don't need to create any additional chips in that cell. But if $c_i < c_{i+1}$, then at least $c_{i+1} - c_i$ chips should be created in the cell $(i+1)$, since we can move at most $c_i$ chips from the left. So, for every $i$ from $2$ to $n$, we have to create $\\max(0, c_i - c_{i-1})$ chips in the $i$-th cell; and the number of times we create a new chip in total is $c_1 - 1 + \\sum\\limits_{i=2}^{n} \\max(0, c_i - c_{i-1})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 200'000;\n \nint t;\n \nint main() {\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        int n;\n        cin >> n;\n        vector <int> cnt(n);\n        long long res = 0;\n        int cur = 0;\n        for (int i = 0; i < n; ++i) {\n            cin >> cnt[i];\n            if (cnt[i] > cur) \n                res += cnt[i] - cur;\n            cur = cnt[i];\n        }\n        \n        cout << res - 1 << endl;\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1901",
    "index": "C",
    "title": "Add, Divide and Floor",
    "statement": "You are given an integer array $a_1, a_2, \\dots, a_n$ ($0 \\le a_i \\le 10^9$). In one operation, you can choose an integer $x$ ($0 \\le x \\le 10^{18}$) and replace $a_i$ with $\\lfloor \\frac{a_i + x}{2} \\rfloor$ ($\\lfloor y \\rfloor$ denotes rounding $y$ down to the nearest integer) for all $i$ from $1$ to $n$. Pay attention to the fact that all elements of the array are affected on each operation.\n\nPrint the smallest number of operations required to make all elements of the array equal.\n\nIf the number of operations is less than or equal to $n$, then print the chosen $x$ for each operation. If there are multiple answers, print any of them.",
    "tutorial": "Sort the array. Notice how applying the operation doesn't change the order of the elements, regardless of $x$. It means that it's enough to make the initial minimum and maximum equal to make all elements equal. Consider the difference between the minimum and the maximum values. What happens to it after an operation? Let the minimum be $a$ and the maximum be $b$. Then it's $\\lfloor \\frac{b + x}{2} \\rfloor - \\lfloor \\frac{a + x}{2} \\rfloor$. The roundings are difficult to deal with, so let's pretend the parities always align to even. So it's $\\frac{b + x}{2} - \\frac{a + x}{2} = \\frac{b - a}{2}$. Apparently, the difference is just getting divided by $2$. Let's bring the parities back. Notice that the rounding of the difference depends only on the parities of $a, b$ and $x$. You can consider all cases of parities of $a$ and $b$ to discover that it's always possible to divide the difference by $2$, rounding down, and it's never possible to make it less than that. One easy algorithm to achieve that is the following: if the minimum is even, choose $x = 0$; otherwise, choose $x = 1$. Repeat until the minimum is equal to the maximum. Overall complexity: $O(n + \\log A)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\tx, y = min(a), max(a)\n\tres = []\n\twhile x != y:\n\t\tres.append(x % 2)\n\t\tx = (x + res[-1]) // 2\n\t\ty = (y + res[-1]) // 2\n\tprint(len(res))\n\tif len(res) <= n:\n\t\tprint(*res)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1901",
    "index": "D",
    "title": "Yet Another Monster Fight",
    "statement": "Vasya is a sorcerer that fights monsters. Again. There are $n$ monsters standing in a row, the amount of health points of the $i$-th monster is $a_i$.\n\nVasya is a very powerful sorcerer who knows many overpowered spells. In this fight, he decided to use a chain lightning spell to defeat all the monsters. Let's see how this spell works.\n\nFirstly, Vasya chooses an index $i$ of some monster ($1 \\le i \\le n$) and the initial power of the spell $x$. Then the spell hits monsters \\textbf{exactly} $n$ times, one hit per monster. The first target of the spell is always the monster $i$. For every target \\textbf{except for the first one}, the chain lightning will choose a \\textbf{random} monster \\textbf{who was not hit by the spell and is adjacent to one of the monsters that already was hit}. So, each monster will be hit exactly once. The first monster hit by the spell receives $x$ damage, the second monster receives $(x-1)$ damage, the third receives $(x-2)$ damage, and so on.\n\nVasya wants to show how powerful he is, so he wants to kill all the monsters with a single chain lightning spell. The monster is considered dead if the damage he received is not less than the amount of its health points. On the other hand, Vasya wants to show he doesn't care that much, so he wants to choose the \\textbf{minimum} initial power of the spell $x$ such that it kills all monsters, \\textbf{no matter which monster (among those who can get hit) gets hit on each step}.\n\nOf course, Vasya is a sorcerer, but the amount of calculations required to determine the optimal spell setup is way above his possibilities, so you have to help him find the minimum spell power required to kill all the monsters.\n\nNote that Vasya chooses the initial target and the power of the spell, other things should be considered random and Vasya wants to kill all the monsters even in the worst possible scenario.",
    "tutorial": "Let's start with a naive solution. Let $i$ be the index of the monster we started with. Let's make sure that we can kill all monsters, starting with monster $i$. Suppose we have chosen spell power $x$. How to check if all monsters will be definitely killed? Let's iterate on each monster $j$ and calculate the minimum possible damage it can get: if $i = j$, then the $j$-th monster will receive exactly $x$ damage. So, $x$ should be at least $a_j$; if $i > j$, then the minimum amount of damage the $j$-th monster may receive happens when the spell first strikes all monsters to the right of monster $i$, and then goes to the left of monster $i$. It means that $n - j$ monsters will be struck before the $j$-th monster, so the $j$-th monster will receive $x - (n-j)$ damage. So, $x$ should be at least $a_j + (n-j)$ for every $j < i$; and if $i < j$, then the minimum amount of of damage the $j$-th monster may receive happens when the spell first strikes all monsters to the left of monster $i$, and then goes to the right of monster $i$. It means that $j-1$ monsters will be struck before the $j$-th monster, so the $j$-th monster will receive $x - (j-1)$ damage. So, $x$ should be at least $a_j + (j-1)$ for every $j > i$. So, if we want to start with the $i$-th monster, the minimum spell power we need is $\\max(\\max\\limits_{j=1}^{i-1} a_j + (n-j), a_i, \\max\\limits_{j=i+1}^{n} a_j + (j-1))$. This gives us a solution in $O(n^2)$, but it can be sped up to $O(n)$ using prefix and suffix maxima.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n//  freopen(\"output.txt\", \"w\", stdout);\n#endif\n    \n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (auto &it : a) cin >> it;\n    \n    vector<int> pref(n), suf(n);\n    for (int i = 0; i < n; ++i) {\n        pref[i] = a[i] + (n - i - 1);\n        suf[i] = a[i] + i;\n    }\n    for (int i = 1; i < n; ++i) {\n        pref[i] = max(pref[i], pref[i - 1]);\n    }\n    for (int i = n - 2; i >= 0; --i) {\n        suf[i] = max(suf[i], suf[i + 1]);\n    }\n    \n    int ans = 2e9;\n    for (int i = 0; i < n; ++i) {\n        int cur = a[i];\n        if (i > 0) cur = max(cur, pref[i - 1]);\n        if (i + 1 < n) cur = max(cur, suf[i + 1]);\n        ans = min(ans, cur);\n    }\n    \n    cout << ans << endl;\n    \n    return 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1901",
    "index": "E",
    "title": "Compressed Tree",
    "statement": "You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.\n\nYou can perform the following operation any number of times (possibly zero):\n\n- choose a vertex which has \\textbf{at most $1$} incident edge and remove this vertex from the tree.\n\nNote that you can delete all vertices.\n\nAfter all operations are done, you're compressing the tree. The compression process is done as follows. While there is a vertex having \\textbf{exactly $2$} incident edges in the tree, perform the following operation:\n\n- delete this vertex, connect its neighbors with an edge.\n\nIt can be shown that if there are multiple ways to choose a vertex to delete during the compression process, the resulting tree is still the same.\n\nYour task is to calculate the maximum possible sum of numbers written on vertices after applying the aforementioned operation any number of times, and then compressing the tree.",
    "tutorial": "We can use dynamic programming on tree to solve this problem. After we're done removing vertices, a vertex will be left in the tree after the compression process if and only if its degree is not $2$. So, we can try to choose the number of children for each vertex in dynamic programming, and depending on this number of children, the vertex we're considering is either removed from the tree during the compression, or left in the tree. But if we want to use dynamic programming, we have to root the tree at some vertex, so the degree of each vertex depends not only on the number of its children we left in the tree, but also on whether there exists an edge leading from the ancestor to that vertex. So, for each vertex, we will consider two values of dynamic programming: the best answer for its subtree if there is an edge leading into it from the parent (i. e. we haven't deleted everything outside of that subtree), and the answer if there is no edge leading from the parent (i. e. we deleted everything outside of that subtree). Let the first of these two values be $dp_v$ - the maximum answer for subtree of $v$ if there is at least one non-deleted vertex not in the subtree of vertex $v$ (i.e there is an edge from vertex $v$ up the tree). Let's look at the dp transitions, depending on the number of children of vertex $v$ that are not deleted: $0$: $dp_v = \\max(dp_v, a_v)$; $1$: $dp_v = \\max(dp_v, \\max\\limits_u dp_u)$ ($a_v$ is not taken into account, because $v$ has $2$ incident edges and will be compressed); at least $2$: $dp_v = \\max(dp_v, a_v + \\sum\\limits_u dp_u)$. Then let us consider the case when the resulting tree is in the subtree of some vertex $v$. We can update the global answer depending on the number of children of vertex $v$ that are not deleted: $0$: $ans = \\max(ans, a_v)$; $1$: $ans = \\max(ans, a_v + \\max\\limits_u dp_u)$; $2$: $ans = \\max(ans, \\max\\limits_{u_1, u_2} dp_{u_1} + dp_{u_2})$ ($a_v$ is not taken into account, because $v$ has $2$ incident edges and will be compressed); at least $3$: $ans = \\max(ans, a_v + \\sum\\limits_u dp_u)$. For convenience, we can calculate auxiliary dynamic programming for children of vertex $v$: $sum_i$ is the maximum sum of $dp_u$ for $i$ children. From above written transitions, we can see that, $sum_3$ can store maximum sum for at least $3$ children. Don't forget that we can delete all vertices, so the answer is at least $0$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing li = long long;\n \nconst li INF = 1e18;\nconst int N = 555555;\n \nint n;\nint a[N];\nvector<int> g[N];\nli dp[N];\nli ans;\n \nvoid calc(int v, int p) {\n  vector<li> sum(4, -INF);\n  sum[0] = 0;\n  for (int u : g[v]) if (u != p) {\n    calc(u, v);\n    for (int i = 3; i >= 0; --i) {\n      sum[min(i + 1, 3)] = max(sum[min(i + 1, 3)], sum[i] + dp[u]);\n    }\n  }\n  dp[v] = -INF;\n  for (int j = 0; j < 4; ++j) {\n    dp[v] = max(dp[v], sum[j] + (j == 1 ? 0 : a[v]));\n    ans = max(ans, sum[j] + (j == 2 ? 0 : a[v]));\n  }\n}\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    cin >> n;\n    for (int i = 0; i < n; ++i) cin >> a[i];\n    for (int i = 0; i < n; ++i) g[i].clear();\n    for (int i = 0; i < n - 1; ++i) {\n      int x, y;\n      cin >> x >> y;\n      --x; --y;\n      g[x].push_back(y);\n      g[y].push_back(x);\n    }\n    ans = 0;\n    calc(0, -1);\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1901",
    "index": "F",
    "title": "Landscaping",
    "statement": "You are appointed to a very important task: you are in charge of flattening one specific road.\n\nThe road can be represented as a polygonal line starting at $(0, 0)$, ending at $(n - 1, 0)$ and consisting of $n$ vertices (including starting and ending points). The coordinates of the $i$-th vertex of the polyline are $(i, a_i)$.\n\n\"Flattening\" road is equivalent to choosing some line segment from $(0, y_0)$ to $(n - 1, y_1)$ such that all points of the polyline are below the chosen segment (or on the same height). Values $y_0$ and $y_1$ \\textbf{may be real}.\n\nYou can imagine that the road has some dips and pits, and you start pouring pavement onto it until you make the road flat. Points $0$ and $n - 1$ have infinitely high walls, so pavement doesn't fall out of segment $[0, n - 1]$.\n\nThe cost of flattening the road is equal to the area between the chosen segment and the polyline. You want to minimize the cost, that's why the flattened road is not necessary horizontal.\n\nBut there is a problem: your data may be too old, so you sent a person to measure new heights. The person goes from $0$ to $n - 1$ and sends you new heights $b_i$ of each vertex $i$ of the polyline.\n\nSince measuring new heights may take a while, and you don't know when you'll be asked, calculate the minimum cost (and corresponding $y_0$ and $y_1$) to flatten the road after each new height $b_i$ you get.",
    "tutorial": "Let's say that we are searching for the best line that contains the best segment. Observation $1$: the best line touches at least one vertex of the polyline. Otherwise, you can push it down until it touches polyline. Observation $2$: the best line touches two vertices of the polyline. Suppose it touches only one vertex $i$ then it's not hard to prove that rotating the line around point $i$ either clockwise or counterclockwise will decrease the area under the line. Observation $3$: if both points are on the left half ($i < j < \\frac{n}{2}$) then rotating the line clockwise around point $j$ will decrease the area. Analogically, if both points are on the right half ($\\frac{n}{2} < i < j$) then rotating the line counterclockwise around $i$ will decrease the area. Observation $4$: since all points of the polyline should be under the line, then the vertices the line touches are the consecutive vertices on the convex hull of the polyline. In total, we understand that the pair of points we need forms a segment of the convex hull that crosses a vertical line $x = \\frac{n}{2}$. Knowing that, what can we do? Let's split all vertices in two halves: \"left half\" with all vertices to the left of $\\frac{n}{2}$ and \"right half\" with all vertices to the right. Note that while we process the first half of \"queries\" the right half (vertices in $[\\frac{n}{2}, n - 1]$) remains the same. If we know how to process the first half of queries, then processing the second half is practically the same thing but in the reverse order. So, how to find that best segment of the convex hull that crosses $x = \\frac{n}{2}$ efficiently while we work with the left half of vertices? Note that if we look at all segments that connect vertex from the left part with vertex from the right part: each segment will certainly cross $x = \\frac{n}{2}$ in some real point $y_c$; the segment of the convex hull will have maximum possible $y_c$ (otherwise, it's not a convex hull segment). There are around $n^2$ segment that crosses $\\frac{n}{2}$ but we don't need all of them. Let's calculate for each vertex $i$ ($i < \\frac{n}{2}$) (both the old and new values) the segment that crosses $\\frac{n}{2}$ and has $y_c$ maximum possible. Note that this \"maximum possible\" segment connects $i$ with some vertex $j$ that has to be on the convex hull that was built on the right half (otherwise, we will find convex hull point with higher slope and its $y_c$ will be bigger). In other words, for each point from the left, we are searching a tangent line to the convex hull on the right. And we can do it efficiently with binary search while checking some cross products. Let's name that tangent line as $t(x, y)$ where $(x, y)$ is a point from the left half. One more observation: $y_c = \\frac{y_0 + y_1}{2}$. You can prove it by looking at the area of trapezoid that formed by segment $(0, y_0) - (n - 1, y_1)$. So, let's define a function $f(l)$ that takes line $l$ and returns $2 y_c$ (or the answer to the task). We have all we need to calculate the answer: the answer to the $i$-th query is equal to the maximum among $f(t(j, b_j))$ for all $j \\le i$ and $f(t(j, a_j))$ for all $i < j < \\frac{n}{2}$. In total, the solution is next: build convex hull on vertices $[\\frac{n}{2}, n - 1]$; calculate $t(i, a_i)$ with binary search for all $i < \\frac{n}{2}$; calculate $f(t(i, a_i))$ for all $i < \\frac{n}{2}$ and store suffix maximums among these values; calculate $t(i, b_i)$ with binary search for all $i < \\frac{n}{2}$; calculate $f(t(i, b_i))$ for all $i < \\frac{n}{2}$ and store prefix maximums among these values; calculate the $i$-th answer as maximum between the $i$-th prefix maximum and the $(i+1)$-th suffix maximum. In order to solve the task for the right half $[\\frac{n}{2}, n - 1]$ just reverse arrays $a$ and $b$ and swap them, and do the same algorithm above. It's true, because replacing first $k$ values $a_i$ with $b_i$ in array $a$ is equivalent to replacing last $n - k$ values $b_i$ with $a_i$ in array $b$. Complexity of the solution is $O(n \\log n)$ because of binary searches. Note that we can do everything in integers, except calculating the values of function $f$ and taking maximum among $f$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n \n#define x first\n#define y second\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n \ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \" \";\n\t\tout << v[i];\n\t}\n\treturn out;\n}\n \npt operator+ (const pt &a, const pt &b) {\n\treturn {a.x + b.x, a.y + b.y};\n}\npt operator- (const pt &a, const pt &b) {\n\treturn {a.x - b.x, a.y - b.y};\n}\nli operator *(const pt &a, const pt &b) {\n\treturn a.x * 1ll * b.x + a.y * 1ll * b.y;\n}\nli operator %(const pt &a, const pt &b) {\n\treturn a.x * 1ll * b.y - a.y * 1ll * b.x;\n}\n \nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n \nint n;\nvector<pt> old, nw;\n \ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\told.resize(n);\n\tnw.resize(n);\n\tfore (i, 0, n) {\n\t\told[i].x = i;\n\t\tcin >> old[i].y;\n\t}\n\tfore (i, 0, n) {\n\t\tnw[i].x = i;\n\t\tcin >> nw[i].y;\n\t}\n\treturn true;\n}\n \ninline ld getTr(const pt &a, const pt &b) {\n\tpt tmp = b - a;\n\tpt v = {-tmp.y, tmp.x};\n\tld c = v * a;\n\tld y0 = (c - v.x * 0) / v.y;\n\tld y1 = (c - v.x * li(n - 1)) / v.y;\n\treturn (y0 + y1);\n}\n \nvector<pt> hull(const vector<pt> &ps, int l, int r) {\n\tvector<pt> h;\n\tfore (i, l, r) {\n\t\twhile (sz(h) > 1 && (h[sz(h) - 1] - h[sz(h) - 2]) % (ps[i] - h[sz(h) - 1]) >= 0)\n\t\t\th.pop_back();\n\t\th.push_back(ps[i]);\n\t}\n\treturn h;\n}\n \ninline void solve() {\n\tvector<ld> maxTr(n - 1, 0);\n\tfore (t, 0, 2) {\n\t\tauto h = hull(old, n / 2, n);\n \n\t\tauto best = [&](const pt &p) {\n\t\t\tint l = -1, r = sz(h) - 1;\n\t\t\twhile (r - l > 1) {\n\t\t\t\tint mid = (l + r) >> 1;\n\t\t\t\tif ((h[mid] - p) % (h[mid + 1] - h[mid]) >= 0)\n\t\t\t\t\tl = mid;\n\t\t\t\telse\n\t\t\t\t\tr = mid;\n\t\t\t}\n\t\t\treturn h[r].x;\n\t\t};\n\t\t\n\t\tvector<ld> bs(n / 2 + 1, 0);\n\t\tfor (int i = n / 2 - 1; i >= 0; i--) {\n\t\t\tint j = best(old[i]);\n\t\t\tbs[i] = getTr(old[i], old[j]);\n\t\t\tbs[i] = max(bs[i], bs[i + 1]);\n\t\t}\n\t\t\n\t\tld lans = 0;\n\t\tfore (i, 0, n / 2) {\n\t\t\tint j = best(nw[i]);\n\t\t\tlans = max(lans, getTr(nw[i], old[j]));\n\t\t\tmaxTr[i] = max({maxTr[i], lans, bs[i + 1]});\n\t\t}\n\t\t\n\t\treverse(all(old));\n\t\treverse(all(nw));\n\t\tswap(old, nw);\n\t\tfore (i, 0, n)\n\t\t\told[i].x = nw[i].x = i;\n\t\t\n\t\treverse(all(maxTr));\n\t}\n\t\t\t\n\tmaxTr.push_back(maxTr.back());\n\tcout << maxTr << endl;\n}\n \nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(12);\n\t\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "geometry",
      "two pointers"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1902",
    "index": "A",
    "title": "Binary Imbalance",
    "statement": "You are given a string $s$, consisting only of characters '0' and/or '1'.\n\nIn one operation, you choose a position $i$ from $1$ to $|s| - 1$, where $|s|$ is the current length of string $s$. Then you insert a character between the $i$-th and the $(i+1)$-st characters of $s$. If $s_i = s_{i+1}$, you insert '1'. If $s_i \\neq s_{i+1}$, you insert '0'.\n\nIs it possible to make the number of zeroes in the string strictly greater than the number of ones, using any number of operations (possibly, none)?",
    "tutorial": "If the string consists of all ones, then it's always impossible. Any operation will only add more ones to the string. Otherwise, let's show that it's always possible. If the string consists of all zeroes, no operations are required. Otherwise, there always exists a pair of adjacent zero and one. Applying an operation between them will increase the number of zeroes by one, and there still will exist a pair of adjacent zero and one. Thus, that operation can be performed infinitely many times. We can keep performing it until there are more zeroes than ones. Overall complexity: $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ts = input()\n\tprint(\"NO\" if s.count('1') == n else \"YES\")",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1902",
    "index": "B",
    "title": "Getting Points",
    "statement": "Monocarp is a student at Berland State University. Due to recent changes in the Berland education system, Monocarp has to study only one subject — programming.\n\nThe academic term consists of $n$ days, and in order not to get expelled, Monocarp has to earn at least $P$ points during those $n$ days. There are two ways to earn points — completing practical tasks and attending lessons. For each practical task Monocarp fulfills, he earns $t$ points, and for each lesson he attends, he earns $l$ points.\n\nPractical tasks are unlocked \"each week\" as the term goes on: the first task is unlocked on day $1$ (and can be completed on any day from $1$ to $n$), the second task is unlocked on day $8$ (and can be completed on any day from $8$ to $n$), the third task is unlocked on day $15$, and so on.\n\nEvery day from $1$ to $n$, there is a lesson which can be attended by Monocarp. And every day, Monocarp chooses whether to study or to rest the whole day. When Monocarp decides to study, he attends a lesson and can complete \\textbf{no more than $2$} tasks, which are already unlocked and not completed yet. If Monocarp rests the whole day, he skips a lesson and ignores tasks.\n\nMonocarp wants to have as many days off as possible, i. e. he wants to maximize the number of days he rests. Help him calculate the maximum number of days he can rest!",
    "tutorial": "Firstly, let $c$ be the total number of tasks in the term. Then $c = \\left\\lceil\\frac{n}{7}\\right\\rceil = \\left\\lfloor \\frac{n + 6}{7} \\right\\rfloor$. Suppose, Monocarp will study exactly $k$ days. How many points will he get? He gets $k \\cdot l$ for attending lessons and, since he can complete at most $2$ tasks per day, he will solve no more than $\\min(c, 2 \\cdot k)$ tasks. So, in the best possible scenario he will get $k \\cdot l + \\min(c, 2 k) \\cdot t$ points. And, actually, it's possible to get exactly that many points. For example, Monocarp can study the last $k$ days of the term: at the $n$-th day he will complete $(c-1)$-th and $c$-th tasks, at the $(n-1)$-th day - tasks $(c - 3)$ and $(c - 2)$ and so on. It's easy to see that all that tasks will be available at the day Monocarp completes them. In total, we need to find the minimum $k$ such that $k \\cdot l + \\min(c, 2 k) \\cdot t \\ge P$. We can analyze two cases, or perform a Binary Search on $k$.",
    "code": "fun main(args: Array<String>) {\n    repeat(readln().toInt()) {\n        val (n, p, l, t) = readln().split(' ').map { it.toLong() }\n        val cntTasks = (n + 6) / 7\n        \n        fun calc(k: Long) = k * l + minOf(2 * k, cntTasks) * t\n        var lf = 0L\n        var rg = n\n        while (rg - lf > 1) {\n            val mid = (lf + rg) / 2\n            if (calc(mid) >= p)\n                rg = mid\n            else\n                lf = mid\n        }\n        println(n - rg)\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1902",
    "index": "C",
    "title": "Insert and Equalize",
    "statement": "You are given an integer array $a_1, a_2, \\dots, a_n$, all its elements are distinct.\n\nFirst, you are asked to insert one more integer $a_{n+1}$ into this array. $a_{n+1}$ should not be equal to any of $a_1, a_2, \\dots, a_n$.\n\nThen, you will have to make all elements of the array equal. At the start, you choose a \\textbf{positive} integer $x$ ($x > 0$). In one operation, you add $x$ to exactly one element of the array. \\textbf{Note that $x$ is the same for all operations}.\n\nWhat's the smallest number of operations it can take you to make all elements equal, after you choose $a_{n+1}$ and $x$?",
    "tutorial": "Let's start by learning how to calculate the function without the insertion. Since $x$ can only be positive, we will attempt to make all elements equal to the current maximum value in the array. Pick some $x$. Now, how to check if it's possible to make every element equal to the maximum? Well, for one element, the difference between the maximum and the element should be divisible by $x$. So, for all elements, all differences should be divisible by $x$. Thus, the greatest common divisor of all differences should be divisible by $x$. Among all values of $x$ that work, we should obviously pick the largest one. The answer is equal to $\\sum\\limits_{i=1}^n \\frac{\\mathit{max} - a_i}{x}$, so it decreases with the increase of $x$. Thus, it only makes sense to make $x = \\mathit{gcd}(\\mathit{max} - a_1, \\mathit{max} - a_2, \\dots, \\mathit{max} - a_n)$. If you think about that from the perspective of the Euclid's algorithm of finding the gcd, you can rewrite it as $\\mathit{gcd}(a_2 - a_1, a_3 - a_2, \\dots, a_n - a_{n - 1}, \\mathit{max} - a_n)$. Think about it on some small $n$. $\\mathit{gcd}(a_3 - a_1, a_2 - a_1) = \\mathit{gcd}((a_3 - a_1) - (a_2 - a_1), a_2 - a_1) = \\mathit{gcd}(a_3 - a_2, a_2 - a_1)$. Basically, you can arbitrarily add or subtract the arguments of gcd from each other. With that interpretation, it's clear that it never makes sense to make all elements equal to anything greater than the current maximum. $x$ will still be required to be divisible by all the adjacent differences, but you will be adding one more condition that can only decrease the gcd. Let's return to the insertion. First, inserting a new element can never decrease the function. You will add one more constraint $a_{n+1} - a_n$ to the gcd. If you increase the maximum value in the array, all $n$ elements will need additional operations to become equal to it instead of the old maximum. If you don't change the maximum, $a_{n+1}$ itself will need some operations to become equal to the maximum. Since $x$ can only decrease, let's try to not change it at all. So, we only add an element of form $a_i + x \\cdot k$ for any integer $k$, if it doesn't appear in the array. Since all elements of the array are also of that form for any $i$, let's instead choose $a_i$ that is the maximum of the array. So, the form is $\\mathit{max} + x \\cdot k$. If we choose a positive $k$, the maximum increases. Thus, the answer increases $k \\cdot n$, since all elements will require $k$ extra operations. Obviously, it doesn't make sense to pick $k > 1$, since $\\mathit{max} + x$ doesn't appear in the array already, and the number of extra operations for it is the minimum possible - just $n$. If we choose a negative $k$, no other elements are affected. Thus, the answer only depends on the number of operations that $a_{n+1}$ will require. So, the best option is to choose the largest $k$ such that $\\mathit{max} + x \\cdot k$ doesn't appear in the array. Worst case, $k = -n$ if the elements are $[\\mathit{max}, \\mathit{max} - x, \\mathit{max} - 2 \\cdot x, \\dots, \\mathit{max} - (n - 1) \\cdot x]$. The number of operations is equal to $-k$, so it's never larger than $n$. Thus, the negative $k$ is always at least as good or even better than the positive $k$. If we change the value of $x$, we can only divide it by something. Thus, it becomes at least twice as small. Notice how it also at least doubles the current answer. The smallest possible current answer is $0 + 1 + 2 + \\dots + (n - 1) = \\frac{n \\cdot (n - 1)}{2}$. For any $n > 2$, that is greater or equal to $n$. If we also consider that $a_{n+1}$ itself will require at least one extra operation, we can extend it to $n > 1$. So, changing $x$ is never better than not changing $x$. Thus, we come to the final algorithm. Calculate $x = \\mathit{gcd}(a_2 - a_1, a_3 - a_2, \\dots, a_n - a_{n - 1})$. For $n = 1$, it's $0$, so we handle it separately - the answer can always be $1$. Then, initialize $k = -1$ and keep decreasing it by $1$ as long as $\\mathit{max} - x \\cdot k$ appears in the array. That can be checked with a structure like set, with a binary search over the sorted array or with two pointers. Finally, calculate the answer as $\\sum\\limits_{i=1}^n \\frac{\\mathit{max} - a_i}{x} - k$. Overall complexity: $O(n \\log n + \\log A)$ per testcase.",
    "code": "from math import gcd\n \nfor _ in range(int(input())):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\tg = 0\n\tfor i in range(n - 1):\n\t\tg = gcd(g, a[i + 1] - a[i])\n\tg = max(g, 1)\n\ta.sort()\n\tj = n - 1\n\tres = a[-1]\n\twhile True:\n\t\twhile j >= 0 and a[j] > res:\n\t\t\tj -= 1\n\t\tif j < 0 or a[j] != res:\n\t\t\tbreak\n\t\tres -= g\n\tprint((a[-1] * (n + 1) - (sum(a) + res)) // g)",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1902",
    "index": "D",
    "title": "Robot Queries",
    "statement": "There is an infinite $2$-dimensional grid. Initially, a robot stands in the point $(0, 0)$. The robot can execute four commands:\n\n- U — move from point $(x, y)$ to $(x, y + 1)$;\n- D — move from point $(x, y)$ to $(x, y - 1)$;\n- L — move from point $(x, y)$ to $(x - 1, y)$;\n- R — move from point $(x, y)$ to $(x + 1, y)$.\n\nYou are given a sequence of commands $s$ of length $n$. Your task is to answer $q$ \\textbf{independent} queries: given four integers $x$, $y$, $l$ and $r$; determine whether the robot visits the point $(x, y)$, while executing a sequence $s$, but the substring from $l$ to $r$ is reversed (i. e. the robot performs commands in order $s_1 s_2 s_3 \\dots s_{l-1} s_r s_{r-1} s_{r-2} \\dots s_l s_{r+1} s_{r+2} \\dots s_n$).",
    "tutorial": "Let's divide the path of the robot into three parts: points before the $l$-th operation; points from the $l$-th to the $r$-th operations; points after the $r$-th operation; The first and the third parts are pretty simple to check because the reverse of the substring $(l, r)$ does not affect them. So we can precompute a dictionary $mp_{x, y}$ that stores all indices of operations in the initial sequence $s$ after which the robot stands at the point $(x, y)$. Then point $(x, y)$ lies on the first part if $mp_{x, y}$ contains at least one index among indices from $0$ to $l-1$. Similarly, for the third part, but we have to check indices from $r$ to $n$. It remains to understand how the second part works. Reversing of the order of commands from $l$ to $r$ means that the robot first performs all commands from $1$ to $l-1$ in the original string, then the command $s_r$, then $s_{r-1}$, and so on, until the command $s_l$. So, it means that the points that the robot visits can be represented as follows: for an integer $k$ such that $l \\le k \\le r$, perform all commands from $1$ to $r$, except for the commands from $l$ to $k$. Let $pos_i$ be the point where the robot stands after the $i$-th operation, and $\\Delta_{i, j}$ be the total movement using operations from $i$ to $j$ (note that $\\Delta_{i, j} = pos_j - pos_{i-1}$). Then we have to check whether there is such $i$ that $l \\le i \\le r$ and $pos_{l-1} + \\Delta_{i, r} = (x, y)$. Using the aforementioned equality for $\\Delta$, we can rewrite this as $pos_{l-1} + pos_r - pos_i = (x, y)$. As a result, our task is to check whether there is such $i$ that $l \\le i \\le r$ and $pos_i = pos_{l-1} + pos_r - (x, y)$. And we already know how to check that, using the dictionary $mp$ (you will need some sort of binary search or a function similar to lower_bound to find whether there is a moment from $l$ to $r$ when a point is visited). If the point belongs to at least one of the parts of the path, then the answer is YES, otherwise the answer is NO.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define x first\n#define y second\n \nusing pt = pair<int, int>;\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int n, q;\n  cin >> n >> q;\n  string s;\n  cin >> s;\n  vector<pt> pos(n + 1);\n  for (int i = 0; i < n; ++i) {\n    pos[i + 1].x = pos[i].x + (s[i] == 'R') - (s[i] == 'L');\n    pos[i + 1].y = pos[i].y + (s[i] == 'U') - (s[i] == 'D');\n  }\n  map<pt, vector<int>> mp;\n  for (int i = 0; i <= n; ++i) mp[pos[i]].push_back(i);\n  auto check = [&](pt p, int l, int r) {\n  \tif (!mp.count(p)) return false;\n  \tauto it = lower_bound(mp[p].begin(), mp[p].end(), l);\n  \treturn it != mp[p].end() && *it <= r;\n  };\n  while (q--) {\n  \tint x, y, l, r;\n  \tcin >> x >> y >> l >> r;\n  \tint nx = pos[r].x + pos[l - 1].x - x, ny = pos[r].y + pos[l - 1].y - y;\n  \tbool f = check({x, y}, 0, l - 1)\n  \t       | check({nx, ny}, l, r - 1)\n  \t       | check({x, y}, r, n);\n  \tcout << (f ? \"YES\" : \"NO\") << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1902",
    "index": "E",
    "title": "Collapsing Strings",
    "statement": "You are given $n$ strings $s_1, s_2, \\dots, s_n$, consisting of lowercase Latin letters. Let $|x|$ be the length of string $x$.\n\nLet a collapse $C(a, b)$ of two strings $a$ and $b$ be the following operation:\n\n- if $a$ is empty, $C(a, b) = b$;\n- if $b$ is empty, $C(a, b) = a$;\n- if the last letter of $a$ is equal to the first letter of $b$, then $C(a, b) = C(a_{1,|a|-1}, b_{2,|b|})$, where $s_{l,r}$ is the substring of $s$ from the $l$-th letter to the $r$-th one;\n- otherwise, $C(a, b) = a + b$, i. e. the concatenation of two strings.\n\nCalculate $\\sum\\limits_{i=1}^n \\sum\\limits_{j=1}^n |C(s_i, s_j)|$.",
    "tutorial": "Let's suppose that when we calculate the collapse of two strings $a$ and $b$, we reverse the string $a$ first, so that instead of checking and removing the last letters of $a$, we do this to the first letters of $a$. Then, $|C(a,b)| = |a| + |b| - 2|LCP(a', b)|$, where $LCP(a', b)$ is the longest common prefix of $a'$ (the reversed version of $a$) and $b$. Then the answer to the problem becomes $2n \\sum\\limits_{i=1}^{n} |s_i| - 2\\sum\\limits_{i=1}^{n}\\sum\\limits_{j=1}^{n} LCP(s_i', s_j)$. We need some sort of data structure that allows us to store all strings $s_i'$ and for every string $s_j$, calculate the total LCP of it with all strings in the structure. There are many ways to implement it (hashing, suffix arrays, etc), but in our opinion, one of the most straightforward is using a trie. Build a trie on all strings $s_i'$. Then, for every vertex of the trie, calculate the number of strings $s_i'$ that end in the subtree of that vertex (you can maintain it while building the trie: when you add a new string into it, increase this value by $1$ on every vertex you go through). If you want to find the $LCP$ of two strings $s$ and $t$ using a trie, you can use the fact that it is equal to the number of vertices that are both on the path to $s$ and on the path to $t$ at the same time (except for the root vertex). This method can be expanded to querying the sum of $LCP$ of a given string $s$ and all strings in the trie as follows: try to find $s$ in the trie. While searching for it, you will descend in the trie and go through vertices that represent prefixes of $s$. For every such prefix, you need the number of strings in the trie that have the same prefix - and it is equal to the number of strings ending in the subtree of the corresponding vertex (which we already calculated). Don't forget that you shouldn't consider the root, since the root represents the empty prefix. This solution works in $O(SA)$ or $O(S \\log A)$, where $S$ is the total length of the strings given in the input and $A$ is the size of the alphabet.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = int(1e6) + 99;\n \nint nxt;\nint to[N][26];\nint sum[N];\nlong long res;\n \nvoid add(const string& s) {\n    int v = 0;\n    ++sum[v];\n    for (auto c : s) {\n        int i = c - 'a';\n        if (to[v][i] == -1)\n            to[v][i] = nxt++;\n        v = to[v][i];\n        ++sum[v];\n    }\n}\n \nvoid upd(const string& s) {\n    int curLen = s.size();\n    int v = 0;\n    \n    for (auto c : s) {\n        int i = c - 'a';\n        if (to[v][i] == -1) {\n            res += sum[v] * 1LL * curLen;\n            break;\n        } else {\n            int nxtV = to[v][i];\n            res += (sum[v] - sum[nxtV]) * 1LL * curLen;\n            --curLen;\n            v = nxtV;\n        }\n    }\n}\n \nvoid solve(int n, vector <string> v) {\n    int sumSizes = 0;\n    for (int i = 0; i < n; ++i)\n        sumSizes += v[i].size();\n        \n    nxt = 1;\n    memset(sum, 0, sizeof sum);\n    memset(to, -1, sizeof to);\n    \n    for(int i = 0; i < n; ++i) \n        add(v[i]);\n    for (int i = 0; i < n; ++i) {\n        reverse(v[i].begin(), v[i].end());\n        upd(v[i]);\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    int n;\n    cin >> n;\n    vector <string> v(n);\n    for (int i = 0; i < n; ++i) \n        cin >> v[i];\n    \n    res = 0;\n    solve(n, v);\n    for(int i = 0; i < n; ++i)\n        reverse(v[i].end(), v[i].end());\n    solve(n, v);\n    \n    cout << res << endl;\n    \n    return 0;\n}",
    "tags": [
      "data structures",
      "strings",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1902",
    "index": "F",
    "title": "Trees and XOR Queries Again",
    "statement": "You are given a tree consisting of $n$ vertices. There is an integer written on each vertex; the $i$-th vertex has integer $a_i$ written on it.\n\nYou have to process $q$ queries. The $i$-th query consists of three integers $x_i$, $y_i$ and $k_i$. For this query, you have to answer if it is possible to choose a set of vertices $v_1, v_2, \\dots, v_m$ (possibly empty) such that:\n\n- every vertex $v_j$ is on the simple path between $x_i$ and $y_i$ (endpoints can be used as well);\n- $a_{v_1} \\oplus a_{v_2} \\oplus \\dots \\oplus a_{v_m} = k_i$, where $\\oplus$ denotes the bitwise XOR operator.",
    "tutorial": "This problem requires working with XOR bases, so let's have a primer on them. Suppose you want to solve the following problem: given a set of integers $x_1, x_2, \\dots, x_k$ and another integer $y$, check whether it is possible to choose several (maybe zero) integers from the set such that their XOR is $y$. It can be solved with Gauss elimination method for systems of linear equations, but there are easier and faster methods, and we will describe one of them. For the given set of integers, let's build an XOR base. An XOR base of a set of integers $X = \\{x_1, x_2, \\dots, x_k\\}$ is another set of integers $A = \\{a_1, a_2, \\dots, a_m\\}$ such that: every integer that can be expressed as the XOR of some integers from the set $X$ can also be expressed as the XOR of some integers from $A$, and vice versa; every integer in $A$ is non-redundant (i. e. if you remove any integer from $A$, the first property is no longer met). For example, one of the XOR bases for $X = \\{1, 2, 3\\}$ is $A = \\{1, 3\\}$. $A = \\{1, 2\\}$ is also an XOR base of $X$, but $A = \\{1, 2, 3\\}$ is not since, for example, $2$ can be deleted. Note that an XOR base is not necessarily a subset of the original set. For example, for $X = \\{1, 2\\}$, $A = \\{1, 3\\}$ is a valid XOR base. Due to the laws of linear algebra, an XOR base of size $m$ supports $2^m$ integers (i. e. $2^m$ integers can be expressed using XOR of some numbers from the base). This means that since in our problem the integers are limited to $20$ bits, the maximum size of an XOR base we need is $20$. Now let's talk about how we build, store and maintain the XOR base. We will use an array of $20$ integers, initially filled with zeroes (an array of all zeroes represents an empty XOR base). Let's call this array $b$. If some integer $b_i$ in this array is non-zero, it has to meet the following constraints: the $i$-th bit is set to $1$ in $b_i$; the $i$-th bit is set to $0$ in every integer $b_j$ such that $j < i$. This is kinda similar to how the Gauss elimination method transforms a matrix representing the system of linear equations: it leaves only one row with non-zero value in the first column and puts it as the first row, then in the next non-zero column it leaves only one row with non-zero value (except for maybe the first row) and puts it as the second row, and so on. Okay, we need to process two types of queries for XOR bases: add an integer and change the XOR base accordingly if needed; check that some integer is supported (i. e. can be represented) by the XOR base. For both of those queries, we will use a special reduction process. In the model solution, it is the function reduce(b,x) that takes an array $b$ representing the XOR base and an integer $x$, and tries to eliminate bits set to $1$ from $x$. In this reduction process, we iterate on bits from $19$ (or the highest bit the number can have set to $1$) to $0$, and every time the bit $i$ we're considering is set to $1$, we try to make it $0$ by XORing $x$ with $b_i$. It can be easily seen that due to the properties of XOR base, XORing with $b_i$ is the only way to do it: if we XOR with any other number $b_j$ such that $j < i$, it won't affect the $i$-th bit; and if we XOR it with $b_j$ such that $j > i$, it sets the $j$-th bit to $1$ (and we have already ensured that it should be $0$). If reduce(b,x) transforms $x$ to $0$, then $x$ is supported by the XOR base, otherwise it is not. And if we want to try adding $x$ to the base, we can simply reduce $x$, find the highest non-zero bit in the resulting integer $x'$, (let it be $i$), and assign $b_i$ to $x'$ (it is guaranteed that $b_i$ was zero, since otherwise we would have eliminated the $i$-th bit). So, that's how we can work with XOR bases and process every query to them in $O(B)$, where $B$ is the number of bits in each integer. Now let's go back to the original problem. Basically, for every query, we have to build a XOR base on some path in the tree. We can root the tree and then use LCA to split this path into two vertical paths, get XOR bases from those two paths, and merge them in $O(B^2)$. But how do we get an XOR base on a vertical path in something like $O(B^2)$? To do this, for each vertex $v$, let's consider the following process. We go from $v$ to the root, maintain the XOR base of the integers we met, and every time we add something to the XOR base, we mark the current vertex as \"interesting\" for $v$. Our goal is to build a list of \"interesting\" vertices for $v$ in order from $v$ to the root. Since the size of each XOR base is up to $20$, the size of each such list is also up to $20$, so we can get the XOR base for a vertical path by simply iterating on that interesting list for the lower endpoint of the path. Okay, the last part of the problem we have to solve is how to build these lists for all vertices in reasonable time. The key insight here is that if $p$ is the parent of $v$, then the list for $v$ will be very similar to the list for $p$: if $v$ is not supported by the XOR base of the list for $p$, then the list for $v$ is simply the list for $p$, with the vertex $v$ added; otherwise, $v$ eliminates one of the vertices from the list for $p$. We can find which one by building the XOR base for $v$ and the list of $p$; we need to add $a_v$ first, and then the values from all vertices in the list of $p$ in order \"from bottom to top\", and when an interesting vertex for $p$ adds nothing to the XOR base, it means that it is exactly the vertex we need to eliminate. Combining all of these, we can get a solution that works in $O(nB^2)$ for preprocessing and in $O(B^2 + \\log n)$ to answer each query.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 200043;\nconst int K = 20;\n \ntypedef array<int, K> base;\nint a[N];\nvector<int> g[N];\nvector<int> path_up[N];\nint tin[N], tout[N];\nint T = 0;\nint fup[N][K];\n \nbase make_empty()\n{\n    base b;\n    for(int i = 0; i < K; i++)\n        b[i] = 0;\n    return b;\n}\n \nint reduce(const base& b, int x)\n{\n    for(int i = K - 1; i >= 0; i--)\n        if(x & (1 << i))\n            x ^= b[i];\n    return x;\n}   \n \nbool add(base& b, int x)\n{\n    x = reduce(b, x);\n    if(x != 0)\n    {\n        for(int i = K - 1; i >= 0; i--)\n            if(x & (1 << i))\n            {\n                b[i] = x;\n                return true;\n            }\n    }   \n    return false;\n}\n \nbool check(const base& b, int x)\n{\n    return reduce(b, x) == 0;\n}\n \nvector<int> rebuild_path(const vector<int>& path, int v)\n{\n    base b = make_empty();\n    vector<int> ans;\n    if(add(b, a[v])) ans.push_back(v);\n    for(auto x : path) if(add(b, a[x])) ans.push_back(x);\n    return ans;\n}\n \nvoid dfs(int v, int u)\n{\n    tin[v] = T++;      \n    if(u == v)\n        path_up[v] = rebuild_path(vector<int>(0), v);\n    else\n        path_up[v] = rebuild_path(path_up[u], v);\n    fup[v][0] = u;\n    for(int i = 1; i < K; i++)\n        fup[v][i] = fup[fup[v][i - 1]][i - 1];\n    for(auto y : g[v])\n        if(y != u)\n            dfs(y, v);\n    tout[v] = T++;   \n}\n \nbool is_ancestor(int u, int v)\n{\n    return tin[u] <= tin[v] && tout[u] >= tout[v];\n}\n \nint LCA(int x, int y)\n{\n    if(is_ancestor(x, y)) return x;\n    for(int i = K - 1; i >= 0; i--)\n        if(!is_ancestor(fup[x][i], y))\n            x = fup[x][i];\n    return fup[x][0];\n}\n \nbool query(int x, int y, int k)\n{\n    base b = make_empty();\n    int z = LCA(x, y);\n    for(auto v : path_up[x])\n        if(!is_ancestor(v, y))\n            add(b, a[v]);\n    for(auto v : path_up[y])\n        if(!is_ancestor(v, x))\n            add(b, a[v]);\n    add(b, a[z]);\n    return check(b, k);            \n}\n \nint main()\n{\n    int n;\n\tscanf(\"%d\", &n);\n\tfor(int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\n\tfor(int i = 0; i < n - 1; i++)\n\t{\n\t\tint x, y;\n\t\tscanf(\"%d %d\", &x, &y);\n\t\t--x;\n\t\t--y;\n\t\tg[x].push_back(y);\n\t\tg[y].push_back(x);\n\t}\n\tdfs(0, 0);\n\tint q;\n\tscanf(\"%d\", &q);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tint x, y, k;\n\t\tscanf(\"%d %d %d\", &x, &y, &k);\n\t\t--x;\n\t\t--y;\n\t\tif(query(x, y, k)) puts(\"YES\");\n\t\telse puts(\"NO\");\n\t}\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "graphs",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1903",
    "index": "A",
    "title": "Halloumi Boxes",
    "statement": "Theofanis is busy after his last contest, as now, he has to deliver many halloumis all over the world. He stored them inside $n$ boxes and each of which has some number $a_i$ written on it.\n\nHe wants to sort them in non-decreasing order based on their number, however, his machine works in a strange way. It can only reverse any subarray$^{\\dagger}$ of boxes with length \\textbf{at most} $k$.\n\nFind if it's possible to sort the boxes using \\textbf{any number of reverses}.\n\n$^{\\dagger}$ Reversing a subarray means choosing two indices $i$ and $j$ (where $1 \\le i \\le j \\le n$) and changing the array $a_1, a_2, \\ldots, a_n$ to $a_1, a_2, \\ldots, a_{i-1}, \\; a_j, a_{j-1}, \\ldots, a_i, \\; a_{j+1}, \\ldots, a_{n-1}, a_n$. The length of the subarray is then $j - i + 1$.",
    "tutorial": "If the array is already sorted or $k > 1$ then there is always a way (reverse of size $2 =$ swap consecutive elements). Else it is not possible since when $k = 1$ the array remains the same.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n,k;\n        cin>>n>>k;\n        int arr[n];\n        for(int i = 0;i < n;i++){\n            cin>>arr[i];\n        }\n        if(is_sorted(arr,arr+n) || k > 1){\n            cout<<\"YES\\n\";\n        }\n        else{\n            cout<<\"NO\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1903",
    "index": "B",
    "title": "StORage room",
    "statement": "In Cyprus, the weather is pretty hot. Thus, Theofanis saw this as an opportunity to create an ice cream company.\n\nHe keeps the ice cream safe from other ice cream producers by locking it inside big storage rooms. However, he forgot the password. Luckily, the lock has a special feature for forgetful people!\n\nIt gives you a table $M$ with $n$ rows and $n$ columns of non-negative integers, and to open the lock, you need to find an array $a$ of $n$ elements such that:\n\n- $0 \\le a_i < 2^{30}$, and\n- $M_{i,j} = a_i | a_j$ for all $i \\neq j$, where $|$ denotes the bitwise OR operation.\n\nThe lock has a bug, and sometimes it gives tables without any solutions. In that case, the ice cream will remain frozen for the rest of eternity.\n\nCan you find an array to open the lock?",
    "tutorial": "Solution: Initially, we set all $a_i = 2^{30} - 1$ (all bits on). You can through every $i$,$j$ such that $i \\neq j$ and do $a_i \\&= M_{i,j}$ and $a_j \\&= M_{i,j}$. Then we check if $M_{i,j} = a_i | a_j$ for all pairs. If this holds you found the array else the answer is NO. Proof: Initially, all elements have all their bits set on and we remove only the bits that affect our answer. If $M_{i,j}$ doesn't have a specific bit then definitely neither $a_i$ nor $a_j$ should have it. If $M_{i,j}$ has a specific bit on then we don't have to remove anything (in the end we want at least one of $a_i$ and $a_j$ to have the bit on).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int m[n][n];\n        int arr[n];\n        for(int i = 0;i < n;i++){\n            arr[i] = (1<<30) - 1;\n        }\n        for(int i = 0;i < n;i++){\n            for(int j = 0;j < n;j++){\n                cin>>m[i][j];\n                if(i != j){\n                    arr[i] &= m[i][j];\n                    arr[j] &= m[i][j];\n                }\n            }\n        }\n        bool ok = true;\n        for(int i = 0;i < n;i++){\n            for(int j = 0;j < n;j++){\n                if(i != j && (arr[i] | arr[j]) != m[i][j]){\n                    ok = false;\n                }\n            }\n        }\n        if(!ok){\n            cout<<\"NO\\n\";\n        }\n        else{\n            cout<<\"YES\\n\";\n            for(int i = 0;i < n;i++){\n                cout<<arr[i]<<\" \";\n            }\n            cout<<\"\\n\";\n        }\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1903",
    "index": "C",
    "title": "Theofanis' Nightmare",
    "statement": "Theofanis easily gets obsessed with problems before going to sleep and often has nightmares about them. To deal with his obsession he visited his doctor, Dr. Emix.\n\nIn his latest nightmare, he has an array $a$ of size $n$ and wants to divide it into non-empty subarrays$^{\\dagger}$ such that every element is in exactly one of the subarrays.\n\nFor example, the array $[1,-3,7,-6,2,5]$ can be divided to $[1] [-3,7] [-6,2] [5]$.\n\nThe Cypriot value of such division is equal to $\\Sigma_{i=1}^{k} i \\cdot \\mathrm{sum}_i$ where $k$ is the number of subarrays that we divided the array into and $\\mathrm{sum}_i$ is the sum of the $i$-th subarray.\n\nThe Cypriot value of this division of the array $[1] [-3,7] [-6,2] [5] = 1 \\cdot 1 + 2 \\cdot (-3 + 7) + 3 \\cdot (-6 + 2) + 4 \\cdot 5 = 17$.\n\nTheofanis is wondering what is the \\textbf{maximum} Cypriot value of any division of the array.\n\n$^{\\dagger}$ An array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.",
    "tutorial": "Let $suf_i$ be the suffix sum of the array (from the $i^{th}$ position to the $n^{th}$). $ans =$ sum of $suf_{L_i}$ where $L_i$ is the leftmost element of the $i^{th}$ subarray. Definitely, $L_1 = 1$ and we can take any other we want (at most once). So we start with $ans = suf_1$ and for every $i > 1$ we add $suf_i$ if it is positive. We can easily see that this greedy works.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int arr[n];\n        long long suf[n+1] = {0};\n        for(int i = 0;i < n;i++){\n            cin>>arr[i];\n        }\n        for(int i = n-1;i >= 0;i--){\n            suf[i] = suf[i+1] + arr[i];\n        }\n        long long ans = suf[0];\n        for(int i = 1;i < n;i++){\n            if(suf[i] > 0){\n                ans += suf[i];\n            }\n        }\n        cout<<ans<<\"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1903",
    "index": "D1",
    "title": "Maximum And Queries (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$ and $q$, the memory and time limits. You can make hacks only if all versions of the problem are solved.}\n\nTheofanis really likes to play with the bits of numbers. He has an array $a$ of size $n$ and an integer $k$. He can make at most $k$ operations in the array. In each operation, he picks a single element and increases it by $1$.\n\nHe found the \\textbf{maximum} bitwise AND that array $a$ can have after at most $k$ operations.\n\nTheofanis has put a lot of work into finding this value and was very happy with his result. Unfortunately, Adaś, being the evil person that he is, decided to bully him by repeatedly changing the value of $k$.\n\nHelp Theofanis by calculating the \\textbf{maximum} possible bitwise AND for $q$ different values of $k$. Note that queries are independent.",
    "tutorial": "Construct the answer by iterating through every single bit from large to small ($2^{60}$ to $2^0$). Denote $x$ a the current answer and $b$ a the bit we want to add. For each $i$ ($1 \\le i \\le n$) if the $b$-th bit in $a_i$ is on we do not need to use any operations. If the $b$-th bit in $a_i$ is 0 then we need to increase $a_i$ by $2^b - a_i$ $mod$ $2^b$. If the total number of operations required to get from $x$ to $x+2^b$ is smaller than $k$, decrease $k$ by that number and change the array accordingly. Otherwise do nothing.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef long double ld;\n#define rep(a, b) for(int a = 0; a < (b); ++a)\n#define st first\n#define nd second\n#define pb push_back\n#define all(a) a.begin(), a.end()\nconst int LIM=1e5+7;\nll T[LIM], P[LIM], n, k;\nvoid solve() {\n  rep(i, n) T[i]=P[i];\n  ll ans=0;\n  for(ll i=60; i>=0; --i) {\n    ll sum=0;\n    rep(j, n) {\n      if(T[j]&(1ll<<i)) continue;\n      ll p=(T[j]/(1ll<<i))*(1ll<<i)+(1ll<<i);\n      p+=ans^(p&ans);\n      sum+=p-T[j];\n      if(sum > k){\n          break;\n      }\n    }\n    if(sum>k) continue;\n    rep(j, n) {\n      if(T[j]&(1ll<<i)) continue;\n      ll p=(T[j]/(1ll<<i))*(1ll<<i)+(1ll<<i);\n      p+=ans^(p&ans);\n      T[j]=p;\n    }\n    ans+=1ll<<i;\n    k-=sum;\n  }\n  cout << ans << '\\n';\n}\nint main() {\n  ios_base::sync_with_stdio(0); cin.tie(0);\n  int q;\n  cin >> n >> q;\n  rep(i, n) cin >> P[i];\n  while(q--) {\n    cin >> k;\n    solve();\n  }\n} ",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1903",
    "index": "D2",
    "title": "Maximum And Queries (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$ and $q$, the memory and time limits. You can make hacks only if all versions of the problem are solved.}\n\nTheofanis really likes to play with the bits of numbers. He has an array $a$ of size $n$ and an integer $k$. He can make at most $k$ operations in the array. In each operation, he picks a single element and increases it by $1$.\n\nHe found the \\textbf{maximum} bitwise AND that array $a$ can have after at most $k$ operations.\n\nTheofanis has put a lot of work into finding this value and was very happy with his result. Unfortunately, Adaś, being the evil person that he is, decided to bully him by repeatedly changing the value of $k$.\n\nHelp Theofanis by calculating the \\textbf{maximum} possible bitwise AND for $q$ different values of $k$. Note that queries are independent.",
    "tutorial": "Let $S = \\sum (2^{20} - a_i)$. If $k \\ge S$ then the answer is $2^{20} + \\lfloor \\frac{k-S}{n} \\rfloor$. Similarly to D1 let's construct the answer bit by bit. Let $x$ be the current answer and $b$ be the bit we want to add. Let's look at the amount of operations we need to do on the $i$-th element to change our answer from $x$ to $x+2^b$. if $x$ is not a submask of $a_i$, then after constructing answer $x$ it has $0$s on all bits not greater than $b$. In this case we need to increase the $i$-th element by $2^b$. if $x+2^b$ is a submask of $a_i$, then we do not need to increase the $i$-th element. otherwise we need to increase the $i$-th element by $2^b - a_i$ $mod$ $2^b$. We can handle all three cases efficiently if we precompute the following two arrays: $A(mask)$ - how many elements from the array is $mask$ a submask of. $B(mask, b)$ - sum of $a_i$ $mod$ $2^b$ over all $a_i$ for which $x$ is a submask. Both arrays can be calculated efficiently using SOS dp. This allows us to answer the queries in $O$($q \\times log$ $a$) with $O$($a$ $log^2$ $a$) preprocessing",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long double ld;\ntypedef long long ll;\n#define rep(a, b) for(ll a = 0; a < (b); ++a)\n#define st first\n#define nd second\n#define pb push_back\n#define all(a) a.begin(), a.end()\nconst int LIM=1e6+7;\nll dpsum[1<<20][20], dpcnt[1<<20], T[LIM];\nint main() {\n  ios_base::sync_with_stdio(0); cin.tie(0);\n  ll n, q;\n  cin >> n >> q;\n  ll sto=0, sfrom=0;\n  rep(i, n) {\n    cin >> T[i];\n    sto+=(1ll<<20ll)-T[i];\n    sfrom+=T[i];\n    ++dpcnt[T[i]];\n    ll sum=0;\n    rep(j, 20) {\n      sum+=T[i]&(1ll<<j);\n      dpsum[T[i]][j]+=sum;\n    }\n  }\n  rep(i, 20) rep(j, 1<<20) if(!(j&(1<<i))) dpcnt[j]+=dpcnt[j+(1<<i)];\n  rep(i, 20) rep(j, 1<<20) if(!(j&(1<<i))) rep(l, 20) dpsum[j][l]+=dpsum[j+(1<<i)][l];\n  while(q--) {\n    ll k;\n    cin >> k;\n    if(k>=sto) {\n      k+=sfrom;\n      cout << k/n << '\\n';\n      continue;\n    }\n    ll ans=0;\n    for(ll i=19; i>=0; --i) {\n      ll x=(n-dpcnt[ans|(1<<i)])*(1ll<<i);\n      x-=dpsum[ans][i]-dpsum[ans|(1<<i)][i];\n      if(x<=k) {\n        k-=x;\n        ans|=1<<i;\n      }\n    }\n    cout << ans << '\\n';\n  }\n}\n \n",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "dp",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1903",
    "index": "E",
    "title": "Geo Game",
    "statement": "This is an interactive problem.\n\nTheofanis and his sister are playing the following game.\n\nThey have $n$ points in a 2D plane and a starting point $(s_x,s_y)$. Each player (starting from the first player) chooses one of the $n$ points that wasn't chosen before and adds to the sum (which is initially $0$) the \\textbf{square} of the Euclidean distance from the previous point (which is either the starting point or it was chosen by the other person) to the new point (that the current player selected).\n\nThe game ends after exactly $n$ moves (after all the points are chosen). The first player wins if the sum is even in the end. Otherwise, the second player wins.\n\nTheofanis is a very competitive person and he hates losing. Thus, he wants to choose whether he should play first or second. Can you show him, which player to choose, and how he should play to beat his sister?",
    "tutorial": "If we went from point $(a,b)$ to $(c,d)$ then we will add to the sum $a^2 + c^2 - 2ac + b^2 + d^2 - 2bd$ which is equal to $a \\oplus b \\oplus c \\oplus d$ mod $2$ ($\\oplus$ is bitwise xor). For each point, we find ($x$ mod $2$) $\\oplus$ ($y$ mod $2$). Let $p_0 =$ the number of ($x$ mod $2$) $\\oplus$ ($y$ mod $2$) $== 0$, $p_1 =$ the number of ($x$ mod $2$) $\\oplus$ ($y$ mod $2$) $== 1$ and $v =$ ($s_x$ mod $2$) $\\oplus$ ($s_y$ mod $2$). Let's say that we create a binary string starting with $v$ and has another $p_0$ zeros and $p_1$ ones. If the number of $s_i \\neq s_{i+1}$ is odd then the sum will be odd otherwise the sum will be even. If you are the first player then you want to have an even number of $s_i \\neq s_{i+1}$. That holds iff the first element of $s$ is the same as the last element of $s$. Thus, the second player will want to put all $p_v$ occurrences of $v$ before the end (so that the last element is not equal to the first). He can do this iff $p_v < (n - 1) / 2$ (rounded down) (this means that $p_v < p_{v \\oplus 1}$). If $p_{v \\oplus 1} \\le p_v$ you play as the first player and you choose occurrences of $v \\oplus 1$ until there aren't any and else ($p_v < p_{v \\oplus 1}$) you play as the second player and you choose occurrences of $v$ until there aren't any.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int sx,sy;\n        cin>>sx>>sy;\n        int x[n],y[n];\n        set<int>p[2];\n        for(int i = 0;i < n;i++){\n            cin>>x[i]>>y[i];\n            p[(x[i] % 2) ^ (y[i] % 2)].insert(i+1);\n        }\n        int v = (sx % 2) ^ (sy % 2);\n        if(p[v].size() >= p[v^1].size()){\n            cout<<\"First\"<<endl;\n            v ^= 1;\n            for(int i = 0;i < n;i++){\n                if(i % 2 == 0){\n                    int j;\n                    if(!p[v].empty()){\n                        j = (*p[v].begin());\n                        p[v].erase(j);\n                    }\n                    else{\n                        j = (*p[v^1].begin());\n                        p[v^1].erase(j);\n                    }\n                    cout<<j<<endl;\n                }\n                else{\n                    int j;\n                    cin>>j;\n                    if(p[0].count(j)){\n                        p[0].erase(j);\n                    }\n                    else{\n                        p[1].erase(j);\n                    }\n                }\n            }\n        }\n        else{\n            cout<<\"Second\"<<endl;\n            for(int i = 0;i < n;i++){\n                if(i % 2 == 1){\n                    int j;\n                    if(!p[v].empty()){\n                        j = (*p[v].begin());\n                        p[v].erase(j);\n                    }\n                    else{\n                        j = (*p[v^1].begin());\n                        p[v^1].erase(j);\n                    }\n                    cout<<j<<endl;\n                }\n                else{\n                    int j;\n                    cin>>j;\n                    if(p[0].count(j)){\n                        p[0].erase(j);\n                    }\n                    else{\n                        p[1].erase(j);\n                    }\n                }\n            }\n        }\n    }\n}",
    "tags": [
      "greedy",
      "interactive",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1903",
    "index": "F",
    "title": "Babysitting",
    "statement": "Theofanis wants to play video games, however he should also take care of his sister. Since Theofanis is a CS major, he found a way to do both. He will install some cameras in his house in order to make sure his sister is okay.\n\nHis house is an undirected graph with $n$ nodes and $m$ edges. His sister likes to play at the edges of the graph, so he has to install a camera to at least one endpoint of every edge of the graph. Theofanis wants to find a vertex cover that maximizes the minimum difference between indices of the chosen nodes.\n\nMore formally, let $a_1, a_2, \\ldots, a_k$ be a vertex cover of the graph. Let the minimum difference between indices of the chosen nodes be the minimum $\\lvert a_i - a_j \\rvert$ (where $i \\neq j$) out of the nodes that you chose. \\textbf{If $k = 1$ then we assume that the minimum difference between indices of the chosen nodes is $n$}.\n\nCan you find the maximum possible minimum difference between indices of the chosen nodes over all vertex covers?",
    "tutorial": "We can solve this problem using 2-sat and binary search the answer. In order to have a vertex cover we should have $(u_i | v_i)$. And if we want to check if the answer is greater or equal to $mid$ we want to have $(!x | !y)$ for all pairs $1\\le x, y \\le n$ such that $|x - y| < mid$. However, this way we will have too many edges. To fix this problem we can create some helping nodes and edges in a similar structure of a segment tree. In 2-sat when we connect two nodes there are two possibilities for each (taken or not taken). If we have an edge from $a$ to $b$ it means that when $a$ holds then definitely also $b$ holds. So, we build a binary tree in a similar structure to a segment tree so that each node is connected to two children creating a binary-directed tree and each node corresponds to a range. When we want to have edges from $x$ to $[x+1,x+mid)$ and $(x-mid,x-1]$ we just choose the nodes in this binary tree that are needed to make the range (they are at most $\\log(n)$). So that makes the total time complexity to: $O(M \\log^2(n))$ There is also an $O(M \\log(n))$ solution. Shootout to jeroenodb for pointing it out. The idea is similar. We use 2-sat and binary search the answer, however, this time we do 2-sat differently. In our graph, we will have the $m$ edges to have a vertex cover. So we should have $(u_i | v_i)$. We add those edges and then we should also have the edges corresponding to $(!x | !y)$ for all pairs $1\\le x, y \\le n$ such that $|x - y| < mid$. But we don't need all of them. We can just only go to first to the left and first to the right by storing the set of unvisited nodes and doing lower bound with dsu.",
    "code": "#pragma GCC optimize(\"O3\")\n#include \"bits/stdc++.h\"\nusing namespace std;\n#define all(x) begin(x),end(x)\ntemplate<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << \", \" << p.second << ')'; }\ntemplate<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = \" \"; return os; }\n#define debug(a) cerr << \"(\" << #a << \": \" << a << \")\\n\";\ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<basic_string<int>> vvi;\ntypedef pair<int,int> pi;\nconst int mxN = 1e5+1, oo = 1e9;\ntemplate<int (*merge)(int,int), int (*init)(int)> struct DSU{\n    vi sz, dat;\n    DSU(int n) : sz(n,-1),dat(n) {\n        for(int i=0;i<n;++i) dat[i] = init(i);\n    }\n    void link(int a, int b) {\n        if(sz[a]>sz[b]) {\n            swap(a,b);\n        }\n        sz[a]+=sz[b];\n        sz[b]=a;\n        dat[a] = merge(dat[a],dat[b]);\n    }\n    bool unite(int a, int b) {\n        int pa = find(a),pb = find(b);\n        if(pa!=pb) link(pa,pb);\n        return pa!=pb;\n    }\n    int get(int i) {\n        return dat[find(i)];\n    }\n    int find(int a) {\n        if(sz[a]<0) return a;\n        return sz[a] = find(sz[a]);\n    }\n};\nint dec(int i) {return i-1;}\nint inc(int i) {return i+1;}\nint mymin(int a, int b) {return min(a,b);}\nint mymax(int a, int b) {return max(a,b);}\nbool solve(const vvi& adj, const vvi& rev, int mid) {\n    int n = rev.size()/2;\n\n    DSU<mymin, dec> dsuL(n);\n    DSU<mymax, inc> dsuR(n);\n    auto getL = [&](int i) {\n        if(i>=n) i-=n;\n        int l = dsuL.get(i);\n        if(l==-1 or abs(i-l)>=mid) return 0;\n        return l+1;\n    };\n    auto getR = [&](int i) {\n        if(i>=n) i-=n;\n        int r = dsuR.get(i);\n        if(r==n or abs(i-r)>=mid) return 0;\n        return r+1;\n    };\n    auto rem = [&](int at) {\n        if(at>=n) at-=n;\n        if(at) dsuR.unite(at-1,at);\n        if(at+1<n) dsuL.unite(at,at+1);\n    };\n    vector<bool> vis(n*2);\n    vi ord;\n    auto dfs = [&](auto&& self, int at) -> void {\n        vis[at]=1;\n        if(at<n) {\n            while(int l = getL(at)) self(self,l-1+n);\n            while(int r = getR(at)) self(self,r-1+n);\n        } else rem(at);\n        for(int to : adj[at]) if(!vis[to]) self(self,to);\n        ord.push_back(at);\n\n    };\n    for(int i=0;i<2*n;++i) if(!vis[i]) dfs(dfs,i);\n    reverse(all(ord));\n\n    fill(all(vis),0);\n    dsuL = DSU<mymin,dec>(n);\n    dsuR = DSU<mymax,inc>(n);\n    int comp=0;\n    vi comps(2*n);\n    auto dfs2 = [&](auto&& self, int at) -> void {\n        comps[at]=comp;\n        vis[at]=1;\n        if(at>=n) {\n            while(int l = getL(at)) self(self,l-1);\n            while(int r = getR(at)) self(self,r-1);\n        } else rem(at);\n        for(int to : rev[at]) if(!vis[to]) self(self,to);\n\n    };\n\n    for(int i : ord) if(!vis[i]) {\n        dfs2(dfs2,i);\n        comp++;\n    }\n    for(int i=0;i<n;++i) if(comps[i]==comps[i+n]) return false;\n    return true;\n\n\n}\nvoid solve() {\n    int n,m; cin >> n >> m;\n    vvi adj(2*n),rev(2*n);\n    auto addE = [&](int u, int v) {\n        adj[u].push_back(v);\n        rev[v].push_back(u);\n    };\n    for(int i=0;i<m;++i) {\n        int u,v; cin >> u >> v;\n        --u,--v;\n        addE(u+n,v);\n        addE(v+n,u);\n    }\n\n    int lo=1,hi=n;\n    while(lo<hi) {\n        int mid = (lo+hi+1)/2;\n        if(solve(adj,rev,mid)) {\n            lo= mid;\n        } else hi = mid-1;\n    }\n    cout << lo << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t; cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "2-sat",
      "binary search",
      "data structures",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1904",
    "index": "A",
    "title": "Forked!",
    "statement": "Lunchbox is done with playing chess! His queen and king just got forked again!\n\nIn chess, a fork is when a knight attacks two pieces of higher value, commonly the king and the queen. Lunchbox knows that knights can be tricky, and in the version of chess that he is playing, knights are even trickier: instead of moving $1$ tile in one direction and $2$ tiles in the other, knights in Lunchbox's modified game move $a$ tiles in one direction and $b$ tiles in the other.\n\nLunchbox is playing chess on an infinite chessboard which contains all cells $(x,y)$ where $x$ and $y$ are (possibly negative) integers. Lunchbox's king and queen are placed on cells $(x_K,y_K)$ and $(x_Q,y_Q)$ respectively. Find the number of positions such that if a knight was placed on that cell, it would attack both the king and queen.",
    "tutorial": "There are at most $8$ positions of the knight that can attack a single cell. Therefore, we can find all $8$ positions that attack the king and the $8$ positions that attack the queen and count the number of positions that appear in both of these lists. 1904B - Collecting Game",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint dx[4] = {-1, 1, -1, 1}, dy[4] = {-1, -1, 1, 1};\n \nint main(){\n    int t; cin >> t;\n    for(int i = 0; i < t; i++){\n        int a, b; cin >> a >> b;\n        int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2;\n        set<pair<int, int>> st1, st2;\n        for(int j = 0; j < 4; j++){\n            st1.insert({x1+dx[j]*a, y1+dy[j]*b});\n            st2.insert({x2+dx[j]*a, y2+dy[j]*b});\n            st1.insert({x1+dx[j]*b, y1+dy[j]*a});\n            st2.insert({x2+dx[j]*b, y2+dy[j]*a});\n        }\n        int ans = 0;\n        for(auto x : st1)\n            if(st2.find(x) != st2.end())\n                ans++;\n        cout << ans << '\\n';\n    }\n} ",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1904",
    "index": "B",
    "title": "Collecting Game",
    "statement": "You are given an array $a$ of $n$ positive integers and a score. If your score is greater than or equal to $a_i$, then you can increase your score by $a_i$ and remove $a_i$ from the array.\n\nFor each index $i$, output the maximum number of additional array elements that you can remove if you remove $a_i$ and then set your score to $a_i$. Note that the removal of $a_i$ should not be counted in the answer.",
    "tutorial": "Let's sort array $a$. The answer for the largest element is $n-1$ because the score, which is $a_n$, cannot be smaller than any of the other elements. Now, consider the second largest element. The answer is at least $n-2$ because every element that is not greater than $a_{n-1}$ can be taken. Then, we check if the score is at least $a_n$. This inspires the following solution: first, we find the prefix sum $p$ of array $a$. We calculate the answer in decreasing order of $a_i$. To calculate the answer for an $a_i$, we find the largest $j$ such that $p_i\\geq a_j$ and set the answer for $i$ equal to the answer of $j$. 1904C - Array Game",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n\n#define pb push_back\n#define ff first\n#define ss second\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pld;\n\nconst int INF = 1e9;\nconst ll LLINF = 1e18;\nconst int MOD = 1e9 + 7;\n\ntemplate<class K> using sset =  tree<K, null_type, less<K>, rb_tree_tag, tree_order_statistics_node_update>;\n\ninline ll ceil0(ll a, ll b) {\n    return a / b + ((a ^ b) > 0 && a % b);\n}\n\nvoid setIO() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n}\n\nint main(){\n    setIO();\n    int T;\n    cin >> T;\n    for(int tt = 1; tt <= T; tt++){\n        int n;\n        cin >> n;\n        pii arr[n + 1];\n        for(int i = 1; i <= n; i++) cin >> arr[i].ff, arr[i].ss = i;\n        sort(arr + 1, arr + n + 1);\n        int nxt[n + 1];\n        ll sum[n + 1];\n        int ans[n + 1];\n        nxt[0] = sum[0] = 0;\n        for(int i = 1; i <= n; i++){\n            if(nxt[i - 1] >= i){\n                nxt[i] = nxt[i - 1];\n                sum[i] = sum[i - 1];\n            } else {\n                sum[i] = sum[i - 1] + arr[i].ff;\n                nxt[i] = i;\n                while(nxt[i] + 1 <= n && sum[i] >= arr[nxt[i] + 1].ff){\n                    nxt[i]++;\n                    sum[i] += arr[nxt[i]].ff;\n                }\n            }\n            ans[arr[i].ss] = nxt[i];\n        }\n        for(int i = 1; i <= n; i++) cout << ans[i] - 1 << \" \";\n        cout << endl;\n    }\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1904",
    "index": "C",
    "title": "Array Game",
    "statement": "You are given an array $a$ of $n$ positive integers. In one operation, you must pick some $(i, j)$ such that $1\\leq i < j\\leq |a|$ and append $|a_i - a_j|$ to the end of the $a$ (i.e. increase $n$ by $1$ and set $a_n$ to $|a_i - a_j|$). Your task is to minimize and print the minimum value of $a$ after performing $k$ operations.",
    "tutorial": "If $k\\geq 3$, the answer is equal to $0$ since after performing an operation on the same pair $(i, j)$ twice, performing an operation on the two new values (which are the same) results in $0$. Therefore, let's consider the case for $1\\leq k\\leq 2$. For $k=1$, it is sufficient to sort the array and output the minimum between $a_i$ and $a_{i+1} - a_i$. For $k=2$, let's brute force the first operation. If the newly created value is $v$, then it is sufficient to find the smallest $a_i$ satisfying $a_i\\geq v$ and greatest $a_i$ satisfying $a_i\\leq v$ and relax the answer on $|a_i - v|$. Also, remember to consider the cases of performing no operation or one operation. This runs in $O(N^2\\log N)$. There also exists a solution in $O(N^2)$ using a two pointers approach. 1904D1 - Set To Max (Easy Version) / 1904D2 - Set To Max (Hard Version)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n \nsigned main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, k;\n        cin >> n >> k;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) cin >> a[i];\n        if (k >= 3) {\n            cout << 0 << endl;\n            continue;\n        }\n        sort(begin(a), end(a));\n        int d = a[0];\n        for (int i = 0; i < n - 1; i++) d = min(d, a[i + 1] - a[i]);\n        if (k == 1) {\n            cout << d << endl;\n            continue;\n        }\n        for (int i = 0; i < n; i++) for (int j = 0; j < i; j++) {\n            int v = a[i] - a[j];\n            int p = lower_bound(begin(a), end(a), v) - begin(a);\n            if (p < n) d = min(d, a[p] - v);\n            if (p > 0) d = min(d, v - a[p - 1]);\n        }\n        cout << d << endl;\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1904",
    "index": "D2",
    "title": "Set To Max (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only differences between the two versions of this problem are the constraints on $n$ and the time limit. You can make hacks only if all versions of the problem are solved.}\n\nYou are given two arrays $a$ and $b$ of length $n$.\n\nYou can perform the following operation some (possibly zero) times:\n\n- choose $l$ and $r$ such that $1 \\leq l \\leq r \\leq n$.\n- let $x=\\max(a_l,a_{l+1},\\ldots,a_r)$.\n- for all $l \\leq i \\leq r$, set $a_i := x$.\n\nDetermine if you can make array $a$ equal to array $b$.",
    "tutorial": "Can we reduce the number of intervals we want to apply an operation on? What is the necessary condition to perform an operation on an interval If $b_i < a_i$ for any $i$, then it is clearly impossible. In order for $a_i$ to become $b_i$, $i$ must be contained by an interval that also contains a $j$ where $a_j = b_i$. Note that if there is a triple $i \\le j < k$ where $a_j = a_k = b_i$, then it is never optimal to apply the operation on interval $[i, k]$, since applying the operation on interval $[i, j]$ will be sufficient. Thus, for $i$ we only need to consider the closest $a_j = b_i$ to the right or left of $i$. Lets find the necessary conditions for us to apply an operation on the interval $[i, j]$. First of all, $a_k \\le b_i$ for $i \\le k \\le j$. Second, $b_k \\ge b_i$ for all $i \\le k \\le j$. Turns out, these conditions are also sufficient, since we can apply these operations in increasing order of $b_i$ without them interfering with each other. If we check for every $i$ there exists an interval $[i, j]$ or $[j, i]$ that satisfies the necessary conditions, then there will exist a sequence of operations to transform $a$ into $b$. Checking for the conditions can be done with brute force for D1 or using monotonic stacks or segment trees for D2. 1904E - Tree Queries",
    "code": "#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n\n#define pb push_back\n#define ff first\n#define ss second\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pld;\n\nconst int INF = 1e9;\nconst ll LLINF = 1e18;\nconst int MOD = 1e9 + 7;\n\ntemplate<class K> using sset =  tree<K, null_type, less<K>, rb_tree_tag, tree_order_statistics_node_update>;\n\ninline ll ceil0(ll a, ll b) {\n    return a / b + ((a ^ b) > 0 && a % b);\n}\n\nvoid setIO() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n}\n\nint main(){\n    setIO();\n    int T;\n    cin >> T;\n    for(int tt = 1; tt <= T; tt++){\n        int n;\n        cin >> n;\n        int a[n + 1], b[n + 1];\n        for(int i = 1; i <= n; i++) cin >> a[i];\n        for(int i = 1; i <= n; i++) cin >> b[i];\n        bool val[n + 1];\n        memset(val, false, sizeof(val));\n        for(int t = 0; t < 2; t++){\n            int prvb[n + 1]; //prev smaller\n            int nxta[n + 1]; //next greater\n            stack<pii> s;\n            s.push({INF, n + 1});\n            for(int i = n; i >= 1; i--){\n                while(s.top().ff <= a[i]) s.pop();\n                nxta[i] = s.top().ss;\n                s.push({a[i], i});\n            }\n            while(!s.empty()) s.pop();\n            s.push({0, 0});\n            for(int i = 1; i <= n; i++){\n                while(s.top().ff >= b[i]) s.pop();\n                prvb[i] = s.top().ss;\n                s.push({b[i], i});\n            }\n            int m[n + 1];\n            memset(m, 0, sizeof(m));\n            for(int i = 1; i <= n; i++){\n                m[a[i]] = i;\n                if(a[i] <= b[i] && m[b[i]]) val[i] |= prvb[i] < m[b[i]] && nxta[m[b[i]]] > i;\n            }\n            reverse(a + 1, a + n + 1);\n            reverse(b + 1, b + n + 1);\n            reverse(val + 1, val + n + 1);\n        }\n        bool ans = true;\n        for(int i = 1; i <= n; i++) ans &= val[i];\n        cout << (ans ? \"YES\" : \"NO\") << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1904",
    "index": "E",
    "title": "Tree Queries",
    "statement": "\\begin{quote}\nThose who don't work don't eat. Get the things you want with your own power. But believe, the earnest and serious people are the ones who have the last laugh... But even then, I won't give you a present.\n\\hfill —Santa, Hayate no Gotoku!\n\\end{quote}\n\nSince Hayate didn't get any Christmas presents from Santa, he is instead left solving a tree query problem.\n\nHayate has a tree with $n$ nodes.\n\nHayate now wants you to answer $q$ queries. Each query consists of a node $x$ and $k$ other additional nodes $a_1,a_2,\\ldots,a_k$. These $k+1$ nodes are guaranteed to be all distinct.\n\nFor each query, you must find the length of the longest simple path starting at node $x^\\dagger$ after removing nodes $a_1,a_2,\\ldots,a_k$ along with all edges connected to at least one of nodes $a_1,a_2,\\ldots,a_k$.\n\n$^\\dagger$ A simple path of length $k$ starting at node $x$ is a sequence of \\textbf{distinct} nodes $x=u_0,u_1,\\ldots,u_k$ such that there exists a edge between nodes $u_{i-1}$ and $u_i$ for all $1 \\leq i \\leq k$.",
    "tutorial": "The solution doesn't involve virtual tree What is an easy way to represent the tree? Consider the Euler tour of the tree where $in[u]$ is the entry time of each node and $out[u]$ is the exit time. The interval $[in[u], out[u]]$ corresponds to the subtree of $u$. Removing a node is equivalent to blocking some intervals on the Euler tour. There are two cases when $a$ is blocked with respect to query node $x$. If $a$ is an ancestor of $x$, then the set of reachable nodes is reduced to the interval $[in[nxt_a], out[nxt_a]]$, where $nxt_a$ is the first node on the path from $a$ to $x$. This is equivalent to blocking the intervals $[0, in[nxt_a])$ and $(out[nxt_a], n - 1]$. If $a$ is not an ancestor, then the interval $[in[a], out[a]]$ is blocked. Lets build a lazy segment tree on the Euler tour of the tree. Each leaf node will correspond to the depth of a node on the tree. We can re-root the tree from $a$ to $b$ by subtracting one from all nodes the range $[in[b], out[b]]$ and adding one to all other nodes. Thus, we can traverse the tree while re-rooting and process our queries offline. When the query node $x$ is the root, block all the necessary intervals and then find the maximum value in the segment tree. In a tree, one of the farthest nodes from some node $x$ is one of the two endpoints of the diameter. Let's try to find the diameter of the connected subgraph node $x$ is in after the nodes $a_{1 \\dots n}$ are removed. Consider an euler tour of the tree and order the nodes by their inorder traversal. When $k$ nodes are removed, the remaining nodes form $O(k)$ contiguous intervals in the tour. Let's build a segtree/sparse table where each node stores the diameter (as a pair of nodes) for the nodes with $in$ values in the range $[l, r]$. To merge two diameters, we can enumerate all $4 \\choose 2$ ways to pick the new diameter and take the best one. To answer a query, we can first generate a list of banned intervals (just like solution 1) and use that list to generate the list of unbanned intervals. Then we can query our segtree for the diameter of each of ranges. Finally, we can combine the answers of the seperate queries to obtain the diameter of the connected subgraph. We know the farthest node from node $x$ is one of the two endpoints, so it suffices to just manually check the distance of those two nodes. Final complexity is $O(n \\log^2 n + \\sum k \\log n)$. 1904F - Beautiful Tree",
    "code": "#include <bits/stdc++.h>\n\n#define sz(x) ((int)(x.size()))\n#define all(x) x.begin(), x.end()\n#define pb push_back\n#define eb emplace_back\n\nconst int MX = 2e5 +10, int_max = 0x3f3f3f3f;\n\nusing namespace std;\n\n//lca template start\nvector<int> dep, sz, par, head, tin, tout, tour;\nvector<vector<int>> adj;\nint n, ind, q;\nvoid dfs(int x, int p){\n\tsz[x] = 1;\n\tdep[x] = dep[p] + 1;\n\tpar[x] = p;\n\tfor(auto &i : adj[x]){\n\t\tif(i == p) continue;\n\t\tdfs(i, x);\n\t\tsz[x] += sz[i];\n\t\tif(adj[x][0] == p || sz[i] > sz[adj[x][0]]) swap(adj[x][0], i);\n\t}\n\tif(p != 0) adj[x].erase(find(all(adj[x]), p));\n}\nvoid dfs2(int x, int p){\n\ttour[ind] = x;\n\ttin[x] = ind++;\n\tfor(auto &i : adj[x]){\n\t\tif(i == p) continue;\n\t\thead[i] = (i == adj[x][0] ? head[x] : i);\n\t\tdfs2(i, x);\n\t}\n\ttout[x] = ind;\n}\n\nint k_up(int u, int k){\n\tif(dep[u] <= k) return -1;\n\twhile(k > dep[u] - dep[head[u]]){\n\t\tk -= dep[u] - dep[head[u]] + 1;\n\t\tu = par[head[u]];\n\t}\n\treturn tour[tin[u] - k];\n}\n\nint lca(int a, int b){\n\twhile(head[a] != head[b]){\n\t\tif(dep[head[a]] > dep[head[b]]) swap(a, b);\n\t\tb = par[head[b]];\n\t}\n\tif(dep[a] > dep[b]) swap(a, b);\n\treturn a;\n}\n\nint dist(int a, int b){\n\treturn dep[a] + dep[b] - 2*dep[lca(a, b)];\n}\n//lca template end\n//segtree template start\n#define ff first\n#define ss second\nint dist(pair<int, int> a){\n\treturn dist(a.ff, a.ss);\n}\npair<int, int> merge(pair<int, int> a, pair<int, int> b){\n\tauto p = max(pair(dist(a), a), pair(dist(b), b));\n\tfor(auto x : {a.ff, a.ss}){\n\t\tfor(auto y : {b.ff, b.ss}){\n\t\t\tif(x == 0 || y == 0) continue;\n\t\t\tp = max(p, pair(dist(pair(x, y)), pair(x, y)));\n\t\t}\n\t}\n\treturn p.ss;\n}\n\npair<int, int> mx[MX*4];\n#define LC(k) (2*k)\n#define RC(k) (2*k +1)\nvoid update(int p, int v, int k, int L, int R){\n\tif(L + 1 == R){\n\t\tmx[k] = {tour[p], tour[p]};\n\t\treturn ;\n\t}\n\tint mid = (L + R)/2;\n\tif(p < mid) update(p, v, LC(k), L, mid);\n\telse update(p, v, RC(k), mid, R);\n\tmx[k] = merge(mx[LC(k)], mx[RC(k)]);\n}\n\nvoid query(int qL, int qR, vector<pair<int, int>>& ret, int k, int L, int R){\n\tif(qR <= L || R <= qL) return ;\n\tif(qL <= L && R <= qR){\n\t\tret.push_back(mx[k]);\n\t\treturn ;\n\t}\n\tint mid = (L + R)/2;\n\tquery(qL, qR, ret, LC(k), L, mid);\n\tquery(qL, qR, ret, RC(k), mid, R);\n}\n\n//segtree template end\n\nint query(vector<int> arr, int x){\n\tvector<pair<int, int>> banned, ret;\n\tfor(int u : arr){\n\t\tif(lca(u, x) == u){\n\t\t\tu = k_up(x, dep[x] - dep[u] - 1);\n\t\t\tbanned.push_back({0, tin[u]});\n\t\t\tbanned.push_back({tout[u], n});\n\t\t}else{\n\t\t\tbanned.push_back({tin[u], tout[u]});\n\t\t}\n\t}\n\tsort(all(banned), [&](pair<int, int> a, pair<int, int> b){\n\t\treturn (a.ff < b.ff) || (a.ff == b.ff && a.ss > b.ss);\n\t\t\t});\n\tvector<pair<int, int>> tbanned; //remove nested intervals\n\tint mx = 0;\n\tfor(auto [a, b] : banned){\n\t\tif(b <= mx) continue;\n\t\telse if(a != b){\n\t\t\ttbanned.pb({a, b});\n\t\t\tmx = b;\n\t\t}\n\t}\n\n\tbanned = tbanned;\n\tint tim = 0;\n\tfor(auto [a, b] : banned){\n\t\tif(tim < a) \n\t\t\tquery(tim, a, ret, 1, 0, n);\n\t\ttim = b;\n\t}\n\n\tif(tim < n) \n\t\tquery(tim, n, ret, 1, 0, n);\n\tpair<int, int> dia = pair(x, x);\n\tfor(auto p : ret) dia = merge(dia, p);\n\tint ans = max(dist(x, dia.ff), dist(x, dia.ss));\n\treturn ans;\n}\n\nvoid solve(){\n\tcin >> n >> q;\n\tdep = sz = par = head = tin = tout = tour = vector<int>(n+1, 0);\n\tadj = vector<vector<int>>(n+1);\n\tfor(int i = 1; i<n; i++){\n\t\tint a, b;\n\t\tcin >> a >> b;\n\t\tadj[a].push_back(b);\n\t\tadj[b].push_back(a);\n\t}\n\t\n\tdfs(1, 0);\n\thead[1] = 1;\n\tdfs2(1, 0);\n\tfor(int i = 1; i<=n; i++){\n\t\tupdate(tin[i], dep[i], 1, 0, n);\n\t}\n\tfor(int i = 1; i<=q; i++){\n\t\tint x, k;\n\t\tcin >> x >> k;\n\t\tvector<int> arr(k);\n\t\tfor(int& y : arr) cin >> y;\t\t\n\t\tcout << query(arr, x) << \"\\n\";\n\t}\n}\n\nsigned main(){\n  cin.tie(0) -> sync_with_stdio(0);\n\n  int T = 1;\n  //cin >> T;\n  for(int i = 1; i<=T; i++){\n\t\t//cout << \"Case #\" << i << \": \";\n\t\tsolve();\n\t}\n  return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1904",
    "index": "F",
    "title": "Beautiful Tree",
    "statement": "Lunchbox has a tree of size $n$ rooted at node $1$. Each node is then assigned a value. Lunchbox considers the tree to be beautiful if each value is distinct and ranges from $1$ to $n$. In addition, a beautiful tree must also satisfy $m$ requirements of $2$ types:\n\n- \"1 a b c\" — The node with the smallest value on the path between nodes $a$ and $b$ must be located at $c$.\n- \"2 a b c\" — The node with the largest value on the path between nodes $a$ and $b$ must be located at $c$.\n\nNow, you must assign values to each node such that the resulting tree is beautiful. If it is impossible to do so, output $-1$.",
    "tutorial": "Can we represent the conditions as a graph? Lets rewrite the condition that node $a$ must be smaller than node $b$ as a directed edge from $a$ to $b$. Then, we can assign each node a value based on the topological sort of this new directed graph. If this directed graph had a cycle, it is clear that there is no way to order the nodes. With this in mind, we can try to construct a graph that would have these properties. Once we have the graph, we can topological sort to find the answer. For now, let's consider the problem if it only had type 1 requirements (type 2 requirements can be done very similarly). Thus, the problem reduces to \"given a path and a node, add a directed edge from the node to every node in that path.\" To do this, we can use binary lifting. For each node, create $k$ dummy nodes, the $i$th of which represents the minimum number from the path between node $a$ and the $2^i$th parent of $a$. Now, we can draw a directed edge from the the $i$th dummy node of $a$ to the $i-1$th dummy node of $a$ and the $i-1$th dummy node of the $2^{i-1}$th parent of $a$. Now, to add an edge from any node to a vertical path of the tree, we can repeatedly add an edge from that node to the largest node we can. This will add $O(\\log n)$ edges per requirement. The final complexity is $O((n+m)\\log n)$ time and $O((n+m)\\log n)$.",
    "code": "#pragma GCC optimize(\"O3,unroll-loops\")\n#pragma GCC target(\"avx,avx2,fma\")\n#pragma GCC target(\"sse4,popcnt,abm,mmx,tune=native\")\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\nusing namespace std;\n\n#define pb push_back\n#define ff first\n#define ss second\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\ntypedef pair<ld, ld> pld;\n\nconst int INF = 1e9;\nconst ll LLINF = 1e18;\nconst int MOD = 1e9 + 7;\n\ntemplate<class K> using sset =  tree<K, null_type, less<K>, rb_tree_tag, tree_order_statistics_node_update>;\n\ninline ll ceil0(ll a, ll b) {\n    return a / b + ((a ^ b) > 0 && a % b);\n}\n\nvoid setIO() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n}\n\nconst int MAXN = 200'000;\nconst int LG = 18;\nconst int MAXM = 200'000;\n\nvector<int> g[MAXN + 5];\nint sz[MAXN + 5], in[MAXN + 5], par[MAXN + 5], depth[MAXN + 5], head[MAXN + 5], tim;\nint n, m;\n\nvoid dfs1(int x, int p){\n    sz[x] = 1;\n    for(int &i : g[x]){\n        if(i == p) continue;\n        dfs1(i, x);\n        sz[x] += sz[i];\n        if(g[x][0] == p || sz[i] > sz[g[x][0]]) swap(g[x][0], i);\n    }\n}\n \nvoid dfs2(int x, int p){\n    in[x] = tim++;\n    par[x] = p;\n    depth[x] = depth[p] + 1;\n    for(int i : g[x]){\n        if(i == p) continue;\n        head[i] = (i == g[x][0] ? head[x] : i);\n        dfs2(i, x);\n    }\n}\n\nconst int MAXSZ = MAXN + 2*MAXN*LG;\nint down[LG][MAXN + 5];\nint up[LG][MAXN + 5];\nvector<int> dag[MAXSZ+ 5];\nint lg[MAXN + 5];\n\nvoid upd(int l, int r, int x, int t){\n    if(l <= in[x] && in[x] <= r){\n        if(l < in[x]) upd(l, in[x] - 1, x, t);\n        if(in[x] < r) upd(in[x] + 1, r, x, t);\n    } else {\n        int sz = lg[r - l + 1];\n        if(t == 2){\n            dag[up[sz][l]].pb(x);\n            dag[up[sz][r - (1 << sz) + 1]].pb(x);\n        } else {\n            dag[x].pb(down[sz][l]);\n            dag[x].pb(down[sz][r - (1 << sz) + 1]);\n        }\n    }\n}\n\n//1 is down, 2 is up\nvoid draw(int a, int b, int c, int t){\n    while(head[a] != head[b]){\n        if(depth[head[a]] > depth[head[b]]) swap(a, b);\n        upd(in[head[b]], in[b], c, t);\n        b = par[head[b]];\n    }\n    if(depth[a] > depth[b]) swap(a, b);\n    upd(in[a], in[b], c, t);\n}\n\nbool vis[MAXSZ + 5], stk[MAXSZ + 5];\nvector<int> ord;\nbool fail;\nint ind;\n\nvoid dfs3(int x){\n    if(fail) return;\n    vis[x] = stk[x] = true;\n    for(int i : dag[x]){\n        if(i == x) continue;\n        if(!vis[i]){\n            dfs3(i);\n        } else if(stk[i]){\n            fail = true;\n            break;\n        }\n    }\n    stk[x] = false;\n    if(x <= n) ord.pb(x);\n}\n\nint main(){\n    setIO();\n    cin >> n >> m;\n    lg[1] = 0;\n    for(int i = 2; i <= n; i++) lg[i] = lg[i/2] + 1;\n    for(int i = 0; i < n - 1; i++){\n        int a, b;\n        cin >> a >> b;\n        g[a].pb(b);\n        g[b].pb(a);\n    }\n    tim = 0;\n    dfs1(1, 1);\n    head[1] = 1;\n    dfs2(1, 1);\n    for(int i = 1; i <= n; i++) down[0][in[i]] = up[0][in[i]] = i;\n    ind = n + 1;\n    for(int i = 1; i < LG; i++){\n        for(int j = 0; j + (1 << i) <= n; j++){\n            down[i][j] = ind++;\n            up[i][j] = ind++;\n\n            dag[down[i][j]].pb(down[i - 1][j]);\n            dag[down[i][j]].pb(down[i - 1][j + (1 << (i - 1))]);\n\n            dag[up[i - 1][j]].pb(up[i][j]);\n            dag[up[i - 1][j + (1 << (i - 1))]].pb(up[i][j]);\n        }\n    }\n    for(int i = 0; i < m; i++){\n        int t, a, b, c;\n        cin >> t >> a >> b >> c;\n        draw(a, b, c, t);\n    }\n    fail = false;\n    for(int i = 1; i <= n; i++){\n        if(!vis[i]){\n            dfs3(i);\n            if(fail) break;\n        }\n    }\n    if(fail){\n        cout << -1 << endl;\n        return 0;\n    }\n    reverse(ord.begin(), ord.end());\n    int ans[n + 1];\n    for(int i = 0; i < ord.size(); i++){\n        ans[ord[i]] = i + 1;\n    }\n    for(int i = 1; i <= n; i++) cout << ans[i] << \" \";\n    cout << endl;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1905",
    "index": "A",
    "title": "Constructive Problems",
    "statement": "Gridlandia has been hit by flooding and now has to reconstruct all of it's cities. Gridlandia can be described by an $n \\times m$ matrix.\n\nInitially, all of its cities are in economic collapse. The government can choose to rebuild certain cities. Additionally, any collapsed city which has at least one vertically neighboring rebuilt city and at least one horizontally neighboring rebuilt city can ask for aid from them and become rebuilt \\textbf{without help from the government}. More formally, collapsed city positioned in $(i, j)$ can become rebuilt if \\textbf{both} of the following conditions are satisfied:\n\n- At least one of cities with positions $(i + 1, j)$ and $(i - 1, j)$ is rebuilt;\n- At least one of cities with positions $(i, j + 1)$ and $(i, j - 1)$ is rebuilt.\n\nIf the city is located on the border of the matrix and has only one horizontally or vertically neighbouring city, then we consider only that city.\n\n\\begin{center}\n\\begin{tabular}{c}\n\\\n\\end{tabular}\n\n{\\small Illustration of two possible ways cities can be rebuilt by adjacent aid. White cells are collapsed cities, yellow cells are initially rebuilt cities (either by the government or adjacent aid), and orange cells are rebuilt cities after adjacent aid.}\n\\end{center}\n\nThe government wants to know the minimum number of cities it has to rebuild such that \\textbf{after some time} all the cities can be rebuild.",
    "tutorial": "We can observe an invariant given by the problem is that every time we apply adjacent aid on any state of the matrix, the sets of rows that have at least one rebuilt city, respectively the sets of columns that appear that have at least one rebuilt city remain constant. Therefore, if we want to have a full matrix as consequence of applying adjacent aid multiple times, both of these sets must contain all rows/columns. As such, the answer is bounded by $max(n, m)$. We can tighten this bound by finding an example which always satisfies the statement. If we take, without loss of generality, $n \\le m$, the following initial setting will satisfy the statement: $(1, 1), (2, 2), (3, 3), ..., (n, n), (n, n + 1), (n, n + 2), .. (n, m)$ I have proposed this div2A at 3 contests and after 1 year of waiting I finally was able to propose it (mainly because theoretically, this was supposed to be my round :)). As the title suggests, this problem is inspired by one day trying to solve some constructive problem that required to draw some weird grid with some properties. And, as I was drawing multiple grids to try out multiple strategies, I was wondering how to draw these grids more optimally, as actually having to count for every matrix the height/width was pretty annoying, and I could just eyeball it by drawing it next to another drawn (but filled out) grid. As such, I needed an already drawn grid \"below\" the current one and another \"to the left\".",
    "code": "#include <bits/stdc++.h>\n#define all(x) (x).begin(),(x).end()\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\n//#define int ll\n#define sz(x) ((int)(x).size())\n\nusing pii = pair<int,int>;\nusing tii = tuple<int,int,int>;\n\nconst int nmax = 1e6 + 5;\nconst int inf = 1e9 + 5;\nint n, k, m, q;\nvector<int> g[nmax];\nint v[nmax];\n\nstatic void testcase() {\n  cin >> n >> m;\n  cout << max(n, m) << '\\n';\n  return;\n}\n\nsigned main() {\n  ios::sync_with_stdio(0);\n  cin.tie(0);\n  int t;\n  cin >> t;\n  for (int i = 0; i < t; i++)\n    testcase();\n}\n\n\n\n/**\n      Anul asta se da centroid.\n-- Surse oficiale\n*/",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1905",
    "index": "B",
    "title": "Begginer's Zelda",
    "statement": "You are given a tree$^{\\dagger}$. In one zelda-operation you can do follows:\n\n- Choose two vertices of the tree $u$ and $v$;\n- Compress all the vertices on the path from $u$ to $v$ into one vertex. In other words, all the vertices on path from $u$ to $v$ will be erased from the tree, a new vertex $w$ will be created. Then every vertex $s$ that had an edge to some vertex on the path from $u$ to $v$ will have an edge to the vertex $w$.\n\n\\begin{center}\n{\\small Illustration of a zelda-operation performed for vertices $1$ and $5$.}\n\\end{center}\n\nDetermine the minimum number of zelda-operations required for the tree to have only one vertex.\n\n$^{\\dagger}$A tree is a connected acyclic undirected graph.",
    "tutorial": "We can prove by induction that on any tree with $K$ leaves, the answer is $[{\\frac{K + 1}{2}}]$, where with $[x]$ we denote the greatest integer smaller than $x$. This can be proven by induction, we will give an overview of what a proof would look like: For two leaves, the answer is clearly $1$. For three leaves, the answer is clearly $2$. For more than four leaves, it is always the case that we can find two leaves for which the node that will be created as a result of applying an operation on these two will have degree greater than $1$ (i.e. it will not be a leaf) The third argument holds because in a tree with four leaves, we have either at least two nodes with degree at least $3$ (and as such we can choose two leaves which contain these two nodes on their chain), or a node with degree at least $4$. Furthermore, it reduces the number of leaves in the tree by $2$.",
    "code": "#include <cmath>\n#include <functional>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <set>\n#include <map>\n#include <list>\n#include <time.h>\n#include <math.h>\n#include <random>\n#include <deque>\n#include <queue>\n#include <unordered_map>\n#include <unordered_set>\n#include <iomanip>\n#include <cassert>\n#include <bitset>\n#include <sstream>\n#include <cstring>\n#include <numeric>\n#define all(x) (x).begin(),(x).end()\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\n//#define int ll\n#define sz(x) ((int)(x).size())\n\nusing pii = pair<int,int>;\nusing tii = tuple<int,int,int>;\n\nconst int nmax = 1e6 + 5;\nconst int inf = 1e9 + 5;\nint n, k, m, q;\nint freq[nmax];\n\nstatic void testcase() {\n  cin >> n;\n  for (int i = 1, a, b; i < n; i++) {\n    cin >> a >> b;\n    freq[a]++;\n    freq[b]++;\n  }\n  int cnt = 0;\n  for(int i = 1; i <= n; i++)\n    cnt += (freq[i] == 1),\n    freq[i] = 0;\n  cout << (cnt + 1) / 2 << '\\n';\n  return;\n}\n\nsigned main() {\n  ios::sync_with_stdio(0);\n  cin.tie(0);\n  int t;\n  cin >> t;\n  for (int i = 0; i < t; i++)\n    testcase();\n}\n\n\n\n/**\n      Anul asta se da centroid.\n-- Surse oficiale\n*/",
    "tags": [
      "greedy",
      "trees"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1905",
    "index": "C",
    "title": "Largest Subsequence",
    "statement": "Given is a string $s$ of length $n$. In one operation you can select the lexicographically largest$^\\dagger$ subsequence of string $s$ and cyclic shift it to the right$^\\ddagger$.\n\nYour task is to calculate the minimum number of operations it would take for $s$ to become sorted, or report that it never reaches a sorted state.\n\n$^\\dagger$A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- In the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.\n\n$^\\ddagger$By cyclic shifting the string $t_1t_2\\ldots t_m$ to the right, we get the string $t_mt_1\\ldots t_{m-1}$.",
    "tutorial": "We can notice that this operation will ultimately reverse the lexicographically largest subset of the initial string. Thus, we can easily check if the string is sortable, and for finding the number of operations we will subtract the length of the largest prefix of equal values of the subset from its length. This solution works in $O(n)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main()\n{\n    cin.tie(nullptr)->sync_with_stdio(false);\n    int q;\n    cin >> q;\n    while (q--)\n    {\n        int n;\n        string s;\n        cin >> n >> s;\n        s = '$' + s;\n        vector<int> subset;\n        for (int i = 1; i <= n; ++i)\n        {\n            while (!subset.empty() && s[subset.back()] < s[i])\n            {\n                subset.pop_back();\n            }\n            subset.push_back(i);\n        }\n        int ans = 0;\n        int m = (int)subset.size() - 1;\n        while (ans <= m && s[subset[ans]] == s[subset[0]])\n        {\n            ans++;\n        }\n        ans = m - ans + 1;\n\n        for (int i = 0; i <= m; ++i)\n        {\n            if (i < m - i)\n            {\n                swap(s[subset[i]], s[subset[m - i]]);\n            }\n        }\n        for (int i = 2; i <= n; ++i)\n        {\n            if (s[i] < s[i - 1])\n            {\n                ans = -1;\n                break;\n            }\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1905",
    "index": "D",
    "title": "Cyclic MEX",
    "statement": "For an array $a$, define its cost as $\\sum_{i=1}^{n} \\operatorname{mex} ^\\dagger ([a_1,a_2,\\ldots,a_i])$.\n\nYou are given a permutation$^\\ddagger$ $p$ of the set $\\{0,1,2,\\ldots,n-1\\}$. Find the maximum cost across all cyclic shifts of $p$.\n\n$^\\dagger\\operatorname{mex}([b_1,b_2,\\ldots,b_m])$ is the smallest non-negative integer $x$ such that $x$ does not occur among $b_1,b_2,\\ldots,b_m$.\n\n$^\\ddagger$A permutation of the set $\\{0,1,2,...,n-1\\}$ is an array consisting of $n$ distinct integers from $0$ to $n-1$ in arbitrary order. For example, $[1,2,0,4,3]$ is a permutation, but $[0,1,1]$ is not a permutation ($1$ appears twice in the array), and $[0,2,3]$ is also not a permutation ($n=3$ but there is $3$ in the array).",
    "tutorial": "Let's analyze how the values of each prefix mex changes upon performing a cyclic shift to the left: The first prefix mex is popped. Each prefix mex with a value less than $p_1$ doesn't change. Each prefix mex with a value greater than $p_1$ becomes $p_1$. $n$ is appended to the back. Let's keep our prefix mexes compressed ( meaning that we keep the value and its frequency instead of keeping multiple same values ). After that, we can simulate the above process naively with a deque, because the potential will decrease by the number of performed operations. This solution works in $O(n)$ time.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n\nusing namespace std;\n\nint32_t main()\n{\n\tcin.tie(nullptr)->sync_with_stdio(false);\n\tint q;\n\tcin >> q;\n\twhile (q--)\n\t{\n\t\tint n;\n\t\tcin >> n;\n\t\tvector<int> a(n + 1);\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t{\n\t\t\tcin >> a[i];\n\t\t}\n\t\tdeque<pair<int, int>> dq;\n\t\tvector<int> f(n + 1);\n\t\tint mex = 0;\n\t\tint sum = 0;\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t{\n\t\t\tf[a[i]]++;\n\t\t\twhile (f[mex])\n\t\t\t{\n\t\t\t\tmex++;\n\t\t\t}\n\t\t\tdq.push_back({mex, 1});\n\t\t\tsum += mex;\n\t\t}\n\t\tint ans = sum;\n\t\tfor (int i = 1; i < n; ++i)\n\t\t{\n\t\t\tpair<int, int> me = {a[i], 0};\n\t\t\tsum -= dq.front().first;\n\t\t\tdq.front().second--;\n\t\t\tif (dq.front().second == 0)\n\t\t\t{\n\t\t\t\tdq.pop_front();\n\t\t\t}\n\t\t\twhile (!dq.empty() && dq.back().first >= a[i])\n\t\t\t{\n\t\t\t\tsum -= dq.back().first * dq.back().second;\n\t\t\t\tme.second += dq.back().second;\n\t\t\t\tdq.pop_back();\n\t\t\t}\n\t\t\tdq.push_back(me);\n\t\t\tsum = sum + me.first * me.second;\n\t\t\tdq.push_back({n, 1});\n\t\t\tsum += n;\n\t\t\tans = max(ans, sum);\n\t\t}\n\t\tcout << ans << '\\n';\n\t}\n}",
    "tags": [
      "data structures",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1905",
    "index": "E",
    "title": "One-X",
    "statement": "In this sad world full of imperfections, ugly segment trees exist.\n\nA segment tree is a tree where each node represents a segment and has its number. A segment tree for an array of $n$ elements can be built in a recursive manner. Let's say function $\\operatorname{build}(v,l,r)$ builds the segment tree rooted in the node with number $v$ and it corresponds to the segment $[l,r]$.\n\nNow let's define $\\operatorname{build}(v,l,r)$:\n\n- If $l=r$, this node $v$ is a leaf so we stop adding more edges\n- Else, we add the edges $(v, 2v)$ and $(v, 2v+1)$. Let $m=\\lfloor \\frac{l+r}{2} \\rfloor$. Then we call $\\operatorname{build}(2v,l,m)$ and $\\operatorname{build}(2v+1,m+1,r)$.\n\nSo, the whole tree is built by calling $\\operatorname{build}(1,1,n)$.\n\nNow Ibti will construct a segment tree for an array with $n$ elements. He wants to find the sum of $\\operatorname{lca}^\\dagger(S)$, where $S$ is a non-empty subset of \\textbf{leaves}. Notice that there are exactly $2^n - 1$ possible subsets. Since this sum can be very large, output it modulo $998\\,244\\,353$.\n\n$^\\dagger\\operatorname{lca}(S)$ is the number of the least common ancestor for the nodes that are in $S$.",
    "tutorial": "Let's try to solve a slightly easier problem first: changing the coefficient of the label to be the msb of the label. We can note that at each depth, every label will have the same number of digits ( in base 2 ), thus the same msb. And we can notice that for each depth there are at most $2$ different interval lengths. Combining the former with the latter, we can solve this case in $O(log(N))$ time complexity, since the maximum depth is bounded by $log(N)$. We can find an easy generalization to this: for the $k$-th most significant bit of each label to be $1$, we have to go right from a node whose depth is $k-1$. Thus the above solution can be extended to find the contribution of the $k$-th most significant bit of each label. Doing this for all bits gives us a time complexity of $O(log^2(N))$ which is sufficient to pass the given constraints.",
    "code": "#include <bits/stdc++.h>\n#define int long long\nusing namespace std;\nconst int mod = 998244353;\nstruct Mint\n{\n    int val;\n    Mint(long long x = 0)\n    {\n        val = x % mod;\n    }\n    Mint operator+(Mint oth)\n    {\n        return val + oth.val;\n    }\n    Mint operator-(Mint oth)\n    {\n        return val - oth.val + mod;\n    }\n    Mint operator*(Mint oth)\n    {\n        return val * oth.val;\n    }\n};\nMint powmod(int a, int b)\n{\n    if (b == 0)\n    {\n        return 1;\n    }\n    if (b % 2 == 1)\n    {\n        return powmod(a, b - 1) * a;\n    }\n    Mint P = powmod(a, b / 2);\n    return P * P;\n}\nmap<int, vector<vector<tuple<int, int, int>>>> memo;\nvector<vector<tuple<int, int, int>>> find_ranges(int lg) // log^2\n{\n    if (memo.find(lg) != memo.end())\n    {\n        return memo[lg];\n    }\n    if (lg == 1)\n    {\n        return {{{1, 1, 1}}};\n    }\n    vector<vector<tuple<int, int, int>>> l = find_ranges((lg + 1) / 2);\n    vector<vector<tuple<int, int, int>>> r = find_ranges(lg / 2);\n    vector<vector<tuple<int, int, int>>> ans(max(l.size(), r.size()) + 1);\n    Mint x = (powmod(2, (lg + 1) / 2) - 1) * (powmod(2, lg / 2) - 1);\n    ans[0].push_back({lg, 1, x.val});\n     for (int i = 0; i < (int)l.size(); ++i)\n    {\n        for (auto j : l[i])\n        {\n            ans[i + 1].push_back(j);\n        }\n    }\n    for (int i = 0; i < (int)r.size(); ++i)\n    {\n        for (auto j : r[i])\n        {\n            bool ok = false;\n            for (auto &[size, cnt, ways] : ans[i + 1])\n            {\n                if (size == get<0>(j))\n                {\n                    ok = true;\n                    cnt += get<1>(j);\n                }\n            }\n            if (!ok)\n            {\n                ans[i + 1].push_back(j);\n            }\n        }\n    }\n    return memo[lg] = ans;\n}\nMint count(int lg, int coef)\n{\n    vector<vector<tuple<int, int, int>>> adam = find_ranges(lg);\n    Mint ans = 0;\n    Mint pow_2 = 1;\n    for (int i = 0; i < (int)adam.size(); ++i)\n    {\n        for (auto [size, cnt, ways] : adam[i])\n        {\n            ans = ans + pow_2 * coef * cnt * ways;\n        }\n        pow_2 = pow_2 * 2;\n    }\n    return ans;\n}\nint32_t main()\n{\n    cin.tie(nullptr)->sync_with_stdio(false);\n    int q;\n    cin >> q;\n    while (q--)\n    {\n        int n;\n        cin >> n;\n        vector<vector<tuple<int, int, int>>> adam = find_ranges(n);\n        Mint ans = count(n, 1);\n        for (int i = 1; i < (int)adam.size(); ++i)\n        {\n            for (auto [size, cnt, ways] : adam[i - 1])\n            {\n                int lsize = (size + 1) / 2;\n                int rsize = size / 2;\n                if (rsize)\n                {\n                    ans = ans + count(rsize, cnt);\n                }\n            }\n        }\n        cout << ans.val << '\\n';\n        memo.clear();\n    }\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1905",
    "index": "F",
    "title": "Field Should Not Be Empty",
    "statement": "You are given a permutation$^{\\dagger}$ $p$ of length $n$.\n\nWe call index $x$ good if for all $y < x$ it holds that $p_y < p_x$ and for all $y > x$ it holds that $p_y > p_x$. We call $f(p)$ the number of good indices in $p$.\n\nYou can perform the following operation: pick $2$ \\textbf{distinct} indices $i$ and $j$ and swap elements $p_i$ and $p_j$.\n\nFind the maximum value of $f(p)$ after applying the aforementioned operation \\textbf{exactly once}.\n\n$^{\\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "The key observation to this problem is that most swaps are useless. In fact, we can find that only $2n$ swaps can increase our initial cost: The first type of meaningful swaps is $(i,p_i)$ For each $1 < i < n$, consider $k$ and $l$ such that $p_k = max(p_1,p_2,...,p_{i-1})$ and $p_l = min(p_{i+1},p_{i+2},...,p_n)$. The second type is $(k,l)$. The reason why this is true is because the first type of swap can create a new good index ( since every good index must be a fixed point ) and the second type of swap can fix an already good index. It's obvious that if a swap does neither of the above, it can't increase our current cost. Calculating $f(p)$ after each swap can be done with a segment tree. Consider adding one on the ranges $(min(i,p_i),max(i,p_i))$. Now an index is good if and only if its value is $1$, which is also the minimum value an index can have. Thus our segment tree has to find the number of minimums while performing range additions which can be easily maintained by lazy propagation. This solution works in $O(nlog(n))$ time complexity.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nstruct aint\n{\n    vector<pair<int, int>> a;\n    vector<int> lazy;\n    void resize(int n)\n    {\n        a = vector<pair<int, int>>(4 * n);\n        lazy = vector<int>(4 * n);\n    }\n    void init(int node, int left, int right)\n    {\n        a[node].second = (right - left + 1);\n        if (left != right)\n        {\n            int mid = (left + right) / 2;\n            init(2 * node, left, mid);\n            init(2 * node + 1, mid + 1, right);\n        }\n    }\n    void prop(int node, int left, int right)\n    {\n        a[node].first += lazy[node];\n        if (left != right)\n        {\n            lazy[2 * node] += lazy[node];\n            lazy[2 * node + 1] += lazy[node];\n        }\n        lazy[node] = 0;\n    }\n    pair<int, int> merge(pair<int, int> a, pair<int, int> b)\n    {\n        if (a.first == b.first)\n        {\n            return pair<int, int>{a.first, a.second + b.second};\n        }\n        return min(a, b);\n    }\n    void update(int node, int left, int right, int st, int dr, int val)\n    {\n        prop(node, left, right);\n        if (right < st || left > dr)\n        {\n            return;\n        }\n        if (st <= left && dr >= right)\n        {\n            lazy[node] += val;\n            prop(node, left, right);\n            return;\n        }\n        int mid = (left + right) / 2;\n        update(2 * node, left, mid, st, dr, val);\n        update(2 * node + 1, mid + 1, right, st, dr, val);\n        a[node] = merge(a[2 * node], a[2 * node + 1]);\n    }\n};\nstruct bit\n{\n    vector<int> a;\n    void resize(int n)\n    {\n        a = vector<int>(n + 1);\n    }\n    void update(int pos, int val)\n    {\n        int n = (int)a.size() - 1;\n        for (int i = pos; i <= n; i += i & (-i))\n        {\n            a[i] += val;\n        }\n    }\n    int query(int pos)\n    {\n        int ans = 0;\n        for (int i = pos; i; i -= i & (-i))\n        {\n            ans += a[i];\n        }\n        return ans;\n    }\n    int query(int st, int dr)\n    {\n        return query(dr) - query(st - 1);\n    }\n};\nint32_t main()\n{\n    cin.tie(nullptr)->sync_with_stdio(false);\n    int q;\n    cin >> q;\n    while (q--)\n    {\n        int n;\n        cin >> n;\n        vector<int> a(n + 1);\n        bool sortat = true;\n        for (int i = 1; i <= n; ++i)\n        {\n            cin >> a[i];\n            if (a[i] != i)\n            {\n                sortat = false;\n            }\n        }\n        if (sortat)\n        {\n            cout << n - 2 << '\\n';\n            continue;\n        }\n        vector<pair<int, int>> qui(n + 1);\n        stack<int> s;\n        bit tree;\n        tree.resize(n);\n        for (int i = 1; i <= n; ++i)\n        {\n            while (!s.empty() && a[s.top()] < a[i])\n            {\n                s.pop();\n            }\n            if (!s.empty())\n            {\n                qui[i].first = s.top();\n            }\n            if (tree.query(a[i], n) > 1)\n            {\n                qui[i].first = 0;\n            }\n            tree.update(a[i], 1);\n            s.push(i);\n        }\n        while (!s.empty())\n            s.pop();\n        tree.resize(n);\n        for (int i = n; i >= 1; --i)\n        {\n            while (!s.empty() && a[s.top()] > a[i])\n            {\n                s.pop();\n            }\n            if (!s.empty())\n            {\n                qui[i].second = s.top();\n            }\n            if (tree.query(1, a[i]) > 1)\n            {\n                qui[i].second = 0;\n            }\n            tree.update(a[i], 1);\n            s.push(i);\n        }\n        aint lesgo;\n        lesgo.resize(n);\n        lesgo.init(1, 1, n);\n        function<void(int, int)> upd = [&](int ind, int sign)\n        {\n            lesgo.update(1, 1, n, min(ind, a[ind]), max(ind, a[ind]), sign);\n        };\n        function<int()> count = [&]()\n        {\n            if (lesgo.a[1].first == 1)\n            {\n                return lesgo.a[1].second;\n            }\n            return 0;\n        };\n        function<void(int, int)> mySwap = [&](int i, int j)\n        {\n            upd(i, -1);\n            upd(j, -1);\n            swap(a[i], a[j]);\n            upd(i, 1);\n            upd(j, 1);\n        };\n        for (int i = 1; i <= n; ++i)\n        {\n            upd(i, 1);\n        }\n        int ans = 0;\n        for (int i = 1; i <= n; ++i)\n        {\n            if (qui[i].first && qui[i].second)\n            {\n                mySwap(qui[i].first, qui[i].second);\n                ans = max(ans, count());\n                mySwap(qui[i].first, qui[i].second);\n            }\n        }\n        vector<int> pos(n + 1);\n        for (int i = 1; i <= n; ++i)\n        {\n            pos[a[i]] = i;\n        }\n        for (int i = 1; i <= n; ++i)\n        {\n            int qui1 = i;\n            int qui2 = pos[i];\n            mySwap(qui1, qui2);\n            ans = max(ans, count());\n            mySwap(qui1, qui2);\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1907",
    "index": "A",
    "title": "Rook",
    "statement": "As you probably know, chess is a game that is played on a board with 64 squares arranged in an $8\\times 8$ grid. Columns of this board are labeled with letters from \\textbf{a} to \\textbf{h}, and rows are labeled with digits from \\textbf{1} to \\textbf{8}. Each square is described by the row and column it belongs to.\n\nThe rook is a piece in the game of chess. During its turn, it may move any non-zero number of squares horizontally or vertically. Your task is to find all possible moves for a rook on an empty chessboard.",
    "tutorial": "The answer includes all cells that share the same column or row with the given cell. Let's iterate through all the columns, keeping the row constant, and vice versa, iterate through the rows without changing the column. To ensure that the input cell is not included in the answer, you can either skip it or add all positions to a set and then remove it from there.",
    "code": "for _ in range(int(input())):\n    s = input()\n    for c in \"abcdefgh\":\n        if c != s[0]:\n            print(c + s[1], end=' ')\n    for c in \"12345678\":\n        if c != s[1]:\n            print(s[0] + c, end=' ')\n    print()",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1907",
    "index": "B",
    "title": "YetnotherrokenKeoard",
    "statement": "Polycarp has a problem — his laptop keyboard is broken.\n\nNow, when he presses the 'b' key, it acts like an unusual backspace: it deletes the last (rightmost) lowercase letter in the typed string. If there are no lowercase letters in the typed string, then the press is completely ignored.\n\nSimilarly, when he presses the 'B' key, it deletes the last (rightmost) uppercase letter in the typed string. If there are no uppercase letters in the typed string, then the press is completely ignored.\n\nIn both cases, the letters 'b' and 'B' are not added to the typed string when these keys are pressed.\n\nConsider an example where the sequence of key presses was \"ARaBbbitBaby\". In this case, the typed string will change as follows: \"\" $\\xrightarrow{A}$ \"A\" $\\xrightarrow{R}$ \"AR\" $\\xrightarrow{a}$ \"ARa\" $\\xrightarrow{B}$ \"Aa\" $\\xrightarrow{b}$ \"A\" $\\xrightarrow{b}$ \"A\" $\\xrightarrow{i}$ \"Ai\" $\\xrightarrow{t}$ \"Ait\" $\\xrightarrow{B}$ \"it\" $\\xrightarrow{a}$ \"ita\" $\\xrightarrow{b}$ \"it\" $\\xrightarrow{y}$ \"ity\".\n\nGiven a sequence of pressed keys, output the typed string after processing all key presses.",
    "tutorial": "To solve the problem, it was necessary to quickly support deletions. For this, one could maintain two stacks: one with the positions of uppercase letters and one with the positions of lowercase letters. Then, when deleting, one needs to somehow mark that the character at this position should not be output. Alternatively, one could reverse the original string, then instead of deleting characters, they would simply need to be skipped.",
    "code": "for _ in range(int(input())):\n    s = list(input())\n    n = len(s)\n    upper = []\n    lower = []\n    for i in range(n):\n        if s[i] == 'b':\n            s[i] = ''\n            if lower:\n                s[lower.pop()] = ''\n            continue\n        if s[i] == 'B':\n            s[i] = ''\n            if upper:\n                s[upper.pop()] = ''\n            continue\n        if 'a' <= s[i] <= 'z':\n            lower += [i]\n        else:\n            upper += [i]\n    print(''.join(s))",
    "tags": [
      "data structures",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1907",
    "index": "C",
    "title": "Removal of Unattractive Pairs",
    "statement": "Vlad found a string $s$ consisting of $n$ lowercase Latin letters, and he wants to make it as short as possible.\n\nTo do this, he can remove \\textbf{any} pair of adjacent characters from $s$ any number of times, provided they are \\textbf{different}. For example, if $s$=racoon, then by removing one pair of characters he can obtain the strings coon, roon, raon, and raco, but he cannot obtain racn (because the removed letters were the same) or rcon (because the removed letters were not adjacent).\n\nWhat is the minimum length Vlad can achieve by applying any number of deletions?",
    "tutorial": "Consider a finite string; obviously, all characters in it are the same, as otherwise, we could remove some pair of characters. If some character occurs in the string more than $\\lfloor \\frac{n}{2} \\rfloor$ times, then the final string will always consist only of it, because with one deletion we can only get rid of one occurrence. To minimize the number of these characters, we need to remove one occurrence each time. We can always do this until the string is left with only such a character. Otherwise, we can remove all possible pairs regardless of the order of deletions.",
    "code": "orda = ord('a')\n\ndef solve():\n    n = int(input())\n    cnt = [0] * 26\n    for c in input():\n        cnt[ord(c) - orda] += 1\n    mx = max(cnt)\n    print(max(n % 2, 2 * mx - n))\n\n\nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1907",
    "index": "D",
    "title": "Jumping Through Segments",
    "statement": "Polycarp is designing a level for a game. The level consists of $n$ segments on the number line, where the $i$-th segment starts at the point with coordinate $l_i$ and ends at the point with coordinate $r_i$.\n\nThe player starts the level at the point with coordinate $0$. In one move, they can move to any point that is within a distance of no more than $k$. After their $i$-th move, the player must land within the $i$-th segment, that is, at a coordinate $x$ such that $l_i \\le x \\le r_i$. This means:\n\n- After the first move, they must be inside the first segment (from $l_1$ to $r_1$);\n- After the second move, they must be inside the second segment (from $l_2$ to $r_2$);\n- ...\n- After the $n$-th move, they must be inside the $n$-th segment (from $l_n$ to $r_n$).\n\nThe level is considered completed if the player reaches the $n$-th segment, following the rules described above. After some thought, Polycarp realized that it is impossible to complete the level with some values of $k$.\n\nPolycarp does not want the level to be too easy, so he asks you to determine the minimum integer $k$ with which it is possible to complete the level.",
    "tutorial": "First, let's note that if we can pass a level with some value of $k$, then we can make all the same moves and pass it with a larger value. This allows us to use binary search for the answer. To check whether it is possible to pass the level with a certain $k$, we will maintain a segment in which we can find ourselves. After each move, it expands by $k$ in both directions and is reduced to the intersection with the segment where the player must be at that move. If at any point the intersection becomes empty, then it is impossible to pass the level with such $k$.",
    "code": "def solve():\n    n = int(input())\n    seg = [list(map(int, input().split())) for x in range(n)]\n\n    def check(k):\n        ll, rr = 0, 0\n        for e in seg:\n            ll = max(ll - k, e[0])\n            rr = min(rr + k, e[1])\n            if ll > rr:\n                return False\n        return True\n\n    l, r = -1, 10 ** 9\n    while r - l > 1:\n        mid = (r + l) // 2\n        if check(mid):\n            r = mid\n        else:\n            l = mid\n    print(r)\n\n\nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "binary search",
      "constructive algorithms"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1907",
    "index": "E",
    "title": "Good Triples",
    "statement": "Given a non-negative integer number $n$ ($n \\ge 0$). Let's say a triple of non-negative integers $(a, b, c)$ is good if $a + b + c = n$, and $digsum(a) + digsum(b) + digsum(c) = digsum(n)$, where $digsum(x)$ is the sum of digits of number $x$.\n\nFor example, if $n = 26$, then the pair $(4, 12, 10)$ is good, because $4 + 12 + 10 = 26$, and $(4) + (1 + 2) + (1 + 0) = (2 + 6)$.\n\nYour task is to find the number of good triples for the given number $n$. The order of the numbers in a triple matters. For example, the triples $(4, 12, 10)$ and $(10, 12, 4)$ are two different triples.",
    "tutorial": "A triplet is considered good only if each digit of the number $n$ was obtained without carrying over during addition. For example, consider $a=2$, $b=7$, $c=4$; the sum of the digits is $2 + 7 + 4 = 13$, and the sum of the digits of their sum is $1 + 3 = 4$. This means that whenever there is a carry in one of the digits, the sum $digsum(a) + digsum(b) + digsum(c)$ always increases more than $digsum(n)$. This allows us to consider each digit separately and multiply their answers. The answer for each digit $x$ will be the number of digit triplets with the sum $x$. These values do not depend on the input data, so they can be precalculated, but this is not necessary to pass the tests.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    cnt = 1\n    while n > 0:\n        d = n % 10\n        n //= 10\n        mul = 0\n        for i in range(d + 1):\n            for j in range(d + 1):\n                if d - i - j >= 0:\n                    mul += 1\n        cnt *= mul\n    print(cnt)",
    "tags": [
      "brute force",
      "combinatorics",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1907",
    "index": "F",
    "title": "Shift and Reverse",
    "statement": "Given an array of integers $a_1, a_2, \\ldots, a_n$. You can make two types of operations with this array:\n\n- Shift: move the last element of array to the first place, and shift all other elements to the right, so you get the array $a_n, a_1, a_2, \\ldots, a_{n-1}$.\n- Reverse: reverse the whole array, so you get the array $a_n, a_{n-1}, \\ldots, a_1$.\n\nYour task is to sort the array in non-decreasing order using the minimal number of operations, or say that it is impossible.",
    "tutorial": "In this problem, there are several possible sequences of actions from which the optimal one must be chosen. For brevity, let's denote the reverse by the letter \"R\", and the shift by the letter \"S\": SS$\\dots$SS RS$\\dots$SR RS$\\dots$SS SS$\\dots$SR Let's write out the array twice and count the segments on which it increases and decreases. This way, we can find all possible shifts that will sort the array.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n    a = list(reversed(a))*2\n    p = [0]\n    q = [0]\n    for i in range(n*2-1):\n        p.append(p[-1]+1 if a[i]>=a[i+1] else 0)\n        q.append(q[-1]+1 if a[i]<=a[i+1] else 0)\n    minn = 1000000\n    for i in range(n-1,len(p)):\n        if p[i] == n-1:\n            minn = min(minn, i-n+1, len(p)-i+1)\n        if q[i] == n-1:\n            minn = min(minn, len(p)-i, i-n+2)\n    print(-1 if minn == 1000000 else minn)",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1907",
    "index": "G",
    "title": "Lights",
    "statement": "In the end of the day, Anna needs to turn off the lights in the office. There are $n$ lights and $n$ light switches, but their operation scheme is really strange. The switch $i$ changes the state of light $i$, but it also changes the state of some other light $a_i$ (change the state means that if the light was on, it goes off and vice versa).\n\nHelp Anna to turn all the lights off using minimal number of switches, or say it is impossible.",
    "tutorial": "Let's construct a directed graph where an edge originates from vertex $i$ to vertex $a_i$. In such a graph, exactly one edge originates from each vertex, and there is exactly one cycle in each connected component. First, we will turn off all the lights that are not part of the cycles; the sequence of such turn-offs is unique: We will remove all the turned-off vertices into which no edges enter, and we will turn off and remove the turned-on ones. After that, only cycle components will remain, some of which may have lights turned on. Consider any edge of the cycle from $i$ to $a_i$; we will either press switch $i$ or not. To count the number of operations in these cases, we will use the same algorithm as before.",
    "code": "#include <bits/stdc++.h>\n\n#define long long long int\n#define DEBUG\nusing namespace std;\n\n// @author: pashka\n\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<bool> s(n);\n    {\n        string ss;\n        cin >> ss;\n        for (int i = 0; i < n; i++) {\n            s[i] = ss[i] == '1';\n        }\n    }\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n        a[i]--;\n    }\n\n    vector<int> res;\n    vector<int> d(n);\n    for (int i = 0; i < n; i++) {\n        d[a[i]]++;\n    }\n    vector<int> z;\n    for (int i = 0; i < n; i++) {\n        if (d[i] == 0) z.push_back(i);\n    }\n\n    for (int i = 0; i < (int)z.size(); i++) {\n        int x = z[i];\n        int y = a[x];\n        if (s[x]) {\n            res.push_back(x);\n            s[x] = !s[x];\n            s[y] = !s[y];\n        }\n        d[y]--;\n        if (d[y] == 0) {\n            z.push_back(y);\n        }\n    }\n\n    vector<bool> u(n);\n    for (int i = 0; i < n; i++) {\n        if (s[i] && !u[i]) {\n            int x = i;\n            vector<int> p;\n            vector<bool> ps;\n            int c = 0;\n            while (!u[x]) {\n                p.push_back(x);\n                ps.push_back(s[x]);\n                c += s[x];\n                u[x] = true;\n                x = a[x];\n            }\n            int k = p.size();\n            p.push_back(x);\n            ps.push_back(s[x]);\n            if (c % 2 == 1) {\n                cout << -1;\n                return;\n            }\n            vector<int> v1;\n            vector<bool> ps1 = ps;\n            for (int j = 0; j < k; j++) {\n                if (j == 0 || ps1[j]) {\n                    v1.push_back(p[j]);\n                    ps1[j] = !ps1[j];\n                    ps1[j + 1] = !ps1[j + 1];\n                }\n            }\n            vector<int> v2;\n            vector<bool> ps2 = ps;\n            for (int j = 0; j < k; j++) {\n                if (j != 0 && ps2[j]) {\n                    v2.push_back(p[j]);\n                    ps2[j] = !ps2[j];\n                    ps2[j + 1] = !ps2[j + 1];\n                }\n            }\n            if (v1.size() < v2.size()) {\n                for (auto x : v1) {\n                    res.push_back(x);\n                }\n            } else {\n                for (auto x : v2) {\n                    res.push_back(x);\n                }\n            }\n        }\n    }\n    cout << res.size() << \"\\n\";\n    for (auto x : res) cout << x + 1 << \" \";\n}\n\nint main() {\n    int t;\n    cin >> t;\n    for(int _ = 0; _ < t; ++_){\n        solve();\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1909",
    "index": "A",
    "title": "Distinct Buttons",
    "statement": "\\begin{quote}\nDeemo - Entrance\n\\hfill ⠀\n\\end{quote}\n\nYou are located at the point $(0, 0)$ of an infinite Cartesian plane. You have a controller with $4$ buttons which can perform one of the following operations:\n\n- $U$: move from $(x, y)$ to $(x, y+1)$;\n- $R$: move from $(x, y)$ to $(x+1, y)$;\n- $D$: move from $(x, y)$ to $(x, y-1)$;\n- $L$: move from $(x, y)$ to $(x-1, y)$.\n\nUnfortunately, the controller is broken. If you press all the $4$ buttons (in any order), the controller stops working. It means that, during the whole trip, you can only press at most $3$ distinct buttons (any number of times, in any order).\n\nThere are $n$ special points in the plane, with integer coordinates $(x_i, y_i)$.\n\nCan you visit all the special points (in any order) without breaking the controller?",
    "tutorial": "Suppose you can only use $\\texttt{U}$, $\\texttt{R}$, $\\texttt{D}$. Which cells can you reach? If you only use buttons $\\texttt{U}$, $\\texttt{R}$, $\\texttt{D}$, you can never reach the points with $x < 0$. However, if all the special points have $x \\geq 0$, you can reach all of them with the following steps: visit all the special points with $x = 0$, using the buttons $\\texttt{U}$, $\\texttt{D}$; press the button $\\texttt{R}$ to reach $x = 1$; visit all the special points with $x = 1$, using the buttons $\\texttt{U}$, $\\texttt{D}$; $\\dots$ visit all the special points with $x = 100$, using the buttons $\\texttt{U}$, $\\texttt{D}$. Similarly, if you use at most $3$ buttons in total, you can reach all the special points if at least one of the following conditions is true: all $x_i \\geq 0$; all $x_i \\leq 0$; all $y_i \\geq 0$; all $y_i \\leq 0$. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        ll a = 1, b = 1, c = 1, d = 1;\n\n        for (ll i = 1; i <= n; i++) {\n\n            ll x, y; cin >> x >> y;\n\n            if (x > 0) a = 0;\n\n            if (x < 0) b = 0;\n\n            if (y > 0) c = 0;\n\n            if (y < 0) d = 0;\n\n        }\n\n\n\n        if (a + b + c + d == 0) cout << \"NO\" << nl;\n\n        else cout << \"YES\" << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1909",
    "index": "B",
    "title": "Make Almost Equal With Mod",
    "statement": "\\begin{quote}\nxi - Solar Storm\n\\hfill ⠀\n\\end{quote}\n\nYou are given an array $a_1, a_2, \\dots, a_n$ of distinct positive integers. You have to do the following operation \\textbf{exactly once}:\n\n- choose a positive integer $k$;\n- for each $i$ from $1$ to $n$, replace $a_i$ with $a_i \\text{ mod } k^\\dagger$.\n\nFind a value of $k$ such that $1 \\leq k \\leq 10^{18}$ and the array $a_1, a_2, \\dots, a_n$ contains \\textbf{exactly} $2$ distinct values at the end of the operation. It can be shown that, under the constraints of the problem, at least one such $k$ always exists. If there are multiple solutions, you can print any of them.\n\n$^\\dagger$ $a \\text{ mod } b$ denotes the remainder after dividing $a$ by $b$. For example:\n\n- $7 \\text{ mod } 3=1$ since $7 = 3 \\cdot 2 + 1$\n- $15 \\text{ mod } 4=3$ since $15 = 4 \\cdot 3 + 3$\n- $21 \\text{ mod } 1=0$ since $21 = 21 \\cdot 1 + 0$",
    "tutorial": "Find a value of $k$ that works in many cases. $k = 2$ works in many cases. What if it does not work? If $k = 2$ does not work, either all the numbers are even or all the numbers are odd. Which $k$ can you try now? Let $f(k)$ be the number of distinct values after the operation, using $k$. Let's try $k = 2$. It works in all cases, except when either all the numbers are even or all the numbers are odd. Let's generalize. If $a_i \\text{ mod } k = x$, one of the following holds: $a_i \\text{ mod } 2k = x$; $a_i \\text{ mod } 2k = x+k$; It means that, if $f(k) = 1$ (i.e., all the values after the operations are $x$), either $f(2k) = 1$ (if either all the values become $x$, or they all become $x+k$), or $f(2k) = 2$. Therefore, it is sufficient to try $k = 2^1, \\dots, 2^{57}$. In fact, $f(1) = 1$ and $f(2^{57}) = n$, so there must exist $m < 57$ such that $f(2^m) = 1$ and $f(2^{m+1}) \\neq 1 \\implies f(2^{m+1}) = 2$. Alternative (more intuitive?) interpretation: $a_i \\text{ mod } 2^j$ corresponds to the last $j$ digits in the binary representation of $a_i$. There must exist $j$ such that the last $j$ digits make exactly $2$ distinct blocks. In the following picture, $a = [1005, 2005, 7005, 11005, 16005]$ and $k = 16$: Complexity: $O(n \\log(\\max a_i))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<ll> a(n + 1, 0);\n\n        for (ll i = 1; i <= n; i++) {\n\n            cin >> a[i];\n\n        }\n\n\n\n        auto good = [&](vector<ll> a, ll k) {\n\n            set<ll> st;\n\n            for (ll i = 1; i <= n; i++) st.insert(a[i] % k);\n\n            return (st.size() == 2);\n\n        };\n\n\n\n        for (ll k = 2;; k *= 2) {\n\n            if (good(a, k)) {\n\n                cout << k << nl; break;\n\n            }\n\n        }\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1909",
    "index": "C",
    "title": "Heavy Intervals",
    "statement": "\\begin{quote}\nShiki - Pure Ruby\n\\hfill ⠀\n\\end{quote}\n\nYou have $n$ intervals $[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]$, such that $l_i < r_i$ for each $i$, and all the endpoints of the intervals are distinct.\n\nThe $i$-th interval has weight $c_i$ per unit length. Therefore, the weight of the $i$-th interval is $c_i \\cdot (r_i - l_i)$.\n\nYou don't like large weights, so you want to make the sum of weights of the intervals as small as possible. It turns out you can perform all the following three operations:\n\n- rearrange the elements in the array $l$ in any order;\n- rearrange the elements in the array $r$ in any order;\n- rearrange the elements in the array $c$ in any order.\n\nHowever, after performing all of the operations, the intervals must still be valid (i.e., for each $i$, $l_i < r_i$ must hold).\n\nWhat's the minimum possible sum of weights of the intervals after performing the operations?",
    "tutorial": "Assign bigger costs to shorter intervals. Solve the problem with $n = 2$. Solve the following case: $l = [1, 2]$, $r = [3, 4]$, $c = [1, 2]$. Can you generalize it? You have to match each $l_i$ with some $r_j > l_i$. Construct $v = {l_1, l_2, \\dots, l_n, r_1, r_2, \\dots, r_n}$ and sort it. If you replace every $l_i$ with the symbol $\\texttt{(}$ and every $r_i$ with the symbol $\\texttt{)}$, you get a regular bracket sequence (sketch of proof: $l_i < r_i$ for each $i$, so each prefix of symbols contains at least as many $\\texttt{(}$ as $\\texttt{)}$, so the bracket sequence is regular). Now match each $\\texttt{(}$ with the corresponding $\\texttt{)}$. You can show that this is the optimal way to rearrange the $l_i$ and the $r_i$. (From now, let the $l_i$, $r_i$ and $c_i$ be the values after your rearrangement.) Proof: If you match the brackets in any other way, you get two intervals such that their intersection is non-empty but it is different from both intervals (i.e., you get $l_i < l_j < r_i < r_j$). You have also assigned some cost $c_i$ to $[l_i, r_i]$ and $c_j$ to $[l_j, r_j]$. Without loss of generality, $c_i \\leq c_j$ (the other case is symmetrical). If you swap $r_i$ and $r_j$, the cost does not increase. Keep swapping endpoints until you get the \"regular\" bracket matching. You can show that the process ends in a finite number of steps. For example, you can show that $\\sum ((r_i - l_i)^2)$ strictly increases after each step, and it is an integer $\\leq \\sum (r_i^2)$. Now, you can get the minimum cost by sorting the intervals by increasing length and sorting the $c_i$ in decreasing order. Alternative (more intuitive?) interpretation: If you solve the problem with $n = 2$ and try to generalize, you can notice that it seems optimal to match every $r_i$ with the largest unused $l_i$ (if you iterate over $r_i$ in increasing order). You can implement the solution by using either a stack (to simulate the bracket matching) or a set (to find the largest unused $l_i$). Complexity: $O(n \\log n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<array<ll, 2>> events;\n\n        vector<ll> c(n + 1, 0);\n\n\n\n        for (ll i = 1; i <= n; i++) {\n\n            ll l; cin >> l;\n\n            events.pb({l, 0});\n\n        }\n\n\n\n        for (ll i = 1; i <= n; i++) {\n\n            ll r; cin >> r;\n\n            events.pb({r, 1});\n\n        }\n\n\n\n        for (ll i = 1; i <= n; i++) cin >> c[i];\n\n\n\n        sort(events.begin(), events.end());\n\n        sort(c.begin() + 1, c.end());\n\n\n\n        vector<ll> st;\n\n        vector<ll> lengths = {0};\n\n        for (auto [pos, type] : events) {\n\n            if (type == 0) {\n\n                st.pb(pos);\n\n            } else {\n\n                assert(!st.empty());\n\n                lengths.pb(pos - st.back());\n\n                st.pop_back();\n\n            }\n\n        }\n\n\n\n        sort(lengths.begin() + 1, lengths.end());\n\n        reverse(lengths.begin() + 1, lengths.end());\n\n\n\n        ll ans = 0;\n\n        for (ll i = 1; i <= n; i++) ans += lengths[i] * c[i];\n\n\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dsu",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1909",
    "index": "D",
    "title": "Split Plus K",
    "statement": "\\begin{quote}\neliteLAQ - Desert Ruins\n\\hfill ⠀\n\\end{quote}\n\nThere are $n$ positive integers $a_1, a_2, \\dots, a_n$ on a blackboard. You are also given a positive integer $k$. You can perform the following operation some (possibly $0$) times:\n\n- choose a number $x$ on the blackboard;\n- erase one occurrence of $x$;\n- write two \\textbf{positive} integers $y$, $z$ such that $y+z = x+k$ on the blackboard.\n\nIs it possible to make all the numbers on the blackboard equal? If yes, what is the minimum number of operations you need?",
    "tutorial": "Solve the problem with $k = 0$. Solve the problem with generic $k$. When is the answer $-1$? Do you notice any similarities between the cases with $k = 0$ and with generic $k$? Consider the \"shifted\" problem, where each $x$ on the blackboard (at any moment) is replaced with $x' = x-k$. Now, the operation becomes \"replace $x$ with $y+z$ such that $y+z = x+k \\implies (y'+k)+(z'+k) = (x'+k)+k \\implies y'+z' = x'$\". Therefore, in the shifted problem, $k' = 0$. Now you can replace every $a'_i := a_i - k$ with any number of values with sum $a'_i$, and the answer is the amount of numbers on the blackboard at the end, minus $n$. If we want to make all the values equal to $m'$, it must be a divisor of every $a'_i$. If all the $a'_i$ are positive, it is optimal to choose $m' = \\gcd a'_i$. If all the $a'_i$ are zero, the answer is $0$. If all the $a'_i$ are negative, it is optimal to choose $m' = -\\gcd -a'_i$. Otherwise, the answer is $-1$. Alternative way to get this result: You have to split each $a_i$ into $p_i$ pieces equal to $m$, and their sum must be equal to $a_i + k(p_i - 1) = (a_i - k) + kp_i = mp_i$. Then, $(a_i - k) = (m - k)p_i$, so $m' = m-k$ must be a divisor of every $a'_i = a_i - k$. In both the positive and the negative case, you will only write positive elements (in the original setup), as wanted. If all the $a'_i$ are positive, the numbers you will write on the shifted blackboard are positive, so they will be positive also in the original blackboard. If all the $a'_i$ are negative, the numbers you will write on the shifted blackboard are greater than the numbers you will erase, so they will be greater than the numbers in input (and positive) in the original blackboard. Complexity: $O(n + \\log(\\max a_i))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n, k; cin >> n >> k;\n\n        vector<ll> a(n + 1, 0);\n\n        ll tot = 0, pos = 0, zero = 0, neg = 0;\n\n        for (ll i = 1; i <= n; i++) {\n\n            cin >> a[i]; a[i] -= k; tot += a[i];\n\n            if (a[i] > 0) pos = 1;\n\n            else if (a[i] == 0) zero = 1;\n\n            else neg = 1;\n\n        }\n\n\n\n        if (pos + zero + neg >= 2) {\n\n            cout << -1 << nl; continue;\n\n        }\n\n\n\n        if (zero == 1) {\n\n            cout << 0 << nl; continue;\n\n        }\n\n\n\n        ll g = 0;\n\n        for (ll i = 1; i <= n; i++) g = __gcd(g, abs(a[i]));\n\n\n\n        ll ans = abs(tot) / g - n;\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1909",
    "index": "E",
    "title": "Multiple Lamps",
    "statement": "\\begin{quote}\nKid2Will - Fire Aura\n\\hfill ⠀\n\\end{quote}\n\nYou have $n$ lamps, numbered from $1$ to $n$. Initially, all the lamps are turned off.\n\nYou also have $n$ buttons. The $i$-th button toggles all the lamps whose index is a multiple of $i$. When a lamp is toggled, if it was off it turns on, and if it was on it turns off.\n\nYou have to press some buttons according to the following rules.\n\n- You have to press at least one button.\n- You cannot press the same button multiple times.\n- You are given $m$ pairs $(u_i, v_i)$. If you press the button $u_i$, you also have to press the button $v_i$ (at any moment, not necessarily after pressing the button $u_i$). Note that, if you press the button $v_i$, you don't need to press the button $u_i$.\n\nYou don't want to waste too much electricity. Find a way to press buttons such that at the end at most $\\lfloor n/5 \\rfloor$ lamps are on, or print $-1$ if it is impossible.",
    "tutorial": "Find a strategy that turns \"few\" lamps on in most cases. Pressing all the buttons turns $\\lfloor \\sqrt n \\rfloor$ lamps on. If the strategy in Hint 2 does not work, at most $3$ lamps must be on at the end. Iterate over all subsets of at most $3$ lamps that must be on at the end. If you press all the buttons, lamp $i$ is toggled by all the divisors of $i$, so it will be on if $i$ has an odd number of divisors, i.e., if $i$ is a perfect square. Then, the strategy of pressing all the buttons works if $\\lfloor \\sqrt n \\rfloor \\leq \\lfloor n/5 \\rfloor$, which is true for $n \\geq 20$. If $n \\leq 19$, at most $\\lfloor 19/5 \\rfloor = 3$ lamps must be turned on at the end. If you know which lamps must be turned on at the end, you can iterate over the buttons from $1$ to $n$ and press button $i$ if and only if lamp $i$ is in the wrong state. So you can iterate over all subsets of at most $3$ lamps, and check if the corresponding choice of buttons is valid (i.e., the $m$ constraints hold). You can remove a $\\log n$ factor by precalculating the choice of buttons for all small subsets before running the testcases. Complexity for each test: $O(\\sum n + (\\sum m \\cdot k^{2k-4}))$ (if $\\lfloor n/k \\rfloor$ lamps must be on; in this case, $k = 5$).",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n#define DEN 5\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n, m; cin >> n >> m;\n\n        vector<vector<ll>> adj_on(n + 1), adj_off(n + 1);\n\n        for (ll i = 1; i <= m; i++) {\n\n            ll a, b; cin >> a >> b;\n\n            if (a > b) adj_on[a].pb(b);\n\n            else adj_off[b].pb(a);\n\n        }\n\n\n\n        if (n >= 20) {\n\n            cout << n << nl;\n\n            for (ll i = 1; i <= n; i++) cout << i << ' ';\n\n            cout << nl;\n\n            continue;\n\n        }\n\n\n\n        ll ans = -1, sol_count = 0;\n\n        auto solve = [&](ll lamps_target) {\n\n            ll lamps = 0, buttons = 0, flag = 1;\n\n            for (ll i = 1; i <= n; i++) {\n\n                if (((lamps ^ lamps_target) >> i) & 1) {\n\n                    buttons ^= (1 << i);\n\n                    for (ll j = i; j <= n; j += i) lamps ^= (1 << j);\n\n                }\n\n\n\n                if ((buttons >> i) & 1) {\n\n                    for (auto j : adj_on[i]) {\n\n                        if (((buttons >> j) & 1) == 0) flag = 0;\n\n                    }\n\n                } else {\n\n                    for (auto j : adj_off[i]) {\n\n                        if ((buttons >> j) & 1) flag = 0;\n\n                    }\n\n                }\n\n            }\n\n\n\n            if (flag == 0) return;\n\n            if (buttons == 0) return;\n\n            if (__builtin_popcount(lamps_target) > n / 5) return;\n\n            ans = buttons; sol_count++;\n\n        };\n\n\n\n        for (ll i = 1; i <= n; i++) {\n\n            solve((1 << i));\n\n            for (ll j = i + 1; j <= n; j++) {\n\n                solve((1 << i) + (1 << j));\n\n                for (ll k = j + 1; k <= n; k++) {\n\n                    solve((1 << i) + (1 << j) + (1 << k));\n\n                }\n\n            }\n\n        }\n\n\n\n        // cout << sol_count << nl;\n\n        if (ans == -1) {\n\n            cout << -1 << nl;\n\n        } else {\n\n            cout << __builtin_popcountll(ans) << nl;\n\n            for (ll i = 1; i <= n; i++) {\n\n                if ((ans >> i) & 1) cout << i << ' ';\n\n            }\n\n            cout << nl;\n\n        }\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1909",
    "index": "F2",
    "title": "Small Permutation Problem (Hard Version)",
    "statement": "\\begin{quote}\nAndy Tunstall - MiniBoss\n\\hfill ⠀\n\\end{quote}\n\n\\textbf{In the easy version, the $a_i$ are in the range $[0, n]$; in the hard version, the $a_i$ are in the range $[-1, n]$ and the definition of good permutation is slightly different. You can make hacks only if all versions of the problem are solved.}\n\nYou are given an integer $n$ and an array $a_1, a_2, \\dots, a_n$ of integers in the range $[-1, n]$.\n\nA permutation $p_1, p_2, \\dots, p_n$ of $[1, 2, \\dots, n]$ is good if, for each $i$, the following condition is true:\n\n- if $a_i \\neq -1$, the number of values $\\leq i$ in $[p_1, p_2, \\dots, p_i]$ is exactly $a_i$.\n\nCount the good permutations of $[1, 2, \\dots, n]$, modulo $998\\,244\\,353$.",
    "tutorial": "Find a clean way to visualize the problem. Draw a $n \\times n$ grid, with tokens in $(i, p_i)$. Which constraints on the tokens do you have? You have some \"L\" shapes, and each of them must contain a fixed number of tokens (in 1909F1 - Small Permutation Problem (Easy Version) the shapes are $1$ cell wide and must contain at most $2$ tokens). Iterate over the shapes in increasing order of $i$. Split each shape into $2$ rectangles and iterate over the number of tokens in the first rectangle. Draw a $n \\times n$ grid, with tokens in $(i, p_i)$. Consider any $a_i \\neq -1$ and the nearest $a_j \\neq -1$ on the left (if it does not exist, let's set $j = a_j = 0$). Then, there must be $a_i$ tokens in the subgrid $[1, i] \\times [1, i]$. We can suppose we have already inserted the $a_j$ tokens in $[1, j] \\times [1, j]$, and we have to insert $a_i - a_j$ tokens in the remaining cells of $[1, i] \\times [1, i]$ (they make an \"L\" shape). WLOG, the $a_j$ tokens in $[1, j] \\times [1, j]$ are in the cells $(1, 1), \\dots, (a_j, a_j)$. Then, we can put tokens in the blue cells in the picture. The blue shape can be further split into these two rectangles: Iterate over $k$, the number of tokens in the first rectangle ($0 \\leq k \\leq a_i - a_j$). Then, you have to insert $k$ tokens into a $h_1 \\times w_1$ rectangle, and the remaining $a_i - a_j - k$ tokens into a $h_2 \\times (w_2 - k)$ rectangle. The number of ways to insert $k$ tokens into a $h \\times w$ rectangle is equal to the product of the number of ways to choose $k$ rows, the number of ways to choose $k$ columns, and the number of ways to fill the resulting $k \\times k$ subgrid: the result is $\\binom{h}{k} \\binom{w}{k} k!$. $a_n = n$ automatically (if $a_n \\neq n$ and $a_n \\neq -1$, the answer is $0$). If the non-negative $a_i$ are non-decreasing, the sum of the $a_i - a_j + 1$ (i.e., the $k$ over which you have to iterate) is $O(n)$, so the algorithm is efficient enough. Otherwise, the answer is $0$. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 200010\n\n\n\nll fc[maxn], nv[maxn];\n\n\n\nll fxp(ll b, ll e) {\n\n    ll r = 1, k = b;\n\n    while (e != 0) {\n\n        if (e % 2) r = (r * k) % mod;\n\n        k = (k * k) % mod; e /= 2;\n\n    }\n\n    return r;\n\n}\n\n\n\nll inv(ll x) {\n\n    return fxp(x, mod - 2);\n\n}\n\n\n\nll bnm(ll a, ll b) {\n\n    if (a < b || b < 0) return 0;\n\n    ll r = (fc[a] * nv[b]) % mod;\n\n    r = (r * nv[a - b]) % mod;\n\n    return r;\n\n}\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    fc[0] = 1; nv[0] = 1;\n\n    for (ll i = 1; i < maxn; i++) {\n\n        fc[i] = (i * fc[i - 1]) % mod; nv[i] = inv(fc[i]);\n\n    }\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<ll> a(n + 1, 0);\n\n        for (ll i = 1; i <= n; i++) {\n\n            cin >> a[i];\n\n        }\n\n\n\n        if (a[n] != -1 && a[n] != n) {\n\n            cout << 0 << nl; continue;\n\n        }\n\n        a[n] = n;\n\n\n\n        auto fill_rect = [&](ll h, ll w, ll x) {\n\n            ll ans = bnm(h, x) * bnm(w, x) % mod * fc[x] % mod;\n\n            return ans;\n\n        };\n\n\n\n        ll ans = 1;\n\n        ll curr_side = 0, curr_inserted = 0;\n\n        for (ll i = 1; i <= n; i++) {\n\n            if (a[i] == -1) continue;\n\n            ll to_insert = a[i] - curr_inserted;\n\n            ll up_h = curr_side - curr_inserted;\n\n            ll up_w = i - curr_side;\n\n            ll down_h = up_w;\n\n            ll down_w = i - curr_inserted;\n\n\n\n            if (to_insert < 0) {\n\n                ans = 0; break;\n\n            }\n\n\n\n            ll partial = 0;\n\n            for (ll j = 0; j <= to_insert; j++) {\n\n                partial = (partial +\n\n                    fill_rect(up_h, up_w, j) *\n\n                    fill_rect(down_h, down_w - j, to_insert - j) % mod) % mod;\n\n            }\n\n\n\n            ans = (ans * partial) % mod;\n\n\n\n            curr_side = i; curr_inserted = a[i];\n\n        }\n\n\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1909",
    "index": "G",
    "title": "Pumping Lemma",
    "statement": "\\begin{quote}\nTanchiky & Siromaru - Crystal Gravity\n\\hfill ⠀\n\\end{quote}\n\nYou are given two strings $s$, $t$ of length $n$, $m$, respectively. Both strings consist of lowercase letters of the English alphabet.\n\nCount the triples $(x, y, z)$ of strings such that the following conditions are true:\n\n- $s = x+y+z$ (the symbol $+$ represents the concatenation);\n- $t = x+\\underbrace{ y+\\dots+y }_{k \\text{ times}} + z$ for some integer $k$.",
    "tutorial": "If you remove the condition $s = x+y+z$, the problem becomes harder. Solve for a fixed $|y|$ (length of $y$). Suppose you have found a valid $y$. Shift it one position to the right. When is it still valid? The valid $y$ with $|y| = l$ start in consecutive positions. Using the same idea of the proof of Hint 4, you can find all the valid $y$. Let's use $s[l, r]$ to indicate the substring $[l, r]$ of $s$. Let's use $(a, b)$ to indicate the triple of strings $(s[1, a], s[a+1, b], s[b+1, n])$. Suppose $(a, b)$ is valid. Then, $(a+1, b+1)$ is valid if and only if $s_{b+1} = t_{b+1}$. If $(a, b)$ is valid, $s[1, b] = t[1, b]$; so if $s_b \\neq t_b$, $(a+k, b+k)$ is invalid for $k \\geq 0$. Therefore, if $(a, b)$ is the first valid pair with $b-a=l$ (i.e., with $|y| = l$), and $k$ is the smallest positive integer such that $(a+k, b+k)$ is invalid, then $s_{b+k} \\neq t_{b+k}$, so the only valid pairs with $|y| = l$ are the $(a+j, b+j)$ with $0 \\leq j < k$ (i.e., the valid $y$ with $|y| = l$ start in consecutive positions). Now let's find all the valid $y$ with $|y| = l$. Suppose $(a, b)$ is valid, and $c$ is the minimum index such that $s_c \\neq t_c$. Then, $b < c$, and $(a+k, b+k)$ is valid for all $b \\leq b+k < c$. Similarly, if $d$ is the minimum integer such that $s_{n-d} \\neq t_{m-d}$, $(a+k, b+k)$ is valid for all $n-d < a+k \\leq a \\implies n-d+l < b+k \\leq b$. Therefore, it's enough to check only one pair for each length, with $b$ in $[n-d+l+1, c-1]$ (because either all these pairs are valid or they are all invalid). This is possible by precomputing the rolling hash of the two strings. Alternatively, you can use z-function. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll N, M; cin >> N >> M;\n\n    string S, T; cin >> S >> T;\n\n\n\n    const ll p = 31;\n\n    const ll m[2] = {(ll)1e9 + 7, (ll)1e9 + 9};\n\n    vector<array<ll, 2>> p_pow(M + 1, {1, 1});\n\n    for (ll i = 0; i < M; i++) {\n\n        for (ll j = 0; j < 2; j++) {\n\n            p_pow[i + 1][j] = (p_pow[i][j] * p) % m[j];\n\n        }\n\n    }\n\n\n\n    auto compute_hash = [&](string s) {\n\n        ll n = s.size();\n\n        vector<array<ll, 2>> hash_value((ll)s.size() + 1, {0, 0});\n\n        for (ll i = 0; i < n; i++) {\n\n            char c = s[i];\n\n            for (ll j = 0; j < 2; j++) {\n\n                hash_value[i + 1][j] = (hash_value[i][j] +\n\n                    (c - 'a' + 1) * p_pow[i][j]) % m[j];\n\n            }\n\n        }\n\n        return hash_value;\n\n    };\n\n\n\n    vector<array<ll, 2>> s_hash = compute_hash(S);\n\n    vector<array<ll, 2>> t_hash = compute_hash(T);\n\n\n\n    auto calc = [&](ll type, ll l, ll r) {\n\n        array<ll, 2> ans = {0, 0};\n\n        vector<array<ll, 2>> *hash;\n\n        if (type == 0) hash = &s_hash;\n\n        else hash = &t_hash;\n\n        for (ll j = 0; j < 2; j++) {\n\n            ans[j] = ((*hash)[r + 1][j] - (*hash)[l][j] + m[j]) % m[j];\n\n            ans[j] = (p_pow[M - l][j] * ans[j]) % m[j];\n\n        }\n\n\n\n        return ans;\n\n    };\n\n\n\n    auto compare = [&](ll t0, ll l0, ll r0, ll t1, ll l1, ll r1) {\n\n        assert(r0 - l0 == r1 - l1);\n\n        return calc(t0, l0, r0) == calc(t1, l1, r1);\n\n    };\n\n\n\n    ll diff = N;\n\n    for (ll i = 0; i < N; i++) {\n\n        if (S[i] != T[i]) {\n\n            diff = i; break;\n\n        }\n\n    }\n\n\n\n    ll diff_alt = -1;\n\n    for (ll i = N - 1; i >= 0; i--) {\n\n        if (S[i] != T[i + (M - N)]) {\n\n            diff_alt = i; break;\n\n        }\n\n    }\n\n\n\n    ll ans = 0;\n\n    for (ll yl = 1; yl <= M; yl++) {\n\n        if ((M - N) % yl != 0) continue;\n\n\n\n        auto check = [&](ll xl) {\n\n            ll zl = N - xl - yl;\n\n            if (zl < 0) return false;\n\n            ll ykl = M - xl - zl;\n\n            if (!compare(0, 0, xl - 1, 1, 0, xl - 1)) return false;\n\n            if (!compare(0, N - zl, N - 1, 1, M - zl, M - 1)) return false;\n\n            if (!compare(0, xl, xl + yl - 1, 1, xl, xl + yl - 1)) return false;\n\n            if (!compare(1, xl, xl + ykl - yl - 1,\n\n                1, xl + yl, xl + ykl - 1)) return false;\n\n            return true;\n\n        };\n\n\n\n        if (check(diff_alt + 1)) {\n\n            ans += max((ll)0, diff - diff_alt - yl);\n\n        }\n\n    }\n\n\n\n    cout << ans << nl;\n\n\n\n    return 0;\n\n}",
    "tags": [
      "hashing",
      "strings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1909",
    "index": "H",
    "title": "Parallel Swaps Sort",
    "statement": "\\begin{quote}\nDubmood - Keygen 8\n\\hfill ⠀\n\\end{quote}\n\nYou are given a permutation $p_1, p_2, \\dots, p_n$ of $[1, 2, \\dots, n]$. You can perform the following operation some (possibly $0$) times:\n\n- choose a subarray $[l, r]$ of even length;\n- swap $a_l$, $a_{l+1}$;\n- swap $a_{l+2}$, $a_{l+3}$ (if $l+3 \\leq r$);\n- $\\dots$\n- swap $a_{r-1}$, $a_r$.\n\nSort the permutation in at most $10^6$ operations. You do not need to minimize the number of operations.",
    "tutorial": "Find a strategy which is as simple and \"easy to handle\" as possible. Only perform operations such that all swapped pairs have $a_i > a_{i+1}$. Let's call such subarrays \"swappable\". First, for each $i$ from left to right, do the operation on $[j, i]$, where $j$ is the minimum index such that $[j, i]$ is swappable. Repeat the same algorithm from right to left. After Hints 3 and 4, the array is sorted. Prove it (it will be useful). Assign $\\texttt{B}$ to the indices $i$ such that $a_i < a_{i-1}$ and $\\texttt{A}$ to the other indices. During the process in Hint 3, after the operation on index $i$, which properties do $\\texttt{A}$, $\\texttt{B}$ have in the prefix $[1, i]$? Answer to Hint 6: the values of type $\\texttt{A}$ are increasing; there are no two consecutive elements of type $\\texttt{B}$. The rest of the proof (i.e., what happens during the process in Hint 4) is relatively easy. Now let's find an efficient implementation. We have to use the properties in Hint 7. You have to find the longest $\\texttt{AB} \\dots \\texttt{AB}$ ending in position $i$, and perform the operation on it. What happens during the operation? $\\texttt{A}$ will always remain $\\texttt{A}$. For each $\\texttt{B}$, you have to detect when it becomes $\\texttt{A}$. For each $\\texttt{B}$, you can precompute the number of moves needed to make it $\\texttt{A}$. For example, you can use a segment tree with the following information: the type of each element, the positions of the elements of type $\\texttt{B}$, and the number of moves required for each $\\texttt{B}$ to become $\\texttt{A}$. Let's only perform operations such that all swapped pairs have $a_i > a_{i+1}$. Let's call such subarrays \"swappable\". First, for each $i$ from left to right, do the operation on $[j, i]$, where $j$ is the minimum index such that $[j, i]$ is swappable (let's call it \"operation $1.i$\"). Then, for each $i$ from right to left, do the operation on $[j, i]$, where $j$ is the minimum index such that $[j, i]$ is swappable (let's call it \"operation $2.i$\"). After these operations, the array is sorted. Let's prove it. Assign $\\texttt{B}$ to the indices $i$ such that $a_i < a_{i-1}$ and $\\texttt{A}$ to the other indices. After operation $1.i$, only assign letters in the prefix $[1, i]$ and ignore the other elements. During the operations $2.i$, assign letters to all the elements. Most of the following proofs are by induction. After the operation $1.i$ (supposing the properties were true after the operation $1.(i-1)$): An element of type $\\texttt{A}$ will always remain of type $\\texttt{A}$. Proof: the only elements of type $\\texttt{A}$ whose previous element changes are the ones in the subarray $[j, i]$, which are swapped with a smaller element of type $\\texttt{B}$. There are no two consecutive elements of type $\\texttt{B}$. Proof: if you swap $[j, i]$, $p_{j-1}$ (if it exists) must be of type $\\texttt{A}$ (otherwise $[j-2, i]$ is swappable). The elements of type $\\texttt{A}$ are increasing. Proof: it's true if no $\\texttt{B}s$ become $\\texttt{A}s$, and it's also true if some $\\texttt{B}s$ become $\\texttt{A}s$ because any of them is adjacent to two $\\texttt{A}s$. After the operation $2.i$: The three properties above are still true. The suffix $[i, n]$ contains the values in $[i, n]$ in order. Proof: $a_i$ is an $\\texttt{A}$, so it must be the largest $p_i$ in $[1, i]$, which is $i$. Now let's understand how we can implement the algorithm. Example implementation: We maintain a segment tree. The $i$-th position of the segment tree contains information about the element which was initially $p_i$. Note that the relative position of $\\texttt{B}s$ never changes: for example, if you want information about the last $k$ $\\texttt{B}s$ in the current permutation, and you search them in the segment tree, you will find exactly the last $k$ $\\texttt{B}s$, even though their indices will not correspond to the current indices. We have to find the longest swappable subarray ending at $i$. It means we need the current positions of the $\\texttt{B}s$. For each $\\texttt{B}$ maintain the current position, and assume the position of all the $\\texttt{A}s$ is $0$. Also maintain, for each element, if it is a $\\texttt{B}$ or not. Note that the $\\texttt{B}s$ that are affected by each operation can be found in a suffix of the segment tree. In this way, finding the longest swappable subarray can be done with a binary search on the segment tree: since $\\texttt{B}s$ cannot be consecutive, you have to find the longest suffix such that the sum of the positions of the $\\texttt{B}s$ is the maximum possible (i.e., if there are $k$ $\\texttt{B}s$ and the last of them is in position $i$, the sum of their positions must be $k(i-k+1)$). After finding the longest subarray in the segment tree, you have to perform the operation on it, i.e., subtract $1$ from all the nonzero positions. Some $\\texttt{B}s$ may become $\\texttt{A}s$. How to detect them? Since $\\texttt{A}s$ never become $\\texttt{B}s$, a $\\texttt{B}$ becomes $\\texttt{A}$ after it is swapped with all the elements greater than it on its left. So you can precompute the number of swaps that every $\\texttt{B}$ needs to become $\\texttt{A}$, and put it in the segment tree as well. Again, the operation is \"subtract $1$ from a range\". Detecting $\\texttt{A}s$ means detecting elements which need $0$ swaps to become $\\texttt{A}s$. You can find them after each operation by traversing the segment tree (which must support \"range min\" on the number of swaps needed), and set their position to $0$ and the number of swaps needed to $\\infty$. Complexity: $2n-3$ moves, $O(n \\log n)$ time.",
    "code": "#include <bits/stdc++.h>\n\n#include <ext/pb_ds/assoc_container.hpp>\n\n\n\n#include <algorithm>\n\n#include <cassert>\n\n#include <functional>\n\n#include <vector>\n\n\n\n\n\n#ifdef _MSC_VER\n\n#include <intrin.h>\n\n#endif\n\n\n\n#if __cplusplus >= 202002L\n\n#include <bit>\n\n#endif\n\n\n\nnamespace atcoder {\n\n\n\nnamespace internal {\n\n\n\n#if __cplusplus >= 202002L\n\n\n\nusing std::bit_ceil;\n\n\n\n#else\n\n\n\nunsigned int bit_ceil(unsigned int n) {\n\n    unsigned int x = 1;\n\n    while (x < (unsigned int)(n)) x *= 2;\n\n    return x;\n\n}\n\n\n\n#endif\n\n\n\nint countr_zero(unsigned int n) {\n\n#ifdef _MSC_VER\n\n    unsigned long index;\n\n    _BitScanForward(&index, n);\n\n    return index;\n\n#else\n\n    return __builtin_ctz(n);\n\n#endif\n\n}\n\n\n\nconstexpr int countr_zero_constexpr(unsigned int n) {\n\n    int x = 0;\n\n    while (!(n & (1 << x))) x++;\n\n    return x;\n\n}\n\n\n\n}  // namespace internal\n\n\n\n}  // namespace atcoder\n\n\n\n\n\nnamespace atcoder {\n\n\n\n#if __cplusplus >= 201703L\n\n\n\ntemplate <class S,\n\n          auto op,\n\n          auto e,\n\n          class F,\n\n          auto mapping,\n\n          auto composition,\n\n          auto id>\n\nstruct lazy_segtree {\n\n    static_assert(std::is_convertible_v<decltype(op), std::function<S(S, S)>>,\n\n                  \"op must work as S(S, S)\");\n\n    static_assert(std::is_convertible_v<decltype(e), std::function<S()>>,\n\n                  \"e must work as S()\");\n\n    static_assert(\n\n        std::is_convertible_v<decltype(mapping), std::function<S(F, S)>>,\n\n        \"mapping must work as F(F, S)\");\n\n    static_assert(\n\n        std::is_convertible_v<decltype(composition), std::function<F(F, F)>>,\n\n        \"compostiion must work as F(F, F)\");\n\n    static_assert(std::is_convertible_v<decltype(id), std::function<F()>>,\n\n                  \"id must work as F()\");\n\n\n\n#else\n\n\n\ntemplate <class S,\n\n          S (*op)(S, S),\n\n          S (*e)(),\n\n          class F,\n\n          S (*mapping)(F, S),\n\n          F (*composition)(F, F),\n\n          F (*id)()>\n\nstruct lazy_segtree {\n\n\n\n#endif\n\n\n\n  public:\n\n    lazy_segtree() : lazy_segtree(0) {}\n\n    explicit lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}\n\n    explicit lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) {\n\n        size = (int)internal::bit_ceil((unsigned int)(_n));\n\n        log = internal::countr_zero((unsigned int)size);\n\n        d = std::vector<S>(2 * size, e());\n\n        lz = std::vector<F>(size, id());\n\n        for (int i = 0; i < _n; i++) d[size + i] = v[i];\n\n        for (int i = size - 1; i >= 1; i--) {\n\n            update(i);\n\n        }\n\n    }\n\n\n\n    void set(int p, S x) {\n\n        assert(0 <= p && p < _n);\n\n        p += size;\n\n        for (int i = log; i >= 1; i--) push(p >> i);\n\n        d[p] = x;\n\n        for (int i = 1; i <= log; i++) update(p >> i);\n\n    }\n\n\n\n    S get(int p) {\n\n        assert(0 <= p && p < _n);\n\n        p += size;\n\n        for (int i = log; i >= 1; i--) push(p >> i);\n\n        return d[p];\n\n    }\n\n\n\n    S prod(int l, int r) {\n\n        assert(0 <= l && l <= r && r <= _n);\n\n        if (l == r) return e();\n\n\n\n        l += size;\n\n        r += size;\n\n\n\n        for (int i = log; i >= 1; i--) {\n\n            if (((l >> i) << i) != l) push(l >> i);\n\n            if (((r >> i) << i) != r) push((r - 1) >> i);\n\n        }\n\n\n\n        S sml = e(), smr = e();\n\n        while (l < r) {\n\n            if (l & 1) sml = op(sml, d[l++]);\n\n            if (r & 1) smr = op(d[--r], smr);\n\n            l >>= 1;\n\n            r >>= 1;\n\n        }\n\n\n\n        return op(sml, smr);\n\n    }\n\n\n\n    S all_prod() { return d[1]; }\n\n\n\n    void apply(int p, F f) {\n\n        assert(0 <= p && p < _n);\n\n        p += size;\n\n        for (int i = log; i >= 1; i--) push(p >> i);\n\n        d[p] = mapping(f, d[p]);\n\n        for (int i = 1; i <= log; i++) update(p >> i);\n\n    }\n\n    void apply(int l, int r, F f) {\n\n        assert(0 <= l && l <= r && r <= _n);\n\n        if (l == r) return;\n\n\n\n        l += size;\n\n        r += size;\n\n\n\n        for (int i = log; i >= 1; i--) {\n\n            if (((l >> i) << i) != l) push(l >> i);\n\n            if (((r >> i) << i) != r) push((r - 1) >> i);\n\n        }\n\n\n\n        {\n\n            int l2 = l, r2 = r;\n\n            while (l < r) {\n\n                if (l & 1) all_apply(l++, f);\n\n                if (r & 1) all_apply(--r, f);\n\n                l >>= 1;\n\n                r >>= 1;\n\n            }\n\n            l = l2;\n\n            r = r2;\n\n        }\n\n\n\n        for (int i = 1; i <= log; i++) {\n\n            if (((l >> i) << i) != l) update(l >> i);\n\n            if (((r >> i) << i) != r) update((r - 1) >> i);\n\n        }\n\n    }\n\n\n\n    template <bool (*g)(S)> int max_right(int l) {\n\n        return max_right(l, [](S x) { return g(x); });\n\n    }\n\n    template <class G> int max_right(int l, G g) {\n\n        assert(0 <= l && l <= _n);\n\n        assert(g(e()));\n\n        if (l == _n) return _n;\n\n        l += size;\n\n        for (int i = log; i >= 1; i--) push(l >> i);\n\n        S sm = e();\n\n        do {\n\n            while (l % 2 == 0) l >>= 1;\n\n            if (!g(op(sm, d[l]))) {\n\n                while (l < size) {\n\n                    push(l);\n\n                    l = (2 * l);\n\n                    if (g(op(sm, d[l]))) {\n\n                        sm = op(sm, d[l]);\n\n                        l++;\n\n                    }\n\n                }\n\n                return l - size;\n\n            }\n\n            sm = op(sm, d[l]);\n\n            l++;\n\n        } while ((l & -l) != l);\n\n        return _n;\n\n    }\n\n\n\n    template <bool (*g)(S)> int min_left(int r) {\n\n        return min_left(r, [](S x) { return g(x); });\n\n    }\n\n    template <class G> int min_left(int r, G g) {\n\n        assert(0 <= r && r <= _n);\n\n        assert(g(e()));\n\n        if (r == 0) return 0;\n\n        r += size;\n\n        for (int i = log; i >= 1; i--) push((r - 1) >> i);\n\n        S sm = e();\n\n        do {\n\n            r--;\n\n            while (r > 1 && (r % 2)) r >>= 1;\n\n            if (!g(op(d[r], sm))) {\n\n                while (r < size) {\n\n                    push(r);\n\n                    r = (2 * r + 1);\n\n                    if (g(op(d[r], sm))) {\n\n                        sm = op(d[r], sm);\n\n                        r--;\n\n                    }\n\n                }\n\n                return r + 1 - size;\n\n            }\n\n            sm = op(d[r], sm);\n\n        } while ((r & -r) != r);\n\n        return 0;\n\n    }\n\n\n\n  private:\n\n    int _n, size, log;\n\n    std::vector<S> d;\n\n    std::vector<F> lz;\n\n\n\n    void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }\n\n    void all_apply(int k, F f) {\n\n        d[k] = mapping(f, d[k]);\n\n        if (k < size) lz[k] = composition(f, lz[k]);\n\n    }\n\n    void push(int k) {\n\n        all_apply(2 * k, lz[k]);\n\n        all_apply(2 * k + 1, lz[k]);\n\n        lz[k] = id();\n\n    }\n\n};\n\n\n\n}  // namespace atcoder\n\n\n\nusing namespace std;\n\nusing namespace __gnu_pbds;\n\nusing namespace atcoder;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\ntypedef tree<ll, null_type, less<ll>, rb_tree_tag,\n\n    tree_order_statistics_node_update> indexed_set;\n\n\n\nstruct S {\n\n    ll sum_B, sum_pos, min_moves;\n\n};\n\n\n\nstruct F {\n\n    ll x, y, z;\n\n    bool rset;\n\n};\n\n\n\nS op(S l, S r) {\n\n    return S{l.sum_B + r.sum_B,\n\n        l.sum_pos + r.sum_pos,\n\n        min(l.min_moves, r.min_moves)};\n\n}\n\n\n\nS e() {\n\n    return S{0, 0, INF};\n\n}\n\n\n\nS mapping(F l, S r) {\n\n    ll a = r.sum_B, b = r.sum_pos, c = r.min_moves;\n\n\n\n    a += l.x;\n\n    if (l.rset) b = l.y;\n\n    else b += (l.y * (r.sum_B + l.x));\n\n    c += l.z;\n\n\n\n    return S{a, b, c};\n\n}\n\n\n\nF composition(F l, F r) {\n\n    ll x = r.x, y = r.y, z = r.z;\n\n    bool rset = r.rset;\n\n\n\n    x += l.x;\n\n    if (l.rset) y = l.y, rset = true;\n\n    else y += l.y;\n\n    z += l.z;\n\n\n\n    return F{x, y, z, rset};\n\n}\n\n\n\nF id() {\n\n    return F{0, 0, 0, false};\n\n}\n\n\n\nbool no_B(S u) {\n\n    return (u.sum_B == 0);\n\n}\n\n\n\nll last_pos = 0;\n\n\n\nbool swappable(S u) {\n\n    return (u.sum_pos == (u.sum_B * (last_pos - u.sum_B + 1)));\n\n}\n\n\n\nbool no_zeros(S u) {\n\n    return (u.min_moves != 0);\n\n}\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll n; cin >> n;\n\n    vector<ll> p(n + 1, 0);\n\n    for (ll i = 1; i <= n; i++) cin >> p[i];\n\n\n\n    lazy_segtree<S, op, e, F, mapping, composition, id> st(\n\n        vector<S>(n + 1, e())\n\n    );\n\n\n\n    auto find_zeros = [&]() {\n\n        while (true) {\n\n            ll pos = st.min_left<no_zeros>(n + 1);\n\n            if (pos == 0) break;\n\n            st.apply(pos - 1, pos, F{-1, 0, INF, true});\n\n        }\n\n    };\n\n\n\n    indexed_set pref;\n\n\n\n    vector<ll> req_moves(n + 1, 0);\n\n    for (ll i = 1; i <= n; i++) {\n\n        req_moves[i] = pref.order_of_key(-p[i]);\n\n        pref.insert(-p[i]);\n\n    }\n\n\n\n    vector<array<ll, 2>> ans;\n\n    auto process_longest = [&](ll st_r) {\n\n        last_pos = st.prod(st_r, st_r + 1).sum_pos;\n\n        ll st_l = st.min_left<swappable>(n + 1);\n\n        ll sum_B = st.prod(st_l, n + 1).sum_B;\n\n        ans.pb({last_pos - 2 * sum_B + 1, last_pos});\n\n        st.apply(st_l, st_r + 1, F{0, -1, -1, false});\n\n        find_zeros();\n\n    };\n\n\n\n    for (ll i = 1; i <= n; i++) {\n\n        if (req_moves[i] != 0) {\n\n            st.apply(i, i + 1, F{1, i, req_moves[i] - INF, false});\n\n            process_longest(i);\n\n        }\n\n    }\n\n\n\n    while (true) {\n\n        ll r = st.min_left<no_B>(n + 1);\n\n        if (r == 0) break;\n\n        process_longest(r - 1);\n\n    }\n\n\n\n    cout << ans.size() << nl;\n\n    for (auto [l, r] : ans) cout << l _ r << nl;\n\n\n\n    return 0;\n\n}",
    "tags": [
      "constructive algorithms",
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1909",
    "index": "I",
    "title": "Short Permutation Problem",
    "statement": "\\begin{quote}\nXomu - Last Dance\n\\hfill ⠀\n\\end{quote}\n\nYou are given an integer $n$.\n\nFor each $(m, k)$ such that $3 \\leq m \\leq n+1$ and $0 \\leq k \\leq n-1$, count the permutations of $[1, 2, ..., n]$ such that $p_i + p_{i+1} \\geq m$ for exactly $k$ indices $i$, modulo $998\\,244\\,353$.",
    "tutorial": "Insert the elements into the permutation in some comfortable order. Suppose $m$ is even. You can insert elements in the order $[m/2, m/2 - 1, m/2 + 1, m/2 - 2, \\dots]$. You can solve for a single $m$ with DP. Can you calculate the DP for multiple $m$ simultaneously? The first part of the DP (where you insert both \"small\" and \"big\" elements) is the same for each $m$ (but with a different length), and for the second part (where you only insert \"small\" elements) you don't need DP. The second part of the DP can be replaced with combinatorics formulas. Binomials are compatible with NTT. Let's solve for a single $m$. Suppose $m$ is even. Start from an empty array, and insert the elements in the order $[m/2, m/2 - 1, m/2 + 1, m/2 - 2, \\dots]$. At any moment, all the elements are concatenated, and you can insert new elements either at the beginning, at the end or between two existing elements. When you insert an element $\\geq m/2$, the sum with any of the previous inserted elements is $\\geq m$. Otherwise, the sum is $< m$. So you can calculate $dp_{i,j} =$ number of ways to insert the first $i$ elements (of $[m/2, m/2 - 1, m/2 + 1, m/2 - 2, \\dots]$) and make $j$ \"good\" pairs (with sum $\\geq m$). You can split the ordering $[m/2, m/2 - 1, m/2 + 1, m/2 - 2, \\dots]$ into two parts: small and big elements alternate; there are only small elements. For the second part, you don't need DP. Suppose you have already inserted $i$ elements, and there are $j$ good pairs, but when you will have inserted all elements you want $k$ good pairs. The number of ways to insert the remaining elements can be computed with combinatorics in $O(1)$ after precomputing factorials and inverses (you have to choose which pairs to break and use stars and bars; we skip exact formulas because they are relatively easy to find). If you rearrange the factorials correctly, you can get that all the answers for a fixed $m$ can be computed by multiplying two polynomials, one of which contains the $dp_{i,j}$, where $i$ is equal to the length of the \"alternating\" prefix. NTT is fast enough. Complexity: $O(n^2 \\log n)$",
    "code": "#include <algorithm>\n\n#include <array>\n\n#include <cassert>\n\n#include <type_traits>\n\n#include <vector>\n\n\n\n\n\n#ifdef _MSC_VER\n\n#include <intrin.h>\n\n#endif\n\n\n\n#if __cplusplus >= 202002L\n\n#include <bit>\n\n#endif\n\n\n\nnamespace atcoder {\n\n\n\nnamespace internal {\n\n\n\n#if __cplusplus >= 202002L\n\n\n\nusing std::bit_ceil;\n\n\n\n#else\n\n\n\nunsigned int bit_ceil(unsigned int n) {\n\n    unsigned int x = 1;\n\n    while (x < (unsigned int)(n)) x *= 2;\n\n    return x;\n\n}\n\n\n\n#endif\n\n\n\nint countr_zero(unsigned int n) {\n\n#ifdef _MSC_VER\n\n    unsigned long index;\n\n    _BitScanForward(&index, n);\n\n    return index;\n\n#else\n\n    return __builtin_ctz(n);\n\n#endif\n\n}\n\n\n\nconstexpr int countr_zero_constexpr(unsigned int n) {\n\n    int x = 0;\n\n    while (!(n & (1 << x))) x++;\n\n    return x;\n\n}\n\n\n\n}  // namespace internal\n\n\n\n}  // namespace atcoder\n\n\n\n\n\n#include <cassert>\n\n#include <numeric>\n\n#include <type_traits>\n\n\n\n#ifdef _MSC_VER\n\n#include <intrin.h>\n\n#endif\n\n\n\n\n\n#include <utility>\n\n\n\n#ifdef _MSC_VER\n\n#include <intrin.h>\n\n#endif\n\n\n\nnamespace atcoder {\n\n\n\nnamespace internal {\n\n\n\nconstexpr long long safe_mod(long long x, long long m) {\n\n    x %= m;\n\n    if (x < 0) x += m;\n\n    return x;\n\n}\n\n\n\nstruct barrett {\n\n    unsigned int _m;\n\n    unsigned long long im;\n\n\n\n    explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}\n\n\n\n    unsigned int umod() const { return _m; }\n\n\n\n    unsigned int mul(unsigned int a, unsigned int b) const {\n\n\n\n        unsigned long long z = a;\n\n        z *= b;\n\n#ifdef _MSC_VER\n\n        unsigned long long x;\n\n        _umul128(z, im, &x);\n\n#else\n\n        unsigned long long x =\n\n            (unsigned long long)(((unsigned __int128)(z)*im) >> 64);\n\n#endif\n\n        unsigned long long y = x * _m;\n\n        return (unsigned int)(z - y + (z < y ? _m : 0));\n\n    }\n\n};\n\n\n\nconstexpr long long pow_mod_constexpr(long long x, long long n, int m) {\n\n    if (m == 1) return 0;\n\n    unsigned int _m = (unsigned int)(m);\n\n    unsigned long long r = 1;\n\n    unsigned long long y = safe_mod(x, m);\n\n    while (n) {\n\n        if (n & 1) r = (r * y) % _m;\n\n        y = (y * y) % _m;\n\n        n >>= 1;\n\n    }\n\n    return r;\n\n}\n\n\n\nconstexpr bool is_prime_constexpr(int n) {\n\n    if (n <= 1) return false;\n\n    if (n == 2 || n == 7 || n == 61) return true;\n\n    if (n % 2 == 0) return false;\n\n    long long d = n - 1;\n\n    while (d % 2 == 0) d /= 2;\n\n    constexpr long long bases[3] = {2, 7, 61};\n\n    for (long long a : bases) {\n\n        long long t = d;\n\n        long long y = pow_mod_constexpr(a, t, n);\n\n        while (t != n - 1 && y != 1 && y != n - 1) {\n\n            y = y * y % n;\n\n            t <<= 1;\n\n        }\n\n        if (y != n - 1 && t % 2 == 0) {\n\n            return false;\n\n        }\n\n    }\n\n    return true;\n\n}\n\ntemplate <int n> constexpr bool is_prime = is_prime_constexpr(n);\n\n\n\nconstexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {\n\n    a = safe_mod(a, b);\n\n    if (a == 0) return {b, 0};\n\n\n\n    long long s = b, t = a;\n\n    long long m0 = 0, m1 = 1;\n\n\n\n    while (t) {\n\n        long long u = s / t;\n\n        s -= t * u;\n\n        m0 -= m1 * u;  // |m1 * u| <= |m1| * s <= b\n\n\n\n\n\n        auto tmp = s;\n\n        s = t;\n\n        t = tmp;\n\n        tmp = m0;\n\n        m0 = m1;\n\n        m1 = tmp;\n\n    }\n\n    if (m0 < 0) m0 += b / s;\n\n    return {s, m0};\n\n}\n\n\n\nconstexpr int primitive_root_constexpr(int m) {\n\n    if (m == 2) return 1;\n\n    if (m == 167772161) return 3;\n\n    if (m == 469762049) return 3;\n\n    if (m == 754974721) return 11;\n\n    if (m == 998244353) return 3;\n\n    int divs[20] = {};\n\n    divs[0] = 2;\n\n    int cnt = 1;\n\n    int x = (m - 1) / 2;\n\n    while (x % 2 == 0) x /= 2;\n\n    for (int i = 3; (long long)(i)*i <= x; i += 2) {\n\n        if (x % i == 0) {\n\n            divs[cnt++] = i;\n\n            while (x % i == 0) {\n\n                x /= i;\n\n            }\n\n        }\n\n    }\n\n    if (x > 1) {\n\n        divs[cnt++] = x;\n\n    }\n\n    for (int g = 2;; g++) {\n\n        bool ok = true;\n\n        for (int i = 0; i < cnt; i++) {\n\n            if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {\n\n                ok = false;\n\n                break;\n\n            }\n\n        }\n\n        if (ok) return g;\n\n    }\n\n}\n\ntemplate <int m> constexpr int primitive_root = primitive_root_constexpr(m);\n\n\n\nunsigned long long floor_sum_unsigned(unsigned long long n,\n\n                                      unsigned long long m,\n\n                                      unsigned long long a,\n\n                                      unsigned long long b) {\n\n    unsigned long long ans = 0;\n\n    while (true) {\n\n        if (a >= m) {\n\n            ans += n * (n - 1) / 2 * (a / m);\n\n            a %= m;\n\n        }\n\n        if (b >= m) {\n\n            ans += n * (b / m);\n\n            b %= m;\n\n        }\n\n\n\n        unsigned long long y_max = a * n + b;\n\n        if (y_max < m) break;\n\n        n = (unsigned long long)(y_max / m);\n\n        b = (unsigned long long)(y_max % m);\n\n        std::swap(m, a);\n\n    }\n\n    return ans;\n\n}\n\n\n\n}  // namespace internal\n\n\n\n}  // namespace atcoder\n\n\n\n\n\n#include <cassert>\n\n#include <numeric>\n\n#include <type_traits>\n\n\n\nnamespace atcoder {\n\n\n\nnamespace internal {\n\n\n\n#ifndef _MSC_VER\n\ntemplate <class T>\n\nusing is_signed_int128 =\n\n    typename std::conditional<std::is_same<T, __int128_t>::value ||\n\n                                  std::is_same<T, __int128>::value,\n\n                              std::true_type,\n\n                              std::false_type>::type;\n\n\n\ntemplate <class T>\n\nusing is_unsigned_int128 =\n\n    typename std::conditional<std::is_same<T, __uint128_t>::value ||\n\n                                  std::is_same<T, unsigned __int128>::value,\n\n                              std::true_type,\n\n                              std::false_type>::type;\n\n\n\ntemplate <class T>\n\nusing make_unsigned_int128 =\n\n    typename std::conditional<std::is_same<T, __int128_t>::value,\n\n                              __uint128_t,\n\n                              unsigned __int128>;\n\n\n\ntemplate <class T>\n\nusing is_integral = typename std::conditional<std::is_integral<T>::value ||\n\n                                                  is_signed_int128<T>::value ||\n\n                                                  is_unsigned_int128<T>::value,\n\n                                              std::true_type,\n\n                                              std::false_type>::type;\n\n\n\ntemplate <class T>\n\nusing is_signed_int = typename std::conditional<(is_integral<T>::value &&\n\n                                                 std::is_signed<T>::value) ||\n\n                                                    is_signed_int128<T>::value,\n\n                                                std::true_type,\n\n                                                std::false_type>::type;\n\n\n\ntemplate <class T>\n\nusing is_unsigned_int =\n\n    typename std::conditional<(is_integral<T>::value &&\n\n                               std::is_unsigned<T>::value) ||\n\n                                  is_unsigned_int128<T>::value,\n\n                              std::true_type,\n\n                              std::false_type>::type;\n\n\n\ntemplate <class T>\n\nusing to_unsigned = typename std::conditional<\n\n    is_signed_int128<T>::value,\n\n    make_unsigned_int128<T>,\n\n    typename std::conditional<std::is_signed<T>::value,\n\n                              std::make_unsigned<T>,\n\n                              std::common_type<T>>::type>::type;\n\n\n\n#else\n\n\n\ntemplate <class T> using is_integral = typename std::is_integral<T>;\n\n\n\ntemplate <class T>\n\nusing is_signed_int =\n\n    typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,\n\n                              std::true_type,\n\n                              std::false_type>::type;\n\n\n\ntemplate <class T>\n\nusing is_unsigned_int =\n\n    typename std::conditional<is_integral<T>::value &&\n\n                                  std::is_unsigned<T>::value,\n\n                              std::true_type,\n\n                              std::false_type>::type;\n\n\n\ntemplate <class T>\n\nusing to_unsigned = typename std::conditional<is_signed_int<T>::value,\n\n                                              std::make_unsigned<T>,\n\n                                              std::common_type<T>>::type;\n\n\n\n#endif\n\n\n\ntemplate <class T>\n\nusing is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;\n\n\n\ntemplate <class T>\n\nusing is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;\n\n\n\ntemplate <class T> using to_unsigned_t = typename to_unsigned<T>::type;\n\n\n\n}  // namespace internal\n\n\n\n}  // namespace atcoder\n\n\n\n\n\nnamespace atcoder {\n\n\n\nnamespace internal {\n\n\n\nstruct modint_base {};\n\nstruct static_modint_base : modint_base {};\n\n\n\ntemplate <class T> using is_modint = std::is_base_of<modint_base, T>;\n\ntemplate <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;\n\n\n\n}  // namespace internal\n\n\n\ntemplate <int m, std::enable_if_t<(1 <= m)>* = nullptr>\n\nstruct static_modint : internal::static_modint_base {\n\n    using mint = static_modint;\n\n\n\n  public:\n\n    static constexpr int mod() { return m; }\n\n    static mint raw(int v) {\n\n        mint x;\n\n        x._v = v;\n\n        return x;\n\n    }\n\n\n\n    static_modint() : _v(0) {}\n\n    template <class T, internal::is_signed_int_t<T>* = nullptr>\n\n    static_modint(T v) {\n\n        long long x = (long long)(v % (long long)(umod()));\n\n        if (x < 0) x += umod();\n\n        _v = (unsigned int)(x);\n\n    }\n\n    template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n\n    static_modint(T v) {\n\n        _v = (unsigned int)(v % umod());\n\n    }\n\n\n\n    unsigned int val() const { return _v; }\n\n\n\n    mint& operator++() {\n\n        _v++;\n\n        if (_v == umod()) _v = 0;\n\n        return *this;\n\n    }\n\n    mint& operator--() {\n\n        if (_v == 0) _v = umod();\n\n        _v--;\n\n        return *this;\n\n    }\n\n    mint operator++(int) {\n\n        mint result = *this;\n\n        ++*this;\n\n        return result;\n\n    }\n\n    mint operator--(int) {\n\n        mint result = *this;\n\n        --*this;\n\n        return result;\n\n    }\n\n\n\n    mint& operator+=(const mint& rhs) {\n\n        _v += rhs._v;\n\n        if (_v >= umod()) _v -= umod();\n\n        return *this;\n\n    }\n\n    mint& operator-=(const mint& rhs) {\n\n        _v -= rhs._v;\n\n        if (_v >= umod()) _v += umod();\n\n        return *this;\n\n    }\n\n    mint& operator*=(const mint& rhs) {\n\n        unsigned long long z = _v;\n\n        z *= rhs._v;\n\n        _v = (unsigned int)(z % umod());\n\n        return *this;\n\n    }\n\n    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n\n\n\n    mint operator+() const { return *this; }\n\n    mint operator-() const { return mint() - *this; }\n\n\n\n    mint pow(long long n) const {\n\n        assert(0 <= n);\n\n        mint x = *this, r = 1;\n\n        while (n) {\n\n            if (n & 1) r *= x;\n\n            x *= x;\n\n            n >>= 1;\n\n        }\n\n        return r;\n\n    }\n\n    mint inv() const {\n\n        if (prime) {\n\n            assert(_v);\n\n            return pow(umod() - 2);\n\n        } else {\n\n            auto eg = internal::inv_gcd(_v, m);\n\n            assert(eg.first == 1);\n\n            return eg.second;\n\n        }\n\n    }\n\n\n\n    friend mint operator+(const mint& lhs, const mint& rhs) {\n\n        return mint(lhs) += rhs;\n\n    }\n\n    friend mint operator-(const mint& lhs, const mint& rhs) {\n\n        return mint(lhs) -= rhs;\n\n    }\n\n    friend mint operator*(const mint& lhs, const mint& rhs) {\n\n        return mint(lhs) *= rhs;\n\n    }\n\n    friend mint operator/(const mint& lhs, const mint& rhs) {\n\n        return mint(lhs) /= rhs;\n\n    }\n\n    friend bool operator==(const mint& lhs, const mint& rhs) {\n\n        return lhs._v == rhs._v;\n\n    }\n\n    friend bool operator!=(const mint& lhs, const mint& rhs) {\n\n        return lhs._v != rhs._v;\n\n    }\n\n\n\n  private:\n\n    unsigned int _v;\n\n    static constexpr unsigned int umod() { return m; }\n\n    static constexpr bool prime = internal::is_prime<m>;\n\n};\n\n\n\ntemplate <int id> struct dynamic_modint : internal::modint_base {\n\n    using mint = dynamic_modint;\n\n\n\n  public:\n\n    static int mod() { return (int)(bt.umod()); }\n\n    static void set_mod(int m) {\n\n        assert(1 <= m);\n\n        bt = internal::barrett(m);\n\n    }\n\n    static mint raw(int v) {\n\n        mint x;\n\n        x._v = v;\n\n        return x;\n\n    }\n\n\n\n    dynamic_modint() : _v(0) {}\n\n    template <class T, internal::is_signed_int_t<T>* = nullptr>\n\n    dynamic_modint(T v) {\n\n        long long x = (long long)(v % (long long)(mod()));\n\n        if (x < 0) x += mod();\n\n        _v = (unsigned int)(x);\n\n    }\n\n    template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n\n    dynamic_modint(T v) {\n\n        _v = (unsigned int)(v % mod());\n\n    }\n\n\n\n    unsigned int val() const { return _v; }\n\n\n\n    mint& operator++() {\n\n        _v++;\n\n        if (_v == umod()) _v = 0;\n\n        return *this;\n\n    }\n\n    mint& operator--() {\n\n        if (_v == 0) _v = umod();\n\n        _v--;\n\n        return *this;\n\n    }\n\n    mint operator++(int) {\n\n        mint result = *this;\n\n        ++*this;\n\n        return result;\n\n    }\n\n    mint operator--(int) {\n\n        mint result = *this;\n\n        --*this;\n\n        return result;\n\n    }\n\n\n\n    mint& operator+=(const mint& rhs) {\n\n        _v += rhs._v;\n\n        if (_v >= umod()) _v -= umod();\n\n        return *this;\n\n    }\n\n    mint& operator-=(const mint& rhs) {\n\n        _v += mod() - rhs._v;\n\n        if (_v >= umod()) _v -= umod();\n\n        return *this;\n\n    }\n\n    mint& operator*=(const mint& rhs) {\n\n        _v = bt.mul(_v, rhs._v);\n\n        return *this;\n\n    }\n\n    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n\n\n\n    mint operator+() const { return *this; }\n\n    mint operator-() const { return mint() - *this; }\n\n\n\n    mint pow(long long n) const {\n\n        assert(0 <= n);\n\n        mint x = *this, r = 1;\n\n        while (n) {\n\n            if (n & 1) r *= x;\n\n            x *= x;\n\n            n >>= 1;\n\n        }\n\n        return r;\n\n    }\n\n    mint inv() const {\n\n        auto eg = internal::inv_gcd(_v, mod());\n\n        assert(eg.first == 1);\n\n        return eg.second;\n\n    }\n\n\n\n    friend mint operator+(const mint& lhs, const mint& rhs) {\n\n        return mint(lhs) += rhs;\n\n    }\n\n    friend mint operator-(const mint& lhs, const mint& rhs) {\n\n        return mint(lhs) -= rhs;\n\n    }\n\n    friend mint operator*(const mint& lhs, const mint& rhs) {\n\n        return mint(lhs) *= rhs;\n\n    }\n\n    friend mint operator/(const mint& lhs, const mint& rhs) {\n\n        return mint(lhs) /= rhs;\n\n    }\n\n    friend bool operator==(const mint& lhs, const mint& rhs) {\n\n        return lhs._v == rhs._v;\n\n    }\n\n    friend bool operator!=(const mint& lhs, const mint& rhs) {\n\n        return lhs._v != rhs._v;\n\n    }\n\n\n\n  private:\n\n    unsigned int _v;\n\n    static internal::barrett bt;\n\n    static unsigned int umod() { return bt.umod(); }\n\n};\n\ntemplate <int id> internal::barrett dynamic_modint<id>::bt(998244353);\n\n\n\nusing modint998244353 = static_modint<998244353>;\n\nusing modint1000000007 = static_modint<1000000007>;\n\nusing modint = dynamic_modint<-1>;\n\n\n\nnamespace internal {\n\n\n\ntemplate <class T>\n\nusing is_static_modint = std::is_base_of<internal::static_modint_base, T>;\n\n\n\ntemplate <class T>\n\nusing is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;\n\n\n\ntemplate <class> struct is_dynamic_modint : public std::false_type {};\n\ntemplate <int id>\n\nstruct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};\n\n\n\ntemplate <class T>\n\nusing is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;\n\n\n\n}  // namespace internal\n\n\n\n}  // namespace atcoder\n\n\n\n\n\nnamespace atcoder {\n\n\n\nnamespace internal {\n\n\n\ntemplate <class mint,\n\n          int g = internal::primitive_root<mint::mod()>,\n\n          internal::is_static_modint_t<mint>* = nullptr>\n\nstruct fft_info {\n\n    static constexpr int rank2 = countr_zero_constexpr(mint::mod() - 1);\n\n    std::array<mint, rank2 + 1> root;   // root[i]^(2^i) == 1\n\n    std::array<mint, rank2 + 1> iroot;  // root[i] * iroot[i] == 1\n\n\n\n    std::array<mint, std::max(0, rank2 - 2 + 1)> rate2;\n\n    std::array<mint, std::max(0, rank2 - 2 + 1)> irate2;\n\n\n\n    std::array<mint, std::max(0, rank2 - 3 + 1)> rate3;\n\n    std::array<mint, std::max(0, rank2 - 3 + 1)> irate3;\n\n\n\n    fft_info() {\n\n        root[rank2] = mint(g).pow((mint::mod() - 1) >> rank2);\n\n        iroot[rank2] = root[rank2].inv();\n\n        for (int i = rank2 - 1; i >= 0; i--) {\n\n            root[i] = root[i + 1] * root[i + 1];\n\n            iroot[i] = iroot[i + 1] * iroot[i + 1];\n\n        }\n\n\n\n        {\n\n            mint prod = 1, iprod = 1;\n\n            for (int i = 0; i <= rank2 - 2; i++) {\n\n                rate2[i] = root[i + 2] * prod;\n\n                irate2[i] = iroot[i + 2] * iprod;\n\n                prod *= iroot[i + 2];\n\n                iprod *= root[i + 2];\n\n            }\n\n        }\n\n        {\n\n            mint prod = 1, iprod = 1;\n\n            for (int i = 0; i <= rank2 - 3; i++) {\n\n                rate3[i] = root[i + 3] * prod;\n\n                irate3[i] = iroot[i + 3] * iprod;\n\n                prod *= iroot[i + 3];\n\n                iprod *= root[i + 3];\n\n            }\n\n        }\n\n    }\n\n};\n\n\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\n\nvoid butterfly(std::vector<mint>& a) {\n\n    int n = int(a.size());\n\n    int h = internal::countr_zero((unsigned int)n);\n\n\n\n    static const fft_info<mint> info;\n\n\n\n    int len = 0;  // a[i, i+(n>>len), i+2*(n>>len), ..] is transformed\n\n    while (len < h) {\n\n        if (h - len == 1) {\n\n            int p = 1 << (h - len - 1);\n\n            mint rot = 1;\n\n            for (int s = 0; s < (1 << len); s++) {\n\n                int offset = s << (h - len);\n\n                for (int i = 0; i < p; i++) {\n\n                    auto l = a[i + offset];\n\n                    auto r = a[i + offset + p] * rot;\n\n                    a[i + offset] = l + r;\n\n                    a[i + offset + p] = l - r;\n\n                }\n\n                if (s + 1 != (1 << len))\n\n                    rot *= info.rate2[countr_zero(~(unsigned int)(s))];\n\n            }\n\n            len++;\n\n        } else {\n\n            int p = 1 << (h - len - 2);\n\n            mint rot = 1, imag = info.root[2];\n\n            for (int s = 0; s < (1 << len); s++) {\n\n                mint rot2 = rot * rot;\n\n                mint rot3 = rot2 * rot;\n\n                int offset = s << (h - len);\n\n                for (int i = 0; i < p; i++) {\n\n                    auto mod2 = 1ULL * mint::mod() * mint::mod();\n\n                    auto a0 = 1ULL * a[i + offset].val();\n\n                    auto a1 = 1ULL * a[i + offset + p].val() * rot.val();\n\n                    auto a2 = 1ULL * a[i + offset + 2 * p].val() * rot2.val();\n\n                    auto a3 = 1ULL * a[i + offset + 3 * p].val() * rot3.val();\n\n                    auto a1na3imag =\n\n                        1ULL * mint(a1 + mod2 - a3).val() * imag.val();\n\n                    auto na2 = mod2 - a2;\n\n                    a[i + offset] = a0 + a2 + a1 + a3;\n\n                    a[i + offset + 1 * p] = a0 + a2 + (2 * mod2 - (a1 + a3));\n\n                    a[i + offset + 2 * p] = a0 + na2 + a1na3imag;\n\n                    a[i + offset + 3 * p] = a0 + na2 + (mod2 - a1na3imag);\n\n                }\n\n                if (s + 1 != (1 << len))\n\n                    rot *= info.rate3[countr_zero(~(unsigned int)(s))];\n\n            }\n\n            len += 2;\n\n        }\n\n    }\n\n}\n\n\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\n\nvoid butterfly_inv(std::vector<mint>& a) {\n\n    int n = int(a.size());\n\n    int h = internal::countr_zero((unsigned int)n);\n\n\n\n    static const fft_info<mint> info;\n\n\n\n    int len = h;  // a[i, i+(n>>len), i+2*(n>>len), ..] is transformed\n\n    while (len) {\n\n        if (len == 1) {\n\n            int p = 1 << (h - len);\n\n            mint irot = 1;\n\n            for (int s = 0; s < (1 << (len - 1)); s++) {\n\n                int offset = s << (h - len + 1);\n\n                for (int i = 0; i < p; i++) {\n\n                    auto l = a[i + offset];\n\n                    auto r = a[i + offset + p];\n\n                    a[i + offset] = l + r;\n\n                    a[i + offset + p] =\n\n                        (unsigned long long)(mint::mod() + l.val() - r.val()) *\n\n                        irot.val();\n\n                    ;\n\n                }\n\n                if (s + 1 != (1 << (len - 1)))\n\n                    irot *= info.irate2[countr_zero(~(unsigned int)(s))];\n\n            }\n\n            len--;\n\n        } else {\n\n            int p = 1 << (h - len);\n\n            mint irot = 1, iimag = info.iroot[2];\n\n            for (int s = 0; s < (1 << (len - 2)); s++) {\n\n                mint irot2 = irot * irot;\n\n                mint irot3 = irot2 * irot;\n\n                int offset = s << (h - len + 2);\n\n                for (int i = 0; i < p; i++) {\n\n                    auto a0 = 1ULL * a[i + offset + 0 * p].val();\n\n                    auto a1 = 1ULL * a[i + offset + 1 * p].val();\n\n                    auto a2 = 1ULL * a[i + offset + 2 * p].val();\n\n                    auto a3 = 1ULL * a[i + offset + 3 * p].val();\n\n\n\n                    auto a2na3iimag =\n\n                        1ULL *\n\n                        mint((mint::mod() + a2 - a3) * iimag.val()).val();\n\n\n\n                    a[i + offset] = a0 + a1 + a2 + a3;\n\n                    a[i + offset + 1 * p] =\n\n                        (a0 + (mint::mod() - a1) + a2na3iimag) * irot.val();\n\n                    a[i + offset + 2 * p] =\n\n                        (a0 + a1 + (mint::mod() - a2) + (mint::mod() - a3)) *\n\n                        irot2.val();\n\n                    a[i + offset + 3 * p] =\n\n                        (a0 + (mint::mod() - a1) + (mint::mod() - a2na3iimag)) *\n\n                        irot3.val();\n\n                }\n\n                if (s + 1 != (1 << (len - 2)))\n\n                    irot *= info.irate3[countr_zero(~(unsigned int)(s))];\n\n            }\n\n            len -= 2;\n\n        }\n\n    }\n\n}\n\n\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\n\nstd::vector<mint> convolution_naive(const std::vector<mint>& a,\n\n                                    const std::vector<mint>& b) {\n\n    int n = int(a.size()), m = int(b.size());\n\n    std::vector<mint> ans(n + m - 1);\n\n    if (n < m) {\n\n        for (int j = 0; j < m; j++) {\n\n            for (int i = 0; i < n; i++) {\n\n                ans[i + j] += a[i] * b[j];\n\n            }\n\n        }\n\n    } else {\n\n        for (int i = 0; i < n; i++) {\n\n            for (int j = 0; j < m; j++) {\n\n                ans[i + j] += a[i] * b[j];\n\n            }\n\n        }\n\n    }\n\n    return ans;\n\n}\n\n\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\n\nstd::vector<mint> convolution_fft(std::vector<mint> a, std::vector<mint> b) {\n\n    int n = int(a.size()), m = int(b.size());\n\n    int z = (int)internal::bit_ceil((unsigned int)(n + m - 1));\n\n    a.resize(z);\n\n    internal::butterfly(a);\n\n    b.resize(z);\n\n    internal::butterfly(b);\n\n    for (int i = 0; i < z; i++) {\n\n        a[i] *= b[i];\n\n    }\n\n    internal::butterfly_inv(a);\n\n    a.resize(n + m - 1);\n\n    mint iz = mint(z).inv();\n\n    for (int i = 0; i < n + m - 1; i++) a[i] *= iz;\n\n    return a;\n\n}\n\n\n\n}  // namespace internal\n\n\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\n\nstd::vector<mint> convolution(std::vector<mint>&& a, std::vector<mint>&& b) {\n\n    int n = int(a.size()), m = int(b.size());\n\n    if (!n || !m) return {};\n\n\n\n    int z = (int)internal::bit_ceil((unsigned int)(n + m - 1));\n\n    assert((mint::mod() - 1) % z == 0);\n\n\n\n    if (std::min(n, m) <= 60) return convolution_naive(a, b);\n\n    return internal::convolution_fft(a, b);\n\n}\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\n\nstd::vector<mint> convolution(const std::vector<mint>& a,\n\n                              const std::vector<mint>& b) {\n\n    int n = int(a.size()), m = int(b.size());\n\n    if (!n || !m) return {};\n\n\n\n    int z = (int)internal::bit_ceil((unsigned int)(n + m - 1));\n\n    assert((mint::mod() - 1) % z == 0);\n\n\n\n    if (std::min(n, m) <= 60) return convolution_naive(a, b);\n\n    return internal::convolution_fft(a, b);\n\n}\n\n\n\ntemplate <unsigned int mod = 998244353,\n\n          class T,\n\n          std::enable_if_t<internal::is_integral<T>::value>* = nullptr>\n\nstd::vector<T> convolution(const std::vector<T>& a, const std::vector<T>& b) {\n\n    int n = int(a.size()), m = int(b.size());\n\n    if (!n || !m) return {};\n\n\n\n    using mint = static_modint<mod>;\n\n\n\n    int z = (int)internal::bit_ceil((unsigned int)(n + m - 1));\n\n    assert((mint::mod() - 1) % z == 0);\n\n\n\n    std::vector<mint> a2(n), b2(m);\n\n    for (int i = 0; i < n; i++) {\n\n        a2[i] = mint(a[i]);\n\n    }\n\n    for (int i = 0; i < m; i++) {\n\n        b2[i] = mint(b[i]);\n\n    }\n\n    auto c2 = convolution(std::move(a2), std::move(b2));\n\n    std::vector<T> c(n + m - 1);\n\n    for (int i = 0; i < n + m - 1; i++) {\n\n        c[i] = c2[i].val();\n\n    }\n\n    return c;\n\n}\n\n\n\nstd::vector<long long> convolution_ll(const std::vector<long long>& a,\n\n                                      const std::vector<long long>& b) {\n\n    int n = int(a.size()), m = int(b.size());\n\n    if (!n || !m) return {};\n\n\n\n    static constexpr unsigned long long MOD1 = 754974721;  // 2^24\n\n    static constexpr unsigned long long MOD2 = 167772161;  // 2^25\n\n    static constexpr unsigned long long MOD3 = 469762049;  // 2^26\n\n    static constexpr unsigned long long M2M3 = MOD2 * MOD3;\n\n    static constexpr unsigned long long M1M3 = MOD1 * MOD3;\n\n    static constexpr unsigned long long M1M2 = MOD1 * MOD2;\n\n    static constexpr unsigned long long M1M2M3 = MOD1 * MOD2 * MOD3;\n\n\n\n    static constexpr unsigned long long i1 =\n\n        internal::inv_gcd(MOD2 * MOD3, MOD1).second;\n\n    static constexpr unsigned long long i2 =\n\n        internal::inv_gcd(MOD1 * MOD3, MOD2).second;\n\n    static constexpr unsigned long long i3 =\n\n        internal::inv_gcd(MOD1 * MOD2, MOD3).second;\n\n\n\n    static constexpr int MAX_AB_BIT = 24;\n\n    static_assert(MOD1 % (1ull << MAX_AB_BIT) == 1, \"MOD1 isn't enough to support an array length of 2^24.\");\n\n    static_assert(MOD2 % (1ull << MAX_AB_BIT) == 1, \"MOD2 isn't enough to support an array length of 2^24.\");\n\n    static_assert(MOD3 % (1ull << MAX_AB_BIT) == 1, \"MOD3 isn't enough to support an array length of 2^24.\");\n\n    assert(n + m - 1 <= (1 << MAX_AB_BIT));\n\n\n\n    auto c1 = convolution<MOD1>(a, b);\n\n    auto c2 = convolution<MOD2>(a, b);\n\n    auto c3 = convolution<MOD3>(a, b);\n\n\n\n    std::vector<long long> c(n + m - 1);\n\n    for (int i = 0; i < n + m - 1; i++) {\n\n        unsigned long long x = 0;\n\n        x += (c1[i] * i1) % MOD1 * M2M3;\n\n        x += (c2[i] * i2) % MOD2 * M1M3;\n\n        x += (c3[i] * i3) % MOD3 * M1M2;\n\n        long long diff =\n\n            c1[i] - internal::safe_mod((long long)(x), (long long)(MOD1));\n\n        if (diff < 0) diff += MOD1;\n\n        static constexpr unsigned long long offset[5] = {\n\n            0, 0, M1M2M3, 2 * M1M2M3, 3 * M1M2M3};\n\n        x -= offset[diff % 5];\n\n        c[i] = x;\n\n    }\n\n\n\n    return c;\n\n}\n\n\n\n}  // namespace atcoder\n\n\n\n\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nusing namespace atcoder;\n\n\n\nusing mint = modint998244353;\n\n\n\n#define int long long\n\n#define ll long long\n\n#define ii pair<int,int>\n\n#define iii tuple<int,int,int>\n\n#define fi first\n\n#define se second\n\n#define endl '\\n'\n\n#define debug(x) cout << #x << \": \" << x << endl\n\n\n\n#define pub push_back\n\n#define pob pop_back\n\n#define puf push_front\n\n#define pof pop_front\n\n#define lb lower_bound\n\n#define ub upper_bound\n\n\n\n#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n\n#define all(x) (x).begin(),(x).end()\n\n#define sz(x) (int)(x).size()\n\n\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\n\n\nconst int MOD=998244353;\n\nconst int HASH_MOD = 1000000007;\n\n\n\nll qexp(ll b,ll p,int m){\n\n    ll res=1;\n\n    while (p){\n\n        if (p&1) res=(res*b)%m;\n\n        b=(b*b)%m;\n\n        p>>=1;\n\n    }\n\n    return res;\n\n}\n\n\n\nll inv(ll i){\n\n\treturn qexp(i,MOD-2,MOD);\n\n}\n\n\n\nll fix(ll i){\n\n\ti%=MOD;\n\n\tif (i<0) i+=MOD;\n\n\treturn i;\n\n}\n\n\n\nll fac[1000005];\n\nll ifac[1000005];\n\n\n\nll nCk(int i,int j){\n\n\tif (i<j) return 0;\n\n\treturn fac[i]*ifac[j]%MOD*ifac[i-j]%MOD;\n\n}\n\n\n\nint n, X;\n\nint memo[4005][4005];\n\nint ans[4005][4005];\n\n\n\nsigned main(){\n\n\tios::sync_with_stdio(0);\n\n\tcin.tie(0);\n\n\tcout.tie(0);\n\n\tcin.exceptions(ios::badbit | ios::failbit);\n\n\n\n\tfac[0]=1;\n\n\trep(x,1,1000005) fac[x]=fac[x-1]*x%MOD;\n\n\tifac[1000004]=inv(fac[1000004]);\n\n\trep(x,1000005,1) ifac[x-1]=ifac[x]*x%MOD;\n\n\n\n\tcin>>n>>X;\n\n\n\n\tmemo[1][0]=1;\n\n\n\n\trep(x,1,n+1){\n\n\t\trep(y,0,x){ //y 1 gaps, x-y-1 0 gaps\n\n\t\t\tif (y) memo[x+1][y-1+2*(x%2)]=(memo[x+1][y-1+2*(x%2)]+y*memo[x][y])%MOD;\n\n\t\t\tmemo[x+1][y+2*(x%2)]=(memo[x+1][y+2*(x%2)]+(x-y-1)*memo[x][y])%MOD;\n\n\t\t\tmemo[x+1][y+(x%2)]=(memo[x+1][y+(x%2)]+2*memo[x][y])%MOD;\n\n\t\t}\n\n\t}\n\n\n\n\trep(x,2,n+1){\n\n\t\tif (x%2==0) reverse(memo[x],memo[x]+x);\n\n\n\n\t\tvector<int> a;\n\n\t\trep(y,x-1,0) a.pub(memo[x][y]*fac[y]%MOD*fac[n-y]%MOD);\n\n\t\tvector<int> b;\n\n\t\trep(y,0,n-x+1) b.pub(ifac[y]*ifac[n-x-y]%MOD);\n\n\t\ta=convolution(a,b);\n\n\t\trep(y,0,x-1) ans[x][y]=a[x-2-y]*ifac[y]%MOD*ifac[x-y]%MOD;\n\n\n\n\t\tint tot=1;\n\n\t\trep(y,1,n-x+1) tot=tot*y%MOD;\n\n\t\trep(y,0,x-1) ans[x][y]=ans[x][y]*tot%MOD;\n\n\t}\n\n\n\n    ll hash = 0;\n\n    ll pow = 1;\n\n\n\n    for (ll i = 1; i <= 3 * n; i++) pow = (X * pow) % HASH_MOD;\n\n\n\n\trep(x,2,n+1){\n\n\t\treverse(ans[x],ans[x]+n);\n\n\t\trep(y,0,n) {\n\n            hash = (hash + pow * ans[x][y]) % HASH_MOD;\n\n            pow = (X * pow) % HASH_MOD;\n\n        }\n\n\t}\n\n\n\n    cout << hash << endl;\n\n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1913",
    "index": "A",
    "title": "Rating Increase",
    "statement": "Monocarp is a great solver of adhoc problems. Recently, he participated in an Educational Codeforces Round, and gained rating!\n\nMonocarp knew that, before the round, his rating was $a$. After the round, it increased to $b$ ($b > a$). He wrote both values one after another to not forget them.\n\nHowever, he wrote them so close to each other, that he can't tell now where the first value ends and the second value starts.\n\nPlease, help him find some values $a$ and $b$ such that:\n\n- neither of them has a leading zero;\n- both of them are strictly greater than $0$;\n- $b > a$;\n- they produce the given value $ab$ when written one after another.\n\nIf there are multiple answers, you can print any of them.",
    "tutorial": "Since the length of the string is pretty small, it's possible to iterate over all possible cuts of $ab$ into $a$ and $b$. First, you have to check if $b$ has a leading zero. If it doesn't, compare integer representations of $a$ and $b$. In order to get an integer from a string, you can use stoi(s) for C++ or int(s) for Python.",
    "code": "for _ in range(int(input())):\n    ab = input()\n    for i in range(1, len(ab)):\n        if ab[i] != '0' and int(ab[:i]) < int(ab[i:]):\n            print(ab[:i], ab[i:])\n            break\n    else:\n        print(-1)",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1913",
    "index": "B",
    "title": "Swap and Delete",
    "statement": "You are given a binary string $s$ (a string consisting only of 0-s and 1-s).\n\nYou can perform two types of operations on $s$:\n\n- delete one character from $s$. This operation costs $1$ coin;\n- swap any pair of characters in $s$. This operation is free (costs $0$ coins).\n\nYou can perform these operations any number of times and in any order.\n\nLet's name a string you've got after performing operations above as $t$. The string $t$ is good if for each $i$ from \\textbf{$1$ to $|t|$} $t_i \\neq s_i$ ($|t|$ is the length of the string $t$). The empty string is always good. Note that you are comparing the resulting string $t$ with the initial string $s$.\n\nWhat is the minimum total cost to make the string $t$ good?",
    "tutorial": "Let's count the number of 0-s and 1-s in $s$ as $cnt_0$ and $cnt_1$ correspondingly. Since $t$ consists of characters from $s$ then $t$ will contain no more than $cnt_0$ zeros and $cnt_1$ ones. Let's build $t$ greedily, since we always compare $t$ with prefix of $s$. Suppose the length of $t$ is at least one, it means that $t_1$ must be different from $s_1$, so if $s_1$ $=$ 0 we must set $t_1$ $=$ 1. So let's check that we have at least one 1 (or $cnt_1 > 0$), take 1 and place it at $t_1$. Case $s_1$ $=$ 1 is the same. After placing $t_1$ we can analogically try to place $t_2$ and so on until we run out of necessary digits or build the whole string of length $|s|$. We've built the longest possible string $t$ in $O(|s|)$ time, so the answer is $|s| - |t|$.",
    "code": "for _ in range(int(input())):\n    s = input()\n    cnt = [0, 0]\n    for i in range(len(s)):\n        cnt[int(s[i])] += 1\n    for i in range(len(s) + 1):\n        if (i == len(s) or cnt[1 - int(s[i])] == 0):\n            print(len(s) - i)\n            break\n        cnt[1 - int(s[i])] -= 1",
    "tags": [
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1913",
    "index": "C",
    "title": "Game with Multiset",
    "statement": "In this problem, you are initially given an empty multiset. You have to process two types of queries:\n\n- ADD $x$ — add an element equal to $2^{x}$ to the multiset;\n- GET $w$ — say whether it is possible to take the sum of some subset of the current multiset and get a value equal to $w$.",
    "tutorial": "We are given a classic knapsack problem. There are items with certain weights and a total weight that we want to achieve. If the weights were arbitrary, we would need dynamic programming to solve it. However, this variation of the knapsack problem can be solved greedily. What makes it special? If we arrange the weights in non-decreasing order, each subsequent weight is divisible by the previous one. Then the following greedy approach works. Arrange the items by weight, from smallest to largest. Let's say we want to achieve sum $s$, and the weights of the items are $x_1, x_2, \\dots$. Let the weights be distinct, and the number of items with weight $x_i$ be $\\mathit{cnt}_i$. If $s$ is not divisible by $x_1$, the answer is NO. Otherwise, we look at the remainder of $s$ divided by $x_2$. If it is not equal to $0$, our only hope to make it $0$ is to take items with weight $x_1$. All other items are divisible by $x_2$, so they will not help. We take exactly $\\frac{s \\bmod x_2}{x_1}$ items. If there are less than that, the answer is NO. Subtract this from $s$ - now the remainder is $0$. Now the claim is: there is no point in taking additional items with weight $x_1$ in a quantity not divisible by $\\frac{x_2}{x_1}$. If we do that, we will break the remainder again. Thus, we can pack $\\frac{x_2}{x_1}$ items with weight $x_1$ into groups of weight $x_2$ and add the number of these groups to $\\mathit{cnt}_2$. Then recursively solve the same problem, but for the new value of $s$ and weights $2, 3, \\dots$. When we run out of distinct weights, we have to check that there are enough items of the largest weight to collect the entire weight $s$. This can be written by iterating through the weight values from smallest to largest. For each weight, we can maintain the count in an array. Then the first type of query works in $O(1)$, and the second type of query works in $30$ iterations.",
    "code": "from sys import stdin, stdout\n\nLOG = 30\ncnt = [0 for i in range(LOG)]\nans = []\nfor _ in range(int(stdin.readline())):\n    t, v = map(int, stdin.readline().split())\n    if t == 1:\n        cnt[v] += 1\n    else:\n        nw = 0\n        for i in range(LOG):\n            r = (v % (2 << i)) // (1 << i)\n            if r > nw + cnt[i]:\n                ans.append(0)\n                break\n            v -= r\n            nw = (nw + cnt[i] - r) // 2\n        else:\n            ans.append(nw >= (v >> 30))\nstdout.write('\\n'.join([\"YES\" if x else \"NO\" for x in ans]))",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1913",
    "index": "D",
    "title": "Array Collapse",
    "statement": "You are given an array $[p_1, p_2, \\dots, p_n]$, where all elements are distinct.\n\nYou can perform several (possibly zero) operations with it. In one operation, you can choose a \\textbf{contiguous subsegment} of $p$ and remove \\textbf{all} elements from that subsegment, \\textbf{except for} the minimum element on that subsegment. For example, if $p = [3, 1, 4, 7, 5, 2, 6]$ and you choose the subsegment from the $3$-rd element to the $6$-th element, the resulting array is $[3, 1, 2, 6]$.\n\nAn array $a$ is called reachable if it can be obtained from $p$ using several (maybe zero) aforementioned operations. Calculate the number of reachable arrays, and print it modulo $998244353$.",
    "tutorial": "Let's rephrase the problem a bit. Instead of counting the number of arrays, let's count the number of subsequences of elements that can remain at the end. One of the classic methods for counting subsequences is dynamic programming of the following kind: $\\mathit{dp}_i$ is the number of subsequences such that the last taken element is at position $i$. Counting exactly this is that simple. It happens that element $i$ cannot be the last overall because it is impossible to remove everything after it. Thus, let's say it a little differently: the number of good subsequences on a prefix of length $i$. Now we are not concerned with what comes after $i$ - after the prefix. If we learned to calculate such dp, we could get the answer from it. We just need to understand when we can remove all elements after a fixed one. It is easy to see that it is enough for all these elements to be smaller than the fixed one. Then they can be removed one by one from left to right. If there is at least one larger element, then the maximum of such elements cannot be removed. Therefore, the answer is equal to the sum of dp for all $i$ such that $a_i$ is the largest element on a suffix of length $n - i + 1$. How to calculate such dp? Let's look at the nearest element to the left that is larger than $a_i$. Let its position be $j$. Then any subsequence that ended with an element between $j$ and $i$ can have the element $i$ appended to it. It is only necessary to remove the elements standing before $i$. This can also be done one by one. Can $j$ be removed as well? It can, but it's not that simple. Only the element that is the nearest larger one to the left for $a_j$ or someone else even more to the left can do this. Let $f[i]$ be the position of the nearest larger element to the left. Then the element $i$ can also extend subsequences ending in $a[f[i]], a[f[f[i]]], a[f[f[f[i]]]], \\dots$. If there are no larger elements to the left of the element - the element is the maximum on the prefix - then $1$ is added to its $\\mathit{dp}$ value. This is a subsequence consisting of only this element. The position of the nearest larger element to the left can be found using a monotonic stack: keep a stack of elements; while the element at the top is smaller, remove it; then add the current one to the stack. Counting the dp currently works in $O(n^2)$ in the worst case. How to optimize this? The first type of transitions is optimized by prefix sums, as it is simply the sum of dp on a segment. For the second type of transitions, you can maintain the sum of dp on a chain of jumps to the nearest larger element: $\\mathit{dpsum}_i = \\mathit{dpsum}_{f[i]} + \\mathit{dp}_i$. Now, both transitions can be done in $O(1)$. Overall complexity: $O(n)$ for each testcase.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint normalize(long long x) {\n    x %= MOD;\n    if (x < 0) x += MOD;\n    return x;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        int n;\n        cin >> n;\n        vector <int> a(n);\n        vector <int> nextMin(n);\n        vector <int> dpSum(n + 2);\n        vector <int> dpNext(n);\n        for (int i = 0; i < n; ++i)\n            cin >> a[i];\n        \n        stack <int> stMin;\n        nextMin[n - 1] = n;\n        dpSum[n] = 1;\n        for (int pos = n - 1; pos >= 0; --pos) {\n            while(!stMin.empty() && a[stMin.top()] > a[pos])\n                stMin.pop();\n            nextMin[pos] = stMin.empty() ? n : stMin.top();\n            stMin.push(pos);\n            \n            int nxtPos = nextMin[pos];\n            int dpPos = normalize(dpSum[pos + 1] - dpSum[nxtPos + 1]);\n            if (nxtPos != n) {\n                dpPos = normalize(dpPos + dpNext[nxtPos]);\n                dpNext[pos] = normalize(dpSum[nxtPos] - dpSum[nxtPos + 1] + dpNext[nxtPos]);\n            }\n            dpSum[pos] = normalize(dpPos + dpSum[pos + 1]);\n            \n            //cout << pos << ' ' << nxtPos << ' ' << dpPos << endl;\n        }\n        \n        int res = 0;\n        int mn = a[0];\n        for(int i = 0; i < n; ++i) {\n            mn = min(mn, a[i]);\n            if (a[i] == mn) {\n                res = normalize(res + dpSum[i] - dpSum[i + 1]);\n            }\n        }\n        cout << res << endl;\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dp",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1913",
    "index": "E",
    "title": "Matrix Problem",
    "statement": "You are given a matrix $a$, consisting of $n$ rows by $m$ columns. Each element of the matrix is equal to $0$ or $1$.\n\nYou can perform the following operation any number of times (possibly zero): choose an element of the matrix and replace it with either $0$ or $1$.\n\nYou are also given two arrays $A$ and $B$ (of length $n$ and $m$ respectively). After you perform the operations, the matrix should satisfy the following conditions:\n\n- the number of ones in the $i$-th row of the matrix should be exactly $A_i$ for every $i \\in [1, n]$.\n- the number of ones in the $j$-th column of the matrix should be exactly $B_j$ for every $j \\in [1, m]$.\n\nCalculate the minimum number of operations you have to perform.",
    "tutorial": "There are many ways to solve this problem (even if all of them are based on minimum cost flows), but in my opinion, the most elegant one is the following one. Let us build another matrix $b$ of size $n \\times m$ that meets the following requirements: the sum in the $i$-th row of the matrix $b$ is $A_i$; the sum in the $j$-th column of the matrix $b$ is $B_j$; the number of cells $(i, j)$ such that $a_{i,j} = b_{i,j} = 1$ is the maximum possible. It's quite easy to see that this matrix $b$ is the one which we need to transform the matrix $a$ into: the first two conditions are literally from the problem statement, and the third condition ensures that the number of $1$'s we change into $0$'s is as small as possible (and since we know the number of $1$'s in the matrix $a$, and we know that the number of $1$'s in the matrix $b$ should be exactly $\\sum A_i$, this also minimizes the number of times we change a $0$ into a $1$). So, the third condition minimizes the number of operations we have to perform. How can we build $b$? Let's model it with a flow network (with costs). We will need a source (let's call it $S$), a sink (let's call it $T$), a vertex for every row (let's call it $R_i$ for the $i$-th row), and a vertex for every column (let's call it $C_j$ for the $j$-th column). To model that we want the $i$-th row to have the sum $A_i$, let's add a directed edge from $S$ to $R_i$ with capacity of $A_i$ and cost of $0$. Some solutions will also need to make sure that this directed edge has a lower constraint on the flow equal to $A_i$, but we will show later why it's unnecessary in our method. Similarly, to model that the $j$-th column should have sum $B_j$, add a directed edge from $C_j$ to $T$ with capacity $A_i$ and cost $0$. To model that we can choose either $0$ or $1$ for the cell $(i, j)$, add a directed edge from $R_i$ to $C_j$ with capacity $1$. The value in the corresponding cell of the matrix $b$ will be equal to the flow along that edge. The cost of this edge should reflect that we want to have as many cells such that $a_{i,j} = b_{i,j} = 1$. To ensure that, let's make its cost $0$ if $a_{i,j} = 1$, or $1$ if $a_{i,j}=0$. That way, the cost of the flow increases by $1$ each time we put a $1$ in a cell where $a_{i,j} = 0$ - and since the number of $1$'s in the matrix $b$ is fixed, this means that we put a $0$ in a cell where $a_{i,j} = 1$; so, the number of cells $(i, j)$ such that $a_{i,j} = b_{i,j} = 1$ gets reduced. Now our network is ready. In order to make sure that all edges connecting $S$ with $R_i$ and $C_j$ with $T$ are saturated, we have to find the minimum cost maximum flow in it. Since the network has no negative cycles, the number of vertices is $O(n+m)$, the number of edges is $O(nm)$, and the maximum flow in the network is also $O(nm)$, any reasonable MCMF algorithm can be used. After running MCMF, let's check that the amount of the flow we pushed is equal both to $\\sum A_i$ and to $sum B_j$. If that's not the case, then it is impossible to construct the matrix $b$, so the answer is $-1$. Otherwise, to calculate the number of operations we have to perform, we can either restore the matrix $b$ from the flow we got and calculate the number of cells such that $a_{i,j} \\ne b_{i,j}$, or derive a formula which can calculate the number of operations directly from the number of $1$'s in $a$, number of $1$'s in $b$ and the cost of the flow. The model solution does the latter.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 111;\n\nstruct edge\n{\n    int y, c, w, f;\n    edge() {};\n    edge(int y, int c, int w, int f) : y(y), c(c), w(w), f(f) {};\n};\n\nvector<edge> e;\nvector<int> g[N];\n\nint rem(int x)\n{\n    return e[x].c - e[x].f;\n}\n\nvoid add_edge(int x, int y, int c, int w)\n{\n    g[x].push_back(e.size());\n    e.push_back(edge(y, c, w, 0));\n    g[y].push_back(e.size());\n    e.push_back(edge(x, 0, -w, 0));\n}\n\nint n, m, s, t, v;\n\npair<int, long long> MCMF()\n{\n    int flow = 0;\n    long long cost = 0;\n    while(true)\n    {\n        vector<long long> d(v, (long long)(1e18));\n        vector<int> p(v, -1);\n        vector<int> pe(v, -1);\n        queue<int> q;\n        vector<bool> inq(v);\n        q.push(s);\n        inq[s] = true;\n        d[s] = 0;\n        while(!q.empty())\n        {\n            int k = q.front();\n            q.pop();\n            inq[k] = false;\n            for(auto ei : g[k])\n            {\n                if(rem(ei) == 0) continue;\n                int to = e[ei].y;\n                int w = e[ei].w;\n                if(d[to] > d[k] + w)\n                {\n                    d[to] = d[k] + w;\n                    p[to] = k;\n                    pe[to] = ei;\n                    if(!inq[to])\n                    {\n                        inq[to] = true;\n                        q.push(to);\n                    }\n                }\n            }\n        }\n        if(p[t] == -1) break;\n        flow++;\n        cost += d[t];\n        int cur = t;\n        while(cur != s)\n        {\n            e[pe[cur]].f++;\n            e[pe[cur] ^ 1].f--;\n            cur = p[cur];\n        }\n    }\n    return make_pair(flow, cost);\n}\n\nint get_sum(const vector<int>& v)\n{\n    int sum = 0;\n    for(auto x : v) sum += x;\n    return sum;\n}\n\nint main()\n{\n    cin >> n >> m;\n    s = n + m;\n    t = n + m + 1;\n    v = n + m + 2;\n    int sum_matrix = 0;\n    vector<int> A(n), B(m);\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < m; j++)\n        {\n            int x;\n            cin >> x;\n            sum_matrix += x;\n            if(x == 1)\n                add_edge(i, j + n, 1, 0);\n            else\n                add_edge(i, j + n, 1, 1);\n        }\n    for(int i = 0; i < n; i++)\n    {\n        cin >> A[i];\n        add_edge(s, i, A[i], 0);\n    }\n    for(int i = 0; i < m; i++) \n    {\n        cin >> B[i];\n        add_edge(i + n, t, B[i], 0);\n    }\n    \n    auto res = MCMF();\n    if(res.first != get_sum(A) || res.first != get_sum(B))\n        cout << -1 << endl;\n    else\n        cout << sum_matrix - res.first + res.second * 2 << endl;\n}",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1913",
    "index": "F",
    "title": "Palindromic Problem",
    "statement": "You are given a string $s$ of length $n$, consisting of lowercase Latin letters.\n\nYou are allowed to replace at most one character in the string with an arbitrary lowercase Latin letter.\n\nPrint the lexicographically minimal string that can be obtained from the original string and contains the maximum number of palindromes as substrings. Note that if a palindrome appears more than once as a substring, it is counted the same number of times it appears.\n\nThe string $a$ is lexicographically smaller than the string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ are different, the string $a$ contains a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "Let's recall the algorithm for counting the number of palindromes in a string. For each position, we can calculate the longest odd and even palindromes with centers at that position (the right one for even). Then sum up all the values. If we forget about the complexity, we can consider the following algorithm for solving the full problem. Iterate over the index of the change and the new letter. Make the change, count the number of palindromes, and update the answer. In case of equality, choose the lexicographically minimal change. Let's keep the first step and optimize the rest. It won't be possible to count the number of palindromes from scratch for every change, so let's try to calculate how much their number will change from the original. It's also not feasible to compare all strings lexicographically naively, so we have to come up with a faster way to compare. Let's fix the change position $i$. Which of the longest palindromes change? If for some center $j$, the longest palindrome included $i$, then we definitely know its new length. Due to the change at $i$, the longest palindrome will stop at $i$. If the longest palindrome did not reach $i$, it will not change. And only if it stopped at $i$, it can become longer, and we don't know by how much yet. But for each center $j$ and the parity of the palindrome, there are only positions to the left and to the right where it stops. So, in total, we will need to make $O(n)$ such checks. How to take into account the palindromes that become shorter? We need to calculate the sum of the differences for all palindromes that include $i$. For an odd palindrome, this change looks like this: $[\\dots, 0, -1, -2, -3, -4, -3, -2, -1, 0, \\dots]$, where $-4$ is the center of the palindrome, and the values show the difference in the number of palindromes for each position of the string. For an even palindrome: $[\\dots, 0, -1, -2, -3, -3, -2, -1, 0, \\dots]$. To calculate the sum at each position, we can pre-calculate a difference array based on these values. The difference array usually implies first-order changes: write $+x$ at $l$, write $-x$ at $r+1$, then collect the prefix sum to get $[\\dots, 0, x, x, \\dots, x, 0, \\dots]$. But we can also record second-order changes. For the odd construction, we will write as follows. Let the length of the palindrome be $\\mathit{len}$, and the center be $i$. Then: $\\mathit{dt}[i - \\mathit{len} + 1] \\mathrel{{+}{=}} 1$; $\\mathit{dt}[i + 1] \\mathrel{{-}{=}} 2$; $\\mathit{dt}[i + \\mathit{len} + 1] \\mathrel{{+}{=}} 1$. Then iterate from left to right, maintaining two variables. The current change and the current value. At each $i$, add $\\mathit{dt}[i]$ to the change, add the change to the value, and save the value to some array. For the even case, it is built similarly. It is easy to see that such changes can be made at the same time. Basically the same as the regular difference array. Now, in each position, the total decrease in the length of the palindromes passing through that position is recorded. The answer will decrease by almost this amount. The only difference is the odd-length palindromes with a center at this position. They will not change at all, and we accidentally subtracted them. Thus, let's save the longest odd palindrome for each position in advance and add it back. Let's learn how to calculate the longest palindromes for each center. Yes, there is the Manacher's algorithm for a static string. We can use it for counting at the very beginning, but it's not really necessary. Instead, let's learn to count palindromes using suffix structures. In particular, with a suffix array. It is known that with an additional sparse table, we can query the longest common prefix of two suffixes in $O(1)$ with pre-calculation in $O(n \\log n)$. Let's build a suffix array on the string $s + \\# + \\mathit{rev}(s) + \\$$. Then we can query the LCP of both suffixes and reverse prefixes. Then the longest odd palindrome with center at $i$ is LCP($s[i..n]$, $\\mathit{rev}$($s[1..i]$)). The even one is LCP($s[i..n]$, $\\mathit{rev}$($s[1..i-1]$)). So, we can count the palindromes at the very beginning with $O(n \\log n)$ pre-calculation and $O(n)$ extra calculations. The following task remains. For each position, the centers of the palindromes that reach it are known. For each such center, we need to be able to recalculate how much longer the palindrome will become after changing the letter at that position. Obviously, even the new letter may still not match the letter on the other side. If it does match, we would like to know how many letters further match the opposite ones in the original string. And we already have a tool for this. It's still a simple LCP query on the suffix to the right of the right letter and the reverse prefix to the left of the left letter. Now we have everything necessary to recalculate the number of palindromes. If the new count is greater than the current maximum, we will simply update the answer. If it is equal, we need to check the lexicographic order. The following check works: if one change increased the original letter, and the other decreased it, then the second one will definitely produce a smaller string; if both changes decreased it, then the more left one will produce a smaller string; if both are in the same position, the smaller letter will produce a smaller string; if both changes increased it, then the more right one will produce a smaller string; if both are in the same position, the smaller letter will produce a smaller string. All these checks can be performed in $O(1)$. Overall complexity: $O(n \\log n + n \\cdot |\\mathit{AL}|)$.",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n#define x first\n#define y second\n\nusing namespace std;\n\nstruct sparse_table {\n    vector<vector<int>> st;\n    vector<int> pw;\n    \n    sparse_table() {}\n    \n    sparse_table(const vector<int> &a) {\n        int n = a.size();\n        int logn = 32 - __builtin_clz(n);\n        st.resize(logn, vector<int>(n));\n        forn(i, n)\n            st[0][i] = a[i];\n        for (int j = 1; j < logn; ++j) forn(i, n) {\n            st[j][i] = st[j - 1][i];\n            if (i + (1 << (j - 1)) < n)\n                st[j][i] = min(st[j][i], st[j - 1][i + (1 << (j - 1))]);\n        }\n        pw.resize(n + 1);\n        pw[0] = pw[1] = 0;\n        for (int i = 2; i <= n; ++i)\n            pw[i] = pw[i >> 1] + 1;\n    }\n    \n    int get(int l, int r) {\n        if (l >= r) return 1e9;\n        int len = pw[r - l];\n        return min(st[len][l], st[len][r - (1 << len)]);\n    }\n};\n\nstruct suffix_array {\n    vector<int> c, pos;\n    vector<pair<pair<int, int>, int>> p, nw;\n    vector<int> cnt;\n    int n;\n    \n    void radix_sort(int max_al) {\n        cnt.assign(max_al, 0);\n        forn(i, n) ++cnt[p[i].x.y];\n        for (int i = 1; i < max_al; ++i) cnt[i] += cnt[i - 1];\n        nw.resize(n);\n        forn(i, n) nw[--cnt[p[i].x.y]] = p[i];\n        cnt.assign(max_al, 0);\n        forn(i, n) ++cnt[nw[i].x.x];\n        for (int i = 1; i < max_al; ++i) cnt[i] += cnt[i - 1];\n        for (int i = n - 1; i >= 0; --i) p[--cnt[nw[i].x.x]] = nw[i];\n    }\n    \n    vector<int> lcp;\n    sparse_table st;\n    \n    int get_lcp(int l, int r) {\n        l = c[l], r = c[r];\n        if (l > r) swap(l, r);\n        return st.get(l, r);\n    }\n    \n    suffix_array(const string &s) {\n        n = s.size();\n        c = vector<int>(s.begin(), s.end());\n        int max_al = *max_element(c.begin(), c.end()) + 1;\n        p.resize(n);\n        for (int k = 1; k < n; k <<= 1) {\n            for (int i = 0, j = k; i < n; ++i, j = (j + 1 == n ? 0 : j + 1))\n                p[i] = make_pair(make_pair(c[i], c[j]), i);\n            radix_sort(max_al);\n            c[p[0].y] = 0;\n            for (int i = 1; i < n; ++i) c[p[i].y] = c[p[i - 1].y] + (p[i].x != p[i - 1].x);\n            max_al = c[p.back().y] + 1;\n        }\n        lcp.resize(n);\n        int l = 0;\n        forn(i, n) {\n            l = max(0, l - 1);\n            if (c[i] == n - 1)\n                continue;\n            while (i + l < n && p[c[i] + 1].y + l < n && s[i + l] == s[p[c[i] + 1].y + l])\n                ++l;\n            lcp[c[i]] = l;\n        }\n        pos.resize(n);\n        forn(i, n)\n            pos[i] = p[i].y;\n        st = sparse_table(lcp);\n    }\n};\n\nint main() {\n    string s;\n    int n;\n    cin >> n;\n    cin >> s;\n    string t = s;\n    reverse(t.begin(), t.end());\n    auto sa = suffix_array(s + \"#\" + t + \"$\");\n    vector<vector<int>> ev0(n), ev1(n);\n    long long base = 0;\n    vector<long long> dt(n + 2);\n    vector<int> d1(n);\n    forn(i, n){\n        int len0 = sa.get_lcp(i, 2 * n - i + 1);\n        base += len0;\n        dt[i - len0] += 1;\n        dt[i] -= 1;\n        dt[i + 1] -= 1;\n        dt[i + len0 + 1] += 1;\n        if (i - len0 - 1 >= 0 && i + len0 < n){\n            ev0[i - len0 - 1].push_back(i);\n            ev0[i + len0].push_back(i);\n        }\n        int len1 = sa.get_lcp(i, 2 * n - i);\n        d1[i] = len1;\n        dt[i - len1 + 1] += 1;\n        dt[i + 1] -= 2;\n        dt[i + len1 + 1] += 1;\n        base += len1;\n        if (i - len1 >= 0 && i + len1 < n){\n            ev1[i - len1].push_back(i);\n            ev1[i + len1].push_back(i);\n        }\n    }\n    vector<long long> dx(n + 1);\n    long long curt = 0, val = 0;\n    forn(i, n){\n        curt += dt[i];\n        val += curt;\n        dx[i] = val;\n    }\n    long long ans = base;\n    int pos = -1, nc = -1;\n    bool gr = false;\n    forn(i, n) forn(c, 26) if (c != s[i] - 'a'){\n        long long cur = base;\n        for (int j : ev0[i]){\n            if (j <= i && c == s[2 * j - i - 1] - 'a')\n                cur += 1 + sa.get_lcp(i + 1, 2 * n - (2 * j - i - 2));\n            else if (j > i && c == s[2 * j - i - 1] - 'a')\n                cur += 1 + sa.get_lcp(2 * j - i, 2 * n - (i - 1));\n        }\n        for (int j : ev1[i]){\n            if (c != s[2 * j - i] - 'a') continue;\n            if (j < i)\n                cur += 1 + sa.get_lcp(i + 1, 2 * n - (2 * j - i - 1));\n            else\n                cur += 1 + sa.get_lcp(2 * j - i + 1, 2 * n - (i - 1));\n        }\n        cur += d1[i];\n        cur -= dx[i];\n        bool upd = false;\n        if (cur > ans){\n            upd = true;\n        }\n        else if (cur == ans){\n            if (c < s[i] - 'a'){\n                if (pos == -1 || gr)\n                    upd = true;\n            }\n            else{\n                if (pos < i && gr)\n                    upd = true;\n            }\n        }\n        if (upd){\n            ans = cur;\n            pos = i;\n            nc = c;\n            gr = c > s[i] - 'a';\n        }\n    }\n    cout << ans << endl;\n    if (pos != -1) s[pos] = nc + 'a';\n    cout << s << endl;\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1914",
    "index": "A",
    "title": "Problemsolving Log",
    "statement": "Monocarp is participating in a programming contest, which features $26$ problems, named from 'A' to 'Z'. The problems are sorted by difficulty. Moreover, it's known that Monocarp can solve problem 'A' in $1$ minute, problem 'B' in $2$ minutes, ..., problem 'Z' in $26$ minutes.\n\nAfter the contest, you discovered his contest log — a string, consisting of uppercase Latin letters, such that the $i$-th letter tells which problem Monocarp was solving during the $i$-th minute of the contest. If Monocarp had spent enough time in total on a problem to solve it, he solved it. Note that Monocarp could have been thinking about a problem after solving it.\n\nGiven Monocarp's contest log, calculate the number of problems he solved during the contest.",
    "tutorial": "For each problem, we will calculate the total number of minutes Monocarp spent on it. Then we will compare it to the minimum required time for solving the problem. One of the possible implementations is as follows. Create a string $t =$\"ABC ... Z\" in the program. Then problem $t_i$ can be solved in $i + 1$ minutes. We can compare s.count(t[i]) to $i + 1$. We can also use the ASCII table to convert the problem number to a letter. In Python, there are functions chr and ord for this purpose. For example, the letter for the $i$-th problem is chr(ord('A') + $i$). In C++, you can directly obtain a char from an int using char('A' + $i$). It is also possible to solve this problem in linear time of the length of the string, but it was not required.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    s = input()\n    print(sum([s.count(chr(ord('A') + i)) >= i + 1 for i in range(26)]))",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1914",
    "index": "B",
    "title": "Preparing for the Contest",
    "statement": "Monocarp is practicing for a big contest. He plans to solve $n$ problems to make sure he's prepared. Each of these problems has a difficulty level: the first problem has a difficulty level of $1$, the second problem has a difficulty level of $2$, and so on, until the last ($n$-th) problem, which has a difficulty level of $n$.\n\nMonocarp will choose some order in which he is going to solve all $n$ problems. Whenever he solves a problem which is more difficult than the last problem he solved, he gets excited because he feels like he's progressing. He doesn't get excited when he solves the first problem in his chosen order.\n\nFor example, if Monocarp solves the problems in the order $[3, \\underline{5}, 4, 1, \\underline{6}, 2]$, he gets excited twice (the corresponding problems are underlined).\n\nMonocarp wants to get excited exactly $k$ times during his practicing session. Help him to choose the order in which he has to solve the problems!",
    "tutorial": "The examples give a pretty big hint to the solution: to get $k = 0$, we have to order all problems from the hardest to the easiest one, and to get $k = n - 1$, we have to order them from the easiest to the hardest problem. Let's try to combine them for the general case. Let's start by placing the problems from the hardest to the easiest one: $[n, n-1, \\dots, 2, 1]$. If $k = 1$, we can just swap two last problems and make solving the last problem exciting. If $k = 2$, we can reverse the order of the last $3$ problems, so $2$ of them excite Monocarp, and so on; generally, reversing $(k+1)$ last problems ensures that exactly $k$ last problems will excite Monocarp. There are also other methods to sovle this problem, but this is one of the easiest.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> a(n);\n\tfor(int i = 0; i < n; i++) a[i] = n - i;\n\treverse(a.end() - k - 1, a.end());\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tif(i) cout << \" \";\n\t\tcout << a[i];\n\t}\n\tcout << endl;\n}\n \nint main()\n{\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1914",
    "index": "C",
    "title": "Quests",
    "statement": "Monocarp is playing a computer game. In order to level up his character, he can complete quests. There are $n$ quests in the game, numbered from $1$ to $n$.\n\nMonocarp can complete quests according to the following rules:\n\n- the $1$-st quest is always available for completion;\n- the $i$-th quest is available for completion if all quests $j < i$ have been completed at least once.\n\nNote that Monocarp can complete the same quest multiple times.\n\nFor each completion, the character gets some amount of experience points:\n\n- for the first completion of the $i$-th quest, he gets $a_i$ experience points;\n- for each subsequent completion of the $i$-th quest, he gets $b_i$ experience points.\n\nMonocarp is a very busy person, so he has free time to complete no more than $k$ quests. Your task is to calculate the maximum possible total experience Monocarp can get if he can complete no more than $k$ quests.",
    "tutorial": "Let's iterate over the number of quests that have been completed at least once (denote it as $i$). It remains to complete $k-i$ quests more, and we are allowed to complete any of the first $i$ quests again. It is obvious that we would like to complete quests with the largest value of $b_i$ among the first $i$ of them. So the answer to the problem is the maximum of $\\sum\\limits_{j=1}^{i} a_j + \\max\\limits_{j=1}^{i} b_j \\cdot (k - i)$ over all values of $i$ from $1$ to $\\min(n, k)$. Note that the value of $n$ is too large to calculate sums and maximums in the aforementioned formula every time (for each $i$ independently), so you have to maintain these values as the value for $i$ grows.",
    "code": "fun main() = repeat(readLine()!!.toInt()) {\n  val (n, k) = readLine()!!.split(\" \").map { it.toInt() }\n  val a = readLine()!!.split(\" \").map { it.toInt() }\n  val b = readLine()!!.split(\" \").map { it.toInt() }\n  var (res, sum, mx) = intArrayOf(0, 0, 0)\n  for (i in 0 until minOf(n, k)) {\n    sum += a[i]\n    mx = maxOf(mx, b[i])\n    res = maxOf(res, sum + mx * (k - i - 1))\n  }\n  println(res)\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1914",
    "index": "D",
    "title": "Three Activities",
    "statement": "Winter holidays are coming up. They are going to last for $n$ days.\n\nDuring the holidays, Monocarp wants to try all of these activities \\textbf{exactly once} with his friends:\n\n- go skiing;\n- watch a movie in a cinema;\n- play board games.\n\nMonocarp knows that, on the $i$-th day, exactly $a_i$ friends will join him for skiing, $b_i$ friends will join him for a movie and $c_i$ friends will join him for board games.\n\nMonocarp also knows that he can't try more than one activity in a single day.\n\nThus, he asks you to help him choose three \\textbf{distinct} days $x, y, z$ in such a way that the total number of friends to join him for the activities ($a_x + b_y + c_z$) is maximized.",
    "tutorial": "The main idea of the problem is that almost always you can take the maximum in each array. And when you can't, you don't need to look at a lot of smaller numbers. In particular, it is enough to consider the three largest numbers from each array. Let's show the correctness of this for the first array. There always exists an optimal answer in which one of the three largest numbers is taken from array $a$. Let's fix some taken elements in arrays $b$ and $c$. Then at least one of the three positions of the largest elements in $a$ is different from both fixed position. The argument is generalized to all three arrays similarly. Thus, the solution looks as follows. Find the positions of the three maximums in each array and iterate over the answer in $3^3$. Finding three maximums can be done using sorting or in one linear time pass over the array.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\tb = list(map(int, input().split()))\n\tc = list(map(int, input().split()))\n\t\n\tdef get_best3(a):\n\t\tmx1, mx2, mx3 = -1, -1, -1\n\t\tfor i in range(len(a)):\n\t\t\tif mx1 == -1 or a[i] > a[mx1]:\n\t\t\t\tmx3 = mx2\n\t\t\t\tmx2 = mx1\n\t\t\t\tmx1 = i\n\t\t\telif mx2 == -1 or a[i] > a[mx2]:\n\t\t\t\tmx3 = mx2\n\t\t\t\tmx2 = i\n\t\t\telif mx3 == -1 or a[i] > a[mx3]:\n\t\t\t\tmx3 = i\n\t\treturn (mx1, mx2, mx3)\n\t\n\tans = 0\n\tfor x in get_best3(a):\n\t\tfor y in get_best3(b):\n\t\t\tfor z in get_best3(c):\n\t\t\t\tif x != y and x != z and y != z:\n\t\t\t\t\tans = max(ans, a[x] + b[y] + c[z])\n\tprint(ans)",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1914",
    "index": "E2",
    "title": "Game with Marbles (Hard Version)",
    "statement": "\\textbf{The easy and hard versions of this problem differ only in the constraints on the number of test cases and $n$. In the hard version, the number of test cases does not exceed $10^4$, and the sum of values of $n$ over all test cases does not exceed $2 \\cdot 10^5$. Furthermore, there are no additional constraints on $n$ in a single test case.}\n\nRecently, Alice and Bob were given marbles of $n$ different colors by their parents. Alice has received $a_1$ marbles of color $1$, $a_2$ marbles of color $2$,..., $a_n$ marbles of color $n$. Bob has received $b_1$ marbles of color $1$, $b_2$ marbles of color $2$, ..., $b_n$ marbles of color $n$. All $a_i$ and $b_i$ are between $1$ and $10^9$.\n\nAfter some discussion, Alice and Bob came up with the following game: players take turns, starting with Alice. On their turn, a player chooses a color $i$ such that \\textbf{both} players have at least one marble of that color. The player then discards one marble of color $i$, and their opponent discards all marbles of color $i$. The game ends when there is no color $i$ such that both players have at least one marble of that color.\n\nThe score in the game is the difference between the number of remaining marbles that Alice has and the number of remaining marbles that Bob has at the end of the game. In other words, the score in the game is equal to $(A-B)$, where $A$ is the number of marbles Alice has and $B$ is the number of marbles Bob has at the end of the game. Alice wants to maximize the score, while Bob wants to minimize it.\n\nCalculate the score at the end of the game if both players play optimally.",
    "tutorial": "Let's change the game in the following way: Firstly, we'll let Bob make all moves. It means that for each color $i$ Bob discarded one marble, while Alice discarded all her marbles. So the score $S$ will be equal to $0 - \\sum_{i}{(b_i - 1)}$. Alice makes the first move by choosing some color $i$ and \"takes back color $i$\". In means that we cancel Bob's move on color $i$ and Alice makes that move instead. How score $S$ will change? Initially, we had $-(b_i - 1)$ contribution to the score, but now contribution becomes $+(a_i - 1)$. In other words, choosing color $i$ gives score $S' = S + (a_i + b_i - 2)$. Note that, the greater $(a_i + b_i)$ the greater $S'$ becomes. Bob makes the second move by \"saving some color $i$\", i. e. he forbids Alice to choose color $i$. It doesn't change score $S$ but now Alice can't choose color $i$ on her turns. Alice and Bob continue playing, by \"taking\" and \"saving\" colors, until Alice will take all non-forbidden colors. As a result, we showed that optimum strategy in the initial game is the same: sort colors by $a_i + b_i$ in decreasing order. Alice chooses $1$-st, $3$-rd, $5$-th and so on colors, while Bob chooses $2$-nd, $4$-th, $6$-th and so on colors. The resulting complexity is $O(n \\log{n})$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n \ntypedef long long li;\n \n// S = sum a_i - sum b_i\n// if Bob made all steps: then S = 0 - sum (b_i - 1)\n// each Alice step: S += (a_i - 1) + (b_i - 1) i. e. the bigger (a_i + b_i) the better\n \nint n;\nvector<int> a, b;\n \ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tb.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> a[i];\n\tfore (i, 0, n)\n\t\tcin >> b[i];\n\treturn true;\n}\n \ninline void solve() {\n\tvector<int> ids(n);\n\tiota(ids.begin(), ids.end(), 0);\n\t\n\tsort(ids.begin(), ids.end(), [&](int i, int j) {\n\t\treturn a[i] + b[i] > a[j] + b[j];\n\t});\n\t\n\tli S = 0;\n\tfore (i, 0, n) {\n\t\tif (i & 1)\n\t\t\tS -= b[ids[i]] - 1;\n\t\telse\n\t\t\tS += a[ids[i]] - 1;\n\t}\n\tcout << S << endl;\n}\n \nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n//\tios_base::sync_with_stdio(false);\n//\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t{\n\tif(read()) {\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1914",
    "index": "F",
    "title": "Programming Competition",
    "statement": "BerSoft is the biggest IT corporation in Berland. There are $n$ employees at BerSoft company, numbered from $1$ to $n$.\n\nThe first employee is the head of the company, and he does not have any superiors. Every other employee $i$ has exactly one direct superior $p_i$.\n\nEmployee $x$ is considered to be a superior (direct or indirect) of employee $y$ if one of the following conditions holds:\n\n- employee $x$ is the direct superior of employee $y$;\n- employee $x$ is a superior of the direct superior of employee $y$.\n\nThe structure of BerSoft is organized in such a way that the head of the company is superior of every employee.\n\nA programming competition is going to be held soon. Two-person teams should be created for this purpose. However, if one employee in a team is the superior of another, they are uncomfortable together. So, teams of two people should be created so that no one is the superior of the other. Note that no employee can participate in more than one team.\n\nYour task is to calculate the maximum possible number of teams according to the aforementioned rules.",
    "tutorial": "Note that the problem basically states the following: you are given a rooted tree; you can pair two vertices $x$ and $y$ if neither $x$ is an ancestor of $y$ nor $y$ is an ancestor of $x$. Each vertex can be used in at most one pair. Calculate the maximum possible number of pairs you can make. Let's look at subtrees of child nodes of the root. If two vertices belong to different subtrees, we can pair them up. So we can slightly rephrase the problem: given $m$ types of objects, with counts $sz_1, sz_2, \\dots, sz_m$, find the maximum number of pairs that can be formed using objects of different types. This is a well-known problem with the following solution. Let $tot$ be the total number of objects and $mx$ be the type that has the maximum number of objects (maximum value of $sz$). If the number of objects of type $mx$ is at most the number of all other objects (i. e. $sz_{mx} \\le tot - sz_{mx}$), then we can pair all objects (except $1$ if the total number of objects is odd). Otherwise, we can create $tot - sz_{mx}$ pairs of the form $(mx, i)$ for all $i$ except $mx$. Now we can return to the original problem. If the first aforementioned option is met for the root, then we know the answer to the problem is $\\frac{tot}{2}$. Otherwise, we can create $tot - sz_{mx}$ pairs, but some nodes from the $mx$-th child's subtree are left unmatched (there are not enough vertices outside that subtree). So we can recursively look at the $mx$-th child subtree and solve the same problem. The only difference is that some number of vertices from that subtree are already matched. To solve this issue, we can add the parameter $k$ - how many vertices in the current subtree are already matched (we care only about the number of them). From the second paragraph, we know that the best situation (we can pair all objects) appears when the maximum value is at most the number of all other objects. Using this fact, we can say that $k$ matched vertices belong to the $mx$-th child's subtree. So we have to modify our check formula from $sz_{mx} \\le tot - sz_{mx}$ to $sz_{mx} - k \\le tot - sz_{mx}$. This process goes on until the current vertex (subtree) is a leaf or the condition is met. This solution works in $O(n)$ if we precalculate the sizes for all the subtrees with a DFS before running it.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 222222;\n \nint n;\nint sz[N];\nvector<int> g[N];\n \nvoid init(int v) {\n  sz[v] = 1;\n  for (int u : g[v]) {\n    init(u);\n    sz[v] += sz[u];\n  }\n}\n \nint calc(int v, int k) {\n  int tot = 0, mx = -1;\n  for (int u : g[v]) {\n    tot += sz[u];\n    if (mx == -1 || sz[mx] < sz[u]) mx = u;\n  }\n  if (tot == 0) return 0;\n  if (sz[mx] - k <= tot - sz[mx])\n    return (tot - k) / 2;\n  int add = tot - sz[mx];\n  return add + calc(mx, max(0, k + add - 1));\n}\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    cin >> n;\n    for (int i = 0; i < n; ++i) g[i].clear();\n    for (int i = 1; i < n; ++i) {\n      int p; cin >> p;\n      g[p - 1].push_back(i);\n    }\n    init(0);\n    cout << calc(0, 0) << '\\n';\n  }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graph matchings",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1914",
    "index": "G2",
    "title": "Light Bulbs (Hard Version)",
    "statement": "\\textbf{The easy and hard versions of this problem differ only in the constraints on $n$. In the hard version, the sum of values of $n$ over all test cases does not exceed $2 \\cdot 10^5$. Furthermore, there are no additional constraints on the value of $n$ in a single test case}.\n\nThere are $2n$ light bulbs arranged in a row. Each light bulb has a color from $1$ to $n$ (\\textbf{exactly two light bulbs for each color}).\n\nInitially, all light bulbs are turned off. You choose a set of light bulbs $S$ that you initially turn on. After that, you can perform the following operations in any order any number of times:\n\n- choose two light bulbs $i$ and $j$ \\textbf{of the same color}, exactly one of which is on, and turn on the second one;\n- choose three light bulbs $i, j, k$, such that both light bulbs $i$ and $k$ \\textbf{are on and have the same color}, and the light bulb $j$ is between them ($i < j < k$), and turn on the light bulb $j$.\n\nYou want to choose a set of light bulbs $S$ that you initially turn on in such a way that by performing the described operations, you can ensure that all light bulbs are turned on.\n\nCalculate two numbers:\n\n- the minimum size of the set $S$ that you initially turn on;\n- the number of sets $S$ of minimum size (taken modulo $998244353$).",
    "tutorial": "Let's call a contiguous segment of lamps closed if the number of lamps for each color is either $0$ or $2$ in this segment. For example, a segment of lamps $[3, 2, 1, 2, 1, 3]$ is closed. Furthermore, let's say that a closed segment of lamps is minimal if it is impossible to split it into multiple closed segments. For example, $[3, 2, 1, 2, 1, 3]$ is minimal, but $[3, 3, 2, 1, 2, 1]$ is not since it can be split into $[3, 3]$ and $[2, 1, 2, 1]$ (which are closed). Each closed segment has the following property: if you start with any lamp in this segment, you cannot \"leave\" this segment; i. e. you cannot use the lamps from this segment to light any lamps outside. To prove this, let's suppose the opposite: we started in the closed segment and managed to turn a lamp of color $x$ outside that segment on (and this was the first lamp outside of the segment we turned on). We could not do it with the operation of the first type, since it would mean that the other lamp of color $x$ is in the segment (so it is not closed); and we could not do it with the operation of the second type, since for every color present in the closed segment, both lamps of that color (and the segment they can light up) belong to the closed segment. For every minimal closed segment, we can light it up using just one lamp (for example, the first lamp). So, to calculate the minimum possible size of a set of lamps $S$ we initially turn on, we can just split the given sequence of colors into minimal closed segments. Unfortunately, calculating the number of possible sets of lamps $S$ is trickier. For every minimal closed segment we got, we can calculate the number of \"starting\" lamps that allow us to light the whole segment, and multiply them. However, not every lamp from a minimal closed segment can be a \"starting\" lamp: for example, in the segment $[3, 2, 1, 2, 1, 3]$, any lamp of color $3$ can be used, but no lamp of other color can be used. To deal with this, let us find all minimal closed segments in the sequence of colors. In the example above, we have to find out that both the segments $[3, 2, 1, 2, 1, 3]$ and $[2, 1, 2, 1]$ are closed; and since lamps of colors $1$ and $2$ belong to the \"inner\" closed segment, they cannot be used to light the whole \"outer\" closed segment. So, if a lamp belongs to any of the \"inner\" closed segments, it cannot be used as a starting lamp. Let's mark all such lamps. We can also show that if a lamp is not marked, it can be used as a starting lamp. It is because if we start with some lamp and try to turn on everything we can with the operations given in the statement, we will get precisely the shortest closed segment that lamp belongs to. Proving it is not that hard: suppose we stopped before turning the whole shortest closed segment on; either we got multiple segments of lamps (and we can turn on everything in between them), or we got a segment which is not closed (and for at least one color, there is exactly one lamp in it; so we can light the other lamp of that color). Okay, let's recap. Our solution consists of the following steps: find all minimal closed segments of lamps; for every \"inner\" segment, mark all lamps in it to show they cannot be used as the starting lamps; split the given sequence of colors into the minimum number of segments; for each segment we got from the split, calculate the number of unmarked lamps and multiply those values. The most difficult part is finding all minimal closed segments of lamps. To get a solution in something like $O(n^2)$, we can do it naively: iterate on the left border of the segment, add the first lamp in the segment, and keep adding next lamps until the number of lamps of each color becomes either $0$ or $2$. That's how the easy version of the problem is solved. For the hard version, this is too slow. We have to find the closed segments faster. In order to do this, we can use hashing. Many hashing methods can help, but in my opinion, the most elegant one is XOR hashing, which works as follows: For each color, generate a random $64$-bit integer and replace both occurrences of that color with the generated number. Then, if the segment is closed, the XOR of all numbers in the segment is equal to $0$ (each color occurs either $0$ or $2$ times, thus each integer is taken either $0$ or $2$ times, and all integers taken twice cancel out). This allows us to find all minimal closed segments in $O(n \\log n)$ as follows: iterate on the array of colors from left to right, maintaining the XOR on the current prefix and a map where, for each XOR we encountered, we store the longest prefix which has that value of XOR. Then, after we process the $i$-th element, we can quickly find the left border of the segment ending in the $i$-th element by looking for the current XOR in the map. Don't forget to update the map after that. That way, we arrive at a solution which works in $O(n \\log n)$, which is enough to solve the hard version.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\n \nint add(int x, int y)\n{\n\treturn (((x + y) % MOD) + MOD) % MOD;\n}\n \nint mul(int x, int y)\n{\n\treturn (x * 1ll * y) % MOD;\n}\n \nmt19937_64 rnd(98275314);\n \nlong long gen()\n{\n\tlong long x = 0;\n\twhile(x == 0)\n\t\tx = rnd();\n\treturn x;\n}\n \nvector<int> c;\nvector<int> g;\n \nint process_block(int l, int r)\n{\n\tint ans = 0;\n\twhile(l < r)\n\t{\n\t\tif(g[l] != -1 && g[l] < r)\n\t\t\tl = g[l];\n\t\telse\n\t\t{\n\t\t\tans++;\n\t\t\tl++;\n\t\t}\n\t}\n\treturn ans;\n}\n \nvoid solve()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tint size = 0, cnt = 1;\n\tc.resize(n * 2);\n\tg.resize(n * 2, -1);\n\tfor(int i = 0; i < 2 * n; i++)\n\t{\n\t\tscanf(\"%d\", &c[i]);\n\t\t--c[i];\n\t}\n\t\n\tvector<long long> val(n);\n\tfor(int i = 0; i < n; i++) val[i] = gen();\n\t\n\tmap<long long, int> last;\n\tlong long cur = 0;\n\tlast[0] = 0;\n\tfor(int i = 0; i < n * 2; i++)\n\t{\n\t\tcur ^= val[c[i]];\n\t\tif(cur == 0)\n\t\t{\n\t\t\tsize++;\n\t\t\tcnt = mul(cnt, process_block(last[0], i + 1));\n\t\t\tlast.clear();\n\t\t}\n\t\telse if(last.count(cur))\n\t\t{\n\t\t\tg[last[cur]] = i + 1;\n\t\t}\n\t\tlast[cur] = i + 1;\n\t}\n\t\n\tprintf(\"%d %d\\n\", size, cnt);\n\tc.clear();\n\tg.clear();\n}\n \nint main()\n{\n\tint t;\n\tscanf(\"%d\", &t);\n\tfor(int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "hashing"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1915",
    "index": "A",
    "title": "Odd One Out",
    "statement": "You are given three digits $a$, $b$, $c$. Two of them are equal, but the third one is different from the other two.\n\nFind the value that occurs exactly once.",
    "tutorial": "You can write three if-statements to find the equal pair, and output the correct answer. A shorter solution: output the bitwise $\\textsf{XOR}$ of $a$, $b$, and $c$. It works, since any number $\\textsf{XOR}$ed with itself is $0$, so the two equal numbers will \"cancel\" and you will be left with the odd number out.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n\nvoid solve() {\n\tint a, b, c;\n\tcin >> a >> b >> c;\n\tcout << (a ^ b ^ c) << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "bitmasks",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1915",
    "index": "B",
    "title": "Not Quite Latin Square",
    "statement": "A Latin square is a $3 \\times 3$ grid made up of the letters $A$, $B$, and $C$ such that:\n\n- in each row, the letters $A$, $B$, and $C$ each appear once, and\n- in each column, the letters $A$, $B$, and $C$ each appear once.\n\nFor example, one possible Latin square is shown below. $$\\begin{bmatrix} A & B & C \\\\ C & A & B \\\\ B & C & A \\\\ \\end{bmatrix}$$You are given a Latin square, but one of the letters was replaced with a question mark $?$. Find the letter that was replaced.",
    "tutorial": "There are many solutions. For example, look at the row with the question mark, and write some if statements to check the missing letter. A shorter solution: find the count of each letter. The one that appears only twice is the missing one.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n\nvoid solve() {\n\tint cnt[3] = {};\n\tfor (int i = 0; i < 9; i++) {\n\t\tchar c;\n\t\tcin >> c;\n\t\tif (c != '?') {cnt[c - 'A']++;}\n\t}\t\n\tfor (int i = 0; i < 3; i++) {\n\t\tif (cnt[i] < 3) {cout << (char)('A' + i) << '\\n';}\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1915",
    "index": "C",
    "title": "Can I Square?",
    "statement": "Calin has $n$ buckets, the $i$-th of which contains $a_i$ wooden squares of side length $1$.\n\nCan Calin build a square using \\textbf{all} the given squares?",
    "tutorial": "You should add up all the values to get the sum $s$. Then we just need to check if $s$ is a perfect square. There are many ways, for example you can use inbuilt sqrt function or binary search. Be careful with precision errors, since sqrt function might return a floating-point type.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nbool is_square(ll x) {\n    ll l = 1, r = 1e9;\n    while(l <= r) {\n        ll mid = l + (r - l) / 2;\n        if(mid * mid == x) return true;\n        if(mid * mid > x) r = mid - 1;\n        else l = mid + 1;\n    }      \n    return false;  \n}\nvoid solve() {\n    ll n; cin >> n;\n    ll s = 0;\n    for(int i = 0, x; i < n; ++i) {\n        cin >> x; s += x;\n    }\n    if(is_square(s)) cout << \"YES\\n\";\n    else cout << \"NO\\n\";\n}\n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1915",
    "index": "D",
    "title": "Unnatural Language Processing",
    "statement": "Lura was bored and decided to make a simple language using the five letters $a$, $b$, $c$, $d$, $e$. There are two types of letters:\n\n- vowels — the letters $a$ and $e$. They are represented by $\\textsf{V}$.\n- consonants — the letters $b$, $c$, and $d$. They are represented by $\\textsf{C}$.\n\nThere are two types of syllables in the language: $\\textsf{CV}$ (consonant followed by vowel) or $\\textsf{CVC}$ (vowel with consonant before and after). For example, $ba$, $ced$, $bab$ are syllables, but $aa$, $eda$, $baba$ are not.A word in the language is a sequence of syllables. Lura has written a word in the language, but she doesn't know how to split it into syllables. Help her break the word into syllables.\n\nFor example, given the word $bacedbab$, it would be split into syllables as $ba.ced.bab$ (the dot $.$ represents a syllable boundary).",
    "tutorial": "There are many solutions. Below is the simplest one: Go through the string in reverse (from right to left). If the last character is a vowel, it must be part of $\\textsf{CV}$ syllable - else, $\\textsf{CVC}$ syllable. So we can go back $2$ or $3$ characters appropriately, insert $\\texttt{.}$, and continue. The complexity is $\\mathcal{O}(n)$ if implemented well.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tstring res = \"\";\n\twhile (!s.empty()) {\n\t\tint x;\n\t\tif (s.back() == 'a' || s.back() == 'e') {x = 2;}\n\t\telse {x = 3;}\n\t\t\n\t\twhile (x--) {\n\t\t\tres += s.back();\n\t\t\ts.pop_back();\n\t\t}\n\t\tres += '.';\n\t}\n\tres.pop_back();\n\treverse(res.begin(), res.end());\n\tcout << res << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1915",
    "index": "E",
    "title": "Romantic Glasses",
    "statement": "Iulia has $n$ glasses arranged in a line. The $i$-th glass has $a_i$ units of juice in it. Iulia drinks only from odd-numbered glasses, while her date drinks only from even-numbered glasses.\n\nTo impress her date, Iulia wants to find a contiguous subarray of these glasses such that both Iulia and her date will have the same amount of juice in total if only the glasses in this subarray are considered. Please help her to do that.\n\nMore formally, find out if there exists two indices $l$, $r$ such that $1 \\leq l \\leq r \\leq n$, and $a_l + a_{l + 2} + a_{l + 4} + \\dots + a_{r} = a_{l + 1} + a_{l + 3} + \\dots + a_{r-1}$ if $l$ and $r$ have the same parity and $a_l + a_{l + 2} + a_{l + 4} + \\dots + a_{r - 1} = a_{l + 1} + a_{l + 3} + \\dots + a_{r}$ otherwise.",
    "tutorial": "Let's rewrite the given equation: $a_l + a_{l + 2} + a_{l + 4} + \\dots + a_{r} = a_{l + 1} + a_{l + 3} + \\dots + a_{r-1}$ as $a_l - a_{l+1} + a_{l + 2} - a_{l+3} + a_{l + 4} + \\dots - a_{r-1} + a_{r} = 0.$ How to check this? Let's flip all elements on even indices $a_2 \\to -a_2, a_4 \\to -a_4, \\dots$. Then alternating sums of $[a_1, a_2, a_3, a_4, \\dots]$ are the same as subarray sums on $[a_1, -a_2, a_3, -a_4, \\dots]$. So we just need to check if there is a subarray with sum $0$. This is a standard problem with prefix sums: if two prefix sums are equal, then the subarray between them has sum $0$; otherwise, no subarray has sum $0$. The complexity is $\\mathcal{O}(n)$ or $\\mathcal{O}(n \\log n)$ depending on how you check if two elements of an array are equal. Be careful about using hash tables, as they can be hacked.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define ll long long\n \n#define          all(v)              v.begin(), v.end()\n#define         rall(v)              v.rbegin(),v.rend()\n \n#define            pb                push_back\n#define          sz(a)               (int)a.size()\n\nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n);\n    for(int i = 0; i < n; ++i) cin >> a[i];\n    map<ll, ll> m;\n    ll s = 0;\n    m[0] = 1;\n    for(int i = 0; i < n; ++i) {\n        a[i] *= ((i % 2) ? -1 : 1);\n        s += a[i];\n        if(m[s]) {\n            cout << \"YES\\n\";\n            return;\n        }\n        ++m[s];\n    }\n    cout << \"NO\\n\";\n}\n \nint32_t main() {\n    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1915",
    "index": "F",
    "title": "Greetings",
    "statement": "There are $n$ people on the number line; the $i$-th person is at point $a_i$ and wants to go to point $b_i$. For each person, $a_i < b_i$, and the starting and ending points of all people are distinct. (That is, all of the $2n$ numbers $a_1, a_2, \\dots, a_n, b_1, b_2, \\dots, b_n$ are distinct.)\n\nAll the people will start moving simultaneously at a speed of $1$ unit per second until they reach their final point $b_i$. When two people meet at the same point, they will greet each other once. How many greetings will there be?\n\nNote that a person can still greet other people even if they have reached their final point.",
    "tutorial": "Let's consider two persons $1$ and $2$. When do they meet each other? We can treat a person traveling from point $a$ to point $b$ as a segment $[a, b]$. Notice that they meet when $a_1 < a_2$ and $b_2 < b_1$, or $a_2 < a_1$ and $b_1 < b_2$; or in other words, when one segment contains another. We can count the number of pairs when one fully contains another, which is a quite classic problem, and can be solved by iterating over the segments in increasing order of the $b$ position and for each of them adding the number of segments that we have already passed that have an $a$ value larger than the one of the current segment. The time complexity is $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\n \ntypedef __gnu_pbds::tree<int, __gnu_pbds::null_type, less<int>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> ordered_set;\n \nint t, n;\n \nvector<pair<int, int>> arr;\n \nlong long ans;\n \nordered_set st;\n \nvoid solve(){\n    cin >> n;\n \n    arr.assign(n, {});\n \n    for(auto &p : arr) cin >> p.second >> p.first;\n \n    sort(arr.begin(), arr.end());\n \n    ans = 0;\n    st.clear();\n \n    for(auto p : arr){\n        ans += st.size() - st.order_of_key(p.second);\n \n        st.insert(p.second);\n    }\n \n    cout << ans << \"\\n\";\n}\n \nint main(){\n    ios_base::sync_with_stdio(false);cin.tie(NULL);\n \n    cin >> t;\n \n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1915",
    "index": "G",
    "title": "Bicycles",
    "statement": "All of Slavic's friends are planning to travel from the place where they live to a party using their bikes. And they all have a bike except Slavic. There are $n$ cities through which they can travel. They all live in the city $1$ and want to go to the party located in the city $n$. The map of cities can be seen as an undirected graph with $n$ nodes and $m$ edges. Edge $i$ connects cities $u_i$ and $v_i$ and has a length of $w_i$.\n\nSlavic doesn't have a bike, but what he has is money. Every city has exactly one bike for sale. The bike in the $i$-th city has a slowness factor of $s_{i}$. Once Slavic buys a bike, he can use it \\textbf{whenever} to travel from the city he is currently in to any neighboring city, by taking $w_i \\cdot s_j$ time, considering he is traversing edge $i$ using a bike $j$ he owns.\n\nSlavic can buy as many bikes as he wants as money isn't a problem for him. Since Slavic hates traveling by bike, he wants to get from his place to the party in the shortest amount of time possible. And, since his informatics skills are quite rusty, he asks you for help.\n\nWhat's the shortest amount of time required for Slavic to travel from city $1$ to city $n$? Slavic can't travel without a bike. It is guaranteed that it is possible for Slavic to travel from city $1$ to any other city.",
    "tutorial": "We can build a graph with $n \\cdot 1000$ nodes, where each node is responsible for the pair $(i, s)$, where $i$ is the index of the city and $s$ is the speed we have when we are at this city. Then, we can use Dijkstra's algorithm to compute the shortest path on this graph by considering all edges of node $i$ (when we are at a pair which has $i$ as the city), and the new $s$ would be the minimum value of $s_i$ and $s_j$ where $j$ is the neighboring city we are considering. After computing all shortest paths from node $(1, s_1)$, we just find the minimum value of $(n, j)$ for all $j$ from $1$ to $1000$, and that will be our answer.",
    "code": "#include \"bits/stdc++.h\"\n\nconst int64_t inf = 1e18;\n\nvoid solve() {\n    int n, m; std::cin >> n >> m;\n    std::vector<std::pair<int, int>> adj[n];\n    for(int i = 0; i < m; ++i) {\n        int u, v, w; std::cin >> u >> v >> w; --u, --v;\n        adj[u].emplace_back(v, w);\n        adj[v].emplace_back(u, w);\n    }\n    std::vector<int> s(n);\n    for(int& i: s) std::cin >> i;\n\n    std::vector<std::vector<int64_t>> dist(n, std::vector<int64_t>(1001, inf));\n    std::vector<std::vector<bool>> vis(n, std::vector<bool>(1001, false));\n    \n    dist[0][s[0]] = 0;\n    std::priority_queue<std::array<int64_t, 3>> q;\n    q.push({0, 0, s[0]});\n    while(!q.empty()) {\n        int u = q.top()[1], k = q.top()[2];\n        q.pop();\n        if(vis[u][k] || dist[u][k] == inf) continue;\n        vis[u][k] = true;\n        for(auto x: adj[u]) {\n            int v = x.first, w = x.second;\n            int c = std::min(s[v], k);\n            if(dist[v][c] > dist[u][k] + 1LL * w * k) {\n                dist[v][c] = dist[u][k] + 1LL * w * k;\n                q.push({-dist[v][c], v, c});\n            }\n        }\n    }\n    int64_t ans = inf;\n    for(int k = 1; k <= 1000; ++k) \n        ans = std::min(ans, dist[n - 1][k]);\n    std::cout << ans << \"\\n\";\n}   \n \nint main() {\n    std::ios_base::sync_with_stdio(0);std::cin.tie(0);\n    int t = 1; std::cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "graphs",
      "greedy",
      "implementation",
      "shortest paths",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1916",
    "index": "A",
    "title": "2023",
    "statement": "In a sequence $a$, whose product was equal to $2023$, $k$ numbers were removed, leaving a sequence $b$ of length $n$. Given the resulting sequence $b$, find any suitable sequence $a$ and output which $k$ elements were removed from it, or state that such a sequence could not have existed.\n\nNotice that you are not guaranteed that such array exists.",
    "tutorial": "Let the product of the numbers in our array be $x$. If $2023$ is not divisible by $x$, then the answer is NO, otherwise the answer is YES. One of the ways to construct the removed numbers is as follows-$1$ number $\\frac{2023}{x}$ and $k - 1$ numbers $1$.",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1916",
    "index": "B",
    "title": "Two Divisors",
    "statement": "A certain number $1 \\le x \\le 10^9$ is chosen. You are given two integers $a$ and $b$, which are the two largest divisors of the number $x$. At the same time, the condition $1 \\le a < b < x$ is satisfied.\n\nFor the given numbers $a$, $b$, you need to find the value of $x$.\n\n$^{\\dagger}$ The number $y$ is a divisor of the number $x$ if there is an integer $k$ such that $x = y \\cdot k$.",
    "tutorial": "First case: $b \\mod a = 0$. In this case, $b = a \\cdot p$, where $p$ is the smallest prime factor of $x$. Then $x = b \\cdot p = b \\cdot \\frac{b}{a}$. Second case: $b \\mod a \\neq 0$. In this case, $b = \\frac{x}{p}, a = \\frac{x}{q}$, where $p, q$ are the two smallest prime factors of $x$. Then $\\gcd(a, b) = \\frac{x}{p \\cdot q}, x = b \\cdot p = b \\cdot \\frac{a}{\\gcd(a, b)}$.",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1916",
    "index": "C",
    "title": "Training Before the Olympiad",
    "statement": "Masha and Olya have an important team olympiad coming up soon. In honor of this, Masha, for warm-up, suggested playing a game with Olya:\n\nThere is an array $a$ of size $n$. Masha goes first, and the players take turns. Each move is described by the following sequence of actions:\n\n$\\bullet$ If the size of the array is $1$, the game ends.\n\n$\\bullet$ The player who is currently playing chooses two \\textbf{different} indices $i$, $j$ ($1 \\le i, j \\le |a|$), and performs the following operation — removes $a_i$ and $a_j$ from the array and adds to the array a number equal to $\\lfloor \\frac{a_i + a_j}{2} \\rfloor \\cdot 2$. In other words, first divides the sum of the numbers $a_i$, $a_j$ by $2$ rounding down, and then multiplies the result by $2$.\n\nMasha aims to maximize the final number, while Olya aims to minimize it.\n\nMasha and Olya decided to play on each non-empty prefix of the initial array $a$, and asked for your help.\n\nFor each $k = 1, 2, \\ldots, n$, answer the following question. Let only the first $k$ elements of the array $a$ be present in the game, with indices $1, 2, \\ldots, k$ respectively. What number will remain at the end with optimal play by both players?",
    "tutorial": "Note that our operation replaces two numbers with their sum if they are of the same parity, and with their sum $-1$ otherwise. Therefore, the second player needs to perform as many operations as possible where an even and an odd number are used. Also, note that on any move of the second player, there will be at least one even number that the first player made on the previous move. Then our task for the first player is to remove two odd numbers as often as possible. It can also be observed that the number of odd numbers in the array does not decrease, which means all operations with two odd numbers will go before operations with two even numbers. And after each such move, the second player will remove one odd number from the array. That is, in two moves, the number of odd numbers decreases by $3$. Let's consider all possible remainders of the number of odd numbers modulo $3$. If the remainder is $0$, then the answer is $sum - \\frac{cnt}{3}$, where $sum$ is the sum of all numbers. If the remainder modulo is $1$, then two situations are possible: when the size of the array is $1$ - then the answer is the single number in the array. Otherwise, at the moment when there is $1$ odd number left, there will be one more move of player number $2$, which means he will reduce the total sum once more, and the answer will be $sum - \\lfloor \\frac{cnt}{3} \\rfloor - 1$. If the remainder modulo is $2$, then the number of moves when the second player reduces the sum does not change, so the answer is $sum - \\lfloor \\frac{cnt}{3} \\rfloor$.",
    "tags": [
      "constructive algorithms",
      "games",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1916",
    "index": "D",
    "title": "Mathematical Problem",
    "statement": "The mathematicians of the 31st lyceum were given the following task:\n\nYou are given an \\textbf{odd} number $n$, and you need to find $n$ different numbers that are squares of integers. But it's not that simple. Each number should have a length of $n$ (and should not have leading zeros), and the multiset of digits of all the numbers should be the same. For example, for $\\mathtt{234}$ and $\\mathtt{432}$, and $\\mathtt{11223}$ and $\\mathtt{32211}$, the multisets of digits are the same, but for $\\mathtt{123}$ and $\\mathtt{112233}$, they are not.\n\nThe mathematicians couldn't solve this problem. Can you?",
    "tutorial": "$1.$ For $n = 1$ the answer is $1$. $2.$ For $n = 3$ the answers are $169, 961, 196$. $3.$ How to obtain the answer for $n + 2$: multiply each number for the answer of length $n$ by $100$ (the square of the number $10$), then each number will also remain a square. And we still have 2 numbers left, let's compose them as follows: $9...6...1$, $1...6...9$ where in the gaps between the digits there should be $(n - 3) / 2$ zeros, these will respectively be the squares of numbers $1...3, 3...1$ with $(n - 3) / 2$ zeros in the gaps between the digits. Alternative solution: For $n = 11$ generate 99 such numbers, for $n \\ge 11$ pad them with zeros. For $n < 11$ solve in $O(\\sqrt{10^n})$",
    "tags": [
      "brute force",
      "constructive algorithms",
      "geometry",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1916",
    "index": "E",
    "title": "Happy Life in University",
    "statement": "Egor and his friend Arseniy are finishing school this year and will soon enter university. And since they are very responsible guys, they have started preparing for admission already.\n\nFirst of all, they decided to take care of where they will live for the long four years of study, and after visiting the university's website, they found out that the university dormitory can be represented as a root tree with $n$ vertices with the root at vertex $1$. In the tree, each vertex represents a recreation with some type of activity $a_i$. The friends need to choose $2$ recreations (not necessarily different) in which they will settle. The guys are convinced that the more the value of the following function $f(u, v) = diff(u, lca(u, v)) \\cdot diff(v, lca(u, v))$, the more fun their life will be. Help Egor and Arseniy and find the maximum value of $f(u, v)$ among all pairs of recreations!\n\n$^{\\dagger} diff(u, v)$ — the number of different activities listed on the simple path from vertex $u$ to vertex $v$.\n\n$^{\\dagger} lca(u, v)$ — a vertex $p$ such that it is at the maximum distance from the root and is a parent of both vertex $u$ and vertex $v$.",
    "tutorial": "Let's initiate a tree traversal from the first vertex, in which for each color on the path from the root to the current vertex, we will maintain the nearest vertex with that color, or note that it does not exist. This can be maintained using an array that is recalculated in $O(1)$. Now, for each vertex, let's remember all the vertices for which we are the nearest ancestor with the same color. Build a segment tree on the Euler tour that will support two operations - adding to a segment and finding the maximum. Let's start another traversal of the tree, and for each vertex, we will maintain the count of different colors on the path from it to the vertex we are currently traversing with depth-first search. It is then asserted that we need to add $1$ to the entire subtree of this vertex and subtract $1$ from the subtrees of all vertices for which we are the nearest ancestor with the same color. After that, we need to find the $2$ maximums among all the subtrees of the children and update the answer using them.",
    "tags": [
      "data structures",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1916",
    "index": "F",
    "title": "Group Division",
    "statement": "In the $31$st lyceum, there were two groups of olympiad participants: computer science and mathematics. The number of computer scientists was $n_1$, and the number of mathematicians was $n_2$. It is not known for certain who belonged to which group, but it is known that there were friendly connections between some pairs of people (these connections could exist between a pair of people from the same group or from different groups).\n\nThe connections were so strong that even if one person is removed along with all their friendly connections, any pair of people still remains acquainted either directly or through mutual friends.\n\n$^{\\dagger}$ More formally, two people $(x, y)$ are acquainted in the following case: there are people $a_1, a_2, \\ldots,a_n$ ($1 \\le a_i \\le n_1 + n_2$) such that the following conditions are simultaneously met:\n\n$\\bullet$ Person $x$ is directly acquainted with $a_1$.\n\n$\\bullet$ Person $a_n$ is directly acquainted with $y$.\n\n$\\bullet$ Person $a_i$ is directly acquainted with $a_{i + 1}$ for any ($1 \\le i \\le n - 1$).\n\nThe teachers were dissatisfied with the fact that computer scientists were friends with mathematicians and vice versa, so they decided to divide the students into two groups in such a way that the following two conditions are met:\n\n$\\bullet$ There were $n_1$ people in the computer science group, and $n_2$ people in the mathematics group.\n\n$\\bullet$ Any pair of computer scientists should be acquainted (acquaintance involving mutual friends, who must be from the same group as the people in the pair, is allowed), the same should be true for mathematicians.\n\nHelp them solve this problem and find out who belongs to which group.",
    "tutorial": "We will generate the first set by adding one vertex at a time. Initially, we will include any vertex. Then, to add a vertex from the second set, it must not be a cut vertex and must be connected to some vertex in the first set. Statement: such a vertex always exists. Proof: No cut vertex $\\Rightarrow$ such a vertex exists. Otherwise, consider a cut vertex such that, if removed, at least one of the resulting components will not have any other cut vertices. Then, if none of the vertices in this component is connected to the second component, this cut vertex will be a cut vertex in the original graph. Contradiction. Time - $O(n_1 \\cdot (n_1 + n_2 + m))$",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1916",
    "index": "G",
    "title": "Optimizations From Chelsu",
    "statement": "You are given a tree with $n$ vertices, whose vertices are numbered from $1$ to $n$. Each edge is labeled with some integer $w_i$.\n\nDefine $len(u, v)$ as the number of edges in the simple path between vertices $u$ and $v$, and $gcd(u, v)$ as the Greatest Common Divisor of all numbers written on the edges of the simple path between vertices $u$ and $v$. For example, $len(u, u) = 0$ and $gcd(u, u) = 0$ for any $1 \\leq u \\leq n$.\n\nYou need to find the maximum value of $len(u, v) \\cdot gcd(u, v)$ over all pairs of vertices in the tree.",
    "tutorial": "Let's perform centroid decomposition and maintain the current found answer $ans$. On vertical paths, simply find the value of the function, and we will immediately update the answer, We need to learn how to update the answer for a pair of vertical paths, combining pairs $(g_1, len_1)$ and $(g_2, len_2)$. Let's make several observations. First. If $len_1 \\ge len_2$, then $gcd(g_1, g_2) = g_1$. Because if $gcd(g_1, g_2)$ is not equal to $g_1$, then it is at least twice smaller than $g_1$. Second. From the first fact, we conclude that $g_2 = g_1 \\cdot k$, so in order to make sense to update the answer, we need $g_1 \\cdot (len_1 + len_2) > g_1 \\cdot k \\cdot len_2$ and from here we get that $len_1 > len_2 \\cdot (k - 1)$. This means that $k \\leq len_1$. Let's do the following for a fixed centroid for each component: For each $g$, we will only keep the largest value of $len$, We will iterate over all such pairs and assume that we have fixed the pair $(g_1, len_1)$. For this, we will need to iterate over $1 \\leq k \\leq len_1$. Let's make the following optimization-if $g \\cdot (len + d) \\leq ans$, then there is no need to iterate over $k$, because we are guaranteed not to improve the answer. $d$-is the farthest distance from the centroid to any vertex. We have an upper bound estimate for this solution $O(n \\sqrt n \\log n)$. Let's prove it. For the pair $(len_i, gcd_i)$, we iterate over $k$ such that $1 \\leq k \\leq k_i$, where $k_i \\leq len_i$ and we also cut off by the answer. Let's mark $k_i$ edges on the path from the centroid to the vertex from which this pair came. Let's look at some edge, suppose it is marked $c$ times, the distance from the centroid is $L$, and the $\\gcd$ from the centroid, including this edge, is $g$. This means that we also marked it for some $gcd_i \\leq \\frac{g}{c}$. But we already knew that the answer was at least $g$, which means the size of the current graph is at least $L \\cdot c$. It turns out that we could not have marked an edge at a distance $L$ from the centroid more than $\\frac{n}{L}$ times. We need to estimate in the tree the sum of $min(\\frac{n}{depth[v]}, sz[v])$. It can be estimated as $n \\sqrt n$. For $depth[v] \\leq \\sqrt n$, we have a total size of subtrees at the level of $n$, and then the value $\\frac{n}{depth[v]} \\leq \\sqrt n$.",
    "tags": [
      "divide and conquer",
      "dp",
      "number theory",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1916",
    "index": "H2",
    "title": "Matrix Rank (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only differences between the two versions of this problem are the constraints on $k$. You can make hacks only if all versions of the problem are solved.}\n\nYou are given integers $n$, $p$ and $k$. $p$ is guaranteed to be a prime number.\n\nFor each $r$ from $0$ to $k$, find the number of $n \\times n$ matrices $A$ of the field$^\\dagger$ of integers modulo $p$ such that the rank$^\\ddagger$ of $A$ is exactly $r$. Since these values are big, you are only required to output them modulo $998\\,244\\,353$.\n\n$^\\dagger$ https://en.wikipedia.org/wiki/Field_(mathematics)\n\n$^\\ddagger$ https://en.wikipedia.org/wiki/Rank_(linear_algebra)",
    "tutorial": "Let $dp_{m,k}$ denote the number of $m \\times n$ matrices whose rank is $k$. The recurrence for $dp_{m,k} = dp_{m-1,k} \\cdot p^k + dp_{m-1,k-1} \\cdot (p^n-p^{k-1})$ with the base case of $dp_{0,0}=1$. Consider enumerating $m \\times n$ matrices $A$ such that $\\text{rank}(A)=k$ based on a $(m-1) \\times n$ matrix $B$ and a row vector $C$ such that $A$ is made by appending $C$ to $B$: If $\\text{rank}(B) = \\text{rank}(A)$, then $C$ must be inside the span of $B$ which has size $p^k$. If $\\text{rank}(B)+1=\\text{rank}(A)$, then $C$ must be outside the span of $B$ which has size $p^n-p^{k-1}$. The $p^n-p^{k-1}$ term in our recurrence is annoying to handle. So we will define $g_{m,k}$ as $g_{m,k} = g_{m-1,k} \\cdot p^k + g_{m-1,k-1}$. It should be easy to see that $dp_{m,k}=g_{m,k} \\cdot \\prod\\limits_{i=0}^{k-1} (p^n-p^i)$. Method 1: Easy Version Only We will show how to compute $g_{2m}$ from $g_m$. I claim that $g_{2m,k} = \\sum\\limits_{a+b=k} g_{m,a} \\cdot g_{m,b} \\cdot p^{a(m-b)}$. The justification for this is to consider moving the DP state from $(0,0) \\to (m,a) \\to (2m,a+b)$. The contribution of moving $(m,a) \\to (2m,a+b)$ is actually very similar to that of moving $(0,a) \\to (m,a+b)$, except every time we multiply the value by $p^k$, we have to instead multiply it by $p^{k+a}$. And conveniently, the number of times we need to additionally multiply by $p^k$ is $m-b$. To convolute these sequences, we will use a technique that is similar to chirp-z transform. Note that $ab = \\binom{a+b}{2} - \\binom{a}{2} - \\binom{b}{2}$, you can prove this geometrically by looking at $\\binom{x}{2}$ as a triangle pyramid. $\\begin{aligned} \\sum\\limits_{a+b=k} g_{m,a} \\cdot g_{m,b} \\cdot p^{a(m-b)} &= \\sum\\limits_{a+b=k} g_{m,a} \\cdot g_{m,b} \\cdot p^{am + \\binom{a}{2} + \\binom{b}{2} - \\binom{a+b}{2}} \\\\ &= p^{-\\binom{k}{2}} \\sum\\limits_{a+b=k} (g_{m,a} \\cdot p^{am + \\binom{a}{2}}) \\cdot (g_{m,b} \\cdot p^{\\binom{b}{2}}) \\end{aligned}$ Therefore, it is we can get $g_{2m}$ from $g_m$ by convoluting $(g_{m,i} \\cdot p^{im+\\binom{i}{2}})$ and $(g_{m,i} \\cdot p^{\\binom{i}{2}})$ in $O(k \\log k)$ time. By performing a process similar to fast exponentiation, we can compute $g_n$ in $O(k \\log k \\log n)$. Method 2: Easy Version Only Consider the ordinary generating function $G_k = \\sum\\limits g_{m,k} x^m$. Based on the recurrence above, We have $G_k = x(p^kG_k + G_{k-1})$. This gives us $G_k = \\frac{xG_{k-1}}{1-p^kx} = x^k \\prod\\limits_{i=0}^k \\frac{1}{1-p^ix}$. We want to find $[x^n] G_0, [x^n] G_1, \\ldots, [x^n] G_k$. Notice that $[x^n] G_k = [x^{n-k}] \\prod\\limits_{i=0}^k \\frac{1}{1-p^ix} = [x^k] x^n ~\\%~ (\\prod\\limits_{i=0}^k x-p^i)$. Where $A ~\\%~ B$ denotes the unique polynomial $C$ with $\\text{deg}(C)<\\text{deg}(B)$ and there exists $D$ such that $A = BD + C$. We can compute all required coefficient in a divide and conquer-esque way. Note that $A ~\\%~ B = (A ~\\%~ BC)~\\%~B$. We want $\\text{dnc}(l,r)$ to find all the answers for $[x^n] G_l, [x^n] G_{l+1}, \\ldots, [x^n] G_r$. $\\text{dnc}(l,r)$ will be provided with $P(x)=x^n ~\\%~ (\\prod\\limits_{i=0}^r x-p^i)$ and $Q(x) = \\prod\\limits_{i=0}^{l} x-p^i$. Then the pseudocode of the DnC is as follows: The above code is at least quadratic. However, we only need to save the last $(r-l+1)$ non-zero coefficients from both $P$ and $Q$. If implemented properly, this code runs in $O(k \\log k \\log n)$. Method 3: Hard Version As with the first part of method $2$, we want to find $[x^n] G_0, [x^n] G_1, \\ldots, [x^n] G_k$ where $G_k = x^k \\prod\\limits_{i=0}^k \\frac{1}{1-p^ix}$. We will try to decompose $\\prod\\limits_{i=0}^k \\frac{1}{1-p^ix}$ into partial fractions. Repeated factors in partial fractions is hard to deal with. It turns out, we do not need to deal with them at all. Suppose $ord$ is the smallest positive integer that such $p^{ord} = 1 \\pmod{998244353}$. Then $p^0,p^1,\\ldots,p^{ord-1}$ are all distinct. Furthermore, $dp_{n,k}=0$ for $k \\geq ord$ as $dp_{m,k}=g_{m,k} \\cdot \\prod\\limits_{i=0}^{k-1} (p^n-p^i)$. Therefore, we can safely assume $k < ord$ so that $p^0,p^1,\\ldots,p^k$ will be all distinct. By using the cover-up rule on $\\prod\\limits_{i=0}^k \\frac{1}{1-p^ix}$, we obtain a partial fraction decomposition of $\\sum\\limits_{i=0}^k \\frac{c_i}{1-p^ix}$ where $c_i = \\prod\\limits_{j=0, i\\neq j}^k \\frac{1}{1-p^{j-i}}$. Let $L_i=\\prod_{j=1}^i\\frac 1{1-p^{-j}},R_i=\\prod_{j=1}^i\\frac 1{1-p^j}$,so that $c_i=L_iR_{k-i}$. $\\begin{aligned}[x^n] G_k &= [x^{n-k}] \\prod\\limits_{i=0}^k \\frac{1}{1-p^ix} \\\\ &= [x^{n-k}] \\sum\\limits_{a+b=k} \\frac{L_a R_b}{1-p^ax} \\\\ &= \\sum\\limits_{a+b=k} p^{a(n-k)} L_a R_b \\\\ &=\\sum\\limits_{a+b=k} p^{\\binom{n-b}{2} - \\binom{n-k}{2} - \\binom{a}{2}} L_a R_b \\\\ &=p^{-\\binom{n-k}{2}} \\sum\\limits_{a+b=k} (L_a \\cdot p^{-\\binom{a}{2}}) (R_{b} \\cdot p^{\\binom{n-b}{2}}) \\end{aligned}$ So we can find $[x^n] G_0, [x^n] G_1, \\ldots, [x^n] G_k$ by convoluting $(L_i \\cdot p^{\\binom{i}{2}})$ and $(R_{i} \\cdot p^{\\binom{n-i}{2}})$. The final time complexity is $O(k \\log k)$. Method 4: Hard Version Thanks to Endagorion for finding this solution during testing. For an $n$-dimensional vector space of $\\mathbb{F}_q$, the number of $k$-dimensional vector subspace is denoted as $\\binom{n}{k}_q$ and is known as the q-analogue of binomial coefficients. It is known that $\\binom{n}{k}_q = \\frac{(q^n-1)\\ldots(q^{n-k+1}-1)}{(1-q)\\ldots(1-q^k)}$. This fact is not too hard to derive by considering the number of possible independent sets dividing the the number of sets that results in the same span. Here it is helpful to use the form $\\binom{n}{k}_q = \\frac{[n!]_q}{[k!]_q[n-k!]_q}$ where $[n!]_q = (1) \\cdot (1+q) \\ldots \\cdot (1+q+\\ldots+q^{n-1})$. If you want to read more about these series, I recommend checking out Enumerative Combinatorics. We will proceed with PIE (principle of inclusion-exclusion) on these $q$-binomials. We want to find the number of ways to choose $n$ vectors that spans exactly some $k$-dimensional vector space, but this is hard. However, we realize that we are able to count the number of ways to choose to choose $n$ vectors that spans a subset of some $k$-dimensional vector space. Let $f_k$ and $g_k$ denote these values respectively. Then we have $g_k = \\sum\\limits_{i=0}^k f_i \\cdot \\binom{k}{i}_q$. Note that this is very similar to egf-convolution with the identity sequence. Indeed, if we define the generating functions $F = \\sum f_k \\frac{x^k}{[k!]_q}$, $G = \\sum g_k \\frac{x^k}{[k!]_q}$ and the identity sequence $I = \\sum \\frac{x^k}{[k!]_q}$, we have $F \\cdot I = G$. We are able to calculate $I$ and $G$, so we can find $F = G \\cdot I^{-1}$. Then, the number of matrices with rank $k$ is simply $f_k \\cdot \\binom{n}{k}_q$. Of course, a caveat is that division might not be defined when some $[n!]_q=0$, and it is a simple exercise to the reader to figure out why defining $0^{-1}=0$, which aligns with our usual definition of $a^{MOD-2}=a^{-1}$ does not break anything in the solution. The final time complexity is $O(k \\log k)$.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "matrices",
      "string suffix structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1917",
    "index": "A",
    "title": "Least Product",
    "statement": "You are given an array of integers $a_1, a_2, \\dots, a_n$. You can perform the following operation any number of times (possibly zero):\n\n- Choose any element $a_i$ from the array and change its value to any integer between $0$ and $a_i$ (inclusive). More formally, if $a_i < 0$, replace $a_i$ with any integer in $[a_i, 0]$, otherwise replace $a_i$ with any integer in $[0, a_i]$.\n\nLet $r$ be the minimum possible product of all the $a_i$ after performing the operation any number of times.\n\nFind the minimum number of operations required to make the product equal to $r$. Also, print one such shortest sequence of operations. If there are multiple answers, you can print any of them.",
    "tutorial": "What is the minimum product that we can get, when one of the given numbers is equal to $0$. How is the absolute value of the integer changed, when we apply the given operation on that integer? We can always make the product as small as possible with at most $1$ operation. First, let's find the minimum product we can get. If one of the numbers is or becomes $0$, then the product will be $0$. Otherwise, all the numbers don't change their sign during the operation. So the initial product won't change its sign as well. Also, we can note that the absolute value will not increase after an operation. That means if the initial product is negative, we cannot decrease it. In this case the necessary number of operations will be $0$. If the initial product is positive, then we know the product won't become negative, therefore we will make it zero with $1$ operation, which will be the answer and the operation will be changing any number to $0$. If the initial product is zero, then we don't need to change anything, so the number of operations needed is $0$.",
    "code": "#include <iostream>\n#include <string>\n#include <vector>\n \nusing namespace std;\n \nconst int N = 105;\n \nint t, n;\nint a[N];\n \nint main() {\n    cin >> t;\n    \n    while (t--) {\n        cin >> n;\n        \n        int c_neg = 0;\n        int c_zero = 0;\n        int c_pos = 0;\n        \n        for (int i = 1; i <= n; i++) {\n            cin >> a[i];\n            \n            if (a[i] < 0) {\n                c_neg++;\n            } else if (a[i] == 0) {\n                c_zero++;\n            } else {\n                c_pos++;\n            }\n        }\n        \n        if (c_zero || c_neg % 2) {\n            cout << 0 << endl;\n        } else {\n            cout << 1 << endl;\n            cout << 1 << \" \" << 0 << endl;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1917",
    "index": "B",
    "title": "Erase First or Second Letter",
    "statement": "You are given a string $s$ of length $n$. Let's define two operations you can apply on the string:\n\n- remove the first character of the string;\n- remove the second character of the string.\n\nYour task is to find the number of distinct \\textbf{non-empty} strings that can be generated by applying the given operations on the initial string any number of times (possibly zero), in any order.",
    "tutorial": "Do we need to use the first operation after the second operation? Try to fix the number of the applied first operation. How many different strings can be obtained? When can two reached strings be the same? Try to consider the first occurrence for each letter. Let's first see, that applying the second operation and then the first is equivalent to applying the first operation twice. In the former case the string will become $s_1s_2s_3 \\ldots s_n \\to s_1s_3 \\ldots s_n \\to s_3 \\ldots s_n$, and in the latter case: $s_1s_2s_3 \\ldots s_n \\to s_2s_3 \\ldots s_n \\to s_3 \\ldots s_n$. As we are concerned with only the number of distinct resulting strings, let's assume that the second operation is never done before the first operation. This means we do $op_1$ first operations (possibly zero) and then $op_2$ second operations (possibly zero). Let's now find the result of applying $i$ of the first and then $j$ of the second operations. It's easy to see, that the result is $s_{i+1}s_{i+j+2}s_{i+j+3} \\ldots s_n$. The only remaining question is in which cases two sequences of operations such that the first operation always comes before the second result in the same string. Consider for the $(i_1, j_1)$ pair, the resulting string is the same as for the $(i_2, j_2)$ pair. We can see that $i_1+j_1 = i_2+j_2$, because the number of erased letters should be the same to get strings of the same length. Next, $s_{i_1+1} = s_{i_2+1}$ as those are the first letters of two resulting equal strings. It's easy to see that these conditions are also sufficient for the result to be the same string. If after applying the first operation $op_1$ times the first letter is not its first occurrence, then any subsequent result could have been achieved by less operations of the first type by removing first character until reaching that letter and then by removing the second character until we reach $op_1$ operations in total. This means we need to consider using the second operation only at the first occurrence of the letter. The final solution can look like this: for each letter $a \\ldots z$ find it's first occurrence. If the letter is found, any number of second type operations lead to a different result. Thus we can just calculate the number of second operations that is valid and add that to the answer.",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n \nusing namespace std;\n \nint n, t;\n \nint main() {\n    cin >> t;\n    \n    while (t--) {\n        cin >> n;\n        string s;\n        cin >> s;\n        \n        vector<long long> ans(n, 0);\n        vector<int> nxt(26, n);\n        ans[n - 1] = 1;\n        nxt[s[n - 1] - 'a'] = n - 1;\n    \n        for (int i = n - 2; i >= 0; i--) {\n            ans[i] = ans[i + 1] + (nxt[s[i] - 'a'] - i);\n            nxt[s[i] - 'a'] = i;\n        }\n    \n        cout << ans[0] << endl;\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "data structures",
      "dp",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1917",
    "index": "C",
    "title": "Watering an Array",
    "statement": "You have an array of integers $a_1, a_2, \\ldots, a_n$ of length $n$. On the $i$-th of the next $d$ days you are going to do exactly one of the following two actions:\n\n- Add $1$ to each of the first $b_i$ elements of the array $a$ (i.e., set $a_j := a_j + 1$ for each $1 \\le j \\le b_i$).\n- Count the elements which are equal to their position (i.e., the $a_j = j$). Denote the number of such elements as $c$. Then, you add $c$ to your score, and reset the entire array $a$ to a $0$-array of length $n$ (i.e., set $[a_1, a_2, \\ldots, a_n] := [0, 0, \\ldots, 0]$).\n\nYour score is equal to $0$ in the beginning. Note that on each day you should perform exactly one of the actions above: you cannot skip a day or perform both actions on the same day.\n\nWhat is the maximum score you can achieve at the end?\n\nSince $d$ can be quite large, the sequence $b$ is given to you in the compressed format:\n\n- You are given a sequence of integers $v_1, v_2, \\ldots, v_k$. The sequence $b$ is a concatenation of infinitely many copies of $v$: $b = [v_1, v_2, \\ldots, v_k, v_1, v_2, \\ldots, v_k, \\ldots]$.",
    "tutorial": "Assume that you are starting with array $a=[0, 0, \\ldots, 0]$. Can your score increase by more than $1$ in this case? Note that array $a$ is non-increasing after each operation and $[1, 2, \\ldots, n]$ is strictly increasing. Try fixing the first day you make reset operation on. Can your score increase by more than $n$ on reset operation? Let's first solve this problem if we start with the array $a=[0, 0, \\ldots, 0]$. This array is non-increasing and adding $1$ to any of its prefixes keeps it non-increasing. On the other hand, array $[1, 2, \\ldots, n]$ is strictly increasing. This means that if $a_i=i$ and $a_j=j$ then $i=j$ (because if $i<j$ then $a_i \\ge a_j$ and both conditions cannot hold simultaneously). Thus you cannot increase your score by more than $1$ in one reset operation. Also you cannot increase your score by $1$ in two operations in a row, because array $a$ will be equal to $[0, 0, \\ldots, 0]$ before the second of this operations. Similary, you cannot increase your score on the first day. Thus, the maximum score you can get is $\\lfloor \\frac{d}{2} \\rfloor$. On the other way, you can always achieve this score by alternating operations. So once we fixed the first day $i$ we are making reset operation on, we can easily compute the maximum total score we will get for all the further days. Trying all $d$ possibilities of the first day $i$ we are making reset operation on is too slow. But do we need to wait for this for more than $2n$ days? Actually no because then we will get at most $n$ score for waiting for $2n+1$ days, but we can get the same (or the greater) score by doing the first reset operation on the first day. Thus, we can solve this problem in $\\mathcal{O}(n\\min(n,d))$. Find the number of ways to achieve the maximum score. Solve this problem for the larger $n$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n    int n, k, s;\n    cin >> n >> k >> s;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) cin >> a[i];\n \n    vector<int> b(k);\n    for (int i = 0; i < k; i++) cin >> b[i];\n \n    int ans = 0;\n    for (int i = 0; i < s && i <= 2 * n; i++)\n    {\n        int cur = 0;\n        for (int j = 0; j < n; j++)\n        {\n            cur += (a[j] == j + 1);\n        }\n        cur += (s - i - 1) / 2;\n        if (cur > ans)\n        {\n            ans = cur;\n        }\n        for (int j = 0; j < b[i % k]; j++)\n        {\n            a[j]++;\n        }\n    }\n    cout << ans << endl;\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1917",
    "index": "D",
    "title": "Yet Another Inversions Problem",
    "statement": "You are given a permutation $p_0, p_1, \\ldots, p_{n-1}$ of odd integers from $1$ to $2n-1$ and a permutation $q_0, q_1, \\ldots, q_{k-1}$ of integers from $0$ to $k-1$.\n\nAn array $a_0, a_1, \\ldots, a_{nk-1}$ of length $nk$ is defined as follows:\n\n\\begin{center}\n$a_{i \\cdot k+j}=p_i \\cdot 2^{q_j}$ for all $0 \\le i < n$ and all $0 \\le j < k$\n\\end{center}\n\nFor example, if $p = [3, 5, 1]$ and $q = [0, 1]$, then $a = [3, 6, 5, 10, 1, 2]$.\n\nNote that all arrays in the statement are zero-indexed. Note that each element of the array $a$ is uniquely determined.\n\nFind the number of inversions in the array $a$. Since this number can be very large, you should find only its remainder modulo $998\\,244\\,353$.\n\nAn inversion in array $a$ is a pair $(i, j)$ ($0 \\le i < j < nk$) such that $a_i > a_j$.",
    "tutorial": "How to count the number of inversions in the permutation of length $n$ in $\\mathcal{O}(n \\log n)$? Consider two arrays $x_1, x_2, \\ldots, x_k$ and $\\alpha x_1, \\alpha x_2, \\ldots, \\alpha x_k$ for some positive $\\alpha$. How does the number of inversions in one of them correspond to the number of inversions in the other of them? Consider splitting array $a$ into subarrays of the length $k$. Let's say you have two arrays $[11, 22, 44, \\ldots, 11 \\cdot 2^m]$ and $[13, 26, 52, \\ldots, 13 \\cdot 2^m]$ of the same length. How many inversions are there in their concatenation $[11, 22, 44, \\ldots, 11 \\cdot 2^m, 13, 26, 52, \\ldots, 13 \\cdot 2^m]$? Consider the merging process of arrays $[11, 22, 44, \\ldots, 11 \\cdot 2^m]$ and $[13, 26, 52, \\ldots, 13 \\cdot 2^m]$ into the sorted array (as in the merge sort). What if the first elements of the arrays you concatenate are not $11$ and $13$ but some odd positive integers $x$ and $y$? Merging processes for some pairs $(x, y)$ look quite similar. The number of inversions in the array $[x, 2x, 4x, \\ldots, 2^m x, y, 2y, 4y, \\ldots, 2^m y]$ depends only on $\\lfloor \\log_2(\\frac{y}{x}) \\rfloor$ and $m$. You don't need to think about rounding of $\\log_2(\\frac{y}{x})$ because $x$ and $y$ are odd in this problem. Also, $m$ is the same for all merges. Consider the following $\\mathcal{O}(n \\log n)$ algorithm to find the number of inversions in the permutation: make a segment tree corresponding to this permutation and fill it with zeroes. For all $i$ from $1$ to $n$ find $j$ such that $p_j=i$, increase the $j$-th element of this segment tree by $1$ and add the sum of elements on the right of the $j$-th element to the number of inversions. Improve this algorithm to count the number of inversions in array $a$ assuming $q=[0,1,\\ldots,k-1]$. The problem can be solved in $\\mathcal{O}(n \\log n \\min(\\log n, k) + k \\log k)$. The order of elements in $q$ matters only on the inversions inside the blocks of length $k$ you chosen in the hint $2$. Let's split the array $a$ into subarrays of the length $k$. The relative order of the elements in each of them is the same (as in permutation $q$), so the number of inversions is the same, too. You can find the number of invesions in one of them as described in the hint $7$. By multiplying this number by $n$, you count all the in-block inversions. All the remaining inversions are formed by pairs of elements from the distinct blocks. You may assume that $q=[0, 1, \\ldots, k-1]$ now for simplicity: it won't change the number of such inversions. Let's fix two elements $x$ and $y$ of $p$ and count the number of inversions $(i, j)$ such that $a_i = x \\cdot 2^{\\alpha}$ and $a_j = y \\cdot 2^{\\beta}$ for some $\\alpha$ and $\\beta$. It is equivalent to counting the number of inversions in the array $[x, 2x, 4x, \\ldots, 2^mx, y, 2y, 4y, \\ldots, 2^my]$. Consider merging two arrays $[x, 2x, 4x, \\ldots, 2^mx]$ and $[y, 2y, 4y, \\ldots, 2^my]$ with $x < y$ ($x$ and $y$ are odd) into one sorted subarray: if $\\color{blue}{x} < \\color{red}{y} < \\color{blue}{2x}$, then the resulting array would look like $[\\color{blue}{x}, \\color{red}{y}, \\color{blue}{2x}, \\color{red}{2y}, \\color{blue}{4x}, \\color{red}{4y}, \\ldots, \\color{blue}{2^mx}, \\color{red}{2^my}]$; if $\\color{blue}{2x} < \\color{red}{y} < \\color{blue}{4x}$, then the resulting array would look like $[\\color{blue}{x}, \\color{blue}{2x}, \\color{red}{y}, \\color{blue}{4x}, \\color{red}{2y}, \\color{blue}{8x}, \\color{red}{4y}, \\ldots, \\color{blue}{2^{m-1}x}, \\color{red}{2^{m-2}y}, \\color{blue}{2^mx}, \\color{red}{2^{m-1}y}, \\color{red}{2^my}]$; if $\\color{blue}{4x} < \\color{red}{y} < \\color{blue}{8x}$, then the resulting array would look like $[\\color{blue}{x}, \\color{blue}{2x}, \\color{blue}{4x}, \\color{red}{y}, \\color{blue}{8x}, \\color{red}{2y}, \\color{blue}{16x}, \\color{red}{4y}, \\ldots, \\color{blue}{2^{m-1}x}, \\color{red}{2^{m-3}y}, \\color{blue}{2^mx}, \\color{red}{2^{m-2}y}, \\color{red}{2^{m-1}y}, \\color{red}{2^my}]$; ... You can see several blue elements in the beginning, followed by alternating blue and red elements, which are followed by several red elements. The number of blue elements in the beginning is equal to the number of red elements in the end and equal to the largest $z$ such that $2^z x < y$. Furthermore, this $z$ is also limited by $\\log n + 1$ because $x$ and $y$ are both positive integers less than $2n$. If $x > y$ the situation is similar, but the order of colors is reversed. Going back to inversions, we have some array $[\\color{blue}{x}, \\color{blue}{2x}, \\color{blue}{4x}, \\ldots, \\color{blue}{2^mx}, \\color{red}{y}, \\color{red}{2y}, \\color{red}{4y}, \\ldots, \\color{red}{2^my}]$. Inversions are formed by a large blue element and a small red element. if $x < y < 2x$, then there are $0+1+2+\\ldots+m=\\frac{m(m+1)}{2}$ inversions; if $2x < y < 4x$, the there are $0+0+1+2+\\ldots+(m-1)=\\frac{m(m+1)}{2} - m$ inversions; if $4x < y < 8x$, the there are $0+0+0+1+2+\\ldots+(m-2)=\\frac{m(m+1)}{2} - m - (m-1)$ inversions; ... For $x > y$ the situation is similar, but we will start with $1+2+3+\\ldots+m+(m+1)=\\frac{(m+1)(m+2)}{2}$ inversions for $y < x < 2y$ and we will add $m, (m-1), \\ldots$ terms instead of substracting them. Well, now we can solve this problem in $\\mathcal{O}(n^2 \\log n)$: enumerate pairs $(x, y)$, find $\\log_2(\\frac{y}{x})$ and add some value to the answer. Now let's add the inversion counting algorithm to solve this problem. Again, let's solve the problem for $x < y$ first. Let's enumerate the value of $y$ from $1$ to $2n-1$. the $x$-s on the right of $y$ should not be counted in now; each of the $x$-s on the left of $y$ such that $x < y$ adds $\\frac{m(m+1)}{2}$ to the answer; each of the $x$-s on the left of $y$ such that $2x < y$ adds $\\frac{m(m+1)}{2} - m$ to the answer; each of the $x$-s on the left of $y$ such that $4x < y$ adds $\\frac{m(m+1)}{2} - m - (m-1)$ to the answer; ... We can maintain a segment tree to compute the sum of the values we should sum up. To update this segment tree let's additionally maintain $\\Theta(\\log n)$ pointers that maintain the largest $x$ such that $2^z x < y$ for each $z$ from $0$ to $\\lceil\\log n\\rceil$. The solution is similar for $x > y$ pairs. You should be careful when implementing this, because for small $k$ at some moment there becomes $0$ elements in the alternating segment of the blue-red array and you shouldn't substract anything further. You are also given $s$ queries of the following two types: Swap $p_i$ and $p_j$ Swap $q_i$ and $q_j$. Perform these queries and maintain the answer. You given three permutations $p$, $q$ and $r$ of lengths $l_1$, $l_2$, $l_3$ (of the first $l_1$, $l_2$ and $l_3$ positive integers correspondingly) and array $a$ is defined as $a[i \\cdot l_2 \\cdot l_3 + j \\cdot l_3 + k] = p[i] \\cdot 2^{q[j]} \\cdot 2^{2^{r[k]}}$. Find the number of inversions in it.",
    "code": "const int MOD = 998'244'353;\n \n#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid add(int pos, long long val, vector<long long>& fenw)\n{\n    while (pos < fenw.size())\n    {\n        fenw[pos] += val;\n        fenw[pos] = (fenw[pos] % MOD + MOD) % MOD;\n        pos |= (pos + 1);\n    }\n}\n \nlong long get(int pos, vector<long long>& fenw)\n{\n    long long res = 0;\n    while (pos >= 0)\n    {\n        res += fenw[pos];\n        res %= MOD;\n        pos &= (pos + 1);\n        pos--;\n    }\n    return res;\n}\n \nlong long get(int l, int r, vector<long long>& fenw)\n{\n    long long vr = get(r, fenw);\n    long long vl = get(l - 1, fenw);\n    return ((vr - vl) % MOD + MOD) % MOD;\n}\n \nvoid solve()\n{\n    int n, k;\n    cin >> n >> k;\n    vector<int> p(n), q(k);\n    for (int i = 0; i < n; i++) cin >> p[i];\n    for (int i = 0; i < k; i++) cin >> q[i];\n \n    long long ans = 0;\n \n    {\n        vector<long long> fenwE(k);\n        for (int i = 0; i < k; i++)\n        {\n            ans += i - get(q[i], fenwE);\n            add(q[i], 1, fenwE);\n        }\n        ans = ans * n % MOD;\n    }\n \n    vector<int> pos(2 * n);\n    for (int i = 0; i < n; i++) pos[p[i]] = i;\n \n    vector<long long> fenwT(n), fenw(n);\n    vector<long long> shT(n);\n \n    const int LG = 20;\n \n    vector<long long> shiftContrib(LG);\n    for (int i = 0; i < LG && i < k; i++)\n    {\n        shiftContrib[i] = 1ll * (k - i + 1) * (k - i) / 2;\n        shiftContrib[i] %= MOD;\n    }\n \n    vector<int> pnt(min(LG, k), 1);\n    for (int num = 1; num <= 2 * n - 1; num += 2)\n    {\n        for (int j = 0; j < LG && j < k; j++)\n        {\n            while ((1ll << j) * pnt[j] < num)\n            {\n                int p = pos[pnt[j]];\n                shT[p]++;\n                add(p, shiftContrib[shT[p]] - shiftContrib[shT[p] - 1], fenwT);\n                pnt[j] += 2;\n            }\n        }\n \n        int i = pos[num];\n        add(i, shiftContrib[0], fenwT);\n        add(i, 1, fenw);\n        ans += get(0, i - 1, fenwT);\n        ans += get(i + 1, n - 1, fenw) * (1ll * k * k % MOD) - get(i + 1, n - 1, fenwT);\n        ans = (ans % MOD + MOD) % MOD;\n    }\n \n    cout << ans << \"\\n\";\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n \n    int t;\n    cin >> t;\n    while (t--)\n    {\n        solve();\n    }\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1917",
    "index": "E",
    "title": "Construct Matrix",
    "statement": "You are given an \\textbf{even} integer $n$ and an integer $k$. Your task is to construct a matrix of size $n \\times n$ consisting of numbers $0$ and $1$ in such a way that the following conditions are true, or report that it is impossible:\n\n- the sum of all the numbers in the matrix is exactly $k$;\n- the bitwise $XOR$ of all the numbers in the row $i$ is the same for each $i$;\n- the bitwise $XOR$ of all the numbers in the column $j$ is the same for each $j$.",
    "tutorial": "Does solution exist when $k$ is odd? What can you understand when $k = 2$ or $k = n^2 - 2$? How can we easily fill the matrix with $1$s, such that all problem conditions are satisfied when $k$ is divisible by $4$? How will you solve the problem when $k = 6$? Try to merge ideas of Hint $3$ and Hint $4$ together. First, let's note that when $k$ is odd, the solution doesn't exist. It's obvious since in the solution the xors of all the rows are the same, it follows that the parity of the number of $1$s in each row is the same, and let's remember that $n$ is even, and from these conditions get that solution exists only when $k$ is even. Second, let's note that for $k = 2$ or $k = n^2 - 2$, the solution exists only for $n = 2$. For all other cases, a solution always exists. when $k \\equiv 0 \\pmod{4}$, we can fill $\\frac{k}{4}$ submatrices of size $2 \\times 2$. when $k \\equiv 2 \\pmod{4}$. Let's note that $k \\geq 6$. Let's write $1$ in the following positions: $(1, 1)$, $(1, 2)$, $(2, 1)$, $(2, 3)$, $(3, 2)$, $(3, 3)$. After this, we should fill the remaining $(k - 6)$ ones, and let's note that $(k - 6) \\equiv 0 \\pmod{4}$. There are obvious $\\frac{n^2 - 16}{4}$ submatrices of size $2 \\times 2$, which aren't filled yet - outside the top left $4 \\times 4$ submatrix. If $k < n^2 - 6$, then we can fill as many of those $2 \\times 2$ submatrices as necessary, otherwise if $k = n^2 - 6$, we can also fill with $1$s the following $4$ positions too: $(1, 3)$, $(1, 4)$, $(4, 3)$, $(4, 4)$. Can you solve the problem for odd $n$? tourist solved it!",
    "code": "///////////////////////////////    _LeMur_\n#define _CRT_SECURE_NO_WARNINGS\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <iostream>\n#include <cstring>\n#include <cassert>\n#include <complex>\n#include <chrono>\n#include <random>\n#include <bitset>\n#include <cstdio>\n#include <vector>\n#include <string>\n#include <stack>\n#include <tuple>\n#include <queue>\n#include <ctime>\n#include <cmath>\n#include <list>\n#include <map>\n#include <set>\n \nusing namespace std;\n \nconst int N = 300005;\nconst int inf = 1000 * 1000 * 1000;\nconst int mod = 998244353;\n// mt19937 myrand(chrono::steady_clock::now().time_since_epoch().count());\nmt19937 myrand(373);\n \nint t;\nint n, k;\n \nvoid print(vector < vector<int> > &answ) {\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      cout << answ[i][j] << \" \";\n    }\n    cout << endl;\n  }\n}\n \nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n \n  cin >> t;\n \n  while (t--) {\n    cin >> n >> k;\n \n    if (k % 2) {\n      cout << \"No\" << endl;\n      continue;\n    }\n \n    if (k == 2 || k == n * n - 2) {\n      if (n != 2) {\n        cout << \"No\" << endl;\n      } else {\n        cout << \"Yes\" << endl;\n        cout << \"1 0\" << endl;\n        cout << \"1 0\" << endl;\n      }\n      continue;\n    }\n \n    cout << \"Yes\" << endl;\n \n    vector < vector<int> > answ(n, vector<int>(n, 0));\n \n    if (k % 4 == 0) {\n      int c = k / 4;\n      for (int i = 0; i < n; i += 2) {\n        for (int j = 0; j < n; j += 2) {\n          if (c > 0) {\n            answ[i][j] = 1;\n            answ[i][j + 1] = 1;\n            answ[i + 1][j] = 1;\n            answ[i + 1][j + 1] = 1;\n            --c;\n          }\n        }\n      }\n      print(answ);\n      continue;\n    }\n \n    assert(k >= 6);\n \n    answ[0][0] = 1;\n    answ[0][1] = 1;\n    answ[1][0] = 1;\n    answ[1][2] = 1;\n    answ[2][1] = 1;\n    answ[2][2] = 1;\n \n    int c = (k - 6) / 4;\n    for (int i = 0; i < n; i += 2) {\n      for (int j = 0; j < n; j += 2) {\n        if (i == 0 && j == 0) continue;\n        if (i == 0 && j == 2) continue;\n        if (i == 2 && j == 2) continue;\n        if (i == 2 && j == 0) continue;\n        if (c > 0) {\n          answ[i][j] = 1;\n          answ[i][j + 1] = 1;\n          answ[i + 1][j] = 1;\n          answ[i + 1][j + 1] = 1;\n          --c;\n        }\n      }\n    }\n \n    assert(c <= 1);\n \n    if (c == 1) {\n      answ[0][2] = answ[0][3] = 1;\n      answ[3][2] = answ[3][3] = 1;\n    }\n \n    print(answ);\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1917",
    "index": "F",
    "title": "Construct Tree",
    "statement": "You are given an array of integers $l_1, l_2, \\dots, l_n$ and an integer $d$. Is it possible to construct a tree satisfying the following three conditions?\n\n- The tree contains $n + 1$ nodes.\n- The length of the $i$-th edge is equal to $l_i$.\n- The (weighted) diameter of the tree is equal to $d$.",
    "tutorial": "If a solution exists, then we can always construct a tree containing a diameter and edges incident to the vertex $v$ ($v$ is from diameter). Try to consider the maximum of the given lengths. What can we say when there exist two lengths with a sum greater than $d$? If a solution exists, then there should be a subset of lengths with the sum equal to $d$. Consider cases when there exists a subset of lengths containing the maximum length with the sum equal to $d$ and doesn't. Knapsack with bitset. Let's consider the lengths in increasing order: $l_1 \\leq l_2 \\leq \\ldots \\leq l_n$. We will discuss some cases depending on the maximum length $l_n$: If $l_n + l_{n - 1} > d$, then the solution doesn't exist since an arbitrary tree will have a diameter greater than $d$. There exists the subset of the given lengths $l$, such that the sum of the lengths of that subset is equal to $d$ (for making a diameter) and $l_n$ is in that subset. In this case, the solution always exists, since we can construct a tree for example in the following way: let's consider that the size of the found subset is equal to $k$, then we can connect the vertices from $1$ to $k + 1$, such that the vertices $i$ and $i + 1$ are connected by edge for each $1 \\leq i \\leq k$ and $length(1, 2) = l_n$. We have some remaining lengths that we haven't used yet, so we can add edges for each length incident to the vertex $2$. Added edges will not increase the diameter, since $l_n$ is greater than or equal to all the remaining edges and $l_n + l_{n - 1} \\leq d$. To check if there exists a subset of lengths such that it contains $l_n$ and the sum of elements in the subset is equal to $d$, can be easily done by the knapsack algorithm. Here, we need to find the subset of the given lengths $l$, such that the sum of the lengths of that subset is equal to $d$ (for making a diameter and we also know that $l_n$ can not be in that subset). Let's consider that diameter consisting of the vertices $v_1$, $v_2$, $\\ldots$, $v_k$, such that $v_i$ and $v_{i + 1}$ are connected by edge for each $1 \\leq i \\leq k - 1$. Now, we need to connect an edge with length $l_n$ to the one vertex $v'$ from diameter, such that both $dist(v', v_1) + l_n < d$ and $dist(v', v_k) + l_n < d$. All the other not-used lengths we can also connect to the vertex $v'$. To check this, we should write knapsack but with two states: $dist(v', v_1)$ and $dist(v', v_k)$. Knapsack can be done using bitset and the final complexity will be $O(\\frac{n \\cdot d^2}{64})$. You can also optimize this two times, since we know that the minimum of $dist(v', v_1)$ and $dist(v', v_k)$ is at most $\\frac{d}{2}$.",
    "code": "///////////////////////////////    _LeMur_\n#define _CRT_SECURE_NO_WARNINGS\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <iostream>\n#include <cstring>\n#include <cassert>\n#include <complex>\n#include <chrono>\n#include <random>\n#include <bitset>\n#include <cstdio>\n#include <vector>\n#include <string>\n#include <stack>\n#include <tuple>\n#include <queue>\n#include <ctime>\n#include <cmath>\n#include <list>\n#include <map>\n#include <set>\n \nusing namespace std;\n \nconst int N = 2005;\nconst int D = 2005;\nconst int inf = 1000 * 1000 * 1000;\nconst int mod = 998244353;\n// mt19937 myrand(chrono::steady_clock::now().time_since_epoch().count());\nmt19937 myrand(373);\n \nint t;\nint n, d;\n \npair <int, int> p[N];\nbitset<D> dp[D / 2];\n \nvoid add(int id) {\n  int len = p[id].first;\n  for (int i = d / 2; i >= 0; i--) {\n    if (i + len <= d / 2) dp[i + len] |= dp[i];\n    dp[i] = (dp[i] | (dp[i] << len));\n  }\n}\n \nint main() {\n  ios_base::sync_with_stdio(false);\n  cin.tie(NULL);\n \n  cin >> t;\n  \n  while (t--) {\n    cin >> n >> d;\n \n    int mx = 0;\n    int sum = 0;\n \n    for (int i = 1; i <= n; i++) {\n      cin >> p[i].first;\n      sum += p[i].first;\n      p[i].second = i;\n      mx = max(mx, p[i].first);\n    }\n \n    sort(p + 1, p + n + 1);\n \n    if (sum == d) {\n      cout << \"Yes\" << endl;\n      continue;\n    }\n \n    for (int i = 0; i <= d / 2; i++) {\n      for (int j = 0; j <= d; j++) {\n        dp[i][j] = 0;\n      }\n    }\n    dp[0][0] = 1;\n \n    bool found = false;\n    int it = 1;\n \n    for (int x = 1; x <= d / 2; x++) {\n      while (it <= n && p[it].first <= x) {\n        add(it);\n        ++it;\n      }\n \n      int big = 0;\n      for (int i = it; i <= n; i++) {\n        big += p[i].first;\n      }\n \n      if (big <= d - x && dp[x][d - x - big]) {\n        found = true;\n        break;\n      }\n    }\n \n    if (!found) {\n      cout << \"No\" << endl;\n    } else {\n      cout << \"Yes\" << endl;\n    }\n  }\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1918",
    "index": "A",
    "title": "Brick Wall",
    "statement": "A brick is a strip of size $1 \\times k$, placed horizontally or vertically, where $k$ can be an arbitrary number that is at least $2$ ($k \\ge 2$).\n\nA brick wall of size $n \\times m$ is such a way to place several bricks inside a rectangle $n \\times m$, that all bricks lie either horizontally or vertically in the cells, do not cross the border of the rectangle, and that each cell of the $n \\times m$ rectangle belongs to exactly one brick. Here $n$ is the height of the rectangle $n \\times m$ and $m$ is the width. \\textbf{Note} that there can be bricks with different values of k in the same brick wall.\n\nThe wall stability is the difference between the number of horizontal bricks and the number of vertical bricks. \\textbf{Note} that if you used $0$ horizontal bricks and $2$ vertical ones, then the stability will be \\textbf{$-2$, not $2$}.\n\nWhat is the maximal possible stability of a wall of size $n \\times m$?\n\nIt is guaranteed that under restrictions in the statement at least one $n \\times m$ wall exists.",
    "tutorial": "The stability of the wall is the number of horizontal bricks minus the number of vertical bricks. Since a horizontal brick has a length of at least $2$, no more than $\\lfloor\\frac{m}{2}\\rfloor$ horizontal bricks can be placed in one row. Therefore, the answer does not exceed $n \\cdot \\lfloor\\frac{m}{2}\\rfloor$. On the other hand, if horizontal bricks of length $2$ are placed in a row, and when $m$ is odd, the last brick has a length of $3$, then in each row there will be exactly $\\lfloor\\frac{m}{2}\\rfloor$ horizontal bricks, and there will be no vertical bricks in the wall at all. This achieves the maximum stability of $n \\cdot \\lfloor\\frac{m}{2}\\rfloor$. The solution is one formula, so it works in $O(1)$ time.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int64_t n,m;\n        cin >> n >> m;\n        cout << n*(m/2) << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1918",
    "index": "B",
    "title": "Minimize Inversions",
    "statement": "You are given two permutations $a$ and $b$ of length $n$. A permutation is an array of $n$ elements from $1$ to $n$ where all elements are distinct. For example, an array [$2,1,3$] is a permutation, but [$0,1$] and [$1,3,1$] aren't.\n\nYou can (as many times as you want) choose two indices $i$ and $j$, then swap $a_i$ with $a_j$ and $b_i$ with $b_j$ simultaneously.\n\nYou hate inversions, so you want to minimize the total number of inversions in both permutations.\n\nAn inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i < j$ and $p_i > p_j$. For example, if $p=[3,1,4,2,5]$ then there are $3$ inversions in it (the pairs of indices are $(1,2)$, $(1,4)$ and $(3,4)$).",
    "tutorial": "Notice that by performing operations of the form: swap $a_i$ with $a_j$ and $b_i$ with $b_j$ simultaneously, we can rearrange the array $a$ how we want, but the same $a_i$ will correspond to the same $b_i$ (because we are changing both $a_i$ and $b_i$ at the same time). Let's sort the array $a$ using these operations. Then the sum of the number of inversions in $a$ and $b$ will be the number of inversions in $b$, since $a$ is sorted. It is claimed that this is the minimum sum that can be achieved. Proof: Consider two pairs of elements $a_i$ with $a_j$ and $b_i$ with $b_j$ ($i$ < $j$). In each of these pairs, there can be either $0$ or $1$ inversions, so among the two pairs, there can be $0$, $1$, or $2$ inversions. If there were $0$ inversions before the operation, then there will be $2$ after the operation; if there was $1$, then there will still be $1$; if there were $2$, then it will become $0$. If the permutation $a_i$ is sorted, then in each pair of indices $i$ and $j$ there will be a maximum of 1 inversion, so any pair of indices will give no more inversions than if they were swapped. Since the number of inversions in each pair is the minimum possible, the total number of inversions is also the minimum possible. Time complexity: $O(n \\log n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int n;\n        cin >> n;\n        pair<int,int> ab[n];\n        for(int i = 0;i < n;++i)\n        {\n            cin >> ab[i].first;\n        }\n        for(int i = 0;i < n;++i)\n        {\n            cin >> ab[i].second;\n        }\n        sort(ab,ab+n);\n        for(int i = 0;i < n;++i)\n        {\n            cout << ab[i].first << ' ';\n        }\n        cout << \"\\n\";\n        for(int i = 0;i < n;++i)\n        {\n            cout << ab[i].second << ' ';\n        }\n        cout << \"\\n\";\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1918",
    "index": "C",
    "title": "XOR-distance",
    "statement": "You are given integers $a$, $b$, $r$. Find the smallest value of $|({a \\oplus x}) - ({b \\oplus x})|$ among all $0 \\leq x \\leq r$.\n\n$\\oplus$ is the operation of bitwise XOR, and $|y|$ is absolute value of $y$.",
    "tutorial": "Let's consider the bitwise representation of numbers $a$, $b$, $x$. Let's look at any $2$ bits at the same position in $a$ and $b$, if they are the same, then regardless of what is in $x$ on this position, the number $|({a \\oplus x}) - ({b \\oplus x})|$ will have a $0$ at this position. Therefore, it is advantageous to set $0$ at all such positions in $x$ (since we want $x \\leq r$, and the answer does not depend on the bit). If the bits in $a$ and $b$ at the same position are different, then at this position there will be a $1$ either in $a \\oplus x$ or in $b \\oplus x$ depending on what is at this position in $x$. Let $a$ < $b$, if not, then we will swap them. Then at the highest position, where the bits differ, there is a $0$ in $a$ and a $1$ in $b$. There are $2$ options, either to set a $1$ at this position in $x$ (and then there will be a $1$ in $a \\oplus x$), or to set a $0$ in $x$ (and then there will be a $0$ in $a \\oplus x$). Suppose we set $0$ in $x$, then $a \\oplus x$ will definitely be less than $b \\oplus x$ (because in the highest differing bit, $a \\oplus x$ has $0$, and $b \\oplus x$ has $1$). Therefore, it is advantageous to set $1$ in $a \\oplus x$ on all next positions, as this will make their difference smaller. Therefore, we can go through the positions in descending order, and if the position is differing, then we will set a $1$ in $a \\oplus x$ at this position if possible (if after this $x$ does not exceed $r$). The second case (when we set $1$ in $x$ at the position of the first differing bit) is analyzed similarly, but in fact it is not needed, because the answer will not be smaller, and $x$ will become larger. Time complexity: $O(\\log 10^{18})$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxb = 60;\n\nbool get_bit(int64_t a,int i)\n{\n    return a&(1ll<<i);\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int64_t a,b,r;\n        cin >> a >> b >> r;\n        int64_t x = 0;\n        bool first_bit = 1;\n        if(a > b)\n            swap(a,b);\n        for(int i = maxb-1;i >= 0;--i)\n        {\n            bool bit_a = get_bit(a,i);\n            bool bit_b = get_bit(b,i);\n            if(bit_a != bit_b)\n            {\n                if(first_bit)\n                {\n                    first_bit = 0;\n                }\n                else\n                {\n                    if(!bit_a && x+(1ll<<i) <= r)\n                    {\n                        x += (1ll<<i);\n                        a ^= (1ll<<i);\n                        b ^= (1ll<<i);\n                    }\n                }\n            }\n        }\n        cout << b-a << \"\\n\";\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1918",
    "index": "D",
    "title": "Blocking Elements",
    "statement": "You are given an array of numbers $a_1, a_2, \\ldots, a_n$. Your task is to block some elements of the array in order to minimize its cost. Suppose you block the elements with indices $1 \\leq b_1 < b_2 < \\ldots < b_m \\leq n$. Then the cost of the array is calculated as the maximum of:\n\n- the sum of the blocked elements, i.e., $a_{b_1} + a_{b_2} + \\ldots + a_{b_m}$.\n- the maximum sum of the segments into which the array is divided when the blocked elements are removed. That is, the maximum sum of the following ($m + 1$) subarrays: [$1, b_1 − 1$], [$b_1 + 1, b_2 − 1$], [$\\ldots$], [$b_{m−1} + 1, b_m - 1$], [$b_m + 1, n$] (the sum of numbers in a subarray of the form [$x,x − 1$] is considered to be $0$).\n\nFor example, if $n = 6$, the original array is [$1, 4, 5, 3, 3, 2$], and you block the elements at positions $2$ and $5$, then the cost of the array will be the maximum of the sum of the blocked elements ($4 + 3 = 7$) and the sums of the subarrays ($1$, $5 + 3 = 8$, $2$), which is $\\max(7,1,8,2) = 8$.\n\nYou need to output the minimum cost of the array after blocking.",
    "tutorial": "Let's do a binary search. Suppose we know that the minimum possible cost is at least $l$ and not greater than $r$. Let's choose $m = (l+r)/2$. We need to learn how to check if the answer is less than or equal to $m$. We will calculate $dp_i$-the minimum sum of blocked elements in the prefix up to $i$ if position $i$ is blocked, and on each of the subsegments without blocked elements, the sum of elements is less than or equal to $m$. Then $dp_i = a_i + \\min(dp_j)$ for all $j$ such that the sum on the subsegment from $j+1$ to $i-1$ is less than or equal to $m$. Such $j$ form a segment, since $a_j$ is positive. We will maintain the boundaries of this segment. We will also maintain all $dp_j$ for $j$ inside this subsegment in the set. When moving from $i$ to $i+1$, we will move the left boundary of the subsegment until the sum on it becomes less than or equal to $m$, and remove $dp_j$ from the set, and also add $dp_i$ to the set. The minimum sum of blocked elements under the condition that the sum on all subsegments without blocked elements is less than or equal to $m$ can be found as the minimum among all $dp_i$ such that the sum from $i$ to $n$ is less than or equal to $m$. If this answer is less than or equal to $m$, then the answer to the problem is less than or equal to $m$, otherwise the answer is greater than $m$. Time complexity: $O(n \\log n \\log 10^9)$ per test case.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int n;\n        cin >> n;\n        int64_t a[n+1];\n        for(int i = 0;i < n;++i)\n        {\n            cin >> a[i];\n        }\n        int64_t l = 0,r = int64_t(1e9)*n;\n        while(l < r)\n        {\n            int64_t m = (l+r)/2;\n            set<pair<int64_t,int>> pos;\n            int64_t dp[n+1];\n            int p2 = n;\n            dp[n] = 0;\n            pos.insert({dp[n],n});\n            int64_t sum = 0;\n            for(int j = n-1;j >= 0;--j)\n            {\n                while(sum > m)\n                {\n                    sum -= a[p2-1];\n                    pos.erase({dp[p2],p2});\n                    p2--;\n                }\n                dp[j] = pos.begin()->first + a[j];\n                pos.insert({dp[j],j});\n                sum += a[j];\n            }\n            sum = 0;\n            int yes = 0;\n            for(int j =0;j < n;++j)\n            {\n                if(sum <= m && dp[j] <= m)\n                    yes = 1;\n                sum += a[j];\n            }\n            if(yes)\n                r = m;\n            else\n                l = m+1;\n        }\n        cout << l << \"\\n\";\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "implementation",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1918",
    "index": "E",
    "title": "ace5 and Task Order",
    "statement": "This is an interactive problem!\n\nIn the new round, there were $n$ tasks with difficulties from $1$ to $n$. The coordinator, who decided to have the first round with tasks in unsorted order of difficulty, rearranged the tasks, resulting in a permutation of difficulties from $1$ to $n$. After that, the coordinator challenged ace5 to guess the permutation in the following way.\n\nInitially, the coordinator chooses a number $x$ from $1$ to $n$.\n\nace5 can make queries of the form: $?\\ i$. The answer will be:\n\n- $>$, if $a_i > x$, after which $x$ increases by $1$.\n- $<$, if $a_i < x$, after which $x$ decreases by $1$.\n- $=$, if $a_i = x$, after which $x$ remains unchanged.\n\nThe task for ace5 is to guess the permutation in no more than $40n$ queries. Since ace5 is too busy writing the announcement, he has entrusted this task to you.",
    "tutorial": "Randomized solution: We will use the quicksort algorithm. We will choose a random element from the array, let its index be $i$, and we will perform $?$ $i$ until we get the answer $=$ (i.e., $x = a_i$). Now we will ask about all the other elements, thereby finding out whether they are greater than or less than $a_i$ (don't forget to return $x = a_i$, i.e., perform $?$ $i$ after each query about the element). After this, we will divide all the elements into two parts, where $a_i > x$ and $a_i < x$. We will recursively run the algorithm on each part. The parts will become smaller and smaller, and in the end, we will sort our permutation, allowing us to guess it. Non-randomized solution: We will find the element $1$ in the array in $3n$ queries. To do this, we will go through the array, asking about each element each time. If the answer is $<$, we will continue asking until the answer becomes $=$, and if the answer is $=$ or $>$, we will move on to the next element. Then the last element on which the answer was $<$ is the element $1$. $x$ will increase by a maximum of $n$ in the process (a maximum of $1$ from each element), so it will decrease by a maximum of $2n$, i.e., a maximum of $3n$ queries. Similarly, we will find the element $n$. Now we will run an algorithm similar to the randomized solution, but now we can set $x = n/2$ instead of taking $x$ as a random element. Both solutions comfortably fit within the limit of $40n$ queries.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nchar query(int pos)\n{\n    cout << \"? \" << pos << endl;\n    char ans;\n    cin >> ans;\n    return ans;\n}\n\nvoid dnq(int l,int r,vector<int> pos,vector<int> & res,int pos1,int posn)\n{\n    int m = (l+r)/2;\n    vector<int> lh;\n    vector<int> rh;\n    for(int i = 0;i < pos.size();++i)\n    {\n        char x = query(pos[i]);\n        if(x == '>')\n        {\n            rh.push_back(pos[i]);\n            query(pos1);\n        }\n        else if(x == '<')\n        {\n            lh.push_back(pos[i]);\n            query(posn);\n        }\n        else\n        {\n            res[pos[i]] = m;\n        }\n    }\n    if(lh.size() != 0)\n    {\n        int m2 = (l+m-1)/2;\n        for(int j = 0;j < m-m2;++j)\n            query(pos1);\n        dnq(l,m-1,lh,res,pos1,posn);\n        query(posn);\n    }\n    if(rh.size() != 0)\n    {\n        int m2 = (m+1+r)/2;\n        for(int j = 0;j < m2-m;++j)\n            query(posn);\n        dnq(m+1,r,rh,res,pos1,posn);\n    }\n    return ;\n}\n\n\nint main()\n{\n    int t;\n    cin >> t;\n    while(t--)\n    {\n        int n;\n        cin >> n;\n        int pos1 = -1;\n        for(int i = 1;i <= n;++i)\n        {\n            char ans = query(i);\n            if(ans == '<')\n            {\n                i--;\n            }\n            else if(ans == '=')\n            {\n                pos1 = i;\n            }\n            else\n            {\n                if(pos1 != -1)\n                {\n                    query(pos1);\n                }\n            }\n        }\n        int posn = -1;\n        for(int i = 1;i <= n;++i)\n        {\n            char ans = query(i);\n            if(ans == '>')\n            {\n                i--;\n            }\n            else if(ans == '=')\n            {\n                posn = i;\n            }\n            else\n            {\n                if(posn != -1)\n                {\n                    query(posn);\n                }\n            }\n        }\n        vector<int> res(n+1);\n        vector<int> pos(n);\n        for(int j = 0;j < n;++j)\n            pos[j] = j+1;\n        int m = (1+n)/2;\n        for(int k = 0;k < n-m;++k)\n        {\n            query(pos1);\n        }\n        dnq(1,n,pos,res,pos1,posn);\n        cout << \"! \";\n        for(int j = 1;j <= n;++j)\n            cout << res[j] << ' ';\n        cout << endl;\n    }\n}",
    "tags": [
      "constructive algorithms",
      "divide and conquer",
      "implementation",
      "interactive",
      "probabilities",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1918",
    "index": "F",
    "title": "Caterpillar on a Tree",
    "statement": "The caterpillar decided to visit every node of the tree. Initially, it is sitting at the root.\n\nThe tree is represented as a rooted tree with the root at the node $1$. Each crawl to a neighboring node takes $1$ minute for the caterpillar.\n\nAnd there is a trampoline under the tree. If the caterpillar detaches from the tree and falls onto the trampoline, it will end up at the root of the tree in $0$ seconds. But the trampoline is old and can withstand no more than $k$ caterpillar's falls.\n\nWhat is the minimum time the caterpillar can take to visit all the nodes of the tree?\n\nMore formally, we need to find the minimum time required to visit all the nodes of the tree, if the caterpillar starts at the root (node $1$) and moves using two methods.\n\n- Crawl along an edge to one of the neighboring nodes: takes $1$ minute.\n- Teleport to the root: takes no time, no new nodes become visited.\n\nThe second method (teleportation) can be used at most $k$ times. The caterpillar can finish the journey at any node.",
    "tutorial": "First, it can be noticed that it is enough to visit all the leaves of the tree. After all, if the caterpillar skips some internal node, then it will not be able to reach the subtree of this node and visit the leaves in it. Therefore, it makes no sense to teleport to the root from a non-leaf (otherwise it would be more profitable to move to the root earlier, and all the leaves would remain visited). The optimal path of the caterpillar on the tree can be divided into movements from the root to a leaf, movements from one leaf to another, and teleportations from a leaf to the root. Let the order of visiting the leaves in the optimal path be fixed. Then it makes no sense to teleport from the last leaf, as all the leaves have already been visited. In addition, it is not profitable to move not along the shortest path in the sections of transition from the root to a leaf without visiting other leaves, or in movements from one leaf to another without visiting other leaves. If the leaf $v$ is visited after the leaf $u$, then teleporting from $u$ saves time of transition from $u$ to $v$ minus the time of moving to $v$ from the root. It is possible to choose $k$ leaves, without the last visited leaf, which give the maximum savings (if there are fewer leaves in the tree, or the savings become negative, then take fewer than $k$ leaves), and teleport from them. Thus, if the order of visiting the leaves is known, the optimal time can be found. It turns out that if you take the tree and sort the children of each node in ascending (not descending) order of the depth of the subtree, and then write down all the leaves from left to right (in depth-first order), then this will be one of the optimal leaf orders. This order of sorting the tree and its leaves will be called the order of sorting by the subtree depth. The tree can be sorted in this way in one depth-first traversal. For each leaf, it is possible to calculate how much time teleporting from it saves. To do this, it is enough to move from this leaf to the root until the first node, for which the previous node is not the rightmost child. Then the savings are the length of the path traveled minus the remaining distance to the root. Such paths for different leaves do not intersect along the edges, and the remaining distance to the root can be precalculated in a depth-first search for all nodes at once. Therefore, the algorithm works in $O(n \\log n)$ time, where the logarithm arises from sorting the children of each node by the depth of the subtree. Theorem. There exists a shortest route for the caterpillar, in which the leaves are visited in the order of sorting the children of each node by the depth of the subtree. Let $u_1, \\ldots, u_m$ be all the leaves of the tree in the order that will result if the children of each node are sorted in ascending order of the depth of the subtree. Consider the shortest route of the caterpillar visiting all the nodes of the tree. Let $v_1, \\ldots, v_m$ be the leaves of the tree, in the order of visiting in this route. Consider the maximum prefix of leaves that coincides with the order of sorting by the depth of the subtree: $v_1 = u_1,\\ldots, v_i = u_i$. If $i = m$, then the theorem is proven. Now, let's assume that the next leaf is the incorrect leaf $v_{i+1} \\neq u_{i+1}$. The goal is to change the route in such a way that the time of traversing the tree does not increase, so that the first $i$ visited leaves do not change and remain in the same order, and so that the leaf $u_{i+1}$ is encountered earlier in the route than before the change. Then it is possible to move the leaf $u_{i+1}$ to its $(i+1)$s place, while maintaining the order of the first $i$ visited leaves. Then, in the same way, one can put all the leaves $u_{i+1}, \\ldots, u_m$ in their places one by one and get the shortest route of the caterpillar with the desired order of visiting leaves. Lemma. Let the node $w$ be the ancestor of the node $u$. Let the caterpillar in the shortest route on the tree crawl from $u$ to $w$. Then the caterpillar enters the subtree of the node $u$ only once, traverses this subtree depth-first, and returns to $w$. Proof of the lemma. If the caterpillar crawls from $w$ to $u$ only once, then it cannot leave the subtree of $u$ until all the nodes in this subtree are visited, and it cannot jump on a trampoline, as it still needs to move from $u$ to $w$. All this cannot be done faster than the number of steps equal to twice the number of nodes in the subtree of $u$, because the caterpillar needs to reach each node via an edge from the ancestor and to return to the ancestor. And any route without teleportations, which uses each edge twice, is one of the depth-first traversals. If the caterpillar crawls from $w$ to $u$ two or more times, then the route can be shortened, as shown in figure. The lemma is proven. At the moment, the leaf $v_{i+1}$ lies in the order of visiting the leaves in the optimal route of the caterpillar in the place of the leaf $u_{i+1}$. The goal is to move the leaf $u_{i+1}$ closer to the beginning of the route, without changing the first $i$ visited leaves: $u_1, \\ldots, u_i$. Let $w$ be the least common ancestor of the leaves $u_{i+1}$ and $v_{i+1}$, let $u$ be the child of $w$, in the subtree of which the node $u_{i+1}$ is located, and $v$ be the child of $w$, in the subtree of which the node $v_{i+1}$ is located, as shown in figure. To move the leaf $u_{i+1}$ closer to the beginning of the route, let us consider cases. Case 1: The caterpillar in the current version of the optimal route crawls from $u$ to $w$. In this case, according to the lemma, the caterpillar enters the subtree of vertex $u$ only once, and traverses it in the depth-first manner before returning to $w$. There are no leaves $u_1, \\ldots, u_i$ in the subtree of $u$, because all the leaves of the subtree of $u$ are visited consecutively during the depth-first traversal, and the leaf $v_{i+1}$ not from the subtree of $u$ is visited after $u_1, \\ldots, u_i$, but before $u_{i+1}$. Then the route can be changed as follows: the cycle $w \\to \\text{ (traversal of the subtree of } u\\text{) } \\to w$ is cut out from where it is located, and inserted at the moment of the first visit to $w$ after the visit to the leaf $u_i$. The leaf $u_i$ is not in the subtree of the node $v$, because the subtree of $u$ has a smaller depth ($u_{i+1}$ is earlier in the desired leaf order than $v_{i+1}$), and there are still unvisited leaves in it. Then, before entering $v_{i+1}$, the caterpillar will have to come from the leaf $u_i$ to the node $w$, and at that moment a depth-first traversal of the subtree of $u$ with the visit to the leaf $u_{i+1}$ will occur. This traversal was moved to an earlier time, before visiting $v_{i+1}$, which means that in the order of visiting the leaves in the caterpillar's route, the leaf $u_{i+1}$ has been moved closer to the beginning. Case 2: The caterpillar in the current version of the optimal route does not crawl from $u$ to $w$, but crawls from $v$ to $w$. Then the entire subtree of $v$ is traversed in a depth-first traversal. Since the leaf $u_{i+1}$ is earlier in the desired order than $v_{i+1}$, the subtree of $v$ is deeper than the subtree of $u$, and in the desired order all the leaves of $v$ come after $u_{i+1}$. Moreover, since the caterpillar does not crawl from $u$ to $w$, it is impossible to leave the subtree of $u$ except by teleporting to the root. The last jump on the trampoline from the subtree of the node $u$ is considered (or stopping at the end of the route). At this moment, all the leaves of the subtree of $u$ are visited. The route can be changed as follows: cut out the depth-first traversal of the subtree of $v$, cancel the last jump or stop in the subtree of $u$, descend from there to $w$, perform a depth-first traversal of the subtree of $v$ in such a way that the deepest node of this subtree is visited last, and teleport to the root (or stop at the end of the route). This will not be longer, because a section of transition from a leaf in the subtree of $u$ to $w$ has been added, and a section of movement from the deepest leaf in the subtree of $v$ to $w$ has disappeared, here it is important that the subtree of $v$ is deeper than the subtree of $u$. And the node $u_{i+1}$ has become closer to the beginning of the list of visited leaves, because all the leaves of the subtree of $v$, including $v_{i+1}$, have moved somewhere after all the leaves of the subtree of $u$. Case 3: The caterpillar in the current version of the optimal route does not crawl either from $u$ to $w$, nor from $v$ to $w$. Then all the sections of the route that move into the subtrees of the nodes $u$ and $v$ do not leave these subtrees and end with teleportation to the root or stopping at the end of the route. Among them, there is a section that starts with a step from $w$ to $u$, in which the leaf $u_{i+1}$ is visited, and a section that starts with a step from $w$ to $v$, in which the leaf $v_{i+1}$ is visited. In the current route, the section with $v_{i+1}$ comes earlier. The route can be changed very simply: swap the section visiting the leaf $u_{i+1}$ and the section visiting the leaf $v_{i+1}$. If both sections end with teleportations, then a correct caterpillar route will result. If the caterpillar stopped at the end of the section visiting $u_{i+1}$, and teleported to the root from the section with $v_{i+1}$, then now it will teleport after completing the section with $u_{i+1}$ and stop at the end of the section with $v_{i+1}$. The positions of the leaves $u_1, \\ldots, u_i$ in the route will not change: they are not in the subtree of $v$, and they are not in the section with $u_{i+1}$, visited after $v_{i+1}$. And the leaf $u_{i+1}$ will get a place closer to the beginning in the order of visiting the leaves, because the section with its visit now occurs earlier in the route. In all cases, it was possible to move the leaf $u_{i+1}$ in the optimal route of the caterpillar closer to the beginning, while maintaining the order of the first $i$ visited leaves, which means that there exists an optimal route of the caterpillar in which the leaves are visited in the order of sorting the subtrees of the tree by depth. The theorem is proven.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int maxn = 200005;\nint d[maxn];\nint h[maxn];\nint p[maxn];\nvector<int> leaf_jump_gains;\nvector<vector<int> > children;\n\nbool comp_by_depth(int u,int v)\n{\n    return d[u] < d[v];\n}\n\nvoid sort_subtrees_by_depth(int v)\n{\n    d[v] = 0;\n    if(v == 1)\n        h[v] = 0;\n    else\n        h[v] = h[p[v]]+1;\n    for(int i = 0; i < int(children[v].size()); ++i)\n    {\n        int u = children[v][i];\n        sort_subtrees_by_depth(u);\n        d[v] = max(d[v],d[u]+1);\n    }\n    sort(children[v].begin(),children[v].end(),comp_by_depth);\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int n,k;\n    cin >> n >> k;\n    children.resize(n+1);\n    for(int i = 2; i <= n; ++i)\n    {\n        cin >> p[i];\n        children[p[i]].push_back(i);\n    }\n    sort_subtrees_by_depth(1);\n    for(int i = 1; i <= n; ++i)\n    {\n        if(children[i].size() == 0)\n        {\n            int jump_gain = 0;\n            int v = i;\n            while(v != 1)\n            {\n                int s = children[p[v]].size();\n                if(children[p[v]][s-1] == v)\n                {\n                    v = p[v];\n                    ++jump_gain;\n                }\n                else\n                {\n                    jump_gain = jump_gain+1-h[p[v]];\n                    break;\n                }\n            }\n            leaf_jump_gains.push_back(jump_gain);\n        }\n    }\n    sort(leaf_jump_gains.begin(),leaf_jump_gains.end());\n    int s = leaf_jump_gains.size();\n    ++k; //non-returning from the last leaf is like one more jump\n    int res = 2*(n-1);\n    for(int i = s-1; i >= max(0,s-k); --i)\n        res -= max(leaf_jump_gains[i],0);\n    cout << res << '\\n';\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation",
      "sortings",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1918",
    "index": "G",
    "title": "Permutation of Given",
    "statement": "You were given only one number, $n$. It didn't seem interesting to you, so you wondered if it's possible to come up with an array of length $n$ consisting of non-zero integers, such that if each element of the array is replaced by the sum of its neighbors (the elements on the ends are replaced by their only neighbors), you obtain a permutation of the numbers in the original array.",
    "tutorial": "At first, you can manually find answers for small values of $n$. For $n = 2, 4, 6$, the answer will be \"YES\" and the arrays will be $[-1, 1]$, $[-1, -2, 2, 1]$, $[-1, -2, 2, 1, -1, 1]$. It is not difficult to prove by case analysis that the answer is \"NO\" for $3$ and $5$. It can be assumed that for all odd $n$, the answer is \"NO\", but if you try to prove the absence of an array or find an array for $n = 7$, it turns out that the array exists: $[-5, 8, 1, -3, -4, -2, 5]$. In fact, an array exists for all $n$ except $3$ and $5$. It would be easy if it were possible to make the number in each cell unchanged. But the presence of array edges and the prohibition of zeros make this impossible. Furthermore, it can be noticed that an infinite array in which the sequence of six numbers $1, -3, -4, -1, 3, 4$ is repeated, generates the same number in each cell as it was there. In general, any sequence of six numbers of the form $a, -b, -a-b, -a, b, a+b$ will have this property. Thus, it is possible to transform the internal cells of the array into cells with the same numbers, the question is what to do at the edges. In the author's solution, suitable edges (possibly consisting of several numbers) were manually selected for each remainder of division by $6$. And then the solution for each value of $n$ was created as follows: take the edges for $n \\mod 6$ and insert into the middle as many sequences of six numbers that transition into themselves as needed. Solution by green_gold_dog: The idea is that any correct array can be extended by $2$ elements to remain correct. Let the array end with the numbers $a$ and $b$. Then it can be extended by two elements as follows: $\\begin{equation*} [\\ldots,\\;a,\\;b] \\to [\\ldots, a,\\; b,\\; -b,\\; a-b] \\end{equation*}$ To start, two arrays are sufficient: $[1, 2]$ for $n = 2$ and $[1, 2, -3, 2, 4, -5, -2]$ for $n = 7$. Then these arrays can be extended by $2$ to obtain the answer for even or odd $n$. Both solutions print an array using simple rules and work in $O(n)$ time.",
    "code": "//#pragma GCC optimize(\"Ofast\")\n//#pragma GCC target(\"avx,avx2,sse,sse2,sse3,ssse3,sse4,abm,popcnt,mmx\")\n#include <bits/stdc++.h>\n \nusing namespace std;\n \ntypedef long long ll;\ntypedef double db;\ntypedef long double ldb;\ntypedef complex<double> cd;\n \nconstexpr ll INF64 = 9'000'000'000'000'000'000, INF32 = 2'000'000'000, MOD = 1'000'000'007;\nconstexpr db PI = acos(-1);\nconstexpr bool IS_FILE = false, IS_TEST_CASES = false;\n \nrandom_device rd;\nmt19937 rnd32(rd());\nmt19937_64 rnd64(rd());\n \ntemplate<typename T>\nbool assign_max(T& a, T b) {\n\tif (b > a) {\n\t\ta = b;\n\t\treturn true;\n\t}\n\treturn false;\n}\n \ntemplate<typename T>\nbool assign_min(T& a, T b) {\n\tif (b < a) {\n\t\ta = b;\n\t\treturn true;\n\t}\n\treturn false;\n}\n \ntemplate<typename T>\nT square(T a) {\n\treturn a * a;\n}\n \ntemplate<>\nstruct std::hash<pair<ll, ll>> {\n\tll operator() (pair<ll, ll> p) const {\n\t\treturn ((__int128)p.first * MOD + p.second) % INF64;\n\t}\n};\n \nvoid solve() {\n\tll n;\n\tcin >> n;\n\tif (n == 5 || n == 3) {\n\t\tcout << \"NO\\n\";\n\t\treturn;\n\t}\n\tcout << \"YES\\n\";\n\tvector<ll> arr;\n\tif (n % 2 == 0) {\n\t\tarr.push_back(1);\n\t\tarr.push_back(2);\n\t} else {\n\t\tarr.push_back(1);\n\t\tarr.push_back(2);\n\t\tarr.push_back(-3);\n\t\tarr.push_back(2);\n\t\tarr.push_back(4);\n\t\tarr.push_back(-5);\n\t\tarr.push_back(-2);\n\t}\n\twhile (arr.size() != n) {\n\t\tll x = arr[arr.size() - 2];\n\t\tll y = x - arr.back();\n\t\tll z = y - x;\n\t\tarr.push_back(z);\n\t\tarr.push_back(y);\n\t}\n\tfor (auto i : arr) {\n\t\tcout << i << ' ';\n\t}\n\tcout << '\\n';\n}\n \nint main() {\n\tif (IS_FILE) {\n\t\tfreopen(\"\", \"r\", stdin);\n\t\tfreopen(\"\", \"w\", stdout);\n\t}\n    \tios_base::sync_with_stdio(false);\n    \tcin.tie(0);\n    \tcout.tie(0);\n\tll t = 1;\n\tif (IS_TEST_CASES) {\n\t\tcin >> t;\n\t}\n\tfor (ll i = 0; i < t; i++) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1919",
    "index": "A",
    "title": "Wallet Exchange",
    "statement": "Alice and Bob are bored, so they decide to play a game with their wallets. Alice has $a$ coins in her wallet, while Bob has $b$ coins in his wallet.\n\nBoth players take turns playing, with Alice making the first move. In each turn, the player will perform the following steps \\textbf{in order}:\n\n- Choose to exchange wallets with their opponent, or to keep their current wallets.\n- Remove $1$ coin from the player's current wallet. The current wallet cannot have $0$ coins before performing this step.\n\nThe player who cannot make a valid move on their turn loses. If both Alice and Bob play optimally, determine who will win the game.",
    "tutorial": "When does the game end? Depending on whether the player chooses to exchange wallets with their opponent on step $1$, $1$ coins will be removed from either the opponent's wallet or the player's wallet. This means that if either of the players still has remaining coins, the game will not end as at least one of the choices will still be valid. The only way that the game ends is when both players have $0$ coins. Since each operation decreases the total amount of coins by exactly $1$, the only way for Alice to win the game is if $a + b$ is odd.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t; cin >> t;\n    while (t--) {\n        int a, b; cin >> a >> b;\n        if ((a + b) % 2 == 0) {\n            cout << \"Bob\\n\";\n        } else {\n            cout << \"Alice\\n\";\n        }\n    }\n}",
    "tags": [
      "games",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1919",
    "index": "B",
    "title": "Plus-Minus Split",
    "statement": "You are given a string $s$ of length $n$ consisting of characters \"+\" and \"-\". $s$ represents an array $a$ of length $n$ defined by $a_i=1$ if $s_i=$ \"+\" and $a_i=-1$ if $s_i=$ \"-\".\n\nYou will do the following process to calculate your penalty:\n\n- Split $a$ into non-empty arrays $b_1,b_2,\\ldots,b_k$ such that $b_1+b_2+\\ldots+b_k=a^\\dagger$, where $+$ denotes array concatenation.\n- The penalty of a single array is the absolute value of its sum multiplied by its length. In other words, for some array $c$ of length $m$, its penalty is calculated as $p(c)=|c_1+c_2+\\ldots+c_m| \\cdot m$.\n- The total penalty that you will receive is $p(b_1)+p(b_2)+\\ldots+p(b_k)$.\n\nIf you perform the above process optimally, find the minimum possible penalty you will receive.\n\n$^\\dagger$ Some valid ways to split $a=[3,1,4,1,5]$ into $(b_1,b_2,\\ldots,b_k)$ are $([3],[1],[4],[1],[5])$, $([3,1],[4,1,5])$ and $([3,1,4,1,5])$ while some invalid ways to split $a$ are $([3,1],[1,5])$, $([3],[\\,],[1,4],[1,5])$ and $([3,4],[5,1,1])$.",
    "tutorial": "Try to find a lower bound. The answer is $|a_1 + a_2 + \\ldots + a_n|$. Intuitively, whenever we have a subarray with a sum equal to $0$, it will be helpful for us as its penalty will become $0$. Hence, we can split $a$ into subarrays with a sum equal to $0$ and group up the remaining elements into individual subarrays of size $1$. A formal proof is given below. Let us define an alternative penalty function $p2(l, r) = |a_l + a_{l+1} + \\ldots + a_r|$. We can see that $p2(l, r) \\le p(l, r)$ for all $1\\le l\\le r\\le n$. Since the alternative penalty function does not have the $(r - l + 1)$ term, there is no reason for us to partition $a$ into two or more subarrays as $|x| + |y| \\ge |x + y|$ for all integers $x$ and $y$, so the answer for the alternative penalty function is $|a_1 + a_2 + \\ldots + a_n|$. Since $p2(l, r)\\le p(l, r)$, this means that the answer to our original problem cannot be smaller than $|a_1 + a_2 + \\ldots + a_n|$. In fact, this lower bound is always achievable. Let us prove this by construction. Note that if we flip every \"$\\mathtt{+}$\" to \"$\\mathtt{-}$\" and every \"$\\mathtt{-}$\" to \"$\\mathtt{+}$\", our answer will remain the same since our penalty function involves absolute values. Hence, we can assume that the sum of elements of $a$ is non-negative. If the sum of elements of $a$ is $0$, we can split $a$ into a single array equal to itself $b_1 = a$ and obtain a penalty of $0$. Otherwise, we find the largest index $i$ where $a_1 + a_2 + \\ldots + a_i = 0$. Then we let the first subarray be $b_1 = [a_1, a_2, \\ldots, a_i]$ and the second subarray be $b_2 = [a_{i + 1}]$, so we have $p(b_1) = 0$ and $p(b_2) = 1$. Since $i$ is the largest index, $a_{i + 1}$ has to be equal to $1$ as if $a_{i + 1}$ is $-1$ instead, there has to be a larger index where the prefix sum becomes $0$ again for the prefix sum to go from negative to the final positive total sum. This means that for the remaining elements of the array $a_{i+2\\ldots n}$, the sum of its elements decreases by $1$, so we can continue to use the same procedure to split the remaining elements which decrease the sum by $1$ and increase the penalty by $1$ each time until the sum of elements becomes $0$. Hence, the total penalty will be equal to the sum of elements of $a$.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n\nint t;\nint n;\nstring s;\n\nint main() {\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        cin >> s;\n        int sm = 0;\n        for (int i = 0; i < n; i++) {\n            sm += s[i] == '+' ? 1 : -1;\n        }\n        cout << abs(sm) << '\\n';\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1919",
    "index": "C",
    "title": "Grouping Increases",
    "statement": "You are given an array $a$ of size $n$. You will do the following process to calculate your penalty:\n\n- Split array $a$ into two (possibly empty) subsequences$^\\dagger$ $s$ and $t$ such that every element of $a$ is either in $s$ or $t^\\ddagger$.\n- For an array $b$ of size $m$, define the penalty $p(b)$ of an array $b$ as the number of indices $i$ between $1$ and $m - 1$ where $b_i < b_{i + 1}$.\n- The total penalty you will receive is $p(s) + p(t)$.\n\nIf you perform the above process optimally, find the minimum possible penalty you will receive.\n\n$^\\dagger$ A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements.\n\n$^\\ddagger$ Some valid ways to split array $a=[3,1,4,1,5]$ into $(s,t)$ are $([3,4,1,5],[1])$, $([1,1],[3,4,5])$ and $([\\,],[3,1,4,1,5])$ while some invalid ways to split $a$ are $([3,4,5],[1])$, $([3,1,4,1],[1,5])$ and $([1,3,4],[5,1])$.",
    "tutorial": "Consider a greedy approach. Consider the following approach. We start with empty arrays $b$ and $c$, then insert elements of the array $a$ one by one to the back of $b$ or $c$. Our penalty function only depends on adjacent elements, so at any point in time, we only care about the value of the last element of arrays $b$ and $c$. Suppose we already inserted $a_1, a_2, \\ldots, a_{i - 1}$ into arrays $b$ and $c$ and we now want to insert $a_i$. Let $x$ and $y$ be the last element of arrays $b$ and $c$ respectively (if they are empty, use $\\infty$). Note that swapping arrays $b$ and $c$ does not matter, so without loss of generality, assume that $x\\le y$. We will use the following greedy approach. If $a_i\\le x$, insert $a_i$ to the back of the array with a smaller last element. If $y < a_i$, insert $a_i$ to the back of the array with a smaller last element. If $x < a_i\\le y$, insert $a_i$ to the back of the array with a bigger last element. The proof of why the greedy approach is optimal is given below: $a_i\\le x$. In this case, $a_i$ is not greater than the last element of both arrays, so inserting $a_i$ to the back of either array will not add additional penalties. However, it is better to insert $a_i$ into the array with a smaller last element so that in the future, we can insert a wider range of values into the new array without additional penalty. $y < a_i$. In this case, $a_i$ is greater than the last element of both arrays, so inserting $a_i$ to the back of either array will contribute to $1$ additional penalty. However, it is better to insert $a_i$ into the array with a smaller last element so that in the future, we can insert a wider range of values into the new array without additional penalty. $x < a_i\\le y$. In this case, if we insert $a_i$ to the back of the array with the larger last element, there will not be any additional penalty. However, if we insert $a_i$ to the back of the array with the smaller last element, there will be an additional penalty of $1$. The former option is always better than the latter. This is because if we consider making the same choices for the remaining elements $a_{i+1}$ to $a_n$ in both scenarios, there will be at most one time where the former scenario will add one penalty more than the latter scenario as the former scenario has a smaller last element after inserting $a_i$. After that happens, the back of the arrays in both scenarios will become the same and hence, the former case will never be less optimal. Following the greedy approach for all 3 cases will result in a correct solution that runs in $O(n)$ time. Consider a dynamic programming approach. Let $dp_{i, v}$ represent the minimum penalty when we are considering splitting $a_{1\\ldots i}$ into two subarrays where the last element of one subarray is $a_i$ while the last element of the second subarray is $v$. Speed up the transition by storing the state in a segment tree. Let us consider a dynamic programming solution. Let $dp_{i, v}$ represent the minimum penalty when we are considering splitting $a_{1\\ldots i}$ into two subarrays where the last element of one subarray is $a_i$ while the last element of the second subarray is $v$. Then, our transition will be $dp_{i, v} = dp_{i - 1, v} + [a_{i - 1} < a_i]$ for all $1\\le v\\le n, v\\neq a_{i - 1}$ and $dp_{i, a_{i - 1}} = \\min(dp_{i - 1, a_{i - 1}} + [a_{i - 1} < a_i], \\min_{1\\le x\\le n}(dp_{i - 1, x} + [x < a_i]))$. To speed this up, we use a segment tree to store the value of $dp_{i - 1, p}$ at position $p$. To transition to $dp_i$, notice that the first transition is just a range increment on the entire range $[1, n]$ of the segment tree if $a_{i - 1} < a_i$. For the second transition, we can do two range minimum queries on ranges $[1, a_i - 1]$ and $[a_i, n]$. The final time complexity is $O(n\\log n)$. Solve the problem if you have to split the array into $k$ subsequences, where $k$ is given in the input ($k = 2$ for the original problem). There is an array $A$ of size $N$ and an array $T$ of size $K$. Initially, $T_i = \\infty$ for all $1 \\le i \\le K$. For each time $t$ from $1$ to $N$, the following will happen: Select an index $1 \\le i \\le K$. If $A_t > T_i$, we increase the cost by $1$. Then, we set $T_i := A_t$. Find the minimum possible cost after time $N$ if we select the indices optimally. The order of $T$ does not matter. Hence for convenience, we will maintain $T$ in non-decreasing order. At each time $t$, we will use the following algorithm: If $A_t > T_K$, do the operation on index $1$. Otherwise, find the smallest index $1 \\le i \\le K$ where $A_t \\le T_i$ and do the operation on index $i$. Suppose there exists an optimal solution that does not follow our algorithm. We will let $OT_{t, i}$ denote the value of $T_i$ before the operation was done at time $t$ in the optimal solution. Let $et$ be the earliest time that the operation done by the optimal solution differs from that of the greedy solution. Case 1: $A_{et} > OT_{et,K}$. Since we are maintaining $T$ in the sorted order, having $A_{et} > OT_{et,K}$ means that $A_{et}$ is larger than all elements of $T$. This means that no matter which index $i$ we choose to do the operation on, the cost will always increase by $1$. Suppose an index $i > 1$ was chosen in the optimal solution. We can always choose to do the operation on index $1$ instead of index $i$ and the answer will not be less optimal. This is because if we let $T'$ be the array $T$ after the operation was done on index $1$, $T'_p \\le OT_{et+1,p}$ for all $1 \\le p \\le K$ since $T'_p = \\begin{cases}OT_{et,p+1}&\\text{if }p<K\\newline A_{et}&\\text{if }p=K\\end{cases}$ while $OT_{et+1,p} = \\begin{cases}OT_{et,p}&\\text{if }p<i\\newline OT_{et,p+1}&\\text{if }i\\le p<K\\newline A_{et}&\\text{if }p=K\\end{cases}$. Case 2: $A_{et} \\le OT_{et,K}$. For convenience, we will denote that the operation was done on index $i$ in the greedy solution while the operation was done on index $j$ based on the optimal solution during time $et$. Case 2A: $i < j$. In this case, the cost does not increase for both the optimal solution and the greedy solution. However, we can always do an operation on index $i$ instead of index $j$ and the answer will not be less optimal. This is because if we let $T'$ be the array $T$ after the operation was done on index $i$, $T'_p\\le OT_{et+1,p}$ for all $1\\le p\\le K$ since $T'_p = \\begin{cases}OT_{et,p}&\\text{if }p\\neq i\\newline A_{et}&\\text{if }p=i\\end{cases}$ while $OT_{et+1,p} = \\begin{cases}OT_{et,p}&\\text{if }p<i\\newline A_{et}&\\text{if }p=i\\newline OT_{et,p-1}&\\text{if }i< p\\le j\\newline OT_{et,p}&\\text{if }j<p\\le K\\end{cases}$. Case 2B: $i > j$. For this case, the cost increases for the optimal solution while the cost does not change for the greedy solution. However, it is not trivial to prove that the greedy solution is more optimal as even though it has a smaller cost, it results in a less optimal array $T$. Hence, we will prove this case below. Case 2A: $i < j$. In this case, the cost does not increase for both the optimal solution and the greedy solution. However, we can always do an operation on index $i$ instead of index $j$ and the answer will not be less optimal. This is because if we let $T'$ be the array $T$ after the operation was done on index $i$, $T'_p\\le OT_{et+1,p}$ for all $1\\le p\\le K$ since $T'_p = \\begin{cases}OT_{et,p}&\\text{if }p\\neq i\\newline A_{et}&\\text{if }p=i\\end{cases}$ while $OT_{et+1,p} = \\begin{cases}OT_{et,p}&\\text{if }p<i\\newline A_{et}&\\text{if }p=i\\newline OT_{et,p-1}&\\text{if }i< p\\le j\\newline OT_{et,p}&\\text{if }j<p\\le K\\end{cases}$. Case 2B: $i > j$. For this case, the cost increases for the optimal solution while the cost does not change for the greedy solution. However, it is not trivial to prove that the greedy solution is more optimal as even though it has a smaller cost, it results in a less optimal array $T$. Hence, we will prove this case below. Case 2B We want to come up with a modified solution that does the same operations as the optimal solution for time $1\\le t<et$ and does an operation on index $i$ during time $et$. Adopting a similar notation to $OT$, we will let $MT_{t, i}$ denote the value of $T_i$ before the operation was done at time $t$ in this modified solution. Then, $MT_{et+1,p} = \\begin{cases}OT_{et,p}&\\text{if }p\\neq i\\newline A_{et}&\\text{if } p=i\\end{cases}$ and $OT_{et+1,p}=\\begin{cases}OT_{et,p} &\\text{if } p<j\\newline OT_{et,p+1}&\\text{if }j\\le p<i-1\\newline A_{et}&\\text{if }p=i-1\\newline OT_{et,p}&\\text{if }i\\le p\\le K\\end{cases}$. Note that in this case, $MT_{et+1,p}\\le OT_{et+1,p}$ for all $1\\le p\\le K$, which means that our modified solution results in a less optimal state than the optimal solution. However, since our modified solution requires one less cost up to this point, we will be able to prove that our modified solution will not perform worse than the optimal solution. Notice that $OT_{et+1,p}\\le MT_{et+1,p+1}$ for all $1\\le p<K$. We denote that the index that the optimal solution operates on during time $t$ is $x_t$. Let $r$ be the minimum time where $et+1\\le r\\le N$ and $e_r=N$. Due to the above property that $OT_{et+1,p}\\le MT_{et+1,p+1}$ for all $1\\le p<K$, we can let our modified solution do the operation on index $x_t+1$ for all time $et+1\\le t<r$ and the cost will not be more than the optimal solution. This is because the property that $OT_{t+1,p}\\le MT_{t+1,p+1}$ for all $1\\le p<K$ still holds throughout that time range even after each update. Note that if such an $r$ does not exist, we can let our modified solution do the operation on index $x_t+1$ for all time $et+1\\le t\\le K$ and we completed coming up with the modified solution with a cost not more than the optimal solution. However, if such an $r$ exists, then at time $r$, since $x_r=N$, we are no longer able to use the same method. However, let us consider what happens if we let our modified solution do an operation on index $1$ during time $r$. If $A_r>MT_{r,K}$, it will mean that $MT_{r+1,p}=\\begin{cases}MT_{r,p+1}&\\text{if }p<K\\newline A_r&\\text{if }p=K\\end{cases}$ while $OT_{r+1,p}=\\begin{cases}OT_{r,p}&\\text{if }p<K\\newline A_r&\\text{if }p=K\\end{cases}$ since $OT_{r,K-1}\\le MT_{r,K}<A_r$. Even though during this time, it might be possible that the cost of the modified solution increases by $1$ while the cost of the optimal solution remains the same, recall that previously during time $i$ our modified solution used one less cost than the optimal solution. As a result, the modified solution will end up having a cost of not more than the optimal solution. At the same time, $OT_{r+1,p}\\le MT_{r+1,p}$ for all $1\\le p\\le K$. Hence, for all time $r<t\\le K$, we can let our modified solution do the operation on the same index as the optimal solution $x_t$ and the cost of our modified solution will not be more than that of the optimal solution. On the other hand, suppose $A_r\\le MT_{r,K}$. Let $v$ be the minimum position such that $A_r\\le MT_{r,v}$ and let $w$ be the minimum position such that $A_r\\le OT_{r,w}$. Then, $MT_{r+1,p}=\\begin{cases}MT_{r,p+1}&\\text{if }p<v-1\\newline A_r&\\text{if }p=v-1\\newline MT_{r,p}&\\text{if }p\\ge v\\end{cases}$ and $OT_{r+1,p}=\\begin{cases}OT_{r,p}&\\text{if }p<w\\newline A_r&\\text{if }p=w\\newline OT_{r,p-1}&\\text{if }p>w\\end{cases}$. In the same way, the cost of our modified solution might increase while the cost of the optimal solution stays the same, however, $OT_{r+1,p}\\le MT_{r+1,p}$ for all $1\\le p\\le K$. - For $p<v-1$ and $p>w$, the condition holds since $OT_{r,p}\\le MT_{r,p+1}$ for all $1\\le p<K$. Note that $v-1\\le w$ because of the same inequality as well. - Suppose $v-1=w$. Then for $p=v-1$, $OT_{r+1,p}=A_r\\le A_r=MT_{r+1,p}$. From now on, we suppose $v-1\\neq w$ - For $p=v-1$, $OT_{r,v-1}\\le A_r$ as $w$ is defined as the minimum position that $A_r\\le OT_{r,w}$ and $v-1< w$. - For $v\\le p<w$, $OT_{r,p}\\le MT_{r,p}$ as $OT_{r,p}<A_r\\le MT_{r,p}$ - For $p=w$, $A_r\\le MT_{r,w}$ as $v$ is defined as the minimum position that $A_r\\le MT_{r,v}$ and $v-1<w$ Now that we managed to construct a modified solution which follows the greedy algorithm from time $1\\le t\\le et$ and is not less optimal than the optimal solution, we can let the optimal solution be our modified solution and find the new $et$ to get a new modified solution. Hence by induction, our greedy solution is optimal.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n\nconst int INF = 1000000005;\nconst int MAXN = 200005;\n\nint t;\nint n;\nint a[MAXN];\n\nint mn[MAXN * 4], lz[MAXN * 4];\nvoid init(int u = 1, int lo = 1, int hi = n) {\n    mn[u] = lz[u] = 0;\n    if (lo != hi) {\n        int mid = lo + hi >> 1;\n        init(u << 1, lo, mid);\n        init(u << 1 ^ 1, mid + 1, hi);\n    }\n}\nvoid propo(int u) {\n    if (lz[u] == 0) {\n        return;\n    }\n    lz[u << 1] += lz[u];\n    lz[u << 1 ^ 1] += lz[u];\n    mn[u << 1] += lz[u];\n    mn[u << 1 ^ 1] += lz[u];\n    lz[u] = 0;\n}\nvoid incre(int s, int e, int x, int u = 1, int lo = 1, int hi = n) {\n    if (lo >= s && hi <= e) {\n        mn[u] += x;\n        lz[u] += x;\n        return;\n    }\n    propo(u);\n    int mid = lo + hi >> 1;\n    if (s <= mid) {\n        incre(s, e, x, u << 1, lo, mid);\n    }\n    if (e > mid) {\n        incre(s, e, x, u << 1 ^ 1, mid + 1, hi);\n    }\n    mn[u] = min(mn[u << 1], mn[u << 1 ^ 1]);\n}\nint qmn(int s, int e, int u = 1, int lo = 1, int hi = n) {\n    if (s > e) {\n        return INF;\n    }\n    if (lo >= s && hi <= e) {\n        return mn[u];\n    }\n    propo(u);\n    int mid = lo + hi >> 1;\n    int res = INF;\n    if (s <= mid) {\n        res = min(res, qmn(s, e, u << 1, lo, mid));\n    }\n    if (e > mid) {\n        res = min(res, qmn(s, e, u << 1 ^ 1, mid + 1, hi));\n    }\n    return res;\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        for (int i = 1; i <= n; i++) {\n            cin >> a[i];\n        }\n        init();\n        for (int i = 1; i <= n; i++) {\n            int ndp = min(qmn(1, a[i] - 1) + 1, qmn(a[i], n));\n            if (i > 1) {\n                if (a[i - 1] < a[i]) {\n                    incre(1, n, 1);\n                }\n                int dp = qmn(a[i - 1], a[i - 1]);\n                if (ndp < dp) {\n                    incre(a[i - 1], a[i - 1], ndp - dp);\n                }\n            }\n        }\n        cout << qmn(1, n) << '\\n';\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1919",
    "index": "D",
    "title": "01 Tree",
    "statement": "There is an edge-weighted complete binary tree with $n$ leaves. A complete binary tree is defined as a tree where every non-leaf vertex has exactly 2 children. For each non-leaf vertex, we label one of its children as the left child and the other as the right child.\n\nThe binary tree has a very strange property. For every non-leaf vertex, one of the edges to its children has weight $0$ while the other edge has weight $1$. Note that the edge with weight $0$ can be connected to either its left or right child.\n\nYou forgot what the tree looks like, but luckily, you still remember some information about the leaves in the form of an array $a$ of size $n$. For each $i$ from $1$ to $n$, $a_i$ represents the distance$^\\dagger$ from the root to the $i$-th leaf in dfs order$^\\ddagger$. Determine whether there exists a complete binary tree which satisfies array $a$. Note that you \\textbf{do not} need to reconstruct the tree.\n\n$^\\dagger$ The distance from vertex $u$ to vertex $v$ is defined as the sum of weights of the edges on the path from vertex $u$ to vertex $v$.\n\n$^\\ddagger$ The dfs order of the leaves is found by calling the following $dfs$ function on the root of the binary tree.\n\n\\begin{verbatim}\ndfs_order = []\nfunction dfs(v):\nif v is leaf:\nappend v to the back of dfs_order\nelse:\ndfs(left child of v)\ndfs(right child of v)\ndfs(root)\n\\end{verbatim}",
    "tutorial": "What does the distance of two leaves that share the same parent look like? What happens if we delete two leaves that share the same parent? Consider two leaves that share the same parent. They will be adjacent to each other in the dfs order, so their distances will be adjacent in array $a$. Furthermore, their distances to the root will differ by exactly $1$ since one of the edges from the parent to its children will have weight $0$ while the other will have weight $1$. If we delete two leaves that share the same parent, the parent itself will become the leaf. Since one of the edges from the parent to the child has weight $0$, the distance from the parent to the root is equal to the smaller distance between its two children. This means that deleting two leaves that share the same parent is the same as selecting an index $i$ such that $a_i = a_{i - 1} + 1$ or $a_i = a_{i + 1} + 1$, then removing $a_i$ from array $a$. Consider the largest value in $a$. If it is possible to delete it (meaning there is a value that is exactly one smaller than it to its left or right), we can delete it immediately. This is because keeping the largest value will not help to enable future operations as it can only help to delete elements that are $1$ greater than it, which is not possible for the largest value. Now, all we have to do is to maintain all elements that can be deleted and choose the element with the largest value each time. Then, whenever we delete an element, we need to check whether the two adjacent elements become deletable and update accordingly. We can do this using a priority_queue and a linked list in $O(n\\log n)$. Note that many other implementations exist, including several $O(n)$ solutions.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int MAXN = 200005;\n\nint n;\nint a[MAXN];\nint prv[MAXN],nxt[MAXN];\nbool in[MAXN];\n\nbool good(int i) {\n    if (i < 1 || i > n) {\n        return 0;\n    }\n    return a[prv[i]] == a[i] - 1 || a[nxt[i]] == a[i] - 1;\n}\nint main(){\n    ios::sync_with_stdio(0), cin.tie(0);\n    int t; cin >> t;\n    while (t--) {\n        cin >> n;\n        priority_queue<pair<int, int>> pq;\n        for (int i = 1; i <= n; i++) {\n            prv[i] = i - 1;\n            nxt[i] = i + 1;\n            in[i] = 0;\n            cin >> a[i];\n        }\n        a[n + 1] = a[0] = -2;\n        for (int i = 1; i <= n; i++) {\n            if (good(i)) {\n                in[i] = 1;\n                pq.push({a[i], i});\n            }\n        }\n        while (!pq.empty()) {\n            auto [_, i] = pq.top(); pq.pop();\n            nxt[prv[i]] = nxt[i];\n            prv[nxt[i]] = prv[i];\n            if (!in[prv[i]] && good(prv[i])) {\n                in[prv[i]]=1;\n                pq.push({a[prv[i]], prv[i]});\n            }\n            if (!in[nxt[i]] && good(nxt[i])) {\n                in[nxt[i]]=1;\n                pq.push({a[nxt[i]], nxt[i]});\n            }\n        }\n        int mn = n, bad = 0;\n        for (int i = 1; i <= n; i++) {\n            bad += !in[i];\n            mn = min(a[i], mn);\n        }\n        if (bad == 1 && mn == 0) {\n            cout << \"YES\\n\";\n        } else {\n            cout << \"NO\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dsu",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1919",
    "index": "E",
    "title": "Counting Prefixes",
    "statement": "There is a hidden array $a$ of size $n$ consisting of only $1$ and $-1$. Let $p$ be the prefix sums of array $a$. More formally, $p$ is an array of length $n$ defined as $p_i = a_1 + a_2 + \\ldots + a_i$. Afterwards, array $p$ is sorted in non-decreasing order. For example, if $a = [1, -1, -1, 1, 1]$, then $p = [1, 0, -1, 0, 1]$ before sorting and $p = [-1, 0, 0, 1, 1]$ after sorting.\n\nYou are given the prefix sum array $p$ after sorting, but you do not know what array $a$ is. Your task is to count the number of initial arrays $a$ such that the above process results in the given sorted prefix sum array $p$. As this number can be large, you are only required to find it modulo $998\\,244\\,353$.",
    "tutorial": "Try solving the problem if the sum of elements of array $a$ is equal to $s$. If we can do this in $O(n)$ time, we can iterate through all possible values of $p_1 \\le s \\le p_n$ and sum up the number of ways for each possible sum. Consider starting with array $a = [1, 1, \\ldots, 1, -1, -1, \\ldots, -1]$ where there are $p_n$ occurences of $1$ and $p_n - s$ occurrences of $-1$. Then, try inserting $(-1, 1)$ into the array to fix the number of occurrences of prefix sum starting from the largest value ($p_n$) to the smallest value ($p_1$). Let us try to solve the problem if the sum of elements of array $a$ is equal to $s$. Consider starting array $a = [1, 1, \\ldots, 1, -1, -1, \\ldots, -1]$ where there are $p_n$ occurrences of $1$ and $p_n - s$ occurrences of $-1$. Notice that when we insert $(-1, 1)$ into array $a$ between positions $i$ and $i + 1$ where the sum of $a$ from $1$ to $i$ is $s$, two new prefix sums $s - 1$ and $s$ will be formed while the remaining prefix sums remain the same. Let us try to fix the prefix sums starting from the largest prefix sum to the smallest prefix sum. In the starting array $a$, we only have $1$ occurrence of prefix sum with value $p_n$. We can insert $(-1, 1)$ right after it $k$ times to increase the number of occurrences of prefix sum with value $p_n$ by $k$. In the process of doing so, the number of occurrences of prefix sum with value $p_n - 1$ also increased by $k$. Now, we want to fix the number of occurrences of prefix sum with value $p_n - 1$. If we already have $x$ occurrences but we require $y > x$ occurrences, we can choose to insert $y - 1$ pairs of $(-1, 1)$ right after any of the $x$ occurrences. We can calculate the number of ways using stars and bars to obtain the formula $y - 1\\choose y - x$. We continue using a similar idea to fix the number of occurrences of $p_n - 2, p_n - 3, \\ldots, p_1$, each time considering the additional occurrences that were contributed from the previous layer. Each layer can be calculated in $O(1)$ time after precomputing binomial coefficients, so the entire calculation to count the number of array $a$ whose sum is $s$ and has prefix sum consistent to the input takes $O(n)$ time. Then, we can iterate through all possible $p_1 \\le s \\le p_n$ and sum up the answers to obtain a solution that works in $O(n^2)$ time. Solve the problem in $O(n)$ time. Unfortunately, it seems like ARC146E is identical to this problem :(",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n\ntypedef long long ll;\nconst int INF = 1000000005;\nconst int MAXN = 200005;\nconst int MOD = 998244353;\n\nll fact[MAXN * 2], ifact[MAXN * 2];\nint t;\nint n;\nint f[MAXN * 2], d[MAXN * 2];\n\ninline ll ncr(int n, int r) {\n    if (r < 0 || n < r) {\n        return 0;\n    }\n    return fact[n] * ifact[r] % MOD * ifact[n - r] % MOD;\n}\n// count number of a_1 + a_2 + ... + a_n = x\ninline ll starbar(int n, int x) {\n    if (n == 0 && x == 0) {\n        return 1;\n    }\n    return ncr(x + n - 1, x);\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    fact[0] = 1;\n    for (int i = 1; i < MAXN * 2; i++) {\n        fact[i] = fact[i - 1] * i % MOD;\n    }\n    ifact[0] = ifact[1] = 1;\n    for (int i = 2; i < MAXN * 2; i++) {\n        ifact[i] = MOD - MOD / i * ifact[MOD % i] % MOD;\n    }\n    for (int i = 2; i < MAXN * 2; i++) {\n        ifact[i] = ifact[i - 1] * ifact[i] % MOD;\n    }\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        for (int i = 0; i < n * 2 + 5; i++) {\n            f[i] = 0;\n        }\n        n++;\n        for (int i = 1; i < n; i++) {\n            int s; cin >> s;\n            f[s + n]++;\n        }\n        f[n]++;\n        int mn = INF, mx = -INF;\n        for (int i = 0; i <= 2 * n; i++) {\n            if (f[i]) {\n                mn = min(mn, i);\n                mx = max(mx, i);\n            }\n        }\n        bool bad = 0;\n        for (int i = mn; i <= mx; i++) {\n            if (!f[i]) {\n                bad = 1;\n                break;\n            }\n        }\n        if (bad || mn == mx) {\n            cout << 0 << '\\n';\n            continue;\n        }\n        ll ans = 0;\n        for (int x = mx; x >= mn; x--) {\n            d[mx - 1] = f[mx] + (mx > n) - (mx == x);\n            for (int i = mx - 2; i >= mn - 1; i--) {\n                d[i] = f[i + 1] - d[i + 1] + (i >= x) + (i >= n);\n            }\n            if (d[mn - 1] != 0) {\n                continue;\n            }\n            ll res = 1;\n            for (int i = mx - 1; i >= mn; i--) {\n                res = res * starbar(d[i], f[i] - d[i]) % MOD;\n            }\n            ans += res;\n            if (ans >= MOD) {\n                ans -= MOD;\n            }\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1919",
    "index": "F1",
    "title": "Wine Factory (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $c_i$ and $z$. You can make hacks only if both versions of the problem are solved.}\n\nThere are three arrays $a$, $b$ and $c$. $a$ and $b$ have length $n$ and $c$ has length $n-1$. Let $W(a,b,c)$ denote the liters of wine created from the following process.\n\nCreate $n$ water towers. The $i$-th water tower initially has $a_i$ liters of water and has a wizard with power $b_i$ in front of it. Furthermore, for each $1 \\le i \\le n - 1$, there is a valve connecting water tower $i$ to $i + 1$ with capacity $c_i$.\n\nFor each $i$ from $1$ to $n$ in this order, the following happens:\n\n- The wizard in front of water tower $i$ removes at most $b_i$ liters of water from the tower and turns the removed water into wine.\n- If $i \\neq n$, at most $c_i$ liters of the remaining water left in water tower $i$ flows through the valve into water tower $i + 1$.\n\nThere are $q$ updates. In each update, you will be given integers $p$, $x$, $y$ and $z$ and you will update $a_p := x$, $b_p := y$ and $c_p := z$. After each update, find the value of $W(a,b,c)$. Note that previous updates to arrays $a$, $b$ and $c$ persist throughout future updates.",
    "tutorial": "When $c_i$ and $z$ equals $10^{18}$, it means that all the remaining water will always flow into the next water tower. Hence, the answer will be the sum of $a_i$ minus the amount of water remaining at tower $n$ after the process. From hint 1, our new task now is to determine the amount of water remaining at tower $n$ after the process. Let $v_i = a_i - b_i$. The remaining amount of water remaining at tower $n$ is the maximum suffix sum of $v$, or more formally $\\max\\limits_{1\\le k\\le n}\\ \\sum\\limits_{i = k}^n v_i$. We can use a segment tree where position $p$ of the segment tree stores $\\sum\\limits_{i = p}^n v_i$. The updates can be done using range prefix increment and the queries can be done using range maximum. Code ReLU segment tree. A similar method can be used to solve the full problem if you combine even more ReLUs. However, it is not very elegant and is much more complicated than the intended solution below. ReLU is a common activation function used in neural networks which is defined by $f(x) = \\max(x, 0)$. The objective of ReLU segment tree is to compose ReLU-like functions together. More precisely, ReLU segment tree can solve the following problem: You are given two arrays $a$ and $b$ of length $n$. You are required to answer the following queries: - $\\texttt{1 p x y}$. Update $a_p = x$ and $b_p = y$. - $\\texttt{2 l r c}$. Output the value of $f_l(f_{l+1}(\\ldots f_{r-1}(f_r(c))))$, where $f_i(x) = \\max(x - a_i, b_i)$. The main idea to solve the problem is to observe that composing ReLU functions still results in a ReLU function, so we just need to store in each node the resultant function $f(x) = \\max(x - p, q)$ after composing the functions that fall in the range of the segment tree node. For the merge function, we just need to figure out the details of composing two ReLU functions together.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n\ntypedef long long ll;\nconst ll LINF = 1000000000000000005;\nconst int MAXN = 500005;\n\nint n, q;\nint a[MAXN], b[MAXN];\nll c[MAXN];\nll v[MAXN], sv[MAXN];\n\nll mx[MAXN * 4], lz[MAXN * 4];\nvoid init(int u = 1, int lo = 1, int hi = n) {\n    lz[u] = 0;\n    if (lo == hi) {\n        mx[u] = sv[lo];\n    } else {\n        int mid = lo + hi >> 1;\n        init(u << 1, lo, mid);\n        init(u << 1 ^ 1, mid + 1, hi);\n        mx[u] = max(mx[u << 1], mx[u << 1 ^ 1]);\n    }\n}\nvoid propo(int u) {\n    if (lz[u] == 0) {\n        return;\n    }\n    lz[u << 1] += lz[u];\n    lz[u << 1 ^ 1] += lz[u];\n    mx[u << 1] += lz[u];\n    mx[u << 1 ^ 1] += lz[u];\n    lz[u] = 0;\n}\nvoid incre(int s, int e, ll x, int u = 1, int lo = 1, int hi = n) {\n    if (lo >= s && hi <= e) {\n        mx[u] += x;\n        lz[u] += x;\n        return;\n    }\n    propo(u);\n    int mid = lo + hi >> 1;\n    if (s <= mid) {\n        incre(s, e, x, u << 1, lo, mid);\n    }\n    if (e > mid) {\n        incre(s, e, x, u << 1 ^ 1, mid + 1, hi);\n    }\n    mx[u] = max(mx[u << 1], mx[u << 1 ^ 1]);\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    cin >> n >> q;\n    for (int i = 1; i <= n; i++) {\n        cin >> a[i];\n    }\n    for (int i = 1; i <= n; i++) {\n        cin >> b[i];\n    }\n    for (int i = 1; i < n; i++) {\n        cin >> c[i];\n    }\n    ll sma = 0;\n    for (int i = n; i >= 1; i--) {\n        v[i] = a[i] - b[i];\n        sv[i] = v[i] + sv[i + 1];\n        sma += a[i];\n    }\n    init();\n    while (q--) {\n        int p, x, y; ll z; cin >> p >> x >> y >> z;\n        sma -= a[p];\n        incre(1, p, -v[p]);\n        a[p] = x;\n        b[p] = y;\n        v[p] = a[p] - b[p];\n        sma += a[p];\n        incre(1, p, v[p]);\n        cout << sma - max(0ll, mx[1]) << '\\n';\n    }\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1919",
    "index": "F2",
    "title": "Wine Factory (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $c_i$ and $z$. You can make hacks only if both versions of the problem are solved.}\n\nThere are three arrays $a$, $b$ and $c$. $a$ and $b$ have length $n$ and $c$ has length $n-1$. Let $W(a,b,c)$ denote the liters of wine created from the following process.\n\nCreate $n$ water towers. The $i$-th water tower initially has $a_i$ liters of water and has a wizard with power $b_i$ in front of it. Furthermore, for each $1 \\le i \\le n - 1$, there is a valve connecting water tower $i$ to $i + 1$ with capacity $c_i$.\n\nFor each $i$ from $1$ to $n$ in this order, the following happens:\n\n- The wizard in front of water tower $i$ removes at most $b_i$ liters of water from the tower and turns the removed water into wine.\n- If $i \\neq n$, at most $c_i$ liters of the remaining water left in water tower $i$ flows through the valve into water tower $i + 1$.\n\nThere are $q$ updates. In each update, you will be given integers $p$, $x$, $y$ and $z$ and you will update $a_p := x$, $b_p := y$ and $c_p := z$. After each update, find the value of $W(a,b,c)$. Note that previous updates to arrays $a$, $b$ and $c$ persist throughout future updates.",
    "tutorial": "Try modelling this problem into a maximum flow problem. Try using minimum cut to find the maximum flow. Speed up finding the minimum cut using a segment tree. Consider a flow graph with $n + 2$ vertices. Let the source vertex be $s = n + 1$ and the sink vertex be $t = n + 2$. For each $i$ from $1$ to $n$, add edge $s\\rightarrow i$ with capacity $a_i$ and another edge $i\\rightarrow t$ with capacity $b_i$. Then for each $i$ from $1$ to $n - 1$, add edge $i\\rightarrow i + 1$ with capacity $c_i$. The maximum flow from $s$ to $t$ will be the answer to the problem. Let us try to find the minimum cut of the above graph instead. Claim: The minimum cut will contain exactly one of $s\\rightarrow i$ or $i\\rightarrow t$ for all $1\\le i\\le n$. Proof: If the minimum cut does not contain both $s\\rightarrow i$ and $i\\rightarrow t$, $s$ can reach $t$ through vertex $i$ and hence it is not a minimum cut. Now, we will prove why the minimum cut cannot contain both $s\\rightarrow i$ and $i\\rightarrow t$. Suppose there exists a minimum cut where there exists a vertex $1\\le i\\le n$ where $s\\rightarrow i$ and $i\\rightarrow t$ are both in the minimum cut. We will consider two cases: Case 1: $s$ can reach $i$ (through some sequence of vertices $s\\rightarrow j\\rightarrow j+1\\rightarrow \\ldots \\rightarrow i$ where $j < i$). If our minimum cut only contains $i\\rightarrow t$ without $s\\rightarrow i$, nothing changes as $s$ was already able to reach $i$ when $s\\rightarrow i$ was removed. Hence, $s$ will still be unable to reach $t$ and we found a minimum cut that has equal or smaller cost. Case 2: $s$ cannot reach $i$. If our minimum cut only contains $s\\rightarrow i$ without $i\\rightarrow t$, nothing changes as $s$ is still unable to reach $i$, so we cannot make use of the edge $i\\rightarrow t$ to reach $t$ from $s$. Hence, $s$ will still be unable to reach $t$ and we found a minimum cut that has equal or smaller cost. Now, all we have to do is select for each $1\\le i\\le n$, whether to cut the edge $s\\rightarrow i$ or the edge $i\\rightarrow t$. Let us use a string $x$ consisting of characters $\\texttt{A}$ and $\\texttt{B}$ to represent this. $x_i = \\texttt{A}$ means we decide to cut the edge $s\\rightarrow i$ for a cost of $a_i$ and $x_i = \\texttt{B}$ means we decide to cut the edge from $i\\rightarrow t$ for a cost of $b_i$. Notice that whenever we have $x_i = \\texttt{B}$ and $x_{i + 1} = \\texttt{A}$, $s$ can reach $t$ through $s\\rightarrow i\\rightarrow i + 1\\rightarrow t$. To prevent this, we have to cut the edge $i\\rightarrow i + 1$ for a cost of $c_i$. To handle updates, we can use a segment tree. Each node of the segment tree stores the minimum possible cost for each of the four combinations of the two endpoints being $\\texttt{A}$ or $\\texttt{B}$. When merging the segment tree nodes, add a cost of $c$ when the right endpoint of the left node is $\\texttt{B}$ and the left endpoint of the right node is $\\texttt{A}$. The final time complexity is $O(n\\log n)$ as only a segment tree is used.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n\ntypedef long long ll;\nconst ll LINF = 1000000000000000005ll;\nconst int MAXN = 500005;\n\nint n, q;\nint a[MAXN], b[MAXN];\nll c[MAXN];\n\nll st[MAXN * 4][2][2];\nvoid merge(int u, int lo, int hi) {\n    int mid = lo + hi >> 1, lc = u << 1, rc = u << 1 ^ 1;\n    for (int l = 0; l < 2; l++) {\n        for (int r = 0; r < 2; r++) {\n            st[u][l][r] = min({st[lc][l][0] + st[rc][0][r],\n                    st[lc][l][1] + st[rc][1][r],\n                    st[lc][l][0] + st[rc][1][r],\n                    st[lc][l][1] + st[rc][0][r] + c[mid]});\n        }\n    }\n}\nvoid init(int u = 1, int lo = 1, int hi = n) {\n    if (lo == hi) {\n        st[u][0][0] = a[lo];\n        st[u][1][1] = b[lo];\n        st[u][1][0] = st[u][0][1] = LINF;\n        return;\n    }\n    int mid = lo + hi >> 1, lc = u << 1, rc = u << 1 ^ 1;\n    init(lc, lo, mid);\n    init(rc, mid + 1, hi);\n    merge(u, lo, hi);\n}\nvoid upd(int p, int u = 1, int lo = 1, int hi = n) {\n    if (lo == hi) {\n        st[u][0][0] = a[lo];\n        st[u][1][1] = b[lo];\n        st[u][1][0] = st[u][0][1] = LINF;\n        return;\n    }\n    int mid = lo + hi >> 1, lc = u << 1, rc = u << 1 ^ 1;\n    if (p <= mid) {\n        upd(p, lc, lo, mid);\n    } else {\n        upd(p, rc, mid + 1, hi);\n    }\n    merge(u, lo, hi);\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    cin >> n >> q;\n    for (int i = 1; i <= n; i++) {\n        cin >> a[i];\n    }\n    for (int i = 1; i <= n; i++) {\n        cin >> b[i];\n    }\n    for (int i = 1; i < n; i++) {\n        cin >> c[i];\n    }\n    init();\n    while (q--) {\n        int p, x, y; ll z; cin >> p >> x >> y >> z;\n        a[p] = x; b[p] = y; c[p] = z;\n        upd(p);\n        cout << min({st[1][0][0], st[1][0][1], st[1][1][0], st[1][1][1]}) << '\\n';\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "flows",
      "greedy",
      "matrices"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1919",
    "index": "G",
    "title": "Tree LGM",
    "statement": "In TreeWorld, there is a popular two-player game played on a tree with $n$ vertices labelled from $1$ to $n$. In this game, the tournament leaders first choose a vertex to be the root of the tree and choose another vertex (possibly the same vertex as the root) to place a coin on. Then, each player will take turns moving the coin to any child$^\\dagger$ of the vertex that the coin is currently on. The first player who is unable to make a move loses.\n\nAlice wants to be a tree LGM, so she spends a lot of time studying the game. She wrote down an $n$ by $n$ matrix $s$, where $s_{i,j} = \\mathtt{1}$ if the first player can win with the root of the tree chosen to be vertex $i$, and the coin was initially placed on vertex $j$. Otherwise, $s_{i, j} = \\mathtt{0}$. Alice is a perfectionist, so she assumes that both players play perfectly in the game.\n\nHowever, she accidentally knocked her head on the way to the tournament and forgot what the tree looked like. Determine whether there exists a tree that satisfies the winning and losing states represented by matrix $s$, and if it exists, construct a valid tree.\n\n$^\\dagger$ A vertex $c$ is a child of vertex $u$ if there is an edge between $c$ and $u$, and $c$ does not lie on the unique simple path from the root to vertex $u$.",
    "tutorial": "Think about how you would construct matrix $s$ if you were given the tree. If $s_{i, i} = \\mathtt{0}$, what should the value of $s_{j, i}$ be for all $1\\le j\\le n$? For some $i$ where $s_{i, i} = \\mathtt{1}$, let $Z$ be a set containing all the vertices $j$ where $s_{j, i} = \\mathtt{0}$. More formally, $Z = \\{j\\ |\\ 1\\le j\\le n\\text{ and } s_{j, i} = \\mathtt{0}\\}$. Does $Z$ have any special properties? Using hint 3, can we break down the problem into smaller sub-problems? Try solving the problem if the values in each column are a constant. In other words, $s_{i, j} = s_{j, j}$ for all $1\\le i\\le n$ and $1\\le j\\le n$. Let us consider how we can code the checker for this problem. In other words, if we are given a tree, how can we construct matrix $s$? We can solve this using dynamic programming. $s_{i, j} = \\mathtt{1}$ if and only if at least one child $c$ of vertex $j$ (when the tree is rooted at vertex $i$) has $s_{i, c} = \\mathtt{0}$. This is because the player can move the coin from vertex $j$ to vertex $c$ which will cause the opponent to be in a losing state. For convenience, we will call a vertex $i$ special if there exists some $1\\le j\\le n$ where $s_{j, i} \\neq s_{i, i}$. Suppose there exist some $i$ where $s_{i, i} = \\mathtt{0}$. This means that moving the coin to any of the neighbours of $i$ results in a winning state for the opponent. If the tree was rooted at some other vertex $j\\neq i$, it will still be a losing state as it reduces the options that the player can move the coin to, so $s_{j, i}$ should be $\\mathtt{0}$ for all $1\\le j\\le n$. This means that special vertices must have $s_{i, i} = \\mathtt{1}$ Now, let us take a look at special vertices. Let $x$ be a special vertex, meaning $s_{x, x} = \\mathtt{1}$ and there exist some $j$ where $s_{j, x} = \\mathtt{0}$. Let $Z$ be a set containing all the vertices $j$ where $s_{j, x} = \\mathtt{0}$. More formally, $Z = \\{j\\ |\\ 1\\le j\\le n\\text{ and } s_{j, x} = \\mathtt{0}\\}$. $Z$ cannot be empty due to the property of special vertices. Notice that whenever we choose to root at some vertex $j\\neq x$, the number of children of $x$ decreases by exactly $1$. This is because the neighbour that lies on the path from vertex $x$ to vertex $j$ becomes the parent of $x$ instead of the child of $x$. If rooting the tree at vertex $x$ is a winning state but rooting the tree at some other vertex $j$ results in a losing state instead, it means that the only winning move is to move the coin from vertex $x$ to the neighbour that is on the path from vertex $x$ to $j$. Let $y$ denote the only neighbour of vertex $x$ where we can move the coin from vertex $x$ to vertex $y$ and win. In other words, $y$ is the neighbour of vertex $x$ where $y$ lies on the path of the vertices in set $Z$ and $x$. This means that $Z$ is the set of vertices that are in the subtree of $y$ rooted at vertex $x$. Now, let us try to find vertex $y$. Notice that $s_{y, y} = \\mathtt{1}$. This is because $s_{y, x} = \\mathtt{0}$, so the coin can be moved from vertex $y$ to vertex $x$ to result in a losing state for the opponent. Furthermore, $s_{j, y} = \\mathtt{0}$ if and only if $j$ is not in $Z$, otherwise $s_{j, y} = \\mathtt{1}$. This is because $s_{x, y} = \\mathtt{0}$ since moving the coin from vertex $x$ to vertex $y$ is a winning move for the first player. For all other vertex $u\\in Z$ that is not $y$, this property will not hold as even if $s_{u, u} = \\mathtt{1}$ and $s_{x, u} = \\mathtt{0}$, $s_{y, u}$ will be equal to $\\mathtt{0}$ as well as the tree being rooted at $x$ has the same effect as if it was rooted at $y$. Since $y \\in Z$, $s_{y, u} = \\mathtt{0}$ does not satisfy $s_{j, u} = \\mathtt{1}$ for all $j$ in $Z$. Since $y$ is a neighbour of vertex $x$, we know that there is an edge between vertex $y$ and $x$. Furthermore, we know that if the edge between vertex $y$ and $x$ is removed, the set of vertices $Z$ forms a single connected component containing $y$, while the set of vertices not in $Z$ forms another connected component containing $x$. This means that we can recursively solve the problem for the two connected components to check whether the values in the matrix $s$ are valid within their components. After recursively solving for each connected component, we are only left with non-special vertices ($s_{j, i} = s_{i, i}$ for all $1\\le j\\le n$) and some special vertices that already have an edge that connects to outside the component. Non-special vertices with $s_{i, i} = \\mathtt{1}$ has to be connected to at least $2$ non-special vertices with $s_{i, i} = \\mathtt{0}$. The most optimal way to do this is to form a line 0 - 1 - 0 - 1 - 0 as it requires the least amount of $s_{i, i} = \\mathtt{0}$. If there is not enough $s_{i, i} = \\mathtt{0}$ to form the line, a solution does not exist. Otherwise, connect the left-over $s_{i, i} = \\mathtt{0}$ to any of $s_{i, i} = \\mathtt{1}$. On the other hand, special vertices can either be connected to nothing, connected to other special vertices, or connected to non-special vertices with $s_{i, i} = \\mathtt{1}$. For the final step, we need to check whether $s_{i, j}$ is consistent when $i$ and $j$ are in different components (i.e. ($i\\in Z$ and $j\\notin Z$) or ($i\\notin Z$ and $j\\in Z$)). Notice that $s_{i, j} = s_{x, j}$ for all $i\\in Z$ and $j\\notin Z$ and $j\\neq x$, and $s_{i, j} = s_{y, j}$ for all $i\\notin Z$ and $j\\in Z$ and $j\\neq y$. From the steps above, we managed to account for every value in the matrix, hence if matrix $s$ is consistent through all the steps, the constructed tree would be valid as well. We can make use of xor hash to find vertex $x$ together with its corresponding vertex $y$. With xor hash, the time complexity is $O(n^2)$. Well-optimised bitset code with time complexity of $O(\\frac{n^3}{w})$ can pass as well.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n \nconst int MAXN = 5005;\n\nmt19937_64 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n \nint n;\nunsigned long long r[MAXN], hsh[MAXN], totr;\nstring s[MAXN];\nvector<pair<int, int>> ans;\n \nbool done[MAXN];\nbool solve(vector<int> grp) {\n    int pr = -1, pl = -1;\n    vector<int> lft, rht;\n    for (int i : grp) {\n        if (s[i][i] == '0' || done[i] || hsh[i] == totr) {\n            continue;\n        }\n        rht.clear();\n        for (int j : grp) {\n            if (s[j][i] == '0') {\n                lft.push_back(j);\n            } else {\n                rht.push_back(j);\n            }\n        }\n        if (!lft.empty()) {\n            pr = i;\n            break;\n        }\n    }\n    if (pr == -1) {\n        vector<int> dv, zero, one;\n        for (int i : grp) {\n            if (done[i]) {\n                dv.push_back(i);\n            } else if (s[i][i] == '0') {\n                zero.push_back(i);\n            } else {\n                one.push_back(i);\n            }\n        }\n        for (int i = 1; i < dv.size(); i++) {\n            ans.push_back({dv[i - 1], dv[i]});\n        }\n        if (one.empty() && zero.empty()) {\n            return 1;\n        }\n        if (one.size() >= zero.size()) {\n            return 0;\n        }\n        if (one.empty()) {\n            if (zero.size() >= 2 || !dv.empty()) {\n                return 0;\n            }\n            return 1;\n        }\n        for (int i = 0; i < one.size(); i++) {\n            ans.push_back({zero[i], one[i]});\n            ans.push_back({one[i], zero[i + 1]});\n        }\n        for (int i = one.size() + 1; i < zero.size(); i++) {\n            ans.push_back({one[0], zero[i]});\n        }\n        if (!dv.empty()) {\n            ans.push_back({one[0], dv[0]});\n        }\n        return 1;\n    }\n    for (int i : lft) {\n        if (s[i][i] == '0' || done[i] || ((hsh[i] ^ hsh[pr]) != totr)) {\n            continue;\n        }\n        vector<int> trht;\n        for (int j : grp) {\n            if (s[j][i] == '0') {\n                trht.push_back(j);\n            }\n        }\n        if (trht == rht) {\n            pl = i;\n            break;\n        }\n    }\n    if (pl == -1) {\n        return 0;\n    }\n    for (int i : lft) {\n        for (int j : rht) {\n            if (j == pr) {\n                continue;\n            }\n            if (s[i][j] != s[pr][j]) {\n                return 0;\n            }\n        }\n    }\n    for (int i : rht) {\n        for (int j : lft) {\n            if (j == pl) {\n                continue;\n            }\n            if (s[i][j] != s[pl][j]) {\n                return 0;\n            }\n        }\n    }\n    ans.push_back({pl, pr});\n    done[pl] = done[pr] = 1;\n    return solve(lft) && solve(rht);\n}\n \nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    cin >> n;\n    for (int i = 0; i < n; i++) {\n        cin >> s[i];\n    }\n    for (int i = 0; i < n; i++) {\n        r[i] = rnd();\n        totr ^= r[i];\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            if (s[i][j] == '1') {\n                hsh[j] ^= r[i];\n            }\n        }\n    }\n    bool pos = 1;\n    for (int i = 0; i < n; i++) {\n        if (s[i][i] == '1') {\n            continue;\n        }\n        for (int j = 0; j < n; j++) {\n            if (s[j][i] == '1') {\n                pos = 0;\n                break;\n            }\n        }\n    }\n    if (!pos) {\n        cout << \"NO\\n\";\n        return 0;\n    }\n    vector<int> v(n, 0);\n    iota(v.begin(), v.end(), 0);\n    if (!solve(v)) {\n        cout << \"NO\\n\";\n        return 0;\n    }\n    cout << \"YES\\n\";\n    for (auto [u, v] : ans) {\n        cout << u + 1 << ' ' << v + 1 << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "divide and conquer",
      "games",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1919",
    "index": "H",
    "title": "Tree Diameter",
    "statement": "There is a hidden tree with $n$ vertices. The $n-1$ edges of the tree are numbered from $1$ to $n-1$. You can ask the following queries of two types:\n\n- Give the grader an array $a$ with $n - 1$ \\textbf{positive} integers. For each edge from $1$ to $n - 1$, the weight of edge $i$ is set to $a_i$. Then, the grader will return the length of the diameter$^\\dagger$.\n- Give the grader two indices $1 \\le a, b \\le n - 1$. The grader will return the number of edges between edges $a$ and $b$. In other words, if edge $a$ connects $u_a$ and $v_a$ while edge $b$ connects $u_b$ and $v_b$, the grader will return $\\min(\\text{dist}(u_a, u_b), \\text{dist}(v_a, u_b), \\text{dist}(u_a, v_b), \\text{dist}(v_a, v_b))$, where $\\text{dist}(u, v)$ represents the number of edges on the path between vertices $u$ and $v$.\n\nFind any tree isomorphic$^\\ddagger$ to the hidden tree after at most $n$ queries of type 1 and $n$ queries of type 2 in any order.\n\n$^\\dagger$ The distance between two vertices is the sum of the weights on the unique simple path that connects them. The diameter is the largest of all those distances.\n\n$^\\ddagger$ Two trees, consisting of $n$ vertices each, are called isomorphic if there exists a permutation $p$ containing integers from $1$ to $n$ such that edge ($u$, $v$) is present in the first tree if and only if the edge ($p_u$, $p_v$) is present in the second tree.",
    "tutorial": "Full solution: dario2994 The original problem allowed $5n$ type 1 queries and $n$ type 2 queries and was used as the last problem of a Div. 2 round. When we opened the round for testing, dario2994 solved the problem using $2n$ type 1 queries, and a few days later, he managed to improve his solution to use only $n$ type 1 queries. This was what made us decide to change this round into a Div. 1 round instead of a Div. 2 round. Try rooting the tree at an edge. Use $n - 2$ of query $2$ to find the distance of every edge to the root. For convenience, we will call the distance of an edge to the root the depth of the edge. We start with only the root edge, then add edges of depth $0$, followed by depth $1, 2, \\ldots$ If we want to add a new edge with depth $i$, we need to attach it to one of the edges with depth $i - 1$. We can let the weight of the edge we want to attach be $10^9$ to force the diameter to pass through it, then let the edges of depth $i - 1$ have weights be different multiples of $n$. This way, we can determine which edges of depth $i - 1$ are used in the diameter (unless the two largest edges are used). Make use of isomorphism to handle the case in hint 4 where the largest two edges are used. If isomorphism cannot be used, find a leaf edge of a lower depth than the query edge and force the diameter to pass through the leaf edge and the query edge. Then, only 1 edge of depth $i - 1$ will be used and the edge weights for edges of depth $i - 1$ can follow a similar structure as hint 4. We will root the tree at edge $1$. Then, use $n - 2$ of query $2$ to find the distance of every edge to the root. For convenience, we will call the distance of an edge to the root the depth of the edge. Our objective is to add the edges in increasing order of depth, so when we are inserting an edge of depth $i$, all edges of depth $i - 1$ are already inserted and we just have to figure out which edge of depth $i - 1$ we have to attach the edge of depth $i$ to. For convenience, the edge weights used in query $1$ will be $1$ by default unless otherwise stated. Let $c_i$ store the list of edges with depth $i$. Suppose we want to insert edge $u$ into the tree and the depth of edge $u$ is $d$. We let the weight of the edge $u$ be $10 ^ 9$ and the weight of edges in $c_{d - 1}$ be $n, 2n, 3n, \\ldots, (|c_{d - 1}| - 2)n, (|c_{d - 1}| - 1)n, (|c_{d - 1}| - 1)n$. The diameter will pass through edge $u$, the parent edge of $u$, as well as one edge of weight $(|c_{d - 1}| - 1)n$. If we calculate $\\left\\lfloor\\frac{\\text{diameter} - 10^9}{n}\\right\\rfloor - (|c_{d - 1}| - 1)$, we will be able to tell the index of the parent edge of $u$. However, there is one exception. When the parent edge of $u$ is one of the last 2 edges of $c_{d - 1}$, we are unable to differentiate between the two of them as they have the same weight. This is not a problem if the last 2 edges are isomorphic to each other, as attaching $u$ to either parent results in the same tree. For now, we will assume that the last 2 edges of $c_{d - 1}$ are isomorphic to each other. However, after attaching edge $u$ to one last 2 edges in $c_{d - 1}$, they are no longer isomorphic. Hence, we need to use a different method to insert the remaining edges of depth $d$. Let the new edge that we want to insert be $v$. Let the weight of edges $u$ and $v$ be $10^9$ and the weights of edges in $c_{d - 1}$ be the same as before. Now, we can use $\\left\\lfloor\\frac{\\text{diameter} - 2\\cdot 10^9}{n}\\right\\rfloor$ to determine whether edge $v$ share the same parent as $u$, and if it does not share the same parent, it can still determine the index of the parent edge of $v$. With the additional information of whether edge $v$ shares the same parent as edge $u$, we will be able to differentiate the last 2 edges of $c_{d - 1}$ from each other. Now, we just need to handle the issue where the last 2 edges of $c_{d - 1}$ are not isomorphic. When we only have the root edge at the start, the left and right ends of the edge are isomorphic (note that for the root edge, we consider it as 2 separate edges, one with the left endpoint and one with the right endpoint). We try to maintain the isomorphism as we add edges of increasing depth. Suppose the last two edges of $c_{d - 1}$ are isomorphic. Let the two edges be $a$ and $b$. Then, we insert edges of depth $d$ using the above method. Let the child edges attached to $a$ and $b$ be represented by sets $S_a$ and $S_b$ respectively. If either $S_a$ or $S_b$ has sizes at least $2$, the two edges in the same set will be isomorphic, so we can let those 2 edges be the last 2 edges of $c_d$. Now, the sizes of $S_a$ and $S_b$ are both strictly smaller than $2$. If the sizes of both sets are exactly $1$, the two edges from each set will be isomorphic as well as $a$ and $b$ are isomorphic. Now, the only case left is if at least one of the sets is empty. Without loss of generality, assume that $S_a$ is empty. Since it is no longer possible to maintain two isomorphic edges, we now change our objective to find a leaf (it will be clear why in the following paragraphs). If $S_b$ is empty as well, both $a$ and $b$ are leaves so we can choose any one of them. If $S_b$ is not empty, then $a$ and $b$ are no longer isomorphic due to their children. This means that we cannot simply use $b$ as the leaf $S_a$ might be children of $b$ instead of $a$ as we did not differentiate $a$ and $b$ in the previous paragraphs. To determine whether $S_a$ belongs to $a$ or $b$, we can make use of one type 2 query to find the distance between one of the edges in $S_a$ and $a$. If the distance is $0$, it means that $S_a$ belongs to $a$. Otherwise, the distance will be $1$ and $S_a$ belongs to $b$. Now that we found a leaf, we can use the following method to insert an edge $u$ of depth $d$. We let the weight of the edge $u$ and the leaf edge be $10 ^ 9$ and the weight of edges in $c_{d - 1}$ be $n, 2n, 3n, \\ldots, (|c_{d - 1}| - 2)n, (|c_{d - 1}| - 1)n, |c_{d - 1}|n$. The diameter will pass through edge $u$, the leaf edge, and only one edge of depth $d - 1$ which is the parent edge of $u$. Hence, after finding a leaf edge, we can uniquely determine the parent edge from $\\left\\lfloor\\frac{\\text{diameter} - 2\\cdot 10^9}{n}\\right\\rfloor$. We used $n - 2$ type 1 queries and $n - 1$ type 2 queries in total. This is because we used a single type 1 query for each non-root edge. We used $n - 2$ type 2 queries at the start, and we only used $1$ additional type 2 query when we were no longer able to maintain two isomorphic edges and changed our methodology to use a leaf edge instead.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n\ntypedef long long ll;\nconst int INF = 1000000000;\nconst int MAXN = 1000;\n\nint n;\nint lvl[MAXN + 5];\nint pe[MAXN + 5];\nvector<int> ch[MAXN + 5];\n\nll query(vector<int> a) {\n    cout << \"? 1\";\n    for (int i = 1; i < n; i++) {\n        cout << ' ' << a[i];\n    }\n    cout << endl;\n    ll res; cin >> res;\n    return res;\n}\nint query(int a, int b) {\n    cout << \"? 2 \" << a << ' ' << b << endl;\n    int res; cin >> res;\n    return res;\n}\n\nint main() {\n    cin >> n;\n    for (int i = 2; i < n; i++) {\n        lvl[i] = query(1, i);\n    }\n    int ptr = 3;\n    vector<int> base = {1, 2};\n    pe[1] = pe[2] = 1;\n    bool iso = 1;\n    int piv = -1;\n    for (int l = 0; l < n; l++) {\n        vector<int> a(n, 1);\n        int m = base.size();\n        for (int i = 0; i < m; i++) {\n            a[pe[base[i]]] = min(i + 1, m - iso) * MAXN;\n        }\n        if (!iso) {\n            a[pe[piv]] = INF;\n        }\n        bool ciso = 0;\n        for (int u = 2; u < n; u++) {\n            if (lvl[u] != l) {\n                continue;\n            }\n            a[u] = INF;\n            ll res = query(a) - INF;\n            a[u] = 1;\n            if (!iso || ciso) {\n                res -= INF;\n            }\n            int id = res / MAXN;\n            if (iso && l) {\n                id -= m - 1;\n            }\n            int v = ptr++;\n            pe[v] = u;\n            if (ciso) {\n                if ((l == 0 && id == 0) || id == -(m - 1)) {\n                    ch[base[m - 2]].push_back(v);\n                } else if (id == m - 1) {\n                    ch[base[m - 1]].push_back(v);\n                } else {\n                    ch[base[id - 1]].push_back(v);\n                }\n            } else if (iso && id == m - 1) {\n                ch[base[m - 2]].push_back(v);\n                ciso = 1;\n                a[u] = INF;\n            } else {\n                ch[base[id - 1]].push_back(v);\n            }\n        }\n        if (m >= 2 && ch[base[m - 2]].size() > ch[base[m - 1]].size()) {\n            swap(base[m - 2], base[m - 1]);\n        }\n        vector<int> nbase;\n        for (int i = 0; i < m; i++) {\n            for (int j : ch[base[i]]) {\n                nbase.push_back(j);\n            }\n        }\n        if (!iso || ch[base[m - 1]].size() >= 2 || ch[base[m - 2]].size() == 1) {\n            base = nbase;\n            continue;\n        }\n        if (ch[base[m - 1]].empty()) {\n            piv = base[m - 1];\n        } else {\n            ll res = query(pe[ch[base[m - 1]][0]], pe[base[m - 1]]);\n            if (res) {\n                swap(base[m - 2], base[m - 1]);\n                swap(ch[base[m - 2]], ch[base[m - 1]]);\n            }\n            piv = base[m - 2];\n        }\n        iso = 0;\n        base = nbase;\n    }\n    cout << '!' << endl;\n    cout << 1 << ' ' << 2 << endl;\n    for (int u = 1; u <= n; u++) {\n        for (int v : ch[u]) {\n            cout << u << ' ' << v << endl;\n        }\n    }\n}",
    "tags": [
      "interactive",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1920",
    "index": "A",
    "title": "Satisfying Constraints",
    "statement": "Alex is solving a problem. He has $n$ constraints on what the integer $k$ can be. There are three types of constraints:\n\n- $k$ must be \\textbf{greater than or equal to} some integer $x$;\n- $k$ must be \\textbf{less than or equal to} some integer $x$;\n- $k$ must be \\textbf{not equal to} some integer $x$.\n\nHelp Alex find the number of integers $k$ that satisfy all $n$ constraints. It is guaranteed that the \\textbf{answer is finite} (there exists at least one constraint of type $1$ and at least one constraint of type $2$). Also, it is guaranteed that \\textbf{no two constraints are the exact same}.",
    "tutorial": "Suppose there are no $\\neq$ constraints. How would you solve the problem? How would you then factor in the $\\neq$ constraints into your solution? Let's first only consider the $\\geq$ and $\\leq$ constraints. The integers satisfying those two constraints will be some contiguous interval $[l, r]$. To find $[l,r]$, for each $\\geq x$ constraint, we do $l := \\max{(l, x)}$ and for each $\\leq x$ constraint, we do $r := \\min{(r, x)}$. Now, for each, $\\neq x$ constraint, we check if $x$ is in $[l, r]$. If so, we subtract one from the answer (remember that there are no duplicate constraints). Let the total number of times we subtract be $s$. Then our answer is $\\max{(r-l+1-s,0)}$. The time complexity of this solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\nvoid solve(){\n    int n;\n    cin >> n;\n\n    int l = 1;\n    int r = 1e9;\n    int s = 0;\n    \n    vector<int> neq;\n\n    for (int i = 0; i < n; i++){\n        int a, x;\n        cin >> a >> x;\n\n        if (a == 1)\n            l = max(l, x);\n        if (a == 2)\n            r = min(r, x);\n        if (a == 3)\n            neq.push_back(x);\n    }\n    for (int x : neq)\n        if (x >= l and x <= r)\n            s++;\n    \n    cout<<max(r - l + 1 - s, 0)<<\"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc; \n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1920",
    "index": "B",
    "title": "Summation Game",
    "statement": "Alice and Bob are playing a game. They have an array $a_1, a_2,\\ldots,a_n$. The game consists of two steps:\n\n- First, Alice will remove \\textbf{at most} $k$ elements from the array.\n- Second, Bob will multiply \\textbf{at most} $x$ elements of the array by $-1$.\n\nAlice wants to maximize the sum of elements of the array while Bob wants to minimize it. Find the sum of elements of the array after the game if both players play optimally.",
    "tutorial": "What is the optimal strategy for Bob? It is optimal for Bob to negate the $x$ largest elements of the array. So what should Alice do? It is optimal for Bob to negate the $x$ largest elements of the array. So in order to minimize the damage Bob will do, Alice should always remove some number of largest elements. To solve the problem, we can sort the array and iterate over $i$ ($0 \\leq i \\leq k$) where $i$ is the number of elements Alice removes. For each $i$, we know that Alice will remove the $i$ largest elements of the array and Bob will then negate the $x$ largest remaining elements. So the sum at the end can be calculated quickly with prefix sums. The time complexity is $O(n \\log n)$ because of sorting.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\nvoid solve(){\n    int n, k, x;\n    cin >> n >> k >> x;\n    \n    int A[n + 1] = {};\n    for (int i = 1; i <= n; i++)\n        cin >> A[i];\n    \n    sort(A + 1, A + n + 1, greater<int>());\n\n    for (int i = 1; i <= n; i++)\n        A[i] += A[i - 1];\n    \n    int ans = -1e9;\n    for (int i = 0; i <= k; i++)\n        ans = max(ans, A[n] - 2 * A[min(i + x, n)] + A[i]);\n    \n    cout<<ans<<\"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc; \n    cin >> tc;\n    \n    while (tc--) \n        solve();\n}",
    "tags": [
      "games",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1920",
    "index": "C",
    "title": "Partitioning the Array",
    "statement": "Allen has an array $a_1, a_2,\\ldots,a_n$. For every positive integer $k$ that is a divisor of $n$, Allen does the following:\n\n- He partitions the array into $\\frac{n}{k}$ disjoint subarrays of length $k$. In other words, he partitions the array into the following subarrays: $$[a_1,a_2,\\ldots,a_k],[a_{k+1}, a_{k+2},\\ldots,a_{2k}],\\ldots,[a_{n-k+1},a_{n-k+2},\\ldots,a_{n}]$$\n- Allen earns one point if there exists some positive integer $m$ ($m \\geq 2$) such that if he replaces every element in the array with its remainder when divided by $m$, then all subarrays will be identical.\n\nHelp Allen find the number of points he will earn.",
    "tutorial": "Try to solve the problem for just two integers $x$ and $y$. Under what $m$ are they equal (modulo $m$)? How can we use the previous hint and gcd to solve the problem? For some $x$ and $y$, let's try to find all $m$ such that $x \\bmod m \\equiv y \\bmod m$. We can rearrange the equation into $(x-y) \\equiv 0 \\pmod m$. Thus, if $m$ is a factor of $|x-y|$, then $x$ and $y$ will be equal modulo $m$. Let's solve for some $k$. A valid partition exists if there exists some $m>1$ such that the following is true: $a_1 \\equiv a_{1+k} \\pmod m$ $a_2 \\equiv a_{2+k} \\pmod m$ ... $a_{n-k} \\equiv a_{n} \\pmod m$ The first condition $a_1 \\equiv a_{1+k} \\pmod m$ is satisfied if $m$ is a factor of $|a_1-a_{1+k}|$. The second condition $a_2 \\equiv a_{2+k} \\pmod m$ is satisfied if $m$ is a factor of $|a_2-a_{2+k}|$. And so on... Thus, all conditions are satisfied if $m$ is a factor of: $|a_1-a_{1+k}|, |a_2-a_{2+k}|,...,|a_{n-k}-a_n|$ In other words, all conditions are satisfied if $m$ is a factor of: $\\gcd(|a_1-a_{1+k}|, |a_2-a_{2+k}|,...,|a_{n-k}-a_n|)$ So a valid $m$ exists for some $k$ if the aforementioned $\\gcd$ is greater than $1$. We can iterate over all possible $k$ (remember that $k$ is a divisor of $n$) and solve for each $k$ to get our answer. The time complexity of this will be $O((n + \\log n) \\cdot \\text{max divisors of n})$. Note that each pass through the array takes $n + \\log n$ time because of how the gcd will either be halved or stay the same at each point.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\nvoid solve(){\n    int n; \n    cin >> n;\n\n    int A[n];\n    for (int &i : A)\n        cin >> i;\n    \n    int ans = 0;\n    for (int k = 1; k <= n; k++){\n        if (n % k == 0){\n            int g = 0;\n            for (int i = 0; i + k < n; i++)\n                g = __gcd(g, abs(A[i + k] - A[i]));\n            ans += (g != 1);\n        }\n    }\n    cout<<ans<<\"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc; \n    cin >> tc;\n\n    while (tc--) \n        solve();\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1920",
    "index": "D",
    "title": "Array Repetition",
    "statement": "Jayden has an array $a$ which is initially empty. There are $n$ operations of two types he must perform in the given order.\n\n- Jayden appends an integer $x$ ($1 \\leq x \\leq n$) to the end of array $a$.\n- Jayden appends $x$ copies of array $a$ to the end of array $a$. In other words, array $a$ becomes $[a,\\underbrace{a,\\ldots,a}_{x}]$. It is guaranteed that he has done at least one operation of the first type before this.\n\nJayden has $q$ queries. For each query, you must tell him the $k$-th element of array $a$. The elements of the array are numbered from $1$.",
    "tutorial": "For some query try to trace your way back to where the $k$-th number was added. Here's an example of tracing back: $\\underbrace{[l_1, l_2,...l_{x}]}_{\\text{length } x} \\underbrace{[l_1, l_2,...l_{x}]}_{\\text{length } x} \\underbrace{[l_1, l_2,...l_{x}]}_{\\text{length } x} ... \\underbrace{[l_1, \\textbf{l_2},...l_{x}]}_{\\text{length } x}$ Suppose the $k$-th element is the bolded $l_2$. Finding the $k$-th element is equivalent to finding the ($k \\bmod x$)-th element (unless if $k \\bmod x$ is $0$). First, let's precalculate some things: $lst_i=\\text{last element after performing the first $i$ operations}$ $dp_i=\\text{number of elements after the first i operations}$ Now, let's try answering some query $k$. If we have some $dp_i=k$ then the answer is $lst_i$. Otherwise, let's find the first $i$ such that $dp_i > k$. This $i$ will be a repeat operation and our answer will lie within one of the repetitions. Our list at this point will look like: $\\underbrace{[l_1, l_2,...l_{dp_{i-1}}]}_{\\text{length } dp_{i-1}} \\underbrace{[l_1, l_2,...l_{dp_{i-1}}]}_{\\text{length } dp_{i-1}} \\underbrace{[l_1, l_2,...l_{dp_{i-1}}]}_{\\text{length } dp_{i-1}} ... \\underbrace{[l_1, \\textbf{l_2},...l_{dp_{i-1}}]}_{\\text{length } dp_{i-1}}$ Let the $k$-th element be the bolded $l_2$ of the final repetition. As you can see, finding the $k$-the element is equivalent to finding the $(k \\bmod dp_{i-1})$-th element. Thus, we should do $k:=k \\bmod dp_{i-1}$ and repeat! But there is one more case! If $k \\equiv 0 \\pmod {dp_{i-1}}$ then the answer is $lst_{i-1}$. At this point there are 2 ways we can go about solving this: Notice that after $\\log{(\\max{k})}$ operations of the second type, the number of elements will exceed $\\max{k}$. So we only care about the first $\\log{(\\max{k})}$ operations of the second type. Thus, iterate through the $\\log{(\\max{k})}$ operations of the second type backwards and perform the casework described above. This leads to a $O(n+q\\log{(\\max{k})})$ solution or a $O(n+q(\\log{(\\max{k})}+\\log n))$ solution depending on implementation details. Observe that $k:=k \\bmod dp_{i-1}$ will reduce $k$ by at least half. If we repeatedly binary search for the first $i$ such that $dp_i \\geq k$, and then do $k:=k \\bmod dp_{i-1}$ (or stop if it's one of the other cases), then each query will take $O(\\log n\\log k)$ time so the total time complexity will be $O(n+q\\log n\\log {(\\max{k})})$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\n#define ll long long\n\nvoid solve(){\n    int n, q;\n    cin >> n >> q;\n\n    ll dp[n + 1] = {};\n    int lstAdd[n + 1] = {};\n\n    for (int i = 1; i <= n; i++){\n        int a, v; \n        cin >> a >> v;\n\n        if (a == 1){\n            lstAdd[i] = v;\n            dp[i] = dp[i - 1] + 1;\n        }\n        else{\n            lstAdd[i] = lstAdd[i - 1];\n            dp[i] = ((v + 1) > 2e18 / dp[i - 1]) ? (ll)2e18 : dp[i - 1] * (v + 1);\n        }\n    }\n    while (q--){\n        ll k; \n        cin >> k;\n\n        while (true){\n            int pos = lower_bound(dp + 1, dp + n + 1, k) - dp;\n            \n            if (dp[pos] == k){\n                cout<<lstAdd[pos]<<\" \\n\"[q == 0];\n                break;\n            }\n            if (k % dp[pos - 1] == 0){\n                cout<<lstAdd[pos - 1]<<\" \\n\"[q == 0];\n                break;\n            }\n            k %= dp[pos - 1];\n        }\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc; \n    cin >> tc;\n    \n    while (tc--) \n        solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "dsu",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1920",
    "index": "E",
    "title": "Counting Binary Strings",
    "statement": "Patrick calls a substring$^\\dagger$ of a binary string$^\\ddagger$ good if this substring contains exactly one 1.\n\nHelp Patrick count the number of binary strings $s$ such that $s$ contains exactly $n$ good substrings and has no good substring of length strictly greater than $k$. Note that substrings are differentiated by their location in the string, so if $s =$ 1010 you should count both occurrences of 10.\n\n$^\\dagger$ A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\n$^\\ddagger$ A binary string is a string that only contains the characters 0 and 1.",
    "tutorial": "How do you count the number of good substrings in a string? We can count the number of good substrings in a string with the counting contribution technique. Now try to solve this problem with dynamic programming. $\\frac{n}{1} + \\frac{n}{2} + \\cdots + \\frac{n}{n} = O(n\\log n)$ Let's first solve the problem where we are given some string $s$ and must count the number of good substrings. To do this we use the technique of counting contributions. For every $1$ in $s$, we find the number of good substrings containing that $1$. Consider the following example: $\\underbrace{00001}_{a_1} \\! \\! \\! \\, \\underbrace{ \\; \\, \\! 0001}_{a_2} \\! \\! \\! \\, \\underbrace{ \\; \\, \\! 00000001}_{a_3} \\! \\! \\! \\, \\underbrace{ \\; \\, \\! 0001}_{a_4} \\! \\! \\! \\, \\underbrace{ \\; \\, \\! 000}_{a_5}$ The number of good substrings in this example is $a_1 a_2 + a_2 a_3 + a_3 a_4 + a_4 a_5$. We can create such array for any string $s$ and the number of good substrings of $s$ is the sum of the products of adjacent elements of the array. This motivates us to reformulate the problem. Instead, we count the number of arrays $a_1,a_2,...,a_m$ such that every element is positive and the sum of the products of adjacent elements is exactly equal to $n$. Furthermore, every pair of adjacent elements should have sum minus $1$ be less than or equal to $k$. We can solve this with dynamic programming. $dp_{i,j} = \\text{number of arrays with sum $i$ and last element $j$}$ $\\displaystyle dp_{i, j} = \\sum_{p=1}^{\\min({\\lfloor \\frac{i}{j} \\rfloor},\\, k-j+1)}{dp_{i - j \\cdot p,p}}$ The key observation is that we only have to iterate $p$ up to $\\lfloor \\frac{i}{j} \\rfloor$ (since if $p$ is any greater, $j \\cdot p$ will exceed $i$). At $j=1$, we will iterate over at most $\\lfloor \\frac{i}{1} \\rfloor$ values of $p$. At $j=2$, we will iterate over at most $\\lfloor \\frac{i}{2} \\rfloor$ values of $p$. In total, at each $i$, we will iterate over at most $\\lfloor \\frac{i}{1} \\rfloor + \\lfloor \\frac{i}{2} \\rfloor +\\cdots + \\lfloor \\frac{i}{i} \\rfloor \\approx i \\log i$ values of $p$. Thus, the time complexity of our solution is $O(nk\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n \nconst int md = 998244353;\n \nvoid solve(){\n    int n, k;\n    cin >> n >> k;\n \n    int dp[n + 1][k + 1] = {};\n    int ans = 0;\n    \n    fill(dp[0] + 1, dp[0] + k + 1, 1);\n \n    for (int sum = 1; sum <= n; sum++){\n        for (int cur = 1; cur <= k; cur++){\n            for (int prv = 1; cur * prv <= sum and cur + prv - 1 <= k; prv++)\n                dp[sum][cur] = (dp[sum][cur] + dp[sum - cur * prv][prv]) % md;\n \n            if (sum == n)\n                ans = (ans + dp[sum][cur]) % md;\n        }\n    }\n    cout<<ans<<\"\\n\";\n}\n \nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc; \n    cin >> tc;\n \n    while (tc--)\n        solve();\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1920",
    "index": "F1",
    "title": "Smooth Sailing (Easy Version)",
    "statement": "\\textbf{The only difference between the two versions of this problem is the constraint on $q$. You can make hacks only if both versions of the problem are solved.}\n\nThomas is sailing around an island surrounded by the ocean. The ocean and island can be represented by a grid with $n$ rows and $m$ columns. The rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The position of a cell at row $r$ and column $c$ can be represented as $(r, c)$. Below is an example of a valid grid.\n\n\\begin{center}\n{\\small Example of a valid grid}\n\\end{center}\n\nThere are three types of cells: island, ocean and underwater volcano. Cells representing the island are marked with a '#', cells representing the ocean are marked with a '.', and cells representing an underwater volcano are marked with a 'v'. It is guaranteed that there is at least one island cell and at least one underwater volcano cell. It is also guaranteed that the set of all island cells forms a single connected component$^{\\dagger}$ and the set of all ocean cells and underwater volcano cells forms a single connected component. Additionally, it is guaranteed that there are no island cells at the edge of the grid (that is, at row $1$, at row $n$, at column $1$, and at column $m$).\n\nDefine a round trip starting from cell $(x, y)$ as a path Thomas takes which satisfies the following conditions:\n\n- The path starts and ends at $(x, y)$.\n- If Thomas is at cell $(i, j)$, he can go to cells $(i+1, j)$, $(i-1, j)$, $(i, j-1)$, and $(i, j+1)$ as long as the destination cell \\textbf{is an ocean cell or an underwater volcano cell} and is still inside the grid. Note that it is allowed for Thomas to visit the same cell multiple times in the same round trip.\n- The path must go around the island and fully encircle it. Some path $p$ fully encircles the island if it is impossible to go from an island cell to a cell on the grid border by only traveling \\textbf{to adjacent on a side or diagonal} cells without visiting a cell on path $p$. In the image below, the path starting from $(2, 2)$, going to $(1, 3)$, and going back to $(2, 2)$ the other way does \\textbf{not} fully encircle the island and is not considered a round trip.\n\n\\begin{center}\n{\\small Example of a path that does \\textbf{not} fully encircle the island}\n\\end{center}\n\nThe safety of a round trip is the minimum Manhattan distance$^{\\ddagger}$ from a cell on the round trip to an underwater volcano (note that the presence of island cells does not impact this distance).\n\nYou have $q$ queries. A query can be represented as $(x, y)$ and for every query, you want to find the maximum safety of a round trip starting from $(x, y)$. It is guaranteed that $(x, y)$ is an ocean cell or an underwater volcano cell.\n\n$^{\\dagger}$A set of cells forms a single connected component if from any cell of this set it is possible to reach any other cell of this set by moving only through the cells of this set, each time going to a cell \\textbf{with a common side}.\n\n$^{\\ddagger}$Manhattan distance between cells $(r_1, c_1)$ and $(r_2, c_2)$ is equal to $|r_1 - r_2| + |c_1 - c_2|$.",
    "tutorial": "Use the fact that a good some path $p$ fully encircles the island if it is impossible to go from an island cell to a cell on the border by only travelling to adjacent or diagonal cells without touching a cell on path $p$. Binary search! For each non-island cell $(i, j)$, let $d_{i,j}$ be the minimum Manhattan distance of cell $(i, j)$ to an underwater volcano. We can find all $d_{i,j}$ with a multisource BFS from all underwater volcanos. The danger of a round trip is the smallest value of $d_{u,v}$ over all $(u, v)$ in the path. For each query, binary search on the answer $k$ - we can only visit cell ($i, j$) if $d_{i,j} \\geq k$. Now, let's mark all cells ($i, j$) ($d_{i,j} \\geq k$) reachable from ($x, y$). There exists a valid round trip if it is not possible to go from an island cell to a border cell without touching a marked cell. The time complexity of this solution is $O(nm \\log{(n+m)})$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int mx = 3e5 + 5;\nconst int diAdj[4] = {-1, 0, 1, 0}, djAdj[4] = {0, -1, 0, 1};\nconst int diDiag[8] = {0, 0, -1, 1, -1, -1, 1, 1}, djDiag[8] = {-1, 1, 0, 0, -1, 1, 1, -1};\n\nint n, m, q, islandi, islandj; string A[mx]; vector<int> dist[mx]; vector<bool> reachable[mx], islandVis[mx]; queue<pair<int, int>> bfsQ;\n\nbool inGrid(int i, int j){\n    return i >= 0 and i < n and j >= 0 and j < m;\n}\nbool onBorder(int i, int j){\n    return i == 0 or i == n - 1 or j == 0 or j == m - 1;\n}\nvoid getReach(int i, int j, int minVal){\n    if (!inGrid(i, j) or reachable[i][j] or dist[i][j] < minVal or A[i][j] == '#')\n        return;\n    \n    reachable[i][j] = true;\n\n    for (int dir = 0; dir < 4; dir++)\n        getReach(i + diAdj[dir], j + djAdj[dir], minVal);\n}\nbool reachBorder(int i, int j){\n    if (!inGrid(i, j) or reachable[i][j] or islandVis[i][j])\n        return false;\n    \n    if (onBorder(i, j))\n        return true;\n    \n    islandVis[i][j] = true;\n\n    bool ok = false;\n    for (int dir = 0; dir < 8; dir++)\n        ok |= reachBorder(i + diDiag[dir], j + djDiag[dir]);\n    return ok;\n}\nbool existsRoundTrip(int x, int y, int minVal){\n    // Reset\n    for (int i = 0; i < n; i++){\n        reachable[i] = vector<bool>(m, false);\n        islandVis[i] = vector<bool>(m, false);\n    }\n    // Get all valid cells you can reach from (x, y)\n    getReach(x, y, minVal);\n\n    // Check if the valid cells you can reach from (x, y) blocks the island from the border\n    return !reachBorder(islandi, islandj);\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    cin >> n >> m >> q;\n\n    for (int i = 0; i < n; i++){\n        cin >> A[i];\n        dist[i] = vector<int>(m, 1e9);\n\n        for (int j = 0; j < m; j++){\n            if (A[i][j] == 'v'){\n                dist[i][j] = 0;\n                bfsQ.push({i, j});\n            }\n            if (A[i][j] == '#'){\n                islandi = i;\n                islandj = j;\n            }\n        }\n    }\n\n    // Multisource BFS to find min distance to volcano\n    while (bfsQ.size()){\n        auto [i, j] = bfsQ.front(); bfsQ.pop();\n\n        for (int dir = 0; dir < 4; dir++){\n            int ni = i + diAdj[dir], nj = j + djAdj[dir];\n\n            if (inGrid(ni, nj) and dist[i][j] + 1 < dist[ni][nj]){\n                dist[ni][nj] = dist[i][j] + 1;\n                bfsQ.push({ni, nj});\n            }\n        }\n    }\n    while (q--){\n        int x, y;\n        cin >> x >> y;\n        x--; y--;\n\n        int L = 0, H = n + m;\n        while (L < H){\n            int M = (L + H + 1) / 2;\n            existsRoundTrip(x, y, M) ? L = M : H = M - 1;\n        }\n        cout<<L<<\"\\n\";\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "shortest paths"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1920",
    "index": "F2",
    "title": "Smooth Sailing (Hard Version)",
    "statement": "\\textbf{The only difference between the two versions of this problem is the constraint on $q$. You can make hacks only if both versions of the problem are solved.}\n\nThomas is sailing around an island surrounded by the ocean. The ocean and island can be represented by a grid with $n$ rows and $m$ columns. The rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The position of a cell at row $r$ and column $c$ can be represented as $(r, c)$. Below is an example of a valid grid.\n\n\\begin{center}\n{\\small Example of a valid grid}\n\\end{center}\n\nThere are three types of cells: island, ocean and underwater volcano. Cells representing the island are marked with a '#', cells representing the ocean are marked with a '.', and cells representing an underwater volcano are marked with a 'v'. It is guaranteed that there is at least one island cell and at least one underwater volcano cell. It is also guaranteed that the set of all island cells forms a single connected component$^{\\dagger}$ and the set of all ocean cells and underwater volcano cells forms a single connected component. Additionally, it is guaranteed that there are no island cells at the edge of the grid (that is, at row $1$, at row $n$, at column $1$, and at column $m$).\n\nDefine a round trip starting from cell $(x, y)$ as a path Thomas takes which satisfies the following conditions:\n\n- The path starts and ends at $(x, y)$.\n- If Thomas is at cell $(i, j)$, he can go to cells $(i+1, j)$, $(i-1, j)$, $(i, j-1)$, and $(i, j+1)$ as long as the destination cell \\textbf{is an ocean cell or an underwater volcano cell} and is still inside the grid. Note that it is allowed for Thomas to visit the same cell multiple times in the same round trip.\n- The path must go around the island and fully encircle it. Some path $p$ fully encircles the island if it is impossible to go from an island cell to a cell on the grid border by only traveling \\textbf{to adjacent on a side or diagonal} cells without visiting a cell on path $p$. In the image below, the path starting from $(2, 2)$, going to $(1, 3)$, and going back to $(2, 2)$ the other way does \\textbf{not} fully encircle the island and is not considered a round trip.\n\n\\begin{center}\n{\\small Example of a path that does \\textbf{not} fully encircle the island}\n\\end{center}\n\nThe safety of a round trip is the minimum Manhattan distance$^{\\ddagger}$ from a cell on the round trip to an underwater volcano (note that the presence of island cells does not impact this distance).\n\nYou have $q$ queries. A query can be represented as $(x, y)$ and for every query, you want to find the maximum safety of a round trip starting from $(x, y)$. It is guaranteed that $(x, y)$ is an ocean cell or an underwater volcano cell.\n\n$^{\\dagger}$A set of cells forms a single connected component if from any cell of this set it is possible to reach any other cell of this set by moving only through the cells of this set, each time going to a cell \\textbf{with a common side}.\n\n$^{\\ddagger}$Manhattan distance between cells $(r_1, c_1)$ and $(r_2, c_2)$ is equal to $|r_1 - r_2| + |c_1 - c_2|$.",
    "tutorial": "How do we check if a point is inside a polygon using a ray? If u draw line from island cell extending all the way right, an optimal round trip will cross this line an odd number of times. What can your state be? How can we simplify this problem down into finding the path that maximizes the minimum node? How can we solve this classic problem? For each non-island cell $(i, j)$, let $d_{i,j}$ be the minimum Manhattan distance of cell $(i, j)$ to an underwater volcano. We can find all $d_{i,j}$ with a multisource BFS from all underwater volcanos. The danger of a round trip is the smallest value of $d_{u,v}$ over all $(u, v)$ in the path. Consider any island cell. We can take inspiration from how we check whether a point is in a polygon - if a point is inside the polygon then a ray starting from the point and going in any direction will intersect the polygon an odd number of times. Draw an imaginary line along the top border of the cell and extend it all the way to the right of the grid. We can observe that an optimal round trip will always cross the line an odd number of times. Using this observation, we can let our state be $(\\text{row}, \\, \\text{column}, \\, \\text{parity of the number of times we crossed the line})$. Naively, we can binary search for our answer and BFS to check if $(x, y, 0)$ and $(x, y, 1)$ are connected. This solves the easy version of the problem. To fully solve this problem, we can add states (and their corresponding edges to already added states) one at a time from highest $d$ to lowest $d$. For each query $(x, y)$, we want to find the first time when $(x, y, 0)$ and $(x, y, 1)$ become connected. This is a classic DSU with small to large merging problem. In short, we drop a token labeled with the index of the query at both $(x, y, 0)$ and $(x, y, 1)$. Each time we merge, we also merge the sets of tokens small to large and check if merging has caused two tokens of the same label to be in the same component. The time complexity of our solution is $O(nm \\log{(nm)} + q\\log^2 q)$ with the $\\log{(nm)}$ coming from sorting the states or edges. Note that there exists a $O((nm \\cdot \\alpha{(nm)} + q) \\cdot \\log{(n+m)})$ parallel binary search solution as well as a $O(nm \\log{(nm)} + q\\log{(nm)})$ solution that uses LCA queries on the Kruskal's reconstruction tree or min path queries on the MSTs. In fact, with offline LCA queries, we can reduce the complexity to $O(nm \\cdot \\alpha{(nm)} + q)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\nconst int mx = 3e5 + 5, di[4] = {-1, 0, 1, 0}, dj[4] = {0, -1, 0, 1};\n\nint n, m, q, id, linei, linej, par[mx * 4], dep[mx], up[mx * 4][21], val[mx * 4]; \nstring A[mx]; queue<pair<int, int>> bfsQ; vector<int> dist[mx], adj[mx * 4]; vector<array<int, 3>> edges; \n\nint enc(int i, int j, bool crossParity){\n    // Note that nodes are 1 indexed\n    return 1 + i * m + j + crossParity * n * m;\n}\nbool inGrid(int i, int j){\n    return i >= 0 and i < n and j >= 0 and j < m;\n}\nint getR(int i){ \n    return i == par[i] ? i : par[i] = getR(par[i]); \n}\nvoid merge(int a, int b, int w){\n    a = getR(a); b = getR(b); \n\n    if (a == b)\n        return;\n    \n    adj[id].push_back(a);\n    adj[id].push_back(b);\n    val[id] = w;\n\n    par[a] = par[b] = id;\n    id++;\n}\nvoid dfs(int i){\n    for (int l = 1; l < 21; l++)\n        up[i][l] = up[up[i][l - 1]][l - 1];\n    \n    for (int to : adj[i]){\n        if (to != up[i][0]){\n            up[to][0] = i;\n            dep[to] = dep[i] + 1;\n            dfs(to);\n        }\n    }\n}\nint qry(int x, int y){\n    if (dep[x] < dep[y]) \n        swap(x, y);\n\n    for (int l = 20, jmp = dep[x] - dep[y]; ~l; l--){\n        if (jmp & (1 << l)){\n            x = up[x][l];\n        }\n    }\n    if (x == y)\n        return val[x];\n    \n    for (int l = 20; ~l; l--){\n        if (up[x][l] != up[y][l]){\n            x = up[x][l]; \n            y = up[y][l];\n        }\n    }\n    return val[up[x][0]];\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    cin >> n >> m >> q;\n\n    for (int i = 0; i < n; i++){\n        cin >> A[i];\n        for (int j = 0; j < m; j++){\n            dist[i].push_back(1e9);\n\n            if (A[i][j] == 'v'){\n                dist[i][j] = 0;\n                bfsQ.push({i, j});\n            }\n            if (A[i][j] == '#'){\n                linei = i;\n                linej = j;\n            }\n        }\n    }\n\n    // Multisource BFS to find min distance to volcano\n    while (bfsQ.size()){\n        auto [i, j] = bfsQ.front(); bfsQ.pop();\n\n        for (int dir = 0; dir < 4; dir++){\n            int ni = i + di[dir], nj = j + dj[dir];\n\n            if (inGrid(ni, nj) and dist[i][j] + 1 < dist[ni][nj]){\n                dist[ni][nj] = dist[i][j] + 1;\n                bfsQ.push({ni, nj});\n            }\n        }\n    }\n\n    // Get the edges\n    for (int i = 0; i < n; i++){\n        for (int j = 0; j < m; j++){\n            // Look at cells to the up and left (so dir = 0 and dir = 1)\n            for (int dir = 0; dir < 2; dir++){\n                int ni = i + di[dir], nj = j + dj[dir];\n\n                if (inGrid(ni, nj) and A[i][j] != '#' and A[ni][nj] != '#'){\n                    int w = min(dist[i][j], dist[ni][nj]);\n                    \n                    // Crosses the line\n                    if (i == linei and ni == linei - 1 and j > linej){\n                        edges.push_back({w, enc(i, j, 0), enc(ni, nj, 1)});\n                        edges.push_back({w, enc(i, j, 1), enc(ni, nj, 0)});\n                    }\n                    // Doesn't cross the line\n                    else{\n                        edges.push_back({w, enc(i, j, 0), enc(ni, nj, 0)});\n                        edges.push_back({w, enc(i, j, 1), enc(ni, nj, 1)});\n                    }\n                }\n            }\n        }\n    }\n\n    // We merge from largest w to smallest\n    sort(edges.begin(), edges.end(), greater<array<int, 3>>());\n\n    // Init DSU stuff\n    id = n * m * 2 + 1;\n    iota(par, par + mx * 4, 0);\n\n    // Merge\n    for (auto [w, u, v] : edges)\n        merge(u, v, w);\n    \n    // DFS to construct the Kruskal's reconstruction trees\n    for (int i = n * m * 4; i; i--)\n        if (!up[i][0])\n            dfs(i);\n    \n    // Answer queries via LCA queries\n    for (int i = 0; i < q; i++){\n        int x, y; cin >> x >> y;\n        x--; y--;\n        cout<<qry(enc(x, y, 0), enc(x, y, 1))<<\"\\n\";\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "dsu",
      "geometry",
      "graphs",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1921",
    "index": "A",
    "title": "Square",
    "statement": "A square of positive (strictly greater than $0$) area is located on the coordinate plane, with sides parallel to the coordinate axes. You are given the coordinates of its corners, in random order. Your task is to find the area of the square.",
    "tutorial": "There are many ways to solve this problem, the simplest way is as follows. Let's find the minimum and maximum coordinate $x$ among all the corners of the square. The difference of these coordinates will give us the length of the square side $d = x_{max} - x_{min}$. After that, we can calculate the area of the square as $s = d^2$.",
    "code": "t = int(input())\nfor _ in range(t):\n    a = [[int(x) for x in input().split()] for i in range(4)]\n    x = [p[0] for p in a]\n    dx = max(x) - min(x)\n    print(dx * dx)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1921",
    "index": "B",
    "title": "Arranging Cats",
    "statement": "In order to test the hypothesis about the cats, the scientists must arrange the cats in the boxes in a specific way. Of course, they would like to test the hypothesis and publish a sensational article as quickly as possible, because they are too engrossed in the next hypothesis about the phone's battery charge.\n\nScientists have $n$ boxes in which cats may or may not sit. Let the current state of the boxes be denoted by the sequence $b_1, \\dots, b_n$: $b_i = 1$ if there is a cat in box number $i$, and $b_i = 0$ otherwise.\n\nFortunately, the unlimited production of cats has already been established, so in one day, the scientists can perform one of the following operations:\n\n- Take a new cat and place it in a box (for some $i$ such that $b_i = 0$, assign $b_i = 1$).\n- Remove a cat from a box and send it into retirement (for some $i$ such that $b_i = 1$, assign $b_i = 0$).\n- Move a cat from one box to another (for some $i, j$ such that $b_i = 1, b_j = 0$, assign $b_i = 0, b_j = 1$).\n\nIt has also been found that some boxes were immediately filled with cats. Therefore, the scientists know the initial position of the cats in the boxes $s_1, \\dots, s_n$ and the desired position $f_1, \\dots, f_n$.\n\nDue to the large amount of paperwork, the scientists do not have time to solve this problem. Help them for the sake of science and indicate the minimum number of days required to test the hypothesis.",
    "tutorial": "Denote the amount of indices $i$ such that $s_i = 0$ and $f_i = 1$ as $add\\_amnt$. Since it is impossible to change 0 to 1 at two different positions in one turn, the answer is not less than $add\\_amnt$. Analogously, if $rmv\\_amnt$ is amount of indices such that $s_i = 1$ and $f_i = 0$, the answer is not less than $rmv\\_amnt$. It turns out that the answer is actually equal to $\\max (add\\_amnt, rmv\\_amnt)$. We can simply apply move operation from the index $i$ with $s_i = 1, f_i = 0$ to $j$ with $s_j = 0, f_j = 1$ while there are both of these types of indices (that will be $\\min (rmv\\_amnt, add\\_amnt)$ operations) and then add or remove the rest of unsatisfied indices (that is exactly $|rmv\\_amnt - add\\_amnt|$ operations).",
    "code": "t = int(input())\n\nfor _ in range(t):\n    n = int(input())\n    start = [int(x) for x in input()]\n    finish = [int(x) for x in input()]\n    pairs = list(zip(start, finish))\n    add_amnt = sum(int(a < b) for a, b in pairs)\n    rmv_amnt = sum(int(a > b) for a, b in pairs)\n    print(max(add_amnt, rmv_amnt))",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1921",
    "index": "C",
    "title": "Sending Messages",
    "statement": "Stepan is a very busy person. Today he needs to send $n$ messages at moments $m_1, m_2, \\dots m_n$ ($m_i < m_{i + 1}$). Unfortunately, by the moment $0$, his phone only has $f$ units of charge left. At the moment $0$, the phone is turned on.\n\nThe phone loses $a$ units of charge for each unit of time it is on. Also, at any moment, Stepan can turn off the phone and turn it on later. This action consumes $b$ units of energy each time. Consider turning on and off to be instantaneous, so you can turn it on at moment $x$ and send a message at the same moment, and vice versa, send a message at moment $x$ and turn off the phone at the same moment.\n\nIf at any point the charge level drops to $0$ (becomes $\\le 0$), it is impossible to send a message at that moment.\n\nSince all messages are very important to Stepan, he wants to know if he can send all the messages without the possibility of charging the phone.",
    "tutorial": "The most challenging part of this problem was probably carefully understanding the problem statement. The problem can be reduced to the following. There are $n$ time intervals: from 0 to $m_1$, from $m_1$ to $m_2$, ..., from $m_{n-1}$ to $m_n$. For each interval, we need to find a way to spend as little charge of the phone as possible, and check that the total amount of charge we spend is less than the initial charge of the phone. To spend the minimum amount of charge for one time interval, we can act in one of two ways. Let the length of the interval be $t$. We either leave the phone on and spend $a\\cdot t$ units of charge, or turn off the phone at the very beginning of the interval and turn it on at the very end, spending $b$ units of charge. The total time complexity of this solution is $O(n)$.",
    "code": "t = int(input())\nfor _ in range(t):\n    n, f, a, b = map(int, input().split())\n    m = [0] + [int(x) for x in input().split()]\n    for i in range(1, n + 1):\n        f -= min(a * (m[i] - m[i - 1]), b)\n    print('YES' if f > 0 else 'NO')",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1921",
    "index": "D",
    "title": "Very Different Array",
    "statement": "Petya has an array $a_i$ of $n$ integers. His brother Vasya became envious and decided to make his own array of $n$ integers.\n\nTo do this, he found $m$ integers $b_i$ ($m\\ge n$), and now he wants to choose some $n$ integers of them and arrange them in a certain order to obtain an array $c_i$ of length $n$.\n\nTo avoid being similar to his brother, Vasya wants to make his array as different as possible from Petya's array. Specifically, he wants the total difference $D = \\sum_{i=1}^{n} |a_i - c_i|$ to be as large as possible.\n\nHelp Vasya find the maximum difference $D$ he can obtain.",
    "tutorial": "Let's sort the array $a$ in ascending order, and the array $b$ in descending order. Notice that small elements of array $a$ need to be matched with large elements of array $b$ and vice versa. Thus, for some $k$, we need to take a prefix of array $b$ of length $k$ and a suffix of length $n-k$, and form array $c$ from them. We iterate over the value of $k$ from $0$ to $n$, and each time $k$ changes by 1, only one element of array $c$ changes, so we can recalculate the value of $D$ in $O(1)$. We select the maximum value of $D$ from the obtained values to get the answer. This solution works in $O(n)$ time plus the initial sorting in $O(n \\log n)$. There are other ways to solve the problem in the same time complexity.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nstruct test {\n   void solve() {\n        int n, m;\n        cin >> n >> m;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) cin >> a[i];\n        vector<int> b(m);\n        for (int i = 0; i < m; i++) cin >> b[i];\n        sort(a.begin(), a.end());\n        sort(b.rbegin(), b.rend());\n        vector<int> c(n);\n        long long s = 0;\n        for (int i = 0; i < n; i++) {\n            c[i] = b[m &mdash; n + i];\n            s += abs(c[i] &mdash; a[i]);\n        }\n        long long res = 0;\n        for (int k = 0; k <= n; k++) {\n            res = max(res, s);\n            if (k < n) {\n                s -= abs(c[k] &mdash; a[k]);\n                c[k] = b[k];\n                s += abs(c[k] &mdash; a[k]);\n            }\n        }\n        cout << res << \"\\n\";\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(false);\n    int n;\n    cin >> n;\n    for (int i = 0; i < n; i++) {\n        test().solve();\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1921",
    "index": "E",
    "title": "Eat the Chip",
    "statement": "Alice and Bob are playing a game on a checkered board. The board has $h$ rows, numbered from top to bottom, and $w$ columns, numbered from left to right. Both players have a chip each. Initially, Alice's chip is located at the cell with coordinates $(x_a, y_a)$ (row $x_a$, column $y_a$), and Bob's chip is located at $(x_b, y_b)$. It is guaranteed that the initial positions of the chips do not coincide. Players take turns making moves, with Alice starting.\n\nOn her turn, Alice can move her chip one cell down or one cell down-right or down-left (diagonally). Bob, on the other hand, moves his chip one cell up, up-right, or up-left. It is not allowed to make moves that go beyond the board boundaries.\n\nMore formally, if at the beginning of Alice's turn she is in the cell with coordinates $(x_a, y_a)$, then she can move her chip to one of the cells $(x_a + 1, y_a)$, $(x_a + 1, y_a - 1)$, or $(x_a + 1, y_a + 1)$. Bob, on his turn, from the cell $(x_b, y_b)$ can move to $(x_b - 1, y_b)$, $(x_b - 1, y_b - 1)$, or $(x_b - 1, y_b + 1)$. The new chip coordinates $(x', y')$ must satisfy the conditions $1 \\le x' \\le h$ and $1 \\le y' \\le w$.\n\n\\begin{center}\nExample game state. Alice plays with the white chip, Bob with the black one. Arrows indicate possible moves.\n\\end{center}\n\nA player immediately wins if they place their chip in a cell occupied by the other player's chip. If either player cannot make a move (Alice—if she is in the last row, i.e. $x_a = h$, Bob—if he is in the first row, i.e. $x_b = 1$), the game immediately ends in a draw.\n\nWhat will be the outcome of the game if both opponents play optimally?",
    "tutorial": "First, let's note that the difference $x_b - x_a$ decreases exactly by one each (both Alice's and Bob's) turn. In the end, if one of the players was able to win, $x_b - x_a = 0$. In particular, that means that if $x_a - x_b$ is initially odd then only Alice has a chance of winning the match and vice versa. Suppose that $x_a - x_b$ is initially even (the outcome of the match could be either Bob's win or draw). If $x_a \\ge x_b$ the answer is immediately draw. Otherwise, the players will make $t = (x_b - x_a) / 2$ moves each before $x_a = x_b$. If at some point during these $2t$ moves Bob can achieve $y_a = y_b$, he is winning as he can continue with symmetrical responses to Alice's turns. If $y_a > y_b$ and Bob cannot reach right border ($w > y_b + t$), Alice can always choose the rightmost option for her and after each of $2t$ moves $y_a$ will be greater than $y_b$ which means Bob cannot win. Otherwise, if Bob always chooses the rightmost option for him, he will eventually achieve $y_a = y_b$. The case when $y_a$ is initially less than $y_b$ as well as the case when Alice has a chance to win ($x_b - x_a$ is odd) can be covered in a similar way.",
    "code": "def solve():\n    h, w, xA, yA, xB, yB = map(int, input().split())\n\n    if (xA - xB) % 2 == 0:\n        winner = \"Bob\"\n        if xA >= xB:\n            win = False\n        elif yA == yB:\n            win = True\n        else:\n            if yA < yB:\n                n_turns = yB - 1\n            else:\n                n_turns = w - yB\n            win = xB - 2 * n_turns >= xA\n\n    else:\n        winner = \"Alice\"\n\n        xA += 1\n        yA += 0 if yB - yA == 0 else 1 if yB - yA > 0 else -1\n\n        if xA > xB:\n            win = False\n        elif yA == yB:\n            win = True\n        else:\n            if yA < yB:\n                n_turns = w - yA\n            else:\n                n_turns = yA - 1\n            win = xB - 2 * n_turns >= xA\n\n    print(winner if win else \"Draw\")\n\n\nt = int(input())\n\nfor _ in range(t):\n    solve()",
    "tags": [
      "brute force",
      "games",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1921",
    "index": "F",
    "title": "Sum of Progression",
    "statement": "You are given an array $a$ of $n$ numbers. There are also $q$ queries of the form $s, d, k$.\n\nFor each query $q$, find the sum of elements $a_s + a_{s+d} \\cdot 2 + \\dots + a_{s + d \\cdot (k - 1)} \\cdot k$. In other words, for each query, it is necessary to find the sum of $k$ elements of the array with indices starting from the $s$-th, taking steps of size $d$, multiplying it by the serial number of the element in the resulting sequence.",
    "tutorial": "The key idea is that we know how to calculate the sum $(i - l + 1) \\cdot a_i$ for $l \\le i \\le r$ fast - we need to calculate all prefix sums $i \\cdot a_i$ and $a_i$ for $1 \\le i \\le k$, then take the difference between the $r$-th and $(l-1)$-th of $i \\cdot a_i$ and subtract the difference between the $r$-th and $(l-1)$-th multiplied by $l - 1$. This way queries with step $1$ will be processed in $O(n + q)$ time, where $q$ is the total amount of queries with step 1. But this idea can be generalized to the following: we can precalculate all the prefix sums and all the prefix sums with multiplication by index for every $d_0 \\le d$ in $O(n \\cdot d)$ time, and then process all queries with step $d_0 \\le d$ in $O(1)$ time. However, for all other queries we can process a single query in $O(n / d)$ time, because the difference between consecutive elements in the resulting sequence is greater than $d$. Combining these two ideas, we get a solution with a time complexity $O(n \\cdot d + q \\cdot n / d)$. Setting $d = \\sqrt{q}$, we get a solution with a time complexity $O(n \\sqrt{q})$. The model solution fixes the value of $d = 322$, which is equal to $\\sqrt{MAX}$. Interestingly, this solution can be generalized to calculate the sums $(i + 1) ^ 2 \\cdot a_{s + d \\cdot i}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nlong long precalc[322][200322];\nlong long precalci[322][200322];\n\nvoid solve() {\n    int n, q;\n    cin >> n >> q;\n    vector<long long> a(n);\n    int pivot = 1;\n    while (pivot * pivot < n) {\n        pivot++;\n    }\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    for (int i = 0; i < pivot; i++) {\n        for (int j = 0; j <= i; j++) {\n            precalc[i][j] = 0LL;\n            precalci[i][j] = 0LL;\n        }\n        for (int j = 0; j < n; j++) {\n            precalci[i][j + i + 1] = precalci[i][j] + a[j] * (j / (i + 1) + 1);\n            precalc[i][j + i + 1] = precalc[i][j] + a[j];\n        }\n    }\n    while (q--) {\n        int s, d;\n        long long k;\n        long long ans = 0;\n        cin >> s >> d >> k;\n        s--;\n        if (d > pivot) {\n            for (int i = s; i <= s + (k - 1) * d; i += d) {\n                ans += a[i] * ((i - s) / d + 1);\n            }\n            cout << ans << \" \";\n            continue;\n        }\n        long long last = s + d * k - d;\n        int first = s;\n        cout << precalci[d - 1][last + d] - precalci[d - 1][first] -\n                (precalc[d - 1][last + d] - precalc[d - 1][first]) * (first / d) << ' ';\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        solve();\n        if (tests) cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1921",
    "index": "G",
    "title": "Mischievous Shooter",
    "statement": "Once the mischievous and wayward shooter named Shel found himself on a rectangular field of size $n \\times m$, divided into unit squares. Each cell either contains a target or not.\n\nShel only had a lucky shotgun with him, with which he can shoot in one of the four directions: right-down, left-down, left-up, or right-up. When fired, the shotgun hits all targets in the chosen direction, the Manhattan distance to which does not exceed a fixed constant $k$. The Manhattan distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is equal to $|x_1 - x_2| + |y_1 - y_2|$.\n\n\\begin{center}\n{\\small Possible hit areas for $k = 3$.}\n\\end{center}\n\nShel's goal is to hit as many targets as possible. Please help him find this value.",
    "tutorial": "First of all, notice that we can consider only the case where the triangle of affected cells is oriented left-up. To solve the remaining cases, we can solve the problem for four different board orientations and choose the maximum result from the obtained results. We will store several arrays with prefix sums: for the sum of all numbers in the cells of the current column above the given one, as well as for the sum of all numbers in the cells up and to the right of the given one. Using such prefix sums, we can easily recalculate the answer in cell $(i, j)$ through the answer in cell $(i, j-1)$ in $O(1)$. To do this, we need to add the sum of the cells marked in green and subtract the sum of the cells marked in red. The total time complexity of this solution is $O(nm)$. Note that the problem could also be solved in time $O(nm\\min(n, m))$ by computing prefix sums in the minimum of the directions and calculating the sums in the triangle in $O(\\min(n, m))$. This solution also fits within the time limit.",
    "code": "//ciao_chill\n#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nint n, m, k;\nvector<vector<int>> a;\n\n\nbool prov(int i, int j) {\n    return 0 <= i && i < n && 0 <= j && j < m;\n}\n\nint ans() {\n    int cnt = 0;\n    int dp[n][m];\n    int pref[n][m];\n    int pref_up[n][m];\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            pref_up[i][j] = a[i][j];\n            if (prov(i - 1, j))\n                pref_up[i][j] += pref_up[i - 1][j];\n        }\n    }\n\n    for (int i = 0; i < n; i++) {\n        for (int j = m - 1; j >= 0; j--) {\n            pref[i][j] = a[i][j];\n            if (prov(i - 1, j + 1))\n                pref[i][j] += pref[i - 1][j + 1];\n        }\n    }\n\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            dp[i][j] = pref_up[i][j];\n            if (prov(i - k, j))\n                dp[i][j] -= pref_up[i - k][j];\n            if (prov(i, j - 1))\n                dp[i][j] += dp[i][j - 1];\n            if (j < k) {\n                int i1 = j - k + i;\n                if (i1 >= 0)\n                    dp[i][j] -= pref[i1][0];\n            }\n            else\n                dp[i][j] -= pref[i][j - k];\n            if (prov(i - k, j))\n                dp[i][j] += pref[i - k][j];\n            cnt = max(cnt, dp[i][j]);\n        }\n    }\n\n    return cnt;\n}\n\nvoid solve() {\n    cin >> n >> m >> k;\n    k++;\n    char c;\n    bool st[n][m];\n    a.resize(n);\n    for (int i = 0; i < n; i++) {\n        a[i].resize(m);\n    }\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++)\n        {\n            cin >> c;\n            st[i][j] = (c == '#');\n            a[i][j] = st[i][j];\n        }\n    }\n\n    int mx = ans();\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            a[i][j] = st[n - i - 1][j];\n        }\n    }\n    mx = max(mx, ans());\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            a[i][j] = st[i][m - j - 1];\n        }\n    }\n    mx = max(mx, ans());\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < m; j++) {\n            a[i][j] = st[n - i - 1][m - j - 1];\n        }\n    }\n    mx = max(mx, ans());\n\n    cout << mx << '\\n';\n\n}\n\nsigned main() {\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    ios_base::sync_with_stdio(false);\n\n    int tt;\n    cin >> tt;\n    while (tt--)\n        solve();\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "dp",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1922",
    "index": "A",
    "title": "Tricky Template",
    "statement": "You are given an integer $n$ and three strings $a, b, c$, each consisting of $n$ lowercase Latin letters.\n\nLet a template be a string $t$ consisting of $n$ lowercase and/or uppercase Latin letters. The string $s$ matches the template $t$ if the following conditions hold for all $i$ from $1$ to $n$:\n\n- if the $i$-th letter of the template is \\textbf{lowercase}, then $s_i$ must be \\textbf{the same} as $t_i$;\n- if the $i$-th letter of the template is \\textbf{uppercase}, then $s_i$ must be \\textbf{different} from the \\textbf{lowercase version} of $t_i$. For example, if there is a letter 'A' in the template, you cannot use the letter 'a' in the corresponding position of the string.\n\nAccordingly, the string doesn't match the template if the condition doesn't hold for at least one $i$.\n\nDetermine whether there exists a template $t$ such that the strings $a$ and $b$ match it, while the string $c$ does not.",
    "tutorial": "In order for a string not to match the pattern, there must be at least one position $i$ from $1$ to $n$ where the condition doesn't hold. Let's iterate over this position and check if it is possible to pick a letter in the pattern such that $a_i$ and $b_i$ match, while $c_i$ doesn't match. If $a_i$ or $b_i$ equal $c_i$, then it is definitely not possible. Since $c_i$ does not match, the equal letter also doesn't match. And if both are different from $c_i$, then it is always possible to pick the uppercase letter $c_i$ to only prohibit it. Great, now the string $c$ definitely doesn't match the pattern. Now we should guarantee that the strings $a$ and $b$ match. Complete the template as follows: for all other positions, we will pick uppercase letters that differ from both $a_i$ and $b_i$. Obviously, among $26$ letters, there will always be such a letter. Therefore, the solution is as follows: iterate over the positions and check that there is at least one where $a_i$ differs from $c_i$ and $b_i$ differs from $c_i$. If there is, the answer is \"YES\". Otherwise, the answer is \"NO\". Overall complexity: $O(n)$ for each testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ta = input()\n\tb = input()\n\tc = input()\n\tprint(\"YES\" if any([a[i] != c[i] and b[i] != c[i] for i in range(n)]) else \"NO\")",
    "tags": [
      "constructive algorithms",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1922",
    "index": "B",
    "title": "Forming Triangles",
    "statement": "You have $n$ sticks, numbered from $1$ to $n$. The length of the $i$-th stick is $2^{a_i}$.\n\nYou want to choose \\textbf{exactly} $3$ sticks out of the given $n$ sticks, and form a \\textbf{non-degenerate} triangle out of them, using the sticks as the sides of the triangle. A triangle is called non-degenerate if its area is \\textbf{strictly} greater than $0$.\n\nYou have to calculate the number of ways to choose exactly $3$ sticks so that a triangle can be formed out of them. Note that the order of choosing sticks does not matter (for example, choosing the $1$-st, $2$-nd and $4$-th stick is the same as choosing the $2$-nd, $4$-th and $1$-st stick).",
    "tutorial": "At first, let's figure out which sticks can be used to make a triangle. Let's denote the length of the longest stick as $2^{s_0}$, the shortest stick as $2^{s_2}$ and the middle stick as $2^{s_1}$ (in other words, $s$ is an array of length $3$, consisting of three sticks for a triangle, sorted in non-ascending order). Important fact: $s_0 == s_1$. It's true because if $s_0 > s_1$, then $2^{s_0} \\ge 2^{s_1} + 2^{s_2}$ and the triangle is degenerate. At the same time, the value of the $s_2$ can be any integer from $0$ to $s_0$. So all we have to do is calculate the number of triples of sticks such that there are two or three maximums in the triple. Let's create an array $cnt$, where $cnt_i$ is the number of sticks of length $2^i$, and the array $sumCnt$, where $sumCnt_i$ is the number of sticks no longer than $2^i$. Now let's iterate over the length of the longest stick in the triangle (denote it as $m$). Then there are two cases: All three sticks in a triangle are equal. Then the number of such triangles can be computed with a binomial coefficient: $\\frac{cnt_m * (cnt_m - 1) * (cnt_m - 2)}{6}$; Only two sticks are equal (and have the same length). Then the number of such triangles is $\\frac{cnt_m * (cnt_m - 1)}{2} \\cdot sumCnt_{m - 1}$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint t;\n \nint main() {\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        int n;\n        cin >> n;\n        map<int, int> numOfLens;\n        for (int i = 0; i < n; ++i){\n            int x;\n            cin >> x;\n            ++numOfLens[x];\n        }\n        \n        long long res = 0;\n        int sum = 0;\n        for (auto it : numOfLens) {\n            long long cnt = it.second;\n            if(cnt >= 3)\n                res += cnt * (cnt - 1) * (cnt - 2) / 6;\n            if(cnt >= 2)\n                res += cnt * (cnt - 1) / 2 * sum;\n            sum += cnt;\n        }\n        \n        cout << res << endl;\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1922",
    "index": "C",
    "title": "Closest Cities",
    "statement": "There are $n$ cities located on the number line, the $i$-th city is in the point $a_i$. The coordinates of the cities are given in ascending order, so $a_1 < a_2 < \\dots < a_n$.\n\nThe distance between two cities $x$ and $y$ is equal to $|a_x - a_y|$.\n\nFor each city $i$, let's define the \\textbf{closest} city $j$ as the city such that the distance between $i$ and $j$ is not greater than the distance between $i$ and each other city $k$. For example, if the cities are located in points $[0, 8, 12, 15, 20]$, then:\n\n- the closest city to the city $1$ is the city $2$;\n- the closest city to the city $2$ is the city $3$;\n- the closest city to the city $3$ is the city $4$;\n- the closest city to the city $4$ is the city $3$;\n- the closest city to the city $5$ is the city $4$.\n\nThe cities are located in such a way that for every city, the closest city is unique. For example, it is impossible for the cities to be situated in points $[1, 2, 3]$, since this would mean that the city $2$ has two closest cities ($1$ and $3$, both having distance $1$).\n\nYou can travel between cities. Suppose you are currently in the city $x$. Then you can perform one of the following actions:\n\n- travel to any other city $y$, paying $|a_x - a_y|$ coins;\n- travel to the city which is the closest to $x$, paying $1$ coin.\n\nYou are given $m$ queries. In each query, you will be given two cities, and you have to calculate the minimum number of coins you have to spend to travel from one city to the other city.",
    "tutorial": "Important observation: the answer will not change if you are allowed to move only to adjacent cities. It is true because if you move to a non-adjacent city, you can split the path to that city into parts without increasing its cost. So, the shortest way from $x$ to $y$ (consider the case $x < y$) is to move from city $x$ to city $x+1$ for $1$ coin if it's possible or for $a_{x+1} - a_x$ if it's not. Then move from city $x+1$ to city $x+2$ for $1$ coin if it's possible, or for $a_{x+2} - a_{x+1}$ coins if it's not. And so on, until we reach the city $y$. Now let's calculate two arrays: $l$ and $r$. $r_i$ is equal to the minimum amount of coins to reach the city $i$ from city $1$ (from left to right), $l_i$ is equal to the minimum amount of coins to reach the city $i$ from city $n$ (from right to left). Both of these arrays can be precalculated just like the arrays of prefix sums are calculated. For example, $r_1 = 0$, $r_2 = dist(1, 2)$, $r_3 = r_2 + dist(2, 3)$, $r_4 = r_3 + dist(3, 4)$ and so on. Here, $dist(s, t)$ denotes the cheapest way to travel between two adjacent cities $s$ and $t$. Then, the cheapest way between two cities $x$ and $y$ can be calculated in the same way as the sum on subarray is calculated for the prefix sum array. There are two cases: If $x < y$ then the answer is $r_y - r_x$; If $x > y$ then the answer is $l_y - l_x$;",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 200'000;\nconst int INF = 1'000'000'009;\nint t;\n \nchar type(const vector <int>& a, int id) {\n    int distL = (id == 0? INF : a[id] - a[id - 1]);\n    int distR = (id + 1 == a.size()? INF : a[id + 1] - a[id]);\n    if(distL < distR) return 'L';\n    if(distL > distR) return 'R';\n    assert(false);\n}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        int n;\n        cin >> n;\n        vector <int> a(n);\n        for (int i = 0; i < n; ++i)\n            cin >> a[i];\n            \n        vector <int> l(n), r(n);\n        for (int i = 1; i < n; ++i)\n            r[i] = r[i - 1] + (type(a, i - 1) == 'R'? 1 : a[i] - a[i - 1]);\n        for (int i = n - 2; i >= 0; --i)\n            l[i] = l[i + 1] + (type(a, i + 1) == 'L'? 1 : a[i + 1] - a[i]);\n        \n        int m;\n        cin >> m;\n        for (int i = 0; i < m; ++i) {\n            int x, y;\n            cin >> x >> y;\n            --x, --y;\n            if (x < y) \n                cout << r[y] - r[x] << endl;\n            else\n                cout << l[y] - l[x] << endl;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1922",
    "index": "D",
    "title": "Berserk Monsters",
    "statement": "Monocarp is playing a computer game (yet again). Guess what is he doing? That's right, killing monsters.\n\nThere are $n$ monsters in a row, numbered from $1$ to $n$. The $i$-th monster has two parameters: attack value equal to $a_i$ and defense value equal to $d_i$. In order to kill these monsters, Monocarp put a berserk spell on them, so they're attacking each other instead of Monocarp's character.\n\nThe fight consists of $n$ rounds. Every round, the following happens:\n\n- first, every alive monster $i$ deals $a_i$ damage to the \\textbf{closest} alive monster to the left (if it exists) and the \\textbf{closest} alive monster to the right (if it exists);\n- then, every alive monster $j$ which received more than $d_j$ damage \\textbf{during this round} dies. I. e. the $j$-th monster dies if and only if its defense value $d_j$ is \\textbf{strictly less} than the total damage it received \\textbf{this round}.\n\nFor each round, calculate the number of monsters that will die during that round.",
    "tutorial": "It is important to note that if during the $j$-th round the $i$-th monster did not die and none of its alive neighbors died, then there is no point in checking this monster in the $(j+1)$-th round. Therefore, we can solve the problem as follows: let's maintain a list of candidates (those who can die) for the current round; if the monster dies in the current round, then add its neighbors to the list of candidates for the next round. Since killing a monster adds no more than $2$ candidates, the total size of the candidate lists for all rounds does not exceed $3n$ (since the size of the list for the first round is equal to $n$ plus no more than $2$ for each killed monster). Therefore, we can simply iterate through these lists to check if the monster will be killed. The only problem left is finding the alive neighbors of the monster (to check whether he is killed or not during the round). This can be done by creating an ordered set with the indices of the monsters. set allows us to remove the killed ones and find neighboring monsters in $O(\\log{n})$. Thus, the solution works in $O(n\\log{n})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n + 2), d(n + 2, INT_MAX);\n    for (int i = 1; i <= n; ++i) cin >> a[i];\n    for (int i = 1; i <= n; ++i) cin >> d[i];\n    set<int> lft, cur;\n    for (int i = 0; i < n + 2; ++i) {\n      lft.insert(i);\n      cur.insert(i);\n    }\n    for (int z = 0; z < n; ++z) {\n      set<int> del, ncur;\n      for (int i : cur) {\n        auto it = lft.find(i);\n        if (it == lft.end()) continue;\n        int prv = *prev(it);\n        int nxt = *next(it);\n        if (a[prv] + a[nxt] > d[i]) {\n          del.insert(i);\n          ncur.insert(prv);\n          ncur.insert(nxt);\n        }\n      }\n      cout << del.size() << ' ';\n      for (auto it : del) lft.erase(it);\n      cur = ncur;\n    }\n    cout << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "data structures",
      "dsu",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1922",
    "index": "E",
    "title": "Increasing Subsequences",
    "statement": "Let's recall that an increasing subsequence of the array $a$ is a sequence that can be obtained from it by removing some elements without changing the order of the remaining elements, and the remaining elements are strictly increasing (i. e $a_{b_1} < a_{b_2} < \\dots < a_{b_k}$ and $b_1 < b_2 < \\dots < b_k$). Note that an empty subsequence is also increasing.\n\nYou are given a positive integer $X$. Your task is to find an array of integers of length \\textbf{at most $200$}, such that it has exactly $X$ increasing subsequences, or report that there is no such array. If there are several answers, you can print any of them.\n\nIf two subsequences consist of the same elements, but correspond to different positions in the array, they are considered different (for example, the array $[2, 2]$ has two different subsequences equal to $[2]$).",
    "tutorial": "Let's consider one of the solutions for constructing the required array. Let array $a$ have $x$ increasing subsequences. If we add a new minimum to the end of the array, the number of increasing subsequences in the new array equals $x+1$ (since the new element does not form increasing subsequences with other elements, only subsequences consisting of this element will be added). If we add a new maximum to the end of the array, the number of increasing subsequences in the new array equals $2x$ (since the new element forms increasing subsequences with any other elements). Using the above facts, let's define a recursive function $f(x)$, which returns an array with exactly $x$ increasing subsequences. For an odd value of $x$, $f(x) = f(x-1) + min$ (here + denotes adding an element to the end of the array); for an even value of $x$, $f(x) = f(\\frac{x}{2}) + max$. Now we need to estimate the number of elements in the array obtained by this algorithm. Note that there cannot be two consecutive operations of the first type ($x \\rightarrow x-1$), so every two operations, the value of $x$ decreases by at least two times. Thus, the size of the array satisfies the limit of $200$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvector<int> f(long long x) {\n  vector<int> res;\n  if (x == 2) {\n  \tres.push_back(0);\n  } else if (x & 1) {\n    res = f(x - 1);\n    res.push_back(*min_element(res.begin(), res.end()) - 1);\n  } else {\n    res = f(x / 2);\n    res.push_back(*max_element(res.begin(), res.end()) + 1);\n  }\n  return res;\n}\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    long long x;\n    cin >> x;\n    auto ans = f(x);\n    cout << ans.size() << '\\n';\n    for (int i : ans) cout << i << ' ';\n    cout << '\\n';\n  }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "divide and conquer",
      "greedy",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1922",
    "index": "F",
    "title": "Replace on Segment",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$, where each element is an integer from $1$ to $x$.\n\nYou can perform the following operation with it any number of times:\n\n- choose three integers $l$, $r$ and $k$ such that $1 \\le l \\le r \\le n$, $1 \\le k \\le x$ and \\textbf{each} element $a_i$ such that $l \\le i \\le r$ is different from $k$. Then, for each $i \\in [l, r]$, replace $a_i$ with $k$.\n\nIn other words, you choose a subsegment of the array and an integer from $1$ to $x$ which does not appear in that subsegment, and replace every element in the subsegment with that chosen integer.\n\nYour goal is to make all elements in the array equal. What is the minimum number of operations that you have to perform?",
    "tutorial": "First of all, we claim the following: if you apply an operation on a segment, you may treat the resulting segment as one element (i. e. we can \"merge\" the elements affected by an operation into one). This is quite intuitive, but the formal proof is kinda long, so if you're not interested in it, feel free to skip the next paragraphs written in italic. Formal proof: suppose we merged several adjacent equal elements into one. Let's show that it doesn't change the answer for the array. Let the array before merging a segment of adjacent equal elements be $a$, and the array after merging be $a'$. We will show that $f(a) = f(a')$, where $f(x)$ is the minimum number of operations to solve the problem on the array $x$. $f(a) \\ge f(a')$: suppose we built a sequence of operations that turns all elements of $a$ equal. Consider the segment of adjacent equal elements we merged to get $a'$. Let's discard all elements of that segment, except for the first one, from all operations in the sequence, and remove all operations which now affect zero elements. We will get a valid sequence of operations that turns all elements of $a'$ equal. So, any valid sequence of operations for $a$ can be transformed into a valid sequence of operations for $a'$ (with possibly discarding some operations), and that's why $f(a) \\ge f(a')$; $f(a) \\le f(a')$: suppose we built a sequence of operations that turns all elements of $a'$ equal. It can be transformed into a valid sequence of operations for $a'$, if we \"expand\" the element we got from merging the segment in all operations. So, $f(a) \\le f(a')$; since $f(a) \\ge f(a')$ and $f(a) \\le f(a')$, then $f(a) = f(a')$. This means that after you've done an operation on a segment, the next operations will either affect that whole segment, or not affect any element from the segment at all. This allows us to use the following dynamic programming idea: let $dp[l][r][k]$ be the minimum number of operations required to turn all elements on the segment $[l, r]$ into $k$. If we want to transform all elements into $k$, then there are two options: either the last operation will turn the whole segment into $k$, so we need to calculate the number of operations required to get rid of all elements equal to $k$ from the segment; or the segment $[l, r]$ can be split into several segments which we will turn into $k$ separately. The second option can be modeled quite easily: we iterate on the splitting point between two parts $i$, and update $dp[l][r][k]$ with $dp[l][i][k] + dp[i+1][r][k]$. However, the first option is a bit more complicated. Let's introduce a second dynamic programming to our solution: let $dp2[l][r][k]$ be the minimum number of operations to remove all occurrences of $k$ from the segment $[l, r]$. Then, the first option for computing $dp[l][r][k]$ can be implemented by simply updating $dp[l][r][k]$ with $dp2[l][r][k] + 1$. Now, let's show how to calculate $dp2[l][r][k]$. It's quite similar to the first dynamic programming: either the last operation on the segment will turn the whole segment into some other element $m$, so we can iterate on it and update $dp2[l][r][k]$ with $dp[l][r][m]$; or the segment $[l, r]$ can be split into two parts, and we will get rid of elements equal to $k$ from these parts separately (so we update $dp2[l][r][k]$ with $dp2[l][i][k] + dp2[i+1][r][k]$). Okay, it looks like we got a solution working in $O(n^4)$. There's just one problem, though. There are cyclic dependencies in our dynamic programming: $dp[l][r][k]$ depends on $dp2[l][r][k]$; $dp2[l][r][k]$ depends on $dp[l][r][m]$, where $m \\ne k$; $dp[l][r][m]$ depends on $dp2[l][r][m]$; $dp2[l][r][m]$ depends on $dp[l][r][k]$. We have to either somehow deal with them, or get rid of them. The model solution eliminates these cyclic dependencies as follows: when we need to calculate $dp[l][r][k]$, let's discard all elements equal to $k$ from the ends of the segment (i. e. move $l$ to $l'$ and $r$ to $r'$, where $l'$ and $r'$ are the first and last occurrences of elements not equal to $k$). Similarly, when we need to calculate $dp2[l][r][k]$, let's discard all elements not equal to $k$ from the ends of the segment. It's quite easy to show that these operations won't make the answer worse (if you remove an element from an array, the minimum number of operations to \"fix\" the array doesn't increase). It's also not that hard to show that this method gets rid of all cyclic dependencies: if we consider the cyclic dependency we described earlier, we can see that the element $a_l$ will be discarded from the segment either when computing $dp[l][r][k]$ (if $a_l = k$) or when computing $dp2[l][r][k]$ (if $a_l \\ne k$). That way, we get a dynamic programming solution working in $O(n^4)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 111;\n \nint n, k;\nint a[N];\nint nxtx[N][N], prvx[N][N];\nint nxtnx[N][N], prvnx[N][N];\nint dp1[N][N][N], dp2[N][N][N];\n \nint calc2(int, int, int);\n \nint calc1(int l, int r, int x) {\n  l = nxtnx[l][x], r = prvnx[r][x];\n  if (l > r) return 0;\n  if (dp1[l][r][x] != -1) return dp1[l][r][x];\n  dp1[l][r][x] = calc2(l, r, x) + 1;\n  for (int i = l; i < r; ++i) dp1[l][r][x] = min(dp1[l][r][x], calc1(l, i, x) + calc1(i + 1, r, x));\n  return dp1[l][r][x];\n}\n \nint calc2(int l, int r, int x) {\n  l = nxtx[l][x], r = prvx[r][x];\n  if (l > r) return 0;\n  if (dp2[l][r][x] != -1) return dp2[l][r][x];\n  dp2[l][r][x] = n;\n  for (int i = l; i < r; ++i) dp2[l][r][x] = min(dp2[l][r][x], calc2(l, i, x) + calc2(i + 1, r, x));\n  for (int y = 0; y < k; ++y) if (x != y) dp2[l][r][x] = min(dp2[l][r][x], calc1(l, r, y)); \n  return dp2[l][r][x];\n}\n \nvoid solve() {\n  cin >> n >> k;\n  for (int i = 0; i < n; ++i) cin >> a[i], --a[i];\n  for (int x = 0; x < k; ++x) prvx[0][x] = prvnx[0][x] = -1;\n  for (int i = 0; i < n; ++i) {\n    prvx[i][a[i]] = i;\n    for (int x = 0; x < k; ++x) prvx[i + 1][x] = prvx[i][x];\n    for (int x = 0; x < k; ++x) if (x != a[i]) prvnx[i][x] = i;\n    for (int x = 0; x < k; ++x) prvnx[i + 1][x] = prvnx[i][x];\n  }\n  for (int x = 0; x < k; ++x) nxtx[n][x] = nxtnx[n][x] = n;\n  for (int i = n - 1; i >= 0; --i) {\n    for (int x = 0; x < k; ++x) nxtx[i][x] = nxtx[i + 1][x];\n    nxtx[i][a[i]] = i;\n    for (int x = 0; x < k; ++x) nxtnx[i][x] = nxtnx[i + 1][x];\n    for (int x = 0; x < k; ++x) if (x != a[i]) nxtnx[i][x] = i;\n  }\n  memset(dp1, -1, sizeof(dp1));\n  memset(dp2, -1, sizeof(dp2));\n  int ans = n;\n  for (int x = 0; x < k; ++x) ans = min(ans, calc1(0, n - 1, x));\n  cout << ans << '\\n';\n}\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) solve();\n}",
    "tags": [
      "dp",
      "graph matchings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1923",
    "index": "A",
    "title": "Moving Chips",
    "statement": "There is a ribbon divided into $n$ cells, numbered from $1$ to $n$ from left to right. Each cell either contains a chip or is free.\n\nYou can perform the following operation any number of times (possibly zero): choose a chip and move it to the \\textbf{closest free cell to the left}. You can choose any chip that you want, provided that there is at least one free cell to the left of it. When you move the chip, the cell where it was before the operation becomes free.\n\nYour goal is to move the chips in such a way that \\textbf{they form a single block, without any free cells between them}. What is the minimum number of operations you have to perform?",
    "tutorial": "Denote the position of the leftmost chip as $l$, the position of the rightmost chip as $r$, and the number of chips as $c$. Having all chips in one block without free spaces means that we need to reach the situation when $r - l = c - 1$. Since $r - l \\ge c - 1$ is always met (the situation when $r-l = c-1$ is when the chips are packed as close as possible), we need to decrease the value of $r-l$ as fast as possible. There are two approaches to do it. One is to try decreasing $r$ every time; i. e. let's code a greedy solution that always applies an operation to the current rightmost chip. This is actually one of the correct solutions to the problem. But if we prove it, we can design an easier solution. Whenever we apply an operation on any chip other than the rightmost chip, the value of $r-l$ does not decrease (we either don't change $l$ and $r$ at all, or decrease $l$). But whenever we apply an operation on the rightmost chip, $r$ decreases by exactly $1$ (the new rightmost chip will be in position $r-1$ - either it is present there before the operation, or it will be moved there from $r$). So, only applying the operations to the rightmost chip decreases $r-l$, and it always decreases $r-l$ by exactly $1$ no matter what. So, the answer to the problem is actually $(r-l) - (c-1)$.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n    l, r = a.index(1), n - a[::-1].index(1) - 1\n    c = a.count(1)\n    print(r - l - c + 1)",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1923",
    "index": "B",
    "title": "Monsters Attack!",
    "statement": "You are playing a computer game. The current level of this game can be modeled as a straight line. Your character is in point $0$ of this line. There are $n$ monsters trying to kill your character; the $i$-th monster has health equal to $a_i$ and is initially in the point $x_i$.\n\nEvery second, the following happens:\n\n- first, you fire up to $k$ bullets at monsters. Each bullet targets exactly one monster and decreases its health by $1$. For each bullet, you choose its target arbitrary (for example, you can fire all bullets at one monster, fire all bullets at different monsters, or choose any other combination). Any monster can be targeted by a bullet, regardless of its position and any other factors;\n- then, all alive monsters with health $0$ or less die;\n- then, all alive monsters move $1$ point closer to you (monsters to the left of you increase their coordinates by $1$, monsters to the right of you decrease their coordinates by $1$). If any monster reaches your character (moves to the point $0$), you lose.\n\nCan you survive and kill all $n$ monsters without letting any of them reach your character?",
    "tutorial": "Let's look at monsters at distance of $1$ (i. e. in positions $1$ and $-1$). We must kill them in the $1$-st second, so their total hp (let denote it as $s_1$) should not exceed $k$. If this condition is not met, the answer is NO. Otherwise, we can say that there are $k-s_1$ bullets left unused during the first second (let denote it as $lft$). Now let's look at the monsters at a distance of $2$. We must kill them no later than the $2$-nd second. We have $k$ bullets for the $2$-nd second plus $lft$ unused bullets from the $1$-st second, so total hp of monsters at distance $2$ should not exceed $k+lft$. We can see that the situation is similar to the $1$-st second, if the condition is not met, then the answer is NO, otherwise we move on to the next distance with the updated value of $lft$. If all $n$ seconds are considered and all conditions are met, then the answer is YES. Therefore, we got a solution that works in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n), x(n);\n    for (auto& it : a) cin >> it;\n    for (auto& it : x) cin >> it;\n    vector<long long> s(n + 1);\n    for (int i = 0; i < n; ++i) s[abs(x[i])] += a[i];\n    bool ok = true;\n    long long lft = 0;\n    for (int i = 1; i <= n; ++i) {\n      lft += k - s[i];\n      ok &= (lft >= 0);\n    }\n    cout << (ok ? \"YES\" : \"NO\") << '\\n';\n  }\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1923",
    "index": "C",
    "title": "Find B",
    "statement": "An array $a$ of length $m$ is considered good if there exists an integer array $b$ of length $m$ such that the following conditions hold:\n\n- $\\sum\\limits_{i=1}^{m} a_i = \\sum\\limits_{i=1}^{m} b_i$;\n- $a_i \\neq b_i$ for every index $i$ from $1$ to $m$;\n- $b_i > 0$ for every index $i$ from $1$ to $m$.\n\nYou are given an array $c$ of length $n$. Each element of this array is greater than $0$.\n\nYou have to answer $q$ queries. During the $i$-th query, you have to determine whether the subarray $c_{l_{i}}, c_{l_{i}+1}, \\dots, c_{r_{i}}$ is good.",
    "tutorial": "At first, let's precalculate the array of prefix sum and the number of elements equal to one on prefix (let's denote them as $sum[]$ and $cnt1[]$). More formally, $sum_i = \\sum_{k=1}^{i} c_i$ and $cnt1_i = \\sum_{k=1}^{i} (is\\_1(c_i))$, where the function $is\\_1(x)$ returns $1$ if $x$ equals $1$ and $0$ otherwise . For example, if $c = [5, 1, 1, 2, 1, 10]$, then $sum = [0, 5, 6, 7, 9, 10, 20]$ and $cnt_1 = [0, 0, 1, 2, 2, 3, 3]$. Now we can answer the query $l$, $r$. For this, let's calculate the sum on subarray $c_l, \\dots, c_r$ and the number of elements equal to $1$ on subarray $c_l, \\dots, c_r$ (let's denote it as $cur\\_sum$ and $cur\\_cnt1$). We can do it by precalculated arrays $sum$ and $cnt1$: $cur\\_sum = sum_r - sum _{l - 1}$; $cur\\_cnt1 = cnt1_r - cnt1 _{l - 1}$. To answer query $l$, $r$ at first let's try to find the array $b$ with the minimum value of $\\sum b_i$. For this, for indexes $i$, where $c_i = 1$ we have to set $b_i = 2$, and for indexes $i$, where $c_i > i$ we have to set $b_i = 1$. Thus, the sum of all elements in array $b$ equal to $cnt_1 \\cdot 2 + (r - l + 1) - cnt_1$ or $(r - l + 1) + cnt_1$. Now we have three cases: If this sum is greater than $\\sum_{i=l}^{r} c_i$ then the answer is $NO$; If this sum is equal to $\\sum_{i=l}^{r} c_i$ then the answer is $YES$; If this sum is greater than $\\sum_{i=l}^{r} c_i$ then we can add this excess to the maximal element in array $b$. In this case, the answer is $YES$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 300043;\n \nint t;\nint n, m;\nint a[N];\nlong long sum[N];\nint cnt1[N];\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    \n    cin >> t;\n    for (int tc = 0; tc < t; ++tc) {\n        cin >> n >> m;\n        memset(sum, 0, sizeof(sum[0]) * (n + 5));\n        memset(cnt1, 0, sizeof(cnt1[0]) * (n + 5));\n        for (int i = 0; i < n; ++i) {\n            cin >> a[i];\n            sum[i + 1] = sum[i] + a[i];\n            cnt1[i + 1] = cnt1[i] + (a[i] == 1);\n        }\n        \n        for (int i = 0; i < m; ++i) {\n            int l, r;\n            cin >> l >> r;\n            --l;\n            int cur_cnt1 = cnt1[r] - cnt1[l];\n            long long cur_sum = sum[r] - sum[l];\n            \n            if((r - l) + cur_cnt1 <= cur_sum && r - l > 1)\n                cout << \"YES\\n\";\n            else\n                cout << \"NO\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1923",
    "index": "D",
    "title": "Slimes",
    "statement": "There are $n$ slimes placed in a line. The slimes are numbered from $1$ to $n$ in order from left to right. The size of the $i$-th slime is $a_i$.\n\nEvery second, the following happens: \\textbf{exactly one} slime eats one of its neighbors and increases its size by the eaten neighbor's size. A slime can eat its neighbor only if it is strictly bigger than this neighbor. If there is no slime which is strictly bigger than one of its neighbors, the process ends.\n\nFor example, suppose $n = 5$, $a = [2, 2, 3, 1, 4]$. The process can go as follows:\n\n- first, the $3$-rd slime eats the $2$-nd slime. The size of the $3$-rd slime becomes $5$, the $2$-nd slime is eaten.\n- then, the $3$-rd slime eats the $1$-st slime (they are neighbors since the $2$-nd slime is already eaten). The size of the $3$-rd slime becomes $7$, the $1$-st slime is eaten.\n- then, the $5$-th slime eats the $4$-th slime. The size of the $5$-th slime becomes $5$, the $4$-th slime is eaten.\n- then, the $3$-rd slime eats the $5$-th slime (they are neighbors since the $4$-th slime is already eaten). The size of the $3$-rd slime becomes $12$, the $5$-th slime is eaten.\n\nFor each slime, calculate the minimum number of seconds it takes for this slime to be eaten by another slime (among all possible ways the process can go), or report that it is impossible.",
    "tutorial": "Let's solve the problem independently for each slime (denote it as $i$). After any number of seconds, the size of each slime is equal to the sum of some subarray. In order to eat the $i$-th slime, the \"eater\" should be its neighbor. So the eater size is equal to the sum of subarray $[j, i-1]$ for some $j < i$ or $[i + 1, j$] for some $j > i$. It remains to understand which $j$ can be the answer. First of all, the sum of subarray should be strictly greater than $a_i$. And also, there should be a sequence of operations that can combine the selected segment of slimes into one slime. Such a sequence exists in two cases: the length of subarray is $1$; there are at least two distinct values in subarray. It is not difficult to prove that these are the only conditions. If the length is $1$, then the subarray is already just only one slime. If all the slimes have the same size, then none of the neighboring pairs can be combined, which means that it is impossible to combine all slimes into one. If there are at least two distinct values, there exist a pair of adjacent slimes of the form (maximum, not maximum). After combining such a pair, the result is the only maximum of the subarray, which means that it can eat all the other slimes in the subarray. It remains to understand how to find such $j$ that satisfies the aforementioned conditions and is as close to $i$ as possible (because the number of required operations is $|i-j|$) faster than iterating over all values of $j$. We can notice that, if the subarray $[j, i-1]$ is good, then the subarray $[j-1, i-1]$ is also good. This leads us to the fact that we can use binary search. It is enough to pre-calculate two arrays: an array of prefix sums that used to find the sum of the subarray and an array $p$, where $p_i$ is the position of the nearest element that different to $a_i$ - to determine whether there are two different elements. So we can find the answer for one slime in $O(\\log{n})$. And the total running time is $O(n\\log{n})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (auto& x : a) cin >> x;\n    vector<int> ans(n, n);\n    for (int z = 0; z < 2; ++z) {\n      vector<long long> s(n + 1);\n      for (int i = 0; i < n; ++i) s[i + 1] = s[i] + a[i];\n      vector<int> p(n, -1);\n      for (int i = 1; i < n; ++i) {\n        int j = (z ? n - i - 1 : i);\n        int l = 1, r = i;\n        while (l <= r) {\n          int m = (l + r) / 2;\n          if (s[i] - s[i - m] > a[i] && p[i - 1] >= i - m) {\n            ans[j] = min(ans[j], m);\n            r = m - 1;\n          } else {\n            l = m + 1;\n          }\n        }\n        if (a[i - 1] > a[i]) ans[j] = 1;\n        p[i] = (a[i] == a[i - 1] ? p[i - 1] : i - 1);\n      }\n      reverse(a.begin(), a.end());\n    }\n    for (int i = 0; i < n; ++i)\n      cout << (ans[i] == n ? -1 : ans[i]) << ' ';\n    cout << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1923",
    "index": "E",
    "title": "Count Paths",
    "statement": "You are given a tree, consisting of $n$ vertices, numbered from $1$ to $n$. Every vertex is colored in some color, denoted by an integer from $1$ to $n$.\n\nA simple path of the tree is called beautiful if:\n\n- it consists of at least $2$ vertices;\n- the first and the last vertices of the path have the same color;\n- no other vertex on the path has the same color as the first vertex.\n\nCount the number of the beautiful simple paths of the tree. Note that paths are considered undirected (i. e. the path from $x$ to $y$ is the same as the path from $y$ to $x$).",
    "tutorial": "Let's consider what the paths passing through some vertex $v$ look like. First, root the tree arbitrarily. Let $u_1, u_2, \\dots, u_k$ be the children of $v$. Then, for some color $x$, there are $\\mathit{cnt}[u_1][x], \\mathit{cnt}[u_2][x], \\dots, \\mathit{cnt}[u_k][x]$ top-level vertices in their subtrees. Top-level here means that there are no vertices of color $x$ on the path from them to $u_i$. If the color of $v$ is not $x$, then you can combine all $\\mathit{cnt}$ top-level vertices from every pair of children into paths. If the color $v$ is $x$, then all $\\mathit{cnt}$ top-level vertices can only be paired with $v$. Moreover, the top-level vertices of color $x$ in subtree of $v$ is only $v$ itself now. With these ideas, some small-to-large can be implemented. Store $\\mathit{cnt}[v][x]$ for all colors $x$ such that there exist top-level vertices of this color. In order to recalculate $\\mathit{cnt}[v]$ from the values of its children, you can first calculate the sum of $\\mathit{cnt}$ for each $x$, then replace $\\mathit{cnt}[v][c_v]$ with $1$ (regardless of if it appeared in children or not). So that can be done by adding all values to the values of the largest child of $v$ (largest by its size of $\\mathit{cnt}$, for example). During this process, you can calculate the number of paths as well. The complexity will be $O(n \\log^2 n)$ for each testcase, and that should pass freely. There's also an idea for a faster solution. Two words: virtual trees. Basically, you can build a virtual tree of all vertices of each color. Now, there are vertices colored $x$ in it and some auxiliary vertices. The answer for that color can be calculated with some sort of dynamic programming. Similar to the first solution, for each vertex, store the number of top-level vertices of color $x$ in its subtree. All the calculations are exactly the same. You can build all virtual trees in $O(n \\log n)$ in total.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nint n;\nvector<int> a;\nvector<vector<int>> g;\n \nlong long ans;\nvector<map<int, int>> cnt;\n \nvoid dfs(int v, int p = -1){\n    int bst = -1;\n    for (int u : g[v]) if (u != p){\n        dfs(u, v);\n        if (bst == -1 || cnt[bst].size() < cnt[u].size())\n            bst = u;\n    }\n    for (int u : g[v]) if (u != p && u != bst){\n        for (auto it : cnt[u]){\n            int x = it.first, y = it.second;\n            if (x != a[v]) ans += cnt[bst][x] * 1ll * y;\n            cnt[bst][x] += y;\n        }\n    }\n    if (bst != -1) swap(cnt[bst], cnt[v]);\n    ans += cnt[v][a[v]];\n    cnt[v][a[v]] = 1;\n}\n \nint main() {\n    cin.tie(0);\n    ios::sync_with_stdio(false);\n    int t;\n    cin >> t;\n    while (t--){\n        int n;\n        cin >> n;\n        a.resize(n);\n        forn(i, n) cin >> a[i];\n        g.assign(n, {});\n        forn(_, n - 1){\n            int v, u;\n            cin >> v >> u;\n            --v, --u;\n            g[v].push_back(u);\n            g[u].push_back(v);\n        }\n        ans = 0;\n        cnt.assign(n, {});\n        dfs(0);\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1923",
    "index": "F",
    "title": "Shrink-Reverse",
    "statement": "You are given a binary string $s$ of length $n$ (a string consisting of $n$ characters, and each character is either 0 or 1).\n\nLet's look at $s$ as at a binary representation of some integer, and name that integer as the value of string $s$. For example, the value of 000 is $0$, the value of 01101 is $13$, \"100000\" is $32$ and so on.\n\nYou can perform at most $k$ operations on $s$. Each operation should have one of the two following types:\n\n- SWAP: choose two indices $i < j$ in $s$ and swap $s_i$ with $s_j$;\n- SHRINK-REVERSE: delete all leading zeroes from $s$ and reverse $s$.\n\nFor example, after you perform SHRINK-REVERSE on 000101100, you'll get 001101.What is the minimum value of $s$ you can achieve by performing at most $k$ operations on $s$?",
    "tutorial": "In order to solve a task, let's observe and prove several facts: Fact 0: Suppose, you have two strings $s_1$ and $s_2$ without leading zeroes. Value of $s_1$ is lower than value of $s_2$ if either $|s_1| < |s_2|$ or $|s_1| = |s_2|$ and $s_1 < s_2$ lexicographically. Fact 1: There is a strategy, where you, firstly, perform all swaps, and only after that perform reverses. Proof: let's take some optimal strategy and split all its operations in blocks by reverse operation. Let's look at the last block of swaps: if there is no reverse before it - we found strategy. Otherwise, we can \"push\" all swaps from this block into the previous block (of course, with fixed indices), since all positions that exist at the current moment, existed earlier. Answer won't increase after this \"push\". So we can transform any optimal strategy into one we need. Fact 2: There is no need to make more than $2$ reverses. Since, we, firstly, swap and then reverse - making $3$ reverses is equivalent to making $1$ reverse. Analogically, making $4$ reverses is equivalent to making $2$ reverses. Fact 3: There is no need to make more than $1$ reverse. If, after the first reverse, we grouped all $1$-s into one segment, then the second reverse won't change anything. Otherwise, instead of the second reverse, we could make one more swap and \"group $1$-s tighter\" thus lowering the value of $s$. Fact 4: Suppose, you have two binary strings $s_1$ and $s_2$ with equal length, equal number of $1$-s, and you'll replace last $k - 1$ zeroes in both of them thus getting strings $s'_1$ and $s'_2$. If $s_1 \\le s_2$ then $s'_1 \\le s'_2$ (lexicographically). Proof: if $s_1 = s_2$ then $s'_1 = s'_2$. Otherwise, there is the first position $p$ where $s_1[p] = 0$ and $s_2[p] = 1$. After replacing last $k - 1$ zeroes with ones, if $s_1[p]$ was replaced, then $s'_1 = s'_2$. Otherwise, $s'_1 < s'_2$ since $s'_1[p] = 0$ and $s'_2[p] = 1$. Using facts above, we can finally solve the problem. Let's check $2$ cases: $0$ reverses or $1$ reverse. $0$ reverses: it's optimal to be greedy. Let's take the leftmost $1$ and swap it with the rightmost $0$ as many times as we can. $1$ reverse: leading zeroes will be deleted; trailing zeroes will become leading, so they won't affect the value of the resulting string. That's why the answer will depend only on positions of leftmost and rightmost $1$-s. For convenience, let's reverse $s$. Then, let's iterate over all possible positions $i$ of now leftmost one. For each left position, let's find the minimum possible position $u$ of the rightmost one. Minimizing $u$ will minimize the value of the answer, so it's optimal. There are two conditions that should be satisfied: the interval $[i, u)$ should be long enough to contain all $1$-s from the whole string $s$; the number of $1$-s outside the interval should be at most $k - 1$. Last step is to choose the minimum interval among all of them. Due to fact 0, we should, firstly, choose the shortest interval. Then (due to fact 4) it's enough to choose the lexicographically smallest one among them. In order to compare two intervals of reversed string $s$ it's enough to use their \"class\" values from Suffix Array built on reversed $s$. The complexity is $O(n \\log{n})$ or $O(n \\log^2{n})$ for building Suffix Array + $O(n)$ for checking each case and comparing answers from both cases.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n#define all(a) (a).begin(), (a).end()\n \ntypedef long long li;\ntypedef pair<int, int> pt;\n \nconst int INF = int(1e9);\nconst int MOD = int(1e9) + 7;\n \nint add(int a, int b) {\n    a += b;\n    if (a >= MOD)\n        a -= MOD;\n    return a;\n}\nint mul(int a, int b) {\n    return int(a * 1ll * b % MOD);\n}\n \nnamespace SuffixArray {\n    string s;\n    vector< array<int, 2> > classes;\n    \n    vector<int> build(const string &bs) {\n        s = bs;\n        s += '$';\n        \n        vector<int> c(all(s)), ord(sz(s));\n        iota(all(ord), 0);\n        classes.resize(sz(s));\n \n        for (int len = 1; len < 2 * sz(s); len <<= 1) {\n            int half = len >> 1;\n            fore (i, 0, sz(s))\n                classes[i] = {c[i], c[(i + half) % sz(s)]};\n            \n            sort(all(ord), [&](int i, int j) {\n                return classes[i] < classes[j];\n            });\n            c[ord[0]] = 0;\n            fore (i, 1, sz(ord))\n                c[ord[i]] = c[ord[i - 1]] + (classes[ord[i - 1]] != classes[ord[i]]);\n        }\n        \n        c.pop_back();\n        for (int &cc : c)\n            cc--;\n        return c;\n    }\n};\n \nint n, k;\nstring s;\n \ninline bool read() {\n    if(!(cin >> n >> k))\n        return false;\n    cin >> s;\n    return true;\n}\n \nstring calcZero(string s) {\n    int rem = k;\n    int pos = 0;\n    for (int i = sz(s) - 1; rem > 0 && i >= 0; i--) {\n        if (s[i] == '1')\n            continue;\n        \n        while (pos < sz(s) && s[pos] == '0')\n            pos++;\n        if (pos >= i)\n            break;\n        \n        swap(s[pos], s[i]);\n        rem--;\n    }\n    return s.substr(s.find('1'));\n}\n \nstring calcOne(string s) {\n    reverse(all(s));\n    \n    auto c = SuffixArray::build(s);\n    int cntOnes = count(all(s), '1');\n    \n    array<int, 3> mn = { 2 * sz(s), INF, -1 };\n        \n    int u = 0, curOnes = 0;\n    fore (i, 0, n) {\n        while (u < sz(s) && (u - i < cntOnes || cntOnes - curOnes > k - 1)) {\n            curOnes += s[u] == '1';\n            u++;\n        }\n        if (u - i < cntOnes || cntOnes - curOnes > k - 1)\n            break;\n        \n        array<int, 3> curAns = { u - i, c[i], i };\n        mn = min(mn, curAns);\n        \n        curOnes -= s[i] == '1';\n    }\n    assert(mn[2] >= 0);\n    \n    string res = s.substr(mn[2], mn[0]);\n    int toAdd = cntOnes - count(all(res), '1');\n    for (int i = sz(res) - 1; toAdd > 0 && i >= 0; i--) {\n        if (res[i] == '0') {\n            res[i] = '1';\n            toAdd--;\n        }\n    }\n    return res;\n}\n \ninline void solve() {\n    auto s1 = calcZero(s);\n    auto s2 = calcOne(s);\n \n    if (sz(s1) > sz(s2) || (sz(s1) == sz(s2) && s1 > s2))\n        swap(s1, s2);\n    \n    int res = 0;\n    for (char c : s1)\n        res = add(mul(res, 2), c - '0');\n    cout << res << endl;\n}\n \nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "hashing",
      "implementation",
      "string suffix structures",
      "strings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1924",
    "index": "A",
    "title": "Did We Get Everything Covered?",
    "statement": "You are given two integers $n$ and $k$ along with a string $s$.\n\nYour task is to check whether all possible strings of length $n$ that can be formed using the first $k$ lowercase English alphabets occur as a subsequence of $s$. If the answer is NO, you also need to print a string of length $n$ that can be formed using the first $k$ lowercase English alphabets which does not occur as a subsequence of $s$.\n\nIf there are multiple answers, you may print any of them.\n\n\\textbf{Note:} A string $a$ is called a subsequence of another string $b$ if $a$ can be obtained by deleting some (possibly zero) characters from $b$ without changing the order of the remaining characters.",
    "tutorial": "Try to build the counter-case greedily. While building the counter-case, it is always optimal to choose the first character as the one whose first index of occurrence in the given string is the highest. We will try to construct a counter-case. If we can't the answer is YES otherwise NO. We will greedily construct the counter-case. It is always optimal to choose the first character of our counter-case as the character (among the first $k$ English alphabets) whose first index of occurrence in $s$ is the highest. Add this character to our counter-case, remove the prefix up to this character from $s$ and repeat until the length of the counter-case reaches $n$ or we reach the end of $s$. If the length of the counter-case is less than $n$, find a character which does not appear in the last remaining suffix of $s$. Keep adding this character to the counter-case until its length becomes $n$. This is a valid string which does not occur as a subsequence of $s$. Otherwise, all possible strings of length $n$ formed using the first $k$ English alphabets occur as a subsequence of $s$. This problem is essentially \"Implement the checker for Div. 2A\". It was not among the problems that were initially proposed for the round. While preparing problem 2A, I realized that writing the checker in itself might be a more interesting problem compared to 2A.",
    "code": "#include <bits/stdc++.h>                   \nusing namespace std;\n\nint main()\n{\n    std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);\n    int t;\n    cin>>t;\n    while(t--)\n    {\n        int n, k, m;\n        cin>>n>>k>>m;\n        string s;\n        cin>>s;\n        string res=\"\";\n        bool found[k];\n        memset(found, false, sizeof(found));\n        int count=0;\n        for(char c:s)\n        {\n            if(res.size()==n)\n                break;\n            count+=(!found[c-'a']);\n            found[c-'a']=true;\n            if(count==k)\n            {\n                memset(found, false, sizeof(found));\n                count=0;\n                res+=c;\n            }\n        }\n        if(res.size()==n)\n            cout<<\"YES\\n\";\n        else\n        {\n            cout<<\"NO\\n\";\n            for(int i=0;i<k;i++)\n            {\n                if(!found[i])\n                {\n                    while(res.size()<n)\n                        res+=(char)('a'+i);\n                }\n            }\n            cout<<res<<\"\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "shortest paths",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1924",
    "index": "B",
    "title": "Space Harbour",
    "statement": "There are $n$ points numbered $1$ to $n$ on a straight line. Initially, there are $m$ harbours. The $i$-th harbour is at point $X_i$ and has a value $V_i$. \\textbf{It is guaranteed that there are harbours at the points $1$ and $n$.} There is exactly one ship on each of the $n$ points. The cost of moving a ship from its current location to the next harbour is the product of the value of the nearest harbour to its left and the distance from the nearest harbour to its right. Specifically, if a ship is already at a harbour, the cost of moving it to the next harbour is $0$.\n\nAdditionally, there are $q$ queries, each of which is either of the following $2$ types:\n\n- $1$ $x$ $v$ — Add a harbour at point $x$ with value $v$. It is guaranteed that before adding the harbour, there is no harbour at point $x$.\n- $2$ $l$ $r$ — Print the sum of the cost of moving all ships at points from $l$ to $r$ to their next harbours. \\textbf{Note that you just need to calculate the cost of moving the ships but not actually move them.}",
    "tutorial": "Segment Tree with Lazy Propogation We can maintain a segment tree of size $n$ which initially stores the cost of all the ships. Now there are 2 types of updates when we add an harbour: The ships to the left of the new harbour have their cost decreased by a fixed amount. The ships to the right of the harbour have their cost changed by the value equivalent to product of distance from the harbour on their right (which remains unchanged) and the difference in values of the previous and new harbour to their left. Let $n=8$ and there be harbours on point $1$ and $8$ with values $10$ and $15$ respectively. Now we add a harbour at point $x=4$ with value $5$. Case 1: $(x=2, 3)$ Cost for both ships get decreased by $10 \\times (8-4)$ Case 2: $(x=5,6,7)$ Cost for the ships get increased by $(5-10) \\times 3, (5-10) \\times 2, (5-10) \\times 1$ respectively. There are multiple ways to handle both the updates simultaneously, a simple way would be to use a struct simulating an arithmetic progression. It can contain two values Base: Simply a value which has to be added to all values belonging to the segment. Difference: For each node of the segment, $dif \\times dist$ will be added to the node, where $dist$ is the distance of node from the end of the segment. Using summation of arithmetic progression we can make sure that the updates on Difference can be applied to an entire segment lazily. You can see the code for more details.",
    "code": "#include <bits/stdc++.h>                 \n#define int long long    \n#define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);\nusing namespace std;\nconst long long N=300005;\n\nstruct ap {\n    int base, dif;\n};\n\nap add(ap a, ap b)\n{\n    ap res;\n    res.base = a.base + b.base;\n    res.dif = a.dif + b.dif;\n    return res;\n}\n\nint convert(ap a, int n)\n{\n    int res = (n*a.base);\n    res += ((n*(n-1))/2ll)*a.dif;\n    return res;\n}\n\nint st[4*N], cost[N];\nap lazy[4*N];\nap zero = {0, 0};\n\nvoid propogate(int node, int l, int r)\n{\n    st[node] += convert(lazy[node], r-l+1);\n    if(l!=r)\n    {\n        lazy[node*2+1] = add(lazy[node*2+1], lazy[node]);\n        int mid = (l+r)/2;\n        int rig = (r-mid);\n        lazy[node].base += (rig*lazy[node].dif);\n        lazy[node*2] = add(lazy[node*2], lazy[node]);\n    }\n    lazy[node] = zero;\n}\nvoid build(int node, int l, int r)\n{\n    if(l==r)\n    {\n        st[node] = cost[l];\n        lazy[node] = zero;\n        return;\n    }\n    int mid=(l+r)/2;\n    build(node*2, l, mid);\n    build(node*2+1, mid+1, r);\n    st[node] = (st[node*2] + st[node*2+1]);\n    lazy[node] = zero; \n    return;\n}\nvoid update(int node, int l, int r, int x, int y, ap val)\n{\n    if(lazy[node].base != 0 || lazy[node].dif != 0)\n    propogate(node, l, r);\n    if(y<x||x>r||y<l)\n    return;\n    if(l>=x&&r<=y)\n    {\n        st[node] += convert(val, r-l+1);\n        if(l!=r)\n        {\n            lazy[node*2+1] = add(lazy[node*2+1], val);\n            int mid = (l+r)/2;\n            int rig = (r-mid);\n            val.base += (rig*val.dif);\n            lazy[node*2] = add(lazy[node*2], val);\n        }\n        return;\n    }\n    int mid=(l+r)/2;\n    update(node*2+1, mid+1, r, x, y, val);\n    if(y>mid)\n    {\n        int rig = (min(y, r)-mid);\n        val.base += (rig*val.dif);\n    }\n    update(node*2, l, mid, x, y, val);\n    st[node] = st[node*2] + st[node*2+1];\n    return;\n}\nint query(int node, int l, int r, int x, int y)\n{\n    if(lazy[node].base != 0 || lazy[node].dif != 0)\n    propogate(node, l, r);\n    if(y<x||y<l||x>r)\n    return 0;\n    if(l>=x&&r<=y)\n    return st[node];\n    int mid=(l+r)/2;\n    return query(node*2, l, mid, x, y) + query(node*2+1, mid+1, r, x, y);\n}\n\nint32_t main()\n{\n    IOS;\n    int n, m, q;\n    cin>>n>>m>>q;\n    set <int> harbours;\n    int X[m], V[n+1];\n    for(int i=0;i<m;i++)\n    {\n        cin>>X[i];\n        harbours.insert(X[i]);\n    }\n    for(int i=0;i<m;i++)\n    {\n        int v;\n        cin>>v;\n        cost[X[i]] = v;\n        V[X[i]] = v;\n    }\n    for(int i=1;i<=n;i++)\n    {\n        if(cost[i] == 0)\n        cost[i] = cost[i-1];\n    }\n    int dist=0;\n    for(int i=n;i>0;i--)\n    {\n        if(harbours.find(i) != harbours.end())\n        dist=0;\n        else\n        dist++;\n        cost[i] *= dist;\n    }\n    build(1, 1, n);\n    while(q--)\n    {\n        int typ;\n        cin>>typ;\n        if(typ == 1)\n        {\n            int x, v;\n            cin>>x>>v;\n            V[x] = v;\n            auto it = harbours.lower_bound(x);\n            int nxt = (*it);\n            it--;\n            int prev = (*it);\n            ap lef = {(V[prev]*(x-nxt)), 0};\n            ap rig = {0, V[x]-V[prev]};\n            update(1, 1, n, prev+1, x, lef);\n            update(1, 1, n, x+1, nxt, rig);\n            harbours.insert(x);\n        }\n        else\n        {\n            int l, r;\n            cin>>l>>r;\n            cout<<query(1, 1, n, l, r)<<'\\n';\n        }\n    }\n}",
    "tags": [
      "data structures",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1924",
    "index": "C",
    "title": "Fractal Origami",
    "statement": "You have a square piece of paper with a side length equal to $1$ unit. In one operation, you fold each corner of the square to the center of the paper, thus forming another square with a side length equal to $\\dfrac{1}{\\sqrt{2}}$ units. By taking this square as a new square, you do the operation again and repeat this process a total of $N$ times.\n\n\\begin{center}\n{\\small Performing operations for $N = 2$.}\n\\end{center}\n\nAfter performing the set of operations, you open the paper with the same side up you started with and see some crease lines on it. Every crease line is one of two types: a mountain or a valley. A mountain is when the paper folds outward, and a valley is when the paper folds inward.\n\nYou calculate the sum of the length of all mountain crease lines on the paper and call it $M$. Similarly, you calculate for valley crease lines and call it $V$. You want to find the value of $\\dfrac{M}{V}$.\n\nIt can be proved that this value can be represented in the form of $A + B\\sqrt{2}$, where $A$ and $B$ are rational numbers. Let this $B$ be represented as an irreducible fraction $\\dfrac{p}{q}$, your task is to print $p*inv(q)$ modulo $999\\,999\\,893$ \\textbf{(note the unusual modulo)}, where $inv(q)$ is the modular inverse of $q$.",
    "tutorial": "You need more math and less paper :) The length of mountain crease lines and valley crease lines created in each operation is the same, except for the first operation. Let there be an upside of the paper and a downside of the paper, initially the upside of the paper is facing up. With a little imagination, we can see that the mountain crease lines on the upside of the paper will be valley crease lines on the downside of the paper, and vice versa. Grey is the upside and orange is the downside After the first operation, what once was a single layer of square paper turns into a square with two overlapping layers of paper. The layer at the bottom has its upside facing up, and the layer at the top has its downside facing up. After this first operation, whatever crease lines are formed on the upside of the bottom layer will be the same as the ones formed on the bottom layer of the top layer, which means when the paper is unfolded and the upside of the entire paper is facing up, the mountain crease lines and the valley crease lines created after the first operation will be equal. Let $M$ be the length of mountain crease lines and $V$ be the length of valley crease lines after $N$ moves, and the side of the square paper is $1$. Let $diff = V - M =$ Length of valley crease lines created in the first operation $= 2\\sqrt{2}$. It is easy to calculate the total crease lines that are created (mountain and valley) in $N$ operations. It is the sum of a GP. Let $sum = V + M = {\\displaystyle\\sum_{i = 1}^{N}}2^{i - 1}\\cdot2\\sqrt{2}\\cdot{(\\dfrac{1}{\\sqrt{2}})}^{i - 1} = {\\displaystyle\\sum_{i = 1}^{N}}(\\sqrt{2})^{i + 2}$ Now to find $\\dfrac{M}{V}$, we use the age-old componendo and dividendo. $\\dfrac{M}{V} = \\dfrac{sum - diff}{sum + diff}$ And then rationalize it to find the coefficient of $\\sqrt{2}$. The reason for the uncommon modulo in the problem is that the irrational part of $\\dfrac{M}{V}$ is of the form $\\dfrac{a\\sqrt{2}}{b^2 - 2}$, where $a$ and $b$ are some integers. If there exists any $b$ such that $b^2 \\equiv 2 \\pmod m$, then the denominator becomes $0$. To avoid this situation, such a prime modulo $m$ was taken for which $2$ is not a quadratic residue modulo $m$. It can be seen that $999999893\\bmod 8 = 5$ and so, the Legendre symbol $\\bigg(\\dfrac{2}{999999893}\\bigg) = -1$ meaning that $2$ is a quadratic non-residue modulo $999999893$.",
    "code": "// library link: https://github.com/manan-grover/My-CP-Library/blob/main/library.cpp\n#include <bits/stdc++.h>\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace std;\nusing namespace __gnu_pbds;\n#define asc(i,a,n) for(I i=a;i<n;i++)\n#define dsc(i,a,n) for(I i=n-1;i>=a;i--)\n#define forw(it,x) for(A it=(x).begin();it!=(x).end();it++)\n#define bacw(it,x) for(A it=(x).rbegin();it!=(x).rend();it++)\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define lb(x) lower_bound(x)\n#define ub(x) upper_bound(x)\n#define fbo(x) find_by_order(x)\n#define ook(x) order_of_key(x)\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (I)((x).size())\n#define clr(x) (x).clear()\n#define U unsigned\n#define I long long int\n#define S string\n#define C char\n#define D long double\n#define A auto\n#define B bool\n#define CM(x) complex<x>\n#define V(x) vector<x>\n#define P(x,y) pair<x,y>\n#define OS(x) set<x>\n#define US(x) unordered_set<x>\n#define OMS(x) multiset<x>\n#define UMS(x) unordered_multiset<x>\n#define OM(x,y) map<x,y>\n#define UM(x,y) unordered_map<x,y>\n#define OMM(x,y) multimap<x,y>\n#define UMM(x,y) unordered_multimap<x,y>\n#define BS(x) bitset<x>\n#define L(x) list<x>\n#define Q(x) queue<x>\n#define PBS(x) tree<x,null_type,less<I>,rb_tree_tag,tree_order_statistics_node_update>\n#define PBM(x,y) tree<x,y,less<I>,rb_tree_tag,tree_order_statistics_node_update>\n#define pi (D)acos(-1)\n#define md 999999893\n#define rnd randGen(rng)\nI modex(I a,I b,I m){\n  a=a%m;\n  if(b==0){\n    return 1;\n  }\n  I temp=modex(a,b/2,m);\n  temp=(temp*temp)%m;\n  if(b%2){\n    temp=(temp*a)%m;\n  }\n  return temp;\n}\nI mod(I a,I b,I m){\n  a=a%m;\n  b=b%m;\n  I c=__gcd(a,b);\n  a=a/c;\n  b=b/c;\n  c=modex(b,m-2,m);\n  return (a*c)%m;\n}\nint main(){\n  mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n  uniform_int_distribution<I> randGen;\n  ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n  #ifndef ONLINE_JUDGE\n  freopen(\"input.txt\", \"r\", stdin);\n  freopen(\"out04.txt\", \"w\", stdout);\n  #endif\n  I temp=md;\n  I t;\n  cin>>t;\n  while(t--){\n    I n;\n    cin>>n;\n    I b=modex(2,n/2,md)-1;\n    I a;\n    if(n%2){\n      a=modex(2,n/2+1,md)-1;\n    }else{\n      a=modex(2,n/2,md)-1;\n    }\n    I temp=(a+1)*(a+1);\n    temp%=md;\n    temp-=2*b*b;\n    temp%=md;\n    I ans=mod(2*b,temp,md);\n    ans+=md;\n    ans%=md;\n    cout<<ans<<\"\\n\";\n  }\n  return 0;\n}",
    "tags": [
      "geometry",
      "math",
      "matrices"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1924",
    "index": "D",
    "title": "Balanced Subsequences",
    "statement": "A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.\n\nA subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.\n\nYou are given three integers $n$, $m$ and $k$. Find the number of sequences consisting of $n$ '(' and $m$ ')', such that the longest balanced subsequence is of length $2 \\cdot k$. Since the answer can be large calculate it modulo $1\\,000\\,000\\,007$ ($10^9 + 7$).",
    "tutorial": "Consider a function $f(n, m, k)$ which returns the number of permutations such that length of longest regular bracket subsequence is at most $2 \\cdot k$ where $n$ is the number of '(' and $m$ is the number of ')'. Answer to the problem is $f(n, m, k) - f(n, m, k-1)$ Now to compute $f(n, m, k)$, we can consider the following cases: Case 1: $k \\ge min(n, m)\\rightarrow$ Here, the answer is ${n+m} \\choose {m}$, since none of the strings can have a subsequence of length greater than $k$. Case 1: $k \\ge min(n, m)\\rightarrow$ Here, the answer is ${n+m} \\choose {m}$, since none of the strings can have a subsequence of length greater than $k$. Case 2: $k < min(n, m)\\rightarrow$ Here we can write $f(n, m, k) = f(n-1, m, k-1) + f(n, m-1, k)$ since all strings will either start with: a) ')' $\\rightarrow$ Here, count is equal to $f(n, m-1, k)$. b) '(' $\\rightarrow$ Here, count is equal to $f(n-1, m, k-1)$, the first opening bracket will always add $1$ to the optimal subsequence length because all strings where each of the $m$ ')' is paired to some '(' don't contribute to the count since $k<m$. Case 2: $k < min(n, m)\\rightarrow$ Here we can write $f(n, m, k) = f(n-1, m, k-1) + f(n, m-1, k)$ since all strings will either start with: a) ')' $\\rightarrow$ Here, count is equal to $f(n, m-1, k)$. b) '(' $\\rightarrow$ Here, count is equal to $f(n-1, m, k-1)$, the first opening bracket will always add $1$ to the optimal subsequence length because all strings where each of the $m$ ')' is paired to some '(' don't contribute to the count since $k<m$. After this recurrence relation we have 2 base cases: $k=0\\rightarrow$ Here, count is $1$ which can also be written as ${n+m} \\choose {k}$. $k=min(n, m)\\rightarrow$ Here, count is ${n+m} \\choose {m}$ (as proved in Case 1) which can also be written as ${n+m} \\choose {k}$. Now using induction we can prove that the value of $f(n, m, k)$ for Case 2 is ${n+m} \\choose {k}$.",
    "code": "#include <bits/stdc++.h>                   \n#define int long long      \nusing namespace std;\nconst long long N=4005, mod=1000000007;\n\nint power(int a, int b, int p)\n{\n    if(a==0)\n    return 0;\n    int res=1;\n    a%=p;\n    while(b>0)\n    {\n        if(b&1)\n        res=(1ll*res*a)%p;\n        b>>=1;\n        a=(1ll*a*a)%p;\n    }\n    return res;\n}\n\nint fact[N], inv[N];\nvoid pre()\n{\n    fact[0]=inv[0]=1;\n    for(int i=1;i<N;i++)\n    fact[i]=(fact[i-1]*i)%mod;\n    for(int i=1;i<N;i++)\n    inv[i]=power(fact[i], mod-2, mod);\n}\nint nCr(int n, int r)\n{\n    if(min(n, r)<0 || r>n)\n    return 0;\n    if(n==r)\n    return 1;\n    return (((fact[n]*inv[r])%mod)*inv[n-r])%mod;\n}\nint f(int n, int m, int k)\n{\n    if(k>=min(n, m))\n        return nCr(n+m, m);\n    return nCr(n+m, k);\n}\nint32_t main()\n{\n    pre();\n    int t;\n    cin>>t;\n    while(t--)\n    {\n        int n, m, k;\n        cin>>n>>m>>k;\n        cout<<(f(n, m, k) - f(n, m, k-1) + mod)%mod<<\"\\n\";\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1924",
    "index": "E",
    "title": "Paper Cutting Again",
    "statement": "There is a rectangular sheet of paper with initial height $n$ and width $m$. Let the current height and width be $h$ and $w$ respectively. We introduce a $xy$-coordinate system so that the four corners of the sheet are $(0, 0), (w, 0), (0, h)$, and $(w, h)$. The sheet can then be cut along the lines $x = 1,2,\\ldots,w-1$ and the lines $y = 1,2,\\ldots,h-1$. In each step, the paper is cut randomly along any one of these $h+w-2$ lines. After each vertical and horizontal cut, the right and bottom piece of paper respectively are discarded.\n\nFind the expected number of steps required to make the area of the sheet of paper strictly less than $k$. It can be shown that this answer can always be expressed as a fraction $\\dfrac{p}{q}$ where $p$ and $q$ are coprime integers. Calculate $p\\cdot q^{-1} \\bmod (10^9+7)$.",
    "tutorial": "Can you solve it for $k=2$? Using linearity of expectation, we can say that expected number of cuts is same as sum of probability of each line being cut and for $k=2$, we need to cut the paper until we achieve a $1 \\times 1$ piece of paper. Probability of each horizontal line being cut is $\\dfrac {1}{count \\thinspace of \\thinspace lines \\thinspace above \\thinspace it + 1}$ Probability of each vertical line being cut is $\\dfrac {1}{count \\thinspace of \\thinspace lines \\thinspace left \\thinspace to \\thinspace it + 1}$ Now for $k=2$ we just have to calculate the sum of all these probabilities. For the given problem we can solve it by dividing it into 4 cases: Only Vertical Cuts: Let the largest integer $y$ for which $n\\cdot y<k$ be $reqv$. The probability of achieving the goal using only vertical cuts is $\\frac{reqv}{reqv+n-1}$ since one of the $reqv$ lines needs to be cut before all the horizontal lines. Now we will multiply this with the sum of conditional probabilities for each of the vertical line. Sum of conditional probabilities of being cut for all lines from $1$ to $reqv$ is exactly $1$, since for area to be smaller than $k$, one of them needs to be cut and as soon as one is cut, the area becomes less than $k$ so no further cuts are required. Now for the lines from $reqv+1$ to $m-1$, their conditional probabilities will form the following harmonic progression: $\\frac{1}{n+reqv} + \\frac{1}{n+reqv+1} + .... + \\frac{1}{n+m-2}$ This is due to the fact that for a line to be cut it needs to occur before all horizontal lines and all vertical lines smaller than it. Only Vertical Cuts: Let the largest integer $y$ for which $n\\cdot y<k$ be $reqv$. The probability of achieving the goal using only vertical cuts is $\\frac{reqv}{reqv+n-1}$ since one of the $reqv$ lines needs to be cut before all the horizontal lines. Now we will multiply this with the sum of conditional probabilities for each of the vertical line. Sum of conditional probabilities of being cut for all lines from $1$ to $reqv$ is exactly $1$, since for area to be smaller than $k$, one of them needs to be cut and as soon as one is cut, the area becomes less than $k$ so no further cuts are required. Now for the lines from $reqv+1$ to $m-1$, their conditional probabilities will form the following harmonic progression: $\\frac{1}{n+reqv} + \\frac{1}{n+reqv+1} + .... + \\frac{1}{n+m-2}$ This is due to the fact that for a line to be cut it needs to occur before all horizontal lines and all vertical lines smaller than it. Case with only horizontal cuts can be handled similarly. Case with only horizontal cuts can be handled similarly. Case when the overall last cut is a horizontal one and there is at least one vertical cut: For this, we iterate over the last cut among all the vertical cuts. Let the last vertical cut be $x$. We now find the largest $y$ such that $(y\\cdot x)<k$. Let this value be $reqh$. The objective can be achieved using this case if the vertical line $x$ occurs before all the horizontal lines from $1$ to $reqh$ and all the vertical lines from $1$ to $x-1$, and after that any one of the horizontal line from $1$ to $reqh$ occur before all the vertical lines from $1$ to $x-1$. The probability of this happening is $\\frac{1}{x+reqh}\\times\\frac{reqh}{reqh+x-1}$. Now we just add the the conditional probabilities of being cut for every line and multiply this with the above probability to find the contribution of this case to the final answer. a. Firstly the conditional probability of the vertical line $x$ being cut is $1$. b. The sum of conditional probabilities for horizontal lines $1$ to $reqh$ is also $1$. The order of the first $x$ vertical cuts and the first $reqh$ horizontal cuts for the given case would look like: $x_v$, $y1_h$, ($(x-1)$ vertical lines and $(reqh-1)$ horizontal lines in any relative ordering) [Total $x+reqh$ elements in the sequence]. $x_v$ denotes the $x^{th}$ vertical cut. $y1_h$ denotes the horizontal cut which occurs first among all the first $reqh$ horizontal cuts. c. Vertical cuts from $x+1$ to $m-1$: For the $(x+1)^{th}$ cut, we can look at this like it needs to occur before the $x^{th}$ vertical cut (or it has one gap in the sequence to choose from a total of $(x+reqh+1)$ gaps). So the probability is $\\frac{1}{x+reqh+1}$. For the $(x+2)^{th}$ cut, we can first place the $(x+2)^{th}$ cut with probability $\\frac{1}{x+reqh+1}$ now we need to place the $(x+1)^{th}$ cut after of this which will happen with the probability of $\\frac{x+reqh+1}{x+reqh+2}$. So the overall probability is the product i.e., $\\frac{1}{x+reqh+2}$. Similarly, the probability for $(x+i)^{th}$ cut is $\\frac{1}{x+reqh+i}$. The sum of this Harmonic Progression can be computed in $\\mathcal{O}(1)$ using pre computation. d. Horizontal cuts from $reqh+1$ to $n-1$ (Trickiest Case imo) Let us see the case for the $(reqh+1)^{th}$ cut $\\rightarrow$ It has $2$ optimal gaps (before $x_v$ and the gap between $x_v$ and $y1_h$) so the probability is $\\frac{2}{x+reqh+1}$. Now for finding the probability for $(reqh+i)^{th}$ cut, we first place this cut into one of the $2$ gaps and handle both cases separately. Gap before $x_v$: this case is similar to case 3c and the answer is just $\\frac{1}{x+reqh+i}$. Gap between $x_v$ and $y1_h$. Here we again have to ensure that all lines from $reqh+1$ to $reqh+i-1$ occur after $reqh+i$. So we multiply $\\frac{reqh+x}{reqh+x+2}\\times\\frac{reqs+x+1}{reqh+x+3}$ since after we place the $(reqh+i)^{th}$ cut, we have $(reqh+x)$ good gaps among a total of $(reqh+x+2)$ and so on for all the other lines we place (Their relative ordering does not matter since we are only concerned with $(reqh+i)^{th}$ cut). The final term for $(reqh+i)^{th}$ cut occurs out to be: $\\frac{x+reqh}{(x+reqh+i)\\cdot(x+reqh+i-1)}$. This forms a quadratic Harmonic Progression, the sum of which can be computed in $\\mathcal{O}(1)$ using precomputation. Case when the overall last cut is a horizontal one and there is at least one vertical cut: For this, we iterate over the last cut among all the vertical cuts. Let the last vertical cut be $x$. We now find the largest $y$ such that $(y\\cdot x)<k$. Let this value be $reqh$. The objective can be achieved using this case if the vertical line $x$ occurs before all the horizontal lines from $1$ to $reqh$ and all the vertical lines from $1$ to $x-1$, and after that any one of the horizontal line from $1$ to $reqh$ occur before all the vertical lines from $1$ to $x-1$. The probability of this happening is $\\frac{1}{x+reqh}\\times\\frac{reqh}{reqh+x-1}$. Now we just add the the conditional probabilities of being cut for every line and multiply this with the above probability to find the contribution of this case to the final answer. a. Firstly the conditional probability of the vertical line $x$ being cut is $1$. b. The sum of conditional probabilities for horizontal lines $1$ to $reqh$ is also $1$. The order of the first $x$ vertical cuts and the first $reqh$ horizontal cuts for the given case would look like: $x_v$, $y1_h$, ($(x-1)$ vertical lines and $(reqh-1)$ horizontal lines in any relative ordering) [Total $x+reqh$ elements in the sequence]. $x_v$ denotes the $x^{th}$ vertical cut. $y1_h$ denotes the horizontal cut which occurs first among all the first $reqh$ horizontal cuts. c. Vertical cuts from $x+1$ to $m-1$: For the $(x+1)^{th}$ cut, we can look at this like it needs to occur before the $x^{th}$ vertical cut (or it has one gap in the sequence to choose from a total of $(x+reqh+1)$ gaps). So the probability is $\\frac{1}{x+reqh+1}$. For the $(x+2)^{th}$ cut, we can first place the $(x+2)^{th}$ cut with probability $\\frac{1}{x+reqh+1}$ now we need to place the $(x+1)^{th}$ cut after of this which will happen with the probability of $\\frac{x+reqh+1}{x+reqh+2}$. So the overall probability is the product i.e., $\\frac{1}{x+reqh+2}$. Similarly, the probability for $(x+i)^{th}$ cut is $\\frac{1}{x+reqh+i}$. The sum of this Harmonic Progression can be computed in $\\mathcal{O}(1)$ using pre computation. d. Horizontal cuts from $reqh+1$ to $n-1$ (Trickiest Case imo) Let us see the case for the $(reqh+1)^{th}$ cut $\\rightarrow$ It has $2$ optimal gaps (before $x_v$ and the gap between $x_v$ and $y1_h$) so the probability is $\\frac{2}{x+reqh+1}$. Now for finding the probability for $(reqh+i)^{th}$ cut, we first place this cut into one of the $2$ gaps and handle both cases separately. Gap before $x_v$: this case is similar to case 3c and the answer is just $\\frac{1}{x+reqh+i}$. Gap between $x_v$ and $y1_h$. Here we again have to ensure that all lines from $reqh+1$ to $reqh+i-1$ occur after $reqh+i$. So we multiply $\\frac{reqh+x}{reqh+x+2}\\times\\frac{reqs+x+1}{reqh+x+3}$ since after we place the $(reqh+i)^{th}$ cut, we have $(reqh+x)$ good gaps among a total of $(reqh+x+2)$ and so on for all the other lines we place (Their relative ordering does not matter since we are only concerned with $(reqh+i)^{th}$ cut). The final term for $(reqh+i)^{th}$ cut occurs out to be: $\\frac{x+reqh}{(x+reqh+i)\\cdot(x+reqh+i-1)}$. This forms a quadratic Harmonic Progression, the sum of which can be computed in $\\mathcal{O}(1)$ using precomputation. Case when the overall last cut is a vertical one and there is at least one horizontal cut: This case can be handled in a similar way as the previous case. Case when the overall last cut is a vertical one and there is at least one horizontal cut: This case can be handled in a similar way as the previous case.",
    "code": "#include <bits/stdc++.h>                    \n#define int long long    \nusing namespace std;\nconst long long N=2000005, mod=1000000007;\n\nint power(int a, int b, int p)\n{\n    if(a==0)\n    return 0;\n    int res=1;\n    a%=p;\n    while(b>0)\n    {\n        if(b&1)\n        res=(1ll*res*a)%p;\n        b>>=1;\n        a=(1ll*a*a)%p;\n    }\n    return res;\n}\n\nint pref[N], inv[N], pref2[N], hp2[N];\n\n// Returns (1/l + 1/(l+1) + ... + 1/r)\nint cal(int l, int r)\n{\n    if(l>r)\n        return 0;\n    return (pref[r]-pref[l-1]+mod)%mod;\n}\n\n// Returns (1/(l*(l+1)) + ... + 1/(r(r+1)))\nint cal2(int l, int r)\n{\n    if(l>r)\n        return 0;\n    return (pref2[r]-pref2[l-1]+mod)%mod;\n}\nvoid pre()\n{\n    pref[0]=0;\n    pref2[0]=0;\n    for(int i=1;i<N;i++)\n    {\n        inv[i]=power(i, mod-2, mod);\n        pref[i]=(pref[i-1]+inv[i])%mod;\n        int mul2=(i*(i+1))%mod;\n        pref2[i]=(pref2[i-1] + power(mul2, mod-2, mod))%mod;\n        hp2[i]=((i*(i-1))%mod)%mod;\n    }\n}\nint solve2(int n, int m, int k)\n{\n    if((n*m)<k)\n        return 0;\n    int ans=0;\n    int reqv=(k-1)/n;\n    if(reqv<m)\n    {\n        int prob=(reqv*inv[reqv+n-1])%mod;\n        int exp=(prob*(1ll + cal(n+reqv, m+n-2)))%mod;\n        ans=(ans + exp)%mod;\n    }\n    int reqh=(k-1)/m;\n    if(reqh<n)\n    {\n        int prob=(reqh*inv[reqh+m-1])%mod;\n        int exp=(prob*(1ll + cal(m+reqh, m+n-2)))%mod;\n        ans=(ans + exp)%mod;\n    }\n    for(int i=1;i<min(n, k);i++)\n    {\n        reqv=(k-1)/i;\n        if(reqv>=m)\n            continue;\n        int prob=(inv[i+reqv]*reqv)%mod;\n        prob=(prob*inv[i-1+reqv])%mod;\n        int num1=(hp2[i+reqv+1]*cal2(i+reqv, i+m-2))%mod;\n        int num2=((i+reqv+1)*cal(i+reqv+1, i+m-1))%mod;\n        int num=((num1+num2)*inv[i+reqv+1])%mod;\n        int exp=(prob*(2ll + cal(i+reqv+1, reqv+(n-1))+num))%mod;\n        ans=(ans + exp)%mod;\n    }\n    for(int i=1;i<min(m, k);i++)\n    {\n        reqh=(k-1)/i;\n        if(reqh>=n)\n            continue;\n        int prob=(inv[i+reqh]*reqh)%mod;\n        prob=(prob*inv[i-1+reqh])%mod;\n        // Sum for cases when the (reqh+i)th horizontal line occurs in the gap b/w x_v and y1_h\n        int num1=(hp2[i+reqh+1]*cal2(i+reqh, i+n-2))%mod;\n        // Sum for cases when the (reqh+i)th horizontal line occurs in the gap to the left of x_v\n        int num2=((i+reqh+1)*cal(i+reqh+1, i+n-1))%mod;\n        int num=((num1+num2)*inv[i+reqh+1])%mod;\n        int exp=(prob*(2ll + cal(i+reqh+1, reqh+(m-1))+num))%mod;\n        ans=(ans + exp)%mod;\n    }\n    return ans;\n}\nint32_t main()\n{\n    pre();\n    int t;\n    cin>>t;\n    while(t--)\n    {\n        int n, m, k;\n        cin>>n>>m>>k;\n        cout<<solve2(n, m, k)<<\"\\n\";\n    }\n}",
    "tags": [
      "combinatorics",
      "probabilities"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1924",
    "index": "F",
    "title": "Anti-Proxy Attendance",
    "statement": "This is an interactive problem!\n\nMr. 1048576 is one of those faculty who hates wasting his time in taking class attendance. Instead of taking attendance the old-fashioned way, he decided to try out something new today.\n\nThere are $n$ students in his class, having roll numbers $1$ to $n$. He knows that \\textbf{exactly $1$ student is absent} today. In order to determine who is absent, he can ask some queries to the class. In each query, he can provide two integers $l$ and $r$ ($1\\leq l\\leq r\\leq n$) and all students whose roll numbers are between $l$ and $r$ (inclusive) will raise their hands. He then counts them to determine if the roll number of the absent student lies between these values.\n\nThings seemed fine until his teaching assistant noticed something — the students are dishonest! Some students whose roll numbers lie in the given range may not raise their hands, while some other students whose roll number does not lie in the given range may raise their hands. But the students don't want to raise much suspicion. So, only the following $4$ cases are possible for a particular query $(l,r)$ —\n\n- True Positive: $r-l+1$ students are present and $r-l+1$ students raised their hands.\n- True Negative: $r-l$ students are present and $r-l$ students raised their hands.\n- False Positive: $r-l$ students are present but $r-l+1$ students raised their hands.\n- False Negative: $r-l+1$ students are present but $r-l$ students raised their hands.\n\nIn the first two cases, the students are said to be answering honestly, while in the last two cases, the students are said to be answering dishonestly. The students can mutually decide upon their strategy, not known to Mr. 1048576. Also, the students do not want to raise any suspicion and at the same time, want to create a lot of confusion. So, their strategy always meets the following two conditions —\n\n- The students will never answer honestly $3$ times in a row.\n- The students will never answer dishonestly $3$ times in a row.\n\nMr. 1048576 is frustrated by this act of students. So, he is willing to mark at most $2$ students as absent (though he knows that only one is). The attendance is said to be successful if the student who is actually absent is among those two. Also, due to limited class time, he can only ask up to $\\lceil\\log_{1.116}{n}\\rceil-1$ queries (weird numbers but okay). Help him complete a successful attendance.",
    "tutorial": "$\\sqrt[4]{1.5}=1.1069$ Try to do a $3\\rightarrow 2$ reduction in $4$ queries. Try to do a $3\\rightarrow 2$ reduction in such a way that if the middle part is eliminated $3$ queries are used otherwise $4$ queries are used. Instead of dividing the search space into $3$ equal parts, divide it into parts having size $36\\%$, $28\\%$ and $36\\%$. There might be multiple strategies to solve this problem. I will describe one of them. First, let's try to solve a slightly easier version where something like $\\lceil \\log_{1.1} n\\rceil$ queries are allowed and subset queries are allowed instead of range queries. The main idea is to maintain a search space of size $S$ and reduce it to a search space of size $\\big\\lceil \\frac{2S}{3}\\big\\rceil$ using atmost $4$ queries. At the end, there will be exactly $2$ elements remaining in the search space which can be guessed. The number of queries required to reduce a search space of size $n$ to a search space of size $2$ using the above strategy will be equal to $4\\cdot\\log_{\\frac{3}{2}}\\frac{n}{2}$ $= \\frac{\\ln\\frac{n}{2}}{0.25\\ln 1.5}$ $= \\frac{\\ln n - \\ln 2}{\\ln 1.1067}$ $< \\frac{\\ln n - \\ln 2}{\\ln 1.1}$ $= \\log_{1.1} n - 9.01$ $< \\lceil\\log_{1.1} n\\rceil$. Given below is one of the strategies how this can be achieved. Let the current search space be $T$. Divide $T$ into $3$ disjoint exhaustive subsets $T_1$, $T_2$ and $T_3$ of nearly equal size. Then follow the decision tree given below to discard one of the three subsets using at most $4$ queries. It can seen that all the leaf nodes discard at least one-third of the search space based on the previous three queries. Now, coming back to the problem where only ranges are allowed to be queried. This can be easily solved by choosing $T_1$, $T_2$ and $T_3$ in such a way that all elements of $T_1$ are less than all elements of $T_2$ and all elements of $T_2$ are less than all elements of $T_3$. Then all queries used in the above decision tree can be reduced to range queries since it really doesn't matter what are the actual elements of $T_1$, $T_2$ and $T_3$. Finally, there is just one small optimization left to be done. Notice that when $T_2$ gets eliminated, only $3$ queries are used and when $T_1$ and $T_3$ get eliminated, $4$ queries are used. So, it must be more optimal to keep the size of $T_2$ smaller than $T_1$ and $T_3$ but by how much? The answer is given by the equation $(1-x)^3 = (2x)^4$. It has two imaginary and two real roots out of which only one is positive $x=0.35843$. So by taking the size of the segments approximately $36\\%$, $28\\%$ and $36\\%$, you can do it in lesser number of queries which is less than $\\max(\\lceil\\log_{\\sqrt[4]{0.64^{-1}}} n\\rceil, \\lceil\\log_{\\sqrt[3]{0.72^{-1}}} n\\rceil)-\\log_{1.116} 2$ which is less than $\\lceil\\log_{1.116} n\\rceil-1$. During testing, the testers were able to come up with harder versions requiring lesser number of queries. Specifically, try to solve the problem under the following constraints assuming $n\\leq 10^5$: Harder version: $70$ queries by dario2994 Even harder version: $55$ queries by kevinsogo",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid assemble(vector<int> &x,vector<int> &x1,vector<int> &x2,vector<int> &x3,string mask)\n{\n    x.clear();\n    if(mask[0]=='1')\n    {\n        for(int i=0;i<x1.size();i++)\n            x.push_back(x1[i]);\n    }\n    if(mask[1]=='1')\n    {\n        for(int i=0;i<x2.size();i++)\n            x.push_back(x2[i]);\n    }\n    if(mask[2]=='1')\n    {\n        for(int i=0;i<x3.size();i++)\n            x.push_back(x3[i]);\n    }\n}\n\nbool query(vector<int> &x1,vector<int> &x2,vector<int> &x3,string mask)\n{\n    vector<int> x;\n    assemble(x,x1,x2,x3,mask);\n    int l=x[0],r=x.back();\n    cout << \"? \" << l << \" \" << r << endl;\n    int y;\n    cin >> y;\n    return (y==r-l);\n}\n\nvoid guess(int x)\n{\n    cout << \"! \" << x << endl;\n    int y;\n    cin >> y;\n}\n\nvoid finish()\n{\n    cout << \"#\" << endl;\n}\n\nint main()\n{\n    int tc;\n    cin >> tc;\n    while(tc--)\n    {\n        int n;\n        cin >> n;\n        vector<int> x;\n        for(int i=1;i<=n;i++)\n            x.push_back(i);\n        while(x.size()>2)\n        {\n            int m = x.size();\n            int k = round(0.36*m);\n            vector<int> x1,x2,x3;\n            for(int i=0;i<k;i++)\n                x1.push_back(x[i]);\n            for(int i=k;i<m-k;i++)\n                x2.push_back(x[i]);\n            for(int i=m-k;i<m;i++)\n                x3.push_back(x[i]);\n            if(query(x1,x2,x3,\"110\"))\n            {\n                if(query(x1,x2,x3,\"100\"))\n                {\n                    if(query(x1,x2,x3,\"111\"))\n                    {\n                        assemble(x,x1,x2,x3,\"011\");\n                    }\n                    else\n                    {\n                        assemble(x,x1,x2,x3,\"110\");\n                    }\n                }\n                else\n                {\n                    if(query(x1,x2,x3,\"110\"))\n                    {\n                        assemble(x,x1,x2,x3,\"101\");\n                    }\n                    else\n                    {\n                        if(query(x1,x2,x3,\"111\"))\n                        {\n                            assemble(x,x1,x2,x3,\"110\");\n                        }\n                        else\n                        {\n                            assemble(x,x1,x2,x3,\"011\");\n                        }\n                    }\n                }\n            }\n            else\n            {\n                if(query(x1,x2,x3,\"100\"))\n                {\n                    if(query(x1,x2,x3,\"110\"))\n                    {\n                        if(query(x1,x2,x3,\"111\"))\n                        {\n                            assemble(x,x1,x2,x3,\"011\");\n                        }\n                        else\n                        {\n                            assemble(x,x1,x2,x3,\"110\");\n                        }\n                    }\n                    else\n                    {\n                        assemble(x,x1,x2,x3,\"101\");\n                    }\n                }\n                else\n                {\n                    if(query(x1,x2,x3,\"111\"))\n                    {\n                        assemble(x,x1,x2,x3,\"110\");\n                    }\n                    else\n                    {\n                        assemble(x,x1,x2,x3,\"011\");\n                    }\n                }\n            }\n        }\n        guess(x[0]);\n        guess(x[1]);\n        finish();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "interactive",
      "ternary search"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1925",
    "index": "A",
    "title": "We Got Everything Covered!",
    "statement": "You are given two positive integers $n$ and $k$.\n\nYour task is to find a string $s$ such that all possible strings of length $n$ that can be formed using the first $k$ lowercase English alphabets occur as a subsequence of $s$.\n\nIf there are multiple answers, print the one with the smallest length. If there are still multiple answers, you may print any of them.\n\n\\textbf{Note:} A string $a$ is called a subsequence of another string $b$ if $a$ can be obtained by deleting some (possibly zero) characters from $b$ without changing the order of the remaining characters.",
    "tutorial": "The smallest length for such a string is $n\\cdot k$. The smallest length possible for such a string is $n\\cdot k$. To have the string $\\texttt{aaa}\\ldots\\texttt{a}$ as a subsequence, you need to have at least $n$ characters in the string as $\\texttt{a}$. Similarly for all $k$ different characters. So, that gives a total length of at least $n\\cdot k$. In fact, it is always possible to construct a string of length $n\\cdot k$ that satisfies this property. One such string is $(a_1a_2a_3\\ldots a_k)(a_1a_2a_3\\ldots a_k)(a_1a_2a_3\\ldots a_k)\\ldots n$ times where $a_i$ is the $i^{th}$ letter of English alphabet. For example, the answer for $n=3,k=4$ can be $\\texttt{abcdabcdabcd}$. It is not hard to see that the first letter of the subsequence can be from the first group of $k$ letters, second letter from the second group and so on.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    int tc;\n    cin >> tc;\n    while(tc--)\n    {\n        int n,k;\n        cin >> n >> k;\n        for(int i=0;i<n;i++)\n            for(char c='a';c<'a'+k;c++)\n                cout << c;\n        cout << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1925",
    "index": "B",
    "title": "A Balanced Problemset?",
    "statement": "Jay managed to create a problem of difficulty $x$ and decided to make it the second problem for Codeforces Round #921.\n\nBut Yash fears that this problem will make the contest highly unbalanced, and the coordinator will reject it. So, he decided to break it up into a problemset of $n$ sub-problems such that the difficulties of all the sub-problems are a positive integer and their sum is equal to $x$.\n\nThe coordinator, Aleksey, defines the balance of a problemset as the GCD of the difficulties of all sub-problems in the problemset.\n\nFind the maximum balance that Yash can achieve if he chooses the difficulties of the sub-problems optimally.",
    "tutorial": "$GCD(a_1,a_2,a_3,\\ldots,a_n) = GCD(a_1,a_1+a_2,a_1+a_2+a_3,\\ldots,a_1+a_2+a_3+\\ldots+a_n)$ The maximum GCD that can be achieved is always a divisor of $x$. Let the difficulties of the $n$ sub-problems be $a_1,a_2,a_3,\\ldots,a_n$. By properties of GCD, $GCD(a_1,a_2,a_3,\\ldots,a_n)$ $= GCD(a_1,a_1+a_2,a_1+a_2+a_3,\\ldots,a_1+a_2+a_3+\\ldots+a_n)$ $= GCD(a_1,a_1+a_2,a_1+a_2+a_3,\\ldots,x)$. So, the final answer will always be a divisor of $x$. Now, consider a divisor $d$ of $x$. If $n\\cdot d\\leq x$, you can choose the difficulties of the sub-problems to be $d,d,d,\\ldots,x-(n-1)d$ each of which is a multiple of $d$ and hence, the balance of this problemset will be $d$. Otherwise you cannot choose the difficulties of $n$ sub-problems such that each of them is a multiple of $d$. Find the maximum $d$ for which this condition holds. This can be done in $\\mathcal{O}(\\sqrt{x})$ using trivial factorization.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n    int tc;\n    cin >> tc;\n    while(tc--)\n    {\n        int x,n;\n        cin >> x >> n;\n        int ans = 1;\n        for(int i=1;i*i<=x;i++)\n        {\n            if(x%i==0)\n            {\n                if(n<=x/i)\n                    ans=max(ans,i);\n                if(n<=i)\n                    ans=max(ans,x/i);\n            }\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1925",
    "index": "D",
    "title": "Good Trip",
    "statement": "There are $n$ children in a class, $m$ pairs among them are friends. The $i$-th pair who are friends have a friendship value of $f_i$.\n\nThe teacher has to go for $k$ excursions, and for each of the excursions she chooses a pair of children randomly, equiprobably and independently. If a pair of children who are friends is chosen, their friendship value increases by $1$ for all subsequent excursions (the teacher can choose a pair of children more than once). The friendship value of a pair who are not friends is considered $0$, and it does not change for subsequent excursions.\n\nFind the expected value of the sum of friendship values of all $k$ pairs chosen for the excursions (at the time of being chosen). It can be shown that this answer can always be expressed as a fraction $\\dfrac{p}{q}$ where $p$ and $q$ are coprime integers. Calculate $p\\cdot q^{-1} \\bmod (10^9+7)$.",
    "tutorial": "Since expected value is linear, we can consider the contribution of initial friendship values and the contribution of increase in friendship values by repeated excursions independently. Contribution of the initial friendship values will be $\\dfrac{k\\times \\sum_{i=1}^{n}f_i}{\\binom{n}{2}}$. Now we can assume that there are $m$ pair of friends out of a total of $\\binom{n}{2}$ pairs of students whose initial friendship value is $0$. Since expected value is linear, we can consider the contribution of initial friendship values and the contribution of increase in friendship values by repeated excursions independently. Let $d=\\binom{n}{2}$ denote the total number of pairs of students that can be formed. Contribution of the initial friendship values will be $s=\\dfrac{k\\cdot \\sum_{i=1}^{n}f_i}{d}$. Now, to calculate the contribution to the answer by the increase in friendship values due to excursions, for each pair of friends, it will be $\\sum_{x=0}^{k}\\dfrac{x(x-1)}{2}\\cdot P(x)$ where $P(x)$ is the probability of a pair of friends to be selected for exactly $x$ out of the $k$ excursions which is given by $P(x)=\\binom{k}{x}\\cdot \\bigg(\\dfrac{1}{d}\\bigg)^{x}\\cdot \\bigg(\\dfrac{d-1}{d}\\bigg)^{k-x}$. Since the increase is uniform for all pair of friends, we just have to multiply this value by $m$ and add it to the answer. The time complexity is $\\mathcal{O}(m+k\\log k)$ per test case.",
    "code": "#include <bits/stdc++.h>                \n#define int long long   \n#define IOS std::ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);\n#define mod 1000000007ll\nusing namespace std;\nconst long long N=200005, INF=2000000000000000000;\n\nint power(int a, int b, int p)\n{\n    if(b==0)\n    return 1;\n    if(a==0)\n    return 0;\n    int res=1;\n    a%=p;\n    while(b>0)\n    {\n        if(b&1)\n        res=(1ll*res*a)%p;\n        b>>=1;\n        a=(1ll*a*a)%p;\n    }\n    return res;\n}\nint fact[N],inv[N];\nvoid pre()\n{\n    fact[0]=1;\n    inv[0]=1;\n    for(int i=1;i<N;i++)\n    fact[i]=(i*fact[i-1])%mod;\n    for(int i=1;i<N;i++)\n    inv[i]=power(fact[i], mod-2, mod);\n}\nint nCr(int n, int r, int p) \n{ \n    if(r>n || r<0)\n    return 0;\n    if(n==r)\n    return 1;\n    if (r==0) \n    return 1; \n    return (((fact[n]*inv[r]) % p )*inv[n-r])%p;\n} \nint32_t main()\n{\n    IOS;\n    pre();\n    int t;\n    cin>>t;\n    while(t--)\n    {\n        int n, m, k;\n        cin>>n>>m>>k;\n        int sum=0;\n        for(int i=0;i<m;i++)\n        {\n            int a, b, f;\n            cin>>a>>b>>f;\n            sum=(sum + f)%mod;\n        }\n        int den=((n*(n-1))/2ll)%mod;\n        int den_inv=power(den, mod-2, mod);\n        int base=(((sum*k)%mod)*den_inv)%mod;\n        int avg_inc=0;\n        for(int i=1;i<=k;i++)\n        {\n            // Extra sum added to ans if a particular pair of friends is picked i times. \n            int sum=((i*(i-1))/2ll)%mod; \n            int prob = (nCr(k, i, mod)*power(den_inv, i, mod))%mod;\n            // Probablity that a particular pair in unpicked for a given excursion.\n            int unpicked_prob = ((den-1)*den_inv)%mod;\n            // Probability that a particular pair is picked exactly i times.\n            prob=(prob * power(unpicked_prob, k-i, mod))%mod;\n            avg_inc = (avg_inc + (sum*prob)%mod)%mod;\n        }\n        int ans = (base + (m*avg_inc)%mod)%mod;\n        cout<<ans<<'\\n';\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1926",
    "index": "A",
    "title": "Vlad and the Best of Five",
    "statement": "Vladislav has a string of length $5$, whose characters are each either $A$ or $B$.\n\nWhich letter appears most frequently: $A$ or $B$?",
    "tutorial": "Since the string is of an odd length, we know that the number of $\\texttt{A}$s can't be equal to the number of $\\texttt{B}$s. So, there is always only one possible answer. Denote variables a_counter and b_counter - the count of $\\texttt{A}$s and $\\texttt{B}$s in the string respectively. Let's just iterate through all 5 characters of the string and increase the a_counter every time we see an $\\texttt{A}$ and the b_counter every time we see a $\\texttt{B}$. If the a_counter is greater than the b_counter we output $\\texttt{A}$, and $\\texttt{B}$ otherwise.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tint a = 0, b = 0;\n\tfor (char c : s) {\n\t\tif (c == 'A') {a++;}\n\t\telse {b++;}\n\t}\t\n\tcout << (a > b ? 'A' : 'B') << '\\n';\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1926",
    "index": "B",
    "title": "Vlad and Shapes",
    "statement": "Vladislav has a binary square grid of $n \\times n$ cells. A triangle or a square is drawn on the grid with symbols $1$. As he is too busy being cool, he asks you to tell him which shape is drawn on the grid.\n\n- A triangle is a shape consisting of $k$ ($k>1$) consecutive rows, where the $i$-th row has $2 \\cdot i-1$ consecutive characters $1$, and the central 1s are located in one column. An upside down triangle is also considered a valid triangle (but not rotated by 90 degrees).\n\n\\begin{center}\n{\\small Two left pictures contain examples of triangles: $k=4$, $k=3$. The two right pictures don't contain triangles.}\n\\end{center}\n\n- A square is a shape consisting of $k$ ($k>1$) consecutive rows, where the $i$-th row has $k$ consecutive characters $1$, which are positioned at an equal distance from the left edge of the grid.\n\n\\begin{center}\n{\\small Examples of two squares: $k=2$, $k=4$.}\n\\end{center}\n\nFor the given grid, determine the type of shape that is drawn on it.",
    "tutorial": "Let's draw some examples on paper and notice a pattern. What we notice is that in the case of a triangle there is a row with exactly one $\\texttt{1}$, but not a square. So, this is what we need to check. Iterate through all rows, and check if there is a row with exactly one $\\texttt{1}$. If it was the case for at least one, then the answer is \"TRIANGLE\", and \"SQUARE\" otherwise. Another solution. Check if any $2 \\times 2$ square has sum $3$. If it does, then we must be at one of the sloped sides of a triangle, so the answer is \"TRIANGLE\". If there is no such square, the answer is \"SQUARE\". Why does it work?",
    "code": " #include <iostream>\n#include <algorithm>\n#include <vector>\n#include <array>\n#include <set>\n#include <map>\n#include <queue>\n#include <stack>\n#include <list>\n#include <chrono>\n#include <random>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <cstring>\n#include <iomanip>\n#include <bitset>\n#include <cassert>\n \nusing namespace std;\n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<string> g;\n    for(int i = 0; i < n; i++)\n    {\n        string s;\n        cin >> s;\n        g.push_back(s);\n    }\n    bool triangle = false;\n    for(int i = 0; i < n; i++)\n    {\n        int cnt = 0;\n        for(int j = 0; j < n; j++)\n        {\n            if(g[i][j] == '1')\n            {\n                cnt++;\n            }\n        }\n        if(cnt == 1)\n        {\n            triangle = true;\n        }\n        else if(cnt > 1)\n        {\n            break;\n        }\n    }\n    reverse(g.begin(), g.end());\n    for(int i = 0; i < n; i++)\n    {\n        int cnt = 0;\n        for(int j = 0; j < n; j++)\n        {\n            if(g[i][j] == '1')\n            {\n                cnt++;\n            }\n        }\n        if(cnt == 1)\n        {\n            triangle = true;\n        }\n        else if(cnt > 1)\n        {\n            break;\n        }\n    }\n    if(triangle)\n    {\n        cout << \"TRIANGLE\" << endl;\n    }\n    else\n    {\n        cout << \"SQUARE\" << endl;\n    }\n}\n \nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n \n \n \n",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1926",
    "index": "C",
    "title": "Vlad and a Sum of Sum of Digits",
    "statement": "{\\textbf{Please note that the time limit for this problem is only 0.5 seconds per test.}}\n\nVladislav wrote the integers from $1$ to $n$, inclusive, on the board. Then he replaced each integer with the sum of its digits.\n\nWhat is the sum of the numbers on the board now?\n\nFor example, if $n=12$ then initially the numbers on the board are: $$1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12.$$ Then after the replacement, the numbers become: $$1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3.$$ The sum of these numbers is $1+2+3+4+5+6+7+8+9+1+2+3=51$. Thus, for $n=12$ the answer is $51$.",
    "tutorial": "Let's denote $S(x)$ as the sum of digits of number $x$. Since $n \\leq 2 \\cdot 10^5$, for a single test case, we can brute force $S(1) + S(2) + S(3) + \\dots + S(n)$ and output the answer. However, since the number of test cases is large, we can't compute this value for $n$ each time. This needs a standard idea of precomputation: we will compute the answer for each value from $1$ to $n$ and store it in an array $\\mathrm{ans}$: $\\mathrm{ans}(n) = S(n) + \\mathrm{ans}(n-1)$. Then to answer each test case we just output $\\mathrm{ans}(n)$. No math is needed! The precomputation takes $\\mathcal{O}(n \\log n)$ time (it takes $\\mathcal{O}(\\log n)$ time to find sum of digits), but now we can answer queries in $\\mathcal{O}(1)$ per test case, so overall the complexity is $\\mathcal{O}(n \\log n + t)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nint res[MAX];\n \nint S(int x) {\n\tint res = 0;\n\twhile (x) {\n\t\tres += (x % 10);\n\t\tx /= 10;\n\t}\n\treturn res;\n}\n \nvoid solve() {\n\tint x;\n\tcin >> x;\n\tcout << res[x] << '\\n';\n}\n \nint main() {\n\tres[0] = 0;\n\tfor (int i = 1; i < MAX; i++) {\n\t\tres[i] = res[i - 1] + S(i);\n\t}\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1926",
    "index": "D",
    "title": "Vlad and Division",
    "statement": "Vladislav has $n$ non-negative integers, and he wants to divide \\textbf{all} of them into several groups so that in any group, any pair of numbers does not have matching bit values among bits from $1$-st to $31$-st bit (i.e., considering the $31$ least significant bits of the binary representation).\n\nFor an integer $k$, let $k_2(i)$ denote the $i$-th bit in its binary representation (from right to left, indexing from 1). For example, if $k=43$, since $43=101011_2$, then $43_2(1)=1$, $43_2(2)=1$, $43_2(3)=0$, $43_2(4)=1$, $43_2(5)=0$, $43_2(6)=1$, $43_2(7)=0$, $43_2(8)=0, \\dots, 43_2(31)=0$.\n\n\\textbf{Formally, for any two numbers $x$ and $y$ in the same group, the condition $x_2(i) \\neq y_2(i)$ must hold for all $1 \\leq i < 32$.}\n\nWhat is the minimum number of groups Vlad needs to achieve his goal? Each number must fall into exactly one group.",
    "tutorial": "We can notice that a group contains either one or two numbers. Now, we check how many numbers we can pair together. The condition that all bits in a pair differ is equivalent to the pair resulting in a number which has all bits set as $1$ when we XOR the $2$ numbers. So, we need to see the number of pairs for which their XOR is equal to $2^{31} - 1$ (As this is the number with all bits set). Now, we iterate through the numbers in order from left to right, we check if we can pair the current number with some existing previous one. We can check if the number can be paired with some previous one if we encountered the value of $(2^{31} - 1)$ XOR $a_i$ in the past. If we have, we mark that value and the current value as taken, and don't start a new group, otherwise we start a new group and continue the process.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \nvoid solve() {\n    int n; cin >> n;\n    map<int, int> cnt;\n    int ans = 0;\n    for(int i = 0, x; i < n; ++i) {\n        cin >> x;\n        if(!cnt[x]) ++ans, ++cnt[((1 << 31) - 1) ^ x];\n        else --cnt[x];\n    }\n    cout << ans << \"\\n\";\n}   \n \nmain() {\n    int t = 1; cin >> t;\n    while(t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1926",
    "index": "E",
    "title": "Vlad and an Odd Ordering",
    "statement": "Vladislav has $n$ cards numbered $1, 2, \\dots, n$. He wants to lay them down in a row as follows:\n\n- First, he lays down all the odd-numbered cards from smallest to largest.\n- Next, he lays down all cards that are twice an odd number from smallest to largest (i.e. $2$ multiplied by an odd number).\n- Next, he lays down all cards that are $3$ times an odd number from smallest to largest (i.e. $3$ multiplied by an odd number).\n- Next, he lays down all cards that are $4$ times an odd number from smallest to largest (i.e. $4$ multiplied by an odd number).\n- And so on, until all cards are laid down.\n\nWhat is the $k$-th card he lays down in this process? Once Vladislav puts a card down, he cannot use that card again.",
    "tutorial": "Idea. The problem is very recursive; after we lay all the odd cards down, we have the same problem as we started with, but every card is multiplied by $2$. Can you solve the problem from here? We present two different solutions, which are actually the same idea, but presented a little differently, so you can understand the problem better ;). Solution 1. Note that we will never lay cards down on moves that are not powers of $2$. Why? Well, for example, if a number is $3 \\times \\mathrm{odd}$, then this number is also $1 \\times \\mathrm{odd}$, and similarly for $5 \\times \\mathrm{odd}$, $7 \\times \\mathrm{odd}$, $\\dots$. This same logic shows that $6 \\times \\mathrm{odd}$ numbers will be laid down in the $2 \\times \\mathrm{odd}$ step, etc. This means that all our cards are divided into \"blocks\": $1 \\times \\mathrm{odd}$ numbers (odd numbers), $2 \\times \\mathrm{odd}$ numbers (multiples of $2$ but not $4$), $4 \\times \\mathrm{odd}$ numbers (multiples of $4$ but not $8$), $8 \\times \\mathrm{odd}$ numbers (multiples of $8$ but not $16$), and so on. This leads to the solution. We can find the number of cards in each of these groups by repeatedly finding the number of odd cards, removing them, and continuing the process on the remaining deck. So to find the $k$-th card, we find the first prefix sum that exceeds $k$, and find the $k$-th card in this block. Solution 2. Let's make some observations: Of the cards $1, 2, \\dots, n$, there are $\\lceil \\frac{n}{2} \\rceil$ odd ones. The even-numbered cards cannot be laid down on an odd-numbered step ($1 \\times \\mathrm{odd}$, $3 \\times \\mathrm{odd}$, $5 \\times \\mathrm{odd}$, $\\dots$), because all those values are odd. In other words, even-numbered cards can only be laid down at even-numbered steps $2 \\times \\mathrm{odd}$, $4 \\times \\mathrm{odd}$, $6 \\times \\mathrm{odd}$, $\\dots$. In other words, even-numbered cards can only be laid down at even-numbered steps $2 \\times \\mathrm{odd}$, $4 \\times \\mathrm{odd}$, $6 \\times \\mathrm{odd}$, $\\dots$. Otherwise, once we are finished laying down all the odd numbers, $\\lceil \\frac{n}{2} \\rceil$ turns have passed, and our remaining cards are the numbers $2, 4, 6, \\dots$ and we will only lay down cards in the steps $2 \\times \\mathrm{odd}$, $4 \\times \\mathrm{odd}$, $6 \\times \\mathrm{odd}$, $\\dots$. Since all the remaining numbers have a factor of $2$, we will divide it out and get the following equivalent problem: and our remaining cards are the numbers $1, 2, 3, \\dots$ and we will only lay down cards in the steps $1 \\times \\mathrm{odd}$, $2 \\times \\mathrm{odd}$, $3 \\times \\mathrm{odd}$, $\\dots$. But this is exactly the same as the original problem! Thus we can solve this problem recursively. More formally, let the answer be $\\mathrm{ans}(n, k)$. Then if $k \\leq \\lceil \\frac{n}{2} \\rceil$, output the $k$-th odd number; otherwise, output $2 \\cdot \\mathrm{ans}(\\lfloor \\frac{n}{2} \\rfloor, k - \\lceil \\frac{n}{2} \\rceil)$. This works in $\\mathcal{O}(\\log n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tint n, k;\n\tcin >> n >> k;\n\tvector<int> v;\n\twhile (n) {\n\t\tv.push_back((n + 1) / 2);\n\t\tn /= 2;\n\t}\n\tint tot = 0, pow2 = 1;\n\tfor (int x : v) {\n\t\tif (tot < k && k <= tot + x) {\n\t\t\tcout << pow2 * (2 * (k - tot) - 1) << '\\n';\n\t\t\treturn;\n\t\t}\n\t\ttot += x;\n\t\tpow2 *= 2;\n\t}\n}\n \nint main() {\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1926",
    "index": "F",
    "title": "Vlad and Avoiding X",
    "statement": "Vladislav has a grid of size $7 \\times 7$, where each cell is colored black or white. In one operation, he can choose any cell and change its color (black $\\leftrightarrow$ white).\n\nFind the minimum number of operations required to ensure that there are no black cells with four diagonal neighbors also being black.\n\n\\begin{center}\n{\\small The left image shows that initially there are two black cells violating the condition. By flipping one cell, the grid will work.}\n\\end{center}",
    "tutorial": "Notice that we can split the grid into two parts, red and blue, in a chessboard coloring fashion as shown, and that Xs from one color only influence cells of that color. This means that we can solve the problem for the red and blue parts independently, and combine them at the end. Let's brute force the number of cells in the blue part that we need to flip using backtracking (i.e. let's brute force all ways we can flip $0$ cells and see if all the black cells work, then try flipping $1$, then $2$, and so on). In fact, it can be shown that this number does not exceed $4$, by running this algorithm on an all-black grid. Similarly, we see that the number of cells in the red part that we need to flip is also not more than $4$. The backtracking will try $\\sim \\binom{25}{4} + \\binom{24}{4}$ flips, and each takes around $50$ operations to check the whole grid, which not more than $115000$. This is not very big, and even with $200$ test cases, it does not take more than 140 milliseconds. You can run the worst-case locally to check. Bonus. Can this problem be solved in polynomial time?",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvector<pair<int, int>> odd, even;\n \nbool valid(int gc[7][7], bool odd) {\n\tfor (int r = 1; r < 6; r++) {\n\t\tfor (int c = 1; c < 6; c++) {\n\t\t\tif (gc[r][c] && ((r + c) % 2 == odd)) {\n\t\t\t\tif (gc[r - 1][c - 1] && gc[r - 1][c + 1] && gc[r + 1][c - 1] && gc[r + 1][c + 1]) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n \nbool check(int g[7][7], int flips_left, int idx, vector<pair<int, int>>& vec, int valid_val) {\n    if (flips_left == 0) {\n        return valid(g, valid_val);\n    }\n    if (idx == vec.size()) {\n        return false;\n    }\n    bool ok = false;\n    ok |= check(g, flips_left, idx + 1, vec, valid_val);\n    g[vec[idx].first][vec[idx].second] ^= 1;\n    ok |= check(g, flips_left - 1, idx + 1, vec, valid_val);\n    g[vec[idx].first][vec[idx].second] ^= 1;\n    return ok;\n}\n \nvoid solve() {\n    int g[7][7];\n    for (int i = 0; i < 7; i++) {\n        for (int j = 0; j < 7; j++) {\n            char c;\n            cin >> c;\n            g[i][j] = (c == 'B');\n        }\n    }   \n    int res = 0;\n    for (int i = 0; i <= 4; i++) {\n        if (check(g, i, 0, odd, 1)) {res += i; break;}\n    }\n    for (int i = 0; i <= 4; i++) {\n        if (check(g, i, 0, even, 0)) {res += i; break;}\n    }\n    cout << res << '\\n';\n}\nint main() {\n\t\n\tfor (int i = 0; i < 7; i++) {\n\t\tfor (int j = 0; j < 7; j++) {\n\t\t\tif ((i + j) % 2) {\n\t\t\t\todd.emplace_back(i, j);\n\t\t\t}\n\t\t\telse {\n\t\t\t\teven.emplace_back(i, j);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n}\n",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1926",
    "index": "G",
    "title": "Vlad and Trouble at MIT",
    "statement": "Vladislav has a son who really wanted to go to MIT. The college dormitory at MIT (Moldova Institute of Technology) can be represented as a tree with $n$ vertices, each vertex being a room with exactly one student. A tree is a connected undirected graph with $n$ vertices and $n-1$ edges.\n\nTonight, there are three types of students:\n\n- students who want to party and play music (marked with $P$),\n- students who wish to sleep and enjoy silence (marked with $S$), and\n- students who don't care (marked with $C$).\n\nInitially, all the edges are thin walls which allow music to pass through, so when a partying student puts music on, it will be heard in every room. However, we can place some thick walls on any edges — thick walls don't allow music to pass through them.\n\nThe university wants to install some thick walls so that every partying student can play music, and no sleepy student can hear it.\n\nBecause the university lost a lot of money in a naming rights lawsuit, they ask you to find the minimum number of thick walls they will need to use.",
    "tutorial": "Let's think of the problem as trying to separate some rooms(with P and possibly some C) that will hear music and the other ones(with S and possibly some C) that will not hear music. Imagine red \"water\" from the P nodes and blue \"water\" flowing from the S nodes flowing freely until hitting a thick wall. We don't want these two \"waters\" to mix. Let's rotate the tree upside down so that on top are all the leaves and end with the root node at the bottom and start letting blue and red water flow down. We want to check so that, at any point, these waters don't mix. Let's go through them layer by layer and do dynamic programming $dp_{i, 3}$ where for each node $i$, we remember the minimum number of walls we have to add such that only red water flows there, only blue water flows, or no water flows, ensuring there is no mixing in nodes above. Using the $dp$ values for the nodes above, we can calculate the $dp$ value of the node below. Of course, the $dp$ value for the \"pumping\" nodes (P or S) will have the $dp$ of other colors infinite. The final answer will be the minimum of $dp_{1, 0}$, $dp_{1, 1}$, $dp_{1, 2}$, the minimum number of walls needed for the root to not reach \"water\"(and no mixing above), to reach only red \"water\"(and no mixing above) or reach only blue \"water\"(and no mixing above). Final complexity is $\\mathcal{O}(n)$",
    "code": " #include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define INF (int)1e18\n \nint n;\nconst int N = 1e5 + 69;\nint dp[N][3];\nstring s; \nvector <int> adj[N];\n \nvoid dfs(int u){\n    // dp[u][0] = nothing open \n    // dp[u][1] = P open \n    // dp[u][2] = S open \n    \n    dp[u][0] = INF;\n    if (s[u] != 'S') dp[u][1] = 0;\n    else dp[u][1] = INF;\n    if (s[u] != 'P') dp[u][2] = 0;\n    else dp[u][2] = INF;\n    int tot = 0;\n    \n    for (int v : adj[u]){\n        dfs(v);\n        dp[u][1] = dp[u][1] + min({dp[v][1], dp[v][2] + 1, dp[v][0]});\n        dp[u][2] = dp[u][2] + min({dp[v][2], dp[v][1] + 1, dp[v][0]});\n        tot += dp[v][0];\n    }\n    \n    if (s[u] != 'C') tot = INF;\n    \n    dp[u][0] = min({tot, dp[u][1] + 1, dp[u][2] + 1});\n    \n    //cout << u << \" \" << dp[u][0] << \" \" << dp[u][1] << \" \" << dp[u][2] << \"\\n\";\n}\n \nvoid Solve() \n{\n    cin >> n;\n    for (int i = 1; i <= n; i++) adj[i].clear();\n    for (int i = 2; i <= n; i++){\n        int x; cin >> x;\n        adj[x].push_back(i);\n    }\n    \n    cin >> s; s = \"0\" + s;\n    \n    dfs(1);\n    \n    cout << min({dp[1][0], dp[1][1], dp[1][2]}) << \"\\n\";\n}\n \nint32_t main() \n{\n    int t = 1;\n    // freopen(\"in\",  \"r\", stdin);\n    // freopen(\"out\", \"w\", stdout);\n    \n    cin >> t;\n    for(int i = 1; i <= t; i++) \n    {\n        //cout << \"Case #\" << i << \": \";\n        Solve();\n    }\n    return 0;\n}\n",
    "tags": [
      "dfs and similar",
      "dp",
      "flows",
      "graphs",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1927",
    "index": "A",
    "title": "Make it White",
    "statement": "You have a horizontal strip of $n$ cells. Each cell is either white or black.\n\nYou can choose a \\textbf{continuous} segment of cells once and paint them all white. After this action, all the black cells in this segment will become white, and the white ones will remain white.\n\nWhat is the minimum length of the segment that needs to be painted white in order for all $n$ cells to become white?",
    "tutorial": "To repaint all the black cells in white, it is necessary to select a segment from $l$ to $r$ that contains all the black cells. Let's choose the entire strip as a segment ($l=1, r=n$). As long as the segment starts with a white cell, it can be left unpainted, i.e., $l$ can be increased by one. Otherwise, we cannot exclude the cell from the segment. Similarly, we can exclude the last cell from the segment until it becomes black. After all exclusions, the answer will be $r - l + 1$. The selected segment contains all the black cells, as we have excluded only white cells. The segment is also minimal because reducing the segment from either side will result in one of the black cells remaining black.",
    "code": "from collections import deque\n \ndef solve():\n    n = int(input())\n    s = deque(input())\n    while len(s) > 0 and s[0] == 'W':\n        s.popleft()\n    while len(s) > 0 and s[-1] == 'W':\n        s.pop()\n    print(len(s))\n    \n \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1927",
    "index": "B",
    "title": "Following the String",
    "statement": "Polycarp lost the string $s$ of length $n$ consisting of lowercase Latin letters, but he still has its trace.\n\nThe trace of the string $s$ is an array $a$ of $n$ integers, where $a_i$ is the number of such indices $j$ ($j < i$) that $s_i=s_j$. For example, the trace of the string abracadabra is the array [$0, 0, 0, 1, 0, 2, 0, 3, 1, 1, 4$].\n\nGiven a trace of a string, find \\textbf{any} string $s$ from which it could have been obtained. The string $s$ should consist only of lowercase Latin letters a-z.",
    "tutorial": "To build the desired string, we will move from left to right and add characters. In order to add a character at each step with the required number of occurrences, we will keep track of the number of times each character is added.",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    cnt = [0] * 26\n    s = ''\n    for i in range(n):\n        for j in range(26):\n            if cnt[j] == a[i]:\n                cnt[j] += 1\n                s += chr(97 + j)\n                break\n    print(s)\n \n \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1927",
    "index": "C",
    "title": "Choose the Different Ones!",
    "statement": "Given an array $a$ of $n$ integers, an array $b$ of $m$ integers, and an even number $k$.\n\nYour task is to determine whether it is possible to choose \\textbf{exactly} $\\frac{k}{2}$ elements from both arrays in such a way that among the chosen elements, every integer from $1$ to $k$ is included.\n\nFor example:\n\n- If $a=[2, 3, 8, 5, 6, 5]$, $b=[1, 3, 4, 10, 5]$, $k=6$, then it is possible to choose elements with values $2, 3, 6$ from array $a$ and elements with values $1, 4, 5$ from array $b$. In this case, all numbers from $1$ to $k=6$ will be included among the chosen elements.\n- If $a=[2, 3, 4, 5, 6, 5]$, $b=[1, 3, 8, 10, 3]$, $k=6$, then it is not possible to choose elements in the required way.\n\nNote that you are not required to find a way to choose the elements — your program should only check whether it is possible to choose the elements in the required way.",
    "tutorial": "Notice that elements with a value greater than $k$ are not relevant to us. Let's divide the values into three categories: Occurring only in array $a$; occurring only in array $b$; occurring in both arrays. The answer will be NO if any of the following conditions are met: the number of values of the first type is greater than $\\frac{k}{2}$ (this implies that we cannot select all such elements); the number of values of the second type is greater than $\\frac{k}{2}$ (this implies that we cannot select all such elements); the total number of values of all three types is less than $k$ (this implies that some values do not occur in either of the arrays). Otherwise, the answer is YES.",
    "code": "def solve():\n    n, m, k = map(int, input().split())\n    a = [int(x) for x in input().split()]\n    b = [int(x) for x in input().split()]\n    cnt = [0] * (k + 1)\n    for e in a:\n        if e <= k:\n            cnt[e] |= 1\n    for e in b:\n        if e <= k:\n            cnt[e] |= 2\n    c = [0] * 4\n    for e in cnt:\n        c[e] += 1\n    if c[1] > k // 2 or c[2] > k // 2 or c[1] + c[2] + c[3] != k:\n        print(\"NO\")\n    else:\n        print(\"YES\")\n \n \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1927",
    "index": "D",
    "title": "Find the Different Ones!",
    "statement": "You are given an array $a$ of $n$ integers, and $q$ queries.\n\nEach query is represented by two integers $l$ and $r$ ($1 \\le l \\le r \\le n$). Your task is to find, for each query, two indices $i$ and $j$ (or determine that they do not exist) such that:\n\n- $l \\le i \\le r$;\n- $l \\le j \\le r$;\n- $a_i \\ne a_j$.\n\nIn other words, for each query, you need to find a pair of different elements among $a_l, a_{l+1}, \\dots, a_r$, or report that such a pair does not exist.",
    "tutorial": "Before processing the requests, let's calculate the position $p_i$ of the nearest element to the left that is not equal to it (we will consider $p_1 = -1$). To do this in linear time, we will traverse the array from left to right. For the $i$-th element ($1 < i \\le n$), if $a_i \\ne a_{i - 1}$, then $p_i=i-1$, otherwise $p_i=p_{i-1}$ (all elements between $p_{i - 1}$ and $i$ will be equal to $a_i$ by construction). To answer a query, we will fix the right boundary as one of the positions for the answer. Then the best of all suitable positions for it is $p_r$, as it is the maximum, and we just need to check that $l \\le p_r$. (Note that by fixing any other position, you may not find the answer for a segment of the form $[1, 1, 1, \\dots, 1, 2]$)",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    p = [-1] * n\n    for i in range(1, n):\n        p[i] = p[i - 1]\n        if a[i] != a[i - 1]:\n            p[i] = i - 1\n    for i in range(int(input())):\n        l, r = map(int, input().split())\n        l -= 1\n        r -= 1\n        if p[r] < l:\n            print(\"-1 -1\")\n        else:\n            print(p[r] + 1, r + 1)\n    \n    \nt = int(input())\nfor _ in range(t):\n    solve()\n    if _ + 1 != t:\n        print()",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "dsu",
      "greedy",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1927",
    "index": "E",
    "title": "Klever Permutation",
    "statement": "You are given two integers $n$ and $k$ ($k \\le n$), where $k$ is even.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation (as $2$ appears twice in the array) and $[0,1,2]$ is also not a permutation (as $n=3$, but $3$ is not present in the array).\n\nYour task is to construct a $k$-level permutation of length $n$.\n\nA permutation is called $k$-level if, among all the sums of continuous segments of length $k$ (of which there are exactly $n - k + 1$), any two sums differ by no more than $1$.\n\nMore formally, to determine if the permutation $p$ is $k$-level, first construct an array $s$ of length $n - k + 1$, where $s_i=\\sum_{j=i}^{i+k-1} p_j$, i.e., the $i$-th element is equal to the sum of $p_i, p_{i+1}, \\dots, p_{i+k-1}$.\n\nA permutation is called $k$-level if $\\max(s) - \\min(s) \\le 1$.\n\nFind \\textbf{any} $k$-level permutation of length $n$.",
    "tutorial": "To construct a permutation, let's make an important observation: $s_i$ cannot be equal to $s_{i + 1}$ (i.e., they differ by at least $1$). Since the array $s$ can only contain two different values, it always has the form $[x, x+1, x, x+1, \\dots]$ or $[x, x-1, x, x-1, \\dots]$. Let's construct a permutation of the first form. Since $s_1 + 1 = s_2$, then $a_1 + 1=a_{k+1}$; since $s_2 = s_3 + 1$, then $a_2 = a_{k+2} + 1$; since $s_3 + 1 = s_4$, then $a_3 + 1 = a_{k+3}$; $\\dotsi$ since $s_k = s_{k + 1} + 1$, then $a_k = a_{k+k} + 1$; $\\dotsi$ Thus, for all odd positions $i$, it must hold that $a_i + 1 = a_{i + k}$, and for even positions, $a_i = a_{i + k} + 1$. To construct such a permutation, we will iterate through all positions $i$ from $1$ to $k$ and fill the permutation in positions $i, i+k, i+2\\cdot k, \\dots$.",
    "code": "def solve():\n    n, k = map(int, input().split())\n    l, r = 1, n\n    ans = [0] * n\n    for i in range(k):\n        for j in range(i, n, k):\n            if i % 2 == 0:\n                ans[j] = l\n                l += 1\n            else:\n                ans[j] = r\n                r -= 1\n    print(*ans)\n    \n    \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "constructive algorithms",
      "math",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1927",
    "index": "F",
    "title": "Microcycle",
    "statement": "Given an undirected weighted graph with $n$ vertices and $m$ edges. There is at most one edge between each pair of vertices in the graph, and the graph does not contain loops (edges from a vertex to itself). The graph is not necessarily connected.\n\nA cycle in the graph is called simple if it doesn't pass through the same vertex twice and doesn't contain the same edge twice.\n\nFind any simple cycle in this graph in which the weight of the lightest edge is minimal.",
    "tutorial": "Let's use the disjoint sets union (DSU). We will add edges to the DSU in descending order of weight. At the same time, we will build a graph containing only the edges that, when added to the DSU, unite different sets. We will also remember the last edge that we did not add to the graph, as it will be the lightest edge of the desired cycle. To find the cycle itself, we will find a path in the constructed graph leading from one end of this edge to the other (due to the construction of the graph, it does not contain cycles, so we need to find a path in the tree).",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n \ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(time(nullptr));\n \nconst ll inf = 1e18;\nconst ll M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n \nstruct dsu{\n    vector<int> p, lvl;\n \n    dsu(int n){\n        p.resize(n);\n        iota(p.begin(), p.end(), 0);\n        lvl.assign(n, 0);\n    }\n \n    int get(int i){\n        if (p[i] == i) return i;\n        return p[i] = get(p[i]);\n    }\n \n    bool unite(int a, int b){\n        a = get(a);\n        b = get(b);\n        if(a == b) return false;\n        if(lvl[a] < lvl[b]) swap(a, b);\n        p[b] = a;\n        if(lvl[a] == lvl[b]) lvl[a]++;\n        return true;\n    }\n};\n \nbool found;\nvector<int> ans, path;\n \nvoid dfs(int v, int p, vector<vector<int>> &g, int f){\n    path.push_back(v);\n    if(v == f){\n        ans = path;\n        found = true;\n        return;\n    }\n    for(int u: g[v]){\n        if(u != p) dfs(u, v, g, f);\n        if (found) return;\n    }\n    path.pop_back();\n}\n \nvoid solve(int tc){\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int>> sl(n);\n    vector<pair<int, pair<int, int>>> edges;\n    for(int i = 0; i < m; ++i){\n        int u, v, w;\n        cin >> u >> v >> w;\n        --u, --v;\n        edges.push_back({w, {u, v}});\n    }\n    sort(rall(edges));\n    dsu g(n);\n    pair<int, int> fin;\n    int best = INT_MAX;\n    for(auto e: edges){\n        if(!g.unite(e.y.x, e.y.y)){\n            fin = e.y;\n            best = e.x;\n        }\n        else{\n            sl[e.y.x].push_back(e.y.y);\n            sl[e.y.y].push_back(e.y.x);\n        }\n    }\n    found = false;\n    path.resize(0);\n    dfs(fin.x, -1, sl, fin.y);\n    cout << best <<  \" \" << ans.size() << \"\\n\";\n    for(int e: ans) cout << e + 1 << \" \";\n}\n \nbool multi = true;\n \nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "implementation",
      "sortings",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1927",
    "index": "G",
    "title": "Paint Charges",
    "statement": "A horizontal grid strip of $n$ cells is given. In the $i$-th cell, there is a paint charge of size $a_i$. This charge can be:\n\n- either used to the left — then all cells to the left at a distance less than $a_i$ (from $\\max(i - a_i + 1, 1)$ to $i$ inclusive) will be painted,\n- or used to the right — then all cells to the right at a distance less than $a_i$ (from $i$ to $\\min(i + a_i - 1, n)$ inclusive) will be painted,\n- or not used at all.\n\nNote that a charge can be used no more than once (that is, it \\textbf{cannot} be used simultaneously to the left and to the right). It is allowed for a cell to be painted more than once.\n\nWhat is the minimum number of times a charge needs to be used to paint all the cells of the strip?",
    "tutorial": "Let's use the method of dynamic programming. Let $dp[i][j][k]$ be the minimum number of operations required for the distance from $i$ to the farthest unpainted cell on the left to be $j$, and to the nearest unpainted cell on the right to be $k$ (including itself). We will update the values forward, that is, for all reachable states, we will find the states reachable from it and update the answer for them. In this case, we will move from the current $i$ to $i + 1$, recalculating $j$ and $k$ depending on the action: not spraying paint from $i$, spraying paint from $i$ to the left, spraying paint from $i$ to the right. The problem could also have been solved in $O(n^2)$, however, the constraints did not require this.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        forn(i, n)\n            cin >> a[i];\n \n        vector<vector<vector<int>>> d(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, INT_MAX)));\n        d[0][0][0] = 0;\n \n        forn(i, n)\n            forn(j, n)\n                forn(k, n + 1)\n                    if (d[i][j][k] < INT_MAX) {\n                        int ai = a[i];\n \n                        // Z\n                        {\n                            int ni = i + 1;\n                            int nj = j > 0 ? j + 1 : (k == 0 ? 1 : 0);\n                            int nk = max(0, k - 1);\n                            d[ni][nj][nk] = min(d[ni][nj][nk], d[i][j][k]);\n                        }\n \n                        // L\n                        {\n                            int ni = i + 1;\n                            int nj = j > 0 ? j + 1 : 0;\n                            if (nj <= ai)\n                                nj = 0;\n                            int nk = max(0, k - 1);\n                            d[ni][nj][nk] = min(d[ni][nj][nk], d[i][j][k] + 1);\n                        }\n \n                        // R\n                        {\n                            int ni = i + 1;\n                            int nj = j > 0 ? j + 1 : 0;\n                            int nk = max(ai - 1, k - 1);\n                            d[ni][nj][nk] = min(d[ni][nj][nk], d[i][j][k] + 1);\n                        }\n                    }\n \n        cout << *min_element(d[n][0].begin(), d[n][0].end()) << endl;\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1928",
    "index": "A",
    "title": "Rectangle Cutting",
    "statement": "Bob has a rectangle of size $a \\times b$. He tries to cut this rectangle into two rectangles with integer sides by making a cut parallel to one of the sides of the original rectangle. Then Bob tries to form some \\textbf{other} rectangle from the two resulting rectangles, and he can rotate and move these two rectangles as he wishes.\n\nNote that if two rectangles differ only by a $90^{\\circ}$ rotation, they are considered \\textbf{the same}. For example, the rectangles $6 \\times 4$ and $4 \\times 6$ are considered the same.\n\nThus, from the $2 \\times 6$ rectangle, another rectangle can be formed, because it can be cut into two $2 \\times 3$ rectangles, and then these two rectangles can be used to form the $4 \\times 3$ rectangle, which is different from the $2 \\times 6$ rectangle.\n\nHowever, from the $2 \\times 1$ rectangle, another rectangle cannot be formed, because it can only be cut into two rectangles of $1 \\times 1$, and from these, only the $1 \\times 2$ and $2 \\times 1$ rectangles can be formed, which are considered the same.\n\nHelp Bob determine if he can obtain some other rectangle, or if he is just wasting his time.",
    "tutorial": "Let $a \\le b$. Let's consider several cases: If $a$ is even, then we can cut the rectangle into two rectangles of size $\\frac{a}{2} \\times b$ and combine them into a rectangle of size $\\frac{a}{2} \\times 2b$, which is definitely different from $a \\times b$. If $a$ is even, then we can cut the rectangle into two rectangles of size $\\frac{a}{2} \\times b$ and combine them into a rectangle of size $\\frac{a}{2} \\times 2b$, which is definitely different from $a \\times b$. If $b$ is even and $b \\ne 2a$, then we can cut the rectangle into two rectangles of size $a \\times \\frac{b}{2}$ and combine them into a rectangle of size $2a \\times \\frac{b}{2}$. Note that here we use the fact that $b \\ne 2a$, because if $b = 2a$, then we will get the same rectangle of size $b \\times a$. If $b$ is even and $b \\ne 2a$, then we can cut the rectangle into two rectangles of size $a \\times \\frac{b}{2}$ and combine them into a rectangle of size $2a \\times \\frac{b}{2}$. Note that here we use the fact that $b \\ne 2a$, because if $b = 2a$, then we will get the same rectangle of size $b \\times a$. If $a$ and $b$ are both odd, or $b = 2a$ and $a$ is odd, then the rectangle is not interesting. It is easy to understand that if we cut the rectangle of size $a \\times b$ into two rectangles of size $a \\times c$ and $a \\times d$, where $c \\ne d$, then we can always only combine the original rectangle (similarly if we cut it into rectangles $c \\times b$ and $d \\times b$). And from here it follows that we must divide one of the sides of the rectangle in half, so at least one side must be even. If $a$ and $b$ are both odd, or $b = 2a$ and $a$ is odd, then the rectangle is not interesting. It is easy to understand that if we cut the rectangle of size $a \\times b$ into two rectangles of size $a \\times c$ and $a \\times d$, where $c \\ne d$, then we can always only combine the original rectangle (similarly if we cut it into rectangles $c \\times b$ and $d \\times b$). And from here it follows that we must divide one of the sides of the rectangle in half, so at least one side must be even.",
    "code": "#include <vector>\n#include <iostream>\n#include <numeric>\n#include <algorithm>\n#include <cassert>\n#include <map>\n\nusing namespace std;\n \nint main() {\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t    int a, b;\n\t    cin >> a >> b;\n\t    if (a > b) {\n\t        swap(a, b);\n\t    }\n\t    if (((a % 2 == 1) && (b % 2 == 1)) || ((a % 2 == 1) && (b == 2 * a))) {\n\t        cout << \"No\\n\";\n\t    } else {\n\t        cout << \"Yes\\n\";\n\t    }\n\t}\n\t\n\treturn 0;\n}\n",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1928",
    "index": "B",
    "title": "Equalize",
    "statement": "Vasya has two hobbies — adding permutations$^{\\dagger}$ to arrays and finding the most frequently occurring element. Recently, he found an array $a$ and decided to find out the maximum number of elements equal to the same number in the array $a$ that he can obtain after adding some permutation to the array $a$.\n\nMore formally, Vasya must choose exactly one permutation $p_1, p_2, p_3, \\ldots, p_n$ of length $n$, and then change the elements of the array $a$ according to the rule $a_i := a_i + p_i$. After that, Vasya counts how many times each number occurs in the array $a$ and takes the maximum of these values. You need to determine the maximum value he can obtain.\n\n$^{\\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Suppose we already know the permutation that needs to be added. Let's consider the elements that will become equal after the addition. Notice that among them there cannot be equal elements, because among the numbers we are adding, there are no duplicates. Thus, only a set of numbers among which there are no equal ones, and the difference between the maximum and minimum does not exceed $n - 1$, can become equal. It is easy to see that any set of numbers satisfying these conditions can be equalized, and any set of numbers that became equal after adding the permutation satisfies these constraints. So let's sort the array, remove the equal elements from it. After that, we can use two pointers to find the maximum length subarray where the difference between the maximum and minimum does not exceed $n - 1$. The answer will be the length of such a subarray. The complexity of the solution is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    sort(a.begin(), a.end());\n    a.resize(unique(a.begin(), a.end()) - a.begin());\n    int pnt = 0, ans = 0;\n    for (int i = 0; i < a.size(); i++) {\n        while(a[i] - a[pnt] >= n) {\n            pnt++;\n        }\n        ans = max(ans, i - pnt + 1);\n    }\n    cout << ans << endl;\n}\n\nsigned main() {\n    int t = 1;\n    cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1928",
    "index": "C",
    "title": "Physical Education Lesson",
    "statement": "In a well-known school, a physical education lesson took place. As usual, everyone was lined up and asked to settle in \"the first–$k$-th\" position.\n\nAs is known, settling in \"the first–$k$-th\" position occurs as follows: the first $k$ people have numbers $1, 2, 3, \\ldots, k$, the next $k - 2$ people have numbers $k - 1, k - 2, \\ldots, 2$, the next $k$ people have numbers $1, 2, 3, \\ldots, k$, and so on. Thus, the settling repeats every $2k - 2$ positions. Examples of settling are given in the \"Note\" section.\n\nThe boy Vasya constantly forgets everything. For example, he forgot the number $k$ described above. But he remembers the position he occupied in the line, as well as the number he received during the settling. Help Vasya understand how many natural numbers $k$ fit under the given constraints.\n\nNote that the settling exists if and only if $k > 1$. In particular, this means that the settling \\textbf{does not exist} for $k = 1$.",
    "tutorial": "All numbers repeat every $2k - 2$ positions. If the boy Vasya's number is calculated to be $x$, then it can be at positions of the form $(2k - 2) \\cdot t + x$, or $(2k - 2) \\cdot t + k + k - x$, for some non-negative $t$. This is true for all $x$, except for $x = 1$ and $x = k$ ~--- for these values, there is only one option left. Let's fix one of the options, the second one will be analogous. We need to find how many different values of $k$ satisfy the equation $(2k - 2) \\cdot t + x = n$, for some non-negative $t$. It is not difficult to see that this holds if and only if $n - x$ is divisible by $2k - 2$. Therefore, it is necessary to find the number of \\textbf{even} divisors of the number $n - x$. To consider the second case, it is necessary to proceed similarly with the number $n + x - 2$. The solution's complexity: $O(\\sqrt{n})$",
    "code": "#include <iostream>\n#include <unordered_set>\n\nusing namespace std;\n\nunordered_set<int> solve(int a) {\n    unordered_set<int> candidates;\n    for (int i = 1; i * i <= a; i++) {\n        if (a % i == 0) {\n            if (i % 2 == 0) // segment len should be even\n                candidates.insert(i);\n            if ((a / i) % 2 == 0)\n                candidates.insert(a / i);\n        }\n    }\n    unordered_set<int> answer;\n    for (int i : candidates) {\n        answer.insert(1 + i / 2);\n    }\n    return answer;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    for (int _ = 1; _ <= t; _++) {\n        int n, pos;\n        cin >> n >> pos;\n        unordered_set<int> candidates = solve(n - pos);  // bug2\n        for (int i : solve(n + pos - 2)) { // bug1\n            candidates.insert(i);\n        }\n        int answer = 0;\n        for (int i : candidates) {\n            if (i >= pos) {\n                answer++;\n            }\n        }\n        cout << answer << endl;\n    }\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1928",
    "index": "D",
    "title": "Lonely Mountain Dungeons",
    "statement": "Once, the people, elves, dwarves, and other inhabitants of Middle-earth gathered to reclaim the treasures stolen from them by Smaug. In the name of this great goal, they rallied around the powerful elf Timothy and began to plan the overthrow of the ruler of the Lonely Mountain.\n\nThe army of Middle-earth inhabitants will consist of several squads. It is known that each pair of creatures of \\textbf{the same race}, which are in different squads, adds $b$ units to the total strength of the army. But since it will be difficult for Timothy to lead an army consisting of a large number of squads, the total strength of an army consisting of $k$ squads is reduced by $(k - 1) \\cdot x$ units. Note that the army always consists \\textbf{of at least one squad}.\n\nIt is known that there are $n$ races in Middle-earth, and the number of creatures of the $i$-th race is equal to $c_i$. Help the inhabitants of Middle-earth determine the maximum strength of the army they can assemble.",
    "tutorial": "Let's learn how to solve the problem when $n = 1$. Suppose there is only one race and the number of its representatives is $c$. Notice that for a fixed $k$, it is advantageous for us to divide the representatives of the race almost evenly into squads. If $c$ is divisible by $k$, then it is advantageous for us to take exactly $y = \\frac{c}{k}$ beings in each squad. Then the total number of pairs of beings in different squads is equal to $\\frac{k(k-1)}{2} \\cdot y^2$ (there are a total of $\\frac{k(k-1)}{2}$ pairs of squads, and for each pair of squads there are $y^2$ pairs of beings from different squads). In the general case, when $c$ may not be divisible by $k$, let's denote $y = \\left\\lfloor \\frac{c}{k} \\right\\rfloor$ and $y' = \\left\\lceil \\frac{c}{k} \\right\\rceil$. Then it is advantageous for us to make squads of size $y$ and $y'$, where the number of squads of size $y'$ is equal to $c \\bmod k$ (we essentially make all squads of size $y$, and then add 1 to some squads from the remaining part). In this case, the total number of pairs of beings in different squads is equal to $C_{k - c \\bmod k}^2 \\cdot y^2 + C_{c \\bmod k}^2 \\cdot y'^2 + (k - c \\bmod k) \\cdot (c \\bmod k) \\cdot y \\cdot y'$. It remains to notice that it makes no sense to have $k > c$, so we can simply iterate through $k$ from $1$ to $c$ and choose the optimal one. When $n > 1$, we can notice that for a fixed $k$, we can solve the problem independently for each race. Let the number of representatives of the $i$-th race be $c_i$. Then we will iterate through $k$ from $1$ to $c_i$ for it and add the maximum total strength to the value of $cnt_k$ (the array $cnt$ is common for all races). Also, notice that for $k > c_i$, we will get the same total strength as for $k = c_i$. Then in the additional array $add$ (again, common for all races), we will add the maximum total strength for $k = c_i$ to $add_{c_i}$. We get the following solution: first, calculate the described arrays $cnt$ and $add$. After that, iterate through $k$ from $1$ to the maximum $c_i$. The maximum total strength of the squads for a fixed $k$ will be equal to $(cnt_k + (\\text{sum of values } add_i \\text{ for } i < k)) \\cdot b - (k - 1) \\cdot X$. From these values, we need to choose the maximum.",
    "code": "\n#include <iostream>\n#include <vector>\n\nusing namespace std;\nusing ll = long long;\n\nll pairs(ll n, ll k){\n    if (n == 0 || k == 0){\n        return 0;\n    }\n    ll x = n / k;\n    ll l = n % k;\n    ll r = k - l;\n    ll L = (x + 1) * l, R = x * r;\n    return R * L + (R - x) * R / 2 + L * (L - x - 1) / 2;\n}\n\nvoid solve(){\n    int m;\n    long long c, b;\n    cin >> m >> b >> c;\n\n    int n = 0;\n    vector<int> cnt(m);\n    for (int i = 0; i < m; ++i) {\n        cin >> cnt[i];\n        n = max(n, cnt[i]);\n    }\n\n\n    vector<long long> pair(n + 1);\n    vector<long long> add(n + 1);\n    for (int i = 0; i < m; ++i) {\n        for (int j = 1; j <= cnt[i]; ++j) {\n            pair[j] += pairs(cnt[i], j);\n        }\n        add[cnt[i]] += pairs(cnt[i], cnt[i]);\n    }\n\n\n    long long ans = 0;\n    long long other = 0;\n    for (int i = 1; i <= n; ++i) {\n        ans = max(ans, b * (pair[i] + other) - c * (i - 1));\n        other += add[i];\n    }\n    cout << ans << endl;\n}\n\nint main(){\n    int t;\n    cin >> t;\n    while (t--){\n        solve();\n    }\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "math",
      "ternary search"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1928",
    "index": "E",
    "title": "Modular Sequence",
    "statement": "You are given two integers $x$ and $y$. A sequence $a$ of length $n$ is called modular if $a_1=x$, and for all $1 < i \\le n$ the value of $a_{i}$ is either $a_{i-1} + y$ or $a_{i-1} \\bmod y$. Here $x \\bmod y$ denotes the remainder from dividing $x$ by $y$.\n\nDetermine if there exists a modular sequence of length $n$ with the sum of its elements equal to $S$, and if it exists, find any such sequence.",
    "tutorial": "Let's see what the answer will look like: first, there will be a prefix of the form $x, x + y, \\ldots, x + k\\cdot y$, and then there will be some number of blocks of the form $x \\bmod y, x \\bmod y + y, \\ldots, x \\bmod y + k \\cdot y$. We can subtract the number $x \\bmod y$ from all the elements of the sequence, and then divide all the elements by $y$ (all the elements will be divisible by $y$, since they initially had a remainder of $x \\bmod y$). Let $b_1 = \\frac{x - x \\bmod y}{y}$. Then our sequence will start with $b_1, b_1 + 1, \\ldots, b_1 + k_1$, and then there will be blocks of the form $0, 1, \\ldots, k_i$. Let's calculate these values: $dp_i$~--- the minimum length of a sequence of blocks of the form $0, 1, \\ldots, k_j$ with a sum of $i$. This value can be calculated for all numbers from $0$ to $s$ using dynamic programming. If we have processed all values from $0$ to $k-1$, then for $k$ we have calculated the minimum length, and we can update the value of $dp$ for $k + 1, k + 1 + 2, \\ldots$~--- a total of $O(\\sqrt{s})$ values not exceeding $s$. In this same $dp$, we can store through which values we were recalculated, for the restoration of the answer. Now, we can iterate over the length of the first block of the form $b_1, b_1 + 1, \\ldots, b_1 + k_1$. Then we know the sum of the remaining blocks, and using the precalculated $dp$, we can determine whether the desired sequence can be formed or not.",
    "code": "#include <cassert>\n#include <initializer_list>\n#include <numeric>\n#include <vector>\n#include <iostream>\n#include <utility>\n#include <stack>\n#include <queue>\n#include <set>\n#include <map>\n#include <algorithm>\n#include <math.h>\n\nusing namespace std;\n\n#define pii pair<int, int>\n#define mp make_pair\n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define ll long long\n#define pb emplace_back\n\nconst int INF = 1e9 + 10;\nconst ll INFLL = 1e18;\n\nvoid solve() {\n    int n, x, y, S;\n    cin >> n >> x >> y >> S;\n    vector<int> dp(S + 1, INF);\n    dp[0] = 0;\n    for (int k = 1; k <= S; k++) {\n        for (int l = 2; (l * (l - 1)) / 2 <= k; l++) {  // just 0 is never optimal\n            dp[k] = min(dp[k], dp[k - (l * (l - 1)) / 2] + l);\n        }\n        assert(dp[k] <= 2 * k);\n    }\n    for (ll k = 0; k < n; k++) {\n        ll prevSum = (k + 1) * x + (k * (k + 1)) / 2 * y;\n        if (prevSum > S) {\n            continue;\n        }\n        ll needSum = S - prevSum;\n        needSum -= (n - k - 1) * (x % y);\n        if (needSum < 0) {\n            continue;\n        }\n        if (needSum % y != 0) {\n            continue;\n        }\n        needSum /= y;\n        assert(needSum <= S);\n        if (dp[needSum] <= n - k - 1) {  // we found the answer\n            vector<int> a(n);\n            a[0] = x;\n            for (int i = 1; i <= k; i++) {  // construct prefix\n                a[i] = a[i - 1] + y;\n            }\n            for (int i = k + 1; i <= k + (n - k - 1) - dp[needSum];\n                 i++) {  // fill the rest like 0 0 0 ...\n                a[i] = x % y;\n            }\n            int i = k + (n - k - 1) - dp[needSum] + 1;  // first free index\n            vector<int> lens;                           // recover lengths of the segments\n            while (needSum != 0) {\n                for (int l = 2; (l * (l - 1)) / 2 <= needSum; l++) {\n                    if (dp[needSum] == dp[needSum - (l * (l - 1)) / 2] + l) {\n                        lens.pb(l);\n                        needSum -= (l * (l - 1)) / 2;\n                        break;\n                    }\n                }\n            }\n            for (auto &len : lens) {\n                for (int j = 0; j < len; j++) {\n                    a[i] = (x % y) + y * j;\n                    i++;\n                }\n            }\n            cout << \"YES\\n\";\n            for (auto &c : a) {\n                cout << c << \" \";\n            }\n            cout << \"\\n\";\n            return;\n        }\n    }\n    cout << \"NO\\n\";\n}\n\nint main() {\n    cin.tie(0);\n    cout.tie(0);\n    ios_base::sync_with_stdio(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "graphs",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1928",
    "index": "F",
    "title": "Digital Patterns",
    "statement": "Anya is engaged in needlework. Today she decided to knit a scarf from semi-transparent threads. Each thread is characterized by a single integer — the transparency coefficient.\n\nThe scarf is made according to the following scheme: horizontal threads with transparency coefficients $a_1, a_2, \\ldots, a_n$ and vertical threads with transparency coefficients $b_1, b_2, \\ldots, b_m$ are selected. Then they are interwoven as shown in the picture below, forming a piece of fabric of size $n \\times m$, consisting of exactly $nm$ nodes:\n\n\\begin{center}\n{\\small Example of a piece of fabric for $n = m = 4$.}\n\\end{center}\n\nAfter the interweaving tightens and there are no gaps between the threads, each node formed by a horizontal thread with number $i$ and a vertical thread with number $j$ will turn into a cell, which we will denote as $(i, j)$. Cell $(i, j)$ will have a transparency coefficient of $a_i + b_j$.\n\nThe interestingness of the resulting scarf will be the number of its sub-squares$^{\\dagger}$ in which there are no pairs of neighboring$^{\\dagger \\dagger}$ cells with the same transparency coefficients.\n\nAnya has not yet decided which threads to use for the scarf, so you will also be given $q$ queries to increase/decrease the coefficients for the threads on some ranges. After each query of which you need to output the interestingness of the resulting scarf.\n\n$^{\\dagger}$A sub-square of a piece of fabric is defined as the set of all its cells $(i, j)$, such that $x_0 \\le i \\le x_0 + d$ and $y_0 \\le j \\le y_0 + d$ for some integers $x_0$, $y_0$, and $d$ ($1 \\le x_0 \\le n - d$, $1 \\le y_0 \\le m - d$, $d \\ge 0$).\n\n$^{\\dagger \\dagger}$. Cells $(i_1, j_1)$ and $(i_2, j_2)$ are neighboring if and only if $|i_1 - i_2| + |j_1 - j_2| = 1$.",
    "tutorial": "Let's assume that $a_i = a_{i+1}$ for some $1 \\le i < n$, then for any $1 \\le j \\le m$, the cells $(i, j)$ and $(i+1, j)$ will have the same transparency. A similar statement can be made if there is an index $j$: $b_j = b_{j+1}$. Then the positions $a_i = a_{i+1}$ divide the array $a$ into \\textit{blocks}, in each of which all neighboring pairs are not equal to each other. It is clear that if there is a square $(x, y, d)$ consisting of cells $(i, j)$ such that $x \\le i < x+d$ and $y \\le j < y+d$, then the segment $[x, x+d-1]$ is entirely contained in one of these \\textit{blocks} of the array $a$. Similarly, the array $b$ can also be divided into blocks, and then the segment $[y, y+d-1]$ will also be entirely contained in one of the blocks. Let's try to solve the problem in $O(1)$ time, if there are no neighboring elements with the same values in the arrays $a$ and $b$ (also assuming that $n \\le m$): $f(n, m) = \\sum \\limits_{k=1}^{n} (n-k+1)(m-k+1) = \\sum_{k=1}^n \\left( k^2 + (m-n)k \\right) \\\\ f(n, m) = \\frac{n(n + 1)(2n + 1)}6 + (m - n) \\cdot \\frac{n(n+1)}2 \\\\$ This formula can be further transformed by introducing a quadruple of numbers for each natural number $n$: $a_n = 1$, $b_n = n$, $c_n = \\frac12 n(n+1)$, $d_n = \\frac16 n(n+1)(2n+1) - \\frac12n^2(n+1)$. Then $f(n, m) = d_n a_m + c_n b_m$, if $n \\le m$ and $f(n, m) = a_n d_m + b_n c_m$, if $n > m$. But if there are neighboring identical elements in the arrays $a$ and $b$, then this means that they are somehow divided into blocks. If these are blocks of lengths $n_1, \\ldots, n_k$ in the array $a$ and blocks of lengths $m_1, \\ldots, m_l$ in the array $b$, then the answer to the problem is $\\textrm{ans} = \\sum_{i=1}^k \\sum_{j=1}^l f(n_i, m_j)$ Let's learn how to quickly calculate sums of the form $f(x, m_1) + \\ldots + f(x, m_l)$. To do this, we will create 4 segment trees to quickly calculate the sums $\\sum a_y$, $\\sum b_y$, $\\sum c_y$, $\\sum d_y$ over segments of $y$, taking into account the multiplicity of $y$ in the array $m_1, \\ldots, m_l$. Now the calculation of $f(x, m_1) + \\ldots + f(x, m_k)$ is reduced to $4$ segment tree queries: $f(x, m_1) + \\ldots + f(x, m_l) = a_x \\cdot \\sum_{m_i < x} d_{m_i} + b_x \\cdot \\sum_{m_i < x} c_{m_i} + c_x \\cdot \\sum_{m_i \\ge x} b_{m_i} + d_x \\cdot \\sum_{m_i \\ge x} a_{m_i}$ The sum $f(n_1, y) + \\ldots + f(n_k, y)$ is calculated similarly. Now we just need to put our solution together. We will maintain the blocks of arrays $a$ and $b$ in an online mode. It is very convenient to do this by storing the positions $a_i = a_{i+1}$ in a data structure like std::set, and also by working with the differential array $a$ (i.e., maintaining not the array $a$ itself, but the array of differences between neighboring elements $c_i = a_{i+1} - a_i$). To recalculate the answer, we will count the number of squares that are involved in a specific block of the array $a$ or $b$, using the above result. As a result, we have a solution in $O((n+q) (\\log n + \\log m))$. P.S. A solution in $O(q \\sqrt n)$ will not work due to a large constant. I tried very hard to rule it out :D.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\nusing pi = pair<int, int>;\n\nstruct SegmentTree {\n    int n;\n    vector<ll> t;\n\n    SegmentTree(int n) : n(n), t(2*n) { }\n\n    void Add(int i, ll x) {\n        for (i += n; i != 0; i >>= 1) t[i] += x;\n    }\n\n    ll Query(int l, int r) {\n        ll ans = 0;\n\n        for (l += n, r += n - 1; l <= r; l >>= 1, r >>= 1) {\n            if ((l&1) == 1) ans += t[l++];\n            if ((r&1) == 0) ans += t[r--];\n        }\n        return ans;\n    }\n};\n\nstruct SegmentContainer {\n    int side;\n    SegmentTree sgt_a, sgt_b, sgt_c, sgt_d;\n    int id;\n    // sgt_a: sum(1)\n    // sgt_b: sum(m)\n    // sgt_c: sum(m*(m+1)/2)\n    // sgt_d: sum(m*(m-1)*(2*m-1)/6 - m*(m-1)/2*m)\n\n    SegmentContainer(int side) : side(side), sgt_a(side), sgt_b(side), sgt_c(side), sgt_d(side) {\n    }\n\n    tuple<ll, ll, ll, ll> GetABCD(ll m) {\n        return make_tuple(1, m, m*(m+1)/2, m*(m-1)*(2*m-1)/6 - m*(m-1)/2*m);\n    }\n\n    void Insert(int m) {\n        auto [a, b, c, d] = GetABCD(m);\n        sgt_a.Add(m-1, +a);\n        sgt_b.Add(m-1, +b);\n        sgt_c.Add(m-1, +c);\n        sgt_d.Add(m-1, +d);\n    }\n\n    void Erase(int m) {\n        auto [a, b, c, d] = GetABCD(m);\n        sgt_a.Add(m-1, -a);\n        sgt_b.Add(m-1, -b);\n        sgt_c.Add(m-1, -c);\n        sgt_d.Add(m-1, -d);\n    }\n\n    ll SquaresCount(int n) {\n        const int mid = min(side, n);\n        auto sum_a = sgt_a.Query(mid, side); // m > n\n        auto sum_b = sgt_b.Query(mid, side); // m > n\n        auto sum_c = sgt_c.Query(0, mid); // m <= n\n        auto sum_d = sgt_d.Query(0, mid); // m <= n\n        auto [a, b, c, d] = GetABCD(n);\n\n        return d * sum_a + c * sum_b + b * sum_c + a * sum_d;\n    }\n};\n\nstruct SegmentMaintainer {\n    SegmentContainer& my;\n    SegmentContainer& other;\n    ll& ans;\n\n    set<int> pos_zero;\n    vector<ll> diff_array;\n\n    SegmentMaintainer(vector<int> a, \n                      SegmentContainer& my,\n                      SegmentContainer& other,\n                      ll& ans) :\n            pos_zero(), diff_array(a.size()), my(my), other(other), ans(ans) {\n        pos_zero.insert(0);\n        for (int i = 1; i < a.size(); ++i) {\n            diff_array[i] = a[i] - a[i-1];\n            if (diff_array[i] == 0) pos_zero.insert(i);\n        }\n        pos_zero.insert(a.size());\n\n        for (auto it = pos_zero.begin(); *it != my.side; ++it) {\n            OnSegmentAppear(*next(it) - *it);\n        }\n    }\n\n    void OnSegmentAppear(int len) {\n        my.Insert(len);\n        ans += other.SquaresCount(len);\n    }\n\n    void OnSegmentDissapear(int len) {\n        my.Erase(len);\n        ans -= other.SquaresCount(len);\n    }\n\n    void ChangeBound(int pos, ll dx) {\n        if (pos == 0 || pos == my.side) return; \n            \n        bool was_zero = diff_array[pos] == 0;\n        diff_array[pos] += dx;\n        bool now_zero = diff_array[pos] == 0;\n\n        if (was_zero && !now_zero) {\n            auto mid = pos_zero.find(pos);\n            auto prv = prev(mid), nxt = next(mid);\n            \n            OnSegmentDissapear(*mid - *prv);\n            OnSegmentDissapear(*nxt - *mid);\n            OnSegmentAppear(*nxt - *prv);\n\n            pos_zero.erase(mid);\n        }\n        \n        if (!was_zero && now_zero) {\n            auto mid = pos_zero.insert(pos).first;\n            auto prv = prev(mid), nxt = next(mid);\n\n            OnSegmentAppear(*mid - *prv);\n            OnSegmentAppear(*nxt - *mid);\n            OnSegmentDissapear(*nxt - *prv);\n        }\n    }\n\n    void RangeAdd(int l, int r, int x) {\n        ChangeBound(l, +x);\n        ChangeBound(r, -x);\n    }\n};\n\nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int n, m, q; cin >> n >> m >> q;\n\n    vector<int> a(n), b(m);\n    for (int& x : a) cin >> x;\n    for (int& x : b) cin >> x;\n\n    ll ans = 0;\n    SegmentContainer a_segments(n), b_segments(m);\n\n    a_segments.id = 1;\n    b_segments.id = 2;\n\n    SegmentMaintainer a_maintainer(a, a_segments, b_segments, ans); \n    SegmentMaintainer b_maintainer(b, b_segments, a_segments, ans);\n    \n    cout << ans << '\\n';\n    while (q--) {\n        int t, l, r, x; cin >> t >> l >> r >> x; --l;\n        if (t == 1) a_maintainer.RangeAdd(l, r, x);\n        if (t == 2) b_maintainer.RangeAdd(l, r, x);\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1929",
    "index": "A",
    "title": "Sasha and the Beautiful Array",
    "statement": "Sasha decided to give his girlfriend an array $a_1, a_2, \\ldots, a_n$. He found out that his girlfriend evaluates the beauty of the array as the sum of the values $(a_i - a_{i - 1})$ for all integers $i$ from $2$ to $n$.\n\nHelp Sasha and tell him the maximum beauty of the array $a$ that he can obtain, if he can rearrange its elements in any way.",
    "tutorial": "$a_2 - a_1 + a_3 - a_2 + \\ldots + a_n - a_{n - 1} = a_n - a_1$. So we just need to maximize this value, which means the answer is the maximum number in the array minus the minimum.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1929",
    "index": "B",
    "title": "Sasha and the Drawing",
    "statement": "Even in kindergarten, Sasha liked a girl. Therefore, he wanted to give her a drawing and attract her attention.\n\nAs a drawing, he decided to draw a square grid of size $n \\times n$, in which some cells are colored. But coloring the cells is difficult, so he wants to color as few cells as possible. But at the same time, he wants \\textbf{at least} $k$ diagonals to have at least one colored cell. Note that the square grid of size $n \\times n$ has a total of $4n - 2$ diagonals.\n\nHelp little Sasha to make the girl fall in love with him and tell him the minimum number of cells he needs to color.",
    "tutorial": "Let's notice that each cell intersects with no more than two diagonals, so the answer to the problem is at least $\\frac{k + 1}{2}$. Claim: Let's look at the construction where we color all cells in the first row and leave only two side cells uncolored in the last row. Then each of these cells corresponds to exactly two diagonals. And if $k \\leq (2n - 2) * 2$, then the answer is exactly $\\frac{k + 1}{2}$. Now let's notice that if we color $2n - 1$ or $2n$ cells, then one or two cells will correspond to exactly one diagonal respectively, because in this case we must color the side cells, as they are the only diagonals not touched, but they are already covered by another diagonal corresponding to another corner cell. Therefore, the answer in case of $4n - 3$ remains the same due to parity, and for $4n - 2$ it is $\\frac{k}{2} + 1$. ",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1929",
    "index": "C",
    "title": "Sasha and the Casino",
    "statement": "Sasha decided to give his girlfriend the best handbag, but unfortunately for Sasha, it is very expensive. Therefore, Sasha wants to earn it. After looking at earning tips on the internet, he decided to go to the casino.\n\nSasha knows that the casino operates under the following rules. If Sasha places a bet of $y$ coins (where $y$ is a positive integer), then in case of winning, he will receive $y \\cdot k$ coins (i.e., his number of coins will increase by $y \\cdot (k - 1)$). And in case of losing, he will lose the entire bet amount (i.e., his number of coins will decrease by $y$).\n\nNote that the bet amount must always be a positive ($> 0$) integer and cannot exceed Sasha's current number of coins.\n\nSasha also knows that there is a promotion at the casino: he cannot lose more than $x$ times in a row.\n\nInitially, Sasha has $a$ coins. He wonders whether he can place bets such that he is guaranteed to win any number of coins. In other words, is it true that for any integer $n$, Sasha can make bets so that for any outcome that does not contradict the rules described above, at some moment of time he will have at least $n$ coins.",
    "tutorial": "Let's notice that the condition that we can achieve arbitrarily large values means that we need to guarantee at least a $+1$ to our coins. At the very first win. In this case, we can repeat this strategy indefinitely. Also, let's notice that if we have lost a total of $z$ before, then in the next round we need to bet $y$ such that $y \\cdot (k - 1) > z$, because otherwise the casino can give us a win. In this case, the condition of not losing more than $x$ times in a row will disappear, and we will end up in the negative. Therefore, the tactic is not optimal. Therefore, the solution is as follows: we bet $1$ at first, then we bet the minimum number such that the win covers our loss. And if we have enough to make such a bet for $x + 1$, then the casino must end up in the negative, otherwise we cannot win. So the solution is in $O(x)$ time complexity, where we simply calculate these values in a loop.",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "games",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1929",
    "index": "D",
    "title": "Sasha and a Walk in the City",
    "statement": "Sasha wants to take a walk with his girlfriend in the city. The city consists of $n$ intersections, numbered from $1$ to $n$. Some of them are connected by roads, and from any intersection, there is exactly one simple path$^{\\dagger}$ to any other intersection. In other words, the intersections and the roads between them form a tree.\n\nSome of the intersections are considered dangerous. Since it is unsafe to walk alone in the city, Sasha does not want to visit three or more dangerous intersections during the walk.\n\nSasha calls a set of intersections good if the following condition is satisfied:\n\n- If in the city only the intersections contained in this set are dangerous, then any simple path in the city contains \\textbf{no more than two} dangerous intersections.\n\nHowever, Sasha does not know which intersections are dangerous, so he is interested in the number of different good sets of intersections in the city. Since this number can be very large, output it modulo $998\\,244\\,353$.\n\n$^{\\dagger}$A simple path is a path that passes through each intersection at most once.",
    "tutorial": "Let $dpv$ be the number of non-empty sets of vertices in the subtree rooted at $v$ such that there are no pairs of vertices in the set where one vertex is the ancestor of the other. Then $dpv = (dp_{u_1} + 1) \\cdot (dp_{u_2} + 1) \\cdot \\ldots \\cdot (dp_{u_k} + 1)$, where $u_1, \\ldots, u_k$ are the children of vertex $v$. This is because from each subtree, you can choose either any non-empty set or an empty set. Choosing an empty set from each subtree implies that only the single vertex $v$ is selected (since our dynamic programming state cannot be empty). Now the claim is: the answer to the problem is $dp_1 + dp_2 + \\ldots + dp_n + 1$. This is because if we consider the case where there is a pair of vertices where vertex $v$ is the ancestor of the other, the answer in this case is $dp{u_1} + \\ldots + dp{u_k}$, as we can select such a set of vertices exactly from one subtree from the dynamic programming states. (And here we are using non-empty sets in the dynamic state, since otherwise, the case where there are no vertices where one is the ancestor of the other would be counted). And $dp_1 + 1$ (where $1$ is the root of the tree) accounts for the scenarios where there is no vertex where one is the ancestor of the other.",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1929",
    "index": "E",
    "title": "Sasha and the Happy Tree Cutting",
    "statement": "Sasha was given a tree$^{\\dagger}$ with $n$ vertices as a prize for winning yet another competition. However, upon returning home after celebrating his victory, he noticed that some parts of the tree were missing. Sasha remembers that he colored some of the edges of this tree. He is certain that for any of the $k$ pairs of vertices $(a_1, b_1), \\ldots, (a_k, b_k)$, he colored at least one edge on the simple path$^{\\ddagger}$ between vertices $a_i$ and $b_i$.\n\nSasha does not remember how many edges he exactly colored, so he asks you to tell him the minimum number of edges he could have colored to satisfy the above condition.\n\n$^{\\dagger}$A tree is an undirected connected graph without cycles.\n\n$^{\\ddagger}$A simple path is a path that passes through each vertex at most once.",
    "tutorial": "Let's consider each edge $i$ and mark the set of pairs $S_i$ that it covers. Then the claim is: we have a total of $O(k)$ different sets. This is because we are only interested in the edges that are present in the compressed tree on these $k$ pairs of vertices. And as it is known, the number of edges in the compressed tree is $O(k)$. Then we need to find the minimum number of sets among these sets such that each pair is present in at least one of them. This can be achieved by dynamic programming on sets as follows: Let $dp[mask]$ be the minimum number of edges that need to be removed in order for at least one edge to be removed among the pairs corresponding to the individual set bits in $mask$. Then the update is as follows: $dp[mask | S_i] = \\min(dp[mask | S_i], dp[mask] + 1)$ for all distinct sets $S$, where $S_i$ is the mask corresponding to the pairs passing through the edge. This update is performed because we are adding one more edge to this mask. As a result, we obtain a solution with a time complexity of $O(nk + 2^k k)$, where $O(nk)$ is for precomputing the set of pairs removed by each edge for each edge, and $O(2^k k)$ is for updating the dynamic programming.",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1929",
    "index": "F",
    "title": "Sasha and the Wedding Binary Search Tree",
    "statement": "Having overcome all the difficulties and hardships, Sasha finally decided to marry his girlfriend. To do this, he needs to give her an engagement ring. However, his girlfriend does not like such romantic gestures, but she does like binary search trees$^{\\dagger}$. So Sasha decided to give her such a tree.\n\nAfter spending a lot of time on wedding websites for programmers, he found the perfect binary search tree with the root at vertex $1$. In this tree, the value at vertex $v$ is equal to $val_v$.\n\nBut after some time, he forgot the values in some vertices. Trying to remember the found tree, Sasha wondered — how many binary search trees could he have found on the website, if it is known that the values in all vertices are integers in the segment $[1, C]$. Since this number can be very large, output it modulo $998\\,244\\,353$.\n\n$^{\\dagger}$A binary search tree is a rooted binary tree in which for any vertex $x$, the following property holds: the values of all vertices in the left subtree of vertex $x$ (if it exists) are less than or equal to the value at vertex $x$, and the values of all vertices in the right subtree of vertex $x$ (if it exists) are greater than or equal to the value at vertex $x$.",
    "tutorial": "Let's list the numbers of vertices in the order of their values. Let it be $v1, \\ldots, vn$. Then it must satisfy $value{vi} \\leq value{v{i + 1}}$. Then we have some segments in this order for which we do not know the values. For each segment, we know the maximum and minimum value that the values in this segment can take, let's say $L$ and $R$. Then we need to choose a value from the interval $(L, R)$ for each number in this segment in order to maintain the relative order. This is a known problem, and there are $\\binom{R - L + len}{len}$ possible ways to do this, where $len$ is the length of the segment. Then we need to multiply all these binomial coefficients. Now, notice that $R - L + len$ is large, so for calculation we can simply use the formula $\\binom{n}{k} = \\frac{n \\cdot (n - 1) \\cdot \\ldots \\cdot (n - k + 1)}{k!}$, since the sum $len$ does not exceed $n$.",
    "tags": [
      "brute force",
      "combinatorics",
      "data structures",
      "dfs and similar",
      "math",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1930",
    "index": "A",
    "title": "Maximise The Score",
    "statement": "There are $2n$ positive integers written on a whiteboard. Being bored, you decided to play a one-player game with the numbers on the whiteboard.\n\nYou start with a score of $0$. You will increase your score by performing the following move \\textbf{exactly} $n$ times:\n\n- Choose two integers $x$ and $y$ that are written on the whiteboard.\n- Add $\\min(x,y)$ to your score.\n- Erase $x$ and $y$ from the whiteboard.\n\nNote that after performing the move $n$ times, there will be no more integers written on the whiteboard.\n\nFind the maximum final score you can achieve if you optimally perform the $n$ moves.",
    "tutorial": "Selecting the smallest two elements on the whiteboard is a good choice in the first move. Let $b$ denote the sorted array $a$. Assume that $b$ contains only distinct elements for convenience. We prove by induction on $n$ that the maximum final score is $b_1 + b_3 + \\ldots + b_{2n-1}$. For the base case $n = 1$, the final and only possible score that can be achieved is $b_1$. Now let $n > 1$. Claim: It is optimal to choose $b_{1}$ with $b_{2}$ for some move. Suppose that in some move, $b_{1}$ is choosen with $b_i$ and $b_{2}$ is choosen with $b_j$, for some $2 < i,j < 2n, i \\not = j$. The contribution to the score according to these choices is $\\min(b_{1}, b_{i}) + \\min(b_{2}, b_{j}) = b_{1} + b_{2}$. However, if we had chosen $b_{1}$ and $b_{2}$ in one move, and $b_i$ and $b_j$ in the other move, the score according to these choices is $\\min(b_{1}, b_{2}) + \\min(b_{i}, b_{j}) = b_{1} + \\min(b_{i}, b_{j})$. As $i, j > 2$, $b_i > b_{2}$ and $b_j > b_{2} \\implies \\min(b_{i}, b_{j}) > b_2$. Thus, we can achieve a strictly larger score by choosing $b_1$ with $b_2$ in some move. The choice of selecting $b_1$ and $b_2$ contributes a value of $b_1$ to the score. The maximum score that can achieved for the remaining numbers $[b_3, b_4, \\ldots, b_{2n}]$ on the whiteboard in the remaining moves is $b_3 + b_5 + b_7 + \\ldots b_{2n-1}$ by the induction hypothesis. Note that we can extend the arguments for the case where $a$ has duplicate elements.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nvoid solve(){ \n    ll n; cin>>n;\n    vector<ll> a(2*n);\n    ll ans=0;\n    for(auto &it:a){\n        cin>>it;\n    }\n    sort(a.begin(),a.end());\n    for(ll i=0;i<2*n;i+=2){\n        ans+=a[i];\n    }\n    cout<<ans<<\"\\n\";\n    return;  \n}                                       \nint main()                                                                               \n{       \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);                               \n    #ifndef ONLINE_JUDGE                   \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif     \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1930",
    "index": "B",
    "title": "Permutation Printing",
    "statement": "You are given a positive integer $n$.\n\nFind a permutation$^\\dagger$ $p$ of length $n$ such that there do \\textbf{not} exist two \\textbf{distinct} indices $i$ and $j$ ($1 \\leq i, j < n$; $i \\neq j$) such that $p_i$ divides $p_j$ and $p_{i+1}$ divides $p_{j+1}$.\n\nRefer to the Notes section for some examples.\n\nUnder the constraints of this problem, it can be proven that at least one $p$ exists.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "For integers $x$ ($\\lfloor \\frac{n}{2} \\rfloor < x \\leq n$), there does not exist integer $y$ ($y > x$) such that $y$ is divisible by $x$. Consider the permutation $p$ such that $p=[1, n, 2, n - 1, \\ldots \\lceil \\frac{n+1}{2} \\rceil]$. It is valid. Why? We have $\\max(p_a, p_{a+1}) > \\lfloor \\frac{n}{2} \\rfloor$ for all $1 \\leq a < n - 1$. So we cannot ever have a pair of integers ($a,b$) such that: $1 \\leq a < n - 1$ $1 \\leq b < n$ $a \\neq b$ $p_a$ divides $p_b$ and $p_{a+1}$ divides $p_{b+1}$ Now, we just need to check for $a = n - 1$. First of all, notice that $p_a$ does not divide $p_1$. There does not exist an integer $b$ ($2 \\leq b < n - 1$) such that $p_{a+1}$ divides $p_{b+1}$ as $2 \\cdot p_{a+1} \\ge n$ and $p_{c+1} < n$ for all $c$ ($2 \\leq c < n - 1$). Note that we covered all possible pairs of indices and did not find two distinct indices $i$ and $j$ ($1 \\leq i, j < n$; $i \\neq j$) such that $p_i$ divides $p_j$ and $p_{i+1}$ divides $p_{j+1}$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nvoid solve(){ \n    ll n; cin>>n;\n    ll l=1,r=n;\n    for(ll i=1;i<=n;i++){\n        if(i&1){\n            cout<<l<<\" \";\n            l++;\n        }\n        else{\n            cout<<r<<\" \";\n            r--;\n        }\n    }\n    cout<<\"\\n\";\n    return;  \n}                                       \nint main()                                                                               \n{       \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);                               \n    #ifndef ONLINE_JUDGE                   \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif     \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1930",
    "index": "C",
    "title": "Lexicographically Largest",
    "statement": "Stack has an array $a$ of length $n$. He also has an empty set $S$. Note that $S$ is \\textbf{not} a multiset.\n\nHe will do the following three-step operation exactly $n$ times:\n\n- Select an index $i$ such that $1 \\leq i \\leq |a|$.\n- Insert$^\\dagger$ $a_i + i$ into $S$.\n- Delete $a_i$ from $a$. Note that the indices of all elements to the right of $a_i$ will decrease by $1$.\n\nNote that after $n$ operations, $a$ will be empty.\n\nStack will now construct a new array $b$ which is $S$ \\textbf{sorted in decreasing order}. Formally, $b$ is an array of size $|S|$ where $b_i$ is the $i$-th largest element of $S$ for all $1 \\leq i \\leq |S|$.\n\nFind the lexicographically largest$^\\ddagger$ $b$ that Stack can make.\n\n$^\\dagger$ A set can only contain unique elements. \\textbf{Inserting an element that is already present in a set will not change the elements of the set.}\n\n$^\\ddagger$ An array $p$ is lexicographically larger than a sequence $q$ if and only if one of the following holds:\n\n- $q$ is a prefix of $p$, but $p \\ne q$; or\n- in the first position where $p$ and $q$ differ, the array $p$ has a larger element than the corresponding element in $q$.\n\nNote that $[3,1,4,1,5]$ is lexicographically larger than $[3,1,3]$, $[\\,]$, and $[3,1,4,1]$ but not $[3,1,4,1,5,9]$, $[3,1,4,1,5]$, and $[4]$.",
    "tutorial": "and satyam343 Consider an array $c$ of length $n$ such that $c_i :=$ number of indices smaller than $i$ which were chosen before index $i$. So set $S$ will be a collection of $a_i + i - c_i$ over all $1 \\leq i \\leq n$. Now one might wonder what type of arrays $c$ is it possible to get. First, it is easy to see that we should have $0 \\leq c_i < i$ for all $i$. Call an array $c$ of length $n$ good, if $0 \\leq c_i < i$ for all $1 \\leq i \\leq n$. The claim is that all good arrays of length $n$ can be obtained. We can prove it by induction on $n$. $c_1 = 0$ always holds. Now $c_2$ can either be $0$ or $1$. We can obtain $c_2 = 0$ by deleting the element at index $2$ before the element at index $1$. We can also obtain $c_2 = 1$ by deleting it after deleting the element at index $1$. Thus, all good arrays of length 2 can be obtained. Now assume that it is possible to obtain all good arrays of length atmost $k$. Choose an integer $x$ ($0 \\leq x \\leq k$) arbitrarily. Consider the following sequence for the order of deletion: The elements at indices $1, 2, \\ldots, x$ in the same order. The element at index $k$. The elements at indices $x + 1, \\ldots, k - 1$ in the same order. It is easy to see that the array obtained on performing the above sequence of operations is a good array of length $k + 1$ with $c_{k+1} = x$. Hence we can establish a bijection between the sequence of order of deletion and the number of good arrays. So we have the following subproblem. We have a set $S$. We will iterate $i$ from $1$ to $n$, select an integer $c_i$ ($0 \\leq c_i \\leq i - 1$) and insert $a_i + i - c_i$ into set $S$ and move to $i + 1$. Now using exchange arguments, we can prove that it is never bad if we select the smallest integer $v$ ($0 \\leq v \\leq i - 1$) such that $a_i + i - v$ is not present in the set $S$, and assign it to $c_i$. Note that as we have $i$ options for $v$, and we would have inserted exactly $i-1$ elements before index $i$, there always exists an integer $v$ ($0 \\leq v \\leq i - 1$) such that $a_i + i - v$ is not present in the set $S$. You can refer to the attached submission to see how to find $v$ efficiently for each $i$.",
    "code": "#include <bits/stdc++.h>     \nusing namespace std;\n#define ll long long\nvoid solve(){ \n    ll n; cin>>n;\n    set<ll> used,not_used;\n    vector<ll> ans;\n    for(ll i=1;i<=n;i++){\n        ll x; cin>>x; x+=i;\n        if(!used.count(x)){\n            not_used.insert(x);\n        }\n        ll cur=*(--not_used.upper_bound(x)); //find the largest element(<= x) which is not in set \"used\"\n        not_used.erase(cur);\n        ans.push_back(cur);\n        used.insert(cur);\n        if(!used.count(cur-1)){\n            not_used.insert(cur-1);\n        }\n    }\n    sort(ans.begin(), ans.end());\n    reverse(ans.begin(), ans.end());\n    for(auto i:ans){\n        cout<<i<<\" \";\n    }  \n    cout<<\"\\n\";\n    return;  \n}                                       \nint main()                                                                               \n{       \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);                               \n    #ifndef ONLINE_JUDGE                   \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif     \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1930",
    "index": "D1",
    "title": "Sum over all Substrings (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $t$ and $n$. You can make hacks only if both versions of the problem are solved.}\n\nFor a binary$^\\dagger$ pattern $p$ and a binary string $q$, both of length $m$, $q$ is called $p$-good if for every $i$ ($1 \\leq i \\leq m$), there exist indices $l$ and $r$ such that:\n\n- $1 \\leq l \\leq i \\leq r \\leq m$, and\n- $p_i$ is a mode$^\\ddagger$ of the string $q_l q_{l+1} \\ldots q_{r}$.\n\nFor a pattern $p$, let $f(p)$ be the minimum possible number of $\\mathtt{1}$s in a $p$-good binary string (of the same length as the pattern).\n\nYou are given a binary string $s$ of size $n$. Find $$\\sum_{i=1}^{n} \\sum_{j=i}^{n} f(s_i s_{i+1} \\ldots s_j).$$ In other words, you need to sum the values of $f$ over all $\\frac{n(n+1)}{2}$ substrings of $s$.\n\n$^\\dagger$ A binary pattern is a string that only consists of characters $\\mathtt{0}$ and $\\mathtt{1}$.\n\n$^\\ddagger$ Character $c$ is a mode of string $t$ of length $m$ if the number of occurrences of $c$ in $t$ is at least $\\lceil \\frac{m}{2} \\rceil$. For example, $\\mathtt{0}$ is a mode of $\\mathtt{010}$, $\\mathtt{1}$ is not a mode of $\\mathtt{010}$, and both $\\mathtt{0}$ and $\\mathtt{1}$ are modes of $\\mathtt{011010}$.",
    "tutorial": "To find $f(s)$, we can partition $s$ into multiple independent substrings of length atmost $3$ and find best answer for them separately. There always exists a string $g$ such that: $g$ is $s-good$ there are $f(s)$ number of $\\mathtt{1}$s in $g$ $g$ is of the form $b_1 + b_2 + \\ldots b_q$, where $b_i$ is either equal to $\\mathtt{0}$ or $\\mathtt{010}$. First of all, append $n$ $\\mathtt{0}$ s to the back of $s$ for our convenience. Note that this does not change the answer. Now let us call a binary string $p$ of size $d$ nice if: there exists a positive integer $k$ such that $d = 3k$ there exists a positive integer $k$ such that $d = 3k$ $p$ is of form $f(\\mathtt{0} , k) + f(\\mathtt{1} , k) + f(\\mathtt{0} , k)$, where $f(c, z)$ gives a string containing exactly $z$ characters equal to $c$. $p$ is of form $f(\\mathtt{0} , k) + f(\\mathtt{1} , k) + f(\\mathtt{0} , k)$, where $f(c, z)$ gives a string containing exactly $z$ characters equal to $c$. Suppose binary string $t$ is one of the $s-good$ strings such that there are exactly $f(s)$ $\\mathtt{1}$ s in $t$. We claim that for any valid $t$, there always exists a binary string $t'$ such that: $t'$ is permutation of $t$ $t'$ is $s-good$ $t'$ is of the form $f(\\mathtt{0}, d_1) + z_1 + f(\\mathtt{0}, d_2) + z_2 + f(\\mathtt{0}, d_3) + \\ldots + z_g + f(\\mathtt{0}, d_{g+1})$, where $z_1, z_2, \\ldots z_g$ are nice binary strings and $d_1, d_2, \\ldots d_{g+1}$ are non-negative integers. Initially, all the $\\mathtt{1}$s in $s$ are unmarked. We will mark all of them and modify the string $t$ in the process. We will do the following recursive process unless all the $\\mathtt{1}$ s in $s$ are marked. Find the index of leftmost unmarked $\\mathtt{1}$ in $s$. Suppose its index is $x$. Now suppose $y$ is the largest index such that there are an equal number of $\\mathtt{0}$ s and $\\mathtt{1}$ s in substring $t[x, y]$. Note that $y$ will always exist as we appended some extra $\\mathtt{0}$s in the starting. Now we can rearrange the characters in substring $t[x,y]$, as they will still contain an equal number of $\\mathtt{0}$ s and $\\mathtt{1}$ s and $\\mathtt{1}$ will still be the mode of substring $t[x,y]$. Obviously rearranging the characters in $t[x,y]$ to $\\mathtt{0} \\ldots \\mathtt{0} \\mathtt{1} \\ldots \\mathtt{1}$ is the best we can do. We will mark all the $\\mathtt{1}$ s in substring $s[x,y]$. Suppose $y-x+1 = 2v$. Now $t[y+1,y+v]$ might contain some $\\mathtt{1}$ s. Say there are $z$ $\\mathtt{1}$ s in $t[y+1,y+v]$ initially. We will do the following operation exactly $z$ times. Find the leftmost $\\mathtt{1}$ in substring $t[y+1,y+v]$. Find the leftmost $\\mathtt{0}$ in substring $t[y+v+1,2n]$. Swap both characters. Now note that $t[x,x+3v-1]$ will be of form $f(\\mathtt{0}, v) + f(\\mathtt{1}, v) + f(\\mathtt{0}, v)$. It is easy to verify that in the updated $t$, there won't be any index $i$ for which there does not exist two indices $1 \\le l \\le i \\le r \\le 2n$ such that $s_i$ is mode of $t[l,r]$. Now we can mark all the $\\mathtt{1}$ s in substring $s[x+2v,x+3v-1]$ too, as $t[x+v,x+3v-1]$ contain equal number of $\\mathtt{0}$ s and $\\mathtt{1}$ s. It is not hard to conclude that the updated $t$ will be of form $f(\\mathtt{0}, d_1) + z_1 + f(\\mathtt{0}, d_2) + z_2 + f(\\mathtt{0}, d_3) + \\ldots + z_g + f(\\mathtt{0}, d_{g+1})$, where $z_1, z_2, \\ldots z_g$ are nice binary strings and $d_1, d_2, \\ldots d_{g+1}$ are non-negative integers. Note that the $\\mathtt{1}$ s in $t[x, x + 3v - 1]$ won't help the $\\mathtt{1}$ s in $s[x + 3v, 2n]$. So, we can solve for $s[x + 3v, 2n]$ independently. Let $t'$ be the updated $t$. Now, carefully observe the structure of $t'$. We can replace all the substrings of the form $f(\\mathtt{0} , k) + f(\\mathtt{1} , k) + f(\\mathtt{0} , k)$ in $t'$ with $\\mathtt{0} \\mathtt{1} \\mathtt{0} \\mathtt{0} \\mathtt{1} \\mathtt{0} \\ldots \\mathtt{0} \\mathtt{1} \\mathtt{0} \\mathtt{0} \\mathtt{1} \\mathtt{0}$. So the updated $t'$(say $t\"$) will be of form $b_1 + b_2 + \\ldots b_q$, where $b_i$ is either equal to $\\mathtt{0}$ or $\\mathtt{010}$. So whenever we need to find $f(e)$ for some binary string $e$, we can always try to find a string of form $t\"$ using as few $\\mathtt{1}$s as possible. Notice that we can construct $t\"$ greedily. You can look at the attached code for the implementation details. Also, we don't need to actually append the $\\mathtt{0}$s at the back of $s$. It was just for proof purposes.",
    "code": "#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\n#define pb push_back                  \n#define mp make_pair          \n#define nline \"\\n\"                            \n#define f first                                            \n#define s second                                             \n#define pll pair<ll,ll> \n#define all(x) x.begin(),x.end()     \nconst ll MOD=1e9+7;\nconst ll MAX=500500;\nll f(string s){\n    ll len=s.size(),ans=0,pos=0;\n    while(pos<len){\n        if(s[pos]=='1'){\n            ans++;\n            pos+=2;\n        }\n        pos++;\n    }\n    return ans;\n}\nvoid solve(){ \n    ll n,ans=0; cin>>n;\n    string s; cin>>s; \n    for(ll i=0;i<n;i++){\n        string t; \n        for(ll j=i;j<n;j++){\n            t.push_back(s[j]);\n            ans+=f(t);\n        }\n    }\n    cout<<ans<<nline;\n    return;  \n}                                       \nint main()                                                                               \n{     \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);                               \n    #ifndef ONLINE_JUDGE                 \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif     \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1930",
    "index": "D2",
    "title": "Sum over all Substrings (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $t$ and $n$. You can make hacks only if both versions of the problem are solved.}\n\nFor a binary$^\\dagger$ pattern $p$ and a binary string $q$, both of length $m$, $q$ is called $p$-good if for every $i$ ($1 \\leq i \\leq m$), there exist indices $l$ and $r$ such that:\n\n- $1 \\leq l \\leq i \\leq r \\leq m$, and\n- $p_i$ is a mode$^\\ddagger$ of the string $q_l q_{l+1} \\ldots q_{r}$.\n\nFor a pattern $p$, let $f(p)$ be the minimum possible number of $\\mathtt{1}$s in a $p$-good binary string (of the same length as the pattern).\n\nYou are given a binary string $s$ of size $n$. Find $$\\sum_{i=1}^{n} \\sum_{j=i}^{n} f(s_i s_{i+1} \\ldots s_j).$$ In other words, you need to sum the values of $f$ over all $\\frac{n(n+1)}{2}$ substrings of $s$.\n\n$^\\dagger$ A binary pattern is a string that only consists of characters $\\mathtt{0}$ and $\\mathtt{1}$.\n\n$^\\ddagger$ Character $c$ is a mode of string $t$ of length $m$ if the number of occurrences of $c$ in $t$ is at least $\\lceil \\frac{m}{2} \\rceil$. For example, $\\mathtt{0}$ is a mode of $\\mathtt{010}$, $\\mathtt{1}$ is not a mode of $\\mathtt{010}$, and both $\\mathtt{0}$ and $\\mathtt{1}$ are modes of $\\mathtt{011010}$.",
    "tutorial": "We can use the idea of D1 and dynamic programming to solve in $O(n)$. Suppose $dp[i][j]$ denotes $f(s[i,j])$ for all $1 \\le i \\le j \\le n$. Performing the transition is quite easy. If $s_i = \\mathtt{1}$, $dp[i][j]=1+dp[i+3][j]$, otherwise $dp[i][j]=dp[i+1][j]$. Note that $dp[i][j] = 0$ for if $i > j$. So if we fix $j$, we can find $dp[i][j]$ for all $1 \\le i \\le j$ in $O(n)$, and the original problem in $O(n^2)$. Now, we need to optimise it. Suppose $track[i] = \\sum_{j=i}^{n} dp[i][j]$ for all $1 \\le i \\le n$, with base condition that $track[i] = 0$ if $i > n$. There are two cases: $s_i = \\mathtt{0}$ : $track[i] = \\sum_{j=i}^{n} dp[i][j]$ $track[i] = dp[i][i] + \\sum_{j=i+1}^{n} dp[i][j]$ $track[i] = dp[i][i] + \\sum_{j=i+1}^{n} dp[i+1][j]$ $track[i] = track[i+1]$ as $dp[i][i]=0$ $s_i = \\mathtt{1}$ : $track[i] = \\sum_{j=i}^{n} dp[i][j]$ $track[i] = \\sum_{j=i}^{n} 1 + dp[i+3][j]$ $track[i] = n - i + 1 + \\sum_{j=i+3}^{n} dp[i+3][j]$ as $dp[i+3][i]=dp[i+3][i+1]=dp[i+3][i+2]=0$ $track[i] = n - i + 1 + \\sum_{j=i+3}^{n} dp[i+3][j]$ $track[i] = n - i + 1 + track[i+3]$ So, the answer to the original problem is $\\sum_{i=1}^{n} track[i]$, which we can do in $O(n)$.",
    "code": "#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\n#define pb push_back                  \n#define mp make_pair          \n#define nline \"\\n\"                            \n#define f first                                            \n#define s second                                             \n#define pll pair<ll,ll> \n#define all(x) x.begin(),x.end()     \nconst ll MOD=1e9+7;\nconst ll MAX=500500;\nvoid solve(){ \n    ll n,ans=0; cin>>n;\n    string s; cin>>s; s=\" \"+s;\n    vector<ll> dp(n+5,0);\n    for(ll i=n;i>=1;i--){\n        if(s[i]=='1'){\n            dp[i]=dp[i+3]+n-i+1;\n        }\n        else{\n            dp[i]=dp[i+1];\n        }\n        ans+=dp[i];\n    }\n    cout<<ans<<nline;\n    return;  \n}                                       \nint main()                                                                               \n{     \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);                               \n    #ifndef ONLINE_JUDGE                 \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif     \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "dp",
      "dsu",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1930",
    "index": "E",
    "title": "2..3...4.... Wonderful! Wonderful!",
    "statement": "Stack has an array $a$ of length $n$ such that $a_i = i$ for all $i$ ($1 \\leq i \\leq n$). He will select a positive integer $k$ ($1 \\leq k \\leq \\lfloor \\frac{n-1}{2} \\rfloor$) and do the following operation on $a$ any number (possibly $0$) of times.\n\n- Select a subsequence$^\\dagger$ $s$ of length $2 \\cdot k + 1$ from $a$. Now, he will delete the first $k$ elements of $s$ from $a$. To keep things perfectly balanced (as all things should be), he will also delete the last $k$ elements of $s$ from $a$.\n\nStack wonders how many arrays $a$ can he end up with for each $k$ ($1 \\leq k \\leq \\lfloor \\frac{n-1}{2} \\rfloor$). As Stack is weak at counting problems, he needs your help.\n\nSince the number of arrays might be too large, please print it modulo $998\\,244\\,353$.\n\n$^\\dagger$ A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deleting several (possibly, zero or all) elements. For example, $[1, 3]$, $[1, 2, 3]$ and $[2, 3]$ are subsequences of $[1, 2, 3]$. On the other hand, $[3, 1]$ and $[2, 1, 3]$ are not subsequences of $[1, 2, 3]$.",
    "tutorial": "Suppose you are given some array $b$ of length $m$ and a positive integer $k$. How to check whether we can get the array $b$ if we start with an array $a$ of length $n$ such that $a_i = i$ for all $i$ ($1 \\leq i \\leq n$)? First of all, array $b$ should be a subsequence of $a$. Now consider an increasing array $c$ (possibly empty) such that it contains all the elements of $a$ which are not present in $b$. Now look at some trivial necessary conditions. The length of array $c$ should divisible by $2k$, as exactly $2k$ elements were deleted in one operation. The length of array $c$ should divisible by $2k$, as exactly $2k$ elements were deleted in one operation. There should be atleast one element $v$ in $b$ such that there are atleast $k$ elements smaller than $v$ in the array $c$, and alteast $k$ elements greater than $v$ in the array $c$. Why? Think about the last operation. We can consider the case of empty $c$ separately. There should be atleast one element $v$ in $b$ such that there are atleast $k$ elements smaller than $v$ in the array $c$, and alteast $k$ elements greater than $v$ in the array $c$. Why? Think about the last operation. We can consider the case of empty $c$ separately. In fact, it turns out that these necessary conditions are sufficient (Why?). Now, we need to find the number of possible $b$. We can instead find the number of binary strings $s$ of length $n$ such that $s_i = 1$ if $i$ is present in $b$, and $s_i=0$ otherwise. For given $n$ and $k$, let us call $s$ good if there exists some $b$ which can be achieved from $a$. Instead of counting strings $s$ which are good, let us count the number of strings which are not good. For convenience, we will only consider strings $s$ having the number of $\\mathtt{0}$'s divisible by $2k$. Now, based on the conditions in hint $2$, we can conclude that $s$ is bad if and only if there does not exist any $1$ between the $k$-th $0$ from the left and the $k$-th $0$ from the right in $s$. Let us compress all the $\\mathtt{0}$'s between the $k$-th $0$ from the left and the $k$-th $0$ from the right into a single $0$ and call the new string $t$. Note that $t$ will have exactly $2k - 1$ $\\mathtt{0}$'s. We can also observe that for each $t$, a unique $s$ exists. This is only because we have already fixed the parameters $n$ and $k$. Thus the number of bad $s$ having exactly $x$ $\\mathtt{1}$'s is ${{x + 2k - 1} \\choose {2k - 1}}$ as there are exactly ${{x + 2k - 1} \\choose {2k - 1}}$ binary strings $t$ having $2k - 1$ $\\mathtt{0}$'s and $x$ $\\mathtt{1}$'s. Finally, there are exactly $\\binom{n}{x} - \\binom{x + 2k - 1}{2k - 1}$ good binary strings $s$ having $x$ $\\mathtt{1}$'s and $n-x$ $\\mathtt{0}$'s. Now, do we need to find this value for each $x$ from $1$ to $n$? No, as the number($n-x$) of $\\mathtt{0}$'s in $s$ should be a multiple of $2k$. There are only $O(\\frac{n}{2k})$ useful candidates for $x$. Thus, our overall complexity is $O(n \\log(n))$ (as $\\sum_{i=1}^{n} O(\\frac{n}{i}) = O(n \\log(n))$).",
    "code": "#pragma GCC optimize(\"O3,unroll-loops\")\n#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\nconst ll INF_ADD=1e18;\n#define pb push_back                  \n#define mp make_pair          \n#define nline \"\\n\"                            \n#define f first                                            \n#define s second                                             \n#define pll pair<ll,ll> \n#define all(x) x.begin(),x.end()     \nconst ll MOD=998244353;\nconst ll MAX=5000500;\nvector<ll> fact(MAX+2,1),inv_fact(MAX+2,1);\nll binpow(ll a,ll b,ll MOD){\n    ll ans=1;\n    a%=MOD;  \n    while(b){\n        if(b&1)\n            ans=(ans*a)%MOD;\n        b/=2;\n        a=(a*a)%MOD;\n    }\n    return ans;\n}\nll inverse(ll a,ll MOD){\n    return binpow(a,MOD-2,MOD);\n} \nvoid precompute(ll MOD){\n    for(ll i=2;i<MAX;i++){\n        fact[i]=(fact[i-1]*i)%MOD;\n    }\n    inv_fact[MAX-1]=inverse(fact[MAX-1],MOD);\n    for(ll i=MAX-2;i>=0;i--){\n        inv_fact[i]=(inv_fact[i+1]*(i+1))%MOD;\n    }\n}\nll nCr(ll a,ll b,ll MOD){\n    if(a==b){\n        return 1;\n    }\n    if((a<0)||(a<b)||(b<0))\n        return 0;   \n    ll denom=(inv_fact[b]*inv_fact[a-b])%MOD; \n    return (denom*fact[a])%MOD;    \n}\nll n,k;    \nll ways(ll gaps,ll options){\n    gaps--;\n    ll now=nCr(gaps+options-1,options-1,MOD);\n    return now;\n}\nvoid solve(){\n    cin>>n; \n    for(ll k=1;k<=(n-1)/2;k++){\n        ll ans=1;\n        for(ll deleted=2*k;deleted<=n-1;deleted+=2*k){\n            ll options=2*k,left_elements=n-deleted;\n            ans=(ans+ways(left_elements+1,deleted+1)-ways(left_elements+1,options)+MOD)%MOD;  \n        }\n        cout<<ans<<\" \";\n    }\n    cout<<nline;\n    return;   \n}                                       \nint main()                                                                               \n{     \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL); \n    #ifndef ONLINE_JUDGE                 \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif  \n    ll test_cases=1;                 \n    cin>>test_cases;\n    precompute(MOD);\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1930",
    "index": "F",
    "title": "Maximize the Difference",
    "statement": "For an array $b$ of $m$ non-negative integers, define $f(b)$ as the \\textbf{maximum} value of $\\max\\limits_{i = 1}^{m} (b_i | x) - \\min\\limits_{i = 1}^{m} (b_i | x)$ over all possible non-negative integers $x$, where $|$ is bitwise OR operation.\n\nYou are given integers $n$ and $q$. You start with an empty array $a$. Process the following $q$ queries:\n\n- $v$: append $v$ to the back of $a$ and then output $f(a)$. It is guaranteed that $0 \\leq v < n$.\n\n\\textbf{The queries are given in a modified way.}",
    "tutorial": "For an array $b$ consiting of $m$ non-negative integers, $f(b) = \\max\\limits_{p=1}^{m} ( \\max\\limits_{i = 1}^{m} (b_i | b_p) - \\min\\limits_{i = 1}^{m} (b_i | b_p))$. In other, we can get the maximum possible value by choosing $x=b_p$ for some $p$ ($1 \\leq p \\leq m$). $f(b)$ is the maximum value of $b_i \\land$ ~ $b_j$ over all pairs of ($i,j$) ($1 \\leq i,j \\leq m$), where $\\land$ is the bitwise AND operator, and ~ is the bitwise One's complement operator. Let us see how to find $f(b)$ in $O(n \\log(n))$ first. We will focus on updates later. Let us have two sets $S_1$ and $S_2$ such that $S_1$ contains all submasks of $b_i$ for all $1 \\leq i \\leq m$ $S_2$ contains all submasks of ~$b_i$for all $1 \\leq i \\leq m$ We can observe that $f(b)$ is the largest element present in both sets $S_1$ and $S_2$. Now, we can insert all submasks naively. But it would be pretty inefficient. Note that we need to insert any submask atmost once in either of the sets. Can you think of some approach in which you efficiently insert all the non-visited submasks of some mask? Note that the above pseudo code inserts all the all submasks efficiently. As all the masks will be visited atmost once, the amortised complexity will be $O(n \\log(n)^2)$. Note that instead of using a set, we can use a boolean array of size $n$ to reduce the complexity to $O(n \\log(n))$. Thus, we can use the above idea to find $f(b)$ in $O(n \\log(n))$. For each $i$ from $1$ to $m$, we can insert all submasks of $b_i$ into set $S_1$ and insert all the submasks of ~$b_i$ into set $S_2$. The above idea hints at how to deal with updates. If we need to append an element $z$ to $b$, we can just insert all submasks of $z$ into set $S_1$ and insert all the submasks of ~$z$ into set $S_2$. Hence, the overall complexity is $O(n \\log(n))$.",
    "code": "#pragma GCC optimize(\"O3,unroll-loops\")\n#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\n#define pb push_back                  \n#define mp make_pair          \n#define nline \"\\n\"                            \n#define f first                                            \n#define s second                                             \n#define pll pair<ll,ll> \n#define all(x) x.begin(),x.end() \nconst ll MAX=100100; \nvoid solve(){     \n    ll n,q; cin>>n>>q;\n    ll till=1,len=1;\n    while(till<n){\n        till*=2;\n        len++;\n    }\n    ll ans=0;\n    vector<vector<ll>> track(2,vector<ll>(till+5,0));\n    auto add=[&](ll x,ll p){\n        queue<ll> trav;\n        if(track[p][x]){\n            return;\n        }\n        trav.push(x); track[p][x]=1;\n        while(!trav.empty()){\n            auto it=trav.front();\n            trav.pop();\n            if(track[0][it]&track[1][it]){\n                ans=max(ans,it);\n            }\n            for(ll j=0;j<len;j++){\n                if(it&(1<<j)){\n                    ll cur=(it^(1<<j));   \n                    if(!track[p][cur]){\n                        track[p][cur]=1;\n                        trav.push(cur);\n                    }\n                }\n            }\n        }\n    };\n    ll supermask=till-1;\n    vector<ll> a(q+5);\n    for(ll i=1;i<=q;i++){\n        ll h; cin>>h; \n        a[i]=(h+ans)%n;\n        add(a[i],0);\n        add(supermask^a[i],1);\n        cout<<ans<<\" \\n\"[i==q];\n    }\n    return;  \n}                                         \nint main()                                                                               \n{     \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);                               \n    #ifndef ONLINE_JUDGE                 \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif     \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "bitmasks",
      "brute force",
      "dfs and similar"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1930",
    "index": "G",
    "title": "Prefix Max Set Counting",
    "statement": "Define a function $f$ such that for an array $b$, $f(b)$ returns the array of prefix maxima of $b$. In other words, $f(b)$ is an array containing only those elements $b_i$, for which $b_i=\\max(b_1,b_2,\\ldots,b_i)$, without changing their order. For example, $f([3,10,4,10,15,1])=[3,10,10,15]$.\n\nYou are given a tree consisting of $n$ nodes rooted at $1$.\n\nA permutation$^\\dagger$ $p$ of is considered a pre-order of the tree if for all $i$ the following condition holds:\n\n- Let $k$ be the number of proper descendants$^\\ddagger$ of node $p_i$.\n- For all $x$ such that $i < x \\leq i+k$, $p_x$ is a proper descendant of node $p_i$.\n\nFind the number of distinct values of $f(a)$ over all possible pre-orders $a$. Since this value might be large, you only need to find it modulo $998\\,244\\,353$.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^\\ddagger$ Node $t$ is a proper descendant of node $s$ if $s \\neq t$ and $s$ is on the unique simple path from $t$ to $1$.",
    "tutorial": "Consider some subsequence $S$ of $[1,2, \\ldots n]$ such that there exists atleast one pre-order $a$ such that $F(a)=S$. Look for some non-trivial properties about $S$. Node $S_i$ will be visited before the node $S_{i+1}$. Assume $|S|=k$. First of all, we should $S_1=1$ and $S_k = n$. There cannot exists there distinct indices $a, b$ and $c$ ($1 \\leq a < b < c \\leq |k|$) such that $S_c$ lies on the path from $S_a$ to $S_b$. Assume $LCA_i$ is the lowest common ancestor of $S_i$ and $S_{i+1}$. For all $i$($1 \\leq i <k$), the largest value over all the nodes on the unique path from $S_i$ to $S_{i+1}$ should be $S_{i+1}$. Suppose $nax_p$ is the maximum value in the subtree of $p$. There is one more important restriction if $S_i$ does not lie on the path from $S_{i+1}$ to $1$. Suppose $m$ is the child of $LCA_i$, which lies on the path from $S_i$ to $LCA_i$. We should have $S_{i+1} > nax_m$. In fact, if you observe carefully you will realise that we should have $S_i = nax_m$. Let us use dynamic programming. Suppose $dp[i]$ gives the number of valid subsequences(say $S$) such that the last element of $S$ is $i$. Note that the answer to our original problem will be $dp[n]$. Suppose $nax(u,v)$ denotes the maximum value on the path from $u$ to $v$(including the endpoints). Let us have a $O(n^2)$ solution first. We have $dp[1]=1$. Suppose we are at some node $i$($i > 1$), and we need to find $dp[i]$. Let us consider some node $j$($1 \\le j < i$) and see if we can append $i$ to all the subsequences which end with node $j$. If we can append, we just need to add $dp[j]$ to $dp[i]$. But how do we check if we can append $i$ to all the subsequences that end with node $j$? Check hints 2 and 3. So, we have a $n^2$ solution now. We need to optimise it now. We will move in the increasing value of the nodes(from $2$ to $n$) and calculate the $dp$ values. Suppose $nax(1, par_i) = v$, where $par_i$ denotes the parent of $i$. Assume we go from node $j$($j < i$) to node $i$. There are two cases: $j$ lies on the path from $1$ to $i$: This case is easy, as we just need to ensure that $nax(j,par_i) = j$. We can add $dp[j]$ to $dp[i]$ if we have $nax(j,par_i) = j$. Note that there exists only one node(node $v$) for which might add $dp[v]$ to $dp[i]$ $j$ lies on the path from $1$ to $i$: This case is easy, as we just need to ensure that $nax(j,par_i) = j$. We can add $dp[j]$ to $dp[i]$ if we have $nax(j,par_i) = j$. Note that there exists only one node(node $v$) for which might add $dp[v]$ to $dp[i]$ $j$ does not lie on the path from $1$ to $i$ : We will only consider the case in which $dp[j]$ will be added to $dp[i]$. Suppose $lca$ is the lowest common ancestor of $j$ and $i$, and $m$ is the child of $lca$, which lies on the path from $j$ to $lca$. Notice that the largest value in the subtree of $m$ should be $j$. This observation is quite helpful. We can traverse over all the ancestors of $i$. Suppose that we are at ancestor $u$. We will iterate over all the child(say $c$) of $u$ such that $nax_c < i$, and add $dp[nax_c]$ to $dp[i]$ if $nax(u,par_i) < nax_c$. Suppose $track[u][i]$ stores the sum of $dp[nax_c]$ for all $c$ such that $nax_c < i$. So we should add $track[u][i]$ to $dp[i]$. But there is a catch. This way, $dp[nax_c]$ will also get added $dp[i]$ even when $nax_c < nax(u, par_i)$. So, we need to subtract some values, which is left as an exercise for the readers. Now, $track[u][d] = track[u][d-1] + dp[nax_c]$ if $nax_c = d$. So, instead of keeping a two-dimensional array $track$, we can just maintain a one-dimensional array $track$. Note that we will only need the sum of $track[u]$ for all the ancestors of $i$, which we can easily calculate using the euler tour. $j$ does not lie on the path from $1$ to $i$ : We will only consider the case in which $dp[j]$ will be added to $dp[i]$. Suppose $lca$ is the lowest common ancestor of $j$ and $i$, and $m$ is the child of $lca$, which lies on the path from $j$ to $lca$. Notice that the largest value in the subtree of $m$ should be $j$. This observation is quite helpful. We can traverse over all the ancestors of $i$. Suppose that we are at ancestor $u$. We will iterate over all the child(say $c$) of $u$ such that $nax_c < i$, and add $dp[nax_c]$ to $dp[i]$ if $nax(u,par_i) < nax_c$. Suppose $track[u][i]$ stores the sum of $dp[nax_c]$ for all $c$ such that $nax_c < i$. So we should add $track[u][i]$ to $dp[i]$. But there is a catch. This way, $dp[nax_c]$ will also get added $dp[i]$ even when $nax_c < nax(u, par_i)$. So, we need to subtract some values, which is left as an exercise for the readers. Now, $track[u][d] = track[u][d-1] + dp[nax_c]$ if $nax_c = d$. So, instead of keeping a two-dimensional array $track$, we can just maintain a one-dimensional array $track$. Note that we will only need the sum of $track[u]$ for all the ancestors of $i$, which we can easily calculate using the euler tour. You can look at the attached code for the implementation details. The intended time complexity is $O(n \\cdot \\log(n))$.",
    "code": "#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\n#define pb push_back                  \n#define mp make_pair          \n#define nline \"\\n\"                            \n#define f first                                            \n#define s second                                             \n#define pll pair<ll,ll> \n#define all(x) x.begin(),x.end()     \nconst ll MOD=998244353;\nconst ll MAX=1000100;\nstruct FenwickTree{\n    vector<ll> bit; \n    ll n;\n    FenwickTree(ll n){\n        this->n = n;\n        bit.assign(n, 0);\n    }\n    FenwickTree(vector<ll> a):FenwickTree(a.size()){  \n        ll x=a.size();\n        for(size_t i=0;i<x;i++)\n            add(i,a[i]);\n    }\n    ll sum(ll r) {\n        ll ret=0;\n        for(;r>=0;r=(r&(r+1))-1){\n            ret+=bit[r];\n            ret%=MOD;\n        }\n        return ret;\n    }\n    ll sum(ll l,ll r) {\n        if(l>r)\n            return 0;\n        ll val=sum(r)-sum(l-1)+MOD;\n        val%=MOD;\n        return val;\n    }\n    void add(ll idx,ll delta) {\n        for(;idx<n;idx=idx|(idx+1)){\n            bit[idx]+=delta;\n            bit[idx]%=MOD;\n        }\n    }\n};\nvector<vector<ll>> adj;\nvector<ll> tin(MAX,0),tout(MAX,0);\nvector<ll> parent(MAX,0);\nvector<ll> overall_max(MAX,0);\nll now=1;\nvector<ll> jump_to(MAX,0),sub(MAX,0);\nvoid dfs(ll cur,ll par){\n    parent[cur]=par;\n    tin[cur]=now++;\n    overall_max[cur]=cur;\n    for(auto chld:adj[cur]){\n        if(chld!=par){\n            jump_to[chld]=max(jump_to[cur],cur);\n            dfs(chld,cur);\n            overall_max[cur]=max(overall_max[cur],overall_max[chld]);\n        }\n    }\n    tout[cur]=now++;\n}\nvector<ll> dp(MAX,0);\nvoid solve(){ \n    ll n; cin>>n;\n    adj.clear();\n    adj.resize(n+5);\n    for(ll i=1;i<=n-1;i++){\n        ll u,v; cin>>u>>v;\n        adj[u].push_back(v);  \n        adj[v].push_back(u);\n    }  \n    now=1;      \n    dfs(1,0);      \n    ll ans=0;    \n    FenwickTree enter_time(now+5),exit_time(now+5);\n    overall_max[0]=MOD;   \n    dp[0]=1;    \n    for(ll i=1;i<=n;i++){\n        ll p=jump_to[i];\n        dp[i]=(enter_time.sum(0,tin[i])-exit_time.sum(0,tin[i])-sub[p]+dp[p]+MOD+MOD)%MOD;\n        if(p>i){  \n            dp[i]=0;\n        }\n        ll node=i;\n        while(overall_max[node]==i){\n            node=parent[node];\n        }\n        enter_time.add(tin[node],dp[i]);\n        exit_time.add(tout[node],dp[i]);\n        sub[i]=(enter_time.sum(0,tin[i])-exit_time.sum(0,tin[i])+MOD)%MOD;\n    }\n    cout<<dp[n]<<nline;\n    return;  \n}                                       \nint main()                                                                               \n{       \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);                               \n    #ifndef ONLINE_JUDGE                 \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif     \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1930",
    "index": "H",
    "title": "Interactive Mex Tree",
    "statement": "This is an interactive problem.\n\nAlice has a tree $T$ consisting of $n$ nodes, numbered from $1$ to $n$. Alice will show $T$ to Bob. After observing $T$, Bob needs to tell Alice two permutations $p_1$ and $p_2$ of $[1, 2, \\ldots, n]$.\n\nThen, Alice will play $q$ rounds of the following game.\n\n- Alice will create an array $a$ that is a permutation of $[0,1,\\ldots,n-1]$. The value of node $v$ will be $a_v$.\n- Alice will choose two nodes $u$ and $v$ ($1 \\leq u, v \\leq n$, $u \\neq v$) of $T$ and tell them to Bob. Bob will need to find the $\\operatorname{MEX}^\\dagger$ of the values on the unique simple path between nodes $u$ and $v$.\n- To find this value, Bob can ask Alice at most $5$ queries. In each query, Bob should give three integers $t$, $l$ and $r$ to Alice such that $t$ is either $1$ or $2$, and $1 \\leq l \\leq r \\leq n$. Alice will then tell Bob the value equal to $$\\min_{i=l}^{r} a[p_{t,i}].$$\n\nNote that all rounds are independent of each other. In particular, the values of $a$, $u$ and $v$ can be different in different rounds.\n\nBob is puzzled as he only knows the HLD solution, which requires $O(\\log(n))$ queries per round. So he needs your help to win the game.\n\n$^\\dagger$ The $\\operatorname{MEX}$ (minimum excludant) of a collection of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $c$.",
    "tutorial": "$\\operatorname{MEX}$ of the path from $u$ to $v$ will be the minimum value over all the nodes of $T$ which do not lie on the path from $u$ to $v$. $p_1$ and $p_2$ are associated with the Euler tour $p_1$ is the permutation of $[1,2, \\ldots n]$ sorted in increasing order on the basis on $tin$ time observed during Euler tour. Similarly, $p_2$ is the permutation of $[1,2, \\ldots n]$ sorted in increasing order based on $tout$ time. Note that any Euler tour is fine. Now we have $p_1$ and $p_2$ with us. Suppose we need to find $\\operatorname{MEX}$ of the path from $u$ to $v$. Assume that $tin_u < tin_v$ for convenience. Assume $T'$ is the forest we get if we remove all the nodes on the path from $u$ to $v$ from $T$. Our goal is to find the minimum value over all the nodes in $T'$. Assume that $T'$ is non-empty, as $\\operatorname{MEX}$ will be $n$ if $T'$ is empty. Assume $LCA$ is the lowest common ancestor of $u$ and $v$. Suppose $m$ is the child of $LCA(u,v)$, which lies on the path from $v$ to $LCA(u,v)$. Let us consider some groups of nodes $p$ such that. $tout_p < tin_u$ $tin_u < tin_p < tin_m$ $tin_m < tout_p < tin_v$ $tin_v < tin_p$ $tout_{LCA} < tout_p$ Note that we have precisely $5$ groups, with the $i$-th group consisting of only those nodes which satisfy the $i$-th condition. Here comes the interesting claim. All nodes in $T'$ are present in atleast one of the above $5$ groups. There does not exist a node $p$ such that $p$ is on the path from $u$ from $v$ and $p$ is present in any of the groups. Now, it is not hard to observe that if we consider the nodes of any group, they will form a continuous segment in either $p_1$ or $p_2$. So we can cover each group in a single query. Hence, we can find the $\\operatorname{MEX}$ of the path in any round using atmost $5$ queries.",
    "code": "\n#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\nconst ll INF_ADD=1e18;\n#define pb push_back                  \n#define mp make_pair          \n#define nline \"\\n\"                            \n#define f first                                            \n#define s second                                             \n#define pll pair<ll,ll> \n#define all(x) x.begin(),x.end()     \nconst ll MOD=998244353;\nconst ll MAX=200200;   \nvector<ll> adj[MAX];\nll now=0,till=20;\nvector<ll> tin(MAX,0),tout(MAX,0),depth(MAX,0);\nvector<vector<ll>> jump(MAX,vector<ll>(till+1,0));\nvoid dfs(ll cur,ll par){\n    jump[cur][0]=par;\n    for(ll i=1;i<=till;i++)\n        jump[cur][i]=jump[jump[cur][i-1]][i-1];\n    tin[cur]=++now;\n    for(ll chld:adj[cur]){\n        if(chld!=par){\n            depth[chld]=depth[cur]+1;\n            dfs(chld,cur);\n        }\n    }\n    tout[cur]=++now;\n} \nbool is_ancestor(ll a,ll b){\n    if((tin[a]<=tin[b])&&(tout[a]>=tout[b]))\n        return 1;\n    return 0;\n} \nll lca(ll a,ll b){\n    if(is_ancestor(a,b))\n        return a;\n    for(ll i=till;i>=0;i--){\n        if(!is_ancestor(jump[a][i],b))\n            a=jump[a][i];\n    }\n    return jump[a][0];\n}  \nvoid solve(){\n    ll n; cin>>n;\n    ll m; cin>>m;\n    vector<ll> a(n+5);\n    for(ll i=1;i<=n-1;i++){\n        ll u,v; cin>>u>>v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    now=1;\n    dfs(1,1);\n    vector<ll> p(n),q(n);\n    for(ll i=0;i<n;i++){\n        p[i]=q[i]=i+1;\n    }\n    sort(all(p),[&](ll l,ll r){\n        return tin[l]<tin[r];\n    });\n    sort(all(q),[&](ll l,ll r){\n        return tout[l]<tout[r];\n    });\n    for(auto it:p){\n        cout<<it<<\" \";\n    }\n    cout<<endl;\n    for(auto it:q){\n        cout<<it<<\" \";\n    }\n    cout<<endl;\n    auto query_p=[&](ll l,ll r){\n        ll left_pos=n+1,right_pos=-1;\n        for(ll i=0;i<n;i++){\n            ll node=p[i];\n            if((tin[node]>=l) and (tin[node]<=r)){\n                left_pos=min(left_pos,i);\n                right_pos=i;\n            }\n        }\n        ll now=n+5;\n        if(right_pos!=-1){\n            left_pos++,right_pos++;\n            cout<<\"? 1 \"<<left_pos<<\" \"<<right_pos<<endl;\n            cin>>now;\n        }\n        return now;\n    };\n    auto query_q=[&](ll l,ll r){\n        ll left_pos=n+1,right_pos=-1;\n        for(ll i=0;i<n;i++){\n            ll node=q[i];\n            if((tout[node]>=l) and (tout[node]<=r)){\n                left_pos=min(left_pos,i);\n                right_pos=i;\n            }\n        }\n        ll now=n+5;\n        if(right_pos!=-1){\n            left_pos++,right_pos++;\n            cout<<\"? 2 \"<<left_pos<<\" \"<<right_pos<<endl;\n            cin>>now;\n        }\n        return now;\n    };\n    while(m--){\n        ll u,v; cin>>u>>v;\n        if(tout[u]>tout[v]){\n            swap(u,v);\n        }\n        ll lca_node=lca(u,v);\n        ll ans=n;\n        if(lca_node==v){\n            ans=min(ans,query_q(1,tin[u]));\n            ans=min(ans,query_p(tin[u]+1,tout[v]));\n            ans=min(ans,query_q(tout[v]+1,now));\n            cout<<\"! \"<<ans<<endl;\n            ll x; cin>>x;\n            continue;\n        }\n        ans=min(ans,query_q(1,tin[u]));\n        ll consider=v;\n        for(auto it:adj[lca_node]){\n            if(is_ancestor(lca_node,it) and is_ancestor(it,v)){\n                consider=it;\n            }\n        }\n        ans=min(ans,query_p(tin[u]+1,tin[consider]-1));\n        ans=min(ans,query_q(tin[consider],tin[v]));\n        ans=min(ans,query_p(tin[v]+1,tout[lca_node]));\n        ans=min(ans,query_q(tout[lca_node]+1,now));\n        cout<<\"! \"<<ans<<endl;\n        ll x; cin>>x;\n    }\n    for(ll i=1;i<=n;i++){\n        adj[i].clear();\n    }\n    return;  \n}                                       \nint main()                                                                               \n{     \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL); \n    #ifndef ONLINE_JUDGE                 \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif  \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "interactive",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1930",
    "index": "I",
    "title": "Counting Is Fun",
    "statement": "You are given a binary$^\\dagger$ pattern $p$ of length $n$.\n\nA binary string $q$ of the same length $n$ is called \\textbf{good} if for every $i$ ($1 \\leq i \\leq n$), there exist indices $l$ and $r$ such that:\n\n- $1 \\leq l \\leq i \\leq r \\leq n$, and\n- $p_i$ is a mode$^\\ddagger$ of the string $q_lq_{l+1}\\ldots q_r$.\n\nCount the number of good binary strings modulo $998\\,244\\,353$.\n\n$^\\dagger$ A binary string is a string that only consists of characters $\\mathtt{0}$ and $\\mathtt{1}$.\n\n$^\\ddagger$ Character $c$ is a mode of string $t$ of length $m$ if the number of occurrences of $c$ in $t$ is at least $\\lceil \\frac{m}{2} \\rceil$. For example, $\\mathtt{0}$ is a mode of $\\mathtt{010}$, $\\mathtt{1}$ is not a mode of $\\mathtt{010}$, and both $\\mathtt{0}$ and $\\mathtt{1}$ are modes of $\\mathtt{011010}$.",
    "tutorial": "A167510 It is convinient here to assign weights to $\\mathtt{0} \\to -1$ and $\\mathtt{1} \\to 1$. Given a string $t$, we can define the prefix sum $p$ of it's weights. For example, if $t=\\mathtt{0010111}$, then $p=[0,-1,-2,-1,-2,-1,0,1]$. So that if $t$ is bad and $i$ is a index that violates the definition, then $\\max(p_0,p_1,\\ldots,p_{i-1}) < \\min(p_i,p_{i+1},\\ldots,p_n)$ if $s_i = \\mathtt{0}$ or $\\min(p_0,p_1,\\ldots,p_{i-1}) > \\max(p_i,p_{i+1},\\ldots,p_n)$ if $s_i = \\mathtt{1}$. Naturally, it is convinient to assume that $p_0 < p_n$. All string with $p_0 = p_n$ are clearly good and $p_0 > p_n$ is handled similarly. For strings with $p_0 < p_n$, the condition can only be violated on an index with $s_i = \\mathtt{0}$. The solution works using PIE. Let us fix a set of positions $I$ that are bad, so that if $i \\in I$, then $s_i =\\mathtt{0}$ and $\\max(p_0,p_1,\\ldots,p_{i-1}) < \\min(p_i,p_{i+1},\\ldots,p_n)$. Then we need to count the number of ways to construct $p$ satisfying these conditions and then add it to the answer multiplied by $(-1)^{|I|}$. Suppose that $I = i_1,i_2,\\ldots,i_k$. $t[1,i_1]$ and $t[i_k,n]$ need to be a ballot sequence of length $i_1-1$ and $n-i_k$ respectively (A001405, denote it as $f(n)$) while $t[i_j,i_{j+1}]$ needs to be bidirectional ballot sequence of length $i_{j+1}-i_j-1$ (A167510, denote it as $g(n)$). Note that in our definition of ballot sequence, we are do not require that prefixes and suffixes have strictly more $\\mathtt{1}$ s thatn $\\mathtt{0}$ s. It is the same sequence, but note that we need to shift it by a few places when refering to OEIS. The first $n$ terms of $f$ is easily computed in linear time. We will focus on how to compute the first $n$ terms of $g$ in $O(n \\log^2 n)$. Computing $g(n)$ Firstly, let us consider the number of bidirectional sequences with $\\frac{n+k}{2}$ $\\mathtt{1}$ s and $\\frac{n-k}{2}$ $\\mathtt{0}$ s. We will imagine this as lattice walks from $(0,0)$ to $(n,k)$ where $\\mathtt{1} \\to (1,1)$ and $\\mathtt{0} \\to (1,-1)$. If we touch the lines $y=-1$ or $y=k+1$, the walk is invalid. We can use the reflection method here, similar to a proof of Catalan. The number of valid walks is $#(*) - #(T) + #(TB) - #(TBT) ..... - #(B) + #(BT) - #(BTB) + .....$ where $#(BTB)$ denotes the number of walks that touch the bottom line, then the top line, then the bottom line, and then may continue to touch the top and bottom line after that. We have $#(*) =$ $\\binom{n}{\\frac{n+k}{2}}$, $#(T) =$ $\\binom{n}{\\frac{n+k+2}{2}}$, $#(TB) =$ $\\binom{n}{\\frac{n+3k+4}{2}}$, $#(TBT) =$ $\\binom{n}{\\frac{n+3k+6}{2}}$, $\\ldots$, $#(B) =$ $\\binom{n}{\\frac{n+k+2}{2}}$, $#(BT) =$ $\\binom{n}{\\frac{n+k+4}{2}}$, $#(BTB) =$ $\\binom{n}{\\frac{n+3k+6}{2}}$, $\\ldots$ This already gives us a method to compute $g(n)$ in $O(n \\log n)$ since for a fixed $k$, we can compute the above sum in $O(\\frac{n}{k})$, since only the first $O(\\frac{n}{k})$ terms are not $0$. First, notice that we can aggregate them sums without iterating on $k$, for some fixed $j$, we can find the coefficient $c_j$ of $\\binom{n}{\\frac{n+j}{2}}$ across all $k$. Notice that this coefficient is independent across all $n$, so we only need to compute $c$ once. Now, note that $\\binom{n}{\\frac{n+z}{2}} = [x^z] (x^{-1} + x) ^ n$. So that $g(n) = [x^0] C \\cdot (x^{-1} + x)^n$, where $C$ is the ogf of $c$. From this formulation, we can describe how to compute the first $n$ terms of $g$ in $O(n \\log^2 n)$ using Divide and Conquer. $DnC(l,r,V)$ computes the $g(l) \\ldots g(r)$ where $V$ is the coefficents between $[l-r,r-l]$ of $C \\cdot (x^{-1} + x)^l$. $DnC(l,r,V)$ will call $DnC(l,m,V)$ and $DnC(m+1,r,V \\cdot (x^{-1}+x)^{m-l+1})$. We have the reccurence $T(n) = 2 T(\\frac{n}{2}) + O(n \\log n)$ so $T(n) = O(n \\log^2 n)$. Of course, for constant time speedup, you can choose to split the odd and even coefficients, but that is not needed. It is possible to compute the first $n$ of $g$ in $O(n \\log n)$ but it does not improve the overall complexity of the solution. Final Steps Now that we obtained the $n$ terms of $f$ and $g$, let us return to the origial problem. If $s_i =\\mathtt{0}$, define $dp_i = f(i-1) - \\sum\\limits_{s_j = \\mathtt{0}} dp_j \\cdot g(j-i-1)$. Then this contributes $f(n-i) \\cdot dp_i$ to the number of bad strings. Again, we will use Divide and Conquer to perform this quickly. Briefly, $DnC(l,r)$ will compute the values of $dp[l,r]$ given that contributions from $dp[1,l-1]$ has been transferred to $dp[l,r]$ already. We will call $DnC(l,m)$, compute the contribution from $dp[l,m]$ to $dp[m+1,r]$ using FFT and then call $DnC(m+1,r)$. The complexity of this is $O(n \\log^2 n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n#define ll long long\n#define ii pair<int,int>\n#define iii tuple<int,int,int>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\n\nconst int MOD=998244353;\n\nll qexp(ll b,ll p,int m){\n    ll res=1;\n    while (p){\n        if (p&1) res=(res*b)%m;\n        b=(b*b)%m;\n        p>>=1;\n    }\n    return res;\n}\n\nll inv(ll i){\n\treturn qexp(i,MOD-2,MOD);\n}\n\nll fix(ll i){\n\ti%=MOD;\n\tif (i<0) i+=MOD;\n\treturn i;\n}\n\nll fac[1000005];\nll ifac[1000005];\n\nll nCk(int i,int j){\n\tif (i<j) return 0;\n\treturn fac[i]*ifac[j]%MOD*ifac[i-j]%MOD;\n}\n\nconst ll mod = (119 << 23) + 1, root = 62; // = 998244353\n// For p < 2^30 there is also e.g. 5 << 25, 7 << 26, 479 << 21\n// and 483 << 21 (same root). The last two are > 10^9.\ntypedef vector<ll> vl;\nvoid ntt(vl &a) {\n\tint n = sz(a), L = 31 - __builtin_clz(n);\n\tstatic vl rt(2, 1);\n\tfor (static int k = 2, s = 2; k < n; k *= 2, s++) {\n\t\trt.resize(n);\n\t\tll z[] = {1, qexp(root, mod >> s, mod)};\n\t\trep(i,k,2*k) rt[i] = rt[i / 2] * z[i & 1] % mod;\n\t}\n\tvector<int> rev(n);\n\trep(i,0,n) rev[i] = (rev[i / 2] | (i & 1) << L) / 2;\n\trep(i,0,n) if (i < rev[i]) swap(a[i], a[rev[i]]);\n\tfor (int k = 1; k < n; k *= 2)\n\t\tfor (int i = 0; i < n; i += 2 * k) rep(j,0,k) {\n\t\t\tll z = rt[j + k] * a[i + j + k] % mod, &ai = a[i + j];\n\t\t\ta[i + j + k] = ai - z + (z > ai ? mod : 0);\n\t\t\tai += (ai + z >= mod ? z - mod : z);\n\t\t}\n}\nvl conv(const vl &a, const vl &b) {\n\tif (a.empty() || b.empty()) return {};\n\tint s = sz(a) + sz(b) - 1, B = 32 - __builtin_clz(s), n = 1 << B;\n\tint inv = qexp(n, mod - 2, mod);\n\tvl L(a), R(b), out(n);\n\tL.resize(n), R.resize(n);\n\tntt(L), ntt(R);\n\trep(i,0,n) out[-i & (n - 1)] = (ll)L[i] * R[i] % mod * inv % mod;\n\tntt(out);\n\treturn {out.begin(), out.begin() + s};\n}\n\nint n;\nstring s;\n\nint c[100005];\nint f[100005];\n\nvoid calc(int l,int r,vector<int> v){\n\twhile (sz(v)>(r-l)*2+1) v.pob();\n\t\n\tif (l==r){\n\t\tf[l]=v[0];\n\t\treturn;\n\t}\n\t\n\tint m=l+r>>1;\n\t\n\tcalc(l,m,vector<int>(v.begin()+(r-m),v.end()));\n\tvector<int> a;\n\tint t=m-l+1;\n\trep(x,0,t+1) a.pub(nCk(t,x)),a.pub(0);\n\t\n\tv=conv(v,a);\n\tcalc(m+1,r,vector<int>(v.begin()+(2*t),v.end()));\n}\n\nint ans[100005];\n\nvoid solve(int l,int r){\n\tif (l==r) return;\n\tint m=l+r>>1;\n\tsolve(l,m);\n\tauto a=conv(vector<int>(ans+l,ans+m+1),vector<int>(f,f+(r-l)));\n\trep(x,m+1,r+1) if (s[x]=='0') ans[x]=fix(ans[x]-a[x-1-l]);\n\tsolve(m+1,r);\n}\n\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tfac[0]=1;\n\trep(x,1,1000005) fac[x]=fac[x-1]*x%MOD;\n\tifac[1000004]=inv(fac[1000004]);\n\trep(x,1000005,1) ifac[x-1]=ifac[x]*x%MOD;\n\t\n\trep(x,1,100005){\n\t\tc[x]++;\n\t\t\n\t\tint curr=x;\n\t\twhile (curr<100005){\n\t\t\tif (curr+2<100005) c[curr+2]-=2;\n\t\t\tif (curr+4<100005) c[curr+4]++;\n\t\t\tif (curr+2*x+4<100005) c[curr+2*x+4]++;\n\t\t\tcurr+=2*x+4;\n\t\t}\n\t}\n\t\n\tcin>>n;\n\tcin>>s;\n\t\n\tvector<int> v;\n\trep(x,n+1,1) v.pub(fix(c[x]+(x>=2?c[x-2]:0LL)));\n\tcalc(1,n,v);\n\tf[0]=1;\n\t\n\tint fin=qexp(2,n,MOD);\n\trep(_,0,2){\n\t\trep(x,0,n) ans[x]=(s[x]=='0')?nCk(x,x/2):0LL;\n\t\tsolve(0,n-1);\n\t\trep(x,0,n) if (s[x]=='0') fin=fix(fin-ans[x]*nCk((n-x-1),(n-x-1)/2));\n\t\t\n\t\tfor (auto &it:s) it^=1;\n\t}\n\t\n\tcout<<fin<<endl;\n}",
    "tags": [
      "combinatorics"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1931",
    "index": "A",
    "title": "Recovering a Small String",
    "statement": "Nikita had a word consisting of exactly $3$ lowercase Latin letters. The letters in the Latin alphabet are numbered from $1$ to $26$, where the letter \"a\" has the index $1$, and the letter \"z\" has the index $26$.\n\nHe encoded this word as the sum of the positions of all the characters in the alphabet. For example, the word \"cat\" he would encode as the integer $3 + 1 + 20 = 24$, because the letter \"c\" has the index $3$ in the alphabet, the letter \"a\" has the index $1$, and the letter \"t\" has the index $20$.\n\nHowever, this encoding turned out to be ambiguous! For example, when encoding the word \"ava\", the integer $1 + 22 + 1 = 24$ is also obtained.\n\nDetermine the lexicographically smallest word of $3$ letters that could have been encoded.\n\nA string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "The problem can be solved by simply going through all the $3$ letter combinations and searching for the lexicographically minimal one among them. It is also possible to consider a string consisting of three letters \"a\", and, going through it from the end until the value of $n$ is greater than zero, increase the letters to the maximum possible value and subtract the corresponding difference from $n$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n \nvoid solve(){\n    int n, sz = 26;\n    cin >> n;\n    string mins = \"zzz\", cur;\n    for(int i = 0; i < sz; i++){\n        for(int j = 0; j < sz; j++){\n            for(int k = 0; k < sz; k++){\n                if(i + j + k + 3 == n){\n                    cur += char(i + 'a');\n                    cur += char(j + 'a');\n                    cur += char(k + 'a');\n                    mins = min(cur, mins);\n                }\n            }\n        }\n    }\n    cout << mins << \"\\n\";\n \n}\nint main(){\n    int t;\n    cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1931",
    "index": "B",
    "title": "Make Equal",
    "statement": "There are $n$ containers of water lined up, numbered from left to right from $1$ to $n$. Each container can hold any amount of water; initially, the $i$-th container contains $a_i$ units of water. The sum of $a_i$ is divisible by $n$.\n\nYou can apply the following operation any (possibly zero) number of times: pour any amount of water from the $i$-th container to the $j$-th container, where $i$ must be \\textbf{less} than $j$ (i.e. $i<j$). Any index can be chosen as $i$ or $j$ any number of times.\n\nDetermine whether it is possible to make the amount of water in all containers the same using this operation.",
    "tutorial": "Since the number of operations does not matter, let's find any suitable sequence of operations. Each vessel should contain $k = \\frac{\\sum a_i}{n}$ units of water. Water can only be poured to the right, so we will iterate over $i$ from $1$ to $n-1$ and pour all the excess water from the $i$-th vessel to the $(i+1)$-th. If at some point there is not enough water in the $i$-th vessel, the answer is NO.",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    k = sum(a) // n\n    for i in range(n - 1):\n        if a[i] < k:\n            print('NO')\n            return\n        a[i + 1] += a[i] - k\n        a[i] = k\n    print('YES')\n    \n    \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1931",
    "index": "C",
    "title": "Make Equal Again",
    "statement": "You have an array $a$ of $n$ integers.\n\nYou can \\textbf{no more than once} apply the following operation: select three integers $i$, $j$, $x$ ($1 \\le i \\le j \\le n$) and assign all elements of the array with indexes from $i$ to $j$ the value $x$. The price of this operation depends on the selected indices and is equal to $(j - i + 1)$ burles.\n\nFor example, the array is equal to $[1, 2, 3, 4, 5, 1]$. If we choose $i = 2, j = 4, x = 8$, then after applying this operation, the array will be equal to $[1, 8, 8, 8, 5, 1]$.\n\nWhat is the least amount of burles you need to spend to make all the elements of the array equal?",
    "tutorial": "If all the elements of the arrays are equal, then nothing additional needs to be done, and the answer is $0$. Otherwise, you need to apply the assignment operation on the segment alone. Our goal is to choose the shortest possible segment, which means to exclude as many elements as possible from the beginning and end of the segment. Note that we can exclude only equal elements, and then assign a value equal to the excluded elements on the segment. Let's find the lengths of the maximum prefix and suffix consisting of equal elements. Let's denote by $k$ the number of excluded elements, by $k_1$ - the length of the maximum suitable prefix, by $k_2$ - the maximum suitable suffix. Then if $a_0 = a_{n - 1}$, then $k = k_1 + k_2$ (exclude both prefix and suffix), otherwise $k = max(k_1, k_2)$ (exclude the longer one). The answer is $n - k$ - all non-excluded elements must be replaced so that they become equal to the excluded one.",
    "code": "def solve():\n    n = int(input())\n    a = list(map(int, input().split()))\n    i1 = 0\n    i2 = 0\n    while i1 < n and a[i1] == a[0]:\n        i1 += 1\n    while i2 < n and a[n - i2 - 1] == a[n - 1]:\n        i2 += 1\n    res = n\n    if a[0] == a[n - 1]:\n        res -= i1\n        res -= i2\n    else:\n        res -= max(i1, i2)\n    print(max(0, res))\n \n \nt = int(input())\n \n \nfor i in range(t):\n    solve()",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1931",
    "index": "D",
    "title": "Divisible Pairs",
    "statement": "Polycarp has two favorite integers $x$ and $y$ (they can be equal), and he has found an array $a$ of length $n$.\n\nPolycarp considers a pair of indices $\\langle i, j \\rangle$ ($1 \\le i < j \\le n$) beautiful if:\n\n- $a_i + a_j$ is divisible by $x$;\n- $a_i - a_j$ is divisible by $y$.\n\nFor example, if $x=5$, $y=2$, $n=6$, $a=$[$1, 2, 7, 4, 9, 6$], then the only beautiful pairs are:\n\n- $\\langle 1, 5 \\rangle$: $a_1 + a_5 = 1 + 9 = 10$ ($10$ is divisible by $5$) and $a_1 - a_5 = 1 - 9 = -8$ ($-8$ is divisible by $2$);\n- $\\langle 4, 6 \\rangle$: $a_4 + a_6 = 4 + 6 = 10$ ($10$ is divisible by $5$) and $a_4 - a_6 = 4 - 6 = -2$ ($-2$ is divisible by $2$).\n\nFind the number of beautiful pairs in the array $a$.",
    "tutorial": "Let's consider a good pair. Since $(a_i + a_j) \\bmod x = 0$, it follows that $(a_i \\bmod x + a_j \\bmod x) \\bmod x = 0$, which implies that $a_i \\bmod x + a_j \\bmod x$ is either $x$ or $0$. Therefore, for some $j$, this holds true if $a_i \\bmod x = (x - a_j \\bmod x) \\bmod x$. Since $(a_i - a_j) \\bmod y = 0$, it follows that $a_i \\bmod y - a_j \\bmod y = 0$, which implies that $a_i \\bmod y = a_j \\bmod y$. Thus, for some fixed $a_j$, all $a_i$ will fit the following criteria: $i < j$; $a_i \\bmod x = (x - a_j \\bmod x) \\bmod x$; $a_i \\bmod y = a_j \\bmod y$. We will iterate through $j$ from left to right and maintain the count of elements with specific pairs $\\langle a_i \\bmod x, a_i \\bmod y \\rangle$ using a map on the prefix.",
    "code": "def solve():\n    n, x, y = map(int, input().split())\n    a = [int(x) for x in input().split()]\n    cnt = dict()\n    ans = 0\n    for e in a:\n        xx, yy = e % x, e % y\n        ans += cnt.get(((x - xx) % x, yy), 0)\n        cnt[(xx, yy)] = cnt.get((xx, yy), 0) + 1\n    print(ans)\n    \n    \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1931",
    "index": "E",
    "title": "Anna and the Valentine's Day Gift",
    "statement": "Sasha gave Anna a list $a$ of $n$ integers for Valentine's Day. Anna doesn't need this list, so she suggests destroying it by playing a game.\n\nPlayers take turns. Sasha is a gentleman, so he gives Anna the right to make the first move.\n\n- On her turn, \\textbf{Anna must} choose an element $a_i$ from the list and reverse the sequence of its digits. For example, if Anna chose the element with a value of $42$, it would become $24$; if Anna chose the element with a value of $1580$, it would become $851$. Note that leading zeros are removed. After such a turn, the number of elements in the list does not change.\n- On his turn, \\textbf{Sasha must} extract \\textbf{two} elements $a_i$ and $a_j$ ($i \\ne j$) from the list, concatenate them in any order and insert the result back into the list. For example, if Sasha chose the elements equal to $2007$ and $19$, he would remove these two elements from the list and add the integer $200719$ or $192007$. After such a turn, the number of elements in the list decreases by $1$.\n\nPlayers can't skip turns. The game ends when Sasha can't make a move, i.e. \\textbf{after} Anna's move there is \\textbf{exactly} one number left in the list. If this integer is \\textbf{not less than} $10^m$ (i.e., $\\ge 10^m$), Sasha wins. Otherwise, Anna wins.\n\nIt can be shown that the game will always end. Determine who will win if both players play optimally.",
    "tutorial": "If the decimal representation of a number $x$ has exactly $c$ digits, then $x \\ge 10^{c - 1}$. From this, it can be concluded that Sasha is not required to maximize the final number; it is sufficient for him to maximize the number of digits in it. During his turn, Sasha does not change the total number of digits, but Anna can change it. It is easy to understand that the total number of digits cannot increase, but it can decrease if Anna removes trailing zeros from a number ($1200 \\to 21$). Now the optimal strategy for Sasha and Anna can be formulated. Anna should choose a number with the largest number of trailing zeros and remove them. Sasha should find a number with the largest number of trailing zeros and concatenate it with any other number. Thus, since $1 \\le a_i$, he will preserve the zeros of this number ($100500, 2007 \\to 1005002007$). Implementing such a solution in $O(n \\log n)$ can be done using sorting and linear traversal or by using std::set. If desired, counting sort can be used to improve the asymptotic complexity to linear.",
    "code": "#include <bits/stdc++.h>\n \n#define all(arr) arr.begin(), arr.end()\n \nusing namespace std;\n \nconst int MAXN = 200200;\n \nint n, m;\nstring arr[MAXN];\nint len[MAXN], zrr[MAXN];\n \nvoid build() {\n    memset(zrr, 0, sizeof(*zrr) * n);\n    for (int i = 0; i < n; ++i) {\n        len[i] = arr[i].size();\n        for (auto it = arr[i].rbegin(); it != arr[i].rend() && *it == '0'; ++it) {\n            ++zrr[i];\n        }\n    }\n}\n \nstring solve() {\n    int ans = 0;\n    for (int i = 0; i < n; ++i) {\n        ans += len[i] - zrr[i];\n    }\n    sort(zrr, zrr + n);\n    reverse(zrr, zrr + n);\n    for (int i = 0; i < n; ++i) {\n        if (i & 1) ans += zrr[i];\n    }\n    return (ans - 1 >= m ? \"Sasha\" : \"Anna\");\n}\n \nint main() {\n    int t; cin >> t;\n    while (t--) {\n        cin >> n >> m;\n        for (int i = 0; i < n; ++i)\n            cin >> arr[i];\n        build();\n        cout << solve() << '\\n';\n    }\n}",
    "tags": [
      "games",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1931",
    "index": "F",
    "title": "Chat Screenshots",
    "statement": "There are $n$ people in the programming contest chat. Chat participants are ordered by activity, but each person sees himself at the top of the list.\n\nFor example, there are $4$ participants in the chat, and their order is $[2, 3, 1, 4]$. Then\n\n- $1$-st user sees the order $[1, 2, 3, 4]$.\n- $2$-nd user sees the order $[2, 3, 1, 4]$.\n- $3$-rd user sees the order $[3, 2, 1, 4]$.\n- $4$-th user sees the order $[4, 2, 3, 1]$.\n\n$k$ people posted screenshots in the chat, which show the order of participants shown to this user. The screenshots were taken within a short period of time, and the order of participants has not changed.\n\nYour task is to determine whether there is a certain order that all screenshots correspond to.",
    "tutorial": "The author of the screenshot is always in the first position, so based on his screenshot, nothing can be said about his first position. The rest of the chat participants are ordered based on the real order. Let's build a graph of $n$ vertices. For each screenshot, add $n - 2$ edges. For all $2 \\le i <n$, add an edge between the vertices $a_{ji}$ and $a_{j{i + 1}}$, where $j$ is the number of the current screenshot. If there is an order that satisfies all screenshots, then topological sorting will exist in this graph, which means there will be no cycles in it. So our goal is to check the graph for acyclicity.",
    "code": "#include <iostream>\n#include <vector>\n#include <set>\n#include <queue>\n#include <algorithm>\n \nusing namespace std;\n \ntypedef long long ll;\n \nint timer = 0;\n \nvoid dfs(int v, vector<vector<int>> &g, vector<bool> &vis, vector<int> &tout) {\n    vis[v] = true;\n    for (int u: g[v]) {\n        if (!vis[u]) {\n            dfs(u, g, vis, tout);\n        }\n    }\n    tout[v] = timer++;\n}\n \nvoid solve() {\n    timer = 0;\n    int n, k;\n    cin >> n >> k;\n    vector<vector<int>> a(k, vector<int>(n));\n    vector<int> authors(k);\n    for (int i = 0; i < k; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> a[i][j];\n            a[i][j]--;\n        }\n        authors[i] = a[i][0];\n    }\n    vector<vector<int>> g(n);\n    for (int i = 0; i < k; ++i) {\n        for (int j = 1; j + 1 < n; ++j) {\n            int i1 = a[i][j], i2 = a[i][j + 1];\n            g[i1].push_back(i2);\n        }\n    }\n    vector<int> tout(n, -1);\n    vector<bool> vis(n);\n    for (int i = 0; i < n; ++i) {\n        if (tout[i] == -1) {\n            dfs(i, g, vis, tout);\n        }\n    }\n    for (int i = 0; i < k; ++i) {\n        for (int j = 1; j + 1 < n; ++j) {\n            int i1 = a[i][j], i2 = a[i][j + 1];\n            if (tout[i1] < tout[i2]) {\n                cout << \"NO\";\n                return;\n            }\n        }\n    }\n    cout << \"YES\";\n}\n \nint main() {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        solve();\n        cout << \"\\n\";\n    }\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "graphs"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1931",
    "index": "G",
    "title": "One-Dimensional Puzzle",
    "statement": "You have a one-dimensional puzzle, all the elements of which need to be put in one row, connecting with each other. All the puzzle elements are completely white and distinguishable from each other only if they have different shapes.\n\nEach element has straight borders at the top and bottom, and on the left and right it has connections, each of which can be a protrusion or a recess. You \\textbf{cannot} rotate the elements.\n\nYou can see that there are exactly $4$ types of elements. Two elements can be connected if the right connection of the left element is opposite to the left connection of the right element.\n\n\\begin{center}\nAll possible types of elements.\n\\end{center}\n\nThe puzzle contains $c_1, c_2, c_3, c_4$ elements of each type. The puzzle is considered complete if you have managed to combine \\textbf{all} elements into one long chain. You want to know how many ways this can be done.",
    "tutorial": "Note that the elements of the $3$ and $4$ types on the right have a connection type opposite to that on the left. This means that what type of connection should be at the end of the chain to attach an element of any of these types will remain the same. Therefore, elements of these types can be combined into separate chains consisting only of elements of the same type. Joining such a chain will not change the type of connection at the end. Therefore, the basis of the chain consists of elements of the $1$ and $2$ types. First, you need to make the basis of a chain of only them, and then insert an arbitrary set of chains of elements of the $3$ and $4$ types. In order to make the basis of the chain possible, it is necessary that $|c_1 - c_2| \\le 1$ be executed. Otherwise, there will be extra elements left, and the answer is $0$. The basis of the chain can start with an element of type $i$ ($1\\le i\\le 2$) if $c_i\\ge c_j$, where $j = 3 - i$ - an element of the opposite type ($1$ for $2$ and vice versa). If $c_1 = c_2$, then there are $2$ options for the basis of the chain, and they need to be counted separately. To find the number of combinations at a fixed base of the chain, we calculate two values independently, and then multiply them: $x_1$ - the number of ways to arrange chains of $3$-type elements after $1$-type elements. $x_2$ - the number of ways to arrange chains of $4$-type elements after $2$-type elements. $x_1$ and $x_2$ are calculated using the same formula, also known as the formula of balls and partitions. We want to arrange $m$ elements ($m$ is equal to $x_3$ or $x_4$, depending on which value we calculate). To arrange them, we have $n = n0 + add$ positions, where $n0$ is the number of elements of type $1$ or $2$ (similar to $m$), and $add$ is the value required to process an additional position equal to $1$ if the basis of the chain begins with an element of another type (then we can put the chain in front of it, for example, several elements of the $4$ type in front of the $1$ type element), and $0$ otherwise. The number of ways to arrange $m$ indistinguishable elements in $n$ positions is $C_{n +m - 1}^{m}$, where $C_n^k$ is the number of combinations. To calculate the answer, multiply the values of $x_1$ and $x_2$, and in the case when $c_1 = c_2$ - sum the resulting products.",
    "code": "\n#include <iostream>\n#include <vector>\n#include <set>\n#include <queue>\n#include <algorithm>\n \nusing namespace std;\n \ntypedef long long ll;\n \nconst int mod = 998244353;\n \nll pow_mod(ll x, ll p) {\n    if (p == 0) {\n        return 1;\n    }\n    if (p % 2 == 0) {\n        ll y = pow_mod(x, p / 2);\n        return (y * y) % mod;\n    }\n    return (x * pow_mod(x, p - 1)) % mod;\n}\n \nll inv(ll x) {\n    return pow_mod(x, mod - 2);\n}\n \nvector<ll> fact = {1};\n \nll cnk(ll n, ll k) {\n    ll res = fact[n];\n    res = (res * inv(fact[k])) % mod;\n    res = (res * inv(fact[n - k])) % mod;\n    return res;\n}\n \nll calc(int n1, int n2, int n3, int n4) {\n    return (cnk(n1 + n3 - 1, n3) * cnk(n2 + n4 - 1, n4)) % mod;\n}\n \nvoid solve() {\n    int n1, n2, n3, n4;\n    cin >> n1 >> n2 >> n3 >> n4;\n    if (n1 + n2 == 0) {\n        cout << (n3 == 0 || n4 == 0 ? 1 : 0) << '\\n';\n        return;\n    }\n    if (abs(n1 - n2) > 1) {\n        cout << \"0\\n\";\n        return;\n    }\n    ll res = 0;\n    if (n1 <= n2) {\n        res += calc(n1 + 1, n2, n3, n4);\n    }\n    if (n2 <= n1) {\n        res += calc(n1, n2 + 1, n3, n4);\n    }\n    cout << res % mod << '\\n';\n}\n \nint main() {\n    for (ll i = 1; i <= 4e6; ++i) {\n        fact.push_back((fact.back() * i) % mod);\n    }\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        solve();\n    }\n}",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1932",
    "index": "A",
    "title": "Thorns and Coins",
    "statement": "During your journey through computer universes, you stumbled upon a very interesting world. It is a path with $n$ consecutive cells, each of which can either be empty, contain thorns, or a coin. In one move, you can move one or two cells along the path, provided that the destination cell does not contain thorns (and belongs to the path). If you move to the cell with a coin, you pick it up.\n\n\\begin{center}\n{\\small Here, green arrows correspond to legal moves, and the red arrow corresponds to an illegal move.}\n\\end{center}\n\nYou want to collect as many coins as possible. Find the maximum number of coins you can collect in the discovered world if you start in the leftmost cell of the path.",
    "tutorial": "Let's move forward by $1$ if the next cell does not have spikes, and by $2$ otherwise. By doing so, we will visit all spike-free cells that we can reach, and thus collect all the coins in those cells. Note that if we are in cell $i$, and cells $i+1$ and $i+2$ have spikes, then we can only jump into the spikes and thus end the game. Therefore, we need to count how many coins appear in the string before the substring \"**\".",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nsigned main() {\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    ios::sync_with_stdio(false);\n \n    int t;\n    cin >> t;\n    for(int _ = 0; _ < t; ++_){\n        int n, ans = 0;\n        cin >> n;\n        string s;\n        cin >> s;\n        for (int i = 1; i < n; i++) {\n            ans += (s[i] == '@');\n            if (s[i] == '*' && s[i - 1] == '*')\n                break;\n        }\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1932",
    "index": "B",
    "title": "Chaya Calendar",
    "statement": "The Chaya tribe believes that there are $n$ signs of the apocalypse. Over time, it has been found out that the $i$-th sign occurs every $a_i$ years (in years $a_i$, $2 \\cdot a_i$, $3 \\cdot a_i$, $\\dots$).\n\nAccording to the legends, for the apocalypse to happen, the signs must occur sequentially. That is, first they wait for the first sign to occur, then strictly after it, the second sign will occur, and so on. That is, if the $i$-th sign occurred in the year $x$, the tribe starts waiting for the occurrence of the $(i+1)$-th sign, starting from the year $x+1$.\n\nIn which year will the $n$-th sign occur and the apocalypse will happen?",
    "tutorial": "The tribe will wait for the first sign in year $a_1$. They will expect the second event in some year $x > a_1$, which is divisible by $a_2$, this will happen after $a_2 - a_1 \\bmod a_2$ years. Let's maintain the number $cur$ of the year in which the $i$-th sign occurred, then the $(i+1)$-th will occur in the year $cur + a_{i+1} - cur \\bmod a_{i+1}$. Since this is the smallest year number divisible by $a_{i+1}$, which is strictly greater than $cur$.",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    cur = 0\n    for e in a:\n        cur += e - cur % e\n    print(cur)\n \n \nfor _ in range(1, int(input()) + 1):\n    solve()",
    "tags": [
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1932",
    "index": "C",
    "title": "LR-remainders",
    "statement": "You are given an array $a$ of length $n$, a positive integer $m$, and a string of commands of length $n$. Each command is either the character 'L' or the character 'R'.\n\nProcess all $n$ commands in the order they are written in the string $s$. Processing a command is done as follows:\n\n- First, output the remainder of the product of all elements of the array $a$ when divided by $m$.\n- Then, if the command is 'L', remove the leftmost element from the array $a$, if the command is 'R', remove the rightmost element from the array $a$.\n\nNote that after each move, the length of the array $a$ decreases by $1$, and after processing all commands, it will be empty.\n\nWrite a program that will process all commands in the order they are written in the string $s$ (from left to right).",
    "tutorial": "If we perform all deletions except the last one, only one element will remain. Let's find its index in the array. Now we will perform the operations in reverse order, then the deletion operations will become additions, which are much easier to maintain. We will store the remainder of the division of the product of the current segment by $m$ and multiply by the new elements when extending the segment. We will output all the obtained numbers in reverse order.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nint main() {\n    int t;\n    cin >> t;\n    forn(tt, t) {\n        int n, m;\n        cin >> n >> m;\n        vector<int> a(n);\n        forn(i, n)\n            cin >> a[i];\n        string s;\n        cin >> s;\n \n        int l = 0;\n        int r = n - 1;\n        forn(i, n - 1)\n            if (s[i] == 'L')\n                l++;\n            else\n                r--;\n        assert(l == r);\n \n        vector<int> b(n);\n        b[n - 1] = a[l] % m;\n \n        for (int i = n - 2; i >= 0; i--) {\n            if (s[i] == 'L')\n                b[i] = (b[i + 1] * a[--l]) % m;\n            else\n                b[i] = (b[i + 1] * a[++r]) % m;\n        }\n        assert(l == 0);\n        assert(r == n - 1);\n \n        forn(i, n)\n            cout << b[i] << \" \";\n        cout << endl;\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1932",
    "index": "D",
    "title": "Card Game",
    "statement": "Two players are playing an online card game. The game is played using a 32-card deck. Each card has a suit and a rank. There are four suits: clubs, diamonds, hearts, and spades. We will encode them with characters 'C', 'D', 'H', and 'S', respectively. And there are 8 ranks, in increasing order: '2', '3', '4', '5', '6', '7', '8', '9'.\n\nEach card is denoted by two letters: its rank and its suit. For example, the 8 of Hearts is denoted as 8H.\n\nAt the beginning of the game, one suit is chosen as the \\textbf{trump suit}.\n\nIn each round, players make moves like this: the first player places one of his cards on the table, and the second player must beat this card with one of their cards. After that, both cards are moved to the discard pile.\n\nA card can beat another card if both cards have the same suit and the first card has a higher rank than the second. For example, 8S can beat 4S. Additionally, a trump card can beat any non-trump card, regardless of the rank of the cards, for example, if the trump suit is clubs ('C'), then 3C can beat 9D. Note that trump cards can be beaten only by the trump cards of higher rank.\n\nThere were $n$ rounds played in the game, so the discard pile now contains $2n$ cards. You want to reconstruct the rounds played in the game, but the cards in the discard pile are shuffled. Find any possible sequence of $n$ rounds that might have been played in the game.",
    "tutorial": "Let's start by solving the problem separately for each suit, except for the trump suit. To do this, we will form the maximum possible number of pairs, after which there will be no more than one card of this suit without a pair. Thus, we will need the minimum number of trump cards to beat the non-trump cards. Now we will beat each of the remaining cards with a trump. If there are not enough trump cards, there is no solution. All that remains is to solve the problem for the remaining trumps, just as at the beginning of the solution. Note that since the total number of cards is even, and the rest of cards are paired, there will be no extra trump card left.",
    "code": "#include <bits/stdc++.h>\n \n#define long long long int\n#define DEBUG\nusing namespace std;\n \n// @author: pashka\n \nint main() {\n    ios::sync_with_stdio(false);\n    \n    int t;\n    cin >> t;\n    for (int tt = 0; tt < t; tt++) {\n        int n;\n        cin >> n;\n    \n        string suites = \"CDHS\";\n    \n        string ts;\n        cin >> ts;\n        int trump = suites.find(ts[0]);\n    \n        vector<int> bs[4];\n        for (int i = 0; i < 2 * n; i++) {\n            string s;\n            cin >> s;\n            bs[suites.find(s[1])].push_back(s[0] - '2');\n        }\n    \n        vector<string> res;\n        vector<string> left;\n        for (int i = 0; i < 4; i++) {\n            sort(bs[i].begin(), bs[i].end());\n            if (i == trump) continue;\n            if (bs[i].size() % 2 == 1) {\n                int x = bs[i].back();\n                left.push_back(string() + char('2' + x) + suites[i]);\n                bs[i].pop_back();\n            }\n            for (int j = 0; j < (int) bs[i].size(); j++) {\n                int x = bs[i][j];\n                res.push_back(string() + char('2' + x) + suites[i]);\n            }\n        }\n        if (left.size() > bs[trump].size()) {\n            cout << \"IMPOSSIBLE\\n\";\n        } else {\n            for (string s : left) {\n                res.push_back(s);\n                int x = bs[trump].back();\n                bs[trump].pop_back();\n                res.push_back(string() + char('2' + x) + suites[trump]);\n            }\n            for (int j = 0; j < (int) bs[trump].size(); j++) {\n                int x = bs[trump][j];\n                res.push_back(string() + char('2' + x) + suites[trump]);\n            }\n            for (int i = 0; i < 2 * n; i += 2) {\n                cout << res[i] << \" \" << res[i + 1] << \"\\n\";\n            }\n        }\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1932",
    "index": "E",
    "title": "Final Countdown",
    "statement": "You are in a nuclear laboratory that is about to explode and destroy the Earth. You must save the Earth before the final countdown reaches zero.\n\nThe countdown consists of $n$ ($1 \\le n \\le 4 \\cdot 10^5$) mechanical indicators, each showing one decimal digit. You noticed that when the countdown changes its state from $x$ to $x-1$, it doesn't happen in one move. Instead, each change of a single digit takes one second.\n\nSo, for example, if the countdown shows 42, then it will change to 41 in one second, because only one digit is changed, but if the countdown shows 2300, then it will change to 2299 in three seconds, because the three last digits are changed.\n\nFind out how much time is left before the countdown reaches zero.",
    "tutorial": "Let's assume that the number $s$ is initially displayed on the countdown. Let's see how many times each of the indicators will switch. Indicator number $i$ (if we number the indicators from right to left, starting with 0) will switch exactly $\\lfloor s / 10^i \\rfloor$ times. Thus, the answer is equal to $\\sum_{i=0}^{n-1} \\lfloor s / 10^i \\rfloor$. To calculate this sum, let's split the number $s$ into individual digits and add their contributions. Let the digits of the number $s$ be $s_{n-1}s_{n-2}\\ldots s_0$. The contribution of the digit $s_i$ to the final sum is $s_i\\cdot\\sum_{j=0}^i 10^j$. Thus, the answer is equal to $\\sum_{i=0}^{n-1} s_i\\cdot\\sum_{j=0}^i 10^j$. Changing the order of summation, we get $\\sum_{j=0}^{n-1} 10^j \\cdot \\sum_{j=i}^{n-1} s_i$. To calculate this sum, we need to pre-calculate the suffix sums $\\sum_{j=i}^{n-1} s_i$ (this can be done in linear time), and then add each of the sums to the corresponding decimal digit of the final number, carrying over to the higher digits (this can also be done in linear time).",
    "code": "#include <bits/stdc++.h>\n#define long long long int\n#define DEBUG\nusing namespace std;\n \n// @author: pashka\n \nint main() {\n    ios::sync_with_stdio(false);\n    \n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        reverse(s.begin(), s.end());\n        vector<int> a(n + 1);\n        for (int i = n - 1; i >= 0; i--) {\n            a[i] = a[i + 1] + (s[i] - '0');\n        }\n        string res;\n        int c = 0;\n        for (int i = 0; i < n; i++) {\n            c += a[i];\n            res += (char)(c % 10 + '0');\n            c /= 10;\n        }\n        res += (char)(c + '0');\n        while (res.back() == '0') {\n            res.pop_back();\n        }\n        reverse(res.begin(), res.end());\n        cout << res << \"\\n\";\n    }\n \n    return 0;\n}",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1932",
    "index": "F",
    "title": "Feed Cats",
    "statement": "There is a fun game where you need to feed cats that come and go. The level of the game consists of $n$ steps. There are $m$ cats; the cat $i$ is present in steps from $l_i$ to $r_i$, inclusive. In each step, you can feed all the cats that are currently present or do nothing.\n\nIf you feed the same cat more than once, it will overeat, and you will immediately lose the game. Your goal is to feed as many cats as possible without causing any cat to overeat.\n\nFind the maximum number of cats you can feed.\n\nFormally, you need to select several integer points from the segment from $1$ to $n$ in such a way that among given segments, none covers two or more of the selected points, and as many segments as possible cover one of the selected points.",
    "tutorial": "Let's use dynamic programming. Let $dp_i$ be the answer for the first $i$ moves ($dp_0 = 0$). Then there are two possible cases: we fed the cats on step $i$ or not. If we did not feed the cats on step $i$, then $dp_i = dp_{i - 1}$, because this is the best result for the first $i-1$ moves, and nothing has changed on this move. If we fed the cats on step $i$, then we could not have fed the cats later than when the first of the present cats arrived, because then it would overeat. Using the multiset structure, we will find the step $x$ at which it arrived. In this case, we will feed all the present cats and can choose the best way to feed the cats for the first $x-1$ moves. At each of the $n$ moves, we will choose the best of the two options. To maintain the multiset with the moments of the cats' arrivals, we will add them at these moments in time and remove them at the departure moments (for each $r$, we can store all $l_i$ that will leave at that moment).",
    "code": "#include <bits/stdc++.h>\n \n//#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n \ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(time(nullptr));\n \nconst ll inf = 1e18;\nconst ll M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n \nvoid solve(int tc){\n    int n, m;\n    cin >> n >> m;\n    vector<pair<int, int>> a(m);\n    vector<int> op(n + 1);\n    vector<vector<int>> del(n + 1);\n    for(auto &e: a) {\n        cin >> e.x >> e.y;\n        op[e.x]++;\n        del[e.y].emplace_back(e.x);\n    }\n    multiset<int> cur;\n    vector<int> dp(n + 1);\n    for(int i = 1; i <= n; ++i){\n        dp[i] = dp[i - 1];\n        for(int j = 0; j < op[i]; ++j){\n            cur.insert(i);\n        }\n        if(!cur.empty()){\n            dp[i] = max(dp[i], int(dp[*cur.begin() - 1] + cur.size()));\n        }\n        for(int e: del[i]){\n            cur.erase(cur.find(e));\n        }\n    }\n    cout << dp[n];\n}\n \nbool multi = true;\n \nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1932",
    "index": "G",
    "title": "Moving Platforms",
    "statement": "There is a game where you need to move through a labyrinth. The labyrinth consists of $n$ platforms, connected by $m$ passages.\n\nEach platform is at some level $l_i$, an integer number from $0$ to $H - 1$. In a single step, if you are currently on platform $i$, you can stay on it, or move to another platform $j$. To move to platform $j$ they have to be connected by the passage, and their levels have to be the same, namely $l_i = l_j$.\n\nAfter each step, the levels of all platforms change. The new level of platform $i$ is calculated as $l'_i = (l_i + s_i) \\bmod H$, for all $i$.\n\nYou start on platform $1$. Find the minimum number of steps you need to get to platform $n$.",
    "tutorial": "First, note that the event of two platforms being on the same level at a given moment does not depend on your moves. Hence, it is always optimal to get to any vertex you may need to reach the vertex $n$ as soon as possible. It means that you can simply run Dijkstra's algorithm to calculate the minimal number of moves needed to reach every vertex. The only complication is that you need to determine for some vertices $u$, $v$ and moment $t$ what is the next moment when $l'_u = l'_v$, i.e. find minimal $k$ such that $k \\ge t$ and $l_u + ks_u = l_v + ks_v \\bmod H$. That can be equivalently written as $l_u - l_v = k(s_v - s_u) \\bmod H$. $a = k'b \\bmod H$ can be solved in such way: If $a$ is not divisible by $\\gcd(H, b)$ then there is no solution. Otherwise, divide $a, b, H$ by $\\gcd(H, b)$. Name them $a', b', H'$. Then $k' = b'^{-1}a' \\bmod H$. $b'^{-1}$ can be found using extended Eucledian algorithm. The only thing remaining is to find minimal $k$ such that $k' = k \\bmod H'$ and $k \\ge t$.",
    "code": "#include <bits/stdc++.h>\n#define long long long int\n#define DEBUG\nusing namespace std;\n \n// @author: pashka\n \nstruct triple {\n    long d, x, y;\n};\n \ntriple eucl(long a, long b) {\n    if (b == 0) {\n        return {a, 1, 0};\n    }\n    long k = a / b;\n    auto [d, x, y] = eucl(b, a - k * b);\n    return {d, y, x - k * y};\n}\n \nstruct test {\n    void solve() {\n        int n, m, H;\n        cin >> n >> m >> H;\n        vector<long> l(n);\n        for (int i = 0; i < n; i++) cin >> l[i];\n        vector<long> s(n);\n        for (int i = 0; i < n; i++) cin >> s[i];\n \n        vector<vector<int>> g(n);\n        for (int i = 0; i < m; i++) {\n            int x, y;\n            cin >> x >> y;\n            x--;\n            y--;\n            g[x].push_back(y);\n            g[y].push_back(x);\n        }\n \n        const long INF = 1e18;\n        vector<long> d(n, INF);\n        d[0] = 0;\n        set<pair<long, int>> q;\n        q.insert({d[0], 0});\n        while (!q.empty()) {\n            auto p = *q.begin();\n            q.erase(p);\n            int v = p.second;\n            long t = d[v];\n            for (int u: g[v]) {\n                long a = (l[v] + (t % H) * s[v]) - (l[u] + (t % H) * s[u]);\n                a %= H;\n                if (a < 0) a += H;\n                long b = s[u] - s[v];\n                b %= H;\n                if (b < 0) b += H;\n                // a - bx = yH\n                auto [dd, x, y] = eucl(b, H);\n                // xb + yH = dd\n                if (a % dd != 0) continue;\n                x *= a / dd;\n                x %= (H / dd);\n                if (x < 0) x += H / dd;\n                long dt = x;\n                if (d[v] + dt + 1 < d[u]) {\n                    q.erase({d[u], u});\n                    d[u] = d[v] + dt + 1;\n                    q.insert({d[u], u});\n                }\n            }\n        }\n        long res = d[n - 1];\n        if (res == INF) res = -1;\n        cout << res << \"\\n\";\n    }\n};\n \nint main() {\n    ios::sync_with_stdio(false);\n \n    int n;\n    cin >> n;\n    for (int i = 0; i < n; i++) {\n        test().solve();\n    }\n    \n    return 0;\n}",
    "tags": [
      "graphs",
      "math",
      "number theory",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1933",
    "index": "A",
    "title": "Turtle Puzzle: Rearrange and Negate",
    "statement": "You are given an array $a$ of $n$ integers. You must perform the following two operations on the array (the first, then the second):\n\n- Arbitrarily rearrange the elements of the array or leave the order of its elements unchanged.\n- Choose at most one contiguous segment of elements and replace the signs of all elements in this segment with their opposites. Formally, you can choose a pair of indices $l, r$ such that $1 \\le l \\le r \\le n$ and assign $a_i = -a_i$ for all $l \\le i \\le r$ (negate elements). Note that you may choose not to select a pair of indices and leave all the signs of the elements unchanged.\n\nWhat is the \\textbf{maximum sum of the array elements} after performing these two operations (the first, then the second)?",
    "tutorial": "Neither of the operations change the absolute value of any $a_i$. Therefore, the maximum answer we can get is $|a_1| + |a_2| + \\ldots + |a_n|$. Now we will show there is a way to obtain this sum. The way is simple. Firstly use operation 1 to sort the array, so all the negative elements come before the non-negative elements. Then use operation 2 to invert the prefix of negative elements (or not perform the operation if all the elements are non-negative initially). Then we obtain an array of non-negative integers, hence the answer is indeed $|a_1| + |a_2| + \\ldots + |a_n|$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> arr(n);\n        for (int i = 0; i < n; i++) {\n            cin >> arr[i];\n        }\n        int sum = 0;\n        for (int i = 0; i < n; i++) {\n            sum += abs(arr[i]);\n        }\n        cout << sum << endl;\n    }\n    return 0;\n}\n",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1933",
    "index": "B",
    "title": "Turtle Math: Fast Three Task",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$.\n\nIn one move, you can perform either of the following two operations:\n\n- Choose an element from the array and remove it from the array. As a result, the length of the array decreases by $1$;\n- Choose an element from the array and increase its value by $1$.\n\nYou can perform any number of moves. If the current array becomes empty, then no more moves can be made.\n\nYour task is to find the \\textbf{minimum} number of moves required to make the sum of the elements of the array $a$ divisible by $3$. It is possible that you may need $0$ moves.\n\nNote that the sum of the elements of an empty array (an array of length $0$) is equal to $0$.",
    "tutorial": "Let's denote the sum of elements as $s$. If $s$ is already divisible by $3$, then the answer is $0$. The answer is $1$ in the following cases: If $s \\bmod 3 = 2$, then we can add $1$ to any element to make the sum divisible by $3$; If there exists an $a_i$ such that $s \\bmod 3 = a_i \\bmod3$, then we can remove such $a_i$ to make the sum divisible by $3$. Otherwise, if $s \\bmod 3 = 1$, we cannot achieve the required sum in one operation. We can increase any element twice, then the sum will increase by $2$ and become divisible by $3$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int k;\n        cin>>k;\n        int ACC=0;\n        bool hv=false;\n        for(int i=0;i<k;i++){\n            int x;\n            cin>>x;\n            ACC+=x;\n\t    if(x%3==1){\n\t\thv=true;\n\t    }\n        }\n        if(ACC%3==0){\n            cout<<0<<endl;\n        }else if(ACC%3==2){\n            cout<<1<<endl;\n        }else{\n            if(hv==true){\n                cout<<1<<endl;\n            }else{\n                cout<<2<<endl;\n            }\n        }\n    }\n}",
    "tags": [
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1933",
    "index": "C",
    "title": "Turtle Fingers: Count the Values of k",
    "statement": "You are given three \\textbf{positive} integers $a$, $b$ and $l$ ($a,b,l>0$).\n\nIt can be shown that there always exists a way to choose \\textbf{non-negative} (i.e. $\\ge 0$) integers $k$, $x$, and $y$ such that $l = k \\cdot a^x \\cdot b^y$.\n\nYour task is to find the number of distinct possible values of $k$ across all such ways.",
    "tutorial": "Notice that there are not so many suitable values of $x$ and $y$ (since $2 \\le a, b$ and $2^{20}=1\\ 048\\ 576$). This allows us to iterate through all suitable pairs of $x$ and $y$ and thus find all different suitable $k$.",
    "code": "#include <bits/stdc++.h>\n#define int long long\nusing namespace std;\n\nvoid solve(int tc){\n    int a, b, l;\n    cin >> a >> b >> l;\n    set<int> ans;\n    for(int i = 0; i <= 34; ++i){\n        int x = l;\n        bool fail = false;\n        for(int _ = 0; _ < i; ++_){\n            if(x % a){\n                fail = true;\n                break;\n            }\n            x /= a;\n        }\n        if(fail) break;\n        while(true){\n            ans.insert(x);\n            if(x % b) break;\n            x /= b;\n        }\n    }\n    cout << ans.size();\n}\n \nbool multi = true;\n \nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1933",
    "index": "D",
    "title": "Turtle Tenacity: Continual Mods",
    "statement": "Given an array $a_1, a_2, \\ldots, a_n$, determine whether it is possible to \\textbf{rearrange its elements} into $b_1, b_2, \\ldots, b_n$, such that $b_1 \\bmod b_2 \\bmod \\ldots \\bmod b_n \\neq 0$.\n\nHere $x \\bmod y$ denotes the remainder from dividing $x$ by $y$. Also, the modulo operations are calculated from left to right. That is, $x \\bmod y \\bmod z = (x \\bmod y) \\bmod z$. For example, $2024 \\bmod 1000 \\bmod 8 = (2024 \\bmod 1000) \\bmod 8 = 24 \\bmod 8 = 0$.",
    "tutorial": "Sort the array in non-decreasing order. Now, assume $a_1 \\le a_2 \\le \\ldots \\le a_n$. If $a_1 \\neq a_2$, the minimum is unique. Therefore, place $a_1$ at the front, and the result after all modulo operations is just $a_1 > 0$. Hence the answer is yes for this case. If $a_1 = a_2$ and there exists some element $a_x$ such that $a_x \\not\\equiv 0 \\pmod {a_1}$, then a possible solution is rearranging the array to $[a_x, a_1, a_2, \\ldots, a_{x-1}, a_{x+1}, \\ldots, a_n]$. Since $a_x \\bmod a_1 < a_1$, $a_x \\bmod a_1$ is the minimum among the other elements and the result after all modulo operations equals $a_x \\bmod a_1 > 0$. Hence the answer is yes for this case. Otherwise (if all elements are multiples of the minimum) the answer is no, because any element modulo the minimum equals $0$, and at least one of the minimums must not be the first element. So after passing through two minimums we are guaranteed to get a $0$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--) {\n        int n;\n        cin >> n;\n        int a[n];\n        for(int i=0; i<n; i++) cin >> a[i];\n        sort(a, a + n);\n        if(a[0] != a[1]) {\n            cout << \"YES\\n\";\n        }\n        else {\n            bool PASS = 0;\n            for(int i=1; i<n; i++) {\n                if(a[i] % a[0] != 0) PASS = 1;\n            }\n            if(PASS) cout << \"YES\\n\";\n            else cout << \"NO\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1933",
    "index": "E",
    "title": "Turtle vs. Rabbit Race: Optimal Trainings",
    "statement": "Isaac begins his training. There are $n$ running tracks available, and the $i$-th track ($1 \\le i \\le n$) consists of $a_i$ equal-length sections.\n\nGiven an integer $u$ ($1 \\le u \\le 10^9$), finishing each section can increase Isaac's ability by a certain value, described as follows:\n\n- Finishing the $1$-st section increases Isaac's performance by $u$.\n- Finishing the $2$-nd section increases Isaac's performance by $u-1$.\n- Finishing the $3$-rd section increases Isaac's performance by $u-2$.\n- $\\ldots$\n- Finishing the $k$-th section ($k \\ge 1$) increases Isaac's performance by $u+1-k$. (The value $u+1-k$ can be negative, which means finishing an extra section decreases Isaac's performance.)\n\nYou are also given an integer $l$. You must choose an integer $r$ such that $l \\le r \\le n$ and Isaac will finish \\textbf{each} section of \\textbf{each} track $l, l + 1, \\dots, r$ (that is, a total of $\\sum_{i=l}^r a_i = a_l + a_{l+1} + \\ldots + a_r$ sections).\n\nAnswer the following question: what is the optimal $r$ you can choose that the increase in Isaac's performance is maximum possible?\n\nIf there are multiple $r$ that maximize the increase in Isaac's performance, output the \\textbf{smallest} $r$.\n\nTo increase the difficulty, you need to answer the question for $q$ different values of $l$ and $u$.",
    "tutorial": "Notice that if we choose some $r$ such that the sum of $a_l, a_{l+1}, \\dots, a_r$ does not exceed $u$, then completing each of the sections will increase our abilities. Using prefix sums and binary search, we will find the largest such $r$. Smaller values will increase our abilities by a smaller amount, so there is no point in checking them. However, it is worth considering the value $r' = r+1$. Despite the fact that some of the sections of the $r'$ track will only decrease our abilities, the overall increase may be positive (for example, if the increases on the $r'$ track are [$3, 2, 1, 0, -1$]). Considering following values is pointless, as completing all following tracks will only decrease our abilities. Also, for finding the answer, ternary search can be used.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n#define int long long \n#define double long double\n\nvoid solve(int tc) {\n  int n;\n  cin >> n;\n  int a[n + 1];\n  for(int i = 1; i <= n; i++) cin >> a[i];\n  int ps[n + 1];\n  ps[0] = 0;\n  for(int i = 1; i <= n; i++) ps[i] = ps[i - 1] + a[i];\n  int q;\n  cin >> q;\n  while(q--) {\n    int l, u;\n    cin >> l >> u;\n    int lb = l, rb = n;\n    while(lb < rb) {\n      int mid = (lb + rb + 1) >> 1;\n      if(ps[mid] - ps[l - 1] <= u) lb = mid;\n      else rb = mid - 1;\n    }\n    int maxu = -1e18, optid;\n    for(int i = max(l, lb - 2); i <= min(n, lb + 2); i++) {\n      int t = ps[i] - ps[l - 1];\n      int ut = (u + (u - t + 1)) * t / 2;\n      if(ut > maxu) {\n        maxu = ut;\n        optid = i;\n      }\n    }\n    cout << optid << \" \";\n  }\n}\n\nsigned main() {\n  int t = 1; cin >> t;\n  for(int i = 1; i <= t; i++){\n    solve(i);\n    cout << \"\\n\";\n  }\n}",
    "tags": [
      "binary search",
      "implementation",
      "math",
      "ternary search"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1933",
    "index": "F",
    "title": "Turtle Mission: Robot and the Earthquake",
    "statement": "The world is a grid with $n$ rows and $m$ columns. The rows are numbered $0, 1, \\ldots, n-1$, while the columns are numbered $0, 1, \\ldots, m-1$. In this world, the columns are \\textbf{cyclic} (i.e. the top and the bottom cells in each column are adjacent). The cell on the $i$-th row and the $j$-th column ($0 \\le i < n, 0 \\le j < m$) is denoted as $(i,j)$.\n\n\\textbf{At time $0$}, the cell $(i,j)$ (where $0 \\le i < n, 0 \\le j < m$) contains either a \\textbf{rock} or \\textbf{nothing}. The state of cell $(i,j)$ can be described using the integer $a_{i,j}$:\n\n- If $a_{i,j} = 1$, there is a rock at $(i,j)$.\n- If $a_{i,j} = 0$, there is nothing at $(i,j)$.\n\nAs a result of aftershocks from the earthquake, the columns follow tectonic plate movements: each column moves cyclically \\textbf{upwards} at a velocity of $1$ cell per unit of time. Formally, for some $0 \\le i < n, 0 \\le j < m$, if $(i,j)$ contains a rock at the moment, it will move from $(i, j)$ to $(i - 1, j)$ (or to $(n - 1, j)$ if $i=0$).\n\nThe robot called RT is initially positioned at $(0,0)$. It has to go to $(n-1,m-1)$ to carry out an earthquake rescue operation (to the bottom rightmost cell). The earthquake doesn't change the position of the robot, they only change the position of rocks in the world.\n\nLet RT's current position be $(x,y)$ ($0 \\le x < n, 0 \\le y < m$), it can perform the following operations:\n\n- Go one cell cyclically upwards, i.e. from $(x,y)$ to $((x+n-1) \\bmod n, y)$ using $1$ unit of time.\n- Go one cell cyclically downwards, i.e. $(x,y)$ to $((x+1) \\bmod n, y)$ using $1$ unit of time.\n- Go one cell to the right, i.e. $(x,y)$ to $(x, y+1)$ using $1$ unit of time. (RT may perform this operation only if $y < m-1$.)\n\n\\textbf{Note that RT cannot go left using the operations nor can he stay at a position.}\n\nUnfortunately, RT will explode upon colliding with a rock. As such, when RT is at $(x,y)$ and there is a rock at $((x+1) \\bmod n, y)$ or $((x+2) \\bmod n, y)$, RT cannot move down or it will be hit by the rock.\n\nSimilarly, if $y+1 < m$ and there is a rock at $((x+1) \\bmod n, y+1)$, RT cannot move right or it will be hit by the rock.\n\nHowever, it is worth noting that if there is a rock at $(x \\bmod n, y+1)$ and $((x+1) \\bmod n, y)$, RT can still move right safely.\n\nFind the minimum amount of time RT needs to reach $(n-1,m-1)$ without colliding with any rocks. If it is impossible to do so, output $-1$.",
    "tutorial": "Idea: erniepsycholone, prepared: erniepsycholone View the task in a relative perspective, with robot RT and the ending location moving downwards instead of rocks moving upwards.",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1933",
    "index": "F",
    "title": "Turtle Mission: Robot and the Earthquake",
    "statement": "The world is a grid with $n$ rows and $m$ columns. The rows are numbered $0, 1, \\ldots, n-1$, while the columns are numbered $0, 1, \\ldots, m-1$. In this world, the columns are \\textbf{cyclic} (i.e. the top and the bottom cells in each column are adjacent). The cell on the $i$-th row and the $j$-th column ($0 \\le i < n, 0 \\le j < m$) is denoted as $(i,j)$.\n\n\\textbf{At time $0$}, the cell $(i,j)$ (where $0 \\le i < n, 0 \\le j < m$) contains either a \\textbf{rock} or \\textbf{nothing}. The state of cell $(i,j)$ can be described using the integer $a_{i,j}$:\n\n- If $a_{i,j} = 1$, there is a rock at $(i,j)$.\n- If $a_{i,j} = 0$, there is nothing at $(i,j)$.\n\nAs a result of aftershocks from the earthquake, the columns follow tectonic plate movements: each column moves cyclically \\textbf{upwards} at a velocity of $1$ cell per unit of time. Formally, for some $0 \\le i < n, 0 \\le j < m$, if $(i,j)$ contains a rock at the moment, it will move from $(i, j)$ to $(i - 1, j)$ (or to $(n - 1, j)$ if $i=0$).\n\nThe robot called RT is initially positioned at $(0,0)$. It has to go to $(n-1,m-1)$ to carry out an earthquake rescue operation (to the bottom rightmost cell). The earthquake doesn't change the position of the robot, they only change the position of rocks in the world.\n\nLet RT's current position be $(x,y)$ ($0 \\le x < n, 0 \\le y < m$), it can perform the following operations:\n\n- Go one cell cyclically upwards, i.e. from $(x,y)$ to $((x+n-1) \\bmod n, y)$ using $1$ unit of time.\n- Go one cell cyclically downwards, i.e. $(x,y)$ to $((x+1) \\bmod n, y)$ using $1$ unit of time.\n- Go one cell to the right, i.e. $(x,y)$ to $(x, y+1)$ using $1$ unit of time. (RT may perform this operation only if $y < m-1$.)\n\n\\textbf{Note that RT cannot go left using the operations nor can he stay at a position.}\n\nUnfortunately, RT will explode upon colliding with a rock. As such, when RT is at $(x,y)$ and there is a rock at $((x+1) \\bmod n, y)$ or $((x+2) \\bmod n, y)$, RT cannot move down or it will be hit by the rock.\n\nSimilarly, if $y+1 < m$ and there is a rock at $((x+1) \\bmod n, y+1)$, RT cannot move right or it will be hit by the rock.\n\nHowever, it is worth noting that if there is a rock at $(x \\bmod n, y+1)$ and $((x+1) \\bmod n, y)$, RT can still move right safely.\n\nFind the minimum amount of time RT needs to reach $(n-1,m-1)$ without colliding with any rocks. If it is impossible to do so, output $-1$.",
    "tutorial": "By viewing the robot's movement relative to the rocks, Robot RT's three moves become as follows: Up: Stationary Down, $(x,y)$ to $((x+2) \\bmod n, y)$ Right, $(x,y)$ to $((x+1) \\bmod n, y+1)$ As staying stationary is not necessary now when we are finding the minimum time, we can run a bfs/dp from $(0,0)$ to find the minimum time required to reach every grid in the second last column $(x mod n,m-2)$. Finally, choose the best among all n tiles after waiting for the endpoint to cycle back.",
    "code": "#include<bits/stdc++.h>\n#define int long long\nusing namespace std;\n\nsigned main(){\n    int t;\n    cin >> t;\n    while (t--){\n        int n, m;\n    \tcin >> n >> m;\n    \tbool a[n][m + 1];\n    \tfor (int i = 0; i < n; i++) {\n    \t\tfor (int j = 1; j <= m; j++) {\n    \t\t\tcin >> a[i][j];\n    \t\t}\n    \t}\n    \tint dp[n][m + 1];\n    \tfor (int i = 0; i < n; i++) {\n    \t\tfor (int j = 0; j <= m; j++) {\n    \t\t\tdp[i][j] = INT_MAX;\n    \t\t}\n    \t}\n    \tdp[0][1] = 0;\n    \tfor (int i = 1; i <= m; i++) {\n    \t\tfor (int j = 0; j < n; j++) {\n    \t\t\tif (a[j][i]){\n    \t\t\t    continue;\n    \t\t\t}\n    \t\t\tdp[j][i] = min(dp[j][i], dp[(j - 1 + n) % n][i - 1] + 1); \n    \t\t}\n    \t\tfor (int j = 0; j < 3 * n; j++) {\n    \t\t\tif (a[j % n][i] || a[(j - 1 + n) % n][i]){\n    \t\t\t    continue;\n    \t\t\t}\n    \t\t\tdp[j % n][i] = min(dp[j % n][i], dp[(j - 2 + n) % n][i] + 1);\n    \t\t}\n    \t}\n    \tint ans = INT_MAX;\n    \tfor (int i = 0; i < n; i++) {\n    \t\tif (dp[i][m] == INT_MAX){\n    \t\t    continue;\n    \t\t}\n    \t\tint npos = ((n - 1) + dp[i][m]) % n;\n    \t\tif (npos < i) npos += n;\n    \t\tint cur = dp[i][m] + min(npos - i, n - (npos - i));\n    \t\tans = min(ans, cur);\n    \t}\n    \tif(ans == INT_MAX){\n    \t    cout << -1 << endl;\n    \t}else{\n    \t    cout << ans << endl;\n    \t}\n    }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1933",
    "index": "G",
    "title": "Turtle Magic: Royal Turtle Shell Pattern",
    "statement": "Turtle Alice is currently designing a fortune cookie box, and she would like to incorporate the theory of LuoShu into it.\n\nThe box can be seen as an $n \\times m$ grid ($n, m \\ge 5$), where the rows are numbered $1, 2, \\dots, n$ and columns are numbered $1, 2, \\dots, m$. Each cell can either be \\textbf{empty} or have a single fortune cookie of one of the following shapes: \\textbf{circle} or \\textbf{square}. The cell at the intersection of the $a$-th row and the $b$-th column is denoted as $(a, b)$.\n\nInitially, the entire grid is empty. Then, Alice performs $q$ operations on the fortune cookie box. The $i$-th operation ($1 \\le i \\le q$) is as follows: specify a currently empty cell $(r_i,c_i)$ and a shape (circle or square), then put a fortune cookie of the specified shape on cell $(r_i,c_i)$. Note that after the $i$-th operation, the cell $(r_i,c_i)$ is no longer empty.\n\nBefore all operations \\textbf{and} after each of the $q$ operations, Alice wonders what the number of ways to place fortune cookies in \\textbf{all remaining empty cells} is, such that the following condition is satisfied:\n\nNo three consecutive cells (in horizontal, vertical, and both diagonal directions) contain cookies of the same shape. Formally:\n\n- There does not exist any $(i,j)$ satisfying $1 \\le i \\le n, 1 \\le j \\le m-2$, such that there are cookies of the same shape in cells $(i,j), (i,j+1), (i,j+2)$.\n- There does not exist any $(i,j)$ satisfying $1 \\le i \\le n-2, 1 \\le j \\le m$, such that there are cookies of the same shape in cells $(i,j), (i+1,j), (i+2,j)$.\n- There does not exist any $(i,j)$ satisfying $1 \\le i \\le n-2, 1 \\le j \\le m-2$, such that there are cookies of the same shape in cells $(i,j), (i+1,j+1), (i+2,j+2)$.\n- There does not exist any $(i,j)$ satisfying $1 \\le i \\le n-2, 1 \\le j \\le m-2$, such that there are cookies of the same shape in cells $(i,j+2), (i+1,j+1), (i+2,j)$.\n\nYou should output all answers modulo $998\\,244\\,353$. Also note that it is possible that after some operations, the condition is already not satisfied with the already placed candies, in this case you should output $0$.",
    "tutorial": "We claim that there are only $8$ configurations that satisfy the condition. The proof is as follows. Firstly, consider a $2 \\times 2$ subgrid that does not lie on any of the grid's corners. Claim 1. Within the $2 \\times 2$ subgrid, there must be 2 Os and 2 Xs. Proof of Claim 1. Assume the contrary that there are 3 Os or 4 Os. (The case with 3 Xs or 4 Xs is done too due to symmetry.) Then, after some logical deduction we will end up with 3 consecutive Xs, as illustrated in the following figure. The condition is not satisfied, hence there is a contradiction and there must be 2 Os and 2 Xs within a $2 \\times 2$ subgrid that does not lie on any of the grid's corners. Next, consider a $3 \\times 3$ subgrid that does not lie on any of the grid's corners. Claim 2. Within the $3 \\times 3$ subgrid, at least one $2 \\times 2$ sub-subgrid is one of the four patterns below. We will call the following $2 \\times 2$ patterns good patterns. Proof of Claim 2. Assume the contrary that none of the 4 sub-subgrids in the $3 \\times 3$ subgrid are one of the four given patterns. This naturally means every two cells which share an edge have different shapes. This gives the following two patterns: The diagonals have the same shape, so the condition is not satisfied. There is a contradiction, hence the claim is true. Next, consider a good $2 \\times 2$ subgrid that does not lie on any of the grid's corners. (We have proved its existence in Claim 2.) Finally, it is possible to uniquely extend a good subgrid to the rest of the grid. For example, you can see in the illustration below, after a few unique logical deductions the grey pattern on the top can tesselate itself a few times, and this can be infinitely repeated. Therefore, the entire grid must be tesselations of one of the four good patterns. The first two patterns may be shifted one column to the right, and the last two patterns may be shifted one column downwards. So there are a total of $4 \\times 2 = 8$ ways to satisfy the condition. Specifically, the $8$ ways for $n = 5, m =5$ are as follows: As for some implementation details, the following $8$ statements each correspond to one $n \\times m$ configuration that satisfies the condition. $a_{i,j}$ represents whether the cell on the $i$-th row and the $j$-th column ($1 \\le i \\le n, 1 \\le j \\le m$) has a circle-shaped fortune cookie. $a_{i,j} = 1$ iff $i + \\left \\lceil \\frac{j}{2} \\right \\rceil$ is odd. $a_{i,j} = 1$ iff $i + \\left \\lceil \\frac{j}{2} \\right \\rceil$ is even. $a_{i,j} = 1$ iff $i + \\left \\lfloor \\frac{j}{2} \\right \\rfloor$ is odd. $a_{i,j} = 1$ iff $i + \\left \\lfloor \\frac{j}{2} \\right \\rfloor$ is even. $a_{i,j} = 1$ iff $j + \\left \\lceil \\frac{i}{2} \\right \\rceil$ is odd. $a_{i,j} = 1$ iff $j + \\left \\lceil \\frac{i}{2} \\right \\rceil$ is even. $a_{i,j} = 1$ iff $j + \\left \\lfloor \\frac{i}{2} \\right \\rfloor$ is odd. $a_{i,j} = 1$ iff $j + \\left \\lfloor \\frac{i}{2} \\right \\rfloor$ is even. Discussion: Try to solve the problem for general $n, m$. Specifically that includes the cases when $1 \\le \\min(n, m) \\le 4$.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\nvoid solve(int tc) { \n  int n, m, q;\n  cin >> n >> m >> q;\n  bool b[8] = {1, 1, 1, 1, 1, 1, 1, 1};\n  int ans = 8;\n  cout << ans << '\\n';\n  while(q--) {\n    int r, c;\n    cin >> r >> c;\n    string shape;\n    cin >> shape;\n    if((r + (c+1) / 2) % 2) {\n      b[0] &= (shape == \"circle\");\n      b[1] &= (shape == \"square\");\n    }\n    else {\n      b[0] &= (shape == \"square\");\n      b[1] &= (shape == \"circle\");\n    }\n    if((r + c / 2) % 2) {\n      b[2] &= (shape == \"circle\");\n      b[3] &= (shape == \"square\");\n    }\n    else {\n      b[2] &= (shape == \"square\");\n      b[3] &= (shape == \"circle\");\n    }\n\n    if((c + (r+1) / 2) % 2) {\n      b[4] &= (shape == \"circle\");\n      b[5] &= (shape == \"square\");\n    }\n    else {\n      b[4] &= (shape == \"square\");\n      b[5] &= (shape == \"circle\");\n    }\n    if((c + r / 2) % 2) {\n      b[6] &= (shape == \"circle\");\n      b[7] &= (shape == \"square\");\n    }\n    else {\n      b[6] &= (shape == \"square\");\n      b[7] &= (shape == \"circle\");\n    }\n    ans = 0;\n    for(int i = 0; i < 8; i++) ans += b[i];\n    cout << ans << '\\n';\n  }\n}\n\nint main() {\n  int t; \n  cin >> t;\n  for(int i = 1; i <= t; i++) solve(i);\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "dfs and similar",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1934",
    "index": "A",
    "title": "Too Min Too Max",
    "statement": "Given an array $a$ of $n$ elements, find the maximum value of the expression:\n\n$$|a_i - a_j| + |a_j - a_k| + |a_k - a_l| + |a_l - a_i|$$\n\nwhere $i$, $j$, $k$, and $l$ are four \\textbf{distinct} indices of the array $a$, with $1 \\le i, j, k, l \\le n$.\n\nHere $|x|$ denotes the absolute value of $x$.",
    "tutorial": "What will be answer if there were only $4$ elements in the array? Suppose if there were only $4$ elements in the array. Let them be $a \\leq b \\leq c \\leq d$. Then the answer will be maximum of the three cases which are listed as follows:- $|a-b|+|b-c|+|c-d|+|d-a| = 2*d - 2*a$ $|a-b|+|b-d|+|d-c|+|c-a| = 2*d-2*a$ $|a-c|+|c-b|+|b-d|+|d-a| = 2*(d+c)-2*(a+b)$ so clearly $2*(d+c)-2*(a+b)$ is the maximum. So, to maximize this we can set $d$, $c$ as large as possible and $a$, $b$ as small as possible i.e. $d=a_n$, $c=a_{n-1}$, $b=a_{2}$ and $a=a_{1}$ where $a_i$ means $i^{th}$ element in sorted order of given array.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n    a = sorted(a)\n    ans = 2 * (a[n - 1] - a[0] + a[n - 2] - a[1])\n    print(ans)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1934",
    "index": "B",
    "title": "Yet Another Coin Problem",
    "statement": "You have $5$ different types of coins, each with a value equal to one of the first $5$ triangular numbers: $1$, $3$, $6$, $10$, and $15$. These coin types are available in abundance. Your goal is to find the minimum number of these coins required such that their total value sums up to exactly $n$.\n\nWe can show that the answer always exists.",
    "tutorial": "At max how many $1$, $3$, $6$, $10$ are required? Fact: You will never need more than $2$ ones, $1$ threes, $4$ sixes and $2$ tens. Reason: For $1$: Suppose if you used $k$ > $2$ ones, then you could have used one $3$ and $k$ - $3$ ones. For $3$: Suppose if you used $k$ > $1$ threes, then you could have used one $6$ and $k$ - $2$ threes. For $6$: Suppose if you used $k$ > $4$ sixes, then you could have used two $15$'s and $k$ - $5$ sixes. For $10$: Suppose if you used $k$ > $2$ tens, then you could have used two $15$'s and $k$ - $3$ tens. now since bound on their count is less, we can bruteforce on these count. When will the greedy logic of choosing the higher-valued coin first work? Fact $1$: If coins of value $1$, $3$, $6$ and $15$ were only present the greedy logic of selecting the higher valued first would work. Reason: We use coins of value one at most $2$ times, coins of value three at most $1$ time, coins of value six at most $2$ times (if it was used $3$ times, it would be better to use two coins $15 + 3$) But we can't use the coin of value $3$ and both coins of value $6$ simultaneously, because we would prefer just using $15$. It means that these coins may sum up to $1 + 1 + 3 + 6 = 11$ or $1 + 1 + 6 + 6 = 14$ at max. So, we may use the value $15$ greedily, because the remaining part is less than $15$. When we are left with only the values $1$, $3$, and $6$, greedily solving is obviously correct, because each coin is a divisor of the next coin. Fact $2$: We don't need more than $2$ ten coins. Reason: Better to use $2$ fifteen coins instead of $3$ ten coins. Using the above two facts it can be shown that the answer will have $k < 3$ ten coin, therefore, answer = $\\min$($\\text{answer}(n-10*k)+k$ assuming $1$, $3$, $6$ and $15$ coins are only present).",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint getAns(int n){\n    int ans=0;\n    ans+=n/15;\n    n%=15;\n    ans+=n/6;\n    n%=6;\n    ans+=n/3;\n    n%=3;\n    ans+=n;\n    return ans;\n}\n \nint main(){\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n \n    int testcases;\n    cin>>testcases;\n    for(int i=1;i<=testcases;i++){\n        int n;cin>>n;\n        if(n<10){\n            cout<<getAns(n)<<endl;\n        }else if(n<20){\n            cout<<min(getAns(n),getAns(n-10)+1)<<endl;\n        }else{\n            cout<<min({getAns(n),getAns(n-10)+1,getAns(n-20)+2})<<endl;\n        }\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1934",
    "index": "C",
    "title": "Find a Mine",
    "statement": "\\textbf{This is an interactive problem.}\n\nYou are given a grid with $n$ rows and $m$ columns. The coordinates $(x, y)$ represent the cell on the grid, where $x$ ($1 \\leq x \\leq n$) is the row number counting from the top and $y$ ($1 \\leq y \\leq m$) is the column number counting from the left. It is guaranteed that there are exactly $2$ mines in the grid at \\textbf{distinct} cells, denoted as $(x_1, y_1)$ and $(x_2, y_2)$. You are allowed to make no more than $4$ queries to the interactor, and after these queries, you need to provide the location of \\textbf{one of the mines}.\n\nIn each query, you can choose any grid cell $(x, y)$, and in return, you will receive the minimum Manhattan distance from both the mines to the chosen cell, i.e., you will receive the value $\\min(|x-x_1|+|y-y_1|, |x-x_2|+|y-y_2|)$.\n\nYour task is to determine the location of one of the mines after making the queries.",
    "tutorial": "After querying \"$?$ $1$ $1$\" What do we know about the location of mines? If the answer is $a_1$ the location of one of the mines is $(x, y)$ such that $x+y = a_1+2$. First, we query \"$?$ $1$ $1$\" then you get a value $a_1$ and you know that at least one of the mine is on the line $x+y=a_1+2$. Now we make two more queries on both ends of this line where it touches the grid. After these two queries, we get two possible locations of the mine. We query one of these positions if we receive $0$ as the answer then this location otherwise the other location is the answer. Reason: One of that two locations contains a mine. The other mine could spoil the result of the query only from one end. If it was closer from the other mine to both of the ends, it would mean that going from one end to the other is shorter through that mine, than through the diagonal. That's impossible. What if we made the second query as \"$?$ $n$ $m$\"? If the answer is $a_2$ the location of one of the mines is $(x, y)$ such that $x+y = n+m-a_2$. Using Hint $1$ and Hint $2$ if we get the same line equation i.e. $n+m-a_2=a_1-2$ we can just query one of the endpoints of this line and get the answer. Otherwise, we can query \"$?$ $1$ $m$\" and we will get one more line perpendicular to the earlier two. One of the mines has to be on this line therefore there will be a mine either on the intersection of line we got from query $1$ and query $3$ or on the intersection of line we got from query $2$ and query $3$. We can make our next query on any of these intersections if we get the answer as $0$, then this point is the answer otherwise the other point is the answer.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n \nusing ll = long long;\n \nll query(ll x, ll y) {\n    cout << \"? \" << x << ' ' << y << endl;\n    ll d;\n    cin >> d;\n    return d;\n}\n \nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    \n    ll t;\n    cin >> t;\n    \n    while (t--) {\n        ll n, m;\n        cin >> n >> m;\n        \n        ll sum1 = query(1, 1) + 2;\n        ll sum2 = n + m - query(n, m);\n        ll dif1 = query(1, m) + 1 - m;\n        \n        auto simplify = [&](ll num, ll lim)->ll{\n            return max(min(num, lim), 1LL);\n        };\n        ll x1 = simplify((sum1+dif1)/2, n), y1 = simplify((sum1-dif1)/2, m);\n        ll x2 = simplify((sum2+dif1)/2, n), y2 = simplify((sum2-dif1)/2, m);\n        \n        if (query(x1, y1)) cout << \"! \" << x2 << ' ' << y2 << endl;\n        else cout << \"! \" << x1 << ' ' << y1 << endl;\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "geometry",
      "greedy",
      "interactive",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1934",
    "index": "D1",
    "title": "XOR Break --- Solo Version",
    "statement": "\\textbf{This is the solo version of the problem. Note that the solution of this problem may or may not share ideas with the solution of the game version. You can solve and get points for both versions independently.}\n\n\\textbf{You can make hacks only if both versions of the problem are solved.}\n\nGiven an integer variable $x$ with the initial value of $n$. A single break operation consists of the following steps:\n\n- Choose a value $y$ such that $0 \\lt y \\lt x$ and $0 \\lt (x \\oplus y) \\lt x$.\n- Update $x$ by either setting $x = y$ or setting $x = x \\oplus y$.\n\nDetermine whether it is possible to transform $x$ into $m$ using a maximum of $63$ break operations. If it is, provide the sequence of operations required to achieve $x = m$.You don't need to minimize the number of operations.\n\nHere $\\oplus$ denotes the bitwise XOR operation.",
    "tutorial": "To generate any possible $m$, it takes at most two operations. Let's determine the achievable values of $m$ for a given $n$. If $n$ is a perfect power of $2$, then it cannot be broken down further, and no $m < n$ is achievable. Otherwise, if $n$ has at least two set bits, let's denote the most significant bit as $a$ and the second most significant bit as $b$. Fact 1: All $m$ values less than $n$ are achievable if their most significant bit does not lie between $b+1$ and $a-1$. Reason: For instance, $1001????$ can be decomposed into $1000????$ and $0001????$, or $1001????$ and $0000????$. In either case, we can never flip the $6^{th}$ or $7^{th}$ bit. Using the above fact, we can break the problem into two cases: Case 1: If the most significant bit of $m$ is at position $\\leq b$. Perform the first operation as $2^{b+1} - 1$ and $n \\oplus (2^{b+1} - 1)$ ($10001????$ -> $10000????$ and $000011111$ in binary form). Then, any submask of $2^{b+1} - 1$ can be created in the next operation. Case 2: If the most significant bit of $m$ is at position $a$. If the most significant bit of $m$ is at position $a$, then $m$ can be obtained in one operation as $m$ and $m \\oplus n$, since $m < n$ as given in the question, and $n \\oplus m$ has its most significant bit $< a$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n \nusing ll = long long;\n \nint main() {\n    ios::sync_with_stdio(false), cin.tie(nullptr);\n    \n    ll t;\n    cin >> t;\n    \n    while (t--) {\n        ll n, m;\n        cin >> n >> m;\n        \n        ll hi = 0, sec_hi = 0;\n        for (ll p = (1LL<<62); p > 0; p >>= 1) {\n            if (p & n) {\n                if (!hi) hi = p;\n                else if (!sec_hi) sec_hi = p;\n            }\n        }\n        bool flag = (sec_hi && ((m & hi) || (m < sec_hi*2)));\n        if (!flag) {\n            cout << -1 << '\\n';\n            continue;\n        }\n        vector<ll> ans = {n, m};\n        if (!(m & hi) && !(m & sec_hi)) ans = {n, m^sec_hi, m};\n        \n        cout << (ll)ans.size()-1 << '\\n';\n        for (auto &x: ans) cout << x << ' ';\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1934",
    "index": "D2",
    "title": "XOR Break --- Game Version",
    "statement": "\\textbf{This is an interactive problem.}\n\n\\textbf{This is the game version of the problem. Note that the solution of this problem may or may not share ideas with the solution of the solo version. You can solve and get points for both versions independently.}\n\nAlice and Bob are playing a game. The game starts with a positive integer $n$, with players taking turns. On each turn of the game, the following sequence of events takes place:\n\n- The player having the integer $p$ breaks it into two integers $p_{1}$ and $p_{2}$, where $0 \\lt p_{1} \\lt p$, $0 \\lt p_{2} \\lt p$ and $p_{1} \\oplus p_{2} = p$.\n- If no such $p_{1}$, $p_{2}$ exist, the player loses.\n- Otherwise, the opponent does either select the integer $p_{1}$ or $p_{2}$.\n- The game continues with the selected integer. The opponent will try to break it.\n\nAs Alice, your goal is to win. You can execute a maximum of $63$ break operations. You have the choice to play first or second. The system will act for Bob.\n\nHere $\\oplus$ denotes the bitwise XOR operation.",
    "tutorial": "If both $p_1$ and $p_2$ are perfect powers of $2$, it is a losing state since you cannot perform a break operation on either of those. If either $p_1$ or $p_2$ has a bit count of $2$, then this is a winning state. You can force your opponent into the state described in Hint $1$ using the number which has $2$ bitcount. Fact 1: If $p_1$ has an odd bit count, then it can only be broken into two numbers such that one has an odd bit count and the other has an even bit count. Fact 2: If either $p_1$ or $p_2$ has an even bit count, then this is a winning state. Reason : If either $p_1$ or $p_2$ has an even bit count, without loss of generality, assume it's $p_1$. Then break it into $2^{msb \\text{ of } p_1}$ and $p_1 \\oplus 2^{msb \\text{ of } p_1}$, where $msb$ is the most significant bit. If the opponent chooses $2^{msb \\text{ of } p_1}$, they instantly lose (using Hint $1$), so they are forced to choose the other number with an odd bit count. From Fact $1$, we can conclude that in the next turn, the state will remain conserved for the current player. Because we eliminate the most significant bit in every query, this game will go on for at most $60$ turns for the player who reached this position first. At one point, the player who is at this state will have a number with two set bits. Hence, from Hint $2$, we can say this player will win. So, as Alice, you will start first if $n$ has an even number of bits and start second if it has an odd number of bits. Proceed using the strategy discussed above. So as Alice you have will start first if $n$ has even number of bits and start second if it has odd number of bits. Any proceed using the strategy discussed above.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int testcases;cin>>testcases;\n \n    for(int testcase=1;testcase<=testcases;testcase++){\n        long long n;cin>>n;\n        long long curr=n;\n        int parity=0;\n        if(__builtin_popcountll(n)%2){\n            cout<<\"secoNd\"<<endl;\n        }else{\n            cout<<\"firSt\"<<endl;\n            parity=1;\n        }\n        int turn=0;\n        while(1){\n            if(turn%2==parity){\n                long long p1,p2;cin>>p1>>p2;\n                if (p1 == 0 && p2 == 0)\n                    break;\n                if(__builtin_popcountll(p1)%2==0){\n                    curr=p1;\n                }else{\n                    curr=p2;\n                }\n            }else{\n                int pos=0;\n                for(int i=0;(1ll<<i)<curr;i++){\n                    if(curr&(1ll<<i)){\n                        pos=i;\n                    }\n                }\n                long long p1=(1ll<<pos);\n                long long p2=curr^p1;\n                cout<<p1<<\" \"<<p2<<endl;\n                curr = p1;\n            }\n            turn++;\n        }\n    }\n}\n",
    "tags": [
      "bitmasks",
      "games",
      "greedy",
      "interactive"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1934",
    "index": "E",
    "title": "Weird LCM Operations",
    "statement": "Given an integer $n$, you construct an array $a$ of $n$ integers, where $a_i = i$ for all integers $i$ in the range $[1, n]$. An operation on this array is defined as follows:\n\n- Select three distinct indices $i$, $j$, and $k$ from the array, and let $x = a_i$, $y = a_j$, and $z = a_k$.\n- Update the array as follows: $a_i = \\operatorname{lcm}(y, z)$, $a_j = \\operatorname{lcm}(x, z)$, and $a_k = \\operatorname{lcm}(x, y)$, where $\\operatorname{lcm}$ represents the least common multiple.\n\nYour task is to provide a possible sequence of operations, containing at most $\\lfloor \\frac{n}{6} \\rfloor + 5$ operations such that after executing these operations, if you create a set containing the greatest common divisors (GCDs) of all subsequences with a \\textbf{size greater than $1$}, then all numbers from $1$ to $n$ should be present in this set.After all the operations $a_i \\le 10^{18}$ should hold for all $1 \\le i \\le n$.\n\nWe can show that an answer always exists.",
    "tutorial": "Fact 1: If for $(x, y, z)$ their pairwise GCDs are equal to their common GCD (this means that $(x, y, z)$ = $(g * X, g * Y, g * Z)$ where $(X, Y, Z)$ are pairwise coprime), then making an operation on them (gives $(g * X * Y, g * X * Z,g * Y * Z)$) and looking at the subsequences of size EXACTLY 2, we find all three GCD: $x$, $y$, $z$. Let's call such tuple NICE. Result: If we can split all values in the array into independent NICE tuples, then we can just perform an operation on each of them and the problem is solved. Fact 2: We don't touch any value $\\leq$ $\\frac{n}{2}$. If there is $x$ $\\leq$ $\\frac{n}{2}$, then $2 * x \\leq n$. If we don't touch $x$, then we will always have another value that is divisible by $x$ (it's easy to see that performing an operation on a multiple of $x$ leaves us with another multiple of $x$), so we will always have GCD equal to $x$ taking a subsequence $(x, x * A)$. Fact 3: A sequence of consecutive integers $(x, x+1, x+2, ..., x+11)$ can be partitioned into $4$ disjoint sets of size $3$, each forming a NICE tuple, if $(x+11) \\% 4$ equals $2$ or $1$. For $(x+11) \\% 4 = 2$: The sets $(x, x+1, x+2)$, $(x+4, x+5, x+6)$ and $(x+8, x+9, x+10)$ are NICE because, the first and third terms are always odd, and the second term is always even. The set $(x+3, x+7, x+11)$ is NICE because it has the form of $2*(2*n-1)$, $2*(2*n)$, $2*(2*n+1)$, ensuring that the pairwise GCDs are equal to the common GCD. For $(x+11) \\% 4 = 1$: The sets $(x, x+4, x+8)$, $(x+1, x+2, x+3)$, $(x+5, x+6, x+7)$ and $(x+9, x+10, x+11)$ are NICE, the same logic like $(x+11) \\% 4 = 2$ follows, If $n \\% 4 = 3$ we can do one operation as $(1, 2, n)$, and if $n \\% 4 = 0$ we can do one operation as $(1, n-1, n)$. Let's group the remaining elements into the groups of size $12$, starting from the end, and continuing until we reach the number $\\frac{n}{2}$. Eventually, we can count that we used no more than $\\lfloor \\frac{n}{6} \\rfloor + 5$ operations. Solutions for $n \\leq 13$ should be found manually.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\nvector<vector<vector<int>>> pans(14);\nint main(){\n \n    ios::sync_with_stdio(false), cin.tie(nullptr);\n \n    int t;cin>>t;\n \n    pans[3]={{1,2,3}};\n    pans[4]={{1,3,4}};\n    pans[5]={{3,4,5}};\n    pans[6]={{1,3,5},{2,4,6}};\n    pans[7]={{2,4,6},{3,5,7}};\n    pans[8]={{2,6,8},{3,5,7}};\n    pans[9]={{1,3,5},{2,4,6},{7,8,9}};\n    pans[10]={{3,4,5},{2,6,8},{7,9,10}};\n    pans[11]={{2,6,8},{3,5,7},{9,10,11}};\n    pans[12]={{1,11,12},{6,8,10},{5,7,9}};\n    pans[13]={{1,12,13},{7,9,11},{6,8,10}};\n    for(int tt=0;tt<t;tt++){\n        int n;cin>>n;\n        if(n<=2){\n            cout<<-1<<endl;\n        }else if(n<14){\n            cout<<pans[n].size()<<endl;\n            for(auto w: pans[n]){\n                cout<<w[0]<<\" \"<<w[1]<<\" \"<<w[2]<<endl;\n            }\n        }else{\n            vector<int> v(n);\n            for(int i=0;i<n;i++){\n                v[i]=i+1;\n            }\n            vector<vector<int>> ans;\n            while (2*v.size()>n){\n                if(v.size()%4==2){\n                    vector<int> buf;\n                    for(int i=0;i<12;i++){\n                        buf.push_back(v.back());\n                        v.pop_back();\n                    }\n                    reverse(buf.begin(),buf.end());\n                    ans.push_back({buf[0],buf[1],buf[2]});\n                    ans.push_back({buf[4],buf[5],buf[6]});\n                    ans.push_back({buf[8],buf[9],buf[10]});\n                    ans.push_back({buf[3],buf[7],buf[11]});\n                }else if(v.size()%4==1){\n                    vector<int> buf;\n                    for(int i=0;i<12;i++){\n                        buf.push_back(v.back());\n                        v.pop_back();\n                    }\n                    reverse(buf.begin(),buf.end());\n                    ans.push_back({buf[1],buf[2],buf[3]});\n                    ans.push_back({buf[5],buf[6],buf[7]});\n                    ans.push_back({buf[9],buf[10],buf[11]});\n                    ans.push_back({buf[0],buf[4],buf[8]});\n                }else if(v.size()%4==3){\n                    vector<int> buf;\n                    buf.push_back(v.back());\n                    v.pop_back();\n                    buf.push_back(2);\n                    buf.push_back(1);\n                    reverse(buf.begin(),buf.end());\n                    ans.push_back({buf[0],buf[1],buf[2]});\n                }else{\n                    vector<int> buf;\n                    buf.push_back(v.back());\n                    v.pop_back();\n                    buf.push_back(v.back());\n                    v.pop_back();\n                    buf.push_back(1);\n                    reverse(buf.begin(),buf.end());\n                    ans.push_back({buf[0],buf[1],buf[2]});\n                }\n            }\n            cout<<ans.size()<<endl;\n            for(auto w: ans){\n                cout<<w[0]<<\" \"<<w[1]<<\" \"<<w[2]<<endl;\n            }\n        }\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "number theory"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1935",
    "index": "A",
    "title": "Entertainment in MAC",
    "statement": "Congratulations, you have been accepted to the Master's Assistance Center! However, you were extremely bored in class and got tired of doing nothing, so you came up with a game for yourself.\n\nYou are given a string $s$ and an \\textbf{even} integer $n$. There are two types of operations that you can apply to it:\n\n- Add the reversed string $s$ to the end of the string $s$ (for example, if $s = $ cpm, then after applying the operation $s = $ cpmmpc).\n- Reverse the current string $s$ (for example, if $s = $ cpm, then after applying the operation $s = $ mpc).\n\nIt is required to determine the lexicographically smallest$^{\\dagger}$ string that can be obtained after applying \\textbf{exactly} $n$ operations. Note that you can apply operations of different types in any order, but you must apply exactly $n$ operations in total.\n\n$^{\\dagger}$A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$;\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "The answer will always have either the prefix $s$, or the reversed string $s$. Adding the string to the end is required no more than once. Let $t$ be the reversed string $s$. Notice that it is advantageous for us to use operation 1 (adding the reversed string at the end) no more than once. Indeed, having obtained some string, we will simply spend the remaining operations on flipping the string. Thus, we will get the original string or the reversed one, depending on the parity of the number of remaining operations. It is easy to see that the answer will always have either the prefix $s$, or $t$. Then, we find two lexicographically minimal strings with the prefix $s$ and $t$. These will be strings: $s$, flip the string $n$ times (since $n$ is even, every 2 operations we return the string to its original) $t + s$, initially flip the string, add the reversed string to the end, then flip the string $n - 2$ times. The answer will be the lexicographically minimal string out of $s$ and $t + s$.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    s = input()\n    t = s[::-1]\n    print(min(s, t + s))\n",
    "tags": [
      "constructive algorithms",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1935",
    "index": "B",
    "title": "Informatics in MAC",
    "statement": "In the Master's Assistance Center, Nyam-Nyam was given a homework assignment in informatics.\n\nThere is an array $a$ of length $n$, and you want to divide it into $k > 1$ subsegments$^{\\dagger}$ in such a way that the $\\operatorname{MEX} ^{\\ddagger}$ on each subsegment is equal to the same integer.\n\nHelp Nyam-Nyam find any suitable division, or determine that it does not exist.\n\n$^{\\dagger}$A division of an array into $k$ subsegments is defined as $k$ pairs of integers $(l_1, r_1), (l_2, r_2), \\ldots, (l_k, r_k)$ such that $l_i \\le r_i$ and for each $1 \\le j \\le k - 1$, $l_{j + 1} = r_j + 1$, and also $l_1 = 1$ and $r_k = n$. These pairs represent the subsegments themselves.\n\n$^{\\ddagger}\\operatorname{MEX}$ of an array is the smallest non-negative integer that does not belong to the array.\n\nFor example:\n\n- $\\operatorname{MEX}$ of the array $[2, 2, 1]$ is $0$, because $0$ does not belong to the array.\n- $\\operatorname{MEX}$ of the array $[3, 1, 0, 1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- $\\operatorname{MEX}$ of the array $[0, 3, 1, 2]$ is $4$, because $0$, $1$, $2$, and $3$ belong to the array, but $4$ does not.",
    "tutorial": "What is the minimum $k$ that can be in a division? Suppose $\\operatorname{MEX}(x, y) = \\operatorname{MEX}(y + 1, z)$, what can be said about $\\operatorname{MEX}(x, z)$? Suppose we correctly divided the array into $k > 2$ segments - $(1, r_1), (l_2, r_2), \\ldots, (l_k, r_k)$. Then, note that we can merge first two subsegments, as the numbers from 0 to $mex - 1$ are encountered in these two segments and the number $mex$ is not encountered in them. Therefore, if there is a division into $k > 2$ segments, then there is also for $k - 1$ segments. Therefore, it is sufficient to check whether there is a division of the array into $k = 2$ segments, which can be done in $O(n)$ by precalcing $\\operatorname{MEX}$ on the prefixes and suffixes, then we need to find some $i$ for which $\\operatorname{MEX}(1, i) = \\operatorname{MEX}(i + 1, n)$.",
    "code": "def solve():\n    n = int(input())\n    a = list(map(int, input().split()))\n    cur_mex = 0\n    cur_have = [0] * (n + 1)\n    for el in a:\n        cur_have[el] += 1\n    while cur_have[cur_mex]:\n        cur_mex += 1\n\n    another_mex = 0\n    another_have = [0] * (n + 1)\n    for i in range(n):\n        cur_have[a[i]] -= 1\n        if cur_have[a[i]] == 0 and cur_mex > a[i]:\n            cur_mex = a[i]\n\n        another_have[a[i]] += 1\n        while another_have[another_mex]:\n            another_mex += 1\n\n        if cur_mex == another_mex:\n            print(2)\n            print(\"1 \" + str(i + 1))\n            print(str(i + 2) + \" \" + str(n))\n            return\n\n    print(-1)\n\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1935",
    "index": "C",
    "title": "Messenger in MAC",
    "statement": "In the new messenger for the students of the Master's Assistance Center, Keftemerum, an update is planned, in which developers want to optimize the set of messages shown to the user. There are a total of $n$ messages. Each message is characterized by two integers $a_i$ and $b_i$. The time spent reading the set of messages with numbers $p_1, p_2, \\ldots, p_k$ ($1 \\le p_i \\le n$, all $p_i$ are \\textbf{distinct}) is calculated by the formula:\n\n$$\\Large \\sum_{i=1}^{k} a_{p_i} + \\sum_{i=1}^{k - 1} |b_{p_i} - b_{p_{i+1}}|$$\n\nNote that the time to read a set of messages consisting of \\textbf{one} message with number $p_1$ is equal to $a_{p_1}$. Also, the time to read an empty set of messages is considered to be $0$.\n\nThe user can determine the time $l$ that he is willing to spend in the messenger. The messenger must inform the user of the maximum possible size of the set of messages, the reading time of which does not exceed $l$. Note that the maximum size of the set of messages can be equal to $0$.\n\nThe developers of the popular messenger failed to implement this function, so they asked you to solve this problem.",
    "tutorial": "Try to find the answer to the problem by hand. How can changing the order of the messages reduce time? Let the order in the response be $p_1, p_2, \\ldots, p_k$. It is always advantageous for the response to satisfy $b_{p_1} \\leq b_{p_2} \\leq \\ldots \\leq b_{p_k}$. Greedy? Let the order in the response be $p_1, p_2, \\ldots, p_k$. Note that in the optimal response, it will hold that $b_{p_1} \\leq b_{p_2} \\leq \\ldots \\leq b_{p_k}$. It's not hard to prove that such an order minimizes the sum of the absolute differences of adjacent elements in the array $b$. Then, this sum will turn into $b_{p_k} - b_{p_1}$, that is, the difference between the highest and lowest value of $b$ in the set of messages. Let's sort the pairs $(a_i, b_i)$ in ascending order of $b_i$. Fix the minimum value in the set of messages $b_l$ and the maximum value $b_r$. Note that the sum of the absolute differences of $b$ in the response will not change if taking values $b_l \\leq b_i \\leq b_r$. Thus, the task reduces to finding the maximum number of messages so that $\\sum a \\leq L - (b_r - b_l)$. Iterate over $b_l$ and $b_r$. Apply a greedy algorithm, sort all values of $a_i$ ($l \\leq i \\leq r$), and keep adding values until the time exceeds $L$. This solution works in $O(n^3\\log{}n)$, which is too slow. To speed up the solution, while iterating over $b_r$, maintain a data structure that allows adding an element, removing the maximum, getting the maximum (in C++, there are $\\textit{multiset}$ and $\\textit{priority_queue}$). In this data structure, maintain the minimum values of $a$, so the sum of times does not exceed $L$. Then, if the current time exceeds $L$, remove from the structure until the current time becomes no more than $L$. There will be no more than $n$ such removals. We have obtained a solution in $O(n^2\\log{}n)$, which is feasibly fast.",
    "code": "import heapq\nimport sys\n\ninput = sys.stdin.readline\n\nt = int(input())\nfor _ in range(t):\n    n, L = map(int, input().split())\n    v = []\n    for i in range(n):\n        a, b = map(int, input().split())\n        v.append((b, a))\n    v.sort()\n\n    ans = 0\n    for l in range(n):\n        pq = []\n        heapq.heapify(pq)\n        cur = 0\n        size = 0\n        for r in range(l, n):\n            heapq.heappush(pq, -v[r][1])\n            size += 1\n            cur += v[r][1]\n            while size and v[r][0] - v[l][0] + cur > L:\n                maxx = -heapq.heappop(pq)\n                cur -= maxx\n                size -= 1\n            ans = max(ans, size)\n\n    print(ans)",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1935",
    "index": "D",
    "title": "Exam in MAC",
    "statement": "The Master's Assistance Center has announced an entrance exam, which consists of the following.\n\nThe candidate is given a set $s$ of size $n$ and some strange integer $c$. For this set, it is needed to calculate the number of pairs of integers $(x, y)$ such that $0 \\leq x \\leq y \\leq c$, $x + y$ \\textbf{is not} contained in the set $s$, and also $y - x$ \\textbf{is not} contained in the set $s$.\n\nYour friend wants to enter the Center. Help him pass the exam!",
    "tutorial": "The principle of inclusion-exclusion. The equation $x+y = s_i$, $y-x=s_j$ has $0$ or $1$ solutions with integers $x, y$. Applying the formula of inclusion-exclusion, the answer to the problem will be: $\\mathrm{cnt}(x, y) - \\mathrm{cnt}(x, y: x + y \\in s) - \\mathrm{cnt}(x, y: y - x \\in s) + \\mathrm{cnt}(x, y: x + y, y - x \\in s)$. Let's calculate each value separately. The number of possible pairs $x, y$ is $\\frac{(c+1)\\cdot(c+2)}{2}$. The number of pairs $x, y: x + y \\in s$. We iterate over the sum value $s_i$, let $x + y = s_i$, then for $0 \\leq x \\leq \\lfloor \\frac{s_i}{2} \\rfloor$ there will correspond exactly one $y$, i.e., the number of pairs with such a sum is $\\lfloor \\frac{s_i}{2} \\rfloor + 1$. The number of pairs $x, y: y - x \\in s$. We iterate over the difference value $s_i$, let $y - x = s_i$, then for $s_i \\leq y \\leq c$ there will correspond exactly one $x$, i.e., the number of pairs with such a difference is $c - s_i + 1$. The number of pairs $x, y: x + y, y - x \\in s$. Let $x+y=s_i$, $y-x=s_j$, then $x = \\frac{s_i - s_j}{2}$, and $y = \\frac{s_i+s_j}{2}$. If $s_i, s_j$ have different parities, then such $x, y$ will not be suitable because they will be non-integers; otherwise, such $x, y$ are suitable, and we need to add this pair. Then, let's calculate the number of even and odd numbers in $s$ - $even$ and $odd$ respectively. Thus, the number of such pairs is $\\frac{even\\cdot(even+1)}{2}+\\frac{odd\\cdot(odd+1)}{2}$. With all these quantities, we can calculate the answer. The final complexity is $O(n)$. The problem can also be solved in $O(n \\cdot \\log n)$ or $O(n)$ using other methods.",
    "code": "def solve_case() :\n    n, c = map(int, input().split())\n    s = list(map(int, input().split()))\n    ans = (c + 1) * (c + 2) // 2\n    even, odd = 0, 0\n    for i in range(n):\n        ans -= s[i] // 2 + 1\n        ans -= c - s[i] + 1\n        if s[i] % 2 == 0:\n            even += 1\n        else:\n            odd += 1\n    ans += even * (even + 1) // 2\n    ans += odd * (odd + 1) // 2\n    print(ans)\n\nt = int(input())\nfor test in range(t):\n    solve_case()",
    "tags": [
      "binary search",
      "combinatorics",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1935",
    "index": "E",
    "title": "Distance Learning Courses in MAC",
    "statement": "The New Year has arrived in the Master's Assistance Center, which means it's time to introduce a new feature!\n\nNow students are given distance learning courses, with a total of $n$ courses available. For the $i$-th distance learning course, a student can receive a grade ranging from $x_i$ to $y_i$.\n\nHowever, not all courses may be available to each student. Specifically, the $j$-th student is only given courses with numbers from $l_j$ to $r_j$, meaning the distance learning courses with numbers $l_j, l_j + 1, \\ldots, r_j$.\n\nThe creators of the distance learning courses have decided to determine the final grade in a special way. Let the $j$-th student receive grades $c_{l_j}, c_{l_j + 1}, \\ldots, c_{r_j}$ for their distance learning courses. Then their final grade will be equal to $c_{l_j}$ $|$ $c_{l_j + 1}$ $|$ $\\ldots$ $|$ $c_{r_j}$, where $|$ denotes the bitwise OR operation.\n\nSince the chatbot for solving distance learning courses is broken, the students have asked for your help. For each of the $q$ students, tell them the maximum final grade they can achieve.",
    "tutorial": "Try to solve the problem if $x_i = 0$ for each $i$. What will be the answer for two segments $(0, 2^i), (0, 2^i)$? Which bits will definitely be included in the answer? Let's solve the problem when $x = 0$. Then we will iterate over the bits from the most significant to the least significant and try to include them in the answer. Suppose we are iterating over bit $i$, then if such a bit occurs $c$ times in $y$ numbers there are several cases: $c = 0$ - this bit cannot be included in the answer $c = 1$ - this bit will be included in the answer, we add it $c > 1$ - a special case, because for one number where bit x is present, we can set it, and for another number, we can set all bits $j < i$. Therefore, if we encounter some bit $i$ that occurs more than once, then all bits $j \\le i$ will also be included in the answer. Now let's solve the original problem, for this we take a pair $(x_i, y_i)$ and find the bitwise largest common prefix - let it be number $w$. Then it is clear that all bits from $w$ will be included in the answer, then we make a new pair $(x'_i, y'_i)$ = $(x_i - w, y_i - w)$, and remember the number $w_i$. Now note that the number $y'_i - 1 \\ge x'_i$. Why do we need this fact? Remember, in the case when some bit occurred more than once, we added it and all smaller bits to the answer. For this, we would set at this position a number equal to $2^i - 1$ (and other larger bits $i$), but if $y'_i - 1 \\ge x'_i$, then we can always add all such bits. Therefore, the solution algorithm for request $j$ is as follows: Take the Bitwise OR of all $w_i$ for $l_j \\le i \\le r_j$, let this be number $W$ Iterate over bit $i$ and similarly to the case $x = 0$ consider the same cases, but for the array $y'$. Also, take into account that the bit occurs in $W$. This solution can be implemented in $O(n \\cdot \\log n)$ using prefix sums for each bit. There is also a solution using a segment tree, so the problem can be solved with modification requests as well.",
    "code": "/* Includes */\n#include <bits/stdc++.h>\n#include <ext/pb_ds/tree_policy.hpp>\n \n/* Using libraries */\nusing namespace std;\n \n/* Defines */\ntemplate <class T>\nusing vc = vector <T>;\nusing ll = long long;\nusing ld = long double;\nusing pii = pair <int, int>;\n \ntemplate<class T>\nvoid output(T &a) {\n    for (auto i : a)\n        cout << i << ' ';\n    cout << '\\n';\n}\n \ntemplate<class T>\nbool chmin(T &a, T b) {\n    if (a > b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \ntemplate<class T>\nbool chmax(T &a, T b) {\n    if (a < b) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n \nconst int N = 2e5;\nconst int bit = 30;\n \nstruct segtree {\n    vc <int> t; int n;\n    segtree (int n) : n(n) {\n        t.resize(n * 2);\n    }\n    void upd (int i, int x) {\n        for (t[i += n] = x; i > 1; i >>= 1) {\n            t[i >> 1] = t[i] | t[i ^ 1];\n        }\n    }\n    int get (int l, int r) {\n        int res = 0;\n        for (l += n, r += n; l < r; l >>= 1, r >>= 1) {\n            if (l & 1)\n                res |= t[l++];\n            if (r & 1)\n                res |= t[--r];\n        }\n        return res;\n    }\n};\n \nint n;\nint l[N], r[N];\nint w[N];\nvoid fix () {\n    for (int i = 0; i < n; ++i) {\n        if (l[i] == r[i]) {\n            w[i] = l[i];\n            l[i] = r[i] = 0;\n            continue;\n        }\n        int pref = (1 << (__lg(l[i] ^ r[i]) + 1)) - 1;\n        w[i] = r[i] - (r[i] & pref);\n        r[i] &= pref;\n        l[i] &= pref;\n    }\n}\n \nvoid solve() {\n    cin >> n;\n    for (int i = 0; i < n; ++i) {\n        cin >> l[i] >> r[i];\n    }\n    fix();\n    segtree t(n);\n    vc <vc <int>> bits(bit, vc <int> (n + 1));\n    for (int i = 0; i < n; ++i) {\n        t.upd(i, w[i]);\n        for (int j = 0; j < bit; ++j) {\n            bits[j][i + 1] = bits[j][i];\n            if (r[i] >> j & 1) {\n                bits[j][i + 1]++;\n            }\n        }\n    }\n    int q;\n    cin >> q;\n    while (q--) {\n        int x, y;\n        cin >> x >> y; --x;\n        int ans = t.get(x, y);\n        for (int j = bit - 1; j >= 0; --j) {\n            int cnt = bits[j][y] - bits[j][x] + (ans >> j & 1);\n            if (cnt > 1) {\n                ans |= (2 << j) - 1;\n                break;\n            } else if (cnt == 1) {\n                ans |= 1 << j;\n            }\n        }\n        cout << ans << ' ';\n    }\n    cout << \"\\n\";\n}\n \nsigned main() {\n    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1935",
    "index": "F",
    "title": "Andrey's Tree",
    "statement": "Master Andrey loves trees$^{\\dagger}$ very much, so he has a tree consisting of $n$ vertices.\n\nBut it's not that simple. Master Timofey decided to steal one vertex from the tree. If Timofey stole vertex $v$ from the tree, then vertex $v$ and all edges with one end at vertex $v$ are removed from the tree, while the numbers of other vertices remain unchanged. To prevent Andrey from getting upset, Timofey decided to make the resulting graph a tree again. To do this, he can add edges between any vertices $a$ and $b$, but when adding such an edge, he must pay $|a - b|$ coins to the Master's Assistance Center.\n\nNote that the resulting tree \\textbf{does not contain} vertex $v$.\n\nTimofey has not yet decided which vertex $v$ he will remove from the tree, so he wants to know for each vertex $1 \\leq v \\leq n$, the minimum number of coins needed to be spent to make the graph a tree again after removing vertex $v$, as well as which edges need to be added.\n\n$^{\\dagger}$A tree is an undirected connected graph without cycles.",
    "tutorial": "What different values can the answer for a vertex take? Edges with a weight of 1 can connect all vertices $[1, v - 1]$ and all vertices $[v + 1, n]$. Consider the edges of the form $(mn_u, mn_u - 1)$, $(mx_u, mx_u + 1)$, where $mn_u$, $mx_u$ are the minimum and maximum in the subtree of vertex u with respect to $v$. Let's fix some vertex $v$ for which the answer is being calculated. Suppose the degree of the vertex $v$ in the tree is $deg_v$, then it's clear that it's necessary to add $deg_v - 1$ edges. Consider the components that appear after removing $v$. Then, the goal is to use the new edges to unite all the components into one, using the minimum total cost. This is the same as finding the minimum spanning tree in a graph, where the vertices are the components that resulted from removing $v$, and for every $a, b$, an edge with a weight of $|a - b|$ is drawn between the components containing $a$ and $b$. Let's simulate Kruskal's algorithm for this graph. Consider all the single-weight edges in this graph: $(1, 2), (2, 3), ..., (v - 2, v - 1), (v + 1, v + 2), ..., (n - 1, n)$. It's clear that using the single-weight edges, the vertices with numbers $[1, v - 1]$ will definitely end up in one component, and the vertices with numbers $[v + 1, n]$ will also end up in one component. To unite these two components, it would be optimal to add an edge $(v - 1, v + 1)$. It turns out that it's sufficient to consider only all the single-weight edges and the edge $(v - 1, v + 1)$. Let's limit the number of single-weight edges to $O(deg_v)$. For this, in each component $u$, calculate $mn_u$ and $mx_u$ - the minimum and maximum in the component, respectively. Claim: among the single-weight edges, it's sufficient to consider edges of the form $(mn_u, mn_u - 1)$, $(mx_u, mx_u + 1)$. First, understand when it's necessary to add the edge $(v - 1, v + 1)$. Note that if there's at least one component $u$ such that $mn_u < v < mx_u$, then the edge $(v - 1, v + 1)$ won't be needed; otherwise, it will be. This is quite easy to show by simulating Kruskal's algorithm. Let $v = 1$. We'll show that using edges $(mn_u, mn_u - 1)$, all components will unite. Go through the vertices $x$ from $2$ to $n$ and maintain the invariant that all vertices from $2$ to $x$ are in one component. At $x = 2$, this holds. When $x$ is the minimum in some component, then the edge $(x - 1, x)$ will be added, and since $x - 1$ is in one component with $2$, $x$ will now also be. When $x$ is not the minimum in some component, then $mn$ - the minimum in the component $x$ will be in one component with $2$ ($mn < x$, the invariant holds), meaning $x$ will also be in one component with $2$. Thus, it turns out that all will be in one component. Now consider an arbitrary $v$. Separately consider the prefix of vertices $[1, v - 1]$ and the suffix $[v + 1, n]$. Then, similarly to $v = 1$, it can be shown that for the prefix of vertices $[1, v - 1]$, using edges of the form $(mn_u, mn_u - 1)$, you can unite $[1, v - 1]$. Similarly, for the suffix of vertices $[v + 1, n]$, using edges of the form $(mx_u, mx_u + 1)$, you can unite $[v + 1, n]$. Now, if the edge $(v - 1, v + 1)$ is necessary, then add it to the answer. Otherwise, there's at least one component $u$ such that $mn_u < v < mx_u$, meaning the prefix of vertices $[1, v - 1]$ and the suffix $[v + 1, n]$ will unite into one component. Finding $mn_u$, $mx_u$ for each component is straightforward; what remains is to determine which components are connected by the edges $(mn_u, mn_u - 1)$, $(mx_u, mx_u + 1)$. This can be done with binary search through the Euler tour of the tree. After that, Kruskal's algorithm can be initiated to calculate the answer. Let's estimate the time complexity. For a specific vertex $v$, the time complexity will be $deg_v \\cdot \\log n$, so the total time complexity is $O(n \\cdot \\log n)$. Depending on the implementation of the last step, the problem can be solved in $O(n)$, $O(n \\cdot \\alpha(n))$, where $\\alpha(n)$ is the inverse Ackermann function relative to $n$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n \nstruct DSU {\n    vector<int> p, r;\n    int comp;\n    DSU(int n) : p(n), r(n) {\n        iota(p.begin(), p.end(), 0);\n        comp = n;\n    }\n    int find(int v) {\n        return (p[v] == v) ? v : p[v] = find(p[v]);\n    }\n    bool join(int a, int b) {\n        a = find(a), b = find(b);\n        if (a == b) return false;\n        comp--;\n        if (r[a] < r[b]) swap(a, b);\n        p[b] = a;\n        if (r[a] == r[b]) r[a]++;\n        return true;\n    }\n};\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    int T;\n    cin >> T;\n    while (T--) {\n        int n;\n        cin >> n;\n        vector<vector<int>> g(n);\n        for (int i = 0; i < n - 1; i++) {\n            int x, y;\n            cin >> x >> y;\n            x--, y--;\n            g[x].push_back(y);\n            g[y].push_back(x);\n        }\n        vector<int> tin(n), tout(n), l0(n), r0(n);\n        vector<int> lup(n), rup(n);\n        int timer = 0;\n        vector<int> ord;\n        function<void(int, int)> dfs = [&](int v, int p) {\n            l0[v] = r0[v] = v;\n            tin[v] = timer++;\n            ord.push_back(v);\n            for (int u : g[v]) {\n                if (u == p) continue;\n                dfs(u, v);\n                l0[v] = min(l0[v], l0[u]);\n                r0[v] = max(r0[v], r0[u]);\n            }\n            tout[v] = timer - 1;\n        };\n        dfs(0, 0);\n        function<bool(int, int)> ancestor = [&](int v, int u) {\n            return tin[v] <= tin[u] && tin[u] <= tout[v];\n        };\n        vector<int> pref_min_ord(n + 1, n), suf_min_ord(n + 1, n);\n        vector<int> pref_max_ord(n + 1, -1), suf_max_ord(n + 1, -1);\n        for (int i = 0; i < n; i++) {\n            pref_min_ord[i + 1] = min(pref_min_ord[i], ord[i]);\n            pref_max_ord[i + 1] = max(pref_max_ord[i], ord[i]);\n        }\n        for (int i = n - 1; i >= 0; i--) {\n            suf_min_ord[i] = min(suf_min_ord[i + 1], ord[i]);\n            suf_max_ord[i] = max(suf_max_ord[i + 1], ord[i]);\n        }\n        for (int id = (int)ord.size() - 1; id >= 0; id--) {\n            int v = ord[id];\n            lup[v] = min(pref_min_ord[tin[v]], suf_min_ord[tout[v] + 1]);\n            rup[v] = max(pref_max_ord[tin[v]], suf_max_ord[tout[v] + 1]);\n        }\n        vector<vector<pair<int, int>>> ans(n);\n        vector<int> weight(n);\n        function<void(int, int)> dfs2 = [&](int v, int p) {\n            vector<int> all_id, all_tin;\n            int idpar = -1;\n            for (int id = 0; id < g[v].size(); id++) {\n                int u = g[v][id];\n                if (u != p) {\n                    dfs2(u, v);\n                    all_id.push_back(id);\n                    all_tin.push_back(tin[u]);\n                } else {\n                    idpar = id;\n                }\n            }\n            function<int(int)> get_subtree = [&](int u) {\n                if (!ancestor(v, u)) return idpar;\n                return all_id[upper_bound(all_tin.begin(), all_tin.end(), tin[u]) - all_tin.begin() - 1];\n            };\n            DSU dsu(g[v].size());\n            function<void(int, int)> try_add = [&](int x, int y) {\n                if (x == -1 || y == n || x == v || y == v) return;\n                if (dsu.join(get_subtree(x), get_subtree(y))) {\n                    ans[v].push_back({x, y});\n                    weight[v] += abs(x - y);\n                }\n            };\n            for (int u : g[v]) {\n                if (u != p) {\n                    try_add(l0[u] - 1, l0[u]);\n                    try_add(r0[u], r0[u] + 1);\n                } else {\n                    try_add(lup[v] - 1, lup[v]);\n                    try_add(rup[v], rup[v] + 1);\n                }\n            }\n            if (dsu.comp != 1) {\n                try_add(v - 1, v + 1);\n            }\n            assert(dsu.comp == 1);\n        };\n        dfs2(0, 0);\n        for (int i = 0; i < n; i++) {\n            cout << weight[i] << \" \" << ans[i].size() << \"\\n\";\n            for (auto [a, b] : ans[i]) {\n                cout << a + 1 << \" \" << b + 1 << \"\\n\";\n            }\n            cout << \"\\n\";\n        }\n    }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dsu",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1936",
    "index": "A",
    "title": "Bitwise Operation Wizard",
    "statement": "\\textbf{This is an interactive problem.}\n\nThere is a secret sequence $p_0, p_1, \\ldots, p_{n-1}$, which is a permutation of $\\{0,1,\\ldots,n-1\\}$.\n\nYou need to find any two indices $i$ and $j$ such that $p_i \\oplus p_j$ is maximized, where $\\oplus$ denotes the bitwise XOR operation.\n\nTo do this, you can ask queries. Each query has the following form: you pick arbitrary indices $a$, $b$, $c$, and $d$ ($0 \\le a,b,c,d < n$). Next, the jury calculates $x = (p_a \\mid p_b)$ and $y = (p_c \\mid p_d)$, where $|$ denotes the bitwise OR operation. Finally, you receive the result of comparison between $x$ and $y$. In other words, you are told if $x < y$, $x > y$, or $x = y$.\n\nPlease find any two indices $i$ and $j$ ($0 \\le i,j < n$) such that $p_i \\oplus p_j$ is maximum among all such pairs, using at most $3n$ queries. If there are multiple pairs of indices satisfying the condition, you may output any one of them.",
    "tutorial": "What's the maximum value of $p_i \\oplus p_j$? How to get $i$, such that $p_i = n-1$? How to get $j$, such that $p_i \\oplus p_j$ reaches the maximum value? Step1:do queries $? \\ x \\ x \\ y \\ y$ like classic searching for the maximum value among $n$ numbers to get $p_i= n-1$; Step2:do queries $? \\ x \\ i \\ y \\ i$ to find all index $k$ such that $p_i | p_{k}$ reaches the maximum value. We store all such indexes in a vector $id$ . Step3:do queries $? \\ id[x] \\ id[x] \\ id[y] \\ id[y]$ to find $j$ in $id$ such that $p_j$ reaches the minimum value.",
    "code": "\n#include <map>\n#include <set>\n#include <cmath>\n#include <ctime>\n#include <queue>\n#include <stack>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n#include <iostream>\nusing namespace std;\ntypedef double db; \ntypedef long long ll;\ntypedef unsigned long long ull;\nconst int N=1000010;\nconst int LOGN=28;\nconst ll  TMD=0;\nconst ll  INF=2147483647;\nint T,n;\n\nchar query(int a,int b,int c,int d)\n{\n\tchar x;\n\tprintf(\"? %d %d %d %d\\n\",a,b,c,d);\n\tfflush(stdout);\n\tcin>>x;\n\tfflush(stdout);\n\treturn x;\n}\n\nint main()\n{\t\n\tscanf(\"%d\",&T);\n\twhile(T--)\n\t{\n    \t        scanf(\"%d\",&n);\n\t\tint mx=0,ans1=0,ans2;\n\t\tvector<int> v;\n\t\tfor(int i=1;i<n;i++)\n\t\t{\n\t\t\tint c=query(ans1,ans1,i,i);\n\t\t\tif(c=='<') ans1=i;\n\t\t}\n\t\tv.push_back(0);\n\t\tfor(int i=1;i<n;i++)\n\t\t{\n\t\t\tint c=query(mx,ans1,i,ans1);\n\t\t\tif(c=='<')\n\t\t\t{\n\t\t\t    mx=i;\n\t\t\t    v.clear();\n\t\t\t    v.push_back(i);\n\t\t\t}\n\t\t\telse if(c=='=') v.push_back(i);\n\t\t}\n\t\tans2=v[0];\n\t\tfor(int i=1;i<v.size();i++)\n\t\t{\n\t\t\tint c=query(ans2,ans2,v[i],v[i]);\n\t\t\tif(c=='>') ans2=v[i];\n\t\t}\n\t\tprintf(\"! %d %d\\n\",ans1,ans2);\n\t\tfflush(stdout);\n\t}\n\t\n\treturn 0;\n}\n\n",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "interactive",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1936",
    "index": "B",
    "title": "Pinball",
    "statement": "There is a one-dimensional grid of length $n$. The $i$-th cell of the grid contains a character $s_i$, which is either '<' or '>'.\n\nWhen a pinball is placed on one of the cells, it moves according to the following rules:\n\n- If the pinball is on the $i$-th cell and $s_i$ is '<', the pinball moves one cell to the left in the next second. If $s_i$ is '>', it moves one cell to the right.\n- After the pinball has moved, the character $s_i$ is inverted (i. e. if $s_i$ used to be '<', it becomes '>', and vice versa).\n- The pinball stops moving when it leaves the grid: either from the left border or from the right one.\n\nYou need to answer $n$ \\textbf{independent} queries. In the $i$-th query, a pinball will be placed on the $i$-th cell. Note that we always place a pinball on the initial grid.\n\nFor each query, calculate how many seconds it takes the pinball to leave the grid. It can be shown that the pinball will always leave the grid within a finite number of steps.",
    "tutorial": "Observe: which cells actually change the direction of the pinball placed at position $p$ initially? These cells are the $>$ to the left of $p$ and the $<$ to the right of $p$. Can you see the trace of the pinball? How to quickly calculate the time when a pinball leaves the grid? We observe that, in fact, only the $>$ to the left of $p$ and the $<$ to the right of $p$ change the direction of the pinball placed at position $p$ initially. For convenience, let's assume $s_p$ is $>$, $k=min(countright(1,p),countleft(p+1,n))$, and the pinball leaves from the left boundary(for other situations, we can handle them in a similar way). We can obtain $right[1,\\ldots,k]$ and $left[1,\\ldots,k]$ through prefix sum + binary search, where $right$ represents the indices of $>$ to the left of $p$ (in decreasing order), and $left$ represents the indices of $<$ to the right of $p$ (in increasing order). We use $right$ and $left$ to describe the trace of the pinball: The first segment: the pinball moves from $right_1$ to $left_1$; The second segment: the pinball moves from $left_1$ to $right_2$; The third segment: the pinball moves from $right_2$ to $left_3$; $\\ldots$ The $2k$-th segment: the pinball moves from $left_k$ to the left boundary. It is not difficult to observe that we can use prefix sum to store the sum of indices, and then quickly calculate the time when the pinball moves.",
    "code": "#include <map>\n#include <set>\n#include <cmath>\n#include <ctime>\n#include <queue>\n#include <stack>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n#include <iostream>\nusing namespace std;\ntypedef double db; \ntypedef long long ll;\ntypedef unsigned long long ull;\nconst int N=1000010;\nconst int LOGN=28;\nconst ll  TMD=0;\nconst ll  INF=2147483647;\nint  T,n;\nll   Sl[N],Sr[N],IDl[N],IDr[N];\nchar s[N];\n\nint findpre(int x)\n{\n\tint L=0,R=n+1,M;\n\twhile(L+1!=R)\n\t{\n\t\tM=(L+R)>>1;\n\t\tif(Sr[M]<x) L=M;\n\t\telse R=M; \n\t}\n\treturn R;\n}\n\nint findsuf(int x)\n{\n\tint L=0,R=n+1,M;\n\twhile(L+1!=R)\n\t{\n\t\tM=(L+R)>>1;\n\t\tif(Sl[n]-Sl[M-1]<x) R=M;\n\t\telse L=M; \n\t}\n\treturn L;\n}\n\nint main()\n{\n\tscanf(\"%d\",&T);\n\twhile(T--)\n\t{\n    \t        scanf(\"%d%s\",&n,s);\n\t\tfor(int i=1;i<=n;i++) \n\t\t{\n\t  \t  Sr[i]=Sr[i-1]+(s[i-1]=='>');\n\t  \t  Sl[i]=Sl[i-1]+(s[i-1]=='<');\n \t\t  IDr[i]=IDr[i-1]+i*(s[i-1]=='>'); \t\n \t\t  IDl[i]=IDl[i-1]+i*(s[i-1]=='<'); \t\n\t\t}\t\t\n\t\tfor(int i=1;i<=n;i++)\n\t\t{\n\t\t\tif(s[i-1]=='>')\n\t\t\t{\n\t\t\t\tif(Sr[i]>Sl[n]-Sl[i])\n\t\t\t\t{\n\t\t\t\t\tint p=findpre(Sr[i]-(Sl[n]-Sl[i]));\n\t\t\t\t\tprintf(\"%I64d \",2*((IDl[n]-IDl[i])-(IDr[i]-IDr[p-1]))+i+(n+1));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tint p=findsuf((Sl[n]-Sl[i])-Sr[i]+1);\n\t\t\t\t\tprintf(\"%I64d \",2*((IDl[p]-IDl[i])-(IDr[i]-IDr[0]))+i);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(Sr[i]>=Sl[n]-Sl[i-1])\n\t\t\t\t{\n\t\t\t\t\tint p=findpre(Sr[i]-(Sl[n]-Sl[i-1])+1);\n\t\t\t\t\tprintf(\"%I64d \",2*((IDl[n]-IDl[i-1])-(IDr[i]-IDr[p-1]))-i+(n+1));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tint p=findsuf((Sl[n]-Sl[i-1])-Sr[i]);\n\t\t\t\t\tprintf(\"%I64d \",2*((IDl[p]-IDl[i-1])-(IDr[i]-IDr[0]))-i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\t\n\treturn 0;\n}\n\n\n",
    "tags": [
      "binary search",
      "data structures",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1936",
    "index": "C",
    "title": "Pokémon Arena",
    "statement": "You are at a dueling arena. You also possess $n$ Pokémons. Initially, only the $1$-st Pokémon is standing in the arena.\n\nEach Pokémon has $m$ attributes. The $j$-th attribute of the $i$-th Pokémon is $a_{i,j}$. Each Pokémon also has a cost to be hired: the $i$-th Pokémon's cost is $c_i$.\n\nYou want to have the $n$-th Pokémon stand in the arena. To do that, you can perform the following two types of operations any number of times in any order:\n\n- Choose three integers $i$, $j$, $k$ ($1 \\le i \\le n$, $1 \\le j \\le m$, $k > 0$), increase $a_{i,j}$ by $k$ permanently. The cost of this operation is $k$.\n- Choose two integers $i$, $j$ ($1 \\le i \\le n$, $1 \\le j \\le m$) and hire the $i$-th Pokémon to duel with the current Pokémon in the arena based on the $j$-th attribute. The $i$-th Pokémon will win if $a_{i,j}$ is \\textbf{greater than or equal to} the $j$-th attribute of the current Pokémon in the arena (otherwise, it will lose). After the duel, only the winner will stand in the arena. The cost of this operation is $c_i$.\n\nFind the minimum cost you need to pay to have the $n$-th Pokémon stand in the arena.",
    "tutorial": "In fact, you don't need to hire the same Pokemon more than once. Consider graph building. How to reduce the number of edges in the graph? Let's consider $n$ Pokémon as nodes, and defeating Pokémon $u$ by Pokémon $v$ as the edge $u \\rightarrow v$. Then the problem is essentially finding the shortest path from $n$ to $1$. If we brute force to construct the graph, the time complexity will be $O(n^2m)$, which is unacceptable. How can we find a better way to build the graph? Recalling, we need to represent all processes like \"Pokémon $u$ increased attribute $x$ by some value and defeated Pokémon $v$\" using paths in the graph. We will use the following graph building to achieve this. Overall, we consider each attribute separately. For the $x$-th attribute, we construct $2n$ virtual nodes $X_1,...,X_n$ and $Y_1,...,Y_n$, and connect each Pokémon based on the $x$-th attribute. For example, $n=3$ and $a_{1,1}=9, a_{2,1}=6, a_{3,1}=1$, we have the following graph building for attribute $1$: In this graph,for example,\"Pokémon $3$ increased attribute $1$ by $8$ and defeated Pokémon $1$\" can be represented as path $3 \\rightarrow X1 \\rightarrow X2 \\rightarrow X3 \\rightarrow Y3 \\rightarrow 1$. More generally, our graph building method is : Consider each attribute separately. Assuming we are processing the $i$-th attribute, insert all $a_{1,i} , \\ldots ,a_{n,i}$ into $val$ and sort it (for convenience, we assume that they are pairwise different). Consider each attribute separately. Assuming we are processing the $i$-th attribute, insert all $a_{1,i} , \\ldots ,a_{n,i}$ into $val$ and sort it (for convenience, we assume that they are pairwise different). Construct $2n$ virtual nodes $X_1,...,X_n$ and $Y_1,...,Y_n$; Construct $2n$ virtual nodes $X_1,...,X_n$ and $Y_1,...,Y_n$; Add edge $X_i \\rightarrow X_{i+1}$ with a value of $(val_{i+1}-val_i)$ for $1 \\le i < n$; Add edge $X_i \\rightarrow X_{i+1}$ with a value of $(val_{i+1}-val_i)$ for $1 \\le i < n$; Add edge $Y_{i+1} \\rightarrow Y_{i}$ with a value of $0$ for $1 \\le i < n$; Add edge $Y_{i+1} \\rightarrow Y_{i}$ with a value of $0$ for $1 \\le i < n$; Add edge $X_i \\rightarrow Y_{i}$ with a value of $0$ for $1 \\le i \\le n$; Add edge $X_i \\rightarrow Y_{i}$ with a value of $0$ for $1 \\le i \\le n$; Add edge $i \\rightarrow X_{rank_i}$ with a value of $c_i$ for $1 \\le i \\le n$; Add edge $i \\rightarrow X_{rank_i}$ with a value of $c_i$ for $1 \\le i \\le n$; Add edge $Y_{rank_i} \\rightarrow i$ with a value of $0$ for $1 \\le i \\le n$. Add edge $Y_{rank_i} \\rightarrow i$ with a value of $0$ for $1 \\le i \\le n$. Then we just run Dijkstra algorithm in this graph. The time complexity is $O(nmlog(nm))$.",
    "code": "\n#include <bits/stdc++.h>\n#define int long long\n#define fi first\n#define se second\n\nusing namespace std;\n\nconst int INFF = 1e18;\n\nint32_t main()\n{\n        ios_base::sync_with_stdio(false);\n        cin.tie(NULL);\n        \n        int t;\n        cin >> t;\n\n        while (t --> 0) {\n                int n, m;\n                cin >> n >> m;\n\n                vector<int> c(n + 1);\n                for (int i = 1; i <= n; i++) cin >> c[i];\n\n                vector<vector<int>> a(n + 1, vector<int>(m + 1));\n                vector<vector<pair<int, int>>> b(m + 1);\n                for (int i = 1; i <= n; i++) {\n                        for (int j = 1; j <= m; j++) {\n                                cin >> a[i][j];\n\n                                b[j].push_back({a[i][j], i});\n                        }\n                }\n\n                vector<vector<int>> rank(n + 1, vector<int>(m + 1));\n                vector<vector<int>> dec(n + 1, vector<int>(m + 1));\n                for (int j = 1; j <= m; j++) {\n                        sort(b[j].begin(), b[j].end());\n\n                        for (int i = 0; i < n; i++) {\n                                auto [x, id] = b[j][i];\n                                rank[id][j] = i + 1;\n                                dec[i + 1][j] = id;\n                        }\n                }\n\n                int ans = INFF;\n                vector<int> vis(n + 1, 0);\n                vector<vector<int>> dist(n + 1, vector<int>(m + 1, INFF));\n                priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq;\n                vis[1] = 1;\n                for (int j = 1; j <= m; j++) dist[1][j] = 0, pq.push({dist[1][j], 1, j});\n                while (!pq.empty()) {\n                        auto [w, x, t] = pq.top();\n                        pq.pop();\n\n                        if (dist[x][t] < w) continue;\n\n                        if (x == n) ans = min(ans, w + c[n]);\n\n                        if (rank[x][t] < n) {\n                                int z = dec[rank[x][t] + 1][t];\n                                if (w < dist[z][t]) {\n                                        dist[z][t] = w;\n                                        pq.push({dist[z][t], z, t});\n                                }\n                        }\n\n                        if (rank[x][t] > 1) {\n                                int z = dec[rank[x][t] - 1][t];\n                                if (w + a[x][t] - a[z][t] < dist[z][t]) {\n                                        dist[z][t] = w + a[x][t] - a[z][t];\n                                        pq.push({dist[z][t], z, t});\n                                }\n                        }\n\n                        if (!vis[x]) {\n                                vis[x] = 1;\n                                for (int j = 1; j <= m; j++) {\n                                        if (w + c[x] < dist[x][j]) {\n                                                dist[x][j] = w + c[x];\n                                                pq.push({dist[x][j], x, j});\n                                        }\n                                }\n                        }\n                }\n\n                cout << ans << '\\n';\n        }\n        \n        return 0;\n}\n",
    "tags": [
      "data structures",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1936",
    "index": "D",
    "title": "Bitwise Paradox",
    "statement": "You are given two arrays $a$ and $b$ of size $n$ along with a fixed integer $v$.\n\nAn interval $[l, r]$ is called a \\textbf{good} interval if $(b_l \\mid b_{l+1} \\mid \\ldots \\mid b_r) \\ge v$, where $|$ denotes the bitwise OR operation. The \\textbf{beauty} of a good interval is defined as $\\max(a_l, a_{l+1}, \\ldots, a_r)$.\n\nYou are given $q$ queries of two types:\n\n- \"1 i x\": assign $b_i := x$;\n- \"2 l r\": find the \\textbf{minimum} beauty among all \\textbf{good} intervals $[l_0,r_0]$ satisfying $l \\le l_0 \\le r_0 \\le r$. If there is no suitable good interval, output $-1$ instead.\n\nPlease process all queries.",
    "tutorial": "First we use the line segment tree to maintain sequence $b$. For the nodes $[l,r]$ on each line segment tree, we maintain the first and last occurrence positions of each binary bit in the interval. We need to merge the two intervals, whether it is modification or query. Suppose you want to use the information of $[l, mid], [mid +1, r]$ to merge the information of $[l, r]$. Consider the answer that spans two intervals. If we want to make the $i$-th position of the interval OR $1$, then there are two possibilities Select the last occurrence position $P$ of the $i$-th bit in $[l,mid].$ Select the last occurrence position $P$ of the $i$-th bit in $[l,mid].$ Select the first occurrence position $Q$ of the $i$-th bit in $[mid+1,r].$ Select the first occurrence position $Q$ of the $i$-th bit in $[mid+1,r].$ Let $x = max(a[P], a[P+1],\\ldots, a[mid]), y = max(a[mid + 1], a[mid + 2], \\ldots, a[Q]).$ If $x<=y,$ we can choose the position $P$ greedily, because his price is smaller. If you choose $Q,$ then you must also choose $P,$ because choosing $P$ does not increase max $a.$ Otherwise, select $Q$ on the contrary. With the above greedy, then you can enumerate the first binary bit $i$ that is larger than $v$. The $i$-th bit of the interval OR must be $1$, and the $i$-th bit of $v$ is $0$. For the $j$-th $(j >i)$ bit, if the $j$-th bit of $v$ is $1$, then the $j$-th bit must also be $1$. The rest of the bits can be regarded as $0$ or $1$, you only need to deal with these bits that must be selected $1$ greedily, and expand the interval. You can use the st table $O(1)$ to find the interval max of $a$, so you can merge the information of the two intervals in the time of $O(log V)$. With the line segment tree, $O(q log n log V + n log V)$ can be done.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconstexpr int N = 5e5 + 10, V = 30, inf = INT_MAX, L = 18;\nint n, q, S, a[N], b[N];\nstruct Rmq\n{\n   int st[L][N];\n   void init()\n   {\n      for (int i = 1; i <= n; i++)\n         st[0][i] = a[i];\n      for (int i = 1; i < L; i++)\n      {\n         for (int j = 1; j <= n - (1 << i) + 1; j++)\n         {\n            st[i][j] = max(st[i - 1][j], st[i - 1][j + (1 << i - 1)]);\n         }\n      }\n   }\n   int qry(int l, int r)\n   {\n      int k = __lg(r - l + 1);\n      return max(st[k][l], st[k][r - (1 << k) + 1]);\n   }\n} ds;\nstruct Info\n{\n   int pre[V], suf[V];\n   int ans, l, r;\n   Info()\n   {\n      memset(pre, 0, sizeof(pre));\n      memset(suf, 0, sizeof(suf));\n      ans = inf, l = r = 0;\n   }\n   Info(const Info &x, const Info &y)\n   {\n      for (int i = 0; i < V; i++)\n      {\n         pre[i] = x.pre[i] ? x.pre[i] : y.pre[i];\n         suf[i] = y.suf[i] ? y.suf[i] : x.suf[i];\n      }\n      ans = inf, l = r = 0;\n   }\n   friend Info operator+(const Info &x, const Info &y)\n   {\n      Info z(x, y);\n      z.ans = min(x.ans, y.ans), z.l = x.l, z.r = y.r;\n      int pl = x.r, pr = y.l;\n      if (!pl)\n         return z;\n      for (int i = V - 1; i >= 0; i--)\n      {\n         int u = x.suf[i], v = y.pre[i];\n         if (u)\n            u = min(u, pl);\n         if (v)\n            v = max(v, pr);\n         int lans = u ? ds.qry(u, pr) : inf;\n         int rans = v ? ds.qry(pl, v) : inf;\n         if (lans < rans)\n         {\n            if (S >> i & 1)\n            {\n               if (lans < z.ans)\n                  pl = u;\n               else\n                  break;\n            }\n            else\n               z.ans = min(z.ans, lans);\n         }\n         else\n         {\n            if (S >> i & 1)\n            {\n               if (rans < z.ans)\n                  pr = v;\n               else\n                  break;\n            }\n            else\n               z.ans = min(z.ans, rans);\n         }\n      }\n      return z;\n   }\n   void clear()\n   {\n      *this = Info();\n   }\n   void upd(int p)\n   {\n      l = r = p, ans = b[p] > S ? a[p] : inf;\n      memset(pre, 0, sizeof(pre));\n      memset(suf, 0, sizeof(suf));\n      for (int j = 0; j < V; j++)\n      {\n         if (b[p] >> j & 1)\n         {\n            suf[j] = p;\n            pre[j] = p;\n         }\n      }\n   }\n} ans;\nvoid reply(const Info &cur)\n{\n   ans = ans + cur;\n}\nstruct Node\n{\n   Node *ls, *rs;\n   int l, r, mid;\n   Info info;\n   void up()\n   {\n      info = ls->info + rs->info;\n   }\n   void update(int p)\n   {\n      if (l == r)\n         return info.upd(l);\n      p <= mid ? ls->update(p) : rs->update(p);\n      up();\n   }\n   void query(int ql, int qr)\n   {\n      if (l >= ql && r <= qr)\n         return reply(info);\n      if (ql <= mid)\n         ls->query(ql, qr);\n      if (qr > mid)\n         rs->query(ql, qr);\n   }\n} mempool[N + 5 << 1], *cnt = mempool, *rt;\nNode *build(int l, int r)\n{\n   Node *u = cnt++;\n   int mid = l + r >> 1;\n   u->l = l, u->r = r, u->mid = mid;\n   if (l == r)\n   {\n      u->info.upd(l);\n      return u;\n   }\n   u->ls = build(l, mid);\n   u->rs = build(mid + 1, r);\n   u->up();\n   return u;\n}\n \nvoid solve()\n{\n   cin >> n >> S;\n   S--;\n   for (int i = 1; i <= n; i++)\n      cin >> a[i];\n   ds.init();\n   for (int i = 1; i <= n; i++)\n      cin >> b[i];\n   rt = build(1, n);\n   cin >> q;\n   for (int i = 0; i < q; i++)\n   {\n      int opt;\n      cin >> opt;\n      if (opt == 1)\n      {\n         int p, x;\n         cin >> p >> x;\n         b[p] = x;\n         rt->update(p);\n      }\n      else\n      {\n         int l, r;\n         cin >> l >> r;\n         ans.clear();\n         rt->query(l, r);\n         cout << (ans.ans == inf ? -1 : ans.ans) << ' ';\n      }\n   }\n   cout << \"\\n\";\n}\nint main()\n{\n#ifndef ONLINE_JUDGE\n   freopen(\"input.txt\", \"r\", stdin);\n   freopen(\"output.txt\", \"w\", stdout);\n#endif\n   ios_base::sync_with_stdio(0);\n   cin.tie(0);\n   cout.tie(0);\n   ios::sync_with_stdio(false), cin.tie(0);\n   int t = 0;\n   cin >> t;\n   while (t--)\n   {\n      solve();\n   }\n \n   // \tcerr << 1.0 * clock() / CLOCKS_PER_SEC << '\\n';\n   return 0;\n}\n",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1936",
    "index": "E",
    "title": "Yet Yet Another Permutation Problem",
    "statement": "You are given a permutation $p$ of length $n$.\n\nPlease count the number of permutations $q$ of length $n$ which satisfy the following:\n\n- for each $1 \\le i < n$, $\\max(q_1,\\ldots,q_i) \\neq \\max(p_1,\\ldots,p_i)$.\n\nSince the answer may be large, output the answer modulo $998\\,244\\,353$.",
    "tutorial": "We found it difficult to directly calculate all valid permutations. How about calculating all invalid permutations? Can you come up with an $O(n^2)$ DP solution? How to optimize the $O(n^2)$ DP solution? We found it difficult to directly calculate all valid permutations. Consider calculating all invalid permutations and subtract it from $n!$. Let's first make some notes. We note $P_i=max(p_1,...,p_i),Q_i=max(q_1,...,q_i)$,and $last_i=max(j)(P_j \\neq P_i)$.And note the values of all extreme points is $val[1,...,m]$ and positions is $pos[1,...,m]$. For example,$p=[3,1,4,2,6,5]$,we get $m=3$, $val=[3,4,6]$ and $pos=[1,3,5]$. Let's call a permutation $q$ \"i-invalid\" if there's an index $j$ satisfying $Q_j=P_j=val_i$. Note $S_i$ as the set of all \"i-invalid\" permutations.According to the Inclusion-Exclusion Principle,the answer is $n!-(|S_1|+|S_2|+...)+(|S_1 \\cap S_2|+|S_1 \\cap S_3|+...)-...$ Consider put $val_i$ in $q$ to make $q$ \"i-invalid\".There're $2$ kinds of ways: $q_j=val_i(1 \\le j < pos_i)$ and $Q_{pos_i}=val_i$; $q_j=val_i(1 \\le j < pos_i)$ and $Q_{pos_i}=val_i$; $q_j=val_i(pos_i \\le j< pos_{i+1})$ and $Q_{pos_i}=val_i$. $q_j=val_i(pos_i \\le j< pos_{i+1})$ and $Q_{pos_i}=val_i$. In both cases,we call the first $max(j,pos_i)$ numbers are \"determined\". In other words,they're some numbers in $[1,val_i]$. Then we can find an $O(n^2)$ DP. Note $dp_{i,j}$ - $i$ stands for the first $i$ numbers is \"determined\",and $j$ stands for $j$ extreme values are \"invalid\". In fact we only care about the parity of $j$,so $j=0,1$. Note for the first $i$ numbers are \"determined\" automatically means $Q_i=P_i$. In addition,$q_i=P_i(P_i=P_{i-1})$ or $q_i<P_i(P_i \\neq P_{i-1})$. We get a DP formula $dp_{i,j}= \\Sigma_{k=0}^{last_i} dp_{k,j \\oplus 1} \\cdot A^{P_i-k-1}_{i-k-1} \\cdot (P_i==P_{i+1}?1:i-k)$ Here is a small trick to reduce the constant. If we note $f_i=dp_{i,0}-dp_{i,1}$, we get a more concise formula $f_{i}= -\\Sigma_{j=0}^{last_i} f_{j} \\cdot A^{P_i-j-1}_{i-j-1} \\cdot (P_i==P_{i+1}?1:i-j)$ We perform the following transformation on the formula. (1) For $i$ satisfying $P_i=P_{i-1}$, we get $f_{i}= -\\Sigma_{j=0}^{last_i} f_{j} \\cdot A^{P_i-j-1}_{i-j-1} = -[(P_i-i)!]^{-1} \\Sigma_{j=0}^{last_i} f_{j} \\cdot (P_i-j-1)!$ (2) For $i$ satisfying $P_i \\neq P_{i-1}$, we get $f_{i}= -\\Sigma_{j=0}^{last_i} f_{j} \\cdot A^{P_i-j-1}_{i-j-1} \\cdot (i-j) = -i[(P_i-i)!]^{-1} \\Sigma_{j=0}^{last_i} f_{j} \\cdot (P_i-j-1)! + [(P_i-i)!]^{-1} \\Sigma_{j=0}^{last_i} jf_{j} \\cdot (P_i-j-1)!$ After that, we have transformed the formula into a classical form $f(i)= h(i) \\Sigma_{j=0}^{i-1} f(j) \\cdot g(i-j)$, which can be calculate in $O(n log^2 n)$ by D&C+FFT.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define all(a) a.begin(),a.end()\n#define pb push_back\n#define sz(a) ((int)a.size())\n\nusing ll=long long;\nusing u32=unsigned int;\nusing u64=unsigned long long;\nusing i128=__int128;\nusing u128=unsigned __int128;\nusing f128=__float128;\n\nusing pii=pair<int,int>;\nusing pll=pair<ll,ll>;\n\ntemplate<typename T> using vc=vector<T>;\ntemplate<typename T> using vvc=vc<vc<T>>;\ntemplate<typename T> using vvvc=vc<vvc<T>>;\n\nusing vi=vc<int>;\nusing vll=vc<ll>;\nusing vvi=vc<vi>;\nusing vvll=vc<vll>;\n\n#define vv(type,name,n,...) \\\n    vector<vector<type>> name(n,vector<type>(__VA_ARGS__))\n#define vvv(type,name,n,m,...) \\\n    vector<vector<vector<type>>> name(n,vector<vector<type>>(m,vector<type>(__VA_ARGS__)))\n\ntemplate<typename T> using min_heap=priority_queue<T,vector<T>,greater<T>>;\ntemplate<typename T> using max_heap=priority_queue<T>;\n\n// https://trap.jp/post/1224/\n#define rep1(n) for(ll i=0; i<(ll)(n); ++i)\n#define rep2(i,n) for(ll i=0; i<(ll)(n); ++i)\n#define rep3(i,a,b) for(ll i=(ll)(a); i<(ll)(b); ++i)\n#define rep4(i,a,b,c) for(ll i=(ll)(a); i<(ll)(b); i+=(c))\n#define cut4(a,b,c,d,e,...) e\n#define rep(...) cut4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)\n#define per1(n) for(ll i=((ll)n)-1; i>=0; --i)\n#define per2(i,n) for(ll i=((ll)n)-1; i>=0; --i)\n#define per3(i,a,b) for(ll i=((ll)a)-1; i>=(ll)(b); --i)\n#define per4(i,a,b,c) for(ll i=((ll)a)-1; i>=(ll)(b); i-=(c))\n#define per(...) cut4(__VA_ARGS__,per4,per3,per2,per1)(__VA_ARGS__)\n#define rep_subset(i,s) for(ll i=(s); i>=0; i=(i==0?-1:(i-1)&(s)))\n\ntemplate<typename T, typename S> constexpr T ifloor(const T a, const S b){return a/b-(a%b&&(a^b)<0);}\ntemplate<typename T, typename S> constexpr T iceil(const T a, const S b){return ifloor(a+b-1,b);}\n\ntemplate<typename T>\nvoid sort_unique(vector<T> &vec){\n    sort(vec.begin(),vec.end());\n    vec.resize(unique(vec.begin(),vec.end())-vec.begin());\n}\n\ntemplate<typename T, typename S> constexpr bool chmin(T &a, const S b){if(a>b) return a=b,true; return false;}\ntemplate<typename T, typename S> constexpr bool chmax(T &a, const S b){if(a<b) return a=b,true; return false;}\n\ntemplate<typename T, typename S> istream& operator >> (istream& i, pair<T,S> &p){return i >> p.first >> p.second;}\ntemplate<typename T, typename S> ostream& operator << (ostream& o, const pair<T,S> &p){return o << p.first << ' ' << p.second;}\n\n#ifdef i_am_noob\n#define bug(...) cerr << \"#\" << __LINE__ << ' ' << #__VA_ARGS__ << \"- \", _do(__VA_ARGS__)\ntemplate<typename T> void _do(vector<T> x){for(auto i: x) cerr << i << ' ';cerr << \"\\n\";}\ntemplate<typename T> void _do(set<T> x){for(auto i: x) cerr << i << ' ';cerr << \"\\n\";}\ntemplate<typename T> void _do(unordered_set<T> x){for(auto i: x) cerr << i << ' ';cerr << \"\\n\";}\ntemplate<typename T> void _do(T && x) {cerr << x << endl;}\ntemplate<typename T, typename ...S> void _do(T && x, S&&...y) {cerr << x << \", \"; _do(y...);}\n#else\n#define bug(...) 777771449\n#endif\n\ntemplate<typename T> void print(vector<T> x){for(auto i: x) cout << i << ' ';cout << \"\\n\";}\ntemplate<typename T> void print(set<T> x){for(auto i: x) cout << i << ' ';cout << \"\\n\";}\ntemplate<typename T> void print(unordered_set<T> x){for(auto i: x) cout << i << ' ';cout << \"\\n\";}\ntemplate<typename T> void print(T && x) {cout << x << \"\\n\";}\ntemplate<typename T, typename... S> void print(T && x, S&&... y) {cout << x << ' ';print(y...);}\n\ntemplate<typename T> istream& operator >> (istream& i, vector<T> &vec){for(auto &x: vec) i >> x; return i;}\n\nvvi read_graph(int n, int m, int base=1){\n    vvi adj(n);\n    for(int i=0,u,v; i<m; ++i){\n        cin >> u >> v,u-=base,v-=base;\n        adj[u].pb(v),adj[v].pb(u);\n    }\n    return adj;\n}\n\nvvi read_tree(int n, int base=1){return read_graph(n,n-1,base);}\n\ntemplate<typename T, typename S> pair<T,S> operator + (const pair<T,S> &a, const pair<T,S> &b){return {a.first+b.first,a.second+b.second};}\n\ntemplate<typename T> constexpr T inf=0;\ntemplate<> constexpr int inf<int> = 0x3f3f3f3f;\ntemplate<> constexpr ll inf<ll> = 0x3f3f3f3f3f3f3f3f;\n\ntemplate<typename T> vector<T> operator += (vector<T> &a, int val){for(auto &i: a) i+=val; return a;}\n\ntemplate<typename T> T isqrt(const T &x){T y=sqrt(x+2); while(y*y>x) y--; return y;}\n\n#define ykh mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())\n\n\n\n#include <utility>\n\nnamespace atcoder {\n\nnamespace internal {\n\n// @param m `1 <= m`\n// @return x mod m\nconstexpr long long safe_mod(long long x, long long m) {\n    x %= m;\n    if (x < 0) x += m;\n    return x;\n}\n\n// Fast modular multiplication by barrett reduction\n// Reference: https://en.wikipedia.org/wiki/Barrett_reduction\n// NOTE: reconsider after Ice Lake\nstruct barrett {\n    unsigned int _m;\n    unsigned long long im;\n\n    // @param m `1 <= m < 2^31`\n    barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}\n\n    // @return m\n    unsigned int umod() const { return _m; }\n\n    // @param a `0 <= a < m`\n    // @param b `0 <= b < m`\n    // @return `a * b % m`\n    unsigned int mul(unsigned int a, unsigned int b) const {\n        // [1] m = 1\n        // a = b = im = 0, so okay\n\n        // [2] m >= 2\n        // im = ceil(2^64 / m)\n        // -> im * m = 2^64 + r (0 <= r < m)\n        // let z = a*b = c*m + d (0 <= c, d < m)\n        // a*b * im = (c*m + d) * im = c*(im*m) + d*im = c*2^64 + c*r + d*im\n        // c*r + d*im < m * m + m * im < m * m + 2^64 + m <= 2^64 + m * (m + 1) < 2^64 * 2\n        // ((ab * im) >> 64) == c or c + 1\n        unsigned long long z = a;\n        z *= b;\n#ifdef _MSC_VER\n        unsigned long long x;\n        _umul128(z, im, &x);\n#else\n        unsigned long long x =\n            (unsigned long long)(((unsigned __int128)(z)*im) >> 64);\n#endif\n        unsigned int v = (unsigned int)(z - x * _m);\n        if (_m <= v) v += _m;\n        return v;\n    }\n};\n\n// @param n `0 <= n`\n// @param m `1 <= m`\n// @return `(x ** n) % m`\nconstexpr long long pow_mod_constexpr(long long x, long long n, int m) {\n    if (m == 1) return 0;\n    unsigned int _m = (unsigned int)(m);\n    unsigned long long r = 1;\n    unsigned long long y = safe_mod(x, m);\n    while (n) {\n        if (n & 1) r = (r * y) % _m;\n        y = (y * y) % _m;\n        n >>= 1;\n    }\n    return r;\n}\n\n// Reference:\n// M. Forisek and J. Jancina,\n// Fast Primality Testing for Integers That Fit into a Machine Word\n// @param n `0 <= n`\nconstexpr bool is_prime_constexpr(int n) {\n    if (n <= 1) return false;\n    if (n == 2 || n == 7 || n == 61) return true;\n    if (n % 2 == 0) return false;\n    long long d = n - 1;\n    while (d % 2 == 0) d /= 2;\n    constexpr long long bases[3] = {2, 7, 61};\n    for (long long a : bases) {\n        long long t = d;\n        long long y = pow_mod_constexpr(a, t, n);\n        while (t != n - 1 && y != 1 && y != n - 1) {\n            y = y * y % n;\n            t <<= 1;\n        }\n        if (y != n - 1 && t % 2 == 0) {\n            return false;\n        }\n    }\n    return true;\n}\ntemplate <int n> constexpr bool is_prime = is_prime_constexpr(n);\n\n// @param b `1 <= b`\n// @return pair(g, x) s.t. g = gcd(a, b), xa = g (mod b), 0 <= x < b/g\nconstexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {\n    a = safe_mod(a, b);\n    if (a == 0) return {b, 0};\n\n    // Contracts:\n    // [1] s - m0 * a = 0 (mod b)\n    // [2] t - m1 * a = 0 (mod b)\n    // [3] s * |m1| + t * |m0| <= b\n    long long s = b, t = a;\n    long long m0 = 0, m1 = 1;\n\n    while (t) {\n        long long u = s / t;\n        s -= t * u;\n        m0 -= m1 * u;  // |m1 * u| <= |m1| * s <= b\n\n        // [3]:\n        // (s - t * u) * |m1| + t * |m0 - m1 * u|\n        // <= s * |m1| - t * u * |m1| + t * (|m0| + |m1| * u)\n        // = s * |m1| + t * |m0| <= b\n\n        auto tmp = s;\n        s = t;\n        t = tmp;\n        tmp = m0;\n        m0 = m1;\n        m1 = tmp;\n    }\n    // by [3]: |m0| <= b/g\n    // by g != b: |m0| < b/g\n    if (m0 < 0) m0 += b / s;\n    return {s, m0};\n}\n\n// Compile time primitive root\n// @param m must be prime\n// @return primitive root (and minimum in now)\nconstexpr int primitive_root_constexpr(int m) {\n    if (m == 2) return 1;\n    if (m == 167772161) return 3;\n    if (m == 469762049) return 3;\n    if (m == 754974721) return 11;\n    if (m == 998244353) return 3;\n    int divs[20] = {};\n    divs[0] = 2;\n    int cnt = 1;\n    int x = (m - 1) / 2;\n    while (x % 2 == 0) x /= 2;\n    for (int i = 3; (long long)(i)*i <= x; i += 2) {\n        if (x % i == 0) {\n            divs[cnt++] = i;\n            while (x % i == 0) {\n                x /= i;\n            }\n        }\n    }\n    if (x > 1) {\n        divs[cnt++] = x;\n    }\n    for (int g = 2;; g++) {\n        bool ok = true;\n        for (int i = 0; i < cnt; i++) {\n            if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {\n                ok = false;\n                break;\n            }\n        }\n        if (ok) return g;\n    }\n}\ntemplate <int m> constexpr int primitive_root = primitive_root_constexpr(m);\n\n}  // namespace internal\n\n}  // namespace atcoder\n\n\n#include <cassert>\n#include <numeric>\n#include <type_traits>\n\nnamespace atcoder {\n\nnamespace internal {\n\n#ifndef _MSC_VER\ntemplate <class T>\nusing is_signed_int128 =\n    typename std::conditional<std::is_same<T, __int128_t>::value ||\n                                  std::is_same<T, __int128>::value,\n                              std::true_type,\n                              std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int128 =\n    typename std::conditional<std::is_same<T, __uint128_t>::value ||\n                                  std::is_same<T, unsigned __int128>::value,\n                              std::true_type,\n                              std::false_type>::type;\n\ntemplate <class T>\nusing make_unsigned_int128 =\n    typename std::conditional<std::is_same<T, __int128_t>::value,\n                              __uint128_t,\n                              unsigned __int128>;\n\ntemplate <class T>\nusing is_integral = typename std::conditional<std::is_integral<T>::value ||\n                                                  is_signed_int128<T>::value ||\n                                                  is_unsigned_int128<T>::value,\n                                              std::true_type,\n                                              std::false_type>::type;\n\ntemplate <class T>\nusing is_signed_int = typename std::conditional<(is_integral<T>::value &&\n                                                 std::is_signed<T>::value) ||\n                                                    is_signed_int128<T>::value,\n                                                std::true_type,\n                                                std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int =\n    typename std::conditional<(is_integral<T>::value &&\n                               std::is_unsigned<T>::value) ||\n                                  is_unsigned_int128<T>::value,\n                              std::true_type,\n                              std::false_type>::type;\n\ntemplate <class T>\nusing to_unsigned = typename std::conditional<\n    is_signed_int128<T>::value,\n    make_unsigned_int128<T>,\n    typename std::conditional<std::is_signed<T>::value,\n                              std::make_unsigned<T>,\n                              std::common_type<T>>::type>::type;\n\n#else\n\ntemplate <class T> using is_integral = typename std::is_integral<T>;\n\ntemplate <class T>\nusing is_signed_int =\n    typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,\n                              std::true_type,\n                              std::false_type>::type;\n\ntemplate <class T>\nusing is_unsigned_int =\n    typename std::conditional<is_integral<T>::value &&\n                                  std::is_unsigned<T>::value,\n                              std::true_type,\n                              std::false_type>::type;\n\ntemplate <class T>\nusing to_unsigned = typename std::conditional<is_signed_int<T>::value,\n                                              std::make_unsigned<T>,\n                                              std::common_type<T>>::type;\n\n#endif\n\ntemplate <class T>\nusing is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;\n\ntemplate <class T>\nusing is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;\n\ntemplate <class T> using to_unsigned_t = typename to_unsigned<T>::type;\n\n}  // namespace internal\n\n}  // namespace atcoder\n\n#include <cassert>\n#include <numeric>\n#include <type_traits>\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\nnamespace atcoder {\n\nnamespace internal {\n\nstruct modint_base {};\nstruct static_modint_base : modint_base {};\n\ntemplate <class T> using is_modint = std::is_base_of<modint_base, T>;\ntemplate <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;\n\n}  // namespace internal\n\ntemplate <int m, std::enable_if_t<(1 <= m)>* = nullptr>\nstruct static_modint : internal::static_modint_base {\n    using mint = static_modint;\n\n  public:\n    static constexpr int mod() { return m; }\n    static mint raw(int v) {\n        mint x;\n        x._v = v;\n        return x;\n    }\n\n    static_modint() : _v(0) {}\n    template <class T, internal::is_signed_int_t<T>* = nullptr>\n    static_modint(T v) {\n        long long x = (long long)(v % (long long)(umod()));\n        if (x < 0) x += umod();\n        _v = (unsigned int)(x);\n    }\n    template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n    static_modint(T v) {\n        _v = (unsigned int)(v % umod());\n    }\n    static_modint(bool v) { _v = ((unsigned int)(v) % umod()); }\n\n    unsigned int val() const { return _v; }\n\n    mint& operator++() {\n        _v++;\n        if (_v == umod()) _v = 0;\n        return *this;\n    }\n    mint& operator--() {\n        if (_v == 0) _v = umod();\n        _v--;\n        return *this;\n    }\n    mint operator++(int) {\n        mint result = *this;\n        ++*this;\n        return result;\n    }\n    mint operator--(int) {\n        mint result = *this;\n        --*this;\n        return result;\n    }\n\n    mint& operator+=(const mint& rhs) {\n        _v += rhs._v;\n        if (_v >= umod()) _v -= umod();\n        return *this;\n    }\n    mint& operator-=(const mint& rhs) {\n        _v -= rhs._v;\n        if (_v >= umod()) _v += umod();\n        return *this;\n    }\n    mint& operator*=(const mint& rhs) {\n        unsigned long long z = _v;\n        z *= rhs._v;\n        _v = (unsigned int)(z % umod());\n        return *this;\n    }\n    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n\n    mint operator+() const { return *this; }\n    mint operator-() const { return mint() - *this; }\n\n    mint pow(long long n) const {\n        assert(0 <= n);\n        mint x = *this, r = 1;\n        while (n) {\n            if (n & 1) r *= x;\n            x *= x;\n            n >>= 1;\n        }\n        return r;\n    }\n    mint inv() const {\n        if (prime) {\n            assert(_v);\n            return pow(umod() - 2);\n        } else {\n            auto eg = internal::inv_gcd(_v, m);\n            assert(eg.first == 1);\n            return eg.second;\n        }\n    }\n\n    friend mint operator+(const mint& lhs, const mint& rhs) {\n        return mint(lhs) += rhs;\n    }\n    friend mint operator-(const mint& lhs, const mint& rhs) {\n        return mint(lhs) -= rhs;\n    }\n    friend mint operator*(const mint& lhs, const mint& rhs) {\n        return mint(lhs) *= rhs;\n    }\n    friend mint operator/(const mint& lhs, const mint& rhs) {\n        return mint(lhs) /= rhs;\n    }\n    friend bool operator==(const mint& lhs, const mint& rhs) {\n        return lhs._v == rhs._v;\n    }\n    friend bool operator!=(const mint& lhs, const mint& rhs) {\n        return lhs._v != rhs._v;\n    }\n\n  private:\n    unsigned int _v;\n    static constexpr unsigned int umod() { return m; }\n    static constexpr bool prime = internal::is_prime<m>;\n};\n\ntemplate <int id> struct dynamic_modint : internal::modint_base {\n    using mint = dynamic_modint;\n\n  public:\n    static int mod() { return (int)(bt.umod()); }\n    static void set_mod(int m) {\n        assert(1 <= m);\n        bt = internal::barrett(m);\n    }\n    static mint raw(int v) {\n        mint x;\n        x._v = v;\n        return x;\n    }\n\n    dynamic_modint() : _v(0) {}\n    template <class T, internal::is_signed_int_t<T>* = nullptr>\n    dynamic_modint(T v) {\n        long long x = (long long)(v % (long long)(mod()));\n        if (x < 0) x += mod();\n        _v = (unsigned int)(x);\n    }\n    template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n    dynamic_modint(T v) {\n        _v = (unsigned int)(v % mod());\n    }\n    dynamic_modint(bool v) { _v = ((unsigned int)(v) % mod()); }\n\n    unsigned int val() const { return _v; }\n\n    mint& operator++() {\n        _v++;\n        if (_v == umod()) _v = 0;\n        return *this;\n    }\n    mint& operator--() {\n        if (_v == 0) _v = umod();\n        _v--;\n        return *this;\n    }\n    mint operator++(int) {\n        mint result = *this;\n        ++*this;\n        return result;\n    }\n    mint operator--(int) {\n        mint result = *this;\n        --*this;\n        return result;\n    }\n\n    mint& operator+=(const mint& rhs) {\n        _v += rhs._v;\n        if (_v >= umod()) _v -= umod();\n        return *this;\n    }\n    mint& operator-=(const mint& rhs) {\n        _v += mod() - rhs._v;\n        if (_v >= umod()) _v -= umod();\n        return *this;\n    }\n    mint& operator*=(const mint& rhs) {\n        _v = bt.mul(_v, rhs._v);\n        return *this;\n    }\n    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n\n    mint operator+() const { return *this; }\n    mint operator-() const { return mint() - *this; }\n\n    mint pow(long long n) const {\n        assert(0 <= n);\n        mint x = *this, r = 1;\n        while (n) {\n            if (n & 1) r *= x;\n            x *= x;\n            n >>= 1;\n        }\n        return r;\n    }\n    mint inv() const {\n        auto eg = internal::inv_gcd(_v, mod());\n        assert(eg.first == 1);\n        return eg.second;\n    }\n\n    friend mint operator+(const mint& lhs, const mint& rhs) {\n        return mint(lhs) += rhs;\n    }\n    friend mint operator-(const mint& lhs, const mint& rhs) {\n        return mint(lhs) -= rhs;\n    }\n    friend mint operator*(const mint& lhs, const mint& rhs) {\n        return mint(lhs) *= rhs;\n    }\n    friend mint operator/(const mint& lhs, const mint& rhs) {\n        return mint(lhs) /= rhs;\n    }\n    friend bool operator==(const mint& lhs, const mint& rhs) {\n        return lhs._v == rhs._v;\n    }\n    friend bool operator!=(const mint& lhs, const mint& rhs) {\n        return lhs._v != rhs._v;\n    }\n\n  private:\n    unsigned int _v;\n    static internal::barrett bt;\n    static unsigned int umod() { return bt.umod(); }\n};\ntemplate <int id> internal::barrett dynamic_modint<id>::bt = 998244353;\n\nusing modint998244353 = static_modint<998244353>;\nusing modint1000000007 = static_modint<1000000007>;\nusing modint = dynamic_modint<-1>;\n\nnamespace internal {\n\ntemplate <class T>\nusing is_static_modint = std::is_base_of<internal::static_modint_base, T>;\n\ntemplate <class T>\nusing is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;\n\ntemplate <class> struct is_dynamic_modint : public std::false_type {};\ntemplate <int id>\nstruct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};\n\ntemplate <class T>\nusing is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;\n\n}  // namespace internal\n\n}  // namespace atcoder\n\n\n#include <algorithm>\n#include <array>\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\nnamespace atcoder {\n\nnamespace internal {\n\n// @param n `0 <= n`\n// @return minimum non-negative `x` s.t. `n <= 2**x`\nint ceil_pow2(int n) {\n    int x = 0;\n    while ((1U << x) < (unsigned int)(n)) x++;\n    return x;\n}\n\n// @param n `1 <= n`\n// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`\nint bsf(unsigned int n) {\n#ifdef _MSC_VER\n    unsigned long index;\n    _BitScanForward(&index, n);\n    return index;\n#else\n    return __builtin_ctz(n);\n#endif\n}\n\n}  // namespace internal\n\n}  // namespace atcoder\n\n#include <cassert>\n#include <type_traits>\n#include <vector>\n\nnamespace atcoder {\n\nnamespace internal {\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\nvoid butterfly(std::vector<mint>& a) {\n    static constexpr int g = internal::primitive_root<mint::mod()>;\n    int n = int(a.size());\n    int h = internal::ceil_pow2(n);\n\n    static bool first = true;\n    static mint sum_e[30];  // sum_e[i] = ies[0] * ... * ies[i - 1] * es[i]\n    if (first) {\n        first = false;\n        mint es[30], ies[30];  // es[i]^(2^(2+i)) == 1\n        int cnt2 = bsf(mint::mod() - 1);\n        mint e = mint(g).pow((mint::mod() - 1) >> cnt2), ie = e.inv();\n        for (int i = cnt2; i >= 2; i--) {\n            // e^(2^i) == 1\n            es[i - 2] = e;\n            ies[i - 2] = ie;\n            e *= e;\n            ie *= ie;\n        }\n        mint now = 1;\n        for (int i = 0; i <= cnt2 - 2; i++) {\n            sum_e[i] = es[i] * now;\n            now *= ies[i];\n        }\n    }\n    for (int ph = 1; ph <= h; ph++) {\n        int w = 1 << (ph - 1), p = 1 << (h - ph);\n        mint now = 1;\n        for (int s = 0; s < w; s++) {\n            int offset = s << (h - ph + 1);\n            for (int i = 0; i < p; i++) {\n                auto l = a[i + offset];\n                auto r = a[i + offset + p] * now;\n                a[i + offset] = l + r;\n                a[i + offset + p] = l - r;\n            }\n            now *= sum_e[bsf(~(unsigned int)(s))];\n        }\n    }\n}\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\nvoid butterfly_inv(std::vector<mint>& a) {\n    static constexpr int g = internal::primitive_root<mint::mod()>;\n    int n = int(a.size());\n    int h = internal::ceil_pow2(n);\n\n    static bool first = true;\n    static mint sum_ie[30];  // sum_ie[i] = es[0] * ... * es[i - 1] * ies[i]\n    if (first) {\n        first = false;\n        mint es[30], ies[30];  // es[i]^(2^(2+i)) == 1\n        int cnt2 = bsf(mint::mod() - 1);\n        mint e = mint(g).pow((mint::mod() - 1) >> cnt2), ie = e.inv();\n        for (int i = cnt2; i >= 2; i--) {\n            // e^(2^i) == 1\n            es[i - 2] = e;\n            ies[i - 2] = ie;\n            e *= e;\n            ie *= ie;\n        }\n        mint now = 1;\n        for (int i = 0; i <= cnt2 - 2; i++) {\n            sum_ie[i] = ies[i] * now;\n            now *= es[i];\n        }\n    }\n\n    for (int ph = h; ph >= 1; ph--) {\n        int w = 1 << (ph - 1), p = 1 << (h - ph);\n        mint inow = 1;\n        for (int s = 0; s < w; s++) {\n            int offset = s << (h - ph + 1);\n            for (int i = 0; i < p; i++) {\n                auto l = a[i + offset];\n                auto r = a[i + offset + p];\n                a[i + offset] = l + r;\n                a[i + offset + p] =\n                    (unsigned long long)(mint::mod() + l.val() - r.val()) *\n                    inow.val();\n            }\n            inow *= sum_ie[bsf(~(unsigned int)(s))];\n        }\n    }\n}\n\n}  // namespace internal\n\ntemplate <class mint, internal::is_static_modint_t<mint>* = nullptr>\nstd::vector<mint> convolution(std::vector<mint> a, std::vector<mint> b) {\n    int n = int(a.size()), m = int(b.size());\n    if (!n || !m) return {};\n    if (std::min(n, m) <= 60) {\n        if (n < m) {\n            std::swap(n, m);\n            std::swap(a, b);\n        }\n        std::vector<mint> ans(n + m - 1);\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                ans[i + j] += a[i] * b[j];\n            }\n        }\n        return ans;\n    }\n    int z = 1 << internal::ceil_pow2(n + m - 1);\n    a.resize(z);\n    internal::butterfly(a);\n    b.resize(z);\n    internal::butterfly(b);\n    for (int i = 0; i < z; i++) {\n        a[i] *= b[i];\n    }\n    internal::butterfly_inv(a);\n    a.resize(n + m - 1);\n    mint iz = mint(z).inv();\n    for (int i = 0; i < n + m - 1; i++) a[i] *= iz;\n    return a;\n}\n\ntemplate <unsigned int mod = 998244353,\n          class T,\n          std::enable_if_t<internal::is_integral<T>::value>* = nullptr>\nstd::vector<T> convolution(const std::vector<T>& a, const std::vector<T>& b) {\n    int n = int(a.size()), m = int(b.size());\n    if (!n || !m) return {};\n\n    using mint = static_modint<mod>;\n    std::vector<mint> a2(n), b2(m);\n    for (int i = 0; i < n; i++) {\n        a2[i] = mint(a[i]);\n    }\n    for (int i = 0; i < m; i++) {\n        b2[i] = mint(b[i]);\n    }\n    auto c2 = convolution(move(a2), move(b2));\n    std::vector<T> c(n + m - 1);\n    for (int i = 0; i < n + m - 1; i++) {\n        c[i] = c2[i].val();\n    }\n    return c;\n}\n\nstd::vector<long long> convolution_ll(const std::vector<long long>& a,\n                                      const std::vector<long long>& b) {\n    int n = int(a.size()), m = int(b.size());\n    if (!n || !m) return {};\n\n    static constexpr unsigned long long MOD1 = 754974721;  // 2^24\n    static constexpr unsigned long long MOD2 = 167772161;  // 2^25\n    static constexpr unsigned long long MOD3 = 469762049;  // 2^26\n    static constexpr unsigned long long M2M3 = MOD2 * MOD3;\n    static constexpr unsigned long long M1M3 = MOD1 * MOD3;\n    static constexpr unsigned long long M1M2 = MOD1 * MOD2;\n    static constexpr unsigned long long M1M2M3 = MOD1 * MOD2 * MOD3;\n\n    static constexpr unsigned long long i1 =\n        internal::inv_gcd(MOD2 * MOD3, MOD1).second;\n    static constexpr unsigned long long i2 =\n        internal::inv_gcd(MOD1 * MOD3, MOD2).second;\n    static constexpr unsigned long long i3 =\n        internal::inv_gcd(MOD1 * MOD2, MOD3).second;\n\n    auto c1 = convolution<MOD1>(a, b);\n    auto c2 = convolution<MOD2>(a, b);\n    auto c3 = convolution<MOD3>(a, b);\n\n    std::vector<long long> c(n + m - 1);\n    for (int i = 0; i < n + m - 1; i++) {\n        unsigned long long x = 0;\n        x += (c1[i] * i1) % MOD1 * M2M3;\n        x += (c2[i] * i2) % MOD2 * M1M3;\n        x += (c3[i] * i3) % MOD3 * M1M2;\n        // B = 2^63, -B <= x, r(real value) < B\n        // (x, x - M, x - 2M, or x - 3M) = r (mod 2B)\n        // r = c1[i] (mod MOD1)\n        // focus on MOD1\n        // r = x, x - M', x - 2M', x - 3M' (M' = M % 2^64) (mod 2B)\n        // r = x,\n        //     x - M' + (0 or 2B),\n        //     x - 2M' + (0, 2B or 4B),\n        //     x - 3M' + (0, 2B, 4B or 6B) (without mod!)\n        // (r - x) = 0, (0)\n        //           - M' + (0 or 2B), (1)\n        //           -2M' + (0 or 2B or 4B), (2)\n        //           -3M' + (0 or 2B or 4B or 6B) (3) (mod MOD1)\n        // we checked that\n        //   ((1) mod MOD1) mod 5 = 2\n        //   ((2) mod MOD1) mod 5 = 3\n        //   ((3) mod MOD1) mod 5 = 4\n        long long diff =\n            c1[i] - internal::safe_mod((long long)(x), (long long)(MOD1));\n        if (diff < 0) diff += MOD1;\n        static constexpr unsigned long long offset[5] = {\n            0, 0, M1M2M3, 2 * M1M2M3, 3 * M1M2M3};\n        x -= offset[diff % 5];\n        c[i] = x;\n    }\n\n    return c;\n}\n\n}  // namespace atcoder\n\nusing namespace atcoder;\n\nusing mint=modint998244353;\n//using mint=modint1000000007;\n\ntemplate<int mod>\nstruct nCr{\n    vector<static_modint<mod>> fac,inv,ifac;\n    void calc(int n){\n        fac.resize(n+1),inv.resize(n+1),ifac.resize(n+1);\n        fac[0]=inv[1]=ifac[0]=1;\n        for(int i=1; i<=n; ++i) fac[i]=fac[i-1]*static_modint<mod>::raw(i);\n        for(int i=2; i<=n; ++i) inv[i]=inv[mod%i]*static_modint<mod>::raw(mod-mod/i);\n        for(int i=1; i<=n; ++i) ifac[i]=ifac[i-1]*inv[i];\n    }\n    static_modint<mod> C(int n, int m){\n        if(m<0||m>n) return 0;\n        return fac[n]*ifac[m]*ifac[n-m];\n    }\n};\n\nnCr<998244353> de;\n\nvoid ahcorz(){\n    // (a_i - j)! / (a_i - i)! (a_i = a_j)\n    // (a_i - j - 1)! / (a_i - i)! * (i - j) (a_i != a_j)\n    int n; cin >> n;\n    de.calc(n+1);\n    vi a; a.pb(0);\n    rep(n){\n        int x; cin >> x;\n        a.pb(max(a.back(),x));\n    }\n    vc<mint> dp(n+1),aux(n+1);\n    auto solve=[&](auto &self, int l, int r) -> void{\n        if(l+1==r){\n            if(l==0) dp[l]=-1;\n            else dp[l]+=aux[l]*l;\n            dp[l]*=de.ifac[a[l]-l];\n            return;\n        }\n        int mid=l+r>>1;\n        self(self,l,mid);\n        if(a[mid]==a[mid-1]){\n            int x=mid-1,y=mid;\n            while(x-1>=l&&a[x-1]==a[mid]) x--;\n            while(y+1<r&&a[y+1]==a[mid]) y++;\n            mint tot,tot1,tot2;\n            rep(i,x,mid) tot+=dp[i]*de.fac[a[mid]-i],tot1+=dp[i]*de.fac[a[mid]-i-1],tot2+=dp[i]*de.fac[a[mid]-i-1]*i;\n            rep(i,mid,y+1) dp[i]-=tot-(tot1*i-tot2);\n        }\n        vc<mint> vec;\n        rep(i,a[mid]-mid,a[r-1]-(l+1)+1) vec.pb(de.fac[i]);\n        vc<mint> vec1,vec2;\n        rep(i,l,mid) vec1.pb(dp[i]),vec2.pb(dp[i]*i);\n        auto res1=convolution(vec,vec1),res2=convolution(vec,vec2);\n        int base=a[mid]-mid+l+1;\n        rep(i,mid,r) if(a[i]-base>=0&&a[i]-base<sz(res1)) aux[i]-=res1[a[i]-base],dp[i]+=res2[a[i]-base];\n        self(self,mid,r);\n    };\n    solve(solve,0,n+1);\n    print(dp[n].val());\n}\n\nsigned main(){\n    ios_base::sync_with_stdio(0),cin.tie(0);\n    cout << fixed << setprecision(20);\n    int t=1;\n    cin >> t;\n    while(t--) ahcorz();\n}\n",
    "tags": [
      "divide and conquer",
      "fft",
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "1936",
    "index": "F",
    "title": "Grand Finale: Circles",
    "statement": "You are given $n$ circles on the plane. The $i$-th of these circles is given by a tuple of integers $(x_i, y_i, r_i)$, where $(x_i, y_i)$ are the coordinates of its center, and $r_i$ is the radius of the circle.\n\nPlease find a circle $C$ which meets the following conditions:\n\n- $C$ is contained inside all $n$ circles given in the input.\n- Among all circles $C$ that meet the first condition, the radius of the circle is maximum.\n\nLet the largest suitable circle have the radius of $a$.\n\nYour output $C$, described as $(x,y,r)$, will be accepted if it meets the following conditions:\n\n- For each $i$, $\\sqrt{(x_i-x)^2+(y_i-y)^2}+ r \\le r_i+\\max(a,1)\\cdot 10^{-7}$.\n- The absolute or relative error of $r$ does not exceed $10^{-7}$. Formally, your answer is accepted if and only if $\\frac{\\left|r - a\\right|}{\\max(1, a)} \\le 10^{-7}$.",
    "tutorial": "For a given center coordinate $(x,y)$, we can model the objective function $r=f(x,y)$ to maximize as follows. $f(x,y)=\\min_{1 \\le i \\le n} {\\left({r_i-\\sqrt{(x_i-x)^2+(y_i-y)^2}}\\right)}$ Formally, this can be modeled as follows: $\\begin{split} \\max & \\ r \\\\ \\text{s.t.} & \\ \\sqrt{(x_i-x)^2+(y_i-y)^2} \\le r_i-r \\ \\ \\forall \\ 1 \\le i \\le n \\end{split}$ This is a second order cone program. Generally, this is not as simple to solve as linear or quadratic programs. There are multiple solvers out there, but all of them are either commercial or simply unfit for use on Codeforces. And even if we use general approaches to second order cone programming, their time complexity is at least $\\mathcal{O}(n^{3.5})$, so they cannot work. Almost all general approaches to convex programming do not help very much for this task also, because of the following reasons. Gradient Descent cannot work in this task. The objective function is not smooth. Gradient Descent cannot work in this task. The objective function is not smooth. Coordinate Descent also cannot work in this task for the same reason, and it is not hard to find a countercase. Coordinate Descent also cannot work in this task for the same reason, and it is not hard to find a countercase. Subgradient methods can solve this task, but they take $\\mathcal{O}(1/\\epsilon^2)$ iterations to converge. This is a very big dependency on the precision, so they take too much time. Subgradient methods can solve this task, but they take $\\mathcal{O}(1/\\epsilon^2)$ iterations to converge. This is a very big dependency on the precision, so they take too much time. We do not expect anyone to write Adaptive Coordinate Descent during contest time, but we still tested the PRAXIS algorithm and checked that it does not pass. We do not expect anyone to write Adaptive Coordinate Descent during contest time, but we still tested the PRAXIS algorithm and checked that it does not pass. Using nested ternary searches does not help very much. The time complexity will be $\\mathcal{O}(n \\log^2 (1/\\epsilon))$, but the constants are large due to multiple function calls and floating point operations. Using nested ternary searches does not help very much. The time complexity will be $\\mathcal{O}(n \\log^2 (1/\\epsilon))$, but the constants are large due to multiple function calls and floating point operations. Heuristics such as the Nelder-Mead method are not proven to converge. In many cases we found it not converging successfully. Heuristics such as the Nelder-Mead method are not proven to converge. In many cases we found it not converging successfully. In the editorial, we will explain a solution of expected $\\mathcal{O}(n)$ time complexity, with constants depending on the number of dimensions (which is $2$ in our case). First, we observe that any answer can be described as a \"basis\" of at most $3$ selected circles. For $k=0,1,2,3$, the basis is as follows. Case 1: $k=0$ This is the case of no circles, which can be regarded as an \"identity element\" of bases. Some very huge circle that will enclose any given circle, for example the circle with $10^{18}$ as radius and $(0,0)$ as center, can represent this case. Case 2: $k=1$ This is the case of a single circle. The circle that represents this case is the one selected circle. Case 3: $k=2$ This is the case of two circles, for which the basis is the largest circle in the intersection of two circles. We can find this by choosing the center as the midpoint of the two points $A$ and $B$, where $A$ and $B$ are the points where the line segment between circle centers and the circle itself intersect. Case 4: $k=3$ This is the case of three circles, and the most tricky of all four cases. It can be found as one solution to the following system of quadratic equations: $(x_A-x)^2+(y_A-y)^2 = (r_A-r)^2 \\\\ (x_B-x)^2+(y_B-y)^2 = (r_B-r)^2 \\\\ (x_C-x)^2+(y_C-y)^2 = (r_C-r)^2$ This can be solved algebraically. If you are used to solving geometry problems in Olympiads, you may know the ''Problem of Apollonius''. This is one special case of the problem, which is not very often mentioned because often the three circles do not intersect with each other (thus most of the time one solution for $r$ must be negative). Or if one does not know the problem, they can find that the locus of the circle center that meets with two circle edges (as in Case 3) is a conic section, precisely one side of a pair of hyperbola. By finding the intersections of two hyperbola, one can find the center of this circle. Thus, this circle can be found in $\\mathcal{O}(1)$ time, with constants based on number of dimensions. By the system of quadratic equations stated above, we see that there are at most $2$ solutions. It is sufficient to take the one that happens to be inside the intersection. (If there are two such solutions, take the larger one. For the current version of the data this check is not necessary, but it does not hurt to try.) Thus, for some $n>3$, the bases can be represented with some $k \\le 3$ circles. Do note that, already, we have an $\\mathcal{O}(n^3)$ solution based on this. We enumerate all possible bases, and find the smallest one out of them (since that one will be the one that satisfies the conditions). Now, for some basis circle $(x,y,r)$, we can check whether some given circle $(x_i,y_i,r_i)$ is \"violated\" by this basis (i.e. this basis is not inside this circle) in $\\mathcal{O}(1)$ by comparing the distance. We take an incremental approach. We add circles to the basis one by one, up to $3$ circles. We choose to change the basis if only the next added circle is violated by the current basis. Of course, still this takes $\\mathcal{O}(n^3)$ time, and sorting the circles based on any argument will not help anyways. However, adding the circles in random order will make it only take expected $\\mathcal{O}(n)$ time. This can be analyzed by the probability that a new basis will be added. The precise analysis for the time complexity is left as a practice for the reader. If you have seen the minimum enclosing circle problem, the Welzl's algorithm to solve that precise problem will seem very similar to this. In fact, the suggested algorithm itself is not very different from Welzl's algorithm. If you want, though, you may take an iterative approach instead of modifying Welzl's algorithm. Using three nested loops will do. There is only two issues left. The first is the issue of numerical instability. Sometimes, due to numerical instability, the algorithm will return a NaN value. It is not that hard to solve, we can simply shuffle again and rerun the algorithm. The given time limit will be sufficient for doing this unless the constant is too big. The second is more tricky, and it is about hacks. If you use a fixed seed for randomization (or time-based seeds to some extent), someone may hack you by adding an adversarial test case which makes the time complexity explode back to $\\mathcal{O}(n^3)$. This is very bad. How do we solve this? To intervent this, we will make the algorithm halt when the number of iterations exceed a certain limit. Formally, let us choose a constant $c$, and the algorithm will halt and rerun when the number of iterations exceeds $c \\cdot n$. Then, if the probability of the algorithm successfully running in this number of iterations is $p$, the expected number of reruns needed is $\\mathcal{O}(1/p)$, and hacking is much harder. The algorithm will successfully find the solution in $\\mathcal{O}((c/p) \\cdot n)$ time. Of course, the probability $p$ depends on $c$, and you must tune the value as needed. Empirically $c=30$ runs very well, almost always taking no longer than $0.4$ seconds under proper optimizations, and $1.5$ seconds without.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n \nusing lf=long double;\nusing pt=pair<lf,lf>;\nlf& real(pt& p){return p.first;}\nlf& imag(pt& p){return p.second;}\npt midp(pt a,pt b){return pt{(real(a)+real(b))/2,(imag(a)+imag(b))/2};}\npt addi(pt a,pt b){return pt{(real(a)+real(b)),(imag(a)+imag(b))};}\npt subt(pt a,pt b){return pt{(real(a)-real(b)),(imag(a)-imag(b))};}\npt mult(pt a,lf b){return pt{real(a)*b,imag(a)*b};}\nlf abs(pt a){return sqrtl(powl(real(a),2)+powl(imag(a),2));}\nlf dist(pt a,pt b){return sqrtl(powl(real(a)-real(b),2)+powl(imag(a)-imag(b),2));}\n \nstruct circ{pt p;lf r;};\nconst lf inf=1e18;\n \ncirc basis0(){return {pt{0,0},inf};}\n \ncirc basis1(circ a){return a;}\n \ncirc basis2(circ a,circ b)\n{\n    pt aa=a.p,bb=b.p;\n    pt ab=subt(bb,aa),ba=subt(aa,bb);\n    lf aab=abs(ab),aba=abs(ba);\n    real(ab)/=aab;\n    imag(ab)/=aab;\n    real(ba)/=aba;\n    imag(ba)/=aba;\n    pt ar=addi(aa,mult(ab,a.r)),br=addi(bb,mult(ba,b.r));\n    \n    return {midp(ar,br),dist(ar,br)/2.0L};\n}\n \ncirc basis3(circ a,circ b,circ c)\n{\n    lf x1=real(a.p),y1=imag(a.p),r1=a.r;\n    lf x2=real(b.p),y2=imag(b.p),r2=b.r;\n    lf x3=real(c.p),y3=imag(c.p),r3=c.r;\n    lf a2=x1-x2,a3=x1-x3,b2=y1-y2,b3=y1-y3,c2=r2-r1,c3=r3-r1;\n    lf d1=x1*x1+y1*y1-r1*r1,d2=d1-x2*x2-y2*y2+r2*r2,d3=d1-x3*x3-y3*y3+r3*r3;\n    lf ab=a3*b2-a2*b3;\n    lf xa=(b2*d3-b3*d2)/(ab*2)-x1;\n    lf xb=(b3*c2-b2*c3)/ab;\n    lf ya=(a3*d2-a2*d3)/(ab*2)-y1;\n    lf yb=(a2*c3-a3*c2)/ab;\n    lf A=xb*xb+yb*yb-1;\n    lf B=2*(r1+xa*xb+ya*yb);\n    lf C=xa*xa+ya*ya-r1*r1;\n    lf r=-(A?(B-sqrtl(B*B-4*A*C))/(2*A):C/B);\n    return {pt{x1+xa+xb*r,y1+ya+yb*r},r};\n}\n \nbool viol(circ p,circ a)\n{\n    return a.r<p.r+dist(a.p,p.p);\n}\n \ncirc solve(vector<circ>&v)\n{\n    lf _nan=nan(\"aaa\");\n    mt19937_64 mt(1999999);\n    //shuffle(begin(v),end(v),mt);\n    vector<circ>basis;\n    auto trivial=[&]()\n    {\n        if(size(basis)==0)return basis0();\n        if(size(basis)==1)return basis[0];\n        if(size(basis)==2)return basis2(basis[0],basis[1]);\n        return basis3(basis[0],basis[1],basis[2]);\n    };\n \n    int counter=0;\n    \n    auto rec=[&](auto rec,int n)->circ\n    {\n        if(n==0||size(basis)==3)return trivial();\n        counter++;\n        if(counter>30*size(v))return {pt{0,0},_nan};\n        auto c=rec(rec,n-1);\n        auto p=v[n-1];\n        if(!viol(c,p)||isnan(c.r))return c;\n        basis.push_back(p);\n        c=rec(rec,n-1);\n        basis.pop_back();\n        return c;\n    };\n    auto c=rec(rec,size(v));\n    while(isnan(c.r))\n    {\n        counter=0;\n        shuffle(begin(v),end(v),mt);\n        c=rec(rec,size(v));\n    }\n    return c;\n}\n \nint main()\n{\n    cin.tie(0)->sync_with_stdio(0);\n    int n;cin>>n;\n    vector<circ>v(n);\n    for(auto&[p,r]:v)\n    {\n        ll x,y,rr;cin>>x>>y>>rr;\n        p={x,y};r=rr;\n    }\n    auto ans=solve(v);\n    cout<<setprecision(16)<<fixed<<real(ans.p)<<\" \"<<imag(ans.p)<<\" \"<<ans.r<<\"\\n\";\n}\n",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1937",
    "index": "A",
    "title": "Shuffle Party",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$. Initially, $a_i=i$ for each $1 \\le i \\le n$.\n\nThe operation $swap(k)$ for an integer $k \\ge 2$ is defined as follows:\n\n- Let $d$ be the largest divisor$^\\dagger$ of $k$ which is not equal to $k$ itself. Then swap the elements $a_d$ and $a_k$.\n\nSuppose you perform $swap(i)$ for each $i=2,3,\\ldots, n$ in this exact order. Find the position of $1$ in the resulting array. In other words, find such $j$ that $a_j = 1$ after performing these operations.\n\n$^\\dagger$ An integer $x$ is a divisor of $y$ if there exists an integer $z$ such that $y = x \\cdot z$.",
    "tutorial": "If you think in terms of $k$, it might be hard to find the solution. Maybe it will be helpful if you fix $d$ and find the $k$ which will be swapped with $d$. Try bruteforcing for, say, $n \\le 20$. Do you see a pattern? On $n=1$, the answer is trivially $1$. On $n=2$, index $1$ and $2$ are swapped. The answer is therefore $2$. For $n>2$, let us assume the element $1$ is on index $a$ and it will be swapped with index $k$. Then, $a$ must be $k/2$. We will prove this by contradiction. Let us assume that there is no divisor greater than $a$, and $a$ is lesser than $k/2$. But then, as $a$ is a multiple of $2$ in the base condition, $k$ must be a multiple of $2$, and $k/2$ is a divisor of $k$. This contradicts the assumption. By induction we can see that $a$ is always a multiple of $2$, and this proof will always hold. The element $1$ will move only when $k/2=a$. Therefore, we can find the largest value of $v$ such that $2^v \\le n$. The answer turns out to be $2^v$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n \nint main()\n{\n    cin.tie(0)->sync_with_stdio(0);\n    ll q;cin>>q;\n    while(q--)\n    {\n        ll n,p=1;cin>>n;\n        while(p*2<=n)p<<=1;\n        cout<<p<<\"\\n\";\n    }\n}\n",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1937",
    "index": "B",
    "title": "Binary Path",
    "statement": "You are given a $2 \\times n$ grid filled with zeros and ones. Let the number at the intersection of the $i$-th row and the $j$-th column be $a_{ij}$.\n\nThere is a grasshopper at the top-left cell $(1, 1)$ that can only jump one cell right or downwards. It wants to reach the bottom-right cell $(2, n)$. Consider the binary string of length $n+1$ consisting of numbers written in cells of the path without changing their order.\n\nYour goal is to:\n\n- Find the lexicographically smallest$^\\dagger$ string you can attain by choosing any available path;\n- Find the number of paths that yield this lexicographically smallest string.\n\n$^\\dagger$ If two strings $s$ and $t$ have the same length, then $s$ is lexicographically smaller than $t$ if and only if in the first position where $s$ and $t$ differ, the string $s$ has a smaller element than the corresponding element in $t$.",
    "tutorial": "Let's call path $(1,1) \\rightarrow \\ldots \\rightarrow (1,i)\\rightarrow(2,i) \\rightarrow \\ldots \\rightarrow (2,n)$ the $i$-th path. What's the difference between the $i$-th path and the $(i+1)$-th path? What if $a_{2i}=1$ and $a_{1(i+1)}=0$ ? What if $a_{2i}=0$ and $a_{1(i+1)}=1$ ? Let the string achieved by moving down on the $i$-th column be $S_i$. Then, for any $1 \\le k < n$, one can observe that $S_k$ and $S_{k+1}$ can only differ by at most one index, which is index $k+1$. Thus, comparing $S_k$ and $S_{k+1}$ lexicographically can be done in $O(1)$, by comparing this one index. Let the string achieved by moving down on the $i$-th column be $S_i$. Then, for any $1 \\le k < n$, one can observe that $S_k$ and $S_{k+1}$ can only differ by at most one index, which is index $k+1$. Thus, comparing $S_k$ and $S_{k+1}$ lexicographically can be done in $O(1)$, by comparing this one index. After finding the lexicographically smallest string, counting the occurrence of this string can be done straightforwardly in $O(n)$. After finding the lexicographically smallest string, counting the occurrence of this string can be done straightforwardly in $O(n)$. The implementation can differ for each participant, but the following method provides a clean implementation. Let the initial coordinate be $(1,1)$, and maintain a counter which is initially reset to $1$. Then repeat the following until we reach $(2,n)$: The implementation can differ for each participant, but the following method provides a clean implementation. Let the initial coordinate be $(1,1)$, and maintain a counter which is initially reset to $1$. Then repeat the following until we reach $(2,n)$: If we are on row $2$, move to the right. If we are on column $n$, move downwards. From here, let the character on the right be $a$, and one below be $b$. If $a>b$, move downwards. If $a<b$, move to the right and reset the counter to $1$. If $a=b$, move to the right and increment the counter. In the end, the string on the path we passed through will be lexicographically smallest, and the integer on the counter will be the number of occurrences.",
    "code": "#include <map>\n#include <set>\n#include <cmath>\n#include <ctime>\n#include <queue>\n#include <stack>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n#include <iostream>\nusing namespace std;\ntypedef double db; \ntypedef long long ll;\ntypedef unsigned long long ull;\nconst int N=1000010;\nconst int LOGN=28;\nconst ll  TMD=0;\nconst ll  INF=2147483647;\nint  T,n;\nchar a[3][N];\n\nint main()\n{\n\tscanf(\"%d\",&T);\n\twhile(T--)\n\t{\n    \t        scanf(\"%d\",&n);\n\t\tfor(int i=1;i<=2;i++)\n\t\t{\n\t\t    scanf(\"\\n\");\n\t\t\tfor(int j=1;j<=n;j++)\n\t\t\t\tscanf(\"%c\",&a[i][j]);\n\t\t}\n\t\tint max_down=n,min_down=1;\n\t\tfor(int i=n;i>=2;i--)\n\t\t\tif(a[1][i]=='1'&&a[2][i-1]=='0') max_down=i-1;\n\t\tfor(int i=1;i<max_down;i++)\n\t\t\tif(a[2][i]=='1'&&a[1][i+1]=='0') min_down=i+1;\n\t\tfor(int i=1;i<=max_down;i++) printf(\"%c\",a[1][i]);\n\t\tfor(int i=max_down;i<=n;i++) printf(\"%c\",a[2][i]);\n\t\tprintf(\"\\n\");\n\t\tprintf(\"%d\\n\",max_down-min_down+1);\n\t}\n\t\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1941",
    "index": "A",
    "title": "Rudolf and the Ticket",
    "statement": "Rudolf is going to visit Bernard, and he decided to take the metro to get to him. The ticket can be purchased at a machine that accepts exactly two coins, the sum of which does not exceed $k$.\n\nRudolf has two pockets with coins. In the left pocket, there are $n$ coins with denominations $b_1, b_2, \\dots, b_n$. In the right pocket, there are $m$ coins with denominations $c_1, c_2, \\dots, c_m$. He wants to choose exactly one coin from the left pocket and exactly one coin from the right pocket (two coins in total).\n\nHelp Rudolf determine how many ways there are to select indices $f$ and $s$ such that $b_f + c_s \\le k$.",
    "tutorial": "For each test case, we calculate all elements $b_i$ from the first array. Then we iterate through the elements $c_j$ in the second array and in a loop, we calculate each sum $b_i + c_j$. If this sum is less than or equal to $k$, we add $1$ to the answer.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin >> t;\n\twhile (t--) {\n\t\tint n, m, k;\n\t\tcin >> n >> m >> k;\n\t\tint ans = 0;\n\t\tvector<int> v1(n);\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tcin >> v1[i];\n\t\t}\n\t\tint o;\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tcin >> o;\n\t\t\tfor (int i = 0; i < n; i++) {\n\t\t\t\tif ((o + v1[i]) <= k) ans++;\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1941",
    "index": "B",
    "title": "Rudolf and 121",
    "statement": "Rudolf has an array $a$ of $n$ integers, the elements are numbered from $1$ to $n$.\n\nIn one operation, he can choose an index $i$ ($2 \\le i \\le n - 1$) and assign:\n\n- $a_{i - 1} = a_{i - 1} - 1$\n- $a_i = a_i - 2$\n- $a_{i + 1} = a_{i + 1} - 1$\n\nRudolf can apply this operation any number of times. Any index $i$ can be used zero or more times.\n\nCan he make all the elements of the array equal to zero using this operation?",
    "tutorial": "Let's consider the minimum $i$ such that $a_i > 0$. Making this element zero is only possible by choosing the $(i + 1)$-th element for the operation (applying the operation to a more leftward element is either impossible or will make some elements less than zero). We will apply operations in this way until we reach the end of the array. If there are non-zero elements left after applying the operations, the answer is \"NO\".",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    for i in range(n - 2):\n        if a[i] < 0:\n            print('NO')\n            return\n        op = a[i]\n        a[i] -= op\n        a[i + 1] -= 2 * op\n        a[i + 2] -= op\n    if a[-1] != 0 or a[-2] != 0:\n        print('NO')\n    else:\n        print('YES')\n    \n\nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1941",
    "index": "C",
    "title": "Rudolf and the Ugly String",
    "statement": "Rudolf has a string $s$ of length $n$. Rudolf considers the string $s$ to be ugly if it contains the substring$^\\dagger$ \"pie\" or the substring \"map\", otherwise the string $s$ will be considered beautiful.\n\nFor example, \"ppiee\", \"mmap\", \"dfpiefghmap\" are ugly strings, while \"mathp\", \"ppiiee\" are beautiful strings.\n\nRudolf wants to shorten the string $s$ by removing some characters to make it beautiful.\n\nThe main character doesn't like to strain, so he asks you to make the string beautiful by removing the minimum number of characters. He can remove characters from \\textbf{any} positions in the string (not just from the beginning or end of the string).\n\n$^\\dagger$ String $a$ is a substring of $b$ if there exists a \\textbf{consecutive} segment of characters in string $b$ equal to $a$.",
    "tutorial": "To solve this problem, you need to find all occurrences of the substrings \"pie\", \"map\", \"mapie\" in the string $s$ and remove the middle character in each of them. This way, you will remove the minimum number of characters to ensure that the string does not contain the substrings \"pie\" and \"map\".",
    "code": "#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nint main() {\n    long long t;\n    cin>>t;\n    for(long long c=0;c<t;c++){\n\tlong long n;\n\tcin >> n;\n\tstring s;\n\tcin >> s;\n\tvector<long long> va;                 \n\tfor (string sul : {\"mapie\", \"pie\", \"map\"}) {\n\t\tfor (size_t pos = 0; (pos = s.find(sul, pos)) != string::npos;) {\n\t\t\ts[pos + sul.length() / 2] = '?';\n\t\t\tva.push_back(pos + sul.length() / 2);\n\t\t}\n\t}\n\tcout << va.size() << endl;\n    }\n\treturn 0;\n}\n",
    "tags": [
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1941",
    "index": "D",
    "title": "Rudolf and the Ball Game",
    "statement": "Rudolf and Bernard decided to play a game with their friends. $n$ people stand in a circle and start throwing a ball to each other. They are numbered from $1$ to $n$ in the clockwise order.\n\nLet's call a transition a movement of the ball from one player to his neighbor. The transition can be made clockwise or counterclockwise.\n\nLet's call the clockwise (counterclockwise) distance from player $y_1$ to player $y_2$ the number of transitions clockwise (counterclockwise) that need to be made to move from player $y_1$ to player $y_2$. For example, if $n=7$ then the clockwise distance from $2$ to $5$ is $3$, and the counterclockwise distance from $2$ to $5$ is $4$.\n\nInitially, the ball is with the player number $x$ (players are numbered clockwise). On the $i$-th move the person with the ball throws it at a distance of $r_i$ ($1 \\le r_i \\le n - 1$) clockwise or counterclockwise. For example, if there are $7$ players, and the $2$nd player, after receiving the ball, throws it a distance of $5$, then the ball will be caught by either the $7$th player (throwing clockwise) or the $4$th player (throwing counterclockwise). An illustration of this example is shown below.\n\nThe game was interrupted after $m$ throws due to unexpected rain. When the rain stopped, the guys gathered again to continue. However, no one could remember who had the ball. As it turned out, Bernard remembered the distances for each of the throws and the direction for \\textbf{some} of the throws (clockwise or counterclockwise).\n\nRudolf asks you to help him and based on the information from Bernard, calculate the numbers of the players who could have the ball after $m$ throws.",
    "tutorial": "Let's introduce a set of unique elements $q$, initially containing a single element $x$ - the index of the first player who started the game. For each $i$ from $1$ to $m$, we will update $q$ in such a way as to maintain the set of players who could have the ball after the $i$-th throw. For each element $q_j$ of the set $q$, we will remove $q_j$ from $q$, and also: if $c_i =$\"$0$\" or $c_i =$\"$?$\", add to $q$ the element $\\left( (q_j + r_i - 1)\\ mod\\ n + 1 \\right)$ - the index of the player who will receive the ball in case of a clockwise throw; if $c_i =$\"$1$\" or $c_i =$\"$?$\", add to $q$ the element $\\left( (q_j - r_i - 1 + n)\\ mod\\ n + 1 \\right)$ - the index of the player who will receive the ball in case of a counterclockwise throw. The term $n$ before the $mod$ operation is necessary to obtain a positive argument of this operation. Otherwise, in some programming languages, the $mod$ function will return a negative result, which does not correspond to the semantics of the problem. After the $m$-th iteration of the described cyclic process, the set $q$ will contain the desired indices of all players who could have the ball at the end of the game. At each iteration of the loop, the power of $q$ does not exceed $n$, and a total of exactly $m$ iterations will be performed. Thus, the asymptotic complexity of the algorithm is of the order $O(n * m)$.",
    "code": "#include <iostream>\n#include <set>\n\nusing namespace std;\n\nint main()\n{\n    int t; cin >> t;\n    while (t--) {\n        int n, m, a; cin >> n >> m >> a;\n        set <int> q[2];\n        int ix = 0;\n        q[ix].insert(a);\n        while (m--) {\n            int x; char ch; cin >> x >> ch;\n            while (!q[ix].empty()) {\n                int u = *(q[ix].begin());\n                q[ix].erase(u);\n                if (ch == '?' || ch == '0') {\n                    q[ix ^ 1].insert((u + x - 1) % n + 1);\n                }\n                if (ch == '?' || ch == '1') {\n                    q[ix ^ 1].insert((u - x - 1 + n) % n + 1);\n                }\n            }\n            ix ^= 1;\n        }\n        cout << q[ix].size() << '\\n';\n        for (auto& x : q[ix]) {\n            cout << x << ' ';\n        }\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1941",
    "index": "E",
    "title": "Rudolf and k Bridges",
    "statement": "Bernard loves visiting Rudolf, but he is always running late. The problem is that Bernard has to cross the river on a ferry. Rudolf decided to help his friend solve this problem.\n\nThe river is a grid of $n$ rows and $m$ columns. The intersection of the $i$-th row and the $j$-th column contains the number $a_{i,j}$ — the depth in the corresponding cell. All cells in the \\textbf{first} and \\textbf{last} columns correspond to the river banks, so the depth for them is $0$.\n\n\\begin{center}\n{\\small The river may look like this.}\n\\end{center}\n\nRudolf can choose the row $(i,1), (i,2), \\ldots, (i,m)$ and build a bridge over it. In each cell of the row, he can install a support for the bridge. The cost of installing a support in the cell $(i,j)$ is $a_{i,j}+1$. Supports must be installed so that the following conditions are met:\n\n- A support must be installed in cell $(i,1)$;\n- A support must be installed in cell $(i,m)$;\n- The distance between any pair of adjacent supports must be \\textbf{no more than} $d$. The distance between supports $(i, j_1)$ and $(i, j_2)$ is $|j_1 - j_2| - 1$.\n\nBuilding just one bridge is boring. Therefore, Rudolf decided to build $k$ bridges on \\textbf{consecutive} rows of the river, that is, to choose some $i$ ($1 \\le i \\le n - k + 1$) and independently build a bridge on each of the rows $i, i + 1, \\ldots, i + k - 1$. Help Rudolf \\textbf{minimize} the total cost of installing supports.",
    "tutorial": "First, for each string separately, we will calculate the minimum total cost of supports and write it to an array. This can be done, for example, using dynamic programming as follows. We will go through the string and maintain the last $d+1$ minimum total costs in a multiset. Then the answer for the current position will be the sum of the cost of the support at this position and the minimum element from the multiset. When moving to the next element of the string, it is important to remember to update the multiset. After that, from the array of minimum total costs, we choose a segment of length $k$ with the minimum sum, which will be the answer. The algorithm's asymptotic complexity is of the order $O(n \\cdot m \\cdot \\log d)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\n\nint main() {\n\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        int N, M, K, D;\n        cin >> N >> M >> K >> D;\n        vector<long long> a(N);\n        for (int i = 0; i < N; i++) {\n            vector<long long> dp(M, 1e9);\n            vector<int> v(M);\n            multiset<long long> mst = {1};\n            dp[0] = 1;\n            cin >> v[0];\n            for (int j = 1; j < M - 1; j++) {\n                cin >> v[j];\n                dp[j] = *mst.begin() + v[j] + 1;\n                if (j - D - 1 >= 0)\n                    mst.erase(mst.find((dp[j - D - 1])));\n                mst.insert(dp[j]);\n            }\n            cin >> v.back();\n            dp.back() = 1 + *mst.begin();\n            a[i] = dp.back();\n        }\n\n        long long cur = 0;\n        for (int i = 0; i < K; i++)\n            cur += a[i];\n\n        long long mn = cur;\n\n        for (int i = K; i < N; i++) {\n            cur += a[i] - a[i - K];\n            mn = min(cur, mn);\n        }\n        cout << mn << endl;\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1941",
    "index": "F",
    "title": "Rudolf and Imbalance",
    "statement": "Rudolf has prepared a set of $n$ problems with complexities $a_1 < a_2 < a_3 < \\dots < a_n$. He is not entirely satisfied with the balance, so he wants to add \\textbf{at most one} problem to fix it.\n\nFor this, Rudolf came up with $m$ models of problems and $k$ functions. The complexity of the $i$-th model is $d_i$, and the complexity of the $j$-th function is $f_j$. To create a problem, he selects values $i$ and $j$ ($1 \\le i \\le m$, $1 \\le j \\le k$) and by combining the $i$-th model with the $j$-th function, he obtains a new problem with complexity $d_i + f_j$ (a new element is inserted into the array $a$).\n\nTo determine the imbalance of the set, Rudolf sorts the complexities of the problems in ascending order and finds the largest value of $a_i - a_{i - 1}$ ($i > 1$).\n\nWhat is the minimum value of imbalance that Rudolf can achieve by adding at most one problem, created according to the described rules?",
    "tutorial": "Let's consider the differences $a_i - a_{i-1}$. Since we can only insert one problem, we can reduce the difference in difficulty in only one place. If we insert a problem not between the tasks whose difference in difficulty is maximum (denote them as $a_p$ and $a_{p+1}$), then the imbalance will not change. The best way to insert a problem in this way is to choose the middle between these tasks, so the larger of the differences $d_i + f_j - a_p$ and $a_{p + 1} - d_i - f_j$ will be minimal. We also cannot forget about the other tasks. Let's find the second maximum among the values $a_i - a_{i - 1}$. Since we insert a problem in another place, this difference will not decrease, and therefore the answer cannot be less than it. To understand what answer we can achieve, let's sort the functions and iterate through all the models. For the model $d_i$, using binary search, we will find the maximum index $l$ such that $d_i + f_l \\le \\lfloor \\frac{a_p + a_{p + 1}}{2} \\rfloor$. For inserting with the selected model, the best fit will be either a problem of difficulty $d_i + f_l$ or a problem of difficulty $d_i + f_{l + 1}$ (if $l < k$) since it is the closest problems to the middle. We will check both options and update the answer.",
    "code": "def solve():\n    n, m, k = map(int, input().split())\n    a = [int(x) for x in input().split()]\n    d = [int(x) for x in input().split()]\n    f = [int(x) for x in input().split()]\n    d.sort()\n    f.sort()\n\n    m1, m2 = 0, 0\n    ind = -1\n    for i in range(1, n):\n        e = a[i] - a[i - 1]\n        m2 = max(m2, e)\n        if m2 > m1:\n            m1, m2 = m2, m1\n            ind = i - 1\n\n    ans = m1\n\n    target = (a[ind] + a[ind + 1]) // 2\n    for model in d:\n        l, r = 0, k - 1\n        while r - l > 1:\n            mid = (r + l) // 2\n            if model + f[mid] <= target:\n                l = mid\n            else:\n                r = mid\n        ans = min(ans, max(m2, abs(model + f[l] - a[ind]), abs(model + f[l] - a[ind + 1])))\n        ans = min(ans, max(m2, abs(model + f[r] - a[ind]), abs(model + f[r] - a[ind + 1])))\n    print(ans)\n\n\nfor _ in range(int(input())):\n    solve()\n",
    "tags": [
      "binary search",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1941",
    "index": "G",
    "title": "Rudolf and Subway",
    "statement": "Building bridges did not help Bernard, and he continued to be late everywhere. Then Rudolf decided to teach him how to use the subway.\n\nRudolf depicted the subway map as an undirected connected graph, without self-loops, where the vertices represent stations. There is at most one edge between any pair of vertices.\n\nTwo vertices are connected by an edge if it is possible to travel directly between the corresponding stations, bypassing other stations. The subway in the city where Rudolf and Bernard live has a color notation. This means that any edge between stations has a specific color. Edges of a specific color together form a subway line. A subway line \\textbf{cannot} contain unconnected edges and forms a connected subgraph of the given subway graph.\n\nAn example of the subway map is shown in the figure.\n\nRudolf claims that the route will be optimal if it passes through the minimum number of subway lines.\n\nHelp Bernard determine this minimum number for the given departure and destination stations.",
    "tutorial": "Let's construct a bipartite graph, where one part is the vertices of the original graph, i.e., subway stations, and the other part is the subway lines. We add an edge between a station vertex and a line vertex if in the original subway graph, the station is incident to an edge of the corresponding subway line. In the new graph, we find the shortest path between the vertices corresponding to the departure and destination stations (for example, using breadth-first search). The answer to the problem will be the shortest path, divided in half.",
    "code": "#include<bits/stdc++.h>\n\nusing LL = long long;\nusing ld = long double;\n\nusing namespace std;\n\n\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    cout << fixed << setprecision(10);\n\n\n    int _ = 0, __ = 1;\n    cin >> __;\n\n    for (int _ = 0; _ < __; ++_) {\n        int n, m;\n        cin >> n >> m;\n        vector<vector<pair<int, int>>> g(n + 1);\n        map<int, int> clrs;\n        int idx = n + 1;\n        for (int i = 0; i < m; ++i) {\n            int u, v, c;\n            cin >> u >> v >> c;\n            g[u].push_back({v, c});\n            g[v].push_back({u, c});\n            if (!clrs.count(c)) {\n                clrs[c] = idx;\n                idx++;\n            }\n        }\n        int s, t;\n        cin >> s >> t;\n        \n        if (s == t) \n        {\n            cout << 0 << endl;\n            continue;\n        }\n\n        vector<set<int>> bg(n + clrs.size() + 3);\n\n        for (int i = 1; i <= n; ++i) {\n            for(auto &[to, c] : g[i])\n            {\n                int clr_v = clrs[c];\n                bg[i].insert(clr_v);\n                bg[clr_v].insert(i);\n\n                bg[to].insert(clr_v);\n                bg[clr_v].insert(to);\n            }\n        }\n\n        vector<int> used(bg.size());\n        vector<int> d(bg.size(), -1);\n        auto bfs = [&](int v)\n        {\n            queue<int> q;\n            q.push(v);\n            used[v] = 1;\n            d[v] = 0;\n            while (!q.empty())\n            {\n                auto from = q.front();\n                q.pop();\n                for (auto& to : bg[from])\n                {\n                    if (!used[to])\n                    {\n                        q.push(to);\n                        used[to] = 1;\n                        d[to] = d[from] + 1;\n                    }\n                }\n            }\n        };\n        bfs(s);\n        if (d[t] > 0) cout << d[t] / 2 << endl;\n        else cout << -1 << endl;\n\n\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1942",
    "index": "A",
    "title": "Farmer John's Challenge",
    "statement": "\\begin{quote}\nTrade Winds - Patrick Deng\n\\hfill ⠀\n\\end{quote}\n\nLet's call an array $a$ sorted if $a_1 \\leq a_2 \\leq \\ldots \\leq a_{n - 1} \\leq a_{n}$.\n\nYou are given two of Farmer John's favorite integers, $n$ and $k$. He challenges you to find any array $a_1, a_2, \\ldots, a_{n}$ satisfying the following requirements:\n\n- $1 \\leq a_i \\leq 10^9$ for each $1 \\leq i \\leq n$;\n- Out of the $n$ total cyclic shifts of $a$, exactly $k$ of them are sorted.$^\\dagger$\n\nIf there is no such array $a$, output $-1$.\n\n$^\\dagger$The $x$-th ($1 \\leq x \\leq n$) \\textbf{cyclic shift} of the array $a$ is $a_x, a_{x+1} \\ldots a_n, a_1, a_2 \\ldots a_{x - 1}$. If $c_{x, i}$ denotes the $i$'th element of the $x$'th cyclic shift of $a$, exactly $k$ such $x$ should satisfy $c_{x,1} \\leq c_{x,2} \\leq \\ldots \\leq c_{x, n - 1} \\leq c_{x, n}$.\n\nFor example, the cyclic shifts for $a = [1, 2, 3, 3]$ are the following:\n\n- $x = 1$: $[1, 2, 3, 3]$ (sorted);\n- $x = 2$: $[2, 3, 3, 1]$ (not sorted);\n- $x = 3$: $[3, 3, 1, 2]$ (not sorted);\n- $x = 4$: $[3, 1, 2, 3]$ (not sorted).",
    "tutorial": "Solve for $k = 1$. $a = 1, 2, 3 \\dots n$ works. Why? Solve for $k = n$. $a = 1, 1, 1 \\dots 1$ works. Why? What other $k$ work for a given $n$? Only $k = 1$ and $k = n$ have possible answers. Read the hints. For $k=1$, the construction $1,2,3\\dots n$ will always work because in any other cyclic shift, $n$ will be before $1$. Now, consider what happens if we want to find an array with two or more cyclic shifts that are sorted. If we consider two of these cyclic shifts, notice they are actually shifts of each other as well. So, there should be a sorted array, and a shift of it which is also sorted. What this means is that some of the first elements in the array move to the back and stays sorted, which can only happen if all values in the array are equal. If the array has all equal values, this gives us our construction for $k=n$. As we have seen, for $k>1$, only $k=n$ is possible. Thus, for any other $k$ not equal to $1$ or $n$, we can print $-1$.",
    "code": "#include <iostream>\nusing namespace std;\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tint n, k; cin >> n >> k;\n\t\tif(k == 1) for(int i = 0; i < n; i++) cout << i + 1 << \" \";\n\t\telse if(k == n) for(int i = 0; i < n; i++) cout << 1 << \" \";\n\t\telse cout << -1;\n\t\tcout << \"\\n\";\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1942",
    "index": "B",
    "title": "Bessie and MEX",
    "statement": "\\begin{quote}\nMOOO! - Doja Cat\n\\hfill ⠀\n\\end{quote}\n\nFarmer John has a permutation $p_1, p_2, \\ldots, p_n$, where every integer from $0$ to $n-1$ occurs exactly once. He gives Bessie an array $a$ of length $n$ and challenges her to construct $p$ based on $a$.\n\nThe array $a$ is constructed so that $a_i$ = $MEX(p_1, p_2, \\ldots, p_i) - p_i$, where the $MEX$ of an array is the minimum non-negative integer that does not appear in that array. For example, $MEX(1, 2, 3) = 0$ and $MEX(3, 1, 0) = 2$.\n\nHelp Bessie construct any valid permutation $p$ that satisfies $a$. The input is given in such a way that at least one valid $p$ exists. If there are multiple possible $p$, it is enough to print one of them.",
    "tutorial": "Solution 1 We will construct the solution forward. Separate the $a_i$'s given into negative and positive cases. What does this tell us about the $\\texttt{MEX}$? We can find $p_1, p_2, ... , p_n$ in order, looking at positive and negative cases. Note that $a_i \\neq 0$ because $p_i$ would equal $\\texttt{MEX}$($p_1 \\dots p_i$), which can never happen. If $a_i > 0$, then $\\texttt{MEX}$($p_1, p_2, ... p_i$) must increase from $\\texttt{MEX}$($p_1, p_2, ... p_{i-1}$), so we know $p_i$ must equal $\\texttt{MEX}$($p_1, p_2, ... p_{i-1}$). Otherwise, the $\\texttt{MEX}$ stays the same, so $p_i$ is just simply $\\texttt{MEX}$($p_1, p_2, ... p_{i-1}$) - $a_i$. Thus, we can just maintain the $\\texttt{MEX}$ and find each $p_i$ as we go forward. There are only 2 things the $\\texttt{MEX}$ can do: increase or stay the same (it can never decrease since larger prefixes contain smaller ones). In the case of a positive difference, consider what would happen if the $\\texttt{MEX}$ stayed the same. Since the difference is positive, the $\\texttt{MEX}$ would have to be greater than the current value, which is impossible because that value had to appear earlier on in the prefix. Since the $\\texttt{MEX}$ is calculated on a permutation that can't happen. So the $\\texttt{MEX}$ has to increase. In the case of a negative value, the $\\texttt{MEX}$ has to be less than the current value. But if it increased that means the current value changed its the $\\texttt{MEX}$, meaning its the $\\texttt{MEX}$ is now at least (current value + 1) and it is actually greater. So it has to stay the same. Note that this is also a way to show $p$ is always unique. Solution 2 We will construct the solution backwards. The $\\texttt{MEX}$ is determined at the last index, since all of $0, 1 \\dots n-1$ appear in $p$. Read the hints. Since we know the $\\texttt{MEX}$ of the last position is $n$, then $n - p_n = a_n$. From this equation, we can find that $p_n = n - a_n$. Now, because we know $p_n$, we can determine the $\\texttt{MEX}$ of the first $n-1$ numbers. Like how we found $p_n$, we can do a similar process for finding $p_{n-1}$. Doing this for $i = n, n - 1 \\dots 1$ will get us a valid answer $p$. Note that this is also a way to show $p$ is always unique.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n\tint n; cin >> n;\n\tvector<int> a(n);\n\tfor(int& i: a) cin >> i;\n\tvector<int> p(n), has(n + 1);\n\tint mex = 0;\n\tfor(int i = 0; i < n; i++){\n\t\tif(a[i] >= 0){\n\t\t\tp[i] = mex;\n\t\t}\n\t\telse{\n\t\t\tp[i] = mex - a[i];\n\t\t}\n\t\thas[p[i]] = true;\n\t\twhile(has[mex]) mex++;\n\t}\n\tfor(int i: p) cout << i << \" \";\n\tcout << \"\\n\";\n}\n\nint main(){\n\tcin.tie(0) -> sync_with_stdio(0);\n\tint T = 1;\n\tcin >> T;\n\twhile(T--) solve();\n}\n\n/*   /\\_/\\\n*   (= ._.)\n*   / >  \\>\n*/",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1942",
    "index": "C2",
    "title": "Bessie's Birthday Cake (Hard Version)",
    "statement": "\\begin{quote}\nProof Geometric Construction Can Solve All Love Affairs - manbo-p\n\\hfill ⠀\n\\end{quote}\n\n\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $y$. In this version $0 \\leq y \\leq n - x$. You can make hacks only if both versions are solved.}\n\nBessie has received a birthday cake from her best friend Elsie, and it came in the form of a regular polygon with $n$ sides. The vertices of the cake are numbered from $1$ to $n$ clockwise. You and Bessie are going to choose some of those vertices to cut \\textbf{non-intersecting} diagonals into the cake. In other words, the endpoints of the diagonals must be part of the chosen vertices.\n\nBessie would only like to give out pieces of cake which result in a triangle to keep consistency. The size of the pieces doesn't matter, and the whole cake does not have to be separated into all triangles (other shapes are allowed in the cake, but those will not be counted).\n\nBessie has already chosen $x$ of those vertices that can be used to form diagonals. She wants you to choose \\textbf{no more than} $y$ other vertices such that the number of triangular pieces of cake she can give out is maximized.\n\nWhat is the maximum number of triangular pieces of cake Bessie can give out?",
    "tutorial": "Ignoring $n$ for now, let's just focus on the $x$ chosen vertices. Sort the $x$ vertices and connect adjacent vertices to form its own smaller polygon. By drawing out some cases or if you're familiar with triangulation (video that proves by induction), you can form $x - 2$ triangles by drawing diagonals in a polygon with $x$ vertices. If you don't know it, one possible construction that always work is fixing one vertex $v$ and drawing diagonals to every other vertex not adjacent to $v$. Now, let's consider the original $n$-sided polygon. In additional to the aforementioned construction, to close the $x$-sided polygon up: for every non-adjacent vertex in the chosen vertices based on the bigger $n$-sided polygon, draw a diagonal between them. Through this construction, we can always guarantee $x - 2$ triangles. However, this doesn't account for all triangles, as some triangles can form sides with the bigger $n$-sided polygon. These triangles occur exactly when two adjacent vertex in $x$ have exactly one vertex not in $x$ between them but part of the bigger polygon. This is because one side is from the diagonals we drew, and the other two sides form from the $n$-sided polygon. Therefore, the answer is $x - 2$ + (number of adjacent chosen vertices $2$ apart). Note that the first chosen vertex is also adjacent to last chosen vertex in $x$. Read the solution to the easy version first. We can now reduce the problem to the following: For every vertex we choose, we can make one more triangle. For every chosen vertices two apart, we can make one more triangle. Let's focus on the latter condition. To maximize the effect of our $y$ vertices, we want to prioritize vertices $v$ that satisfy the following: the vertex is not included in $x$ and there is a chosen vertex two apart. Let's denote such $v$ as good. Let vertex $a$ and $b$ $(a < b)$ be adjacent chosen vertices in the $x$-sided polygon. There are $g = b - a - 1$ vertices for us to choose between them. There are two cases: if $g$ is odd, then we can choose $\\lfloor \\frac{g}{2} \\rfloor$ vertices to form $\\lfloor \\frac{g}{2}\\rfloor + 1$ extra triangles. This is because all of the vertices we choose will be good. if $g$ is even, then we can choose $\\frac{g}{2}$ vertices to make $\\frac{g}{2}$ extra triangles. This is because one of the vertices we choose will not be good. This shows that it is always optimal to process smaller and odd $g$ first. After processing these adjacent gaps, if we have any leftover vertices, we can just ignore them. This is because since we have maximized the number of good vertices, even though any further vertex we place will increase the answer by $1$, it will break two good vertices which will decrease the answer by $1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve(){\n\tint n, x, y; cin >> n >> x >> y;\n\tint initial_y = y;\n\tvector<int> chosen(x);\n\tfor(int& i: chosen) cin >> i;\n\tsort(chosen.begin(), chosen.end());\n\tint ans = x - 2;\n\tint triangles_from_even_g = 0;\n\tvector<int> odd_g;\n\tauto process_gap = [&](int g) -> void{\n\t\tif(g <= 1){\n\t\t\t// already two apart\n\t\t\tans += g;\n\t\t}\n\t\telse if(g % 2 == 1){\n\t\t\todd_g.push_back(g / 2);\n\t\t}\n\t\telse{\n\t\t\ttriangles_from_even_g += g / 2;\n\t\t}\n\t};\n\tfor(int i = 0; i < x - 1; i++){\n\t\tprocess_gap(chosen[i + 1] - chosen[i] - 1);\n\t}\n\tprocess_gap((chosen[0] + n) - chosen[x - 1] - 1);\n\tsort(odd_g.begin(), odd_g.end());\n\tfor(int g: odd_g){\n\t\tif(y >= g){\n\t\t\t// all vertices are good, so we can make g + 1 triangles\n\t\t\tans += g + 1;\n\t\t\ty -= g;\n\t\t}\n\t\telse{\n\t\t\tans += y;\n\t\t\ty = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\tint even_triangles = min(triangles_from_even_g, y);\n\ty -= even_triangles;\n\tans += even_triangles;\n\tint used_vertices = initial_y - y;\n\tans += used_vertices;\n\tcout << ans << \"\\n\";\n}\n\nint main(){\n\tcin.tie(0) -> sync_with_stdio(0);\n\tint T = 1;\n\tcin >> T;\n\twhile(T--) solve();\n}\n\n/*   /\\_/\\\n*   (= ._.)\n*   / >  \\>\n*/",
    "tags": [
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1942",
    "index": "D",
    "title": "Learning to Paint",
    "statement": "\\begin{quote}\nPristine Beat - Touhou\n\\hfill ⠀\n\\end{quote}\n\nElsie is learning how to paint. She has a canvas of $n$ cells numbered from $1$ to $n$ and can paint any (potentially empty) subset of cells.\n\nElsie has a 2D array $a$ which she will use to evaluate paintings. Let the maximal contiguous intervals of painted cells in a painting be $[l_1,r_1],[l_2,r_2],\\ldots,[l_x,r_x]$. The beauty of the painting is the sum of $a_{l_i,r_i}$ over all $1 \\le i \\le x$. In the image above, the maximal contiguous intervals of painted cells are $[2,4],[6,6],[8,9]$ and the beauty of the painting is $a_{2,4}+a_{6,6}+a_{8,9}$.\n\nThere are $2^n$ ways to paint the strip. Help Elsie find the $k$ largest possible values of the beauty of a painting she can obtain, among all these ways. Note that these $k$ values do not necessarily have to be distinct. It is guaranteed that there are at least $k$ different ways to paint the canvas.",
    "tutorial": "We can solve this with dynamic programming. Let $\\texttt{dp}[i]$ store a list of all $\\min(k, 2^i)$ highest beauties of a painting in non-increasing order if you only paint cells $1,2,\\ldots ,i$. Transitioning boils down to finding the $k$ largest elements from $n$ non-increasing lists. Try to do this in $\\mathcal{O}((n + k) \\log n)$ time. Let $\\texttt{dp}[i]$ store a list of all $\\min(k, 2^i)$ highest beauties of a painting in non-increasing order if you only paint cells $1,2,\\ldots ,i$. Let's define merging two lists as creating a new list that stores the $k$ highest values from the two lists. First, let's look at a slow method of transitioning. We iterate over the left endpoint $l$ such that $l \\ldots i$ is a maximal painted interval. At each $l$, we merge $\\texttt{dp}[l - 2]$, with $a_{l,i}$ added to each value, into $\\texttt{dp}[i]$. We also merge $\\texttt{dp}[i - 1]$ into $\\texttt{dp}[i]$ to handle the case in which we do not paint cell $i$. If implemented well, transitioning takes $\\mathcal{O}(nk)$ time leading to an $\\mathcal{O}(n^2k)$ solution which is too slow. We can speed this up. This merging process boils down to finding the $k$ largest elements from $n$ non-increasing lists in $\\mathcal{O}((n + k) \\log n)$ time. We can use a priority queue that stores ($\\texttt{element}, \\texttt{index}$) for each list. We can do the following $k$ times: add the top of the priority queue to our answer, advance its index, and update the priority queue accordingly. This allows us to transition in $\\mathcal{O}((n + k) \\log n)$ time which leads to an $\\mathcal{O}((n^2 + nk) \\log n)$ solution. Bonus: find an $\\mathcal{O}(n^2 + k)$ solution.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve(){\n    int n, k;\n    cin >> n >> k;\n \n    int A[n + 1][n + 1];\n \n    for (int i = 1; i <= n; i++)\n        for (int j = i; j <= n; j++)\n            cin >> A[i][j];\n    \n    // dp[i] = Answer if we consider 1...i\n    vector<int> dp[n + 1];\n    dp[0] = {0};\n \n    for (int i = 1; i <= n; i++){\n        priority_queue<array<int, 3>> pq;\n \n        // Don't create an interval\n        pq.push({dp[i - 1][0], i - 1, 0});\n \n        // Create interval j+2...i (transition from j)\n        for (int j = i - 2; j >= -1; j--){\n            pq.push({(j < 0 ? 0 : dp[j][0]) + A[j + 2][i], j, 0});\n        }\n \n        while (pq.size() and dp[i].size() < k){\n            auto [val, j, num] = pq.top(); pq.pop();\n            dp[i].push_back(val);\n            \n            if (j < 0 or num + 1 >= dp[j].size())\n                continue;\n            \n            // Don't create interval\n            if (j == i - 1)\n                pq.push({dp[i - 1][num + 1], i - 1, num + 1});\n            \n            // Create interval j+2...i (transition from j)\n            else \n                pq.push({dp[j][num + 1] + A[j + 2][i], j, num + 1});\n        }\n    }\n    for (int i : dp[n])\n        cout << i << \" \";\n    cout << \"\\n\";\n}\n \nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc; \n    cin >> tc;\n \n    while (tc--) \n        solve();\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dp",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1942",
    "index": "E",
    "title": "Farm Game",
    "statement": "\\begin{quote}\nLunatic Princess - Touhou\n\\hfill ⠀\n\\end{quote}\n\nFarmer Nhoj has brought his cows over to Farmer John's farm to play a game! FJ's farm can be modeled by a number line with walls at points $0$ and $l + 1$. On the farm, there are $2n$ cows, with $n$ of the cows belonging to FJ and the other $n$ belonging to FN. They place each of their cows at a distinct point, and no two FJ's cows nor FN's cows are adjacent. Two cows are adjacent if there are no other cows between them.\n\nFormally, if $a_1, a_2, \\ldots, a_n$ represents the positions of FJ's cows and $b_1, b_2, \\ldots, b_n$ represents the positions of FN's cows, then either $0 < a_1 < b_1 < a_2 < b_2 < \\ldots < a_n < b_n < l + 1$ or $0 < b_1 < a_1 < b_2 < a_2 < \\ldots < b_n < a_n < l + 1$.\n\nIn one move, a farmer chooses a number $k$ $(1 \\leq k \\leq n)$ and a direction (left or right). Then, that farmer chooses $k$ of his cows and moves them one position towards the chosen direction. A farmer cannot move any of his cows onto the walls or onto another farmer's cow. If a farmer cannot move any cows, then that farmer loses. FJ starts the game, making the first turn.\n\nGiven $l$ and $n$, find the number of possible game configurations for Farmer John to win if both farmers play optimally. It may be the case that the game will continue indefinitely, in which no farmer wins. A configuration is different from another if there is any $i$ such that $a_i$ or $b_i$ is different. Output the answer modulo $998\\,244\\,353$.",
    "tutorial": "Think about the gaps between $(a_1,b_1), (a_2,b_2), ... ,(a_n,b_n)$. Let the gaps be $g_1,g_2,...,g_n$. What effect do the moves have on the gaps? WLOG let the first cow be FJ's cow. FN wins if all $g_i$ are even. Otherwise FJ wins. Note that the game will always end. Try to count the number of ways FN wins. We can iterate over the sum of $g_i$ and use stars and bars as well as other counting techniques. Consider the gaps between $(a_1,b_1), (a_2,b_2), ... ,(a_n,b_n)$. In the example below, '$\\texttt{a}$' represents FJ's cow, '$\\texttt{b}$' represents FN's cow, and '$\\texttt{.}$' represents an empty space. The gaps are $[2,3]$. $\\texttt{|.a..b....a...b.|}$ Consider the gaps $g_1,g_2,...,g_n$. When a farmer moves, they choose some non-empty subset of non-zero $g_i$ and add or subtract $1$ from every element in the subset (so long such move is possible). The game ends when some farmer cannot move (which implies that all $g_i$ must be $0$ when the game ends). WLOG let the first cow be FJ's cow. The winner of the game is determined as follows: 1) If all $g_i$ are even, then FN wins. If FJ pushes the cows corresponding to gaps $i_1, i_2, \\ldots, i_k$ some direction in a move, then $g_{i_1}, g_{i_2}, \\ldots g_{i_k}$ will change by $1$ and become odd. FN can then push the cows corresponding to gaps $i_1, i_2, \\ldots, i_k$ left so that $g_{i_1}, g_{i_2}, \\ldots g_{i_k}$ will become even again. Therefore, all $g_i$ will be even when it's FJ's turn and at least one $g_i$ will be odd when it's FN's turn. Since the game ends when all $g_i$ are $0$ (which is even), then FJ will lose. Note that the game will always end. This is since the sum of positions of FN's cows will always be decreasing since FN will always push some cow left. 2) Otherwise, FJ wins since he can subtract $1$ to all odd $g_i$ in his first move to make all elements even. Then it's FN's turn and all $g_i$ are even so by the reasoning above, FJ wins. Let's use complementary counting and determine the number of ways FN wins (which is when all $g_i$ are even). We can iterate over the sum, $s$ ($s$ is even), of all $g_i$. At each $s$, we can use stars and bars to find how many such $g_1,g_2,...,g_n$ (all $g_i$ are even) sum to $s$. Specifically, the number of ways are $\\frac{s}{2} + n - 1 \\choose n - 1$. The number of ways to place the cows in the available positions given the gaps will be $2 \\cdot {l - s - n \\choose n}$. We multiply by $2$ since we can alternate starting with either FJ's cow or FN's cow. Finally, we subtract this result from the total number of configurations, $2 \\cdot {l \\choose 2 \\cdot n}$, to get the number of ways FJ wins. This runs in $\\mathcal{O}(l)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n\nconst int MAX = 2e6 + 5, MOD = 998244353;\n\nll fact[MAX], ifact[MAX];\n\nll bpow(ll a, int p){\n    ll ans = 1;\n\n    for (;p; p /= 2, a = (a * a) % MOD) \n        if (p & 1) \n            ans = (ans * a) % MOD;\n\n    return ans;\n}\nll ncr(int n, int r){\n    if (n < 0)\n        return 0;\n    if (r > n)\n        return 0;\n\n    return fact[n] * ifact[r] % MOD * ifact[n - r] % MOD;\n}\nvoid solve(){\n    int l, n;\n    cin >> l >> n;\n \n    ll all_even = 0;\n \n    for (int s = 0; s <= l; s += 2){\n        all_even += 2 * ncr(s / 2 + n - 1, n - 1) % MOD * ncr(l - s - n, n) % MOD;\n        all_even %= MOD;\n    }\n    cout << (2 * ncr(l, 2 * n) % MOD - all_even + MOD) % MOD << \"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    \n    for (int i = 0; i < MAX; i++)\n        fact[i] = !i ? 1 : fact[i - 1] * i % MOD;\n    \n    for (int i = MAX - 1; i >= 0; i--)\n        ifact[i] = (i == MAX - 1) ? bpow(fact[MAX - 1], MOD - 2) : ifact[i + 1] * (i + 1) % MOD;\n\n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "combinatorics",
      "games"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1942",
    "index": "F",
    "title": "Farmer John's Favorite Function",
    "statement": "\\begin{quote}\nΩΩPARTS - Camellia\n\\hfill ⠀\n\\end{quote}\n\nFarmer John has an array $a$ of length $n$. He also has a function $f$ with the following recurrence:\n\n- $f(1) = \\sqrt{a_1}$;\n- For all $i > 1$, $f(i) = \\sqrt{f(i-1)+a_i}$.\n\nNote that $f(i)$ is not necessarily an integer.\n\nHe plans to do $q$ updates to the array. Each update, he gives you two integers $k$ and $x$ and he wants you to set $a_k = x$. After each update, he wants to know $\\lfloor f(n) \\rfloor$, where $\\lfloor t \\rfloor$ denotes the value of $t$ rounded down to the nearest integer.",
    "tutorial": "Consider the case where all $f(i)$ are integers. Decreasing any $a_i$ will decrease $\\lfloor f(n) \\rfloor$. So solutions that iterate over the last few elements will not work. If $n \\ge 6$, changing $a_1$ will only affect $\\lfloor f(n) \\rfloor$ by at most $1$. We can take the floor each time we square root. Specifically, we can define $f$ as: $f(1) = \\lfloor \\sqrt{a_1} \\rfloor$ For all $i > 1$, $f(i) = \\lfloor \\sqrt{f(i-1)+a_i} \\rfloor$ This allows us to work with integers. We can divide our array into blocks of size $b \\ge 6$ (note that the value of $b$ depends on the solution). How can we use hint $2$? What should we store for each block? Let's first look at the impact of earlier numbers on the final result. Earlier numbers can still influence $\\lfloor f(n) \\rfloor$ when $n$ is large. Suppose that all $f(i)$ are integers. Then decreasing any $a_i$ will decrease $\\lfloor f(n) \\rfloor$. However, it is clear that the impact of earlier number on $\\lfloor f(n) \\rfloor$ is still extremely small. A key observation is that when $n \\ge 6$, changing $a_1$ will only affect $\\lfloor f(n) \\rfloor$ by at most $1$. Another observation is that we can take the floor each time we square root. Specifically, we can define $f$ as: $f(1) = \\lfloor \\sqrt{a_1} \\rfloor$ For all $i > 1$, $f(i) = \\lfloor \\sqrt{f(i-1)+a_i} \\rfloor$ This allows us to work with integers. From here on, we work with this new definition of $f$. Let's divide our array into blocks of size $b=6$. We can append zeroes to the front of the array to make $n$ a multiple of $b$. Consider some block representing range $[l,r]$. Let's consider the subarray $a_l,a_{l+1},\\ldots ,a_r$. Let $v$ be the value of $f(r)$ if we let $f(l - 1)=0$. Using our first observation, we know that $f(r)$ will be either $v$ or $v+1$ depending on $f(l - 1)$. So let's find the smallest value $c$ such that if $f(l - 1)=c$, then $f(r)=v+1$. This can be done by iterating over the elements of the block backwards. For each block, we store its corresponding ($v,c$). We can build a segment tree over the blocks for an $\\mathcal{O}((n + q) \\log n)$ solution. Alternatively, we can do square root decomposition by having $b=\\sqrt n$ which leads to an $\\mathcal{O}(n + q \\sqrt n)$ solution (in practice, we should set $b$ to something small like $100$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n\nconst int B = 100, MAX = 2e5 + B + 5;\n\nint n, q, offset, numBlocks; ll A[MAX], val[MAX], cut[MAX];\n\nvoid buildBlock(int blk){\n    int l = blk * B;\n    int r = l + B - 1;\n\n    ll cur = 0;\n\n    for (int i = l; i <= r; i++)\n        cur = floor(sqrtl((long double)cur + A[i]));\n    \n    val[blk] = cur;\n\n    ll req = cur + 1;\n\n    for (int i = r; i >= l; i--){\n        if (req > 2e9){\n            cut[blk] = 2e18;\n            return;\n        }\n        req = req * req - A[i];\n    }\n    cut[blk] = req;\n}\nll qry(){\n    ll cur = 0;\n\n    for (int b = 0; b < numBlocks; b++)\n        cur = (cur >= cut[b]) ? val[b] + 1 : val[b];\n    \n    return cur;\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    cin >> n >> q;\n\n    offset = (B - n % B) % B;\n    n += offset;\n    numBlocks = n / B;\n\n    for (int i = offset; i < n; i++)\n        cin >> A[i];\n    \n    for (int b = 0; b < numBlocks; b++)\n        buildBlock(b);\n\n    while (q--){\n        ll k, x;\n        cin >> k >> x;\n        k--; \n        k += offset;\n\n        A[k] = x;\n        buildBlock(k / B);\n\n        cout << qry() << \"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1942",
    "index": "G",
    "title": "Bessie and Cards",
    "statement": "\\begin{quote}\nSecond Dark Matter Battle - Pokemon Super Mystery Dungeon\n\\hfill ⠀\n\\end{quote}\n\nBessie has recently started playing a famous card game. In the game, there is only one deck of cards, consisting of $a$ \"draw $0$\" cards, $b$ \"draw $1$\" cards, $c$ \"draw $2$\" cards, and $5$ special cards. At the start of the game, all cards are in the randomly shuffled deck.\n\nBessie starts the game by drawing the top $5$ cards of the deck. She may then play \"draw $x$\" cards from the hand to draw the next $x$ cards from the top of the deck. Note that every card can only be played once, special cards cannot be played, and if Bessie uses a \"draw $2$\" card when there is only $1$ card remaining in the deck, then she simply draws that remaining card. Bessie wins if she draws all $5$ special cards.\n\nSince Bessie is not very good at math problems, she wants you to find the probability that she wins, given that the deck is shuffled randomly over all $(a + b + c + 5)!$ possible orderings. It can be shown that this answer can always be expressed as a fraction $\\frac{p}{q}$ where $p$ and $q$ are coprime integers. Output $p \\cdot q^{-1}$ modulo $998\\,244\\,353$.",
    "tutorial": "\"Draw $1$\" cards do not matter because we can immediately play them when we draw them. Treat \"draw $2$\" as $+1$ and \"draw $0$\" as $-1$. We start with a balance of $+5$. We draw all the cards up to the first prefix where the balance dips to $0$. We are interested in the number of ways where the special cards lie in this prefix. Read the hints. Treat the special cards as \"draw $0$\" cards and multiply by the appropriate binomial coefficient at the end. Also treat cards of the same type as indistinguishable and multiply by the appropriate factorials at the end. Enumerate the length of the prefix where the balance first hits $0$. This dictates how many $+1$ and $-1$ we have. Now we want to count the number of ways of arranging $+1$ and $-1$ such that the balance never dips to $0$, assuming we start with $+5$. To solve this subproblem, we can draw inspiration from the path counting interpretation for counting balanced bracket sequences. We have $n$ open and $n$ close brackets and want to count the number of balanced bracket sequences starting with (((( (note that there are only $4$ instead of $5$ open brackets to shift from all balances being strictly positive to all balances being non-negative). The number of sequences ignoring the balance constraint is $\\binom{2n-4}{n}$. Any bracket sequence where some balance dips negative corresponds to a path that walks above the line $y = x$. For those paths, we reflect over the line $y = x + 1$ at the first point where it steps over the line. So there is a bijection between these paths and paths that reach the point $(n-1,n+1)$, of which there are $\\binom{2n-4}{n+1}$. So the total number of ways is $\\binom{2n-4}{n} - \\binom{2n-4}{n+1}$. Our final answer is summing up the number of ways over all prefix lengths. Make sure to handle the case where you draw the entire deck correctly. The complexity is $\\mathcal O(\\min(a,c))$.",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1942",
    "index": "H",
    "title": "Farmer John's Favorite Intern",
    "statement": "\\begin{quote}\nPeaches...\n\\hfill ⠀\n\\end{quote}\n\nRuby just won an internship position at Farmer John's farm by winning a coding competition! As the newly recruited intern, Ruby is tasked with maintaining Farmer John's peach tree, a tree consisting of $n$ nodes rooted at node $1$. Each node initially contains $a_i = 0$ peaches, and there are two types of events that can happen:\n\n- Growth event at some node $x$: Ruby must choose \\textbf{either} the parent of $x$ \\textbf{or} any node in the subtree of $x$ and increase the amount of peaches it contains by one.\n- Harvest event at some node $x$: Ruby must choose a single node that is in the subtree of $x$ and decrease the amount of peaches it contains by one. Note that this is \\textbf{not} the same set of nodes as the growth event.\n\nNote that the subtree of $x$ includes the node $x$ as well.Ruby is also given an array $b$ of length $n$. The peach tree is deemed healthy if $a_i \\ge b_i$ for every node $i$.\n\nRuby is asked to perform $q$ operations of two types:\n\n- 1 x v — Perform $v$ growth events on node $x$. Ruby does \\textbf{not} have to choose the same node to increase in every growth event.\n- 2 x v — Perform $v$ harvest events on node $x$. Ruby does \\textbf{not} have to choose the same node to decrease in every harvest event.\n\nFor every prefix of operations, Ruby asks you to find if she can perform these operations \\textbf{in some order} such that the resulting peach tree (at the end of these operations) is healthy. Note that Ruby can't perform a harvest event that makes any $a_i$ negative.\n\nEvery prefix is independent, meaning that for a given operation, Ruby may choose different nodes to perform events on for every prefix that contains that operation.",
    "tutorial": "Model this as a flow problem where growth events are an input of some flow to a node and harvest events and the necessary amount of fruits are an output of flow to the sink. We will define the $a_i$ edge to be the input edge of every node, $b_i$ to be the output edge for necessary fruits, and $c_i$ to be the output edge for growth events. The connections for each individual node will look like: $(\\text{source}, a_i, \\text{# of growth events})$ $(a_i, \\text{temporary node}, \\text{INF})$ $(\\text{temporary node}, b_i, \\text{INF})$ $(\\text{temporary node}, c_i, \\text{INF})$ $(b_i, \\text{sink}, \\text{# of required peaches})$ $(c_i, \\text{sink}, \\text{# of harvest events})$ To simulate growth events affecting the subtree, every temporary node has infinite capacity directed edges down to the temporary nodes of its children. To simulate growth events affecting the parent, every temporary node has an infinite capacity directed edge to its parent's $b_i$. To simulate harvest events affecting subtree, every node has infinite capacity directed edges to all its ancestors' $c_i$ nodes. Lets try to find the min cut of the graph. If we don't put cut some node's $a_i$, then we must cut both $b_i$ and $c_i$ for all of its descendants. If we don't cut some node's $a_i$, then we also must cut $c_i$ for all its ancestors and $b_i$ for its parent. Thus, we can model a $dp[i][0/1/2]$ to know if we are currently cutting the a_i input edge, cutting the b_i and c_i output edge, or cutting the a_i edge but there is some node in the subtree where we did not cut the a_i edge, in which case we need to cut the c_i edge as well. Transitions look like: $dp[i][0] = a_i + \\sum_j dp[j][0]$ $dp[i][1] = b_i + c_i + \\sum_j dp[j][1]$ $dp[i][2] = a_i + c_i + \\min(\\sum_j \\min(dp[j][0], dp[j][2]), b_i + \\sum_j \\min(dp[j][0], dp[j][1], dp[j][2]))$ where at least one child is a $dp[j][2]$ or $dp[j][1]$ $dp[i][2]$ can be rewritten as: $dp[i][2] = a_i + c_i + \\min(\\min(dp[j][2] - \\min(dp[j][0], dp[j][2])) + \\sum_j \\min(dp[j][0], dp[j][2]),$ $\\min(dp[j][1] - \\min(dp[j][0], dp[j][1], dp[j][2])) + b_i + \\sum_j \\min(dp[j][0], dp[j][1], dp[j][2])))$ Use dynamic dp by representing dp transitions as a matrix where all the light children dp values are known and the heavy child dp values are variable. Then, we can accelerate each chain in the heavy light decomposition of the tree. To get the matrix representation of each transition to the heavy child, there are 5 cases when considering a $dp[j][0/1/2]$ -> $dp[j][2]$ transiton where $dp[j][0]$ is the min, $dp[j][1]$ is the min, and $dp[j][2]$ is the min, $dp[j][2] - \\min(dp[j][0], dp[j][2])$ is the optimal added value, or $dp[j][0] - min(dp[j][0], dp[j][1], dp[j][2])$, is the optimal added value. For each cell in the matrix, put the min of the $5$ cases. Since you will only ever change hld chains $\\log n$ times, the total complexity will be $n \\log^2 n \\cdot 3^3$. If we use balanced hld or other $n \\log n$ hld techniques, then the complexity becomes $n \\log^2 n$. Both solutions should pass under the given constraints. There also exists a solution without flows. Thanks to rainboy for discovering it during testing! Lets greedily assign the growth events. We will always try to use the growth events to satisfy harvest events or required peaches in its subtree, and if there is any excess then we give it to the parent's required peaches. Similarly, we will always use harvest events on growth events in its subtree. Lets define a $dp[u]$ for each node $u$. If $dp[x] > 0$ then it means we can give $dp[u]$ growths to $u$'s parent. Otherwise, it means $dp[u]$ requires $-dp[u]$ growths from its ancestors. Let $pos_u$ denote the sum of positive $dp[v]$ where $v$ is a child a of $u$, and $neg_u$ denote the sum of negative $dp[v]$. First we used the excess growth to satisfy the required peaches, so we can set $b_u = \\max(0, b_u - pos_u)$. Then we distribute the growth events at node $u$ to satisfy the requirements in the subtree. Define $a_i$ as the number of growth events on node $i$ and $c_i$ as the number of harvest events on node $i$. To account for the harvest events at node $i$, we can define $bal_u = \\text{sum of } a_i \\text{ in u's subtree} - \\text{sum of } b_i \\text{ in u's subtree} - \\text{sum of } c_i \\text{ in u's subtree}$. We know that $dp[u] \\le bal_u$, and as it turns out, as long as we keep $bal_u$ as an upper bound on $dp[u]$, the harvest events will always be satisfied. Why? $a_u + neg_u - \\max(0, b_u - pos_u)$ is the assignment of growth events without considering harvest events. The amount of unused growth events in the subtree of $u$ is given by $bal_u - (a_u + neg_u - \\max(0, b_u - pos_u)) + c_u$. If $a_u + neg_u - \\max(0, b_u - pos_u) \\le bal_u$, then it means we can use all of our harvest events on unused growth events in the subtree. If $a_u + neg_u - \\max(0, b_u - pos_u) > bal_u$, then it means we will use all of our harvest events but still have $bal_u - (a_u + neg_u - \\max(0, b_u - pos_u))$ harvest events remaining. Thus, we can formulate our dp as $dp[u] = \\min(a_u + neg_u - \\max(0, b_u - pos_u), bal_u)$. Let $v$ be the heavy child of $u$ and $pos'_u$ be the sum of positive dp excluding $v$ and $neg'_u$ be the sum of positive dp excluding $v$. Then, we can rewrite our dp as $dp[u] = \\min(dp[v] + a_u + neg'_u - \\max(0, b_u - pos'_u), a_u + neg'_u, bal_u)$. Define $x_u = a_u + neg'_u - \\max(0, b_u - pos'_u)$ and $y_u = a_u + neg'_u$. Then $dp[u] = \\min(dp[v] + x_u, y_u, bal_u)$. This can be accelerated by representing the transition as a matrix and accelerating it using dynamic dp. However, we can also notice that the dp can be represented as the smallest $x_1 + x_2 + \\ldots + x_{i - 1} + \\min(y_i, bal_i)$ over all prefixes of each heavy light decomposition chain. Thus, we can maintain the dp by using a range add and prefix min segment tree.",
    "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define N\t300000\n#define N_\t(1 << 19)\t/* N_ = pow2(ceil(log2(N))) */\n#define INF\t0x3f3f3f3f3f3f3f3fLL\n\nlong long min(long long a, long long b) { return a < b ? a : b; }\nlong long max(long long a, long long b) { return a > b ? a : b; }\n\nint *ej[N], eo[N], n;\n\nvoid append(int i, int j) {\n\tint o = eo[i]++;\n\n\tif (o >= 2 && (o & o - 1) == 0)\n\t\tej[i] = (int *) realloc(ej[i], o * 2 * sizeof *ej[i]);\n\tej[i][o] = j;\n}\n\nint dd[N], pp[N], qq[N], jj[N], ta[N], tb[N], qu[N];\nint bb[N]; long long aa[N], zz[N], zzp[N], zzn[N];\n\nint dfs1(int i, int d) {\n\tint o, s, k_, j_;\n\n\tdd[i] = d;\n\ts = 1, k_ = 0, j_ = -1;\n\tzz[i] = -bb[i];\n\tfor (o = eo[i]; o--; ) {\n\t\tint j = ej[i][o], k = dfs1(j, d + 1);\n\n\t\ts += k;\n\t\tif (k_ < k)\n\t\t\tk_ = k, j_ = j;\n\t\tzz[i] += zz[j];\n\t}\n\tqq[i] = j_, jj[i] = j_ == -1 ? i : jj[j_];\n\treturn s;\n}\n\nint t_;\n\nvoid dfs2(int i, int q) {\n\tint o, j_;\n\n\tqu[ta[i] = t_++] = i;\n\tj_ = qq[i], qq[i] = q;\n\tif (j_ != -1)\n\t\tdfs2(j_, q);\n\tfor (o = eo[i]; o--; ) {\n\t\tint j = ej[i][o];\n\n\t\tif (j != j_)\n\t\t\tdfs2(j, j);\n\t}\n\ttb[i] = t_;\n}\n\nlong long stx[N_ * 2], sty[N_ * 2], stz[N_ * 2], lz[N_]; int h_, n_;\n\nvoid put(int i, long long x) {\n\tstz[i] += x;\n\tif (i < n_)\n\t\tlz[i] += x;\n}\n\nvoid pus(int i) {\n\tif (lz[i])\n\t\tput(i << 1 | 0, lz[i]), put(i << 1 | 1, lz[i]), lz[i] = 0;\n}\n\nvoid pul(int i) {\n\tif (!lz[i]) {\n\t\tint l = i << 1, r = l | 1;\n\n\t\tstx[i] = stx[l] + stx[r];\n\t\tsty[i] = min(sty[l], stx[l] + sty[r]);\n\t\tstz[i] = min(stz[l], stx[l] + stz[r]);\n\t}\n}\n\nvoid push(int i) {\n\tint h;\n\n\tfor (h = h_; h > 0; h--)\n\t\tpus(i >> h);\n}\n\nvoid pull(int i) {\n\twhile (i > 1)\n\t\tpul(i >>= 1);\n}\n\nvoid build() {\n\tint i, j, a, o;\n        h_ = 0;\n\n\twhile (1 << h_ < n)\n\t\th_++;\n\tn_ = 1 << h_;\n\tmemset(stx, 0, n_ * 2 * sizeof *stx);\n\tmemset(sty, 0, n_ * 2 * sizeof *sty);\n\tmemset(stz, 0, n_ * 2 * sizeof *stz);\n\tmemset(lz, 0, n_ * sizeof *lz);\n\tmemset(aa, 0, n * sizeof *aa);\n\tmemset(zzp, 0, n * sizeof *zzp);\n\tmemset(zzn, 0, n * sizeof *zzn);\n\tfor (i = 0; i < n; i++) {\n\t\ta = ta[i];\n\t\tstz[n_ + a] = zz[i];\n\t\tfor (o = eo[i]; o--; ) {\n\t\t\tj = ej[i][o];\n\t\t\tif (qq[j] == j)\n\t\t\t\tzzn[i] += -zz[j];\n\t\t}\n\t\tstx[n_ + a] = -zzn[i] - bb[i];\n\t\tsty[n_ + a] = -zzn[i];\n\t}\n\tfor (i = n_ - 1; i > 0; i--)\n\t\tpul(i);\n}\n\nvoid upd(int i) {\n\tint i_ = n_ + ta[i];\n\n\tpush(i_);\n\tstx[i_] = aa[i] - zzn[i] - max(bb[i] - zzp[i], 0);\n\tsty[i_] = aa[i] - zzn[i];\n\tpull(i_);\n}\n\nvoid update_z(int l, int r, long long x) {\n\tint l_ = l += n_, r_ = r += n_;\n\n\tpush(l_), push(r_);\n\tfor ( ; l <= r; l >>= 1, r >>= 1) {\n\t\tif ((l & 1) == 1)\n\t\t\tput(l++, x);\n\t\tif ((r & 1) == 0)\n\t\t\tput(r--, x);\n\t}\n\tpull(l_), pull(r_);\n}\n\nlong long query(int l, int r) {\n\tlong long xl, yl, zl, xr, yr, zr;\n\n\tpush(l += n_), push(r += n_);\n\txl = 0, yl = INF, zl = INF, xr = 0, yr = INF, zr = INF;\n\tfor ( ; l <= r; l >>= 1, r >>= 1) {\n\t\tif ((l & 1) == 1) {\n\t\t\tyl = min(yl, xl + sty[l]), zl = min(zl, xl + stz[l]), xl += stx[l];\n\t\t\tl++;\n\t\t}\n\t\tif ((r & 1) == 0) {\n\t\t\tyr = min(sty[r], yr == INF ? INF : stx[r] + yr), zr = min(stz[r], zr == INF ? INF : stx[r] + zr), xr += stx[r];\n\t\t\tr--;\n\t\t}\n\t}\n\treturn min(min(xl + xr, min(yl, yr == INF ? INF : xl + yr)), min(zl, zr == INF ? INF : xl + zr));\n}\n\nint main() {\n\tint t;\n\n\tscanf(\"%d\", &t);\n\twhile (t--) {\n\t\tint q_, i, p, q;\n\n\t\tscanf(\"%d%d\", &n, &q_);\n\t\tfor (i = 0; i < n; i++)\n\t\t\tej[i] = (int *) malloc(2 * sizeof *ej[i]), eo[i] = 0;\n\t\tpp[0] = -1;\n\t\tfor (i = 1; i < n; i++) {\n\t\t\tscanf(\"%d\", &pp[i]), pp[i]--;\n\t\t\tappend(pp[i], i);\n\t\t}\n\t\tfor (i = 0; i < n; i++)\n\t\t\tscanf(\"%d\", &bb[i]);\n\t\tdfs1(0, 0);\n\t\tt_ = 0, dfs2(0, 0);\n\t\tbuild();\n\t\twhile (q_--) {\n\t\t\tint t, x;\n\n\t\t\tscanf(\"%d%d%d\", &t, &i, &x), i--;\n\t\t\tif (t == 2)\n\t\t\t\tx = -x;\n\t\t\tif (t == 1)\n\t\t\t\taa[i] += x, upd(i);\n\t\t\twhile (i >= 0) {\n\t\t\t\tq = qq[i], p = pp[q];\n\t\t\t\tif (p >= 0) {\n\t\t\t\t\tif (zz[q] > 0)\n\t\t\t\t\t\tzzp[p] -= zz[q];\n\t\t\t\t\telse\n\t\t\t\t\t\tzzn[p] -= -zz[q];\n\t\t\t\t}\n\t\t\t\tupdate_z(ta[q], ta[i], x);\n\t\t\t\tzz[q] = query(ta[q], ta[jj[q]]);\n\t\t\t\tif (p >= 0) {\n\t\t\t\t\tif (zz[q] > 0)\n\t\t\t\t\t\tzzp[p] += zz[q];\n\t\t\t\t\telse\n\t\t\t\t\t\tzzn[p] += -zz[q];\n\t\t\t\t\tupd(p);\n\t\t\t\t}\n\t\t\t\ti = p;\n\t\t\t}\n\t\t\tprintf(zz[0] >= 0 ? \"YES\\n\" : \"NO\\n\");\n\t\t}\n\t\tfor (i = 0; i < n; i++)\n\t\t\tfree(ej[i]);\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "flows",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1943",
    "index": "A",
    "title": "MEX Game 1",
    "statement": "Alice and Bob play yet another game on an array $a$ of size $n$. Alice starts with an empty array $c$. Both players take turns playing, with Alice starting first.\n\nOn Alice's turn, she picks one element from $a$, appends that element to $c$, and then deletes it from $a$.\n\nOn Bob's turn, he picks one element from $a$, and then deletes it from $a$.\n\nThe game ends when the array $a$ is empty. Game's score is defined to be the MEX$^\\dagger$ of $c$. Alice wants to maximize the score while Bob wants to minimize it. Find game's final score if both players play optimally.\n\n$^\\dagger$ The $\\operatorname{MEX}$ (minimum excludant) of an array of integers is defined as the smallest non-negative integer which does not occur in the array. For example:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.",
    "tutorial": "Alice can adapt to Bob's strategy. Try to keep that in mind. Whenever Bob chooses $i$, and if there are any copies of $i$ left, Alice can take $i$ on her next move. Let $f$ be the frequency array of $a$. You can ignore all $f(i) \\ge 2$ due to the previous hint. Now the answer is some simple casework. For any $i$ s.t. $f_i \\ge 2$, whenever Bob chooses to remove an occurence of $i$, on the next move Alice simply chooses $i$ herself (if she hasn't already taken $i$ before that). Thus, we only focus on $f_i \\le 1$ now. The answer is min(first $i$ s.t. $f(i) = 0$, second $i$ s.t. $f(i) = 1$). Obviously, Alice can't do better than the mex of array (first $i$ s.t. $f(i) = 0$). Further, among $f(i) = 1$, Alice can save atmost $1$ $i$ after which Bob will remove the smallest $f(i) = 1$ he can find. This is optimal for Bob as well because he cannot do better when Alice removes the (first $i$ s.t. $f(i) = 1$) on her first move.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    while (t--){\n        int n; cin >> n;\n        vector <int> f(n + 1, 0);\n        \n        for (int i = 0; i < n; i++){\n            int x; cin >> x;\n            f[x]++;\n        }\n        \n        int c = 0;\n        for (int i = 0; i <= n; i++){\n            c += (f[i] == 1);\n            if ((c == 2) || (f[i] == 0)){\n                cout << i << \"\\n\";\n                break;\n            }\n        }\n    }\n    return 0;\n}",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1943",
    "index": "B",
    "title": "Non-Palindromic Substring",
    "statement": "A string $t$ is said to be $k$-good if there exists at least one substring$^\\dagger$ of length $k$ which is not a palindrome$^\\ddagger$. Let $f(t)$ denote the sum of all values of $k$ such that the string $t$ is $k$-good.\n\nYou are given a string $s$ of length $n$. You will have to answer $q$ of the following queries:\n\n- Given $l$ and $r$ ($l < r$), find the value of $f(s_ls_{l + 1}\\ldots s_r)$.\n\n$^\\dagger$ A substring of a string $z$ is a contiguous segment of characters from $z$. For example, \"$\\mathtt{defor}$\", \"$\\mathtt{code}$\" and \"$\\mathtt{o}$\" are all substrings of \"$\\mathtt{codeforces}$\" while \"$\\mathtt{codes}$\" and \"$\\mathtt{aaa}$\" are not.\n\n$^\\ddagger$ A palindrome is a string that reads the same backwards as forwards. For example, the strings \"$z$\", \"$aa$\" and \"$tacocat$\" are palindromes while \"$codeforces$\" and \"$ab$\" are not.",
    "tutorial": "When is a string not $k$-good? (Ignore the trivial edge cases of $k = 1$ and $k = n$). What happens when $s[i....j]$ and $s[i + 1....j + 1]$ are both palindromes? We first try to find the answer for a string Let $k = j - i + 1$, $s[i....j]$ -> I and $s[i + 1...j + 1]$ -> II are both palindromes. Then $s_i = s_j$ (due to I) $s_j = s_{i + 2}$ (due to II) $s_{i + 2} = s_{j - 2}$ (due to I) $s_{j - 2} = s_{i + 4}$ (due to II) and so on.... you can see that it forces $s_i = s_{i + 2} = s_{i + 4} = ....$. A similiar reasoning gives you $s_{i + 1} = s_{i + 3} = s_{i + 5}$. Further, if $k$ is even, $i$ and $j$ have different parities, but $s_i = s_j$ implies that all characters must be equal actually. We mentioned that the edge cases are $1$ and $n$, but why exactly? How does the analysis fail for them?(Left as a exercise) So, the condition for a string to be $k$-good can be written as follows : $k = 1$ : never possible $1 < k < n$, odd : not an alternating string $1 < k < n$, even : not all characters same $k = n$ : non-palindromic string Now onto substring queries. The second and third things are easy to handle, you can store the next position where $s_i \\ne s_{i + 2}$ and $s_i \\ne s_{i + 1}$ respectively. Checking if a substring is a palindrome is standard with various methods such as string hashing or manacher's algorithm.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define INF (int)1e18\n\nmt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());\n\nvector<int> manacher_odd(string s) {\n    int n = s.size();\n    s = \"$\" + s + \"^\";\n    vector<int> p(n + 2);\n    int l = 1, r = 1;\n    for(int i = 1; i <= n; i++) {\n        p[i] = max(0, min(r - i, p[l + (r - i)]));\n        while(s[i - p[i]] == s[i + p[i]]) {\n            p[i]++;\n        }\n        if(i + p[i] > r) {\n            l = i - p[i], r = i + p[i];\n        }\n    }\n    return vector<int>(begin(p) + 1, end(p) - 1);\n}\n\nvector<int> manacher(string s) {\n    string t;\n    for(auto c: s) {\n        t += string(\"#\") + c;\n    }\n    auto res = manacher_odd(t + \"#\");\n    return vector<int>(begin(res) + 1, end(res) - 1);\n}\n\n#define int long long\n\nvoid Solve() \n{\n    int n, q; cin >> n >> q;\n\n    string s; cin >> s;\n    auto v = manacher(s);\n    for (auto &x : v) x--;\n\n    // we also need to know if all same, and all alternating \n    set <int> s1, s2;\n    for (int i = 0; i < n - 1; i++){\n        if (s[i] != s[i + 1]) s1.insert(i);\n        if (i != n - 1 && s[i] != s[i + 2]) s2.insert(i);\n    }\n\n    while (q--){\n        int l, r; cin >> l >> r;\n        l--;\n        r--;\n\n        if (l == r){\n            cout << 0 << \"\\n\";\n            continue;\n        }\n        \n        int len = r - l + 1;\n\n        int ans;\n        auto it = s1.lower_bound(l);\n        if (it == s1.end() || (*it) >= r){\n            ans = 0;\n        } else {\n            it = s2.lower_bound(l);\n            if (it == s2.end() || (*it) >= r - 1){\n                ans = ((len - 1)/ 2) * (((len - 1) / 2) + 1);\n            } else {\n                ans =  len * (len - 1) / 2 - 1;\n            }\n        }\n\n        if (v[l + r] < (r - l + 1)) ans += len;\n\n        cout << ans << \"\\n\";\n    }\n}\n\nint32_t main() \n{\n    auto begin = std::chrono::high_resolution_clock::now();\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t = 1;\n    // freopen(\"in\",  \"r\", stdin);\n    // freopen(\"out\", \"w\", stdout);\n    \n    cin >> t;\n    for(int i = 1; i <= t; i++) \n    {\n        //cout << \"Case #\" << i << \": \";\n        Solve();\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    cerr << \"Time measured: \" << elapsed.count() * 1e-9 << \" seconds.\\n\"; \n    return 0;\n}",
    "tags": [
      "hashing",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1943",
    "index": "C",
    "title": "Tree Compass",
    "statement": "You are given a tree with $n$ vertices numbered $1, 2, \\ldots, n$. Initially, all vertices are colored white.\n\nYou can perform the following two-step operation:\n\n- Choose a vertex $v$ ($1 \\leq v \\leq n$) and a distance $d$ ($0 \\leq d \\leq n-1$).\n- For all vertices $u$ ($1 \\leq u \\leq n$) such that $\\text{dist}^\\dagger(u,v)=d$, color $u$ black.\n\nConstruct a sequence of operations to color all the nodes in the tree black using the minimum possible number of operations. It can be proven that it is always possible to do so using at most $n$ operations.\n\n$^\\dagger$ $\\text{dist}(x, y)$ denotes the number of edges on the (unique) simple path between vertices $x$ and $y$ on the tree.",
    "tutorial": "Try to solve for line case. You may have to use more than $1$ node for certain cases. Extend the solution for the line to the general tree version (consider the diamater). For a line, an obvious bound on the answer is $\\lceil \\frac{n}{2} \\rceil$, as we can colour atmost $2$ nodes per operation. I claim this is achieveable except for when $n$ mod $4 = 2$, where we do $1$ worse. That is however still provably optimal as you can bicolour the line and operations only colours nodes black which are in the same bicolouring. When $n$ mod $2 = 1$, simply use the centre of the line and do operations of the form $(centre, i)$ ($0 \\le i \\le \\lfloor \\frac{n}{2} \\rfloor$). When $n$ mod $4 = 0$, for convenience let the line be $1, 2, ...., n$. Then, we can do operations like $(2, 1), (3, 1), (6, 1), (7, 1)....$. When $n$ mod $4 = 2$, either of the above $2$ methods can be adapted to work because we are allowed $1$ \"extra\" operation. Now that we have the solution for the line case, lets divide into $2$ cases based on parity of diamater (maximum number of nodes on a path) : diameter mod $2 = 1$ : Find the centre of the diamater. Then we can simply do operations of the form $(centre, i)$ (for all $0 \\le i \\le \\lfloor \\frac{diameter}{2} \\rfloor$). If this doesn't colour all nodes, then one can easily check that the diamater we found is not the real diamater, as the node which is not coloured is an endpoint of a larger diameter. diamater mod $2 = 0$ : Find the $2$ centres of the diameter. Then the following set of operations satisfy the requirements : $(centre1, i)$ and $(centre2, i)$ for all odd $i$ satisfying $1 \\le i \\le \\frac{diameter}{2}$. The intuition behind this is to basically split the nodes into $2$ sets according to a bicolouring, and then $1$ centre colours all nodes of a certain colour, while the other centre colours all nodes of the other colour.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define INF (int)1e18\n#define f first\n#define s second\n\nmt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());\n\nvoid Solve() \n{\n    int n;\n    cin >> n;\n    \n    vector<vector<int>> E(n);\n    \n    for (int i = 1; i < n; i++){\n        int u, v; cin >> u >> v;\n        \n        u--; v--;\n        E[u].push_back(v);\n        E[v].push_back(u);\n    }\n    \n    auto bfs = [&](int s){\n      vector<int> d(n, -1);\n      d[s] = 0;\n      queue<int> Q;\n      Q.push(s);\n      while (!Q.empty()){\n        int v = Q.front();\n        Q.pop();\n        for (int w : E[v]){\n          if (d[w] == -1){\n            d[w] = d[v] + 1;\n            Q.push(w);\n          }\n        }\n      }\n      return d;\n    };\n    \n    vector<int> d1 = bfs(0);\n    int a = max_element(d1.begin(), d1.end()) - d1.begin();\n    vector<int> d2 = bfs(a);\n    int b = max_element(d2.begin(), d2.end()) - d2.begin();\n    vector<int> d3 = bfs(b);\n    int diam = d3[max_element(d3.begin(), d3.end()) - d3.begin()] + 1;\n    //if 3 we want 1, 1 if 4 we want 1 2 \n    \n    vector <int> ans;\n    for (int i = 0; i < n; i++){\n        if ((d2[i] + d3[i] == diam - 1) && ((d2[i] == diam/2) || (d3[i] == diam/2))) \n            ans.push_back(i);\n    }\n    \n    if (diam & 1) assert(ans.size() == 1);\n    else assert(ans.size() == 2);\n    \n    vector <pair<int, int>> ok;\n    \n    if (diam & 1){\n        //print everything from 0 to diam/2 \n        for (int i = 0; i <= diam/2; i++){\n            ok.push_back({ans[0], i});\n        }\n    } else {\n        //2 => 2 ops, 4 => 2 ops , 6 => 4 ops, 8 => 4 ops \n        int ops = ((n - 2)/4) + 1;\n        int need = (diam/2) - 1;\n        while (need >= 0){\n            ok.push_back({ans[0], need});\n            ok.push_back({ans[1], need});\n            \n            need -= 2;\n        }\n    }\n    \n    cout << ok.size() << \"\\n\";\n    for (auto [u, r] : ok){\n        cout << u + 1 << \" \" << r << \"\\n\";\n    }\n}\n\nint32_t main() \n{\n    auto begin = std::chrono::high_resolution_clock::now();\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t = 1;\n    cin >> t;\n    for(int i = 1; i <= t; i++) \n    {\n        //cout << \"Case #\" << i << \": \";\n        Solve();\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n   // cerr << \"Time measured: \" << elapsed.count() * 1e-9 << \" seconds.\\n\"; \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1943",
    "index": "D1",
    "title": "Counting Is Fun (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if both versions of the problem are solved.}\n\nAn array $b$ of $m$ non-negative integers is said to be good if all the elements of $b$ can be made equal to $0$ using the following operation some (possibly, zero) times:\n\n- Select two \\textbf{distinct} indices $l$ and $r$ ($1 \\leq l \\textcolor{red}{<} r \\leq m$) and subtract $1$ from all $b_i$ such that $l \\leq i \\leq r$.\n\nYou are given two positive integers $n$, $k$ and a prime number $p$.\n\nOver all $(k+1)^n$ arrays of length $n$ such that $0 \\leq a_i \\leq k$ for all $1 \\leq i \\leq n$, count the number of good arrays.\n\nSince the number might be too large, you are only required to find it modulo $p$.",
    "tutorial": "Try to come up with some necessary and sufficient conditions of a good array. Apply dp once you have a good condition. All operations which include $i$ must also either include $i - 1$ or $i + 1$. Hence $a_i \\le a_{i - 1} + a_{i + 1}$ must hold. Throughout the editorial treat $a_i = 0$ for $(i \\le 0)$ or $(i > n)$. But, is this sufficient? Infact, it is and we can prove it by strong induction. Group arrays according to the sum of the array. We will now apply strong induction on the sum of the array. Base Cases (sum = 0, 1 or 2) are all trivial. Now, assume that the condition is sufficient for all arrays with sum $< x$ ($x \\ge 3$). Let us consider some array $a_1, a_2, ...., a_n$ with sum $x$. Let $a_i$ be the first non-zero element of $a$.(Observe that $a_{i + 1}$ can't be $0$). We claim that either operating on $[i, i + 1]$ or $[i, i + 2]$ will give still satisfy the condition $a_j \\le a_{j - 1} + a_{j + 1}$ for all $j$. Let's check it. The only time $[i, i + 1]$ operation causes an issue is when $a_{i + 2} > a_{i + 1} - 1 + a_{i + 3}$, i.e. it should necessarily hold that $a_{i + 2} > a_{i + 3}$, but then $a_{i + 3} \\le a_{i + 2} - 1$, and so, $a_{i + 3} \\le a_{i + 2} - 1 + a_{i + 4}$, meaning $[i, i + 2]$ is valid. Now that we have the condition, we can define a dynamic programming as follows : $dp(i, a, b)$ = number of ways to make an array upto the $i$-th index with $a_{i - 1} = a$, $a_i = b$ (since only the last $2$ elements are relevant). Let the new element be $c$, then it is a valid way iff $b \\le a + c$. So we have a $\\mathcal{O}(n^4)$ by iterating over all possibilities. As a final optimization, we can speed it up to $\\mathcal{O}(n^3)$ by using prefix sums. Note that the valid values of $a$ for fixed $b$ and $c$ satisfy $a \\ge max(0, b - c)$, and hence maintaining prefix sums over $a$, we can speed it up.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define INF (int)1e18\n#define f first\n#define s second\n\nmt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());\n\nvoid Solve() \n{\n    int n, k, mod; cin >> n >> k >> mod;\n    \n    vector<vector<int>> dp(k + 1, vector<int>(k + 1, 0));\n    dp[0][0] = 1; // dp[a][b]\n    \n    for (int i = 1; i <= n + 2; i++){\n        vector<vector<int>> ndp(k + 1, vector<int>(k + 1, 0)); // dp[b][c]\n        vector<vector<int>> pref(k + 1, vector<int>(k + 1, 0)); // pref[b][a]\n        \n        for (int b = 0; b <= k; b++){\n            pref[b][0] = dp[0][b];\n            for (int a = 1; a <= k; a++){\n                pref[b][a] = (pref[b][a - 1] + dp[a][b]) % mod;\n            }\n        }\n        \n        for (int b = 0; b <= k; b++){\n            for (int c = 0; c <= k; c++){\n                if (b > c){\n                    // a must be atleast b - c \n                    ndp[b][c] = (pref[b][k] - pref[b][b - c - 1] + mod) % mod;\n                } else {\n                    ndp[b][c] = pref[b][k];\n                }\n            }\n        }\n        \n        dp = ndp;\n    }\n    \n    cout << dp[0][0] << \"\\n\";\n}\n\nint32_t main() \n{\n    auto begin = std::chrono::high_resolution_clock::now();\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t = 1;\n    // freopen(\"in\",  \"r\", stdin);\n    // freopen(\"out\", \"w\", stdout);\n    \n    cin >> t;\n    for(int i = 1; i <= t; i++) \n    {\n        //cout << \"Case #\" << i << \": \";\n        Solve();\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    cerr << \"Time measured: \" << elapsed.count() * 1e-9 << \" seconds.\\n\"; \n    return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1943",
    "index": "D2",
    "title": "Counting Is Fun (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if both versions of the problem are solved.}\n\nAn array $b$ of $m$ non-negative integers is said to be good if all the elements of $b$ can be made equal to $0$ using the following operation some (possibly, zero) times:\n\n- Select two \\textbf{distinct} indices $l$ and $r$ ($1 \\leq l \\textcolor{red}{<} r \\leq m$) and subtract $1$ from all $b_i$ such that $l \\leq i \\leq r$.\n\nYou are given two positive integers $n$, $k$ and a prime number $p$.\n\nOver all $(k+1)^n$ arrays of length $n$ such that $0 \\leq a_i \\leq k$ for all $1 \\leq i \\leq n$, count the number of good arrays.\n\nSince the number might be too large, you are only required to find it modulo $p$.",
    "tutorial": "Try to apply Principle of Inclusion Exclusion (PIE). You do not need to store both last elements! Only the last is enough. Since there are $n^3$ states in our dp, we will have to optimize the number of states somehow. Let us consider all arrays and not just good arrays. An element is bad if $a_i > a_{i - 1} + a_{i + 1}$. Suppose, $f(x_1, x_2, ...., x_k)$ gave us the number of arrays where each of $x_i$ are distinct and bad. (Note that other positions may be bad as well). Then, by PIE, the answer is $(-1)^k \\cdot f(x_1, x_2, ....., x_k)$. For example, for $n = 3$, we would want to compute $f([]) - f([1]) - f([2]) - f([3]) + f([1, 2]) + f([1, 3]) + f([2, 3]) - f([1, 2, 3])$. Note that $f([])$ is simply $(k + 1)^n$ as there are no restrictions placed on the array. This has $2^n$ calculations, so we need to optimize it. First optimization : obviously, only $k$ matters and not the exact indices. This means we only have to maintain the count of the number of indices we have made sure are bad. Second optimization : only parity of $k$ matters, due to the only dependence of $k$ being $(-1)^k$. We now define $dp(i, last, x)$ = number of arrays such that $a_i = last$ and the parity of bad elements (that we know of) till $i$ is $x$. Transitions : Without (necessarily) creating a bad element : $dp(i, last, x) += dp(i - 1, y, x)$ for all $0 \\le y \\le k$. We might accidentally create more bad elements, but remember that PIE allows us to not worry about that. Without (necessarily) creating a bad element : $dp(i, last, x) += dp(i - 1, y, x)$ for all $0 \\le y \\le k$. We might accidentally create more bad elements, but remember that PIE allows us to not worry about that. With creating a bad element : We view it as a transition from index $(i - 2)$, $a_{i - 1} > a_i + a_{i - 2}$ for it to bad, so fix $a_i = l1$, $a_{i - 2} = l2$, and you get $dp(i, l1, x) += dp(i - 2, l2, 1 - x) \\cdot (max(0, k - l1 - l2))$. The $max(0, k - l1 - l2)$ term comes from the ways to choose $a_{i - 1}$ such that $a_{i - 1} > l1 + l2$. With creating a bad element : We view it as a transition from index $(i - 2)$, $a_{i - 1} > a_i + a_{i - 2}$ for it to bad, so fix $a_i = l1$, $a_{i - 2} = l2$, and you get $dp(i, l1, x) += dp(i - 2, l2, 1 - x) \\cdot (max(0, k - l1 - l2))$. The $max(0, k - l1 - l2)$ term comes from the ways to choose $a_{i - 1}$ such that $a_{i - 1} > l1 + l2$. Both the transitions are optimizable with some prefix sums and running totals to get a $\\mathcal{O}(n^2)$ solution.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define INF (int)1e18\n#define f first\n#define s second\n\nmt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());\n\nvoid Solve() \n{\n    int n, k, mod; cin >> n >> k >> mod;\n    \n    vector<vector<int>> dp(2, vector<int>(k + 1, 0));\n    auto prev2 = dp;\n    dp[0][0] = 1;\n    \n    for (int i = 1; i <= n + 1; i++){\n        vector<vector<int>> ndp(2, vector<int>(k + 1, 0));\n        vector<int> sum(2, 0);\n        \n        for (int j = 0; j < 2; j++) for (int x = 0; x <= k; x++){\n            sum[j] += dp[j][x]; sum[j] %= mod;\n        }\n        \n        for (int j = 0; j < 2; j++){\n            int s1 = 0, s2 = 0;\n            \n            for (int x = k; x >= 0; x--){\n                ndp[j][x] += sum[j];  // normal transition\n                \n                ndp[j][x] += s2; ndp[j][x] %= mod; // with one wrong\n                \n                s1 += prev2[j ^ 1][k - x]; s1 %= mod;\n                s2 += s1; s2 %= mod;\n            }\n        }\n        \n        prev2 = dp;\n        dp = ndp;\n    }\n    \n    int ans = (dp[0][0] - dp[1][0] + mod) % mod;\n    cout << ans << \"\\n\";\n}\n\nint32_t main() \n{\n    auto begin = std::chrono::high_resolution_clock::now();\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t = 1;\n    // freopen(\"in\",  \"r\", stdin);\n    // freopen(\"out\", \"w\", stdout);\n    \n    cin >> t;\n    for(int i = 1; i <= t; i++) \n    {\n        //cout << \"Case #\" << i << \": \";\n        Solve();\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    cerr << \"Time measured: \" << elapsed.count() * 1e-9 << \" seconds.\\n\"; \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1943",
    "index": "E1",
    "title": "MEX Game 2 (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $t$, $m$ and the sum of $m$. You can make hacks only if both versions of the problem are solved.}\n\nAlice and Bob play yet another game on an array $a$ of size $n$. Alice starts with an empty array $c$. Both players take turns playing, with Alice starting first.\n\nOn Alice's turn, she picks one element from $a$, appends that element to $c$, and then deletes it from $a$.\n\nOn Bob's turn, he picks at most $k$ elements from $a$, and then deletes it from $a$.\n\nThe game ends when the array $a$ is empty. Alice's score is defined to be the MEX$^\\dagger$ of $c$. Alice wants to maximize her score while Bob wants to minimize it. Find Alice's final score if both players play optimally.\n\nThe array will be given in compressed format. Instead of giving the elements present in the array, we will be giving their frequencies. Formally, you will be given $m$, the maximum element in the array, and then $m + 1$ integers $f_0, f_1, \\ldots, f_m$, where $f_i$ represents the number of times $i$ occurs in the array $a$.\n\n$^\\dagger$ The $\\operatorname{MEX}$ (minimum excludant) of an array of integers is defined as the smallest non-negative integer which does not occur in the array. For example:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.",
    "tutorial": "It might be optimal for Bob to reduce multiple elements at the same time, thus making Alice choose between which element she wants to take. Suppose you are only checking whether $ans \\ge i$ for now, what would Alice's strategy be? Try fixing the element that Bob wants to make sure Alice is not able to get. What would be his strategy then? For now, lets try to see if $ans \\ge i$. This is equivalent to Alice being able to take $1$ occurence of everything when the game is reduced to numbers $[0, i - 1]$. Alice's strategy here is actually easy to find. At every step, Alice will choose the minimum $f_j$ such that $0 \\le j < i$, and she hasn't chosen $i$ yet. You can reason this with greedy stays ahead, exchange argument, whatever you want. This gives us a nice definition of Alice's moves, however we seemingly have to maintain the sorted sequence of $f_i$ always. But we can actually rewrite Bob's moves such that it does not affect the sorted order of $f_i$ and always keeps it sorted. Here, by sorted order, we mean some permutation $p = [p_1, p_2, ...., p_i]$ of $[0, i - 1]$ such that $f_{p_i} \\le f_{p_j}$ whenever $i \\le j$. First, instead of subtracting $k$, we will do $k$ subtractions of only $1$. Then, the only case when sorted order can be destroyed is when there exists $k1$ and $k2$ such that $f_{k1} = f_{k2}$ and we do an operation on $k1$ but $k2$ occurs before $k1$ in the sorted order. This issue can simply be fixed by doing the operation on the smallest $x$ (according to sorted order) such that $f_x = f_{k1}$. Now, we have a good way of representing Alice moves. Suppose we fixed the element that Bob \"wins\" on. Then, Bob's strategy will obviously be to make the frequency of that element as small as possible, but he must make sure to never violate sorted condition. Since Bob will make at most $m$ moves, you can just simulate his moves. The main details of the simulation is that you need to figure out upto what index all values will become equal when doing k operations (or nearly equal, off by 1), and then first take all elements to that state. Let $w$ be the remaining operations from the $k$ operations after this, and $l$ the length of the equal sequence. Then you will reduce every frequency by $w / l$, and finally reduce the first $w$ mod $l$ numbers of this sequence. Check the code for more details. A naive implementation takes $O(m)$ per move, so $O(m^2)$ per element we fix => $O(m^3)$ total to check $ans \\ge i$. With a binary search on the answer, you get $O(m^3 logm)$. It can be optimized further, but it wasnt needed to pass. Most other polynomial solutions should pass this.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define INF (int)1e18\n#define f first\n#define s second\n\nmt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());\n\nvoid Solve() \n{\n    int n, k; cin >> n >> k;\n\n    vector <int> a(n + 1);\n    for (auto &x : a) cin >> x;\n\n    auto check = [&](int x){\n        vector <int> b;\n        for (int i = 0; i < x; i++){\n            b.push_back(a[i] - k);\n        }\n\n        sort(b.begin(), b.end());\n\n        for (int fix = 1; fix < x; fix++){\n            // this is element where bob wins \n\n            deque <int> c;\n            for (int i = 0; i <= fix; i++){\n                c.push_back(b[i]);\n            }\n            \n            assert(c.size() >= 2);\n\n            while (c.size() != 2){\n                c.pop_front(); \n\n                // find suffix which works \n                int sz = c.size();\n                int works = 0;\n                int sum = 0;\n                for (int j = 1; j < sz; j++){\n                    // sum(elements of c - current element) \n                    // this shud be >= k \n                    sum += c[sz - j];\n                    int loss = sum - c[sz - j - 1] * j;\n                    if (loss >= k){\n                        works = sz - j;\n                        break;\n                    }\n                }\n\n                int have = k;\n\n                // make everything = c[works]\n                for (int j = works + 1; j < sz; j++){\n                    have -= c[j] - c[works];\n                    c[j] = c[works];\n                }\n\n                assert(have >= 0);\n                for (int j = works; j < sz; j++){\n                    c[j] -= have / (sz - works);\n                }\n                have %= (sz - works);\n\n                for (int j = works; j < sz; j++){\n                    if (have){\n                        c[j]--;\n                        have--;\n                    }\n                }\n\n                for (int j = 0; j < sz - 1; j++){\n                    assert(c[j] <= c[j + 1]);\n                }\n            }\n\n            c.pop_front();\n            if (c[0] <= 0) return false;\n        }\n\n        return true;\n    };\n\n    int l = 1, r = n + 1;   \n    while (l != r){\n        int mid = (l + r + 1) / 2;\n\n        if (check(mid)) l = mid;\n        else r = mid - 1;\n    }\n\n    cout << l << \"\\n\";\n}\n\nint32_t main() \n{\n    auto begin = std::chrono::high_resolution_clock::now();\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t = 1;\n    // freopen(\"in\",  \"r\", stdin);\n    // freopen(\"out\", \"w\", stdout);\n    \n    cin >> t;\n    for(int i = 1; i <= t; i++) \n    {\n        //cout << \"Case #\" << i << \": \";\n        Solve();\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    cerr << \"Time measured: \" << elapsed.count() * 1e-9 << \" seconds.\\n\"; \n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1943",
    "index": "E2",
    "title": "MEX Game 2 (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $t$, $m$ and the sum of $m$. You can make hacks only if both versions of the problem are solved.}\n\nAlice and Bob play yet another game on an array $a$ of size $n$. Alice starts with an empty array $c$. Both players take turns playing, with Alice starting first.\n\nOn Alice's turn, she picks one element from $a$, appends that element to $c$, and then deletes it from $a$.\n\nOn Bob's turn, he picks at most $k$ elements from $a$, and then deletes it from $a$.\n\nThe game ends when the array $a$ is empty. Alice's score is defined to be the MEX$^\\dagger$ of $c$. Alice wants to maximize her score while Bob wants to minimize it. Find Alice's final score if both players play optimally.\n\nThe array will be given in compressed format. Instead of giving the elements present in the array, we will be giving their frequencies. Formally, you will be given $m$, the maximum element in the array, and then $m + 1$ integers $f_0, f_1, \\ldots, f_{m}$, where $f_i$ represents the number of times $i$ occurs in the array $a$.\n\n$^\\dagger$ The $\\operatorname{MEX}$ (minimum excludant) of an array of integers is defined as the smallest non-negative integer which does not occur in the array. For example:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.",
    "tutorial": "Instead of doing the check for $ans \\geq i$ in $O(m^3)$, we will do it in $O(m)$. For an array $f$ of length $n$. Let $s=f_1+f_2+\\ldots+f_n$ be the sum of the element. $f$ will be called flat if $f_i = \\lfloor \\frac{s+i-1}{n} \\rfloor$. That is, it has the form $x, \\ldots, x, x+1, \\ldots x+1$. All flat array can be characters by $2$ integers $(n,s)$ only. Imagine simulating Bob's strategy without simulating Alice's moves of removing the first element of the array. For some prefix of the moves, the actual simulation will be a suffix of this simulation. This is because to subtract something from index $\\leq i$, we must have $f_{i+1} = f_{i+2} = \\ldots = f_n$. As an example, let $k=4$. With Alice moves: $[1,2,3,5,5] \\to [2,3,3,3] \\to [1,2,2]$ Without Alice moves: $[1,2,3,5,5] \\to [1,2,3,3,3] \\to [1,1,2,2,2]$ $[1,2,2]$ is not a suffix of $[1,1,2,2,2]$ and is the first time such a thing happens. Suppose that the first time this happens is after $p$ moves. Then the resulting array is the flat array $(n-p,f_{p+1}+f_{p+2}+\\ldots+f_n-pk)$. To find the necessary value of $p$, we can binary search or run $2$-pointers to check if the suffix of the array can reach $f_p$ with the amount of subtraction operations till then. (What we basically did is find the suffix of the array that actually gets operated on, since that makes it much more easier to solve) Then, since the flat array $(n,s)$ becomes $(n-1,s-\\lfloor \\frac{s}{n} \\rfloor - k)$, we can figure out whether each flat array evantually becomes a losing or winning state as we can calculate for each $n$, the minimum $s$ such that $(n,s)$ is a winning state.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n#define ll long long\n#define ii pair<ll,ll>\n#define iii pair<ii,ll>\n#define fi first\n#define se second\n#define endl '\\n'\n#define debug(x) cout << #x << \": \" << x << endl\n\n#define pub push_back\n#define pob pop_back\n#define puf push_front\n#define pof pop_front\n#define lb lower_bound\n#define ub upper_bound\n\n#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define all(x) (x).begin(),(x).end()\n#define sz(x) (int)(x).size()\n\nmt19937 rng(chrono::system_clock::now().time_since_epoch().count());\n\nint n,k;\nint arr[200005];\nint temp[200005];\n\nbool solve(vector<int> v){\n    sort(all(v));\n    \n    rep(x,0,sz(v)) temp[x]=1e18;\n    \n    int l=1,curr=0;\n    rep(x,1,sz(v)){\n        curr+=v[x];\n        \n        while (l<x && (curr-v[l])-(x-l)*v[l] >= l*k){\n            curr-=v[l];\n            l++;\n        }\n        \n        temp[x-l]=min(temp[x-l],curr-l*k);\n    }\n    \n    rep(x,sz(v),1) temp[x-1]=min(temp[x-1],(temp[x]-temp[x]/(x+1))-k);\n    \n    return temp[0]>0;\n}\n\nsigned main(){\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    cin.exceptions(ios::badbit | ios::failbit);\n    \n    int TC;\n    cin>>TC;\n    while (TC--){\n        cin>>n>>k;\n        rep(x,0,n+1) cin>>arr[x];\n        \n        // solve(vector<int>(arr,arr+n+1));\n        // continue;\n        \n        int lo=0,hi=n+2,mi;\n        while (hi-lo>1){\n            mi=hi+lo>>1;\n            \n            if (solve(vector<int>(arr,arr+mi))) lo=mi;\n            else hi=mi;\n        }\n        \n        cout<<lo<<endl;\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "two pointers"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1943",
    "index": "F",
    "title": "Minimum Hamming Distance",
    "statement": "You are given a binary string$^\\dagger$ $s$ of length $n$.\n\nA binary string $p$ of the same length $n$ is called \\textbf{good} if for every $i$ ($1 \\leq i \\leq n$), there exist indices $l$ and $r$ such that:\n\n- $1 \\leq l \\leq i \\leq r \\leq n$\n- $s_i$ is a mode$^\\ddagger$ of the string $p_lp_{l+1}\\ldots p_r$\n\nYou are given another binary string $t$ of length $n$. Find the minimum Hamming distance$^\\S$ between $t$ and any \\textbf{good} string $g$.\n\n$^\\dagger$ A binary string is a string that only consists of characters $\\mathtt{0}$ and $\\mathtt{1}$.\n\n$^\\ddagger$ Character $c$ is a mode of string $p$ of length $m$ if the number of occurrences of $c$ in $p$ is at least $\\lceil \\frac{m}{2} \\rceil$. For example, $\\mathtt{0}$ is a mode of $\\mathtt{010}$, $\\mathtt{1}$ is not a mode of $\\mathtt{010}$, and both $\\mathtt{0}$ and $\\mathtt{1}$ are modes of $\\mathtt{011010}$.\n\n$^\\S$ The Hamming distance of strings $a$ and $b$ of length $m$ is the number of indices $i$ such that $1 \\leq i \\leq m$ and $a_i \\neq b_i$.",
    "tutorial": "Assumption: 0 is the mode of string t. If 1 occurs more times than 0 in t, we will flip all characters of s and t so that 0 is the mode of string t. Let us say index $i$ nice if there exists $l$ and $r$($1 \\le l \\le i \\le r \\le n$) such that $s_i$ is the mode of substring $t[l,r]$. So we might have some not nice indices $i$ such that $s_i =$ $\\mathtt{1}$. We will not have any index $i$ such that i is not nice and $s_i =$ $\\mathtt{0}$, as $\\mathtt{0}$ is the mode of $t$. So, we need to fix the not nice indices. Now we will start changing some $\\mathtt{0}$ to $\\mathtt{1}$. So it might be possible that in final $t$, the frequency of $\\mathtt{1}$ is more than that of $\\mathtt{0}$, and $\\mathtt{0}$ is no longer the mode. So should we worry about indices $i$ such that $i$ was nice in the beginning, and now that we made some flips, $i$ may become not nice? No! It will never be possible. In case $\\mathtt{1}$ occurs more times than $\\mathtt{0}$ in the updated $t$, we will have $frequency[1] = frequency[0] + 1$ and $t[1] = t[n] =$ $\\mathtt{1}$(we will have such cases for pairs like ($s =$ $\\mathtt{011}$, $t =$ $\\mathtt{100}$; for this pair final $t$ should be $t =$ $\\mathtt{101}$). So the substrings $t[1, n - 1]$ and $t[2, n]$ will have equal numbers of $\\mathtt{0}$ and $\\mathtt{1}$, and thus all indices should be nice. So our claim is that we should change some $\\mathtt{0}$ to $\\mathtt{1}$, without caring about indices $i$(which were nice initially) becoming not nice such that $s_i =$ $\\mathtt{0}$. We can use dynamic programming here. So let us have $dp$, such that $dp[i][j]$ gives the minimum number of flips required to make $t[1, i]$ friend of $s[1, i]$ and the maximum suffix sum is $j$. String $x$ is called to be friend of string $y(|x| = |y|)$, if for every $i$($1 \\le i \\le |x|$), there exists indices $l$ and $r$ such that: 1. $1 \\le l \\le i \\le r \\le |x|$ 2. $x_i$ is a mode of the string $y[l,r]$ Please read hints $1$ and $2$ if you haven't as they contain some claims and definitions. Note that when we find some sum, we add $1$ when we get $\\mathtt{1}$ and subtract $-1$ when we get $\\mathtt{0}$. Suppose we have found $dp$ values for the first $i - 1$ indices, and we want to find $dp[i][j]$ for $0 \\le j \\le n$. Now, we need to perform the transitions. Let us try to have a $O(n^3)$ solution first, which we can optimise after making some observations. Take some $l$($0 \\leq l \\leq i - 1$). We will iterate over $suff$_$sum = 0$ to $n$, here $suff$_$sum$ is the maximum suffix sum of substring $t[1, l]$, and use $dp[l][suff$_$sum]$ to find optimal values for $dp[i][x]$ for some $x$. So we need to do some flips to substring $t[l + 1, i]$, as $s[1, l]$ and $t[1, l]$ are already friends. So we only care to make all indices $j$ ($l + 1 \\le j \\le i$) nice. So there are two possibilities(either $\\mathtt{1}$ occurs in substring $s[l + 1, i]$ or not): If $\\mathtt{1}$ does not occur, we can perform the transition without making any flips. If $\\mathtt{1}$ does not occur, we can perform the transition without making any flips. Assume $\\mathtt{1}$ occurs in substring $s[l + 1, i]$. So firstly, find the sum(say $cur$_$sum$) of substring $t[l + 1, i]$. Now, if we do some flips to substring $t[l + 1, i]$, $cur$_$sum$ will change accordingly. We will do a minimum number of flips such that $suff$_$sum + cur$_$sum \\ge 0$. Note that we are talking here about updated $cur$_$sum$. So we can find the minimum number(say $cost$) of flips, which will be $\\lfloor \\frac{\\max(0, 1 -d )}{2} \\rfloor$, where $d=suff$_$sum + initial$_$cur$_$sum$. So we know how many flips to make. Assume $\\mathtt{1}$ occurs in substring $s[l + 1, i]$. So firstly, find the sum(say $cur$_$sum$) of substring $t[l + 1, i]$. Now, if we do some flips to substring $t[l + 1, i]$, $cur$_$sum$ will change accordingly. We will do a minimum number of flips such that $suff$_$sum + cur$_$sum \\ge 0$. Note that we are talking here about updated $cur$_$sum$. So we can find the minimum number(say $cost$) of flips, which will be $\\lfloor \\frac{\\max(0, 1 -d )}{2} \\rfloor$, where $d=suff$_$sum + initial$_$cur$_$sum$. So we know how many flips to make. But which ones to flip? Here is one more claim. We should only flip the last $cost$ $\\mathtt{0}$ of substring $t[l + 1, i]$. So this is a sufficient condition, as we can certainly say that $t[1, i]$ will be friend of $s[1, i]$ now. So we know the required number of flips, which is $dp[l][suff$_$sum] + cost$. We need to find one more thing - what would be the maximum suffix sum if we flip the last $cost$ characters of $t[l + 1, i]$? We can precompute. But we have an issue now. We know that what we performed is sufficient. But is it necessary? What if we did not need to flip cost characters of $t[l + 1, i]$? It might be possible that we could have done less number of flips and still made all indices $l + 1 \\le j \\le i$ nice. The reasoning behind this is we made sure that $suff$_$sum + cur$_$sum \\ge 0$, but what if it was not needed? Like it is possible that total sum is negative, but all indices $j$($l + 1 \\le j \\le i$) such that $s_j =$ $\\mathtt{1}$ are satisfied. So here, we can use exchange arguments and conclude that all cases will be covered if we check for all pairs of ($l, suff$_$sum$) $0 \\le l, suff$_$sum \\le i - 1$. Now we need to optimise this to $O(n^2)$. Notice that when we do the flips, there will be a suffix(possibly empty when $cost=0$) of $t[l + 1, i]$ containing only $\\mathtt{1}$ s. Suppose we are at index $i$ and need to find $dp[i][j]$ for $0 \\le j \\le i$. We can iterate over all $j$($1 \\le j \\le i$), assume that all the characters in substring $t[j,i]$ are $\\mathtt{1}$ s, and find the $dp$ values. Maximum suffix sum will be $i-j+1+max$_$suffix$_$sum[j-1]$. So we can find the smallest index $p$ such that the sum of the elements in substring $t[p,l]$ is greater than or equal to $0$ if we make all the characters in substring $t[j,i]$ $\\mathtt{1}$. Notice that we already have the new suffix maximum, and we know the $cost$ too, which is equal to the number of $\\mathtt{0}$ s in the original substring $t[j,i]$. So our transition will be $dp[i][new$_$suffix$_$max]=\\max(dp[i][new$_$suffix$_$max], \\min\\limits_{k = p-1}^{i} best[k] + cost)$, where $best[i]= \\min\\limits_{k = 0}^{i} dp[i][k]$. So, our final complexity will be $O(n^2)$, as we can perform the transition in $O(1)$ if we precompute the needed things.",
    "code": "#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll int\n#define pb push_back                  \n#define mp make_pair          \n#define nline \"\\n\"                            \n#define f first                                            \n#define s second                                             \n#define pll pair<ll,ll> \n#define all(x) x.begin(),x.end()     \nconst ll MOD=998244353;\nconst ll MAX=10005;  \nll dp[MAX][MAX];\nll suffix_min[MAX];\nll suffix_max[MAX];\nll can_go_till[MAX][MAX+5];\nvoid solve(){     \n    ll n; cin>>n; \n    ll shift=n;\n    for(ll i=-n;i<=0;i++){\n        can_go_till[0][shift+i]=0;\n    }\n    string s,t; cin>>s>>t;\n    s=\" \"+s,t=\" \"+t;\n    ll sum=0;\n    for(ll i=1;i<=n;i++){\n        sum+=2*(t[i]-'0')-1;\n    }\n    suffix_max[0]=0;\n    if(sum>=0){   \n        for(ll i=1;i<=n;i++){\n            s[i]='0'+'1'-s[i];  \n            t[i]='0'+'1'-t[i];\n        }    \n    }\n    ll max_sum=0;\n    for(ll i=1;i<=n;i++){\n        max_sum+=2*(t[i]-'0')-1;\n        max_sum=max(0,max_sum);\n        suffix_max[i]=max_sum;\n    }  \n    for(ll i=1;i<=n;i++){\n        sum=0;\n        for(ll j=-n;j<=0;j++){\n            can_go_till[i][shift+j]=i+1;\n        }\n        for(ll j=i;j>=1;j--){\n            sum+=2*(t[j]-'0')-1;\n            ll use=min(sum,0);\n            can_go_till[i][shift+use]=j;\n        }\n        for(ll j=n-1;j>=0;j--){\n            can_go_till[i][j]=min(can_go_till[i][j],can_go_till[i][j+1]);\n        }\n    }\n    for(ll i=0;i<=n+1;i++){\n        for(ll j=0;j<=n+1;j++){\n            dp[i][j]=MOD;\n        }\n    }\n    dp[0][0]=0;\n    vector<ll> best(n+5,MOD);\n    best[0]=0;\n    for(ll i=1;i<=n;i++){\n        for(ll l=0;l<=i-1;l++){ \n            dp[i][l+1]=dp[i-1][l]+(t[i]=='0');\n        }\n        for(ll l=0;l<=i;l++){\n            ll new_sum=l+2*(t[i]-'0')-1;  \n            if(s[i]=='1' and new_sum<=-1){\n                continue; \n            }    \n            new_sum=max(0,new_sum); \n            dp[i][new_sum]=min(dp[i][new_sum],dp[i-1][l]);\n        }\n        suffix_min[i]=MOD;\n        for(ll j=i-1;j>=0;j--){\n            suffix_min[j]=min(suffix_min[j+1],best[j]);\n        }\n        ll cnt=0;\n        for(ll j=i;j>=1;j--){\n            cnt+=(t[j]=='0');\n            ll now=i-j+1;\n            ll cur_suff_max=now+suffix_max[j-1];\n            ll pos=max(0,can_go_till[j-1][shift-now]-1);\n            dp[i][cur_suff_max]=min(dp[i][cur_suff_max],suffix_min[pos]+cnt);\n        }\n        for(ll j=0;j<=n;j++){\n            best[i]=min(best[i],dp[i][j]); \n        }\n    } \n    ll ans=MOD; \n    s[0]='1';\n    for(ll i=n;i>=0;i--){  \n        ans=min(ans,best[i]);    \n        if(s[i]=='1'){\n            cout<<ans<<nline;\n            return;  \n        }\n    }\n    return;          \n}                                          \nint main()                                                                               \n{     \n    ios_base::sync_with_stdio(false);                         \n    cin.tie(NULL);                               \n    #ifndef ONLINE_JUDGE                 \n    freopen(\"input.txt\", \"r\", stdin);                                           \n    freopen(\"output.txt\", \"w\", stdout);      \n    freopen(\"error.txt\", \"w\", stderr);                        \n    #endif     \n    ll test_cases=1;                 \n    cin>>test_cases;\n    while(test_cases--){\n        solve();\n    }\n    cout<<fixed<<setprecision(10);\n    cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1944",
    "index": "A",
    "title": "Destroying Bridges",
    "statement": "There are $n$ islands, numbered $1, 2, \\ldots, n$. Initially, every pair of islands is connected by a bridge. Hence, there are a total of $\\frac{n (n - 1)}{2}$ bridges.\n\nEverule lives on island $1$ and enjoys visiting the other islands using bridges. Dominater has the power to destroy at most $k$ bridges to minimize the number of islands that Everule can reach using (possibly multiple) bridges.\n\nFind the minimum number of islands (including island $1$) that Everule can visit if Dominater destroys bridges optimally.",
    "tutorial": "What is the minimum number of bridges to burn if we want to make exactly $i$ islands visitable from $1$? Atleast $i \\cdot (n - i)$ bridges need to burnt (the bridges connecting the $i$ reachable islands and the $n - i$ non-reachable islands). A simple $O(n)$ solution is for every $i$ from $1$ to $n$, check if $i \\cdot (n - i) \\le k$, in which case print $i$ and break. What is the answer when $k \\ge n - 1$. When $k < n - 1$, is it possible to make any island non-visitable? When $k \\ge n - 1$, the answer is $1$ since we can just destroy all bridges $(1, i)$ for $2 \\le i \\le n$. Otherwise, suppose we tried to make some set of $i$ islands non-visitable, and the other $n - i$ nodes reachable from $1$. Then we need to burn atleast $i \\cdot (n - i)$ bridges (the bridges connecting the $2$ sets). It is not hard to see that this function attains the minimum value when $i = 1$ or $i = n - 1$ for $1 \\le i < n$. Hence the minimum number of bridges to burn always exceeds $n - 1$. The function $f(x) = x \\cdot (n - x)$ is a quadratic function in $x$, which attains maximum value at $x = \\frac{n}{2}$, and the value decreasing proportionally as the distance from $\\frac{n}{2}$ increases. This means that $f(1) = f(n - 1)$, and $f(1) > f(i)$ for all ($2 \\le i \\le (n - 2)$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    while (t--){\n        int n, k; cin >> n >> k;\n        if (k >= n - 1) cout << 1 << \"\\n\";\n        else cout << n << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1944",
    "index": "B",
    "title": "Equal XOR",
    "statement": "You are given an array $a$ of length $2n$, consisting of each integer from $1$ to $n$ exactly \\textbf{twice}.\n\nYou are also given an integer $k$ ($1 \\leq k \\leq \\lfloor \\frac{n}{2} \\rfloor $).\n\nYou need to find two arrays $l$ and $r$ each of length $\\mathbf{2k}$ such that:\n\n- $l$ is a subset$^\\dagger$ of $[a_1, a_2, \\ldots a_n]$\n- $r$ is a subset of $[a_{n+1}, a_{n+2}, \\ldots a_{2n}]$\n- bitwise XOR of elements of $l$ is equal to the bitwise XOR of elements of $r$; in other words, $l_1 \\oplus l_2 \\oplus \\ldots \\oplus l_{2k} = r_1 \\oplus r_2 \\oplus \\ldots \\oplus r_{2k}$\n\nIt can be proved that at least one pair of $l$ and $r$ always exists. If there are multiple solutions, you may output any one of them.\n\n$^\\dagger$ A sequence $x$ is a subset of a sequence $y$ if $x$ can be obtained by deleting several (possibly none or all) elements of $y$ and rearranging the elements in any order. For example, $[3,1,2,1]$, $[1, 2, 3]$, $[1, 1]$ and $[3, 2]$ are subsets of $[1, 1, 2, 3]$ but $[4]$ and $[2, 2]$ are not subsets of $[1, 1, 2, 3]$.",
    "tutorial": "Group numbers according to how many times they occur in $a[1...n]$. The group of numbers having $0$ occurrences in $a[1...n]$ is of the same size as the group of numbers having $2$ occurences in $a[1...n]$. Try to use the $0$ and $2$ occurrence numbers first, and then if we still need more, we can use the $1$ occurence numbers. Remember that we have to form sequences of size $2 \\cdot k$ which is even. We can append any $2$ occurrence numbers to our sequence $l$ and any $0$ occurrence numbers to our sequence $r$ without any issue because the xor value will cancel out. We do this while our sequence sizes are less than $2 \\cdot k$. At the end of this process, $l$ and $r$ will have the same size due to Hint $2$. Now, we use as many $1$ occurrence numbers appending to both $l$ and $r$ as needed. Since we append to both sequences, the xor value of the $2$ sequences will be the same. If we had to solve for odd sequence sizes, we could take a $1$ occurrence number at the very start to make it even, and then run the same process, but if there are no $1$ occurrence numbers at all, we fail with this method.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    while (t--){\n        int n, k; \n        cin >> n >> k; \n        k = 2 * k;\n        \n        vector <int> a(2 * n), occ(n + 1, 0);\n        \n        for (auto &x : a) cin >> x;\n        for (int i = 0; i < n; i++) occ[a[i]]++;\n        \n        vector <int> g0, g1, g2;\n        for (int i = 1; i <= n; i++){\n            if (occ[i] == 0) g0.push_back(i);\n            else if (occ[i] == 1) g1.push_back(i);\n            else g2.push_back(i);\n        }\n        \n        int v = 0;\n        for (auto x : g2){\n            if (v < k){\n                v += 2;\n                cout << x << \" \" << x << \" \";\n            }\n        }\n        for (auto x : g1){\n            if (v < k){\n                v++;\n                cout << x << \" \";\n            }\n        }\n        cout << \"\\n\";\n        \n        v = 0;\n        for (auto x : g0){\n            if (v < k){\n                v += 2;\n                cout << x << \" \" << x << \" \";\n            }\n        }\n        for (auto x : g1){\n            if (v < k){\n                v++;\n                cout << x << \" \";\n            }\n        }\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1945",
    "index": "A",
    "title": "Setting up Camp",
    "statement": "The organizing committee plans to take the participants of the Olympiad on a hike after the tour. Currently, the number of tents needed to be taken is being calculated. It is known that each tent can accommodate up to $3$ people.\n\nAmong the participants, there are $a$ introverts, $b$ extroverts, and $c$ universals:\n\n- Each introvert wants to live in a tent alone. Thus, a tent with an introvert must contain exactly one person — only the introvert himself.\n- Each extrovert wants to live in a tent with two others. Thus, the tent with an extrovert must contain exactly three people.\n- Each universal is fine with any option (living alone, with one other person, or with two others).\n\nThe organizing committee respects the wishes of each participant very much, so they want to fulfill all of them.\n\nTell us the minimum number of tents needed to be taken so that all participants can be accommodated according to their preferences. If it is impossible to accommodate the participants in a way that fulfills all the wishes, output $-1$.",
    "tutorial": "First, let's consider introverts. Since each of them needs exactly one tent, we simply add $a$ to the answer. Then let's consider extroverts. If their number is divisible by 3, we add $\\frac{b}{3}$ to the answer. Otherwise, we calculate $d = 3 - b \\bmod 3$, where $x \\bmod y$ denotes the remainder from dividing $x$ by $y$. If $d > c$, then there is no answer, as it is not possible to accommodate the extroverts in the tents. Otherwise, we subtract $d$ from $c$ and add $\\frac{c}{3}$ to the answer. The general formula when there is an answer: $a + \\frac{b + d}{3} + \\lceil\\frac{c - d + 2}{3}\\rceil$. Complexity: $\\mathcal{O}(1)$.",
    "code": "#include <iostream>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    ll single, poly, uni;\n    cin >> single >> poly >> uni;\n    ll needPoly = (3 - poly % 3) % 3;\n    if (poly > 0 && needPoly > uni) {\n        cout << \"-1\\n\";\n        return;\n    }\n\n    uni -= needPoly;\n    poly += needPoly;\n\n    ll mn = single + uni / 3 + (uni % 3 + 1) / 2 + poly / 3;\n    cout << mn << '\\n';\n}\n\nint32_t main() {\n    ll T;\n    cin >> T;\n    while(T--){\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1945",
    "index": "B",
    "title": "Fireworks",
    "statement": "One of the days of the hike coincided with a holiday, so in the evening at the camp, it was decided to arrange a festive fireworks display. For this purpose, the organizers of the hike bought two installations for launching fireworks and a huge number of shells for launching.\n\nBoth installations are turned on simultaneously. The first installation launches fireworks every $a$ minutes (i.e., after $a, 2 \\cdot a, 3 \\cdot a, \\dots$ minutes after launch). The second installation launches fireworks every $b$ minutes (i.e., after $b, 2 \\cdot b, 3 \\cdot b, \\dots$ minutes after launch).\n\nEach firework is visible in the sky for $m + 1$ minutes after launch, i.e., if a firework was launched after $x$ minutes after the installations were turned on, it will be visible every minute from $x$ to $x + m$, inclusive. If one firework was launched $m$ minutes after another, both fireworks will be visible for one minute.\n\nWhat is the maximum number of fireworks that could be seen in the sky at the same time?",
    "tutorial": "Let's consider the moment in time $T = \\text{LCM}(a, b)$ (least common multiple of numbers $a$ and $b$). It is easy to notice that since $T > 0$ and $T$ is divisible by both $a$ and $b$, at this moment both camps will release a firework, each of which will disappear after $m + 1$ minutes. Let's look at the sky at the $T + m$-th minute. We will still see two fireworks released at the moment $T$, the first camp managed to release $\\lfloor\\frac{m}{a}\\rfloor$ fireworks, and the second, similarly, $\\lfloor\\frac{m}{b}\\rfloor$ fireworks (this follows from the fact that $T$ is divisible by $a$ and $b$). Taking into account the two fireworks released at the moment $T$, we will reach the answer $\\lfloor\\frac{m}{a}\\rfloor + \\lfloor\\frac{m}{b}\\rfloor + 2$. Why can't we achieve a greater answer? Let's consider two setups for launching fireworks independently. Without loss of generality, consider the first setup (releasing fireworks every $a$ minutes). Consider the moment when the fireworks from this setup are visible in the sky. Let the first firework among the visible ones disappear at the moment $x$, then at the moment $x$ we will see no fewer fireworks, but at the moment $x + 1$ - fewer. At the moment $x$, there will be fireworks in the sky, released at moments [$x$, $x + a$, $\\dots$, $x + a \\cdot \\lfloor\\frac{m}{a}\\rfloor$]. Thus, from the first setup, we can see no more than $\\lfloor\\frac{m}{a}\\rfloor + 1$ fireworks simultaneously. The same formula is applicable to the second setup. We have proved that the answer does not exceed $\\lfloor\\frac{m}{a}\\rfloor + 1 + \\lfloor\\frac{m}{b}\\rfloor + 1 = \\lfloor\\frac{m}{a}\\rfloor + \\lfloor\\frac{m}{b}\\rfloor + 2$, so that is the answer. Complexity: $\\mathcal{O}(1)$.",
    "code": "t = int(input())\nfor qi in range(t):\n    a, b, m = [int(x) for x in  input().split()]\n    ans = m // a + m // b + 2\n    print(ans)",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "1945",
    "index": "C",
    "title": "Left and Right Houses",
    "statement": "In the village of Letovo, there are $n$ houses. The villagers decided to build a big road that will divide the village into left and right sides. Each resident wants to live on either the right or the left side of the street, which is described as a sequence $a_1, a_2, \\dots, a_n$, where $a_j = 0$ if the resident of the $j$-th house wants to live on the left side of the street; otherwise, $a_j = 1$.\n\nThe road will pass between two houses. The houses to the left of it will be declared the left-side, and the houses to the right will be declared the right-side. More formally, let the road pass between houses $i$ and $i+1$. Then the houses at positions between $1$ and $i$ will be on the \\textbf{left} side of the street, and at positions between $i+1$ and $n$ will be on the \\textbf{right} side. The road also \\textbf{may} pass before the first and after the last house; in this case, the entire village is declared to be either the right or left side, respectively.\n\nTo make the design fair, it was decided to lay the road so that at least half of the residents on each side of the village are satisfied with the choice. That is, among $x$ residents on one side, at least $\\lceil\\frac{x}{2}\\rceil$ should want to live on that side, where $\\lceil x \\rceil$ denotes rounding up a real number $x$.\n\n\\begin{center}\n{\\small To the left of the road, there will be $i$ houses, among the corresponding $a_j$ there must be at least $\\lceil\\frac{i}{2}\\rceil$ zeros. To the right of the road, there will be $n-i$ houses, among the corresponding $a_j$ there must be at least $\\lceil\\frac{n-i}{2}\\rceil$ ones.}\n\\end{center}\n\nDetermine after which house $i$ the road should be laid in order to satisfy the described condition and be as close to the middle of the village as possible. Formally, among all suitable positions $i$, minimize $\\left|\\frac{n}{2} - i\\right|$.\n\nIf there are multiple suitable positions $i$ with the minimum $\\left|\\frac{n}{2} - i\\right|$, output the smaller one.",
    "tutorial": "According to the statement, to the left of the road there should be no less elements $a_i$ such that $a_i = 0$ than such that $a_i = 1$, and to the right of the road there should be no less elements $a_i$ than such that $a_i = 1$ than such that $a_i = 0$. We will consider each position of the road and check the compliance with the road design condition. To do this, we will use the prefix sum method to access the number of $1$'s in the suffix in $\\mathcal{O}(1)$ (the number of such $i$ that $i > x$ and $a_i = 1$ for any $x$). We will also maintain the count of $0$'s among the elements to the left of the road and the optimal answer. If the road position $x$ is suitable and it is closer to the middle than the most optimal answer found before, we will update it (and will not forget to increase the count of $0$ if the next element $a_{x + 1} = 0$). It is convenient to double the distance to the middle of the village: instead of $\\left|\\frac{n}{2} - i\\right|$, consider it as $2\\left|\\frac{n}{2} - i\\right| = \\left|n - 2\\cdot i\\right|$. This way, we can get rid of calculations in non-integer numbers. Complexity: $\\mathcal{O}(n)$",
    "code": "for case in range(int(input())):\n    n = int(input())\n    a = input()\n    suf_cnt = [0] * (n + 1)\n    for i in range(n - 1, -1, -1):\n        suf_cnt[i] = suf_cnt[i + 1] + (a[i] == '1')\n    pref_cnt = 0\n     \n    opt_ans = -1\n    opt_dist = n * 2\n    threshold = (n + 1) // 2\n     \n    for i in range(n + 1):\n        if pref_cnt >= (i + 1) // 2 and suf_cnt[i] >= (n - i + 1) // 2 and abs(n - 2 * i) < opt_dist:\n            opt_dist = abs(n - 2 * i)\n            opt_ans = i\n        if i != n:\n            pref_cnt += (a[i] == '0')\n     \n    print(opt_ans)\n",
    "tags": [
      "brute force"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1945",
    "index": "D",
    "title": "Seraphim the Owl",
    "statement": "The guys lined up in a queue of $n$ people, starting with person number $i = 1$, to ask Serafim the Owl about the meaning of life. Unfortunately, Kirill was very busy writing the legend for this problem, so he arrived a little later and stood at the end of the line after the $n$-th person. Kirill is completely dissatisfied with this situation, so he decided to bribe some people ahead of him.\n\nFor the $i$-th person in the queue, Kirill knows two values: $a_i$ and $b_i$. If at the moment Kirill is standing at position $i$, then he can choose any position $j$ such that $j < i$ and exchange places with the person at position $j$. In this case, Kirill will have to pay him $a_j$ coins. And for each $k$ such that $j < k < i$, Kirill will have to pay $b_k$ coins to the person at position $k$. Kirill can perform this action any number of times.\n\nKirill is thrifty, so he wants to spend as few coins as possible, but he doesn't want to wait too long, so Kirill believes he should be among the first $m$ people in line.\n\nHelp Kirill determine the minimum number of coins he will have to spend in order to not wait too long.",
    "tutorial": "Let's consider a greedy approach. Suppose we are standing at position $i$. Find the first $j$ such that $j < i$ and $a_j < b_j$. If such $j$ exists and $j > m$, then swap with $j$. This will be optimal, because in any case we will have to pay the people at positions $i - 1, i - 2, \\dots, j$ some amount of coins, and in this way we will pay each person at position $k$ where $i > k > j$, $b_k$ coins. According to the greedy condition $b_k > a_k$, so $b_k$ is the minimum amount of coins we can pay $k$-th person. We will also pay the $j$-th person $a_j$ coins. $a_j < b_j$, hence we will pay the minimum amount of coins to all people. If such $j$ does not exist, then it is advantageous for us to choose the final position $f$, such that $1 \\le f \\le m$, in order to finish the movements and overpay as little as possible. Simply check each $f$, recalculating the answer using prefix sums on array $b$ and choose the smallest one. Asymptotics: $\\mathcal{O}(n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    ll n, k;\n    cin >> n >> k;\n    vector<ll> A(n);\n    for (auto& item : A) {\n        cin >> item;\n    }\n    reverse(A.begin(), A.end());\n\n    vector<ll> B(n);\n    for (auto& item : B) {\n        cin >> item;\n    }\n    reverse(B.begin(), B.end());\n\n    ll bSum = 0;\n    ll pref = 0;\n    for (ll i = 0; i < n - k; ++i) {\n        if (A[i] < B[i]) {\n            pref += bSum;\n            pref += A[i];\n            bSum = 0;\n        } else {\n            bSum += B[i];\n        }\n    }\n\n    ll res = 1e18;\n    for (ll i = n - k; i < n; ++i) {\n        res = min(res, pref + bSum + A[i]);\n        bSum += B[i];\n    }\n\n    cout << res << '\\n';\n}\n\nint32_t main() {\n    ll testN;\n    cin >> testN;\n    while (testN--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1945",
    "index": "E",
    "title": "Binary Search",
    "statement": "Anton got bored during the hike and wanted to solve something. He asked Kirill if he had any new problems, and of course, Kirill had one.\n\nYou are given a permutation $p$ of size $n$, and a number $x$ that needs to be found. A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nYou decided that you are a cool programmer, so you will use an advanced algorithm for the search — binary search. However, you forgot that for binary search, the array must be sorted.\n\nYou did not give up and decided to apply this algorithm anyway, and in order to get the correct answer, you can perform the following operation \\textbf{no more than} $2$ times before running the algorithm: choose the indices $i$, $j$ ($1\\le i, j \\le n$) and swap the elements at positions $i$ and $j$.\n\nAfter that, the binary search is performed. At the beginning of the algorithm, two variables $l = 1$ and $r = n + 1$ are declared. Then the following loop is executed:\n\n- If $r - l = 1$, end the loop\n- $m = \\lfloor \\frac{r + l}{2} \\rfloor$\n- If $p_m \\le x$, assign $l = m$, otherwise $r = m$.\n\nThe goal is to rearrange the numbers in the permutation before the algorithm so that after the algorithm is executed, $p_l$ is equal to $x$. It can be shown that $2$ operations are always sufficient.",
    "tutorial": "In fact, the problem can be solved in a single operation. Let's start a binary search on the initial permutation. We will get some index $l$. Then, it is enough to swap $p_l$ and $x$. Now our binary search will stop exactly at the number $x$. Notice that in the search, any number less than or equal to $x$ affects the result like $x$. Indeed, $p_l \\le x$ remains true if we replace $p_l$ with $x$. Note that if we swapped two numbers that give the same result in the condition of the binary search, then the final $l$ will not change. The previous statements assumed that $p_l \\le x$. Indeed, in the algorithm description, after changing $l$, the number $p_l$ cannot become greater than $x$. It is also necessary to consider the case when $l = 1$ after executing the algorithm. If $l = 1$, then at each iteration of the algorithm, $p_m > x$, in particular, this means that $p_m$ was never equal to $x$. In this case, swapping $p_1$ and $x$ will also not affect the result ($l$) of the binary search. Complexity: $\\mathcal{O}(n)$.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve() {\n    int n, x;\n    cin >> n >> x;\n    vector<int> src(n);\n    int P = 0;\n    for (int i = 0; i < n; ++i) {\n        cin >> src[i];\n        if (src[i] == x) {\n            P = i;\n        }\n    }\n\n    int l = 0;\n    int r = n;\n    while (r - l > 1) {\n        int m = (l + r) / 2;\n\n        if (src[m] <= x) {\n            l = m;\n        } else {\n            r = m;\n        }\n    }\n\n    cout << \"1\\n\";\n    cout << P + 1 << ' ' << l + 1 << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1945",
    "index": "F",
    "title": "Kirill and Mushrooms",
    "statement": "As soon as everyone in the camp fell asleep, Kirill sneaked out of the tent and went to the Wise Oak to gather mushrooms.\n\nIt is known that there are $n$ mushrooms growing under the Oak, each of which has magic power $v_i$. Kirill really wants to make a magical elixir of maximum strength from the mushrooms.\n\nThe strength of the elixir is equal to the product of the \\textbf{number} of mushrooms in it and the \\textbf{minimum} magic power among these mushrooms. To prepare the elixir, Kirill will sequentially pick one mushroom growing under the Oak. Kirill can gather mushrooms in any order.\n\nHowever, it's not that simple. The Wise Oak informed Kirill of a permutation of numbers $p$ from $1$ to $n$. If Kirill picks only $k$ mushrooms, then the magic power of all mushrooms with indices $p_1, p_2, \\dots, p_{k - 1}$ will become $0$. Kirill will not use mushrooms with zero magic power to prepare the elixir.\n\nYour task is to help Kirill gather mushrooms in such a way that he can brew the elixir of maximum possible strength. However, Kirill is a little scared to stay near the oak for too long, so out of all the suitable options for gathering mushrooms, he asks you to find the one with the minimum number of mushrooms.\n\nA permutation of length $n$ is an array consisting of $n$ different integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears in the array twice) and $[1,3,4]$ is also not a permutation ($n=3$, but $4$ appears in the array).",
    "tutorial": "Consider a fixed number $k$ - the amount of mushrooms in the elixir. In this case, we need to maximize the minimum of the taken numbers. We will iterate through the numbers in descending order: until we collect $k$ numbers, we iterate over the next number. If its index is greater than or equal to $k$, we take this number as the answer, otherwise we skip it. If we iterate through $k$, we get a solution in $\\mathcal{O}(n^2)$ time. How can we speed it up? Notice that at incrementing $k$, only a few numbers change: $v_{p_k}$ becomes zero, if we have already taken it, then we need to take the next one in descending order. Also, we need to take the next number in descending order, because we are incrementing $k$. After sorting, we can traverse the array in linear time. We keep a pointer $j$ to the last taken element, as well as an array $\\text{used}$ - whether the $i$-th number is taken, and an array $\\text{zero}$ - whether the $i$-th number is turned into zero. Every time we move $j$, we check that $\\text{zero}_j = \\text{false}$, and if so, we take the number and set $\\text{used}_j = \\text{true}$. Complexity: $\\mathcal{O}(n \\log n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    ll n;\n    cin >> n;\n    vector<ll> src(n);\n    vector<pair<ll, ll>> can(n);\n    for (ll i = 0; i < n; ++i) {\n        cin >> src[i];\n        can[i] = {src[i], i};\n    }\n\n    vector<ll> ord(n);\n    for (auto& item : ord) {\n        cin >> item;\n        --item;\n    }\n\n    sort(can.rbegin(), can.rend());\n    ll best = can[0].first;\n    ll take = 1;\n\n    ll cur;\n    ll P = 1;\n    vector<bool> burn(n);\n    vector<bool> used(n);\n    used[can[0].second] = true;\n    for (ll k = 0; k + 1 < n && P < n; ++k) {\n        while (P < n && burn[can[P].second]) {\n            ++P;\n        }\n\n        if (P == n) {\n            break;\n        }\n\n        used[can[P].second] = true;\n        cur = can[P].first;\n        ++P;\n\n        burn[ord[k]] = true;\n        if (used[ord[k]]) {\n            while (P < n && burn[can[P].second]) {\n                ++P;\n            }\n\n            if (P == n) {\n                break;\n            }\n\n            used[can[P].second] = true;\n            cur = can[P].first;\n            ++P;\n        }\n\n        if (best < cur * (k + 2)) {\n            take = k + 2;\n            best = cur * (k + 2);\n        }\n    }\n\n    cout << best << ' ' << take << '\\n';\n}\n\nint32_t main() {\n    ll testN;\n    cin >> testN;\n    while (testN--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1945",
    "index": "G",
    "title": "Cook and Porridge",
    "statement": "Finally, lunchtime!\n\n$n$ schoolchildren have lined up in a long queue at the cook's tent for porridge. The cook will be serving porridge for $D$ minutes. The schoolchild standing in the $i$-th position in the queue has a priority of $k_i$ and eats one portion of porridge in $s_i$ minutes.\n\n\\textbf{At the beginning} of each minute of the break, the cook serves the first schoolchild in the queue one portion of porridge, after which the schoolchild goes to eat their portion. If the $i$-th schoolchild is served a portion at the beginning of the $x$-th minute, then they will return to the queue \\textbf{at the end} of the $(x + s_i)$-th minute.\n\nWhen the $i$-th schoolchild returns to the queue, the schoolchildren at the end of the queue whose priority is \\textbf{strictly lower} than that of the $i$-th schoolchild must let them pass. Thus, they will stand in the queue behind the last schoolchild whose priority is \\textbf{not lower} than their own. That is, behind the last schoolchild $j$ with $k_j \\ge k_i$. If there is no such schoolchild in the queue, the $i$-th schoolchild will stand at the front of the queue.\n\nIf several schoolchildren return at the same time, they will return to the queue in ascending order of their $s_i$.\n\nFor example, if $n = 3$, $D = 3$, $k = [2, 3, 2]$, and $s = [2, 1, 3]$, the serving will occur as follows:\n\n- At the beginning of minute $1$, the students in the queue are $[1, 2, 3]$, and student $1$ is served porridge;\n- at the beginning of minute $2$, the students in the queue are $[2, 3]$, and student $2$ is served porridge;\n- at the beginning of minute $3$, the student in the queue is $[3]$, and student $3$ is served porridge;\n- at the end of minute $3$, student $2$ returns to the queue, and the queue becomes $[2]$;\n- at the end of minute $3$, student $1$ returns to the queue, and the queue becomes $[2, 1]$, as his priority is lower.\n\nDetermine the minimum number of minutes after the start of the break that each schoolchild will receive porridge at least once, or report that this will not happen within $D$ minutes.",
    "tutorial": "Let's divide the queue into two parts: the original queue $\\text{Q1}$ and the returning people queue $\\text{Q2}$. $\\text{Q1}$ will simply be an array with a pointer $P$ to the current person at the front. And $\\text{Q2}$ will be a priority queue. Now the problem can be formulated as follows: find out how much time it will take for $P$ to become equal to $n + 1$. Let's iterate through the time. At each moment, the cook serves porridge to either a person from $\\text{Q1}$ or from $\\text{Q2}$. How do we know which one? Let's calculate $\\text{sufMax}$ - an array of suffix maximums for $k$. Now it's clear that if $\\text{sufMax}_P \\le k(\\text{Q2}_\\text{front})$ (here $k(x)$ is the priority of student $x$), then there is still someone in $\\text{Q1}$ with a higher $k$ than the one who wants to return, so at the next moment the cook will serve porridge to a person from $\\text{Q1}$. Otherwise, the person with the maximum appetite from $\\text{Q2}$ can bypass everyone from $\\text{Q1}$ and get the porridge. To form $\\text{Q2}$, we will store an array of arrays $\\text{eat}$, where $\\text{eat}_i$ is the list of people who will return to the queue at the end of the $i$-th minute. Then we simply need to simulate this process. The answer will be the moment when $P$ becomes equal to $n + 1$. Complexity: $\\mathcal{O}(d \\log n)$",
    "code": "#include <iostream>\n#include <vector>\n#include <queue>\n\nusing namespace std;\nusing ll = long long;\n\nconst int MAX_N = 2e5;\nconst int MAX_D = 3e5;\n\nstruct Student {\n    int k;\n    int s;\n    int tin = 0;\n\n    bool operator<(const Student& other) const {\n        if (k == other.k) {\n            if (tin == other.tin) {\n                return s > other.s;\n            }\n            return tin > other.tin;\n        }\n        return k < other.k;\n    }\n};\n\nint n, D, x;\nStudent qu1[MAX_N];\nint sufMax[MAX_N];\nvector<Student> eat[MAX_D];\n\nint check() {\n    int origPos = 0;\n    priority_queue<Student> qu2;\n    for (int i = 0; i < D && origPos < n; ++i) {\n        if (qu2.empty() || qu2.top().k <= sufMax[origPos]) {\n            ll nxtTime = ll(i) + ll(x) * ll(qu1[origPos].s);\n            if (nxtTime < D) {\n                eat[nxtTime].push_back(qu1[origPos]);\n            }\n\n            ++origPos;\n            if (origPos == n) {\n                for (int tm = 0; tm < D; ++tm) {\n                    eat[tm].clear();\n                }\n\n                return i + 1;\n            }\n        } else {\n            ll nxtTime = ll(i) + ll(x) * ll(qu2.top().s);\n            if (nxtTime < D) {\n                eat[nxtTime].push_back(qu2.top());\n            }\n            qu2.pop();\n        }\n\n        for (const auto& student : eat[i]) {\n            qu2.push({student.k, student.s, i});\n        }\n    }\n\n    for (int i = 0; i < D; ++i) {\n        eat[i].clear();\n    }\n\n    return -1;\n}\n\nvoid solve() {\n    cin >> n >> D;\n    x = 1;\n    for (int i = 0; i < n; ++i) {\n        cin >> qu1[i].k >> qu1[i].s;\n    }\n\n    sufMax[n - 1] = qu1[n - 1].k;\n    for (int i = n - 2; i >= 0; --i) {\n        sufMax[i] = max(qu1[i].k, sufMax[i + 1]);\n    }\n\n    cout << check() << '\\n';\n}\n\nint32_t main() {\n    ll testN;\n    cin >> testN;\n    while (testN--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1945",
    "index": "H",
    "title": "GCD is Greater",
    "statement": "In the evenings during the hike, Kirill and Anton decided to take out an array of integers $a$ of length $n$ from their backpack and play a game with it. The rules are as follows:\n\n- Kirill chooses from $2$ to $(n-2)$ numbers and encircles them in red.\n- Anton encircles all the remaining numbers in blue.\n- Kirill calculates the \\textbf{greatest common divisor} (GCD) of all the red numbers.\n- Anton calculates the \\textbf{bitwise AND} of all the blue numbers and adds the number $x$ to the result.\n- If the GCD of all the red numbers is strictly greater than the sum of the bitwise AND of all the blue numbers and the number $x$, then Kirill wins; otherwise, Anton wins.\n\nHelp Kirill to beat Anton or tell if it's impossible.",
    "tutorial": "Let's notice that it is sufficient to take the greatest common divisor (GCD) of two numbers. Indeed, suppose we take the GCD of a larger number of numbers. Then we can move one of them to the set of AND. Then the GCD will not decrease, and the AND will not increase. Also, pre-calculate the number of ones in the given numbers and remember it. Notice that if a certain bit $y$ is equal to zero in more than two numbers, then in the AND of all these numbers bit $y$ will also be zero. For all the bits that are equal to zero in no more than two numbers, we will save these numbers. We will iterate through each of these numbers as one of the red numbers, and iterate through the second one for $n$. This will require $\\mathcal{O}(2\\cdot \\log(\\text{maxA}) \\cdot \\log(\\text{maxA}) \\cdot n)$ time. The additional logarithm comes from calculating the GCD for a pair of numbers. After this, we remove all such numbers from our list. Let $A$ be the bitwise AND of all the numbers in the initial array. Now we can consider that the GCD should be greater than $A + X$. We will iterate through the GCD from ($A + X + 1$) to maxA and check: if there is a pair of numbers in the array (not counting the discarded ones) that are divisible by it, then the answer is to color these numbers in red, and the rest in blue. Otherwise, if such a GCD is not found, the answer is \"NO\".",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int BITS = 20;\nconst int MAX_N = 4e5 + 10;\nint n;\nint x;\n\nint src[MAX_N];\n\nvoid coutYES(int fId, int sId) {\n    cout << \"YES\\n\";\n    cout << \"2 \" << src[fId] << ' ' << src[sId] << '\\n';\n    cout << n - 2 << ' ';\n    for (int i = 0; i < n; i++) {\n        if (i == fId || i == sId) {\n            continue;\n        }\n        cout << src[i] << ' ';\n    }\n    cout << '\\n';\n}\n\nvoid solve() {\n    cin >> n >> x;\n    vector<int> bitCnt[BITS];\n\n    int maxA = 1;\n    for (int i = 0; i < n; i++) {\n        cin >> src[i];\n        maxA = max(maxA, src[i] + 1);\n        for (int bit = 0; bit < BITS; bit++) {\n            if ((1 << bit) & src[i]) {\n                continue;\n            }\n\n            bitCnt[bit].push_back(i);\n        }\n    }\n\n    bool incr[n];\n    int cnt[maxA];\n    int divBy[maxA];\n    for (int i = 0; i < maxA; ++i) {\n        cnt[i] = 0;\n        divBy[i] = 0;\n    }\n\n    int pref[n];\n    int suf[n];\n    for (int i = 0; i < n; i++) {\n        incr[i] = false;\n        pref[i] = src[i];\n        if (i) {\n            pref[i] = pref[i - 1] & src[i];\n        }\n    }\n\n    for (int i = n - 2; i >= 0; i--) {\n        suf[n - 1] = src[n - 1];\n        if (i < n - 1) {\n            suf[i] = suf[i + 1] & src[i];\n        }\n    }\n\n    for (const auto& item : bitCnt) {\n        if (item.size() <= 2) {\n            for (const int& id : item) {\n                incr[id] = true;\n                int myAnd = -1;\n                for (int j = id + 1; j < n; j++) {\n                    int curAND = (1 << BITS) - 1;\n                    if (j + 1 < n) curAND &= suf[j + 1];\n                    if (id - 1 >= 0) curAND &= pref[id - 1];\n                    if (myAnd != -1) curAND &= myAnd;\n\n                    if (curAND + x < __gcd(src[id], src[j])) {\n                        coutYES(id, j);\n                        return;\n                    }\n\n                    if (myAnd == -1) {\n                        myAnd = src[j];\n                    } else {\n                        myAnd &= src[j];\n                    }\n                }\n\n                myAnd = -1;\n                for (int j = id - 1; j >= 0; j--) {\n                    int curAND = (1 << BITS) - 1;\n\n                    if (j - 1 >= 0) curAND &= pref[j - 1];\n                    if (id + 1 < n) curAND &= suf[id + 1];\n                    if (myAnd != -1) curAND &= myAnd;\n\n                    if (curAND + x < __gcd(src[id], src[j])) {\n                        coutYES(id, j);\n                        return;\n                    }\n\n                    if (myAnd == -1) {\n                        myAnd = src[j];\n                    } else {\n                        myAnd &= src[j];\n                    }\n                }\n            }\n        }\n    }\n\n    int AND = (1 << BITS) - 1;\n    for (int i = 0; i < BITS; i++) {\n        if (!bitCnt[i].empty()) {\n            AND ^= (1 << i);\n        }\n    }\n\n    for (int i = 0; i < n; i++) {\n        if (!incr[i]) {\n            ++cnt[src[i]];\n        }\n    }\n\n    for (int i = 1; i < maxA; i++) {\n        for (int j = i; j < maxA; j += i) {\n            divBy[i] += cnt[j];\n        }\n    }\n\n    for (int g = maxA - 1; g > AND + x; g--) {\n        if (divBy[g] < 2) {\n            continue;\n        }\n\n        int fId = -1;\n        int sId = -1;\n        for (int i = 0; i < n; i++) {\n            if (!incr[i]) {\n                if (src[i] % g == 0) {\n                    if (fId == -1) {\n                        fId = i;\n                    } else {\n                        sId = i;\n                    }\n                }\n            }\n        }\n        coutYES(fId, sId);\n        return;\n    }\n\n    cout << \"NO\\n\";\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int testN;\n    cin >> testN;\n    while (testN--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1946",
    "index": "A",
    "title": "Median of an Array",
    "statement": "You are given an array $a$ of $n$ integers.\n\nThe median of an array $q_1, q_2, \\ldots, q_k$ is the number $p_{\\lceil \\frac{k}{2} \\rceil}$, where $p$ is the array $q$ sorted in non-decreasing order. For example, the median of the array $[9, 5, 1, 2, 6]$ is $5$, as in the sorted array $[1, 2, 5, 6, 9]$, the number at index $\\lceil \\frac{5}{2} \\rceil = 3$ is $5$, and the median of the array $[9, 2, 8, 3]$ is $3$, as in the sorted array $[2, 3, 8, 9]$, the number at index $\\lceil \\frac{4}{2} \\rceil = 2$ is $3$.\n\nYou are allowed to choose an integer $i$ ($1 \\le i \\le n$) and increase $a_i$ by $1$ in one operation.\n\nYour task is to find the minimum number of operations required to increase the median of the array.\n\nNote that the array $a$ may not necessarily contain distinct numbers.",
    "tutorial": "The median is defined as the number at index $\\lceil \\frac{n}{2} \\rceil$ in the sorted array, so we can sort the array and work with it. So, let's start by sorting the array and finding the median in it, namely the number $a_{\\lceil \\frac{n}{2} \\rceil}$, let it be equal to $x$. In order for the median to increase, that is, to become at least $x + 1$, it is necessary that there are at least $n - \\lceil \\frac{n}{2} \\rceil + 1$ numbers in the array greater than or equal to $x + 1$. Now let's find the maximum index $t$ such that $a_t$ equals $x$. Then we know that there are currently $n - t$ numbers that are greater than or equal to $x + 1$ (all such $a_i$ that $i > t$), which means that at least $(n - \\lceil \\frac{n}{2} \\rceil + 1) - (n - t) = t - \\lceil \\frac{n}{2} \\rceil + 1$ operations will be required. I claim that this estimate is always achievable, it is enough to apply one operation to each index from $\\lceil \\frac{n}{2} \\rceil$ to $t$, because all the numbers under these indices are equal to $x$, so after applying the operations they will become equal to $x + 1$. And in the end, the number of numbers greater than or equal to $x + 1$ will become equal to $(n - t) + (t - \\lceil \\frac{n}{2} \\rceil + 1) = n - \\lceil \\frac{n}{2} \\rceil + 1$, which is what we need.",
    "code": "#include <bits/stdc++.h>\n\nusing i64 = long long;\n\nvoid solve() {\n    int n;\n    std::cin >> n;\n    std::vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        std::cin >> a[i];\n    }\n    std::sort(a.begin(), a.end());\n    int p = (n + 1) / 2 - 1;\n    int res = std::count(a.begin() + p, a.end(), a[p]);\n    std::cout << res << \"\\n\";\n}\n\nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n\n    int t = 1;\n    std::cin >> t;\n\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1946",
    "index": "B",
    "title": "Maximum Sum",
    "statement": "You have an array $a$ of $n$ integers.\n\nYou perform exactly $k$ operations on it. In one operation, you select any contiguous subarray of the array $a$ (possibly empty) and insert the sum of this subarray anywhere in the array.\n\nYour task is to find the maximum possible sum of the array after $k$ such operations.\n\nAs this number can be very large, output the answer modulo $10^9 + 7$.\n\nReminder: the remainder of a number $x$ modulo $p$ is the smallest non-negative $y$ such that there exists an integer $q$ and $x = p \\cdot q + y$.",
    "tutorial": "Let's denote $s$ as the sum of the original array and $x$ as the sum of the subarray with the maximum sum from the original array. We solve the problem when $k$ equals $1$. In this case, we need to find the subarray of the array with the maximum sum and insert this sum anywhere in the array, so the answer is $s + x$. Now, let $k$ be $2$. In this case, there is already a value where we insert the sum of the subarray with the maximum sum. Then we can increase the sum of the subarray with the maximum sum by no more than $x$ (we can increase it by $x$ simply by inserting it into the subarray with the maximum sum), and obtain the sum of the subarray with the maximum sum $2 \\cdot x$. Then insert it anywhere in the array, thus obtaining the sum of the final array equal to $s + x + 2 \\cdot x$. Similarly, for any $k$, the sum of the subarray with the maximum sum is initially $x$, then $2 \\cdot x$, then $4 \\cdot x$, $\\dots$, $2^{k - 1} \\cdot x$, then the answer is equal to $s + x + 2 \\cdot x + \\dots + 2^{k - 1} \\cdot x = s + 2^k \\cdot x - x$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\nconst int P = 1e9 + 7;\n\nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++)\n        cin >> a[i];\n    int S = 0, sum = 0;\n    int cur = 0;\n    for (int i = 0; i < n; i++) {\n        sum += a[i];\n        cur += a[i];\n        cur = max(cur, 0LL);\n        S = max(S, cur);\n    }\n    sum = (sum % P + P) % P;\n    S = S % P;\n    int t = 1;\n    for (int i = 0; i < k; i++) {\n        t = t * 2 % P;\n    }\n    int ans = (sum + S * t - S + P) % P;\n    cout << ans << '\\n';\n}\n\n\nsigned main() {\n    //cout << fixed << setprecision(20);\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int T = 1, G = 1;\n    //cin >> G;\n    cin >> T;\n    while (T--)\n        solve();\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1946",
    "index": "C",
    "title": "Tree Cutting",
    "statement": "You are given a tree with $n$ vertices.\n\nYour task is to find the maximum number $x$ such that it is possible to remove exactly $k$ edges from this tree in such a way that the size of each remaining connected component$^{\\dagger}$ is at least $x$.\n\n$^{\\dagger}$ Two vertices $v$ and $u$ are in the same connected component if there exists a sequence of numbers $t_1, t_2, \\ldots, t_k$ of arbitrary length $k$, such that $t_1 = v$, $t_k = u$, and for each $i$ from $1$ to $k - 1$, vertices $t_i$ and $t_{i+1}$ are connected by an edge.",
    "tutorial": "Let's hang the tree from an arbitrary vertex, for definiteness let's hang the tree from vertex $1$ (proof is given below). First of all, notice that if we can obtain some answer $x$, then we can also obtain the answer $x - 1$ (exactly the same way as for $x$), so we can do a binary search for $x$. To check the condition for a fixed $x$, we will use a greedy algorithm. We will find the maximum number of connected components into which we can cut our tree so that each component has at least $x$ vertices. We will start a dfs from vertex $1$, let's say we are currently at vertex $v$ and the number of vertices in its subtree is greater than or equal to $x$, then it is advantageous for us to remove the edge from vertex $v$ to its parent. If after this process there are at least $k + 1$ connected components, then the condition is satisfied for this $x$, otherwise it is not. Proof that it doesn't matter which vertex to hang the tree from: We need to prove that the greedy algorithm will obtain the same number of cuts for all roots. We will prove this in the order of depth-first search. It is also important to note that it doesn't matter in which order to run the greedy algorithm from the children. Let the initial root be $1$, and we want to prove it for its child $2$. Then let's see how the greedy algorithm will act in the first case: it will start from vertex $2$, and then from all its adjacent vertices except $1$, and remove some edges. When we run the greedy algorithm in the second case, we can reorder the vertices, and first run it from all adjacent vertices except $1$, and there will be the same removals. Then we will run the greedy algorithm from vertex $1$, it will perform the same removals as in the first case, if we made vertex $2$ the last one. So the only edge that may not coincide in these removals is $1-2$. If this edge did not participate in the removals the first time, then the size of the remaining part of vertex $2 < x$, so we cannot remove it now. If the edge $1-2$ was removed in the first variant, then the size of the component $1$ was $\\ge x$, and there were no vertices of subtree $2$ in it. Then when running the greedy algorithm from the second vertex, it will cut the edge $1-2$, because the size of this part became $\\ge x$, so the set of edges coincides.",
    "code": "#include <bits/stdc++.h>\n \nusing i64 = long long;\n \nvoid solve() {\n    int n, k;\n    std::cin >> n >> k;\n    std::vector<std::vector<int>> adj(n);\n    for (int i = 0; i < n - 1; i++) {\n        int v, u;\n        std::cin >> v >> u;\n        --v, --u;\n        adj[v].emplace_back(u);\n        adj[u].emplace_back(v);\n    }\n    auto check = [&](int x) {\n        int res = 0;\n        auto dfs = [&](auto self, int v, int f) -> int {\n            int sz = 1;\n            for (int u : adj[v]) {\n                if (u == f) {\n                    continue;\n                }\n                sz += self(self, u, v);\n            }\n            if (sz >= x && f != v) {\n                ++res, sz = 0;\n            }\n            return sz;\n        };\n        int t = dfs(dfs, 0, 0);\n        return (res > k || (t >= x && res == k) ? true : false);\n    };\n    int low = 1, high = n / (k + 1) + 1;\n    while (high - low > 1) {\n        int mid = (low + high) / 2;\n        if (check(mid)) {\n            low = mid;\n        } else {\n            high = mid;\n        }\n    }\n    std::cout << low << \"\\n\";\n}\n \nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n \n    int t = 1;\n    std::cin >> t;\n \n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1946",
    "index": "D",
    "title": "Birthday Gift",
    "statement": "Yarik's birthday is coming soon, and Mark decided to give him an array $a$ of length $n$.\n\nMark knows that Yarik loves bitwise operations very much, and he also has a favorite number $x$, so Mark wants to find the maximum number $k$ such that it is possible to select pairs of numbers [$l_1, r_1$], [$l_2, r_2$], $\\ldots$ [$l_k, r_k$], such that:\n\n- $l_1 = 1$.\n- $r_k = n$.\n- $l_i \\le r_i$ for all $i$ from $1$ to $k$.\n- $r_i + 1 = l_{i + 1}$ for all $i$ from $1$ to $k - 1$.\n- $(a_{l_1} \\oplus a_{l_1 + 1} \\oplus \\ldots \\oplus a_{r_1}) | (a_{l_2} \\oplus a_{l_2 + 1} \\oplus \\ldots \\oplus a_{r_2}) | \\ldots | (a_{l_k} \\oplus a_{l_k + 1} \\oplus \\ldots \\oplus a_{r_k}) \\le x$, where $\\oplus$ denotes the operation of bitwise XOR, and $|$ denotes the operation of bitwise OR.\n\nIf such $k$ does not exist, then output $-1$.",
    "tutorial": "For convenience, let's increase $x$ by $1$, and then iterate through the bit in which the final number is less than $x$. We will iterate from the most significant bit to the least significant bit, denoting it as $i$. The initial bit will be $30$. Let's look at all the numbers $a$ in which this bit is $1$. If there is an odd number of such numbers, then the $\\oplus$ of some subsegment will be odd, and therefore the final $|$ will also be odd. If at the same time the bit $i$ in $x$ is $0$, then the process needs to be terminated, because in all the other bits it will no longer be possible to decrease the final number. If, however, in $x$ this bit is also $1$, then we need to move on to the less significant bits, since in both numbers this bit will always be $1$. If the number of numbers with $1$ in bit $i$ is even, then in order to make this bit $0$ in the final number, each segment must contain an even number of such numbers, and since we want to maximize the number of segments, each segment must contain exactly $2$ such numbers. For this, for every two indices $l$ and $r$, such that $a_{l}$ and $a_{r}$ in bit $i$ contain $1$, and all numbers from $a_{l + 1}$ to $a_{r - 1}$ contain $0$, replace the subsegment $[l, r]$ with $a_{l} \\oplus a_{l + 1} \\oplus \\ldots \\oplus a_{r}$. After this, if there is a $1$ in $x$ in this bit, update the answer and return the array to its original state. Then move on to the less significant bits. There is also an alternative solution that also iterates through the bits from the most significant to the least significant, but instead of compressing subsegments into one number, it uses a greedy algorithm.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint const maxn = 1e5 + 5;\nint a[maxn];\n \nint solve(int n, int x) {\n    int res = 0, curr = 0;\n    for (int i = 1; i <= n; i++) {\n        curr ^= a[i];\n        if ((curr|x) == x) curr = 0, res++;\n        else {\n            if (i == n) return -1;\n        }\n    }\n    return res;\n}\n \nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, x;\n        cin >> n >> x;\n        for (int i = 1; i <= n; i++) cin >> a[i];\n        int ans = -1;\n        ans = max(ans, solve(n, x));\n        for (int b = 29; b >= 0; b--) {\n            if ((x>>b)&1) {\n                int y = (x^(1 << b));\n                for (int c = b - 1; c >= 0; c--) {\n                    if (((y>>c)&1) == 0) y ^= (1 << c);\n                }\n                ans = max(ans, solve(n, y));\n            }\n        }\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1946",
    "index": "E",
    "title": "Girl Permutation",
    "statement": "Some permutation of length $n$ is guessed.\n\nYou are given the indices of its prefix maximums and suffix maximums.\n\nRecall that a permutation of length $k$ is an array of size $k$ such that each integer from $1$ to $k$ occurs exactly once.\n\nPrefix maximums are the elements that are the maximum on the prefix ending at that element. More formally, the element $a_i$ is a prefix maximum if $a_i > a_j$ for every $j < i$.\n\nSimilarly, suffix maximums are defined, the element $a_i$ is a suffix maximum if $a_i > a_j$ for every $j > i$.\n\nYou need to output the number of different permutations that could have been guessed.\n\nAs this number can be very large, output the answer modulo $10^9 + 7$.",
    "tutorial": "First, if $p_1$ is not equal to $1$, or $s_{m_2}$ is not equal to $n$, or $p_{m_1}$ is not equal to $s_1$, then the answer is $0$ for obvious reasons. Otherwise, we know exactly where the number $n$ is located, at position $s_1$. Next, we have $\\binom{n - 1}{s_1 - 1}$ ways to divide the numbers from $1$ to $n - 1$ into two sets - the numbers that will be in the left part and the numbers that will be in the right part (the left part - all indices $< s_1$, the right part - all indices $> s_1$). We solve for the left part, and similarly for the right part. For the left part, the position of the maximum ($p_{m_1 - 1}$) is again defined, and the maximum itself is also unique in the set of numbers for the left part, so we can again divide the left part into two, with $\\binom{p_{m_1} - 2}{p_{m_1 - 1} - 1}$ ways to do so, but we can also arrange the numbers between indices $p_{m_1 - 1}$ and $p_{m_1}$ (non-inclusive) in any order, i.e., $(p_{m_1} - p_{m_1 - 1} - 1)!$ ways. Then we solve similarly for the left set (i.e., for indices less than $p_{m_1 - 1}$).",
    "code": "#include <bits/stdc++.h>\n \nusing i64 = long long;\n \ntemplate<class T>\nconstexpr T power(T a, i64 b) {\n    T res = 1;\n    for (; b; b /= 2, a *= a) {\n        if (b % 2) {\n            res *= a;\n        }\n    }\n    return res;\n}\n \ntemplate<int P>\nstruct MInt {\n    int x;\n    constexpr MInt() : x{} {}\n    constexpr MInt(i64 x) : x{norm(x % P)} {}\n    \n    constexpr int norm(int x) const {\n        if (x < 0) {\n            x += P;\n        }\n        if (x >= P) {\n            x -= P;\n        }\n        return x;\n    }\n    constexpr int val() const {\n        return x;\n    }\n    explicit constexpr operator int() const {\n        return x;\n    }\n    constexpr MInt operator-() const {\n        MInt res;\n        res.x = norm(P - x);\n        return res;\n    }\n    constexpr MInt inv() const {\n        assert(x != 0);\n        return power(*this, P - 2);\n    }\n    constexpr MInt &operator*=(MInt rhs) {\n        x = 1LL * x * rhs.x % P;\n        return *this;\n    }\n    constexpr MInt &operator+=(MInt rhs) {\n        x = norm(x + rhs.x);\n        return *this;\n    }\n    constexpr MInt &operator-=(MInt rhs) {\n        x = norm(x - rhs.x);\n        return *this;\n    }\n    constexpr MInt &operator/=(MInt rhs) {\n        return *this *= rhs.inv();\n    }\n    friend constexpr MInt operator*(MInt lhs, MInt rhs) {\n        MInt res = lhs;\n        res *= rhs;\n        return res;\n    }\n    friend constexpr MInt operator+(MInt lhs, MInt rhs) {\n        MInt res = lhs;\n        res += rhs;\n        return res;\n    }\n    friend constexpr MInt operator-(MInt lhs, MInt rhs) {\n        MInt res = lhs;\n        res -= rhs;\n        return res;\n    }\n    friend constexpr MInt operator/(MInt lhs, MInt rhs) {\n        MInt res = lhs;\n        res /= rhs;\n        return res;\n    }\n    friend constexpr std::istream &operator>>(std::istream &is, MInt &a) {\n        i64 v;\n        is >> v;\n        a = MInt(v);\n        return is;\n    }\n    friend constexpr std::ostream &operator<<(std::ostream &os, const MInt &a) {\n        return os << a.val();\n    }\n    friend constexpr bool operator==(MInt lhs, MInt rhs) {\n        return lhs.val() == rhs.val();\n    }\n    friend constexpr bool operator!=(MInt lhs, MInt rhs) {\n        return lhs.val() != rhs.val();\n    }\n};\n \nconstexpr int MOD = 1e9 + 7;\nusing Z = MInt<MOD>;\n \nnamespace comb {\n    int n = 0;\n    std::vector<Z> _fac = {1};\n    std::vector<Z> _invfac = {1};\n    std::vector<Z> _inv = {0};\n    \n    void init(int m) {\n        if (m <= n) return;\n        _fac.resize(m + 1);\n        _invfac.resize(m + 1);\n        _inv.resize(m + 1);\n        \n        for (int i = n + 1; i <= m; i++) {\n            _fac[i] = _fac[i - 1] * i;\n        }\n        _invfac[m] = _fac[m].inv();\n        for (int i = m; i > n; i--) {\n            _invfac[i - 1] = _invfac[i] * i;\n            _inv[i] = _invfac[i] * _fac[i - 1];\n        }\n        n = m;\n    }\n    \n    Z fac(int m) {\n        if (m > n) init(2 * m);\n        return _fac[m];\n    }\n    Z invfac(int m) {\n        if (m > n) init(2 * m);\n        return _invfac[m];\n    }\n    Z inv(int m) {\n        if (m > n) init(2 * m);\n        return _inv[m];\n    }\n    Z binom(int m, int k) {\n        if (m < k || k < 0) return 0;\n        return fac(m) * invfac(k) * invfac(m - k);\n    }\n} // namespace comb\n \nvoid solve() {\n    int n, m1, m2;\n    std::cin >> n >> m1 >> m2;\n    std::vector<int> p(m1), s(m2);\n    for (int i = 0; i < m1; i++) {\n        std::cin >> p[i];\n    }\n    for (int i = 0; i < m2; i++) {\n        std::cin >> s[i];\n    }\n    if (p[0] != 1 || s[0] != p[m1 - 1] || s[m2 - 1] != n) {\n        std::cout << \"0\\n\";\n        return;\n    }\n    Z res = comb::binom(n - 1, s[0] - 1);\n    for (int i = m1 - 2; i > -1; i--) {\n        res *= comb::binom(p[i + 1] - 2, p[i + 1] - p[i] - 1) * comb::fac(p[i + 1] - p[i] - 1);\n    }\n    for (int i = 1; i < m2; i++) {\n        res *= comb::binom(n - s[i - 1] - 1, s[i] - s[i - 1] - 1) * comb::fac(s[i] - s[i - 1] - 1);\n    }\n    std::cout << res << \"\\n\";\n}\n \nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n \n    #ifndef ONLINE_JUDGE\n        freopen(\"/home/q1n/coding/input.txt\", \"r\", stdin);\n        freopen(\"/home/q1n/coding/output.txt\", \"w\", stdout);\n    #else\n        // online submission\n    #endif\n \n    int t = 1;\n    std::cin >> t;\n \n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1946",
    "index": "F",
    "title": "Nobody is needed",
    "statement": "Oleg received a permutation $a$ of length $n$ as a birthday present.\n\nOleg's friend Nechipor asks Oleg $q$ questions, each question is characterized by two numbers $l$ and $r$, in response to the question Oleg must say the number of sets of indices $(t_1, t_2, \\ldots, t_k)$ of any length $k \\ge 1$ such that:\n\n- $l \\le t_i \\le r$ for each $i$ from $1$ to $k$.\n- $t_i < t_{i+1}$ for each $i$ from $1$ to $k-1$.\n- $a_{t_{i+1}}$ is divisible by $a_{t_i}$ for each $i$ from $1$ to $k-1$.\n\nHelp Oleg and answer all of Nechipor's questions.",
    "tutorial": "Let's iterate the left boundary of our queries $L$ from $n$ to $1$ and maintain the Fenwick tree $F$, where $F_i$ = the number of sought sets of indices in which $t_k = i$, and $t_1 \\ge L$. Then the answer to the query with the left boundary at $L$ will be the sum over the interval $[l_i; r_i]$ in our Fenwick tree. Now we just need to learn how to update our tree when transitioning from $L$ to $L - 1$. Some new sets of indices may have been added, starting at $L - 1$. Let's denote $pos_i$ as the position of the number $i$ in the permutation. We'll create an auxiliary array $dp$. We'll learn to calculate the dynamics $dp_i =$ the number of sought sets of indices where $t_1 = L - 1$, $t_k = i$. The base case will be $dp_{L - 1} = 1$. Suppose we know the value of $dp_{pos_x}$. Then we can update $dp_{pos_y} = dp_{pos_y} + dp_{pos_x}$, if $y$ is divisible by $x$ and $y \\ne x$, $pos_{a_i} \\le pos_x \\le pos_y$. We can calculate this dynamics straightforwardly, iterating over $x$ and $y$ $(y$ is divisible by $x$ and $x$ is divisible by $a_i)$. Notice that this will work in total for $O(n \\cdot \\log{n} \\cdot \\log{n})$ for the permutation. Now we can iterate over all numbers again that are multiples of $a_i$, update the Fenwick tree, and clear the $dp$ array to reuse it in the future.",
    "code": "#include <bits/stdc++.h>\n\nusing i64 = long long;\n\ntemplate<class Info>\nstruct Fenwick {\n    std::vector<Info> t;\n    int n;\n    \n    Fenwick(int n = 0) : n(n) {\n        t.resize(n);\n    }\n    \n    void add(int x, const Info &v) {\n        for (int i = x + 1; i <= n; i += i & -i) {\n            t[i - 1] = t[i - 1] + v;\n        }\n    }\n    \n    Info sum(int x) {\n        x++;\n        Info res = Info();\n        for (int i = x; i > 0; i -= i & -i) {\n            res = res + t[i - 1];\n        }\n        return res;\n    }\n    \n    Info rangeSum(int l, int r) {\n        Info res = sum(r) - sum(l - 1);\n        return res;\n    }\n};\n\nvoid solve() {\n    int n, q;\n    std::cin >> n >> q;\n    std::vector<int> a(n), pos(n + 1);\n    for (int i = 0; i < n; i++) {\n        std::cin >> a[i];\n    }\n    std::reverse(a.begin(), a.end());\n    for (int i = 0; i < n; i++) {\n        pos[a[i]] = i;\n    }\n    constexpr int K = 19;\n    std::vector<i64> res(q);\n    std::vector<std::vector<std::pair<int, int>>> qry(n);\n    for (int i = 0; i < q; i++) {\n        int l, r;\n        std::cin >> l >> r;\n        l--, r--;\n        std::swap(l, r);\n        l = n - l - 1;\n        r = n - r - 1;\n        qry[r].emplace_back(l, i);\n    }\n    std::vector<i64> dp(n + 1);\n    Fenwick<i64> f(n);\n    for (int r = 0; r < n; r++) {\n        int x = a[r];\n        dp[x] = 1;\n        // n * log(n) * log(n)\n        for (int y = x; y <= n; y += x) {\n            if (pos[y] > pos[x]) {\n                continue;\n            }\n            for (int z = 2 * y; z <= n; z += y) {\n                if (pos[z] > pos[y]) {\n                    continue;\n                }\n                dp[z] += dp[y];\n            }\n        }\n        // n * log(n) * log(n)\n        for (int y = x; y <= n; y += x) {\n            f.add(pos[y], dp[y]);\n            dp[y] = 0;\n        }\n        // q * log(n)\n        for (auto [l, i] : qry[r]) {\n            res[i] += f.rangeSum(l, r);\n        }\n    }\n    for (int i = 0; i < q; i++) {\n        std::cout << res[i] << \" \\n\"[i == q - 1];\n    }\n}\n\nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n\n    int t = 1;\n    std::cin >> t;\n\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "2-sat",
      "data structures",
      "dfs and similar",
      "dp"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1948",
    "index": "A",
    "title": "Special Characters",
    "statement": "You are given an integer $n$.\n\nYour task is to build a string of uppercase Latin letters. There must be exactly $n$ special characters in this string. Let's call a character special if it is equal to exactly one of its neighbors.\n\nFor example, there are $6$ special characters in the AAABAACC string (at positions: $1$, $3$, $5$, $6$, $7$ and $8$).\n\nPrint any suitable string or report that there is no such string.",
    "tutorial": "Let's look at the blocks of consecutive equal characters (such that it cannot be extended to the left or to the right): if its length is $1$, then this block has $0$ special characters; if its length is $2$, then this block has $2$ special characters; if its length is at least $3$, then this block has $2$ special characters (only the leftmost and the rightmost elements); We can see that there is no way to obtain an odd number of special characters. So the answer is NO for all odd values of $n$. And we can easily build the string for all even values of $n$. The answer for an even $n$ may look like this: AABBAABB... with $\\frac{n}{2}$ blocks of length $2$ alternating between two different letters.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    if (n % 2 == 1) {\n      cout << \"NO\" << '\\n';\n      continue;\n    }\n    cout << \"YES\" << '\\n';\n    for (int i = 0; i < n / 2; ++i)\n      for (int j = 0; j < 2; ++j)\n        cout << \"AB\"[i & 1];\n    cout << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1948",
    "index": "B",
    "title": "Array Fix",
    "statement": "You are given an integer array $a$ of length $n$.\n\nYou can perform the following operation any number of times (possibly zero): take any element of the array $a$, which is at least $10$, delete it, and instead insert the digits that element consisted of in the same position, in order they appear in that element.\n\nFor example:\n\n- if we apply this operation to the $3$-rd element of the array $[12, 3, 45, 67]$, then the array becomes $[12, 3, 4, 5, 67]$.\n- if we apply this operation to the $2$-nd element of the array $[2, 10]$, then the array becomes $[2, 1, 0]$.\n\nYour task is to determine whether it is possible to make $a$ sorted in non-descending order using the aforementioned operation \\textbf{any number of times (possibly zero)}. In other words, you have to determine if it is possible to transform the array $a$ in such a way that $a_1 \\le a_2 \\le \\dots \\le a_k$, where $k$ is the current length of the array $a$.",
    "tutorial": "The key to solving the problem is the following observation: if $a_i > a_{i + 1}$, then the $i$-th element should always be split (since it is the only way to decrease the element compared with $a_{i+1}$). This observation allows us to solve the problem greedily as follows: iterate on the array $a$ from right to left, keeping track of the list of elements we processed; if the current element is greater than the last element in our list, we have to split it (and add the digits it consists of to the list); otherwise, we don't have to split it (because it might forbid some of the next elements and force them to split as well). After that, we have to make sure we obtained a sorted array (because, for example, a number like $98$ will break the sorted order if we split it, and we didn't check that). But since we maintained the list of elements we processed, that's quite easy, because that list is the resulting array $a$ in reversed order.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (auto& x : a) cin >> x;\n    vector<int> b({a[n - 1]});\n    for (int i = n - 2; i >= 0; --i) {\n      if (a[i] > b.back()) {\n        b.push_back(a[i] % 10);\n        b.push_back(a[i] / 10);\n      } else {\n        b.push_back(a[i]);\n      }\n    }\n    cout << (is_sorted(b.rbegin(), b.rend()) ? \"YES\" : \"NO\") << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1948",
    "index": "C",
    "title": "Arrow Path",
    "statement": "There is a grid, consisting of $2$ rows and $n$ columns. The rows are numbered from $1$ to $2$ from top to bottom. The columns are numbered from $1$ to $n$ from left to right. Each cell of the grid contains an arrow pointing either to the left or to the right. No arrow points outside the grid.\n\nThere is a robot that starts in a cell $(1, 1)$. Every second, the following two actions happen one after another:\n\n- Firstly, the robot moves left, right, down or up (\\textbf{it can't try to go outside the grid, and can't skip a move});\n- then it moves along the arrow that is placed in the current cell (the cell it ends up after its move).\n\nYour task is to determine whether the robot can reach the cell $(2, n)$.",
    "tutorial": "There are multiple different approaches to this problem. We will describe a couple of them. The key observation for this problem that works for all these approaches is that, since we never skip a move and never try to move outside the grid, we can split the cells into two groups: if the sum of coordinates of the cell is even (we will call it \"even cell\"), we can end up in such a cell only after moving along the arrow (only after the second action during each second); otherwise, if the sum of coordinates of the cell is odd (we will call it \"odd cell\"), we can end up in such a cell only after making a move on our own (only after the first action during each second). Each movement leads us from one of these groups to the other group, that's why we always visit even cells after the second action and odd cells after the first action during each second. Solution 1 (graph-based). Create a graph where each cell is represented by a vertex; if this is an even cell, then the robot can choose any direction from it, so we add directed arcs from it into all adjacent cells. If this is an odd cell, then the robot will be forced to move along the arrow in that cell, so we add only one directed arc from the corresponding vertex. Then we check if the vertex representing $(2, n)$ is reachable from the vertex representing $(1, 1)$ via DFS or BFS. Solution 2 (observation-based). We can try searching for a pattern that \"blocks\" our robot, i. e. does not let it advance further. If there are two adjacent by angle odd cells, which both have arrows leading to the left, then every path of the robot will pass through at least one of them; and every time it goes through one of them, it will be forced to the left. So any pair of odd <-type cells which share an angle (i. e. are on the same diagonal) means that the answer is NO. Otherwise, we can show that the answer is yes; the proof is based on the fact that for every even cell, either the cell in the same column or the cell to the right will contain an arrow leading to the right, so we can always go forward.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<char> ok1(n / 2), ok2(n / 2);\n    for (int i = 0; i < 2; ++i) {\n      string s;\n      cin >> s;\n      for (int j = 0; j < n; ++j) if ((i + j) & 1) {\n        ok1[(i + j) / 2] |= (s[j] == '>');\n        ok2[(j - i + 1) / 2] |= (s[j] == '>');\n      }\n    }\n    bool ans = true;\n    for (int i = 0; i < n / 2; ++i) ans &= ok1[i] && ok2[i];\n    cout << (ans ? \"YES\" : \"NO\") << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1948",
    "index": "D",
    "title": "Tandem Repeats?",
    "statement": "You are given a string $s$, consisting of lowercase Latin letters and/or question marks.\n\nA tandem repeat is a string of an even length such that its first half is equal to its second half.\n\nA string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\nYour goal is to replace each question mark with some lowercase Latin letter in such a way that the length of the longest substring that is a tandem repeat is maximum possible.",
    "tutorial": "The key idea of the problem is to believe that no algorithms are required to solve the problem. Now, we can start looking for ways to iterate over all substrings so that it doesn't degenerate into $O(n^3)$. One of the ways is the following. How to check if the substring $[l; r)$ is a tandem repeat? Let $d = \\frac{r - l}{2}$. Then $s_i$ should match (either be equal or one of them should be a question mark) $s_{i + d}$ for all $i$ from $l$ to $l + d$ exclusive. If you iterate over the left border, then the right border of the substring, a lot of these checks change. However, if you iterate over the length $d$ first, then over the left border, it becomes much easier. What changes when you go from checking $[l; r)$ to checking $[l + 1; r + 1)$? One check is removed: $s_l$ matches $s_{l + d}$ is now irrelevant, since $l$ doesn't belong to the substring anymore. One check is added: $s_{l + d}$ matches $s_r$ is required, since $r$ belongs to the substring now. So, the solution can be as follows: maintain the number of successful checks for the current substring $[l; r)$. If that value is equal to $d$, then the substring is a tandem repeat, and you can update the answer with its length. Otherwise, subtract the contribution of the check ($1$ if it's successful, and $0$ otherwise) for $l$ and $l + d$, add the contribution for $l + d$ and $r$ and proceed to $[l + 1; r + 1)$. Overall complexity: $O(n^2)$ per testcase.",
    "code": "for _ in range(int(input())):\n    s = input()\n    n = len(s)\n    ans = 0\n    for d in range(1, n // 2 + 1):\n        cnt = 0\n        for i in range(n - d):\n            cnt += s[i] == s[i + d] or s[i] == '?' or s[i + d] == '?'\n            if i - d >= 0:\n                cnt -= s[i - d] == s[i] or s[i - d] == '?' or s[i] == '?'\n            if i - d >= -1 and cnt == d:\n                ans = 2 * d\n    print(ans)",
    "tags": [
      "brute force",
      "strings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1948",
    "index": "E",
    "title": "Clique Partition",
    "statement": "You are given two integers, $n$ and $k$. There is a graph on $n$ vertices, numbered from $1$ to $n$, which initially has no edges.\n\nYou have to assign each vertex an integer; let $a_i$ be the integer on the vertex $i$. All $a_i$ should be distinct integers from $1$ to $n$.\n\nAfter assigning integers, for every pair of vertices $(i, j)$, you add an edge between them if $|i - j| + |a_i - a_j| \\le k$.\n\nYour goal is to create a graph which can be partitioned into the minimum possible (for the given values of $n$ and $k$) number of cliques. Each vertex of the graph should belong to exactly one clique. Recall that a clique is a set of vertices such that every pair of vertices in it are connected with an edge.\n\nSince BledDest hasn't really brushed his programming skills up, he can't solve the problem \"given a graph, partition it into the minimum number of cliques\". So we also ask you to print the partition itself.",
    "tutorial": "There are two main steps to solve the problem: analyzing the maximum size of a clique; showing a construction that always allows us to get a clique of the maximum possible size. Firstly, the maximum size of a clique cannot exceed $k$. If there are at least $k+1$ vertices in the same clique, then at least two of them (call them $i$ and $j$) have $|i - j| \\ge k$. And since $a_i \\ne a_j$, then $|a_i - a_j| \\ge 1$. So, $|i - j| + |a_i - a_j|$ is at least $k+1$, so these two vertices won't have an edge connecting them (and cannot belong to the same clique). Secondly, let's try to find a construction that always allows us to get cliques of size $k$. To do this, try to solve the problem when $k = n$; and if $n > k$, we can split all vertices into $\\lceil \\frac{n}{k} \\rceil$ cliques as follows: for each clique, we assign a consecutive block of vertices and numbers that will be assigned to them (for example, vertices from $1$ to $k$ and numbers from $1$ to $k$ belong to the first clique, vertices from $k+1$ to $2k$ and numbers from $k+1$ to $2k$n belong to the second clique), and then use the solution for $n = k$ on each of these blocks. To obtain a solution for $n = k$, you can either try bruteforcing it locally on, say, $n \\le 10$ and analyzing the results. One of the possible constructions is as follows: let $m = \\lceil \\frac{k}{2} \\rceil$; split all vertices and numbers from $1$ to $k$ into two blocks: $[1, m]$ and $[m + 1, k]$; and then, in each block, the greater the index of the vertex, the less the integer it gets. So it looks as follows: $a_1 = m, a_2 = m-1, \\dots, a_m = 1, a_{m+1} = n, a_{m+2} = n-1, \\dots, a_n = m+1$. We can show that the \"distance\" between any two vertices in different halves is exactly $k$, and the distance between any two vertices in the same half is at most $2(m-1)$, which never exceeds $k$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n), c(n);\n    for(int i = 0; i < n; i++)\n    {\n        a[i] = i + 1;\n        c[i] = i / k + 1;\n    }\n    int q = *max_element(c.begin(), c.end());\n    for(int i = 1; i <= q; i++)\n    {\n        int l = find(c.begin(), c.end(), i) - c.begin();\n        int r = c.rend() - find(c.rbegin(), c.rend(), i);\n        int m = (l + r) / 2;\n        reverse(a.begin() + l, a.begin() + m);\n        reverse(a.begin() + m, a.begin() + r);\n    }\n    for(int i = 0; i < n; i++)\n        cout << a[i] << \" \\n\"[i == n - 1];\n    cout << q << \"\\n\";\n    for(int i = 0; i < n; i++)\n        cout << c[i] << \" \\n\"[i == n - 1];\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n        solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1948",
    "index": "F",
    "title": "Rare Coins",
    "statement": "There are $n$ bags numbered from $1$ to $n$, the $i$-th bag contains $a_i$ golden coins and $b_i$ silver coins.\n\nThe value of a gold coin is $1$. The value of a silver coin is either $0$ or $1$, determined for each silver coin independently ($0$ with probability $\\frac{1}{2}$, $1$ with probability $\\frac{1}{2}$).\n\nYou have to answer $q$ independent queries. Each query is the following:\n\n- $l$ $r$ — calculate the probability that the total value of coins in bags from $l$ to $r$ is strictly greater than the total value in all other bags.",
    "tutorial": "To calculate the probability, we will calculate the number of ways to assign values to silver coins in such a way that the total value inside the segment is greater than the total value outside. Let define $x$ as the number of silver coins with value $1$ inside the segment, $y$ as the number of silver coins with value $1$ outside, $k$ as the difference between golden coins inside and outside the segment. Then the way to assign values to the coins is considered good if condition $x - y + k > 0$ is met. We have an issue here: coins in the segment and coins outside the segment affect the inequality in different directions (that is, one of them increases the difference with a probability of $\\frac{1}{2}$, while others decrease with a probability of $\\frac{1}{2}$). It is not convenient for us. So let's fix it, we can say that the coins inside the segment have value $1$ by default, and with a probability of $\\frac{1}{2}$ are $0$. And the coins outside the segment have value of $0$ by default, and with a probability of $\\frac{1}{2}$ are $1$. Then each of them, with a probability of $\\frac{1}{2}$, reduces the difference \"total in the segment minus total outside the segment\" by $1$. Thus, we have some starting value that decreases by $1$ with a probability of $\\frac{1}{2}$ $m$ times (where $m$ is the total number of silver coins). And it is left to calculate the number of ways when the number of decreases is not big enough to break the inequality. Let $cur$ be the number of silver coins inside the segment. Then the starting value is $st = k+cur$ and the number of ways to not break the inequality is equal to $sum = \\sum\\limits_{i=0}^{st-1} \\binom{m}{i}$. And the answer to the problem is equal to $\\frac{sum}{2^m}$. Now we only need to consider how to answer queries faster than iterating from $0$ to $st$. But thanks to the fact that the value of $m$ is always the same, we can precalculate the prefix sums on these binomial coefficients.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n  return x;\n}\n\nint mul(int x, int y) {\n  return x * 1LL * y % MOD;\n}\n\nint binpow(int x, int y) {\n  int z = 1;\n  while (y) {\n    if (y & 1) z = mul(z, x);\n    x = mul(x, x);\n    y >>= 1;\n  }\n  return z;\n}\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int n, q;\n  cin >> n >> q;\n  vector<int> a(n), b(n);\n  for (auto& x : a) cin >> x;\n  for (auto& x : b) cin >> x;\n  vector<int> suma(n + 1), sumb(n + 1);\n  for (int i = 0; i < n; ++i) {\n    suma[i + 1] = suma[i] + a[i];\n    sumb[i + 1] = sumb[i] + b[i];\n  }\n  int m = sumb[n];\n  vector<int> f(m + 1), invf(m + 1);\n  f[0] = 1;\n  for (int i = 1; i <= m; ++i) f[i] = mul(f[i - 1], i);\n  invf[m] = binpow(f[m], MOD - 2);\n  for (int i = m; i > 0; --i) invf[i - 1] = mul(invf[i], i);\n  vector<int> sumc(m + 2);\n  for (int i = 0; i <= m; ++i)\n    sumc[i + 1] = add(sumc[i], mul(f[m], mul(invf[i], invf[m - i])));\n  int pw2 = binpow(binpow(2, MOD - 2), m);\n  while (q--) {\n    int l, r;\n    cin >> l >> r;\n    --l;\n    int k = 2 * (suma[r] - suma[l]) - suma[n];\n    int cur = sumb[r] - sumb[l];\n    int mx = max(0, min(k + cur, m + 1));\n    int cnt = sumc[mx];\n    cout << mul(cnt, pw2) << ' ';\n  }\n}",
    "tags": [
      "combinatorics",
      "math",
      "probabilities"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1948",
    "index": "G",
    "title": "MST with Matching",
    "statement": "You are given an undirected connected graph on $n$ vertices. Each edge of this graph has a weight; the weight of the edge connecting vertices $i$ and $j$ is $w_{i,j}$ (or $w_{i,j} = 0$ if there is no edge between $i$ and $j$). All weights are positive integers.\n\nYou are also given a positive integer $c$.\n\nYou have to build a spanning tree of this graph; i. e. choose exactly $(n-1)$ edges of this graph in such a way that every vertex can be reached from every other vertex by traversing some of the chosen edges. The cost of the spanning tree is the sum of two values:\n\n- the sum of weights of all chosen edges;\n- the maximum matching in the spanning tree (i. e. the maximum size of a set of edges such that they all belong to the chosen spanning tree, and no vertex has more than one incident edge in this set), multiplied by the given integer $c$.\n\nFind any spanning tree with the minimum cost. Since the graph is connected, there exists at least one spanning tree.",
    "tutorial": "The key to solving this problem is applying Kőnig's theorem: in a bipartite graph, the size of the maximum matching is equal to the size of the minimum vertex cover. At the first glance it shouldn't work here, because our graph is not bipartite; however, when we leave only the edges belonging to the spanning tree we chose, it becomes bipartite. So instead of adding $c$ to the cost of the tree for each edge in its maximum matching, we can add $c$ to the cost of the tree for each vertex in its minimum vertex cover. This allows us to try iterating on that vertex cover. Let's fix a set of vertices $S$, say that this is the minimum vertex cover, and the second part of the cost is equal to $c \\cdot |S|$. How to build a minimum-cost spanning tree which has $S$ as its minimum vertex cover? Well, that's not really easy to do; but instead, we can build a minimum-cost spanning tree which has $S$ as one of its vertex covers (not necessarily minimum). The fact that there might be some other vertex cover of smaller size for the tree doesn't really matter, because we can generate this tree again using a smaller set of vertices as its vertex cover. So, how do we build a minimum spanning tree such that $S$ is its vertex cover? This is actually easy: we forbid all edges such that none of their endpoints are in $S$ (because they can't be covered), and use any regular MST algorithm on all edges we have not forbidden. If we use Prim's algorithm, we get a solution in $O(2^n \\cdot n^2)$, which is fast enough to pass the time limit. Kruskal's algorithm with DSU might be a bit slower, but can also get accepted.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint n, c;\nint g[21][21];\n\nconst int INF = int(1e9);\n\nint primMST(int vertex_cover_mask)\n{\n    vector<int> d(n, INF);\n    vector<bool> used(n, false);\n    d[0] = 0;\n    int ans = 0;\n    for(int i = 0; i < n; i++)\n    {\n        int idx = -1;\n        for(int j = 0; j < n; j++)\n        {\n            if(!used[j] && d[j] < INF && (idx == -1 || d[j] < d[idx]))\n                idx = j;\n        }\n        if(idx == -1) return INF;\n        used[idx] = true;\n        ans += d[idx];\n        for(int k = 0; k < n; k++)\n        {\n            if(used[k]) \n                continue;\n            if((vertex_cover_mask & (1 << idx)) == 0 && (vertex_cover_mask & (1 << k)) == 0)\n                continue;\n            d[k] = min(d[k], g[idx][k]);\n        }\n    }\n    return ans;\n}\n\nint main()\n{\n    cin >> n >> c;\n    for(int i = 0; i < n; i++)\n    {\n        for(int j = 0; j < n; j++)\n        {\n            cin >> g[i][j];\n            if(g[i][j] == 0) g[i][j] = INF;\n        }\n    }\n    int ans = INF;\n    for(int mask = 0; mask < (1 << n); mask++)\n    {\n        int cur = primMST(mask);\n        if(cur != INF) ans = min(ans, cur + c * __builtin_popcount(mask));\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dsu",
      "graph matchings",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1949",
    "index": "A",
    "title": "Grove",
    "statement": "You want to plant trees in a square lawn of size $n \\times n$ whose corners have Cartesian coordinates $(0, 0)$, $(n, 0)$, $(0, n)$, and $(n, n)$. Trees can only be planted at locations with integer coordinates. Every tree will grow roots within a disk of radius $r$ centered at the location where the tree was planted; such disks must be fully contained in the lawn (possibly touching the boundary of the lawn) and can only intersect each other on their boundaries.\n\nFind a configuration that maximizes the number of trees.",
    "tutorial": "Let $\\delta = \\lceil r \\rceil$. Note that all trees need to be planted at least $\\delta$ away from the boundary of the lawn, so their coordinates $(x, y)$ have to satisfy $\\delta \\leq x, y \\leq n-\\delta$. For integers $0 \\leq a_\\delta, \\dots, a_{n-\\delta} \\leq n-\\delta$, denote by $f(a_\\delta, \\dots, a_{n-\\delta})$ any configuration that maximizes the number of trees while only using locations $(x, y)$ such that $x \\leq a_y$. Our task is to compute $f(n-\\delta, \\dots, n-\\delta)$. We compute values of $f$ recursively, and store all results using memoization. Let $\\bar x = \\max(a_\\delta, \\dots, a_{n-\\delta})$, and let $\\bar y$ be such that $a_{\\bar y} = \\bar x$. Note that, if $\\bar x < \\delta$, then $f(a_\\delta, \\dots, a_{n-\\delta})=\\emptyset$ because any tree would be too close to the left boundary of the lawn. Assuming that $\\bar x \\geq \\delta$, we try to plant or not plant a tree at the location $(\\bar x, \\bar y)$. If we do not plant a tree at $(\\bar x, \\bar y)$, an optimal configuration is given by $f(a_\\delta', \\dots, a_{n-\\delta}')$, where $a_y' = a_y$ if $y \\neq \\bar y$ and $a_{\\bar y}' = a_{\\bar y} - 1$. If we plant a tree at $(\\bar x, \\bar y)$, an optimal configuration is given by $f(a_\\delta', \\dots, a_{n-\\delta}') \\cup \\{ (\\bar x, \\bar y) \\}$, where $a_y'$ is the largest integer $\\leq a_y$ such that locations $(a_y', y)$ and $(\\bar x, \\bar y)$ are at distance $\\geq 2r$. The number of recursive calls increases as $r$ decreases. For this reason, it can be beneficial to solve by hand the cases where $r$ is small. For instance, if $r\\leq 1/2$, then we can plant trees at all integer coordinates in the interior of the lawn; if $1/2 < r < \\sqrt{2}/2$, we can plant trees at all integer coordinates $(x, y)$ in the interior of the lawn such that $x+y$ is even. If the implementation of the above algorithm is not fast enough, it is also possible to pre-compute all optimal configurations offline. Indeed, for every $n$, there is a finite number of intervals $(p,q] \\subseteq \\mathbb R$ such that the valid configurations of trees are the same for all $r\\in (p, q]$. The boundaries of these intervals are of the form $\\sqrt{a^2+b^2}/2$ for integers $0\\leq a \\leq b \\leq n$. For instance, the first two intervals are always $(0,1/2]$ and $(1/2, \\sqrt 2/2]$, which we have already encountered above. Finally, it is also possible to solve this problem using a generic max-clique algorithm, especially in combination with the above idea to pre-compute optimal configurations offline.",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "geometry",
      "probabilities"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1949",
    "index": "B",
    "title": "Charming Meals",
    "statement": "The Czech cuisine features $n$ appetizers and $n$ main dishes. The $i$-th appetizer has spiciness $a_i$, and the $i$-th main dish has spiciness $b_i$.\n\nA typical Czech meal consists of exactly one appetizer and one main dish. You want to pair up the $n$ appetizers and $n$ main dishes into $n$ meals with each appetizer and each main dish being included in exactly one meal.\n\nYour meals shall surprise the diners, so you want the spiciness levels of the two parts of the same meal to be as different as possible. The charm of a meal is the difference (in absolute value) between the spiciness of the appetizer and the spiciness of the main dish. So, a meal consisting of an appetizer with spiciness $x$ and a main dish with spiciness $y$ has charm equal to $|x-y|$.\n\nYou want to maximize the minimum charm of the resulting $n$ meals. What is the largest possible value of the minimum charm that you can achieve?",
    "tutorial": "Let's sort spicinesses, assume $a_1 \\leq a_2 \\leq \\ldots \\leq a_n$, $b_1 \\leq b_2 \\leq \\ldots \\leq b_n$. Lemma: Let $c, d$ be some nondecreasing arrays of length $n$. If there exists some permutation $\\sigma(1), \\sigma(2), \\ldots, \\sigma(n)$, such that $c_i \\leq d_{\\sigma(i)}$ for all $i$, then $c_i \\leq d_i$ for all $i$. Proof: for each $i$, there can be at most $i-1$ $d$s smaller than $c_i$: $d_{p_1}, d_{p_2}, \\ldots, d_{p_{i-1}}$, as for any $j\\geq i$ we have $d_{p_j} \\geq c_j \\geq c_i$. Consider some optimal pairing, assume we paired $a_i$ with $b_{\\sigma(i)}$, and got a minimum charm of $k$. Let's call pairs with $a_i + k \\leq b_{\\sigma(i)}$ small, and pairs with $a_i \\geq b_{\\sigma(i)} + k$ large. Consider small pairs, assume there are $t$ of them. Note that, by the lemma, we can assume that $a_i$s and $b_{\\sigma(i)}$s in these pairs are nondecreasing. Similarly, they are nondecreasing in large pairs. But then we can just pair smallest $t$ $a_i$s with largest $t$ $b_i$s, and largest $n-t$ $a_i$s with smallest $n-t$ $b_i$s, and we will still have a charm of at least $k$. More formally: For $1 \\leq i \\leq t$, pair $a_i$ with $b_{i + (n-t)}$; For $t+1 \\leq i \\leq n$, pair the $a_i$ with $b_{i - t}$. So, it's enough to check such a pairing for each possible $0 \\leq 1 \\leq t \\leq n$, and to pick the best one! Total runtime is $O(n^2)$.",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1949",
    "index": "C",
    "title": "Annual Ants' Gathering",
    "statement": "Deep within a forest lies an ancient tree, home to $n$ ants living in $n$ tiny houses, indexed from $1$ to $n$, connected by the branches of the tree.\n\nOnce a year, all the ants need to gather to watch the EUC. For this, all ants move along the $n-1$ branches of the tree they live on to meet at the home of one ant.\n\nHowever, this year the ants could not agree on where to meet and need your help to gather up. You can tell all the ants currently at house $u$ to move to house $v$ if there is a branch directly connecting those two houses. However, the ants ignore your command if there are fewer ants gathered in house $v$ than in house $u$, i.e., if it would be easier for the ants from house $v$ to move. This even holds true if no ant at all is currently in house $v$. You can give this kind of commands as many times as you want.\n\nIs it possible for you to gather all the ants in a single house?",
    "tutorial": "First Solution Since ants can not move to an empty house the region of non-empty homes always needs to stay connected. Therefore, only ants on a leaf of the tree (of non-empty homes) can ever move and they can only move in one direction. Further, notice that if the smallest group of ants on a leaf can not move the solution is impossible (all other leaf groups are larger and can therefore also never be merged into the parent group of the smallest group). We can simply simulate this process. Second Solution Notice that the centroids of the tree are the only homes where all ants can gather up. For a fixed root we can greedily simulate the process with a DFS for each centroid.",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1949",
    "index": "D",
    "title": "Funny or Scary?",
    "statement": "You are designing a new video game. It has $n$ scenarios, which the player may play in any order, but each scenario must be played exactly once. When a player switches from a scenario to another scenario, the game shows a specially crafted transition video to make it all feel part of one big story. This video is specific to a pair of scenarios, but not to their order, in other words, the video playing when switching from scenario $a$ to scenario $b$ is the same as the video playing when switching from scenario $b$ to scenario $a$. Therefore, you need to create $\\frac{n(n-1)}{2}$ different transition videos, one for each possible pair of different scenarios.\n\nEach transition video can be either \\underline{funny} or \\underline{scary}. It is boring to see too many funny videos or too many scary videos in a row. Therefore, your goal is to create the videos in such a way that no matter in which order does the player approach the scenarios, they will never see more than $\\lceil \\frac{3n}{4} \\rceil$ transition videos of the same type in a row.\n\nYou have already come up with ideas for at most $\\lfloor \\frac{n}{2} \\rfloor$ of the transition videos, and therefore already know if those will be funny or scary. Now you need to choose funny or scary for all other transition videos in such a way that the above requirement is satisfied.",
    "tutorial": "In graph terms, this problem can be formulated as follows: you are given a complete undirected graph on $n$ vertices. Some of the edges of the graph are already colored with two colors. You need to color all remaining edges with two colors in such a way that the graph does not have long monochromatic simple paths. First of all, what happens when no edges are already colored? It turns out this exact question is well-studied in mathematics, and the definitive answer was given 57 years ago in the following paper: L. Gerencsér, A. Gyárfás, On Ramsey-type problems, Ann. Univ. Sci. Budapest Eötvös Sect. Math. 10 (1967), pp. 167-170. They prove that for any such graph on $n$ vertices there always exists a monochromatic path with at least $\\lfloor \\frac{2n}{3} \\rfloor$ edges, and provide an example of such a graph where the longest monochromatic path has exactly $\\lfloor \\frac{2n}{3} \\rfloor$ edges. What does their example look like? The key idea is to use a bipartite graph with unbalanced parts. More specifically, we split all vertices into two groups, the first one of size roughly $\\frac{n}3$, and the second one of size roughly $\\frac{2n}3$. We color the edges between the two groups red, and the edges within each group blue. Now each blue path will have to stay within one of the groups, and therefore will not be longer than $\\frac{2n}3$. The red edges form a bipartite graph, so each red path will have to alternate groups, which means that it will have to go to the smaller group every second step, and since the smaller group has only $\\frac{n}3$ vertices, the path also cannot be longer than $\\frac{2n}3$. Sadly, not everyone will have read this seminal paper from 1967, so how can one come up with this construction during the contest? Since every edge in the complete graph will have one of the two colors, at least one of the colors will be used by a lot of edges. So we need to come up with examples of graphs with lots of edges, but no long paths. Disconnected graphs are a natural way to achieve this, and then we can consider what edges the complement of a disconnected graph must have, and arrive at the above construction. One other thing one can do when stuck is experimentation: try generating random complete graphs colored with two colors until you find some examples with no long monochromatic paths, for example where there is no monochromatic path with $n-1$ edges, and then try to generalize their structure. In fact, the answer to the second sample was generated in exactly this fashion: we repeatedly tried to color each edge randomly and independenty until we got a graph with 12 vertices and no monochromatic path with 10 edges. It actually took a few hours to find just one such graph. Studying this answer could be another way to discover the above construction, as the funny edges do form an almost-bipartite structure with nodes 5 and 11 in one part, and the rest in the other part (for example row 5 of the matrix is $\\texttt{FFFF.FFFFFSF}$). We still need to deal with edges that are already colored, but we also still have some reserves: our paths do not exceed $\\lfloor \\frac{2n}{3} \\rfloor$, while this problem allows paths up to $\\lceil \\frac{3n}{4} \\rceil$. How bad is a wrongly colored edge to the above construction? If an edge that is supposed to be red is actually blue, it is very bad: now the two blue groups are connected, and therefore it is easy to create a blue path through all vertices. However, if an edge that is supposed to be blue is actually red, it is not so bad: even when this edge is used in a red path, all \"originally\" red edges still have to have one of their endpoints in the smaller group, and therefore the number of originally red edges in a red path still does not exceed two times the size of the smaller group, so changing one blue edge to red increases the boundary on the red path length by at most 1. We have the freedom to choose which vertex belongs to which group, so we need to use this freedom to make sure that all edges that are already blue connect vertices within one group, as even one incorrectly blue edge is bad. This means that we need to find the connected components using the preexisting blue edges, and then take some of those components to the bigger group and the rest to the smaller group. The edges that are already colored red can each increase the boundary on the red path length by 1. If all $\\lfloor \\frac{n}{2} \\rfloor$ already colored edges are red, this would increase the path length by $\\lfloor \\frac{n}{2} \\rfloor$, which is a lot. However, we also have the freedom to decide which one out of funny and scary corresponds to red. Let us choose one that has fewer edges, and therefore the number of already colored red edges will not exceed $\\lfloor \\frac{n}{4} \\rfloor$. Because the length of the red path can be increased by $\\lfloor \\frac{n}{4} \\rfloor$ through the already colored edges, we need to make the smaller group even smaller: since the red path must not exceed $\\lceil \\frac{3n}{4} \\rceil$, we can have at most $\\lfloor\\frac{\\lceil \\frac{3n}{4} \\rceil - \\lfloor \\frac{n}{4} \\rfloor}{2}\\rfloor$ vertices in the smaller group, which is roughly $\\frac{n}{4}$, and more precisely it is $\\ge \\lfloor \\frac{n}{4} \\rfloor$. If the smaller group has $\\lfloor \\frac{n}{4} \\rfloor$ vertices, the bigger group has $n-\\lfloor \\frac{n}{4} \\rfloor=\\lceil \\frac{3n}{4} \\rceil$ vertices, which means that blue paths have at most $\\lceil \\frac{3n}{4} \\rceil-1$ edges. Notice how all pieces of the puzzle come together now: this is good enough for this problem, but only barely, by 1 edge. So we can allow the smaller group to have either $\\lfloor \\frac{n}{4} \\rfloor$ or $\\lfloor \\frac{n}{4} \\rfloor - 1$ vertices. The only remaining question is: since we add vertices to groups not one by one, but an entire preexisting blue edge component at a time, can we actually achieve the required size of the smaller group? It turns out that we can, using the following simple approach: sort the components in increasing order of size, and take them in this order to the smaller group until the size of the smaller group is $\\lfloor \\frac{n}{4} \\rfloor - 1$ or $\\lfloor \\frac{n}{4} \\rfloor$. The only way this could fail is if we jump from at most $\\lfloor \\frac{n}{4} \\rfloor - 2$ to at least $\\lfloor \\frac{n}{4} \\rfloor + 1$, meaning that the component we have added has at least 3 vertices. But since we add components in increasing order of size, it means that the remaining components also all have at least 3 vertices, which means that components with at least 3 vertices cover at least $n-(\\lfloor \\frac{n}{4} \\rfloor - 2)=\\lceil \\frac{3n}{4} \\rceil+2$ vertices of the graph. Since we need 2 edges for a component with 3 vertices, and with bigger components we still need at least $\\frac{2k}{3}$ edges for a component with $k$ vertices, we need at least $\\frac{2(\\lceil \\frac{3n}{4} \\rceil+2)}{3}$ edges to get into this situation, and $\\frac{2(\\lceil \\frac{3n}{4} \\rceil+2)}{3} \\ge \\frac{\\frac{3n}{2}+4}{3} > \\frac{\\frac{3n}{2}}{3} = \\frac{n}{2}$. So we need more than $\\frac{n}{2}$ edges to get into this situation, which is impossible under the constraints of the problem, therefore the greedy approach of taking already blue components in increasing order of size always works. The solution is complete now, and it runs in time linear in the input size, in other words $O(n^2)$. Why does the problem have the very low limit of $n \\le 24$ in this case? The reason is that we also need to implement the checker that will read your output and check if there are no long monochromatic paths. For that we use a relatively standard dynamic programming approach that runs in $O(n^2\\cdot 2^n)$, sped up using bitmasks to do only $O(n\\cdot 2^n)$ operations with integers. It takes a few seconds for $n=24$ so we could not go much higher. We have explored using various heuristic approaches to find the longest monochromatic paths for larger values of $n$, but it turns out that even though those heuristic approaches work quite well on random graphs, they actually cannot find the longest path reliably in the type of graph output by the solution above, namely an unbalanced bipartite graph with a few additional edges. The low value of $n$ allows to simplify the implementation of the above solution in the following manner: we can skip finding connected components of preexisting blue edges, instead just iterating over all $2^n$ subsets of vertices as candidates for the smaller group, and then checking if the size of the smaller group is appropriate and that there are no preexisting blue edges going from the smaller group to its complement.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1949",
    "index": "E",
    "title": "Damage per Second",
    "statement": "You just created a new character in your favourite role-playing game and now have to decide how to skill him.\n\nThe two skill attributes to be chosen are: \\underline{damage per hit} and \\underline{hits per second}. Damage per hit is the amount of damage you deal with a single hit, while hits per second is the number of hits you can make in one second. Initially, both skill attributes are set at $0$. You have $k$ skill points to distribute as you want; in other words, you can choose the values of the two skills so that they are positive integers with sum at most $k$.\n\nThe tutorial of the game (the boring part you want to finish as soon as possible) consists of $n$ monsters to be killed one after the other. The $i$-th monster has $h_i$ health points, i.e., it dies after you have inflicted at least $h_i$ damage.\n\nHow can you assign the two skill attributes to minimize the time necessary to kill all the $n$ monsters?",
    "tutorial": "Once the sugar-coating is removed, the problem boils down to: Let $f(x) = \\sum_{i=1}^n \\left\\lceil\\frac{h_i}{x}\\right\\rceil$, and $g(x) = \\frac{f(x)}{k-x}$. Find the minimum of $g(x)$. Sort the values so that $h_1\\geq h_2\\geq\\dots\\geq h_n$. Define $H:=h_1+\\dots+h_n$. From now on, we will assume that $k$ is even, so that $x=\\frac k2$ is a valid choice (the case $k$ odd is absolutely equivalent, just more annoying to write down). Let us begin with two simple observations. Observation 1. What are the \"most interesting\" values of $x$? If we ignore the ceiling in the definition of $g$, we get $g(x) \\ge \\frac{H}{x(k-x)}$ whose minimum is achieved by $x=\\frac k2$. Unless the values $h_1, \\dots, h_n$ are well-crafted, we expect the minimum of $g$ to be achieved for an $x$ very close to $\\frac k2$. Observation 2. Speeding up the computation of $g$. Let us describe a strategy to compute $g(x)$. Iterate from $i=1$ to $n$ until $i < \\frac{h_i}{x}\\log n$. Say that such condition is satisfied for $1\\le i\\le q(x)$ and fails for $q+1$ (for notational clarity we will omit the dependence of $q$ on $x$). We compute the first part of $g(x)$, that is $\\sum_{i=1}^q \\lceil \\frac{h_i}x\\rceil$, naively in $O(q)$. For $q+1\\le i \\le n$ the quantity $\\lceil \\frac{h_i}x\\rceil$ takes at most $\\frac{h_{q+1}}x$ different values. Therefore the second part of $g(x)$, that is $\\sum_{i=q+1}^n \\lceil \\frac{h_i}x\\rceil$, can be computed in $O(\\frac{h_{q+1}}{x}\\log n) = O(q)$ by using binary search. So, we have described a way to compute $g(x)$ in $O(q(x))$ where $q$ satisfies $h_q \\ge \\frac{qx}{\\log n}$. Description of the algorithm. These two observations suggest the following algorithm. Maintain the running minimum $m$ of $g(x)$, initializing it as $m=g(\\frac k2)$. Iterate over all $x$, starting from those closest to $\\frac k2$ and moving further away. For each $x$, if $\\frac H{x(k-x)}\\ge m$ then skip this choice of $x$ (as it cannot be a minimizer in view of the first observation). Otherwise compute $g(x)$ in $O(q(x))$ as described in observation 2 and update $m$ accordingly. This algorithm produces the correct answer, but is it provably fast enough? Unexpectedly yes! We will see that this algorithm has the remarkable running time $O(\\sqrt{n\\log n}k)$. Running time analysis. Let us begin by making one further remark about the second observation. By definition of $q(x)$, we have $H \\ge h_1 + \\cdots + h_q \\ge qh_q \\ge \\frac{q^2x}{\\log n} \\implies q\\le \\sqrt{\\frac{H\\log n}{x}}.$ Let us now discuss the first observation. For any $1\\le x\\le k-1$, $\\frac{H}{x(k-x)}\\leq g(x)\\leq \\frac{H}{x(k-x)} + \\frac{n}{k-x} .$ We have $g(\\frac k2)\\le \\frac{4H}{k^2} + \\frac{2n}{k}$ and $\\frac{H}{x(k-x)}\\leq g(x)$. Therefore, if $\\frac{4H}{k^2} + \\frac{2n}{k} < \\frac{H}{x(k-x)} \\iff \\frac{k^2}4 - \\big(x-\\frac k2\\big)^2 = x(k-x) < \\frac{H}{\\frac{4H}{k^2} + \\frac{2n}{k}} \\iff \\big(x-\\frac k2\\big)^2 > \\frac{k^2}4 - \\frac{H}{\\frac{4H}{k^2} + \\frac{2n}{k}} = \\frac{nk^3}{8H+4nk}$ $\\Big|x - \\frac k2\\Big| \\le \\sqrt{\\frac{nk^3}{8H}} .$ Conclusion. Now we have all the tools and we can conclude by considering two cases (which, morally, correspond to $H$ large and $H$ small). If $\\sqrt{\\frac{nk^3}{8H}} < \\frac k4$, then the interesting values of $x$ are comparable to $k$. Thus $g(x)$ can be computed in $O(\\sqrt{\\frac{H\\log n}{k}})$ and we shall do such computation $2\\sqrt{\\frac{nk^3}{8H}}$ times. So the overall complexity is $O(\\sqrt{n\\log n}k)$. On the other hand, if $\\sqrt{\\frac{nk^3}{8H}} \\ge \\frac k4$ (which implies $H\\le 2nk$) then we use only the second observation to bound the complexity. Let us assume that we care only about values of $x$ of magnitude comparable to $k$, the other cases are easy to handle. Then, the computation of $g(x)$ requires $O(q\\log n)$. To compute $g(x)$ for all $1\\le x\\le k$, we need $O\\Big(\\sum_{x=1}^k \\sqrt{\\frac{H\\log n}{x}}\\Big) = \\sqrt{nk\\log n}O\\Big(\\sum_{x=1}^k x^{-1/2}\\Big) = O(\\sqrt{n\\log n}k).$",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1949",
    "index": "F",
    "title": "Dating",
    "statement": "You are the developer of a dating app which ignores gender completely. The app has $n$ users, indexed from $1$ to $n$. Each user's profile features a list of the activities they enjoy doing. There are $m$ possible activities, indexed from $1$ to $m$.\n\nA match between two users is good if they share at least one activity and, at the same time, both of them like at least one activity that the other user does not like.\n\nFind a good match if it exists.",
    "tutorial": "After formalizing the statement, we get the following: Given $n$ sets $S_1, S_2, \\ldots, S_n$ of activities, find a pair $(a, b)$ such that all three sets $S_a \\setminus S_b, S_b \\setminus S_a, S_a \\cap S_b$ are non-empty. In essence, this means that for a pair $(a, b)$ to not be good, it must suffice that $S_a$ and $S_b$ are either disjoint or one included in the other. Consequently, it means that, if there are no such good pairs, then the sets must induce a tree structure! In this structure, some vertex $u$ is an ancestor of vertex $v$ if and only if $S_v \\subseteq S_u$. The solution now can be summarized by the following idea: try to construct the tree (assuming there are no good pairs), and check for errors along the process (this will, in fact, expose a good pair). There are multiple ways of achieving that, both top-down and bottom-up (and they are more or less equivalent). We will describe a solution based on a top-down approach. Top down approach. Let's start by sort the activity sets in decreasing order of lengths. For all activity sets $S_i$ in this order, we will create a parent-child relationship $j = p(i)$ with the last processed index $j$ that contains some activity (or $-1$, if there is no such index). The activity based on which we choose $j$ is not relevant, for reasons that will be apparent as follows. After finding such $j$ (or deciding that $j = -1$), we have some cases to consider: If $j \\neq -1$ and $S_i \\not\\subseteq S_j$, then $(i, j)$ is a good pair, as $S_j$ cannot possibly include $S_i$ due to the length of $S_j$ being at least as much as $S_i$. If some activity $x \\in S_i$ is also in some other set $S_k$ where $p(k) = p(i)$, then $(i, k)$ is a good pair. Otherwise, the activity sets still form a tree, therefore no good pairs exist (yet). Complexity is $\\mathcal{O}(k \\log k)$ or $\\mathcal{O}(k)$, where $k$ is the total number of activities, depending on whether one uses ordered sets or hash maps. It is possible to implement this solution in $\\mathcal{O}(k)$ using just arrays, but this is not required. Alternative approach. One may solve this problem without leveraging the tree structure of the activity sets. It stems from the observation that any good pair $(a, b)$ must have a common element $x$. Let's fix all such $x$, and sort the sets having $x$ as an element in the order of length. Then, similarly to the first solution, one may prove that it is sufficient that a set with a smaller length has an element not present in some set with a larger length. We can solve this by simply keeping an array which keeps track of existing elements present in the sets, and iterating from right to left. This approach does not quite work yet, as it has quadratic complexity; however, by considering the sets with large size (i.e., larger than $\\sqrt{k}$) separately than the elements with a small size (i.e. smaller than $\\sqrt{k}$), then one may achieve $\\mathcal{O}(k \\sqrt{k})$ complexity using this approach.",
    "tags": [
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1949",
    "index": "G",
    "title": "Scooter",
    "statement": "The Czech Technical University campus consists of $n$ buildings, indexed from $1$ to $n$. In each building, there can be a math class scheduled, or a computer science class, or neither (but not both). Additionally, in each building, there is at most one professor, and each professor is either an expert in mathematics or in computer science.\n\nAs an intern at University Express Inc., your job is to quickly transport the professors to their classes. For this, you have been granted a brand new two-person scooter, able to accommodate yourself, plus at most one passenger.\n\nInitially, you are the only person on the scooter. When you arrive at a building, you may drop off or pick up professors to/from that building. However, in order to improve the efficiency of your task, you are allowed to drive to each of the $n$ buildings \\textbf{at most once}, in the order of your choice (you can also decide where to start the itinerary).\n\nAfter the end of your itinerary, in each building where a math class is scheduled, there must be a professor expert in math, and in each building where a computer science class is scheduled, there must be a professor expert in computer science.\n\nDevise an itinerary that makes it possible to teach all classes.",
    "tutorial": "First and foremost, let's notice that we can ignore professors that are already in a proper building, as well as empty buildings (in essence, all positions $i$ such that $c_i = p_i$). More so, if there are no positions $i$ such that $c_i \\neq p_i$ then we can simply answer $\\texttt{YES}$ without doing any operations. From this point on, we will assume that for all $i$, we have $c_i \\neq p_i$. General idea. Intuitively, we would want to iteratively pick up the professor from some building and drive them to a building where a corresponding class is held. However, we must make sure to not visit the same place twice. Multiple greedy solutions might solve this, but we also have to take into account implementation effort and the number of edge cases to consider. In this sense, we advise the reader to not rush into writing an implementation just yet, and instead try to simplify the solution as much as possible on paper. An easier subproblem. The issue with the problem currently is that there is much room for making choices and, consequently, much room for making an erroneous decision. Let's consider the easier subproblem where there are exactly as many professors of a given class types as there are classes. Even though one might say that this makes the problem tighter, it actually paradoxically makes it easier! This is mainly because, as tight as it is, there is not much room for bad decisions. A key observation is that this subproblem (and, as it turns out, the original problem as well) is $\\textbf{impossible}$ if there are no buildings where no class is being held, as there is simply no way of returning to the starting position to drop off the corresponding professor (note, again, that we are ignoring positions $i$ with $c_i = p_i$). Therefore, a greedy strategy that works for this subproblem is simply repeatedly choosing a professor from a building where no class is being held and driving them to one of the buildings where their class is being held. If one prioritizes buildings where there are professors before those where there are no professors, the key condition never becomes unsatisfied, thus the problem is solved. Solving the original problem. Going back, let's solve the original problem. We can do that by simply reducing it to the easier version, by removing \"excess\" professors from some of the buildings. At the same time, note that we have to make sure the key observation above remains valid throughout the removal process. One easy and correct way of doing that is, yet again, the greedy approach of simply prioritizing removing professors from buildings where there are classes to buldings with no classes. Final complexity of the solution is $\\mathcal{O}(n)$.",
    "tags": [
      "graphs",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1949",
    "index": "H",
    "title": "Division Avoidance",
    "statement": "A newly discovered organism can be represented as a set of cells on an infinite grid. There is a coordinate system on the grid such that each cell has two integer coordinates $x$ and $y$. A cell with coordinates $x=a$ and $y=b$ will be denoted as $(a, b)$.\n\nInitially, the organism consists of a single cell $(0, 0)$. Then zero or more divisions can happen. In one division, a cell $(a, b)$ is removed and replaced by two cells $(a+1, b)$ and $(a, b+1)$.\n\nFor example, after the first division, the organism always consists of two cells $(1, 0)$ and $(0, 1)$, and after the second division, it is either the three cells $(2, 0)$, $(1, 1)$ and $(0, 1)$, or the three cells $(1, 0)$, $(1, 1)$ and $(0, 2)$.\n\n\\textbf{A division of a cell $(a, b)$ can only happen if the cells $(a+1, b)$ and $(a, b+1)$ are not yet part of the organism.} For example, the cell $(1, 0)$ cannot divide if the organism currently consists of the three cells $(1, 0)$, $(1, 1)$ and $(0, 2)$, since the cell $(1, 1)$ that would be one of the results of this division is already part of the organism.\n\nYou are given a set of forbidden cells ${(c_i, d_i)}$. Is it possible for the organism to contain none of those cells after zero or more divisions?",
    "tutorial": "Looking at the solution for the sample, the most difficulty seems to come from the condition in bold: A division of a cell $(a, b)$ can only happen if the cells $(a+1, b)$ and $(a, b+1)$ are not yet part of the organism. It forces us to clean up space, potentially recursively, before a division that we want to happen can actually happen. What happens if we remove this condition, instead allowing to have multiple copies of a cell with the same coordinates in the organism? Then of course it is possible to avoid any finite set of forbidden cells, so this version of the problem is not very useful. However, consider the following modification instead: we allow to have multiple copies of a cell with the same coordinates temporarily, but the final state of the organism must have at most one copy of any cell, and of course zero copies of the forbidden cells. It turns out that this modification is equivalent to the original problem! To see why, consider a sequence of operations that starts from $(0,0)$ and ends in a valid state as described above, but has multiple copies of some cells in its intermediate states. We claim that it is possible to reoder its sequence of operations in such a way that all operations stay valid, but we never have multiple copies of the same cell. Notice that reodering the operations does not change the end state, because each operation can be seen as subtracting 1 from the number of occurrences of the cell $(a,b)$ and adding 1 to the numbers of occurrences of the cells $(a+1,b)$ and $(a,b+1)$, and such subtractions and additions clearly commute. To avoid getting multiple copies of the same cell, we can repeatedly do the following to produce a reordering: from all operations that are yet to be done in the reference sequence of operations, we choose the operation $(a,b)$ such that $(a,b)$ is part of the organism and $a+b$ is maximized. Maximizing $a+b$ guarantees that we are not going to have two copies of the same cell: when we decide to divide $(a,b)$, we cannot have $(a+1,b)$ in the organism, as otherwise $(a+1,b)$ would also be one of the operations yet to be done (since the final state has at most one cell at $(a+1,b)$), so we should have chosen $(a+1,b)$ as the opeation to do over $(a,b)$ since $a+1+b>a+b$, which is a contradiction. Now we know that we can focus on what operations to do, and no longer care about the order in which we do them. It means that we can choose the order that suits us best, and as long as we do only necessary operations, we will always arrive at exactly the same result. It is natural to go by diagonals: first consider all operations with $a+b=0$, then all operations with $a+b=1$, then all operations with $a+b=2$, and so on. The operations with $a+b=z$ only create new cells with $a+b=z+1$, so those operations are independent within each value of $z$, and we never have to return to smaller values of $z$. This leads to the following solution: we go in increasing order of $z$, and before processing a given value of $z$ we know how many copies of each cell with $a+b=z$ we have, as an array $d_{z,a}$. Now for each forbidden cell $(a,b)$ with $a+b=z$ we have to apply division to it $d_{z,a}$ times, which means that we have to add $d_{z,a}$ to $d_{z+1,a}$ and to $d_{z+1,a+1}$. Similarly, for each non-forbidden cell we have to apply division to it $\\max(0,d_{z,a}-1)$ times. We continue while the array $d_z$ has at least one non-zero value. If this process terminates, the answer is $\\texttt{YES}$. If it runs infinitely, the answer is $\\texttt{NO}$. For example, in the first sample case we get the following arrays: $d_0 = (1)$ $d_1 = (1, 1)$ $d_2 = (1, 2, 1)$ $d_3 = (0, 2, 2, 0)$ $d_4 = (0, 1, 2, 1, 0)$ $d_5 = (0, 0, 1, 1, 0, 0)$ $d_6 = (0, 0, 0, 0, 0, 0, 0)$ However, this solution is still not practical: how do we check if the process runs infinitely? Looking at a few examples can help spot a pattern: if we ever get a 3, then the process never stops. Having identified this pattern, it is relatively easy to prove. Since we always add the same number to two adjacent elements of $d_{z+1}$, getting a 3 in it means that one of its adjacent numbers will be at least 2. And then, even if there are no forbidden cells at all anymore, $3, 2$ becomes $2, 3, 1$ on the next diagonal, so we have a 3 adjacent to a 2 again, and this will repeat forever. What if we never get a 3? Then it turns out that as soon as we pass all forbidden cells, we will start going down towards all zeros and eventually get there. With no forbidden cells, a 1 does not propagate to the next diagonal at all, and a 2 propagates two adjacent +1s to the next diagonal. So if we have a sequence that looks like $(2, 2, \\dots, 2)$ with $k$ 2s, on the next diagonal we will get $(1, 2, 2, \\dots, 2, 1)$ with $k-1$ 2s, so after $k$ diagonals the 2s will disappear. This argument also demonstrates that the process will converge after $O(n)$ steps, since every forbidden cell will create a constant amount of additional 2s, and without forbidden cells the number of 2s decreases by at least 1 per step. Therefore we finally have a complete solution, albeit one that runs in $O(n^2)$ which is too slow for $n=10^6$. In order to make it faster, we have to take a closer look at the changes of the array $d$. Suppose the array looks like $(0, 0, \\dots, 0, 1, 2, 2, \\dots, 2, 1, 0, 0, \\dots, 0)$ for a certain diagonal. How is it going to look for the next diagonal depending on the locations of the forbidden cells on this diagonal? If a cell with a 0 is forbidden, this changes nothing. If a cell with a 2 is forbidden, then we are going to get a 3 on the next diagonal, and the answer will be $\\texttt{NO}$. So the only interesting question is whether the two cells with 1 are forbidden: If none of the 1s are forbidden, then we get the same structure on the next diagonal, but with the left 1 moving one position to the right (and therefore the number of 2s decreases by one). If only the left 1 is forbidden, then we still get the same pattern on the next diagonal, but the left 1 stays in the same position (and therefore the number of 2s is unchanged). If only the right 1 is forbidden, then it moves one position to the right on the next diagonal (and therefore the number of 2s is also unchanged). Finally, if both 1s are forbidden, then we still get the same pattern on the next diagonal, but with the number of 2s actually increasing by one. This suggests the following idea: when there are no 3s or higher on a diagonal, and when not all numbers are 0s, the array $d$ for it always has the form $(0, 0, \\dots, 0, 1, 2, 2, \\dots, 2, 1, 0, 0, \\dots, 0)$: exactly two 1s, zero or more 2s in between the 1s, and 0s on the outside. This is not entirely correct: in the sample discussed above there is also the case of $(0, 0, \\dots, 0, 2, 2, 0, 0, \\dots, 0)$: exactly two 2s surrounded by all 0s. This pattern always appears after $(0, 0, \\dots, 0, 1, 2, 1, 0, 0, \\dots, 0)$ when the 2 is forbidden, and it is actually the only situation where a 2 can be forbidden without getting a 3. It turns out that this is the only special case, and we can easily prove by induction that we always have one of the patterns mentioned above. Therefore as we go in increasing order of $z$, for the diagonal $a+b=z$ we can simply store two integers and a boolean: the position of the left 1, the position of the right 1, and whether we have the special $0, 2, 2, 0$ case. We need to find all forbidden cells on the given diagonal, which we can achieve by sorting the forbidden cells by the sum of the coordinates and keeping a pointer into the sorted array as we increase $z$. After that we can determine the state of the next diagonal in $O(1)$, so the total running time of this solution is $O(n\\log n)$ if we use normal sorting, or $O(n)$ if we use counting/radix sorting (we can use counting sorting since we only care about the first $O(n)$ diagonals). The time limit in this problem was pretty tight, so even the $O(n)$ solution had to be implemented with care. The reason for this was that the $O(n^2)$ solution mentioned above yields itself perfectly to optimizations. The only quadratic part is a couple of small inner loops looking roughly like this: The C++ compilers are very good at vectorizing such code using SIMD instructions (which you can enable using some pragmas). But we can also help the compiler because we know that the values in our arrays are always only 0, 1 or 2, so we can actually represent our array as two bitsets. We could not get the compiler to efficiently vectorize std::bitset, but it turns out that gcc supports a relatively new syntax This defines a new type that works like an array of 4 uint64's, but supports element-wise operations including bitwise operations that automatically use vectorization. Using this trick made the $O(n^2)$ solution mentioned above run in under 7 seconds for $n=10^6$, therefore to make sure this solution does not pass we had to set the tight time limit. One other potentially relevant remark for implementing the solution: we have mentioned above that we only care about the first $O(n)$ diagonals, but what is the constant hidden in the $O$-notation? Initially one might think that a case with the following forbidden cells is the worst: $(0, 0), (1, 0), (2, 0), \\dots, (\\lceil\\frac{n-1}{2}\\rceil, 0), (0, 1), (0, 2), \\dots, (0, \\lfloor\\frac{n-1}{2}\\rfloor)$. The final state of the organism in this case is a big rectangle (so it also catches solutions that assume we only do a linear number of divisions), and we have $n+1$ nonzero diagonals in this case. However, the $0, 2, 2, 0$ exception from the solution above allows to construct a testcase that is twice nastier: $(0, 0), (0, 1), (1, 0), (1, 1), (2, 2), \\dots, (n-3, n-3)$. In this case the array $d$ constantly changes from $1, 2, 1$ to $0, 2, 2, 0$ and back, and we get $2n-2$ nonzero diagonals. So if your solution hardcodes the number of diagonals to process you need to go as high as $2n-2$. For more context about the origins of this problem and related topics you can check out the following paper: F. Chung, R. Graham, J. Morrison, A. Odlyzko, Pebbling a Chessboard, Amer. Math. Monthly 102 (1995), pp. 113-123.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1949",
    "index": "I",
    "title": "Disks",
    "statement": "You are given $n$ disks in the plane. The center of each disk has integer coordinates, and the radius of each disk is a positive integer. No two disks overlap in a region of positive area, but it is possible for disks to be tangent to each other.\n\nYour task is to determine whether it is possible to change the radii of the disks in such a way that:\n\n- Disks that were tangent to each other remain tangent to each other.\n- No two disks overlap in a region of positive area.\n- The sum of all radii strictly decreases.\n\nThe new radii are allowed to be arbitrary positive real numbers. The centers of the disks cannot be changed.",
    "tutorial": "To start, we build the graph that describes the tangency relation between the disks: each disk is represented by a node in the graph, and an edge connects two nodes if and only if the corresponding disks are tangent. Constructing this graph can be done in time $O(n^2)$ by checking all pairs of disks. In fact, it can be done in faster than quadratic time, but this is not necessary to solve the problem with the given constraints. Suppose that you change the radii of the disks by real numbers $\\delta_1, \\dots, \\delta_n$. In order to maintain tangency, we must have $\\delta_i + \\delta_j = 0$ whenever the $i$-th and $j$-th disks are initially tangent. In fact, this is condition is also sufficient, provided that $\\delta_1, \\dots, \\delta_n$ are small enough in absolute value (to avoid overlaps and to keep all the radii positive). Fix a connected component of the tangency graph, and fix any node $i$ in this component. The value $\\delta_i$ determines the values of $\\delta_j$ for all $j$ in the same connected component, and each $\\delta_j$ has to be equal to either $\\delta_i$ or $-\\delta_i$. If the connected component is not bipartite, it contains a cycle of odd length, and such a cycle shows that $\\delta_i = -\\delta_i$ and so $\\delta_i=0$. On the other hand, if the connected component is bipartite, then it is possible to assign any real value to $\\delta_i$. Color the nodes of such a bipartite connected component black and white, so that every edge connects a white node and a black node; use white to color the node $i$. The sum of the radii in this connected component changes by $\\delta_i \\cdot k$, where $k$ is the difference between the number of white nodes and the number of black nodes. In order to strictly decrease the sum of the radii, we need a different number of black and white nodes ($k \\neq 0$); if this happens, we can pick $\\delta_i$ to be any sufficiently small real number such that $\\delta_i \\cdot k < 0$. To summarize, the answer is YES if and only if there is at least one connected component which is bipartite and has a different number of white and black nodes. This condition can be checked in time $O(n)$.",
    "tags": [
      "dfs and similar",
      "geometry",
      "graph matchings",
      "graphs"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1949",
    "index": "J",
    "title": "Amanda the Amoeba",
    "statement": "\\textbf{This problem has an attachment. You can use it to simulate and visualize the movements of the amoeba.}\n\nAmoeba Amanda lives inside a rectangular grid of square pixels. Her body occupies some of these pixels. Other pixels may be either free or blocked. Amanda moves across the grid using the so-called amoeboid movement. In each step of such a movement, her body first shrinks by one pixel (one pixel of the body is removed and becomes free), and then grows at a different place (one previously-free pixel is added to the body).\n\nTo prevent structural damage, Amanda's body always occupies a connected region of pixels, which means that any pair of pixels forming the body can be connected by a sequence of adjacent pixels without ever leaving the body. Two pixels are considered adjacent if they share a common side (each pixel has at most 4 neighbours). The body remains connected even during the movement, including the moment after removing a pixel and before adding another one.\n\nYour task is to help Amanda find her way around. Given her initial position and desired final position, suggest a sequence of valid moves leading from the former to the latter.\n\n\\begin{center}\n{\\small Illustration of sample $1$: The filled shape is the initial position, the dotted region is the final position.}\n\\end{center}",
    "tutorial": "To solve this problem, we first find a path $P_{AB}$ connecting two pixels $A$ and $B$ such that Pixel $A$ is a part of the initial position. Pixel $B$ is a part of the final position. All inner pixels of $P_{AB}$ (let us denote their sequence as $Q_{AB}$) are free pixels, neither inside the initial position nor the final one. Note that it is generally allowed to select two neighbouring pixels or even having $A=B$, in which case $Q_{AB}$ will be empty. For the solution to work, it is not important how such a path is found, one possible way is to find the shortest path between the initial and final position. If no such path exists, the problem has no solution, as it means the initial and final position are completely separated by blocked cells. Otherwise, the final position is reachable and the problem has a solution, which will be proven by describing its construction. As the next step, we will construct a tree $T_A$ rooted in pixel $A$ and containing all pixels of the initial position (and no other pixels), and also a tree $T_B$ rooted in pixel $B$ and containing all pixels of the final position (and only them). Again, it is not important how the trees look like, as far as they contain all appropriate pixels. It is easy to construct them using either DFS or BFS. The solution then consecutively removes pixels of $T_A$ bottom-up, starting from leaves and proceeding to parents when they become leaves. Such removed pixels are first added to fill the sequence $Q_{AB}$, and then to tree $T_B$ top-down, starting with $B$ and going to lower nodes after their parents were added. In the end, pixels of $Q_{AB}$ need to be removed (and added to the bottom of $T_{B}$). After that, the amoeba will occupy the exact final position. There is one more important issue to cope with. The trees $T_A$ and $T_B$ are not necessarily disjoint, which means that some (or even many) pixels may appear in both. While removing pixels from $T_A$ and adding them to $T_B$, the following situations may occur: Some pixel should be removed from $T_A$ but we know it is also part of $T_B$ and has not been added yet. In this case, the algorithm proceeds just normally, removing the pixel. It will later be added again to the body, which adds to the total number of moves, but there is no requirement to minimize that number. Some pixel should be added to $T_B$ but it is still part of the body, as it was not yet removed from $T_A$. In such a case, the pixel is skipped (and stays a part of the body to keep it connected) and it has to be marked as such. When the algorithm later proceeds to that pixel as part of $T_A$, it must not be removed anymore, and the algorithm proceeds to other pixels in $T_A$. These steps keep the amoeba connected at all times, and in the end, all pixels of $T_B$ are occupied, which means reaching the final position. Although the algorithm may remove some pixels and then add the same pixels again, this happens at most once for each of the pixels. In fact, each pixel is removed at most once and also added at most once, which means the maximal number of steps produced by the algorithm is limited by the total number of pixels in the pixture, $r\\cdot c$, which is way below the required limit.",
    "tags": [
      "graphs",
      "implementation",
      "trees",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1949",
    "index": "K",
    "title": "Make Triangle",
    "statement": "You are given $n$ positive integers $x_1, x_2, \\ldots, x_n$ and three positive integers $n_a, n_b, n_c$ satisfying $n_a+n_b+n_c = n$.\n\nYou want to split the $n$ positive integers into three groups, so that:\n\n- The first group contains $n_a$ numbers, the second group contains $n_b$ numbers, the third group contains $n_c$ numbers.\n- Let $s_a$ be the sum of the numbers in the first group, $s_b$ be the sum in the second group, and $s_c$ be the sum in the third group. Then $s_a, s_b, s_c$ are the sides of a triangle with positive area.\n\nDetermine if this is possible. If this is possible, find one way to do so.",
    "tutorial": "We will denote these groups as $A, B, C$ correspondingly. Wlog $n_a \\leq n_b \\leq n_c$, and $x_1 \\leq x_2 \\leq \\ldots \\leq x_n$. Let $x_1 + x_2 + \\ldots + x_n = S$. We just want the sum in each group to be smaller than $\\frac{S}{2}$. Let's note some obvious conditions for construction to be possible: The largest group is not too large: $x_1 + x_2 + \\ldots + x_{n_c} < \\frac{S}{2}$; The largest item is not too large: $x_n + (x_1 + x_2 + \\ldots + x_{n_a - 1}) < \\frac{S}{2}$. It turns out that these conditions are sufficient! We will prove even stronger statement. Lemma. Assume we already placed some numbers, which are $\\geq$ than any remaining numbers. Assume current sum in group $g$ is $S_g$, the number of empty spots in group $g$ is $n'_g$, and there are $n'_a + n'_b + n'_c = n'$ numbers remaining, $x_1 \\leq x_2 \\leq \\ldots \\leq x_{n'}$. Then, it's possible to distribute the remaining numbers if and only if the following conditions hold: No group is too large: for any group $g$, $S_g + x_1 + x_2 + \\ldots + x_{n'_g} < \\frac{S}{2}$ $S_g + x_1 + x_2 + \\ldots + x_{n'_g} < \\frac{S}{2}$ The largest item is not too large: there exists a group $g$ with $n'_g>0$, such that $S_g + x_{n'} + (x_1 + x_2 + \\ldots + x_{n'_g - 1}) < \\frac{S}{2}$ $S_g + x_{n'} + (x_1 + x_2 + \\ldots + x_{n'_g - 1}) < \\frac{S}{2}$ Proof. These conditions are obviously necessary; let's show that they are sufficient. Forget about $n_a \\leq n_b \\leq n_c$ for now Wlog we can put the largest element $x_{n'}$ in group $a$, so $S_a + x_{n'} + (x_1 + x_2 + \\ldots + x_{n'_a - 1}) < \\frac{S}{2}$. Put the remaining numbers in the other two groups arbitrarily. If both have sum less than $\\frac{S}{2}$, we are good! Otherwise, wlog, sum in group $B$ is at least $\\frac{S}{2}$. Now, start swapping free elements in $B$ and $C$ one by one. If at some point sums in both $B$ and $C$ were smaller than $\\frac{S}{2}$, we are good. Note that it's not possible that at one moment, the sum in $B$ is $\\geq \\frac{S}{2}$, and at next the sum in $C$ is $\\geq \\frac{S}{2}$: the sum in $C$ currently is at most $S - \\frac{S}{2} - x_{n'}$, and it will decrease by at most $x_{n'}$ and increase by at least $1$ after the swap, so it will still be at most $S - \\frac{S}{2} - 1 < \\frac{S}{2}$. So, the only possibility is that the sum in $B$ is still $\\geq \\frac{S}{2}$. Now, note that if we swap free elements in $A$ and $C$, the sum in $B$ is still $\\geq \\frac{S}{2}$. Also, note that if $n'_C = 0$, that is, there are no free elements in $C$ remaining, then we swap free elements in $A$ and $B$, and we will either get a valid partition, or the sum in $B$ will still be $\\geq \\frac{S}{2}$, as it's not possible for sum in $A$ to get $\\geq \\frac{S}{2}$ after one swap, for the same reason. So, here is the idea: we will start swapping elements, so that the smallest $n'_B$ end up in $B$. We will get a contradiction, since we know that $S_B + x_1 + x_2 + \\ldots + x_{n'_B}) < \\frac{S}{2}$. This lemma also gives us a way to find a construction: add elements from largest to smallest. When deciding where to put an element, put it in any group, such that the conditions will hold after we put it there. We can check these conditions in $O(1)$ after we sorted $x_i$s and precomputed their prefix sums. Runtime $O(n\\log{n})$.",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1950",
    "index": "A",
    "title": "Stair, Peak, or Neither?",
    "statement": "You are given three digits $a$, $b$, and $c$. Determine whether they form a stair, a peak, or neither.\n\n- A stair satisfies the condition $a<b<c$.\n- A peak satisfies the condition $a<b>c$.",
    "tutorial": "You just need to write two if-statements and check the two cases. Please note that some languages like C++ won't allow a chain of comparisons like a < b < c, and you should instead write it as a < b && b < c.",
    "code": "#include <iostream>\n\nvoid solve() {\n\tint a, b, c;\n\tstd::cin >> a >> b >> c;\n\tif(a < b && b < c) std::cout << \"STAIR\"<< \"\\n\";\n\telse if(a < b && b > c) std::cout << \"PEAK\"<< \"\\n\";\n\telse std::cout << \"NONE\" << \"\\n\";\n}\n\nint main() {\n\tint tt; std::cin >> tt;\n\twhile(tt--) \n\t    solve();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1950",
    "index": "B",
    "title": "Upscaling",
    "statement": "You are given an integer $n$. Output a $2n \\times 2n$ checkerboard made of $2 \\times 2$ squares alternating '$#$' and '$.$', with the top-left cell being '$#$'.\n\n\\begin{center}\n{\\small The picture above shows the answers for $n=1,2,3,4$.}\n\\end{center}",
    "tutorial": "You just need to implement what is written. One way is to go cell-by-cell in a regular $n \\times n$ checkerboard, and construct the larger one one cell at a time by copying cell $(i,j)$ into cells $(2i,2j)$, $(2i+1, 2j)$, $(2i, 2j+1)$, $(2i+1, 2j+1)$. A faster solution is to notice that if we round down coordinates $(x,y)$ in the enlarged checkerboard to $(\\lfloor \\frac{x}{2} \\rfloor, \\lfloor \\frac{y}{2} \\rfloor)$, we get the corresponding cell in the original checkerboard. And to output a regular checkerboard, we output $\\texttt{#}$ if the sum of coordinates is even, and $\\texttt{.}$ if it is odd. So the faster implementation is: iterate over all cells $(x,y)$ in the $2n \\times 2n$ checkerboard. If $\\lfloor \\frac{x}{2} \\rfloor + \\lfloor \\frac{y}{2} \\rfloor$ is even output $\\texttt{#}$, else output $\\texttt{.}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tfor (int i = 0; i < 2 * n; i++) {\n\t\tfor (int j = 0; j < 2 * n; j++) {\n\t\t\tcout << (i / 2 + j / 2 & 1 ? '.' : '#');\n\t\t}\n\t\tcout << '\\n';\n\t}\t\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1950",
    "index": "C",
    "title": "Clock Conversion",
    "statement": "Given the time in 24-hour format, output the equivalent time in 12-hour format.\n\n- 24-hour format divides the day into 24 hours from $00$ to $23$, each of which has 60 minutes from $00$ to $59$.\n- 12-hour format divides the day into two halves: the first half is $\\mathrm{AM}$, and the second half is $\\mathrm{PM}$. In each half, the hours are numbered in the order $12, 01, 02, 03, \\dots, 11$. Each hour has 60 minutes numbered from $00$ to $59$.",
    "tutorial": "From 24-hour format to 12-hour format, the minutes are the same. For the hours: If $\\texttt{hh}$ is $00$, then it should become $12 \\; \\mathrm{AM}$. If $\\texttt{hh}$ is from $01$ to $11$, then it should become $\\texttt{hh} \\; \\mathrm{AM}$. If $\\texttt{hh}$ is $12$, then it should become $12 \\; \\mathrm{PM}$. If $\\texttt{hh}$ is from $13$ to $23$, then it should become $(\\texttt{hh} - 12) \\; \\mathrm{PM}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int h, m; char c;\n    cin >> h >> c >> m;\n    string am = (h < 12 ? \" AM\" : \" PM\");\n    h = (h % 12 ? h % 12 : 12);\n    cout << (h < 10 ? \"0\" : \"\") << h << c << (m < 10 ? \"0\" : \"\") << m << am << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1950",
    "index": "D",
    "title": "Product of Binary Decimals",
    "statement": "Let's call a number a binary decimal if it is a positive integer and all digits in its decimal notation are either $0$ or $1$. For example, $1\\,010\\,111$ is a binary decimal, while $10\\,201$ and $787\\,788$ are not.\n\nGiven a number $n$, you are asked whether or not it is possible to represent $n$ as a product of some (not necessarily distinct) binary decimals.",
    "tutorial": "First, let's make precompute list of all binary decimals at most $10^5$. You can do it in many ways, for example iterating through all numbers up to $10^5$ and checking if each is a binary decimal. Let's call a number good if it can be represented as the product of binary decimals. For each test case, we will write a simple recursive function. $n$ is good if: $n=1$, or $\\frac{n}{i}$ is good, for some binary decimal $i>1$. Even if your implementation is slightly too slow, there are not many good numbers; you can simply precompute them all locally and hardcode them to get a solution that works in $\\mathcal{O}(1)$. $T(n) \\leq 2 T\\left(\\left\\lfloor\\frac{n}{10}\\right\\rfloor\\right) + 4 T\\left(\\left\\lfloor\\frac{n}{100}\\right\\rfloor\\right) + 26 T\\left(\\left\\lfloor\\frac{n}{1000}\\right\\rfloor\\right).$ $T(n) \\in \\mathcal{O}(n^{\\log_{10} \\alpha}) = \\mathcal{O}\\left(n^{\\log_{10} \\left( \\frac{2 + \\sqrt[3]{395 - 3\\sqrt{16881}} + \\sqrt[3]{395 + 3\\sqrt{16881}}}{3} \\right)}\\right) \\approx \\mathcal{O}(n^{0.635})\\,,$ A more accurate estimate can be made by picking the solution to $\\alpha^5 = 2\\alpha^4 + 4\\alpha^3 + 8\\alpha^2 + 16\\alpha+2$, which gives a bound $\\mathcal{O}(n^{0.587})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 100'007;\nconst int MOD = 1'000'000'007;\n\nvector<int> binary_decimals;\n\nbool ok(int n) {\n\tif (n == 1) {return true;}\n\tbool ans = false;\n\tfor (int i : binary_decimals) {\n\t\tif (n % i == 0) {\n\t\t\tans |= ok(n / i);\n\t\t}\n\t}\n\treturn ans;\n}\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tcout << (ok(n) ? \"YES\\n\" : \"NO\\n\");\t\n}\n\nint main() {\n\tfor (int i = 2; i < MAX; i++) {\n\t\tint curr = i;\n\t\tbool bad = false;\n\t\twhile (curr) {\n\t\t\tif (curr % 10 > 1) {bad = true; break;}\n\t\t\tcurr /= 10;\n\t\t}\n\t\tif (!bad) {binary_decimals.push_back(i);}\n\t}\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1950",
    "index": "E",
    "title": "Nearly Shortest Repeating Substring",
    "statement": "You are given a string $s$ of length $n$ consisting of lowercase Latin characters. Find the length of the shortest string $k$ such that several (possibly one) copies of $k$ can be concatenated together to form a string with the same length as $s$ and, at most, one different character.\n\nMore formally, find the length of the shortest string $k$ such that $c = \\underbrace{k + \\cdots + k}_{x\\rm\\ \\text{times}}$ for some positive integer $x$, strings $s$ and $c$ has the same length and $c_i \\neq s_i$ for at most one $i$ (i.e. there exist $0$ or $1$ such positions).",
    "tutorial": "Let's call a string a period if it can be multiplied to the same length as $s$ What are the possibilities for the lengths of the period? Clearly, it must be a divisor of $n$. So the solution is to check all divisors of $n$ and see the smallest one that works. To check if length $l$ works, multiply the prefix of length $l$ until it's the same length as $s$ and check how many differences there are. However, the different letter can be in the prefix(for example, $\\texttt{hshaha}$ and $l = 2$), so we also check the same for the suffix of length $l$. If either of them is true, output $l$. All numbers at most $10^5$ have at most $128$ divisors, so this will take $\\sim 128 \\cdot 10^5$ operations, which is fast enough.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    for(int i = 1; i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            int satisfy = 2;\n            for(int j = 0; j < i; j++)\n            {\n                for(int k = j+i; k < n; k+=i)\n                {\n                    if(s[k] != s[j])\n                    {\n                        satisfy--;\n                    }\n                }\n            }\n            if(satisfy > 0)\n            {\n                cout << i << endl;\n                return;\n            }\n            satisfy = 2;\n            for(int j = n-i; j < n; j++)\n            {\n                for(int k = j-i; k >= 0; k-=i)\n                {\n                    if(s[k] != s[j])\n                    {\n                        satisfy--;\n                    }\n                }\n            }\n            if(satisfy > 0)\n            {\n                cout << i << endl;\n                return;\n            }\n        }\n    }\n}\n\nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "implementation",
      "number theory",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1950",
    "index": "F",
    "title": "0, 1, 2, Tree!",
    "statement": "Find the minimum height of a rooted tree$^{\\dagger}$ with $a+b+c$ vertices that satisfies the following conditions:\n\n- $a$ vertices have exactly $2$ children,\n- $b$ vertices have exactly $1$ child, and\n- $c$ vertices have exactly $0$ children.\n\nIf no such tree exists, you should report it.\\begin{center}\n{\\small The tree above is rooted at the top vertex, and each vertex is labeled with the number of children it has. Here $a=2$, $b=1$, $c=3$, and the height is $2$.}\n\\end{center}\n\n$^{\\dagger}$ A rooted tree is a connected graph without cycles, with a special vertex called the root. In a rooted tree, among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child.\n\nThe distance between two vertices in a tree is the number of edges in the shortest path between them. The height of a rooted tree is the maximum distance from a vertex to the root.",
    "tutorial": "Note that since the tree has $a+b+c$ vertices, all vertices have $0$, $1$, or $2$ children. Call a vertex a leaf if it has no children. The idea is to \"grow\" the tree from the root by adding one or two vertices at a time. Formally: Start with a root (which is initially a leaf). Repeatedly add $1$ or $2$ children to a leaf. In total, add $2$ children $a$ times and $1$ child $b$ times. Every time we grow by adding $1$ child, the number of leaves does not change (since we lose one and gain one). Every time we grow by adding $2$ children, the number of leaves increases by one (since we lose one and gain two). Otherwise we need to minimize the height. The idea is greedy: note that we should always grow by $2$ instead of $1$ when we have a choice, because it's clear that it will strictly decrease the height. Similarly, we should always grow the node closest to the root to minimize the height. Thus we can just simulate the process described above growing by $2$ first and $1$ afterwards, which takes $\\mathcal{O}(a+b+c)$ time. Bonus: can you solve the problem in $\\mathcal{O}(\\log(a+b+c))$ time? Or even better? A note on the implementation. You can store the number of \"free\" nodes on the current level and the next level in two variables, i.e. you don't need to store a whole tree at all. As you iterate through the current level, store the number of nodes in the next level.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tint a, b, c;\n\tcin >> a >> b >> c;\n\tif (a + 1 != c) {cout << -1 << '\\n'; return;}\n\tif (a + b + c == 1) {cout << 0 << '\\n'; return;}\n\tint curr = 1, next = 0, res = 1;\n\tfor (int i = 0; i < a + b; i++) {\n\t\tif (!curr) {\n\t        swap(next, curr);\n\t        res++;\n\t    }\n\t    curr--;\n\t    next++;\n\t    if (i < a) {next++;}\n\t}\n\tcout << res << '\\n';\n}\n\nint main() {\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1950",
    "index": "G",
    "title": "Shuffling Songs",
    "statement": "Vladislav has a playlist consisting of $n$ songs, numbered from $1$ to $n$. Song $i$ has genre $g_i$ and writer $w_i$. He wants to make a playlist in such a way that every pair of adjacent songs either have the same writer or are from the same genre (or both). He calls such a playlist exciting. Both $g_i$ and $w_i$ are strings of length no more than $10^4$.\n\nIt might not always be possible to make an exciting playlist using all the songs, so the shuffling process occurs in two steps. First, some amount (possibly zero) of the songs are removed, and then the remaining songs in the playlist are rearranged to make it exciting.\n\nSince Vladislav doesn't like when songs get removed from his playlist, he wants the making playlist to perform as few removals as possible. Help him find the minimum number of removals that need to be performed in order to be able to rearrange the rest of the songs to make the playlist exciting.",
    "tutorial": "First of all, always comparing strings takes quite a long time, so, let's map the strings to integers. We can do that by keeping all strings in some array, sorting the array, and mapping each string to its position in the array. This process is called \"Normalization\" or \"Coordinate Compression\". Now, we can do a dynamic programming solution over subsets. We denote mask as our current bit-mask and we say it has the value of all elements we include. For example, if our mask is equal to 7, in binary it looks like ...000111, so we can say that we included elements 0, 1 and 2. Each power of two set in our mask, implies we include that element. So now, if we iterate over masks and the last included element, we can mark $dp_{mask, i}$ as a boolean which tells whether it is possible to get to this state. We transition from a state to another by using the current mask and trying to include all non-included elements one-by-one, and checking out if it is possible to include them. If it is, we update our new mask. After calculating for each state whether we can get to it, using previously calculated states, we update our answer as the maximum number of included elements (bits set) in a mask which is obtainable.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n\n#define all(x) x.begin(),x.end()\n\nvoid solve() {\n    int n; cin >> n;\n    vector<int> s(n), g(n);\n    vector<string> aa(n), bb(n);\n    vector<string> vals;\n    for(int i = 0; i < n; ++i) {\n        string a, b; cin >> a >> b;\n        vals.push_back(a);\n        vals.push_back(b);\n        aa[i] = a, bb[i] = b;\n    }\n    sort(all(vals));\n    vals.erase(unique(all(vals)), vals.end());\n    for(int i = 0; i < n; ++i) {\n        s[i] = lower_bound(all(vals), aa[i]) - vals.begin();\n        g[i] = lower_bound(all(vals), bb[i]) - vals.begin();\n    }\n    vector<vector<int>> dp(1 << n, vector<int>(n, 0));\n    for(int i = 0; i < n; ++i) dp[1 << i][i] = 1;\n    for(int mask = 0; mask < (1 << n); ++mask) {\n        for(int lst = 0; lst < n; ++lst) {\n            if(!dp[mask][lst]) continue;\n            for(int i = 0; i < n; ++i) {\n                if(mask >> i & 1) continue;\n                if(s[lst] == s[i] || g[lst] == g[i]) {\n                    dp[mask | (1 << i)][i] |= dp[mask][lst];\n                }\n            }\n        }\n    }\n    int ans = 0;\n    for(int mask = 0; mask < (1 << n); ++mask) {\n        for(int i = 0; i < n; ++i) {\n            if(dp[mask][i]) {\n                ans = max(ans, __builtin_popcount(mask));\n            }\n        }\n    }\n    cout << n - ans << \"\\n\";\n}   \n \nmain() {\n    int t = 1; cin >> t;\n    while(t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "graphs",
      "hashing",
      "implementation",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1951",
    "index": "A",
    "title": "Dual Trigger",
    "statement": "\\begin{quote}\nNgọt - LẦN CUỐI (đi bên em xót xa người ơi)\n\\hfill ඞ\n\\end{quote}\n\nThere are $n$ lamps numbered $1$ to $n$ lined up in a row, initially turned off. You can perform the following operation any number of times (possibly zero):\n\n- Choose two \\textbf{non-adjacent}${}^\\dagger$ lamps that are currently turned off, then turn them on.\n\nDetermine whether you can reach configuration $s$, where $s_i = 1$ means the $i$-th lamp is turned on, and $s_i = 0$ otherwise.\n\n${}^\\dagger$ Only lamp $i$ and $i + 1$ are adjacent for all $1 \\le i < n$. Note that lamp $n$ and $1$ are \\textbf{not} adjacent when $n \\ne 2$.",
    "tutorial": "The answer is obviously \"NO\" if there is an odd amount of $\\mathtt{1}$ in $s$. When there are zero $\\mathtt{1}$'s, the answer is trivially \"YES\". When there are exactly two $\\mathtt{1}$'s in $s$, then we also need to check whether the two $\\mathtt{1}$'s are adjacent or not. Otherwise, when there are $k \\ge 4$ $\\mathtt{1}$'s in $s$, let their positions be $x_1, x_2, \\dots, x_k$. Note that we can always turn on the $x_i$-th and the $x_{i + k/2}$-th lamp as they are not adjacent. Therefore the answer is \"YES\" in this case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        int n; cin >> n;\n        string s; cin >> s;\n        int cnt = 0, mi = n, mx = -1;\n        for (int i = 0; i < n; i++) {\n            if (s[i] == '1') {\n                cnt++;\n                mi = min(mi, i); mx = max(mx, i);\n            }\n        }\n        cout << (cnt % 2 == 1 || (cnt == 2 && mx - mi == 1) ? \"NO\\n\" : \"YES\\n\");\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1951",
    "index": "B",
    "title": "Battle Cows",
    "statement": "\\begin{quote}\nThe HU - Shireg Shireg\n\\hfill ඞ\n\\end{quote}\n\nThere are $n$ cows participating in a coding tournament. Cow $i$ has a Cowdeforces rating of $a_i$ (all distinct), and is initially in position $i$. The tournament consists of $n-1$ matches as follows:\n\n- The first match is between the cow in position $1$ and the cow in position $2$.\n- Subsequently, each match $i$ is between the cow in position $i+1$ and the winner of match $i-1$.\n- In each match, the cow with the higher Cowdeforces rating wins and proceeds to the next match.\n\nYou are the owner of cow $k$. For you, winning the tournament is not important; rather, you want your cow to win in as many matches as possible. As an acquaintance of the tournament organizers, you can ask them to swap the position of your cow with another cow \\textbf{only once}, or you can choose to do nothing.\n\nFind the maximum number of wins your cow can achieve.",
    "tutorial": "It is easy to note that the $i$-th match is between cow $i+1$ and the strongest cow among cows $1, 2, \\cdots, i$. Therefore, in order to win any match at all, you cow have to be stronger than every cow before her (and cow $2$ if your cow is cow $1$). Consider the following cases: There exists no stronger cow before your cow. Then you should maximize the number of wins by swapping your cow with cow $1$. There exists some stronger cows before your cow. Let $i$ be the first such cow. Obviously you want cow $i$ to end up to the right of your cow. There are two ways to achieve this: Swap your cow before cow $i$. Since your cow will lose to cow $i$ anyway, you should maximize the number of wins by swapping with cow $1$. Swap your cow with cow $i$. Swap your cow before cow $i$. Since your cow will lose to cow $i$ anyway, you should maximize the number of wins by swapping with cow $1$. Swap your cow with cow $i$. The answer for the problem is the maximum among all above candidates. Since there are only $2$ of them, the overall time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        int n, k; cin >> n >> k; k--;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n        int x = find_if(a.begin(), a.end(), [&](int v) { return v > a[k]; }) - a.begin();\n        vector<int> pos(n); iota(pos.begin(), pos.end(), 0);\n        int ans = 0;\n        for (int i : {0, x}) {\n            if (i == n) {\n                continue;\n            }\n            swap(pos[i], pos[k]);\n            vector<int> stt(n);\n            for (int j = 1, u = pos[0]; j < n; j++) {\n                int v = pos[j];\n                u = (a[u] > a[v] ? u : v);\n                stt[u]++;\n            }\n            swap(pos[i], pos[k]);\n            ans = max(ans, stt[k]);\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1951",
    "index": "C",
    "title": "Ticket Hoarding",
    "statement": "\\begin{quote}\nMaître Gims - Est-ce que tu m'aimes ?\n\\hfill ඞ\n\\end{quote}\n\nAs the CEO of a startup company, you want to reward each of your $k$ employees with a ticket to the upcoming concert. The tickets will be on sale for $n$ days, and by some time travelling, you have predicted that the price per ticket at day $i$ will be $a_i$. However, to prevent ticket hoarding, the concert organizers have implemented the following measures:\n\n- A person may purchase no more than $m$ tickets per day.\n- If a person purchases $x$ tickets on day $i$, all subsequent days (i.e. from day $i+1$ onwards) will have their prices per ticket increased by $x$.\n\nFor example, if $a = [1, 3, 8, 4, 5]$ and you purchase $2$ tickets on day $1$, they will cost $2$ in total, and the prices from day $2$ onwards will become $[5, 10, 6, 7]$. If you then purchase $3$ more tickets on day $2$, they will cost in total an additional $15$, and the prices from day $3$ onwards will become $[13, 9, 10]$.\n\nFind the minimum spending to purchase $k$ tickets.",
    "tutorial": "Note: we will present the intuitive idea first; the formal proof follows later. Let's try to find a way to interpret the raised price at day $i$ from buying on earlier days. We know that every ticket bought on an earlier day than $i$ raised the price per ticket $i$ by $1$; in turn, this \"additional tax\" will be added to our total cost every time a ticket is bought on day $i$. Parsing in a different way, every pair of ticket where one is bought before day $i$ and one is bought on day $i$ adds $1$ additional tax to the total cost, so the final additional tax is exactly \"the number of pair of tickets that were bought on different days\". We now try to find a way to optimize both the base cost and the total additional tax. Observe that the same greedy strategy of \"take as many cheap tickets as possible\" works for both of them (obviously works for the first quantity, and for the second quantity it works because we're limiting the number of pair of tickets bought on different days). Implementing this gives an $O(n \\log n)$ solution. - - - Formally, suppose we buy $b_1, b_2, \\ldots, b_n$ tickets on day $1, 2, \\ldots, n$, respectively, then $0 \\leq b_i \\leq m$, $\\sum_{i=1}^{n} b_i = k$ and the price per ticket on day $i$ will be $a_i + b_1 + b_2 + \\ldots + b_{i-1} = a_i + \\sum_{j=1}^{i-1} b_j$. Thus, the total cost will be: $\\sum_{i=1}^{n} (a_i + \\sum_{j=1}^{i-1} b_j)b_i = \\sum_{i=1}^{n} a_ib_i + \\sum_{1 \\leq j < i \\leq n} b_ib_j$ Note that if we choose two days $i$, $j$ and swap $(a_i, b_i)$ with $(a_j, b_j)$, the above sum does not change its value. Therefore, we can freely rearrange the sequence $a$ without changing the answer. Let's sort the sequence $a$ in non-decreasing order. It is obvious that the first sum is minimized when we buy the $k$ cheapest tickets, i.e. $b = (m, m, \\ldots, k \\mod m, 0, 0, \\ldots, 0)$. We will prove that the greedy strategy also minimizes the second sum, by noting that the second sum is equal to: $\\frac{1}{2} ((\\sum_{i = 1}^{n}b_i)^{2} - \\sum_{i = 1}^{n}{b_i^2}) = \\frac{1}{2}k^2 - \\frac{1}{2} \\sum_{i = 1}^{n}{b_i^2}$ If there exists two days $i$, $j$ such that $0 < b_i \\leq b_j < m$, then replacing $(b_i, b_j)$ with $(b_i - 1, b_j + 1)$ gives a smaller cost. Hence, the sequence $b = (m, m, \\ldots, k \\mod m, 0, 0, \\ldots, 0)$ minimizes the overall cost.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        int n, m, k; cin >> n >> m >> k;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n        sort(a.begin(), a.end());\n        int64_t ans = 0;\n        int tax = 0;\n        for (int i = 0; i < n; ++i) {\n            int buy = min(m, k);\n            ans += 1LL * buy * (a[i] + tax);\n            tax += buy;\n            k -= buy;\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1951",
    "index": "D",
    "title": "Buying Jewels",
    "statement": "\\begin{quote}\nNightwish feat. Jonsu - Erämaan Viimeinen\n\\hfill ඞ\n\\end{quote}\n\nAlice has $n$ coins and wants to shop at Bob's jewelry store. Today, although Bob has not set up the store yet, Bob wants to make sure Alice will buy \\textbf{exactly} $k$ jewels. To set up the store, Bob can erect at most $60$ stalls (each containing an unlimited amount of jewels) and set the price per jewel for each stall to be an integer number of coins between $1$ and $10^{18}$.\n\nFortunately, Bob knows that Alice buys greedily: and she will go to stall $1$, buy as many jewels as possible, then go to stall $2$, buy as many jewels as possible, and so on until the last stall. Knowing this, Bob can choose the number of stalls to set up, as well as set the price for each stall so that Alice buys exactly $k$ jewels. Help Bob fulfill the task, or determine if it is impossible to do so.\n\nNote that Alice does not need to spend all her coins.",
    "tutorial": "We first assume that $p_i \\leq n$ for $1 \\leq i \\leq s$, since adding stalls with price greater than $n$ doesn't change the result. If $n < k$ then the answer is obviously \"NO\". If $n = k$ then the answer is obviously \"YES\" - we can set up a single stall of price $1$. Otherwise, the first stall should have price $p_1 \\geq 2$. Let $n = p_1q + r$ such that $q$, $r$ are integers and $q \\geq 1$, $0 \\leq r < p_1$. Obviously Alice can buy at most $q + r$ jewels ($q$ from stall $1$, at most $r$ from other stalls). On the other hand: $n - 2(q+r) = (p_1 - 2)q - r$ $\\geq (p_1 - 2)q - p_1 + 1$ (since $r \\leq p_1 - 1$) $\\geq (p_1 - 2) - p_1 + 1$ (since $q \\geq 1, p_1 \\geq 2$) $= -1$ $\\Rightarrow 2(q+r) \\leq n + 1$ Thus, if $k < n$ and $2k > n + 1$, the answer is \"NO\". Otherwise, choosing $p_1 = n - k + 1$ and $p_2 = 1$ solves the problem (you also have the option to print $58$ random integers afterwards to test our checker!)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        int64_t n, k; cin >> n >> k;\n        if (n < k) {\n            cout << \"NO\\n\";\n        } else if (n == k) {\n            cout << \"YES\\n1\\n1\\n\";\n        } else if (n < 2 * k - 1) {\n            cout << \"NO\\n\";\n        } else {\n            cout << \"YES\\n2\\n\" << n - k + 1 << \" 1\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1951",
    "index": "E",
    "title": "No Palindromes",
    "statement": "\\begin{quote}\nChristopher Tin ft. Soweto Gospel Choir - Baba Yetu\n\\hfill ඞ\n\\end{quote}\n\nYou are given a string $s$ consisting of lowercase Latin characters. You need to partition$^\\dagger$ this string into some substrings, such that each substring is not a palindrome$^\\ddagger$.\n\n$^\\dagger$ A partition of a string $s$ is an ordered sequence of some $k$ strings $t_1, t_2, \\ldots, t_k$, such that $t_1 + t_2 + \\ldots + t_k = s$, where $+$ here represents the concatenation operation.\n\n$^\\ddagger$ A string $s$ is considered a palindrome if it reads the same backwards as forwards. For example, $\\mathtt{racecar}$, $\\mathtt{abccba}$, and $\\mathtt{a}$ are palindromes, but $\\mathtt{ab}$, $\\mathtt{dokibird}$, and $\\mathtt{kurosanji}$ are not.",
    "tutorial": "If $s$ is not a palindrome then we are done. If $s$ consists of only one type of character then we're also done. Consider the case when $s$ is a palindrome and there are at least $2$ distinct characters. Let $t$ be the first position where $s_t \\neq s_1$, and note that this means $s_{[1, t]}$ is not a palindrome. If $s_{[t + 1, n]}$ isn't a palindrome then we're done. Otherwise, we note that the string has the form $A\\mathtt{b}A\\mathtt{b} \\dots A\\mathtt{b}A$, where $A$ consists of $t-1$ $\\mathtt{a}$ characters (from the assumptions that $s$ and $s_{[t + 1, n]}$ are palindromes). We do a case analysis on $t$, observing that $t$ is between $2$ and $\\frac{n + 1}{2}$: If $t = \\frac{n + 1}{2}$, the string has the form $A\\mathtt{b}A$, and we can verify that this is a \"NO\" case (proof: for every partition, either the substring containing $s_1$ or the substring containing $s_n$ has length at most $\\frac{n - 1}{2}$, which means it consists of only character $\\mathtt{a}$). If $t = 2$, the string has the form $\\mathtt{abab\\dots aba}$, and we can verify that this is another \"NO\" case (proof: every partition must have an odd-length substring, which is always a palindrome). Otherwise, $s_{[1, t + 1]} = A\\mathtt{ba}$ starts with $t - 1$ $\\mathtt{a}$ characters and ends with $1$ $\\mathtt{a}$ character, and $s_{[t + 2, n]}$ starts with $t - 2$ $\\mathtt{a}$ characters and ends with $t - 1$ $\\mathtt{a}$ character. Therefore, both substrings are not palindromes, which means this is a valid partition. Implementing this idea directly gives a time complexity of $O(n)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint main(void) {\n    ios_base::sync_with_stdio(false); cin.tie(NULL);\n    int ntest;\n    cin >> ntest;\n    while (ntest--) {\n        string s;\n        cin >> s;\n        int n = s.size();\n        auto is_palindrome = [&](int l, int r) -> bool {\n            for (int i = l; i < r + l - i; ++i) if (s[i] != s[r + l - i]) return false;\n            return true;\n        };\n        if (!is_palindrome(0, n - 1)) {\n            cout << \"YES\\n1\\n\" << s << \"\\n\";\n            continue;\n        }\n        int first_dif = -1;\n        for (int i = 1; i < n; ++i) if (s[i] != s[0]) {\n            first_dif = i;\n            break;\n        }\n        if (first_dif == -1) {\n            cout << \"NO\\n\";\n            continue;\n        }\n        if (!is_palindrome(0, first_dif) && !is_palindrome(first_dif + 1, n - 1)) {\n            cout << \"YES\\n2\\n\" << s.substr(0, first_dif + 1) << ' ' << s.substr(first_dif + 1) << \"\\n\";\n            continue;\n        } else if (first_dif == 1 || first_dif == n / 2) {\n            cout << \"NO\\n\";\n        } else {\n            cout << \"YES\\n2\\n\" << s.substr(0, first_dif + 2) << ' ' << s.substr(first_dif + 2) << \"\\n\";\n        }\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "divide and conquer",
      "greedy",
      "hashing",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1951",
    "index": "F",
    "title": "Inversion Composition",
    "statement": "\\begin{quote}\nMy Chemical Romance - Disenchanted\n\\hfill ඞ\n\\end{quote}\n\nYou are given a permutation $p$ of size $n$, as well as a non-negative integer $k$. You need to construct a permutation $q$ of size $n$ such that $\\operatorname{inv}(q) + \\operatorname{inv}(q \\cdot p) = k {}^\\dagger {}^\\ddagger$, or determine if it is impossible to do so.\n\n${}^\\dagger$ For two permutations $p$ and $q$ of the same size $n$, the permutation $w = q \\cdot p$ is such that $w_i = q_{p_i}$ for all $1 \\le i \\le n$.\n\n${}^\\ddagger$ For a permutation $p$ of size $n$, the function $\\operatorname{inv}(p)$ returns the number of inversions of $p$, i.e. the number of pairs of indices $1 \\le i < j \\le n$ such that $p_i > p_j$.",
    "tutorial": "We say that $(i, j)$ is an inverse on permutation $p$ if $i < j$ and $p_i > p_j$, or $i > j$ and $p_i < p_j$. For any two integers $1 \\le i < j \\le n$, let's observe the \"inverseness\" of $(p_i, p_j)$ on $q$ and $(i, j)$ on $q \\cdot p$: If $(i, j)$ is not an inverse on $p$, then the inverseness of $(p_i, p_j)$ on $q$ and $(i, j)$ on $q \\cdot p$ is the same. Therefore, this pair contributes either $0$ or $2$ to $\\operatorname{inv}(q) + \\operatorname{inv}(q \\cdot p)$. Otherwise, the inverseness of $(p_i, p_j)$ on $q$ and $(i, j)$ on $q \\cdot p$ is different. Therefore, this pair always contribute $1$ to $\\operatorname{inv}(q) + \\operatorname{inv}(q \\cdot p)$. Therefore, the answer is \"NO\" if $k \\notin [\\operatorname{inv}(p), n(n - 1) - \\operatorname{inv}(p)]$, or if $k$ has different parity from $\\operatorname{inv}(p)$. Otherwise, we claim that we can always construct $q$; the following implementation actually constructs $q \\cdot p$, but we can easily find one permutation from the other. Let $k' = \\frac{k - \\operatorname{inv}(p)}{2}$, then the problem becomes \"find $q \\cdot p$ with $k'$ special inversions\", where an inverse $(i, j)$ on $q \\cdot p$ is special if $(i, j)$ is not an inverse on $p$. Let $x_i$ be the number of indices $j < i$ where $p_j < p_i$, which can be easily found via a standard Fenwick tree (note that $\\sum_{i=1}^n x_i = \\frac{n(n-1)}{2} - \\operatorname{inv}(p)$). Then there exists an index $t$ such that $\\sum_{i < t} x_i \\le k'$, and $\\sum_{i \\le t} x_i \\ge k'$. It's straightforward to see that the permutation $q \\cdot p = [t, t - 1, \\dots, v + 1, v - 1, v - 2, \\dots, 1, v, t + 1, t + 2, \\dots, n]$ works for some value $v \\in [1, t]$, chosen such that there are exactly $k' - \\sum_{i < t} x_i$ indices before $t$ that forms a special inversion with $t$. Time complexity: $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \ntemplate<typename T>\nstruct fenwick_tree {\n    vector<T> bit;\n    int n;\n \n    fenwick_tree(int n) : n(n), bit(n + 1) {}\n \n    T sum(int x) {\n        T ans = 0;\n        for (; x > 0; x -= x & -x) {\n            ans += bit[x];\n        }\n        return ans;\n    }\n \n    T sum(int l, int r) {\n        return sum(r) - sum(l);\n    }\n \n    void add(int x, T v) {\n        for (++x; x <= n; x += x & -x) {\n            bit[x] += v;\n        }\n    }\n};\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        int n; cin >> n;\n        int64_t k; cin >> k;\n        fenwick_tree<int> fen(n);\n        vector<int> p(n), ip(n), cnt(n);\n        int64_t inv = 0;\n        for (int i = 0; i < n; i++) {\n            cin >> p[i]; p[i]--;\n            ip[p[i]] = i;\n            inv += i - (cnt[i] = fen.sum(0, p[i]));\n            fen.add(p[i], 1);\n        }\n        if (k < inv || k > 1LL * n * (n - 1) - inv || (k - inv) % 2 == 1) {\n            cout << \"NO\\n\";\n        } else {\n            cout << \"YES\\n\";\n            k = (k - inv) / 2;\n            vector<int> qp(n);\n            for (int i = 0; i < n; i++) {\n                if (cnt[i] < k) {\n                    k -= cnt[i];\n                } else {\n                    for (int j = 0, v = i; j < i; j++) {\n                        qp[j] = v--;\n                        if (p[j] < p[i] && --k == 0) {\n                            qp[i] = v--;\n                        }\n                    }\n                    for (int j = i + 1; j < n; j++) {\n                        qp[j] = j;\n                    }\n                    break;\n                }\n            }\n            for (int i = 0; i < n; i++) {\n                cout << qp[ip[i]] + 1 << \" \\n\"[i + 1 == n];\n            }\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1951",
    "index": "G",
    "title": "Clacking Balls",
    "statement": "\\begin{quote}\nRammstein - Ausländer\n\\hfill ඞ\n\\end{quote}\n\nThere are $m$ baskets placed along a circle, numbered from $1$ to $m$ in clockwise order (basket $m$ is next to basket $1$). Furthermore, there are $n$ balls, where ball $i$ is initially placed in basket $a_i$, and no basket contains more than one ball.\n\nAlice is allowed to perform the following operation, which always takes exactly one second whether you move/throw a ball or not:\n\n- Alice chooses an integer $i$ between $1$ and $n$ \\textbf{uniformly at random}.\n- If ball $i$ was thrown away before, do nothing.\n- Otherwise, ball $i$ is moved from the basket currently containing it to the next basket (in clockwise order). If the target basket currently contains another ball $j$, throw ball $j$ away.\n\nShe repeats this operation until there is exactly one ball left. Calculate the expected time needed (in seconds) for Alice to end the process.\n\nIt can be proven that the answer can be represented as a rational number $\\frac{p}{q}$ with coprime $p$ and $q$. You need to output $p \\cdot q^{-1} \\bmod 10^9 + 7$. It can be proven that $10^9 + 7 \\nmid q$.",
    "tutorial": "Note: there are other (more elegant in our opinion) solutions from some of our testers, which you may or may not find under the comment section. We will present here the original solution here. Consider a state with $k \\leq n$ balls remaining. Let's represent the state as a sequence $S = (d_1, d_2, \\cdots, d_k)$ where $d_i$ is the distance between ball $i$ and ball $(i \\bmod{k}) + 1$. Note that $\\sum_{i=1}^{k} d_i = m$. Then, after a second, one of the following happens: $d_i$ is increased by $1$ and $d_{(i \\bmod{k}) + 1}$ is decreased by $1$ with probability $\\frac{1}{n}$ for each $1 \\leq i \\leq k$ (if $d_{(i \\bmod{k}) + 1} = 0$, we erase it from the sequence). We denote the new sequence as $S + \\{i\\}$. Nothing changes with probability $1 - \\frac{k}{n}$. The terminal state is $(m)$. Therefore, let $f(S)$ be the expected number of seconds to reach the terminal state from state $S = (d_1, d_2, \\cdots, d_k)$, then: $f((m)) = 0$ (*) $f(S) = 1 + \\frac{1}{n} \\sum_{i=1}^{k} f(S + \\{i\\}) + (1 - \\frac{k}{n}) f(S)$ $\\Rightarrow$ $k f(S) = n + \\sum_{i=1}^{k} f(S + \\{i\\})$ (**) Let $h(S, i) = f(S) - f(S + \\{i\\})$, condition (**) becomes $\\sum_{i=1}^{k} h(S, i) = n$. To proceed, we will apply the idea from this comment. If we choose $f(S) = c + \\sum_{i=1}^{k} \\sum_{x=0}^{d_i} g(x)$ for some constant $c$ and function $g: \\mathbb{Z_{\\geq 0}} \\rightarrow \\mathbb{R}$, then: $n = \\sum_{i=1}^{k} h(S, i)$ $= \\sum_{i=1}^{k} g(d_{(i \\bmod{k}) + 1}) - g(d_i + 1)$ $= \\sum_{i=1}^{k} g(d_i) - g(d_i + 1)$ Additionally, since we want $h(S, i) = g(d_{(i \\bmod{k}) + 1}) - g(d_i + 1)$ to hold even when $d_{(i \\bmod{k}) + 1} = 0$, we need to choose $g$ such that $g(0) = 0$. Let's choose $g$ such that $g(0) = 0$ and $g(x + 1) - g(x) = -\\frac{n}{m}x$ for all $x \\geq 0$. Then $\\sum_{i=1}^{k} g(d_i) - g(d_i + 1) = \\frac{n}{m} \\sum_{i=1}^{k} d_i = n$, thus satisfies (**). Solving for $g$ gives $g(x) = -\\frac{n}{m}\\frac{x(x-1)}{2} = -\\frac{n}{m} \\binom{x}{2}$. Finally, $f(S) = c - \\frac{n}{m} \\sum_{i=1}^{k} \\binom{d_i + 1}{3}$. In order to satisfy (*), we need to choose $c = \\frac{n}{m} \\binom{m + 1}{3}$.",
    "code": "#include <bits/stdc++.h>\n \n#include <cassert>\n#include <numeric>\n#include <type_traits>\n \n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n \n \n#include <utility>\n \n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n \nnamespace atcoder {\n \nnamespace internal {\n \nconstexpr long long safe_mod(long long x, long long m) {\n    x %= m;\n    if (x < 0) x += m;\n    return x;\n}\n \nstruct barrett {\n    unsigned int _m;\n    unsigned long long im;\n \n    explicit barrett(unsigned int m) : _m(m), im((unsigned long long)(-1) / m + 1) {}\n \n    unsigned int umod() const { return _m; }\n \n    unsigned int mul(unsigned int a, unsigned int b) const {\n \n        unsigned long long z = a;\n        z *= b;\n#ifdef _MSC_VER\n        unsigned long long x;\n        _umul128(z, im, &x);\n#else\n        unsigned long long x =\n            (unsigned long long)(((unsigned __int128)(z)*im) >> 64);\n#endif\n        unsigned int v = (unsigned int)(z - x * _m);\n        if (_m <= v) v += _m;\n        return v;\n    }\n};\n \nconstexpr long long pow_mod_constexpr(long long x, long long n, int m) {\n    if (m == 1) return 0;\n    unsigned int _m = (unsigned int)(m);\n    unsigned long long r = 1;\n    unsigned long long y = safe_mod(x, m);\n    while (n) {\n        if (n & 1) r = (r * y) % _m;\n        y = (y * y) % _m;\n        n >>= 1;\n    }\n    return r;\n}\n \nconstexpr bool is_prime_constexpr(int n) {\n    if (n <= 1) return false;\n    if (n == 2 || n == 7 || n == 61) return true;\n    if (n % 2 == 0) return false;\n    long long d = n - 1;\n    while (d % 2 == 0) d /= 2;\n    constexpr long long bases[3] = {2, 7, 61};\n    for (long long a : bases) {\n        long long t = d;\n        long long y = pow_mod_constexpr(a, t, n);\n        while (t != n - 1 && y != 1 && y != n - 1) {\n            y = y * y % n;\n            t <<= 1;\n        }\n        if (y != n - 1 && t % 2 == 0) {\n            return false;\n        }\n    }\n    return true;\n}\ntemplate <int n> constexpr bool is_prime = is_prime_constexpr(n);\n \nconstexpr std::pair<long long, long long> inv_gcd(long long a, long long b) {\n    a = safe_mod(a, b);\n    if (a == 0) return {b, 0};\n \n    long long s = b, t = a;\n    long long m0 = 0, m1 = 1;\n \n    while (t) {\n        long long u = s / t;\n        s -= t * u;\n        m0 -= m1 * u;  // |m1 * u| <= |m1| * s <= b\n \n \n        auto tmp = s;\n        s = t;\n        t = tmp;\n        tmp = m0;\n        m0 = m1;\n        m1 = tmp;\n    }\n    if (m0 < 0) m0 += b / s;\n    return {s, m0};\n}\n \nconstexpr int primitive_root_constexpr(int m) {\n    if (m == 2) return 1;\n    if (m == 167772161) return 3;\n    if (m == 469762049) return 3;\n    if (m == 754974721) return 11;\n    if (m == 998244353) return 3;\n    int divs[20] = {};\n    divs[0] = 2;\n    int cnt = 1;\n    int x = (m - 1) / 2;\n    while (x % 2 == 0) x /= 2;\n    for (int i = 3; (long long)(i)*i <= x; i += 2) {\n        if (x % i == 0) {\n            divs[cnt++] = i;\n            while (x % i == 0) {\n                x /= i;\n            }\n        }\n    }\n    if (x > 1) {\n        divs[cnt++] = x;\n    }\n    for (int g = 2;; g++) {\n        bool ok = true;\n        for (int i = 0; i < cnt; i++) {\n            if (pow_mod_constexpr(g, (m - 1) / divs[i], m) == 1) {\n                ok = false;\n                break;\n            }\n        }\n        if (ok) return g;\n    }\n}\ntemplate <int m> constexpr int primitive_root = primitive_root_constexpr(m);\n \nunsigned long long floor_sum_unsigned(unsigned long long n,\n                                      unsigned long long m,\n                                      unsigned long long a,\n                                      unsigned long long b) {\n    unsigned long long ans = 0;\n    while (true) {\n        if (a >= m) {\n            ans += n * (n - 1) / 2 * (a / m);\n            a %= m;\n        }\n        if (b >= m) {\n            ans += n * (b / m);\n            b %= m;\n        }\n \n        unsigned long long y_max = a * n + b;\n        if (y_max < m) break;\n        n = (unsigned long long)(y_max / m);\n        b = (unsigned long long)(y_max % m);\n        std::swap(m, a);\n    }\n    return ans;\n}\n \n}  // namespace internal\n \n}  // namespace atcoder\n \n \n#include <cassert>\n#include <numeric>\n#include <type_traits>\n \nnamespace atcoder {\n \nnamespace internal {\n \n#ifndef _MSC_VER\ntemplate <class T>\nusing is_signed_int128 =\n    typename std::conditional<std::is_same<T, __int128_t>::value ||\n                                  std::is_same<T, __int128>::value,\n                              std::true_type,\n                              std::false_type>::type;\n \ntemplate <class T>\nusing is_unsigned_int128 =\n    typename std::conditional<std::is_same<T, __uint128_t>::value ||\n                                  std::is_same<T, unsigned __int128>::value,\n                              std::true_type,\n                              std::false_type>::type;\n \ntemplate <class T>\nusing make_unsigned_int128 =\n    typename std::conditional<std::is_same<T, __int128_t>::value,\n                              __uint128_t,\n                              unsigned __int128>;\n \ntemplate <class T>\nusing is_integral = typename std::conditional<std::is_integral<T>::value ||\n                                                  is_signed_int128<T>::value ||\n                                                  is_unsigned_int128<T>::value,\n                                              std::true_type,\n                                              std::false_type>::type;\n \ntemplate <class T>\nusing is_signed_int = typename std::conditional<(is_integral<T>::value &&\n                                                 std::is_signed<T>::value) ||\n                                                    is_signed_int128<T>::value,\n                                                std::true_type,\n                                                std::false_type>::type;\n \ntemplate <class T>\nusing is_unsigned_int =\n    typename std::conditional<(is_integral<T>::value &&\n                               std::is_unsigned<T>::value) ||\n                                  is_unsigned_int128<T>::value,\n                              std::true_type,\n                              std::false_type>::type;\n \ntemplate <class T>\nusing to_unsigned = typename std::conditional<\n    is_signed_int128<T>::value,\n    make_unsigned_int128<T>,\n    typename std::conditional<std::is_signed<T>::value,\n                              std::make_unsigned<T>,\n                              std::common_type<T>>::type>::type;\n \n#else\n \ntemplate <class T> using is_integral = typename std::is_integral<T>;\n \ntemplate <class T>\nusing is_signed_int =\n    typename std::conditional<is_integral<T>::value && std::is_signed<T>::value,\n                              std::true_type,\n                              std::false_type>::type;\n \ntemplate <class T>\nusing is_unsigned_int =\n    typename std::conditional<is_integral<T>::value &&\n                                  std::is_unsigned<T>::value,\n                              std::true_type,\n                              std::false_type>::type;\n \ntemplate <class T>\nusing to_unsigned = typename std::conditional<is_signed_int<T>::value,\n                                              std::make_unsigned<T>,\n                                              std::common_type<T>>::type;\n \n#endif\n \ntemplate <class T>\nusing is_signed_int_t = std::enable_if_t<is_signed_int<T>::value>;\n \ntemplate <class T>\nusing is_unsigned_int_t = std::enable_if_t<is_unsigned_int<T>::value>;\n \ntemplate <class T> using to_unsigned_t = typename to_unsigned<T>::type;\n \n}  // namespace internal\n \n}  // namespace atcoder\n \n \nnamespace atcoder {\n \nnamespace internal {\n \nstruct modint_base {};\nstruct static_modint_base : modint_base {};\n \ntemplate <class T> using is_modint = std::is_base_of<modint_base, T>;\ntemplate <class T> using is_modint_t = std::enable_if_t<is_modint<T>::value>;\n \n}  // namespace internal\n \ntemplate <int m, std::enable_if_t<(1 <= m)>* = nullptr>\nstruct static_modint : internal::static_modint_base {\n    using mint = static_modint;\n \n  public:\n    static constexpr int mod() { return m; }\n    static mint raw(int v) {\n        mint x;\n        x._v = v;\n        return x;\n    }\n \n    static_modint() : _v(0) {}\n    template <class T, internal::is_signed_int_t<T>* = nullptr>\n    static_modint(T v) {\n        long long x = (long long)(v % (long long)(umod()));\n        if (x < 0) x += umod();\n        _v = (unsigned int)(x);\n    }\n    template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n    static_modint(T v) {\n        _v = (unsigned int)(v % umod());\n    }\n \n    unsigned int val() const { return _v; }\n \n    mint& operator++() {\n        _v++;\n        if (_v == umod()) _v = 0;\n        return *this;\n    }\n    mint& operator--() {\n        if (_v == 0) _v = umod();\n        _v--;\n        return *this;\n    }\n    mint operator++(int) {\n        mint result = *this;\n        ++*this;\n        return result;\n    }\n    mint operator--(int) {\n        mint result = *this;\n        --*this;\n        return result;\n    }\n \n    mint& operator+=(const mint& rhs) {\n        _v += rhs._v;\n        if (_v >= umod()) _v -= umod();\n        return *this;\n    }\n    mint& operator-=(const mint& rhs) {\n        _v -= rhs._v;\n        if (_v >= umod()) _v += umod();\n        return *this;\n    }\n    mint& operator*=(const mint& rhs) {\n        unsigned long long z = _v;\n        z *= rhs._v;\n        _v = (unsigned int)(z % umod());\n        return *this;\n    }\n    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n \n    mint operator+() const { return *this; }\n    mint operator-() const { return mint() - *this; }\n \n    mint pow(long long n) const {\n        assert(0 <= n);\n        mint x = *this, r = 1;\n        while (n) {\n            if (n & 1) r *= x;\n            x *= x;\n            n >>= 1;\n        }\n        return r;\n    }\n    mint inv() const {\n        if (prime) {\n            assert(_v);\n            return pow(umod() - 2);\n        } else {\n            auto eg = internal::inv_gcd(_v, m);\n            assert(eg.first == 1);\n            return eg.second;\n        }\n    }\n \n    friend mint operator+(const mint& lhs, const mint& rhs) {\n        return mint(lhs) += rhs;\n    }\n    friend mint operator-(const mint& lhs, const mint& rhs) {\n        return mint(lhs) -= rhs;\n    }\n    friend mint operator*(const mint& lhs, const mint& rhs) {\n        return mint(lhs) *= rhs;\n    }\n    friend mint operator/(const mint& lhs, const mint& rhs) {\n        return mint(lhs) /= rhs;\n    }\n    friend bool operator==(const mint& lhs, const mint& rhs) {\n        return lhs._v == rhs._v;\n    }\n    friend bool operator!=(const mint& lhs, const mint& rhs) {\n        return lhs._v != rhs._v;\n    }\n \n  private:\n    unsigned int _v;\n    static constexpr unsigned int umod() { return m; }\n    static constexpr bool prime = internal::is_prime<m>;\n};\n \ntemplate <int id> struct dynamic_modint : internal::modint_base {\n    using mint = dynamic_modint;\n \n  public:\n    static int mod() { return (int)(bt.umod()); }\n    static void set_mod(int m) {\n        assert(1 <= m);\n        bt = internal::barrett(m);\n    }\n    static mint raw(int v) {\n        mint x;\n        x._v = v;\n        return x;\n    }\n \n    dynamic_modint() : _v(0) {}\n    template <class T, internal::is_signed_int_t<T>* = nullptr>\n    dynamic_modint(T v) {\n        long long x = (long long)(v % (long long)(mod()));\n        if (x < 0) x += mod();\n        _v = (unsigned int)(x);\n    }\n    template <class T, internal::is_unsigned_int_t<T>* = nullptr>\n    dynamic_modint(T v) {\n        _v = (unsigned int)(v % mod());\n    }\n \n    unsigned int val() const { return _v; }\n \n    mint& operator++() {\n        _v++;\n        if (_v == umod()) _v = 0;\n        return *this;\n    }\n    mint& operator--() {\n        if (_v == 0) _v = umod();\n        _v--;\n        return *this;\n    }\n    mint operator++(int) {\n        mint result = *this;\n        ++*this;\n        return result;\n    }\n    mint operator--(int) {\n        mint result = *this;\n        --*this;\n        return result;\n    }\n \n    mint& operator+=(const mint& rhs) {\n        _v += rhs._v;\n        if (_v >= umod()) _v -= umod();\n        return *this;\n    }\n    mint& operator-=(const mint& rhs) {\n        _v += mod() - rhs._v;\n        if (_v >= umod()) _v -= umod();\n        return *this;\n    }\n    mint& operator*=(const mint& rhs) {\n        _v = bt.mul(_v, rhs._v);\n        return *this;\n    }\n    mint& operator/=(const mint& rhs) { return *this = *this * rhs.inv(); }\n \n    mint operator+() const { return *this; }\n    mint operator-() const { return mint() - *this; }\n \n    mint pow(long long n) const {\n        assert(0 <= n);\n        mint x = *this, r = 1;\n        while (n) {\n            if (n & 1) r *= x;\n            x *= x;\n            n >>= 1;\n        }\n        return r;\n    }\n    mint inv() const {\n        auto eg = internal::inv_gcd(_v, mod());\n        assert(eg.first == 1);\n        return eg.second;\n    }\n \n    friend mint operator+(const mint& lhs, const mint& rhs) {\n        return mint(lhs) += rhs;\n    }\n    friend mint operator-(const mint& lhs, const mint& rhs) {\n        return mint(lhs) -= rhs;\n    }\n    friend mint operator*(const mint& lhs, const mint& rhs) {\n        return mint(lhs) *= rhs;\n    }\n    friend mint operator/(const mint& lhs, const mint& rhs) {\n        return mint(lhs) /= rhs;\n    }\n    friend bool operator==(const mint& lhs, const mint& rhs) {\n        return lhs._v == rhs._v;\n    }\n    friend bool operator!=(const mint& lhs, const mint& rhs) {\n        return lhs._v != rhs._v;\n    }\n \n  private:\n    unsigned int _v;\n    static internal::barrett bt;\n    static unsigned int umod() { return bt.umod(); }\n};\ntemplate <int id> internal::barrett dynamic_modint<id>::bt(998244353);\n \nusing modint998244353 = static_modint<998244353>;\nusing modint1000000007 = static_modint<1000000007>;\nusing modint = dynamic_modint<-1>;\n \nnamespace internal {\n \ntemplate <class T>\nusing is_static_modint = std::is_base_of<internal::static_modint_base, T>;\n \ntemplate <class T>\nusing is_static_modint_t = std::enable_if_t<is_static_modint<T>::value>;\n \ntemplate <class> struct is_dynamic_modint : public std::false_type {};\ntemplate <int id>\nstruct is_dynamic_modint<dynamic_modint<id>> : public std::true_type {};\n \ntemplate <class T>\nusing is_dynamic_modint_t = std::enable_if_t<is_dynamic_modint<T>::value>;\n \n}  // namespace internal\n \n}  // namespace atcoder\n \nusing namespace std;\nusing namespace atcoder;\n \nusing mint = modint1000000007;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    auto C3 = [&](int n) { return mint(n) * (n - 1) * (n - 2) / 6; };\n    while (t--) {\n        int n, m; cin >> n >> m;\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n        sort(a.begin(), a.end());\n        mint ans = C3(m + 1);\n        for (int i = 0; i < n; i++) {\n            int dis = (a[(i + 1) % n] - a[i] + m) % m;\n            if (dis == 0) {\n                dis = m;\n            }\n            ans -= C3(dis + 1);\n        }\n        ans = ans * n / m;\n        cout << ans.val() << '\\n';\n    }\n}",
    "tags": [
      "combinatorics",
      "math",
      "probabilities"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1951",
    "index": "H",
    "title": "Thanos Snap",
    "statement": "\\begin{quote}\nPiotr Rubik - Psalm dla Ciebie\n\\hfill ඞ\n\\end{quote}\n\nThere is an array $a$ of size $2^k$ for some positive integer $k$, which is initially a permutation of values from $1$ to $2^k$. Alice and Bob play the following game on the array $a$. First, a value $t$ between $1$ and $k$ is shown to both Alice and Bob. Then, for exactly $t$ turns, the following happens:\n\n- Alice either does nothing, or chooses two distinct elements of the array $a$ and swaps them.\n- Bob chooses either the left half or the right half of the array $a$ and erases it.\n\nThe score of the game is defined as the maximum value in $a$ after all $t$ turns have been played. Alice wants to maximize this score, while Bob wants to minimize it.\n\nYou need to output $k$ numbers: the score of the game if both Alice and Bob play optimally for $t$ from $1$ to $k$.",
    "tutorial": "Let $n = 2^k$. Let's see how we can solve for each $t$ first. We binary search on the answer, which results in every element being either $0$ or $1$ depending on if it's larger than the threshold, and we now need to check if the answer is $0$ or $1$. Let's instead try to directly construct Alice's strategy to achieve $1$; if we cannot construct such a strategy, the answer is $0$. The main idea here is that Alice's strategy can be represented as a perfect binary tree with $t + 1$ layers, where: Every leaf node represents a subarray of $a$ of size $2^{n - t}$. Every non-leaf node represents Alice's next action when the game is restricted to the subarray $[l, r]$ covered by this node; such an action is in the form \"swap $a_i$ and $a_j$\", where $l \\le i \\le j \\le r$. Some trivial observations: For Alice to win, we would want every leaf node to have at least one value $1$ when the game reaches that leaf node. We say a leaf is deficient if it originally did not satisfy this condition. Every leaf node that has more than one value $1$ can \"donate\" the extra $1$'s via the swapping action. If an action can be performed by Alice in a node, it can also be performed in any of its ancestors. The third observation motivates us to look for a greedy bottom-up construction of Alice's strategy. Combining with the first two observations, we get the following greedy construction: For every node, maintain the number of deficient leaves and the number of extra $1$'s that can be donated from other leaves. At any non-leaf node, we try to match an extra $1$ with a deficient leaf (if both quantities are more than $0$), and we propagate the remaining deficient leaves and extra $1$'s to the node's parent. Alice wins if at the root node, the number of deficient leaves remaining is $0$. This strategy can be implemented in time $O((n + 2^t) \\log n)$ or $O(n + 2^t \\log n)$ depending on implementation (to get the second complexity, note that while binary searching, the total number of element status changes between $0$ and $1$ is $O(n)$). This gives us a complexity of $O(n \\log^2 n)$ or $O(n \\log n)$ after looping through all $t$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nbool solve(vector<int>& v) {\n    int n = v.size();\n    vector<int> a(n), b(n);\n    for (int i = 0; i < n; ++i) a[i] = max(1 - v[i], 0), b[i] = max(0, v[i] - 1);\n    for (; n > 1; n /= 2) {\n        for (int i = 0; i < n; i += 2) {\n            a[i / 2] = a[i] + a[i + 1];\n            b[i / 2] = b[i] + b[i + 1];\n            if (a[i / 2] && b[i / 2]) a[i / 2]--, b[i / 2]--;\n        }\n        a.resize(n / 2); b.resize(n / 2);\n    }\n    return a[0] == 0;\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int te; cin >> te;\n    while (te--) {\n        int k; cin >> k;\n        vector<int> pos(1 << k);\n        for (int i = 0; i < (1 << k); i++) {\n            int u; cin >> u; u--;\n            pos[u] = i;\n        }\n        for (int t = 1; t <= k; t++) {\n            vector<int> v(1 << t);\n            int le = 0, ri = (1 << k);\n            while (le + 1 < ri) {\n                int mi = (le + ri) / 2;\n                for (int i = mi; i < ri; i++) {\n                    v[pos[i] >> (k - t)]++;\n                }\n                (solve(v) ? le : ri) = mi;\n                for (int i = mi; i < ri; i++) {\n                    v[pos[i] >> (k - t)]--;\n                }\n            }\n            cout << ri << \" \\n\"[t == k];\n        }\n    }\n}",
    "tags": [
      "binary search",
      "dp",
      "games",
      "greedy",
      "trees"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1951",
    "index": "I",
    "title": "Growing Trees",
    "statement": "\\begin{quote}\nwowaka ft. Hatsune Miku - Ura-Omote Lovers\n\\hfill ඞ\n\\end{quote}\n\nYou are given an undirected connected simple graph with $n$ nodes and $m$ edges, where edge $i$ connects node $u_i$ and $v_i$, with two positive parameters $a_i$ and $b_i$ attached to it. Additionally, you are also given an integer $k$.\n\nA non-negative array $x$ with size $m$ is called a $k$-spanning-tree generator if it satisfies the following:\n\n- Consider the undirected multigraph with $n$ nodes where edge $i$ is cloned $x_i$ times (i.e. there are $x_i$ edges connecting $u_i$ and $v_i$). It is possible to partition the edges of this graph into $k$ spanning trees, where each edge belongs to exactly one spanning tree$^\\dagger$.\n\nThe cost of such array $x$ is defined as $\\sum_{i = 1}^m a_i x_i^2 + b_i x_i$. Find the minimum cost of a $k$-spanning-tree generator.\n\n$^\\dagger$ A spanning tree of a (multi)graph is a subset of the graph's edges that form a tree connecting all vertices of the graph.",
    "tutorial": "From now on, we say an array $x$ to be good if the graph created by cloning the $i$-th edge $x_i$ times can be partitioned into $k$ forests (this is slightly different from $k$-spanning-tree generators). Let's first discuss how to check whether an array $x$ is good. Let $G'$ be the graph created by cloning the $i$-th edge $x_i$ times. By Nash-Williams theorem, for every subset of vertices $U$, we need the induced subgraph $G'[U]$ to have at most $k(|U| - 1)$ edges, so it suffices to check this condition quickly. Furthermore, this condition can easily be modified to $k$-spanning-tree generators: the only additional condition necessary is to have $\\sum_{i=1}^m x_i = k(n - 1)$. Consider the unweighted bipartite graph $B_{G'}$ where every left node represents a node $u$ of $G'$, every right node represents an edge $(u, v)$ of $G'$, and we connect edges $u - (u, v)$ and $v - (u, v)$ for every right node $(u, v)$, then Hall's marriage theorem states that $B_{G'}$ has a right-saturating matching iff the induced subgraph $G'[U]$ has at most $|U|$ edges for all $U$. We can further extend this idea by making $k$ clones of every left node $u$, which now means that the $B_{G'}$ has a right-saturating matching iff $|G'[U]| \\le k |U|$ for all $U$. The big last idea is to try \"turning off\" a left node $u$: formally, consider $B_{G', u}$ be the same as $B_{G'}$, but all clones of some left node $u$ are deleted, and note that this graph enforces the condition $|G'[U']| \\le k(|U'| - 1)$ for every subset $U'$ containing $u$. Therefore, by checking if $B_{G', u}$ has a right-saturating matching matching for all $u$, we can now ensure the Nash-Williams condition. Finally, note that we can quickly check if $B_{G', u}$ has a right-saturating matching by constructing the following directed graph: direct an edge from the source node to every left node $v \\neq u$ with capacity $k$, direct an edge from every right node $(u_i, v_i)$ to the sink node with capacity $x_i$, and direct an edge from left node $u_i$ (or $v_i$) to right node $(u_i, v_i)$ with capacity $\\infty$; $B_{G', u}$ has a perfect matching iff this new graph has a flow from source to sink that saturates all incoming edges to sink. As the constructed flow graph has $O(n + m)$ nodes and edges, we now know how to check if an array $x$ is good in time complexity $O(n \\cdot F(n + m, n + m))$, where $F(N, M)$ is the complexity to run max flow on a graph with $N$ nodes and $M$ edges. We now return to the original problem. Observe that the cost function is convex on every coordinate $x_i$; hence, one could imagine the following greedy strategy: starts with $x = 0$; until the sum of $x_i$ reaches $k(n - 1)$, try to find a coordinate $i$ and increases $x_i$ by $1$ such that increasing $x_i$ by $1$ doesn't make $x$ bad, and increasing $x_i$ by $1$ increases the cost by as little as possible. It turns out that this strategy works, as the set of all good arrays forms a \"matroid\", and $k$-spanning-tree generators are the \"bases\" of this \"matroid\" (note that the greedy algorithm guarantees to find the min-weight basis of a matroid). To be more formal, consider a set of elements $E$, where each element denoted by a pair $(i, t)$ represents the clone of the edge $i$ with cost $(a_i t^2 + b_i t) - (a_i (t-1)^2 + b_i(t - 1))$, and a subset $E' \\subseteq E$ is independent if the multiset edges represented by elements in $E'$ can be partitioned into $k$ forests (here, we let $i \\in [1, n]$ and $t \\in [1, k]$). Observe that this set $E$ forms a matroid (we can think of $E$ as a \"permuted\" direct sum of $k$ disjoint versions of the graphic matroids on $G$, and note that direct sums of matroids are themselves matroid). Furthermore, the weight of element $(i, t)$ represents exactly the increment to the cost when we increase $x_i$ from $t - 1$ to $t$. By convexity of the cost on each edge, the weight of $(i, t)$ is less than the weight of $(i, t + 1)$. Hence the min-cost $k$-spanning-tree generator represents exactly the min-weight basis of $E$, as the basis would greedily use $(i, j)$ with $j$ being as small as possible. Finally, while this greedy algorithm is correct, we still need to optimize it as the number of steps is $k(n - 1)$. Observe that if at some step, increasing a coordinate $i$ makes $x$ bad, we would never consider coordinate $i$ again at later steps of the algorithm. Therefore, we can effectively simulate the greedy algorithm by 1) finding the first step where a coordinate $i$ turns bad, 2) advancing until such step, 3) discarding coordinate $i$ from consideration, and 4) repeating until every coordinate turns bad. Fortunately, step 1) can be quickly implemented by binary searching on the cost of the increment, and the number of iterations is $m$ as every coordinate can only be discarded once. Therefore, the problem has been solved in time complexity of either $O(m \\cdot (\\log W + m) \\cdot n \\cdot F(n + m, n + m))$, $O(m \\cdot \\log mW \\cdot n \\cdot F(n + m, n + m))$, or $O(m \\cdot \\log W \\cdot n \\cdot F(n + m, n + m) + m^2 n^2)$ depending on how you break ties on the same cost increment (note that we can ensure no ties by adding $\\epsilon i$ to $x_i$), where $W \\le 2 k \\cdot \\max a + \\max b$ is the maximum cost increment.",
    "code": "#include <bits/stdc++.h>\n \n#include <algorithm>\n#include <cassert>\n#include <limits>\n#include <queue>\n#include <vector>\n \n \n#include <vector>\n \nnamespace atcoder {\n \nnamespace internal {\n \ntemplate <class T> struct simple_queue {\n    std::vector<T> payload;\n    int pos = 0;\n    void reserve(int n) { payload.reserve(n); }\n    int size() const { return int(payload.size()) - pos; }\n    bool empty() const { return pos == int(payload.size()); }\n    void push(const T& t) { payload.push_back(t); }\n    T& front() { return payload[pos]; }\n    void clear() {\n        payload.clear();\n        pos = 0;\n    }\n    void pop() { pos++; }\n};\n \n}  // namespace internal\n \n}  // namespace atcoder\n \n \nnamespace atcoder {\n \ntemplate <class Cap> struct mf_graph {\n  public:\n    mf_graph() : _n(0) {}\n    explicit mf_graph(int n) : _n(n), g(n) {}\n \n    int add_edge(int from, int to, Cap cap) {\n        assert(0 <= from && from < _n);\n        assert(0 <= to && to < _n);\n        assert(0 <= cap);\n        int m = int(pos.size());\n        pos.push_back({from, int(g[from].size())});\n        int from_id = int(g[from].size());\n        int to_id = int(g[to].size());\n        if (from == to) to_id++;\n        g[from].push_back(_edge{to, to_id, cap});\n        g[to].push_back(_edge{from, from_id, 0});\n        return m;\n    }\n \n    struct edge {\n        int from, to;\n        Cap cap, flow;\n    };\n \n    edge get_edge(int i) {\n        int m = int(pos.size());\n        assert(0 <= i && i < m);\n        auto _e = g[pos[i].first][pos[i].second];\n        auto _re = g[_e.to][_e.rev];\n        return edge{pos[i].first, _e.to, _e.cap + _re.cap, _re.cap};\n    }\n    std::vector<edge> edges() {\n        int m = int(pos.size());\n        std::vector<edge> result;\n        for (int i = 0; i < m; i++) {\n            result.push_back(get_edge(i));\n        }\n        return result;\n    }\n    void change_edge(int i, Cap new_cap, Cap new_flow) {\n        int m = int(pos.size());\n        assert(0 <= i && i < m);\n        assert(0 <= new_flow && new_flow <= new_cap);\n        auto& _e = g[pos[i].first][pos[i].second];\n        auto& _re = g[_e.to][_e.rev];\n        _e.cap = new_cap - new_flow;\n        _re.cap = new_flow;\n    }\n \n    Cap flow(int s, int t) {\n        return flow(s, t, std::numeric_limits<Cap>::max());\n    }\n    Cap flow(int s, int t, Cap flow_limit) {\n        assert(0 <= s && s < _n);\n        assert(0 <= t && t < _n);\n        assert(s != t);\n \n        std::vector<int> level(_n), iter(_n);\n        internal::simple_queue<int> que;\n \n        auto bfs = [&]() {\n            std::fill(level.begin(), level.end(), -1);\n            level[s] = 0;\n            que.clear();\n            que.push(s);\n            while (!que.empty()) {\n                int v = que.front();\n                que.pop();\n                for (auto e : g[v]) {\n                    if (e.cap == 0 || level[e.to] >= 0) continue;\n                    level[e.to] = level[v] + 1;\n                    if (e.to == t) return;\n                    que.push(e.to);\n                }\n            }\n        };\n        auto dfs = [&](auto self, int v, Cap up) {\n            if (v == s) return up;\n            Cap res = 0;\n            int level_v = level[v];\n            for (int& i = iter[v]; i < int(g[v].size()); i++) {\n                _edge& e = g[v][i];\n                if (level_v <= level[e.to] || g[e.to][e.rev].cap == 0) continue;\n                Cap d =\n                    self(self, e.to, std::min(up - res, g[e.to][e.rev].cap));\n                if (d <= 0) continue;\n                g[v][i].cap += d;\n                g[e.to][e.rev].cap -= d;\n                res += d;\n                if (res == up) return res;\n            }\n            level[v] = _n;\n            return res;\n        };\n \n        Cap flow = 0;\n        while (flow < flow_limit) {\n            bfs();\n            if (level[t] == -1) break;\n            std::fill(iter.begin(), iter.end(), 0);\n            Cap f = dfs(dfs, t, flow_limit - flow);\n            if (!f) break;\n            flow += f;\n        }\n        return flow;\n    }\n \n    std::vector<bool> min_cut(int s) {\n        std::vector<bool> visited(_n);\n        internal::simple_queue<int> que;\n        que.push(s);\n        while (!que.empty()) {\n            int p = que.front();\n            que.pop();\n            visited[p] = true;\n            for (auto e : g[p]) {\n                if (e.cap && !visited[e.to]) {\n                    visited[e.to] = true;\n                    que.push(e.to);\n                }\n            }\n        }\n        return visited;\n    }\n \n  private:\n    int _n;\n    struct _edge {\n        int to, rev;\n        Cap cap;\n    };\n    std::vector<std::pair<int, int>> pos;\n    std::vector<std::vector<_edge>> g;\n};\n \n}  // namespace atcoder\n \nusing namespace std;\nusing namespace atcoder;\n \nconst int64_t INF = 1E13 + 100;\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        int n, m, k; cin >> n >> m >> k;\n        vector<array<int, 4>> edg(m);\n        vector<int64_t> lim(m, INF);\n        for (auto& [u, v, a, b] : edg) {\n            cin >> u >> v >> a >> b; u--; v--;\n        }\n        auto initialize_counts = [&](int64_t thr) {\n            vector<int64_t> cnt(m);\n            for (int i = 0; i < m; i++) {\n                int a = edg[i][2], b = edg[i][3];\n                int64_t val = (thr - i) / m;\n                // a * (2c - 1) + b <= thr\n                cnt[i] = max(0LL, min(lim[i], ((val - b) / a + 1) / 2));\n            }\n            return cnt;\n        };\n        auto check = [&](int64_t thr) {\n            auto cnt = initialize_counts(thr);\n            mf_graph<int64_t> b(n + m + 3);\n            int src = 0, snk = 1;\n            auto vertex = [&](int u) { return u + 2; };\n            auto edge = [&](int i) { return i + n + 2; };\n            for (int i = 0; i < n; i++) {\n                b.add_edge(src, vertex(i), k);\n            }\n            int64_t sum = 0;\n            for (int i = 0; i < m; i++) {\n                int u = edg[i][0], v = edg[i][1];\n                b.add_edge(vertex(u), edge(i), INF);\n                b.add_edge(vertex(v), edge(i), INF);\n                b.add_edge(edge(i), snk, cnt[i]);\n                sum += cnt[i];\n            }\n            if (b.flow(src, snk) < sum) {\n                return false;\n            }\n            for (int i = 0; i < n; i++) {\n                auto bi = b;\n                bi.add_edge(vertex(i), snk, k);\n                if (bi.flow(src, snk) < k) {\n                    return false;\n                }\n            }\n            return true;\n        };\n        int64_t low = 0;\n        for (int lft = m; lft > 0; lft--) {\n            int64_t hig = INF;\n            while (low + 1 < hig) {\n                int64_t mid = (low + hig) / 2;\n                (check(mid) ? low : hig) = mid;\n            }\n            int bad = (low + 1) % m;\n            auto [u_, v_, a, b] = edg[bad];\n            int64_t val = (low - bad) / m;\n            lim[bad] = ((val - b) / a + 1) / 2;\n            low++;\n        }\n        int64_t ans = 0;\n        for (int i = 0; i < m; i++) {\n            int a = edg[i][2], b = edg[i][3];\n            ans += lim[i] * lim[i] * a + lim[i] * b;\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "flows",
      "graphs",
      "greedy"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1954",
    "index": "A",
    "title": "Painting the Ribbon",
    "statement": "Alice and Bob have bought a ribbon consisting of $n$ parts. Now they want to paint it.\n\nFirst, Alice will paint every part of the ribbon into one of $m$ colors. For each part, she can choose its color arbitrarily.\n\nThen, Bob will choose \\textbf{at most $k$} parts of the ribbon and repaint them \\textbf{into the same color} (he chooses the affected parts and the color arbitrarily).\n\nBob would like all parts to have the same color. However, Alice thinks that this is too dull, so she wants to paint the ribbon in such a way that Bob cannot make all parts have the same color.\n\nIs it possible to paint the ribbon in such a way?",
    "tutorial": "When is Bob able to get a ribbon where each part has color $i$? There should be at least $n-k$ parts of color $i$. So if the number of parts with color $i$ is less than $n-k$, Bob cannot repaint the whole ribbon into color $i$. So, Alice has to paint the ribbon in such a way that for every color, there are at most $n-k-1$ parts of that color. There are at least two ways to check if it is possible: for example, you can calculate the maximum possible length of the ribbon such that it contains no more than $n-k-1$ parts of every color; or you can calculate the maximum number of parts among all colors if you try to color the ribbon as evenly as possible.",
    "code": "t = int(input())\nfor i in range(t):\n    n, m, k = map(int, input().split())\n    max_color = (n + m - 1) / m\n    if max_color + k >= n:\n        print('NO')\n    else:\n        print('YES')",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1954",
    "index": "B",
    "title": "Make It Ugly",
    "statement": "Let's call an array $a$ beautiful if you can make all its elements the same by using the following operation an arbitrary number of times (possibly, zero):\n\n- choose an index $i$ ($2 \\le i \\le |a| - 1$) such that $a_{i - 1} = a_{i + 1}$, and replace $a_i$ with $a_{i - 1}$.\n\nYou are given a beautiful array $a_1, a_2, \\dots, a_n$. What is the minimum number of elements you have to remove from it in order for it to stop being beautiful? Swapping elements is prohibited. If it is impossible to do so, then output -1.",
    "tutorial": "As given in the problem statement, the definition of a beautiful array is not very interesting to us, since checking the beauty of an array is quite complex. Let's try to simplify it. First of all, the first and last elements will never be changed, as it is impossible to choose such $i$ for operations. If they are different, then the array is definitely not beautiful. Moreover, if the array is beautiful, then all its elements at the end will be equal to the first and the last elements. The second idea is a bit more complicated. Notice that each element can be changed at most once. Consider an arbitrary operation. We choose some $i$ for which $a_{i - 1} = a_{i + 1}$, and change $a_i$ to $a_{i - 1}$. Now both $a_{i - 1}$ and $a_{i + 1}$ will always remain equal to their current values, because in any operation involving them, $a_i$ will also be involved. This means that $a_i$ will also remain equal to the new value. The next idea is as follows. We know what all the elements should be equal to in the end. This means that we need to apply operations to all elements that are not equal to this value. According to the previous idea, this is possible if and only if there are no two consecutive numbers in the array that are not equal to this value. The sufficiency of this condition is obvious, and the necessity is left as an exercise to the reader. In other words, the check looks like this: $a_1 = a_n$, and $a_i = a_1$ or $a_{i + 1} = a_1$ (or both are equal) for all $i$. What elements should be removed so that the check does not pass? There are two options: break the first or second condition. So, you can do the following: remove the entire prefix of numbers equal to $a_1$; remove the entire suffix of numbers equal to $a_1$ (or $a_n$ - they are equal to each other, since the given array is beautiful); choose two numbers that are not equal to $a_1$, and remove all the numbers between them, so that these two numbers become adjacent. The third condition can be simplified. If other numbers not equal to $a_1$ are encountered between the selected numbers, then another pair can be chosen, for which fewer numbers have to be removed. Therefore, it is only optimal to choose a pair for which all the numbers between them are equal to $a_1$. Then the solution is as follows. Find the shortest block of numbers equal to $a_1$. Remove it from the array. It can be at the prefix or at the suffix - then the first condition will be broken. Or it can be somewhere in the middle - then the second condition will be broken. To find such a block, you can go through the array from left to right, maintaining the position of the previous element not equal to $a_1$. If the current element is not equal to $a_1$, update the answer with the difference between the saved and current positions, and update the saved position. The only case when the answer is -1 is when all the elements of the array are the same. Otherwise, it is always possible to make the array not beautiful. Overall complexity: $O(n)$ for each testcase.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    lst = -1\n    ans = n\n    for i in range(n):\n        if a[i] != a[0]:\n            ans = min(ans, i - lst - 1)\n            lst = i\n    ans = min(ans, n - lst - 1)\n    if ans == n:\n        print(-1)\n    else:\n        print(ans)",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1954",
    "index": "C",
    "title": "Long Multiplication",
    "statement": "You are given two integers $x$ and $y$ of the same length, consisting of digits from $1$ to $9$.\n\nYou can perform the following operation any number of times (possibly zero): swap the $i$-th digit in $x$ and the $i$-th digit in $y$.\n\nFor example, if $x=73$ and $y=31$, you can swap the $2$-nd digits and get $x=71$ and $y=33$.\n\nYour task is to maximize the product of $x$ and $y$ using the aforementioned operation any number of times. If there are multiple answers, print any of them.",
    "tutorial": "There are two observations to solve the problem: applying the operation does not change the sum of the numbers; the smaller the difference of the numbers, the greater their product (the proof is given below). Proof: let's denote the sum of the numbers as $s$, the smallest number as $\\frac{s}{2} - a$ and the largest number as $\\frac{s}{2} + a$. Then the product is equal to $\\left(\\frac{s}{2} - a\\right)\\left(\\frac{s}{2} + a\\right) = \\left(\\frac{s}{2}\\right)^2 - a^2$. We can see that, the smaller $a$ (the half of difference), the larger the product. In order to get the minimum difference, we can use the following algorithm: let $i$ be the smallest index (the most significant digit) such that $x_i \\ne y_i$ and set the maximum digit among $x_i$ and $y_i$ to the number $x$ and smallest to the number $y$; thus $x$ is definitely greater than $y$, then the less significant digits should be the maximum possible for the number $y$ (i. e. the inequality $x_j \\le y_j$ must hold for all $j > i$).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    string x, y;\n    cin >> x >> y;\n    int n = x.size();\n    bool f = false;\n    for (int i = 0; i < n; ++i) {\n      if ((x[i] > y[i]) == f) swap(x[i], y[i]);\n      f |= (x[i] != y[i]);\n    }\n    cout << x << '\\n' << y << '\\n';\n  }\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1954",
    "index": "D",
    "title": "Colored Balls",
    "statement": "There are balls of $n$ different colors; the number of balls of the $i$-th color is $a_i$.\n\nThe balls can be combined into groups. Each group should contain at most $2$ balls, and no more than $1$ ball of each color.\n\nConsider all $2^n$ sets of colors. For a set of colors, let's denote its value as the minimum number of groups the balls of those colors can be distributed into. For example, if there are three colors with $3$, $1$ and $7$ balls respectively, they can be combined into $7$ groups (and not less than $7$), so the value of that set of colors is $7$.\n\nYour task is to calculate the sum of values over all $2^n$ possible sets of colors. Since the answer may be too large, print it modulo $998\\,244\\,353$.",
    "tutorial": "For a fixed set of colors, this is a standard problem with the following solution: let's denote the total number of balls as $s$, then the value of the set is $\\left\\lceil\\frac{s}{2}\\right\\rceil$; but there is an exception in the case when there is a color with more than $\\frac{s}{2}$ balls, then the value is the number of balls of this color. So the answer depends only on whether there is a color that has more balls than all the others combined. Using the aforementioned fact, we can come up with the following solution: let's iterate over the total number of balls in the set (denote it as $j$) and increase the answer by $\\left\\lceil\\frac{j}{2}\\right\\rceil$ for each subset of colors with exactly $j$ balls in it. The number of subsets with the fixed number of balls can be calculated using simple knapsack dynamic programming. It remains to consider the subsets of colors with a \"dominant\" color, because we added the wrong value to the answer for them. Let the \"dominant\" color be $i$ and the total number of balls in all other colors be $j$ ($j < a_i$). The answer should be increased by $a_i - \\left\\lceil\\frac{a_i + j}{2}\\right\\rceil$ (the correct value of this set is $a_i$, but we have already added the wrong value in the answer - $\\left\\lceil\\frac{a_i + j}{2}\\right\\rceil$, so we should compensate it) for each subset of colors with exactly $j$ balls in it (we can use the same dp as in previous case). Note that if you consider only $j < a_i$, you don't have to deal with the possibility that the \"dominant\" color could already be included in the subset. This solution works in $O(nS)$ time, where $S$ is the total number of balls.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\n \nint add(int x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n  return x;\n} \n \nint mul(int x, int y) {\n  return x * 1LL * y % MOD;\n}\n \nint main() {\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  for (int i = 0; i < n; ++i) cin >> a[i];\n  int s = accumulate(a.begin(), a.end(), 0);\n  vector<int> dp(s + 1);\n  dp[0] = 1;\n  for (int i = 0; i < n; ++i)\n    for (int j = s - a[i]; j >= 0; --j) \n      dp[j + a[i]] = add(dp[j + a[i]], dp[j]);\n  int ans = 0;\n  for (int j = 0; j <= s; ++j) \n    ans = add(ans, mul((j + 1) / 2, dp[j]));\n  for (int i = 0; i < n; ++i)\n    for (int j = 0; j < a[i]; ++j) \n      ans = add(ans, mul(a[i] - (a[i] + j + 1) / 2, dp[j]));\n  cout << ans << '\\n';\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1954",
    "index": "E",
    "title": "Chain Reaction",
    "statement": "There are $n$ monsters standing in a row. The $i$-th monster has $a_i$ health points.\n\nEvery second, you can choose one \\textbf{alive} monster and launch a chain lightning at it. The lightning deals $k$ damage to it, and also spreads to the left (towards decreasing $i$) and to the right (towards increasing $i$) to \\textbf{alive} monsters, dealing $k$ damage to each. When the lightning reaches a dead monster or the beginning/end of the row, it stops. A monster is considered alive if its health points are strictly greater than $0$.\n\nFor example, consider the following scenario: there are three monsters with health equal to $[5, 2, 7]$, and $k = 3$. You can kill them all in $4$ seconds:\n\n- launch a chain lightning at the $3$-rd monster, then their health values are $[2, -1, 4]$;\n- launch a chain lightning at the $1$-st monster, then their health values are $[-1, -1, 4]$;\n- launch a chain lightning at the $3$-rd monster, then their health values are $[-1, -1, 1]$;\n- launch a chain lightning at the $3$-th monster, then their health values are $[-1, -1, -2]$.\n\nFor each $k$ from $1$ to $\\max(a_1, a_2, \\dots, a_n)$, calculate the minimum number of seconds it takes to kill all the monsters.",
    "tutorial": "Let's solve the problem for a single $k$. We'll start with $k = 1$ for simplicity. The first lightning can be launched at any monster, as it will always spread to all of them. We will continue launching lightnings until a monster dies. When one or more monsters die, the problem breaks down into several independent subproblems, because no lightning will pass through dead monsters. This means that there is no concept of \"minimum number of seconds\" - the answer does not depend on the choice of monsters to launch the lightnings. Great, so how do we calculate this answer? The idea is as follows. We will attack the first monster until it dies. This will take $a_1$ seconds. We then move on to the second monster. If it has more health than the first one, we need to launch an additional $a_2 - a_1$ lightnings to kill it. Otherwise, it will already be dead. How much damage will the third monster receive in both cases? Let's say it has a lot of health. In the first case, it will receive $a_2$ damage, because all the lightnings will reach it. But in the second case, it will also receive $a_2$ damage, because the lightnings launched at the first monster after the death of the second one will not reach the third one. This means that we now need to compare the health of the second monster with the third one in the same way. And so on. This means that the $i$-th monster needs to be hit with $\\max(0, a_i - a_{i - 1})$ lightnings. Then the answer for $k = 1$ is equal to $a_1 + \\sum\\limits_{i = 2}^{n} \\max(0, a_i - a_{i - 1})$. How to calculate the answer for any $k$? In fact, the difference is not very significant. It is sufficient to change the health of each monster from $a_i$ to $\\lceil \\frac{a_i}{k} \\rceil$, and the entire process described earlier will remain the same. Therefore, the answer for any $k$ is equal to $\\lceil \\frac{a_1}{k} \\rceil + \\sum\\limits_{i = 2}^{n} \\max(0, \\lceil \\frac{a_i}{k} \\rceil - \\lceil \\frac{a_{i - 1}}{k} \\rceil)$. To further optimize this solution, another transformation is needed. Ideally, we would like each $a_i$ to contribute to the answer independently of other values. And this can almost be achieved. Notice that the maximum returns $0$ only if $a_i < a_{i - 1}$ for any $k$, not just for $k = 1$. This may require proof, but it is quite obvious. This means that the coefficient for $\\lceil \\frac{a_i}{k} \\rceil$ in the answer depends on two conditions: it is increased by $1$ if $i = 1$ or $a_i \\ge a_{i - 1}$; it is decreased by $1$ if $i < n$ and $a_i < a{i + 1}$. Let's call this coefficient for the $i$-th monster $c_i$. Therefore, we need to calculate $\\sum\\limits_{i = 1}^n c_i \\cdot \\lceil \\frac{a_i}{k} \\rceil$. There are two ways to optimize the solution further. The first option is to notice that $\\lceil \\frac{a_i}{k} \\rceil$ doesn't take a lot of different values for different $k$. More precisely, it is $O(\\sqrt{a_i})$. This can be shown as follows. Consider $\\lceil \\frac{a_i}{k} \\rceil = x$. Either $k \\le \\sqrt{a_i}$, or $x \\le \\sqrt{a_i}$. Therefore, $x$ takes no more than $2 \\sqrt{a_i}$ different values. Then the solution can be implemented as follows. For each $a_i$, we will identify all possible values that the rounding result takes. For each of them, we will find the range of $k$ for which the result is equal to that. And we will add the contribution of the $i$-th monster within this range of values to the result. This can be done using a difference array to achieve a complexity of $O(n \\cdot \\sqrt{A})$. The second option is a bit smarter. Let's take another look at the formula for calculating the answer for a fixed $k$: $\\sum\\limits_{i = 1}^n c_i \\cdot \\lceil \\frac{a_i}{k} \\rceil$. Let's group the terms by equal values of $\\lceil \\frac{a_i}{k} \\rceil$. What do they look like? Numbers from $1$ to $k$ give the value $1$. Numbers from $k + 1$ to $2k$ give the value $2$, and so on. This means that for a certain $k$, there are $\\frac{A}{k}$ segments, on each of which we need to calculate the sum of $c_i$ for those $i$ for which $a_i$ fall into this segment. The total number of segments for all $k$ is $O(A \\log A)$. The complexity of the solution will then be $O(n + A \\log A)$.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nint main() {\n    cin.tie(0);\n    ios::sync_with_stdio(false);\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    forn(i, n) cin >> a[i];\n    int mx = *max_element(a.begin(), a.end());\n    vector<long long> pr(mx + 1);\n    forn(i, n){\n        int coef = 0;\n        if (i == 0 || a[i] > a[i - 1]) ++coef;\n        if (i + 1 < n && a[i] < a[i + 1]) --coef;\n        pr[a[i]] += coef;\n    }\n    forn(i, mx) pr[i + 1] += pr[i];\n    for (int k = 1; k <= mx; ++k){\n        long long ans = 0;\n        for (int l = 1, val = 1; l <= mx; l += k, ++val)\n            ans += val * 1ll * (pr[min(mx, l + k - 1)] - pr[l - 1]);\n        cout << ans << ' ';\n    }\n    cout << '\\n';\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dsu",
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1954",
    "index": "F",
    "title": "Unique Strings",
    "statement": "Let's say that two strings $a$ and $b$ are \\textbf{equal} if you can get the string $b$ by cyclically shifting string $a$. For example, the strings 0100110 and 1100100 are equal, while 1010 and 1100 are not.\n\nYou are given a binary string $s$ of length $n$. Its first $c$ characters are 1-s, and its last $n - c$ characters are 0-s.\n\nIn one operation, you can replace one 0 with 1.\n\nCalculate the number of unique strings you can get using no more than $k$ operations. Since the answer may be too large, print it modulo $10^9 + 7$.",
    "tutorial": "What's common in all strings we can get: each string has no more than $c + k$ ones and at least $c$ consecutive ones. So let's loosen up our constraints a little and just calculate the number of strings with no more than $c + k$ ones and at least $c$ consecutive ones, i. e. this block of ones can be anywhere, can even start at the end and continue at the beginning. Let's name such strings as good strings. Note that the number of unique good strings is exactly equal to the answer of the initial task, since we can shift each good string and make it start from the block of ones. How to calculate the number of good strings? Using Burnside's lemma! Since the group of transformations is just a group of cyclic shifts, we can calculate the answer as following $\\mathrm{ans} = \\frac{1}{n} \\sum_{i=1}^{n}{\\mathrm{FixedPoints}(i)}$ Note that if the string doesn't change while shifting by $i$ characters, then it means that $s[p] = s[(p + i) \\mod |s|]$ for all $p$. Further investigation reveals that all characters will be split into exactly $g = \\gcd(i, n)$ groups and each group will contain exactly $\\frac{n}{g}$ equal characters. It means that if $\\gcd(i, n) = \\gcd(j, n)$ then $\\mathrm{FixedPoints}(i) = \\mathrm{FixedPoints}(j)$ since in both cases we'll get exactly the same group division. So, we can rewrite the answer as following: $\\mathrm{ans} = \\frac{1}{n} \\sum_{g | n}{cnt[g] \\cdot \\mathrm{FixedPoints}(g)}$ So, it's time to calculate $\\mathrm{FixedPoints}(g)$ for some divisor $g$ of $n$. It's not hard to see that if $s[p] = s[(p + g) \\mod |s|]$ then the first $g$ characters of $s$ will uniquely define the whole string $s$. So it's enough to work with only a prefix of length $g$, remembering that each character will be copied $\\frac{n}{g}$ times. Remember that a good string is a string with at most $c + k$ ones, and since each character will be copied $\\frac{n}{g}$ times, we can place at most $on = \\frac{(c + k) g}{n}$ ones in our prefix (or at least $zr = g - on$ zeroes). Also, since a good string has $c$ consecutive ones, our prefix should also have $c$ consecutive ones, including the case where the ones go \"cyclically\" starting at the end of the prefix. In case if $c \\ge g$ then the whole prefix should consist of ones, and it's either possible (if $c + k = n$) or impossible (if $c + k < n$). In case $c < g$ we need to calculate the number of good prefixes that can be described as \"the cyclic strings of length $g$ that has no more than $on$ ones and contains $c$ consecutive ones\". Instead of good prefixes, let's calculate bad prefixes and subtract them from all possible prefixes. All prefixes are just strings with at most $on$ ones and there are $all = \\sum\\limits_{i=0}^{on}{\\binom{g}{i}}$ such strings. Bad prefixes are cyclic strings with at most $on$ ones, where all blocks of ones have length less than $c$. In order to calculate bad prefixes, let's precalc the following dp: $d[z][l]$ is the number of strings of length $l$ with $z$ zeroes where all blocks of ones have length less than $c$ and the last character of the string is $0$. Why did we use the number of zeroes in the state, and why did we add the last zero in $d[z][l]$? Because it will help us to calculate dp fast. $d[0][0] = 1$. Now, if we have value $d[z][l]$, we can add a block of $i$ ones ($0 \\le i < c$) and zero to the end of the string and update the value in $d[z + 1][l + i + 1]$. Note that we are updating a segment of row $z + 1$ from $l + 1$ to $l + c$ with value $d[z][l]$ - we can do it in $O(1)$. So, we can precalc the whole dp in $O(n^2)$ time. Now, it's time to calculate the number of bad strings: if we iterate over the length of the prefix of ones, length of the suffix of ones and the number of zeroes in between, we'll get $bad = \\sum_{p=0}^{c - 1}\\sum_{s = 0}^{c - p - 1}\\sum_{z = zr - 1}^{g - p - s - 1}{d[z][g - p - s - 1]}$ If we play a little with the sum, we can simplify it in the following way: $bad = \\sum_{p = 0}^{c - 1}\\sum_{z = \\max(0, zr - 1)}^{g - p - 1}{\\mathrm{sumD}(z, g - c, g - p - 1)}$ Good prefixes are just $all - bad$ and since $bad$ can be calculated in $O(g^2)$, the total complexity of $\\mathrm{FixedPoints}(g)$ is $O(g^2)$. The resulting complexity is $O(n^2) + \\sum\\limits_{g|n}{O(g^2)}$ that looks like just $O(n^2)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n \ntypedef long long li;\ntypedef pair<int, int> pt;\n \ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n    return out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n    fore(i, 0, sz(v)) {\n        if(i) out << \" \";\n        out << v[i];\n    }\n    return out;\n}\n \nconst int MOD = int(1e9) + 7;\nint add(int a, int b) {\n    a += b;\n    while (a >= MOD)\n        a -= MOD;\n    while (a < 0)\n        a += MOD;\n    return a;\n}\nvoid upd(int &ans, int val) {\n    ans = add(ans, val);\n}\nint mul(int a, int b) {\n    return int(a * 1ll * b % MOD);\n}\nint binPow(int a, int k) {\n    int ans = 1;\n    while (k > 0) {\n        if (k & 1)\n            ans = mul(ans, a);\n        a = mul(a, a);\n        k >>= 1;\n    }\n    return ans;\n}\n \nconst int N = 3055;\nint f[N], invf[N];\n \nvoid precalcFact() {\n    f[0] = invf[0] = 1;\n    fore (i, 1, N) {\n        f[i] = mul(f[i - 1], i);\n        invf[i] = binPow(f[i], MOD - 2);\n    }\n}\nint C(int n, int k) {\n    if (k < 0 || k > n)\n        return 0;\n    return mul(f[n], mul(invf[k], invf[n - k]));\n}\n \nint n, c, k;\n \ninline bool read() {\n    if(!(cin >> n >> c >> k))\n        return false;\n    return true;\n}\n \nint d[N][N], sum[N][N];\n \n// d[z][l] - number of strings of length l, with z zeroes and blocks of 1-s shorter than mx\nvoid precalcShort(int mx) {\n    memset(d, 0, sizeof d);\n    d[0][0] = 1;\n    fore (z, 0, n) {\n        fore (l, 0, n) {\n            if (d[z][l] == 0)\n                continue;\n            upd(d[z + 1][l + 1], +d[z][l]);\n            upd(d[z + 1][min(n, l + mx) + 1], -d[z][l]);\n        }\n        fore (l, 0, n + 1)\n            upd(d[z + 1][l + 1], d[z + 1][l]);\n    }\n        \n    memset(sum, 0, sizeof sum);\n    fore (z, 0, n + 1) fore (l, 0, n + 1)\n        sum[z][l + 1] = add(sum[z][l], d[z][l]);\n    \n}\n \n//[lf, rg)\nint getSum(int z, int lf, int rg) {\n    if (z < 0 || z > n || lf >= rg)\n        return 0;\n    return add(sum[z][rg], -sum[z][lf]);\n}\n \n// cnt[g] is a number of x <= n with gcd(x, n) = g\nvector<int> precalcCnt(int n) {\n    vector<int> cnt(n + 1, 0);\n    fore (x, 1, n + 1)\n        cnt[gcd(x, n)]++;\n    return cnt;\n}\n \nint calcFixedPoints(int g) {\n    if (c >= g)\n        return c + k >= n;\n    \n    int cntOnes = (c + k) / (n / g);\n    int cntZeros = g - cntOnes;\n    \n    int all = 0;\n    fore (ones, 0, cntOnes + 1)\n        upd(all, C(g, ones));\n    \n    int bad = 0;\n    fore (pref, 0, c) {\n        int minZeros = max(0, cntZeros - 1);\n        int minMid = g - c;\n        int sufLen = g - pref - 1;\n        fore (z, minZeros, sufLen + 1)\n            upd(bad, getSum(z, minMid, sufLen + 1));\n    }\n    return add(all, -bad);\n}\n \ninline void solve() {\n    precalcFact();\n    precalcShort(c);\n    auto cnt = precalcCnt(n);\n    \n    int ans = 0;\n    fore (g, 1, n + 1) {\n        if (n % g != 0)\n            continue;\n        \n        int cntFP = calcFixedPoints(g);\n//      cerr << \"g = \" << g << \" += \" << cnt[g] << \" * \" << cntFP << endl;\n        upd(ans, mul(cnt[g], cntFP));\n    }\n    \n//  cerr << \"ans/n = \" << ans << \" \" << n << endl;\n    cout << mul(ans, binPow(n, MOD - 2)) << endl;\n}\n \nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1955",
    "index": "A",
    "title": "Yogurt Sale",
    "statement": "The price of one yogurt at the \"Vosmiorochka\" store is $a$ burles, but there is a promotion where you can buy two yogurts for $b$ burles.\n\nMaxim needs to buy \\textbf{exactly} $n$ yogurts. When buying two yogurts, he can choose to buy them at the regular price or at the promotion price.\n\nWhat is the minimum amount of burles Maxim should spend to buy $n$ yogurts?",
    "tutorial": "You can always buy yogurts one by one without using the promotion, then the answer is $n \\cdot a$. Suppose it is more advantageous to buy yogurts on promotion than one by one, that is, $b < 2 \\cdot a$. If $n$ is even, the answer is ${n \\over 2} \\cdot b$, otherwise ${(n - 1) \\over 2} \\cdot b + a$. Now you just need to choose whether to buy yogurts one by one or on promotion, taking the minimum of the two options.",
    "code": "#include <bits/stdc++.h>\n \nusing ll = signed long long int;\n \nusing namespace std;\n \nvoid solve() {\n    ll n, a, b;\n    cin >> n >> a >> b;\n    ll ans = n * a;\n    if (b < 2 * a) {\n        ans = (n / 2) * b + (n % 2) * a;\n    }\n    cout << ans << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1955",
    "index": "B",
    "title": "Progressive Square",
    "statement": "A progressive square of size $n$ is an $n \\times n$ matrix. Maxim chooses three integers $a_{1,1}$, $c$, and $d$ and constructs a progressive square according to the following rules:\n\n$$a_{i+1,j} = a_{i,j} + c$$\n\n$$a_{i,j+1} = a_{i,j} + d$$\n\nFor example, if $n = 3$, $a_{1,1} = 1$, $c=2$, and $d=3$, then the progressive square looks as follows:\n\n$$ \\begin{pmatrix} 1 & 4 & 7 \\\\ 3 & 6 & 9 \\\\ 5 & 8 & 11 \\end{pmatrix} $$\n\nLast month Maxim constructed a progressive square and remembered the values of $n$, $c$, and $d$. Recently, he found an array $b$ of $n^2$ integers in random order and wants to make sure that these elements are the elements of \\textbf{that specific} square.\n\nIt can be shown that for any values of $n$, $a_{1,1}$, $c$, and $d$, there exists exactly one progressive square that satisfies all the rules.",
    "tutorial": "Since $c > 0$ and $d > 0$, the elements of the square increase starting from the top left corner. Thus, $a_{1,1}$ is the minimum element in the square, and consequently in the found elements. Given $n$, $c$, $d$, and the found $a_{1,1}$, we will reconstruct the square. It remains to check that the given numbers in the input form the same square. The easiest way is to sort both arrays of numbers and check for equality. The complexity of the solution is $O(n ^ 2 \\cdot \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define all(x) (x).begin(), (x).end()\n \nusing ll = signed long long int;\nusing pii = pair<int, int>;\nusing pll = pair<ll, ll>;\nusing vi = vector<int>;\nusing vl = vector<ll>;\n \nvoid solve() {\n    int n;\n    ll c, d;\n    cin >> n >> c >> d;\n    vl a(n * n);\n    for (int i = 0; i < n * n; ++i) {\n        cin >> a[i];\n    }\n    sort(all(a));\n    vl b(n * n);\n    b[0] = a[0];\n    for (int i = 1; i < n; ++i) {\n        b[i] = b[i - 1] + c;\n    }\n    for (int i = 1; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            b[i * n + j] = b[(i - 1) * n + j] + d;\n        }\n    }\n    sort(all(b));\n    cout << (a == b ? \"YEs\" : \"nO\") << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "constructive algorithms",
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1955",
    "index": "C",
    "title": "Inhabitant of the Deep Sea",
    "statement": "$n$ ships set out to explore the depths of the ocean. The ships are numbered from $1$ to $n$ and follow each other in ascending order; the $i$-th ship has a durability of $a_i$.\n\nThe Kraken attacked the ships $k$ times in a specific order. First, it attacks the first of the ships, then the last, then the first again, and so on.\n\nEach attack by the Kraken reduces the durability of the ship by $1$. When the durability of the ship drops to $0$, it sinks and is no longer subjected to attacks (thus the ship ceases to be the first or last, and the Kraken only attacks the ships that have not yet sunk). If all the ships have sunk, the Kraken has nothing to attack and it swims away.\n\nFor example, if $n=4$, $k=5$, and $a=[1, 2, 4, 3]$, the following will happen:\n\n- The Kraken attacks the first ship, its durability becomes zero and now $a = [2, 4, 3]$;\n- The Kraken attacks the last ship, now $a = [2, 4, 2]$;\n- The Kraken attacks the first ship, now $a = [1, 4, 2]$;\n- The Kraken attacks the last ship, now $a = [1, 4, 1]$;\n- The Kraken attacks the first ship, its durability becomes zero and now $a = [4, 1]$.\n\nHow many ships were sunk after the Kraken's attack?",
    "tutorial": "To solve the problem, let's model the behavior of the Kraken. Suppose initially there are two or more ships in the sea, we will consider the first and last ship, denote their durabilities as $a_l$ and $a_r$, and also let $m = \\min(a_l, a_r)$, initially setting $l = 1$ and $r = n$. After two attacks, the durability of both ships will decrease by $1$. If $k \\ge 2 \\cdot m$, then we need to subtract $m$ from the durabilities of both ships, and also reduce the remaining attacks of the Kraken by $2 \\cdot m$. If $k < 2 \\cdot m$, then the Kraken will inflict $\\lfloor {k \\over 2} \\rfloor$ damage to the $r$-th ship. In this case, if $k$ is odd, the $l$-th ship will receive $\\lfloor {k \\over 2} \\rfloor + 1$ damage, otherwise $\\lfloor {k \\over 2} \\rfloor$ damage. After these attacks, some ships may have sunk. If $a_l = 0$, we increase $l$ by $1$, if $a_r = 0$, we decrease $r$ by $1$, and move on to considering the next pair of ships that will be under attack by the Kraken. If at some point $l = r$, it means that there is only one ship left in the sea, and the Kraken can sink it if $k \\ge a_l$. A deque is perfect for this problem, allowing us to not think about $l$ and $r$ and simply look at the first and last elements in the queue. At each step of considering a pair of ships, either the Kraken's attacks end, or at least one ship sinks. The final complexity of the solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define all(x) (x).begin(), (x).end()\n\nusing ll = signed long long int;\n\nvoid solve() {\n    int n;\n    ll k;\n    cin >> n >> k;\n    deque<ll> dq(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> dq[i];\n    }\n    while (dq.size() > 1 && k) {\n        ll mn = min(dq.front(), dq.back());\n        if (k < 2 * mn) {\n            dq.front() -= k / 2 + k % 2;\n            dq.back() -= k / 2;\n            k = 0;\n        } else {\n            dq.front() -= mn;\n            dq.back() -= mn;\n            k -= 2 * mn;\n        }\n        if (dq.front() == 0) {\n            dq.pop_front();\n        }\n        if (dq.back() == 0) {\n            dq.pop_back();\n        }\n    }\n    int ans = n - dq.size();\n    cout << ans + (dq.size() && dq.front() <= k) << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1955",
    "index": "D",
    "title": "Inaccurate Subsequence Search",
    "statement": "Maxim has an array $a$ of $n$ integers and an array $b$ of $m$ integers ($m \\le n$).\n\nMaxim considers an array $c$ of length $m$ to be good if the elements of array $c$ can be rearranged in such a way that at least $k$ of them match the elements of array $b$.\n\nFor example, if $b = [1, 2, 3, 4]$ and $k = 3$, then the arrays $[4, 1, 2, 3]$ and $[2, 3, 4, 5]$ are good (they can be reordered as follows: $[1, 2, 3, 4]$ and $[5, 2, 3, 4]$), while the arrays $[3, 4, 5, 6]$ and $[3, 4, 3, 4]$ are not good.\n\nMaxim wants to choose every subsegment of array $a$ of length $m$ as the elements of array $c$. Help Maxim count how many selected arrays will be good.\n\nIn other words, find the number of positions $1 \\le l \\le n - m + 1$ such that the elements $a_l, a_{l+1}, \\dots, a_{l + m - 1}$ form a good array.",
    "tutorial": "How to check if two arrays are good? For each element of $b$, try to pair it with an element from array $a$. If we managed to create $k$ or more pairs, then the arrays are good. Since rearranging the elements of the array is allowed, we will maintain three multisets $C$, $D$, and $E$. In $D$, we will store all elements from $b$ for which we found a pair, and in $C$ and $E$, all elements from $b$ and $a$ for which a pair was not found, i.e., $C \\cap E = \\emptyset$. Then the arrays are good if $|D| \\ge k$. It remains to understand how to find all good subsegments using this data organization. Suppose we shift the left boundary $l$ by $1$, simultaneously moving the right boundary, where $r = l + m - 1$. We need to remove the pair with the element $a_l$ from $D$, if it exists, and immediately try to find a replacement for the removed pair in $E$. After that, we try to find a pair for $a_r$ from $C$, and if a pair cannot be found, we place the element in $E$. The complexity of the solution is $O(n \\log n)$ or $O(n)$ if a hash table is used.",
    "code": "#include <bits/stdc++.h>\n \nusing ll = signed long long int;\n \n#define all(x) (x).begin(), (x).end()\n \nusing pii = std::pair<int, int>;\nusing pll = std::pair<ll, ll>;\n \nusing namespace std;\n \nvoid solve() {\n    int n, m;\n    size_t k;\n    cin >> n >> m >> k;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    multiset<int> todo, done, extra;\n    for (int j = 0; j < m; ++j) {\n        int b;\n        cin >> b;\n        todo.insert(b);\n    }\n    for (int j = 0; j < m; ++j) {\n        if (todo.find(a[j]) != todo.end()) {\n            todo.erase(todo.find(a[j]));\n            done.insert(a[j]);\n        } else {\n            extra.insert(a[j]);\n        }\n    }\n    int ans = (done.size() >= k);\n    for (int r = m; r < n; ++r) {\n        int old = a[r - m];\n        if (extra.find(old) != extra.end()) {\n            extra.erase(extra.find(old));\n        } else if (done.find(old) != done.end()) {\n            done.erase(done.find(old));\n            todo.insert(old);\n        }\n        if (todo.find(a[r]) != todo.end()) {\n            todo.erase(todo.find(a[r]));\n            done.insert(a[r]);\n        } else {\n            extra.insert(a[r]);\n        }\n        ans += (done.size() >= k);\n    }\n    cout << ans << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "data structures",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1955",
    "index": "E",
    "title": "Long Inversions",
    "statement": "A binary string $s$ of length $n$ is given. A binary string is a string consisting only of the characters '1' and '0'.\n\nYou can choose an integer $k$ ($1 \\le k \\le n$) and then apply the following operation any number of times: choose $k$ consecutive characters of the string and invert them, i.e., replace all '0' with '1' and vice versa.\n\nUsing these operations, you need to make all the characters in the string equal to '1'.\n\nFor example, if $n=5$, $s=00100$, you can choose $k=3$ and proceed as follows:\n\n- choose the substring from the $1$-st to the $3$-rd character and obtain $s=\\textcolor{blue}{110}00$;\n- choose the substring from the $3$-rd to the $5$-th character and obtain $s=11\\textcolor{blue}{111}$;\n\nFind the maximum value of $k$ for which it is possible to make all the characters in the string equal to '1' using the described operations. Note that the number of operations required to achieve this is not important.",
    "tutorial": "No substring of the string needs to be inverted twice, as it does not change the string in any way. Let's fix $k$ and try to check if all the characters of the string can be made equal to 1. Suppose the first $i$ characters are already equal to 1, and $s_{i + 1}=0$. Then we need to invert all the bits starting from the $i + 1$-th to the $i + k$-th inclusive, i.e., not invert the first $i$ characters. If we invert any of the first $i$ characters, then we will have to invert it again. Either we will invert $s_{i + 1}$ again, so it will become equal to 0, or we will invert the characters to the left and come to the same situation, but for a smaller prefix. Naive checking for a fixed $k$ takes $O(n \\cdot k)$ time, if we honestly invert $k$ characters every time we encounter 0. We will maintain an inversion counter - how many times we need to invert a character of the string. Getting the actual value of a character is simple - if the counter is odd, invert the character. If $s_{i} = 0$, add $1$ to the counter, and remember that we need to subtract $1$ from the counter after position $i + k$, forming a segment $[i, i + k)$. This way, the complexity of the check will be $O(n)$. It remains to iterate over $k$ and find the maximum for which it was possible to bring the string to all 1s. The complexity of the solution is $O(n ^ 2)$.",
    "code": "#include <bits/stdc++.h>\n \nusing ll = signed long long int;\n \n#define all(x) (x).begin(), (x).end()\n \nusing pii = std::array<int, 2>;\nusing pll = std::array<ll, 2>;\nusing vi = std::vector<int>;\nusing vl = std::vector<ll>;\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    string s;\n    cin >> n >> s;\n    for (int k = n; k > 0; --k) {\n        vector<char> t(n), end(n + 1);\n        for (int i = 0; i < n; ++i) {\n            t[i] = s[i] - '0';\n        }\n        int cnt = 0;\n        for (int i = 0; i < n; ++i) {\n            cnt -= end[i];\n            t[i] ^= (cnt & 1);\n            if (t[i] == 0) {\n                if (i + k <= n) {\n                    ++end[i + k];\n                    ++cnt;\n                    t[i] = 1;\n                } else {\n                    break;\n                }\n            }\n        }\n        if (*min_element(all(t)) == 1) {\n            cout << k << '\\n';\n            return;\n        }\n    }\n    assert(false);\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1955",
    "index": "F",
    "title": "Unfair Game",
    "statement": "Alice and Bob gathered in the evening to play an exciting game on a sequence of $n$ integers, each integer of the sequence \\textbf{doesn't exceed $4$}. The rules of the game are too complex to describe, so let's just describe the winning condition — Alice wins if the bitwise XOR of all the numbers in the sequence is non-zero; otherwise, Bob wins.\n\nThe guys invited Eve to act as a judge. Initially, Alice and Bob play with $n$ numbers. After one game, Eve removes one of the numbers from the sequence, then Alice and Bob play with $n-1$ numbers. Eve removes one number again, after which Alice and Bob play with $n - 2$ numbers. This continues until the sequence of numbers is empty.\n\nEve seems to think that in such a game, Alice almost always wins, so she wants Bob to win as many times as possible. Determine the maximum number of times Bob can win against Alice if Eve removes the numbers optimally.",
    "tutorial": "Let's try to solve the problem if all the numbers in the sequence are equal to $4$. If the number of elements is even, the bitwise XOR is zero, and if it's odd, then it's equal to $4$. By removing one $4$ at a time, Eve will change the parity, so the answer will be $\\lfloor {p_4 \\over 2} \\rfloor$. Suppose there are some other numbers in the sequence besides $4$. For Bob to win, the number of $4$s still needs to be even. Therefore, we can solve the problem for the remaining numbers separately from the fours. One of the solutions uses dynamic programming. Let's denote $dp_{i,j,k}$ as the maximum number of Bob's wins, if there were initially $i$ ones, $j$ twos, and $k$ threes. Since an empty sequence is not considered in the answer, then $dp_{0,0,0} = 0$. We will iterate over which number to remove, and get the following transitions: $dp_{i,j,k} = \\max(dp_{i - 1,j,k}, dp_{i,j - 1,k}, dp_{i,j,k - 1}) + x(i,j,k)$. Here, $x(i,j,k) = 1$ if the bitwise XOR of $i$ ones, $j$ twos, and $k$ threes is zero, and $x(i,j,k) = 0$ otherwise. The complexity of calculating these values is $O(N ^ 3)$, where $N = 200$. Another solution is analytical. Bob wins in two cases: if the number of ones, twos, and threes is even; if the number of ones, twos, and threes is odd. In the first case, the bitwise XOR is zero, because each number occurs an even number of times, and in the second case, $1 \\oplus 2 \\oplus 3 = 0$. To maintain the parities, Eve needs to remove the same number, so with two removals, Bob will win once. If the second condition is not initially met, it is always more advantageous to remove numbers to reach the first case, then the answer is $\\sum^{3}_{i = 1} \\lfloor{cnt_i \\over 2}\\rfloor$. If the second condition is already met, then $1$ needs to be added to the answer.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 201;\n \nint dp[N][N][N];\n \nvoid precalc() {\n    dp[0][0][0] = 0;\n    for (int i = 0; i < N; ++i) {\n        for (int j = 0; j < N; ++j) {\n            for (int k = 0; k < N; ++k) {\n                int prev = 0;\n                if (i) prev = max(prev, dp[i - 1][j][k]);\n                if (j) prev = max(prev, dp[i][j - 1][k]);\n                if (k) prev = max(prev, dp[i][j][k - 1]);\n                dp[i][j][k] = prev;\n                int xr = ((i & 1) * 1) ^ ((j & 1) * 2) ^ ((k & 1) * 3);\n                if (xr == 0 && (i || j || k)) {\n                    ++dp[i][j][k];\n                }\n            }\n        }\n    }\n}\n \nvoid solve() {\n    vector<int> cnt(4);\n    for (int i = 0; i < 4; ++i) {\n        cin >> cnt[i];\n    }\n    cout << dp[cnt[0]][cnt[1]][cnt[2]] + cnt[3] / 2 << '\\n';\n}\n \nint main() {\n    precalc();\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "dp",
      "games",
      "greedy",
      "math",
      "schedules"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1955",
    "index": "G",
    "title": "GCD on a grid",
    "statement": "Not long ago, Egor learned about the Euclidean algorithm for finding the greatest common divisor of two numbers. The greatest common divisor of two numbers $a$ and $b$ is the largest number that divides both $a$ and $b$ without leaving a remainder. With this knowledge, Egor can solve a problem that he once couldn't.\n\nVasily has a grid with $n$ rows and $m$ columns, and the integer ${a_i}_j$ is located at the intersection of the $i$-th row and the $j$-th column. Egor wants to go from the top left corner (at the intersection of the first row and the first column) to the bottom right corner (at the intersection of the last row and the last column) and find the greatest common divisor of all the numbers along the path. He is only allowed to move down and to the right. Egor has written down several paths and obtained different GCD values. He became interested in finding the maximum possible GCD.\n\nUnfortunately, Egor is tired of calculating GCDs, so he asks for your help in finding the maximum GCD of the integers along the path from the top left corner to the bottom right corner of the grid.",
    "tutorial": "First, let's learn how to check for a fixed $x$ if there exists a path from $(1,1)$ to $(n,m)$ with a GCD of $x$. It is necessary for all numbers along the path to be divisible by $x$. Let's define a grid $b$ of size $n$ by $m$, where $b_{i,j} = 1$ if $a_{i,j}$ is divisible by $x$, and $b_{i,j} = 0$ otherwise. If there exists a path of ones in $b$, then there exists a path in $a$ with a GCD of $x$. To check if there exists a path consisting entirely of ones, dynamic programming can be used. Let $dp_{i, j}$ denote whether it is possible to reach $(i,j)$ from $(1,1)$. Then the transitions are $dp_{i,j} = dp_{i - 1,j} \\lor dp_{i,j - 1}$, with the base case of the dynamic programming being $dp_{1,1} = b_{1,1}$. Since the path will definitely pass through the cells $(1,1)$ and $(n,m)$, we iterate through all divisors of the number $g = \\gcd(a_{1,1}, a_{n,m})$, check for each one if there exists a path with that GCD, and take the maximum such divisor. The complexity of the solution is $O(n \\cdot m \\cdot \\sqrt[3]{A})$, where $A \\le 10^6$.",
    "code": "#include <bits/stdc++.h>\n \nusing ll = signed long long int;\n \n#define all(x) (x).begin(), (x).end()\n \nusing pii = std::pair<int, int>;\nusing pll = std::pair<ll, ll>;\n \nusing namespace std;\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<int> > a(n, vector<int>(m));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < m; ++j) {\n            cin >> a[i][j];\n        }\n    }\n    int ans = 1, g = gcd(a[0][0], a[n - 1][m - 1]);\n    vector<vector<char> > dp(n, vector<char>(m));\n    for (int x = 1; x * x <= g; ++x) {\n        if (g % x > 0) {\n            continue;\n        }\n        vector<int> cand = {x, g / x};\n        for (int el : cand) {\n            for (int i = 0; i < n; ++i) {\n                dp[i].assign(m, 0);\n            }\n            dp[0][0] = 1;\n            for (int i = 0; i < n; ++i) {\n                for (int j = 0; j < m; ++j) {\n                    if (a[i][j] % el > 0) {\n                        continue;\n                    }\n                    if (!dp[i][j] && i) {\n                        dp[i][j] = (dp[i - 1][j] == 1 ? 1 : 0);\n                    }\n                    if (!dp[i][j] && j) {\n                        dp[i][j] = (dp[i][j - 1] == 1 ? 1 : 0);\n                    }\n                }\n            }\n            if (dp[n - 1][m - 1]) {\n                ans = max(ans, el);\n            }\n        }\n    }\n    cout << ans << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1955",
    "index": "H",
    "title": "The Most Reckless Defense",
    "statement": "You are playing a very popular Tower Defense game called \"Runnerfield 2\". In this game, the player sets up defensive towers that attack enemies moving from a certain starting point to the player's base.\n\nYou are given a grid of size $n \\times m$, on which $k$ towers are already placed and a path is laid out through which enemies will move. The cell at the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$.\n\nEach second, a tower deals $p_i$ units of damage to all enemies within its range. For example, if an enemy is located at cell $(x, y)$ and a tower is at $(x_i, y_i)$ with a range of $r$, then the enemy will take damage of $p_i$ if $(x - x_i) ^ 2 + (y - y_i) ^ 2 \\le r ^ 2$.\n\nEnemies move from cell $(1, 1)$ to cell $(n, m)$, visiting each cell of the path exactly once. An enemy instantly moves to an adjacent cell horizontally or vertically, but before doing so, it spends one second in the current cell. If its health becomes zero or less during this second, the enemy can no longer move. The player loses if an enemy reaches cell $(n, m)$ and can make one more move.\n\nBy default, all towers have a zero range, but the player can set a tower's range to an integer $r$ ($r > 0$), in which case the health of all enemies will increase by $3^r$. However, each $r$ can only be used for \\textbf{at most one} tower.\n\nSuppose an enemy has a base health of $h$ units. If the tower ranges are $2$, $4$, and $5$, then the enemy's health at the start of the path will be $h + 3 ^ 2 + 3 ^ 4 + 3 ^ 5 = h + 9 + 81 + 243 = h + 333$. The choice of ranges is made once before the appearance of enemies and cannot be changed after the game starts.\n\nFind the maximum amount of base health $h$ for which it is possible to set the ranges so that the player does not lose when an enemy with health $h$ passes through (without considering the additions for tower ranges).",
    "tutorial": "Let's solve the problem for a single tower. The tower's area of effect is a circle, so the theoretically possible number of cells in which a tower with radius $r$ will deal damage is $\\pi \\cdot r ^ 2$. In total, the tower will deal $p_i \\cdot \\pi \\cdot r^2$ damage to the enemy. At the same time, the initial health of the enemy will be increased by $3^r$, so in fact, this health increase needs to be subtracted from the tower's damage. Thus, the maximum radius for the tower can be found from the inequality $500 \\cdot \\pi \\cdot r ^ 2 - 3 ^ r > 0$, assuming that the tower has a damage of $p_i = 500$. This estimate gives $R = 12$, above which the enemy's health increase is too large for the tower to overcome. So, there are not so many radii, and each radius can be applied to no more than one tower. We will use the subset dynamic programming method: $dp_{i,mask}$ - the maximum damage that the first $i$ towers will deal with the optimal distribution of the radii in the $mask$. The transitions are quite simple: $dp_{i, mask} = \\max_{r \\in mask}(dp_{i - 1, mask}, dp_{i - 1, mask \\oplus r} + p_i \\cdot cover(i, r))$. The answer will be the maximum value $\\max_{mask} (dp_{k, mask} - \\sum_{r \\in mask} {3 ^ r})$. $cover(i, r)$ - this is the number of cells covered by the $i$-th tower when the radius is set to $r$. It can be calculated for one tower and for one radius in $O(r ^ 2)$ time, just iterate through the square with a side length of $2 \\cdot r$ and a center coinciding with the location of the tower. In total, the precalculation of $cover$ for all towers and all radii will take $O(k \\cdot R ^ 3)$ time. The complexity of calculating the dynamic programming values is $O(k \\cdot R \\cdot 2 ^ R)$, so the final complexity of the solution is $O(k \\cdot R \\cdot (2 ^ R + R ^ 2))$.",
    "code": "#include <bits/stdc++.h>\n \nusing ll = signed long long int;\n \n#define all(x) (x).begin(), (x).end()\n \nusing pii = std::pair<int, int>;\nusing pll = std::pair<ll, ll>;\n \nusing namespace std;\n \nconst int R = 12, INF = 2e9;\n \nbool check(int x, int n) { return (0 <= x && x < n); }\n \nvoid solve() {\n    int n, m, k;\n    cin >> n >> m >> k;\n    vector<string> gr(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> gr[i];\n    }\n    vector<pii> cord(k);\n    vector<int> p(k);\n    for (int i = 0; i < k; ++i) {\n        cin >> cord[i].first >> cord[i].second >> p[i];\n        --cord[i].first;\n        --cord[i].second;\n    }\n    vector<vector<int> > cover(k, vector<int>(R + 1));\n    for (int i = 0; i < k; ++i) {\n        int x = cord[i].first;\n        int y = cord[i].second;\n        for (int r = 1; r <= R; ++r) {\n            for (int dx = -r; dx <= r; ++dx) {\n                for (int dy = -r; dy <= r; ++dy) {\n                    int nx = x + dx;\n                    int ny = y + dy;\n                    if (!check(nx, n) || !check(ny, m)) {\n                        continue;\n                    }\n                    if ((x - nx) * (x - nx) + (y - ny) * (y - ny) <= r * r) {\n                        cover[i][r] += (gr[nx][ny] == '#');\n                    }\n                }\n            }\n        }\n    }\n    vector<vector<int> > dp(k + 1, vector<int>(1 << R, -INF));\n    dp[0][0] = 0;\n    for (int i = 1; i <= k; ++i) {\n        for (int mask = 0; mask < (1 << R); ++mask) {\n            dp[i][mask] = dp[i - 1][mask];\n            for (int r = 1; r <= R; ++r) {\n                int j = r - 1;\n                if (!(mask & (1 << j))) {\n                    continue;\n                }\n                dp[i][mask] = max(dp[i][mask], dp[i - 1][mask ^ (1 << j)] +\n                                                   p[i - 1] * cover[i - 1][r]);\n            }\n        }\n    }\n    int ans = 0;\n    for (int mask = 0; mask < (1 << R); ++mask) {\n        int hp = 0, mlt = 3;\n        for (int j = 0; j < R; ++j) {\n            if (mask & (1 << j)) {\n                hp += mlt;\n            }\n            mlt *= 3;\n        }\n        for (int i = 0; i <= k; ++i) {\n            ans = max(ans, dp[i][mask] - hp);\n        }\n    }\n    cout << ans << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dp",
      "flows",
      "graph matchings",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1956",
    "index": "A",
    "title": "Nene's Game",
    "statement": "Nene invented a new game based on an increasing sequence of integers $a_1, a_2, \\ldots, a_k$.\n\nIn this game, initially $n$ players are lined up in a row. In each of the rounds of this game, the following happens:\n\n- Nene finds the $a_1$-th, $a_2$-th, $\\ldots$, $a_k$-th players in a row. They are kicked out of the game simultaneously. If the $i$-th player in a row should be kicked out, but there are fewer than $i$ players in a row, they are skipped.\n\nOnce no one is kicked out of the game in some round, all the players that are still in the game are declared as winners.\n\nFor example, consider the game with $a=[3, 5]$ and $n=5$ players. Let the players be named player A, player B, $\\ldots$, player E in the order they are lined up initially. Then,\n\n- Before the first round, players are lined up as ABCDE. Nene finds the $3$-rd and the $5$-th players in a row. These are players C and E. They are kicked out in the first round.\n- Now players are lined up as ABD. Nene finds the $3$-rd and the $5$-th players in a row. The $3$-rd player is player D and there is no $5$-th player in a row. Thus, only player D is kicked out in the second round.\n- In the third round, no one is kicked out of the game, so the game ends after this round.\n- Players A and B are declared as the winners.\n\nNene has not yet decided how many people would join the game initially. Nene gave you $q$ integers $n_1, n_2, \\ldots, n_q$ and you should answer the following question for each $1 \\le i \\le q$ \\textbf{independently}:\n\n- How many people would be declared as winners if there are $n_i$ players in the game initially?",
    "tutorial": "Obviously, a person at place $p$ will be kicked out if and only if $p \\ge a_1$. Therefore, the answer is $\\min(n,a_1-1)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define MP make_pair\nmt19937 rnd(time(0));\nint a[105];\nvoid solve(){\n\tint q,k,n;cin>>k>>q;\n\tfor(int i=1;i<=k;i++) cin>>a[i];\n\tfor(int i=1;i<=q;i++){\n\t\tcin>>n;\n\t\tcout<<min(a[1]-1,n)<<' ';\n\t}\n\tcout<<endl;\n}\nint main(){\n\tios::sync_with_stdio(false);\n\tint _;cin>>_;\n\twhile(_--) solve(); \n}\n",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "games",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1956",
    "index": "B",
    "title": "Nene and the Card Game",
    "statement": "You and Nene are playing a card game. The deck with $2n$ cards is used to play this game. Each card has an integer from $1$ to $n$ on it, and each of integers $1$ through $n$ appears exactly on $2$ cards. Additionally, there is a table where cards are placed during the game (initially, the table is empty).\n\nIn the beginning of the game, these $2n$ cards are distributed between you and Nene so that each player receives $n$ cards.\n\nAfter it, you and Nene alternatively take $2n$ turns, i.e. each person takes $n$ turns, \\textbf{starting with you}. On each turn:\n\n- The player whose turn is it selects one of the cards in his hand. Let $x$ be the number on it.\n- The player whose turn is it receives $1$ point if there is already a card with the integer $x$ on the table (otherwise, he receives no points). After it, he places the selected card with the integer $x$ on the table.\n\nNote that turns are made publicly: each player can see all the cards on the table at each moment.\n\nNene is very smart so she always selects cards optimally in order to maximize her score in the end of the game (after $2n$ rounds). If she has several optimal moves, she selects the move that minimizes your score in the end of the game.\n\nMore formally, Nene always takes turns optimally in order to maximize her score in the end of the game in the first place and to minimize your score in the end of the game in the second place.\n\nAssuming that the cards are already distributed and cards in your hand have integers $a_1, a_2, \\ldots, a_n$ written on them, what is the maximum number of points you can get by taking your turns optimally?",
    "tutorial": "The number of pairs on each side should be the same. For each color (in the following text, \"this point\" refers to the point someone got by playing a card with this color): If you have both cards of this color in your hand, you will be able to get this point. If you have both cards of this color in your hand, you will be able to get this point. If Nene has both cards, you will not be able to get this point. If Nene has both cards, you will not be able to get this point. If you have only one card, you cannot get this point when Nene is using the following strategy: If you have only one card, you cannot get this point when Nene is using the following strategy: When you play one of your paired cards, Nene also plays one of her paired cards; Otherwise, Nene will have the card with the same color. She can play it and get this point. Therefore, the answer will be the amount of pairs in your hand.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int MAXN=4e5+5;\nint cnt[MAXN];\nvoid solve() {\n\tint n,ans=0;\n\tscanf(\"%d\",&n);\n\tfill(cnt+1,cnt+n+1,0);\n\tfor(int i=1,a;i<=n;++i) scanf(\"%d\",&a),ans+=(++cnt[a]==2);\n\tprintf(\"%d\\n\",ans);\n}\nsigned main() {\n\tint T;\n\tscanf(\"%d\",&T);\n\twhile(T--) solve();\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1956",
    "index": "C",
    "title": "Nene's Magical Matrix",
    "statement": "The magical girl Nene has an $n\\times n$ matrix $a$ filled with zeroes. The $j$-th element of the $i$-th row of matrix $a$ is denoted as $a_{i, j}$.\n\nShe can perform operations of the following two types with this matrix:\n\n- Type $1$ operation: choose an integer $i$ between $1$ and $n$ and a permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$. Assign $a_{i, j}:=p_j$ for all $1 \\le j \\le n$ simultaneously.\n- Type $2$ operation: choose an integer $i$ between $1$ and $n$ and a permutation $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$. Assign $a_{j, i}:=p_j$ for all $1 \\le j \\le n$ simultaneously.\n\nNene wants to maximize the sum of all the numbers in the matrix $\\sum\\limits_{i=1}^{n}\\sum\\limits_{j=1}^{n}a_{i,j}$. She asks you to find the way to perform the operations so that this sum is maximized. As she doesn't want to make too many operations, you should provide a solution with no more than $2n$ operations.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "When $n=3$, the optimal matrix is the following: The optimal matrix would be: Construction method: This takes exactly $2n$ operations. For the final matrix, we define $f(x)$ as the number of elements greater or equal to $x$. The sum of all elements in the matrix is $\\sum_{i=1}^n f(i)$ because an element with value $x$ will be counted $x$ times in the formula before. Now, we proof that $f(x) \\le n^2-(x-1)^2$: Let's rewrite the problem to make it a little simpler: You have an $n\\times n$ matrix. In each operation, you can paint exactly $x-1$ cells white and $n-(x-1)$ cells black in a row or a column. Proof that there will be at most $n^2-(x-1)^2$ black cells. Try to strengthen the conclusion by stating that: For any matrix of size $n\\times m$, each operation can paint a row into $x$ white cells and $m-x$ black cells, or a column into $y$ white cells and $n-y$ black cells. No matter how we paint, the final matrix will have at most $nm-xy$ black cells. We will prove this by induction. If $x=m$ or $y=n$, the conclusion holds. Otherwise, if the last operation is to paint a row, then this row has exactly $m-x$ black cells. And, by induction, other rows will contain at most $(n-1)m-x(y-1)$ black cells. Painting a column in the last step is similar. Then, we have proven the conclusion above. Since the construction above maximizes each $f(x)$, it is the optimal answer.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define MP make_pair\nmt19937 rnd(time(0));\nvoid solve(){\n\tint n;cin>>n;\n\tint ans=0;\n\tfor(int i=1;i<=n;i++) ans+=(2*i-1)*i;\n\tcout<<ans<<' '<<2*n<<endl;\n\tfor(int i=n;i>=1;i--){\n\t\tcout<<\"1 \"<<i<<' ';\n\t\tfor(int j=1;j<=n;j++) cout<<j<<' ';cout<<endl;\n\t\tcout<<\"2 \"<<i<<' ';\n\t\tfor(int j=1;j<=n;j++) cout<<j<<' ';cout<<endl;\n\t}\n}\nint main(){\n\tios::sync_with_stdio(false);\n\tint _;cin>>_;\n\twhile(_--) solve(); \n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1956",
    "index": "D",
    "title": "Nene and the Mex Operator",
    "statement": "Nene gave you an array of integers $a_1, a_2, \\ldots, a_n$ of length $n$.\n\nYou can perform the following operation no more than $5\\cdot 10^5$ times (possibly zero):\n\n- Choose two integers $l$ and $r$ such that $1 \\le l \\le r \\le n$, compute $x$ as $\\operatorname{MEX}(\\{a_l, a_{l+1}, \\ldots, a_r\\})$, and simultaneously set $a_l:=x, a_{l+1}:=x, \\ldots, a_r:=x$.\n\nHere, $\\operatorname{MEX}$ of a set of integers $\\{c_1, c_2, \\ldots, c_k\\}$ is defined as the smallest non-negative integer $m$ which does not occur in the set $c$.\n\nYour goal is to maximize the sum of the elements of the array $a$. Find the maximum sum and construct a sequence of operations that achieves this sum. Note that you don't need to minimize the number of operations in this sequence, you only should use no more than $5\\cdot 10^5$ operations in your solution.",
    "tutorial": "What is the answer when $a_i = 0$? When $a_i =0$, the sum can hit $n^2$ with making $a_i = n$ at last. Construction: Here, solve(k) will take about $2^k$ operations. Since doing operation $[l,r]$ will make $a_l,\\cdots,a_r \\le r-l+1$, if for all $l\\le i\\le r$, $a_i$ is included in at least one of the operations and $a_{l-1},a_{r+1}$ are not, the optimal strategy will be setting $a_i = r-l+1$ for $i\\in[l,r]$ using the construction above. Finally, we can use DFS or DP to determine whether each element is included in operations. The number of operations used will not exceed $2^n$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint n,a[20],cnt[20];\nvector <array<int,2>> I;\nvoid oper(int l,int r) {\n\tfill(cnt,cnt+n+1,0);\n\tfor(int i=l;i<=r;++i) if(a[i]<=n) ++cnt[a[i]];\n\tint mex=0;\n\twhile(cnt[mex]) ++mex;\n\tfor(int i=l;i<=r;++i) a[i]=mex;\n\tI.push_back({l,r});\n}\nvoid build(int l,int r) {\n\tif(l==r) {\n\t\tif(a[l]) oper(l,r);\n\t\treturn ;\n\t}\n\tbuild(l,r-1);\n\tif(a[r]!=r-l) oper(l,r),build(l,r-1);\n}\nvoid solve() {\n\tscanf(\"%d\",&n),I.clear(),memset(a,0,sizeof(a));\n\tfor(int i=0;i<n;++i) scanf(\"%d\",&a[i]);\n\tint cur=0,ans=0;\n\tfor(int s=0;s<(1<<n);++s) {\n\t\tint tmp=0;\n\t\tfor(int l=0;l<n;++l) {\n\t\t\tif(s&(1<<l)) {\n\t\t\t\tint r=l;\n\t\t\t\twhile(r+1<n&&(s&(1<<(r+1)))) ++r;\n\t\t\t\ttmp+=(r-l+1)*(r-l+1);\n\t\t\t\tl=r;\n\t\t\t} else tmp+=a[l];\n\t\t}\n\t\tif(tmp>ans) ans=tmp,cur=s;\n\t}\n\tfor(int l=0;l<n;++l) if(cur&(1<<l)) {\n\t\tint r=l;\n\t\twhile(r+1<n&&(cur&(1<<(r+1)))) ++r;\n\t\tbuild(l,r),oper(l,r),l=r;\n\t}\n\tprintf(\"%d %d\\n\",ans,(int)I.size());\n\tfor(auto i:I) printf(\"%d %d\\n\",i[0]+1,i[1]+1);\n}\nsigned main() {\n\tsolve();\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "divide and conquer",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1956",
    "index": "E2",
    "title": "Nene vs. Monsters (Hard Version)",
    "statement": "This is the hard version of the problem. The only difference between the versions is the constraints on $a_i$. You can make hacks only if both versions of the problem are solved.\n\nNene is fighting with $n$ monsters, located in a circle. These monsters are numbered from $1$ to $n$, and the $i$-th ($1 \\le i \\le n$) monster's current energy level is $a_i$.\n\nSince the monsters are too strong, Nene decided to fight with them using the Attack Your Neighbour spell. When Nene uses this spell, the following actions happen in the following order \\textbf{one by one}:\n\n- The $1$-st monster attacks the $2$-nd monster;\n- The $2$-nd monster attacks the $3$-rd monster;\n- $\\ldots$\n- The $(n-1)$-th monster attacks the $n$-th monster;\n- The $n$-th monster attacks the $1$-st monster.\n\nWhen the monster with energy level $x$ attacks the monster with the energy level $y$, the energy level of the defending monster becomes $\\max(0, y-x)$ (the energy level of the attacking monster remains equal to $x$).\n\nNene is going to use this spell $10^{100}$ times and deal with the monsters that will still have a non-zero energy level herself. She wants you to determine which monsters will have a non-zero energy level once she will use the described spell $10^{100}$ times.",
    "tutorial": "If three consecutive monsters have energy level $0,x,y\\ (x,y>0)$, the monster with energy lever $y$ will \"die\"(have energy level $0$) at last. If four consecutive monsters have energy levels $0,x,y,z\\ (x,y,z>0)$, what will happen to the monster $z$? If four consecutive monsters have energy level $x,y,z,w\\ (x,y,z,w>0)$, how many rounds of spells must be used to make at least one of these monsters die? If four consecutive monsters have energy level $x,y,z,w\\ (x,y,z,w>0)$ and they did not die after $t$ rounds of spells, then $y$ will receive at least $t$ points of damage, $z$ will receive at least $(t-1) +(t-2)+\\cdots=O(t^2)$ of damage, and $w$ will receive at least $O(t^3)$ of damage. That is to say, let $V=\\max_{i=1}^n a_i$, after $O(\\sqrt[3]{V})$ rounds, at least one of $x,y,z,w$ will die. So, we can simulate the process by brute force until there are no four consecutive alive monsters, and then the problem is reduced to the one described in Hint 2. If four consecutive monster have energy level $0,x,y,z\\ (x,y,z>0)$, $x$ will remain alive, $y$ will die at last and sending $D=(y-x)+(y-2x)+\\cdots+(y\\bmod x)$ damage to $z$ before that. Therefore, $z$ will remain alive if and only if $z>D$. The time complexity is $O(n\\sqrt[3]{V})$. Bonus: Actually, it can be shown that after $O(\\sqrt[k]{V})$ rounds, there will be no $k$ consecutive alive monsters. Making $k$ bigger than $3$ can further reduce the time complexity, but it will be harder to implement and optimize little on actual performance.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define MP make_pair\nmt19937 rnd(time(0));\nconst int MAXN=2e5+5;\nint n,a[MAXN];bool b[MAXN];\nbool check(){\n\ta[n+1]=a[1],a[n+2]=a[2],a[n+3]=a[3];\n\tfor(int i=1;i<=n;i++)\n\t\tif(a[i]&&a[i+1]&&a[i+2]&&a[i+3]) return true;\n\treturn false;\n} \nvoid solve(){\n\tcin>>n;\n\tfor(int i=1;i<=n;i++) cin>>a[i];\n\tif(n==2){\n\t\twhile(a[1]&&a[2]){\n\t\t\ta[2]=max(0,a[2]-a[1]);\n\t\t\ta[1]=max(0,a[1]-a[2]);\n\t\t}\n\t\tb[1]=(a[1]>0);b[2]=(a[2]>0);\n\t}else if(n==3){\n\t\twhile(a[1]&&a[2]&&a[3]){\n\t\t\ta[2]=max(0,a[2]-a[1]);\n\t\t\ta[3]=max(0,a[3]-a[2]);\n\t\t\ta[1]=max(0,a[1]-a[3]);\n\t\t}\n\t\tb[1]=(!a[3]&&a[1]);\n\t\tb[2]=(!a[1]&&a[2]);\n\t\tb[3]=(!a[2]&&a[3]);\n\t}else{\n\t\twhile(check()){\n\t\t\tfor(int i=1;i<=n;i++) a[i%n+1]=max(0,a[i%n+1]-a[i]);\n\t\t}\n\t\tfor(int i=1;i<=n;i++) b[i]=false;\n\t\tauto attack=[&](ll x,ll y){\n\t\t\tll k=x/y;\n\t\t\treturn (2*x-(k+1)*y)*k/2;\n\t\t};\n\t\tfor(int p=1;p<=n;p++) \n\t\t\tif(a[p]&&a[p%n+1]) a[p%n+1]=max(0,a[p%n+1]-a[p]);\n\t\t\telse break;\n\t\tfor(int i=1;i<=n;i++) if(!a[i]&&a[i%n+1]){\n\t\t\tb[i%n+1]=true;\n\t\t\tb[(i+2)%n+1]=(a[(i+2)%n+1]>attack(a[(i+1)%n+1],a[i%n+1]));\n\t\t}\n\t}\n\tint cnt=0;\n\tfor(int i=0;i<=n;i++) if(b[i]) cnt++;\n\tcout<<cnt<<endl;\n\tfor(int i=1;i<=n;i++) if(b[i]) cout<<i<<' ';\n\tcout<<endl;\n}\nint main(){\n\tios::sync_with_stdio(false);\n\tint _;cin>>_;\n\twhile(_--) solve();\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1956",
    "index": "F",
    "title": "Nene and the Passing Game",
    "statement": "Nene is training her team as a basketball coach. Nene's team consists of $n$ players, numbered from $1$ to $n$. The $i$-th player has an arm interval $[l_i,r_i]$. Two players $i$ and $j$ ($i \\neq j$) can pass the ball to each other if and only if $|i-j|\\in[l_i+l_j,r_i+r_j]$ (here, $|x|$ denotes the absolute value of $x$).\n\nNene wants to test the cooperation ability of these players. In order to do this, she will hold several rounds of assessment.\n\n- In each round, Nene will select a sequence of players $p_1,p_2,\\ldots,p_m$ such that players $p_i$ and $p_{i+1}$ can pass the ball to each other for all $1 \\le i < m$. The length of the sequence $m$ can be chosen by Nene. Each player can appear in the sequence $p_1,p_2,\\ldots,p_m$ multiple times or not appear in it at all.\n- Then, Nene will throw a ball to player $p_1$, player $p_1$ will pass the ball to player $p_2$ and so on... Player $p_m$ will throw a ball away from the basketball court so it can no longer be used.\n\nAs a coach, Nene wants each of $n$ players to appear in at least one round of assessment. Since Nene has to go on a date after school, Nene wants you to calculate the minimum number of rounds of assessment needed to complete the task.",
    "tutorial": "Two people $i$ and $j\\ (i<j)$ can pass the ball to each other directly if and only if $[i+l_i,i+r_i]\\cap[j-r_j,j-l_j]\\neq \\varnothing$ According to the hint above, we can build the following graph: There are $2n$ vertices in the graph. Vertice $i$ links to vertices $([n+i-r_i,n+i-l_1]\\cup[n+i+l_i,n+i+r_i])\\cap[n+1,2n]\\cap Z$. That is, assuming vertices $1$ to $n$ are players, vertices $n+1$ to $2n$ are temporary spots, and player $i$ links to all the spots where his/her arm can reach. Then, the answer will be the number of connected components in this graph which contains at least one vertice with an index less than or equal to $n$. But there's still a little problem with the solution. For two players $i, j\\ (i<j)$ satisfying $[i+l_i,i+r_i]\\cap[j+l_i,j+r_i]\\neq \\varnothing$ (that is, both players reaching out their \"right arm\"s), they are incorrectly counted as connected. To solve that, we can delete all the vertices $n+x$ such that $\\forall i,\\ x\\not\\in[i-r_i,i-l_i]$ or $\\forall i,\\ x\\not\\in[i+l_i,i+r_i]$ (that is, nobody's left/right arm can reach $x$). Finding such $x$ can be done easily in $O(n)$. The last issue is, the graph contains $O(n^2)$ edges. but since we only care about connectivity, operation \"link $x$ to $[y,z]$\" can be changed to \"link $x$ to $y$, and link $i$ to $i+1$ for all $i$ in $[y,z-1]$\". After that and removing multiple edges, the number of edges is reduced to $O(n)$. Finally, counting connected components in a graph can be easily done in $O(n)$, so the time complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define MP make_pair\nconst int MAXN=2e6+5;\nint n,tot,le[MAXN],ri[MAXN];\nint fa[MAXN<<1],s[MAXN],t[MAXN],pre[MAXN],suf[MAXN];\ninline int find(int x){\n\twhile(x^fa[x]) x=fa[x]=fa[fa[x]];\n\treturn x;\n}\nvoid solve(){\n\tcin>>n;\n\tfor(int i=1;i<=2*n+1;i++) fa[i]=i;\n\tfor(int i=0;i<=n+1;i++) s[i]=t[i]=pre[i]=suf[i]=0;\n\tfor(int i=1;i<=n;i++){\n\t\tcin>>le[i]>>ri[i];\n\t\ts[max(1,i-ri[i])]++;s[max(0,i-le[i])+1]--;\n\t\tt[min(n+1,i+le[i])]++;t[min(n,i+ri[i])+1]--;\n\t}\n\ttot=n;\n\tfor(int i=1;i<=n;i++){\n\t\ts[i]+=s[i-1],t[i]+=t[i-1];\n\t\tif(s[i]&&t[i]) suf[i]=pre[i]=++tot;\n\t}\n\tsuf[n+1]=0;\n\tfor(int i=1;i<=n;i++) pre[i]=(pre[i]?pre[i]:pre[i-1]);\n\tfor(int i=n;i>=1;i--) suf[i]=(suf[i]?suf[i]:suf[i+1]);\n\tfor(int i=1;i<=n;i++){\n\t\tint l=max(1,i-ri[i]),r=max(0,i-le[i]);\n\t\tif(l<=r){\n\t\t\tl=suf[l],r=pre[r];\n\t\t\tif(l&&r&&l<=r) for(int i=find(l);i<r;i=find(i)) fa[i]=i+1; \n\t\t}\n\t\tl=min(n+1,i+le[i]),r=min(n,i+ri[i]);\n\t\tif(l<=r){\n\t\t\tl=suf[l],r=pre[r];\n\t\t\tif(l&&r&&l<=r) for(int i=find(l);i<r;i=find(i)) fa[i]=i+1; \n\t\t}\n\t}\n\tfor(int i=1;i<=n;i++){\n\t\tint l=max(1,i-ri[i]),r=max(0,i-le[i]);\n\t\tif(l<=r){\n\t\t\tl=suf[l],r=pre[r];\n\t\t\tif(l&&r&&l<=r) fa[find(i)]=find(l);\n\t\t}\n\t\tl=min(n+1,i+le[i]),r=min(n,i+ri[i]);\n\t\tif(l<=r){\n\t\t\tl=suf[l],r=pre[r];\n\t\t\tif(l&&r&&l<=r) fa[find(i)]=find(l);\n\t\t}\n\t}\n\tint ans=0;\n\tfor(int i=1;i<=tot;i++) if(fa[i]==i) ans++; \n\tcout<<ans<<'\\n';\n}\nint main(){\n\tios::sync_with_stdio(false);\n\t// freopen(\"Otomachi_Una.in\",\"r\",stdin);\n\t// freopen(\"Otomachi_Una.out\",\"w\",stdout);\n\tint _;cin>>_;\n\twhile(_--) solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dsu",
      "graphs",
      "sortings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1957",
    "index": "A",
    "title": "Stickogon",
    "statement": "You are given $n$ sticks of lengths $a_1, a_2, \\ldots, a_n$. Find the maximum number of regular (equal-sided) polygons you can construct simultaneously, such that:\n\n- Each side of a polygon is formed by exactly one stick.\n- No stick is used in more than $1$ polygon.\n\nNote: Sticks cannot be broken.",
    "tutorial": "The first observation that needs to be made in this problem is that we have to greedily try to build triangles from the sticks available. The number of triangles that can be created simultaneously by $S$ sticks of the same length is $\\left\\lfloor \\frac{S}{3} \\right\\rfloor$. Hence, the answer is just the sum of the count of all triangles for all stick lengths, $\\sum\\limits_{i = 1}^{100} \\left\\lfloor \\frac{S_i}{3} \\right\\rfloor$, where $S_i$ denotes the number of sticks of length $i$. The time complexity of the problem is therefore $O(n) + O(100) = O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){ \n  int t; \n  cin >> t;\n  while(t--) {\n    int n; \n    cin >> n; \n    vector<int> a(101, 0);\n    for (int i = 0; i < n; i++) {\n      int x; \n      cin >> x;\n      a[x]++;\n    }\n    int sum = 0;\n    for (auto& s : a) \n      sum += s / 3;\n    cout << sum << \"\\n\";\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1957",
    "index": "B",
    "title": "A BIT of a Construction",
    "statement": "Given integers $n$ and $k$, construct a sequence of $n$ non-negative (i.e. $\\geq 0$) integers $a_1, a_2, \\ldots, a_n$ such that\n\n- $\\sum\\limits_{i = 1}^n a_i = k$\n- The \\textbf{number} of $1$s in the binary representation of $a_1 | a_2 | \\ldots | a_n$ is maximized, where $|$ denotes the bitwise OR operation.",
    "tutorial": "The case $n = 1$ needs to be handled separately, as we can only output $k$ itself. For $n > 1$, we make the following observations. Let $x$ be the position of the most significant bit in $k$, that is $2^{x} \\leq k < 2^{x+1}$. From this, we learn that the bitwise OR of the sequence cannot have more than $x+1$ set bits because that would make the sum greater than $2^{x+1}$. Now, having $x+1$ bits set in the bitwise OR of the sequence is only possible if $k = 2^{x+1} - 1$ (or $k = 111\\ldots1_2$). Any $k$ less than this cannot have $x+1$ bits set in the bitwise OR of the sequence, as otherwise the sum would exceed $k$. However, we can always set $x$ bits, as we can always have one number in the sequence as $2^x - 1$ (which has exactly $x$ bits set). Using these observations, we get our solution as $2^x - 1, k - (2^x - 1), 0, 0, 0,\\ldots, 0$. This ensures that we have at least $x$ bits set in the bitwise OR, and additionally also handles the case where $x+1$ bits can be set, while maintaining the sum.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n \nint main(){\n    int t; \n    cin >> t;\n    while(t--) {\n        int n, k;\n        cin >> n >> k;\n        vector<int> a(n);\n        if (n == 1) {\n            a[0] = k;\n        }\n        else {\n            int msb = 0;\n            // find the msb of k\n            for (int i = 0; i < 31; i++) {\n                if (k & (1 << i)) {\n                    msb = i;\n                }\n            }\n            a[0] = (1 << msb) - 1;\n            a[1] = k - a[0];\n            for (int i = 2; i < n; i++) {\n                a[i] = 0;\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            cout << a[i] << \" \";\n        }\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1957",
    "index": "C",
    "title": "How Does the Rook Move?",
    "statement": "You are given an $n \\times n$ chessboard where you and the computer take turns alternatingly to place white rooks & black rooks on the board respectively. While placing rooks, you have to ensure that no two rooks attack each other. Two rooks attack each other if they share the same row or column \\textbf{regardless of color}.\n\nA valid move is placing a rook on a position ($r$, $c$) such that it doesn't attack any other rook.\n\nYou start first, and when you make a valid move in your turn, placing a white rook at position ($r$, $c$), the computer will mirror you and place a black rook at position ($c$, $r$) in its turn. If $r = c$, then the computer can't mirror your move, and skips its turn.\n\nYou have already played $k$ moves with the computer (the computer tries to mirror these moves too), and you must continue playing the game until there are no valid moves remaining. How many different final configurations are possible when you continue the game after the $k$ moves? It is guaranteed that the $k$ moves and the implied computer moves are valid. Since the answer may be large, print it modulo $10^9+7$.\n\nTwo configurations are considered different if there exists a coordinate ($r$, $c$) which has a rook in one configuration, but not in the other \\textbf{or} the color of the rook on the coordinate is different.",
    "tutorial": "There are essentially two types of moves: Placing a rook at some $(i, i)$: This reduces the number of free rows and columns available by $1$. Placing a rook at some $(i, j)$, where $i \\neq j$: The computer now mirrors this by placing a rook at $(j, i)$, blocking rows $i$ and $j$ along with columns $i$ and $j$. So the number of free rows and columns is reduced by $2$. First, we account for the $k$ moves played earlier and count the number of free columns/rows remaining to place rooks in, and call it $m$. Notice that the order of removing rows/columns doesn't affect the final configuration of rooks, and hence only the count of rows matters, to determine the number of final configurations. We can use a dynamic programming approach where $dp[i]$ represents the number of final configurations when $i$ rows and columns are left. Since the order of removing rows/columns is unimportant, let's start by removing the last row or column. When removing the last row or column in an $i \\times i$ grid, we have two options: We place a rook $(i, i)$, resulting in the deletion of only the last row and column leaving an $(i-1) \\times (i-1)$ grid. The number of final configurations in this case are given by $dp[i-1]$. Alternatively, we can place a rook at $(i, j)$ or $(j, i)$ for any $j \\in \\{1, 2, \\ldots, i-1\\}$. After this move, both the $j$-th and the $i$-th rows and columns are deleted, leaving an $(i-2) \\times (i-2)$ grid. This contributes $2 (i-1) \\cdot dp[i-2]$ to $dp[i]$. Overall, we compute $dp[i] = dp[i-1] + 2 (i-1) \\cdot dp[i-2]$ for all $i \\in \\{2, 3, \\ldots, n\\}$, with the base case of $dp[0] = dp[1] = 1$. Our final answer is $dp[m]$. Altenatively, we can iterate on the number of type $1$ moves we play. Let's term this to be $c$. There are ${m\\choose c}$ ways to choose the $c$ type $1$ moves. Now, we have $m - c$ rows/columns left, and this must be even (type 2 moves cannot exhaust an odd number of rows/columns). We can see that each of the $(m - c)!$ permutations of the remaining columns correspond to a set of moves we can play. For example, if we have the columns $(1, 4, 5, 6)$ remaining, a permutation $(4, 5, 6, 1)$ corresponds to playing the moves $(4, 5), (6, 1)$. However, if we simply count the number of permutations, we would also be counting the permutation $(6, 1, 4, 5)$, which corresponds to the same set of moves. To remove overcounting, we can just divide $(m - c)!$ by $((m - c)/2)!$ (removing the permutations of the pairs chosen). Hence, the answer becomes $\\sum\\limits_{c = 0}^m [(m - c) \\bmod 2 = 0] {m \\choose c} \\frac{(m - c)!}{\\left(\\frac{m - c}{2}\\right)!}$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint dp[(int) 3e5+5];\nconst int MOD = 1e9 + 7;\n \nint main() {\n    cin.tie(0), cout.tie(0)->sync_with_stdio(0);\n    int t; \n    cin >> t;\n    while (t--) {\n        int n, k;\n        cin >> n >> k;\n        int used = 0;\n        for (int i = 0; i < k; i++) {\n            int r, c; cin >> r >> c;\n            used += 2 - (r == c);\n        }\n        int m = n - used;\n        dp[0] = dp[1] = 1;\n        for (int i = 2; i <= m; i++)\n            dp[i] = (dp[i-1] + 2ll * (i-1) * dp[i-2] % MOD) % MOD;\n        cout << dp[m] << \"\\n\";    \n    }\n    \n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1957",
    "index": "D",
    "title": "A BIT of an Inequality",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$. Find the number of tuples ($x, y, z$) such that:\n\n- $1 \\leq x \\leq y \\leq z \\leq n$, and\n- $f(x, y) \\oplus f(y, z) > f(x, z)$.\n\nWe define $f(l, r) = a_l \\oplus a_{l + 1} \\oplus \\ldots \\oplus a_{r}$, where $\\oplus$ denotes the bitwise XOR operation.",
    "tutorial": "How can you simplify the given inequality? Use the fact that the XOR of a number with itself is 0. The inequality simplifies to $f(x, z) \\oplus a_y > f(x, z)$. For a given $a_y$ what subarrays (that include $a_y$) would satisfy this? First we may rewrite the inequality as $f(x, z) \\oplus a_y > f(x, z)$. So, for each index $y$, we want to find the total number of subarrays that contain $y$ but whose $\\text{xor}$ decreases when we include the contribution of $a_y$. Including $a_y$ in some subarray $[x, z]$ (where $x \\le y \\le z$) can make the $\\text{xor}$ lower only when some set bit of $a_y$ cancels out an existing set bit in $f(x, y - 1) \\oplus f(y + 1, z)$. Consider the most signicant set bit in $a_y$. Call this bit $i$. Including $a_y$ would decrease the subarray $\\text{xor}$ in subarrays where $f(x, y - 1)$ has $i$ set while $f(y+1, z)$ is unset or vice-versa. Now, for the subarrays where both the prefix subarray ($[x \\dots y - 1]$) as well as the suffix subarray ($[y + 1 \\dots z]$) where either both have bit $i$ set or both have it unset, by including $a_y$, we increment the xor by at least $2^i$. Even if by including $a_y$, every other smaller bit gets unset (because of cancelling out with $a_y$), this sum of these decrements is still less than $2^i$ thereby resulting in an overall positive contribution by including $a_y$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int Z = 30;\nconst int MAX_N = 1e5 + 3;\nint pref[Z][MAX_N][2];\nint suff[Z][MAX_N][2];\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n + 1);\n    for (int i = 1; i <= n; i++) cin >> a[i];\n    for (int i = 0; i < Z; i++) suff[i][n + 1][0] = suff[i][n + 1][1] = 0;\n    for (int i = 0; i < Z; i++) {\n        for (int j = 1; j <= n; j++) {\n            int t = !!(a[j] & (1 << i));\n            for (int k = 0; k < 2; k++) pref[i][j][k] = (t == k) + pref[i][j - 1][k ^ t];\n        }\n        for (int j = n; j >= 1; j--) {\n            int t = !!(a[j] & (1 << i));\n            for (int k = 0; k < 2; k++) suff[i][j][k] = (t == k) + suff[i][j + 1][k ^ t];\n        }\n    }\n    long long ans = 0;\n    for (int i = 1; i <= n; i++) {\n        int z = 31 - __builtin_clz(a[i]);\n        ans += 1ll * pref[z][i - 1][1] * (1 + suff[z][i + 1][0]);\n        ans += 1ll * (1 + pref[z][i - 1][0]) * suff[z][i + 1][1];\n    }\n    cout << ans << \"\\n\";\n}\n\nint main() {\n    int tc;\n    cin >> tc;\n    while (tc--)\n        solve();\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1957",
    "index": "E",
    "title": "Carousel of Combinations",
    "statement": "You are given an integer $n$. The function $C(i,k)$ represents the number of distinct ways you can select $k$ distinct numbers from the set {$1, 2, \\ldots, i$} and arrange them in a circle$^\\dagger$.\n\nFind the value of $$ \\sum\\limits_{i=1}^n \\sum\\limits_{j=1}^i \\left( C(i,j) \\bmod j \\right). $$ Here, the operation $x \\bmod y$ denotes the remainder from dividing $x$ by $y$.\n\nSince this value can be very large, find it modulo $10^9+7$.\n\n$^\\dagger$ In a circular arrangement, sequences are considered identical if one can be rotated to match the other. For instance, $[1, 2, 3]$ and $[2, 3, 1]$ are equivalent in a circle.",
    "tutorial": "For what values of $j$ is $C(i,j) \\bmod j = 0$? For all other values of $j$, how can you precompute the result? To precompute, switch around the loop order. The number of distinct ways you can select $k$ distinct numbers from the set {$1, 2, \\ldots, i$} and arrange them in a line is $i(i-1)\\cdots(i-k+1)$, and since arranging in a circle introduces rotational symmetry we have to divide by $k$, so we have $C(i,k) = \\frac{i(i-1)\\cdots(i-k+1)}{k}$. Therefore $C(i,j) \\bmod j = \\frac{i(i-1)\\cdots(i-j+1)}{j} \\bmod j$. Now since the numerator is a product of $j$ consecutive integers, atleast one of them will be divisible by $j$. More precisely the exact integer which will be divisible by $j$ will be $j \\times \\lfloor \\frac{i}{j} \\rfloor$. Hence we can simplify the fraction by removing the denominator and replacing the term $j \\times \\lfloor \\frac{i}{j} \\rfloor$ with $\\lfloor \\frac{i}{j} \\rfloor$ in the numerator. Each of the other $j-1$ integers in the numerator, after applying $\\bmod j$ would cover all integers from $1$ to $j-1$. Hence $C(i,j) \\bmod j = \\frac{i(i-1)\\cdots(i-j+1)}{j} \\bmod j = \\left( (j-1)! \\times \\left\\lfloor \\frac{i}{j} \\right\\rfloor \\right) \\bmod j$ Here we can notice that all proper factors of $j$ will occur in $(j-1)!$, so based on this we can tell that $C(i,j) \\bmod j = 0$ for all composite numbers $j$ except $j=4$. We first can handle the case of $j$ being prime. Using Wilson's Theorem, we know that $(j-1)! \\equiv -1 \\bmod j$ when $j$ is prime. Hence $C(i,j) \\bmod j = - \\left\\lfloor \\frac{i}{j} \\right\\rfloor$ Now we can reverse the order of loops to sum over all primes, and to calculate the contribution of each prime we can maintain a update array called $delta$. To calculate the contribution for a single prime $p$, we know that for all $n$ from $kp$ to $(k + 1)p - 1$ (for all $k$ such that $kp < 1e6$) the contribution would be $-k$. So, in the $delta$ array, we increment index $kp$ with $-k \\bmod p$ and decrement index $(k + 1)p$ with $-k \\mod p$. Now, when we perform a prefix sum on this $delta$ array, we obtain the correct contributions from all primes. For the case of $j=4$, we just need to handle it as a prime.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 1e9 + 7;\nconst int MAX_N = 1e6 + 3;\nbitset<MAX_N> isprime;\nvector<int> primes;\n \nvector<int> eratosthenesSieve(int lim) {\n    isprime.set();\n    isprime[0] = isprime[1] = false;\n    for (int i = 4; i < lim; i += 2) isprime[i] = false;\n    for (int i = 3; i * i < lim; i += 2)\n        if (isprime[i])\n            for (int j = i * i; j < lim; j += i * 2) isprime[j] = false;\n    vector<int> pr;\n    for (int i = 2; i < lim; i++)\n        if (isprime[i]) pr.push_back(i);\n    return pr;\n}\n \nvector<int> ans(MAX_N, 0);\n \nsigned main() {\n    primes = eratosthenesSieve(MAX_N);\n    vector<int> del(MAX_N, 0);\n    // Handle the contribution for all primes\n    for (auto &p: primes) {\n        for (int curr = p; curr < MAX_N; curr += p) {\n            int inc = (p - ((curr / p) % p)) % p;\n            del[curr] = (del[curr] + inc) % MOD;\n            if (curr + p < MAX_N) del[curr + p] = (del[curr + p] - inc + MOD) % MOD;\n        }\n    }\n    //Special case of 4\n    for (int curr = 4; curr < MAX_N; curr += 4) {\n        int inc = (2 * (curr / 4)) % 4;\n        del[curr] = (del[curr] + inc) % MOD;\n        if (curr + 4 < MAX_N) del[curr + 4] = (del[curr + 4] - inc + MOD) % MOD;\n    }\n    int pref = 0;\n    for (int i = 1; i < MAX_N; i++) {\n        pref = (pref + del[i]) % MOD;\n        ans[i] = (ans[i - 1] + pref) % MOD;\n    }\n    int tc;\n    cin >> tc;\n    while (tc--) {\n        int n;\n        cin >> n;\n        cout << ans[n] << \"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1957",
    "index": "F1",
    "title": "Frequency Mismatch (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the two versions of this problem is the constraint on $k$. You can make hacks only if all versions of the problem are solved.}\n\nYou are given an undirected tree of $n$ nodes. Each node $v$ has a value $a_v$ written on it. You have to answer queries related to the tree.\n\nYou are given $q$ queries. In each query, you are given $5$ integers, $u_1, v_1, u_2, v_2, k$. Denote the count of nodes with value $c$ on path $u_1 \\rightarrow v_1$ with $x_c$, and the count of nodes with value $c$ on path $u_2 \\rightarrow v_2$ with $y_c$. If there are $z$ such values of $c$ such that $x_c \\neq y_c$, output any $\\min(z, k)$ such values in any order.",
    "tutorial": "Let's try answering a different question. Given two multisets of elements how can we check if they differ? Hashing? How to multiset hash efficiently? Okay if we can now differentiate two multisets of unequal elements, can we try to answer queries by inserting into these hypothetical multisets and binary search the differing point to identify the element? Let's discuss how to hash a multiset of elements $a$, $b$ and $c$. Here, I will link you to a famous blog by rng_58 Hashing and Probability of Collision. Quoting, let's take a random integer $r$ from the interval $[0, MOD)$, and compute the hash $(r+a_1)(r+a_2)\\dots(r+a_n)$. This is a polynomial of $r$ of degree $n$, so again from Schwartz-Zippel lemma, the collision probability is at most $\\frac{n}{MOD}$. The nice thing about this construction is that we can compute rolling hashes using this idea fast. To make implementation easier, this bound applies for summing the random numbers as well. You can check this for proof. Let's try to answer a single query $(u_1, v_1, u_2, v_2)$ using binary search. We will solve this query in $nlog^2(n)$ using this idea. To check for some $mid$ in our binary search, we insert the values of all nodes which have values from $1$ to $mid$ into a data structure that we can query the path sum of $u$ to $v$ using. Querying path sum is a fairly standard problem that can be solved using BIT / Segment trees and ETT (Euler-Tour Trick). Now to solve this query, we only need to binary search and find the first vertex where the hashes differ for both the paths. This vertex is guaranteed to have mismatched frequency on the two paths since it's addition into the path multi-sets changed their hashes. So now we can solve a single query in $nlog^2(n)$ time using hashing + BIT / Segtree. Now to solve this problem for all $Q$ queries. We can use the idea of parallel binary search here to improve our idea to answering all $Q$ queries efficiently. We can run the binary search for all queries in parallel. For each iteration, sort queries by the current position of their $mid$ values. Then insert values from $1$ to $mid$ of the first query into the BIT and query range sum to determine for that particular query how to adjust $mid$. You can then move the $mid$ pointer to that of the next query and so on. This solution will run in $O(nlog(n) + qlog^2(n))$. Upd: Thanks to IceKnight1093 for pointing this out. If we just use a single int hash with a field size of $\\approx 10^9$, it gives us a probability of failure of $\\frac{1}{10^9}$ per query. Since we're doing somewhere of the order $10^6$ comparisons per hash representation, this gives a rough $1 - \\Big(1 - \\frac{1}{10^9}\\Big)^{10^6} \\approx 10^{-3}$ chance of failure. This is not a great bound theoretically speaking, but from a practical standpoint, it is a loose bound and it is extremely unlikely that this solution can be hacked. That said, if we want better theoretical bounds we can just use a hash with field size $\\approx 10^{18}$ or use double hashing. Even if we were to query all ${n \\choose 2}$ paths, the chance of collision is $\\approx \\frac{n^2}{10^{18}} \\approx 10^{-8}$, which is more than good enough. TL's were set to allow double hashing solutions to pass comfortably.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MOD = 1e9 + 7;\nusing ll = long long;\nusing dbl = long double;\n//#define int ll\n\nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing pii = pair<int, int>;\nusing vii = vector<pii>;\nusing vvii = vector<vii>;\nusing vll = vector<ll>;\n\n#define ff first\n#define ss second\n#define pb push_back\n#define rep(i, a, b) for(int i = a; i < (b); ++i)\n#define all(x) begin(x), end(x)\n#define sz(x) (int)(x).size()\n#define tc int t; cin>>t; while(t--)\n#define fightFight cin.tie(0) -> sync_with_stdio(0)\n\ntemplate<class T>\nstruct RMQ {\n    vector<vector<T>> jmp;\n    RMQ(const vector<T>& V) : jmp(1, V) {\n        for (int pw = 1, k = 1; pw * 2 <= sz(V); pw *= 2, ++k) {\n            jmp.emplace_back(sz(V) - pw * 2 + 1);\n            rep(j,0,sz(jmp[k]))\n                jmp[k][j] = min(jmp[k - 1][j], jmp[k - 1][j + pw]);\n        }\n    }\n    T query(int a, int b) {\n        assert(a <= b); // tie(a, b) = minimax(a, b)\n        int dep = 31 - __builtin_clz(b-a+1);\n        return min(jmp[dep][a], jmp[dep][b - (1 << dep) + 1]);\n    }\n};\n\nstruct LCA {\n    int T = 0;\n    vi st, path, ret; vi en, d;\n    RMQ<int> rmq;\n    LCA(vector<vi>& C) : st(sz(C)), en(sz(C)), d(sz(C)), rmq((dfs(C,0,-1), ret)) {}\n    void dfs(vvi &adj, int v, int par) {\n        st[v] = T++;\n        for (auto to : adj[v]) if (to != par) {\n            path.pb(v), ret.pb(st[v]);\n            d[to] = d[v] + 1;\n            dfs(adj, to, v);\n        }\n        en[v] = T-1;\n    }\n    bool anc(int p, int c) { return st[p] <= st[c] and en[p] >= en[c]; }\n    int lca(int a, int b) {\n        if (a == b) return a;\n        tie(a, b) = minmax(st[a], st[b]);\n        return path[rmq.query(a, b-1)];\n    }\n    int dist(int a, int b) { return d[a] + d[b] - 2*d[lca(a,b)]; }\n};\n\ntemplate<const int mod>\nstruct mint {\n    constexpr mint(int x = 0) : val((x % mod + mod) % mod) {}\n    mint& operator+=(const mint &b) { val += b.val; val -= mod * (val >= mod); return *this; }\n    mint& operator-=(const mint &b) { val -= b.val; val += mod * (val < 0); return *this; }\n    mint& operator*=(const mint &b) { val = 1ll * val * b.val % mod; return *this; }\n    mint& operator/=(const mint &b) { return *this *= b.inv(); }\n    mint inv() const {\n        int x = 1, y = 0, t;\n        for(int a=val, b=mod; b; swap(a, b), swap(x, y))\n            t = a/b, a -= t * b, x -= t * y;\n        return mint(x);\n    }\n    mint pow(int b) const {\n        mint a = *this, res(1);\n        for(; b; a *= a, b /= 2)  if(b&1) res *= a;\n        return res;\n    }\n    friend mint operator+(const mint &a, const mint &b) {return mint(a) += b;}\n    friend mint operator-(const mint &a, const mint &b) {return mint(a) -= b;}\n    friend mint operator*(const mint &a, const mint &b) {return mint(a) *= b;}\n    friend mint operator/(const mint &a, const mint &b) {return mint(a) /= b;}\n    friend bool operator==(const mint &a, const mint &b) {return a.val == b.val;}\n    friend bool operator!=(const mint &a, const mint &b) {return a.val != b.val;}\n    friend bool operator<(const mint &a, const mint &b) {return a.val < b.val;}\n    friend ostream& operator<<(ostream &os, const mint &a) {return os << a.val;}\n    int val;\n};\nusing Mint = mint<MOD>;\n\ntemplate<typename... Ts, size_t... Is, typename F>\nvoid __op(index_sequence<Is...>, tuple<Ts...>& a, const tuple<Ts...>& b, F op) { ((get<Is>(a) = op(get<Is>(a), get<Is>(b))), ...); }\n#define OVERLOAD(OP, F) \\\ntemplate<typename... Ts> auto& operator OP##=(tuple<Ts...> &a, const tuple<Ts...> &b) { __op(index_sequence_for<Ts...>(), a, b, F<>{}); return a; } \\\ntemplate<typename... Ts> auto operator OP(const tuple<Ts...> &a, const tuple<Ts...> &b) { auto c = a; c OP##= b; return c; }\nOVERLOAD(+, plus) OVERLOAD(-, minus) OVERLOAD(*, multiplies) OVERLOAD(/, divides)\n\nconstexpr int NUM_HASHES = 2; // *\nconstexpr array<int, NUM_HASHES> mods = {127657753, 987654319}; // *\ntemplate <size_t N = NUM_HASHES>\nconstexpr auto mint_ntuple(const int &v) {\n    return [&]<size_t... Is>(index_sequence<Is...>) { return make_tuple(mint<mods[Is]>(v)...); }(make_index_sequence<N>{}); }\n\nusing HT = decltype(mint_ntuple(0));\n\ntemplate<typename T>\nstruct FT {\n    vector<T> s;\n    T def;\n    FT(int n, T def) : s(n, def), def(def) {}\n    void update(int pos, T dif) { // a[pos] += dif\n        for (; pos < sz(s); pos |= pos + 1) s[pos] += dif;\n    }\n    T query(int pos) { // sum of values in [0, pos)\n        pos++;\n        T res = def;\n        for (; pos > 0; pos &= pos - 1) res += s[pos-1];\n        return res;\n    }\n};\n\nstruct Query {\n    int u1, v1, u2, v2, k;\n    int l, r, ans, i;\n    int mid(){ return l + (r-l)/2; }\n};\n\nauto rng = std::mt19937(std::random_device()());\nconstexpr const int MXN = 1e5+5;\n\nvoid solve(){\n    int n; cin >> n;\n    vi a(n); for(auto &x : a) cin >> x, x--;\n    vvi adj(n);\n    for(int i=0; i < n-1; i++){\n        int u, v; cin >> u >> v; u--, v--;\n        adj[u].pb(v); adj[v].pb(u);\n    }\n\n    int q; cin >> q;\n    vector<Query> queries(q);\n    int idx=0;\n    for(auto &[u1, v1, u2, v2, k, l, r, ans, i] : queries) cin >> u1 >> v1 >> u2 >> v2 >> k, u1--, v1--, u2--, v2--, l=0, ans=-1, i=idx++;\n\n    LCA lca(adj);\n    vi uni(a); sort(all(uni)); uni.resize(unique(all(uni)) - uni.begin());\n    vvi cnode(MXN);\n    for(int v=0; v < n; v++) cnode[a[v]].pb(v);\n    vector<HT> hash(MXN);\n    for(auto &c : uni) hash[c] = {rng(), rng()};    \n\n    auto get_ett = [&](vvi &adj){\n        vi tin(n), tout(n);\n        int timer = 0;\n        function<void(int,int)> dfs = [&](int v, int p){\n            tin[v] = timer++;\n            for(auto &to : adj[v]) if(to != p) dfs(to, v);\n            tout[v] = timer++;\n        };\n        dfs(0, -1);\n        return make_pair(tin, tout);\n    };\n    auto [tin, tout] = get_ett(adj);\n\n    for(auto &q : queries) q.r = sz(uni)-1;\n\n    vi vis(MXN);\n    for(int _=0; _<20; _++){\n        FT<HT> st(2*n, mint_ntuple(0));\n        sort(all(queries), [&](Query &a, Query &b) { return a.mid() < b.mid(); });\n        for(int qq=0, cptr=0; qq < q; qq++) if(queries[qq].l <= queries[qq].r) {\n            auto &[u1, v1, u2, v2, k, l, r, ans, i] = queries[qq];\n            for(; cptr < sz(uni) and cptr <= queries[qq].mid(); cptr++){\n                for(auto &v : cnode[uni[cptr]])\n                    st.update(tin[v], hash[uni[cptr]]), st.update(tout[v], mint_ntuple(0)-hash[uni[cptr]]);\n                vis[uni[cptr]] = true;\n            }\n\n            int lca1 = lca.lca(u1, v1), lca2 = lca.lca(u2, v2);\n            HT r1 = st.query(tin[lca1]), r2 = st.query(tin[lca2]);\n            HT hash1 = (st.query(tin[u1]) + st.query(tin[v1]) - (r1 + r1));\n            if(vis[a[lca1]]) hash1 += hash[a[lca1]];\n            HT hash2 = (st.query(tin[u2]) + st.query(tin[v2]) - (r2 + r2));\n            if(vis[a[lca2]]) hash2 += hash[a[lca2]];\n\n            if(hash1 != hash2){\n                ans = queries[qq].mid();\n                r = queries[qq].mid()-1;\n            }\n            else l = queries[qq].mid()+1;\n        }\n        for(auto &c : uni) vis[c] = false;\n    }\n    \n    sort(all(queries), [&](Query &a, Query &b) { return a.i < b.i; });\n    for(auto &[u1, v1, u2, v2, k, l, r, ans, i] : queries){\n        if(ans == -1) cout << 0 << '\\n';\n        else cout << 1 << ' ' << uni[ans]+1 << '\\n';\n    }\n}\nsigned main(){ \n    fightFight; \n    solve(); \n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "hashing",
      "probabilities",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1957",
    "index": "F2",
    "title": "Frequency Mismatch (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the two versions of this problem is the constraint on $k$. You can make hacks only if all versions of the problem are solved.}\n\nYou are given an undirected tree of $n$ nodes. Each node $v$ has a value $a_v$ written on it. You have to answer queries related to the tree.\n\nYou are given $q$ queries. In each query, you are given $5$ integers, $u_1, v_1, u_2, v_2, k$. Denote the count of nodes with value $c$ on path $u_1 \\rightarrow v_1$ with $x_c$, and the count of nodes with value $c$ on path $u_2 \\rightarrow v_2$ with $y_c$. If there are $z$ such values of $c$ such that $x_c \\neq y_c$, output any $\\min(z, k)$ such values in any order.",
    "tutorial": "Let's start by first solving the problem for $k = 1$, and extend the idea to $k > 1$ later. To solve for $k = 1$, we'll find the smallest value that occurs with different frequencies on the two paths. We'll solve an easier version by solving for two static arrays, instead of solving the problem of two paths. To find the smallest value that has a different frequency between the two arrays, we can have a segment tree on the frequency array for each static array. Then, we can store the hash of each segment tree node and perform a descent to find the first point at which the hashes in the two segment trees differ. The hash of a node is the polynomial hash of the subarray it corresponds to. Now, in order to use the same technique on the path, we want the frequency array of the path $u \\rightarrow v$. To achieve this, we can use persistent segment trees. We define $seg(u \\rightarrow v)$ to be the segment tree that corresponds to the frequency array of the values on the path $u \\rightarrow v$. With the idea of persistence, we can quickly compute $seg(1 \\rightarrow u)$ for all $u$, when we root at $1$. To compute $seg(u \\rightarrow v)$, we can use this: $seg(u \\rightarrow v) = seg(1 \\rightarrow u) + seg(1 \\rightarrow v) - seg(1 \\rightarrow lca(u, v)) - seg(1 \\rightarrow parent(lca(u, v)))$ for every node in the segment tree that we want. Hence, we are able to get the segment tree for the two paths we need to compare in a query. In our solution with the static arrays, we used the polynomial hash to find the first point of difference between the two frequency arrays. So, we need a way to quickly compute the hash of the pseudo node we computed for $seg(u \\rightarrow v)$. If we have two frequency arrays $f_1$, $f_2$, $hash(f_1) + hash(f_2) = hash(f_1 + f_2)$, where the hash of a node is the polynomial hash of the subarray that corresponds to that node. Hence, we can say: $hash(seg(u \\rightarrow v)) = hash(seg(1 \\rightarrow u)) + hash(seg(1 \\rightarrow v)) - hash(seg(1 \\rightarrow lca(u, v))) - hash(seg(1 \\rightarrow parent(lca(u, v)))$ Hence, we can perform the same descent that we talked about earlier on the derived segment tree. Now to solve this for $k > 1$, you can perform a dfs on $seg(u \\rightarrow v)$, and keep entering nodes of the segment tree which have differing hashes, until we find $k$ values. The total time complexity comes out to $O(nlogn) + O(q) \\times O(k) \\times O(logn) = O(qklogn + nlogn)$ You can also use an idea similar to the hashing technique used in F1 to hash the segment tree nodes.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int MOD1 = 1e9 + 7;\nconst int MOD2 = 998244353;\nusing ll = long long;\nusing dbl = long double;\n//#define int ll\n \nusing vi = vector<int>;\nusing vvi = vector<vi>;\nusing pii = pair<int, int>;\nusing vii = vector<pii>;\nusing vvii = vector<vii>;\nusing vll = vector<ll>;\n \n#define ff first\n#define ss second\n#define pb push_back\n#define rep(i, a, b) for(int i = a; i < (b); ++i)\n#define all(x) begin(x), end(x)\n#define sz(x) (int)(x).size()\n#define tc int t; cin>>t; while(t--)\n#define fightFight cin.tie(0) -> sync_with_stdio(0)\ntemplate<class T>\nstruct RMQ {\n    vector<vector<T>> jmp;\n    RMQ(const vector<T>& V) : jmp(1, V) {\n        for (int pw = 1, k = 1; pw * 2 <= sz(V); pw *= 2, ++k) {\n            jmp.emplace_back(sz(V) - pw * 2 + 1);\n            rep(j,0,sz(jmp[k]))\n                jmp[k][j] = min(jmp[k - 1][j], jmp[k - 1][j + pw]);\n        }\n    }\n    T query(int a, int b) {\n        assert(a <= b); // tie(a, b) = minimax(a, b)\n        int dep = 31 - __builtin_clz(b-a+1);\n        return min(jmp[dep][a], jmp[dep][b - (1 << dep) + 1]);\n    }\n};\nstruct LCA {\n    int T = 0;\n    vi st, path, ret; vi en, d;\n    RMQ<int> rmq;\n    LCA(vector<vi>& C) : st(sz(C)), en(sz(C)), d(sz(C)), rmq((dfs(C,1,-1), ret)) {}\n    void dfs(vvi &adj, int v, int par) {\n        st[v] = T++;\n        for (auto to : adj[v]) if (to != par) {\n            path.pb(v), ret.pb(st[v]);\n            d[to] = d[v] + 1;\n            dfs(adj, to, v);\n        }\n        en[v] = T-1;\n    }\n    bool anc(int p, int c) { return st[p] <= st[c] and en[p] >= en[c]; }\n    int lca(int a, int b) {\n        if (a == b) return a;\n        tie(a, b) = minmax(st[a], st[b]);\n        return path[rmq.query(a, b-1)];\n    }\n    int dist(int a, int b) { return d[a] + d[b] - 2*d[lca(a,b)]; }\n};\ntemplate<const int mod>\nstruct mint {\n    constexpr mint(int x = 0) : val((x % mod + mod) % mod) {}\n    mint& operator+=(const mint &b) { val += b.val; val -= mod * (val >= mod); return *this; }\n    mint& operator-=(const mint &b) { val -= b.val; val += mod * (val < 0); return *this; }\n    mint& operator*=(const mint &b) { val = 1ll * val * b.val % mod; return *this; }\n    mint& operator/=(const mint &b) { return *this *= b.inv(); }\n    mint inv() const {\n        int x = 1, y = 0, t;\n        for(int a=val, b=mod; b; swap(a, b), swap(x, y))\n            t = a/b, a -= t * b, x -= t * y;\n        return mint(x);\n    }\n    mint pow(int b) const {\n        mint a = *this, res(1);\n        for(; b; a *= a, b /= 2)  if(b&1) res *= a;\n        return res;\n    }\n    friend mint operator+(const mint &a, const mint &b) { return mint(a) += b; }\n    friend mint operator-(const mint &a, const mint &b) { return mint(a) -= b; }\n    friend mint operator*(const mint &a, const mint &b) { return mint(a) *= b; }\n    friend mint operator/(const mint &a, const mint &b) { return mint(a) /= b; }\n    friend bool operator==(const mint &a, const mint &b) { return a.val == b.val; }\n    friend bool operator!=(const mint &a, const mint &b) { return a.val != b.val; }\n    friend bool operator<(const mint &a, const mint &b) { return a.val < b.val; }\n    friend ostream& operator<<(ostream &os, const mint &a) { return os << a.val; }\n    int val;\n};\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\nuniform_int_distribution<ll> rnd(20,10000);\nusing Mint1 = mint<MOD1>;\nusing Mint2 = mint<MOD2>;\nusing Mint = pair<Mint1,Mint2>;\nconst int N = 3e5 + 10, LOGN = 20;\nint p1, p2;\nint blen = 0;\nint L[N * LOGN], R[N * LOGN];\nMint ST[N * LOGN], p_pow[N];\nvoid prec() {\n    p1 = rnd(rng);\n    p2 = p1; \n    while (p2 == p1) p2 = rnd(rng);\n    p_pow[0].ff = 1;\n    p_pow[0].ss = 1;\n    for (int i = 1; i < N; i++) {\n        p_pow[i].ff = p_pow[i - 1].ff * p1;\n        p_pow[i].ss = p_pow[i - 1].ss * p2;\n    }\n}\nint update(int pos, int l, int r, int id) {\n    if (pos < l || pos > r) return id;\n    int ID = ++blen, m = (l + r) / 2;\n    if (l == r) return (ST[ID] = {ST[id].ff + 1, ST[id].ss + 1}, ID);\n    L[ID] = update(pos, l, m, L[id]);\n    R[ID] = update(pos, m + 1, r, R[id]);\n    return (ST[ID] = {ST[L[ID]].ff + p_pow[m - l + 1].ff * ST[R[ID]].ff, ST[L[ID]].ss + p_pow[m - l + 1].ss * ST[R[ID]].ss}, ID);\n}\nvi vals;\nusing a4 = array<int,4>;\nvoid descent(int l, int r, const array<int, 4>& a, const array<int, 4>& b, int k) {\n    if (l == r) return void(vals.push_back(l));\n    int m = (l + r) / 2;\n#define stm(X, y) {ST[X[y[0]]].ff + ST[X[y[1]]].ff - ST[X[y[2]]].ff - ST[X[y[3]]].ff, ST[X[y[0]]].ss + ST[X[y[1]]].ss - ST[X[y[2]]].ss - ST[X[y[3]]].ss}\n#define arr(X, y) (a4{X[y[0]], X[y[1]], X[y[2]], X[y[3]]})\n    Mint l1 = stm(L, a), l2 = stm(L, b), r1 = stm(R, a), r2 = stm(R, b);\n    if (sz(vals) < k && l1 != l2) descent(l, m, arr(L, a), arr(L, b), k);\n    if (sz(vals) < k && r1 != r2) descent(m + 1, r, arr(R, a), arr(R, b), k);\n}\n \nvvi adj;\nvi a, roots, par; \nvoid dfs(int x, int p) {\n    par[x] = p;\n    roots[x] = update(a[x], 0, N, roots[par[x]]);\n    for (auto& s : adj[x]) if (s != p) {\n        dfs(s, x);\n    }\n}\nvoid solve(){\n    int n; cin >> n;        \n    adj = vvi(n + 1);\n    a = roots = par = vi(n + 1);\n    for (int i = 1; i <= n; i++) cin >> a[i];\n    for (int i = 0; i < n - 1; i++) {\n        int a, b; cin >> a >> b;\n        adj[a].pb(b), adj[b].pb(a);\n    }\n    dfs(1, 0);\n    LCA lca(adj);\n    int q; cin >> q;\n    while (q--) {\n        vals.clear();\n        int u1, v1, u2, v2, k; cin >> u1 >> v1 >> u2 >> v2 >> k;\n        int l1 = lca.lca(u1, v1), l2 = lca.lca(u2, v2);\n        a4 a{roots[u1], roots[v1], roots[l1], roots[par[l1]]};\n        a4 b{roots[u2], roots[v2], roots[l2], roots[par[l2]]};\n        descent(0, N, a, b, k);\n        cout << sz(vals) << \" \";\n        for (auto& s : vals) cout << s << \" \";\n        cout << \"\\n\";\n    }\n}\nsigned main(){ \n    fightFight; \n    prec();\n    solve(); \n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "hashing",
      "probabilities",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1965",
    "index": "A",
    "title": "Everything Nim",
    "statement": "Alice and Bob are playing a game on $n$ piles of stones. On each player's turn, they select a positive integer $k$ that is at most the size of the smallest \\textbf{nonempty} pile and remove $k$ stones from \\textbf{each} nonempty pile at once. The first player who is unable to make a move (because all piles are empty) loses.\n\nGiven that Alice goes first, who will win the game if both players play optimally?",
    "tutorial": "If the smallest pile is of size $1$, then Alice must choose $k=1$ in her first move. Therefore, we can imagine subtracting $1$ from all piles, and determining who wins given that Bob goes first. We can repeat this process, switching the first player back and forth, until there is no longer a pile of size $1$. At this point, we are in one of two states: If there are no piles remaining, the first player loses, because they cannot make any moves Otherwise, the smallest pile is of size $x \\ge 2$. We can show that the first player will always win. To do this, consider what happens if the first player chooses $k=x$: If this would create a losing state for the next player, then the first player can choose $k=x$ and win. Otherwise, the state reached by choosing $k=x$ is a winning state for the next player to move. So the first player can choose $k=x-1$, forcing the second player to choose $k=1$. The first player will now be in the winning state and can proceed to win the game. If this would create a losing state for the next player, then the first player can choose $k=x$ and win. Otherwise, the state reached by choosing $k=x$ is a winning state for the next player to move. So the first player can choose $k=x-1$, forcing the second player to choose $k=1$. The first player will now be in the winning state and can proceed to win the game. To implement this solution, we only need to keep track of the largest pile size $a$, and the smallest positive integer $b$ that is not a pile size (essentially the MEX of the pile sizes, excluding $0$). If $b > a$, then Alice and Bob will be forced to choose $k=1$ until the end of the game, so the parity of $a$ determines the winner. Otherwise, they will eventually reach a state with minimum pile size at least $2$, so the parity of $b$ determines the winner. Complexity: $O(n)$ or $O(n\\log n)$ depending on implementation",
    "code": "t = int(input())\n\nfor tc in range(t):\n\n    n = int(input())\n    a = list(map(int, input().split()))\n\n    maxsize = max(a)\n\n    a.sort()\n    mexsize = 1\n    for sz in a:\n        if sz == mexsize:\n            mexsize = mexsize + 1\n\n    if mexsize > maxsize:\n        print(\"Alice\" if maxsize % 2 == 1 else \"Bob\")\n    else:\n        print(\"Alice\" if mexsize % 2 == 1 else \"Bob\")",
    "tags": [
      "games",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1965",
    "index": "B",
    "title": "Missing Subsequence Sum",
    "statement": "You are given two integers $n$ and $k$. Find a sequence $a$ of non-negative integers of size at most $25$ such that the following conditions hold.\n\n- There is no subsequence of $a$ with a sum of $k$.\n- For all $1 \\le v \\le n$ where $v \\ne k$, there is a subsequence of $a$ with a sum of $v$.\n\nA sequence $b$ is a subsequence of $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements, without changing the order of the remaining elements. For example, $[5, 2, 3]$ is a subsequence of $[1, 5, 7, 8, 2, 4, 3]$.\n\nIt can be shown that under the given constraints, a solution always exists.",
    "tutorial": "Notice that for a fixed $k$, a solution for $n=c$ is also a solution for all $n < c$. So we can ignore the value of $n$ and just assume it's always $10^6$. If we didn't have the restriction that no subsequence can add up to $k$, the most natural solution would be $[1, 2, 4, 8, \\cdots 2^{19}]$. Every value from $1$ to $10^6$ appears as the sum of the subsequence given by its binary representation. We will use a modified version of this array to solve the problem. Let $i$ be the largest integer such that $2^i \\le k$. We will use this array (of size $22$): $a=[k-2^i, k+1, k+1+2^i, 1, 2, 4, ... 2^{i-1}, 2^{i+1}, ... 2^{19}]$ To prove that no subsequence of $a$ adds up to $k$, consider the list of all elements in the array that are at most $k$, since these are the only ones that could be present in a subsequence adding to $k$. These are $k-2^i, 1, 2, 4, ... 2^{i-1}$ Since these add up to $k-1$, no subsequence can add up to $k$. To prove that for all $1 \\le v \\le n$ where $v \\ne k$, there is a subsequence adding up to $v$, we consider several cases: If $v < 2^i$, we can simply use the binary representation of $v$. If $2^i \\le v < k$, we can first take all of the elements that are at most $k$ as part of our subsequence. We then need to remove elements with a sum equal to $k-1-v$. Because $2^i \\le v < k < 2^{i+1}$, $k-1-v$ is less than $2^i$, so we can simply remove its binary representation. If $v > k$, we can take $k+1$ along with the binary representation of $v-k-1$. The one edge case is when the $2^i$ bit is set in $v-k-1$. In this case, we replace $k+1$ with $k+1+2^i$. So in all cases, we can form a subsequence adding up to $v$. Complexity: $O(\\log n)$",
    "code": "t = int(input())\n\nfor tc in range(t):\n    n, k = map(int, input().split())\n\n    i = 0\n    while (1 << (i + 1)) <= k:\n        i = i + 1\n\n    ans = [k - (1 << i), k + 1, k + 1 + (1 << i)]\n\n    for j in range(20):\n        if j != i:\n            ans.append(1 << j);\n\n    print(len(ans))\n    print(*ans)",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1965",
    "index": "C",
    "title": "Folding Strip",
    "statement": "You have a strip of paper with a binary string $s$ of length $n$. You can fold the paper in between any pair of adjacent digits.\n\nA set of folds is considered valid if after the folds, all characters that are on top of or below each other match. Note that all folds are made at the same time, so the characters don't have to match in between folds.\n\nFor example, these are valid foldings of $s = \\mathtt{110110110011}$ and $s = \\mathtt{01110}$:\n\nThe length of the folded strip is the length seen from above after all folds are made. So for the two above examples, after the folds shown above, the lengths would be $7$ and $3$, respectively.\n\nNotice that for the above folding of $s = \\mathtt{01110}$, if we made either of the two folds on their own, that would not be a valid folding. However, because we don't check for validity until all folds are made, this folding is valid.\n\nAfter performing a set of valid folds, what is the minimum length strip you can form?",
    "tutorial": "Define the pattern of a (validly) folded strip to be the set of characters, in order, seen from above after all folds are made. It is always possible to fold the strip in such a way that no two adjacent characters in the pattern are equal. If we fold in between every pair of equal characters, and don't fold in between every pair of distinct characters, we will achieve this. This diagram shows one example of this (the red lines indicate where to fold, and the final pattern is $10101$): This set of folds will always be valid because it ensures that all $1$s in the original string are on odd indices and all $0$s are on even indices (or vice versa). Also, there is only one obtainable pattern (up to reversal) that is alternating in this way. It is never possible to fold in between two adjacent different characters, because that can never be part of a valid folding, and if there exists a pair of adjacent equal characters that you don't fold in between, the pattern will not be alternating. We can also show that the pattern formed by this process is always optimal. Let $t$ be any pattern obtained from a valid folding of $s$. Notice that if we perform a valid fold on $t$, that corresponds to a valid fold on $s$, because we can essentially \"compose\" the valid folding of $s$ into $t$ and the valid folding of $t$ into one valid folding. So we can fold $t$ using the process above, which will yield a pattern with alternating characters of length at most $len(t)$. Because the alternating pattern is unique for a given $s$, it must be the same (up to reversal) as the one described above. So the above pattern is of size at most $len(t)$ for any valid pattern $t$, and is therefore optimal. We can simulate the folding process to determine the final length. Complexity: $O(n)$",
    "code": "t = int(input())\n\nfor tc in range(t):\n    n = int(input())\n    s = input()\n    mn = 0\n    mx = 0\n    cur = 0\n\n    for c in s:\n\n        if (cur % 2 == 0) == (c == '1'):\n            cur = cur + 1\n        else:\n            cur = cur - 1\n\n        mn = min(mn, cur)\n        mx = max(mx, cur)\n\n    print(mx - mn)",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1965",
    "index": "D",
    "title": "Missing Subarray Sum",
    "statement": "There is a hidden array $a$ of $n$ positive integers. You know that $a$ is a \\textbf{palindrome}, or in other words, for all $1 \\le i \\le n$, $a_i = a_{n + 1 - i}$. You are given the sums of all but one of its distinct subarrays, in arbitrary order. The subarray whose sum is not given can be any of the $\\frac{n(n+1)}{2}$ distinct subarrays of $a$.\n\nRecover any possible palindrome $a$. The input is chosen such that there is always at least one array $a$ that satisfies the conditions.\n\nAn array $b$ is a subarray of $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "Let's first look at the set of subarray sums of a palindromic array $a$ of $n$ positive integers. Because $a$ is a palindrome, the sum of the subarray with indices in the range $[l, r]$ is the same as the sum of the subarray with indices in the range $[n + 1 - r, n + 1 - l]$. So if we ignore all subarrays where $l + r = n + 1$ (subarrays centered at the center of $a$), each sum must appear an even number of times. Also, every \"centered\" subarray $[l, n + 1 - l]$ must have a unique sum. This is because all elements of $a$ are strictly positive, and if the \"centered\" subarrays are ordered by length, each one contains all elements in the previous one, along with two new elements, so its sum must be strictly greater. Therefore, the set of subarray sums that appear an odd number of times is exactly the set of sums of subarrays centered at the center of $a$. For example, in the array $a = [1, 2, 3, 2, 1]$, the sums that appear an odd number of times are: $3$ ($[3]$, $[1, 2]$, $[2, 1]$) $7$ ($[2, 3, 2]$) $9$ ($[1, 2, 3, 2, 1]$) So if we have all $\\frac{n(n+1)}{2}$ subarray sums of $a$, we can then use the \"centered\" sums to reconstruct $a$ itself. The smallest \"centered\" sum is either the middle element or the sum of the middle two (equal) elements, depending on the parity of $n$, and for each \"centered\" sum in ascending order after that, its difference with the previous sum must be the sum of the next two (equal) elements closest to the center of $a$. Now, let's find out how to reconstruct the missing sum. We consider two cases: If the missing sum is for a \"centered\" subarray, then there will be exactly $\\lceil\\frac{n}{2}\\rceil - 1$ sums that appear an odd number of times in the input. We can use these sums to construct a palindromic array $b$ of size $n-2$ as described above.We can then remove all sums of subarrays of $b$ from the initial input list, and look at what is remaining. If we let $[l, r]$ be the indices of the missing subarray, the largest remaining sum in the list must be the sum of $[1, r]$ in $a$ (or equivalently $[l, n]$). Let this sum be $x$ and the sum of $b$ be $y$. If $l > 1$ (and therefore $r < n$), the missing sum must be $2x-y$, because the $2x$ part includes everything in the missing subarray twice, and everything else once, and $y$ includes everything once. $l=1$, $r=n$ initially seems like it will be an edge case, but the same equation works there as well, since $2x$ includes everything in the missing array (all of $a$) once, and everything in $b$ once, and $y$ includes everything in $b$ once. We can then remove all sums of subarrays of $b$ from the initial input list, and look at what is remaining. If we let $[l, r]$ be the indices of the missing subarray, the largest remaining sum in the list must be the sum of $[1, r]$ in $a$ (or equivalently $[l, n]$). Let this sum be $x$ and the sum of $b$ be $y$. If $l > 1$ (and therefore $r < n$), the missing sum must be $2x-y$, because the $2x$ part includes everything in the missing subarray twice, and everything else once, and $y$ includes everything once. $l=1$, $r=n$ initially seems like it will be an edge case, but the same equation works there as well, since $2x$ includes everything in the missing array (all of $a$) once, and everything in $b$ once, and $y$ includes everything in $b$ once. If the missing sum is not for a \"centered\" subarray, then there will be exactly $\\lceil\\frac{n}{2}\\rceil + 1$ sums that appear an odd number of times in the input. We can use these sums to construct a palindromic array $b$ of size $n+2$ as described above.In a similar way to the previous case, we can then remove all sums from the initial input list from the set of subset sums of $b$. If we let $[l, r]$ be the indices of the extra \"centered\" subarray in $b$, the largest remaining sum in the list must be the sum of $[1, r]$ in $b$ (or equivalently $[l, n + 2]$). If we let $x$ be this largest sum, and $y$ be the sum of $b$, we can use similar logic to the previous case to determine that the missing sum is $2x-y$. In a similar way to the previous case, we can then remove all sums from the initial input list from the set of subset sums of $b$. If we let $[l, r]$ be the indices of the extra \"centered\" subarray in $b$, the largest remaining sum in the list must be the sum of $[1, r]$ in $b$ (or equivalently $[l, n + 2]$). If we let $x$ be this largest sum, and $y$ be the sum of $b$, we can use similar logic to the previous case to determine that the missing sum is $2x-y$. So we can determine the missing sum, using the number of sums that appear an odd number of times in the input to determine which case we are in. Once we have found the missing sum, we just need to reconstruct $a$ using the process above. Also, notice that by the construction we have followed so far, the solution is always unique. Complexity: $O(n^2 \\log n)$",
    "code": "def getSubarraySums(a):\n\n    cts = []\n    for i in range(len(a)):\n        sm = 0\n        for j in range(i, len(a)):\n            sm = sm + a[j]\n            cts.append(sm)\n\n    cts.sort()\n    return cts\n\ndef getOddOccurringElements(cts):\n\n    odds = []\n\n    for ct in cts:\n        if len(odds) > 0 and ct == odds[-1]:\n            odds.pop()\n        else:\n            odds.append(ct)\n    return odds\n\ndef getPalindrome(odds, n):\n\n    a = [0] * n\n    prev = 0\n    idx = (n - 1) // 2\n    \n    for x in odds:\n        if idx == n - 1 - idx:\n            a[idx] = x\n        else:\n            a[idx] = (x - prev) // 2\n            a[n - 1 - idx] = (x - prev) // 2\n        prev = x\n        idx = idx - 1\n    \n    return a\n\ndef getLargestExcluded(bigList, smallList):\n\n    while len(smallList) > 0 and bigList[-1] == smallList[-1]:\n        bigList.pop()\n        smallList.pop()\n    return bigList[-1]\n\nt = int(input())\n\nfor tc in range(t):\n\n    n = int(input())\n    \n    subarraySums = list(map(int, input().split()))\n    subarraySums.sort()\n    odds = getOddOccurringElements(subarraySums)\n    \n    missingSum = -1\n    \n    if len(odds) > (n + 1) // 2:\n    \n        oddvals = []\n        evenvals = []\n        for x in odds:\n            if x % 2 == 1:\n                oddvals.append(x)\n            else:\n                evenvals.append(x)\n\n        if len(evenvals) > 0 and len(oddvals) > 0:\n\n            missingSum = evenvals[0] if len(evenvals) == 1 else oddvals[0]\n\n        else:\n\n            b = getPalindrome(odds, n + 2)\n            bSums = getSubarraySums(b)\n            y = bSums[-1]\n            x = getLargestExcluded(bSums, subarraySums)\n            missingSum = 2 * x - y\n    \n    else:\n        \n        b = getPalindrome(odds, n - 2)\n        bSums = getSubarraySums(b)\n        y = bSums[-1]\n        x = getLargestExcluded(subarraySums, bSums)\n        missingSum = 2 * x - y\n\n    odds.append(missingSum)\n    odds.sort()\n    odds = getOddOccurringElements(odds)\n    \n    ans = getPalindrome(odds, n)\n    print(*ans)",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1965",
    "index": "E",
    "title": "Connected Cubes",
    "statement": "There are $n \\cdot m$ unit cubes currently in positions $(1, 1, 1)$ through $(n, m, 1)$. Each of these cubes is one of $k$ colors. You want to add additional cubes at any integer coordinates such that the subset of cubes of each color is connected, where two cubes are considered connected if they share a face.\n\nIn other words, for every pair of cubes of the same color $c$, it should be possible to travel from one to the other, moving only through cubes of color $c$ that share a face.\n\nThe existing cubes are currently in the corner of a room. There are colorless cubes completely filling the planes $x = 0$, $y = 0$, and $z = 0$, preventing you from placing additional cubes there or at any negative coordinates.\n\nFind a solution that uses at most $4 \\cdot 10^5$ additional cubes (not including the cubes that are currently present), or determine that there is no solution. It can be shown that under the given constraints, if there is a solution, there is one using at most $4 \\cdot 10^5$ additional cubes.",
    "tutorial": "We can show that a solution always exists. This example with $n=3$, $m=5$, $k=4$ will demonstrate the construction we will use: First, extend each of the even columns up by $n+k-1$ spaces, keeping all cubes in a given vertical column the same color: Then, for the odd columns, do something similar, except we use the bottom $n-1$ rows to \"bend\" them around so the tops point out to the right: After that, extend each of these new \"bent\" rows (each of which corresponds to an input cube in an odd column) to the right by $k$: Now, each initial cube in the $n$ by $m$ grid corresponds to one of these extended rows or columns, each of which is a connected group. Fill in the remaining columns between the even columns with $k$ rows each. The $i$-th of these should be color $i$. Now do the same for the odd columns: At this point, each cell of a given color is connected to at least one of the rows/columns we added in the last two steps. Now, we want to connect all of those by color. Start by adding these $k$ rows: Followed by these $k-1$ rows: Once again, at this point, each cube of a given color is connected to one of the rows of that color we added in the last two steps. So the last remaining step is to connect them: Now, all cubes of each color are connected. This construction uses exactly $(n+k)^2m - (k-1)^2(m-1) - nm$ additional cubes. Since $n, m, k \\le 50$, this is at most $379,851$, which fits within the bounds of the problem. Complexity: $O((n+k)^2 m)$",
    "code": "n, m, k = map(int, input().split())\na = []\n\nfor i in range(n):\n    a.append(list(map(int, input().split())))\n\nans = []\n\nfor x in range(n):\n    for y in range(m):\n        for z in range(1, n + 1):\n            if y % 2 == 1:\n                ans.append([x, y, z, a[x][y]])\n            else:\n                ans.append([x, y, z, a[min(x, n - z)][y]])\n        for z in range(n + 1, n + k + 1):\n            if y % 2 == 1:\n                ans.append([x, y, z, a[x][y]])\n            else:\n                ans.append([x, y, z, z - n])\n\nfor x in range(n, n + k):\n    for y in range(m):\n        for z in range(1, n + 1):\n            if y % 2 == 1:\n                ans.append([x, y, z, x - n + 1])\n            else:\n                ans.append([x, y, z, a[n - z][y]])\n        ans.append([x, y, n + 1, x - n + 1])\n\nfor y in range(m):\n    for z in range(n + 2, n + k + 1):\n        ans.append([n, y, z, z - n])\n\nfor x in range(n + 1, n + k):\n    for z in range(n + 2, n + k + 1):\n        ans.append([x, 0, z, max(x - n + 1, z - n)])\n\nprint(len(ans))\n\nfor cube in ans:\n    print(cube[0] + 1, cube[1] + 1, cube[2] + 1, cube[3])",
    "tags": [
      "constructive algorithms",
      "games"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1965",
    "index": "F",
    "title": "Conference",
    "statement": "You have been asked to organize a very important art conference. The first step is to choose the dates.\n\nThe conference must last for a certain number of consecutive days. Each day, one lecturer must perform, and the same lecturer cannot perform more than once.\n\nYou asked $n$ potential lecturers if they could participate in the conference. Lecturer $i$ indicated that they could perform on any day from $l_i$ to $r_i$ inclusive.\n\nA certain segment of days can be chosen as the conference dates if there is a way to assign an available lecturer to each day of the segment, assigning each lecturer to no more than one day.\n\nFor each $k$ from $1$ to $n$, find how many ways there are to choose a segment of $k$ consecutive days as the conference dates.",
    "tutorial": "For a segment of days, how can we tell if there's a way to assign a lecturer to each day of the segment? Consider a bipartite graph: the first part consists of the days in the segment, the second part consists of all lecturers, an edge between a day and a lecturer exists if that lecturer is available on that day. We need to check if the maximum matching covers all vertices in the first part. If this is the case, we'll call the segment of days valid. A common way to check if a segment is valid is to use Hall's marriage theorem. In our case, we can formulate it as follows: If for each subset of days $s$, the number of lecturers available on at least one day of that subset is at least $|s|$, then this segment of days is valid. It might be tempting to only consider subsets which form contiguous subsegments. However, consider the following test case: For a segment of days $[1; 3]$, the only subset that violates the Hall's marriage theorem condition is $\\{1, 3\\}$, which is not contiguous. Let's try to fix that. Suppose there are two lecturers with equal $l_i$: let their availability segments be $[a; b]$ and $[a; c]$, where $b \\le c$. Then, if we replace $[a; c]$ with $[a+1; c]$, the answer does not change. This can be easily seen if you consider the set of all pairs of days that these two lecturers can cover, and notice that this set stays the same after the $[a; c] \\rightarrow [a+1; c]$ transformation. (Note that when $a = b = c$, replacing $[a; c]$ with $[a+1; c]$ is effectively equivalent to removing one of the lecturers: their segment becomes empty.) We can keep applying this operation until all $l_i$ are distinct (potentially removing some lecturers in the process). This process can be simulated in $O(n \\log n)$ time by going left to right using a priority queue. Why is this transformation useful? Consider a subset of days $t$ that violates the Hall's marriage theorem condition. Suppose it's non-contiguous: say, days $x$ and $y$ ($x + 1 < y$) belong to $t$, while none of days $x+1, x+2, \\ldots, y-1$ belong to $t$. Then, if we include days $x+1, x+2, \\ldots, y-1$ into $t$, then $t$ will still violate the condition! (proof left as an exercise) As a consequence, if we include all \"gaps\" in $t$, we'll still get a violating subset, but this time, it will be contiguous. We have described a transformation that makes all $l_i$ distinct. Similarly, we can apply it in the same way to make all $r_i$ distinct. After that, we'll get another useful property: monotonicity. Specifically, if $t = [l; r]$ is a violating subset, then $[l-1; r]$ and $[l; r+1]$ are violating subsets as well. Now we can see that a segment of days is valid iff it is not a violating subset itself (i.e. instead of checking all subsets of the segment, it's enough to just check the whole segment). To finish the solution, we can use the two pointers technique to find all valid segments in linear time. Bonus: solve the problem for $1 \\le l_i \\le r_i \\le 10^{12}$.",
    "code": "/**\n *    author:  tourist\n *    created: 26.11.2023 09:36:38       \n**/\n#include <bits/stdc++.h>\n \nusing namespace std;\n \n#ifdef LOCAL\n#include \"algo/debug.h\"\n#else\n#define debug(...) 42\n#endif\n \nconst long long inf = (long long) 1e18;\n \nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(0);\n  int n;\n  cin >> n;\n  vector<long long> l(n), r(n);\n  for (int i = 0; i < n; i++) {\n    cin >> l[i] >> r[i];\n  }\n  int original_n = n;\n  for (int rot = 0; rot < 2; rot++) {\n    // make all left ends distinct\n    map<long long, vector<long long>> mp;\n    for (int i = 0; i < n; i++) {\n      mp[l[i]].push_back(r[i]);\n    }\n    vector<long long> new_l, new_r;\n    auto it = mp.begin();\n    multiset<long long> s;\n    long long T = -inf;\n    while (true) {\n      if (s.empty()) {\n        if (it == mp.end()) {\n          break;\n        }\n        T = it->first;\n      }\n      while (it != mp.end() && T == it->first) {\n        s.insert(it->second.begin(), it->second.end());\n        ++it;\n      }\n      assert(!s.empty());\n      new_l.push_back(T);\n      new_r.push_back(*s.begin());\n      s.erase(s.begin());\n      T += 1;\n      while (!s.empty() && *s.begin() < T) {\n        s.erase(s.begin());\n      }\n    }\n    swap(l, new_l);\n    swap(r, new_r);\n    n = (int) l.size();\n    for (int i = 0; i < n; i++) {\n      l[i] *= -1;\n      r[i] *= -1;\n      swap(l[i], r[i]);\n    }\n  }\n  sort(l.begin(), l.end());\n  sort(r.begin(), r.end());\n  vector<long long> ans(original_n + 1);\n  long long lx = -inf, rx = -inf;\n  int pl = 0, pr = 0;\n  int k = 0;\n  while (pl < n || pr < n) {\n    long long wait = min(pl < n ? l[pl] - lx : inf, pr < n ? r[pr] - rx : inf);\n    ans[k] += wait;\n    lx += wait;\n    rx += wait;\n    while (pl < n && l[pl] == lx) {\n      k += 1;\n      lx += 1;\n      pl += 1;\n    }\n    while (pr < n && r[pr] == rx) {\n      ans[k] += 1;\n      k -= 1;\n      rx += 1;\n      pr += 1;\n    }\n  }\n  for (int i = n; i > 1; i--) {\n    ans[i - 1] += ans[i];\n  }\n  for (int i = 1; i <= original_n; i++) {\n    cout << ans[i] << '\\n';\n  }\n  return 0;\n}",
    "tags": [
      "data structures",
      "flows"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1966",
    "index": "A",
    "title": "Card Exchange",
    "statement": "You have a hand of $n$ cards, where each card has a number written on it, and a fixed integer $k$. You can perform the following operation any number of times:\n\n- Choose any $k$ cards from your hand that all have the same number.\n- Exchange these cards for $k-1$ cards, each of which can have \\textbf{any} number you choose (including the number written on the cards you just exchanged).\n\nHere is one possible sequence of operations for the first example case, which has $k=3$:\n\nWhat is the minimum number of cards you can have in your hand at the end of this process?",
    "tutorial": "If you don't initially have at least $k$ copies of any number, you can't perform any operations, so the answer is $n$. Otherwise, we can show that we can always get down to $k-1$ cards, with the following algorithm: Choose any card that you have $k$ copies of, and remove those $k$ copies If you have no more cards, take any $k-1$ cards and end the process. Otherwise, let $x$ be the number on any card you have. Take $k-1$ copies of $x$. Now, you have at least $k$ copies of $x$, so return to step $1$. Since the total number of cards decreases at each step, this process will always terminate, so you will always end up with $k-1$ cards. Also, since the total number of cards decreases by exactly $1$ at each step, and you can't do any operations if you have less than $k$ cards, it is impossible to do better than $k-1$, so our solution of $k-1$ is optimal. Complexity: $O(n)$ or $O(n \\log n)$ depending on implementation.",
    "code": "t = int(input())\n\nfor tc in range(t):\n    n, k = map(int, input().split())\n\n    cards = list(map(int, input().split()))\n    ct = {}\n\n    ans = n\n\n    for c in cards:\n        if c in ct:\n            ct.update({c: ct[c] + 1})\n        else:\n            ct.update({c: 1})\n        if ct[c] >= k:\n            ans = k - 1\n\n    print(ans)",
    "tags": [
      "constructive algorithms",
      "games",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "1966",
    "index": "B",
    "title": "Rectangle Filling",
    "statement": "There is an $n \\times m$ grid of white and black squares. In one operation, you can select any two squares of the same color, and color all squares in the subrectangle between them that color.\n\nFormally, if you select positions $(x_1, y_1)$ and $(x_2, y_2)$, both of which are currently the same color $c$, set the color of all $(x, y)$ where $\\min(x_1, x_2) \\le x \\le \\max(x_1, x_2)$ and $\\min(y_1, y_2) \\le y \\le \\max(y_1, y_2)$ to $c$.\n\nThis diagram shows a sequence of two possible operations on a grid:\n\nIs it possible for all squares in the grid to be the same color, after performing any number of operations (possibly zero)?",
    "tutorial": "If either pair of opposite corners is the same color, then we can choose those corners to make everything the same color in one operation. Otherwise, we have four cases for the colors of the corners: Notice that these are all essentially rotations of each other, so we can only consider the first case by symmetry: If any of the squares in the first row are black, then we can color everything black in two operations: In the same way, if any of the squares in the last row are white, then we can color everything white in two operations. Otherwise, the grid looks like this: Notice that no matter how many operations we do, all squares in the top row will remain white, and all squares in the bottom row will remain black, so we can never make everything the same color. So, considering the four cases from earlier, the solution is: NO if all squares in the top row are the same color, all squares in the bottom row are the same color, and these two colors are different NO if all squares in the leftmost column are the same color, all squares in the rightmost column are the same color, and these two colors are different YES otherwise Complexity: $O(nm)$",
    "code": "t = int(input())\n\nfor tc in range(t):\n    n, m = map(int, input().split())\n    gr = []\n\n    for i in range(n):\n        gr.append(input())\n\n    ans = \"YES\"\n\n    if gr[0][0] != gr[n - 1][m - 1]:\n\n        impossible = True\n        for j in range(m - 1):\n            if gr[0][j] != gr[0][j + 1] or gr[n - 1][j] != gr[n - 1][j + 1]:\n                impossible = False\n\n        if impossible:\n            ans = \"NO\"\n\n        impossible = True\n        for i in range(n - 1):\n            if gr[i][0] != gr[i + 1][0] or gr[i][m - 1] != gr[i + 1][m - 1]:\n                impossible = False\n\n        if impossible:\n            ans = \"NO\"\n\n    print(ans)",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1967",
    "index": "A",
    "title": "Permutation Counting",
    "statement": "You have some cards. An integer between $1$ and $n$ is written on each card: specifically, for each $i$ from $1$ to $n$, you have $a_i$ cards which have the number $i$ written on them.\n\nThere is also a shop which contains unlimited cards of each type. You have $k$ coins, so you can buy $k$ new cards in total, and the cards you buy can contain any integer between $1$ and $n$.\n\nAfter buying the new cards, you rearrange all your cards in a line. The score of a rearrangement is the number of (contiguous) subarrays of length $n$ which are a permutation of $[1, 2, \\ldots, n]$. What's the maximum score you can get?",
    "tutorial": "If $a_1=a_2=\\cdots=a_n$ and $k=0$, it's obvious that the optimal rearrangement is $[1,2,\\cdots,n,1,2,\\cdots,n,\\cdots,1,2,\\cdots,n]$, because every subarray of length $n$ is a permutation of $1\\sim n$. WLOG, assume that $a_1\\ge a_2\\ge\\cdots a_n=w$. If $k=0$, we can insert more numbers at the back and form more permutations. But because $a_n$ is the minimum number, we can only make these subarrays become permutations: The remaining cards can be placed arbitrarily. This won't always be satisfied (if $a_{n-1}=w$, the green subarray won't exist). But this will only happen if $a_{n-1}=w$ is also minimum. It's the same for $a_{n-2}$ etc. So we can calculate the answer: $ans = nw - \\sum_{i=1}^n [a_i = w] + 1$ Considering $k > 0$ cases, we find that every time we choose a minimum $a_i$ and increase it by $1$, the answer will be increased. And the answer won't change if we increase some other $a_i$. So we have two different approaches: Sort the array $a$, enumerate the range where the minimum number will be, and check if it's possible. If so, we can just calculate by using the above equation. Binary search the $w$ after buying cards. After calculating the array $a$ after buying cards, we will be able to calculate the answer. Time complexity: $\\mathcal O(n\\log n)$ or $\\mathcal O(n\\log a_i)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid solve()\n{\n    int n;long long k;\n    cin>>n>>k;\n    vector<long long>a(n);\n    for(int x=0;x<n;x++)\n    cin>>a[x];\n    sort(a.begin(),a.end());\n    reverse(a.begin(),a.end());\n    long long lst=a.back(),cnt=1;\n    a.pop_back();\n    while(!a.empty()&&lst==a.back())a.pop_back(),cnt++;\n    while(!a.empty())\n    {\n        long long delta=a.back()-lst;\n        if(k<delta*cnt)break;\n        k-=delta*cnt;\n        lst=a.back();\n        while(!a.empty()&&lst==a.back())a.pop_back(),cnt++;\n    }\n    lst+=k/cnt;\n    k%=cnt;\n    cnt-=k;\n    cout<<lst*n-cnt+1<<endl;\n}\nmain()\n{\n    ios::sync_with_stdio(false),cin.tie(0);\n    int t;\n    cin>>t;\n    while(t--)solve();\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1967",
    "index": "B1",
    "title": "Reverse Card (Easy Version)",
    "statement": "\\textbf{The two versions are different problems. You may want to read both versions. You can make hacks only if both versions are solved.}\n\nYou are given two positive integers $n$, $m$.\n\nCalculate the number of ordered pairs $(a, b)$ satisfying the following conditions:\n\n- $1\\le a\\le n$, $1\\le b\\le m$;\n- $a+b$ is a multiple of $b \\cdot \\gcd(a,b)$.",
    "tutorial": "Denote $\\gcd(a,b)$ as $d$. Assume that $a=pd$ and $b=qd$, then we know that $\\gcd(p,q)=1$. $(b\\cdot\\gcd(a,b))\\mid (a+b)\\iff (qd^2)\\mid (pd+qd)\\iff (qd)\\mid (p+q)$. Assume that $p+q=kqd$, then $p=(kd-1)q$. We know $q=1$ because $\\gcd(p,q)=1$. Enumerate $d$ from $1$ to $m$, we know $p+1=kd\\le\\lfloor\\frac{n}{d}\\rfloor+1$, so we add $\\left\\lfloor\\frac{\\lfloor\\frac{n}{d}\\rfloor+1}{d}\\right\\rfloor$ to answer. In this method, $p=0,k=1,d=1$ will also be included in the answer, so we should subtract $1$ from the answer. Time Complexity: $\\mathcal O(\\sum m)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst int N=2000005;\nint tc,n,m; ll ans;\ninline void solve(){\n\tcin>>n>>m; ans=0;\n\tfor(int i=1;i<=m;i++)\n\t\tans+=(n+i)/(1ll*i*i);\n\tcout<<ans-1<<'\\n';\n}\nint main(){\n\tios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tcin>>tc; while(tc--) solve();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1967",
    "index": "B2",
    "title": "Reverse Card (Hard Version)",
    "statement": "\\textbf{The two versions are different problems. You may want to read both versions. You can make hacks only if both versions are solved.}\n\nYou are given two positive integers $n$, $m$.\n\nCalculate the number of ordered pairs $(a, b)$ satisfying the following conditions:\n\n- $1\\le a\\le n$, $1\\le b\\le m$;\n- $b \\cdot \\gcd(a,b)$ is a multiple of $a+b$.",
    "tutorial": "Denote $\\gcd(a,b)$ as $d$. Assume that $a=pd$ and $b=qd$, then we know that $\\gcd(p,q)=1$. $(a+b)\\mid (b\\cdot\\gcd(a,b))\\iff (pd+qd)\\mid (qd^2)\\iff (p+q)\\mid (qd)$. We know that $\\gcd(p+q,q)=\\gcd(p,q)=1$, so $(p+q)\\mid d$. We also know that $p\\ge 1,q\\ge 1$, so $p < d=\\frac{a}{p}\\le \\frac{n}{p}$ and thus $p^2 < n$. Similarly, we can prove $q^2 < m$. So the number of $(p,q)$ is $\\mathcal O(\\sqrt{nm})=\\mathcal O(n+m)$. We can enumerate each $(p,q)$ such that $\\gcd(p,q)=1$ and calculate the answer. $(p+q)\\mid d$ is required, so we add $\\left\\lfloor\\frac{\\min\\{\\lfloor\\frac{n}{p}\\rfloor,\\lfloor\\frac{m}{q}\\rfloor\\}}{p+q}\\right\\rfloor$. Time Complexity: $\\mathcal O(\\sum n + \\sum m)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define nl \"\\n\"\n#define nf endl\n#define ll long long\n#define pb push_back\n#define _ << ' ' <<\n \n#define INF (ll)1e18\n#define mod 998244353\n#define maxn 110\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    #if !ONLINE_JUDGE && !EVAL\n        ifstream cin(\"input.txt\");\n        ofstream cout(\"output.txt\");\n    #endif\n    int t;\n    cin>>t;\n    while(t--)\n    {\n        ll n,m; cin >> n>>m;\n        ll sq = sqrt(n) + 2,sqm=sqrt(m)+2;\n    \n        vector bad(sq + 1, vector<bool>(sqm+1, 0));\n        for (ll i = 2; i <= min(sq,sqm); i++) {\n            for (ll a = i; a <= sq; a += i) {\n                for (ll b = i; b <= sqm; b += i) {\n                    bad[a][b] = true;\n                }\n            }\n        }\n    \n        ll ans = 0;\n        for (ll a = 1; a * a <= n; a++) {\n            for (ll b = 1; b * b <= m; b++) {\n                if (bad[a][b]) continue;\n                ans += min(n/(a+b)/a,m/(a+b)/b);\n            }\n        }\n        cout << ans << nl;\n    }\n \n    return 0;\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1967",
    "index": "C",
    "title": "Fenwick Tree",
    "statement": "Let $\\operatorname{lowbit}(x)$ denote the value of the lowest binary bit of $x$, e.g. $\\operatorname{lowbit}(12)=4$, $\\operatorname{lowbit}(8)=8$.\n\nFor an array $a$ of length $n$, if an array $s$ of length $n$ satisfies $s_k=\\left(\\sum\\limits_{i=k-\\operatorname{lowbit}(k)+1}^{k}a_i\\right)\\bmod 998\\,244\\,353$ for all $k$, then $s$ is called the Fenwick Tree of $a$. Let's denote it as $s=f(a)$.\n\nFor a positive integer $k$ and an array $a$, $f^k(a)$ is defined as follows:\n\n$$ f^k(a)= \\begin{cases} f(a)&\\textrm{if }k=1\\\\ f(f^{k-1}(a))&\\textrm{otherwise.}\\\\ \\end{cases} $$\n\nYou are given an array $b$ of length $n$ and a positive integer $k$. Find an array $a$ that satisfies $0\\le a_i < 998\\,244\\,353$ and $f^k(a)=b$. It can be proved that an answer always exists. If there are multiple possible answers, you may print any of them.",
    "tutorial": "It's well-known that Fenwick Tree is the data structure shown in the image below, and the sum of each subtree is stored at each vertex (i.e. $c=f(a)$ and $c_u=\\sum\\limits_{v\\textrm{ in subtree of }u}a_v$). Denote the depth of a vertex $u$ as $\\operatorname{dep}(u)$. Assume that $b=f^k(a)$. Consider a vertex $u$ and one of its ancestors $v$. Let $\\Delta d=\\operatorname{dep}(u)-\\operatorname{dep}(v)$. It can be easily proved (by using the stars and bars method or generating functions) that the coefficient of $a_u$ in $b_v$ is $\\binom{\\Delta d+k-1}{\\Delta d}$. Obviously, $a_u=b_u$ is satisfied for each leaf $u$. Enumerate each vertex $u$ whose $a$ value is already known (just in the increasing order is fine), and all its ancestors $v$, remove the $\\textrm{coefficient}\\cdot a_u$ part from $b_v$, and we can calculate the $a$ value of each vertex. Time complexity is $\\mathcal O(n\\log n)$ because the height of a Fenwick Tree is $\\mathcal O(\\log n)$.",
    "code": "//By: OIer rui_er\n#include <bits/stdc++.h>\n#define rep(x, y, z) for(int x = (y); x <= (z); ++x)\n#define per(x, y, z) for(int x = (y); x >= (z); --x)\n#define debug(format...) fprintf(stderr, format)\n#define fileIO(s) do {freopen(s\".in\", \"r\", stdin); freopen(s\".out\", \"w\", stdout);} while(false)\n#define endl '\\n'\nusing namespace std;\ntypedef long long ll;\n \nmt19937 rnd(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count());\nint randint(int L, int R) {\n    uniform_int_distribution<int> dist(L, R);\n    return dist(rnd);\n}\n \ntemplate<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}\ntemplate<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}\n \ntemplate<int mod>\ninline unsigned int down(unsigned int x) {\n\treturn x >= mod ? x - mod : x;\n}\n \ntemplate<int mod>\nstruct Modint {\n\tunsigned int x;\n\tModint() = default;\n\tModint(unsigned int x) : x(x) {}\n\tfriend istream& operator>>(istream& in, Modint& a) {return in >> a.x;}\n\tfriend ostream& operator<<(ostream& out, Modint a) {return out << a.x;}\n\tfriend Modint operator+(Modint a, Modint b) {return down<mod>(a.x + b.x);}\n\tfriend Modint operator-(Modint a, Modint b) {return down<mod>(a.x - b.x + mod);}\n\tfriend Modint operator*(Modint a, Modint b) {return 1ULL * a.x * b.x % mod;}\n\tfriend Modint operator/(Modint a, Modint b) {return a * ~b;}\n\tfriend Modint operator^(Modint a, int b) {Modint ans = 1; for(; b; b >>= 1, a *= a) if(b & 1) ans *= a; return ans;}\n\tfriend Modint operator~(Modint a) {return a ^ (mod - 2);}\n\tfriend Modint operator-(Modint a) {return down<mod>(mod - a.x);}\n\tfriend Modint& operator+=(Modint& a, Modint b) {return a = a + b;}\n\tfriend Modint& operator-=(Modint& a, Modint b) {return a = a - b;}\n\tfriend Modint& operator*=(Modint& a, Modint b) {return a = a * b;}\n\tfriend Modint& operator/=(Modint& a, Modint b) {return a = a / b;}\n\tfriend Modint& operator^=(Modint& a, int b) {return a = a ^ b;}\n\tfriend Modint& operator++(Modint& a) {return a += 1;}\n\tfriend Modint operator++(Modint& a, int) {Modint x = a; a += 1; return x;}\n\tfriend Modint& operator--(Modint& a) {return a -= 1;}\n\tfriend Modint operator--(Modint& a, int) {Modint x = a; a -= 1; return x;}\n\tfriend bool operator==(Modint a, Modint b) {return a.x == b.x;}\n\tfriend bool operator!=(Modint a, Modint b) {return !(a == b);}\n};\n \nconst int N = 1e6 + 100, mod = 998244353;\ntypedef Modint<mod> mint;\n \nint T, n, k;\nmint a[N], inv[N];\n \ninline int lowbit(int x) {return x & -x;}\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); cout.tie(0);\n    inv[0] = inv[1] = 1;\n    rep(i, 2, N - 1) inv[i] = (mod - mod / i) * inv[mod % i];\n    for(cin >> T; T; --T) {\n        cin >> n >> k;\n        rep(i, 1, n) cin >> a[i];\n        rep(i, 1, n) {\n            mint mul = 1;\n            for(int u = i + lowbit(i), d = 1; u <= n; u += lowbit(u), ++d) {\n                mul *= (d + k - 1) * inv[d];\n                a[u] -= mul * a[i];\n            }\n        }\n        rep(i, 1, n) cout << a[i] << \" \\n\"[i == n];\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "data structures",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1967",
    "index": "D",
    "title": "Long Way to be Non-decreasing",
    "statement": "Little R is a magician who likes non-decreasing arrays. She has an array of length $n$, initially as $a_1, \\ldots, a_n$, in which each element is an integer between $[1, m]$. She wants it to be non-decreasing, i.e., $a_1 \\leq a_2 \\leq \\ldots \\leq a_n$.\n\nTo do this, she can perform several magic tricks. Little R has a fixed array $b_1\\ldots b_m$ of length $m$. Formally, let's define a trick as a procedure that does the following things in order:\n\n- Choose a set $S \\subseteq \\{1, 2, \\ldots, n\\}$.\n- For each $u \\in S$, assign $a_u$ with $b_{a_u}$.\n\nLittle R wonders how many tricks are needed at least to make the initial array non-decreasing. If it is not possible with any amount of tricks, print $-1$ instead.",
    "tutorial": "Binary search on the answer of magics. You may come up with many $\\mathcal O(m\\log m + n\\log^2 m)$ solutions with heavy data structures. Unfortunately, none of them is helpful. The key is to judge $\\mathcal O(m\\log n)$ times whether vertex $u$ is reachable from vertex $v$ in $k$ steps, instead of querying the minimal value or something else.",
    "code": "#include <bits/stdc++.h>\n \nnamespace FastIO {\n\ttemplate <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }\n\ttemplate <typename T> inline void write(T x) { if (!x) return; write<T>(x / 10), putchar(x % 10 ^ '0'); }\n\ttemplate <typename T> inline void print(T x) { if (x < 0) putchar('-'), x = -x; else if (x == 0) putchar('0'); write<T>(x); }\n\ttemplate <typename T> inline void print(T x, char en) { if (x < 0) putchar('-'), x = -x; else if (x == 0) putchar('0'); write<T>(x), putchar(en); }\n}; using namespace FastIO;\n \n#define MAXM 1000001\nint dep[MAXM], id[MAXM], dfn[MAXM], to[MAXM], sz[MAXM], tot = 0;\nstd::vector<int> ch[MAXM];\nvoid dfs(int u) {\n\tsz[u] = 1, dfn[u] = ++tot;\n\tfor (int v : ch[u]) {\n\t\tdep[v] = dep[u] + 1, id[v] = id[u];\n\t\tdfs(v), sz[u] += sz[v];\n\t}\n}\ninline bool inSub(int u, int v) /* v \\in u ? */ { return dfn[u] <= dfn[v] && dfn[v] < dfn[u] + sz[u]; }\nconstexpr int INF = 0x3f3f3f3f;\ninline int query(int u, int v) /* u -> v */ {\n\tif (u == v) return 0;\n\tif (id[u] != id[v]) return INF;\n\tint res = INF;\n\tif (inSub(v, u)) res = dep[u] - dep[v];\n\tif (inSub(v, to[id[u]])) res = std::min(dep[u] - dep[v] + dep[to[id[u]]] + 1, res);\n\t// printf(\"query(%d, %d) = %d\\n\", u, v, res);\n\treturn res;\n}\n \n#define MAXN 1000001\nint a[MAXN], N, M;\nbool check(int val) {\n\t// printf(\"check %d\\n\", val);\n\tint lst = 1;\n\tfor (int i = 1; i <= N; ++i) {\n\t\twhile (lst <= M && query(a[i], lst) > val) ++lst;\n\t\tif (lst > M) return false;\n\t\t// printf(\"a[%d] = %d\\n\", i, lst);\t\n\t}\n\treturn true;\n}\n \nnamespace DSU {\n\tint fa[MAXM];\n\tvoid inis(int n) { for (int i = 1; i <= n; ++i) fa[i] = i; }\n\tinline int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }\n\tinline bool merge(int x, int y) { if (find(x) == find(y)) return false; fa[fa[x]] = fa[y]; return true; }\n}; using namespace DSU;\n \nint main() {\n\tint T = read<int>();\n\twhile (T--) {\n\t\tN = read<int>(), M = read<int>(), inis(M);\n\t\tfor (int i = 1; i <= N; ++i) a[i] = read<int>();\n\t\tfor (int x = 1; x <= M; ++x) dep[x] = id[x] = dfn[x] = to[x] = sz[x] = 0, ch[x].clear();\n\t\ttot = 0;\n\t\tfor (int i = 1, p; i <= M; ++i) {\n\t\t\tp = read<int>();\n\t\t\tif (merge(i, p)) ch[p].push_back(i); else to[i] = p;\n\t\t}\n\t\tfor (int i = 1; i <= M; ++i) if (to[i] > 0) id[i] = i, dfs(i);\n\t\tif (!check(M)) { puts(\"-1\"); continue; }\n\t\tint L = 0, R = M;\n\t\twhile (L < R) {\n\t\t\tint mid = L + R >> 1;\n\t\t\tif (check(mid)) R = mid; else L = mid + 1;\n\t\t}\n\t\tprint<int>(R, '\\n');\n\t}\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "graphs",
      "implementation",
      "shortest paths",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1967",
    "index": "E1",
    "title": "Again Counting Arrays (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The differences between the two versions are the constraints on $n, m, b_0$ and the time limit. You can make hacks only if both versions are solved.}\n\nLittle R has counted many sets before, and now she decides to count arrays.\n\nLittle R thinks an array $b_0, \\ldots, b_n$ consisting of non-negative integers is continuous if and only if, for each $i$ such that $1 \\leq i \\leq n$, $\\lvert b_i - b_{i-1} \\rvert = 1$ is satisfied. She likes continuity, so she only wants to generate continuous arrays.\n\nIf Little R is given $b_0$ and $a_1, \\ldots, a_n$, she will try to generate a non-negative continuous array $b$, which has no similarity with $a$. More formally, for all $1 \\leq i \\leq n$, $a_i \\neq b_i$ holds.\n\nHowever, Little R does not have any array $a$. Instead, she gives you $n$, $m$ and $b_0$. She wants to count the different integer arrays $a_1, \\ldots, a_n$ satisfying:\n\n- $1 \\leq a_i \\leq m$;\n- At least one non-negative continuous array $b_0, \\ldots, b_n$ can be generated.\n\n\\textbf{Note that $b_i \\geq 0$, but the $b_i$ can be arbitrarily large.}\n\nSince the actual answer may be enormous, please just tell her the answer modulo $998\\,244\\,353$.",
    "tutorial": "It can be easily proven that for a given $a$, we can always try to get the largest $b_i$ from $1$ to $n$ one by one. A perceptual understanding is that if not so, we can't escape from some gap in $a$ either. Thus, it's easy to get a $\\mathcal O(nm)$ solution: Let $dp_{i,j}$ be, in the optimal $b$ determination progress, the ways of $b_i = j$. The transition is easy, and it reminds us that $b_{i, m}$s always add to answers with $m^{n-i}$ straightly without continuing to transmit. There is a $\\mathcal O(n\\log^2 n)$ solution that solves the above grid path counting problem with NTT. It can pass this version of the problem, but it is not that useful for the hard version. However, we strongly suggest you read the following part as it reveals the $\\mathcal O(n)$ solution in the hard version. It currently works in $\\mathcal O(n\\sqrt{n})$, but in fact, it runs much faster than the polylog one. Try to modify the solution so that it works in $\\mathcal O(\\frac{n^2}{m})$. Consider the simplified version: You have two lines $y = x + b_1$ and $y = x + b_2$ in a Cartesian coordinate system. You are at $(0, 0)$ and you want to move to $(p, q)$. Each move is $x \\gets x + 1$ or $y \\gets y + 1$. You are not allowed to get onto the points on the two lines. Count the number of ways to get to $(p, q)$. We will introduce a classical $\\mathcal O(\\frac{p+q}{|b_2 - b_1|})$ solution$^\\dagger$. Then, for each invalid path, we enumerate the end position where $b_i = 0, a_{i+1} = 1$, and after that, simply conduct the $\\mathcal O(\\frac nm)$ process (you just need to change some parameters). Now, we get a $\\mathcal O(n\\sqrt{n})$ solution, which should be fast enough to pass. Note $^\\dagger$: If there is only one line $y = x + b$, we can do like what we have done in solving the grid path counting problem, which ultimately yields one of the general term formulas for Catalan numbers. Remind that the key part is to flip $(p, q)$ by the line $y = x + b$ to $(p', q')$. Thus, for each invalid path (It touches at least once $y = x + b$), if we flip all the way from the last time it touches the line to $(p, q)$, then it uniquely corresponds to a path starting from the origin, and finally arriving at $(p', q')$. For the answer to the problem with two lines $y_1 = x + b_1$, $y_2 = x + b_2$, we perform the inclusion-exclusion principle (aka. the reflection method). Let's denote $\\tt A$ as touching $y_1$, $\\tt B$ as touching $y_2$. An invalid path can, for example, be explained as $S = \\tt AAABBABAABBBA$. From the experiment in solving the previous problem, we shrink $S$ into $\\tt ABABABA$ (That is, to replace each $\\tt AA$ with $\\tt A$, and each $\\tt BB$ with $\\tt B$). Then we can calculate the answer as, $f(\\varnothing) - f(\\texttt{A}) - f(\\texttt{B}) + f(\\texttt{AB}) + f(\\texttt{BA}) - f(\\texttt{ABA}) - f(\\texttt{BAB}) + \\ldots$. $f(S)$ refers to flip $(p, q)$ by the characters in $S$ in order. For example, $f(\\texttt{ABA})$ is, flip $(p, q)$ by first $y_1$, then $y_2$, then $y_1$ again, and count the paths from the origin to $(p^\\star, q^\\star)$. And $f(S)$ actually refers to all the invalid schemes containing the pattern $S$ which are the borderlines a path touches in order. There are $\\mathcal O(\\frac{p+q}{\\lvert b_1 - b_2 \\rvert})$ non-zero terms, each term is a combinatorial number. So the overall time complexity is $\\mathcal O(\\frac{p+q}{\\lvert b_1 - b_2 \\rvert})$.",
    "code": "#include <bits/stdc++.h>\n \nnamespace FastIO {\n\ttemplate <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }\n\ttemplate <typename T> inline void write(T x) { if (!x) return; write<T>(x / 10), putchar(x % 10 ^ '0'); }\n\ttemplate <typename T> inline void print(T x) { if (x < 0) putchar('-'), x = -x; else if (x == 0) putchar('0'); write<T>(x); }\n\ttemplate <typename T> inline void print(T x, char en) { if (x < 0) putchar('-'), x = -x; else if (x == 0) putchar('0'); write<T>(x), putchar(en); }\n}; using namespace FastIO;\n \n#define MAXN 2000001\nnamespace Maths {\n\tconstexpr int MOD = 998244353;\n\tlong long qpow(long long a, long long x) { long long ans = 1; while (x) (x & 1) && (ans = ans * a % MOD), a = a * a % MOD, x >>= 1; return ans; }\n\tlong long frac[MAXN << 1 | 1], prac[MAXN << 1 | 1];\n\tinline void inis(int V = MAXN * 2) { frac[0] = prac[0] = 1; for (int i = 1; i <= V; ++i) frac[i] = frac[i - 1] * i % MOD; prac[V] = qpow(frac[V], MOD - 2); for (int i = V - 1; i; --i) prac[i] = prac[i + 1] * (i + 1) % MOD; }\n\tinline long long C(int N, int M) { if (N < 0 || M < 0 || N < M) return 0; return frac[N] * prac[M] % MOD * prac[N - M] % MOD; }\n}; using namespace Maths;\n \nstruct Point {\n\tint x, y;\n\tPoint () {}\n\tPoint (int X, int Y) : x(X), y(Y) {}\n\tinline void flip(int b) { x += b, y -= b, std::swap(x, y); }\n\tinline int calc() { return C(x + y, y); }\n} pA, pB;\n \ninline void add(int& x, int y) { (x += y) >= MOD && (x -= MOD); }\ninline void del(int& x, int y) { (x -= y) < 0 && (x += MOD); }\n \nint calc(int p, int q, int b1, int b2) {\n\tpA = pB = Point(p, q);\n\tint ans = pA.calc();\n\twhile (pA.x >= 0 && pA.y >= 0) \n\t\tpA.flip(b1), del(ans, pA.calc()), pA.flip(b2), add(ans, pA.calc());\n\twhile (pB.x >= 0 && pB.y >= 0) \n\t\tpB.flip(b2), del(ans, pB.calc()), pB.flip(b1), add(ans, pB.calc());\n\treturn ans;\n}\n \nint dp[2][3001], powm[MAXN];\nvoid solve() {\n\tint N = read<int>(), M = read<int>(), b0 = read<int>();\n\tif (b0 >= M) return (void)print<int>(qpow(M, N), '\\n');\n\tpowm[0] = 1; for (int i = 1; i <= N; ++i) powm[i] = 1ll * M * powm[i - 1] % MOD;\n\tif (1ll * M * M <= N) { // dp\n\t\tfor (int k = 0; k < M; ++k) dp[0][k] = (int)(k == b0), dp[1][k] = 0;\n\t\tint ans = 1ll * dp[0][M - 1] * (M - 1) % MOD * powm[N - 1] % MOD;\n\t\tfor (int i = 1; i <= N; ++i) {\n\t\t\tauto now = dp[i & 1], lst = dp[(i & 1) ^ 1];\n\t\t\tnow[0] = 0; for (int k = 0; k + 1 < M; ++k) now[k + 1] = 1ll * lst[k] * (M - 1) % MOD;\n\t\t\tfor (int k = 1; k < M; ++k) add(now[k - 1], lst[k]);\n\t\t\tif (i < N) add(ans, 1ll * now[M - 1] * (M - 1) % MOD * powm[N - i - 1] % MOD);\n\t\t}\n\t\tfor (int k = 0; k < M; ++k) add(ans, dp[N & 1][k]);\n\t\tprint<int>(ans, '\\n');\n\t} else { // reflective inclusion-exclusion\n\t\tconst int B1 = M - b0, B2 = -1 - b0; int ans = qpow(M, N);\n\t\tfor (int x = b0, y = 0, k = 1, p = b0; p < N; p += 2, ++x, ++y, k = 1ll * k * (M - 1) % MOD) \n\t\t\tdel(ans, 1ll * calc(x, y, B1, B2) * k % MOD * powm[N - p - 1] % MOD);\n\t\tprint<int>(ans, '\\n');\n\t}\n}\n \nint main() { int T = read<int>(); inis(); while (T--) solve(); return 0; }",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1967",
    "index": "E2",
    "title": "Again Counting Arrays (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The differences between the two versions are the constraints on $n, m, b_0$ and the time limit. You can make hacks only if both versions are solved.}\n\nLittle R has counted many sets before, and now she decides to count arrays.\n\nLittle R thinks an array $b_0, \\ldots, b_n$ consisting of non-negative integers is continuous if and only if, for each $i$ such that $1 \\leq i \\leq n$, $\\lvert b_i - b_{i-1} \\rvert = 1$ is satisfied. She likes continuity, so she only wants to generate continuous arrays.\n\nIf Little R is given $b_0$ and $a_1, \\ldots, a_n$, she will try to generate a non-negative continuous array $b$, which has no similarity with $a$. More formally, for all $1 \\leq i \\leq n$, $a_i \\neq b_i$ holds.\n\nHowever, Little R does not have any array $a$. Instead, she gives you $n$, $m$ and $b_0$. She wants to count the different integer arrays $a_1, \\ldots, a_n$ satisfying:\n\n- $1 \\leq a_i \\leq m$;\n- At least one non-negative continuous array $b_0, \\ldots, b_n$ can be generated.\n\n\\textbf{Note that $b_i \\geq 0$, but the $b_i$ can be arbitrarily large.}\n\nSince the actual answer may be enormous, please just tell her the answer modulo $998\\,244\\,353$.",
    "tutorial": "The definition of the function $f$ is the same as that in G1 editorial. Please read that first. Consider the process of the reflection method. We don't need to enumerate the place from where the contribution is $0$. We can just consider the contribution of each path. Note that each step is either $x\\gets x+1$ or $y\\gets y\\pm 1$ here, instead of rotating it by $45^\\circ$. Denote $\\tt X$ as touching $y=m$ and $\\tt Y$ as touching $y=-1$. Then we need to calculate the paths that either are empty or begin with $\\tt X$. We can write down the equation of the answer: $f(\\varnothing) - f(\\texttt{Y}) + f(\\texttt{XY}) - f(\\texttt{YXY}) + f(\\texttt{XYXY}) - \\dots$. Let's consider how to calculate $f(\\varnothing)$. We can represent it as: $\\sum_{x=b-n}^{b+n} (m - 1)^{(x - b + n)/2} {n \\choose (x - b + n) / 2}$ A point $(n,k)$ will be flipped at $(n,-2-k)$ after $\\tt Y$, and will be flipped at $(n,2m+2+k)$ after $\\tt XY$. So we only need to calculate: $\\sum_{p \\geq 0} \\sum_{x = b - n}^{b + n} (m - 1)^{(x - b + n)/2} {n \\choose (x - b + n + p(2m + 2))/2}\\\\-\\sum_{p \\geq 0} \\sum_{x =b-n}^{b+n} (m - 1)^{(x - b + n)/2} {n \\choose (-2 - x - b + n + p(2m + 2))/2}$ There are still some small problems. The reflection method points out that, if the targeted point $T$ is between the two lines, then we can keep reflecting $T$ and get $T'$, every path to $T'$ bijects to a path to $T$ which contains reflections. But what if $T$ is not between the two lines? We must solve a problem - the path to $T'$ maybe doesn't touch the two lines at all and there won't be reflections, and these should not be included in the answer. So we should consider $x\\ge 0$ part and $x\\le -1$ part separately. The above equation is for the $x\\ge 0$ part. For the $x\\le -1$ part, we are sure that $\\tt Y$ will occur, so the path should begin with $\\tt X$, then it will be $f(\\texttt{X})-f(\\texttt{YX})+f(\\texttt{XYX})-\\dots$ and can be calculated in the same way. The combinatorial number is hard to deal with, so let's maintain a coefficient sequence $c_0\\cdots c_n$, that the answer is $\\sum_i c_i\\binom{n}{i}$. The sequence $c_i$ can be calculated using differentiation. Time Complexity: $\\mathcal O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int MOD = 998244353;\nconst int N = 2e6+5;\nint inv[N];\n \nint inversemod(int p, int q) {\n  // assumes p > 0\n  // https://codeforces.com/blog/entry/23365\n  return (p > 1 ? q-1LL*inversemod(q%p, p)*q/p : 1);\n}\n \nvoid add(int& x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n}\n \nvoid sub(int& x, int y) {\n  x -= y;\n  if (x < 0) x += MOD;\n}\n \nint solve(int n, int m, int b0) {\n  // let X = hit -1, Y = hit m\n  // f(S) = count of sequences that end up in [0, infty] while containing the pattern S\n  // g(S) = count of sequences that end up in [-infty, -1] while containing the pattern S\n  // we want f() - f(X) + f(YX) - f(XYX) + f(YXYX) - f(XYXYX) + ...\n  //             + g(Y) - g(XY) + g(YXY) - g(XYXY) + g(YXYXY) - ...\n  vector<int> pw(n+1);\n  pw[0] = 1;\n  for (int i = 1; i <= n; i++) pw[i] = 1LL*pw[i-1]*(m-1) % MOD;\n \n  // final ans will be sum from i = 0 to n of (n choose i) a_i\n  vector<int> a(n+2);\n  auto work = [&] (int c, int pw_coeff, int sgn_x) -> bool {\n    // let RANGE = [-infty, -1] if sgn_x == -1 and [0, infty] if sgn_x == 1\n    // for all x in RANGE such that (n+x+c)/2 is between 0 and n inclusive,\n    // add pw_coeff*pw[(n+x-b0)/2] to a[(n+x+c)/2]\n \n    // return 0 to signal that we are out of bounds and should exit, otherwise 1\n    int l = 0;\n    if (sgn_x == 1) l = max(l, (n+c+1)>>1);\n    int r = n;\n    if (sgn_x == -1) r = min(r, (n+c-1)>>1);\n    if (l > r) return 0;\n    add(a[l], 1LL*pw_coeff*pw[l-(b0+c)/2] % MOD);\n    sub(a[r+1], 1LL*pw_coeff*pw[r+1-(b0+c)/2] % MOD);\n    return 1;\n  };\n \n  int ans = 0;\n  // f(k*YX)\n  // after reflection trick, end up in x + 2*(m+1)*k\n  for (int k = 0; work(2*(m+1)*k - b0, 1, 1); k++);\n \n  // f(X + k*YX)\n  // after reflection trick, end up in -2-x - 2*(m+1)*k\n  for (int k = 0; work(2*(m+1)*k+2+b0, MOD-1, 1); k++);\n \n  // g(Y + k*XY)\n  // after reflection trick, end up in 2*m-x + 2*(m+1)*k\n  for (int k = 0; work(-2*m -2*(m+1)*k + b0, 1, -1); k++);\n \n  // g(k*XY)\n  // after reflection trick, end up in x - 2*(m+1)*k\n  for (int k = 1; work(-2*(m+1)*k - b0, MOD-1, -1); k++);\n \n  for (int i = 1; i <= n; i++) {\n    add(a[i], 1LL*a[i-1]*(m-1) % MOD);\n  }\n \n  // do the binomial stuff without precalculated factorials because why not\n  int coeff = 1;\n  for (int i = 0; i <= n; i++) {\n    add(ans, 1LL * coeff * a[i] % MOD);\n    coeff = 1LL * coeff * (n-i) % MOD * inv[i+1] % MOD;\n  }\n \n  return ans;\n}\n \nint main () {\n  ios_base::sync_with_stdio(0); cin.tie(0);\n  inv[1] = 1;\n  for (int i = 2; i < N; i++) inv[i] = 1LL*(MOD-MOD/i)*inv[MOD % i] % MOD;\n \n  int T;\n  cin >> T;\n  while (T--) {\n    int n, m, b0;\n    cin >> n >> m >> b0;\n    if (b0 >= m) {\n      int ans = 1;\n      for (int i = 0; i < n; i++) ans = 1LL*ans*m % MOD;\n      cout << ans << '\\n';\n      continue;\n    }\n    cout << solve(n, m, b0) << '\\n';\n  }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1967",
    "index": "F",
    "title": "Next and Prev",
    "statement": "Let $p_1, \\ldots, p_n$ be a permutation of $[1, \\ldots, n]$.\n\nLet the $q$-subsequence of $p$ be a permutation of $[1, q]$, whose elements are in the same relative order as in $p_1, \\ldots, p_n$. That is, we extract all elements not exceeding $q$ together from $p$ in the original order, and they make the $q$-subsequence of $p$.\n\nFor a given array $a$, let $pre(i)$ be the largest value satisfying $pre(i) < i$ and $a_{pre(i)} > a_i$. If it does not exist, let $pre(i) = -10^{100}$. Let $nxt(i)$ be the smallest value satisfying $nxt(i) > i$ and $a_{nxt(i)} > a_i$. If it does not exist, let $nxt(i) = 10^{100}$.\n\nFor each $q$ such that $1 \\leq q \\leq n$, let $a_1, \\ldots, a_q$ be the $q$-subsequence of $p$. For each $i$ such that $1 \\leq i \\leq q$, $pre(i)$ and $nxt(i)$ will be calculated as defined. Then, you will be given some integer values of $x$, and for each of them you have to calculate $\\sum\\limits_{i=1}^q \\min(nxt(i) - pre(i), x)$.",
    "tutorial": "Consider an array with length $n+x-1$. For each integer $k$ from $n$ to $1$, consider $i$ s.t. $p_i = k$, we tag the untagged (that is, a position will not be tagged for a second time) positions in the range $[i, i + x)\\cap \\mathbb{Z}$. By examining the total number of positions tagged, we have $\\begin{aligned} n + x - 1 &= \\sum_{i=1}^n \\max(\\min(i + x, nxt_i) - \\max(pre_i + x, i), 0) \\\\ &= \\sum_{i=1}^n \\max(\\min(x, nxt_i - i) + \\min(i - pre_i, x) - x, 0) \\\\ &= \\sum_{i=1}^n \\min(x, nxt_i - i) + \\min(i - pre_i, x) -\\min(x, \\min(x, nxt_i - i) + \\min(i - pre_i, x)) \\\\ &= \\sum_{i=1}^n \\min(x, nxt_i - i) + \\min(i - pre_i, x) - \\min(x, nxt_i - pre_i) \\\\ \\end{aligned}$ Symmetrically on the other side, we only have to compute $\\displaystyle \\sum_{i=1}^n \\min(x, nxt_i - i)$. We want to maintain all $nxt_i - i$ in a sorted order, so that queries can be done using binary search. This can be done with the help of chunking. Let the length of each block be $B$. In each block, we divide the positions into two categories: Positions with the maximum $nxt_i$ (hereinafter referred to as $\\tt A$) and positions without the maximum $nxt_i$ (hereinafter referred to as $\\tt B$). We sort the positions by $nxt_i - i$ for A and for B respectively. How does an update affect the $nxt_i - i$ values? For the block that the new number is inserted, we brutely reconstruct it. For an affected complete block, the update is $+1(nxt_i\\gets nxt_i+1)$ or $\\operatorname{chkmin}(nxt_i \\gets \\min(nxt_i, pos))$. A $+1$ operation can just be handled with a lazy tag. For a $\\operatorname{chkmin}$ operation, if it only affects the elements with maximum $nxt_i$, it can be done lazily, otherwise you can reconstruct the whole block. Let the potential of a block $\\Phi:= \\text{Numbers of different } nxt_i \\text{ values in the block}$. Similar to the segment tree beats, each insertion increases $\\sum \\Phi$ by at most $1$, and each brute reconstruction takes $\\mathcal O(B)$ time and decreases $\\sum \\Phi$ by at least $1$. Therefore the overall time complexity for the insertion part would be $\\mathcal O(nB + \\frac{n^2}{B})$. To answer a query, we iterate over all the different blocks. If we precalculate the prefix sums of $nxt_i - i$ in the sorted order, with a simple binary search, this part can be done easily in $\\mathcal O(\\frac{nk\\log B}{B})$. Let $B = \\mathcal O(\\sqrt{n})$. The time complexity would be $\\mathcal O(n\\sqrt{n} + k\\sqrt{n}\\log n)$, while the space complexity is $\\mathcal O(n)$. Merge sorting or fractional cascading will make the time complexity $\\mathcal O((n + k)\\sqrt{n})$, but it runs slower than the previously mentioned solution.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconstexpr int maxn=300010,maxq=100010,B=400;\n \nint n,bn,a[maxn],b[maxn],idx[maxn],nxt[maxn],add[maxn/B+5],mxadd[maxn/B+5],mx[maxn/B+5],se[maxn/B+5],t[maxn];\nlong long ans[maxq];\nvector<int>val[maxn/B+5],mxval[maxn/B+5],pre[maxn/B+5],mxpre[maxn/B+5],pos[maxn/B+5],ks[maxn];\n \nvoid vAdd(int i)\n{\n\tfor(;i<=n;i+=(i&-i)) t[i]++;\n}\n \nint nQuery(int i)\n{\n\tint s=0;\n\tfor(;i;i-=(i&-i)) s+=t[i];\n\treturn s;\n}\n \nvoid vWork()\n{\n\tint i,j,tot=0;\n\tfor(i=1;i<=n;i++) b[a[i]]=i;\n\tfor(i=1;i<=n;i++)\n\t{\n\t\tint p=b[i],bp=(p-1)/B+1;\n\t\tval[bp].clear();\n\t\tmxval[bp].clear();\n\t\tauto radixsort=[](vector<int>&v)\n\t\t{\n\t\t\tif(v.empty()) return;\n\t\t\tstatic int buc[1024],res[B+5];\n\t\t\tauto tmp=minmax_element(v.begin(),v.end());\n\t\t\tint mn=*tmp.first,rg=*tmp.second-mn;\n\t\t\tif(!rg) return;\n\t\t\tint lv=__lg(rg)/2+1,len=1<<lv,i;\n\t\t\tmemset(buc,0,len*4);\n\t\t\tfor(int &it:v) it-=mn,buc[it&(len-1)]++;\n\t\t\tfor(i=1;i<len;i++) buc[i]+=buc[i-1];\n\t\t\tfor(int it:v) res[--buc[it&(len-1)]]=it;\n\t\t\tmemset(buc,0,len*4);\n\t\t\tfor(int it:v) buc[it>>lv]++;\n\t\t\tfor(i=1;i<len;i++) buc[i]+=buc[i-1];\n\t\t\tfor(i=v.size()-1;i>=0;i--) v[--buc[res[i]>>lv]]=res[i]+mn;\n\t\t};\n\t\tauto getpre=[&](vector<int>&pre,const vector<int>&ori)\n\t\t{\n\t\t\tpre.resize(ori.size());\n\t\t\tif(ori.empty()) return;\n\t\t\tpre[0]=ori[0];\n\t\t\tfor(int i=1;i<(int)ori.size();i++) pre[i]=pre[i-1]+ori[i];\n\t\t};\n\t\tint lstmx=mx[bp];\n\t\tvAdd(p);\n\t\tidx[p]=nQuery(p);\n\t\tmx[bp]=nxt[p]=n*2;\n\t\tse[bp]=0;\n\t\tauto it=pos[bp].begin();\n\t\tfor(;it<pos[bp].end();it++)\n\t\t{\n\t\t\tj=*it;\n\t\t\tif(j>p) break;\n\t\t\tnxt[j]+=add[bp];\n\t\t\tif(nxt[j]>lstmx) nxt[j]+=mxadd[bp];\n\t\t\tnxt[j]=min(nxt[j],idx[p]);\n\t\t\tidx[j]+=add[bp];\n\t\t\tif(nxt[j]>mx[bp]) se[bp]=mx[bp],mx[bp]=nxt[j];\n\t\t\telse if(nxt[j]>se[bp]) se[bp]=nxt[j];\n\t\t}\n\t\tit=pos[bp].insert(it,p);\n\t\tfor(it++;it!=pos[bp].end();it++)\n\t\t{\n\t\t\tj=*it;\n\t\t\tnxt[j]+=add[bp];\n\t\t\tif(nxt[j]>lstmx) nxt[j]+=mxadd[bp];\n\t\t\tnxt[j]++;\n\t\t\tidx[j]+=add[bp]+1;\n\t\t\tif(nxt[j]>mx[bp]) se[bp]=mx[bp],mx[bp]=nxt[j];\n\t\t\telse if(nxt[j]>se[bp]) se[bp]=nxt[j];\n\t\t}\n\t\tfor(int j:pos[bp])\n\t\t{\n\t\t\tif(nxt[j]==mx[bp]) mxval[bp].push_back(nxt[j]-idx[j]);\n\t\t\telse val[bp].push_back(nxt[j]-idx[j]);\n\t\t}\n\t\tadd[bp]=mxadd[bp]=0;\n\t\tradixsort(val[bp]);\n\t\tgetpre(pre[bp],val[bp]);\n\t\tradixsort(mxval[bp]);\n\t\tgetpre(mxpre[bp],mxval[bp]);\n\t\tfor(j=bp+1;j<=bn;j++) add[j]++,mx[j]++,se[j]++;\n\t\tfor(j=1;j<bp;j++)\n\t\t{\n\t\t\tif(mx[j]<=idx[p]) continue;\n\t\t\tif(se[j]<idx[p])\n\t\t\t{\n\t\t\t\tmxadd[j]+=idx[p]-mx[j],mx[j]=idx[p];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tval[j].clear();\n\t\t\tmxval[j].clear();\n\t\t\tlstmx=mx[j];\n\t\t\tmx[j]=idx[p],se[j]=0;\n\t\t\tfor(int x:pos[j])\n\t\t\t{\n\t\t\t\tnxt[x]+=add[j];\n\t\t\t\tidx[x]+=add[j];\n\t\t\t\tif(nxt[x]>lstmx) nxt[x]+=mxadd[j];\n\t\t\t\tif(nxt[x]>=idx[p])\n\t\t\t\t{\n\t\t\t\t\tnxt[x]=idx[p];\n\t\t\t\t\tmxval[j].push_back(nxt[x]-idx[x]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(nxt[x]>se[j]) se[j]=nxt[x];\n\t\t\t\t\tval[j].push_back(nxt[x]-idx[x]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tadd[j]=mxadd[j]=0;\n\t\t\tradixsort(val[j]);\n\t\t\tgetpre(pre[j],val[j]);\n\t\t\tradixsort(mxval[j]);\n\t\t\tgetpre(mxpre[j],mxval[j]);\n\t\t}\n\t\tfor(int ki:ks[i])\n\t\t{\n\t\t\ttot++;\n\t\t\tfor(j=1;j<=bn;j++)\n\t\t\t{\n\t\t\t\tauto it=lower_bound(val[j].begin(),val[j].end(),ki);\n\t\t\t\tans[tot]+=(val[j].end()-it)*ki;\n\t\t\t\tif(it!=val[j].begin()) ans[tot]+=pre[j][it-val[j].begin()-1];\n\t\t\t\tit=lower_bound(mxval[j].begin(),mxval[j].end(),ki-mxadd[j]);\n\t\t\t\tans[tot]+=(mxval[j].end()-it)*ki;\n\t\t\t\tif(it!=mxval[j].begin()) ans[tot]+=(it-mxval[j].begin())*mxadd[j]+mxpre[j][it-mxval[j].begin()-1];\n\t\t\t}\n\t\t}\n\t}\n}\n \nint main()\n{\n\tios::sync_with_stdio(false),cin.tie(0);\n\tint T;\n\tcin>>T;\n\twhile(T--)\n\t{\n    \tint i,ki,tot=0;\n    \tcin>>n;\n    \tbn=(n-1)/B+1;\n    \tfor(i=1;i<=n;i++) cin>>a[i];\n    \tfor(i=1;i<=n;i++)\n    \t{\n    \t\tcin>>ki;\n    \t\tks[i].resize(ki);\n    \t\tfor(int &it:ks[i])\n    \t\t{\n    \t\t\tcin>>it;\n    \t\t\tans[++tot]=-(i+it-1);\n    \t\t}\n    \t}\n    \tvWork();\n    \treverse(a+1,a+n+1);\n    \tfor(int x=1;x<=n;x++)\n    \tt[x]=0;\n    \tfor(i=1;i<=bn;i++) mx[i]=0,se[i]=0,val[i].clear(),mxval[i].clear(),pos[i].clear();\n    \tvWork();\n    \tfor(int x=1;x<=n;x++)\n    \tt[x]=0;\n    \tfor(i=1;i<=bn;i++) mx[i]=0,se[i]=0,val[i].clear(),mxval[i].clear(),pos[i].clear();\n    \tfor(i=1;i<=tot;i++) cout<<ans[i]<<'\\n';\n    \ttot=0;\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1968",
    "index": "A",
    "title": "Maximize?",
    "statement": "You are given an integer $x$. Your task is to find any integer $y$ $(1\\le y<x)$ such that $\\gcd(x,y)+y$ is maximum possible.\n\n\\textbf{Note that if there is more than one $y$ which satisfies the statement, you are allowed to find any.}\n\n$\\gcd(a,b)$ is the Greatest Common Divisor of $a$ and $b$. For example, $\\gcd(6,4)=2$.",
    "tutorial": "The core idea is to find the upper bound of $\\gcd(x,y)+y$. Let us look closer at the formula $\\gcd(x,y)+y$. It is a well-known fact that $\\gcd(a,b)=\\gcd(a-b,b)$ for $a\\geq b$. Applying it to our formula, we get $\\gcd(x-y,y)+y$. Using the fact that $\\gcd(x-y,y)\\le x-y$, we get $\\gcd(x-y,y)+y\\le x-y+y=x$. Hence, $\\gcd(x,y)+y\\le x$ for $1\\le y<x$. For $y=x-1$, we have $\\gcd(x,x-1)+x-1=1+x-1=x$, which is the maximal possible value. Note that the constraints allow finding the optimal $y$ in $O(x)$, while the above solution works in $O(1)$.",
    "code": "#include<iostream>\nusing namespace std;\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint x;\n\t\tcin>>x;\n\t\tcout<<x-1<<\"\\n\";\n\t}\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1968",
    "index": "B",
    "title": "Prefiquence",
    "statement": "You are given two binary strings $a$ and $b$. A binary string is a string consisting of the characters '0' and '1'.\n\nYour task is to determine the maximum possible number $k$ such that a prefix of string $a$ of length $k$ is a subsequence of string $b$.\n\nA sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements.",
    "tutorial": "We will be solving this task using dynamic programming. Let us define $dp_i$ as the maximal prefix of $a$ that is contained in $b_1,\\dots,b_i$ as a subsequence. Then the transitions are as follows: if $b_i$ is equal to $a_{dp_{i-1}+1}$ then $dp_i = dp_{i-1} + 1$. otherwise $dp_i=dp_{i-1}$. The answer is $dp_{m}$.",
    "code": "#include<iostream>\n#include<vector>\nusing namespace std;\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n,m;\n\t\tcin>>n>>m;\n\t\tvector<char>a(n+1),b(m+1);\n\t\tfor(int i=1;i<=n;i++){\n\t\t\tcin>>a[i];\n\t\t}\n\t\tfor(int i=1;i<=m;i++){\n\t\t\tcin>>b[i];\n\t\t}\n\t\tvector<int>dp(m+1);\n\t\tdp[1]=(a[1]==b[1]?1:0);\n\t\tfor(int i=2;i<=m;i++){\n\t\t\tif(dp[i-1]!=n && b[i]==a[dp[i-1]+1]){\n\t\t\t\tdp[i]=dp[i-1]+1;\n\t\t\t}else{\n\t\t\t\tdp[i]=dp[i-1];\n\t\t\t}\n\t\t}\n\t\tcout<<dp[m]<<\"\\n\";\n\t}\n}",
    "tags": [
      "greedy",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1968",
    "index": "C",
    "title": "Assembly via Remainders",
    "statement": "You are given an array $x_2,x_3,\\dots,x_n$. Your task is to find \\textbf{any} array $a_1,\\dots,a_n$, where:\n\n- $1\\le a_i\\le 10^9$ for all $1\\le i\\le n$.\n- $x_i=a_i \\bmod a_{i-1}$ for all $2\\le i\\le n$.\n\nHere $c\\bmod d$ denotes the remainder of the division of the integer $c$ by the integer $d$. For example $5 \\bmod 2 = 1$, $72 \\bmod 3 = 0$, $143 \\bmod 14 = 3$.\n\n\\textbf{Note that if there is more than one $a$ which satisfies the statement, you are allowed to find any.}",
    "tutorial": "Notice that $((a+b) \\bmod a)=b$ for $0\\le b< a$. So we may try to generate a sequence with $b=x_i$. Let us take $a_1=1000$, because $1000$ is larger than any of $x_i$. Then, we can take $a_i$ as $a_{i-1}+x_i$, since $((a_{i-1}+x_i)\\bmod a_{i-1})=x_i$ will be hold. The maximal value of $a$ will be at most $1000+500n$ what is smaller than $10^9$.",
    "code": "#include<iostream>\nusing namespace std;\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n;\n\t\tcin>>n;\n\t\tint S=1000;\n\t\tcout<<S<<\" \";\n\t\tfor(int i=2;i<=n;i++){\n\t\t\tint x;\n\t\t\tcin>>x;\n\t\t\tS+=x;\n\t\t\tcout<<S<<\" \";\n\t\t}\n\t\tcout<<\"\\n\";\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1968",
    "index": "D",
    "title": "Permutation Game",
    "statement": "Bodya and Sasha found a permutation $p_1,\\dots,p_n$ and an array $a_1,\\dots,a_n$. They decided to play a well-known \"Permutation game\".\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\nBoth of them chose a starting position in the permutation.\n\nThe game lasts $k$ turns. The players make moves simultaneously. On each turn, two things happen to each player:\n\n- If the current position of the player is $x$, his score increases by $a_x$.\n- Then the player either \\textbf{stays} at his current position $x$ or \\textbf{moves} from $x$ to $p_x$.\n\nThe winner of the game is the player with the higher score after exactly $k$ turns.Knowing Bodya's starting position $P_B$ and Sasha's starting position $P_S$, determine who wins the game if both players are trying to win.",
    "tutorial": "Because $p$ is a permutation, it will be divided into cycles. For every player it is optimal to move during the first $min(n,k)$ turns. We will answer the question by calculating maximal possible score for both players. Let us define $sum_i$ and $pos_i$: sum of values in the positions that occur during the first $i$ turns. position in which player will stop if he decides to move $i$ times. $sum_i = sum_{i-1} + a_{pos_{i}}$ $pos_i$=$p_{pos_{i-1}}$. Now the maximal possible answer for one player is equal to: $ans=\\max\\limits_{0\\le i\\le \\min(n,k)}(sum_i+(k-i)a_{pos_i})$ Now we will compare maximal possible answers for every player.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nlong long score(vector<int>&p,vector<int>&a,int s,int k){\n\tint n=p.size();\n\tlong long mx=0,cur=0;\n\tvector<bool>vis(n);\n\twhile(!vis[s]&&k>0){\n\t\tvis[s]=1;\n\t\tmx=max(mx,cur+1ll*k*a[s]);\n\t\tcur+=a[s];\n\t\tk--;\n\t\ts=p[s];\n\t}\n\treturn mx;\n}\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n,k,s1,s2;\n\t\tcin>>n>>k>>s1>>s2;\n\t\tvector<int>p(n),a(n);\n\t\tfor(auto&e:p){\n\t\t\tcin>>e;\n\t\t\te--;\n\t\t}\n\t\tfor(auto&e:a){\n\t\t\tcin>>e;\n\t\t}\n\t\tlong long A=score(p,a,s1-1,k),B=score(p,a,s2-1,k);\n\t\tcout<<(A>B?\"Bodya\\n\":A<B?\"Sasha\\n\":\"Draw\\n\");\n\t}\n}\n",
    "tags": [
      "brute force",
      "dfs and similar",
      "games",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1968",
    "index": "E",
    "title": "Cells Arrangement",
    "statement": "You are given an integer $n$. You choose $n$ cells $(x_1,y_1), (x_2,y_2),\\dots,(x_n,y_n)$ in the grid $n\\times n$ where $1\\le x_i\\le n$ and $1\\le y_i\\le n$.\n\nLet $\\mathcal{H}$ be the set of \\textbf{distinct} Manhattan distances between any pair of cells. Your task is to maximize the size of $\\mathcal{H}$. Examples of sets and their construction are given in the notes.\n\n\\textbf{If there exists more than one solution, you are allowed to output any.}\n\nManhattan distance between cells $(x_1,y_1)$ and $(x_2,y_2)$ equals $|x_1-x_2|+|y_1-y_2|$.",
    "tutorial": "Author: JuicyGrape What is the maximal possible size of $\\mathcal{H}$? Can you always get that size for $n\\geq 4$? Consider odd and even distances independently. Let us find an interesting pattern for $n\\geq 4$. Can you generalize the pattern? We put $n-2$ cells on the main diagonal. Then put two cells at $(n-1,n)$ and $(n,n)$. But why does it work? Interesting fact, that in such way we generate all possible Manhattan distances. Odd distances are generated between cells from the main diagonal and $(n-1,n)$. Even distances are generated between cells from the main diagonal and $(n,n)$.",
    "code": "#include<iostream>\nusing namespace std;\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n;\n\t\tcin>>n;\n\t\tfor(int i=1;i<=n-2;i++){\n\t\t\tcout<<i<<' '<<i<<\"\\n\";\n\t\t}\n\t\tcout<<n-1<<' '<<n<<\"\\n\"<<n<<' '<<n<<\"\\n\";\n\t}\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1968",
    "index": "F",
    "title": "Equal XOR Segments",
    "statement": "Let us call an array $x_1,\\dots,x_m$ interesting if it is possible to divide the array into $k>1$ parts so that bitwise XOR of values from each part are equal.\n\nMore formally, you must split array $x$ into $k$ consecutive segments, each element of $x$ must belong to \\textbf{exactly} $1$ segment. Let $y_1,\\dots,y_k$ be the XOR of elements from each part respectively. Then $y_1=y_2=\\dots=y_k$ must be fulfilled.\n\nFor example, if $x = [1, 1, 2, 3, 0]$, you can split it as follows: $[\\color{blue}1], [\\color{green}1], [\\color{red}2, \\color{red}3, \\color{red}0]$. Indeed $\\color{blue}1=\\color{green}1=\\color{red}2 \\oplus \\color{red}3\\oplus \\color{red}0$.\n\nYou are given an array $a_1,\\dots,a_n$. Your task is to answer $q$ queries:\n\n- For fixed $l$, $r$, determine whether the subarray $a_l,a_{l+1},\\dots,a_r$ is interesting.",
    "tutorial": "Observation: any division on more than $k>3$ segments can be reduced to at most $3$ segments. Proof: suppose the XORs of elements from the segments are $x_1,\\dots,x_k$. The condition $x_1=x_2=\\dots=x_k$ must be fulfilled. If $k>3$ we may take any three consecutive segments and merge them into one, because $x\\oplus x\\oplus x=x$. In such way, we reduce $k$ by two. We may repeat this process while $k>3$. Let us construct an array $b_1=a_1$ and $b_i=b_{i-1}\\oplus a_i$ for $i\\geq 2$. Now, $a_l\\oplus a_{l+1}\\oplus \\dots \\oplus a_r=b_r\\oplus b_{l-1}$. There are two cases: $k=2$, meaning that we divide the segment $[l,r]$ into two segments. Suppose the segments are $[l,m]$ and $[m+1,r]$. In such case we must check if $b_m\\oplus b_{l-1}=b_{r}\\oplus b_m$. This equality reduces to $b_{l-1}=b_r$. $k=3$, meaning that we divide segment $[l,r]$ into $[l,s]$, $[s+1,t]$ and $[t+1,r]$. We must check if $b_s\\oplus b_{l-1}=b_{t}\\oplus b_s$ and $b_s \\oplus b_{t}=b_r \\oplus b_{t}$. It is equivalent to check if $b_{l-1}=b_t$ and $b_s=b_r$. Also, $s<t$ must be fulfilled. Hence, we may find the largest $t < r$ that $b_t=b_{l-1}$ and the minimal $s\\geq l$ that $b_s=b_r$. It can be done using binary search on the positions of a certain value.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N=200005;\nint a[N];\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n,q;\n\t\tcin>>n>>q;\n\t\tmap<int,vector<int>>id;\n\t\tid[0].push_back(0);\n\t\tfor(int i=1;i<=n;i++){\n\t\t\tcin>>a[i];\n\t\t\ta[i]^=a[i-1];\n\t\t\tid[a[i]].push_back(i);\n\t\t}\n\t\twhile(q--){\n\t\t\tint l,r;\n\t\t\tcin>>l>>r;\n\t\t\tif(a[r]==a[l-1]){\n\t\t\t\tcout<<\"YES\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tint pL=*--lower_bound(id[a[l-1]].begin(),id[a[l-1]].end(),r);\n\t\t\tint pR=*lower_bound(id[a[r]].begin(),id[a[r]].end(),l);\n\t\t\tcout<<(pL>pR?\"YES\\n\":\"NO\\n\");\n\t\t}\n\t\tif(t)cout << \"\\n\";\n\t}\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1968",
    "index": "G1",
    "title": "Division + LCP (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. In this version $l=r$.}\n\nYou are given a string $s$. For a fixed $k$, consider a division of $s$ into exactly $k$ continuous substrings $w_1,\\dots,w_k$. Let $f_k$ be the maximal possible $LCP(w_1,\\dots,w_k)$ among all divisions.\n\n$LCP(w_1,\\dots,w_m)$ is the length of the Longest Common Prefix of the strings $w_1,\\dots,w_m$.\n\nFor example, if $s=abababcab$ and $k=4$, a possible division is $\\textcolor{red}{ab}\\textcolor{blue}{ab}\\textcolor{orange}{abc}\\textcolor{green}{ab}$. The $LCP(\\textcolor{red}{ab},\\textcolor{blue}{ab},\\textcolor{orange}{abc},\\textcolor{green}{ab})$ is $2$, since $ab$ is the Longest Common Prefix of those four strings. Note that each substring consists of a continuous segment of characters and each character belongs to \\textbf{exactly} one substring.\n\nYour task is to find $f_l,f_{l+1},\\dots,f_r$. \\textbf{In this version $l=r$}.",
    "tutorial": "Consider $F_{\\ell}$ is a function which returns true iff it is possible to divide the string into at least $k$ segments with their LCP equal to $\\ell$. Notice that $F_{\\ell}$ implies $F_{\\ell - 1}$ for $\\ell > 0$. So we may find the maximal $\\ell$ using binary search, which will be the answer for the problem. How to compute $F_{\\ell}$? Let us find Z-function $z_1,\\dots,z_n$ of the given string. Notice that in the division $w_1,\\dots,w_k$ we have $w_1$ as the prefix of the given string and all the strings have the common prefix with $w_1$ of length $\\ell$. Notice that $z_p$ gives us the longest common prefix with $w_1$ and a segment starting at $p$. So if $z_p\\geq \\ell$ we may take this segment into account. In such greedy approach we count the maximal number of segments we can divide our string into. If this number is at least $k$, then $F_{\\ell}$ is true. The complexity is $O(n\\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvector<int>Zfunc(string& str){\n\tint n=str.size();\n\tvector<int>z(n);\n\tint l=0,r=0;\n\tfor(int i=1;i<n;i++){\n\t\tif(i<=r){\n\t\t\tz[i]=min(r-i+1,z[i-l]);\n\t\t}\n\t\twhile(i+z[i]<n&&str[z[i]]==str[i+z[i]]){\n\t\t\tz[i]++;\n\t\t}\n\t\tif(i+z[i]-1>r){\n\t\t\tl=i;\n\t\t\tr=i+z[i]-1;\n\t\t}\n\t}\n\treturn z;\n}\nint f(vector<int>&z,int len){\n\tint n=z.size();\n\tint cnt=1;\n\tfor(int i=len;i<n;){\n\t\tif(z[i]>=len){\n\t\t\tcnt++;\n\t\t\ti+=len;\n\t\t}else{\n\t\t\ti++;\n\t\t}\n\t}\n\treturn cnt;\n}\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n,k;\n\t\tstring s;\n\t\tcin>>n>>k>>k>>s;\n\t\tvector<int>z=Zfunc(s);\n\t\tint l=0,r=n+1;\n\t\twhile(r-l>1){\n\t\t\tint mid=(l+r)/2;\n\t\t\tif(f(z,mid)>=k){\n\t\t\t\tl=mid;\n\t\t\t}else{\n\t\t\t\tr=mid;\n\t\t\t}\n\t\t}\n\t\tcout<<l<<\"\\n\";\n\t}\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "hashing",
      "string suffix structures",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1968",
    "index": "G2",
    "title": "Division + LCP (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version $l\\le r$.}\n\nYou are given a string $s$. For a fixed $k$, consider a division of $s$ into exactly $k$ continuous substrings $w_1,\\dots,w_k$. Let $f_k$ be the maximal possible $LCP(w_1,\\dots,w_k)$ among all divisions.\n\n$LCP(w_1,\\dots,w_m)$ is the length of the Longest Common Prefix of the strings $w_1,\\dots,w_m$.\n\nFor example, if $s=abababcab$ and $k=4$, a possible division is $\\textcolor{red}{ab}\\textcolor{blue}{ab}\\textcolor{orange}{abc}\\textcolor{green}{ab}$. The $LCP(\\textcolor{red}{ab},\\textcolor{blue}{ab},\\textcolor{orange}{abc},\\textcolor{green}{ab})$ is $2$, since $ab$ is the Longest Common Prefix of those four strings. Note that each substring consists of a continuous segment of characters and each character belongs to \\textbf{exactly} one substring.\n\nYour task is to find $f_l,f_{l+1},\\dots,f_r$.",
    "tutorial": "In general, in this version we must answer for each $k\\in\\{1,2,\\dots,n\\}$. We will use a similar idea as in the easy version considering two cases: $k\\le \\sqrt{n}$. We may calculate these values as in the easy version in $O(n\\sqrt{n}\\log n)$. $k> \\sqrt{n}$. As we divide the string into $k$ segments and the LCP is $\\ell$, then $k\\cdot \\ell\\le n$. We get, that $\\ell\\le \\sqrt{n}$. We may find the maximal possible $k$ for a fixed $\\ell$ as our answer. It works in $O(n\\sqrt{n})$. There are other approaches to solving this problem, but the authors believe this solution is the simplest one.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvector<int>Zfunc(string& str){\n\tint n=str.size();\n\tvector<int>z(n);\n\tint l=0,r=0;\n\tfor(int i=1;i<n;i++){\n\t\tif(i<=r){\n\t\t\tz[i]=min(r-i+1,z[i-l]);\n\t\t}\n\t\twhile(i+z[i]<n&&str[z[i]]==str[i+z[i]]){\n\t\t\tz[i]++;\n\t\t}\n\t\tif(i+z[i]-1>r){\n\t\t\tl=i;\n\t\t\tr=i+z[i]-1;\n\t\t}\n\t}\n\treturn z;\n}\nint f(vector<int>&z,int len){\n\tint n=z.size();\n\tint cnt=1;\n\tfor(int i=len;i<n;){\n\t\tif(z[i]>=len){\n\t\t\tcnt++;\n\t\t\ti+=len;\n\t\t}else{\n\t\t\ti++;\n\t\t}\n\t}\n\treturn cnt;\n}\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n,L,R;\n\t\tstring s;\n\t\tcin>>n>>L>>R>>s;\n\t\tvector<int>z=Zfunc(s);\n\t\tconst int E=ceil(sqrt(n));\n\t\tvector<int>ans(n+1);\n\t\tfor(int k=1;k<=E;k++){\n\t\t\tint l=0,r=n+1;\n\t\t\twhile(r-l>1){\n\t\t\t\tint mid=(l+r)/2;\n\t\t\t\tif(f(z,mid)>=k){\n\t\t\t\t\tl=mid;\n\t\t\t\t}else{\n\t\t\t\t\tr=mid;\n\t\t\t\t}\n\t\t\t}\n\t\t\tans[k]=l;\n\t\t}\n\t\tfor(int len=1;len<=E;len++){\n\t\t\tint k=1;\n\t\t\tfor(int i=len;i<n;){\n\t\t\t\tif(z[i]>=len){\n\t\t\t\t\tk++;\n\t\t\t\t\ti+=len;\n\t\t\t\t}else{\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tans[k]=max(ans[k],len);\n\t\t}\n\t\tfor(int i=n-1;i>=1;i--){\n\t\t\tans[i]=max(ans[i],ans[i+1]);\n\t\t}\n\t\tfor(int i=L;i<=R;i++){\n\t\t\tcout<<ans[i]<<' ';\n\t\t}\n\t\tcout<<\"\\n\";\n\t}\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "hashing",
      "math",
      "string suffix structures",
      "strings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1969",
    "index": "A",
    "title": "Two Friends",
    "statement": "Monocarp wants to throw a party. He has $n$ friends, and he wants to have at least $2$ of them at his party.\n\nThe $i$-th friend's best friend is $p_i$. All $p_i$ are distinct, and for every $i \\in [1, n]$, $p_i \\ne i$.\n\nMonocarp can send invitations to friends. The $i$-th friend comes to the party if \\textbf{both the $i$-th friend and the $p_i$-th friend} receive an invitation (note that the $p_i$-th friend doesn't have to actually come to the party). Each invitation is sent to exactly one of the friends.\n\nFor example, if $p = [3, 1, 2, 5, 4]$, and Monocarp sends invitations to the friends $[1, 2, 4, 5]$, then the friends $[2, 4, 5]$ will come to the party. The friend $1$ won't come since his best friend didn't receive an invitation; the friend $3$ won't come since he didn't receive an invitation.\n\nCalculate the minimum number of invitations Monocarp has to send so that \\textbf{at least $2$} friends come to the party.",
    "tutorial": "Obviously, you can't send fewer than $2$ invitations. Since all $p_i \\neq i$, you need to send at least $2$ invitations ($i$ and $p_i$) in order for at least some friend $i$ to come. On the other hand, you never need to send more than $3$ invitations. You can always send invitations to friends $i, p_i$, and $p_{p_i}$, so that $i$ and $p_i$ come. Now we need to determine the condition for when two invitations are enough. That is, we send invitations to friends $i$ and $j$, and both of them come. This means $p_i = j$ and $p_j = i$. This check is already enough to solve the problem in $O(n^2)$. But you can think further and see that since $j = p_i$, the second check becomes $p_{p_i} = i$. This means it is enough to iterate over friend $i$ and check if $p_{p_i} = i$ for at least one of them. Overall complexity: $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    p = [int(x) - 1 for x in input().split()]\n    ans = 3\n    for i in range(n):\n        if p[p[i]] == i:\n            ans = 2\n    print(ans)",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1969",
    "index": "B",
    "title": "Shifts and Sorting",
    "statement": "Let's define a cyclic shift of some string $s$ as a transformation from $s_1 s_2 \\dots s_{n-1} s_{n}$ into $s_{n} s_1 s_2 \\dots s_{n-1}$. In other words, you take one last character $s_n$ and place it before the first character while moving all other characters to the right.\n\nYou are given a binary string $s$ (a string consisting of only 0-s and/or 1-s).\n\nIn one operation, you can choose any substring $s_l s_{l+1} \\dots s_r$ ($1 \\le l < r \\le |s|$) and cyclically shift it. The cost of such operation is equal to $r - l + 1$ (or the length of the chosen substring).\n\nYou can perform the given operation any number of times. What is the minimum \\textbf{total} cost to make $s$ sorted in non-descending order?",
    "tutorial": "Let's look at the operation as the following: you choose $(l, r)$, erase the element at position $r$ and then insert it before the element at position $l$. We can also interpret the cost of such operation as the following: you pay $1$ for the element at position $r$ you \"teleport\" to the left and $1$ for each element you teleport through (element inside segment $[l, r - 1]$). Now let's look at two indices $x < y$ where $a_x = 1$ and $a_y = 0$. Since at the end, all zeroes should be before ones, you have to move $a_y$ to the left of $a_x$. But the only thing that moves to the left is element $a_r$, so you have to make at least one operation ending at $a_y$. What does it mean? It means: for every 0 that has at least one 1 from the left, you have to pay at least $1$ for teleporting it to the left; for every 1, if there are $c$ 0-s to the right, you have to pay at least $c$, since each zero should be teleported through this 1. The thoughts above gave us the lower bound on the answer, and it's not hard to come up with some constructive algorithms that will give us exactly that cost. To calculate the lower bound, you just need to maintain some info while iterating from left to right: for example, the number of 0-s and 1-s to the left of the current position and the total number of 0-s in $s$. It's enough to check: is there any 1 to the left of the current position, and how many 0-s are to the right. Instead of calculating the lower bound itself, you can also implement one of the algorithms that reach that lower bound, and it may be even a little easier.",
    "code": "fun main() {\n    repeat(readln().toInt()) {\n        val s = readln().map { it.code - '0'.code }\n        val zeroes = s.count { it == 0 }\n        val cnt = intArrayOf(0, 0)\n        var ans = 0L\n        for (c in s) {\n            cnt[c]++\n            if (c == 0)\n                ans += if (cnt[1] > 0) 1 else 0\n            else\n                ans += (zeroes - cnt[0])\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1969",
    "index": "C",
    "title": "Minimizing the Sum",
    "statement": "You are given an integer array $a$ of length $n$.\n\nYou can perform the following operation: choose an element of the array and replace it with any of its neighbor's value.\n\nFor example, if $a=[3, 1, 2]$, you can get one of the arrays $[3, 3, 2]$, $[3, 2, 2]$ and $[1, 1, 2]$ using one operation, but not $[2, 1, 2$] or $[3, 4, 2]$.\n\nYour task is to calculate the minimum possible total sum of the array if you can perform the aforementioned operation at most $k$ times.",
    "tutorial": "The small values of $k$ leads to the idea that expected solution is dynamic programming. In fact, we can actually design a dynamic programming solution. Let $dp_{i, j}$ be the minimum sum, if we considered the first $i$ elements and already done $j$ operations. Note that, we can turn a segment of length $d+1$ into a minimum on it using $d$ operations. So the transitions can be done by iterating over the length of the next segment (denote it as $d$) and we can update $dp_{i + d + 1, j + d}$ with $dp_{i, j} + (d + 1) \\cdot x$, where $x$ is the minimum among $a_i, a_{i + 1}, \\dots, a_{i + d - 1}$ (that can be maintained in a single variable during iteration over $d$). There are $O(nk)$ states in the dynamic programming and $O(k)$ transitions from each of them, so the solution works in $O(nk^2)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nusing li = long long;\nconst li INF = 1e18;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<li> a(n);\n    for (auto& x : a) cin >> x;\n    vector<vector<li>> dp(n + 1, vector<li>(k + 1, INF));\n    dp[0][0] = 0;\n    for (int i = 0; i < n; ++i) {\n      for (int j = 0; j <= k; ++j) {\n        li mn = INF;\n        for (int d = 0; j + d <= k && i + d < n; ++d) {\n          mn = min(mn, a[i + d]);\n          dp[i + d + 1][j + d] = min(dp[i + d + 1][j + d], dp[i][j] + (d + 1) * mn);\n        }\n      }\n    }\n    cout << *min_element(dp[n].begin(), dp[n].end()) << '\\n';\n  }\n}",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1969",
    "index": "D",
    "title": "Shop Game",
    "statement": "Alice and Bob are playing a game in the shop. There are $n$ items in the shop; each item has two parameters: $a_i$ (item price for Alice) and $b_i$ (item price for Bob).\n\nAlice wants to choose a subset (possibly empty) of items and buy them. After that, Bob does the following:\n\n- if Alice bought less than $k$ items, Bob can take all of them for free;\n- otherwise, he will take $k$ items for free that Alice bought (Bob chooses which $k$ items it will be), and for the rest of the chosen items, Bob will buy them from Alice and pay $b_i$ for the $i$-th item.\n\nAlice's profit is equal to $\\sum\\limits_{i \\in S} b_i - \\sum\\limits_{j \\in T} a_j$, where $S$ is the set of items Bob buys from Alice, and $T$ is the set of items Alice buys from the shop. In other words, Alice's profit is the difference between the amount Bob pays her and the amount she spends buying the items.\n\nAlice wants to maximize her profit, Bob wants to minimize Alice's profit. Your task is to calculate Alice's profit if both Alice and Bob act optimally.",
    "tutorial": "Let's sort the array in descending order based on the array $b$. For a fixed set of Alice's items, Bob will take the first $k$ of them for free (because they are the most expensive) and pay for the rest. Now we can iterate over the first item that Bob will pay (denote it as $i$). Alice has to buy the cheapest $k$ items among $1, 2, \\dots, i-1$ (denote the sum of these values as $f$), because Bob can take them for free. Bob has to pay for each of the items among $i, i+1, \\dots, n$ that Alice will buy. So Alice will buy all the items with $b_i - a_i > 0$ (denote the sum of these values as $p$). Then the Alice's profit is $p - f$. Thus, we got a solution that works in $O(n^2)$. In order to speed up this solution, we have to calculate the values $f$ and $p$ faster than $O(n)$. We can do it as follows: while iterating over the value of $i$, let's store \"free\" items in the ordered set, and when the size of this set becomes larger than $k$, remove the most expensive element from it; and the value of $p$ can be calculated using prefix sums (over the values $\\max(0, b_i - a_i)$) or maintaining a variable (and update it when moving to the next value of $i$).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\n#define sz(a) int((a).size())\nusing li = long long;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n), b(n);\n    for (auto& x : a) cin >> x;\n    for (auto& x : b) cin >> x;\n    vector<int> ord(n);\n    iota(ord.begin(), ord.end(), 0);\n    sort(ord.begin(), ord.end(), [&](int i, int j) {\n      return b[i] > b[j];\n    });\n    li f = 0, p = 0;\n    for (int i : ord) p += max(0, b[i] - a[i]);\n    li ans = 0;\n    multiset<int> s;\n    if (sz(s) == k) ans = max(ans, p - f);\n    for (int i : ord) {\n      p -= max(0, b[i] - a[i]);\n      s.insert(a[i]);\n      f += a[i];\n      if (sz(s) > k) {\n        f -= *s.rbegin();\n        s.erase(--s.end());\n      }\n      if (sz(s) == k) ans = max(ans, p - f);\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1969",
    "index": "E",
    "title": "Unique Array",
    "statement": "You are given an integer array $a$ of length $n$. A subarray of $a$ is one of its contiguous subsequences (i. e. an array $[a_l, a_{l+1}, \\dots, a_r]$ for some integers $l$ and $r$ such that $1 \\le l < r \\le n$). Let's call a subarray unique if there is an integer that occurs exactly once in the subarray.\n\nYou can perform the following operation any number of times (possibly zero): choose an element of the array and replace it with any integer.\n\nYour task is to calculate the minimum number of aforementioned operation in order for all the subarrays of the array $a$ to be unique.",
    "tutorial": "When we replace an element, we can always choose an integer that is not present in the array. So, if we replace the $i$-th element, every subarray containing it becomes unique; and the problem can be reformulated as follows: consider all non-unique subarrays of the array, and calculate the minimum number of elements you have to choose so that, for every non-unique subarray, at least one of its elements is chosen. We can use the following greedy strategy to do it: go through the array from left to right, maintaining the index $s$ of the last element we replaced. When we consider the $i$-th element of the array, if there is a non-unique subarray $[l, r]$ with $l > s$, we replace the $i$-th element, otherwise we don't replace anything. Why is it optimal? Essentially, this greedy approach always finds a non-unique subarray $[l, r]$ with the lowest value of $r$, and replaces the $r$-th element. We obviously have to replace at least one element from the subarray $[l, r]$; but replacing the $r$-th element is optimal since we picked the lowest value of $r$, so every non-unique subarray which contains any element from $[l, r]$ also contains the $r$-th element. Okay, but we need to make this greedy solution work fast. When we consider the $i$-th element, how do we check that there's a non-unique subarray starting after the element $s$ and ending at the $i$-th element? Suppose we go from the $i$-th element to the left and maintain a counter; when we meet an element for the first time, we increase this counter; when we meet an element for the second time, we decrease this counter. If this counter is equal to $0$, then the current subarray is non-unique: every element appears at least twice. Otherwise, at least one element has exactly one occurrence. Suppose we maintain an array $t$ where for each integer present in the original array, we put $1$ in the last position we've seen this element, and $-1$ in the second-to-last position we've seen this element (i. e. for every element, we consider its two last occurrences among the first $i$ positions in the array, put $1$ in the last of them, and $-1$ in the second-to-last of them). Then, if we go from $i$ to $l$ and maintain the counter in the same way as we described in the previous paragraph, the value of this counter will be equal to the sum of the corresponding segment in this array $t$. So, we want to check if there's a segment in the array $t$ such that its left border is greater than $s$ (the last position where we made a replacement), the right border is $i$, and the sum is $0$. We can show that the sum on any segment ending in the $i$-th position is currently non-negative; so, we actually want to find the segment with the minimum sum. We can store a segment tree that, for every position $l$ from $s+1$ to $i$, maintains the sum on segment $[l, i]$; then changing an element is just performing the query \"add on segment\", and finding the minimum sum is just performing the query \"minimum on segment\". This allows us to get a solution with complexity of $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\n#define sz(a) int((a).size())\n\nvector<int> t, p;\n\nvoid push(int v) {\n  if (v * 2 + 2 >= sz(t)) return;\n  t[v * 2 + 1] += p[v]; p[v * 2 + 1] += p[v];\n  t[v * 2 + 2] += p[v]; p[v * 2 + 2] += p[v];\n  p[v] = 0;\n}\n\nvoid upd(int v, int l, int r, int L, int R, int x) {\n  if (L >= R) return;\n  if (l == L && r == R) {\n    t[v] += x; p[v] += x;\n    return;\n  }\n  int m = (l + r) / 2;\n  push(v);\n  upd(v * 2 + 1, l, m, l, min(m, R), x);\n  upd(v * 2 + 2, m, r, max(m, L), R, x);\n  t[v] = min(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\nint get(int v, int l, int r, int L, int R) {\n  if (L >= R) return 1e9;\n  if (l == L && r == R) return t[v];\n  int m = (l + r) / 2;\n  push(v);\n  return min(\n    get(v * 2 + 1, l, m, l, min(m, R)),\n    get(v * 2 + 2, m, r, max(m, L), R)\n  );\n}\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  for (auto& x : a) cin >> x, --x;\n  t = p = vector<int>(4 * n);\n  vector<vector<int>> pos(n);\n  int ans = 0, st = 0;\n  for (int i = 0; i < n; ++i) {\n    int x = a[i];\n    pos[x].push_back(i);\n    int k = sz(pos[x]);\n    if (k > 0) upd(0, 0, n, st, pos[x][k - 1] + 1, +1);\n    if (k > 1) upd(0, 0, n, st, pos[x][k - 2] + 1, -2);\n    if (k > 2) upd(0, 0, n, st, pos[x][k - 3] + 1, +1);\n    if (get(0, 0, n, st, i + 1) == 0) {\n      ans += 1;\n      st = i + 1;\n    }\n  }\n  cout << ans << '\\n';\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) solve();\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dp",
      "greedy"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1969",
    "index": "F",
    "title": "Card Pairing",
    "statement": "There is a deck of $n$ cards, each card has one of $k$ types. You are given the sequence $a_1, a_2, \\dots, a_n$ denoting the types of cards in the deck from top to bottom. Both $n$ and $k$ are even numbers.\n\nYou play a game with these cards. First, you draw $k$ topmost cards from the deck. Then, the following happens each turn of the game:\n\n- you choose \\textbf{exactly} two cards from your hand and play them. If these cards have the same type, you earn a coin;\n- then, if the deck is not empty, you draw \\textbf{exactly} two top cards from it;\n- then, if both your hand and your deck are empty, the game ends. Otherwise, the new turn begins.\n\nYou have to calculate the maximum number of coins you can earn during the game.",
    "tutorial": "It's pretty obvious that every time we have a pair of equal cards in hand, we should play one of these pairs. If you're interested in a formal proof, please read the paragraph in italic, otherwise skip it. Formal proof: suppose we have a pair of cards of type $x$, but we play a card of type $y$ and a card of type $z$ in the optimal solution, where $z \\ne x$ and $z \\ne y$. Let's show that playing a pair of cards of type $x$ can also be optimal. If $y = x$, then let's find the next moment when we play a card of type $x$. By swapping that card with a card of type $z$, we \"fix\" the current pair and possibly \"break\" the pair from which we took the card of type $x$, so our number of coins won't go down. If $y \\ne x$, almost the same proof can be used: find the first two cards of type $x$ we play after that moment. Either they are played at the same moment, then we can swap the pairs we used at the current moment and at that moment. Or they are played at different moments $t_1$ and $t_2$; by swapping these two cards with cards of type $y$ and $z$, we \"fix\" the pair we played at the current moment, we might \"break\" the pair played at the moment $t_2$, but we cannot \"break\" the pair played at the moment $t_1$, since the cards played at that moment are different. Whenever we have a pair of equal cards, we will always play it at some moment and earn a coin, and it does not matter in which order we play different pairs. So we have to make a meaningful choice about which cards we play only when all $k$ cards in our hand are different. In the ideal situation, if there are $c_i$ cards of type $i$, we want to earn $\\lfloor\\frac{c_i}{2}\\rfloor$ coins by playing these cards. But whenever we play only one card of type $i$ and there is an odd number of cards of type $i$ left (both in hand and in deck), we \"lose\" a coin, because the number of pairs we can make decreases by $1$. Let's calculate the answer as the maximum possible number of pairs we can form (equal to $\\sum\\limits_{i=1}^{k} \\lfloor\\frac{c_i}{2}\\rfloor$), minus the minimum number of coins we \"lose\" in such a way. Since we play a pair when we have at least one pair, we can \"lose\" coins only when all cards in our hand are different. So, let's try to use a dynamic programming of the form: $dp_i$ is the minimum number of coins we could lose when we have drawn $i$ first cards from the deck, and all cards in our hand are different. Let's analyze the transitions of this dynamic programming. When transitioning out of $dp_i$, we can iterate on the pair of cards we play (since we consider the situation when all cards in our hand are different, we can play any pair of different cards); for each of these two cards, check if we \"lose\" a coin by playing them, and try to find the next moment when all $k$ cards in our hand will be different (or update the answer if there is no such moment). However, when implemented naively, it is too slow (might take up to $O(n^5)$). We can use the following optimizations to improve it: XOR Hashing: this is one of my favorite techniques. Let's assign each card type a random $64$-bit number (let it be $h_i$ for type $i$). Then, let $p_i$ be the XOR of the numbers assigned to the first $i$ cards in the deck. Suppose we are considering transitions from $dp_i$; we try to play cards of type $x$ and $y$; when will be the next moment when we have all $k$ types of cards? If this moment is $j$, then we need to take an odd number of cards of type $x$ and $y$ from moment $i$ to moment $j$, and an even number of cards for all other types. So, we can see that $p_j = p_i \\oplus h_x \\oplus h_y$, and this allows us to locate the next moment when we have $k$ different cards more easily, in $O(n)$ or even $O(\\log n)$. Reducing the number of transitions: we have up to $O(k^2)$ pairs of cards we can play from each state, but only $O(n)$ different states we can go into, and no two transitions lead to the same state. Let's try to make only $O(n)$ transitions from each state. When considering a state, we can split all $k$ cards into two types: the ones that make us lose a coin when we play them (group $1$), and all the others (group $2$). First, let's try to play two cards from the group $2$; if we find a combination of them such that, after playing it, we never have $k$ different cards in our hand - we don't need any other transitions from this state, because this transition updates the answer directly without any increases. Otherwise, perform all transitions with pairs of cards from group $2$, and try to play a pair of cards from different groups. If we find a combination that updates the answer directly, we again can stop considering transitions, the next transitions we use won't be more optimal. And then we do the same with transitions where we use a pair of cards of group $1$. This way, we will consider at most $n+1$ transitions from each state. Combining these two optimizations results in a solution in $O(n^3)$ or $O(n^2 \\log n)$, but there are other optimizations you can try.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nmt19937_64 rnd(12341234);\n\nint n, k;\nvector<int> deck;\nvector<int> dp;\nvector<vector<bool>> odd;\nvector<bool> full_odd;\nvector<long long> val;\nvector<long long> hs;      \n\nbool bad(const vector<bool>& v)\n{\n    for(int i = 0; i < k; i++)\n        if(!v[i])\n            return false;\n    return true;\n}\n\nvector<bool> inv(const vector<bool>& v)\n{\n    vector<bool> res(k);\n    for(int i = 0; i < k; i++)\n        res[i] = !v[i];\n    return res;\n}\n\nvector<bool> get_suffix(int l)\n{\n    vector<bool> v(k);                     \n    for(int i = l; i < n; i++) v[deck[i]] = !v[deck[i]];\n    return v;\n}\n\nint get_next(long long cur, int x)\n{\n    for(int i = x; i <= n; i += 2)\n        if(hs[i] == cur)\n            return i;\n    return -1;\n}                \n\nint main()\n{\n    cin >> n >> k;\n    deck.resize(n);\n    for(int i = 0; i < n; i++) cin >> deck[i];\n    for(int i = 0; i < n; i++) --deck[i];\n    val.resize(k);\n    for(int i = 0; i < k; i++)\n        while(val[i] == 0)\n            val[i] = rnd();\n\n    int max_score = 0;\n    dp.resize(n + 1);\n    full_odd.resize(k);\n    odd.resize(n + 1, vector<bool>(k));\n    hs.resize(n + 1);\n    long long cur_hash = 0;\n    for(int i = 0; i < n; i++)\n    {\n        cur_hash ^= val[deck[i]];\n        if(full_odd[deck[i]]) max_score++;\n        full_odd[deck[i]] = !full_odd[deck[i]];\n        odd[i + 1] = full_odd;\n        hs[i + 1] = cur_hash;\n    }   \n\n    for(int i = k; i <= n; i++)\n        dp[i] = 1e9;                          \n    long long start = 0ll;\n    for(int i = 0; i < k; i++) start ^= val[i];\n    int pos = get_next(start, k);\n    if(pos == -1)\n    {\n        cout << max_score << endl;  \n    }\n    else\n    {\n        dp[pos] = 0;\n        int ans = 1e9;\n        for(int p = k; p <= n; p += 2)\n        {\n            if(dp[p] > 1e8) continue;   \n            vector<bool> suff = get_suffix(p);\n            vector<int> o, e;\n            for(int j = 0; j < k; j++)\n                if(suff[j])\n                    e.push_back(j);\n                else\n                    o.push_back(j);\n            int es = e.size();\n            int os = o.size();\n            bool flag = true;\n            for(int i = 0; i < os && flag; i++)\n                for(int j = 0; j < i && flag; j++)\n                {\n                    int x = o[i];\n                    int y = o[j];\n                    int add = 0;         \n                    long long h = hs[p] ^ val[x] ^ val[y];\n                    int pos = get_next(h, p);\n                    if(pos == -1)                  \n                    {\n                        flag = false;\n                        ans = min(ans, dp[p] + add);\n                    }\n                    else\n                        dp[pos] = min(dp[pos], dp[p] + add);\n                }\n\n            for(int i = 0; i < os && flag; i++)\n                for(int j = 0; j < es && flag; j++)\n                {\n                    int x = o[i];\n                    int y = e[j];\n                    int add = 1;         \n                    long long h = hs[p] ^ val[x] ^ val[y];\n                    int pos = get_next(h, p);    \n                    if(pos == -1)\n                    {\n                        flag = false;\n                        ans = min(ans, dp[p] + add);\n                    }\n                    else\n                        dp[pos] = min(dp[pos], dp[p] + add);\n                }\n\n            for(int i = 0; i < es && flag; i++)\n                for(int j = 0; j < i && flag; j++)\n                {\n                    int x = e[i];\n                    int y = e[j];\n                    int add = 2;                             \n                    long long h = hs[p] ^ val[x] ^ val[y];\n                    int pos = get_next(h, p);\n                    if(pos == -1)\n                    {\n                        flag = false;\n                        ans = min(ans, dp[p] + add);\n                    }\n                    else\n                        dp[pos] = min(dp[pos], dp[p] + add);\n                }\n        }\n        cout << max_score - ans << endl;\n    }       \n}",
    "tags": [
      "dp",
      "greedy",
      "hashing",
      "implementation"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1970",
    "index": "A1",
    "title": "Balanced Shuffle (Easy)",
    "statement": "A parentheses sequence is a string consisting of characters \"(\" and \")\", for example \"(()((\".\n\nA balanced parentheses sequence is a parentheses sequence which can become a valid mathematical expression after inserting numbers and operations into it, for example \"(()(()))\".\n\nThe balance of a parentheses sequence is defined as the number of opening parentheses \"(\" minus the number of closing parentheses \")\". For example, the balance of the sequence \"(()((\" is 3.\n\nA balanced parentheses sequence can also be defined as a parentheses sequence with balance 0 such that each of its prefixes has a non-negative balance.\n\nWe define the balanced shuffle operation that takes a parentheses sequence and returns a parentheses sequence as follows: first, for every character of the input sequence, we compute the balance of the prefix of the sequence before that character and write those down in a table together with the positions of the characters in the input sequence, for example:\n\n\\begin{tabular}{l||c||c||c||c||c||c||c||c}\nPrefix balance & 0 & 1 & 2 & 1 & 2 & 3 & 2 & 1 \\\n\\hline\n\\hline\nPosition & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\\n\\hline\n\\hline\nCharacter & ( & ( & ) & ( & ( & ) & ) & ) \\\n\\end{tabular}\n\nThen, we sort the columns of this table in increasing order of prefix balance, breaking ties in decreasing order of position. In the above example, we get:\n\n\\begin{tabular}{l||c||c||c||c||c||c||c||c}\nPrefix balance & 0 & 1 & 1 & 1 & 2 & 2 & 2 & 3 \\\n\\hline\n\\hline\nPosition & 1 & 8 & 4 & 2 & 7 & 5 & 3 & 6 \\\n\\hline\n\\hline\nCharacter & ( & ) & ( & ( & ) & ( & ) & ) \\\n\\end{tabular}\n\nThe last row of this table forms another parentheses sequence, in this case \"()(()())\". This sequence is called the result of applying the balanced shuffle operation to the input sequence, or in short just the balanced shuffle of the input sequence.\n\nYou are given a balanced parentheses sequence. Print its balanced shuffle.",
    "tutorial": "The problem statement describes exactly what needs to be done, so we just need to implement it carefully, using a $O(n\\log n)$ sorting algorithm from the standard library. If you're using Python for this problem, the time limit can be a bit tight so you might need to optimize a bit. For example, tuples are much faster than custom classes in Python, so the following passes in 0.5s:",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1970",
    "index": "A2",
    "title": "Balanced Unshuffle (Medium)",
    "statement": "\\textbf{The differences with the easy version of this problem are highlighted in bold.}\n\nA parentheses sequence is a string consisting of characters \"(\" and \")\", for example \"(()((\".\n\nA balanced parentheses sequence is a parentheses sequence which can become a valid mathematical expression after inserting numbers and operations into it, for example \"(()(()))\".\n\nThe balance of a parentheses sequence is defined as the number of opening parentheses \"(\" minus the number of closing parentheses \")\". For example, the balance of the sequence \"(()((\" is 3.\n\nA balanced parentheses sequence can also be defined as a parentheses sequence with balance 0 such that each of its prefixes has a non-negative balance.\n\nWe define the balanced shuffle operation that takes a parentheses sequence and returns a parentheses sequence as follows: first, for every character of the input sequence, we compute the balance of the prefix of the sequence before that character and write those down in a table together with the positions of the characters in the input sequence, for example:\n\n\\begin{tabular}{l||c||c||c||c||c||c||c||c}\nPrefix balance & 0 & 1 & 2 & 1 & 2 & 3 & 2 & 1 \\\n\\hline\n\\hline\nPosition & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\\n\\hline\n\\hline\nCharacter & ( & ( & ) & ( & ( & ) & ) & ) \\\n\\end{tabular}\n\nThen, we sort the columns of this table in increasing order of prefix balance, breaking ties in decreasing order of position. In the above example, we get:\n\n\\begin{tabular}{l||c||c||c||c||c||c||c||c}\nPrefix balance & 0 & 1 & 1 & 1 & 2 & 2 & 2 & 3 \\\n\\hline\n\\hline\nPosition & 1 & 8 & 4 & 2 & 7 & 5 & 3 & 6 \\\n\\hline\n\\hline\nCharacter & ( & ) & ( & ( & ) & ( & ) & ) \\\n\\end{tabular}\n\nThe last row of this table forms another parentheses sequence, in this case \"()(()())\". This sequence is called the result of applying the balanced shuffle operation to the input sequence, or in short just the balanced shuffle of the input sequence.\n\n\\textbf{Surprisingly, it turns out that the balanced shuffle of any balanced parentheses sequence is always another balanced parentheses sequence (we will omit the proof for brevity). Even more surprisingly, the balanced shuffles of two different balanced parentheses sequences are always different, therefore the balanced shuffle operation is a bijection on the set of balanced parentheses sequences of any given length (we will omit this proof, too).}\n\n\\textbf{You are given a balanced parentheses sequence. Find its preimage: the balanced parentheses sequence the balanced shuffle of which is equal to the given sequence.}",
    "tutorial": "In a balanced parentheses sequence each opening parenthesis corresponds (would form a pair enclosing a subexpression in a mathematical expression) to exactly one closing parenthesis and vice versa. In such a pair the balance before the opening parenthesis is always 1 less than the balance before the closing parenthesis. After sorting, the parentheses with equal prefix balance go together. Let us consider them in groups of equal prefix balance. The first group, with prefix balance 0, will contain only opening parentheses. The second group, with prefix balance 1, will contain the closing parentheses corresponding to the opening parentheses from the first group, and potentially some more opening parentheses. The third group, with prefix balance 2, will contain the closing parentheses corresponding to the opening parentheses from the second group, and potentially some more opening parentheses, and so on. Moreover, each group except the first one will always start with a closing parenthesis (since we break ties in decreasing order of position). This observation allows to split the input string into the groups of equal prefix balance: the first group is everything before the first closing parenthesis. The second group is everything after that and before the $k+1$-th closing parenthesis, where $k$ is the number of opening parentheses in the first group, and so on. Having done that, we can also construct the original sequence group-by-group. After processing a certain number of groups we will have a string that is a parentheses sequence but not a balanced parentheses sequence yet: some opening parentheses in it will be marked as unmatched (for example, we can use opening square brackets instead of parentheses to denote those). When processing the next group, we put each closing parenthesis and all opening parentheses that follow it after the corresponding unmatched opening parenthesis. Here is how this process works on the sample testcase: After the first group, our string is [. After the second group, our string is ([[). After the third group, our string is (()([)). After the fourth group, our string is (()(())) and we have correctly recovered the original sequence. The straightforward implementation of this algorithm runs in $O(n^2)$, fast enough for the constraints of this subtask. The transformation described in this problem is called a sweep map in the literature, and searching the Internet using that term will lead to a much deeper dive on the subject if desired.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1970",
    "index": "A3",
    "title": "Balanced Unshuffle (Hard)",
    "statement": "\\textbf{The only difference with the medium version is the maximum length of the input.}\n\nA parentheses sequence is a string consisting of characters \"(\" and \")\", for example \"(()((\".\n\nA balanced parentheses sequence is a parentheses sequence which can become a valid mathematical expression after inserting numbers and operations into it, for example \"(()(()))\".\n\nThe balance of a parentheses sequence is defined as the number of opening parentheses \"(\" minus the number of closing parentheses \")\". For example, the balance of the sequence \"(()((\" is 3.\n\nA balanced parentheses sequence can also be defined as a parentheses sequence with balance 0 such that each of its prefixes has a non-negative balance.\n\nWe define the balanced shuffle operation that takes a parentheses sequence and returns a parentheses sequence as follows: first, for every character of the input sequence, we compute the balance of the prefix of the sequence before that character and write those down in a table together with the positions of the characters in the input sequence, for example:\n\n\\begin{tabular}{l||c||c||c||c||c||c||c||c}\nPrefix balance & 0 & 1 & 2 & 1 & 2 & 3 & 2 & 1 \\\n\\hline\n\\hline\nPosition & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\\n\\hline\n\\hline\nCharacter & ( & ( & ) & ( & ( & ) & ) & ) \\\n\\end{tabular}\n\nThen, we sort the columns of this table in increasing order of prefix balance, breaking ties in decreasing order of position. In the above example, we get:\n\n\\begin{tabular}{l||c||c||c||c||c||c||c||c}\nPrefix balance & 0 & 1 & 1 & 1 & 2 & 2 & 2 & 3 \\\n\\hline\n\\hline\nPosition & 1 & 8 & 4 & 2 & 7 & 5 & 3 & 6 \\\n\\hline\n\\hline\nCharacter & ( & ) & ( & ( & ) & ( & ) & ) \\\n\\end{tabular}\n\nThe last row of this table forms another parentheses sequence, in this case \"()(()())\". This sequence is called the result of applying the balanced shuffle operation to the input sequence, or in short just the balanced shuffle of the input sequence.\n\nSurprisingly, it turns out that the balanced shuffle of any balanced parentheses sequence is always another balanced parentheses sequence (we will omit the proof for brevity). Even more surprisingly, the balanced shuffles of two different balanced parentheses sequences are always different, therefore the balanced shuffle operation is a bijection on the set of balanced parentheses sequences of any given length (we will omit this proof, too).\n\nYou are given a balanced parentheses sequence. Find its preimage: the balanced parentheses sequence the balanced shuffle of which is equal to the given sequence.",
    "tutorial": "Solving this problem requires a more careful implementation of the algorithm described in the previous subtask. Since we only ever insert new parentheses into the current string after an unmatched parenthesis, we can use a linked list of characters instead of a string to represent it, and also store a vector of pointers to unmatched parentheses in it. This way each insertion will be done in $O(1)$ for a total running time of $O(n)$. Another way to view this solution is that we are constructing a rooted tree corresponding to the original parentheses sequence in a breadth-first manner, layer-by-layer, but then need to traverse it in a depth-first manner to print the original sequence. This runs in $O(n)$ if we store the tree using pointers or indices of children. In fact, we can notice that the layer-by-layer construction is not really necessary: we just create a queue of tree nodes, each opening parenthesis creates a new child of the node at the front of the queue and puts it at the back of the queue, and each closing parenthesis removes the node at the front of the queue from the queue. This way the implementation becomes very short.",
    "tags": [
      "constructive algorithms",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1970",
    "index": "B1",
    "title": "Exact Neighbours (Easy)",
    "statement": "\\textbf{The only difference between this and the hard version is that all $a_{i}$ are even.}\n\nAfter some recent attacks on Hogwarts Castle by the Death Eaters, the Order of the Phoenix has decided to station $n$ members in Hogsmead Village. The houses will be situated on a picturesque $n\\times n$ square field. Each wizard will have their own house, and every house will belong to some wizard. Each house will take up the space of one square.\n\nHowever, as you might know wizards are very superstitious. During the weekends, each wizard $i$ will want to visit the house that is exactly $a_{i}$ $(0 \\leq a_{i} \\leq n)$ away from their own house. The roads in the village are built horizontally and vertically, so the distance between points $(x_{i}, y_{i})$ and $(x_{j}, y_{j})$ on the $n\\times n$ field is $ |x_{i} - x_{j}| + |y_{i} - y_{j}|$. The wizards know and trust each other, so one wizard can visit another wizard's house when the second wizard is away. The houses to be built will be big enough for all $n$ wizards to simultaneously visit any house.\n\nApart from that, each wizard is mandated to have a view of the Hogwarts Castle in the north and the Forbidden Forest in the south, so the house of no other wizard should block the view. In terms of the village, it means that in each column of the $n\\times n$ field, there can be at most one house, i.e. if the $i$-th house has coordinates $(x_{i}, y_{i})$, then $x_{i} \\neq x_{j}$ for all $i \\neq j$.\n\nThe Order of the Phoenix doesn't yet know if it is possible to place $n$ houses in such a way that will satisfy the visit and view requirements of all $n$ wizards, so they are asking for your help in designing such a plan.\n\nIf it is possible to have a correct placement, where for the $i$-th wizard there is a house that is $a_{i}$ away from it and the house of the $i$-th wizard is the only house in their column, output YES, the position of houses for each wizard, and to the house of which wizard should each wizard go during the weekends.\n\nIf it is impossible to have a correct placement, output NO.",
    "tutorial": "Place all houses on the diagonal. Notice that for each house $i$ either to the left or to the right, on the diagonal, there will be a house with the desired distance $a_{i}$",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1970",
    "index": "B2",
    "title": "Exact Neighbours (Medium)",
    "statement": "\\textbf{The only difference between this and the hard version is that $a_{1} = 0$.}\n\nAfter some recent attacks on Hogwarts Castle by the Death Eaters, the Order of the Phoenix has decided to station $n$ members in Hogsmead Village. The houses will be situated on a picturesque $n\\times n$ square field. Each wizard will have their own house, and every house will belong to some wizard. Each house will take up the space of one square.\n\nHowever, as you might know wizards are very superstitious. During the weekends, each wizard $i$ will want to visit the house that is exactly $a_{i}$ $(0 \\leq a_{i} \\leq n)$ away from their own house. The roads in the village are built horizontally and vertically, so the distance between points $(x_{i}, y_{i})$ and $(x_{j}, y_{j})$ on the $n\\times n$ field is $ |x_{i} - x_{j}| + |y_{i} - y_{j}|$. The wizards know and trust each other, so one wizard can visit another wizard's house when the second wizard is away. The houses to be built will be big enough for all $n$ wizards to simultaneously visit any house.\n\nApart from that, each wizard is mandated to have a view of the Hogwarts Castle in the north and the Forbidden Forest in the south, so the house of no other wizard should block the view. In terms of the village, it means that in each column of the $n\\times n$ field, there can be at most one house, i.e. if the $i$-th house has coordinates $(x_{i}, y_{i})$, then $x_{i} \\neq x_{j}$ for all $i \\neq j$.\n\nThe Order of the Phoenix doesn't yet know if it is possible to place $n$ houses in such a way that will satisfy the visit and view requirements of all $n$ wizards, so they are asking for your help in designing such a plan.\n\nIf it is possible to have a correct placement, where for the $i$-th wizard there is a house that is $a_{i}$ away from it and the house of the $i$-th wizard is the only house in their column, output YES, the position of houses for each wizard, and to the house of which wizard should each wizard go during the weekends.\n\nIf it is impossible to have a correct placement, output NO.",
    "tutorial": "We don't care about satisfying the condition for the first house, since this house will always be at a distance $0$ from itself. There are at least two approaches for constructing the desired placement. Approach 1: Let's sort all $a_{i}$ in non-increasing order, then we can place houses in the zigzag order the following way: we will start by placing the first house in $(1, 1)$, then we will place each new house in the next column, alternating the relative position to the previous house up to down. Since $a_{i}$ is sorted in non-increasing order, we will never get out of the bounds of the field and the $i$-th house in the sorted order will satisfy the condition for the $i - 1$ house in the sorted order. Approach 2: Place the first house in $(1, 1)$. Then, place each next house in the next column. If $a_{i} \\geq i$, you can place the $i$-th house in such a way that it will be $a_{i}$ away from the first one. If $a_{i} < i$, you can place the house in the same row as the house with index $i - a_{i}$ and the house with this index will be $a_{i}$ away.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1970",
    "index": "B3",
    "title": "Exact Neighbours (Hard)",
    "statement": "After some recent attacks on Hogwarts Castle by the Death Eaters, the Order of the Phoenix has decided to station $n$ members in Hogsmead Village. The houses will be situated on a picturesque $n\\times n$ square field. Each wizard will have their own house, and every house will belong to some wizard. Each house will take up the space of one square.\n\nHowever, as you might know wizards are very superstitious. During the weekends, each wizard $i$ will want to visit the house that is exactly $a_{i}$ $(0 \\leq a_{i} \\leq n)$ away from their own house. The roads in the village are built horizontally and vertically, so the distance between points $(x_{i}, y_{i})$ and $(x_{j}, y_{j})$ on the $n\\times n$ field is $ |x_{i} - x_{j}| + |y_{i} - y_{j}|$. The wizards know and trust each other, so one wizard can visit another wizard's house when the second wizard is away. The houses to be built will be big enough for all $n$ wizards to simultaneously visit any house.\n\nApart from that, each wizard is mandated to have a view of the Hogwarts Castle in the north and the Forbidden Forest in the south, so the house of no other wizard should block the view. In terms of the village, it means that in each column of the $n\\times n$ field, there can be at most one house, i.e. if the $i$-th house has coordinates $(x_{i}, y_{i})$, then $x_{i} \\neq x_{j}$ for all $i \\neq j$.\n\nThe Order of the Phoenix doesn't yet know if it is possible to place $n$ houses in such a way that will satisfy the visit and view requirements of all $n$ wizards, so they are asking for your help in designing such a plan.\n\nIf it is possible to have a correct placement, where for the $i$-th wizard there is a house that is $a_{i}$ away from it and the house of the $i$-th wizard is the only house in their column, output YES, the position of houses for each wizard, and to the house of which wizard should each wizard go during the weekends.\n\nIf it is impossible to have a correct placement, output NO.",
    "tutorial": "Let's divide all valid arrays $a$ into three cases and solve the problem for each of them. First case There exists $i$ such that $a_{i} = 0$. We can use the solution to Medium. Now we can assume $1 \\leq a_{i} \\leq n$. Second case There are two numbers $i \\neq j$, such that $a_{i} = a_{j}$. We can adapt the algorithm from Medium to this case. For example, consider the first approach to Medium. We can do the same zigzag algorithm but skip the satisfaction of the next house when we have that in the sorted order two values are the same ($b_{i - 1} = b_{i}$ where $b$ is the sorted in non-increasing order array $a$). Third case In the remaining case the set of values will be exactly $\\{1, 2, \\ldots, n\\}$. When $n = 2$, the answer is $-1$. When $n \\geq 3$, we again sort $a_{i}$ and do the zigzag until we meet $3, 2, 1$. At that point we can do a special construction for $3, 2, 1$ which is not hard to come up with.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1970",
    "index": "C1",
    "title": "Game on Tree (Easy)",
    "statement": "\\textbf{This is the easy version of the problem. The difference in this version is that $t=1$ and we work on an array-like tree.}\n\nRon and Hermione are playing a game on a tree of $n$ nodes that are initially inactive. This tree is special because it has exactly two leaves. It can thus be seen as an array. The game consists of $t$ rounds, each of which starts with a stone on exactly one node, which is considered as activated. A move consists of picking an inactive neighbor of the node with a stone on it and moving the stone there (thus activating this neighbor). Ron makes the first move, after which he alternates with Hermione until no valid move is available. The player that cannot make a move loses the round. If both players play optimally, who wins each round of this game?\n\nNote that all the rounds are played with the same tree; only the starting node changes. Moreover, after each round, all active nodes are considered inactive again.",
    "tutorial": "We are given a linked list with an initial coin at index $1 \\leq i \\leq n$. There are $i-1$ nodes to its left and $n-i$ nodes to its right. Note that after the first move, all the remaining moves are fixed since there will be exactly one inactive neighbor. If one of $i-1, n-i$ is odd, Ron should move to the corresponding node as there will be an even number left thus guaranteeing a victory for Ron. Otherwise, Hermione is guaranteed to win.",
    "tags": [
      "games"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1970",
    "index": "C2",
    "title": "Game on Tree (Medium)",
    "statement": "\\textbf{This is the medium version of the problem. The difference in this version is that $t=1$ and we work on trees.}\n\nRon and Hermione are playing a game on a tree of $n$ nodes that are initially inactive. The game consists of $t$ rounds, each of which starts with a stone on exactly one node, which is considered as activated. A move consists of picking an inactive neighbor of the node with a stone on it and moving the stone there (thus activating this neighbor). Ron makes the first move, after which he alternates with Hermione until no valid move is available. The player that cannot make a move loses the round. If both players play optimally, who wins each round of this game?\n\nNote that all the rounds are played with the same tree; only the starting node changes. Moreover, after each round, all active nodes are considered inactive again.",
    "tutorial": "Let's root the tree at node $u_1$ (the start node). By doing so, we guarantee that if the coin is at node $v$, the parent of $v$ is already active and thus we can only go down in the tree. This means that each subtree can be seen as its own independent game. So, each node is either a winning or losing position (w.r.t. to the player whose turn is next). We will find recursively whether $u_1$ corresponds to a winning game for Ron. If some child of a node $v$ is a losing position, then the current player should move the coin to that child to guarantee a win. If all children are winning positions, the current player will surely lose. So, $v$ is a winning position iff it has a child that is a losing position. Note that the leaves are losing positions. This is solved in $O(n)$ time.",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1970",
    "index": "C3",
    "title": "Game on Tree (Hard)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference in this version is the constraint on $t$.}\n\nRon and Hermione are playing a game on a tree of $n$ nodes that are initially inactive. The game consists of $t$ rounds, each of which starts with a stone on exactly one node, which is considered as activated. A move consists of picking an inactive neighbor of the node with a stone on it and moving the stone there (thus activating this neighbor). Ron makes the first move, after which he alternates with Hermione until no valid move is available. The player that cannot make a move loses the round. If both players play optimally, who wins each round of this game?\n\nNote that all the rounds are played with the same tree; only the starting node changes. Moreover, after each round, all active nodes are considered inactive again.",
    "tutorial": "Repeating the previous solution for each $u_i$ is too slow as it gives a $O(n.t)$ solution. Instead, we will reuse the computations we did when assigning losing/winning positions. We do so using the re-rooting technique. Let's first compute the positions of the nodes in the tree rooted at 0. We will now find in linear time the position of each node if the tree was rooted at that node. Let $v$ be the current root (initially $v=0$) and let $w$ be a child of $v$. Let $T$ be the initial tree and $T'$ be the tree re-rooted at $w$. We know the positions of all nodes in $T$, and we want to find the position of nodes in $T'$. First note that only the positions of $v$ and $w$ may differ because the subtrees of all the other nodes remain unchanged. If $v$ has a child other than $w$ which corresponds to a losing position (in $T)$, then $v$ is a winning position in $T'$. If $v$ has no losing child or has exactly one losing child which is $w$ (in $T)$, then it is a losing position in $T'$. Similarly, if $w$ has some child that is a losing position (including $v$ in $T'$), then it is a winning position otherwise it is a losing position in $T'$. The above checks can be done in constant time by counting the number of losing children before the recursive calls (this count also needs to be maintained before recurring on a subtree). We thus recur on $W$ and repeat. Once the recursive call is over, we backtrack our changes before recurring on a different child of $v$. At the beginning of each recursive call, we know whether Ron or Hermione wins if the game started at that node so we can answer all the queries by doing linear-time pre-processing.",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1970",
    "index": "D1",
    "title": "Arithmancy (Easy)",
    "statement": "Professor Vector is preparing to teach her Arithmancy class. She needs to prepare $n$ distinct magic words for the class. Each magic word is a string consisting of characters X and O. A spell is a string created by concatenating two magic words together. The power of a spell is equal to the number of its different non-empty substrings. For example, the power of the spell XOXO is equal to 7, because it has 7 different substrings: X, O, XO, OX, XOX, OXO and XOXO.\n\nEach student will create their own spell by concatenating two magic words. Since the students are not very good at magic yet, they will choose each of the two words independently and uniformly at random from the $n$ words provided by Professor Vector. It is therefore also possible that the two words a student chooses are the same. Each student will then compute the power of their spell, and tell it to Professor Vector. In order to check their work, and of course to impress the students, Professor Vector needs to find out which two magic words and in which order were concatenated by each student.\n\nYour program needs to perform the role of Professor Vector: first, create $n$ distinct magic words, and then handle multiple requests where it is given the spell power and needs to determine the indices of the two magic words, in the correct order, that were used to create the corresponding spell.",
    "tutorial": "Given that we need to output 3 words only, we can manually (trying a few options on paper until we find a solution) construct 3 words such that all 9 spell powers are different.",
    "tags": [
      "brute force",
      "constructive algorithms",
      "interactive",
      "strings"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1970",
    "index": "D2",
    "title": "Arithmancy (Medium)",
    "statement": "\\textbf{The only difference between the versions of this problem is the maximum value of $n$.}\n\nProfessor Vector is preparing to teach her Arithmancy class. She needs to prepare $n$ distinct magic words for the class. Each magic word is a string consisting of characters X and O. A spell is a string created by concatenating two magic words together. The power of a spell is equal to the number of its different non-empty substrings. For example, the power of the spell XOXO is equal to 7, because it has 7 different substrings: X, O, XO, OX, XOX, OXO and XOXO.\n\nEach student will create their own spell by concatenating two magic words. Since the students are not very good at magic yet, they will choose each of the two words independently and uniformly at random from the $n$ words provided by Professor Vector. It is therefore also possible that the two words a student chooses are the same. Each student will then compute the power of their spell, and tell it to Professor Vector. In order to check their work, and of course to impress the students, Professor Vector needs to find out which two magic words and in which order were concatenated by each student.\n\nYour program needs to perform the role of Professor Vector: first, create $n$ distinct magic words, and then handle multiple requests where it is given the spell power and needs to determine the indices of the two magic words, in the correct order, that were used to create the corresponding spell.",
    "tutorial": "Now we need to find 30 words, so manually solving on paper is out of question. However, \"just trying\" still works: what we can do is to keep generating random words until we find 30 that have all 900 corresponding spell powers different. Depending on how you fast is your computation of the spell power you can either do this during the time limit, or precompute locally and then just submit a solution that prints the precomputed words. To make sure that we have to precompute only once instead of 30 times (for $n=1$, $n=2$, ...), we can find 30 words such that the $i$-th word has length $30\\cdot i$. This way the first $n$ words from this list give a valid answer to the problem for any $n<=30$. To compute the spell power, we can either use the naive approach of taking all substrings, sorting them and finding unique ones, some optimization thereof (for example, if the words are randomly generated, the chances that sufficiently long substrings coincide are vanishingly small and can be ignored), or the asymptotically optimal approach using any of the suffix data structures (the suffix array, or the suffix automaton, or the suffix tree).",
    "tags": [
      "constructive algorithms",
      "interactive",
      "probabilities",
      "strings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1970",
    "index": "D3",
    "title": "Arithmancy (Hard)",
    "statement": "\\textbf{The only difference between the versions of this problem is the maximum value of $n$.}\n\nProfessor Vector is preparing to teach her Arithmancy class. She needs to prepare $n$ distinct magic words for the class. Each magic word is a string consisting of characters X and O. A spell is a string created by concatenating two magic words together. The power of a spell is equal to the number of its different non-empty substrings. For example, the power of the spell XOXO is equal to 7, because it has 7 different substrings: X, O, XO, OX, XOX, OXO and XOXO.\n\nEach student will create their own spell by concatenating two magic words. Since the students are not very good at magic yet, they will choose each of the two words independently and uniformly at random from the $n$ words provided by Professor Vector. It is therefore also possible that the two words a student chooses are the same. Each student will then compute the power of their spell, and tell it to Professor Vector. In order to check their work, and of course to impress the students, Professor Vector needs to find out which two magic words and in which order were concatenated by each student.\n\nYour program needs to perform the role of Professor Vector: first, create $n$ distinct magic words, and then handle multiple requests where it is given the spell power and needs to determine the indices of the two magic words, in the correct order, that were used to create the corresponding spell.",
    "tutorial": "The previous approach of just generating random words does not even come close to working for $n=1000$ (in fact, it is hard to push it beyond roughly $n=50$). Now we need to add our own insights to the process. The first idea is: in order to answer the queries, we will likely need to know the spell power for all $n^2$ possible spells. But even if we use a suffix array to compute the spell power, it will be too slow to compute the spell power $10^6$ times for spells of length around $6\\cdot 10^4$. Therefore it is better to choose the magic words in such a way that computing the spell power of a concatenation of two such words can be done in $O(1)$. One way to achieve this is to choose some family of magic words $g_i$ with a regular structure and a single parameter $i$, and just figure out the function $f(i, j)$ for the spell power for the concatenation of $g_i$ and $g_j$ on paper, hopefully it will be easy to figure out and quick to compute. Then, what we can do is to go in increasing order of $i$, and try to take the next word $g_i$ into our set by checking if after adding it to the set, the newly added spells have spell powers that are different from each other and from the existing spell powers. Since we compute the spell power in $O(1)$, the total running time of this process is around $O(n\\cdot k)$, where $k$ is the number of $g_i$ we had to check before we managed to add $n$ of them into the set. The only remaining difficulty, and of course it is actually the main part of the solution, is to choose the family $g_i$. Here we have two main competing constraints: The words have to have simple structure, so that we can compute $f(i, j)$ quickly (in both senses: quickly figure out the formula, and the formula should be simple). However, we must have $f(i, j) \\ne f(j, i)$. It turns out that this rules out many word families with a very simple structure. We expect that once you realize the two constraints above, after a small amount of experimentation you will stumble upon a family that works. Here are two families that work that we know about, but I expect that there are many many more: $g_i=\\texttt{XOX}^{i-1}$. So $g_1=\\texttt{XO}$, $g_2=\\texttt{XOX}$, $g_3=\\texttt{XOXX}$, and so on. We found this family in the upsolving solution from one of the teams in the onsite round. $g_i=\\texttt{XO}^i\\texttt{XO}^i$. So $g_1=\\texttt{XOXO}$, $g_2=\\texttt{XOOXOO}$, $g_3=\\texttt{XOOOXOOO}$ and so on. This family actually leads to a string slightly longer than 30000 for $n=1000$, but it can be fixed by skipping the short strings that lead to too many collisions later (so we actually use $g_i=\\texttt{XO}^{i+5n}\\texttt{XO}^{i+5n}$). This was the original reference solution. As you noticed, our solution does not use the fact that the interactor is guaranteed to be random. The reason the problem was set like this is that we're not aware of a way to find collisions quickly enough that we could use to simply check if the $n$ printed magic words yield $n^2$ distinct spell powers. Therefore to make the problem well-defined and avoid the need for contestants to guess how strong the checker is, we made it weak (just trying 1000 random spells) but well-specified.",
    "tags": [
      "interactive"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1970",
    "index": "E1",
    "title": "Trails (Easy)",
    "statement": "Harry Potter is hiking in the Alps surrounding Lake Geneva. In this area there are $m$ cabins, numbered 1 to $m$. Each cabin is connected, with one or more trails, to a central meeting point next to the lake. Each trail is either \\underline{short} or \\underline{long}. Cabin $i$ is connected with $s_i$ short trails and $l_i$ long trails to the lake.\n\nEach day, Harry walks a trail from the cabin where he currently is to Lake Geneva, and then from there he walks a trail to any of the $m$ cabins (including the one he started in). However, as he has to finish the hike in a day, at least one of the two trails has to be short.\n\nHow many possible combinations of trails can Harry take if he starts in cabin 1 and walks for $n$ days?\n\nGive the answer modulo $10^9 + 7$.",
    "tutorial": "Let $t_i := s_i + l_i$. The number of possible paths between cabin $i$ and cabin $j$ is $t_i t_j - l_i l_j$. Let $\\mathbf{v}_{k,i}$ be the number of paths that ends in cabin $i$ after walking for $k$ days. We then have $\\mathbf{v}_{0,1} = 1, \\\\ \\mathbf{v}_{0,i} = 0 \\text{ for } i \\neq 1,$ $\\mathbf{v}_{k+1,i} = \\sum_{j = 1}^{m} (t_i t_j - l_i l_j) \\mathbf{v}_{k,j}.$ $\\mathbf{v}_{n,1} + \\dots + \\mathbf{v}_{n,m}.$",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1970",
    "index": "E2",
    "title": "Trails (Medium)",
    "statement": "Harry Potter is hiking in the Alps surrounding Lake Geneva. In this area there are $m$ cabins, numbered 1 to $m$. Each cabin is connected, with one or more trails, to a central meeting point next to the lake. Each trail is either \\underline{short} or \\underline{long}. Cabin $i$ is connected with $s_i$ short trails and $l_i$ long trails to the lake.\n\nEach day, Harry walks a trail from the cabin where he currently is to Lake Geneva, and then from there he walks a trail to any of the $m$ cabins (including the one he started in). However, as he has to finish the hike in a day, at least one of the two trails has to be short.\n\nHow many possible combinations of trails can Harry take if he starts in cabin 1 and walks for $n$ days?\n\nGive the answer modulo $10^9 + 7$.",
    "tutorial": "Let $t_i := s_i + l_i$. The number of possible paths between cabin $i$ and cabin $j$ is $t_i t_j - l_i l_j$. Let $\\mathbf{v}_{k}$ be the vector whose $i$th entry is the number of paths that ends in cabin $i$ after walking for $k$ days. We then have $\\mathbf{v}_0 = (1, 0, \\dots, 0),$ $(\\mathbf{v}_{k+1})_i = \\sum_{j = 1}^{m} (t_i t_j - l_i l_j) (\\mathbf{v}_{k})_j.$ $A_{i,j} = t_i t_j - l_i l_j.$ $\\mathbf{v}_{k+1} = A \\mathbf{v}_k.$ $\\mathbf{v}_n = A^n \\mathbf{v}_0.$ Compute $B := A^{\\lfloor n/2 \\rfloor}$ If $n$ is even: Return $B^2$ Else: Return $B^2 A$ The solution to the problem is now $(\\mathbf{v}_n)_1 + \\dots + (\\mathbf{v}_n)_m.$",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1970",
    "index": "E3",
    "title": "Trails (Hard)",
    "statement": "Harry Potter is hiking in the Alps surrounding Lake Geneva. In this area there are $m$ cabins, numbered 1 to $m$. Each cabin is connected, with one or more trails, to a central meeting point next to the lake. Each trail is either \\underline{short} or \\underline{long}. Cabin $i$ is connected with $s_i$ short trails and $l_i$ long trails to the lake.\n\nEach day, Harry walks a trail from the cabin where he currently is to Lake Geneva, and then from there he walks a trail to any of the $m$ cabins (including the one he started in). However, as he has to finish the hike in a day, at least one of the two trails has to be short.\n\nHow many possible combinations of trails can Harry take if he starts in cabin 1 and walks for $n$ days?\n\nGive the answer modulo $10^9 + 7$.",
    "tutorial": "Let $t_i := s_i + l_i$. The number of possible paths between cabin $i$ and cabin $j$ is $t_i t_j - l_i l_j$. Let $\\mathbf{v}_{k}$ be the vector whose $i$th entry is the number of paths that ends in cabin $i$ after walking for $k$ days. We then have $\\mathbf{v}_0 = (1, 0, \\dots, 0),$ $(\\mathbf{v}_{k+1})_i = \\sum_{j = 1}^{m} (t_i t_j - l_i l_j) (\\mathbf{v}_{k})_j.$ $A_{i,j} = t_i t_j - l_i l_j.$ $\\mathbf{v}_{k+1} = A \\mathbf{v}_k.$ $\\mathbf{v}_n = A^n \\mathbf{v}_0.$ Now, observe that $A$ can be written as $A = BC$, where $B$ is the $(m \\times 2)$-matrix $\\begin{pmatrix} t_1 & l_1 \\\\ t_2 & l_2 \\\\ \\vdots & \\vdots \\\\ t_m & l_m \\\\ \\end{pmatrix},$ $\\begin{pmatrix} t_1 & t_2 & \\cdots & t_m \\\\ -l_1 & -l_2 & \\cdots & -l_m \\\\ \\end{pmatrix}.$ $A^n = B (CB)^{n-1} C.$ $\\mathbf{v}_n = B (CB)^{n-1} C \\mathbf{v}_0$",
    "tags": [
      "dp",
      "matrices"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1970",
    "index": "F3",
    "title": "Playing Quidditch (Hard)",
    "statement": "This afternoon, you decided to enjoy the first days of Spring by taking a walk outside. As you come near the Quidditch field, you hear screams. Once again, there is a conflict about the score: the two teams are convinced that they won the game! To prevent this problem from happening one more time, you decide to get involved in the refereeing of the matches.\n\nNow, you will stay in the stadium to watch the game and count the score. At the end of the game, you will decide the winner.\n\nToday, two teams are competing: the red Gryffindor (R) and the blue Ravenclaw (B) team. Each team is composed of $P$ players ($1 \\leq P \\leq 10$).\n\nThe field is a rectangle of $N$ lines and $M$ columns ($3 \\leq N, M \\leq 99$, $N$ and $M$ are odd). All the positions are integers, and several entities are allowed to be at the same position in the field. At the beginning of the game, the field contains goals for the two teams (each team can own between one and five goals), the players, and exactly one Quaffle. In this version of the problem, one Bludger \\textbf{and a Golden Snitch} can be present.\n\nA game is composed of $T$ steps ($0 \\leq T \\leq 10000$). At each step, one entity on the field (a player or a ball) performs one action. All entities can move. A player can also catch a ball or throw the Quaffle that it is carrying. To catch a ball, a player must be located on the same cell as it. The Quaffle does not perform any action while it is being carried; it only follows the movements of the player. If a player carrying the Quaffle decides to throw it, the Quaffle is simply put at the current position of the player. If a player is on the same cell as a Bludger (either after a movement from the player or the Bludger), the player is eliminated. If the player is eliminated while it is carrying the Quaffle, the Quaffle remains on the cell containing both the player and the Bludger after the move. It is guaranteed that this never occurs while the player is in a cell containing a goal.\n\nTo win a point, a player must leave the Quaffle at a goal of the other team. When it does, the team of the player wins one point, and the Quaffle instantly moves to the middle of the field (the cell at the $(M+1)/2$-th column of the $(N+1)/2$-th line of the field, starting from 1). There is no goal in the middle of the field. If a player puts the ball in its own goal, the other team wins the point. \\textbf{If a player catches the Golden Snitch, their team wins 10 points and the game is over.}",
    "tutorial": "This subject does not contain theoretical difficulty: it is only needed to simulate the game following the rules described in the statement. To be able to perform the simulation easily, it is useful to store wisely the current state of the game. the position of the goals, either in a grid, a set or a list the position of the players, for example a list containing the position of each player the position of the balls the current score of each team Then, at each step of the simulation, the current state must be updated following the rules.",
    "tags": [
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1970",
    "index": "G1",
    "title": "Min-Fund Prison (Easy)",
    "statement": "\\textbf{In the easy version, $m = n-1$ and there exists a path between $u$ and $v$ for all $u, v$ ($1 \\leq u, v \\leq n$).}\n\nAfter a worker's strike organized by the Dementors asking for equal rights, the prison of Azkaban has suffered some damage. After settling the spirits, the Ministry of Magic is looking to renovate the prison to ensure that the Dementors are kept in check. The prison consists of $n$ prison cells and $m$ bi-directional corridors. The $i^{th}$ corridor is from cells $u_i$ to $v_i$. A subset of these cells $S$ is called a complex if any cell in $S$ is reachable from any other cell in $S$. Formally, a subset of cells $S$ is a complex if $x$ and $y$ are reachable from each other for all $x, y \\in S$, using only cells from $S$ on the way. The funding required for a complex $S$ consisting of $k$ cells is defined as $k^2$.\n\nAs part of your Intro to Magical Interior Design course at Hogwarts, you have been tasked with designing the prison. The Ministry of Magic has asked that you divide the prison into $2$ complexes with $\\textbf{exactly one corridor}$ connecting them, so that the Dementors can't organize union meetings. For this purpose, you are allowed to build bi-directional corridors. The funding required to build a corridor between any $2$ cells is $c$.\n\nDue to budget cuts and the ongoing fight against the Death Eaters, you must find the $\\textbf{minimum total funding}$ required to divide the prison as per the Ministry's requirements or $-1$ if no division is possible.\n\nNote: The total funding is the sum of the funding required for the $2$ complexes and the corridors built. If after the division, the two complexes have $x$ and $y$ cells respectively and you have built a total of $a$ corridors, the total funding will be $x^2 + y^2 + c \\times a$. Note that $x+y=n$.",
    "tutorial": "The cells and corridors in this subtask form a tree. No matter how we divide the prison into two complexes, there will be at least one existing corridor connecting them, but we must have at most one such corridor, which means that we do not need to build any more corridors. For each existing corridor, removing it splits the tree into two parts, and those two parts are the only possibility to have two complexes connected only by this corridor. So we need to compute the sizes of the two parts for every corridor, and then pick the corridor that minimizes the sum of squares of the sizes. In order to compute the sizes of the two parts for each corridor quickly we can root the tree and then use depth-first search that recursively computes the size of each subtree. The running time of this solution is $O(n)$.",
    "tags": [
      "dfs and similar",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1970",
    "index": "G2",
    "title": "Min-Fund Prison (Medium)",
    "statement": "\\textbf{In the medium version, $2 \\leq \\sum n \\leq 300$ and $1 \\leq \\sum m \\leq 300$}\n\nAfter a worker's strike organized by the Dementors asking for equal rights, the prison of Azkaban has suffered some damage. After settling the spirits, the Ministry of Magic is looking to renovate the prison to ensure that the Dementors are kept in check. The prison consists of $n$ prison cells and $m$ bi-directional corridors. The $i^{th}$ corridor is from cells $u_i$ to $v_i$. A subset of these cells $S$ is called a complex if any cell in $S$ is reachable from any other cell in $S$. Formally, a subset of cells $S$ is a complex if $x$ and $y$ are reachable from each other for all $x, y \\in S$, using only cells from $S$ on the way. The funding required for a complex $S$ consisting of $k$ cells is defined as $k^2$.\n\nAs part of your Intro to Magical Interior Design course at Hogwarts, you have been tasked with designing the prison. The Ministry of Magic has asked that you divide the prison into $2$ complexes with $\\textbf{exactly one corridor}$ connecting them, so that the Dementors can't organize union meetings. For this purpose, you are allowed to build bi-directional corridors. The funding required to build a corridor between any $2$ cells is $c$.\n\nDue to budget cuts and the ongoing fight against the Death Eaters, you must find the $\\textbf{minimum total funding}$ required to divide the prison as per the Ministry's requirements or $-1$ if no division is possible.\n\nNote: The total funding is the sum of the funding required for the $2$ complexes and the corridors built. If after the division, the two complexes have $x$ and $y$ cells respectively and you have built a total of $a$ corridors, the total funding will be $x^2 + y^2 + c \\times a$. Note that $x+y=n$.",
    "tutorial": "The graph is no longer a tree in this problem, but we can try to generalize the solution for the first subtask. First of all, suppose the graph is connected. Similar to the first subtask, there will always be at least one existing corridor connecting the two complexes, so we do not need to build new corridors. Moreover, there will be exactly one existing corridor connecting the two complexes if and only if said corridor is a bridge in the graph, and the two complexes are the two connected components that appear after removing this bridge. We can modify the depth-first search algorithm that finds bridges in the graph to also compute the component sizes, and therefore we can solve our problem for connected graphs. Now, what to do if the graph is not connected? There are two cases: At least one connected component will be split between the two complexes. In this case exactly one component must be split in this way, and the split must be done using a bridge in this component similar to the connected graph solution. For every other connected component it must go either completely to the first complex or completely to the second complex. We need to build additional corridors to connect components within the complexes, and the number of additional corridors is equal to the number of connected components in the graph minus one. No connected component will be split between the two complexes. In this case we need to build additional corridors both to connect components within the complexes, but also to connect the complexes to each other. The number of additional corridors is still equal to the number of connected components in the graph minus one. Since the number of additional corridors is constant, we still need to minimize the sum of squares of the sizes of the complexes. We now need to solve a knapsack problem to find out the possible sizes of the first complex. To account for the fact that at most one component may be split using a bridge, we can add a boolean flag to the knapsack dynamic programming state that tracks whether we have already split a component. The running time of this solution is $O(n^2)$.",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1970",
    "index": "G3",
    "title": "Min-Fund Prison (Hard)",
    "statement": "\\textbf{In the hard version, $2 \\leq \\sum n \\leq 10^5$ and $1 \\leq \\sum m \\leq 5 \\times 10^{5}$}\n\nAfter a worker's strike organized by the Dementors asking for equal rights, the prison of Azkaban has suffered some damage. After settling the spirits, the Ministry of Magic is looking to renovate the prison to ensure that the Dementors are kept in check. The prison consists of $n$ prison cells and $m$ bi-directional corridors. The $i^{th}$ corridor is from cells $u_i$ to $v_i$. A subset of these cells $S$ is called a complex if any cell in $S$ is reachable from any other cell in $S$. Formally, a subset of cells $S$ is a complex if $x$ and $y$ are reachable from each other for all $x, y \\in S$, using only cells from $S$ on the way. The funding required for a complex $S$ consisting of $k$ cells is defined as $k^2$.\n\nAs part of your Intro to Magical Interior Design course at Hogwarts, you have been tasked with designing the prison. The Ministry of Magic has asked that you divide the prison into $2$ complexes with $\\textbf{exactly one corridor}$ connecting them, so that the Dementors can't organize union meetings. For this purpose, you are allowed to build bi-directional corridors. The funding required to build a corridor between any $2$ cells is $c$.\n\nDue to budget cuts and the ongoing fight against the Death Eaters, you must find the $\\textbf{minimum total funding}$ required to divide the prison as per the Ministry's requirements or $-1$ if no division is possible.\n\nNote: The total funding is the sum of the funding required for the $2$ complexes and the corridors built. If after the division, the two complexes have $x$ and $y$ cells respectively and you have built a total of $a$ corridors, the total funding will be $x^2 + y^2 + c \\times a$. Note that $x+y=n$.",
    "tutorial": "In the hard subtask, the $O(n^2)$ solution is too slow. One way to get it accepted is to use bitsets to speed it up, as the knapsack transitions can simply be expressed as a bitwise shift + bitwise or. However, there is also an asymptotically faster approach. First of all, instead of remembering the possible splits using a bridge for each component, we will just remember for each component size, how it can be split by a bridge. Since the sum of component sizes is $n$, this needs only $O(n)$ memory. Now, if we have at least four components of the same size $x$, for the purposes of our knapsack we can replace two of them with a component of size $2x$, and the set of reachable complex sizes will not change. Since we keep at least two components of size $x$, the set of reachable complex sizes will not change even if we later split one of the components of size $x$ using the bridges. If we repeat the above procedure until we have at most three components of each size, the total number of components will be $O(\\sqrt{n})$. Therefore the knapsack dynamic programming that does not take splitting via a bridge into account will run in $O(n\\cdot\\sqrt{n})$. In order to tackle the splitting via a bridge fast, let us first run the dynamic programming that does not allow to split components, but instead of computing a boolean for each complex size that tells if this size can be reached, we will compute the number of ways to reach it, modulo a large prime. A step of this dynamic programming is reversible, therefore we can then for each component size compute in $O(n)$ which sizes can be reached without using one of the components of this size. Now we need to combine this with the ways to split a component of this size using a bridge, and since the sum of squares of the sizes is smaller whenever the sizes are closer to each other, for each way to split the component using a bridge we need to find the reachable state of the dynamic programming that is the closest to $\\frac{n}{2}$ minus the size of the part disconnected by the bridge, which can be done in $O(n)$ for all ways to split using a bridge via the two pointer method. Therefore the total running time of this solution is $O(n\\cdot\\sqrt{n})$.",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "dp",
      "graphs",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1971",
    "index": "A",
    "title": "My First Sorting Problem",
    "statement": "You are given two integers $x$ and $y$.\n\nOutput two integers: the minimum of $x$ and $y$, followed by the maximum of $x$ and $y$.",
    "tutorial": "You can use, for example, an if-statement or some inbuilt $\\texttt{min}$ and $\\texttt{max}$ function available in most languages (like Python or C++).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tint x, y;\n\tcin >> x >> y;\n\tcout << min(x, y) << ' ' << max(x, y) << '\\n';\t\n}\n \nint main() {\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1971",
    "index": "B",
    "title": "Different String",
    "statement": "You are given a string $s$ consisting of lowercase English letters.\n\nRearrange the characters of $s$ to form a new string $r$ that is \\textbf{not equal} to $s$, or report that it's impossible.",
    "tutorial": "Since the string is length at most $10$, we can try all swaps of two characters of the string. This is $\\mathcal{O}(|s|^2)$ per test case, which is fast enough. If none of them create a different string, then all characters in the original string are the same, so the answer is NO. Bonus: Actually, it's enough to try all swaps with the first character, solving the problem in $\\mathcal{O}(|s|)$. Why?",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tbool ok = false;\n\tfor (int i = 1; i < (int)(s.length()); i++) {\n\t\tif (s[i] != s[0]) {swap(s[i], s[0]); ok = true; break;}\n\t}\t\n\tif (!ok) {\n\t\tcout << \"NO\\n\"; return;\n\t}\n\tcout << \"YES\\n\";\n\tcout << s << '\\n';\n}\n \nint main() {\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1971",
    "index": "C",
    "title": "Clock and Strings",
    "statement": "There is a clock labeled with the numbers $1$ through $12$ in clockwise order, as shown below.\n\n\\begin{center}\n{\\small In this example, $(a,b,c,d)=(2,9,10,6)$, and the strings intersect.}\n\\end{center}\n\nAlice and Bob have four \\textbf{distinct} integers $a$, $b$, $c$, $d$ not more than $12$. Alice ties a red string connecting $a$ and $b$, and Bob ties a blue string connecting $c$ and $d$. Do the strings intersect? (The strings are straight line segments.)",
    "tutorial": "There are many ways to implement the solution, but many involve a lot of casework. Below is the shortest solution we know of. Walk around the clock in the order $1$, $2$, $\\dots$, $12$. If we pass by two red strings or two blue strings in a row, the strings don't intersect; otherwise, they do. This is because if we don't have two red or blue in a row, then the red and blue strings alternate, so there must be an intersection.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tint a, b, c, d;\n\tcin >> a >> b >> c >> d;\n\tstring s;\n\tfor (int i = 1; i <= 12; i++) {\n\t\tif (i == a || i == b) {s += \"a\";}\n\t\tif (i == c || i == d) {s += \"b\";}\n\t}\n\tcout << (s == \"abab\" || s == \"baba\" ? \"YES\\n\" : \"NO\\n\");\n}\n \nint main() {\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1971",
    "index": "D",
    "title": "Binary Cut",
    "statement": "You are given a binary string$^{\\dagger}$. Please find the minimum number of pieces you need to cut it into, so that the resulting pieces can be rearranged into a sorted binary string.\n\nNote that:\n\n- each character must lie in exactly one of the pieces;\n- the pieces must be contiguous substrings of the original string;\n- you must use all the pieces in the rearrangement.\n\n$^{\\dagger}$ A binary string is a string consisting of characters $0$ and $1$. A sorted binary string is a binary string such that all characters $0$ come before all characters $1$.",
    "tutorial": "First, note that it's always optimal to divide the string into \"blocks\" of equal values; there is no use having two strings $\\texttt{111}|\\texttt{11}$ when we can just have $\\texttt{11111}$ and use fewer pieces. Now note that to sort the string, we need all blocks of $\\texttt{0}$ to come before all blocks of $\\texttt{1}$. The only way that two blocks can join is if we have a block of $\\texttt{0}$s before a block of $\\texttt{1}$s, and we can have at most one such block. That is, all strings look like: $(\\text{blocks of }\\texttt{0}\\text{s}) \\underbrace{\\texttt{0...1}}_{\\leq 1\\text{joined block of }\\texttt{0}\\text{s and }\\texttt{1}\\text{s}} (\\text{blocks of }\\texttt{1}\\text{s})$ So the answer is the number of blocks, but we should subtract $1$ if a substring $\\texttt{01}$ exists (because then we can make the center block above). The time complexity is $\\mathcal{O}(|s|)$. For example, for the string $\\texttt{111000110}$, we can use three pieces: $\\texttt{111}|\\texttt{00011}|\\texttt{0} \\to \\texttt{0}|\\texttt{00011}|\\texttt{111}$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tstring s;\n\tcin >> s;\n\tint res = 1;\n\tbool ex = false;\n\tfor (int i = 0; i + 1 < (int)(s.size()); i++) {\n\t\tres += (s[i] != s[i + 1]);\n\t\tex |= (s[i] == '0' && s[i + 1] == '1');\n\t}\n\tcout << res - ex << '\\n';\n}\n \nint main() {\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1971",
    "index": "E",
    "title": "Find the Car",
    "statement": "Timur is in a car traveling on the number line from point $0$ to point $n$. The car starts moving from point $0$ at minute $0$.\n\nThere are $k+1$ signs on the line at points $0, a_1, a_2, \\dots, a_k$, and Timur knows that the car will arrive there at minutes $0, b_1, b_2, \\dots, b_k$, respectively. The sequences $a$ and $b$ are strictly increasing with $a_k = n$.\n\nBetween any two adjacent signs, the car travels with a \\textbf{constant speed}. Timur has $q$ queries: each query will be an integer $d$, and Timur wants you to output how many minutes it takes the car to reach point $d$, \\textbf{rounded down to the nearest integer}.",
    "tutorial": "For each query, we binary search to find the last sign we passed (since the array $a$ is sorted). Say it is $a_r$. Then, $b_r$ minutes have passed. To find out how much time has passed since we left that sign, we know that the speed between sign $r$ and $r+1$ is $\\frac{a_{r+1} - a_r}{b_{r+1} - b_r} \\, \\frac{\\text{distance}}{\\text{minute}}$ (by the usual formula for speed). We have passed a distance $c - a_r$ since the last sign, so the total number of minutes since the last sign is $\\frac{b_{r+1} - b_r}{a_{r+1} - a_r} \\, \\frac{\\text{minute}}{\\text{distance}} \\times c - a_r \\, \\text{distance} = (c - a_r) \\times \\frac{b_{r+1} - b_r}{a_{r+1} - a_r} \\, \\text{minutes}.$ Be careful about using floating-point numbers, as they can behave strangely. Our solution below doesn't use them at all.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <array>\n#include <set>\n#include <map>\n#include <queue>\n#include <stack>\n#include <list>\n#include <chrono>\n#include <random>\n#include <cstdlib>\n#include <cmath>\n#include <ctime>\n#include <cstring>\n#include <iomanip>\n#include <bitset>\n#include <cassert>\ntypedef long long  ll;\nusing namespace std;\n \nvoid solve()\n{\n    int n, k, q;\n    cin >> n >> k >> q;\n    vector<long long> a(k+1), b(k+1);\n    a[0] = 0;\n    b[0] = 0;\n    for(int i = 1; i <= k; i++)\n    {\n        cin >> a[i];\n    }\n    for(int i = 1; i <= k; i++)\n    {\n        cin >> b[i];\n    }\n    for(int i = 0; i < q; i++)\n    {\n        long long c;\n        cin >> c;\n        int l = 0, r = k;\n        while(l <= r)\n        {\n            int mid = l+r>>1;\n            if(a[mid] > c)\n            {\n                r = mid-1;\n            }\n            else\n            {\n                l = mid+1;\n            }\n        }\n        if(a[r] == c)\n        {\n            cout << b[r] << \" \";\n            continue;\n        }\n        long long ans = b[r] + (c-a[r])*(b[r+1]-b[r])/(a[r+1]-a[r]);\n        cout << ans << \" \";\n    }\n    cout << endl;\n}\n \nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n \n \n \n",
    "tags": [
      "binary search",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1971",
    "index": "F",
    "title": "Circle Perimeter",
    "statement": "Given an integer $r$, find the number of lattice points that have a Euclidean distance from $(0, 0)$ \\textbf{greater than or equal to} $r$ but \\textbf{strictly less} than $r+1$.\n\nA lattice point is a point with integer coordinates. The Euclidean distance from $(0, 0)$ to the point $(x,y)$ is $\\sqrt{x^2 + y^2}$.",
    "tutorial": "There are many solutions to this problem, some of which involve binary search, but we will present a solution that doesn't use it. In fact, our solution is basically just brute force, but with some small observations that make it pass. See the implementation for more detail. First, we can only count points $(x,y)$ such that $x \\geq 0$ and $y > 0$; we can multiply by $4$ at the end to get points in all four quadrants, by symmetry. Let's store a variable $\\mathrm{height}$ initially equal to $r$. It will tell us the maximum $y$-value to look at. Iterate through all values of $x$ from $0$ to $r$. For each $x$, decrease $\\mathrm{height}$ until the distance of $(x,\\mathrm{height})$ to the origin is $< r+1$. Then, brute force all values of $y$ from $\\mathrm{height}$ downwards until we hit a point whose distance to the origin is $< r$; at this point, we break and add the number of valid points to our total. Note that we essentially only look at points whose distance to the origin is between $r$ and $r+1$; that is, we brute force over all valid points. How many valid points are there? Well, we can roughly estimate the number of points as the area of the region, which is $\\pi(r^2 - (r-1)^2) = 2\\pi r - \\pi$. This means we only visit $\\mathcal{O}(r)$ points per test case, which is fast enough.",
    "code": "#include <iostream>\nusing namespace std;\n \nvoid solve()\n{\n    long long r;\n    cin >> r;\n    long long height = r;\n    long long ans = 0;\n    for(long long i = 0; i <= r; i++)\n    {\n        while(i*i+height*height >= (r+1)*(r+1))\n        {\n            height--;\n        }\n        long long cop = height;\n        while(i*i+cop*cop >= r*r && cop > 0)\n        {\n            cop--;\n            ans++;\n        }\n    }\n    cout << ans*4 << endl;\n}\n \nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n \n \n \n",
    "tags": [
      "binary search",
      "brute force",
      "dfs and similar",
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1971",
    "index": "G",
    "title": "XOUR",
    "statement": "You are given an array $a$ consisting of $n$ nonnegative integers.\n\nYou can swap the elements at positions $i$ and $j$ if $a_i~\\mathsf{XOR}~a_j < 4$, where $\\mathsf{XOR}$ is the bitwise XOR operation.\n\nFind the lexicographically smallest array that can be made with any number of swaps.\n\nAn array $x$ is lexicographically smaller than an array $y$ if in the first position where $x$ and $y$ differ, $x_i < y_i$.",
    "tutorial": "Note that if $a_i~\\mathsf{XOR}~a_j < 4$, then $a_i$ and $a_j$ must share all bits in their binary representation, except for the last $2$ bits. This is because if they have a mismatch in any greater bit, their $\\mathsf{XOR}$ will include this bit, making its value $\\geq 2^2=4$. This means that we can group the numbers by removing the last two bits and putting equal numbers into the same group. In each group, we can order the numbers freely (since we can swap any two of them), so it's optimal to sort the numbers in each group. Thus we can just divide the numbers into groups and sort each, solving the problem in $\\mathcal{O}(n \\log n)$. There are several ways to implement this: for instead, you can use a map storing all the groups, and then sort the values in each group. The implementation we used maps each integer to a priority queue, which automatically will sort the numbers in each group.",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <map>\n#include <queue>\n \nusing namespace std;\n \n \nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    map<int, priority_queue<int>> mp;\n    for(int i = 0; i < n; i++)\n    {\n        cin >> a[i];\n        mp[a[i]>>2].push(-a[i]);\n    }\n    for(int i = 0; i < n; i++)\n    {\n        cout << -mp[a[i]>>2].top() << \" \";\n        mp[a[i]>>2].pop();\n    }\n    cout << endl;\n}\n \nint32_t main(){\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "data structures",
      "dsu",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1971",
    "index": "H",
    "title": "±1",
    "statement": "Bob has a grid with $3$ rows and $n$ columns, each of which contains either $a_i$ or $-a_i$ for some integer $1 \\leq i \\leq n$. For example, one possible grid for $n=4$ is shown below:\n\n$$\\begin{bmatrix} a_1 & -a_2 & -a_3 & -a_2 \\\\ -a_4 & a_4 & -a_1 & -a_3 \\\\ a_1 & a_2 & -a_2 & a_4 \\end{bmatrix}$$\n\nAlice and Bob play a game as follows:\n\n- Bob shows Alice his grid.\n- Alice gives Bob an array $a_1, a_2, \\dots, a_n$ of her choosing, \\textbf{whose elements are all $\\mathbf{-1}$ or $\\mathbf{1}$}.\n- Bob substitutes these values into his grid to make a grid of $-1$s and $1$s.\n- Bob \\textbf{sorts} the elements of each column in non-decreasing order.\n- Alice wins if all the elements in the middle row are $1$; otherwise, Bob wins.\n\nFor example, suppose Alice gives Bob the array $[1, -1, -1, 1]$ for the grid above. Then the following will happen (colors are added for clarity):\n\n$$\\begin{bmatrix} \\textcolor{red}{a_1} & \\textcolor{green}{-a_2} & \\textcolor{blue}{-a_3} & \\textcolor{green}{-a_2} \\\\ -a_4 & a_4 & \\textcolor{red}{-a_1} & \\textcolor{blue}{-a_3} \\\\ \\textcolor{red}{a_1} & \\textcolor{green}{a_2} & \\textcolor{green}{-a_2} & a_4 \\end{bmatrix} \\xrightarrow{[\\textcolor{red}{1},\\textcolor{green}{-1},\\textcolor{blue}{-1},1]} \\begin{bmatrix} \\textcolor{red}{1} & \\textcolor{green}{1} & \\textcolor{blue}{1} & \\textcolor{green}{1} \\\\ -1 & 1 & \\textcolor{red}{-1} & \\textcolor{blue}{1} \\\\ \\textcolor{red}{1} & \\textcolor{green}{-1} & \\textcolor{green}{1} & 1 \\end{bmatrix} \\xrightarrow{\\text{sort each column}} \\begin{bmatrix} -1 & -1 & -1 & 1 \\\\ \\mathbf{1} & \\mathbf{1} & \\mathbf{1} & \\mathbf{1} \\\\ 1 & 1 & 1 & 1 \\\\ \\end{bmatrix}\\,. $$ Since the middle row is all $1$, Alice wins.\n\nGiven Bob's grid, determine whether or not Alice can choose the array $a$ to win the game.",
    "tutorial": "The problem statement is somewhat reminiscent of SAT. Indeed, treating $+1$ as true and $-1$ as false, we have clauses of length $3$, and we need at least $2$ of the variables to be true. We can reduce this to 2-SAT with the following observation: at least $2$ of $(x,y,z)$ are true $\\iff$ at least one of $(x,y)$ is true, at least one of $(y,z)$ is true, and at least one of $(z,x)$ is true. That is, for each column of the grid, we make three 2-SAT clauses. Then we just run 2-SAT on these clauses, and output if there is a solution. The time complexity is $\\mathcal{O}(n)$ per test case. It might be time-consuming to code 2-SAT during the contest, so we recommend using some standard library (for example, our solution uses AtCoder library).",
    "code": "#include <bits/stdc++.h>\n \n \n#include <algorithm>\n#include <utility>\n#include <vector>\n \nnamespace atcoder {\nnamespace internal {\n \ntemplate <class E> struct csr {\n    std::vector<int> start;\n    std::vector<E> elist;\n    csr(int n, const std::vector<std::pair<int, E>>& edges)\n        : start(n + 1), elist(edges.size()) {\n        for (auto e : edges) {\n            start[e.first + 1]++;\n        }\n        for (int i = 1; i <= n; i++) {\n            start[i] += start[i - 1];\n        }\n        auto counter = start;\n        for (auto e : edges) {\n            elist[counter[e.first]++] = e.second;\n        }\n    }\n};\n \n// Reference:\n// R. Tarjan,\n// Depth-First Search and Linear Graph Algorithms\nstruct scc_graph {\n  public:\n    scc_graph(int n) : _n(n) {}\n \n    int num_vertices() { return _n; }\n \n    void add_edge(int from, int to) { edges.push_back({from, {to}}); }\n \n    // @return pair of (# of scc, scc id)\n    std::pair<int, std::vector<int>> scc_ids() {\n        auto g = csr<edge>(_n, edges);\n        int now_ord = 0, group_num = 0;\n        std::vector<int> visited, low(_n), ord(_n, -1), ids(_n);\n        visited.reserve(_n);\n        auto dfs = [&](auto self, int v) -> void {\n            low[v] = ord[v] = now_ord++;\n            visited.push_back(v);\n            for (int i = g.start[v]; i < g.start[v + 1]; i++) {\n                auto to = g.elist[i].to;\n                if (ord[to] == -1) {\n                    self(self, to);\n                    low[v] = std::min(low[v], low[to]);\n                } else {\n                    low[v] = std::min(low[v], ord[to]);\n                }\n            }\n            if (low[v] == ord[v]) {\n                while (true) {\n                    int u = visited.back();\n                    visited.pop_back();\n                    ord[u] = _n;\n                    ids[u] = group_num;\n                    if (u == v) break;\n                }\n                group_num++;\n            }\n        };\n        for (int i = 0; i < _n; i++) {\n            if (ord[i] == -1) dfs(dfs, i);\n        }\n        for (auto& x : ids) {\n            x = group_num - 1 - x;\n        }\n        return {group_num, ids};\n    }\n \n    std::vector<std::vector<int>> scc() {\n        auto ids = scc_ids();\n        int group_num = ids.first;\n        std::vector<int> counts(group_num);\n        for (auto x : ids.second) counts[x]++;\n        std::vector<std::vector<int>> groups(ids.first);\n        for (int i = 0; i < group_num; i++) {\n            groups[i].reserve(counts[i]);\n        }\n        for (int i = 0; i < _n; i++) {\n            groups[ids.second[i]].push_back(i);\n        }\n        return groups;\n    }\n \n  private:\n    int _n;\n    struct edge {\n        int to;\n    };\n    std::vector<std::pair<int, edge>> edges;\n};\n \n}  // namespace internal\n \n}  // namespace atcoder\n \n#include <cassert>\n#include <vector>\n \nnamespace atcoder {\n \n// Reference:\n// B. Aspvall, M. Plass, and R. Tarjan,\n// A Linear-Time Algorithm for Testing the Truth of Certain Quantified Boolean\n// Formulas\nstruct two_sat {\n  public:\n    two_sat() : _n(0), scc(0) {}\n    two_sat(int n) : _n(n), _answer(n), scc(2 * n) {}\n \n    void add_clause(int i, bool f, int j, bool g) {\n        assert(0 <= i && i < _n);\n        assert(0 <= j && j < _n);\n        scc.add_edge(2 * i + (f ? 0 : 1), 2 * j + (g ? 1 : 0));\n        scc.add_edge(2 * j + (g ? 0 : 1), 2 * i + (f ? 1 : 0));\n    }\n    bool satisfiable() {\n        auto id = scc.scc_ids().second;\n        for (int i = 0; i < _n; i++) {\n            if (id[2 * i] == id[2 * i + 1]) return false;\n            _answer[i] = id[2 * i] < id[2 * i + 1];\n        }\n        return true;\n    }\n    std::vector<bool> answer() { return _answer; }\n \n  private:\n    int _n;\n    std::vector<bool> _answer;\n    internal::scc_graph scc;\n};\n \n}  // namespace atcoder\n \n \nusing namespace std;\nusing namespace atcoder;\n \nvoid solve() {\n\tint n;\n\tcin >> n;\n\tint b[3][n];\n\tfor (int i = 0; i < 3; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tcin >> b[i][j];\n\t\t}\n\t}\n\ttwo_sat ts(n);\n\tfor (int j = 0; j < n; j++) {\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tint nxt = (i + 1) % 3;\n\t\t\tts.add_clause(abs(b[i][j]) - 1, b[i][j] > 0, abs(b[nxt][j]) - 1, b[nxt][j] > 0);\n\t\t}\n\t}\n\tcout << (ts.satisfiable() ? \"YES\\n\" : \"NO\\n\");\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}\n",
    "tags": [
      "2-sat",
      "dfs and similar",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1972",
    "index": "A",
    "title": "Contest Proposal",
    "statement": "A contest contains $n$ problems and the difficulty of the $i$-th problem is expected to be \\textbf{at most} $b_i$. There are already $n$ problem proposals and the difficulty of the $i$-th problem is $a_i$. Initially, both $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_n$ are sorted in non-decreasing order.\n\nSome of the problems may be more difficult than expected, so the writers must propose more problems. When a new problem with difficulty $w$ is proposed, the most difficult problem will be deleted from the contest, and the problems will be sorted in a way that the difficulties are non-decreasing.\n\nIn other words, in each operation, you choose an integer $w$, insert it into the array $a$, sort array $a$ in non-decreasing order, and remove the last element from it.\n\nFind the minimum number of new problems to make $a_i\\le b_i$ for all $i$.",
    "tutorial": "Enumerate through the array $a$, if $a_i > b_i$ at some index $i$, then propose a problem with difficulty $b_i$. Time complexity: $\\mathcal O(n^2)$ for each test case. It can also be solved in $\\mathcal O(n)$ if we record the problems we've added.",
    "code": "//By: OIer rui_er\n#include <bits/stdc++.h>\n#define rep(x, y, z) for(int x = (y); x <= (z); ++x)\n#define per(x, y, z) for(int x = (y); x >= (z); --x)\n#define endl '\\n'\nusing namespace std;\ntypedef long long ll;\n \nconst int N = 105;\n \nint T, n, a[N], b[N];\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); cout.tie(0);\n    for(cin >> T; T; --T) {\n        cin >> n;\n        rep(i, 1, n) cin >> a[i];\n        rep(i, 1, n) cin >> b[i];\n        int diff = 0, ans = 0;\n        rep(i, 1, n) {\n            if(a[i - diff] > b[i]) {\n                ++ans;\n                ++diff;\n            }\n        }\n        cout << ans << endl;\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "1972",
    "index": "B",
    "title": "Coin Games",
    "statement": "There are $n$ coins on the table forming a circle, and each coin is either facing up or facing down. Alice and Bob take turns to play the following game, and Alice goes first.\n\nIn each operation, the player chooses a facing-up coin, removes the coin, and flips the two coins that are adjacent to it. If (before the operation) there are only two coins left, then one will be removed and the other won't be flipped (as it would be flipped twice). If (before the operation) there is only one coin left, no coins will be flipped. If (before the operation) there are no facing-up coins, the player loses.\n\nDecide who will win the game if they both play optimally. It can be proved that the game will end in a finite number of operations, and one of them will win.",
    "tutorial": "It can be proved that Alice will win the game if and only if the number of facing-up coins is odd. Time complexity: $\\mathcal O(n)$ for each case. Proof: Consider all possible operations: ...UUU... -> ...DD...: The number of U decreases by $3$. ...UUD... -> ...DU...: The number of U decreases by $1$. ...DUU... -> ...UD...: The number of U decreases by $1$. ...DUD... -> ...UU...: The number of U increases by $1$. It can be seen that the parity always changes. It's obvious that if the number of U is equal to $0$, the player loses because there aren't any available operations. So Alice wins if and only if the number of U is odd.",
    "code": "//By: OIer rui_er\n#include <bits/stdc++.h>\n#define rep(x, y, z) for(int x = (y); x <= (z); ++x)\n#define per(x, y, z) for(int x = (y); x >= (z); --x)\n#define endl '\\n'\nusing namespace std;\ntypedef long long ll;\n \nint T, n;\nstring s;\n \nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0); cout.tie(0);\n    for(cin >> T; T; --T) {\n        cin >> n >> s;\n        int cntU = 0;\n        for(char c : s) if(c == 'U') ++cntU;\n        if(cntU & 1) cout << \"YES\" << endl;\n        else cout << \"NO\" << endl;\n    }\n    return 0;\n}",
    "tags": [
      "games"
    ],
    "rating": 900
  },
  {
    "contest_id": "1973",
    "index": "A",
    "title": "Chess For Three",
    "statement": "Three friends gathered to play a few games of chess together.\n\nIn every game, two of them play against each other. The winner gets $2$ points while the loser gets $0$, and in case of a draw, both players get $1$ point each. Note that the same pair of players could have played any non-negative number of times (possibly zero). It is also possible that no games were played at all.\n\nYou've been told that their scores after all the games were played were $p_1$, $p_2$ and $p_3$. Additionally, it is guaranteed that $p_1 \\leq p_2 \\leq p_3$ holds.\n\nFind the maximum number of draws that could have happened and print it. If there isn't any way to obtain $p_1$, $p_2$ and $p_3$ as a result of a non-negative number of games between the three players, print $-1$ instead.",
    "tutorial": "If someone would claim that the number of draws that happened between the three players are $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$, can you check in $O(1)$ whether this can be true? The constraints are very small. The number of draws between any two players is at most $30$. Hint 3: Try all the possibilities for $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$ and find the one with the biggest sum out of all possibilities that could've been the result of game that ended with scores $p_1$, $p_2$ and $p_3$. After each round, sum of players' scores increases by 2, so if the sum $p_1 + p_2 + p_3$ is odd, answer is $-1$. Now, as the hints suggest, you can try all possible combinations of $d_{1, 2}$, $d_{1, 3}$ and $d_{2, 3}$ with three for-loops and check for each combination whether it could result in scores $p_1$, $p_2$ and $p_3$. Specifically, it must hold that $p_1 - d_{1, 2} - d_{1, 3} \\equiv 0 \\mod 2$, $d_{1, 2} + d_{1, 3} \\leq p_1$ and the same two conditions for $p_2$ and $p_3$ analogously. Now you can find the biggest value of $d_{1, 2}$ + $d_{1, 3}$ + $d_{2, 3}$ over all valid choices and print it as the answer. The time complexity is $O(t \\cdot \\max(p) ^3)$.",
    "code": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <deque>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <string>\n#include <vector>\ntypedef long long ll;\ntypedef long double ld;\nusing namespace std;\n \nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        vector<int> v(3);\n        cin >> v[0] >> v[1] >> v[2];\n        if ((v[0] + v[1] + v[2]) % 2 == 1)\n        {\n            cout << \"-1\\n\";\n            continue;\n        }\n        cout << (v[0] + v[1] + v[2] - max(0, v[2] - v[0] - v[1])) / 2 << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1973",
    "index": "B",
    "title": "Cat, Fox and the Lonely Array",
    "statement": "Today, Cat and Fox found an array $a$ consisting of $n$ non-negative integers.\n\nDefine the loneliness of $a$ as the \\textbf{smallest} positive integer $k$ ($1 \\le k \\le n$) such that for any two positive integers $i$ and $j$ ($1 \\leq i, j \\leq n - k +1$), the following holds: $$a_i | a_{i+1} | \\ldots | a_{i+k-1} = a_j | a_{j+1} | \\ldots | a_{j+k-1},$$ where $x | y$ denotes the bitwise OR of $x$ and $y$. In other words, for every $k$ consecutive elements, their bitwise OR should be the same. Note that the loneliness of $a$ is well-defined, because for $k = n$ the condition is satisfied.\n\nCat and Fox want to know how lonely the array $a$ is. Help them calculate the loneliness of the found array.",
    "tutorial": "We will say that the array is $k$-lonely if $a_i|a_{i+1}| \\ldots |a_{i+k-1}=a_j|a_{j+1}| \\ldots |a_{j+k-1}$ is true for any two positive integers $1 \\leq i,j \\leq n-k+1$. Let $A$ be the maximum value an element in array $a$ can have. how to check if the array is $k$-lonely in $O(n \\log A)$? if the array is $k$-lonely, the array is also $k+1$-lonely binary search the answer :) If the array is $k$-lonely, then since $a_i | \\ldots | a_{i+k} = (a_i | \\ldots | a_{i+k-1}) | (a_{i+1} | \\ldots | a_{i+k}) = (a_j | \\ldots | a_{j+k-1}) | (a_{j+1} | \\ldots | a_{j+k}) = a_j | \\ldots | a_{j+k}$, the array is also $k+1$-lonely. You can check whether an array is $k$-lonely in $O(n \\log A)$ by calculating the OR of every segment of length $k$. You can do this by iterating $i$ from $1$ to $n-k+1$ and mantaining an array $t$ of size $\\log n$ where $t[j]$ will be equal to the number of elements from $a_i, ..., a_{i+k-1}$ that have the bit $2^j$ set. For $i = 1$ we can calculate this array in $O (k \\log A)$ and then when moving $i$ to the right, we can update the array in $O (\\log A)$ complexity and we can also calculate the OR of all elements in the segment, using the array $t$, in $O (\\log A)$. Once you have a checking function that runs in $O (n \\log A)$, you can binary search the answer in $O(n \\log A \\log n)$ time, which is fast enough to pass.",
    "code": " \n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <string>\nusing namespace std;\nbool check(vector<int>& v, int mid,int ori)\n{\n    vector<int>frekbit(31);\n    for (int i = 0; i < mid; i++)\n    {\n        int x = v[i];\n \n        for (int j = 30; j >= 0; j--)\n        {\n            if (x>=(1<<j))\n            {\n                x -= (1<<j);\n                frekbit[j]++;\n            }\n        }\n    }\n    int or2 = 0;\n    for (int i = 0; i < frekbit.size(); i++)\n    {\n        if (frekbit[i] > 0)\n        {\n            or2 += (1 << i);\n        }\n    }\n    if (or2 != ori)\n    {\n        return false;\n    }\n    for (int i = 1; i + mid - 1 < v.size(); i++)\n    {\n        int x = v[i - 1];\n        for (int j = 30; j >= 0; j--)\n        {\n            if (x >= (1 << j))\n            {\n                x -= (1 << j);\n                frekbit[j]--;\n                if (frekbit[j] == 0)\n                {\n                    or2 -= (1 << j);\n                }\n            }\n        }\n        x = v[i+mid - 1];\n        for (int j = 30; j >= 0; j--)\n        {\n            if (x >= (1 << j))\n            {\n                x -= (1 << j);\n                frekbit[j]++;\n                if (frekbit[j] == 1)\n                {\n                    or2 += (1 << j);\n                }\n            }\n        }\n        if (or2 != ori)\n        {\n            return false;\n        }\n    }\n    return true;\n \n}\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        int n;\n        cin >> n;\n        vector<int>v(n);\n        int ori = 0;\n        for (int i = 0; i < n; i++)\n        {\n            cin >> v[i];\n            ori |= v[i];\n        }\n        int lo = 1;\n        int hi = n;\n        while (lo < hi)\n        {\n            int mid = (lo+hi) / 2;\n            if (check(v,mid,ori) == true)\n            {\n                hi = mid;\n            }\n            else\n            {\n                lo = mid + 1;\n            }\n        }\n        cout << lo << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1973",
    "index": "C",
    "title": "Cat, Fox and Double Maximum",
    "statement": "Fox loves permutations! She came up with the following problem and asked Cat to solve it:\n\nYou are given an \\textbf{even} positive integer $n$ and a permutation$^\\dagger$ $p$ of length $n$.\n\nThe score of another permutation $q$ of length $n$ is the number of \\textbf{local maximums} in the array $a$ of length $n$, where $a_i = p_i + q_i$ for all $i$ ($1 \\le i \\le n$). In other words, the score of $q$ is the number of $i$ such that $1 < i < n$ (note the \\textbf{strict} inequalities), $a_{i-1} < a_i$, and $a_i > a_{i+1}$ (once again, note the strict inequalities).\n\nFind the permutation $q$ that achieves the maximum score for given $n$ and $p$. If there exist multiple such permutations, you can pick any of them.\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "$n$ is even. What is the obvious upper bound on the number of the local maximums? Right, it is ${n \\over 2} - 1$. We can actually achieve this value for any permutation. Consider $p_1 = n$. Can you find $q$ such that all other odd positions will be local maximums? We can easily prove that the sequence can have at most ${n \\over 2} - 1$ local maximums, because the corner elements can't be the local maximums and no two consecutive elements can be local maximums. Let's see how we can achieve this upper bound. Let's consider the case when $n$ is at odd position in the original array first. We will construct a permutation $q$ such that the resulting array $a$ will have local maximums at all the odd positions except the first one. We can do this by placing the numbers ${n \\over 2} + 1, {n \\over 2} + 2, \\ldots n$ at the odd indexes in $q$, giving the bigger numbers to the indexes with smaller $p_i$, and placing the numbers $1, 2, \\ldots, {n \\over 2}$ at the even indexes in $p$, giving the smaller numbers to the indexes with bigger $p_i$. Then since $n$ belongs to an odd index, the $a_i$ for each odd $i$ will be at least $n + 1$ while the $a_i$ for each even $i$ will be at most $n$. So every element of $a$ at odd position, except for the corner, will be a local maximum. This means we will have ${n \\over 2} - 1$ local maximums, which is optimal, as we noitced above. We can get the solution for the case when $n$ is at even position analogously. For example, by reversing the permutation $p$, calculating the right permutation $q$, reversing them again and printing this $q$ as the answer. Time complexity: $O(n \\log n)$ because of sorting. Actually, since you are sorting a permutation, you can do it in just $O(n)$ but it's not necessary.",
    "code": "#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <string>\n#include <vector>\ntypedef long long ll;\ntypedef long double ld;\nusing namespace std;\n \nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        int n;\n        cin >> n;\n        vector<int> p(n);\n        for (int i = 0; i < n; i++) cin >> p[i];\n        vector<int> q(n);\n        int nid = find(p.begin(), p.end(), n) - p.begin();\n        if (!(nid & 1)) // maximums will be on the even positions\n        {\n            vector<pair<int, int> > v;\n            for (int i = 1; i < n; i += 2) v.push_back({ p[i], i });\n            v.push_back({ p[0], 0 });\n            for (int i = 2; i < n; i += 2) v.push_back({ p[i], i });\n            sort(v.begin(), v.begin() + (n / 2), greater<pair<int, int> >());\n            sort(v.begin() + (n / 2) + 1, v.begin() + n, greater<pair<int, int> >());\n            for (int i = 0; i < n; i++) q[v[i].second] = i + 1;\n        }\n        else // maximums will be on the odd positions\n        {\n            vector<pair<int, int> > v;\n            for (int i = 0; i < n; i += 2) v.push_back({ p[i], i });\n            v.push_back({ p[n - 1], n - 1 });\n            for (int i = 1; i < n - 1; i += 2) v.push_back({ p[i], i });\n            sort(v.begin(), v.begin() + (n / 2), greater<pair<int, int> >());\n            sort(v.begin() + (n / 2) + 1, v.begin() + n, greater<pair<int, int> >());\n            for (int i = 0; i < n; i++) q[v[i].second] = i + 1;\n        }\n        for (int i = 0; i < n; i++) cout << q[i] << \" \\n\"[i == n - 1];\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1973",
    "index": "D",
    "title": "Cat, Fox and Maximum Array Split",
    "statement": "This is an interactive problem.\n\nFox gave Cat two positive integers $n$ and $k$. She has a hidden array $a_1, \\ldots , a_n$ of length $n$, such that $1 \\leq a_i \\leq n$ for every $i$. Now they are going to play the following game:\n\nFor any two integers $l, r$ such that $1 \\leq l \\leq r \\leq n$, define $f(l, r) = (r - l + 1) \\cdot \\max\\limits_{x=l}^r a_x$. In other words, $f(l, r)$ is equal to the maximum of the subarray $a_l, \\ldots, a_r$ multiplied by its size.\n\nCat can ask Fox at most $2 n$ questions about the array. He will tell her two integers $l$ and $x$ ($1 \\leq l \\leq n, 1 \\leq x \\leq 10^9$), and she will tell him one integer $p$ as the answer — the smallest positive integer $r$ such that $f(l, r) = x$, or $n+1$ if no such $r$ exists.\n\nNow, Cat needs to find the largest value $m$ such that there exists a sequence $c_1, \\ldots, c_{k-1}$ such that $1 \\leq c_1 < \\ldots < c_{k-1} < n$ and $f(1, c_1) = f(c_1 + 1, c_2) = \\ldots = f(c_{k-1}+1, n) = m$. If no such $m$ exists, he should indicate this and take $-1$ as the answer. Note that for $k = 1$, $m$ is always equal to $f(1, n)$.\n\nIn other words, the goal is to find the largest $m$ such that you can split the array into exactly $k$ subarrays ($k$ is the constant given to you in the beginning of the interaction) so that all the subarrays have the product of their length and their maximum equal to $m$, or determine that no such $m$ exists. Every element should belong in exactly one of the subarrays.\n\nCat doesn't know what he should do, so he asked you to play the game for him.",
    "tutorial": "Let $m$ be value we want to find. What values can $m$ take? Look at the maximum value in array $a$. Can you find the maximum value in array? Think about the segment containing the maximum value. Can you finish the problem in $n$ queries? Let's denote maximum value in array $a$ as $mx$. Since the element with maximum value will belong to some segment, then if $m$ exists, $m$ will be divisible by $mx$. Obviously, $m$ can't be greater than $n \\cdot mx$, so now the candidates for value of $m$ are $mx, 2 \\cdot mx, 3 \\cdot mx, \\dots, n \\cdot mx$. To find the value of $mx$ we can query $?$ $1$ $n \\cdot i$ for each $1\\leq i \\leq n$ and $mx$ will be equal to such $i$, querying which will give $n$ as the answer. We can check each of $n$ possible values in $k$ queries, but that wouldn't fit in query limit. Actually, since the length of each segment in partition will be greater than or equal to $\\frac{m}{mx}$, and there are exactly $k$ segments, we can get a simple inequality $k \\cdot \\frac{m}{mx} \\leq n$ (since sum of lengths of segments is exactly $n$), which means $m$ can not be greater than $mx \\cdot \\lfloor{n/k}\\rfloor$, so it is enough to check first $\\lfloor{n/k}\\rfloor$ candidates for $m$ in $k$ queries each. Total number of queries used would be $n + k \\cdot \\lfloor{n/k}\\rfloor$ which doesn't exceed $2n$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#pragma GCC optimize(\"O3\")\n#pragma GCC target(\"popcnt\")\nusing ll = long long;\n#define int long long\n#define forn(i,n) for(int i=0; i<(n); ++i)\n#define pb push_back\n#define pi pair<int,int>\n#define f first\n#define s second \n#define vii(a,n) vector<int> a(n); forn(i,n) cin>>a[i];\n#define all(x) x.begin(), x.end()\n#define rall(x) x.rbegin(), x.rend()\n \nconst ll inf = 1e18;\nconst ll mod = 1e9+7;//998244353;\n \nvoid answer(int x) {\n    cout<<\"! \"<<x<<'\\n'; cout.flush(); cin>>x;\n}\n \nvoid solve() {\n \n    int n,k; cin>>n>>k;\n    int mx=0;\n    for(int i=1; i<=n; ++i) {\n        cout<<\"? 1 \"<<i*n<<'\\n'; cout.flush();\n        int x; cin>>x;\n        if (x==n) {\n            mx=i; break;\n        }\n    }\n    for(int c=mx*(n/k); ; c-=mx) {\n        if (!c) {\n            answer(-1); return;\n        }\n        int l=0;\n        int bad=0;\n        forn(it,k) {\n            if (l>=n) {bad=1; break;}\n            cout<<\"? \"<<l+1<<' '<<c<<'\\n'; cout.flush();\n            int x; cin>>x;\n            l=x;\n        }\n        if (bad) continue;\n        if (l!=n) continue;\n        answer(c); return;\n    }\n \n}\n \nint32_t main() {\n    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int t=1; \n    cin>>t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "brute force",
      "interactive",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1973",
    "index": "E",
    "title": "Cat, Fox and Swaps ",
    "statement": "Fox has found an array $p_1, p_2, \\ldots, p_n$, that is a permutation of length $n^\\dagger$ of the numbers $1, 2, \\ldots, n$. She wants to sort the elements in increasing order. Cat wants to help her — he is able to swap any two numbers $x$ and $y$ in the array, but only if $l \\leq x + y \\leq r$ (note that the constraint is imposed on the values of the elements, not their positions). He can make such swaps any number of times.\n\nThey don't know the numbers $l$, $r$ yet, they only know that it's true that $1 \\leq l \\leq r \\leq 2 \\cdot n$.\n\nYou are given the number $n$ and the array $p_1, p_2, \\ldots, p_n$. Determine how many pairs $(l, r)$ satisfying the conditions are there such that you can sort the permutation if you can only swap two number $(x, y)$ such that $l \\leq x + y \\leq r$ (arbitrary number of times, possibly $0$).\n\n$^\\dagger$ A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Forget about graphs and data structures, there exists a simple $O(n)$ solution. Find the number of pairs with $l = r$ for which you can sort the permutation. Okay now that you have the special case handled, let's proceed to the general case. Find the minimum and maximum number that need to be swapped. Write down the inequalities that $l$ and $r$ have to satisfy so that we can swap these two elements with some other elements. This is the obvious necessary condition, right? Right, so if $l \\neq r$ and additionally, $l$ and $r$ satisfy the inequalities mentioned above, is it enough? Yes, it is enough. But you can try to find the proof too :) Let's consider the pairs $l, r$ that have $l = r$ first. Then you can swap each $x$ with at most one other element, $l - x$. So if $i \\neq p_i$ for some $i$, then we need to be able to swap the element $i$ with the element $p_i$, so it must hold that $l = i + p_i$. This is obviously also a sufficient condition, so it's enough to just find all $i + p_i$ for $i \\neq p_i$, if there exist more then one different value, there's no good pair with $l = r$, if there's exactly one different value, there's exactly one good pair with $l = r$ and otherwise there are $2 n$ such pairs. Now let's count the pairs with $l \\neq r$. If the array is sorted already, all pairs of $l, r$ are good. From now, consider only the case when the array isn't sorted yet. Let $L$ be the smallest value such that $p_L \\neq L$ and $R$ the largest such value respectively. We obviously need to be able to swap $L$ and $R$ with some other values. Note that $L \\neq n$ and $R \\neq 1$, otherwise the array would be sorted already. Now we can get the inequalities $l \\leq L + n$ and $R + 1 \\leq r$, those are the necessary conditions for being able to swap the numbers $L, R$ with at least one other element. We can actually prove that these are the sufficient conditions too. If $l, r$ satisfy these conditions, then for any number $X$ in the range $[L, R-1]$, we can find an $x$ in the range $[l, r]$ such that $1 \\leq x - X \\leq n$ and then we can swap the numbers $X$ and $X + 1$, while not affecting any other element, by swapping $X$ and $x - X$ first and then swapping $X + 1$ and $x - X$. Thanks to this, we can sort the whole range of values between $L$ and $R$ - while the array isn't sorted, we will always find the smallest index $i$ that doesn't have the right value and keep swapping the value $p_i$ with the value $p_i - 1$, so eventually we will get $p_i = i$ and we can continue sorting on the right. So it's enough to just count the number of pairs $l, r$ such that $l \\neq r$, $l \\leq L + n$ and $R + 1 \\leq r$, add it to the answer and print it. All of this can be done in time and memory complexity $O(n)$.",
    "code": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <deque>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <string>\n#include <vector>\ntypedef long long ll;\ntypedef long double ld;\nusing namespace std;\n \nll all(ll n)\n{\n    if (n <= 0) return 0;\n    return (n * (n - 1)) / 2ll;\n}\nvoid solve()\n{\n    int n;\n    cin >> n;\n    vector<ll> p(n);\n    for (int i = 0; i < n; i++) cin >> p[i];\n    set<int> s;\n    for (int i = 0; i < n; i++) if (i != p[i] - 1) s.insert(p[i] + i);\n    if (s.empty())\n    {\n        cout << all(2 * n + 1) << \"\\n\";\n        return;\n    }\n    ll ans = (s.size() == 1);\n    ll l = 0, r = 2 * n;\n    for (int i = 0; i < n; i++) if (i != p[i] - 1)\n    {\n        l = max(l, p[i] + 1);\n        r = min(r, p[i] + n);\n    }\n    ans += all(2ll * n) - all(l - 1) - all(2ll * n - r);\n    cout << ans << \"\\n\";\n}\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "graphs",
      "math",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1973",
    "index": "F",
    "title": "Maximum GCD Sum Queries",
    "statement": "For $k$ positive integers $x_1, x_2, \\ldots, x_k$, the value $\\gcd(x_1, x_2, \\ldots, x_k)$ is the greatest common divisor of the integers $x_1, x_2, \\ldots, x_k$ — the largest integer $z$ such that all the integers $x_1, x_2, \\ldots, x_k$ are divisible by $z$.\n\nYou are given three arrays $a_1, a_2, \\ldots, a_n$, $b_1, b_2, \\ldots, b_n$ and $c_1, c_2, \\ldots, c_n$ of length $n$, containing positive integers.\n\nYou also have a machine that allows you to swap $a_i$ and $b_i$ for any $i$ ($1 \\le i \\le n$). Each swap costs you $c_i$ coins.\n\nFind the maximum possible value of $$\\gcd(a_1, a_2, \\ldots, a_n) + \\gcd(b_1, b_2, \\ldots, b_n)$$ that you can get by paying in total at most $d$ coins for swapping some elements. The amount of coins you have changes a lot, so find the answer to this question for each of the $q$ possible values $d_1, d_2, \\ldots, d_q$.",
    "tutorial": "What are the possible pairs of $\\gcd$'s of the two arrays we can have after some swaps? For every pair $(X, Y)$ such that $X$ divides $a_1$ and $Y$ divides $b_1$, let's calculate the total number of indices $i$ such that we can have $X | a_i$ and $Y | b_i$ (either with or without the swap), and the minimum cost of swaps to achieve this. This is all we need to solve the problem, right? Write for each $i$ the conditions that the pair $(X, Y)$ has to satisfy in order to add $i$ to the result/make swap on the position $i$. Use something like SOS-DP to add up all the values efficiently. Let $k$ be the maximum value of $a_i$, $b_i$ on input ($10^8$). Let $D(k)$ be the maximum number of divisors a number in range $[1, \\ldots, k]$ can have and $P(k)$ the maximum number of prime divisors such number can have. Let's think about how to solve one query (with $M$ coins) for now. Assume that in the optimal solution, we never swap $a_1$ and $b_1$. In the end, we will just run the same solution on input where $a_1$ and $b_1$ is swapped and $M$ is decreased by $c_1$, and then we will take the maximum of the two values these two runs will find. So now, in the optimal solution, the gcd of $a$ is always a divisor of $a_1$, and the $\\gcd$ of $b$ is a divisor of $b_1$. Let's start by factorizing the two numbers in $O(\\sqrt k)$. Now we will precalculate something in order to be efficiently able to determine for every $X$, a divisor of $a$, and $Y$, a divisor of $b_1$, whether we can have $\\gcd(a_1, \\ldots, a_n) = X$ and $gcd(b_1, ..., b_n) = Y$ simultaneously (and also the minimum cost of making it so). Then we can obviously answer the query by finding the best pair with sum at most $M$. Let's create new two dimensional arrays $P$ and $S$ of size $D(a_1) \\times D(b_1)$. We will use $P$ to be able to tell the number of indexes $i$ such that we have either $X | a_i$ and $Y | b_i$ or $X | b_i$ and $Y | a_i$. If this count won't be $n$, then obviously we can't have $X$ and $Y$ as $\\gcd$'s of $a$ and $b$. Also, we will use $S$ to tell us the sum of costs of all swaps we need to perform to have $X | \\gcd(a_1, \\ldots, a_n)$ and $Y | \\gcd(b_1, ..., b_n)$. Now how to make two such arrays efficiently? It is obvious that if the pair of $\\gcd$ s $(X, Y)$ is consistent with some indexes in the original array, then for every pair $(x, y)$ such that $x|X$ and $y|Y$, this pair of $\\gcd$s is also consistent with those indexes (and maybe even more, also maybe some swaps just became unnecessary, but the point is, it doesn't get worse). So if we want to add some value to a pair, we also want to get it added to all its divisors. That's why, in order to calculate the arrays efficiently, we will first add some values on some positions and then do something like $2D$ prefix sums - for every cell $(x, y)$ we will sum the values for all pairs $(X, Y)$ such that $x | X$ and $y | Y$ and update its current value with it. Assuming this is going to happen in the end, let's look at every $i$ and consider what pairs are \"good\" for this index - with or without the swap: a) If $X$ divides $a_i$ and $Y$ divides $b_i$: For this type of pairs, we don't need to make any swaps on this index. Let's add $1$ to $P[\\gcd(a_1, a_i)][\\gcd(b_1, b_i)]$ to indicate that for all $(X, Y)$ such that $X|a_i$ and $Y|b_i$, we don't have to perform any swaps at the position $i$, the index is good as it is. b) $X$ divides $b_i$ and $Y$ divides $a_i$: In this case we will add $1$ to $P[\\gcd(a_1, b_i)][\\gcd(b_1, a_i])]$ and $c_i$ to $S[\\gcd(a_1, b_i)][\\gcd(b_1, a_i)]$ to indicate that if we pick $X$, $Y$ such that $X|b_i$ and $Y|a_i$, we can make index $i$ good if we swap $a_i$ and $b_i$. c) $X$ and $Y$ both divide both $a_i$ and $b_i$: To avoid counting both of the previous cases and therefore overcounting, we will add $-1$ to $P[\\gcd(a_1, a_i, b_i)][\\gcd(b_1, a_i, b_i)]$ and $-c_i$ to $S[\\gcd(a_1, a_i, b_i)][\\gcd(b_1, a_i, b_i)]$ (we have to undo paying for the swap since in this case we actually don't have to pay for it, but it falls under the case b) too). This step can be done in $O(n \\log k)$. Now let's fix the arrays $P$ and $S$ so they store the actual values, not just the values we need to add. We will go through all primes $p$ dividing $a_1$ and update $P[X][Y]$ with $P[p \\cdot X][Y]$ and $S[X][Y]$ with $S[p \\cdot X][Y]$, similarly for all primes dividing $b_1$. If we make those updates in the right order, we achieve that $P[x][y]$ is the sum of all original values $P[X][Y]$ for all the pairs $(X, Y)$ such that $x|X$ and $y|Y$ like we wanted (and we can do the same for $S$). By careful precalculation of divisors and their order while factorizing, we can do this step in $O(D(k)^2 P(k))$. Some efficient implementations with extra log might pass also, but you will have to be more careful. For multiple queries, after precalculating the possible sums of $\\gcd$ s and their costs, you can sort them and use binary search to answer the queries. Time complexity: $O(n \\log k + \\sqrt k + D(k)^2 P(k) + D(k)^2 \\log D(k) + q \\log D(k))$ Memory complexity: $O(n + D(k)^2 + P(k))$",
    "code": "// O(n log k + sqrt(k) * log(k) + d(k)^2 * p(k)) solution, model solution for the harder version\n \n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <set>\n#include <vector>\ntypedef long long ll;\nusing namespace std;\n \nint gcd(int a, int b) { return b ? gcd(b, a % b) : a; }\nvoid upd(int& a, int b) { a = max(a, b); }\n \nvoid prepare(int x, vector<int>& dx, vector<int>& px, vector<int>& cx, map<int, int>& mx)\n{\n    vector<int> cntx;\n    for (int i = 2; i * i <= x; i++) if (x % i == 0)\n    {\n        px.push_back(i), cntx.push_back(0);\n        while (x % i == 0) cntx.back()++, x /= i;\n    }\n    if (x > 1) px.push_back(x), cntx.push_back(1);\n    dx.push_back(1);\n    for (int i = 0; i < px.size(); i++)\n    {\n        cx.push_back(dx.size());\n        for (int j = 0; j < cx.back() * cntx[i]; j++) dx.push_back(dx[j] * px[i]);\n    }\n    for (int i = 0; i < dx.size(); i++) mx[dx[i]] = i;\n}\nvector<ll> solve(int n, vector<int> a, vector<int> b, vector<ll> c, vector<ll > qu)\n{\n    int k = max(*max_element(a.begin(), a.end()), *max_element(b.begin(), b.end())) + 1;\n    vector<int> g(n);\n    for (int i = 0; i < n; i++) g[i] = gcd(a[i], b[i]);\n    vector<pair<ll, int> > v;\n    vector<ll> ans;\n    for (int it = 0; it < 2; it++)\n    {\n        vector<int> da, pa, ca, db, pb, cb;\n        map<int, int> ma, mb;\n        prepare(a[0], da, pa, ca, ma), prepare(b[0], db, pb, cb, mb);\n        vector<vector<ll> > p(da.size(), vector<ll>(db.size(), 0));\n        vector<vector<ll> > d(da.size(), vector<ll>(db.size(), 0));\n        for (int i = 1; i < n; i++)\n        {\n            p[ma[gcd(a[0], a[i])]][mb[gcd(b[0], b[i])]] += 1, d[ma[gcd(a[0], a[i])]][mb[gcd(b[0], b[i])]] += 0;\n            p[ma[gcd(a[0], b[i])]][mb[gcd(b[0], a[i])]] += 1, d[ma[gcd(a[0], b[i])]][mb[gcd(b[0], a[i])]] += c[i];\n            p[ma[gcd(a[0], g[i])]][mb[gcd(b[0], g[i])]] -= 1, d[ma[gcd(a[0], g[i])]][mb[gcd(b[0], g[i])]] -= c[i];\n        }\n        for (int ia = 0; ia < ca.size(); ia++) for (int i = da.size() - 1; i >= 0; i--) if (da[i] % pa[ia] == 0) for (int j = db.size() - 1; j >= 0; j--)\n        {\n            p[i - ca[ia]][j] += p[i][j];\n            d[i - ca[ia]][j] += d[i][j];\n        }\n        for (int ib = 0; ib < cb.size(); ib++) for (int i = db.size() - 1; i >= 0; i--) if (db[i] % pb[ib] == 0) for (int j = da.size() - 1; j >= 0; j--)\n        {\n            p[j][i - cb[ib]] += p[j][i];\n            d[j][i - cb[ib]] += d[j][i];\n        }\n        for (int i = 0; i < da.size(); i++) for (int j = 0; j < db.size(); j++) if (p[i][j] >= n - 1)\n            v.push_back({ d[i][j] + (it ? c[0] : 0ll), da[i] + db[j] });\n        swap(a[0], b[0]);\n    }\n    sort(v.begin(), v.end());\n    for (int i = 1; i < v.size(); i++) v[i].second = max(v[i - 1].second, v[i].second);\n    for (ll d : qu) ans.push_back(v[lower_bound(v.begin(), v.end(), make_pair(d + 1, 0)) - v.begin() - 1].second);\n    return ans;\n}\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    int n, q;\n    cin >> n >> q;\n    vector<int> a(n), b(n);\n    vector<ll> c(n), qi(q);\n    for (int i = 0; i < n; i++) cin >> a[i];\n    for (int i = 0; i < n; i++) cin >> b[i];\n    for (int i = 0; i < n; i++) cin >> c[i];\n    for (int i = 0; i < q; i++) cin >> qi[i];\n    vector<ll> ans = solve(n, a, b, c, qi);\n    for (ll x : ans) cout << x << \" \";\n    cout << \"\\n\";\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "implementation",
      "number theory"
    ],
    "rating": 3100
  },
  {
    "contest_id": "1974",
    "index": "A",
    "title": "Phone Desktop",
    "statement": "Little Rosie has a phone with a desktop (or launcher, as it is also called). The desktop can consist of several screens. Each screen is represented as a grid of size $5 \\times 3$, i.e., five rows and three columns.\n\nThere are $x$ applications with an icon size of $1 \\times 1$ cells; such an icon occupies only one cell of the screen. There are also $y$ applications with an icon size of $2 \\times 2$ cells; such an icon occupies a \\textbf{square} of $4$ cells on the screen. Each cell of each screen can be occupied by no more than one icon.\n\nRosie wants to place the application icons on the minimum number of screens. Help her find the minimum number of screens needed.",
    "tutorial": "Note that on one screen we can put no more than two $2 \\times 2$ icons. Thus, we need at least $Z = \\lceil y / 2 \\rceil$ screens. Then, we check how many $1 \\times 1$ icons we can put on these screens: $15 \\cdot Z - 4 \\cdot y$. The $1 \\times 1$ icons left we need to put on additional screens.",
    "code": "nt = int(input())\n \nfor t in range(nt):\n    line = input()\n    x, y = [int(q) for q in line.split()]\n    mm = (y + 1) // 2\n    x -= (mm * 5 * 3 - y * 2 * 2)\n    x = max(x, 0)\n    mm += (x + 5 * 3 - 1) // (5 * 3)\n    print(mm)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1974",
    "index": "B",
    "title": "Symmetric Encoding",
    "statement": "Polycarp has a string $s$, which consists of lowercase Latin letters. He encodes this string using the following algorithm:\n\n- first, he constructs a new auxiliary string $r$, which consists of all distinct letters of the string $s$, written in alphabetical order;\n- then the encoding happens as follows: each character in the string $s$ is replaced by its symmetric character from the string $r$ (the first character of the string $r$ will be replaced by the last, the second by the second from the end, and so on).\n\nFor example, encoding the string $s$=\"codeforces\" happens as follows:\n\n- the string $r$ is obtained as \"cdefors\";\n- the first character $s_1$='c' is replaced by 's';\n- the second character $s_2$='o' is replaced by 'e';\n- the third character $s_3$='d' is replaced by 'r';\n- ...\n- the last character $s_{10}$='s' is replaced by 'c'.\n\n\\begin{center}\n{\\small The string $r$ and replacements for $s$=\"codeforces\".}\n\\end{center}\n\nThus, the result of encoding the string $s$=\"codeforces\" is the string \"serofedsoc\".\n\nWrite a program that performs decoding — that is, restores the original string $s$ from the encoding result.",
    "tutorial": "Let's construct a string $r$ according to the definition from the condition: we write down all the letters from $s$ once in ascending order. After that, we just need to replace all the characters in $s$ with their symmetric characters in the string $r$. The length of string $r$ does not exceed $26$, so the position of this character can be found by linear search.",
    "code": "def solve():\n    n = int(input())\n    b = input()\n    cnt = [0] * 26\n    for c in b:\n        cnt[ord(c) - ord('a')] = 1\n    tmp = ''\n    for i in range(26):\n        if cnt[i] > 0:\n            tmp += chr(ord('a') + i)\n    a = ''\n    for c in b:\n        a += tmp[-1 - tmp.find(c)]\n    print(a)\n    \n \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1974",
    "index": "C",
    "title": "Beautiful Triple Pairs",
    "statement": "Polycarp was given an array $a$ of $n$ integers. He really likes triples of numbers, so for each $j$ ($1 \\le j \\le n - 2$) he wrote down a triple of elements $[a_j, a_{j + 1}, a_{j + 2}]$.\n\nPolycarp considers a pair of triples $b$ and $c$ beautiful if they differ in exactly one position, that is, one of the following conditions is satisfied:\n\n- $b_1 \\ne c_1$ and $b_2 = c_2$ and $b_3 = c_3$;\n- $b_1 = c_1$ and $b_2 \\ne c_2$ and $b_3 = c_3$;\n- $b_1 = c_1$ and $b_2 = c_2$ and $b_3 \\ne c_3$.\n\nFind the number of beautiful pairs of triples among the written triples $[a_j, a_{j + 1}, a_{j + 2}]$.",
    "tutorial": "To consider each pair only once, we will go from left to right and while adding a new triplet, we will add to the answer the number of already added triplets that form a beautiful pair with the current one. We will maintain a map with triplets, to denote a triplet with an error, we will place $0$ (or any other value that cannot occur in the array $a$) in place of the error. Thus, for each triplet $b$, the already found triplets $(0, b_2, b_3)$, $(b_1, 0, b_3)$, $(b_1, b_2, 0)$ will be good. In each case, triplets equal to $b$ will also be included, so they need to be subtracted from each of the three cases.",
    "code": "def solve():\n    n = int(input())\n    a = [int(x) for x in input().split()]\n    cnt = dict()\n    ans = 0\n    for i in range(n - 2):\n        triplet = (a[i], a[i + 1], a[i + 2])\n        mist = [0] * 3\n        mist[0] = (0, a[i + 1], a[i + 2])\n        mist[1] = (a[i], 0, a[i + 2])\n        mist[2] = (a[i], a[i + 1], 0)\n        for trip in mist:\n            ans += cnt.get(trip, 0) - cnt.get(triplet, 0)\n            cnt[trip] = cnt.get(trip, 0) + 1\n        cnt[triplet] = cnt.get(triplet, 0) + 1\n    print(ans)\n    \n    \nfor i in range(int(input())):\n    solve()",
    "tags": [
      "combinatorics",
      "data structures"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1974",
    "index": "D",
    "title": "Ingenuity-2",
    "statement": "Let's imagine the surface of Mars as an infinite coordinate plane. Initially, the rover Perseverance-2 and the helicopter Ingenuity-2 are located at the point with coordinates $(0, 0)$. A set of instructions $s$ consisting of $n$ instructions of the following types was specially developed for them:\n\n- N: move one meter north (from point $(x, y)$ to $(x, y + 1)$);\n- S: move one meter south (from point $(x, y)$ to $(x, y - 1)$);\n- E: move one meter east (from point $(x, y)$ to $(x + 1, y)$);\n- W: move one meter west (from point $(x, y)$ to $(x - 1, y)$).\n\nEach instruction must be executed either by the rover or by the helicopter. Moreover, each device must execute \\textbf{at least one} instruction. Your task is to distribute the instructions in such a way that after executing all $n$ instructions, the helicopter and the rover end up at the same point, or determine that this is impossible.",
    "tutorial": "For the string $S$, calculate the 2D-coordinates $(x, y)$ of the point obtained as a result of sequentially executing all instructions (for example, N decreases $y$ by 1, S increases $y$ by 1, E increases $x$ by 1, W decreases $x$ by 1). Consider the following cases: $x \\bmod 2 \\neq 0$ or $y \\bmod 2 \\neq 0$. Obviously, a solution does not exist. $x = 0, y = 0, |S| = 2$. This is one of the strings NS, SN, WE, EW. Again, in this case, it is impossible to construct a solution, as both the rover and the helicopter must execute at least 1 instruction. $x = 0, y = 0, |S| > 2$. A solution exists: assign the first instruction to the helicopter, as well as one of its complements, which exists. Assign all the remaining positive number of instructions to the rover. Both will obviously end up at $(0, 0)$. All other cases: a solution exists. Assign $|x|/2$ and $|y|/2$ instructions moving in the direction of the sign of $x$ and $y$ respectively - which definitely exist - to the helicopter, and the rest to the rover. Both subsets of instructions will be non-empty.",
    "code": "inv = {'N':'S', 'S': 'N',\n    'E': 'W', 'W': 'E'}\n\ndef solve():\n    n = int(input())\n    s = input()\n    x, y = 0, 0\n    for c in s:\n        if c == 'N':\n            y += 1\n        if c == 'S':\n            y -= 1\n        if c == 'E':\n            x += 1\n        if c == 'W':\n            x -= 1\n    if x % 2 == 1 or y % 2 == 1:\n        print('NO')\n        return\n    ans = ['R'] * n\n    if x == y == 0:\n        if n == 2:\n            print('NO')\n            return\n        ans[0] = ans[s.find(inv[s[0]])] = 'H'\n    else:\n        for i in range(n):\n            if s[i] == 'N' and y > 0:\n                y -= 2\n                ans[i] = 'H'\n            if s[i] == 'S' and y < 0:\n                y += 2\n                ans[i] = 'H'\n            if s[i] == 'E' and x > 0:\n                x -= 2\n                ans[i] = 'H'\n            if s[i] == 'W' and x < 0:\n                x += 2\n                ans[i] = 'H'\n    print(*ans, sep='')\n    \n    \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1974",
    "index": "E",
    "title": "Money Buys Happiness",
    "statement": "Being a physicist, Charlie likes to plan his life in simple and precise terms.\n\nFor the next $m$ months, starting with no money, Charlie will work hard and earn $x$ pounds per month. For the $i$-th month $(1 \\le i \\le m)$, there'll be a single opportunity of paying cost $c_i$ pounds to obtain happiness $h_i$.\n\nBorrowing is not allowed. Money earned in the $i$-th month can only be spent in a later $j$-th month ($j>i$).\n\nSince physicists don't code, help Charlie find the maximum obtainable sum of happiness.",
    "tutorial": "Let's consider the classic knapsack problem. Let $dp[j]$ be the minimum cost required to achieve happiness $j$. In the $i$-th month, we iterate through $dp[k]$ and check if $dp[k]+c_i \\le (i-1) \\cdot x$, and if so, we can afford to transition to $dp[k+h_i]$ and accordingly update $dp[k+h_i]$. The complexity is $O(m \\cdot \\sum_i h_i)$ for each set of input data.",
    "code": "T = int(input())\nbig = float('inf')\nfor _ in range(T):\n    m, x = map(int, input().split())\n    c = []\n    h = []\n    for i in range(m):\n        ci, hi = map(int, input().split())\n        c.append(ci)\n        h.append(hi)\n    mh = sum(h)\n    dp = [0] + [big] * mh\n    for i in range(m):\n        for j in range(mh, h[i]-1, -1):\n            if dp[j-h[i]] + c[i] <= i*x:\n                dp[j] = min(dp[j], dp[j-h[i]]+c[i])\n    for i in range(mh, -1, -1):\n        if dp[i] != big:\n            print(i)\n            break",
    "tags": [
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1975",
    "index": "A",
    "title": "Bazoka and Mocha's Array",
    "statement": "Mocha likes arrays, so before her departure, Bazoka gave her an array $a$ consisting of $n$ positive integers as a gift.\n\nNow Mocha wants to know whether array $a$ could become sorted in non-decreasing order after performing the following operation some (possibly, zero) times:\n\n- Split the array into two parts — a prefix and a suffix, then swap these two parts. In other words, let $a=x+y$. Then, we can set $a:= y+x$. Here $+$ denotes the array concatenation operation.\n\nFor example, if $a=[3,1,4,1,5]$, we can choose $x=[3,1]$ and $y=[4,1,5]$, satisfying $a=x+y$. Then, we can set $a:= y + x = [4,1,5,3,1]$. We can also choose $x=[3,1,4,1,5]$ and $y=[\\,]$, satisfying $a=x+y$. Then, we can set $a := y+x = [3,1,4,1,5]$. Note that we are not allowed to choose $x=[3,1,1]$ and $y=[4,5]$, neither are we allowed to choose $x=[1,3]$ and $y=[5,1,4]$, as both these choices do not satisfy $a=x+y$.",
    "tutorial": "We can't do any insertions by the operation. If the answer is yes, we can make $a$ become non-decreasing in no more than one operation. Read the hints. If $a$ is non-decreasing initially, the answer is yes. If $a$ isn't non-decreasing initially, we can find the smallest $i$ such that $a_i> a_{i+1}$. Then we choose $x=[a_1,a_2,...,a_i]$ and $y=[a_{i+1},a_{i+2},...,a_n]$. If the array $y+x$ is non-decreasing, the answer is yes. Otherwise, the answer is no.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N = 1e5+10;\nint a[N];\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        for(int i=1;i<=n;i++){\n            cin>>a[i];\n        }\n        int pos=0;\n        for(int i=1;i<n;i++){\n            if(a[i]>a[i+1]){\n                pos=i;\n                break;\n            }\n        }\n        if(!pos)cout<<\"Yes\\n\";\n        else{\n            int fl=0;\n            for(int i=pos+1;i<=n;i++){\n                int j=(i%n)+1;\n                if(a[i]>a[j])fl=1;\n            }\n            if(!fl)cout<<\"Yes\\n\";\n            else cout<<\"No\\n\";\n        }\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1975",
    "index": "B",
    "title": "378QAQ and Mocha's Array",
    "statement": "Mocha likes arrays, so before her departure, 378QAQ gave her an array $a$ consisting of $n$ positive integers as a gift.\n\nMocha thinks that $a$ is beautiful if there exist two numbers $i$ and $j$ ($1\\leq i,j\\leq n$, $i\\neq j$) such that for all $k$ ($1 \\leq k \\leq n$), $a_k$ is divisible$^\\dagger$ by either $a_i$ or $a_j$.\n\nDetermine whether $a$ is beautiful.\n\n$^\\dagger$ $x$ is divisible by $y$ if there exists an integer $z$ such that $x = y \\cdot z$.",
    "tutorial": "How to solve the problem if we only need to find a number $i$($1\\leq i\\leq n$) such that $a_k$ is divisible by $a_i$ for all $k$($1\\leq k\\leq n$)? We only need to check whether all elements are divisible by the minimum element of the array. Read the hints. Suppose the minimum element of $a$ is $x$. Then we iterate over $a$, if an element is not divisible by $x$, then we add it to $b$ ($b$ is initially empty). If $b$ is still empty after iterating $a$, the answer is yes. If $b$ isn't empty, we check whether all elements of $b$ are divisible by the minimum element of $b$. If so, the answer is yes. Otherwise, the answer is no.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\nconst int N = 1e5+10;\nint a[N];\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int fl=0;\n        for(int i=1;i<=n;i++){\n            cin>>a[i];\n            if(a[i]==1)fl=1;\n        }\n        if(fl)cout<<\"Yes\\n\";\n        else{\n            sort(a+1,a+1+n);\n            vector<int> b;\n            for(int i=2;i<=n;i++){\n                if(a[i]%a[1])b.push_back(a[i]);\n            }\n            sort(b.begin(),b.end());\n            n = b.size();\n            for(int j=1;j<n;j++){\n                if(b[j]%b[0]){\n                    fl=1;\n                    break;\n                }\n            }\n            if(!fl)cout<<\"Yes\\n\";\n            else cout<<\"No\\n\";\n        }\n\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1975",
    "index": "C",
    "title": "Chamo and Mocha's Array",
    "statement": "Mocha likes arrays, so before her departure, Chamo gave her an array $a$ consisting of $n$ positive integers as a gift.\n\nMocha doesn't like arrays containing different numbers, so Mocha decides to use magic to change the array. Mocha can perform the following three-step operation some (possibly, zero) times:\n\n- Choose indices $l$ and $r$ ($1 \\leq l < r \\leq n$)\n- Let $x$ be the median$^\\dagger$ of the subarray $[a_l, a_{l+1},\\ldots, a_r]$\n- Set all values $a_l, a_{l+1},\\ldots, a_r$ to $x$\n\nSuppose $a=[1,2,3,4,5]$ initially:\n\n- If Mocha chooses $(l,r)=(3,4)$ in the first operation, then $x=3$, the array will be changed into $a=[1,2,3,3,5]$.\n- If Mocha chooses $(l,r)=(1,3)$ in the first operation, then $x=2$, the array will be changed into $a=[2,2,2,4,5]$.\n\nMocha will perform the operation until the array contains only the same number. Mocha wants to know what is the maximum possible value of this number.\n\n$^\\dagger$ The median in an array $b$ of length $m$ is an element that occupies position number $\\lfloor \\frac{m+1}{2} \\rfloor$ after we sort the elements in non-decreasing order. For example, the median of $[3,1,4,1,5]$ is $3$ and the median of $[5,25,20,24]$ is $20$.",
    "tutorial": "If a subarray of length at least $2$ contains only the same elements, we can change all elements of the array to that element by operations. Suppose the answer is $x$, we can perform no more than one operation on the original array $a$ so that there is a subarray of length at least $2$ that contains only $x$. If we can make all elements of a subarray become $x$ in one operation, then there must be a subarray of length $3$ with a median of $y$ ($y\\geq x$). Read the hints. If $n=2$, the answer is the minimum element. If $n\\geq 3$, we iterate over all subarrays of length $3$, and the answer is the maximum value of the median of all subarrays of length $3$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N = 1e5+10;\nint a[N];\nint main(){\n    int n,t;\n    cin>>t;\n    while(t--){\n        cin>>n;\n        for(int i=1;i<=n;i++) \n            cin>>a[i];\n        if(n==2)cout<<min(a[1],a[2])<<\"\\n\";\n        else{\n            int ans = min(a[1],a[2]);\n            for(int i=1;i<=n-2;i++){\n                vector<int> tmp;\n                for(int k=0;k<=2;k++)\n                    tmp.push_back(a[i+k]);\n                sort(tmp.begin(),tmp.end());\n                ans = max(ans,tmp[1]);\n            }\n            cout<<ans<<\"\\n\";\n        }\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1975",
    "index": "D",
    "title": "Paint the Tree",
    "statement": "378QAQ has a tree with $n$ vertices. Initially, all vertices are white.\n\nThere are two chess pieces called $P_A$ and $P_B$ on the tree. $P_A$ and $P_B$ are initially located on vertices $a$ and $b$ respectively. In one step, 378QAQ will do the following in order:\n\n- Move $P_A$ to a neighboring vertex. If the target vertex is white, this vertex will be painted red.\n- Move $P_B$ to a neighboring vertex. If the target vertex is colored in red, this vertex will be painted blue.\n\nInitially, the vertex $a$ is painted red. If $a=b$, the vertex $a$ is painted blue instead. Note that both the chess pieces \\textbf{must} be moved in each step. Two pieces can be on the same vertex at any given time.\n\n378QAQ wants to know the minimum number of steps to paint all vertices blue.",
    "tutorial": "If two pieces overlap at the beginning, can you solve the problem? Consider the first time a vertex is painted blue. After this event occurs, what happens next? Read the hints. In subsequent movements after the first time a vertex is painted blue, we can ignore the process of painting vertices red and then painting them blue. We call the first vertex painted blue $r$. Then it is not difficult to find that $P_A$ arrived at this vertex earlier than $P_B$. Considering all subsequent movements of $P_B$, $P_A$ can restore these movements one by one after reaching $r$, then $P_B$ will pass through all vertices have been painted red. If we know which vertex is $r$, this will be a classic problem, assuming the distance between the farthest vertex on the tree from $r$ and $r$ is $d$, then the answer is $2(n-1)-d$. Then we consider the strategies of $P_A$ and $P_B$ at this time. The two must be close to each other, and then until the first vertex is painted blue. If another vertex is $r$, although the value of $d$ may increase, every time the value of $d$ increases by $1$, the time when $P_A$ and $P_B$ meet will also increase by at least $1$, so the answer will not decrease.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define ll long long\nconst int N = 2e5+10;\nvector<int> g[N];\nint dep[N],f[N],mx,n,a,b;\nvoid dfs(int x,int fa){\n    dep[x]=dep[fa]+1;\n    mx = max(mx,dep[x]);\n    f[x]=fa;\n    for(auto i:g[x]){\n        if(i==fa)continue;\n        dfs(i,x);\n    }\n}\nvector<int> move(int x,int y){\n    if (dep[x] > dep[y]) swap(x, y);\n    vector<int> track,ano;\n    int tmp = dep[y] - dep[x], ans = 0;\n    track.push_back(y);\n    while(tmp--){\n        y = f[y];\n        track.push_back(y);\n    }\n    if (y == x) return track;\n    ano.push_back(x);\n    while (f[x] != f[y]) {\n        x = f[x];\n        y = f[y];\n        ano.push_back(x);\n        track.push_back(y);\n    }\n    track.push_back(f[y]);\n    reverse(ano.begin(),ano.end());\n    for(auto i:ano)track.push_back(i);\n    return track;\n}\nint main(){\n    int t;\n    cin>>t;\n    dep[0]=-1;\n    while(t--){\n        mx = -1;\n        cin>>n;\n        for(int i=1;i<=n;i++)g[i].clear();\n        cin>>a>>b;\n        for(int i=1;i<n;i++){\n            int u,v;\n            cin>>u>>v;\n            g[u].push_back(v);\n            g[v].push_back(u);\n        }\n        if(a==b){\n            dfs(a,0);\n            cout<<2*(n-1)-mx<<\"\\n\";\n            continue;\n        }\n        dfs(1,0);\n        auto tr = move(a,b);\n        int m = tr.size();\n        if(tr[0]!=a)reverse(tr.begin(),tr.end());\n        int x = tr[(m-1)/2];\n        mx = -1;\n        dfs(x,0);\n        cout<<2*(n-1)-mx+(m-1-(m-1)/2)<<\"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "greedy",
      "shortest paths",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1975",
    "index": "E",
    "title": "Chain Queries",
    "statement": "You are given a tree of $n$ vertices numbered from $1$ to $n$. Initially, all vertices are colored white or black.\n\nYou are asked to perform $q$ queries:\n\n- \"u\" — toggle the color of vertex $u$ (if it was white, change it to black and vice versa).\n\nAfter each query, you should answer whether all the black vertices form a chain. That is, there exist two black vertices such that the simple path between them passes through all the black vertices and only the black vertices. Specifically, if there is only one black vertex, they form a chain. If there are no black vertices, they do \\textbf{not} form a chain.",
    "tutorial": "Suppose the tree is a rooted tree, we only need to care about the number of black child vertices of each vertex. If the black vertices form a chain, there is no black vertex that has three or more black child vertices. And there is at most one black vertex that has two black child vertices. If the black vertices form a chain, there is at most one black vertex whose parent vertex is white. Read the hints. We can maintain the number of black vertices with $0/1/2/3+$ black child vertices in $O(1)$. When we flip the color of one vertex, only it and its parent node are affected. If the black vertices form a chain: - no black vertex that has three or more black child vertices and there is at most one black vertex that has two black child vertices. - there is at most one black vertex whose parent vertex is white. - if there is one black vertex that has two black child vertices, its parent vertex must be white.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int N = 1e6+10;\n\nint f[N];\nvector<int> g[N];\nint col[N],num[N];\nint faw,sum_two,sum_more,tot_black,xor_two;\nint n;\nvoid init(){\n    sum_two=0;\n    tot_black=0;\n    sum_more=0;\n    faw=0;\n    xor_two=0;\n    for(int i=1;i<=n;i++){\n        g[i].clear();\n        num[i]=0;\n    }\n}\n\nvoid dfs(int x,int fa){\n    f[x]=fa;\n    if(col[x]==1)tot_black++;\n    int sum=0;\n    for(auto i:g[x]){\n        if(i==fa)continue;\n        dfs(i,x);\n        if(col[i]==1)sum++;\n    }\n    if(col[fa]==0&&col[x]==1)faw++;\n    if(col[x]==1){\n        if(sum==2)sum_two++,xor_two^=x;\n        if(sum>2)sum_more++;\n    }\n    num[x]=sum;\n}\n\nvoid flip(int x){\n    col[x]^=1;\n    int d = col[x]==1?1:-1;\n    tot_black+=d;\n    if(col[f[x]]==0)faw+=d;\n    if(num[x]==2)sum_two+=d,xor_two^=x;\n    if(num[x]>2)sum_more+=d;\n    faw-=d*num[x];\n    if(col[x]==1){\n        if(col[f[x]]==1&&num[f[x]]==2)sum_two--,sum_more++,xor_two^=f[x];\n        num[f[x]]++;\n        if(col[f[x]]==1&&num[f[x]]==2)sum_two++,xor_two^=f[x];\n    }else{\n        if(col[f[x]]==1&&num[f[x]]==2)sum_two--,xor_two^=f[x];\n        num[f[x]]--;\n        if(col[f[x]]==1&&num[f[x]]==2){\n            sum_two++;\n            sum_more--;\n            xor_two^=f[x];\n        }\n    }\n}\n\nbool check(){\n    if(!tot_black)return false;\n    if(sum_more||sum_two>1)return false;\n    if(faw>1)return false;\n    if(sum_two&&col[f[xor_two]]==1)return false;\n    return true;\n}\n\nint main(){\n    int t;\n    scanf(\"%d\",&t);\n    while(t--){\n        init();\n        int q;\n        scanf(\"%d %d\",&n,&q);\n        for(int i=1;i<=n;i++) cin>>col[i];\n        for(int i=1;i<n;i++){\n            int u,v;\n            scanf(\"%d %d\",&u,&v);\n            g[u].push_back(v);\n            g[v].push_back(u);\n        }\n        dfs(1,0);\n        while(q--){\n            int x;\n            scanf(\"%d\",&x);\n            flip(x);\n            if(check()) printf(\"Yes\\n\");\n            else printf(\"No\\n\");\n        }\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "implementation",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1975",
    "index": "F",
    "title": "Set",
    "statement": "Define the binary encoding of a finite set of natural numbers $T \\subseteq \\{0,1,2,\\ldots\\}$ as $f(T) = \\sum\\limits_{i \\in T} 2^i$. For example, $f(\\{0,2\\}) = 2^0 + 2^2 = 5$ and $f(\\{\\}) = 0$. Notice that $f$ is a bijection from all such sets to all non-negative integers. As such, $f^{-1}$ is also defined.\n\nYou are given an integer $n$ along with $2^n-1$ sets $V_1,V_2,\\ldots,V_{2^n-1}$.\n\nFind all sets $S$ that satisfy the following constraint:\n\n- $S \\subseteq \\{0,1,\\ldots,n-1\\}$. Note that $S$ can be \\textbf{empty}.\n- For all \\textbf{non-empty} subsets $T \\subseteq \\{0,1,\\ldots,n-1\\}$, $|S \\cap T| \\in V_{f(T)}$.\n\nDue to the large input and output, both input and output will be given in terms of binary encodings of the sets.",
    "tutorial": "Consider enumerating each number from $0$ to $n-1$ whether it is contained by $S$, when we have enumerated the first $x$ numbers, there are only $2^{n-x}$ constraints. Read the hints. Consider enumerating each number from $0$ to $n-1$ whether it is contained by $S$. Suppose that the current enumeration reaches $i$, and in the remaining constraints, $T_1$ and $T_2$ are two sets, the only difference between them is whether they contain $i$ ($T_1$ contains $i$): $S$ contains $i$. We can merge $T_1$ and $T_2$ into a new constraint $T'$ and $v_{T'}=(v_{T_1}>>1)$&$v_{T_2}$. $S$ doesn't contain $i$. We can merge $T_1$ and $T_2$ into a new constraint $T'$ and $v_{T'}=v_{T_1}$&$v_{T_2}$. We can merge constraints quickly when the enumeration reaches a new number. And the time complexity is $O(n\\cdot 2^n)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 24, S = (1 << 20) + 5;\nint n = 0, f[N][S] = {};\nvector<int> ans;\n\ninline void dfs(int s = 0, int i = 0){\n\tif(i < n){\n\t\tint m = 1 << (n - i - 1);\n\t\tfor(int t = 0 ; t < m ; t ++) f[i + 1][t] = f[i][t] & f[i][m | t];\n\t\tdfs(s << 1, i + 1);\n\t\tfor(int t = 0 ; t < m ; t ++) f[i + 1][t] = f[i][t] & (f[i][m | t] >> 1);\n\t\tdfs(s << 1 | 1, i + 1);\n\t}\n\telse if(f[n][0] & 1) ans.push_back(s);\n}\n\nint main(){\n\tscanf(\"%d\", &n);\n\tf[0][0] = 1;\n\tfor(int s = 1 ; s < 1 << n ; s ++) scanf(\"%d\", &f[0][s]);\n\tdfs();\n\tprintf(\"%d\\n\", int(ans.size()));\n\tfor(int s : ans) printf(\"%d\\n\", s);\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dfs and similar",
      "divide and conquer",
      "dp",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1975",
    "index": "G",
    "title": "Zimpha Fan Club",
    "statement": "One day, Zimpha casually came up with a problem. As a member of \"Zimpha fan club\", you decided to solve that problem.\n\nYou are given two strings $s$ and $t$ of length $n$ and $m$, respectively. Both strings only consist of lowercase English letters, - and *.\n\nYou need to replace all occurrences of * and -, observing the following rules:\n\n- For each -, you must replace it with any lowercase English letter.\n- For each *, you must replace it with a string of any (possibly, zero) length which only consists of lowercase English letters.\n\nNote that you can replace two different instances of - with different characters. You can also replace each two different instances of * with different strings.\n\nSuppose $s$ and $t$ have been transformed into $s'$ and $t'$. Now you're wondering if there's a replacement that makes $s'=t'$.",
    "tutorial": "If $s, t$ both have $*$, or both don't have $*$, then it will be a simple problem. Can you try to solve this problem? According to the first hint, we have discussed two cases. In the remaining cases, without loss of generality, we think that only $t$ has $*$. Suppose we write $t$ as $t'_0*t'_1*t'_2* \\dots*t'_k$. Where $t'_i$ does not take $*$, assuming that $|t'_i| \\leq 50$ is satisfied for all $i$, can you solve this problem? There is a strictly subproblem of this problem, namely, given two strings $s$ and $t$ consisting only of characters from $a$ to $z$ and $-$, you need to find all positions in $s$ where $t$ can be matched. This problem has a classic solution, where $-$ is set to $0$, and $a$ to $z$ are sequentially assigned values from $1$ to $26$, and then let $f_i = \\sum_{j=1}^m [s_{i +j-1} > 0] \\times [t_j > 0] (s_{i+j-1}-t_j)^2$, then all positions of $f_i = 0$ satisfy $s[i, i + m -1]$ can match $t$. Decompose the calculation formula, $f_i = \\sum_{j=1}^m s_{i+j-1}^2+s_j^2 - 2\\sum_{j=1}^m s_{i+j -1}{t_j} - \\sum_{j=1}^m [s_{i+j-1} = 0] t_j^2 - \\sum_{j=1}^m s_{i+j-1}^ 2[t_j=0]$. For $\\sum_{j=1}^m s_{i+j-1}^2+s_j^2$, you can prefix and process it, and for the remaining part, you can use FFT in $O(n \\log n )$ to be resolved. What is the use of this solution in the original problem? Read the hints. In the following, we consider $n, m$ to be of the same order. Consider the case where $s$ and $t$ do not contain $*$. We only need to be compared bit by bit. Consider the case where $s, t$ both contain $*$, if the beginning of $s$ is not $*$ or the beginning of $t$ is not $*$: If one of the first characters of $s$ and $t$ is $*$ or the first characters can match, delete the first characters of the two strings that are not $*$. Oherwise the answer is obviously No. Performing the same operation on the last characters, it is not difficult to find that it will be reduced to two strings $*s'$ and $t'*$, where $s'$ and $t'$ are arbitrary strings. Then it is not difficult to find that $t's'$ matches two strings at the same time. Therefore, as long as the head and tail can be successfully deleted, the answer must be Yes. Consider the hardest case. Without loss of generality, we assume that only $t$ contains $*$, otherwise $s, t$ can be exchanged. We still delete the beginning and the end first. It is not difficult to find that thereafter $t$ can be written as $*t'_1*t'_2*\\dots*t'_k *$. Then we will have a greedy solution. We iterate $i$ from $1$ to $n$, find the first matching position of $t'_i$ in $s$ each time, and delete tthese matching characters and all preceding characters in $s$, that is, remove a prefix of $s$, and then until all matching is completed or no matching position is found in $s$. Assume that we use FFT to brute force solve this problem every time. See Hint.3 for the specific solution, then the complexity is $O(nk \\log n)$. But it is not difficult to find that this is very wasteful. In fact, we can do this: When matching $t'_i$, only take out the first $|2t'_i|$ characters of $s$ each time and try to match $t'_i$. Because if the match is successful, then since all positions matching $t'_i$ are deleted, it is not difficult to find that at least $|t'_i|$ characters are deleted. And if the match fails, it is not difficult to find that the first $|t'_i|$ characters of $s$ will no longer be useful and can also be deleted. Therefore we remove at least the first $|t'_i|$ characters in $s$ in complexity $O(|t'_i| \\log |t'_i|)$. Since the total length of $s$ is $n$, the total time complexity does not exceed $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nconst ll N = (1 << 22) + 5, Mod = 2013265921, G = 31;\n\ninline ll power(ll x, ll y){\n\tll ret = 1;\n\twhile(y){\n\t\tif(y & 1) ret = ret * x % Mod;\n\t\tx = x * x % Mod, y >>= 1;\n\t}\n\treturn ret;\n}\n\nll p[N] = {}, w[N] = {}, g[N] = {}, iv[N] = {};\n\ninline void dft(ll n, ll a[], bool idft){\n\tfor(ll i = 0 ; i < n ; i ++) if(i < p[i]) swap(a[i], a[p[i]]);\n\tfor(ll m = 1 ; m < n ; m <<= 1) for(ll j = 0, k = 0 ; j < n ; j += m << 1, k ++) for(ll i = j ; i < j + m ; i ++){\n\t\tll x = a[i], y = a[i + m];\n\t\ta[i] = x + y, a[i] >= Mod && (a[i] -= Mod);\n\t\ta[i + m] = (x - y + Mod) * w[k] % Mod;\n\t}\n\tif(!idft) return;\n\treverse(a + 1, a + n);\n\tfor(int i = 0 ; i < n ; i ++) a[i] = a[i] * iv[n] % Mod;\n}\n\ninline ll sqr(ll x){\n\treturn x * x;\n}\n\nll n = 0, m = 0, a[3][N] = {}, b[3][N] = {}, c[N] = {}, d[N] = {};\nchar s[N] = {}, t[N] = {};\n\ninline ll work(ll L, ll R, ll l, ll r){\n\tll M = 1; while(M < R - L + r - l) M <<= 1;\n\tw[0] = 1;\n\tfor(ll k = 1 ; k < M ; k <<= 1){\n\t\tll bit = M / 2 / k;\n        if(k == M / 2) for(ll i = 0; i < k ; i ++) p[i + k] = p[i] | bit;\n        else for(ll i = 0 ; i < k ; i ++){\n            w[i + k] = w[i] * g[k] % Mod;\n            p[i + k] = p[i] | bit;\n        }\n    }\n\tfor(ll i = 0 ; i < M ; i ++){\n\t\tp[i] = p[i >> 1] >> 1;\n\t\tif(i & 1) p[i] |= M >> 1;\n\t}\n\tll z = 0;\n\tfor(ll i = 0 ; i < M ; i ++){\n\t\tc[i] = 0;\n\t\tfor(ll f = 0 ; f < 3 ; f ++)  a[f][i] = b[f][i] = 0;\n\t}\n\tfor(ll i = L ; i < R ; i ++){\n\t\tll x = (s[i] == '-') ? 0 : (s[i] - 'a' + 1);\n\t\ta[0][i - L] = x ? 0 : 1, a[1][i - L] = 2 * x, a[2][i - L] = sqr(x), d[i] = sqr(x);\n\t}\n\td[R] = 0;\n\tfor(ll i = l ; i < r ; i ++){\n\t\tll x = (t[i] == '-') ? 0 : (t[i] - 'a' + 1);\n\t\tb[0][r - i] = sqr(x), b[1][r - i] = x, b[2][r - i] = x ? 0 : 1, z += sqr(x);\n\t}\n\tfor(ll f = 0 ; f < 3 ; f ++){\n\t\tdft(M, a[f], 0), dft(M, b[f], 0);\n\t\tfor(ll i = 0 ; i < M ; i ++) c[i] = (c[i] + a[f][i] * b[f][i]) % Mod;\n\t}\n\tdft(M, c, 1);\n\tfor(ll i = 0 ; i < r - l ; i ++) z += d[i + L];\n\tfor(ll i = L ; i <= R - (r - l) ; z -= d[i], z += d[i + (r - l)], i ++) if(z % Mod == c[i - L + r - l]) return i;\n\treturn -1;\n}\n\nint main(){\n\tfor(ll i = 1 ; i < N ; i <<= 1) g[i] = power(G, Mod / 4 / i), iv[i] = power(i, Mod - 2);\n\tscanf(\"%lld %lld\", &n, &m);\n\tscanf(\"%s %s\", s, t);\n\twhile(n && m && s[n - 1] != '*' && t[m - 1] != '*'){\n\t\tif(s[n - 1] != t[m - 1] && s[n - 1] != '-' && t[m - 1] != '-'){\n\t\t\tprintf(\"No\");\n\t\t\treturn 0;\n\t\t}\n\t\telse n --, m --;\n\t}\n\treverse(s, s + n), reverse(t, t + m);\n\twhile(n && m && s[n - 1] != '*' && t[m - 1] != '*'){\n\t\tif(s[n - 1] != t[m - 1] && s[n - 1] != '-' && t[m - 1] != '-'){\n\t\t\tprintf(\"No\");\n\t\t\treturn 0;\n\t\t}\n\t\telse n --, m --;\n\t}\n\treverse(s, s + n), reverse(t, t + m);\n\tif(min(n, m) == 0){\n\t\twhile(n && s[n - 1] == '*') n --;\n\t\twhile(m && t[m - 1] == '*') m --;\n\t\tif(max(n, m) == 0) printf(\"Yes\");\n\t\telse printf(\"No\");\n\t\treturn 0;\n\t}\n\tbool u = 0, v = 0;\n\tfor(ll i = 0 ; i < n ; i ++) if(s[i] == '*') u = 1;\n\tfor(ll i = 0 ; i < m ; i ++) if(t[i] == '*') v = 1;\n\tif(u){\n\t\tif(v){\n\t\t\tprintf(\"Yes\");\n\t\t\treturn 0;\n\t\t}\n\t\telse swap(n, m), swap(s, t);\n\t}\n\tll L = 0, R = 0;\n\tfor(ll l = 1, r = l ; l < m ; l = r + 1, r = l){\n\t\twhile(t[r] != '*') r ++;\n\t\tif(r - l) while(1){\n\t\t\tR = min(n, L + 2 * (r - l));\n\t\t\tif(R - L < r - l){\n\t\t\t\tprintf(\"No\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tll h = work(L, R, l, r);\n\t\t\tif(h == -1) L = R - (r - l) + 1;\n\t\t\telse{\n\t\t\t\tL = h + r - l;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tprintf(\"Yes\");\n\treturn 0;\n}",
    "tags": [
      "fft",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1975",
    "index": "H",
    "title": "378QAQ and Core",
    "statement": "378QAQ has a string $s$ of length $n$. Define the core of a string as the substring$^\\dagger$ with maximum lexicographic$^\\ddagger$ order.\n\nFor example, the core of \"$\\mathtt{bazoka}$\" is \"$\\mathtt{zoka}$\", and the core of \"$\\mathtt{aaa}$\" is \"$\\mathtt{aaa}$\".\n\n378QAQ wants to rearrange the string $s$ so that the core is lexicographically minimum. Find the lexicographically minimum possible core over all rearrangements of $s$.\n\n$^\\dagger$ A substring of string $s$ is a continuous segment of letters from $s$. For example, \"$\\mathtt{defor}$\", \"$\\mathtt{code}$\" and \"$\\mathtt{o}$\" are all substrings of \"$\\mathtt{codeforces}$\" while \"$\\mathtt{codes}$\" and \"$\\mathtt{aaa}$\" are not.\n\n$^\\ddagger$ A string $p$ is lexicographically smaller than a string $q$ if and only if one of the following holds:\n\n- $p$ is a prefix of $q$, but $p \\ne q$; or\n- in the first position where $p$ and $q$ differ, the string $p$ has a smaller element than the corresponding element in $q$ (when compared by their ASCII code).\n\nFor example, \"$\\mathtt{code}$\" and \"$\\mathtt{coda}$\" are both lexicographically smaller than \"$\\mathtt{codeforces}$\" while \"$\\mathtt{codeforceston}$\" and \"$\\mathtt{z}$\" are not.",
    "tutorial": "Consider the maximum character $m$ of the string $s$. If $m$ only appears once, then obviously the string starting with it is the largest in lexicographical order. To make it the smallest, $m$ should be arranged at the end. Other characters can be arranged arbitrarily. If $m$ appears more than twice, it can be proven that the beginning and end of the answer string must be $m$. If the beginning of the string is not $m$, moving the character at the beginning to somewhere before a non-first $m$ can make the suffix lexicographical order starting with this $m$ smaller, while the suffix lexicographical order starting with $m$ after this remains unchanged. For suffixes that do not start with $m$, they are definitely not the largest, so they do not need to be considered. If the end of the string is not $m$, first remove it, and all suffix lexicographical orders become smaller. Similarly, it can also be placed in front of a certain $m$ to reduce the lexicographical order. In this case, the answer is always in the form of $ms_{1}ms_{2}m\\dots ms_{t}m$. Where $s_{1},s_{2},\\dots,s_{t}$ contain characters that are less than $m$, it could also be an empty string. Now suppose that the set ${s_{1},s_{2},\\dots,s_{t}}$ is determined, and consider how to arrange their order. Suppose we are currently comparing two suffixes $S_{i}=ms_{i}m\\dots ms_{t}m$ and $S_{j}=ms_{j}m\\dots ms_{t}m$, and suppose $s_{i+k}$ and $s_{j+k}$ are the first two substrings that appear differently. Then $ms_{i}m\\dots ms_{i+k-1}$ and $ms_{j}m\\dots ms_{j+k-1}$ must be equal, and the size relationship between $S_{i}$ and $S_{j}$ is the same as the size relationship between $ms_{i+k}$ and $ms_{j+k}$. In this way, all $ms_{i}$ can be sorted according to lexicographical order, and regarded as a new character, and Solving the original problem for $(ms1)(ms_2) \\dots (ms_t)$ is sufficient. Now consider how to determine the set ${s_{1},s_{2},\\dots,s_{t}}$. For a certain $s_{i}$, it should obviously be ordered, because this can make $ms_{i}$ smaller. There is also another property. Suppose there are $s_{i}=p_{i}c$ and $s_{j}$ such that $ms_{j}$ is the current lexicographically largest string, and $mp_{i}<ms_{j}$, where $c$ is a character less than $m$. Putting $c$ after $s_{j}$ can make the answer smaller. The proof of the property is as follows. Without loss of generality, let $f_{1}=p_{i}c$, $f_{2}=p_{i}$, $f_{3}=s_{j}c$, $f_{4}=s_{j}$, then we have $mf_{2}<mf_{1}<mf_{4}$ and $f_{3}m<f_{4}m$. Consider the subproblem after iteration, by definition, $f_{4}$ is the largest character in the problem. If $f_{1}$ and $f_{4}$ are used, and there is an $f_{4}$ to the left of some $f_{1}$ in the optimal solution string, then replacing this $f_{1}$ and its nearest $f_{4}$ on the left with $f_{2}$ and $f_{3}$ respectively, it is easy to prove that the largest suffix will definitely become smaller or unchanged. Otherwise, all $f_{1}$ are to the left of all $f_{4}$, at this time you can arbitrarily replace some $f_{1}$ and $f_{4}$ with $f_{2}$ and $f_{3}$ respectively, it is easy to prove that the largest suffix still becomes smaller or unchanged. Based on the above discussion, we can now give the final greedy algorithm for the problem. Suppose the largest character $m$ has $t+1$ occurrences. If $t=0$, then put the only $m$ at the end, and the other characters can be arranged arbitrarily. Otherwise, suppose there are $p$ characters less than $m$, if $p\\le t$, it can be proved that there is at most one character between any two $m$. Consider $|s_{i}|\\ge2$, $s_{j}=\\varepsilon$ (empty string), then they meet the above properties, and it is more optimal to exchange the last character of $s_{i}$ to $s_{j}$. Therefore, $s_{1},\\dots,s_{p}$ is a single character, $s_{p+1}=\\dots=s_{t}=\\varepsilon$, and recursively solve the subproblem. Note that to ensure time complexity, when $t\\gg p$, multiple rounds of recursion need to be combined. If $p>t$, it can be similarly proved that there will not be an $s_{i}$ that is an empty string. In addition, consider the first character of all $s_{i}$, for those among these $t$ characters that are not the largest, using the same property, it can be proved that the length of the string they are in must be $1$, and no other characters will follow. Also, since $s_{i}$ is ordered, it can be proved that the first character of all $s_{i}$ must be the smallest $t$ characters less than $m$. Next, the remaining characters will only be filled after those largest characters among these $t$ characters, and it can be similarly proved that those filled in the second position of these strings are also the smallest among the remaining characters, and so on, until all characters are used up. Notice that the complexity of each recursion is linear, and each recursion at least halves the number of characters, so the total complexity is $O(n\\log n)$. How to solve this problem in $O(n)$?",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nstruct ch{\n    string c;\n    ch(){c = \"\";}\n    ch(string cc){c=cc;}\n    bool operator == (const ch& p)const{\n        return c==p.c;\n    }\n    bool operator != (const ch& p)const{\n        return c!=p.c;\n    }\n    void add(ch& p){\n        c.append(p.c);\n    }\n};\nvector<ch> solve(vector<ch> cs){\n    int n = cs.size();\n    int t = 0;\n    if(cs.empty())return cs;\n    for(int i=n-2;i>=0;i--){\n        if(cs[i]!=cs[n-1])break;\n        t++;\n    }\n    if(t==0){\n        vector<ch> res;\n        res.push_back(cs[n-1]);\n        return res;\n    }\n    int p = n-(t+1);\n    if(p<=t){\n        vector<ch> res;\n        vector<ch> nxt;\n        int k = (t+1)/(p+1);\n        int le = (t+1)%(p+1);\n        ch m = cs[n-1];\n        for(int j=1;j<k;j++){\n            m.add(cs[n-1]);\n        }\n        for(int i=0;i<p;i++){\n            ch tmp = m;\n            tmp.add(cs[i]);\n            nxt.push_back(tmp);\n        }\n        for(int i=0;i<le;i++){\n            nxt.push_back(cs[n-1]);\n        }\n        auto nxt_solved = solve(nxt);\n        for(auto i:nxt_solved)res.push_back(i);\n        res.push_back(m);\n        return res;\n    }else{\n        vector<ch> res;\n        vector<ch> nxt;\n        ch m = cs[n-1];\n        for(int i=0;i<t;i++){\n            nxt.push_back(m);\n        }\n        int now = 0,beg=0;\n        for(int i=0;i<p;i++){\n            nxt[now].add(cs[i]);\n            if(now>=1){\n                if(cs[i]!=cs[i-1]){\n                    beg=now;\n                }\n            }\n            now++;\n            if(now>=t)now=beg;\n        }\n        auto nxt_solved = solve(nxt);\n        for(auto i:nxt_solved)res.push_back(i);\n        res.push_back(m);\n        return res;\n    }\n}\nvector<ch> trans(string s){\n    vector<ch> tmp;\n    for(auto i:s){\n        string tmpp = \"\";\n        tmpp+=i;\n        tmp.push_back(tmpp);\n    }\n    return tmp;\n}\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        string s;\n        cin>>s;\n        sort(s.begin(),s.end());\n        auto tmp = trans(s);\n        auto ans= solve(tmp); \n        for(auto c:ans)cout<<c.c;\n        cout<<\"\\n\";\n    }\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1975",
    "index": "I",
    "title": "Mind Bloom",
    "statement": "\\begin{quote}\nThis is the way it always was.\n\\end{quote}\n\n\\begin{quote}\nThis is the way it always will be.\n\\end{quote}\n\n\\begin{quote}\nAll will be forgotten again soon...\n\\end{quote}\n\nJellyfish is playing a one-player card game called \"Slay the Spire\". There are $n$ cards in total numbered from $1$ to $n$. The $i$-th card has power $c_i$.\n\nThere is a binary string $s$ of length $n$. If $s_i = 0$, the $i$-th card is initially in the draw pile. If $s_i = 1$, the $i$-th card is initially in Jellyfish's hand.\n\nJellyfish will repeat the following process until either her hand or the draw pile is empty.\n\n- Let $x$ be the power of the card with the largest power in her hand.\n- Place a single card with power $x$ back into the draw pile.\n- Randomly draw $x$ cards from the draw pile. All subsets of $x$ cards from the draw pile have an equal chance of being drawn. If there are fewer than $x$ cards in the draw pile, Jellyfish will draw all cards.\n\nAt the end of this process, find the probability that Jellyfish can empty the draw pile, modulo $1\\,000\\,000\\,007$.\n\nFormally, let $M=1\\,000\\,000\\,007$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Play \"Slay the Spire\". Unfortunately, it doesn't help much. It may be helpful to calculate the probability that your hand becomes empty instead of the probability that the draw pile becomes empty. The intended solution is a $O(n^5)$ DP. The constant factor is small enough to run. If all the cards in your hand is $0$, you immediately lose. Therefore, we only need to consider whether we can empty our hand by playing cards with non-$0$ value. Consider a sequence of playing cards that will lead to use losing. The sum over the probabilities of all these losing sequences is the probability of us losing. To simplify the process, we will consider drawing $x$ random cards from the deck as drawing a random card from the deck $x$ times. Consider a sequence of played cards as $z_1, z_2, \\ldots, z_k$ where $z_i$ is the index of the card played. Consider how $z_i$ was drawn into our hand. It is not hard to see that either: $z_i$ was in our hand at the start $z_i$ from drawn from card $a_j$ where $j$ is the maximum index such that $z_j \\leq z_i$ and $j < i$. From our previous observation, we can motivate the following range DP. Let $f(i,0/1,u,p,x)$ denote the a sequence of played cards with the following: the minimum index of a card we played is $i$ whether there are any cards with value greater than $i$ that is one of the cards that were in our hand in the start before we played this sequence, we played a card of value $u$ before we played this sequence, the deck has $p$ cards The net number of cards that we draw is $x$ We will use $g(i,0/1,u,p,x)$ to help us transition quickly. It is defined as the suffix sum (on dimension $i$) of $f$. Consider transitioning based on the card of index $i$. We have the following transition for $f(*,0,*,*,*)$: $f(i, 0, u, p, x) = \\sum_{y=0}^{x-(c_i-1)} g(i+1, 0, u, p, y) \\times g(i, 0, c_i, p - (c_i - 1) - y, x - (c_i - 1) - y) \\times \\frac {u+y} {(p-y+1)^{\\underline c_i}}$ $g(i, 0, u, p, x) = g(i+1, 0, u, p, x) + f(i, 0, u, p, x)$ For $f(*,1,*,*,*)$, To handle the fact that there are some cards that are initially in our hands, let $h$ denote the the number of $j>i$ such that $s_j=1$. If $s_i = 1$, we have the following transitions: $f(i, 1, u, p, x) = \\sum_{y=h}^{x-c_i} g(i+1, 1, u, p, y) \\times g(i, 0, c_i, p - (c_i - 1) - y+h, x - c_i - y) \\times \\frac {1} {(p-y+1+h)^{\\underline c_i}}$ $g(i, 1, u, p, x) = f(i, 1, u, p, x)$ If $s_i = 0$, we have the following transitions: $f(i, 1, u, p, x) = \\sum_{y=h}^{x-(c_i-1)} g(i+1, 1, u, p, y) \\times g(i, 0, c_i, p - (c_i - 1) - y+h, x - (c_i - 1) - y) \\times \\frac {u+y} {(p-y+1+h)^{\\underline c_i}}$ $g(i, 1, u, p, x) = g(i+1, 1, u, p, x) + f(i, 1, u, p, x)$ The time complexity is $O(n^5)$. Now consider adding the cards with value $1$. It is possible that our game never terminates when we keep on drawing cards with value $1$. We will instead force that when we play a card of value $1$, we are not allowed to draw a card of value $1$. It is not hard to observe that the answer will not change. Consider $dp(i,x)$ to be the probability that we have in our hand: $i$ card of value $0$ $x$ card of value $1$ It is not hard to observe that for the initial state, $dp(i, o+x)$ is $g(1, 1, i+x, 0, m) \\times \\binom {i+x} i \\times (m-o)^{\\underline x}$. Next, consider the transitions. There are only two cases, we draw a card with value $0$, or a card with value greater than $0$: $dp(i, x) \\times \\frac 1 {w+k-i}\\rightarrow dp(i + 1, x - 1)$ $dp(i, x) \\times \\frac 1 {w+k-i}\\rightarrow dp(i + 1, x - 1)$ $\\forall j+y>1, dp(i, x) \\times g(1, 0, 1, n-d-i-x,j+y-1) \\times \\frac 1 {w+k-i} \\times \\binom {j+y} j \\times (m-x+1)^{\\underline y}\\rightarrow dp(i+j, x+y-1)$ $\\forall j+y>1, dp(i, x) \\times g(1, 0, 1, n-d-i-x,j+y-1) \\times \\frac 1 {w+k-i} \\times \\binom {j+y} j \\times (m-x+1)^{\\underline y}\\rightarrow dp(i+j, x+y-1)$ Finally, the answer is $\\sum_{i=0}^k dp(i, 0) \\times k^{\\underline i}$. The time complexity is $O(n^4)$. Therefore, the total complexity is $O(n^5)$. If we use FFT, it can be $O(n^4 \\log n)$, but it was not required in our solution and would probably make the code slower. Furthermore, we can record $v$ instead of $u$, which means there are $v$ cards with $i$ or greater index drawn from $u$ draws. So it's not difficult to find $v \\leq u$. And when $c_i \\leq \\sqrt n$, we have $v \\leq u \\leq c_i \\leq \\sqrt n$. And when $c_i > \\sqrt n$, we have $v \\leq \\frac n {c_i - 1} \\leq \\sqrt n$, the complexity can become $O (n ^ {4.5})$. If we use FFT, it can be $O (n ^ {3.5} \\log n)$. Let $k$ be the number of cards with value $0$. It is not hard to see that: the size of $i$ is $n-k$ the size of $x$ is $k$ the size of $u$ is $n-k$ the size of $p$ is $n$ The number of states is $(n-k)^2k^2n$, which has a constant of $\\frac{1}{16}$. We also have that $y \\leq x$ and $u \\leq c_i$, which both gives us another constant of $\\frac{1}{2}$. Since we have a flag in our dp state, it has a factor of $2$. This gives us a constant factor of rougly $\\frac{1}{32}$, which is extremely small. So it is reasonable to expect $O(n^5)$ to run about $1$ second. Solution by Melania Let $S$ denote the set of cards currently in Jellyfish's hand. We assume that $a_1 = 0$ and $a_n \\geq 2$. Initially, $|S| \\in [1, n-1]$. Cases where these conditions do not hold are trivial. We observe that Jellyfish cannot empty the draw pile if and only if she runs out of non-zero cards to play. In the following section, we compute the probability that she eventually runs out of non-zero cards. It is clear that in any scenario where she runs out of non-zero cards, $\\max(S)$ must gradually decrease to zero. We can break down the entire process into sub-procedures, where in each sub-procedure, $\\max(S)$ decreases from $i$ to $\\leq i-1$, ultimately reaching zero. Assume she is currently in a state where $\\max(S) = i$ and $|S \\setminus {i}| = x$. We denote $F_{i,x,y}$ as the probability that she will eventually transition to a state where $\\max(S) \\leq i-1$, and in the very first state where $\\max(S) \\leq i-1$, the size of $S$ is $y$. For a fixed and given pair $(i,x)$, we aim to compute all values of $F_{i,x,y}$ simultaneously. To determine the values of $F_{i,x,y}$, consider the situation after Jellyfish plays card $a_i$. For the remaining $n-x$ cards, each card is equally likely to be one of the $a_i$ cards drawn. Therefore, for any individual card outside of the initial $x$ cards, the probability of possessing that card is $p = \\dfrac{a_i}{n-x}$. We define the initial event where Jellyfish plays card $a_i$ as the starting point of our timeline. Following this event, we consider $n-i+2$ key moments when $\\max(S)$ becomes $\\leq n$ for the first time, $\\leq n-1$ for the first time, and so on, down to $\\leq i+1$, $\\leq i$, and finally $\\leq i-1$ for the first time. We denote $G_{j,y}$ as the probability that Jellyfish will eventually reach a state where $\\max(S) \\leq j$, and in the very first state where $\\max(S) \\leq j$, the size of $S$ is $y$. Initially, $G_{n,x + a_i} = 1$. To understand the transitions of $G_{j,y}$, note that since all cards $\\leq j$ (excluding the initial $x$ cards) are symmetrical, the probability of owning card $j$ is exactly $p=\\dfrac{y-x}{j-x}$. If Jellyfish does not own card $j$, then the first state where $\\max(S) \\leq j-1$ is simply the first state where $\\max(S) \\leq j$. This describes a transition of $G_{j-1,y} \\leftarrow (1-p)G_{j,y}$. If Jellyfish owns card $j$, we enumerate the number of cards $|S| = z$ in her hand when she first reaches $\\max(S) \\leq j-1$. The probability of this happening is $F_{j,y-1,z}$. Thus, we have $G_{j-1,z} \\leftarrow pG_{j,y}F_{j,y-1,z}$. Here's a further explanation of why \"all cards $\\leq j$ (excluding the initial $x$ cards) are symmetrical\": Because this state is the very first time $\\max(S) \\leq j$, it means that all cards played before this state and after Jellyfish initially plays $a_i$ are $\\geq j+1$. From the perspective of those cards $\\geq j+1$, all cards $\\leq j$ (excluding the initial $x$ cards) are symmetrical. In the end, the actual algorithm we derived for computing $F_{i,x,y}$ is quite straightforward: Iterate through $j$ backwards from $n$ to $i$. For each $G_{j,y}$, make two types of transitions: $G_{j-1,z} \\leftarrow pG_{j,y}F_{j,y-1,z}$, where $p = \\dfrac{y-x}{j-x}$; $G_{j-1,y} \\leftarrow (1-p)G_{j,y}$. Finally, $F_{i,x,y} = G_{i-1,y}$. A small catch is that we could have self-loops. If $a_i = 1$, then in the final step where $j = i$, there will be some transitions where $F_{i,x,y} \\leftarrow cF_{i,x,y}$. For a given $F_{i,x,y}$, if all the other known values that contribute to it sum to $A$ and all the $c$ coefficients sum to $C$, then we have $F_{i,x,y} = A + CF_{i,x,y}$. This results in $F_{i,x,y} = \\dfrac{A}{1-C}$. We can address this by calculating the inverse. It can be shown that if we also iterate through $x$ from larger to smaller values, no $F_{i,x,y}$ will use other values of $F_{i',x',y'}$ that are neither known nor equal to $F_{i,x,y}$ itself. In other words, the value of $F_{i,x,y}$ does not invoke other unknown values of $F_{i',x',y'}$. After computing all values of $F_{i,x,y}$, we proceed to determine the final answer. We define $\\text{ans}_{i,x}$ as the average probability that Jellyfish will eventually run out of non-zero cards (thus losing the game) if she starts with all $s_i$ cards in $[1, i]$ (which she owns initially) plus an additional $x$ cards drawn randomly from the remaining $i - s_i$ cards in $[1, i]$ (which she does not own initially). If $c_i = 1$, the transition is given by: $\\text{ans}_{i,x}=\\displaystyle\\sum F_{i,x-1,y}\\text{ans}_{i-1,y}$; If $c_i = 0$, the transition is given by: $\\text{ans}_{i,x}=(1-p)\\text{ans}_{i-1,x}+p\\displaystyle\\sum F_{i,x-1,y}\\text{ans}_{i-1,y}$, where $p=\\dfrac{x-s_i}{i-s_i}$. Finally, we compute $1 - \\text{ans}_{n,s_n}$ to obtain the probability that Jellyfish will eventually win the game. The time complexity of this approach is $\\mathcal{O}(n^5 + n^3 \\log p)$, and the space complexity is $\\mathcal{O}(n^3)$. It is also possible to optimize the $\\mathcal{O}(n^5)$ time complexity to $\\mathcal{O}(n^4 \\sqrt{n})$ by using Lagrange interpolation. To achieve this speedup, we notice that the values of $i$ and $x$ do not play a crucial role in the transition of $G_{j,y}$. Specifically, the influence of the values $i$ and $x$ on the transition of $G_{j,y}$ can be described as follows: The initial value is $G_{n,x+a_i} = 1$. During the transition, $p = \\dfrac{y-x}{j-x}$ and $1-p = \\dfrac{j-y}{j-x}$. We can fix the value of $k = x + a_i$ and treat $x$ as a variable, maintaining a polynomial in $x$ as the value of $G_{j,y}$. We observe that it is only necessary to keep the point values between $[k-1, k-\\sqrt{n}]$ to track the polynomial accurately. For $a_i > \\sqrt{n}$, since each transition involving multiplication by $p$ will increase the value of $y$ by at least $a_i$, it is clear that the degree of the polynomial $G_{j,y}$ is at most $\\sqrt{n}$. Thus, keeping track of $\\sqrt{n}$ values is sufficient to restore the polynomial, and we can use linear Lagrange interpolation to obtain the point values outside these $\\sqrt{n}$ points. For $a_i \\leq \\sqrt{n}$, since $x = k - a_i$, we only care about the point values in the range $[k-1, k-\\sqrt{n}]$. Although the polynomial restored may be inaccurate beyond this range, these point values are the ones that matter for our calculations anyway. By applying this optimization, we effectively reduce the time complexity to $\\mathcal{O}(n^4 \\sqrt{n} + n^3 \\log p)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nconst ll N = 120 + 5, Mod = 1e9 + 7;\n\ninline ll power(ll x, ll y){\n\tll ret = 1;\n\twhile(y){\n\t\tif(y & 1) ret = ret * x % Mod;\n\t\tx = x * x % Mod, y >>= 1;\n\t}\n\treturn ret;\n}\n\ninline ll inv(ll x){\n\treturn power(x, Mod - 2);\n}\n\nll n = 0, m = 0, w = 0, o = 0, d = 0, r = 0, k = 0, c[N] = {}, v[N] = {};\nll iv[N] = {}, a[N][N] = {}, b[N][N] = {}, binom[N][N] = {};\nll f[2][2][N][N][N] = {}, g[2][2][N][N][N] = {}, dp[N][N] = {};\nchar s[N] = {};\n\ninline void init(){\n\tn = m = w = o = d = r = k = 0;\n\tmemset(c, 0, sizeof(c)), memset(v, 0, sizeof(v)), memset(s, 0, sizeof(s));\n\tmemset(f, 0, sizeof(f)), memset(g, 0, sizeof(g)), memset(dp, 0, sizeof(dp));\n}\n\ninline void solve(){\n\tscanf(\"%lld\", &n);\n\tv[0] = v[1] = 1;\n\tfor(ll i = 1 ; i <= n ; i ++){\n\t\tscanf(\"%lld\", &c[i]);\n\t\tv[c[i]] = 1;\n\t}\n\tscanf(\"%s\", s + 1);\n\tfor(ll i = 1 ; i <= n ; i ++){\n\t\tif(s[i] == '0') r ++;\n\t\tif(c[i] > 1) w ++;\n\t\telse if(c[i] == 1){\n\t\t\tif(s[i] == '1') o ++;\n\t\t\tm ++;\n\t\t}\n\t\telse{\n\t\t\tif(s[i] == '1') d ++;\n\t\t\telse k ++;\n\t\t}\n\t}\n\tif(c[n] <= 1){\n\t\tfor(ll i = 1 ; i <= n ; i ++) if(s[i] == '0'){\n\t\t\tprintf(\"0\\n\");\n\t\t\treturn;\n\t\t}\n\t\tprintf(\"1\\n\");\n\t\treturn;\n\t}\n\tfor(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[n] ; u ++) if(v[u]){\n\t\tf[1][0][u][p][0] = f[1][1][u][p][0] = 1;\n\t\tg[1][0][u][p][0] = g[1][1][u][p][0] = 1;\n\t}\n\tfor(ll i = n, h = 0 ; c[i] > 1 ; i --){\n\t\tfor(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[i] ; u ++) if(v[u]){\n\t\t\tg[0][0][u][p][0] = 1;\n\t\t\tif(s[i] == '0') g[0][1][u][p][0] = g[1][1][u][p][0];\n\t\t}\n\t\tfor(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[i] ; u ++) if(v[u]) for(ll x = 1 ; x <= k ; x ++){\n\t\t\tfor(ll y = 0 ; y <= x - (c[i] - 1) ; y ++) f[0][0][u][p][x] = (f[0][0][u][p][x] + (g[1][0][u][p][y] * g[0][0][c[i]][p - (c[i] - 1) - y][x - (c[i] - 1) - y] % Mod) * ((u + y) * b[p - y + 1][c[i]] % Mod)) % Mod;\n\t\t\tg[0][0][u][p][x] = (g[1][0][u][p][x] + f[0][0][u][p][x]) % Mod;\n\t\t}\n\t\tfor(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[i] ; u ++) if(v[u]) for(ll x = 1 ; x <= k ; x ++){\n\t\t\tif(s[i] == '1'){\n\t\t\t\tfor(ll y = h ; y <= x - c[i] ; y ++) f[0][1][u][p][x] = (f[0][1][u][p][x] + (g[1][1][u][p][y] * g[0][0][c[i]][p - (c[i] - 1) - y + h][x - c[i] - y] % Mod) * b[p - y + 1 + h][c[i]]) % Mod;\n\t\t\t\tg[0][1][u][p][x] = f[0][1][u][p][x];\n\t\t\t}\n\t\t\telse{\n\t\t\t\tfor(ll y = h ; y <= x - (c[i] - 1) ; y ++) f[0][1][u][p][x] = (f[0][1][u][p][x] + (g[1][1][u][p][y] * g[0][0][c[i]][p - (c[i] - 1) - y + h][x - (c[i] - 1) - y] % Mod) * ((u + y) * b[p - y + 1 + h][c[i]] % Mod)) % Mod;\n\t\t\t\tg[0][1][u][p][x] = (g[1][1][u][p][x] + f[0][1][u][p][x]) % Mod;\n\t\t\t}\n\t\t}\n\t\tfor(ll p = 0 ; p <= n ; p ++) for(ll u = 0 ; u <= c[i] ; u ++) if(v[u]) for(ll x = 0 ; x <= k ; x ++){\n\t\t\tf[1][0][u][p][x] = f[0][0][u][p][x], f[1][1][u][p][x] = f[0][1][u][p][x];\n\t\t\tg[1][0][u][p][x] = g[0][0][u][p][x], g[1][1][u][p][x] = g[0][1][u][p][x];\n\t\t\tf[0][0][u][p][x] = f[0][1][u][p][x] = g[0][0][u][p][x] = g[0][1][u][p][x] = 0;\n\t\t}\n\t\tif(s[i] == '1') h ++;\n\t}\n\tfor(ll i = 0 ; i <= k ; i ++) for(ll x = 0 ; x <= m - o ; x ++) dp[i][o + x] = g[1][1][0][r][i + x] * (binom[i + x][i] * a[m - o][x] % Mod) % Mod;\n\tfor(ll i = 0 ; i <= k ; i ++) for(ll x = 1 ; x <= m ; x ++) if(dp[i][x]){\n\t\tif(i < k) dp[i + 1][x - 1] = (dp[i + 1][x - 1] + dp[i][x] * iv[w + k - i]) % Mod;\n\t\tfor(ll j = 0 ; i + j <= k ; j ++) for(ll y = 0 ; x + y - 1 <= m ; y ++) if(j + y > 1) dp[i + j][x + y - 1] = (dp[i + j][x + y - 1] + (dp[i][x] * g[1][0][1][n - d - i - x][j + y - 1] % Mod) * (iv[w + k - i] * (binom[j + y][j] * a[m - x + 1][y] % Mod) % Mod)) % Mod;\n\t}\n\tll ans = 1;\n\tfor(ll i = 0 ; i <= k ; i ++) ans = (ans + (Mod - dp[i][0]) * a[k][i]) % Mod;\n\tprintf(\"%lld\\n\", ans);\n}\n\nll T = 0;\n\nint main(){\n\tfor(ll x = 0 ; x < N ; x ++){\n\t\ta[x][0] = b[x][0] = 1, iv[x] = inv(x), binom[x][0] = 1;\n\t\tfor(ll y = 1 ; y <= x ; y ++){\n\t\t\ta[x][y] = a[x][y - 1] * (x - y + 1) % Mod, b[x][y] = inv(a[x][y]);\n\t\t\tbinom[x][y] = (binom[x - 1][y - 1] + binom[x - 1][y]) % Mod;\n\t\t}\n\t}\n\tscanf(\"%lld\", &T);\n\tfor(ll i = 1 ; i <= T ; i ++) init(), solve();\n\treturn 0;\n}",
    "tags": [
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1976",
    "index": "A",
    "title": "Verify Password",
    "statement": "Monocarp is working on his new site, and the current challenge is to make the users pick strong passwords.\n\nMonocarp decided that strong passwords should satisfy the following conditions:\n\n- password should consist only of lowercase Latin letters and digits;\n- there should be no digit that comes after a letter (so, after each letter, there is either another letter or the string ends);\n- all digits should be sorted in the non-decreasing order;\n- all letters should be sorted in the non-decreasing order.\n\nNote that it's allowed for the password to have only letters or only digits.\n\nMonocarp managed to implement the first condition, but he struggles with the remaining ones. Can you help him to verify the passwords?",
    "tutorial": "There's no real idea in the problem, the main difficulty is the implementation. Many programming languages have functions to check if a character is a digit or if it's a letter. They can be used to check that no digit follows a letter. How does the order check work? Well, most languages allow you to compare characters with inequality signs (so, we have to check that $s_i \\le s_{i + 1}$ for all corresponding $i$ - separately for digits and letters). How does that work? Inside the language, every character is assigned a code. That's called an ASCII table. It contains digits, letters and lots of other characters. And the less or equal check uses that table. If you look at the table carefully, you'll notice that the digits come before the lowercase Latin letters. Digits have codes from 48 to 57 and the lowercase letters have codes from 97 to 122. Thus, you can ignore the check that the digits come before the letters and just make sure that all characters of the string (regardless of their types) and sorted in a non-decreasing order. For example, you can sort the string and compare the result with the original string. If they are the same, then the answer is \"YES\". Alternatively, you can use function is_sorted if your language has it. Overall complexity: $O(n)$ or $O(n \\log n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ts = input()\n\tprint(\"YES\" if list(s) == sorted(s) else \"NO\")",
    "tags": [
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1976",
    "index": "B",
    "title": "Increase/Decrease/Copy",
    "statement": "You are given two integer arrays: array $a$ of length $n$ and array $b$ of length $n+1$.\n\nYou can perform the following operations any number of times in any order:\n\n- choose any element of the array $a$ and increase it by $1$;\n- choose any element of the array $a$ and decrease it by $1$;\n- choose any element of the array $a$, copy it and append the copy to the end of the array $a$.\n\nYour task is to calculate the minimum number of aforementioned operations (possibly zero) required to transform the array $a$ into the array $b$. It can be shown that under the constraints of the problem, it is always possible.",
    "tutorial": "Let's fix the index of the element to be copied (denote it as $i$). For all other elements of the array, the number of required operations is $|a_j-b_j|$ for all $j \\ne i$. Consider the case when $a_i \\le b_i$ (similar to the case when $a_i \\ge b_i$). There are three possible relative location of the desired element $b_{n + 1}$: if $b_{n + 1} < a_i$, you can proceed as follows: copy $i$-th element, increase $a_{n + 1}$ to $b_{n + 1}$ and increase $a_i$ to $b_i$, then the number of operations is equal to $1 + (b_{n + 1} - a_i) + (b_i - a_i)$; if $a_i \\le b_{n + 1} \\le b_i$, you can proceed as follows: increase $a_i$ to $b_{n + 1}$, copy it, and keep increasing to $b_i$, then the number of operations is equal to $(b_{n + 1} - a_i) + 1 + (b_i - b_{n + 1}) = (b_i - a_i) + 1$; if $b_i < b_{n + 1}$, you can proceed as follows: increase $a_i$ to $b_i$, copy $i$-th element, and increase $a_{n + 1}$ to $b_{n + 1}$, then the number of operations is equal to $(b_i - a_i) + 1 + (b_{n + 1} - b_i)$. As you can see, regardless of the case, $|b_i-a_i|$ is also added to the answer. So the answer looks like this: $\\sum\\limits_{j=1}^{n} |b_j-a_j|$ plus some extra operations to get $b_{n + 1}$. That extra value is equal to the minimum value of $f(i)$ over all indices $i$, where $f(i)$ is equal to $1 + |b_{n + 1} - a_i|$ or $1$ or $1 + |b_{n + 1} - b_i|$ depending on the cases described above.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing li = long long;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<li> a(n), b(n + 1);\n    for (auto& x : a) cin >> x;\n    for (auto& x : b) cin >> x;\n    li sum = 0, ext = 1e18;\n    for (int i = 0; i < n; ++i) {\n      sum += abs(a[i] - b[i]);\n      ext = min(ext, abs(a[i] - b[n]));\n      ext = min(ext, abs(b[i] - b[n]));\n      if (min(a[i], b[i]) <= b[n] && b[n] <= max(a[i], b[i]))\n        ext = 0;\n    }\n    cout << sum + ext + 1 << '\\n';\n  }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1976",
    "index": "C",
    "title": "Job Interview",
    "statement": "Monocarp is opening his own IT company. He wants to hire $n$ programmers and $m$ testers.\n\nThere are $n+m+1$ candidates, numbered from $1$ to $n+m+1$ in chronological order of their arriving time. The $i$-th candidate has programming skill $a_i$ and testing skill $b_i$ (a person's programming skill is different from their testing skill). The skill of the team is the sum of the programming skills of all candidates hired as programmers, and the sum of the testing skills of all candidates hired as testers.\n\nWhen a candidate arrives to interview, Monocarp tries to assign them to the most suitable position for them (if their programming skill is higher, then he hires them as a programmer, otherwise as a tester). If all slots for that position are filled, Monocarp assigns them to the other position.\n\nYour task is, for each candidate, calculate the skill of the team if everyone except them comes to interview. Note that it means that exactly $n+m$ candidates will arrive, so all $n+m$ positions in the company will be filled.",
    "tutorial": "Let's naively calculate the answer for the $(n+m+1)$-th candidate. While calculating it, let's store two values: $type_i$ - the type of job the $i$-th candidate was hired for; $bad$ - the index of the first candidate who was hired for a suboptimal role. We can show that this first candidate $bad$ who was hired for a suboptimal role is the only possible candidate who can change his role if another candidate doesn't show up. So, for all other candidates among the first $n+m$ candidates, their roles are fixed. To prove this, we can consider the following cases: if the candidate who doesn't show up has an index $bad$ or greater, then for all candidates after them, there is only one possible job (when we consider that candidate $bad$, all positions on one of the job are already filled); if the index who doesn't show up has index less than $bad$, then the candidate $bad$ will take the same job as that candidate has taken, and in any case, all positions of the optimal job of the candidate $bad$ will be filled after we take that candidate. Now we can use the $(n+m+1)$-th candidate's answer to calculate the answer for the $i$-th candidate as follows: if $i < bad$ and $type_i \\ne type_{bad}$, we can \"move\" the $bad$-th candidate to the role $type_i$ and the $(n+m+1)$-th candidate to the role $type_{bad}$, this will change the answer by $(a_{bad} - a_i) + (b_{n+m+1} - b_{bad})$ in case of the $i$-th candidate was hired as programmer (similarly for tester); otherwise, we can simply \"move\" the $(n+m+1)$-th candidate to the role $type_i$, this will change the answer by $(a_{n+m+1} - a_i)$ in case of the $i$-th candidate was hired as programmer (similarly for tester).",
    "code": "for _ in range(int(input())):\n    n, m = map(int, input().split())\n    bounds = [n, m]\n    a = []\n    a.append(list(map(int, input().split())))\n    a.append(list(map(int, input().split())))\n    \n    bad = -1\n    badType = -1\n    cur = [0, 0]\n    ans = 0\n    types = [0 for i in range(n + m + 1)]\n    for i in range(n + m):\n        curType = 0\n        if a[0][i] < a[1][i]:\n            curType = 1\n        if cur[curType] == bounds[curType]:\n            curType = 1 - curType\n            if bad == -1:\n                bad = i\n                badType = 1 - curType\n        types[i] = curType\n        ans += a[types[i]][i]\n        cur[types[i]] += 1\n        \n    res = []\n    for i in range(n + m):\n        val = ans - a[types[i]][i]\n        if bad != -1 and i < bad and types[i] == badType:\n            val = val + a[badType][bad] - a[1 - badType][bad] + a[1 - badType][n + m]\n        else:\n            val = val + a[types[i]][n + m]\n        res.append(val)\n    res.append(ans)\n    print(*res)",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1976",
    "index": "D",
    "title": "Invertible Bracket Sequences",
    "statement": "A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example:\n\n- bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\");\n- bracket sequences \")(\", \"(\" and \")\" are not.\n\nLet's define the inverse of the bracket sequence as follows: replace all brackets '(' with ')', and vice versa (all brackets ')' with '('). For example, strings \"()((\" and \")())\" are inverses of each other.\n\nYou are given a regular bracket sequence $s$. Calculate the number of pairs of integers $(l,r)$ ($1 \\le l \\le r \\le |s|$) such that if you replace the substring of $s$ from the $l$-th character to the $r$-th character (inclusive) with its inverse, $s$ will still be a regular bracket sequence.",
    "tutorial": "Let's define $bal_i$ as the number of characters '(' minus the number of characters ')' if we consider a prefix of length $i$. The bracket sequence is regular if both of the following conditions holds: there is no index $i$ such that $bal_i < 0$; $bal_n = 0$, where $n$ is the length of the sequence. Using that fact, we can say that the substring $[l, r]$ is \"good\" if both of the following conditions holds: $bal_{l-1} \\ge bal_i - bal_{l-1}$ should hold for all $i$ in $[l, r]$, otherwise that would lead to the negative balance after inverting the substring; $bal_{l-1} = bal_r$, otherwise that would lead to $bal_n \\ne 0$ after inverting substring. There are many solutions that are based on these two facts. Let's consider one of them. Let's iterate over the right bound of the substring (denote it as $r$). According to the second condition, $bal_{l-1} = bal_r$, therefore, we can maintain a map that stores the number of positions for each balance value. But, unfortunately, not all such left borders form a good substring because of the first condition. Luckily, it is easy to fix, if the current balance $bal_r$ and there is balance $x$ in the map such that $x < bal_r - x$, we can remove all its occurrences from the map (i. e. remove the key $x$ from the map). This fix works because the current position lies between the left border (which we store in the map) and the potential right border, and the current balance is too high (which violates the first condition). So, we get a solution that works in $O(n\\log{n})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    string s;\n    cin >> s;\n    map<int, int> cnt;\n    int b = 0;\n    ++cnt[b];\n    long long ans = 0;\n    for (auto& c : s) {\n      b += (c == '(' ? +1 : -1);\n      ans += cnt[b];\n      ++cnt[b];\n      while (cnt.begin()->first * 2 < b)\n        cnt.erase(cnt.begin());\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "data structures",
      "divide and conquer",
      "implementation",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1976",
    "index": "E",
    "title": "Splittable Permutations",
    "statement": "Initially, we had one array, which was a permutation of size $n$ (an array of size $n$ where each integer from $1$ to $n$ appears exactly once).\n\nWe performed $q$ operations. During the $i$-th operation, we did the following:\n\n- choose any array we have with at least $2$ elements;\n- split it into two non-empty arrays (prefix and suffix);\n- write two integers $l_i$ and $r_i$, where $l_i$ is the maximum element in the left part which we get after the split, and $r_i$ is the maximum element in the right part;\n- remove the array we've chosen from the pool of arrays we can use, and add the two resulting parts into the pool.\n\nFor example, suppose the initial array was $[6, 3, 4, 1, 2, 5]$, and we performed the following operations:\n\n- choose the array $[6, 3, 4, 1, 2, 5]$ and split it into $[6, 3]$ and $[4, 1, 2, 5]$. Then we write $l_1 = 6$ and $r_1 = 5$, and the arrays we have are $[6, 3]$ and $[4, 1, 2, 5]$;\n- choose the array $[4, 1, 2, 5]$ and split it into $[4, 1, 2]$ and $[5]$. Then we write $l_2 = 4$ and $r_2 = 5$, and the arrays we have are $[6, 3]$, $[4, 1, 2]$ and $[5]$;\n- choose the array $[4, 1, 2]$ and split it into $[4]$ and $[1, 2]$. Then we write $l_3 = 4$ and $r_3 = 2$, and the arrays we have are $[6, 3]$, $[4]$, $[1, 2]$ and $[5]$.\n\nYou are given two integers $n$ and $q$, and two sequences $[l_1, l_2, \\dots, l_q]$ and $[r_1, r_2, \\dots, r_q]$. A permutation of size $n$ is called valid if we can perform $q$ operations and produce the given sequences $[l_1, l_2, \\dots, l_q]$ and $[r_1, r_2, \\dots, r_q]$.\n\nCalculate the number of valid permutations.",
    "tutorial": "First, let's deal with the case $q=n-1$. In this case, after all operations are performed, all arrays have only one element each, and can no longer be split. We can show that the initial order of elements can be restored uniquely in this case. For example, we can start with $n$ arrays consisting of single elements (one array for each integer from $1$ to $n$), and \"undo\" the operations to restore the initial order. \"Undoing\" the operations means linking two arrays together, and we don't have any choice which arrays and in which order we link, so the result of each operation is uniquely determined. So, in the case $q = n-1$, the answer is $1$. What about the case $q < n-1$? Let's divide all integers from $1$ to $n$ into two groups: the integers from the sequences $l$ and/or $r$, and all other integers. We can use the same process to show that the order of elements from the first group (the ones which were present in at least one of the given sequences) is unique, and we can restore their order using something like DSU (performing operations from the last to the first) or a double-linked list (performing operations from the first to the last). So, suppose we restored the order of elements which are present in the input; we need to insert all of the remaining integers and don't make the sequence of operations invalid. We have an array of $q+1$ elements, the order of which is fixed; and there are $q+2$ \"buckets\" where we can insert the remaining elements (before the first element, between the first and the second, and so on). For each of these \"buckets\", let's consider the maximum between the elements on the borders of the bucket (the fixed elements between which we insert the remaining elements). It's quite easy to see that each element we insert in a \"bucket\" should be less than this maximum: suppose the fixed element on the left border is $y$, the fixed element on the right border is $z$, and there was an element $x > \\max(y,z)$ between them. After we performed all operations, $x$ is either in the same array as $y$ or in the same array as $z$; so when we \"made\" that array during an operation, we would have written the integer $x$ (or some even greater integer) instead of $y$ or $z$. And we can also show the opposite: if each element in each \"bucket\" is less than the maximum of the two elements bordering the bucket, the operation sequence is valid. To prove it, let's merge every bucket with the greater of the elements on its borders, and then again \"undo\" all operations to restore the original order of elements. So, for each remaining element, there are some buckets where we can put it, and some buckets where we can't. However, we also have to consider the relative order of the elements we insert in the same bucket. Let's start with the sequence of \"fixed\" elements, and insert the remaining elements one by one from the greatest integer to the smallest integer. We can show that every time we insert an element in this order, the number of places where it can go does not depend on where we inserted the previous elements. Suppose we insert an element which \"fits\" into $b$ buckets, and before inserting it, we also inserted $k$ other elements. Then there are exactly $b+k$ places where this element can fit, because every element we inserted earlier went into one of those same $b$ buckets and split that bucket into two. So, maintaining these two numbers (the number of available buckets and the number of elements we already inserted) is enough, and the positions of elements we inserted does not matter. This allows us to count the number of possible permutations in $O(n)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 300043;\nconst int MOD = 998244353;\n \nint add(int x, int y)\n{\n\tx += y;\n\twhile(x >= MOD) x -= MOD;\n\twhile(x < 0) x += MOD;\n\treturn x;\n}\n \nint mul(int x, int y)\n{\n\treturn (x * 1ll * y) % MOD;\n}\n \nint nxt[N], prv[N];\nbool exists[N];\n \nint main()\n{\n\tint n, q;\n\tscanf(\"%d %d\", &n, &q);\n\tfor(int i = 1; i <= n; i++) nxt[i] = prv[i] = -1;\n\texists[n] = true;\n\tvector<int> l(q), r(q);\n\tfor(int i = 0; i < q; i++) scanf(\"%d\", &l[i]);\n\tfor(int i = 0; i < q; i++) scanf(\"%d\", &r[i]);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t\tint L = l[i], R = r[i];\n\t\tif(exists[L])\n\t\t{\n\t\t\texists[R] = true;\n\t\t\tnxt[R] = nxt[L];\n\t\t\tif(nxt[R] != -1) prv[nxt[R]] = R;\n\t\t\tprv[R] = L;\n\t\t\tnxt[L] = R;\n\t\t}\n\t\telse\n\t\t{\n\t\t\texists[L] = true;\n\t\t\tprv[L] = prv[R];\n\t\t\tif(prv[L] != -1) nxt[prv[L]] = L;\n\t\t\tnxt[L] = R;\n\t\t\tprv[R] = L;\n\t\t}\n\t}\n\tvector<int> seq;\n\tint start = -1;\n\tfor(int i = 1; i <= n; i++)\n\t\tif(prv[i] == -1 && exists[i])\n\t\t\tstart = i;\n\tseq.push_back(start);\n\twhile(nxt[start] != -1)\n\t{\n\t\tstart = nxt[start];\n\t\tseq.push_back(start);\n\t}\n\tvector<int> cnt_segments(n + 1);\n\tcnt_segments[seq[0]]++;\n\tcnt_segments[seq[q]]++;\n\tfor(int i = 0; i < q; i++)\n\t\tcnt_segments[max(seq[i], seq[i + 1])]++;\n\tint ans = 1;\n\tint places = 0;\n\tfor(int i = n; i >= 1; i--)\n\t{\n\t\tif(exists[i])\n\t\t\tplaces += cnt_segments[i];\n\t\telse\n\t\t{\n\t\t\tans = mul(ans, places);\n\t\t\tplaces++;\n\t\t}\n\t}\n\tprintf(\"%d\\n\", ans);\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dfs and similar",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1976",
    "index": "F",
    "title": "Remove Bridges",
    "statement": "You are given a rooted tree, consisting of $n$ vertices, numbered from $1$ to $n$. Vertex $1$ is the root. Additionally, the root only has one child.\n\nYou are asked to add exactly $k$ edges to the tree (possibly, multiple edges and/or edges already existing in the tree).\n\nRecall that a bridge is such an edge that, after you remove it, the number of connected components in the graph increases. So, initially, all edges of the tree are bridges.\n\nAfter $k$ edges are added, some original edges of the tree are still bridges and some are not anymore. You want to satisfy two conditions:\n\n- for every bridge, all tree edges in the subtree of the lower vertex of that bridge should also be bridges;\n- the number of bridges is as small as possible.\n\nSolve the task for all values of $k$ from $1$ to $n - 1$ and output the smallest number of bridges.",
    "tutorial": "What does an extra edge change in the configuration of the bridges? Well, all tree edges on the path between the two vertices that an extra edge connects, stop being bridges. So, the task can be restated as follows: choose $k$ pairs of distinct vertices such that: a root is present in at least one pair; the number of edges in the union of the paths between the vertices of all pairs is as large as possible; there is no vertex covered by at least one path such that an edge to its parent is not a part of any path. The next idea is quite intuitive. It only makes sense to choose a root or the leaves of the tree into the pairs. If any pair has a non-leaf vertex, you can safely prolong the path until any of the leaves in its subtree, and the union of the paths will not become smaller. Now for the tricky idea. Instead of choosing $k$ pairs of root/leaves, you can actually just take a root and $2k - 1$ leaves, and there will always be a way to split them into pairs to satisfy all conditions. Let's show that. Traverse the tree with a DFS and record the order you visit the leaves. Pair up a root with the middle leaf in that order. Then pair up leaves $1$ and $2k-1$, $2$ and $2k-2$ and so on. This way, the path for every pair includes a vertex on the path of the first pair (the one that includes the root). Thus, the union of the paths is the same as the union of all vertical paths from the leaves to the root. That obviously satisfies the condition on the connectedness of the bridges. Notice how that union of the paths is also the largest possible on that set of leaves. Every path between the leaves can be viewed at as two vertical paths from each leaf. The longest vertical path from each leaf is the one going to the root. And we have exactly the union of these vertical paths as our solution. Thus, the task actually becomes as follows: choose $2k - 1$ leaves in such a way that the union of their paths to the root is as large as possible. That can actually be done greedily. Take a leaf with the longest path to the root. Then keep taking leaves that add as many new edges into the union as possible. That idea can be implemented as follows. For every vertex, calculate the longest path that starts in it and ends in some leaf. Can be done with a single DFS. Maintain a set of all vertices sorted by their longest paths. On each step, take a vertex with the largest value and remove all vertices on that path (any path of the maximum length if there are multiple) from the set. Overall complexity: $O(n \\log n)$ per testcase.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nvector<int> h;\nvector<vector<int>> g;\n \nvoid dfs(int v, int p = -1){\n\tfor (int u : g[v]) if (u != p){\n\t\tdfs(u, v);\n\t\th[v] = max(h[v], h[u] + 1);\n\t}\n}\n \nint main() {\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tint t;\n\tcin >> t;\n\twhile (t--){\n\t\tint n;\n\t\tcin >> n;\n\t\tg.assign(n, {});\n\t\tforn(i, n - 1){\n\t\t\tint v, u;\n\t\t\tcin >> v >> u;\n\t\t\t--v, --u;\n\t\t\tg[v].push_back(u);\n\t\t\tg[u].push_back(v);\n\t\t}\n\t\th.assign(n, 0);\n\t\tdfs(0);\n\t\tset<pair<int, int>> cur;\n\t\tforn(i, n) cur.insert({h[i], i});\n\t\tvector<int> ans;\n\t\tint tmp = n;\n\t\twhile (!cur.empty()){\n\t\t\tint v = cur.rbegin()->second;\n\t\t\twhile (v != -1){\n\t\t\t\t--tmp;\n\t\t\t\tcur.erase({h[v], v});\n\t\t\t\tint pv = -1;\n\t\t\t\tfor (int u : g[v]) if (h[u] == h[v] - 1){\n\t\t\t\t\tpv = u;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tv = pv;\n\t\t\t}\n\t\t\tans.push_back(tmp);\n\t\t}\n\t\tfor (int i = 0; i < int(ans.size()); i += 2){\n\t\t\tcout << ans[i] << ' ';\n\t\t}\n\t\tfor (int i = (int(ans.size()) + 1) / 2; i < n - 1; ++i){\n\t\t\tcout << 0 << ' ';\n\t\t}\n\t\tcout << '\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1977",
    "index": "A",
    "title": "Little Nikita",
    "statement": "The little boy Nikita was given some cubes as a present. He decided to build a tower out of them.\n\nInitially, the tower doesn't have any cubes. In one move, Nikita either puts exactly $1$ cube on top of the tower or removes exactly $1$ cube from the top of the tower. Is it possible that after $n$ moves, the resulting tower has exactly $m$ cubes?",
    "tutorial": "Note that one action with the cube changes the parity of the number of cubes in the tower. Therefore, if the parities of $n$ and $m$ do not match, it is impossible to build the tower. Also, if $n < m$, the tower cannot be built either. In all other cases, it is possible to build a tower of height $m$ in $m$ operations, and then add and remove a cube until the operations are exhausted.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main () {\n  ios_base::sync_with_stdio(0); cin.tie(0);\n  int T;\n  cin >> T;\n  while (T--) {\n    int n, m;\n    cin >> n >> m;\n    cout << (n >= m && (n%2) == (m%2) ? \"Yes\" : \"No\") << '\\n';\n  }\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1977",
    "index": "B",
    "title": "Binary Colouring",
    "statement": "You are given a positive integer $x$. Find any array of integers $a_0, a_1, \\ldots, a_{n-1}$ for which the following holds:\n\n- $1 \\le n \\le 32$,\n- $a_i$ is $1$, $0$, or $-1$ for all $0 \\le i \\le n - 1$,\n- $x = \\displaystyle{\\sum_{i=0}^{n - 1}{a_i \\cdot 2^i}}$,\n- There does not exist an index $0 \\le i \\le n - 2$ such that both $a_{i} \\neq 0$ and $a_{i + 1} \\neq 0$.\n\nIt can be proven that under the constraints of the problem, a valid array always exists.",
    "tutorial": "We will iterate over the prefix of $i$ bits and construct a correct answer for the number formed by the prefix bits of the number $x$. We are interested in considering only the one bits, as they are the only ones that affect the value of the number $x$. If we have already placed a one at position $i$ in the answer, we need to somehow add $2^i$ to the number. To do this, we simply zero out the $i$-th bit in the answer and set it at $i + 1$ - this will add $2 \\cdot 2^i = 2^{i+1}$. Now, the $i$-th position in the answer holds $0$. Let's consider what we placed at position $i-1$ in the answer. If it's $0$, then everything is fine; we just place $1$ at position $i$. If it's $1$, we have a situation of [1 1], which we correct by making it [-1 0 1] - placing $-1$ at $i-1$, leaving $0$ at $i$, and placing $1$ at $i+1$. This will add $2^i$ to the sum because $2^i + 2^{i-1} = 2^{i+1} - 2^{i-1}$. The remaining case is when $i-1$ holds $-1$, but this is impossible because our forward operations only place ones, and $-1$ is placed behind. The final time complexity is $O(\\log(x))$ per test case.",
    "code": "#include \"bits/stdc++.h\"\n\n#define all(a) a.begin(), a.end()\n#define pb push_back\ntypedef long long ll;\nusing namespace std;\nmt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());\n \n/// Actual code starts here\nconst int N = 100005;\n \nvoid solve() {\n    ll x;\n    cin >> x;\n    vector<int> res(31, 0);\n    for (int i = 0; i < 30; i++) {\n        if (1ll & (x >> i)) {\n            if (res[i]) {\n                res[i + 1] = 1;\n                res[i] = 0;\n            } else if (i > 0) {\n                if (res[i - 1] == 1) {\n                    res[i + 1] = 1;\n                    res[i - 1] = -1;\n                } else {\n                    res[i] = 1;\n                }\n            } else if (i == 0) {\n                res[i] = 1;\n            }\n        }\n    }\n    cout << 31 << '\\n';\n    for (int i = 0; i <= 30; i++) {\n        cout << res[i] << ' ';\n    }\n    cout << '\\n';\n}\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int tt = 1;\n    cin >> tt;\n    while (tt--)\n        solve();\n}\n",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1977",
    "index": "C",
    "title": "Nikita and LCM",
    "statement": "Nikita is a student passionate about number theory and algorithms. He faces an interesting problem related to an array of numbers.\n\nSuppose Nikita has an array of integers $a$ of length $n$. He will call a subsequence$^\\dagger$ of the array special if its least common multiple (LCM) is not contained in $a$. The LCM of an empty subsequence is equal to $0$.\n\nNikita wonders: what is the length of the longest special subsequence of $a$? Help him answer this question!\n\n$^\\dagger$ A sequence $b$ is a subsequence of $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements, without changing the order of the remaining elements. For example, $[5,2,3]$ is a subsequence of $[1,5,7,8,2,4,3]$.",
    "tutorial": "Try to check if the entire array $a$ can be the answer. First, let's understand if we can take the entire array $a$ as the special subsequence. To do this, find the LCM($a_1, a_2, \\dots, a_n$). If it is greater than max($a_1, a_2, \\dots, a_n$), then obviously such a number is not in the subsequence, because $LCM \\geq max$. After this check, it becomes known that each $a_i \\ | \\ max(a_1, a_2, \\dots, a_n)$. Then we iterate over the divisors of the maximum and greedily check for the presence of a subsequence with such an LCM. If we do this naively, it will be $O(\\sqrt{C} + n \\cdot d(C) \\cdot \\log(C))$, but this is already sufficient. Note that we can count the occurrence of each number and check only the distinct numbers. Then the complexity will be $O(\\sqrt{C} + d(C)^2 \\cdot \\log(C))$.",
    "code": "#include \"bits/stdc++.h\"\n \n#define err(x) cerr << \"[\"#x\"]  \" << (x) << \"\\n\"\n#define errv(x) {cerr << \"[\"#x\"]  [\"; for (const auto& ___ : (x)) cerr << ___ << \", \"; cerr << \"]\\n\";}\n#define errvn(x, n) {cerr << \"[\"#x\"]  [\"; for (auto ___ = 0; ___ < (n); ++___) cerr << (x)[___] << \", \"; cerr << \"]\\n\";}\n#define all(a) a.begin(), a.end()\n#define pb push_back\ntypedef long long ll;\ntypedef long double ld;\nusing namespace std;\nconst int MOD = 1000000007;\nmt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());\n \ntemplate<typename T1, typename T2>\ninline bool relaxmi(T1 &a, const T2 &b) {\n    return a > b ? a = b, true : false;\n}\n \ntemplate<typename T1, typename T2>\ninline bool relaxma(T1 &a, const T2 &b) {\n    return a < b ? a = b, true : false;\n}\n \ndouble GetTime() { return clock() / (double) CLOCKS_PER_SEC; }\n \n/// Actual code starts here\nconst int N = 100005;\n \nint calc(vector<pair<int, int>> &t, int d) {\n    int LCM = 0, cnt = 0;\n    for (auto [j, c]: t) {\n        if (d % j == 0) {\n            if (LCM == 0) LCM = j;\n            else LCM = lcm(LCM, j);\n            cnt += c;\n        }\n    }\n    if (LCM != d) cnt = 0;\n    return cnt;\n}\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> v(n);\n    for (auto &i: v) cin >> i;\n    ll LCM = 1;\n    int mx = *max_element(all(v));\n    for (auto i: v) {\n        LCM = lcm(LCM, i);\n        if (LCM > mx) {\n            cout << n << '\\n';\n            return;\n        }\n    }\n    map<int, int> cnt;\n    for (auto i: v) cnt[i]++;\n    vector<pair<int, int>> t;\n    for (auto i: cnt)\n        t.push_back(i);\n    int res = 0;\n    for (int i = 1; i * i <= mx; i++) {\n        if (mx % i == 0) {\n            if (!cnt.contains(i))\n                relaxma(res, calc(t, i));\n            if (!cnt.contains(mx / i))\n                relaxma(res, calc(t, mx / i));\n        }\n    }\n    cout << res << '\\n';\n}\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int tt = 1;\n    cin >> tt;\n    while (tt--)\n        solve();\n}\n",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1977",
    "index": "D",
    "title": "XORificator",
    "statement": "You are given a binary (consisting only of 0s and 1s) $n \\times m$ matrix. You are also given a XORificator, using which you can invert all the values in a chosen row (i.e. replace 0 with 1 and 1 with 0).\n\nA column in the matrix is considered special if it contains exactly one 1. Your task is to find the maximum number of columns that can be made special at the same time, and the set of rows the XORificator should be used on to achieve that.",
    "tutorial": "Try to fix the specialty of column $i$ and the presence of a one in cell $i, j$. Let's assume that the value in the $i$-th row and $j$-th column is strictly one and it is the only one in the column. Then the entire table is uniquely determined, as well as the XORificator. For each possible state of the XORificator that constructs the required table, Let's maintain a counter. Then the state that maximizes the number of columns with exactly one 1 has the maximum counter. To efficiently maintain the counter, it is necessary to maintain the hash of the XORificator and quickly recalculate it when moving to the next row. The answer can be easily reconstructed by traversing the table again and counting the hash. If the desired hash is obtained, simply output the state of the XORificator. The final time complexity is $O(nm \\log{(nm)})$ or $O(nm)$ if a hash map is used. For hashing, it is convenient to use Zobrist hashing.",
    "code": "#include \"bits/stdc++.h\"\n \nusing namespace std;\n \nmt19937_64 rnd(chrono::steady_clock::now().time_since_epoch().count());\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<vector<bool>> table(n, vector<bool>(m));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < m; ++j) {\n            char c;\n            cin >> c;\n            table[i][j] = c - '0';\n        }\n    }\n    vector<long long> rands(n), rands2(n);\n    for (int i = 0; i < n; ++i) {\n        rands[i] = rnd();\n        rands2[i] = rnd();\n    }\n    map<pair<long long, long long>, int> ans;\n    int res = 0;\n    pair<int, int> ind_ans = {0, 0};\n    for (int j = 0; j < m; ++j) {\n        long long summ = 0, summ2 = 0;\n        for (int i = 0; i < n; ++i) {\n            if (table[i][j]) {\n                summ ^= rands[i];\n                summ2 ^= rands2[i];\n            }\n        }\n        for (int i = 0; i < n; ++i) {\n            summ ^= rands[i];\n            summ2 ^= rands2[i];\n            ans[{summ, summ2}]++;\n            if (res < ans[{summ, summ2}]) {\n                res = ans[{summ, summ2}];\n                ind_ans = {j, i};\n            }\n            summ ^= rands[i];\n            summ2 ^= rands2[i];\n        }\n    }\n    cout << res << \"\\n\";\n    string inds(n, '0');\n    for (int i = 0; i < n; ++i) {\n        if (table[i][ind_ans.first]) {\n            if (i != ind_ans.second) {\n                inds[i] = '1';\n            }\n        } else if (ind_ans.second == i) {\n            inds[i] = '1';\n        }\n    }\n    cout << inds << \"\\n\";\n}\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt = 1;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy",
      "hashing"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1977",
    "index": "E",
    "title": "Tensor",
    "statement": "This is an interactive problem.\n\nYou are given an integer $n$.\n\nThe jury has hidden from you a directed graph with $n$ vertices (numbered from $1$ to $n$) and some number of edges. You additionally know that:\n\n- The graph only contains edges of the form $i \\leftarrow j$, where $1 \\le i < j \\le n$.\n- For any three vertices $1 \\le i < j < k \\le n$, at least one of the following holds$^\\dagger$:\n\n- Vertex $i$ is reachable from vertex $j$, or\n- Vertex $i$ is reachable from vertex $k$, or\n- Vertex $j$ is reachable from vertex $k$.\n\nYou want to color each vertex in either black or white such that for any two vertices $i$ and $j$ ($1 \\le i < j \\le n$) of the same color, vertex $i$ is reachable from vertex $j$.\n\nTo do that, you can ask queries of the following type:\n\n- ? i j — is vertex $i$ reachable from vertex $j$ ($1 \\le i < j \\le n$)?\n\nFind any valid vertex coloring of the hidden graph in at most $2 \\cdot n$ queries. It can be proven that such a coloring always exists.\n\nNote that the grader is \\textbf{not} adaptive: the graph is fixed before any queries are made.\n\n$^\\dagger$ Vertex $a$ is reachable from vertex $b$ if there exists a path from vertex $b$ to vertex $a$ in the graph.",
    "tutorial": "First, let's understand why 2 colors are indeed sufficient. Notice that the reachability relation in a graph defines a Partially Ordered Set. According to Dilworth's Theorem, the size of the maximum antichain is equal to the minimum number of chains that cover the Partially Ordered Set. Note that the condition on the reachability of pairs of vertices within any triplet implies a constraint on the maximum size of the antichain. It is simply no more than 2. Therefore, 2 colors are indeed sufficient. The remaining task is to understand how to explicitly construct these 2 chains. We will build this inductively. Let's maintain 3 stacks - the last vertices painted in black, white, and red respectively. These will correspond to the chains we are building. Suppose we have built chains on $n$ vertices and want to build them on $n + 1$: If the white or black stacks are empty, simply add vertex $n+1$ to the empty stack. If the white or black stacks are empty, simply add vertex $n+1$ to the empty stack. If the red stack is empty: If the red stack is empty: Ask about the reachability of the last vertices in the white and black stacks from vertex $n+1$. Ask about the reachability of the last vertices in the white and black stacks from vertex $n+1$. If both vertices are reachable, put vertex $n+1$ in the red stack. If both vertices are reachable, put vertex $n+1$ in the red stack. If only one vertex is reachable, put vertex $n+1$ in the stack whose last vertex is reachable from $n+1$. If only one vertex is reachable, put vertex $n+1$ in the stack whose last vertex is reachable from $n+1$. The case where neither vertex is reachable is impossible as it contradicts the condition. The case where neither vertex is reachable is impossible as it contradicts the condition. If the red stack is not empty: If the red stack is not empty: Ask about the reachability of the last vertex in the red stack from vertex $n+1$. Ask about the reachability of the last vertex in the red stack from vertex $n+1$. If it is reachable, put it in the red stack. If it is reachable, put it in the red stack. If it is not reachable, ask about the end of the white stack. If it is not reachable, ask about the end of the white stack. If the vertex at the end of the white stack is not reachable, then the vertex at the end of the black stack must be reachable, otherwise, it contradicts the problem's condition. If the vertex at the end of the white stack is not reachable, then the vertex at the end of the black stack must be reachable, otherwise, it contradicts the problem's condition. Color vertex $n+1$ black if the black vertex is reachable or white if the white vertex is reachable. Color vertex $n+1$ black if the black vertex is reachable or white if the white vertex is reachable. Recolor all vertices in the red stack to the opposite color relative to vertex $n+1$. We can do this because, by construction, all vertices in the white and black stacks are reachable from all vertices in the red stack. Recolor all vertices in the red stack to the opposite color relative to vertex $n+1$. We can do this because, by construction, all vertices in the white and black stacks are reachable from all vertices in the red stack. Do not forget to clear the red stack. Do not forget to clear the red stack. Each time a new vertex is added, no more than 2 queries are used. Therefore, we will use no more than $2 \\cdot n$ queries in total. During the algorithm, all operations are performed in $O(1)$ time, resulting in an overall complexity of $O(n)$. As an exercise for the reader, try to prove the lower bound on the number of queries.",
    "code": "#include \"bits/stdc++.h\"\n \n#define err(x) cerr << \"[\"#x\"]  \" << (x) << \"\\n\"\n#define errv(x) {cerr << \"[\"#x\"]  [\"; for (const auto& ___ : (x)) cerr << ___ << \", \"; cerr << \"]\\n\";}\n#define errvn(x, n) {cerr << \"[\"#x\"]  [\"; for (auto ___ = 0; ___ < (n); ++___) cerr << (x)[___] << \", \"; cerr << \"]\\n\";}\n#define all(a) a.begin(), a.end()\n#define pb push_back\ntypedef long long ll;\ntypedef long double ld;\nusing namespace std;\nconst int MOD = 1000000007;\nmt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());\n \ntemplate<typename T1, typename T2>\ninline bool relaxmi(T1 &a, const T2 &b) {\n    return a > b ? a = b, true : false;\n}\n \ntemplate<typename T1, typename T2>\ninline bool relaxma(T1 &a, const T2 &b) {\n    return a < b ? a = b, true : false;\n}\n \ndouble GetTime() { return clock() / (double) CLOCKS_PER_SEC; }\n \n/// Actual code starts here\nconst int N = 100005;\n \nbool ask(int i, int j) {\n    cout << \"? \" << j << ' ' << i << endl;\n    string resp;\n    cin >> resp;\n    if (resp == \"-1\") assert(false);\n    if (resp == \"YES\") return true;\n    else return false;\n}\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> st, st2, st3;\n    st = {1};\n    for (int i = 2; i <= n; i++) {\n        if (st2.empty()) {\n            if (ask(i, st.back())) {\n                st.push_back(i);\n            } else {\n                st2.push_back(i);\n            }\n        } else if (st3.empty()) {\n            int ok1 = ask(i, st.back()), ok2 = ask(i, st2.back());\n            if (ok1 && ok2) {\n                st3.push_back(i);\n            } else if (ok1) {\n                st.push_back(i);\n            } else if (ok2) {\n                st2.push_back(i);\n            } else {\n                assert(false);\n            }\n        } else {\n            if (ask(i, st3.back())) {\n                st3.push_back(i);\n            } else {\n                if (ask(i, st.back())) {\n                    st.push_back(i);\n                    for (auto j: st3)\n                        st2.push_back(j);\n                    st3.clear();\n                } else {\n                    st2.push_back(i);\n                    for (auto j: st3)\n                        st.push_back(j);\n                    st3.clear();\n                }\n            }\n        }\n    }\n    if (!st3.empty()) {\n        for (auto i: st3)\n            st.push_back(i);\n        st3.clear();\n    }\n    vector<int> colors(n + 1);\n    for (auto i: st2)\n        colors[i] = 1;\n    cout << \"! \";\n    for (int i = 1; i <= n; i++) cout << colors[i] << ' ';\n    cout << endl;\n}\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int tt = 1;\n    cin >> tt;\n    while (tt--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "interactive"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1978",
    "index": "A",
    "title": "Alice and Books",
    "statement": "Alice has $n$ books. The $1$-st book contains $a_1$ pages, the $2$-nd book contains $a_2$ pages, $\\ldots$, the $n$-th book contains $a_n$ pages. Alice does the following:\n\n- She divides all the books into two non-empty piles. Thus, each book ends up in exactly one of the two piles.\n- Alice reads one book with the \\textbf{highest number} in each pile.\n\nAlice loves reading very much. Help her find the maximum total number of pages she can read by dividing the books into two piles.",
    "tutorial": "Note that we will always be required to take a book with the number $n$. Thus, the answer can be all pairs of the form $(k, n)$, where $k < n$. We will find a pair with the maximum sum among these, and it will be the answer.",
    "code": "#include <random>\n#include <vector>\n#include <iostream>\n#include <set>\n#include <map>\n#include <algorithm>\n \nusing namespace std;\n \n#define fi first\n#define se second\n#define all(x) (x).begin(), (x).end()\n#define ll long long\n#define pii pair<int, int>\n#define pb emplace_back\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (auto &c : a) cin >> c;\n        int mx = 0;\n        for (int i = 0; i < n - 1; i++) mx = max(mx, a[i]);\n        cout << mx + a[n - 1] << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1978",
    "index": "B",
    "title": "New Bakery",
    "statement": "Bob decided to open a bakery. On the opening day, he baked $n$ buns that he can sell. The usual price of a bun is $a$ coins, but to attract customers, Bob organized the following promotion:\n\n- Bob chooses some integer $k$ ($0 \\le k \\le \\min(n, b)$).\n- Bob sells the first $k$ buns at a modified price. In this case, the price of the $i$-th ($1 \\le i \\le k$) sold bun is $(b - i + 1)$ coins.\n- The remaining $(n - k)$ buns are sold at $a$ coins each.\n\nNote that $k$ can be equal to $0$. In this case, Bob will sell all the buns at $a$ coins each.\n\nHelp Bob determine the maximum profit he can obtain by selling all $n$ buns.",
    "tutorial": "If $b < a$, then the answer is obviously equal to $a \\cdot n$. Otherwise, the profit will be maximized when $k = \\min(b - a, n)$. Indeed, if we take $k$ larger, then Bob will sell some buns for less than $a$ coins, which is not profitable. If we take $k$ smaller, then he will sell some buns for $a$ coins, although he could have sold them for more. Knowing that $a + (a + 1) + \\ldots + (b - 1) + b = \\frac{a + b}{2} \\cdot (b - a + 1)$, we can find the answer. It will be equal to $\\frac{b + (b - k + 1)}{2} \\cdot k + (n - k) \\cdot a$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        long long n, a, b;\n        cin >> n >> a >> b;\n        if (b <= a) {\n            cout << n * a << endl;\n        } else {\n            long long k = min(b &mdash; a + 1, n);\n            cout << (b &mdash; k + 1) * n + k * (k &mdash; 1) / 2 << endl;\n        }\n    }\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "ternary search"
    ],
    "rating": 800
  },
  {
    "contest_id": "1978",
    "index": "C",
    "title": "Manhattan Permutations",
    "statement": "Let's call the Manhattan value of a permutation$^{\\dagger}$ $p$ the value of the expression $|p_1 - 1| + |p_2 - 2| + \\ldots + |p_n - n|$.\n\nFor example, for the permutation $[1, 2, 3]$, the Manhattan value is $|1 - 1| + |2 - 2| + |3 - 3| = 0$, and for the permutation $[3, 1, 2]$, the Manhattan value is $|3 - 1| + |1 - 2| + |2 - 3| = 2 + 1 + 1 = 4$.\n\nYou are given integers $n$ and $k$. Find a permutation $p$ of length $n$ such that its Manhattan value is equal to $k$, or determine that no such permutation exists.\n\n$^{\\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Notice that if $k$ is odd, then there is no solution. Also notice that the maximum $max_k$ is achieved with the permutation $[n, n - 1, n - 2, ..., 1]$, so if $k > max_k$, then there is also no solution. It is claimed that for any other $k$, a solution exists. Let's consider what happens if we swap $x$ and $1$ in the identity permutation. The Manhattan value for such a permutation will be equal to $|x - 1| + |x - 1| = 2 \\cdot |x - 1|$. Then any even $k$ from $0$ to $2 \\cdot (n - 1)$ can be achieved. If $k > 2 \\cdot (n - 1)$, let's swap $1$ and $n$ elements. Notice that we have reduced the problem to a smaller size of $(n - 2)$, just now the indices start from $2$ instead of $1$. Now we can do exactly the same as with the identity permutation, i.e., swap $2$ with some $x$ ($x > 1$ and $x < n$). The value of the permutation will change by $|x - 2| \\cdot 2$, so any even $k$ from $0$ to $2 \\cdot (n - 1) + 2 \\cdot (n - 3)$ can be achieved. Notice that if we continue to do this further, in the end we will get the permutation $[n, n - 1, ..., 1]$, and we have proved that any even $k$ from $0$ to $max_k$ is achievable. Hence, it is clear how to reconstruct the permutation itself in $O(n)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    int T = 1;\n    cin >> T;\n    while (T--) {\n        int n;\n        ll k;\n        cin >> n >> k;\n        ll max_s = 0;\n        for (int i = 0; i < n; i++) max_s += abs(n &mdash; 1 &mdash; i &mdash; i);\n        if (k % 2 != 0 || k > max_s) {\n            cout << \"No\\n\";\n        } else {\n            cout << \"Yes\\n\";\n            vector<int> p(n);\n            k /= 2;\n            iota(p.begin(), p.end(), 0);\n            for (int i = 0; k > 0; i++) {\n                if (k >= n &mdash; 1 &mdash; 2 * i) {\n                    swap(p[i], p[n &mdash; 1 &mdash; i]);\n                    k -= n &mdash; 1 &mdash; 2 * i;\n                } else {\n                    swap(p[i], p[i + k]);\n                    k = 0;\n                }\n            }\n            for (int i = 0; i < n; i++) {\n                cout << p[i] + 1 << \" \";\n            }\n            cout << \"\\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1978",
    "index": "D",
    "title": "Elections",
    "statement": "Elections are taking place in Berland. There are $n$ candidates participating in the elections, numbered from $1$ to $n$. The $i$-th candidate has $a_i$ fans who will vote for him. Additionally, there are $c$ people who are undecided about their favorite candidate, let's call them undecided. Undecided people will vote for the candidate with the lowest number.\n\nThe candidate who receives the maximum number of votes wins the elections, and if multiple candidates receive the same maximum number of votes, the candidate with the lowest number among them wins.\n\nYou found these elections too boring and predictable, so you decided to exclude some candidates from them. If you do not allow candidate number $i$ to participate in the elections, all $a_i$ of his fans will become undecided, and will vote for the candidate with the lowest number.\n\nYou are curious to find, for each $i$ from $1$ to $n$, the minimum number of candidates that need to be excluded from the elections for candidate number $i$ to win the elections.",
    "tutorial": "Notice that if candidate $i$ does not win initially (when no one is removed), then for their victory, we must definitely remove all candidates with numbers less than $i$. Because if someone remains unremoved with a number less than $i$, then the votes for candidate $i$ will not increase, and the maximum number of votes for someone else will not decrease. Let's find the winner of the election initially, for them the answer is $0$, for all other candidates we need to remove all people with numbers less than $i$. But sometimes these removals alone may not be enough, so we need to additionally remove several candidates so that their fans' votes go to us. Notice that then it is enough to remove only one candidate with the maximum $a_i$, then we will definitely win, so the answer for candidate $i$ is either $0$, or $i$, or $i + 1$. So we end up with a solution which works in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nvoid solve() {\n    int n, c;\n    cin >> n >> c;\n\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n\n    if (n == 1) {\n        cout << \"0\\n\";\n        return;\n    }\n\n    int mx = *max_element(a.begin() + 1, a.end());\n    int mxc = max(a[0] + c, mx);\n    int winner = mxc == a[0] + c ? 0 : find(a.begin() + 1, a.end(), mx) - a.begin();\n    ll sum = c;\n    for (int i = 0; i < n; sum += a[i], ++i) {\n        int answer;\n        if (i == winner) {\n            answer = 0;\n        } else if (sum + a[i] >= mx) {\n            answer = i;\n        } else {\n            answer = i + 1;\n        }\n        cout << answer << \" \\n\"[i == n - 1];\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int test = 1;\n    cin >> test;\n    \n    while (test--) {\n        solve();\n    }\n\n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1978",
    "index": "E",
    "title": "Computing Machine",
    "statement": "Sasha has two binary strings $s$ and $t$ of the same length $n$, consisting of the characters 0 and 1.\n\nThere is also a computing machine that can perform two types of operations on binary strings $a$ and $b$ of the same length $k$:\n\n- If $a_{i} = a_{i + 2} =$ 0, then you can assign $b_{i + 1} :=$ 1 ($1 \\le i \\le k - 2$).\n- If $b_{i} = b_{i + 2} =$ 1, then you can assign $a_{i + 1} :=$ 1 ($1 \\le i \\le k - 2$).\n\nSasha became interested in the following: if we consider the string $a=s_ls_{l+1}\\ldots s_r$ and the string $b=t_lt_{l+1}\\ldots t_r$, what is the maximum number of 1 characters in the string $a$ that can be obtained using the computing machine. Since Sasha is very curious but lazy, it is up to you to answer this question for several pairs $(l_i, r_i)$ that interest him.",
    "tutorial": "Notice that it is advantageous to perform only operations of the first type first, and then only operations of the second type. Perform all possible operations of the first type on the string $t$ and save it in $t'$. Perform all possible operations of the second type on the string $s$, using $t'$, and save it in $s'$. Calculate the prefix sums on the string $s'$. Let $len$ be the length of the query range. The answer to queries with small length ranges ($len < 5$) can be computed by simulating the proposed process. For longer strings, it can be guaranteed that in the string $a$ with the maximum number of 1 characters, $a_{3}a_{4}\\ldots a_{len - 2}$ will match the characters $s'_{3}s'_{4}\\ldots s'_{len - 2}$, their count can be found using prefix sums. Separately check if $a_{1}$, $a_{2}$, $a_{len - 1}$, $a_{len}$ can become 1.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main () {\n  ios_base::sync_with_stdio(0); cin.tie(0);\n  int T;\n  cin >> T;\n  while (T--) {\n    int n;\n    string s, t;\n    cin >> n >> s >> t;\n    auto get_range = [&] (int i) {\n      if (s[i] == '1') return make_pair(i, i);\n      int l = -1, r = -1;\n      if (i > 0 && t[i-1] == '1') l = i-1;\n      else if (i > 1 && t[i-1] == '0' && s[i-2] == '0') l = i-2;\n      if (i+1 < n && t[i+1] == '1') r = i+1;\n      else if (i+2 < n && t[i+1] == '0' && s[i+2] == '0') r = i+2;\n      if (l == -1) r = -1;\n      if (r == -1) l = -1;\n      return make_pair(l, r);\n    };\n \n    vector<int> pref(n+1);\n    for (int i = 0; i < n; i++) pref[i+1] = pref[i] + (get_range(i).first != -1);\n \n    int q;\n    cin >> q;\n    while (q--) {\n      int l, r;\n      cin >> l >> r;\n      int ans = 0;\n      if (r-l <= 5) {\n        for (int i = l-1; i < r; i++) {\n          auto [ll, rr] = get_range(i);\n          if (ll >= l-1 && rr < r) ans++;\n        }\n      }\n      else {\n        ans = pref[r] - pref[l-1];\n        for (int j: {l-1, l, r-2, r-1}) {\n          auto [ll, rr] = get_range(j);\n          if (ll != -1 && (ll < l-1 || rr >= r)) ans--;\n        }\n      }\n      cout << ans << '\\n';\n    }\n  }\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1978",
    "index": "F",
    "title": "Large Graph",
    "statement": "Given an array $a$ of length $n$. Let's construct a square matrix $b$ of size $n \\times n$, in which the $i$-th row contains the array $a$ cyclically shifted to the right by $(i - 1)$. For example, for the array $a = [3, 4, 5]$, the obtained matrix is\n\n$$b = \\begin{bmatrix} 3 & 4 & 5 \\\\ 5 & 3 & 4 \\\\ 4 & 5 & 3 \\end{bmatrix}$$\n\nLet's construct the following graph:\n\n- The graph contains $n^2$ vertices, each of which corresponds to one of the elements of the matrix. Let's denote the vertex corresponding to the element $b_{i, j}$ as $(i, j)$.\n- We will draw an edge between vertices $(i_1, j_1)$ and $(i_2, j_2)$ if $|i_1 - i_2| + |j_1 - j_2| \\le k$ and $\\gcd(b_{i_1, j_1}, b_{i_2, j_2}) > 1$, where $\\gcd(x, y)$ denotes the greatest common divisor of integers $x$ and $y$.\n\nYour task is to calculate the number of connected components$^{\\dagger}$ in the obtained graph.\n\n$^{\\dagger}$A connected component of a graph is a set of vertices in which any vertex is reachable from any other via edges, and adding any other vertex to the set violates this rule.",
    "tutorial": "Notice that since we have cyclic shifts to the right and k > 1, the diagonals parallel to the main one will be in the same connected component, except for the case with ones. Diagonals consisting of ones will be counted separately and forgotten. After that, we can solve the problem for the one-dimensional case, where each element is a representative of its diagonal. By definition, if the GCD of some pair of elements is greater than $1$, then this means that they are both divisible by some prime number. Let's find all the elements of the array-diagonals that are divisible by each prime number. Let the indices of the current prime number be $c_1, c_2, \\ldots, c_t$. We will draw edges between $c_i$ and $c_{i + 1}$ if $c_{i + 1} - c_{i} \\leqslant k$. It is claimed that the connected components in such a graph will coincide with the connected components if we draw edges between all valid pairs. Indeed, if there is an edge between two elements in the complete graph, this means that the distance between them is not greater than $k$, and we can reach them in the new graph either by one edge or through elements that are divisible by the same prime number. Using the sieve of Eratosthenes, we can quickly factorize all numbers into prime divisors, after which the number of connected components in the graph can be calculated using DSU or DFS. The time complexity of this solution is $O(n \\log \\log n)$.",
    "code": "#include <iostream>\n#include <vector>\n#include <map>\n#include <set>\n#include <queue>\n#include <algorithm>\n#include <string>\n#include <cmath>\n#include <cstdio>\n#include <iomanip>\n#include <fstream>\n#include <cassert>\n#include <cstring>\n#include <unordered_set>\n#include <unordered_map>\n#include <numeric>\n#include <ctime>\n \nusing namespace std;\n \nusing ll = long long;\n \nconst int MAXA = 1e6;\n \nint n, k;\nvector<int> a;\nvector<int> primes_x[MAXA + 1];\nunordered_map<int, int> last_ind_p;\nvector<bool> is_prime(MAXA + 1, true);\nvector<int> primes;\n \nvoid read() {\n\tcin >> n >> k;\n\ta.assign(n, 0);\n\tfor (int& elem : a) {\n\t\tcin >> elem;\n\t}\n}\n \nvector<int> p, sz, p_rs;\n \nint col(int A) {\n\treturn (A == p[A] ? A : p[A] = col(p[A]));\n}\n \nvoid unique(int A, int B) {\n\tA = col(A); B = col(B);\n\tif (A == B) return;\n\tif (sz[A] < sz[B]) {\n\t\tswap(A, B);\n\t}\n\tp[B] = A;\n\tsz[A] += sz[B];\n}\n \nvoid solve() {\n    last_ind_p.clear();\n\tvector<int> aa;\n\tfor (int i = 1; i < n; i++) {\n\t\taa.push_back(a[i]);\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\taa.push_back(a[i]);\n\t}\n\ta = aa;\n\tint n2 = n;\n\tn = a.size();\n\tp.assign(n, -1);\n\tp_rs.assign(n, -1);\n\tsz.assign(n, -1);\n\tfor (int i = 0; i < n; i++) {\n\t\tp[i] = i;\n\t\tsz[i] = 1;\n\t}\n \n\tfor (int i = 0; i < n2; i++) {\n\t\tp_rs[i] = i + 1;\n\t\tp_rs[2 * n2 - 2 - i] = i + 1;\n\t}\n\tvector<int> a2 = a;\n\tsort(a2.begin(), a2.end());\n\ta2.resize(unique(a2.begin(), a2.end()) - a2.begin());\n    unordered_set<int> to_clean;\n\tfor (int elem : a2) {\n\t\tint cur_elem = elem;\n\t\tfor (ll p : primes) {\n\t\t\tif (p * p > elem) break;\n\t\t\tif (elem % p == 0) {\n\t\t\t\tprimes_x[cur_elem].push_back(p);\n                if (primes_x[cur_elem].size() == 1) {\n                    to_clean.insert(cur_elem);\n                }\n\t\t\t}\n\t\t\twhile (elem % p == 0) {\n\t\t\t\telem /= p;\n\t\t\t}\n\t\t}\n\t\tif (elem > 1) {\n\t\t\tprimes_x[cur_elem].push_back(elem);\n            if (primes_x[cur_elem].size() == 1) {\n                to_clean.insert(cur_elem);\n            }\n\t\t}\n\t}\n \n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int cur_p : primes_x[a[i]]) {\n\t\t\tif (last_ind_p.count(cur_p) && i - last_ind_p[cur_p] <= k) {\n\t\t\t\tunique(last_ind_p[cur_p], i);\n\t\t\t}\n\t\t\tlast_ind_p[cur_p] = i;\n\t\t}\n\t}\n    for (int i : to_clean)\n        primes_x[i].clear();\n}\n \nvoid write() {\n\tll ans = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tif (p[i] == i) {\n\t\t\tif (a[i] > 1) {\n\t\t\t\tans += 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tans += p_rs[i];\n\t\t\t}\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n \nint main() {\n    for (ll i = 2; i <= MAXA; i++) {\n        if (is_prime[i]) {\n            primes.push_back(i);\n            for (ll j = i * i; j <= MAXA; j += i) {\n                is_prime[j] = false;\n            }\n        }\n    }\n\tios_base::sync_with_stdio(false); cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        read();\n        solve();\n        write();\n    }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "number theory",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1979",
    "index": "A",
    "title": "Guess the Maximum",
    "statement": "Alice and Bob came up with a rather strange game. They have an array of integers $a_1, a_2,\\ldots, a_n$. Alice chooses a certain integer $k$ and tells it to Bob, then the following happens:\n\n- Bob chooses two integers $i$ and $j$ ($1 \\le i < j \\le n$), and then finds the maximum among the integers $a_i, a_{i + 1},\\ldots, a_j$;\n- If the obtained maximum is \\textbf{strictly greater} than $k$, Alice wins, otherwise Bob wins.\n\nHelp Alice find the maximum $k$ at which she is guaranteed to win.",
    "tutorial": "Let $m$ be the maximum among the numbers $a_i, a_{i + 1},\\ldots, a_j$. Notice that there always exists such $k$ that $i \\le k < j$ and $a_k = m$ or $a_{k + 1} = m$. Therefore, we can assume that Bob always chooses the pair of numbers $p$ and $p + 1$ ($1 \\le p < n$) as $i$ and $j$. Therefore you need to consider the maximums in pairs of adjacent elements and take the minimum among them. Let $min$ be the found minimum, then it is obvious that the answer is equal to $min - 1$.",
    "code": "#include <iostream>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        int a[n];\n        for (int& i : a) {\n            cin >> i;\n        }\n        int mini = max(a[0], a[1]);\n        for (int i = 1; i < n - 1; i++) {\n            mini = min(mini, max(a[i], a[i + 1]));\n        }\n        cout << mini - 1 << \"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1979",
    "index": "B",
    "title": "XOR Sequences",
    "statement": "You are given two distinct non-negative integers $x$ and $y$. Consider two infinite sequences $a_1, a_2, a_3, \\ldots$ and $b_1, b_2, b_3, \\ldots$, where\n\n- $a_n = n \\oplus x$;\n- $b_n = n \\oplus y$.\n\nHere, $x \\oplus y$ denotes the bitwise XOR operation of integers $x$ and $y$.\n\nFor example, with $x = 6$, the first $8$ elements of sequence $a$ will look as follows: $[7, 4, 5, 2, 3, 0, 1, 14, \\ldots]$. Note that the indices of elements start with $1$.\n\nYour task is to find the length of the longest common subsegment$^\\dagger$ of sequences $a$ and $b$. In other words, find the maximum integer $m$ such that $a_i = b_j, a_{i + 1} = b_{j + 1}, \\ldots, a_{i + m - 1} = b_{j + m - 1}$ for some $i, j \\ge 1$.\n\n$^\\dagger$A subsegment of sequence $p$ is a sequence $p_l,p_{l+1},\\ldots,p_r$, where $1 \\le l \\le r$.",
    "tutorial": "Look at samples. Consider two numbers $v$ and $u$ such that $x \\oplus v = y \\oplus u$. Then consider the numbers $x \\oplus (v + 1)$ and $y \\oplus (u + 1)$. Let's look at the last bit of $v$ and $u$. Possible scenarios: Both bits are equal to $0$ - adding one will change the bits at the same positions, therefore $x \\oplus (v + 1) = y \\oplus (u + 1)$; Both bits are equal to $1$ - adding one will change the bits at the same positions and also add one to the next bit, therefore we can similarly consider the next bit; Bits are different - adding one to the zero bit will only change one bit, while the subsequent bit of the other number will be changed. This means that $x \\oplus (v + 1) \\neq y \\oplus (u + 1)$. It is clear that we need to maximize the number of zeros in the maximum matching suffix of $u$ and $v$. Obviously, this number is equal to the maximum matching suffix of $x$ and $y$. Let $k$ be the length of the maximum matching suffix of $x$ and $y$, then the answer is $2^k$. This can be calculated in $O(\\log C)$ time for one test case, where $C$ is the limit on $x$ and $y$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int a, b;\n        cin >> a >> b;\n        \n        for (int i = 0; i < 30; i++) {\n            if ((a & (1 << i)) != (b & (1 << i))) {\n                cout << (1ll << i) << \"\\n\";\n                break;\n            }\n        }\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1979",
    "index": "C",
    "title": "Earning on Bets",
    "statement": "You have been offered to play a game. In this game, there are $n$ possible outcomes, and for each of them, you must bet a certain \\textbf{integer} amount of coins. In the event that the $i$-th outcome turns out to be winning, you will receive back the amount of coins equal to your bet on that outcome, multiplied by $k_i$. Note that \\textbf{exactly one} of the $n$ outcomes will be winning.\n\nYour task is to determine how to distribute the coins in such a way that you will come out ahead in the event of \\textbf{any} winning outcome. More formally, the total amount of coins you bet on all outcomes must be \\textbf{strictly less} than the number of coins received back for each possible winning outcome.",
    "tutorial": "Try to come up with a condition for the existence of an answer. Let $S$ be the total amount of coins placed on all possible outcomes. Then, if the coefficient for winning is $k_i$, we have to place more than $\\frac{S}{k_i}$ on this outcome. We can obtain the following inequality: $\\sum_{i = 1}^n \\frac{S}{k_i} < S.$ Dividing both sides by $S$, we obtain the necessary and sufficient condition for the existence of an answer: $\\sum_{i = 1}^n \\frac{1}{k_i} < 1.$ This check can be performed by reducing all fractions to a common denominator. Notice that the numerators of the reduced fractions correspond to the required bets on the outcomes.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n\nint gcd(int a, int b) {\n    while (b != 0) {\n        int tmp = a % b;\n        a = b;\n        b = tmp;\n    }\n    return a;\n}\nint lcm(int a, int b) {\n    return a * b / gcd(a, b);\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector <int> k(n);\n    for (int i = 0; i < n; i++) {\n        cin >> k[i];\n    }\n    \n    int z = 1;\n    for (int i = 0; i < n; i++) {\n        z = lcm(z, k[i]);\n    }\n    \n    int suma = 0;\n    for (int i = 0; i < n; i++) {\n        suma += z / k[i];\n    }\n    \n    if (suma < z) {\n        for (int i = 0; i < n; i++) {\n            cout << z / k[i] << \" \";\n        }\n        cout << \"\\n\";\n    } else {\n        cout << -1 << \"\\n\";\n    }\n}\n\nsigned main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "constructive algorithms",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1979",
    "index": "D",
    "title": "Fixing a Binary String",
    "statement": "You are given a binary string $s$ of length $n$, consisting of zeros and ones. You can perform the following operation \\textbf{exactly once}:\n\n- Choose an integer $p$ ($1 \\le p \\le n$).\n- Reverse the substring $s_1 s_2 \\ldots s_p$. After this step, the string $s_1 s_2 \\ldots s_n$ will become $s_p s_{p-1} \\ldots s_1 s_{p+1} s_{p+2} \\ldots s_n$.\n- Then, perform a cyclic shift of the string $s$ to the left $p$ times. After this step, the initial string $s_1s_2 \\ldots s_n$ will become $s_{p+1}s_{p+2} \\ldots s_n s_p s_{p-1} \\ldots s_1$.\n\nFor example, if you apply the operation to the string 110001100110 with $p=3$, after the second step, the string will become {\\textbf{011}001100110}, and after the third step, it will become {001100110\\textbf{011}}.\n\nA string $s$ is called $k$-proper if two conditions are met:\n\n- $s_1=s_2=\\ldots=s_k$;\n- $s_{i+k} \\neq s_i$ for any $i$ ($1 \\le i \\le n - k$).\n\nFor example, with $k=3$, the strings 000, 111000111, and 111000 are $k$-proper, while the strings 000000, 001100, and 1110000 are not.\n\nYou are given an integer $k$, which \\textbf{is a divisor} of $n$. Find an integer $p$ ($1 \\le p \\le n$) such that after performing the operation, the string $s$ becomes $k$-proper, or determine that it is impossible. Note that if the string is initially $k$-proper, you still need to apply exactly one operation to it.",
    "tutorial": "Let's consider the block of characters at the end. Notice that their quantity cannot decrease. Let $x$ be the number of identical characters at the end; there are three possible cases: $x = k$ - it is enough to find any block of length greater than $k$ and separate a block of length $k$ from it; $x > k$ - obviously, there is no solution; $x < k$ - find a block of length $k - x$ or $2k - x$ and separate a block of length $k - x$ from it. This solution works in $O(n)$, but it is not the only correct one. Your solution may differ significantly from the one proposed.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, k;\n        cin >> n >> k;\n        \n        string s;\n        cin >> s;\n        \n        int x = 0;\n        for (int i = n - 1; i >= 0; i--) {\n            if (s[i] == s[n - 1]) {\n                x++;\n            } else {\n                break;\n            }\n        }\n        \n        auto check = [&]() {\n            for (int i = 0; i < k; i++) {\n                if (s[i] != s[0]) return false;\n            }\n            for (int i = 0; i + k < n; i++) {\n                if (s[i] == s[i + k]) return false;\n            }\n            return true;\n        };\n        \n        auto operation = [&](int p) {\n            reverse(s.begin(), s.begin() + p);\n            s = s.substr(p, (int)s.size() - p) + s.substr(0, p);\n            if (check()) {\n                cout << p << \"\\n\";\n            } else {\n                cout << -1 << \"\\n\";\n            }\n        };\n        \n        if (x == k) {\n            int p = n;\n            for (int i = n - 1 - k; i >= 0; i--) {\n                if (s[i] == s[i + k]) {\n                    p = i + 1;\n                    break;\n                }\n            }\n            operation(p);\n        } else if (x > k) {\n            cout << -1 << \"\\n\";\n        } else {\n            bool was = false;\n            for (int i = 0; i < n; i++) {\n                if (s[i] != s.back()) continue;\n                int j = i;\n                while (j + 1 < n && s[i] == s[j + 1]) {\n                    j++;\n                }\n                if (j - i + 1 + x == k) {\n                    operation(j + 1);\n                    was = true;\n                    break;\n                } else if (j - i + 1 - k + x == k) {\n                    operation(i + k - x);\n                    was = true;\n                    break;\n                }\n                i = j;\n            }\n            if (!was) {\n                operation(n);\n            }\n        }\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dp",
      "greedy",
      "hashing",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1979",
    "index": "E",
    "title": "Manhattan Triangle",
    "statement": "The Manhattan distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is defined as: $$|x_1 - x_2| + |y_1 - y_2|.$$\n\nWe call a Manhattan triangle three points on the plane, the Manhattan distances between each pair of which are equal.\n\nYou are given a set of pairwise distinct points and an \\textbf{even} integer $d$. Your task is to find any Manhattan triangle, composed of three distinct points from the given set, where the Manhattan distance between any pair of vertices is equal to $d$.",
    "tutorial": "In every Manhattan triangle there are two points such that $|x_1 - x_2| = |y_1 - y_2|$. Note this fact: in every Manhattan triangle there are two points such that $|x_1 - x_2| = |y_1 - y_2|$. Let's start with distributing all points with their $(x + y)$ value. For each point $(x; y)$ find point $(x + d / 2; y - d / 2)$ using lower bound method in corresponding set. Then we have to find the third point: it can be in either $(x + y + d)$ or $(x + y - d)$ diagonal. Borders at $x$ coordinate for them are $[x + d / 2; x + d]$ and $[x - d / 2; x]$ - it can be found using the same lower bound method. Then, distribute all points with $(x - y)$ value and do the same algorithm. Total time complexity is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int MAXC = 1e5;\nconst int MAXD = 4e5 + 10;\n\nset <pair <int, int>> diag[MAXD];\n\nvoid solve() {\n    int n, d;\n    cin >> n >> d;\n    \n    vector <int> x(n), y(n);\n    for (int i = 0; i < n; i++) {\n        cin >> x[i] >> y[i];\n        x[i] += MAXC;\n        y[i] += MAXC;\n    }\n    \n    bool found = false;\n    {\n        for (int i = 0; i < n; i++) {\n            diag[x[i] + y[i]].insert({x[i], i});\n        }\n        for (int i = 0; i < n; i++) {\n            auto it1 = diag[x[i] + y[i]].lower_bound({x[i] + d / 2, -1});\n            if (it1 == diag[x[i] + y[i]].end() || it1->first != x[i] + d / 2) continue;\n            if (x[i] + y[i] + d < MAXD) {\n                auto it2 = diag[x[i] + y[i] + d].lower_bound({x[i] + d / 2, -1});\n                if (it2 != diag[x[i] + y[i] + d].end() && it2->first <= it1->first + d / 2) {\n                    cout << i + 1 << \" \" << it1->second + 1 << \" \" << it2->second + 1 << \"\\n\";\n                    found = true;\n                    break;\n                }\n            }\n            if (x[i] + y[i] - d >= 0) {\n                auto it2 = diag[x[i] + y[i] - d].lower_bound({x[i] - d / 2, -1});\n                if (it2 != diag[x[i] + y[i] - d].end() && it2->first <= it1->first - d / 2) {\n                    cout << i + 1 << \" \" << it1->second + 1 << \" \" << it2->second + 1 << \"\\n\";\n                    found = true;\n                    break;\n                }\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            diag[x[i] + y[i]].erase({x[i], i});\n        }\n    }\n    if (!found) {\n        for (int i = 0; i < n; i++) {\n            y[i] -= 2 * MAXC;\n            diag[x[i] - y[i]].insert({x[i], i});\n        }\n        for (int i = 0; i < n; i++) {\n            auto it1 = diag[x[i] - y[i]].lower_bound({x[i] + d / 2, -1});\n            if (it1 == diag[x[i] - y[i]].end() || it1->first != x[i] + d / 2) continue;\n            if (x[i] - y[i] + d < MAXD) {\n                auto it2 = diag[x[i] - y[i] + d].lower_bound({x[i] + d / 2, -1});\n                if (it2 != diag[x[i] - y[i] + d].end() && it2->first <= it1->first + d / 2) {\n                    cout << i + 1 << \" \" << it1->second + 1 << \" \" << it2->second + 1 << \"\\n\";\n                    found = true;\n                    break;\n                }\n            }\n            if (x[i] - y[i] - d >= 0) {\n                auto it2 = diag[x[i] - y[i] - d].lower_bound({x[i] - d / 2, -1});\n                if (it2 != diag[x[i] - y[i] - d].end() && it2->first <= it1->first - d / 2) {\n                    cout << i + 1 << \" \" << it1->second + 1 << \" \" << it2->second + 1 << \"\\n\";\n                    found = true;\n                    break;\n                }\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            diag[x[i] - y[i]].erase({x[i], i});\n        }\n    }\n    if (!found) {\n        cout << \"0 0 0\\n\";\n    }\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "geometry",
      "implementation",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1979",
    "index": "F",
    "title": "Kostyanych's Theorem",
    "statement": "This is an interactive problem.\n\nKostyanych has chosen a complete undirected graph$^{\\dagger}$ with $n$ vertices, and then removed exactly $(n - 2)$ edges from it. You can ask queries of the following type:\n\n- \"? $d$\" — Kostyanych tells you the number of vertex $v$ with a degree \\textbf{at least} $d$. Among all possible such vertices, he selects the vertex \\textbf{with the minimum degree}, and if there are several such vertices, he selects the one with the minimum number. He also tells you the number of another vertex in the graph, with which $v$ is not connected by an edge (if none is found, then $0$ is reported). Among all possible such vertices, he selects the one with the minimum number. Then he removes the vertex $v$ and all edges coming out of it. If the required vertex $v$ is not found, then \"$0\\ 0$\" is reported.\n\nFind a Hamiltonian path$^{\\ddagger}$ in the \\textbf{original} graph in at most $n$ queries. It can be proven that under these constraints, a Hamiltonian path always exists.\n\n$^{\\dagger}$A complete undirected graph is a graph in which there is exactly one undirected edge between any pair of distinct vertices. Thus, a complete undirected graph with $n$ vertices contains $\\frac{n(n-1)}{2}$ edges.\n\n$^{\\ddagger}$A Hamiltonian path in a graph is a path that passes through each vertex exactly once.",
    "tutorial": "Let's consider the following recursive algorithm. We will store the Hamiltonian path as a double-ended queue, maintaining the start and end. In case there are only $1$ or $2$ vertices left in the graph, the problem is solved trivially. Suppose we know that the current graph has $n$ vertices, and there are at most $(n - 2)$ edges missing. Then the total number of edges in such a graph is at least $\\frac{n(n - 1)}{2} - (n - 2) = \\frac{n^2 - 3n + 4}{2}.$ Let all vertices in the graph have a degree of at most $(n - 3)$, then the total number of edges does not exceed $\\frac{n(n-3)}{2} = \\frac{n^2 - 3n}{2},$ which is less than the stated value. Hence, we conclude that there is at least one vertex with a degree greater than $(n - 3)$. If there exists a vertex $v$ with a degree of $(n - 2)$, then it is sufficient to run our recursive algorithm for the remaining graph. Since $v$ is only not connected by an edge to one vertex, $v$ is connected either to the start or the end of the maintained path in the remaining graph. Thus, we can insert the vertex $v$ either at the beginning or at the end of the path. Otherwise, let $u$ be the vertex with a degree of $(n - 1)$. There is at least one vertex $w$ with a degree not exceeding $(n - 3)$. Remove $u$ and $w$ from the graph. Notice that the number of edges in such a graph does not exceed $\\frac{n^2 - 3n + 4}{2} - (n - 1) - (n - 3) + 1 = \\frac{n^2 - 7n + 14}{2}$ $\\frac{n^2 - 7n + 14}{2} = \\frac{n^2 - 5n + 6}{2} - \\frac{2n - 8}{2}$ $\\frac{n^2 - 5n + 6}{2} - \\frac{2n - 8}{2} = \\frac{(n - 2)(n - 3)}{2} - (n - 4)$ $\\frac{(n - 2)(n - 3)}{2} - (n - 4) = \\frac{(n - 2)((n - 2) - 1)}{2} - ((n - 2) - 2).$ The invariant is preserved, so we can run the algorithm for the remaining graph. Then, we can arrange the vertices in the following order: $w$ - $u$ - $s$ - ..., where $s$ - the start of the Hamiltonian path in the remaining graph. It remains to understand how to use queries. Make a query $d = (n - 2)$. Let $u$ be the second number in the response to our query. If $u \\neq 0$, the degree of vertex $v$ is $(n - 2)$. Run our recursive algorithm, and then compare the start and end of the obtained path with $u$. Otherwise, if $u = 0$, it means the degree of vertex $v$ is $(n - 1)$. In this case, ask about any vertex with a low degree (this can be done with a query $d = 0$). Then simply arrange the vertices in the order mentioned above. We will make no more than $n$ queries, and the final asymptotic will be $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\npair <int, int> ask(int d) {\n    cout << \"? \" << d << endl;\n    int v, u;\n    cin >> v >> u;\n    return {v, u};\n}\n \npair <int, int> get(int n, vector <int>& nxt) {\n    if (n == 1) {\n        int v = ask(0).first;\n        return {v, v};\n    }\n    if (n == 2) {\n        int u = ask(0).first;\n        int v = ask(0).first;\n        nxt[u] = v;\n        return {u, v};\n    }\n    pair <int, int> t = ask(n - 2);\n    int v = t.first;\n    int ban = t.second;\n    if (ban != 0) {\n        pair <int, int> res = get(n - 1, nxt);\n        if (ban != res.first) {\n            nxt[v] = res.first;\n            return {v, res.second};\n        } else {\n            nxt[res.second] = v;\n            return {res.first, v};\n        }\n    } else {\n        int u = ask(0).first;\n        nxt[u] = v;\n        pair <int, int> res = get(n - 2, nxt);\n        nxt[v] = res.first;\n        return {u, res.second};\n    }\n}\n \nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector <int> nxt(n + 1, -1);\n    pair <int, int> ans = get(n, nxt);\n    \n    int v = ans.first;\n    cout << \"! \";\n    do {\n        cout << v << \" \";\n        v = nxt[v];\n    } while (v != -1);\n    cout << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graphs",
      "interactive"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1980",
    "index": "A",
    "title": "Problem Generator",
    "statement": "Vlad is planning to hold $m$ rounds next month. Each round should contain one problem of difficulty levels 'A', 'B', 'C', 'D', 'E', 'F', and 'G'.\n\nVlad already has a bank of $n$ problems, where the $i$-th problem has a difficulty level of $a_i$. There may not be enough of these problems, so he may have to come up with a few more problems.\n\nVlad wants to come up with as few problems as possible, so he asks you to find the minimum number of problems he needs to come up with in order to hold $m$ rounds.\n\nFor example, if $m=1$, $n = 10$, $a=$ 'BGECDCBDED', then he needs to come up with two problems: one of difficulty level 'A' and one of difficulty level 'F'.",
    "tutorial": "It is necessary to have at least $m$ problems of each difficulty level. If there are already at least $m$ problems of difficulty level $c$, then there is no need to come up with more problems of this difficulty level. Otherwise, it is necessary to come up with $m - cnt_c$ problems, where $cnt_c$ is the number of problems of difficulty level $c$ (if more problems of this difficulty level are created, the number will not be minimum).",
    "code": "def solve():\n    n, m = map(int, input().split())\n    a = input()\n    ans = 0\n    for ch in range(ord('A'), ord('H')):\n        ans += max(0, m - a.count(chr(ch)))\n    print(ans)\n    \n    \nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1980",
    "index": "B",
    "title": "Choosing Cubes",
    "statement": "Dmitry has $n$ cubes, numbered from left to right from $1$ to $n$. The cube with index $f$ is his favorite.\n\nDmitry threw all the cubes on the table, and the $i$-th cube showed the value $a_i$ ($1 \\le a_i \\le 100$). After that, he arranged the cubes in non-increasing order of their values, from largest to smallest. If two cubes show the same value, they can go in any order.\n\nAfter sorting, Dmitry removed the first $k$ cubes. Then he became interested in whether he removed his favorite cube (note that its position could have changed after sorting).\n\nFor example, if $n=5$, $f=2$, $a = [4, \\color{green}3, 3, 2, 3]$ (the favorite cube is highlighted in green), and $k = 2$, the following could have happened:\n\n- After sorting $a=[4, \\color{green}3, 3, 3, 2]$, since the favorite cube ended up in the second position, it will be removed.\n- After sorting $a=[4, 3, \\color{green}3, 3, 2]$, since the favorite cube ended up in the third position, it will not be removed.",
    "tutorial": "Let $x$ be the value of the cube with the number $f$. Let's sort all the cubes by non-growth. Then let's look at the value of the $k$-th cube in order. Since the cubes are removed by non-growth, all cubes with large values will be removed, some (perhaps not all) cubes with the same value, and cubes with smaller values will not be removed. If the value of the $k$-th cube is greater than $x$, then Dmitry's favorite cube will not be removed, because all the removed cubes will have more values. If it is less than $x$, then the favorite cube will always be removed, since the cube with the lower value will also be removed. If the value of the $k$ th cube is equal to $x$, then some cubes with this value will be removed. However, if there are several such cubes, then perhaps not all of them will be removed. If the $k + 1$th cube is missing (for $k = n$) or if its value is less than $x$, then all cubes with this value will be removed, and the answer is YES. Otherwise, only a part of the cubes with the value $x$ will be removed, and the answer is MAYBE, because cubes with the same values are indistinguishable when sorting.",
    "code": "def solve():\n    n, f, k = map(int, input().split())\n    f -= 1\n    k -= 1\n    a = list(map(int, input().split()))\n    x = a[f]\n    a.sort(reverse=True)\n    if a[k] > x:\n        print(\"NO\")\n    elif a[k] < x:\n        print(\"YES\")\n    else:\n        print(\"YES\" if k == n - 1 or a[k + 1] < x else \"MAYBE\")\n \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1980",
    "index": "C",
    "title": "Sofia and the Lost Operations",
    "statement": "Sofia had an array of $n$ integers $a_1, a_2, \\ldots, a_n$. One day she got bored with it, so she decided to \\textbf{sequentially} apply $m$ modification operations to it.\n\nEach modification operation is described by a pair of numbers $\\langle c_j, d_j \\rangle$ and means that the element of the array with index $c_j$ should be assigned the value $d_j$, i.e., perform the assignment $a_{c_j} = d_j$. After applying \\textbf{all} modification operations \\textbf{sequentially}, Sofia discarded the resulting array.\n\nRecently, you found an array of $n$ integers $b_1, b_2, \\ldots, b_n$. You are interested in whether this array is Sofia's array. You know the values of the original array, as well as the values $d_1, d_2, \\ldots, d_m$. The values $c_1, c_2, \\ldots, c_m$ turned out to be lost.\n\nIs there a sequence $c_1, c_2, \\ldots, c_m$ such that the \\textbf{sequential} application of modification operations $\\langle c_1, d_1, \\rangle, \\langle c_2, d_2, \\rangle, \\ldots, \\langle c_m, d_m \\rangle$ to the array $a_1, a_2, \\ldots, a_n$ transforms it into the array $b_1, b_2, \\ldots, b_n$?",
    "tutorial": "First, in the array $b_1, b_2, \\ldots, b_n$, the number $d_m$ must be present. Second, if $a_i = b_i$, we will not apply any operations to $i$. All extra operations can be applied to $a_j$, where $b_j = d_m$, they will be overwritten by the operation $d_m$. For all other $i$ ($a_i \\neq b_i$) we must apply the operation $d_k = b_i$, so it remains to check that the multiset of such $b_i$ is included in the multiset $d_1, d_2, \\ldots, d_m$. This solution can be implemented using sorting and two pointers or std::map, resulting in a time complexity of $O((n + m) \\log n)$. If you used std::unordered_map or dict, you were most likely hacked. Check out this post.",
    "code": "#include <stdio.h>\n#include <stdbool.h>\n \n#define MAXN 200200\n#define MAXM 200200\n \nint n, m, k;\nint arr[MAXN], brr[MAXN], drr[MAXM], buf[MAXN];\n \nint cmp_i32(const void* pa, const void* pb) {\n    return *(const int*)pa - *(const int*)pb;\n}\n \nvoid build() {\n    k = 0;\n    for (int i = 0; i < n; ++i) {\n        if (arr[i] != brr[i])\n            buf[k++] = brr[i];\n    }\n    qsort(buf, k, sizeof(*buf), cmp_i32);\n}\n \nbool check() {\n    for (int i = 0; i < n; ++i)\n        if (brr[i] == drr[m - 1])\n            return true;\n    return false;\n}\n \nbool solve() {\n    if (!check()) return false;\n    qsort(drr, m, sizeof(*drr), cmp_i32);\n    int ib = 0, id = 0;\n    while (ib < k && id < m) {\n        if (buf[ib] == drr[id])\n            ++ib, ++id;\n        else if (buf[ib] < drr[id])\n            return false;\n        else ++id;\n    }\n    return ib == k;\n}\n \nint main() {\n    int t; scanf(\"%d\", &t);\n    while (t--) {\n        scanf(\"%d\", &n);\n        for (int i = 0; i < n; ++i)\n            scanf(\"%d\", arr + i);\n        for (int i = 0; i < n; ++i)\n            scanf(\"%d\", brr + i);\n        scanf(\"%d\", &m);\n        for (int j = 0; j < m; ++j)\n            scanf(\"%d\", drr + j);\n        build();\n        if (solve()) printf(\"YES\\n\");\n        else printf(\"NO\\n\");\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1980",
    "index": "D",
    "title": "GCD-sequence",
    "statement": "GCD (Greatest Common Divisor) of two integers $x$ and $y$ is the maximum integer $z$ by which both $x$ and $y$ are divisible. For example, $GCD(36, 48) = 12$, $GCD(5, 10) = 5$, and $GCD(7,11) = 1$.\n\nKristina has an array $a$ consisting of exactly $n$ positive integers. She wants to count the GCD of each neighbouring pair of numbers to get a new array $b$, called GCD-sequence.\n\nSo, the elements of the GCD-sequence $b$ will be calculated using the formula $b_i = GCD(a_i, a_{i + 1})$ for $1 \\le i \\le n - 1$.\n\nDetermine whether it is possible to remove \\textbf{exactly one} number from the array $a$ so that the GCD sequence $b$ is non-decreasing (i.e., $b_i \\le b_{i+1}$ is always true).\n\nFor example, let Khristina had an array $a$ = [$20, 6, 12, 3, 48, 36$]. If she removes $a_4 = 3$ from it and counts the GCD-sequence of $b$, she gets:\n\n- $b_1 = GCD(20, 6) = 2$\n- $b_2 = GCD(6, 12) = 6$\n- $b_3 = GCD(12, 48) = 12$\n- $b_4 = GCD(48, 36) = 12$\n\nThe resulting GCD sequence $b$ = [$2,6,12,12$] is non-decreasing because $b_1 \\le b_2 \\le b_3 \\le b_4$.",
    "tutorial": "Let's loop through the initial array $a$, counting the GCD of neighbouring elements. If at some point, the GCD of the previous pair becomes greater than the GCD of the next pair, we remember the index $i$ of the first element of the pair that gave the greater GCD and stop the loop. Then consider the following cases: the sequence of GCDs for array $a$ was already non-decreasing. Then it is enough to remove the last element from it, the previous elements of the GCD-sequence will not be affected. The answer in this case is always YES. some element $a_i$ has been found such that $GCD(a_{i-1}, a_i) \\gt GCD(a_i, a_{i+1})$. Then, since there is already at least one place in the original GCD-sequence where it ceases to be non-decreasing, we can try to fix it by removing the $i-1$-th, $i$-th or $i+1$-th element from the array $a$. Let's create $3$ new arrays of length $n-1$, and in each of them remove one of the above elements. If at least one of these arrays has a non-decreasing GCD-sequence - the answer is YES, otherwise - NO.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nbool good(vector<int>&b){\n    int g = __gcd(b[0], b[1]);\n    for(int i = 1; i < int(b.size()) - 1; i++){\n        int cur_gcd = __gcd(b[i], b[i + 1]);\n        if(g > cur_gcd) return false;\n        g = cur_gcd;\n    }\n    return true;\n}\n \nbool solve(){\n    int n;\n    cin >> n;\n    vector<int>a(n);\n    for(int i = 0; i < n; i++){\n        cin >> a[i];\n    }\n \n    int g = -1;\n    int to_del = -1;\n    for(int i = 0; i < n - 1; i++){\n        int cur_gcd = __gcd(a[i], a[i + 1]);\n        if(cur_gcd < g){\n            to_del = i;\n            break;\n        }\n        g = cur_gcd;\n    }\n    if(to_del == -1) return true;\n    vector<int>b0 = a, b1 = a, b2 = a;\n    if(to_del > 0) b0.erase(b0.begin() + to_del - 1);\n    b1.erase(b1.begin() + to_del);\n    if(to_del < n - 1) b2.erase(b2.begin() + to_del + 1);\n    return good(b0) || good(b1) || good(b2);\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        cout << (solve() ? \"YES\" : \"NO\") << \"\\n\";\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1980",
    "index": "E",
    "title": "Permutation of Rows and Columns",
    "statement": "You have been given a matrix $a$ of size $n$ by $m$, containing a permutation of integers from $1$ to $n \\cdot m$.\n\nA permutation of $n$ integers is an array containing all numbers from $1$ to $n$ exactly once. For example, the arrays $[1]$, $[2, 1, 3]$, $[5, 4, 3, 2, 1]$ are permutations, while the arrays $[1, 1]$, $[100]$, $[1, 2, 4, 5]$ are not.\n\nA matrix contains a permutation if, when all its elements are written out, the resulting array is a permutation. Matrices $[[1, 2], [3, 4]]$, $[[1]]$, $[[1, 5, 3], [2, 6, 4]]$ contain permutations, while matrices $[[2]]$, $[[1, 1], [2, 2]]$, $[[1, 2], [100, 200]]$ do not.\n\nYou can perform one of the following two actions in one operation:\n\n- choose columns $c$ and $d$ ($1 \\le c, d \\le m$, $c \\ne d$) and swap these columns;\n- choose rows $c$ and $d$ ($1 \\le c, d \\le n$, $c \\ne d$) and swap these rows.\n\nYou can perform any number of operations.\n\nYou are given the original matrix $a$ and the matrix $b$. Your task is to determine whether it is possible to transform matrix $a$ into matrix $b$ using the given operations.",
    "tutorial": "For each element, you can calculate its positions in both matrices. You can see that the rearrangement of rows does not affect the column positions of the elements being rearranged. Similarly, column rearrangement does not affect row positions. Since the permutation of rows affects the entire rows, for all elements that have the same position row in the original matrix, the position row in the resulting matrix must also match. Similarly, the columns must match. In order to check the coincidence of rows and columns, let's count 4 arrays - the positions of rows and columns in the original and received matrices. Then you need to check that for all $x$ with the same row value in the original matrix, the row values in the resulting matrix are the same. Similarly, the values of the columns should be the same.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n \nusing namespace std;\n \ntypedef long long ll;\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\n \nvi read_ints(int n) {\n    vi res(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> res[i];\n    }\n    return res;\n}\n \nvvi read_matrix(int n, int m) {\n    vvi res(n);\n    for (int i = 0; i < n; ++i) {\n        res[i] = read_ints(m);\n    }\n    return res;\n}\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vvi a = read_matrix(n, m), b = read_matrix(n, m);\n    int nm = n * m;\n    vi pos1i(nm), pos2i(nm), pos1j(nm), pos2j(nm);\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < m; ++j) {\n            int x = a[i][j] - 1;\n            int y = b[i][j] - 1;\n            pos1i[x] = pos2i[y] = i;\n            pos1j[x] = pos2j[y] = j;\n        }\n    }\n    vector<set<int>> pi(nm), pj(nm);\n    for (int x = 0; x < nm; ++x) {\n        int i1 = pos1i[x], i2 = pos2i[x];\n        int j1 = pos1j[x], j2 = pos2j[x];\n        pi[i1].insert(i2);\n        pj[j1].insert(j2);\n    }\n    for (int x = 0; x < nm; ++x) {\n        if (pi[x].size() > 1 || pj[x].size() > 1) {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    cout << \"YES\\n\";\n}\n \nint main() {\n    int t;\n    cin >> t;\n    for (int _ = 0; _ < t; ++_) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "hashing",
      "implementation",
      "math",
      "matrices",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1980",
    "index": "F1",
    "title": "Field Division (easy version)",
    "statement": "\\textbf{This is an easy version of the problem; it differs from the hard version only by the question. The easy version only needs you to print whether some values are non-zero or not. The hard version needs you to print the exact values.}\n\nAlice and Bob are dividing the field. The field is a rectangle of size $n \\times m$ ($2 \\le n, m \\le 10^9$), the rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The cell at the intersection of row $r$ and column $c$ is denoted as ($r, c$).\n\nBob has $k$ ($2 \\le k \\le 2 \\cdot 10^5$) fountains, all of them are located in different cells of the field. Alice is responsible for dividing the field, but she must meet several conditions:\n\n- To divide the field, Alice will start her path in any free (without a fountain) cell on the left or top side of the field and will move, each time moving to the adjacent cell \\textbf{down} or \\textbf{right}. Her path will end on the right or bottom side of the field.\n- Alice's path will divide the field into two parts — one part will belong to Alice (this part includes the cells of her path), the other part — to Bob.\n- Alice will own the part that includes the cell ($n, 1$).\n- Bob will own the part that includes the cell ($1, m$).\n\nAlice wants to divide the field in such a way as to get as many cells as possible.\n\nBob wants to keep ownership of all the fountains, but he can give one of them to Alice. First, output the integer $\\alpha$ — the maximum possible size of Alice's plot, if Bob does not give her any fountain (i.e., all fountains will remain on Bob's plot). Then output $k$ non-negative integers $a_1, a_2, \\dots, a_k$, where:\n\n- $a_i=0$, if after Bob gives Alice the $i$-th fountain, the maximum possible size of Alice's plot does not increase (i.e., remains equal to $\\alpha$);\n- $a_i=1$, if after Bob gives Alice the $i$-th fountain, the maximum possible size of Alice's plot increases (i.e., becomes greater than $\\alpha$).",
    "tutorial": "Since Alice can only move down or to the right, if in the $i$-th row $x$ cells belong to her, then in the $(i-1)$-th row she can have no more than $x$ cells. The construction of the maximum plot can be represented as follows: we will go through the rows from bottom to top and keep track of how many cells we have collected in the row below. In the current row, we will collect either the same number of cells, or all the cells up to the leftmost fountain in the row, if there are fewer such cells. There are three possible positions of the fountains relative to the boundary with Alice's plot: the fountain has no adjacent cells belonging to Alice's plot; the fountain has one adjacent cell belonging to Alice's plot; the fountain has two adjacent cells belonging to Alice's plot. The area of Alice's plot changes only when removing the third type of fountain position, which we will call the corner. Since a corner has formed, in the row below Alice had more cells, and when removing this fountain, she will be able to take at least one cell with this fountain, and the answer for it will be $1$. For the other two types of positions, removing the fountain will not change the size of the plot, and the answer for them will be $0$ (you can proof it by yourself). To ensure that the solution does not depend on the size of the field, we will sort the fountains in descending order of the $x$ coordinate, and in case of equality of $x$, in ascending order of the $y$ coordinate. We will iterate through the fountains in this order, keep track of the coordinates of the last corner, and update the answer when a new corner is found.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n \ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(time(nullptr));\n \nconst ll inf = 1e9 + 1;\nconst ll M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n \nbool cmp(pair<int, int> &a, pair<int, int> &b){\n    if(a.x != b.x) return a.x > b.x;\n    return a.y < b.y;\n}\n \nvoid solve(int tc){\n    int n, m, k;\n    cin >> n >> m >> k;\n    vector<pair<int, int>> a(k);\n    map<pair<int, int>, int> idx;\n    for(int i = 0; i < k; ++i){\n        cin >> a[i].x >> a[i].y;\n        idx[a[i]] = i;\n    }\n    sort(all(a), cmp);\n    vector<int> ans(k);\n    int total = 0;\n    int cur = m + 1;\n    int last = n;\n    for(auto e: a){\n        if(cur > e.y) {\n            ans[idx[e]] = 1;\n            total += (cur - 1) * (last - e.x);\n            cur = e.y;\n            last = e.x;\n        }\n    }\n    total += (cur - 1) * last;\n    cout << total << \"\\n\";\n    for(int e: ans) cout << e << \" \";\n}\n \nbool multi = true;\n \nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "math",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1980",
    "index": "F2",
    "title": "Field Division (hard version)",
    "statement": "\\textbf{This is a hard version of the problem; it differs from the easy version only by the question. The easy version only needs you to print whether some values are non-zero or not. The hard version needs you to print the exact values.}\n\nAlice and Bob are dividing the field. The field is a rectangle of size $n \\times m$ ($2 \\le n, m \\le 10^9$); the rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The cell at the intersection of row $r$ and column $c$ is denoted as ($r, c$).\n\nBob has $k$ ($2 \\le k \\le 2 \\cdot 10^5$) fountains, all of them are located in different cells of the field. Alice is responsible for dividing the field, but she must meet several conditions:\n\n- To divide the field, Alice will start her path in any free (without a fountain) cell on the left or top side of the field and will move, each time moving to the adjacent cell \\textbf{down} or \\textbf{right}. Her path will end on the right or bottom side of the field.\n- Alice's path will divide the field into two parts — one part will belong to Alice (this part includes the cells of her path), the other part — to Bob.\n- Alice will own the part that includes the cell ($n, 1$).\n- Bob will own the part that includes the cell ($1, m$).\n\nAlice wants to divide the field in such a way as to get as many cells as possible.\n\nBob wants to keep ownership of all the fountains, but he can give one of them to Alice. First, output the integer $\\alpha$ — the maximum possible size of Alice's plot, if Bob does not give her any fountain (i.e., all fountains will remain on Bob's plot).\n\nThen output $k$ non-negative integers $a_1, a_2, \\dots, a_k$, where $a_i$ is a value such that after Bob gives Alice the $i$-th fountain, the maximum size of her plot will be $\\alpha + a_i$.",
    "tutorial": "First, read the editorial of the easy version. Let's use the solution of the easy version to precalculate the stored information on the prefix. The fountain will stop being a corner only when it is removed, because the leftmost corner on the prefix could not become further left as a result of removal. To calculate the change in area, let's make an important observation: if fountain $j$ is not a corner, then it either cannot become one, or will become one only after the removal of the last corner that comes before it in sorted order. It was the leftmost corner that came before fountain $j$, and the next corner in sorted order will be strictly higher. Thus, we need to do the following: for each corner, calculate the area without considering it until the next corner, and this will be helped by the precalculation we did when calculating the area. Each fountain will be processed only once, so the time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n \ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(time(nullptr));\n \nconst ll inf = 1e9 + 1;\nconst ll M = 998244353;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n \nbool cmp(pair<int, int> &a, pair<int, int> &b){\n    if(a.x != b.x) return a.x > b.x;\n    return a.y < b.y;\n}\n \nvoid solve(int tc){\n    int n, m, k;\n    cin >> n >> m >> k;\n    vector<pair<int, int>> a(k);\n    map<pair<int, int>, int> idx;\n    for(int i = 0; i < k; ++i){\n        cin >> a[i].x >> a[i].y;\n        idx[a[i]] = i;\n    }\n    idx[{0, 0}] = k++;\n    a.emplace_back(0, 0);\n    sort(all(a), cmp);\n    vector<int> ans(k);\n    vector<int> total(k + 1), cur(k + 1, m + 1), last(k + 1, n);\n    for(int i = 1; i <= k; ++i){\n        auto e = a[i - 1];\n        total[i] = total[i - 1];\n        cur[i] = cur[i - 1];\n        last[i] = last[i - 1];\n        if(cur[i] > e.y) {\n            ans[idx[e]] = 1;\n            total[i] += (cur[i] - 1) * (last[i] - e.x);\n            cur[i] = e.y;\n            last[i] = e.x;\n        }\n    }\n    cout << total[k] << \"\\n\";\n    for(int i = 1; i <= k; ++i){\n        auto e = a[i - 1];\n        if(ans[idx[e]] == 0)continue;\n        int tot = total[i - 1];\n        int cr = cur[i - 1];\n        int lst = last[i - 1];\n        for(int j = i + 1; j <= k; ++j){\n            auto ee = a[j - 1];\n            if(cr > ee.y){\n                tot += (cr - 1) * (lst - ee.x);\n                cr = ee.y;\n                lst = ee.x;\n            }\n            if(ans[idx[ee]] == 1){\n                ans[idx[e]] = tot - total[j];\n                break;\n            }\n        }\n    }\n    ans.pop_back();\n    for(int e: ans) cout << e << \" \";\n}\n \nbool multi = true;\n \nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1980",
    "index": "G",
    "title": "Yasya and the Mysterious Tree",
    "statement": "Yasya was walking in the forest and accidentally found a tree with $n$ vertices. A tree is a connected undirected graph with no cycles.\n\nNext to the tree, the girl found an ancient manuscript with $m$ queries written on it. The queries can be of two types.\n\nThe first type of query is described by the integer $y$. The weight of \\textbf{each} edge in the tree is replaced by the bitwise exclusive OR of the weight of that edge and the integer $y$.\n\nThe second type is described by the vertex $v$ and the integer $x$. Yasya chooses a vertex $u$ ($1 \\le u \\le n$, $u \\neq v$) and mentally draws a bidirectional edge of weight $x$ from $v$ to $u$ in the tree.\n\nThen Yasya finds a simple cycle in the resulting graph and calculates the bitwise exclusive OR of all the edges in it. She wants to choose a vertex $u$ such that the calculated value is \\textbf{maximum}. This calculated value will be the answer to the query. It can be shown that such a cycle exists and is unique under the given constraints (independent of the choice of $u$). If an edge between $v$ and $u$ already existed, a simple cycle is the path $v \\to u \\to v$.\n\nNote that the second type of query is performed mentally, meaning the tree does \\textbf{not} change in any way after it.\n\nHelp Yasya answer all the queries.",
    "tutorial": "We will hang the tree on the vertex $1$ and count for each vertex $d_v$ - xor on the path from it to the root. This can be done by depth-first traversal in $O(n)$. Now let's learn how to solve the problem in $O(n)$ for each query. The first type of query can be executed straightforwardly. Notice that due to the properties of the xor operation, the values will only change for vertices at odd depth (the depth of the root is $0$). At the same time, they will change trivially: they will be xored with $y$. To answer the second query, it is necessary to realize that the xor on a simple cycle $v \\to \\text{lca}(v, u) \\to u \\to v$ is equal to $d_v \\oplus d_u \\oplus x$. Indeed, the path from $\\text{lca(v, u)}$ to the root will be counted twice, so it will turn into $0$, and no other extra edges will be included in this xor. With due skill, you can try to speed up such a solution with AVX instructions, but the time constraints were chosen strictly. For a complete solution to the problem, you can use the data structure prefix tree (trie). With its help, you can find in $O(\\log x)$ for the number $x$ such a $y$ in the set, that $x \\oplus y$ is maximal. Since $d_v$ change differently, you will have to use two tries - for vertices at even and odd heights. Operations of the first type can be accumulated in the variable $w_\\text{odd}$ and added to the xor expression. In addition, you must not forget to remove $d_v$ from the necessary trie when answering the second query, and then insert it back. To do this, you can maintain a counter of terminal leaves in each vertex and use this information during descent. Thus, the final asymptotic is $O((n + m) \\log 10^9)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nstruct trie {\n    int l, c;\n    vector<array<int, 2>> node;\n    vector<int> cnt;\n    trie(int l, int max_members) : l(l), c(0), node((l + 2) * max_members + 3), cnt((l + 2) * max_members + 3) {}\n    void add(int x) {\n        int cur = 0;\n        for (int i = l; i >= 0; --i) {\n            bool has_bit = (1 << i) & x;\n            if (!node[cur][has_bit]) {\n                node[cur][has_bit] = ++c;\n            }\n            cur = node[cur][has_bit];\n            ++cnt[cur];\n        }\n    }\n    void remove(int x) {\n        int cur = 0;\n        for (int i = l; i >= 0; --i) {\n            bool has_bit = (1 << i) & x;\n            if (!node[cur][has_bit]) {\n                node[cur][has_bit] = ++c;\n            }\n            cur = node[cur][has_bit];\n            --cnt[cur];\n        }\n    }\n    int find_max(int x) {\n        int cur = 0, ans = 0;\n        for (int i = l; i >= 0; --i) {\n            bool has_bit = (1 << i) & x;\n            if (node[cur][!has_bit] && cnt[node[cur][!has_bit]]) {\n                ans += 1 << i;\n                cur = node[cur][!has_bit];\n            }\n            else {\n                cur = node[cur][has_bit];\n            }\n        }\n        return ans;\n    }\n};\n \nconst int N = 2e5 + 2;\nint x[N];\nbitset<N> dp;\nvector<array<int, 2>> e[N];\n \nvoid dfs(int c, int p) {\n    for (auto [i, w] : e[c]) {\n        if (i == p) {\n            continue;\n        }\n        dp[i] = !dp[c];\n        x[i] = x[c] ^ w;\n        dfs(i, c);\n    }\n}\n \nvoid solve() {\n    int n, m, gx = 0;\n    cin >> n >> m;\n    for (int i = 1; i <= n; ++i) {\n        e[i].clear();\n    }\n    for (int i = 1, u, v, w; i < n; ++i) {\n        cin >> u >> v >> w;\n        e[u].push_back({v, w});\n        e[v].push_back({u, w});\n    }\n    dfs(1, 0);\n    vector<trie> t(2, trie(30, n));\n    for (int i = 1; i <= n; ++i) {\n        t[dp[i]].add(x[i]);\n    }\n    while (m--) {\n        char c;\n        cin >> c;\n        if (c == '^') {\n            int y;\n            cin >> y;\n            gx ^= y;\n        }\n        else {\n            int a, b;\n            cin >> a >> b;\n            t[dp[a]].remove(x[a]);\n            int same_group = t[dp[a]].find_max(x[a] ^ b);\n            int diff_group = t[1 - dp[a]].find_max(x[a] ^ b ^ gx);\n            t[dp[a]].add(x[a]);\n            cout << max(same_group, diff_group) << \"\\n\";\n        }\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "strings",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1981",
    "index": "A",
    "title": "Turtle and Piggy Are Playing a Game",
    "statement": "Turtle and Piggy are playing a number game.\n\nFirst, Turtle will choose an integer $x$, such that $l \\le x \\le r$, where $l, r$ are given. It's also guaranteed that $2l \\le r$.\n\nThen, Piggy will keep doing the following operation until $x$ becomes $1$:\n\n- Choose an integer $p$ such that $p \\ge 2$ and $p \\mid x$ (i.e. $x$ is a multiple of $p$).\n- Set $x$ to $\\frac{x}{p}$, and the score will increase by $1$.\n\nThe score is initially $0$. Both Turtle and Piggy want to maximize the score. Please help them to calculate the maximum score.",
    "tutorial": "For a specific $x$, Piggy always chooses $p$ such that $p$ is a prime number, so the score is the number of prime factors of $x$. It is easy to see that the number with at least $t$ prime factors is $2^t$. The largest integer $t$ satisfying $2^t \\le r$ is $\\left\\lfloor\\log_2 r\\right\\rfloor$. Also, because $2l \\le r$, then $\\log_2 l + 1 \\le \\log_2 r$, so $\\log_2 l < \\left\\lfloor\\log_2 r\\right\\rfloor \\le \\log_2 r$, hence $l < 2^{\\left\\lfloor\\log_2 r\\right\\rfloor} \\le r$. So the answer is $\\left\\lfloor\\log_2 r\\right\\rfloor$. Time complexity: $O(1)$ or $O(\\log r)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint T;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tint l, r;\n\t\tscanf(\"%d%d\", &l, &r);\n\t\tprintf(\"%d\\n\", __lg(r));\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1981",
    "index": "B",
    "title": "Turtle and an Infinite Sequence",
    "statement": "There is a sequence $a_0, a_1, a_2, \\ldots$ of infinite length. Initially $a_i = i$ for every non-negative integer $i$.\n\nAfter every second, each element of the sequence will \\textbf{simultaneously} change. $a_i$ will change to $a_{i - 1} \\mid a_i \\mid a_{i + 1}$ for every positive integer $i$. $a_0$ will change to $a_0 \\mid a_1$. Here, $|$ denotes bitwise OR.\n\nTurtle is asked to find the value of $a_n$ after $m$ seconds. In particular, if $m = 0$, then he needs to find the initial value of $a_n$. He is tired of calculating so many values, so please help him!",
    "tutorial": "Each bit of the answer is independent, so we can calculate the value of each bit of the answer separately. Let's consider the $d$-th bit. Then, $a_i = \\left\\lfloor\\frac{i}{2^d}\\right\\rfloor \\bmod 2$. Every second, a $1$ will \"spread\" one position to the left and right. If $a_n$ is initially $1$, then the answer for this bit is $1$. Otherwise, $a_n$ is in a continuous segment of $0$s, and we need to calculate whether the $1$s on the left and right of this segment can \"spread\" to $a_n$. Let $x = n \\bmod 2^{d + 1}$, then $0 \\le x \\le 2^d - 1$. The left $1$ spreading to $a_n$ takes $x + 1$ seconds, and the right $1$ spreading to $a_n$ takes $2^d - x$ seconds. Therefore, if $\\min(x + 1, 2^d - x) \\le m$, then $a_n$ can become $1$. Specifically, if $n < 2^d$, then there is no $1$ on the left. Therefore, in this case, if $2^d - x \\le m$, then $a_n$ can become $1$. Time complexity: $O(\\log (n + m))$ per test case. The answer is the bitwise OR of the range $[\\max(0, n - m), n + m]$. Let's figure out how to calculate the bitwise OR of the range $[l, r]$. We can consider each bit separately. If the $d$-th bit of $l$ is $1$ or the $d$-th bit of $r$ is $1$, then the $d$-th bit of the answer is $1$. Otherwise, if $\\left\\lfloor\\frac{l}{2^{d + 1}}\\right\\rfloor \\ne \\left\\lfloor\\frac{r}{2^{d + 1}}\\right\\rfloor$, then the $d$-th bit has been flipped at least twice from $l$ to $r$, so in this case the $d$-th bit of the answer is also $1$. Time complexity: $O(\\log (n + m))$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<ll, ll> pii;\n\nvoid solve() {\n\tll n, m;\n\tscanf(\"%lld%lld\", &n, &m);\n\tll l = max(0LL, n - m), r = n + m, ans = 0;\n\tfor (int i = 31; ~i; --i) {\n\t\tif ((l & (1LL << i)) || (r & (1LL << i)) || (l >> (i + 1)) != (r >> (i + 1))) {\n\t\t\tans |= (1LL << i);\n\t\t}\n\t}\n\tprintf(\"%lld\\n\", ans);\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1981",
    "index": "C",
    "title": "Turtle and an Incomplete Sequence",
    "statement": "Turtle was playing with a sequence $a_1, a_2, \\ldots, a_n$ consisting of positive integers. Unfortunately, some of the integers went missing while playing.\n\nNow the sequence becomes incomplete. There may exist an arbitrary number of indices $i$ such that $a_i$ becomes $-1$. Let the new sequence be $a'$.\n\nTurtle is sad. But Turtle remembers that for every integer $i$ from $1$ to $n - 1$, either $a_i = \\left\\lfloor\\frac{a_{i + 1}}{2}\\right\\rfloor$ or $a_{i + 1} = \\left\\lfloor\\frac{a_i}{2}\\right\\rfloor$ holds for the original sequence $a$.\n\nTurtle wants you to help him complete the sequence. But sometimes Turtle makes mistakes, so you need to tell him if you can't complete the sequence.\n\nFormally, you need to find another sequence $b_1, b_2, \\ldots, b_n$ consisting of positive integers such that:\n\n- For every integer $i$ from $1$ to $n$, if $a'_i \\ne -1$, then $b_i = a'_i$.\n- For every integer $i$ from $1$ to $n - 1$, either $b_i = \\left\\lfloor\\frac{b_{i + 1}}{2}\\right\\rfloor$ or $b_{i + 1} = \\left\\lfloor\\frac{b_i}{2}\\right\\rfloor$ holds.\n- For every integer $i$ from $1$ to $n$, $1 \\le b_i \\le 10^9$.\n\nIf there is no sequence $b_1, b_2, \\ldots, b_n$ that satisfies all of the conditions above, you need to report $-1$.",
    "tutorial": "Handle the special case where all elements are $-1$ first. Consider extracting all positions where the values are not $-1$, denoted as $c_1, c_2, \\ldots, c_k$. The segments $[1, c_1 - 1]$ and $[c_k + 1, n]$ with $-1$s are easy to handle by repeatedly multiplying and dividing by $2$. It's easy to see that the constructions of the segments $[c_1 + 1, c_2 - 1], [c_2 + 1, c_3 - 1], \\ldots, [c_{k - 1} + 1, c_k - 1]$ are independent of each other. Therefore, we now only need to solve the problem where $a'_1 \\ne -1$, $a'_n \\ne -1$, and $a'_2 = a'3 = \\cdots = a'{n - 1} = -1$. It's clear that if $a_i$ is determined, then $a_{i + 1}$ can only be one of $\\left\\lfloor\\frac{a_i}{2}\\right\\rfloor$, $2a_i$, or $2a_i + 1$. We observe that the transition $a_i \\to a_{i + 1}$ is essentially moving along an edge in a complete binary tree. Therefore, the problem is reduced to finding a path in a complete binary tree with a given start point $a'_1$, end point $a'_n$, and passing through $n$ nodes. For example, $a' = [3, -1, -1, -1, 9]$ is equivalent to finding a path from $3$ to $9$ in the complete binary tree that passes through $5$ nodes: First, consider finding the shortest path from $a'_1$ to $a'_n$ in the complete binary tree (which can be found by computing the LCA of $a'_1$ and $a'_n$; the shortest path is $a'_1 \\to \\text{LCA}(a'_1, a'_n) \\to a'_n$). Let the number of nodes in this shortest path be $l$. There is no solution if and only if $l > n$ or if the parities of $l$ and $n$ are different. Otherwise, we first fill $a'_1, a'_2, \\ldots, a'_l$ with the nodes from the shortest path, and then alternate between $a'_n$ and $2a'_n$ to fill the remaining positions. Time complexity: $O(n)$ or $O(n \\log V)$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<ll, ll> pii;\n\nconst int maxn = 200100;\n\nint n, a[maxn];\n\ninline vector<int> path(int x, int y) {\n\tvector<int> L, R;\n\twhile (__lg(x) > __lg(y)) {\n\t\tL.pb(x);\n\t\tx >>= 1;\n\t}\n\twhile (__lg(y) > __lg(x)) {\n\t\tR.pb(y);\n\t\ty >>= 1;\n\t}\n\twhile (x != y) {\n\t\tL.pb(x);\n\t\tR.pb(y);\n\t\tx >>= 1;\n\t\ty >>= 1;\n\t}\n\tL.pb(x);\n\treverse(R.begin(), R.end());\n\tfor (int x : R) {\n\t\tL.pb(x);\n\t}\n\treturn L;\n}\n\nvoid solve() {\n\tscanf(\"%d\", &n);\n\tint l = -1, r = -1;\n\tvector<int> vc;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &a[i]);\n\t\tif (a[i] != -1) {\n\t\t\tif (l == -1) {\n\t\t\t\tl = i;\n\t\t\t}\n\t\t\tr = i;\n\t\t\tvc.pb(i);\n\t\t}\n\t}\n\tif (l == -1) {\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\tprintf(\"%d%c\", (i & 1) + 1, \" \\n\"[i == n]);\n\t\t}\n\t\treturn;\n\t}\n\tfor (int i = l - 1; i; --i) {\n\t\ta[i] = (((l - i) & 1) ? a[l] * 2 : a[l]);\n\t}\n\tfor (int i = r + 1; i <= n; ++i) {\n\t\ta[i] = (((i - r) & 1) ? a[r] * 2 : a[r]);\n\t}\n\tfor (int _ = 1; _ < (int)vc.size(); ++_) {\n\t\tint l = vc[_ - 1], r = vc[_];\n\t\tvector<int> p = path(a[l], a[r]);\n\t\tif (((int)p.size() & 1) != ((r - l + 1) & 1) || r - l + 1 < (int)p.size()) {\n\t\t\tputs(\"-1\");\n\t\t\treturn;\n\t\t}\n\t\tfor (int i = 0; i < (int)p.size(); ++i) {\n\t\t\ta[l + i] = p[i];\n\t\t}\n\t\tfor (int i = l + (int)p.size(), o = 1; i <= r; ++i, o ^= 1) {\n\t\t\ta[i] = (o ? a[i - 1] * 2 : a[i - 1] / 2);\n\t\t}\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tprintf(\"%d%c\", a[i], \" \\n\"[i == n]);\n\t}\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1981",
    "index": "D",
    "title": "Turtle and Multiplication",
    "statement": "Turtle just learned how to multiply two integers in his math class, and he was very excited.\n\nThen Piggy gave him an integer $n$, and asked him to construct a sequence $a_1, a_2, \\ldots, a_n$ consisting of integers which satisfied the following conditions:\n\n- For all $1 \\le i \\le n$, $1 \\le a_i \\le 3 \\cdot 10^5$.\n- For all $1 \\le i < j \\le n - 1$, $a_i \\cdot a_{i + 1} \\ne a_j \\cdot a_{j + 1}$.\n\nOf all such sequences, Piggy asked Turtle to find the one with the \\textbf{minimum} number of \\textbf{distinct} elements.\n\nTurtle definitely could not solve the problem, so please help him!",
    "tutorial": "The necessary condition for $a_i \\cdot a_{i + 1} = a_j \\cdot a_{j + 1}$ is that the unordered pairs $(a_i, a_{i + 1})$ and $(a_j, a_{j + 1})$ are identical. In fact, if $a_i$ are all prime numbers, then this necessary condition becomes sufficient. If we consider $(a_i, a_{i + 1})$ as an edge, then the problem can be transformed into finding the undirected complete graph with the fewest nodes (where each node also has a self-loop) such that this complete graph contains a path of $n - 1$ edges without repeating any edge. Next, we consider how to calculate the length of the longest path in a complete graph with a given number of vertices that does not repeat any edges. Let the number of vertices in the complete graph be $m$. If $m$ is odd, then the degree of each node is even, so this graph contains an Eulerian path, and the path length is equal to the number of edges, which is $\\frac{m(m + 1)}{2}$. If $m$ is even, then the degree of each node is odd, and we need to remove some edges to make this graph contain an Eulerian path. It is easy to see that each edge removed can reduce the number of vertices with odd degrees by at most $2$, so we need to remove at least $\\frac{m}{2} - 1$ edges. Removing the edges $(2, 3), (4, 5), \\ldots, (m - 2, m - 1)$ will suffice, and the path length will be $\\frac{m(m - 1)}{2} - \\frac{m}{2} + 1 + m = \\frac{m^2}{2} + 1$. When $n = 10^6$, the smallest $m$ is $1415$, and the $1415$-th smallest prime number is $11807$, which satisfies $a_i \\le 3 \\cdot 10^5$. We can use binary search to find the smallest $m$ and use Hierholzer's algorithm to find an Eulerian path in an undirected graph. Time complexity: $O(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<int, int> pii;\n\nconst int maxn = 4000100;\nconst int N = 1000000;\n\nint n, a[maxn], pr[maxn], tot, stk[maxn], top;\nbool vis[maxn];\n\ninline void init() {\n\tfor (int i = 2; i <= N; ++i) {\n\t\tif (!vis[i]) {\n\t\t\tpr[++tot] = i;\n\t\t}\n\t\tfor (int j = 1; j <= tot && i * pr[j] <= N; ++j) {\n\t\t\tvis[i * pr[j]] = 1;\n\t\t\tif (i % pr[j] == 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tmems(vis, 0);\n}\n\ninline bool check(int x) {\n\tif (x & 1) {\n\t\treturn x + 1 + x * (x - 1) / 2 >= n;\n\t} else {\n\t\treturn x * (x - 1) / 2 - x / 2 + 2 + x >= n;\n\t}\n}\n\nvector<pii> G[10000];\n\nvoid dfs(int u) {\n\twhile (G[u].size()) {\n\t\tpii p = G[u].back();\n\t\tG[u].pop_back();\n\t\tif (vis[p.scd]) {\n\t\t\tcontinue;\n\t\t}\n\t\tvis[p.scd] = 1;\n\t\tdfs(p.fst);\n\t}\n\tstk[++top] = pr[u];\n}\n\nvoid solve() {\n\tscanf(\"%d\", &n);\n\tint l = 1, r = 10000, ans = -1;\n\twhile (l <= r) {\n\t\tint mid = (l + r) >> 1;\n\t\tif (check(mid)) {\n\t\t\tans = mid;\n\t\t\tr = mid - 1;\n\t\t} else {\n\t\t\tl = mid + 1;\n\t\t}\n\t}\n\tfor (int i = 1; i <= ans; ++i) {\n\t\tvector<pii>().swap(G[i]);\n\t}\n\tint tot = 0;\n\tfor (int i = 1; i <= ans; ++i) {\n\t\tfor (int j = i; j <= ans; ++j) {\n\t\t\tif (ans % 2 == 0 && i % 2 == 0 && i + 1 == j) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tG[i].pb(j, ++tot);\n\t\t\tG[j].pb(i, tot);\n\t\t}\n\t}\n\tfor (int i = 1; i <= tot; ++i) {\n\t\tvis[i] = 0;\n\t}\n\ttop = 0;\n\tdfs(1);\n\treverse(stk + 1, stk + top + 1);\n\tfor (int i = 1; i <= n; ++i) {\n\t\tprintf(\"%d%c\", stk[i], \" \\n\"[i == n]);\n\t}\n}\n\nint main() {\n\tinit();\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1981",
    "index": "E",
    "title": "Turtle and Intersected Segments",
    "statement": "Turtle just received $n$ segments and a sequence $a_1, a_2, \\ldots, a_n$. The $i$-th segment is $[l_i, r_i]$.\n\nTurtle will create an undirected graph $G$. If segment $i$ and segment $j$ intersect, then Turtle will add an undirected edge between $i$ and $j$ with a weight of $|a_i - a_j|$, for every $i \\ne j$.\n\nTurtle wants you to calculate the sum of the weights of the edges of the minimum spanning tree of the graph $G$, or report that the graph $G$ has no spanning tree.\n\nWe say two segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect if and only if $\\max(l_1, l_2) \\le \\min(r_1, r_2)$.",
    "tutorial": "We observe that for three segments $(l_1, r_1, a_1), (l_2, r_2, a_2), (l_3, r_3, a_3)$ where each pair of segments intersects (assume $a_1 \\le a_2 \\le a_3$), we only need to keep the edges between $(1, 2)$ and $(2, 3)$, because $a_3 - a_1 = a_2 - a_1 + a_3 - a_2$ and for every cycle in a graph, the edge with the maximum weight will not appear in the minimum spanning tree. Therefore, consider the following scanline process: each segment is added at $l$ and removed at $r$. When adding a segment, find its predecessor and successor in the order sorted by $a$ and connect edges accordingly. Essentially, we maintain all the segments that exist at each moment as a chain sorted by $a$. It is easy to see that after the scanline process, the number of edges is reduced to $O(n)$. Then we can directly compute the minimum spanning tree. Time complexity: $O(n \\log n)$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<int, int> pii;\n\nconst int maxn = 1000100;\n\nint n, lsh[maxn], tot, fa[maxn];\npii b[maxn];\n\nstruct node {\n\tint l, r, x;\n} a[maxn];\n\nstruct edg {\n\tint u, v, d;\n\tedg(int a = 0, int b = 0, int c = 0) : u(a), v(b), d(c) {}\n} E[maxn];\n\nint find(int x) {\n\treturn fa[x] == x ? x : fa[x] = find(fa[x]);\n}\n\ninline bool merge(int x, int y) {\n\tx = find(x);\n\ty = find(y);\n\tif (x != y) {\n\t\tfa[x] = y;\n\t\treturn 1;\n\t} else {\n\t\treturn 0;\n\t}\n}\n\nvoid solve() {\n\ttot = 0;\n\tcin >> n;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tcin >> a[i].l >> a[i].r >> a[i].x;\n\t\tlsh[++tot] = a[i].l;\n\t\tlsh[++tot] = (++a[i].r);\n\t}\n\tint m = 0;\n\tsort(lsh + 1, lsh + tot + 1);\n\ttot = unique(lsh + 1, lsh + tot + 1) - lsh - 1;\n\tfor (int i = 1; i <= n; ++i) {\n\t\ta[i].l = lower_bound(lsh + 1, lsh + tot + 1, a[i].l) - lsh;\n\t\ta[i].r = lower_bound(lsh + 1, lsh + tot + 1, a[i].r) - lsh;\n\t\tb[++m] = mkp(a[i].l, i);\n\t\tb[++m] = mkp(a[i].r, -i);\n\t}\n\tset<pii> S;\n\tsort(b + 1, b + m + 1);\n\tint tt = 0;\n\tfor (int i = 1; i <= m; ++i) {\n\t\tint j = b[i].scd;\n\t\tif (j > 0) {\n\t\t\tauto it = S.insert(mkp(a[j].x, j)).fst;\n\t\t\tif (it != S.begin()) {\n\t\t\t\tint k = prev(it)->scd;\n\t\t\t\tE[++tt] = edg(j, k, abs(a[j].x - a[k].x));\n\t\t\t}\n\t\t\tif (next(it) != S.end()) {\n\t\t\t\tint k = next(it)->scd;\n\t\t\t\tE[++tt] = edg(j, k, abs(a[j].x - a[k].x));\n\t\t\t}\n\t\t} else {\n\t\t\tj = -j;\n\t\t\tS.erase(mkp(a[j].x, j));\n\t\t}\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tfa[i] = i;\n\t}\n\tsort(E + 1, E + tt + 1, [&](const edg &a, const edg &b) {\n\t\treturn a.d < b.d;\n\t});\n\tll ans = 0, cnt = 0;\n\tfor (int i = 1; i <= tt; ++i) {\n\t\tif (merge(E[i].u, E[i].v)) {\n\t\t\t++cnt;\n\t\t\tans += E[i].d;\n\t\t}\n\t}\n\tcout << (cnt == n - 1 ? ans : -1) << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tint T = 1;\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1981",
    "index": "F",
    "title": "Turtle and Paths on a Tree",
    "statement": "\\textbf{Note the unusual definition of $\\text{MEX}$ in this problem.}\n\nPiggy gave Turtle a \\textbf{binary tree}$^{\\dagger}$ with $n$ vertices and a sequence $a_1, a_2, \\ldots, a_n$ on his birthday. The binary tree is rooted at vertex $1$.\n\nIf a set of paths $P = \\{(x_i, y_i)\\}$ in the tree covers each edge \\textbf{exactly once}, then Turtle will think that the set of paths is good. Note that a good set of paths can cover a vertex twice or more.\n\nTurtle defines the value of a set of paths as $\\sum\\limits_{(x, y) \\in P} f(x, y)$, where $f(x, y)$ denotes the $\\text{MEX}^{\\ddagger}$ of all $a_u$ such that vertex $u$ is on the simple path from $x$ to $y$ in the tree (including the starting vertex $x$ and the ending vertex $y$).\n\nTurtle wonders the \\textbf{minimum} value over all good sets of paths. Please help him calculate the answer!\n\n$^{\\dagger}$A binary tree is a tree where every non-leaf vertex has at most $2$ sons.\n\n$^{\\ddagger}\\text{MEX}$ of a collection of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest \\textbf{positive} integer $x$ which does not occur in the collection $c$. For example, $\\text{MEX}$ of $[3, 3, 1, 4]$ is $2$, $\\text{MEX}$ of $[2, 3]$ is $1$.",
    "tutorial": "Let's consider dp. Let $f_{u, i}$ denote the path extending upward within the subtree rooted at $u$, with the condition that this path does not include the value $i$. The value of $i$ ranges from $[1, n + 1]$. In this case, we can directly take the MEX of this path as $i$, because if the MEX is not $i$, then the MEX will be smaller, making this dp state suboptimal. Let $f_{u,i}$ denote the minimum result of the $\\operatorname{MEX}$ of a path that extends outside the subtree of $u$ and is specified to be $i$ (where $i$ is not included in the result). Since the $\\operatorname{MEX}$ of each path does not exceed $n+1$, the values of $i$ range from $1$ to $n+1$. Consider all the transitions for the dp: If $u$ is a leaf, then: $f_{u,i} = \\begin{cases} 0, & i \\neq a_u \\\\ +\\infty, & i = a_u \\end{cases}$ $f_{u,i} = \\begin{cases} 0, & i \\neq a_u \\\\ +\\infty, & i = a_u \\end{cases}$ If $u$ has only one child, let the child be $x$. Let $\\text{minx} = \\min\\limits_{i \\neq a_u} (f_{x,i} + i)$, then: $f_{u,i} = \\begin{cases} \\min(f_{x,i}, \\text{minx}), & i \\neq a_u \\\\ +\\infty, & i = a_u \\end{cases}$ $f_{u,i} = \\begin{cases} \\min(f_{x,i}, \\text{minx}), & i \\neq a_u \\\\ +\\infty, & i = a_u \\end{cases}$ If $u$ has two children, let the children be $x$ and $y$. Let $\\text{minx} = \\min\\limits_{i \\neq a_u} (f_{x,i} + i)$ and $\\text{miny} = \\min\\limits_{i \\neq a_u} (f_{y,i} + i)$. There are four possible transitions: Continuing the path from the subtree of $x$, i.e., $\\forall i \\neq a_u, f_{u,i} = \\min(f_{u,i}, f_{x,i} + \\text{miny})$ Continuing the path from the subtree of $y$, i.e., $\\forall i \\neq a_u, f_{u,i} = \\min(f_{u,i}, f_{y,i} + \\text{minx})$ Creating a new path and merging the paths from both subtrees, i.e., $\\forall i \\neq a_u, f_{u,i} = \\min(f_{u,i}, \\min\\limits_{j \\neq a_u} (f_{x,j} + f_{y,j} + j))$ Creating a new path without merging the paths from the two subtrees, i.e., $\\forall i \\neq a_u, f_{u,i} = \\min(f_{u,i}, \\text{minx} + \\text{miny})$ Let $k = \\min(\\min\\limits_{i \\neq a_u} (f_{x,i} + f_{y,i} + i), \\text{minx} + \\text{miny})$, then the transition can be written as follows: $f_{u,i} = \\begin{cases} \\min(f_{x,i} + \\text{miny}, f_{y,i} + \\text{minx}, k), & i \\neq a_u \\\\ +\\infty, & i = a_u \\end{cases}$ Continuing the path from the subtree of $x$, i.e., $\\forall i \\neq a_u, f_{u,i} = \\min(f_{u,i}, f_{x,i} + \\text{miny})$ Continuing the path from the subtree of $y$, i.e., $\\forall i \\neq a_u, f_{u,i} = \\min(f_{u,i}, f_{y,i} + \\text{minx})$ Creating a new path and merging the paths from both subtrees, i.e., $\\forall i \\neq a_u, f_{u,i} = \\min(f_{u,i}, \\min\\limits_{j \\neq a_u} (f_{x,j} + f_{y,j} + j))$ Creating a new path without merging the paths from the two subtrees, i.e., $\\forall i \\neq a_u, f_{u,i} = \\min(f_{u,i}, \\text{minx} + \\text{miny})$ Let $k = \\min(\\min\\limits_{i \\neq a_u} (f_{x,i} + f_{y,i} + i), \\text{minx} + \\text{miny})$, then the transition can be written as follows: $f_{u,i} = \\begin{cases} \\min(f_{x,i} + \\text{miny}, f_{y,i} + \\text{minx}, k), & i \\neq a_u \\\\ +\\infty, & i = a_u \\end{cases}$ This results in a time complexity of $O(n^2)$. In fact, we can prove that we only need to consider MEX values up to $O(\\frac{n}{\\ln n})$ (for $n = 25000$, we only need to consider MEX values up to $3863$). Therefore, the second dimension of the dp only needs to be enumerated up to $O(\\frac{n}{\\ln n})$ (or $3863$). Also, we have a construction of a chain that can achieve the MEX value of $O(\\frac{n}{\\ln n})$, which is enumerating $i$ from $1$ and listing all the divisors of $i$ in descending order, such as $[1, 2, 1, 3, 1, 4, 2, 1, 5, 1]$. Time complexity: $O(\\frac{n^2}{\\ln n})$ per test case. Proof of the upper bound for MEX: Let's only consider the case of a chain. For a fixed $x$, consider a sequence like $[a, \\ldots, b, x, c, \\ldots, d, x, e, \\ldots, f, x, g, \\ldots, h]$. We can divide it into segments as follows: $[a, \\ldots, b], [b, x, c], [c, \\ldots, d], [d, x, e], [e, \\ldots, f], [f, x, g], [g, \\ldots, h]$ Where segments without $x$ have a MEX value $\\le x$, and segments with $x$ have a MEX value $\\le 4$. Let $t$ be the answer. Then, $t$ satisfies: (where $c_i$ is the number of occurrences of $i$) $\\min_{i \\ge 1} (c_i + 1) i + 4 c_i \\ge t$ Expanding, we get: $\\min_{i \\ge 1} (c_i + 1) (i + 4) \\ge t$ Furthermore, for segments like $[b, x, c]$, if $x \\ge 4$, then the term $4c_i$ above can be reduced to $3c_i$ (since $x$ can be none of $1, 2, 3$). So, we have: $\\min(\\min_{i = 1}^3 (c_i + 1)(i + 4), \\min_{i \\ge 4}(c_i + 1)(i + 3)) \\ge t$ Hence: $c_i \\ge \\begin{cases} \\left\\lceil\\frac{t}{i + 4}\\right\\rceil - 1 & 1 \\le i \\le 3 \\\\ \\left\\lceil\\frac{t}{i + 3}\\right\\rceil - 1 & i \\ge 4 \\end{cases}$ This means we need $O(\\frac{t}{i})$ occurrences of $i$, and since $n = O(t \\ln t)$, we have $t = O(\\frac{n}{\\ln n})$. We also have: $n = \\sum_{i \\ge 1} c_i \\ge \\sum_{i = 1}^3 (\\left\\lceil\\frac{t}{i + 4}\\right\\rceil - 1) + \\sum_{i \\ge 4} (\\left\\lceil\\frac{t}{i + 3}\\right\\rceil - 1)$ By fixing $n$, we can binary search for the largest $t$ satisfying the above condition, and for $n = 25000$, we find $t = 3863$. Read the $O(n^2)$ part of Solution 1 first. Consider using a segment tree to maintain the dp values. The transitions for $u$ with at most one child are easy to maintain, so we only need to consider the case with two children. First, use a segment tree to maintain the minimum value of $f_{u,i} + i$, so $\\text{minx}$ and $\\text{miny}$ can be computed. The value of $f_{u,a_u}$ can be set to $+\\infty$ by a point update. Ignoring how to compute $k$ for now, in the end, all $f_{x,i}$ are incremented by $\\text{miny}$, all $f_{y,i}$ are incremented by $\\text{minx}$, and the segment trees are merged. Finally, all $f_{u,i}$ are taken as the minimum with $k$. To compute $k$, which is $\\min\\limits_{i \\neq a_u} (f_{x,i} + f_{y,i} + i)$, we can use a similar segment tree merging method, quickly computing this as we recursively descend to the leaf nodes of the segment tree. Additionally, we need to maintain the minimum value of $f_{u,i}$. Time complexity: $\\mathcal{O}(n \\log n)$ per test case.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nnamespace my_std{\n\t#define ll long long\n\t#define bl bool\n\tll my_pow(ll a,ll b,ll mod){\n\t\tll res=1;\n\t\tif(!b) return 1;\n\t\twhile(b){\n\t\t\tif(b&1) res=(res*a)%mod;\n\t\t\ta=(a*a)%mod;\n\t\t\tb>>=1;\n\t\t}\n\t\treturn res;\n\t}\n\tll qpow(ll a,ll b){\n\t\tll res=1;\n\t\tif(!b) return 1;\n\t\twhile(b){\n\t\t\tif(b&1) res*=a;\n\t\t\ta*=a;\n\t\t\tb>>=1;\n\t\t}\n\t\treturn res;\n\t}\n\t#define db double\n\t#define pf printf\n\t#define pc putchar\n\t#define fr(i,x,y) for(register ll i=(x);i<=(y);i++)\n\t#define pfr(i,x,y) for(register ll i=(x);i>=(y);i--)\n\t#define go(u) for(ll i=head[u];i;i=e[i].nxt)\n\t#define enter pc('\\n')\n\t#define space pc(' ')\n\t#define fir first\n\t#define sec second\n\t#define MP make_pair\n\t#define il inline\n\t#define inf 1e18\n\t#define random(x) rand()*rand()%(x)\n\t#define inv(a,mod) my_pow((a),(mod-2),(mod))\n\til ll read(){\n\t\tll sum=0,f=1;\n\t\tchar ch=0;\n\t\twhile(!isdigit(ch)){\n\t\t\tif(ch=='-') f=-1;\n\t\t\tch=getchar();\n\t\t}\n\t\twhile(isdigit(ch)){\n\t\t\tsum=sum*10+(ch^48);\n\t\t\tch=getchar();\n\t\t}\n\t\treturn sum*f;\n\t}\n\til void write(ll x){\n\t\tif(x<0){\n\t\t\tx=-x;\n\t\t\tpc('-');\n\t\t}\n\t\tif(x>9) write(x/10);\n\t\tpc(x%10+'0');\n\t}\n\til void writeln(ll x){\n\t\twrite(x);\n\t\tenter;\n\t}\n\til void writesp(ll x){\n\t\twrite(x);\n\t\tspace;\n\t}\n}\nusing namespace my_std;\n#define LC tree[x].lc\n#define RC tree[x].rc\nll t,n,a[25025],ch[25025][2],ans=inf;\nll rt[25025],tot=0;\nstruct node{\n\tll minn1,minn2,lz,lzmin,lc,rc;\n\til void addtag(ll v,ll vmin,ll l){\n\t\tminn1=min(minn1+v,vmin);\n\t\tminn2=min(minn2+v,vmin+l);\n\t\tlz+=v;\n\t\tlzmin=min(lzmin+v,vmin);\n\t}\n}tree[1000010];\nil void pushup(ll x){\n\ttree[x].minn1=min(tree[LC].minn1,tree[RC].minn1);\n\ttree[x].minn2=min(tree[LC].minn2,tree[RC].minn2);\n}\nil ll newnode(){\n\ttree[++tot]=(node){(ll)inf,(ll)inf,0,(ll)inf,0,0};\n\treturn tot;\n}\nil void pushdown(ll x,ll l,ll r){\n\tif(!LC) LC=newnode();\n\tif(!RC) RC=newnode();\n\tll mid=(l+r)>>1;\n\ttree[LC].addtag(tree[x].lz,tree[x].lzmin,l);\n\ttree[RC].addtag(tree[x].lz,tree[x].lzmin,mid+1);\n\ttree[x].lz=0;\n\ttree[x].lzmin=inf;\n}\nvoid upd(ll &x,ll l,ll r,ll pos){\n\tif(!x) x=newnode();\n\tif(l==r){\n\t\ttree[x].minn1=tree[x].minn2=inf;\n\t\treturn;\n\t}\n\tll mid=(l+r)>>1;\n\tpushdown(x,l,r);\n\tif(pos<=mid) upd(LC,l,mid,pos);\n\telse upd(RC,mid+1,r,pos);\n\tpushup(x);\n}\nvoid add(ll &x,ll l,ll r,ll ql,ll qr,ll v){\n\tif(!x) x=newnode();\n\tif(ql<=l&&r<=qr){\n\t\ttree[x].addtag(v,(ll)inf,l);\n\t\treturn;\n\t}\n\tll mid=(l+r)>>1;\n\tpushdown(x,l,r);\n\tif(ql<=mid) add(LC,l,mid,ql,qr,v);\n\tif(mid<qr) add(RC,mid+1,r,ql,qr,v);\n\tpushup(x);\n}\nvoid mdf(ll &x,ll l,ll r,ll ql,ll qr,ll v){\n\tif(!x) x=newnode();\n\tif(ql<=l&&r<=qr){\n\t\ttree[x].addtag(0,v,l);\n\t\treturn;\n\t}\n\tll mid=(l+r)>>1;\n\tpushdown(x,l,r);\n\tif(ql<=mid) mdf(LC,l,mid,ql,qr,v);\n\tif(mid<qr) mdf(RC,mid+1,r,ql,qr,v);\n\tpushup(x);\n}\nll merge(ll x,ll y,ll l,ll r){\n\tif(!LC&&!RC){\n\t\ttree[y].addtag(0,tree[x].minn1,l);\n\t\treturn y;\n\t}\n\tif(!tree[y].lc&&!tree[y].rc){\n\t\ttree[x].addtag(0,tree[y].minn1,l);\n\t\treturn x;\n\t}\n\tll mid=(l+r)>>1;\n\tpushdown(x,l,r);\n\tpushdown(y,l,r);\n\tLC=merge(LC,tree[y].lc,l,mid);\n\tRC=merge(RC,tree[y].rc,mid+1,r);\n\tpushup(x);\n\treturn x;\n}\nll query(ll x,ll y,ll l,ll r){\n\tif(!LC&&!RC) return tree[x].minn1+tree[y].minn2;\n\tif(!tree[y].lc&&!tree[y].rc) return tree[y].minn1+tree[x].minn2;\n\tll mid=(l+r)>>1,res=inf;\n\tpushdown(x,l,r);\n\tpushdown(y,l,r);\n\tres=min(res,query(LC,tree[y].lc,l,mid));\n\tres=min(res,query(RC,tree[y].rc,mid+1,r));\n\treturn res;\n}\nvoid dfs(ll u){\n\tif(!ch[u][0]){\n\t\tmdf(rt[u],1,n+1,1,n+1,0);\n\t\tif(a[u]<=(n+1)) upd(rt[u],1,n+1,a[u]);\n\t\tif(u==1) ans=0;\n\t}\n\telse if(!ch[u][1]){\n\t\tdfs(ch[u][0]);\n\t\trt[u]=rt[ch[u][0]];\n\t\tif(a[u]<=(n+1)) upd(rt[u],1,n+1,a[u]);\n\t\tll minn=tree[rt[u]].minn2;\n\t\tmdf(rt[u],1,n+1,1,n+1,minn);\n\t\tif(a[u]<=(n+1)) upd(rt[u],1,n+1,a[u]);\n\t\tif(u==1) ans=minn;\n\t}\n\telse{\n\t\tll x=ch[u][0],y=ch[u][1];\n\t\tdfs(x);\n\t\tdfs(y);\n\t\tif(a[u]<=(n+1)){\n\t\t\tupd(rt[x],1,n+1,a[u]);\n\t\t\tupd(rt[y],1,n+1,a[u]);\n\t\t}\n\t\tll minx=tree[rt[x]].minn2,miny=tree[rt[y]].minn2,k=min(query(rt[x],rt[y],1,n+1),minx+miny);\n\t\tadd(rt[x],1,n+1,1,n+1,miny);\n\t\tadd(rt[y],1,n+1,1,n+1,minx);\n\t\trt[u]=merge(rt[x],rt[y],1,n+1);\n\t\tmdf(rt[u],1,n+1,1,n+1,k);\n\t\tif(a[u]<=(n+1)) upd(rt[u],1,n+1,a[u]);\n\t\tif(u==1) ans=k;\n\t}\n}\nil void clr(){\n\tfr(i,1,n) ch[i][0]=ch[i][1]=rt[i]=0;\n\ttot=0;\n\tans=inf;\n}\nint main(){\n\tt=read();\n\twhile(t--){\n\t\tn=read();\n\t\tfr(i,1,n) a[i]=read();\n\t\tfr(i,2,n){\n\t\t\tll x=read();\n\t\t\tif(!ch[x][0]) ch[x][0]=i;\n\t\t\telse ch[x][1]=i;\n\t\t}\n\t\tdfs(1);\n\t\twriteln(ans);\n\t\tclr();\n\t}\n}\n/*\n1\n5\n3 2 2 1 1\n1 1 2 2\nans:\n4 \n*/ ",
    "tags": [
      "data structures",
      "dp",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1982",
    "index": "A",
    "title": "Soccer",
    "statement": "Dima loves watching soccer. In such a game, the score on the scoreboard is represented as $x$ : $y$, where $x$ is the number of goals of the first team, and $y$ is the number of goals of the second team. At any given time, only one team can score a goal, so the score $x$ : $y$ can change to either $(x + 1)$ : $y$, or $x$ : $(y + 1)$.\n\nWhile watching a soccer game, Dima was distracted by very important matters, and after some time, he returned to watching the game. Dima remembers the score right before he was distracted, and the score right after he returned. Given these two scores, he wonders the following question. Is it possible that, \\textbf{while Dima was not watching the game}, the teams never had an equal score?\n\nIt is guaranteed that at neither of the two time points Dima remembers the teams had equal scores. However, it is possible that the score did not change during his absence.\n\nHelp Dima and answer the question!",
    "tutorial": "In all cases where the first team initially led the score, and then the second team, there will be a moment when the score is equal, so it is enough to check only this condition. If it is met, the answer is \"NO\", otherwise the answer is \"YES\". Let's demonstrate how events could have unfolded without an equal score, if the condition is not met. Let $x_{1} > y_{1}$ and $x_{2} > y_{2}$, then the events could have occurred as follows: $x_{1}$ : $y_{1}$($x_{1} + 1$) : $y_{1}$ ($x_{1} + 2$) : $y_{1}$ ... $x_{2}$ : $y_{1}$ $x_{2}$ : ($y_{1} + 1$) $x_{2}$ : ($y_{1} + 2$) ... $x_{2}$ : $y_{2}$ ($x_{1} + 1$) : $y_{1}$ ($x_{1} + 2$) : $y_{1}$ ... $x_{2}$ : $y_{1}$ $x_{2}$ : ($y_{1} + 1$) $x_{2}$ : ($y_{1} + 2$) ... $x_{2}$ : $y_{2}$",
    "code": "t = int(input())\nfor T in range(t):\n\tla, lb = map(int, input().split())\n\tra, rb = map(int, input().split())\n\tif la > lb:\n\t\tla, lb, ra, rb = lb, la, rb, ra\n\tif la < lb and rb < ra:\n\t\tprint(\"NO\")\n\telse:\n\t\tprint(\"YES\")",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1982",
    "index": "B",
    "title": "Collatz Conjecture",
    "statement": "Recently, the first-year student Maxim learned about the Collatz conjecture, but he didn't pay much attention during the lecture, so he believes that the following process is mentioned in the conjecture:\n\nThere is a variable $x$ and a constant $y$. The following operation is performed $k$ times:\n\n- increase $x$ by $1$, then\n- while the number $x$ is divisible by $y$, divide it by $y$.\n\nNote that both of these actions are performed sequentially within one operation.For example, if the number $x = 16$, $y = 3$, and $k = 2$, then after one operation $x$ becomes $17$, and after another operation $x$ becomes $2$, because after adding one, $x = 18$ is divisible by $3$ twice.\n\nGiven the initial values of $x$, $y$, and $k$, Maxim wants to know what is the final value of $x$.",
    "tutorial": "Let's write down what happens in the problem and try to speed it up. The first observation: we will perform operations until $x \\neq 1$, after which the answer can be found using the formula $ans = 1 + k\\,\\%\\,(y - 1)$. Indeed, after $x$ becomes equal to $1$, if we continue applying operations to it, it will change as follows: $1 \\to 2 \\to ... \\to (y - 1) \\to 1 \\to 2 \\to ... \\to (y - 1) \\to 1 \\to ...$ The second optimization is to group the operations that only add one, so instead of $1$ we will add the next value to $x$ in one action $min(k, \\lceil \\frac{x}{y} \\rceil \\cdot y - x)$. After this (if we added at least $1$), we should try to divide the number by $y$ (if it is divisible). If we use these two optimizations, our solution will work in $O(\\log x)$ for one set of input data, since in one action $x$ decreases to $\\lceil \\frac{x + 1}{y} \\rceil$, and therefore $x$ becomes $1$ in no more than $O(\\log x)$ actions.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve(){\n\tlong long x, y, k;\n\tcin >> x >> y >> k;\n\twhile (k > 0 && x != 1) {\n\t\tlong long ost = (x / y + 1) * y - x;\n                ost = max(1ll, ost);\n                ost = min(ost, k);\n                x += ost;\n\t\twhile (x % y == 0) {\n\t\t\tx /= y;\n\t\t}\n\t\tk -= ost;\n\t}\n\tcout << x + k % (y - 1) << '\\n';\n}\n \nint main()\n{\n#ifdef FELIX\n\tauto _clock_start = chrono::high_resolution_clock::now();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n \n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 0; test < tests; test++){\n\t\tsolve();\n\t}\n \n#ifdef FELIX\n\tcerr << \"Executed in \" << chrono::duration_cast<chrono::milliseconds>(\n\t\tchrono::high_resolution_clock::now()\n\t\t\t- _clock_start).count() << \"ms.\" << endl;\n#endif\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1982",
    "index": "C",
    "title": "Boring Day",
    "statement": "On another boring day, Egor got bored and decided to do something. But since he has no friends, he came up with a game to play.\n\nEgor has a deck of $n$ cards, the $i$-th card from the top has a number $a_i$ written on it. Egor wants to play a certain number of rounds until the cards run out. In each round, he takes a non-zero number of cards from the top of the deck and finishes the round. If the sum of the numbers on the cards collected during the round is between $l$ and $r$, inclusive, the round is won; otherwise, it is lost.\n\nEgor knows by heart the order of the cards. Help Egor determine the maximum number of rounds he can win in such a game. Note that Egor is not required to win rounds consecutively.",
    "tutorial": "Solution 1: Let $dp[i]$ - the maximum number of rounds won by Egor for the first $i$ elements (top cards). It is possible to come up with a solution in $O(n^{2})$ right now. For each state of the dynamic programming $i$, you can either skip the next card (not take it in any winning segment), or iterate over the length of the segment that will start with the next card. If you calculate prefix sums and compute the sum over a segment in $O(1)$, the solution works exactly in $O(n^{2})$. Let's try to optimize the transitions in such a dynamic. First, it can be noticed that all $a_{i}$ are positive, which means that the sum of the segment $(a, b)$ will be less than $(a, b + 1)$. This means that the first suitable segment (with a sum $\\ge l$) can be found using binary search or two pointers. Secondly, if the segment has a suitable sum (from $l$ to $r$), it does not make sense to increase its length, as this can only worsen the answer. Thus, for each state of the dynamic programming, there are only $O(1)$ transitions, so the entire problem can be solved in $O(n)$ or $O(n\\log n)$. Solution 2: Let's try to solve the problem greedily. Let's look for a segment $(a, b)$ in the prefix such that the sum of all its elements is not less than $l$ and not greater than $r$, and among all such segments, we will take the segment with the minimum $b$. After that, we will consider that the array starts from the $(b + 1)$-th element and continue to search for the next segment in the same way. How to find $(a, b)$? Let's start by finding the minimum prefix $k$ (which is also the segment $(1, k)$) such that the sum of the elements in it is $\\ge l$. If this sum is also not greater than $r$, then this prefix is the segment we need $(a, b)$. Otherwise, we know that the sum of the elements in any subsegment of this prefix that does not contain the last element $a_{k}$ is less than $l$, so we can try to find a subsegment that ends at $k$, for this, we can iterate over the left boundary from $1$ to $k$. At the same time, the sum of the elements in the iterated segment will decrease and it may happen again that at some point it becomes $< l$, in this case, we already know that we will not find the required segment with the right boundary $k$, so it needs to be increased (again until the sum becomes $\\ge l$). By repeating these actions, we will either find the required segment $(a, b)$, or the right boundary will become equal to $n$. The algorithm is nothing but \"two pointers\", we keep two boundaries $l$ and $r$ and move them only to the right, so in total, this all works in $O(n)$.",
    "code": "t = int(input())\nfor T in range(t):\n\tn, l, r = map(int, input().split())\n\ta = [int(x) for x in input().split()]\n\tans = 0\n\tcur = 0\n\tL, R = 0, 0\n\twhile L < n:\n\t\twhile R < n and cur < l:\n\t\t\tcur += a[R]\n\t\t\tR += 1\n\t\tif l <= cur and cur <= r:\n\t\t\tans += 1\n\t\t\tL = R\n\t\t\tcur = 0\n\t\telse:\n\t\t\tcur -= a[L]\n\t\t\tL += 1\n\tprint(ans)",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1982",
    "index": "D",
    "title": "Beauty of the mountains",
    "statement": "Nikita loves mountains and has finally decided to visit the Berlyand mountain range! The range was so beautiful that Nikita decided to capture it on a map. The map is a table of $n$ rows and $m$ columns, with each cell containing a non-negative integer representing the height of the mountain.\n\nHe also noticed that mountains come in two types:\n\n- With snowy caps.\n- Without snowy caps.\n\nNikita is a very pragmatic person. He wants the sum of the heights of the mountains with snowy caps to be equal to the sum of the heights of the mountains without them. He has arranged with the mayor of Berlyand, Polikarp Polikarpovich, to allow him to transform the landscape.\n\nNikita can perform transformations on submatrices of size $k \\times k$ as follows: he can add an integer constant $c$ to the heights of the mountains within this area, but the type of the mountain remains unchanged. Nikita can choose the constant $c$ independently for each transformation. \\textbf{Note that $c$ can be negative}.\n\nBefore making the transformations, Nikita asks you to find out if it is possible to achieve equality of the sums, or if it is impossible. It doesn't matter at what cost, even if the mountains turn into canyons and have negative heights.\n\nIf only one type of mountain is represented on the map, then the sum of the heights of the other type of mountain is considered to be zero.",
    "tutorial": "First, let's calculate the current difference between the heights of different types of mountains, denoted as $D$. Then, for each submatrix of size $k \\times k$, we will calculate how the difference in the sums of heights of different types of mountains changes. That is, for each submatrix, we will calculate the difference in the number of zeros and ones in it, let these values be $d_{i}$ and there will be $q = (n - k + 1) \\cdot (m - k + 1)$. This can be done using two-dimensional prefix sums or a \"sliding window\". After that, formally we can write the following equation: $c_{1} \\cdot d_{1} + c_{2} \\cdot d_{2} + \\dots + c_{q} \\cdot d_{q} = D$ , where $c_{1}$, $c_{2}$, ..., $c_{q}$ - are constants $c$ that Nikita chose for a specific submatrix ($0$ if we did not transform using this submatrix). This is very similar to a Diophantine equation, in fact, it is, but with $q$ unknowns. What can be said about the existence of a solution to this equation in integers? For this, it is sufficient that $D \\bmod gcd(d_{1}, d_{2}, \\dots, d_{q}) = 0$ It is worth mentioning that it is necessary to carefully handle the case when all $d_{i} = 0$, and also not to forget about the case when $D$ is initially equal to $0$. In total, the solution is in $O(n \\cdot m + \\log A)$",
    "code": "import math\n \ndef solve():\n    n, m, k = map(int, input().split())\n    a = [[int(x) for x in input().split()] for j in range(n)]\n    s = [input() for i in range(n)]\n    pref = [[0 for i in range(m + 1)] for j in range(n + 1)]\n    diff = 0\n    for i in range(n):\n        cur = 0\n        for j in range(m):\n            if s[i][j] == '1':\n                cur += 1\n                diff += a[i][j]\n            else:\n                diff -= a[i][j]\n            pref[i + 1][j + 1] = pref[i][j + 1] + cur\n    if diff == 0:\n        print(\"YES\")\n        return\n    g = 0\n    for i in range(n - k + 1):\n        for j in range(m - k + 1):\n            f = pref[i + k][j + k] - pref[i + k][j] - pref[i][j + k] + pref[i][j]\n            f = abs(k * k - 2 * f)\n            g = math.gcd(g, f)\n    if g == 0 or diff % g != 0:\n        print(\"NO\")\n    else:\n        print(\"YES\")\n \n \nif __name__ == \"__main__\":\n    t = int(input())\n    for _ in range(t):\n        solve()",
    "tags": [
      "brute force",
      "data structures",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1982",
    "index": "E",
    "title": "Number of k-good subarrays",
    "statement": "Let $bit(x)$ denote the number of ones in the binary representation of a non-negative integer $x$.\n\nA subarray of an array is called $k$-good if it consists only of numbers with no more than $k$ ones in their binary representation, i.e., a subarray $(l, r)$ of array $a$ is good if for any $i$ such that $l \\le i \\le r$ condition $bit(a_{i}) \\le k$ is satisfied.\n\nYou are given an array $a$ of length $n$, consisting of consecutive non-negative integers starting from $0$, i.e., $a_{i} = i$ for $0 \\le i \\le n - 1$ (in $0$-based indexing). You need to count the number of $k$-good subarrays in this array.\n\nAs the answer can be very large, output it modulo $10^{9} + 7$.",
    "tutorial": "Let $f(n, k)$ be a function to solve the problem, which will return three values $(l, r, ans)$ such that: $l$ - for the first $l$ numbers (i.e. from $0$ to $l - 1$) $bit(x) \\le k$ holds, while $bit(l) > k$ or $l \\ge n$; $r$ - for the last $r$ numbers (i.e. from $n - r$ to $n - 1$) $bit(x) \\le k$ holds, while $bit(n - r - 1) > k$ or $n - r - 1 < 0$; $ans$ - the answer for the pair $(n, k)$. Let's use the \"divide and conquer\" approach. Divide the segment from $0$ to $n$ into two segments: from $0$ to $2^{m} - 1$, where $m$ is the maximum such that $2^{m} < n$; from $2^{m}$ to $n - 1$. It can be noticed that instead of calculating the function on the segment from $2^{k}$ to $n - 1$, it is possible to calculate it from $0$ to $n - 1 - 2^{m}$, but with a smaller $k$. More formally, $f(n, k)$ can be recalculated through $f(2^{m}, k)$ and $f(n - 2^{m}, k - 1)$. Based on the pair of triples $(l_{1}, r_{1}, ans_{1})$, which is obtained after calculating $f(2^{m}, k)$ and $(l_{2}, r_{2}, ans_{2})$, which is obtained after calculating $f(n - 2^{m}, k - 1)$, it is quite trivial to recalculate the triple for $f(n, k)$ using the formula in $O(1)$. However, the solution still works in $O(n)$ time, as we will have a complete binary tree of recursive calls. To fix this, it is only necessary to precalculate all $f(2^{m}, k)$ for each possible $k$ and $m$. For $f(2^{m}, k)$, it can be noticed that it is recalculated through $f(2^{m - 1}, k)$ and $f(2^{m - 1}, k - 1)$, so all values can be calculated using dynamic programming. After this, in the recursive function, we always calculate $f(2^{m}, k)$ in $O(1)$, and for the next call, the first argument is halved, so now everything works in $O(\\log n)$ for one test case. In total, the solution is in $O(\\log n)$ for the test case.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 1000000007;\n \nmap<pair<long long, int>, tuple<int, long long, long long>> mem;\n \ntuple<int, long long, long long> calc(long long n, int k){\n\tif (k < 0){\n\t\treturn tuple{0, 0ll, 0ll};\n\t}\n\tif (n == 1){\n\t\treturn tuple{1, 1ll, 1ll};\n\t}\n\tint bit = 63 - __builtin_clzll(n);\n\tlong long mid = (1ll << bit);\n\tif (mid == n){\n\t\tmid >>= 1;\n\t\tif (mem.count({n, k})){\n\t\t\treturn mem[{n, k}];\n\t\t}\n\t}\n\tauto [f1, s1, e1] = calc(mid, k);\n\tauto [f2, s2, e2] = calc(n - mid, k - 1);\n \n\tint sub1 = (e1 % MOD) * ((e1 + 1) % MOD) % MOD * 500000004 % MOD;\n\tf1 = (f1 * 1ll - sub1 + MOD) % MOD;\n\tint sub2 = (s2 % MOD) * ((s2 + 1) % MOD) % MOD * 500000004 % MOD;\n\tf2 = (f2 * 1ll - sub2 + MOD) % MOD;\n \n\tlong long p = (e1 + s2) % MOD;\n\tint f_cur = (f1 * 1ll + f2 + (p * 1ll * ((p + 1) % MOD) % MOD * 500000004 % MOD)) % MOD;\n\tlong long s_cur = s1;\n\tlong long e_cur = e2;\n\tif (s1 == e1 && s1 != 0){\n\t\ts_cur = (s1 + s2);\n\t}\n\tif (s2 == e2 && s2 != 0){\n\t\te_cur = (e1 + e2);\n\t}\n\tif ((mid << 1) == n){\n\t\tmem[{n, k}] = tuple{f_cur, s_cur, e_cur};\n\t}\n\treturn tuple{f_cur, s_cur, e_cur};\n};\n \nvoid solve(){\n\tlong long n;\n\tint k;\n\tcin >> n >> k;\n\tcout << get<0>(calc(n, k)) << '\\n';\n}\n \nint main()\n{\n#ifdef FELIX\n\tauto _clock_start = chrono::high_resolution_clock::now();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n \n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 0; test < tests; test++){\n\t\tsolve();\n\t}\n \n#ifdef FELIX\n\tcerr << \"Executed in \" << chrono::duration_cast<chrono::milliseconds>(\n\t\tchrono::high_resolution_clock::now()\n\t\t\t- _clock_start).count() << \"ms.\" << endl;\n#endif\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "divide and conquer",
      "dp",
      "math",
      "meet-in-the-middle"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1982",
    "index": "F",
    "title": "Sorting Problem Again",
    "statement": "You have an array $a$ of $n$ elements. There are also $q$ modifications of the array. Before the first modification and after each modification, you would like to know the following:\n\nWhat is the minimum length subarray that needs to be sorted in non-decreasing order in order for the array $a$ to be completely sorted in non-decreasing order?\n\nMore formally, you want to select a subarray of the array $(l, r)$ with the minimum value of $r - l + 1$. After that, you will sort the elements $a_{l}, a_{l + 1}, \\ldots, a_{r}$ and want the condition $a_{i} \\le a_{i + 1}$ to hold for all $1 \\le i < n$. If the array is already sorted in non-decreasing order, then $l$ and $r$ should be considered as equal to $-1$.\n\nNote that finding such $(l, r)$ does not change the array in any way. The modifications themselves take the form: assign $a_{pos} = x$ for given $pos$ and $x$.",
    "tutorial": "Let's maintain a set $s$ of positions $i$ such that $a_{i} < a_{i - 1}$, and also a segment tree (or any other data structure that allows changing the value at a position and finding the minimum/maximum on a segment). Recalculating the set and the segment tree is quite simple for each change in the array $a$. To answer a query, let's notice a few facts: If $s$ is empty, then the array $a$ is completely sorted. If $s$ is not empty, then we can find the minimum and maximum elements from this set, denote them as $pos_{min}$, $pos_{max}$. With these elements, we can easily answer queries. Similarly to the previous point, we can say that the prefix of size $pos_{min}$ and the suffix of size $n - 1 - pos_{max}$ are sorted in non-decreasing order. Now, at the very least, we need to sort the segment $(l, r)$ such that $l \\le pos_{min}$, $r > pos_{max}$. How can we find exactly these $l$ and $r$? First, let's find $l$. To do this, we find the minimum on the segment $(pos_{min} - 1, pos_{max})$, this value will be somewhere in the prefix of the entire array, so we need to find the position in the prefix between which elements it should be inserted. But we also know that the prefix is sorted, so we can use binary search (as in insertion sort) and find the position for this value. This position will be our $l$. For $r$, everything is similar, we find the maximum on the segment $(pos_{min} - 1, pos_{max})$ and also find its position in the sorted suffix. In conclusion, to find the answer after changing the array, we need to find the maximum/minimum positions in $s$, the maximum/minimum on the segment, and perform $2$ binary searches on the prefix and suffix. All of this works in $O(\\log n)$. Complexity: $O((n + q) \\cdot \\log n)$ It is also worth noting that some solutions with $O((n + q) \\cdot \\log^{2} n)$ can also fit within the time limit if they are very carefully written and use a non-recursive segment tree.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int inf = 1000000007;\n \nstruct SegTree{\n\tvector<int> mn, mx;\n\tint n;\n\tSegTree(int _n): n(_n){\n\t\tmx.assign(2 * n, -inf);\n\t\tmn.resize(2 * n, inf);\n\t}\n \n\tvoid upd(int pos, int val){\n\t\tmx[pos + n] = val;\n\t\tmn[pos + n] = val;\n\t\tpos = (pos + n) >> 1;\n\t\tfor (;pos > 0; pos >>= 1){\n\t\t\tmx[pos] = max(mx[pos << 1], mx[(pos << 1) | 1]);\n\t\t\tmn[pos] = min(mn[pos << 1], mn[(pos << 1) | 1]);\n\t\t}\n\t}\n \n\tpair<int,int> get(int l, int r){\n\t\tpair<int,int> res = {-inf, inf};\n\t\tl += n;\n\t\tr += n + 1;\n\t\tfor (;l < r; l >>= 1, r >>= 1){\n\t\t\tif (l & 1) {\n\t\t\t\tres.first = max(res.first, mx[l]);\n\t\t\t\tres.second = min(res.second, mn[l++]);\n\t\t\t}\n\t\t\tif (r & 1) {\n\t\t\t\tres.first = max(res.first, mx[--r]);\n\t\t\t\tres.second = min(res.second, mn[r]);\n\t\t\t}\t\t\t\n\t\t}\n\t\treturn res;\n\t}\n};\n \nvoid solve(){\n\tint n;\n\tcin >> n;\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; i++){\n\t\tcin >> a[i];\n\t}\n \n\tSegTree tree(n);\n\tset<int> st;\n\tfor (int i = 0; i < n; i++){\n\t\ttree.upd(i, a[i]);\n\t\tif (i > 0 && a[i] < a[i - 1]){\n\t\t\tst.insert(i);\n\t\t}\n\t}\n \n\tfunction<int(int, int)> find_pref = [&](int pos, int x){\n\t\tif (pos < 0){\n\t\t\treturn 0;\n\t\t}\n\t\tint l = 0, r = pos;\n\t\twhile(l <= r){\n\t\t\tint m = l + (r - l) / 2;\n\t\t\tif (a[m] > x){\n\t\t\t\tr = m - 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tl = m + 1;\n\t\t\t}\n\t\t}\n\t\treturn r + 1;\n\t};\n \n\tfunction<int(int, int)> find_suff = [&](int pos, int x){\n\t\tif (pos >= n){\n\t\t\treturn n - 1;\n\t\t}\n\t\tint l = pos, r = n - 1;\n\t\twhile(l <= r){\n\t\t\tint m = l + (r - l) / 2;\n\t\t\tif (a[m] >= x){\n\t\t\t\tr = m - 1;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tl = m + 1;\n\t\t\t}\n\t\t}\n\t\treturn r;\n\t};\n \n\tfunction<void()> query = [&](){\n\t\tif (st.empty()){\n\t\t\tcout << -1 << ' ' << -1 << '\\n';\n\t\t\treturn;\n\t\t}\n\t\tint l = *st.begin() - 1;\n\t\tint r = *(--st.end());\n \n\t\tauto [mx, mn] = tree.get(l, r);\n \n\t\tcout << find_pref(l - 1, mn) + 1 << ' ' << find_suff(r + 1, mx) + 1 << '\\n';\n\t};\n \n\tquery();\n\tint q;\n\tcin >> q;\n\tfor (int i = 0; i < q; i++){\n\t\tint pos, val;\n\t\tcin >> pos >> val;\n\t\tpos--;\n\t\tif (pos > 0 && a[pos] < a[pos - 1]){\n\t\t\tst.erase(pos);\n\t\t}\n\t\tif (pos + 1 < n && a[pos + 1] < a[pos]){\n\t\t\tst.erase(pos + 1);\n\t\t}\n\t\ta[pos] = val;\n\t\ttree.upd(pos, val);\n\t\tif (pos > 0 && a[pos] < a[pos - 1]){\n\t\t\tst.insert(pos);\n\t\t}\n\t\tif (pos + 1 < n && a[pos + 1] < a[pos]){\n\t\t\tst.insert(pos + 1);\n\t\t}\n\t\tquery();\n\t}\n}\n \nint main()\n{\n#ifdef FELIX\n\tauto _clock_start = chrono::high_resolution_clock::now();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 0; test < tests; test++){\n\t\tsolve();\n\t}\n#ifdef FELIX\n\tcerr << \"Executed in \" << chrono::duration_cast<chrono::milliseconds>(\n\t\tchrono::high_resolution_clock::now()\n\t\t\t- _clock_start).count() << \"ms.\" << endl;\n#endif\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1983",
    "index": "A",
    "title": "Array Divisibility",
    "statement": "An array of integers $a_1,a_2,\\cdots,a_n$ is beautiful subject to an integer $k$ if it satisfies the following:\n\n- The sum of $a_{j}$ over all $j$ such that $j$ is a multiple of $k$ and $1 \\le j \\le n $, itself, is a multiple of $k$.\n- More formally, if $\\sum_{k | j} a_{j}$ is divisible by $k$ for all $1 \\le j \\le n$ then the array $a$ is beautiful subject to $k$. Here, the notation ${k|j}$ means $k$ divides $j$, that is, $j$ is a multiple of $k$.\n\nGiven $n$, find an array of positive nonzero integers, with each element less than or equal to $10^5$ that is beautiful subject to all $1 \\le k \\le n$.It can be shown that an answer always exists.",
    "tutorial": "The construction $a[i] = i$ for all $1 \\le i \\le n$ satisfies all the required conditions.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    for i in range(1, n + 1):\n        print(i, end=\" \")\n    print()",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1983",
    "index": "B",
    "title": "Corner Twist",
    "statement": "You are given two grids of numbers $a$ and $b$, with $n$ rows and $m$ columns. All the values in the grid are $0$, $1$ or $2$.\n\nYou can perform the following operation on $a$ any number of times:\n\n- Pick any subrectangle in the grid with length and width $\\ge 2$. You are allowed to choose the entire grid as a subrectangle.\n- The subrectangle has four corners. Take any pair of diagonally opposite corners of the chosen subrectangle and add $1$ to their values modulo $3$.\n- For the pair of corners not picked, add $2$ to their values modulo $3$.\n\nNote that the operation only changes the values of the corners of the picked subrectangle.\n\nIs it possible to convert the grid $a$ into grid $b$ by applying the above operation any number of times (possibly zero)?",
    "tutorial": "Notice how the operations affect each row and column. The problem offers a really simple solution: the sum of each row and each column modulo $3$ needs to remain constant throughout all the operations. It is easy to see that this is a necessary condition. Let's prove that this is sufficient as well. Notice that using the 2x2 versions of the operations defined in the statement, i.e., addition of $\\begin{matrix}1 & 2 \\\\ 2 & 1\\end{matrix}$ or $\\begin{matrix}2 & 1 \\\\ 1 & 2\\end{matrix}$ along the corners of a 2x2 square can be used to generate the same result as the operation applied on any rectangle. For instance, we can combine two 2x2 operations sideways to get a 2x3 operation: $\\begin{matrix}1 & \\fbox{2+1} & 2\\\\ 2 & \\fbox{1+2} & 1\\end{matrix} \\equiv \\begin{matrix}1 & 0 & 2\\\\ 2 & 0 & 1\\end{matrix} \\pmod{3}$ If $a[i][j] + 1 \\equiv b[i][j] \\pmod{3}$, add $\\begin{matrix}1 & 2 \\\\ 2 & 1\\end{matrix}$ to the subrectange of $a$ starting at $a[i[j]$. If $a[i][j] + 2 \\equiv b[i][j] \\pmod{3}$, add $\\begin{matrix}2 & 1 \\\\ 1 & 2\\end{matrix}$ to the subrectange of $a$ starting at $a[i[j]$. Make no changes otherwise. We see that it is always possible to make all the elements in the first $n-1$ rows and $m-1$ columns equal using this method. Note that the sum of each row and each column stays constant after each operation. If $b$ is derived from $a$ using these operations, then all the values for the remaining $n + m - 1$ elements of the grid can be uniquely determined using the row and column sums and need to be equal. Hence, proving sufficiency.",
    "code": "t = int(input())\nwhile(t):\n    t -= 1\n    n, m = list(map(int,input().split(' ')))\n    grid_a = []\n    grid_b = []\n    for i in range(n):\n        grid_a.append(list(map(int, list(input()))))\n    for i in range(n):\n        grid_b.append(list(map(int, list(input()))))\n    ac = [0] * n\n    ar = [0] * m\n    bc = [0] * n\n    br = [0] * m\n    for i in range(n):\n        for j in range(m):\n            ac[i] += grid_a[i][j]\n            bc[i] += grid_b[i][j]\n            ar[j] += grid_a[i][j]\n            br[j] += grid_b[i][j]\n    ok = True\n    for i in range(n):\n        ok &= (ac[i] % 3 == bc[i] % 3)\n    for i in range(m):\n        ok &= (br[i] % 3 == ar[i] % 3)\n    if ok:\n        print(\"Yes\")\n    else:\n        print(\"No\")",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1983",
    "index": "C",
    "title": "Have Your Cake and Eat It Too",
    "statement": "Alice, Bob and Charlie want to share a rectangular cake cut into $n$ pieces. Each person considers every piece to be worth a different value. The $i$-th piece is considered to be of value $a_i$ by Alice, $b_i$ by Bob and $c_i$ by Charlie.\n\nThe sum over all $a_i$, all $b_i$ and all $c_i$ individually is the same, equal to $tot$.\n\nGiven the values of each piece of the cake for each person, you need to give each person a contiguous slice of cake. In other words, the indices at the left and right ends of these subarrays (the slices given to each person) can be represented as $(l_a, r_a)$, $(l_b, r_b)$ and $(l_c, r_c)$ respectively for Alice, Bob and Charlie. The division needs to satisfy the following constraints:\n\n- No piece is assigned to more than one person, i.e., no two subarrays among $[l_a,\\ldots,r_a]$, $[l_b, \\ldots, r_b]$ and $[l_c, \\ldots, r_c]$ intersect.\n- $ \\sum_{i = l_a}^{r_a} a_i, \\sum_{i = l_b}^{r_b} b_i, \\sum_{i = l_c}^{r_c} c_i \\geq \\lceil \\frac{tot}{3} \\rceil$.\n\nHere, the notation $\\lceil \\frac{a}{b} \\rceil$ represents ceiling division. It is defined as the smallest integer greater than or equal to the exact division of $a$ by $b$. In other words, it rounds up the division result to the nearest integer. For instance $\\lceil \\frac{10}{3} \\rceil = 4$ and $\\lceil \\frac{15}{3} \\rceil = 5$.",
    "tutorial": "There can be several correct answers. It is sufficient to find any correct answer. Although it is not necessary to finish the entire cake, we can easily find a way such that the entire cake is given away. We can start by trying to give a prefix to Alice. To determine if it is possible to divide the cake such that Alice gets at least one-third of the total value by taking a prefix, and Bob and Charlie can split the remaining cake into two parts where each gets at least one-third of the total value, we can use the following approach: We start by calculating the prefix sums for Alice, Bob, and Charlie. Using these prefix sums, we iterate left to right to search for the minimum prefix size for Alice, where she gets at least one-third of the total value. Once we find an index, we give that prefix to Alice and search again on array $b$ to check if we can give a prefix of the remaining cake to Bob such that Bob gets at least one-third of the total sum, and so does Charlie. If, after removing the prefix of the remaining cake, the value left for Charlie is not enough, we repeat the last step on array $c$ instead and check if the value of the cake left for Bob after Alice and Charlie get theirs' is enough. If the above fails, we repeat the process starting with a prefix of $b$. If that fails too, we try again, beginning with a prefix of $c$. Here are the specific steps for each of the 6 permutations of Alice, Bob, and Charlie: 1. Start with a prefix for Alice, then check Bob's prefix and Charlie gets the rest of the cake. 2. Start with a prefix for Alice, then check Charlie's prefix and Bob gets the rest of the cake. 3. Start with a prefix for Bob, then check Alice's prefix and Charlie gets the rest of the cake. 4. Start with a prefix for Bob, then check Charlie's prefix and Alice gets the rest of the cake. 5. Start with a prefix for Charlie, then check Alice's prefix and Bob gets the rest of the cake. 6. Start with a prefix for Charlie, then check Bob's prefix and Alice gets the rest of the cake. If after trying all permutations, none of them work, the answer is \"-1\". Otherwise, print the respective indices for the subarrays.",
    "code": "from itertools import permutations\n \nt = int(input())\n \nwhile(t):\n    t -= 1\n    n = int(input())\n    val = [[0],[0],[0]]\n    pf = [[0],[0],[0]]\n    for i in range(3):\n        val[i] += list(map(int,input().split(' ')))\n    for i in range(3):\n        for j in range(1,n+1):\n            pf[i].append(pf[i][j-1] + val[i][j])\n \n    ok = False\n    perms = list(permutations([0,1,2]))\n    comp = (pf[0][n]+2)//3\n \n    for i in range(6):\n        cur = 1\n        perm = perms[i]\n        while(cur <= n and pf[perm[0]][cur] < comp): cur += 1\n        for j in range(cur+1, n):\n            if(pf[perm[1]][j] - pf[perm[1]][cur] >= comp and pf[perm[2]][n] - pf[perm[2]][j] >= comp):\n                ans = [[],[],[]]\n                ans[perm[0]] = [1,cur]\n                ans[perm[1]] = [cur+1,j]\n                ans[perm[2]] = [j+1,n]\n \n                for x in ans: print(x[0], x[1])\n                print()\n                ok = True\n                break\n \n        if(ok): break\n    \n    if(not ok):\n        print(-1)\n        print()",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1983",
    "index": "D",
    "title": "Swap Dilemma",
    "statement": "Given two arrays of distinct positive integers $a$ and $b$ of length $n$, we would like to make both the arrays the same. Two arrays $x$ and $y$ of length $k$ are said to be the same when for all $1 \\le i \\le k$, $x_i = y_i$.\n\nNow in one move, you can choose some index $l$ and $r$ in $a$ ($l \\le r$) and swap $a_l$ and $a_r$, then choose some $p$ and $q$ ($p \\le q$) in $b$ such that $r-l=q-p$ and swap $b_p$ and $b_q$.\n\nIs it possible to make both arrays the same?",
    "tutorial": "If both the arrays don't have the same multiset of elements then trivially the answer is \"NO\". Otherwise, we can convert any operation of the form $l$, $r$, $p$, $q$ to swapping $l$, $l+1$, $p$, $p+1$ multiple times. For example: swapping $l=1$, $r=3$, $p=2$, $q=4$ can be converted into three steps: swapping $l=1$, $r=2$, $p=2$, $q=3$, then swapping $l=2$, $r=3$, $p=3$, $q=4$ and finally $l=1$, $r=2$, $p=2$, $q=3$. This can be generalized for any such operation. An interesting observation here is that swapping any two adjacent elements in a distinct array leads to a change in number of inversions of that array by $1$ - which essentially means the parity of inversions of the array gets changed. So, if both the arrays don't have the same parity of inversions initially, they will never have the same parity of inversions. Now, we will prove that when both arrays have the same parity of inversions, then it is definitely possible to make them equal. Keep using operations for array $a$ of the form $l=1$ and $r=2$ while changing the operation $p, q$ to different values to make the elements at indices $3, 4, \\ldots n$ the same in array $b$ as they are in array $a$. Now, since both the arrays should have the same parity of inversions at the end, $a_1 = b_1$ and $a_2 = b_2$, and so, our arrays $a$ and $b$ will become equal. Therefore, the answer is \"YES\" in this case.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\nusing namespace std;\n \nint inversions(int arr[],int l,int r){\n    if(r==l)return 0;\n    \n    //divide and conquer:\n    int mid=(l+r)/2;\n    int x=inversions(arr,l,mid);\n    int y=inversions(arr,mid+1,r);\n \n    //simple merging:\n    int ans[r-l+1];\n \n    int curr=0,inv=0;\n    int pointx=l,pointy=mid+1;\n    while(pointx<=mid && pointy<=r){\n        if(arr[pointx]<arr[pointy]){\n            inv+=pointy-mid-1;\n            ans[curr]=arr[pointx];\n            \n            pointx++;\n        }\n        else{\n            ans[curr]=arr[pointy];\n            \n            pointy++;\n        }\n \n        curr++;\n    }\n \n    while(pointx<=mid){\n        inv+=pointy-mid-1;\n        ans[curr]=arr[pointx];\n            \n        pointx++;\n        curr++;\n    }\n \n    while(pointy<=r){\n        ans[curr]=arr[pointy];\n \n        pointy++;\n        curr++;\n    }\n \n    //final writeback:\n    for(int i=l;i<=r;i++){\n        arr[i]=ans[i-l];\n    }\n \n    return x+y+inv;\n}\n \nint32_t main(){\n    int t;\n    cin >> t;\n    while(t--){\n        int n;\n        cin >> n;\n        int a[n],b[n],x[n],y[n];\n        for(int i=0;i<n;i++){\n            cin >> a[i];\n            x[i]=a[i];\n        }\n        for(int i=0;i<n;i++){\n            cin >> b[i];\n            y[i]=b[i];\n        }\n        \n        sort(x,x+n);\n        sort(y,y+n);\n        \n        int flag=0;\n        for(int i=0;i<n;i++){\n            if(x[i]!=y[i])flag=1;\n        }\n \n        cout << (((inversions(a,0,n-1)%2)==(inversions(b,0,n-1)%2)) && flag==0 ? \"YES\" : \"NO\") << \"\\n\";\n    }\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1983",
    "index": "E",
    "title": "I Love Balls",
    "statement": "Alice and Bob are playing a game. There are $n$ balls, out of which $k$ are special. Each ball has a value associated with it.\n\nThe players play turn by turn. In each turn, the player randomly picks a ball and adds the value of the ball to their score, which is $0$ at the beginning of the game. The selected ball is removed from the game. If the ball was special, the same player takes the next turn if at least one ball is remaining. If the ball picked was not special, the next player plays their turn.\n\nThey play this game until no balls are remaining in the game. Alice plays first.\n\nFind the expected score that both the players have at the end of the game modulo $10^9+7$.\n\nFormally, let $M = 10^9+7$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "When there are no special balls, Alice and Bob alternately pick balls starting with Alice. This means Alice picks ${\\frac{n+1}{2}}$ balls if $n$ is odd or $\\frac{n}{2}$ if $n$ is even. The total value of all balls is $\\sum v_i$. On average, Alice's score is $\\lfloor\\frac{n + 1}{2}\\rfloor \\cdot \\frac{\\sum v_i}{n}$. With $k$ special balls, the picking order can be interrupted, allowing the same player to pick again. We need to distribute $k$ special balls into $n - k + 1$ possible positions (gaps). The expected number of special balls picked by Alice can be derived as the expected number of gaps encountered by Alice ($\\lfloor\\frac{n - k + 2}{2}\\rfloor$) times the expected number of special balls per gap($\\frac{k}{n - k + 1}$). The formula is $\\frac{(\\lfloor\\frac{n - k + 2}{2} \\rfloor) \\cdot k}{n - k + 1}$. Expected value without special balls: $\\lfloor\\frac{n + 1}{2}\\rfloor \\cdot \\frac{\\sum v_i}{n}$. Expected special balls for Alice: $\\frac{(\\lfloor\\frac{n - k}{2}\\rfloor + 1) \\cdot k}{n - k + 1}$. Expected normal balls for Alice when there are non-zero special balls: $\\lfloor\\frac{n - k + 1}{2}\\rfloor$ Therefore, expected score of Alice: $\\frac{(\\lfloor\\frac{n - k}{2}\\rfloor + 1) \\cdot k}{n - k + 1} \\cdot \\frac{\\sum_{i \\in \\{1,2, \\cdot \\cdot \\cdot k\\}}{v_i}}{k} + \\lfloor\\frac{n - k + 1}{2}\\rfloor \\cdot \\frac{\\sum_{i \\in \\{k+1,k+2, \\cdot \\cdot \\cdot n\\}}{v_i}}{n - k}$ Similarly, expected score of Bob: $(k - \\frac{(\\lfloor\\frac{n - k}{2}\\rfloor + 1) \\cdot k}{n - k + 1}) \\cdot \\frac{\\sum_{i \\in \\{1,2, \\cdot \\cdot \\cdot k\\}}{v_i}}{k} + (n - k - \\lfloor \\frac{n - k + 1}{2} \\rfloor) \\cdot \\frac{\\sum_{i \\in \\{k+1,k+2, \\cdot \\cdot \\cdot n\\}}{v_i}}{n - k}$",
    "code": "#include <iostream>\n#include <vector>\n \n#define int long long\n \nconst int mod = 1e9 + 7;\n \nint power(int a, int b) {\n    int ans = 1;\n    while (b) {\n        if (b & 1) ans = (ans * a) % mod;\n        a = (a * a) % mod;\n        b >>= 1;\n    }\n    return ans;\n}\n \nint inline inv(int x) { return power(x, mod - 2); }\n \nvoid solve() {\n    int N, K;\n    std::cin >> N >> K;\n \n    std::vector<int> values(N);\n    int avg_special_value = 0, avg_normal_value = 0;\n    for (int i = 0; i < N; i++) {\n        std::cin >> values[i];\n        if (i < K)\n            avg_special_value += values[i];\n        else\n            avg_normal_value += values[i];\n    }\n \n    int total_score = (avg_normal_value + avg_special_value) % mod;\n \n    avg_normal_value %= mod;\n    avg_special_value %= mod;\n \n    avg_special_value = (avg_special_value * inv(K)) % mod;\n    avg_normal_value = (avg_normal_value * inv(N - K)) % mod;\n \n    int count_normal_balls = (N - K + 1) / 2;\n    int expected_special_balls =\n        (((((N - K + 2) / 2) * K) % mod) * inv(N - K + 1)) % mod;\n \n    int expected_alice_score = (count_normal_balls * avg_normal_value +\n                                expected_special_balls * avg_special_value) %\n                               mod;\n \n    int expected_bob_score =\n        ((total_score - expected_alice_score) % mod + mod) % mod;\n \n    std::cout << expected_alice_score << \" \" << expected_bob_score << \"\\n\";\n}\n \nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(0);\n    \n    int t;\n    std::cin >> t;\n    while (t--) {\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "math",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1983",
    "index": "F",
    "title": "array-value",
    "statement": "You have an array of non-negative integers $a_1, a_2, \\ldots, a_n$.\n\nThe value of a sub-array of length $\\ge 2$, $a[l, r] = [a_l, a_{l+1}, \\ldots, a_r]$ is the minimum value of $a_i \\oplus a_j$ such that $l \\le i < j \\le r$, where $\\oplus$ is the xor (exclusive-or) operator.\n\nYou have to find the $k$-th smallest value over all sub-arrays of length $\\ge 2$.",
    "tutorial": "We can binary search on the the value of the $k$th-smallest and maintain the number of subarrays with xor-pair less than the value. This way, we can find the $k$th-smallest value easily. In order to maintain the number of subarrays, we can use our popular xor data structure called trie. For a given binary searched value, we will traverse from left to right, putting in the values of the array in our trie with their highest corresponding indices. For a fixed index $i$, we would like to find the highest index $j<i$ such that the subarray from $[j,i]$ contains xor-pair less than the fixed upper bound. Then all subarrays with their left end between $[1,j]$ and right end fixed at $i$ will have xor-pair less than the value. Therefore, this becomes a sliding window where we want to maximize the value of the left end $j$ so that the number of subarrays for a fixed right end $i$ becomes as large as possible. To achieve this, we would maintain in our trie the following two things: - the current bit (on/off) - the maximum index which reached this bit in our trie Now when querying: - if both searched bit and current array index bit is $1$: take the max for left index from child \"on\" bit and go to child \"off\" bit - if both searched bit and current array index bit is $0$: just go to child \"off\" bit - if searched bit is $1$ and current array index bit is $0$: take the max for left index from child \"off\" bit and go to child \"on\" bit - if searched bit is $0$ and current array index bit is $1$: just go to child \"on\" bit This is done so that we can find the maximum left index for the given fixed right index at $i$. We follow binary searched value as closely as possible while traversing the trie to stay under the upper bound as well as maximize the left index. Finally, putting the values and corresponding index in the trie is trivial. Simply follow the trie and put in the corresponding bits the maximum index which can reach that bit. This way we can solve this problem in $O(n \\log^2 n)$",
    "code": "#include <bits/stdc++.h>\n \n#define endl \"\\n\"\nusing namespace std;\n \nint ch[3000042][2]{}, mx[3000042]{};\nint nc = 1;\nvoid insert(int root,int val,int idx){\n    int curr=root;\n    for(int i=29;i>=0;i--){\n        int lr = ((val&(1<<i)) != 0);\n        \n        if(!ch[curr][lr]){\n            nc++;\n            mx[nc]=idx;\n            ch[curr][lr]=nc;\n        }\n \n        mx[curr]=max(mx[curr],idx);\n        curr=ch[curr][lr];\n    }\n \n    mx[curr]=max(mx[curr],idx);\n}\n \nint query(int root,int mid,int val){\n    int curr=root;\n    int idx=-1;\n \n    for(int i=29;i>=0;i--){\n        if(!curr)return idx;\n \n        //check out with 1\n        if((val&(1<<i)) && (mid&(1<<i))){\n            if(ch[curr][1])idx=max(idx,mx[ch[curr][1]]);\n            curr=ch[curr][0];\n        }\n        else if((val&(1<<i))){\n            curr=ch[curr][1];\n        }\n        else if((mid&(1<<i))){\n            if(ch[curr][0])idx=max(idx,mx[ch[curr][0]]);\n            curr=ch[curr][1];\n        }\n        else{\n            curr=ch[curr][0];\n        }\n    }\n \n    if(curr)idx=max(idx,mx[curr]);\n \n    return idx;\n}\n \n \nint v[100069]{};\nint32_t main(){ \n    int t;\n    cin >> t;\n    while(t--){\n        int n;\n        long long k;\n        cin >> n >> k;\n        for(int i=0;i<n;i++){\n            cin >> v[i];\n        }\n \n        int l=0,r=(1<<30)-1,fin;\n        while(l<=r){\n            int mid=l+(r-l)/2;\n \n            int left=-1;\n            long long ans=0;\n            nc = 1;\n            int root = nc;\n            for(int i=0;i<n;i++){\n                left=max(left,query(root,mid,v[i]));\n                ans+=((long long)left+1);\n                insert(root,v[i],i);\n            }\n \n            for(int i=0;i<=nc;i++){\n                ch[i][0] = 0;\n                ch[i][1] = 0;\n                mx[i] = 0;\n            }\n \n            if(ans<k){\n                l=mid+1;\n            }\n            else{\n                fin=mid;\n                r=mid-1;\n            }\n        }\n \n        cout << fin << endl;\n    }\n \n    return 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1983",
    "index": "G",
    "title": "Your Loss",
    "statement": "You are given a tree with $n$ nodes numbered from $1$ to $n$, along with an array of size $n$. The value of $i$-th node is $a_{i}$. There are $q$ queries. In each query, you are given 2 nodes numbered as $x$ and $y$.\n\nConsider the path from the node numbered as $x$ to the node numbered as $y$. Let the path be represented by $x = p_0, p_1, p_2, \\ldots, p_r = y$, where $p_i$ are the intermediate nodes. Compute the sum of $a_{p_i}\\oplus i$ for each $i$ such that $0 \\le i \\le r$ where $\\oplus$ is the XOR operator.\n\nMore formally, compute $$\\sum_{i =0}^{r} a_{p_i}\\oplus i$$.",
    "tutorial": "We'll solve for each bit separately. Observe that the number of nodes contributing to the sum for a fixed bit $j$ is the sum of the bit xor'ed with an alternating pattern of $2^j$ continuous bits over the path, i.e., say for $j=2$, the bits are xor'ed with $0000111100001\\ldots$. For the rest of the editorial, we will use the word \"bit pattern\" to refer to this binary string. Let's root the tree arbitrarily and define $dp[u][j]$ as the number of nodes that contribute $2^j$ to the sum required in the query on the path from the node $u$ to the root. Notice that for $dp[u][j]$ the pattern $000\\ldots0111\\ldots1$ transitions from $0$ to $1$ at the $2^j$th ancestor of $u$. Hence, you can compute $dp[u][j]$ just by knowing the value of the $dp$ at the $2^j$th ancestor and its depth, and the sum of set bits on the remaining path. You can precompute all the power of two ancestors by binary jumping and calculate sums using root-to-node prefix sums. Now, you need to keep track of a few variables to answer queries. Let there be a query from the node $u$ to the node $v$. We define $lc$ as $lca(u,v)$. For a fixed bit $j$, let there be nodes $ux[j],vx[j]$ such that the path from $ux[j]$ to $vx[j]$ is the largest subpath of the path from $u$ to $v$ with $lc$ lying on this path and all the bits from the pattern being the same over this path. Let's call it the central path. One more position to keep track of is the node $vy[j]$ such that it is the lowest ancestor of $v$ where the length of the path from $u$ to $vy$ is a multiple of $2^j$ and $vy$ lies on the path from $u$ to $v$. It is possible that this node does not exist. Notice that the bit pattern for $dp[vy][j]$ upwards will coincide or will be the exact opposite of the bit pattern for the query up to the node $lc$. With these values computed, we can split the query path into separate paths; the answer for each can be easily calculated using prefix sums and precomputed $dp$ values: The path from $u$ to $ux[j]$. The path from $ux[j]$ to $vx[j]$. The path from $vx[j]$ to $vy[j]$. The path from $vy[j]$ to $v$. To compute these three positions quickly, we will again use binary jumping, precomputing these for all queries. To compute $vy[j]$, we notice that for $vy[0] = v$. Then, we make binary jumps whenever necessary. For $ux[j]$ and $vx[j]$, we can start iterating from a bit larger than n to the smallest, noting that if $2^j >= n$, the endpoints will be $ux[j]=u$ and $vx[j]=v$. We make binary jumps when necessary, $vy[j]$ is also required for the computation. Another alternative to binary jumping is to maintain a list of ancestors of the current node while running dfs on the tree and calculate these positions directly during the dfs for each query.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int MAX = 5e5+5;\nconst int MAXL = 20;\nconst int QMAX = 1e5+5;\nint n,q,b[MAX];\nvector<int>g[MAX];\nvector<array<int,3>>qinfo(QMAX);\nvector<long long>ans(QMAX,0);\nint up[MAX][MAXL],depth[MAX];\nint pf[MAX], dp[MAX];\nint u_split[QMAX][MAXL+1], v_split[QMAX][MAXL+1], v_end[QMAX][MAXL+1]{};\n \nvoid dfs(int a,int p,int d) {\n    up[a][0]=p;\n    depth[a]=d;\n    for(int j=1;j<MAXL;j++) {\n        up[a][j]=up[up[a][j-1]][j-1];\n    }\n    for(int i=0;i<g[a].size();i++) {\n        if(g[a][i]!=p) {\n            dfs(g[a][i],a,d+1);\n        }\n    }\n}\n// no of nodes in path [u..v] lca is lc\nint get_length(int u,int v,int lc) {\n    return depth[u]+depth[v]-2*depth[lc]+1;\n}\n \nint get_kth(int a,int k) {\n    int curr=a;\n    for(int i=0;i<MAXL;i++) {\n        if((k>>i)&1) {\n            curr=up[curr][i];\n        }\n    }\n    return curr;\n}\n \nint lca(int a,int b) {\n    if(depth[b]<depth[a]) {\n        swap(a,b);\n    }\n    b=get_kth(b,depth[b]-depth[a]);\n    if(a==b) {\n        return a;\n    }\n    for(int j=MAXL-1;j>=0;j--) {\n        if(up[a][j]!=up[b][j]) {\n            a=up[a][j],b=up[b][j];\n        }\n    }\n    return up[a][0];\n}\n \nint get_sum(int u, int v, int lc, int k){\n    return pf[u] + pf[v] -2*pf[lc] + ((b[lc]>>k)&1);\n}\n \nvoid calc_dp_pf(int a, int p, int k){\n    pf[a] = pf[p] + ((b[a]>>k)&1);\n    int next = up[a][k];\n    if(depth[a]>(1<<k)) dp[a]=depth[next]-dp[next]+pf[a]-pf[next];\n    else dp[a] = pf[a];\n    for(int i=0;i<g[a].size();i++) {\n        if(g[a][i]!=p) {\n            calc_dp_pf(g[a][i],a,k);\n        }\n    }\n}\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin>>t;\n    dp[0] = 0;\n    pf[0] = 0;\n    while(t--) {\n        int n,q;\n        cin>>n;\n        for(int i=0;i<n-1;i++) {\n            int a,b;\n            cin>>a>>b;\n            g[a].push_back(b);\n            g[b].push_back(a);\n        }\n        for(int i=1;i<=n;i++) {\n            cin>>b[i];\n        }\n        dfs(1,0,1);\n        cin>>q;\n        for(int i=0;i<q;i++) {\n            int u,v;\n            cin>>u>>v;\n            qinfo[i] = {u,v,lca(u,v)};\n            ans[i] = 0;\n        }\n        for(int i=0;i<q;i++){\n            int u = qinfo[i][0], v = qinfo[i][1], lc = qinfo[i][2];\n            v_end[i][0] = v;\n            if(v == lc) v_end[i][0] = 0;\n            for(int j=1;j<MAXL;j++){\n                if(v_end[i][j-1] != 0 && (get_length(u, v_end[i][j-1], lc) & ((1 << j) - 1))){\n                    v_end[i][j] = up[v_end[i][j-1]][j-1];\n                    if(depth[v_end[i][j]] < depth[lc]) v_end[i][j] = 0;\n                }\n                else v_end[i][j] = v_end[i][j-1];\n            }\n            v_split[i][MAXL] = v;\n            u_split[i][MAXL] = u;\n            for(int j=MAXL-1;j>=0;j--){\n                if(depth[u_split[i][j+1]] - (1<<j) >= depth[lc]) u_split[i][j] = up[u_split[i][j+1]][j];\n                else u_split[i][j] = u_split[i][j+1];\n \n                if(v_end[i][j] && v_end[i][j+1] == 0) v_split[i][j] = v_end[i][j];\n                else if(depth[v_split[i][j+1]] - (1<<j) >= depth[lc]) v_split[i][j] = up[v_split[i][j+1]][j];\n                else v_split[i][j] = v_split[i][j+1];\n            }\n        }\n        \n        for(int j=0;j<MAXL;j++) {\n            calc_dp_pf(1,0,j);\n            for(int i=0;i<q;i++) {\n                long long temp = 0;\n                \n                int u = qinfo[i][0], v = qinfo[i][1], lc = qinfo[i][2];\n                int us = u_split[i][j], vs = v_split[i][j], vend = v_end[i][j];\n                int center = get_sum(us, vs, lc, j);\n \n                if(((depth[u] - depth[us]) >> j) & 1){\n                    center = get_length(us, vs, lc) - center;\n                    temp += dp[u] - depth[us] + dp[us];\n                }else temp += dp[u] - dp[us];\n                temp += center;\n \n                if(vend){\n                    if((get_length(u,vend,lc) >> j) & 1){\n                        temp += depth[v] - depth[vend] - pf[v] + pf[vend];\n                        if(((depth[vend] - depth[vs]) >> j) & 1) temp += dp[vend] - depth[vs] + dp[vs];\n                        else temp += dp[vend] - dp[vs];\n                    }else{\n                        temp += pf[v] - pf[vend];\n                        if(((depth[vend] - depth[vs]) >> j) & 1) temp += depth[vend] - dp[vend] - dp[vs];\n                        else temp += depth[vend] - dp[vend] - depth[vs] + dp[vs];\n                    }\n                    \n                }\n                ans[i] += temp << j;\n \n \n            }\n        }\n        for(int i=0;i<q;i++) {\n            cout<<ans[i]<<\"\\n\";\n        }\n        for(int i=1;i<=n;i++) {\n            g[i].clear();\n        }\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1984",
    "index": "A",
    "title": "Strange Splitting",
    "statement": "Define the range of a non-empty array to be the maximum value minus the minimum value. For example, the range of $[1,4,2]$ is $4-1=3$.\n\nYou are given an array $a_1, a_2, \\ldots, a_n$ of length $n \\geq 3$. \\textbf{It is guaranteed $a$ is sorted}.\n\nYou have to color each element of $a$ red or blue so that:\n\n- the range of the red elements \\textbf{does not equal} the range of the blue elements, and\n- there is at least one element of each color.\n\n\\textbf{If there does not exist any such coloring, you should report it.} If there are multiple valid colorings, you can print any of them.",
    "tutorial": "When is it impossible? When $a = [x, x \\dots x]$ for some $x$. Only color one element red to make the range $0$. Which one do you pick to make the blue range different? Read the hints. It is impossible to color the array when all the elements are the same, because the range for the red and blue elements will always be $0$. Otherwise, notice there will always be at least $2$ distinct values in the array. This means there is a way to get a positive range for the blue elements, by taking the maximum value and the minimum value and coloring them blue. This works because $n \\geq 3$, so there is at least one element left. Since we can get a positive range, we can then try to get the red elements to have a range of $0$, by coloring exactly one value red. So, we can color any $a_i$ for $2 \\leq i \\leq n - 1$ red since it will not affect the positive range we constructed for the blue elements. For simplicity sake, our solution chooses $i = 2$. Then, the remaining elements can be colored blue. Therefore, our final solution is to check if it is impossible, or color $a_2$ red and the rest blue.",
    "code": "#include <iostream>\nusing namespace std;\nint main(){\n    int T; cin >> T;\n\n    while (T--) {\n\n        int n; cin >> n;\n\n        vector<int> a(n);\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n\n        if (a[0] == a[n - 1]) {\n            cout << \"NO\" << \"\\n\";\n        }\n        else {\n            cout << \"YES\" << \"\\n\";\n            string s(n, 'R'); \n            s[1] = 'B';\n            cout << s << \"\\n\";\n\n        }\n\n        \n    }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "1984",
    "index": "B",
    "title": "Large Addition",
    "statement": "A digit is large if it is between $5$ and $9$, inclusive. A positive integer is large if all of its digits are large.\n\nYou are given an integer $x$. Can it be the sum of two large positive integers with the \\textbf{same number of digits}?",
    "tutorial": "Solution 1 What must the first (largest) digit be? What must the other non-unit digits be? What must the last digit be? Because every digit is large, every two digits being added together will carry to the next digit. The two addends have the same length, so the sum must be one greater in length, with the largest digit equal to $1$. For all other digits except for the units digit, we have the value to be the sum of two large digits, plus $1$ being carried over from the previous column. This makes the acceptable range of values be from $1$ to $9$, inclusive. For the units digit, there is no previous column to carry over a $1$, so the acceptable range of values is from $0$ to $8$, inclusive.",
    "code": "\n#include <iostream>\nusing namespace std;\n \n#define ll long long\n \nvoid solve() {\n  ll n; cin >> n;\n  n = n - n % 10 + (n % 10 + 1) % 10;\n  while (n > 9) {\n    if (n % 10 == 0) {\n      cout << \"NO\\n\";\n      return;\n    }\n    n /= 10;\n  }\n  cout << (n == 1 ? \"YES\\n\" : \"NO\\n\");\n}\n \nint main() {\n  ios_base::sync_with_stdio(false); cin.tie(NULL);\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) solve();\n  return 0;\n}\n\n",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1984",
    "index": "C2",
    "title": "Magnitude (Hard Version)",
    "statement": "\\textbf{The two versions of the problem are different. You may want to read both versions. You can make hacks only if both versions are solved.}\n\nYou are given an array $a$ of length $n$. Start with $c = 0$. Then, for each $i$ from $1$ to $n$ (in increasing order) do \\textbf{exactly one} of the following:\n\n- Option $1$: set $c$ to $c + a_i$.\n- Option $2$: set $c$ to $|c + a_i|$, where $|x|$ is the absolute value of $x$.\n\nLet the maximum final value of $c$ after the procedure described above be equal to $k$. Find the number of unique procedures that result in $c = k$. Two procedures are different if at any index $i$, one procedure chose option $1$ and another chose option $2$, even if the value of $c$ is equal for both procedures after that turn.\n\nSince the answer may be large, output it modulo $998\\,244\\,353$.",
    "tutorial": "How many times do we need to pick option $2$? We only need to pick it once. How can we calculate the final value for every position we can pick? We only need to pick option $2$ once. Why? Assume we picked option $2$ more than once, and consider the last two times it was picked. Both of these must occur when $c + a_i$ is negative, otherwise there is no reason to pick option $2$ over option $1$. Thus, if we chose option $1$ the first of these times instead of option $2$, that would cause the value of $c$ before the second operation to decrease. Because it was negative, this increases the magnitude, and thus it was more optimal to choose option $1$ for the first operation. Because we only need to use option $2$ once, we can brute force where we use that operation and compute the final value of $c$ with prefix sums. Read the solution to the easy version first. Let's think a bit more. Where do we actually end up using option $2$? We only use option $2$ when our prefix sum up to this point is minimum in the whole array. Now, focus on each individual \"important\" use of option $2$ (where it actually makes a difference from option $1$), Let's say it is done at index $i$. Let's consider indices before. Since the operation at index $i$ is the only important option $2$, any option $2$'s we use before must not have been different from option $1$ (meaning that the value of $c + a_j$ has to be non-negative). Thus, we have the choice of using option $2$ or option $1$ at any index $j < i$ where the prefix sum is non-negative. Let's say there exists $x$ unique values of $j$. Now, let's consider indices after. Since index $i$ is at a minimum prefix sum, that guarantees that all indices after will never have a lower value of $c$ than what $c$ is after doing the operation at index $i$. Thus, since we use option 2 at index $i$, we can use any of the two options moving forward. Thus, any index $j > i$ has two choices on which option to pick. Let's say there exists $y$ unique values of $j$. The contribution of index $i$ to the answer is then $2^{x + y}$. Special case: the prefix sum never becomes negative. What is the answer then?",
    "code": "\n#include <iostream>\n#include <vector>\n#include <climits>\nusing namespace std;\n \n#define ll long long\n \nconst ll MAX_N = 400001;\nconst ll MOD = 998244353;\n \nvector<ll> p2(MAX_N);\n \nvoid solve() {\n  int n; cin >> n;\n  vector<int> arr(n); for (int i = 0; i < n; ++i) cin >> arr[i];\n  ll sum = 0, mn = 0, ans = 0, abses = 0;\n  for (int i = 0; i < n; ++i) sum += arr[i], mn = min(mn, sum);\n  if (mn == 0) {\n      cout << p2[n] << '\\n';\n      return;\n  }\n  sum = 0;\n  for (int i = 0; i < n; ++i) {\n    sum += arr[i];\n    if (sum == mn) {\n      ans = (ans + p2[n - i - 1 + abses]) % MOD;\n    }\n    if (sum >= 0) ++abses;\n  }\n  cout << ans << '\\n';\n}\n \nint main() {\n  ios_base::sync_with_stdio(false); cin.tie(NULL);\n  p2[0] = 1;\n  for (int i = 1; i < MAX_N; ++i) p2[i] = 2 * p2[i - 1] % MOD;\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) solve();\n  return 0;\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1984",
    "index": "D",
    "title": "''a'' String Problem",
    "statement": "You are given a string $s$ consisting of lowercase Latin characters. Count the number of nonempty strings $t \\neq$ \"$a$\" such that it is possible to partition$^{\\dagger}$ $s$ into some substrings satisfying the following conditions:\n\n- each substring either equals $t$ or \"$a$\", and\n- at least one substring equals $t$.\n\n$^{\\dagger}$ A partition of a string $s$ is an ordered sequence of some $k$ strings $t_1, t_2, \\ldots, t_k$ (called substrings) such that $t_1 + t_2 + \\ldots + t_k = s$, where $+$ represents the concatenation operation.",
    "tutorial": "What does $t$ have to include? Special case: the string consists of only \"$\\texttt{a}$\", then answer is $n - 1$. Otherwise, $t$ has to contain a character that is not \"$\\texttt{a}$\". Let's consider one approach of counting. Let's force all $t$ to start with the first non-a character, and see how many work. To see if one of these strings $t$ will work, we can start with $i = 0$. As long as $i$ does not point to the end of the string, we can find the next non-a character in $s$, and then see if the next $|t|$ characters in $s$ matches $t$. The last check mentioned can be done through hashing or using the Z-function. If it doesn't, this value of $t$ doesn't work. Otherwise, we update $i$ to the new current position and continue checking. Now, if we find a string $t$ that does work, we need to count its contribution to the answer. We can just add $1$, but obviously not all working $t$ will start with a non-a character. Instead, we can find the minimum unused \"$\\texttt{a}$\"s before all of the substrings equal to $t$ (call this $m$), and the current $t$ will be able to extend out up to $m$ \"$\\texttt{a}$\"s at the beginning of the string. Thus, the contribution is $m + 1$ to the answer. How fast is this? Because we are checking at most one string $t$ of each length, and the check itself can be made to take $O(\\frac{n}{|t|})$, we have a total time complexity of $O(n\\log{n})$ due to harmonic sums.",
    "code": "\n#include <iostream>\n#include <vector>\n#include <climits>\n#include <set>\nusing namespace std;\n \n#define ll long long\n \nvector<int> z_function(string s) {\n  int n = s.size();\n  vector<int> z(n);\n  int l = 0, r = 0;\n  for(int i = 1; i < n; ++i) {\n    if (i < r) z[i] = min(r - i, z[i - l]);\n    while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i];\n    if (i + z[i] > r) l = i, r = i + z[i];\n  }\n  return z;\n}\n \nvoid solve() {\n  int n; // cin >> n;\n  string s; cin >> s;\n  n = s.length();\n  vector<int> nona(n, n);\n  for (int i = n - 1; i >= 0; --i) {\n    if (s[i] != 'a') nona[i] = i;\n    else if (i + 1 < n) nona[i] = nona[i + 1];\n  }\n  if (nona[0] == n) {\n    cout << n - 1 << '\\n';\n    return;\n  }\n  string s2 = \"\";\n  int i1 = nona[0];\n  for (int i = i1; i < n; ++i) s2 += s[i];\n  vector<int> z = z_function(s2);\n  ll ans = 0;\n  for (int len = 1; i1 + len <= n; ++len) {\n    int cur = i1 + len;\n    int mn = i1;\n    bool works = true;\n    while (cur < n) {\n      if (nona[cur] == n) break;\n      int bt = nona[cur] - cur;\n      mn = min(mn, bt);\n      cur += bt;\n      if (z[cur - i1] < len) {\n        works = false;\n        break;\n      }\n      cur += len;\n    }\n    if (works) ans += mn + 1;\n  }\n  cout << ans << '\\n';\n}\n \nint main() {\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) solve();\n  return 0;\n}\n",
    "tags": [
      "brute force",
      "hashing",
      "implementation",
      "math",
      "string suffix structures",
      "strings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1984",
    "index": "E",
    "title": "Shuffle",
    "statement": "Two hungry red pandas, Oscar and Lura, have a tree $T$ with $n$ nodes. They are willing to perform the following \\textbf{shuffle procedure} on the whole tree $T$ \\textbf{exactly once}. With this shuffle procedure, they will create a new tree out of the nodes of the old tree.\n\n- Choose any node $V$ from the original tree $T$. Create a new tree $T_2$, with $V$ as the root.\n- Remove $V$ from $T$, such that the original tree is split into one or more subtrees (or zero subtrees, if $V$ is the only node in $T$).\n- Shuffle each subtree with the same procedure (again choosing any node as the root), then connect all shuffled subtrees' roots back to $V$ to finish constructing $T_2$.\n\nAfter this, Oscar and Lura are left with a new tree $T_2$. They can only eat leaves and are very hungry, so please find the maximum number of leaves over all trees that can be created in \\textbf{exactly one} shuffle.\n\nNote that leaves are all nodes with degree $1$. Thus, the root may be considered as a leaf if it has only one child.",
    "tutorial": "Excluding the root, the maximum number of leaves we have is the maximum independent set (MIS) of the rest of the tree. Why? First of all, after rooting tree $T_2$, no two adjacent nodes can both be leaves. This is because, no matter which one you choose to add to $T_2$ first, it must be the ancestor of the other one. Thus, the first chosen node will not be a leaf. Furthermore, any chosen MIS of nodes can all become leaves. This is because we can essentially choose to add all of the nodes not in the MIS first to the tree, leaving all of the remaining nodes to be childless nodes, making them all leaves. To find the answer, we want to find the maximum MIS of all subtrees that are missing one leaf. The answer will be one greater than this maximum MIS due to the root of $T_2$ being also a leaf. There are multiple dynamic programming approaches to compute this efficiently, including rerooting and performing dynamic programming on tree edges. Time complexity: $O(n)$ or $O(n \\log{n})$, depending on implementation.",
    "code": "\n#include <iostream>\n#include <vector>\n#include <map>\nusing namespace std;\n \n#define pii pair<int, int>\n \nint n;\nvector<vector<int>> adj;\nvector<pii> edges;\nmap<pii, int> mp;\n \nvector<vector<int>> dp;\nvector<vector<int>> from;\nvector<int> miss;\n \nvoid dfs(int e) {\n  if (dp[0][e] >= 0 || dp[1][e] >= 0) return;\n  int p = edges[e].first, v = edges[e].second;\n  dp[0][e] = 0, dp[1][e] = 1;\n  if (miss[v] < 0) {\n    for (int u : adj[v]) {\n      if (u == p) continue;\n      int ne = mp[{v, u}];\n      dfs(ne);\n      from[0][v] += max(dp[1][ne], dp[0][ne]);\n      from[1][v] += dp[0][ne];\n    }\n    miss[v] = p;\n  }\n  if (miss[v] != p && miss[v] != n) {\n    int ne = mp[{v, miss[v]}];\n    dfs(ne);\n    from[0][v] += max(dp[1][ne], dp[0][ne]);\n    from[1][v] += dp[0][ne];\n    miss[v] = n;\n  }\n  if (miss[v] == n) {\n    int nne = mp[{v, p}];\n    dp[0][e] += from[0][v] - max(dp[1][nne], dp[0][nne]);\n    dp[1][e] += from[1][v] - dp[0][nne];\n  } else if (miss[v] == p) {\n    dp[0][e] += from[0][v];\n    dp[1][e] += from[1][v];\n  }\n}\n \nvoid solve() {\n  cin >> n;\n  adj.clear(), edges.clear();\n  adj.resize(n), edges.resize(2 * n - 2);\n  for (int i = 0; i < n - 1; ++i) {\n    int a, b; cin >> a >> b; --a, --b;\n    adj[a].push_back(b);\n    adj[b].push_back(a);\n    edges[2 * i] = {a, b};\n    edges[2 * i + 1] = {b, a};\n    mp[{a, b}] = 2 * i;\n    mp[{b, a}] = 2 * i + 1;\n  }\n  from = vector<vector<int>>(2, vector<int>(n));\n  miss = vector<int>(n, -1);\n  dp = vector<vector<int>>(2, vector<int>(2 * n - 2, -1));\n  for (int i = 0; i < 2 * n - 2; ++i) dfs(i);\n  int ans = 0;\n  for (int i = 0; i < n; ++i) {\n    if (adj[i].size() != 1) continue;\n    int e = mp[{i, adj[i][0]}];\n    ans = max(ans, 1 + max(dp[0][e], dp[1][e]));\n  }\n  cout << ans << '\\n';\n}\n \nint main() {\n  ios_base::sync_with_stdio(false); cin.tie(NULL);\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) solve();\n  return 0;\n}\n",
    "tags": [
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1984",
    "index": "F",
    "title": "Reconstruction",
    "statement": "There is a hidden array $a_1, a_2, \\ldots, a_n$ of length $n$ whose elements are integers between $-m$ and $m$, inclusive.\n\nYou are given an array $b_1, b_2, \\ldots, b_n$ of length $n$ and a string $s$ of length $n$ consisting of the characters $P$, $S$, and $?$.\n\nFor each $i$ from $1$ to $n$ inclusive, we must have:\n\n- If $s_i = P$, $b_i$ is the sum of $a_1$ through $a_i$.\n- If $s_i = S$, $b_i$ is the sum of $a_i$ through $a_n$.\n\nOutput the number of ways to replace all $?$ in $s$ with either $P$ or $S$ such that there exists an array $a_1, a_2, \\ldots, a_n$ with elements not exceeding $m$ by absolute value satisfying the constraints given by the array $b_1, b_2, \\ldots, b_n$ and the string $s$.\n\nSince the answer may be large, output it modulo $998\\,244\\,353$.",
    "tutorial": "Solve for no question marks in the string first. Add a $0$ on both sides of $a$ and $b$, and add a $\\texttt{P}$ before the start of the string and a $\\texttt{S}$ after the string. Now you are guaranteed to have a $\\texttt{PS}$ somewhere in the string. How does this help? You know the sum of the array. Look at adjacent elements in $b$, and its corresponding characters in the string, and see if you can determine anything about $a$. Go back to the original problem, with question marks. We do not know the sum now, but how many possible ones can there be? How to solve with no question marks? To simplify things, let's extend all arrays both ways by 1 element. In array $a$ and $b$, we can keep both values at $0$, and in the string $s$, we can assign the left value to \"$\\texttt{P}$\" and the right value to \"$\\texttt{S}$\" (the other values will still be satisfied -- why?) Now, somewhere within the string, we are guaranteed to see the combination \"$\\texttt{PS}$\" because we now have a string that starts with \"$\\texttt{P}$\" and ends with \"$\\texttt{S}$\", therefore it must transition somewhere in between. Notice, if we add the values in $b$ of the \"$\\texttt{PS}$\", we can gather the sum of the array. Now, solving becomes simpler. We can focus on adjacent elements in the array. Say we are currently examining indices $i$ and $i + 1$. There are four cases: We are currently at a \"$\\texttt{PP}$\". We then know $b_i + a_{i+1} = b_{i+1}$, so $a_{i+1}$ is now known. We are currently at a \"$\\texttt{PS}$\". Again, this must be the sum. All we have to do here is check that our sum is correct. We are currently at an \"$\\texttt{SP}$\". Here, we have $b_{i} + b_{i+1} - SUM = a_i + a_{i+1}$ (why?). Our left side is known, and the only requirement on the right side is that both $a_i$ and $a_{i+1}$ have to have a magnitude of at most $m$. Thus, to make their maximum magnitude as small as possible, we make them as close as possible to each other. If the left side is $x$, we assign $a_i = \\text{floor}(x / 2)$, and $a_{i+1} = x - a_i$. We are currently at an \"$\\texttt{SS}$\". This is similar to the first case, as we know that $b_i = a_i + b_{i+1}$. Thus, $a[i]$ will be known. If $a_i$ is always possible, then we know our answer exists. Thus, this solves a version without question marks. For the version with question marks, we can only try to guess what the sum of the entire array is, since we don't know where \"$\\texttt{PS}$\" might be for sure every time. There are only $n$ possibilities - the sum of every pair of adjacent numbers in $b$. For every possibility, we can run a dp[i][j] where we are currently at index $i$ and the last character within \"$\\texttt{P}$\" and \"$\\texttt{S}$\" in string $s$ used was $j$. This dynamic programming will run in linear time because of constant-time transitions and linear amount of states. Note that this is only possible due to the independent nature of adjacent pairs as described earlier. With this DP, we can calculate how many paths are possible, adding to our answer. Time complexity $O(n^2)$",
    "code": "\n#include <iostream>\n#include <vector>\n#include <cstring>\n#include <assert.h>\n#include <set>\nusing namespace std;\n \n#define ll long long\n \nconst int INF = 998244353;\n// const int BOUND = 1e9;\n \nvoid solve() {\n  int n; cin >> n;\n  int BOUND; cin >> BOUND;\n  string s; cin >> s;\n  s = \"P\" + s + \"S\";\n  vector<ll> b(n + 2);\n  for (int i = 0; i < n; ++i) cin >> b[i + 1];\n  ll ans = 0;\n  set<ll> done;\n  for (int i = 0; i < n + 1; ++i) {\n    ll sum = b[i] + b[i + 1];\n    if (done.count(sum)) continue;\n    int dp[n + 2][2];\n    for (int j = 0; j < n + 2; ++j) for (int k = 0; k < 2; ++k) dp[j][k] = -1;\n    // [\"P\", \"S\"]\n    dp[0][0] = 1;\n    for (int j = 1; j < n + 2; ++j) {\n      bool tr[2]; tr[0] = tr[1] = true;\n      if (s[j] == 'P') tr[1] = false;\n      else if (s[j] == 'S') tr[0] = false;\n      if (abs(b[j] - b[j - 1]) <= BOUND) {\n        for (int k = 0; k < 2; ++k)\n          if (dp[j - 1][k] > -1 && tr[k]) dp[j][k] = dp[j - 1][k];\n      }\n      if (dp[j - 1][0] > -1 && tr[1] && sum == b[j] + b[j - 1]) {\n        // \"P\" -> \"S\":\n        if (dp[j][1] < 0) dp[j][1] = 0;\n        dp[j][1] = (dp[j][1] + dp[j - 1][0]) % INF;\n      }\n      if (dp[j - 1][1] > -1 && tr[0]) {\n        // \"S\" -> \"P\":\n        ll add = b[j] + b[j - 1] - sum;\n        ll large = max(abs(add / 2), abs(add - add / 2));\n        if (large <= BOUND) {\n          if (dp[j][0] < 0) dp[j][0] = 0;\n          dp[j][0] = (dp[j][0] + dp[j - 1][1]) % INF;\n        }\n      }\n    }\n    if (dp[n + 1][1] < 0) continue;\n    ans = (ans + dp[n + 1][1]) % INF;\n    done.insert(sum);\n  }\n  cout << ans << '\\n';\n}\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(NULL);\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) solve();\n  return 0;\n}\n",
    "tags": [
      "brute force",
      "dp",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1984",
    "index": "G",
    "title": "Magic Trick II",
    "statement": "The secret behind Oscar's first magic trick has been revealed! Because he still wants to impress Lura, he comes up with a new idea: he still wants to sort a permutation $p_1, p_2, \\ldots, p_n$ of $[1, 2, \\ldots, n]$.\n\nThis time, he chooses an integer $k$. He wants to sort the permutation in non-decreasing order using the following operation several times:\n\n- Pick a continuous subarray of length $k$ and remove it from $p$.\n- Insert the continuous subarray back into $p$ at any position (perhaps, in the very front or the very back).\n\nTo be as impressive as possible, Oscar would like to choose the maximal value of $k$ such that he can sort his permutation. Please help him find the maximal $k$ as well as a sequence of operations that will sort the permutation. You don't need to minimize the number of operations, but you are allowed to use at most $5n^2$ operations.\n\nWe have a proof that, for the maximal $k$ such that you can sort the permutation in any number of operations, you can also sort it in at most $5n^2$ operations.",
    "tutorial": "Solve what the maximum $k$ will be for different types of arrays. The maximum is always close to $n$. There exists two trivial cases. If array is already sorted, $k = n$. If array is cyclic shift of sorted array, $k = n - 1$. Now, $k = n - 2$ and $k = n - 3$ is sufficient to sort any array. Let's assume $n$ is odd first, and construct an answer in the general case with $k = n - 2$. Because $k$ is so large, our operations are limited in choices. If we represent the array as a cyclic array with a divider representing the end of the array, an operation can be seen as two choices: Move the divider $2$ positions in any direction. Swap the two numbers around the divider, then move the divider by $1$ position in any direction. With this representation, the construction becomes quite easy. Because $n$ is odd, we can use the first type of operation to put the divider wherever we want. Then, using the second type of operation, if our divider is on the right side of a specific number, we can move it all the way to the right by swapping, then moving the divider right by $1$ position. Because we are able to do this, we can bubble sort. For each number, position the divider in $O(n)$ moves, then move it to the very right in another $O(n)$ moves. There are $n$ numbers total, so this takes a total of around $2n^2$ operations, less if optimized. What if $n$ is even? In this case $k = n - 2$ is not always guaranteed to work. The motivation for seeing this can come from the fact that you can't place the divider anywhere just by using type $1$ operations. As a lower bound, we know that $k = n - 3$ will always work. We can use operations to move the largest number to the very end, then we basically have an array of length $n - 1$ with $k = n - 3$, which is the odd case we presented earlier. So, when can we use $k = n - 2$ in the even case? Let's consider the number of inversions in the array at any given time. If $n$ is even, then $k = n - 2$ is also even, meaning that the parity of the number of inversions will never change with operations. Thus, since a sorted array will have no inversions, we cannot use $k = n - 2$ if the initial array had an odd number of inversions. If we have an even number of inversions, we can sort in a similar manner. Except, now, if the inversion constraint prevents moving the divider to the immediate right of our current number with only type $1$ operations, we can use a few type $2$ operations to fix the position of the divider (many possible strategies for this, one possible way is shown in the implementation). Overall, this should also take around $2n^2$ operations total.",
    "code": "\n#include <iostream>\n#include <vector>\nusing namespace std;\n \n#define pii pair<int, int>\n \nbool sorted(vector<int> arr, int n) {\n  for (int i = 1; i < n; ++i) if (arr[i] < arr[i - 1]) return false;\n  return true;\n}\n \nbool cyclic(vector<int> arr, int n) {\n  for (int i = 1; i < n; ++i) if (arr[i] % n != (arr[i - 1] + 1) % n) return false;\n  return true;\n}\n \nvoid solve() {\n  int n; cin >> n;\n  vector<int> arr(n); for (int i = 0; i < n; ++i) cin >> arr[i];\n  if (sorted(arr, n)) {\n    cout << n << \"\\n0\\n\";\n    return;\n  }\n  if (cyclic(arr, n)) {\n    cout << n - 1 << '\\n';\n    int pos;\n    for (pos = 0; pos < n; ++pos) if (arr[pos] == 1) break;\n    cout << pos << '\\n';\n    for (int i = 0; i < pos; ++i) {\n      cout << \"2 1\\n\";\n    }\n    return;\n  }\n  vector<pii> ops;\n  if (n % 2 == 0) {\n    int inv = 0;\n    for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) if (arr[i] > arr[j]) ++inv;\n    if (inv & 1) {\n      int pos;\n      for (pos = 0; pos < n; ++pos) if (arr[pos] == n) break;\n      if (pos < 3) {\n        for (int i = 0; i <= pos; ++i) ops.push_back({2, 1});\n        vector<int> tmp = arr;\n        for (int i = 0; i < n - 2; ++i) arr[i] = tmp[(i + pos + 1) % (n - 2)];\n      }\n      for (pos = 0; pos < n; ++pos) if (arr[pos] == n) break;\n      for (int i = pos; i < n - 1; ++i) ops.push_back({3, 4});\n      vector<int> tmp = arr;\n      for (int i = 2; i < n; ++i) arr[i] = tmp[((i + pos - 3) % (n - 2)) + 2];\n      --n;\n    }\n  }\n  cout << n - 2 << '\\n';\n  int div = 0;\n  for (int i = n; i > 0; --i) {\n    int pos;\n    for (pos = 0; pos < n; ++pos) if (arr[pos] == i) break;\n    pos += 1;\n    if (pos == i) continue;\n    if (div % 2 != pos % 2) {\n      if (n & 1) {\n        while (div < n) {\n          ops.push_back({3, 1});\n          div += 2;\n        }\n        div %= n;\n      } else {\n        while (div != pos - 1) {\n          if (div < pos - 1) {\n            ops.push_back({3, 1});\n            div += 2;\n          } else {\n            ops.push_back({1, 3});\n            div -= 2;\n          }\n        }\n        if (pos > 1) {\n          ops.push_back({2, 3});\n          swap(arr[(div + n - 1) % n], arr[div]);\n          div = (div + n - 1) % n;\n          --pos;\n        }\n        ops.push_back({3, 1});\n        div += 2;\n        ops.push_back({2, 3});\n        swap(arr[(div + n - 1) % n], arr[div]);\n        div = (div + n - 1) % n;\n      }\n    }\n    while (div != pos) {\n      if (div < pos) {\n        ops.push_back({3, 1});\n        div += 2;\n      } else {\n        ops.push_back({1, 3});\n        div -= 2;\n      }\n    }\n    for (int j = pos; j < i; ++j) {\n      ops.push_back({2, 1});\n      swap(arr[div - 1], arr[div]);\n      ++div;\n    }\n  }\n  if (div % 2 == 1) {\n    while (div < n) {\n      ops.push_back({3, 1});\n      div += 2;\n    }\n    div %= n;\n  }\n  while (div > 0) {\n    ops.push_back({1, 3});\n    div -= 2;\n  }\n  cout << ops.size() << '\\n';\n  for (pii p : ops) {\n    cout << p.first << ' ' << p.second << '\\n';\n  }\n}\n \nint main() {\n  ios_base::sync_with_stdio(false); cin.tie(NULL);\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) solve();\n  return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "1984",
    "index": "H",
    "title": "Tower Capturing",
    "statement": "There are $n$ towers at $n$ distinct points $(x_1, y_1), (x_2, y_2), \\ldots, (x_n, y_n)$, such that no three are collinear and no four are concyclic. Initially, you own towers $(x_1, y_1)$ and $(x_2, y_2)$, and you want to capture all of them. To do this, you can do the following operation any number of times:\n\n- Pick two towers $P$ and $Q$ you own and one tower $R$ you don't own, such that the circle through $P$, $Q$, and $R$ contains \\textbf{all} $n$ towers inside of it.\n- Afterwards, capture all towers in or on triangle $\\triangle PQR$, including $R$ itself.\n\nAn attack plan is a series of choices of $R$ ($R_1, R_2, \\ldots, R_k$) using the above operations after which you capture all towers. Note that two attack plans are considered different only if they differ in their choice of $R$ in some operation; in particular, two attack plans using the same choices of $R$ but different choices of $P$ and $Q$ are considered the same.Count the number of attack plans of \\textbf{minimal length}. Note that it might not be possible to capture all towers, in which case the answer is $0$.\n\nSince the answer may be large, output it modulo $998\\,244\\,353$.",
    "tutorial": "Are there any useless points? Draw all triangles that contain all points inside their circumcircle. What do you notice? Claim. We can't ever pick a tower inside the convex hull. Proof. A circle can only contain all the points if the points on the circle are on the convex hull; otherwise, the circle will necessarily split the convex hull into two parts, one of which is outside. It follows that if our initial two towers aren't on the convex hull, the answer is $0$. Also, we can safely ignore all points in the convex hull, since we'll capture them anyway, as the convex hull is the union of all triangles whose vertices are vertices of the convex hull. From now on we'll only consider points on the convex hull. Now comes the key claim of the problem. Claim. Call a triangle covering if its circumcircle contains all the points. Draw all covering triangles. We claim that these triangles form a triangulation of the convex hull. Proof. Recall that a triangulation is a set of triangles with pairwise non-intersecting interiors whose union is the polygon. There are two parts to the proof: the triangles are pairwise non-intersecting. their union is the polygon. Let's prove them separately. First we'll prove point (1) directly. Consider two circles through points $ABC$ and $DEF$. Of course, the convex hull needs to lie in the intersection of the two circles. In particular, the circle through $ABC$ must contain the points $DEF$, while the circle through $DEF$ must contain the points $ABC$. It follows that the two circumcircles (say, $\\Omega$ and $\\Psi$ respectively) have the following property: the points $A$, $B$, $C$ lie on an arc of $\\Omega$ inside $\\Psi$, and the points $D$, $E$, $F$ lie on an arc of $\\Psi$ inside $\\Omega$. The claim follows. Formally, we can define $U$ and $V$ as the intersection points of $\\Omega$ and $\\Psi$. Then if we walk along the digon $UV$ (whose edges are arcs of $\\Omega$ and $\\Psi$), we will pass through $A$, $B$, $C$ along one of the arcs, and $D$, $E$, $F$ on the other. This means that there is some closed convex loop passing through the points $A$, $B$, $C$ before $D$, $E$, $F$, implying those two triangles don't intersect. The proof remains the same even if some of $A$, $B$, $C$, $D$, $E$, $F$ overlap. Now we'll move on to the proof of (2). Consider any covering triangle $ABC$. WLOG suppose $AB$ is not an edge of the convex hull. Consider the points in the halfplane of $AB$ not containing $C$, and let $C'$ be the point among these such that $\\angle AC'B$ is minimized. Then it follows that $ABC'$ is also covering. It's easy to see why this works and why $C'$ is unique by the inscribed angle theorem. As a result, given any covering triangle, we can recursively triangulate the regions it cuts off by a chord. Thus, inductively, the whole polygon will be triangulated. We are done with the proof. Note that this implies our original three towers in the problem must form a covering triangle, since we create a covering triangle after every operation; thus, at the end of these operations, all but possibly one of these triangles is covering (the \"possibly one\" is the initial triangle). But such a covering triangulation exists and is unique, as shown, so our initial triangle in fact must be covering. Now on to the actual operations present in the problem. Using them, we can \"construct\" the triangulation one step at a time using operations like the one mentioned. Of course, the triangulation is unique, so the only change we can do is the order in which we construct the triangles. Consider the dual tree of the triangulation (that is, make a vertex for each triangle and an edge between those vertices corresponding to two triangles that share a diagonal of the convex hull). In an operation, we attach a leaf to any vertex, and in the end we end up with the final dual tree. Note that we can start growing the tree at either triangle adjacent to our original diagonal; that is, if our original points are $A$ and $B$, then we need to consider rooting our tree at either $T_1$ or $T_2$, where those are the two triangles that contain the edge $AB$ (note that $T_2$ may not exist). Let's reverse time. Then given the final tree (rooted at either $T_1$ or $T_2$), in an operation we prune a leaf (a leaf here is a vertex with no children). How many ways can we prune all the leaves? This is a standard dynamic programming problem, since at each step we need to prune all of our children before we prune ourselves. In particular, if the sizes of our childrens' subtrees are $s_1, \\dots, s_k$, then our answer is $\\binom{s_1 + \\dots + s_k}{s_1, \\dots, s_k} \\cdot \\prod_{i=1}^{k} \\mathrm{ans}(\\mathrm{child}_i)$. This DP runs in $\\mathcal{O}(n)$ time, so it is not a problem to compute. We can easily compute the triangulation in $\\mathcal{O}(n^2)$ time as follows: given an edge $PQ$, we need to find the point $R$ in a halfplane such that $(PQR)$ covers all points, and as mentioned before, by the inscribed angle theorem this is precisely the point $R$ such that $PQR'$ is minimized. So you can find it with an $\\mathcal{O}(n)$ sweep and add the new edges to our triangulation. Therefore the solution runs in $\\mathcal{O}(n^2)$, but the validator takes $\\mathcal{O}(n^3)$ to check. We accepted slower solutions in $\\mathcal{O}(n^3)$ as well, and even $\\mathcal{O}(n^4)$ with a decent constant factor (which are relatively hard to cut). A note about implementation: I'm not very good at it, so my code below is a bit messy. Also, to keep the computations in integers, I needed to use big integers at exactly one point, but it's not so bad: you only need to implement big integer multiplication and comparison, which I shamelessly stole from jeroenodb. You may not need to use it, and can pass using floating-point numbers.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200007;\nconst int MOD = 998244353;\n\nstruct bignum {\n    static constexpr long long B = 1LL<<30;\n    static constexpr int N = 6;\n    array<long long, N> b = {};\n    bignum() {}\n    bignum(long long a) {\n        b[2] = (a / B) / B;\n        b[1] = (a / B) % B;\n        b[0] = a % B;\n    }\n    bignum operator*(const bignum& o) {\n        bignum res;\n        for (int i = 0; i < N; i++) {\n\t\t    for (int j = 0; j + i < N; j++) {\n\t\t        res.b[i + j] += b[i] * o.b[j];\n\t\t        for (int k = i + j; k + 1 < N; k++) {\n\t\t            auto tmp = res.b[k] / B;\n\t\t            res.b[k + 1] += tmp;\n\t\t            res.b[k] -= tmp * B;\n\t\t        }\n\t\t    }\n\t\t}\n        return res;\n    }\n    bool operator<=(const bignum& o) const {\n        if (b == o.b) return true;\n        return lexicographical_compare(b.rbegin(),b.rend(),o.b.rbegin(),o.b.rend());\n    }\n};\n\ntemplate <class T> int sgn(T x) { return (x > 0) - (x < 0); }\ntemplate<class T>\nstruct Point {\n\ttypedef Point P;\n\tT x, y;\n\texplicit Point(T x=0, T y=0) : x(x), y(y) {}\n\tbool operator<(P p) const { return tie(x,y) < tie(p.x,p.y); }\n\tbool operator==(P p) const { return tie(x,y)==tie(p.x,p.y); }\n\tP operator+(P p) const { return P(x+p.x, y+p.y); }\n\tP operator-(P p) const { return P(x-p.x, y-p.y); }\n\tP operator*(T d) const { return P(x*d, y*d); }\n\tP operator/(T d) const { return P(x/d, y/d); }\n\tT dot(P p) const { return x*p.x + y*p.y; }\n\tT cross(P p) const { return x*p.y - y*p.x; }\n\tT cross(P a, P b) const { return (a-*this).cross(b-*this); }\n\tT dist2() const { return x*x + y*y; }\n\tdouble dist() const { return sqrt((double)dist2()); }\n\t// angle to x-axis in interval [-pi, pi]\n\tdouble angle() const { return atan2(y, x); }\n\tP unit() const { return *this/dist(); } // makes dist()=1\n\tP perp() const { return P(-y, x); } // rotates +90 degrees\n\tP normal() const { return perp().unit(); }\n\t// returns point rotated 'a' radians ccw around the origin\n\tP rotate(double a) const {\n\t\treturn P(x*cos(a)-y*sin(a),x*sin(a)+y*cos(a)); }\n\tfriend ostream& operator<<(ostream& os, P p) {\n\t\treturn os << \"(\" << p.x << \",\" << p.y << \")\"; }\n\tfriend istream& operator>>(istream& is, P& p) {\n\t\treturn is >> p.x >> p.y; }\n};\n\ntypedef Point<long long> P;\nvector<P> convexHull(vector<P> pts) {\n\tif (pts.size() <= 1) return pts;\n\tsort(pts.begin(), pts.end());\n\tvector<P> h(pts.size()+1);\n\tint s = 0, t = 0;\n\tfor (int it = 2; it--; s = --t, reverse(pts.begin(), pts.end()))\n\t\tfor (P p : pts) {\n\t\t\twhile (t >= s + 2 && h[t-2].cross(h[t-1], p) <= 0) t--;\n\t\t\th[t++] = p;\n\t\t}\n\treturn {h.begin(), h.begin() + t - (t == 2 && h[0] == h[1])};\n}\n\nint n, t;\nlong long inv[MAX], fact[MAX], invfact[MAX];\nvector<P> v;\n\nvoid orient(P &a, P &b, P &c) {\n\t// move points a, b, c to be in counterclockwise order\n\tlong long val = (b - a).cross(c - a);\n\tassert(val != 0);\n\tif (val < 0) {swap(a, c);} \n}\n\npair<long long, long long> angleComp(P a, P b, P c) {\n\t// get a (scaled) value of f(cos(angle ABC))\n\tP ab = a - b, cb = c - b;\n\tlong long dt = ab.dot(cb);\n\tdt *= dt;\n\tint sgn = (ab.dist2() + cb.dist2() >= (a - c).dist2() ? 1 : -1);\n\treturn make_pair(sgn * dt, ab.dist2() * cb.dist2());\n}\n\nbool inCircle(P a, P b, P c, P d) {\n\t// is D in (or on) (ABC)?\n\torient(a, b, c);\n\tP ad = a - d, bd = b - d, cd = c - d;\n\treturn (\n\t\tad.dist2() * (bd.x * cd.y - bd.y * cd.x) -\n\t\tbd.dist2() * (ad.x * cd.y - ad.y * cd.x) +\n\t\tcd.dist2() * (ad.x * bd.y - ad.y * bd.x)\n\t) >= 0;\n}\n\npair<bool, int> check(int l, int r) {\n\tint start = l, finish = r;\n\tif (finish < start) {finish += n;}\n\tpair<long long, long long> best = make_pair(-MOD, 1);\n\tint w = -1;\n\tfor (int i = start + 1; i < finish; i++) {\n\t\tpair<long long, long long> val = angleComp(v[l], v[i % n], v[r]);\n\t\tbignum v1 = bignum(val.first) * bignum(best.second);\n\t\tbignum v2 = bignum(val.second) * bignum(best.first);\n\t\tif (!(v1 <= v2)) {\n\t\t\tbest = val;\n\t\t\tw = i % n;\n\t\t}\n\t}\n\tif (w == -1) {\n\t\t// cout << v[l] << ' ' << v[r] << \" empty?\\n\";\n\t\treturn make_pair(true, -1);\n\t}\n\t// cout << v[l] << ' ' << v[r] << \" connects to \" << v[w] << \"?\\n\";\n\tfor (P Q : v) {\n\t\tif (!inCircle(v[l], v[w], v[r], Q)) {return make_pair(false, -1);}\n\t}\n\treturn make_pair(true, w);\n}\n\nvoid reset(int n) {\n\tv.clear();\n\t// for (int i = 0; i < n + 5; i++) {\n\t\t// g[i].clear();\n\t\t// child[i].clear();\n\t// }\n\tt = 1;\n}\n\nvoid solve() {\n\tcin >> n;\n\treset(n);\n\tvector<P> pts(n);\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> pts[i];\n\t}\n\tvector<P> us{pts[0], pts[1]};\n\tvector<int> us_vals;\n\tv = convexHull(pts);\n\tn = v.size();\n\tfor (auto P : us) {\n\t\tint i = 0; bool hit = false;\n\t\tfor (auto Q : v) {\n\t\t\tif (P == Q) {us_vals.push_back(i); hit = true;}\n\t\t\ti++;\n\t\t}\n\t\tif (!hit) {cout << 0 << '\\n'; return;}\n\t}\n\tif (v.size() <= 3) {cout << 1 << '\\n'; return;}\n\tqueue<pair<pair<int, int>, int>> q;\n\tvector<int> child[MAX];\n\tq.push(make_pair(make_pair(us_vals[0], us_vals[1]), -1));\n\tq.push(make_pair(make_pair(us_vals[1], us_vals[0]), -1));\n\twhile (!q.empty()) {\n\t\tauto p = q.front();\n\t\tq.pop();\n\t\tpair<bool, int> resp = check(p.first.first, p.first.second);\n\t\tif (!resp.first) {cout << 0 << '\\n'; return;}\n\t\tif (resp.second == -1) {continue;}\n\t\tq.push(make_pair(make_pair(p.first.first, resp.second), t));\n\t\tq.push(make_pair(make_pair(resp.second, p.first.second), t));\n\t\tif (p.second != -1) {\n\t\t\tchild[p.second].push_back(t);\n\t\t}\n\t\tt++;\n\t}\n\t// for (int i = 1; i <= n - 2; i++) {\n\t\t// cout << i << \": \";\n\t\t// for (int j : child[i]) {cout << j << ' ';}\n\t\t// cout << '\\n';\n\t// }\n\tbool edge_case = true; // both 1 and 2 are roots\n\tfor (int j : child[1]) {\n\t\tif (j == 2) {edge_case = false;} // only 1 is root\n\t}\n\t\n\tvector<long long> dp(n + 7);\n\tvector<int> sz(n + 7);\n\t\n\tauto cnt = [&](auto self, int v) -> int {\n\t\tif (sz[v] != -1) {return sz[v];}\n\t\tint res = 1;\n\t\tif (!child[v].empty()) {\n\t\t\tfor (int u : child[v]) {\n\t\t\t\tres += self(self, u);\n\t\t\t}\n\t\t}\n\t\tsz[v] = res;\n\t\treturn res;\n\t};\n\t\n\tauto f = [&](auto self, int v) -> long long {\n\t\tif (dp[v] != -1LL) {return dp[v];}\n\t\tlong long res = 1LL;\n\t\tif (!child[v].empty()) {\n\t\t\tres = (res * fact[cnt(cnt, v) - 1]) % MOD;\n\t\t\tfor (int u : child[v]) {\n\t\t\t\tres = (res * self(self, u)) % MOD;\n\t\t\t\tres = (res * invfact[cnt(cnt, u)]) % MOD;\n\t\t\t}\n\t\t}\n\t\tdp[v] = res;\n\t\treturn res;\n\t};\n\n\tif (edge_case) {child[1].push_back(2);}\n\t\n\tfill(dp.begin(), dp.end(), -1LL);\n\tfill(sz.begin(), sz.end(), -1);\n\tlong long res = f(f, 1);\n\t\n\tif (edge_case) {\n\t\tchild[1].erase(remove(child[1].begin(), child[1].end(), 2), child[1].end());\n\t\tchild[2].push_back(1);\n\t\tfill(dp.begin(), dp.end(), -1LL);\n\t\tfill(sz.begin(), sz.end(), -1);\n\t\tres = (res + f(f, 2)) % MOD;\n\t}\n\t\n\tcout << res << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tinv[0] = inv[1] = 1;\n\tfor (int i = 2; i < MAX; i++) {\n\t\tinv[i] = MOD - (long long)(MOD / i) * inv[MOD % i] % MOD;\n\t}\n\tfact[0] = fact[1] = 1; invfact[0] = invfact[1] = 1;\n\tfor (int i = 2; i < MAX; i++) {\n\t\tfact[i] = (fact[i - 1] * (long long)i) % MOD;\n\t\tinvfact[i] = (invfact[i - 1] * inv[i]) % MOD;\n\t}\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "combinatorics",
      "dp",
      "geometry"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1985",
    "index": "A",
    "title": "Creating Words",
    "statement": "Matthew is given two strings $a$ and $b$, both of length $3$. He thinks it's particularly funny to create two new words by swapping the first character of $a$ with the first character of $b$. He wants you to output $a$ and $b$ after the swap.\n\nNote that the new words may not necessarily be different.",
    "tutorial": "To swap the first character of the strings, you can use the built-in method std::swap in C++, or for each string, separate the first character from the rest of the string and concatenate it with the other string.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tstring a, b; cin >> a >> b;\n\t\tswap(a[0], b[0]);\n\t\tcout << a << \" \" << b << endl;\n\t}\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1985",
    "index": "B",
    "title": "Maximum Multiple Sum",
    "statement": "Given an integer $n$, find an integer $x$ such that:\n\n- $2 \\leq x \\leq n$.\n- The sum of multiples of $x$ that are less than or equal to $n$ is maximized. Formally, $x + 2x + 3x + \\dots + kx$ where $kx \\leq n$ is maximized over all possible values of $x$.",
    "tutorial": "To maximize the number of multiples of $x$ less than $n$, it optimal to choose a small $x$, in this case, $2$. The only exception is $n = 3$, where it is optimal to choose $3$ instead, since both $2$ and $3$ have only one multiple less than $3$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tint n; cin >> n;\n\t\tcout << (n == 3 ? 3 : 2) << endl;\n \t}\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "1985",
    "index": "C",
    "title": "Good Prefixes",
    "statement": "Alex thinks some array is good if there exists some element that can be represented as the sum of all \\textbf{other} elements (the sum of all other elements is $0$ if there are no other elements). For example, the array $[1,6,3,2]$ is good since $1+3+2=6$. Furthermore, the array $[0]$ is also good. However, the arrays $[1,2,3,4]$ and $[1]$ are not good.\n\nAlex has an array $a_1,a_2,\\ldots,a_n$. Help him count the number of good non-empty prefixes of the array $a$. In other words, count the number of integers $i$ ($1 \\le i \\le n$) such that the length $i$ prefix (i.e. $a_1,a_2,\\ldots,a_i$) is good.",
    "tutorial": "The only element that can be the sum of all other elements is the maximum element, since all elements are positive. Therefore, for each prefix $i$ from $1$ to $n$, check if $sum(a_1, a_2, ..., a_i) - max(a_1, a_2, ..., a_i) = max(a_1, a_2, ..., a_i)$. The sum and max of prefixes can be tracked with variables outside the loop.",
    "code": "#include <iostream>\nusing namespace std;\n\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tint n; cin >> n;\n\t\tint a[n];\n\t\tfor(int i = 0; i < n; i++)\n\t\t\tcin >> a[i];\n\t\tlong long sum = 0;\n\t\tint mx = 0, ans = 0;;\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tsum += a[i];\n\t\t\tmx = max(mx, a[i]);\n\t\t\tif(sum - mx == mx) \n\t\t\t\tans++;\n\t\t}\n\t\tcout << ans << endl;\n\t}\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1985",
    "index": "D",
    "title": "Manhattan Circle",
    "statement": "Given a $n$ by $m$ grid consisting of '.' and '#' characters, there exists a whole manhattan circle on the grid. The top left corner of the grid has coordinates $(1,1)$, and the bottom right corner has coordinates $(n, m)$.\n\nPoint ($a, b$) belongs to the manhattan circle centered at ($h, k$) if $|h - a| + |k - b| < r$, where $r$ is a positive constant.\n\nOn the grid, the set of points that are part of the manhattan circle is marked as '#'. Find the coordinates of the center of the circle.",
    "tutorial": "Note that the manhattan circle is always in a diamond shape, symmetric from the center. Let's take notice of some special characteristics that can help us. One way is to find the top and bottom points of the circle. Note that these points will have columns at the center of the circle, so here we can acquire the value of $k$. To find $h$, since the circle is symmetric, it is just the middle of the rows of the top and bottom points. Note that we never needed to find the value of $r$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int INF = 1e9;\n\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tint n, m; cin >> n >> m;\n\t\tvector<vector<char>> g(n, vector<char>(m));\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tfor(int j = 0; j < m; j++){\n\t\t\t\tcin >> g[i][j];\n\t\t\t}\n\t\t}\n\t\tpair<int, int> top = {INF, INF}, bottom = {-INF, -INF};\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tfor(int j = 0; j < m; j++){\n\t\t\t\tif(g[i][j] == '#'){\n\t\t\t\t\ttop = min(top, {i, j});\n\t\t\t\t\tbottom = max(bottom, {i, j});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tassert(top.second == bottom.second);\n\t\tcout << (top.first + bottom.first) / 2 + 1 << \" \" << top.second + 1 << endl;\n\t}\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1985",
    "index": "E",
    "title": "Secret Box",
    "statement": "Ntarsis has a box $B$ with side lengths $x$, $y$, and $z$. It lies in the 3D coordinate plane, extending from $(0,0,0)$ to $(x,y,z)$.\n\nNtarsis has a secret box $S$. He wants to choose its dimensions such that all side lengths are positive integers, and the volume of $S$ is $k$. He can place $S$ somewhere within $B$ such that:\n\n- $S$ is parallel to all axes.\n- every corner of $S$ lies on an integer coordinate.\n\n$S$ is magical, so when placed at an integer location inside $B$, it will not fall to the ground.\n\nAmong all possible ways to choose the dimensions of $S$, determine the \\textbf{maximum} number of distinct locations he can choose to place his secret box $S$ inside $B$. Ntarsis does not rotate $S$ once its side lengths are selected.",
    "tutorial": "Since the side lengths of $S$ has to multiply to $k$, all three side lengths of $S$ has to be divisors of $k$. Let's denote the side lengths of $S$ along the $x$, $y$, and $z$ axes as $a$, $b$, and $c$ respectively. For $S$ to fit in $B$ , $a \\leq x$, $b \\leq y$, and $c \\leq z$ must hold. Because of the low constraints, we can afford to loop through all possible values of $a$ and $b$, and deduce that $c=\\frac{k}{a \\cdot b}$ (make sure $c \\leq z$ and $c$ is an integer). To get the amount of ways we can place $S$, we can just multiply the amount of shifting space along each axes, and that just comes down to $(x-a+1) \\cdot (y-b+1) \\cdot (z-c+1)$. The answer is the maximum among all possible values of $a$, $b$, and $c$ . The time complexity is $\\mathcal{O}(n^2)$ where $n$ is at most $2000$.",
    "code": "#include <iostream>\nusing namespace std;\nusing ll = long long;\n\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tll x, y, z, k; cin >> x >> y >> z >> k;\n\t\tll ans = 0;\n\t\tfor(int a = 1; a <= x; a++){\n\t\t\tfor(int b = 1; b <= y; b++){\n\t\t\t\tif(k % (a * b)) continue;\n\t\t\t\tll c = k / (a * b);\n\t\t\t\tif(c > z) continue;\n\t\t\t\tll ways = (ll)(x - a + 1) * (y - b + 1) * (z - c + 1);\n\t\t\t\tans = max(ans, ways);\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1985",
    "index": "F",
    "title": "Final Boss",
    "statement": "You are facing the final boss in your favorite video game. The boss enemy has $h$ health. Your character has $n$ attacks. The $i$'th attack deals $a_i$ damage to the boss but has a cooldown of $c_i$ turns, meaning the next time you can use this attack is turn $x + c_i$ if your current turn is $x$. Each turn, you can use all attacks that are not currently on cooldown, \\textbf{all at once}. If all attacks are on cooldown, you do nothing for the turn and skip to the next turn.\n\nInitially, all attacks are not on cooldown. How many turns will you take to beat the boss? The boss is beaten when its health is $0$ or less.",
    "tutorial": "Unfortunately, there was a lot of hacks on this problem, and we're sorry for it. Since our intended solution is not binary search, we didn't really take overflow using binary search seriously. I (cry) prepared this problem and I only took into account about overflow with big cooldown, but I forgot overflow can happen on attacks as well. I apologize and we will do better next time! Since the sum of $h$ is bounded by $2 \\cdot 10^5$, and each attack deals at least $1$ damage. If we assume every turn we can make at least one attack, the sum of turns to kill the boss in every test case is bounded by $2 \\cdot 10^5$. This means that we can afford to simulate each turn where we make at least one attack. But what if we cannot make an attack on this turn? Since the cooldown for each attack can be big, we cannot increment turns one by one. We must jump to the next turn we can make an attack. This can be done by retrieving the first element of a sorted set, where the set stores pairs {$t$, $i$} which means {next available turn you can use this attack, index of this attack} for all $i$. Here, we can set the current turn to $t$ and use all attacks in the set with first element in the pair equal to $t$. Remember to insert the pair to {$c_i + t$, $i$} back into the set after processing the attacks. The time complexity is $\\mathcal{O}(h \\log n)$. Try to solve this if $1 \\le h \\le 10^9$. We can do this by binary searching for the answer. For some time $t$, we know that we can perform an attack of cooldown $c$ exactly $\\lfloor \\frac{t - 1}{c} \\rfloor + 1$ times. The total damage we will do in time $t$ will be: $\\displaystyle \\sum_{i=1}^{n}{a_i\\left( \\lfloor\\frac{t - 1}{c_i}\\rfloor + 1 \\right)}$ So we binary search for the first $t$ such that the total damage we do in time $t$ is greater than or equal to $h$. This runs in $\\mathcal{O(n \\log {(h \\cdot \\max c_i)})}$. Be careful of long long overflow!",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n\nvoid solve(){\n    ll h, n;\n    cin >> h >> n;\n\n    vector<ll> A(n), C(n);\n\n    for (ll &i : A)\n        cin >> i;\n    for (ll &i : C)\n        cin >> i;\n    \n    auto chk = [&](ll t){\n        ll dmg = 0;\n        for (int i = 0; i < n and dmg < h; i++){\n            ll cnt = (t - 1) / C[i] + 1;\n\n            if (cnt >= h)\n                return true;\n\n            dmg += cnt * A[i];\n        }\n        return dmg >= h;\n    };\n\n    ll L = 1, H = 1e12;\n\n    while (L < H){\n        ll M = (L + H) / 2;\n        chk(M) ? H = M : L = M + 1;\n    }\n    cout << L << \"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1985",
    "index": "G",
    "title": "D-Function",
    "statement": "Let $D(n)$ represent the sum of digits of $n$. For how many integers $n$ where $10^{l} \\leq n < 10^{r}$ satisfy $D(k \\cdot n) = k \\cdot D(n)$? Output the answer modulo $10^9+7$.",
    "tutorial": "To satisfy $D(k \\cdot n) = k \\cdot D(n)$, each digit $d$ in $n$ must become $k \\cdot d$ after multiplying $n$ by $k$. In other words, none of $n$'s digits can carry over to the next digit upon multiplication. From this, we can deduce that each digit in $n$ must be less than or equal to $\\lfloor \\frac{9}{k} \\rfloor$. Only thing left is to count all such numbers in the range of $10^l$ inclusive and $10^r$ exclusive. Every number below ${10}^r$ has $r$ or less digits. For numbers with less than $r$ digits, let's pad the beginning with zeroes until it becomes a $r$ digit number (for example, if $r = 5$, then $69$ becomes $00069$). This allows us to consider numbers with less than $r$ digits the same way as numbers with exactly $r$ digits. For each digit, we have $\\lfloor \\frac{9}{k} \\rfloor + 1$ choices (including zero), and there are $r$ digits, so the total number of numbers that satisfies the constraint below ${10}^r$ is $(\\lfloor \\frac{9}{k} \\rfloor + 1)^r$. To get the count of numbers in range, it suffices to subtract all valid numbers less than $10^l$. Therefore, the answer is $(\\lfloor \\frac{9}{k} \\rfloor + 1)^r - (\\lfloor \\frac{9}{k} \\rfloor + 1)^l$. To exponentiate fast, we can use modular exponentiation.",
    "code": "MOD = int(1e9+7)\nt = int(input())\nfor _ in range(t):\n    l, r, k = map(int, input().split())\n    print((pow(9 // k + 1, r, MOD) - pow(9 // k + 1, l, MOD) + MOD) % MOD)",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1985",
    "index": "H1",
    "title": "Maximize the Largest Component (Easy Version)",
    "statement": "\\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. The only difference between the two versions is the operation.}\n\nAlex has a grid with $n$ rows and $m$ columns consisting of '.' and '#' characters. A set of '#' cells forms a connected component if from any cell in this set, it is possible to reach any other cell in this set by only moving to another cell in the set that shares a \\textbf{common side}. The size of a connected component is the number of cells in the set.\n\nIn one operation, Alex selects any row $r$ ($1 \\le r \\le n$) \\textbf{or} any column $c$ ($1 \\le c \\le m$), then sets every cell in row $r$ \\textbf{or} column $c$ to be '#'. Help Alex find the maximum possible size of the largest connected component of '#' cells that he can achieve after performing the operation \\textbf{at most once}.",
    "tutorial": "Let's first solve the problem if we can only select and fill rows. Columns can be handled in the exact same way. For each row $r$, we need to find the size of the component formed by filling row $r$ (i.e. the size of the component containing row $r$ if we set all cells in row $r$ to be $\\texttt{#}$). The size of the component containing row $r$ if we set all cells in row $r$ to be $\\texttt{#}$ will be the sum of: The number of $\\texttt{.}$ in row $r$ since these cells will be set to $\\texttt{#}$. Let $F_r$ denote this value for some row $r$. The sum of sizes of components containing a cell in either row $r-1$, $r$, or $r+1$ (i.e. components that are touching row $r$). This is since these components will be part of the component containing row $r$. Let $R_r$ denote this value for some row $r$. The challenge is computing the second term quickly. For some component, let $s$ be the size of the component and let $r_{min}$ and $r_{max}$ denote the minimum and maximum row of a cell in the component. This means that the component will contain cells with rows $r_{min},r_{min+1},...,r_{max}$. Note that we can find these values with a dfs. Since the component will contribute $s$ to rows in $[r_{min}-1,r_{min},\\ldots r_{max}+1]$, we add $s$ to $R_{r_{min}-1},R_{r_{min}},\\ldots,R_{r_{max}+1}$. This can be done naively or with prefix sums. We find the maximum $F_r+R_r$ and then handle columns in the same way. This solution runs in $\\mathcal{O}(nm)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n, m, minR, maxR, minC, maxC, sz, ans; vector<int> R, C, freeR, freeC; \nvector<vector<bool>> vis; vector<vector<char>> A;\n\nvoid dfs(int i, int j){\n    if (i <= 0 or i > n or j <= 0 or j > m or vis[i][j] or A[i][j] == '.')\n        return;\n    \n    vis[i][j] = true;\n\n    sz++;\n    minR = min(minR, i);\n    maxR = max(maxR, i);\n    minC = min(minC, j);\n    maxC = max(maxC, j);\n\n    dfs(i - 1, j);\n    dfs(i + 1, j);\n    dfs(i, j - 1);\n    dfs(i, j + 1);\n}\n\nvoid solve(){\n    cin >> n >> m;\n\n    R.assign(n + 5, 0);\n    C.assign(m + 5, 0);\n    freeR.assign(n + 5, 0);\n    freeC.assign(m + 5, 0);\n    vis.assign(n + 5, vector<bool>(m + 5, false));\n    A.assign(n + 5, vector<char>(m + 5, ' '));\n\n    for (int i = 1; i <= n; i++){\n        for (int j = 1; j <= m; j++){\n            cin >> A[i][j];\n\n            if (A[i][j] == '.'){\n                freeR[i]++;\n                freeC[j]++;\n            }\n        }\n    }\n    \n    for (int i = 1; i <= n; i++){\n        for (int j = 1; j <= m; j++){\n            if (vis[i][j] or A[i][j] == '.')\n                continue;\n\n            // Reset\n            sz = 0;\n            minR = 1e9;\n            maxR = -1e9;\n            minC = 1e9;\n            maxC = -1e9;\n\n            dfs(i, j);\n\n            // Expand by 1 since adjacent cells also connect\n            minR = max(minR - 1, 1);\n            maxR = min(maxR + 1, n);\n            minC = max(minC - 1, 1);\n            maxC = min(maxC + 1, m);\n            \n            // Update prefix sums\n            R[minR] += sz;\n            R[maxR + 1] -= sz;\n\n            C[minC] += sz;\n            C[maxC + 1] -= sz;\n        }\n    }\n\n    ans = 0;\n\n    for (int i = 1; i <= n; i++){\n        R[i] += R[i - 1];\n        ans = max(ans, freeR[i] + R[i]);\n    }\n    for (int i = 1; i <= m; i++){\n        C[i] += C[i - 1];\n        ans = max(ans, freeC[i] + C[i]);\n    }\n\n    cout << ans << \"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1985",
    "index": "H2",
    "title": "Maximize the Largest Component (Hard Version)",
    "statement": "\\textbf{Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. The only difference between the two versions is the operation.}\n\nAlex has a grid with $n$ rows and $m$ columns consisting of '.' and '#' characters. A set of '#' cells forms a connected component if from any cell in this set, it is possible to reach any other cell in this set by only moving to another cell in the set that shares a \\textbf{common side}. The size of a connected component is the number of cells in the set.\n\nIn one operation, Alex selects any row $r$ ($1 \\le r \\le n$) \\textbf{and} any column $c$ ($1 \\le c \\le m$), then sets every cell in row $r$ \\textbf{and} column $c$ to be '#'. Help Alex find the maximum possible size of the largest connected component of '#' cells that he can achieve after performing the operation \\textbf{at most once}.",
    "tutorial": "For each row $r$ and column $c$, we need to find the size of the component formed by filling both row $r$ and column $c$ (i.e. the size of the component containing row $r$ and column $c$ if we set all cells in both row $r$ and column $c$ to be $\\texttt{#}$). Extending the reasoning in H1, for some row $r$ and column $c$, consider the sum of: The number of $\\texttt{.}$ in row $r$ or column $c$ since these cells will be set to $\\texttt{#}$. Let $F_{r,c}$ denote this value for some row $r$ and column $c$. The sum of sizes of components containing a cell in either row $r-1$, $r$, or $r+1$ (i.e. components that are touching row $r$). This is since these components will be part of the component containing row $r$ and column $c$. Let $R_r$ denote this value for some row $r$. The sum of sizes of components containing a cell in either column $c-1$, $c$, or $c+1$ (i.e. components that are touching column $c$). This is since these components will be part of the component containing row $r$ and column $c$. Let $C_c$ denote this value for some column $c$. However, components that contain a cell in either row $r-1$, $r$, or $r+1$ as well as in either column $c-1$, $c$, or $c+1$ will be overcounted (since it will be counted in both terms $2$ and $3$) (you can think of it as components touching both row $r$ and column $c$). Thus, we need to subtract the sum of sizes of components that contain a cell in either row $r-1$, $r$, or $r+1$ as well as in either column $c-1$, $c$, or $c+1$. Let $B_{r,c}$ denote this for some row $r$ and column $c$. Then the size of the component formed by filling both row $r$ and column $c$ will be $F_{r,c}+R_r+C_c-B_{r,c}$ and we want to find the maximum value of this. Let's try to calculate these values efficiently. Consider some component. Let $s$ be its size. Let $r_{min}$ and $r_{max}$ denote the minimum and maximum row of a cell in the component. This means that the component contains cells with rows $r_{min},r_{min+1},...,r_{max}$. Let $c_{min}$ and $c_{max}$ denote the minimum and maximum column of a cell in the component. This means that the component contains cells with columns $c_{min},c_{min+1},...,c_{max}$. All these values can be found with a dfs. We then do the following updates: Add $s$ to $R_{r_{min}-1},R_{r_{min}},\\ldots,R_{r_{max}+1}$. This can be done naively or with prefix sums. Add $s$ to $C_{c_{min}-1},C_{c_{min}},\\ldots,C_{c_{max}+1}$. This can be done naively or with prefix sums. Add $s$ to the subrectangle of $B$ with top left at ($r_{min}-1,c_{min}-1$) and bottom right at ($r_{max}+1,c_{max}+1$). This can be done with 2D prefix sums. (Note that doing this naively will pass because of low constant factor and the fact that we could not cut this solution without cutting slow correct solutions.) We do this for each component. Also, calculating $F_{r,c}$ can be done by looking at the number of $\\texttt{.}$ in row $r$, column $c$, and checking whether we overcounted a $\\texttt{.}$ at ($r,c$). In all, this solution runs in $\\mathcal{O}(nm)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint n, m, minR, maxR, minC, maxC, sz, ans; vector<int> R, C, freeR, freeC; \nvector<vector<int>> RC; vector<vector<bool>> vis; vector<vector<char>> A;\n\nvoid dfs(int i, int j){\n    if (i <= 0 or i > n or j <= 0 or j > m or vis[i][j] or A[i][j] == '.')\n        return;\n    \n    vis[i][j] = true;\n\n    sz++;\n    minR = min(minR, i);\n    maxR = max(maxR, i);\n    minC = min(minC, j);\n    maxC = max(maxC, j);\n\n    dfs(i - 1, j);\n    dfs(i + 1, j);\n    dfs(i, j - 1);\n    dfs(i, j + 1);\n}\n\nvoid solve(){\n    cin >> n >> m;\n\n    R.assign(n + 5, 0);\n    C.assign(m + 5, 0);\n    freeR.assign(n + 5, 0);\n    freeC.assign(m + 5, 0);\n    RC.assign(n + 5, vector<int>(m + 5, 0));\n    vis.assign(n + 5, vector<bool>(m + 5, false));\n    A.assign(n + 5, vector<char>(m + 5, ' '));\n\n    for (int i = 1; i <= n; i++){\n        for (int j = 1; j <= m; j++){\n            cin >> A[i][j];\n\n            if (A[i][j] == '.'){\n                freeR[i]++;\n                freeC[j]++;\n            }\n        }\n    }\n    \n    for (int i = 1; i <= n; i++){\n        for (int j = 1; j <= m; j++){\n            if (vis[i][j] or A[i][j] == '.')\n                continue;\n\n            // Reset\n            sz = 0;\n            minR = 1e9;\n            maxR = -1e9;\n            minC = 1e9;\n            maxC = -1e9;\n\n            dfs(i, j);\n\n            // Expand by 1 since adjacent cells also connect\n            minR = max(minR - 1, 1);\n            maxR = min(maxR + 1, n);\n            minC = max(minC - 1, 1);\n            maxC = min(maxC + 1, m);\n            \n            // Update prefix sums\n            R[minR] += sz;\n            R[maxR + 1] -= sz;\n\n            C[minC] += sz;\n            C[maxC + 1] -= sz;\n\n            RC[minR][minC] += sz;\n            RC[maxR + 1][minC] -= sz;\n            RC[minR][maxC + 1] -= sz;\n            RC[maxR + 1][maxC + 1] += sz;\n        }\n    }\n\n    for (int i = 1; i <= n; i++)\n        R[i] += R[i - 1];\n\n    for (int i = 1; i <= m; i++)\n        C[i] += C[i - 1];\n\n    for (int i = 1; i <= n; i++)\n        for (int j = 1; j <= m; j++)\n            RC[i][j] += RC[i - 1][j] + RC[i][j - 1] - RC[i - 1][j - 1];\n    \n    ans = 0;\n\n    for (int i = 1; i <= n; i++)\n        for (int j = 1; j <= m; j++)\n            ans = max(ans, (R[i] + C[j] - RC[i][j]) + (freeR[i] + freeC[j] - (A[i][j] == '.')));\n    \n    cout << ans << \"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1986",
    "index": "A",
    "title": "X Axis",
    "statement": "You are given three points with integer coordinates $x_1$, $x_2$, and $x_3$ on the $X$ axis ($1 \\leq x_i \\leq 10$). You can choose any point with an integer coordinate $a$ on the $X$ axis. Note that the point $a$ may coincide with $x_1$, $x_2$, or $x_3$. Let $f(a)$ be the total distance from the given points to the point $a$. Find the smallest value of $f(a)$.\n\nThe distance between points $a$ and $b$ is equal to $|a - b|$. For example, the distance between points $a = 5$ and $b = 2$ is $3$.",
    "tutorial": "Let $x_1 \\leq x_2 \\leq x_3$. Notice that the answer is at least $x_3 - x_1$, because $|x_3 - a| + |x_1 - a| \\geq |x_3 - x_1|$ for any numbers $a$, $x_1$, $x_3$. The answer is equal to $x_3 - x_1$, since we can choose $a = x_2$.",
    "tags": [
      "brute force",
      "geometry",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1986",
    "index": "B",
    "title": "Matrix Stabilization",
    "statement": "You are given a matrix of size $n \\times m$, where the rows are numbered from $1$ to $n$ from top to bottom, and the columns are numbered from $1$ to $m$ from left to right. The element at the intersection of the $i$-th row and the $j$-th column is denoted by $a_{ij}$.\n\nConsider the algorithm for stabilizing matrix $a$:\n\n- Find the cell $(i, j)$ such that its value is strictly greater than the values of all its neighboring cells. If there is no such cell, terminate the algorithm. If there are multiple such cells, choose the cell with the smallest value of $i$, and if there are still multiple cells, choose the one with the smallest value of $j$.\n- Set $a_{ij} = a_{ij} - 1$.\n- Go to step $1$.\n\nIn this problem, cells $(a, b)$ and $(c, d)$ are considered neighbors if they share a common side, i.e., $|a - c| + |b - d| = 1$.\n\nYour task is to output the matrix $a$ after the stabilization algorithm has been executed. It can be shown that this algorithm cannot run for an infinite number of iterations.",
    "tutorial": "Let's consider any two adjacent cells of the matrix. Notice that our algorithm can change at most one value of these two cells. If the values in the cells are equal, then neither of these two adjacent cells will ever change its value. If the values in the cells are not equal, then the value of the larger cell will never become smaller than the value of the smaller cell. Let $mx$ be the maximum value written in the cells adjacent to $(i, j)$. If $mx \\geq a_{ij}$, then the value of the cell $(i, j)$ will not change during the execution of the algorithm; otherwise, it will eventually become equal to $mx$.",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1986",
    "index": "C",
    "title": "Update Queries",
    "statement": "Let's consider the following simple problem. You are given a string $s$ of length $n$, consisting of lowercase Latin letters, as well as an array of indices $ind$ of length $m$ ($1 \\leq ind_i \\leq n$) and a string $c$ of length $m$, consisting of lowercase Latin letters. Then, in order, you perform the update operations, namely, during the $i$-th operation, you set $s_{ind_i} = c_i$. Note that you perform all $m$ operations from the first to the last.\n\nOf course, if you change the order of indices in the array $ind$ and/or the order of letters in the string $c$, you can get different results. Find the lexicographically smallest string $s$ that can be obtained after $m$ update operations, if you can rearrange the indices in the array $ind$ and the letters in the string $c$ as you like.\n\nA string $a$ is lexicographically less than a string $b$ if and only if one of the following conditions is met:\n\n- $a$ is a prefix of $b$, but $a \\neq b$;\n- in the first position where $a$ and $b$ differ, the symbol in string $a$ is earlier in the alphabet than the corresponding symbol in string $b$.",
    "tutorial": "Let $i_1 < i_2 < \\ldots < i_k$ be the set of indices of the array $ind$. Note that the indices of the string $s$ that are not in this set will simply not change their value. Then we want to place the smallest character of the string $c$ at position $i_1$, the next smallest at position $i_2$, and so on. To achieve this, we can sort all the characters in the string $c$. This approach to obtaining the answer is possible because all other operations, except those described above, can be performed first and will not affect the answer.",
    "tags": [
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1986",
    "index": "D",
    "title": "Mathematical Problem",
    "statement": "You are given a string $s$ of length $n > 1$, consisting of digits from $0$ to $9$. You must insert exactly $n - 2$ symbols $+$ (addition) or $\\times$ (multiplication) into this string to form a valid arithmetic expression.\n\nIn this problem, the symbols cannot be placed before the first or after the last character of the string $s$, and two symbols cannot be written consecutively. Also, note that the order of the digits in the string cannot be changed. Let's consider $s = 987009$:\n\n- From this string, the following arithmetic expressions can be obtained: $9 \\times 8 + 70 \\times 0 + 9 = 81$, $98 \\times 7 \\times 0 + 0 \\times 9 = 0$, $9 + 8 + 7 + 0 + 09 = 9 + 8 + 7 + 0 + 9 = 33$. Note that the number $09$ is considered valid and is simply transformed into $9$.\n- From this string, the following arithmetic expressions cannot be obtained: $+9 \\times 8 \\times 70 + 09$ (symbols should only be placed between digits), $98 \\times 70 + 0 + 9$ (since there are $6$ digits, there must be exactly $4$ symbols).\n\nThe result of the arithmetic expression is calculated according to the rules of mathematics — first all multiplication operations are performed, then addition. You need to find the minimum result that can be obtained by inserting exactly $n - 2$ addition or multiplication symbols into the given string $s$.",
    "tutorial": "First, let's iterate through the position $i$, such that we do not place a mathematical sign between the $i$-th and $(i+1)$-th elements. Next, we have the following task - we have $n - 1$ numbers and we need to place a $+$ or $\\times$ sign between each pair of neighboring numbers to minimize the result. There are three possible cases: If there is at least one $0$, the answer is $0$. We can simply place all signs as $\\times$. If all numbers are $1$, the answer is $1$. We can simply place all signs as $\\times$. Otherwise, the answer is the sum of numbers not equal to $1$. It is not advantageous to multiply numbers greater than one with each other, and all ones can simply be multiplied by any of the neighbors.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1986",
    "index": "E",
    "title": "Beautiful Array",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$ and an integer $k$. You need to make it beautiful with the least amount of operations.\n\nBefore applying operations, you can shuffle the array elements as you like. For one operation, you can do the following:\n\n- Choose an index $1 \\leq i \\leq n$,\n- Make $a_i = a_i + k$.\n\nThe array $b_1, b_2, \\ldots, b_n$ is beautiful if $b_i = b_{n - i + 1}$ for all $1 \\leq i \\leq n$.\n\nFind the minimum number of operations needed to make the array beautiful, or report that it is impossible.",
    "tutorial": "Notice that we actually want to pair the elements (in the odd case, exactly one element will not have a pair). If numbers $x \\leq y$ fall into the same pair, then: These two numbers should have the same remainder when divided by $k$. This is necessary in order to obtain one from the other. To make them equal, we will need $\\frac{y - x}{k} = \\frac{y}{k} - \\frac{x}{k}$ operations. Consider all numbers from the array $a$ with the same remainder when divided by $k$. Also, immediately divide them by the number $k$. Let these numbers be $b_1 \\leq b_2 \\leq \\ldots \\leq b_m$. There are two possible cases: If $m$ is even, we need to pair all the numbers. It is best to pair $b_1$ and $b_2$, $b_3$ and $b_4$, and so on. Consequently, we will need $b_2 - b_1 + b_4 - b_3 + \\ldots + b_{n} - b_{n - 1}$ operations. If $m$ is odd, one element will remain unpaired. It can be tried and then an even number of elements will remain, and we can apply the idea for the even case. Notice that it is advantageous to remove the element with an odd index (denote it as $i$). Then, if we leave the $i$-th element unpaired, we will need $b_2 - b_1 + b_4 - b_3 + \\ldots + b_{i - 1} - b_{i - 2} + b_{i + 2} - b_{i + 1} + \\ldots b_n - b_{n - 1}$ operations. To quickly calculate this sum, you can use prefix/suffix sums. Also, note that if there are two different remainders for which $m$ is odd, the answer is $-1$.",
    "tags": [
      "greedy",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1986",
    "index": "F",
    "title": "Non-academic Problem",
    "statement": "You are given a connected undirected graph, the vertices of which are numbered with integers from $1$ to $n$. Your task is to minimize the number of pairs of vertices $1 \\leq u < v \\leq n$ between which there exists a path in this graph. To achieve this, you can remove exactly one edge from the graph.\n\nFind the smallest number of pairs of vertices!",
    "tutorial": "Notice that if an edge is not a bridge, then after its removal the graph remains connected and all vertices are reachable from each other. Therefore, we would like to remove some bridge edge (if there are no bridges, the answer is $\\frac{n \\cdot (n - 1)}{2}$). After its removal, the graph will split into two connected components, let their sizes be $x$ and $y$ (note that $x + y = n$). Then the number of pairs of vertices reachable from each other will be equal to $\\frac{x \\cdot (x - 1)}{2} + \\frac{y \\cdot (y - 1)}{2}$. Let's find all the bridges in the graph, run a $dfs$ from an arbitrary vertex and calculate for each vertex the size of its subtree in the $dfs$ traversal tree (denote the size of the subtree of vertex $v$ as $sz_v$). Thus, for each bridge, we can find $x$ and $y$, knowing the sizes of the subtrees (if the edge $(u, v)$ is a bridge, then $x = \\min(sz_x, sz_y), y = n - x$). For all bridges, output the smallest answer.",
    "tags": [
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1986",
    "index": "G2",
    "title": "Permutation Problem (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $n \\leq 5 \\cdot 10^5$ and the sum of $n$ for all sets of input data does not exceed $5 \\cdot 10^5$.}\n\nYou are given a permutation $p$ of length $n$. Calculate the number of index pairs $1 \\leq i < j \\leq n$ such that $p_i \\cdot p_j$ is divisible by $i \\cdot j$ without remainder.\n\nA permutation is a sequence of $n$ integers, in which each integer from $1$ to $n$ occurs exactly once. For example, $[1]$, $[3,5,2,1,4]$, $[1,3,2]$ are permutations, while $[2,3,2]$, $[4,3,1]$, $[0]$ are not.",
    "tutorial": "Let $a_i = \\frac{p_i}{\\gcd(i, p_i)}$, $b_i = \\frac{i}{\\gcd(i, p_i)}$. Notice that we want to calculate the number of index pairs $i < j$, such that: $a_j$ is divisible by $b_i$. $a_i$ is divisible by $b_j$. Let's iterate through the values of $b_i$ from $1$ to $n$ (note that we are not fixing the element $i$, but rather fixing the value of $b_i$). Now we know that we are interested in all $a_j = b_i \\cdot k$, for some positive integer $k$. Let's iterate through all such possible $a_j$, and then iterate through all pairs with that value of $a_j$. Add all suitable $b_j$ to the count array. Now, for a fixed $b_i$ and the constructed count array for it, iterate through all $a_i$ that exist with this $b_i$. We can iterate through all divisors of $a_i$ and simply add their count from the count array to the answer, because: Only those pairs for which $a_j$ is divisible by $b_i$ are considered in the count array, so we have accounted for the first condition. We have accounted for the second condition when iterating through the divisors of $a_i$. If the above is implemented correctly, a solution can be obtained in $O(n \\log n)$. For this, we will need to pre-calculate all divisors for each $i$ from $1$ to $n$. We can iterate through $i$ and mark it as a divisor for all numbers of the form $k \\cdot i$. Also, everything written above works in $O(n \\log n)$, because: the array $a$ was obtained from a permutation by dividing some elements, so the total number of divisors of all elements in $a$ (as well as the array $b$) is no more than the total number of divisors of numbers from $1$ to $n$. And the total number of divisors of numbers from $1$ to $n$ is at most $\\sum\\limits_{i=1}^n \\frac{n}{i} = O(n \\log n)$.",
    "tags": [
      "brute force",
      "data structures",
      "hashing",
      "math",
      "number theory"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1987",
    "index": "A",
    "title": "Upload More RAM",
    "statement": "Oh no, the ForceCodes servers are running out of memory! Luckily, you can help them out by uploading some of your RAM!\n\nYou want to upload $n$ GBs of RAM. Every second, you will upload either $0$ or $1$ GB of RAM. However, there is a restriction on your network speed: in any $k$ consecutive seconds, you can upload only at most $1$ GB of RAM in total.\n\nFind the minimum number of seconds needed to upload $n$ GBs of RAM!",
    "tutorial": "First of all, note that you can upload $n$ GBs of RAM if you upload on the seconds $1, k + 1, 2k + 1, \\ldots, (n - 1)k + 1$, taking $(n - 1)k + 1$ seconds in total. Let's show that it's impossible to do better. Suppose there is a solution where you upload on the times $t_1, t_2, \\ldots t_n$, taking $t_n$ seconds to upload $n$ GBs. Then, $t_{i} + k \\le t_{i + 1}$ for all $1 \\le i \\le n - 1$. Furthermore, $t_1 \\ge 1$. Thus, we have the following inequalities: $1 \\le t_1$ $t_1 + k \\le t_2$ $t_2 + k \\le t_3$ $\\ldots$ $t_{n - 1} + k \\le t_n$ Using them, we get the inequalities $1 \\le t_1$ $1 + k \\le t_1 + k \\le t_2$ $1 + 2k \\le t_2 + k \\le t_3$ $\\ldots$ $1 + (n - 1)k \\le t_{n-1} + k \\le t_n$ So, $t_n \\ge (n - 1)k + 1$, so the answer is at least $(n - 1)k + 1$. Since there is always a way to upload in exactly this many seconds, this is the answer to our problem. Complexity: $\\mathcal{O}(1)$",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    cout << 1 + (n - 1) * k << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1987",
    "index": "B",
    "title": "K-Sort",
    "statement": "You are given an array of integers $a$ of length $n$.\n\nYou can apply the following operation any number of times (maybe, zero):\n\n- First, choose an integer $k$ such that $1 \\le k \\le n$ and pay $k + 1$ coins.\n- Then, choose \\textbf{exactly} $k$ indices such that $1 \\le i_1 < i_2 < \\ldots < i_k \\le n$.\n- Then, for each $x$ from $1$ to $k$, increase $a_{i_x}$ by $1$.\n\nFind the minimum number of coins needed to make $a$ non-decreasing. That is, $a_1 \\le a_2 \\le \\ldots \\le a_n$.",
    "tutorial": "Suppose that after all of the operations, the value at index $i$ has been increased by $b_i$. Notice that our cost can be factored into two parts: $k$ is responsible for how many elements we choose, and $1$ is responsible for how many operations we apply. Since we have to apply at least $\\max(b_i)$ operations, and over all operations we select a total of $\\sum{b_i}$ elements, we have to pay at least $\\sum{b_i} + \\max(b_i)$ coins. This bound is also achievable, if on the $m$-th operation (numbered from $1$ to $\\max(b_i)$) we select all indices with $b_i \\ge m$. Suppose the resulting array is sorted ($a_1 + b_1 \\le a_2 + b_2 \\le \\ldots \\le a_n + b_n$). Then, $a_i + b_i \\le a_j + b_j$ must hold for all $1 \\le i \\le j \\le n$. Using $b_i \\ge 0$, we get $a_j + b_j \\ge a_i + b_i \\ge a_i \\implies b_j \\ge a_i - a_j$ for all $1 \\le i \\le j$. If we define $p_j := max(a_1, \\ldots, a_j)$, we get $b_j \\ge p_j - a_j$. This gives the lower bounds $\\sum{b_i} \\ge \\sum(p_i - a_i)$ and $\\max(b_i) \\ge \\max(p_i - a_i)$. Setting $b_i := p_i - a_i$ achieves them, so the answer to our problem is $\\sum(p_i - a_i) + \\max(p_i - a_i)$ coins. Complexity: $\\mathcal{O}(n)$ Note: it's possible to simulate the process on the values of $b$ (described above) in $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector<int> a(n);\n    for (int i = 0; i < n; i++) cin >> a[i];\n    \n    ll pref_max = 0, s = 0, mx = 0;\n    for (int i = 0; i < n; i++) {\n        pref_max = max(pref_max, (ll) a[i]);\n        \n        ll d = pref_max - a[i];\n        s += d;\n        mx = max(mx, d);\n    }\n    \n    cout << s + mx << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1987",
    "index": "C",
    "title": "Basil's Garden",
    "statement": "There are $n$ flowers in a row, the $i$-th of them initially has a positive height of $h_i$ meters.\n\nEvery second, the wind will blow from the left, causing the height of some flowers to decrease.\n\nSpecifically, every second, for each $i$ from $1$ to $n$, in this order, the following happens:\n\n- If $i = n$ or $h_i > h_{i + 1}$, the value of $h_i$ changes to $\\max(0, h_i - 1)$.\n\nHow many seconds will pass before $h_i=0$ for all $1 \\le i \\le n$ for the first time?",
    "tutorial": "First, let's try to find when $h_{n}$ will first be equal to zero. The answer is clearly $h_{n}$. Suppose for some $2 \\le i \\le n$ we know that $h_{i}$ will first become equal to zero at time $t_{i}$ ($t_n = h_n$). If at some point in time, $h_{i-1}$ was equal to $h_{i}$ (at the start of the second and before they are both equal to zero), $t_{i-1}$ is equal to $t_{i} + 1$. Since after that point in time, if $h_{i}$ decreases, $h_{i-1}$ must decrease in the next second. If $h_{i-1}$ is never equal to $h_{i}$ (until they hit zero), $h_{i - 1}$ must always be strictly greater than $h_{i}$. This means that $h_{i-1}$ will keep decreasing every second until it hits zero, so $t_{i-1}$ is equal to $h_{i-1}$ in this case. Examples: The array $[2, 3, 1, 1, 1]$ changes as follows: $[2, \\color{red}{3}, 1, 1, \\color{red}{1}] \\rightarrow [2, \\color{red}{2}, 1, \\color{red}{1}, 0] \\rightarrow [\\color{red}{2}, 1, \\color{red}{1}, 0, 0] \\rightarrow$ $[1, \\color{red}{1}, 0, 0, 0] \\rightarrow [\\color{red}{1}, 0, 0, 0, 0] \\rightarrow [0, 0, 0, 0, 0]$. If we focus on the first two elements, they change as follows: $[2, \\color{red}{3}] \\rightarrow [2, \\color{red}{2}] \\rightarrow [\\color{red}{2}, 1] \\rightarrow [1, 1] \\rightarrow [1, \\color{red}{1}] \\rightarrow [\\color{red}{1}, 0] \\rightarrow [0, 0]$. The array $[4, 1, 1]$ changes as follows: $[\\color{red}{4}, 1, \\color{red}{1}] \\rightarrow [\\color{red}{3}, \\color{red}{1}, 0] \\rightarrow [\\color{red}{2}, 0, 0] \\rightarrow [\\color{red}{1}, 0, 0] \\rightarrow [0, 0, 0]$. Let's combine the two cases. If initially $h_{i-1} \\le h_{i}$ holds, $h_{i-1}$ will become equal to $h_{i}$ at some point in time, so $t_{i-1} = t_{i} + 1$. Else, $h_{i-1} > h_{i}$, so $t_{i-1} = h_{i-1}$. Combining the two, we get $t_{i-1} = \\max(h_{i-1}, t_{i} + 1)$. Since we know $t_n = h_n$, we can easily calculate all the other values of $t_i$ by iterating from $n - 1$ to $1$. The answer to the problem is $t_1$, since $t_{i-1} \\ge t_{i} + 1$ for all $2 \\le i \\le n$. Complexity: $\\mathcal{O}(n)$",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector<int> h(n);\n    for (auto &x: h) cin >> x;\n    \n    int ans = h[n - 1];\n    for (int i = n - 2; i >= 0; i--) {\n        ans = max(ans + 1, h[i]);\n    }\n\n    cout << ans << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) solve();\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1987",
    "index": "D",
    "title": "World is Mine",
    "statement": "Alice and Bob are playing a game. Initially, there are $n$ cakes, with the $i$-th cake having a tastiness value of $a_i$.\n\nAlice and Bob take turns eating them, with Alice starting first:\n\n- In her turn, Alice chooses and eats any remaining cake whose tastiness is \\textbf{strictly greater} than the \\textbf{maximum} tastiness of any of the cakes she's eaten before that. Note that on the first turn, she can choose any cake.\n- In his turn, Bob chooses any remaining cake and eats it.\n\nThe game ends when the current player can't eat a suitable cake. Let $x$ be the number of cakes that Alice ate. Then, Alice wants to maximize $x$, while Bob wants to minimize $x$.\n\nFind out how many cakes Alice will eat if both players play optimally.",
    "tutorial": "Let's consider Alice's strategy. Notice that if both players play optimally, Alice eating a cake with a tastiness value of $t$ is equivalent to her eating all remaining cakes with $a_i \\le t$. Since it is better for her to have more cakes to choose from later on, she will choose the minimum possible $t$ on each turn. Now let's consider Bob's strategy. Suppose Bob ate at least one cake with a tastiness value of $t$. Then he has to have eaten all of them, because eating only some of them does not affect Alice's possible moves, resulting in wasted turns (he might be forced to waste moves at the end of the game when there are some leftover cakes). Let $A_1, \\ldots, A_m$ be the sorted unique values of $a_1, \\ldots, a_n$, and let $c_i$ be the number of occurrences of $A_i$ in $a$. Then the game is reduced to Alice finding the first $c_i > 0$ and assigning $c_i := 0$, and Bob choosing any $c_i > 0$ and decreasing it by $1$. Since Bob's optimal strategy is for each $c_i$ either not to touch it or make $c_i = 0$, we can model it as him selecting some set of indices $1 \\le i_1 < \\ldots < i_k \\le m$ and zeroing out $c_{i_1}, c_{i_2}, \\ldots, c_{i_k}$ in this order. To be able to zero out $c_{i_p}$ ($1 \\le p \\le k$), Alice must not have gotten to the value $c_{i_p}$. In $c_{i_1} + \\ldots + c_{i_p}$ turns, Alice will zero out exactly that many values. Additionally, Bob would have zeroed out $p - 1$ values before index $i_p$. So, $c_{i_1} + \\ldots + c_{i_p} + p - 1$ must be less than $i_p$. Transforming this a bit, we get that the condition $\\sum_{j=1}^{p}{c_{i_j}} \\le i_p - p$ must hold for all $1 \\le p \\le k$. Bob's objective to maximize the size of the set of incides $1 \\le i_1 < \\ldots < i_k \\le m$. Let $dp[i][k] =$ the minimum possible $\\sum_{j=1}^{k}{c_{i_j}}$ over all valid sets of indices $1 \\le i_1 < \\ldots < i_k \\le i$. Initialize $dp[0][0] = 0$, and everything else to $+\\infty$. The main idea is to grow valid sets of indices one index at a time. We will iterate over all $i$ from $1$ to $m$, and then for each $k$ from $0$ to $m$. The transitions are: $dp[i][k] = \\min(dp[i][k], d[i - 1][k])$, which corresponds to not using the current index in the set. Let $s := dp[i - 1][k - 1] + c_i$. If $s \\le i_k - k$, update $dp[i][k] = \\min(dp[i][k], s)$, which is equivalent to adding the current index to the set. We only need to check the condition on the last index because it is already satisfied for all the previous indices. The answer to the problem is $m - y$, where $y$ is the largest value where $dp[m][y] < +\\infty$. Complexity: $\\mathcal{O}(n^2)$ Note: it is possible to solve in $\\mathcal{O}(n \\log n)$ by making an additional observation.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int inf = 1e9;\n\nvoid solve() {\n    vector<int> a;\n    {\n        int n;\n        cin >> n;\n        \n        map<int, int> cnt;\n        while (n--) {\n            int x;\n            cin >> x;\n            cnt[x]++;\n        }\n        \n        for (auto const &[k, v]: cnt) {\n            a.push_back(v);\n        }\n    }\n    \n    int n = a.size();\n    vector<int> dp(n + 1, inf);\n    dp[0] = 0;\n    \n    for (int i = 1; i <= n; i++) {\n        vector<int> ndp = dp;\n        \n        for (int k = 1; k <= n; k++) {\n            int nv = dp[k - 1] + a[i - 1];\n            \n            if (nv <= i - k) {\n                ndp[k] = min(ndp[k], nv);\n            }\n        }\n        \n        dp = ndp;\n    }\n    \n    int ans = n;\n    while (dp[ans] >= inf) ans--;\n    cout << n - ans << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) solve();\n}",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1987",
    "index": "E",
    "title": "Wonderful Tree!",
    "statement": "\\begin{quote}\nGod's Blessing on This ArrayForces!\n\\hfill A Random Pebble\n\\end{quote}\n\nYou are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.\n\nLet $L$ be the set of all direct children$^{\\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \\le \\sum_{u \\in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.\n\nFind the minimum number of operations needed to make the given tree wonderful!\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:\n\n- $u$ and $v$ are connected by an edge, and\n- $v$ is on the (unique) path from $u$ to the root of the tree.\n\n\\end{footnotesize}",
    "tutorial": "Let $b_v := \\sum_{u \\in L}{a_u} - a_v$ if $L$ is not empty and $b_v := +\\infty$ otherwise. Then, in one operation we decrease $b_v$ by $1$ and increase $b_{p_v}$ by $1$ ($p_v$ is the parent of $v$), and our objective is to make $b_v \\ge 0$ for all vertices $v$ in as few operations as possible. We can actually chain our operations to form a more powerful one. In particular, the new operation becomes: Select two vertices $v$ and $w$ such that $d_v \\le d_w$ and $v$ is an ancestor of $w$ by paying $d_w - d_v$ coins, where $d_v$ is the depth of vertex $v$. Decrease $b_w$ by $1$ and increase $b_v$ by $1$. Suppose one optimal sequence of operations applies the operations on the pairs of vertices $(v_1, w_1)$ and $(v_2, w_2)$ and the paths $v_1 \\rightarrow w_1$ and $v_2 \\rightarrow w_2$ intersect. Then, applying the operations on the pairs of vertices $(v_1, w_2)$ and $(v_2, w_1)$, is not less optimal since $(d_{w_1} - d_{v_1}) + (d_{w_2} - d_{v_2}) = (d_{w_2} - d_{v_1}) + (d_{w_1} - d_{v_2})$. This means that we can choose which operations to apply on lower $v$ without caring about its ancestors. Example of two operations on $(v_1, w_1)$ and $(v_2, w_2)$. Suppose that after some sequence of operations, which includes the operation $(v, w)$, there is a vertex $u$ in the subtree of $v$ with $d_u < d_w$ and $b_u > 0$. Then, it is optimal to apply the operation on $(v, u)$ instead of $(v, w)$. This means that we want to apply the operation on the closest vertices in the subtree of $v$. The two observations above lead to a greedy. We will iterate over all $v$ from $n$ to $1$, and while $b_v$ is less than zero, keep applying the operation on $(v, u)$, where $u$ is the closest vertex in the subtree of $v$ with $b_u > 0$. This is possible to implement in a number of ways, one of them includes running a bfs from each vertex $v$. Complexity: $\\mathcal{O}(n^2)$ Note: it is possible to solve this problem faster, up to only $\\mathcal{O}(n)$ time.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nconst ll inf = 1e15;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector<int> a(n);\n    for (auto &x: a) cin >> x;\n    \n    vector<int> d(n);\n    vector<vector<int>> g(n);\n    for (int i = 1; i < n; i++) {\n        int p;\n        cin >> p;\n        p--;\n        \n        g[p].push_back(i);\n        d[i] = d[p] + 1;\n    }\n    \n    vector<ll> b(n); // b[v] = sum(a[u]) - a[v]\n    for (int v = 0; v < n; v++) {\n        if (g[v].empty()) {\n            b[v] = inf;\n        } else {\n            b[v] = -a[v];\n        \n            for (int u: g[v]) {\n                b[v] += a[u];\n            }\n        }\n    }\n    \n    ll ans = 0;\n    for (int v = n - 1; v >= 0; v--) {\n        queue<int> q;\n        \n        q.push(v);\n        while (!q.empty()) {\n            int i = q.front();\n            q.pop();\n            \n            for (int u: g[i]) {\n                ll delta = min(-b[v], b[u]);\n                \n                if (delta > 0) {\n                    b[v] += delta;\n                    b[u] -= delta;\n                    ans += delta * (d[u] - d[v]);\n                }\n                \n                q.push(u);\n            }\n        }\n    }\n    \n    cout << ans << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dsu",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1987",
    "index": "F2",
    "title": "Interesting Problem (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if both versions of the problem are solved.}\n\nYou are given an array of integers $a$ of length $n$.\n\nIn one operation, you will perform the following two-step process:\n\n- Choose an index $i$ such that $1 \\le i < |a|$ and $a_i = i$.\n- Remove $a_i$ and $a_{i+1}$ from the array and concatenate the remaining parts.\n\nFind the maximum number of times that you can perform the operation above.",
    "tutorial": "Balanced bracket sequence analogy Suppose there is a way to remove the entire array. Let's look at the process in reverse. Then, we are effectively inserting pairs of adjacent elements into an array until we get the original one. Let's look at a mirror process, where instead we keep inserting pairs of brackets $()$ to get a balanced bracket sequence. For example, consider the array $[1, 2, 5, 4, 5, 7, 7, 1]$. Then, one possible way to delete it is $[1, 2, 5, 4, 5, 7, \\color{red}{7}, \\color{blue}{1}] \\rightarrow [1, 2, 5, \\color{red}{4}, \\color{blue}{5}, 7] \\rightarrow [1, \\color{red}{2}, \\color{blue}{5}, 7] \\rightarrow [\\color{red}{1}, \\color{blue}{7}] \\rightarrow []$. If we now build our bracket sequence, we get $\\emptyset \\rightarrow \\color{red}{(}\\color{blue}{)} \\rightarrow (\\color{red}{(}\\color{blue}{)}) \\rightarrow (()\\color{red}{(}\\color{blue}{)}) \\rightarrow (()())\\color{red}{(}\\color{blue}{)}$. Note that such a bracket sequence doesn't tell us in which order the operation needs to be performed, only on which indices. Solution Let's go back to the original problem. Suppose we want to eventually perform the operation on index $i$ (in the indexation of the original array). Then, two conditions must be met: $a_i \\equiv i \\pmod{2}$ must hold, since the operation does not change the parity of indices. Exactly $\\frac{i - a_i}{2}$ operations must be made to the left of $a_i$ before we apply the operation on it. This, together with the bracket analogy, leads to a pretty natural dynamic programming solution: $dp[l][r] =$ min number of operations that need to be performed to the left of $l$ to be able to remove the subsegment $a_l, \\ldots, a_r$. If $l > r$, initialize $dp[l][r] := 0$, else initialize $dp[l][r] := +\\infty$. Similar to dps on balanced bracket sequences, for $a_l$, we will iterate over the other element $a_m$ with which we will perform the operation, $l \\equiv m \\pmod{2}$: If $dp[l+1][m-1]$ is greater than $\\frac{l - a_l}{2}$, it is impossible to apply the operation on the pair $(a_l, a_m)$, so we do not update $dp[l][r]$. Else, it will take at least $op := \\max(\\frac{l - a_l}{2}, dp[m+1][r] - \\frac{m-l+1}{2})$ operations to the left of $l$ to delete this subsegment if we want to perform the operation on $(a_l, a_m)$. So we update as follows: $dp[l][r] := \\min(dp[l][r], op)$. Suppose we have calculated all the values of $dp[l][r]$. Let's introduce $dp2[r] =$ the maximum number of times that we can perform the operation on the prefix $a_1, a_2, \\ldots, a_r$, initially $dp2[r] := 0$ for all $0 \\le r \\le n$. Then, for some $r$, the transitions are to iterate over all $1 \\le l \\le r$ and update $dp2[r] := \\max(dp2[r], dp2[l - 1] + \\frac{r - l + 1}{2})$ if $dp[l][r] \\le dp2[l - 1]$ holds. The answer to the problem is $dp2[n]$. It takes $\\mathcal{O}(n^3)$ time to calculate the values of $dp[l][r]$, and $\\mathcal{O}(n^2)$ time for $dp2[r]$. Complexity: $\\mathcal{O}(n^3)$ Note: to solve F1, you can calculate the values of $dp[l][r][k] =$ the maximum number of operations that you can perform on the subsegment $a_l, \\ldots, a_r$ if exactly $k$ operations were performed to the left of $l$, which can be done similar to the way above in $O(n^4)$. The answer will be $dp[1][n][0]$.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nconst int inf = 1e9;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector<int> a(n);\n    for (int i = 0; i < n; i++) cin >> a[i];\n    \n    \n    vector<vector<int>> dp(n + 1, vector<int> (n + 1, inf));\n    \n    for (int i = 0; i <= n; i++) {\n        dp[i][i] = 0;\n    }\n    \n    for (int le = 1; le <= n; le++) {\n        for (int l = 0; l + le <= n; l++) {\n            if (a[l] % 2 != (l + 1) % 2) continue;\n            if (a[l] > l + 1) continue;\n            int v = (l + 1 - a[l]) / 2;\n            \n            int r = l + le;\n            for (int m = l + 1; m < r; m += 2) { // index of the closing bracket\n                if (dp[l + 1][m] <= v) {\n                    int new_val = max(v, dp[m + 1][r] - (m - l + 1) / 2);\n                    dp[l][r] = min(dp[l][r], new_val);\n                }\n            }\n        }\n    }\n    \n    vector<int> dp2(n + 1);\n    for (int i = 0; i < n; i++) {\n        dp2[i + 1] = dp2[i];\n        \n        for (int j = 0; j < i; j++) {\n            if (dp[j][i + 1] <= dp2[j]) {\n                dp2[i + 1] = max(dp2[i + 1], dp2[j] + (i - j + 1) / 2);\n            }\n        }\n    }\n    \n    cout << dp2[n] << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "dp"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1987",
    "index": "G1",
    "title": "Spinning Round (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions are the allowed characters in $s$. In the easy version, $s$ only contains the character ?. You can make hacks only if both versions of the problem are solved.}\n\nYou are given a permutation $p$ of length $n$. You are also given a string $s$ of length $n$, consisting only of the character ?.\n\nFor each $i$ from $1$ to $n$:\n\n- Define $l_i$ as the largest index $j < i$ such that $p_j > p_i$. If there is no such index, $l_i := i$.\n- Define $r_i$ as the smallest index $j > i$ such that $p_j > p_i$. If there is no such index, $r_i := i$.\n\nInitially, you have an undirected graph with $n$ vertices (numbered from $1$ to $n$) and no edges. Then, for each $i$ from $1$ to $n$, add one edge to the graph:\n\n- If $s_i =$ L, add the edge $(i, l_i)$ to the graph.\n- If $s_i =$ R, add the edge $(i, r_i)$ to the graph.\n- If $s_i =$ ?, either add the edge $(i, l_i)$ or the edge $(i, r_i)$ to the graph at your choice.\n\nFind the maximum possible diameter$^{\\text{∗}}$ over all \\textbf{connected} graphs that you can form. Output $-1$ if it is not possible to form any connected graphs.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ Let $d(s, t)$ denote the smallest number of edges on any path between $s$ and $t$.\n\nThe diameter of the graph is defined as the maximum value of $d(s, t)$ over all pairs of vertices $s$ and $t$.\n\\end{footnotesize}",
    "tutorial": "Meow? (Waiting for something to happen?) Consider that the edges are directed from $i \\to l_i$ or $i \\to r_i$ respectively. So that edges point from vertices with smaller values to vertices with larger values. That is $a \\to b$ implies that $p_a < p_b$. Notice that by definition, every vertex must have only $1$ edge that is going out of it. Therefore, if we consider the diameter to be something like $v_1 \\to v_2 \\to v_3 \\to \\ldots \\to v_k \\leftarrow \\ldots \\leftarrow v_{d-1} \\leftarrow v_{d}$, since it is impossible for there to be some $\\leftarrow v_i \\to$ since each vertex has exactly one edge going out of it. Therefore, it makes that we can split the path into 2 distinct parts: - $v_1 \\to v_2 \\to v_3 \\to \\ldots \\to v_k$ - $v_d \\to v_{d-1} \\to \\ldots \\to v_{k}$ I claim that I can choose some $m$ such that the path $v_1 \\to v_2 \\to v_3 \\to \\ldots \\to v_{k-1}$ and $v_d \\to v_{d-1} \\to \\ldots \\to v_{k+1}$ are in the range $[1,m]$ and $[m+1,n]$ or vice versa. That we are able to cut the array into half and each path will stay on their side. The red line shown above is the cutting line, as described. Proof is at the bottom under Proof 1 for completeness. Now, we want to use this idea to make a meet in the middle solutions where we merge max stacks from both sides. Specifically: - maintain a max stack of elements as we are sweeping from $i=1\\ldots n$. - for each element on the max stack, maintain the maximum size of a path that is rooted on that element. Here is an example with $p=[4,1,5,3,2,6]$ $i=1$: $s=[(4,1)]$ $i=2$: $s=[(4,2),(1,1)]$ $i=3$: $s=[(5,3)]$ $i=4$: $s=[(5,3),(3,1)]$ $i=5$: $s=[(5,3),(3,2),(2,1)]$ $i=6$: $s=[(6,4)]$ When we insert a new element $x$, we pop all $(p_i,val)$ with $p_i < p_x$ and add in $(x,\\max(val)+1)$ into the stack. Now, all elements of the stack has to updated with $s_{i,1} := \\max(s_{i,1},s_{i+1,1}+1)$, which is really updating a suffix of $s_{*,1}$ with $val+k,\\ldots,val+1,val$. Firstly, it is clear that the $2$ vertices we merge, should have the biggest $p_i$ value, since a bigger $p_i$ value implies a bigger path size. What we care about is the biggest path size possible only using vertices on $[1,i]$, which we denote array $best$. In the above example, $best = [1,2,3,3,4]$. We really only care about obtaining the array $best$ and not $s$. We can find this array in $O(n \\log n)$ using segment trees or even in $O(n)$. However, we cannot directly take the biggest values on each side. Consider $p=[2,1\\mid,3,4]$. On the left and right side, the max stacks are $[2,1]$ and $[4,3]$ respectively, but we cannot connect $2$ with $4$ since the $3$ is blocking the $2$. Suppose $a_1,a_2,\\ldots,a_s$ are the prefix maximums while $b_1,b_2,\\ldots,b_t$ are the suffix maximums. Then, if the dividing line is at $a_i \\leq m < a_{i+1}$, we will merge $a_i$ on the left side with $a_{i+1}$ on the right side. Similarly, if the dividing line is at $b_i \\leq m < b_{i+1}$, we will merge $b_i$ on the left side with $b_{i+1}$ on the right side. So, if $a_i \\leq m < a_{i+1}$, it is equivalent to merging the best path on $[1,m]$ and $(m,a_{i+1})$ since then $a_{i+1}$ will be the root of the best path on the right side. It is similar for $b_i \\leq m < b_{i+1}$. Actually, we can prove that instead of $(m,a_{i+1})$, $(m,a_{i})$ is enough, and the proof is left as an exercise. The total complexity becomes $O(n \\log n)$ or $O(n)$ depending on how quickly array $best$ is found for subarrays. Suppose that there are 2 paths $a_1 \\to a_2 \\to \\ldots \\to a_s$ and $b_1 \\to b_2 \\to \\ldots \\to b_t$, $a_1 < b_1$, and $a_s = b_t$ but they do not intersect at any vertices other vertices. Then we will prove that there is no such case where $a_s' > b_t'$. Suppose that it is true that we can find some $a_{s'} > b_{t'}$. Let $(s',t')$ be the minimum counterexample so that $a_{s'} > b_{t'}$ but $a_{s'-1}<b_{t}$. Therefore, we have $a_{s'-1} < b_t < a_{s'}$. By definition, that $r_{a_{s'-1}} = a_{s'}$, we have $p_{b_t} < p_{a_{s'-1}}$. Then, $a_s$ cannot be in between $a_{s'-1}$ and $a_{s'}$ or else $r_{a_{s'-1}} = a_{s} \\neq a_{s'}$. But, then we need to find a path from $b_{t'}$ to $b_{t}=a_{s}$ which does not touch either $a_{s'-1}$ or $a_{s'}$ which is impossible.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ii pair<int,int>\n#define fi first\n#define se second\n\n#define pub push_back\n#define pob pop_back\n\n#define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))\n#define sz(x) (int)(x).size()\n\nint n;\nint arr[400005];\nstring s;\n\nint ans[2][400005];\nint t[400005];\nvector<int> stk[2];\n\nvector<ii> process(int l,int r,int val[]){\n\tvector<ii> v;\n\tint curr=0;\n\t\n\trep(x,l,r+1){\n\t\tii res={x,0};\n\t\twhile (!v.empty() && arr[v.back().fi]<arr[x]){\n\t\t\tint t=v.back().se; v.pob();\n\t\t\tif (!v.empty()) v.back().se=max(v.back().se,t+1);\n\t\t\tres.se=max(res.se,t+1);\n\t\t}\n\t\tv.pub(res);\n\t\t\n\t\tcurr=max(curr,res.se+sz(v));\n\t\tval[x]=curr;\n\t}\n\t\n\treturn v;\n}\n\nsigned main(){\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tcout.tie(0);\n\tcin.exceptions(ios::badbit | ios::failbit);\n\t\n\tint TC;\n\tcin>>TC;\n\twhile (TC--){\n\t\tcin>>n;\n\t\trep(x,1,n+1) cin>>arr[x];\n\t\tcin>>s;\n\t\t\n\t\trep(z,0,2){\n\t\t\tauto v=process(1,n,ans[z]);\n\t\t\tstk[z].clear();\n\t\t\tfor (auto [a,b]:v) stk[z].pub(a);\n\t\t\treverse(arr+1,arr+n+1);\n\t\t}\n\t\t\n\t\tint mx=ans[0][stk[0][0]]+ans[1][n-stk[0][0]+1]-1;\n\t\t\n\t\trep(z,0,2){\n\t\t\trep(x,0,sz(stk[z])-1){\n\t\t\t\tprocess(stk[z][x],stk[z][x+1],t);\n\t\t\t\trep(y,stk[z][x],stk[z][x+1]) mx=max(mx,t[y]+ans[z^1][n-y]);\n\t\t\t}\n\t\t\t\n\t\t\treverse(arr+1,arr+n+1);\n\t\t}\n\t\t\n\t\tcout<<mx-1<<endl;\n\t}\n}",
    "tags": [
      "divide and conquer",
      "dp",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1987",
    "index": "G2",
    "title": "Spinning Round (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference between the two versions are the allowed characters in $s$. You can make hacks only if both versions of the problem are solved.}\n\nYou are given a permutation $p$ of length $n$. You are also given a string $s$ of length $n$, where each character is either L, R, or ?.\n\nFor each $i$ from $1$ to $n$:\n\n- Define $l_i$ as the largest index $j < i$ such that $p_j > p_i$. If there is no such index, $l_i := i$.\n- Define $r_i$ as the smallest index $j > i$ such that $p_j > p_i$. If there is no such index, $r_i := i$.\n\nInitially, you have an undirected graph with $n$ vertices (numbered from $1$ to $n$) and no edges. Then, for each $i$ from $1$ to $n$, add one edge to the graph:\n\n- If $s_i =$ L, add the edge $(i, l_i)$ to the graph.\n- If $s_i =$ R, add the edge $(i, r_i)$ to the graph.\n- If $s_i =$ ?, either add the edge $(i, l_i)$ or the edge $(i, r_i)$ to the graph at your choice.\n\nFind the maximum possible diameter over all \\textbf{connected}$^{\\text{∗}}$ graphs that you can form. Output $-1$ if it is not possible to form any connected graphs.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ Let $d(s, t)$ denote the smallest number of edges on any path between $s$ and $t$.\n\nThe diameter of the graph is defined as the maximum value of $d(s, t)$ over all pairs of vertices $s$ and $t$.\n\\end{footnotesize}",
    "tutorial": "For simplicity, let $p_0 = p_{n+1} = +\\infty$, and let's recalculate the values of $l_i$ and $r_i$. Then, the answer is not $-1$ if for all $1 \\le i \\le n$ and $p_i < n$: $s_i =~$L $\\implies l_i \\ge 1$. $s_i =~$R $\\implies r_i \\le n$. $s_i =~$? $\\implies l_i \\ge 1$ or $r_i \\le n$. Let $dp[tl][tr]$ store some set of pairs $(a, b)$, where for some valid graph: $a$ is a possible depth of a path that starts at index $tl$ and passes only through indices $tl \\le i \\le tr$. $b$ is a possible depth of a path that starts at index $tr$ and passes only through indices $tl \\le i \\le tr$. The paths do not intersect. Let's iterate over all $i$ in order of increasing $p_i$. For each $i$ ($tl = l_i$ and $tr = r_i$), we will iterate over all pairs $(d_1, d_2)$ in $dp[tl][i]$ and $(e_1, e_2)$ in $dp[i][tr]$: If $s_i \\neq$ R and $tl \\ge 1$, we can add the edge $(tl, i)$, so: Update the answer with $\\max(ans, d_1 + 1 + \\max(d_2, e_1))$. Add the pairs $(d_1, e_2)$, $(d_2 + 1, e_2)$, and $(e_1 + 1, e_2)$ to $dp[tl][tr]$. Update the answer with $\\max(ans, d_1 + 1 + \\max(d_2, e_1))$. Add the pairs $(d_1, e_2)$, $(d_2 + 1, e_2)$, and $(e_1 + 1, e_2)$ to $dp[tl][tr]$. If $s_i \\neq$ L and $tr \\le n$, we can add the edge $(i, tr)$, so: Update the answer with $\\max(ans, \\max(d_2, e_1) + 1 + e_2)$. Add the pairs $(d_1, d_2 + 1)$, $(d_1, e_1 + 1)$, and $(d_1, e_2)$ to $dp[tl][tr]$. Update the answer with $\\max(ans, \\max(d_2, e_1) + 1 + e_2)$. Add the pairs $(d_1, d_2 + 1)$, $(d_1, e_1 + 1)$, and $(d_1, e_2)$ to $dp[tl][tr]$. Turns out, it is enough to store at most three pairs for each $dp[tl][tr]$. Specifically, it is enough to store: One pair with the maximum possible $a$. One pair with the maximum possible $b$. One pair with the maximum possible $a + b$. If true, this leads to an $\\mathcal{O}(n)$ or $\\mathcal{O}(n \\log n)$ solution, albeit with a large constant factor. Proof We will proceed with a proof by induction. Hypothesis: it is enough to store the three pairs described above. Base case: for $i$ with $l_i = i - 1$ and $r_i = i + 1$, only the pairs $(0, 0)$, $(1, 0)$ and $(0, 1)$ are possible. Induction step: For some $i$, let $dp[tl][i]$ and $dp[i][tr]$ only store the three pairs described above. First of all, we update the answer with the same value: When adding the left edge: If the answer came from $d_1 + 1 + d_2$, we maximize $d_1 + d_2$. If the answer came from $d_1 + 1 + e_1$, we maximize $d_1$ and $e_1$. If the answer came from $d_1 + 1 + d_2$, we maximize $d_1 + d_2$. If the answer came from $d_1 + 1 + e_1$, we maximize $d_1$ and $e_1$. When adding the right edge: If the answer came from $d_2 + 1 + e_2$, we maximize $d_2$ and $e_2$. If the answer came from $e_1 + 1 + e_2$, we maximize $e_1 + e_2$. If the answer came from $d_2 + 1 + e_2$, we maximize $d_2$ and $e_2$. If the answer came from $e_1 + 1 + e_2$, we maximize $e_1 + e_2$. Secondly, $dp[tl][tr]$ will store the pairs with the same values of $\\max a$, $\\max b$, and $\\max (a + b)$; as in the case when all pairs are stored on all previous stages: When adding the left edge, it is clearly not less optimal to add only the pair $(\\max(d_1, d_2 + 1, e_1 + 1), e_2)$: When maximizing $a$, we maximize $\\max(d_1, d_2 + 1, e_1 + 1)$, which we do by maximizing $d_1$, $d_2$, or $e_1$. When maximizing $b$, we maximize $e_2$. When maximizing $a + b$, we maximize $d_1 + e_2$, $d_2 + e_2$, or $e_1 + e_2$, which we do by induction. When maximizing $a$, we maximize $\\max(d_1, d_2 + 1, e_1 + 1)$, which we do by maximizing $d_1$, $d_2$, or $e_1$. When maximizing $b$, we maximize $e_2$. When maximizing $a + b$, we maximize $d_1 + e_2$, $d_2 + e_2$, or $e_1 + e_2$, which we do by induction. When adding the right edge, we can only add the pair $(d_1, \\max(d_2 + 1, e_1 + 1, e_2))$: When maximizing $a$, we maximize $d_1$. When maximizing $b$, we maximize $\\max(d_2 + 1, e_1 + 1, e_2)$, which we do by maximizing $d_2$, $e_1$, or $e_2$. When maximizing $a + b$, we maximize $d_1 + d_2$, $d_1 + e_1$, or $d_1 + e_2$, which we do by induction. When maximizing $a$, we maximize $d_1$. When maximizing $b$, we maximize $\\max(d_2 + 1, e_1 + 1, e_2)$, which we do by maximizing $d_2$, $e_1$, or $e_2$. When maximizing $a + b$, we maximize $d_1 + d_2$, $d_1 + e_1$, or $d_1 + e_2$, which we do by induction. Thus, we achieve the same answer by only storing these pairs, which concludes our proof. Complexity: $\\mathcal{O}(n)$ or $\\mathcal{O}(n \\log n)$ Note: there are a number of other possible solutions, please refer to the comments below.",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\narray<vector<int>, 2> get_l_and_r(vector<int> &p) {\n    int n = p.size();\n    \n    vector<int> l(n), r(n);\n    \n    stack<int> s;\n    for (int i = 0; i < n; i++) {\n        while (!s.empty() && p[s.top()] < p[i]) s.pop();\n        \n        if (s.empty()) l[i] = -1;\n        else l[i] = s.top();\n        \n        s.push(i);\n    }\n    \n    s = {};\n    for (int i = n - 1; i >= 0; i--) {\n        while (!s.empty() && p[s.top()] < p[i]) s.pop();\n        \n        if (s.empty()) r[i] = n;\n        else r[i] = s.top();\n        \n        s.push(i);\n    }\n    \n    return {l, r};\n}\n\nint ans_l_edge(array<int, 2> d, array<int, 2> e) {\n    return d[0] + 1 + max(d[1], e[0]);\n}\n\nint ans_r_edge(array<int, 2> d, array<int, 2> e) {\n    return e[1] + 1 + max(d[1], e[0]);\n}\n\narray<int, 2> add_l_edge(array<int, 2> d, array<int, 2> e) {\n    return {max({d[0], d[1] + 1, e[0] + 1}), e[1]};\n}\n\narray<int, 2> add_r_edge(array<int, 2> d, array<int, 2> e) {\n    return {d[0], max({d[1] + 1, e[0] + 1, e[1]})};\n}\n\nvector<array<int, 2>> process_dp(vector<array<int, 2>> &dp) {\n    array<int, 2> max_a = {-1, -1}, max_b = {-1, -1}, max_s = {-1, -1};\n    \n    for (auto [a, b]: dp) {\n        if (a > max_a[0] || (a == max_a[0] && b > max_a[1])) {\n            max_a = {a, b};\n        }\n        \n        if (b > max_b[1] || (b == max_b[1] && a > max_b[0])) {\n            max_b = {a, b};\n        }\n        \n        if (a + b > max_s[0] + max_s[1]) {\n            max_s = {a, b};\n        }\n    }\n    \n    return {max_a, max_b, max_s};\n}\n\nvoid add_to_map(map<array<int, 2>, int> &dp_ind, int &len_dp, array<int, 2> a) {\n    if (!dp_ind.count(a)) {\n        dp_ind[a] = len_dp++;\n    }\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    vector<int> p(n);\n    for (int i = 0; i < n; i++) cin >> p[i];\n    \n    string s;\n    cin >> s;\n    \n    auto [l, r] = get_l_and_r(p);\n    \n    for (int i = 0; i < n; i++) {\n        if (p[i] == n) continue;\n        \n        if (l[i] == -1 && s[i] == 'L') {\n            cout << -1 << nl;\n            return;\n        }\n        \n        if (r[i] == n && s[i] == 'R') {\n            cout << -1 << nl;\n            return;\n        }\n    }\n    \n    int ans = 0;\n    \n    vector<int> q(n + 1);\n    for (int i = 0; i < n; i++) {\n        q[p[i]] = i;\n    }\n    \n    int len_dp = 0;\n    map<array<int, 2>, int> dp_ind;\n    \n    for (int x = 1; x <= n; x++) {\n        int i = q[x];\n        int tl = l[i], tr = r[i];\n        \n        add_to_map(dp_ind, len_dp, {tl, i});\n        add_to_map(dp_ind, len_dp, {i, tr});\n        add_to_map(dp_ind, len_dp, {tl, tr});\n    }\n    \n    vector<vector<array<int, 2>>> dp(len_dp, {{0, 0}});\n    for (int x = 1; x <= n; x++) {\n        int i = q[x];\n        int tl = l[i], tr = r[i];\n        \n        int ind_l = dp_ind[{tl, i}];\n        int ind_r = dp_ind[{i, tr}];\n        int ind_c = dp_ind[{tl, tr}];\n        \n        for (auto const &d: dp[ind_l]) {\n            for (auto const &e: dp[ind_r]) {\n                ans = max(ans, d[1] + e[0]);\n                \n                if (tl >= 0 && s[i] != 'R') {\n                    ans = max(ans, ans_l_edge(d, e));\n                    dp[ind_c].push_back(add_l_edge(d, e));\n                }\n                \n                if (tr <= n - 1 && s[i] != 'L') {\n                    ans = max(ans, ans_r_edge(d, e));\n                    dp[ind_c].push_back(add_r_edge(d, e));\n                }\n            }\n        }\n        \n        dp[ind_c] = process_dp(dp[ind_c]);\n    }\n    \n    cout << ans << nl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "divide and conquer",
      "dp",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1987",
    "index": "H",
    "title": "Fumo Temple",
    "statement": "\\begin{quote}\nThis temple only magnifies the mountain's power.\n\\hfill Badeline\n\\end{quote}\n\nThis is an interactive problem.\n\nYou are given two positive integers $n$ and $m$ ($\\bf{n \\le m}$).\n\nThe jury has hidden from you a rectangular matrix $a$ with $n$ rows and $m$ columns, where $a_{i,j} \\in \\{ -1, 0, 1 \\}$ for all $1 \\le i \\le n$ and $1 \\le j \\le m$. The jury has also selected a cell $(i_0, j_0)$. Your goal is to find $(i_0,j_0)$.\n\nIn one query, you give a cell $(i, j)$, then the jury will reply with an integer.\n\n- If $(i, j) = (i_0, j_0)$, the jury will reply with $0$.\n- Else, let $S$ be the sum of $a_{x,y}$ over all $x$ and $y$ such that $\\min(i, i_0) \\le x \\le \\max(i, i_0)$ and $\\min(j, j_0) \\le y \\le \\max(j, j_0)$. Then, the jury will reply with $|i - i_0| + |j - j_0| + |S|$.\n\nFind $(i_0, j_0)$ by making at most $n + 225$ queries.\n\n\\textbf{Note: the grader is not adaptive}: $a$ and $(i_0,j_0)$ are fixed before any queries are made.",
    "tutorial": "In this solution, we will assume that there is no matrix $a$ and the interactor just returns some number $x$ between $di + dj \\le x \\le di + dj + (di + 1)(dj + 1)$, where $di = |i - i_0|$ and $dj = |j - j_0|$. Let's first solve for $n = 1$. Let the hidden cell be $(1, j_0)$. Let $l = 1$ and $r = m$. On each iteration, we will query the cell $(1, l)$, let the result be $x$. If $x = 0$, we are done. Else, we know that $j_0 - l \\le x \\le j_0 - l + (j_0 - l + 1)$. Transforming, we get $\\max(l + 1, \\frac{x-1}{2} + l) \\le j_0 \\le \\min(r, x + l)$. So, on each iteration, we at least half the length of $[l; r]$, so we use at most $\\lceil \\log_2(m) \\rceil$ queries. This allows us to solve the problem in $n \\cdot \\lceil \\log_2(m) \\rceil$ queries, if for each row we assume that the hidden cell is in it and then run the algorithm above. We will solve the problem recursively, ensuring $n \\le m$. If $m \\le A$ (we will choose $A$ later), we can solve the problem for the remaining rows in $A \\cdot \\lceil \\log_2(A) \\rceil$ queries. Else, our objective is to either decrease $m$ by a lot, or decrease $n$ by a bit and recurse further. To do that, we will query the three cells $(2, \\frac{3m}{16}), (2, \\frac{m}{2}), (2, \\frac{13m}{16})$ (choose integer coordinates + things should be pretty symmetrical). This ensures that for large enough $m$, if we get a large query result $> B$ ($B$ is around $\\frac{3m}{4}$), we will know that $i_0 \\ge 4$ must hold, and so we will recurse with $n_{new} = n - 3$ and $m_{new} = m$. If not, we will recurse to $n_{new} \\le m_{new} \\le B$ ($n_{new} \\le m_{new}$ since we query on the edge of the matrix). For the model solution below, we take at most $63$ queries to get to $m \\le A = 25$, so we solve the problem in at most $n + 3 \\cdot 21 + 25 \\cdot \\lceil \\log_2(25) \\rceil = n + 188 \\le n + 225$ queries. You can get a slightly better constant factor with this solution, or you can even reduce $n$ by a rate of quicker than $1$ per $1$ query. Complexity: $\\mathcal{O}(nm)$",
    "code": "#include <bits/stdc++.h>\n\n#define all(x) (x).begin(), (x).end()\n#define allr(x) (x).rbegin(), (x).rend()\n\nconst char nl = '\\n';\ntypedef long long ll;\ntypedef long double ld;\n\nusing namespace std;\n\nint ans_x = 0, ans_y = 0, cnt_q = 0;\n// Coordinates are flipped\nint query(int x, int y) {\n    cnt_q++;\n\n    int res = 0;\n    cout << \"? \" << y << ' ' << x << endl;\n    cout.flush();\n    \n    cin >> res;\n    \n    if (res < 0) {\n        exit(0);\n    }\n    \n    if (res == 0) {\n        ans_x = x;\n        ans_y = y;\n    }\n    \n    return res;\n}\n\n/* Explanation:\n * Splits the stripe of three into |a-O-a-b-O-b-a-O-a|.\n * O are the three query points (all in the same column). \n * Cons: hard to correctly account for errors in a non-bruteforce way.\n * Pros: gives a better constant factor (3 / 4 of the original length)\n * Number of queries: n + 3 * 21 + 25 * ceil(log(25, 2)) + eps \n * Though the binary search part uses less queries than that */\n\nvoid f(int lx, int rx, int ly, int ry) {\n    int n = rx - lx + 1;\n    \n    // Bruteforce base case (uses binary search)\n    if (n <= 25) { // can be n <= 22 or above\n        for (int x = lx; x <= rx; x++) {\n            int lb = ly, ub = ry;\n            \n            while (lb <= ub) {\n                int res = query(x, lb);\n                \n                int low_y = ((res - 1) + 1) / 2, high_y = res;\n                \n                int new_lb = lb + max(1, low_y), new_ub = min(ub, lb + high_y);\n                lb = new_lb;\n                ub = new_ub;\n            }\n        }\n        \n        return;\n    }\n    \n    \n    // Here, (2a - 1) + (2b - 1) + (2a - 1) = n\n    int a = 3 * (n + 3) / 16;\n    int y = min(ry, ly + 1);\n    \n    int x1 = lx + a - 1;\n    x1 = max(x1, lx);\n    x1 = min(x1, rx);\n    \n    int x2 = (lx + rx) / 2;\n    x2 = max(x2, x1 + 1);\n    x2 = min(x2, rx);\n    \n    int x3 = rx - a + 1;\n    x3 = max(x3, x2 + 1);\n    x3 = min(x3, rx);\n\n\n    int m = min(3, ry - ly + 1);\n    vector<vector<bool>> good(n, vector<bool> (m, true));\n    \n    int new_lx = lx, new_rx = rx;\n    int new_ly = ly, new_ry = ry;\n    \n    for (int x: {x1, x2, x3}) {\n        int res = query(x, y);\n        \n        new_lx = max(new_lx, x - res);\n        new_rx = min(new_rx, x + res);\n        \n        new_ly = max(new_ly, y - res);\n        new_ry = min(new_ry, y + res);\n        \n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                int r_x = lx + i, r_y = ly + j;\n                \n                int dx = abs(r_x - x);\n                int dy = abs(r_y - y);\n                \n                int d = dx + dy;\n                int S = (dx + 1) * (dy + 1);\n                \n                // d <= res <= d + S must hold\n                if (res < d || d + S < res) {\n                    good[i][j] = false;\n                }\n            }\n        }\n    }\n    \n    bool has_good = false;\n    for (auto vx: good) {\n        for (auto vy: vx) {\n            if (vy) {\n                has_good = true;\n            }\n        }\n    }\n    good.clear();\n    good.shrink_to_fit();\n    \n    if (has_good) {\n        f(new_lx, new_rx, new_ly, new_ry);\n    } else {\n        f(lx, rx, ly + m, ry);\n    }\n}\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    ans_x = 0; ans_y = 0; cnt_q = 0;\n    \n    f(1, m, 1, n);\n    \n    cout << \"! \" << ans_y << ' ' << ans_x << endl;\n    cout.flush();\n    \n    cerr << n << ' ' << cnt_q << \" | \" << n + 225 << endl;\n}\n\nint main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n    \n    int T;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "interactive"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1988",
    "index": "A",
    "title": "Split the Multiset",
    "statement": "A multiset is a set of numbers in which there can be equal elements, and the order of the numbers does not matter. For example, $\\{2,2,4\\}$ is a multiset.\n\nYou have a multiset $S$. Initially, the multiset contains only one positive integer $n$. That is, $S=\\{n\\}$. Additionally, there is a given positive integer $k$.\n\nIn one operation, you can select any positive integer $u$ in $S$ and remove one copy of $u$ from $S$. Then, insert no more than $k$ positive integers into $S$ so that the sum of all inserted integers is equal to $u$.\n\nFind the minimum number of operations to make $S$ contain $n$ ones.",
    "tutorial": "The optimal sequence of operations is very simple. The optimal sequence of operations is adding $k-1$ 1-s into the set each time, at the same time decreasing $n$ by $k-1$. This implies that the answer is $\\lceil \\frac{n-1}{k-1}\\rceil$. I failed to find a Div2-A level proof. If you have a simpler proof please share it in the comments. Consider the number of elements that is $\\equiv 1\\pmod{(k-1)}$ in the set. The number of such elements increase by at most $k-1$ in each operation, and the aforementioned sequence of operation achieves the maximum increment. A simpler proof in the comments: consider the number of elements in the set. It increases by at most $k-1$ each time, and our construction reaches the maximum increment.",
    "code": "t = (int)(input())\nfor _ in range(t):\n    n, k = map(int, input().split())\n    print((n - 1 + k - 2) // (k - 1))",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1988",
    "index": "B",
    "title": "Make Majority",
    "statement": "You are given a sequence $[a_1,\\ldots,a_n]$ where each element $a_i$ is either $0$ or $1$. You can apply several (possibly zero) operations to the sequence. In each operation, you select two integers $1\\le l\\le r\\le |a|$ (where $|a|$ is the current length of $a$) and replace $[a_l,\\ldots,a_r]$ with a single element $x$, where $x$ is the majority of $[a_l,\\ldots,a_r]$.\n\nHere, the majority of a sequence consisting of $0$ and $1$ is defined as follows: suppose there are $c_0$ zeros and $c_1$ ones in the sequence, respectively.\n\n- If $c_0\\ge c_1$, the majority is $0$.\n- If $c_0<c_1$, the majority is $1$.\n\nFor example, suppose $a=[1,0,0,0,1,1]$. If we select $l=1,r=2$, the resulting sequence will be $[0,0,0,1,1]$. If we select $l=4,r=6$, the resulting sequence will be $[1,0,0,1]$.\n\nDetermine if you can make $a=[1]$ with a finite number of operations.",
    "tutorial": "\"Most sequences\" can be transformed into $[1]$. Conditions for a sequence to be un-transformable is stringent. Find several simple substrings that make the string transformable. We list some simple conditions for a string to be transformable: If 111 exists somewhere (as a substring) in the string, the string is always transformable. If 11 appears at least twice in the string, the string is always transformable. If the string both begins and ends with 1, it is always transformable. If the string begins or ends with 1 and 11 exists in the string, it is always transformable. These can be found by simulating the operation for short strings on paper. Contrarily, if a string does not meet any of the four items, it is always not transformable. This can be proved using induction (as an exercise). Observe that the number of 1 never increases in an operation. We can change a continuous segment of zeros into one zero. After that, it suffices to check that the number of occurences of 1 is larger than the number of occurences of 0.",
    "code": "t = (int)(input())\nfor _ in range(t):\n    n = (int)(input())\n    a = input()\n    ok = 0\n    if a.count(\"111\") >= 1:\n        ok = 1\n    if a.count(\"11\") >= 2:\n        ok = 1\n    if a.count(\"11\") >= 1 and (a[0] == \"1\" or a[-1] == \"1\"):\n        ok = 1\n    if a[0] == \"1\" and a[-1] == \"1\":\n        ok = 1\n    if ok:\n        print(\"Yes\")\n    else:\n        print(\"No\")",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "1988",
    "index": "C",
    "title": "Increasing Sequence with Fixed OR",
    "statement": "You are given a positive integer $n$. Find the \\textbf{longest} sequence of positive integers $a=[a_1,a_2,\\ldots,a_k]$ that satisfies the following conditions, and print the sequence:\n\n- $a_i\\le n$ for all $1\\le i\\le k$.\n- $a$ is strictly increasing. That is, $a_i>a_{i-1}$ for all $2\\le i\\le k$.\n- $a_i\\,|\\,a_{i-1}=n$ for all $2\\le i\\le k$, where $|$ denotes the bitwise OR operation.",
    "tutorial": "The answer is a simple construction. The maximum length for $2^k-1\\ (k>1)$ is $k+1$. It's obvious that the answer only depends on the popcount of $n$. Below, we assume $n=2^k-1$. If $k=1$, it is shown in the samples that the length is $1$. Otherwise, the maximum sequence length for $2^k-1$ is $k+1$. This can be achived by $a_i=n-2^{i-1}\\ (1\\le i\\le k),a_{k+1}=n$. Consider the value of $a_1$. Note that its $k$-th bit (indexed from $2^0$ to $2^{k-1}$) should be 0, otherwise we would not make use of the largest bit. Since $a_1$ and $a_2$'s OR is $n$, $a_2$'s $k$-th bit should be 1, and thus the construction of $a_2\\sim a_{k+1}$ boils down to the subproblem when $n=2^{k-1}-1$. This shows that $f(k)\\le f(k-1)+1$ where $k$ is the popcount of $n$ and $f(k)$ is the maximum sequence length. We know that $f(2)=3$, so $f(k)\\le k+1$ for all $k\\ge 2$.",
    "code": "t = (int)(input())\nfor _ in range(t):\n    n = (int)(input())\n    a = []\n    for i in range(62, -1, -1):\n        x = 1 << i\n        if ((x & n) == x) and (x != n):\n            a.append(n - x)\n    a.append(n)\n    print(len(a))\n    for i in a:\n        print(i, end=\" \")\n    print(\"\")",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1988",
    "index": "D",
    "title": "The Omnipotent Monster Killer",
    "statement": "You, the monster killer, want to kill a group of monsters. The monsters are on a tree with $n$ vertices. On vertex with number $i$ ($1\\le i\\le n$), there is a monster with $a_i$ attack points. You want to battle with monsters for $10^{100}$ rounds.\n\nIn each round, the following happens in order:\n\n- All living monsters attack you. Your health decreases by the sum of attack points of all living monsters.\n- You select some (possibly all or none) monsters and kill them. After being killed, the monster will not be able to do any attacks in the future.\n\nThere is a restriction: in one round, you cannot kill two monsters that are directly connected by an edge.\n\nIf you choose what monsters to attack optimally, what is the smallest health decrement you can have after all rounds?",
    "tutorial": "Formulate the problem. Some variables can't be large. Suppose monster $i$ is killed in round $b_i$. Then, the total health decrement is the sum of $a_i\\times b_i$. The \"independent set\" constraint means that for adjacent vertices, their $b$-s must be different. Observation: $b_i$ does not exceed $\\lfloor \\log_2 n\\rfloor+1$. In this problem, $b_i\\le 19$ always holds for at least one optimal $a_i$. Let the mex of a set be the smallest positive integer that does not appear in it. Note that in an optimal arrangement, $b_i=\\mathrm{mex}_{(j,i)\\in E} b_j$. Consider an vertex with the maximum $b$, equal to $u$. Root the tree at this vertex $x$. The vertices connected with $x$ should take all $b$-s from $1$ to $u-1$. Denote $f(u)$ as the minimum number of vertices to make this happen, we have $f(1)=1,\\ f(u)\\ge 1+\\sum_{1\\le i<u}f(i)\\to f(u)\\ge 2^{u-1}$ This ends the proof. By dp, we can find the answer in $O(n\\log n)$ or $O(n\\log^2 n)$, depending on whether you use prefix/suffix maximums to optimize the taking max part. Bonus: Find a counterexample for $b_i\\le 18$ when $n=300000$. (Pretest 2 is one case) Note that $b_x\\le \\deg x$. By carefully handing the dp transitions, we can achieve a $O(\\sum \\deg_x)=O(n)$ solution.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nint n;\nll a[300005], f[300005][24], smn[30];\nvector<int> g[300005];\nvoid dfs(int x, int fa) {\n\tfor (int i = 1; i <= 22; i++) f[x][i] = i * a[x];\n\tfor (int y : g[x]) {\n\t\tif (y == fa) continue;\n\t\tdfs(y, x);\n\t\tll tt = 8e18;\n\t\tsmn[23] = 8e18;\n\t\tfor (int i = 22; i >= 1; i--) {\n\t\t\tsmn[i] = min(smn[i + 1], f[y][i]);\n\t\t}\n\t\tfor (int i = 1; i <= 22; i++) {\n\t\t\tf[x][i] += min(tt, smn[i + 1]);\n\t\t\ttt = min(tt, f[y][i]);\n\t\t}\n\t}\n}\nvoid Solve() {\n\tcin >> n;\n\tfor (int i = 1; i <= n; i++) cin >> a[i];\n\tfor (int i = 1, x, y; i < n; i++) {\n\t\tcin >> x >> y;\n\t\tg[x].push_back(y), g[y].push_back(x);\n\t}\n\tdfs(1, 0);\n\tcout << *min_element(f[1] + 1, f[1] + 23) << '\\n';\n\tfor (int i = 1; i <= n; i++) {\n\t\tg[i].clear();\n\t\tmemset(f[i], 0, sizeof(f[i]));\n\t}\n}\nint main() {\n\tios::sync_with_stdio(0), cin.tie(0);\n\tint t;\n\tcin >> t;\n\twhile (t--) Solve();\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1988",
    "index": "E",
    "title": "Range Minimum Sum",
    "statement": "For an array $[a_1,a_2,\\ldots,a_n]$ of length $n$, define $f(a)$ as the sum of the minimum element over all subsegments. That is, $$f(a)=\\sum_{l=1}^n\\sum_{r=l}^n \\min_{l\\le i\\le r}a_i.$$\n\nA permutation is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. You are given a permutation $[a_1,a_2,\\ldots,a_n]$. For each $i$, solve the following problem independently:\n\n- Erase $a_i$ from $a$, concatenating the remaining parts, resulting in $b = [a_1,a_2,\\ldots,a_{i-1},\\;a_{i+1},\\ldots,a_{n}]$.\n- Calculate $f(b)$.",
    "tutorial": "Formulate the problem on a cartesian tree. Find a clever bruteforce. Calculate the time complexity carefully. Build the cartesian tree of $a$. Let $lc_x,rc_x$ respectively be $x$'s left and right children. Consider a vertex $x$. If we delete it, what would happen to the tree? Vertices that are on the outside of $x$'s subtree will not be affected. Vertices inside the subtree of $x$ will \"merge\". Actually, we can see that, only the right chain of $x$'s left child ($lc_x\\to rc_{lc_x}\\to rc_{rc_{lc_x}}\\to \\dots$) and the left chain of $x$'s right child will merge in a way like what we do in mergesort. Now, if we merge the chains by bruteforce (use sorting or std::merge), the time complexity is $O(n)$! It's easy to see that each vertex will only be considered $O(1)$ times.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\ntypedef pair<int, int> pr;\nint n, a[500005], st[500005], c[500005][2], top, sz[500005];\nll ans[500005], atv[500005], sum;\nvoid dfs1(int x) {\n\tsz[x] = 1;\n\tfor (int i = 0; i < 2; i++)\n\t\tif (c[x][i]) dfs1(c[x][i]), sz[x] += sz[c[x][i]];\n\tsum += (atv[x] = (sz[c[x][0]] + 1ll) * (sz[c[x][1]] + 1ll) * a[x]);\n}\nvoid dfs2(int x, ll dlt) {\n\tll val = sum - dlt - atv[x];\n\tvector<int> lr, rl;\n\tvector<pr> ve;\n\tint y = c[x][0];\n\twhile (y) lr.push_back(y), val -= atv[y], y = c[y][1];\n\ty = c[x][1];\n\twhile (y) rl.push_back(y), val -= atv[y], y = c[y][0];\n\t{\n\t\tint i = 0, j = 0;\n\t\twhile (i < lr.size() || j < rl.size()) {\n\t\t\tif (j >= rl.size() || (i < lr.size() && j < rl.size() && a[lr[i]] < a[rl[j]])) {\n\t\t\t\tve.push_back(pr(lr[i], 0));\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tve.push_back(pr(rl[j], 1));\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n\t}\n\t// cout << x << ' ' << val << '\\n';\n\tint cursz = 0;\n\tfor (int i = (int)ve.size() - 1; i >= 0; i--) {\n\t\tint p = ve[i].first, q = ve[i].second;\n\t\t// cout << \"I:\" << i << ' ' << cursz << '\\n';\n\t\tval += (cursz + 1ll) * (sz[c[p][q]] + 1ll) * a[p];\n\t\tcursz += sz[c[p][q]] + 1;\n\t}\n\tans[x] = val;\n\tfor (int i = 0; i < 2; i++)\n\t\tif (c[x][i]) dfs2(c[x][i], dlt + 1ll * (sz[c[x][i ^ 1]] + 1) * a[x]);\n}\nvoid Solve() {\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; i++) scanf(\"%d\", &a[i]);\n\tst[top = 0] = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\twhile (top && a[st[top]] > a[i]) top--;\n\t\tc[i][0] = c[st[top]][1], c[st[top]][1] = i;\n\t\tst[++top] = i;\n\t}\n\tint rt = st[1];\n\tsum = 0, dfs1(rt), dfs2(rt, 0);\n\tfor (int i = 1; i <= n; i++) cout << ans[i] << ' ';\n\tcout << '\\n';\n\tfor (int i = 0; i <= n; i++) c[i][0] = c[i][1] = 0;\n}\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--) Solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "divide and conquer",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1988",
    "index": "F",
    "title": "Heartbeat",
    "statement": "For an array $u_1, u_2, \\ldots, u_n$, define\n\n- a prefix maximum as an index $i$ such that $u_i>u_j$ for all $j<i$;\n- a suffix maximum as an index $i$ such that $u_i>u_j$ for all $j>i$;\n- an ascent as an index $i$ ($i>1$) such that $u_i>u_{i-1}$.\n\nYou are given three cost arrays: $[a_1, a_2, \\ldots, a_n]$, $[b_1, b_2, \\ldots, b_n]$, and $[c_0, c_1, \\ldots, c_{n-1}]$.\n\nDefine the cost of an array that has $x$ prefix maximums, $y$ suffix maximums, and $z$ ascents as $a_x\\cdot b_y\\cdot c_z$.\n\nLet the sum of costs of all permutations of $1,2,\\ldots,n$ be $f(n)$. Find $f(1)$, $f(2)$, ..., $f(n)$ modulo $998\\,244\\,353$.",
    "tutorial": "We can use dp to calculate the number of permutations of $1\\sim n$ with $i$ prefix maximums and $j$ ascents, $f(n,i,j)$: consider where 1 is inserted, we will have a $O(n^3)$ dp that finds $f(n,i,j)$ for all suitable $(n,i,j)$-s. For suffix maximums, (the number of permutations of $1\\sim n$ with $i$ prefix maximums and $j$ ascents, $g(n,i,j)$, we can just reverse some dimension of $f$). To calculate the answer, consider the position of $n$. Suppose it's $p$. The the answer is $\\sum_{p=1}^n\\sum_{i=0}^{p-1}\\sum_{j=0}^{n-p}\\sum_{x=0}^{p-1}\\sum_{y=0}^{n-p}f(p-1,i,x)g(n-p,j,y)\\binom{n-1}{p-1}a_{i+1}b_{j+1}c_{x+y+[p>1]}$ Let $u(x,y)=\\sum_{i}f(x,i,y)a_{i+1}$, $v(x,y)=\\sum_{z}g(x,i,y)b_{i+1}$ (both of these are calculated in $O(n^3)$), then the answer is $\\sum_{p=1}^n\\sum_{x=0}^{p-1}\\sum_{y=0}^{n-p}u(p-1,x)v(n-p,y)\\binom{n-1}{p-1}c_{x+y+[p>1]}$ By seeing $u$ and $v$ as 2D polynomials, this can be calculated with 2D FFT in $O(n^2\\log n)$. Of course! This problem can also be solved with modulo $10^9+7$ or on an algebraic structure where FFT is not easy, but interpolation can be successfully carried out. We still need to consider $u(p-1,*)$ and $v(n-p,*)$ as polynomials $\\sum_{i}u(p-1,i)x^i,\\sum_{i}v(n-p,i)x^i$. Instead of doing FFT, consider substitute $x$ with $0,1,\\dots,n+1$, and use interpolation to recover the final coefficients. Suppose we have a value of $x$. Then, calculating $u(p-1)$ and $v(n-p)$ takes $O(n^2)$ in total. For fixed $x$ and $n$, the answer for $n$ is (here, note how $x$ is multiplied) $\\sum_{p=1}^nu(p-1)v(n-p)\\binom{n-1}{p-1}x^{p>1}$ This also takes $O(n^2)$ in total. So, for each $x$, the calculation is $O(n^2)$. For each $n$, the naive implementation of interpolation runs in $O(n^2)$. After we recover the coefficients, we multiply it with $c$ and update the answer. So, the time complexity is $O(n^3)$. We are trying to iterate over $i,x,j,y$ and do $ans_{i+j}\\leftarrow f(i,x)g(j,y)h_{x+y}$. We can achieve this with two steps: first, iterate over $i,x,y$ and do $v_{i,y}\\leftarrow f(i,x)h_{x+y}$. Then, iterate over $i,j,y$ and do $ans_{i+j}\\leftarrow g(j,y)v_{i,y}$. This runs in $O(n^3)$, and does not need to calculate inverses, and thus can be carried out on any ring.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int mod = 998244353, N = 705;\nint n, a[N + 5], b[N + 5], c[N + 5], f[N + 5][N + 5], u[N + 5][N + 5], v[N + 5][N + 5],\n    C[N + 5][N + 5];\nint g[N + 5], h[N + 5], t[N + 5][N + 5], p[N + 5][N + 5], ny[N + 5], o[N + 5];\nvoid upd(int &x, int y) { x += y, (x >= mod && (x -= mod)); }\nint main() {\n\tcin >> n;\n\tfor (int i = 1; i <= n; i++) cin >> a[i];\n\tfor (int i = 1; i <= n; i++) cin >> b[i];\n\tfor (int i = 0; i < n; i++) cin >> c[i];\n\tf[0][0] = ny[1] = ny[0] = 1;\n\tfor (int i = 0; i <= n; i++) {\n\t\tC[i][0] = 1;\n\t\tfor (int j = 1; j <= i; j++) C[i][j] = (C[i &mdash; 1][j] + C[i &mdash; 1][j &mdash; 1]) % mod;\n\t}\n\tfor (int i = 2; i <= n; i++) ny[i] = 1ll * ny[mod % i] * (mod &mdash; mod / i) % mod;\n\tfor (int i = 2; i <= n; i++) ny[i] = 1ll * ny[i &mdash; 1] * ny[i] % mod;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = i; j >= 0; j--) {\n\t\t\tfor (int k = i; k >= 0; k--) {\n\t\t\t\tif (!f[j][k]) continue;\n\t\t\t\t// cout << i << ' ' << j << ' ' << k << ' ' << f[j][k] << '\\n';\n\t\t\t\tupd(u[i][k], 1ll * f[j][k] * a[j + 1] % mod);\n\t\t\t\tupd(v[i][k], 1ll * f[j][k] * b[j + 1] % mod);\n\t\t\t\tupd(f[j + 1][k + (i != 0)], f[j][k]);\n\t\t\t\tupd(f[j][k + 1], 1ll * f[j][k] * (i &mdash; (i != 0) &mdash; k) % mod);\n\t\t\t\tf[j][k] = 1ll * f[j][k] * (k + (i != 0)) % mod;\n\t\t\t}\n\t\t}\n\t\tif (i > 0) reverse(v[i], v[i] + i);\n\t}\n\tfor (int x = 1; x <= n; x++) {\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tg[i] = h[i] = 0;\n\t\t\tfor (int j = i; j >= 0; j--) {\n\t\t\t\tg[i] = (1ll * g[i] * x + u[i][j]) % mod;\n\t\t\t\th[i] = (1ll * h[i] * x + v[i][j]) % mod;\n\t\t\t}\n\t\t}\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfor (int j = 1; j <= i; j++) {\n\t\t\t\tupd(t[i][x], 1ll * g[j &mdash; 1] * h[i &mdash; j] % mod * C[i &mdash; 1][j &mdash; 1] % mod *\n\t\t\t\t                 (j > 1 ? x : 1) % mod);\n\t\t\t}\n\t\t}\n\t}\n\tp[0][0] = 1;\n\tfor (int i = 1; i <= n; i++) {\n\t\tfor (int j = 0; j < i; j++) p[i][j] = p[0][j], o[j] = 0;\n\t\tfor (int j = 0; j <= i; j++) {\n\t\t\tif (j != i) {\n\t\t\t\tfor (int k = i &mdash; 1; k >= 0; k--) {\n\t\t\t\t\tupd(p[j][k + 1], p[j][k]);\n\t\t\t\t\tp[j][k] = 1ll * p[j][k] * (mod &mdash; i) % mod;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!j) continue;\n\t\t\tint s = 1ll * t[i][j] * ny[j &mdash; 1] % mod * ny[i &mdash; j] % mod;\n\t\t\tif ((i &mdash; j) & 1) s = mod &mdash; s;\n\t\t\tfor (int k = 0; k < i; k++) {\n\t\t\t\tupd(o[k], 1ll * s * p[j][k] % mod);\n\t\t\t}\n\t\t}\n\t\tint ans = 0;\n\t\tfor (int k = 0; k < i; k++) {\n\t\t\tans = (ans + 1ll * o[k] * c[k]) % mod;\n\t\t}\n\t\tcout << ans << ' ';\n\t}\n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1989",
    "index": "A",
    "title": "Catch the Coin",
    "statement": "Monocarp visited a retro arcade club with arcade cabinets. There got curious about the \"Catch the Coin\" cabinet.\n\nThe game is pretty simple. The screen represents a coordinate grid such that:\n\n- the X-axis is directed from left to right;\n- the Y-axis is directed from bottom to top;\n- the center of the screen has coordinates $(0, 0)$.\n\nAt the beginning of the game, the character is located in the center, and $n$ coins appear on the screen — the $i$-th coin is at coordinates $(x_i, y_i)$. The coordinates of all coins are different and not equal to $(0, 0)$.\n\nIn one second, Monocarp can move the character in one of eight directions. If the character is at coordinates $(x, y)$, then it can end up at any of the coordinates $(x, y + 1)$, $(x + 1, y + 1)$, $(x + 1, y)$, $(x + 1, y - 1)$, $(x, y - 1)$, $(x - 1, y - 1)$, $(x - 1, y)$, $(x - 1, y + 1)$.\n\nIf the character ends up at the coordinates with a coin, then Monocarp collects that coin.\n\nAfter Monocarp makes a move, all coins fall down by $1$, that is, they move from $(x, y)$ to $(x, y - 1)$. You can assume that the game field is infinite in all directions.\n\nMonocarp wants to collect at least one coin, but cannot decide which coin to go for. Help him determine, for each coin, whether he can collect it.",
    "tutorial": "At first glance, it's not very convenient that the move consists of two parts: first the character moves, then the coin. Let's try to combine these steps. Since the coin moves down by $1$ each time, we can add this change in the $y$ coordinate to the change in the character's $y$ coordinate. That is, the character can now change its $y$ coordinate not by $-1, 0$, or $1$, but by $0, 1$, or $2$. And the coins will always be in their initial positions. Now it is easy to see that all coins with $y \\ge 0$ can be picked up. For example, you can first align with the coin in terms of the $x$ coordinate, and then move up to it. However, in the example, it can be seen that Monocarp can pick up the coin $(-2, -1)$. This happens because the move still consists of two parts. Since the character moves first, and then the coin, we can align with the $x$ coordinate again, and then have the time to move down to it. Thus, all coins with $y \\ge -1$ can be picked up. Overall complexity: $O(n)$.",
    "code": "for _ in range(int(input())):\n\tx, y = map(int, input().split())\n\tprint(\"YES\" if y >= -1 else \"NO\")",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1989",
    "index": "B",
    "title": "Substring and Subsequence",
    "statement": "You are given two strings $a$ and $b$, both consisting of lowercase Latin letters.\n\nA subsequence of a string is a string which can be obtained by removing several (possibly zero) characters from the original string. A substring of a string is a contiguous subsequence of that string.\n\nFor example, consider the string abac:\n\n- a, b, c, ab, aa, ac, ba, bc, aba, abc, aac, bac and abac are its subsequences;\n- a, b, c, ab, ba, ac, aba, bac and abac are its substrings.\n\nYour task is to calculate the minimum possible length of the string that contains $a$ as a substring and $b$ as a subsequence.",
    "tutorial": "Since the string $a$ is a substring of the answer, the answer can be represented as follows - $x + a + y$, where + denotes string concatenation, and $x$ and $y$ are some, possibly empty, strings. Now, we have to ensure that the string $x+a+y$ contains the string $b$ as a subsequence. Notice that to minimize the length of the answer, it is optimal to choose the strings $x$ and $y$ in such a way that $x$ is a prefix of $b$, and $y$ is a suffix of $b$. This means that we can represent the string $b$ as $x+c+y$. Then, in order for the entire string $x+c+y$ to be a subsequence of the answer $x+a+y$, the string $c$ must be a subsequence of the string $a$. Using the above facts, we can solve the problem as follows: iterate over the length of $x$, iterate over the length of $y$, and then check that the remaining part $c$ is a subsequence of the string $a$. If this is the case, update the answer with the value $|x| + |a| + |y|$. Unfortunately, this solution is too slow, but it can be easily optimized. Since we need to minimize the length of the answer, it is sufficient to iterate over the length of $x$, and consequently the position of the start of the string $c$, and then find the minimum possible length of $y$. To do this, greedily find how many of the following characters in the string $b$ will be a subsequence of the string $a$: we can go through the string $a$ from left to right, and if the current character of the string $a$ matches the next character in the string $b$ that we need, increase the number of found characters in the string $b$ by $1$. All the remaining characters in the string $b$ will form the string $y$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    string a, b;\n    cin >> a >> b;\n    int n = a.size(), m = b.size();\n    int ans = n + m;\n    for (int i = 0; i < m; ++i) {\n      int j = i;\n      for (auto c : a) {\n        if (j < m && c == b[j]) ++j;\n      }\n      ans = min(ans, n + m - (j - i));\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "greedy",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1989",
    "index": "C",
    "title": "Two Movies",
    "statement": "A movie company has released $2$ movies. These $2$ movies were watched by $n$ people. For each person, we know their attitude towards the first movie (liked it, neutral, or disliked it) and towards the second movie.\n\nIf a person is asked to leave a review for the movie, then:\n\n- if that person liked the movie, they will leave a positive review, and the movie's rating will increase by $1$;\n- if that person disliked the movie, they will leave a negative review, and the movie's rating will decrease by $1$;\n- otherwise, they will leave a neutral review, and the movie's rating will not change.\n\nEvery person will review exactly one movie — and for every person, you can choose which movie they will review.\n\nThe company's rating is the minimum of the ratings of the two movies. Your task is to calculate the maximum possible rating of the company.",
    "tutorial": "Let's notice an important fact: if $a_i \\ne b_i$, it is always optimal to choose a review for the movie with the better rating: taking the worse option doesn't increase the rating of any movie. Using this fact, let's calculate several values: $x$ - the rating of the first movie among people who liked the first movie more than the second one ($a_i > b_i$); $y$ - the rating of the second movie among people who liked the second movie more than the first one ($b_i > a_i$); $neg$ - the number of people who didn't like either movie; $pos$ - the number of people who liked both movies. Now we have to distribute the reviews of the viewers having $a_i=b_i$. To do this, we can iterate the contribution of such viewers to the rating of the first movie (denoted as $i$) from $-neg$ to $pos$. Then, the final rating of the first movie is $x+i$, and the final rating of the second movie is $y+(pos-neg-i)$. Among all the options, choose the one where the minimum of these two values is maximized.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n);\n    for (auto& x : a) cin >> x;\n    for (auto& x : b) cin >> x;\n    int x = 0, y = 0, neg = 0, pos = 0;\n    for (int i = 0; i < n; ++i) {\n      if (a[i] > b[i]) {\n        x += a[i];\n      } else if (a[i] < b[i]) {\n        y += b[i];\n      } else {\n        neg += (a[i] < 0);\n        pos += (a[i] > 0);\n      }\n    }\n    int ans = -1e9;\n    for (int i = -neg; i <= pos; ++i)\n      ans = max(ans, min(x + i, y + (pos - neg - i)));\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1989",
    "index": "D",
    "title": "Smithing Skill",
    "statement": "You are playing a famous computer game (that just works) where you have various skills you can level up. Today, you focused on the \"Smithing\" skill. Your tactic is obvious: forging weapons from ingots and then melting them back to return the materials partially. For simplicity, every time you create an item, you get $1$ experience point, and every time you melt an item, you also get $1$ experience point.\n\nThere are $n$ classes of weapons you can forge and $m$ types of metal ingots.\n\nYou can create one weapon of the $i$-th class, spending $a_i$ ingots of metal of the same type. Melting a weapon of the $i$-th class (which you crafted earlier) returns you $b_i$ ingots of the type of metal it was made of.\n\nYou have $c_j$ metal ingots of the $j$-th type, and you know that you can craft a weapon of any class from any metal type. Each combination of a weapon class and a metal type can be used any number of times.\n\nWhat is the maximum total amount of experience you can earn by crafting and melting weapons?",
    "tutorial": "It's quite obvious that we should melt every weapon we forge, and we can do it as soon as we forge it. So, let's do these actions in pairs: forge a weapon, then instantly melt it. Since you can't use two types of metal while forging one weapon, we can solve our task independently for each metal type. Suppose you have $x$ ingots of the chosen metal. You can act greedily: you can forge only weapons of classes with $a_i \\le x$, but among them, it's optimal to chose one that makes us lose the minimum number of ingots by forging it and melting it; so, we need to minimize the value of $a_i - b_i$. However, this greedy solution is too slow when implemented naively. Let's define $A = \\max{a_i}$ and look at two cases: $x \\le A$ or $x > A$. If $x \\le A$, let's just precalculate answers $\\mathrm{ans}[x]$ for all $x$ from $0$ to $A$. To do so, let's precalculate another value $\\mathrm{best}[x]$ as \"the minimum $a_i - b_i$ among all classes $i$ where $a_i \\le x$\". In other words, $\\mathrm{best}[x]$ will be equal to the minimum amount of ingots you'll lose if you have $x$ ingots, and you need to forge-melt one weapon. We can precalculate $\\mathrm{best}[x]$ in two steps: for each class $i$, we can set $\\mathrm{best}[a_i] = \\min{(\\mathrm{best}[a_i], a_i - b_i)}$; using approach similar to prefix minima or dynamic programming, we can also update $\\mathrm{best}[x] = \\min{(\\mathrm{best}[x], \\mathrm{best}[x - 1])}$ for all $x$ from $1$ to $A$. In case $x > A$, we can forge-melt a weapon with minimum $a_i - b_i$ as many times as we can until $x \\le A$. Once $x$ becomes less or equal to $A$, we can take the value $\\mathrm{ans}[x]$ and finish processing that metal type. Knowing that the minimum $a_i - b_i$ is just $\\mathrm{best}[A]$, we can reformulate our first step as finding minimum $k$ such that $x - k \\cdot \\mathrm{best}[A] \\le A$ or $k \\ge \\frac{x - A}{\\mathrm{best}[A]}$. In other words, we'll make the first step exactly $k = \\left\\lceil \\frac{x - A}{\\mathrm{best}[A]} \\right\\rceil$ times. So we can calculate the final answer as $2k + \\mathrm{ans}[x - k \\cdot \\mathrm{best}[A]]$. As a result, we run precalculating in $O(n + A)$ time and process each metal type in $O(1)$ time. The total complexity is $O(n + m + A)$ time and space.",
    "code": "fun main() {\n    val (n, m) = readln().split(\" \").map { it.toInt() }\n    val a = readln().split(\" \").map { it.toInt() }\n    val b = readln().split(\" \").map { it.toInt() }\n    val c = readln().split(\" \").map { it.toInt() }\n\n    val mx = a.maxOrNull()!! + 1\n\n    val best = IntArray(mx) { 1e9.toInt() }\n    val calc = IntArray(mx) { 0 }\n\n    for (i in a.indices)\n        best[a[i]] = minOf(best[a[i]], a[i] - b[i])\n    for (v in 1 until mx)\n        best[v] = minOf(best[v], best[v - 1])\n\n    for (v in 1 until mx)\n        if (v >= best[v])\n            calc[v] = 2 + calc[v - best[v]]\n\n    var ans = 0L\n    for (v in c) {\n        var cur = v\n        if (cur >= mx) {\n            val k = (cur - mx + 1 + best[mx - 1]) / best[mx - 1]\n            ans += 2L * k\n            cur -= k * best[mx - 1]\n        }\n        ans += calc[cur]\n    }\n    println(ans)\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1989",
    "index": "E",
    "title": "Distance to Different",
    "statement": "Consider an array $a$ of $n$ integers, where every element is from $1$ to $k$, and every integer from $1$ to $k$ appears \\textbf{at least once}.\n\nLet the array $b$ be constructed as follows: for the $i$-th element of $a$, $b_i$ is the distance to the closest element in $a$ which is not equal to $a_i$. In other words, $b_i = \\min \\limits_{j \\in [1, n], a_j \\ne a_i} |i - j|$.\n\nFor example, if $a = [1, 1, 2, 3, 3, 3, 3, 1]$, then $b = [2, 1, 1, 1, 2, 2, 1, 1]$.\n\nCalculate the number of different arrays $b$ you can obtain if you consider all possible arrays $a$, and print it modulo $998244353$.",
    "tutorial": "Consider a block of equal elements in $a$. If we split $a$ into such blocks, we can consider each block separately - for each element, we need only the distance to the closest border of the block (except for the first and the last block, where we consider only one border). It's quite easy to see that if the length of the block is even (let's say it's $2x$), then the distances for the elements in this block are $[1, 2, 3, \\dots, x-1, x, x, x-1, \\dots, 3, 2, 1]$. And if the length of the block is odd (let's say it's $2x-1$), the distances are $[1, 2, 3, \\dots, x-1, x, x-1, \\dots, 3, 2, 1]$. Now we don't need the actual values in $a$, we only need the information about the blocks of equal elements. We need at least $k$ blocks of equal elements in $a$, since if the number of blocks is less than $k$, it's impossible for the array $a$ to have $k$ different values (and if there are at least $k$ blocks, it's possible to assign each block a value so that every integer from $1$ to $k$ appears). So, it looks like we need to calculate the number of ways to split the array into at least $k$ blocks. However, this only works if there is a bijection between the ways to split the array and the resulting arrays $b$. Unfortunately, some ways to split the array might result in the same distance array: for example, the distance array $[1, 1, 1, 1]$ can be obtained either by splitting into four blocks of size $1$, or into three blocks, the middle of which has size $2$. So, if there is a block of size $2$, and it is not the first or the last block in the split, it can be replaced with two blocks of size $1$, and nothing changes (except for the number of blocks, which goes up). Thankfully, this is the only such situation we need to handle: any block longer than $2$ can be uniquely determined by the values in the middle of it (if there is a value $x$ which is greater than both its neighbors, it is the middle of a block of size $2x-1$; and if there is a pair of values $x$ which are greater than both the value to the left and the value to the right, it is the middle of a block of size $2x$). So, we need to count the number of ways to split the array of size $n$ into at least $k$ blocks so that only the first and the last block can have size $2$. This can be done with the following dynamic programming: let $dp_{i,j}$ be the number of ways to split the first $i$ elements into $j$ blocks. This looks like it works in $O(n^3)$, but we can use two improvements to speed this up: the values $j > k$ are treated identically to the values $j=k$, so we can limit the value of $j$ to $k$ and say that $dp_{i,j}$ is the number of ways to split the first $i$ elements into at least $j$ blocks if $j=k$; we can do transitions in $O(1)$ instead of $O(n)$ by using partial sums. Combining these two optimizations, we get a solution in $O(nk)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y)\n{\n \tx += y;\n \twhile(x >= MOD) x -= MOD;\n \twhile(x < 0) x += MOD;\n \treturn x;\n}\n\nint mul(int x, int y)\n{\n \treturn (x * 1ll * y) % MOD;\n}\n\nint main()\n{\n\tint n;\n\tcin >> n;\n\tint k;\n\tcin >> k;\n\tvector<vector<int>> dp(n + 1, vector<int>(k + 1));\n\tdp[0][0] = 1;\n\tvector<int> sum(k + 1);\n\tsum[0] = 1;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tfor(int j = 0; j <= k; j++)\n\t\t{\n\t\t\tint& d = dp[i + 1][min(j + 1, k)];\n\t\t \td = add(d, sum[j]);\n\t\t \tif(i >= 2 && i != n - 1)\n\t\t \t\td = add(d, -dp[i - 1][j]); \n\t\t}\n\t\tfor(int j = 0; j <= k; j++)\n\t\t\tsum[j] = add(sum[j], dp[i + 1][j]);\n\t}\n\tcout << dp[n][k] << endl;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1989",
    "index": "F",
    "title": "Simultaneous Coloring",
    "statement": "You are given a matrix, consisting of $n$ rows and $m$ columns.\n\nYou can perform two types of actions on it:\n\n- paint the entire column in blue;\n- paint the entire row in red.\n\n\\textbf{Note that you cannot choose which color to paint the row or column.}\n\nIn one second, you can perform either one action or multiple actions at the same time. If you perform one action, it will be free. If you perform $k > 1$ actions at the same time, it will cost $k^2$ coins. When multiple actions are performed at the same time, for each cell affected by actions of both types, the color can be chosen independently.\n\nYou are asked to process $q$ queries. Before each query, all cells become colorless. Initially, there are no restrictions on the color of any cells. In the $i$-th query, a restriction of the following form is added:\n\n- $x_i~y_i~c_i$ — the cell in row $x_i$ in column $y_i$ should be painted in color $c_i$.\n\nThus, after $i$ queries, there are $i$ restrictions on the required colors of the matrix cells. After each query, output the minimum cost of painting the matrix according to the restrictions.",
    "tutorial": "The main idea is as follows. Consider any constraint on a cell. If the cell must be red, then the last action on this cell must be coloring the row; otherwise, it should be the column. That is, if the operation is applied to both the row and the column of this cell, then there is a certain order of performing these operations. It is also worth noting that it does not make sense to apply the same operation twice, because the second application of the operation will recolor all the cells. The word \"order\" should immediately bring to mind thoughts of directed graphs and topological sorting. Let's try to build a graph of operation execution. Create a graph with $n + m$ vertices - one vertex for each row and column. If the cell must be red, then draw a directed edge from its column to its row. Otherwise, draw an edge from its row to its column. Now we would like to perform operations simply in the order of topological sorting. If this is possible (i.e., there are no cycles in the graph), then the answer is just $0$. This means that operations can always be applied one by one. It is also worth noting that we apply the operations that do not color any cells with constraints. Their cost is always $0$, so they do not change the answer. Otherwise, there are some strongly connected components in the graph with size greater than $1$. In these components, we will always have to perform some operations at the same time. Of course, operations can be applied to the entire component at once. The cost will then be equal to the square of the component's size. Doesn't sound optimal but that's one way to satisfy the constraints. Let's show that it is not possible to do it cheaper. Consider the last set of actions on this component. If they do not affect the entire component, then within the affected subset, there will be a vertex with an outgoing edge outside the subset, but inside the component (otherwise it would be two different components). This means that there must be at least one more operation performed on the vertex to which this edge leads. Therefore, the set of actions considered will not be the last one. Then the solution is as follows. After adding each constraint, add the previously described edges and find the condensation of the graph. The answer will be the sum of the squares of the sizes of strongly connected components with size greater than $1$. This solution works in $O(q \\cdot (n + m + q))$. To optimize this solution, you can use the technique of incremental condensation. You can read about it in the blog by Radewoosh. Since DSU is used in it, you can maintain the sum of the squares of the component sizes on the fly. The blog describes a solution with a logarithmic time complexity, but the problem did not require an implementation faster than $log^2$. Solutions with a logarithmic memory complexity with a large constant might not pass (the author's solution consumes $O(q \\log q)$ memory and fits into $50$ megabytes).",
    "code": "#include <bits/stdc++.h>\n\n#define forn(i, n) for (int i = 0; i < int(n); i++)\n\nusing namespace std;\n\nstruct edge{\n\tint v, u;\n};\n\nvector<vector<int>> g, tg;\nvector<int> ord;\nvector<char> used;\nvector<int> clr;\n\nvoid ts(int v){\n\tused[v] = true;\n\tfor (int u : g[v]) if (!used[u])\n\t\tts(u);\n\tord.push_back(v);\n}\n\nvoid dfs(int v, int k){\n\tclr[v] = k;\n\tfor (int u : tg[v]) if (clr[u] == -1)\n\t\tdfs(u, k);\n}\n\nvector<long long> rk, p;\nlong long sum;\nvector<long long*> where;\nvector<long long> val;\n\nlong long cost(int x){\n\treturn x == 1 ? 0ll : x * 1ll * x;\n}\n\nint getp(int a){\n\treturn a == p[a] ? a : getp(p[a]);\n}\n\nvoid unite(int a, int b){\n\ta = getp(a), b = getp(b);\n\tif (a == b) return;\n\tif (clr[a] != clr[b]) return;\n\tif (rk[a] < rk[b]) swap(a, b);\n\twhere.push_back(&sum);\n\tval.push_back(sum);\n\tsum -= cost(rk[a]);\n\tsum -= cost(rk[b]);\n\tsum += cost(rk[a] + rk[b]);\n\twhere.push_back(&rk[a]);\n\tval.push_back(rk[a]);\n\trk[a] += rk[b];\n\twhere.push_back(&p[b]);\n\tval.push_back(p[b]);\n\tp[b] = a;\n}\n\nvector<edge> e;\nvector<long long> ans;\n\nvoid calc(int l, int r, const vector<int> &cur){\n\tif (l == r - 1){\n\t\tans.push_back(sum);\n\t\treturn;\n\t}\n\tint m = (l + r) / 2;\n\tfor (int i : cur) if (i < m){\n\t\tint v = getp(e[i].v), u = getp(e[i].u);\n\t\tfor (int w : {v, u}) if (used[w]){\n\t\t\tg[w].clear();\n\t\t\ttg[w].clear();\n\t\t\tclr[w] = -1;\n\t\t\tused[w] = false;\n\t\t}\n\t\tg[v].push_back(u);\n\t\ttg[u].push_back(v);\n\t}\n\tord.clear();\n\tfor (int i : cur) if (i < m){\n\t\tfor (int v : {getp(e[i].v), getp(e[i].u)}) if (!used[v]){\n\t\t\tts(v);\n\t\t}\n\t}\n\treverse(ord.begin(), ord.end());\n\tint k = 0;\n\tfor (int v : ord) if (clr[v] == -1){\n\t\tdfs(v, k);\n\t\t++k;\n\t}\n\tint tim = val.size();\n\tfor (int i : cur) if (i < m) unite(e[i].v, e[i].u);\n\tvector<int> tol, tor;\n\tfor (int i : cur){\n\t\tif (i >= m)\n\t\t\ttor.push_back(i);\n\t\telse if (getp(e[i].v) == getp(e[i].u))\n\t\t\ttol.push_back(i);\n\t\telse\n\t\t\ttor.push_back(i);\n\t}\n\tcalc(m, r, tor);\n\twhile (int(val.size()) > tim){\n\t\t*where.back() = val.back();\n\t\twhere.pop_back();\n\t\tval.pop_back();\n\t}\n\tcalc(l, m, tol);\n}\n\nint main() {\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tint n, m, q;\n\tcin >> n >> m >> q;\n\te.resize(q);\n\tforn(i, q){\n\t\tint x, y;\n\t\tchar c;\n\t\tcin >> x >> y >> c;\n\t\t--x, --y;\n\t\tif (c == 'R')\n\t\t\te[i] = {y + n, x};\n\t\telse\n\t\t\te[i] = {x, y + n};\n\t}\n\trk.resize(n + m, 1);\n\tp.resize(n + m);\n\tiota(p.begin(), p.end(), 0);\n\tused.resize(n + m, 0);\n\tclr.resize(n + m, -1);\n\tg.resize(n + m);\n\ttg.resize(n + m);\n\tvector<int> cur(q);\n\tiota(cur.begin(), cur.end(), 0);\n\tcalc(0, q + 1, cur);\n\tans.pop_back();\n\treverse(ans.begin(), ans.end());\n\tfor (long long x : ans) cout << x << '\\n';\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "divide and conquer",
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "1990",
    "index": "A",
    "title": "Submission Bait",
    "statement": "Alice and Bob are playing a game in an array $a$ of size $n$.\n\nThey take turns to do operations, with Alice starting first. The player who can not operate will lose. At first, a variable $mx$ is set to $0$.\n\nIn one operation, a player can do:\n\n- Choose an index $i$ ($1 \\le i \\le n$) such that $a_{i} \\geq mx$ and set $mx$ to $a_{i}$. Then, set $a_{i}$ to $0$.\n\nDetermine whether Alice has a winning strategy.",
    "tutorial": "For Alice, what if choosing the maximum value doesn't work? Consider parity. Case $1$: When all values appear an even number of times, Alice will lose. This is because no matter which number Alice chooses, Bob can mimic Alice's move. Case $2$: When at least one value appears an odd number of times, Alice will win. Alice only needs to choose the maximum value that appears an odd number of times, which will force Bob into Case $1$. Time complexity: $O(n)$. Sort the array $a$ in non-increasing order. We can observe that any state can be represented as a prefix of the array $a$. Consider dynamic programming: let $dp_i$ denote whether the first player is guaranteed to win when the state is $a_{1...i}$ ($dp_i=1$ indicates a guaranteed win for the first player). We have the following formula: $dp_1=1$; $dp_1=1$; $dp_i= \\sim (dp_{i-1}$ & $dp_{id_1-1}$ & $dp_{id_2-1} \\ldots)$, where $id_j$ satisfies $a_{id_j} \\neq a_{id_j+1}$ and $id_j < i$. $dp_i= \\sim (dp_{i-1}$ & $dp_{id_1-1}$ & $dp_{id_2-1} \\ldots)$, where $id_j$ satisfies $a_{id_j} \\neq a_{id_j+1}$ and $id_j < i$. Time complexity: $O(n^2)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define m_p make_pair\n#define all(x) (x).begin(),(x).end()\n#define sz(x) ((int)(x).size())\n#define fi first\n#define se second\ntypedef long long ll;\nmt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());\nmt19937 rnf(2106);\nconst int N = 55;\n\nint n;\nint q[N];\n\nvoid solv()\n{\n    cin >> n;\n    for (int i = 1; i <= n; ++i)\n        q[i] = 0;\n    for (int i = 1; i <= n; ++i)\n    {\n        int x;\n        cin >> x;\n        ++q[x];\n    }\n\n    for (int i = 1; i <= n; ++i)\n    {\n        if (q[i] % 2 == 1)\n        {\n            cout << \"YES\\n\";\n            return;\n        }\n    }\n    cout << \"NO\\n\";\n}\n\nint main()\n{\n    #ifdef SOMETHING\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #endif // SOMETHING\n    ios_base::sync_with_stdio(false), cin.tie(0);\n\n    int tt = 1;\n    cin >> tt;\n    while (tt--)\n    {\n        solv();\n    }\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "1990",
    "index": "B",
    "title": "Array Craft",
    "statement": "For an array $b$ of size $m$, we define:\n\n- the \\textbf{maximum prefix position} of $b$ is the \\textbf{smallest} index $i$ that satisfies $b_1+\\ldots+b_i=\\max_{j=1}^{m}(b_1+\\ldots+b_j)$;\n- the \\textbf{maximum suffix position} of $b$ is the \\textbf{largest} index $i$ that satisfies $b_i+\\ldots+b_m=\\max_{j=1}^{m}(b_j+\\ldots+b_m)$.\n\nYou are given three integers $n$, $x$, and $y$ ($x > y$). Construct an array $a$ of size $n$ satisfying:\n\n- $a_i$ is either $1$ or $-1$ for all $1 \\le i \\le n$;\n- the \\textbf{maximum prefix position} of $a$ is $x$;\n- the \\textbf{maximum suffix position} of $a$ is $y$.\n\nIf there are multiple arrays that meet the conditions, print any. It can be proven that such an array always exists under the given conditions.",
    "tutorial": "Starting from a trival construction. Utilize the condition $x > y$. First, we consider making $presum_x > presum_j$ for all $x < i \\le n$, and similarly for $y$. We can think of a trivial construction: $a[r, \\ldots ,l]=[1, \\ldots ,1], a[1, \\ldots...,r-1]=[-1, \\ldots, -1]$ and $a[l+1,\\ldots,n]=[-1, \\ldots, -1]$. The construction doesn't works when $presum_x<0$, but we are close to the correct solution. Next, we will make a little adjustment: $a[r, \\ldots, l]=[1,\\ldots,1], a[1, \\ldots...,r-1]=[\\ldots,1, -1]$ and $a[l+1,\\ldots,n]=[-1,1, \\ldots]$. It is not hard to see $presum_x \\ge presum_j$ for all $x < i \\le n$, and for $1 \\le i \\le y$, $\\max(presum_i)-min(presum_i)\\le 1$. Thus, we get $presum_x \\ge 2+presum_{y-1} \\ge 2+min(presum_i) \\ge 1+max(presum_i)$. The same applies to the suffix sum as well. Therefore, this construction is valid. Time complexity: $O(n)$. Solve the problem when $x \\le y$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int t;\n  cin >> t;\n  while(t>0){\n    t--;\n    int n,x,y;\n    cin >> n >> x >> y;\n    x--; y--;\n    vector<int> a(n,1);\n    int e;\n    e=-1;\n    for(int i=x+1;i<n;i++){\n      a[i]=e;\n      e*=-1;\n    }\n    e=-1;\n    for(int i=y-1;i>=0;i--){\n      a[i]=e;\n      e*=-1;\n    }\n    for(int i=0;i<n;i++){\n      if(i){cout << \" \";}\n      cout << a[i];\n    }cout << \"\\n\";\n  }\n  return 0;\n}\n\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1990",
    "index": "C",
    "title": "Mad MAD Sum",
    "statement": "We define the $\\operatorname{MAD}$ (Maximum Appearing Duplicate) in an array as the largest number that appears at least twice in the array. Specifically, if there is no number that appears at least twice, the $\\operatorname{MAD}$ value is $0$.\n\nFor example, $\\operatorname{MAD}([1, 2, 1]) = 1$, $\\operatorname{MAD}([2, 2, 3, 3]) = 3$, $\\operatorname{MAD}([1, 2, 3, 4]) = 0$.\n\nYou are given an array $a$ of size $n$. Initially, a variable $sum$ is set to $0$.\n\nThe following process will be executed in a sequential loop until all numbers in $a$ become $0$:\n\n- Set $sum := sum + \\sum_{i=1}^{n} a_i$;\n- Let $b$ be an array of size $n$. Set $b_i :=\\ \\operatorname{MAD}([a_1, a_2, \\ldots, a_i])$ for all $1 \\le i \\le n$, and then set $a_i := b_i$ for all $1 \\le i \\le n$.\n\nFind the value of $sum$ after the process.",
    "tutorial": "After one operation, the array becomes non-decreasing. Consider $a_1=a_2=\\ldots=a_n$, the operation seems to have shifted the array right. When does the \"right shift\" parttern happen? Read hints first. Let's consider only non-decreasing arrays. Observe a continuous segments $a[l...r]=x(l<r,x>0)$, after one operation, we get $a[l+1,min(r+1,n)]=x$ holds. We can conclude that if, for all non-zero contiguous segments in the array (except the last one), their lengths are all greater than $1$, then the array follows the \"right shift\" parttern. Let's say this kind of array \"good\". The last problem is when will the array become \"good\". Let's assume we get the array $b$ after one operation on array $a$, we get $b_i<b_{i+1}<b_{i+2}$. We can infer that $b_i=a_i,b_{i+1}=a_{i+1}$ and there is at least $a_j=a_{i+1}(j \\le i)$, which shows that $a$ is not non-decreasing. In other words, after two operations, we can always get a \"good\" array. Then the calculating is trival. Time complexity: $O(n)$. The title \"Mad MAD Sum\" is not only a pun on the words Mad and MAD (Maximum Appearing Duplicate), but also implies the solution to the problem :)",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n#define m_p make_pair\n#define all(x) (x).begin(),(x).end()\n#define sz(x) ((int)(x).size())\n#define fi first\n#define se second\ntypedef long long ll;\nmt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());\nmt19937 rnf(2106);\nconst int N = 200005;\n\nint n;\nint a[N];\n\nbool c[N];\nvoid doit()\n{\n    for (int i = 1; i <= n; ++i)\n        c[i] = false;\n    int maxu = 0;\n    for (int i = 1; i <= n; ++i)\n    {\n        if (c[a[i]])\n            maxu = max(maxu, a[i]);\n        c[a[i]] = true;\n        a[i] = maxu;\n    }\n}\n\nvoid solv()\n{\n    cin >> n;\n    for (int i = 1; i <= n; ++i)\n        cin >> a[i];\n\n    ll ans = 0;\n    for (int i = 1; i <= n; ++i)\n        ans += a[i];\n    doit();\n    for (int i = 1; i <= n; ++i)\n        ans += a[i];\n    doit();\n\n    for (int i = 1; i <= n; ++i)\n        ans += (n - i + 1) * 1LL * a[i];\n    cout << ans << \"\\n\";\n}\n\nint main()\n{\n    #ifdef SOMETHING\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #endif // SOMETHING\n    ios_base::sync_with_stdio(false), cin.tie(0);\n\n    int tt = 1;\n    cin >> tt;\n    while (tt--)\n    {\n        solv();\n    }\n    return 0;\n}\n\n",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1990",
    "index": "D",
    "title": "Grid Puzzle",
    "statement": "You are given an array $a$ of size $n$.\n\nThere is an $n \\times n$ grid. In the $i$-th row, the first $a_i$ cells are black and the other cells are white. In other words, note $(i,j)$ as the cell in the $i$-th row and $j$-th column, cells $(i,1), (i,2), \\ldots, (i,a_i)$ are black, and cells $(i,a_i+1), \\ldots, (i,n)$ are white.\n\nYou can do the following operations any number of times in any order:\n\n- Dye a $2 \\times 2$ subgrid white;\n- Dye a whole row white. Note you can \\textbf{not} dye a whole column white.\n\nFind the minimum number of operations to dye all cells white.",
    "tutorial": "Obviously, when $a_i$ is large enough, we will definitely use operation $2$ on the $i$-th row. What is its specific value? It is $5$(try to prove it). Now we can only consider $a_i \\le 4$ cases. From left to right, consider a greedy solution or a DP solution. Read hints first. For $a_i \\ge 5$, we will definitely use operation $2$ on the $i$-th row because at least three $2 \\times 2$ subgrid are needed to cover it, which is not better then do three times operation $2$ in the $i-1,i$ and $i+1$ row. Now we can only consider $a_i \\le 4$ cases. Let's consider from left to right. In the left most row, there are $3$ cases: there is no black cells Do nothing; there is no black cells Do nothing; there is $\\le 2$ black cells. We can put one $2 \\times 2$ subgrid greedily; there is $\\le 2$ black cells. We can put one $2 \\times 2$ subgrid greedily; there is $> 2$ black cells. We just use one time operation $2$ in this row(try to prove it). there is $> 2$ black cells. We just use one time operation $2$ in this row(try to prove it). We can summarize that for the $i$-th row, there are only three situations where it is affected by the $i-1$-th row: it is not affected; it is not affected; the cells in the third and fourth columns have been colored white; the cells in the third and fourth columns have been colored white; the cells in the first and second columns have been colored white. the cells in the first and second columns have been colored white. We can greedily process this process from left to right, or use DP. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define m_p make_pair\n#define all(x) (x).begin(),(x).end()\n#define sz(x) ((int)(x).size())\n#define fi first\n#define se second\ntypedef long long ll;\nmt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());\nmt19937 rnf(2106);\nconst int N = 200005;\n\nint n;\nint a[N];\n\nint dp[N];\nvoid minh(int& x, int y)\n{\n    x = min(x, y);\n}\n\nvoid solv()\n{\n    cin >> n;\n    for (int i = 1; i <= n; ++i)\n        cin >> a[i];\n\n    int minu[2] = {N, N};\n    for (int i = 1; i <= n; ++i)\n    {\n        dp[i] = dp[i - 1] + 1;\n        if (a[i] == 0)\n            minh(dp[i], dp[i - 1]);\n        if (a[i] <= 2)\n            minh(dp[i], i + minu[1 - i % 2]);\n\n        if (a[i] <= 2)\n            minh(minu[i % 2], dp[i - 1] - i);\n        else if (a[i] > 4)\n            minu[0] = minu[1] = N;\n    }\n\n    cout << dp[n] << \"\\n\";\n}\n\nint main()\n{\n    #ifdef SOMETHING\n    freopen(\"input.txt\", \"r\", stdin);\n    //freopen(\"output.txt\", \"w\", stdout);\n    #endif // SOMETHING\n    ios_base::sync_with_stdio(false), cin.tie(0);\n\n    int tt = 1;\n    cin >> tt;\n    while (tt--)\n    {\n        solv();\n    }\n    return 0;\n}\n\n",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1990",
    "index": "E2",
    "title": "Catch the Mole(Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is the limit on the number of queries.}\n\n\\textbf{This is an interactive problem.}\n\nYou are given a tree of $n$ nodes with node $1$ as its root node.\n\nThere is a hidden mole in one of the nodes. To find its position, you can pick an integer $x$ ($1 \\le x \\le n$) to make an inquiry to the jury. Next, the jury will return $1$ when the mole is in subtree $x$. Otherwise, the judge will return $0$. If the judge returns $0$ and the mole is not in root node $1$, the mole will move to the parent node of the node it is currently on.\n\nUse at most $160$ operations to find the \\textbf{current} node where the mole is located.",
    "tutorial": "Consider querying a subtree. If the jury returns $0$, we can delete the entire subtree. We can query any leaf node. If the jury returns $1$, we are done; otherwise, the mole will move up. Consider querying a subtree. If the jury returns $1$, we can \"drive\" it out of this subtree using the method in hint2. Combime the idea in hint $1$ and $3$. Read hints first. For easy version, we can pick a vertex $v$ such that $maxdep_v-dep_v+1=50$: if the jury returns $0$, we can delete the entire subtree; if the jury returns $0$, we can delete the entire subtree; otherwise, make queries until it is out and answer $fa_v$(a special case is $v=1$);  otherwise, make queries until it is out and answer $fa_v$(a special case is $v=1$);  if there is no such vertex, then make $100$ queries and answer the root node $1$. This costs about $200$ queries, which can not pass hard version. But we can optimize it. The bottleneck is the step $2$, when we drive away this mole once, we need to immediately check if it is still in the subtree $v$, which can be optimized. In fact, we can drive the mole 50 times and then perform a binary search on the chain from $v$ to the root node. Number of queries: $O(2sqrt(n)+log(n))$ Query any leaf $70$ times, then delete all nodes $x$ such that $maxdep_v-dep_v+1<=70$. Then the tree can be split into $\\le 70$ chains. Do binary search for these chains. Solve the problem in $100$ queries.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define all(a) a.begin(),a.end()\n#define pb push_back\n#define sz(a) ((int)a.size())\n\nusing ll=long long;\nusing u32=unsigned int;\nusing u64=unsigned long long;\nusing i128=__int128;\nusing u128=unsigned __int128;\nusing f128=__float128;\n\nusing pii=pair<int,int>;\nusing pll=pair<ll,ll>;\n\ntemplate<typename T> using vc=vector<T>;\ntemplate<typename T> using vvc=vc<vc<T>>;\ntemplate<typename T> using vvvc=vc<vvc<T>>;\n\nusing vi=vc<int>;\nusing vll=vc<ll>;\nusing vvi=vc<vi>;\nusing vvll=vc<vll>;\n\n#define vv(type,name,n,...) \\\n    vector<vector<type>> name(n,vector<type>(__VA_ARGS__))\n#define vvv(type,name,n,m,...) \\\n    vector<vector<vector<type>>> name(n,vector<vector<type>>(m,vector<type>(__VA_ARGS__)))\n\ntemplate<typename T> using min_heap=priority_queue<T,vector<T>,greater<T>>;\ntemplate<typename T> using max_heap=priority_queue<T>;\n\n// https://trap.jp/post/1224/\n#define rep1(n) for(ll i=0; i<(ll)(n); ++i)\n#define rep2(i,n) for(ll i=0; i<(ll)(n); ++i)\n#define rep3(i,a,b) for(ll i=(ll)(a); i<(ll)(b); ++i)\n#define rep4(i,a,b,c) for(ll i=(ll)(a); i<(ll)(b); i+=(c))\n#define cut4(a,b,c,d,e,...) e\n#define rep(...) cut4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)\n#define per1(n) for(ll i=((ll)n)-1; i>=0; --i)\n#define per2(i,n) for(ll i=((ll)n)-1; i>=0; --i)\n#define per3(i,a,b) for(ll i=((ll)a)-1; i>=(ll)(b); --i)\n#define per4(i,a,b,c) for(ll i=((ll)a)-1; i>=(ll)(b); i-=(c))\n#define per(...) cut4(__VA_ARGS__,per4,per3,per2,per1)(__VA_ARGS__)\n#define rep_subset(i,s) for(ll i=(s); i>=0; i=(i==0?-1:(i-1)&(s)))\n\ntemplate<typename T, typename S> constexpr T ifloor(const T a, const S b){return a/b-(a%b&&(a^b)<0);}\ntemplate<typename T, typename S> constexpr T iceil(const T a, const S b){return ifloor(a+b-1,b);}\n\ntemplate<typename T>\nvoid sort_unique(vector<T> &vec){\n    sort(vec.begin(),vec.end());\n    vec.resize(unique(vec.begin(),vec.end())-vec.begin());\n}\n\ntemplate<typename T, typename S> constexpr bool chmin(T &a, const S b){if(a>b) return a=b,true; return false;}\ntemplate<typename T, typename S> constexpr bool chmax(T &a, const S b){if(a<b) return a=b,true; return false;}\n\ntemplate<typename T, typename S> istream& operator >> (istream& i, pair<T,S> &p){return i >> p.first >> p.second;}\ntemplate<typename T, typename S> ostream& operator << (ostream& o, const pair<T,S> &p){return o << p.first << ' ' << p.second;}\n\n#ifdef i_am_noob\n#define bug(...) cerr << \"#\" << __LINE__ << ' ' << #__VA_ARGS__ << \"- \", _do(__VA_ARGS__)\ntemplate<typename T> void _do(vector<T> x){for(auto i: x) cerr << i << ' ';cerr << \"\\n\";}\ntemplate<typename T> void _do(set<T> x){for(auto i: x) cerr << i << ' ';cerr << \"\\n\";}\ntemplate<typename T> void _do(unordered_set<T> x){for(auto i: x) cerr << i << ' ';cerr << \"\\n\";}\ntemplate<typename T> void _do(T && x) {cerr << x << endl;}\ntemplate<typename T, typename ...S> void _do(T && x, S&&...y) {cerr << x << \", \"; _do(y...);}\n#else\n#define bug(...) 777771449\n#endif\n\ntemplate<typename T> void print(vector<T> x){for(auto i: x) cout << i << ' ';cout << \"\\n\";}\ntemplate<typename T> void print(set<T> x){for(auto i: x) cout << i << ' ';cout << \"\\n\";}\ntemplate<typename T> void print(unordered_set<T> x){for(auto i: x) cout << i << ' ';cout << \"\\n\";}\ntemplate<typename T> void print(T && x) {cout << x << \"\\n\";}\ntemplate<typename T, typename... S> void print(T && x, S&&... y) {cout << x << ' ';print(y...);}\n\ntemplate<typename T> istream& operator >> (istream& i, vector<T> &vec){for(auto &x: vec) i >> x; return i;}\n\nvvi read_graph(int n, int m, int base=1){\n    vvi adj(n);\n    for(int i=0,u,v; i<m; ++i){\n        cin >> u >> v,u-=base,v-=base;\n        adj[u].pb(v),adj[v].pb(u);\n    }\n    return adj;\n}\n\nvvi read_tree(int n, int base=1){return read_graph(n,n-1,base);}\n\ntemplate<typename T, typename S> pair<T,S> operator + (const pair<T,S> &a, const pair<T,S> &b){return {a.first+b.first,a.second+b.second};}\n\ntemplate<typename T> constexpr T inf=0;\ntemplate<> constexpr int inf<int> = 0x3f3f3f3f;\ntemplate<> constexpr ll inf<ll> = 0x3f3f3f3f3f3f3f3f;\n\ntemplate<typename T> vector<T> operator += (vector<T> &a, int val){for(auto &i: a) i+=val; return a;}\n\ntemplate<typename T> T isqrt(const T &x){T y=sqrt(x+2); while(y*y>x) y--; return y;}\n\n#define ykh mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())\n\n//#include<atcoder/all>\n//using namespace atcoder;\n\n//using mint=modint998244353;\n//using mint=modint1000000007;\n\nstruct Tree{\n    int n;\n    vector<vector<int>> adj,anc;\n    vector<int> par,tl,tr,dep,ord,siz,ch,head;\n    Tree(int _n=0){\n        n=_n;\n        adj.resize(n);\n    }\n    void add_edge(int u, int v){\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n    void init(){\n        par.resize(n),tl.resize(n),tr.resize(n),dep.resize(n),anc.resize(n),siz.resize(n),ch.resize(n),head.resize(n);\n        int cur=-1,m=0;\n        while((1<<m)<=n) m++;\n        for(int i=0; i<n; ++i) anc[i].resize(m),ch[i]=-1;\n        auto dfs1=[&](auto &self, int u, int fa) -> void{\n            par[u]=fa;\n            siz[u]=1;\n            for(int v: adj[u]) if(v!=fa) self(self,v,u),siz[u]+=siz[v];\n            for(int v: adj[u]) if(v!=fa&&(ch[u]==-1||siz[v]>siz[ch[u]])) ch[u]=v;\n        };\n        auto dfs2=[&](auto &self, int u, int fa) -> void{\n            ord.push_back(u);\n            tl[u]=++cur;\n            anc[u][0]=fa;\n            if(fa==-1) dep[u]=0;\n            else dep[u]=dep[fa]+1;\n            for(int i=1; i<m; ++i){\n                if(anc[u][i-1]==-1) anc[u][i]=-1;\n                else anc[u][i]=anc[anc[u][i-1]][i-1];\n            }\n            if(ch[u]!=-1) self(self,ch[u],u);\n            for(int v: adj[u]) if(v!=fa&&v!=ch[u]) self(self,v,u);\n            tr[u]=cur;\n        };\n        dfs1(dfs1,0,-1);\n        dfs2(dfs2,0,-1);\n        head[0]=0;\n        for(int u: ord){\n            for(int v: adj[u]) if(v!=par[u]){\n                if(v==ch[u]) head[v]=head[u];\n                else head[v]=v;\n            }\n        }\n    }\n    bool is_anc(int u, int v){return tl[u]<=tl[v]&&tr[u]>=tr[v];}\n    int get_anc(int u, int x){\n        for(int i=anc[0].size()-1; i>=0; --i) if(u!=-1&&(x>>i&1)) u=anc[u][i];\n        return u;\n    }\n    int lca(int u, int v){\n        if(is_anc(u,v)) return u;\n        for(int i=anc[0].size()-1; i>=0; --i) if(anc[u][i]!=-1&&!is_anc(anc[u][i],v)) u=anc[u][i];\n        return par[u];\n    }\n};\n\nvoid ahcorz(){\n    int lft=150;\n    auto query=[&](int u){\n        assert(lft>0);\n        cout << \"? \" << u+1 << endl;\n        lft--;\n        int res; cin >> res; return res;\n    };\n    int n; cin >> n;\n    Tree tree(n);\n    rep(n-1){\n        int u,v; cin >> u >> v; u--,v--;\n        tree.add_edge(u,v);\n    }\n    tree.init();\n    vi vis(n);\n    auto fill_vis=[&](auto &self, int u){\n        if(vis[u]) return;\n        vis[u]=1;\n        for(int v: tree.adj[u]) if(v!=tree.par[u]) self(self,v);\n    };\n    vi ord(n); iota(all(ord),0);\n    sort(all(ord),[&](int i, int j){return tree.dep[i]<tree.dep[j];});\n    per(n){\n        int u=ord[i];\n        if(vis[u]) continue;\n        int v=u;\n        rep(_,(lft-1)/2-1){\n            if(v==0) break;\n            v=tree.par[v];\n        }\n        if(!query(v)){\n            fill_vis(fill_vis,v);\n            continue;\n        }\n        int x=tree.ord.back();\n        int m=tree.dep[u]-tree.dep[v]+1;\n        rep(_,m){\n            if(query(x)){\n                cout << \"! \" << x+1 << endl;\n                return;\n            }\n            if(!query(v)){\n                int y=tree.par[v];\n                if(y!=-1) y=tree.par[y];\n                if(y==-1) y=0;\n                cout << \"! \" << y+1 << endl;\n                return;\n            }\n        }\n        cout << \"! 1\" << endl;\n        return;\n    }\n    assert(0);\n}\n\nsigned main(){\n    ios_base::sync_with_stdio(0),cin.tie(0);\n    cout << fixed << setprecision(20);\n    int t=1;\n    cin >> t;\n    while(t--) ahcorz();\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "interactive",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1990",
    "index": "F",
    "title": "Polygonal Segments",
    "statement": "You are given an array $a$ of size $n$.\n\nA segment $[l, r](1 \\le l < r \\le n)$ is called a \\textbf{polygonal} segment only if the following conditions hold:\n\n- $(r-l+1) \\geq 3$;\n- Considering $a_l, a_{l+1}, \\ldots, a_r$ as side lengths, these sides can form a polygon with $(r-l+1)$ sides.\n\nProcess $q$ queries of two types:\n\n- \"1 l r\": find the length of the longest segment among all \\textbf{polygonal} segments $[l_0,r_0]$ satisfying $l \\le l_0 \\le r_0 \\le r$. If there is no such \\textbf{polygonal} segment, output $-1$ instead;\n- \"2 i x\": assign $a_i := x$.",
    "tutorial": "Consider using a segment tree to solve this problem. We need to merge the information of two intervals. First, we take the maximum value of the answers in the two intervals, and then calculate the polygon segment spanning the two intervals. We notice that a local maximal polygon segment $[l, r]$ must satisfy $min(a_{l-1}, a_{r+1}) >= 2(a_l + ... + a_r)$(or $l=1$,$r=n$). Define the suffix $[i, r]$ of the interval $[l, r]$ as a special suffix if and only if $a_i+ \\ldots +a_r$ $\\le 2 \\cdot a_i$. The same principle applies to special prefixes. We can observe that there are at most $O(log(maxa))$ special suffixes, because the sum of one special suffix is at least twice the sum of the previous special suffix. Therefore, we can merge the special suffixes of the left interval and the special prefixes of the right interval (using the two-pointer algorithm) to obtain the answer spanning the two intervals. Number of queries: $O(nlog^2(n))$ Consider the following process: This looks $O(n^2)$ when $a=[1,2,1,4,1,2,1,8,1,2,1,4,1,2,1,16,... ]$. However, if we store all the ranges which are already calculated, it becomes $O(n log n)$. Why? Let's call a range $[l,r]$ \"key range\" when $sum(a[l...r])<=2min(a[l-1],a[r+1])$. We can see: 1.There're only $O(n log n)$ different key ranges; 2.We only visit at most $2$ ranges which are not key range in each query. Assume we have changed $a_p$. We need to clear all the answer of key ranges which pass through $p$. We can use interval tree to achieve it.",
    "code": "// #pragma GCC optimize(\"O3,unroll-loops\")\n// #pragma GCC target(\"avx2,bmi,bmi2,lzcnt,popcnt\")\n#include \"bits/stdc++.h\"\nusing namespace std;\nusing ll = long long int;\nmt19937_64 RNG(chrono::high_resolution_clock::now().time_since_epoch().count());\n\n/**\n * Point-update Segment Tree\n * Source: kactl\n * Description: Iterative point-update segment tree, ranges are half-open i.e [L, R).\n *              f is any associative function.\n * Time: O(logn) update/query\n */\n\ntemplate<class T, T unit = T()>\nstruct SegTree {\n\tT f(T a, T b) {\n        a[0] += b[0];\n        if (a[1] < b[1]) a[1] = b[1], a[2] = b[2];\n        return a;\n    }\n\tvector<T> s; int n;\n\tSegTree(int _n = 0, T def = unit) : s(2*_n, def), n(_n) {}\n\tvoid update(int pos, T val) {\n\t\tfor (s[pos += n] = val; pos /= 2;)\n\t\t\ts[pos] = f(s[pos * 2], s[pos * 2 + 1]);\n\t}\n\tT query(int b, int e) {\n\t\tT ra = unit, rb = unit;\n\t\tfor (b += n, e += n; b < e; b /= 2, e /= 2) {\n\t\t\tif (b % 2) ra = f(ra, s[b++]);\n\t\t\tif (e % 2) rb = f(s[--e], rb);\n\t\t}\n\t\treturn f(ra, rb);\n\t}\n};\n\n#include <ext/pb_ds/assoc_container.hpp>\n\nstruct splitmix64_hash {\n\tstatic uint64_t splitmix64(uint64_t x) {\n\t\t// http://xorshift.di.unimi.it/splitmix64.c\n\t\tx += 0x9e3779b97f4a7c15;\n\t\tx = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;\n\t\tx = (x ^ (x >> 27)) * 0x94d049bb133111eb;\n\t\treturn x ^ (x >> 31);\n\t}\n\n\tsize_t operator()(uint64_t x) const {\n\t\tstatic const uint64_t FIXED_RANDOM = std::chrono::steady_clock::now().time_since_epoch().count();\n\t\treturn splitmix64(x + FIXED_RANDOM);\n\t}\n};\n\ntemplate <typename K, typename V, typename Hash = splitmix64_hash>\nusing hash_map = __gnu_pbds::gp_hash_table<K, V, Hash>;\n\ntemplate <typename K, typename Hash = splitmix64_hash>\nusing hash_set = hash_map<K, __gnu_pbds::null_type, Hash>;\n\nint main()\n{\n    ios::sync_with_stdio(false); cin.tie(0);\n\n    int t; cin >> t;\n    while (t--) {\n        int n, q; cin >> n >> q;\n        vector<ll> a(n);\n        for (auto &x : a) cin >> x;\n\n        map<ll, int> cache;\n\n        struct Node {\n            int L, R, M; // [L, R)\n            set<array<int, 2>> by_l, by_r;\n            void ins(int l, int r) {\n                by_l.insert({l, r});\n                by_r.insert({r, l});\n            }\n            void del(int l, int r) {\n                by_l.erase({l, r});\n                by_r.erase({r, l});\n            }\n        };\n        vector<Node> ITree(4*n);\n        auto build = [&] (const auto &self, int node, int l, int r) -> void {\n            int mid = (l + r)/2;\n            ITree[node].L = l;\n            ITree[node].R = r;\n            ITree[node].M = mid;\n            if (l+1 == r) return;\n            self(self, 2*node + 1, l, mid);\n            self(self, 2*node + 2, mid, r);\n        };\n        build(build, 0, 0, n);\n        auto insert = [&] (const auto &self, int node, int l, int r) -> void { // Insert interval [l, r) into the tree\n            if (ITree[node].L+1 == ITree[node].R) {\n                ITree[node].ins(l, r);\n                return;\n            }\n\n            if (l >= ITree[node].M) self(self, 2*node+2, l, r);\n            else if (r <= ITree[node].M) self(self, 2*node+1, l, r);\n            else ITree[node].ins(l, r);\n        };\n        auto erase = [&] (const auto &self, int node, int x) -> void { // Delete all intervals covering point x\n            if (x < ITree[node].M) {\n                // Delete some prefix\n                auto &st = ITree[node].by_l;\n                while (!st.empty()) {\n                    auto [l, r] = *begin(st);\n                    if (l <= x) {\n                        ITree[node].del(l, r);\n                        ll id = 1ll*(n+1)*l + r;\n                        cache.erase(id);\n                    }\n                    else break;\n                }\n            }\n            else {\n                // Delete some suffix\n                auto &st = ITree[node].by_r;\n                while (!st.empty()) {\n                    auto [r, l] = *rbegin(st);\n                    if (r > x) {\n                        ITree[node].del(l, r);\n                        ll id = 1ll*(n+1)*l + r;\n                        cache.erase(id);\n                    }\n                    else break;\n                }\n            }\n\n            if (ITree[node].L+1 == ITree[node].R) return;\n            if (x < ITree[node].M) self(self, 2*node+1, x);\n            else self(self, 2*node+2, x);\n        };\n\n        constexpr array<ll, 3> unit = {0, 0, -1};\n        SegTree<array<ll, 3>, unit> seg(n);\n        for (int i = 0; i < n; ++i) seg.update(i, array<ll, 3>{a[i], a[i], i});\n        \n        auto solve = [&] (const auto &self, int L, int R) -> int {\n            if (R-L <= 2) return -1;\n            ll id = 1ll*L*(n+1) + R;\n            if (cache.find(id) != cache.end()) return cache[id];\n            \n            auto [sm, mx, pivot] = seg.query(L, R);\n\n            insert(insert, 0, L, R);\n            if (mx < sm - mx) {\n                return cache[id] = R-L;\n            }\n            else {\n                int ret = self(self, L, pivot);\n                ret = max(ret, self(self, pivot+1, R));\n                return cache[id] = ret;\n            }\n        };\n\n        while (q--) {\n            int type; cin >> type;\n            if (type == 1) {\n                int l, r; cin >> l >> r;\n                cout << solve(solve, l-1, r) << '\\n';\n            }\n            else {\n                ll pos, val; cin >> pos >> val; --pos;\n\n                erase(erase, 0, pos);\n                if (pos) erase(erase, 0, pos-1);\n                if (pos+1 < n) erase(erase, 0, pos+1);\n                seg.update(pos, array<ll, 3>{val, val, pos});\n            }\n        }\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1991",
    "index": "A",
    "title": "Maximize the Last Element",
    "statement": "You are given an array $a$ of $n$ integers, where $n$ is \\textbf{odd}.\n\nIn one operation, you will remove two \\textbf{adjacent} elements from the array $a$, and then concatenate the remaining parts of the array. For example, given the array $[4,7,4,2,9]$, we can obtain the arrays $[4,2,9]$ and $[4,7,9]$ by the operations $[\\underline{4,7}, 4,2,9] \\to [4,2,9]$ and $[4,7,\\underline{4,2},9] \\to [4,7,9]$ respectively. However, we cannot obtain the array $[7,2,9]$ as it requires deleting non-adjacent elements $[\\underline{4},7,\\underline{4},2,9]$.\n\nYou will repeatedly perform this operation until exactly one element remains in $a$.\n\nFind the maximum possible value of the remaining element in $a$.",
    "tutorial": "Consider the parity of the position. The answer is the maximum value of the elements at odd indices. Proof Any element at an odd index can be preserved until the end. Since each element at an odd index has an even number of elements on both sides, pairs of adjacent elements can be removed from left to right until only the element at the odd index remains. For example, if you want to keep the element at the $i$-th position, you can remove the elements at positions $1$ and $2$, $3$ and $4$, and so on, until the elements at positions $i-2$ and $i-1$ are removed. Then, continue removing elements at positions $i+1$ and $i+2$, and so on, until the elements at positions $n-1$ and $n$ are removed. Therefore, any element at an odd index can be preserved through this method. No element at an even index can be preserved until the end. Since $n$ is odd, there are more elements at odd indices than at even indices. Each operation removes one element at an odd index and one element at an even index. Since there are always more elements at odd indices, the last remaining element must be at an odd index.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 105;\nint t, n, a[MAX_N];\nint main() {\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        for (int i = 1; i <= n; i++)\n            cin >> a[i];\n        int max_value = 0;\n        for (int i = 1; i <= n; i += 2)\n            max_value = max(max_value, a[i]);\n        cout << max_value << '\\n';\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1991",
    "index": "B",
    "title": "AND Reconstruction",
    "statement": "You are given an array $b$ of $n - 1$ integers.\n\nAn array $a$ of $n$ integers is called good if $b_i = a_i \\, \\& \\, a_{i + 1}$ for $1 \\le i \\le n-1$, where $\\&$ denotes the bitwise AND operator.\n\nConstruct a good array, or report that no good arrays exist.",
    "tutorial": "Consider $b_{i - 1} | b_i$. Let's construct an array $a$ using the formula $a_i = b_{i - 1} | b_i$ (assuming $b_0$ and $b_n$ are $0$). We then verify the condition $b_i = a_i \\& a_{i + 1}$ for $1 \\le i < n$. If any condition fails, then such an array $a$ does not exist. Explanation Using the above construction method, we get: $a_i \\& a_{i + 1} = (b_{i - 1} | b_i) \\& (b_i | b_{i + 1}) = b_i | (b_{i - 1} \\& b_{i + 1})$ If for any $i$, $b_i | (b_{i - 1} \\& b_{i + 1}) \\neq b_i$, then the constructed array $a$ does not satisfy the required condition. This indicates that there exists a bit in $b$ where $b_{i - 1} = 1$, $b_i = 0$, and $b_{i + 1} = 1$, which can prove there is no solution. Proof: If $a_{i - 2} \\& a_{i - 1} = b_{i - 1} = 1$, then $a_{i - 1} = 1$. Similarly, since $a_i \\& a_{i + 1} = b_i = 1$, then $a_i = 1$. However, $a_{i - 1} \\& a_i = 1 \\& 1 = 1$, which contradicts $b_i = 0$. Therefore, this configuration is unsolvable. This shows that our construction method can construct a valid array $a$, except in cases where the above bit configuration in $b$ makes it unsolvable.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 1e5 + 5;\nint n, b[MAX_N], a[MAX_N];\nvoid solve() {\n    cin >> n;\n    for (int i = 1; i < n; i++)\n        cin >> b[i];\n    b[0] = b[n] = 0;\n    for (int i = 1; i <= n; i++)\n        a[i] = b[i - 1] | b[i];\n    bool valid = true;\n    for (int i = 1; i < n; i++)\n        if ((a[i] & a[i + 1]) != b[i]) {\n            valid = false;\n            break;\n        }\n    if (valid) {\n        for (int i = 1; i <= n; i++)\n            cout << a[i] << ' ';\n        cout << '\\n';\n    } else\n        cout << -1 << endl;\n}\nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1991",
    "index": "C",
    "title": "Absolute Zero",
    "statement": "You are given an array $a$ of $n$ integers.\n\nIn one operation, you will perform the following two-step move:\n\n- Choose an integer $x$ ($0 \\le x \\le 10^{9}$).\n- Replace each $a_i$ with $|a_i - x|$, where $|v|$ denotes the absolute value of $v$.\n\nFor example, by choosing $x = 8$, the array $[5, 7, 10]$ will be changed into $[|5-8|, |7-8|, |10-8|] = [3,1,2]$.\n\nConstruct a sequence of operations to make all elements of $a$ equal to $0$ in at most $40$ operations or determine that it is impossible. You do \\textbf{not} need to minimize the number of operations.",
    "tutorial": "If the array contains both odd and even elements, it is impossible to zero the array. Is there a method to narrow the range of elements after every operation? If the array contains both odd and even numbers, it is impossible to zero the array. This is because any operation will maintain the presence of both odd and even elements. Otherwise, if all elements in the array are either odd or even, it is feasible to zero the array in no more than $31$ operations. The operation strategy works by iteratively narrowing the range of all elements. Initially, the range of all elements is between $[0, 2^{30}]$. Starting from $x = 2^{29}$, we use each power of $2$ as $x$, reducing the exponent by one each time (i.e., $2^{29}, 2^{28}, \\ldots, 2^{0}$). After each operation, the range of all elements is halved, narrowed down to $[0, x]$. Continuing this process, after $30$ operations, all elements will become $0$ or $1$. If all elements are $1$ after $30$ operations, perform one last operation with $x = 1$ to turn all $1\\text{s}$ into $0\\text{s}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 2e5 + 5;\nint n, a[MAX_N];\nvoid solve() {\n    cin >> n;\n    for (int i = 1; i <= n; i++)\n        cin >> a[i];\n    bool has_odd = false, has_even = false;\n    for (int i = 1; i <= n; i++)\n        if (a[i] % 2 == 1)\n            has_odd = true;\n        else\n            has_even = true;\n    if (has_even && has_odd)\n        cout << -1 << '\\n';\n    else {\n        vector<int> operations;\n        for (int i = 29; i >= 0; i--)\n            operations.push_back(1 << i);\n        if (has_even)\n            operations.push_back(1);\n        cout << operations.size() << '\\n';\n        for (int x : operations)\n            cout << x << ' ';\n        cout << '\\n';\n    }\n}\nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1991",
    "index": "D",
    "title": "Prime XOR Coloring",
    "statement": "You are given an undirected graph with $n$ vertices, numbered from $1$ to $n$. There is an edge between vertices $u$ and $v$ if and only if $u \\oplus v$ is a prime number, where $\\oplus$ denotes the bitwise XOR operator.\n\nColor all vertices of the graph using the minimum number of colors, such that no two vertices directly connected by an edge have the same color.",
    "tutorial": "We can use only $4$ colors for all $n$. For $n \\ge 6$, the minimum number of colors is always $4$. Proof First, we can show that the number of colors cannot be less than $4$. This is because vertices $1$, $3$, $4$, and $6$ form a clique, meaning they are all connected, so they must have different colors. Next, we can provide a construction where the number of colors is $4$. For the $i$-th vertex, assign the color $i \\bmod 4 + 1$. This ensures that any two vertices of the same color have a difference that is a multiple of $4$, so their XOR is a multiple of $4$, which is not a prime number. For $n < 6$, the example provides the coloring for all cases: $n = 1$: A valid coloring is $[1]$. $n = 2$: A valid coloring is $[1, 2]$. $n = 3$: A valid coloring is $[1, 2, 2]$. $n = 4$: A valid coloring is $[1, 2, 2, 3]$. $n = 5$: A valid coloring is $[1, 2, 2, 3, 3]$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    int n;\n    cin >> n;\n    if (n < 6) {\n        if (n == 1)\n            cout << 1 << '\\n' << \"1\" << '\\n';\n        else if (n == 2)\n            cout << 2 << '\\n' << \"1 2\" << '\\n';\n        else if (n == 3)\n            cout << 2 << '\\n' << \"1 2 2\" << '\\n';\n        else if (n == 4)\n            cout << 3 << '\\n' << \"1 2 2 3\" << '\\n';\n        else if (n == 5)\n            cout << 3 << '\\n' << \"1 2 2 3 3\" << '\\n';\n    } else {\n        cout << 4 << '\\n';\n        for (int i = 1; i <= n; i++)\n            cout << i % 4 + 1 << ' ';\n        cout << '\\n';\n    }\n}\nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "graphs",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1991",
    "index": "E",
    "title": "Coloring Game",
    "statement": "This is an interactive problem.\n\nConsider an undirected connected graph consisting of $n$ vertices and $m$ edges. Each vertex can be colored with one of three colors: $1$, $2$, or $3$. Initially, all vertices are uncolored.\n\nAlice and Bob are playing a game consisting of $n$ rounds. In each round, the following two-step process happens:\n\n- Alice chooses two \\textbf{different} colors.\n- Bob chooses an uncolored vertex and colors it with one of the two colors chosen by Alice.\n\nAlice wins if there exists an edge connecting two vertices of the same color. Otherwise, Bob wins.\n\nYou are given the graph. Your task is to decide which player you wish to play as and win the game.",
    "tutorial": "Determine if the graph is bipartite. If the graph is not bipartite, Alice will win. If the graph is bipartite, Bob will win. If the graph is not bipartite, Alice can always choose colors $1$ and $2$. According to the definition of a non-bipartite graph, Bob cannot color the graph with two colors without having two adjacent vertices of the same color. If the graph is bipartite, it can be divided into two parts, Part $1$ and Part $2$, with no edges within each part. If the colors chosen by Alice include color $1$, Bob can paint vertices in part $1$ with color $1$. If the colors chosen by Alice include color $2$, Bob can paint vertices in part $2$ with color $2$. Once one part is completely painted, Bob can use color $3$ or continue using the original color of that part to paint the remaining vertices, ensuring no two adjacent vertices have the same color. In this way, Bob will win.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 1e4 + 5;\nint n, m, color[MAX_N], isBipartite;\nvector<int> graph[MAX_N];\nvoid dfs(int vertex) {\n    for (auto neighbor: graph[vertex])\n        if (!color[neighbor]) {\n            color[neighbor] = 3 — color[vertex];\n            dfs(neighbor);\n        } else if (color[neighbor] + color[vertex] != 3)\n            isBipartite = 0;\n}\nvoid solve() {\n    cin >> n >> m;\n    for (int i = 1; i <= n; i++) {\n        graph[i].clear();\n        color[i] = 0;\n    }\n    for (int i = 1; i <= m; i++) {\n        int u, v;\n        cin >> u >> v;\n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n    isBipartite = 1;\n    color[1] = 1;\n    dfs(1);\n    if (!isBipartite) {\n        cout << \"Alice\" << endl;\n        for (int i = 1; i <= n; i++) {\n            cout << 1 << ' ' << 2 << endl;\n            int vertex, chosenColor;\n            cin >> vertex >> chosenColor;\n        }\n    } else {\n        cout << \"Bob\" << endl;\n        vector<int> part1, part2;\n        for (int i = 1; i <= n; i++)\n            if (color[i] == 1)\n                part1.push_back(i);\n            else\n                part2.push_back(i);\n        for (int i = 1; i <= n; i++) {\n            int color1, color2;\n            cin >> color1 >> color2;\n            if ((color1 == 1 || color2 == 1) && part1.size()) {\n                cout << part1.back() << ' ' << 1 << endl;\n                part1.pop_back();\n            } else if ((color1 == 2 || color2 == 2) && part2.size()) {\n                cout << part2.back() << ' ' << 2 << endl;\n                part2.pop_back();\n            } else if (!part1.size()) {\n                int chosenColor = (color1 == 1 ? color2 : color1);\n                cout << part2.back() << ' ' << chosenColor << endl;\n                part2.pop_back();\n            } else {\n                int chosenColor = (color1 == 2 ? color2 : color1);\n                cout << part1.back() << ' ' << chosenColor << endl;\n                part1.pop_back();\n            }\n        }\n    }\n}\nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "games",
      "graphs",
      "greedy",
      "interactive"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1991",
    "index": "F",
    "title": "Triangle Formation",
    "statement": "You are given $n$ sticks, numbered from $1$ to $n$. The length of the $i$-th stick is $a_i$.\n\nYou need to answer $q$ queries. In each query, you are given two integers $l$ and $r$ ($1 \\le l < r \\le n$, $r - l + 1 \\ge 6$). Determine whether it is possible to choose $6$ \\textbf{distinct} sticks from the sticks numbered $l$ to $r$, to form $2$ \\textbf{non-degenerate} triangles$^{\\text{∗}}$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A triangle with side lengths $a$, $b$, and $c$ is called non-degenerate if:\n\n- $a < b + c$,\n- $b < a + c$, and\n- $c < a + b$.\n\n\\end{footnotesize}",
    "tutorial": "Under the constraints of the problem, there exists a (small) integer $C$ such that for intervals longer than $C$, it is guaranteed to form two triangles. If there are at least $45$ sticks, it is guaranteed to form a triangle. Proof: For any sequence of stick lengths that cannot form a triangle, we can replace it with the Fibonacci sequence. By replacing the sticks in increasing order, the sequence will remain incapable of forming a triangle. This implies that the Fibonacci sequence is one of the longest sequences that cannot form a triangle. The $45$th Fibonacci number exceeds $10^9$. Therefore, having at least $45$ sticks ensures that it is possible to form a triangle. If there are at least $48$ sticks, it is guaranteed to form two triangles. Proof: We can first form the first triangle and remove those sticks. The remaining number of sticks is still at least $45$, which is sufficient to form the second triangle. Therefore, only for intervals with fewer than $48$ sticks, we need to check whether it is possible to form two triangles. First, we sort the sticks within the interval. Then we use the following algorithm to find two triangles: Algorithm 1: Enumerate all possible sets of $6$ consecutive sticks and check if they can form two triangles. Algorithm 2: Identify all possible sets of $3$ consecutive sticks that can form a triangle, and check if there exist two disjoint sets among them. If neither algorithm can find two triangles, then it is impossible to form two triangles within the given interval. Proof: Consider an interval where Algorithm 1 cannot find two triangles. Suppose it is indeed possible to form two triangles; the six sticks must be non-consecutive. For any unselected sticks between the chosen sticks, if there exists a stick to its left and a stick to its right that belongs to the same triangle, we can replace the leftmost stick of this triangle with the unselected stick. Continuing this process, either the six sticks will become consecutive, or the left side will form one triangle and the right side will form another, which can be detected by Algorithm 2.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 1e5 + 5;\nint n, q, a[MAX_N], p[MAX_N];\nbool canFormTwoTriangles(int l, int r) {\n    int t = 0;\n    for (int i = l; i <= r; i++)\n        p[++t] = a[i];\n    sort(p + 1, p + t + 1);\n    for (int i = 1; i <= t - 5; i++)\n        for (int j = i + 1; j <= i + 5; j++)\n            for (int k = j + 1; k <= i + 5; k++) {\n                int q[4], c = 0;\n                for (int m = i + 1; m <= i + 5; m++)\n                    if (m != j && m != k)\n                        q[++c] = p[m];\n                if (p[i] + p[j] > p[k] && q[1] + q[2] > q[3])\n                    return true;\n            }\n    int triangleCount = 0;\n    for (int i = 1; i <= t - 2; i++)\n        if (p[i] + p[i + 1] > p[i + 2]) {\n            i += 2;\n            triangleCount++;\n        }\n    return triangleCount > 1;\n}\nint main() {\n    cin >> n >> q;\n    for (int i = 1; i <= n; i++)\n        cin >> a[i];\n    while (q--) {\n        int l, r;\n        cin >> l >> r;\n        if (r — l + 1 >= 48 || canFormTwoTriangles(l, r))\n            cout << \"YES\" << '\\n';\n        else\n            cout << \"NO\" << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1991",
    "index": "G",
    "title": "Grid Reset",
    "statement": "You are given a grid consisting of $n$ rows and $m$ columns, where each cell is initially white. Additionally, you are given an integer $k$, where $1 \\le k \\le \\min(n, m)$.\n\nYou will process $q$ operations of two types:\n\n- $\\mathtt{H}$ (horizontal operation) — You choose a $1 \\times k$ rectangle completely within the grid, where all cells in this rectangle are white. Then, all cells in this rectangle are changed to black.\n- $\\mathtt{V}$ (vertical operation) — You choose a $k \\times 1$ rectangle completely within the grid, where all cells in this rectangle are white. Then, all cells in this rectangle are changed to black.\n\nAfter each operation, if any rows or columns become completely black, all cells in these rows and columns are \\textbf{simultaneously} reset to white. Specifically, if all cells in the row and column a cell is contained in become black, all cells in both the row and column will be reset to white.\n\nChoose the rectangles in a way that you can perform all given operations, or determine that it is impossible.",
    "tutorial": "Perform horizontal operations only on the leftmost $k$ columns and vertical operations only on the topmost $k$ rows. Prioritize operations that will lead to a reset. Here is a strategy to ensure you can perform operations infinitely: Perform horizontal operations only on the leftmost $k$ columns and vertical operations only on the topmost $k$ rows. Prioritize operations that will lead to a reset. If multiple operations can cause a reset, perform any of them; if no operations can cause a reset, perform any available operation. Proof of Correctness For a $n \\times m$ grid, we define it to be in a horizontal state if its black cells can be covered by non-overlapping $1 \\times m$ rectangles without gaps. Similarly, the grid is in a vertical state if its black cells can be covered by non-overlapping $n \\times 1$ rectangles without gaps. Our strategy ensures the grid always satisfies the following properties: The $k \\times k$ region in the top-left corner, the $(n-k) \\times k$ region in the bottom-left corner, and the $k \\times (m-k)$ region in the top-right corner are either in a horizontal state, vertical state, or both. The top-left and bottom-left regions cannot both be purely in a vertical state; similarly, the top-left and top-right regions cannot both be purely in a horizontal state. We will prove two points: first, when these properties are satisfied, there is always a valid operation; second, after performing operations according to our strategy, the grid still satisfies these properties. Existence of Valid Operations Assume the current operation is horizontal (the proof for vertical operations is similar). If the top-left and bottom-left regions cannot perform a horizontal operation, they must be completely black or in a purely vertical state. If one region is completely black, the other cannot be completely black or purely vertical, because that would have led to a reset earlier. According to the second property, the top-left and bottom-left regions cannot both be in a purely vertical state. Therefore, there is always a valid operation. Maintaining the First Property For the bottom-left and top-right regions, they always satisfy the first property. Proof: Consider the bottom-left region (the proof for the top-right region is similar). It starts as completely white, turning black row by row, maintaining a horizontal state. Once it is completely black, it resets column by column, maintaining a vertical state. Thus, it alternates between horizontal and vertical states. For the top-left region, it always satisfies the first property. Proof: After coloring and before resetting, the top-left region still satisfies the first property. Suppose it is in a horizontal state before resetting (the proof for a vertical state is similar). Since it cannot reset vertically, it remains at least in a horizontal state after resetting. If it becomes completely black and resets horizontally (the proof for a vertical reset is similar), it remains in a horizontal state. Unless $k = 1$, rows and columns cannot reset simultaneously. Suppose both rows and columns can reset, and assume the current operation is horizontal in the top-left region (the proof for a vertical operation is similar). This means the top-left region was in a purely horizontal state before turning completely black. The row in the top-right region was completely black, while other rows were white, contradicting the second property before the operation. Maintaining the Second Property Assume the current operation is horizontal (the proof for vertical operations is similar) and causes a reset, the second property still holds. Proof: If the operation is in the bottom-left region, it was completely black before resetting. After resetting, the top-left region turns completely white, maintaining the second property. We previously proved that unless $k = 1$, rows and columns cannot reset simultaneously. If the horizontal operation is in the top-left region and columns reset, the top-left region was completely black before resetting. After resetting, the top-left region becomes vertical, while the bottom-left region turns white, maintaining the second property. If the horizontal operation is in the top-left region and rows reset, the top-left region remains unchanged, while the row in the top-right region turns white. If the top-right region's state changes and resets to a purely horizontal state (the only possible violation of the second property), the top-right region is completely black before resetting. Thus, the top-left region was not in a purely horizontal state before resetting. Since the top-left region remains unchanged, it cannot be in a purely horizontal state, maintaining the second property. Assume the current operation is horizontal (the proof for vertical operations is similar) and does not cause a reset, the second property still holds. Proof: If the operation is in the bottom-left region, it remains in a horizontal state, maintaining the second property. If the operation is in the top-left region, the only possible violation of the second property is if the top-right region remains in a purely horizontal state while the top-left region becomes purely horizontal. This means the top-left region was completely white before the operation. In this case, we can choose to reset any completely black row in the top-right region. According to the strategy, we prioritize resets, leading to a contradiction. Thus, the second property still holds.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_SIZE = 105;\nchar operationType;\nint n, m, k, q, grid[MAX_SIZE][MAX_SIZE];\nstring s;\nint calculateSum(int x1, int y1, int x2, int y2) {\n    int sum = 0;\n    for (int i = x1; i <= x2; i++)\n        for (int j = y1; j <= y2; j++)\n            sum += grid[i][j];\n    return sum;\n}\nvoid performOperation(int x, int y) {\n    cout << x << ' ' << y << '\\n';\n    for (int i = 1; i <= k; i++) {\n        grid[x][y] = 1;\n        if (operationType == 'H')\n            y++;\n        else\n            x++;\n    }\n    int rowSums[MAX_SIZE] = {}, colSums[MAX_SIZE] = {};\n    for (int i = 1; i <= n; i++)\n        for (int j = 1; j <= m; j++) {\n            rowSums[i] += grid[i][j];\n            colSums[j] += grid[i][j];\n        }\n    for (int i = 1; i <= n; i++)\n        for (int j = 1; j <= m; j++)\n            if (rowSums[i] == m || colSums[j] == n)\n                grid[i][j] = 0;\n}\nvoid solve() {\n    cin >> n >> m >> k >> q >> s;\n    s = ' ' + s;\n    memset(grid, 0, sizeof(grid));\n    for (int i = 1; i <= q; i++) {\n        operationType = s[i];\n        if (operationType == 'H') {\n            int row = -1;\n            for (int j = 1; j <= n; j++)\n                if (calculateSum(j, 1, j, k) == 0) {\n                    row = j;\n                    if (calculateSum(j, 1, j, m) == m - k) {\n                        break;\n                    }\n                }\n            performOperation(row, 1);\n        } else {\n            int col = -1;\n            for (int j = 1; j <= m; j++)\n                if (calculateSum(1, j, k, j) == 0) {\n                    col = j;\n                    if (calculateSum(1, j, n, j) == n - k) {\n                        break;\n                    }\n                }\n            performOperation(1, col);\n        }\n    }\n}\nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1991",
    "index": "H",
    "title": "Prime Split Game",
    "statement": "Alice and Bob are playing a game with $n$ piles of stones, where the $i$-th pile has $a_i$ stones. Players take turns making moves, with Alice going first.\n\nOn each move, the player does the following three-step process:\n\n- Choose an integer $k$ ($1 \\leq k \\leq \\frac n 2$). Note that the value of $k$ can be different for different moves.\n- Remove $k$ piles of stones.\n- Choose another $k$ piles of stones and split each pile into two piles. The number of stones in each new pile must be a prime number.\n\nThe player who is unable to make a move loses.\n\nDetermine who will win if both players play optimally.",
    "tutorial": "Consider which pairs of numbers an odd number can be split into. What about an even number? Consider a simplified version of the game with only two piles of stones, where the first pile contains $x$ stones, and the second pile contains one stone. Determine all winning positions for this game configuration. For the simplified version of the game, given that we have calculated the odd $x$ which are losing positions, we can quickly determine the winning positions for even $x$ using Fast Fourier Transform or bitset operations. We can determine the winner of most games by considering how many $a_i$ are in winning positions and whether $n$ is odd or even. For games where we currently cannot determine the winner, we can use the number of $a_i$ that can be split into two winning positions to determine the final winner. Let's analyze this problem from simple to complex scenarios. First, let's consider how to split a single number $x$: For an odd number $x$, it can only be split into $x - 2$ and $2$. Proof: An odd number can only be split into an odd and an even number, and the only even prime is $2$. For an even number $x$, apart from $x = 4$ which can be split into $2$ and $2$, it can only be split into two odd numbers. Proof: An even number can only be split into odd and odd, or even and even. The only even prime is $2$, thus only $4$ can be split into even and even. Next, let's consider a simplified version of the game with only two piles of stones, where the first pile contains $x$ stones, and the second pile contains one stone. If Alice wins in this setup, we call $x$ a winning position; otherwise, it is a losing position. We first determine whether an odd $x$ is a winning position, then determine whether an even $x$ is a winning position: For an odd $x$, we need to calculate how many times $2$ stones can be split from $x$ until $x - 2$ is not a prime. If the number of splits is odd, then it is a winning position; otherwise, it is a losing position. For an even $x$, if $x$ can be split into two losing positions, then $x$ is a winning position; otherwise, $x$ is a losing position. Apart from $x = 4$ (a winning position), other even numbers can only be split into two odd numbers. Optimization: Directly checking all ways to split each even number will time out. However, we can use the Fast Fourier Transform (FFT) or bitset operations, based on the losing positions of odd numbers, to determine the winning positions of even numbers. If you are not familiar with this optimization technique, it is recommended to first solve 2014 ICPC SWERC Problem C Golf Bot, the tutorial is here. In summary, the characteristics of winning and losing positions are: losing positions either cannot be split, or they must split out at least one winning position. Winning positions can be split into two losing positions. Let's return to the original game. If all $a_i$ are in losing positions, Bob will win. Proof: No matter how Alice moves, Bob can always turn all $a_i$ back to losing positions. Suppose Alice splits to produce $2 \\cdot k$ new piles in one move, then at least $k$ of them will be in winning positions. Bob can split these $k$ piles into $2 \\cdot k$ losing positions and remove the remaining $k$ new piles. As a result, all piles will be back in losing positions. This process will continue until no more losing positions can be split, which will lead to Bob's win. Since we now have a general scenario where Bob wins, we can discuss all scenarios that can turn into this scenario with one move. In these scenarios, Alice will win: When $n$ is even and the number of winning positions $a_i$ ranges between $[1, n]$, Alice will win. Proof: Assuming the number of winning positions is $w$, Alice can choose $k = \\lceil \\frac{w}{2} \\rceil$ to select $k$ winning positions and split them into $2 \\cdot k$ losing positions. She then removes other winning positions and may remove one extra pile, to sum up $k$ piles. After the move, all piles will be turned into losing positions, ensuring Alice's win. When $n$ is odd and the number of winning positions $a_i$ ranges between $[1, n-1]$, Alice will win. Proof: Similar to the previous proof, Alice can turn all piles into losing positions in one move. The only unresolved case is when $n$ is odd and the number of winning positions $a_i$ equals $n$. Alice cannot turn all positions into losing positions in one move because at most $2 \\cdot k$ positions can be changed in a single move. Since $2 \\cdot k < n$, it is impossible to change all $n$ positions. In this case, if someone splits a winning position into a losing position, the number of winning positions will drop to $[1, n - 1]$, leading to failure. However, winning positions can sometimes be split into two winning positions. Therefore, we only need to consider this splitting case. A number is called a good position if it can be split into two winning positions; otherwise, it is called a bad position. We find that odd numbers cannot be good positions because they can only be split into $x - 2$ and $2$, and $2$ is not a winning position. Thus, only even numbers can be good positions if they can be split into two odd winning positions. Optimization: Directly checking ways to split each even number will time out. We can use FFT or bitset operations to identify good positions among even numbers. Note that good positions can only be split into two bad positions because even numbers can only be split into odd numbers or $2$, both of which are considered bad positions. Thus, when $n$ is odd and all $a_i$ are in winning positions, we only need to determine the winner based on the number of good positions: If the number of good positions $a_i$ is $0$, Bob will win. Proof: Any move by Alice will produce losing positions, as analyzed earlier, leading to failure. If the number of good positions $a_i$ is between $[1, n - 1]$, Alice will win. Proof: In one move, Alice can turn all numbers into bad positions using a method similar to when $n$ is odd and winning positions are between $[1, n - 1]$. If the number of good positions $a_i$ is $n$, Bob will win. Proof: Any move by Alice will produce losing or bad positions, ultimately leading to the previous scenario and resulting in failure.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 2e5 + 5;\nbitset<MAX_N + 1> isComposite, isWinning, isPrimeLosing, isPrimeWinning, isGoodPosition;\nvoid initialize() {\n    isComposite[1] = true;\n    for (int i = 2; i <= MAX_N; i++)\n        for (int j = 2 * i; j <= MAX_N; j += i)\n            isComposite[j] = true;\n    for (int i = 3; i <= MAX_N; i += 2) {\n        int count = 0, j = i;\n        while (!isComposite[j - 2]) {\n            count++;\n            j -= 2;\n        }\n        isWinning[i] = count % 2;\n        isPrimeLosing[i] = !isComposite[i] && !isWinning[i];\n    }\n    isWinning[4] = true;\n    for (int i = 3; i <= MAX_N; i += 2)\n        if (isPrimeLosing[i])\n            isWinning |= isPrimeLosing << i;\n    for (int i = 1; i <= MAX_N; ++i)\n        isPrimeWinning[i] = (i % 2) && isWinning[i] && !isComposite[i];\n    for (int i = 3; i <= MAX_N; i += 2)\n        if (isPrimeWinning[i])\n            isGoodPosition |= isPrimeWinning << i;\n}\nvoid solve() {\n    int n, x, totalWinning = 0, totalGood = 0;\n    cin >> n;\n    for (int i = 1; i <= n; ++i) {\n        cin >> x;\n        totalWinning += isWinning[x];\n        totalGood += isGoodPosition[x];\n    }\n    if (totalWinning <= n - n % 2)\n        cout << (totalWinning ? \"Alice\" : \"Bob\") << endl;\n    else\n        cout << (totalGood && totalGood < n ? \"Alice\" : \"Bob\") << endl;\n}\nint main() {\n    initialize();\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "bitmasks",
      "dp",
      "fft",
      "games",
      "math",
      "number theory"
    ],
    "rating": 3300
  },
  {
    "contest_id": "1991",
    "index": "I",
    "title": "Grid Game",
    "statement": "This is an interactive problem.\n\nYou are given a grid with $n$ rows and $m$ columns. You need to fill each cell with a unique integer from $1$ to $n \\cdot m$.\n\nAfter filling the grid, you will play a game on this grid against the interactor. Players take turns selecting one of the previously unselected cells from the grid, with the interactor going first.\n\nOn the first turn, the interactor can choose any cell from the grid. After that, any chosen cell must be orthogonally adjacent to at least one previously selected cell. Two cells are considered orthogonally adjacent if they share an edge. The game continues until all cells have been selected.\n\nYour goal is to let the sum of numbers in the cells selected by you be \\textbf{strictly} less than the sum of numbers in the cells selected by the interactor.",
    "tutorial": "Notice that if the problem requires our selected numbers' sum to be greater than the interactor's sum, instead of smaller, the essence of the problem changes. Depending on whether $n \\cdot m$ is odd or even, we can use different methods to fill the grid and adapt our game strategy. When $n \\cdot m$ is odd, we can adopt a strategy that forces the interactor to choose the largest number, $n \\cdot m$. When $n \\cdot m$ is even, we can divide the grid into several tiles. After the interactor chooses a number from a tile, we immediately choose from the same tile. We set each tile size to be even, ensuring we always select the second number from each tile. When $n \\cdot m$ is even, we can create some T-shaped tiles at the edges of the grid, where each T-shaped tile consists of a cell on the edge and three cells surrounding it. Place a small number in the center of each T-shaped tile, and fill the surrounding three cells with large numbers. This way, we can always select the smallest number from each T-shaped tile, except for the interactor's first choice. When $n \\cdot m$ is even, we only need to create $4$ T-shaped tiles and divide the remaining cells into several dominos, each containing two adjacent numbers. This method of filling numbers is sufficient to ensure that the sum of the numbers we choose is smaller. Notice that if the problem requires our selected numbers' sum to be greater than the interactor's sum, instead of smaller, the essence of the problem changes. Specifically, when $n \\cdot m$ is odd, the interactor will select one more number than us. If the goal is to have a greater sum of numbers, the interactor will have an advantage; conversely, if the goal is to have a smaller sum, we will have an advantage. Depending on whether $n \\cdot m$ is odd or even, we can use different methods to fill the grid and adapt our game strategy. Here, we will explain these two methods and strategies in detail. When $n \\cdot m$ is odd, we can adopt a strategy that forces the interactor to choose the largest number, $n \\cdot m$. Specifically, we can divide the grid into: $\\lfloor \\frac{n \\cdot m}{2} \\rfloor$ dominos ($1 \\times 2$ or $2 \\times 1$ tiles), each containing two adjacent numbers. In the remaining single cell, we place the largest number. Our strategy is as follows: If the interactor chooses a number from a domino and the other number has not yet been chosen, we choose that number; otherwise, we choose any valid number from the dominos. This ensures that: In each domino, both we and the interactor select one number. Proof: The interactor cannot choose both numbers in a domino because as soon as they choose the first one, we immediately choose the second one. Therefore, we select at least one number in each domino. We cannot select two numbers in any domino because our total number of selections would exceed the number of dominos, which equals our total number of selections. Hence, we exactly select one number in each domino. The interactor will inevitably choose the largest number. Proof: Since we only choose numbers from the dominos, the remaining largest number will not be selected by us. In the worst case, we will choose the larger number in each domino. However, the interactor will always select the largest number. Therefore, in this scenario, our sum will be less than the interactor's sum by $n \\cdot m - \\lfloor \\frac{n \\cdot m}{2} \\rfloor = \\lceil \\frac{n \\cdot m}{2} \\rceil$. When $n \\cdot m$ is even, we can divide the grid into several tiles. After the interactor chooses a number from a tile, we immediately choose from the same tile. We set each tile size to be even, ensuring we always select the second number from each tile. If a small number is surrounded by large numbers in a tile, as the second chooser we can choose the small number. We place the small numbers on the edges of the grid, where the number of surrounding cells is odd, ensuring that each tile has an even number of cells. This tiling arrangement gives us a significant advantage; only a few such tiles are needed, while the rest of the grid can be filled with dominos containing adjacent numbers, making our sum of numbers smaller. Here are the detailed descriptions of grid filling and game strategy: We divide the grid into: $4$ T-shaped tiles, each with a small number at the edge of the grid, surrounded by three large numbers. $\\frac{n \\cdot m - 16}{2}$ dominos, each containing two adjacent numbers. Specifically, we define $[1, 4]$ as small numbers, and $[n \\cdot m - 11, n \\cdot m]$ as large numbers. Numbers $[n \\cdot m - 11, n \\cdot m - 9]$ surround number $1$, $[n \\cdot m - 8, n \\cdot m - 6]$ surround number $2$, $[n \\cdot m - 5, n \\cdot m - 3]$ surround number $3$, and $[n \\cdot m - 2, n \\cdot m]$ surround number $4$. Assuming $n \\le m$, we divide the grid as follows: For $n = 4$ and $m = 4$, as well as $n = 4$ and $m = 5$, we manually divide the grid. This is a specific layout for a $4 \\times 4$ grid, with bold lines indicating tiles division, green cells representing small numbers, and red cells representing large numbers. This is a specific layout for a $4 \\times 5$ grid, with additional settings, where yellow cells represent adjacent numbers in dominos. For $m \\geq 6$, we place two T-shaped tiles and two dominos in the top left and top right $4 \\times 3$ areas. The remaining part of the top four rows can be filled with vertical dominos. For rows beyond the top four, if $m$ is even, we fill them with horizontal dominos; if $m$ is odd, we fill them with vertical dominos. This is a specific layout for a $5 \\times 8$ grid, an example where $m$ is even. This is a specific layout for a $6 \\times 7$ grid, an example where $m$ is odd. Our strategy is as follows: After the interactor chooses a number from a tile, we will immediately choose the smallest valid number from the same tile. This ensures that the interactor can only start choosing from the large numbers in each T-shaped tile, allowing us to choose the small number, except for the small number that the interactor initially chooses. Next, we will analyze why this strategy ensures a smaller sum. For each T-shaped tile, if the interactor did not initially choose from this tile, we can at least choose the smallest and largest numbers; if the interactor initially chose from this tile, we can at least choose the second smallest and largest numbers. We find that if the interactor chooses to start from the T-shaped tile, they take away our smallest number and give us the second smallest number. Thus, in the worst case, the interactor starts choosing from number $4$, where the difference between the smallest and second smallest numbers in that tile is the largest. In dominos, we assume we will choose the larger number. In the worst case, the calculation of our sum of numbers minus the interactor's sum of numbers is: $(1 - (n \\cdot m - 11) - (n \\cdot m - 10) + (n \\cdot m - 9)) +$ $(2 - (n \\cdot m - 8) - (n \\cdot m - 7) + (n \\cdot m - 6)) +$ $(3 - (n \\cdot m - 5) - (n \\cdot m - 4) + (n \\cdot m - 3)) +$ $(-4 + (n \\cdot m - 2) - (n \\cdot m - 1) + n \\cdot m) +$ $(n \\cdot m - 16) / 2 =$ $20 - 1.5 \\cdot n \\cdot m$ When $n$ and $m$ are at their minimum, this value is the largest and unfavorable for us. However, when $n$ and $m$ are at their minimum of $4$, our sum of numbers is still $4$ less than the interactor's ($20 - 1.5 \\cdot 4 \\cdot 4 = -4$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int MAX_N = 15, dx[] = {-1, 0, 0, 1}, dy[] = {0, -1, 1, 0};\nint n, m, x, y, grid[MAX_N][MAX_N], color[MAX_N][MAX_N], visited[MAX_N][MAX_N], currentValue, currentColor, flipCoords;\nbool isAdjacent(int x, int y) {\n    int nx, ny;\n    for (int i = 0; i < 4; i++) {\n        nx = x + dx[i];\n        ny = y + dy[i];\n        if (1 <= nx && nx <= n && 1 <= ny && ny <= m && visited[nx][ny])\n            return true;\n    }\n    return false;\n}\nvoid interact() {\n    cin >> x >> y;\n    if (flipCoords)\n        swap(x, y);\n    visited[x][y] = 1;\n}\nvoid output(int x, int y) {\n    visited[x][y] = 1;\n    if (flipCoords)\n        cout << y << ' ' << x << endl;\n    else\n        cout << x << ' ' << y << endl;\n}\nvoid placePair(int x1, int y1, int x2, int y2) {\n    grid[x1][y1] = ++currentValue;\n    grid[x2][y2] = ++currentValue;\n    color[x1][y1] = color[x2][y2] = ++currentColor;\n}\nvoid placeTShape(int x, int y) {\n    int largestValue = n * m - 12 + currentColor * 3;\n    grid[x][y] = ++currentValue;\n    color[x][y] = ++currentColor;\n    int nx, ny;\n    for (int i = 0; i < 4; i++) {\n        nx = x + dx[i];\n        ny = y + dy[i];\n        if (1 <= nx && nx <= n && 1 <= ny && ny <= m) {\n            grid[nx][ny] = ++largestValue;\n            color[nx][ny] = currentColor;\n        }\n    }\n}\nvoid printGrid() {\n    if (!flipCoords)\n        for (int i = 1; i <= n; i++) {\n            for (int j = 1; j <= m; j++) {\n                cout << grid[i][j] << ' ';\n            }\n            cout << endl;\n        }\n    else\n        for (int i = 1; i <= m; i++) {\n            for (int j = 1; j <= n; j++) {\n                cout << grid[j][i] << ' ';\n            }\n            cout << endl;\n        }\n}\nvoid fillHorizontalPairs() {\n    for (int i = 1; i <= n; i++)\n        for (int j = 1; j < m; j++)\n            if (!grid[i][j] && !grid[i][j + 1])\n                placePair(i, j, i, j + 1);\n}\nvoid fillVerticalPairs() {\n    for (int i = 1; i < n; i++)\n        for (int j = 1; j <= m; j++)\n            if (!grid[i][j] && !grid[i + 1][j])\n                placePair(i, j, i + 1, j);\n}\nvoid solve() {\n    cin >> n >> m;\n    memset(grid, 0, sizeof(grid));\n    memset(color, 0, sizeof(color));\n    memset(visited, 0, sizeof(visited));\n    currentColor = currentValue = flipCoords = 0;\n    if (n % 2 == 1 && m % 2 == 1) {\n        for (int i = 1; i <= n; i++)\n            for (int j = 1; j < m; j += 2)\n                placePair(i, j, i, j + 1);\n        for (int i = 1; i <= n; i += 2)\n            placePair(i, m, i + 1, m);\n        grid[n][m] = n * m;\n        printGrid();\n        for (int i = 1; i < n * m; i += 2) {\n            interact();\n            bool selected = false;\n            for (int i = 1; i <= n; i++) {\n                for (int j = 1; j <= m; j++)\n                    if (!visited[i][j] && color[i][j] == color[x][y]) {\n                        output(i, j);\n                        selected = true;\n                        break;\n                    }\n                if (selected)\n                    break;\n            }\n            if (selected)\n                continue;\n            for (int i = 1; i <= n; i++)\n                for (int j = 1; j <= m; j++)\n                    if (!visited[i][j] && isAdjacent(i, j) && grid[i][j] != n * m) {\n                        output(i, j);\n                        i = n;\n                        j = m;\n                    }\n        }\n        cin >> x >> y;\n        return;\n    }\n    if (n > m) {\n        swap(n, m);\n        flipCoords = 1;\n    }\n    if (n == 4 && m == 4) {\n        placeTShape(1, 2);\n        placeTShape(2, 4);\n        placeTShape(3, 1);\n        placeTShape(4, 3);\n    } else if (n == 4 && m == 5) {\n        placeTShape(1, 2);\n        placeTShape(3, 1);\n        placeTShape(3, 5);\n        placeTShape(4, 3);\n        fillHorizontalPairs();\n    } else {\n        placeTShape(1, 2);\n        placeTShape(3, 1);\n        placeTShape(1, m — 1);\n        placeTShape(3, m);\n        placePair(2, 3, 3, 3);\n        placePair(4, 2, 4, 3);\n        placePair(2, m — 2, 3, m — 2);\n        placePair(4, m — 2, 4, m — 1);\n        if (m % 2 == 0)\n            fillHorizontalPairs();\n        else\n            fillVerticalPairs();\n    }\n    printGrid();\n    for (int i = 1; i <= n * m; i += 2) {\n        interact();\n        pair bestMove = {-1,-1};\n        for (int i = 1; i <= n; i++)\n            for (int j = 1; j <= m; j++)\n                if (!visited[i][j] && color[i][j] == color[x][y] && (bestMove.first == -1 || grid[i][j] < grid[bestMove.first][bestMove.second]))\n                    bestMove = {i,j};\n        output(bestMove.first, bestMove.second);\n    }\n}\nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "games",
      "graph matchings",
      "greedy",
      "interactive"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1992",
    "index": "A",
    "title": "Only Pluses",
    "statement": "Kmes has written three integers $a$, $b$ and $c$ in order to remember that he has to give Noobish_Monk $a \\times b \\times c$ bananas.\n\nNoobish_Monk has found these integers and decided to do the following \\textbf{at most $5$ times}:\n\n- pick one of these integers;\n- increase it by $1$.\n\nFor example, if $a = 2$, $b = 3$ and $c = 4$, then one can increase $a$ three times by one and increase $b$ two times. After that $a = 5$, $b = 5$, $c = 4$. Then the total number of bananas will be $5 \\times 5 \\times 4 = 100$.\n\nWhat is the maximum value of $a \\times b \\times c$ Noobish_Monk can achieve with these operations?",
    "tutorial": "Let's prove why it's always better to add to the smallest number, let $a \\le b \\le c$, then compare the three expressions: $(a+1)\\times b \\times c$, $a \\times (b+1) \\times c$, and $a \\times b \\times (c+1)$. Remove the common part $a \\times b \\times c$, and we get: $b \\times c$, $a \\times c$, $a \\times b$. $b \\times c \\ge a \\times c$, since $a \\le b$, similarly, $b \\times c \\ge a \\times b$, since $a \\le c$. Therefore, we can simply find the minimum $5$ times and add one to it. And thus, obtain the answer. Another, primitive approach is to simply iterate through what we will add to $a$, $b$, and $c$ with three loops. Since we can only add $5$ times, the time complexity of the solution is $O(1)$.",
    "code": "for _ in range(int(input())):\n    arr = sorted(list(map(int,input().split())))\n    for i in range(5):\n        arr[0]+=1\n        arr.sort()\n    print(arr[0] * arr[1] * arr[2])",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1992",
    "index": "B",
    "title": "Angry Monk",
    "statement": "To celebrate his recovery, k1o0n has baked an enormous $n$ metres long potato casserole.\n\nTurns out, Noobish_Monk just can't stand potatoes, so he decided to ruin k1o0n's meal. He has cut it into $k$ pieces, of lengths $a_1, a_2, \\dots, a_k$ meters.\n\nk1o0n wasn't keen on that. Luckily, everything can be fixed. In order to do that, k1o0n can do one of the following operations:\n\n- Pick a piece with length $a_i \\ge 2$ and divide it into two pieces with lengths $1$ and $a_i - 1$. As a result, the number of pieces will increase by $1$;\n- Pick a slice $a_i$ and another slice with length $a_j=1$ ($i \\ne j$) and merge them into one piece with length $a_i+1$. As a result, the number of pieces will decrease by $1$.\n\nHelp k1o0n to find the minimum number of operations he needs to do in order to merge the casserole into one piece with length $n$.\n\nFor example, if $n=5$, $k=2$ and $a = [3, 2]$, it is optimal to do the following:\n\n- Divide the piece with length $2$ into two pieces with lengths $2-1=1$ and $1$, as a result $a = [3, 1, 1]$.\n- Merge the piece with length $3$ and the piece with length $1$, as a result $a = [4, 1]$.\n- Merge the piece with length $4$ and the piece with length $1$, as a result $a = [5]$.",
    "tutorial": "Let's say we want to connect two casseroles with lengths $x$ and $y$. We can disassemble one of them into pieces of length $1$ and then attach them to the casserole of size $y$. In total, we will perform $2x - 1$ operations. Since we want to connect $k$ pieces, at least $k - 1$ of them will have to be disassembled and then attached to something. If we attach something to a piece, there is no point in disassembling it, because to disassemble it, we will need to remove these pieces as well. Therefore, we want to choose a piece to which we will attach all the others. It will be optimal to choose a piece with the maximum size and attach everything to it. Thus, the answer is $2 \\cdot (n - mx) - k + 1$, where $mx$ $-$ the length of the maximum piece. Solution complexity: $O(n)$.",
    "code": "for _ in range(int(input())):\n    n,k = map(int,input().split())\n    mx = max(map(int, input().split()))\n    print((n - mx) * 2 - (k - 1))",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1992",
    "index": "C",
    "title": "Gorilla and Permutation",
    "statement": "Gorilla and Noobish_Monk found three numbers $n$, $m$, and $k$ ($m < k$). They decided to construct a permutation$^{\\dagger}$ of length $n$.\n\nFor the permutation, Noobish_Monk came up with the following function: $g(i)$ is the sum of all the numbers in the permutation on a prefix of length $i$ that are not greater than $m$. Similarly, Gorilla came up with the function $f$, where $f(i)$ is the sum of all the numbers in the permutation on a prefix of length $i$ that are not less than $k$. A prefix of length $i$ is a subarray consisting of the first $i$ elements of the original array.\n\nFor example, if $n = 5$, $m = 2$, $k = 5$, and the permutation is $[5, 3, 4, 1, 2]$, then:\n\n- $f(1) = 5$, because $5 \\ge 5$; $g(1) = 0$, because $5 > 2$;\n- $f(2) = 5$, because $3 < 5$; $g(2) = 0$, because $3 > 2$;\n- $f(3) = 5$, because $4 < 5$; $g(3) = 0$, because $4 > 2$;\n- $f(4) = 5$, because $1 < 5$; $g(4) = 1$, because $1 \\le 2$;\n- $f(5) = 5$, because $2 < 5$; $g(5) = 1 + 2 = 3$, because $2 \\le 2$.\n\nHelp them find a permutation for which the value of $\\left(\\sum_{i=1}^n f(i) - \\sum_{i=1}^n g(i)\\right)$ is maximized.\n\n$^{\\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation (as $2$ appears twice in the array) and $[1,3,4]$ is also not a permutation (as $n=3$, but $4$ appears in the array).",
    "tutorial": "Let $p$ be some permutation. Let's look at the contribution of the number $p_i$ to the sum $\\sum_{i=1}^n {f(i)}$. If it is less than $k$, the contribution is $0$, otherwise the contribution is $p_i \\cdot (n - i + 1)$. Similarly, let's look at the contribution of $p_i$ to the sum $\\sum_{i=1}^n {g(i)}$. If it is greater than $m$, the contribution is $0$, otherwise it is $p_i \\cdot (n - i + 1)$. Since $m < k$, each number gives a contribution greater than $0$ in at most one sum. Therefore, it is advantageous to place numbers not less than $k$ at the beginning, and numbers not greater than $m$ at the end. Also, numbers not less than $k$ should be in descending order to maximize the sum of $f(i)$. Similarly, numbers not greater than $m$ should be in ascending order to minimize the sum of $g(i)$. For example, you can construct such a permutation: $n, n - 1, \\ldots, k, m + 1, m + 2, \\ldots, k - 1, 1, 2, \\ldots, m$. It is easy to see that $\\sum_{i=1}^n f(i)$ cannot be greater for any other permutation, and $\\sum_{i=1}^n g(i)$ cannot be less for any other permutation, so our answer is optimal. Solution complexity: $O(n)$.",
    "code": "for _ in range(int(input()):\n    n,m,k = map(int,input().split())\n    print(*range(n,m,-1), *range(1,m))",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "1992",
    "index": "D",
    "title": "Test of Love",
    "statement": "ErnKor is ready to do anything for Julen, even to swim through crocodile-infested swamps. We decided to test this love. ErnKor will have to swim across a river with a width of $1$ meter and a length of $n$ meters.\n\nThe river is very cold. Therefore, \\textbf{in total} (that is, throughout the entire swim from $0$ to $n+1$) ErnKor can swim in the water for no more than $k$ meters. For the sake of humanity, we have added not only crocodiles to the river, but also logs on which he can jump. Our test is as follows:\n\nInitially, ErnKor is on the left bank and needs to reach the right bank. They are located at the $0$ and $n+1$ meters respectively. The river can be represented as $n$ segments, each with a length of $1$ meter. Each segment contains either a log 'L', a crocodile 'C', or just water 'W'. ErnKor can move as follows:\n\n- If he is on the surface (i.e., on the bank or on a log), he can jump forward for no more than $m$ ($1 \\le m \\le 10$) meters (he can jump on the bank, on a log, or in the water).\n- If he is in the water, he can only swim to the next river segment (or to the bank if he is at the $n$-th meter).\n- ErnKor cannot land in a segment with a crocodile in any way.\n\nDetermine if ErnKor can reach the right bank.",
    "tutorial": "In this problem, there are two main solutions: dynamic programming and greedy algorithm. Dynamic programming solution: $dp_i$ $-$ the minimum number of meters that need to be swum to reach the $i$-th cell. The base case of the dynamic programming is $dp_0 = 0$. Then, the update rule is: $\\begin{equation*} dp_i = \\text{minimum of} \\begin{cases} dp_{i-1} + 1& \\text{if } A_i = \\text{'W'} \\\\ min(dp_j) & \\text{for all } j, \\text{where:} \\max(0, i - m) \\le j < i \\text{ and } A_j = \\text{'L'} \\end{cases} \\end{equation*}$ Greedy algorithm solution: If we can jump, we want to jump to the shore if possible. If we can't, we want to jump to any log ahead to jump from it later. If we can't, we jump as far as possible to avoid crocodiles and swim as little as possible. Solution complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m, k; \n        cin >> n >> m >> k;\n        string s;\n        cin >> s;\n        vector<int> dp(n + 2, -1);\n        dp[0] = k;\n        for (int i = 1; i <= n + 1; i++) {\n            if (i != n + 1 && s[i - 1] == 'C') \n                continue;\n            for (int t = 1; t <= m; t++)\n                if (i - t >= 0 && (i - t == 0 || s[i - t - 1] == 'L'))\n                    dp[i] = max(dp[i], dp[i - t]);\n            if (i > 1 && s[i - 2] == 'W') \n                dp[i] = max(dp[i], dp[i - 1] - 1);\n        }\n        if (dp[n + 1] >= 0) \n            cout << \"YES\\n\";\n        else \n            cout << \"NO\\n\";\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1992",
    "index": "E",
    "title": "Novice's Mistake",
    "statement": "One of the first programming problems by K1o0n looked like this: \"Noobish_Monk has $n$ $(1 \\le n \\le 100)$ friends. Each of them gave him $a$ $(1 \\le a \\le 10000)$ apples for his birthday. Delighted with such a gift, Noobish_Monk returned $b$ $(1 \\le b \\le \\min(10000, a \\cdot n))$ apples to his friends. How many apples are left with Noobish_Monk?\"\n\nK1o0n wrote a solution, but accidentally considered the value of $n$ as a string, so the value of $n \\cdot a - b$ was calculated differently. Specifically:\n\n- when multiplying the string $n$ by the integer $a$, he will get the string $s=\\underbrace{n + n + \\dots + n + n}_{a\\ \\text{times}}$\n- when subtracting the integer $b$ from the string $s$, the last $b$ characters will be removed from it. If $b$ is greater than or equal to the length of the string $s$, it will become empty.\n\nLearning about this, ErnKor became interested in how many pairs $(a, b)$ exist for a given $n$, satisfying the constraints of the problem, on which K1o0n's solution gives the correct answer.\n\n\"The solution gives the correct answer\" means that it outputs a \\textbf{non-empty} string, and this string, when converted to an integer, equals the correct answer, i.e., the value of $n \\cdot a - b$.",
    "tutorial": "Notice that $n * a - b$ is strictly less than $10^6$, i.e., it has no more than $6$ digits. The number of characters in the strange calculation $n * a - b$ is equal to $|n| * a - b$, where $|n|$ is the number of digits in n. Let's iterate over the value of $a$, and then determine the boundaries $minB$ and $maxB$ for it, such that $|n| * a > maxB$ and $|n| * a - minB \\le 6$. Then: $\\begin{cases} minB = |n| * a- 6 \\\\ maxB = |n| * a- 1 \\end{cases}$ Solution complexity: $O(a)$.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    sn = str(n)\n    lenN = len(str(n))\n    ans = []\n    for a in range(1, 10001):\n        minB = max(1, lenN * a - 5)\n        maxB = lenN * a\n        for b in range(minB, maxB):\n            x = n * a - b\n            y = 0\n            for i in range(lenN * a - b):\n                y = y * 10 + int(sn[i % lenN])\n            if x == y:\n                ans.append((a, b))\n    print(len(ans))\n    for p in ans:\n        print(*p)",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "math",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1992",
    "index": "F",
    "title": "Valuable Cards",
    "statement": "In his favorite cafe Kmes once again wanted to try the herring under a fur coat. Previously, it would not have been difficult for him to do this, but the cafe recently introduced a new purchasing policy.\n\nNow, in order to make a purchase, Kmes needs to solve the following problem: $n$ cards with prices for different positions are laid out in front of him, on the $i$-th card there is an integer $a_i$, among these prices there is no whole positive integer $x$.\n\nKmes is asked to divide these cards into the minimum number of bad segments (so that each card belongs to exactly one segment). A segment is considered bad if it is impossible to select a subset of cards with a product equal to $x$. All segments, in which Kmes will divide the cards, must be bad.\n\nFormally, the segment $(l, r)$ is bad if there are no indices $i_1 < i_2 < \\ldots < i_k$ such that $l \\le i_1, i_k \\le r$, and $a_{i_1} \\cdot a_{i_2} \\ldots \\cdot a_{i_k} = x$.\n\nHelp Kmes determine the minimum number of bad segments in order to enjoy his favorite dish.",
    "tutorial": "Let's consider the greedy algorithm ``take as long as you can''. Let's prove that it works. In any optimal division, if we take the first segment of non-maximum length, we will not violate the criteria if we transfer one element from the second segment to the first. Therefore, the given greedy algorithm is correct. Now let's figure out how to quickly understand if the segment can be extended. First, find all divisors of the number $x$. If the number $a_i$ is not a divisor of it, then it cannot be included in any set of numbers whose product is equal to $x$, so we can simply add it to the segment. If $a_i$ is a divisor, we need to somehow learn to understand whether it, in combination with some other divisors, gives the number $x$ on the segment. We will maintain a set of divisors that are products of some numbers in the segment. To update the set when adding $a_i$, we will go through all the divisors of this set and for each divisor $d$ add $d \\cdot a_i$ to the set. If we added the number $x$ to the set, $a_i$ will already be in the next segment and we need to clear the set. P. S.: About implementation details and runtime. If you maintain the set in a set structure, then we get a runtime of $O(n \\cdot d(x) \\cdot \\log(d(x)))$, where $d(x)$ is the number of divisors of $x$. Instead of a set, you can use, for example, a global array $used$ of size $10^5 + 1$, as well as maintain a vector of reachable divisors. Using these structures, you can achieve a runtime of $O(n \\cdot d(x))$.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int A = 1e6 + 1;\nbool used[A];\nbool divs[A];\n\nvoid solve() {\n\tint n, x;\n\tcin >> n >> x;\n\tvector<int> a(n);\n\tvector<int> vecDivs;\n\tfor (int d = 1; d * d <= x; d++) {\n\t\tif (x % d == 0) {\n\t\t\tdivs[d] = true;\n\t\t\tvecDivs.push_back(d);\n\t\t\tif (d * d < x) {\n\t\t\t    vecDivs.push_back(x / d);\n\t\t\t\tdivs[x / d] = true;\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++)\n\t\tcin >> a[i];\n\tint ans = 1;\n\tused[1] = true;\n\tvector<int> cur{ 1 };\n\tfor (int i = 0; i < n; i++) {\n\t\tif (!divs[a[i]])\n\t\t\tcontinue;\n\t\tvector<int> ncur;\n\t\tbool ok = true;\n\t\tfor (int d : cur)\n\t\t\tif (1ll * d * a[i] <= x && divs[d * a[i]] && !used[d * a[i]]) {\n\t\t\t\tncur.push_back(d * a[i]);\n\t\t\t\tused[d * a[i]] = true;\n\t\t\t\tif (d * a[i] == x)\n\t\t\t\t\tok = false;\n\t\t\t}\n\t\tfor (int d : ncur)\n\t\t\tcur.push_back(d);\n\t\tif (!ok) {\n\t\t\tans++;\n\t\t\tfor (int d : cur)\n\t\t\t\tused[d] = false;\n\t\t\tused[1] = true;\n\t\t\tused[a[i]] = true;\n\t\t\tcur = vector<int>{ 1, a[i] };\n\t\t}\n\t}\n\tfor (int d : vecDivs) {\n\t    divs[d] = false;\n\t    used[d] = false;\n\t}\n\tcout << ans << '\\n';\n}\n\nsigned main() {\n    int T;\n    cin >> T;\n    while (T--)\n\t    solve();\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "number theory",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1992",
    "index": "G",
    "title": "Ultra-Meow",
    "statement": "K1o0n gave you an array $a$ of length $n$, consisting of numbers $1, 2, \\ldots, n$. Accept it? Of course! But what to do with it? Of course, calculate $\\text{MEOW}(a)$.\n\nLet $\\text{MEX}(S, k)$ be the $k$-th \\textbf{positive} (strictly greater than zero) integer in ascending order that is not present in the set $S$. Denote $\\text{MEOW}(a)$ as the sum of $\\text{MEX}(b, |b| + 1)$, over all \\textbf{distinct} subsets $b$ of the array $a$.\n\nExamples of $\\text{MEX}(S, k)$ values for sets:\n\n- $\\text{MEX}(\\{3,2\\}, 1) = 1$, because $1$ is the first positive integer not present in the set;\n- $\\text{MEX}(\\{4,2,1\\}, 2) = 5$, because the first two positive integers not present in the set are $3$ and $5$;\n- $\\text{MEX}(\\{\\}, 4) = 4$, because there are no numbers in the empty set, so the first $4$ positive integers not present in it are $1, 2, 3, 4$.",
    "tutorial": "We will iterate over the size of the set $k$ and its $\\text{MEOW}$, $m$. If $2k \\geqslant n$, then the set $x$ will fill all the remaining numbers up to $n$, and there may still be some larger than $n$ in it, so the $MEOW$ of all such sets will be $2k+1$, and there will be a total of $C(n, k)$ such sets for each $k$. If $2k < n$, $m$ lies in the interval from $k+1$ to $2k+1$. Notice that there can be exactly $m - 1 - k$ numbers before $m$, and correspondingly $2k + 1 - m$ numbers to the right of $m$, so the answer needs to be added with $C_{m - 1}^{m - 1 - k} \\cdot C_{n - m}^{2k + 1 - m} \\cdot m$. Asymptotic complexity of the solution: $O(n^2)$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int mod = 1e9 + 7;\n\nint add(int a, int b) {\n    if (a + b >= mod)\n        return a + b - mod;\n    return a + b;\n}\n\nint sub(int a, int b) {\n    if (a < b)\n        return a + mod - b;\n    return a - b;\n}\n\nint mul(int a, int b) {\n    return (int)((1ll * a * b) % mod);\n}\n\nint binpow(int a, int pw) {\n    int b = 1;\n    while (pw) {\n        if (pw & 1)\n            b = mul(b, a);\n        a = mul(a, a);\n        pw >>= 1;\n    }\n    return b;\n}\n\nint inv(int a) {\n    return binpow(a, mod - 2);\n}\n\nconst int N = 15000;\nint f[N], r[N];\n\nvoid precalc() {\n    f[0] = 1;\n    for (int i = 1; i < N; i++)\n        f[i] = mul(f[i - 1], i);\n    r[N - 1] = inv(f[N - 1]);\n    for (int i = N - 2; i > -1; i--)\n        r[i] = mul(r[i + 1], i + 1);\n}\n\nint C(int n, int k) {\n    if (n < 0 || k < 0 || n < k)\n        return 0;\n    return mul(f[n], mul(r[k], r[n - k]));\n}\n\ninline void solve() {\n    int n;\n    cin >> n;\n    int ans = 1;\n    for (int k = 1; k <= n; k++) {\n        if (2 * k >= n) {\n            ans = add(ans, mul(2 * k + 1, C(n, k)));\n            continue;\n        }\n        for (int m = k + 1; m <= 2 * k + 1; m++) {\n            int c = mul(C(m - 1, m - 1 - k), C(n - m, 2 * k + 1 - m));\n            ans = add(ans, mul(mul(C(m - 1, m - 1 - k), C(n - m, 2 * k + 1 - m)), m));\n        }\n    }\n    cout << ans << '\\n';\n}\n\nsigned main() {\n    int T = 1;\n    cin >> T;\n    precalc();\n    while(T--)\n        solve();\n    return 0;\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1993",
    "index": "A",
    "title": "Question Marks",
    "statement": "Tim is doing a test consisting of $4n$ questions; each question has $4$ options: 'A', 'B', 'C', and 'D'. For each option, there are exactly $n$ correct answers corresponding to that option — meaning there are $n$ questions with the answer 'A', $n$ questions with the answer 'B', $n$ questions with the answer 'C', and $n$ questions with the answer 'D'.\n\nFor each question, Tim wrote his answer on the answer sheet. If he could not figure out the answer, he would leave a question mark '?' for that question.\n\nYou are given his answer sheet of $4n$ characters. What is the maximum number of correct answers Tim can get?",
    "tutorial": "What is the pattern of Tim's answer sheet that can give him maximum score? Let's say there are $n$ problems take $A$ as the answer, therefore he can only get $n$ points with the answer $A$. The same is correct for $B$, $C$ and $D$. Therefore, the maximum score can be achieved is $min(n, A) + min(n, B) + min(n, C) + min(n, D)$. Time complexity: $O(4n)$",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    s = input()\n\n    print(sum(min(n, s.count(c)) for c in \"ABCD\"))",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1993",
    "index": "B",
    "title": "Parity and Sum",
    "statement": "Given an array $a$ of $n$ positive integers.\n\nIn one operation, you can pick any pair of indexes $(i, j)$ such that $a_i$ and $a_j$ have \\textbf{distinct} parity, then replace the smaller one with the sum of them. More formally:\n\n- If $a_i < a_j$, replace $a_i$ with $a_i + a_j$;\n- Otherwise, replace $a_j$ with $a_i + a_j$.\n\nFind the minimum number of operations needed to make all elements of the array have the same parity.",
    "tutorial": "Find a way to make all the elements even. Then odd. In the worst case, the number of operations required is the number of even elements + 1. Why? First, if all elements already have the same parity, we don't need to do perform any operation. Next, if the array contains both $even$ and $odd$ numbers. In this case, it is impossible to convert all elements to $even$ numbers. If we apply an operation on: two $odd$ elements, one of them remains $odd$. two elements of distinct parities, one of them is replaced with their sum, which is an $odd$ number. This implies even if we want to change an $odd$ element to $even$ number, it fails in both ways possible. So we just want to convert all of them to $odd$ numbers. Now come the greedy part: $even + even = even \\longrightarrow$ it doesn't reduce the number of $even$ elements, so skip it. $odd + odd = even \\longrightarrow$ this creates another $even$ number, indeed very awful. $even + odd = odd \\longrightarrow$ this is great, but only if the sum replaces the $even$ one (which means $even < odd$). Let's find the largest $odd$ element and call it $s$. Then traverse each $even$ elements $t$ in non-decreasing order and apply an operation on $s$ and $t$: If $t < s$, $s+t$ becomes largest odd number. Thus, we set $s := s+t$. This reduce the number of even element by $1$. If $t > s$, before we do this operation, we need to do another on $s$ and the largest even element to make $s$ the largest in the array. Note that this case only happens at most once. As a result, the answer is the number of even elements (plus $1$ if the second case occurs). Time complexity: $O(n\\log n)$.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n\n    s = -1\n    v = []\n    for x in a:\n        if x%2 == 0:\n            v.append(x)\n        elif x > s:\n            s = x\n    v.sort()\n\n    if s == -1 or v == []:\n        print(0)\n        continue\n    \n    ans = len(v)\n    for t in v:\n        if t < s:\n            s += t\n        else:\n            ans += 1\n            break\n\n    print(ans)",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1993",
    "index": "C",
    "title": "Light Switches",
    "statement": "There is an apartment consisting of $n$ rooms, each with its light \\textbf{initially turned off}.\n\nTo control the lights in these rooms, the owner of the apartment decided to install chips in the rooms so that each room has exactly one chip, and the chips are installed at different times. Specifically, these times are represented by the array $a_1, a_2, \\ldots, a_n$, where $a_i$ is the time (in minutes) at which a chip is installed in the $i$-th room.\n\nAs soon as a chip is installed, it changes the room's light status every $k$ minutes — it turns on the light for $k$ minutes, then turns it off for the next $k$ minutes, then turns it back on for the next $k$ minutes, and so on. In other words, the light status is changed by the chip at minute $a_i$, $a_i + k$, $a_i + 2k$, $a_i + 3k$, $\\ldots$ for the $i$-th room.\n\nWhat is the earliest moment when all rooms in the apartment have their lights turned on?",
    "tutorial": "Try to find the segments of moments when a light is on. Select this segment from each light. The answer should be the intersection of all of them. As soon as a chip is installed, it changes the light's status every $k$ minutes. Let's first list the segments of the moments when a light is on if we install a chip at moment $x$: $x\\rightarrow x+k-1$ $x+2k\\rightarrow x+3k-1$ $x+4k\\rightarrow x+5k-1$ $\\dots$ Have you seen the pattern yet? Apparently each segment in the list (except the first one) is actually the segment before it, shifted by $2k$ minutes. This also means that if we divide by $2k$ and take the remainder at both ends of each segment, all these segments become equal. With that, let's call $(a_i\\bmod 2k, (a_i+k-1)\\bmod 2k)$ the segment of the $i$-th chip. Our problem is thus simplified to: find the smallest integer $s$ such that: $max(a) \\le s$ $s\\bmod 2k$ appears in every segments of all chips. In order to satisfy the first condition, it seems if we figure out some $r = s\\bmod 2k$ that satisfy the second condition, we may come up with: $s = max(a) + ((r - max(a))\\bmod 2k)$ Next, in order for a segment to contain $r$, this inequality must be satisfied: $r-k+1 \\le a_i \\le r \\pmod{2k}$. This is because a light is on only for at most $k$ minutes (before it gets turned off), so it must come not long before the moment $r$. Let's call $d[z]$ the number of chips that has $a_i \\equiv z \\pmod{2k}$, then in order for all lights to be on at moment $s$, the condition is: $\\sum \\limits_{z=r-k+1}^{r} d[z] = n$ This idea can be implemented using two-pointer technique, that traverse all $r$ from $0$ to $2k-1$. As there can be many possible values of $r$, we only take one that produces $s$ with minimum value. Be careful when handling signs in problems with modules to avoid unnecessary errors. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n \nconst int N = 2e5 + 5;\n \nint n, k, d[2*N];\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    \n    int t;\n    cin >> t;\n \n    while (t--) {\n        cin >> n >> k;\n \n        int mx = -1;\n        fill(d, d + 2*k, 0);\n \n        for (int i = 0; i < n; i++) {\n            int x;\n            cin >> x;\n            assert(x >= 1);\n            d[x % (2*k)]++;\n            mx = max(mx, x);\n        }\n \n        int cnt = 0;\n        int ans = INT_MAX;\n        for (int i = 0; i <= k - 2; i++) {\n            cnt += d[i];\n        }\n \n        for (int l = 0, r = k-1; l < 2*k; l++, r++) {\n            if (r >= 2*k) r -= 2*k;\n \n            if (cnt += d[r]; cnt == n) {\n                int wait = (r-mx) % (2*k);\n                if (wait < 0) wait += 2*k;\n                ans = min(ans, mx + wait);\n            }\n \n            cnt -= d[l];\n        }\n \n        if (ans == INT_MAX) {\n            ans = -1;\n        }\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "1993",
    "index": "D",
    "title": "Med-imize",
    "statement": "Given two positive integers $n$ and $k$, and another array $a$ of $n$ integers.\n\nIn one operation, you can select any subarray of size $k$ of $a$, then remove it from the array without changing the order of other elements. More formally, let $(l, r)$ be an operation on subarray $a_l, a_{l+1}, \\ldots, a_r$ such that $r-l+1=k$, then performing this operation means replacing $a$ with $[a_1, \\ldots, a_{l-1}, a_{r+1}, \\ldots, a_n]$.\n\nFor example, if $a=[1,2,3,4,5]$ and we perform operation $(3,5)$ on this array, it will become $a=[1,2]$. Moreover, operation $(2, 4)$ results in $a=[1,5]$, and operation $(1,3)$ results in $a=[4,5]$.\n\nYou have to repeat the operation while the length of $a$ is greater than $k$ (which means $|a| \\gt k$). What is the largest possible median$^\\dagger$ of all remaining elements of the array $a$ after the process?\n\n$^\\dagger$The median of an array of length $n$ is the element whose index is $\\left \\lfloor (n+1)/2 \\right \\rfloor$ after we sort the elements in non-decreasing order. For example: $median([2,1,5,4,3]) = 3$, $median([5]) = 5$, and $median([6,8,2,4]) = 4$.",
    "tutorial": "Is there any method to calculate median without sorting? Is there any relationship between the original array with the final array? Note: in order to explain this solution easier, we'll suppose all arrays are 0-indexed. If $n \\le k$, we don't have to remove any segment since the statement only tell us to do it while the length of $a$ is greater than $k$. That way, the median of $a$ is fixed. Let's find a way to calculate this value without sorting the array. Given an integer $x$. If $x$ is less than or equal to the median of $a$, then suppose we sort $a$ in increasing order, $x$ is somewhat to the left of $med(a)$. That means the number of elements greater than or equal to $x$ is more than the number of elements less than $x$. Using this observation, we can create another array $b$ of the same size as $a$, such that $b[i] = 1$ if $a[i] \\ge x$, otherwise $b[i] = -1$. The trick here is if $sum(b) > 0$, then the condition $x \\le med(a)$ is satisfied. Using this trick, we can easily binary search the median of $a$ by fixing value of $x$, checking if $sum(b) > 0$ and adjusting the value range of $med(a)$. How about $n>k$. In this case, we'll keep using the same strategy as above. That is: fix the value of $x$, find a way to delete segments of $a$ so that the array $b$ has largest sum, check if that sum is greater than $0$ and adjust the value range of the answer. Note that each time we delete a segment, the size of $a$ is reduced by $k$. We do that until $|a|\\le k$. Let's call the final array $a$ after deleting segments $a'$. After some calculation, we come up with $|a'| = ((n-1)\\bmod k) + 1$. Also, it can be seen that the elements $a'[0], \\dots, a'[m-1]$ (where $m = |a'|$) always originate from the elements $a[i_0], \\dots, a[i_{m-1}]$ such that $i_0\\equiv 0\\pmod k, i_1\\equiv 1\\pmod k, \\dots, i_{m-1}\\equiv m-1\\pmod k$. Suppose we want to delete the segment $[i, i+k-1]$ from $a$. This operation shift all the elements from the right by $k$ units to the left, which means the indexes are subtracted by $k$ units. But if we only care about the indexes modulo $k$ before and after deleting the segments, shifting $k$ units doesn't change their modulos at all. With all above observations, we come up with the following DP formula to find the optimal segment deletions: $dp[0] = b[0]$ If $i\\equiv 0\\pmod k$ and $i > 0$, then $dp[i] = max(dp[i-k], b[i])$ Otherwise $dp[i] = dp[i-1] + b[i]$. If $i > k$ then maximize $dp[i]$ by $dp[i-k]$ Then, the maximum sum of $b$ in the optimal deletions equals to $dp[n-1]$. Time complexity: $O(n\\log max(a))$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 500005;\n\nint n, k, a[N];\nint dp[N], b[N];\n\nbool check(int med) {\n    for (int i = 0; i < n; i++) {\n        if (a[i] >= med) {\n            b[i] = 1;\n        } else {\n            b[i] = -1;\n        }\n    }\n\n    dp[0] = b[0];\n    for (int i = 1; i < n; i++) {\n        if (i%k == 0) {\n            dp[i] = max(dp[i-k], b[i]);\n        } else {\n            dp[i] = dp[i-1] + b[i];\n            if (i > k) {\n                dp[i] = max(dp[i], dp[i-k]);\n            }\n        }\n    }\n\n    return dp[n-1] > 0;\n}\n\nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n\n    int t; cin >> t;\n    while (t--) {\n        cin >> n >> k;\n\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n        }\n\n        int lo = 1, hi = 1e9;\n        while (lo <= hi) {\n            int mid = lo + hi >> 1;\n            if (check(mid)) {\n                lo = mid + 1;\n            } else {\n                hi = mid - 1;\n            }\n        }\n\n        cout << hi << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1993",
    "index": "E",
    "title": "Xor-Grid Problem",
    "statement": "Given a matrix $a$ of size $n \\times m$, each cell of which contains a non-negative integer. The integer lying at the intersection of the $i$-th row and the $j$-th column of the matrix is called $a_{i,j}$.\n\nLet's define $f(i)$ and $g(j)$ as the XOR of all integers in the $i$-th row and the $j$-th column, respectively. In one operation, you can either:\n\n- Select any row $i$, then assign $a_{i,j} := g(j)$ for each $1 \\le j \\le m$; or\n- Select any column $j$, then assign $a_{i,j} := f(i)$ for each $1 \\le i \\le n$.\n\n\\begin{center}\n{\\small An example of applying an operation on column $2$ of the matrix.}\n\\end{center}\n\nIn this example, as we apply an operation on column $2$, all elements in this column are changed:\n\n- $a_{1,2} := f(1) = a_{1,1} \\oplus a_{1,2} \\oplus a_{1,3} \\oplus a_{1,4} = 1 \\oplus 1 \\oplus 1 \\oplus 1 = 0$\n- $a_{2,2} := f(2) = a_{2,1} \\oplus a_{2,2} \\oplus a_{2,3} \\oplus a_{2,4} = 2 \\oplus 3 \\oplus 5 \\oplus 7 = 3$\n- $a_{3,2} := f(3) = a_{3,1} \\oplus a_{3,2} \\oplus a_{3,3} \\oplus a_{3,4} = 2 \\oplus 0 \\oplus 3 \\oplus 0 = 1$\n- $a_{4,2} := f(4) = a_{4,1} \\oplus a_{4,2} \\oplus a_{4,3} \\oplus a_{4,4} = 10 \\oplus 11 \\oplus 12 \\oplus 16 = 29$\n\nYou can apply the operations any number of times. Then, we calculate the $beauty$ of the final matrix by summing the absolute differences between all pairs of its adjacent cells.\n\nMore formally, $beauty(a) = \\sum|a_{x,y} - a_{r,c}|$ for all cells $(x, y)$ and $(r, c)$ if they are adjacent. Two cells are considered adjacent if they share a side.\n\nFind the minimum $beauty$ among all obtainable matrices.",
    "tutorial": "Try applying an operation on the same row twice. Does it change the matrix significantly? Now apply operations on two different rows. Does the second row (that the operation is applied) look familiar? First, let's extend the original matrix by one unit in rows and columns (which means there's an additional $(n+1)$-th row and $(m+1)$-th column). Then, assign $a[i][m+1] = f(i)$ (xorsum of the $i$-th row) and $a[n+1][j] = g(j)$ (xorsum of the $j$-th column). That way, the operation is simplified as follows: The first-type operation becomes swapping the $i$-th row with the $(n+1)$-th row. The second-type operation becomes swapping the $j$-th column with the $(m+1)$-th column. As we know, the first-type operation is to select any row $i$, then assign $a[i][j] = g(j)$ for all index $j$. But after the matrix extension, the value of $g(j)$ is also $a[n+1][j]$ so it means replacing the $i$-th row with the $(n+1)$-th one. But we also need to care about the new value of $g(j)$ for future operations right? Surprisingly, the new value of $g(j)$ is nowhere strange, just the old value of element $a[i][j]$ being replaced right before! This takes advantage of the fact that if we perform the operation on the same row twice, the row become unchanged. After swapping two rows, the value of $a[n+1][j]$ then again become $g(j)$ of the new matrix. The change of the second-type operation can be proven the same way. That way, the matrix can be constructed by the permutation of rows, and the permutation of columns (as we can swap them however we want). After all operations, let's say the rows ordered from the top to the bottom are $r_1, r_2, \\dots, r_{n+1}$. Similarly, the columns ordered from the left to the right are $c_1, c_2, \\dots, c_{m+1}$. Next thing to consider is: $\\text{beauty(a)} = R + C$ - the beauty of the matrix, where: $R = \\sum\\limits_{i=1}^n \\sum\\limits_{j=2}^m \\big|a[i][j] - a[i][j-1]\\big|$ - sum of adjacent cells on the same row. $C = \\sum\\limits_{j=1}^m \\sum\\limits_{i=2}^n \\big|a[i][j] - a[i-1][j]\\big|$ - sum of adjacent cells on the same column. Note that we include neither the $(n+1)$-th row nor the $(m+1)$-th column when calculating $R$ and $C$. That being said, after all operations, the $r_{n+1}$-th row and the $c_{m+1}$-th column is excluded and do not make any effect in further calculations anymore. After that, we calculate two arrays: $dr[u][v] =$ sum of differences between $u$-th row and $v$-th row. $dc[u][v] =$ sum of differences between $u$-th column and $v$-th column. Then, we'll rewrite the formulas of $R$ and $C$ as: $R = \\sum\\limits_{i=2}^n dr[r_{i-1}][r_i]$ and $C = \\sum\\limits_{i=2}^m dc[c_{i-1}][c_i]$. From now on, calculating $R$ and $C$ is as easy as solving the Travelling Salesman Problem: finding a good permutation $r_1, \\dots, r_n$ that produces the minimum $R$, and a good permutation $c_1, \\dots, c_n$ that produces the minimum $C$. At the end, by summing $R + C$ we got the $\\text{beauty}$ for a fixed excluded row and column for the matrix $a$. Time complexity: $O((n+1)(m+1)^22^{m+1} + (m+1)(n+1)^22^{n+1})$, or just $O(n^32^n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N = 16;\n \nint n, m;\nint a[N][N];\n \nint fr[N][N], fc[N][N];\nint w[N][N], dp[N][1<<N];\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    \n    int t;\n    cin >> t;\n \n    while (t--) {\n        cin >> n >> m;\n \n        for (int i = 0; i <= n; i++) a[i][m] = 0;\n        for (int j = 0; j <= m; j++) a[n][j] = 0;\n \n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                cin >> a[i][j];\n                a[i][m] ^= a[i][j];\n                a[n][j] ^= a[i][j];\n                a[n][m] ^= a[i][j];\n            }\n        }\n \n        int fullmask_n = (1 << (n+1)) - 1;\n        int fullmask_m = (1 << (m+1)) - 1;\n \n        for (int rmv = 0; rmv <= m; rmv++) {\n            for (int i = 0; i <= n; i++) {\n                for (int j = i + 1; j <= n; j++) {\n                    w[i][j] = 0;\n                    for (int l = 0; l <= m; l++) {\n                        if (rmv == l) continue;\n                        w[i][j] += abs(a[i][l] - a[j][l]);\n                    }\n                    w[j][i] = w[i][j];\n                }\n            }\n \n            for (int i = 0; i <= n; i++) {\n                fill(dp[i], dp[i] + fullmask_n, INT_MAX);\n                dp[i][1 << i] = 0;\n            }\n \n            for (int mask = 0; mask <= fullmask_n; mask++) {\n                for (int last = 0; last <= n; last++) {\n                    if (~mask >> last & 1) continue;\n                    if (__builtin_popcount(mask) == n) continue;\n \n                    for (int next = 0; next <= n; next++) {\n                        if (mask >> next & 1) continue;\n \n                        int new_mask = mask | 1 << next;\n                        dp[next][new_mask] = min(\n                            dp[next][new_mask],\n                            dp[last][mask] + w[last][next]\n                        );\n                    }\n                }\n            }\n \n            for (int i = 0; i <= n; i++) {\n                fr[i][rmv] = INT_MAX;\n                int mask = fullmask_n ^ 1 << i;\n \n                for (int last = 0; last <= n; last++) {\n                    fr[i][rmv] = min(fr[i][rmv], dp[last][mask]);\n                }\n            }\n        }\n \n        for (int rmv = 0; rmv <= n; rmv++) {\n            for (int i = 0; i <= m; i++) {\n                for (int j = i + 1; j <= m; j++) {\n                    w[i][j] = 0;\n                    for (int l = 0; l <= n; l++) {\n                        if (rmv == l) continue;\n                        w[i][j] += abs(a[l][i] - a[l][j]);\n                    }\n                    w[j][i] = w[i][j];\n                }\n            }\n \n            for (int i = 0; i <= m; i++) {\n                fill(dp[i], dp[i] + fullmask_m, INT_MAX);\n                dp[i][1 << i] = 0;\n            }\n \n            for (int mask = 0; mask <= fullmask_m; mask++) {\n                for (int last = 0; last <= m; last++) {\n                    if (~mask >> last & 1) continue;\n                    if (__builtin_popcount(mask) == m) continue;\n \n                    for (int next = 0; next <= m; next++) {\n                        if (mask >> next & 1) continue;\n \n                        int new_mask = mask | 1 << next;\n                        dp[next][new_mask] = min(\n                            dp[next][new_mask],\n                            dp[last][mask] + w[last][next]\n                        );\n                    }\n                }\n            }\n \n            for (int i = 0; i <= m; i++) {\n                fc[rmv][i] = INT_MAX;\n                int mask = fullmask_m ^ 1 << i;\n \n                for (int last = 0; last <= m; last++) {\n                    fc[rmv][i] = min(fc[rmv][i], dp[last][mask]);\n                }\n            }\n        }\n \n        int ans = INT_MAX;\n        for (int i = 0; i <= n; i++) {\n            for (int j = 0; j <= m; j++) {\n                ans = min(ans, fr[i][j] + fc[i][j]);\n            }\n        }\n \n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1993",
    "index": "F1",
    "title": "Dyn-scripted Robot (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is that in this version $k \\le n$. You can make hacks only if both versions of the problem are solved.}\n\nGiven a $w \\times h$ rectangle on the $Oxy$ plane, with points $(0, 0)$ at the bottom-left and $(w, h)$ at the top-right of the rectangle.\n\nYou also have a robot initially at point $(0, 0)$ and a script $s$ of $n$ characters. Each character is either L, R, U, or D, which tells the robot to move left, right, up, or down respectively.\n\nThe robot can only move inside the rectangle; otherwise, it will change the script $s$ as follows:\n\n- If it tries to move outside a vertical border, it changes all L characters to R's (and vice versa, all R's to L's).\n- If it tries to move outside a horizontal border, it changes all U characters to D's (and vice versa, all D's to U's).\n\nThen, it will execute the changed script starting from the character which it couldn't execute.\n\n\\begin{center}\n{\\normalsize An example of the robot's movement process, $s = \"ULULURD\"$}\n\\end{center}\n\nThe script $s$ will be executed for $k$ times continuously. All changes to the string $s$ will be retained even when it is repeated. During this process, how many times will the robot move to the point $(0, 0)$ in total? \\textbf{Note that the initial position does NOT count}.",
    "tutorial": "Let the robot moves freely (no modification on the script). The new path of the robot is the \"mirrored\" version of how the robot must go. Imagine we have two robots, let's call them Alex and Bob. Alex is the one who follows the instruction well, but Bob doesn't (if he tries to move outside the box, he keeps going without modifying the script). Then, you follow the path of each robot that is moving. How do you think their paths differ from each other? Yes! Suppose at some moment they reach the top side of the box at the same time. Suddenly, Bob wants to move up while Alex know the discipline and modify the script before executing the command and move down. Then, each of them is $1$ unit away from the top side of the box. If Bob keeps moving up, Alex keep moving down. In case Bob changes his mind and move down then this time Alex changes her mind and move up. What do we learn from this? They move like two objects facing each other through a mirror. Actually there are four mirror of them, placing at the four sides of the box. Now, let's say Bob moves up so much that Alex follows the script and reaches the top side and the bottom side as well. Because of that, she has to change the script once again and start moving up like Bob. When Alex reaches the bottom side at point $(x, 0)$, then Bob should be at point $(x, 2H)$ (prove it yourself!). If Bob keeps moving up to the point $(x, 4H), (x, 6H), or (x, 8H), \\dots$, at these moment Alex will also be at point $(x, 0)$. That being said, Alex's position is $(x, 0)$ then Bob's position must be $(x, y)$ where y is a multiple of $2H$. This idea is exactly the same as if Bob were moving sideways (left or right). As we only care about the number of times Alex's position is $(0, 0)$, we know that if we don't change the script at all, the position of the robot must be $(x, y)$ where $x$ is a multiple of $2W$, and $y$ is a multiple of $2H$. So apparently, we need to calculate the number of times the robot reaches $(x, y)$, where $x$ is a multiple of $2W$ and $y$ is a multiple of $2H$ (see the general idea above). Let's call $t_k = (x_k, y_k)$ how much the robot moves (in direction) after executing the first $k$ commands of the script. Then: $t_0 = (0, 0)$ and $t_k$ can be calculated through $t_{k-1}$ and $s_k$. The robot will execute the script $k$ times and the script contains $n$ commands, so we have $nk$ positions to check out. Each position can be represented by: $(x, y) = it_n + t_j = (ix_n + x_j, iy_n + y_j)$ (where $0\\le i\\le k-1$ and $1\\le j\\le n$). Besides, we need: $x\\equiv 0\\pmod{2W} \\Longrightarrow ix_n + x_j\\equiv 0\\pmod{2W} \\Longrightarrow x_j\\equiv -ix_n\\pmod{2W}$ $y\\equiv 0\\pmod{2H} \\Longrightarrow iy_n + y_j\\equiv 0\\pmod{2H} \\Longrightarrow y_j\\equiv -iy_n\\pmod{2H}$ Lastly, we can traverse all possible $i$ from $0$ to $k-1$ and count the number of $j$ that satisfies the above equivalence. One possible way to do this is to use a map to count each element in the array $t_1, t_2, \\dots, t_n$. Summing all the counts will give the answer for this problem. Time complexity: $O((n + k)\\log n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nconst int N = 1e6 + 5;\n \nstring s;\nll n, k, w, h;\nll tx[2*N], ty[2*N];\nmap<pair<ll, ll>, ll> cnt;\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    \n    int t;\n    cin >> t;\n \n    while (t--) {\n        cin >> n >> k >> w >> h >> s;\n \n        cnt.clear();\n        ll x = 0, y = 0;\n \n        for (int i = 0; i < n; i++) {\n            if (s[i] == 'L') x--;\n            if (s[i] == 'R') x++;\n            if (s[i] == 'D') y--;\n            if (s[i] == 'U') y++;\n\n            x = (x + 2*w) % (2*w);\n            y = (y + 2*h) % (2*h);\n            cnt[{x, y}]++;\n        }\n \n        ll ans = 0;\n        for (int i = 0; i < k; i++) {\n            ll vx = (-i*x%(2*w) + 2*w)%(2*w);\n            ll vy = (-i*y%(2*h) + 2*h)%(2*h);\n            ans += cnt[{vx, vy}];\n        }\n\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "brute force",
      "chinese remainder theorem",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "1993",
    "index": "F2",
    "title": "Dyn-scripted Robot (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version $k \\le 10^{12}$. You can make hacks only if both versions of the problem are solved.}\n\nGiven a $w \\times h$ rectangle on the $Oxy$ plane, with points $(0, 0)$ at the bottom-left and $(w, h)$ at the top-right of the rectangle.\n\nYou also have a robot initially at point $(0, 0)$ and a script $s$ of $n$ characters. Each character is either L, R, U, or D, which tells the robot to move left, right, up, or down respectively.\n\nThe robot can only move inside the rectangle; otherwise, it will change the script $s$ as follows:\n\n- If it tries to move outside a vertical border, it changes all L characters to R's (and vice versa, all R's to L's).\n- If it tries to move outside a horizontal border, it changes all U characters to D's (and vice versa, all D's to U's).\n\nThen, it will execute the changed script starting from the character which it couldn't execute.\n\n\\begin{center}\n{\\normalsize An example of the robot's movement process, $s = \"ULULURD\"$}\n\\end{center}\n\nThe script $s$ will be executed for $k$ times continuously. All changes to the string $s$ will be retained even when it is repeated. During this process, how many times will the robot move to the point $(0, 0)$ in total? \\textbf{Note that the initial position does NOT count}.",
    "tutorial": "The idea of this version is almost the same as F1: counting the number of pairs $(i, j)$ that satisfies: $ix_n + x_j\\equiv 0\\pmod{2W}$, and $iy_n + y_j\\equiv 0\\pmod{2H}$ However, as $k$ is increased to $10^{12}$ we cannot brute-force the same way as the previous version. Luckily, there is a more efficient way. We need to modify these equivalences a bit: $ix_n \\equiv -x_j\\pmod{2W}$ $(*)$ $iy_n \\equiv -y_j\\pmod{2H}$ As we can see, these two equivalences have the same format $ia \\equiv b\\pmod{M}$. To solve this equivalence for $i$, one way to hang around is to divide $a$, $b$ and $M$ by $\\gcd(a, M)$. If $b$ is not divisible, there is no solution! Otherwise, we come up with: $i \\equiv ba^{-1}\\pmod{M}$ Where $a^{-1}$ is the modular inverse of $a$. We can always calculate it because the condition $\\gcd(a, M)=1$ is satisfied. Let's define $g=\\gcd(2W, x_n)$, $c_x = -\\frac{x_j}g\\left(\\frac{x_n}g\\right)^{-1}$ and $W'=\\frac{2W}{g}$ (similar for $c_y$ and $H'$). Then, the solutions of the equivalences at $(*)$ are: $i\\equiv c_x\\pmod{W'}$ $i\\equiv c_y\\pmod{H'}$ This system of equivalences can be solved using Chinese Remainder Theorem. After some calculations, we come up with: $i=c_x + zW'$ ($z$ is a non-negative integer). $zW'\\equiv c_y-c_x\\pmod{H'}$ $(**)$ $(**)$ can be solved for $z$ the same way as $(*)$. Now we know the solution is $i \\equiv c_x + zW' \\pmod{lcm(W', H')}$, the last thing to do is to count number of such value doesn't exceed $k-1$ and we're done! Time complexity: $O(Nlog(W))$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n\nusing ll = long long;\n\nnamespace CRT {    \n    // v * inv(v, M) = 1 (mod M)\n    ll inv(ll v, ll M) {\n        ll a = 1, b = 0;\n        for (ll x = v, y = M; x != 0; ) {\n            swap(a, b -= y/x * a);\n            swap(x, y -= y/x * x);\n        }\n        return b + (b<0) * M;\n    }\n\n    // Minimum x that ax = b (mod c)\n    ll solve_1(ll a, ll b, ll c) {\n        ll g = gcd(a, c);\n        if (b % g != 0) return -1;\n        return b/g * inv(a/g, c/g) % (c/g);\n    }\n\n    // Minimum x that x%b = a and x%d = c\n    ll solve_2(ll a, ll b, ll c, ll d) {\n        ll t = (c-a)%d;\n        if (t < 0) t += d;\n        ll k = solve_1(b, t, d);\n        return k==-1 ? -1 : a + k*b;\n    }\n}\n\n\nconst int N = 1e6 + 5;\n\nll n, k, w, h;\nll x[N], y[N];\n\nint main() {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n\n    int tc; cin >> tc;\n    while (tc--) {\n        string s;\n        cin >> n >> k >> w >> h >> s;\n\n        for (int i = 1; i <= n; i++) {\n            x[i] = x[i-1] + (s[i-1] == 'R') - (s[i-1] == 'L');\n            y[i] = y[i-1] + (s[i-1] == 'U') - (s[i-1] == 'D');\n            x[i] += (x[i] < 0) * 2*w - (x[i] >= 2*w) * 2*w;\n            y[i] += (y[i] < 0) * 2*h - (y[i] >= 2*h) * 2*h;\n        }\n\n        ll ww = 2*w / gcd(x[n], 2*w);\n        ll hh = 2*h / gcd(y[n], 2*h);\n        ll ans = 0, l = lcm(ww, hh);\n\n        for (int i = 1; i <= n; i++) {\n            ll cx = CRT::solve_1(x[n], 2*w - x[i], 2*w);\n            ll cy = CRT::solve_1(y[n], 2*h - y[i], 2*h);\n            if (cx == -1 || cy == -1) continue;\n\n            ll result = CRT::solve_2(cx, ww, cy, hh);\n            if (result != -1 && result < k) {\n                ans += (k - result - 1) / l + 1;\n            }\n        }\n\n        cout << ans << '\\n';\n    }\n}",
    "tags": [
      "chinese remainder theorem",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "1994",
    "index": "A",
    "title": "Diverse Game",
    "statement": "Petr, watching Sergey's stream, came up with a matrix $a$, consisting of $n$ rows and $m$ columns (the number in the $i$-th row and $j$-th column is denoted as $a_{i, j}$), which contains all integers from $1$ to $n \\cdot m$. But he didn't like the arrangement of the numbers, and now he wants to come up with a new matrix $b$, consisting of $n$ rows and $m$ columns, which will also contain all integers from $1$ to $n \\cdot m$, such that for any $1 \\leq i \\leq n, 1 \\leq j \\leq m$ it holds that $a_{i, j} \\ne b_{i, j}$.\n\nYou are given the matrix $a$, construct \\textbf{any} matrix $b$ that meets Petr's requirements, or determine that it is impossible.\n\nHurry up! Otherwise, he will donate all his money to the stream in search of an answer to his question.",
    "tutorial": "If $n = m = 1$, then there is only one possible matrix, so the answer is $-1$. Otherwise, at least one of the numbers $n, m$ is greater than $1$, then one of the solutions is, for example, a matrix $a$ with cyclically shifted rows (if $m > 1$) or columns (if $n > 1$).",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    cin.tie(nullptr)->sync_with_stdio(false);\n\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        int n, m;\n        cin >> n >> m;\n        vector<vector<int>> a(n, vector<int>(m));\n        for (auto &i: a) {\n            for (auto &j: i) cin >> j;\n        }\n        if (n * m == 1) cout << \"-1\\n\";\n        else {\n            for (int i = 0; i < n; ++i) {\n                for (int j = 0; j < m; ++j) {\n                    cout << a[(i + 1) % n][(j + 1) % m] << ' ';\n                }\n                cout << '\\n';\n            }\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1994",
    "index": "B",
    "title": "Fun Game",
    "statement": "Vova really loves the XOR operation (denoted as $\\oplus$). Recently, when he was going to sleep, he came up with a fun game.\n\nAt the beginning of the game, Vova chooses two binary sequences $s$ and $t$ of length $n$ and gives them to Vanya. A binary sequence is a sequence consisting only of the numbers $0$ and $1$. Vanya can choose integers $l, r$ such that $1 \\leq l \\leq r \\leq n$, and for all $l \\leq i \\leq r$ \\textbf{simultaneously} replace $s_i$ with $s_i \\oplus s_{i - l + 1}$, where $s_i$ is the $i$-th element of the sequence $s$.\n\nIn order for the game to be interesting, there must be a possibility to win. Vanya wins if, with an \\textbf{unlimited} number of actions, he can obtain the sequence $t$ from the sequence $s$. Determine if the game will be interesting for the sequences $s$ and $t$.",
    "tutorial": "If the string $s$ consists entirely of $0$, then obviously no other string can be obtained from it, so the answer is \"Yes\" only if $s = t$. Otherwise, let $i$ - the index of the first $1$ in $s$. Note that if there is at least one $1$ in $t$ at positions $[1; i)$, then the answer is \"No\", since $s$ has $0$ at these positions, so some of them must be changed to $1$. However, when applying the operation the first $1$ from position $i$ can change bits only at positions greater than or equal to $i$, i.e. it will not be possible to change $0$ at positions before $i$. If there is only $0$ at positions $[1; i)$ in $t$, then it is possible to change any bit on the segment $[i; n]$ in $s$ to any other bit by choosing segments of length $i$ and acting from the end, i.e. the answer is \"Yes\".",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    string s, t;\n    cin >> s >> t;\n    for (int i = 0; i < s.size() && s[i] == '0'; ++i) {\n        if (t[i] != '0') {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    cout << \"YES\\n\";\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1994",
    "index": "C",
    "title": "Hungry Games",
    "statement": "Yaroslav is playing a computer game, and at one of the levels, he encountered $n$ mushrooms arranged in a row. Each mushroom has its own level of toxicity; the $i$-th mushroom from the beginning has a toxicity level of $a_i$. Yaroslav can choose two integers $1 \\le l \\le r \\le n$, and then his character will take turns from left to right to eat mushrooms from this subsegment one by one, i.e., the mushrooms with numbers $l, l+1, l+2, \\ldots, r$.\n\nThe character has a toxicity level $g$, initially equal to $0$. The computer game is defined by the number $x$ — the maximum toxicity level at any given time. When eating a mushroom with toxicity level $k$, the following happens:\n\n- The toxicity level of the character is increased by $k$.\n- If $g \\leq x$, the process continues; otherwise, $g$ becomes zero and the process continues.\n\nYaroslav became interested in how many ways there are to choose the values of $l$ and $r$ such that the final value of $g$ is not zero. Help Yaroslav find this number!",
    "tutorial": "We'll solve the problem by dynamic programming. Let $dp[i]$ - the number of good subsegments with left boundary at $i$. We will count $dp$ from the end, for each $i$ we will find such a minimum $j$ that the sum on the subsegment $[i; j]$ is greater than $x$. If there is no such $j$, then all right bounds are good, otherwise $dp[i] = dp[j + 1] + j - i$. To search for $j$, we can use a binary search on prefix sums. The answer will be the sum of all $dp$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nint main() {\n    cin.tie(nullptr)->sync_with_stdio(false);\n\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        int n;\n        ll x;\n        cin >> n >> x;\n        vector<ll> a(n + 1);\n        for (int i = 1; i <= n; ++i) cin >> a[i];\n        partial_sum(a.begin() + 1, a.end(), a.begin() + 1);\n        vector<int> dp(n + 2);\n        for (int i = n - 1; i >= 0; --i) {\n            int q = upper_bound(a.begin(), a.end(), a[i] + x) - a.begin();\n            dp[i] = dp[q] + q - i - 1;\n        }\n        cout << accumulate(dp.begin(), dp.end(), 0ll) << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "dp",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1994",
    "index": "D",
    "title": "Funny Game",
    "statement": "Vanya has a graph with $n$ vertices (numbered from $1$ to $n$) and an array $a$ of $n$ integers; initially, there are no edges in the graph. Vanya got bored, and to have fun, he decided to perform $n - 1$ operations.\n\nOperation number $x$ (operations are numbered in order starting from $1$) is as follows:\n\n- Choose $2$ different numbers $1 \\leq u,v \\leq n$, such that $|a_u - a_v|$ is divisible by $x$.\n- Add an undirected edge between vertices $u$ and $v$ to the graph.\n\nHelp Vanya get a connected$^{\\text{∗}}$ graph using the $n - 1$ operations, or determine that it is impossible.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A graph is called connected if it is possible to reach any vertex from any other by moving along the edges.\n\\end{footnotesize}",
    "tutorial": "Note that we have only $n - 1$ edges, so after each operation, the number of connectivity components must decrease by $1$. Since the order of operations is not important, we will perform the operations in reverse order. Then after the operation with number $x$, there will be $x + 1$ connectivity components in the graph. For each component, let's take any of its vertices $v$ and look at the number that corresponds to it. Note that we have chosen $x + 1$ numbers, so by the pigeonhole principle, some two numbers will be equal modulo $x$. This means that we find two vertices $u$ and $v$ from different components such that $|a_u - a_v|$ is a multiple of $x$. By drawing an edge between $u$ and $v$, we will achieve what we want - the number of connectivity components will become $1$ less. Now it remains to go through the operations in reverse order and print the answer.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for (auto& i : a) cin >> i;\n        vector<int> pos(n);\n        iota(pos.begin(), pos.end(), 0);\n        vector<pair<int, int>> ans;\n        for (int i = n - 1; i; --i) {\n            vector<int> occ(i, -1);\n            for (auto j : pos) {\n                if (occ[a[j] % i] != -1) {\n                    ans.emplace_back(j, occ[a[j] % i]);\n                    pos.erase(find(pos.begin(), pos.end(), j));\n                    break;\n                }\n                occ[a[j] % i] = j;\n            }\n        }\n        reverse(ans.begin(), ans.end());\n        cout << \"YES\\n\";\n        for (auto [x, y] : ans) cout << x + 1 << ' ' << y + 1 << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dsu",
      "graphs",
      "greedy",
      "math",
      "number theory",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1994",
    "index": "E",
    "title": "Wooden Game",
    "statement": "You are given a forest of $k$ rooted trees$^{\\text{∗}}$. Lumberjack Timofey wants to cut down the entire forest by applying the following operation:\n\n- Select a subtree$^{\\text{†}}$ of any vertex of one of the trees and remove it from the tree.\n\nTimofey loves bitwise operations, so he wants the bitwise OR of the sizes of the subtrees he removed to be maximum. Help him and find the maximum result he can obtain.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ A tree is a connected graph without cycles, loops, or multiple edges. In a rooted tree, a selected vertex is called a root. A forest is a collection of one or more trees.\n\n$^{\\text{†}}$ The subtree of a vertex $v$ is the set of vertices for which $v$ lies on the shortest path from this vertex to the root, including $v$ itself.\n\\end{footnotesize}",
    "tutorial": "We know that the maximal result from one tree is the size of this tree (see hints), but we can make every number from $1$ to the size of the tree. To do that, we can delete leaves until we have the needed value. So the remaining problem is to find the maximal OR if we can choose numbers from $1$ to $a_i$. For every bit, let's count the number of $a_i$, where this bit is set. Find the highest bit which is set in more than one number. Obviously, we can make a suffix of $1$-s from this position. Before this position we need to set bits that are set in one of $a_i$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solve() {\n    int k;\n    cin >> k;\n    vector<int> a(k);\n    for (int i = 0; i < k; ++i) {\n        cin >> a[i];\n        for (int j = 0; j < a[i] - 1; ++j) {\n            int trash;\n            cin >> trash;\n        }\n    }\n    sort(a.begin(), a.end(), greater<>());\n    int ans = 0;\n    for (auto x : a) {\n        for (int h = 23; h >= 0; --h) {\n            int ca = ans >> h & 1, cx = x >> h & 1;\n            if (cx == 0) continue;\n            if (ca == 0) ans |= 1 << h;\n            else {\n                ans |= (1 << h) - 1;\n                break;\n            }\n        }\n    }\n    cout << ans << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "1994",
    "index": "F",
    "title": "Stardew Valley",
    "statement": "Pelican Town represents $n$ houses connected by $m$ bidirectional roads. Some roads have NPCs standing on them. Farmer Buba needs to walk on each road with an NPC and talk to them.\n\nHelp the farmer find a route satisfying the following properties:\n\n- The route starts at some house, follows the roads, and ends at the same house.\n- The route does not follow any road more than once (in both directions together).\n- The route follows each road with an NPC exactly once.\n\nNote that the route can follow roads without NPCs, and you do \\textbf{not} need to minimize the length of the route.It is \\textbf{guaranteed} that you can reach any house from any other by walking on the roads with NPCs only.",
    "tutorial": "The edges with $0$ on them will be called black, the other edges will be called white. To find such a route, we need the graph to be Eulerian (degree of each vertex is even). To achieve this, we can remove some black edges. Let's calculate the degree of each vertex (further we will keep this degree in mind) and leave only black edges. Solve the problem independently for each component. If a component has an odd number of vertices with odd degree, we cannot remove edges so that all degrees become even (since removing an edge does not change the parity of the sum of degrees), so in this case the answer is NO. Otherwise, such a route exists. Leave only the spanning tree and run dfs on it. If we leave a vertex and it has an odd degree, we remove an edge to its ancestor. This will work since the sum of the degrees in the component is even. Finally, we need to find the Eulerian cycle in the resulting graph and print it.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    cin.tie(nullptr)->sync_with_stdio(false);\n\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        int n, m;\n        cin >> n >> m;\n        vector<vector<int>> black(n);\n        vector<int> edg(m);\n        vector<vector<int>> g(n);\n        for (int i = 0; i < m; ++i) {\n            int x, y, c;\n            cin >> x >> y >> c;\n            --x, --y;\n            edg[i] = x ^ y;\n            g[x].push_back(i);\n            g[y].push_back(i);\n            if (c == 0) {\n                black[x].push_back(i);\n                black[y].push_back(i);\n            }\n        }\n        vector<int> deg(n);\n        for (int i = 0; i < n; ++i) deg[i] = g[i].size() & 1;\n        vector<bool> del(m, false), used(n, false);\n        auto dfs = [&](auto dfs, int u) -> void {\n            used[u] = true;\n            for (auto id : black[u]) {\n                int to = edg[id] ^ u;\n                if (used[to]) continue;\n                dfs(dfs, to);\n                if (deg[to]) {\n                    del[id] = true;\n                    deg[to] ^= 1;\n                    deg[u] ^= 1;\n                }\n            }\n        };\n        bool ok = true;\n        for (int i = 0; i < n; ++i) {\n            if (used[i]) continue;\n            dfs(dfs, i);\n            ok &= !deg[i];\n        }\n        if (!ok) {\n            cout << \"NO\\n\";\n            continue;\n        }\n        auto euler = [&](auto euler, int u) -> void {\n            while (!g[u].empty()) {\n                int id = g[u].back();\n                g[u].pop_back();\n                int to = edg[id] ^ u;\n                if (del[id]) continue;\n                del[id] = true;\n                euler(euler, to);\n            }\n            cout << u + 1 << ' ';\n        };\n        cout << \"YES\\n\";\n        cout << m - accumulate(del.begin(), del.end(), 0) << '\\n';\n        euler(euler, 0);\n        cout << '\\n';\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1994",
    "index": "G",
    "title": "Minecraft",
    "statement": "After winning another Bed Wars game, Masha and Olya wanted to relax and decided to play a new game. Masha gives Olya an array $a$ of length $n$ and a number $s$. Now Olya's task is to find a non-negative number $x$ such that $\\displaystyle\\sum_{i=1}^{n} a_i \\oplus x = s$. But she is very tired after a tight round, so please help her with this.\n\nBut this task seemed too simple to them, so they decided to make the numbers larger (up to $2^k$) and provide you with their binary representation.",
    "tutorial": "We will do recursion. Let's go from the lower bits to the significant bits. $rec(i, sum)$ means that the first $i$ bits are selected, the sum of them divided by $2^i$ equals $sum$, and the first $i$ bits match the ones we need. Let $cnt_i$ - the number of ones in the numbers in the $i$-th bit. Then we can go from state $(i, sum)$ to $(i + 1, \\lfloor \\frac{sum + cnt_i}{2} \\rfloor)$ and $(i + 1, \\lfloor \\frac{sum + n - cnt_i}{2} \\rfloor)$ if the lowest bit matches the $i$-th bit in $s$. There are at most $nk$ states in such a recursion (proof below). Thus, if we do the memoization, the solution will run $O(nk)$. Proof: $sum$ is always at most $n$. At the beginning of the recursion, $sum = 0$, so the inequality is satisfied. When we go to the next step $\\frac{sum + cnt_i}{2}$, $\\frac{sum + n - cnt_i}{2} \\leq \\frac{n + n}{2} = n$, which was required to prove.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint n, k;\nvector<vector<bool>> memo;\nstring res;\nvector<int> cnt;\nstring s;\n\nbool rec(int i, int cur) {\n    if (i == k) {\n        if (cur == 0) {\n            return true;\n        }\n        return false;\n    }\n    if (memo[i][cur]) return false;\n    memo[i][cur] = true;\n    for (int c = 0; c < 2; ++c) {\n        int q = cur;\n        if (c == 0) q += cnt[i];\n        else q += n - cnt[i];\n        if ((q & 1) == s[i] - '0') {\n            if (rec(i + 1, q / 2)) {\n                res += char(c + '0');\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\nint main() {\n    cin.tie(nullptr)->sync_with_stdio(false);\n\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        cin >> n >> k;\n        cin >> s;\n        reverse(s.begin(), s.end());\n        cnt = vector<int>(k);\n        for (int i = 0; i < n; ++i) {\n            string t;\n            cin >> t;\n            reverse(t.begin(), t.end());\n            for (int j = 0; j < k; ++j) cnt[j] += t[j] - '0';\n        }\n        memo = vector<vector<bool>>(k, vector<bool>(n, false));\n        res = \"\";\n        rec(0, 0);\n        if (res.empty()) cout << \"-1\\n\";\n        else cout << res << '\\n';\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "graphs",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "1994",
    "index": "H",
    "title": "Fortnite",
    "statement": "\\textbf{This is an interactive problem!}\n\nTimofey is writing a competition called Capture the Flag (or CTF for short). He has one task left, which involves hacking a security system. The entire system is based on polynomial hashes$^{\\text{∗}}$.\n\nTimofey can input a string consisting of lowercase Latin letters into the system, and the system will return its polynomial hash. To hack the system, Timofey needs to find the polynomial hash parameters ($p$ and $m$) that the system uses.\n\nTimofey doesn't have much time left, so he will only be able to make $3$ queries. Help him solve the task.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ The polynomial hash of a string $s$, consisting of lowercase Latin letters of length $n$, based on $p$ and modulo $m$ is $(\\mathrm{ord}(s_1) \\cdot p ^ 0 + \\mathrm{ord}(s_2) \\cdot p ^ 1 + \\mathrm{ord}(s_3) \\cdot p ^ 2 + \\ldots + \\mathrm{ord}(s_n) \\cdot p ^ {n - 1}) \\bmod m$. Where $s_i$ denotes the $i$-th character of the string $s$, $\\mathrm{ord}(\\mathrm{chr})$ denotes the ordinal number of the character $\\mathrm{chr}$ in the English alphabet, and $x \\bmod m$ is the remainder of $x$ when divided by $m$.\n\\end{footnotesize}",
    "tutorial": "The first query is $aa$, it can be used to find out $p$. The second query is $zzzzzzzzzz$, let's calculate its hash without modulus, denote h_1, hash with modulus denote a1. Suppose we get a string with hash without modulus from $h_1 - a_1 - m$ to $h_1 - a_1 - 1$, then if we query it, we can easily find out the modulus. Let's find such a string. To do this, let's write $h_1$ in $p$-ary number system, we get $26, 26, .... 26$, and also write $(a1 + 1)$ in $p$-ary notation. Subtract the second one from the first one without transfers, take the leftmost position, where we get $< 1$, and put there and in all the left $26$, as long as the number on the left is $1$, put $26$ in it and stand in it, when the number on the left is not $1$, we just subtract 1 from it. After that we translate it all back into a string. It is claimed that this string fits, let's prove it. Its hash without modulus is obviously not greater than $h_1 - a_1 - 1$. Let's consider $2$ digits, the one in which we made $-1$ and $1$ to the left, let the number of the left digit $i$, then $a_1 + 1 \\geq 25 * p^i$, and we subtracted less than $p^{i + 1} - 25 * p^i$, less because either in $i$ that digit was $0$, or $0$ was somewhere to the left, so there could be no equality, $p \\leq 50$ by convention, $\\geq p^{i + 1} - 25 * p^i \\leq 50 * p^i - 25 * p^i = 25 * p^i \\leq a_1 + 1$ => we subtracted less than $a_1 + 1$ => not more than $a_1$ => less than m. Let's denote what we subtracted by $x$, then our hash is $h_1 - a_1 - 1 - x = h_1 - a_1 - (x + 1)$. $x < m$ => $x + 1 \\leq m$ => $hash \\geq h1 - a1 - m$, which is what we needed to prove.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nvoid solve() {\n    cout << \"? aa\" << endl;\n    int p, v[10];\n    cin >> p; p--;\n    cout << \"? zzzzzzzzzz\" << endl;\n    int hsh, hsho;\n    ll nom = 0, cnt = 1;\n    cin >> hsh;\n    hsho = hsh;\n    hsh++;\n    for (int i = 0; i < 10; i++) {\n        nom += 26 * cnt;\n        cnt *= p;\n        v[i] = 26 - (hsh % p);\n        hsh /= p;\n    }\n    string s;\n    cnt = 1;\n    ll ch = 0;\n    for (int i = 0; i < 10; i++) {\n        if (v[i] < 1) {\n            v[i] = 26;\n            v[i + 1]--;\n        }\n        ch += cnt * v[i];\n        cnt *= p;\n        s += 'a' + (v[i] - 1);\n    }\n    cout << \"? \" << s << endl;\n    int ans;\n    cin >> ans;\n    cout << \"! \" << p << ' ' << ans + nom - ch - hsho << endl;\n}\n\nint32_t main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "games",
      "greedy",
      "hashing",
      "interactive",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "1995",
    "index": "A",
    "title": "Diagonals",
    "statement": "Vitaly503 is given a checkered board with a side of $n$ and $k$ chips. He realized that all these $k$ chips need to be placed on the cells of the board (no more than one chip can be placed on a single cell).\n\nLet's denote the cell in the $i$-th row and $j$-th column as $(i ,j)$. A diagonal is the set of cells for which the value $i + j$ is the same. For example, cells $(3, 1)$, $(2, 2)$, and $(1, 3)$ lie on the same diagonal, but $(1, 2)$ and $(2, 3)$ do not. A diagonal is called occupied if it contains at least one chip.\n\nDetermine what is the minimum possible number of occupied diagonals among all placements of $k$ chips.",
    "tutorial": "How many described diagonals are there in total? How many cells do they contain? In total we have $2 n - 1$ diagonals. There is only one diagonal that contains $n$ cells, two containing $n - 1$ cells, ..., and two containing only one cell each (namely passing through $(1, n)$ and $(n, 1)$). Obviously, in this case, it is worth filling the largest diagonal with chips, then two that are smaller in size, and so on. The asymptotics turns out to be $O(n)$.",
    "code": "def solver():\n    n, k = map(int, input().split())\n    a, b = n, n - 1\n    ans = 0\n    while k > 0:\n        k -= a\n        ans += 1\n        a, b = b, (b if a != b else b - 1)\n    print(ans)\n \nt = int(input())\n \nfor _ in range(t):\n    solver()",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1995",
    "index": "B1",
    "title": "Bouquet (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is that in this version, the flowers are specified by enumeration.}\n\nA girl is preparing for her birthday and wants to buy the most beautiful bouquet. There are a total of $n$ flowers in the store, each of which is characterized by the number of petals, and a flower with $k$ petals costs $k$ coins. The girl has decided that the difference in the number of petals between any two flowers she will use in her bouquet should not exceed one. At the same time, the girl wants to assemble a bouquet with the maximum possible number of petals. Unfortunately, she only has $m$ coins, and she cannot spend more. What is the maximum total number of petals she can assemble in the bouquet?",
    "tutorial": "For each number of petals, we can bruteforce the answer for $x, x + 1$ First, we can aggregate number of flowers with $x$ petals into $c_{x}$ (for example, sort the array and then create array of pairs $(x, c_{x})$, where $c_{x}$ is the length of segment with elements equal to $x$). Note that $\\sum_{x} c_{x} = n$. Also note that for every $x$ we won't need more than $\\left\\lfloor\\frac{m}{x}\\right\\rfloor$ flowers (otherwise total number of petals will exceed $m$). Then we iterate through all $x$. Suppose that we want to assemble a bouquet with $x, x + 1$ petals. We can bruteforce the amount of flowers with $x$ petals in $O(c_{x})$. If we have $0 \\le k_1 \\le min(c_{x}, \\left\\lfloor\\frac{m}{x}\\right\\rfloor)$ flowers with $x$ petals, we already have $k_1 * x$ petals. There are still $m - k_1 * x$ coins which we can spend for flowers with $x + 1$ petals. There are at most $k_2 = min(c_{x + 1}, \\left\\lfloor\\frac{m - k_1 * x}{x + 1}\\right\\rfloor)$ flowers with $x + 1$ petal we can buy. So we need to find maximum over all such $k_1 * x + k_2 * (x + 1)$. Total complexity is $O(\\sum_{x} c_{x}) = O(n)$ for finding the maximum and $O(n \\log n)$ for sorting.",
    "code": "tests = int(input())\np = 10 ** 9 + 7\n \n \ndef pow(x, q):\n    if q == 0:\n        return 1\n    i = pow(x, q // 2)\n    if q % 2 == 0:\n        return (i * i) % p\n    return (i * i * x) % p\n \n \ndef solve():\n    global p\n    n, m = map(int, input().split(\" \"))\n    a = list(map(int, input().split(\" \")))\n    hs = {}\n    for x in a:\n        if x not in hs:\n            hs[x] = 0\n        hs[x] += 1\n    ans = 0\n    for x in hs:\n        y = hs[x]\n        l = min(m // x, y)\n        ans = max(ans, l * x)\n        if x + 1 not in hs:\n            continue\n        z = hs[x + 1]\n        for i in range(1, y + 1):\n            if i * x > m:\n                break\n            du = m - i * x\n            su = min(du // (x + 1), z) * (x + 1) + i * x\n            ans = max(su, ans)\n    print(ans)\n \n \nfor _ in range(tests):\n    solve()\n \n\t\n \n\t\n \n \t\n \n  \n \n\t\n ",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1995",
    "index": "B2",
    "title": "Bouquet (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is that in this version, instead of listing the number of petals for each flower, the number of petals and the quantity of flowers in the store is set for all types of flowers.}\n\nA girl is preparing for her birthday and wants to buy the most beautiful bouquet. There are a total of $n$ different types of flowers in the store, each of which is characterized by the number of petals and the quantity of this type of flower. A flower with $k$ petals costs $k$ coins. The girl has decided that the difference in the number of petals between any two flowers she will use to decorate her cake should not exceed one. At the same time, the girl wants to assemble a bouquet with the maximum possible number of petals. Unfortunately, she only has $m$ coins, and she cannot spend more. What is the maximum total number of petals she can assemble in the bouquet?",
    "tutorial": "Maybe there is a way to change bruteforce into checking optimal values for counts of $x, x + 1$? Maybe there are only few types of optimal bouquets for $x, x + 1$? We already have a list of $c_x$. We can use hash map to be able to check for any $c_x$ by $x$. We again will try to assemble the bouquet only with flowers with $x, x + 1$ petals. We set $k1 = min(c_{x}, \\left\\lfloor\\frac{m}{x}\\right\\rfloor)$. Then we have $coins = m - k1 * x$. Let's set $k2 = min(c_{x + 1}, \\left\\lfloor\\frac{coins}{x + 1}\\right\\rfloor)$. Then we have $coins = m - (k1 * x + k2 * (x + 1))$. Let's substitute flower with $x$ petals with flower with $x + 1$ petals as many times as we can. This can be done $r = min(k1, c_{x + 1} - k2, coins)$ times, as each operation will require us 1 coin, 1 flower in the bouquet with $x$ petals and one 1 flower with $x + 1$ petals not in the bouquet. In total we can get $(k1 - r) * x + (k2 + r) * (x + 1)$ petals. This assembling is optimal. Here is why. Suppose that we have $0 \\le b1 \\le c_{x}$ flowers with $x$ petals and $0 \\le b2 \\le c_{x + 1}$ flowers with $x + 1$ petals and greater total value of $b1 * x + b2 * (x + 1)$. We already know that $b1 \\le k1$ by choosing of $k1$. If $k1 - r < b1$, then we can ''undo'' our operation $r + b1 - k1$ times, sum is still not greater than $m$, and we know that now there can't be more than $k2 + r + b1 - k1$ flowers with $x + 1$ petals, as otherwise we didn't chose optimal $k2$. If $k2 + r < b2$, then $r \\ne c_{x + 1} - k2$, if $r = k1$ then it is just the case when we have only flowers with $x + 1$ petals which will be considered in case $x + 1, x + 2$, if $r = coins$ then $m = (k1 - r) * x + (k2 + r) * (x + 1)$ and we already found the maximum. So $b2 \\le k2 + r$ and $b1 \\le k1 - r$ and $b1 * x + b2 * (x + 1)$ is not better than optimal. Total time complexity is $O(n)$.",
    "code": "def solve():\n    n, m = map(int, input().split(\" \"))\n    a = list(map(int, input().split(\" \")))\n    c = list(map(int, input().split(\" \")))\n    ch = {}\n    ans = 0\n    for a1, c1 in zip(a, c):\n        if a1 not in ch:\n            ch[a1] = 0\n        ch[a1] += c1\n    for x, c_x in ch.items():\n        ans = max(ans, min(m // x, c_x) * x)\n        if x + 1 in ch:\n            c_x1 = ch[x + 1]\n            k1 = min(m // x, c_x)\n            pred = x * k1\n            c_x -= k1\n            coins = m - pred\n            if coins >= x + 1:\n                k2 = min(coins // (x + 1), c_x1)\n                pred += k2 * (x + 1)\n                c_x1 -= k2\n                coins = m - pred\n            ans = max(ans, min(m // (x + 1), c_x1))\n            pred += min([coins, c_x1, k1])\n            ans = max(pred, ans)\n    print(ans)\n \n \ndef main():\n    tests = int(input())\n    for _ in range(tests):\n        solve()\n \n \nmain()",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "1995",
    "index": "C",
    "title": "Squaring",
    "statement": "ikrpprpp found an array $a$ consisting of integers. He likes justice, so he wants to make $a$ fair — that is, make it non-decreasing. To do that, he can perform an act of justice on an index $1 \\le i \\le n$ of the array, which will replace $a_i$ with $a_i ^ 2$ (the element at position $i$ with its square). For example, if $a = [2,4,3,3,5,3]$ and ikrpprpp chooses to perform an act of justice on $i = 4$, $a$ becomes $[2,4,3,9,5,3]$.\n\nWhat is the minimum number of acts of justice needed to make the array non-decreasing?",
    "tutorial": "How many times we need to apply the operation to index $i$, so that $a[i - 1] \\leq a[i]$? Let's call it $op[i]$ It's easy to calculate these values in no time. Can we just accumulate them? We almost can. But, let's take $[4, 2, 4]$ as an example. op[2] = 1, but we don't want to do anything with a[3]. So, sometimes $a[i - 1] \\le a[i]$ and we may not want touch a[i] at all, even if something was applied before it. So, should we consider making $op[i] < 0$ for some $i$? Let's set $op[i]$ to the number of operation we need to apply to index $i$ so that $a[i - 1] \\leq a[i]$. But, if $a[i - 1] \\ll a[i]$, let's set it to the negative number of times that we can apply the operation to $a[i - 1]$ so that $a[i - 1] \\leq a[i]$ still holds. Now let's just calculate the prefix sum $\\texttt{prefix_op}$, don't forget to do $\\max(0, \\texttt{prefix_op}[i])$. The sum of values in $\\texttt{prefix_op}$ is the answer. Let's try to go to the logarithmic space to get rid of too big numbers. $\\log(x * x) = 2\\log(x)$ So, if we replace each value with its logarithm, the operation of squaring becomes multiplying by 2. But this is not good enough, since we may need to do the operation thousands of times, $2^{1000}$ is too big, it doesn't fit into any floating point. So, let's just repeat our trick and go to the log-log space $\\log(2 * y) = \\log(y) + \\log(2)$ Now we see that the operation turns into just adding $\\log(2)$. We can afford doing that thousands and millions of times. Let's deine $b[i] = \\log{\\log{a[i]}}$ So now, we can just go with a for-loop and do $\\displaystyle{\\left\\lceil\\frac{b[i] - b[i - 1]}{\\log(2)}\\right\\rceil}$ opeartions with $i$-th element, updating $b[i]$ accordingly. Since initially $b[i] \\leq \\log(10^6) \\leq 20 \\log(2)$, we can maintain the invariant that $b[i] \\leq (20 + i)\\log(2)$ since after applying an operation to $b[i]$ we can't exceed $b[i - 1]$ by more than $\\log(2)$. It means that the final numbers in the log-log space won't exceed $(n + 20)\\log(2)$. We can maintain $O(n)$ arithmetics using double without any problems.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define F first\n#define S second\ntypedef long long       ll;\ntypedef long double     ld;\ntypedef pair<ll, ll>   pll; \ntypedef pair<int, int> pii; \n \nconst long long kk = 1000;\nconst long long ml = kk * kk;\nconst long long mod = ml * kk + 7;\nconst long long inf = ml * ml * ml + 7; \nconst ld eps = 1e-9; \n \n \nint n;\nvector<ld> v;\n \nvoid solve() {\n\tcin >> n;\n\tv.resize(n);\n\tfor (auto &i : v)\n\t\tcin >> i;\n \n\treverse(v.begin(), v.end());\n\twhile (v.size() && v.back() == 1)\n\t\tv.pop_back();\n\treverse(v.begin(), v.end());\n \n\tfor (auto i : v)\n\t\tif (i == 1) {\n\t\t\tcout << \"-1\\n\";\n\t\t\treturn;\n\t\t}\n \n \n\tfor (auto &i : v)\n\t\ti = log(log(i));\n \n\tll ans = 0;\n\tfor (int i = 1; i < v.size(); i++) {\n\t\tld need = v[i - 1] - v[i];\n\t\tif (need > eps) {\n\t\t\tint cnt = 1 + (need - eps) / log(2);\n\t\t\tans += cnt;\n\t\t\tv[i] += cnt * log(2);\n\t\t}\n\t}\n \n\tcout << ans << '\\n';\n}\n \nint main() {\n\tios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\tint t = 1; \n\tcin >> t;\n\twhile (t--)\n\t\tsolve();\n \n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "1995",
    "index": "D",
    "title": "Cases",
    "statement": "You're a linguist studying a mysterious ancient language. You know that\n\n- Its words consist only of the first $c$ letters of the Latin alphabet.\n- Each word has a case which can be unambiguously determined by its last letter (different letters correspond to different cases). For example, words \"ABACABA\" and \"ABA\" (if they exist) have the same case in this language because they both have the same ending 'A', whereas \"ALICE\" and \"BOB\" have different cases. If the language does not have a case corresponding to some letter, it means that the word cannot end with this letter.\n- The length of each word is $k$ or less.\n\nYou have a single text written in this language. Unfortunately, as the language is really ancient, spaces between words are missing and all letters are uppercase. You wonder what is the minimum number of cases the language can have. Can you find this out?",
    "tutorial": "If letter is chosen as an ending to some case, each occurrence of this letter may in the text can be considered an ending? The length of the word is something too complex. How can you simplify the restriction? The final letter must be an ending of some case and among any $k$ consecutive letters there must be at least one ending. Now you don't need the text because you can store bitmasks instead of substrings of length $k$. To calculate the bitmasks you can use prefix sums for each of the characters (it will take $O(cn)$ overall). Now you need to find a bitmask with a minimal number of ones which intersects all the stored bitmasks. Identify \"bad\" bitmask instead of \"good\" ones. (Read the hints.) $b$ is bad if there exists stored $a$ such that $a \\text{&} b = 0$ which is equivalent to $b$ being a submask of $\\text{~}a$. All such b can be found using simple dp on bitmasks. The rest $b$ are good. Time complexity: $O(c n + c 2^c)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n, c, k;\n    cin >> n >> c >> k;\n \n    string s;\n    cin >> s;\n \n    vector<vector<int>> cumsums(c, vector<int>(n + 1));\n \n    for (int i = 0; i < c; ++i)\n        for (int j = 0; j < n; ++j)\n            cumsums[i][j + 1] = cumsums[i][j] + (s[j] == i + 'A');\n \n    vector<bool> bms(1 << c);\n \n    for (int lo = 0; lo <= n - k; ++lo) {\n        int ms = 0;\n        for (int i = 0; i < c; ++i)\n            if (cumsums[i][lo + k] - cumsums[i][lo] != 0) ms |= (1 << i);\n        bms[ms] = true;\n    }\n    bms[1 << (s.back() - 'A')] = true;\n \n    vector<bool> bad(1 << c);\n    for (int i = 0; i < (1 << c); ++i)\n        bad[i] = bms[((1 << c) - 1) ^ i];\n \n    for (int bm = (1 << c) - 1; bm >= 0; --bm)\n        for (int b = 0; b < c; ++b)\n            bad[bm] = bad[bm | (1 << b)] | bad[bm];\n \n    int res = 1'000'000'000;\n \n    for (int i = 0; i < (1 << c); ++i)\n        if (!bad[i]) res = min(res, __builtin_popcount(i));\n    cout << res << '\\n';\n}\n \nsigned main() {\n    std::ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int t = 1;\n    cin >> t;\n    while (t--) solve();\n \n    return 0;\n}\n  \t\n \n\t\n\t \n \t \n \t \t",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "1995",
    "index": "E1",
    "title": "Let Me Teach You a Lesson (Easy Version)",
    "statement": "\\textbf{This is the easy version of a problem. The only difference between an easy and a hard version is the constraints on $t$ and $n$. You can make hacks only if both versions of the problem are solved.}\n\nArthur is giving a lesson to his famous $2 n$ knights. Like any other students, they're sitting at the desks in pairs, but out of habit in a circle. The knight $2 i - 1$ is sitting at the desk with the knight $2 i$.\n\nEach knight has intelligence, which can be measured by an integer. Let's denote the intelligence of the $i$-th knight as $a_i$. Arthur wants the maximal difference in total intelligence over all pairs of desks to be as small as possible. More formally, he wants to minimize $\\max\\limits_{1 \\le i \\le n} (a_{2 i - 1} + a_{2 i}) - \\min\\limits_{1 \\le i \\le n} (a_{2 i - 1} + a_{2 i})$.\n\nHowever, the Code of Chivalry only allows swapping the opposite knights in the circle, i.e., Arthur can simultaneously perform $a_i := a_{i + n}$, $a_{i + n} := a_i$ for any $1 \\le i \\le n$. Arthur can make any number of such swaps. What is the best result he can achieve?",
    "tutorial": "Consider cases of odd and even $n$. Which one is simpler? Even. In this case you can solve the problem for the opposite desks independently. From now on $n$ is odd. Let a desk have knights with intelligence $a$, $b$ and the opposite one with $c$, $d$. Since $(a + b) + (c + d) = (a + c) + (b + d)$, the minimal total intelligence on these desks is greater iff the maximal total intelligence is less. If you reorder desks/knights in a way that you swap neighbors (i.e. $2$ with $3$, $4$ with $5$, ..., $2 n$ with $1$) instead of opposite knights, it'll probably become easier to think about this problem. We will use this notation from now on. You're allowed to run in $O(n^2)$. Wouldn't it have sense to fix some entity and solve in linear time for fixed entity? Fix the minimal (maximal) desk and the knights who are sitting at it (if the original knights were swapped or not). You'll need to find the minimal maximum on a desk for $4 n$ such cases. DP. (Read the hints.) Let the fixed desk have index $k$. Let $dp_{i, b}$ (where $i$ is the index of the desk and $b$ is $0$ / $1$ which indicates whether the knight $2 i$ was swapped) be the minimal maximum that can be achieved on a segment from $k$ to $i$ (satisfying bit $b$ and the fact that the desk $k$ is actually minimal). Then you can easily make transitions $dp_{i, 0}, dp_{i, 1} \\to dp_{i + 1, 0}, dp_{i + 1, 1}$. In the end you'll just need to check $dp_{k - 1, b'}$ where $b'$ indicates whether the knight $2 * k - 1$ was swapped in our choice. (All the indices for the desks are taken modulo $n$ and all the indices for the knights are taken modulo $2 n$.) Time complexity: $O(n^2)$, but the constant is large and $O(n^2\\log n)$ solutions with binary search are unlikely to pass.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconstexpr int VB = 2'000'000'001;\n \n \nvoid solve() {\n#define M(x) (((x) + 2 * n) % (2 * n))\n    int n;\n    cin >> n;\n \n    vector<int> v(2 * n);\n    for (auto &e: v) {\n        cin >> e;\n    }\n \n    if (n % 2 == 0) {\n        int ma = 0;\n        int mi = VB;\n        for (int i = 0; i < n / 2; ++i) {\n            int s[4]{v[2 * i] + v[2 * i + 1],\n                     v[2 * i] + v[2 * i + n + 1],\n                     v[2 * i + n] + v[2 * i + n + 1],\n                     v[2 *i + n] + v[2 * i + 1]\n            };\n            sort(s, s + 4);\n            ma = max(ma, s[2]);\n            mi = min(mi, s[1]);\n        }\n        cout << ma - mi << '\\n';\n        return;\n    }\n    if (n == 1) {\n        cout << 0 << '\\n';\n        return;\n    }\n    vector<int> r;\n    int cur = 0;\n    for (int i = 0; i < n; ++i) {\n        r.push_back(v[cur]);\n        r.push_back(v[cur ^= 1]);\n        cur = M(cur + n);\n    }\n    \n    int ans = VB;\n \n    for (int id = 0; id < n; ++id) {\n        for (int m1 = 0; m1 < 2; ++m1) {\n            for (int m2 = 0; m2 < 2; ++m2) {\n                int mi_value = r[M(2 * id - m1)] + r[M(2 * id + 1 + m2)];\n                vector<int> dp[2]{\n                    vector<int>(n, VB),\n                    vector<int>(n, VB)};\n                dp[m2][id] = mi_value;\n                for (int j = 1; j < n; ++j) {\n                    int jd = (id + j) % n;\n                    int pd = (id + j - 1) % n;\n                    for (int pc = 0; pc < 2; ++pc) {\n                        for (int jc = 0; jc < 2; ++jc) {\n                            if (dp[pc][pd] != VB && r[M(2 * jd - pc)] + r[M(2 * jd + 1 + jc)] >= mi_value)\n                                dp[jc][jd] = min(dp[jc][jd], max(dp[pc][pd], r[M(2 * jd - pc)] + r[M(2 * jd + 1 + jc)]));\n                        }\n                    }\n                }\n                \n                int pd = (id + n - 1) % n;\n                if (dp[m1][pd] != VB) ans = min(ans, dp[m1][pd] - mi_value);\n            }\n        }\n    }\n    \n    cout << ans << '\\n';\n}\n \nsigned main() {\n    std::ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int t = 1;\n    cin >> t;\n    while (t--) solve();\n \n    return 0;\n}\n\t\t\t\n \n \n\t\n \n\t\n \n \n  \n ",
    "tags": [
      "2-sat",
      "data structures",
      "dp",
      "matrices",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1995",
    "index": "E2",
    "title": "Let Me Teach You a Lesson (Hard Version)",
    "statement": "\\textbf{This is the hard version of a problem. The only difference between an easy and a hard version is the constraints on $t$ and $n$. You can make hacks only if both versions of the problem are solved.}\n\nArthur is giving a lesson to his famous $2 n$ knights. Like any other students, they're sitting at the desks in pairs, but out of habit in a circle. The knight $2 i - 1$ is sitting at the desk with the knight $2 i$.\n\nEach knight has intelligence, which can be measured by an integer. Let's denote the intelligence of the $i$-th knight as $a_i$. Arthur wants the maximal difference in total intelligence over all pairs of desks to be as small as possible. More formally, he wants to minimize $\\max\\limits_{1 \\le i \\le n} (a_{2 i - 1} + a_{2 i}) - \\min\\limits_{1 \\le i \\le n} (a_{2 i - 1} + a_{2 i})$.\n\nHowever, the Code of Chivalry only allows swapping the opposite knights in the circle, i.e., Arthur can simultaneously perform $a_i := a_{i + n}$, $a_{i + n} := a_i$ for any $1 \\le i \\le n$. Arthur can make any number of such swaps. What is the best result he can achieve?",
    "tutorial": "Read the first two hints to E1. There are $4 n$ possible desks in total. One of them will be the minimal desk and another one will be the maximal. What is the common-used technique for such problems? Sort them and then use two pointers. The data structure you need is very famous. (Read the hints.) Assign a boolean matrix $2 \\times 2$ to each of the desks. Rows correspond to the first knight at the desk (two rows for each of the events \"the knight was swapped\" / \"the knight was not swapped\"), columns correspond to the second one. The value in the intersection is true if under current restrictions (minimum and maximum) both events can happen, i.e. the result on the desk is between minimum and maximum. What is a (boolean) multiplication of matrices from $d_l$ to $d_r$? The matrix where the rows correspond to the knight $2 d_l - 1$ and the columns correspond to the knight $2 d_r$. To determine whether it's possible to swap the knights under current restrictions you can just multiply all the matrices and check if there are ones on the main diagonal. Now using two pointers and a segment tree on these matrices you can solve the problem (basically, when you leave some option for a desk in the sorted array of options, you change one of the values of this matrix from $1$ to $0$, and vice versa).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nstruct desk {\n    bool t[2][2]{};\n \n    desk() = default;\n    desk(bool t11, bool t01, bool t10, bool t00) : t{{t00, t01}, {t10, t11}} {\n    }\n};\n \ndesk operator*(const desk &a, const desk &b) {\n    desk c {a.t[1][1] && b.t[1][1] || a.t[1][0] && b.t[0][1],\n            a.t[0][1] && b.t[1][1] || a.t[0][0] && b.t[0][1],\n            a.t[1][1] && b.t[1][0] || a.t[1][0] && b.t[0][0],\n            a.t[0][0] && b.t[0][0] || a.t[0][1] && b.t[1][0]};\n    return c;\n}\n \nconstexpr int shift = 1 << 17;\ndesk sg[shift << 1];\n \nvoid sg_set(int index, const desk &d) {\n    index += shift;\n    sg[index] = d;\n    do {\n        index >>= 1;\n        sg[index] = sg[index * 2] * sg[index * 2 + 1];\n    } while (index > 1);\n}\n \nvoid sg_clear(int n_indices) {\n    for (int i = 0; i < n_indices; ++i) {\n        sg_set(i, {});\n    }\n}\n \ndesk sg_get(int index) {\n    return sg[index + shift];\n}\n \ndesk sg_get(int lo, int hi) {\n    std::function<desk(int, int)> inner = [&inner](int lo, int hi) -> desk {\n        if (lo == hi - 1) return sg[lo];\n        if (lo % 2) return sg[lo] * inner(lo + 1, hi);\n        if (hi % 2) return inner(lo, hi - 1) * sg[hi - 1];\n        return inner(lo / 2, hi / 2);\n    };\n    return inner(lo + shift, hi + shift);\n}\n \nstruct desk_poss {\n    int val = 0;\n    int m1 = 0;\n    int m2 = 0;\n    int di = 0;\n    desk_poss(int val, int m1, int m2, int di) : val(val), m1(m1), m2(m2), di(di) {\n    }\n};\n \nvoid solve() {\n    int n;\n    cin >> n;\n \n    vector<int> v(2 * n);\n    for (auto &e: v) {\n        cin >> e;\n    }\n \n    if (n % 2 == 0) {\n        int ma = 0;\n        int mi = 2'000'000'001;\n        for (int i = 0; i < n / 2; ++i) {\n            int s[4]{v[2 * i] + v[2 * i + 1],\n                     v[2 * i] + v[2 * i + n + 1], \n                     v[2 * i + n] + v[2 * i + n + 1],\n                     v[2 *i + n] + v[2 * i + 1]\n                    };\n            sort(s, s + 4);\n            ma = max(ma, s[2]);\n            mi = min(mi, s[1]);\n        }\n        cout << ma - mi << '\\n';\n        return;\n    }\n    if (n == 1) {\n        cout << 0 << '\\n';\n        return;\n    }\n    vector<int> r;\n    int cur = 0;\n    for (int i = 0; i < n; ++i) {\n        r.push_back(v[cur]);\n        r.push_back(v[cur ^= 1]);\n        cur = (cur + n) % (2 * n);\n    }\n    vector<desk_poss> posses;\n    for (int d = 0; d < n; ++d) {\n        posses.emplace_back(r[2 * d] + r[2 * d + 1], 1, 1, d);\n        posses.emplace_back(r[(2 * d + 2 * n - 1) % (2 * n)] + r[2 * d + 1], 0, 1, d);\n        posses.emplace_back(r[(2 * d + 2 * n - 1) % (2 * n)] + r[(2 * d + 2) % (2 * n)], 0, 0, d);\n        posses.emplace_back(r[2 * d] + r[(2 * d + 2) %  (2 * n)], 1, 0, d);\n    }\n \n    sg_clear(n);\n    sort(posses.begin(), posses.end(), [](const auto &a,const auto &b) {\n        return a.val < b.val;\n    });\n    int loi = 0;\n    int hii = 0;\n    int ans = 2'000'000'001;\n    while (true) {\n        auto d = sg_get(0, n);\n        if (d.t[0][0] || d.t[1][1]) {\n            auto lop = posses[loi];\n            ans = min(ans, posses[hii - 1].val - lop.val);\n            auto extr = sg_get(lop.di);\n            extr.t[lop.m1][lop.m2] = false;\n            sg_set(lop.di, extr);\n            ++loi;\n        } else {\n            if (hii == 4 * n) break;\n            auto hip = posses[hii];\n            auto extr = sg_get(hip.di);\n            extr.t[hip.m1][hip.m2] = true;\n            sg_set(hip.di, extr);\n            ++hii;\n        }\n    }\n    cout << ans << '\\n';\n}\n \nsigned main() {\n    std::ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int t = 1;\n    cin >> t;\n    while (t--) solve();\n \n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "matrices",
      "two pointers"
    ],
    "rating": 2900
  },
  {
    "contest_id": "1996",
    "index": "A",
    "title": "Legs",
    "statement": "It's another beautiful day on Farmer John's farm.\n\nAfter Farmer John arrived at his farm, he counted $n$ legs. It is known only chickens and cows live on the farm, and a chicken has $2$ legs while a cow has $4$.\n\nWhat is the minimum number of animals Farmer John can have on his farm assuming he counted the legs of all animals?",
    "tutorial": "If $n$ is a multiple of $4$, then you can have $\\frac{n}{4}$ cows. Otherwise, you must have at least one chicken, so you can have $\\frac{n-2}{4}$ cows and $1$ chicken.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int tc;\n    cin >> tc;\n\n    while (tc--){\n        int n;\n        cin >> n;\n\n        cout << (n + 2) / 4 << \"\\n\";\n    }\n}",
    "tags": [
      "binary search",
      "math",
      "ternary search"
    ],
    "rating": 800
  },
  {
    "contest_id": "1996",
    "index": "B",
    "title": "Scale",
    "statement": "Tina has a square grid with $n$ rows and $n$ columns. Each cell in the grid is either $0$ or $1$.\n\nTina wants to reduce the grid by a factor of $k$ (\\textbf{$k$ is a \\underline{divisor} of $n$}). To do this, Tina splits the grid into $k \\times k$ nonoverlapping blocks of cells such that every cell belongs to exactly one block.\n\nTina then replaces each block of cells with a single cell equal to the value of the cells in the block. \\textbf{It is guaranteed that every cell in the same block has the same value}.\n\nFor example, the following demonstration shows a grid being reduced by factor of $3$.\n\n\\begin{center}\n\\textbf{Original grid} \\begin{tabular}{|c||c||c||c||c||c|}\n\\hline\n$0$ & $0$ & $0$ & $1$ & $1$ & $1$ \\\n\\hline\n\\hline\n$0$ & $0$ & $0$ & $1$ & $1$ & $1$ \\\n\\hline\n\\hline\n$0$ & $0$ & $0$ & $1$ & $1$ & $1$ \\\n\\hline\n\\hline\n$1$ & $1$ & $1$ & $0$ & $0$ & $0$ \\\n\\hline\n\\hline\n$1$ & $1$ & $1$ & $0$ & $0$ & $0$ \\\n\\hline\n\\hline\n$1$ & $1$ & $1$ & $0$ & $0$ & $0$ \\\n\\hline\n\\end{tabular}\n\\end{center}\n\n\\begin{center}\n\\textbf{Reduced grid} \\begin{tabular}{|c||c|}\n\\hline\n$0$ & $1$ \\\n\\hline\n\\hline\n$1$ & $0$ \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nHelp Tina reduce the grid by a factor of $k$.",
    "tutorial": "Let's define every $k$ by $k$ block of cells by its value in the top left corner, since all cells in the block must have the same value. So, we can just print out the value of the cell in every $k$'th row and every $k$'th column.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int tc;\n    cin >> tc;\n\n    while (tc--){\n        int n, k;\n        cin >> n >> k;\n\n        char A[n][n];\n        \n        for (auto &row : A)\n            for (char &c : row)\n                cin >> c;\n        \n        for (int i = 0; i < n; i += k){\n            for (int j = 0; j < n; j += k){\n                cout << A[i][j];\n            }\n            cout << \"\\n\";\n        }\n    }\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1996",
    "index": "C",
    "title": "Sort",
    "statement": "You are given two strings $a$ and $b$ of length $n$. Then, you are (forced against your will) to answer $q$ queries.\n\nFor each query, you are given a range bounded by $l$ and $r$. In one operation, you can choose an integer $i$ ($l \\leq i \\leq r$) and set $a_i = x$ where $x$ is any character you desire. Output the minimum number of operations you must perform such that $sorted(a[l..r]) = sorted(b[l..r])$. \\textbf{The operations you perform on one query does not affect other queries.}\n\nFor an arbitrary string $c$, $sorted(c[l..r])$ denotes the substring consisting of characters $c_l, c_{l+1}, ... , c_r$ sorted in lexicographical order.",
    "tutorial": "For two strings to be the same after sorting, they must have the same occurrences of every possible lowercase letter. To answer the query for a range $[l, r]$, we must ensure that after the operations, $cnt_c = cnt2_c$ must where $cnt_c$ is the number of times character $c$ occurs in the range for $a$ and $cnt2_c$ is defined similarly for $b$. Both $cnt_c$ and $cnt2_c$ can be obtained by doing prefix sums for character $c$ specifically. Note that since there are only $26$ possible $c$, you can afford to create $26$ length $n$ prefix sum arrays. In one operation, you can replace one occurrence of a character $c$ with another character $c2$. Essentially, you are subtracting one from $cnt_c$ and adding one to $cnt_{c2}$. Obviously, you must choose $c$ and $c2$ such that $cnt_c > cnt2_c$ and $cnt_{c2} < cnt2_{c2}$. So, we only have to focus on $c$ or $c2$ since one decreasing will automatically lead to the other increase. The answer is just the sum of $cnt_c - cnt2_c$ if $cnt_c > cnt2_c$ over all possible lowercase characters $c$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\nvoid solve(){\n    int n, q;\n    cin >> n >> q;\n\n    vector<vector<int>> pre1(n + 1, vector<int>(26, 0));\n    vector<vector<int>> pre2(n + 1, vector<int>(26, 0));\n\n    for (int i = 1; i <= n; i++){\n        char c;\n        cin >> c;\n        pre1[i][c - 'a']++;\n\n        for (int j = 0; j < 26; j++)\n            pre1[i][j] += pre1[i - 1][j];\n    }\n    for (int i = 1; i <= n; i++){\n        char c;\n        cin >> c;\n        pre2[i][c - 'a']++;\n\n        for (int j = 0; j < 26; j++)\n            pre2[i][j] += pre2[i - 1][j];\n    }\n    while (q--){\n        int l, r;\n        cin >> l >> r;\n\n        int dif = 0;\n\n        for (int c = 0; c < 26; c++){\n            int v1 = pre1[r][c] - pre1[l - 1][c];\n            int v2 = pre2[r][c] - pre2[l - 1][c];\n\n            dif += abs(v1 - v2);\n        }\n        cout << dif / 2 << \"\\n\";\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "1996",
    "index": "D",
    "title": "Fun",
    "statement": "\\begin{quote}\nCounting is Fun!\n\\hfill — satyam343\n\\end{quote}\n\nGiven two integers $n$ and $x$, find the number of triplets ($a,b,c$) of \\textbf{positive integers} such that $ab + ac + bc \\le n$ and $a + b + c \\le x$.\n\nNote that order matters (e.g. ($1, 1, 2$) and ($1, 2, 1$) are treated as different) and $a$, $b$, $c$ must be strictly greater than $0$.",
    "tutorial": "There are several solutions to this problem, The easiest way is to just fix either $a$, $b$ or $c$. Let's fix $a$. Since $ab + ac + bc \\leq n$, we know at the minimum, $ab \\leq n$. Divide on both sides to get $b \\leq \\frac{n}{a}$. When $a = 1$, there are $n$ choices for $b$. When $a = 2$, there are $\\frac{n}{2}$ choices for $b$. So in total, there are $n + \\frac{n}{2} + \\frac{n}{3} + ... + \\frac{n}{n}$ total choices for $b$. This is just the harmonic series, so over all possible $a$, there are about $n \\log n$ choices for $b$. Therefore, we can afford to loop through both $a$ and $b$. Now that we have $a$ and $b$, all that's left is to solve for $c$. Let's solve for $c$ in both equations. In the first equation, we can factor $c$ out to obtain $ab + c(a+b) \\leq n$. So, $c \\leq \\frac{n-ab}{a+b}$. In the second equation, $c \\leq x - a - b$. Since we want the $c$ to satisfy both inequalities, we must choose the stricter one. So, the number of possible $c$ is $\\min(\\frac{n-ab}{a+b},x-a-b)$. The answer is the sum of number of possible $c$ over all possible $a$ and $b$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int tc;\n    cin >> tc;\n\n    while (tc--){\n        int n, x;\n        cin >> n >> x;\n\n        long long ans = 0;\n        \n        for (int a = 1; a <= min(n, x); a++){\n            for (int b = 1; a * b <= n and a + b <= x; b++){\n                int highestC = min((n - a * b) / (a + b), x - (a + b));\n                ans += highestC;\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1996",
    "index": "E",
    "title": "Decode",
    "statement": "{In a desperate attempt to obtain your \\sout{waifu} favorite character, you have hacked into the source code of the game. After days of struggling, you finally find the binary string that encodes the gacha system of the game. In order to decode it, you must first solve the following problem.}\n\nYou are given a binary string $s$ of length $n$. For each pair of integers $(l, r)$ $(1 \\leq l \\leq r \\leq n)$, count the number of pairs $(x, y)$ $(l \\leq x \\leq y \\leq r)$ such that the amount of $\\mathtt{0}$ equals the amount of $\\mathtt{1}$ in the substring $s_xs_{x+1}...s_y$.\n\nOutput the sum of counts over all possible $(l, r)$ modulo $10^9+7$.",
    "tutorial": "How can we efficiently check if a range contains the same amount of zeroes and ones? Let's create an array $a$ where $a_i = -1$ if $s_i = 0$ and $a_i = 1$ if $s_i = 1$. Let's denote $p$ as the prefix sum array of $a$. We want the contribution of $-1$ by the zeroes to cancel out with the ones, so if $p_r - p_{l-1} = 0$, then the range $[l, r]$ contain equal amounts of zeroes and ones. We can rephrase the problem as the following: for each subrange $[l, r]$, count the number of pairs $(x,y)$ such that $p_{x-1} = p_y$. Let's fix $p_{x-1}$ and keep track of all potential $y$ such that $y > x$ and $p_{x-1} = p_{y}$. How many subarrays will cover $[x, y]$? Well, we have $x+1$ options as $l$ and $n-y+1$ options as $r$, so the range $[x,y]$ contributes to $(x+1) \\cdot (n-y+1)$ subarrays. We just need to calculate this expression for all potential $y$ now. Let's denote the all possible $y$ as $y_1, y_2, ... y_k$. We are asked to find the sum of $(x+1) \\cdot (n-y_1+1) + (x+1) \\cdot (n-y_2+1) + \\dots + (x+1) \\cdot (n-y_k+1)$. Let's factor $(x+1)$ out, and we have $(x+1) \\cdot ((n-y_1+1)+(n-y_2+1)+\\dots+(n-y_k+1))$. Since, the second part of the expression is just the sum of all $(n-y_i+1)$, we can first precalculate that sum and since $y > x$, subtract as we sweep from left to right.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\n#define ll long long\n\nconst int MOD = 1e9 + 7;\n\nvoid solve(){\n    string S;\n    cin >> S;\n\n    int n = S.size();\n    S = \" \" + S;\n\n    vector<int> P(n + 1, 0);\n\n    for (int i = 1; i <= n; i++){\n        P[i] = (S[i] == '1' ? 1 : -1) + P[i - 1];\n    }\n\n    map<int, ll> cnt;\n    ll ans = 0;\n\n    for (int i = 0; i <= n; i++){\n        ans = (ans + (n - i + 1) * cnt[P[i]]) % MOD;\n        cnt[P[i]] = (cnt[P[i]] + (i + 1)) % MOD;\n    }\n    cout << ans << \"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "1996",
    "index": "F",
    "title": "Bomb",
    "statement": "Sparkle gives you two arrays $a$ and $b$ of length $n$. Initially, your score is $0$. In one operation, you can choose an integer $i$ and add $a_i$ to your score. Then, you must set $a_i$ = $\\max(0, a_i - b_i)$.\n\nYou only have time to perform $k$ operations before Sparkle sets off a nuclear bomb! What is the maximum score you can acquire after $k$ operations?",
    "tutorial": "Let's first solve the problem in $\\mathcal{O}(k)$. One possible solution is to loop through each operation and take the largest $a_i$ each time, and set $a_i = \\max(0, a_i - b_i)$. This can be done with a set or a priority queue. With that in mind, let's binary search for the largest $x$ such that every value we add to our score has been greater or equal to $x$ for all $k$ operations. Define $f(x)$ as the number of operations required for every $a_i$ to be less than $x$. Specifically, $f(x) = \\sum_{i=1}^n \\lceil \\frac{a_i-x}{b_i} \\rceil$. We are searching for the smallest $x$ such that $f(x) \\leq k$. Once we've found $x$, we can subtract $f(x)$ from $k$. Note that now, $k$ must be less than to $n$ (otherwise we can another operation on all $a_i$). So, it suffices to run the slow solution for these remaining operations (as long as $a_i > 0$). Alternatively, we can notice that the remaining operations will all add $x-1$ to our answer (assuming $x > 0$). To obtain the sum of all $a_i$ we collected when calculating $f(x)$, we can use the arithmetic sequence sum formula. For each $i$, the number of terms in the sequence is $t = \\lceil \\frac{a_i-x}{b_i} \\rceil$. The first term of the sequence is $f = a_i - b_i \\cdot (t-1)$. The last term is $a_i$. Using the formula, we can add $\\frac{t}{2}(f+a_i)$ to the answer.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\n#define ll long long\n\nvoid solve(){\n    int n, k;\n    cin >> n >> k;\n\n    vector<int> A(n), B(n);\n    \n    for (int &i : A)\n        cin >> i;\n    for (int &i : B)\n        cin >> i;\n\n    auto getInfo = [&](int cutoff){\n        ll ops = 0;\n        ll sum = 0;\n\n        for (int i = 0; i < n; i++){\n            ll a = A[i];\n            ll b = B[i];\n\n            if (cutoff > a)\n                continue;\n\n            // a - uses * b >= cutoff\n            ll uses = (a - cutoff) / b;\n            sum += (uses + 1) * a - b * uses * (uses + 1) / 2; \n            ops += uses + 1;\n\n            sum = min(sum, 2 * (ll)1e18);\n        }\n        return make_pair(sum, ops);\n    };\n\n    int L = 0, H = 1e9 + 5;\n\n    while (L < H){\n        int M = (L + H) / 2;\n        getInfo(M).second <= k ? H = M : L = M + 1;\n    }\n\n    auto [ans, opsUse] = getInfo(L);\n    cout << ans + (k - opsUse) * max(L - 1, 0) << \"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0);\n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1996",
    "index": "G",
    "title": "Penacony",
    "statement": "On Penacony, The Land of the Dreams, there exists $n$ houses and $n$ roads. There exists a road between house $i$ and $i+1$ for all $1 \\leq i \\leq n-1$ and a road between house $n$ and house $1$. All roads are bidirectional. However, due to the crisis on Penacony, the overseeing family has gone into debt and may not be able to maintain all roads.\n\nThere are $m$ pairs of friendships between the residents of Penacony. If the resident living in house $a$ is friends with the resident living in house $b$, there must be a path between houses $a$ and $b$ through maintained roads.\n\nWhat is the minimum number of roads that must be maintained?",
    "tutorial": "There are two configurations to satisfy every friendship $(a, b)$: activate all the roads from $a \\rightarrow a+1 \\rightarrow \\dots \\rightarrow b$ or $b \\leftarrow \\dots \\leftarrow n \\leftarrow 1 \\leftarrow \\dots \\leftarrow a$. Let's fix a road we deactivate. Say it goes from $i \\rightarrow i+1$. Observe that the configuration for all friendships is fixed to one of the two cases. For example, if $a \\leq i < b$, then we must use the second configuration. We can try fixing every road and taking the minimum of number of roads. This can be done with sweep line. Once we reach $i = a$ for any friendship, we toggle to the second configuration. Once we reach $b$, we toggle back to the first. We can track maintained roads by performing a range addition on a lazy propagated segment tree for each point covered by the current configuration. The number of roads required is $n$ minus the number of occurrences of zeroes in the segment tree, which can be tracked with Counting Minimums in a Segment Tree. Consider the $n$-gon formed by the houses, with each road becoming an edge of the polygon. We draw diagonals between houses if they are friends. Let each diagonal arbitrarily \"cover\" one side of the polygon, where every road contained within one section split by the diagonal is covered by the diagonal. We claim that two roads can both be deleted if and only if they are covered by the same set of diagonals. First, this is equivalent to saying that when we draw a line between these two roads, they do not intersect any of our drawn diagonals. (This is since if any diagonal covers one road and not another, then they must be on opposite sides of the diagonal, so drawing a line between the two roads must intersect that diagonal. The converse also holds.) Now note that if two roads are on opposite sides of a diagonal, they cannot both be deleted, as then there is no path along maintained roads that connects the two endpoints of the diagonals, or the two houses that are friends. So it suffices to count the most frequent set of covered diagonals over all roads. We can represent a diagonal cover for some road using a xor hashing, where each diagonal is assigned a random number, and the roads that are covered by that diagonal are xor'd by this number. By using $64$-bit integers, the probability of collision is negligible, as each 64-bit integer has equal probability of representing a unique set of diagonals, and we have at most $n$ represented sets. For each pair of friends, we want to xor all values in a range by some random number. This can be done with a prefix xor array in $\\mathcal{O}(1)$ per pair of friends. Counting the most frequent value at the end will take $\\mathcal{O}(n \\log n)$ time if a map is used or $\\mathcal{O}(n)$ if an unordered map is used. In all, this solution runs in $\\mathcal{O}(n \\log n + m)$ or $\\mathcal{O}(n + m)$ time.",
    "code": "#include <bits/stdc++.h>\n#define int long long\nusing namespace std;\n\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nint n,m,a,b,k,t; \n\nvoid solve() {\n\tcin >> n >> m;\n\tvector<int> v(n); \n\twhile (m--) {\n\t\tk=rng(); cin >> a >> b;\n\t\tv[a-1]^=k;\n\t\tv[b-1]^=k;\n\t}\n\tmap<int,int> c;\n\tfor (int r:v) m=max(m,c[a^=r]++); \n\tcout << n-m-1 << \"\\n\"; \n}\n\nint32_t main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\tcin >> t;\n\twhile (t--) solve();\n}",
    "tags": [
      "brute force",
      "data structures",
      "graphs",
      "greedy",
      "hashing"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1997",
    "index": "A",
    "title": "Strong Password",
    "statement": "Monocarp's current password on Codeforces is a string $s$, consisting of lowercase Latin letters. Monocarp thinks that his current password is too weak, so he wants to \\textbf{insert exactly one lowercase Latin letter} into the password to make it stronger. Monocarp can choose any letter and insert it anywhere, even before the first character or after the last character.\n\nMonocarp thinks that the password's strength is proportional to the time it takes him to type the password. The time it takes to type the password is calculated as follows:\n\n- the time to type the first character is $2$ seconds;\n- for each character other than the first, the time it takes to type it is $1$ second if it is the same as the previous character, or $2$ seconds otherwise.\n\nFor example, the time it takes to type the password abacaba is $14$; the time it takes to type the password a is $2$; the time it takes to type the password aaabacc is $11$.\n\nYou have to help Monocarp — insert a lowercase Latin letter into his password so that the resulting password takes the maximum possible amount of time to type.",
    "tutorial": "The time it takes to type a string can actually be calculated as follows: $2 \\cdot |s| - p$, where $|s|$ is the number of characters in the string, and $p$ is the number of pairs of adjacent equal characters (usually a character takes $2$ seconds to type, but the right character in every pair of adjacent equal characters takes only $1$, so each pair reduces the total time by $1$). Since we always add a new character, $|s|$ will increase by $1$ no matter what; so we need to minimize $p$. Now there are two cases: if there is a pair of adjacent equal characters in the string, we can decrease $p$ by $1$ by \"breaking\" it as follows: choose any character different from the characters in that pair, and insert it between them. It's easy to see that we can \"break\" at most one such pair, so we can't do better; otherwise, $p$ is already $0$, so we just need to keep it equal to $0$. For example, we can choose any character not equal to the last character in the string, and append it to the right of it. There are other solutions as well, like iterating on all possible characters and all possible insertion positions.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve()\n{\n\tstring s;\n\tcin >> s;\n\tint n = s.size();\n\tint idx = -1;\n\tfor(int i = 0; i + 1 < n; i++)\n\t\tif(s[i] == s[i + 1])\n\t\t\tidx = i;\n\tif(idx == -1)\n\t{\n\t\tif(s.back() == 'a') cout << (s + \"b\") << endl;\n\t\telse cout << (s + \"a\") << endl;\n\t}\n\telse\n\t{\n\t\tstring t = \"a\";\n\t\tif(s[idx] == 'a') t = \"b\";\n\t\tcout << s.substr(0, idx + 1) + t + s.substr(idx + 1) << endl;\n\t}\n}\n \nint main()\n{\n\tint t;\n\tcin >> t;\n\tfor(int i = 0; i < t; i++)\n\t\tsolve();\n}",
    "tags": [
      "brute force",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "1997",
    "index": "B",
    "title": "Make Three Regions",
    "statement": "There is a grid, consisting of $2$ rows and $n$ columns. Each cell of the grid is either free or blocked.\n\nA free cell $y$ is reachable from a free cell $x$ if at least one of these conditions holds:\n\n- $x$ and $y$ share a side;\n- there exists a free cell $z$ such that $z$ is reachable from $x$ and $y$ is reachable from $z$.\n\nA connected region is a set of free cells of the grid such that all cells in it are reachable from one another, but adding any other free cell to the set violates this rule.\n\nFor example, consider the following layout, where white cells are free, and dark grey cells are blocked:\n\nThere are $3$ regions in it, denoted with red, green and blue color respectively:\n\nThe given grid contains at most $1$ connected region. Your task is to calculate the number of free cells meeting the following constraint:\n\n- if this cell is blocked, the number of connected regions becomes exactly $3$.",
    "tutorial": "Since the chosen cell should split a connected region into $3$ non-empty parts, this cell should share a side with all $3$ of them. But any cell has at most $3$ neighbor cells (because there are only $2$ rows), and they should be split from each other by blocked cells. From the above, we can conclude how a pattern of a \"good\" cell should look like. In fact, there are only $2$ of them (on the layouts below, white cells are free, dark grey cells are blocked, and the red cell is a \"good\" cell): These patterns are the only possible ones: all $3$ neighbors of a \"good\" cell should be free (otherwise there will be less than $3$ regions connected to it); and both of the \"corner\" cells should be blocked (if at least one of them is free, two regions will merge into one, so there will be less than $3$ regions). So the problem becomes to calculate the number of the above patterns inside the given grid.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<string> s(2);\n    for (auto& x : s) cin >> x;\n    int ans = 0;\n    for (int i = 1; i < n - 1; ++i) {\n      bool ok = true;\n      ok &= (s[0][i] == '.' && s[1][i] == '.');\n      ok &= (s[0][i - 1] != s[1][i - 1]);\n      ok &= (s[0][i + 1] != s[1][i + 1]);\n      ok &= (s[0][i - 1] == s[0][i + 1]);\n      ans += ok;\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "constructive algorithms",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1997",
    "index": "C",
    "title": "Even Positions",
    "statement": "Monocarp had a regular bracket sequence $s$ of length $n$ ($n$ is even). He even came up with his own way to calculate its cost.\n\nHe knows that in a regular bracket sequence (RBS), each opening bracket is paired up with the corresponding closing bracket. So he decided to calculate the cost of RBS as the sum of distances between pairs of corresponding bracket pairs.\n\nFor example, let's look at RBS (())(). It has three pairs of brackets:\n\n- (__)__: the distance between brackets at position $1$ and at $4$ is $4 - 1 = 3$;\n- _()___: the distance is $3 - 2 = 1$;\n- ____(): the distance is $6 - 5 = 1$.\n\nSo the cost of (())() is $3 + 1 + 1 = 5$.Unfortunately, due to data corruption, Monocarp lost all characters on odd positions $s_1, s_3, \\dots, s_{n-1}$. Only characters on even positions ($s_2, s_4, \\dots, s_{n}$) remain. For example, (())() turned to _(_)_).\n\nMonocarp wants to restore his RBS by placing brackets on the odd positions. But since the restored RBS may not be unique, he wants to choose one with \\textbf{minimum cost}. It's too hard to do for Monocarp alone, so can you help him?\n\nReminder: A regular bracket sequence is a string consisting of only brackets, such that this sequence, when inserted 1-s and +-s, gives a valid mathematical expression. For example, (), (()) or (()())() are RBS, while ), ()( or ())(() are not.",
    "tutorial": "Let's define a balance of a bracket sequence as the $\\texttt{number_of_opening_brackets} - \\texttt{number_of_closing_brackets}$. It's a well-known fact that for RBS the balance of all its prefixes must be greater than or equal to zero and the balance of the whole string must be exactly zero. So, if we want to restore RBS from $s$ we shouldn't break that rule. Next, let's define $S_{o}$ as the sum of positions of the opening brackets in RBS and $S_{c}$ as the sum of positions of the closing brackets in RBS. It turns out that the cost defined in the statement is just $S_c - S_o$. Moreover, you can see that $S_c - S_o = 2 S_c - \\frac{n (n + 1)}{2}$. It means that in order to minimize the cost, we should minimize $S_c$, or we should try to place closing brackets on the smaller positions. The most interesting part is that it's enough to come up with the right strategy. Let's iterate from left to right, maintaining the current balance and place the closing brackets whenever we can: if the current balance is $0$ we can't place a closing bracket, since it will make the balance negative, so we place an opening bracket; if the current balance is bigger than $0$ we place a closing bracket. Since we need to calculate the cost of the RBS, we can replace the balance counter with a stack containing positions of opening brackets that don't have a pair yet. Each time we meet an opening bracket, we'll push its position to the top of the stack, and each time we meet a closing bracket, we'll take one bracket from the top of the stack. The current balance is just the size of the stack. Here is a sketch of the proof, why the strategy above is correct. Firstly, the strategy creates RBS, because after processing a prefix of even length the current balance will be equal to either $0$ or $2$, while after an odd length prefix it will be always $1$. At the start, the balance is $0$ and we make it $1$, then it either becomes $0$ or $2$, and in both cases we return it to $1$ and so on. Since the last character is always a closing bracket, the total balance will return to $0$. Secondly, to prove that the strategy minimizes the cost, we can use a standard technique of proof by contradiction: suppose there is a better answer, look at the first position of the difference: it will be ) in our string and ( in the answer. Then just find the next ) in the answer and swap them. The answer will stay RBS, while $S_c$ will decrease - contradiction.",
    "code": "import java.util.LinkedList\n \nfun main() {\n    repeat(readln().toInt()) {\n        val n = readln().toInt()\n        val s = readln()\n \n        var ans = 0L\n        val bracketPositions = LinkedList<Int>()\n        for (i in s.indices) {\n            var c = s[i]\n            if (c == '_') {\n                c = if (bracketPositions.isEmpty()) '(' else ')'\n            }\n            if (c == ')') {\n                ans += i - bracketPositions.pollLast()\n            }\n            else\n                bracketPositions.addLast(i)\n        }\n        println(ans)\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1997",
    "index": "D",
    "title": "Maximize the Root",
    "statement": "You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.\n\nYou can perform the following operation any number of times (possibly zero): choose a vertex $v$ \\textbf{which has at least one child}; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.\n\nYour task is to calculate the maximum possible value written at the root using the aforementioned operation.",
    "tutorial": "We can clearly say that if some value $k$ can be obtained at the root, then any value from $a_1$ to $k$ can also be obtained. Using that fact, we can use binary search to solve the problem. Let's fix some value $\\mathit{mid}$ in binary search and check if it is possible to apply an operation from the statement $\\mathit{mid}$ times to the root. Let's write the following recursive function: $\\mathit{check}(v, x)$ - the function that checks whether it is possible to obtain at least $x$ at all vertices from the subtree of $v$ (including $v$ itself) simultaneously (i. e. we had to make $x$ operations above the current vertex, can the subtree of $v$ \"support\" them?). Let the current state be $(v, x)$, then there are three cases of transitions: $v$ is a leaf, then $x \\le a_v$ should hold; $v$ is not a leaf and $x \\le a_v$, then the vertex $v$ is ok, and we have to check its subtree (i. e. $\\mathit{check}(u, x)$ should be true for all $u$ that are children of $v$). $v$ is not a leaf and $x > a_v$, then we have to apply the operation $(x - a_v)$ times to the vertex $v$, and that adds an additional constraint on the subtree of $v$; specifically, $\\mathit{check}(u, x + (x - a_v))$ should be true for all $u$ that are children of $v$. Be careful with overflows: $x$ might grow exponentially, so you should, for example, return from the function when $x$ becomes very large. When we check a single value of $mid$, this recursive function is called once for each vertex in the tree, so the total time complexity of this solution is $O(n\\log{A})$, where $A$ is an upper bound of the values of the array $a$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int INF = 1e9;\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (auto& x : a) cin >> x;\n    vector<vector<int>> g(n);\n    for (int i = 1; i < n; ++i) {\n        int p;\n        cin >> p;\n        g[p - 1].push_back(i);\n    }\n    \n    auto check = [&](auto&& self, int v, int x) -> bool {\n      if (x > INF) return false;\n      bool isLeaf = true;\n      if (v) x += max(0, x - a[v]);\n      for (auto u : g[v]) {\n        isLeaf = false;\n        if (!self(self, u, x)) return false;\n      }\n      return (!isLeaf || x <= a[v]);\n    };\n    \n    int l = 1, r = INF;\n    while (l <= r) {\n      int mid = (l + r) / 2;\n      if (check(check, 0, mid)) {\n        l = mid + 1;\n      } else {\n        r = mid - 1;\n      }\n    }\n    \n    cout << a[0] + l - 1 << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1997",
    "index": "E",
    "title": "Level Up",
    "statement": "Monocarp is playing a computer game. He starts the game being level $1$. He is about to fight $n$ monsters, in order from $1$ to $n$. The level of the $i$-th monster is $a_i$.\n\nFor each monster in the given order, Monocarp's encounter goes as follows:\n\n- if Monocarp's level is strictly higher than the monster's level, the monster flees (runs away);\n- otherwise, Monocarp fights the monster.\n\nAfter every $k$-th fight with a monster (\\textbf{fleeing monsters do not count}), Monocarp's level increases by $1$. So, his level becomes $2$ after $k$ monsters he fights, $3$ after $2k$ monsters, $4$ after $3k$ monsters, and so on.\n\nYou need to process $q$ queries of the following form:\n\n- $i~x$: will Monocarp fight the $i$-th monster (or will this monster flee) if the parameter $k$ is equal to $x$?",
    "tutorial": "I would like to describe two different intended solutions to this problem. Solution One. Let's start with the following idea. How many times can the character's level increase for a fixed $k$? Given that there are $n$ monsters, even if we fight all of them, the level will not exceed $\\frac{n}{k}$. That is, if we sum over all $k$, the level will change no more than $O(n \\log n)$ times (harmonic series). Let's simulate the process for each $k$ and find out when the level changed. Suppose the character's level became $x$ after fighting monster $i$. Then the level will become $x + 1$ after fighting the $k$-th monster with a level greater than or equal to $x$ after position $i$. That is, if we had an array of positions of monsters with a level greater than or equal to $x$, we could find the position of the level change from it. Unfortunately, it is not possible to keep all such arrays in memory. Instead, let's try to use a more powerful data structure. Now, suppose we want to add or remove positions from the structure and be able to query the $k$-th position greater than $i$. Such structures exist. We can use a segment tree, a BIT, or an ordered_set from pbds. How can we reduce the problem to using this structure? The idea is as follows. Previously, we had the idea to iterate over $k$ and inside that iterate over the current character level. Let's do the opposite. We will iterate over the character level on the outside. And inside, we will update the level for all such $k$ for which the character has not reached the end of the monsters yet. It turns out that this will be a prefix of the $k$. Why is that? For each $x$, the character reaches level $x$ at some $k$ no later than at $k + 1$. Suppose this is not the case. Consider the first such $x$ where the character reached level $x$ at $k$ later than at $k + 1$. That is, he reached level $x - 1$ earlier or at the same time. This means that he will encounter at least all the same monsters at $k$ as at $k + 1$ (since the segment of monsters will start no later and end no earlier). Since at $k + 1$, the character must have encountered at least $k + 1$ monsters of level at least $x$, at $k$ he will definitely encounter at least $k$. Thus, this cannot happen. Then the implementation is as follows. For each $k$, we will maintain the position at which the character reached the current level $x$. Then, for the prefix of $k$, for which this position is within the array, we will update it with the new position for level $k + 1$. For this, we will store the positions of all monsters of level at least $x$ in the data structure. After processing level $x$, we will remove all monsters of this level from the structure. To find the new position, we need to make such queries to the structure: either find the $k$-th position after the current saved one (in the segment tree or Fenwick tree), or find the first (using order_of_key) and move $k - 1$ positions from it (using find_by_order) (in ordered_set). We can answer the queries within the simulation. For each $k$, we will store all queries related to it and sort them in ascending order of $i$. Since within each $k$ we move in the order of increasing level, and thus position, we can answer the queries in that order. While the position of the query is less than or equal to the position where the level will become $x + 1$, we answer the queries by checking that the monster's level at that position is not less than $x$. Overall complexity: $O(n \\log^2 n)$. Solution Two. Let's still simulate level increases directly. We will use the square root heuristics. If $k$ is greater than or equal to some constant $B$, then the character will definitely fight all monsters of level at least $\\frac{n}{B}$, simply because he cannot become greater than this level himself. That is, if we choose $B$ on the order of $1000$, for example, we only need to know whether the character is fighting a monster, only for monsters of level no higher than $200$. We will solve the problem for all $k$ less than $1000$ in $O(n)$. That is, we will honestly go through the monsters, maintaining the character's level and a counter of fights until the level increases. For larger $k$, we will solve the problem as follows. We will sum the indices of all characters of each level from $1$ to $200$ into separate arrays. We will consider whom the character fought at the end of the game for each level separately. It is obvious that for each level of monsters $x$, the character fought a prefix of these monsters. Since the character's level increases monotonically, at some point the character's level will exceed $x$, and all monsters of level $x$ will flee. Moreover, if the character fought a monster for some $k$, he will also fight it for $k + 1$ (by the proof from the previous solution). Thus, to find out which new monsters the character will fight at level $k$, we can do the following. We will iterate over monster levels up to $200$ and for the first fleeing monster of this level, we will check whether the character will fight it now. For this, we need to find out how many monsters the character fought before this monster. If his level is not less than this number divided by $k$ (rounded down), then he will fight it. Among all the first monsters the character will fight, we will find the minimum. For it, our solution is definitely correct. For the others, this is not necessarily true, because the character's level may increase due to fights to the left of this position. If no such monsters are found, then for this $k$ we have found all. Otherwise, in some data structure, we will mark that the character is fighting with the leftmost found monster. Thus, we need a data structure that can answer prefix sum queries and update an element at a certain position. There are quite a few such structures. However, we have a large number of queries: for each fight, we need to make $200$ queries, that is, a total of $n \\cdot 200$ queries. However, there are not so many updates: each position will be updated in the structure no more than once, that is, no more than $n$ updates. Therefore, we would like to have a structure that balances these operations. For example, let the query be $O(1)$, and the update be $O(\\sqrt{n})$. We will divide the array into blocks of size $O(\\sqrt{n})$. For each block, we will store the sum of elements up to its left boundary. And for each position within each block, we will store the sum up to the left boundary of the block. Then, to query the prefix sum up to $i$, we need to add the sum up to the left position of the block $\\frac{i}{\\sqrt{n}}$ and the sum from $i$ to the start of this block. To update at position $i$, we need to add one to the first sum for each block from $\\frac{i}{\\sqrt{n}} + 1$ to the end. And also for each position from $i$ to the end of its block. Queries can be answered as follows. For each monster, we will keep track of the first $k$ at which we will fight it. Then it is sufficient to check that the $k$ from the query is not less than this value. Overall complexity: $O(n \\sqrt{n})$.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nstruct query{\n\tint i, j;\n};\n \nint main() {\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tint n, m;\n\tcin >> n >> m;\n\tvector<int> a(n);\n\tforn(i, n) cin >> a[i];\n\tvector<vector<query>> q(n + 1);\n\tforn(j, m){\n\t\tint i, x;\n\t\tcin >> i >> x;\n\t\t--i;\n\t\tq[x].push_back({i, j});\n\t}\n\tforn(i, n + 1) sort(q[i].begin(), q[i].end(), [](const query &a, const query &b){\n\t\treturn a.i > b.i;\n\t});\n\t\n\tint P = min(1000, n + 1);\n\t\n\tvector<char> ans(m);\n\tfor (int k = 1; k < P; ++k){\n\t\tint cur = 1;\n\t\tint cnt = 0;\n\t\tforn(i, n){\n\t\t\tbool fl = false;\n\t\t\tif (a[i] >= cur){\n\t\t\t\t++cnt;\n\t\t\t\tfl = true;\n\t\t\t\tif (cnt == k){\n\t\t\t\t\t++cur;\n\t\t\t\t\tcnt = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\twhile (!q[k].empty() && q[k].back().i == i){\n\t\t\t\tans[q[k].back().j] = fl;\n\t\t\t\tq[k].pop_back();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvector<int> sum1(n), sum2(n);\n\tint p2 = ceil(sqrt(n + 2));\n\t\n\tauto add = [&](int i){\n\t\tint bl = i / p2;\n\t\tfor (int j = bl + 1; j * p2 < n; ++j)\n\t\t\t++sum1[j];\n\t\tfor (int j = i; j < (bl + 1) * p2 && j < n; ++j)\n\t\t\t++sum2[j];\n\t};\n\t\n\tint mx = n / P + 5;\n\tvector<vector<int>> pos(mx);\n\tforn(i, n){\n\t\tif (a[i] < mx)\n\t\t\tpos[a[i]].push_back(i);\n\t\telse\n\t\t\tadd(i);\n\t}\n\tfor (auto &it : pos) reverse(it.begin(), it.end());\n\t\n\tfor (int k = P; k <= n; ++k){\n\t\twhile (true){\n\t\t\tint mn = n;\n\t\t\tint who = -1;\n\t\t\tforn(lvl, mx) if (!pos[lvl].empty()){\n\t\t\t\tint i = pos[lvl].back();\n\t\t\t\tif (mn < i) continue;\n\t\t\t\tint cnt = sum1[i / p2] + sum2[i];\n\t\t\t\tif (a[i] >= cnt / k + 1){\n\t\t\t\t\tmn = i;\n\t\t\t\t\twho = lvl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (who == -1) break;\n\t\t\tadd(mn);\n\t\t\tpos[who].pop_back();\n\t\t}\n\t\tfor (auto it : q[k]){\n\t\t\tint lvl = a[it.i];\n\t\t\tans[it.j] = (lvl >= mx || pos[lvl].empty() || pos[lvl].back() > it.i);\n\t\t}\n\t}\n\t\n\tfor (auto x : ans) cout << (x ? \"YES\" : \"NO\") << '\\n';\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "divide and conquer",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1997",
    "index": "F",
    "title": "Chips on a Line",
    "statement": "You have $n$ chips, and you are going to place all of them in one of $x$ points, numbered from $1$ to $x$. There can be multiple chips in each point.\n\nAfter placing the chips, you can perform the following four operations (in any order, any number of times):\n\n- choose a chip in point $i \\ge 3$, remove it and place two chips: one in $i-1$, one in $i-2$;\n- choose two chips in adjacent points $i$ and $i+1$, remove them and place a new chip in $i+2$;\n- choose a chip in point $1$ and move it to $2$;\n- choose a chip in point $2$ and move it to $1$.\n\nNote that the coordinates of the chips you place during the operations cannot be less than $1$, but can be greater than $x$.\n\nDenote the cost of chip placement as the \\textbf{minimum} number of chips which can be present on the line after you perform these operations, starting from the placement you've chosen.\n\nFor example, the cost of placing two chips in points $3$ and one chip in point $5$ is $2$, because you can reduce the number of chips to $2$ as follows:\n\n- choose a chip in point $3$, remove it, place a chip in $1$ and another chip in $2$;\n- choose the chips in points $2$ and $3$, remove them and place a chip in $4$;\n- choose the chips in points $4$ and $5$, remove them and place a chip in $6$.\n\nYou are given three integers $n$, $x$ and $m$. Calculate the number of placements of exactly $n$ chips in points from $1$ to $x$ having cost equal to $m$, and print it modulo $998244353$. Two placements are considered different if the number of chips in some point differs between these placements.",
    "tutorial": "The operations described in the statement are kinda similar to the identities for Fibonacci numbers, so maybe the solution will be connected to them. Let's assign each chip placement a weight: if chips are placed in points $x_1, x_2, \\dots, x_n$ (repeating if multiple chips are in the same position), the weight of this placement is $f_{x_1} + f_{x_2} + \\dots + f_{x_k}$, where $f_i$ is the $i$-th Fibonacci number ($f_1 = f_2 = 1$; $f_{i+2} = f_i + f_{i+1}$). We can show that two placements can be transformed into each other if and only if their weights are identical. First of all, the operations described in the statement don't change the weight, so two placements with different weights cannot be transformed into each other. To show how to transform two placements with identical weight into each other, let's bring them into \"canonical\" form as follows: while there is a chip with coordinate $i > 2$, convert it into two chips with coordinates $i-1$ and $i-2$; if all remaining chips are in points $1$ and $2$, move all chips from $2$ to $1$. After performing this sequence of actions, we will transform a placement of chips into the form \"all chips are in point $1$, and the number of these chips is equal to the weight of the placement\". And since all operations we apply are invertible (for every operation, there is an operation which \"rolls it back\"), we can transform any placement to any other placement with the same weight through this \"canonical form\". So, instead of counting the placements, let's group them according to their weights and work with them. For every possible weight of a placement (which is an integer from $1$ to $f_x \\cdot n$), we need to answer two questions: Is it true that the minimum cost of a placement of this weight is exactly $m$? How many placements with this weight are there? The former is simple: this is just checking that the minimum number of Fibonacci numbers used to represent an integer is equal to $m$. We can precalculate this minimum number of Fibonacci numbers to represent each integer with a simple dynamic programming. The latter is a bit more tricky: we need to count the number of ways to represent the given number as a sum of exactly $n$ Fibonacci numbers from $f_1$ to $f_x$, where the order of these Fibonacci numbers does not matter. There are different ways to calculate it, the model solution uses a dynamic programming which uses $O(f_x \\cdot n^2 \\cdot x)$ time and $O(f_x \\cdot n^2)$ memory. Let $dp_{i,j}$ be the number of ways to partition the integer $i$ into $j$ Fibonacci numbers. Initially, we will consider the situation when we can't use any Fibonacci numbers, so $dp_{0,0} = 1$ and everything else is $0$. And then we will \"add\" Fibonacci numbers one by one, so first we will update our dynamic programming in such a way that we can only use $f_1$; then, only $f_1$ and/or $f_2$; and so on. Let's show how to \"update\" our dynamic programming when we can use a new number $k$ in partitions. The simple way to do this is as follows: for every $dp_{i,j}$, iterate on the number $c$ of new elements we will use, and get a partition of integer $i + c \\cdot k$ into $j+c$ numbers. However, that is too slow. Instead, let's iterate on the states of our dynamic programming in ascending order of $i$, and in each state, add at most one element to the partition (so, increase $dp_{i+k,j+1}$ by $dp_{i,j}$). At the first glance, it only allows us to use one element equal to $k$; however, when we consider the state $dp_{i+k,j+1}$ we updated, it will already store both the partitions which didn't use elements equal to $k$, and the partitions which used at least one element equal to $k$ (which came from the state $dp_{i,j}$); and by transitioning from $dp_{i+k,j+1}$ to $dp_{i+2k,j+2}$, we will \"expand\" all these partitions. If the previous paragraph is a bit unclear to you, you can try viewing it as a three-state dynamic programming of the form \"let $dp_{i,j,k}$ be the number of partitions of $i$ into $j$ Fibonacci numbers from $f_1$ to $f_k$\", where we dropped the third state of our dynamic programming in favor of maintaining only one layer and being more memory efficient.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\n \nint add(int x, int y)\n{\n \tx += y;\n \twhile(x >= MOD) x -= MOD;\n \twhile(x < 0) x += MOD;\n \treturn x;\n}\n \nint mul(int x, int y)\n{\n \treturn (x * 1ll * y) % MOD;\n}\n \nint main()\n{\n \tint n, x, m;\n \tcin >> n >> x >> m;\n \tvector<int> fib = {0, 1};\n \tfor(int i = 2; i <= 30; i++)\n \t\tfib.push_back(fib[i - 1] + fib[i - 2]);\n \n \n \tint max_sum = fib[x] * n;\n \tvector<vector<int>> dp(max_sum + 1, vector<int>(n + 1));\n \tdp[0][0] = 1;\n \tfor(int i = 1; i <= x; i++)\n \t\tfor(int j = 0; j < max_sum; j++)\n \t\t\tfor(int k = 0; k < n; k++)\n \t\t\t{\n \t\t\t \tif(j + fib[i] <= max_sum)\n \t\t\t \t\tdp[j + fib[i]][k + 1] = add(dp[j + fib[i]][k + 1], dp[j][k]);\n \t\t\t}\n\t\n\tvector<int> cost(max_sum + 1, 1e9);\n\tcost[0] = 0;\n\tfor(int j = 1; j <= max_sum; j++)\n\t\tfor(int i = 1; i <= 30; i++)\n\t\t\tif(j >= fib[i])\n\t\t\t\tcost[j] = min(cost[j], cost[j - fib[i]] + 1);\n \n\tint ans = 0;\n\tfor(int i = 0; i <= max_sum; i++)\n\t\tif(cost[i] == m)\n\t\t\tans = add(ans, dp[i][n]);\n\tcout << ans << endl;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "1998",
    "index": "A",
    "title": "Find K Distinct Points with Fixed Center",
    "statement": "\\begin{quote}\nI couldn't think of a good title for this problem, so I decided to learn from LeetCode.\n\\hfill — Sun Tzu, The Art of War\n\\end{quote}\n\nYou are given three integers $x_c$, $y_c$, and $k$ ($-100 \\leq x_c, y_c \\leq 100$, $1 \\leq k \\leq 1000$).\n\nYou need to find $k$ \\textbf{distinct} points ($x_1, y_1$), ($x_2, y_2$), $\\ldots$, ($x_k, y_k$), having integer coordinates, on the 2D coordinate plane such that:\n\n- their center$^{\\text{∗}}$ is ($x_c, y_c$)\n- $-10^9 \\leq x_i, y_i \\leq 10^9$ for all $i$ from $1$ to $k$\n\nIt can be proven that at least one set of $k$ distinct points always exists that satisfies these conditions.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The center of $k$ points ($x_1, y_1$), ($x_2, y_2$), $\\ldots$, ($x_k, y_k$) is $\\left( \\frac{x_1 + x_2 + \\ldots + x_k}{k}, \\frac{y_1 + y_2 + \\ldots + y_k}{k} \\right)$.\n\\end{footnotesize}",
    "tutorial": "We can construct a solution by fixing all $x_i$ as $x_c$ or all $y_i$ as $y_c$. For example, if we fix all $y_i$ as $y_c$, then we can output pairs $(x_c-1, y_c), (x_c+1, y_c), (x_c-2, y_c), (x_c+2, y_c), ... , (x_c- \\lfloor \\frac{k}{2} \\rfloor, y_c), (x_c + \\lfloor \\frac{k}{2} \\rfloor, y_c)$. If the $k$ is odd, we need one more pair, so just output $(x_c, y_c)$.",
    "code": "#include <iostream>\nusing namespace std;\n\nint main() {\n\tint t; cin >> t;\n\twhile(t--){\n\t\tint x, y, k; cin >> x >> y >> k;\n\t\tfor(int i = 0; i < k - k % 2; i++){\n\t\t\tcout << x - (i & 1 ? 1 : -1) * (i / 2 + 1) << \" \" << y << \"\\n\";\n\t\t} \n\t\tif(k & 1){\n\t\t\tcout << x << \" \" << y << \"\\n\";\n\t\t}\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1998",
    "index": "B",
    "title": "Minimize Equal Sum Subarrays",
    "statement": "\\begin{quote}\nIt is known that Farmer John likes Permutations, but I like them too!\n\\hfill — Sun Tzu, The Art of Constructing Permutations\n\\end{quote}\n\nYou are given a permutation$^{\\text{∗}}$ $p$ of length $n$.\n\nFind a permutation $q$ of length $n$ that minimizes the number of pairs ($i, j$) ($1 \\leq i \\leq j \\leq n$) such that $p_i + p_{i+1} + \\ldots + p_j = q_i + q_{i+1} + \\ldots + q_j$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "We can always construct a solution such that the number of pairs $(i, j)$ is $1$ where the only pair is $(1, n)$. There exists several constructions, such as rotating $p$ once or increment all $p_i$ (and $p_i = n$ turns into $p_i = 1$). Consider the former construction, where $q = [p_2, p_3, ..., p_n, p_1]$. For an arbitrarily interval $[i, j]$, $p[i..j]$ and $q[i..j]$ will have exactly $1$ element that's different, disregarding ordering. Since we have a permutation and all elements are distinct, the sum in the range will never be the same. The only exception is the entire array, of course.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tint n; cin >> n;\n\t\tvector<int> p(n);\n\t\tfor(int& i: p) cin >> i;\n\t\trotate(p.begin(), p.begin() + 1, p.end());\n\t\tfor(int i: p) cout << i << \" \";\n\t\tcout << \"\\n\";\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1998",
    "index": "C",
    "title": "Perform Operations to Maximize Score",
    "statement": "\\begin{quote}\nI see satyam343. I'm shaking. Please more median problems this time. I love those. Please satyam343 we believe in you.\n\\hfill — satyam343's biggest fan\n\\end{quote}\n\nYou are given an array $a$ of length $n$ and an integer $k$. You are also given a binary array $b$ of length $n$.\n\nYou can perform the following operation at most $k$ times:\n\n- Select an index $i$ ($1 \\leq i \\leq n$) such that $b_i = 1$. Set $a_i = a_i + 1$ (i.e., increase $a_i$ by $1$).\n\nYour score is defined to be $\\max\\limits_{i = 1}^{n} \\left( a_i + \\operatorname{median}(c_i) \\right)$, where $c_i$ denotes the array of length $n-1$ that you get by deleting $a_i$ from $a$. In other words, your score is the maximum value of $a_i + \\operatorname{median}(c_i)$ over all $i$ from $1$ to $n$.\n\nFind the maximum score that you can achieve if you perform the operations optimally.\n\nFor an arbitrary array $p$, $\\operatorname{median}(p)$ is defined as the $\\left\\lfloor \\frac{|p|+1}{2} \\right\\rfloor$-th \\textbf{smallest} element of $p$. For example, $\\operatorname{median} \\left( [3,2,1,3] \\right) = 2$ and $\\operatorname{median} \\left( [6,2,4,5,1] \\right) = 4$.",
    "tutorial": "satyam343, Dominater069 First, solve for $k = 0$. Find some nice characterization about $med(c_i)$ and thus the maximum score. Divide into $2$ cases where we either increment the max element or the median. Apply binary search Let's forget about the operations of adding $1$ to $a_i$ and figure out how to find an array's score. Assume the array $a$ is sorted in increasing order as the order doesnt change the problem. First observe how $med(c_i)$ changes with respect to $i$. $med(c_i)$ is always either $a_{\\lfloor \\frac{n}{2} \\rfloor}$ or $a_{\\lfloor \\frac{n + 2}{2} \\rfloor}$. You can prove this formally by considering different positions of $i$ with respect to the initial median position. Specifically, for all $i \\le \\lfloor \\frac{n}{2} \\rfloor$, $med(c_i) = a_{\\lfloor \\frac{n + 2}{2} \\rfloor}$, and for other $i$, $med(c_i) = a_{\\lfloor \\frac{n}{2} \\rfloor}$. Claim 1 : The score of the final array (after sorting in increasing order) is $a_n + med(c_n)$ There are $2$ cases we need to consider. 1) $med(c_i) = a_{\\lfloor \\frac{n}{2} \\rfloor}$, in which case optimum value of $i$ is $n$ as we want to maximise $a_i$. Thus score in this case is $a_n + a_{\\lfloor \\frac{n}{2} \\rfloor}$. 2) $med(c_i)= a_{\\lfloor \\frac{n + 2}{2} \\rfloor}$, in which case optimum value of $i$ is $\\lfloor \\frac{n}{2} \\rfloor$ as this is the largest value of $i$ which will change median. This obtains a score of $a_{\\lfloor \\frac{n}{2} \\rfloor} + a_{\\lfloor \\frac{n + 2}{2} \\rfloor}$ The score in Case $1$ is clearly larger than Case $2$, hence it is optimal. Hence, our score can be nicely characterized by \"max + median of the others\". Claim 2 : Either we will use all $k$ operations on the element which eventually becomes max element in our array, or we will use all operations trying to improve $med(c_n)$ and keep max element constant. Suppose we did $x$ ($0 < x < k$) operations on the element which eventually became maximum. Then, we could have done the remaining $(k - x)$ operations on this element too, as this is already the max element and doing operations on it guaranteedly improves our score each time by $1$. Doing operations on any other element can only improve our score by atmost $1$ Thus, we are in $2$ cases now, either increase max, or increase median of the rest. We will solve the problem considering both cases separately. Case $1$ : We do operations on the element which becomes max eventually. Lets fix $i$ to be the index that will become max. Then $b_i = 1$ must hold. We want to find $med(c_i)$, i.e. the median of the other $(n - 1)$ elements. This can be done with the observation mentioned above that $med(c_i)$ is always either $a_{\\lfloor \\frac{n}{2} \\rfloor}$ or $a_{\\lfloor \\frac{n + 2}{2} \\rfloor}$. Another possible way to solve this case is observe that we should only do operations on the largest index $i$ such that $b_i = 1$. While intuitive, the proof is left as an exercise to the reader. Case 2 : We do operations to increase the median of the others. $a_n$ is fixed as the max element in this case, and we want to find the largest possible median by using the $k$ operations on the other $(n - 1)$ elements. Let's binary search! Suppose we want to check if we can get $med(c_n) \\ge x$ or not. Some elements are already $\\ge x$, and we will not modify them. Some of the other elements can be incremented to become $\\ge x$ too. Obviously, we should choose the largest indices $i$ such that $a_i < x$ and $b_i = 1$, and greedily increment as many as possible. Let $z$ be the maximum number of elements which become $\\ge x$ at the end. The check is true iff $z \\ge \\lfloor \\frac{n + 1}{2} \\rfloor$. Thus, the problem is solved in $O(N \\cdot log (MAX))$. The code is nicely written and commented, you may want to check it out.",
    "code": "#include <bits/stdc++.h> \nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    \n    while (t--){\n        int n, k; cin >> n >> k;\n        \n        vector <pair<int, int>> a(n);\n        for (auto &x : a) cin >> x.first;\n        for (auto &x : a) cin >> x.second;\n        sort(a.begin(), a.end());\n        \n        long long ans = 0;\n        // case 1 : increment max \n        for (int i = 0; i < n; i++) if (a[i].second == 1){\n            // find med(c_i) \n            int mc;\n            if (i < n / 2) mc = a[n / 2].first;\n            else mc = a[(n - 2) / 2].first;\n            \n            ans = max(ans, 0LL + a[i].first + k + mc);\n        }\n        \n        // case 2 : increment median\n        int lo = 0, hi = 2e9;\n        while (lo != hi){\n            int mid = (1LL + lo + hi) / 2;\n            \n            int z = 0;\n            vector <int> smaller_list;\n            for (int i = 0; i < n - 1; i++){\n                if (a[i].first >= mid){\n                    z++;\n                } else if (a[i].second == 1){\n                    smaller_list.push_back(mid - a[i].first); // list of numbers smaller than x but b[i] = 1 \n                }\n            }\n            \n            reverse(smaller_list.begin(), smaller_list.end()); // list will be sorted in ascending, but we want sorted in descending, as greedily changing largest elements \n            int kk = k;\n            for (auto x : smaller_list) if (kk >= x){\n                kk -= x;\n                z++;\n            }\n            \n            if (z >= (n + 1) / 2) lo = mid;\n            else hi = mid - 1;\n        }\n        \n        ans = max(ans, 0LL + a[n - 1].first + lo);\n        \n        cout << ans << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "1998",
    "index": "D",
    "title": "Determine Winning Islands in Race",
    "statement": "\\begin{quote}\nMOOOOOOOOOOOOOOOOO\n\\hfill — Bessie the Cow, The Art of Racing on Islands\n\\end{quote}\n\nTwo of Farmer John's cows, Bessie and Elsie, are planning to race on $n$ islands. There are $n - 1$ main bridges, connecting island $i$ to island $i + 1$ for all $1 \\leq i \\leq n - 1$. Additionally, there are $m$ alternative bridges. Elsie can use \\textbf{both} main and alternative bridges, while Bessie can only use main bridges. All bridges are \\textbf{one way} and can only be used to travel from an island with a lower index to an island with a higher index.\n\nInitially, Elsie starts on island $1$, and Bessie starts on island $s$. The cows alternate turns, with Bessie making the first turn. Suppose the cow is on island $i$. During a cow's turn, if there are any bridges connecting island $i$ to island $j$, then the cow can move to island $j$. Then, island $i$ collapses, and all bridges connecting to island $i$ also collapse. Also, note the following:\n\n- If there are no bridges connecting island $i$ to another island, then island $i$ collapses, and this cow is eliminated from the race.\n- If the other cow is also on island $i$, then after this cow moves to another island, the island collapses, and the other cow is eliminated from the race.\n- After an island or bridge collapses, no cows may use them.\n- If a cow is eliminated, their turn is skipped for the rest of the race.\n\nThe race ends once either cow reaches island $n$. It can be shown that regardless of the cows' strategies, at least one cow reaches island $n$. Bessie wins if and only if she reaches island $n$ first.\n\nFor each $1 \\leq s \\leq n - 1$, determine whether Bessie wins if she starts the race on island $s$. Assume both cows follow optimal strategies to ensure their own respective victories.",
    "tutorial": "First, let's consider if there was no alternative bridges. Then obviously, if Bessie starts at island $i$ and keeps moving forwards, it is impossible for Elsie to move past island $i$ since the bridge would have already collapsed. From this, we can deduce that Bessie cannot let Elsie use these alternative bridges to overtake the island Bessie is on, or else Elsie will always reach the end first. Therefore, Bessie will keep moving right in hopes of breaking enough bridges so that it is impossible to for Elsie to overtake Bessie. This can be simplified to: consider we are at island $i$ and $t$ units of time has passed, for all alternative bridges that Elsie can take with an endpoint $v > i + t$, we have to reach $v$ before her. Let $d_i$ denote the minimum amount of time Elsie takes to reach island $i$. For the first case, consider all bridges with endpoints $v > S$, then $d_v \\geq v - S - 1$ must hold true since we want to reach $v$ before Elsie does when we keep going right. We can rearrange the equation as $S \\geq v - d_v - 1$. To make sure this holds true for all bridges, we just have to make sure this is true for the maximum value of $v - d_v$. All $d_i$ can be calculated using a linear sweep to the right, and we can track all $v - d_v$ with a sweep to the left. Note that we cannot take a bridge if it starts past $S$, so we need to track the maximum with a multiset and erasing as we sweep. Time Complexity is $\\mathcal{O}(n \\log n)$. There exists other solutions using prefix sums in $\\mathcal{O}(n)$ and segment tree in $\\mathcal{O}(n \\log n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define pb push_back\n#define FOR(i,a,b) for(int i = (a); i < (b); ++i)\n#define ROF(i,a,b) for(int i = (a); i >= (b); --i)\n#define trav(a,x) for(auto& a: x)\n\nvoid solve() {\n\tint n, m; cin >> n >> m;\n\tvector<vector<int>> g(n), rg(n);\n\tFOR(i,0,m){\n\t\tint u, v; cin >> u >> v;\n\t\t--u; --v;\n\t\tg[u].pb(v);\n\t\trg[v].pb(u);\n\t}\n\tFOR(i,0,n-1) g[i].pb(i+1);\n\tvector<int> dist(n, -1);\n\tqueue<int> q;\n\tdist[0] = 0;\n\tq.push(0);\n\twhile(!q.empty()){\n\t\tint f = q.front();\n\t\tq.pop();\n\t\ttrav(i, g[f]){\n\t\t\tif(dist[i] == -1){\n\t\t\t\tdist[i] = dist[f] + 1;\n\t\t\t\tq.push(i);\n\t\t\t}\n\t\t}\n\t}\n\tmultiset<int> max_good_rights;\n\tvector<vector<int>> to_erase(n);\n\tstring ans = string(n - 1, '0');\n\tROF(i,n-1,0){\n\t\ttrav(j, rg[i]){\n\t\t\tint max_right = i - dist[j];\n\t\t\tmax_good_rights.insert(max_right);\n\t\t\tto_erase[j].pb(max_right);\n\t\t}\n\t\ttrav(j, to_erase[i]){\n\t\t\tmax_good_rights.erase(max_good_rights.find(j));\n\t\t}\n\t\tif(i < n - 1){\n\t\t\tint max_good_right = max_good_rights.empty() ? -1 : *prev(max_good_rights.end());\n\t\t\tif(i >= max_good_right - 1){\n\t\t\t\tans[i] = '1';\n\t\t\t}\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n\nsigned main() {\n\tcin.tie(0) -> sync_with_stdio(0);\n\tint t = 1;\n\tcin >> t;\n\tfor(int test = 1; test <= t; test++){\n\t\tsolve();\n\t}\n}",
    "tags": [
      "data structures",
      "dp",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "1998",
    "index": "E1",
    "title": "Eliminating Balls With Merging (Easy Version)",
    "statement": "\\begin{quote}\nDrink water.\n\\hfill — Sun Tzu, The Art of Becoming a Healthy Programmer\n\\end{quote}\n\n\\textbf{This is the easy version of the problem. The only difference is that $x=n$ in this version. You must solve both versions to be able to hack.}\n\nYou are given two integers $n$ and $x$ ($x=n$). There are $n$ balls lined up in a row, numbered from $1$ to $n$ from left to right. Initially, there is a value $a_i$ written on the $i$-th ball.\n\nFor each integer $i$ from $1$ to $n$, we define a function $f(i)$ as follows:\n\n- Suppose you have a set $S = \\{1, 2, \\ldots, i\\}$.\n- In each operation, you have to select an integer $l$ ($1 \\leq l < i$) from $S$ such that $l$ is not the largest element of $S$. Suppose $r$ is the smallest element in $S$ which is greater than $l$.\n\n- If $a_l > a_r$, you set $a_l = a_l + a_r$ and remove $r$ from $S$.\n- If $a_l < a_r$, you set $a_r = a_l + a_r$ and remove $l$ from $S$.\n- If $a_l = a_r$, you choose either the integer $l$ or $r$ to remove from $S$:\n\n- If you choose to remove $l$ from $S$, you set $a_r = a_l + a_r$ and remove $l$ from $S$.\n- If you choose to remove $r$ from $S$, you set $a_l = a_l + a_r$ and remove $r$ from $S$.\n\n- $f(i)$ denotes the number of integers $j$ ($1 \\le j \\le i$) such that it is possible to obtain $S = \\{j\\}$ after performing the above operations exactly $i - 1$ times.\n\nFor each integer $i$ from $x$ to $n$, you need to find $f(i)$.",
    "tutorial": "Consider the ball with the maximum number. Let this ball be $m$. That ball can clearly be the last ball remaining. And if we are able to merge some ball $i$ with ball $m$ (whilst removing $m$), then ball $i$ can also be the last ball remaining. We can do a divide and conquer solution. For some range $[l,r]$, let $m$ be the ball with the maximum value. Clearly, $m$ can be the last ball remaining if we only consider the range $[l, r]$. Let's first recurse on $[l,m)$ and $(m,r]$. Let $s_l=a_l+a_{l+1}+\\cdots+a_{m-1}$ (i.e. the sum of the left half). If $s_l < a_m$ then no ball in the left half can be the last one remaining. Otherwise, the results (i.e. whether each ball can be the last one standing) for range $[l,r]$ for balls in $[l,m)$ is the results we computer when recursing onto $[l,m)$. The same reasoning holds for the right half. We can use a sparse table to find the maximum ball in any range. This leads to a $\\mathcal{O}(n\\log n)$ solution. For some ball $i$, let $l_i$ and $r_i$ be the first balls on the left and right that have a value greater than $a_i$. Proccess the balls from largest $a_i$ to smallest $a_i$. For each ball $i$, let $\\text{ans}_i$ denote whether it can be the last ball remaining. We know that if we merge ball $i$ with some ball $j$ (while discarding $j$) and $\\text{ans}_j=1$, then $\\text{ans}_i=1$. Furthermore, we know that balls $l_i$ and $r_i$ can freely merge with balls $j$ where $j$ is in interval $[l_i+1 \\ldots r_i-1]$ while discarding $j$ (i.e. $\\text{ans}_{l_i}$ and $\\text{ans}_{r_i}$ would have taken this into account). This motivates the following idea. Let $s$ be the sum of values in $[l_i+1 \\ldots r_i-1]$. If $s \\geq a_{l_i}$ then we do $\\text{ans}_i := \\text{ans}_i |\\text{ans}_{l_i}$. Similarly, if $s \\geq a_{r_i}$, then we do $\\text{ans}_i := \\text{ans}_i |\\text{ans}_{r_i}$. This solution runs in $\\mathcal{O}(n \\log n)$ due to sorting.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n\n#define ll long long\n\nvoid solve(){\n    int n, x;\n    cin >> n >> x;\n\n    vector<int> A(n + 5);\n    vector<ll> P(n + 5);\n    vector<int> ans(n + 5, 0);\n    vector<int> ord(n);\n    set<int> S{0, n + 1};\n\n    for (int i = 1; i <= n; i++){\n        cin >> A[i];\n        P[i] = P[i - 1] + A[i];\n        ord.push_back(i);\n    }\n    sort(ord.begin(), ord.end(), [&](int a, int b){\n        return A[a] > A[b];\n    });\n    for (int i : ord){\n        int l = *(--S.lower_bound(i));\n        int r = *S.lower_bound(i);\n        ll sum = P[r - 1] - P[l];\n\n        if (i == ord[0])\n            ans[i] = true;\n        if (sum >= A[l])\n            ans[i] |= ans[l];\n        if (sum >= A[r])\n            ans[i] |= ans[r];\n        \n        S.insert(i);\n    }\n    cout << accumulate(ans.begin(), ans.end(), 0) << \"\\n\";\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "divide and conquer",
      "greedy"
    ],
    "rating": 2200
  },
  {
    "contest_id": "1998",
    "index": "E2",
    "title": "Eliminating Balls With Merging (Hard Version)",
    "statement": "\\begin{quote}\nDrink water.\n\\hfill — Sun Tzu, The Art of Becoming a Healthy Programmer\n\\end{quote}\n\n\\textbf{This is the hard version of the problem. The only difference is that $x=1$ in this version. You must solve both versions to be able to hack.}\n\nYou are given two integers $n$ and $x$ ($x=1$). There are $n$ balls lined up in a row, numbered from $1$ to $n$ from left to right. Initially, there is a value $a_i$ written on the $i$-th ball.\n\nFor each integer $i$ from $1$ to $n$, we define a function $f(i)$ as follows:\n\n- Suppose you have a set $S = \\{1, 2, \\ldots, i\\}$.\n- In each operation, you have to select an integer $l$ ($1 \\leq l < i$) from $S$ such that $l$ is not the largest element of $S$. Suppose $r$ is the smallest element in $S$ which is greater than $l$.\n\n- If $a_l > a_r$, you set $a_l = a_l + a_r$ and remove $r$ from $S$.\n- If $a_l < a_r$, you set $a_r = a_l + a_r$ and remove $l$ from $S$.\n- If $a_l = a_r$, you choose either the integer $l$ or $r$ to remove from $S$:\n\n- If you choose to remove $l$ from $S$, you set $a_r = a_l + a_r$ and remove $l$ from $S$.\n- If you choose to remove $r$ from $S$, you set $a_l = a_l + a_r$ and remove $r$ from $S$.\n\n- $f(i)$ denotes the number of integers $j$ ($1 \\le j \\le i$) such that it is possible to obtain $S = \\{j\\}$ after performing the above operations exactly $i - 1$ times.\n\nFor each integer $i$ from $x$ to $n$, you need to find $f(i)$.",
    "tutorial": "Consider the naive greedy solution. We continuously merge with the balls on the left and right without removing our ball until we can't anymore or our ball is the final remaining one. Suppose at some point in this greedy approach, we can not merge with the balls on our left and right anymore without discarding our ball. Let our ball be $i$. Then we have the following cases. There is a ball $l$ on the left of $i$ and ball $r$ on the right of $i$. Then: $\\min(a_l,a_r) > a_{l+1}+a_{l+2}+\\cdots+a_{r-1}$. There is a ball $l$ on the left of $i$ but no ball on the right of $i$. Then: $a_l > a_{l+1}+a_{l+2}+\\cdots+a_{\\text{last}}$. There exists no ball on the left of $i$ but a ball $r$ on the right of $i$. Then: $a_r > a_1+a_2+\\cdots+a_{r-1}$. For some ball $i$, if there exists some $l$ and/or some $r$ such that one of the above is true, then there exists no way for our ball to be the last one remaining. Otherwise, the ball can be the last one remaining. Let $p$ be the prefix sum array of $a$ (i.e. $p_i=a_1+a_2+\\cdots+a_i$). For some ball $i$, we want to do the following. Find the smallest $r_1$ such that there exists some $l$ such that ($l, r_1$) is a pair (i.e. $\\min(a_l,a_{r_1}) > a_{l+1}+a_{l+2}+\\cdots+a_{r_1-1}$). Finding this is more difficult than the other cases and will be focused on later. Find the smallest $r_2$ such that $a_{r_2} > a_1+a_2+\\cdots+a_{{r_r}-1}$. We can rewrite it as as $a_{r_2} > p_{r_2-1}$ and it can easily be found. Find the smallest $r_l$ such that there exists no $l$ on the left of $i$ such that $a_l > a_{l+1}+a_{l+2}+\\cdots+a_{r_l}$. We can rewrite the inequality as finding the first $r_l$ such that $p_{r_l} \\geq a_l + p_l$ which can be done with binary search. Suppose at some $i$, we know its $r_l$, $r_1$, and $r_{2}$. Then we know ball $i$ can be the last one remaining for prefixes spanning from $r_l$ to $\\min(r_1-1, r_{2}-1)$ so we can do a range add with prefix sums. The only thing we have not resolved yet is how to find the smallest $r_1$ for some $i$ such that $\\min(a_l,a_{r_1}) > a_{l+1}+a_{l+2}+\\cdots+a_{r_1-1}$. Let's iterate over $r$. For each $r$ we want to find the leftmost $l$ such that $\\min(a_l,a_{r}) > a_{l+1}+a_{l+2}+\\cdots+a_{r-1}$ A key observation is that we can write the following inequality as $a_l > a_{l+1}+a_{l+2}+\\cdots+a_{r-1}$ and $a_r > a_{l+1}+a_{l+2}+\\cdots+a_{r-1}$ (both have to be true). Using prefix sums, the equations can be rewritten as $a_l + p_l > p_{r-1}$ and $p_l > p_{r-1} - a_r$. So some $(l,r)$ works if the equation above is satisfied. Consider the second part $p_l > p_{r-1} - a_r$. We can binary search to find the range of available $l$ that satisfy this. Specifically, let $l_b$ be the lower bound of the range. Then, any $l$ in $[l_b...i)$ satisfies this. Now, let's try to satisfy $a_l + p_l > p_{r-1}$. Unfortunately, $a_l + p_l$ is not monotonic so the method above will not work. Instead, we can create a sparse table over all $a_i + p_i$. Then we can binary search to find the first $l_{opt}$ such that the maximum in range $[l_b,l_{opt}]$ (which can be found with the sparse table) is greater than $p_{r-1}$. Circling back, $r_1$ is the minimum $r$ of an interval covering $i$ which can be found with things such as sweepline. In all, this solution runs in $\\mathcal{O}(n \\log n)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define ll long long\n\nvoid solve(){\n    int n, x;\n    cin >> n >> x;\n\n    vector<ll> A(n + 5, 0);\n    vector<ll> P(n + 5, 0);\n    vector<vector<ll>> rmq(n + 5, vector<ll>(18, 0));\n\n    for (int i = 1; i <= n; i++){\n        cin >> A[i];\n        P[i] = P[i - 1] + A[i];        \n        rmq[i][0] = A[i] + P[i];\n    }\n    for (int j = 1; j <= 17; j++)\n        for (int i = 1; i + (1 << j) - 1 <= n; i++)\n            rmq[i][j] = max(rmq[i][j - 1], rmq[i + (1 << (j - 1))][j - 1]);\n\n    vector<vector<int>> add(n + 5), rem(n + 5);\n\n    auto ins = [&](int l, int r, int v){\n        l = max(l, 1);\n\n        if (l > r)\n            return;\n\n        add[l].push_back(v);\n        rem[r + 1].push_back(v);\n    };\n    for (int r = 1; r <= n; r++){\n        // r is a roadblock\n        if (A[r] > P[r - 1])\n            ins(1, r - 1, r);\n\n        // Find leftmost l possible\n        int lowerB = upper_bound(P.begin() + 1, P.begin() + n + 1, P[r - 1] - A[r]) - P.begin();\n        int lo = lowerB, hi = r - 1;\n\n        while (lo < hi){\n            int mid = (lo + hi) / 2;\n\n            // Query lowerB...mid\n            int lg = 31 - __builtin_clz(mid - lowerB + 1);\n            ll val = max(rmq[lowerB][lg], rmq[mid - (1 << lg) + 1][lg]);\n\n            val > P[r - 1] ? hi = mid : lo = mid + 1;\n        }\n        ins(lo + 1, r - 1, r);\n    }\n\n    multiset<int> badR{n + 1};\n    vector<int> ans(n + 5, 0);\n    ll worst = 0; \n\n    for (int i = 1; i <= n; i++){\n        for (int v : add[i])\n            badR.insert(v);\n        for (int v : rem[i])\n            badR.erase(badR.find(v));\n\n        int l = lower_bound(P.begin() + i, P.begin() + n + 1, worst) - P.begin();\n        int r = *badR.begin();\n\n        // Active for interval [l...r)\n        if (l <= r){\n            ans[l]++;\n            ans[r]--;\n        }\n        worst = max(worst, A[i] + P[i]);\n    }\n    \n    for (int i = x; i <= n; i++){\n        ans[i] += ans[i - 1];\n        cout << ans[i] << \" \\n\"[i == n];\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int tc;\n    cin >> tc;\n\n    while (tc--)\n        solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "divide and conquer",
      "greedy",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "1999",
    "index": "A",
    "title": "A+B Again?",
    "statement": "Given a two-digit positive integer $n$, find the sum of its digits.",
    "tutorial": "You can take the input as a string and output the sum of the two characters in the string. There is also a formula: $\\lfloor \\frac{n}{10} \\rfloor + n \\bmod 10$. The first term is the tens digit, the second term - the ones digit.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tcout << (n / 10) + (n % 10) << '\\n';\t\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "1999",
    "index": "B",
    "title": "Card Game",
    "statement": "Suneet and Slavic play a card game. The rules of the game are as follows:\n\n- Each card has an integer value between $1$ and $10$.\n- Each player receives $2$ cards which are face-down (so a player doesn't know their cards).\n- The game is turn-based and consists \\textbf{exactly of two turns}. In a round, both players pick a \\textbf{random unflipped} card and flip it. The player who flipped a card with a strictly greater number wins the round. In case of equality, no one wins the round.\n- A player wins a game if he wins the most number of rounds (i.e. strictly greater than the other player). In case of equality, no one wins the game.\n\nSince Suneet and Slavic aren't best friends, you need to calculate the number of ways the game could happen that Suneet would end up as the winner.\n\nFor a better understanding, please check the notes section.",
    "tutorial": "For each test case, we can brute force through all possible games (there are only four of them) and calculate who is the winner of the game by simulating the game.",
    "code": "def f(a, b):\n    if (a > b): return 1\n    if (a == b): return 0\n    if (a < b): return -1\nfor _ in range(int(input())):\n    a, b, c, d = map(int, input().split())\n    ans = 0\n    if f(a, c) + f(b, d) > 0:\n        ans += 1\n    if f(a, d) + f(b, c) > 0:\n        ans += 1\n    if f(b, c) + f(a, d) > 0:\n        ans += 1\n    if f(b, d) + f(a, c) > 0:\n        ans += 1\n    print(ans)",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "1999",
    "index": "C",
    "title": "Showering",
    "statement": "As a computer science student, Alex faces a hard challenge — showering. He tries to shower daily, but despite his best efforts there are always challenges. He takes $s$ minutes to shower and a day only has $m$ minutes!\n\nHe already has $n$ tasks planned for the day. Task $i$ is represented as an interval $(l_i$, $r_i)$, which means that Alex is busy and can not take a shower in that time interval (at any point in time strictly between $l_i$ and $r_i$). \\textbf{No two tasks overlap.}\n\nGiven all $n$ time intervals, will Alex be able to shower that day? In other words, will Alex have a free time interval of length at least $s$?\n\n\\begin{center}\n{\\small In the first test case, Alex can shower for the first $3$ minutes of the day and not miss any of the tasks.}\n\\end{center}",
    "tutorial": "We just need to find the lengths of the gaps between intervals. Note that from the additional constraint on the input, the intervals are in sorted order. So you need to find if for any $i > 1$, $l_i - r_{i - 1} \\geq s$, and also if $l_1 \\geq s$ (the initial interval), or if $m - r_{n} \\geq s$ (the final interval).",
    "code": "def solve():\n    n, s, m = map(int, input().split())\n    segs = [[0, 0], [m, m]] + [list(map(int, input().split())) for i in range(n)]\n    segs.sort()\n    for i in range(1, n + 2):\n        if segs[i][0] - segs[i - 1][1] >= s:\n            print('YES')\n            return\n    print('NO')\n\n\n#sys.stdin = open('in', 'r')\nfor _ in range(int(input())):\n    solve()",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "1999",
    "index": "D",
    "title": "Slavic's Exam",
    "statement": "Slavic has a very tough exam and needs your help in order to pass it. Here is the question he is struggling with:\n\nThere exists a string $s$, which consists of lowercase English letters and possibly zero or more \"?\".\n\nSlavic is asked to change each \"?\" to a lowercase English letter such that string $t$ becomes a subsequence (not necessarily continuous) of the string $s$.\n\nOutput any such string, or say that it is impossible in case no string that respects the conditions exists.",
    "tutorial": "Let's use a greedy strategy with two pointers, one at the start of $s$ (called $i$) and one at the start of $t$ (called $j$). At each step, advance $i$ by $1$. If $s_i = \\texttt{?}$, then we set it to $t_j$ and increment $j$. If $s_i = t_j$ then we also increment $j$ (because there is a match). It works because if there is ever a question mark, it never makes it worse to match the current character in $t$ earlier than later. The complexity is $\\mathcal{O}(n)$.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int test_cases; cin >> test_cases;\n    while(test_cases--) {\n        string s, t; cin >> s >> t;\n    \tint idx = 0;\n    \n    \tfor(int i = 0; i < (int)s.size(); ++i) {\n    \t\tif(s[i] == '?') {\n    \t\t\tif(idx < (int)t.size()) s[i] = t[idx++];\n    \t\t\telse s[i] = 'a';\n    \t\t} else if(s[i] == t[idx]) ++idx;\n    \t}\n    \tif(idx >= t.size()) cout << \"YES\\n\" << s << \"\\n\";\n    \telse cout << \"NO\\n\";\n    }\n}",
    "tags": [
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "1999",
    "index": "E",
    "title": "Triple Operations",
    "statement": "On the board Ivy wrote down all integers from $l$ to $r$, inclusive.\n\nIn an operation, she does the following:\n\n- pick two numbers $x$ and $y$ on the board, erase them, and in their place write the numbers $3x$ and $\\lfloor \\frac{y}{3} \\rfloor$. (Here $\\lfloor \\bullet \\rfloor$ denotes rounding down to the nearest integer).\n\nWhat is the minimum number of operations Ivy needs to make all numbers on the board equal $0$? We have a proof that this is always possible.",
    "tutorial": "Consider writing the numbers in ternary (it is like binary but instead we use three digits, and for clarity we will use \"digit\" in the solution instead of \"bit\" or \"trit\"). In the operation, we will add a $0$ to the end of the number $x$ and remove the last digit of $y$. For example, if $x=8$ and $y=11$, then in ternary the numbers are $22_{3}$ and $102_{3}$. After the operation, $x=24$ and $y=3$, and indeed in ternary they are $220_{3}$ and $10_{3}$. (This is because multiplying by $3$ is multiplying by $10_{3}$, and similarly dividing by $3$ is like dividing by $10_{3}$.) This means that the total number of digits across all numbers does not change (since we add one digit and remove one digit). So how is it possible to make all numbers $0$? Well, there is one exception to the above rule: when we use the operation with $x=0$, we add a $0$ to the end of the number $0$, but this added digit doesn't count (because $3 \\cdot 0 = 0$). This means that if we ever do the operation with $x=0$, then we will lose one digit total (since $x$ doesn't gain a digit, but $y$ loses a digit). This means the solution is as follows: first, we make one of the numbers equal to $0$. Then, we will use this $0$ to remove all the digits of all other numbers. To use the fewest number of operations possible, we should do the first step on the minimum number, since it has the fewest digits. Let $f(x)$ denote the number of ternary digits in the number $x$ (actually, $f(x) = \\lfloor \\log_3 (x) \\rfloor + 1$). Then the first step takes $f(l)$ operations (since $l$ is the smallest number in the range $[l, r]$), and the second step takes $f(l) + \\cdots + f(r)$ operations (since we need to remove all the digits, which is the total number of digits from $l$ to $r$). This means the answer for each test case is $f(l) + f(l) + \\cdots + f(r)$. To find this sum quickly, we can compute prefix sums on $f$ so that the answer is simply $f(l) + \\mathrm{psum}(r) - \\mathrm{psum}(l-1)$, which takes $\\mathcal{O}(1)$ time per test case with $\\mathcal{O}(n)$ precomputation.",
    "code": "\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n\nint a[MAX], psum[MAX];\n\nint f(int x) {\n\tint cnt = 0;\n\twhile (x) {\n\t\tx /= 3;\n\t\tcnt++;\n\t}\n\treturn cnt;\n}\n\nvoid solve() {\n\tint l, r;\n\tcin >> l >> r;\n\tcout << psum[r] - psum[l - 1] + a[l] << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\t\n\tpsum[0] = 0;\n\tfor (int i = 1; i < MAX - 1; i++) {\n\t\ta[i] = f(i);\n\t\tpsum[i] = psum[i - 1] + a[i];\n\t}\n\t\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "1999",
    "index": "F",
    "title": "Expected Median",
    "statement": "Arul has a \\textbf{binary} array$^{\\text{∗}}$ $a$ of length $n$.\n\nHe will take all subsequences$^{\\text{†}}$ of length $k$ ($k$ is odd) of this array and find their median.$^{\\text{‡}}$\n\nWhat is the sum of all these values?\n\nAs this sum can be very large, output it modulo $10^9 + 7$. In other words, print the remainder of this sum when divided by $10^9 + 7$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary array is an array consisting only of zeros and ones.\n\n$^{\\text{†}}$An array $b$ is a subsequence of an array $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements. Subsequences \\textbf{don't} have to be contiguous.\n\n$^{\\text{‡}}$The median of an array of odd length $k$ is the $\\frac{k+1}{2}$-th element when sorted.\n\\end{footnotesize}",
    "tutorial": "Say the array has $x$ ones and $y$ zeroes. If the median of a subsequence of length $k$ is $1$, then there are at least $\\lfloor \\frac{k}{2} \\rfloor + 1$ ones in the array. Let's iterate over the number of ones in the subsequence from $\\lfloor \\frac{k}{2} \\rfloor + 1$ to $x$. Suppose there are $i$ ones. Then there are $k - i$ zeroes. The number of ways to choose $i$ ones from $x$ is $\\binom{x}{i}$, that is, $x$ choose $i$ (this is the so-called binomial coefficient). Similarly, the number of ways to choose $k-i$ zeroes from $y$ of them is $\\binom{y}{k-i}$. Therefore the answer is the sum of $\\binom{x}{i}\\binom{y}{k-i}$ over all $i$ from $\\lfloor \\frac{k}{2} \\rfloor + 1$ to $x$. You can compute binomial coefficients in many ways, for example precomputing all factorials and then using the formula $\\binom{n}{k} = \\frac{n!}{(n-k)!k!}$. Depending on your implementation, it can take $\\mathcal{O}(n \\log \\mathrm{MOD})$ or $\\mathcal{O}(n + \\log \\mathrm{MOD})$ time. If you don't know how to do that, we recommend you read the article.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\nconst int N = 2e5 + 5, mod = 1e9 + 7;\nint64_t fact[N];\nint64_t pw(int64_t a, int64_t b) {\n\tint64_t r = 1;\n\twhile(b > 0) {\n\t\tif(b & 1) r = (r * a) % mod;\n\t\tb /= 2;\n\t\ta = (a * a) % mod; \n\t}\n\treturn r;\n}\nint64_t C(int64_t n, int64_t k) {\n\tif(n < k) return 0LL;\n\treturn (fact[n] * pw((fact[n - k] * fact[k]) % mod, mod - 2)) % mod;\n}\nint main() {\n\tint t; cin >> t;\n\tfact[0] = 1;\n\tfor(int64_t i = 1; i < N; ++i) fact[i] = (fact[i - 1] * i) % mod;\n\twhile(t--) {\n\t\tint n, k; cin >> n >> k;\n\t\tvector<int> a(n);\n\t\tint ones = 0;\n\t\tfor(int i = 0; i < n; ++i) {\n\t\t\tcin >> a[i];\n\t\t\tones += a[i];\n\t\t}\n\t\t//at least k/2+1 ones\n\t\tint64_t ans = 0;\n\t\tfor(int cnt_ones = k / 2 + 1; cnt_ones <= min(ones, k); ++cnt_ones) {\n\t\t\tans += C(ones, cnt_ones) * C(n - ones, k - cnt_ones) % mod;\n\t\t\tans %= mod;\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1999",
    "index": "G1",
    "title": "Ruler (easy version)",
    "statement": "This is the easy version of the problem. The only difference between the two versions is that in this version, you can make at most $\\mathbf{10}$ queries.\n\nThis is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants.\n\nWe have a secret ruler that is missing one number $x$ ($2 \\leq x \\leq 999$). When you measure an object of length $y$, the ruler reports the following values:\n\n- If $y < x$, the ruler (correctly) measures the object as having length $y$.\n- If $y \\geq x$, the ruler incorrectly measures the object as having length $y+1$.\n\n\\begin{center}\n{\\small The ruler above is missing the number $4$, so it correctly measures the first segment as length $3$ but incorrectly measures the second segment as length $6$ even though it is actually $5$.}\n\\end{center}\n\nYou need to find the value of $x$. To do that, you can make queries of the following form:\n\n- $?~a~b$ — in response, we will measure the side lengths of an $a \\times b$ rectangle with our ruler and multiply the results, reporting the measured area of the rectangle back to you. For example, if $x=4$ and you query a $3 \\times 5$ rectangle, we will measure its side lengths as $3 \\times 6$ and report $18$ back to you.\n\nFind the value of $x$. You can ask at most $\\mathbf{10}$ queries.",
    "tutorial": "Consider queries of the form $\\texttt{?}~~\\texttt{1}~~y$. Since $x > 1$, the height of the rectangle is always measured correctly. That means: If $y < x$, the response is $y$. If $y \\geq x$, the response is $y+1$.",
    "code": "\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tint l = 2, r = 1000;\n\twhile (l < r) {\n\t\tint mid = l + (r - l) / 2;\n\t\tcout << \"? 1 \" << mid << endl;\n\t\tint resp; cin >> resp;\n\t\t\n\t\tif (resp == mid) {\n\t\t\tl = mid + 1;\n\t\t} \n\t\telse {\n\t\t\tr = mid;\n\t\t}\n\t}\n\tcout << \"! \" << l << endl;\t\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "binary search",
      "interactive"
    ],
    "rating": 1500
  },
  {
    "contest_id": "1999",
    "index": "G2",
    "title": "Ruler (hard version)",
    "statement": "This is the hard version of the problem. The only difference between the two versions is that in this version, you can make at most $\\mathbf{7}$ queries.\n\nThis is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants.\n\nWe have a secret ruler that is missing one number $x$ ($2 \\leq x \\leq 999$). When you measure an object of length $y$, the ruler reports the following values:\n\n- If $y < x$, the ruler (correctly) measures the object as having length $y$.\n- If $y \\geq x$, the ruler incorrectly measures the object as having length $y+1$.\n\n\\begin{center}\n{\\small The ruler above is missing the number $4$, so it correctly measures the first segment as length $3$ but incorrectly measures the second segment as length $6$ even though it is actually $5$.}\n\\end{center}\n\nYou need to find the value of $x$. To do that, you can make queries of the following form:\n\n- $?~a~b$ — in response, we will measure the side lengths of an $a \\times b$ rectangle with our ruler and multiply the results, reporting the measured area of the rectangle back to you. For example, if $x=4$ and you query a $3 \\times 5$ rectangle, we will measure its side lengths as $3 \\times 6$ and report $18$ back to you.\n\nFind the value of $x$. You can ask at most $\\mathbf{7}$ queries.",
    "tutorial": "Consider one query of the form $\\texttt{?}~~a~~b$ for $a < b$. That means: If $a < b < x$, the response is $a \\cdot b$ (both $a$ and $b$ are measured correctly). If $a < x \\leq b$, the response is $a \\cdot (b + 1)$ ($a$ is measured correctly, but $b$ is not). If $x \\leq a < b$, the repsone is $(a + 1) \\cdot (b + 1)$ (both $a$ and $b$ are measured incorrectly). If we repeat this, each time dividing the search space into three equal pieces, then the number of queries needed is $\\lceil \\log_3(1000) \\rceil = 7$. This is similar to the so-called ternary search to find the maximum of a unimodal function (although it is slightly different). You should be careful about the small case when there are only two possible values of $x$ left.",
    "code": "\n#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MAX = 200'007;\nconst int MOD = 1'000'000'007;\n \nvoid solve() {\n\tint l = 1, r = 999;\n\twhile (r - l > 2) {\n\t\tint a = (2 * l + r) / 3;\n\t\tint b = (2 * r + l) / 3;\n\t\tcout << \"? \" << a << ' ' << b << endl;\n\t\tint resp; cin >> resp;\n\t\t\n\t\tif (resp == (a + 1) * (b + 1)) {\n\t\t\tr = a;\n\t\t}\n\t\telse if (resp == a * b) {\n\t\t\tl = b;\n\t\t}\n\t\telse {\n\t\t\tl = a; r = b;\n\t\t}\n\t}\n\tif (r - l == 2) {\n\t\tcout << \"? 1 \" << l + 1 << endl;\n\t\tint resp; cin >> resp;\n\t\t\n\t\tif (resp == l + 1) {l = l + 1;}\n\t\telse {r = l + 1;}\n\t\t\n\t}\n\tcout << \"! \" << r << endl;\n}\n \nint main() {\n\tios::sync_with_stdio(false);\n\tcin.tie(nullptr);\n\tint tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();}\n\t// solve();\n}",
    "tags": [
      "binary search",
      "interactive",
      "ternary search"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2000",
    "index": "A",
    "title": "Primary Task",
    "statement": "Dmitry wrote down $t$ integers on the board, and that is good. He is sure that he lost an important integer $n$ among them, and that is bad.\n\nThe integer $n$ had the form $\\text{10^x}$ ($x \\ge 2$), where the symbol '$\\text{^}$' denotes exponentiation.. Something went wrong, and Dmitry missed the symbol '$\\text{^}$' when writing the important integer. For example, instead of the integer $10^5$, he would have written $105$, and instead of $10^{19}$, he would have written $1019$.\n\nDmitry wants to understand which of the integers on the board could have been the important integer and which could not.",
    "tutorial": "You need to check that the number has the form '$\\text{10x}$', where $x$ is an integer without leading zeros. This means it must start with '10'; if the length of the number is $3$, then the third digit must be at least $2$; if the length is greater, then the third digit must be at least $1$ (all such numbers $x$ are at least $10$). Additionally, under these constraints, you can simply check that for the given number $a$, either $102 \\le a \\le 109$ or $1010 \\le a \\le 1099$ holds true.",
    "code": "for _ in range(int(input())):\n    a = int(input())\n    if 102 <= a <= 109 or 1010 <= a <= 1099:\n        print(\"YES\")\n    else:\n        print(\"NO\")",
    "tags": [
      "implementation",
      "math",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2000",
    "index": "B",
    "title": "Seating in a Bus",
    "statement": "In Berland, a bus consists of a row of $n$ seats numbered from $1$ to $n$. Passengers are advised to always board the bus following these rules:\n\n- If there are no occupied seats in the bus, a passenger can sit in any free seat;\n- Otherwise, a passenger should sit in any free seat that has at least one occupied neighboring seat. In other words, a passenger can sit in a seat with index $i$ ($1 \\le i \\le n$) only if at least one of the seats with indices $i-1$ or $i+1$ is occupied.\n\nToday, $n$ passengers boarded the bus. The array $a$ chronologically records the seat numbers they occupied. That is, $a_1$ contains the seat number where the first passenger sat, $a_2$ — the seat number where the second passenger sat, and so on.\n\nYou know the contents of the array $a$. Determine whether all passengers followed the recommendations.\n\nFor example, if $n = 5$, and $a$ = [$5, 4, 2, 1, 3$], then the recommendations were not followed, as the $3$-rd passenger sat in seat number $2$, while the neighboring seats with numbers $1$ and $3$ were free.",
    "tutorial": "To solve the problem, it is enough to use an array $used$ of size $2 \\cdot 10^5 + 1$ (maximal value $n + 1$) consisting of boolean variables. When a passenger gets on the bus to seat $a_i$, we will replace the value of $used[a_i]$ with true. Then, for all passengers, starting from the second one, we should check that at least one of the existing elements $used[a_i - 1]$ or $used[a_i + 1]$ has the value true. If this condition is not satisfied, the answer to the problem is \"NO\". If at least $1$ occupied neighbouring seat always existed for all passengers at the moment they took their seat - the answer is \"YES\".",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int>a(n);\n    for(auto &i : a) cin >> i;\n    int left = a[0], right = a[0];\n    for(int i = 1; i < n; i++){\n        if(a[i] + 1 == left) left = a[i];\n        else if(a[i] - 1 == right) right = a[i];\n        else {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    cout << \"YES\\n\";\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "2000",
    "index": "C",
    "title": "Numeric String Template",
    "statement": "Kristina has an array $a$, called a template, consisting of $n$ integers. She also has $m$ strings, each consisting only of lowercase Latin letters. The strings are numbered from $1$ to $m$. She wants to check which strings match the template.\n\nA string $s$ is considered to match the template if all of the following conditions are simultaneously satisfied:\n\n- The length of the string $s$ is equal to the number of elements in the array $a$.\n- The same numbers from $a$ correspond to the same symbols from $s$. So, if $a_i = a_j$, then $s_i = s_j$ for ($1 \\le i, j \\le n$).\n- The same symbols from $s$ correspond to the same numbers from $a$. So, if $s_i = s_j$, then $a_i = a_j$ for ($1 \\le i, j \\le n$).\n\nIn other words, there must be a one-to-one correspondence between the characters of the string and the elements of the array.For example, if $a$ = [$3, 5, 2, 1, 3$], then the string \"abfda\" matches the template, while the string \"afbfa\" does not, since the character \"f\" corresponds to both numbers $1$ and $5$.",
    "tutorial": "To solve the problem, we can use two dictionaries (map): match the characters of the string to the numbers of the array in the map $m_1$ and the numbers of the array to the characters of the string in the map $m_2$. First, we check the length of the string to see if it is equal to the number $n$. If the string is longer or shorter, the answer is \"NO\". Otherwise, we will loop through the characters of the string and check the following conditions: The map $m_1$ does not contain the character $s_i$ as a key, and the map $m_2$ does not contain the number $a_i$ as a key. Then let's perform the assignments $m_1[s_i] = a_i$ and $m_2[a_i] = s_i$. One of the maps contains the current array element or string character as a key, but its value does not match the character or number in the current position. Then the answer to the problem is - \"NO\", you can break the loop. If the loop reaches the end of the line, the answer to the problem is \"YES\".",
    "code": "def solve():\n    n = int(input())\n    a = list(map(int, input().split()))\n    m = int(input())\n    for _ in range(m):\n        m_1 = {}\n        m_2 = {}\n        s = input().strip()\n        if len(s) != n:\n            print(\"NO\")\n            continue\n \n        ok = True\n        for j in range(n):\n            if s[j] not in m_1 and a[j] not in m_2:\n                m_1[s[j]] = a[j]\n                m_2[a[j]] = s[j]\n            elif (s[j] in m_1 and m_1[s[j]] != a[j]) or (a[j] in m_2 and m_2[a[j]] != s[j]):\n                ok = False\n                break\n        print(\"YES\" if ok else \"NO\")\n \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "data structures",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2000",
    "index": "D",
    "title": "Right Left Wrong",
    "statement": "Vlad found a strip of $n$ cells, numbered from left to right from $1$ to $n$. In the $i$-th cell, there is a positive integer $a_i$ and a letter $s_i$, where all $s_i$ are either 'L' or 'R'.\n\nVlad invites you to try to score the maximum possible points by performing any (possibly zero) number of operations.\n\nIn one operation, you can choose two indices $l$ and $r$ ($1 \\le l < r \\le n$) such that $s_l$ = 'L' and $s_r$ = 'R' and do the following:\n\n- add $a_l + a_{l + 1} + \\dots + a_{r - 1} + a_r$ points to the current score;\n- replace $s_i$ with '.' for all $l \\le i \\le r$, meaning you can no longer choose these indices.\n\nFor example, consider the following strip:\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||c||c||c|}\n\\hline\n$3$ & $5$ & $1$ & $4$ & $3$ & $2$ \\\n\\hline\n\\hline\nL & R & L & L & L & R \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nYou can first choose $l = 1$, $r = 2$ and add $3 + 5 = 8$ to your score.\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||c||c||c|}\n\\hline\n$3$ & $5$ & $1$ & $4$ & $3$ & $2$ \\\n\\hline\n\\hline\n. & . & L & L & L & R \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nThen choose $l = 3$, $r = 6$ and add $1 + 4 + 3 + 2 = 10$ to your score.\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||c||c||c|}\n\\hline\n$3$ & $5$ & $1$ & $4$ & $3$ & $2$ \\\n\\hline\n\\hline\n. & . & . & . & . & . \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nAs a result, it is impossible to perform another operation, and the final score is $18$.\n\nWhat is the maximum score that can be achieved?",
    "tutorial": "Note that since all characters of the selected segment of the string $s$ are erased after applying the operation, the segments we choose cannot overlap. However, they can be nested if we first choose an inner segment and then an outer one. Since all numbers in the array are positive, it is always beneficial to take the largest possible segment in the answer, that is, from the first 'L' to the last 'R'. By choosing this segment, we can only select segments within it. We will continue to choose such segments within the last selected one as long as possible. To quickly find the sums of the segments, we will calculate the prefix sums of the array $a$.",
    "code": "def solve():\n    n = int(input())\n    a = [0]\n    for x in input().split():\n        x = int(x)\n        a.append(a[-1] + x)\n    s = input()\n    ans = 0\n    l = 0\n    r = n - 1\n    while r > l:\n        while l < n and s[l] == 'R':\n            l += 1\n        while r >= 0 and s[r] == 'L':\n            r -= 1\n        if l < r:\n            ans += a[r + 1] - a[l]\n            l += 1\n            r -= 1\n    print(ans)\n \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2000",
    "index": "E",
    "title": "Photoshoot for Gorillas",
    "statement": "You really love gorillas, so you decided to organize a photoshoot for them. Gorillas live in the jungle. The jungle is represented as a grid of $n$ rows and $m$ columns. $w$ gorillas agreed to participate in the photoshoot, and the gorilla with index $i$ ($1 \\le i \\le w$) has a height of $a_i$. You want to place \\textbf{all} the gorillas in the cells of the grid such that there is \\textbf{no more than one gorilla} in each cell.\n\nThe spectacle of the arrangement is equal to the sum of the spectacles of all sub-squares of the grid with a side length of $k$.\n\nThe spectacle of a sub-square is equal to the sum of the heights of the gorillas in it.\n\nFrom all suitable arrangements, choose the arrangement with the \\textbf{maximum} spectacle.",
    "tutorial": "We will learn how to find the number of sub-squares that cover the cell $(i, j)$: $(\\min(i, n - k) - \\max(-1, i - k)) \\cdot (\\min(j, m - k) - \\max(-1, j - k))$. Next, we will use a straightforward greedy algorithm: we will place the tallest gorillas in the cells covered by the maximum number of squares. This can be done using two std::sort operations and a linear pass. The time complexity of the solution is: $O(n \\cdot m \\log (n \\cdot m) + w \\log w)$.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\n \nusing namespace std;\n \n#define MAXW 200200\n#define MAXNM 200200\n \nint n, m, k, w, p;\nint arr[MAXW], prr[MAXNM];\n \nstatic inline int calcc(int i, int j) {\n    int upr = min(i, n - k);\n    int leftr = min(j, m - k);\n    int upl = max(-1LL, i - k);\n    int leftl = max(-1LL, j - k);\n    return (upr - upl) * (leftr - leftl);\n}\n \nvoid build() {\n    sort(arr, arr + w);\n    reverse(arr, arr + w);\n    p = 0;\n    for (int i = 0; i < n; ++i)\n        for (int j = 0; j < m; ++j)\n            prr[p++] = calcc(i, j);\n    sort(prr, prr + p);\n    reverse(prr, prr + p);\n}\n \nint solve() {\n    int sum = 0;\n    for (int i = 0; i < w; ++i)\n        sum += prr[i] * arr[i];\n    return sum;\n}\n \nsigned main() {\n    int t; cin >> t;\n    while (t--) {\n        cin >> n >> m >> k >> w;\n        for (int i = 0; i < w; ++i)\n            cin >> arr[i];\n        build();\n        cout << solve() << endl;\n    }\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2000",
    "index": "F",
    "title": "Color Rows and Columns",
    "statement": "You have $n$ rectangles, the $i$-th of which has a width of $a_i$ and a height of $b_i$.\n\nYou can perform the following operation an unlimited number of times: choose a rectangle and a cell in it, and then color it.\n\nEach time you completely color any row or column, you earn $1$ point. Your task is to score at least $k$ points with as few operations as possible.\n\nSuppose you have a rectangle with a width of $6$ and a height of $3$. You can score $4$ points by coloring all the cells in any $4$ columns, thus performing $12$ operations.",
    "tutorial": "We will use the idea from the knapsack problem: let $dp[i][j]$ be the minimum number of operations required to achieve $j$ points using the first $i$ rectangles. To calculate the next value, we will iterate over the number of points scored in the $i$-th rectangle. To count the number of operations, we note that it is always better to paint the outer row of the smaller side of the unpainted part of the rectangle (which may change after painting the row).",
    "code": "#include <iostream>\n#include <algorithm>\n#include <vector>\n \nusing namespace std;\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n), b(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i] >> b[i];\n    }\n    vector<vector<int>> dp(n + 1, vector<int>(k + 1, 1e9));\n    dp[0][0] = 0;\n    for (int i = 0; i < n; ++i) {\n        int x = a[i], y = b[i];\n        int xy = x + y;\n        int cost = 0;\n        for (int j = 0; j <= xy; ++j) {\n            for (int j1 = 0; j1 + j <= k; ++j1) {\n                dp[i + 1][j1 + j] = min(dp[i + 1][j1 + j], dp[i][j1] + cost);\n            }\n            if (j < xy) {\n                if (x >= y) {\n                    x--, cost += y;\n                } else {\n                    y--, cost += x;\n                }\n            }\n        }\n    }\n    cout << (dp[n][k] == 1e9 ? -1 : dp[n][k]) << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2000",
    "index": "G",
    "title": "Call During the Journey",
    "statement": "You live in a city consisting of $n$ intersections and $m$ streets connecting some pairs of intersections. You can travel in either direction on each street. No two streets connect the same pair of intersections, and no street connects an intersection to itself. You can reach any intersection from any other, possibly passing through some other intersections.\n\nEvery minute, you can board a bus at intersection $u_i$ and travel for $l_{i1}$ minutes to intersection $v_i$. Conversely, you can travel from intersection $v_i$ to intersection $u_i$ in $l_{i1}$ minutes. You can only board and exit the bus at intersections. You can only board the bus at an intersection if you are currently there.\n\nYou can also walk along each street, which takes $l_{i2} > l_{i1}$ minutes.\n\nYou can make stops at intersections.\n\nYou live at intersection number $1$. Today you woke up at time $0$, and you have an important event scheduled at intersection number $n$, which you must reach no later than time $t_0$. You also have a phone call planned that will last from $t_1$ to $t_2$ minutes ($t_1 < t_2 < t_0$).\n\nDuring the phone call, you cannot ride the bus, but you can walk along any streets, make stops, or stay at home. You can exit the bus at minute $t_1$ and board the bus again at minute $t_2$.\n\nSince you want to get enough sleep, you became curious — how late can you leave home to have time to talk on the phone and still not be late for the event?",
    "tutorial": "Let's find the maximum time $ans_i$ for each vertex, at which it is possible to leave from it and reach vertex $n$ at time $t_0$. To find this value, we will run Dijkstra's algorithm from the last vertex. When processing the next edge, we will check if it is possible to travel by bus during the time interval from $ans_v - l_{i1}$ to $ans_v$. If it is possible, we will travel by bus; otherwise, we will either walk or wait at this vertex and then go by bus.",
    "code": "#include <iostream>\n#include <vector>\n#include <set>\n \nusing namespace std;\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    int t0, t1, t2;\n    cin >> t0 >> t1 >> t2;\n    vector<vector<vector<int>>> g(n);\n    for (int i = 0; i < m; ++i) {\n        int u, v, l1, l2;\n        cin >> u >> v >> l1 >> l2;\n        u--, v--;\n        g[u].push_back({v, l1, l2});\n        g[v].push_back({u, l1, l2});\n    }\n    set<pair<int, int>> prq;\n    prq.insert({t0, n - 1});\n    for (int i = 0; i + 1 < n; ++i) {\n        prq.insert({-1e9, i});\n    }\n    vector<int> dist(n, -1e9);\n    dist[n - 1] = t0;\n    while (!prq.empty()) {\n        auto p = *prq.rbegin();\n        prq.erase(p);\n        int d = p.first, u = p.second;\n        for (auto e: g[u]) {\n            int v = e[0], l1 = e[1], l2 = e[2];\n            int d1 = (d - l1 >= t2 || d <= t1) ? d - l1 : d - l2;\n            if(d1 == d - l2) d1 = max(d1, t1 - l1);\n            if (dist[v] < d1) {\n                prq.erase({dist[v], v});\n                dist[v] = d1;\n                prq.insert({d1, v});\n            }\n        }\n    }\n    cout << (dist[0] >= 0 ? dist[0] : -1) << '\\n';\n}\n \nint main() {\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2000",
    "index": "H",
    "title": "Ksyusha and the Loaded Set",
    "statement": "Ksyusha decided to start a game development company. To stand out among competitors and achieve success, she decided to write her own game engine. The engine must support a set initially consisting of $n$ distinct integers $a_1, a_2, \\ldots, a_n$.\n\nThe set will undergo $m$ operations sequentially. The operations can be of the following types:\n\n- Insert element $x$ into the set;\n- Remove element $x$ from the set;\n- Report the $k$-load of the set.\n\nThe $k$-load of the set is defined as the \\textbf{minimum} \\textbf{positive} integer $d$ such that the integers $d, d + 1, \\ldots, d + (k - 1)$ do not appear in this set. For example, the $3$-load of the set $\\{3, 4, 6, 11\\}$ is $7$, since the integers $7, 8, 9$ are absent from the set, and no smaller value fits.\n\nKsyusha is busy with management tasks, so you will have to write the engine. Implement efficient support for the described operations.",
    "tutorial": "We will maintain the elements of a set in std::set. We will also maintain a std::set of free segments (in the form of half-intervals). These segments can be easily updated during insertion and deletion operations. In one case, we need to remove a large segment and insert two small ones; in another case, we need to remove two small ones and insert one large segment. We will find suitable segments using std::set::lower_bound. To answer the query ?, we will maintain a Cartesian tree, where the keys are pairs (length, left boundary). Additionally, we will store the minimum of all left boundaries at the nodes. Now, to answer the query, it is sufficient to cut the Cartesian tree at $k$ and take the minimum from the stored minimums. The time complexity of the solution is: $O(n \\log n + m \\log n)$.",
    "code": "#pragma GCC optimize(\"O3,unroll-loops\")\n \n#include <bits/stdc++.h>\n \n#define endl '\\n'\n \nusing namespace std;\n \ntypedef pair<int, int> ipair;\n \n#define INF 1'000'000'009\n#define MAXN 200200\n#define MAXMEM 5'000'000\n#define MAXLEN 2'000'100\n \n#define X first\n#define Y second\n \nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n \nstruct node {\n    node *lv = nullptr, *rv = nullptr;\n    ipair key;\n    int prior;\n    int minl = INF;\n    \n    node(const ipair& key) : key(key), prior(rng()), minl(key.Y) {}\n};\n \nstatic inline int minl(node *v) {\n    return (v == nullptr ? INF : v->minl);\n}\n \nstatic inline void upd(node *v) {\n    v->minl = min(v->key.Y, min(minl(v->lv), minl(v->rv)));\n}\n \nnode *merge(node *s1, node *s2) {\n    if (s1 == nullptr) return s2;\n    if (s2 == nullptr) return s1;\n    if (s1->prior > s2->prior) {\n        s1->rv = merge(s1->rv, s2);\n        upd(s1);\n        return s1;\n    } else {\n        s2->lv = merge(s1, s2->lv);\n        upd(s2);\n        return s2;\n    }\n}\n \npair<node*, node*> split(node* &v, ipair x) {\n    if (v == nullptr) {\n        return {nullptr, nullptr};\n    }\n    if (v->key < x) {\n        auto [s1, s2] = split(v->rv, x);\n        v->rv = s1;\n        upd(v);\n        return {v, s2};\n    } else {\n        auto [s1, s2] = split(v->lv, x);\n        v->lv = s2;\n        upd(v);\n        return {s1, v};\n    }\n}\n \nint n, m;\nint arr[MAXN];\nnode *mem = (node*)calloc(MAXMEM, sizeof(*mem));\nnode *mpos = mem;\nnode *root;\nset<int> M;\n \n// [l..r)\nvoid add_seg(int l, int r) {\n    if (l >= r) return;\n    ipair p {r - l, l};\n    auto [s1, s2] = split(root, p);\n    node *v = mpos++;\n    *v = node(p);\n    root = merge(merge(s1, v), s2);\n}\n \nvoid rem_dek(node* &v, const ipair& x) {\n    if (v == nullptr) return;\n    if (v->key == x) {\n        v = merge(v->lv, v->rv);\n        if (v) upd(v);\n        return;\n    }\n    if (v->key < x) rem_dek(v->rv, x);\n    else rem_dek(v->lv, x);\n    upd(v);\n}\n \n// [l..r)\nvoid rem_seg(int l, int r) {\n    if (l >= r) return;\n    ipair p {r - l, l};\n    rem_dek(root, p);\n}\n \nvoid add_val(int x) {\n    auto it = M.lower_bound(x);\n    int clsl = (it == M.begin() ? 0 : *prev(it));\n    int clsr = (it == M.end() ? INF : *it);\n    rem_seg(clsl + 1, clsr);\n    add_seg(clsl + 1, x);\n    if (clsr != INF) add_seg(x + 1, clsr);\n    M.insert(x);\n}\n \nvoid rem_val(int x) {\n    auto it = M.lower_bound(x);\n    int clsl = (it == M.begin() ? 0 : *prev(it));\n    int clsr = (next(it) == M.end() ? INF : *next(it));\n    rem_seg(clsl + 1, x);\n    rem_seg(x + 1, clsr);\n    if (clsr != INF) add_seg(clsl + 1, clsr);\n    M.erase(x);\n}\n \nint query(int k) {\n    if (M.empty()) return 1;\n    auto [s1, s2] = split(root, make_pair(k, -1));\n    fprintf(stderr, \"AMOGUS: %p, %p\\n\", s1, s2);\n    int ans = min(*M.rbegin() + 1, minl(s2));\n    root = merge(s1, s2);\n    return ans;\n}\n \nvoid init() {\n    root = nullptr;\n    mpos = mem;\n    M = {arr, arr + n};\n    add_seg(1, *M.begin());\n    for (auto it = M.begin(); next(it) != M.end(); ++it)\n        add_seg(*it + 1, *next(it));\n}\n \nsigned main() {\n    int t; cin >> t;\n    while (t--) {\n        cin >> n;\n        for (int i = 0; i < n; ++i)\n            cin >> arr[i];\n        init();\n        cin >> m;\n        for (int j = 0; j < m; ++j) {\n            char tp; cin >> tp;\n            int x, k;\n            switch (tp) {\n            case '+':\n                cin >> x;\n                add_val(x);\n                break;\n            case '-':\n                cin >> x;\n                rem_val(x);\n                break;\n            case '?':\n                cin >> k;\n                cout << query(k) << \" \";\n                break;\n            }\n        }\n        cout << endl;\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2001",
    "index": "A",
    "title": "Make All Equal",
    "statement": "You are given a cyclic array $a_1, a_2, \\ldots, a_n$.\n\nYou can perform the following operation on $a$ at most $n - 1$ times:\n\n- Let $m$ be the current size of $a$, you can choose any two adjacent elements where the previous one is no greater than the latter one (In particular, $a_m$ and $a_1$ are adjacent and $a_m$ is the previous one), and delete exactly one of them. In other words, choose an integer $i$ ($1 \\leq i \\leq m$) where $a_i \\leq a_{(i \\bmod m) + 1}$ holds, and delete exactly one of $a_i$ or $a_{(i \\bmod m) + 1}$ from $a$.\n\nYour goal is to find the minimum number of operations needed to make all elements in $a$ equal.",
    "tutorial": "What's the most obvious lower bound of the answer? Is the lower bound achievable? One standard way to solve optimization problem is to make observation on lower(upper) bound of the answer and prove such bound is achievable, it's useful in lot of problems. Let $x$ be one of the most frequent elements in $a$, then the answer must be at least $(n - \\text{frequency of } x)$, and this lower bound is always achievable by keep erasing a non-$x$ element from $a$, and we can prove it's always possible to do so. proof: If all elements of $a$ are $x$, we are done. Otherwise, let $y$ denote all the elements that are not $x$, then $a$ would have some subarray of the form $x \\ldots x, y \\ldots y, x \\ldots x$. In this subarray, there must exist adjacent elements that satisfy $a_i \\leq a_{(i \\bmod m) + 1}$, otherwise we would have $x > y > \\ldots > y > x$ implying $x > x$ which leads to a contradiction.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false), cin.tie(NULL);\n\n  int t; cin >> t;\n  while(t--) {\n    int n; cin >> n;\n    vector<int> a(n);\n    for(int &x : a) cin >> x;\n\n    vector<int> freq(n + 1);\n    for(int x : a) freq[x]++;\n\n    cout << n - (*max_element(freq.begin(), freq.end())) << '\\n';\n  }\n}\n",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2001",
    "index": "B",
    "title": "Generate Permutation",
    "statement": "There is an integer sequence $a$ of length $n$, where each element is initially $-1$.\n\nMisuki has two typewriters where the first one writes letters from left to right, with a pointer initially pointing to $1$, and another writes letters from right to left with a pointer initially pointing to $n$.\n\nMisuki would choose one of the typewriters and use it to perform the following operations until $a$ becomes a permutation of $[1, 2, \\ldots, n]$\n\n- write number: write the minimum \\textbf{positive} integer that isn't present in the array $a$ to the element $a_i$, $i$ is the position where the pointer points at. Such operation can be performed only when $a_i = -1$.\n- carriage return: return the pointer to its initial position (i.e. $1$ for the first typewriter, $n$ for the second)\n- move pointer: move the pointer to the next position, let $i$ be the position the pointer points at before this operation, if Misuki is using the first typewriter, $i := i + 1$ would happen, and $i := i - 1$ otherwise. Such operation can be performed only if after the operation, $1 \\le i \\le n$ holds.\n\nYour task is to construct any permutation $p$ of length $n$, such that the minimum number of carriage return operations needed to make $a = p$ is the same no matter which typewriter Misuki is using.",
    "tutorial": "Write a few small cases (ex. $n = 3, 4, 5$) and play with it, can you notice something interesting about the cost function? Write a few examples and play with it is a good start to solve ad-hoc problems. Consider subtask - decision version of the problem (i.e. yes/no problem) as follow: \"Given a fixed $p$, check if this permutation is valid.\" The above problem would reduce to finding minimum number of carriage return operations needed for each typewriter. Now you know how to solve above problem, do you notice something interesting about the cost function? In lot of problems, decision version of the problem is usually a useful subtask to consider. Let $c_1, c_2$ denote the minimum number of carriage return operations needed to make $a = p$ if Misuki is using first/second typewritter. Let's consider how to calculate them. For $c_1$, we need to do carriage return operation whenever the position of value $x + 1$ is before $x$, for all $x \\in [1, n - 1]$, so $c_1 = (\\text{#}x \\in [1, n - 1] \\text{ such that } \\mathrm{pos}_x > \\mathrm{pos}_{x + 1})$. Similarly, $c_2 = (\\text{#}x \\in [1, n - 1] \\text{ such that } \\mathrm{pos}_x < \\mathrm{pos}_{x + 1})$. Since for $x \\in [1, n - 1]$, either $\\mathrm{pos}_x < \\mathrm{pos}_{x + 1}$ or $\\mathrm{pos}_x > \\mathrm{pos}_{x + 1}$ would hold, so we have $c_1 + c_2 = n - 1$, which is a constant, and $c_1 = c_2 \\leftrightarrow c_1 = \\frac{n - 1}{2}$, which only has solution when $n$ is odd, and such $p$ can be constructed easily (for example, ${n - 1, n, n - 3, n - 2, ..., 4, 5, 2, 3, 1}$).",
    "code": "#include <iostream>\n#include <numeric>\n#include <vector>\n\nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false), cin.tie(NULL);\n\n  int t; cin >> t;\n  while(t--) {\n    int n; cin >> n;\n    if (n % 2 == 0) {\n      cout << -1 << '\\n';\n    } else {\n      vector<int> p(n);\n      iota(p.begin(), p.end(), 1);\n      for(int i = 1; i < n; i += 2)\n        swap(p[i], p[i + 1]);\n      for(int i = 0; i < n; i++)\n        cout << p[i] << \" \\n\"[i + 1 == n];\n    }\n  }\n}\n",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "2001",
    "index": "C",
    "title": "Guess The Tree",
    "statement": "This is an interactive problem.\n\nMisuki has chosen a secret tree with $n$ nodes, indexed from $1$ to $n$, and asked you to guess it by using queries of the following type:\n\n- \"? a b\" — Misuki will tell you which node $x$ minimizes $|d(a,x) - d(b,x)|$, where $d(x,y)$ is the distance between nodes $x$ and $y$. If more than one such node exists, Misuki will tell you the one which minimizes $d(a,x)$.\n\nFind out the structure of Misuki's secret tree using at most $15n$ queries!",
    "tutorial": "Imagine we have $n$ isolated vertices initially, can you find any edge connect two component using reasonable number of queries? Use binary search. It's easy to verify that querying $a$ and $b$ will return the midpoint of the path between $a$ and $b$. In case the path has odd length, the node closer to $a$ of the two central nodes will be returned. We will now construct the tree by expanding a connected component. Let $A = \\{1\\}$ and $B = \\{2,\\ldots,n\\}$. While $B$ is not empty, choose any $b \\in B$ and $a \\in A$. Let $P$ be the path between $a$ and $b$. By construction, $P$ will consist of a prefix contained in $A$ and a suffix contained in $B$. We can binary search for the first $i$ such that $P_i \\in B$. This will take at most $\\lceil log(|P|) \\rceil + 2$ queries. Then, $(P_{i-1}, P_i)$ will be an edge of the tree, so we will set $A = A \\cup {P_i}$ and $B = B \\backslash {P_i}$. The total number of queries will be smaller than $n \\lceil log(n) \\rceil + 2n = 12000$. Consider we have $n$ isolated vertices initially, and try to keep finding an edge connect two different component. Assume $u, v$ is at different component, then we have the following possible cases for the answer $x$. $x = u$: which means $u, v$ are connected by an edge and we are done. $x$ belongs to same component of $u$, seting $u := x$. $x$ belongs to same component of $v$, seting $v := x$. $x$ belongs to other component than $u, v$, in such case, either setting $u := x$ or $v := x$. in case 1. we are done, and in case 2, 3, 4, we shorten the distance between $u, v$ by about half while keeping them not belongs to same component, so we can find an edge connect two component in $O(\\lg n)$ queries and we are done.",
    "code": "#include <iostream>\n#include <numeric>\n#include <vector>\n#include <array>\n\nusing namespace std;\n\nint query(int u, int v) {\n  cout << \"? \" << u + 1 << ' ' << v + 1 << '\\n';\n  int x; cin >> x;\n  return x - 1;\n}\n\nint main() {\n  int t; cin >> t;\n  while(t--) {\n    int n; cin >> n;\n\n    vector<array<int, 2>> e;\n    vector<int> c(n);\n    iota(c.begin(), c.end(), 0);\n    auto addEdge = [&](int u, int v) {\n      e.push_back({u, v});\n      vector<int> cand;\n      for(int i = 0; i < n; i++)\n        if (c[i] == c[v])\n          cand.emplace_back(i);\n      for(int i : cand)\n        c[i] = c[u];\n    };\n\n    for(int i = 0; i < n - 1; i++) {\n      int u = 0, v = 0;\n      while(c[v] == c[u]) v++;\n      int x;\n      while((x = query(u, v)) != u) {\n        if (c[u] == c[x]) u = x;\n        else v = x;\n      }\n      addEdge(u, v);\n    }\n\n    cout << \"!\";\n    for(auto [u, v] : e) cout << ' ' << u + 1 << ' ' << v + 1;\n    cout << '\\n';\n  }\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "greedy",
      "interactive",
      "trees"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2001",
    "index": "D",
    "title": "Longest Max Min Subsequence",
    "statement": "You are given an integer sequence $a_1, a_2, \\ldots, a_n$. Let $S$ be the set of all possible non-empty subsequences of $a$ without duplicate elements. Your goal is to find the longest sequence in $S$. If there are multiple of them, find the one that minimizes lexicographical order after multiplying terms at odd positions by $-1$.\n\nFor example, given $a = [3, 2, 3, 1]$, $S = \\{[1], [2], [3], [2, 1], [2, 3], [3, 1], [3, 2], [2, 3, 1], [3, 2, 1]\\}$. Then $[2, 3, 1]$ and $[3, 2, 1]$ would be the longest, and $[3, 2, 1]$ would be the answer since $[-3, 2, -1]$ is lexicographically smaller than $[-2, 3, -1]$.\n\nA sequence $c$ is a subsequence of a sequence $d$ if $c$ can be obtained from $d$ by the deletion of several (possibly, zero or all) elements.\n\nA sequence $c$ is lexicographically smaller than a sequence $d$ if and only if one of the following holds:\n\n- $c$ is a prefix of $d$, but $c \\ne d$;\n- in the first position where $c$ and $d$ differ, the sequence $c$ has a smaller element than the corresponding element in $d$.",
    "tutorial": "Forget about minimize lexicographical order. What's the size of longest $b$ we can get? It's the number of different elements. Try to minimize/maximize first element in $b$ without reducing the max size of $b$ we can get. When solving problem asking for minimize/maximize lexicographical order of something, we can often construct them by minimize/maximize first element greedily. Let's ignore the constraint where $b$ should be lexicographically smallest. How can we find the length of $b$? Apparently, it is the number of distinct elements in $a$. Let's call it $k$. Now we know how to find the maximum possible length of $b$. Let's try to construct $b$ from left to right without worsening the answer, and greedily minimize its lexicographical order. Assume we pick $a_i$ as the $j$-th element in $b$, then there should be $k - j$ distinct elements in the subarray $a[i + 1, n]$ after deleting all elements that appear in the subarray $b[1, j]$. Assume we already construct $b_1, b_2, \\ldots, b_j$ where $b_j = a_i$ and we want to find $b_{j + 1}$, and let $l_x$ be the last position where $x$ occurs in the subarray $a[i + 1, n]$ or $\\infty$ if it doesn't exist, then we can choose anything in $a[i + 1, \\min\\limits_{1 \\le x \\le n}(l_x)]$. And to minimize lexicographical order, we need to choose the maximum element in it if $(j + 1)$ is odd, or the minimum element otherwise. If there are multiple of them, choose the leftmost one of them is optimal since we would have a longer suffix of $a$ for future construction. Then observe for the candidate window (i.e. $a[i + 1, \\min\\limits_{1 \\le x \\le n}(l_x)]$), its left bound and right bound are non-decreasing, so we can use priority queues or set to maintain all possible candidates by storing $(a_{pos}, pos)$, and another priority queue or set to maintain all $l_x > i$. And the total time complexity is $O(nlgn)$.",
    "code": "#include <cstdint>\n#include <iostream>\n#include <set>\n#include <vector>\n\nusing namespace std;\n\nvoid solve() {\n    int N; cin >> N;\n    \n    vector<int> A(N);\n    for (int &x : A) cin >> x, --x;\n    \n    vector<int> cnt(N, 0), is_last(N, 0), last_pos(N, -1);\n    for (int i = N-1; i >= 0; --i) {\n        if (!cnt[A[i]]++) is_last[i] = 1, last_pos[A[i]] = i;\n    }\n    \n    vector<int> ans;\n    multiset<int> st;\n    int l = 0, r = -1, flag = 0;\n    while (r+1 < N) {\n        while (r+1 < N and (r == -1 or !is_last[r])) {\n            ++r;\n            if (is_last[last_pos[A[r]]]) st.emplace(A[r]);\n        }\n        if (st.size()) {\n            ans.emplace_back(flag ? *begin(st) : *rbegin(st)), flag ^= 1;\n            is_last[last_pos[ans.back()]] = 0;\n            while (A[l] != ans.back()) {\n                if (auto it = st.find(A[l++]); it != end(st)) st.erase(it);\n            }\n            st.erase(A[l++]); // no find\n        }\n    }\n    \n    int M = ans.size();\n    cout << M << '\\n';\n    for (int i = 0; i < M; ++i) cout << ans[i] + 1 << \" \\n\"[i == M-1];\n}\n\nint32_t main() {\n    ios_base::sync_with_stdio(0), cin.tie(0);\n    \n    int t = 1; cin >> t;\n    for (int _ = 1; _ <= t; ++_)\n        solve();\n    \n    return 0;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2001",
    "index": "E1",
    "title": "Deterministic Heap (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the two versions is the definition of deterministic max-heap, time limit, and constraints on $n$ and $t$. You can make hacks only if both versions of the problem are solved.}\n\nConsider a perfect binary tree with size $2^n - 1$, with nodes numbered from $1$ to $2^n-1$ and rooted at $1$. For each vertex $v$ ($1 \\le v \\le 2^{n - 1} - 1$), vertex $2v$ is its left child and vertex $2v + 1$ is its right child. Each node $v$ also has a value $a_v$ assigned to it.\n\nDefine the operation $\\mathrm{pop}$ as follows:\n\n- initialize variable $v$ as $1$;\n- repeat the following process until vertex $v$ is a leaf (i.e. until $2^{n - 1} \\le v \\le 2^n - 1$);\n\n- among the children of $v$, choose the one with the larger value on it and denote such vertex as $x$; if the values on them are equal (i.e. $a_{2v} = a_{2v + 1}$), you can choose any of them;\n- assign $a_x$ to $a_v$ (i.e. $a_v := a_x$);\n- assign $x$ to $v$ (i.e. $v := x$);\n\n- assign $-1$ to $a_v$ (i.e. $a_v := -1$).\n\nThen we say the $\\mathrm{pop}$ operation is deterministic if there is a unique way to do such operation. In other words, $a_{2v} \\neq a_{2v + 1}$ would hold whenever choosing between them.\n\nA binary tree is called a max-heap if for every vertex $v$ ($1 \\le v \\le 2^{n - 1} - 1$), both $a_v \\ge a_{2v}$ and $a_v \\ge a_{2v + 1}$ hold.\n\nA max-heap is deterministic if the $\\mathrm{pop}$ operation is deterministic to the heap when we do it \\textbf{for the first time}.\n\nInitially, $a_v := 0$ for every vertex $v$ ($1 \\le v \\le 2^n - 1$), and your goal is to count the number of different deterministic max-heaps produced by applying the following operation $\\mathrm{add}$ exactly $k$ times:\n\n- Choose an integer $v$ ($1 \\le v \\le 2^n - 1$) and, for every vertex $x$ on the path between $1$ and $v$, add $1$ to $a_x$.\n\nTwo heaps are considered different if there is a node which has different values in the heaps.\n\nSince the answer might be large, print it modulo $p$.",
    "tutorial": "Consider subtask - decision version of the problem (i.e. yes/no problem) as follow: \"Given a sequence $a$ resulting from $k$ operations, check whether such $a$ is a deterministic max-heap.\", what property $a$ should have? Try to fix the position of leaf being popped, what property are needed on the path from root to it? Does it really matter where the leaf being popped lies important? Try to count the number of $a$ where the first leaf being popped is fixed at one position using DP. Try to use DP to track the path of elements being popped and count number of possible $a$ satisfy the property. Again, in lot of problems, decision version of the problem is usually a useful subtask to consider. And it's especially useful in counting problems about giving some operation and ask you to count the number of possible outcomes. Since there may be multiple ways to apply operations to make the same heap, let's consider the decision version of the problem instead of counting the operation sequence directly. That is, \"Given a sequence $a$ resulting from $k$ operations, check whether such $a$ is a deterministic max-heap.\", and try to figure out what properties are needed. Let $v = 2^{n - 1}$ be the only leaf such that after popping one element from the top, every element on the path between $1$ and $v$ would be moved upward, then the condition of a deterministic max-heap can be rephrased as follows: $a_1 = k$ $a_{v} \\ge a_{2v} + a_{2v + 1}$, for any $v$ ($1 \\le v < 2^{n - 1}$) $a_{2\\cdot 2^k} > a_{2 \\cdot 2^k + 1}$, for any $k$ ($0 \\le k \\le n - 2$) So we can see that for any $k$ ($0 \\le k \\le n - 2$), the number of operations done in the subtree of $2\\cdot 2^k$ should be greater than the number of operations done in the subtree of $2 \\cdot 2^k + 1$, and we don't care much about how these operations distribute in the subtree of $2 \\cdot 2^k + 1$ as long as 3. holds. Let's call such subtree \"uncritical\". For any uncritical subtree with size $sz$, if we do $x$ operations under it, there are $\\binom{x + (sz - 1)}{x}$ ways to do so. Now we can use dp to consider all valid $a$ we can get by enumerating the number of operation done on each vertex on the path from $1$ to $2^{n - 1}$ and all uncritical subtree. Let $dp[i][j]$ be the number of different $a$ we can get by $j$ operations on the subtree with size $2^i - 1$, then we have base case: $dp[1][j] = 1, \\forall j \\in [0, k]$ transition: $dp[i + 1][l] \\text{ += } dp[i][j] \\times \\binom{x + (2^i - 2)}{x} ,\\forall x \\in [0, j), l \\in [j + x, k]$ using prefix sum, we can optimize the above dp to $O(nk^2)$, and the number of deterministic max-heap where vertex $2^{n - 1}$ would be pulled up is $dp[n][k]$. Finally, due to the symmetry property of a perfect binary tree, the number of deterministic max-heap where $v$ would be pulled are equal for all possible $v$, so the final answer we want would be $dp[n][k] \\times 2^{n - 1}$.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nusing ll = long long;\n\nint binpow(ll a, ll b, ll p) {\n  ll c = 1;\n  while(b) {\n    if (b & 1) c = c * a % p;\n    a = a * a % p, b >>= 1;\n  }\n  return c;\n}\n\nint main() {\n  int t; cin >> t;\n  while(t--) {\n    int n, k, p; cin >> n >> k >> p;\n\n    vector<ll> fac(k + 1, 1);\n    for(int i = 1; i <= k; i++) fac[i] = fac[i - 1] * i % p;\n\n    vector<ll> faci(k + 1);\n    faci[k] = binpow(fac[k], p - 2, p);\n    for(int i = k - 1; i >= 0; i--) faci[i] = faci[i + 1] * (i + 1) % p;\n\n    vector<ll> pow2(n + 1, 1);\n    for(int i = 1; i <= n; i++) pow2[i] = pow2[i - 1] * 2 % p;\n\n    vector<ll> dp(k + 1, 1);\n    for(int i = 1; i < n; i++) {\n      vector<ll> binom(k + 1, 1);\n      for(int j = 1; j <= k; j++) binom[j] = binom[j - 1] * (pow2[i] + j - 2 + p) % p;\n      for(int j = 0; j <= k; j++) binom[j] = binom[j] * faci[j] % p;\n\n      vector<ll> nxt(k + 1);\n      for(int j = 0; j <= k; j++)\n        for(int x = 0; x < j and j + x <= k; x++)\n          nxt[j + x] = (nxt[j + x] + dp[j] * binom[x] % p) % p;\n\n      for(int j = 1; j <= k; j++)\n        nxt[j] = (nxt[j - 1] + nxt[j]) % p;\n      dp.swap(nxt);\n    }\n\n    cout << dp[k] * pow2[n - 1] % p << '\\n';\n  }\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2001",
    "index": "E2",
    "title": "Deterministic Heap (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the two versions is the definition of deterministic max-heap, time limit, and constraints on $n$ and $t$. You can make hacks only if both versions of the problem are solved.}\n\nConsider a perfect binary tree with size $2^n - 1$, with nodes numbered from $1$ to $2^n-1$ and rooted at $1$. For each vertex $v$ ($1 \\le v \\le 2^{n - 1} - 1$), vertex $2v$ is its left child and vertex $2v + 1$ is its right child. Each node $v$ also has a value $a_v$ assigned to it.\n\nDefine the operation $\\mathrm{pop}$ as follows:\n\n- initialize variable $v$ as $1$;\n- repeat the following process until vertex $v$ is a leaf (i.e. until $2^{n - 1} \\le v \\le 2^n - 1$);\n\n- among the children of $v$, choose the one with the larger value on it and denote such vertex as $x$; if the values on them are equal (i.e. $a_{2v} = a_{2v + 1}$), you can choose any of them;\n- assign $a_x$ to $a_v$ (i.e. $a_v := a_x$);\n- assign $x$ to $v$ (i.e. $v := x$);\n\n- assign $-1$ to $a_v$ (i.e. $a_v := -1$).\n\nThen we say the $\\mathrm{pop}$ operation is deterministic if there is a unique way to do such operation. In other words, $a_{2v} \\neq a_{2v + 1}$ would hold whenever choosing between them.\n\nA binary tree is called a max-heap if for every vertex $v$ ($1 \\le v \\le 2^{n - 1} - 1$), both $a_v \\ge a_{2v}$ and $a_v \\ge a_{2v + 1}$ hold.\n\nA max-heap is deterministic if the $\\mathrm{pop}$ operation is deterministic to the heap when we do it \\textbf{for the first and the second time}.\n\nInitially, $a_v := 0$ for every vertex $v$ ($1 \\le v \\le 2^n - 1$), and your goal is to count the number of different deterministic max-heaps produced by applying the following operation $\\mathrm{add}$ exactly $k$ times:\n\n- Choose an integer $v$ ($1 \\le v \\le 2^n - 1$) and, for every vertex $x$ on the path between $1$ and $v$, add $1$ to $a_x$.\n\nTwo heaps are considered different if there is a node which has different values in the heaps.\n\nSince the answer might be large, print it modulo $p$.",
    "tutorial": "Fix the position of first and second leaf being popped, what's the property needed for $a$ to be determinitic? Does the position of first leaf being popped really matters? Fix the position of first leaf being popped, do we really need to consider all possible position of second leaf being popped? Make good use of symmetry can reduce the complexity of problem significantly! For convenience, let $\\text{det_heap}()$ denote # twice-deterministic heap, $\\text{det_heap}(v)$ denote # twice-deterministic heap where the first pop come from leaf $v$, $\\text{det_heap}(v, u)$ denote # twice-deterministic heap where the first pop come from leaf $v$, second pop come from leaf $u$. Similar to easier version, we have $\\text{det_heap}() = 2^{n - 1}\\cdot\\text{det_heap}(2^{n - 1})$ because of symmetry. Then consider enumerate $u$, the second leaf being popped, we have $\\text{det_heap}(2^{n - 1}) = \\sum\\limits_{u = 2^{n - 1} + 1}^{2^n - 1}\\text{det_heap}(2^{n - 1}, u)$ because of symmetry, again, for any $u_1 \\neq u_2, LCA(2^{n - 1}, u_1) = LCA(2^{n - 1}, u_2)$, we have $\\text{det_heap}(2^{n - 1}, u_1) = \\text{det_heap}(2^{n - 1}, u_2)$, so for each LCA, we only need to enumerate leftmost leaf under it as second popped leaf and multiply answer with # leaves in such subtree. then consider the relation of values between vertices, we have where black edge from $x$ to $y$ means $a_x \\le a_y$, which comes from the nature of $\\text{add}$ operation red edge from $x$ to $y$ means $a_x < a_y$, which come from the fact that $v$ should be first leaf being pulled blue edge from $x$ to $y$ means $a_x < a_y$, which come from the fact that $u$ should be second leaf being pulled Then observe if we have some directed triangle consist of edges $(x, y), (y, z), (x, z)$, edge $(x, z)$ didn't bring extra relation so we can delete it, after that, we would have Then we can use pair of value of vertices from same depth as the state of dp, and enumerate such pair in increasing order of height while not breaking the relations, then we would have $dp[h][l][r]$ = # twice-deterministic heap when the left vertex have value $l$ and right vertex have value $r$ and the current height is $h$. First, to handle the relation of Z shape formed by red/blue arrows and enumerate value of $(L, R, R')$, consider the following picture (The red subtree is one-time deterministic heap, while the other can be any heap.) Also let $f(h, k)$ denote # deterministic heap for one time pop with height $h$ after doing operation $k$ times where the leftmost leaf being pulled, $g(h, k)$ denote # max heap with height $h$ after doing operation $k$ times (We already know how to compute them in easier version of this problem) Let's fix the value $L$ and $R$, and push it to some $dp[h][L'][R']$, we need to satisfy $L' > R' > L > R$ $L' \\ge L + R$ in such case, enumerate all pair $(L, R), (L > R)$ and for all $L' \\ge L + R, R' \\ge L + 1$, add $f(h - 1, L) \\cdot g(h - 1, R)$ to $dp[h][L'][R']$. After that, for every $L' \\le R'$, eliminate its contribution, while for every $L' > R'$, multiply its contribution with $f(h, R') \\cdot 2^h$. which can be done in $O(k^2)$ with the help of prefix sum. Second, to handle the relation formed by black/blue edges and enumerate value $R'$, consider the following picture For each $L, R$, we need to push it some some $dp[h][L'][R']$ where the following conditions hold $L' \\ge L > R'$ $L' \\ge L + R$ we can handle it by first adding $dp[h - 1][L][R]$ to $dp[L'][R']$ for all $L' \\ge L + R, R' \\le L - 1$. Then for all $L' \\le R'$, eliminate its contribution, while for the other, multiply the contribution with $g(h, R')$, which can also be done by prefix sum in $O(k^2)$. Then the answer would be $2^{n - 1} \\cdot \\sum\\limits_{L + R \\le k}dp[h - 2][L][R]$ and the problem has been solved in $O(nk^2)$.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nusing ll = long long;\n\nint binpow(ll a, ll b, ll p) {\n  ll c = 1;\n  while(b) {\n    if (b & 1) c = c * a % p;\n    a = a * a % p, b >>= 1;\n  }\n  return c;\n}\n\nint main() {\n  int t; cin >> t;\n  while(t--) {\n    int n, k, p; cin >> n >> k >> p;\n\n    vector<ll> fac(k + 1, 1);\n    for(int i = 1; i <= k; i++) fac[i] = fac[i - 1] * i % p;\n\n    vector<ll> faci(k + 1);\n    faci[k] = binpow(fac[k], p - 2, p);\n    for(int i = k - 1; i >= 0; i--) faci[i] = faci[i + 1] * (i + 1) % p;\n\n    vector<ll> pow2(n + 1, 1);\n    for(int i = 1; i <= n; i++) pow2[i] = pow2[i - 1] * 2 % p;\n\n    vector<ll> dp(k + 1, 1);\n    vector dp2(k + 1, vector<ll>(k + 1));\n    for(int l = 0; l <= k; l++)\n      for(int r = 0; r < l; r++)\n        dp2[l][r] = 1;\n    for(int i = 1; i + 1 < n; i++) {\n      vector<ll> binom(k + 1, 1);\n      for(int j = 1; j <= k; j++) binom[j] = binom[j - 1] * (pow2[i] + j - 2 + p) % p;\n      for(int j = 0; j <= k; j++) binom[j] = binom[j] * faci[j] % p;\n\n      vector<ll> binom2(k + 1, 1);\n      for(int j = 1; j <= k; j++) binom2[j] = binom2[j - 1] * (pow2[i + 1] + j - 2 + p) % p;\n      for(int j = 0; j <= k; j++) binom2[j] = binom2[j] * faci[j] % p;\n\n      vector<ll> nxt(k + 1);\n      for(int j = 0; j <= k; j++)\n        for(int x = 0; x < j and j + x <= k; x++)\n          nxt[j + x] = (nxt[j + x] + dp[j] * binom[x] % p) % p;\n\n      for(int j = 1; j <= k; j++)\n        nxt[j] = (nxt[j - 1] + nxt[j]) % p;\n\n      vector nxt2(k + 1, vector<ll>(k + 1));\n      {\n        vector tmp(k + 1, vector<ll>(k + 1));\n        for(int l = 0; l < k; l++)\n          for(int r = 0; r < l and l + r <= k; r++)\n            tmp[l + r][l + 1] = (tmp[l + r][l + 1] + dp[l] * binom[r]) % p;\n        for(int l = 0; l <= k; l++)\n          for(int r = 1; r <= k; r++)\n            tmp[l][r] = (tmp[l][r] + tmp[l][r - 1]) % p;\n        for(int l = 1; l <= k; l++)\n          for(int r = 1; r <= k; r++)\n            tmp[l][r] = (tmp[l][r] + tmp[l - 1][r]) % p;\n        for(int l = 0; l <= k; l++)\n          for(int r = 0; r < l; r++)\n            nxt2[l][r] = (nxt2[l][r] + tmp[l][r] * nxt[r] % p * pow2[i]) % p;\n      }\n\n      {\n        vector tmp(k + 1, vector<ll>(k + 1));\n        for(int l = 1; l <= k; l++)\n          for(int r = 0; l + r <= k; r++)\n            tmp[l + r][l - 1] = (tmp[l + r][l - 1] + dp2[l][r]) % p;\n        for(int l = 0; l <= k; l++)\n          for(int r = k - 1; r >= 0; r--)\n            tmp[l][r] = (tmp[l][r] + tmp[l][r + 1]) % p;\n        for(int l = 1; l <= k; l++)\n          for(int r = 0; r <= k; r++)\n            tmp[l][r] = (tmp[l][r] + tmp[l - 1][r]) % p;\n        for(int l = 0; l <= k; l++)\n          for(int r = 0; r <= k; r++)\n            nxt2[l][r] = (nxt2[l][r] + tmp[l][r] * binom2[r]) % p;\n      }\n\n      dp.swap(nxt);\n      dp2.swap(nxt2);\n    }\n\n    ll ans = 0;\n    for(int l = 0; l <= k; l++)\n      for(int r = 0; l + r <= k; r++)\n        ans = (ans + dp2[l][r]) % p;\n\n    cout << ans * pow2[n - 1] % p << '\\n';\n  }\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2002",
    "index": "A",
    "title": "Distanced Coloring",
    "statement": "You received an $n\\times m$ grid from a mysterious source. The source also gave you a magic positive integer constant $k$.\n\nThe source told you to color the grid with some colors, satisfying the following condition:\n\n- If $(x_1,y_1)$, $(x_2,y_2)$ are two distinct cells with the same color, then $\\max(|x_1-x_2|,|y_1-y_2|)\\ge k$.\n\nYou don't like using too many colors. Please find the minimum number of colors needed to color the grid.",
    "tutorial": "Consider the case with $n=m=k$. Generalize the solution for all $n,m,k$. It can be shown that for any $k\\times k$ subgrid, the colors we use must be pairwise distinct. Thus, we have an lower bound of $\\min(n,k)\\cdot\\min(m,k)$. We can show that this lower bound is indeed achievable by coloring the upper-left $\\min(n,k)\\cdot\\min(m,k)$ subgrid with distinct colors, and copy-pasting it to fill the rest of the grid. Time complexity: $O(1)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint t, n, m, k;\nint main() {\n    scanf(\"%d\", &t);\n\n    while (t--) {\n        scanf(\"%d%d%d\", &n, &m, &k);\n        printf(\"%d\\n\", min(n, k)*min(m, k));\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2002",
    "index": "B",
    "title": "Removals Game",
    "statement": "Alice got a permutation $a_1, a_2, \\ldots, a_n$ of $[1,2,\\ldots,n]$, and Bob got another permutation $b_1, b_2, \\ldots, b_n$ of $[1,2,\\ldots,n]$. They are going to play a game with these arrays.\n\nIn each turn, the following events happen in order:\n\n- Alice chooses either the first or the last element of her array and removes it from the array;\n- Bob chooses either the first or the last element of his array and removes it from the array.\n\nThe game continues for $n-1$ turns, after which both arrays will have exactly one remaining element: $x$ in the array $a$ and $y$ in the array $b$.\n\nIf $x=y$, Bob wins; otherwise, Alice wins. Find which player will win if both players play optimally.",
    "tutorial": "Find some conditions that Bob need to win. A general idea is that it is very difficult for Bob to win. We make some observations regarding the case where Bob wins. It is intuitive to see that for any subarray $[A_l,A_{l+1},\\cdots,A_r]$, the elements' positions in $B$ must also form an interval. If $A[l:r]$ does not form an interval in $B$, Alice can simply remove elements until only $A[l:r]$ is left, no matter how Bob plays, there must now be an element in $A$ but not in $B$ because of our previous condition. Alice can then remove everything other than this element to win. From here, it is easy to prove by induction that for Bob to win, either $A=B$ or $A=\\textrm{rev}(B)$. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\n#define lc(x) ((x) << 1)\n#define rc(x) ((x) << 1 | 1)\n#define ru(i, l, r) for (int i = (l); i <= (r); i++)\n#define rd(i, r, l) for (int i = (r); i >= (l); i--)\n#define mid ((l + r) >> 1)\n#define pii pair<int, int>\n#define mp make_pair\n#define fi first\n#define se second\n#define sz(s) (int)s.size()\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\n#define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>\nusing namespace std;\nmt19937 Rand(chrono::steady_clock::now().time_since_epoch().count());\nint read() {\n    int x = 0, w = 0;\n    char ch = getchar();\n\n    while (!isdigit(ch))\n        w |= ch == '-', ch = getchar();\n\n    while (isdigit(ch))\n        x = x * 10 + ch - '0', ch = getchar();\n\n    return w ? -x : x;\n}\nint main() {\n    int T = read();\n\n    while (T--) {\n        int n = read();\n        vector<int> a, b;\n        ru(i, 1, n) a.push_back(read());\n        ru(i, 1, n) b.push_back(read());\n\n        if (a == b) {\n            printf(\"Bob\\n\");\n            continue;\n        }\n\n        reverse(a.begin(), a.end());\n\n        if (a == b) {\n            printf(\"Bob\\n\");\n            continue;\n        }\n\n        printf(\"Alice\\n\");\n    }\n\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "games"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2002",
    "index": "C",
    "title": "Black Circles",
    "statement": "There are $n$ circles on a two-dimensional plane. The $i$-th circle is centered at $(x_i,y_i)$. Initially, all circles have a radius of $0$.\n\nThe circles' radii increase at a rate of $1$ unit per second.\n\nYou are currently at $(x_s,y_s)$; your goal is to reach $(x_t,y_t)$ without touching the circumference of any circle (\\textbf{including the moment you reach $(x_t,y_t)$}). You can move in any direction you want. However, your speed is limited to $1$ unit per second.\n\nPlease determine whether this is possible.",
    "tutorial": "The problem can't be that hard, find some simple strategy. We consider a simple strategy: walk towards the goal in a straight line. If some circle reaches the goal first, it is obvious that we have no chance of succeeding, no matter what path we take. Otherwise, it can be proven that we will not pass any circles on our way to the goal. Suppose we start at $A$, our goal is $B$, and we got intercepted by some circle $C$ at the point $D$. It follows that $CD=AD$. According to the triangle inequality, $CD>CB-DB$ should hold. Thus, we have $CB-DB\\le AD$, which means $CB\\le AB$, proof by contradiction. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\nint t, n, x[100011], y[100011], xs, ys, xt, yt;\nll dis(int x1, int y1, int x2, int y2) {\n    return 1ll * (x2 - x1) * (x2 - x1) + 1ll * (y2 - y1) * (y2 - y1);\n}\nint main() {\n    scanf(\"%d\", &t);\n\n    while (t--) {\n        scanf(\"%d\", &n);\n\n        for (int i = 1; i <= n; ++i)\n            scanf(\"%d%d\", x + i, y + i);\n\n        scanf(\"%d%d%d%d\", &xs, &ys, &xt, &yt);\n        bool ok = 1;\n\n        for (int i = 1; i <= n; ++i) {\n            if (dis(xt, yt, x[i], y[i]) <= dis(xt, yt, xs, ys)) {\n                ok = 0;\n                break;\n            }\n        }\n\n        printf(ok ? \"YES\\n\" : \"NO\\n\");\n    }\n\n    fclose(stdin);\n    fclose(stdout);\n    return 0;\n}",
    "tags": [
      "brute force",
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2002",
    "index": "D2",
    "title": "DFS Checker (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, you are given a generic tree and the constraints on $n$ and $q$ are higher. You can make hacks only if both versions of the problem are solved.}\n\nYou are given a rooted tree consisting of $n$ vertices. The vertices are numbered from $1$ to $n$, and the root is the vertex $1$. You are also given a permutation $p_1, p_2, \\ldots, p_n$ of $[1,2,\\ldots,n]$.\n\nYou need to answer $q$ queries. For each query, you are given two integers $x$, $y$; you need to swap $p_x$ and $p_y$ and determine if $p_1, p_2, \\ldots, p_n$ is a valid DFS order$^\\dagger$ of the given tree.\n\nPlease note that the swaps are \\textbf{persistent} through queries.\n\n$^\\dagger$ A DFS order is found by calling the following $dfs$ function on the given tree.\n\n\\begin{verbatim}\ndfs_order = []\n\nfunction dfs(v):\nappend v to the back of dfs_order\npick an arbitrary permutation s of children of v\nfor child in s:\ndfs(child)\ndfs(1)\n\n\\end{verbatim}\n\nNote that the DFS order is not unique.",
    "tutorial": "Try to find some easy checks that can be maintained. The problem revolves around finding a check for dfs orders that's easy to maintain. We have discovered several such checks, a few checks and their proofs are described below, any one of these checks suffices to tell whether a dfs order is valid. For every $u$, all of its children $v$ satisfies $[pos_v,pos_v+siz_v-1]\\subseteq[pos_u,pos_u+siz_u-1]$. We can maintain this check by keeping track of the number of $u$ which violates this condition, and check for each $u$ using sets, when checking, we need only check the child with the minimum $pos_v$ and maximum $pos_v+siz_v-1$. Proof: We prove by induction. When $u$'s children only consists of leaves, it is easy to see that this check ensures $[pos_u,pos_u+siz_u-1]$ is a valid dfs order of the subtree of $u$. Then, we can merge the subtree of $u$ into a large node with size $siz_u$, and continue the analysis above. Check 2: First we check $p_1=1$. Then, for each pair of adjacent elements $p_i,p_{i+1}$, $fa(p_{i+1})$ must be an ancestor of $p_i$, where $fa(u)$ denotes the father of node $u$. We can maintain this check by keeping track of the number of $u$ which violates this condition, and check for each $i$ by checking whether $p_i$ is in the subtree of $fa(p_{i+1})$. Proof: For any subtree $u$, we take any $p_i,p_{i+1}$ such that $p_i$ does not belong in subtree $u$, but $p_{i+1}$ does. It follows that $p_{i+1}=u$, since only the subtree of $fa(u)$ has nodes that does not belong in subtree $u$. From this, we can gather that each subtree will be entered at most once (and form a continuous interval), and that the first visited node will be $u$, which is sufficient to say that $p$ is a dfs order. Time complexity: $O((n+q)\\log n)/O(n+q)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define int long long\nvoid dbg_out() { cerr << endl; }\ntemplate <typename H, typename... T>\nvoid dbg_out(H h, T... t) { cerr << ' ' << h; dbg_out(t...); }\n#define dbg(...) { cerr << #__VA_ARGS__ << ':'; dbg_out(__VA_ARGS__); }\nusing ll = long long;\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n \nconst int MAXN = 3e5 + 5;\nconst int MOD = 1e9+7; //998244353;\nconst int INF = 0x3f3f3f3f;\nconst ll INF64 = ll(4e18) + 5;\n \n \nvector<int> g[MAXN];\n \nint tin[MAXN];\nint tout[MAXN];\nint id[MAXN];\nint par[MAXN];\nint T = 0;\nvoid dfs(int u, int p){\n\tid[u] = tin[u] = tout[u] = T++;\n\tfor(auto v : g[u]) if(v != p){\n\t\tdfs(v,u);\n\t\tpar[v] = u;\n\t\ttout[u] = tout[v];\n\t}\n}\n \nvoid solve(){\n\tint n,q;\n\tcin >> n >> q;\n\tvector<int> p(n+1);\n\tfor(int i = 0; i <= n; i++) g[i].clear();\n\tT = 0;\n\tfor(int i = 2; i <= n; i++){\n\t\tint pi;\n\t\tcin >> pi;\n\t\tg[pi].push_back(i);\n\t}\n\tfor(int i = 1; i <= n; i++){\n\t\tcin >> p[i];\n\t}\n\tdfs(1,1);\n\tint cnt = 0;\n\tauto ok = [&](int i){\n\t\tif(p[i] == 1){\n\t\t\tif(i == 1) return 1;\n\t\t\treturn 0;\n\t\t}\n\t\tint ant = p[i-1];\n\t\tif(par[p[i]] == ant) return 1;\n\t\tif(tin[ant] != tout[ant]) return 0;\n\t\tint pa = par[p[i]];\n\t\tif(tin[ant] < tin[pa] || tin[ant] > tout[pa]) return 0;\n\t\treturn 1;\n\t};\n\tfor(int i = 1; i <= n; i++){\n\t\tcnt += ok(i);\n\t}\n\tfor(int qw = 0; qw < q; qw++){\n\t\tint x,y;\n\t\tcin >> x >> y;\n\t\tset<int> in;\n\t\tin.insert(x);\n\t\tin.insert(y);\n\t\tif(x-1 >= 1) in.insert(x-1);\n\t\tif(x+1 <= n) in.insert(x+1);\n\t\tif(y-1 >= 1) in.insert(y-1);\n\t\tif(y+1 <= n) in.insert(y+1);\n\t\tfor(auto v : in){\n\t\t\tcnt -= ok(v);\n\t\t}\n\t\tswap(p[x],p[y]);\n\t\tfor(auto v : in){\n\t\t\tcnt += ok(v);\n\t\t}\n\t\tcout << (cnt == n ? \"YES\": \"NO\") << '\\n';\n\t}\n\t\n}\n \nsigned main(){\n \n    ios::sync_with_stdio(false); cin.tie(NULL);\n \n    int t = 1;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "graphs",
      "hashing",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2002",
    "index": "E",
    "title": "Cosmic Rays",
    "statement": "Given an array of integers $s_1, s_2, \\ldots, s_l$, every second, cosmic rays will cause all $s_i$ such that $i=1$ or $s_i\\neq s_{i-1}$ to be deleted simultaneously, and the remaining parts will be concatenated together in order to form the new array $s_1, s_2, \\ldots, s_{l'}$.\n\nDefine the \\textbf{strength} of an array as the number of seconds it takes to become empty.\n\nYou are given an array of integers compressed in the form of $n$ pairs that describe the array left to right. Each pair $(a_i,b_i)$ represents $a_i$ copies of $b_i$, i.e. $\\underbrace{b_i,b_i,\\cdots,b_i}_{a_i\\textrm{ times}}$.\n\nFor each $i=1,2,\\dots,n$, please find the \\textbf{strength} of the sequence described by the first $i$ pairs.",
    "tutorial": "Consider an incremental solution. Use stacks. The problems asks for the answer for every prefix, which hints at an incremental solution. To add a new pair to the current prefix, we need to somehow process the new block merging with old ones. Thus, we should use some structure to store the information on the last block over time. Namely, we use a stack to keep track of all blocks that became the last. For each block, we keep two values: its color $c$ and its lifetime $l$ (the times it takes for the block to disappear). When inserting a new block, we pop all blocks that would be shadowed by the current one (i.e. with lifetime shorter than the current block), and merging blocks with the same $a$. When merging two blocks with length $x$ and $z$, and the maximum lifetime of blocks between them is $y$, $y\\le\\min(x,z)$ should hold, and the new block will have lifetime $x+z-y$. For more details, please refer to the solution code. There also exists $O(n\\log n)$ solutions using ordered sets or heaps. Time complexity: $O(n)$.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\n#define N 3000011\n#define pii pair<ll,int>\n#define s1 first\n#define s2 second\nusing namespace std;\nint t, n, prv[N], nxt[N], b[N];\nll a[N];\npriority_queue<pair<ll, int>> pq, del;\nll sum = 0, ans[N];\nint main() {\n    scanf(\"%d\", &t);\n\n    while (t--) {\n        scanf(\"%d\", &n);\n\n        for (int i = 1; i <= n; ++i)\n            scanf(\"%lld%d\", a + i, b + i);\n\n        while (!pq.empty())\n            pq.pop();\n\n        while (!del.empty())\n            del.pop();\n\n        nxt[0] = 1;\n        prv[n + 1] = n;\n\n        for (int i = 1; i <= n; ++i)\n            pq.push({-a[i], i}), prv[i] = i - 1, nxt[i] = i + 1;\n        ll tim = 0;\n        int lst = 1;\n\n        for (int _ = 1; _ <= n; ++_) {\n            while (!del.empty() && pq.top() == del.top())\n                pq.pop(), del.pop();\n\n            pii p = pq.top();\n            pq.pop();\n            int id = p.s2;\n            tim = -p.s1;\n\n            if (nxt[id] <= n && b[id] == b[nxt[id]]) {\n                a[nxt[id]] += tim;\n                pq.push({-a[nxt[id]], nxt[id]});\n            }\n\n            if (prv[id] && nxt[id] <= n && b[prv[id]] == b[nxt[id]]) {\n                del.push({-a[nxt[id]], nxt[id]});\n                a[nxt[id]] -= tim;\n            }\n\n            prv[nxt[id]] = prv[id];\n            nxt[prv[id]] = nxt[id];\n\n            while (lst < nxt[0])\n                ans[lst++] = tim;\n        }\n\n        for (int i = 1; i <= n; ++i)\n            printf(\"%lld \", ans[i]);\n\n        putchar(10);\n    }\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2002",
    "index": "F1",
    "title": "Court Blue (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. In this version, $n=m$ and the time limit is lower. You can make hacks only if both versions of the problem are solved.}\n\nIn the court of the Blue King, Lelle and Flamm are having a performance match. The match consists of several rounds. In each round, either Lelle or Flamm wins.\n\nLet $W_L$ and $W_F$ denote the number of wins of Lelle and Flamm, respectively. The Blue King considers a match to be \\textbf{successful} if and only if:\n\n- after every round, $\\gcd(W_L,W_F)\\le 1$;\n- at the end of the match, $W_L\\le n, W_F\\le m$.\n\nNote that $\\gcd(0,x)=\\gcd(x,0)=x$ for every non-negative integer $x$.\n\nLelle and Flamm can decide to stop the match whenever they want, and the final score of the performance is $l \\cdot W_L + f \\cdot W_F$.\n\nPlease help Lelle and Flamm coordinate their wins and losses such that the performance is \\textbf{successful}, and the total score of the performance is maximized.",
    "tutorial": "Primes are powerful. Prime gaps are small. We view the problem as a walk on grid, starting at $(1,1)$. WLOG, we suppose $l>f$, thus only cells $(a,b)$ where $a<b$ would be considered. Notice that when $n$ is large enough, the largest prime $p\\le n$ satisfies $2p>n$. As such, all cells $(p,i)$ where $i<p$ will be unblocked and reachable. However, we've only bounded one side of the final result. We take this a step further, let $q$ be the second-largest prime $q\\le n$. By the same logic, we assume that $2q>n$. As such, all cells $(i,q)$, where $p\\le i\\le n$ will be unblocked and reachable. Thus, we have constructed an area where the optimal solution must be, with its dimensions bounded by $n-p$ and $n-q$. We just need to run any brute force solution (dfs with memorization or dp) on this area to find the result. If we assume the asymptotic of prime gap is $O(P(n))$, this yields a $O(n\\cdot P(n)^2\\cdot\\log P(n))$ solution, where the $\\log\\log n$ is from taking the gcd of two numbers which differ by $O(P(n))$. This can also be optimized to $O(n\\cdot P(n)^2)$ by preprocessing gcd. We added the constraints that $n$'s are pairwise distinct to avoid forcing participants to write memorizations. In fact, under the constraints of the problem, the maximum area is $39201$, and the sum of the $10^3$ largest areas is $2.36\\times10^7$. Time complexity: $O(P(n)^2\\log P(n))/O(P(n)^2)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nconst int N = 2e7 + 5;\nbool ntp[N];\nint di[405][405];\nbool bad[405][405];\nint pos[N], g = 0, m = 3;\nint prime[2000005], cnt = 0;\nvoid sieve(int n) {\n    int i, j;\n\n    for (i = 2; i <= n; i++) {\n        if (!ntp[i])\n            prime[++cnt] = i;\n\n        for (j = 1; j <= cnt && i * prime[j] <= n; j++) {\n            ntp[i * prime[j]] = 1;\n\n            if (!(i % prime[j]))\n                break;\n        }\n    }\n}\nint gcd(int x, int y) {\n    if (!x)\n        return y;\n\n    if (x <= g && y <= g)\n        return di[x][y];\n\n    return gcd(y % x, x);\n}\n\nint main() {\n    sieve(2e7);\n    int i, j = 1, T, n, a, b, c, u, v;\n    ll ans;\n\n    for (i = 3; i <= 2e7; i++) {\n        while (j < cnt - 1 && prime[j + 2] <= i)\n            j++;\n\n        g = max(g, i - prime[j] + 1);\n\n        if (prime[j] * 2 <= i)\n            m = i;\n\n        pos[i] = j;\n    }\n\n    for (i = 0; i <= g; i++)\n        for (j = 0; j <= g; j++)\n            if (!i)\n                di[i][j] = j;\n            else\n                di[i][j] = di[j % i][i];\n\n    scanf(\"%d\", &T);\n\n    while (T--) {\n        scanf(\"%*d%d%d%d\", &n, &a, &b);\n\n        if (n <= m)\n            u = v = 1;\n        else {\n            u = prime[pos[n] + 1];\n            v = prime[pos[n]];\n        }\n\n        ans = 0;\n\n        for (i = u; i <= n; i++)\n            for (j = v; j <= i; j++) {\n                bad[i - u + 1][j - v + 1] = (gcd(i, j) > 1 || (bad[i - u][j - v + 1] && bad[i - u + 1][j - v]));\n\n                if (!bad[i - u + 1][j - v + 1])\n                    ans = max(ans, max((ll)a * i + (ll)b * j, (ll)a * j + (ll)b * i));\n            }\n\n        printf(\"%lld\\n\", ans);\n    }\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2002",
    "index": "F2",
    "title": "Court Blue (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, it is not guaranteed that $n=m$, and the time limit is higher. You can make hacks only if both versions of the problem are solved.}\n\nIn the court of the Blue King, Lelle and Flamm are having a performance match. The match consists of several rounds. In each round, either Lelle or Flamm wins.\n\nLet $W_L$ and $W_F$ denote the number of wins of Lelle and Flamm, respectively. The Blue King considers a match to be \\textbf{successful} if and only if:\n\n- after every round, $\\gcd(W_L,W_F)\\le 1$;\n- at the end of the match, $W_L\\le n, W_F\\le m$.\n\nNote that $\\gcd(0,x)=\\gcd(x,0)=x$ for every non-negative integer $x$.\n\nLelle and Flamm can decide to stop the match whenever they want, and the final score of the performance is $l \\cdot W_L + f \\cdot W_F$.\n\nPlease help Lelle and Flamm coordinate their wins and losses such that the performance is \\textbf{successful}, and the total score of the performance is maximized.",
    "tutorial": "Try generalizing the solution of F1. Write anything and pray that it will pass because of number theory magic. We generalize the solution in F1. Let $p$ be the largest prime $\\le m$ and $q$ be the largest prime $\\le\\min(n,p-1)$. The problem is that there might be $\\gcd(q,i)\\neq1$ for some $p+1\\le i\\le m$, thus invalidating our previous analysis. To solve this, we simply choose $q$ to be the largest integer such that $q\\le n$ and $\\gcd(q,i)=1$ for all $p+1\\le i\\le m$. An asymptotic analysis of this solution is as follows: As the length of $[p+1,m]$ is $O(P(m))$, and each of these integers have at most $O(\\log_nm)$ prime divisors of $O(m)$ magnitude, which means that if we only restrict $q$ to primes, we will have to skip at most $O(P(n)\\log_nm)$ primes to find the largest $q$. As the density of primes is $O(\\frac1{P(n)})$, the asymptotic of $n-q$ will be $O(P(m)\\log_nm\\cdot P(n))=O(P(m)^2)$, our actual $q$ (which is not restricted to primes) will not be worse than this. Thus, our total area will be $O(P(m)^3)$, times the gcd complexity gives us an $O(P(m)^3\\log m)$ solution. However, the actual area is much lower than this. Under the constraints of the problem, when forcing $p,q$ to take primes, the maximum area is $39960$, and the sum of the $10^3$ largest areas is $3.44\\times10^7$. The actual solution will not be worse than this. Because we only need to check whether $\\gcd(x,y)=1$, the complexity can actually be optimized to $O(P(m)^3)$ with some sieves. Namely, iterating over prime divisors $d$ of $[p,m]$ and $[q,n]$ and marking all cells which has $d$ as its common divisor. This solution is by far from optimal. We invite you to continue optimizing your solutions and try to minimize the number of cells visited in each query :) Time complexity: $O(P(m)^3\\log m)$ Keep $p$ the same, set $q$ to $p-L$ and only keep reachable cells in $[p,n]\\times [q,m]$. $L$ is some constant ($100$ should work). We found this solution during testing, tried, and failed to hack it. Keep $p$ the same, do dfs from each cell $(n,p),(n-1,p),\\cdots$, prioritizing increasing $W_L$ over increasing $W_F$, and stop the process the first time you reach any cell $(x,m)$, take the maximum of all cells visited. This should not be worse than the intended solution, and actually runs quite fast. Simply take all cells in $[n-L,n]\\times [m-L,m]$ and mark everything outside as reachable. $L=50$ works. We found this solution the day before the round, we don't know how to hack it either. UPD: $L=50$ was hacked. Hats off to the hacker. Do dfs with pruning. Run dfs starting at $(n,m)$, return when the cell is $(p,i)$ (i.e. obviously reachable because of primes), or when the value of the cell is smaller than the current answer. Add some memorization and it passes.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\n#define N 20000011\nusing namespace std;\nint t, n, m, a, b;\nbool is[N];\nint pr[N / 10];\nint gcd(int a, int b) {\n    while (b)\n        a %= b, swap(a, b);\n\n    return a;\n}\nll ans = 0;\nbool vis[1011][1011];\npair<int, int> vv[200011];\nint vn, c;\nbool flg = 0;\ninline ll V(int i, int j) {\n    return i <= n ? 1ll * max(i, j) * max(a, b) + 1ll * min(i, j) * min(a, b) : 1ll * i * b + 1ll * j * a;\n}\nvoid dfs(int i, int j) {\n    ++c;\n    bool mk = gcd(i, j) == 1;\n\n    if (!mk)\n        return;\n\n    ans = max(ans, V(i, j));\n    vis[m - i][n - j] = 1;\n    vv[++vn] = {i, j};\n\n    if (j < n && !vis[m - i][n - j - 1])\n        dfs(i, j + 1);\n\n    if (i == m || flg) {\n        flg = 1;\n        return;\n    }\n\n    if (i < m && !vis[m - i - 1][n - j])\n        dfs(i + 1, j);\n}\nint main() {\n    is[0] = is[1] = 1;\n\n    for (int i = 2; i < N; ++i) {\n        if (!is[i])\n            pr[++pr[0]] = i;\n\n        for (int j = 1; j <= pr[0] && i * pr[j] < N; ++j) {\n            is[i * pr[j]] = 1;\n\n            if (i % pr[j] == 0)\n                break;\n        }\n    }\n\n    scanf(\"%d\", &t);\n\n    while (t--) {\n        scanf(\"%d%d%d%d\", &n, &m, &a, &b);\n        int p;\n\n        if (m <= 10)\n            p = 1;\n        else {\n            p = m;\n\n            while (is[p])\n                --p;\n        }\n\n        vn = 0;\n        ans = 0;\n        flg = 0;\n        c = 0;\n\n        for (int i = min(n, p - (p > 1));; --i) {\n            assert(i > 0);\n            ans = max(ans, V(p, i));\n\n            if (p < m)\n                dfs(p + 1, i);\n            else\n                break;\n\n            if (flg)\n                break;\n        }\n\n        for (int i = 1; i <= vn; ++i)\n            vis[m - vv[i].first][n - vv[i].second] = 0;\n\n        printf(\"%lld\\n\", ans);\n    }\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2002",
    "index": "G",
    "title": "Lattice Optimizing",
    "statement": "Consider a grid graph with $n$ rows and $n$ columns. Let the cell in row $x$ and column $y$ be $(x,y)$. There exists a directed edge from $(x,y)$ to $(x+1,y)$, with non-negative integer value $d_{x,y}$, for all $1\\le x < n, 1\\le y \\le n$, and there also exists a directed edge from $(x,y)$ to $(x,y+1)$, with non-negative integer value $r_{x,y}$, for all $1\\le x \\le n, 1\\le y < n$.\n\nInitially, you are at $(1,1)$, with an empty set $S$. You need to walk along the edges and eventually reach $(n,n)$. Whenever you pass an edge, its value will be inserted into $S$. Please maximize the MEX$^{\\text{∗}}$ of $S$ when you reach $(n,n)$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:\n\n- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.\n- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.\n- The MEX of $[0,3,1,2]$ is $4$, because $0, 1, 2$, and $3$ belong to the array, but $4$ does not.\n\n\\end{footnotesize}",
    "tutorial": "We apologize for unintended solutions passing, and intended solutions failing with large constants. Brute force runs very fast on $n=18$, which forced us to increase constraints. Meet in the middle with a twist. Union of sets is hard. Disjoint union of sets is easy. The problem hints strongly at meet in the middle, at each side, there will be $O(2^n)$ paths. The twist is on merging: we are given two sequence of sets $S_1,S_2,\\cdots$ and $T_1,T_2,\\cdots$, we have to find the maximum $\\textrm{MEX}(S_i\\cup T_j)$. If we enumerate over the maximum MEX $P$, we only need to check whether there exists two sets such that $\\{ 0,1,\\cdots,P-1\\} \\subseteq S_i\\cup T_j$. Instead of meeting at $n$, we perform meet in the middle at the partition of $Bn$ and $(2-B)n$. For each $S_i$, we put all its subsets $S^\\prime_i$ into a hashmap. When checking MEX $P$, we iterate over all $T_j$, and check whether $\\{ 0,1,\\cdots,P-1\\} -T_j$ is in the hashmap. This gives us a $O((2^{2Bn}+2^{(2-B)n})\\cdot n)$ solution, which is optimal at $B=\\frac23$, where the complexity is $O(2^{\\frac43}\\cdot n)$. We can substitute enumerating $P$ with binary search, yielding $O(2^{\\frac43n}\\cdot\\log n)$, or checking whether $P$ can be increased each time, yielding $O(2^{\\frac43n})$. Instead of hashmaps, you can also insert all $S$ and $T$'s into a trie, and run a brute force dfs to search for MEX $P$. It can be proven that the complexity is also $O(2^{\\frac43n}\\cdot n)$. The intended solution is $O(2^{\\frac43 n})$, however solutions that have slightly higher complexity can pass with good optimizations. Time complexity: $O(2^{\\frac43n})$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define pb push_back\n#define mp make_pair\n#define fi first\n#define se second\n#define int long long\nvoid dbg_out() {\n    cerr << endl;\n}\ntemplate <typename H, typename... T>\nvoid dbg_out(H h, T... t) {\n    cerr << ' ' << h;\n    dbg_out(t...);\n}\n#define dbg(...) { cerr << #__VA_ARGS__ << ':'; dbg_out(__VA_ARGS__); }\nusing ll = long long;\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nconst int MAXN = 3e7 + 5;\nconst int MOD = 1e9 + 7; //998244353;\nconst int INF = 0x3f3f3f3f;\nconst ll INF64 = ll(4e18) + 5;\n\nint D[40][40];\nint R[40][40];\n\nint L;\n\nint32_t trie[MAXN][2];\nint n;\nint li = 1;\nvoid add(int x) {\n    int at = 0;\n    int K = 2 * n - 2;\n\n    for (int i = 0; i <= K; i++) {\n        int id = (x >> i) & 1;\n\n        if (trie[at][id] == 0) {\n            trie[at][id] = li++;\n        }\n\n        at = trie[at][id];\n    }\n}\n\nvoid limpa() {\n    for (int i = 0; i < li; i++) {\n        trie[i][0] = trie[i][1] = 0;\n    }\n\n    li = 1;\n}\n\nint query(int at, int x, int dep) {\n    int id = (x >> dep) & 1;\n\n    if (id == 0) {\n        if (trie[at][1]) {\n            return query(trie[at][1], x, dep + 1);\n        }\n\n        return dep;\n    }\n\n    int ans = dep;\n\n    if (trie[at][0])\n        ans = max(ans, query(trie[at][0], x, dep + 1));\n\n    if (trie[at][1])\n        ans = max(ans, query(trie[at][1], x, dep + 1));\n\n    while ((x >> ans) & 1)\n        ans++;\n\n    return ans;\n}\n\nvoid rec_in(int i, int j, int tar1, int tar2, int v) {\n    if (i > tar1 || j > tar2)\n        return;\n\n    if (i == tar1 && j == tar2) {\n        add(v);\n    }\n\n    int right = v | (1ll << R[i][j]);\n    int down = v | (1ll << D[i][j]);\n    rec_in(i + 1, j, tar1, tar2, down);\n    rec_in(i, j + 1, tar1, tar2, right);\n}\n\nint ANS = 0;\nvoid rec_out(int i, int j, int tar1, int tar2, int v) {\n    if (i < tar1 || j < tar2)\n        return;\n\n    if (i == tar1 && j == tar2) {\n        ANS = max(ANS, query(0, v, 0));\n        return;\n    }\n\n    int left = v | (1ll << R[i][j - 1]);\n    int up = v | (1ll << D[i - 1][j]);\n    rec_out(i - 1, j, tar1, tar2, up);\n    rec_out(i, j - 1, tar1, tar2, left);\n}\n\nvoid solve() {\n    ANS = 0;\n\n    for (int i = 1; i <= li; i++)\n        trie[i][0] = trie[i][1] = 0;\n\n    li = 1;\n    cin >> n;\n    L = 4 * n / 3;\n\n    for (int i = 0; i < n - 1; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> D[i][j];\n        }\n    }\n\n    if (L > n) {\n        L--;\n    }\n\n    if (L > n) {\n        L--;\n    }\n\n    if (L > n) {\n        L--;\n    }\n\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n - 1; j++) {\n            cin >> R[i][j];\n        }\n    }\n\n    for (int i = 0; i < n; i++)\n        for (int j = 0; j < n; j++)\n            if (i + j == L) {\n                limpa();\n                rec_in(0, 0, i, j, 0);\n                rec_out(n - 1, n - 1, i, j, 0);\n            }\n\n    cout << ANS << '\\n';\n\n}\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int t = 1;\n    cin >> t;\n\n    while (t--) {\n        solve();\n    }\n\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "hashing",
      "meet-in-the-middle"
    ],
    "rating": 3400
  },
  {
    "contest_id": "2002",
    "index": "H",
    "title": "Counting 101",
    "statement": "It's been a long summer's day, with the constant chirping of cicadas and the heat which never seemed to end. Finally, it has drawn to a close. The showdown has passed, the gates are open, and only a gentle breeze is left behind.\n\nYour predecessors had taken their final bow; it's your turn to take the stage.\n\nSorting through some notes that were left behind, you found a curious statement named \\textbf{Problem 101}:\n\n- Given a positive integer sequence $a_1,a_2,\\ldots,a_n$, you can operate on it any number of times. In an operation, you choose three consecutive elements $a_i,a_{i+1},a_{i+2}$, and merge them into one element $\\max(a_i+1,a_{i+1},a_{i+2}+1)$. Please calculate the maximum number of operations you can do without creating an element greater than $m$.\n\nAfter some thought, you decided to propose the following problem, named \\textbf{Counting 101}:\n\n- Given $n$ and $m$. For each $k=0,1,\\ldots,\\left\\lfloor\\frac{n-1}{2}\\right\\rfloor$, please find the number of integer sequences $a_1,a_2,\\ldots,a_n$ with elements in $[1, m]$, such that when used as input for \\textbf{Problem 101}, the answer is $k$. As the answer can be very large, please print it modulo $10^9+7$.",
    "tutorial": "Try to solve Problem 101 with any approach. Can you express the states in the solution for Problem 101 with some simple structures? Maybe dp of dp? Try finding some unnecessary states and pruning them, to knock a $n$ off the complexity. We analyse Problem 101 first. A dp solution will be, let $f_{l,r,v}$ be the minimum number of elements left after some operations, if we only consider elements in $a[l:r]$, without creating any elements $>v$. If $\\max(a[l:r])<v$, then the answer is $1$ if $r-l+1$ is odd, and $2$ otherwise. We simply repeatedly perform operations with middle element as the center. It is easy to see that this is optimal. If $\\max(a[l:r])=v$, then $a[l:r]$ will be partitioned into blocks by elements equal to $v$. Denote the length of the blocks as $y_1,y_2,\\cdots,y_l$. Let $b_i$ be the number of operations that has the $i$-th element with value $v$ as its center. We can perform a dp as follows: let $g_{i,j}$ be the minimum number of elements left if we have already considered the first $i$ blocks, and $b_i=j$. When adding a new block, we need to know several things: $[l^\\prime,r^\\prime]$, the minimum/maximum number of elements of the new block after some operations, without creating an element greater than $v-1$. $[l^\\prime,r^\\prime]$, the minimum/maximum number of elements of the new block after some operations, without creating an element greater than $v-1$. $j_2$, the value of $b_{i+1}$. $j_2$, the value of $b_{i+1}$. The transition of the dp will be: $g_{i+1,j_2}=g_{i,j_1}+cost(j_1+j_2,l^\\prime,r^\\prime)$, where $cost(j,l,r)$ is defined as follows: $cost(j,l,r)=\\left\\{ \\begin{aligned} +\\infty,&&j>r\\\\ 0,&&l\\le j\\le r, j\\equiv l\\pmod2\\\\ 1,&&j\\le r,j\\not\\equiv l\\pmod2\\\\ 2,&&j<l, j\\equiv l\\pmod2\\\\ \\end{aligned} \\right.$ The $cost$ function follows from the case where $\\max(a)<v$. Now, we have a solution to Problem 101. We now consider generalizing it to Counting 101. We make some observations regarding the structure of $g$. If you printed a table of $g$, you would discover that for each $g_i$, if you subtract the minimum element from all $g_{i,j}$ in this row, you will get something like: $[\\cdots,2,1,2,1,2,1,0,1,0,1,0,1,0,1,2,1,2,\\cdots]$. We can prove this by induction and some casework, which is omitted for brevity. If a $g_i$ satisfies this property, then we can express it with a triple $(l,r,mn)$, where $mn$ is the minimum element of $g_i$, and $l,r$ are the minimum/maximum $j$ such that $g_{i,j}=mn$. Now that we can express the structure of each $g_i$ with a triple $(l,r,mn)$, we can run a dp of dp. Our state will be $dp_{i,v,l,r,mn}$, where $i$ is the current length, $v$ is the upper bound, and $(l,r,mn)$ describes the current $g$. For each transition, we need to enumerate $l^\\prime,r^\\prime$, and the new $(l,r,mn)$ can be found in $O(1)$ with some casework. This gives us an $O(n^6m)$ solution. Now to optimize the solution. We optimize the solution by reducing the number of viable states. Suppose we have a state $+(l,r,mn)$, we claim, that the answer will remain the same if we replace it with $+(l,\\infty,mn)+(l\\bmod2,r,mn)-(l\\bmod2,\\infty,mn)$. We prove this by examining their behaviour when we add any number of blocks after them. If the answer remains unchanged for any blocks we can add, then the claim stands. Suppose we are at $g_i$, and we will add a sequence of blocks $S$ after $g_i$. The final answer can be found by running a backwards dp similar to $g$, on $\\text{rev}(S)$, and merging with $g_i$ in the middle. If we denote the backwards dp as $g^\\prime$, then the answer will be $\\min(g_j+g^\\prime_j)$ over all $j$. It can be shown after some brief casework (using $g$'s structure), that there exists an optimal $j$ where $g_{i,j}$ is the minimum of $g_i$, thus the answer is just a range (with a certain parity) min of $g^\\prime$, plus $mn$. Because $g^\\prime$ also follow $g$'s structure, any range will be first decreasing, then increasing. It can be shown with these properties, $\\min(g^\\prime[l:r])=\\min(g^\\prime[l:\\infty])+\\min(g^\\prime[l\\bmod2:r])-\\min(g^\\prime[l\\bmod2:\\infty])$. Thus, our answer will not change when substituting the states. After substituting, the total number of different $l,r$ pairs will be $O(n)$, which yields an $O(n^5m)$ solution. The solution can also be optimized to $O(n^4m)$ using Lagrange Interpolation, but it actually runs slower than $O(n^5m)$ because of large constants (or bad implementation by setters).",
    "code": "#include <bits/stdc++.h>\n#pragma comment(linker, \"/stack:200000000\")\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC target(\"sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native\")\n#define L(i, j, k) for(int i = (j); i <= (k); ++i)\n#define R(i, j, k) for(int i = (j); i >= (k); --i)\n#define ll long long\n#define vi vector <int>\n#define sz(a) ((int) (a).size())\n#define me(f, x) memset(f, x, sizeof(f))\n#define ull unsigned long long\n#define pb emplace_back\nusing namespace std;\nconst int N = 133, mod = 1e9 + 7;\nstruct mint {\n    int x;\n    inline mint(int o = 0) {\n        x = o;\n    }\n    inline mint &operator = (int o) {\n        return x = o, *this;\n    }\n    inline mint &operator += (mint o) {\n        return (x += o.x) >= mod && (x -= mod), *this;\n    }\n    inline mint &operator -= (mint o) {\n        return (x -= o.x) < 0 && (x += mod), *this;\n    }\n    inline mint &operator *= (mint o) {\n        return x = (ll) x * o.x % mod, *this;\n    }\n    inline mint &operator ^= (int b) {\n        mint w = *this;\n        mint ret(1);\n\n        for (; b; b >>= 1, w *= w)\n            if (b & 1)\n                ret *= w;\n\n        return x = ret.x, *this;\n    }\n    inline mint &operator /= (mint o) {\n        return *this *= (o ^= (mod - 2));\n    }\n    friend inline mint operator + (mint a, mint b) {\n        return a += b;\n    }\n    friend inline mint operator - (mint a, mint b) {\n        return a -= b;\n    }\n    friend inline mint operator * (mint a, mint b) {\n        return a *= b;\n    }\n    friend inline mint operator / (mint a, mint b) {\n        return a /= b;\n    }\n    friend inline mint operator ^ (mint a, int b) {\n        return a ^= b;\n    }\n};\ninline mint qpow(mint x, int y = mod - 2) {\n    return x ^ y;\n}\nmint fac[N], ifac[N], inv[N];\nvoid init(int x) {\n    fac[0] = ifac[0] = inv[1] = 1;\n    L(i, 2, x) inv[i] = (mod - mod / i) * inv[mod % i];\n    L(i, 1, x) fac[i] = fac[i - 1] * i, ifac[i] = ifac[i - 1] * inv[i];\n}\nmint C(int x, int y) {\n    return x < y || y < 0 ? 0 : fac[x] * ifac[y] * ifac[x - y];\n}\ninline mint sgn(int x) {\n    return (x & 1) ? mod - 1 : 1;\n}\n\nint n, m;\nmint f[N][N];\nmint g[N][N];\nmint h1[N][N][N];\nmint h2[N][N][N];\nmint pw[N][N];\nint ans[N][N][N];\nint main() {\n    ios :: sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    n = 130, m = 30;\n    // n = m = 10;\n    L(i, 0, max(n, m)) {\n        pw[i][0] = 1;\n        L(j, 1, max(n, m)) pw[i][j] = pw[i][j - 1] * i;\n    }\n    f[0][0] = 1;\n    int c1 = 0, c2 = 0;\n    L(test, 1, m) {\n        me(g, 0);\n        int up = n;\n        L(i, 0, up + 1) L(j, 0, i) L(l, 0, i) h1[i][j][l] = h2[i][j][l] = 0;\n        h2[0][0][0] = 1;\n        L(i, 0, up + 1) {\n            L(j, 0, i) L(l, 0, i) h1[i][j][l & 1] -= h1[i][j][l];\n            L(j, 0, i) {\n                for (int l = (i - j) & 1; l <= i; l += 2)\n                    if (h1[i][j][l].x) {\n                        L(k, 0, up - i) {\n                            if (l > k) {\n                                int tr = k - !(l & 1);\n\n                                if (tr < 0)\n                                    h2[i + k + 1][j + 3][0] += h1[i][j][l] * pw[test - 1][k];\n                                else\n                                    h2[i + k + 1][j + 2][tr] += h1[i][j][l] * pw[test - 1][k];\n                            } else {\n                                h2[i + k + 1][j + 1][k - l] += h1[i][j][l] * pw[test - 1][k];\n                            }\n                        }\n                    }\n\n                for (int r = (i - j) & 1; r <= i; r += 2)\n                    if (h2[i][j][r].x) {\n                        int l = r & 1;\n                        L(k, 0, up - i) {\n                            if (l > k) {\n                                int tr = k - !(r & 1);\n\n                                if (tr < 0)\n                                    h2[i + k + 1][j + 3][0] += h2[i][j][r] * pw[test - 1][k];\n                                else\n                                    h2[i + k + 1][j + 2][tr] += h2[i][j][r] * pw[test - 1][k];\n                            } else {\n                                h2[i + k + 1][j + 1][k - l] += h2[i][j][r] * pw[test - 1][k];\n\n                                L(d, r + 1, k) if (f[k][d].x)\n                                    h1[i + k + 1][j + 1][d - r] += h2[i][j][r] * f[k][d];\n                            }\n                        }\n                    }\n            }\n        }\n        // cout << \"H = \" << h[1][1][0][0].x << endl;\n        L(i, 1, up + 1)\n        L(j, 1, i) {\n\n            L(l, 0, i) if (h1[i][j][l].x) {\n                if (!l)\n                    g[i - 1][j - 1] += h1[i][j][l];\n                else\n                    g[i - 1][j - 1 + (l % 2 == 0 ? 2 : 1)] += h1[i][j][l];\n            }\n\n            L(r, 0, i) if (h2[i][j][r].x) {\n                if (!(r & 1))\n                    g[i - 1][j - 1] += h2[i][j][r];\n                else\n                    g[i - 1][j - 1 + (r % 2 == 0 ? 2 : 1)] += h2[i][j][r];\n            }\n        }\n        L(i, 1, up) {\n            mint vl = 0;\n\n            if (i == 1)\n                vl = test;\n            else if (i % 2 == 1) {\n                vl += pw[test - 1][i];\n                L(p, 1, i - 2) {\n                    int l = p, r = i - p - 1;\n\n                    if (l > r)\n                        swap(l, r);\n\n                    L(j, 1, l) {\n                        vl += f[r][j] * pw[test - 1][l];\n                    }\n                }\n            }\n\n            g[i][1] = vl;\n            mint sum = 0;\n            L(j, 1, i) sum += g[i][j];\n            int pos = (i & 1) ? 3 : 2;\n            g[i][pos] += pw[test][i] - sum;\n        }\n        swap(f, g);\n\n        for (int i = 0; i <= n; i++) {\n            for (int j = 0; j <= n; j++) {\n                ans[test][i][j] = f[i][j].x;\n            }\n        }\n    }\n    // cout << \"clock = \" << clock() << endl;\n    int T;\n    cin >> T;\n\n    while (T--) {\n        int N, M;\n        cin >> N >> M;\n        L(i, 0, (N - 1) / 2)\n        cout << ans[M][N][N - i * 2] << \" \";\n        cout << '\\n';\n    }\n\n    return 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2003",
    "index": "A",
    "title": "Turtle and Good Strings",
    "statement": "Turtle thinks a string $s$ is a good string if there exists a sequence of strings $t_1, t_2, \\ldots, t_k$ ($k$ is an arbitrary integer) such that:\n\n- $k \\ge 2$.\n- $s = t_1 + t_2 + \\ldots + t_k$, where $+$ represents the concatenation operation. For example, $abc = a + bc$.\n- For all $1 \\le i < j \\le k$, the first character of $t_i$ \\textbf{isn't equal to} the last character of $t_j$.\n\nTurtle is given a string $s$ consisting of lowercase Latin letters. Please tell him whether the string $s$ is a good string!",
    "tutorial": "A necessary condition for $s$ to be good is that $s_1 \\ne s_n$. For a string $s$ where $s_1 \\ne s_n$, let $t_1$ be a string composed of just the single character $s_1$, and let $t_2$ be a string composed of the $n - 1$ characters from $s_2$ to $s_n$. In this way, the condition is satisfied. Therefore, if $s_1 \\ne s_n$, the answer is \"Yes\"; otherwise, the answer is \"No\". Time complexity: $O(n)$ per test case.",
    "code": "#include <cstdio>\n\nconst int maxn = 110;\n\nint n;\nchar s[maxn];\n\nvoid solve() {\n\tscanf(\"%d%s\", &n, s + 1);\n\tputs(s[1] != s[n] ? \"Yes\" : \"No\");\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2003",
    "index": "B",
    "title": "Turtle and Piggy Are Playing a Game 2",
    "statement": "Turtle and Piggy are playing a game on a sequence. They are given a sequence $a_1, a_2, \\ldots, a_n$, and Turtle goes first. Turtle and Piggy alternate in turns (so, Turtle does the first turn, Piggy does the second, Turtle does the third, etc.).\n\nThe game goes as follows:\n\n- Let the current length of the sequence be $m$. If $m = 1$, the game ends.\n- If the game does not end and it's Turtle's turn, then Turtle must choose an integer $i$ such that $1 \\le i \\le m - 1$, set $a_i$ to $\\max(a_i, a_{i + 1})$, and remove $a_{i + 1}$.\n- If the game does not end and it's Piggy's turn, then Piggy must choose an integer $i$ such that $1 \\le i \\le m - 1$, set $a_i$ to $\\min(a_i, a_{i + 1})$, and remove $a_{i + 1}$.\n\nTurtle wants to \\textbf{maximize} the value of $a_1$ in the end, while Piggy wants to \\textbf{minimize} the value of $a_1$ in the end. Find the value of $a_1$ in the end if both players play optimally.\n\nYou can refer to notes for further clarification.",
    "tutorial": "The problem can be rephrased as follows: the first player can remove a number adjacent to a larger number, while the second player can remove a number adjacent to a smaller number. To maximize the value of the last remaining number, in the $i$-th round of the first player's moves, he will remove the $i$-th smallest number in the sequence, and this is always achievable. Similarly, in the $i$-th round of the second player's moves, he will remove the $i$-th largest number. Thus, the answer is the $\\left\\lfloor\\frac{n}{2}\\right\\rfloor + 1$-th smallest number in the original sequence. Time complexity: $O(n \\log n)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int maxn = 100100;\n\nint n, a[maxn];\n\nvoid solve() {\n\tscanf(\"%d\", &n);\n\tfor (int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &a[i]);\n\t}\n\tsort(a + 1, a + n + 1, greater<int>());\n\tprintf(\"%d\\n\", a[(n + 1) / 2]);\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2003",
    "index": "C",
    "title": "Turtle and Good Pairs",
    "statement": "Turtle gives you a string $s$, consisting of lowercase Latin letters.\n\nTurtle considers a pair of integers $(i, j)$ ($1 \\le i < j \\le n$) to be a pleasant pair if and only if there exists an integer $k$ such that $i \\le k < j$ and \\textbf{both} of the following two conditions hold:\n\n- $s_k \\ne s_{k + 1}$;\n- $s_k \\ne s_i$ \\textbf{or} $s_{k + 1} \\ne s_j$.\n\nBesides, Turtle considers a pair of integers $(i, j)$ ($1 \\le i < j \\le n$) to be a good pair if and only if $s_i = s_j$ \\textbf{or} $(i, j)$ is a pleasant pair.\n\nTurtle wants to reorder the string $s$ so that the number of good pairs is \\textbf{maximized}. Please help him!",
    "tutorial": "Partition the string $s$ into several maximal contiguous segments of identical characters, denoted as $[l_1, r_1], [l_2, r_2], \\ldots, [l_m, r_m]$. For example, the string \"aabccc\" can be divided into $[1, 2], [3, 3], [4, 6]$. We can observe that a pair $(i, j)$ is considered a \"good pair\" if and only if the segments containing $i$ and $j$ are non-adjacent. Let $a_i = r_i - l_i + 1$. Then, the number of good pairs is $\\frac{n(n - 1)}{2} - \\sum\\limits_{i = 1}^{m - 1} a_i \\cdot a_{i + 1}$. Hence, the task reduces to minimizing $\\sum\\limits_{i = 1}^{m - 1} a_i \\cdot a_{i + 1}$. If $s$ consists of only one character, simply output the original string. Otherwise, for $m \\ge 2$, it can be inductively proven that $\\sum\\limits_{i = 1}^{m - 1} a_i \\cdot a_{i + 1} \\ge n - 1$, and this minimum value of $n - 1$ can be achieved. As for the construction, let the maximum frequency of any character be $x$, and the second-highest frequency be $y$. Begin by placing $x - y$ instances of the most frequent character at the start. Then, there are $y$ remaining instances of both the most frequent and the second most frequent characters. Next, sort all characters by frequency in descending order and alternate between them when filling the positions (ignoring any character once it's fully used). This guarantees that, except for the initial segment of length $\\ge 1$, all other segments have a length of exactly $1$. Time complexity: $O(n + |\\Sigma| \\log |\\Sigma|)$ per test case, where $|\\Sigma| = 26$.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<int, int> pii;\n\nconst int maxn = 1000100;\n\nint n;\npii a[99];\nchar s[maxn];\n\nvoid solve() {\n\tscanf(\"%d%s\", &n, s + 1);\n\tfor (int i = 0; i < 26; ++i) {\n\t\ta[i] = mkp(0, i);\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\t++a[s[i] - 'a'].fst;\n\t}\n\tsort(a, a + 26, greater<pii>());\n\tqueue<pii> q;\n\twhile (a[0].fst > a[1].fst) {\n\t\tputchar('a' + a[0].scd);\n\t\t--a[0].fst;\n\t}\n\tfor (int i = 0; i < 26; ++i) {\n\t\tq.push(a[i]);\n\t}\n\twhile (q.size()) {\n\t\tpii p = q.front();\n\t\tq.pop();\n\t\tif (!p.fst) {\n\t\t\tcontinue;\n\t\t}\n\t\tputchar('a' + p.scd);\n\t\t--p.fst;\n\t\tq.push(p);\n\t}\n\tputchar('\\n');\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2003",
    "index": "D1",
    "title": "Turtle and a MEX Problem (Easy Version)",
    "statement": "\\textbf{The two versions are different problems. In this version of the problem, you can choose the same integer twice or more. You can make hacks only if both versions are solved.}\n\nOne day, Turtle was playing with $n$ sequences. Let the length of the $i$-th sequence be $l_i$. Then the $i$-th sequence was $a_{i, 1}, a_{i, 2}, \\ldots, a_{i, l_i}$.\n\nPiggy gave Turtle a problem to solve when Turtle was playing. The statement of the problem was:\n\n- There was a non-negative integer $x$ at first. Turtle would perform an arbitrary number (possibly zero) of operations on the integer.\n- In each operation, Turtle could choose an integer $i$ such that $1 \\le i \\le n$, and set $x$ to $\\text{mex}^{\\dagger}(x, a_{i, 1}, a_{i, 2}, \\ldots, a_{i, l_i})$.\n- Turtle was asked to find the answer, which was the \\textbf{maximum} value of $x$ after performing an arbitrary number of operations.\n\nTurtle solved the above problem without difficulty. He defined $f(k)$ as the answer to the above problem when the initial value of $x$ was $k$.\n\nThen Piggy gave Turtle a non-negative integer $m$ and asked Turtle to find the value of $\\sum\\limits_{i = 0}^m f(i)$ (i.e., the value of $f(0) + f(1) + \\ldots + f(m)$). Unfortunately, he couldn't solve this problem. Please help him!\n\n$^{\\dagger}\\text{mex}(c_1, c_2, \\ldots, c_k)$ is defined as the smallest \\textbf{non-negative} integer $x$ which does not occur in the sequence $c$. For example, $\\text{mex}(2, 2, 0, 3)$ is $1$, $\\text{mex}(1, 2)$ is $0$.",
    "tutorial": "Let the smallest non-negative integer that does not appear in the $i$-th sequence be denoted as $u_i$, and the second smallest non-negative integer that does not appear as $v_i$. In one operation of choosing index $i$, if $x = u_i$, then $x$ changes to $v_i$; otherwise, $x$ changes to $u_i$. It can be observed that if $x$ is operated at least once, its final value will not exceed $\\max\\limits_{i = 1}^n v_i$. To achieve this maximum value, one can select the index corresponding to this maximum value twice. Let $k = \\max\\limits_{i = 1}^n v_i$, then the answer is $\\sum\\limits_{i = 0}^m \\max(i, k)$. If $k \\ge m$, the answer is $(m + 1) \\cdot k$; otherwise, the answer is $\\sum\\limits_{i = 0}^{k - 1} k + \\sum\\limits_{i = k}^m i = k^2 + \\frac{(m + k)(m - k + 1)}{2}$. Time complexity: $O(\\sum l_i)$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<ll, ll> pii;\n\nconst int maxn = 200100;\n\nll n, m, a[maxn];\nbool vis[maxn];\n\nvoid solve() {\n\tscanf(\"%lld%lld\", &n, &m);\n\tll k = 0;\n\twhile (n--) {\n\t\tint t;\n\t\tscanf(\"%d\", &t);\n\t\tfor (int i = 0; i <= t + 5; ++i) {\n\t\t\tvis[i] = 0;\n\t\t}\n\t\tfor (int i = 1; i <= t; ++i) {\n\t\t\tscanf(\"%lld\", &a[i]);\n\t\t\tif (a[i] <= t + 4) {\n\t\t\t\tvis[a[i]] = 1;\n\t\t\t}\n\t\t}\n\t\tll mex = 0;\n\t\twhile (vis[mex]) {\n\t\t\t++mex;\n\t\t}\n\t\tvis[mex] = 1;\n\t\twhile (vis[mex]) {\n\t\t\t++mex;\n\t\t}\n\t\tk = max(k, mex);\n\t}\n\tprintf(\"%lld\\n\", k >= m ? (m + 1) * k : k * k + (m + k) * (m - k + 1) / 2);\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2003",
    "index": "D2",
    "title": "Turtle and a MEX Problem (Hard Version)",
    "statement": "\\textbf{The two versions are different problems. In this version of the problem, you can't choose the same integer twice or more. You can make hacks only if both versions are solved.}\n\nOne day, Turtle was playing with $n$ sequences. Let the length of the $i$-th sequence be $l_i$. Then the $i$-th sequence was $a_{i, 1}, a_{i, 2}, \\ldots, a_{i, l_i}$.\n\nPiggy gave Turtle a problem to solve when Turtle was playing. The statement of the problem was:\n\n- There was a non-negative integer $x$ at first. Turtle would perform an arbitrary number (possibly zero) of operations on the integer.\n- In each operation, Turtle could choose an integer $i$ such that $1 \\le i \\le n$ and \\textbf{$i$ wasn't chosen before}, and set $x$ to $\\text{mex}^{\\dagger}(x, a_{i, 1}, a_{i, 2}, \\ldots, a_{i, l_i})$.\n- Turtle was asked to find the answer, which was the \\textbf{maximum} value of $x$ after performing an arbitrary number of operations.\n\nTurtle solved the above problem without difficulty. He defined $f(k)$ as the answer to the above problem when the initial value of $x$ was $k$.\n\nThen Piggy gave Turtle a non-negative integer $m$ and asked Turtle to find the value of $\\sum\\limits_{i = 0}^m f(i)$ (i.e., the value of $f(0) + f(1) + \\ldots + f(m)$). Unfortunately, he couldn't solve this problem. Please help him!\n\n$^{\\dagger}\\text{mex}(c_1, c_2, \\ldots, c_k)$ is defined as the smallest \\textbf{non-negative} integer $x$ which does not occur in the sequence $c$. For example, $\\text{mex}(2, 2, 0, 3)$ is $1$, $\\text{mex}(1, 2)$ is $0$.",
    "tutorial": "Please first read the solution for problem D1. Construct a directed graph. For the $i$-th sequence, add a directed edge from $u_i$ to $v_i$. In each operation, you can either move along an outgoing edge of $x$ or move to any vertex $u$ and remove one of its outgoing edges. Let $f_i$ be the maximum vertex number that can be reached starting from vertex $i$ by continuously selecting one outgoing edge in the directed graph. This can be solved using DP in reverse order from large to small. Firstly, the answer for $x$ is at least $f_x$. Additionally, the answer for every $x$ is at least $\\max\\limits_{i=1}^n u_i$. Moreover, for any vertex $i$ with outdegree greater than 1, the answer for every $x$ is at least $f_i$, since you can disconnect any outgoing edge from $i$ except the one leading to $f_i$. Let $k = \\max\\limits_{i=1}^n v_i$. For values $\\le k$, we can directly enumerate and calculate. For values $> k$, they won't be operated. Time complexity: $O(\\sum l_i)$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<ll, ll> pii;\n\nconst int maxn = 200100;\n\nll n, m, a[maxn], f[maxn];\npii b[maxn];\nbool vis[maxn];\nvector<int> G[maxn];\n\ninline ll calc(ll l, ll r) {\n\treturn (l + r) * (r - l + 1) / 2;\n}\n\nvoid solve() {\n\tscanf(\"%lld%lld\", &n, &m);\n\tll t = -1, ans = 0, k = 0;\n\tfor (int i = 1, l; i <= n; ++i) {\n\t\tscanf(\"%d\", &l);\n\t\tfor (int j = 1; j <= l; ++j) {\n\t\t\tscanf(\"%lld\", &a[j]);\n\t\t\tif (a[j] < maxn) {\n\t\t\t\tvis[a[j]] = 1;\n\t\t\t}\n\t\t}\n\t\tll u = 0;\n\t\twhile (vis[u]) {\n\t\t\t++u;\n\t\t}\n\t\tt = max(t, u);\n\t\tll v = u;\n\t\tvis[u] = 1;\n\t\twhile (vis[v]) {\n\t\t\t++v;\n\t\t}\n\t\tb[i] = mkp(u, v);\n\t\tk = max(k, v);\n\t\tvis[u] = 0;\n\t\tfor (int j = 1; j <= l; ++j) {\n\t\t\tif (a[j] < maxn) {\n\t\t\t\tvis[a[j]] = 0;\n\t\t\t}\n\t\t}\n\t}\n\tfor (int i = 0; i <= k; ++i) {\n\t\tvector<int>().swap(G[i]);\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tG[b[i].fst].pb(b[i].scd);\n\t}\n\tfor (int u = k; ~u; --u) {\n\t\tf[u] = u;\n\t\tfor (int v : G[u]) {\n\t\t\tf[u] = max(f[u], f[v]);\n\t\t}\n\t\tif ((int)G[u].size() >= 2) {\n\t\t\tt = max(t, f[u]);\n\t\t}\n\t}\n\tfor (int i = 0; i <= min(k, m); ++i) {\n\t\tans += max(t, f[i]);\n\t}\n\tif (k < m) {\n\t\tans += calc(k + 1, m);\n\t}\n\tprintf(\"%lld\\n\", ans);\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2003",
    "index": "E1",
    "title": "Turtle and Inversions (Easy Version)",
    "statement": "\\textbf{This is an easy version of this problem. The differences between the versions are the constraint on $m$ and $r_i < l_{i + 1}$ holds for each $i$ from $1$ to $m - 1$ in the easy version. You can make hacks only if both versions of the problem are solved.}\n\nTurtle gives you $m$ intervals $[l_1, r_1], [l_2, r_2], \\ldots, [l_m, r_m]$. He thinks that a permutation $p$ is interesting if there exists an integer $k_i$ for every interval ($l_i \\le k_i < r_i$), and if he lets $a_i = \\max\\limits_{j = l_i}^{k_i} p_j, b_i = \\min\\limits_{j = k_i + 1}^{r_i} p_j$ for every integer $i$ from $1$ to $m$, the following condition holds:\n\n$$\\max\\limits_{i = 1}^m a_i < \\min\\limits_{i = 1}^m b_i$$\n\nTurtle wants you to calculate the maximum number of inversions of all interesting permutations of length $n$, or tell him if there is no interesting permutation.\n\nAn inversion of a permutation $p$ is a pair of integers $(i, j)$ ($1 \\le i < j \\le n$) such that $p_i > p_j$.",
    "tutorial": "Divide all numbers into two types: small numbers ($0$) and large numbers ($1$), such that any small number is less than any large number. In this way, a permutation can be transformed into a $01$ sequence. A permutation is interesting if and only if there exists a way to divide all numbers into two types such that, for every given interval $[l, r]$, all $0$s appear before all $1$s, and there is at least one $0$ and one $1$ in the interval. Such a $01$ sequence is called interesting. If an interesting $01$ sequence is fixed, we can greedily arrange all $0$s in descending order and all $1$s in descending order. Let the number of $0$s be $x$ and the number of $1$s be $y$. Let $z$ be the number of index pairs $(i, j)$, where the $i$-th number is $1$ and the $j$-th number is $0$ (such pairs are called $10$ pairs). Then, the maximum number of inversions is $\\frac{x(x - 1)}{2} + \\frac{y(y - 1)}{2} + z$. In this version, the intervals are non-overlapping, so DP can be applied directly. Let $f_{i, j}$ represent the maximum number of $10$ pairs when considering all numbers from $1$ to $i$, where there are $j$ $1$s. For transitions, if $i$ is the left endpoint of an interval and the right endpoint of this interval is $p$, we can enumerate the number of $0$s as $k$ and the number of $1$s as $p - i + 1 - k$ for the transition. Otherwise, we consider whether $i$ is $0$ or $1$. The answer is $\\max\\limits_{i = 0}^n f_{n, i} + \\frac{i(i - 1)}{2} + \\frac{(n - i)(n - i - 1)}{2}$. Time complexity: $O(n^2 + m)$ per test case.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<ll, ll> pii;\n\nconst int maxn = 5050;\n\nint n, m, f[maxn][maxn], a[maxn], b[maxn];\n\nvoid solve() {\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 0; i <= n + 1; ++i) {\n\t\tfor (int j = 0; j <= n + 1; ++j) {\n\t\t\tf[i][j] = -1e9;\n\t\t}\n\t\ta[i] = 0;\n\t}\n\tfor (int i = 1, l, r; i <= m; ++i) {\n\t\tscanf(\"%d%d\", &l, &r);\n\t\ta[l] = r;\n\t}\n\tf[0][0] = 0;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tif (a[i]) {\n\t\t\tint p = a[i];\n\t\t\tfor (int j = 0; j < i; ++j) {\n\t\t\t\tfor (int k = 1; k <= p - i; ++k) {\n\t\t\t\t\tf[p][j + k] = max(f[p][j + k], f[i - 1][j] + (p - i + 1 - k) * j);\n\t\t\t\t}\n\t\t\t}\n\t\t\ti = p;\n\t\t} else {\n\t\t\tfor (int j = 0; j <= i; ++j) {\n\t\t\t\tf[i][j] = f[i - 1][j] + j;\n\t\t\t\tif (j) {\n\t\t\t\t\tf[i][j] = max(f[i][j], f[i - 1][j - 1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tint ans = 0;\n\tfor (int i = 0; i <= n; ++i) {\n\t\tans = max(ans, f[n][i] + i * (i - 1) / 2 + (n - i) * (n - i - 1) / 2);\n\t}\n\tprintf(\"%d\\n\", ans);\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "divide and conquer",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2003",
    "index": "E2",
    "title": "Turtle and Inversions (Hard Version)",
    "statement": "\\textbf{This is a hard version of this problem. The differences between the versions are the constraint on $m$ and $r_i < l_{i + 1}$ holds for each $i$ from $1$ to $m - 1$ in the easy version. You can make hacks only if both versions of the problem are solved.}\n\nTurtle gives you $m$ intervals $[l_1, r_1], [l_2, r_2], \\ldots, [l_m, r_m]$. He thinks that a permutation $p$ is interesting if there exists an integer $k_i$ for every interval ($l_i \\le k_i < r_i$), and if he lets $a_i = \\max\\limits_{j = l_i}^{k_i} p_j, b_i = \\min\\limits_{j = k_i + 1}^{r_i} p_j$ for every integer $i$ from $1$ to $m$, the following condition holds:\n\n$$\\max\\limits_{i = 1}^m a_i < \\min\\limits_{i = 1}^m b_i$$\n\nTurtle wants you to calculate the maximum number of inversions of all interesting permutations of length $n$, or tell him if there is no interesting permutation.\n\nAn inversion of a permutation $p$ is a pair of integers $(i, j)$ ($1 \\le i < j \\le n$) such that $p_i > p_j$.",
    "tutorial": "Compared to problem E1, this version contains the situation where intervals can overlap. Consider a pair of overlapping intervals $[l_1, r_1]$ and $[l_2, r_2]$ (assuming $l_1 \\le l_2$). The range $[l_1, l_2 - 1]$ must consist entirely of $0$s, and the range $[r_1 + 1, r_2]$ must consist entirely of $1$s. Then, you can remove the intervals $[l_1, r_1]$ and $[l_2, r_2]$, add a new interval $[l_2, r_1]$, and keep track of which numbers are guaranteed to be $0$ and which are guaranteed to be $1$. After processing in this way, the intervals will no longer overlap, reducing the problem to problem E1. Time complexity: $O(n^2 + m \\log m)$ per test case. There exists a $O(n + m)$ solution to this problem.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<int, int> pii;\n\nconst int maxn = 5050;\nconst int inf = 0x3f3f3f3f;\n\nint n, m, b[maxn], c[maxn], f[maxn][maxn];\nstruct node {\n\tint l, r;\n} a[maxn];\n\nvoid solve() {\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 1; i <= n; ++i) {\n\t\tc[i] = -1;\n\t\tb[i] = 0;\n\t}\n\tfor (int i = 1; i <= m; ++i) {\n\t\tscanf(\"%d%d\", &a[i].l, &a[i].r);\n\t}\n\tif (!m) {\n\t\tprintf(\"%d\\n\", n * (n - 1) / 2);\n\t\treturn;\n\t}\n\tsort(a + 1, a + m + 1, [&](const node &a, const node &b) {\n\t\treturn a.l < b.l;\n\t});\n\tint mnl = a[1].l, mxl = a[1].l, mnr = a[1].r, mxr = a[1].r;\n\tfor (int i = 2; i <= m + 1; ++i) {\n\t\tif (i == m + 1 || a[i].l > mxr) {\n\t\t\tif (mxl >= mnr) {\n\t\t\t\tputs(\"-1\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (int j = mnl; j < mxl; ++j) {\n\t\t\t\tc[j] = 0;\n\t\t\t}\n\t\t\tfor (int j = mnr + 1; j <= mxr; ++j) {\n\t\t\t\tc[j] = 1;\n\t\t\t}\n\t\t\tb[mxl] = mnr;\n\t\t\tmnl = mxl = a[i].l;\n\t\t\tmnr = mxr = a[i].r;\n\t\t} else {\n\t\t\tmnl = min(mnl, a[i].l);\n\t\t\tmxl = max(mxl, a[i].l);\n\t\t\tmnr = min(mnr, a[i].r);\n\t\t\tmxr = max(mxr, a[i].r);\n\t\t}\n\t}\n\tfor (int i = 0; i <= n; ++i) {\n\t\tfor (int j = 0; j <= n; ++j) {\n\t\t\tf[i][j] = -inf;\n\t\t}\n\t}\n\tf[0][0] = 0;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tif (b[i]) {\n\t\t\tint p = b[i];\n\t\t\tfor (int j = 0; j < i; ++j) {\n\t\t\t\tfor (int k = 1; k <= p - i; ++k) {\n\t\t\t\t\tf[p][j + k] = max(f[p][j + k], f[i - 1][j] + (p - i + 1 - k) * j);\n\t\t\t\t}\n\t\t\t}\n\t\t\ti = p;\n\t\t} else if (c[i] == 1) {\n\t\t\tfor (int j = 1; j <= i; ++j) {\n\t\t\t\tf[i][j] = f[i - 1][j - 1];\n\t\t\t}\n\t\t} else if (c[i] == 0) {\n\t\t\tfor (int j = 0; j < i; ++j) {\n\t\t\t\tf[i][j] = f[i - 1][j] + j;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (int j = 0; j <= i; ++j) {\n\t\t\t\tf[i][j] = max(f[i - 1][j] + j, j ? f[i - 1][j - 1] : -inf);\n\t\t\t}\n\t\t}\n\t}\n\tint ans = -1;\n\tfor (int i = 0; i <= n; ++i) {\n\t\tans = max(ans, f[n][i] + i * (i - 1) / 2 + (n - i) * (n - i - 1) / 2);\n\t}\n\tprintf(\"%d\\n\", ans);\n}\n\nint main() {\n\tint T = 1;\n\tscanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "dp",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2003",
    "index": "F",
    "title": "Turtle and Three Sequences",
    "statement": "Piggy gives Turtle three sequences $a_1, a_2, \\ldots, a_n$, $b_1, b_2, \\ldots, b_n$, and $c_1, c_2, \\ldots, c_n$.\n\nTurtle will choose a subsequence of $1, 2, \\ldots, n$ of length $m$, let it be $p_1, p_2, \\ldots, p_m$. The subsequence should satisfy the following conditions:\n\n- $a_{p_1} \\le a_{p_2} \\le \\cdots \\le a_{p_m}$;\n- All $b_{p_i}$ for all indices $i$ are \\textbf{pairwise distinct}, i.e., there don't exist two different indices $i$, $j$ such that $b_{p_i} = b_{p_j}$.\n\nHelp him find the maximum value of $\\sum\\limits_{i = 1}^m c_{p_i}$, or tell him that it is impossible to choose a subsequence of length $m$ that satisfies the conditions above.\n\nRecall that a sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements.",
    "tutorial": "If the number of possible values for $b_i$ is small, you can use bitmask DP. Define $f_{i, S, j}$ as the maximum result considering all numbers up to $i$, where $S$ is the current set of distinct $b_i$ values in the subsequence, and $j$ is the value of $a$ for the last element of the subsequence. The transitions can be optimized using a Fenwick tree (Binary Indexed Tree). When $b_i$ has many possible values, consider using color-coding, where each $b_i$ is randomly mapped to a number in $[1, m]$, and then apply bitmask DP. The probability of obtaining the optimal solution in one attempt is $\\frac{m!}{m^m}$, and the probability of not obtaining the optimal solution after $T$ attempts is $(1 - \\frac{m!}{m^m})^T$. When $T = 300$, the probability of not obtaining the optimal solution is approximately $7.9 \\cdot 10^{-6}$, which is acceptable. Time complexity: $O(Tn2^m \\log n)$.",
    "code": "#include <bits/stdc++.h>\n#define pb emplace_back\n#define fst first\n#define scd second\n#define mkp make_pair\n#define mems(a, x) memset((a), (x), sizeof(a))\n\nusing namespace std;\ntypedef long long ll;\ntypedef double db;\ntypedef unsigned long long ull;\ntypedef long double ldb;\ntypedef pair<ll, ll> pii;\n\nconst int maxn = 3030;\n\nint n, m, a[maxn], b[maxn], c[maxn], d[maxn], e[maxn];\n\nstruct BIT {\n\tint c[maxn];\n\t\n\tinline void init() {\n\t\tmems(c, -0x3f);\n\t}\n\t\n\tinline void update(int x, int d) {\n\t\tfor (int i = x; i <= n; i += (i & (-i))) {\n\t\t\tc[i] = max(c[i], d);\n\t\t}\n\t}\n\t\n\tinline int query(int x) {\n\t\tint res = -1e9;\n\t\tfor (int i = x; i; i -= (i & (-i))) {\n\t\t\tres = max(res, c[i]);\n\t\t}\n\t\treturn res;\n\t}\n} T[32];\n\nvoid solve() {\n\tscanf(\"%d%d\", &n, &m);\n\tfor (int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &a[i]);\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &b[i]);\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tscanf(\"%d\", &c[i]);\n\t}\n\tmt19937 rnd(chrono::system_clock::now().time_since_epoch().count());\n\tint ans = 0;\n\tfor (int _ = 0; _ < 300; ++_) {\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\td[i] = rnd() % m;\n\t\t}\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\te[i] = d[b[i]];\n\t\t}\n\t\tfor (int i = 0; i < (1 << m); ++i) {\n\t\t\tT[i].init();\n\t\t}\n\t\tT[0].update(1, 0);\n\t\tfor (int i = 1; i <= n; ++i) {\n\t\t\tfor (int S = 0; S < (1 << m); ++S) {\n\t\t\t\tif (S & (1 << e[i])) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tT[S | (1 << e[i])].update(a[i], T[S].query(a[i]) + c[i]);\n\t\t\t}\n\t\t}\n\t\tans = max(ans, T[(1 << m) - 1].query(n));\n\t}\n\tprintf(\"%d\\n\", ans > 0 ? ans : -1);\n}\n\nint main() {\n\tint T = 1;\n\t// scanf(\"%d\", &T);\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "math",
      "probabilities",
      "two pointers"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2004",
    "index": "A",
    "title": "Closest Point",
    "statement": "Consider a set of points on a line. The distance between two points $i$ and $j$ is $|i - j|$.\n\nThe point $i$ from the set is \\textbf{the closest} to the point $j$ from the set, if there is no other point $k$ in the set such that the distance from $j$ to $k$ is \\textbf{strictly less} than the distance from $j$ to $i$. In other words, all other points from the set have distance to $j$ greater or equal to $|i - j|$.\n\nFor example, consider a set of points $\\{1, 3, 5, 8\\}$:\n\n- for the point $1$, the closest point is $3$ (other points have distance greater than $|1-3| = 2$);\n- for the point $3$, there are two closest points: $1$ and $5$;\n- for the point $5$, the closest point is $3$ (but not $8$, since its distance is greater than $|3-5|$);\n- for the point $8$, the closest point is $5$.\n\nYou are given a set of points. You have to add an \\textbf{integer} point into this set in such a way that \\textbf{it is different from every existing point in the set}, and \\textbf{it becomes the closest point to every point in the set}. Is it possible?",
    "tutorial": "This problem can be solved \"naively\" by iterating on the point we add and checking that it becomes the closest point to all elements from the set. However, there is another solution which is faster and easier to implement. When we add a point, it can become the closest only to two points from the set: one to the left, and one to the right. If there are, for example, two points to the left of the point we add, then the condition on the leftmost point won't be met (the point we add won't be the closest to it). So, if $n>2$, there is no way to add a point. If $n=2$, we want to insert a new point between the two existing points - so we need to check that they are not adjacent.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    x = list(map(int, input().split()))\n    if n > 2 or x[0] + 1 == x[-1]:\n        print('NO')\n    else:\n        print('YES')",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2004",
    "index": "B",
    "title": "Game with Doors",
    "statement": "There are $100$ rooms arranged in a row and $99$ doors between them; the $i$-th door connects rooms $i$ and $i+1$. Each door can be either locked or unlocked. Initially, all doors are unlocked.\n\nWe say that room $x$ is reachable from room $y$ if all doors between them are unlocked.\n\nYou know that:\n\n- Alice is in some room from the segment $[l, r]$;\n- Bob is in some room from the segment $[L, R]$;\n- Alice and Bob are in different rooms.\n\nHowever, you don't know the exact rooms they are in.\n\nYou don't want Alice and Bob to be able to reach each other, so you are going to lock some doors to prevent that. What's the smallest number of doors you have to lock so that Alice and Bob cannot meet, regardless of their starting positions inside the given segments?",
    "tutorial": "Let's find the segment of rooms where both Alice and Bob can be. This segment is $[\\max(L, l), \\min(R, r)]$. If it is empty, then it is sufficient to simply block any door between Alice's segment and Bob's segment, so the answer is $1$. If it is not empty, let's denote by $x$ the number of doors in this segment - $\\min(R, r) - \\max(L, l)$. Each of these doors definitely needs to be blocked so that Alice and Bob cannot meet if they are in adjacent rooms within this segment. Therefore, the answer is at least $x$. However, sometimes we also need to restrict this segment on the left and/or right. If either of them is to the left of this segment (i.e., the left boundaries of their segments do not coincide), we need to block the door to the left of the intersection (and increase the answer by $1$). Similarly for the right boundary.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int l, r, L, R;\n    cin >> l >> r >> L >> R;\n    int inter = min(r, R) - max(l, L) + 1;\n    int ans = inter - 1;\n    if (inter <= 0) {\n      ans = 1;\n    } else {\n      ans += (l != L);\n      ans += (r != R);\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2004",
    "index": "C",
    "title": "Splitting Items",
    "statement": "Alice and Bob have $n$ items they'd like to split between them, so they decided to play a game. All items have a cost, and the $i$-th item costs $a_i$. Players move in turns starting from Alice.\n\nIn each turn, the player chooses one of the remaining items and takes it. The game goes on until no items are left.\n\nLet's say that $A$ is the total cost of items taken by Alice and $B$ is the total cost of Bob's items. The resulting score of the game then will be equal to $A - B$.\n\nAlice wants to maximize the score, while Bob wants to minimize it. Both Alice and Bob will play optimally.\n\nBut the game will take place tomorrow, so today Bob can modify the costs a little. He can increase the costs $a_i$ of several (possibly none or all) items by an integer value (possibly, by the same value or by different values for each item). However, the total increase must be less than or equal to $k$. Otherwise, Alice may suspect something. Note that Bob \\textbf{can't decrease} costs, only increase.\n\nWhat is the minimum possible score Bob can achieve?",
    "tutorial": "Let's sort the array in descending order and consider the first two moves of the game. Since Alice goes first, she takes the maximum element in the array ($a_1$). Then, during his turn, Bob takes the second-largest element ($a_2$) to minimize the score difference. Bob can increase his element in advance; however, he cannot make it larger than $a_1$ (since Alice always takes the maximum element in the array). This means that Bob needs to increase his element to $\\min(a_1, a_2 + k)$. Then the game moves to a similar situation, but without the first two elements and with an updated value of $k$. Thus, to solve the problem, we can sort the array and then iterate through it while maintaining several values. If the current index is odd (corresponding to Alice's turn), increase the answer by $a_i$. If the current index is even (corresponding to Bob's turn), increase the current value of $a_i$ by $\\min(k, a_{i - 1} - a_i)$, decrease $k$ by that same value, and also subtract the new value of $a_i$ from the answer.",
    "code": "fun main() {\n    repeat(readln().toInt()) {\n        val (n, k) = readln().split(\" \").map { it.toInt() }\n        val a = readln().split(\" \").map { it.toInt() }.sortedDescending().toIntArray()\n\n        var score = 0L\n        var rem = k\n        for (i in a.indices) {\n            if (i % 2 == 0) {\n                score += a[i]\n            }\n            else {\n                val needed = minOf(rem, a[i - 1] - a[i])\n                a[i] += needed\n                rem -= needed\n                score -= a[i]\n            }\n        }\n        println(score)\n    }\n}",
    "tags": [
      "games",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2004",
    "index": "D",
    "title": "Colored Portals",
    "statement": "There are $n$ cities located on a straight line. The cities are numbered from $1$ to $n$.\n\nPortals are used to move between cities. There are $4$ colors of portals: blue, green, red, and yellow. Each city has portals of two different colors. You can move from city $i$ to city $j$ if they have portals of the same color (for example, you can move between a \"blue-red\" city and a \"blue-green\" city). This movement costs $|i-j|$ coins.\n\nYour task is to answer $q$ independent queries: calculate the minimum cost to move from city $x$ to city $y$.",
    "tutorial": "If cities $x$ and $y$ have a common portal, then the cost of the path is $|x-y|$. Otherwise, we have to move from city $x$ to some intermediate city $z$. It's important to note that the type of city $z$ should be different from the type of city $x$. Otherwise, we could skip city $z$ and go directly from $x$ to the next city in the path. Since the type of city $z$ doesn't match the type of city $x$, it must have a common portal with city $y$. Therefore, the optimal path look like this: $x \\rightarrow z \\rightarrow y$. Additional cities won't decrease the cost of the path. Now we have to figure out how to choose city $z$ to minimize the cost of the path. Without loss of generality, let's say that $x \\le y$. Then there are three possible locations for city $z$: $z < x$, then the cost of the path is $(x-z) + (y-z)$; $x \\le z \\le y$, then the cost of the path is $(z-x) + (y-z) = y - x$; $y < z$, then the cost of the path is $(z-x) + (z-y)$. It is easy to see that in each case, to minimize the cost of the path, we should choose $z$ as close to $x$ as possible. Let's define two arrays: $\\mathrm{lf}_{i, j}$ - the index of the nearest city to the left of $i$ with type $j$, and similarly $\\mathrm{rg}_{i, j}$ - the index of the nearest city to the right of $i$ with type $j$. Then the answer to the problem is the minimum value among $|x - \\mathrm{lf}_{x, j}| + |\\mathrm{lf}_{x, j} - y|$ and $|x - \\mathrm{rg}_{x, j}| + |\\mathrm{rg}_{x, j} - y|$ for all types $j$ for which there are common portals with cities $x$ and $y$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int INF = 1e9;\nconst string vars[] = {\"BG\", \"BR\", \"BY\", \"GR\", \"GY\", \"RY\"};\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, q;\n    cin >> n >> q;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) {\n      char s[5];\n      cin >> s;\n      a[i] = find(vars, vars + 6, s) - vars;\n    }\n    vector<vector<int>> lf(n), rg(n);\n    for (int o = 0; o < 2; ++o) {\n      vector<int> last(6, -INF);\n      for (int i = 0; i < n; ++i) {\n        last[a[i]] = (o ? n - i - 1 : i);\n        (o ? rg[n - i - 1] : lf[i]) = last;\n      }\n      reverse(a.begin(), a.end());\n    }\n    while (q--) {\n      int x, y;\n      cin >> x >> y;\n      --x; --y;\n      int ans = INF;\n      for (int j = 0; j < 6; ++j) {\n        if (a[x] + j != 5 && j + a[y] != 5) {\n          ans = min(ans, abs(x - lf[x][j]) + abs(lf[x][j] - y));\n          ans = min(ans, abs(x - rg[x][j]) + abs(rg[x][j] - y));\n        }\n      }\n      if (ans > INF / 2) ans = -1;\n      cout << ans << '\\n';\n    }\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2004",
    "index": "E",
    "title": "Not a Nim Problem",
    "statement": "Two players, Alice and Bob, are playing a game. They have $n$ piles of stones, with the $i$-th pile initially containing $a_i$ stones.\n\nOn their turn, a player can choose any pile of stones and take any positive number of stones from it, with one condition:\n\n- let the current number of stones in the pile be $x$. It is not allowed to take from the pile a number of stones $y$ such that the greatest common divisor of $x$ and $y$ is not equal to $1$.\n\nThe player who cannot make a move loses. Both players play optimally (that is, if a player has a strategy that allows them to win, no matter how the opponent responds, they will win). Alice goes first.\n\nDetermine who will win.",
    "tutorial": "So, okay, this is actually a problem related to Nim game and Sprague-Grundy theorem. If you're not familiar with it, I recommend studying it here. The following tutorial expects you to understand how Grundy values are calculated, which you can read there. The first (naive) solution to this problem would be to calculate the Grundy values for all integers from $1$ to $10^7$ via dynamic programming. That would work in $O(A^2 log A)$ or $O(A^2)$, where $A$ is the maximum value in the input, so it's not fast enough. However, coding a naive solution to this problem might still help. There is a method that allows you to (sometimes) approach these kinds of problems where you can calculate Grundy values slowly, and you need to do it faster. This method usually consists of four steps: code a solution that calculates Grundy values naively; run it and generate several first values of Grundy function; try to observe some patterns and formulate a faster way to calculate Grundy functions using them; verify your patterns on Grundy values of larger numbers and/or try to prove them. The third step is probably the most difficult, and generating too few Grundy values might lead you to wrong conclusions. For example, the first $8$ values of Grundy are $[1, 0, 2, 0, 3, 0, 4, 0]$, which may lead to an assumption that $g(x) = 0$ if $x$ is even, or $g(x) = \\frac{x+1}{2}$ if $x$ is odd. However, this pattern breaks as soon as you calculate $g(9)$, which is not $5$, but $2$. You can pause reading the editorial here and try formulating a different pattern which would explain that; the next paragraph contains the solution. Okay, we claim that: $g(1) = 1$; $g(x) = 0$ if $x$ is even; $g(x) = p(x)$ if $x$ is an odd prime number, where $p(x)$ is the index of $x$ in the sequence of prime numbers; $g(x) = g(d(x))$ if $x$ is an odd composite number, where $d(x)$ is the minimum prime divisor of $x$. We can prove it with induction on $x$ and something like that: $g(1) = 1$ can simply be verified by calculation; if $x$ is even, there are no transitions to other even values of pile size from the current state of the game (because that would imply that both $x$ and $x-y$ are divisible by $2$, so $gcd(x,y)$ is at least $2$). Since these are the only states having Grundy values equal to $0$, the MEX of all transitions is equal to $0$; if $x$ is an odd prime number, there are transitions to all states of the game from $1$ to $x-1$. The set of Grundy values of these transitions contains all integers from $0$ to $g(x')$, where $x'$ is the previous odd prime number; so, the MEX of this set is $g(x') + 1 = p(x') + 1 = p(x)$; if $x$ is a composite prime number and $d(x)$ is its minimum prime divisor, then there are transitions to all states from $1$ to $d(x)-1$ (having Grundy values from $0$ to $g(d(x))-1$); but every $x'$ such that $g(x') = g(d(x))$ is divisible by $d(x)$; so, there are no transitions to those states (otherwise $gcd(x,y)$ would be at least $d(x)$). So, the MEX of all states reachable in one step is $g(d(x))$. This is almost the whole solution. However, we need to calculate $p(x)$ and $d(x)$ for every $x$ until $10^7$. Probably the easiest way to do it is using the linear prime sieve.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\n \nconst int N = int(1e7) + 43;\n \nint lp[N + 1];\nvector<int> pr;\nint idx[N + 1];\n \nvoid precalc()\n{\n\tfor (int i = 2; i <= N; i++) \n\t{\n\t\tif (lp[i] == 0) \n\t\t{\n\t\t\tlp[i] = i;\n\t\t\tpr.push_back(i);\n\t\t}\n\t\tfor (int j = 0; j < pr.size() && pr[j] <= lp[i] && i * 1ll * pr[j] <= N; ++j)\n\t\t\tlp[i * pr[j]] = pr[j];\n\t}\n\tfor (int i = 0; i < pr.size(); i++)\n\t\tidx[pr[i]] = i + 1; \n}\n \nint get(int x)\n{\n\tif(x == 1) return 1;\n \tx = lp[x];\n \tif(x == 2)\n \t\treturn 0;\n \telse return idx[x]; \t\t\n}\n \nvoid solve()\n{             \n\tint n;\n\tscanf(\"%d\", &n);\n\tint res = 0;\n\tfor(int i = 0; i < n; i++)\n\t{\n\t \tint x;\n\t \tscanf(\"%d\", &x);\n\t \tres ^= get(x);\n\t}\n\tif(res) puts(\"Alice\");\n\telse puts(\"Bob\");\n}\n \nint main()\n{\n \tprecalc();\n \tint t;\n \tscanf(\"%d\", &t);\n \tfor(int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "brute force",
      "games",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2004",
    "index": "F",
    "title": "Make a Palindrome",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nLet the function $f(b)$ return the minimum number of operations needed to make an array $b$ a palindrome. The operations you can make are:\n\n- choose two adjacent elements $b_i$ and $b_{i+1}$, remove them, and replace them with a single element equal to $(b_i + b_{i + 1})$;\n- or choose an element $b_i > 1$, remove it, and replace it with two positive integers $x$ and $y$ ($x > 0$ and $y > 0$) such that $x + y = b_i$.\n\nFor example, from an array $b=[2, 1, 3]$, you can obtain the following arrays in one operation: $[1, 1, 1, 3]$, $[2, 1, 1, 2]$, $[3, 3]$, $[2, 4]$, or $[2, 1, 2, 1]$.\n\nCalculate $\\displaystyle \\left(\\sum_{1 \\le l \\le r \\le n}{f(a[l..r])}\\right)$, where $a[l..r]$ is the subarray of $a$ from index $l$ to index $r$, inclusive. In other words, find the sum of the values of the function $f$ for all subarrays of the array $a$.",
    "tutorial": "To begin with, let's find out how to solve the problem for a single subarray in linear time. If equal numbers are at both ends, we can remove them and reduce the problem to a smaller size (thus, we have decreased the length of the array by $2$ in $0$ operations, or by $1$ if there is only one element). Otherwise, we have to do something with one of these numbers: either merge the smaller one with its neighbor or split the larger one. It can be shown that it doesn't matter which of these actions we take, so let's split the larger of the two numbers at the ends in such a way that the numbers at the ends become equal, and then we can remove the equal numbers at the ends (thus, we reduce the length of the array by $1$ in $1$ operation). In this case, the answer for the array depends on the number of situations where the ends of the array have equal numbers and the number of situations where they are different. Now let's understand how to quickly calculate how many times, when processing a subarray, we encounter a situation where the ends have equal numbers. After removing these equal numbers at the ends, we obtain a subarray such that numbers with equal sums have been removed from the prefix and suffix compared to the original subarray. We can determine how many such subarrays can be obtained from the original one by removing a prefix and a suffix with equal sums. For this, we can use prefix sums. Let the prefix sum at the beginning of the segment be $p_l$, and at the end be $p_r$. If we remove a prefix and a suffix with sum $s$, the sums become $p_l + s$ and $p_r - s$. At the same time, the sum $p_l + p_r$ for the smaller subarray remains the same. Therefore, for each such subarray that results from the situation \"the elements on the right and left were equal, we removed them\" the sum $p_l + p_r$ is the same as that of the original segment. To calculate the number of shorter segments with the same sum $p_l + p_r$ for each segment, we can iterate through all segments in order of increasing length and store in a map the count of subarrays with each sum $p_l + p_r$. This leads us to solve the problem in $O(n^2 \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (auto& x : a) cin >> x;\n    vector<int> p(n + 1);\n    for (int i = 0; i < n; ++i) p[i + 1] = p[i] + a[i];\n    map<int, int> cnt;\n    long long ans = 0;\n    for (int len = 0; len <= n; ++len) {\n      for (int i = 0; i <= n - len; ++i) {\n        int s = p[i] + p[i + len];\n        ans += len;\n        ans -= 2 * cnt[s];\n        ans -= (s % 2 == 1 || !binary_search(p.begin(), p.end(), s / 2));\n        cnt[s] += 1;\n      }\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2004",
    "index": "G",
    "title": "Substring Compression",
    "statement": "Let's define the operation of compressing a string $t$, consisting of at least $2$ digits from $1$ to $9$, as follows:\n\n- split it into an \\textbf{even} number of non-empty substrings — let these substrings be $t_1, t_2, \\dots, t_m$ (so, $t = t_1 + t_2 + \\dots + t_m$, where $+$ is the concatenation operation);\n- write the string $t_2$ $t_1$ times, then the string $t_4$ $t_3$ times, and so on.\n\nFor example, for a string \"12345\", one could do the following: split it into (\"1\", \"23\", \"4\", \"5\"), and write \"235555\".\n\nLet the function $f(t)$ for a string $t$ return the minimum length of the string that can be obtained as a result of that process.\n\nYou are given a string $s$, consisting of $n$ digits from $1$ to $9$, and an integer $k$. Calculate the value of the function $f$ for all contiguous substrings of $s$ of length exactly $k$.",
    "tutorial": "Let's start with learning how to solve the problem for a single string with any polynomial complexity. One immediately wants to use dynamic programming. For example, let $\\mathit{dp}_i$ be the minimum length of the compressed string from the first $i$ characters. Then, for the next transition, we could iterate over the next odd block first, and then over the next even block. This results in $O(n^3)$ complexity ($O(n)$ states and $O(n^2)$ for transitions). Note that there is no point in taking very long odd blocks. For instance, we can always take the first digit in the first block and the rest of the string in the second block. In this case, the answer will not exceed $9n$. Therefore, there is no point in taking more than $6$ digits in any odd block, as that would exceed our estimate. Can we take even fewer digits? Ideally, we would like to never take more than $1$ digit. Let's show that this is indeed possible. Consider two blocks: an odd block where we took a number with at least $2$ digits, and the even block after it. Let's try to change them so that the first block consists only of the first digit, and all the others go into the second block. Let's estimate how the length has changed. The digits that were previously in the first block and are now in the second block will now appear in the answer $9$ times in the worst case. The digits in the second block previously appeared $x$ times, and now they appear the following number of times: If the length was $2$, then $\\displaystyle \\lfloor\\frac{x}{10}\\rfloor$ times. In the best case, $11 \\rightarrow 1$ times, so $-10$. Thus, since the length was $2$, one digit now appears $+9$ times, and at least one appears $-10$ times. The answer has decreased. If the length was $3$, then $\\displaystyle \\lfloor\\frac{x}{100}\\rfloor$ times. In the best case, $111 \\rightarrow 1$ times, so $-110$. Thus, since the length was $3$, two digits now appear $+9$ times (a total of $+18$), and at least one appears $-110$ times. The answer has decreased. And so on. Now we can write the same dynamic programming in $O(n^2)$. There is no need to iterate over the odd block anymore, as it always has a length of $1$. The iteration over the even block still takes $O(n)$. We can try to make the states of the dp more complicated. What do the transitions look like now? Let $j$ be the end of the even block that we are iterating over. Then $\\mathit{dp}_j = \\min(\\mathit{dp}_j, \\mathit{dp}_i + \\mathit{ord(s_i)} \\cdot (j - i - 1))$. That is, essentially, for each character of the string, we choose how many times it should be written in the answer. Let's put this coefficient (essentially the digit in the last chosen odd block) into the state. Let $\\mathit{dp}[i][c]$ be the minimum length of the compressed string from the first $i$ characters, if the last odd block contains the digit $c$. Then the transitions are as follows: $\\mathit{dp}[i + 1][c] = \\min(\\mathit{dp}[i + 1][c], \\mathit{dp}[i][c] + c)$ - append the next character to the end of the last even block; $\\mathit{dp}[i + 2][s_i] = \\min(\\mathit{dp}[i + 2][s_i], \\mathit{dp}[i][c] + s_i)$ - start a new odd block at position $i$ and immediately take another character in the subsequent even block. If we do not take another character, the dynamic programming will start accumulating empty even blocks, which is prohibited by the problem. Thus, we have learned to solve the problem in $O(n)$ for a fixed string. The remaining task is to figure out how to solve it for all substrings of length $k$. Let's represent the entire set of the query substrings as a queue. That is, to transition from the substring $s_{i,i+k-1}$ to $s_{i+1,i+k}$, we need to append a character to the end and remove a character from the beginning. There is a known technique for solving problems on queues. It is called \"minimum on a queue\". If we figure out how to solve the problem on a stack (that is, with operations to append a character to the end and remove a character from the end), then we can solve it on a queue using two stacks. Our dynamic programming has only one drawback that slightly hinders this. One transition is at $i + 1$, and the other is at $i + 2$. Let's make both transitions at $i + 1$. To do this, we can introduce a dummy state that indicates that we wrote out an odd block in the last step. That is, let $\\mathit{dp}[i][c]$ still mean the same when $c > 0$, while the state $c = 0$ is dummy. For convenience, I suggest thinking about these transitions this way. We have a vector of values $\\mathit{dp}[i]$ with $10$ elements. We want to be able to convert it into a vector $\\mathit{dp}[i + 1]$ with the same $10$ elements, knowing the value of $s_i$. Now, this sounds like multiplying a vector by a matrix. Yes, the matrix consists of operations not $*/+$, but $+/\\min$, yet it still works. Then the solution on the stack is as follows. For each digit from $1$ to $9$, we pre-build the transition matrix of dynamic programming for that digit. We maintain one stack of transition matrices and another stack of the dp vectors. When we append a digit, we add elements to both stacks, multiplying the last vector by the matrix. When we remove, we pop the last elements from both stacks. If you are not familiar with the minimum on a queue, you can read this article: https://cp-algorithms.com/data_structures/stack_queue_modification.html. However, we have a slight difference from the standard technique. The minimum is a commutative operation, unlike matrix multiplication. But fixing this is not very difficult. In the first stack, we will multiply by the new matrix on the right. In the second stack, we will multiply on the left. Since the complexity of that queue is linear, we get an algorithm with a complexity of $n \\cdot 10^3$. It can be noted that, in the transition matrix, there is a linear number of useful values (not equal to $\\infty$). Thus, multiplying by such a matrix can be done in $10^2$.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nconst int D = 10;\nconst int INF = 1e9;\n \ntypedef array<array<int, D>, D> mat;\n \nmat mul(const mat &a, const mat &b, bool fl){\n\tmat c;\n\tforn(i, D) forn(j, D) c[i][j] = INF;\n\tif (fl){\n\t\tforn(i, D) forn(j, D){\n\t\t\tc[j][i] = min(c[j][i], min(a[j][0] + b[0][i], a[j][i] + b[i][i]));\n\t\t\tc[j][0] = min(c[j][0], a[j][i] + b[i][0]);\n\t\t}\n\t}\n\telse{\n\t\tforn(i, D) forn(j, D){\n\t\t\tc[i][j] = min(c[i][j], min(a[i][0] + b[0][j], a[i][i] + b[i][j]));\n\t\t\tc[0][j] = min(c[0][j], a[0][i] + b[i][j]);\n\t\t}\n\t}\n\treturn c;\n}\n \nstruct minqueue{\n\tvector<pair<mat, mat>> st1, st2;\n\t\n\tvoid push(const mat &a){\n\t\tif (!st1.empty())\n\t\t\tst1.push_back({a, mul(st1.back().second, a, true)});\n\t\telse\n\t\t\tst1.push_back({a, a});\n\t}\n\t\n\tvoid pop(){\n\t\tif (st2.empty()){\n\t\t\tst2 = st1;\n\t\t\treverse(st2.begin(), st2.end());\n\t\t\tst1.clear();\n\t\t\tassert(!st2.empty());\n\t\t\tst2[0].second = st2[0].first;\n\t\t\tforn(i, int(st2.size()) - 1)\n\t\t\t\tst2[i + 1].second = mul(st2[i + 1].first, st2[i].second, false);\n\t\t}\n\t\tst2.pop_back();\n\t}\n\t\n\tint get(){\n\t\tif (st1.empty()) return st2.back().second[0][0];\n\t\tif (st2.empty()) return st1.back().second[0][0];\n\t\tint ans = INF;\n\t\tforn(i, D) ans = min(ans, st2.back().second[0][i] + st1.back().second[i][0]);\n\t\treturn ans;\n\t}\n};\n \nmat tran[D];\n \nvoid init(int d){\n\tforn(i, D) forn(j, D) tran[d][i][j] = INF;\n\tfor (int i = 1; i <= 9; ++i){\n\t\ttran[d][i][i] = i;\n\t\ttran[d][i][0] = i;\n\t}\n\ttran[d][0][d] = 0;\n}\n \nint main() {\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tfor (int i = 1; i <= 9; ++i) init(i);\n\tint n, k;\n\tcin >> n >> k;\n\tstring s;\n\tcin >> s;\n\tminqueue q;\n\tforn(i, n){\n\t\tq.push(tran[s[i] - '0']);\n\t\tif (i - k >= 0) q.pop();\n\t\tif (i - k >= -1) cout << q.get() << ' ';\n\t}\n\tcout << '\\n';\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "matrices"
    ],
    "rating": 3200
  },
  {
    "contest_id": "2005",
    "index": "A",
    "title": "Simple Palindrome",
    "statement": "Narek has to spend 2 hours with some 2-year-old kids at the kindergarten. He wants to teach them competitive programming, and their first lesson is about palindromes.\n\nNarek found out that the kids only know the vowels of the English alphabet (the letters $\\mathtt{a}$, $\\mathtt{e}$, $\\mathtt{i}$, $\\mathtt{o}$, and $\\mathtt{u}$), so Narek needs to make a string that consists of vowels only. After making the string, he'll ask the kids to count the number of subsequences that are palindromes. Narek wants to keep it simple, so he's looking for a string such that the amount of palindrome subsequences is minimal.\n\nHelp Narek find a string of length $n$, consisting of \\textbf{lowercase} English \\textbf{vowels only} (letters $\\mathtt{a}$, $\\mathtt{e}$, $\\mathtt{i}$, $\\mathtt{o}$, and $\\mathtt{u}$), which \\textbf{minimizes} the amount of \\textbf{palindrome$^{\\dagger}$ subsequences$^{\\ddagger}$} in it.\n\n$^{\\dagger}$ A string is called a palindrome if it reads the same from left to right and from right to left.\n\n$^{\\ddagger}$ String $t$ is a subsequence of string $s$ if $t$ can be obtained from $s$ by removing several (possibly, zero or all) characters from $s$ and concatenating the remaining ones, without changing their order. For example, $\\mathtt{odocs}$ is a subsequence of $c{\\textcolor{red}{od}}ef{\\textcolor{red}{o}}r{\\textcolor{red}{c}}e{\\textcolor{red}{s}}$.",
    "tutorial": "If the the numbers of vowels are fixed, how to arrange them to get the best possible answer? How to choose the numbers of vowels? Should they be as close, as possible? Let's define the numbers of vowels by $a_0, \\cdots, a_4$ and assume we have fixed them. Obviously, $a_0 + \\cdots + a_4 = n$. At first, let's not consider the empty string as it doesn't change anything. Then, the number of palindrome subsequences will be at least $A = 2^{a_0} + \\cdots + 2^{a_4} - 5$ (every subsequence consisting of the same letter minus the five empty strings). Now, notice that if we put the same characters consecutively then the answer would be exactly $A$, and that would be the best possible answer for that fixed numbers (there cannot be other palindrome subsequences because if the first and last characters are the same, then all the middle part will be the same as well). Now, we need to find the best array $a$. To do this, let's assume there are 2 mumbers $x$ and $y$ in the array such that $x + 2 \\leq y$. Then, $2^x + 2^y > 2 \\cdot 2^{y-1} \\geq 2^{x+1} + 2^{y-1}$. This means, that replacing $x$ and $y$ with $x+1$ and $y-1$ will not change the sum of the array $a$ but will make the number of palindrome subsequences smaller. We can do this replacing process until no two numbers in $a$ have difference bigger than $1$. Actually, there is only one such array (not considering its permutations) and it contains only $(n / 5)$-s and $((n / 5) + 1)$-s.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst string VOWELS = \"aeiou\";\n\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0); cout.tie(0);\n\n\tint t; cin >> t; // test cases\n\n\twhile (t--) {\n\t\tint n; cin >> n; // string length\n\n\t\tvector<int> v(5, n / 5);                // n - (n % 5) numbers should be (n / 5)\n\t\tfor (int i = 0; i < n % 5; i++) v[i]++; // and the others should be (n / 5) + 1\n\n\t\tfor (int i = 0; i < 5; i++) for (int j = 0; j < v[i]; j++) cout << VOWELS[i]; // output VOWELS[i] v[i] times\n\t\tcout << \"\\n\";\n\t}\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2005",
    "index": "B2",
    "title": "The Strict Teacher (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only differences between the two versions are the constraints on $m$ and $q$. In this version, $m, q \\le 10^5$. You can make hacks only if both versions of the problem are solved.}\n\nNarek and Tsovak were busy preparing this round, so they have not managed to do their homework and decided to steal David's homework. Their strict teacher noticed that David has no homework and now wants to punish him. She hires other teachers to help her catch David. And now $m$ teachers together are chasing him. Luckily, the classroom is big, so David has many places to hide.\n\nThe classroom can be represented as a one-dimensional line with cells from $1$ to $n$, inclusive.\n\nAt the start, all $m$ teachers and David are in \\textbf{distinct} cells. Then they make moves. During each move\n\n- David goes to an adjacent cell or stays at the current one.\n- Then, each of the $m$ teachers simultaneously goes to an adjacent cell or stays at the current one.\n\nThis continues until David is caught. David is caught if any of the teachers (possibly more than one) is located in the same cell as David. \\textbf{Everyone sees others' moves, so they all act optimally.}\n\nYour task is to find how many moves it will take for the teachers to catch David if they all act optimally.\n\nActing optimally means the student makes his moves in a way that maximizes the number of moves the teachers need to catch him; and the teachers coordinate with each other to make their moves in a way that minimizes the number of moves they need to catch the student.\n\nAlso, as Narek and Tsovak think this task is easy, they decided to give you $q$ queries on David's position.",
    "tutorial": "There are only few cases. Try finding them and handling separately. For the easy version, there are three cases and they can be considered separately. Case 1: David is in the left of both teachers. In this case, it is obvious that he needs to go as far left as possible, which is cell $1$. Then, the time needed to catch David will be $b_1-1$. Case 2: David is in the right of both teachers. In this case, similarly, David needs to go as far right as possible, which is cell $n$. Then, the time needed to catch David will be $n-b_2$. Case 3: David is between the two teachers. In this case, David needs to stay in the middle (if there are two middle cells, it doesn't matter which one is picked as the middle) of two teachers, so they both have to come closer to him simultaneously. So, they will need the same amount of time, which will be $(b_2-b_1) / 2$. Notice, that David can always go to the middle cell not depending on his cell number. What changes in Case 3 if there are more than two teachers? For this version, there are three cases, too. Case 1 and Case 2 from the above solution are still correct, but the last one should be changed a bit because now it is important between which two consecutive teachers David is. To find that teachers, we can use binary search (after sorting $b$, of course). After finding that David is between teachers $i$ and $i+1$, the answer is $(b_{i+1}-b_i) / 2$, just like the easy version.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0); cout.tie(0);\n\n\tint t; cin >> t; // test cases\n\n\twhile (t--) {\n\t\tint n, m, q; cin >> n >> m >> q;\n\n\t\tvector<int> a(m);\n\t\tfor (int i = 0; i < m; i++) cin >> a[i];\n\n\t\tsort(a.begin(), a.end());\n\n\t\tfor (int i = 1; i <= q; i++) {\n\t\t\tint b; cin >> b;\n\t\t\tint k = upper_bound(a.begin(), a.end(), b) - a.begin(); // finding the first teacher at right\n\n\t\t\tif (k == 0) cout << a[0] - 1 << ' ';          // case 1\n\t\t\telse if (k == m) cout << n - a[m - 1] << ' '; // case 2\n\t\t\telse cout << (a[k] - a[k - 1]) / 2 << ' ';    // case 3\n\t\t}\n\t\tcout << \"\\n\";\n\t}\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2005",
    "index": "C",
    "title": "Lazy Narek",
    "statement": "Narek is too lazy to create the third problem of this contest. His friend Artur suggests that he should use ChatGPT. ChatGPT creates $n$ problems, each consisting of $m$ letters, so Narek has $n$ strings. To make the problem harder, he combines the problems by selecting some of the $n$ strings \\textbf{possibly none} and concatenating them \\textbf{without altering their order}. His chance of solving the problem is defined as $score_n - score_c$, where $score_n$ is Narek's score and $score_c$ is ChatGPT's score.\n\nNarek calculates $score_n$ by examining the selected string (he moves from left to right). He initially searches for the letter $\"n\"$, followed by $\"a\"$, $\"r\"$, $\"e\"$, and $\"k\"$. Upon finding all occurrences of these letters, he increments $score_n$ by $5$ and resumes searching for $\"n\"$ again (he doesn't go back, and he just continues from where he left off).\n\nAfter Narek finishes, ChatGPT scans through the array and increments $score_c$ by $1$ for each letter $\"n\"$, $\"a\"$, $\"r\"$, $\"e\"$, or $\"k\"$ that Narek fails to utilize (note that if Narek fails to complete the last occurrence by finding all of the $5$ letters, then all of the letters he used are counted in ChatGPT's score $score_c$, and Narek doesn't get any points if he doesn't finish finding all the 5 letters).\n\nNarek aims to maximize the value of $score_n - score_c$ by selecting the most optimal subset of the initial strings.",
    "tutorial": "A greedy approach doesn't work because the end of one string can connect to the beginning of the next. Try thinking in terms of dynamic programming. Before processing the next string, we only need to know which letter we reached from the previous selections. Let's loop through the $n$ strings and define $dp_i$ as the maximal answer if we are currently looking for the $i$-th letter in the word \"Narek\". Initially, $dp_0 = 0$, and $dp_1 = \\cdots = dp_4 = -\\infty$. For the current string, we brute force on all five letters we could have previously ended on. Let's say the current letter is the $j$-th, where $0 \\leq j < 5$. If $dp_j$ is not $-\\infty$, we can replicate the process of choosing this string for our subset and count the score difference (the answer). Eventually, we will reach to some $k$-th letter in the word \"Narek\". If reaching $dp_k$ from $dp_j$ is bigger than the previous value of $dp_k$, we update $dp_k$ by $dp_j + counted\\texttt{_}score$. Finally, the answer is $dp_i - 2 \\cdot i$. This is because if $i$ is not $0$, then we didn't fully complete the entire word (the problem states that in this case, these letters are counted in the GPT's score, so we subtract this from our score and add it to the GPT's). Note: Updating the array $dp$ is incorrect, because we may update some $dp_i$ for some string, and then use that updated $dp_i$ for that same string. To avoid this, we can use two arrays and overwrite one to the other for each string. Time complexity: $O(n*m*5)$ or $O(n*m*25)$, depending on the implementation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst string narek = \"narek\";\n\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0); cout.tie(0);\n\n\tint t; cin >> t; // test cases\n\n\twhile (t--) {\n\t\tint n, m; cin >> n >> m;\n\n\t\tvector<string> s(n);\n\t\tfor (int i = 0; i < n; i++) cin >> s[i];\n\n\t\tvector<int> dp(5, int(-1e9)), ndp;\n\t\tdp[0] = 0;\n\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tndp = dp; // overwriting dp\n\n\t\t\tfor (int j = 0; j < 5; j++) {\n\t\t\t\tif (dp[j] == int(-1e9)) continue;\n\n\t\t\t\tint counted_score = 0, next = j;\n\n\t\t\t\tfor (int k = 0; k < m; k++) {\n\t\t\t\t\tint ind = narek.find(s[i][k]);\n\n\t\t\t\t\tif (ind == -1) continue; // if s[i][k] is not a letter of \"narek\"\n\n\t\t\t\t\tif (next == ind) { // if s[i][k] is the next letter\n\t\t\t\t\t\tnext = (next + 1) % 5;\n\t\t\t\t\t\tcounted_score++;\n\t\t\t\t\t}\n\t\t\t\t\telse counted_score--;\n\t\t\t\t}\n\n\t\t\t\tndp[next] = max(ndp[next], dp[j] + counted_score);\n\t\t\t}\n\n\t\t\tdp = ndp; // overwriting dp back\n\t\t}\n\n\t\tint ans = 0;\n\t\tfor (int i = 0; i < 5; i++) ans = max(ans, dp[i] - 2 * i); // checking all letters\n\n\t\tcout << ans << \"\\n\";\n\t}\n}",
    "tags": [
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2005",
    "index": "D",
    "title": "Alter the GCD",
    "statement": "You are given two arrays $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_n$.\n\nYou must perform the following operation \\textbf{exactly once}:\n\n- choose any indices $l$ and $r$ such that $1 \\le l \\le r \\le n$;\n- swap $a_i$ and $b_i$ for all $i$ such that $l \\leq i \\leq r$.\n\nFind the maximum possible value of $\\text{gcd}(a_1, a_2, \\ldots, a_n) + \\text{gcd}(b_1, b_2, \\ldots, b_n)$ after performing the operation exactly once. Also find the number of distinct pairs $(l, r)$ which achieve the maximum value.",
    "tutorial": "Find the the maximal sum of $\\gcd$-s first. Try checking whether it is possible to get some fixed $\\gcd$-s for $a$ and $b$ (i.e. fix the $\\gcd$-s and try finding a sufficient range to swap) Choosing a range is equivalent to choosing a prefix and a suffix. Which prefixes and suffixes are needed to be checked to find the maximal sum of $\\gcd$-s? There are only few different values in the $\\gcd$-s of prefixes and suffixes. Try finding a limit for them. After finding the maximal sum of $\\gcd$-s, try dynamic programming to find the nubmer of ways. Let $M$ be the maximal value of $a$. Finding the maximal sum of $\\gcd$-s. Let's define $p_i$ and $q_i$ as the $\\gcd$-s of the $i$-th prefixes of $a$ and $b$, respectively. Then, for each index $i$, such that $1 < i \\leq n$, $p_i$ is a divisor of $p_{i-1}$, so either $p_i=p_{i-1}$ or $p_i \\leq p_{i-1} / 2$ (the same holds for $q$). This means, that there are at most $\\log(M)$ different values in each of $p$ and $q$. The same holds for suffixes. Now, let's assume we have fixed the $\\gcd$-s of $a$ and $b$ after the operation as $A$ and $B$. Now, let's consider the shortest of the longest prefixes of $a$ and $b$ having $\\gcd$ $A$ and $B$, respectively. If the swapped range has intersection with that prefix, we can just not swap the intersection as it cannot worsen the answer. The same holds for the suffix. This means, that the swapped range should be inside the middle part left between that prefix and suffix. But the first and last elements of the middle part have to be changed, because they didn't allow us to take longer prefix or suffix. So, the part that has to be swapped is that middle part. Then, we can see that the only sufficient lengths of the longest prefixes and suffixes are the places where one of them (i.e. in array $a$ or $b$) changes (i.e. $i$ is a sufficient prefix if $p_i \\neq p_{i+1}$ or $q_i \\neq q_{i+1}$, because otherwise we would have taken longer prefix). So, we can brute force through the sufficient prefixes and suffixes (the number of each is at most $\\log(M)$). All we are left with is calculating the $\\gcd$-s of the middle parts to update the answer, which can be done with sparse table. Now, let's brute force through the sufficient prefixes. Assume we are considering the prefix ending at $i$. This means the left border of the range will start at $i+1$. Then, we can brute force the right border starting from $i+1$. In each iteration, we keep $\\gcd$-s of the range and update the answer. To proceed to the next one, we only need to update the $\\gcd$-s with the next numbers of $a$ and $b$. Finding the number of ways. Let's fix the $\\gcd$-s of $a$ and $b$ and compute $dp_{i,j}$ ($1 \\leq i \\leq n$ and $0 \\leq j < 3$), which shows: the number of ways to get the fixed $\\gcd$-s in the interval $[1, i]$ without swapping a range, if $j=0$ the number of ways to get the fixed $\\gcd$-s in the interval $[1, i]$ without swapping a range, if $j=0$ the number of ways to get the fixed $\\gcd$-s in the interval $[1, i]$ with a range started swapping but not ended yet, if $j=1$ the number of ways to get the fixed $\\gcd$-s in the interval $[1, i]$ with a range started swapping but not ended yet, if $j=1$ the number of ways to get the fixed $\\gcd$-s in the interval $[1, i]$ with an already swapped range, if $j=2$ the number of ways to get the fixed $\\gcd$-s in the interval $[1, i]$ with an already swapped range, if $j=2$ In all $dp$-s we assume we don't swap $a_1$ and $b_1$ Then, we calculate the $dp$ with $i$ starting from $1$. In each iteration, we check if the pair $(a_i, b_i)$ is sufficient, or no (we consider them swapped, if $j=1$). If it is not sufficient, we don't do anything. Otherwise: $dp_{i,0} = dp_{i-1,0}$ $dp_{i,0} = dp_{i-1,0}$ $dp_{i,1} = dp_{i-1,0}+dp_{i-1,1}$ $dp_{i,1} = dp_{i-1,0}+dp_{i-1,1}$ $dp_{i,2} = dp_{i-1,0}+dp_{i-1,1}+dp_{i-1,2}$ $dp_{i,2} = dp_{i-1,0}+dp_{i-1,1}+dp_{i-1,2}$ After the calculations the answer is $dp_{n,0}+dp_{n,1}+dp_{n,2}$. But we have to subtract $n$ from the answer if not swapping any range gives the expected sum of $\\gcd$-s, because we counted that case once in $dp_{n, 0}$ and $n-1$ times when adding $dp_{i-1,0}$ to $dp_{i,2}$. We also check the swaps of prefixes separately. Finally, the only thing left is to brute force through the $\\gcd$-s of $a$ and $b$ in a smart way. As $a_1$ and $b_1$ are not swapped, the $\\gcd$-s of the arrays should be their divisors. Then, it is enough to brute force through the divisors of $a_1$ only (the $\\gcd$ of $a$), as the other $\\gcd$ is derieved from their sum. And since $a_1$ has at most $\\sqrt[3]{a_i}$ ($1344$, to be precise) divisors, the solution will be fast enough (actually, there are way too few cases when the derieved $\\gcd$ of $b$ is actually a divisor of $b_1$). Finalizing. But this solution is not fast enough when all $a_1$-s are $10^9$, because they have $\\sqrt[3]{a_1}$ divisors, but in order to find them, we need to do $\\sqrt{a_1}$ checks. It means, that the time complexity is $O(t * \\sqrt{a_1})$, which is slow. To handle this, we can write another slower solution which doesn't depend on $a_1$. One of them is the following solution working in $O(n^2* \\log(M))$, but $\\log(M)$ comes from $\\gcd$, which is actually amortized and faster. We brute force through the left border, and then through the right border of the swapping range, keeping its $\\gcd$ and checking each of them. The reason we need this slow solution is that now, we can use it for $n\\leq20$. But for bigger $n$-s, the first solution will work, because there are at most $t/20$ such $n$-s. So the time complexity for them will be $O(n*\\log^2(M))$ for the sum of the $\\gcd$-s and $O(t/20*\\sqrt{M} + \\sqrt[3]{M} * n)$ for the number of ways. For the small $n$-s, the time complexity will be $O(n*\\log(M)*20)$. See the formal proof below. Let's say there are $c_i$ $n$-s equal to $i$. We know, that $\\displaystyle\\sum_{i=1}^{20} (c_i\\cdot i) \\leq n$. Then the time complexity will be $O(\\displaystyle\\sum_{i=1}^{20} (c_i\\cdot i^2* \\log(M))) \\leq O((\\displaystyle\\sum_{i=1}^{20} (c_i\\cdot i))*\\log(M)*20) \\leq O(n*\\log(M)*20)$. Time complexity: $O(n*\\log^2(M) + t/20*\\sqrt{M} + \\sqrt[3]{M} * n + n*\\log(M)*20) \\approx O(10^9)$. It is actually a very rough estimation with amortized $\\log(M)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N = 200005;\nint a[N], b[N];\nint pa[N], pb[N], sa[N], sb[N];\nint n;\n\nll dp[N][3];\n\nll solve_one(ll ga, ll gb)\n{\n\tif (ga <= 0 || gb <= 0) return 0; // invalid fixed gcd(s)\n\tif (b[1] % gb) return 0; // ivanlid gcd of b\n\n\tfor (int i = 0; i <= n; i++) for (int j = 0; j < 3; j++) dp[i][j] = 0; // intializing\n\n\tdp[1][0] = 1; // base case\n\tfor (int i = 2; i <= n; i++) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tfor (int k = 0; k <= j; k++) {\n\t\t\t\tbool flag = 1;\n\n\t\t\t\tif (j == 1) swap(a[i], b[i]); // if swapping\n\n\t\t\t\tif (a[i] % ga) flag = 0; // checking sufficiency\n\t\t\t\tif (b[i] % gb) flag = 0; // checking sufficiency\n\n\t\t\t\tif (j == 1) swap(a[i], b[i]); // if swapping\n\n\t\t\t\tif (flag) dp[i][j] += dp[i - 1][k];\n\n\t\t\t\t/*\n\t\t\t\t\tif j is 0, we can use only k=0 (not started swapping yet)\n\t\t\t\t\tif j is 1, we can use both k=0 (starging swapping) and k=1 (currently swapping)\n\t\t\t\t\tif j is 2, we can use k=0 (no swaps at all), k=1 (finishing swapping), k=2 (already finished swapping)\n\t\t\t\t*/\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[n][0] + dp[n][1] + dp[n][2];\n}\n\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\n\tint t; cin >> t; // test cases\n\n\twhile (t--) {\n\t\tcin >> n;\n\n\t\tfor (int i = 1; i <= n; i++) cin >> a[i];\n\t\tfor (int i = 1; i <= n; i++) cin >> b[i];\n\n\t\tsa[n + 1] = sb[n + 1] = 0; // initializing\n\n\t\tfor (int i = 1; i <= n; i++) { // calculating the gcd-s of prefixes and suffixes of a and b\n\t\t\tpa[i] = gcd(pa[i - 1], a[i]);\n\t\t\tpb[i] = gcd(pb[i - 1], b[i]);\n\n\t\t\tsa[n - i + 1] = gcd(sa[n - i + 2], a[n - i + 1]);\n\t\t\tsb[n - i + 1] = gcd(sb[n - i + 2], b[n - i + 1]);\n\t\t}\n\n\t\tif (n <= 300) { // slower solution\n\t\t\tint max_gcd = 0, ways = 0;\n\n\t\t\tfor (int i = 1; i <= n; i++) {\n\t\t\t\tint ga = 0, gb = 0; // current gcd-s of the range\n\n\t\t\t\tfor (int j = i; j <= n; j++)\n\t\t\t\t{\n\t\t\t\t\tga = gcd(ga, a[j]);\n\t\t\t\t\tgb = gcd(gb, b[j]);\n\n\t\t\t\t\tint ca = gcd(pa[i - 1], gcd(sa[j + 1], gb)); // gcd of a after the operation\n\t\t\t\t\tint cb = gcd(pb[i - 1], gcd(sb[j + 1], ga)); // gcd of b after the operation\n\n\t\t\t\t\tif (ca + cb > max_gcd) {\n\t\t\t\t\t\tmax_gcd = ca + cb;\n\t\t\t\t\t\tways = 1;\n\t\t\t\t\t}\n\t\t\t\t\telse if (ca + cb == max_gcd) ways++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcout << max_gcd << ' ' << ways << \"\\n\";\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tint max_gcd = pa[n] + pb[n];\n\n\t\tfor (int i = 2; i <= n; i++) {\n\t\t\tif (pa[i] == pa[i - 1] && pb[i] == pb[i - 1]) continue; // checking sufficiency of the prefix\n\n\t\t\tint ga = 0, gb = 0; // current gcd-s of the range\n\n\t\t\tfor (int j = i; j <= n; j++) {\n\t\t\t\tga = gcd(ga, a[j]); // updating gcd of the range of a\n\t\t\t\tgb = gcd(gb, b[j]); // updating gcd of the range of b\n\n\t\t\t\tint ca = gcd(pa[i - 1], gcd(sa[j + 1], gb)); // gcd of a after the operation\n\t\t\t\tint cb = gcd(pb[i - 1], gcd(sb[j + 1], ga)); // gcd of b after the operation\n\n\t\t\t\tmax_gcd = max(max_gcd, ca + cb); // updating the answer\n\t\t\t}\n\t\t}\n\n\t\tll ans = 0;\n\t\tfor (int ga = 1; ga * ga <= a[1]; ga++) {\n\t\t\tif (a[1] % ga) continue;\n\n\t\t\tans += solve_one(ga, max_gcd - ga); // counting for fixed gcd-s\n\t\t\tif (ga * ga == a[1]) continue;\n\t\t\tans += solve_one(a[1] / ga, max_gcd - a[1] / ga); // counting for fixed gcd-s\n\t\t}\n\n\t\tif (pa[n] + pb[n] == max_gcd) ans -= n; // n-1 times updated with j=2 and k=0 and one time with no swaps at all (dp[n][0])\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tif (gcd(pa[i], sb[i + 1]) + gcd(pb[i], sa[i + 1]) == max_gcd) ans++; // checking prefixes\n\t\t}\n\n\t\tcout << max_gcd << ' ' << ans << \"\\n\";\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "divide and conquer",
      "implementation",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2005",
    "index": "E2",
    "title": "Subtangle Game (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The differences between the two versions are the constraints on all the variables. You can make hacks only if both versions of the problem are solved.}\n\nTsovak and Narek are playing a game. They have an array $a$ and a matrix $b$ of integers with $n$ rows and $m$ columns, numbered from $1$. The cell in the $i$-th row and the $j$-th column is $(i, j)$.\n\nThey are looking for the elements of $a$ in turns; Tsovak starts first. Each time a player looks for a cell in the matrix containing the current element of $a$ (Tsovak looks for the first, then Narek looks for the second, etc.). Let's say a player has chosen the cell $(r, c)$. The next player has to choose his cell in the submatrix starting at $(r + 1, c + 1)$ and ending in $(n, m)$ (the submatrix can be empty if $r=n$ or $c=m$). If a player cannot find such a cell (or the remaining submatrix is empty) or the array ends (the previous player has chosen the last element), then he loses.\n\nYour task is to determine the winner if the players play optimally.\n\n\\textbf{Note: since the input is large, you may need to optimize input/output for this problem.}\n\nFor example, in C++, it is enough to use the following lines at the start of the main() function:\n\n\\begin{verbatim}\nint main() {\nios_base::sync_with_stdio(false);\ncin.tie(NULL); cout.tie(NULL);\n}\n\n\\end{verbatim}",
    "tutorial": "What happens, when some number appears in $a$ more than once? How to use the constraint on the numbers of the array and the matrix? Let's say some number $x$ accures in $a$ more than once. Let's define by $u$ and $v$ the first two indexes of $a$, such that $u<v$ and $a_u=a_v=x$. When a player reahces $a_u = x$, it is always optimal to choose such cell that after it no $x$ can be choosen (there is no other $x$ in the remaining submatrix). This is true, because if the player would win when choosing that \"inside\" $x$ (let's call him $x_2$), he would also win in that bigger matrix. But if he would lose, that means there is some number inside the submatrix left from $x_2$ that is winning for the other player, so the latter can choose that not depending on the opponent's choose. So, when a player reaches $a_v$, he will lose, which is the same as the array $a$ ends there. This gives us the chance to \"stop\" array $a$ at the first index where some number appears the second time. Now, as all the numbers are not greater than $7$, we can shorten array $a$ to at most $7$ elements. Then, we can keep $dp_{k,i,j}$ which shows whether the player, starting from $k$-th position of the array $a$ (i.e. considering only the suffix starting at $k$, but not necessarily Tsovak has to start), will win, or not. To calculate the $dp$, we can go from the bottom-right cell of the matrix to the upper-left cell. $dp_{k,i,j}$ wins, if at least ono of these happens: $i<n$ and $dp_{k,i+1,j}$ wins $i<n$ and $dp_{k,i+1,j}$ wins $j<m$ and $dp_{k,i,j+1}$ wins $j<m$ and $dp_{k,i,j+1}$ wins $b_{i,j}=a_k$ and ($k=l$ or $i=n$ or $j=m$ or $dp_{k+1,i+1,j+1}$ loses) $b_{i,j}=a_k$ and ($k=l$ or $i=n$ or $j=m$ or $dp_{k+1,i+1,j+1}$ loses) Finally, if $dp_{1,1,1}$ wins, Tsovak wins, otherwise, Narek wins. Time complexity: $O(n*m)$. Consider the same $dp$ as in E1. Can you eliminate one of the states? Instead of $dp_{k,i,j}$, eliminate $k$ from the state. Instead, assign some array index to the $dp$ value to keep information about the array. Keep $dp0_{i,j}$ which shows the smalles even $k$, such that $dp_{k,i,j}$ wins. Do the same for odd ones. Let's define $dp0_{i,j}$ as the minimal even index $k$ ($1 \\le k \\le l$), such that $dp_{k,i,j}$ wins. Define $dp1_{i,j}$ similarly for odds. First, fill all of them with $\\infty$. Then, compute them from the bottom-right cell of the matrix to the top-left cell of the matrix. $dp0_{i,j}$ will be the minimal of the following three values: $dp0_{i+1, j}$ (if $i=n$ there will be no submatrix left, so $dp0_{i+1,j}$ will be $\\infty$) $dp0_{i+1, j}$ (if $i=n$ there will be no submatrix left, so $dp0_{i+1,j}$ will be $\\infty$) $dp0_{i,j+1}$ $dp0_{i,j+1}$ Let's define by $ind$ the index of $b_{i,j}$ in $a$ (there are no duplicates in $a$ and if there is no $b_{i,j}$ there, assign $\\infty$ to $ind$). If $dp1_{i+1,j+1}>ind+1$, which means that $dp_{ind+1,i+1,j+1}$ loses and ensues the current player's win, then the value of this part will be $ind$. Otherwise, $\\infty$. This is because, in other cases, the opponent either had a winning position starting from $ind+1$ or even earlier in the game, so we can't win from that index. Let's define by $ind$ the index of $b_{i,j}$ in $a$ (there are no duplicates in $a$ and if there is no $b_{i,j}$ there, assign $\\infty$ to $ind$). If $dp1_{i+1,j+1}>ind+1$, which means that $dp_{ind+1,i+1,j+1}$ loses and ensues the current player's win, then the value of this part will be $ind$. Otherwise, $\\infty$. This is because, in other cases, the opponent either had a winning position starting from $ind+1$ or even earlier in the game, so we can't win from that index. We count $dp1$ similarly (but we count $dp0$ and $dp1$ simultaneously for every $(i,j)$). Lastly, if $dp1_{1,1}=1$, then Tsovak wins, otherwise, Narek wins.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int L = 1505, N = 1505, M = 1505;\nint a[L], b[N][M];\nint l, n, m;\n\nint ind[N * M];\n\nint dp0[N][M], dp1[N][M];\n\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0); cout.tie(0);\n\n\tint t; cin >> t; // test cases\n\n\twhile (t--) {\n\t\tint i, j;\n\n\t\tcin >> l >> n >> m;\n\n\t\tfor (i = 1; i <= l; i++) cin >> a[i];\n\t\tfor (i = 1; i <= l; i++) {\n\t\t\tif (ind[a[i]]) { // checking if a[i] has already appeared\n\t\t\t\tl = i - 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tind[a[i]] = i;\n\t\t}\n\t\tfor (i = 1; i <= n; i++) for (j = 1; j <= m; j++) cin >> b[i][j];\n\n\n\t\tfor (i = 0; i <= n + 1; i++) for (j = 0; j <= m + 1; j++) dp0[i][j] = dp1[i][j] = int(1e9); // initializing dp0 and dp1\n\n\t\tfor (i = n; i >= 1; i--) {\n\t\t\tfor (j = m; j >= 1; j--) {\n\t\t\t\tdp0[i][j] = min(dp0[i + 1][j], dp0[i][j + 1]); // default update\n\t\t\t\tdp1[i][j] = min(dp1[i + 1][j], dp1[i][j + 1]); // default update\n\n\t\t\t\tif (!ind[b[i][j]]) continue; // if there is no b[i][j] in a then it cannot be taken by a player\n\n\t\t\t\tif (ind[b[i][j]] % 2 == 0 && ind[b[i][j]] + 3 <= dp1[i + 1][j + 1]) dp0[i][j] = min(dp0[i][j], ind[b[i][j]]); // if dp1 cannot win after dp0 choosing b[i][j]\n\t\t\t\tif (ind[b[i][j]] % 2 == 1 && ind[b[i][j]] + 3 <= dp0[i + 1][j + 1]) dp1[i][j] = min(dp1[i][j], ind[b[i][j]]); // if dp0 cannot win after dp1 choosing b[i][j]\n\t\t\t}\n\t\t}\n\n\t\tif (dp1[1][1] == 1) cout << \"T\\n\";\n\t\telse cout << \"N\\n\";\n\n\t\tfor (i = 1; i <= l; i++) ind[a[i]] = 0; // changing used ind[i]-s back to 0-s for the next test case\n\t}\n}",
    "tags": [
      "data structures",
      "dp",
      "games",
      "greedy",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2006",
    "index": "A",
    "title": "Iris and Game on the Tree",
    "statement": "Iris has a tree rooted at vertex $1$. Each vertex has a value of $\\mathtt 0$ or $\\mathtt 1$.\n\nLet's consider a leaf of the tree (the vertex $1$ is never considered a leaf) and define its weight. Construct a string formed by the values of the vertices on the path starting at the root and ending in this leaf. Then the weight of the leaf is the difference between the number of occurrences of $\\mathtt{10}$ and $\\mathtt{01}$ substrings in it.\n\nTake the following tree as an example. Green vertices have a value of $\\mathtt 1$ while white vertices have a value of $\\mathtt 0$.\n\n- Let's calculate the weight of the leaf $5$: the formed string is $\\mathtt{10110}$. The number of occurrences of substring $\\mathtt{10}$ is $2$, the number of occurrences of substring $\\mathtt{01}$ is $1$, so the difference is $2 - 1 = 1$.\n- Let's calculate the weight of the leaf $6$: the formed string is $\\mathtt{101}$. The number of occurrences of substring $\\mathtt{10}$ is $1$, the number of occurrences of substring $\\mathtt{01}$ is $1$, so the difference is $1 - 1 = 0$.\n\nThe score of a tree is defined as the number of leaves with non-zero weight in the tree.\n\nBut the values of some vertices haven't been decided and will be given to you as $?$. Filling the blanks would be so boring, so Iris is going to invite Dora to play a game. On each turn, one of the girls chooses any of the remaining vertices with value $?$ and changes its value to $\\mathtt{0}$ or $\\mathtt{1}$, \\textbf{with Iris going first}. The game continues until there are no vertices with value $\\mathtt{?}$ left in the tree. Iris aims to maximize the score of the tree, while Dora aims to minimize that.\n\nAssuming that both girls play optimally, please determine the final score of the tree.",
    "tutorial": "Consider a formed string. Let's delete the useless part that doesn't contribute to the number of $\\tt{01}$ and $\\tt{10}$ substrings. We will get a string where each pair of adjacent bits is different. For example, $\\tt{110001}\\rightarrow\\tt{101}$. Then the weight of a leaf depends on the parity of the length of the string. You can also see that the weight is non-zero if the value of the root is different from the value of the leaf. If the value of the root is already decided, the strategy is quite simple: just fill the values of the leaf nodes with a value different from or equal to the root. It's easy to calculate the answer. If the value of the root has not yet been decided, it seems optimal to fill it first. That's because some values of the leaves have already been decided. When Iris chooses to colour the root at the very beginning, she will make the initial value larger (which is the larger one of the counts of $\\tt 0$ and $\\tt 1$ in the leaves). However, this can go wrong when there are equal numbers of $\\tt 0$ and $\\tt 1$ in the leaf nodes. The first to colour the root may lose the advantage of being the first (and when there are odd numbers of $\\tt ?$ in the initial leaf nodes, Iris will colour one node less). In this situation, the optimal choice is to colour the unimportant nodes - the nodes that are neither the root nor a leaf. If there is an odd number of $\\tt ?$ in the unimportant nodes, then Dora will have to colour the root (after filling the $\\tt ?$ in the unimportant nodes one by one), which will cause Iris to colour the leaves first. When Dora colours a leaf, Iris can colour another leaf with the opposite colour if there is at least one leaf left; and colour the root with the opposite colour if there is none left. So Dora will never choose to colour a leaf first in this case. To judge whether a node is a leaf, you can record the degrees of the nodes. The time complexity is $\\mathcal O(n)$.",
    "code": "T = int(input())\n \nfor _ in range(T) :\n    n = int(input())\n    x, y, z, w = 0, 0, 0, 0\n    deg = [0] * (n + 1)\n    for __ in range(n - 1) :\n        u, v = map(int, input().split())\n        deg[u] += 1\n        deg[v] += 1\n    s = \" \" + input()\n    for i in range(2, n + 1) :\n        if deg[i] == 1 :\n            if s[i] == '?' :\n                z += 1\n            elif s[i] == '0' :\n                x += 1\n            else :\n                y += 1\n        elif s[i] == '?' :\n            w += 1\n    if s[1] == '0' :\n        print(y + (z + 1) // 2)\n    elif s[1] == '1' :\n        print(x + (z + 1) // 2)\n    else :\n        print(max(x, y) + (z + (w % 2 if x == y else 0)) // 2)",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "games",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2006",
    "index": "B",
    "title": "Iris and the Tree",
    "statement": "Given a rooted tree with the root at vertex $1$. For any vertex $i$ ($1 < i \\leq n$) in the tree, there is an edge connecting vertices $i$ and $p_i$ ($1 \\leq p_i < i$), with a weight equal to $t_i$.\n\nIris does not know the values of $t_i$, but she knows that $\\displaystyle\\sum_{i=2}^n t_i = w$ and each of the $t_i$ is a \\textbf{non-negative integer}.\n\nThe vertices of the tree are numbered in a special way: the numbers of the vertices in each subtree are consecutive integers. In other words, the vertices of the tree are numbered in the order of a depth-first search.\n\n\\begin{center}\n{\\small The tree in this picture satisfies the condition. For example, in the subtree of vertex $2$, the vertex numbers are $2, 3, 4, 5$, which are consecutive integers.}\n\\end{center}\n\n\\begin{center}\n{\\small The tree in this picture does not satisfy the condition, as in the subtree of vertex $2$, the vertex numbers $2$ and $4$ are not consecutive integers.}\n\\end{center}\n\nWe define $\\operatorname{dist}(u, v)$ as the length of the simple path between vertices $u$ and $v$ in the tree.\n\nNext, there will be $n - 1$ events:\n\n- Iris is given integers $x$ and $y$, indicating that $t_x = y$.\n\nAfter each event, Iris wants to know the maximum possible value of $\\operatorname{dist}(i, i \\bmod n + 1)$ \\textbf{independently} for each $i$ ($1\\le i\\le n$). She only needs to know the sum of these $n$ values. Please help Iris quickly get the answers.\n\nNote that when calculating the maximum possible values of $\\operatorname{dist}(i, i \\bmod n + 1)$ and $\\operatorname{dist}(j, j \\bmod n + 1)$ for $i \\ne j$, the unknown edge weights \\textbf{may be different}.",
    "tutorial": "The nodes are numbered by dfs order, which tells us the vertex numbers in one subtree are always consecutive. Let's consider an edge connecting vertex $i$ and $p_i$. Suppose the size of the subtree $i$ is $s_i$, so the vertices are numbered between $[i,i+s_i-1]$. Then for each $j$ that $i\\le j<i+s_i-1$, the path between node $j$ and $j+1$ is always in the subtree, so it doesn't pass the edge. The only two paths that passes edge $(i,p_i)$ is the path between $i-1$ and $i$, and between $i+s_i-1$ and $i+s_i$. Let's calculate the maximum value of $\\text{dist}(i,(i\\bmod n)+1)$. First, if all of the weights of its edges have been determined, then it's already calculated. Otherwise, it's optimal to set one of the edges with undetermined weight with weight $w-\\text{sum of weights of the known edges}$. Then the answer is $w-\\text{sum of weights of the known edges outside the path}$. How to maintain the process? Each time we know the weight of an edge, we specially check whether the weights of the two paths that passes this edge are uniquely determined or not. For all other paths that are not uniquely determined, the contribution of the edge is $-y$ ($y$ is the weight). We can use addition tags to handle this. The time complexity is $O(n)$. Can you solve the problem if the nodes are not numbered by dfs order?",
    "code": "#include <bits/stdc++.h>\n \nnamespace FastIO {\n\ttemplate <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }\n\ttemplate <typename T> inline void write(T x) { if (!x) return; write<T>(x / 10), putchar(x % 10 ^ '0'); }\n\ttemplate <typename T> inline void print(T x) { if (x < 0) putchar('-'), x = -x; else if (x == 0) putchar('0'); write<T>(x); }\n\ttemplate <typename T> inline void print(T x, char en) { if (x < 0) putchar('-'), x = -x; else if (x == 0) putchar('0'); write<T>(x), putchar(en); }\n}; using namespace FastIO;\n \n#define MAXN 200001\nint fa[MAXN], dep[MAXN];\nint c1[MAXN], c2[MAXN], len[MAXN];\n \nvoid solve() {\n\tint N = read<int>(); long long w = read<long long>();\n\tfor (int i = 2; i <= N; ++i) fa[i] = read<int>();\n\tfor (int i = 2; i <= N; ++i) dep[i] = dep[fa[i]] + 1;\n\tfor (int i = 1; i <= N; ++i) len[i] = c1[i] = 0;\n\tfor (int i = 1, x, y; i <= N; ++i) {\n\t\tx = i, y = (i == N ? 1 : i + 1);\n\t\twhile (x != y) {\n\t\t\tif (dep[x] < dep[y]) std::swap(x, y);\n\t\t\t(c1[x] ? c2[x] : c1[x]) = i, x = fa[x], ++len[i];\n\t\t}\n\t}\n\tlong long sum = 0, sur = N;\n\tfor (int i = 1, x; i < N; ++i) {\n\t\tx = read<int>(), sum += read<long long>();\n\t\tif ((--len[c1[x]]) == 0) --sur;\n\t\tif ((--len[c2[x]]) == 0) --sur;\n\t\tprint<long long>(sum * 2 + sur * (w - sum), \" \\n\"[i == N - 1]);\n\t}\n}\n \nint main() { int T = read<int>(); while (T--) solve(); return 0; }\n",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dsu",
      "math",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2006",
    "index": "C",
    "title": "Eri and Expanded Sets",
    "statement": "Let there be a set that contains \\textbf{distinct} positive integers. To expand the set to contain as many integers as possible, Eri can choose two integers $x\\neq y$ from the set such that their average $\\frac{x+y}2$ is still a positive integer and isn't contained in the set, and add it to the set. The integers $x$ and $y$ remain in the set.\n\nLet's call the set of integers consecutive if, after the elements are sorted, the difference between any pair of adjacent elements is $1$. For example, sets $\\{2\\}$, $\\{2, 5, 4, 3\\}$, $\\{5, 6, 8, 7\\}$ are consecutive, while $\\{2, 4, 5, 6\\}$, $\\{9, 7\\}$ are not.\n\nEri likes consecutive sets. Suppose there is an array $b$, then Eri puts all elements in $b$ into the set. If after a finite number of operations described above, the set can become consecutive, the array $b$ will be called brilliant.\n\nNote that if the same integer appears in the array multiple times, we only put it into the set \\textbf{once}, as a set always contains distinct positive integers.\n\nEri has an array $a$ of $n$ positive integers. Please help him to count the number of pairs of integers $(l,r)$ such that $1 \\leq l \\leq r \\leq n$ and the subarray $a_l, a_{l+1}, \\ldots, a_r$ is brilliant.",
    "tutorial": "Let's consider the elements in the final set $a$, and take $b_i=a_i-a_{i-1}$ as its difference array. Observation 1: $b_i$ is odd. Otherwise we can turn $b_i$ into two $\\frac{b_i}{2}$. Observation 2: Adjacent $b_i$ are not different. Suppose $b_i$ and $b_{i+1}$ are different and odd, then $a_{i+1}-a_{i-1}$ is even, and $\\frac{a_{i+1}+a_{i-1}}{2}\\neq a_i$, so $a$ can be larger. Thus, the array $a$ is an arithmetic progression, with an odd tolerance $b_i$. If you notice this, and can also notice the monotonicity, you can maintain $(c,d,len)$ for a range of numbers to show that the final set is an arithmetic progression starting from $c$, consisting of $len$ elements and has tolerance $d$. It's amazing that two pieces of information like this can be merged, so we can use sparse table to maintain. However, there's a better way to solve it. Similar to Euclidean Algorithm, the tolerance is equal to the maximum odd divisor of the gcd of the difference array of $a$, that is, $\\gcd\\{a_i-a_{i-1}\\}$. Then the restriction means that $\\gcd\\{a_i-a_{i-1}\\}$ is a power of $2$. For a fixed point $l$, find the smallest $r$ that interval $[l,r]$ is good. A divisor of a power of $2$ is still a power of $2$, so it has monotonicity, which makes it possible to use two pointers to maintain it in $O(n\\log nV)$ or $O(n\\log V)$. Using sparse table or binary lifting may reach the same complexity. Note that adjacent same numbers should be carefully dealt with. There's a harder but similar version of the problem. Can you solve it? There're $q$ queries: $L,R,k$. Find the number of pairs $(l,r)$ that $L\\le l\\le r\\le R$, and $(\\lvert Q({a_l\\dots a_r}) \\rvert-1) \\cdot k\\ge \\max(a_l\\dots a_r) - \\min(a_l\\dots a_r)$, where $Q(array)$ means the result of putting the array into the set.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define int         long long\n#define pii         pair<int,int>\n#define all(v)      v.begin(),v.end()\n#define pb          push_back\n#define REP(i,b,e)  for(int i=(b);i<(int)(e);++i)\n#define over(x)     {cout<<x<<endl;return;}\n#define cntbit(x)   __buitin_popcount(x)\nint n;\nint a[400005],res[400005],lsteq[400005];\nint st[400005][20];\nint query(int l,int r){\n\tint s=__lg(r-l+1);\n\treturn __gcd(st[l][s],st[r-(1<<s)+1][s]);\n}\nvoid Main() {\n\tcin>>n;\n\tREP(i,0,n)cin>>a[i];\n\t--n;\n\tif(!n)over(1)\n\tREP(i,0,n)st[i][0]=llabs(a[i]-a[i+1]);\n\tREP(j,0,__lg(n)){\n\t\tREP(i,0,n-(1<<(j+1))+1){\n\t\t\tst[i][j+1]=__gcd(st[i][j],st[i+(1<<j)][j]);\n\t\t}\n\t}\n\tlsteq[n]=n;\n\tfor(int i=n-1;i>=0;--i)lsteq[i]=(a[i]==a[i+1]? lsteq[i+1]:i);\n\tint ans=1;\n\tint l=0,r=0;\n\tREP(i,0,n){\n\t\tl=max(l,lsteq[i]);r=max(r,l);\n\t\twhile(r<n&&cntbit(query(l,r))>1)++r;\n\t\tans+=n-r;ans+=lsteq[i]-i+1;\n\t}\n\tcout<<ans<<endl;\n}\nvoid TC() {\n\tint tc=1;\n\tcin>>tc;\n\twhile(tc--){\n\t\tMain();\n\t\tcout.flush();\n\t}\n}\nsigned main() {\n\treturn cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2006",
    "index": "D",
    "title": "Iris and Adjacent Products",
    "statement": "Iris has just learned multiplication in her Maths lessons. However, since her brain is unable to withstand too complex calculations, she could not multiply two integers with the product greater than $k$ together. Otherwise, her brain may explode!\n\nHer teacher sets a difficult task every day as her daily summer holiday homework. Now she is given an array $a$ consisting of $n$ elements, and she needs to calculate the product of each two adjacent elements (that is, $a_1 \\cdot a_2$, $a_2 \\cdot a_3$, and so on). Iris wants her brain to work safely, and in order to do that, she would like to modify the array $a$ in such a way that $a_i \\cdot a_{i + 1} \\leq k$ holds for every $1 \\leq i < n$. There are two types of operations she can perform:\n\n- She can rearrange the elements of the array $a$ in an arbitrary way.\n- She can select an arbitrary element of the array $a$ and change its value to an arbitrary integer from $1$ to $k$.\n\nIris wants to minimize the number of operations of \\textbf{type $2$} that she uses.\n\nHowever, that's completely not the end of the summer holiday! Summer holiday lasts for $q$ days, and on the $i$-th day, Iris is asked to solve the Math homework for the subarray $b_{l_i}, b_{l_i + 1}, \\ldots, b_{r_i}$. Help Iris and tell her the minimum number of type $2$ operations she needs to perform for each day. Note that the operations are \\textbf{independent} for each day, i.e. the array $b$ is not changed.",
    "tutorial": "Read the hints. Let's consider how to reorder the array. Let the sorted array be $a_1,a_2,\\dots,a_n$. We can prove that it is optimal to reorder it like this: $a_n,a_1,a_{n-1},a_2,a_{n-2},\\dots$. You can find the proof at the end of the tutorial. From the proof or anything we can discover the restriction is: for all $i$ that $1\\le i\\le \\frac n2$, $a_i\\times a_{n-i+1}\\le k$. Let $cnt(l,r)$ denote the number of elements with values in range $[l,r]$. We can rewrite the restrictions into: for each $i$ that $1\\le i\\le \\sqrt k$, it must satisfy that $\\min(cnt(1,i),\\lfloor\\frac n2\\rfloor)\\ge \\min(cnt(\\lfloor\\frac k{i+1}\\rfloor+1,k),\\lfloor\\frac n2\\rfloor)$. This means that the number of $a_j$ that cannot fit $i+1$ must not be greater than the number of $a_j\\le i$, and only $\\lfloor\\frac n2\\rfloor$ numbers should be considered. Note that there're only $O(\\sqrt k)$ range sums on the value range to consider, which is acceptable. Consider a modify operation, we obviously change the maximum value into $1$. This increases every $cnt(1,i)$ by $1$ and decreases every non-zero $cnt(\\lfloor\\frac k{i+1}\\rfloor+1,k)$ by $1$, so the answer is easy to calculate. Just notice the situation when $cnt(1,\\sqrt k)$ is too small and the length of the interval is too short. How to maintain $cnt(1,i)$ for all subintervals? You can consider simply prefix sums, but its time constant factor seems too large for a 2-dimensional array. So we lowered the memory limit to reduce such issues. An easy way to handle is: solve the problem offline, and for each $i$ we calculate the prefix sum for $cnt(1,i)$ and $cnt(\\lfloor\\frac k{i+1}\\rfloor+1,k)$, and then answer all the queries. In this way the time constant factor becomes much smaller and the memory becomes $O(n+q+k)$. Another way to solve is to use Mo's algorithm. It uses $O(n+q+k)$ memory and $O(n\\sqrt q)$ time. The time complexity is $O(\\sqrt k\\sum(n+q))$. Proof for the optimal way to reorder: If $n=1$, it's correct. First, it is optimal to put $a_n$ at the first position. Suppose there's a way to reorder that $a_n$ is not at the first position: $a_{p_1},a_{p_2},\\dots,a_{p_k=n},\\dots$, we can always reverse the prefix $a_{p_1},a_{p_2},\\dots,a_{p_k}$ so that it still satisfies the condition but $a_n$ is at the first position. Then, it is optimal to put $a_1$ at the second position. Suppose there's a way to reorder that $a_n$ is at the first position and $a_{t\\neq 1}$ at the second position, as $a_t$ and $a_1$ both can fit $a_n$, we can consider them the same(any number can be put beside them), so it's possible to swap $a_t$ and $a_1$. If $a_1\\times a_n>k$, then the array isn't good. Otherwise, any number can be put beside $a_1$, so the method of reordering $a_2,a_3,\\dots,a_{n-1}$ can be reduced to the same problem of $n'=n-2$. So the conclusion is proved.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define all(v)      v.begin(),v.end()\n#define pb          push_back\n#define REP(i,b,e)  for(int i=(b);i<(int)(e);++i)\n#define over(x)     {cout<<(x)<<endl;return;}\nint n,q,r;\nint a[300005];\nint sum[300005];\nint ql[300005],qr[300005];\nint ans[300005];\nint cnt[300005],cnt2[300005];\nvoid Main() {\n\tcin>>n>>q>>r;\n\tREP(i,0,n)cin>>a[i];\n\tsum[0]=0;\n\tint B=sqrt(r);\n\tREP(i,0,n)sum[i+1]=sum[i]+(a[i]<=B);\n\tREP(i,0,q){\n\t\tint x,y;\n\t\tcin>>x>>y;\n\t\t--x,--y;\n\t\tql[i]=x;qr[i]=y;\n\t\tans[i]=0;\n\t\tif(sum[y+1]-sum[x]<(y-x+1)/2)ans[i]=(y-x+1)/2-sum[y+1]+sum[x];\n\t}\n\tREP(i,0,B){\n\t\tREP(j,0,n+1)cnt[j]=cnt2[j]=0;\n\t\tREP(j,0,n){\n\t\t\tcnt[j+1]=cnt[j]+(a[j]<=i);\n\t\t\tcnt2[j+1]=cnt2[j]+(a[j]<=r/(i+1));\n\t\t}\n\t\tREP(j,0,q){\n\t\t\tint x=ql[j],y=qr[j],l=y-x+1;\n\t\t\tint c1=cnt2[y+1]-cnt2[x],c2=cnt[y+1]-cnt[x];\n\t\t\tans[j]=max(ans[j],min((l-c1-c2+1)/2,l/2-c2));\n\t\t}\n\t}\n\tREP(i,0,q)cout<<ans[i]<<' ';\n\tcout<<endl;\n}\nvoid TC() {\n    int tc=1;\n    cin>>tc;\n\twhile(tc--){\n\t\tMain();\n\t\tcout.flush();\n\t}\n}\nsigned main() {\n\treturn cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;\n}\n/*\n1. CLEAR the arrays (ESPECIALLY multitests)\n2. DELETE useless output\n */",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2006",
    "index": "E",
    "title": "Iris's Full Binary Tree",
    "statement": "Iris likes full binary trees.\n\nLet's define the depth of a rooted tree as the maximum number of \\textbf{vertices} on the simple paths from some vertex to the root. A full binary tree of depth $d$ is a binary tree of depth $d$ with exactly $2^d - 1$ vertices.\n\nIris calls a tree a $d$-binary tree if some vertices and edges can be \\textbf{added} to it to make it a full binary tree of depth $d$. Note that \\textbf{any vertex} can be chosen as the root of a full binary tree.\n\nSince performing operations on large trees is difficult, she defines the binary depth of a tree as the minimum $d$ satisfying that the tree is $d$-binary. Specifically, if there is no integer $d \\ge 1$ such that the tree is $d$-binary, the binary depth of the tree is $-1$.\n\nIris now has a tree consisting of only vertex $1$. She wants to add $n - 1$ more vertices to form a larger tree. She will add the vertices one by one. When she adds vertex $i$ ($2 \\leq i \\leq n$), she'll give you an integer $p_i$ ($1 \\leq p_i < i$), and add a new edge connecting vertices $i$ and $p_i$.\n\nIris wants to ask you the binary depth of the tree formed by the first $i$ vertices for each $1 \\le i \\le n$. Can you tell her the answer?",
    "tutorial": "Here're two lemmas that will be used in the solution. Lemma 1: Among all the points on a tree with the greatest distance from a certain point, one of which must be one of the two endpoints of a certain diameter. Lemma 2: After merging two trees, at least one new diameter is generated at the four endpoints of two certain diameters. Obviously, we consider a subtree composed of the first $k$ points, which corresponds to a fully binary tree with a depth of $d$, and must have only one node with the smallest depth (otherwise it would not be connected). If the depth of the node with the smallest depth is greater than $1$, then we can reduce the depth of all nodes by $1$. It is easy to see that this will not cause conflicts, and $d$ should be reduced by $1$. In this case, we obtain: Conclusion 1: There must be a node corresponding to the root of a fully binary tree. Meanwhile, due to the degrees of the nodes of a full binary tree, it is obtained that: Conclusion 2: The node corresponding to the root should have a degree $\\leq 2$; if there is a node with a degree $\\gt 3$, then all subsequent queries should be $d = -1$. We can consider the case where each point is the root, and due to the Lemma, we can obtain $d$ as the maximum distance from that point to the endpoints of two diameters, then plus $1$. Finally, select the point with degree $\\leq 2$ that minimizes this maximum value as the root. Brute practices can achieve $\\mathcal O(n^2\\log n)$ time. Consider optimization. According to Lemma 2, each time a point is added, the diameter length either remains unchanged or increases by $1$. In the case of adding $1$, as mentioned earlier, we investigate the maximum distance of all points (temporarily ignoring their degrees). If we consider real-time maintenance of its changes, it is obvious that if the new diameter distance is even, it is equivalent to a maximum distance of $+1$ for all points except for a subtree at the midpoint of the new diameter; otherwise, it is equivalent to a maximum distance of $+1$ for all points of the subtree at the midpoint of the original diameter. Pay attention to the subtrees mentioned, where the roots of the entire tree are variable, but this is not very important. We can traverse and number all nodes in the DFS order, so that the subtree of each node is within an interval in such order. Therefore, an indefinite rooted subtree can also be represented by $\\mathcal O(1)$ intervals. You can use a segment tree to facilitate the maintenance of the $+1$ operations. In addition, considering the impact of degrees, we just need to increase the maximum distance of a $3$-degreed node by $+\\inf$. Ultimately, at the end of each operation, we need only the global minimum value. The time complexity is $O (n\\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define int         long long\n#define pii         pair<int,int>\n#define all(v)      v.begin(),v.end()\n#define pb          push_back\n#define REP(i,b,e)  for(int i=(b);i<(int)(e);++i)\n#define over(x)     {cout<<(x)<<endl;return;}\nstruct ds{\n\tint seg[2000005],tag[2000005];\n\tvoid build(int l,int r,int p){\n\t\tseg[p]=(l==0? 0:1e18),tag[p]=0;\n\t\tif(l==r)return;\n\t\tint m=(l+r)>>1;\n\t\tbuild(l,m,p*2+1);build(m+1,r,p*2+2);\n\t}\n\tvoid pushdown(int p){\n\t\tif(!tag[p])return;\n\t\ttag[p*2+1]+=tag[p];tag[p*2+2]+=tag[p];\n\t\tseg[p*2+1]+=tag[p];seg[p*2+2]+=tag[p];\n\t\ttag[p]=0;\n\t}\n\tvoid add(int l,int r,int s,int t,int p,int val){\n\t\tif(l<=s&&t<=r){\n\t\t\tseg[p]+=val;tag[p]+=val;\n\t\t\treturn;\n\t\t}\n\t\tint m=(s+t)>>1;pushdown(p);\n\t\tif(m>=l)add(l,r,s,m,p*2+1,val);\n\t\tif(m<r)add(l,r,m+1,t,p*2+2,val);\n\t\tseg[p]=min(seg[p*2+1],seg[p*2+2]);\n\t}\n\tvoid update(int pos,int l,int r,int p,int val){\n\t\tif(l==r){\n\t\t\tseg[p]=val;\n\t\t\treturn;\n\t\t}\n\t\tint m=(l+r)>>1;pushdown(p);\n\t\tif(m>=pos)update(pos,l,m,p*2+1,val);\n\t\telse update(pos,m+1,r,p*2+2,val);\n\t\tseg[p]=min(seg[p*2+1],seg[p*2+2]);\n\t}\n}seg;\nint n;\nvector<int>v[500005];\nint fa[500005],an[500005][21];\nint dep[500005],dfn[500005],rev[500005];\nint tot,deg[500005],ls[500005];\nvoid dfs(int x,int pre,int d){\n\tdep[x]=d;fa[x]=pre;an[x][0]=fa[x];ls[x]=1;\n\tREP(i,0,__lg(n+1))if(an[x][i]==-1)an[x][i+1]=-1;else an[x][i+1]=an[an[x][i]][i];\n\trev[tot]=x;dfn[x]=tot++;\n\tfor(auto i:v[x])dfs(i,x,d+1),ls[x]+=ls[i];\n}\nint getlca(int x,int y){\n\tif(dep[x]<dep[y])swap(x,y);\n\tint d=dep[x]-dep[y];\n\tfor(int i=__lg(d);i>=0;--i)if((d>>i)&1)x=an[x][i];\n\tif(x==y)return x;\n\td=dep[x];\n\tfor(int i=__lg(d);i>=0;--i)if((1<<i)<=dep[x]&&an[x][i]!=an[y][i])x=an[x][i],y=an[y][i];\n\treturn fa[x];\n}\nint getan(int x,int y){\n\tif(dfn[y]>=dfn[x]&&dfn[y]<=ls[x]){\n\t\tint d=dep[y]-dep[x]-1;\n\t\tfor(int i=0;(1<<i)<=d;++i)if((d>>i)&1)y=an[y][i];\n\t\treturn y;\n\t}else return fa[x];\n}\nvoid updside(int x,int y){\n\tif(dfn[y]>=dfn[x]&&dfn[y]<=ls[x]){\n\t\tseg.add(0,n-1,0,n-1,0,1);\n\t\tx=getan(x,y);\n\t\tseg.add(dfn[x],ls[x],0,n-1,0,-1);\n\t}else seg.add(dfn[x],ls[x],0,n-1,0,1);\n}\nint getdist(int x,int y){return dep[x]+dep[y]-2*dep[getlca(x,y)];}\nstruct diameter{\n\tint x,y,len;\n\tint update(int z){\n\t\tif(x==y){\n\t\t\tint d=getdist(x,z);\n\t\t\tif(d<=len)return d+len;\n\t\t\tupdside(y,z);\n\t\t\ty=getan(y,z);\n\t\t\treturn d+len;\n\t\t}else{\n\t\t\tint d1=getdist(x,z),d2=getdist(y,z),d3=min(d1,d2);\n\t\t\tif(d3<=len)return d3+len+1;\n\t\t\tif(d1>d2)swap(x,y);\n\t\t\tupdside(y,z);\n\t\t\ty=x;++len;return len*2;\n\t\t}\n\t}\n\tint query(int z){\n\t\tif(x==y)return len+getdist(x,z);\n\t\telse return len+min(getdist(x,z),getdist(y,z))+1;\n\t}\n};\nvoid Main() {\n\tcin>>n;\n\tREP(i,0,n)v[i].clear();\n\tREP(i,1,n){\n\t\tcin>>fa[i];--fa[i];\n\t\tv[fa[i]].pb(i);\n\t}\n\ttot=0;dfs(0,-1,0);seg.build(0,n-1,0);\n\tREP(i,0,n)deg[i]=0,ls[i]+=dfn[i]-1;\n\tdiameter d={0,0,0};\n\tcout<<\"1 \";\n\tREP(i,1,n){\n\t\t++deg[fa[i]];++deg[i];\n\t\tif(deg[fa[i]]==4){\n\t\t\tREP(j,i,n)cout<<-1<<' ';\n\t\t\tcout<<endl;return;\n\t\t}\n\t\tif(deg[fa[i]]==3)seg.update(dfn[fa[i]],0,n-1,0,1e18);\n\t\tseg.update(dfn[i],0,n-1,0,d.update(i));\n\t\tcout<<seg.seg[0]+1<<' ';\n\t}\n\tcout<<endl;\n}\nvoid TC() {\n    int tc=1;\n    cin>>tc;\n\twhile(tc--){\n\t\tMain();\n\t\tcout.flush();\n\t}\n}\nsigned main() {\n\treturn cin.tie(0),cout.tie(0),ios::sync_with_stdio(0),TC(),0;\n}\n/*\n1. CLEAR the arrays (ESPECIALLY multitests)\n2. DELETE useless output\n */",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2006",
    "index": "F",
    "title": "Dora's Paint",
    "statement": "Sadly, Dora poured the paint when painting the class mural. Dora considers the mural as the matrix $b$ of size $n \\times n$. Initially, $b_{i,j} = 0$ for all $1 \\le i, j \\le n$.\n\nDora has only two brushes which have two different colors. In one operation, she can paint the matrix with one of two brushes:\n\n- The first brush has color $1$ on it and can paint one column of the matrix. That is, Dora chooses $1 \\leq j \\leq n$ and makes $b_{i,j} := 1$ for all $1 \\leq i \\leq n$;\n- The second brush has color $2$ on it and can paint one row of the matrix. That is, Dora chooses $1 \\leq i \\leq n$ and makes $b_{i,j} := 2$ for all $1 \\leq j \\leq n$.\n\nDora paints the matrix so that the resulting matrix $b$ \\textbf{contains only} $1$ and $2$.\n\nFor a matrix $b$, let $f(b)$ denote the minimum number of operations needed to turn the initial matrix (containing only $0$) into $b$. The beauty of a matrix $b$ is the number of ways to paint the initial matrix in exactly $f(b)$ operations to turn it into $b$. If there's no way to turn the initial matrix into $b$, the beauty of $b$ is $0$.\n\nHowever, Dora made a uniformly random mistake; there's \\textbf{exactly one} element different in the matrix $a$ given to you from the real matrix $b$. That is, there is exactly one pair $(i, j)$ such that $a_{i, j} = 3 - b_{i, j}$.\n\nPlease help Dora compute the expected beauty of the real matrix $b$ modulo $998\\,244\\,353$ (all possible $n^2$ mistakes have equal probability).\n\nSince the size of the matrix is too large, Dora will only tell you the positions of $m$ elements of color $1$, and the remaining $n^2-m$ elements have color $2$.",
    "tutorial": "Read the hints. From the hints, you may understand that, when given the degrees of each node, you can get the initial beauty of a matrix in $\\mathcal O(n)$. To quickly perform topological sort, you should use addition tags to maintain the degrees of each node. Also, this is equal to sorting them by degrees. Brute-force traversal of each edge solves in $\\mathcal O(n^3)$. First, let's try to solve the problem in $\\mathcal O(n^2)$. In the Case of Initial Beauty is not $0$ For an inverted edge between column $i$ and row $j$, we claim that the beauty is still not $0$ if and only if column $i$ and row $j$ are in adjacent layers in the initial topological sort. If they are not in adjacent layers, WLOG let the initial direction be $i \\to j$. Since it's a bipartite graph, we can't get $i \\to x \\to j$, but we can definitely get $i \\to x \\to y \\to j$. If the edge is inverted, then there exists a cycle: $i \\to x \\to y \\to j \\to i$, which means that the beauty becomes $0$. Otherwise, it can also be proved that no new cycle is created. Since the answer is $\\displaystyle\\prod_{i=1}^n [\\sum_{j=1}^n \\text{ColOutdeg}(j) = i]! \\cdot \\prod_{i=1}^n [\\sum_{j=1}^n \\text{RowOutdeg}(j) = i]!$, a modification will only lead to changes in $\\mathcal O(1)$ terms, and can therefore be easily calculated. In the Case of Initial Beauty is $0$ Note that this is a full bipartite graph. This means, if there is a cycle, then there must be a cycle of exactly $4$ vertices. Proof: If we can find the cycle of any number of vertices, we can get a cycle of $4$ vertices, and after that we can simply try to invert only the $4$ edges and sum the answer up, otherwise the cycle still exists. The problem is turned down to how to find a cycle. We can try to DFS from each vertex. If a cycle is found, it will contain no more than $2m$ edges, and we can do as the proof does to reduce the number of edges (so that the size eventually becomes $4$). $\\rule{1000px}{1px}$ Then, let's move on to $\\mathcal O(n + m)$ (In fact, $\\mathcal O((n + m)\\log n)$ solutions may pass as well). In the Case of Initial Beauty is not $0$ Let's assume that all the blocks are from being $\\tt 2$ to being $\\tt 1$, and then you can calculate the answer efficiently enough. Then, brute go over the $\\tt 1$ blocks and recalculate its contribution to the answer. In the Case of Initial Beauty is $0$ Since the topo sorting is done halfway (some nodes are first extracted as previous \"layers\"), we need to flip an edge to continue. At the moment, however, no remaining vertices have an indegree of $0$. Then, after a flip, there should be a vertex with an indegree of $0$ (otherwise the beauty remains $0$ and we skip it). From this point of view, if there is no vertex with an indegree of $1$, then the beauty will always be $0$ after one flip. If there is a node with an indegree of $1$ (assume that it is $u$), we can easily find a cycle of $4$ vertices containing $u$: We find the only node $x$ satisfying $x \\to u$. We find a node $y$ satisfying $y \\to x$. We find a node $z$, again, satisfying $z \\to y$. There must be $u \\to z$ since the indegree of $u$ is only $1$. There are some other ways to find the cycle. For example, you are just going to find a pattern, and after selecting a node, you can do sweepline on all the $m$ occurrences of $\\tt 1$. If you implement it well, it is also in linear time. Time complexity: $\\mathcal O(n + m)$. Method 2: Try to find some way to \"sort\" the grid, for swapping different rows and different columns doesn't matter. How? Sort by the number of $1$. How to calculate the beauty? The beauty is the product of factorials of number of equal rows and equal columns. How to solve the original problem when the initial grid has positive beauty? How to optimize? How to solve the original problem when the initial grid is impossible to be painted out? Are there too many ways to flip a block? Read the hints. Let's sort the rows and columns in some way, which means you should swap two rows or two columns each time to make them ordered. Let's sort by the number of $1$ in each row and column. For example, the result of sorting the left part is shown in the right part: $\\left[\\begin{matrix}2&1&1&1\\\\2&2&1&2\\\\1&1&1&1\\\\2&2&1&2\\end{matrix}\\right]\\Rightarrow\\left[\\begin{matrix}1&1&1&1\\\\1&1&1&2\\\\1&2&2&2\\\\1&2&2&2\\end{matrix}\\right]$ We claim that the grid is solvealbe if and only if the later rows are \"included\" by previous rows, and so for the columns. For example, if a position in any row is filled with $1$, then the position in any previous row must also be $1$. This is correct because you'll notice that any submatrices of the following two types cannot appear in a solveable grid. To check that, you'll only need to check adjacent rows and columns. $\\left[\\begin{matrix}1&2\\\\2&1\\end{matrix}\\right],\\left[\\begin{matrix}2&1\\\\1&2\\end{matrix}\\right]$ After you sort all of that, the number of ways to paint it is easy to think about. It's similar to the product of factorials of the number of each kind of rows(for example, the last two rows in the right above). The only to notice is the first step of painting shouldn't be counted. Consider modifying one block. If the initial grid is solveable, there're only $O(n)$ types of changing(in each row, all the $1$ and $2$ can be considered the same). Each type of changing can be done in $O(1)$ using simple discussion. If the initial grid is unsolveable, we should find the two adjacent rows and columns that starts the problem. We claim that the block to change must belong to one of the four blocks in the intersection of the rows and columns. Just try every possible situation and do brute force on it. For example, consider the following matrix: The first two columns and the last two rows went wrong. So let's try to change blocks $(3,1),(3,2),(4,1),(4,2)$ to judge whether it is possible. $\\left[\\begin{matrix}1&1&1&1\\\\1&1&1&2\\\\1&2&2&2\\\\2&1&2&2\\end{matrix}\\right]$ The time complexity is $O((n+m)\\log n)$, and if you implement carefully enough you can solve it in $O(n+m)$.",
    "code": "#if defined(LOCAL) or not defined(LUOGU)\n#pragma GCC optimize(3)\n#pragma GCC optimize(\"Ofast,unroll-loops\")\n#endif\n#include<bits/stdc++.h>\nusing namespace std;\nstruct time_helper\n{\n#ifdef LOCAL\n\tclock_t time_last;\n#endif\n\ttime_helper()\n\t{\n#ifdef LOCAL\n\t\ttime_last=clock();\n#endif\n\t}\n\tvoid test()\n\t{\n#ifdef LOCAL\n\t\tauto time_now=clock();\n\t\tstd::cerr<<\"time:\"<<1.*(time_now-time_last)/CLOCKS_PER_SEC<<\";all_time:\"<<1.*time_now/CLOCKS_PER_SEC<<std::endl;\n\t\ttime_last=time_now;\n#endif\n\t}\n\t~time_helper()\n\t{\n\t\ttest();\n\t}\n}time_helper;\n#ifdef LOCAL\n#include\"dbg.h\"\n#else\n#define dbg(...) (__VA_ARGS__)\n#endif\nnamespace Fread{const int SIZE=1<<16;char buf[SIZE],*S,*T;inline char getchar(){if(S==T){T=(S=buf)+fread(buf,1,SIZE,stdin);if(S==T)return'\\n';}return *S++;}}namespace Fwrite{const int SIZE=1<<16;char buf[SIZE],*S=buf,*T=buf+SIZE;inline void flush(){fwrite(buf,1,S-buf,stdout);S=buf;}inline void putchar(char c){*S++=c;if(S==T)flush();}struct NTR{~NTR(){flush();}}ztr;}\n#define getchar Fread::getchar\n#define putchar Fwrite::putchar\n#define Setprecision 10\n#define between '\\n'\n#define __int128 long long\ntemplate<typename T>struct is_char{static constexpr bool value=(std::is_same<T,char>::value||std::is_same<T,signed char>::value||std::is_same<T,unsigned char>::value);};template<typename T>struct is_integral_ex{static constexpr bool value=(std::is_integral<T>::value||std::is_same<T,__int128>::value)&&!is_char<T>::value;};template<typename T>struct is_floating_point_ex{static constexpr bool value=std::is_floating_point<T>::value||std::is_same<T,__float128>::value;};namespace Fastio{struct Reader{template<typename T>typename std::enable_if_t<std::is_class<T>::value,Reader&>operator>>(T&x){for(auto &y:x)*this>>y;return *this;}template<typename T>typename std::enable_if_t<is_integral_ex<T>::value,Reader&>operator>>(T&x){char c=getchar();short f=1;while(c<'0'||c>'9'){if(c=='-')f*=-1;c=getchar();}x=0;while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+(c^48);c=getchar();}x*=f;return *this;}template<typename T>typename std::enable_if_t<is_floating_point_ex<T>::value,Reader&>operator>>(T&x){char c=getchar();short f=1,s=0;x=0;T t=0;while((c<'0'||c>'9')&&c!='.'){if(c=='-')f*=-1;c=getchar();}while(c>='0'&&c<='9'&&c!='.')x=x*10+(c^48),c=getchar();if(c=='.')c=getchar();else return x*=f,*this;while(c>='0'&&c<='9')t=t*10+(c^48),s++,c=getchar();while(s--)t/=10.0;x=(x+t)*f;return*this;}template<typename T>typename std::enable_if_t<is_char<T>::value,Reader&>operator>>(T&c){c=getchar();while(c=='\\n'||c==' '||c=='\\r')c=getchar();return *this;}Reader&operator>>(char*str){int len=0;char c=getchar();while(c=='\\n'||c==' '||c=='\\r')c=getchar();while(c!='\\n'&&c!=' '&&c!='\\r')str[len++]=c,c=getchar();str[len]='\\0';return*this;}Reader&operator>>(std::string&str){str.clear();char c=getchar();while(c=='\\n'||c==' '||c=='\\r')c=getchar();while(c!='\\n'&&c!=' '&&c!='\\r')str.push_back(c),c=getchar();return*this;}Reader(){}}cin;const char endl='\\n';struct Writer{typedef __int128 mxdouble;template<typename T>typename std::enable_if_t<std::is_class<T>::value,Writer&>operator<<(T x){for(auto &y:x)*this<<y<<between;*this<<'\\n';return *this;}template<typename T>typename std::enable_if_t<is_integral_ex<T>::value,Writer&>operator<<(T x){if(x==0)return putchar('0'),*this;if(x<0)putchar('-'),x=-x;static int sta[45];int top=0;while(x)sta[++top]=x%10,x/=10;while(top)putchar(sta[top]+'0'),--top;return*this;}template<typename T>typename std::enable_if_t<is_floating_point_ex<T>::value,Writer&>operator<<(T x){if(x<0)putchar('-'),x=-x;x+=pow(10,-Setprecision)/2;mxdouble _=x;x-=(T)_;static int sta[45];int top=0;while(_)sta[++top]=_%10,_/=10;if(!top)putchar('0');while(top)putchar(sta[top]+'0'),--top;putchar('.');for(int i=0;i<Setprecision;i++)x*=10;_=x;while(_)sta[++top]=_%10,_/=10;for(int i=0;i<Setprecision-top;i++)putchar('0');while(top)putchar(sta[top]+'0'),--top;return*this;}template<typename T>typename std::enable_if_t<is_char<T>::value,Writer&>operator<<(T c){putchar(c);return*this;}Writer&operator<<(char*str){int cur=0;while(str[cur])putchar(str[cur++]);return *this;}Writer&operator<<(const char*str){int cur=0;while(str[cur])putchar(str[cur++]);return*this;}Writer&operator<<(std::string str){int st=0,ed=str.size();while(st<ed)putchar(str[st++]);return*this;}Writer(){}}cout;}\n#define cin Fastio::cin\n#define cout Fastio::cout\n#define endl Fastio::endl\n \nvoid solve();\nmain()\n{\n\tint t=1;\n\tcin>>t;\n\twhile(t--)solve();\n}\ntemplate <uint32_t mod>\nstruct LazyMontgomeryModInt {\n\tusing mint = LazyMontgomeryModInt;\n\tusing i32 = int32_t;\n\tusing u32 = uint32_t;\n\tusing u64 = uint64_t;\n\tstatic constexpr u32 get_r() {\n\t\tu32 ret = mod;\n\t\tfor (i32 i = 0; i < 4; ++i) ret *= 2 - mod * ret;\n\t\treturn ret;\n\t}\n\tstatic constexpr u32 r = get_r();\n\tstatic constexpr u32 n2 = -u64(mod) % mod;\n\tstatic_assert(r * mod == 1, \"invalid, r * mod != 1\");\n\tstatic_assert(mod < (1 << 30), \"invalid, mod >= 2 ^ 30\");\n\tstatic_assert((mod & 1) == 1, \"invalid, mod % 2 == 0\");\n\tu32 a;\n\tconstexpr LazyMontgomeryModInt() : a(0) {}\n\tconstexpr LazyMontgomeryModInt(const int64_t &b)\n\t\t\t: a(reduce(u64(b % mod + mod) * n2)){};\n\tstatic constexpr u32 reduce(const u64 &b) {\n\t\treturn (b + u64(u32(b) * u32(-r)) * mod) >> 32;\n\t}\n\tconstexpr mint &operator+=(const mint &b) {\n\t\tif (i32(a += b.a - 2 * mod) < 0) a += 2 * mod;\n\t\treturn *this;\n\t}\n\tconstexpr mint &operator-=(const mint &b) {\n\t\tif (i32(a -= b.a) < 0) a += 2 * mod;\n\t\treturn *this;\n\t}\n\tconstexpr mint &operator*=(const mint &b) {\n\t\ta = reduce(u64(a) * b.a);\n\t\treturn *this;\n\t}\n\tconstexpr mint &operator/=(const mint &b) {\n\t\t*this *= b.inverse();\n\t\treturn *this;\n\t}\n\tconstexpr mint operator+(const mint &b) const { return mint(*this) += b; }\n\tconstexpr mint operator-(const mint &b) const { return mint(*this) -= b; }\n\tconstexpr mint operator*(const mint &b) const { return mint(*this) *= b; }\n\tconstexpr mint operator/(const mint &b) const { return mint(*this) /= b; }\n\tconstexpr bool operator==(const mint &b) const {\n\t\treturn (a >= mod ? a - mod : a) == (b.a >= mod ? b.a - mod : b.a);\n\t}\n\tconstexpr bool operator!=(const mint &b) const {\n\t\treturn (a >= mod ? a - mod : a) != (b.a >= mod ? b.a - mod : b.a);\n\t}\n\tconstexpr mint operator-() const { return mint() - mint(*this); }\n\tconstexpr mint pow(u64 n) const {\n\t\tmint ret(1), mul(*this);\n\t\twhile (n > 0) {\n\t\t\tif (n & 1) ret *= mul;\n\t\t\tmul *= mul;\n\t\t\tn >>= 1;\n\t\t}\n\t\treturn ret;\n\t}\n\tconstexpr mint inverse() const { return pow(mod - 2); }\n\tfriend ostream &operator<<(ostream &os, const mint &b) {\n\t\treturn os << b.get();\n\t}\n\tfriend istream &operator>>(istream &is, mint &b) {\n\t\tint64_t t;\n\t\tis >> t;\n\t\tb = LazyMontgomeryModInt<mod>(t);\n\t\treturn (is);\n\t}\n\tconstexpr u32 get() const {\n\t\tu32 ret = reduce(a);\n\t\treturn ret >= mod ? ret - mod : ret;\n\t}\n\tstatic constexpr u32 get_mod() { return mod; }\n\texplicit operator u32() const {return get();}\n};\n#define modint LazyMontgomeryModInt\n#define mint modint<p>\nconstexpr int p=998244353;\nstd::pmr::monotonic_buffer_resource pool(100000000);\nvoid solve()\n{\n\tint n,m;\n\tcin>>n>>m;\n\tvector<std::pmr::vector<int>>a(n,std::pmr::vector<int>{&pool});\n\ttime_helper.test();\n\twhile(m--)\n\t{\n\t\tint u,v;\n\t\tcin>>u>>v;\n\t\tu--,v--;\n\t\ta[u].emplace_back(v);\n\t}\n\ttime_helper.test();\n\tstd::pmr::vector<mint>inv{&pool},fac{&pool},ifac{&pool};\n\tinv.resize(n+1),fac.resize(n+1),ifac.resize(n+1);\n\tstd::pmr::vector<int>arr_cnt{&pool};\n\tarr_cnt.resize(n+2);\n\tauto arr_sort=[&](const auto&a)\n\t{\n\t\tfor(int i=0;i<n;i++)\n\t\tarr_cnt[a[i].size()+1]++;\n\t\tfor(int x=1;x<=n;x++)\n\t\tarr_cnt[x]+=arr_cnt[x-1];\n\t\tvector<std::pmr::vector<int>>b(n,std::pmr::vector<int>{&pool});\n\t\tfor(int i=0;i<n;i++)\n\t\tb[arr_cnt[a[i].size()]++]=move(a[i]);\n\t\tfor(int x=0;x<=n+1;x++)\n\t\tarr_cnt[x]=0;\n\t\treturn b;\n\t};\n\ta=move(arr_sort(a));\n\tauto arr_eq=[&](const auto&a,const auto&b)\n\t{\n\t\tif(a.size()!=b.size())return false;\n\t\tbool res=1;\n\t\tfor(auto q:a)arr_cnt[q]=1;\n\t\tfor(auto q:b)if(!arr_cnt[q]){res=0;break;}\n\t\tfor(auto q:a)arr_cnt[q]=0;\n\t\treturn res;\n\t};\n\tauto arr_includes=[&](const auto&a,const auto&b)\n\t{\n\t\tbool res=1;\n\t\tfor(auto q:a)arr_cnt[q]=1;\n\t\tfor(auto q:b)if(!arr_cnt[q]){res=0;break;}\n\t\tfor(auto q:a)arr_cnt[q]=0;\n\t\treturn res;\n\t};\n\tauto arr_set_difference=[&](const auto&a,const auto&b,auto &diff)\n\t{\n\t\tfor(auto q:b)arr_cnt[q]=1;\n\t\tfor(auto q:a)\n\t\tif(!arr_cnt[q])\n\t\t{\n\t\t\tdiff.emplace_back(q);\n\t\t\tif(diff.size()>2)break;\n\t\t}\n\t\tfor(auto q:b)arr_cnt[q]=0;\n\t};\n\t{\n\t\tfac[0]=1;\n\t\tfor(int x=1;x<=n;x++)\n\t\tfac[x]=fac[x-1]*x;\n\t\tifac[n]=fac[n].inverse();\n\t\tfor(int x=n;x>=1;x--)\n\t\tifac[x-1]=ifac[x]*x,inv[x]=ifac[x]*fac[x-1];\n\t}\n\tint failcnt=0;\n\tfor(int x=1;x<n;x++)\n\tfailcnt+=!(arr_includes(a[x],a[x-1]));\n\tif(failcnt==0)\n\t{\n\t\tint nc=0;\n\t\tmint ansbas=fac[a[0].size()],ans=0;\n\t\tstd::pmr::vector<int>tnc{&pool},tmc{&pool};\n\t\ttmc.emplace_back(a[0].size());\n\t\tint ct=0;\n\t\tfor(int x=0;x<n;x++)\n\t\tif(x==n-1||!arr_eq(a[x],a[x+1]))\n\t\t{\n\t\t\tnc++;\n\t\t\tif(a[x].size()!=n)\n\t\t\tansbas*=fac[nc];\n\t\t\tint mc=0;\n\t\t\tif(x==n-1)mc=n-a[x].size();\n\t\t\telse mc=a[x+1].size()-a[x].size();\n\t\t\tif(x!=n-1)\n\t\t\tansbas*=fac[mc];\n\t\t\ttnc.emplace_back(nc);\n\t\t\ttmc.emplace_back(mc);\n\t\t\tnc=0;\n\t\t\tct++;\n\t\t}\n\t\telse nc++;\n\t\tfor(int x=0;x<ct;x++)\n\t\t{\n\t\t\tint nc=tnc[x],mc=tmc[x+1];\n\t\t\tif(mc==0)continue;\n\t\t\tmint fix=ansbas;\n\t\t\tif(x==ct-1)\n\t\t\t{\n\t\t\t\tfix*=mc;\n\t\t\t}\n\t\t\tif(x==ct-2&&mc==1&&tmc[x+2]==0)\n\t\t\t{\n\t\t\t\tfix*=inv[tnc[x+1]+1];\n\t\t\t}\n\t\t\tif(x==ct-1||mc!=1)\n\t\t\t{\n\t\t\t\tif(mc)\n\t\t\t\t{\n\t\t\t\t\tif(nc>1)ans+=fix;\n\t\t\t\t\telse ans+=fix*(tmc[x]+1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(nc>1)ans+=fix*(tnc[x+1]+1);\n\t\t\telse ans+=fix*(tnc[x+1]+1)*(tmc[x]+1);\n\t\t}\n\t\tfor(int x=0;x<ct;x++)\n\t\t{\n\t\t\tint nc=tnc[x],mc=tmc[x];\n\t\t\tif(mc==0)continue;\n\t\t\tmint fix=ansbas;\n\t\t\tif(x==ct-1)\n\t\t\t{\n\t\t\t    if(tmc[x+1]==0)fix*=nc;\n\t\t\t    if(nc==1)fix*=inv[tmc[x+1]+1];\n\t\t\t}\n\t\t\tif(x==0||mc!=1)\n\t\t\t{\n\t\t\t\tif(mc)\n\t\t\t\t{\n\t\t\t\t\tif(nc>1)ans+=fix;\n\t\t\t\t\telse ans+=fix*(tmc[x+1]+1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(nc>1)ans+=fix*(tnc[x-1]+1);\n\t\t\telse ans+=fix*(tnc[x-1]+1)*(tmc[x+1]+1);\n\t\t}\n\t\tcout<<(ans*inv[n]*inv[n]).get()<<endl;\n\t\treturn;\n\t}\n\tif(failcnt>2){cout<<0<<endl;return;}\n\tmint ans=0;\n    auto calc=[&](vector<std::pmr::vector<int>>&a)->mint\n\t{\n        a=move(arr_sort(a));\n\t\tfor(int x=1;x<n;x++)\n\t\tif(!arr_includes(a[x],a[x-1]))return 0;\n\t\tint nc=0;\n\t\tmint ansbas=fac[a[0].size()];\n\t\tfor(int x=0;x<n;x++)\n\t\tif(x==n-1||!arr_eq(a[x],a[x+1]))\n\t\t{\n\t\t\tnc++;\n\t\t\tif(a[x].size()!=n)\n\t\t\tansbas=ansbas*fac[nc];\n\t\t\tint mc=0;\n\t\t\tif(x==n-1)mc=n-a[x].size();\n\t\t\telse mc=a[x+1].size()-a[x].size();\n\t\t\tif(x!=n-1)\n\t\t\tansbas=ansbas*fac[mc];\n\t\t\tnc=0;\n\t\t}\n\t\telse nc++;\n\t\treturn ansbas;\n\t};\n\tstd::pmr::set<pair<int,int>>st{&pool};\n\tstd::pmr::vector<int>diff{&pool};\n\tvector<std::pmr::vector<int>>b(n,std::pmr::vector<int>{&pool});\n\ttime_helper.test();\n\tfor(int x=1;x<n;x++)\n\tif(!arr_includes(a[x],a[x-1]))\n\t{\n\t\tfor(int y=x+2;y<n;y++)\n\t\tif(!arr_includes(a[y],a[y-1]))goto fail;\n\t\t{\n\t\t\tdiff.clear();\n\t\t\tarr_set_difference(a[x],a[x-1],diff);\n\t\t\tif(diff.size()<=1)\n\t\t\t{\n\t\t\t\tif(!st.count({x-1,diff[0]}))\n\t\t\t\t{\n\t\t\t\t\tb=a;\n\t\t\t\t\tb[x-1].emplace_back(diff[0]);\n\t\t\t\t\tans+=calc(b),st.insert({x-1,diff[0]});\n\t\t\t\t}\n\t\t\t\tif(!st.count({x,diff[0]}))\n\t\t\t\t{\n\t\t\t\t\tb=a;\n\t\t\t\t\tb[x].erase(find(b[x].begin(),b[x].end(),diff[0]));\n\t\t\t\t\tans+=calc(b),st.insert({x,diff[0]});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tdiff.clear();\n\t\t\tarr_set_difference(a[x-1],a[x],diff);\n\t\t\tif(diff.size()<=1)\n\t\t\t{\n\t\t\t\tif(!st.count({x,diff[0]}))\n\t\t\t\t{\n\t\t\t\t\tb=a;\n\t\t\t\t\tb[x].emplace_back(diff[0]);\n\t\t\t\t\tans+=calc(b),st.insert({x,diff[0]});\n\t\t\t\t}\n\t\t\t\tif(!st.count({x-1,diff[0]}))\n\t\t\t\t{\n\t\t\t\t\tb=a;\n\t\t\t\t\tb[x-1].erase(find(b[x-1].begin(),b[x-1].end(),diff[0]));\n\t\t\t\t\tans+=calc(b),st.insert({x-1,diff[0]});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfail:\n\t\tbreak;\n\t}\n\tcout<<(ans*inv[n]*inv[n]).get()<<endl;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "constructive algorithms",
      "graphs",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2007",
    "index": "A",
    "title": "Dora's Set",
    "statement": "Dora has a set $s$ containing integers. In the beginning, she will put all integers in $[l, r]$ into the set $s$. That is, an integer $x$ is initially contained in the set if and only if $l \\leq x \\leq r$. Then she allows you to perform the following operations:\n\n- Select three \\textbf{distinct} integers $a$, $b$, and $c$ from the set $s$, such that $\\gcd(a, b) = \\gcd(b, c) = \\gcd(a, c) = 1^\\dagger$.\n- Then, remove these three integers from the set $s$.\n\nWhat is the maximum number of operations you can perform?\n\n$^\\dagger$Recall that $\\gcd(x, y)$ means the greatest common divisor of integers $x$ and $y$.",
    "tutorial": "In a pair of $(a, b, c)$ there are at least two odd integers and at most one even integer. That's because if two even integers occur at the same time, their $\\gcd$ will be at least $2$. It's optimal to make full use of the odd integers, so we try to choose two odd integers in a pair. In fact, this is always possible. Note that two consecutive odd integers always have $\\gcd=1$, and consecutive integers also have $\\gcd=1$, so we can choose three consecutive integers $(a,b,c)$ in the form of $2k - 1, 2k, 2k + 1$. We can see that this is always optimal. Therefore, the answer is: the result of dividing the number of odd numbers in $[l, r]$ by $2$ and rounding down. The time complexity is: $\\mathcal O(T)$ or $\\mathcal O(\\sum (r - l))$.",
    "code": "T = int(input())\n \nfor _ in range(T) :\n\tl, r = map(int, input().split())\n\tprint(((r + 1) // 2 - l // 2) // 2)",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2007",
    "index": "B",
    "title": "Index and Maximum Value",
    "statement": "After receiving yet another integer array $a_1, a_2, \\ldots, a_n$ at her birthday party, Index decides to perform some operations on it.\n\nFormally, there are $m$ operations that she is going to perform in order. Each of them belongs to one of the two types:\n\n- $+ l r$. Given two integers $l$ and $r$, for all $1 \\leq i \\leq n$ such that $l \\leq a_i \\leq r$, set $a_i := a_i + 1$.\n- $- l r$. Given two integers $l$ and $r$, for all $1 \\leq i \\leq n$ such that $l \\leq a_i \\leq r$, set $a_i := a_i - 1$.\n\nFor example, if the initial array $a = [7, 1, 3, 4, 3]$, after performing the operation $+ \\space 2 \\space 4$, the array $a = [7, 1, 4, 5, 4]$. Then, after performing the operation $- \\space 1 \\space 10$, the array $a = [6, 0, 3, 4, 3]$.\n\nIndex is curious about the maximum value in the array $a$. Please help her find it after each of the $m$ operations.",
    "tutorial": "We take a maximum value from the initial array. Let's call it $a_{pos}$. We can see that $a_{pos}$ will always be one of the maximum values after any number of operations. Proof: Consider the value $x$ (which should be less than or equal to $a_{pos}$) before a particular operation. If $x = a_{pos}$, then $x = a_{pos}$ still holds after the operation. Otherwise $x < a_{pos}$. In the operation, the difference between $x$ and $a_{pos}$ decreases by at most $1$, so $x$ cannot become strictly greater than $a_{pos}$. Then, $a_{pos}$ remains the maximum value. So we have reduced the problem to $n = 1$. Each time a new operation is added, we perform it only on $a_{pos}$ (and then output $a_{pos}$). Time complexity: $\\mathcal O(n + q)$.",
    "code": "T = int(input())\n \nfor _ in range(T) :\n\tn, m = map(int, input().split())\n\tv = max(map(int, input().split()))\n\tfor __ in range(m) :\n\t\tc, l, r = input().split()\n\t\tl = int(l)\n\t\tr = int(r)\n\t\tif (l <= v <= r) :\n\t\t\tif (c == '+') :\n\t\t\t\tv = v + 1\n\t\t\telse :\n\t\t\t\tv = v - 1\n\t\tprint(v, end = ' ' if __ != m - 1 else '\\n')",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "2007",
    "index": "C",
    "title": "Dora and C++",
    "statement": "Dora has just learned the programming language C++!\n\nHowever, she has completely misunderstood the meaning of C++. She considers it as two kinds of adding operations on the array $c$ with $n$ elements. Dora has two integers $a$ and $b$. In one operation, she can choose one of the following things to do.\n\n- Choose an integer $i$ such that $1 \\leq i \\leq n$, and increase $c_i$ by $a$.\n- Choose an integer $i$ such that $1 \\leq i \\leq n$, and increase $c_i$ by $b$.\n\nNote that $a$ and $b$ are \\textbf{constants}, and they can be the same.\n\nLet's define a range of array $d$ as $\\max(d_i) - \\min(d_i)$. For instance, the range of the array $[1, 2, 3, 4]$ is $4 - 1 = 3$, the range of the array $[5, 2, 8, 2, 2, 1]$ is $8 - 1 = 7$, and the range of the array $[3, 3, 3]$ is $3 - 3 = 0$.\n\nAfter any number of operations (possibly, $0$), Dora calculates the range of the new array. You need to help Dora minimize this value, but since Dora loves exploring all by herself, you only need to tell her the minimized value.",
    "tutorial": "Read the hints. Consider $a = b$. First, the answer is less than $a$. Otherwise, you can always increase the minimum value by $a$ so that all elements are greater than $\\max(c_i) - a$. Let's go over all possible minimum values, say $m$, and we can do the operations so that all elements are in the range $[m, m + a - 1]$. Then we can calculate the range and compare it with the answer. There are $n$ possible minimum values, so the process is too slow. Consider first letting $c_1$ be the minimum, and we do the operations to make $c_2 \\dots c_n$ in the range $[c_1, c_1 + a - 1]$. Then, sort the array, and try $c_2, c_3, \\dots c_n$ as the minimum in turn. Suppose $c_i$ is the current minimum, and $j$ is the largest integer such that $c_j < c_i$. If $j$ exists, then $c_j + a$ is the maximum. That's because for all $k < j$, $c_k + a \\leq c_j + a$; and for all $k > i$, $c_k \\leq c_j + a$. So we can do this in $O(n)$ after sorting. In the case of $a \\neq b$. We can prove that this is equivalent to $a = b = \\gcd(a, b)$ according to the Bezout's Identity (Please, search it yourself on https://en.wikipedia.org/wiki/, for the character \"é\" cannot be displayed inside a $\\LaTeX$ link): First, the changes in value of each element must be a multiple of $d$, since $a, b$ are both multiples of $\\gcd(a, b)$. Second, we can always construct integers $x, y$ such that $ax + by = \\gcd(a, b)$, so we can perform some operations such that we only increase / decrease an element by $\\gcd(a, b)$. Time complexity: $\\mathcal O(n\\log n + \\log V)$.",
    "code": "import math\n \nT = int(input())\nfor _ in range(T) :\n\tn, a, b = map(int, input().split())\n\td = math.gcd(a, b)\n\ta = list(map(int, input().split()))\n\ta = [x % d for x in a]\n\ta.sort()\n\tres = a[n - 1] - a[0]\n\tfor i in range(1, n) :\n\t\tres = min(res, a[i - 1] + d - a[i])\n\tprint(res)\n",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2008",
    "index": "A",
    "title": "Sakurako's Exam",
    "statement": "Today, Sakurako has a math exam. The teacher gave the array, consisting of $a$ ones and $b$ twos.\n\nIn an array, Sakurako \\textbf{must} place either a '+' or a '-' in front of each element so that the sum of all elements in the array equals $0$.\n\nSakurako is not sure if it is possible to solve this problem, so determine whether there is a way to assign signs such that the sum of all elements in the array equals $0$.",
    "tutorial": "First of all, this task is the same as: \"divide an array into two arrays with equal sum\". So, obviously, we need to check if the sum of all elements is even which implies that the number of ones is even. Then, we can out half of 2s in one array and the other half in another, but if number of 2s is odd, then one array will have a greater sum then another, so we need to put two 1s there. So, if we don't have two ones while the number of 2s is odd then the answer is \"NO\". Also, if sum is odd, the answer is also \"NO\". In all other cases, the answer is \"YES\".",
    "code": "t=int(input())\nfor _ in range(t):\n    a,b=map(int,input().split())\n    if a%2==1:\n        print(\"NO\")\n        continue\n    if a==0 and b%2==1:\n        print(\"NO\")\n        continue\n    print(\"YES\")",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2008",
    "index": "B",
    "title": "Square or Not",
    "statement": "A beautiful binary matrix is a matrix that has ones on its edges and zeros inside.\n\n\\begin{center}\n{\\small Examples of four beautiful binary matrices.}\n\\end{center}\n\nToday, Sakurako was playing with a beautiful binary matrix of size $r \\times c$ and created a binary string $s$ by writing down all the rows of the matrix, starting from the first and ending with the $r$-th. More formally, the element from the matrix in the $i$-th row and $j$-th column corresponds to the $((i-1)*c+j)$-th element of the string.\n\nYou need to check whether the beautiful matrix from which the string $s$ was obtained could be \\textbf{squared}. In other words, you need to check whether the string $s$ could have been build from a \\textbf{square} beautiful binary matrix (i.e., one where $r=c$).",
    "tutorial": "Assume that string was created from the beautiful binary matrix with size $r\\times c$. If $r\\le 2$ or $c\\le 2$, then the whole matrix consists of '1'. This means that the string will have only one character and this is the only case such happening. So, if the whole string is constructed out of '1', we print \"Yes\" only if the size of the string is 4, since only $r=c=2$ is a good matrix for us. Otherwise, we have at least one '0' in the string. Let's look at what is the index of the first '0'. If it has index $r+1$, since the whole first line and the first character of the first line equal to '1', so now, we have a fixed value of $r$ (index of the first '0' minus 1) and the answer is \"Yes\" only if $r$ is the square root of $n$.",
    "code": "for _ in range(int(input())):\n    n=int(input())\n    s=input()\n    i=0\n    while i<n and s[i]=='1':\n        i+=1\n    if i==n:\n        if n==4:\n            print(\"Yes\")\n        else:\n            print(\"No\")\n        continue\n    i-=1\n    if i*i==n:\n        print(\"Yes\")\n    else:\n        print(\"No\")",
    "tags": [
      "brute force",
      "math",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2008",
    "index": "C",
    "title": "Longest Good Array",
    "statement": "Today, Sakurako was studying arrays. An array $a$ of length $n$ is considered good if and only if:\n\n- the array $a$ is increasing, meaning $a_{i - 1} < a_i$ for all $2 \\le i \\le n$;\n- the differences between adjacent elements are increasing, meaning $a_i - a_{i-1} < a_{i+1} - a_i$ for all $2 \\le i < n$.\n\nSakurako has come up with boundaries $l$ and $r$ and wants to construct a good array of maximum length, where $l \\le a_i \\le r$ for all $a_i$.\n\nHelp Sakurako find the maximum length of a good array for the given $l$ and $r$.",
    "tutorial": "We can solve this problem greedily. Let's choose the first element equal to $l$. Then, the second element should be $l+1$. The third $l+3$, and so on. In general, the $i-$th element is equal to $l+\\frac{i\\cdot (i+1)}{2}$. Proof of this solution: Assume that array $a$ is the array made by our algorithm and $b$ is the array with a better answer. This means that $len(b)>len(a)$. By the construction of $a$, there exists an integer $i$ such that for all $j<i$, $a_j=b_j$ and $a_i<b_i$, because $a_i$ we choose as the smallest possible element. WLOG assume that $len(b)=len(a)+1=n$. Then $b_n-b_{n-1}>b_{n-1}-b_{n-2}\\ge a_{n-1}-a_{n-2}$. So, we can append $b_n$ to the array $a$, which leads to a contradiction. Now, the task is to find the biggest $x$ such that $l+\\frac{x\\cdot (x+1)}{2}\\le r$. In fact, it can be found by binary search, the formula of discriminant, or just by brute force.",
    "code": "for _ in range(int(input())): \n    a, b = map(int, input().split())\n    i = 0\n    while a + i <= b:\n        a += i\n        i += 1\n    print(i)",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2008",
    "index": "D",
    "title": "Sakurako's Hobby",
    "statement": "For a certain permutation $p$$^{\\text{∗}}$ Sakurako calls an integer $j$ reachable from an integer $i$ if it is possible to make $i$ equal to $j$ by assigning $i=p_i$ a certain number of times.\n\nIf $p=[3,5,6,1,2,4]$, then, for example, $4$ is reachable from $1$, because: $i=1$ $\\rightarrow$ $i=p_1=3$ $\\rightarrow$ $i=p_3=6$ $\\rightarrow$ $i=p_6=4$. Now $i=4$, so $4$ is reachable from $1$.\n\nEach number in the permutation is colored either black or white.\n\nSakurako defines the function $F(i)$ as the number of black integers that are reachable from $i$.\n\nSakurako is interested in $F(i)$ for each $1\\le i\\le n$, but calculating all values becomes very difficult, so she asks you, as her good friend, to compute this.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation (the number $2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$, but the array contains $4$).\n\\end{footnotesize}",
    "tutorial": "Any permutation can be divided into some number of cycles, so $F(i)$ is equal to the number of black colored elements in the cycle where $i$ is. So, we can write out all cycles in $O(n)$ and memorize for each $i$ the number of black colored elements in the cycle where it is.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    b = [0] * (n + 1)\n    us = [0] * (n + 1)\n    p = [k-1 for k in map(int, input().split())]\n    s = input()\n    for i in range(0, n):\n        if us[i]:\n            continue\n        sz = 0\n        while not us[i]:\n            us[i] = 1\n            sz += s[i] == '0'\n            i = p[i]\n        while us[i] != 2:\n            b[i] = sz\n            us[i] = 2\n            i = p[i]\n    print(\" \".join(map(str, b[:-1])))",
    "tags": [
      "dp",
      "dsu",
      "graphs",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2008",
    "index": "E",
    "title": "Alternating String",
    "statement": "Sakurako really loves alternating strings. She calls a string $s$ of lowercase Latin letters an alternating string if characters in the even positions are the same, if characters in the odd positions are the same, and the length of the string is \\textbf{even}.\n\nFor example, the strings 'abab' and 'gg' are alternating, while the strings 'aba' and 'ggwp' are not.\n\nAs a good friend, you decided to gift such a string, but you couldn't find one. Luckily, you can perform two types of operations on the string:\n\n- Choose an index $i$ and delete the $i$-th character from the string, which will reduce the length of the string by $1$. This type of operation can be performed \\textbf{no more than $1$ time};\n- Choose an index $i$ and replace $s_i$ with any other letter.\n\nSince you are in a hurry, you need to determine the minimum number of operations required to make the string an alternating one.",
    "tutorial": "Firstly, since first operation can be used at most 1 time, we need to use it only when string has odd length. Let's assume that the string has even length, then we can look at characters on odd and even positions independently. So, if we change all characters on even positions to the character that which is occurs the most. Same goes to the characters on the odd position. Now, we have case where we need to delete one character. We can make prefix sum on even positions (let's call $pref_1[i][c]$ number of $c$ on such even $i>j$ and $s[j]=c$), prefix sum on odd position (let's call it $pref_2[i][c]$. Definition same as for $pref_1[i][c]$ but with odd instead of even), suffix sum on even positions (let's call it $suff_1[i][c]$ and definition same as $pref_1[i][c]$ but with $j>i$ instead of $i>j$) and suffix sum on odd positions (let's call it $suff_2[i][c]$ and definition same as $pref_2[i][c]$ but with $j>i$ instead of $i>j$). If we delete character on index $i$, our string after $i$ shift right and changes parity for all indeces bigger then $i$, so to find how many characters $c$ there are on even positions after deleting index $i$ is $pref_1[i][c]+suf_2[i][c]$. Using this, we can try to delete each character independently and solve the task as it has even length.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    s = input()\n    res = len(s)\n    if n % 2 == 0:\n        v = [[0] * 26 for _ in range(2)]\n        for i in range(n):\n            v[i % 2][ord(s[i]) - ord('a')] += 1\n        for i in range(2):\n            mx = max(v[i])\n            res -= mx\n        print(res)\n    else:\n        pref = [[0] * 26 for _ in range(2)]\n        suf = [[0] * 26 for _ in range(2)]\n        for i in range(n - 1, -1, -1):\n            suf[i % 2][ord(s[i]) - ord('a')] += 1\n        for i in range(n):\n            suf[i % 2][ord(s[i]) - ord('a')] -= 1\n            ans = n\n            for k in range(2):\n                mx = 0\n                for j in range(26):\n                    mx = max(mx, suf[1 - k][j] + pref[k][j])\n                ans -= mx\n            res = min(res, ans)\n            pref[i % 2][ord(s[i]) - ord('a')] += 1\n        print(res)",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2008",
    "index": "F",
    "title": "Sakurako's Box",
    "statement": "Sakurako has a box with $n$ balls. Each ball has it's value. She wants to bet with her friend that if the friend randomly picks two balls from the box (it could be two distinct balls, but they may have the same value), the product of their values will be the same as the number that Sakurako guessed.\n\nSince Sakurako has a PhD in probability, she knows that the best number to pick is the expected value, but she forgot how to calculate it. Help Sakurako and find the expected value of the product of two elements from the array.\n\nIt can be shown that the expected value has the form $\\frac{P}{Q}$, where $P$ and $Q$ are non-negative integers, and $Q \\ne 0$. Report the value of $P \\cdot Q^{-1}(\\bmod 10^9+7)$.",
    "tutorial": "By the statement, we need to find the value of this expresion $\\frac{\\sum_{i=0}^{n}\\sum_{j=i+1}^{n} a_i\\cdot a_j}{\\frac{n\\cdot (n-1)}{2}}$. Let's find this two values separately. For the first, we can do it in several ways. We can see that this sum equal to $\\sum_{i=0}^{n}a_i\\cdot (\\sum_{j=i+1}^{n}a_j)$ and compute by prefix sum. Also, we can notice that it is equal to $\\frac{(\\sum_{i=0}^{n}a_i)^2-\\sum_{i=0}^{n}a_i^2}{2}$. Note, that for second approach you need to use division by modulo, i.e. $2^{-1}=2^{p-2}$ for prime p. To compute $\\frac{n\\cdot (n-1)}{2}$, you can compute $n\\cdot (n-1)$ by modulo and than use division by modulo for $2^{-1}$. Then, also using division by modulo you need to divide first value by second.",
    "code": "import sys; input = sys.stdin.readline\nfor i in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    ans = 0\n    s = 0\n    mod = int(1e9 + 7)\n    for i in range(n): s += a[i]\n    s %= mod\n    for i in range(n):\n        s -= a[i]\n        ans = (ans + a[i] * s) % mod\n    ans = (ans * pow(n * (n - 1) // 2, mod - 2, mod)) % mod\n    print(ans)\n",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2008",
    "index": "G",
    "title": "Sakurako's Task",
    "statement": "Sakurako has prepared a task for you:\n\nShe gives you an array of $n$ integers and allows you to choose $i$ and $j$ such that $i \\neq j$ and $a_i \\ge a_j$, and then assign $a_i = a_i - a_j$ or $a_i = a_i + a_j$. You can perform this operation any number of times for any $i$ and $j$, as long as they satisfy the conditions.\n\nSakurako asks you what is the maximum possible value of $mex_k$$^{\\text{∗}}$ of the array after any number of operations.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$mex_k$ is the $k$-th non-negative integer that is absent in the array. For example, $mex_1(\\{1,2,3 \\})=0$, since $0$ is the first element that is not in the array, and $mex_2(\\{0,2,4 \\})=3$, since $3$ is the second element that is not in the array.\n\\end{footnotesize}",
    "tutorial": "Let's look at case when $n=1$. We cannot change the value of the element, so we will not change the array. If $n>1$, let's call $g=gcd(a_1,a_2,\\dots,a_n)$. Using operations in the statement, we can get only numbers 0 and that have $g$ as a divisor. So, the best array for this task will be $a_i=(i-1)\\cdot g$. Now, we can find where the $mex_k$ should be in linear time. Firstly, if it is before the first one, then the answer is $k$, otherwise, we can assign $k=k-a_1$. Then let's look at the second element. If $a_1+k<a_2$, then answer should be $a_1+k$ and otherwise we can assign $k=k-a_2+a_1-1$. In other words, when we look if our $k$ can be in range from $a_i$ to $a_{i+1}$, we know that number of elements that were not in the array and less than $a_i$ equal to $k+a_i$. Then, when we find such $i$, we can output the answer.",
    "code": "import math\n\nt = int(input())\nfor _ in range(t):\n    n, k = map(int, input().split())\n    a = list(map(int, input().split()))\n    g = 0\n    mx = 0\n    for i in range(n):\n        g = math.gcd(g, a[i])\n        mx = max(mx, a[i])\n    if g == 0:\n        print(k)\n        continue\n    a.sort()\n    q = -g\n    if n != 1:\n        for i in range(n):\n            q += g\n            a[i] = q\n    a.append(10**16)\n    lst = -1\n    for i in range(n + 1):\n        if k <= a[i] - lst - 1:\n            break\n        k -= max(a[i] - lst - 1, 0)\n        lst = a[i]\n    print(lst + k)",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2008",
    "index": "H",
    "title": "Sakurako's Test",
    "statement": "Sakurako will soon take a test. The test can be described as an array of integers $n$ and a task on it:\n\nGiven an integer $x$, Sakurako can perform the following operation any number of times:\n\n- Choose an integer $i$ ($1\\le i\\le n$) such that $a_i\\ge x$;\n- Change the value of $a_i$ to $a_i-x$.\n\nUsing this operation any number of times, she must find the minimum possible median$^{\\text{∗}}$ of the array $a$.\n\nSakurako knows the array but does not know the integer $x$. Someone let it slip that one of the $q$ values of $x$ will be in the next test, so Sakurako is asking you what the answer is for each such $x$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The median of an array of length $n$ is the element that stands in the middle of the sorted array (at the $\\frac{n+2}{2}$-th position for even $n$, and at the $\\frac{n+1}{2}$-th for odd)\n\\end{footnotesize}",
    "tutorial": "Let's fix one $x$ and try to solve this task for it. As we know, in $0-$indexed array median is $\\lfloor\\frac{n}{2}\\rfloor$ where $n$ is number of elements in the array, so to find median, we need to find the smallest element which has at least $\\lfloor\\frac{n}{2}\\rfloor$ elements in the array that is less or equal to it. Also, it is obvious, that we need to decrease all elements till we can, since the least element, the least median of the array is. So, after all operation, we change $a_i$ to $a_i \\mod x$. How to find number of $i$ that $a_i\\mod x\\le m$ for some $m$. In fact, we can try to find number of elements in range $[k\\cdot x,k\\cdot x+m]$ for all $k$, since all this elements will be less then $m$ if we take it by modulo $x$. To find number of elements in such range, we can notice that $a_i\\le n$, so we can make prefix sum of counting array (let's call it $pref[i]$ number of elements less or equal $i$) and then number of elements in tange $[a,b]$ will be $pref[b]-pref[a-1]$. Also, since $a_i\\le n$, $k$ will be less then $\\frac{n}{x}$, so for fixed $x$ our solution will work in $\\frac{n}{x}\\cdot log(n)$. Let's precompute it for all $x$ in range $[1,n]$. Then, it will work in time $\\sum_{x=1}^{n+1}\\frac{n}{x}\\cdot log(n)=log(n)\\cdot \\sum_{x=1}^{n+1}\\frac{n}{x} \\stackrel{(*)}{=} log(n)\\cdot n\\cdot log(n)=n\\cdot log^2(n)$. $(*)$ This transition is true because of $\\sum_{i=1}^{n+1}\\frac{n}{x}$ is harmonic series. It means, $\\sum_{i=1}^{n+1}\\frac{n}{x}=n\\cdot \\sum_{i=1}^{n+1}\\frac{1}{x}\\le n\\cdot log(n)$.",
    "code": "for _ in range(int(input())):\n    n, m = map(int, input().split())\n    a = list(map(int, input().split()))\n    c = [0] * (n + 1)\n    \n    for i in range(n):\n        c[a[i]] += 1\n    \n    for i in range(1, n + 1):\n        c[i] += c[i - 1]\n    \n    res = [0] * (n + 1)\n    \n    for x in range(1, n + 1):\n        l, r = 0, x\n        while l < r:\n            mid = (l + r) // 2\n            cnt = c[mid]\n            for k in range(1, n // x + 1):\n                cnt += c[min(k * x + mid, n)] - c[k * x - 1]\n            if cnt - 1 >= n // 2:\n                r = mid\n            else:\n                l = mid + 1\n        res[x] = l\n    \n    for _ in range(m):\n        x = int(input())\n        print(res[x])",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2009",
    "index": "A",
    "title": "Minimize!",
    "statement": "You are given two integers $a$ and $b$ ($a \\leq b$). Over all possible integer values of $c$ ($a \\leq c \\leq b$), find the minimum value of $(c - a) + (b - c)$.",
    "tutorial": "We choose $c$ between $a$ and $b$ $(a \\leq c \\leq b)$. The distance is $(c - a) + (b - c) = b - a$. Note that the distance does not depend on the the position $c$ at all.",
    "code": "for _ in range(int(input())):\n    a,b = map(int,input().split())\n    print(b-a)",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2009",
    "index": "B",
    "title": "osu!mania",
    "statement": "You are playing your favorite rhythm game, osu!mania. The layout of your beatmap consists of $n$ rows and $4$ columns. Because notes at the bottom are closer, you will process the bottommost row first and the topmost row last. Each row will contain exactly one note, represented as a '#'.\n\nFor each note $1, 2, \\dots, n$, in the order of processing, output the column in which the note appears.",
    "tutorial": "Implement the statement. Iterate from $n-1$ to $0$ and use the .find() method in std::string in C++ (or .index() in python) to find the '#' character.",
    "code": "import sys\ninput=lambda:sys.stdin.readline().rstrip()\n\nfor i in range(int(input())):\n    n=int(input())\n    print(*reversed([input().index(\"#\")+1 for i in range(n)]))",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2009",
    "index": "C",
    "title": "The Legend of Freya the Frog",
    "statement": "Freya the Frog is traveling on the 2D coordinate plane. She is currently at point $(0,0)$ and wants to go to point $(x,y)$. In one move, she chooses an integer $d$ such that $0 \\leq d \\leq k$ and jumps $d$ spots forward in the direction she is facing.\n\nInitially, she is facing the positive $x$ direction. After every move, she will alternate between facing the positive $x$ direction and the positive $y$ direction (i.e., she will face the positive $y$ direction on her second move, the positive $x$ direction on her third move, and so on).\n\nWhat is the minimum amount of moves she must perform to land on point $(x,y)$?",
    "tutorial": "Consider the $x$ and $y$ directions separately and calculate the jumps we need in each direction. The number of jumps we need in the $x$ direction is $\\lceil \\frac{x}{k} \\rceil$ and similarily $\\lceil \\frac{y}{k} \\rceil$ in the $y$ direction. Now let's try to combine them to obtain the total number of jumps. Let's consider the following cases: $\\lceil \\frac{y}{k} \\rceil \\geq \\lceil \\frac{x}{k} \\rceil$. In this case, there will need to be $\\lceil \\frac{y}{k} \\rceil - \\lceil \\frac{x}{k} \\rceil$ extra jumps in the $y$ direction. While Freya performs these extra jumps, she will choose $d = 0$ for the $x$ direction. In total, there will need to be $2 \\cdot \\lceil \\frac{y}{k} \\rceil$ jumps. $\\lceil \\frac{y}{k} \\rceil \\geq \\lceil \\frac{x}{k} \\rceil$. In this case, there will need to be $\\lceil \\frac{y}{k} \\rceil - \\lceil \\frac{x}{k} \\rceil$ extra jumps in the $y$ direction. While Freya performs these extra jumps, she will choose $d = 0$ for the $x$ direction. In total, there will need to be $2 \\cdot \\lceil \\frac{y}{k} \\rceil$ jumps. $\\lceil \\frac{x}{k} \\rceil > \\lceil \\frac{y}{k} \\rceil$. We can use the same reasoning as the previous case, but there's a catch. Since Freya is initially facing the $x$ direction, for the last jump, she does not need to jump in the $y$ direction. In total, there will need to be $2 \\cdot \\lceil \\frac{x}{k} \\rceil - 1$ jumps. $\\lceil \\frac{x}{k} \\rceil > \\lceil \\frac{y}{k} \\rceil$. We can use the same reasoning as the previous case, but there's a catch. Since Freya is initially facing the $x$ direction, for the last jump, she does not need to jump in the $y$ direction. In total, there will need to be $2 \\cdot \\lceil \\frac{x}{k} \\rceil - 1$ jumps.",
    "code": "for _ in range(int(input())):\n    x,y,k = map(int,input().split())\n    print(max(2*((x+k-1)//k)-1,2*((y+k-1)//k)))",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2009",
    "index": "D",
    "title": "Satyam and Counting",
    "statement": "Satyam is given $n$ distinct points on the 2D coordinate plane. \\textbf{It is guaranteed that $0 \\leq y_i \\leq 1$ for all given points $(x_i, y_i)$.} How many different nondegenerate right triangles$^{\\text{∗}}$ can be formed from choosing three different points as its vertices?\n\nTwo triangles $a$ and $b$ are different if there is a point $v$ such that $v$ is a vertex of $a$ but not a vertex of $b$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A nondegenerate right triangle has positive area and an interior $90^{\\circ}$ angle.\n\\end{footnotesize}",
    "tutorial": "Initially, the obvious case one might first consider is an upright right triangle (specifically, the triangle with one of its sides parallel to the $y$-axis). This side can only be made with two points in the form $(x, 0)$ and $(x,1)$. We only need to search third point. Turns out, the third point can be any other unused vertex! If the third point has $y = 0$, then it will be an upright triangle, but if the third point has $y = 1$, it will simply be upside down. One of the other case is in the form of $(x,0), (x+1,1), (x+2, 0)$. Let's see why this is a right triangle. Recall that in right triangle, the sum of the squares of two of the sides must equal to the square of the third side. The length between the first and the second point is $\\sqrt 2$ because it is the diagonal of $1$ by $1$ unit block. Similarily, the second and third point also has length $\\sqrt 2$. Obviously, the length between the first and third point is $2$. Since we have $\\sqrt 2^2 + \\sqrt 2^2 = 2^2$, this is certainly a right triangle. Of course, we can flip the $y$ values of each point and it will still be a valid right triangle, just upside down.",
    "code": "from collections import Counter\nfor _ in range(int(input())):\n    n = int(input())\n    nums = []\n    for i in range(n):\n        x,y = map(int,input().split())\n        nums.append((x,y))\n    ans = 0\n    b = Counter(x[0] for x in nums)\n    check = set(nums)\n    for i in b:\n        if b[i]==2: ans += n-2\n    for p in check:\n        if (p[0]-1,p[1]^1) in check and (p[0]+1,p[1]^1) in check: \n            ans +=1\n    print(ans)\n    ",
    "tags": [
      "geometry",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2009",
    "index": "E",
    "title": "Klee's SUPER DUPER LARGE Array!!!",
    "statement": "Klee has an array $a$ of length $n$ containing integers $[k, k+1, ..., k+n-1]$ in that order. Klee wants to choose an index $i$ ($1 \\leq i \\leq n$) such that $x = |a_1 + a_2 + \\dots + a_i - a_{i+1} - \\dots - a_n|$ is minimized. Note that for an arbitrary integer $z$, $|z|$ represents the absolute value of $z$.\n\nOutput the minimum possible value of $x$.",
    "tutorial": "We can rewrite $x$ as $|a_1+\\dots+a_i-(a_{i+1}+\\dots+a_n)|$. Essentially, we want to minimize the absolute value difference between the sums of the prefix and the suffix. With absolute value problems. it's always good to consider the positive and negative cases separately. We will consider the prefix greater than the suffix separately with the less than case. We can use binary search to search for the greatest $i$ such that $a_1 + \\dots + a_i \\leq a_{i+1} + \\dots + a_n$. Note that here, the positive difference is minimized. If we move to $i+1$, then the negative difference is minimized (since the sum of prefix will now be less than the sum of suffix). The answer is the minimum absolute value of both cases. To evaluate $a_1 + \\dots + a_i$ fast, we can use the sum of arithmetic sequence formula. Bonus: Solve in $\\mathcal{O}(1)$.",
    "code": "import sys\ninput=sys.stdin.readline\n\nfrom math import floor,sqrt\n\nf=lambda x: (2*x*x + x*(4*k-2) + (n-n*n-2*k*n))//2\n\nt=int(input())\nfor _ in range(t):\n    n,k=map(int,input().split())\n    D=4*k*k + 4*k*(n-1) + (2*n*n-2*n+1)\n    i=(floor(sqrt(D))-(2*k-1))//2\n    ans=min(abs(f(i)),abs(f(i+1)))\n    print(ans) ",
    "tags": [
      "binary search",
      "math",
      "ternary search"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2009",
    "index": "F",
    "title": "Firefly's Queries",
    "statement": "Firefly is given an array $a$ of length $n$. Let $c_i$ denote the $i$'th cyclic shift$^{\\text{∗}}$ of $a$. She creates a new array $b$ such that $b = c_1 + c_2 + \\dots + c_n$ where $+$ represents concatenation$^{\\text{†}}$.\n\nThen, she asks you $q$ queries. For each query, output the sum of all elements in the subarray of $b$ that starts from the $l$-th element and ends at the $r$-th element, inclusive of both ends.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The $x$-th ($1 \\leq x \\leq n$) cyclic shift of the array $a$ is $a_x, a_{x+1} \\ldots a_n, a_1, a_2 \\ldots a_{x - 1}$. Note that the $1$-st shift is the initial $a$.\n\n$^{\\text{†}}$The concatenation of two arrays $p$ and $q$ of length $n$ (in other words, $p + q$) is $p_1, p_2, ..., p_n, q_1, q_2, ..., q_n$.\n\\end{footnotesize}",
    "tutorial": "Let's duplicate the array $a$ and concatenate it with itself. Now, $a$ should have length $2n$ and $a_i = a_{i-n}$ for all $n < i \\leq 2n$. Now, the $j$'th element of the $i$'th rotation is $a_{i+j-1}$. It can be shown for any integer $x$, it belongs in rotation $\\lfloor \\frac{x-1}{n} \\rfloor + 1$ and at position $(x-1) \\mod n + 1$. Let $rl$ denote the rotation for $l$ and $rr$ denote the rotation for $r$. If $rr - rl > 1$, we are adding $rr-rl-1$ full arrays to our answer. The leftovers is just the suffix of rotation $rl$ starting at position $l$ and the prefix of rotation of $rr$ starting at position $r$. This can be done with prefix sums. You may need to handle $rl=rr$ separately.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        ll n, q;\n        cin >> n >> q;\n        vector<ll> a(n), ps(1);\n        for (ll &r : a) {\n            cin >> r;\n            ps.push_back(ps.back() + r);\n        }\n        for (ll &r : a) {\n            ps.push_back(ps.back() + r);\n        }\n        while (q--) {\n            ll l, r;\n            cin >> l >> r;\n            l--; r--;\n            ll i = l / n, j = r / n;\n            l %= n; r %= n;\n            cout << ps[n] * (j - i + 1) - (ps[i + l] - ps[i]) - (ps[j + n] - ps[j + r + 1]) << \"\\n\";\n        }\n    }\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "flows",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2009",
    "index": "G1",
    "title": "Yunli's Subarray Queries (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. In this version, it is guaranteed that $r=l+k-1$ for all queries.}\n\nFor an arbitrary array $b$, Yunli can perform the following operation any number of times:\n\n- Select an index $i$. Set $b_i = x$ where $x$ is any integer she desires ($x$ is not limited to the interval $[1,n]$).\n\nDenote $f(b)$ as the minimum number of operations she needs to perform until there exists a consecutive subarray$^{\\text{∗}}$ of length at least $k$ in $b$.\n\nYunli is given an array $a$ of size $n$ and asks you $q$ queries. In each query, you must output $\\sum_{j=l+k-1}^{r} f([a_l, a_{l+1}, \\ldots, a_j])$. Note that in this version, you are only required to output $f([a_l, a_{l+1}, \\ldots, a_{l+k-1}])$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$If there exists a consecutive subarray of length $k$ that starts at index $i$ ($1 \\leq i \\leq |b|-k+1$), then $b_j = b_{j-1} + 1$ for all $i < j \\leq i+k-1$.\n\\end{footnotesize}",
    "tutorial": "We first make the sequence $b_i=a_i-i$ for all $i$. Now, if $b_i=b_j$, then $i$ and $j$ are in correct relative order. Now, to solve the problem, we precompute the answer for every window of $k$, and then each query is a lookup. We use a sliding window, maintaining a multiset of frequencies of values of $b$ in the current window. To move from the window $[i\\ldots i+k-1]$ to $i+1 \\ldots i+k$, we lower the frequency of $b_i$ by $1$, and increase the frequency of $b_{i+k}$ by $1$.",
    "code": "#include \"bits/stdc++.h\"\n#pragma GCC optimize(\"O3,unroll-loops\")\n#pragma GCC target(\"avx,avx2,sse,sse2\")\n#define fast ios_base::sync_with_stdio(0) , cin.tie(0) , cout.tie(0)\n#define endl '\\n'\n#define int long long\n#define f first\n#define mp make_pair\n#define s second\nusing namespace std;\n\nvoid solve(){\n    int n, k, q; cin >> n >> k >> q;\n    int a[n + 1]; for(int i = 1; i <= n; i++) cin >> a[i];\n    map <int,int> m;\n    multiset <int> tot;\n    for(int i = 1; i <= n; i++) tot.insert(0);\n    for(int i = 1; i < k; i++){\n        tot.erase(tot.find(m[a[i] - i]));\n        m[a[i] - i]++;\n        tot.insert(m[a[i] - i]);\n    }\n    int ret[n + 1];\n    for(int i = k; i <= n; i++){\n        tot.erase(tot.find(m[a[i] - i]));\n        m[a[i] - i]++;\n        tot.insert(m[a[i] - i]);\n        int p = i - k + 1;\n        ret[p] = k - *tot.rbegin();\n        tot.erase(tot.find(m[a[p] - p]));\n        m[a[p] - p]--;\n        tot.insert(m[a[p] - p]);\n    }\n    while(q--){\n        int l, r ; cin >> l >> r;\n        cout << ret[l] << endl;\n    }\n    tot.clear();\n    m.clear();\n}\n\nsigned main()\n{\n    fast;\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2009",
    "index": "G2",
    "title": "Yunli's Subarray Queries (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, it is guaranteed that $r \\geq l+k-1$ for all queries.}\n\nFor an arbitrary array $b$, Yunli can perform the following operation any number of times:\n\n- Select an index $i$. Set $b_i = x$ where $x$ is any integer she desires ($x$ is not limited to the interval $[1,n]$).\n\nDenote $f(b)$ as the minimum number of operations she needs to perform until there exists a consecutive subarray$^{\\text{∗}}$ of length at least $k$ in $b$.\n\nYunli is given an array $a$ of size $n$ and asks you $q$ queries. In each query, you must output $\\sum_{j=l+k-1}^{r} f([a_l, a_{l+1}, \\ldots, a_j])$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$If there exists a consecutive subarray of length $k$ that starts at index $i$ ($1 \\leq i \\leq |b|-k+1$), then $b_j = b_{j-1} + 1$ for all $i < j \\leq i+k-1$.\n\\end{footnotesize}",
    "tutorial": "First, read the solution to the easy version of the problem to compute the answer for every window of $k$. Let $c_i=f([a_i, ..., a_{i+k-1}])$. Now, the problem simplifies to finding $\\sum_{j=l}^{r-k+1} ( \\min_{i=l}^{j} c_i)$ We will answer the queries offline in decreasing order of $l$. We maintain a lazy segment tree. We have a variable $x$ sweeping from $n-k$ to $0$. As the variable sweeps leftwards, in node $i$ of the segment tree, we keep track of $\\min_{j=x}^{i}c_i$. To decrease the value of $x$, we note that the range $[x-1, y]$ in the segment tree will be set to $c_{x-1}$, where $y$ is the largest value such that $c_y>c_{x-1}$ but $c_{y+1}\\leq c_{x-1}$ (or $y=n-1$). To find the $y$ for each $x$, we may either walk/binary search in the segment tree, or use a monotonic stack. Let $p_i$ be the smallest value $j>i$ such that $c_j<c_i.$ We can calculate these values using a monotonic stack and iterating through $c$ backwards. If such $j$ does not exist, then we let $p_i=n.$ Then $f(h,i)=c_i$ for all $i\\le h-k+1<p_i.$ Further, $f(h,i)=c_{p_i}$ for $p_i\\le h-k+1<p_{p_i},$ and so on. Now, let $w(0,i)=i,$ and $w(h,i)=p_{w(h-1,i)}$ for $h>0.$ To calculate the answer for a query $(l,r),$ consider the largest value of $j$ such that $w(j,l)\\le r.$ Then we can take the sum $c_{w(j,l)}\\cdot(r-w(j,l)+1)+\\sum_{i=1}^jc_{w(i-1,l)}\\cdot(w(i,l)-w(i-1,l)).$ Now it remains to quickly calculate this sum. We can use binary lifting to solve this. Specifically, we create an $n\\times20$ data table where $d[i][j]=\\sum_{h=1}^{2^j}c_{w(h-1,i)}\\cdot(w(h,i)-w(h-1,i)),$ if $w(2^j,i)$ exists, and $-1$ otherwise. We can precompute this table recursively, as $d[i][0]=c_i\\cdot(w(1,i)-i)$ and $d[i][j]=d[i][j-1]+d[w(2^{j-1},i)][j-1].$ Then, to answer queries, we iterate $j$ from $19$ to $0,$ and if $w(2^j,l)\\le r,$ we add $d[l][j]$ to our answer, and set $l=w(2^j,l).$ At the end, we add $c_l\\cdot(r-l+1)$ to our answer.",
    "code": "#include <bits/stdc++.h>\n#define int long long\n#define pii pair<int, int>\n#define fi first\n#define se second\nusing namespace std;\nvoid solve() {\n    int n, k, q;\n    cin >> n >> k >> q;\n    vector<int> a(n);\n    for (int &r : a) cin >> r;\n    vector<int> c(3 * n), v(n);\n    multiset<int> s;\n    for (int i = 0; i < k; i++) c[a[i] - i + n - 1]++;\n    for (int r : c) s.insert(r);\n    v[k - 1] = k - *s.rbegin();\n    for (int i = k; i < n; i++) {\n        int x = a[i] - i + n - 1, y = a[i - k] - i + k + n - 1;\n        c[x]++;\n        s.erase(s.find(c[x] - 1));\n        s.insert(c[x]);\n        c[y]--;\n        s.erase(s.find(c[y] + 1));\n        s.insert(c[y]);\n        v[i] = k - *s.rbegin();\n    }\n    vector<int> l(n, -1);\n    stack<pii> t;\n    for (int i = k - 1; i < n; i++) {\n        while (!t.empty()) {\n            if (t.top().se <= v[i]) break;\n            l[t.top().fi] = i;\n            t.pop();\n        }\n        t.push({i, v[i]});\n    }\n    vector<vector<pii>> w(n, vector<pii>(20, {-1, -1}));\n    for (int i = n - 1; i >= k - 1; i--) {\n        w[i][0].se = l[i];\n        if (l[i] < 0) {\n            w[i][0].fi = (n - i) * v[i];\n            continue;\n        }\n        w[i][0].fi = (l[i] - i) * v[i];\n        for (int j = 1; j < 20; j++) {\n            if (w[w[i][j - 1].se][j - 1].se < 0) break;\n            w[i][j].se = w[w[i][j - 1].se][j - 1].se;\n            w[i][j].fi = w[i][j - 1].fi + w[w[i][j - 1].se][j - 1].fi;\n        }\n    }\n    while (q--) {\n        int l, r, ans = 0;\n        cin >> l >> r;\n        l--;\n        r--;\n        l += k - 1;\n        for (int j = 19; ~j; j--) {\n            if (w[l][j].se < 0) continue;\n            if (w[l][j].se > r) continue;\n            ans += w[l][j].fi;\n            l = w[l][j].se;\n        }\n        cout << ans + v[l] * (r - l + 1) << \"\\n\";\n    }\n}\nint32_t main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2009",
    "index": "G3",
    "title": "Yunli's Subarray Queries (extreme version)",
    "statement": "\\textbf{This is the extreme version of the problem. In this version, the output of each query is different from the easy and hard versions. It is also guaranteed that $r \\geq l+k-1$ for all queries.}\n\nFor an arbitrary array $b$, Yunli can perform the following operation any number of times:\n\n- Select an index $i$. Set $b_i = x$ where $x$ is any integer she desires ($x$ is not limited to the interval $[1,n]$).\n\nDenote $f(b)$ as the minimum number of operations she needs to perform until there exists a consecutive subarray$^{\\text{∗}}$ of length at least $k$ in $b$.\n\nYunli is given an array $a$ of size $n$ and asks you $q$ queries. In each query, you must output $\\sum_{i=l}^{r-k+1} \\sum_{j=i+k-1}^{r} f([a_i, a_{i+1}, \\ldots, a_j])$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$If there exists a consecutive subarray of length $k$ that starts at index $i$ ($1 \\leq i \\leq |b|-k+1$), then $b_j = b_{j-1} + 1$ for all $i < j \\leq i+k-1$.\n\\end{footnotesize}",
    "tutorial": "I decided to write the Editorial for this problem in a step-by-step manner. Some of the steps are really short and meant to be used as hints but i decided to have a uniform naming for everything. Continuing from the easier versions of the problem, we know we need to compute sum of min of subarrays, and answer subarray queries on this. Consider the standard approach of finding sum of min over all subarrays. Sum of min of all subarrays for a fixed array is a well known problem. Here is how you can solve it, given an array $a$ of length $n$. Let $nx_i$ denote the smallest integer $j (j > i)$ such that $a_j < a_i$ holds, or $n + 1$ if no such integer exists. Similarly, define $pv_i$ denote the largest integer $j (j < i)$ such that $a_j \\le a_i$ holds, or $0$ if no such integer exists. The answer is simply $\\sum_{i = 1}^{n} a_i \\cdot (nx_i - i) \\cdot (i - pv_i)$. Calculating $nx_i$ and $pv_i$ can be done with Monotonic Stack. Given a query $(L, R)$, divide all indices $i$ ($L \\le i \\le R$) into $4$ groups depending on the existence of $nx_i$ and $pv_i$ within the interval $[L, R]$, i.e. : Case $1$ : $L \\le pv_i, nx_i \\le R$ Case $1$ : $L \\le pv_i, nx_i \\le R$ Case $2$ : $pv_i < L, nx_i \\le R$ Case $2$ : $pv_i < L, nx_i \\le R$ Case $3$ : $L \\le pv_i, nx_i > R$ Case $3$ : $L \\le pv_i, nx_i > R$ Case $4$ : $pv_i < L, nx_i > R$ Case $4$ : $pv_i < L, nx_i > R$ Try to calculate the contributions of each of these categories separately. Case $1$ can be reduced to rectangle queries. Case $4$ is simple to handle as there is atmost $1$ element which satisfies that condition, which (if exists) is the minimum element in the range $(L, R)$ which can be found using any RMQ data structure like Sparse Table or Segment Tree. Given a list of $n$ tuples $(l, r, v)$ and $q$ queries $(L, R)$ you have to add $v$ to answer of the $i$-th query if $L <= l <= r <= R$. This can be solved in $O((n + q) log(n))$ using Fenwick Tree and Sweepline. Iterate from $i = n$ to $i = 1$. For every tuple with left end at $i$ say $(i, j, v)$, add $v$ to a range query sum data structure at position $j$. Then, for every query with left end at $i$, we can simply query the range sum from $i = l$ to $i = r$ to get the required answer. For every index $i$ from $1$ to $n$, generate a tuple as $(pv_i, nx_i, a_i \\cdot (i - pv_i) \\cdot (nx_i - i)$. Then, solve the Rectangle Queries problem with this list of tuples. The answer will be the required contribution of all indices belonging to Case $1$. This leaves us with Case $2$ and $3$, which are symmetric, so we discuss only case $2$. Let us sweepline from $i = n$ to $i = 1$, maintaining a Monotonic Stack of elements, popping elements when we find a smaller element, similar to how we find $pv_i$. The indices belonging to Case $2$ are precisely the elements present in the Monotonic Stack (obviously ignore any element $> R$) when we have swept till $i = L$, with the possible exception of the minimum in the range $[L, R]$ (that might belong to Case $4$). Let's analyze the contribution of the indices in Case $2$. It is $a_i \\cdot (L - i + 1) \\cdot (nx_i - i)$. Take a look at what happens when we go from $L$ to $L - 1$, how do all the contributions of elements belonging to Case $2$ change. Some elements get popped from the Monotonic Stack because $a_{L - 1}$. We need to reset the contribution of all these elements to $0$. The elements that do not get popped have their contribution increased by exactly $(nx_i - i)$. $1$ element gets added to the Monotonic Stack, which is $a_{L - 1}$, so we need to initiliatize its contribution to $(nx_{L - 1} - (L - 1)).$ Resetting and Initiliazing Contribution is simple enough with most data structures, so let us focus on adding $(nx_i - i)$ to the elements present in the Monotonic Stack. We can keep a Lazy Segment Tree with $2$ parameters, $sumcon=$ sum of all contributions in this segment tree node, and $addcon =$ sum of $(nx_i - i)$ of all \"non-popped\" elements in this node. The lazy tag will denote how many contribution increases I have to do. We can simply do $sumcon += lazy * addcon$ for the lazy updates. Then, we can query the range sum from $L$ to $R$ to get the sum of contributions of all elements belonging to Case $2$. Case $3$ can be solved in a symmetric way. Adding up the answers over Case $1$, $2$, $3$ and $4$ will give us the required answer. We need to be quite careful with the Case $4$ element, as we might double count its contribution in Case $2$ and $3$. I handle this in the model solution by querying the sum of contribution in $[L, X - 1]$ where $X$ is the largest element present in the monostack which is $\\le R$, and handling $X$ separately. You can easily note that $X$ is the only element belonging to Case $4$ (if any at all).",
    "code": "#include <bits/stdc++.h>\n#define int long long\n#define ll long long \n#define pii pair<int,int> \n#define piii pair<pii,pii>\n#define fi first\n#define se second\n#pragma GCC optimize(\"O3,unroll-loops\")\n#pragma GCC target(\"avx2,bmi,bmi2,lzcnt,popcnt\")\nusing namespace std;\nstruct segtree {\n    const static int INF = 1e18, INF2 = 0;\n    int l, r;\n    segtree* lc, * rc;\n    int v = INF, v2=0, v3=0, v4=0;\n    segtree* getmem();\n    segtree() : segtree(-1, -1) {};\n    segtree(int l, int r) : l(l), r(r) {\n        if (l == r) return;\n        int m = (l + r) / 2;\n        lc = getmem(); *lc = segtree(l, m);\n        rc = getmem(); *rc = segtree(m + 1, r);\n    }\n    int op(int a, int b) {\n        return min(a,b); \n    }\n    int op2(int a, int b) {\n        return a+b; \n    }\n    void add(int qi, int qv, int h, int h4=0) {\n        if (r < qi || l > qi) return;\n        if (l == r) { if (v==INF) v=qv; v2+=qv, v3+=qv*h; v4+=qv*h4; return;}\n        lc->add(qi, qv, h, h4); rc->add(qi, qv, h, h4);\n        v = op(lc->v, rc->v);\n        v2 = op2(lc->v2, rc->v2); \n        v3 = op2(lc->v3, rc->v3); \n        v4 = op2(lc->v4, rc->v4); \n    }\n    int qrr(int ql, int qx) {\n        if (v>=qx||r<ql) return 1e9; \n        if (l==r) return l; \n        int k=lc->qrr(ql,qx); \n        if (k<1e9) return k; \n        return rc->qrr(ql,qx); \n    }\n    int q2(int ql, int qr) {\n        if (l > qr || r < ql) return INF2;\n        if (ql <= l && r <= qr) return v2;\n        return op2(lc->q2(ql, qr), rc->q2(ql, qr));\n    }\n    int q3(int ql, int qr) {\n        if (l > qr || r < ql) return INF2;\n        if (ql <= l && r <= qr) return v3;\n        return op2(lc->q3(ql, qr), rc->q3(ql, qr));\n    }\n    int q4(int ql, int qr) {\n        if (l > qr || r < ql) return INF2; \n        if (ql <= l && r <= qr) return v4; \n        return op2(lc->q4(ql, qr), rc->q4(ql, qr)); \n    }\n};\nsegtree mem[2000005];int memsz = 0;\nsegtree* segtree::getmem() { return &mem[memsz++]; }\nvoid solve() {\n    int n, k, q;\n    cin >> n >> k >> q;\n    vector<int> a(n);\n    for (int &r : a) cin >> r;\n    vector<int> c(2 * n), v(n);\n    multiset<int> s;\n    for (int i = 0; i < k; i++) c[a[i] - i + n - 1]++;\n    for (int r : c) s.insert(r);\n    v[k - 1] = k - *s.rbegin();\n    for (int i = k; i < n; i++) {\n        int x = a[i] - i + n - 1, y = a[i - k] - i + k + n - 1;\n        c[x]++;\n        s.erase(s.find(c[x] - 1));\n        s.insert(c[x]);\n        c[y]--;\n        s.erase(s.find(c[y] + 1));\n        s.insert(c[y]);\n        v[i] = k - *s.rbegin();\n    }\n    vector<int> ans(q);\n    vector<vector<pii>> w(n); \n    segtree co(0, n+2), lb(0, n+2), e(0,n+2),e2(0,n+2); \n    vector<int> rb(n); \n    stack<int> t; \n    for (int i = 0; i < q; i++) {\n        int l,r; cin >> l >> r; \n        w[l+k-2].push_back({i,r-1}); \n    }\n    for (int i = n-1; ~i; i--) {\n        e.add(i,v[i],i,i*i); \n        int j=min(n,e.qrr(i,v[i])); \n        rb[i]=j; \n        e.add(j-1,-v[i],i,i*i);\n        e2.add(j,v[i]*(j-i),i);\n        while (!t.empty()) {\n            int x=t.top(); \n            if (v[x]<v[i]) break;\n            t.pop(); \n            co.add(rb[x],v[x]*(rb[x]-x)*(x-i),0); \n            lb.add(x,v[x]*(x-i),x);\n            lb.add(rb[x]-1,-v[x]*(x-i),x); \n            e.add(x,-v[x],x,x*x);\n            e.add(rb[x]-1,v[x],x,x*x);\n            e2.add(rb[x],-v[x]*(rb[x]-x),x); \n        }\n        t.push(i); \n        int l=i;\n        for (auto [p,r]:w[i]) {\n            int x=e.q2(l,r), y=e.q3(l,r), z=e.q4(l,r);\n            int f=y*(r+1)-z, g=x*(r+1)-y; \n            int lx=lb.q2(l,r), ly=lb.q3(l,r); \n            ans[p]=co.q2(l,r+1)+lx*(r+1)-ly+e2.q3(l,r+1)-e2.q2(l,r+1)*(i-1)+f-g*(i-1);\n        }\n    }\n    for (int r:ans) cout << r << \"\\n\";\n}\n\nint32_t main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n\tint t = 1; cin >> t;\n\twhile (t--) solve();\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2013",
    "index": "A",
    "title": "Zhan's Blender",
    "statement": "Today, a club fair was held at \"NSPhM\". In order to advertise his pastry club, Zhan decided to demonstrate the power of his blender.\n\nTo demonstrate the power of his blender, Zhan has $n$ fruits.\n\nThe blender can mix up to $x$ fruits per second.\n\nIn each second, Zhan can put up to $y$ fruits into the blender. After that, the blender will blend $\\min(x, c)$ fruits, where $c$ is the number of fruits inside the blender. After blending, blended fruits are removed from the blender.\n\nHelp Zhan determine the minimum amount of time required for Zhan to blend all fruits.",
    "tutorial": "Let's consider two cases: If $x \\geq y$. In this case, the blender will mix $\\min(y, c)$ fruits every second (where $c$ is the number of unmixed fruits). Therefore, the answer will be $\\lceil \\frac{n}{y} \\rceil$. If $x < y$. Here, the blender will mix $\\min(x, c)$ fruits every second. In this case, the answer will be $\\lceil \\frac{n}{x} \\rceil$, similarly. Thus, the final answer is $\\lceil \\frac{n}{\\min(x, y)} \\rceil$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nint main(){\n    int t = 1;\n    cin >> t;\n    while(t--){\n        int n, x, y;\n        cin >> n >> x >> y;\n        x = min(x, y);\n        cout << (n + x - 1) / x << endl;\n    }\n}\n",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2013",
    "index": "B",
    "title": "Battle for Survive",
    "statement": "Eralim, being the mafia boss, manages a group of $n$ fighters. Fighter $i$ has a rating of $a_i$.\n\nEralim arranges a tournament of $n - 1$ battles, in each of which two not yet eliminated fighters $i$ and $j$ (\\textbf{$1 \\le i < j \\le n$}) are chosen, and as a result of the battle, fighter $i$ is eliminated from the tournament, and the rating of fighter $j$ is reduced by the rating of fighter $i$. That is, $a_j$ is decreased by $a_i$. Note that fighter $j$'s rating can become negative. The fighters indexes do not change.\n\nEralim wants to know what maximum rating the last remaining fighter can preserve if he chooses the battles optimally.",
    "tutorial": "It can be noted that the value of $a_{n-1}$ will always be negative in the final result. Therefore, we can subtract the sum $a_1 + a_2 + \\ldots + a_{n-2}$ from $a_{n-1}$, and then subtract $a_{n-1}$ from $a_n$. Thus, the final sum will be $a_1 + a_2 + \\ldots + a_{n-2} - a_{n-1} + a_n$. This value cannot be exceeded because $a_{n-1}$ will always be negative.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\ntypedef long long ll;\n \nconst int mod = 1e9 + 7;\n \nvoid solve(){\n    int n;\n    cin >> n;\n    ll ans = 0;\n    vector<int> a(n);\n    for(int i=0;i<n;i++){\n        cin >> a[i];\n        ans += a[i];\n    }\n    cout << ans - 2 * a[n - 2] << '\\n';\n}\n \nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2013",
    "index": "C",
    "title": "Password Cracking",
    "statement": "Dimash learned that Mansur wrote something very unpleasant about him to a friend, so he decided to find out his password at all costs and discover what exactly he wrote.\n\nBelieving in the strength of his password, Mansur stated that his password — is a binary string of length $n$. He is also ready to answer Dimash's questions of the following type:\n\nDimash says a binary string $t$, and Mansur replies whether it is true that $t$ is a substring of his password.\n\nHelp Dimash find out the password in no more than $2n$ operations; otherwise, Mansur will understand the trick and stop communicating with him.",
    "tutorial": "We will initially maintain an empty string $t$ such that $t$ appears as a substring in $s$. We will increase the string $t$ by one character until its length is less than $n$. We will perform $n$ iterations. In each iteration, we will check the strings $t + 0$ and $t + 1$. If one of them appears in $s$ as a substring, we will add the appropriate character to the end of $t$ and proceed to the next iteration. If neither of these two strings appears in $s$, it means that the string $t$ is a suffix of the string $s$. After this iteration, we will check the string $0 + t$. If it appears in $s$, we will add $0$ to $t$; otherwise, we will add $1$. Thus, in each iteration, we perform 2 queries, except for one iteration in which we perform 3 queries. However, after this iteration, we will make only 1 query, so the total number of queries will not exceed $2 \\cdot n$.",
    "code": "\n#include <iostream>\n#include <vector>\n#include <string>\n#include <array>\n \nusing namespace std;\n \nbool ask(string t) {\n    cout << \"? \" << t << endl;\n    int res;\n    cin >> res;\n    return res;\n}\n \nvoid result(string s) {\n    cout << \"! \" << s << endl;\n}\n \nvoid solve() {\n    int n;\n    cin >> n;\n    string cur;\n    while (cur.size() < n) {\n        if (ask(cur + \"0\")) {\n            cur += \"0\";\n        } else if (ask(cur + \"1\")) {\n            cur += \"1\";\n        } else {\n            break;\n        }\n    }\n    while ((int) cur.size() < n) {\n        if (ask(\"0\" + cur)) {\n            cur = \"0\" + cur;\n        } else{\n            cur = \"1\" + cur;\n        }\n    }\n    result(cur);\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "strings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2013",
    "index": "D",
    "title": "Minimize the Difference",
    "statement": "Zhan, tired after the contest, gave the only task that he did not solve during the contest to his friend, Sungat. However, he could not solve it either, so we ask you to try to solve this problem.\n\nYou are given an array $a_1, a_2, \\ldots, a_n$ of length $n$. We can perform any number (possibly, zero) of operations on the array.\n\nIn one operation, we choose a position $i$ ($1 \\leq i \\leq n - 1$) and perform the following action:\n\n- $a_i := a_i - 1$, and $a_{i+1} := a_{i+1} + 1$.\n\nFind the minimum possible value of $\\max(a_1, a_2, \\ldots, a_n) - \\min(a_1, a_2, \\ldots, a_n)$.",
    "tutorial": "First statement: if $a_i > a_{i+1}$, then it is always beneficial to perform an operation at position $i$. Therefore, the final array will be non-decreasing. Second statement: if the array is non-decreasing, then performing operations is not advantageous. We will maintain a stack that holds a sorted array. Each element in the stack will represent a pair $(x, cnt)$, where $x$ is the value and $cnt$ is the number of its occurrences. When adding $a_i$ to the stack, we will keep track of the sum of the removed elements $sum$ from the stack and their count $cnt$. Initially, $sum = a_i$ and $cnt = 1$. We will remove the last element from the stack while it is greater than $\\frac{sum}{cnt}$. After that, we recalculate $sum$ and $cnt$. Then we add the pairs $\\left( \\frac{sum}{cnt}, cnt - sum \\mod cnt \\right)$ and $\\left( \\frac{sum}{cnt} + 1, sum \\mod cnt \\right)$ to the stack. The time complexity of the algorithm is $O(n)$, since on each iteration, no more than 2 elements are added to the stack, and each element is removed at most once.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nll a[200200];\nint n;\n\nvoid solve(){\n    cin >> n;\n    for(int i=1;i<=n;i++){\n        cin >> a[i];\n    }\n    stack<pair<ll, int>> s;\n    for(int i=1;i<=n;i++){\n        ll sum = a[i], cnt = 1;\n        while(s.size() && s.top().first >= sum / cnt){\n            sum += s.top().first * s.top().second;\n            cnt += s.top().second;\n            s.pop();\n        }\n        s.push({sum / cnt, cnt - sum % cnt});\n        if(sum % cnt != 0){\n            s.push({sum / cnt + 1, sum % cnt});\n        }\n    }\n    ll mx = s.top().first;\n    while(s.size() > 1){\n        s.pop();\n    }\n    cout << mx - s.top().first << '\\n';\n}\n\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2013",
    "index": "E",
    "title": "Prefix GCD",
    "statement": "Since Mansur is tired of making legends, there will be no legends for this task.\n\nYou are given an array of positive integer numbers $a_1, a_2, \\ldots, a_n$. The elements of the array can be rearranged in any order. You need to find the smallest possible value of the expression $$\\gcd(a_1) + \\gcd(a_1, a_2) + \\ldots + \\gcd(a_1, a_2, \\ldots, a_n),$$ where $\\gcd(a_1, a_2, \\ldots, a_n)$ denotes the greatest common divisor (GCD) of $a_1, a_2, \\ldots, a_n$.",
    "tutorial": "Let $g$ be the greatest common divisor $gcd$ of the array $a$. We will divide each element $a_i$ by $g$, and at the end, simply multiply the result by $g$. Now, consider the following greedy algorithm. We will start with an initially empty array $b$ and add to the end of array $b$ the element that minimizes the GCD with the already existing array $b$. It can be observed that the $gcd$ will reach 1 in at most 10 iterations. After that, the remaining elements can be added in any order. Let $A$ be the minimum possible GCD for the current prefix of array $b$, and let $B$ be the optimal answer such that $A < B$. In this case, we can first place $A$, and then write the sequence $B$ in the same order. The answer will not worsen, since $A + \\text{gcd}(A, B) \\leq B$. Total time complexty: $O(n \\cdot 10)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint a[200200];\nint n;\n\nvoid solve(){\n    cin >> n;\n    int g = 0, cur = 0;\n    long long ans = 0;\n    for(int i=0;i<n;i++){\n        cin >> a[i];\n        g = __gcd(g, a[i]);\n    }\n    for(int i=0;i<n;i++){\n        a[i] /= g;\n    }\n    for(int t=0;t<n;t++){\n        int nc = 1e9;\n        for(int i=0;i<n;i++){\n            nc = min(nc, __gcd(cur, a[i]));\n        }\n        cur = nc;\n        ans += cur;\n        if(cur == 1) {\n            ans += n - t - 1;\n            break;\n        }\n    }\n    cout << ans * g << '\\n';\n}\n\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t = 1;\n     cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2013",
    "index": "F1",
    "title": "Game in Tree (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. In this version, $\\mathbf{u = v}$. You can make hacks only if both versions of the problem are solved.}\n\nAlice and Bob are playing a fun game on a tree. This game is played on a tree with $n$ vertices, numbered from $1$ to $n$. Recall that a tree with $n$ vertices is an undirected connected graph with $n - 1$ edges.\n\nAlice and Bob take turns, with Alice going first. Each player starts at some vertex.\n\nOn their turn, a player must move from the current vertex to a neighboring vertex that has not yet been visited by anyone. The first player who cannot make a move loses.\n\nYou are given two vertices $u$ and $v$. Represent the simple path from vertex $u$ to $v$ as an array $p_1, p_2, p_3, \\ldots, p_m$, where $p_1 = u$, $p_m = v$, and there is an edge between $p_i$ and $p_{i + 1}$ for all $i$ ($1 \\le i < m$).\n\nYou need to determine the winner of the game if Alice starts at vertex $1$ and Bob starts at vertex $p_j$ for each $j$ (where $1 \\le j \\le m$).",
    "tutorial": "First, let's understand how the game proceeds. Alice and Bob start moving toward each other along the path from vertex $1$ to vertex $u$. At some vertex, one of the players can turn into a subtree of a vertex that is not on the path $(1, u)$. After this, both players go to the furthest accessible vertex. Let the path from vertex $1$ to vertex $u$ be denoted as $(p_1, p_2, \\dots, p_m)$, where $p_1 = 1$ and $p_m = u$. Initially, Alice is at vertex $p_1$ and Bob is at vertex $p_m$. For each vertex on the path $(p_1, p_2, \\dots, p_m)$, we define two values: $a_i$ - the number of vertices that Alice will visit if she descends into the subtree of vertex $p_i$ that does not lie on the path $(1, u)$; $a_i$ - the number of vertices that Alice will visit if she descends into the subtree of vertex $p_i$ that does not lie on the path $(1, u)$; $b_i$ - the number of vertices that Bob will visit if he descends into the subtree of vertex $p_i$ that also does not lie on this path. $b_i$ - the number of vertices that Bob will visit if he descends into the subtree of vertex $p_i$ that also does not lie on this path. Let the distance to the furthest vertex in the subtree of vertex $p_i$ be denoted as $d_{p_i}$. Then: $a_i = d_{p_i} + i$ - the number of vertices Alice can visit if she descends into the subtree at vertex $p_i$. $a_i = d_{p_i} + i$ - the number of vertices Alice can visit if she descends into the subtree at vertex $p_i$. $b_i = d_{p_i} + m - i + 1$ - the number of vertices Bob can visit if he descends into the subtree at vertex $p_i$. $b_i = d_{p_i} + m - i + 1$ - the number of vertices Bob can visit if he descends into the subtree at vertex $p_i$. Now, consider what happens if Alice is at vertex $p_i$ and Bob is at vertex $p_j$. If Alice decides to descend into the subtree of vertex $p_i$, she will visit $a_i$ vertices. Meanwhile, Bob can reach any vertex on the segment $(p_i, p_{i+1}, \\dots, p_j)$. It is advantageous for Bob to descend into the subtree of the vertex with the maximum value of $b_k$, where $k \\in [i+1, j]$. Therefore, it is beneficial for Alice to descend into the subtree of vertex $p_i$ if the following condition holds: $a_i > \\max(b_{i+1}, b_{i+2}, \\dots, b_j)$ Otherwise, she should move to vertex $p_{i+1}$. The situation for Bob is similar: he will descend into the subtree of vertex $p_j$ if the condition analogous to Alice's condition holds for him. To efficiently find the maximum on the segment $(p_{i+1}, \\dots, p_j)$, one can use a segment tree or a sparse table. This allows finding the maximum in $O(\\log n)$ for each query, resulting in an overall time complexity of $O(n \\log n)$. However, it can be proven that instead of using a segment tree or sparse table, one can simply iterate through all vertices on the segment and terminate the loop upon finding a greater vertex. This approach will yield a solution with a time complexity of $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint dfs(int v, int p, int to, const vector<vector<int>> &g, vector<int> &max_depth) {\n    int ans = 0;\n    bool has_to = false;\n    for (int i : g[v]) {\n        if (i == p) {\n            continue;\n        }\n        int tmp = dfs(i, v, to, g, max_depth);\n        if (tmp == -1) {\n            has_to = true;\n        } else {\n            ans = max(ans, tmp + 1);\n        }\n    }\n    if (has_to || v == to) {\n        max_depth.emplace_back(ans);\n        return -1;\n    } else {\n        return ans;\n    }\n}\n\nint solve(const vector<vector<int>> &g, int to) {\n    vector<int> max_depth;\n    dfs(0, -1, to, g, max_depth);\n    int n = max_depth.size();\n    reverse(max_depth.begin(), max_depth.end());\n    int first = 0, second = n - 1;\n    while (true) {\n        {\n            int value1 = max_depth[first] + first;\n            bool valid = true;\n            for (int j = second; j > first; --j) {\n                if (value1 <= max_depth[j] + (n - j - 1)) {\n                    valid = false;\n                    break;\n                }\n            }\n            if (valid) {\n                return 0;\n            }\n            ++first;\n            if (first == second) {\n                return 1;\n            }\n        }\n        {\n            int value2 = max_depth[second] + (n - second - 1);\n            bool valid = true;\n            for (int j = first; j < second; ++j) {\n                if (value2 < max_depth[j] + j) {\n                    valid = false;\n                    break;\n                }\n            }\n            if (valid) {\n                return 1;\n            }\n            --second;\n            if (first == second) {\n                return 0;\n            }\n        }\n    }\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<vector<int>> g(n);\n    for (int i = 0; i < n - 1; ++i) {\n        int a, b;\n        cin >> a >> b;\n        g[a - 1].push_back(b - 1);\n        g[b - 1].push_back(a - 1);\n    }\n    int s, f;\n    cin >> s >> f;\n    --s, --f;\n    int ans = solve(g, s);\n    if (ans == 0) {\n        cout << \"Alice\\n\";\n    } else {\n        cout << \"Bob\\n\";\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "games",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2013",
    "index": "F2",
    "title": "Game in Tree (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, it is not guaranteed that $u = v$. You can make hacks only if both versions of the problem are solved.}\n\nAlice and Bob are playing a fun game on a tree. This game is played on a tree with $n$ vertices, numbered from $1$ to $n$. Recall that a tree with $n$ vertices is an undirected connected graph with $n - 1$ edges.\n\nAlice and Bob take turns, with Alice going first. Each player starts at some vertex.\n\nOn their turn, a player must move from the current vertex to a neighboring vertex that has not yet been visited by anyone. The first player who cannot make a move loses.\n\nYou are given two vertices $u$ and $v$. Represent the simple path from vertex $u$ to $v$ as an array $p_1, p_2, p_3, \\ldots, p_m$, where $p_1 = u$, $p_m = v$, and there is an edge between $p_i$ and $p_{i + 1}$ for all $i$ ($1 \\le i < m$).\n\nYou need to determine the winner of the game if Alice starts at vertex $1$ and Bob starts at vertex $p_j$ for each $j$ (where $1 \\le j \\le m$).",
    "tutorial": "Read the Solution of the easy version of the problem. The path $(u, v)$ can be divided into two vertical paths $(1, u)$ and $(1, v)$. We will solve for the vertices on the path $(1, u)$, while the path $(1, v)$ is solved similarly. For each vertex on the path $(1, u)$, we define two values: $fa_i$ - the first vertex at which Alice will win if she descends into the subtree when Bob starts at vertex $p_i$. $fb_i$ - the first vertex at which Bob will win if he descends into the subtree when he starts at vertex $p_i$. The claim is that it is beneficial for Alice to descend into the subtree at vertex $v$ only over a certain segment of vertices from which Bob starts. A similar claim holds for Bob. Now, for each of Alice's vertices, we need to determine the segment where it is beneficial to descend. The left boundary of the segment for vertex $p_i$ will be $2 \\cdot i$, since Alice will always be on the left half of the path. It is easy to notice that the right boundary of the segment can be found using binary search. We redefine the value $b_i$ to be $d_{p_i} - i$. To check whether it is beneficial for us to descend into the subtree for a fixed midpoint $mid$, we need to satisfy the following condition: $a_i > \\max(b_{i+1}, b_{i+2}, \\ldots, b_{mid - i}) + mid.$ Let $(l_j, r_j)$ denote the segment where it is beneficial for Alice to descend if Bob starts at vertex $p_j$. Then the value $fa_i$ will be the minimum position $j$ such that $l_j \\leq i \\leq r_j$; this can be found using a set. The value $fb_i$ is calculated similarly. Alice wins at vertex $p_i$ if $fa_i \\leq i - fb_i$; otherwise, Bob wins. To efficiently find the maximum on the segment, a sparse table can be used. Additionally, using sets and binary searches gives us a time complexity of $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nconst int maxn = 2e5 + 12;\n\nvector<int> g[maxn], del[maxn], add[maxn];\nvector<int> ord;\nint ans[maxn];\nint dp[maxn];\nint n, m, k;\n\nbool calc(int v, int p, int f){\n    bool is = 0;\n    if(v == f) is = 1;\n    dp[v] = 1;\n    for(int to:g[v]){\n        if(to == p){\n            continue;\n        }\n        bool fg = calc(to, v, f);\n        is |= fg;\n        if(fg == 0){\n            dp[v] = max(dp[v], dp[to] + 1);\n        }\n    }\n    if(is){\n        ord.push_back(v);\n    }\n    return is;\n}\n\nstruct sparse {\n    int mx[20][200200], lg[200200];\n    int n;\n    void build(vector<int> &a){\n        n = a.size();\n        for(int i=0;i<n;i++){\n            mx[0][i] = a[i];\n        }\n        lg[0] = lg[1] = 0;\n        for(int i=2;i<=n;i++){\n            lg[i] = lg[i/2] + 1;\n        }\n        for(int k=1;k<20;k++){\n            for(int i=0;i + (1 << k) - 1 < n;i++){\n                mx[k][i] = max(mx[k-1][i], mx[k-1][i + (1 << (k - 1))]);\n            }\n        }\n    }\n    int get (int l, int r) {\n        if(l > r) return -1e9;\n        int k = lg[r-l+1];\n        return max(mx[k][l], mx[k][r - (1 << k) + 1]);\n    }\n} st_a, st_b;\n\nvoid solve(int v){\n    ord.clear();\n    calc(1, 0, v);\n    reverse(ord.begin(), ord.end());\n    m = ord.size();\n    vector<int> a(m+1), b(m+1);\n    vector<int> fa(m+1, 1e9), fb(m+1, -1e9);\n    for(int i=0;i<m;i++){\n        a[i] = dp[ord[i]] + i;\n        b[i] = dp[ord[i]] - i;\n        del[i].clear();\n        add[i].clear();\n    }\n    st_a.build(a);\n    st_b.build(b);\n    multiset<int> s;\n    for(int i=1;i<m;i++){\n        int pos = i;\n        for(int l=i+1, r=m-1;l<=r;){\n            int mid = l + r >> 1;\n            if(st_b.get(i+1 , mid) + mid < a[i] - i){\n                pos = mid;\n                l = mid + 1;\n            }\n            else r = mid - 1;\n        }\n        if(i < pos){\n            add[min(m, 2 * i)].push_back(i);\n            del[min(m, pos + i)].push_back(i);\n        }\n        for(int x:add[i]){\n            s.insert(x);\n        }\n        if(s.size()) fa[i] = *s.begin();\n        for(int x:del[i]){\n            s.erase(s.find(x));\n        }\n    }\n    s.clear();\n    for(int i=0;i<=m;i++){\n        add[i].clear();\n        del[i].clear();\n    }\n    for(int i=1;i<m;i++){\n        int pos = i;\n        for(int l=1, r = i-1;l<=r;){\n            int mid = l + r >> 1;\n            if(st_a.get(mid, i-1) - mid + 1 <= b[i] + i){\n                pos = mid;\n                r = mid - 1;\n            }\n            else l = mid + 1;\n        }\n        pos--;\n        if(pos >= 0){\n            add[min(m, pos + i)].push_back(i);\n            del[min(m, 2 * i - 1)].push_back(i);\n        }\n        for(int x:add[i]){\n            s.insert(x);\n        }\n        if(s.size()) fb[i] = *s.rbegin();\n        for(int x:del[i]){\n            s.erase(s.find(x));\n        }\n    }\n    for(int i=m-1;i>0;i--){\n        b[i] = max(b[i+1] + 1, dp[ord[i]]);\n        if(b[i] >= st_a.get(1, i-1)){\n            fb[i] = i;\n        }\n        if(a[0] > max(st_b.get(1, i-1) + i, b[i])){\n            fa[i] = 0;\n        }\n        ans[ord[i]] = 0;\n        if(fa[i] <= i - fb[i]){\n            ans[ord[i]] = 1;\n        }\n    }\n}\n\nvoid solve(){\n    cin >> n;\n    for(int i=1;i<=n;i++){\n        g[i].clear();\n    }\n    for(int i=1;i<n;i++){\n        int a, b;\n        cin >> a >> b;\n        g[a].push_back(b);\n        g[b].push_back(a);\n    }\n    int u, v;\n    cin >> u >> v;\n    solve(u), solve(v);\n    ord.clear();\n    calc(v, 0, u);\n    auto p = ord;\n    for(int x:p){\n        if(ans[x] == 1){\n            cout << \"Alice\\n\";\n        }\n        else{\n            cout << \"Bob\\n\";\n        }\n    }\n}\n\nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t = 1;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "trees"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2014",
    "index": "A",
    "title": "Robin Helps",
    "statement": "\\begin{quote}\nThere is a little bit of the outlaw in everyone, and a little bit of the hero too.\n\\end{quote}\n\nThe heroic outlaw Robin Hood is famous for taking from the rich and giving to the poor.\n\nRobin encounters $n$ people starting from the $1$-st and ending with the $n$-th. The $i$-th person has $a_i$ gold. If $a_i \\ge k$, Robin will take all $a_i$ gold, and if $a_i=0$, Robin will give $1$ gold if he has any. Robin starts with $0$ gold.\n\nFind out how many people Robin gives gold to.",
    "tutorial": "This problem requires a simple implementation. Set a variable (initially $0$) to represent the gold Robin has, and update it according to the rules as he scans through $a_i$, adding $1$ to answer whenever Robin gives away a gold.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nvoid work(){\n    int n,k;\n    cin >> n >> k;\n \n    int res = 0, gold = 0;\n    for (int i=0;i<n;i++){\n        int cur;\n        cin >> cur;\n        if (!cur && gold) gold--, res++;\n        else if (cur >= k) gold += cur; \n    }\n \n    cout << res << '\\n';\n}\n \nint main(){\n \n    int t;\n    cin >> t;\n    while (t--) work();\n \n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2014",
    "index": "B",
    "title": "Robin Hood and the Major Oak",
    "statement": "\\begin{quote}\nIn Sherwood, the trees are our shelter, and we are all children of the forest.\n\\end{quote}\n\nThe Major Oak in Sherwood is known for its majestic foliage, which provided shelter to Robin Hood and his band of merry men and women.\n\nThe Major Oak grows $i^i$ new leaves in the $i$-th year. It starts with $1$ leaf in year $1$.\n\nLeaves last for $k$ years on the tree. In other words, leaves grown in year $i$ last between years $i$ and $i+k-1$ inclusive.\n\nRobin considers even numbers lucky. Help Robin determine whether the Major Oak will have an even number of leaves in year $n$.",
    "tutorial": "The key observation is that $i^i$ has the same even/odd parity as $i$. Therefore, the problem reduces to finding whether the sum of $k$ consecutive integers ending in $n$ is even. This can be done by finding the sum of $n-k+1, n-k+2, ..., n-1, n$ which is $k*(2n-k+1)/2$, and checking its parity. Alternatively, one can count the number of odd numbers in those $k$ consecutive integers. Note: Originally, the number of leaves grown was to be $i^m$ according to the fractal nature of life where $m$ is set to some integer. Developers decided to replace $m$ with $i$ for simplicity, following Filikec's suggestion.",
    "code": "#include <iostream>\n \nusing namespace std;\n \n \nvoid work(){\n    int n,k;\n    cin >> n >> k;\n \n    cout << (((n+1)*n/2 - (n-k)*(n-k+1)/2)%2?\"NO\":\"YES\") << '\\n';\n}\n \nint main(){\n \n    int t;\n    cin >> t;\n    while (t--) work();\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2014",
    "index": "C",
    "title": "Robin Hood in Town",
    "statement": "\\begin{quote}\nIn Sherwood, we judge a man not by his wealth, but by his merit.\n\\end{quote}\n\nLook around, the rich are getting richer, and the poor are getting poorer. We need to take from the rich and give to the poor. We need Robin Hood!\n\nThere are $n$ people living in the town. Just now, the wealth of the $i$-th person was $a_i$ gold. But guess what? The richest person has found an extra pot of gold!\n\nMore formally, find an $a_j=max(a_1, a_2, \\dots, a_n)$, change $a_j$ to $a_j+x$, where $x$ is a non-negative integer number of gold found in the pot. If there are multiple maxima, it can be any one of them.\n\nA person is unhappy if their wealth is \\textbf{strictly less than half} of the average wealth$^{\\text{∗}}$.\n\nIf \\textbf{strictly more than half} of the total population $n$ are unhappy, Robin Hood will appear by popular demand.\n\nDetermine the minimum value of $x$ for Robin Hood to appear, or output $-1$ if it is impossible.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The average wealth is defined as the total wealth divided by the total population $n$, that is, $\\frac{\\sum a_i}{n}$, the result is a real number.\n\\end{footnotesize}",
    "tutorial": "If we sort the wealth in increasing order, then the $j$-th person must be unhappy for Robin to appear, where $j=\\lfloor n/2 \\rfloor +1$ if $1$-indexing or $j=\\lfloor n/2 \\rfloor$ if $0$-indexing. We need $a_j < \\frac{s+x}{2*n}$, where $s$ is the original total wealth before $x$ gold from the pot was added. Rearranging the equation gives $x>2*n*a_j-s$. Because $x$ is a non-negative integer, we arrive at the answer $max(0,2*n*a_j-s+1)$. Of course, this problem can also be solved by binary search, with two caveats. First, one needs to be careful to avoid comparison between integer and float types, as rounding errors could create issues. You can always avoid division by $2n$ by multiplying it out. Second, one needs to pick the upper limit carefully to ensure it is large enough. Note that $2*n*max(a)$ can serve as the upper limit for the binary search for $x$, because that would push the average to be strictly above $2*max(a)$ and everyone except the one with the pot of gold would be unhappy. There are $2$ edge cases, $n=1, 2$, where the condition for Robin can never be reached, because the richest person will always be happy (at least in this problem, though perhaps not IRL). ChatGPT struggled to identify these edge cases, so it was tempting to leave at least one hidden. Following testing, we decided to give both in samples to reduce frustration. Note: Wealth inequality is better measured by the Gini coefficient which is too involved for this problem. Our criterion is a crude approximation for the Gini coefficient, and is equivalent to setting the mean to median ratio (a well known indicator for inequality) to $2$. For a random distribution, this ratio is close to $1$. Interestingly, this ratio for UK salary distribution is around $1.2$, so no Robin yet.",
    "code": "#include <iostream>\n#include <vector>\n#include <algorithm>\n \nusing namespace std;\n \nvoid work(){\n    int n;\n    cin >> n;\n    \n    long long sum = 0;\n    vector<long long> v(n);\n    for (auto &c : v) cin >> c, sum += c;\n \n    sort(v.begin(),v.end());\n \n    if (n < 3){\n        cout << \"-1\\n\";\n        return;\n    }\n    cout << max(0LL,v[n/2]*2*n-sum+1) << '\\n';\n}\n \n \nint main(){\n    \n    int t;\n    cin >> t;\n    while (t--) work();\n \n \n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2014",
    "index": "D",
    "title": "Robert Hood and Mrs Hood",
    "statement": "\\begin{quote}\nImpress thy brother, yet fret not thy mother.\n\\end{quote}\n\nRobin's brother and mother are visiting, and Robin gets to choose the start day for each visitor.\n\nAll days are numbered from $1$ to $n$. Visitors stay for $d$ continuous days, all of those $d$ days must be between day $1$ and $n$ inclusive.\n\nRobin has a total of $k$ risky 'jobs' planned. The $i$-th job takes place between days $l_i$ and $r_i$ inclusive, for $1 \\le i \\le k$. If a job takes place on any of the $d$ days, the visit overlaps with this job (the length of overlap is unimportant).\n\nRobin wants his brother's visit to overlap with the maximum number of \\textbf{distinct jobs}, and his mother's the minimum.\n\nFind suitable start days for the visits of Robin's brother and mother. If there are multiple suitable days, choose the earliest one.",
    "tutorial": "Since the number of days $n$ is capped, we can check all possible start day $x$ in range $[1,n-d+1]$ (so that the duration of $d$ days would fit). We would like to find the number of overlapped jobs for each value of $x$. A job between days $l_i$ and $r_i$ would overlap with the visit if the start day $x$ satisfies $l_i-d+1 \\le x \\le r_i$. Naively, this range update could be potentially $O(n)$, which is too slow. However, noting the start and end, each job update could be done in $2$ operations. We add $+1$ at $l_i-d+1$ and $-1$ at $r_i+1$, and after all jobs are recorded, we will take a prefix sum to work out the number of overlapped jobs for each $x$. When $l_i-d+1$ drops below $1$, we simply use $1$ to avoid lower values which are not being considered for $x$. The time complexity is $O(n)$. Note: Robin's risky jobs are generally deemed illegal by the Sheriff of Nottingham. Robert is practical and helpful. Like all good parents, Mrs Hood is a worrier.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n\nvoid work(){\n    int n,k,d;\n    cin >> n >> d >> k;\n \n    vector<int> ss(n+1),es(n+1);\n \n    for (int i=0;i<k;i++){\n        int a,b;\n        cin >> a >> b;\n        ss[a]++;\n        es[b]++;\n    }\n \n    for (int i=0;i<n;i++) ss[i+1] += ss[i];\n    for (int i=0;i<n;i++) es[i+1] += es[i];\n \n    int most = 0;\n    int robert = 0;\n    int mrs = 0;\n    int least = 1e9;\n    for (int i=d;i<=n;i++){\n        int cur = ss[i] - es[i-d];\n        if (cur > most) most = cur, robert = i-d+1;\n        if (cur < least) least = cur, mrs = i-d+1;\n    }\n \n    cout << robert << ' ' << mrs << \"\\n\";\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while (t--) work();\n \n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2014",
    "index": "E",
    "title": "Rendez-vous de Marian et Robin",
    "statement": "\\begin{quote}\nIn the humble act of meeting, joy doth unfold like a flower in bloom.\n\\end{quote}\n\nAbsence makes the heart grow fonder. Marian sold her last ware at the Market at the same time Robin finished training at the Major Oak. They couldn't wait to meet, so they both start without delay.\n\nThe travel network is represented as $n$ vertices numbered from $1$ to $n$ and $m$ edges. The $i$-th edge connects vertices $u_i$ and $v_i$, and takes $w_i$ seconds to travel (all $w_i$ are even). Marian starts at vertex $1$ (Market) and Robin starts at vertex $n$ (Major Oak).\n\nIn addition, $h$ of the $n$ vertices each has a single horse available. Both Marian and Robin are capable riders, and could mount horses in no time (i.e. in $0$ seconds). Travel times are halved when riding. Once mounted, a horse lasts the remainder of the travel. Meeting must take place on a vertex (i.e. not on an edge). Either could choose to wait on any vertex.\n\nOutput the earliest time Robin and Marian can meet. If vertices $1$ and $n$ are disconnected, output $-1$ as the meeting is cancelled.",
    "tutorial": "This problem builds on the standard Dijkstra algorithm. So please familiarise yourself with the algorithm if not already. In Dijkstra algorithm, a distance vector/list is used to store travel times to all vertices, here we need to double the vector/list to store travel times to vertices arriving with and without a horse. If a vertex has a horse, then it's possible to transition from without horse to with horse there. The Dijkstra algorithm is then run as standard. What if a horse has already been taken by Marian when Robin arrives, and vice versa? Well, the optimal solution would not require the second person to arrive to use the horse, because the first to arrive could simply wait for the second to arrive, giving an earlier meeting than whatever is possible if the second to arrive had to use the horse and go elsewhere. Therefore, for any vertex, $1$ horse is sufficient. We run Dijkstra algorithm twice to find the fastest time Robin and Marian could reach any vertex $i$ as $tR(i)$ and $tM(i)$. The earliest meeting time at a given vertex $i$ is $max(tR(i),tM(i))$, and we need to check all vertices. The time complexity is that of Dijkstra algorithm which, in this problem, is $O(n \\log n)$.",
    "code": "\n\n#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\n\nvoid dijkstra(int s, vector<vector<long long>> &d, vector<vector<pair<int,long long>>> &graph, vector<bool> &hs){\n    auto cmp = [&](auto &a, auto &b){return make_pair(d[a.first][a.second],a) < make_pair(d[b.first][b.second],b);};\n    set<pair<int,int>,decltype(cmp)> q(cmp);\n    \n    d[s][0] = 0;\n    q.insert({s,0});\n\n    while (q.size()){\n        auto [curv,curh] = *q.begin();\n        q.erase(q.begin());\n\n        bool horse = (curh || hs[curv]);\n        for (auto &[neighv, neighd] : graph[curv]){\n            long long dist = horse?neighd/2:neighd;\n            if (d[neighv][horse] > d[curv][curh] + dist){\n                q.erase({neighv,horse});\n                d[neighv][horse] = d[curv][curh] + dist;\n                q.insert({neighv,horse});\n            }\n        }\n    }\n}\n\nvoid work(){\n    int n,m,h;\n    cin >> n >> m >> h;\n\n    vector<bool> hs(n);\n    vector<vector<pair<int,long long>>> graph(n);\n    \n    for (int i=0;i<h;i++){\n        int c;\n        cin >> c;\n        hs[--c]=1;\n    }\n\n    for (int i=0;i<m;i++){\n        int a,b,c;\n        cin >> a >> b >> c;\n\n        a--,b--;\n        graph[a].push_back({b,c});\n        graph[b].push_back({a,c});\n    }\n\n    vector<vector<long long>> d1(n,vector<long long>(2,1e18));\n    vector<vector<long long>> d2(n,vector<long long>(2,1e18));\n\n    dijkstra(0,d1,graph,hs);\n    dijkstra(n-1,d2,graph,hs);\n\n\n    long long best = 1e18;\n    auto get = [&](int a){return max(min(d1[a][0],d1[a][1]),min(d2[a][0],d2[a][1]));};\n\n    for (int i=0;i<n;i++) best = min(best,get(i));\n    \n    cout << (best==1e18?-1:best) << '\\n';\n}\n\n\nint main(){\n    int t;\n    cin >> t;\n    while (t--) work();\n\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "shortest paths"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2014",
    "index": "F",
    "title": "Sheriff's Defense",
    "statement": "\\begin{quote}\n\"Why, master,\" quoth Little John, taking the bags and weighing them in his hand, \"here is the chink of gold.\"\n\\end{quote}\n\nThe folk hero Robin Hood has been troubling Sheriff of Nottingham greatly. Sheriff knows that Robin Hood is about to attack his camps and he wants to be prepared.\n\nSheriff of Nottingham built the camps with strategy in mind and thus there are exactly $n$ camps numbered from $1$ to $n$ and $n-1$ trails, each connecting two camps. Any camp can be reached from any other camp. Each camp $i$ has initially $a_i$ gold.\n\nAs it is now, all camps would be destroyed by Robin. Sheriff can strengthen a camp by subtracting exactly $c$ gold from \\textbf{each of its neighboring camps} and use it to build better defenses for that camp. Strengthening a camp \\textbf{doesn't change} its gold, only its neighbors' gold. A camp can have negative gold.\n\nAfter Robin Hood's attack, all camps that have been strengthened survive the attack, all others are destroyed.\n\nWhat's the maximum gold Sheriff can keep in his surviving camps after Robin Hood's attack if he strengthens his camps optimally?\n\nCamp $a$ is neighboring camp $b$ if and only if there exists a trail connecting $a$ and $b$. Only strengthened camps count towards the answer, as others are destroyed.",
    "tutorial": "An important observation is that strengthening a base only influences its neighbors, so we can just keep consider adjacent nodes as later ones are not affected. Let's consider induction to solve this problem. Let $d[i][0]$ denote the most gold from node $i$ and all its children if we don't strengthen node $i$ and $d[i][1]$ if we do strengthen the node $i$. Base case: If the current node $i$ is a leaf, $d[i][0] = 0$, $d[i][1] = a_i$. Base case: If the current node $i$ is a leaf, $d[i][0] = 0$, $d[i][1] = a_i$. Induction step: Consider the node $i$ with children $1 \\dots m$. Assume that all nodes $1 \\dots m$ are already calculated. If we don't strengthen the node $i$, $d[i][0] = {\\sum_{j = 1}^m max(d[j][0],d[j][1])}$. If the node $i$ is strengthened, $d[i][1] = a_i + {\\sum_{j = 1}^m max(d[j][0],d[j][1]-2\\cdot c)}$. Induction step: Consider the node $i$ with children $1 \\dots m$. Assume that all nodes $1 \\dots m$ are already calculated. If we don't strengthen the node $i$, $d[i][0] = {\\sum_{j = 1}^m max(d[j][0],d[j][1])}$. If the node $i$ is strengthened, $d[i][1] = a_i + {\\sum_{j = 1}^m max(d[j][0],d[j][1]-2\\cdot c)}$. Time complexity - $O(n)$.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nvoid work(){\n    int n,k;\n    cin >> n >> k;\n \n    vector<long long> v(n);\n    vector<vector<int>> g(n);\n    \n    for (auto &c : v) cin >> c;\n \n    for (int i=0;i<n-1;i++){\n        int a,b;\n        cin >> a >> b;\n        a--,b--;\n        g[a].push_back(b);\n        g[b].push_back(a);\n    }\n \n    vector<bool> vis(n);\n    vector<vector<long long>> d(n,vector<long long>(2));\n \n    auto dfs = [&](auto &&dfs, int cur, int p) -> void {\n        \n        for (auto &neigh : g[cur]){\n            if (neigh == p) continue;\n            dfs(dfs,neigh,cur);\n            d[cur][1] += max(d[neigh][0],d[neigh][1] - 2*k);\n            d[cur][0] += max(d[neigh][0],d[neigh][1]);\n        }\n \n        d[cur][1] += v[cur];\n    };\n \n    dfs(dfs,0,-1);\n \n    cout << max(0LL,max(d[0][0],d[0][1])) << '\\n';\n}\n \nint main(){\n \n    int t;\n    cin >> t;\n    while (t--) work();\n \n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2014",
    "index": "G",
    "title": "Milky Days",
    "statement": "\\begin{quote}\nWhat is done is done, and the spoilt milk cannot be helped.\n\\end{quote}\n\nLittle John is as little as night is day — he was known to be a giant, at possibly $2.1$ metres tall. It has everything to do with his love for milk.\n\nHis dairy diary has $n$ entries, showing that he acquired $a_i$ pints of fresh milk on day $d_i$. Milk declines in freshness with time and stays drinkable for a maximum of $k$ days. In other words, fresh milk acquired on day $d_i$ will be drinkable between days $d_i$ and $d_i+k-1$ inclusive.\n\nEvery day, Little John drinks drinkable milk, up to a maximum of $m$ pints. In other words, if there are less than $m$ pints of milk, he will drink them all and not be satisfied; if there are at least $m$ pints of milk, he will drink exactly $m$ pints and be satisfied, and it's a milk satisfaction day.\n\nLittle John always drinks \\textbf{the freshest} drinkable milk first.\n\nDetermine the number of milk satisfaction days for Little John.",
    "tutorial": "The key for this problem is the use of a stack, where last item in is the first item out. As we scan through the diary entries, we will only drink till the day of the next entry. If there is left over milk, we will push them into the stack with number of pints and the day they were acquired. If there isn't enough milk to reach the next entry, we will check the stack for left overs. Careful implementation is required to check for expiry day. It might help to append a fictitious entry with large day number and $0$ pints. Since every pop from the stack accompanies either the processing of a diary entry or permanently removing a stack item, the number of stack operation is $O(n)$. Since diary entries are presented in sorted order, the time complexity is $O(n)$. Note: Originally, this problem has an easy version, where Little John drinks the oldest drinkable milk first. However testers and the team were uncertain about the difficulties of the two problems, and there was concern that they are too 'implementation heavy'. For the sake of balance, only the hard version is presented here as G. However, you may wish to try the easy version yourself. I recall my parents telling me to use the oldest milk first, and now I say the same to my children. Has it all been worthwhile?",
    "code": "#include <iostream>\n#include <map>\n#include <list>\n#include <vector>\n\nusing namespace std;\n\ntypedef long long ll;\ntypedef pair<ll,ll> pll;\ntypedef vector<pll> vpll;\n\n\nvoid work(){\n    int n,m,k;\n    cin >> m >> n >> k;\n\n    map<ll,ll> days;\n    for (int i=0;i<m;i++){\n        int a,b;\n        cin >> a >> b;\n        days[a] += b;\n    }\n\n    days[1e18] = 0;\n\n    ll curd = 1;\n    ll got = 0;  \n    ll res = 0;\n\n    list<pll> pq;\n    \n    for (auto &cur : days){\n       while (pq.size() && curd < cur.first){\n            auto [d,x] = pq.front();\n            pq.pop_front();\n\n            if (d+k-1 < curd) continue;\n            else if (d > curd) curd = d, got = 0;\n\n            if (n-got > x) got += x;\n            else{\n                ll sat = min(curd + (x-n+got)/n + 1,min(d + k, cur.first));\n                ll newx = x-(sat-curd)*n+got;\n                if (newx) pq.push_front({d,newx});\n                res += sat-curd;\n                got = 0;\n                curd = sat;\n            } \n        }\n        pq.push_front(cur);\n    }\n    \n    cout << res << '\\n';\n}\n\nint main(){\n    cin.tie(NULL);\n    ios_base::sync_with_stdio(false);\n\n    int t;\n    cin >> t;\n    while (t--) work();\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2014",
    "index": "H",
    "title": "Robin Hood Archery",
    "statement": "\\begin{quote}\nAt such times archery was always the main sport of the day, for the Nottinghamshire yeomen were the best hand at the longbow in all merry England, but this year the Sheriff hesitated...\n\\end{quote}\n\nSheriff of Nottingham has organized a tournament in archery. It's the final round and Robin Hood is playing against Sheriff!\n\nThere are $n$ targets in a row numbered from $1$ to $n$. When a player shoots target $i$, their score increases by $a_i$ and the target $i$ is destroyed. The game consists of turns and players alternate between whose turn it is. Robin Hood always starts the game, then Sheriff and so on. The game continues until all targets are destroyed. Both players start with score $0$.\n\nAt the end of the game, the player with most score wins and the other player loses. If both players have the same score, it's a tie and no one wins or loses. In each turn, the player can shoot any target that wasn't shot before. Both play optimally to get the most score possible.\n\nSheriff of Nottingham has a suspicion that he might lose the game! This cannot happen, you must help Sheriff. Sheriff will pose $q$ queries, each specifying $l$ and $r$. This means that the game would be played only with targets $l, l+1, \\dots, r$, as others would be removed by Sheriff before the game starts.\n\nFor each query $l$, $r$, determine whether the Sheriff can \\textbf{not lose} the game when only considering the targets $l, l+1, \\dots, r$.",
    "tutorial": "Sheriff can never win. This is quite obvious as Robin is the first to pick and both just keep picking the current biggest number. This means that Sheriff can at best get a tie - this happens if and only if all elements have even appearance. The segment $a_l \\dots a_r$ is a tie if and only if there's no element that appears an odd number of times. There are multiple ways to solve this problem. Two are outlined. We can keep the count of appearances of each element using an array in $O(1)$ time. Sort the queries into blocks of size ${\\sqrt n}$. Keep updating the boundaries of the current segment and the total count of elements that appear an odd number of times. Sheriff can tie iff there is no odd appearance. Time complexity - $O((n+q){\\sqrt n})$. Consider the prefixes of all targets. If the current segment is $a_l \\dots a_r$, there's no element with odd appearance if and only if the set of numbers with odd appearance in $a_1 \\dots a_{l-1}$ is the same as $a_1 \\dots a_r$. We can check if two prefixes have the same set of elements with odd appearance with xor hashing. Time complexity - $O(n+q)$.",
    "code": "#Mo's algorithm\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <array>\n \nusing namespace std;\n \nint K = 500;\nint Cnt[1000001];\n \nvoid work(){\n    int n,q;\n    cin >> n >> q;\n \n    vector<int> v(n);\n    for (auto &c : v) cin >> c, Cnt[c] = 0;\n \n    vector<array<int,3>> qs(q);\n    for (int i=0;i<q;i++) cin >> qs[i][0] >> qs[i][1], qs[i][2] = i;\n \n    auto cmp = [&](array<int,3> &a, array<int,3> &b){return make_pair(make_pair(a[0]/K,a[1]/K),a) < make_pair(make_pair(b[0]/K,b[1]/K),b);};\n    sort(qs.begin(),qs.end(),cmp);\n \n    int l, r;\n    l = r = 0;\n    int odd = 1;\n    Cnt[v.front()]++;\n \n    vector<bool> res(q);\n \n    for (auto &c : qs){\n        c[0]--,c[1]--;\n \n        while (r < c[1]){\n            Cnt[v[++r]]++;\n            if (Cnt[v[r]]%2) odd++;\n            else odd--;\n        }\n \n        while (l > c[0]){\n            Cnt[v[--l]]++;\n            if (Cnt[v[l]]%2) odd++;\n            else odd--;\n        }\n \n        while (l < c[0]){\n            Cnt[v[l]]--;\n            if (Cnt[v[l++]]%2) odd++;\n            else odd--;\n        }\n \n        while (r > c[1]){\n            Cnt[v[r]]--;\n            if (Cnt[v[r--]]%2) odd++;\n            else odd--;\n        }\n \n        res[c[2]] = odd;\n    }\n \n    for (bool c : res) cout << (c?\"NO\\n\":\"YES\\n\");\n}\n \nint main(){\n    int t;\n    cin >> t;\n    while (t--) work();\n    return 0;\n}\n\n#xor hashing\n#include <iostream>\n#include <vector>\n#include <map>\n#include <random>\n#include <set>\n \nusing namespace std;\n \n \nvoid work(){\n    int n,q;\n    cin >> n >> q;\n    vector<unsigned long long> v(n);\n    for (auto &c : v) cin >> c;\n \n    random_device rd; \n    mt19937_64 gen(rd());\n    map<unsigned long long, unsigned long long> mapping;\n    set<unsigned long long> used = {0};\n \n    for (auto &c : v){\n        unsigned long long random;\n        if (!mapping.contains(c)){\n            do{\n                random = gen();\n            }while (used.contains(random));\n            used.insert(random);\n            mapping[c] = random;\n        }else{\n            random = mapping[c];\n        }\n        c = random;\n    }\n \n    vector<unsigned long long> xor_pref(n+1);\n \n    for (int i=0;i<n;i++) xor_pref[i+1] = xor_pref[i] ^ v[i];\n    \n    for (int i=0;i<q;i++){\n        int l,r;\n        cin >> l >> r;\n        cout << ((xor_pref[r]^xor_pref[l-1])?\"NO\\n\":\"YES\\n\");\n    }\n}\n \nint main(){\n \n    int t;\n    cin >> t;\n    while (t--) work();\n \n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "greedy",
      "hashing"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2018",
    "index": "A",
    "title": "Cards Partition",
    "statement": "\\begin{quote}\nDJ Genki vs Gram - Einherjar Joker\n\\hfill ⠀\n\\end{quote}\n\nYou have some cards. An integer between $1$ and $n$ is written on each card: specifically, for each $i$ from $1$ to $n$, you have $a_i$ cards which have the number $i$ written on them.\n\nThere is also a shop which contains unlimited cards of each type. You have $k$ coins, so you can buy \\textbf{at most} $k$ new cards in total, and the cards you buy can contain any integer \\textbf{between $\\mathbf{1}$ and $\\mathbf{n}$}, inclusive.\n\nAfter buying the new cards, you must partition \\textbf{all} your cards into decks, according to the following rules:\n\n- all the decks must have the same size;\n- there are no pairs of cards with the same value in the same deck.\n\nFind the maximum possible size of a deck after buying cards and partitioning them optimally.",
    "tutorial": "The answer is at most $n$. Solve the problem with $k = 0$. When is the answer $n$? If the answer is not $n$, how can you buy cards? Note that there are $n$ types of cards, so the subsets have size at most $n$, and the answer is at most $n$. If $k = 0$, you can make subsets of size $s$ if and only if the following conditions are true: the number of cards ($m$) is a multiple of $s$; the maximum number of cards of some type ($x$) is $\\leq m/s$. Proof: $m$ is the number of decks times $s$. The number of decks is $m/s$. Each deck can contain at most $1$ card of each type, so there are at most $m/s$ cards of each type in total. If the two conditions above hold, you can make a deck containing the $s$ types of cards with maximum frequency. You can show with some calculations that the conditions still hold after removing these cards. So you can prove by induction that the two conditions are sufficient to make decks of size $s$. The same idea is used in problems like 1954D - Colored Balls and abc227_d - Project Planning. For a generic $k$, the answer is $n$ if you can make the number of cards of type $1, \\ldots, n$ equal. Otherwise, for any choice of number of cards to buy, you can buy them without changing $x$. It means that you need $x \\cdot s$ cards in total: if you have less than $x \\cdot s$ cards, you have to check if you can reach $x \\cdot s$ cards by buying at most $k$ new cards; if you already have $x \\cdot s$ or more cards at the beginning, you have to check if you can make $m$ a multiple of $s$. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n, k; cin >> n >> k;\n\n        vector<ll> a(n + 1, 0);\n\n        ll mx = 0, tot = 0;\n\n        for (ll i = 1; i <= n; i++) {\n\n            cin >> a[i]; mx = max(mx, a[i]); tot += a[i];\n\n        }\n\n\n\n        ll ans = 0;\n\n        for (ll sz = 1; sz <= n; sz++) {\n\n            ll last_mul = sz * ((tot + k) / sz);\n\n            if (last_mul < tot) continue;\n\n            if (mx > last_mul / sz) continue;\n\n            ans = max(ans, sz);\n\n        }\n\n\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "2-sat",
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2018",
    "index": "B",
    "title": "Speedbreaker",
    "statement": "\\begin{quote}\nDjjaner - Speedbreaker\n\\hfill ⠀\n\\end{quote}\n\nThere are $n$ cities in a row, numbered $1, 2, \\ldots, n$ left to right.\n\n- At time $1$, you conquer exactly one city, called the starting city.\n- At time $2, 3, \\ldots, n$, you can choose a city adjacent to the ones conquered so far and conquer it.\n\nYou win if, for each $i$, you conquer city $i$ at a time no later than $a_i$. A winning strategy may or may not exist, also depending on the starting city. How many starting cities allow you to win?",
    "tutorial": "When is the answer $0$? Starting from city $x$ is equivalent to setting $a_x = 1$. At some time $t$, consider the minimal interval $[l, r]$ that contains all the cities with $a_i \\leq t$ (let's call it \"the minimal interval at time $t$\"). You have to visit all this interval within time $t$, otherwise there are some cities with $a_i \\leq t$ which you do not visit in time. So if this interval has length $> t$, you cannot visit it all within time $t$, and the answer is $0$. Otherwise, the answer is at least $1$. A possible construction is visiting \"the minimal interval at time $1$\", then \"the minimal interval at time $2$\", ..., then \"the minimal interval at time $n$\". Note that, when you visit \"the minimal interval at time $t$\", the actual time is equal to the length of the interval, which is $\\leq t$. In this way, at time $t$ you will have conquered all the cities in the minimal interval at time $t$, and possibly other cities. Starting from city $x$ is equivalent to setting $a_x = 1$. After this operation, you have to guarantee that, for each $i$, the minimal interval at time $t$ is short enough. If this interval is $[l, r]$ before the operation, it can become either $[x, r]$ (if $x < l$), or $[l, x]$ (if $x > r$), or stay the same. In all this cases, the resulting length must be $\\leq t$. With some calculations (e.g., $r-x+1 \\leq t$), you can get than $x$ must be contained in $[r-t+1, l+t-1]$. So it's enough to calculate and intersect the intervals obtained at $t = 1, \\ldots, n$, and print the length of the final interval. You can calculate the minimal intervals by iterating on the cities in increasing order of $a_i$. Again, if the old interval is $[l, r]$ and the new city has index $x$, the new possible intervals are $[x, r]$, $[l, r]$, $[l, x]$. Another correct solution is to intersect the intervals $[i-a_i+1, i+a_i-1]$. The proof is contained in the editorial of",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<ll> a(n + 1, 0);\n\n        vector<vector<ll>> adj(n + 1);\n\n        for (ll i = 1; i <= n; i++) {\n\n            cin >> a[i];\n\n            adj[min(n, a[i])].pb(i);\n\n        }\n\n\n\n        ll l = INF, r = -INF;\n\n        ll l_ans = -INF, r_ans = INF;\n\n        ll flag = 1;\n\n        for (ll i = 1; i <= n; i++) {\n\n            for (auto u : adj[i]) {\n\n                l = min(l, u); r = max(r, u);\n\n            }\n\n            if (l == INF) continue;\n\n\n\n            if (r - l + 1 > i) flag = 0;\n\n            l_ans = max(l_ans, r - i + 1);\n\n            r_ans = min(r_ans, l + i - 1);\n\n        }\n\n\n\n        if (flag == 0 || l_ans > r_ans) cout << 0 << nl;\n\n        else cout << r_ans - l_ans + 1 << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2018",
    "index": "C",
    "title": "Tree Pruning",
    "statement": "\\begin{quote}\nt+pazolite, ginkiha, Hommarju - Paved Garden\n\\hfill ⠀\n\\end{quote}\n\nYou are given a tree with $n$ nodes, rooted at node $1$. In this problem, a leaf is a non-root node with degree $1$.\n\nIn one operation, you can remove a leaf and the edge adjacent to it (possibly, new leaves appear). What is the minimum number of operations that you have to perform to get a tree, also rooted at node $1$, where all the leaves are at the same distance from the root?",
    "tutorial": "Solve for a fixed final depth of the leaves. Which nodes are \"alive\" if all leaves are at depth $d$ at the end? If the final depth of the leaves is $d$, it's optimal to keep in the tree all the nodes at depth $d$ and all their ancestors. These nodes are the only ones which satisfy the following two conditions: their depth ($a_i$) is $\\leq d$; the maximum depth of a node in their subtree ($b_i$) is $\\geq d$. So every node is alive in the interval of depths $[a_i, b_i]$. The optimal $d$ is the one contained in the maximum number of intervals.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<vector<ll>> adj(n + 1);\n\n        for (ll i = 0; i < n - 1; i++) {\n\n            ll a, b; cin >> a >> b;\n\n            adj[a].pb(b); adj[b].pb(a);\n\n        }\n\n\n\n        vector<bool> vis(n + 1, false);\n\n        vector<ll> depth(n + 1, 0), max_depth(n + 1, 0);\n\n\n\n        function<void(ll)> dfs = [&](ll s) {\n\n            vis[s] = true;\n\n            for (auto u : adj[s]) {\n\n                if (vis[u]) continue;\n\n                depth[u] = depth[s] + 1;\n\n                dfs(u);\n\n                max_depth[s] = max(max_depth[s], max_depth[u]);\n\n            }\n\n            max_depth[s] = max(max_depth[s], depth[s]);\n\n        };\n\n\n\n        dfs(1);\n\n\n\n        vector<ll> sweep(n + 2, 0);\n\n        for (ll i = 1; i <= n; i++) {\n\n            sweep[depth[i]]++; sweep[max_depth[i] + 1]--;\n\n        }\n\n\n\n        for (ll i = 1; i <= n + 1; i++) sweep[i] += sweep[i - 1];\n\n\n\n        ll ans = n - (*max_element(sweep.begin(), sweep.end()));\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2018",
    "index": "D",
    "title": "Max Plus Min Plus Size",
    "statement": "\\begin{quote}\nEnV - The Dusty Dragon Tavern\n\\hfill ⠀\n\\end{quote}\n\nYou are given an array $a_1, a_2, \\ldots, a_n$ of positive integers.\n\nYou can color some elements of the array red, but there cannot be two adjacent red elements (i.e., for $1 \\leq i \\leq n-1$, at least one of $a_i$ and $a_{i+1}$ must not be red).\n\nYour score is the maximum value of a red element, plus the minimum value of a red element, plus the number of red elements. Find the maximum score you can get.",
    "tutorial": "The optimal subsequence must contain at least one occurrence of the maximum. Iterate over the minimum, in decreasing order. You have some \"connected components\". How many elements can you pick from each component? How to make sure you have picked at least one occurrence of the maximum? The optimal subsequence must contain at least one occurrence of the maximum ($r$) (suppose it doesn't; then you can just add one occurrence, at the cost of removing at most two elements, and this does not make your score smaller). Now you can iterate over the minimum value ($l$), in decreasing order. At any moment, you can pick elements with values $[l, r]$. Then you have to support queries \"insert pick-able element\" and \"calculate score\". The pick-able elements make some \"connected components\" of size $s$, and you can pick $\\lceil s/2 \\rceil$ elements. You can maintain the components with a DSU. You also want to pick an element with value $r$. For each component, check if it contains $r$ in a subsequence with maximum size. If this does not happen for any component, your score decreases by $1$. All this information can be maintained by storing, for each component, if it contains $r$ in even positions, and if it contains $r$ in odd positions. Complexity: $O(n \\alpha(n))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<ll> a(n + 1, 0);\n\n        ll mx = 0;\n\n        for (ll i = 1; i <= n; i++) cin >> a[i], mx = max(mx, a[i]);\n\n\n\n        vector<ll> pr(n + 1, 0), sz(n + 1, 0);\n\n        iota(pr.begin(), pr.end(), 0);\n\n        vector<ll> mx_even(n + 1, 0), mx_odd(n + 1, 0);\n\n\n\n        function<ll(ll)> find = [&](ll x) {\n\n            if (x == pr[x]) return x;\n\n            return pr[x] = find(pr[x]);\n\n        };\n\n\n\n        ll total_sz = 0, cnt_mx = 0;\n\n\n\n        auto toggle = [&](ll x) {\n\n            sz[x] = 1; total_sz++;\n\n            if (a[x] == mx) mx_even[x] = 1, cnt_mx++;\n\n        };\n\n\n\n        auto is_mx = [&](ll a) {\n\n            if (mx_even[a]) return true;\n\n            if (sz[a] % 2) return false;\n\n            if (mx_odd[a]) return true;\n\n            return false;\n\n        };\n\n\n\n        function<void(ll, ll)> onion = [&](ll a, ll b) {\n\n            if (a <= 0 || a > n || b <= 0 || b > n) return;\n\n\n\n            a = find(a); b = find(b);\n\n            if (a == b) return;\n\n            if (a > b) swap(a, b);\n\n            pr[b] = a;\n\n\n\n            total_sz -= (sz[a] + 1) / 2; total_sz -= (sz[b] + 1) / 2;\n\n            cnt_mx -= (is_mx(a) + is_mx(b));\n\n\n\n            if (sz[a] % 2) {\n\n                mx_even[a] |= mx_odd[b]; mx_odd[a] |= mx_even[b];\n\n            } else {\n\n                mx_even[a] |= mx_even[b]; mx_odd[a] |= mx_odd[b];\n\n            }\n\n            sz[a] += sz[b];\n\n\n\n            total_sz += (sz[a] + 1) / 2;\n\n            cnt_mx += (is_mx(a));\n\n        };\n\n\n\n        map<ll, vector<ll>> events;\n\n        for (ll i = 1; i <= n; i++) events[-a[i]].pb(i);\n\n\n\n        ll ans = 0;\n\n        for (auto [val, v] : events) {\n\n            for (auto pos : v) toggle(pos);\n\n            for (auto pos : v) {\n\n                if (pos - 1 >= 1 && a[pos - 1] >= a[pos]) {\n\n                    onion(pos - 1, pos);\n\n                }\n\n                if (pos + 1 <= n && a[pos + 1] >= a[pos]) {\n\n                    onion(pos, pos + 1);\n\n                }\n\n            }\n\n\n\n            ans = max(ans, mx - val + total_sz - (cnt_mx == 0));\n\n        };\n\n\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "data structures",
      "dp",
      "dsu",
      "greedy",
      "implementation",
      "matrices",
      "sortings"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2018",
    "index": "E1",
    "title": "Complex Segments (Easy Version)",
    "statement": "\\begin{quote}\nKen Arai - COMPLEX\n\\hfill ⠀\n\\end{quote}\n\n\\textbf{This is the easy version of the problem. In this version, the constraints on $n$ and the time limit are lower. You can make hacks only if both versions of the problem are solved.}\n\nA set of (closed) segments is \\textbf{complex} if it can be partitioned into some subsets such that\n\n- all the subsets have the same size; and\n- a pair of segments intersects \\textbf{if and only if} the two segments are in the same subset.\n\nYou are given $n$ segments $[l_1, r_1], [l_2, r_2], \\ldots, [l_n, r_n]$. Find the maximum size of a \\textbf{complex} subset of these segments.",
    "tutorial": "Solve for a fixed $m$ (size of the subsets). $m = 1$ is easy. Can you do something similar for other $m$? Solve for a fixed $k$ (number of subsets). If you have a $O(n \\log n)$ solution for a fixed $m$, note that there exists a faster solution! Let's write a function max_k(m), which returns the maximum $k$ such that there exists a partition of $k$ valid sets containing $m$ intervals each. max_k works in $O(n \\log n)$ in the following way (using a lazy segment tree): (wlog) $r_i \\leq r_{i+1}$; for each $i$ not intersecting the previous subset, add $1$ on the interval $[l[i], r[i]]$; as soon as a point belongs to $m$ intervals, they become a subset; return the number of subsets. For a given $k$, you can binary search the maximum $m$ such that max_k(m) $\\geq k$ in $O(n \\log^2 n)$. The problem asks for the maximum $mk$. Since $mk \\leq n$, for any constant $C$ either $m \\leq C$ or $k \\leq n/C$. For $C = (n \\log n)^{1/2}$, the total complexity becomes $O((n \\log n)^{3/2})$, which is enough to solve",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nstatic constexpr int MAXN = 2.5e4;\n\nstatic constexpr int MAXT = 2 * MAXN;\n\nstatic constexpr int THRESHOLD = 600;\t// about sqrt{n log n}\n\nstatic constexpr int THRESHOLD2 = 256;\n\n\n\nstruct Segment {\n\n\tstruct Node {\n\n\t\tint mx;\n\n\t\tint lz;\n\n\t\tNode(int _mx = 0, int _lz = 0)\n\n\t\t\t: mx(_mx), lz(_lz) {}\n\n\t};\n\n\n\n\tint n;\n\n\tvector<Node> t;\n\n\n\n\tSegment(int _n) {\n\n\t\tfor (n = 1; n < _n; n <<= 1);\n\n\t\tt.resize(2 * n);\n\n\t}\n\n\n\n\tvoid prop(int i) {\n\n\t\tif (t[i].lz && i < n) {\n\n\t\t\tt[2*i  ].mx += t[i].lz;\n\n\t\t\tt[2*i+1].mx += t[i].lz;\n\n\t\t\tt[2*i  ].lz += t[i].lz;\n\n\t\t\tt[2*i+1].lz += t[i].lz;\n\n\t\t\tt[i].lz = 0;\n\n\t\t}\n\n\t}\n\n\n\n\tvoid upd(int i, int a, int b, int l, int r, int x) {\n\n\t\tprop(i);\n\n\t\tif (b <= l || r <= a) return;\n\n\t\tif (l <= a && b <= r) {\n\n\t\t\tt[i].mx += x;\n\n\t\t\tt[i].lz += x;\n\n\t\t} else {\n\n\t\t\tint m = (a + b) / 2;\n\n\t\t\tupd(2*i  , a, m, l, r, x);\n\n\t\t\tupd(2*i+1, m, b, l, r, x);\n\n\t\t\tt[i].mx = max(t[2*i].mx, t[2*i+1].mx);\n\n\t\t}\n\n\t}\n\n\n\n\tint get_max() {\n\n\t\treturn t[1].mx;\n\n\t}\n\n};\n\n\n\nstruct MySegment : public Segment {\n\n\tvector<array<int, 3>> upds;\n\n\n\n\tMySegment(int n) : Segment(n) {}\n\n\n\n\tvoid add(int l, int r, int x) {\n\n\t\tupds.push_back({l, r, x});\n\n\t\tupd(1, 0, n, l, r, x);\n\n\t}\n\n\tvoid clean() {\n\n\t\tfor (auto [l, r, x] : upds) {\n\n\t\t\tupd(1, 0, n, l, r, -x);\n\n\t\t}\n\n\t\tupds.clear();\n\n\t}\n\n};\n\n\n\nint maxpartition(int n, vector<int> l, vector<int> r) {\n\n\tvector<int> idxs(n);\n\n\tiota(begin(idxs), end(idxs), 0);\n\n\tsort(begin(idxs), end(idxs), [&](int i, int j){ return r[i] < r[j]; });\n\n\n\n\tMySegment st(2 * n + 1);\n\n\tauto max_k = [&](int m) -> int {\n\n\t\t// return max{k : one can form k subsets of m elements each}\n\n\t\tint k = 0;\n\n\t\tint last_r = -1;\n\n\t\tfor (int i : idxs) {\n\n\t\t\tif (l[i] <= last_r) continue;\n\n\t\t\tst.add(l[i], r[i]+1, 1);\n\n\t\t\tif (st.get_max() >= m) {\n\n\t\t\t\t++k;\n\n\t\t\t\tlast_r = r[i];\n\n\t\t\t\tst.clean();\n\n\t\t\t}\n\n\t\t}\n\n\t\tst.clean();\n\n\t\treturn k;\n\n\t};\n\n\n\n\tint ans = 1;\n\n\tfor (int m = 1; m <= min(n, THRESHOLD); ++m)\n\n\t\tans = max(ans, m * max_k(m));\n\n\tfor (int k = 1; k <= n / THRESHOLD; ++k) {\n\n\t\tint bsl = 0, bsu = n + 1;\n\n\t\twhile (bsu - bsl > 1) {\n\n\t\t\tint bsm = (bsl + bsu) / 2;\n\n\t\t\tif (max_k(bsm) >= k)\n\n\t\t\t\tbsl = bsm;\n\n\t\t\telse\n\n\t\t\t\tbsu = bsm;\n\n\t\t}\n\n\t\tans = max(ans, k * bsl);\n\n\t}\n\n\n\n\treturn ans;\n\n}\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<int> l(n, 0), r(n, 0);\n\n        for (ll i = 0; i < n; i++) cin >> l[i];\n\n        for (ll i = 0; i < n; i++) cin >> r[i];\n\n\n\n        ll ans = maxpartition(n, l, r);\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dsu",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2018",
    "index": "E2",
    "title": "Complex Segments (Hard Version)",
    "statement": "\\begin{quote}\nKen Arai - COMPLEX\n\\hfill ⠀\n\\end{quote}\n\n\\textbf{This is the hard version of the problem. In this version, the constraints on $n$ and the time limit are higher. You can make hacks only if both versions of the problem are solved.}\n\nA set of (closed) segments is \\textbf{complex} if it can be partitioned into some subsets such that\n\n- all the subsets have the same size; and\n- a pair of segments intersects \\textbf{if and only if} the two segments are in the same subset.\n\nYou are given $n$ segments $[l_1, r_1], [l_2, r_2], \\ldots, [l_n, r_n]$. Find the maximum size of a \\textbf{complex} subset of these segments.",
    "tutorial": "Now let's go back to max_k(m). It turns out you can implement it in $O(n \\alpha(n))$. First of all, let's make all the endpoints distinct, in such a way that two intervals intersect if and only if they were intersecting before. Let's maintain a binary string of size $n$, initially containing only ones, that can support the following queries: set bit in position $p$ to 0; find the nearest 1 to the left of position $p$. This can be maintained with DSU, where the components are the maximal intervals containing 100...00. Now let's reuse the previous solution (sweeping $r$ from left to right), but instead of a segment tree we will maintain a binary string with the following information: the positions $> r$ store 1; the positions $\\leq r$ store 1 if and only if the value in that position (in the previous solution) is a suffix max. So the queries become: add $1$ to $[l, r]$: $r$ changes, so you have to set elements in $[r'+1, r-1]$ to $0$; $r$ changes, so you have to set elements in $[r'+1, r-1]$ to $0$; the only other element that changes is the nearest 1 to the left of position $l$, which does not represent a suffix max anymore. the only other element that changes is the nearest 1 to the left of position $l$, which does not represent a suffix max anymore. find the maximum: it's equal to the number of suffix maximums, which depends on $r$ and on the number of components. This solution allows us to replace a $O(\\log n)$ factor with a $O(\\alpha(n))$ factor. Complexity: $O(n \\sqrt n \\alpha(n))$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint N;\n\n\n\nstruct DSU {\n\n    int cc;\n\n    vector<int> arr, ans;\n\n\n\n    int find(int node) {\n\n        if (arr[node] < 0) return node;\n\n        return arr[node] = find(arr[node]);\n\n    }\n\n\n\n    void join(int u, int v) {\n\n        u = find(u), v = find(v);\n\n        if (u == v) return;\n\n        cc--;\n\n\n\n        if (arr[u] > arr[v]) swap(u, v);\n\n\n\n        arr[u] += arr[v];\n\n        arr[v] = u;\n\n        ans[u] = min(ans[u], ans[v]);\n\n    }\n\n\n\n    void reset() {\n\n        ans.resize(2 * N + 1);\n\n        arr.assign(2 * N + 1, -1);\n\n        iota(ans.begin(), ans.end(), 0);\n\n        cc = 2 * N + 1;\n\n    }\n\n};\n\n\n\nDSU dsu;\n\nvector<pair<int, int>> rangers;\n\n\n\nint max_groups(int group_size) {\n\n    dsu.reset();\n\n\n\n    int curr_l = 0;\n\n    int last_r = 1;\n\n    int cnt = 0;\n\n    int actual_l = 0;\n\n\n\n    for (auto [l, r]: rangers) {\n\n        if (l < curr_l) continue;\n\n\n\n        while (last_r < r - 1) {\n\n            dsu.join(last_r, last_r - 1);\n\n            last_r++;\n\n        }\n\n        last_r++;\n\n\n\n        int fake = dsu.ans[dsu.find(l - 1)];\n\n        if (fake > actual_l)\n\n            dsu.join(fake, fake - 1);\n\n\n\n        if (dsu.cc - (2 * N + 1 - r) - cnt - 1 == group_size) {\n\n            cnt++;\n\n            curr_l = r;\n\n\n\n            int curr = r - 1;\n\n            while (curr != actual_l) {\n\n                dsu.join(curr, curr - 1);\n\n                curr = dsu.ans[dsu.find(curr)];\n\n            }\n\n\n\n            actual_l = last_r;\n\n            last_r++;\n\n        }\n\n    }\n\n\n\n    return cnt;\n\n}\n\n\n\nint maxpartition(int N, vector<int> L, vector<int> R) {\n\n    ::N = N;\n\n    vector<array<int, 3>> positions(2 * N);\n\n    for (int i = 0; i < N; i++) {\n\n        positions[2 * i] = {L[i], 0, i};\n\n        positions[2 * i + 1] = {R[i], 1, i};\n\n    }\n\n\n\n    sort(positions.begin(), positions.end());\n\n\n\n    rangers.resize(N);\n\n    for (int i = 0; i < 2 * N; i++) {\n\n        auto [z, wh, pos] = positions[i];\n\n        if (!wh) rangers[pos].first = i + 1;\n\n        else rangers[pos].second = i + 2;\n\n    }\n\n\n\n    sort(rangers.begin(), rangers.end(), [&](const auto &a, const auto &b) {\n\n        return a.second < b.second;\n\n    });\n\n\n\n    int ans = 0;\n\n    function<void(int, int, int, int)> solve =\n\n        [&](int tl, int tr, int al, int ar) {\n\n        if (tl > tr) return;\n\n        if (al == ar) {\n\n            ans = max(ans, tr * ar); return;\n\n        }\n\n\n\n        int tm = (tl + tr) / 2;\n\n        int am = max_groups(tm);\n\n        ans = max(ans, tm * am);\n\n        solve(tl, tm - 1, am, ar); solve(tm + 1, tr, al, am);\n\n    };\n\n\n\n    solve(1, N, 0, N);\n\n\n\n    return ans;\n\n}\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<int> l(n, 0), r(n, 0);\n\n        for (ll i = 0; i < n; i++) cin >> l[i];\n\n        for (ll i = 0; i < n; i++) cin >> r[i];\n\n\n\n        ll ans = maxpartition(n, l, r);\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "dsu",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 3400
  },
  {
    "contest_id": "2018",
    "index": "F3",
    "title": "Speedbreaker Counting (Hard Version)",
    "statement": "\\begin{quote}\nNightHawk22 - Isolation\n\\hfill ⠀\n\\end{quote}\n\n\\textbf{This is the hard version of the problem. In the three versions, the constraints on $n$ and the time limit are different. You can make hacks only if all the versions of the problem are solved.}\n\nThis is the statement of \\textbf{Problem D1B}:\n\n- There are $n$ cities in a row, numbered $1, 2, \\ldots, n$ left to right.\n\n- At time $1$, you conquer exactly one city, called the starting city.\n- At time $2, 3, \\ldots, n$, you can choose a city adjacent to the ones conquered so far and conquer it.\n\nYou win if, for each $i$, you conquer city $i$ at a time no later than $a_i$. A winning strategy may or may not exist, also depending on the starting city. How many starting cities allow you to win?\n\nFor each $0 \\leq k \\leq n$, count the number of arrays of positive integers $a_1, a_2, \\ldots, a_n$ such that\n\n- $1 \\leq a_i \\leq n$ for each $1 \\leq i \\leq n$;\n- the answer to \\textbf{Problem D1B} is $k$.\n\nThe answer can be very large, so you have to calculate it modulo a given prime $p$.",
    "tutorial": "Suppose you are given a starting city and you want to win. Find several strategies to win (if possible) and try to work with the simplest ones. The valid starting cities are either zero, or all the cities in $I := \\cap_{i=1}^n [i - a_i + 1, i + a_i - 1] = [l, r]$. Now you have some bounds on the $a_i$. Fix the interval $I$ and try to find a (slow) DP. Counting paths seems easier than counting arrays. Make sure that, for each array, you make exactly one path (or a number of paths which is easy to handle). How many distinct states do you calculate in your DP? For a fixed starting city, if you can win, this strategy works: [Strategy 1] If there is a city on the right whose distance is $t$ and whose deadline is in $t$ turns, go to the right. Otherwise, go to the left. Proof: All constraints on the right hold. This strategy minimizes the time to reach any city on the left. So, if any strategy works, this strategy works too. For a fixed starting city, if you can win, this strategy works: [Strategy 2] If there is a city whose distance is $t$ and whose deadline is in $t$ turns, go to that direction. Otherwise, go to any direction. The valid starting cities are either zero, or all the cities in $I := \\cap_{i=1}^n [i - a_i + 1, i + a_i - 1] = [l, r]$. Proof: The cities outside $I$ are losing, because there exists at least one unreachable city. Let's start from any city $x$ in $I$, and use Strategy 2. You want to show that, for any $x$ in $I$, Strategy 2 can visit all cities in $I$ first, then all the other cities. Then, you can conclude that either all the cities in $I$ are winning, or they are all losing. The interval $I$ gives bounds on the $a_i$: specifically, $a_i \\geq \\max(i-l+1, r-i+1)$. Then, you can verify that visiting the interval $I$ first does not violate Strategy 2. If you use Strategy 1, the first move on the right determines $l$. Let's iterate on the (non-empty) interval $I$. Let's calculate the bounds $a_i \\geq \\max(i-l+1, r-i+1)$. Note that Strategy 1 is deterministic (i.e., it gives exactly one visiting order for each fixed pair (starting city, $a$)). From now, you will use Strategy 1. Now you will calculate the number of pairs ($a$, visiting order) such that the cities in $I$ are valid starting cities (and there might be other valid starting cities). Let's define dp[i][j][k] = number of pairs ($a$, visiting order), restricted to the interval $[i, j]$, where $k =$ \"are you forced to go to the right in the next move?\". Here are the main ideas to find the transitions: If you go from $[i+1, j]$ to $[i, j]$, you must ensure that $a_i \\geq \\max(i-l+1, r-i+1, j-i+1)$ (because you visit it at time $j-i+1$). Also, $k$ must be $0$. If you go from $[i, j-1]$ to $[i, j]$, and you want to make $k = 0$, you must make $a_j = j-i+1$. It means that $j$ was the city that was enforcing you to go to the right. In my code, the result is stored in int_ans[i][j]. Now you want to calculate the number of pairs ($a$, visiting order) such that the cities in $I$ are the only valid starting cities. This is similar to 2D prefix sums, and it's enough to make int_ans[i][j] -= int_ans[i - 1][j] + int_ans[i][j + 1] - int_ans[i - 1][j + 1]. Since, for a fixed $a$, the visiting order only depends on the starting city, the number of $a$ for the interval $[i, j]$ is now int_ans[i][j] / (j - i + 1). You have solved $k \\geq 1$. The answer for $k = 0$ is just $n^n$ minus all the other answers. In the previous section, you are running the same DP for $O(n^2)$ different \"bound arrays\" on the $a_i$ (in particular, $O(n)$ arrays for each $k$). Now you want to solve a single $k$ with a single DP. For a fixed $k$, you can notice that, if you run the DP on an array of length $2n$ instead of $n$, the bound array obtained from $I = [n-k+1, n]$ contains all the bound arrays you wanted as subarrays of length $n$. So you can run the DP and get all the results as dp[i][i + n - 1][0]. You still have $O(n^3)$ distinct states in total. How to make \"bound arrays\" simpler? It turns out that you can handle $l$ and $r$ differently! You can create bound arrays only based on $r$ (and get $O(n^2)$ distinct states), and find $l$ using the Corollary of Lemma 2. The transitions before finding $l$ are very simple (you always go to the left). So a possible way to get $O(n^2)$ complexity is processing Strategy 1 and the DP in reverse order (from time $n$ to time $1$). Complexity: $O(n^2)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint t,n,p,dp[6011][6011][2],lim[6011],w[6011][6011],ans[3011];\n\nvoid solve(int x)\n\n{//printf(\"==========================solve(%d)\\n\",x);\n\n\tfor(int i=1;i<=x;++i)lim[i]=x-i+1;\n\n\tfor(int i=x+1;i<=n;++i)lim[i]=i-x+1;\n\n\t// printf(\"lim:\");for(int i=1;i<=n;++i)printf(\"%d \",lim[i]);putchar(10);\n\n\t// printf(\"res[%d]:\",x);for(int i=1;i<=n;++i)printf(\"%d \",res[x][i]);putchar(10);\n\n}\n\nint main()\n\n{\n\n\tscanf(\"%d\",&t);while(t--)\n\n\t{\n\n\t\tscanf(\"%d%d\",&n,&p);//printf(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>. n:%d p:%d\\n\",n,p);\n\n\t\tfor(int i=1;i<=n;++i)lim[i]=n-i+1;\n\n\t\tfor(int i=n+1;i<2*n;++i)lim[i]=i-n+1;\n\n\t\tfor(int i=1;i<=n;++i)ans[i]=0;\n\n\t\tfor(int i=1;i<=2*n;++i)for(int j=i;j<=2*n;++j)dp[i][j][0]=dp[i][j][1]=0;\n\n\t\tfor(int r=1;r<2*n;++r)\n\n\t\t{\n\n\t\t\tint cur=1;\n\n\t\t\tfor(int i=r;i>=1;--i)\n\n\t\t\t{\n\n\t\t\t\tif(r-i+1<lim[i])w[i][r]=0;\n\n\t\t\t\telse w[i][r]=cur;\n\n\t\t\t\tcur=1ll*cur*(n-max(lim[i],r-i+1)+1)%p;\n\n\t\t\t}\n\n\t\t}\n\n\t\tfor(int i=1;i<=n;++i)dp[i][i+n-1][1]=1;\n\n\t\tfor(int i=n;i;--i)\n\n\t\t{\n\n\t\t\tfor(int l=1;l+i-1<2*n;++l)\n\n\t\t\t{\n\n\t\t\t\tint r=l+i-1;\n\n\t\t\t\tif(r>=n)\n\n\t\t\t\t{\n\n\t\t\t\t\tans[r-n+1]=(ans[r-n+1]+1ll*w[l][r]*dp[l][r][1])%p;\n\n\t\t\t\t\tans[r-n]=(ans[r-n]-1ll*w[l][r]*dp[l][r][1])%p;\n\n\t\t\t\t}\n\n\t\t\t\tif(l<r)\n\n\t\t\t\t{\n\n\t\t\t\t\tdp[l+1][r][0]=(dp[l+1][r][0]+1ll*dp[l][r][0]*(n-max(lim[l],r-l+1)+1))%p;\n\n\t\t\t\t\tdp[l][r-1][1]=(dp[l][r-1][1]+1ll*dp[l][r][0]*(n-max(lim[r],r-l+1)+1))%p;\n\n\t\t\t\t\tif(lim[l]<=r-l+1)dp[l+1][r][0]=(dp[l+1][r][0]+dp[l][r][1])%p;\n\n\t\t\t\t\tdp[l][r-1][1]=(dp[l][r-1][1]+1ll*dp[l][r][1]*(n-max(lim[r],r-l+1)+1))%p;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tans[0]=1;for(int i=1;i<=n;++i)ans[0]=1ll*ans[0]*n%p;\n\n\t\tfor(int i=1;i<=n;++i)ans[0]=(ans[0]-ans[i])%p;\n\n\t\tfor(int i=0;i<=n;++i)printf(\"%d \",(ans[i]%p+p)%p);putchar(10);\n\n\t}\n\n}",
    "tags": [
      "dp",
      "greedy",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2019",
    "index": "A",
    "title": "Max Plus Size",
    "statement": "\\begin{quote}\nEnV - Dynasty\n\\hfill ⠀\n\\end{quote}\n\nYou are given an array $a_1, a_2, \\ldots, a_n$ of positive integers.\n\nYou can color some elements of the array red, but there cannot be two adjacent red elements (i.e., for $1 \\leq i \\leq n-1$, at least one of $a_i$ and $a_{i+1}$ must not be red).\n\nYour score is the maximum value of a red element plus the number of red elements. Find the maximum score you can get.",
    "tutorial": "Can you reach the score $\\max(a) + \\lceil n/2 \\rceil$? Can you reach the score $\\max(a) + \\lceil n/2 \\rceil - 1$? The maximum red element is $\\leq \\max(a)$, and the maximum number of red elements is $\\lceil n/2 \\rceil$. Can you reach the score $\\max(a) + \\lceil n/2 \\rceil$? If $n$ is even, you always can, by either choosing all the elements in even positions or all the elements in odd positions (at least one of these choices contains $\\max(a)$). If $n$ is odd, you can if and only if there is one occurrence of $\\max(a)$ in an odd position. Otherwise, you can choose even positions and your score is $\\max(a) + \\lceil n/2 \\rceil - 1$. Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n; cin >> n;\n\n        vector<ll> a(n + 1, 0);\n\n        for (ll i = 1; i <= n; i++) cin >> a[i];\n\n\n\n        ll ans = 0;\n\n        for (ll i = 1; i <= n; i++) {\n\n            ll sz = n / 2 + (n % 2 == 1 && i % 2 == 1);\n\n            ans = max(ans, a[i] + sz);\n\n        }\n\n\n\n        cout << ans << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "2019",
    "index": "B",
    "title": "All Pairs Segments",
    "statement": "\\begin{quote}\nShirobon - FOX\n\\hfill ⠀\n\\end{quote}\n\nYou are given $n$ points on the $x$ axis, at increasing positive integer coordinates $x_1 < x_2 < \\ldots < x_n$.\n\nFor each pair $(i, j)$ with $1 \\leq i < j \\leq n$, you draw the segment $[x_i, x_j]$. The segments are closed, i.e., a segment $[a, b]$ contains the points $a, a+1, \\ldots, b$.\n\nYou are given $q$ queries. In the $i$-th query, you are given a positive integer $k_i$, and you have to determine how many points with integer coordinates are contained in exactly $k_i$ segments.",
    "tutorial": "Can you determine fast how many intervals contain point $p$? The intervals that contain point $p$ are the ones with $l \\leq p$ and $r \\geq p$. Determine how many intervals contain: point $x_1$; points $x_1 + 1, \\ldots, x_2 - 1$; point $x_2$; $\\ldots$ point $x_n$. First, let's focus on determining how many intervals contain some point $x$. These intervals are the ones with $l \\leq x$ and $x \\leq r$. So a point $x_i < p < x_{i+1}$ satisfies $x_1 \\leq p, \\ldots, x_i \\leq p$, and $p \\leq x_{i+1}, \\ldots, p \\leq x_n$. It means that you have found $x_{i+1} - x_i - 1$ points contained in exactly $i(n-i)$ intervals (because there are $i$ possible left endpoints and $n-i$ possible right endpoints). Similarly, the point $p = x_i$ is contained in $i(n-i+1) - 1$ intervals (you have to remove interval $[x_i, x_i]$, which you do not draw). So you can use a map that stores how many points are contained in exactly $x$ intervals, and update the map in the positions $i(n-i)$ and $i(n-i+1) - 1$. Complexity: $O(n \\log n)$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n\n\n#define nl \"\\n\"\n\n#define nf endl\n\n#define ll long long\n\n#define pb push_back\n\n#define _ << ' ' <<\n\n\n\n#define INF (ll)1e18\n\n#define mod 998244353\n\n#define maxn 110\n\n\n\nint main() {\n\n    ios::sync_with_stdio(0);\n\n    cin.tie(0);\n\n\n\n    #if !ONLINE_JUDGE && !EVAL\n\n        ifstream cin(\"input.txt\");\n\n        ofstream cout(\"output.txt\");\n\n    #endif\n\n\n\n    ll t; cin >> t;\n\n    while (t--) {\n\n        ll n, q; cin >> n >> q;\n\n        vector<ll> x(n + 1, 0);\n\n        for (ll i = 1; i <= n; i++) cin >> x[i];\n\n\n\n        map<ll, ll> mp;\n\n        for (ll i = 1; i <= n - 1; i++) {\n\n            mp[i * (n - i)] += (x[i + 1] - x[i] - 1);\n\n        }\n\n        for (ll i = 1; i <= n; i++) {\n\n            mp[i * (n - i + 1) - 1]++;\n\n        }\n\n\n\n        while (q--) {\n\n            ll x; cin >> x;\n\n            cout << mp[x] << ' ';\n\n        }\n\n        cout << nl;\n\n    }\n\n\n\n    return 0;\n\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2020",
    "index": "A",
    "title": "Find Minimum Operations",
    "statement": "You are given two integers $n$ and $k$.\n\nIn one operation, you can subtract any power of $k$ from $n$. Formally, in one operation, you can replace $n$ by $(n-k^x)$ for any non-negative integer $x$.\n\nFind the minimum number of operations required to make $n$ equal to $0$.",
    "tutorial": "How many operations will have $x = 0$. Try $k = 2$. Answer will be the number of ones in binary representation of $n$. If $k$ is 1, we can only subtract 1 in each operation, and our answer will be $n$. Now, first, it can be seen that we have to apply at least $n$ mod $k$ operations of subtracting $k^0$ (as all the other operations will not change the value of $n$ mod $k$). Now, once $n$ is divisible by $k$, solving the problem for $n$ is equivalent to solving the problem for $\\frac{n}{k}$ as subtracting $k^0$ will be useless because if we apply the $k^0$ subtraction operation, then $n$ mod $k$ becomes $k-1$, and we have to apply $k-1$ more operations to make $n$ divisible by $k$ (as the final result, i.e., 0 is divisible by $k$). Instead of doing these $k$ operations of subtracting $k^0$, a single operation subtracting $k^1$ will do the job. So, our final answer becomes the sum of the digits of $n$ in base $k$. The complexity of the solution is $O(\\log_{k}{n})$ per testcase.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint find_min_oper(int n, int k){\n\tif(k == 1) return n;\n\tint ans = 0;\n\twhile(n){\n\t\tans += n%k;\n\t\tn /= k;\n\t}\n\treturn ans;\n}\n \nint main()\n{\n\tint t;\n\tcin >> t;\n\twhile(t--){\n\t\tint n,k;\n\t\tcin >> n >> k;\n\t\tcout << find_min_oper(n,k) << \"\\n\";\n\t}\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2020",
    "index": "B",
    "title": "Brightness Begins",
    "statement": "Imagine you have $n$ light bulbs numbered $1, 2, \\ldots, n$. \\textbf{Initially, all bulbs are on}. To flip the state of a bulb means to turn it off if it used to be on, and to turn it on otherwise.\n\nNext, you do the following:\n\n- for each $i = 1, 2, \\ldots, n$, flip the state of all bulbs $j$ such that $j$ is divisible by $i^\\dagger$.\n\nAfter performing all operations, there will be several bulbs that are still on. Your goal is to make this number exactly $k$.\n\nFind the smallest suitable $n$ such that after performing the operations there will be exactly $k$ bulbs on. We can show that an answer always exists.\n\n$^\\dagger$ An integer $x$ is divisible by $y$ if there exists an integer $z$ such that $x = y\\cdot z$.",
    "tutorial": "The final state of $i$th bulb (on or off) is independent of $n$. The final state of the $i$th bulb tells us about the parity of number of divisors of $i$. For any bulb $i$, its final state depends on the parity of the number of divisors of $i$. If $i$ has an even number of divisors, then bulb $i$ will be on; else it will be off. This translates to, if $i$ is not a perfect square, bulb $i$ will be on; else it will be off. So now the problem is to find the $k$th number which is not a perfect square. This can be done by binary searching the value of $n$ such that $n- \\lfloor \\sqrt{n} \\rfloor = k$ or the direct formula $n$ = $\\lfloor k + \\sqrt{k} + 0.5 \\rfloor$. For the proof of the second formula you can refer this book page 141 E18",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    cin >> t;\n    while(t--){\n        long long k;\n        cin >> k;\n        cout << k + int(sqrtl(k) + 0.5) << \"\\n\";\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2020",
    "index": "C",
    "title": "Bitwise Balancing",
    "statement": "You are given three non-negative integers $b$, $c$, and $d$.\n\nPlease find a non-negative integer $a \\in [0, 2^{61}]$ such that $(a\\, |\\, b)-(a\\, \\&\\, c)=d$, where $|$ and $\\&$ denote the bitwise OR operation and the bitwise AND operation, respectively.\n\nIf such an $a$ exists, print its value. If there is no solution, print a single integer $-1$. If there are multiple solutions, print any of them.",
    "tutorial": "Try to find some independent operations/combinations. The expression is independent for each digit in binary representation The first observation is that the expression $a$|$b$ - $a$&$c = d$ is bitwise independent. That is, the combination of a tuple of bits of $a, b, and\\ c$ corresponding to the same power of 2 will only affect the bit value of $d$ at that power of 2 only. This is because: We are performing subtraction, so extra carry won't be generated to the next power of 2. We are performing subtraction, so extra carry won't be generated to the next power of 2. Any tuple of bits of $a$, $b$, and $c$ corresponding to the same power of 2 won't result in -1 for that power of 2. As that would require $a|b$ to be zero and $a$&$c$ to be one. The former condition requires the bit of $a$ to be zero, while the latter requires it to be one, which is contradicting. Any tuple of bits of $a$, $b$, and $c$ corresponding to the same power of 2 won't result in -1 for that power of 2. As that would require $a|b$ to be zero and $a$&$c$ to be one. The former condition requires the bit of $a$ to be zero, while the latter requires it to be one, which is contradicting. Now, let us consider all 8 cases of bits of a, b, c and the corresponding bit value of d in the following table: So, clearly, for different bits of $b, c,$ and $d$, we can find the value of the corresponding bit in $a$, provided it is not the case when bit values of $b, c,$ and $d$ are 1,0,0 or 0,1,1, which are not possible; so, in that case, the answer is -1.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\n \nvoid solve() {\n    ll a = 0, b, c, d, pos = 1, bit_b, bit_c, bit_d, mask = 1;\n    cin >> b >> c >> d;\n    for (ll i = 0; i < 62; i++) {\n        if (b&mask) bit_b = 1;\n        else bit_b = 0;\n        if (c&mask) bit_c = 1;\n        else bit_c = 0;\n        if (d&mask) bit_d = 1;\n        else bit_d = 0;\n        if ((bit_b && (!bit_c) && (!bit_d)) || ((!bit_b) && bit_c && bit_d)) {\n            pos = 0;\n            break;\n        }\n        if (bit_b && bit_c) {\n            a += (1ll-bit_d)*mask;\n        } else {\n            a += bit_d*mask;\n        }\n        mask<<=1;\n    }\n    if (pos) {\n        cout << a << \"\\n\";\n    } else {\n        cout << -1 << \"\\n\";\n    }\n}\n \nint main() {\n    ll t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "hashing",
      "implementation",
      "math",
      "schedules",
      "ternary search"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2020",
    "index": "D",
    "title": "Connect the Dots",
    "statement": "One fine evening, Alice sat down to play the classic game \"Connect the Dots\", but with a twist.\n\nTo play the game, Alice draws a straight line and marks $n$ points on it, indexed from $1$ to $n$. Initially, there are no arcs between the points, so they are all disjoint. After that, Alice performs $m$ operations of the following type:\n\n- She picks three integers $a_i$, $d_i$ ($1 \\le d_i \\le 10$), and $k_i$.\n- She selects points $a_i, a_i+d_i, a_i+2d_i, a_i+3d_i, \\ldots, a_i+k_i\\cdot d_i$ and connects each pair of these points with arcs.\n\nAfter performing all $m$ operations, she wants to know the number of connected components$^\\dagger$ these points form. Please help her find this number.\n\n$^\\dagger$ Two points are said to be in one connected component if there is a path between them via several (possibly zero) arcs and other points.",
    "tutorial": "The value of $d$ is very small. Try using Disjoint Set Union (DSU). The main idea is to take advantage of the low upper bound of $d_i$ and apply the Disjoint Set Union. We will consider $dp[j][w]$, which denotes the number of ranges that contain the $j$ node in connection by the triplets/ranges with $w$ as $d$ and $j$ is not $a\\ +\\ k\\ *\\ d$, and $id[j][w]$, which denotes the node that represents an overall connected component of which $j$ node is part of for now. The size of both $dp$ and $id$ is $max_j * max_w = (n) * 10 = 10\\ n$. We will maintain two other arrays, $Start_cnt[j][w]$ and $End_cnt[j][w]$, which store the number of triplets with $j$ as $a_i$ and $a_i+k_i*d_i$, respectively, and with $w$ as $d_i$, to help us maintain the beginning and end of ranges. We will now apply Disjoint Set Union. For each $i$th triplet, we assume $a_i$ will be the parent node of the Set created by $a_i$, $a_i$ + $d_i$, ..., $a_i+k_i*d_i$. The transitions of $dp$ are as follows: 1) if $j \\ge 10$ (max of $d_i$): for all $w$, $dp[j][w]$ are the same as $dp[j-w][w]$, just with some possible changes. These changes are due to $j$ being the start or the end of some triplet with $d_i$ as $w.$ So, let us start with $dp[j][w]$ as $Start_cnt[j][w] - End_cnt[j][w]$. If $dp[j-w][w]$ is non-zero, then perform a union operation (of DSU) between the $j$ node and $id[j-w][w]$, increment $dp[j][w]$ by $dp[j-w][w]$, and assign $id[j][w]$ as $id[j-w][w]$. This unites the ranges over the $j$ node. 2) if $j \\lt 10$ (max of $d_i$): we do the same as above; rather than doing for all $w,$ we would restrict ourselves with $w$ from $0$ to $j-1$. The net time complexity = updation of $dp[j][w]$ value by $Start_cnt$ and $End_cnt$ + union operations due to union of $id[j-w][w]$ with $j$ over all $w$ + incrementing $dp$ values (by $dp[j-w][w]$) + copying $id$ values = $10\\ n + 10\\ nlogn + 10\\ n + 10\\ n= 10 nlogn + 30n$ (in worst case) = $O(max_d*n*logn)$.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\nusing namespace std;\nconst ll N = 2e5+2;\nconst ll C = 10 + 1;\n \nvector<ll> par(N), sz(N, 0);\nvector<vector<ll>> dp(N, vector<ll> (C, 0)), ind(N, vector<ll> (C, 0)), start_cnt(N, vector<ll> (C, 0)), end_cnt(N, vector<ll> (C,0));\n \nll find_par(ll a) {\n    if (par[a] == a) return a;\n    return par[a] = find_par(par[a]);\n}\n \nvoid unite(ll a, ll b){\n    a = find_par(a), b = find_par(b);\n    if (a == b) return;\n    if (sz[b] > sz[a]) swap(a, b);\n    sz[a] += sz[b];\n    par[b] = a;\n}\n \nvoid reset(ll n) {\n    for (ll i = 1; i <= n; i++) {\n        par[i] = i;\n        sz[i] = 1;\n        for (ll j = 1; j < C; j++) {\n            dp[i][j] = start_cnt[i][j] = end_cnt[i][j] = 0;\n            ind[i][j] = i;\n        }\n    }\n}\n \nvoid solve() {\n    ll n, m, a, d, k;\n    cin >> n >> m;\n    reset(n);\n    for (ll i = 0; i < m; i++) {\n        cin >> a >> d >> k;\n        start_cnt[a][d]++;\n        end_cnt[a + k * d][d]++;\n    }\n    for (ll i = 1; i <= n; i++) {\n        for (ll j = 1; j < C; j++) {\n            dp[i][j] = start_cnt[i][j] - end_cnt[i][j];\n            if (i-j < 1) continue;\n            if (dp[i-j][j]) {\n                unite(ind[i-j][j], i);\n                ind[i][j] = ind[i-j][j];\n                dp[i][j] += dp[i-j][j];\n            }\n        }\n    }\n    ll ans = 0;\n    for (ll i = 1; i <= n; i++) {\n        if (find_par(i) == i) ans++;\n    }\n    cout << ans << \"\\n\";\n}\n \nint main() {\n    ll t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "brute force",
      "dp",
      "dsu",
      "graphs",
      "math",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2020",
    "index": "E",
    "title": "Expected Power",
    "statement": "You are given an array of $n$ integers $a_1,a_2,\\ldots,a_n$. You are also given an array $p_1, p_2, \\ldots, p_n$.\n\nLet $S$ denote the random \\textbf{multiset} (i. e., it may contain equal elements) constructed as follows:\n\n- Initially, $S$ is empty.\n- For each $i$ from $1$ to $n$, insert $a_i$ into $S$ with probability $\\frac{p_i}{10^4}$. Note that each element is inserted independently.\n\nDenote $f(S)$ as the bitwise XOR of all elements of $S$. Please calculate the expected value of $(f(S))^2$. Output the answer modulo $10^9 + 7$.\n\nFormally, let $M = 10^9 + 7$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Try to find the expected value of $f(S)$ rather than $(f(S))^2$. Write the binary representation of $f(S)$ and find $(f(S))^2$. Let the binary representation of the $Power$ be $b_{20}b_{19}...b_{0}$. Now $Power^2$ is $\\sum_{i=0}^{20} \\sum_{j=0}^{20} b_i b_j * 2^{i+j}$. Now if we compute the expected value of $b_ib_j$ for every pair $(i,j)$, then we are done. We can achieve this by dynamic programming. For each pair $i,j$, there are only 4 possible values of $b_i,b_j$. For every possible value, we can maintain the probability of reaching it, and we are done. The complexity of the solution is $O(n.log(max(a_i))^2)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint fast_exp(int b, int e, int mod){\n\tint ans = 1;\n\twhile(e){\n\t\tif(e&1) ans = (1ll*ans*b) % mod;\n\t\tb = (1ll*b*b) % mod;\n\t\te >>= 1;\n\t}\n\treturn ans;\n}\nconst int mod = 1e9+7;\nconst int bits = 11;\n \nint inv(int n){\n\treturn fast_exp(n,mod-2,mod);\n}\n \nconst int inverse_1e4 = inv(10000);\nint dp[bits][bits][2][2];\nvoid transition(int a, int p){\n\tp = (1ll*p*inverse_1e4) % mod;\n\tint negp = (mod+1-p) % mod;\n\tint bin[bits];\n\tfor(int i = 0; i < bits; i++){\n\t\tbin[i] = a&1;\n\t\ta >>= 1;\n\t}\n\tfor(int i = 0; i < bits; i++){\n\t\tfor(int j = 0; j < bits; j++){\n\t\t\tint temp[2][2];\n \n\t\t\tfor(int k : {0,1}) for(int l : {0,1}) temp[k][l] = (1ll*dp[i][j][k][l]*negp + 1ll*dp[i][j][k^bin[i]][l^bin[j]]*p) % mod;\n \n\t\t\tfor(int k : {0,1}) for(int l : {0,1}) dp[i][j][k][l] = temp[k][l];\n\t\t}\n\t}\n}\nint main() {\n    int t;\n    cin >> t;\n    while(t--){\n    \tint n;\n    \tcin >> n;\n    \tint a[n],p[n];\n    \tfor(int i = 0; i < n; i++) cin >> a[i];\n    \tfor(int i = 0; i < n; i++) cin >> p[i];\n    \tfor(int i = 0; i < bits; i++) for(int j = 0; j < bits; j++) dp[i][j][0][0] = 1;\n    \tfor(int i = 0; i < n; i++) transition(a[i],p[i]);\n    \tint ans = 0;\n    \tfor(int i = 0; i < bits; i++){\n    \t\tfor(int j = 0; j < bits; j++){\n    \t\t\tint pw2 = (1ll<<(i+j)) % mod;\n    \t\t\tans += (1ll*pw2*dp[i][j][1][1]) % mod;\n    \t\t\tans %= mod;\n    \t\t\tfor(int k : {0,1}) for(int l : {0,1}) dp[i][j][k][l] = 0;\n    \t\t}\n    \t}\n    \tcout << ans << \"\\n\";\n    }\n\treturn 0;\n}\n",
    "tags": [
      "bitmasks",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2020",
    "index": "F",
    "title": "Count Leaves",
    "statement": "Let $n$ and $d$ be positive integers. We build the the divisor tree $T_{n,d}$ as follows:\n\n- The root of the tree is a node marked with number $n$. This is the $0$-th layer of the tree.\n- For each $i$ from $0$ to $d - 1$, for each vertex of the $i$-th layer, do the following. If the current vertex is marked with $x$, create its children and mark them with all possible distinct divisors$^\\dagger$ of $x$. These children will be in the $(i+1)$-st layer.\n- The vertices on the $d$-th layer are the leaves of the tree.\n\nFor example, $T_{6,2}$ (the divisor tree for $n = 6$ and $d = 2$) looks like this:\n\nDefine $f(n,d)$ as the number of leaves in $T_{n,d}$.\n\nGiven integers $n$, $k$, and $d$, please compute $\\sum\\limits_{i=1}^{n} f(i^k,d)$, modulo $10^9+7$.\n\n$^\\dagger$ In this problem, we say that an integer $y$ is a divisor of $x$ if $y \\ge 1$ and there exists an integer $z$ such that $x = y \\cdot z$.",
    "tutorial": "$f$ satisfies a special property for fixed d. $f$ is multiplicative i.e. $f(x.y)$ = $f(x) * f(y)$ if $x,y$ are coprime, for fixed d. It can be observed that the number of leaves is equal to the number of ways of choosing $d$ integers $a_0,a_1,a_2...a_d$ with $a_d = n$ and $a_i divides a_{i+1}$ for all $(0 \\le i \\le d-1)$. Lets define $g(n) = f(n,d)$ for given $d$. It can be seen that the function $g$ is multiplicative i.e. $g(p*q) = g(p)*g(q)$ if $p$ and $q$ are coprime. Now, lets try to calculate $g(n)$ when $n$ is of the form $p^x$ where $p$ is a prime number and $x$ is any non negative integer. From the first observation, we can say that here all the $a_i$ will be a power of $p$. Therefore $a_0,a_1,a_2...a_d$ can be written as $p^{b_0},p^{b_1},p^{b_2}...p^{b_d}$. Now we just have to ensure that $0 \\le b_0 \\le b_1 \\le b_2 ... \\le b_d = x$. The number of ways of doing so is $\\binom{x+d}{d}$. Now, lets make a dp (inspired by the idea of the dp used in fast prime counting) where $dp(n,x) = \\sum_{i=1, spf(i) >= x}^{n} g(i)$. Here $spf(i)$ means smallest prime factor of $i$. $dp(x, p) = \\begin{cases} 0 & \\text{if } x = 0 \\\\ 1 & \\text{if } p > x \\\\ dp(x, p+1) & \\text{if } p \\text{ is not prime} \\\\ \\sum\\limits_{i=0 \\, \\text{to} \\, p^i \\le x} dp\\left(\\lfloor{\\frac{x}{p^i}} \\rfloor, p+1\\right) f(p^{ik}, d) & \\text{otherwise} \\end{cases}$ Our required answer is $dp(n,2)$. The overall complexity of the solution is $O(n^{\\frac{2}{3}})$.",
    "code": "#include <bits/stdc++.h>\n#define ll long long\n#define pb push_back\n#define mp make_pair\n#define F first\n#define S second\n#define pii pair<int,int>\n#define pll pair<ll,ll>\n#define pcc pair<char,char>\n#define vi vector <int>\n#define vl vector <ll>\n#define sd(x) scanf(\"%d\",&x)\n#define slld(x) scanf(\"%lld\",&x)\n#define pd(x) printf(\"%d\",x)\n#define plld(x) printf(\"%lld\",x)\n#define pds(x) printf(\"%d \",x)\n#define pllds(x) printf(\"%lld \",x)\n#define pdn(x) printf(\"%d\\n\",x)\n#define plldn(x) printf(\"%lld\\n\",x)\nusing namespace std;\nll powmod(ll base,ll exponent,ll mod){\n\tll ans=1;\n\tif(base<0) base+=mod;\n\twhile(exponent){\n\t\tif(exponent&1)ans=(ans*base)%mod;\n\t\tbase=(base*base)%mod;\n\t\texponent/=2;\n\t}\n\treturn ans;\n}\nll gcd(ll a, ll b){\n\tif(b==0) return a;\n\telse return gcd(b,a%b);\n}\nconst int INF = 2e9;\nconst ll INFLL = 4e18;\nconst int small_lim = 1e6+1;\nconst int mod = 1e9+7;\nconst int big_lim = 1e3+1;\nll primes_till_i[small_lim];\nll primes_till_bigger_i[big_lim];\nvl sieved_primes[small_lim];\nvl sieved_primes_big[big_lim];\nvi prime;\nint N,k,d;\nvoid sieve(){\n\tvi lpf(small_lim);\n\tll pw;\n\tfor(int i = 2; i < small_lim; i++){\n\t\tif(! lpf[i]){\n\t\t\tprime.pb(i);\n\t\t\tlpf[i] = i;\n\t\t}\n\t\tfor(int j : prime){\n\t\t\tif((j > lpf[i]) || (j*i >= small_lim)) break;\n\t\t\tlpf[j*i] = j;\n\t\t}\n\t}\n\tfor(int i = 2; i < small_lim; i++){\n\t\tprimes_till_i[i] = primes_till_i[i-1] + (lpf[i] == i);\n\t}\n}\nll count_primes(ll n, int ind){\n\tif(ind < 0) return n-1;\n\tif(1ll*prime[ind]*prime[ind] > n){\n\t\tif(n < small_lim) return primes_till_i[n];\n\t\tif(primes_till_bigger_i[N/n]) return primes_till_bigger_i[N/n];\n\t\tint l = -1, r = ind;\n\t\twhile(r-l > 1){\n\t\t\tint mid = (l+r)>>1;\n\t\t\tif(1ll*prime[mid]*prime[mid] > n) r = mid;\n\t\t\telse l = mid;\n\t\t}\n\t\treturn primes_till_bigger_i[N/n] = count_primes(n,l);\n\t}\n\tint sz;\n\tif(n < small_lim) sz = sieved_primes[n].size();\n\telse sz = sieved_primes_big[N/n].size();\n\tll ans;\n\tif(sz <= ind){\n\t\tans = count_primes(n,ind-1);\n\t\tans -= count_primes(n/prime[ind],ind-1);\n\t\tans += ind;\n\t\tif(n < small_lim) sieved_primes[n].pb(ans);\n\t\telse sieved_primes_big[N/n].pb(ans);\n\t}\n\tif(n < small_lim) return sieved_primes[n][ind];\n\telse return sieved_primes_big[N/n][ind];\n}\nll count_primes(ll n){\n\tif(n < small_lim) return primes_till_i[n];\n\tif(primes_till_bigger_i[N/n]) return primes_till_bigger_i[N/n];\n\treturn count_primes(n,prime.size()-1);\n}\n \nconst int ncrlim = 3.5e6;\n \nint fact[ncrlim];\nint invfact[ncrlim];\n \nvoid init_fact(){\n\tfact[0] = 1;\n\tfor(int i = 1; i < ncrlim; i++) fact[i] = (1ll*fact[i-1]*i)%mod;\n\tinvfact[ncrlim-1] = powmod(fact[ncrlim-1], mod-2, mod);\n\tfor(int i = ncrlim-1; i > 0; i--) invfact[i-1] = (1ll*invfact[i]*i)%mod;\n}\n \nint ncr(int n, int r){\n\tif(r > n || r < 0) return 0;\n\tint ans = fact[n];\n\tans = (1ll*ans*invfact[n-r]) % mod;\n\tans = (1ll*ans*invfact[r]) % mod;\n\treturn ans;\n}\n \nll calculate_dp(ll n, int ind){\n\tif(n == 0) return 0;\n\tif(prime[ind] > n) return 1;\n\tll ans = 1,temp;\n\tif(1ll*prime[ind]*prime[ind] > n){\n\t\ttemp = ncr(k+d,d);\n\t\ttemp *= count_primes(n)-ind;\n\t\tans+=temp; ans %= mod;\n\t\treturn ans;\n\t}\n\tans = 0;\n\tll gg = 1;\n\tll mult = d;\n\twhile(gg <= n){\n\t\ttemp = calculate_dp(n/gg,ind+1);\n\t\ttemp *= ncr(mult,d);\n\t\tans += temp;\n\t\tans %= mod;\n\t\tmult += k;\n\t\tgg *= prime[ind];\n\t}\n\treturn ans;\n}\nint main(){\n\tsieve();\n\tinit_fact();\n\tint t;\n\tsd(t);\n\twhile(t--){\n\t\tsd(N);sd(k);sd(d);\n\t\tplldn(calculate_dp(N,0));\n\t\tfor(int i = 1; i < big_lim; i++){\n\t\t\tprimes_till_bigger_i[i] = 0;\n\t\t\tsieved_primes_big[i].clear();\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2021",
    "index": "A",
    "title": "Meaning Mean",
    "statement": "Pak Chanek has an array $a$ of $n$ positive integers. Since he is currently learning how to calculate the floored average of two numbers, he wants to practice it on his array $a$.\n\nWhile the array $a$ has at least two elements, Pak Chanek will perform the following three-step operation:\n\n- Pick two different indices $i$ and $j$ ($1 \\leq i, j \\leq |a|$; $i \\neq j$), note that $|a|$ denotes the current size of the array $a$.\n- Append $\\lfloor \\frac{a_i+a_j}{2} \\rfloor$$^{\\text{∗}}$ to the end of the array.\n- Remove elements $a_i$ and $a_j$ from the array and concatenate the remaining parts of the array.\n\nFor example, suppose that $a=[5,4,3,2,1,1]$. If we choose $i=1$ and $j=5$, the resulting array will be $a=[4,3,2,1,3]$. If we choose $i=4$ and $j=3$, the resulting array will be $a=[5,4,1,1,2]$.\n\nAfter all operations, the array will consist of a single element $x$. Find the maximum possible value of $x$ if Pak Chanek performs the operations optimally.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\lfloor x \\rfloor$ denotes the floor function of $x$, which is the greatest integer that is less than or equal to $x$. For example, $\\lfloor 6 \\rfloor = 6$, $\\lfloor 2.5 \\rfloor=2$, $\\lfloor -3.6 \\rfloor=-4$ and $\\lfloor \\pi \\rfloor=3$\n\\end{footnotesize}",
    "tutorial": "For now, let's ignore the floor operation, so an operation is merging two elements $a_i$ and $a_j$ into one element $\\frac{a_i+a_j}{2}$. Consider the end result. Each initial element in $a$ must contribute a fractional coefficient to the final result. It turns out that the sum of the coefficients is fixed (it must be $1$). That means we can greedily give the biggest values in $a$ the biggest coefficients. One way to do this is by sorting $a$ in ascending order. We merge $a_1$ and $a_2$, then merge that result with $a_3$, then merge that result with $a_4$, and so on until $a_n$. If we do this, $a_n$ contributes $\\frac{1}{2}$ times, $a_{n-1}$ contributes $\\frac{1}{4}$ times, $a_{n-2}$ contributes $\\frac{1}{8}$ times, and so on. This is the optimal way to get the maximum final result. It turns out that the strategy above is also the optimal strategy for the original version of the problem. So we can simulate that process to get the answer. Time complexity for each test case: $O(n\\log n)$",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2021",
    "index": "B",
    "title": "Maximize Mex",
    "statement": "You are given an array $a$ of $n$ positive integers and an integer $x$. You can do the following two-step operation any (possibly zero) number of times:\n\n- Choose an index $i$ ($1 \\leq i \\leq n$).\n- Increase $a_i$ by $x$, in other words $a_i := a_i + x$.\n\nFind the maximum value of the $\\operatorname{MEX}$ of $a$ if you perform the operations optimally.\n\nThe $\\operatorname{MEX}$ (minimum excluded value) of an array is the smallest non-negative integer that is not in the array. For example:\n\n- The $\\operatorname{MEX}$ of $[2,2,1]$ is $0$ because $0$ is not in the array.\n- The $\\operatorname{MEX}$ of $[3,1,0,1]$ is $2$ because $0$ and $1$ are in the array but $2$ is not.\n- The $\\operatorname{MEX}$ of $[0,3,1,2]$ is $4$ because $0$, $1$, $2$ and $3$ are in the array but $4$ is not.",
    "tutorial": "For the $\\operatorname{MEX}$ to be at least $k$, then each non-negative integer from $0$ to $k-1$ must appear at least once in the array. First, notice that since there are only $n$ elements in the array, there are at most $n$ different values, so the $\\operatorname{MEX}$ can only be at most $n$. And since we can only increase an element's value, that means every element with values bigger than $n$ can be ignored. We construct a frequency array $\\text{freq}$ such that $\\text{freq}[k]$ is the number of elements in $a$ with value $k$. Notice that the values just need to appear at least once to contribute to the $\\operatorname{MEX}$, so two or more elements with the same value should be split into different values to yield a potentially better result. To find the maximum possible $\\operatorname{MEX}$, we iterate each index $k$ in the array $\\text{freq}$ from $0$ to $n$. In each iteration of $k$, if we find $\\text{freq[k]}>0$, that means it's possible to have the $\\operatorname{MEX}$ be bigger than $k$, so we can iterate $k$ to the next value. Before we iterate to the next value, if we find $\\text{freq}[k]>1$, that indicates duplicates, so we should do an operation to all except one of those values to change them into $k+x$, which increases $\\text{freq}[k+x]$ by $\\text{freq}[k]-1$ and changes $\\text{freq}[k]$ into $1$. In each iteration of $k$, if we find $\\text{freq}[k]=0$, that means, $k$ is the maximum $\\operatorname{MEX}$ we can get, and we should end the process. Time complexity for each test case: $O(n)$",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2021",
    "index": "C2",
    "title": "Adjust The Presentation (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. In the two versions, the constraints on $q$ and the time limit are different. In this version, $0 \\leq q \\leq 2 \\cdot 10^5$. You can make hacks only if all the versions of the problem are solved.}\n\nA team consisting of $n$ members, numbered from $1$ to $n$, is set to present a slide show at a large meeting. The slide show contains $m$ slides.\n\nThere is an array $a$ of length $n$. Initially, the members are standing in a line in the order of $a_1, a_2, \\ldots, a_n$ from front to back. The slide show will be presented in order from slide $1$ to slide $m$. Each section will be presented by the member at the front of the line. After each slide is presented, you can move the member at the front of the line to any position in the lineup (without changing the order of the rest of the members). For example, suppose the line of members is $[\\textcolor{red}{3},1,2,4]$. After member $3$ presents the current slide, you can change the line of members into either $[\\textcolor{red}{3},1,2,4]$, $[1,\\textcolor{red}{3},2,4]$, $[1,2,\\textcolor{red}{3},4]$ or $[1,2,4,\\textcolor{red}{3}]$.\n\nThere is also an array $b$ of length $m$. The slide show is considered good if it is possible to make member $b_i$ present slide $i$ for all $i$ from $1$ to $m$ under these constraints.\n\nHowever, your annoying boss wants to make $q$ updates to the array $b$. In the $i$-th update, he will choose a slide $s_i$ and a member $t_i$ and set $b_{s_i} := t_i$. Note that these updates are \\textbf{persistent}, that is changes made to the array $b$ will apply when processing future updates.\n\nFor each of the $q+1$ states of array $b$, the initial state and after each of the $q$ updates, determine if the slideshow is good.",
    "tutorial": "Firstly, let's relabel the $n$ members such that member number $i$ is the $i$-th member in the initial line configuration in array $a$. We also adjust the values in $b$ (and the future updates) accordingly. For now, let's solve the problem if there are no updates to the array $b$. Consider the first member who presents. Notice that member $1$ must be the first one presenting since he/she is at the very front of the line, which means $b_1=1$ must hold. After this, we insert him/her into any position in the line. However, instead of determining the target position immediately, we make member $1$ a \"pending member\" and we will only determine his/her position later on when we need him/her again. To generalize, we can form an algorithm to check whether achieving $b$ is possible or not. We iterate each element $b_i$ for each $i$ from $1$ to $m$. While iterating, we maintain a set of pending members which is initially empty, and we maintain who is the next member in the line. When iterating a value of $b_i$, there are three cases: If $b_i$ is equal to the next member in the line, then we can make that member present. And then he/she will become a pending member for the next iterations. Else, if $b_i$ is one of the pending members, then we can always set a precise target position when moving that member in the past such that he/she will be at the very front of the line at this very moment. And then, that member will be a pending member again. Else, then it's impossible to make member $b_i$ present at this time. To solve the problem with updates, let's observe some special properties of $b$ if $b$ is valid. Notice that once a member becomes a pending member, he/she will be a pending member forever. And a member $x$ becomes a pending member during the first occurence of value $x$ $b$. Since the order of members becoming pending must follow the order of the members in the line, that means the first occurence for each value $x$ in $b$ must be in chronological order from $1$ to $n$. More formally, let's define $\\text{first}[x]$ as follows: If the value $x$ appears at least once in $b$, then $\\text{first}[x]$ is the smallest index $i$ such that $b_i=x$. If the value $x$ doesn't appear in $b$, then $\\text{first}[x]=m+1$. Then, for $b$ to be valid, it must hold that $\\text{first}[1]\\leq\\text{first}[2]\\leq\\ldots\\leq\\text{first}[n]$. To handle the updates, we must maintain the array $\\text{first}$. In order to do that, for each value $x$ from $1$ to $n$, we maintain a set of indices for every occurence of $x$ in $b$. The value of $\\text{first}$ is just the minimum value in the set, or $m+1$ if the set is empty. An update to an element in $b$ corresponds to two updates among the sets, which corresponds to two updates in array $\\text{first}$. To maintain the status on whether array $\\text{first}$ is non-decreasing or not, we maintain a value $c$ which represents the number of pairs of adjacent indices $(x,x+1)$ (for all $1\\leq x\\leq n-1$) such that $\\text{first}[x]\\leq\\text{first}[x+1]$. The array is non-decreasing if and only if $c=n-1$. For an update to an index $x$ in $\\text{first}$, we only need to check how pairs $(x-1,x)$ and $(x,x+1)$ affect the value of $c$. Time complexity for each test case: $O((n+m+q)\\log (n+m))$",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2021",
    "index": "D",
    "title": "Boss, Thirsty",
    "statement": "Pak Chanek has a friend who runs a drink stall in a canteen. His friend will sell drinks for $n$ days, numbered from day $1$ to day $n$. There are also $m$ types of drinks, numbered from $1$ to $m$.\n\nThe profit gained from selling a drink on a particular day can vary. On day $i$, the projected profit from selling drink of type $j$ is $A_{i, j}$. Note that $A_{i, j}$ can be negative, meaning that selling the drink would actually incur a loss.\n\nPak Chanek wants to help his friend plan the sales over the $n$ days. On day $i$, Pak Chanek must choose to sell \\textbf{at least} one type of drink. Furthermore, the types of drinks sold on a single day must form a subarray. In other words, in each day, Pak Chanek will select $i$ and $j$ such that $1 \\leq i \\leq j \\leq m$. Then all types of drinks between $i$ and $j$ (inclusive) will be sold.\n\nHowever, to ensure that customers from the previous day keep returning, the selection of drink types sold on day $i$ ($i>1$) must meet the following conditions:\n\n- At least one drink type sold on day $i$ must also have been sold on day $i-1$.\n- At least one drink type sold on day $i$ must \\textbf{not} have been sold on day $i-1$.\n\nThe daily profit is the sum of the profits from all drink types sold on that day. The total profit from the sales plan is the sum of the profits over $n$ days. What is the maximum total profit that can be achieved if Pak Chanek plans the sales optimally?",
    "tutorial": "We can see it as a grid of square tiles, consisting of $n$ rows and $m$ columns. Consider a single row. Instead of looking at the $m$ tiles, we can look at the $m+1$ edges between tiles, including the leftmost edge and the rightmost edge. We number the edges from $0$ to $m$ such that tile $j$ ($1\\leq j\\leq m$) is the tile between edge $j-1$ and edge $j$. For a single row $i$, choosing a segment of tiles is equivalent to choosing two different edges $l$ and $r$ ($0\\leq l<r\\leq m$) as the endpoints of the segment, which denotes choosing the tiles from $l+1$ to $r$. For each edge $j$, we can precompute a prefix sum $\\text{pref}[j]=A_{i,1}+A_{i,2}+\\ldots+A_{i,j}$. That means, choosing edges $l$ and $r$ yields a profit of $\\text{pref}[r]-\\text{pref}[l]$. Let's say we've chosen edges $l'$ and $r'$ for row $i-1$ and we want to choose two edges $l$ and $r$ for row $i$ that satisfies the problem requirement. We want to choose a continuous segment that includes at least one chosen tile and at least one unchosen tile from the previous row. A chosen tile that is adjacent to an unchosen tile only appears at the endpoints of the previous segment. That means, to satisfy the requirement, the new segment must strictly contain at least one endpoint of the previous segment. More formally, at least one of the following conditions must be satisfied: $l<l'<r$ $l<r'<r$ Knowing that, we can see that when going from one row to the next, we only need the information for one of the two endpoints, not both. We can solve this with dynamic programming from row $1$ to row $n$. For each row, we find the optimal profit for each $l$ and the optimal profit for each $r$. We do those two things separately. For each row $i$, define the following things: $\\text{dpL}[i][l]$: the optimal profit for the first $i$ rows if the left endpoint of the last segment is $l$. $\\text{dpR}[i][r]$: the optimal profit for the first $i$ rows if the right endpoint of the last segment is $r$. Let's say we've calculated all values of $\\text{dpL}$ and $\\text{dpR}$ for row $i-1$ and we want to calculate for row $i$. Let $l$ and $r$ be the left and right endpoints of the new segment respectively. Let $p$ be one of the endpoints of the previous segment. Then it must hold that $l<p<r$, which yields a maximum profit of $-\\text{pref}[l]+\\max(\\text{dpL}[i-1][p],\\text{dpR}[i-1][p])+\\text{pref}[r]$. Let's calculate all values of $\\text{dpR}$ first for row $i$. For each $r$, we want to consider all corresponding triples $(l,p,r)$ and find the maximum profit among them. In order to do that, we do three steps: Make a prefix maximum of $-\\text{pref}[l]$. Then, for each $p$, we add $\\max(\\text{dpL[i-1][p]},\\text{dpR}[i-1][p])$ with the maximum value of $-\\text{pref}[l]$ for all $0\\leq l<j$. And then we make a prefix maximum of those values. Then, for each $r$, the value of $\\text{dpR}[i][r]$ is $\\text{pref}[r]$ added by the maximum value for the previous calculation for each $p$ from $0$ to $r-1$. We do the same thing for $\\text{dpL}$ but we use suffix maxmiums instead. After doing all that for every row from $1$ to $n$, we find the maximum value of $\\text{dpL}$ and $\\text{dpR}$ in the last row to get the answer. Time complexity of each test case: $O(nm)$",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2021",
    "index": "E3",
    "title": "Digital Village (Extreme Version)",
    "statement": "\\textbf{This is the extreme version of the problem. In the three versions, the constraints on $n$ and $m$ are different. You can make hacks only if all the versions of the problem are solved.}\n\nPak Chanek is setting up internet connections for the village of Khuntien. The village can be represented as a connected simple graph with $n$ houses and $m$ internet cables connecting house $u_i$ and house $v_i$, each with a latency of $w_i$.\n\nThere are $p$ houses that require internet. Pak Chanek can install servers in at most $k$ of the houses. The houses that need internet will then be connected to one of the servers. However, since each cable has its latency, the latency experienced by house $s_i$ requiring internet will be the \\textbf{maximum} latency of the cables between that house and the server it is connected to.\n\nFor each $k = 1,2,\\ldots,n$, help Pak Chanek determine the minimum \\textbf{total} latency that can be achieved for all the houses requiring internet.",
    "tutorial": "Since the cost of a path uses the maximum edge weight in the path, we can use a Kruskal-like algorithm that is similar to finding the MST (Minimum Spanning Tree). Initially, the graph has no edges, and we add each edge one by one starting from the smallest values of $w_i$, while maintaining the connected components in the graph using DSU (Disjoint Set Union). While doing the MST algorithm, we simultaneously construct the reachability tree of the graph, whose structure represents the sequence of mergings of connected components in the algorithm. Each vertex in the reachability tree corresponds to some connected component at some point in time in the algorithm. Each non-leaf vertex in the reachability tree always has two children, which are the two connected components that are merged to form the connected component represented by that vertex, so every time two connected components merge in the algorithm, we make a new vertex in the reachability tree that is connected to its two corresponding children. After doing all that, we've constructed a reachability tree that is a rooted binary tree with $2n-1$ vertices, $n$ of which are leaves. For each non-leaf vertex $x$, we write down $\\text{weight}[x]$ which is the weight of the edge that forms its connected component. For each leaf, we mark it as special if and only if it corresponds to a house that needs internet. Then, for each vertex $x$, we calculate $\\text{cnt}[x]$, which is the number of special leaves in the subtree of $x$. These values will be used later. Consider a non-leaf $x$ in the reachability tree. It can be obtained that two vertices in the original graph corresponding to any two leaves in the subtree of $x$ can have a path between them in the original graph with a weight of at most $\\text{weight}[x]$. Let's solve for some value of $k$. For each special vertex $x$, we want to choose a target vertex $y$ that's an ancestor of $x$. Then, we choose a set of $k$ leaves for the houses with installed servers. We want it such that each chosen target has at least one leaf in its subtree that is a member of the set. The total path cost of this is the sum of $\\text{weight}[y]$ for all chosen targets $y$. Let's say we've fixed the set of $k$ leaves. Then, we mark every ancestor of these leaves. If we only consider the marked vertices with the edges between them, we have a reduced tree. For each special leaf, we want to choose its nearest ancestor that is in the reduced tree for its target to get the one with the smallest weight. Knowing this, we can solve the problem in another point of view. Initially, we have the original reachability tree. We want to reduce it into a reduced tree with $k$ leaves. We want to do it while maintaining the chosen targets of the special leaves and their costs. Initially, for each special leaf, we choose itself as its target. In one operation, we can do the following: Choose a vertex that's currently a leaf. Move every target that's currently in that leaf to its parent. Remove that leaf and the edge connecting it to its parent. We want to do that until the reduced tree has $k$ leaves. For each edge connecting a vertex $x$ to its parent $y$ in the reachability tree, calculate $(\\text{weight}[y]-\\text{weight}[x])\\times\\text{cnt}[x]$. That is the cost to move every target in vertex $x$ to vertex $y$. Define that as the edge's length. We want to do operations with the minimum cost so that the reduced tree has $k$ leaves. We want to minimize the sum of lengths of the deleted edges. If we look at it in a different way, we want to choose edges to be in the reduced tree with the maximum sum of lengths. For some value of $k$, the edges of the reduced tree can be decomposed into $k$ paths from some vertex to its descendant. We want the total sum of lengths of these paths to be as big as possible. But how do we solve it for every $k$ from $1$ to $n$? Let's say $k=1$. We can choose the path from the root to its furthest leaf. How do we solve for $k=2$ onwards? It turns out that we can use the optimal solution for some value of $k$ to make the optimal solution for $k+1$, by just adding the longest possible available path. That means, for each $k$ from $1$ to $n$, we just find the current longest available path and add it to our reduced tree. What if at some point. there are more than one possible longest paths? It can be proven that we can choose any of these paths and the optimal solutions for the next values of $k$ will still be optimal. The proof for this greedy strategy involves the convexity of the total length as $k$ goes from $1$ to $n$. However, we won't explain it in detail here. So to solve the problem, we do DFS in the reachability tree to calculate for each vertex $x$, the furthest leaf and the second furthest leaf in its subtree. For each $k$ from $1$ to $n$, we add the current longest available path using this precalculation. Time complexity: $O(n\\log n+m\\log m)$",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2022",
    "index": "A",
    "title": "Bus to Pénjamo",
    "statement": "\\begin{quote}\nYa vamos llegando a Péeeenjamoo ♫♫♫\n\\end{quote}\n\nThere are $n$ families travelling to Pénjamo to witness Mexico's largest-ever \"walking a chicken on a leash\" marathon. The $i$-th family has $a_i$ family members. All families will travel using a single bus consisting of $r$ rows with $2$ seats each.\n\nA person is considered happy if:\n\n- Another family member is seated in the same row as them, or\n- They are sitting alone in their row (with an empty seat next to them).\n\nDetermine the maximum number of happy people in an optimal seating arrangement. Note that \\textbf{everyone} must be seated in the bus.\n\nIt is guaranteed that all family members will fit on the bus. Formally, it is guaranteed that $\\displaystyle\\sum_{i=1}^{n}a_i \\le 2r$.",
    "tutorial": "The key to maximizing happiness is to seat family members together as much as possible. If two members of the same family sit in the same row, both will be happy, and we only use two seats. However, if they are seated separately, only one person is happy, but two seats are still used. Therefore, we prioritize seating family pairs together first. Once all possible pairs are seated, there may still be some family members left to seat. If a family has an odd number of members, one person will be left without a pair. Ideally, we want to seat this person alone in a row to make them happy. However, if there are no remaining rows to seat them alone, we'll have to seat them with someone from another family. This means the other person might no longer be happy since they are no longer seated alone. The easiest way to handle part 2 is to check the number of remaining rows and people. If the number of remaining rows is greater than or equal to the number of unpaired people, all unpaired people can sit alone and remain happy. Otherwise, some people will have to share a row, and their happiness will be affected. In that case, the number of happy people will be $2 \\times$ remaining rows $-$ remaining people. Write down key observations and mix them to solve the problem",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n,r;\n\t\tcin>>n>>r;\n\t\tvector<int>arr(n);\n\t\tint leftalone=0;\n\t\tint happy=0;\n\t\tfor(int k=0;k<n;k++)\n\t\t{\n\t\t\tcin>>arr[k];\n\t\t\thappy+=(arr[k]/2)*2;\n\t\t\tr-=arr[k]/2;\n\t\t\tleftalone+=arr[k]%2;\n\t\t}\n\t\tif(leftalone>r)\n\t\t\thappy+=r*2-leftalone;\n\t\telse\n\t\t \thappy+=leftalone;\n\t\tcout<<happy<<endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2022",
    "index": "B",
    "title": "Kar Salesman",
    "statement": "Karel is a salesman in a car dealership. The dealership has $n$ different models of cars. There are $a_i$ cars of the $i$-th model. Karel is an excellent salesperson and can convince customers to buy up to $x$ cars (of Karel's choice), as long as the cars are from different models.\n\nDetermine the minimum number of customers Karel has to bring in to sell all the cars.",
    "tutorial": "Since no customer can buy more than one car from the same model, the minimum number of clients we need is determined by the model with the most cars. Therefore, we need at least: $\\max\\{a_1, a_2, \\cdots a_n\\}$ clients, because even if a customer buys cars from other models, they cannot exceed this limit for any single model. Each client can buy up to $x$ cars from different models. To distribute all the cars among the clients, we also need to consider the total number of cars. Thus, the minimum number of clients needed is at least: $\\displaystyle\\left\\lceil \\frac{a_1 + a_2 + \\cdots + a_n}{x}\\right\\rceil$ This ensures that all cars can be distributed across the clients, respecting the limit of $x$ cars per customer. The actual number of clients required is the maximum of the two values: $\\displaystyle\\max\\left\\{\\left\\lceil \\frac{a_1 + a_2 + \\cdots + a_n}{x}\\right\\rceil, \\max\\{a_1, a_2, \\cdots a_n\\}\\right\\}$ This gives us a lower bound for the number of clients required, satisfying both constraints (the maximum cars of a single model and the total number of cars). Apply binary search on the answer. To demonstrate that this is always sufficient, we can reason that the most efficient strategy is to reduce the car count for the models with the largest numbers first. By doing so, we maximize the benefit of allowing each client to buy up to $x$ cars from different models. After distributing the cars, two possible outcomes will arise: All models will have the same number of remaining cars, and this situation will be optimal when the total cars are evenly distributed (matching the $\\displaystyle\\left\\lceil \\frac{a_1 + a_2 + ... + a_n}{x}\\right\\rceil$ bound). All models will have the same number of remaining cars, and this situation will be optimal when the total cars are evenly distributed (matching the $\\displaystyle\\left\\lceil \\frac{a_1 + a_2 + ... + a_n}{x}\\right\\rceil$ bound). There will be still a quantity of models less than or equal to x remaining, which matches the case where the maximum number of cars from a single model $\\max(a_1, a_2, ..., a_n)$ determines the bound. There will be still a quantity of models less than or equal to x remaining, which matches the case where the maximum number of cars from a single model $\\max(a_1, a_2, ..., a_n)$ determines the bound. Imagine a grid of size $w \\times x$, where $w$ represents the minimum number of clients needed: $\\displaystyle w = \\max\\left\\{\\left\\lceil \\frac{a_1 + a_2 + \\cdots + a_n}{x}\\right\\rceil, \\max\\{a_1, a_2, \\cdots a_n\\}\\right\\}$ Now, place the cars in this grid by filling it column by column, from the first model to the $n$-th model. This method ensures that each client will buy cars from different models and no client exceeds the $x$ car limit. Since the total number of cars is less than or equal to the size of the grid, this configuration guarantees that all cars will be sold within $w$ clients. If you don't know how to solve a problem, try to solve for small cases to find a pattern.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tlong long n,x;\n\t\tcin>>n>>x;\n\t\tvector<long long>arr(n);\n\t\tlong long sum=0;\n\t\tlong long maximo=0;\n\t\tfor(int k=0;k<n;k++)\n\t\t{\n\t\t\tcin>>arr[k];\n\t\t\tmaximo=max(maximo,arr[k]);\n\t\t\tsum+=arr[k];\n\t\t}\n\t\tlong long sec=(sum+x-1)/(long long)x;\n\t\tcout<<max(maximo,sec)<<endl;\n\t}\n}",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2022",
    "index": "C",
    "title": "Gerrymandering",
    "statement": "\\begin{quote}\nWe all steal a little bit. But I have only one hand, while my adversaries have two.\n\\hfill Álvaro Obregón\n\\end{quote}\n\nÁlvaro and José are the only candidates running for the presidency of Tepito, a rectangular grid of $2$ rows and $n$ columns, where each cell represents a house. It is guaranteed that $n$ is a multiple of $3$.\n\nUnder the voting system of Tepito, the grid will be split into districts, which consist of any $3$ houses that are connected$^{\\text{∗}}$. Each house will belong to exactly one district.\n\nEach district will cast a single vote. The district will vote for Álvaro or José respectively if at least $2$ houses in that district select them. Therefore, a total of $\\frac{2n}{3}$ votes will be cast.\n\nAs Álvaro is the current president, he knows exactly which candidate each house will select. If Álvaro divides the houses into districts optimally, determine the maximum number of votes he can get.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A set of cells is connected if there is a path between any $2$ cells that requires moving only up, down, left and right through cells in the set.\n\\end{footnotesize}",
    "tutorial": "We will use dynamic programming to keep track of the maximum number of votes Álvaro can secure as we move from column to column (note that there are many ways to implement the DP, we will use the easiest to understand). An important observation is that if you use a horizontal piece in one row, you also have to use it in the other to avoid leaving holes. Let $dp[i][j]$ represent the maximum number of votes Álvaro can get considering up to the $i$-th column. The second dimension $j$ represents the current configuration of filled cells: $j = 0$: All cells up to the $i$-th column are completely filled (including $i$-th). $j = 1$: All cells up to the i-th column are completely filled (including $i$-th), and there's one extra cell filled in the first row of the next column. $j = 2$: The $i$-th column is filled, and there's one extra cell filled in the second row of the next column. For simplicity, we will call \"L\", \"second L\", \"third L\", and \"fourth L\" respectively the next pieces: From $dp[k][0]$ (Both rows filled at column $k$): You can place a horizontal piece in both rows, leading to $dp[k+3][0]$. You can place a first L piece, leading to $dp[k+1][1]$. You can place an L piece, leading to $dp[k+1][2]$. You can place a horizontal piece in both rows, leading to $dp[k+3][0]$. You can place a first L piece, leading to $dp[k+1][1]$. You can place an L piece, leading to $dp[k+1][2]$. From $dp[k][1]$ (One extra cell in the first row of the next column): You can place a horizontal piece in the first row occupying from $k+2$ to $k+4$ and also a horizontal piece in the second row from $k+1$ to $k+3$, leading to $dp[k+3][1]$. You can place a fourth L, leading to $dp[k+2][0]$. You can place a horizontal piece in the first row occupying from $k+2$ to $k+4$ and also a horizontal piece in the second row from $k+1$ to $k+3$, leading to $dp[k+3][1]$. You can place a fourth L, leading to $dp[k+2][0]$. From $dp[k][2]$ (One extra cell in the second row of the next column): You can place a horizontal piece in the first row occupying from $k+1$ to $k+3$ and also a horizontal piece in the second row from $k+2$ to $k+4$, leading to $dp[k+3][2]$. You can place a third L, leading to $dp[k+2][0]$. You can place a horizontal piece in the first row occupying from $k+1$ to $k+3$ and also a horizontal piece in the second row from $k+2$ to $k+4$, leading to $dp[k+3][2]$. You can place a third L, leading to $dp[k+2][0]$. More formally for each DP state, the following transitions are possible: From $dp[k][0]$: $dp[k+3][0] = max(dp[k+3][0], dp[k][0] + \\text{vot})$ $dp[k+1][1] = max(dp[k+1][1], dp[k][0] + \\text{vot})$ $dp[k+1][2] = max(dp[k+1][2], dp[k][0] + \\text{vot})$ From $dp[k][1]$: $dp[k+3][1] = max(dp[k+3][1], dp[k][1] + \\text{vot})$ $dp[k+2][0] = max(dp[k+2][0], dp[k][1] + \\text{vot})$ From $dp[k][2]$: $dp[k+3][2] = max(dp[k+3][2], dp[k][2] + \\text{vot})$ $dp[k+2][0] = max(dp[k+2][0], dp[k][2] + \\text{vot})$ To implement the DP solution, you only need to handle the transitions for states $dp[i][0]$ and $dp[i][1]$. For $dp[i][2]$, the transitions are the same as $dp[i][1]$, with the rows swapped. Don't begin to implement until all the details are very clear, this will make your implementation much easier. Draw images to visualize easier everything.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve()\n{\n    int n;\n    cin>>n;\n    vector<string>cad(n);\n    vector<vector<int> >vot(2,vector<int>(n+8));\n    for(int k=0;k<2;k++)\n    {\n\tcin>>cad[k];\n\tfor(int i=0;i<n;i++)\n\t\tif(cad[k][i]=='A')\n\t\t\tvot[k][i+1]=1;\n    }\n    vector<vector<int> >dp(n+9,vector<int>(3,-1));\n    dp[0][0]=0;\n    for(int k=0;k<=n-1;k++)\n    {\n\tfor(int i=0;i<3;i++)\n\t{\n\t    if(dp[k][i]!=-1)\n\t    {\n\t   \tint vt=0,val=dp[k][i];\n\t  \t    if(i==0)\n\t\t    {\n\t\t\t// *\n\t\t\t// *\n\t\t\tvt=(vot[0][k+1]+vot[0][k+2]+vot[0][k+3])/2+(vot[1][k+1]+vot[1][k+2]+vot[1][k+3])/2;\n\t\t\tdp[k+3][0]=max(vt+val,dp[k+3][0]);\n\t\t\tvt=(vot[1][k+1]+vot[0][k+2]+vot[0][k+1])/2;\n\t\t\tdp[k+1][1]=max(vt+val,dp[k+1][1]);\n\t\t\tvt=(vot[1][k+1]+vot[1][k+2]+vot[0][k+1])/2;\n\t\t\tdp[k+1][2]=max(vt+val,dp[k+1][2]);\n\t\t    }\n\t\t    if(i==1)\n\t\t    {\n\t\t\t// **\n\t\t\t// *\n\t\t\tvt=(vot[0][k+2]+vot[0][k+3]+vot[0][k+4])/2+(vot[1][k+1]+vot[1][k+2]+vot[1][k+3])/2;\n\t\t\tdp[k+3][1]=max(vt+val,dp[k+3][1]);\n\t\t\tvt=(vot[1][k+1]+vot[1][k+2]+vot[0][k+2])/2;\n\t\t\tdp[k+2][0]=max(vt+val,dp[k+2][0]);\n\t   \t    }\n\t\t    if(i==2)\n\t\t    {\n\t\t\t//*\n\t\t\t//**\n\t\t\tvt=(vot[1][k+2]+vot[1][k+3]+vot[1][k+4])/2+(vot[0][k+1]+vot[0][k+2]+vot[0][k+3])/2;\n\t\t\tdp[k+3][2]=max(vt+val,dp[k+3][2]);\n\t\t\tvt=(vot[0][k+1]+vot[0][k+2]+vot[1][k+2])/2;\n\t\t\tdp[k+2][0]=max(vt+val,dp[k+2][0]);\n\t\t    }\n\t    }\n\t}\n    }\n    cout<<dp[n][0]<<endl;\n}\nint main() {\n    int t;\n    cin>>t;\n    while(t--)\n\tsolve();\n}\n",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2022",
    "index": "D1",
    "title": "Asesino (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. In this version, you can ask at most $n+69$ questions. You can make hacks only if both versions of the problem are solved.}\n\nThis is an interactive problem.\n\nIt is a tradition in Mexico's national IOI trainings to play the game \"Asesino\", which is similar to \"Among Us\" or \"Mafia\".\n\nToday, $n$ players, numbered from $1$ to $n$, will play \"Asesino\" with the following three roles:\n\n- \\textbf{Knight}: a Knight is someone who always tells the truth.\n- \\textbf{Knave}: a Knave is someone who always lies.\n- \\textbf{Impostor}: an Impostor is someone everybody thinks is a Knight, but is secretly a Knave.\n\nEach player will be assigned a role in the game. There will be \\textbf{exactly one} Impostor but there can be any (possible zero) number of Knights and Knaves.\n\nAs the game moderator, you have accidentally forgotten the roles of everyone, but you need to determine the player who is the Impostor.\n\nTo determine the Impostor, you will ask some questions. In each question, you will pick two players $i$ and $j$ ($1 \\leq i, j \\leq n$; $i \\neq j$) and ask if player $i$ thinks that player $j$ is a Knight. The results of the question is shown in the table below.\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||c|}\n\\hline\n& Knight & Knave & Impostor \\\n\\hline\n\\hline\nKnight & Yes & No & Yes \\\n\\hline\n\\hline\nKnave & No & Yes & No \\\n\\hline\n\\hline\nImpostor & No & Yes & — \\\n\\hline\n\\end{tabular}\n\n{\\small The response of the cell in row $a$ and column $b$ is the result of asking a question when $i$ has role $a$ and $j$ has row $b$. For example, the \"Yes\" in the top right cell belongs to row \"Knight\" and column \"Impostor\", so it is the response when $i$ is a Knight and $j$ is an Impostor.}\n\\end{center}\n\nFind the Impostor in at most $n + 69$ questions.\n\n\\textbf{Note: the grader is adaptive:} the roles of the players are not fixed in the beginning and may change depending on your questions. However, it is guaranteed that there exists an assignment of roles that is consistent with all previously asked questions under the constraints of this problem.",
    "tutorial": "Try to do casework for small $n$. It is also a good idea to simulate it. Think about this problem as a directed graph, where for each query there is a directed edge. Observe that if you ask $u \\mapsto v$ and $v \\mapsto u$, both answers will match if and only if $u$ and $v$ are not the impostor. This can be easily shown by case work. We can observe that $n = 3$ and $n = 4$ are solvable with $4$ queries. This strategies are illustrated in the image below: There's many solutions that work. Given that 69 is big enough, we can use the previous observation of asking in pairs and reducing the problem recursively. Combining hint 2 with our solutions for $n = 3$ and $n = 4$, we can come up with the following algorithm: While $n > 4$, query $n \\mapsto n - 1$ and $n - 1 \\mapsto n$. If their answers don't match, one of them is the impostor. Query $n \\mapsto n - 2$ and $n - 2 \\mapsto n$. If their answers don't match, $n$ is the impostor. Otherwise, $n - 1$ is the impostor. If the answers match, do $n -= 2$. While $n > 4$, query $n \\mapsto n - 1$ and $n - 1 \\mapsto n$. If their answers don't match, one of them is the impostor. Query $n \\mapsto n - 2$ and $n - 2 \\mapsto n$. If their answers don't match, $n$ is the impostor. Otherwise, $n - 1$ is the impostor. If the answers match, do $n -= 2$. If their answers don't match, one of them is the impostor. Query $n \\mapsto n - 2$ and $n - 2 \\mapsto n$. If their answers don't match, $n$ is the impostor. Otherwise, $n - 1$ is the impostor. If their answers don't match, $n$ is the impostor. Otherwise, $n - 1$ is the impostor. If the answers match, do $n -= 2$. If $n > 4$ doesn't hold and we haven't found the impostor, we either have the $n = 3$ case or the $n = 4$ case, and we can solve either of them in $4$ queries. If $n > 4$ doesn't hold and we haven't found the impostor, we either have the $n = 3$ case or the $n = 4$ case, and we can solve either of them in $4$ queries. In the worst case, this algorithm uses $n + 1$ queries. I'm also aware of a solution with $n + 4$ queries, $n + 2$ queries, and one with $n + \\lceil\\log(n)\\rceil$ queries. We only present this solution to shorten the length of the blog but feel free to ask about the others in the comments.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nbool query(int i, int j, int ans = 0) {\n  cout << \"? \" << i << \" \" << j << endl;\n  cin >> ans;\n  return ans;\n}\n \nint main() {\n  int tt; \n  for (cin >> tt; tt; --tt) {\n    int n, N; cin >> N; n = N;\n    array<int, 2> candidates = {-1, -1};\n \n    while (n > 4) {\n      if (query(n - 1, n) != query(n, n - 1)) {\n        candidates = {n - 1, n}; break;\n      } else n -= 2;\n    }\n \n    if (candidates[0] != -1) {\n      int not_candidate = (candidates[0] == N - 1) ? N - 2 : N;\n \n      if (query(candidates[0], not_candidate) != query(not_candidate, candidates[0])) {\n        cout << \"! \" << candidates[0] << endl;\n      } else cout << \"! \" << candidates[1] << endl;\n \n    } else  {\n \n      if (n == 3) {\n \n        if (query(1, 2) == query(2, 1)) cout << \"! 3\\n\";\n        else {\n          if (query(1, 3) == query(3, 1)) cout << \"! 2\\n\";\n          else cout << \"! 1\\n\";\n        }\n \n      } else {\n \n        if (query(1 , 2) != query(2, 1)) {\n          if (query(1, 3) == query(3, 1)) cout << \"! 2\\n\";\n          else cout << \"! 1\\n\";\n        } else {\n          if (query(1, 3) != query(3, 1)) cout << \"! 3\\n\";\n          else cout << \"! 4\\n\";\n        }\n \n      }\n    }\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "implementation",
      "interactive"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2022",
    "index": "D2",
    "title": "Asesino (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, you must use the minimum number of queries possible. You can make hacks only if both versions of the problem are solved.}\n\nThis is an interactive problem.\n\nIt is a tradition in Mexico's national IOI trainings to play the game \"Asesino\", which is similar to \"Among Us\" or \"Mafia\".\n\nToday, $n$ players, numbered from $1$ to $n$, will play \"Asesino\" with the following three roles:\n\n- \\textbf{Knight}: a Knight is someone who always tells the truth.\n- \\textbf{Knave}: a Knave is someone who always lies.\n- \\textbf{Impostor}: an Impostor is someone everybody thinks is a Knight, but is secretly a Knave.\n\nEach player will be assigned a role in the game. There will be \\textbf{exactly one} Impostor but there can be any (possible zero) number of Knights and Knaves.\n\nAs the game moderator, you have accidentally forgotten the roles of everyone, but you need to determine the player who is the Impostor.\n\nTo determine the Impostor, you will ask some questions. In each question, you will pick two players $i$ and $j$ ($1 \\leq i, j \\leq n$; $i \\neq j$) and ask if player $i$ thinks that player $j$ is a Knight. The results of the question is shown in the table below.\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||c|}\n\\hline\n& Knight & Knave & Impostor \\\n\\hline\n\\hline\nKnight & Yes & No & Yes \\\n\\hline\n\\hline\nKnave & No & Yes & No \\\n\\hline\n\\hline\nImpostor & No & Yes & — \\\n\\hline\n\\end{tabular}\n\n{\\small The response of the cell in row $a$ and column $b$ is the result of asking a question when $i$ has role $a$ and $j$ has row $b$. For example, the \"Yes\" in the top right cell belongs to row \"Knight\" and column \"Impostor\", so it is the response when $i$ is a Knight and $j$ is an Impostor.}\n\\end{center}\n\nFind the Impostor in the minimum number of queries possible. That is, let $f(n)$ be the minimum integer such that for $n$ players, there exists a strategy that can determine the Impostor using at most $f(n)$ questions. Then, you should use at most $f(n)$ questions to determine the Impostor.\n\n\\textbf{Note: the grader is adaptive:} the roles of the players are not fixed in the beginning and may change depending on your questions. However, it is guaranteed that there exists an assignment of roles that is consistent with all previously asked questions under the constraints of this problem.",
    "tutorial": "What is the minimal value anyway? Our solution to D1 used $n$ queries if $n$ is even and $n + 1$ queries when $n$ is odd. Is this the optimal strategy? Can we find a lower bound? Can we find the optimal strategy for small $n$? There's only $9$ possible unlabeled directed graphs with $3$ nodes and at most $3$ edges, you might as well draw them. They are illustrated in the image below for convenience though. Stare at them and convince yourself $4$ queries is the optimal for $n = 3$. We would have to prove that $n - 1 < f(n)$ for all $n$ and $n < f(n)$ for $n$ odd. How could we structure a proof? For $n - 1$ we have some control over the graph. We can show by pigeonhole principle that at least one of them has in-degree $0$, and at least one of them has out-degree $0$. If those two nodes are different, call $A$ the node with in-degree $0$ and $B$ the node with out-degree $0$. Let the grader always reply yes to your queries. $A$ can be the impostor and everyone else Knaves. $B$ can be the impostor and everyone else Knights. If those two nodes are different, call $A$ the node with in-degree $0$ and $B$ the node with out-degree $0$. Let the grader always reply yes to your queries. $A$ can be the impostor and everyone else Knaves. $B$ can be the impostor and everyone else Knights. If those two nodes are the same, then the graph looks like a collection of cycles and one isolated node. The grader will always reply yes except for the last query where it replies no. Let the last query be to player $A$ about player $B$. The two assignments of roles are: $A$ is the impostor and everyone else in the cycle is a Knight. $B$ is the impostor and everyone else in the cycle is a Knave. If those two nodes are the same, then the graph looks like a collection of cycles and one isolated node. The grader will always reply yes except for the last query where it replies no. Let the last query be to player $A$ about player $B$. The two assignments of roles are: $A$ is the impostor and everyone else in the cycle is a Knight. $B$ is the impostor and everyone else in the cycle is a Knave. Note that the structure of our proof is very general and is very easy to simulate for small values of $n$ and small number of queries. Can we extend it to $n$ odd and $n$ queries? Try writing an exhaustive checker and run it for small values. According to our conjecture, $n = 5$ shouldn't solvable with $5$ queries. So we should find a set of answers that for any queries yields two valid assignments with different nodes as the impostor. It doesn't exist! Which means $n = 5$ is solvable with $5$ queries. How? Also, observe that if we find a solution to $n = 5$ we can apply the same idea and recursively solve the problem in $n$ queries for all $n > 3$. Consider the natural directed graph representation, adding a directed edge with weight $0$ between node $i$ and $j$ if the answer to the query ''? i j'' was yes, and a $1$ otherwise. We will also denote this query by $i \\mapsto j$. We will use a lemma, that generalizes the idea for D1. The sum of weights of a cycle is odd if and only if the impostor is among us (among the cycle, I mean). Suppose the impostor is not in the cycle. Then observe that the only time you get an edge with weight $1$ is whenever there are two consecutive nodes with different roles. - Consider consecutive segments of nodes with the same role in this cycle, and compress each of this segments into one node. The image bellow illustrates how, grey edges are queries with answer no. The new graph is bipartite, and thus has an even number of edges. But all the edges in this new graph, are all the grey edges in the original graph, which implies what we want. The new graph is bipartite, and thus has an even number of edges. But all the edges in this new graph, are all the grey edges in the original graph, which implies what we want. If the impostor is in the cycle, there are three ways of inserting it (assume the cycle has more than $2$ nodes that case is exactly what we proved in hint 2). We can insert the impostor into one of this ``segments'' of consecutive nodes with the same role. This would increase the number of grey edges by $1$, changing the parity, We can insert it between two segments. If we have Knight $\\mapsto$ Impostor $\\mapsto$ Knave, the number of grey edges decreases by $1$. If thee is Knave $\\mapsto$ Impostor $\\mapsto$ Knight, the number of grey edges increases by $1$. Either way, we changed the parity of the cycle. $\\blacksquare$ If the impostor is in the cycle, there are three ways of inserting it (assume the cycle has more than $2$ nodes that case is exactly what we proved in hint 2). We can insert the impostor into one of this ``segments'' of consecutive nodes with the same role. This would increase the number of grey edges by $1$, changing the parity, We can insert it between two segments. If we have Knight $\\mapsto$ Impostor $\\mapsto$ Knave, the number of grey edges decreases by $1$. If thee is Knave $\\mapsto$ Impostor $\\mapsto$ Knight, the number of grey edges increases by $1$. Either way, we changed the parity of the cycle. $\\blacksquare$ The algorithm that solves the problem is the following: If $n = 3$, query $1 \\mapsto 2$ and $2 \\mapsto 1$, If queries match, $3$ is the impostor. If queries match, $3$ is the impostor. Else, query $1 \\mapsto 3$ and $3 \\mapsto 1$. If queries match, $2$ is the impostor. Else, $1$ is the impostor. Else, query $1 \\mapsto 3$ and $3 \\mapsto 1$. If queries match, $2$ is the impostor. Else, $1$ is the impostor. Else, Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] While $n > 5$, query $n \\mapsto n - 1$ and $n - 1 \\mapsto n$. If their answers don't match, one of them is the impostor. Query $n \\mapsto n - 2$ and $n - 2 \\mapsto n$. If their answers don't match, $n$ is the impostor. Otherwise, $n - 1$ is the impostor. If the answers match, do Unable to parse markup [type=CF_MATHJAX] . While $n > 5$, query $n \\mapsto n - 1$ and $n - 1 \\mapsto n$. If their answers don't match, one of them is the impostor. Query $n \\mapsto n - 2$ and $n - 2 \\mapsto n$. If their answers don't match, $n$ is the impostor. Otherwise, $n - 1$ is the impostor. If the answers match, do Unable to parse markup [type=CF_MATHJAX] . If their answers don't match, one of them is the impostor. Query $n \\mapsto n - 2$ and $n - 2 \\mapsto n$. If their answers don't match, $n$ is the impostor. Otherwise, $n - 1$ is the impostor. If their answers don't match, $n$ is the impostor. Otherwise, $n - 1$ is the impostor. If the answers match, do Unable to parse markup [type=CF_MATHJAX] . Unable to parse markup [type=CF_MATHJAX] If Unable to parse markup [type=CF_MATHJAX] doesn't hold and we haven't found the impostor, we either have the Unable to parse markup [type=CF_MATHJAX] case or the Unable to parse markup [type=CF_MATHJAX] case, we solve them optimally in Unable to parse markup [type=CF_MATHJAX] or $5$ queries each. If Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] To solve $n = 5$ in $5$ queries, We will form a cycle of size $3$, asking for $1 \\mapsto 2$, $2 \\mapsto 3$ and $3 \\mapsto 2$ (blue edges in the image below). If the cycle has an even number of no's, we know the impostor is among $4$ or $5$. So we ask $3 \\mapsto 4$ and $4 \\mapsto 3$ (green edges). If both queries match, $5$ is the impostor. Else, $4$ is the impostor. If both queries match, $5$ is the impostor. Else, $4$ is the impostor. Else, The impostor is among us (among the cycle, I mean). Ask $1 \\mapsto 3$ and $2 \\mapsto 1$ (purple edges). If $1 \\mapsto 2$ doesn't match with $2 \\mapsto 1$ and $1 \\mapsto 3$ doesn't match with $3 \\mapsto 1$, $1$ is the impostor. If $1 \\mapsto 2$ doesn't match with $2 \\mapsto 1$ and $1 \\mapsto 3$ matches with $3 \\mapsto 1$, $2$ is the impostor. If $1 \\mapsto 2$ matches with $2 \\mapsto 1$ and $1 \\mapsto 3$ doesn't match with $3 \\mapsto 1$, $3$ is the impostor. It is impossible for $1 \\mapsto 2$ to match with $2 \\mapsto 1$ and $1 \\mapsto 3$ to match with $3 \\mapsto 1$, because we know at least one of this cycles will contain the impostor. If $1 \\mapsto 2$ doesn't match with $2 \\mapsto 1$ and $1 \\mapsto 3$ doesn't match with $3 \\mapsto 1$, $1$ is the impostor. If $1 \\mapsto 2$ doesn't match with $2 \\mapsto 1$ and $1 \\mapsto 3$ matches with $3 \\mapsto 1$, $2$ is the impostor. If $1 \\mapsto 2$ matches with $2 \\mapsto 1$ and $1 \\mapsto 3$ doesn't match with $3 \\mapsto 1$, $3$ is the impostor. It is impossible for $1 \\mapsto 2$ to match with $2 \\mapsto 1$ and $1 \\mapsto 3$ to match with $3 \\mapsto 1$, because we know at least one of this cycles will contain the impostor. To solve $n = 4$ in Unable to parse markup [type=CF_MATHJAX] We will query $1 \\mapsto 2$, $2 \\mapsto 1$, $1 \\mapsto 3$ and $3 \\mapsto 1$. If $1 \\mapsto 2$ doesn't match with $2 \\mapsto 1$ and $1 \\mapsto 3$ doesn't match with $3 \\mapsto 1$, $1$ is the impostor. If $1 \\mapsto 2$ doesn't match with $2 \\mapsto 1$ and $1 \\mapsto 3$ matches with $3 \\mapsto 1$, $2$ is the impostor. If $1 \\mapsto 2$ matches with $2 \\mapsto 1$ and $1 \\mapsto 3$ doesn't match with $3 \\mapsto 1$, $3$ is the impostor. If $1 \\mapsto 2$ matches with $2 \\mapsto 1$ and $1 \\mapsto 3$ matches with $3 \\mapsto 1$, then $4$ is the impostor. If $1 \\mapsto 2$ doesn't match with $2 \\mapsto 1$ and $1 \\mapsto 3$ matches with $3 \\mapsto 1$, $2$ is the impostor. If $1 \\mapsto 2$ matches with $2 \\mapsto 1$ and $1 \\mapsto 3$ doesn't match with $3 \\mapsto 1$, $3$ is the impostor. If $1 \\mapsto 2$ matches with $2 \\mapsto 1$ and $1 \\mapsto 3$ matches with $3 \\mapsto 1$, then $4$ is the impostor. We have proven that that $f(n) \\le \\max(4, n)$. Now we will prove that $n \\le f(n)$. We will show it is impossible to solve the problem for any $n$ with only $n - 1$ queries. We will show that the grader always has a strategy of answering queries, such that there exists at least 2 different assignments of roles that are consistent with the answers given, and have different nodes as the impostor. Consider the directed graph generated from the queries. By pigeonhole principle at least one node has in-degree $0$, and at least one node has out-degree $0$. If those two nodes are different, call Unable to parse markup [type=CF_MATHJAX] the node with in-degree Unable to parse markup [type=CF_MATHJAX] and $B$ the node with out-degree $0$. Let the grader always reply yes to your queries. $A$ can be the impostor and everyone else Knaves. $B$ can be the impostor and everyone else Knights. If those two nodes are different, call Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] $A$ can be the impostor and everyone else Knaves. $B$ can be the impostor and everyone else Knights. If those two nodes are the same, then the graph looks like a collection of cycles and one isolated node. The grader will always reply yes except for the last query where it replies no. Let the last query be to player $A$ about player $B$. The two assignments of roles are: $A$ is the impostor and everyone else in the cycle is a Knight. $B$ is the impostor and everyone else in the cycle is a Knave. If those two nodes are the same, then the graph looks like a collection of cycles and one isolated node. The grader will always reply yes except for the last query where it replies no. Let the last query be to player $A$ about player $B$. The two assignments of roles are: $A$ is the impostor and everyone else in the cycle is a Knight. $B$ is the impostor and everyone else in the cycle is a Knave. Thus, we have shown that regardless what the questions asked are, it is impossible to find the impostor among $n$ players, in $n - 1$ queries. $\\blacksquare$ Now, we prove that $f(3) = 4$: Stare at this image: lol, Actually, one of the testers coded the exhaustive checker. I will let them post their code if they want to. In the Olympiad version, the impostor behaved differently. It could either disguise as a Knight while secretly being a Knave, or disguise as a Knave while secretly being a Knight. Turns out the test cases and the interactor in both versions are practically the same. Why would that be? Do small cases! Let the pencil (or the computer) do the work and use your brain to look out for patterns. Do small cases! Let the pencil (or the computer) do the work and use your brain to look out for patterns. Try to find the most natural and simple way of modeling the problem. Try to find the most natural and simple way of modeling the problem. Learn how to code a decision tree, or other models to exhaustively search for constructions, proof patterns, recursive complete search, etc. and build intuition on that to solve the more general cases of the problem. Learn how to code a decision tree, or other models to exhaustively search for constructions, proof patterns, recursive complete search, etc. and build intuition on that to solve the more general cases of the problem.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint n;\n \nvoid answer (int a) {\n\tcout << \"! \" << a << endl;\n} \n \nint query (int a, int b) {\n\tcout << \"? \" << a << \" \" << b << endl;\n\tint r;\n\tcin >> r;\n\tif (r == -1)\n\t\texit(0);\n\treturn r;\n}\n \nvoid main_ () {\n\tcin >> n;\n\t\n\tif (n == -1)\n\t    exit(0);\n\t\n\tif (n == 3) {\n\t    if (query(1, 2) != query(2, 1)) {\n\t        if (query(1, 3) != query(3, 1)) {\n\t            answer(1);\n\t        } else {\n\t            answer(2);\n\t        }\n\t    } else {\n\t        answer(3);\n\t    }\n\t    return;\n\t}\n\t\n\tfor (int i = 1; i + 1 <= n; i += 2) {\n\t\tif (n % 2 == 1 && i == n - 4)\n\t\t\tbreak;\n\t\t\n\t\tif ((n % 2 == 0 && i + 1 == n) || query(i, i + 1) != query(i + 1, i)) {\n\t\t\tint k = 1;\n\t\t\twhile (k == i || k == i + 1)\n\t\t\t\tk++;\n\t\t\t\n\t\t\tif (query(i, k) != query(k, i)) {\n\t\t\t\treturn answer(i);\n\t\t\t} else {\n\t\t\t\treturn answer(i + 1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvector<int> v = {\n\t\tquery(n - 4, n - 3),\n\t\tquery(n - 3, n - 2),\n\t\tquery(n - 2, n - 4)\n\t};\n\t\n\tif ((v[0] + v[1] + v[2]) % 2 == 0) {\n\t\tif (query(n - 3, n - 4) != v[0]) {\n\t\t\tif (query(n - 2, n - 3) != v[1]) {\n\t\t\t\tanswer(n - 3);\n\t\t\t} else {\n\t\t\t\tanswer(n - 4);\n\t\t\t}\n\t\t} else {\n\t\t\tanswer(n - 2);\n\t\t}\n\t} else {\n\t\tif (query(n, 1) != query(1, n)) {\n\t\t\tanswer(n);\n\t\t} else {\n\t\t\tanswer(n - 1);\n\t\t}\n\t}\n}\n \nint main () {\n\t\n\tint t;\n\tcin >> t;\n\t\n\twhile (t--)\n\t\tmain_();\n\t\t\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "interactive"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2022",
    "index": "E1",
    "title": "Billetes MX (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. In this version, it is guaranteed that $q = 0$. You can make hacks only if both versions of the problem are solved.}\n\nAn integer grid $A$ with $p$ rows and $q$ columns is called beautiful if:\n\n- All elements of the grid are integers between $0$ and $2^{30}-1$, and\n- For any subgrid, the XOR of the values at the corners is equal to $0$. Formally, for any four integers $i_1$, $i_2$, $j_1$, $j_2$ ($1 \\le i_1 < i_2 \\le p$; $1 \\le j_1 < j_2 \\le q$), $A_{i_1, j_1} \\oplus A_{i_1, j_2} \\oplus A_{i_2, j_1} \\oplus A_{i_2, j_2} = 0$, where $\\oplus$ denotes the bitwise XOR operation.\n\nThere is a partially filled integer grid $G$ with $n$ rows and $m$ columns where only $k$ cells are filled. Polycarp wants to know how many ways he can assign integers to the unfilled cells so that the grid is beautiful.\n\nHowever, Monocarp thinks that this problem is too easy. Therefore, he will perform $q$ updates on the grid. In each update, he will choose an unfilled cell and assign an integer to it. Note that these updates are \\textbf{persistent}. That is, changes made to the grid will apply when processing future updates.\n\nFor each of the $q + 1$ states of the grid, the initial state and after each of the $q$ queries, determine the number of ways Polycarp can assign integers to the unfilled cells so that the grid is beautiful. Since this number can be very large, you are only required to output their values modulo $10^9+7$.",
    "tutorial": "Consider the extremal cases, what is the answer if the grid is empty? What is the answer if the grid is full? What happens if $N = 2$? Observe that if $N = 2$, the xor of every column is constant. Can we generalize this idea? Imagine you have a valid full grid $a$. For each $i$, change $a[0][i]$ to $a[0][0]\\oplus a[0][i]$. Observe that the grid still satisfies the condition! Using the previous idea we can show that for any valid grid, there must exist two arrays $X$ and $Y$, such that $a[i][j] = X[i] \\oplus Y[j]$. Consider doing the operation described in hint 4 for every row and every column of a full grid that satisfies the condition; That is, for each row, and each column, fix the first element, and change every value in that row or column by their xor with the first element. We will be left with a grid whose first row and first column are all zeros. But this grid also satisfies the condition! So it must hold that $a[i][j] \\oplus a[i][0] \\oplus a[0][j] \\oplus a[0][0] = 0$, but 3 of this values are zero! We can conclude that $a[i][j]$ must also be zero. This shows that there must exist two arrays $X$ and $Y$, such that $a[i][j] = X[i] \\oplus Y[j]$, for any valid full grid. Think of each tile of the grid that we know of, as imposing a condition between two elements of arrays $X$ and $Y$. For each tile added, we lose one degree of freedom right? We could make a bunch of substitutions to determine new values of the grid. How can we best model the problem now? Think about it as a graph where the nodes are rows and columns, and there is an edge between row $i$ and column $j$ with weight $a[i][j]$. Substitutions are now just paths on the graph. If we have a path between the node that represents row $i$ and column $j$, the xor of the weights in this path represents the value of $a[i][j]$. What happens if there's more than one path, and two paths have different values? To continue hint 7, we can deduce that if there is a cycle with xor of weights distinct to $0$ in this graph, there would be a contradiction, and arrays $X$ and $Y$ can't exist. How can we check if this is the case? Do a dfs on this graph, maintaining an array $p$, such that $p[u]$ is the xor of all edges in the path you took from the root, to node $u$. Whenever you encounter a back edge between nodes $u$ and $v$ with weight $w$, check if $p[u] \\oplus p[v] = w$. So lets assume there is no contradiction, ie, all cycles have xor 0. What would be the answer to the problem? We know that if the graph is connected, there exists a path between any two tiles and all the values of the tiles would be determined. So, in how many ways can we make a graph connected? Say there are $K$ connected components. We can connect them all using $K - 1$ edges. For each edge, there are $2^{30}$ possible values they can have. Thus, the number of ways of making the graph connected is $\\left(2^{30} \\right)^{K - 1}$. Why is this the answer to the problem? This is just the solution. Please read the hints in order to understand why it works and how to derive it. Precompute an array $c$, with $c[i] = 2^{30\\cdot i} \\pmod{10^9 + 7}$. Let $a$ be the 2d array with known values of the grid. Consider the graph formed by adding an edge between node $i$ and node $j + n$ and weight $a[i][j]$ for every known tile $(i, j)$ in the grid. Iterate from $1$ to $n + m$ maintaining an array $p$ initialized in $-1$s. If the current proceed node hasn't been visited, we run a dfs through it. We will use array $p$ to maintain the running xor for each node during the dfs. If we ever encounter a back edge between nodes $u, v$ and weight $w$, we check if $p[u] \\oplus p[v] = w$. If not, we the answer is zero. If this condition always holds, let $K$ be the number of times you had to run the dfs. $K$ is also the number of connected components in the graph. The answer is $c[K - 1]$. Complexity: $\\mathcal{O}(n + m + k)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint const Mxn = 2e5 + 2;\nlong long int const MOD = 1e9 + 7;\nlong long int precalc[Mxn];\n \nvector<vector<array<int, 2>>> adj;\n \nbool valid = 1;\nint pref[Mxn];\n \nvoid dfs(int node) {\n  for (auto [child, w] : adj[node]) {\n    if (pref[child] == -1) {\n      pref[child] = pref[node]^w;\n      dfs(child);\n    } else {\n      if ((pref[child]^pref[node]) != w) valid = 0;\n    }\n  }\n}\n \nint main() {\n    \n  precalc[0] = 1;\n  for (int i = 1; i < Mxn; i++) {\n    precalc[i] = (precalc[i - 1]<<30)%MOD;\n  }\n \n  int tt;\n  for (cin >> tt; tt; --tt) {\n    int N, M, K, Q;\n    cin >> N >> M >> K >> Q;\n    \n    adj.clear();\n    adj.assign(N + M, vector<array<int, 2>>{});\n \n    int x, y, z;\n    for (int i = 0; i < K; i++) {\n      cin >> x >> y >> z;\n      x--, y--;\n      adj[x].push_back({y + N, z});\n      adj[y + N].push_back({x, z});\n    }\n \n    for (int i = 0; i < N + M; i++) pref[i] = -1;\n    valid = 1;\n    int cnt = 0;\n \n    for (int i = 0; i < N + M; i++) {\n      if (pref[i] != -1) continue;\n      cnt++; pref[i] = 0; dfs(i);\n    }\n \n    if (valid) cout << precalc[cnt - 1] << '\\n';\n    else cout << 0 << '\\n';\n  }\n}",
    "tags": [
      "2-sat",
      "binary search",
      "combinatorics",
      "constructive algorithms",
      "dfs and similar",
      "dsu",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2022",
    "index": "E2",
    "title": "Billetes MX (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, it is guaranteed that $q \\leq 10^5$. You can make hacks only if both versions of the problem are solved.}\n\nAn integer grid $A$ with $p$ rows and $q$ columns is called beautiful if:\n\n- All elements of the grid are integers between $0$ and $2^{30}-1$, and\n- For any subgrid, the XOR of the values at the corners is equal to $0$. Formally, for any four integers $i_1$, $i_2$, $j_1$, $j_2$ ($1 \\le i_1 < i_2 \\le p$; $1 \\le j_1 < j_2 \\le q$), $A_{i_1, j_1} \\oplus A_{i_1, j_2} \\oplus A_{i_2, j_1} \\oplus A_{i_2, j_2} = 0$, where $\\oplus$ denotes the bitwise XOR operation.\n\nThere is a partially filled integer grid $G$ with $n$ rows and $m$ columns where only $k$ cells are filled. Polycarp wants to know how many ways he can assign integers to the unfilled cells so that the grid is beautiful.\n\nHowever, Monocarp thinks that this problem is too easy. Therefore, he will perform $q$ updates on the grid. In each update, he will choose an unfilled cell and assign an integer to it. Note that these updates are \\textbf{persistent}. That is, changes made to the grid will apply when processing future updates.\n\nFor each of the $q + 1$ states of the grid, the initial state and after each of the $q$ queries, determine the number of ways Polycarp can assign integers to the unfilled cells so that the grid is beautiful. Since this number can be very large, you are only required to output their values modulo $10^9+7$.",
    "tutorial": "Please read the solution to E1 beforehand, as well as all the hints. Through the observations in E1, we can reduce the problem to the following: We have a graph, we add edges, and we want to determine after each addition if all its cycles have xor 0, and the number of connected components in the graph. The edges are never removed, so whenever an edge is added that creates a cycle with xor distinct to zero, this cycle will stay in the graph for all following updates. So we can binary search the first addition that creates a cycle with xor distinct to zero, using the same dfs we used in E1. After the first such edge, the answer will always be zero. Now, for all the additions before that, we must determine how many connected components the graph has at each step. But this is easily solvable with Disjoint Set Union. Complexity: $\\mathcal{O}(\\log(q)(n + m + k + q) + \\alpha(n + m)(q + k))$. We will answer the queries online. Remember that if the graph only contains cycles with xor $0$, the xor of a path between a pair of nodes is unique. We'll use this in our advantage. Let $W(u, v)$ be the unique value of the xor of a path between nodes $u$ and $v$. Lets modify a dsu, drop the path compression, and define array $p$, that maintains the following invariant: For every node $u$ in a component with root $r$, $W(u, r)$ equals the xor of $p[x]$ for all ancestors $x$ of $u$ in our dsu (we also consider $u$ an ancestor of itself). Whenever we add an edge between two nodes $u$ and $v$ in two different components with weight $w$, we consider consider the roots $U$ and $V$ of their respective components. Without loss of generality, assume $U$'s component has more elements than $V$'s. We will add an edge with weight $W(u, U) \\oplus W(v, V) \\oplus w$ between $V$ and $U$, and make $U$ the root of our new component. This last step is the small to large optimization, to ensure the height of our trees is logarithmic. With this data structure, we can maintain the number of connected components like in a usual dsu, and whenever an edge $(u, v)$ with weight $w$ is added, and $u$ and $v$ belong to the same component, we can obtain the value of $W(u, v)$ in $\\mathcal{O(\\log(n))}$, and check if it is equal to $w$. This idea is similar to the data structure described here, and is useful in other contexts. Complexity: $\\mathcal{O}(\\log(q + k)(n + m + k + q))$. In our Olympiad, we had $v_i \\le 1$ instead of $v_i \\le 2^{30}$, and we also had a final subtask were tiles could change values. How would you solve this? We have three different solutions for this problem, one of them found during the Olympiad! I'll let the contestant who found it post it if he wants to.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint const Mxn = 2e5 + 2;\nlong long int const MOD = 1e9 + 7;\n \nvector<vector<array<int, 2>>> adj;\nvector<array<int, 3>> Edges;\nlong long int precalc[Mxn];\n \n \nstruct DSU {\n  vector<int> leader;\n  vector<int> sz;\n  int components;\n \n  DSU(int N) {\n    leader.resize(N); iota(leader.begin(), leader.end(), 0);\n    sz.assign(N, 1);\n    components = N;\n  }\n \n  int find(int x) {\n    return (leader[x] == x) ? x : (leader[x] = find(leader[x]));\n  }\n \n  void unite(int x, int y) {\n    x = find(x), y = find(y);\n    if (x == y) return;\n    if (sz[x] < sz[y]) swap(x, y);\n    leader[y] = leader[x]; sz[x] += sz[y];\n    components--;\n  }\n};\n \nbool valid = 1;\nint pref[Mxn];\n \nvoid dfs(int node = 0) {\n  for (auto [child, w] : adj[node]) {\n    if (pref[child] == -1) {\n      pref[child] = pref[node]^w;\n      dfs(child);\n    } else {\n      if ((pref[child]^pref[node]) != w) valid = 0;\n    }\n  }\n}\n \nint main() {\n  precalc[0] = 1;\n  for (int i = 1; i < Mxn; i++) {\n    precalc[i] = (precalc[i - 1]<<30)%MOD;\n  }\n \n  int tt; \n  for (cin >> tt; tt; --tt) {\n \n    int N, M, K, Q;\n    cin >> N >> M >> K >> Q;\n \n    Edges.clear();\n    adj.clear();\n    adj.assign(N + M, vector<array<int, 2>>{});\n \n    DSU dsu(N + M);\n    dsu.components = N + M;\n \n    int x, y, z;\n    for (int i = 0; i < K; i++) {\n      cin >> x >> y >> z;\n      x--, y--;\n      adj[x].push_back({y + N, z});\n      adj[y + N].push_back({x, z});\n      dsu.unite(x, y + N);\n    }\n \n    for (int i = 0; i < Q; i++) {\n      cin >> x >> y >> z;\n      x--, y--;\n      Edges.push_back({x, y + N, z});\n    }\n \n    int firstzero = 0;\n \n    for (int k = 20; k >= 0; k--) {\n      if (firstzero + (1<<k) > Q) continue;\n \n      for (int i = firstzero; i < firstzero + (1<<k); i++) {\n        x = Edges[i][0], y = Edges[i][1], z = Edges[i][2];\n        adj[x].push_back({y, z});\n        adj[y].push_back({x, z});\n      }\n \n      valid = 1;\n      for (int i = 0; i < N + M; i++) pref[i] = -1;\n      for (int i = 0; i < N + M; i++) {\n        if (pref[i] == -1) pref[i] = 0, dfs(i);\n      }\n \n      if (!valid) {\n        for (int i = firstzero + (1<<k) - 1; i >= firstzero; --i) {\n          x = Edges[i][0], y = Edges[i][1];\n          adj[x].pop_back();\n          adj[y].pop_back();\n        }\n      } else {\n        firstzero += (1<<k);\n      }\n    }\n \n    if (firstzero == 0) {\n      valid = 1;\n      for (int i = 0; i < N + M; i++) pref[i] = -1;\n      for (int i = 0; i < N + M; i++) {\n        if (pref[i] == -1) pref[i] = 0, dfs(i);\n      }\n \n      if (!valid) firstzero--;\n    }\n \n    for (int i = 0; i <= Q; i++) {\n      if (i <= firstzero) cout << precalc[dsu.components - 1] << '\\n';\n      else cout << 0 << '\\n';\n      if (i == Q) break;\n      x = Edges[i][0], y = Edges[i][1];\n      dsu.unite(x, y);\n    }\n \n  }\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "data structures",
      "dsu",
      "graphs"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2023",
    "index": "A",
    "title": "Concatenation of Arrays",
    "statement": "You are given $n$ arrays $a_1$, $\\ldots$, $a_n$. The length of each array is two. Thus, $a_i = [a_{i, 1}, a_{i, 2}]$. You need to concatenate the arrays into a single array of length $2n$ such that the number of inversions$^{\\dagger}$ in the resulting array is minimized. Note that you \\textbf{do not need} to count the actual number of inversions.\n\nMore formally, you need to choose a permutation$^{\\ddagger}$ $p$ of length $n$, so that the array $b = [a_{p_1,1}, a_{p_1,2}, a_{p_2, 1}, a_{p_2, 2}, \\ldots, a_{p_n,1}, a_{p_n,2}]$ contains as few inversions as possible.\n\n$^{\\dagger}$The number of inversions in an array $c$ is the number of pairs of indices $i$ and $j$ such that $i < j$ and $c_i > c_j$.\n\n$^{\\ddagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Let's sort the arrays in order of non-decreasing sum of elements. It turns out that it is always optimal to concatenate the arrays in this order. To prove this, let's consider some optimal answer. Note that if in the final order there are two adjacent arrays, such that the sum of the elements of the left array is greater than the sum of the elements of the right array, then we can swap them, and the number of inversions will not increase. Thus, we can bring any optimal answer to ours by swapping adjacent arrays so that the number of inversions does not increase each time. Thus, such an order is truly optimal.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2023",
    "index": "B",
    "title": "Skipping",
    "statement": "It is already the year $3024$, ideas for problems have long run out, and the olympiad now takes place in a modified individual format. The olympiad consists of $n$ problems, numbered from $1$ to $n$. The $i$-th problem has its own score $a_i$ and a certain parameter $b_i$ ($1 \\le b_i \\le n$).\n\nInitially, the testing system gives the participant the \\textbf{first} problem. When the participant is given the $i$-th problem, they have two options:\n\n- They can submit the problem and receive $a_i$ points;\n- They can skip the problem, in which case they will never be able to submit it.\n\nThen, the testing system selects the next problem for the participant from problems with indices $j$, such that:\n\n- If he submitted the $i$-th problem, it looks at problems with indices $j < i$;\n- If he skipped the $i$-th problem, it looks at problems with indices $j \\leq b_i$.\n\nAmong these problems, it selects the problem with the \\textbf{maximum} index that it has \\textbf{not previously given} to the participant (he has neither submitted nor skipped it before). If there is no such problem, then the competition for the participant \\textbf{ends}, and their result is equal to the sum of points for all submitted problems. In particular, if the participant submits the first problem, then the competition for them ends. Note that the participant receives each problem \\textbf{at most once}.\n\nProkhor has prepared thoroughly for the olympiad, and now he can submit any problem. Help him determine the maximum number of points he can achieve.",
    "tutorial": "Notice that it makes no sense for us to skip problems for which $b_i \\leq i$, since we can solve the problem, earn points for it, and the next problem will be chosen from the numbers $j < i$. If we skip it, we do not earn points, and the next problem will be chosen from the same set of problems or even a smaller one. We also note that if we are at problem $i$ and the maximum problem number that has been assigned to us earlier in the competition is $j \\geqslant b_i$, then it makes no sense to skip this problem, because after skipping, we could have reached the next problem from problem $j$ simply by solving problems. Under these conditions, it turns out that all the problems assigned to us, after the competition ends, are on some prefix of the set of problems (i.e., there exists some number $i$ from $1$ to $n$ such that all problems with numbers $j \\leq i$ were received by us, and problems with numbers $j > i$ were not received). This is indeed the case; let $i$ be the maximum problem number that has been assigned to us. After this problem is assigned, we will not skip any more problems, as we have already proven that it is not beneficial, which means we will only solve problems and will solve all problems with numbers $j < i$ that have not been visited before. Instead of trying to maximize the total score for the solved problems, we will aim to minimize the total score for the skipped problems. We will incur a penalty equal to $a_i$ for a skipped problem and $0$ if we solve it. We know that the answer lies on some prefix, so now we want to determine the minimum penalty required to reach each problem. Let's solve the following subproblem. We are given the same problems, and the following two options if we are at problem $i$: Pay a penalty of $0$ and move to problem $i - 1$, if such a problem exists; Pay a penalty of $a_i$ and move to problem $b_i$. Now we are allowed to visit each problem as many times as we want. In this case, we can construct a weighted directed graph of the following form: The graph has $n$ vertices, each vertex $i$ corresponds to problem $i$; For each $i > 1$, there is an edge of weight $0$ from vertex $i$ to vertex $i - 1$; For each $i$, there is an edge of weight $a_i$ from vertex $i$ to vertex $b_i$. Thus, our task reduces to finding the shortest distance from vertex $1$ to each vertex. Recall that the shortest distance guarantees that on the way to vertex $i$, we visited each vertex at most once, which means that if we reached problem $i$ with some penalty, we can solve all problems on the prefix up to $i$ (inclusive), since the points for all skipped problems will be compensated by the penalty. Since we already know that the optimal answer lies on one of the prefixes, we need to know the total points for the problems for each prefix, which can be easily done using prefix sums. After that, from all the values of the difference between the prefix sum and the minimum penalty needed to reach vertex $i$, we will choose the maximum across all prefixes $i$, and this will be the answer. We will find the shortest distance using Dijkstra's algorithm in $O(n \\log n)$. Prefix sums are calculated in $O(n)$. Final asymptotic complexity: $O(n \\log n)$.",
    "tags": [
      "binary search",
      "dp",
      "graphs",
      "shortest paths"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2023",
    "index": "C",
    "title": "C+K+S",
    "statement": "You are given two strongly connected$^{\\dagger}$ directed graphs, each with exactly $n$ vertices, but possibly different numbers of edges. Upon closer inspection, you noticed an important feature — the length of any cycle in these graphs is divisible by $k$.\n\nEach of the $2n$ vertices belongs to exactly one of two types: incoming or outgoing. For each vertex, its type is known to you.\n\nYou need to determine whether it is possible to draw exactly $n$ directed edges between the source graphs such that the following four conditions are met:\n\n- The ends of any added edge lie in different graphs.\n- From each outgoing vertex, exactly one added edge originates.\n- Into each incoming vertex, exactly one added edge enters.\n- In the resulting graph, the length of any cycle is divisible by $k$.\n\n$^{\\dagger}$A strongly connected graph is a graph in which there is a path from every vertex to every other vertex.",
    "tutorial": "Consider a strongly connected graph in which the lengths of all cycles are multiples of $k$. It can be observed that it is always possible to color this graph with $k$ colors in such a way that any edge connects a vertex of color $color$ to a vertex of color $(color + 1) \\mod k$. It turns out that we can add edges to this graph only if they preserve the described color invariant. Let's make some colorings of the original graphs. With fixed colorings, it is quite easy to check whether the required edges can be added. To do this, we will create corresponding counting arrays for each color and each class of vertices, and then we will compare the elements of the arrays according to the criterion mentioned above. However, we could have initially colored the second graph differently, for example, by adding $1$ to the color of each vertex modulo $k$. It is not difficult to verify that all the values of the counting arrays for the second graph would then shift by $1$ in a cycle. Similarly, depending on the coloring, all values could shift cyclically by an arbitrary amount. To solve this problem, we will construct the initial arrays in such a way that, for fixed colorings, they need to be checked for equality. If equality is achieved for some coloring, it means that one array is a cyclic shift of the other. This condition can be checked, for example, using the Knuth-Morris-Pratt algorithm.",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "hashing",
      "implementation",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2023",
    "index": "D",
    "title": "Many Games",
    "statement": "Recently, you received a rare ticket to the only casino in the world where you can actually earn something, and you want to take full advantage of this opportunity.\n\nThe conditions in this casino are as follows:\n\n- There are a total of $n$ games in the casino.\n- You can play each game \\textbf{at most once}.\n- Each game is characterized by two parameters: $p_i$ ($1 \\le p_i \\le 100$) and $w_i$ — the probability of winning the game in percentage and the winnings for a win.\n- If you lose in any game you decide to play, you will receive nothing at all (even for the games you won).\n\nYou need to choose a set of games in advance that you will play in such a way as to maximize the expected value of your winnings.\n\nIn this case, if you choose to play the games with indices $i_1 < i_2 < \\ldots < i_k$, you will win in all of them with a probability of $\\prod\\limits_{j=1}^k \\frac{p_{i_j}}{100}$, and in that case, your winnings will be equal to $\\sum\\limits_{j=1}^k w_{i_j}$.\n\nThat is, the expected value of your winnings will be $\\left(\\prod\\limits_{j=1}^k \\frac{p_{i_j}}{100}\\right) \\cdot \\left(\\sum\\limits_{j=1}^k w_{i_j}\\right)$.\n\nTo avoid going bankrupt, the casino owners have limited the expected value of winnings for each individual game. Thus, for all $i$ ($1 \\le i \\le n$), it holds that $w_i \\cdot p_i \\le 2 \\cdot 10^5$.\n\nYour task is to find the maximum expected value of winnings that can be obtained by choosing some set of games in the casino.",
    "tutorial": "Claim 1: Suppose we took at least one item with $p_i < 100$. Then it is claimed that the sum $w_i$ over all taken elements is $\\le 200\\,000 \\cdot \\frac{100}{99} = C$. To prove this, let's assume the opposite and try to remove any element with $p_i < 100$ from the taken set, denoting $q_i = \\frac{p_i}{100}$. The answer was $(W + w_i) \\cdot Q \\cdot q_i$, but it became $W \\cdot Q$. The answer increased if $w_i \\cdot Q \\cdot q_i < W \\cdot Q \\cdot (1 - q_i)$, that is, $w_i \\cdot q_i < W \\cdot (1 - q_i)$, which is true if $w_i \\cdot pi < W \\cdot (100 - p_i)$. This is true since $w_i \\cdot p_i \\le 200,000$, while $W \\cdot (100 - p_i) > 200\\,000$. Let's isolate all items with $p_i == 100$. If their sum is $> C$, then we know the answer; otherwise, for each weight sum, we will find the maximum probability with which such weight can be obtained using a dynamic programming approach similar to the knapsack problem. To do this quickly, we will reduce the number of considered items. For each $p$, answer will contain some prefix of elements with that $p$, sorted in descending order by $w_i$. If in the optimal answer there are $c_p$ elements with $p_i == p$, then $c_p \\cdot q^{c_p} > (c_p - 1) \\cdot q^{c_p - 1}$; otherwise, the smallest element can definitely be removed. Rewriting the inequality gives us $c_p \\cdot q > c_p - 1$, which means $c_p < \\frac{1}{1-q}$. Thus, among the elements with a given $p$, it is sufficient to keep for consideration the top $\\frac{100}{100-p}$ best items, or about $450$ (i.e., $99 \\cdot \\ln{99}$) items across all $p$. In the end, it is enough to go through the dynamic programming and find the cell with the highest answer. The total running time is $C \\cdot 99 \\cdot \\ln{99}$.",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2023",
    "index": "E",
    "title": "Tree of Life",
    "statement": "In the heart of an ancient kingdom grows the legendary Tree of Life — the only one of its kind and the source of magical power for the entire world. The tree consists of $n$ nodes. Each node of this tree is a magical source, connected to other such sources through magical channels (edges). In total, there are $n-1$ channels in the tree, with the $i$-th channel connecting nodes $v_i$ and $u_i$. Moreover, there exists a unique simple path through the channels between any two nodes in the tree.\n\nHowever, the magical energy flowing through these channels must be balanced; otherwise, the power of the Tree of Life may disrupt the natural order and cause catastrophic consequences. The sages of the kingdom discovered that when two magical channels converge at a single node, a dangerous \"magical resonance vibration\" occurs between them. To protect the Tree of Life and maintain its balance, it is necessary to select several paths and perform special rituals along them. A path is a sequence of distinct nodes $v_1, v_2, \\ldots, v_k$, where each pair of adjacent nodes $v_i$ and $v_{i+1}$ is connected by a channel. When the sages perform a ritual along such a path, the resonance vibration between the channels $(v_i, v_{i+1})$ and $(v_{i+1}, v_{i+2})$ is blocked for each $1 \\leq i \\leq k - 2$.\n\nThe sages' task is to select the minimum number of paths and perform rituals along them to block all resonance vibrations. This means that for every pair of channels emanating from a single node, there must exist \\textbf{at least one} selected path that contains \\textbf{both} of these channels.\n\nHelp the sages find the minimum number of such paths so that the magical balance of the Tree of Life is preserved, and its power continues to nourish the entire world!",
    "tutorial": "This problem has several solutions that are similar to varying degrees. We will describe one of them. We will apply the following greedy approach. We will construct the answer by combining the answers for the subtrees. To do this, we will perform a depth-first traversal, and when exiting a vertex, we return a triplet $(ans, up, bonus)$, where $ans$ is the minimum number of paths needed to cover all pairs of adjacent edges in the subtree (considering the edge upwards), $up$ is the number of edges upwards, and $bonus$ is the number of paths that are connected at some vertex of the subtree but can be separated into two paths upwards without violating the coverage. Then, if we are at vertex $v$ and receive from child $u$ the triplet $(ans_u, up_u, bonus_u)$, we need to increase $up_u$ to at least $deg_v - 1$ (to satisfy the coverage). Next, we will effectively reduce it by $deg_v - 1$, implying that we have satisfied all such pairs. Meanwhile, we will sum $ans_u$ and $bonus_u$, and subtract from $ans$ when connecting. We first increase using $bonus$ ($ans_u += 1, up_u += 2, bonus_u -= 1$), and then simply by adding new paths. After this, we have remaining excess paths ($up$) leading to $v$, which we might be able to combine to reduce the answer. This is represented by the set $U = \\{up_{u_1}, up_{u_2}, \\ldots, up_{u_k}\\}$. If $\\max(U) * 2 \\leq sum(U)$, we can combine all pairs (leaving at most $1$ path upwards) in $U$, adding these paths to $bonus_v$. Otherwise, we increase all $up_{u_i} \\neq \\max(U)$ using $bonus_{u_i}$ until $\\max(U) * 2 \\leq sum(U)$ is satisfied. Finally, we return $up_v = (sum(U) \\mod 2) + deg_v - 1$ if the condition is met, and $up_v = 2 * \\max(U) - sum(U) + deg_v - 1$, while $bonus_v$ and $ans_v$ are the sums that may have changed during the process. Don't forget to account for the paths that merged at $v$. The root needs to be handled separately, as there are no paths upwards there. To prove this solution, one can consider $dp_{v, up}$ - the minimum number of paths needed to cover subtree $v$ if $up$ paths go upwards. It is not hard to notice that the triplet $(ans, up, bonus)$ in the greedy solution describes all optimal states of the dynamic programming. P.S. Strict proofs are left as an exercise for the reader.",
    "tags": [
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2023",
    "index": "F",
    "title": "Hills and Pits",
    "statement": "In a desert city with a hilly landscape, the city hall decided to level the road surface by purchasing a dump truck. The road is divided into $n$ sections, numbered from $1$ to $n$ from left to right. The height of the surface in the $i$-th section is equal to $a_i$. If the height of the $i$-th section is greater than $0$, then the dump truck must take sand from the $i$-th section of the road, and if the height of the $i$-th section is less than $0$, the dump truck must fill the pit in the $i$-th section of the road with sand. It is guaranteed that the initial heights are not equal to $0$.\n\nWhen the dump truck is in the $i$-th section of the road, it can either take away $x$ units of sand, in which case the height of the surface in the $i$-th section will decrease by $x$, or it can fill in $x$ units of sand (provided that it currently has at least $x$ units of sand in its bed), in which case the height of the surface in the $i$-th section of the road will increase by $x$.\n\nThe dump truck can start its journey from any section of the road. Moving to an adjacent section on the left or right takes $1$ minute, and the time for loading and unloading sand can be neglected. The dump truck has an infinite capacity and is initially empty.\n\nYou need to find the minimum time required for the dump truck to level the sand so that the height in each section becomes equal to $0$. Note that after all movements, the dump truck \\textbf{may still have sand left in its bed}. You need to solve this problem \\textbf{independently} for the segments numbered from $l_i$ to $r_i$. Sand outside the segment cannot be used.",
    "tutorial": "To begin, let's solve the problem for a single query, where $l = 1$ and $r = n$. We will introduce an additional constraint - the dump truck must start on the first segment and finish on the last one. We will calculate the prefix sums of the array $a_1, a_2, \\ldots, a_n$, denoted as $p_1, p_2, \\ldots, p_n$. If $p_n < 0$, then the answer is $-1$, as there won't be enough sand to cover all $a_i < 0$; otherwise, an answer exists. Let $x_i$ be the number of times the dump truck travels between segments $i$ and $i+1$ (in either direction). Notice that if $p_i < 0$, then $x_i \\geq 3$. Since the dump truck starts to the left of segment $i+1$, it will have to pass through $x_i$ once. Additionally, since $p_i < 0$, it will have to return to the prefix to balance it out (it won't have enough sand to cover the negative $a_i$). Then it will have to pass through $x_i$ a third time, as the dump truck must finish its journey to the right of segment $i$. The dump truck can travel such that when $p_i < 0$, $x_i = 3$, and when $p_i \\geq 0$, $x_i = 1$. To achieve this, it simply needs to travel from left to right, and if $p_i \\geq 0$, it just returns left while traversing the negative prefix sums, nullifying the negative $a_i$. If it reaches $p_j \\geq 0$, then the entire prefix to the left of it has already been nullified (we maintain this invariant), and it simply returns right to $p_i$. The entire prefix $p_i$ is nullified. With this algorithm, we achieve $x_i = 3$ when $p_i < 0$ and $x_i = 1$ otherwise, which is the optimal answer to the problem. Now, let's remove the constraint on the starting and ending positions of the dump truck. Let the dump truck start at segment $s$ and finish at segment $f$, with $s \\leq f$. Then, if $i < s$, $x_i \\geq 2$, since the dump truck starts and finishes to the right of segment $i$, meaning it needs to reach it and then return right. Similarly, if $i \\geq f$, then $x_i = 2$. For all $s \\leq i < f$, the constraints on $x_i$ described earlier still hold. How can we now achieve optimal $x_i$? Let the dump truck travel from $s$ to $1$, nullifying all $a_i > 0$ and collecting sand, and then travel right to $s$, covering all $a_i < 0$ (here we used the fact that $p_s \\geq 0$, which we will prove later). From $s$ to $f$, the dump truck follows the previously described algorithm for $s = 1$ and $f = n$. Next, it will travel from $f$ to $n$, nullifying $a_i > 0$, and then return to $f$, covering $a_i < 0$. Thus, we have obtained optimal $x_i$. We still need to understand why $p_s \\geq 0$. Suppose this is not the case; then, according to our estimates, $x_s \\geq 3$. But if we increase $s$ by $1$, this estimate will decrease to $x_s \\geq 2$, meaning we have no reason to consider this $s$. If we cannot increase $s$ by $1$, it means that $s = f$. Then for all $i$, we have the estimate $x_i \\geq 2$. But then we can simply traverse all segments from right to left and then from left to right, resulting in all $x_i = 2$. The case $s \\leq f$ has been analyzed. If $s > f$, we simply need to reverse the array $a_i$ and transition to the case $s < f$. Let's try to better understand what we have actually done by removing the constraints on the starting and ending positions of the dump truck. Let's look at the array $x_i$. Initially, it contains $1$ and $3$; we can replace some prefix and suffix with $2$. The answer to the problem is the sum of the resulting array. First, let's understand how to recalculate $1$ and $3$. We will sort the queries by $p_{l-1}$ (assuming $p_0 = 0$). Let's consider the segment $a_l, a_{l+1}, \\ldots, a_r$. Its prefix sums are $p_l - p_{l-1}, p_{l+1} - p_{l-1}, \\ldots, p_r - p_{l-1}$. Notice that as $p_{l-1}$ increases, the values $p_i - p_{l-1}$ will decrease. Therefore, if we consider the queries in increasing order of $p_{l-1}$, initially $x_i = 1$ for any $i$, and then they gradually become $x_i = 3$ (when $p_i$ becomes less than $p_{l-1}$). We need to come up with a structure that can efficiently find the optimal replacement over a segment. We can simply use a Segment Tree, where each node will store $5$ values - the sum over the segment without replacements; the sum over the segment if everything is replaced; the sum over the segment if the prefix is optimally replaced; the sum over the segment if the suffix is optimally replaced; and the sum over the segment if both the prefix and suffix are optimally replaced. It is not difficult to figure out how to combine $2$ segments (this problem is very similar to the well-known problem of finding the maximum subarray of ones in a binary array). To solve the problem, we just need to make replacements of $1$ with $3$ at a point and make a query over the segment in this Segment Tree. This solution needs to be run $2$ times, once for the original array $a_i$ and once for its reversed version. The answer to the query is the minimum of the two obtained results. The complexity of the solution is $O((n + q) \\log(n))$ time and $O(n + q)$ space.",
    "tags": [
      "data structures",
      "greedy",
      "math",
      "matrices"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2024",
    "index": "A",
    "title": "Profitable Interest Rate",
    "statement": "Alice has $a$ coins. She can open a bank deposit called \"Profitable\", but the minimum amount required to open this deposit is $b$ coins.\n\nThere is also a deposit called \"Unprofitable\", which can be opened with \\textbf{any} amount of coins. Alice noticed that if she opens the \"Unprofitable\" deposit with $x$ coins, the minimum amount required to open the \"Profitable\" deposit decreases by $2x$ coins. However, these coins cannot later be deposited into the \"Profitable\" deposit.\n\nHelp Alice determine the maximum number of coins she can deposit into the \"Profitable\" deposit if she first deposits some amount of coins (possibly $0$) into the \"Unprofitable\" deposit. If Alice can never open the \"Profitable\" deposit, output $0$.",
    "tutorial": "Let's say we have deposited $x$ coins into the \"Unprofitable\" deposit, then we can open a \"Profitable\" deposit if $a - x \\geq b - 2x$ is satisfied. Which is equivalent to the inequality: $x \\geq b - a$. Thus, we need to open an \"Unprofitable\" deposit for $\\text{max}(0, b - a)$ coins, and open a \"Profitable\" deposit for the rest of the coins.",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2024",
    "index": "B",
    "title": "Buying Lemonade",
    "statement": "There is a vending machine that sells lemonade. The machine has a total of $n$ slots. You know that initially, the $i$-th slot contains $a_i$ cans of lemonade. There are also $n$ buttons on the machine, each button corresponds to a slot, with exactly one button corresponding to each slot. Unfortunately, the labels on the buttons have worn off, so you \\textbf{do not know} which button corresponds to which slot.\n\nWhen you press the button corresponding to the $i$-th slot, one of two events occurs:\n\n- If there is a can of lemonade in the $i$-th slot, it will drop out and you will take it. At this point, the number of cans in the $i$-th slot decreases by $1$.\n- If there are no cans of lemonade left in the $i$-th slot, nothing will drop out.\n\nAfter pressing, the can drops out so quickly that it is impossible to track from which slot it fell. The contents of the slots are hidden from your view, so you cannot see how many cans are left in each slot. The only thing you know is the initial number of cans in the slots: $a_1, a_2, \\ldots, a_n$.\n\nDetermine the minimum number of button presses needed to guarantee that you receive at least $k$ cans of lemonade.\n\nNote that you can adapt your strategy during the button presses based on whether you received a can or not. It is guaranteed that there are at least $k$ cans of lemonade in total in the machine. In other words, $k \\leq a_1 + a_2 + \\ldots + a_n$.",
    "tutorial": "Let's make a few simple observations about the optimal strategy of actions. First, if after pressing a certain button, no cans have been obtained, there is no point in pressing that button again. Second, among the buttons that have not yet resulted in a failure, it is always advantageous to press the button that has been pressed the least number of times. This can be loosely justified by the fact that the fewer times a button has been pressed, the greater the chance that the next press will be successful, as we have no other information to distinguish these buttons from one another. From this, our strategy clearly emerges: let's sort the array, let $a_1 \\leq a_2 \\leq \\ldots a_n$. In the first action, we will press all buttons $a_1$ times. It is clear that all these presses will yield cans, and in total, we will collect $a_1 \\cdot n$ cans. If $k \\leq a_1 \\cdot n$, no further presses are needed. However, if $k > a_1 \\cdot n$, we need to make at least one more press. Since all buttons are still indistinguishable to us, it may happen that this press will be made on the button corresponding to $a_1$ and will be unsuccessful. Next, we will press all remaining buttons $a_2 - a_1$ times; these presses will also be guaranteed to be successful. After that, again, if $k$ does not exceed the number of cans already collected, we finish; otherwise, we need to make at least one more press, which may hit an empty cell $a_2$. And so on. In total, the answer to the problem will be $k + x$, where $x$ is the smallest number from $0$ to $n-1$ such that the following holds: $\\displaystyle\\sum_{i=0}^{x} (a_{i+1}-a_i) \\cdot (n-i) \\geq k$ (here we consider $a_0 = 0$). $O(n \\log n)$.",
    "tags": [
      "binary search",
      "constructive algorithms",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2025",
    "index": "A",
    "title": "Two Screens",
    "statement": "There are two screens which can display sequences of uppercase Latin letters. Initially, both screens display nothing.\n\nIn one second, you can do one of the following two actions:\n\n- choose a screen and an uppercase Latin letter, and append that letter to \\textbf{the end} of the sequence displayed on that screen;\n- choose a screen and copy the sequence from it to the other screen, \\textbf{overwriting the sequence that was displayed on the other screen}.\n\nYou have to calculate the minimum number of seconds you have to spend so that the first screen displays the sequence $s$, and the second screen displays the sequence $t$.",
    "tutorial": "Whenever we perform the second action (copy from one screen to the other screen), we overwrite what was written on the other screen. It means that we can consider the string on the other screen to be empty before the copying, and that we only need to copy at most once. So, the optimal sequence of operations should look as follows: add some characters to one of the screens, copy them to the other screen, and then finish both strings. We need to copy as many characters as possible. Since after copying, we can only append new characters to the end of the strings on the screens, the string we copy must be a prefix of both of the given strings. So, we need to find the length of the longest common prefix of the given strings. This can be done in linear time if we scan these strings until we find a pair of different characters in the same positions; however, the constraints were low enough so that you could do it slower (like, for example, iterate on the length of the prefix and check that both prefixes of this length are equal). Okay, now let $l$ be the length of the longest common prefix. Using $l+1$ operations, we write $2l$ characters in total; so the number of operations we need will be $|s|+|t|-2l+l+1 = |s|+|t|+1-l$. However, if the longest common prefix is empty, there's no need to copy anything, and we can write both strings in $|s|+|t|$ seconds.",
    "code": "for _ in range(int(input())):\n\ts = input()\n\tt = input()\n\n\tlcp = 0\n\tn = len(s)\n\tm = len(t)\n\tfor i in range(1, min(n, m) + 1):\n\t\tif s[:i] == t[:i]:\n\t\t\tlcp = i\n\tprint(n + m - max(lcp, 1) + 1)",
    "tags": [
      "binary search",
      "greedy",
      "strings",
      "two pointers"
    ],
    "rating": 800
  },
  {
    "contest_id": "2025",
    "index": "B",
    "title": "Binomial Coefficients, Kind Of",
    "statement": "Recently, akshiM met a task that needed binomial coefficients to solve. He wrote a code he usually does that looked like this:\n\n\\begin{verbatim}\nfor (int n = 0; n < N; n++) { // loop over n from 0 to N-1 (inclusive)\nC[n][0] = 1;\nC[n][n] = 1;\nfor (int k = 1; k < n; k++) // loop over k from 1 to n-1 (inclusive)\nC[n][k] = C[n][k - 1] + C[n - 1][k - 1];\n}\n\\end{verbatim}\n\nUnfortunately, he made an error, since the right formula is the following:\n\n\\begin{verbatim}\nC[n][k] = C[n - 1][k] + C[n - 1][k - 1]\n\\end{verbatim}\n\nBut his team member keblidA is interested in values that were produced using the wrong formula. Please help him to calculate these coefficients for $t$ various pairs $(n_i, k_i)$. Note that they should be calculated according to the first (wrong) formula.\n\nSince values $C[n_i][k_i]$ may be too large, print them modulo $10^9 + 7$.",
    "tutorial": "In order to solve the task, just try to generate values and find a pattern. The pattern is easy: $C[n][k] = 2^k$ for all $k \\in [0, n)$. The last step is to calculate $C[n][k]$ fast enough. For example, we can precalculate all powers of two in some array $p$ as $p[k] = 2 \\cdot p[k - 1] \\bmod (10^9 + 7)$ for all $k < 10^5$ and print the necessary values when asked. Proof: $C[n][k] = C[n][k - 1] + C[n - 1][k - 1] =$ $= C[n][k - 2] + 2 \\cdot C[n - 1][k - 2] + C[n - 2][k - 2] =$ $= C[n][k - 3] + 3 \\cdot C[n - 1][k - 3] + 3 \\cdot C[n - 2][k - 3] + C[n - 3][k - 3] =$ $= \\sum_{i = 0}^{j}{\\binom{j}{i} \\cdot C[n - i][k - j]} = \\sum_{i = 0}^{k}{\\binom{k}{i} \\cdot C[n - i][0]} = \\sum_{i = 0}^{k}{\\binom{k}{i}} = 2^k$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int MOD = int(1e9) + 7;\n\nint main() {\n\tint t; cin >> t;\n\tvector<int> ks(t);\n\tfor (int _ = 0; _ < 2; _++)\n\t\tfor (int i = 0; i < t; i++)\n\t\t\tcin >> ks[i];\n\t\n\tvector<int> ans(1 + *max_element(ks.begin(), ks.end()), 1);\n\tfor (int i = 1; i < (int)ans.size(); i++)\n\t\tans[i] = (2LL * ans[i - 1]) % MOD;\n\t\n\tfor (int k : ks)\n\t\tcout << ans[k] << '\\n';\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2025",
    "index": "C",
    "title": "New Game",
    "statement": "There's a new game Monocarp wants to play. The game uses a deck of $n$ cards, where the $i$-th card has exactly one integer $a_i$ written on it.\n\nAt the beginning of the game, on the first turn, Monocarp can take any card from the deck. During each subsequent turn, Monocarp can take exactly one card that has either the same number as on the card taken on the previous turn or a number that is one greater than the number on the card taken on the previous turn.\n\nIn other words, if on the previous turn Monocarp took a card with the number $x$, then on the current turn he can take either a card with the number $x$ or a card with the number $x + 1$. Monocarp can take any card which meets that condition, regardless of its position in the deck.\n\nAfter Monocarp takes a card on the current turn, it is removed from the deck.\n\nAccording to the rules of the game, the number of distinct numbers written on the cards that Monocarp has taken must not exceed $k$.\n\nIf, after a turn, Monocarp cannot take a card without violating the described rules, the game ends.\n\nYour task is to determine the maximum number of cards that Monocarp can take from the deck during the game, given that on the first turn he can take any card from the deck.",
    "tutorial": "Let's fix the value of the first selected card $x$. Then it is optimal to take the cards as follows: take all cards with the number $x$, then all cards with the number $x + 1$, ..., all cards with the number $x + k - 1$. If any of the intermediate numbers are not present in the deck, we stop immediately. Let's sort the array $a$. Then the answer can be found as follows. Start at some position $i$ and move to the right from it as long as the following conditions are met: the difference between the next number and the current one does not exceed $1$ (otherwise, some number between them occurs $0$ times) and the difference between the next number and $a_i$ is strictly less than $k$ (otherwise, we will take more than $k$ different numbers). It is easy to notice that as $i$ increases, the position we reach through this process also increases. Therefore, we can use two pointers to solve the problem. We will maintain a pointer to this position and update the answer at each $i$ with the distance between $i$ and the pointer. Overall complexity: $O(n \\log n)$ for each test case.",
    "code": "for _ in range(int(input())):\n\tn, k = map(int, input().split())\n\ta = list(map(int, input().split()))\n\ta.sort()\n\tans = 0\n\tj = 0\n\tfor i in range(n):\n\t\tj = max(i, j)\n\t\twhile j + 1 < n and a[j + 1] - a[j] <= 1 and a[j + 1] - a[i] < k:\n\t\t\tj += 1\n\t\tans = max(ans, j - i + 1)\n\tprint(ans)",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2025",
    "index": "D",
    "title": "Attribute Checks",
    "statement": "Imagine a game where you play as a character that has two attributes: \"Strength\" and \"Intelligence\", that are at zero level initially.\n\nDuring the game, you'll acquire $m$ attribute points that allow you to increase your attribute levels — one point will increase one of the attributes by one level. But sometimes, you'll encounter a so-called \"Attribute Checks\": if your corresponding attribute is high enough, you'll pass it; otherwise, you'll fail it.\n\nSpending some time, you finally prepared a list which contains records of all points you got and all checks you've met. And now you're wondering: what is the maximum number of attribute checks you can pass in a single run if you'd spend points wisely?\n\nNote that you can't change the order of records.",
    "tutorial": "For the start, let's introduce a slow but correct solution. Let $d[i][I]$ be the answer to the task if we processed first $i$ records and the current Intelligence level is $I$. If we know Intelligence level $I$, then we also know the current Strength level $S = P - I$, where $P$ is just a total number of points in first $i$ records. Since we want to use dp, let's discuss transitions: If the last record $r_i = 0$, then it was a point, and there are only two options: we either raised Intelligence, so the last state was $d[i - 1][I - 1]$; or raised Strength, coming from state $d[i - 1][I]$. In other words, we can calculate $d[i][I] = \\max(d[i - 1][I - 1], d[i - 1][I])$. we either raised Intelligence, so the last state was $d[i - 1][I - 1]$; or raised Strength, coming from state $d[i - 1][I]$. If the last record $r_i > 0$, then it's an Intelligence check, and it doesn't affect the state, only its answer. For all $I \\ge r_i$, $d[i][I] = d[i - 1][I] + 1$; otherwise, it's $d[i][I] = d[i - 1][I]$. If $r_i < 0$, then it's a Strength check and affects the values in a similar way. For all $I \\le P + r_i$, $d[i][I] = d[i - 1][I] + 1$; otherwise, it's also $d[i][I] = d[i - 1][I]$. OK, we've got a solution with $O(nm)$ time and memory, but we can speed it up. Note that the first case appears only $O(m)$ times, while the second and third cases are just range additions. So, if we can do addition in $O(1)$, then processing the first case in linear time is enough to achieve $O(m^2 + n)$ complexity. How to process range additions in $O(1)$ time? Let's use some difference array $a$ to do it lazily. Instead of adding some value $v$ to the segment $[l, r]$, we'll only add value $v$ to $a[l]$ and $-v$ to $a[r + 1]$. And when we meet $r_i = 0$, we'll \"push\" all accumulated operations all at once. The total value you need to add to some position $i$ is $\\sum_{j=0}^{i}{a[i]}$. So, we can calculate all of them in $O(m)$ just going from left to right, maintaining the prefix sum. The last question is reducing the space complexity. As usual, you can store only the last two layers: for the current layer $i$ and previous layer $i - 1$. But actually, you can store only one layer and update it in-place. Let's store only one last layer of dp as $d[I]$. Attribute checks don't change array $d$ at all. In case $r_i = 0$, you, firstly, push all data from $a$ to $d$, and then you need to recalc values in $d$. But since the formula is $d[I] = \\max(d[I], d[I - 1])$, you can just iterate over $I$ in descending order and everything works! In total, we have a solution with $O(m^2 + n)$ time and $O(m)$ space complexity.",
    "code": "n, m = map(int, input().split())\nrs = map(int, input().split())\n\nd = [-int(1e9)] * (m + 1)\nd[0] = 0\nadd = [0] * (m + 2)\ndef addSegment(l, r):\n    if l <= r:\n        add[l] += 1\n        add[r + 1] -= 1\n\ndef pushAll():\n    sum = 0\n    for i in range(m + 1):\n        sum += add[i]\n        d[i] += sum\n    for i in range(m + 2):\n        add[i] = 0\n\ncntPoints = 0\nfor r in rs:\n    if r == 0:\n        pushAll()\n        for i in range(m, 0, -1):\n            d[i] = max(d[i], d[i - 1])\n        cntPoints += 1\n    else:\n        lf, rg = 0, 0\n        if (r > 0):\n            lf = min(r, m + 1)\n            rg = m\n        else:\n            lf = 0\n            rg = max(-1, cntPoints + r)\n        addSegment(lf, rg)\npushAll()\nprint(max(d))",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2025",
    "index": "E",
    "title": "Card Game",
    "statement": "In the most popular card game in Berland, a deck of $n \\times m$ cards is used. Each card has two parameters: suit and rank. Suits in the game are numbered from $1$ to $n$, and ranks are numbered from $1$ to $m$. There is exactly one card in the deck for each combination of suit and rank.\n\nA card with suit $a$ and rank $b$ can beat a card with suit $c$ and rank $d$ in one of two cases:\n\n- $a = 1$, $c \\ne 1$ (a card of suit $1$ can beat a card of any other suit);\n- $a = c$, $b > d$ (a card can beat any other card of the same suit but of a lower rank).\n\nTwo players play the game. Before the game starts, they receive exactly half of the deck each. The first player wins if for every card of the second player, he can choose his card that can beat it, and there is no card that is chosen twice (i. e. there exists a matching of the first player's cards with the second player's cards such that in each pair the first player's card beats the second player's card). Otherwise, the second player wins.\n\nYour task is to calculate the number of ways to distribute the cards so that the first player wins. Two ways are considered different if there exists a card such that in one way it belongs to the first player and in the other way it belongs to the second player. The number of ways can be very large, so print it modulo $998244353$.",
    "tutorial": "Suppose we're solving the problem for one suit. Consider a distribution of cards between two players; how to check if at least one matching between cards of the first player and cards of the second player exists? Let's order the cards from the highest rank to the lowest rank and go through them in that order. If we get a card of the first player, we can add it to the \"pool\" of cards to be matched; if we get a card belonging to the second player, we match it with one of the cards from the \"pool\" (if there are none - there is no valid matching). So, if there exists a prefix of this order where the number of cards of the second player exceeds the number of cards belonging to the first player, it is not a valid distribution. Does this sound familiar? Let's say that a card belonging to the first player is represented by an opening bracket, and a card belonging to the second player is represented by a closing bracket. Then, if we need to solve the problem for just one suit, the distribution must be a regular bracket sequence. So, in this case, we just need to count the number of regular bracket sequences. However, if there are at least $2$ suits, there might be \"extra\" cards of the $1$-st suit belonging to the first player, which we can match with \"extra\" cards of other suits belonging to the second player. To resolve this issue, we can use the following dynamic programming: let $dp_{i,j}$ be the number of ways to distribute the cards of the first $i$ suits so that there are $j$ extra cards of the $1$-st suit belonging to the $1$-st player. To calculate $dp_{1,j}$, we have to count the number of bracket sequences such that the balance on each prefix is at least $0$, and the balance of the whole sequence is exactly $j$. In my opinion, the easiest way to do this is to run another dynamic programming (something like \"$w_{x,y}$ is the number of sequences with $x$ elements and balance $y$\"); however, you can try solving it in a combinatorial way similar to how Catalan numbers are calculated. What about transitions from $dp_{i,j}$ to $dp_{i+1, j'}$? Let's iterate on $k$ - the number of \"extra\" cards we will use to match the cards of the $(i+1)$-th suit belonging to the second player, so we transition from $dp_{i,j}$ to $dp_{i+1,j-k}$. Now we need to count the ways to distribute $m$ cards of the same suit so that the second player receives $k$ cards more than the first player, and all cards of the first player can be matched. Consider that we ordered the cards from the lowest rank to the highest rank. Then, on every prefix, the number of cards belonging to the first player should not exceed the number of cards belonging to the second player (otherwise we won't be able to match all cards belonging to the first player), and in total, the number of cards belonging to the second player should be greater by $k$. So this is exactly the number of bracket sequences with balance $\\ge 0$ on every prefix and balance equal to $k$ in total (and we have already calculated that)! So, the solution consists of two steps. First, for every $k \\in [0, m]$, we calculate the number of bracket sequences with non-negative balance on each prefix and total balance equal to $k$; then we run dynamic programming of the form \"$dp_{i,j}$ is the number of ways to distribute the cards of the first $i$ suits so that there are $j$ extra cards of the $1$-st suit belonging to the $1$-st player\". The most time-consuming part of the solution is this dynamic programming, and it works in $O(nm^2)$, so the whole solution works in $O(nm^2)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\n \nint add(int x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n  return x;\n}\n \nint mul(int x, int y) {\n  return x * 1LL * y % MOD;\n}\n \nint main() {\n  int n, m;\n  cin >> n >> m;\n  vector<vector<int>> ways(m + 1, vector<int>(m + 1));\n  ways[0][0] = 1;\n  for (int i = 0; i < m; ++i) {\n    for (int j = 0; j <= i; ++j) {\n      ways[i + 1][j + 1] = add(ways[i + 1][j + 1], ways[i][j]);\n      if (j) ways[i + 1][j - 1] = add(ways[i + 1][j - 1], ways[i][j]);\n    }\n  }\n  \n  vector<vector<int>> dp(n + 1, vector<int>(m + 1));\n  dp[0][0] = 1;\n  for (int i = 0; i < n; ++i) {\n    for (int j = 0; j <= m; ++j) {\n      for (int k = 0; k <= m; ++k) {\n        int nj = i ? j - k : j + k;\n        if (0 <= nj && nj <= m) {\n          dp[i + 1][nj] = add(dp[i + 1][nj], mul(dp[i][j], ways[m][k]));\n        }\n      }\n    }\n  }\n  cout << dp[n][0] << '\\n';\n}",
    "tags": [
      "combinatorics",
      "dp",
      "fft",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2025",
    "index": "F",
    "title": "Choose Your Queries",
    "statement": "You are given an array $a$, consisting of $n$ integers (numbered from $1$ to $n$). Initially, they are all zeroes.\n\nYou have to process $q$ queries. The $i$-th query consists of two different integers $x_i$ and $y_i$. During the $i$-th query, you have to choose an integer $p$ (which is either $x_i$ or $y_i$) and an integer $d$ (which is either $1$ or $-1$), and assign $a_p = a_p + d$.\n\nAfter each query, every element of $a$ should be a non-negative integer.\n\nProcess all queries in such a way that the sum of all elements of $a$ after the last query is the minimum possible.",
    "tutorial": "We will use the classical method for solving maximization/minimization problems: we will come up with an estimate for the answer and try to achieve it constructively. The first idea. Since we have $n$ objects connected by binary relations, we can model the problem as a graph. Let the $n$ elements of the array be the vertices, and the $q$ queries be the edges. For each query, we would like to choose the direction of the edge (let the edge be directed towards the vertex to which the operation is applied) and the sign of the operation. It would be great if, in each connected component, we could choose an equal number of pluses and minuses so that the sum equals zero. Or, if the number of edges in the component is odd, to make the sum equal to one. Obviously, it is not possible to do less than this. It turns out that this is always possible. There is a well-known graph problem: to split the edges of an undirected connected graph into pairs with at least one common endpoint. We will reduce our problem to this one. If we split the graph into pairs, we will construct the answer from them as follows: we will direct the edges of each pair towards any common vertex, write + on the edge with the smaller number (query index), and write - on the edge with the larger number. This construction guarantees that each pair will not add anything to the sum, and each element will be non-negative after each query. The problem of splitting into pair can be solved using the following algorithm. We will perform a DFS from any vertex and construct a DFS tree. Now we will divide the edges into pairs in the order from the leaves to the root. Let us stand at some vertex $v$. First, run the algorithm recursively for the children of $v$. When we finish processing the children, we will consider the following edges from the current vertex $v$: tree edges to the children, the edge to the parent, and back edges with the lower endpoint at $v$. Now, we form as many pairs as possible from the edges to the children and the back edges. We will remove all such edges from the graph. If their total number was odd, then one edge remains unpaired. Form a pair from it and the edge to the parent, and again remove them from the graph. It turns out that when we exit the recursive call, either there will be no edges left in the subtree at all, or there will be one tree edge that will be processed by the parent later. If the number of edges in the component is odd, then at the end, one edge without a pair will remain at the root. I would also like to mention the following implementation details. In the adjacency list, it is better to store the indices of the queries rather than the vertices, and then derive the vertex numbers from them. This will allow for careful handling of multiple edges. Removing edges from the graph directly is also not very convenient. The most convenient way to work around this, in my opinion, is to maintain an array that marks that the edge with such a query number is now removed. Alternatively, for back edges, we can check whether $v$ is the upper or lower endpoint, as well as return a flag from the depth-first search indicating \"is the edge to the child removed\". Overall complexity: $O(n + q)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 300043;\n \nstring choice = \"xy\";\nstring sign = \"+-\";\n \nint qs[N][2];\nstring ans[N];\nint n, q;\nvector<int> g[N];\nint color[N];\n \nvoid pair_queries(int q1, int q2)\n{\n \tif(q1 > q2) swap(q1, q2);\n \tfor(int i = 0; i < 2; i++)\n \t\tfor(int j = 0; j < 2; j++)\n \t\t\tif(qs[q1][i] == qs[q2][j])\n \t\t\t{\n \t\t\t \tans[q1] = { choice[i], sign[0] };\n \t\t\t \tans[q2] = { choice[j], sign[1] };\n \t\t\t \treturn;\n \t\t\t}\n}\n \nbool dfs(int v, int pe = -1)\n{\n \t// return true if parent edge still exists\n \tcolor[v] = 1;\n \tvector<int> edge_nums;\n \tfor(auto e : g[v])\n \t{\n \t\tint u = v ^ qs[e][0] ^ qs[e][1];\n \t\tif(color[u] == 1) continue;\n \t\tif(color[u] == 0)\n \t\t{\n \t\t\tif(dfs(u, e))\n \t\t\t\tedge_nums.push_back(e);\n \t\t}\n \t\telse\n \t\t\tedge_nums.push_back(e);\n \t}\n \tbool res = true;\n \tif(edge_nums.size() % 2 != 0)\n \t{\n \t\tif(pe != -1) edge_nums.push_back(pe);\n \t\telse edge_nums.pop_back();\n \t\tres = false;\n \t}\n \tfor(int i = 0; i < edge_nums.size(); i += 2)\n \t\tpair_queries(edge_nums[i], edge_nums[i + 1]);\n \tcolor[v] = 2;\n \treturn res;\n}\n \nint main()\n{\n\tios_base::sync_with_stdio(0);\n\tcin.tie(0);\n\tcin >> n >> q;\n\tfor(int i = 0; i < q; i++)\n\t{\n\t \tcin >> qs[i][0] >> qs[i][1];\n\t \t--qs[i][0];\n\t \t--qs[i][1];\n\t \tg[qs[i][0]].push_back(i);\n\t \tg[qs[i][1]].push_back(i);\n\t \tans[i] = \"x+\";\n\t}\n\tfor(int i = 0; i < n; i++)\n\t\tif(color[i] == 0)\n\t\t\tdfs(i);\n\tfor(int i = 0; i < q; i++) cout << ans[i] << endl;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2025",
    "index": "G",
    "title": "Variable Damage",
    "statement": "Monocarp is gathering an army to fight a dragon in a videogame.\n\nThe army consists of two parts: the heroes and the defensive artifacts. Each hero has one parameter — his health. Each defensive artifact also has one parameter — its durability.\n\nBefore the battle begins, Monocarp distributes artifacts to the heroes so that each hero receives at most one artifact.\n\nThe battle consists of rounds that proceed as follows:\n\n- first, the dragon deals damage equal to $\\frac{1}{a + b}$ (\\textbf{a real number without rounding}) to each hero, where $a$ is the number of heroes alive and $b$ is the number of active artifacts;\n- after that, all heroes with health $0$ or less die;\n- finally, some artifacts are deactivated. An artifact with durability $x$ is deactivated when one of the following occurs: the hero holding the artifact either dies or receives $x$ total damage (from the start of the battle). If an artifact is not held by any hero, it is inactive from the beginning of the battle.\n\nThe battle ends when there are no heroes left alive.\n\nInitially, the army is empty. There are $q$ queries: add a hero with health $x$ or an artifact with durability $y$ to the army. After each query, determine the maximum number of rounds that Monocarp can survive if he distributes the artifacts optimally.",
    "tutorial": "Let's start unraveling the solution from the end. Suppose we currently have $n$ heroes with health $a_1, a_2, \\dots, a_n$ and $m$ artifacts with durability $b_1, b_2, \\dots, b_m$. Let's assume we have already distributed the artifacts to the heroes, forming pairs $(a_i, b_i)$. If $m > n$, we will discard the excess artifacts with the lowest durability. If $m < n$, we will add the artifacts with durability $0$ (that will deactivate at the start). How many rounds will the battle last? Notice the following: a hero with health $a$ and an artifact with durability $b$ can be replaced with two heroes with health $a$ and $\\min(a, b)$, respectively, and the answer will not change. Thus, it is sufficient to analyze the case when there are no artifacts, and there are only heroes with health $a_1, \\min(a_1, b_1), a_2, \\min(a_2, b_2), \\dots, a_n, \\min(a_n, b_n)$. The idea is as follows: in each round, the heroes take exactly $1$ point of damage in total. Therefore, the battle will last $\\displaystyle \\sum_{i=1}^n a_i + \\sum_{i=1}^n \\min(a_i, b_i)$ rounds. The first sum is easy to maintain -let's focus on the second one. Next, we need to learn how to distribute the artifacts in such a way that maximizes this sum. Intuitively, it seems that the healthiest heroes should receive the most durable artifacts. That is, we should sort the heroes in descending order of health and the artifacts in descending order of durability. We will show that this is indeed the case. Suppose there are two heroes with health $a_1$ and $a_2$ ($a_1 \\ge a_2$). They receive artifacts with durability $b_1$ and $b_2$ ($b_1 \\ge b_2$). We will show that it is optimal to give the first artifact to the first hero and the second one to the second hero. If there is at least one artifact with durability not greater than $a_2$ (that is, the minimum will always be equal to this artifact), it is always optimal to give it to the second hero and the other artifact to the first hero. If there is at least one artifact with durability not less than $a_1$ (that is, the minimum will always be equal to the hero), it is always optimal to give it to the first hero. Otherwise, the durabilities of the artifacts lie between the health values of the heroes, meaning that the minimum for the first hero will always be equal to his artifact, and the minimum for the second hero will be his health. Therefore, it is again optimal to give the larger artifact to the first hero. It follows that if for a pair of heroes the condition that the larger hero has the larger artifact is not met, we can swap their artifacts, and the answer will not decrease. Thus, the task is as follows. After each query, we need to maintain a sorted sequence of heroes, artifacts, and the sum $\\min(a_i, b_i)$. This sounds quite complicated because there are a lot of changes with each query. Some suffix of one of the arrays shifts one position to the right after inserting a new element, affecting many terms. Let's consider an idea of a sweep line instead. We will combine the heroes and artifacts into one array and sort it in descending order. For simplicity, let's assume all durability and health values are distinct integers. Then we will iterate over this array while maintaining the number of heroes who have not yet received an artifact and the number of artifacts that have not been assigned to a hero. If we encounter an artifact and there are previously encountered heroes who have not received an artifact, we will give this artifact to any of them. Since all these heroes have health greater than the durability of this artifact, the minimum will always be equal to the durability of the artifact. Thus, the sum will increase by the durability of the artifact. Otherwise, we will remember that there is one more free artifact. The same goes for a hero. If we encounter a hero and there are previously encountered artifacts that have not been assigned to a hero, we will give any of these artifacts to the hero. The sum will then increase by the hero's health. It can be shown that this process of assigning artifacts yields the same result as sorting. Note that at any moment of time, there are either no free heroes or no free artifacts. Thus, it is sufficient to maintain a \"balance\" -the difference between the number of heroes and artifacts on the prefix. If the balance is positive, and we encounter an artifact, we add its durability to the answer. If the balance is negative, and we encounter a hero, we add his health to the answer. Note that equal elements do not break this algorithm. For simplicity, I suggest sorting not just the values but pairs of values and query indices to maintain a strict order. How does this reduction help? It turns out that it is now possible to use square root decomposition to solve the problem. Read all queries in advance and sort them by the value $(v_i, i)$ in descending order. We will divide all queries into blocks of size $B$. Initially, all queries are deactivated. When processing the next query in the input order, we will activate it within the block and recalculate the entire block. What should we store for each block? Notice that all balance checks for the terms depend on two values: the balance at the start of the block and the balance before this term within the block. Therefore, for the block, we can maintain the following values: the total balance in the block, as well as the total contribution of the terms from this block for each balance at the start of the block. Obviously, the balance at the start of the block can range from $-q$ to $q$. However, if the absolute value of the balance exceeds $B$, the contribution of the block will be the same as if this balance was limited by $-B$ or $B$, respectively (since within the block it will either always be positive or always negative). Thus, it is sufficient to calculate the answer only for balances from $-B$ to $B$. Knowing these values for each block, the answer can be calculated in $O(\\frac{q}{B})$. We will go through the blocks while maintaining the current balance. We will add the block's contribution for the current balance to the answer and add the total balance of the block to the current balance. We still need to learn how to quickly recalculate the answers for all balances within the block. We will iterate over the elements within the block while maintaining the current balance inside the block. Let the balance be $k$. Then if the current element is an artifact, its durability will be added to the sum if the balance at the start of the block is at least $-k + 1$. Similarly, if the current element is a hero, his health will be added if the balance at the start of the block is at most $-k - 1$. Thus, we need to add a value over some range of balances-either from $-k + 1$ to $B$, or from $-B$ to $-k - 1$. This can be done using a difference array. That is, we can make two updates in $O(1)$ for each element of the block, and then compute the prefix sum once in $O(B)$. Therefore, for each query, we can update the structure in $O(B)$, and recalculate the sum in $O(\\frac{q}{B})$. Hence, it is optimal to choose $B = \\sqrt{q}$. Overall complexity: $O(q \\sqrt{q})$.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nstruct query{\n\tint t, v;\n};\n \nint main() {\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tint m;\n\tcin >> m;\n\tvector<query> q(m);\n\tforn(i, m) cin >> q[i].t >> q[i].v;\n\t\n\tvector<pair<int, int>> xs;\n\tforn(i, m) xs.push_back({q[i].v, i});\n\tsort(xs.rbegin(), xs.rend());\n\tforn(i, m) q[i].v = xs.rend() - lower_bound(xs.rbegin(), xs.rend(), make_pair(q[i].v, i)) - 1;\n\t\n\tconst int p = sqrt(m + 10);\n\tconst int siz = (m + p - 1) / p;\n\t\n\tvector<int> tp(m);\n\tvector<int> val(m);\n\tvector<vector<long long>> dp(p, vector<long long>(2 * siz + 1));\n\tvector<int> blbal(p);\n\t\n\tauto upd = [&](const query &q){\n\t\ttp[q.v] = q.t;\n\t\tval[q.v] = xs[q.v].first;\n\t\tblbal[q.v / siz] += q.t == 1 ? 1 : -1;\n\t};\n\t\n\tauto recalc = [&](int b){\n\t\tdp[b].assign(2 * siz + 1, 0);\n\t\tint bal = 0;\n\t\tfor (int i = b * siz; i < m && i < (b + 1) * siz; ++i){\n\t\t\tif (tp[i] == 1){\n\t\t\t\tdp[b][0] += val[i];\n\t\t\t\tdp[b][0] += val[i];\n\t\t\t\tdp[b][-bal + siz] -= val[i];\n\t\t\t\t++bal;\n\t\t\t}\n\t\t\telse if (tp[i] == 2){\n\t\t\t\tdp[b][-bal + 1 + siz] += val[i];\n\t\t\t\t--bal;\n\t\t\t}\n\t\t}\n\t\tforn(i, 2 * siz){\n\t\t\tdp[b][i + 1] += dp[b][i];\n\t\t}\n\t};\n\t\n\tauto get = [&](int b, int bal){\n\t\tbal += siz;\n\t\tif (bal < 0) return dp[b][0];\n\t\tif (bal >= 2 * siz + 1) return dp[b].back();\n\t\treturn dp[b][bal];\n\t};\n\t\n\tfor (auto it : q){\n\t\tupd(it);\n\t\trecalc(it.v / siz);\n\t\tint bal = 0;\n\t\tlong long ans = 0;\n\t\tfor (int i = 0; i * siz < m; ++i){\n\t\t\tans += get(i, bal);\n\t\t\tbal += blbal[i];\n\t\t}\n\t\tcout << ans << '\\n';\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "flows"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2026",
    "index": "A",
    "title": "Perpendicular Segments",
    "statement": "You are given a coordinate plane and three integers $X$, $Y$, and $K$. Find two line segments $AB$ and $CD$ such that\n\n- the coordinates of points $A$, $B$, $C$, and $D$ are integers;\n- $0 \\le A_x, B_x, C_x, D_x \\le X$ and $0 \\le A_y, B_y, C_y, D_y \\le Y$;\n- the length of segment $AB$ is at least $K$;\n- the length of segment $CD$ is at least $K$;\n- segments $AB$ and $CD$ are perpendicular: if you draw lines that contain $AB$ and $CD$, they will cross at a right angle.\n\nNote that it's \\textbf{not} necessary for segments to intersect. Segments are perpendicular as long as the lines they induce are perpendicular.",
    "tutorial": "Let's look at all segments with a fixed angle between them and the X-axis. Let's take the shortest one with integer coordinates and length at least $K$ as $AB$. Let's say that a bounding box of $AB$ has width $w$ and height $h$. It's easy to see that a bounding box of segment $CD$ will have width at least $h$ and height at least $w$, since the shortest segment $CD$ will be just the segment $AB$ rotated at ninety degrees. So, in order to fit both segments $AB$ and $CD$, both $h$ and $w$ should be at most $M = \\min(X, Y)$. But if both $w \\le M$ and $h \\le M$, then what is the longest segment that can fit in such a bounding box? The answer is to set $h = w = M$, then the length $|AB| \\le M \\sqrt{2}$. In such a way, we found out that $K$ must not exceed $M \\sqrt{2}$, but if $K \\le M \\sqrt{2}$, then we can always take the following two segments: $(0, 0) - (M, M)$ and $(0, M) - (M, 0)$ where $M = \\min(X, Y)$. They are perpendicular, fit in the allowed rectangle, and have length exactly $M \\sqrt{2}$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint main() {\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tint X, Y, K;\n\t\tcin >> X >> Y >> K;\n\t\tint M = min(X, Y);\n\t\tcout << \"0 0 \" << M << \" \" << M << endl;\n\t\tcout << \"0 \" << M << \" \" << M << \" 0\" << endl;\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2026",
    "index": "B",
    "title": "Black Cells",
    "statement": "You are given a strip divided into cells, numbered from left to right from $0$ to $10^{18}$. Initially, all cells are white.\n\nYou can perform the following operation: choose two \\textbf{white} cells $i$ and $j$, such that $i \\ne j$ and $|i - j| \\le k$, and paint them black.\n\nA list $a$ is given. All cells from this list must be painted black. Additionally, \\textbf{at most one} cell that is not in this list can also be painted black. Your task is to determine the minimum value of $k$ for which this is possible.",
    "tutorial": "First, let's consider the case when $n$ is even. It is not difficult to notice that to minimize the value of $k$, the cells have to be painted in the following pairs: $(a_1, a_2)$, $(a_3, a_4)$, ..., $(a_{n-1}, a_n)$. Then the answer is equal to the maximum of the distances between the cells in the pairs. For odd $n$, it is necessary to add one more cell (so that cells can be divided into pairs). If we add a new cell from the segment $(a_i, a_{i+1})$, it's paired either with the $i$-th cell or with the $(i+1)$-th cell (depending on the parity of $i$). Therefore, to minimize the value of $k$, the new cell should be chosen among $(a_i+1)$ and $(a_{i+1}-1)$ (in fact, only one of the two options is needed, but we can keep both). Note that one of these options may already be an existing cell, in which case it does not need to be considered. Thus, there are $O(n)$ options for the new cell, and for each of them, we can calculate the answer in $O(n)$ or $O(n\\log{n})$, and take the minimum among them. Thus, we obtained a solution in $O(n^2)$ (or $O(n^2\\log{n})$ depending on the implementation). There is also a faster solution in $O(n)$, but it was not required for this problem.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<long long> a(n);\n    for (auto& x : a) cin >> x;\n    \n    long long ans = 1e18;\n    \n    auto upd = [&](vector<long long> a) {\n      sort(a.begin(), a.end());\n      for (int i = 1; i < (int)a.size(); ++i)\n        if (a[i - 1] == a[i]) return;\n      long long res = 0;\n      for (int i = 0; i < (int)a.size(); i += 2)\n        res = max(res, a[i + 1] - a[i]);\n      ans = min(ans, res);\n    };\n    \n    if (n % 2 == 0) {\n      upd(a);\n      cout << ans << '\\n';\n      continue;\n    }\n    \n    for (int i = 0; i < n; ++i) {\n      for (int x : {-1, 1}) {\n        a.push_back(a[i] + x);\n        upd(a);\n        a.pop_back();\n      }\n    }\n    \n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2026",
    "index": "C",
    "title": "Action Figures",
    "statement": "There is a shop that sells action figures near Monocarp's house. A new set of action figures will be released shortly; this set contains $n$ figures, the $i$-th figure costs $i$ coins and is available for purchase from day $i$ to day $n$.\n\nFor each of the $n$ days, Monocarp knows whether he can visit the shop.\n\nEvery time Monocarp visits the shop, he can buy any number of action figures which are sold in the shop (of course, he cannot buy an action figure that is not yet available for purchase). If Monocarp buys \\textbf{at least two} figures during the same day, he gets a discount equal to the cost of \\textbf{the most expensive} figure he buys (in other words, he gets the most expensive of the figures he buys for free).\n\nMonocarp wants to buy \\textbf{exactly} one $1$-st figure, one $2$-nd figure, ..., one $n$-th figure from the set. He cannot buy the same figure twice. What is the minimum amount of money he has to spend?",
    "tutorial": "Consider the following solution: we iterate on the number of figures we get for free (let this number be $k$), and for each value of $k$, we try to check if it is possible to get $k$ figures for free, and if it is, find the best figures which we get for free. For a fixed value of $k$, it is optimal to visit the shop exactly $k$ times: if we visit the shop more than $k$ times, then during some visits, we buy only one figure - instead of that, we can buy figures from these visits during the last day, so there are no visits during which we buy only one figure. It is quite obvious that if we want to visit the shop $k$ times, we always can do it during the last $k$ days with $s_i=1$. Let the last $k$ days with $s_i=1$ be $x_1, x_2, \\dots, x_k$ (from right to left, so $x_1 > x_2 > \\dots > x_k$). It is impossible to get a total discount of more than $(x_1 + x_2 + \\dots + x_k)$ if we visit the shop only $k$ times, since when we visit the shop on day $i$, the maximum discount we can get during that day is $i$. Now suppose we can't get the figures $\\{x_1, x_2, \\dots, x_k\\}$ for free, but we can get some other set of figures $\\{y_1, y_2, \\dots, y_k\\}$ ($y_1 > y_2 > \\dots > y_k$) for free. Let's show that this is impossible. Consider the first $j$ such that $x_j \\ne y_j$: if $y_j > x_j$, it means that on some suffix of days (from day $y_j$ to day $n$), we visit the shop $j$ times. But since $x_1, x_2, \\dots, x_{j-1}, x_j$ are the last $j$ days when we visit the shop, then we can't visit the shop $j$ times from day $y_j$ to day $n$, so this is impossible; otherwise, if $y_j < x_j$, it means that during the day $x_j$, we get some figure $f$ for free, but it is not $x_j$. Let's get the figure $x_j$ for free during that day instead (swap the figures $f$ and $x_j$). Using a finite number of such transformations, we can show that we can get the figures $\\{x_1, x_2, \\dots, x_k\\}$ for free. Now, for a fixed value of $k$, we know which figures we should get for free. And if we increase the value of $k$, our total discount increases as well. Let's find the greatest possible $k$ with binary search, and we will get a solution working in $O(n \\log n)$. The only thing that's left is checking that some value of $k$ is achievable. To do it, we can mark the $k$ figures we try to get for free, and simulate the process, iterating the figures from left to right. If on some prefix, the number of figures we want to get for free is greater than the number of figures we pay for, then it is impossible, since we can't find a \"match\" for every figure we want to get for free.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 400043;\nchar buf[N];\n \nbool can(const string& s, int k)\n{\n    int n = s.size();\n    vector<int> used(n);\n    for(int i = n - 1; i >= 0; i--)\n        if(k > 0 && s[i] == '1')\n        {\n            used[i] = 1;\n            k--;\n        }\n    int cur = 0;\n    for(int i = 0; i < n; i++)\n        if(used[i])\n        {\n            cur--;\n            if(cur < 0) return false;\n        }\n        else cur++;\n    return true;\n}   \n \nvoid solve()\n{\n    int n;\n    scanf(\"%d\", &n);\n    scanf(\"%s\", buf);                         \n    if(n == 1)\n    {\n        puts(\"1\");\n        return;\n    }\n    string s = buf;\n    int count_1 = 0;\n    for(auto x : s) if (x == '1') count_1++;\n    int l = 1;\n    int r = count_1 + 1;\n    while(r - l > 1)\n    {\n        int mid = (l + r) / 2;\n        if(can(s, mid))\n            l = mid;\n        else\n            r = mid;\n    }\n    long long ans = 0;\n    for(int i = n - 1; i >= 0; i--)\n        if(s[i] == '1' && l > 0)\n            l--;\n        else\n            ans += (i + 1);\n    printf(\"%lld\\n\", ans);\n}\n \nint main()\n{\n    int t;\n    scanf(\"%d\", &t);\n    for(int i = 0; i < t; i++)\n        solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2026",
    "index": "D",
    "title": "Sums of Segments",
    "statement": "You are given a sequence of integers $[a_1, a_2, \\dots, a_n]$. Let $s(l,r)$ be the sum of elements from $a_l$ to $a_r$ (i. e. $s(l,r) = \\sum\\limits_{i=l}^{r} a_i$).\n\nLet's construct another sequence $b$ of size $\\frac{n(n+1)}{2}$ as follows: $b = [s(1,1), s(1,2), \\dots, s(1,n), s(2,2), s(2,3), \\dots, s(2,n), s(3,3), \\dots, s(n,n)]$.\n\nFor example, if $a = [1, 2, 5, 10]$, then $b = [1, 3, 8, 18, 2, 7, 17, 5, 15, 10]$.\n\nYou are given $q$ queries. During the $i$-th query, you are given two integers $l_i$ and $r_i$, and you have to calculate $\\sum \\limits_{j=l_i}^{r_i} b_j$.",
    "tutorial": "In the editorial, we will treat all elements as $0$-indexed. The array $b$ consists of $n$ \"blocks\", the first block has the elements $[s(0,0), s(0,1), \\dots, s(0,n-1)]$, the second block contains $[s(1,1), s(1,2), \\dots, s(1,n-1)]$, and so on. Each position of element in $b$ can be converted into a pair of the form \"index of the block, index of element in the block\" using either a formula or binary search. Let's analyze a query of the form \"get the sum from the $i_1$-th element in the $j_1$-th block to the $i_2$-th element in the $j_2$-th block\". Let's initialize the result with the sum of all blocks from $j_1$ to $j_2$ (inclusive), then drop some first elements from the block $j_1$, and then drop some last elements from the block $j_2$. We have to be able to calculate the following values: given an index of the block $b$ and the indices of elements $l$ and $r$ from this block, calculate the sum from the $l$-th element to the $r$-th element in that block; given two indices of blocks $l$ and $r$, calculate the sum from block $l$ to block $r$. In the first case, we need to calculate $s(b,l+b) + s(b,l+b+1) + \\dots + s(b,r+b)$. Let $p_i$ be the sum of the first $i$ elements from the given array. The sum can be rewritten as $(p_{l+b+1} - p_b) + (p_{l+b+2} - p_b) + \\dots + (p_{r+b+1}-p_b)$. This is equal to $\\sum\\limits_{i=l+b+1}^{r+b+1} p_i - (r-l+1) \\cdot p_l$; the first value can be calculated in $O(1)$ by building prefix sums over the array $p$. The easiest way to calculate the sum over several blocks is the following one: for each block, calculate the sum in it the same way as we calculate the sum over part of the block; build prefix sums over sums in blocks. Depending on the implementation, the resulting complexity will be either $O(n)$ or $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\n \nint n;\n \nvector<long long> a;\nvector<long long> pa;\nvector<long long> ppa;\nvector<long long> start;\nvector<long long> block;\nvector<long long> pblock;\n \nvector<long long> prefix_sums(vector<long long> v)\n{\n \tint k = v.size();\n \tvector<long long> res(k + 1);\n \tfor(int i = 0; i < k; i++) res[i + 1] = res[i] + v[i];\n \treturn res;\n}\n \nlong long get_partial(int l, int r1, int r2)\n{\n\t// s(l, r1) + s(l, r1 + 1) + ... + s(l, r2 - 1)\n \tif(r2 <= r1) return 0ll;\n \tint cnt = r2 - r1;\n \tlong long rem = pa[l] * cnt;\n \tlong long add = ppa[r2 + 1] - ppa[r1 + 1];\n \treturn add - rem;\n}\n \npair<int, int> convert(long long i)\n{\n\tint idx = upper_bound(start.begin(), start.end(), i) - start.begin() - 1;\n\tpair<int, int> res = {idx, i - start[idx] + idx};\n\treturn res; \t\n}\n \nlong long query(long long l, long long r)\n{\n\tpair<int, int> lf = convert(l);\n\tpair<int, int> rg = convert(r);\n\tlong long res = pblock[rg.first + 1] - pblock[lf.first];\n\tif(lf.second != lf.first) res -= get_partial(lf.first, lf.first, lf.second);\n\tif(rg.second != n - 1) res -= get_partial(rg.first, rg.second + 1, n);\n\treturn res;\t\n}\n \nint main()\n{\n\tscanf(\"%d\", &n);\n\ta.resize(n);\n\tfor(int i = 0; i < n; i++) scanf(\"%lld\", &a[i]);\n\tpa = prefix_sums(a);\n\tppa = prefix_sums(pa);\n\tstart = {0};\n\tfor(int i = n; i >= 1; i--)\n\t\tstart.push_back(start.back() + i);\n\tblock.resize(n);\n\tfor(int i = 0; i < n; i++)\n\t\tblock[i] = get_partial(i, i, n);\n\tpblock = prefix_sums(block);\n\tint q;\n\tscanf(\"%d\", &q);\n\tfor(int i = 0; i < q; i++)\n\t{\n\t \tlong long l, r;\n\t \tscanf(\"%lld %lld\", &l, &r);\n\t \tprintf(\"%lld\\n\", query(l - 1, r - 1));\n\t}\n \n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2026",
    "index": "E",
    "title": "Best Subsequence",
    "statement": "Given an integer array $a$ of size $n$.\n\nLet's define the value of the array as its size minus the number of set bits in the bitwise OR of all elements of the array.\n\nFor example, for the array $[1, 0, 1, 2]$, the bitwise OR is $3$ (which contains $2$ set bits), and the value of the array is $4-2=2$.\n\nYour task is to calculate the maximum possible value of some subsequence of the given array.",
    "tutorial": "Let the number of chosen elements be $k$, and their bitwise OR be $x$. The answer is equal to $k - popcount(x)$, where $popcount(x)$ is the number of bits equal to $1$ in $x$. However, we can rewrite $popcount(x)$ as $60 - zeroes(x)$, where $zeroes(x)$ is equal to the number of bits equal to $0$ among the first $60$ bits in $x$. So, we have to maximize the value of $k + zeroes(x)$. Consider the following bipartite graph: the left part consists of elements of the given array, the right part consists of bits. An edge between vertex $i$ from the left part and vertex $j$ from the right part means that the $j$-th bit in $a_i$ is set to $1$. Suppose we've chosen a set of vertices in the left part (the elements of our subsequence). The bits which are equal to $0$ in the bitwise OR are represented by such vertices $j$ such that no chosen vertex from the left part is connected to $j$. So, if we unite the chosen vertices from the left part with the vertices in the right part representing bits equal to $0$, this will be an independent subset of vertices. Thus, our problem is reduced to finding the maximum size of the independent subset of vertices. Usually, this problem is NP-complete. However, our graph is bipartite. So, we can use the following: by Konig's theorem, in a bipartite graph, the size of the minimum vertex cover is equal to the size of the maximum matching; and in every graph, independent subsets and vertex covers are complements of each other (if $S$ is a vertex cover, then the set of all vertices not belonging to $S$ is an independent subset, and vice versa). So, the maximum independent subset is the complement of the minimum vertex cover. It means that we can calculate the size of the maximum independent subset as $V - MM$, where $V$ is the number of vertices in the graph, and $MM$ is the size of the maximum matching. We can compute $MM$ using any maximum matching algorithm or network flow.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define sz(a) int((a).size())\n \ntemplate<typename T = int>\nstruct Dinic {\n  struct edge {\n    int u, rev;\n    T cap, flow;\n  };\n  \n  int n, s, t;\n  T flow;\n  vector<int> lst;\n  vector<int> d;\n  vector<vector<edge>> g;\n  \n  Dinic() {}\n  \n  Dinic(int n, int s, int t) : n(n), s(s), t(t) {\n    g.resize(n);\n    d.resize(n);\n    lst.resize(n);\n    flow = 0;\n  }\n \n  void add_edge(int v, int u, T cap, bool directed = true) {\n    g[v].push_back({u, sz(g[u]), cap, 0});\n    g[u].push_back({v, sz(g[v]) - 1, directed ? 0 : cap, 0});\n  }\n \n  T dfs(int v, T flow) {\n    if (v == t) return flow;\n    if (flow == 0) return 0;\n    T result = 0;\n    for (; lst[v] < sz(g[v]); ++lst[v]) {\n      edge& e = g[v][lst[v]];\n      if (d[e.u] != d[v] + 1) continue;\n      T add = dfs(e.u, min(flow, e.cap - e.flow));\n      if (add > 0) {\n        result += add;\n        flow -= add;\n        e.flow += add;\n        g[e.u][e.rev].flow -= add;\n      }\n      if (flow == 0) break;\n    }\n    return result;\n  }\n \n  bool bfs() {\n    fill(d.begin(), d.end(), -1);\n    queue<int> q({s});\n    d[s] = 0;\n    while (!q.empty() && d[t] == -1) {\n      int v = q.front(); q.pop();\n      for (auto& e : g[v]) {\n        if (d[e.u] == -1 && e.cap - e.flow > 0) {\n          q.push(e.u);\n          d[e.u] = d[v] + 1;\n        }\n      }\n    }\n    return d[t] != -1;\n  }\n \n  T calc() {\n    T add;\n    while (bfs()) {\n      fill(lst.begin(), lst.end(), 0);\n      while((add = dfs(s, numeric_limits<T>::max())) > 0)\n        flow += add;\n    }\n    return flow;\n  }\n};\n \nconst int B = 60;\nconst int INF = 1e9;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    int s = n + B, t = n + B + 1;\n    Dinic mf(t + 1, s, t);\n    for (int i = 0; i < n; ++i) {\n      long long x;\n      cin >> x;\n      mf.add_edge(s, i, 1);\n      for (int j = 0; j < B; ++j) {\n        if ((x >> j) & 1) mf.add_edge(i, j + n, INF);\n      }\n    }\n    for (int i = 0; i < B; ++i) mf.add_edge(i + n, t, 1);\n    cout << n - mf.calc() << '\\n';\n  }\n}",
    "tags": [
      "bitmasks",
      "dfs and similar",
      "flows",
      "graph matchings",
      "graphs"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2026",
    "index": "F",
    "title": "Bermart Ice Cream",
    "statement": "In the Bermart chain of stores, a variety of ice cream is sold. Each type of ice cream has two parameters: price and tastiness.\n\nInitially, there is one store numbered $1$, which sells nothing. You have to process $q$ queries of the following types:\n\n- $1~x$ — a new store opens, that sells the same types of ice cream as store $x$. It receives the minimum available positive index. The order of the types of ice cream in the new store is the same as in store $x$.\n- $2~x~p~t$ — a type of ice cream with price $p$ and tastiness $t$ becomes available in store $x$.\n- $3~x$ — a type of ice cream that was available the longest (appeared the earliest) in store $x$ is removed.\n- $4~x~p$ — for store $x$, find the maximum total tastiness of a subset of types of ice cream that are sold there, such that the total price does not exceed $p$ (each type can be used in the subset no more than once).",
    "tutorial": "Let's try to solve the problem without queries of type $1$. This leads to a data structure where elements are added to the end and removed from the beginning. In other words, a queue. The query is a dynamic programming problem of the \"knapsack\" type. To implement a knapsack on a queue, we can use the technique of implementing a queue with two stacks. This is commonly referred to as a \"queue with minimum\", as it is usually used to maintain the minimum. You can read more about it on cp-algorithms. We replace the operation of taking the minimum with the operation of adding a new item to the knapsack in $O(P)$, where $P$ is the maximum price in the queries. This gives us a solution with a time complexity of $O(qP)$. Now, let's return to the original problem. A type $1$ operation essentially adds the necessity to make the data structure persistent. However, this is only true if we need to respond to queries in the order they are given. In this problem, this is not the case - we can try to transition to an \"offline\" solution. Let's build a version tree of our persistent structure. For each query of type $1$, $2$, or $3$, create a new version. The edge between versions will store information about the type of change: a simple copy, an addition of an element, or a deletion of an element. Queries of type $4$ will be stored in a list for each vertex to which they are addressed. We will perform a depth-first traversal of the version tree. During the transition along an edge, we need to be able to do the following. If the transition is of the \"add element\" type, we need to add the element to the end, then process the subtree of the vertex, answer the queries for that vertex, and upon exiting, remove the element from the end. For a transition of the \"remove element\" type, we need to remove the element from the beginning and then add an element to the beginning. Thus, a structure of the \"deque\" type is sufficient. It turns out that a deque that maintains a minimum also exists. You can read about it in a blog by k1r1t0. Overall complexity: $O(qP)$, where $P$ is the maximum price in the queries.",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nconst int P = 2000 + 5;\n \nstruct item{\n\tint p, t;\n};\n \nstruct minstack {\n\tstack<item> st;\n\tstack<array<int, P>> dp;\n\tint get(int p) {return dp.empty() ? 0 : dp.top()[p];}\n\tbool empty() {return st.empty();}\n\tint size() {return st.size();}\n\tvoid push(item it) {\n\t\tif (empty()){\n\t\t    dp.push({});\n\t\t    for (int i = 0; i < P; ++i)\n\t\t        dp.top()[i] = 0;\n\t\t}\n\t\telse{\n\t\t    dp.push(dp.top());\n\t\t}\n\t\tst.push(it);\n\t\tfor (int i = P - it.p - 1; i >= 0; --i)\n\t\t\tdp.top()[i + it.p] = max(dp.top()[i + it.p], dp.top()[i] + it.t);\n\t}\n\tvoid pop() {\n\t\tst.pop();\n\t\tdp.pop();\n\t}\n\titem top() {\n\t\treturn st.top();\n\t}\n\tvoid swap(minstack &x) {\n\t\tst.swap(x.st);\n\t\tdp.swap(x.dp);\n\t}\n};\n \nstruct mindeque {\n\tminstack l, r, t;\n\tvoid rebalance() {\n\t\tbool f = false;\n\t\tif (r.empty()) {f = true; l.swap(r);}\n\t\tint sz = r.size() / 2;\n\t\twhile (sz--) {t.push(r.top()); r.pop();}\n\t\twhile (!r.empty()) {l.push(r.top()); r.pop();}\n\t\twhile (!t.empty()) {r.push(t.top()); t.pop();}\n\t\tif (f) l.swap(r);\n\t}\n\tint get(int p) {\n\t\tint ans = 0;\n\t\tfor (int i = 0; i <= p; ++i)\n\t\t\tans = max(ans, l.get(i) + r.get(p - i));\n\t\treturn ans;\n\t}\n\tbool empty() {return l.empty() && r.empty();}\n\tint size() {return l.size() + r.size();}\n\tvoid push_front(item it) {l.push(it);}\n\tvoid push_back(item it) {r.push(it);}\n\tvoid pop_front() {if (l.empty()) rebalance(); l.pop();}\n\tvoid pop_back() {if (r.empty()) rebalance(); r.pop();}\n\titem front() {if (l.empty()) rebalance(); return l.top();}\n\titem back() {if (r.empty()) rebalance(); return r.top();}\n\tvoid swap(mindeque &x) {l.swap(x.l); r.swap(x.r);}\n};\n \nstruct edge{\n\tint u, tp, p, t;\n};\n \nstruct query{\n\tint i, p;\n};\n \nvector<vector<edge>> g;\nvector<vector<query>> qs;\nvector<int> ans;\nmindeque ks;\n \nvoid dfs(int v){\n\tfor (auto& [i, p] : qs[v]){\n\t\tans[i] = ks.get(p);\n\t}\n\tfor (auto& [u, tp, p, t] : g[v]){\n\t\tif (tp == 0){\n\t\t\tdfs(u);\n\t\t}\n\t\telse if (tp == -1){\n\t\t    auto it = ks.front();\n\t\t    ks.pop_front();\n\t\t\tdfs(u);\n\t\t\tks.push_front({it.p, it.t});\n\t\t}\n\t\telse{\n\t\t\tks.push_back({p, t});\n\t\t\tdfs(u);\n\t\t\tks.pop_back();\n\t\t}\n\t}\n}\n \nint main() {\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tint q;\n\tcin >> q;\n\tvector<int> st(1);\n\tvector<int> where(q, -1);\n\tint cnt = 1, cnt_real = 1;\n\twhere[0] = 0;\n\tg.push_back({});\n\tqs.push_back({});\n\t\n\tauto copy_shop = [&](int x, bool real){\n\t\tg.push_back({});\n\t\tqs.push_back({});\n\t\tst.push_back(st[x]);\n\t\tif (real){\n\t\t\twhere[cnt_real] = cnt;\n\t\t\t++cnt_real;\n\t\t}\n\t\t++cnt;\n\t};\n\t\n\tforn(i, q){\n\t\tint tp, x;\n\t\tcin >> tp >> x;\n\t\t--x;\n\t\tint v = where[x], u = -1;\n\t\tif (tp != 4){\n\t\t\tcopy_shop(v, tp == 1);\n\t\t\tu = cnt - 1;\n\t\t}\n\t\tif (tp == 1){\n\t\t\tg[v].push_back({u, 0, -1, -1});\n\t\t\tcontinue;\n\t\t}\n\t\tif (tp == 3){\n\t\t\tg[v].push_back({u, -1, -1, -1});\n\t\t\t++st[u];\n\t\t\twhere[x] = u;\n\t\t\tcontinue;\n\t\t}\n\t\tint p;\n\t\tcin >> p;\n\t\tif (tp == 4){\n\t\t\tqs[v].push_back({i, p});\n\t\t\tcontinue;\n\t\t}\n\t\tint t;\n\t\tcin >> t;\n\t\tg[v].push_back({u, 1, p, t});\n\t\twhere[x] = u;\n\t}\n\t\n\tans.assign(q, -1);\n\tdfs(0);\n\tforn(i, q) if (ans[i] != -1) cout << ans[i] << '\\n';\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dp",
      "implementation",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2027",
    "index": "A",
    "title": "Rectangle Arrangement",
    "statement": "You are coloring an infinite square grid, in which all cells are initially white. To do this, you are given $n$ stamps. Each stamp is a rectangle of width $w_i$ and height $h_i$.\n\nYou will use \\textbf{each} stamp exactly \\textbf{once} to color a rectangle of the same size as the stamp on the grid in black. You cannot rotate the stamp, and for each cell, the stamp must either cover it fully or not cover it at all. You can use the stamp at any position on the grid, even if some or all of the cells covered by the stamping area are already black.\n\nWhat is the minimum sum of the \\textbf{perimeters} of the connected regions of black squares you can obtain after all the stamps have been used?",
    "tutorial": "We must minimize the perimeter, and an obvious way to attempt this is to maximize the overlap. To achieve this, we can place each stamp such that the lower left corner of each stamp is at the same position, like shown in the sample explanation. Now, we can observe that the perimeter of this shape is determined solely by the maximum height and width of any stamp, and these values cannot be reduced further. Therefore, the answer is $2 \\cdot \\bigl( \\max(a_i) + \\max(b_i) \\bigr)$. Furthermore, it's true that any arrangement of stamps which are fully enclosed in an outer rectangular area of $\\max(a_i)$ by $\\max(b_i)$ will yield the same perimeter.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        int maxw = 0, maxh = 0;\n        for (int i=0; i<n; i++) {\n            int w, h;\n            cin >> w >> h;\n            maxw = max(maxw, w);\n            maxh = max(maxh, h);\n        }\n        cout << 2 * (maxw + maxh) << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "geometry",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2027",
    "index": "B",
    "title": "Stalin Sort",
    "statement": "Stalin Sort is a humorous sorting algorithm designed to eliminate elements which are out of place instead of bothering to sort them properly, lending itself to an $\\mathcal{O}(n)$ time complexity.\n\nIt goes as follows: starting from the second element in the array, if it is strictly smaller than the previous element (ignoring those which have already been deleted), then delete it. Continue iterating through the array until it is sorted in non-decreasing order. For example, the array $[1, 4, 2, 3, 6, 5, 5, 7, 7]$ becomes $[1, 4, 6, 7, 7]$ after a Stalin Sort.\n\nWe define an array as vulnerable if you can sort it in \\textbf{non-increasing} order by repeatedly applying a Stalin Sort to \\textbf{any of its subarrays$^{\\text{∗}}$}, as many times as is needed.\n\nGiven an array $a$ of $n$ integers, determine the minimum number of integers which must be removed from the array to make it vulnerable.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "An array is vulnerable if and only if the first element is the largest. To prove the forward direction, we can trivially perform a single operation on the entire range, which will clearly make it non-increasing. Now, let's prove the reverse direction. Consider any array in which the maximum is not the first element. Note that a Stalin Sort on any subarray will never remove the first element, and also will never remove the maximum. So if the first is not the maximum, this will always break the non-increasing property. Therefore, we just need to find the longest subsequence in which the first element is the largest. This can be done easily in $\\mathcal{O}(n^2)$ - consider each index being the first item in the subsequence, and count all items to the right of it which are smaller or equal to it. Find the maximum over all of these, then subtract this from $n$. Bonus: Solve this task in $\\mathcal{O}(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> A(n);\n        for (int i=0; i<n; i++) cin >> A[i];\n        int best = 0;\n        for (int i=0; i<n; i++) {\n            int curr = 0;\n            for (int j=i; j<n; j++) {\n                if (A[j] <= A[i]) {\n                    curr += 1;\n                }\n            }\n            best = max(best, curr);\n        }\n        cout << n - best << \"\\n\";\n    }\n  return 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2027",
    "index": "C",
    "title": "Add Zeros",
    "statement": "You're given an array $a$ initially containing $n$ integers. In one operation, you must do the following:\n\n- Choose a position $i$ such that $1 < i \\le |a|$ and $a_i = |a| + 1 - i$, where $|a|$ is the \\textbf{current} size of the array.\n- Append $i - 1$ zeros onto the end of $a$.\n\nAfter performing this operation as many times as you want, what is the maximum possible length of the array $a$?",
    "tutorial": "Let's rearrange the equation given in the statement to find a 'required' $|a|$ value in order to use an operation at that index. We have $a_i = |a| + 1 - i$, so $|a| = a_i + i - 1$. Note that if $a_i = 0$, then the condition is never true, since $i - 1 < |a|$ always. So actually, we just need to consider the first $n$ positions. Once we use an operation at position $i$, the length of the array will increase by $i - 1$. So, for each position we require some length $u_i = a_i + i - 1$ and make a length of $v_i = u + i - 1$. So, let's create a graph containing all $n$ edges, and run some DFS or BFS on this graph starting from node $n$ (the starting value of $|a|$). It then follows that the largest node visited is the maximum length of the array we can possibly get. We should use a map to store the graph, since the length of the array can grow up to $\\approx n^2$ and so the graph is very sparse. If we don't want to use a map, we can also take advantage of the fact that all edges are directed from $u_i$ to $v_i$ where $u_i < v_i$ and that all edges and nodes are fixed, so we can actually iterate through all $u_i$ and maintain a boolean array of which $v_i$ values are visited so far, updating it at any point using a binary search.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nint main() {\n  cin.tie(0)->sync_with_stdio(0);\n  int t;\n  cin >> t;\n  while (t--) {\n        int n;\n        cin >> n;\n        vector<ll> A(n);\n        for (int i=0; i<n; i++) cin >> A[i];\n        map<ll,vector<ll>> adj;\n        for (int i=1; i<n; i++) {\n            ll u = A[i] + i;\n            ll v = u + i;\n            adj[u].push_back(v);\n        }\n        set<ll> vis;\n        function<void(ll)> dfs = [&](ll u) -> void {\n            if (vis.count(u)) return;\n            vis.insert(u);\n            for (ll v : adj[u]) dfs(v);\n        };\n        dfs(n);\n        cout << *vis.rbegin() << \"\\n\";\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2027",
    "index": "D1",
    "title": "The Endspeaker (Easy Version)",
    "statement": "\\textbf{This is the easy version of this problem. The only difference is that you only need to output the minimum total cost of operations in this version. You must solve both versions to be able to hack.}\n\nYou're given an array $a$ of length $n$, and an array $b$ of length $m$ ($b_i > b_{i+1}$ for all $1 \\le i < m$). Initially, the value of $k$ is $1$. Your aim is to make the array $a$ empty by performing one of these two operations repeatedly:\n\n- Type $1$ — If the value of $k$ is less than $m$ and the array $a$ is \\textbf{not empty}, you can increase the value of $k$ by $1$. This does not incur any cost.\n- Type $2$ — You remove a non-empty prefix of array $a$, such that its sum does not exceed $b_k$. This incurs a cost of $m - k$.\n\nYou need to minimize the total cost of the operations to make array $a$ empty. If it's impossible to do this through any sequence of operations, output $-1$. Otherwise, output the minimum total cost of the operations.",
    "tutorial": "Let's use dynamic programming. We will have $\\operatorname{dp}_{i,j}$ be the minimum cost to remove the prefix of length $i$, where the current value of $k$ is $j$. By a type $1$ operation, we can transition from $\\operatorname{dp}_{i,j}$ to $\\operatorname{dp}_{i,j+1}$ at no cost. Otherwise, by a type $2$ operation, we need to remove some contiguous subarray $a_{i+1}, a_{i+2}, \\dots, a_{x}$ (a prefix of the current array), to transition to $\\operatorname{dp}_{x,j}$ with a cost of $m - k$. Let $r$ be the largest value of $x$ possible. Given we're spending $m - k$ whatever value of $x$ we choose, it's clear to see that we only need to transition to $\\operatorname{dp}_{r,j}$. To find $r$ for each value of $i$ and $j$, we can either binary search over the prefix sums or simply maintain $r$ as we increase $i$ for a fixed value of $k$. The answer is then $\\operatorname{dp}_{n,k}$. The latter method solves the problem in $\\mathcal{O}(nm)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing ll = long long;\n\nconst int inf = 1 << 30;\n\nvoid chmin(int &a, int b) {\n  a = min(a, b);\n}\n\nint main() {\n  cin.tie(0)->sync_with_stdio(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, m;\n    cin >> n >> m;\n    vector<int> A(n+1);\n    for (int i=0; i<n; i++) cin >> A[i];\n    vector<int> B(m);\n    for (int i=0; i<m; i++) cin >> B[i];\n    vector nxt(n, vector<int>(m));\n    for (int k=0; k<m; k++) {\n      int r = -1, sum = 0;\n      for (int i=0; i<n; i++) {\n        while (r < n && sum <= B[k]) sum += A[++r];\n        nxt[i][k] = r;\n        sum -= A[i];\n      }\n    }\n    vector dp(n+1, vector<int>(m, inf));\n    dp[0][0] = 0;\n    for (int k=0; k<m; k++) {\n      for (int i=0; i<n; i++) {\n        chmin(dp[nxt[i][k]][k], dp[i][k] + m - k - 1);\n        if (k < m-1)\n          chmin(dp[i][k+1], dp[i][k]);\n      }\n    }\n    int ans = inf;\n    for (int k=0; k<m; k++) {\n      chmin(ans, dp[n][k]);\n    }\n    if (ans == inf) {\n      cout << \"-1\\n\";\n    } else {\n      cout << ans << \"\\n\";\n    }\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "graphs",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2027",
    "index": "D2",
    "title": "The Endspeaker (Hard Version)",
    "statement": "\\textbf{This is the hard version of this problem. The only difference is that you need to also output the number of optimal sequences in this version. You must solve both versions to be able to hack.}\n\nYou're given an array $a$ of length $n$, and an array $b$ of length $m$ ($b_i > b_{i+1}$ for all $1 \\le i < m$). Initially, the value of $k$ is $1$. Your aim is to make the array $a$ empty by performing one of these two operations repeatedly:\n\n- Type $1$ — If the value of $k$ is less than $m$ and the array $a$ is \\textbf{not empty}, you can increase the value of $k$ by $1$. This does not incur any cost.\n- Type $2$ — You remove a non-empty prefix of array $a$, such that its sum does not exceed $b_k$. This incurs a cost of $m - k$.\n\nYou need to minimize the total cost of the operations to make array $a$ empty. If it's impossible to do this through any sequence of operations, output $-1$. Otherwise, output the minimum total cost of the operations, and the number of sequences of operations which yield this minimum cost modulo $10^9 + 7$.\n\nTwo sequences of operations are considered different if you choose a different type of operation at any step, or the size of the removed prefix is different at any step.",
    "tutorial": "Following on from the editorial for D1. Let's have the $\\operatorname{dp}$ table store a pair of the minimum cost and the number of ways. Since we're now counting the ways, it's not enough just to consider the transition to $\\operatorname{dp}_{r,j}$; we also need to transition to all $\\operatorname{dp}_{x,j}$. Doing this naively is too slow, so let's instead find a way to perform range updates. Let's say we want to range update $\\operatorname{dp}_{l,j}, \\operatorname{dp}_{l+1,j}, ..., \\operatorname{dp}_{r,j}$. We'll store some updates in another table at either end of the range. Then, for a fixed value of $k$ as we iterate through increasing $i$-values, let's maintain a map of cost to ways. Whenever the number of ways falls to zero, we can remove it from the map. On each iteration, we can set $\\operatorname{dp}_{i,j}$ to the smallest entry in the map, and then perform the transitions. This works in $\\mathcal{O}(nm \\log n)$. Bonus: It's also possible to solve without the $\\log n$ factor. We can use the fact that $\\operatorname{dp}_{i,k}$ is non-increasing for a fixed value of $k$ to make the range updates non-intersecting by updating a range strictly after the previous iteration. Then we can just update a prefix sum array, instead of using a map. There exists an alternative solution for D1 & D2, using segment tree. We can actually consider the process in reverse; let's reformulate $\\operatorname{dp}_{i,j}$ to represent the minimum score required to remove all elements after the $i$-th element, given that the current value of $k$ is $j$. Instead of using a dp table, we maintain $m$ segment trees, each of length $n$. The $i$-th segment tree will represent the $i$-th column of the dp table. We precalculate for each $i$ and $j$ the furthest position we can remove starting from $i$ - specifically, the maximum subarray starting from $i$ with a sum less than $b_j$. We store this in $\\operatorname{nxt}_{i,j}$. This calculation can be done in $\\mathcal{O}(nm)$ time using a sliding window. To transition in the dp, we have: $\\operatorname{dp}_{i,j} = \\min\\left( \\operatorname{dp}_{i, j + 1}, \\, \\min(\\operatorname{dp}_{i + 1, j}, \\operatorname{dp}_{i + 2, j}, \\ldots, \\operatorname{dp}_{{\\operatorname{nxt}_{i,j}}, j}) + m - j + 1 \\right)$ This transition can be computed in $\\mathcal{O}(\\log n)$ time thanks to range querying on the segment tree, so our total complexity is $\\mathcal{O}(nm \\log n)$. For D2, we can store the count of minimums within each segment, and simply sum these counts to get the total number of ways.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define int long long\nint modN = 1e9 + 7;\n\nint mod(int n) {\n    return (n + modN) % modN;\n}\n\nstruct SegmentTree { \n    struct Node {\n        int val = 1e18;\n        int cnt = 1;\n    }; \n \n    vector<Node> st;\n    int n;\n    SegmentTree(int n): n(n) {\n        st.resize(4 * n + 1, Node());\n    }\n \n    SegmentTree(vector<int> a): n(a.size()) {\n        st.resize(4 * n + 1, Node());\n        build(a, 1, 0, n - 1);\n    }\n \n    void merge(Node& a, Node& b, Node& c) {\n        a.val = min(b.val, c.val);\n        if (b.val == c.val)\n            a.cnt = mod(b.cnt + c.cnt);\n        else if (b.val < c.val)\n            a.cnt = b.cnt;\n        else if (b.val > c.val)\n            a.cnt = c.cnt;\n    }\n \n    void build(vector<int>& a, int id, int l, int r) {\n        if (l == r) {\n            st[id].val = a[l];\n            return;\n        }\n        int mid = (l + r) / 2;\n        build(a, id * 2, l, mid);\n        build(a, id * 2 + 1, mid + 1, r);\n        merge(st[id], st[id * 2], st[id * 2 + 1]);\n    }\n \n    void update(int id, int l, int r, int u, int val, int cnt) {\n        if (l == r) {\n            st[id].val = val; // or st[id].sum += val\n            st[id].cnt = cnt;\n            return;\n        }\n        int mid = (l + r) / 2;\n        if (u <= mid) update(id * 2, l, mid, u, val, cnt);\n        else update(id * 2 + 1, mid + 1, r, u, val, cnt); \n        merge(st[id], st[id * 2], st[id * 2 + 1]);\n    }\n \n    void update(int idx, int val, int cnt) { //wrapper\n        update(1, 0, n - 1, idx, val, cnt);\n    }\n \n    Node query(int id, int l, int r, int u, int v) { //give 0, n - 1 as l and r and 1 as id\n        if (v < l || r < u) return Node();\n        if (u <= l && r <= v) {\n            return st[id];\n        }\n        int mid = (l + r) / 2;\n        auto a = query(id * 2, l, mid, u, v);\n        auto b = query(id * 2 + 1, mid + 1, r, u, v);\n        Node res;\n        merge(res, a, b);\n        return res;\n    }\n \n    Node query(int l, int r) { //wrapper\n        return query(1, 0, n - 1, l, r);\n    }\n};\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n), b(m);\n    for (int &A : a) cin >> A;\n    for (int &B : b) cin >> B;\n    if (*max_element(a.begin(), a.end()) > b[0]) {\n        cout << -1 << '\\n';\n        return;\n    }\n    vector<vector<int>> nxt(m, vector<int>(n));\n    for (int i = 0; i < m; i++) {\n        int curr = 0, r = -1;\n        for (int j = 0; j < n; j++) {\n            while (r + 1 < n && curr + a[r + 1] <= b[i]) \n                curr += a[r + 1], r += 1;\n            nxt[i][j] = r + 1;\n            if (j <= r) curr -= a[j];\n            r = max(r, j);\n        }\n    }\n    vector<SegmentTree> dp(m, SegmentTree(vector<int>(n + 1, 1e18)));\n    for (int i = 0; i < m; i++)\n        dp[i].update(n, 0, 1);\n    for (int i = n - 1; i >= 0; i--) {\n        for (int j = m - 1; j >= 0; j--) {\n            auto q1 = dp[j].query(i + 1, nxt[j][i]);\n            int v1 = q1.val + m - (j + 1), ps1 = q1.cnt;\n            if (i + 1 <= nxt[j][i]) dp[j].update(i, v1, ps1); \n            if (j != m - 1) {\n                auto q2 = dp[j + 1].query(i, i);\n                int v2 = q2.val, ps2 = q2.cnt;\n                auto q3 = dp[j].query(i, i);\n                if (v2 < q3.val)\n                    dp[j].update(i, v2, ps2);\n                else if (v2 == q3.val)\n                    dp[j].update(i, v2, mod(ps2 + q3.cnt));\n            }\n        }\n    }\n    cout << dp[0].query(0, 0).val << ' ' << dp[0].query(0, 0).cnt << '\\n';\n}\n\nsigned main() {\n    cin.tie(0) -> sync_with_stdio(false);\n    int t;  \n    cin >> t;\n    while (t--) \n       solve();\n    return 0;\n} ",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2027",
    "index": "E1",
    "title": "Bit Game (Easy Version)",
    "statement": "\\textbf{This is the easy version of this problem. The only difference is that you need to output the winner of the game in this version, and the number of stones in each pile are fixed. You must solve both versions to be able to hack.}\n\nAlice and Bob are playing a familiar game where they take turns removing stones from $n$ piles. Initially, there are $x_i$ stones in the $i$-th pile, and it has an associated value $a_i$. A player can take $d$ stones away from the $i$-th pile if and only if both of the following conditions are met:\n\n- $1 \\le d \\le a_i$, and\n- $x \\, \\& \\, d = d$, where $x$ is the current number of stones in the $i$-th pile and $\\&$ denotes the bitwise AND operation.\n\nThe player who cannot make a move loses, and Alice goes first.\n\nYou're given the $a_i$ and $x_i$ values for each pile, please determine who will win the game if both players play optimally.",
    "tutorial": "Each pile is an independent game, so let's try to find the nimber of a pile with value $a$ and size $x$ - let's denote this by $f(x, a)$. Suppose $x = 2^k - 1$ for some integer $k$; in this case, the nimber is entirely dependent on $a$. If $x$ is not in that form, consider the binary representation of $a$. If any bit in $a$ is on where $x$ is off, then it's equivalent to if $a$ had that bit off, but all lower bits were on. Let's call such a bit a 'good bit'. So we can build some value $a'$ by iterating along the bits from highest to lowest; if $x$ has an on bit in this position, then $a'$ will have an on bit in this position if and only if $a$ has one there, or we've already found a good bit. Now that the bits of $x$ and $a'$ align, we can remove all zeros from both representations and it's clear that this is an equivalent game with $x = 2^k - 1$. One small observation to make is that we can remove the ones in $x$ which correspond to leading zeros in $a'$, since we can never use these. So actually, after calculating $a'$ we only need $g(a') = f(2^k - 1, a')$, where $k$ is the smallest integer such that $2^k - 1 \\ge a'$. By running a brute force using the Sprague-Grundy theorem to find the nimbers you can observe some patterns which encompass all cases: $g(2^k - 2) = 0$, for all $k \\ge 1$. $g(2^k - 1) = k$, for all $k \\ge 0$. $g(2^k) = k \\oplus 1$, for all $k \\ge 0$. $g(2^k+1) = g(2^k+2) = \\ldots = g(2^{k+1} - 3) = k + 1$, for all $k \\ge 2$. The first $3$ cases are nice and relatively simple to prove, but the last is a lot harder (at least, I couldn't find an easier way). Anyway, I will prove all of them here, for completeness. First, note that if at any point we have $x \\le a$, then we have a standard nim-game over the $k$ bits of the number, since we can remove any of them on each operation, so the nimber of such a game would be $k$. The second case is one example of this; we have $x = a = 2^k - 1$, so its nimber is $k$. Now let's prove the first case. When $k = 1$, $g(0) = 0$ since there are no moves. For larger values of $k$, no matter which value of $d$ we choose, the resulting game has $x \\le a$ where $x$ has a positive number of bits. Overall, we have the $\\operatorname{mex}$ of a bunch of numbers which are all positive, so the nimber is $0$ as required. Now let's prove the third case. To reiterate, since $a' = 2^k$ we have $x = 2^{k+1} - 1$ by definition. This case is equivalent to having a nim-game with one pile of $k$ bits (all bits below the most significant one), and another pile of $1$ bit (the most significant one). This is because we can remove any amount from either pile in one move, but never both. Therefore, the nimber is $k \\oplus 1$ as required. The last case is the hardest to prove. We need to show that there is some move that lands you in a game for all nimbers from $0$ to $k$, and never with nimber $k + 1$. Well, the only way that you could get a nimber of $k + 1$ is by landing in case $3$ without changing the number of bits in $x$/$a'$. Any move will change this though, since any move will remove some bits of $x$ and when $a'$ is recalculated it'll have fewer bits. Okay, now one way of getting a nimber of $0$ is just by removing all bits in $x$ which are strictly after the first zero-bit in $a'$. For example, if $a' = 101101$, then let's choose $d = 001111$; then we'll land in case $1$. As for getting the rest of the nimbers from $1$ to $k$, it helps if we can just land in case $2$ but with a varying number of bits. If $a' \\ge 2^k + 2^{k-1} - 1$ this is easily possible by considering all $d$ in the range $2^k \\le d < 2^k + 2^{k-1}$. On the other hand, if $a < 2^k + 2^{k-1} - 1$, let's first consider the resulting value of $x$ to be equal to $2^k + 2^m$, where $2^m$ is the lowest set bit in $a'$. This will give a nimber of $2$. Now, we can repeatedly add the highest unset bit in this $x$ to itself to generate the next nimber until we now have all nimbers from $2$ to $k$. For the nimber of $1$, just have the resulting $x$ be $2^k$. Time complexity: $\\mathcal{O}(n \\log C)$, where $C$ is the upper limit on $x_i$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint nimber(int x, int a) {\n  int aprime = 0;\n  bool goodbit = false;\n  for (int bit=30; bit>=0; bit--) {\n    if (x & (1 << bit)) {\n      aprime *= 2;\n      if (goodbit || (a & (1 << bit))) {\n        aprime += 1;\n      }\n    } else if (a & (1 << bit)) {\n      goodbit = true;\n    }\n  }\n \n  // g(2^k - 2) = 0, for all k >= 1.\n  for (int k=1; k<=30; k++) {\n    if (aprime == (1 << k) - 2) {\n      return 0;\n    }\n  }\n \n  // g(2^k - 1) = k, for all k >= 1.\n  for (int k=1; k<=30; k++) {\n    if (aprime == (1 << k) - 1) {\n      return k;\n    }\n  }\n \n  // g(2^k) = k + (-1)^k, for all k >= 0.\n  for (int k=1; k<=30; k++) {\n    if (aprime == (1 << k)) {\n      if (k % 2) return k - 1;\n      else return k + 1;\n    }\n  }\n \n  // g(2^k+1) = g(2^k+2) = ... = g(2^{k+1} - 3) = k + 1, for all k >= 2.\n  for (int k=2; k<=30; k++) {\n    if ((1 << k) < aprime && aprime <= (2 << k) - 3) {\n      return k + 1;\n    }\n  }\n \n  // should never get to this point\n  assert(false);\n  return -1;\n}\n \nint main() {\n  cin.tie(0)->sync_with_stdio(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> A(n);\n    for (int i=0; i<n; i++) cin >> A[i];\n    vector<int> X(n);\n    for (int i=0; i<n; i++) cin >> X[i];\n    int curr = 0;\n    for (int i=0; i<n; i++) curr ^= nimber(X[i], A[i]);\n    cout << (curr ? \"Alice\" : \"Bob\") << \"\\n\";\n  }\n  return 0;\n}\n\n",
    "tags": [
      "bitmasks",
      "brute force",
      "games",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2027",
    "index": "E2",
    "title": "Bit Game (Hard Version)",
    "statement": "\\textbf{This is the hard version of this problem. The only difference is that you need to output the number of choices of games where Bob wins in this version, where the number of stones in each pile are not fixed. You must solve both versions to be able to hack.}\n\nAlice and Bob are playing a familiar game where they take turns removing stones from $n$ piles. Initially, there are $x_i$ stones in the $i$-th pile, and it has an associated value $a_i$. A player can take $d$ stones away from the $i$-th pile if and only if both of the following conditions are met:\n\n- $1 \\le d \\le a_i$, and\n- $x \\, \\& \\, d = d$, where $x$ is the current number of stones in the $i$-th pile and $\\&$ denotes the bitwise AND operation.\n\nThe player who cannot make a move loses, and Alice goes first.\n\nYou're given the $a_i$ values of each pile, but the number of stones in the $i$-th pile has not been determined yet. For the $i$-th pile, $x_i$ can be any integer between $1$ and $b_i$, inclusive. That is, you can choose an array $x_1, x_2, \\ldots, x_n$ such that the condition $1 \\le x_i \\le b_i$ is satisfied for all piles.\n\nYour task is to count the number of games where Bob wins if both players play optimally. Two games are considered different if the number of stones in any pile is different, i.e., the arrays of $x$ differ in at least one position.\n\nSince the answer can be very large, please output the result modulo $10^9 + 7$.",
    "tutorial": "Let's continue on from the editorial for E1. We figured out that the nimbers lie in one of these four cases: $g(2^k - 2) = 0$, for all $k \\ge 1$. $g(2^k - 1) = k$, for all $k \\ge 0$. $g(2^k) = k + (-1)^k$, for all $k \\ge 0$. $g(2^k+1) = g(2^k+2) = \\ldots = g(2^{k+1} - 3) = k + 1$, for all $k \\ge 2$. From these, it's clear to see that the nimber of each pile is always $\\le 31$ given the constraints. So, let's say we can count the amount of values of $x_i \\le b_i$ exist such that $f(x_i, a_i) = p$ for all $p$, then we can easily maintain a knapsack to count the number of games where the nimbers of piles have a bitwise XOR of $0$. All that's left is to count the number of values of $x_i$ which yield some $a'$ in each of the cases above, which is probably the hardest part of the problem. We can use digit DP for this. The state should store the position of the most significant one in $a'$, and whether $a'$ is $0$ or in the form $1$, $11 \\cdots 1$, $11 \\cdots 0$, $100 \\cdots 0$ or anything else. To find whether a $1$ added to $x$ becomes $0$ or $1$ in $a'$, have another flag to check whether a good bit has occurred yet. Also, to ensure that $x \\le b$, have one more flag to check whether the current prefix has fallen strictly below $b$ yet. Please see the model code's comments for a better understanding of how the transitions are computed. Time complexity: $\\mathcal{O}(n \\log^2 C)$, where $C$ is the upper limit on $a_i$ and $b_i$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n        \nint dp[32][32][6][2][2];\n \nconst int mod = 1000000007;\n \nint main() {\n  cin.tie(0)->sync_with_stdio(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> A(n);\n    for (int i=0; i<n; i++) cin >> A[i];\n    vector<int> B(n);\n    for (int i=0; i<n; i++) cin >> B[i];\n    vector<int> curr(32);\n    curr[0] = 1; // identity\n    for (int i=0; i<n; i++) {\n      memset(dp, 0, sizeof dp);\n      dp[0][0][0][0][0] = 1;\n      for (int j=0; j<=29; j++) {\n        int p = 29 - j; // place we are going to add a bit in\n        for (int k=0; k<=29; k++) { // position of most significant one in a'\n          for (int type=0; type<6; type++) { // 0, 1, 11111, 11110, 10000, else\n            for (int good=0; good<2; good++) { // good=1 iff good bit has occured\n              for (int low=0; low<2; low++) { // low=1 iff prefix below b\n                for (int bit=0; bit<2; bit++) { // bit in x\n                  if (dp[j][k][type][good][low] == 0) \n                    continue; // no point in transition since count is 0\n                  if (!low && (B[i] & (1 << p)) == 0 && bit == 1) \n                    continue; // x can't go higher than B[i]\n                  if (bit == 0) {\n                    int good2 = good || (A[i] & (1 << p)) != 0; // check good bit\n                    int low2 = low || (B[i] & (1 << p)) != 0; // check if low\n                    // nothing added to a' so nothing else changes\n                    (dp[j+1][k][type][good2][low2] += dp[j][k][type][good][low]) %= mod;\n                  } else {\n                    int bita = good || (A[i] & (1 << p)) != 0; // bit in a'\n                    int k2 = type == 0 ? 0 : k + 1; // increase if MSOne exists\n                    int type2 = bita ?\n                      (\n                        type == 0 ? 1 : // add first one\n                        (type == 1 || type == 2) ? 2 : // 11111\n                        5 // can't add 1 after a 0\n                      ) : (\n                        (type == 0) ? 0 : // 0\n                        (type == 1 || type == 4) ? 4 : // 10000\n                        (type == 2) ? 3 : // 11110\n                        5 // can't have a zero in any other case\n                      );\n                    (dp[j+1][k2][type2][good][low] += dp[j][k][type][good][low]) %= mod;\n                  }\n                }\n              }\n            }\n          }\n        } \n      }\n      vector<int> count(32); // number of x-values for each nimber\n      for (int k=0; k<=29; k++) { // position of MSOne\n        for (int good=0; good<2; good++) { // doesn't matter\n          for (int low=0; low<2; low++) { // doesn't matter\n            (count[0] += dp[30][k][0][good][low]) %= mod; // 0\n            (count[1] += dp[30][k][1][good][low]) %= mod; // 1\n            (count[k+1] += dp[30][k][2][good][low]) %= mod; // 11111\n            (count[0] += dp[30][k][3][good][low]) %= mod; // 11110\n            (count[k+(k%2?-1:1)] += dp[30][k][4][good][low]) %= mod; // 10000\n            (count[k+1] += dp[30][k][5][good][low]) %= mod; // else\n          }\n        }\n      }\n      count[0] -= 1; // remove when x=0\n      vector<int> next(32); // knapsack after adding this pile\n      for (int j=0; j<32; j++)\n        for (int k=0; k<32; k++)\n          (next[j ^ k] += 1LL * curr[j] * count[k] % mod) %= mod;\n      swap(curr, next);\n    }\n    cout << curr[0] << \"\\n\";\n  }\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2028",
    "index": "A",
    "title": "Alice's Adventures in ''Chess''",
    "statement": "Alice is trying to meet up with the Red Queen in the countryside! Right now, Alice is at position $(0, 0)$, and the Red Queen is at position $(a, b)$. Alice can only move in the four cardinal directions (north, east, south, west).\n\nMore formally, if Alice is at the point $(x, y)$, she will do one of the following:\n\n- go north (represented by N), moving to $(x, y+1)$;\n- go east (represented by E), moving to $(x+1, y)$;\n- go south (represented by S), moving to $(x, y-1)$; or\n- go west (represented by W), moving to $(x-1, y)$.\n\nAlice's movements are predetermined. She has a string $s$ representing a sequence of moves that she performs from left to right. Once she reaches the end of the sequence, she repeats the same pattern of moves forever.\n\nCan you help Alice figure out if she will ever meet the Red Queen?",
    "tutorial": "We can run the whole pattern $100\\gg \\max(a, b, n)$ times, which gives a total runtime of $O(100tn)$ (be careful in that running the pattern only 10 times is not enough!) To prove that $100$ repeats suffices, suppose that Alice's steps on the first run of the pattern are $(0, 0), (x_1, y_1), (x_2, y_2), \\ldots, (x_n, y_n)$ (we will take $x_0 = 0, y_0 = 0$ for convenience) Then, Alice ends up at position $(a, b)$ if there exists a $t\\ge 0$ (the number of extra repeats) such that for some $i$, $x_i + tx_n = a$ and $y_i + ty_n = b$. Certainly, if $x_n = y_n = 0$, we only need one repeat so assume WLOG that $x_n \\neq 0$. Then, it must be the case that $t = \\frac{a - x_i}{x_n}$. However, $a - x_i \\le 20$ (since $x_i \\ge -10$) and $|x_n|\\ge 1$, so $t \\le 20$ and therefore $21$ repeats always suffice. In fact, the above proof shows that we can solve each testcase in time $O(n)$.",
    "code": "def solve():\n    [n, a, b] = list(map(int, input().split()))\n    s = str(input())\n    x, y = 0, 0\n    for __ in range(100):\n        for c in s:\n            if c == 'N':\n                y += 1\n            elif c == 'E':\n                x += 1\n            elif c == 'S':\n                y -= 1\n            else:\n                x -= 1\n            if x == a and y == b:\n                print(\"YES\")\n                return\n    print(\"NO\")\n \nt = int(input())\n \nfor _ in range(t):\n    solve()",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2028",
    "index": "B",
    "title": "Alice's Adventures in Permuting",
    "statement": "Alice mixed up the words transmutation and permutation! She has an array $a$ specified via three integers $n$, $b$, $c$: the array $a$ has length $n$ and is given via $a_i = b\\cdot (i - 1) + c$ for $1\\le i\\le n$. For example, if $n=3$, $b=2$, and $c=1$, then $a=[2 \\cdot 0 + 1, 2 \\cdot 1 + 1, 2 \\cdot 2 + 1] = [1, 3, 5]$.\n\nNow, Alice really enjoys permutations of $[0, \\ldots, n-1]$$^{\\text{∗}}$ and would like to transform $a$ into a permutation. In one operation, Alice replaces the maximum element of $a$ with the $\\operatorname{MEX}$$^{\\text{†}}$ of $a$. If there are multiple maximum elements in $a$, Alice chooses the leftmost one to replace.\n\nCan you help Alice figure out how many operations she has to do for $a$ to become a permutation for the first time? If it is impossible, you should report it.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $0$ to $n-1$ in arbitrary order. \\textbf{Please note, this is slightly different from the usual definition of a permutation.} For example, $[1,2,0,4,3]$ is a permutation, but $[0,1,1]$ is not a permutation ($1$ appears twice in the array), and $[0,2,3]$ is also not a permutation ($n=3$ but there is $3$ in the array).\n\n$^{\\text{†}}$The $\\operatorname{MEX}$ of an array is the smallest non-negative integer that does not belong to the array. For example, the $\\operatorname{MEX}$ of $[0, 3, 1, 3]$ is $2$ and the $\\operatorname{MEX}$ of $[5]$ is $0$.\n\\end{footnotesize}",
    "tutorial": "Suppose that $b = 0$. Then, if $c \\ge n$, the answer is $n$; if $c = n - 1$ or $c = n - 2$, the answer is $n - 1$; and otherwise, it is $-1$ (for example, consider $c = n - 3$, in which case we will end up with $a = [0, 1, \\ldots, n - 4, n - 3, n - 3, n - 3] \\rightarrow [0, 1, \\ldots, n - 4, n - 3, n - 3, n - 2] \\rightarrow [0, 1, \\ldots, n - 4, n - 3, n - 3, n - 1]$ Otherwise, since $a$ has distinct elements, we claim that the answer is $n - m$, where $m$ is the number of elements in $0, 1, \\ldots, n - 1$ already present in the array. Equivalently, it is the number of steps until $\\max(a) < n$ since we always preserve the distinctness of the elements of $a$. So, we want to find the maximum $i$ such that $a_i < n$. This happens exactly when $i < \\frac{n - c}{b}$. The expected complexity is $O(1)$ per testcase.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing vi = vector<int>;\n#define rep(i, a, b) for(int i = a; i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define sz(x) (int)(x).size()\n#define smx(a, b) a = max(a, b)\n#define smn(a, b) a = min(a, b)\n#define pb push_back\n#define endl '\\n'\n \nconst ll MOD = 1e9 + 7;\nconst ld EPS = 1e-9;\n \nmt19937 rng(time(0));\n \nint main() {\n\tcin.tie(0)->sync_with_stdio(0);\n \n\tint t; cin >> t;\n\twhile (t--) {\n\t\tll n, b, c; cin >> n >> b >> c;\n\t\tif (b == 0) {\n\t\t\tif (c >= n) {\n\t\t\t\tcout << n << \"\\n\";\n\t\t\t} else if (c >= n - 2) {\n\t\t\t\tcout << n - 1 << \"\\n\";\n\t\t\t} else {\n\t\t\t\tcout << -1 << \"\\n\";\n\t\t\t}\n\t\t} else {\n\t\t    if (c >= n) cout << n << \"\\n\";\n\t\t\telse cout << n - max(0ll, 1 + (n - c - 1) / b) << \"\\n\";\n\t\t}\n\t}\n}",
    "tags": [
      "binary search",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2028",
    "index": "C",
    "title": "Alice's Adventures in Cutting Cake",
    "statement": "Alice is at the Mad Hatter's tea party! There is a long sheet cake made up of $n$ sections with tastiness values $a_1, a_2, \\ldots, a_n$. There are $m$ creatures at the tea party, excluding Alice.\n\nAlice will cut the cake into $m + 1$ pieces. Formally, she will partition the cake into $m + 1$ subarrays, where each subarray consists of some number of adjacent sections. The tastiness of a piece is the sum of tastiness of its sections. Afterwards, she will divvy these $m + 1$ pieces up among the $m$ creatures and herself (her piece can be empty). However, each of the $m$ creatures will only be happy when the tastiness of its piece is $v$ or more.\n\nAlice wants to make sure every creature is happy. Limited by this condition, she also wants to maximize the tastiness of her own piece. Can you help Alice find the maximum tastiness her piece can have? If there is no way to make sure every creature is happy, output $-1$.",
    "tutorial": "Alice's piece of cake will be some subsegment $a[i:j]$. For a fixed $i$, how large can $j$ be? To determine this, let $pfx[i]$ be the maximum number of creatures that can be fed on $a[:i]$ and $sfx[j]$ the maximum number of creatures on $a[j:]$. Then, for a given $i$, the maximum possible $j$ is exactly the largest $j$ such that $pfx[i] + sfx[j] \\ge m$. If we compute the $pfx$ and $sfx$ arrays, we can then compute these largest $j$ for all $i$ with two pointers in $O(n)$ (or with binary search in $O(n\\log n)$, since $sfx$ is monotonically non-increasing). To compute $pfx[i]$, we can use prefix sums and binary search to find the maximum $k < i$ such that $\\sum_{\\ell=k}^{i}a[\\ell] \\ge v$: then $pfx[i] = 1 + pfx[k]$. We can compute $sfx$ similarly by reversing $a$. This takes time $O(n\\log n)$ (it is also possible to do this with two pointers in $O(n)$, which you can see in the model solution). Expected complexity: $O(n)$ or $O(n\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing vi = vector<int>;\n#define rep(i, a, b) for(int i = a; i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define sz(x) (int)(x).size()\n#define smx(a, b) a = max(a, b)\n#define smn(a, b) a = min(a, b)\n#define pb push_back\n#define endl '\\n'\n \nconst ll MOD = 1e9 + 7;\nconst ld EPS = 1e-9;\n \nmt19937 rng(time(0));\n \nint main() {\n\tcin.tie(0)->sync_with_stdio(0);\n \n\tint t; cin >> t;\n\twhile (t--) {\n\t\tint n, m; cin >> n >> m;\n\t\tll v; cin >> v;\n\t\tvector<ll> a(n);\n\t\trep(i,0,n) cin >> a[i];\n \n\t\tvector<ll> sums(n + 1);\n\t\trep(i,0,n) sums[i + 1] = sums[i] + a[i];\n \n\t\tauto query = [&](int i, int j) { // [i, j)\n\t\t\treturn sums[j] - sums[i];\n\t\t};\n \n\t\tauto compute_pfx = [&]() -> vector<int> {\n\t\t\tvector<int> pfx(n + 1, 0);\n\t\t\tint end = 0, val = 0;\n\t\t\tll sum = 0;\n\t\t\tfor (int start = 0; start < n; start++) {\n\t\t\t\twhile (end < n && sum < v) {\n\t\t\t\t\tsum += a[end];\n\t\t\t\t\t++end;\n\t\t\t\t\tpfx[end] = max(pfx[end], pfx[end - 1]);\n\t\t\t\t}\n\t\t\t\tif (sum >= v) {\n\t\t\t\t\tpfx[end] = 1 + pfx[start];\n\t\t\t\t}\n\t\t\t\tsum -= a[start];\n\t\t\t}\n\t\t\trep(i,1,n+1) {\n\t\t\t\tpfx[i] = max(pfx[i], pfx[i - 1]);\n\t\t\t}\n\t\t\treturn pfx;\n\t\t};\n \n\t\tauto pfx = compute_pfx();\n\t\treverse(all(a));\n\t\tauto sfx = compute_pfx();\n\t\treverse(all(a));\n\t\treverse(all(sfx));\n \n\t\tif (pfx[n] < m) {\n\t\t\tcout << \"-1\\n\";\n\t\t\tcontinue;\n\t\t}\n \n\t\tint end = 0;\n\t\tll ans = 0;\n\t\tfor (int start = 0; start < n; start++) {\n\t\t\twhile (end < n && pfx[start] + sfx[end + 1] >= m) ++end;\n\t\t\tif (pfx[start] + sfx[end] >= m)\n\t\t\t\tans = max(ans, query(start, end));\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2028",
    "index": "D",
    "title": "Alice's Adventures in Cards",
    "statement": "Alice is playing cards with the Queen of Hearts, King of Hearts, and Jack of Hearts. There are $n$ different types of cards in their card game. Alice currently has a card of type $1$ and needs a card of type $n$ to escape Wonderland. The other players have one of each kind of card.\n\nIn this card game, Alice can trade cards with the three other players. Each player has different preferences for the $n$ types of cards, which can be described by permutations$^{\\text{∗}}$ $q$, $k$, and $j$ for the Queen, King, and Jack, respectively.\n\nA player values card $a$ more than card $b$ if for their permutation $p$, $p_a > p_b$. Then, this player is willing to trade card $b$ to Alice in exchange for card $a$. Alice's preferences are straightforward: she values card $a$ more than card $b$ if $a > b$, and she will also only trade according to these preferences.\n\nDetermine if Alice can trade up from card $1$ to card $n$ subject to these preferences, and if it is possible, give a possible set of trades to do it.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "We will use DP to answer the following question for each $a$ from $n$ down to $1$: is it possible to trade up from card $a$ to card $n$? To answer this question efficiently, we need to determine for each of the three players whether there exists some $b > a$ such that $p(b) < p(a)$ and it is possible to trade up from card $b$ to card $n$. We can do this efficiently by keeping track for each player the minimum value $x = p(b)$ over all $b$ that can reach $n$: then, for a given $a$ we can check for each player if $p(a)$ exceeds $x$. If it does for some player, we can then update the values $x$ for each of the three players. Alongside these minimum values $x$ we can keep track of the $b$ achieving them to be able to reconstruct a solution. This takes time $O(n)$ since each iteration takes time $O(1)$. Solve the same problem, but now with the additional requirement that the solution must use the minimum number of trades (same constraints).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing vi = vector<int>;\n#define rep(i, a, b) for(int i = a; i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define sz(x) (int)(x).size()\n#define smx(a, b) a = max(a, b)\n#define smn(a, b) a = min(a, b)\n#define pb push_back\n#define endl '\\n'\n \nconst ll MOD = 1e9 + 7;\nconst ld EPS = 1e-9;\n \nmt19937 rng(time(0));\n \nint main() {\n\tcin.tie(0)->sync_with_stdio(0);\n \n\tint t; cin >> t;\n\tstd::string s = \"qkj\";\n\twhile (t--) {\n\t\tint n; cin >> n;\n\t\tvector p(3, vector<int>(n + 1));\n\t\trep(i,0,3) rep(j,1,n + 1) cin >> p[i][j];\n\t\tvector<pair<char, int>> sol(n + 1, {'\\0', -1});\n\t\tarray<int, 3> mins = {n, n, n}; // minimizing index\n\t\tfor (int i = n - 1; i >= 1; i--) {\n\t\t\tint win = -1;\n\t\t\trep(j,0,3) if (p[j][i] > p[j][mins[j]]) win = j;\n\t\t\tif (win == -1) continue;\n\t\t\tsol[i] = {s[win], mins[win]};\n\t\t\trep(j,0,3) if (p[j][i] < p[j][mins[j]]) mins[j] = i;\n\t\t}\n\t\tif (sol[1].second == -1) {\n\t\t\tcout << \"NO\\n\";\n\t\t\tcontinue;\n\t\t}\n\t\tcout << \"YES\\n\";\n\t\tvector<pair<char, int>> ans = {sol[1]};\n\t\twhile (ans.back().second >= 0) {\n\t\t\tans.push_back(sol[ans.back().second]);\n\t\t}\n\t\tans.pop_back();\n\t\tcout << sz(ans) << \"\\n\";\n\t\tfor (auto && [c, i] : ans) {\n\t\t\tcout << c << \" \" << i << \"\\n\";\n\t\t}\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "graphs",
      "greedy",
      "implementation",
      "ternary search"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2028",
    "index": "E",
    "title": "Alice's Adventures in the Rabbit Hole",
    "statement": "Alice is at the bottom of the rabbit hole! The rabbit hole can be modeled as a tree$^{\\text{∗}}$ which has an exit at vertex $1$, and Alice starts at some vertex $v$. She wants to get out of the hole, but unfortunately, the Queen of Hearts has ordered her execution.\n\nEach minute, a fair coin is flipped. If it lands heads, Alice gets to move to an adjacent vertex of her current location, and otherwise, the Queen of Hearts gets to pull Alice to an adjacent vertex of the Queen's choosing. If Alice ever ends up on any of the non-root leaves$^{\\text{†}}$ of the tree, Alice loses.\n\nAssuming both of them move optimally, compute the probability that Alice manages to escape for every single starting vertex $1\\le v\\le n$. Since these probabilities can be very small, output them modulo $998\\,244\\,353$.\n\nFormally, let $M = 998\\,244\\,353$. It can be shown that the exact answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected simple graph which has $n$ vertices and $n-1$ edges.\n\n$^{\\text{†}}$A leaf is a vertex that is connected to exactly one edge.\n\\end{footnotesize}",
    "tutorial": "Note that Alice should always aim to move to the root, as this maximizes her probability of escaping (i.e., for any path from leaf to root, Alice's probability of escaping increases moving up the path). Furthermore, the Queen should always move downward for the same reason as above. Furthermore, the Queen should always move to the closest leaf in the subtree rooted at the current node. There are now a few ways to compute this, but basically all of them are $O(n)$. For one such slick way, define $d(v)$ to be the distance to the closest leaf of the subtree of $v$, $p(v)$ to be the parent of $v$, and $t(v)$ to be the probability Alice gets the treasure starting at node $v$. Then, we claim that $t(v) = \\frac{d(v)}{d(v)+1}\\cdot t(p(v))$ for all vertices except the root. We can populate these values as we DFS down the tree. Indeed, suppose that the tree is just a path with $d + 1$ vertices, labelled from $1$ through $d + 1$. Then, Alice's probability of getting the treasure at node $i$ is $1 - \\frac{i - 1}{d}$ (this comes from solving a system of linear equations). This lines up with the above $t(v)$ calculation. Now, we can construct the answer inductively. Let $P$ be a shortest root-to-leaf path in $T$ and consider the subtrees formed by removing the edges of $P$ from $T$. Each such subtree is rooted at some node $v\\in P$. Then, in a subtree $T'$ rooted at $v$, the probability of Alice getting the treasure is exactly the probability that Alice gets to node $v$ and then to node $1$ from $v$, by the chain rule of conditioning and noting that the Queen will never re-enter the subtree $T'$ and the game will only play out along $P$ from this point forward. Therefore, it suffices to deconstruct $T$ into shortest root-to-leaf paths and note that at a given vertex $v$, we only have to play along the sequence of shortest root-to-leaf paths leading from $v$ to $1$. Along each of these paths, the above probability calculation holds, so we are done.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing vi = vector<int>;\n#define rep(i, a, b) for(int i = a; i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define sz(x) (int)(x).size()\n#define smx(a, b) a = max(a, b)\n#define smn(a, b) a = min(a, b)\n#define pb push_back\n#define endl '\\n'\n \nconst ll MOD = 1e9 + 7;\nconst ld EPS = 1e-9;\n \n// mt19937 rng(time(0));\n \nll euclid(ll a, ll b, ll &x, ll &y) {\n\tif (!b) return x = 1, y = 0, a;\n\tll d = euclid(b, a % b, y, x);\n\treturn y -= a/b * x, d;\n}\n \nconst ll mod = 998244353;\nstruct mint {\n\tll x;\n\tmint(ll xx) : x(xx) {}\n\tmint operator+(mint b) { return mint((x + b.x) % mod); }\n\tmint operator-(mint b) { return mint((x - b.x + mod) % mod); }\n\tmint operator*(mint b) { return mint((x * b.x) % mod); }\n\tmint operator/(mint b) { return *this * invert(b); }\n\tmint invert(mint a) {\n\t\tll x, y, g = euclid(a.x, mod, x, y);\n\t\tassert(g == 1); return mint((x + mod) % mod);\n\t}\n\tmint operator^(ll e) {\n\t\tif (!e) return mint(1);\n\t\tmint r = *this ^ (e / 2); r = r * r;\n\t\treturn e&1 ? *this * r : r;\n\t}\n};\n \nvoid solve() {\n\tint n; cin >> n;\n\tvector<vector<int>> t(n);\n\trep(i,0,n-1) {\n\t\tint x, y; cin >> x >> y; --x, --y;\n\t\tt[x].push_back(y);\n\t\tt[y].push_back(x);\n\t}\n \n\tvector<int> d(n, n + 1);\n\tfunction<int(int, int)> depths = [&](int curr, int par) {\n\t\tfor (auto v : t[curr]) {\n\t\t\tif (v == par) continue;\n\t\t\td[curr] = min(d[curr], 1 + depths(v, curr));\n\t\t}\n\t\tif (d[curr] > n) d[curr] = 0;\n\t\treturn d[curr];\n\t};\n \n\tdepths(0, -1);\n \n\tvector<mint> ans(n, 0);\n\tfunction<void(int, int, mint)> dfs = [&](int curr, int par, mint val) {\n\t\tans[curr] = val;\n\t\tfor (auto v : t[curr]) {\n\t\t\tif (v == par) continue;\n\t\t\tdfs(v, curr, val * d[v] / (d[v] + 1));\n\t\t}\n\t};\n \n\tdfs(0, -1, mint(1));\n\tfor (auto x : ans) {\n\t\tcout << x.x << \" \";\n\t}\n\tcout << \"\\n\";\n}\n \nint main() {\n\tcin.tie(0)->sync_with_stdio(0);\n \n\tint t; cin >> t;\n\twhile (t--) solve();\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "games",
      "greedy",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2028",
    "index": "F",
    "title": "Alice's Adventures in Addition",
    "statement": "\\textbf{Note that the memory limit is unusual.}\n\nThe Cheshire Cat has a riddle for Alice: given $n$ integers $a_1, a_2, \\ldots, a_n$ and a target $m$, is there a way to insert $+$ and $\\times$ into the circles of the expression $$a_1 \\circ a_2 \\circ \\cdots \\circ a_n = m$$ to make it true? We follow the usual order of operations: $\\times$ is done before $+$.\n\nAlthough Alice is excellent at chess, she is not good at math. Please help her so she can find a way out of Wonderland!",
    "tutorial": "Let $dp[i][j]$ be whether $a_1\\circ a_2\\circ \\ldots \\circ a_i = j$ can be satisfied. Then, let's case on $a_i$. If $a_i = 0$, then $dp[i][j] = dp[i - 1][j] \\lor dp[i - 2][j]\\lor \\cdots \\lor dp[0][j]$ (where we will take $dp[0][j]= \\boldsymbol{1}[j = 0]$, the indicator that $j = 0$). This is because we can multiply together any suffix to form $0$. We can do this in time $O(1)$ by keeping these prefix ORs. If $a_i = 1$, then $dp[i][j] = dp[i - 1][j] \\lor dp[i - 1][j - 1]$ (since $m \\ge 1$ we don't have to worry about accidentally allowing $0$s). This is because we can either multiply $a_{i-1}$ by $1$ or add $1$. Otherwise, note that we can only multiply together at most $\\log_2(j)$ many $a_i > 1$ before the result exceeds $j$. So, for each $i$ let $\\text{back}(i)$ denote the biggest $k < i$ such that $a_k \\neq 1$. Then, we can write $dp[i][j] = dp[i - 1][j - a_i] \\lor dp[\\text{back}(i) - 1][j - a_i \\cdot a_{\\text{back}(i)}] \\lor \\cdots$ where we continue until we either reach $i = 0$, hit $0$, or exceed $j$. $dp[i][j] = dp[i - 1][j - a_i] \\lor dp[\\text{back}(i) - 1][j - a_i \\cdot a_{\\text{back}(i)}] \\lor \\cdots$ There is one special case: if $a_k = 0$ for any $k < i$, then we should also allow $dp[i][j] |= dp[k - 1][j] \\lor dp[k - 2][j] \\lor \\cdots \\lor dp[0][j]$. We can keep track of the last time $a_k = 0$ and use the same prefix OR idea as above. Note that all of these operations are \"batch\" operations: that is, we can do them for all $j$ simultaneously for a given $i$. Thus, this gives a bitset solution in time $O(\\frac{nm\\log m}{w})$ and with space complexity $O(\\frac{nm}{w})$. However, this uses too much space. We can optimize the space complexity to only store $\\log_2(m) + 4$ bitsets (with some extra integers) instead. To do this, note that for the $0$ case we only require one bitset which we can update after each $i$, for the $1$ case we only have to keep the previous bitset, and for the $> 1$ case we only need to store the most recent $\\log_2(m)$ bitsets for indices $i$ with $a_{i+1} > 1$. We can keep this in a deque and pop from the back if the size exceeds $\\log_2(m)$. For the special case at the end, we can keep track of a prefix bitset for the last occurrence of a $0$. Overall, this uses space complexity $O(\\frac{m\\log_2 m}{w})$ which is sufficient (interestingly, we don't even have to store the input!)",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\nusing pii = pair<int, int>;\nusing vi = vector<int>;\n#define rep(i, a, b) for(int i = a; i < (b); ++i)\n#define all(x) (x).begin(), (x).end()\n#define sz(x) (int)(x).size()\n#define smx(a, b) a = max(a, b)\n#define smn(a, b) a = min(a, b)\n#define pb push_back\n#define endl '\\n'\n\nconst ll MOD = 1e9 + 7;\nconst ld EPS = 1e-9;\n\nmt19937 rng(time(0));\n\nconst int LOG = 14;\nconst int MAX = 10000 + 1;\n\nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n \n    int t; cin >> t;\n    while (t--) {\n        int n, m; cin >> n >> m;\n        bitset<MAX> prev(1), pfx(1), zero(0);\n        list<pair<int, bitset<MAX>>> q;\n        rep(i,0,n) {\n            int x; cin >> x;\n            bitset<MAX> curr = zero;\n\n            if (x == 0) {\n                curr |= pfx;\n                zero = curr;\n                q.push_front({0, prev});\n            } else if (x == 1) {\n                curr |= prev | (prev << 1);\n            } else {\n                int prod = 1;\n                q.push_front({x, prev});\n                for (auto const& val : q) {\n                    if (prod == 0 || prod * val.first > m) break;\n                    prod *= val.first;\n                    curr |= val.second << prod;\n                }\n            }\n            pfx |= curr;\n            prev = curr;\n            if (sz(q) > LOG) q.pop_back();\n        }\n\n        cout << (prev[m] ? \"YES\" : \"NO\") << \"\\n\";\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2029",
    "index": "A",
    "title": "Set",
    "statement": "You are given a positive integer $k$ and a set $S$ of all integers from $l$ to $r$ (inclusive).\n\nYou can perform the following two-step operation any number of times (possibly zero):\n\n- First, choose a number $x$ from the set $S$, such that there are at least $k$ multiples of $x$ in $S$ (including $x$ itself);\n- Then, remove $x$ from $S$ (note that nothing else is removed).\n\nFind the maximum possible number of operations that can be performed.",
    "tutorial": "Greedy from small to large. We can delete the numbers from small to large. Thus, previously removed numbers will not affect future choices (if $x<y$, then $x$ cannot be a multiple of $y$). So an integer $x$ ($l\\le x\\le r$) can be removed if and only if $k\\cdot x\\le r$, that is, $x\\le \\left\\lfloor\\frac{r}{k}\\right\\rfloor$. The answer is $\\max\\left(\\left\\lfloor\\frac{r}{k}\\right\\rfloor-l+1,0\\right)$. Time complexity: $\\mathcal{O}(1)$ per test case.",
    "code": "for _ in range(int(input())):\n    l, r, k = map(int, input().split())\n    print(max(r // k - l + 1, 0))",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2029",
    "index": "B",
    "title": "Replacement",
    "statement": "You have a binary string$^{\\text{∗}}$ $s$ of length $n$, and Iris gives you another binary string $r$ of length $n-1$.\n\nIris is going to play a game with you. During the game, you will perform $n-1$ operations on $s$. In the $i$-th operation ($1 \\le i \\le n-1$):\n\n- First, you choose an index $k$ such that $1\\le k\\le |s| - 1$ and $s_{k} \\neq s_{k+1}$. If it is impossible to choose such an index, you lose;\n- Then, you replace $s_ks_{k+1}$ with $r_i$. Note that this decreases the length of $s$ by $1$.\n\nIf all the $n-1$ operations are performed successfully, you win.\n\nDetermine whether it is possible for you to win this game.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string is a string where each character is either $\\mathtt{0}$ or $\\mathtt{1}$.\n\\end{footnotesize}",
    "tutorial": "($\\texttt{01}$ or $\\texttt{10}$ exists) $\\Longleftrightarrow$ (both $\\texttt{0}$ and $\\texttt{1}$ exist). Each time we do an operation, if $s$ consists only of $\\texttt{0}$ or $\\texttt{1}$, we surely cannot find any valid indices. Otherwise, we can always perform the operation successfully. In the $i$-th operation, if $t_i=\\texttt{0}$, we actually decrease the number of $\\texttt{1}$-s by $1$, and vice versa. Thus, we only need to maintain the number of $\\texttt{0}$-s and $\\texttt{1}$-s in $s$. If any of them falls to $0$ before the last operation, the answer is NO, otherwise, the answer is YES. Time complexity: $\\mathcal{O}(n)$ per test case.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    s = input()\n    one = s.count(\"1\")\n    zero = s.count(\"0\")\n    ans = \"YES\"\n    for ti in input():\n        if one == 0 or zero == 0:\n            ans = \"NO\"\n            break\n        one -= 1\n        zero -= 1\n        if ti == \"1\":\n            one += 1\n        else:\n            zero += 1\n    print(ans)",
    "tags": [
      "constructive algorithms",
      "games",
      "strings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2029",
    "index": "C",
    "title": "New Rating",
    "statement": "\\begin{quote}\n{{Hello, \\sout{Codeforces} Forcescode!}}\n\\end{quote}\n\nKevin used to be a participant of Codeforces. Recently, the KDOI Team has developed a new Online Judge called Forcescode.\n\nKevin has participated in $n$ contests on Forcescode. In the $i$-th contest, his performance rating is $a_i$.\n\nNow he has hacked into the backend of Forcescode and will select an interval $[l,r]$ ($1\\le l\\le r\\le n$), then skip all of the contests in this interval. After that, his rating will be recalculated in the following way:\n\n- Initially, his rating is $x=0$;\n- For each $1\\le i\\le n$, after the $i$-th contest,\n\n- If $l\\le i\\le r$, this contest will be skipped, and the rating will remain unchanged;\n- Otherwise, his rating will be updated according to the following rules:\n\n- If $a_i>x$, his rating $x$ will increase by $1$;\n- If $a_i=x$, his rating $x$ will remain unchanged;\n- If $a_i<x$, his rating $x$ will decrease by $1$.\n\nYou have to help Kevin to find his maximum possible rating after the recalculation if he chooses the interval $[l,r]$ optimally. Note that Kevin has to skip at least one contest.",
    "tutorial": "Binary search. Do something backward. First, do binary search on the answer. Suppose we're checking whether the answer can be $\\ge k$ now. Let $f_i$ be the current rating after participating in the $1$-st to the $i$-th contest (without skipping). Let $g_i$ be the minimum rating before the $i$-th contest to make sure that the final rating is $\\ge k$ (without skipping). $f_i$-s can be calculated easily by simulating the process in the statement. For $g_i$-s, it can be shown that $g_i= \\begin{cases} g_{i+1}-1, & a_i\\ge g_{i+1}\\\\ g_{i+1}+1, & a_i< g_{i+1} \\end{cases}$ where $g_{n+1}=k$. Then, we should check if there exists an interval $[l,r]$ ($1\\le l\\le r\\le n$), such that $f_{l-1}\\ge g_{r+1}$. If so, we can choose to skip $[l,r]$ and get a rating of $\\ge k$. Otherwise, it is impossible to make the rating $\\ge k$. We can enumerate on $r$ and use a prefix max to check whether valid $l$ exists. Time complexity: $\\mathcal{O}(n\\log n)$ per test case. Consider DP. There are only three possible states for each contest: before, in, or after the skipped interval. Consider $dp_{i,0/1/2}=$ the maximum rating after the $i$-th contest, where the $i$-th contest is before/in/after the skipped interval. Let $f(a,x)=$ the result rating when current rating is $a$ and the performance rating is $x$, then $\\begin{cases} dp_{i,0} = f(dp_{i-1,0}, a_i),\\\\ dp_{i,1} = \\max(dp_{i-1,1}, dp_{i-1,0}), \\\\ dp_{i,2} = \\max(f(dp_{i-1,1}, a_i), f(dp_{i-1,2}, a_i)). \\end{cases}$ And the final answer is $\\max(dp_{n,1}, dp_{n,2})$. Time complexity: $\\mathcal{O}(n)$ per test case.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    \n    def f(a, x):\n        return a + (a < x) - (a > x)\n    \n    dp = [0, -n, -n]\n    for x in map(int, input().split()):\n        dp[2] = max(f(dp[1], x), f(dp[2], x))\n        dp[1] = max(dp[1], dp[0])\n        dp[0] = f(dp[0], x)\n\n    print(max(dp[1], dp[2]))",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2029",
    "index": "D",
    "title": "Cool Graph",
    "statement": "You are given an undirected graph with $n$ vertices and $m$ edges.\n\nYou can perform the following operation at most $2\\cdot \\max(n,m)$ times:\n\n- Choose three distinct vertices $a$, $b$, and $c$, then for each of the edges $(a,b)$, $(b,c)$, and $(c,a)$, do the following:\n\n- If the edge does not exist, add it. On the contrary, if it exists, remove it.\n\nA graph is called cool if and only if one of the following holds:\n\n- The graph has no edges, or\n- The graph is a tree.\n\nYou have to make the graph cool by performing the above operations. Note that you can use at most $2\\cdot \\max(n,m)$ operations.\n\nIt can be shown that there always exists at least one solution.",
    "tutorial": "There are many different approaches to this problem. Only the easiest one (at least I think so) is shared here. Try to make the graph into a forest first. ($deg_i\\le 1$ for every $i$) $\\Longrightarrow$ (The graph is a forest). Let $d_i$ be the degree of vertex $i$. First, we keep doing the following until it is impossible: Choose a vertex $u$ with $d_u\\ge 2$, then find any two vertices $v,w$ adjacent to $u$. Perform the operation on $(u,v,w)$. Since each operation decreases the number of edges by at least $1$, at most $m$ operations will be performed. After these operations, $d_i\\le 1$ holds for every $i$. Thus, the resulting graph consists only of components with size $\\le 2$. If there are no edges, the graph is already cool, and we don't need to do any more operations. Otherwise, let's pick an arbitrary edge $(u,v)$ as the base of the final tree, and then merge everything else to it. For a component with size $=1$ (i.e. it is a single vertex $w$), perform the operation on $(u, v, w)$, and set $(u, v) \\gets (u, w)$. For a component with size $=2$ (i.e. it is an edge connecting $a$ and $b$), perform the operation on $(u, a, b)$. It is clear that the graph is transformed into a tree now. The total number of operations won't exceed $n+m\\le 2\\cdot \\max(n,m)$. In the author's solution, we used some data structures to maintain the edges, thus, the time complexity is $\\mathcal{O}(n+m\\log m)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#ifdef DEBUG\n#include \"debug.hpp\"\n#else\n#define debug(...) (void)0\n#endif\n\nusing i64 = int64_t;\nconstexpr bool test = false;\n\nint main() {\n  cin.tie(nullptr)->sync_with_stdio(false);\n  int t;\n  cin >> t;\n  for (int ti = 0; ti < t; ti += 1) {\n    int n, m;\n    cin >> n >> m;\n    vector<set<int>> adj(n + 1);\n    for (int i = 0, u, v; i < m; i += 1) {\n      cin >> u >> v;\n      adj[u].insert(v);\n      adj[v].insert(u);\n    }\n    vector<tuple<int, int, int>> ans;\n    for (int i = 1; i <= n; i += 1) {\n      while (adj[i].size() >= 2) {\n        int u = *adj[i].begin();\n        adj[i].erase(adj[i].begin());\n        int v = *adj[i].begin();\n        adj[i].erase(adj[i].begin());\n        adj[u].erase(i);\n        adj[v].erase(i);\n        ans.emplace_back(i, u, v);\n        if (adj[u].contains(v)) {\n          adj[u].erase(v);\n          adj[v].erase(u);\n        } else {\n          adj[u].insert(v);\n          adj[v].insert(u);\n        }\n      }\n    }\n    vector<int> s;\n    vector<pair<int, int>> p;\n    for (int i = 1; i <= n; i += 1) {\n      if (adj[i].size() == 0) {\n        s.push_back(i);\n      } else if (*adj[i].begin() > i) {\n        p.emplace_back(i, *adj[i].begin());\n      }\n    }\n    if (not p.empty()) {\n      auto [x, y] = p.back();\n      p.pop_back();\n      for (int u : s) {\n        ans.emplace_back(x, y, u);\n        tie(x, y) = pair(x, u);\n      }\n      for (auto [u, v] : p) {\n        ans.emplace_back(y, u, v);\n      }\n    }\n    println(\"{}\", ans.size());\n    for (auto [x, y, z] : ans) println(\"{} {} {}\", x, y, z);\n  }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2029",
    "index": "E",
    "title": "Common Generator",
    "statement": "For two integers $x$ and $y$ ($x,y\\ge 2$), we will say that $x$ is a generator of $y$ if and only if $x$ can be transformed to $y$ by performing the following operation some number of times (possibly zero):\n\n- Choose a divisor $d$ ($d\\ge 2$) of $x$, then increase $x$ by $d$.\n\nFor example,\n\n- $3$ is a generator of $8$ since we can perform the following operations: $3 \\xrightarrow{d = 3} 6 \\xrightarrow{d = 2} 8$;\n- $4$ is a generator of $10$ since we can perform the following operations: $4 \\xrightarrow{d = 4} 8 \\xrightarrow{d = 2} 10$;\n- $5$ is not a generator of $6$ since we cannot transform $5$ into $6$ with the operation above.\n\nNow, Kevin gives you an array $a$ consisting of $n$ pairwise distinct integers ($a_i\\ge 2$).\n\nYou have to find an integer $x\\ge 2$ such that for each $1\\le i\\le n$, $x$ is a generator of $a_i$, or determine that such an integer does not exist.",
    "tutorial": "$2$ is powerful. Consider primes. How did you prove that $2$ can generate every integer except odd primes? Can you generalize it? In this problem, we do not take the integer $1$ into consideration. Claim 1. $2$ can generate every integer except odd primes. Proof. For a certain non-prime $x$, let $\\operatorname{mind}(x)$ be the minimum divisor of $x$. Then $x-\\operatorname{mind}(x)$ must be an even number, which is $\\ge 2$. So $x-\\operatorname{mind}(x)$ can be generated by $2$, and $x$ can be generated by $x-\\operatorname{mind}(x)$. Thus, $2$ is a generator of $x$. Claim 2. Primes can only be generated by themselves. According to the above two claims, we can first check if there exist primes in the array $a$. If not, then $2$ is a common generator. Otherwise, let the prime be $p$, the only possible generator should be $p$ itself. So we only need to check whether $p$ is a generator of the rest integers. For an even integer $x$, it is easy to see that, $p$ is a generator of $x$ if and only if $x\\ge 2\\cdot p$. Claim 3. For a prime $p$ and an odd integer $x$, $p$ is a generator of $x$ if and only if $x - \\operatorname{mind}(x)\\ge 2\\cdot p$. Proof. First, $x-\\operatorname{mind}(x)$ is the largest integer other than $x$ itself that can generate $x$. Moreover, only even numbers $\\ge 2\\cdot p$ can be generated by $p$ ($x-\\operatorname{mind}(x)$ is even). That ends the proof. Thus, we have found a good way to check if a certain number can be generated from $p$. We can use the linear sieve to pre-calculate all the $\\operatorname{mind}(i)$-s. Time complexity: $\\mathcal{O}(\\sum n+V)$, where $V=\\max a_i$. Some other solutions with worse time complexity can also pass, such as $\\mathcal{O}(V\\log V)$ and $\\mathcal{O}(t\\sqrt{V})$.",
    "code": "#include <bits/stdc++.h>\n#define all(s) s.begin(), s.end()\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\n\nconst int _N = 4e5 + 5;\n\nint vis[_N], pr[_N], cnt = 0;\n\nvoid init(int n) {\n\tvis[1] = 1;\n\tfor (int i = 2; i <= n; i++) {\n\t\tif (!vis[i]) {\n\t\t\tpr[++cnt] = i;\n\t\t}\n\t\tfor (int j = 1; j <= cnt && i * pr[j] <= n; j++) {\n\t\t\tvis[i * pr[j]] = pr[j];\n\t\t\tif (i % pr[j] == 0) continue;\n\t\t}\n\t}\n}\n\nint T;\n\nvoid solve() {\n\tint n; cin >> n;\n\tvector<int> a(n + 1);\n\tfor (int i = 1; i <= n; i++) cin >> a[i];\n\tint p = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (!vis[a[i]]) p = a[i];\n\t}\n\tif (!p) {\n\t\tcout << 2 << '\\n';\n\t\treturn;\n\t}\n\tfor (int i = 1; i <= n; i++) {\n\t\tif (a[i] == p) continue;\n\t\tif (vis[a[i]] == 0) {\n\t\t\tcout << -1 << '\\n';\n\t\t\treturn;\n\t\t}\n\t\tif (a[i] & 1) {\n\t\t\tif (a[i] - vis[a[i]] < 2 * p) {\n\t\t\t\tcout << -1 << '\\n';\n\t\t\t\treturn;\n\t\t\t}\n\t\t} else {\n\t\t\tif (a[i] < 2 * p) {\n\t\t\t\tcout << -1 << '\\n';\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tcout << p << '\\n';\n\treturn;\n}\n\nint main() {\n\tios::sync_with_stdio(false), cin.tie(0), cout.tie(0);\n\tinit(400000);\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2029",
    "index": "F",
    "title": "Palindrome Everywhere",
    "statement": "You are given a cycle with $n$ vertices numbered from $0$ to $n-1$. For each $0\\le i\\le n-1$, there is an undirected edge between vertex $i$ and vertex $((i+1)\\bmod n)$ with the color $c_i$ ($c_i=R$ or $B$).\n\nDetermine whether the following condition holds for every pair of vertices $(i,j)$ ($0\\le i<j\\le n-1$):\n\n- There exists a palindrome route between vertex $i$ and vertex $j$. Note that the route may \\textbf{not} be simple. Formally, there must exist a sequence $p=[p_0,p_1,p_2,\\ldots,p_m]$ such that:\n\n- $p_0=i$, $p_m=j$;\n- For each $0\\leq x\\le m-1$, either $p_{x+1}=(p_x+1)\\bmod n$ or $p_{x+1}=(p_{x}-1)\\bmod n$;\n- For each $0\\le x\\le y\\le m-1$ satisfying $x+y=m-1$, the edge between $p_x$ and $p_{x+1}$ has the same color as the edge between $p_y$ and $p_{y+1}$.",
    "tutorial": "If there are both consecutive $\\texttt{R}$-s and $\\texttt{B}$-s, does the condition hold for all $(i,j)$? Why? Suppose that there are only consecutive $\\texttt{R}$-s, check the parity of the number of $\\texttt{R}$-s in each consecutive segment of $\\texttt{R}$-s. If for each consecutive segment of $\\texttt{R}$-s, the parity of the number of $\\texttt{R}$-s is odd, does the condition hold for all $(i,j)$? Why? If for at least two of the consecutive segments of $\\texttt{R}$-s, the parity of the number of $\\texttt{R}$-s is even, does the condition hold for all $(i,j)$? Why? Is this the necessary and sufficient condition? Why? Don't forget some trivial cases like $\\texttt{RRR...RB}$ and $\\texttt{RRR...R}$. For each $k>n$ or $k\\leq0$, let $c_k$ be $c_{k\\bmod n}$. Lemma 1: If there are both consecutive $\\texttt{R}$-s and $\\texttt{B}$-s, the answer is NO. Proof 1: Suppose that $c_{i-1}=c_i=\\texttt{R}$ and $c_{j-1}=c_j=\\texttt{B}$, it's obvious that there doesn't exist a palindrome route between $i$ and $j$. Imagine there are two persons on vertex $i$ and $j$. They want to meet each other (they are on the same vertex or adjacent vertex) and can only travel through an edge of the same color. Lemma 2: Suppose that there are only consecutive $\\texttt{R}$-s, if for each consecutive segment of $\\texttt{R}$-s, the parity of the number of $\\texttt{R}$-s is odd, the answer is NO. Proof 2: Suppose that $c_i=c_j=\\texttt{B}$, $i\\not\\equiv j\\pmod n$ and $c_{i+1}=c_{i+2}=\\dots=c_{j-1}=\\texttt{R}$. The two persons on $i$ and $j$ have to \"cross\" $\\texttt{B}$ simultaneously. As for each consecutive segment of $\\texttt{R}$-s, the parity of the number of $\\texttt{R}$-s is odd, they can only get to the same side of their current consecutive segment of $\\texttt{R}$-s. After \"crossing\" $\\texttt{B}$, they will still be on different consecutive segments of $\\texttt{R}$-s separated by exactly one $\\texttt{B}$ and can only get to the same side. Thus, they will never meet. Lemma 3: Suppose that there are only consecutive $\\texttt{R}$-s, if, for at least two of the consecutive segments of $\\texttt{R}$-s, the parity of the number of $\\texttt{R}$-s is even, the answer is NO. Proof 3: Suppose that $c_i=c_j=\\texttt{B}$, $i\\not\\equiv j \\pmod n$ and vertex $i$ and $j$ are both in a consecutive segment of $\\texttt{R}$-s with even number of $\\texttt{R}$-s. Let the starting point of two persons be $i$ and $j-1$ and they won't be able to \"cross\" and $\\texttt{B}$. Thus, they will never meet. The only case left is that there is exactly one consecutive segment of $\\texttt{R}$-s with an even number of $\\texttt{R}$-s. Lemma 4: Suppose that there are only consecutive $\\texttt{R}$-s, if, for exactly one of the consecutive segments of $\\texttt{R}$-s, the parity of the number of $\\texttt{R}$-s is even, the answer is YES. Proof 4: Let the starting point of the two persons be $i,j$. Consider the following cases: Case 1: If vertex $i$ and $j$ are in the same consecutive segment of $\\texttt{R}$-s, the two persons can meet each other by traveling through the $\\texttt{R}$-s between them. Case 2: If vertex $i$ and $j$ are in the different consecutive segment of $\\texttt{R}$-s and there are odd numbers of $\\texttt{R}$-s in both segments, the two person may cross $\\texttt{B}$-s in the way talked about in Proof 2. However, when one of them reaches a consecutive segment with an even number of $\\texttt{R}$-s, the only thing they can do is let the one in an even segment cross the whole segment and \"cross\" the next $\\texttt{B}$ in the front, while letting the other one traveling back and forth and \"cross\" the $\\texttt{B}$ he just \"crossed\". Thus, unlike the situation in Proof 2, we successfully changed the side they can both get to and thus they will be able to meet each other as they are traveling toward each other and there are only odd segments between them. Case 3: If vertex $i$ and $j$ are in the different consecutive segment of $\\texttt{R}$-s and there are an odd number of $\\texttt{R}$-s in exactly one of the segments, we can let both of them be in one side of there segments and change the situation to the one we've discussed about in Case 2 (when one of them reached a consecutive segment with even number of $\\texttt{R}$-s). As a result, the answer is YES if: At least $n-1$ of $c_1,c_2,\\dots,c_n$ are the same (Hint 6), or Suppose that there are only consecutive $\\texttt{R}$-s, there's exactly one of the consecutive segments of $\\texttt{R}$-s such that the parity of the number of $\\texttt{R}$-s is even. And we can judge them in $\\mathcal{O}(n)$ time complexity. Count the number of strings of length $n$ satisfying the condition. Solve the problem for $c_i\\in\\{\\texttt{A},\\texttt{B},\\dots,\\texttt{Z}\\}$, and solve the counting version.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nvoid solve(){\n\tint n; cin>>n;\n\tstring s; cin>>s;\n\tint visr=0,visb=0,ok=0; \n\tfor(int i=0;i<n;i++){\n\t\tif(s[i]==s[(i+1)%n]){\n\t\t\tif(s[i]=='R') visr=1;\n\t\t\telse visb=1;\n\t\t\tok++;\n\t\t}\n\t}\n\tif(visr&visb){\n\t\tcout<<\"NO\\n\";\n\t\treturn ;\n\t}\n\tif(ok==n){\n\t\tcout<<\"YES\\n\";\n\t\treturn ;\n\t}\n\tif(visb) for(int i=0;i<n;i++) s[i]='R'+'B'-s[i];\n\tint st=0;\n\tfor(int i=0;i<n;i++) if(s[i]=='B') st=(i+1)%n;\n\tvector<int> vc;\n\tint ntot=0,cnt=0;\n\tfor(int i=0,j=st;i<n;i++,j=(j+1)%n){\n\t\tif(s[j]=='B') vc.push_back(ntot),cnt+=(ntot&1)^1,ntot=0;\n\t\telse ntot++;\n\t}\n\tif(vc.size()==1||cnt==1){\n\t\tcout<<\"YES\\n\";\n\t\treturn ;\n\t}\n\tcout<<\"NO\\n\";\n\treturn ;\n}\nsigned main(){\n\tint t; cin>>t;\n\twhile(t--) solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2029",
    "index": "G",
    "title": "Balanced Problem",
    "statement": "There is an array $a$ consisting of $n$ integers. Initially, all elements of $a$ are equal to $0$.\n\nKevin can perform several operations on the array. Each operation is one of the following two types:\n\n- Prefix addition — Kevin first selects an index $x$ ($1\\le x\\le n$), and then for each $1\\le j\\le x$, increases $a_j$ by $1$;\n- Suffix addition — Kevin first selects an index $x$ ($1\\le x\\le n$), and then for each $x\\le j\\le n$, increases $a_j$ by $1$.\n\nIn the country of KDOI, people think that the integer $v$ is balanced. Thus, Iris gives Kevin an array $c$ consisting of $n$ integers and defines the beauty of the array $a$ as follows:\n\n- Initially, set $b=0$;\n- For each $1\\le i\\le n$, if $a_i=v$, add $c_i$ to $b$;\n- The beauty of $a$ is the final value of $b$.\n\nKevin wants to maximize the beauty of $a$ after all the operations. However, he had already performed $m$ operations when he was sleepy. Now, he can perform an arbitrary number (possibly zero) of new operations.\n\nYou have to help Kevin find the maximum possible beauty if he optimally performs the new operations.\n\nHowever, to make sure that you are not just rolling the dice, Kevin gives you an integer $V$, and you need to solve the problem for each $1\\le v\\le V$.",
    "tutorial": "This problem has two approaches. The first one is the authors' solution, and the second one was found during testing. The array $a$ is constructed with the operations. How can we use this property? If we want to make all $a_i=x$, what is the minimum value of $x$? Use the property mentioned in Hint 1. (For the subproblem in Hint 2), try to find an algorithm related to the positions of $\\texttt{L/R}$-s directly. (For the subproblem in Hint 2), the conclusion is that, the minimum $x$ equals $\\text{# of }\\texttt{L}\\text{-s} + \\text{# of }\\texttt{R}\\text{-s} - \\text{# of adjacent }\\texttt{LR}\\text{-s}$. Think why. Go for DP. Read the hints first. Then, note that there are only $\\mathcal{O}(V)$ useful positions: If (after the initial operations) $a_i>V$ or $a_{i}=a_{i-1}$, we can simply ignore $a_i$, or merge $c_i$ into $c_{i-1}$. Now let $dp(i,s)$ denote the answer when we consider the prefix of length $i$, and we have \"saved\" $s$ pairs of $\\texttt{LR}$. Then, $dp(i,s)=\\displaystyle\\max_{j< i} dp(j,s-|\\mathrm{cntL}(j,i-1)-\\mathrm{cntR}(j+1,i)|)+c_i$ Write $\\mathrm{cntL}$ and $\\mathrm{cntR}$ as prefix sums: $dp(i,s)=\\displaystyle\\max_{j< i} dp(j,s-|\\mathrm{preL}(i-1)-\\mathrm{preR}(i)+\\mathrm{preR}(j)-\\mathrm{preL}(j-1)|)+c_i$ Do casework on the sign of the things inside the $\\mathrm{abs}$, and you can maintain both cases with 1D Fenwick trees. Thus, you solved the problem in $\\mathcal{O}(V^2\\log V)$. Solve the problem for a single $v$ first. Don't think too much, just go straight for a DP solution. Does your time complexity in DP contain $n$ or $m$? In fact, both $n$ and $m$ are useless. There are only $\\mathcal{O}(V)$ useful positions. Use some data structures to optimize your DP. Even $\\mathcal{O}(v^2\\log^2 v)$ is acceptable. Here is the final step: take a look at your DP carefully. Can you change the definition of states a little, so that it can get the answer for each $1\\le v\\le V$? First, note that there are only $\\mathcal{O}(V)$ useful positions: If (after the initial operations) $a_i>V$ or $a_{i}=a_{i-1}$, we can simply ignore $a_i$, or merge $c_i$ into $c_{i-1}$. Now, let's solve the problem for a single $v$. Denote $dp(i,j,k)$ as the maximum answer when considering the prefix of length $i$, and there are $j$ prefix additions covering $i$, $k$ suffix additions covering $i$. Enumerate on $i$, and it is easy to show that the state changes if and only if $j+k+a_i=v$, and $dp(i,j,k)=\\displaystyle\\max_{p\\le j,q\\ge k} dp(i-1,p,q) + c_i$ You can use a 2D Fenwick tree to get the 2D prefix max. Thus, you solved the single $v$ case in $\\mathcal{O}(v^2\\log^2 v)$. In fact, we can process the DP in $\\mathcal{O}(v^2 \\log v)$ by further optimization: $dp(i,j,k)=\\displaystyle\\max_{p\\le i-1,q\\ge j,v-a_p-q\\le k} dp(p,q,v-a_p-q) + c_i$ This only requires $a_p+q\\ge a_i+j$ when $a_p\\le a_i$, and $q\\le j$ when $a_p\\ge a_i$. So you can use 1D Fenwick trees to process the dp in $\\mathcal{O}(v^2 \\log v)$. Now, let's go for the whole solution. Let's modify the DP state a bit: now $dp(i,j,k)$ is the state when using $v-k$ suffix operations (note that $v$ is not a constant here). The transformation is similar. Then the answer for $v=i$ will be $\\max dp(*,*,i)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define pb push_back\n#define pii pair<int, int>\n#define all(a) a.begin(), a.end()\nconst int mod = 1e9 + 7, N = 5005;\n\nvoid solve() {\n    int n, m, V;\n    cin >> n >> m >> V;\n    vector <int> c(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> c[i];\n    }\n    vector <int> pre(n + 1);\n    for (int i = 0; i < m; ++i) {\n        char x; int v; cin >> x >> v, --v;\n        if (x == 'L') {\n            pre[0]++, pre[v + 1]--;\n        } else {\n            pre[v]++;\n        }\n    }\n    for (int i = 0; i < n; ++i) {\n        pre[i + 1] += pre[i];\n    }\n    vector <pair <ll, int>> vec;\n    for (int i = 0, j = 0; i < n; i = j) {\n        ll tot = 0;\n        while (j < n && pre[i] == pre[j]) {\n            tot += c[j], j++;\n        }\n        if (pre[i] <= V) {\n            vec.emplace_back(tot, pre[i]);\n        }\n    }\n\n    vector bit(V + 5, vector <ll>(V + 5, -1ll << 60));\n    auto upd = [&](int x, int y, ll v) {\n        for (int i = x + 1; i < V + 5; i += i & (-i)) {\n            for (int j = y + 1; j < V + 5; j += j & (-j)) {\n                bit[i][j] = max(bit[i][j], v);\n            }\n        }\n    };\n    auto query = [&](int x, int y) {\n        ll ans = -1ll << 60;\n        for (int i = x + 1; i > 0; i -= i & (-i)) {\n            for (int j = y + 1; j > 0; j -= j & (-j)) {\n                ans = max(ans, bit[i][j]);\n            }\n        }\n        return ans;\n    };\n\n    upd(0, 0, 0);\n    vector <ll> tmp(V + 1);\n    for (auto [val, diff] : vec) {\n        for (int i = 0; i + diff <= V; ++i) {\n            tmp[i] = query(i, i + diff);\n        }\n        for (int i = 0; i + diff <= V; ++i) {\n            upd(i, i + diff, tmp[i] + val);\n        }\n    }\n\n    for (int i = 1; i <= V; ++i) {\n        cout << query(i, i) << \" \\n\"[i == V];\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false), cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2029",
    "index": "H",
    "title": "Message Spread",
    "statement": "Given is an undirected graph with $n$ vertices and $m$ edges. Each edge connects two vertices $(u, v)$ and has a probability of $\\frac{p}{q}$ of appearing each day.\n\nInitially, vertex $1$ has a message. At the end of the day, a vertex has a message if and only if itself or at least one of the vertices adjacent to it had the message the day before. Note that each day, each edge chooses its appearance independently.\n\nCalculate the expected number of days before all the vertices have the message, modulo $998\\,244\\,353$.",
    "tutorial": "It's hard to calculate the expected number. Try to change it to the probability. Consider a $\\mathcal{O}(3^n)$ dp first. Use inclusion and exclusion. Write out the transformation. Try to optimize it. Let $dp_S$ be the probability such that exactly the points in $S$ have the message. The answer is $\\sum dp_S\\cdot tr_S$, where $tr_S$ is the expected number of days before at least one vertex out of $S$ to have the message (counting from the day that exactly the points in $S$ have the message). For transformation, enumerate $S,T$ such that $S\\cap T=\\varnothing$. Transfer $dp_S$ to $dp_{S\\cup T}$. It's easy to precalculate the coefficient, and the time complexity differs from $\\mathcal{O}(3^n)$, $\\mathcal{O}(n\\cdot 3^n)$ to $\\mathcal{O}(n^2\\cdot 3^n)$, according to the implementation. The transformation is hard to optimize. Enumerate $T$ and calculate the probability such that vertices in $S$ is only connected with vertices in $T$, which means that the real status $R$ satisfies $S\\subseteq R\\subseteq (S\\cup T)$. Use inclusion and exclusion to calculate the real probability. List out the coefficient: $\\frac{\\displaystyle\\prod_{e\\in\\{1,2,3,\\dots,n\\}}(1-w_e)\\cdot\\prod_{e\\in(S\\cup T)}\\frac{1}{1-w_e}\\cdot\\prod_{e\\in \\{1,2,\\dots,n\\}\\setminus S}\\frac{1}{1-w_e}\\cdot\\prod_{e\\in T}(1-w_e)}{\\displaystyle1-\\prod_{e\\in\\{1,2,3,\\dots,n\\}}(1-w_e)\\cdot\\prod_{e\\in S}\\frac{1}{1-w_e}\\cdot\\prod_{e\\in\\{1,2,3,\\dots,n\\}\\setminus S}\\frac{1}{1-w_e}}$ (Note that $w_e$ denotes the probability of the appearance of the edge $e$) We can express it as $\\mathrm{Const}\\cdot f_{S\\cup T}\\cdot g_S\\cdot h_T$. Use a subset convolution to optimize it. The total time complexity is $\\mathcal{O}(2^n\\cdot n^2)$. It's easy to see that all $dp_S\\neq0$ satisfies $1\\in S$, so the time complexity can be $\\mathcal{O}(2^{n-1}\\cdot n^2)$ if well implemented.",
    "code": "#include <bits/stdc++.h>\n#define int long long \nusing namespace std;\nconst int N=(1<<21),mod=998244353;\nconst int Lim=8e18;\ninline void add(signed &i,int j){\n\ti+=j;\n\tif(i>=mod) i-=mod;\n}\nint qp(int a,int b){\n\tint ans=1;\n\twhile(b){\n\t\tif(b&1) (ans*=a)%=mod;\n\t\t(a*=a)%=mod;\n\t\tb>>=1;\n\t}\n\treturn ans;\n}\nint dp[N],f[N],g[N],h[N];\nint s1[N],s2[N];\nsigned pre[22][N/2],t[22][N/2],pdp[N][22];\nint p[N],q[N],totp,totq;\nsigned main(){\n\tint n,m; cin>>n>>m;\n\tint totprod=1;\n\tfor(int i=0;i<(1<<n);i++) s1[i]=s2[i]=1;\n\tfor(int i=1;i<=m;i++){\n\t\tint u,v,p,q; cin>>u>>v>>p>>q;\n\t\tint w=p*qp(q,mod-2)%mod;\n\t\t(s1[(1<<(u-1))+(1<<(v-1))]*=(mod+1-w))%=mod;\n\t\t(s2[(1<<(u-1))+(1<<(v-1))]*=qp(mod+1-w,mod-2))%=mod;\n\t\t(totprod*=(mod+1-w))%=mod;\n\t}\n\tfor(int j=1;j<=n;j++) for(int i=0;i<(1<<n);i++) if((i>>(j-1))&1) (s1[i]*=s1[i^(1<<(j-1))])%=mod,(s2[i]*=s2[i^(1<<(j-1))])%=mod;\n\tfor(int i=0;i<(1<<n);i++) f[i]=s2[i],g[i]=totprod*s2[((1<<n)-1)^i]%mod*qp(mod+1-totprod*s2[i]%mod*s2[((1<<n)-1)^i]%mod,mod-2)%mod,h[i]=s1[i];\n\tfor(int i=1;i<(1<<n);i++) pre[__builtin_popcount(i)][i>>1]=h[i];\n\tdp[1]=1;\n\tfor(int j=1;j<=n;j++){\n\t\tif(!((1>>(j-1))&1)) add(pdp[1|(1<<(j-1))][j],mod-(dp[1]*g[1]%mod*f[1]%mod));\n\t}\n\tt[0][0]=dp[1]*g[1]%mod;\n\tfor(int k=1;k<=n;k++) for(int j=1;j<n;j++) for(int i=0;i<(1<<(n-1));i++) if((i>>(j-1))&1) add(pre[k][i],pre[k][i^(1<<(j-1))]);\n\tfor(int j=1;j<n;j++) for(int i=0;i<(1<<(n-1));i++) if((i>>(j-1))&1) add(t[0][i],t[0][i^(1<<(j-1))]);\n\tfor(int k=1;k<n;k++){\n\t\ttotp=totq=0;\n\t\tfor(int i=0;i<(1<<(n-1));i++) if(__builtin_popcount(i)<=k) p[++totp]=i; else q[++totq]=i;\n\t\tfor(int l=1,i=p[l];l<=totp;l++,i=p[l]) for(int j=0;j<k;j++) add(t[k][i],1ll*t[j][i]*pre[k-j][i]%mod);\n\t\tfor(int i=0;i<(1<<(n-1));i++) t[k][i]%=mod;\n\t\tfor(int j=1;j<n;j++) for(int l=1,i=p[l];l<=totp;l++,i=p[l]) if((i>>(j-1))&1) add(t[k][i],mod-t[k][i^(1<<(j-1))]);\n\t\tfor(int i=0;i<(1<<(n-1));i++){\n\t\t\tif(__builtin_popcount(i)==k){\n\t\t\t\tadd(pdp[(i<<1)|1][0],t[k][i]*f[(i<<1)|1]%mod);\n\t\t\t\tint pre=0;\n\t\t\t\tfor(int j=1;j<=n;j++){\n\t\t\t\t\t(pre+=pdp[(i<<1)|1][j-1])%=mod;\n\t\t\t\t\tif(!((((i<<1)|1)>>(j-1))&1)) add(pdp[(i<<1)|1|(1<<(j-1))][j],mod-pre);\n\t\t\t\t}\n\t\t\t\t(pre+=pdp[(i<<1)|1][n])%=mod;\n\t\t\t\tdp[(i<<1)|1]=pre;\n\t\t\t\tfor(int j=1;j<=n;j++){\n\t\t\t\t\tif(!((((i<<1)|1)>>(j-1))&1)) add(pdp[(i<<1)|1|(1<<(j-1))][j],mod-(dp[(i<<1)|1]*g[(i<<1)|1]%mod*f[(i<<1)|1]%mod));\n\t\t\t\t}\n\t\t\t\tt[k][i]=pre*g[(i<<1)|1]%mod;\n\t\t\t}\n\t\t\telse t[k][i]=0;\n\t\t}\n\t\tfor(int j=1;j<n;j++) for(int l=1,i=q[l];l<=totq;l++,i=q[l]) if((i>>(j-1))&1) add(t[k][i],t[k][i^(1<<(j-1))]);\n\t}\n\tint ans=0;\n\tfor(int i=1;i<(1<<n)-1;i+=2) (ans+=dp[i]*qp(mod+1-totprod*s2[i]%mod*s2[((1<<n)-1)^i]%mod,mod-2)%mod)%=mod;\n\tcout<<ans;\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2029",
    "index": "I",
    "title": "Variance Challenge",
    "statement": "Kevin has recently learned the definition of variance. For an array $a$ of length $n$, the variance of $a$ is defined as follows:\n\n- Let $x=\\dfrac{1}{n}\\displaystyle\\sum_{i=1}^n a_i$, i.e., $x$ is the mean of the array $a$;\n- Then, the variance of $a$ is $$ V(a)=\\frac{1}{n}\\sum_{i=1}^n(a_i-x)^2. $$\n\nNow, Kevin gives you an array $a$ consisting of $n$ integers, as well as an integer $k$. You can perform the following operation on $a$:\n\n- Select an interval $[l,r]$ ($1\\le l\\le r\\le n$), then for each $l\\le i\\le r$, increase $a_i$ by $k$.\n\nFor each $1\\le p\\le m$, you have to find the minimum possible variance of $a$ after exactly $p$ operations are performed, independently for each $p$.\n\nFor simplicity, you only need to output the answers multiplied by $n^2$. It can be proven that the results are always integers.",
    "tutorial": "The intended solution has nothing to do with dynamic programming. This is the key observation of the problem. Suppose we have an array $b$ and a function $f(x)=\\sum (b_i-x)^2$, then the minimum value of $f(x)$ is the variance of $b$. Using the observation mentioned in Hint 2, we can reduce the problem to minimizing $\\sum(a_i-x)^2$ for a given $x$. There are only $\\mathcal{O}(n\\cdot m)$ possible $x$-s. The rest of the problem is somehow easy. Try flows, or just find a greedy algorithm! If you are trying flows: the quadratic function is always convex. Key Observation. Suppose we have an array $b$ and a function $f(x)=\\sum (b_i-x)^2$, then the minimum value of $f(x)$ is the variance of $b$. Proof. This is a quadratic function of $x$, and the its symmetry axis is $x=\\frac{1}{n}\\sum b_i$. So the minimum value is $f\\left(\\frac{1}{n}\\sum b_i\\right)$. That is exactly the definition of variance. Thus, we can enumerate all possible $x$-s, and find the minimum $\\sum (a_i-x)^2$ after the operations, then take the minimum across them. That will give the correct answer to the original problem. Note that there are only $\\mathcal{O}(n\\cdot m)$ possible $x$-s. More formally, let $k_{x,c}$ be the minimum value of $\\sum (a_i-x)^2$ after exactly $c$ operations. Then $\\mathrm{ans}_i=\\displaystyle\\min_{\\text{any possible }x} k_{x,i}$. So we only need to solve the following (reduced) problem: Given a (maybe non-integer) number $x$. For each $1\\le i\\le m$, find the minimum value of $\\sum (a_i-x)^2$ after exactly $i$ operations. To solve this, we can use the MCMF model: Set a source node $s$ and a target node $t$. For each $1\\le i\\le n$, add an edge from $s$ to $i$ with cost $0$. For each $1\\le i\\le n$, add an edge from $i$ to $t$ with cost $0$. For each $1\\le i< n$, add an edge from $i$ to $i+1$ with cost being a function $\\mathrm{cost}(f)=(a_i+f-x)^2-(a_i-x)^2$, where $f$ is the flow on this edge. Note that the $\\mathrm{cost}$ function is convex, so this model is correct, as you can split an edge into some edges with cost of $\\mathrm{cost}(1)$, $\\mathrm{cost}(2)-\\mathrm{cost}(1)$, $\\mathrm{cost}(3)-\\mathrm{cost}(2)$, and so on. Take a look at the model again. We don't need to run MCMF. We can see that it is just a process of regret greedy. So you only need to find the LIS (Largest Interval Sum :) ) for each operation. Thus, we solved the reduced problem in $\\mathcal{O(n\\cdot m)}$. Overall time complexity: $\\mathcal{O}((n\\cdot m)^2)$ per test case. Reminder: don't forget to use __int128 if you didn't handle the numbers carefully!",
    "code": "#include <bits/stdc++.h>\n#define all(s) s.begin(), s.end()\nusing namespace std;\nusing ll = long long;\nusing ull = unsigned long long;\n\nconst int _N = 1e5 + 5;\n\nint T;\n\nvoid solve() {\n\tll n, m, k; cin >> n >> m >> k;\n\tvector<ll> a(n + 1);\n\tfor (int i = 1; i <= n; i++) cin >> a[i];\n\tvector<ll> kans(m + 1, LLONG_MAX);\n\tvector<__int128> f(n + 1), g(n + 1), v(n + 1);\n\tvector<int> vis(n + 1), L(n + 1), L2(n + 1);\n\tll sum = 0;\n\tfor (int i = 1; i <= n; i++) sum += a[i];\n\t__int128 pans = 0;\n\tfor (int i = 1; i <= n; i++) pans += n * a[i] * a[i];\n\tauto work = [&](ll s) {\n\t\t__int128 ans = pans;\n\t\tans += s * s - 2ll * sum * s;\n\t\tf.assign(n + 1, LLONG_MAX);\n\t\tg.assign(n + 1, LLONG_MAX);\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tv[i] = n * (2 * a[i] * k + k * k) - 2ll * s * k;\n\t\t\tvis[i] = 0;\n\t\t}\n\t\tfor (int i = 1; i <= m; i++) {\n\t\t\tfor (int j = 1; j <= n; j++) {\n\t\t\t\tL[j] = L2[j] = j;\n\t\t\t\tif (f[j - 1] < 0) f[j] = f[j - 1] + v[j], L[j] = L[j - 1];\n\t\t\t\telse f[j] = v[j];\n\t\t\t\tif (!vis[j]) {\n\t\t\t\t\tg[j] = LLONG_MAX;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (g[j - 1] < 0) g[j] = g[j - 1] + 2ll * n * k * k - v[j], L2[j] = L2[j - 1];\n\t\t\t\telse g[j] = 2ll * n * k * k - v[j];\n\t\t\t}\n\t\t\t__int128 min_sum = LLONG_MAX;\n\t\t\tint l = 1, r = n, type = 0;\n\t\t\tfor (int j = 1; j <= n; j++) {\n\t\t\t\tif (f[j] < min_sum) {\n\t\t\t\t\tmin_sum = f[j], r = j, l = L[j];\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int j = 1; j <= n; j++) {\n\t\t\t\tif (g[j] < min_sum) {\n\t\t\t\t\tmin_sum = g[j], r = j, l = L2[j];\n\t\t\t\t\ttype = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tans += min_sum;\n\t\t\tif (type == 0) {\n\t\t\t\tfor (int j = l; j <= r; j++) vis[j]++, v[j] += 2 * n * k * k;\n\t\t\t} else {\n\t\t\t\tfor (int j = l; j <= r; j++) vis[j]--, v[j] -= 2 * n * k * k;\n\t\t\t}\n\t\t\tkans[i] = min((__int128)kans[i], ans);\n\t\t}\n\t};\n\t\n\tfor (ll x = sum; x <= sum + n * m * k; x += k) {\n\t\twork(x);\n\t}\n\tfor (int i = 1; i <= m; i++) cout << kans[i] << \" \\n\"[i == m];\n\treturn;\n}\n\nint main() {\n\tios::sync_with_stdio(false), cin.tie(0), cout.tie(0);\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "flows",
      "graphs",
      "greedy"
    ],
    "rating": 3400
  },
  {
    "contest_id": "2030",
    "index": "A",
    "title": "A Gift From Orangutan",
    "statement": "While exploring the jungle, you have bumped into a rare orangutan with a bow tie! You shake hands with the orangutan and offer him some food and water. In return...\n\nThe orangutan has gifted you an array $a$ of length $n$. Using $a$, you will construct two arrays $b$ and $c$, both containing $n$ elements, in the following manner:\n\n- $b_i = \\min(a_1, a_2, \\ldots, a_i)$ for each $1 \\leq i \\leq n$.\n- $c_i = \\max(a_1, a_2, \\ldots, a_i)$ for each $1 \\leq i \\leq n$.\n\nDefine the score of $a$ as $\\sum_{i=1}^n c_i - b_i$ (i.e. the sum of $c_i - b_i$ over all $1 \\leq i \\leq n$). Before you calculate the score, you can \\textbf{shuffle} the elements of $a$ however you want.\n\nFind the maximum score that you can get if you shuffle the elements of $a$ optimally.",
    "tutorial": "First, what is the maximum possible value of $c_i-b_j$ for any $i,j$? Since $c_i$ is the maximum element of some subset of $a$ and $b_i$ is the minimum element of some subset of $a$, the maximum possible value of $c_i-b_j$ is $max(a)-min(a)$. Also note that $c_1=b_1$ for any reordering of $a$. By reordering such that the largest element of $a$ appears first and the smallest element of $a$ appears second, the maximum possible value of the score is achieved. This results in a score of $(max(a)-min(a))\\cdot(n-1)$.",
    "code": "for i in range(int(input())):\n    n = int(input())\n    mx = 0\n    mn= 1000000\n    lst = input().split()\n    for j in range(n):\n        x = int(lst[j])\n        mx = max(mx, x)\n        mn = min(mn, x)\n    print((mx-mn)*(n-1))",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2030",
    "index": "B",
    "title": "Minimise Oneness",
    "statement": "For an arbitrary binary string $t$$^{\\text{∗}}$, let $f(t)$ be the number of non-empty subsequences$^{\\text{†}}$ of $t$ that contain only $\\mathtt{0}$, and let $g(t)$ be the number of non-empty subsequences of $t$ that contain at least one $\\mathtt{1}$.\n\nNote that for $f(t)$ and for $g(t)$, each subsequence is counted as many times as it appears in $t$. E.g., $f(\\mathtt{000}) = 7, g(\\mathtt{100}) = 4$.\n\nWe define the oneness of the binary string $t$ to be $|f(t)-g(t)|$, where for an arbitrary integer $z$, $|z|$ represents the absolute value of $z$.\n\nYou are given a positive integer $n$. Find a binary string $s$ of length $n$ such that its oneness is as small as possible. If there are multiple strings, you can print any of them.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string is a string that only consists of characters $0$ and $1$.\n\n$^{\\text{†}}$A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements. For example, subsequences of $\\mathtt{1011101}$ are $\\mathtt{0}$, $\\mathtt{1}$, $\\mathtt{11111}$, $\\mathtt{0111}$, but not $\\mathtt{000}$ nor $\\mathtt{11100}$.\n\\end{footnotesize}",
    "tutorial": "Observation: $f(t)-g(t)$ is odd. Proof: $f(t)+g(t)$ is the set of all non-empty subsets of $t$, which is $2^{|t|}-1$, which is odd. The sum and difference of two integers has the same parity, so $f(t)-g(t)$ is always odd. By including exactly one $1$ in the string $s$, we can make $f(s)=2^{n-1}-1$ and $g(s)=2^{n-1}$, or $f(s)-g(s)=1$ by the multiplication principle. Clearly, this is the best we can do. So, we print out any string with exactly one $1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--) {\n        int n;\n        cin >> n;\n        cout << '1';\n        for(int i = 1; i < n; i++) cout << '0';\n        cout << endl;\n    }\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "games",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2030",
    "index": "C",
    "title": "A TRUE Battle",
    "statement": "Alice and Bob are playing a game. There is a list of $n$ booleans, each of which is either true or false, given as a binary string $^{\\text{∗}}$ of length $n$ (where $1$ represents true, and $0$ represents false). Initially, there are no operators between the booleans.\n\nAlice and Bob will take alternate turns placing and or or between the booleans, with Alice going first. Thus, the game will consist of $n-1$ turns since there are $n$ booleans. Alice aims for the final statement to evaluate to true, while Bob aims for it to evaluate to false. Given the list of boolean values, determine whether Alice will win if both players play optimally.\n\nTo evaluate the final expression, repeatedly perform the following steps until the statement consists of a single true or false:\n\n- If the statement contains an and operator, choose any one and replace the subexpression surrounding it with its evaluation.\n- Otherwise, the statement contains an or operator. Choose any one and replace the subexpression surrounding the or with its evaluation.\n\nFor example, the expression true or false and false is evaluated as true or (false and false) $=$ true or false $=$ true. It can be shown that the result of any compound statement is unique.\\begin{footnotesize}\n$^{\\text{∗}}$A binary string is a string that only consists of characters $0$ and $1$\n\\end{footnotesize}",
    "tutorial": "Let's understand what Alice wants to do. She wants to separate a statement that evaluates to true between two or's. This guarantees her victory since or is evaluated after all and's. First, if the first or last boolean is true, then Alice instantly wins by placing or between the first and second, or second to last and last booleans. Otherwise, if there are two true's consecutively, Alice can also win. Alice may place or before the first of the two on her first move. If Bob does not put his operator between the two true's, then Alice will put an or between the two true's on her next move and win. Otherwise, Bob does place his operator between the two true's. However, no matter what Bob placed, the two true's will always evaluate to true, so on her second move Alice can just place an or on the other side of the two true's to win. We claim these are the only two cases where Alice wins. This is because otherwise, there does not contain two true's consecutively. Now, whenever Alice places an or adjacent to a true, Bob will respond by placing and after the true, which will invalidate this clause to be false.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        vector<int> v(n);\n        for(int i = 0; i < n; i++) {\n            if(s[i]=='1') v[i]=1;\n        }\n        bool win = false;\n        if(v[0]||v[n-1]) win=true;\n        for(int i = 1; i < n; i++) {\n            if(v[i]&&v[i-1]) win=true;\n        }\n        if(win) cout << \"YES\" << endl;\n        else cout << \"NO\" << endl;\n    }\n}",
    "tags": [
      "brute force",
      "games",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2030",
    "index": "D",
    "title": "QED's Favorite Permutation",
    "statement": "QED is given a permutation$^{\\text{∗}}$ $p$ of length $n$. He also has a string $s$ of length $n$ containing only characters $L$ and $R$. QED only likes permutations that are sorted in non-decreasing order. To sort $p$, he can select any of the following operations and perform them any number of times:\n\n- Choose an index $i$ such that $s_i = L$. Then, swap $p_i$ and $p_{i-1}$. It is guaranteed that $s_1 \\neq L$.\n- Choose an index $i$ such that $s_i = R$. Then, swap $p_i$ and $p_{i+1}$. It is guaranteed that $s_n \\neq R$.\n\nHe is also given $q$ queries. In each query, he selects an index $i$ and changes $s_i$ from $L$ to $R$ (or from $R$ to $L$). Note that the changes are \\textbf{persistent}.\n\nAfter each query, he asks you if it is possible to sort $p$ in non-decreasing order by performing the aforementioned operations any number of times. Note that before answering each query, the permutation $p$ is reset to its original form.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "Observation: Through a series of swaps, we can swap an element from position $i$ to position $j$ (WLOG, assume $i < j$) if there is no such $k$ such that $i \\leq k < j$ such that $s_k = \\texttt{L}$ and $s_{k+1} = \\texttt{R}$. Let's mark all indices $i$ such that $s_i = \\texttt{L}$ and $s_{i+1} = \\texttt{R}$ as bad. If $pos_i$ represents the position of $i$ in $p$, then we must make sure it is possible to swap from $\\min(i, pos_i)$ to $\\max(i, pos_i)$. As you can see, we can model these conditions as intervals. We must make sure there are no bad indices included in any intervals. We need to gather indices $i$ such that $i$ is included in at least one interval. This can be done with difference array. Let $d_i$ denote the number of intervals that include $i$. If $d_i > 0$, then we need to make sure $i$ is not a bad index. We can keep all bad indices in a set. Notice that when we update $i$, we can only potentially toggle indices $i$ and $i-1$ from good to bad (or vice versa). For example, if $s_i = \\texttt{L}$, $s_i = \\texttt{R}$, $d_i > 0$ and index $i$ is not in the bad set, then we will insert it. After each query, if the bad set is empty, then the answer is \"YES\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--) {\n        int n,q;\n        cin >> n >> q;\n        vector<int> perm(n);\n        for(int i = 0; i < n; i++) cin >> perm[i];\n        for(int i = 0; i < n; i++) perm[i]--;\n        vector<int> invperm(n);\n        for(int i = 0; i < n; i++) invperm[perm[i]]=i;\n        vector<int> diffArr(n);\n        for(int i = 0; i < n; i++) {\n            diffArr[min(i, invperm[i])]++;\n            diffArr[max(i, invperm[i])]--;\n        }\n        for(int i = 1; i < n; i++) diffArr[i]+=diffArr[i-1];\n        string s;\n        cin >> s;\n        set<int> problems;\n        for(int i = 0; i < n-1; i++) {\n            if(s[i]=='L'&&s[i+1]=='R'&&diffArr[i]!=0) {\n                problems.insert(i);\n            } \n        }\n        while(q--) {\n            int x;\n            cin >> x;\n            x--;\n            if(s[x]=='L') {\n                s[x]='R';\n            } else {\n                s[x]='L';\n            }\n            if(s[x-1]=='L'&&s[x]=='R'&&diffArr[x-1]!=0) {\n                problems.insert(x-1);\n            } else {\n                problems.erase(x-1);\n            }\n            if(s[x]=='L'&&s[x+1]=='R'&&diffArr[x]!=0) {\n                problems.insert(x);\n            } else {\n                problems.erase(x);\n            }\n            if(problems.size()) {\n                cout << \"NO\" << endl;\n            } else {\n                cout << \"YES\" << endl;\n            }\n        }\n    }\n}",
    "tags": [
      "data structures",
      "implementation",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2030",
    "index": "E",
    "title": "MEXimize the Score",
    "statement": "Suppose we partition the elements of an array $b$ into any number $k$ of non-empty multisets $S_1, S_2, \\ldots, S_k$, where $k$ is an arbitrary positive integer. Define the score of $b$ as the maximum value of $\\operatorname{MEX}(S_1)$$^{\\text{∗}}$$ + \\operatorname{MEX}(S_2) + \\ldots + \\operatorname{MEX}(S_k)$ over all possible partitions of $b$ for any integer $k$.\n\nEnvy is given an array $a$ of size $n$. Since he knows that calculating the score of $a$ is too easy for you, he instead asks you to calculate the sum of scores of all $2^n - 1$ non-empty subsequences of $a$.$^{\\text{†}}$ Since this answer may be large, please output it modulo $998\\,244\\,353$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\operatorname{MEX}$ of a collection of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $x$ that does not occur in the collection $c$. For example, $\\operatorname{MEX}([0,1,2,2]) = 3$ and $\\operatorname{MEX}([1,2,2]) = 0$\n\n$^{\\text{†}}$A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deleting several (possibly, zero or all) elements.\n\\end{footnotesize}",
    "tutorial": "Observation: The score of $b$ is equivalent to $f_0$ + $\\min(f_0, f_1)$ + $\\ldots$ + $\\min(f_0, \\ldots, f_{n-1})$ where $f_i$ stores the frequency of integer $i$ in $b$. Intuition: We can greedily construct the $k$ arrays by repeating this step: Select the minimum $j$ such that $f_j = 0$ and $\\min(f_0, \\ldots f_{j-1}) > 0$, and construct the array $[0, 1, \\ldots, j-1]$. This is optimal because every element we add will increase the MEX by $1$, which will increase the score by $1$. If we add $j$, the MEX will not increase. Also, when we add an element, we cannot increase the score by more than $1$. Adding less than $j$ elements cannot increase MEX for future arrays. From this observation, we can see that only the frequency array of $a$ matters. From now on, let's denote the frequency of $i$ in $a$ as $f_i$. We can find the sum over all subsequences using dynamic programming. Let's denote $dp[i][j]$ as the number of subsequences containing only the first $i$ integers and $min(f_0, \\ldots, f_i) = j$. Initially, $dp[0][i] = \\binom{f_0}{i}$. To transition, we need to consider two cases: In the first case, let's assume $j < \\min(f_0, \\ldots, f_{i-1})$. The number of subsequences that can be created is $(\\sum_{k=j+1}^n dp[i-1][k]) \\cdot \\binom{f_i}{j}$. That is, all the subsequences from previous length such that it is possible for $j$ to be the new minimum, multiplied by the number of subsequences where $f_i = j$. In the second case, let's assume $j \\geq \\min(f_0, \\ldots, f_{i-1})$. The number of subsequences that can be created is $(\\sum_{k=j}^{f_i} \\binom{f_i}{k}) \\cdot dp[i-1][j]$. That is, all subsequences containing at least $j$ elements of $i$, multiplied by all previous subsequences with minimum already equal to $j$. The total score is $dp[i][j] \\cdot j \\cdot 2^{f_{i+1} + \\dots + f_{n-1}}$ over the length of the prefix $i$ and prefix minimum $j$. We can speed up the calculations for both cases using suffix sums, however, this still yields an $O(n^2)$ algorithm. However, $j$ is bounded to the interval $[1, f_i]$ for each $i$. Since the sum of $f_i$ is $n$, the total number of secondary states is $n$. This becomes just a constant factor, so the total complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n#define int long long\n#define ll long long \n#define pii pair<int,int> \n#define piii pair<pii,pii>\n#define fi first\n#define se second\n#pragma GCC optimize(\"O3,unroll-loops\")\n#pragma GCC target(\"avx2,bmi,bmi2,lzcnt,popcnt\")\nusing namespace std;\n\nconst int MX = 2e5;\nll fact[MX+1];\nll ifact[MX+1];\nll MOD=998244353;\n \nll binPow(ll base, ll exp) {\n    ll ans = 1;\n    while(exp) {\n        if(exp%2) {\n            ans = (ans*base)%MOD;\n        }\n        base = (base*base)%MOD;\n        exp /= 2;\n    }\n    return ans;\n}\n \nint nCk(int N, int K) {\n    if(K>N||K<0) {\n        return 0;\n    }\n    return (fact[N]*((ifact[K]*ifact[N-K])%MOD))%MOD;\n}\n \nvoid ICombo() {\n\tfact[0] = 1;\n    for(int i=1;i<=MX;i++) {\n        fact[i] = (fact[i-1]*i)%MOD;\n    }    \n    ifact[MX] = binPow(fact[MX],MOD-2);\n    for(int i=MX-1;i>=0;i--) {\n        ifact[i] = (ifact[i+1]*(i+1))%MOD;\n    }\n}\n\nvoid solve() {\n    int n, ans=0; cin >> n;\n    vector<int> c(n);\n    for (int r:c) {\n        cin >> r; c[r]++; \n    }\n    vector<vector<int>> dp(n,vector<int>(1));\n    vector<int> ps, co; \n    for (int i = 1; i <= c[0]; i++) dp[0].push_back(nCk(c[0],i));\n    for (int i = 1; i < n; i++) {\n        ps.resize(1); co=ps; \n        for (int r:dp[i-1]) ps.push_back((ps.back()+r)%MOD); \n        int m=ps.size()-1;\n        dp[i].resize(min(m,c[i]+1));\n        for (int j = 0; j <= c[i]; j++) co.push_back((co.back()+nCk(c[i],j))%MOD);\n        for (int j = 1; j < dp[i].size(); j++) dp[i][j]=nCk(c[i],j)*(ps[m]-ps[j]+MOD)%MOD+(co.back()-co[j+1]+MOD)*dp[i-1][j]%MOD; \n    }\n    int j=0;\n    for (auto r:dp) {\n        n-=c[j++];\n        for (int i = 1; i < r.size(); i++) (ans+=i*r[i]%MOD*binPow(2,n))%=MOD;\n    }\n    cout << ans << \"\\n\"; \n}\n\nint32_t main() {\n\tios::sync_with_stdio(0); cin.tie(0);\n        ICombo();\n\tint t = 1; cin >> t;\n\twhile (t--) solve();\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2030",
    "index": "F",
    "title": "Orangutan Approved Subarrays",
    "statement": "Suppose you have an array $b$. Initially, you also have a set $S$ that contains all distinct elements of $b$. The array $b$ is called orangutan-approved if it can be \\textbf{emptied} by repeatedly performing the following operation:\n\n- In one operation, select indices $l$ and $r$ ($1 \\leq l \\leq r \\leq |b|$) such that $v = b_l = b_{l+1} = \\ldots = b_r$ and $v$ is present in $S$. Remove $v$ from $S$, and simultaneously remove all $b_i$ such that $l \\leq i \\leq r$. Then, reindex the elements $b_{r+1}, b_{r+2}, \\ldots$ as $b_l, b_{l+1}, \\ldots$ accordingly.\n\nYou are given an array $a$ of length $n$ and $q$ queries.\n\nEach query consists of two indices $l$ and $r$ ($1 \\le l \\le r \\le n$), and you need to determine whether or not the subarray $a_{l}, a_{l+1}, \\ldots, a_r$ is orangutan-approved.",
    "tutorial": "First, let's try to find whether a single array is orangutan-approved or not. Claim: The array $b$ of size $n$ is not orangutan-approved if and only if there exists indices $1\\leq w < x < y < z \\leq n$ such that $b_w=b_y$, $b_x=b_z$, and $b_w\\neq b_x$. Proof: Let's prove this with strong induction. For $n=0$, the claim is true because the empty array is orangutan-approved. Now, let's suppose that the claim is true for all $m < n$. Now, let $s$ be a sorted sequence such that $x$ is in $s$ if and only if $b_x=b_1$. Suppose $s$ is length $k$. We can split the array $b$ into disjoint subarrays $c_1, c_2, \\ldots, c_k$ such that $c_i$ is the subarray $b[s_i+1\\ldots s_{i+1}-1]$ for all $1 \\leq i < k$ and $c_k=b[s_k+1\\ldots n]$ That is, $c_i$ is the subarray that lies between each occurrence of $b_1$ in the array $b$. First, we note that the set of unique elements of $c_i$ and $c_j$ cannot contain any elements in common for all $i\\neq j$. This is because suppose that there exists $i$ and $j$ such that $i < j$ and the set of unique values in $c_i$ and $c_j$ both contain $y$. Then, in the original array $b$, there must exist a subsequence $b_1, y, b_1, y$. This makes our premise false. By our inductive claim, each of the arrays $c_1, c_2, \\ldots, c_k$ must be orangutan-approved. Since there are no overlapping elements, we may delete each of the arrays $c_1, c_2, \\ldots, c_k$ separately. Finally, the array $b$ is left with $k$ copies of $b_1$, and we can use one operation to delete all remaining elements in the array $b$. Now, how do we solve for all queries? First, precompute the array $last$, which is the array containing for each $i$ the largest index $j<i$ such that $a[j]=a[i]$. Let's then use two pointers to compute the last element $j<i$ such that $a[j\\ldots i]$ is orangutan-approved but $a[j-1\\ldots i]$ is not, and store this in an array called $left$. Let's also keep a maximum segment tree $next$ such that $next[i]$ is the first element $j>i$ such that $a_j=a_i$. As we sweep from $i-1$ to $i$, we do the following: Set $L=left[i-1]$ Set $L=left[i-1]$ Otherwise, while $\\max(next[L...last[i]-1]>last[i]$ and $last[i]\\neq-1$), increment $L$ by $1$. Otherwise, while $\\max(next[L...last[i]-1]>last[i]$ and $last[i]\\neq-1$), increment $L$ by $1$. Set $left[i]=L$ Set $left[i]=L$ When the $left$ array is fully calculated, we can solve each query in $O(1)$.",
    "code": "#pragma GCC optimize(\"Ofast\")\n \n#include <bits/stdc++.h> \nusing namespace std;\n#define ll long long\n#define nline \"\\n\"\n#define f first\n#define s second\n#define sz(x) x.size()\n#define all(x) x.begin(),x.end()\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nconst ll INF_ADD=1e18;\nconst ll MOD=1e9+7;\nconst ll MAX=1048579;\nclass ST {\npublic:\n    vector<ll> segs;\n    ll size = 0;\n    ll ID = 0;\n \n    ST(ll sz) {\n        segs.assign(2 * sz, ID);\n        size = sz;  \n    }   \n   \n    ll comb(ll a, ll b) {\n        return max(a, b);  \n    }\n \n    void upd(ll idx, ll val) {\n        segs[idx += size] = val;\n        for(idx /= 2; idx; idx /= 2) segs[idx] = comb(segs[2 * idx], segs[2 * idx + 1]);\n    }\n \n    ll query(ll l, ll r) {\n        ll lans = ID, rans = ID;\n        for(l += size, r += size + 1; l < r; l /= 2, r /= 2) {\n            if(l & 1) lans = comb(lans, segs[l++]);\n            if(r & 1) rans = comb(segs[--r], rans);\n        }\n        return comb(lans, rans);\n    }\n}; \nvoid solve(){\n  ll n,q,l=1; cin>>n>>q;\n  ST track(n+5);\n  vector<ll> a(n+5),last(n+5,0),lft(n+5);\n  for(ll i=1;i<=n;i++){\n    cin>>a[i];\n    ll till=last[a[i]];\n    while(track.query(l,till)>=till+1){\n      l++;\n    }\n    if(till){\n      track.upd(till,i);\n    }\n    lft[i]=l;\n    last[a[i]]=i;\n  }\n  while(q--) {\n    ll l,r; cin>>l>>r;\n    if(lft[r]<=l){\n      cout<<\"YES\\n\";\n    } \n    else{\n      cout<<\"NO\\n\";\n    }\n  }\n}\nint main()                                                                                 \n{         \n  ios_base::sync_with_stdio(false);                         \n  cin.tie(NULL);                                  \n  ll test_cases=1;                 \n  cin>>test_cases;\n  while(test_cases--){\n    solve();\n  }\n} ",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2030",
    "index": "G2",
    "title": "The Destruction of the Universe (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, $n \\leq 10^6$. You can only make hacks if both versions of the problem are solved.}\n\nOrangutans are powerful beings—so powerful that they only need $1$ unit of time to destroy every vulnerable planet in the universe!\n\nThere are $n$ planets in the universe. Each planet has an interval of vulnerability $[l, r]$, during which it will be exposed to destruction by orangutans. Orangutans can also expand the interval of vulnerability of any planet by $1$ unit.\n\nSpecifically, suppose the expansion is performed on planet $p$ with interval of vulnerability $[l_p, r_p]$. Then, the resulting interval of vulnerability may be either $[l_p - 1, r_p]$ or $[l_p, r_p + 1]$.\n\nGiven a set of planets, orangutans can destroy all planets if the intervals of vulnerability of all planets in the set intersect at least one common point. Let the score of such a set denote the minimum number of expansions that must be performed.\n\nOrangutans are interested in the sum of \\textbf{scores} of all non-empty subsets of the planets in the universe. As the answer can be large, output it modulo $998\\,244\\,353$.",
    "tutorial": "To find the score of a set of intervals $([l_1, r_1], [l_2, r_2], \\ldots, [l_v, r_v])$, we follow these steps: Initially, the score is set to $0$. We perform the following process repeatedly: Let $x$ be the interval with the smallest $r_i$ among all active intervals. Let $y$ be the interval with the largest $l_i$ among all active intervals. If $r_x < l_y$, add $l_y - r_x$ to the score, mark intervals $x$ and $y$ as inactive, and continue the process. If $r_x \\geq l_y$, stop the process. At the end of this process, all active intervals will intersect at least one common point. Now, we need to prove that the process indeed gives us the minimum possible score. We can prove this by induction. Let $S$ be some set of intervals, and let $x$ and $y$ be the intervals defined above. Consider the set $S' = S \\setminus {x, y}$ (i.e., $S'$ is the set $S$ excluding $x$ and $y$). We claim that: $\\text{score}(S) \\geq \\text{score}(S') + \\text{distance}(x, y)$ This is true because, for $x$ and $y$ to intersect, we must perform at least $\\text{distance}(x, y)$ operations. Our construction achieves the lower bound of $\\text{score}(S') + \\text{distance}(x, y)$. Thus, $\\text{score}(S) = \\text{score}(S') + \\text{distance}(x, y)$ During the process, we pair some intervals (possibly none). Specifically, in the $k$-th step, we pair the interval with the $k$-th smallest $r_i$ with the interval having the $k$-th largest $l_j$, and add the distance between them to the score. In the problem G1, we can compute the contribution of each pair of intervals as follows: Suppose we consider a pair $(i, j)$. Without loss of generality, assume that $r_i < l_j$. The pair $(i, j)$ will be considered in some subset $S$ if there are exactly $x$ intervals $p$ such that $r_p < r_i$ and exactly $x$ intervals $p$ such that $l_p > l_j$, for some non-negative integer $x$. Let there be $g$ intervals $p$ such that $r_p < r_i$ and $h$ intervals $p$ such that $l_p > l_j$. For $(i, j)$ to be paired in some subset $S$, we must choose $x$ intervals from the $g$ intervals on the left and $x$ intervals from the $h$ intervals on the right, for some non-negative integer $x$. There are no restrictions on the remaining $n - 2 - g - h$ intervals. Therefore, the contribution of $(i, j)$ is: $\\sum_{x = 0}^{g} (l_j - r_i) \\cdot \\binom{g}{x} \\cdot \\binom{h}{x} \\cdot 2^{n - 2 - g - h}$ We can simplify this sum using the identity: $\\sum_{x = 0}^{g} \\binom{g}{x} \\cdot \\binom{h}{x} = \\binom{g + h}{g}$ (This is a form of the Vandermonde Identity.) Thus, the contribution of $(i, j)$ becomes: $(l_j - r_i) \\cdot \\binom{g + h}{g} \\cdot 2^{n - 2 - g - h}$ This can be computed in $O(1)$ time. Note that in the explanation above, we assumed that the interval endpoints are distinct for simplicity. If they are not, we can order the intervals based on their $l_i$ values to maintain consistency. Let us find the contribution of $r[i]$, the right endpoint of $i$-th interval. Let $x$ be the number of intervals $j$ such that $r[j] < r[i]$, and let $y$ be the number of intervals $j$ such that $l[j] > r[i]$. To determine the contribution of $r[i]$ to the final answer, we consider selecting $p$ intervals from the $x$ intervals to the left and $q$ intervals from the $y$ intervals to the right, with the constraint that $p < q$. We require $p < q$ so that interval $i$ is paired with some other interval on the right (as discussed in the solution for G1). Therefore, the contribution of $r[i]$ can be expressed as: $\\text{Contribution} = -r[i] \\cdot \\text{ways}(x, y) \\cdot 2^{n - 1 - x - y}$ Here, $\\text{ways}(x, y)$ represents the number of valid selections where $p < q$. Calculating $\\text{ways}(x, y)$ To compute $\\text{ways}(x, y)$, we can use the Vandermonde identity to simplify the expression: $\\text{ways}(x, y) = \\sum_{\\substack{0 \\leq p < q \\leq y}} \\binom{x}{p} \\binom{y}{q}$ This can be rewritten as: $\\text{ways}(x, y) = \\sum_{p=0}^{x} \\sum_{k=1}^{y} \\binom{x}{p} \\binom{y}{p + k}$ Define the function $g(k)$ as: $g(k) = \\sum_{p=0}^{x} \\binom{x}{p} \\binom{y}{p + k}$ By applying the Vandermonde identity, we get: $g(k) = \\binom{x + y}{x + k}$ Thus, the total number of ways is: $\\text{ways}(x, y) = \\sum_{k=1}^{y} \\binom{x + y}{x + k}$ We can simplify this summation using the property of binomial coefficients: $\\text{ways}(x, y) = 2^{x + y} - h(x + y, x)$ where the function $h(p, q)$ is defined as: $h(p, q) = \\sum_{i=0}^{q} \\binom{p}{i}$ Efficient Computation of $h(p, q)$ Note that: $h(p, q) = 2 \\cdot h(p - 1, q) - \\binom{p - 1}{q}$ Suppose throughout the solution, we call the function $h(p, q)$ $d$ times for pairs $(p_1, q_1), (p_2, q_2), \\ldots, (p_d, q_d)$, in that order. We can observe that: $\\sum_{i=2}^{d} |p_i - p_{i-1}| + |q_i - q_{i-1}| = O(n)$ Since $h(p_i, q_i)$ can be computed from $h(p_{i-1}, q_{i-1})$ in $|p_i - p_{i-1}| + |q_i - q_{i-1}|$ operations, the amortized time complexity for this part is $O(n)$. Final Contribution Combining the above results, the contribution of $r[i]$ to the answer is: $-r[i] \\cdot \\left(2^{x + y} - h(x + y, x)\\right) \\cdot 2^{n - 1 - x - y}$ A similar calculation can be applied to the contribution of $l[i]$. By summing these contributions across all relevant intervals, we obtain the final answer.",
    "code": "\n#pragma GCC optimize(\"Ofast\")\n \n#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\n#define ld long double\n#define nline \"\\n\"\n#define f first\n#define s second\n#define sz(x) (ll)x.size()\n#define vl vector<ll>\nconst ll INF_MUL=1e13;\nconst ll INF_ADD=1e18;\n#define all(x) x.begin(),x.end()\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\ntypedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\n//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------     \nconst ll MOD=998244353;\nconst ll MAX=5000500;\nvector<ll> fact(MAX+2,1),inv_fact(MAX+2,1);\nll binpow(ll a,ll b,ll MOD){\n    ll ans=1;\n    a%=MOD;  \n    while(b){\n        if(b&1)\n            ans=(ans*a)%MOD;\n        b/=2;\n        a=(a*a)%MOD;\n    }\n    return ans;\n}\nll inverse(ll a,ll MOD){\n    return binpow(a,MOD-2,MOD);\n} \nvoid precompute(ll MOD){\n    for(ll i=2;i<MAX;i++){\n        fact[i]=(fact[i-1]*i)%MOD;\n    }\n    inv_fact[MAX-1]=inverse(fact[MAX-1],MOD);\n    for(ll i=MAX-2;i>=0;i--){\n        inv_fact[i]=(inv_fact[i+1]*(i+1))%MOD;\n    }\n}\nll nCr(ll a,ll b,ll MOD){\n    if((a<0)||(a<b)||(b<0))\n        return 0;   \n    ll denom=(inv_fact[b]*inv_fact[a-b])%MOD;\n    return (denom*fact[a])%MOD;  \n}\nll l[MAX],r[MAX],power[MAX];\nll ans=0,on_left=0,on_right,len;\nll x=0,y=0,ways=0,inv2;\nll getv(){\n  while(x>=len+1){\n    ways=((ways+nCr(x-1,y,MOD))*inv2)%MOD;\n    x--;\n  }\n  while(x<=len-1){\n    ways=(2ll*ways-nCr(x,y,MOD)+MOD)%MOD;\n    x++;\n  }\n  while(y<=on_left-1){\n    ways=(ways+nCr(x,y+1,MOD))%MOD;\n    y++;\n  }\n  return ways;\n}\nvoid solve(){ \n  ll n; cin>>n;\n  power[0]=1;\n  vector<array<ll,2>> track;\n  multiset<ll> consider;\n  for(ll i=1;i<=n;i++){\n    cin>>l[i]>>r[i];\n    track.push_back({r[i],l[i]});\n    consider.insert(l[i]);\n    power[i]=(power[i-1]*2ll)%MOD;\n  }\n  ans=on_left=0;\n  on_right=len=n;\n  x=y=0; ways=1;\n  sort(all(track));\n  for(auto it:track){\n    while(!consider.empty()){\n      if(*consider.begin() <= it[0]){\n        consider.erase(consider.begin());\n        on_right--,len--;\n      }\n      else{\n        break;\n      }\n    }\n    ll now=power[len]-getv();\n    now=(now*power[n-1-len])%MOD;\n    now=(now*it[0])%MOD;\n    ans=(ans+MOD-now)%MOD;\n    on_left++,len++;\n  }\n  track.clear(); consider.clear();\n  for(ll i=1;i<=n;i++){\n    track.push_back({l[i],r[i]});\n    consider.insert(r[i]);\n  }\n  sort(all(track));\n  reverse(all(track));\n  on_left=0;\n  on_right=len=n;\n  x=y=0; ways=1;\n  for(auto it:track){\n    while(!consider.empty()){\n      if(*(--consider.end()) >= it[0]){\n        consider.erase(--consider.end());\n        on_right--,len--;\n      }\n      else{\n        break;\n      }\n    }\n    ll now=power[len]-getv();\n    now=(now*power[n-1-len])%MOD;\n    now=(now*it[0])%MOD;\n    ans=(ans+now)%MOD;\n    on_left++,len++;\n  }\n  ans=(ans+MOD)%MOD;\n  cout<<ans<<nline;\n  return;    \n}  \nint main()                                                                                 \n{         \n  ios_base::sync_with_stdio(false);                         \n  cin.tie(NULL);                              \n  ll test_cases=1;                 \n  cin>>test_cases;\n  precompute(MOD);\n  inv2=inverse(2,MOD);\n  while(test_cases--){\n    solve();\n  }\n  cout<<fixed<<setprecision(12);  \n  cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n} ",
    "tags": [
      "combinatorics",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2031",
    "index": "A",
    "title": "Penchick and Modern Monument",
    "statement": "Amidst skyscrapers in the bustling metropolis of Metro Manila, the newest Noiph mall in the Philippines has just been completed! The construction manager, Penchick, ordered a state-of-the-art monument to be built with $n$ pillars.\n\nThe heights of the monument's pillars can be represented as an array $h$ of $n$ positive integers, where $h_i$ represents the height of the $i$-th pillar for all $i$ between $1$ and $n$.\n\nPenchick wants the heights of the pillars to be in \\textbf{non-decreasing} order, i.e. $h_i \\le h_{i + 1}$ for all $i$ between $1$ and $n - 1$. However, due to confusion, the monument was built such that the heights of the pillars are in \\textbf{non-increasing} order instead, i.e. $h_i \\ge h_{i + 1}$ for all $i$ between $1$ and $n - 1$.\n\nLuckily, Penchick can modify the monument and do the following operation on the pillars as many times as necessary:\n\n- Modify the height of a pillar to any positive integer. Formally, choose an index $1\\le i\\le n$ and a positive integer $x$. Then, assign $h_i := x$.\n\nHelp Penchick determine the minimum number of operations needed to make the heights of the monument's pillars \\textbf{non-decreasing}.",
    "tutorial": "Consider the maximum number of pillars that can be left untouched instead. Under what conditions can $k>1$ pillars be untouched? Note that if pillars $i$ and $j$ with different heights are both untouched, then the first pillar must be taller than the second, which contradicts the fact that the heights must be non-decreasing after the adjustment. Thus, all unadjusted pillars must be of the same height. Therefore, the required number of pillars to adjust is $n-k$, where $k$ is the maximum number of pillars with the same height $h$. This bound is reachable by, for example, adjusting all pillars to height $h$. To find $k$, we can go through each index $i$ and find the number of pillars with the same height as $i$; this gives $O(n^2)$ time complexity, which is good enough for this problem. Alternatively, you can use a frequency array or std::map, or sequentially go through the list and find the longest sequence of equal terms, all of which have better time complexities.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve(){\n    int n;\n \n    cin >> n;\n \n    vector<int> arr(n);\n \n    for(auto &x : arr) cin >> x;\n \n    int ans = 0, cnt = 1;\n \n    for(int i = 1; i < n; i++){\n        if(arr[i] == arr[i - 1]) cnt++;\n        else{\n            ans = max(ans, cnt);\n            cnt = 1;\n        }\n    }\n \n    ans = max(ans, cnt);\n \n    cout << n - ans << \"\\n\";\n}\n \nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int t;\n \n    cin >> t;\n \n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2031",
    "index": "B",
    "title": "Penchick and Satay Sticks",
    "statement": "Penchick and his friend Kohane are touring Indonesia, and their next stop is in Surabaya!\n\nIn the bustling food stalls of Surabaya, Kohane bought $n$ satay sticks and arranged them in a line, with the $i$-th satay stick having length $p_i$. It is given that $p$ is a permutation$^{\\text{∗}}$ of length $n$.\n\nPenchick wants to sort the satay sticks in increasing order of length, so that $p_i=i$ for each $1\\le i\\le n$. For fun, they created a rule: they can only swap neighboring satay sticks whose lengths differ by exactly $1$. Formally, they can perform the following operation any number of times (including zero):\n\n- Select an index $i$ ($1\\le i\\le n-1$) such that $|p_{i+1}-p_i|=1$;\n- Swap $p_i$ and $p_{i+1}$.\n\nDetermine whether it is possible to sort the permutation $p$, thus the satay sticks, by performing the above operation.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "Consider which permutations you can get by reversing the operations and starting from the identity permutation After $p_i$ and $p_{i+1}$ have been swapped, i.e. $p_i=i+1$ and $p_{i+1}=i$, neither of them can then be involved in another different swap. Suppose we begin with the identity permutation. Consider what happens after swapping $p_i=i$ and $p_{i+1}=i+1$. After this swap, elements $p_1$ to $p_{i-1}$ will consist of $1$ to $i-1$, and $p_{i+2}$ to $p_n$ will consist of $i+2$ to $n$. Thus, it is impossible for $p_i=i+1$ to swap with $p_{i-1}\\lt i$, or for $p_{i+1}=i$ to swap with $p_{i+2}\\gt i+1$. Therefore, the swaps made must be independent of each other; in other words, the indices $i$ chosen in the process must differ from each other than at least $2$. These permutations satisfy the following: for each index $i$, $p_i=i$, or $p_i=i+1$ and $p_{i+1}=i$, or $p_i=i-1$ and $p_{i-1}=i$. One way to check for this is to iterate for $i$ from $1$ to $n$. If $p_i=i$ then continue, and if $p_i=i+1$ then check if $p_{i+1}=i$, then swap $p_i$ and $p_{i+1}$. Otherwise, the permutation cannot be sorted. Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve(){\n    int n;\n \n    cin >> n;\n \n    vector<int> arr(n);\n \n    for(auto &x : arr) cin >> x;\n \n    for(int i = 0; i < n - 1; i++){\n        if(arr[i] != i + 1){\n            if(arr[i + 1] == i + 1 && arr[i] == i + 2) swap(arr[i], arr[i + 1]);\n            else{\n                cout << \"NO\\n\";\n                return;\n            }\n        }\n    }\n \n    cout << \"YES\\n\";\n}\n \nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n \n    int t;\n \n    cin >> t;\n \n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "greedy",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "2031",
    "index": "C",
    "title": "Penchick and BBQ Buns",
    "statement": "Penchick loves two things: square numbers and Hong Kong-style BBQ buns! For his birthday, Kohane wants to combine them with a gift: $n$ BBQ buns arranged from left to right. There are $10^6$ available fillings of BBQ buns, numbered from $1$ to $10^6$. To ensure that Penchick would love this gift, Kohane has a few goals:\n\n- No filling is used exactly once; that is, each filling must either not appear at all or appear at least twice.\n- For any two buns $i$ and $j$ that have the same filling, the distance between them, which is $|i-j|$, must be a perfect square$^{\\text{∗}}$.\n\nHelp Kohane find a valid way to choose the filling of the buns, or determine if it is impossible to satisfy her goals! If there are multiple solutions, print any of them.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A positive integer $x$ is a perfect square if there exists a positive integer $y$ such that $x = y^2$. For example, $49$ and $1$ are perfect squares because $49 = 7^2$ and $1 = 1^2$ respectively. On the other hand, $5$ is not a perfect square as no integer squared equals $5$\n\\end{footnotesize}",
    "tutorial": "Solve the problem for $n=2$ and for even $n$ in general. For odd $n$, there exists a color that appears at least thrice. What does this mean? Note that $1$ is a square number; thus, for even $n$, the construction $1~1~2~2~3~3\\ldots\\frac{n}{2}~\\frac{n}{2}$ works. For odd $n$, note that there exists a color that appears at least thrice, say at positions $x\\lt y \\lt z$. Then $y-x$, $z-y$ and $z-x$ are all square numbers. Note that $z-x=(z-y)+(y-x)$, which has the smallest solution being $z-x=5^2=25$, and ${z-y,y-x}={9,16}$. Therefore, there is no solution if $n\\le 25$. We devise a solution for $n=27$. By the above, we have the following posts filled in: $1\\text{ (8 blanks) }1\\text{ (15 blanks) }1~\\underline{ }$ We can use the same color for positions $11$ and $27$, to obtain the following: $1\\text{ (8 blanks) }1~2\\text{ (14 blanks) }1~2$ The remaining even-length blanks can be filled in similar to above. The result is as follows and can be hard-coded: $\\mathtt{1~3~3~4~4~5~5~6~6~1~2~7~7~8~8~9~9~10~10~11~11~12~12~13~13~1~2}$ Then, for odd $n\\ge 27$, add $\\frac{n-27}{2}$ pairs with distance $1$ to complete the construction. Note that there are different ways to construct this starting array for $n=27$ as well. Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n    int t;cin>>t;\n    while (t--) {\n        int n;cin>>n;\n        if (n%2) {\n            if (n<27) cout<<-1<<endl;\n            else {\n                cout<<\"1 3 3 4 4 5 5 6 6 1 2 7 7 8 8 9 9 10 10 11 11 12 12 13 13 1 2 \";\n                for (int i=14;i<=n/2;i++) cout<<i<<\" \"<<i<<\" \";\n                cout<<endl;\n            }\n        }\n        else {\n            for (int i=1;i<=n/2;i++) cout<<i<<\" \"<<i<<\" \";\n            cout<<endl;\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2031",
    "index": "D",
    "title": "Penchick and Desert Rabbit",
    "statement": "Dedicated to pushing himself to his limits, Penchick challenged himself to survive the midday sun in the Arabian Desert!\n\nWhile trekking along a linear oasis, Penchick spots a desert rabbit preparing to jump along a line of palm trees. There are $n$ trees, each with a height denoted by $a_i$.\n\nThe rabbit can jump from the $i$-th tree to the $j$-th tree if exactly one of the following conditions is true:\n\n- $j < i$ and $a_j > a_i$: the rabbit can jump backward to a taller tree.\n- $j > i$ and $a_j < a_i$: the rabbit can jump forward to a shorter tree.\n\nFor each $i$ from $1$ to $n$, determine the maximum height among all trees that the rabbit can reach if it starts from the $i$-th tree.",
    "tutorial": "Suppose that you have found the maximum height reachable from tree $i+1$. How do you find the maximum height reachable from tree $i$? Let $p$ be the highest height among trees indexed from $1$ to $i$, and $s$ be the lowest height among trees indexed from $i+1$ to $n$. When can tree $i$ be reachable from tree $i+1$? First, observe that a rabbit at tree $n$ can reach the highest tree; if the tree has index $i<n$, then the rabbit can jump from tree $n$ to $i$. Let $ans_k$ denote the tallest height reachable from tree $k$, then $ans_n=\\max(a_1,a_2,\\ldots a_n)$. We iteratively look at trees $n-1$ to $1$. Suppose we have found the tallest height $ans_{i+1}$ reachable from tree $i+1$. Note that from tree $i$ we can reach the tallest tree with index between $1$ and $i$, and from tree $i+1$ we can reach the shortest tree with index between $i+1$ and $n$. Let $a_x=p_i=\\max(a_1,a_2,\\ldots a_i)$ and $a_y=s_i=\\min(a_{i+1},a_{i+1},\\ldots a_n)$. Then if $p_i>s_i$ then tree $i+1$ is reachable from tree $i$ by the sequence $i\\leftrightarrow x\\leftrightarrow y\\leftrightarrow i+1$. Thus, any tree reachable from tree $i$ is reachable from tree $i+1$, and vice versa; thus, $ans_i=ans_{i+1}.$ On the other hand, if $p_i\\le s_i$, then for any $r\\le i$ and $s\\ge i+1$, we have $r<s$ and $a_r\\le p_i\\le s_i\\le a_s$. Thus, no tree between index $i+1$ and $n$ inclusive is reachable from any tree from $1$ and $i$ inclusive. Similar to the first paragraph, we have $ans_i=\\max(a_1,a_2,\\ldots a_i)=p_i$. Time complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    int t; cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> ar(n), pref(n), suff(n), ans(n);\n        for (int i = 0; i < n; i++) cin >> ar[i];\n        \n        // prefix maximum\n        pref[0] = ar[0];\n        for (int i = 1; i < n; i++) pref[i] = max(pref[i-1], ar[i]);\n        \n        // suffix minimum\n        suff[n-1] = ar[n-1];\n        for (int i = n - 2; i >= 0; i--) suff[i] = min(suff[i+1], ar[i]);\n        \n        ans[n-1] = pref[n-1]; // maximum of all a[i]\n        for (int i=n-2;i>=0;i--) {\n            if (pref[i]>suff[i+1]) ans[i] = ans[i+1];\n            else ans[i] = pref[i];\n        }\n        \n        for (int i = 0; i < n; i++) cout << ans[i] << \" \";\n        cout << \"\\n\";\n    }\n}",
    "tags": [
      "binary search",
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2031",
    "index": "E",
    "title": "Penchick and Chloe's Trees",
    "statement": "With just a few hours left until Penchick and Chloe leave for Singapore, they could hardly wait to see the towering trees at the Singapore Botanic Gardens! Attempting to contain their excitement, Penchick crafted a rooted tree to keep Chloe and himself busy.\n\nPenchick has a rooted tree$^{\\text{∗}}$ consisting of $n$ vertices, numbered from $1$ to $n$, with vertex $1$ as the root, and Chloe can select a non-negative integer $d$ to create a perfect binary tree$^{\\text{†}}$ of depth $d$.\n\nSince Penchick and Chloe are good friends, Chloe wants her tree to be isomorphic$^{\\text{‡}}$ to Penchick's tree. To meet this condition, Chloe can perform the following operation on her own tree any number of times:\n\n- Select an edge $(u,v)$, where $u$ is the parent of $v$.\n- Remove vertex $v$ and all the edges connected to $v$, then connect all of $v$'s previous children directly to $u$.\n\nIn particular, doing an operation on an edge $(u, v)$ where $v$ is a leaf will delete vertex $v$ without adding any new edges.\n\nSince constructing a perfect binary tree can be time-consuming, Chloe wants to choose the minimum $d$ such that a perfect binary tree of depth $d$ can be made isomorphic to Penchick's tree using the above operation. Note that she can't change the roots of the trees.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles. A rooted tree is a tree where one vertex is special and called the root. The parent of vertex $v$ is the first vertex on the simple path from $v$ to the root. The root has no parent. A child of vertex $v$ is any vertex $u$ for which $v$ is the parent. A leaf is any vertex without children.\n\n$^{\\text{†}}$A full binary tree is rooted tree, in which each node has $0$ or $2$ children. A perfect binary tree is a full binary tree in which every leaf is at the same distance from the root. The depth of such a tree is the distance from the root to a leaf.\n\n$^{\\text{‡}}$Two rooted trees, rooted at $r_1$ and $r_2$ respectively, are considered isomorphic if there exists a permutation $p$ of the vertices such that an edge $(u, v)$ exists in the first tree if and only if the edge $(p_u, p_v)$ exists in the second tree, and $p_{r_1} = r_2$.\n\\end{footnotesize}",
    "tutorial": "Consider the tree where root $1$ has $k$ children which are all leaves. What is its minimum depth? Consider undoing the operations from the given tree back to the perfect binary tree. Where can each child of the tree go? As in Hint 2, suppose that there exists a finite sequence of operations that convert a perfect binary tree $T_d$ of depth $d$ to our target tree $T$. We consider where each child of vertex $1$ in $T$ is mapped to the binary tree; specifically, for each such child $c$, let $c'$ be the highest vertex in $T_d$ that maps to $c$ under the operations. Then we can see that the subtree rooted at $c'$ in $T_d$ maps to the subtree rooted at $c$ in $T$. Suppose that the minimum depth required for the subtree rooted at $c$ in $T$ is $d_c$. Claim 1: $2^d\\ge \\sum_{c}2^{d_c}$, where the sum is taken across all children $c$ of $1$. Note that no two of the $v_c$ are ancestors or descendants of each other; otherwise, if $v_{c_1}$ is an ancestor of $v_{c_2}$, then $c_1$ would be an ancestor of $c_2$. Consider the $2^d$ leaves of $T_d$. Of them, for each $c$, $2^{d_c}$ of them are descendants of $v_c$. As no leaf can be descendants of two $v_c$'s, the inequality follows. Claim 2: If $1$ has only one child $c$, then $d=d_c+1$; otherwise, $d$ is the least integer that satisfies the inequality of Claim 1. Suppose $1$ only has one child $c$. Then $d\\le d_c$ clearly does not suffice, but $d=d_c+1$ does as we can merge the entire right subtree into the root $1$. Suppose now that $1$ has multiple children $c_1,c_2,\\ldots c_k$, sorted by descending $d_c$. For each child $c_i$ from $c_1$ to $c_k$, allocate $v_{c_i}$ to be the leftmost possible vertex at a height of $d_{c_i}$. Then the leaves that are ancestors of $c_i$ form a contiguous segment, so this construction ensures that each child $c_i$ can be placed on the tree. Thus, we can apply tree dp with the transition function from $d_{c_i}$ to $d$ described by Claim 2. However, naively implementing it has a worst-case time complexity of $O(n^2).$ Consider a tree constructed this way: $2$ and $3$ are children of $1$, $4$ and $5$ are children of $3$, $6$ and $7$ are children of $5$, and so on; the odd-numbered vertices form a chain with the even-numbered vertices being leaves. In such a graph, the depth $d$ is the length of the odd-numbered chain. Thus, during the computation of $d$, we would have to evaluate $2^x+1$ for $x$ from $1$ to $d\\approx\\frac{n}{2}.$ However, evaluating $2^x+1$ naively requires at least $O(x)$ time, so the algorithm runs in $O(n^2)$. There are several ways to improve the time complexity of the dp transition. For example, sort $d_{c_i}$ in increasing order, then maintain the sum as $a\\times 2^b$, where initially $a=b=0$. For each $c_i$ in order, replace $a$ by $\\lceil \\frac{a}{2^{d_{c_i}-b}}\\rceil$ and replace $b$ by $d_{c_i}$, which essentially serves to round up the sum to the nearest $2^{d_{c_i}}$. Then, increment $a$ to add $2^{d_{c_i}}$ to the sum. At the end of these operations, we have $d=\\lceil \\log_2 a\\rceil+b$. Another way to do so is to \"merge\" terms from smallest to largest; importantly, since we just need to crudely bound $S=\\sum_{c}2^{d_c}$, we can replace $2^x+2^y$ by $2^{max(x,y)+1}$. Then we can repeat this process until only one element remains. Suppose that $x>y$. Then the above operation rounds up $S$ to the nearest $2^x$. Since $2^d\\ge S>2^x$, rounding up $S$ will not cause it to exceed the next power of $2$, so $2^d\\ge S$ remains true after the operation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int maxn = 1'000'000;\n \nvoid dfs(int u, int p, vector<vector<int>>& adj, vector<int>& depth) {\n    priority_queue<int,vector<int>,greater<int>> pq;\n    for (int v : adj[u]) {\n        if (v != p) {\n            dfs(v, u, adj, depth);\n            pq.push(depth[v]);\n        }\n    }\n    if (pq.size() == 0) {\n        depth[u] = 0;\n    } else if (pq.size() == 1) {\n        depth[u] = pq.top() + 1;\n    } else {\n        int hold = -1;\n        bool add = false;\n        while (pq.size()) {\n            if (pq.top() != hold) {\n                if (hold != -1) {\n                    add = true;\n                }\n                hold = pq.top();\n            } else {\n                pq.push(hold + 1);\n                hold = -1;\n            }\n            pq.pop();\n        }\n        depth[u] = hold + add;\n    }\n}\n \nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    int t;cin>>t;while (t--) {\n        int n;\n        cin >> n;\n        vector<int> depth(n);\n        vector<vector<int>> adj(n);\n        for (int i = 1; i < n; i++) {\n            int p;\n            cin >> p;\n            adj[p - 1].push_back(i);\n            adj[i].push_back(p - 1);\n        }\n        dfs(0, 0, adj, depth);\n        cout << depth[0] << \"\\n\";\n    }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "greedy",
      "implementation",
      "math",
      "sortings",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2031",
    "index": "F",
    "title": "Penchick and Even Medians",
    "statement": "This is an interactive problem.\n\nReturning from a restful vacation on Australia's Gold Coast, Penchick forgot to bring home gifts for his pet duck Duong Canh! But perhaps a beautiful problem crafted through deep thought on the scenic beaches could be the perfect souvenir.\n\nThere is a hidden permutation$^{\\text{∗}}$ $p$ of length $n$, where $n$ is even. You are allowed to make the following query:\n\n- Choose a subsequence$^{\\text{†}}$ of the permutation $p$ with even length $4\\le k\\le n$. The interactor will return the \\textbf{value} of the two medians$^{\\text{‡}}$ in the chosen subsequence.\n\nFind the \\textbf{index} of the two medians in permutation $p$ using at most $80$ queries.\n\nNote that the interactor is \\textbf{non-adaptive}. This means that the permutation $p$ is fixed at the beginning and will not change based on your queries.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) element from arbitrary positions.\n\n$^{\\text{‡}}$The two medians of an array $a$ with even length $k$ are defined as the $\\frac{k}{2}$-th and $\\left(\\frac{k}{2} + 1\\right)$-th \\textbf{smallest} element in the array ($1$-indexed).\n\\end{footnotesize}",
    "tutorial": "Querying $n - 2$ elements is very powerful. Try to find two indices $x$ and $y$ such that one of $p_x, p_y$ is strictly smaller than $\\frac{n}{2}$ and the other is strictly greater than $\\frac{n}{2} + 1$. What can you do after finding these two elements? This solution is non-deterministic and uses $\\frac{n}{2} + O(1)$ queries Part 1 Suppose we select all elements except for two indices $1 \\le i, j \\le n$ to be used in the query. Let the result we receive be $(a, b)$ where $a \\lt b$. If $a = \\frac{n}{2}$ and $b = \\frac{n}{2} + 1$, it means that one of $p_i, p_j$ is strictly smaller than $\\frac{n}{2}$ and the other is strictly larger than $\\frac{n}{2}$. If we do the above query randomly, there is around $50\\%$ chance of getting the above outcome. So we can just randomly select two indices to exclude from the query until we get the above result. Part 2 Now that we have two elements $x$ and $y$ such that one of $p_x, p_y$ is strictly smaller than $\\frac{n}{2}$ and the other is strictly greater than $\\frac{n}{2} + 1$, we can query $[x, y, i, j]$. The median of $[p_x, p_y, p_i, p_j]$ will include $\\frac{n}{2}$ if and only if one of $p_i, p_j$ is equal to $\\frac{n}{2}$. The same is true for $\\frac{n}{2} + 1$. We can iterate through all $\\frac{n}{2} - 1$ pairs to find the two pairs that contain the median, then iterate through all $4\\choose 2$ combinations of median to find the answer. This solution is deterministic and uses $\\frac{3n}{4}$ queries To make the solution deterministic, we need to find a deterministic solution to Part 1. Part 2 is already deterministic so we can just use the same solution. Let us analyse all the possible cases if we select all elements except for two indices $1 \\le i, j \\le n$ to be used in the query. Let the result we receive be $(a, b)$ where $a \\lt b$. $a = \\frac{n}{2}$ and $b = \\frac{n}{2} + 1$. In this case, one of $p_i, p_j$ is strictly smaller than $\\frac{n}{2}$ and the other is strictly larger than $\\frac{n}{2}$, which is exactly what we wanted to find. $a = \\frac{n}{2}$ and $b = \\frac{n}{2} + 2$. In this case, one of $p_i, p_j$ is strictly smaller than $\\frac{n}{2}$ and the other is equal to $\\frac{n}{2} + 1$. $a = \\frac{n}{2} - 1$ and $b = \\frac{n}{2} + 1$. In this case, one of $p_i, p_j$ is strictly larger than $\\frac{n}{2} + 1$ and the other is equal to $\\frac{n}{2}$. $a = \\frac{n}{2} - 1$ and $b = \\frac{n}{2}$. In this case, both of $p_i, p_j$ are larger than or equal to $\\frac{n}{2} + 1$. $a = \\frac{n}{2} + 1$ and $b = \\frac{n}{2} + 2$. In this case, both $p_i, p_j$ are smaller than or equal to $\\frac{n}{2}$. $a = \\frac{n}{2} - 1$ and $b = \\frac{n}{2} + 2$. In this case, $p_i$ and $p_j$ are the two medians. \\end{enumerate} If we have two queries such that one query is type 4 and another is type 5, then we can use one element from each pair to form the desired $x$ and $y$. We have to use one additional query to make sure that the chosen elements are not part of the median. We will only ask at most $\\frac{n}{4}$ queries before there is at least one query of type 4 and one query of type 5. Types 2 and 3 can be treated together with types 4 and 5 with some careful handling. This solution is deterministic and uses $\\frac{n}{2}+\\log_2 n$ queries. Special thanks to SHZhang for discovering this solution. Call the elements of the permutation less than or equal to $\\frac{n}{2}$ lower elements, and call the rest upper elements. Pair up the permutation's elements (we can just pair index 1 with index 2, index 3 with index 4, and so on). Do $\\frac{n}{2}$ queries where the $i$-th query consists of all elements except those in the $i$-th pair. This lets us determine whether (1) both elements in the pair are lower elements, (2) both are upper elements, or (3) there is one lower and one upper element in the pair. In case (3), we can also tell if the pair contains one or both of the desired medians (Take a look at solution 2 for a more in-depth case analysis). Our goal now is to identify the pairs that the lower and upper medians belong to. It suffices to be able to find them from the pairs of type (1) and (2), since we have already found the ones in type (3) pairs. This can be done with binary search on the type (1) and (2) pairs, by balancing the number of pairs of both types and checking if the median is in the result (The two binary searches can be performed simultaneously). This is similar to Part 2 of solution 1, but instead of just using $4$ elements, we can generalise to use more elements if there is an equal number of lower and upper elements. After figuring out which pair each median is in, there are four possibilities remaining for the answer. For each one, make a query consisting of all the elements but the two candidates for the two medians that we are checking. When we see $\\left(\\frac{n}{2} - 1, \\frac{n}{2} + 2\\right)$ as the response, we know we found the answer.",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <queue>\n#include <cmath>\n#include <cstdlib>\n#include <utility>\n#include <cstring>\n \nusing namespace std;\n \n#define ll long long\n#define MOD // Insert modulo here\n#define mul(a, b) (((ll)(a) * (ll)(b)) % MOD)\n \n#ifndef ONLINE_JUDGE\n#define debug(format, ...) fprintf(stderr, \\\n    \"%s:%d: \" format \"\\n\", __func__, __LINE__,##__VA_ARGS__)\n#else\n#define debug(format, ...)\n#define NDEBUG\n#endif\n \nint n, k;\n \npair<int, int> query(vector<int>& v)\n{\n    printf(\"? %d \", (int)v.size());\n    for (int x: v) printf(\"%d \", x);\n    printf(\"\\n\");\n    fflush(stdout);\n    int m1, m2; scanf(\"%d%d\", &m1, &m2);\n    if (m1 == -1) {\n        exit(0);\n    }\n    return make_pair(m1, m2);\n}\n \npair<int, int> query_missing(int x, int y)\n{\n    vector<int> v;\n    for (int i = 1; i <= n; i++) {\n        if (i != x && i != y) v.push_back(i);\n    }\n    return query(v);\n}\n \nvoid work()\n{\n    scanf(\"%d\", &n);\n    k = n / 2;\n    vector<int> lower_pairs, upper_pairs;\n    int lower_mid_pair = -1;\n    int upper_mid_pair = -1;\n    for (int i = 1; i <= k; i++) {\n        pair<int, int> pr = query_missing(2*i-1, 2*i);\n        if (pr.first == k+1 && pr.second == k+2) {\n            lower_pairs.push_back(i);\n        } else if (pr.first == k-1 && pr.second == k) {\n            upper_pairs.push_back(i);\n        } else {\n            bool has_lower_mid = (pr.first == k-1);\n            bool has_upper_mid = (pr.second == k+2);\n            if (has_lower_mid && has_upper_mid) {\n                printf(\"! %d %d\\n\", 2*i-1, 2*i);\n                fflush(stdout);\n                return;\n            } else if (has_lower_mid) {\n                lower_mid_pair = i;\n            } else if (has_upper_mid) {\n                upper_mid_pair = i;\n            }\n        }\n    }\n    if (lower_mid_pair == -1 || upper_mid_pair == -1) {\n        int loweridx = 0, upperidx = 0;\n        for (int bit = 0; bit < 10; bit++) {\n            vector<int> qr;\n            for (int i = 0; i < lower_pairs.size(); i++) {\n                if (!(i & (1 << bit))) {\n                    qr.push_back(2*lower_pairs[i]);\n                    qr.push_back(2*lower_pairs[i]-1);\n                    qr.push_back(2*upper_pairs[i]);\n                    qr.push_back(2*upper_pairs[i]-1);\n                }\n            }\n            pair<int, int> result = query(qr);\n            if (result.first < k) loweridx |= (1 << bit);\n            if (result.second > k+1) upperidx |= (1 << bit);\n        }\n        if (lower_mid_pair == -1) lower_mid_pair = lower_pairs[loweridx];\n        if (upper_mid_pair == -1) upper_mid_pair = upper_pairs[upperidx];\n    }\n    /*if (lower_mid_pair == upper_mid_pair) {\n        printf(\"! %d %d\\n\", 2*lower_mid_pair-1, 2*lower_mid_pair);\n        return;\n    }*/\n    for (int i = 2*lower_mid_pair-1; i <= 2*lower_mid_pair; i++) {\n        for (int j = 2*upper_mid_pair-1; j <= 2*upper_mid_pair; j++) {\n            pair<int, int> result = query_missing(i, j);\n            if (result.first == k-1 && result.second == k+2) {\n                printf(\"! %d %d\\n\", i, j);\n                fflush(stdout);\n                return;\n            }\n        }\n    }\n}\n \nint main()\n{\n    int t; scanf(\"%d\", &t);\n    for (int i = 1; i <= t; i++) {\n        work();\n        fflush(stdout);\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "interactive",
      "probabilities"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2032",
    "index": "A",
    "title": "Circuit",
    "statement": "Alice has just crafted a circuit with $n$ lights and $2n$ switches. Each component (a light or a switch) has two states: on or off. The lights and switches are arranged in a way that:\n\n- Each light is connected to \\textbf{exactly two} switches.\n- Each switch is connected to \\textbf{exactly one} light. It's \\textbf{unknown} which light each switch is connected to.\n- When all switches are off, all lights are also off.\n- If a switch is toggled (from on to off, or vice versa), the state of the light connected to it will also toggle.\n\nAlice brings the circuit, which shows only the states of the $2n$ switches, to her sister Iris and gives her a riddle: what is the minimum and maximum number of lights that can be turned on?\n\nKnowing her little sister's antics too well, Iris takes no more than a second to give Alice a correct answer. Can you do the same?",
    "tutorial": "Observe that an even number of switch toggles on the same light will not change that light's status. In other words, a light is on if and only if exactly one of the two switches connecting to it is on. Let's denote $\\text{cnt}_0$ and $\\text{cnt}_1$ as the number of off switches and on switches in the circuit. We see that The maximum number of on lights is $\\min(\\text{cnt}_0, \\text{cnt}_1)$: we can't achieve more than this amount since any on light decreases both $\\text{cnt}_0$ and $\\text{cnt}_1$ by $1$, and we can achieve this amount by matching $\\min(\\text{cnt}_0, \\text{cnt}_1)$ pairs of one off switch and one on switch, and the rest can be matched arbitrarily. The minimum number of on lights is $\\text{cnt}_0 \\bmod 2$. Since $\\text{cnt}_0 + \\text{cnt}_1 = 2n$, they have the same parity. Then, we can easily see that when both $\\text{cnt}_0$ and $\\text{cnt}_1$ are even, we can match $n$ pairs of the same type of switches, so there are no on lights in this case. When both $\\text{cnt}_0$ and $\\text{cnt}_1$ are odd, we must match one on switch with one off switch to make $\\text{cnt}_0$ and $\\text{cnt}_1$ even, so there is one on light in this case. The calculation of $\\text{cnt}_0$ and $\\text{cnt}_1$ can be easily done by a simple iteration over the switches. Time complexity: $\\mathcal{O}(n)$.",
    "code": "class Solution:\n    hasMultipleTests = True\n\n    n: int = None\n    a: list = None\n\n    @classmethod\n    def preprocess(cls):\n        pass\n\n    @classmethod\n    def input(cls, testcase):\n        cls.n = int(input())\n        cls.a = list(map(int, input().split()))\n\n    @classmethod\n    def solve(cls, testcase):\n        cnt0 = sum(cls.a)\n        \n        print(cnt0 & 1, min(cnt0, cls.n*2 - cnt0))\n\n# end Solution",
    "tags": [
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2032",
    "index": "B",
    "title": "Medians",
    "statement": "You are given an array $a = [1, 2, \\ldots, n]$, where $n$ is \\textbf{odd}, and an integer $k$.\n\nYour task is to choose an \\textbf{odd} positive integer $m$ and to split $a$ into $m$ subarrays$^{\\dagger}$ $b_1, b_2, \\ldots, b_m$ such that:\n\n- Each element of the array $a$ belongs to exactly one subarray.\n- For all $1 \\le i \\le m$, $|b_i|$ is \\textbf{odd}, i.e., the length of each subarray is odd.\n- $\\operatorname{median}([\\operatorname{median}(b_1), \\operatorname{median}(b_2), \\ldots, \\operatorname{median}(b_m)]) = k$, i.e., the median$^{\\ddagger}$ of the array of medians of all subarrays must equal $k$. $\\operatorname{median}(c)$ denotes the median of the array $c$.\n\n$^{\\dagger}$A subarray of the array $a$ of length $n$ is the array $[a_l, a_{l + 1}, \\ldots, a_r]$ for some integers $1 \\le l \\le r \\le n$.\n\n$^{\\ddagger}$A median of the array of odd length is the middle element after the array is sorted in non-decreasing order. For example: $\\operatorname{median}([1,2,5,4,3]) = 3$, $\\operatorname{median}([3,2,1]) = 2$, $\\operatorname{median}([2,1,2,1,2,2,2]) = 2$.",
    "tutorial": "For $n = 1$ (and $k = 1$ as well), the obvious answer would be not partitioning anything, i.e., partition with 1 subarray being itself. For $n > 1$, we see that $k = 1$ and $k = n$ cannot yield a satisfactory construction. Proof is as follows: $m = 1$ will yield $ans = \\lfloor \\frac{n+1}{2} \\rfloor$, which will never be equal to $1$ or $n$ when $n \\ge 3$. If $m > 1$, considering the case of $k = 1$, we see that $\\operatorname{median}(b_i) = 1$ iff $i \\ge 2$, and since the original array $a$ is an increasingly-sorted permutation, we can conclude that $\\operatorname{median}(b_1) < 1$. This is not possible. Similarly, $k = n$ also doesn't work with $m > 1$, as it'll require $\\operatorname{median}(b_m) > n$. Apart from these cases, any other $k$ can yield an answer with $m = 3$ - a prefix subarray $b_1$, a middle subarray $b_2$ containing $k$ ($b_2$ will be centered at $k$, of course), and a suffix subarray $b_3$. This way, the answer will be $\\operatorname{median}(b_2) = k$. The length of $b_2$ can be either $1$ or $3$, depending on the parity of $k$ (so that $b_1$ and $b_3$ could have odd lengths). In detail: $b_2$ will have length $1$ (i.e., $[k]$) if $k$ is an even integer, and length $3$ (i.e., $[k-1, k, k+1]$) if $k$ is an odd integer. Time complexity: $\\mathcal{O}(1)$.",
    "code": "class Solution:\n    hasMultipleTests = True\n\n    n: int = None\n    k: int = None\n\n    @classmethod\n    def preprocess(cls):\n        pass\n\n    @classmethod\n    def input(cls, testcase):\n        cls.n, cls.k = map(int, input().split())\n\n    @classmethod\n    def solve(cls, testcase):\n        if cls.n == 1: return(print('1\\n1'))\n\n        if cls.k in {1, cls.n}: return(print(-1))\n\n        p2, p3 = cls.k - cls.k % 2, cls.k + 1 + cls.k % 2\n        print(f'3\\n1 {p2} {p3}')\n\n# end Solution",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2032",
    "index": "C",
    "title": "Trinity",
    "statement": "You are given an array $a$ of $n$ elements $a_1, a_2, \\ldots, a_n$.\n\nYou can perform the following operation any number (possibly $0$) of times:\n\n- Choose two integers $i$ and $j$, where $1 \\le i, j \\le n$, and assign $a_i := a_j$.\n\nFind the minimum number of operations required to make the array $a$ satisfy the condition:\n\n- For every pairwise distinct triplet of indices $(x, y, z)$ ($1 \\le x, y, z \\le n$, $x \\ne y$, $y \\ne z$, $x \\ne z$), there exists a non-degenerate triangle with side lengths $a_x$, $a_y$ and $a_z$, i.e. $a_x + a_y > a_z$, $a_y + a_z > a_x$ and $a_z + a_x > a_y$.",
    "tutorial": "Without loss of generality, we assume that every array mentioned below is sorted in non-descending order. An array $b$ of $k$ elements ($k \\ge 3$) will satisfy the problem's criteria iff $b_1 + b_2 > b_k$. The proof is that $b_1 + b_2$ is the minimum sum possible of any pair of distinct elements of array $b$, and if it is larger than the largest element of $b$, every pair of distinct elements of $b$ will be larger than any element of $b$ on its own. The upper bound for our answer is $n - 2$. This can be done as follows: we will turn every value from $a_2$ to $a_{n-1}$ to $a_n$ - this way, we only have two types of triangles: $(a_1, a_n, a_n)$ and $(a_n, a_n, a_n)$. Since $a_1 \\ge 1 > 0$, we have $a_1 + a_n > a_n$, which means the former type of triangles is non-degenerate. The latter is also trivially one, as it is a regular/equilateral triangle. Otherwise, we'll need a pair of indices $(i, j)$ ($1 \\le i \\le n-2$, $i+2 \\le j \\le n$), so that in the final array after applying operations to $a$, $a_i$ and $a_{i+1}$ will be respectively the smallest and second smallest element, and $a_j$ will be the largest element. Such indices must satisfy $a_i + a_{i+1} > a_j$. Let's consider a pair $(i, j)$ that satisfies the above condition, then we need to turn elements outside of it (i.e. those before $i$ or after $j$) into some elements within the range $[a_{i+1}, a_j]$, and indeed we can change them into $a_{i+1}$ - this way, we have everything in place while keeping the relative rankings of $a_i$, $a_{i+1}$ and $a_j$ as what they are initially. Therefore, for such a pair, the number of operations needed is $n - (j - i + 1)$. This means that for every $i$, we need to find the largest $j > i$ that satisfies the condition, which can easily be done using two pointers. Sorting complexity: $\\mathcal{O}(n \\log n)$. Two-pointer complexity: $\\mathcal{O}(n)$.",
    "code": "class Solution:\n    hasMultipleTests = True\n\n    n: int = None\n    a: list = None\n\n    @classmethod\n    def preprocess(cls):\n        pass\n\n    @classmethod\n    def input(cls, testcase):\n        cls.n = int(input())\n        cls.a = list(map(int, input().split()))\n\n    @classmethod\n    def solve(cls, testcase):\n        cls.a.sort()\n        l, r, ans = 0, 2, cls.n - 2\n        while r < cls.n:\n            while r - l >= 2 and cls.a[l] + cls.a[l+1] <= cls.a[r]: l += 1\n            ans = min(ans, cls.n - (r - l + 1))\n            r += 1\n        print(ans)\n\n# end Solution",
    "tags": [
      "binary search",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2032",
    "index": "D",
    "title": "Genokraken",
    "statement": "This is an interactive problem.\n\nUpon clearing the Waterside Area, Gretel has found a monster named Genokraken, and she's keeping it contained for her scientific studies.\n\nThe monster's nerve system can be structured as a tree$^{\\dagger}$ of $n$ nodes (really, everything should stop resembling trees all the time$\\ldots$), numbered from $0$ to $n-1$, with node $0$ as the root.\n\nGretel's objective is to learn the exact structure of the monster's nerve system — more specifically, she wants to know the values $p_1, p_2, \\ldots, p_{n-1}$ of the tree, where $p_i$ ($0 \\le p_i < i$) is the direct parent node of node $i$ ($1 \\le i \\le n - 1$).\n\nShe doesn't know exactly how the nodes are placed, but she knows a few convenient facts:\n\n- If we remove root node $0$ and all adjacent edges, this tree will turn into a forest consisting of only paths$^{\\ddagger}$. Each node that was initially adjacent to the node $0$ \\textbf{will be the end of some path}.\n- The nodes are indexed in a way that if $1 \\le x \\le y \\le n - 1$, then $p_x \\le p_y$.\n- Node $1$ has \\textbf{exactly two} adjacent nodes (including the node $0$).\n\n\\begin{center}\n\\begin{tabular}{ccc}\n& & \\\n{\\small The tree in this picture \\textbf{does not} satisfy the condition, because if we remove node $0$, then node $2$ (which was initially adjacent to the node $0$) will not be the end of the path $4-2-5$.} & {\\small The tree in this picture \\textbf{does not} satisfy the condition, because $p_3 \\le p_4$ must hold.} & {\\small The tree in this picture \\textbf{does not} satisfy the condition, because node $1$ has only one adjacent node.} \\\n\\end{tabular}\n\\end{center}\n\nGretel can make queries to the containment cell:\n\n- \"? a b\" ($1 \\le a, b < n$, $a \\ne b$) — the cell will check if the simple path between nodes $a$ and $b$ contains the node $0$.\n\nHowever, to avoid unexpected consequences by overstimulating the creature, Gretel wants to query at most $2n - 6$ times. Though Gretel is gifted, she can't do everything all at once, so can you give her a helping hand?\n\n$^{\\dagger}$A tree is a connected graph where every pair of distinct nodes has exactly one simple path connecting them.\n\n$^{\\ddagger}$A path is a tree whose vertices can be listed in the order $v_1, v_2, \\ldots, v_k$ such that the edges are $(v_i, v_{i+1})$ ($1 \\le i < k$).",
    "tutorial": "For simplicity, we'll use the term \"tentacle\" to call each path tree in the forest made by cutting off node $0$. We also notice that in each tentacle, two nodes will never have the same distance from root node $0$. The condition of $p_x \\le p_y$ iff $x \\le y$ leads to a crucial observation of the system: it is indexed in accordance to a BFS order of the tree. Hence, we now have two goals: Determine $m$ - the number of tentacles. From node $m+1$ to $n-1$, assign every node to their respective tentacles. Due to the BFS order, at the moment of assignment, the previous tip of the tentacle is the parent of the current node, and the current node becomes the new tip of the tentacle. For the first objective, we see that node $1$ is guaranteed to be connected with nodes $0$ and $m + 1$. Furthermore, $m + 1$ is the first non-zero node where the path between it and $1$ does not cross $0$. Therefore, you can keep querying $(1, j)$ for increasing $j$ until you find a $0$ to get $m$. For the second objective, we need to find the tentacle that each node $i$ ($m + 2 \\le i \\le n - 1$) belongs to; in other words, find the node $1 \\le i \\le m$ so that query $(i, j)$ yields a $0$. Denote $t(j)$ as the tentacle associated with node $j$, then note that: If $j-1$ and $j$ share the same distance from $0$, then obviously $t(j-1) < t(j)$, i.e., $t(j)$ will be a tentacle at the forward direction from $t(j-1)$ in the tentacle list. If $j-1$ and $j$ don't share the same distance from $0$, then $t(j)$ can be any tentacle in the list. So we can approach this objective like this: denote $\\text{next}(t(j-1))$ as the next tentacle in the list after $t(j-1)$ (or $1$ if $t(j-1)$ was at the end of the list), starting from $i = t(j-1)$, we'll keep re-assigning $i = \\text{next}(i)$ until query $(i, j)$ yields a $0$. From hindsight, it looks like we'll need $\\mathcal{O}(n^2)$ query count order to finish this part, but there is another crucial observation: due to the nodes being indexed in BFS order, if any tentacle yields a $1$ during probing, that tentacle will never be extended again - proof for this is pretty intuitive but a bit lengthy to express in words, so we'll leave it as an exercise for the reader - thus if you reach an $i$ that has already been deactivated before, you ignore it and call $\\text{next}$ again, which wouldn't count towards the queries as it is your internal processing. Let's count the number of queries we used. Let $m \\le n - 2$ be the number of tentacles, then If $m = n-2$, the second objective wouldn't be needed, so we end up with $n - 2 \\le 2n - 6$ queries in total (as $n \\le 4$). If $m \\le n - 3$, note that each time we process a query, either a node is appended to a tentacle, or a tentacle is removed. Since at most $m - 1$ tentacles can be removed and there are $n - m - 2$ nodes to be processed, the second phase uses at most $n - 3$ queries, so in total we use $n + m - 3 \\le 2n - 6$ queries. To process the list of tentacles, there are a few options: Naively mark the tentacles as active/inactive to know when to stop by for queries and when to skip. Time complexity will be $\\mathcal{O}(n^2)$, and though it can still pass (in fact one such solution from the author passed nicely), it is not recommended. Maintain the list of tentacles in a set, if a node is known to be inactive, remove it. Time complexity will be $\\mathcal{O}(n \\log n)$. Maintain the list of tentacles in a similar manner as above, but using a doubly linked list this time. Time complexity will be $\\mathcal{O}(n)$.",
    "code": "class DeleteOnly_DLL:\n    def __init__(self, size: int):\n        self.values = [None for _ in range(size)]\n        self.prev = [(i + size - 1) % size for i in range(size)]\n        self.next = [(i +        1) % size for i in range(size)]\n        self.pointer = 0\n    \n    def current(self):\n        return self.values[self.pointer]\n    \n    # Set value at pointer and move pointer to next\n    def set_and_move(self, val):\n        self.values[self.pointer] = val\n        self.pointer = self.next[self.pointer]\n        \n    # \"Delete\" node and move pointer to next\n    def erase(self):\n        if self.prev[self.pointer] != -1:\n            self.next[self.prev[self.pointer]] = self.next[self.pointer]\n        if self.next[self.pointer] != -1:\n            self.prev[self.next[self.pointer]] = self.prev[self.pointer]\n        \n        next_id = self.next[self.pointer]\n        self.prev[self.pointer] = self.next[self.pointer] = -1\n        self.pointer = next_id\n    \n# end DeleteOnly_DLL\n\n\nclass Solution:\n    hasMultipleTests = True\n\n    n: int = None\n    \n    @classmethod\n    def ask(cls, a: int, b: int):\n        print(f'? {a} {b}', flush=True)\n        return int(input())\n    \n    @classmethod\n    def answer(cls, p: list):\n        print(f'! {\" \".join(map(str, p[1:]))}', flush=True)\n\n    @classmethod\n    def preprocess(cls):\n        pass\n\n    @classmethod\n    def input(cls, testcase):\n        cls.n = int(input())\n\n    @classmethod\n    def solve(cls, testcase):\n        p = [-1 for _ in range(cls.n)]\n        p[1] = 0\n        \n        r = 2\n        while True:\n            response = cls.ask(1, r)\n            if response == -1: exit(2226)\n            \n            if response == 1:\n                p[r] = 0\n                r += 1\n            else: break\n        \n        tentacle_count = r - 1\n        \n        tentacles = DeleteOnly_DLL(size = tentacle_count)\n        for i in range(tentacle_count):\n            tentacles.set_and_move(i + 1)\n\n        p[r] = tentacles.current()\n        tentacles.set_and_move(r)\n        r += 1\n        \n        while r < cls.n:\n            response = cls.ask(tentacles.current(), r)\n            if response == -1: exit(2226)\n            \n            if response == 1:\n                tentacles.erase()\n            else:\n                p[r] = tentacles.current()\n                tentacles.set_and_move(r)\n                r += 1\n        \n        cls.answer(p)\n\n# end Solution",
    "tags": [
      "constructive algorithms",
      "data structures",
      "graphs",
      "greedy",
      "implementation",
      "interactive",
      "trees",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2032",
    "index": "E",
    "title": "Balanced",
    "statement": "You are given a \\textbf{cyclic} array $a$ with $n$ elements, where $n$ is \\textbf{odd}. In each operation, you can do the following:\n\n- Choose an index $1 \\le i \\le n$ and increase $a_{i - 1}$ by $1$, $a_i$ by $2$, and $a_{i + 1}$ by $1$. The element before the first element is the last element because this is a cyclic array.\n\nA cyclic array is called balanced if all its elements are equal to each other.\n\nFind any sequence of operations to make this cyclic array balanced or determine that it is impossible. Please note that you \\textbf{do not} have to minimize the number of operations.",
    "tutorial": "To simplify this problem a little bit before starting, we will temporarily allow \"negative\" operation: choose an index $1 \\le i \\le n$ and increase $a_{i - 1}$ by $-1$, $a_i$ by $-2$, and $a_{i + 1}$ by $-1$. This is counted as $-1$ operation on index $i$. Should we get negative elements in array $v$ in the end, we can normalize it just fine by subtracting all $v_i$ with $\\min v_i$ so that the final array $v$ is valid - it's trivial to prove that applying the same amount of operations in all indices does not change the relative difference between any two values in the array. Imagine we have $n = 3$ and array $a = [a_1, a_2, a_3]$ where $a_1 \\ge a_2 \\le a_3$; i.e., a trench. This array always has at least one solution: try to balance $a_1$ and $a_3$ by adding an amount of operation on either side based on their difference - here we have something we'll denote as a \"balanced trench\", then add another amount of operations on index $2$ to balance them three, and due to the cyclic nature of $a$. In fact, every array with $n = 3$, without regards to value intensity, can be thought of this form - if $a_2$ is higher than both $a_1$ and $a_3$, the act of \"raising\" $a_2$ is actually applying a negative amount of operations to index $2$. How to make a \"balanced trench\" for $n > 3$? At least, we can balance $a_1$ and $a_n$ in the same fashion as we did for $n = 3$. Can we balance $a_2$ and $a_{n-1}$ without breaking the balance we achieved between $a_1$ and $a_n$? Assuming we have an array $[0, x, y, x + 1, 0]$. By logic, we want to increase the value of index $2$. Applying an operation to index $1$ won't do, as the new array would be $[2, x+1, y, x+1, 1]$. We are balancing the inner elements by sacrificing the outer ones. Applying an operation to index $3$ also won't do as it increases both sides. Applying an operation to index $2$ will make the array become $[1, x+2, y+1, x+1, 0]$. By applying another operation to index $5$, we'll reach our desired goal with array $[2, x+2, y+1, x+2, 2]$. In fact, a series of operations in \"consecutive\" indices of the same parity would have this effect, regardless of how long that series is. To be precise, without loss of generality, a series of operations in indices $2, 4, \\ldots, i$, with $i \\le n-1$, will increase $a_1$ and $a_{i+1}$ by $1$, and all values with indices in range $[2, i]$ by $2$. The catch here is that we mitigate $1$ unit of difference between sides with each operation series by adding just $1$ unit to the higher side, while the corresponding other $1$ would be further beyond the lower side. If we aim to balance the sides from outwards to inwards, that exceeding $1$ will either fall into a deeper-inwards layer, or the center of the array (since $n$ is odd), which will not harm whatever we have achieved at first. Take an example with array $[48, 18, 26, 57, 39]$. First, we'll balance index $1$ and index $5$. We can simply apply $9$ operations to index $5$. The new array would be $[57, 18, 26, 66, 57]$. Then, we'll balance index $2$ and index $4$. From index $2$, we'll move to the left until it reaches index $5$, and apply $48$ operations for every $2$ steps. In other words, apply $48$ operations to index $2$ and $48$ operations to index $5$. This array is now a balanced trench: $[153, 114, 64, 114, 153]$. Now, achieving the desired array (we'll call it a \"plateau\") from a balanced trench is easy: starting from the rightmost element of the left side before the center going leftwards, compare the value to its adjacent element to the right, and apply a corresponding amount of operations. Now, take the balanced trench we just acquired. First, we'll check index $2$. Clearly, we want to rise index $3$ to close the $50$ unit gap, thus we'll apply $50$ operations to index $3$. The new array will become $[153, 164, 164, 164, 153]$. Then, we'll check index $1$. Our objective is to decrease $11$ for all elements with indices in range $[2, 4]$. Using the similar operation series as discussed earlier, this can be done like this: apply $-11$ operations to index $2$, then apply $-11$ operations to index $4$. The final array will be $[142, 142, 142, 142, 142]$. That operation series can be used here because the range of elements changing by $2$ units per series has an odd size, and since we're growing the plateau from the center point outwards, its size is always odd as well. With this, the non-normalized array $v$ will be $[0, 46, 50, -11, 57]$. Implementing this method can be separated into two separate steps: Step $1$ (creating the balanced trench): for each pair of indices $(i, n+1-i)$ with difference $a_{n+1-i} - a_i = d$, apply $d$ operations for each index of the cyclic range $[n+3-i, i]$ with step $2$. Step $2$ (creating the plateau): for each pair of indices $(i, i+1)$ with difference $a_i - a_{i+1} = d$, apply $d$ operations for each index of the range $[i+1, n-i]$ with step $2$. Some extra notes: Each step requires an independent prefix-sum structure to quickly maintain the operation updates. Notice that the prefix sum here takes account of parity, since only the other index in a range is updated, not every one of them. Remember that after each index considered, its value will alter based on the amount of operations just applied on it, so keep track of it properly. To avoid confusion, it's advised to apply the operations of step $1$ directly into array $a$ before proceeding with step $2$. Remember to normalize array $v$ before outputting to get rid of negative values. Refer to the model solution for more details. Time complexity: $\\mathcal{O}(n)$.",
    "code": "class Solution:\n    hasMultipleTests = True\n\n    n: int = None\n    a: list = None\n\n    @classmethod\n    def apply_prefixes(cls, prefixes, v):\n        for i in range(2, cls.n*2):\n            prefixes[i] += prefixes[i - 2]\n        \n        for i in range(cls.n*2):\n            v[i % cls.n] += prefixes[i]\n\n    @classmethod\n    def construct_trench(cls, arr, v):\n        prefixes = [0 for _ in range(cls.n * 2)]\n        delta = [0 for _ in range(cls.n)]\n        \n        for i in range(cls.n // 2):\n            diff = arr[cls.n - 1 - i] - (arr[i] + delta[i])\n            \n            delta[i] += 2 * diff\n            delta[i + 1] += diff\n            \n            prefixes[cls.n - i] += diff\n            prefixes[cls.n + i + 2] -= diff\n        \n        cls.apply_prefixes(prefixes, v)\n        \n        for i in range(cls.n):\n            arr[i] += v[i] * 2\n            arr[(i + 1) % cls.n] += v[i]\n            arr[(i + cls.n - 1) % cls.n] += v[i]\n\n    @classmethod\n    def construct_plateau(cls, arr, v):\n        prefixes = [0 for _ in range(cls.n * 2)]\n        delta = [0 for _ in range(cls.n)]\n        \n        for i in range(cls.n // 2 - 1, -1, -1):\n            diff = arr[i] - (arr[i + 1] + delta[i + 1])\n            \n            delta[i] += diff\n            \n            prefixes[i + 1] += diff\n            prefixes[cls.n - i] -= diff\n        \n        cls.apply_prefixes(prefixes, v)\n\n    @classmethod\n    def preprocess(cls):\n        pass\n\n    @classmethod\n    def input(cls, testcase):\n        cls.n = int(input())\n        cls.a = list(map(int, input().split()))\n\n    @classmethod\n    def solve(cls, testcase):\n        if cls.n == 1:\n            return(print(0))\n        \n        v = [0 for _ in range(cls.n)]\n        \n        cls.construct_trench(cls.a, v)\n        cls.construct_plateau(cls.a, v)\n        \n        offset = min(v)\n        v = list(map(lambda x: x - offset, v))\n        \n        print(*v)\n\n# end Solution",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2032",
    "index": "F",
    "title": "Peanuts",
    "statement": "Having the magical beanstalk, Jack has been gathering a lot of peanuts lately. Eventually, he has obtained $n$ pockets of peanuts, conveniently numbered $1$ to $n$ from left to right. The $i$-th pocket has $a_i$ peanuts.\n\nJack and his childhood friend Alice decide to play a game around the peanuts. First, Alice divides the pockets into some boxes; each box will have a non-zero number of \\textbf{consecutive} pockets, and each pocket will, obviously, belong to exactly one box. At the same time, Alice does not change the order of the boxes, that is, the boxes are numbered in ascending order of the indices of the pockets in them.\n\nAfter that, Alice and Jack will take turns alternately, with Alice going first.\n\nAt each turn, the current player will remove a positive number of peanuts from \\textbf{exactly one} pocket which belongs to the \\textbf{leftmost non-empty box} (i.e., the leftmost box containing at least one non-empty pocket). In other words, if we number the boxes from left to right, then each player can only pick peanuts from the pocket in the $j$-th box ($j \\ge 2$) only if the $(j - 1)$-th box has no peanuts left. The player who cannot make a valid move loses.\n\nAlice is sure she will win since she has the advantage of dividing the pockets into boxes herself. Thus, she wanted to know how many ways there are for her to divide the peanuts into boxes at the start of the game so that she will win, assuming both players play optimally. Can you help her with the calculation?\n\nAs the result can be very large, output it modulo $998\\,244\\,353$.",
    "tutorial": "Let's get the trivial case out of the way: If the peanut pockets always contain $1$ nut each, then partitioning the pockets doesn't affect the game's outcome at all: Alice will always win if $n$ is odd, and there are $2^{n-1}$ ways to partition $n$ pockets. Jack will always win if $n$ is even. Proof for the trivial case is, indeed, trivial. For the main problem, we see that this is a derivative of a game of Nim. To be exact, each box is a vanilla Nim game. To determine the winner of a vanilla Nim game when both players play optimally is trivial - if not for you, I strongly suggest reading about the game and the Sprague-Grundy theorem before continuing. In short, the Nim-sum of a Nim game is the xor sum of all values presented, and if that value is at least $1$, the first player will win if they play optimally. The original game of this problem is a series of consecutive Nim games, with the loser of the previous game becoming the first player of the next game. Clearly, trying to win all the boxes isn't a correct approach - one of the simplest counterexamples is a partition with two boxes, both with the first player winning if played optimally, so of course if the first player \"wins\" the first box, they immediately lose the second one and thus lose the whole game. In short, sometimes, tactically \"losing\" some boxes might be required. But how to know which player would lose if they both aimed for it? Now, introducing the \"mirrored\" version of a Nim game - a Misère Nim game, where the winning condition is the original Nim game's losing condition. If the peanut pockets always contain $1$ nut each, then the winner of a Misère Nim game can be easily declared by the parity of $n$. Otherwise, the winner of a Misère Nim game can be decided using the same nimber used in a regular Nim game: if the nimber is not $0$, the first player wins both the original and the Misère version; otherwise, the second player wins - the optimal strategies to acquire such outcome have the exact mirror intents of those in a regular Nim game. Also, surpassing the leading $1$s in array $a$, both Alice and Jack have the rights to tactically lose. Thus, any of them would win the game if and only if they could win the first box containing non-trivial pockets (here defined as pockets with more than $1$ nut, we'll call a box having at least one non-trivial pocket a non-trivial box) if both play optimally until there - as proven above, if they could theoretically win it, they could also tactically lose it, thus they would have full control of the game, and they could make a decision in accordance with whatever partition coming next in the remaining pockets. We'll denote $l$ as the number of trivial pockets (i.e. pockets with $1$ nut each) standing at the left side of array $a$, i.e., the $(l+1)^{th}$ pocket will be the leftmost one to have more than $1$ nut. We'll consider all possible options for first boxes containing non-trivial pockets, and thus we'll iterate $r$ in range $[l+1, n]$: First, we denote $P(r)$ as the xor sum of all elements of the prefix of array $a$ up until the $r^{th}$ element. This value will determine how much control Alice would have. If $P(r) = 0$, Alice will lose in all cases with the first non-trivial box ending at $r$. Proof is simple: if this box has an even amount of $1$s before it, obviously Alice will be the starting player of a game with nimber of $0$ and thus cannot control it to her will; and if the amount of preceding $1$s is odd, then the first non-trivial box is a game with nimber of $1$ and Jack as first player, thus Jack retains full control. If $P(r) = 1$, Alice will win in all cases with the first non-trivial box ending at $r$. Proof is literally the reverse of the above case. If $P(r) > 1$, both Alice and Jack have full control to win it, thus Alice will win if and only if she is the starting player of the game at the first non-trivial box. So we have the detailed winning condition. Now, towards the maths. First, whatever pockets after the first non-trivial box doesn't matter. Thus, for each $r$, there exists $2^{\\max(0, n-r-1)}$ different partitions of the pockets following the $r^{th}$ one. We don't consider cases with $P(r) = 0$, obviously. If $P(r) = 1$, all partitions involving only the first $l$ pockets are allowed. In fact, there are $l+1$ items here: $l$ trivial pockets, and the first non-trivial blob always coming last, thus the number of different partitions of the pockets preceding the $r^{th}$ one in this case is $2^l$. If $P(r) > 1$, we'll consider all even $l_0$ in range $[0, l]$, with $l_0$ denoting the number of $1$s not within the first non-trivial box. Clearly, for each $l_0$, the number of different partitions would be $2^{\\max(0, l_0-1)}$. And since $l$ is fixed and this process has no relation with $r$, this value could be pre-calculated. In more details, denoting that value as $M$, we have $M = \\sum_{i = 0}^{\\lfloor \\frac{l0}{2} \\rfloor} 2^{\\max(0, 2i-1)}$. All powers of $2$ could be pre-calculated as well, saving a considerable amount of runtime. All pre-calculations have time complexity in linear order of the maximum size of array $a$. Time complexity: $\\mathcal{O}(n)$.",
    "code": "class Solution:\n    hasMultipleTests = True\n\n    n: int = None\n    a: list = None\n    \n    MAXN: int = 1000000\n    MOD: int = 998244353\n    pow2: list = None\n\n    @classmethod\n    def preprocess(cls):\n        cls.pow2 = [None for _ in range(cls.MAXN)]\n        for i in range(cls.MAXN):\n            cls.pow2[i] = 1 if i == 0 else (2 * cls.pow2[i-1]) % cls.MOD\n\n    @classmethod\n    def input(cls, testcase):\n        cls.n = int(input())\n        cls.a = list(map(int, input().split()))\n\n    @classmethod\n    def solve(cls, testcase):\n        if max(cls.a) == 1:\n            return(print(cls.pow2[cls.n-1] if cls.n & 1 else 0))\n        \n        ans = 0\n\n        # The critical layer (assuming prefix Grundy > 1) can only fall into Alice's control\n        # if and only if before it is an even amount of pockets\n        alice_at_critical = 1\n        prefix_1 = 0\n        while cls.a[prefix_1] == 1:\n            prefix_1 += 1\n            \n            if prefix_1 % 2 == 0:\n                alice_at_critical = (alice_at_critical + cls.pow2[prefix_1 - 1]) % cls.MOD\n                \n        grundy = prefix_1 & 1\n        for r in range(prefix_1, cls.n):\n            grundy ^= cls.a[r]\n            \n            if grundy == 0: continue\n        \n            post_critical = cls.pow2[cls.n - 2 - r] if r < cls.n - 1 else 1\n            pre_critical = cls.pow2[prefix_1] if grundy == 1 else alice_at_critical\n            \n            ans = (ans + pre_critical * post_critical) % cls.MOD\n            \n        print(ans)\n\n# end Solution",
    "tags": [
      "combinatorics",
      "dp",
      "games",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2033",
    "index": "A",
    "title": "Sakurako and Kosuke",
    "statement": "Sakurako and Kosuke decided to play some games with a dot on a coordinate line. The dot is currently located in position $x=0$. They will be taking turns, and \\textbf{Sakurako will be the one to start}.\n\nOn the $i$-th move, the current player will move the dot in some direction by $2\\cdot i-1$ units. Sakurako will always be moving the dot in the negative direction, whereas Kosuke will always move it in the positive direction.\n\nIn other words, the following will happen:\n\n- Sakurako will change the position of the dot by $-1$, $x = -1$ now\n- Kosuke will change the position of the dot by $3$, $x = 2$ now\n- Sakurako will change the position of the dot by $-5$, $x = -3$ now\n- $\\cdots$\n\nThey will keep on playing while the absolute value of the coordinate of the dot does not exceed $n$. More formally, the game continues while $-n\\le x\\le n$. It can be proven that the game will always end.\n\nYour task is to determine who will be the one who makes the last turn.",
    "tutorial": "For this task we could just brute-force the answer by repeatedly adding or substracting the odd numbers from the initial position $0$. This would result in $O(n)$ time complexity. This is sufficient enough.",
    "code": "def solve():\n    n = int(input())\n    x = 0\n    c = 1\n    while -n <= x <= n:\n        if c % 2 == 1:\n            x -= 2 * c - 1\n        else:\n            x += 2 * c - 1\n        c += 1\n    if c % 2 == 0:\n        print(\"Sakurako\")\n    else:\n        print(\"Kosuke\")\n\n\nfor tc in range(int(input())):\n    solve()",
    "tags": [
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2033",
    "index": "B",
    "title": "Sakurako and Water",
    "statement": "During her journey with Kosuke, Sakurako and Kosuke found a valley that can be represented as a matrix of size $n \\times n$, where at the intersection of the $i$-th row and the $j$-th column is a mountain with a height of $a_{i,j}$. If $a_{i,j} < 0$, then there is a lake there.\n\nKosuke is very afraid of water, so Sakurako needs to help him:\n\n- With her magic, she can select a square area of mountains and increase the height of each mountain on the main diagonal of that area by exactly one.\n\nMore formally, she can choose a submatrix with the upper left corner located at $(i, j)$ and the lower right corner at $(p, q)$, such that $p-i=q-j$. She can then add one to each element at the intersection of the $(i + k)$-th row and the $(j + k)$-th column, for all $k$ such that $0 \\le k \\le p-i$.\n\nDetermine the minimum number of times Sakurako must use her magic so that there are no lakes.",
    "tutorial": "In this task we were supposed to find the minimal possible amount of moves that Sakurako needs to make in order to make all elements in the matrix non-negative. The key observation is to notice that Sakurako can only add simultaneously to elements that lay on one diagonal. For cell $(i,j)$, let the \"index\" of diagonal which it is placed on is equal to $d(i,j)=(i-j)$. This is proven by the fact that for $(i,j)$ and $(i+1,j+1)$ the equation $d(i,j)=d(i+1,j+1)$ holds. We are able to add to a pair of elements $(x,y)$ and $(x_1,y_1)$ simultaneously if and only if $d(x,y)=d(x_1,y_1)$. From this we can reduce our problem to finding the amount of times that we need to add 1 to this diagonal in order for all of its elements to become non-negative. For each diagonal we find the minimal element in it and there will be two cases: 1. The minimal element is non-negative: we don't need to add anything to that diagonal. 2. The minimal element is negative and equal to $x$: we will need to add one at least $-x$ times (remember that $x$ is negative). After that, the answer for our task is the sum of answers for each individual diagonal. Total time complexity $O(n^2)$",
    "code": "def solve():\n    n = int(input())\n    mn = dict()\n    for i in range(n):\n        a = [int(x) for x in input().split()]\n        for j in range(n):\n            mn[i - j] = min(a[j], mn.get(i - j, 0))\n    ans = 0\n    for value in mn.values():\n        ans -= value\n    print(ans)\n \nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "2033",
    "index": "C",
    "title": "Sakurako's Field Trip",
    "statement": "Even in university, students need to relax. That is why Sakurakos teacher decided to go on a field trip. It is known that all of the students will be walking in one line. The student with index $i$ has some topic of interest which is described as $a_i$. As a teacher, you want to minimise the disturbance of the line of students.\n\nThe disturbance of the line is defined as the number of neighbouring people with the same topic of interest. In other words, disturbance is the number of indices $j$ ($1 \\le j < n$) such that $a_j = a_{j + 1}$.\n\nIn order to do this, you can choose index $i$ ($1\\le i\\le n$) and swap students at positions $i$ and $n-i+1$. You can perform any number of swaps.\n\nYour task is to determine the minimal amount of disturbance that you can achieve by doing the operation described above any number of times.",
    "tutorial": "Note that the answer is influenced by neighboring elements. This allows us to optimally place elements $i$ and $n - i + 1$ with respect to elements $i - 1$ and $n - i + 2$. Thus, we need to be able to choose the best order for an array of $4$ elements. Let's consider several types of arrays: $[1, x, y, 1]$ or $[x, 1, 1, y]$ (the ones denote equal elements): swaps will not change the answer; $[1, 1, y, 2]$: a swap will improve the answer if $y \\ne 1$, otherwise the answer will not change; Thus, if $a[i - 1] = a[i]$ or $a[n - i + 2] = a[n - i + 1]$, then swapping elements $a[i]$ and $a[n - i + 1]$ will either not change the answer or improve it. After all swaps, we only need to calculate the final disturbance.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int a[n+1];\n        for(int i=1;i<=n;i++){\n            cin>>a[i];\n        }\n        for(int i=n/2-1;i>=1;i--){\n            if(a[i]==a[i+1] || a[n-i+1]==a[n-i]){\n                swap(a[i],a[n-i+1]);\n            }\n        }\n        int re=0;\n        for(int i=1;i<n;i++){\n            re+=(a[i]==a[i+1]);\n        }\n        cout<<re<<endl;\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2033",
    "index": "D",
    "title": "Kousuke's Assignment",
    "statement": "After a trip with Sakurako, Kousuke was very scared because he forgot about his programming assignment. In this assignment, the teacher gave him an array $a$ of $n$ integers and asked him to calculate the number of \\textbf{non-overlapping} segments of the array $a$, such that each segment is considered beautiful.\n\nA segment $[l,r]$ is considered beautiful if $a_l + a_{l+1} + \\dots + a_{r-1} + a_r=0$.\n\nFor a fixed array $a$, your task is to compute the maximum number of non-overlapping beautiful segments.",
    "tutorial": "For this task we were supposed to find the biggest amount of non-intersecting segments all of which have their sum equal to zero. First of all, the problem \"find the maximal number of non-intersecting segments\" is an exaxmple of a classic dynamic programming problem. First of all, we will sort all our segments by their right end in an increasing order. After that, we will be processing all segments one by one and updating our answer as follows: For a segment with fixed ends $l,r$, we will be updating our answer as follows. $dp_r=max(dp_{r-1},dp_{l-1}+1)$ Because we are processing all our segments one by one in that order, when we start computing $dp_r$, for all $i<r$ the maximal possible answer will already be computed. By filling the $dp$ array in this way, we are sure that the answer will always be contained in $dp_n$. Now back to our task: First of all, if we construct an array $p$ where $p_i=\\sum^i_{j=1}a_i$, $(p_0=0)$ then for every segment which has sum equal to $0$, $p_{l-1}=p_r$. It can be easily proven that for fixed $r$ there is at most one segment which will be useful for the optimal answer: If there is no $p_l$ where $l<r$ such that $p_l=p_r$, then there is no segment that ends in position $r$. Otherwise, it is sufficient to choose the one with the largest $l$. That is because if we chose the one with $l_1<l$, then we would have missed segment $[l_1+1,l]$. Because of that miss, we would not have found the correct answer for our $r$. So our final algorithm would be to find the smallest segments that end in position $r$ and have their sum equal to $0$. After that we can compute the answer by simply solving the maximal number of non-intersecting segments problem using dynamic programming. Total tme complexity $O(nlogn)$ or $O(n)$ depending on implementation.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int a[n+1];\n        map<int,int>mp;\n        for(int i=1;i<=n;i++){\n            cin>>a[i];\n        }\n        int p_su[n+1];\n        p_su[0]=0;\n        int lst[n+1];\n        mp[0]=0;\n        for(int i=1;i<=n;i++){\n            p_su[i]=p_su[i-1]+a[i];\n            if(mp.find(p_su[i])==mp.end()){\n                lst[i]=-1;\n            }\n            else{\n                lst[i]=mp[p_su[i]];\n            }\n            mp[p_su[i]]=i;\n        }\n        int dp[n+1];\n        memset(dp,0,sizeof dp);\n        for(int i=1;i<=n;i++){\n            dp[i]=max(dp[i],dp[i-1]);\n            if(lst[i]!=-1){\n                dp[i]=max(dp[i],dp[lst[i]]+1);\n            }\n        }\n        cout<<*max_element(dp,dp+n+1)<<endl;\n    }\n}",
    "tags": [
      "data structures",
      "dp",
      "dsu",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2033",
    "index": "E",
    "title": "Sakurako, Kosuke, and the Permutation",
    "statement": "Sakurako's exams are over, and she did excellently. As a reward, she received a permutation $p$. Kosuke was not entirely satisfied because he failed one exam and did not receive a gift. He decided to sneak into her room (thanks to the code for her lock) and spoil the permutation so that it becomes simple.\n\nA permutation $p$ is considered simple if for every $i$ $(1\\le i \\le n)$ one of the following conditions holds:\n\n- $p_i=i$\n- $p_{p_i}=i$\n\nFor example, the permutations $[1, 2, 3, 4]$, $[5, 2, 4, 3, 1]$, and $[2, 1]$ are simple, while $[2, 3, 1]$ and $[5, 2, 1, 4, 3]$ are not.\n\nIn one operation, Kosuke can choose indices $i,j$ $(1\\le i,j\\le n)$ and swap the elements $p_i$ and $p_j$.\n\nSakurako is about to return home. Your task is to calculate the minimum number of operations that Kosuke needs to perform to make the permutation simple.",
    "tutorial": "Lets make this the shortest editorial out of all. Observation $1$: All permutations can be split into cycles. All cycles of permutation can be traversed in $O(n)$ time. Observation $2$: When we are swapping $2$ elements that belong to one cycle, we are splitting our cycle into $2$ parts. If we rephrase our definition of simple permutation, we can see that the permutation is called simple if every cycle in it has length not larger than $2$. Observation $3$: By splitting our initial cycle of length $x$ repeatedly, we can achieve its division into cycles of length not larger than $2$ in $\\lfloor\\frac{x-1}{2}\\rfloor$ swaps. (this is achieved by repeatedly decreasing size of the cycle by $2$) Observation $4$: All cycles are independent, so the answer for the initial task is the sum of answers for every cycle. Total time complexity is $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n    int t;\n    ios_base::sync_with_stdio(false);cout.tie(nullptr);cin.tie(nullptr);\n    cin>>t;\n    while(t--){\n        int n;\n        cin>>n;\n        int p[n+1];\n        for(int i=1;i<=n;i++){\n            cin>>p[i];\n        }\n        bool us[n+1];\n        memset(us,0,sizeof us);\n        int re=0;\n        for(int i=1;i<=n;i++){\n            if(!us[i]){\n                int cu=i;\n                int le=0;\n                while(us[cu]==0){\n                    le++;\n                    us[cu]=1;\n                    cu=p[cu];\n                }\n                re+=(le-1)/2;\n            }\n        }\n        cout<<re<<'\\n';\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2033",
    "index": "F",
    "title": "Kosuke's Sloth",
    "statement": "Kosuke is too lazy. He will not give you any legend, just the task:\n\nFibonacci numbers are defined as follows:\n\n- $f(1)=f(2)=1$.\n- $f(n)=f(n-1)+f(n-2)$ $(3\\le n)$\n\nWe denote $G(n,k)$ as an index of the $n$-th Fibonacci number that is divisible by $k$. For given $n$ and $k$, compute $G(n,k)$.As this number can be too big, output it by modulo $10^9+7$.\n\nFor example: $G(3,2)=9$ because the $3$-rd Fibonacci number that is divisible by $2$ is $34$. $[1,1,\\textbf{2},3,5,\\textbf{8},13,21,\\textbf{34}]$.",
    "tutorial": "This was one of my favourite tasks untill I realised that the amount of numbers in Fibonacci cycle is either $1$, $2$ or $4$... First of all, the length of cycle after which our sequence would be repeating for modulo $k$ is at most $6k$ (We will just take this as a fact for now, it is too long to explain but you can read it here. Now, if we know that the amount of operations needed to take untill we are in a cycle is at most $6k$, we can brute-force our solution in $O(k)$ time. Also, one last thing that we will need to consider is the fact that if $F_i$ is divisible by $k$, then for every $j$, $F_{i\\cdot j}$ is also divisible by $k$. Proof: as we know, $gcd(F_n,F_m)=F_{gcd(n,m)}$ so if we take any multiple of $i$ as $n$ and $i=m$, then the $gcd(F_{n},F_{m})$ would be equal to $F_{i}$. And because $F_{i}$ is divisible by $k$, every other multiple of $i$ is going to be also divisible by $k$. So, our final solution would be brute-forcing first $6k$ Fibonacci numbers and their remainder after division by $k$ in order to find the first one that is divisible by $k$. Then just multiply that number by $n$ and we will get the answer for our task. Also, don't forget to take everything via modulo $10^9+7$. (Someone kept whining about it in comments) Total time complexity $O(k)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nusing LL = long long;\n#define ssize(x) (int)(x.size())\n#define ALL(x) (x).begin(), (x).end()\n \nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n \nint rd(int l, int r) {\n    return uniform_int_distribution<int>(l, r)(rng);\n}\nconst LL MOD = 1e9 + 7;\nint bp(int a, int n) {\n    if (n == 0)\n        return 1;\n    if (n % 2 == 0)\n        return bp(1LL * a * a % MOD, n / 2);\n    else\n        return 1LL * bp(a, n - 1) * a % MOD;\n}\nint inv(int a) {\n    return bp(a, MOD - 2);\n}\nvoid solve() {\n    LL n, k;\n    cin >> n >> k;\n    n %= MOD;\n    if (k == 1) {\n        cout << n << \"\\n\";\n        return;\n    }\n    vector<int> fib(3);\n    fib[0] = fib[1] = 1;\n    int cnt = 0;\n    for (int i = 2; i <= 10 * k; i++) {\n        fib[i % 3] = (fib[(i + 2) % 3] + fib[(i + 1) % 3]) % k;\n        if (fib[i % 3] == 0)\n            cnt++;\n        if (fib[i % 3] == 1 && fib[(i + 2) % 3] == 0) {\n            cout << 1LL * i * n % MOD * inv(cnt) % MOD << \"\\n\";\n            return;\n        }\n    }\n}\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t = 1;\n     cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2033",
    "index": "G",
    "title": "Sakurako and Chefir",
    "statement": "Given a tree with $n$ vertices rooted at vertex $1$. While walking through it with her cat Chefir, Sakurako got distracted, and Chefir ran away.\n\nTo help Sakurako, Kosuke recorded his $q$ guesses. In the $i$-th guess, he assumes that Chefir got lost at vertex $v_i$ and had $k_i$ stamina.\n\nAlso, for each guess, Kosuke assumes that Chefir could move along the edges an arbitrary number of times:\n\n- from vertex $a$ to vertex $b$, if $a$ \\textbf{is an ancestor}$^{\\text{∗}}$ of $b$, the stamina will not change;\n- from vertex $a$ to vertex $b$, if $a$ \\textbf{is not an ancestor} of $b$, then Chefir's stamina decreases by $1$.\n\nIf Chefir's stamina is $0$, he cannot make a move of the second type.\n\nFor each assumption, your task is to find the distance to the farthest vertex that Chefir could reach from vertex $v_i$, having $k_i$ stamina.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$Vertex $a$ is an ancestor of vertex $b$ if the shortest path from $b$ to the root passes through $a$.\n\\end{footnotesize}",
    "tutorial": "In each query, Chefir can ascend from vertex $v$ by no more than $k$. To maximize the distance, we need to first ascend $x$ times ($0 \\le x \\le k$), and then descend to the deepest vertex. For each vertex $u$, we will find $maxd[v].x$ - the distance to the farthest descendant of vertex $u$. We will also need $maxd[v].y$ - the distance to the farthest descendant of vertex $u$ from a different subtree of vertex $v$, which will allow us to avoid counting any edges twice when searching for the answer. Now we can construct binary lifts. The lift by $2^i$ from vertex $u$ will store information about all vertices from $u$ to the $(2^i)$-th ancestor, excluding vertex $u$ itself. The value of the lift from vertex $u$ by $1$ (i.e., to its ancestor $p$) will be calculated as follows: if $maxd[v].x + 1 < maxd[p].x$, then the value is equal to $maxd[p].x - h(p)$, and $maxd[p].y - h(p)$ otherwise. Here, $h(p)$ is the distance from vertex $p$ to the root. The subsequent lifts will be computed as the maximums of the corresponding values. The constructed maximums will not account for cases where any edge was traversed twice. Thus, by ascending from vertex $v$ by $k$, we will be able to find the best value of the form $\\text{max_depth} - h(u)$, and by adding $h(v)$ to it, we will obtain the distance to the desired vertex.",
    "code": "#include <bits/stdc++.h>\n \n//#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n \ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(time(nullptr));\n \nconst int inf = 1e9;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n \nvoid precalc(int v, int p, vector<vector<int>> &sl, vector<pair<int, int>> &maxd, vector<int> &h){\n    maxd[v] = {0, 0};\n    if (v != p) h[v] = h[p] + 1;\n    for(int u: sl[v]){\n        if (u == p) continue;\n        precalc(u, v, sl, maxd, h);\n        if (maxd[v].y < maxd[u].x + 1) {\n            maxd[v].y = maxd[u].x + 1;\n        }\n        if (maxd[v].y > maxd[v].x) {\n            swap(maxd[v].x, maxd[v].y);\n        }\n    }\n}\n \nvoid calc_binups(int v, int p, vector<vector<int>> &sl, vector<vector<pair<int, int>>> &binup, vector<pair<int, int>> &maxd, vector<int> &h){\n    binup[v][0] = {maxd[p].x, p};\n    if (maxd[p].x == maxd[v].x + 1) {\n        binup[v][0].x = maxd[p].y;\n    }\n    binup[v][0].x -= h[p];\n    for(int i = 1; i < 20; ++i){\n        binup[v][i].y = binup[binup[v][i - 1].y][i - 1].y;\n        binup[v][i].x = max(binup[v][i - 1].x, binup[binup[v][i - 1].y][i - 1].x);\n    }\n \n    for(int u: sl[v]){\n        if (u == p) continue;\n        calc_binups(u, v, sl, binup, maxd, h);\n    }\n}\n \nint get_ans(int v, int k, vector<vector<pair<int, int>>> &binup, vector<pair<int, int>> &maxd, vector<int> &h){\n    k = min(k, h[v]);\n    int res = maxd[v].x - h[v];\n    int ini = h[v];\n    for(int i = 19; i >= 0; --i){\n        if ((1 << i) <= k) {\n            res = max(res, binup[v][i].x);\n            v = binup[v][i].y;\n            k -= (1 << i);\n        }\n    }\n    return res + ini;\n}\n \nvoid solve(int tc){\n    int n;\n    cin >> n;\n    vector<vector<int>> sl(n);\n    for(int i = 1; i < n; ++i){\n        int u, v;\n        cin >> u >> v;\n        sl[--u].emplace_back(--v);\n        sl[v].emplace_back(u);\n    }\n    vector<pair<int, int>> maxd(n);\n    vector<int> h(n);\n    precalc(0, 0, sl, maxd, h);\n    vector<vector<pair<int, int>>> binup(n, vector<pair<int, int>>(20));\n    calc_binups(0, 0, sl, binup, maxd, h);\n    int q;\n    cin >> q;\n    for(int _ = 0; _ < q; ++_){\n        int v, k;\n        cin >> v >> k;\n        cout << get_ans(v - 1, k, binup, maxd, h) << \" \";\n    }\n}\n \nbool multi = true;\n \nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2034",
    "index": "A",
    "title": "King Keykhosrow's Mystery",
    "statement": "There is a tale about the wise King Keykhosrow who owned a grand treasury filled with treasures from across the Persian Empire. However, to prevent theft and ensure the safety of his wealth, King Keykhosrow's vault was sealed with a magical lock that could only be opened by solving a riddle.\n\nThe riddle involves two sacred numbers $a$ and $b$. To unlock the vault, the challenger must determine the smallest key number $m$ that satisfies two conditions:\n\n- $m$ must be greater than or equal to at least one of $a$ and $b$.\n- The remainder when $m$ is divided by $a$ must be equal to the remainder when $m$ is divided by $b$.\n\nOnly by finding the smallest correct value of $m$ can one unlock the vault and access the legendary treasures!",
    "tutorial": "Step 1: Prove that for the minimum value of $m$, we must have $m \\% a = m \\% b = 0$. Step 2: To prove this, show that if $m \\% a = m \\% b = x > 0$, then $m-1$ will also satisfy the problem's requirements. Step 3: Since $m \\ge \\min(a , b)$, if $x > 0$, then $m > \\min(a , b)$ must hold. Therefore, $m - 1 \\ge \\min(a , b)$ implies that $m-1$ satisfies the requirements. Step 4: Thus, $m$ must be divisible by both $a$ and $b$. The smallest such $m$ is $lcm(a, b)$ which can be calculated in $O(\\log(\\max(a, b)))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main(){\n  int tt;\n  cin >> tt;\n  while(tt--){\n    int a, b;\n    cin >> a >> b;\n    cout << lcm(a , b) << endl;\n  }\n}",
    "tags": [
      "brute force",
      "chinese remainder theorem",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2034",
    "index": "B",
    "title": "Rakhsh's Revival",
    "statement": "Rostam's loyal horse, Rakhsh, has seen better days. Once powerful and fast, Rakhsh has grown weaker over time, struggling to even move. Rostam worries that if too many parts of Rakhsh's body lose strength at once, Rakhsh might stop entirely. To keep his companion going, Rostam decides to strengthen Rakhsh, bit by bit, so no part of his body is too frail for too long.\n\nImagine Rakhsh's body as a line of spots represented by a binary string $s$ of length $n$, where each $0$ means a weak spot and each $1$ means a strong one. Rostam's goal is to make sure that no interval of $m$ consecutive spots is entirely weak (all $0$s).\n\nLuckily, Rostam has a special ability called Timar, inherited from his mother Rudabeh at birth. With Timar, he can select any segment of length $k$ and instantly strengthen all of it (changing every character in that segment to $1$). The challenge is to figure out the minimum number of times Rostam needs to use Timar to keep Rakhsh moving, ensuring there are no consecutive entirely weak spots of length $m$.",
    "tutorial": "We will solve the problem using the following approach: Start from the leftmost spot and move rightwards. Whenever a consecutive segment of $m$ weak spots (i.e., $0$'s) is found, apply Timar to a segment of length $k$, starting from the last index of the weak segment. Repeat this process until no segment of $m$ consecutive weak spots remains. The key idea behind this solution is that whenever we encounter a block of $m$ consecutive $0$'s, we need to strengthen it. Since we can apply Timar to a segment of length $k$, the optimal strategy is always to apply Timar starting at the last index of the block of $m$ consecutive $0$'s. Correctness Proof: For any block of $m$ consecutive $0$'s, we must apply Timar to at least one index within this block. Hence, the strengthened segment of length $k$ must overlap with the block of weak spots. Suppose an optimal solution exists where Timar is applied to a segment starting leftward within the block. Suppose we shift this segment one step to the right (closer to the end of the block). In that case, the solution remains valid and optimal since it covers all weak spots in the block while reducing unnecessary overlap with already-strengthened areas. By always starting from the last index of a block of $m$ consecutive $0$'s, this greedy strategy ensures that Timar is used in the minimum number of applications, making it correct and efficient.",
    "code": "# include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int xn = 2e5 + 10;\n\nint q, n, m, k, ps[xn];\nstring s;\n\nint main() {\n    cin >> q;\n    while (q --) {\n        cin >> n >> m >> k >> s;\n        fill(ps, ps + n, 0);\n        int ans = 0, cnt = 0, sum = 0;\n        for (int i = 0; i < n; ++ i) {\n            sum += ps[i];\n            if (sum || s[i] == '1') cnt = 0;\n            else {\n                cnt++;\n                if (cnt == m) {\n                    sum++, ans++, cnt = 0;\n                    if (i + k < n) ps[i + k]--;\n                }\n            }\n        }\n        cout << ans << \"\\n\";\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "two pointers"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2034",
    "index": "C",
    "title": "Trapped in the Witch's Labyrinth",
    "statement": "In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $n$ rows and $m$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.\n\nIf Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.\n\nThe witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.",
    "tutorial": "If a cell has a fixed direction (i.e., it points to another cell), and following that direction leads outside the maze, it must eventually exit the maze. Such cells cannot be part of any loop. We can analyze the remaining cells once we identify cells that lead out of the maze. Any undirected cell or $?$ cell might either lead to the exit or form part of a loop. If all neighboring cells of a $?$ cell can eventually lead out of the maze, then this $?$ cell will also lead out of the maze. The state of such $?$ cells can be determined based on their surroundings. For any remaining cells (directed cells that do not lead out of the maze, or other $?$ cells that cannot be determined to lead to an exit), we can assign directions such that starting from those cells will eventually lead to a loop. These cells will form the loops. To find how many cells will eventually lead to a loop, we can use a Depth-First Search (DFS) on the reversed graph, where all directions are reversed. By performing DFS starting from the \"out-of-maze\" cells, we can identify all cells that are reachable from the outside and thus will eventually lead out of the maze. Count the number of cells that can reach the exit. Subtract this number from the total number of cells in the maze to determine how many are part of loops (i.e., cells that cannot reach the exit).",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() \n{\n    int tc;\n    cin >> tc;\n    while(tc--){\n        int n, m;\n        cin >> n >> m;\n        string c[n+1];\n        for(int i = 1 ; i <= n ; i++) cin >> c[i] , c[i] = \"-\" + c[i];\n        vector<pair<int,int>> jda[n+2][m+2];\n        for(int i = 1 ; i <= n ; i++){\n            for(int j = 1 ; j <= m ; j++){\n                if(c[i][j] == 'U') jda[i-1][j].push_back({i , j});\n                if(c[i][j] == 'R') jda[i][j+1].push_back({i , j});\n                if(c[i][j] == 'D') jda[i+1][j].push_back({i , j});\n                if(c[i][j] == 'L') jda[i][j-1].push_back({i , j});\n            }\n        }\n        int vis[n+2][m+2] = {};\n        queue<pair<int,int>> q;\n        for(int j = 0 ; j <= m+1 ; j++) vis[0][j] = 1 , q.push({0 , j});\n        for(int i = 1 ; i <= n+1 ; i++) vis[i][0] = 1 , q.push({i , 0});\n        for(int j = 1 ; j <= m+1 ; j++) vis[n+1][j] = 1 , q.push({n+1 , j});\n        for(int i = 1 ; i <= n ; i++) vis[i][m+1] = 1 , q.push({i , m+1});\n        while(q.size()){\n            auto [i , j] = q.front();\n            q.pop();\n            for(auto [a , b] : jda[i][j]){\n                if(vis[a][b] == 0){\n                    vis[a][b] = 1;\n                    q.push({a , b});\n                }\n            }\n        }\n        for(int i = 1 ; i <= n ; i++){\n            for(int j = 1 ; j <= m ; j++){\n                if(c[i][j] == '?' and\n                vis[i-1][j] and vis[i][j+1] and vis[i+1][j] and vis[i][j-1]) vis[i][j] = 1;\n            }\n        }\n        int ans = n * m;\n        for(int i = 1 ; i <= n ; i++){\n            for(int j = 1 ; j <= m ; j++){\n                if(vis[i][j] == 1) ans -= 1;\n            }\n        }\n        cout << ans << endl;\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2034",
    "index": "D",
    "title": "Darius' Wisdom",
    "statement": "Darius the Great is constructing $n$ stone columns, each consisting of a base and between $0$, $1$, or $2$ inscription pieces stacked on top.\n\nIn each move, Darius can choose two columns $u$ and $v$ such that the difference in the number of inscriptions between these columns is exactly $1$, and transfer one inscription from the column with more inscriptions to the other one. It is guaranteed that at least one column contains exactly $1$ inscription.\n\nSince beauty is the main pillar of historical buildings, Darius wants the columns to have ascending heights. To avoid excessive workers' efforts, he asks you to plan a sequence of \\textbf{at most $n$} moves to arrange the columns in non-decreasing order based on the number of inscriptions. Minimizing the number of moves is \\textbf{not required}.",
    "tutorial": "Step 1: Using two moves, we can move an element to any arbitrary position in the array. Thus, we can place all $0$'s in their correct positions with at most $2 \\min(count(0), count(1) + count(2))$ moves. Step 2: After placing all $0$'s, the rest of the array will contain only $1$'s and $2$'s. To sort this part of the array, we need at most $min(count(1), count(2))$ moves. Step 3: The first step takes at most $n$ moves, and the second step takes at most $\\frac{n}{2}$ moves. However, it can be proven that the total number of moves is at most $\\frac{8n}{7}$. Step 4: We can assume $count(0) \\leq count(2)$ without loss of generality (Why?). So, the maximum number of moves are: $2 \\min(count(0), count(1)+count(2))+\\min(count(1), count(2))$ $= 2 \\cdot count(0) + \\min(count(1), count(2))$ $\\le count(0) + \\max(count(1), count(2)) + \\min(count(1), count(2))$ $=count(0)+count(1)+count(2)=n$ Better approach: Step 1: Since we are allowed to perform $n$ moves, assign each index one \"move\" as its \"specified cost\". Step 2: While there exists an index with a value of $0$ or $2$ that can be fixed with just one move, fix it using its assigned cost. Step 3: After fixing all $0$'s, $2$'s, and all $1$'s except one, the remaining array will have the following structure and we are now allowed to use $2x+1$ moves: $2\\ 2\\ \\dots\\ 2\\ (x\\ \\text{times})\\ 1\\ 0\\ 0\\ \\dots\\ 0\\ (x\\ \\text{times}),$ Step 4: First, swap the $1$ with a random element (denote it as $r$). Then, for $2x-1$ moves, swap the index with the value $1$ with any index where the correct value must be placed, except $r$. Finally, swap $1$ and $r$.",
    "code": "// In the name of god\n#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 200000;\nint n, cnt[3], a[N];\nvector<int> vip[3][3]; // Value In Position\nvector<pair<int, int>> swaps;\n\ninline int Pos(int index) {\n    if(index < cnt[0])\n        return 0;\n    else if(index < cnt[0]+cnt[1])\n        return 1;\n    else\n        return 2; \n}\n\ninline void AddBack(int index) {\n    vip[a[index]][Pos(index)].push_back(index);\n}\n\ninline void RemoveBack(int index) {\n    vip[a[index]][Pos(index)].pop_back();\n}\n\ninline void Swap(int i, int j) {\n    swaps.push_back({i, j});\n    RemoveBack(i);\n    RemoveBack(j);\n    swap(a[i], a[j]);\n    AddBack(i);\n    AddBack(j);\n}\n\ninline void Fix() {\n    bool change;\n    do {\n        change = false;\n        while ((!vip[1][0].empty()) && (!vip[0][1].empty()))\n            Swap(vip[1][0].back(), vip[0][1].back()), change = true;\n        while ((!vip[1][0].empty()) && (!vip[0][2].empty()))\n            Swap(vip[1][0].back(), vip[0][2-0].back()), change = true;\n        while ((!vip[1][2].empty()) && (!vip[2][1].empty()))\n            Swap(vip[1][2].back(), vip[2][1].back()), change = true;\n        while ((!vip[1][2].empty()) && (!vip[2][0].empty()))\n            Swap(vip[1][2].back(), vip[2][0].back()), change = true;\n    } while (change);    \n}\n\ninline void PingPong() {\n    if(vip[0][2].empty())\n        return;\n    Swap(vip[1][1].back(), vip[0][2].back());\n    while (true){\n        Swap(vip[1][2].back(), vip[2][0].back());\n        if(vip[0][2].empty())\n            break;\n        Swap(vip[1][0].back(), vip[0][2].back());\n    }\n    Swap(vip[1][0].back(), vip[0][1].back());\n}\n\nint main() \n{\n    ios_base::sync_with_stdio(false), cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        cin >> n;\n        for(int i = 0; i < n; i++)\n            cin >> a[i], cnt[a[i]]++;\n        for(int i = 0; i < n; i++)\n            AddBack(i);\n        Fix();\n        PingPong();\n        cout << swaps.size() << endl;\n        for(auto [i, j]: swaps)\n            cout << i+1 << ' ' << j+1 << endl;\n        // reset\n        cnt[0] = cnt[1] = cnt[2] = 0;\n        for(int i = 0; i < 3; i++)\n            for(int j = 0; j < 3; j++)\n                vip[i][j].clear();\n        swaps.clear();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2034",
    "index": "E",
    "title": "Permutations Harmony",
    "statement": "Rayan wants to present a gift to Reyhaneh to win her heart. However, Reyhaneh is particular and will only accept a k-harmonic set of permutations.\n\nWe define a k-harmonic set of permutations as a set of $k$ \\textbf{pairwise distinct} permutations $p_1, p_2, \\ldots, p_k$ of size $n$ such that for every pair of indices $i$ and $j$ (where $1 \\leq i, j \\leq n$), the following condition holds:\n\n$$ p_1[i] + p_2[i] + \\ldots + p_k[i] = p_1[j] + p_2[j] + \\ldots + p_k[j] $$\n\nYour task is to help Rayan by either providing a valid k-harmonic set of permutations for given values of $n$ and $k$ or by determining that such a set does not exist.\n\nWe call a sequence of length $n$ a permutation if it contains every integer from $1$ to $n$ exactly once.",
    "tutorial": "Step 1: There are $n$ positions that must be equal, and their sum is $\\frac{n \\cdot (n+1) \\cdot k}{2}$. Hence, each position must be $\\frac{(n+1) \\cdot k}{2}$. Additionally, there must be $k$ distinct permutations, so $k \\leq n!$. Step 2: For even $k$, we can group $n!$ permutations into $\\frac{n!}{2}$ double handles, where each group corresponds to a solution for $k = 2$. Then, pick $\\frac{k}{2}$ handles. The match for permutation $a_1, a_2, \\ldots, a_n$ is $(n+1)-a_1, (n+1)-a_2, \\ldots, (n+1)-a_n$. Step 3: For $k = 1$, $n$ must be $1$. Symmetrically, $k$ cannot be $n! - 1$. Solutions for other odd $k$ will now be provided. Step 4: To construct an answer for $k = 3$ and $n = 2x + 1$, consider the following derived using a greedy approach: Step 5: Now, combine the solution for even $k$ and the $k = 3$ solution by selecting the 3 permutations and $\\frac{k-3}{2}$ other handles.",
    "code": "// In the name of God\n#include <bits/stdc++.h>\nusing namespace std;\n \nint main() {\n    ios_base::sync_with_stdio(false), cin.tie(0);\n    int t;\n    cin >> t;\n    int f[8] = {1,1,2,6,24,120,720,5040};\n    while(t--) {\n        int n, k;\n        cin >> n >> k;\n        if(min(n, k) == 1) {\n            if(n*k == 1) {\n                cout << \"Yes\\n1\\n\";\n            } else cout << \"No\\n\";\n        } else if(n < 8 and (f[n] < k or f[n] == k+1)) {\n            cout << \"No\\n\";\n        } else if(n % 2 == 0 and k % 2 == 1) {\n            cout << \"No\\n\";\n        } else {\n            vector<vector<int>> base, all;\n            vector<int> per(n);\n            for(int i = 0; i < n; i++) per[i] = i+1;\n            if(k % 2) {\n                vector<int> p1(n), p2(n);\n                for(int i = 0; i < n; i += 2) p1[i] = (n+1)/2-i/2, p2[i] = n-i/2;\n                for(int i = 1; i < n; i += 2) p1[i] = n-i/2, p2[i] = n/2-i/2;\n                all = base = {per, p1, p2};\n                k -= 3;\n            }\n            do {\n                if(k == 0)\n                    break;\n                vector<int> mirror(n);\n                for(int i = 0; i < n; i++)\n                    mirror[i] = n+1-per[i];\n                if(per < mirror) {\n                    bool used = false;\n                    for(auto &p: base) used |= (p == per), used |= (p == mirror);\n                    if(not used) {\n                        k -= 2;\n                        all.push_back(per);\n                        all.push_back(mirror);\n                    }\n                }\n            } while (next_permutation(per.begin(), per.end()));\n            cout << \"Yes\\n\";\n            for(auto p: all) {\n                for(int i = 0; i < n; i++)\n                    cout << p[i] << (i+1==n?'\\n':' ');\n            }\n        }\n    }\n \n    return 0;\n}\n \n// Thanks God\n",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "hashing",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2034",
    "index": "F1",
    "title": "Khayyam's Royal Decree (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only differences between the two versions are the constraints on $k$ and the sum of $k$.}\n\nIn ancient Persia, Khayyam, a clever merchant and mathematician, is playing a game with his prized treasure chest containing $n$ red rubies worth $2$ dinars each and $m$ blue sapphires worth $1$ dinar each. He also has a satchel, which starts empty, and $k$ scrolls with pairs $(r_1, b_1), (r_2, b_2), \\ldots, (r_k, b_k)$ that describe special conditions.\n\nThe game proceeds for $n + m$ turns as follows:\n\n- Khayyam draws a gem uniformly at random from the chest.\n- He removes the gem from the chest and places it in his satchel.\n- If there exists a scroll $i$ ($1 \\leq i \\leq k$) such that the chest contains exactly $r_i$ red rubies and $b_i$ blue sapphires, Khayyam receives a royal decree that doubles the value of all the gems in his satchel as a reward for achieving a special configuration.\n\nNote that the value of some gems might be affected by multiple decrees, and in that case the gems' value is doubled multiple times.\n\nDetermine the expected value of Khayyam's satchel at the end of the game, modulo $998,244,353$.\n\nFormally, let $M = 998,244,353$. It can be shown that the exact answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Step 1: For simplicity, redefine the special conditions for the number of rubies and sapphires in your satchel (not chest). Add two dummy states, $(0,0)$ and $(n,m)$ for convenience (the first one indexed as $0$ and the second one indexed as $k+1$). Note that these dummy states won't involve doubling the value. Step 2: Order the redefined conditions $(x, y)$ in increasing order based on the value of $x + y$. Step 3: Define $ways_{i,j}$ as the number of ways to move from state $i$ to state $j$ without passing through any other special condition. This can be computed using inclusion-exclusion in $O(k^3)$. Step 4: Define $cost_{i,j}$, the increase in value for moving directly from state $i$ to state $j$ without intermediate doubling, as: $cost_{i,j} = 2|x_i - x_j| + |y_i - y_j|$ Step 5: Define $dp_i$ as the total sum of the value of your satchel across all ways to reach the state defined by the $i$-th condition. This can be computed recursively as: $dp_i = 2 \\sum_{0 \\leq j < i} ways_{j,i} \\times (dp_j + \\binom{x_j + y_j}{x_j} \\times cost_{j,i})$ Step 6: Compute the final answer as the value of $dp_{k+1}$ divided by the total number of ways to move from $(0,0)$ to $(n,m)$, which is $\\binom{n+m}{n}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define nl \"\\n\"\n#define nf endl\n#define ll long long\n#define pb push_back\n#define _ << ' ' <<\n \n#define INF (ll)1e18\n#define mod 998244353\n#define maxn 400010\n \nll fc[maxn], nv[maxn];\n \nll fxp(ll b, ll e) {\n    ll r = 1, k = b;\n    while (e != 0) {\n        if (e % 2) r = (r * k) % mod;\n        k = (k * k) % mod; e /= 2;\n    }\n    return r;\n}\n \nll inv(ll x) {\n    return fxp(x, mod - 2);\n}\n \nll bnm(ll a, ll b) {\n    if (a < b || b < 0) return 0;\n    ll r = (fc[a] * nv[b]) % mod;\n    r = (r * nv[a - b]) % mod;\n    return r;\n}\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    fc[0] = 1; nv[0] = 1;\n    for (ll i = 1; i < maxn; i++) {\n        fc[i] = (i * fc[i - 1]) % mod; nv[i] = inv(fc[i]);\n    }\n \n    ll t; cin >> t;\n    while (t--) {\n        ll n, m, k; cin >> n >> m >> k;\n        vector<array<ll, 2>> a(k + 2, {0, 0});\n        for (ll i = 1; i <= k; i++) {\n            cin >> a[i][0] >> a[i][1];\n            a[i][0] = n - a[i][0]; a[i][1] = m - a[i][1];\n        }\n        a[k + 1] = {n, m}; k++;\n        sort(a.begin() + 1, a.end());\n \n        auto paths = [&](ll i, ll j) {\n            ll dx = a[j][0] - a[i][0], dy = a[j][1] - a[i][1];\n            return bnm(dx + dy, dx);\n        };\n \n        auto add = [&](ll &x, ll y) {\n            x = (x + y) % mod;\n            x = (x + mod) % mod;\n        };\n \n        vector direct(k + 1, vector<ll>(k + 1, 0));\n        for (ll i = 1; i <= k; i++) {\n            for (ll j = i - 1; j >= 0; j--) {\n                direct[j][i] = paths(j, i);\n                for (ll l = j + 1; l < i; l++) {\n                    add(direct[j][i], -paths(j, l) * direct[l][i]);\n                }\n            }\n        }\n \n        vector<ll> dp(k + 1, 0);\n        for (ll i = 1; i <= k; i++) {\n            for (ll j = 0; j < i; j++) {\n                if (direct[j][i] == 0) continue;\n                ll partial = dp[j];\n                ll delta = 2 * (a[i][0] - a[j][0]) + (a[i][1] - a[j][1]);\n                add(partial, paths(0, j) * delta);\n                add(dp[i], partial * direct[j][i]);\n            }\n            if (i != k) dp[i] = (2 * dp[i]) % mod;\n        }\n \n        ll ans = (dp[k] * inv(bnm(n + m, m))) % mod;\n        cout << ans << nl;\n    }\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2034",
    "index": "F2",
    "title": "Khayyam's Royal Decree (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only differences between the two versions are the constraints on $k$ and the sum of $k$.}\n\nIn ancient Persia, Khayyam, a clever merchant and mathematician, is playing a game with his prized treasure chest containing $n$ red rubies worth $2$ dinars each and $m$ blue sapphires worth $1$ dinar each. He also has a satchel, which starts empty, and $k$ scrolls with pairs $(r_1, b_1), (r_2, b_2), \\ldots, (r_k, b_k)$ that describe special conditions.\n\nThe game proceeds for $n + m$ turns as follows:\n\n- Khayyam draws a gem uniformly at random from the chest.\n- He removes the gem from the chest and places it in his satchel.\n- If there exists a scroll $i$ ($1 \\leq i \\leq k$) such that the chest contains exactly $r_i$ red rubies and $b_i$ blue sapphires, Khayyam receives a royal decree that doubles the value of all the gems in his satchel as a reward for achieving a special configuration.\n\nNote that the value of some gems might be affected by multiple decrees, and in that case the gems' value is doubled multiple times.\n\nDetermine the expected value of Khayyam's satchel at the end of the game, modulo $998,244,353$.\n\nFormally, let $M = 998,244,353$. It can be shown that the exact answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.",
    "tutorial": "Step 1: For simplicity, redefine the special conditions for the number of rubies and sapphires in your satchel (not chest). Step 2: Order the redefined conditions $(x, y)$ in increasing order based on the value of $x + y$. Step 3: Define $total_{i,j}$ as the total number of ways to move from state $i$ to state $j$ (ignoring special condition constraints). This can be computed as: $total_{i,j} = \\binom{|x_i - x_j| + |y_i - y_j|}{|x_i - x_j|}$ Step 4: Define $weight_i$ as the total contribution of all paths passing through condition $i$ to reach the final state $(n, m)$. This can be computed recursively as: $weight_i = \\sum_{i < j \\leq k} total_{i,j} \\times weight_j$ Step 5: The main insight is to account for the doubling effect of passing through multiple scrolls. If a path passes through a sequence of conditions $s_1, \\dots, s_c$, each gem collected before entering $s_1$ is counted with multiplicity $2^c$. Instead of explicitly multiplying by $2^c$, consider the number of subsets $q_1, \\dots, q_d$ of $s_1, \\dots, s_c$. By summing over all subsets, the correct multiplicity is automatically handled. Step 6: Define $dp_i$ as the total value of all paths passing through condition $i$, considering the contribution of each state's rubies and sapphires. This can be computed as: $dp_i = (2x_i + y_i) \\times total_{0, i} \\times weight_i$ Step 7: Compute the final answer as $\\sum dp_i$ divided by the total number of ways to move from $(0,0)$ to $(n,m)$, which is equal to $\\binom{n+m}{n}$. Clarification: The approach hinges on the insight that $2^i$ can be derived from the structure of subsets of scrolls $s_1, \\dots, s_c$. Generalizations to $3^i$ or other multiplicative factors are possible by appropriately modifying $weight_i$ and adjusting the factor in Step 5. For example, a factor of 3 can be applied by multiplying path contributions by 2 at the relevant steps.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \n#define nl \"\\n\"\n#define nf endl\n#define ll long long\n#define pb push_back\n#define _ << ' ' <<\n \n#define INF (ll)1e18\n#define mod 998244353\n#define maxn 400010\n \nll fc[maxn], nv[maxn];\n \nll fxp(ll b, ll e) {\n    ll r = 1, k = b;\n    while (e != 0) {\n        if (e % 2) r = (r * k) % mod;\n        k = (k * k) % mod; e /= 2;\n    }\n    return r;\n}\n \nll inv(ll x) {\n    return fxp(x, mod - 2);\n}\n \nll bnm(ll a, ll b) {\n    if (a < b || b < 0) return 0;\n    ll r = (fc[a] * nv[b]) % mod;\n    r = (r * nv[a - b]) % mod;\n    return r;\n}\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    fc[0] = 1; nv[0] = 1;\n    for (ll i = 1; i < maxn; i++) {\n        fc[i] = (i * fc[i - 1]) % mod; nv[i] = inv(fc[i]);\n    }\n \n    ll t; cin >> t;\n    while (t--) {\n        ll n, m, k; cin >> n >> m >> k;\n        vector<array<ll, 2>> a(k + 2, {0, 0});\n        for (ll i = 1; i <= k; i++) {\n            cin >> a[i][0] >> a[i][1];\n            a[i][0] = n - a[i][0]; a[i][1] = m - a[i][1];\n        }\n        a[k + 1] = {n, m}; k++;\n        sort(a.begin() + 1, a.end());\n \n        auto paths = [&](ll i, ll j) {\n            ll dx = a[j][0] - a[i][0], dy = a[j][1] - a[i][1];\n            return bnm(dx + dy, dx);\n        };\n \n        auto add = [&](ll &x, ll y) {\n            x = (x + y) % mod;\n            x = (x + mod) % mod;\n        };\n \n        vector<ll> cnt_weighted(k + 1, 0);\n        cnt_weighted[k] = 1;\n        for (ll i = k - 1; i >= 1; i--) {\n            for (ll j = i + 1; j <= k; j++) {\n                add(cnt_weighted[i], paths(i, j) * cnt_weighted[j]);\n            }\n        }\n \n        ll ans = 0;\n        for (ll i = 1; i <= k; i++) {\n            ll delta = 2 * a[i][0] + a[i][1];\n            add(ans, delta * paths(0, i) % mod * cnt_weighted[i]);\n        }\n \n        ans = (ans * inv(bnm(n + m, m))) % mod;\n        cout << ans << nl;\n    }\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "sortings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2034",
    "index": "G1",
    "title": "Simurgh's Watch (Easy Version)",
    "statement": "\\textbf{The only difference between the two versions of the problem is whether overlaps are considered at all points or only at integer points.}\n\nThe legendary Simurgh, a mythical bird, is responsible for keeping watch over vast lands, and for this purpose, she has enlisted $n$ vigilant warriors. Each warrior is alert during a specific time segment $[l_i, r_i]$, where $l_i$ is the start time (included) and $r_i$ is the end time (included), both positive integers.\n\nOne of Simurgh's trusted advisors, Zal, is concerned that if multiple warriors are stationed at the same time and all wear the same color, the distinction between them might be lost, causing confusion in the watch. To prevent this, whenever multiple warriors are on guard at the same moment (\\textbf{which can be non-integer}), there must be at least one color which is worn by exactly one warrior.\n\nSo the task is to determine the minimum number of colors required and assign a color $c_i$ to each warrior's segment $[l_i, r_i]$ such that, for every (real) time $t$ contained in at least one segment, there exists one color which belongs to exactly one segment containing $t$.",
    "tutorial": "It is easy to check if the solution can be achieved with only one color. For any time point $x$, there must be at most one interval containing $x$, since if multiple intervals contain $x$, they must be colored differently. A simple strategy is to solve the problem using three colors. First, we color some intervals with colors 1 and 2, then color others with color 3. For each step, we find the leftmost point that has not been colored yet and color the segment that contains this point. We always choose the interval with the largest endpoint that contains the current point. By coloring the intervals alternately with colors 1 and 2, we ensure that all points are covered by exactly one of these colors. For each step, we find the leftmost point that has not been colored yet and color the segment that contains this point. We always choose the interval with the largest endpoint that contains the current point. By coloring the intervals alternately with colors 1 and 2, we ensure that all points are covered by exactly one of these colors. Now, we check if we can color the intervals with just two colors using a greedy algorithm: We iterate over the intervals sorted by start (increasingly) and then by end (decreasingly). At each point, we keep track of the number of colors used in previous intervals that are not yet closed. Let this number be $I$, and suppose we are currently at interval $i$. We color the current interval based on the value of $I$: If $I = 0$, color interval $i$ with color 1. If $I = 1$, color interval $i$ with the opposite color of the current used color. If $I = 2$, color interval $i$ with the opposite color of the interval with the greatest endpoint among the currently open intervals. If it is impossible to assign a unique color between overlapping intervals at any point, it can be shown that coloring the intervals using only 2 colors is impossible. We iterate over the intervals sorted by start (increasingly) and then by end (decreasingly). At each point, we keep track of the number of colors used in previous intervals that are not yet closed. Let this number be $I$, and suppose we are currently at interval $i$. We color the current interval based on the value of $I$: If $I = 0$, color interval $i$ with color 1. If $I = 1$, color interval $i$ with the opposite color of the current used color. If $I = 2$, color interval $i$ with the opposite color of the interval with the greatest endpoint among the currently open intervals. If $I = 0$, color interval $i$ with color 1. If $I = 1$, color interval $i$ with the opposite color of the current used color. If $I = 2$, color interval $i$ with the opposite color of the interval with the greatest endpoint among the currently open intervals. If it is impossible to assign a unique color between overlapping intervals at any point, it can be shown that coloring the intervals using only 2 colors is impossible. Solving G1 using G2: It's sufficient to check the integer points and half-points (e.g., 1.5, 2.5,  \\dots ) to verify whether the coloring is valid (Why?). To handle this, we can multiply all the given points by two, effectively converting the problem into one in which only integer points exist. After this transformation, we solve the problem in the integer system of G2, where the intervals and coloring rules are defined using integer boundaries!",
    "code": "/* In the name of Allah */\n// Welcome to the Soldier Side!\n// Where there's no one here, but me...\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 2e5 + 5;\nint t, n, l[N], r[N], col[N];\nvector<int> st[N << 1], en[N << 1];\n\nvoid compress_points() {\n    vector<int> help;\n    for (int i = 0; i < n; i++) {\n        help.push_back(l[i]);\n        help.push_back(r[i]);\n    }\n\n    sort(help.begin(), help.end());\n    help.resize(unique(help.begin(), help.end()) - help.begin());\n    for (int i = 0; i < n; i++) {\n        l[i] = lower_bound(help.begin(), help.end(), l[i]) - help.begin();\n        r[i] = lower_bound(help.begin(), help.end(), r[i]) - help.begin();\n    }\n}\n\nvoid record_points() {\n    for (int i = 0; i < n; i++) {\n        st[l[i]].push_back(i);\n        en[r[i] + 1].push_back(i);\n    }\n    for (int i = 0; i < 2 * n; i++)\n        sort(st[i].begin(), st[i].end(), [](int i, int j) {\n            return r[i] > r[j];\n        });\n}\n\nvoid try3_points() {\n    fill(col, col + n, 0);\n    int cur = -1, nxt = -1, c = 2;\n    for (int i = 0; i < 2 * n; i++) {\n        if (st[i].empty())\n            continue;\n\n        if (!~cur || i > r[cur]) {\n            if (cur ^ nxt && r[nxt] < i) {\n                col[nxt] = (c ^= 3);\n                cur = nxt;\n            }\n\n            if (cur ^ nxt)\n                cur = nxt;\n            else {\n                cur = st[i][0];\n                for (int p: st[i])\n                    if (r[p] > r[cur])\n                        cur = p;\n                nxt = cur;\n            }\n            col[cur] = (c ^= 3);\n        }\n        \n        for (int p: st[i])\n            if (r[p] > r[nxt])\n                nxt = p;\n    }\n    if (cur ^ nxt)\n        col[nxt] = c ^ 3;\n}\n\nbool is_bad(set<pair<int, int>> s[2]) {\n    int cnt1 = s[0].size(), cnt2 = s[1].size();\n    return cnt1 + cnt2 && cnt1 ^ 1 && cnt2 ^ 1;\n}\n\nvoid try2_points() {\n    set<pair<int, int>> s[2];\n    for (int i = 0; i <= 2 * n; i++) {\n        for (int p: en[i])\n            s[col[p]].erase({r[p], p});\n        if (is_bad(s)) {\n            try3_points();\n            return;\n        }\n\n        for (int p: st[i]) {\n            int cnt1 = s[0].size();\n            int cnt2 = s[1].size();\n            if (!cnt1 || !cnt2)\n                col[p] = cnt1 > 0;\n            else if (cnt1 ^ cnt2)\n                col[p] = cnt1 < cnt2;\n            else\n                col[p] = s[0].begin()->first > s[1].begin()->first;\n\n            s[col[p]].insert({r[p], p});\n            if (is_bad(s)) {\n                try3_points();\n                return;\n            }\n        }\n    }\n}\n\nvoid read_input() {\n    cin >> n;\n    for (int i = 0; i < n; i++)\n        cin >> l[i] >> r[i];\n}\n\nvoid solve() {\n    compress_points();\n    record_points();\n    try2_points();\n}\n\nvoid write_output() {\n    cout << *max_element(col, col + n) + 1 << endl;\n    for (int i = 0; i < n; i++)\n        cout << col[i] + 1 << \"\\n \"[i < n - 1];\n}\n\nvoid reset_variables() {\n    for (int i = 0; i < n; i++) {\n        col[i] = 0;\n        st[l[i]].clear();\n        en[r[i] + 1].clear();\n    }\n}\n\nint main() {\n    ios:: sync_with_stdio(0), cin.tie(0), cout.tie(0);\n    for (cin >> t; t--; reset_variables())\n        read_input(), solve(), write_output();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2034",
    "index": "G2",
    "title": "Simurgh's Watch (Hard Version)",
    "statement": "\\textbf{The only difference between the two versions of the problem is whether overlaps are considered at all points or only at integer points.}\n\nThe legendary Simurgh, a mythical bird, is responsible for keeping watch over vast lands, and for this purpose, she has enlisted $n$ vigilant warriors. Each warrior is alert during a specific time segment $[l_i, r_i]$, where $l_i$ is the start time (included) and $r_i$ is the end time (included), both positive integers.\n\nOne of Simurgh's trusted advisors, Zal, is concerned that if multiple warriors are stationed at the same time and all wear the same color, the distinction between them might be lost, causing confusion in the watch. To prevent this, whenever multiple warriors are on guard at the same \\textbf{integer} moment, there must be at least one color which is worn by exactly one warrior.\n\nSo the task is to determine the minimum number of colors required and assign a color $c_i$ to each warrior's segment $[l_i, r_i]$ such that, for every (integer) time $t$ contained in at least one segment, there exists one color which belongs to exactly one segment containing $t$.",
    "tutorial": "Step 1: It is easy to check if the solution can be achieved with only one color. For any time point $x$, there must be at most one interval containing $x$, since if multiple intervals contain $x$, they must be colored differently. Step 2: A simple strategy is to solve the problem using three colors; First, we color some intervals with colors 1 and 2, then color others with color 3. For each step, we find the leftmost point that has not been colored yet and color the segment that contains this point. We always choose the interval with the largest endpoint that contains the current point. By coloring the intervals alternately with colors 1 and 2, we ensure that all points are covered by exactly one of these colors. Step 3: Now, we check if we can color the intervals with just two colors. For some point, $x$, suppose we have already colored the intervals $[l_i, r_i]$ with $l_i \\leq x$, such that all points before $x$ have a unique color. At each step, we only need to determine which of the intervals like $p$ that $l_p \\leq x \\leq r_p$ can have a unique color. The key observation is that if an interval can be uniquely colored at time $x$, it can also remain uniquely colored for all times $t$ such that $x \\leq t \\leq r_i$. Lemma: If an interval $[l_i, r_i]$ can be uniquely colored at time $x$, it can also be uniquely colored at all subsequent times $x \\leq t \\leq r_i$. Proof: Consider coloring the intervals at time $x$. Intervals starting at $x + 1$ will be colored with the opposite color to interval $i$, ensuring that the interval remains uniquely colored at time $x+1$. With this lemma, we can conclude that the changes in the coloring are $O(n)$. It suffices to track the intervals that are added and removed at each point in time. Lemma: If an interval $[l_i, r_i]$ can be uniquely colored at time $x$, it can also be uniquely colored at all subsequent times $x \\leq t \\leq r_i$. Proof: Consider coloring the intervals at time $x$. Intervals starting at $x + 1$ will be colored with the opposite color to interval $i$, ensuring that the interval remains uniquely colored at time $x+1$. With this lemma, we can conclude that the changes in the coloring are $O(n)$. It suffices to track the intervals that are added and removed at each point in time. Step 4: To efficiently move from time $x$ to $x + 1$, we perform the following steps: Remove the intervals that have $r_i = x$ (since they no longer contain $x+1$). Add the intervals that have $l_i = x + 1$. Update the set of intervals that can be uniquely colored at time $x+1$. Remove the intervals that have $r_i = x$ (since they no longer contain $x+1$). Add the intervals that have $l_i = x + 1$. Update the set of intervals that can be uniquely colored at time $x+1$. Step 5: Finally, we observe that only the following points are important for the coloring: $l_i$ and $r_i$ for each interval. $l_i - 1$ and $r_i + 1$, since these points mark the boundaries where intervals start or end. Step 5: Finally, we observe that only the following points are important for the coloring: $l_i$ and $r_i$ for each interval. $l_i - 1$ and $r_i + 1$, since these points mark the boundaries where intervals start or end. Thus, we can compress the numbers to reduce the range of values we need to process.",
    "code": "/* In the name of Allah */\n// Welcome to the Soldier Side!\n// Where there's no one here, but me...\n#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 2e5 + 5;\nvector<int> st[N << 2], en[N << 2];\nint t, n, k, l[N], r[N], dp[N], col[N], prv[N];\n\nvoid compress_numbers() {\n    vector<int> help;\n    for (int i = 0; i < n; i++) {\n        help.push_back(l[i] - 1);\n        help.push_back(l[i]);\n        help.push_back(r[i]);\n        help.push_back(r[i] + 1);\n    }\n\n    sort(help.begin(), help.end());\n    help.resize(k = unique(help.begin(), help.end()) - help.begin());\n    for (int i = 0; i < n; i++) {\n        l[i] = lower_bound(help.begin(), help.end(), l[i]) - help.begin();\n        r[i] = lower_bound(help.begin(), help.end(), r[i]) - help.begin();\n    }\n}\n\nvoid save_checkpoints() {\n    for (int i = 0; i < n; i++) {\n        st[l[i]].push_back(i);\n        en[r[i]].push_back(i);\n    }\n}\n\nbool check_one() {\n    for (int i = 0, open = 0; i < k; i++) {\n        open += st[i].size();\n        if (open > 1)\n            return false;\n        open -= en[i].size();\n    }\n    return true;\n}\n\nvoid color_with_two() {\n    for (int i = k - 1, cur = -1; ~i; i--) {\n        if (en[i].empty())\n            continue;\n\n        while (!~cur || i < dp[cur])\n            if (~cur && ~prv[cur]) {\n                col[prv[cur]] = col[cur];\n                if (r[prv[cur]] >= l[cur])\n                    col[prv[cur]] ^= 1;\n                cur = prv[cur];\n            }\n            else\n                for (int p: en[i])\n                    if (~dp[p] && (!~cur || dp[p] < dp[cur]))\n                        cur = p;\n\n        for (int p: en[i])\n            if (p ^ cur)\n                col[p] = col[cur] ^ 1;\n    }\n}\n\nbool check_two() {\n    set<int> goods, bads;\n    fill(dp, dp + n, -1);\n    fill(prv, prv + n, -1);\n    for (int i = 0; i < k; i++) {\n        int prev = -1;\n        if (i)\n            for (int p: en[i - 1]) {\n                bads.erase(p), goods.erase(p);\n                if (~dp[p] && (!~prev || dp[p] < dp[prev]))\n                    prev = p;\n            }\n        int open = goods.size() + bads.size();\n\n        if (open == 1 || (open == 2 && !goods.empty())) {\n            for (int p: bads) {\n                if (open == 1)\n                    prv[p] = prev;\n                else\n                    prv[p] = *goods.begin();\n                goods.insert(p);\n                dp[p] = i;\n            }\n            bads.clear();\n        }\n\n        if (open == 1)\n            prev = *goods.begin();\n        for (int p: st[i])\n            if (!open || open == 1 || ~prev) {\n                goods.insert(p);\n                prv[p] = prev;\n                dp[p] = i;\n            }\n            else\n                bads.insert(p);\n        open += st[i].size();\n\n        if (open && goods.empty())\n            return false;\n    }\n\n    color_with_two();\n    return true;\n}\n\nvoid color_with_three() {\n    int cur = -1, nxt = -1;\n    for (int i = 0; i < k; i++) {\n        if (st[i].empty())\n            continue;\n\n        if (~cur && i > r[cur] && nxt ^ cur) {\n            col[nxt] = col[cur] ^ 3;\n            cur = nxt;\n        }\n        if (!~cur || i > r[cur]) {\n            for (int p: st[i])\n                if (!~cur || r[p] > r[cur])\n                    cur = p;\n            col[nxt = cur] = 1;\n        }\n\n        for (int p: st[i])\n            if (r[p] > r[nxt])\n                nxt = p;\n    }\n\n    if (cur ^ nxt)\n        col[nxt] = col[cur] ^ 3;\n}\n\nvoid read_input() {\n    cin >> n;\n    for (int i = 0; i < n; i++)\n        cin >> l[i] >> r[i];\n}\n\nvoid solve() {\n    compress_numbers();\n    save_checkpoints();\n    if (check_one())\n        return;\n    if (check_two())\n        return;\n    color_with_three();\n}\n\nvoid write_output() {\n    cout << *max_element(col, col + n) + 1 << endl;\n    for (int i = 0; i < n; i++)\n        cout << col[i] + 1 << \"\\n \"[i < n - 1];\n}\n\nvoid reset_variables() {\n    fill(col, col + n, 0);\n    for (int i = 0; i < k; i++) {\n        st[i].clear();\n        en[i].clear();\n    }\n}\n\nint main() {\n    ios:: sync_with_stdio(0), cin.tie(0), cout.tie(0);\n    for (cin >> t; t--; reset_variables())\n        read_input(), solve(), write_output();\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2034",
    "index": "H",
    "title": "Rayan vs. Rayaneh",
    "statement": "Rayan makes his final efforts to win Reyhaneh's heart by claiming he is stronger than Rayaneh (i.e., computer in Persian). To test this, Reyhaneh asks Khwarizmi for help. Khwarizmi explains that a set is integer linearly independent if no element in the set can be written as an integer linear combination of the others. Rayan is given a set of integers each time and must identify one of the largest possible integer linearly independent subsets.\n\nNote that a single element is always considered an integer linearly independent subset.\n\nAn integer linearly combination of $a_1, \\ldots, a_k$ is any sum of the form $c_1 \\cdot a_1 + c_2 \\cdot a_2 + \\ldots + c_k \\cdot a_k$ where $c_1, c_2, \\ldots, c_k$ are integers (which may be zero, positive, or negative).",
    "tutorial": "Step 1: According to Bézout's Identity, we can compute $\\gcd(x_1, \\ldots, x_t)$ and all its multipliers as an integer linear combination of $x_1, x_2, \\ldots, x_t$. Step 2: A set {$a_1, \\ldots, a_k$} is good (integer linearly independent) if for every $i$, $\\gcd(${$a_j \\mid j \\neq i$}$) \\nmid a_i$. Step 3: A set {$a_1, \\ldots, a_k$} is good if and only if there exists a set {${p_1}^{q_1}, {p_2}^{q_2}, \\ldots, {p_k}^{q_k}$} such that ${p_i}^{q_i} \\mid a_j$ for $j \\neq i$ and ${p_i}^{q_i} \\nmid a_i$. Step 4: The set {$a_1, \\ldots, a_k$} can be identified by determining {${p_1}^{q_1}, {p_2}^{q_2}, \\ldots, {p_k}^{q_k}$}. Assume $p_1^{q_1} < p_2^{q_2} < \\ldots < p_k^{q_k}$, where $p_i \\neq p_j$ and $p_i$ is prime. Step 5: Let $G = {p_1}^{q_1} \\cdot {p_2}^{q_2} \\ldots \\cdot {p_k}^{q_k}.$ Then {$a_1, \\ldots, a_k$} is good if and only if $\\frac{G}{{p_i}^{q_i}} \\mid a_i$ and $G \\nmid a_i$ for every $i$. Step 6: The answer is a singleton if, for every pair of numbers $x$ and $y$ in the array, $x \\mid y$ or $y \\mid x$. Since the numbers are distinct, a good subset {$a_1, a_2$} can always be found by searching the first $\\log M + 2$ elements. Step 7: Define $CM[i]$ (count multipliers of $i$) as the number of $x$ such that $i \\mid a_x$. This can be computed in $O(n + M \\log M)$. Step 8: A corresponding set {$a_1, \\ldots, a_k$} exists for a set {${p_1}^{q_1}, {p_2}^{q_2}, \\ldots, {p_k}^{q_k}$} if and only if $CM\\left[\\frac{G}{{p_i}^{q_i}}\\right] > CM[G] \\geq 0$ for all $i$. Step 9: Iterate over all valid sets of the form {${p_1}^{q_1}, {p_2}^{q_2}, \\ldots, {p_k}^{q_k}$}, and check if a corresponding {$a_1, a_2, \\ldots, a_k$} exists. Note that $k \\geq 3$ since a good subset {$a_1, a_2$} is found using another method. Step 10: We know $\\frac{G}{{p_1}^{q_1}} \\leq M$ and also ${p_1}^{q_1} \\leq \\sqrt{M},$ as ${p_1}^{q_1} \\leq \\sqrt{{p_2}^{q_2} \\cdot {p_3}^{q_3}} \\leq \\sqrt{\\frac{G}{{p_1}^{q_1}}} \\leq \\sqrt{M}.$ Step 11: There are $\\sum_{i=1}^{\\frac{\\log M}{2}} P[\\lfloor \\sqrt[2i]{M} \\rfloor]$ numbers in the form ${p_1}^{q_1}$, where $P[i]$ denotes the number of primes in the range $[1, i]$. This count is $O(\\frac{\\sqrt M}{\\log M})$. Step 12: The value of $k$ is at most 6 (denoted as $K$), as ${p_2}^{q_2} \\ldots {p_k}^{q_k} = \\frac{G}{{p_1}^{q_1}} \\leq M,$ and $3 \\cdot 5 \\cdot 7 \\cdot 11 \\cdot 13 \\leq M < 3 \\cdot 5 \\cdot 7 \\cdot 11 \\cdot 13 \\cdot 17.$ Step 13: We can determine {$a_1, \\ldots, a_k$} from {${p_1}^{q_1}, {p_2}^{q_2}, \\ldots, {p_k}^{q_k}$} in $O(n \\cdot K)$. The total time complexity is $O\\left(T \\cdot M \\cdot \\frac{\\sqrt M}{\\log M} \\cdot K + T \\cdot M \\cdot \\log M + \\sum_{i=0}^T n_i \\cdot K\\right).$",
    "code": "/// In the name of God the most beneficent the most merciful\n\n#pragma GCC optimize(\"Ofast,no-stack-protector,unroll-loops,fast-math,O3\")\n#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconstexpr int T = 100;\nconstexpr int M = 100001;\nconstexpr int SQM = 320;\nconstexpr int LGM = 20;\nvector<pair<int,int>> factor;\nint t, n[T], count_multipliers[T][M];\nbitset<M> is_composite;\nvector<int> ans[T], a[T];\n\ninline void calculate_importants() {\n    for(int i = 2; i < SQM; i++)\n        if(!is_composite[i]) {\n            for(int j = i; j < M; j *= i)\n                factor.push_back({j,i});\n            for(int j = i*i; j < M; j += i)\n                is_composite.set(j);\n        }\n    for(int i = SQM; i < M; i++)\n        if(!is_composite[i])\n            factor.push_back({i,i});\n    sort(factor.begin(), factor.end());\n}\n\nvoid check(vector<int> &factors, int G) {\n    if(factors.size() > 2u) {\n        for(int i = 0; i < t; i++) \n            if(ans[i].size() < factors.size()) {\n                int count_product = (G < M? count_multipliers[i][G] : 0);\n                bool can = true;\t\n                for(auto u: factors)\n                    if(count_multipliers[i][G/factor[u].first] == count_product) {\n                        can = false;\n                        break;\n                    }\n                if(can)\n                    ans[i] = factors;\n            }\n    }\n    int bound = (factors.size() == 1 ? SQM : M);\n    if(1LL*G/factor[factors[0]].first*factor[factors.back()].first > bound)\n        return;\n    for(int new_factor = factors.back(); G/factor[factors[0]].first*factor[new_factor].first <= bound; new_factor++) \n        if(G%factor[new_factor].second) {\n            factors.push_back(new_factor);\n            check(factors, G*factor[new_factor].first);\n            factors.pop_back();\n        }\n}\n\nint main() {\n    ios_base :: sync_with_stdio(false); cin.tie(nullptr);\n    calculate_importants();\n    cin >> t;\n    for(int i = 0; i < t; i++) {\n        cin >> n[i];\n        a[i].resize(n[i]);\n        for(int j = 0; j < n[i]; j++) {\n            cin >> a[i][j];\n            count_multipliers[i][a[i][j]]++;\n        }\n        ans[i] = {a[i][0]};\n        sort(a[i].begin(), a[i].begin()+min(n[i], LGM));\n        for(int c = 0; c+1 < n[i]; c++)\n            if(a[i][c+1]%a[i][c]) {\n                ans[i] = {a[i][c], a[i][c+1]};\n                break;\n            }\n        for(int c = 1; c < M; c++)\n            for(int j = c+c; j < M; j += c)\n                count_multipliers[i][c] += count_multipliers[i][j];\n    }\n    for(int i = 0; factor[i].first < SQM; i++) {\n        vector<int> starter = {i};\n        check(starter, factor[i].first);\n    }\n    for(int i = 0; i < t; i++) {\n        int k = ans[i].size();\n        cout << k << '\\n';\n        if(k == 1u) {\n            cout << ans[i][0] << '\\n';\n        } else if(k == 2u) {\n            cout << ans[i][0] << ' ' << ans[i][1] << '\\n';\n        } else {\n            int subset[k];\n            for(auto u: a[i]) {\n                int ls = -1;\n                for(int j = 0; j < (int)k; j++)\n                    if(u%factor[ans[i][j]].first)\n                        ls = (ls == -1? j: -2);\n                if(ls >= 0)\n                    subset[ls] = u;\n            }\n            for(int j = 0; j < k; j++)\n                cout << subset[j] << (j+1 == k? '\\n' : ' ');\n        }\n    }\n    return 0;\n}\n\n/// Thank God . . .",
    "tags": [
      "brute force",
      "dfs and similar",
      "dp",
      "number theory"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2035",
    "index": "A",
    "title": "Sliding",
    "statement": "\\begin{quote}\nRed was ejected. They were not the imposter.\n\\end{quote}\n\nThere are $n$ rows of $m$ people. Let the position in the $r$-th row and the $c$-th column be denoted by $(r, c)$. Number each person starting from $1$ in row-major order, i.e., the person numbered $(r-1)\\cdot m+c$ is initially at $(r,c)$.\n\nThe person at $(r, c)$ decides to leave. To fill the gap, let the person who left be numbered $i$. Each person numbered $j>i$ will move to the position where the person numbered $j-1$ is initially at. The following diagram illustrates the case where $n=2$, $m=3$, $r=1$, and $c=2$.\n\nCalculate the sum of the Manhattan distances of each person's movement. If a person was initially at $(r_0, c_0)$ and then moved to $(r_1, c_1)$, the Manhattan distance is $|r_0-r_1|+|c_0-c_1|$.",
    "tutorial": "The people with a smaller row major number won't move at all so we can ignore them. Now we can break everyone else into $2$ groups of people. The first group will be changing rows while the second group will stay in the same row. For the people changing rows their manhattan distance will change by a total of $m$ and there are $n - r$ of these people. For the second group of people, their manhattan distance will change by $1$ and there are $n \\cdot m - ((r - 1) \\cdot m + c) - (n - r)$ of these people. Thus, the final answer will be: $m \\cdot (n - r) + n \\cdot m - ((r - 1) \\cdot m + c) - (n - r)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing int64 = long long;\nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int t; cin >> t; while (t--) {\n        int64 n, m, r, c; cin >> n >> m >> r >> c;\n        cout << (n - r) * (m - 1) + n * m - (r - 1) * m - c << endl;\n    }\n}\n \n \n \n ",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2035",
    "index": "B",
    "title": "Everyone Loves Tres",
    "statement": "\\begin{quote}\nThere are 3 heroes and 3 villains, so 6 people in total.\n\\end{quote}\n\nGiven a positive integer $n$. Find the \\textbf{smallest} integer whose decimal representation has length $n$ and consists only of $3$s and $6$s such that it is divisible by both $33$ and $66$. If no such integer exists, print $-1$.",
    "tutorial": "If we had the lexicographically smallest number for some $n$, we could extend it to the lexicographically smallest number for $n+2$ by prepending $33$ to it. This is due to the lexicographic condition that values minimize some digits over all the digits behind them. In other words, $3666xx$ is always better than $6333xx$. We can observe that $66$ is the lexicographically smallest number for $n = 2$, $n = 1$ and $n = 3$ are impossible, and $36366$ is the lexicographically smallest number for $n = 5$. So our final answer is $n-2$ $3$'s followed by $66$ if $n$ is even, $-1$ if $n = 1$ or $n = 3$, or $n-5$ $3$'s followed by $36366$ if $n$ is odd and greater than or equal to $5$. For instance, for $n = 8$, the answer is $33333366$, and for $n = 9$, the answer is $333336366$.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nint main(){\n\tint T;\n\tcin >> T;\n\twhile(T--){\n\t\tint n;\n\t\tcin >> n;\n\t\tif(n == 1 || n == 3){\n\t\t\tcout << \"-1\\n\";\n\t\t}else if(n%2 == 0){\n\t\t\tfor(int i = 0; i<n-2; i++){\n\t\t\t\tcout << \"3\";\n\t\t\t}\n\t\t\tcout << \"66\\n\";\n\t\t}else{\n\t\t\tfor(int i = 0; i<n-5; i++){\n\t\t\t\tcout << \"3\";\n\t\t\t}\n\t\t\tcout << \"36366\\n\";\n\t\t}\n\t}\n}\n \n \n ",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 900
  },
  {
    "contest_id": "2035",
    "index": "C",
    "title": "Alya and Permutation",
    "statement": "Alya has been given a hard problem. Unfortunately, she is too busy running for student council. Please solve this problem for her.\n\nGiven an integer $n$, construct a permutation $p$ of integers $1, 2, \\ldots, n$ that maximizes the value of $k$ (which is initially $0$) after the following process.\n\nPerform $n$ operations, on the $i$-th operation ($i=1, 2, \\dots, n$),\n\n- If $i$ is odd, $k=k\\,\\&\\,p_i$, where $\\&$ denotes the bitwise AND operation.\n- If $i$ is even, $k=k\\,|\\,p_i$, where $|$ denotes the bitwise OR operation.",
    "tutorial": "We can make $k$ what it needs to be using at most the last $5$ numbers of the permutation. Every other element can be assigned randomly. We can split this up into several cases. Case 1: $n$ is odd. The last operation will be bitwise and. The bitwise and of $k$ with the last element which is less than or equal to $n$ is less than or equal to $n$. It is always possible to get the final $k$ value equal to $n$. Let $l$ be the lowest bit of $n$. We can set the last $4$ numbers to be: $l, l + (l == 1 ? 2 : 1), n - l, n$ After the first $2$, $k$ will at least have the bit $l$. After the third one, $k$ will be equal to $n$. The bitwise and of $k$ and the last element equal to $n$ will be $n$. Case 2: $n$ is even Now the last operation will be a bitwise or so we can do better than $n$ here. The maximum possible $k$ will be the bitwise or of every number from $1$ to $n$. Case 2a: $n$ is not a power of $2$. Let $h$ be the highest bit of $n$. We can set the last $3$ numbers to: $n, n - 1, h - 1$ After the first $2$, $k$ will have at least the highest bit of $n$. After bitwise or-ing this with the third element, it will have all bits. Case 2b: $n$ is a power of $2$. We can set the last $5$ numbers to $1, 3, n - 2, n - 1, n$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing vi = vector<int>;\n#define FOR(i, a, b) for (int i = (a); i < (b); i++)\n \nint main() {\n  ios::sync_with_stdio(0); cin.tie(0);\n  int t; cin >> t; while (t--) {\n    int n; cin >> n;\n    set<int> s; FOR(i, 1, n) s.insert(i);\n    vi a(n + 1);\n    int po2 = 1; while (po2 * 2 <= n) po2 *= 2;\n    if (n & 1) {\n      cout << n << endl;\n      int low = n & (-n);\n      a[n - 3] = low, a[n - 2] = low + (low == 1 ? 2 : 1), a[n - 1] = n - low, a[n] = n;\n    } else {\n      cout << po2 * 2 - 1 << endl;\n      if (n == po2) {\n        a[n - 4] = 1, a[n - 3] = 3, a[n - 2] = n - 2, a[n - 1] = n - 1, a[n] = n;\n      } else {\n        a[n - 2] = n, a[n - 1] = n - 1, a[n] = po2 - 1;\n      }\n    }\n    FOR(i, 1, n + 1) s.erase(a[i]);\n    FOR(i, 1, n + 1) if (!a[i]) a[i] = *s.begin(), s.erase(a[i]);\n    FOR(i, 1, n + 1) cout << a[i] << \" \"; cout << endl;\n  }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2035",
    "index": "D",
    "title": "Yet Another Real Number Problem",
    "statement": "\\begin{quote}\nThree r there are's in strawberry.\n\\end{quote}\n\nYou are given an array $b$ of length $m$. You can perform the following operation any number of times (possibly zero):\n\n- Choose two distinct indices $i$ and $j$ \\textbf{where} $\\bf{1\\le i < j\\le m}$ and $b_i$ is even, divide $b_i$ by $2$ and multiply $b_j$ by $2$.\n\nYour task is to maximize the sum of the array after performing any number of such operations. Since it could be large, output this sum modulo $10^9+7$.Since this problem is too easy, you are given an array $a$ of length $n$ and need to solve the problem for each prefix of $a$.\n\nIn other words, denoting the maximum sum of $b$ after performing any number of such operations as $f(b)$, you need to output $f([a_1])$, $f([a_1,a_2])$, $\\ldots$, $f([a_1,a_2,\\ldots,a_n])$ modulo $10^9+7$ respectively.",
    "tutorial": "Consider how to solve the problem for an entire array. We iterate backwards on the array, and for each $a_i$ we consider, we give all of its $2$ divisors to the largest $a_j > a_i$ with $j > i$. If $a_i$ is the largest, we do nothing. To do this for every prefix $x$, notice that if we after we have iterated backwards from $x$ over $31$ $2$ divisors, the largest $a_i$ will always be larger than $10^9$ and thus all remaining $2$'s will be given to that largest $a_i$. Thus, we can iterate over these $31$ $2$'s and assign them manually, then multiply the largest $a_i$ by the number of $2$'s we have remaining. Thus, if we maintain the previous $31$ even numbers for every prefix, we can solve the problem in $O(n \\log a_i)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#ifdef DEBUG\n#include \"debug.hpp\"\n#else\n#define debug(...) (void)0\n#endif\n \nusing i64 = int64_t;\nusing u64 = uint64_t;\nconstexpr bool test = false;\nconstexpr i64 mod = 1000000007;\nint main() {\n  cin.tie(nullptr)->sync_with_stdio(false);\n  int t;\n  cin >> t;\n  for (int ti = 0; ti < t; ti += 1) {\n    int n;\n    cin >> n;\n    vector<pair<i64, i64>> stack;\n    auto pow = [&](i64 a, i64 r) {\n      i64 res = 1;\n      for (; r; r >>= 1, a = a * a % mod)\n        if (r & 1) res = res * a % mod;\n      return res;\n    };\n    i64 sum = 0;\n    for (int i = 0, ai; i < n; i += 1) {\n      cin >> ai;\n      i64 r = countr_zero(u64(ai)), a = ai >> r;\n      while (not stack.empty()) {\n        if (r >= 30 or stack.back().first <= (a << r)) {\n          r += stack.back().second;\n          sum += stack.back().first;\n          stack.pop_back();\n        } else {\n          break;\n        }\n      }\n      if (r == 0) {\n        sum += a;\n      } else {\n        stack.emplace_back(a, r);\n      }\n      i64 res = sum;\n      for (auto [a, r] : stack) res += pow(2, r) * a % mod;\n      cout << res % mod << \" \";\n    }\n    cout << \"\\n\";\n  }\n}",
    "tags": [
      "binary search",
      "data structures",
      "divide and conquer",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2035",
    "index": "E",
    "title": "Monster",
    "statement": "\\begin{quote}\nMan, this Genshin boss is so hard. Good thing they have a top-up of $6$ coins for only $ \\$4.99$. I should be careful and spend no more than I need to, lest my mom catches me...\n\\end{quote}\n\nYou are fighting a monster with $z$ health using a weapon with $d$ damage. Initially, $d=0$. You can perform the following operations.\n\n- Increase $d$ — the damage of your weapon by $1$, costing $x$ coins.\n- Attack the monster, dealing $d$ damage and costing $y$ coins.\n\nYou cannot perform the first operation for more than $k$ times in a row.\n\nFind the minimum number of coins needed to defeat the monster by dealing at least $z$ damage.",
    "tutorial": "Let $\\text{damage}(a, b)$ represent the maximum number of damage by performing the first operation $a$ times and the second operation $b$ times. Since we should always increase damage if possible, the optimal strategy will be the following: increase damage by $k$, deal damage, increase damage by $k$, deal damage, and so on, until we run out of the first or second operation. Let's treat each group of increase by $k$ and one damage as one block. Specifically, we will have $c = \\min(\\lfloor \\frac{a}{k} \\rfloor, b)$ blocks. Afterwards, we will increase damage by $a\\bmod k$ times (making our weapon's damage $a$) and use our remaining $b - c$ attacks. Hence, $\\text{damage}(a, b) = k\\cdot \\frac{c\\cdot (c + 1)}{2} + a\\cdot (b - c)$ where $c = \\min(\\lfloor \\frac{a}{k} \\rfloor, b)$. The cost of this is $\\text{cost}(a, b) = a\\cdot x + b\\cdot y$. For a fixed $a$, since $\\text{damage}(a, b)$ is non-decreasing, we can binary search the smallest $b = \\text{opt_b}(a)$ where $\\text{damage}(a, b)\\geq z$. Similarly, for a fixed $b$, we can binary search the smallest $a = \\text{opt_a}(b)$ where $\\text{damage}(a, b)\\geq z$. Now, the issue is that we can't evaluate all $z$ possible values of $a$ or $b$. However, we can prove that for $(a, b)$ where all operations are useful (when we end with an attack), $\\text{damage}(a, b) > \\frac{a\\cdot b}{2}$: first, the lower bound of $\\text{damage}(a, b)$ must be when $k = 1$ (when we're limited the most). Since we end with an attack, $a\\leq b$ so $c = \\min(a, b) = a$. Now, $\\text{damage}(a, b) = \\frac{a\\cdot (a + 1)}{2} + a\\cdot(b - a) > \\frac{a^2}{2} + a\\cdot b - a^2 = a\\cdot b - \\frac{a^2}{2} > \\frac{a\\cdot b}{2}$. Since we want $\\text{damage}(a, b)\\geq z$, we have $\\text{damage}(a, b) > \\frac{a\\cdot b}{2}\\geq z$ which gives us $a\\cdot b\\geq z\\cdot 2$. This implies that $\\min(a, b)\\leq \\sqrt{2\\cdot z}$. Thus, it suffices to check all fixed $a$ where $a\\leq \\sqrt{2\\cdot z}$ and all fixed $b$ where $b\\leq \\sqrt{2\\cdot z}$. Alternatively, we can binary search the smallest $x$ where $x\\geq \\text{opt_b}(x)$ and check all $a\\leq x$ and $b\\leq \\text{opt_b}(x)$. Our final solution runs in $O(\\sqrt z\\log z)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing i64 = long long;\n \ni64 solve(int x, int y, int z, int k) {\n    auto cost = [&](int a, int b) {\n        return (i64) a * x + (i64) b * y;\n    };\n    auto damage = [&](int a, int b) {\n        int c = min(b, a / k);\n        return (i64) k * c * (c + 1) / 2 + (i64) (b - c) * a;\n    };\n    auto opt_a = [&](int b) {\n        int low = 1, hi = z + 1;\n        while (low < hi) {\n            int a = (low + hi) / 2;\n            damage(a, b) >= z ? hi = a : low = a + 1;\n        }\n        return low;\n    };\n    auto opt_b = [&](int a) {\n        int low = 1, hi = z + 1;\n        while (low < hi) {\n            int b = (low + hi) / 2;\n            damage(a, b) >= z ? hi = b : low = b + 1;\n        }\n        return low;\n    };\n    int low = 0, hi = z;\n    while (low < hi) {\n        int a = (low + hi) / 2;\n        a >= opt_b(a) ? hi = a : low = a + 1;\n    }\n    i64 ans = LLONG_MAX;\n    assert(low > 0 && low <= z);\n    for (int a = 1; a <= low; a++) {\n        int b = opt_b(a);\n        if (b <= z) {\n            ans = min(ans, cost(a, b));\n        }\n    }\n    for (int b = 1; b <= low; b++) {\n        int a = opt_a(b);\n        if (a <= z) {\n            ans = min(ans, cost(a, b));\n        }\n    }\n    return ans;\n}\n \nint main() {\n    int T;\n    cin >> T;\n    while (T--) {\n        int x, y, z, k;\n        cin >> x >> y >> z >> k;\n        cout << solve(x, y, z, k) << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math",
      "ternary search"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2035",
    "index": "F",
    "title": "Tree Operations",
    "statement": "\\begin{quote}\nThis really says a lot about our society.\n\\end{quote}\n\nOne day, a turtle gives you a tree with $n$ nodes rooted at node $x$. Each node has an initial nonnegative value; the $i$-th node has starting value $a_i$.\n\nYou want to make the values of all nodes equal to $0$. To do so, you will perform a series of operations on the tree, where each operation will be performed on a certain node. Define an operation on node $u$ as choosing a single node in $u$'s subtree$^{\\text{∗}}$ and incrementing or decrementing its value by $1$. The order in which operations are performed on nodes is as follows:\n\n- For $1 \\le i \\le n$, the $i$-th operation will be performed on node $i$.\n- For $i > n$, the $i$-th operation will be performed on the same node as operation $i - n$.\n\nMore formally, the $i$-th operation will be performed on the $(((i - 1) \\bmod n) + 1)$-th node.$^{\\text{†}}$\n\nNote that you cannot skip over operations; that is, you cannot perform the $i$-th operation without first performing operations $1, 2, \\ldots, i - 1$.\n\nFind the minimum number of operations you must perform before you can make the values of all nodes equal to $0$, assuming you pick operations optimally. If it's impossible to make the values of all nodes equal to $0$ after finite operations, output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The subtree of a node $u$ is the set of nodes for which $u$ lies on the shortest path from this node to the root, including $u$ itself.\n\n$^{\\text{†}}$Here, $a \\bmod b$ denotes the remainder from dividing $a$ by $b$.\n\\end{footnotesize}",
    "tutorial": "The key observation to make is that if we can make all nodes equal to $0$ using $t$ operations, we can make all nodes equal to $0$ in $t + 2n$ operations by increasing all nodes by $1$ before decreasing all nodes by $1$. As such, this motivates a binary search solution. For each $i$ from $0$ to $2n - 1$, binary search on the set of integers {$x \\in \\mathbb{Z} \\mid x \\bmod 2n \\equiv i$} for the first time we can make all nodes $0$. Our answer is then the minimum value over all these binary searches. For a constant factor speedup, note that we only need to check the values of $i$ such that the parity of $i$ is equal to the parity of $\\sum{a_i}$. All that remains is to find a suitably fast check function for determining whether or not we can solve the tree using a fixed number of operations. This can be done with dynamic programming in $O(n)$ time. Suppose we fix the number of operations as $x$. We can then calculate for each node in $O(1)$ time how many operations on its respective subtree it can perform. For a node $i$, this is $\\lfloor \\frac{x}{n} \\rfloor + [((x \\bmod n) + 1) < i]$. Define this value as $\\text{has_i}$. Define $\\text{dp}[i]$ as the number of operations needed to make the entire subtree of $i$ equal to $0$. $\\text{dp}[i]$ is then $(\\sum_{j\\in\\text{child($i$)}}\\text{dp}[j]) + a_i - \\text{has_i}$. If $\\text{dp}[i] < 0$ at the end, $\\text{dp}[i] = -\\text{dp}[i] \\bmod 2$, since we may need to waste an operation. Finally, the tree is solvable for a fixed $x$ if $\\text{dp}[\\text{root}] = 0$. This solution can actually be improved to $O(n\\log(a_i) + n^2\\log(n))$. We will do so by improving our bounds for each binary search we perform. This improved solution also serves as a proof for why it is always possible to make all nodes equal to $0$ after finite operations. Consider solving the easier subtask where the goal is to make all values of the tree $\\le 0$. The minimum number of operations can be binary searched for directly, and the only change to the check function is changing the value of $\\text{dp}[i]$ for when $\\text{dp}[i]$ $\\le 0$ to simply be $0$ instead. As such, this subtask can be solved in $O(n\\log(a_i))$, and is clearly a lower bound on the answer. Let's denote this number of operations as $t$. Claim: The tree is solvable within $t + n^2 + 2n + 1$ operations. Proof: After using $t$ operations, we can reduce all the values in the tree into either $1$ or $0$ based on the parity of extra operations used. We want to turn all the nodes into the same number. Consider running through $n$ operations with each node applying the operation to itself. Note that the parity of all nodes flip. We will fix the parity of $1$ node per $n$ operations (that is, while all other nodes change parity, one node's parity will stay the same). We can accomplish this by having the root node change the parity of the node who's parity we want to maintain, while all other nodes apply the operation to itself. Now, after $n^2$ operations, all nodes (except for possibly the root) will have the same parity. We can fix the parity of the root in at worst $n + 1$ extra operations. Have all nodes toggle their own parity, but have the root toggle the parity of the node that comes directly after it. Now, that node can just fix itself, and all nodes have the same parity. If all the nodes are equal to $1$, we simply use $n$ operations to toggle the parity and make all the nodes equal to $0$. With this bound of $t + n^2 + 2n + 1$, we can simply adjust the upper and lower bounds of our binary search for the $O(n^2\\log(a_i))$ solution, resulting in a $O(n\\log(a_i) + n^2\\log(n))$ solution.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#ifdef DEBUG\n#include \"debug.hpp\"\n#else\n#define debug(...) (void)0\n#endif\nusing i64 = int64_t;\nint main() {\n  cin.tie(nullptr)->sync_with_stdio(false);\n  int t;\n  cin >> t;\n  for (int ti = 0; ti < t; ti += 1) {\n    int n, x;\n    cin >> n >> x;\n    vector<int> a(n + 1);\n    for (int i = 1; i <= n; i += 1) cin >> a[i];\n    vector<vector<int>> adj(n + 1);\n    for (int i = 1, u, v; i < n; i += 1) {\n      cin >> u >> v;\n      adj[u].push_back(v);\n      adj[v].push_back(u);\n    }\n    vector<int> p(n + 1), o;\n    auto rec = [&](auto& rec, int u) -> void {\n      for (int v : adj[u])\n        if (v != p[u]) {\n          p[v] = u;\n          rec(rec, v);\n        }\n      o.push_back(u);\n    };\n    rec(rec, x);\n \n    vector<int> can_use(n);\n    auto dfs = [&](auto&& self, int cur, int par) -> long long {\n    long long need = a[cur];\n    for (auto to : adj[cur]) {\n      if (to == par) continue;\n      need += self(self, to, cur);\n    }\n    if (need >= can_use[cur - 1]) {\n      return need - can_use[cur - 1];\n    } else {\n      return 0;\n    }\n  };\n \n  auto check = [&](long long operations) -> bool {\n    for (int i = 0; i < n; i++) {\n      can_use[i] = operations / n + (i < operations % n);\n    }\n \n    return dfs(dfs, x, x) == 0;\n  };\n \n  long long lower, higher;\n  {\n    long long l = 0, r = *max_element(a.begin(), a.end()) * (long long)n;\n    while (l < r) {\n      long long m = l + (r - l) / 2;\n      check(m) ? r = m : l = m + 1;\n    }\n \n    lower = l, higher = l + n * n;\n  }\n \n  long long ans = higher;\n \n    for (int i = 0; i < 2 * n; i += 1) {\n      vector<i64> b(n + 1);\n      i64 pans = *ranges::partition_point(views::iota((lower - i) / (2 * n), (ans - i) / (2 * n) + 1), [&](i64 x) {\n        for (int u : o) {\n          i64 y = x * 2 + (u - 1 < i) + (u - 1 + n < i);\n          b[u] = a[u];\n          for (int v : adj[u])\n            if (p[u] != v) b[u] += b[v];\n          if (y < b[u]) {\n            b[u] = b[u] - y;\n          } else {\n            b[u] = (y - b[u]) % 2;\n          }\n        }\n        return b[o.back()];\n      });\n      debug(i, pans);\n      ans = min(ans, pans * (2 * n) + i);\n    }\n    cout << ans << \"\\n\";\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2035",
    "index": "G1",
    "title": "Go Learn! (Easy Version)",
    "statement": "\\textbf{The differences between the easy and hard versions are the constraints on $n$ and the sum of $n$. In this version, $n \\leq 3000$ and the sum of $n$ does not exceed $10^4$. You can only make hacks if both versions are solved.}\n\nWell, well, well, let's see how Bessie is managing her finances. She seems to be in the trenches! Fortunately, she is applying for a job at Moogle to resolve this issue. Moogle interviews require intensive knowledge of obscure algorithms and complex data structures, but Bessie received a tip-off from an LGM on exactly what she has to go learn.\n\nBessie wrote the following code to binary search for a certain element $k$ in a possibly unsorted array $[a_1, a_2,\\ldots,a_n]$ with $n$ elements.\n\n\\begin{verbatim}\nlet l = 1\nlet h = n\n\nwhile l < h:\nlet m = floor((l + h) / 2)\n\nif a[m] < k:\nl = m + 1\nelse:\nh = m\n\nreturn l\n\n\\end{verbatim}\n\nBessie submitted her code to Farmer John's problem with $m$ ($1 \\leq m \\leq n$) tests. The $i$-th test is of the form $(x_i, k_i)$ ($1 \\leq x, k \\leq n$). It is guaranteed all the $x_i$ are distinct and all the $k_i$ are distinct.\n\nTest $i$ is correct if the following hold:\n\n- The $x_i$-th element in the array is $k_i$.\n- If Bessie calls the binary search as shown in the above code for $k_i$, it will return $x_i$.\n\nIt might not be possible for all $m$ tests to be correct on the same array, so Farmer John will remove some of them so Bessie can AC. Let $r$ be the minimum of tests removed so that there exists an array $[a_1, a_2,\\ldots,a_n]$ with $1 \\leq a_i \\leq n$ so that all remaining tests are correct.\n\nIn addition to finding $r$, Farmer John wants you to count the number of arrays $[a_1, a_2,\\ldots,a_n]$ with $1 \\leq a_i \\leq n$ such that there exists a way to remove exactly $r$ tests so that all the remaining tests are correct. Since this number may be very large, please find it modulo $998\\,244\\,353$.",
    "tutorial": "Let's sort the tests by $x_i$. I claim a subsequence of tests $t_1 \\dots t_r$ remaining is correct iff $k_{t_i} < k_{t_{i+1}}$ for all $1 \\leq i < r$. $x_{t_1} = 1$ or $k_{t_1} \\neq 1$. In other words, the set of tests is increasing, and if some test has $k_i = 1$, that test's $x_i$ must $= 1$. This is because a binary search for value $1$ will always be index $1$. Otherwise, the array $a$ where $a_i = k_{t_j}$ if $i = t_j$ for some $j$, $a_i = 1$ if $i < x_{t_1}$ or $a_i = a_{i-1}$ is a valid array for all of these tests. This is because the binary search will perform normally and correctly lower bound all of those occurrences. Suppose then the tests were not increasing. Consider two indices $i$ and $j$ such that $x_i < x_j$ but $k_i > k_j$. Consider the $l$, $r$, and $m$ in the binary search where $l \\leq x_i \\leq m$ and $m+1 \\leq x_j \\leq r$. For test $i$ to search left, $a_m$ must be $\\geq k_i$, but $j$ also had to search right so $a_m$ must be $< k_j$. Then we need $k_i \\leq a_m < k_j$, but we assumed that $k_i > k_j$, hence a contradiction. $\\Box$ Suppose $r$ was the minimum number of tests removed. I claim for each valid $a_1 \\dots a_n$, there is exactly one set of $r$ tests to remove to make $a_1 \\dots a_n$ valid. This is because if there were more than one way, these two choices of the $m-r$ tests to keep would be different. Then $a$ would actually satisfy at least $m-r+1$ remaining tests, so $r$ is not minimal. Putting these two statements together, we can formulate an $O(m^2 \\log n)$ dp. Let $\\text{touch}(i)$ denote the set of indices $m$ such that a binary search that terminates at position $i$ checks all these $a_m$ at some point. Also, let $k_i$ be the $k$ of the test with $x = i$. If no such test exists $k_i$ is undefined. Let $\\text{dp}_i$ be a tuple of $(x, y)$ where $x$ is the longest increasing set of tests where the last test has $x_j = i$ and $y$ is the number of ways to fill the prefix of $a_1 \\dots a_{i}$ to satisfy some choice of $x$ tests removed. Note that $\\text{dp}_i$ is not defined when there does not exist some $x_j = i$. Also if, $i \\neq 1$, and $k_i = 1$, $\\text{dp}_i = (0, 0)$. Consider computing some $\\text{dp}_i$. Let $mx = \\max\\limits_{j < i, k_j < k_i} \\text{dp}_j.x$. $\\text{dp}_i = (mx+1, \\sum\\limits_{j < i, k_j < k_i, \\text{dp}_j.x = mx} cnt(j, i)\\cdot \\text{dp}_j.y)$ where $\\text{cnt}(j, i)$ is the number of ways to fill the $a_i \\dots a_j$ if both the test with $x = i$ and the test with $x = j$ are taken. Most of the elements between $i$ and $j$ will be free, so we can assign them to any number from $1 \\dots n$. Let's determine which (and how many) numbers are not free. Consider all elements $m$ such that $m\\in\\text{touch}(i)$, $m\\in\\text{touch}(j)$, and $i < m < j$. Let there be $b$ of such $m$, these elements are forced to take on values $k_j \\leq v < k_i$. Then consider all elements $m$ such that $m \\in \\text{touch}(i)$, $m \\notin \\text{touch}(j)$, and $i < m < j$. Let there be $g$ such $m$, these elements are forced to take on values $k_j \\leq v$. Finally, consider all $m$ such that $m \\in \\text{touch}(j)$, $m \\notin \\text{touch}(i)$, and $i < m < j$. Let there be $l$ such $m$, these elements are forced to take on values $v < k_i$. Then $\\text{cnt}(i, j) = n^{i - j - 1 - (g + m + l)} (k_i - k_j)^b (n - k_j + 1)^g (k_i - 1)^l$. After we have found all the $\\text{dp}$'s, we can try each $\\text{dp}$ as the last test taken in the entire set. We can determine all the elements in the suffix that have their value forced (relative to $i$). We can precompute $\\text{touch}(i)$ or compute it on the fly in $O(\\log n)$ time per $i$. We can also choose to use binpow/precompute powers. As we have $m$ states with up to $m$ transitions each each taking $O(\\log n)$ time, our final complexity is $O(m^2 \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std; \n \n#define ll long long\n#define pii pair<int, int>\n#define f first\n#define s second\n \nconst int mx = 3005, md = 998244353;\n \nint n, m, t, A[mx]; pii ans; vector<int> touch[mx]; vector<pii> tests; pii dp[mx];\n \npii comb(pii a, pii b){\n    return a.f == b.f ? make_pair(a.f, (a.s + b.s) % md) : max(a, b); \n}\nll bpow(ll a, int p){\n    ll ans = 1;\n    for (;p; p /= 2, a = (a * a) % md) \n        if (p & 1) \n            ans = (ans * a) % md;\n    return ans;\n}\nvector<int> findTouch(int idx){\n    int l = 1, h = n;\n    vector<int> ret;\n \n    while (l < h){\n        int m = (l + h) / 2;\n        ret.push_back(m);\n \n        if (m < idx)\n            l = m + 1;\n        else \n            h = m;\n    }\n    return ret;\n}\n \nint main(){\n    ios_base::sync_with_stdio(0); cin.tie(0); \n    int T; cin >> T;\n    while(T--){\n    cin >> n >> m;\n    for(int i = 1; i<=n; i++){\n        A[i] = 0;\n        touch[i].clear();\n        dp[i] = {0, 0};\n    }\n    tests.clear();\n    for (int i = 1; i <= m; i++){\n        int idx, k;\n        cin >> idx >> k;\n        A[idx] = k;\n    }\n \n    ans = {0, bpow(n, n)};\n    \n    for (int i = 1; i <= n; i++){\n        if (!A[i]) \n            continue;\n        \n        touch[i] = findTouch(i);\n \n        int le = 0, ge = 0;\n        int mark[n + 1] = {};\n \n        for (int pos : touch[i]){\n            mark[pos] = true;\n            le += pos < i;\n            ge += pos > i;\n        }\n        dp[i] = make_pair(1, bpow(A[i] - 1, le) * bpow(n, i - 1 - le) % md);\n \n        // Corner case -- not possible to have A[i] = 1\n        if (i > 1 and A[i] == 1)\n            dp[i] = {0, 0};\n \n        for (int j = 1; j < i; j++){\n            if (!A[j] or A[j] > A[i])\n                continue;\n \n            int geqj = 0;\n            int lei = 0;\n            int both = 0;\n            int none = i - j - 1;\n \n            for (int pos : touch[i]){\n                if (pos > j and pos < i){\n                    lei++;\n                    none--;\n                }\n            }\n            for (int pos : touch[j]){\n                if (pos > j and pos < i){\n                    if (mark[pos]){\n                        both++;\n                        lei--;\n                    }\n                    else{\n                        geqj++;\n                        none--;\n                    }\n                }\n            }\n            int ways = dp[j].s * bpow(n, none) % md * bpow(n - A[j] + 1, geqj) % md * bpow(A[i] - 1, lei) % md * bpow(A[i] - A[j], both) % md;\n                \n            dp[i] = comb(dp[i], make_pair(dp[j].f + 1, ways));\n        }\n        ans = comb(ans, make_pair(dp[i].f, dp[i].s * bpow(n - A[i] + 1, ge) % md * bpow(n, n - i - ge) % md));\n    }\n    \n \n    cout<<m - ans.f<<\" \"<<ans.s<<\"\\n\";\n    }\n}",
    "tags": [
      "dp",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2035",
    "index": "G2",
    "title": "Go Learn! (Hard Version)",
    "statement": "\\textbf{The differences between the easy and hard versions are the constraints on $n$ and the sum of $n$. In this version, $n \\leq 3\\cdot 10^5$ and the sum of $n$ does not exceed $10^6$. You can only make hacks if both versions are solved.}\n\nWell, well, well, let's see how Bessie is managing her finances. She seems to be in the trenches! Fortunately, she is applying for a job at Moogle to resolve this issue. Moogle interviews require intensive knowledge of obscure algorithms and complex data structures, but Bessie received a tip-off from an LGM on exactly what she has to go learn.\n\nBessie wrote the following code to binary search for a certain element $k$ in a possibly unsorted array $[a_1, a_2,\\ldots,a_n]$ with $n$ elements.\n\n\\begin{verbatim}\nlet l = 1\nlet h = n\n\nwhile l < h:\nlet m = floor((l + h) / 2)\n\nif a[m] < k:\nl = m + 1\nelse:\nh = m\n\nreturn l\n\n\\end{verbatim}\n\nBessie submitted her code to Farmer John's problem with $m$ ($1 \\leq m \\leq n$) tests. The $i$-th test is of the form $(x_i, k_i)$ ($1 \\leq x, k \\leq n$). It is guaranteed all the $x_i$ are distinct and all the $k_i$ are distinct.\n\nTest $i$ is correct if the following hold:\n\n- The $x_i$-th element in the array is $k_i$.\n- If Bessie calls the binary search as shown in the above code for $k_i$, it will return $x_i$.\n\nIt might not be possible for all $m$ tests to be correct on the same array, so Farmer John will remove some of them so Bessie can AC. Let $r$ be the minimum of tests removed so that there exists an array $[a_1, a_2,\\ldots,a_n]$ with $1 \\leq a_i \\leq n$ so that all remaining tests are correct.\n\nIn addition to finding $r$, Farmer John wants you to count the number of arrays $[a_1, a_2,\\ldots,a_n]$ with $1 \\leq a_i \\leq n$ such that there exists a way to remove exactly $r$ tests so that all the remaining tests are correct. Since this number may be very large, please find it modulo $998\\,244\\,353$.",
    "tutorial": "Read the editorial for G1; we will build off of that. The most important observation is that $b$ is defined above as at most $1$. If you consider binary searching for $j$ and $i$, at the index $m$ which is present both in $\\text{touch}(j)$ and $\\text{touch}(i)$ and between $j$ and $i$, the search must go left for $j$ and go right for $i$. Then none of the points after $m$ can occur in both $\\text{touch}(i)$ and $\\text{touch}(j)$. The only time when such $m$ doesn't exist is when the $m = i$ or $m = j$. We can call such $m$ as the LCA of $i$ and $j$. We can also observe that the indices in $\\text{touch}(i)$ but not in $\\text{touch}(j)$ are between $m$ and $i$. Similarly, the indices in $\\text{touch}(j)$ but not in $\\text{touch}(i)$ are between $j$ and $m$. We can associate all the transitions from $j$ to $i$ with the same LCA together and transition simultaneously. We can break our dp into parts only dependent on $i$ and $j$, and only the $(a_i - a_j)^b$ depends on both. We can account for this by storing $dp_j \\cdot (n - k_j + 1)^g$ and $k_j\\cdot dp_j (n - k_j + 1)^g$. A little extra casework is needed when $j$ or $i$ is also the LCA. Then for each $i$, we can iterate all the possible LCA's and do all the candidate $j$ transitions at once. To ensure our dp only makes valid transitions, we can insert $i$ in increasing order of $k_i$. For each $i$, there are $\\log n$ transitions, making the complexity $O(m \\log n)$. Depending on the precomputation used and constant factors, $O(m \\log^2 n)$ might pass as well.",
    "code": "//maomao and hanekawa will carry me to red\n \n//#pragma GCC target(\"avx2,bmi,bmi2,lzcnt,popcnt\")\n \n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <utility>\n#include <cassert>\n#include <algorithm>\n#include <vector>\n#include <array>\n#include <cstring>\n#include <functional>\n#include <numeric>\n#include <set>\n#include <queue>\n#include <map>\n#include <chrono>\n#include <random>\n \n#define sz(x) ((int)(x.size()))\n#define all(x) x.begin(), x.end()\n#define pb push_back\n#define eb emplace_back\n#define kill(x, s) {if(x){ cout << s << \"\\n\"; return ; }}\n \n#ifndef LOCAL\n#define cerr while(0) cerr\n#endif\n \nusing ll = long long;\nusing lb = long double;\n \nconst lb eps = 1e-9;\n//const ll mod = 1e9 + 7, ll_max = 1e18;\nconst ll mod = (1 << (23)) * 119 +1, ll_max = 1e18;\nconst int MX = 3e5 +10, int_max = 0x3f3f3f3f;\n \nstruct {\n\ttemplate<class T>\n\t\toperator T() {\n\t\t\tT x; std::cin >> x; return x;\n\t\t}\n} in;\n \nusing namespace std;\n \n//ritwin/jeroen orz\ntemplate <int M>\nstruct Modint {\n\tint v;\n\tModint() : v(0) {}\n\ttemplate <typename T> Modint(T x) : v(x%M) { if (v < 0) v += M; }\n\tModint  operator+ () { return *this; }\n\tModint  operator- () { return Modint() - *this; }\n\tModint& operator++() { if (++v == M) v = 0; return *this; }\n\tModint& operator--() { if (--v < 0) v = M-1; return *this; }\n\tModint& operator++(int) { Modint r = *this; ++*this; return r; }\n\tModint& operator--(int) { Modint r = *this; --*this; return r; }\n\tModint& operator+=(const Modint &r) { if ((v += r.v) >= M) v -= M; return *this; }\n\tModint& operator-=(const Modint &r) { if ((v -= r.v) <  0) v += M; return *this; }\n\tModint& operator*=(const Modint &r) { v = (ll) v * r.v % M; return *this; }\n\tfriend Modint operator+(const Modint &a, const Modint &b) { return Modint(a) += b; }\n\tfriend Modint operator-(const Modint &a, const Modint &b) { return Modint(a) -= b; }\n\tfriend Modint operator*(const Modint &a, const Modint &b) { return Modint(a) *= b; }\n\tfriend bool  operator==(const Modint &a, const Modint &b) { return a.v == b.v; }\n\tfriend bool  operator!=(const Modint &a, const Modint &b) { return a.v != b.v; }\n};\n \nusing mint = Modint<mod>;\n \n \n \n#define info pair<int, mint>\nint n, m;\nint arr[MX];\n \ninfo dp[MX];\ninfo prec[2][MX];\n \nmint pown[MX];\n \n \ninfo comb(info a, info b){\n\tint c = max(a.first, b.first);\n\treturn pair(c, (a.first == c)*a.second + (b.first == c)*b.second);\n}\n \nmint binpow(ll base, ll b = mod-2){\n\tmint ans = 1;\n\tmint a = base;\n\tfor(int i = 1; i<=b; i++){\n\t\tif(i&b) ans *= a;\n\t\ta *= a;\n\t}\n\treturn ans;\n}\n \nvector<pair<int, int>> touch(int i){\n\tvector<pair<int, int>> ret;\n\tint l = 1, h = n;\n\twhile(l < h){\n\t\tint mid = (l + h)/2;\n\t\tret.pb({mid, i>=mid+1});\n\t\tif(i <= mid) h = mid;\n\t\telse l = mid+1;\n\t}\n\treverse(all(ret));\n\treturn ret;\n}\n \n \nvoid update(int j){\n\tauto p = touch(j);\n\tint right = 0;\n\tmint pj = 1;\n\tfor(auto [lca, dir] : p){\n\t\tif(lca < j) continue;\n \n\t\tif(dir == 0){\n\t\t\t//there are \"right\" things that are >= j\n\t\t\t//there are lca-j-1-right things that free\n\t\t\tmint ways = dp[j].second*pown[lca-j-right-(j != lca)]*pj;\n\t\t\tcerr << lca << \" \" << ways.v << \"\\n\";\n\t\t\tif(j != lca){\n\t\t\t\tprec[0][lca] = comb(prec[0][lca], pair(dp[j].first, ways));\n\t\t\t\tprec[1][lca] = comb(prec[1][lca], pair(dp[j].first, ways*arr[j]));\n\t\t\t}else{\n\t\t\t\tprec[0][lca] = comb(prec[0][lca], pair(dp[j].first, 0));\n\t\t\t\tprec[1][lca] = comb(prec[1][lca], pair(dp[j].first, -ways));\n\t\t\t}\n\t\t}\n\t\tif(j < lca){\n\t\t\tright++;\n\t\t\tpj *= n-arr[j]+1;\n\t\t}\n\t}\n \n}\n \ninfo query(int i, info best){\n\t//obtain dp[i]\n\tauto p = touch(i);\n\tint left = 0;\n\tmint pi = 1;\n\tfor(auto [lca, dir] : p){\n\t\tif(i < lca) continue;\n\t\tif(dir == 1){\n\t\t\tmint ways = prec[0][lca].second*(arr[i]) - prec[1][lca].second;\n\t\t\tways *= pown[i-lca-left-(i != lca)]*pi;\n\t\t\tbest = comb(best, make_pair(prec[0][lca].first+1, ways));\n\t\t}\n\t\tif(lca < i){\n\t\t\tleft++;\n\t\t\tpi *= arr[i]-1;\n\t\t}\n\t}\n\treturn best;\n}\n \nvoid solve(){\n\tn = in, m = in;\n\tpown[0] = 1;\n\tfor(int i = 1; i<=n; i++){\n\t\tarr[i] = 0;\n\t\tdp[i] = pair(0, mint(0));\n\t\tprec[0][i] = prec[1][i] = pair(0, mint(0));\n\t\tpown[i] = pown[i-1]*n;\n\t}\n\tvector<pair<int, int>> events;\n\tfor(int i = 1; i<=m; i++){\n\t\tint x = in;\n\t\tarr[x] = in;\n\t\tevents.pb({arr[x], x});\n\t}\n\tsort(all(events));\n\tinfo ans = pair(0, pown[n]);\n\tfor(auto [x, i] : events){\n\t\tauto p = touch(i);\n\t\tint left = 0;\n\t\tmint pi = 1;\n\t\tfor(auto [lca, dir] : p){\n\t\t\tif(lca < i){ \n\t\t\t\tleft++;\n\t\t\t\tpi *= arr[i]-1;\n\t\t\t}\n\t\t}\n\t\tinfo best = pair(1, pown[i-left-1]*pi);\n\t\tif(x == 1 && i > 1) continue;\n\t\tbest = query(i, best);\n\t\tint right = 0;\n\t\tmint pj = 1;\n\t\tfor(auto [lca, dir] : p){\n\t\t\tif(i < lca){\n\t\t\t\tright++;\n\t\t\t\tpj *= (n - arr[i]+1);\n\t\t\t}\n\t\t}\n \n\t\tans = comb(ans, pair(best.first, best.second*pown[n-i-right]*pj));\n\t\tdp[i] = best;\n\t\tupdate(i);\n\t}\n\tcout << m - ans.first << \" \" << ans.second.v << \"\\n\";\n \n}\n \nsigned main(){\n\tcin.tie(0) -> sync_with_stdio(0);\n \n\tint T = 1;\n\tcin >> T;\n\tfor(int i = 1; i<=T; i++){\n\t\t//cout << \"Case #\" << i << \": \";\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "divide and conquer",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2035",
    "index": "H",
    "title": "Peak Productivity Forces",
    "statement": "\\begin{quote}\nI'm peakly productive and this is deep.\n\\end{quote}\n\nYou are given two permutations$^{\\text{∗}}$ $a$ and $b$, both of length $n$.\n\nYou can perform the following three-step operation on permutation $a$:\n\n- Choose an index $i$ ($1 \\le i \\le n$).\n- Cyclic shift $a_1, a_2, \\ldots, a_{i-1}$ by $1$ to the right. If you had chosen $i = 1$, then this range doesn't exist, and you cyclic shift nothing.\n- Cyclic shift $a_{i + 1}, a_{i + 2}, \\ldots, a_n$ by $1$ to the right. If you had chosen $i = n$, then this range doesn't exist, and you cyclic shift nothing.\n\nAfter the operation, $a_1,a_2,\\ldots, a_{i-2},a_{i-1},a_i,a_{i + 1}, a_{i + 2},\\ldots,a_{n-1}, a_n$ is transformed into $a_{i-1},a_1,\\ldots,a_{i-3},a_{i-2},a_i,a_n, a_{i + 1},\\ldots,a_{n-2}, a_{n-1}$.\n\nHere are some examples of operations done on the identity permutation $[1,2,3,4,5,6,7]$ of length $7$:\n\n- If we choose $i = 3$, it will become $[2, 1, 3, 7, 4, 5, 6]$.\n- If we choose $i = 1$, it will become $[1, 7, 2, 3, 4, 5, 6]$.\n- If we choose $i = 7$, it will become $[6, 1, 2, 3, 4, 5, 7]$.\n\nNotably, position $i$ is \\textbf{not} shifted. Find a construction using at most $2n$ operations to make $a$ equal to $b$ or print $-1$ if it is impossible. The number of operations does not need to be minimized. It can be shown that if it is possible to make $a$ equal to $b$, it is possible to do this within $2n$ operations.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "We can rephrase the problem as sorting $b^{-1}(a)$. First, it is impossible to sort the permutation $[2, 1]$ because no operations you make affect the permutation. Instead of completely sorting it we can get it to a semi sorted state in $n + 1$ moves. This semi sorted state will be: some pairs of non-intersecting adjacent elements will be swapped and $n$ will always be in its position at the very end. ex: $[2, 1, 3, 5, 4, 6]$ where $1, 2$ are swapped and $4, 5$ are swapped How we can reach the semi sorted state? We will try to build this up in the prefix from largest element to smallest element. To move $x$ at index $i$ to the front we can do an operation on $i + 1$ if $i < n$. Because our sorted state condition requires $n$ to be at the front, if $i = n$ and $x = n$ we can make a query on position $1$ and then position $3$ to insert it into the front. If $i = n$ we can move $x - 1$ to the front and then $x$. Let $i'$ be the new position of $x$ after moving $x - 1$ to the front. If $i' = n$, we can move $x$ to it's correct position by doing the operation on position $1$. Otherwise, we can do the operation on position $i' + 1$ and insert it into the front. From here we can make $n - 1$ more operations on either position $n$ or $n - 1$ depending on which one we need to send to the front to sort it properly. We now need to be able to simulate the following operations efficiently. Do the operation on index $i$. Find the index of element $v$. Find the element at index $i$. This can be done in $O(\\log n)$ amortized per operation using an implicit BBST using a treap or splay. Alternatively, we can index each value by $\\text{current time} - \\text{position}$. The general rotation to the right does not affect this index, but the positions that do not just shift to the right by $1$ must be manually updated. This takes $O(1)$ per update and $O(1)$ per query (for more information, read the code). Depending on the data structure used, the final complexity is either $O(n)$ or $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n// #include \"../lib/hori.h\"\n \nstruct ds {\n  vector<int> occ, pos;\n  int counter, n;\n  ds() {}\n  ds(vector<int> perm) {\n    counter = 0;\n    n = ssize(perm);\n    occ = vector<int>(n, 0);\n    pos = vector<int>(2 * n, 0);  // store n + i - update\n    for (int i = 0; i < n; i++) {\n      occ[perm[i]] = i;\n      pos[n + i - 0] = perm[i];\n    }\n  }\n  int query(int x) {  // find the i such that a[i] = x;\n    return occ[x] + counter;\n  }\n  void op(int i) {  // funny operation\n    int a = pos[n + i - 1 - counter];\n    int b = pos[n + i - counter];\n    int c = pos[n + n - 1 - counter];\n    counter++;\n    if (i) pos[n + 0 - counter] = a, occ[a] = -counter;\n    pos[n + i - counter] = b, occ[b] = i - counter;\n    if (i != n - 1) pos[n + i + 1 - counter] = c, occ[c] = i + 1 - counter;\n  }\n  int at(int i) {  // return a[i]\n    return pos[n + i - counter];\n  }\n  vector<int> get() {  // return the new permutation\n    vector<int> arr(n);\n    for (int i = 0; i < n; i++) {\n      arr[i] = pos[n + i - counter];\n    }\n    return arr;\n  }\n};\n \nint main() {\n  ios::sync_with_stdio(0); cin.tie(0);\n  int t; cin >> t; for (int tt = 0; tt < t; tt++) {\n    int n; cin >> n;\n    vector<int> aa(n), bb(n), pos_b(n), a(n);\n    for (auto& i : aa) cin >> i, i--;\n    for (auto& i : bb) cin >> i, i--;\n    for (int i = 0; i < n; i++) pos_b[bb[i]] = i;\n    for (int i = 0; i < n; i++) a[i] = pos_b[aa[i]];\n    if (a == vector<int>{1, 0}) {\n      cout << -1 << endl;\n      continue;\n    }\n    ds d(a);\n    vector<int> ans;\n    auto op = [&] (int i) {\n      d.op(i);\n      ans.push_back(i + 1);\n      if (d.counter > n - 1) d = ds(d.get());\n    };\n    for (int i = n - 1; i >= 0; i--) {\n      int j = d.query(i);\n      if (j != n - 1) {\n        op(j + 1);\n      } else if (i != 0) {\n        int k = d.query(i - 1);\n        op(k + 1);\n        int j = d.query(i);\n        if (j == n - 1) op(0);\n        else op(j + 1), i += (i == n - 1);\n        i--;\n      } else {\n        op(0);\n      }\n    }\n    for (int i = 0; i < n - 1; i++) {\n      if (i != n - 2 and d.at(n - 3) > d.at(n - 2)) op(n - 2), i++;\n      op(n - 1);\n    }\n    cout << ans.size() << endl;\n    for (int i : ans) cout << i << \" \"; cout << endl;\n  }\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2036",
    "index": "A",
    "title": "Quintomania",
    "statement": "Boris Notkin composes melodies. He represents them as a sequence of notes, where each note is encoded as an integer from $0$ to $127$ inclusive. The interval between two notes $a$ and $b$ is equal to $|a - b|$ semitones.\n\nBoris considers a melody perfect if the interval between each two adjacent notes is either $5$ semitones or $7$ semitones.\n\nAfter composing his latest melodies, he enthusiastically shows you his collection of works. Help Boris Notkin understand whether his melodies are perfect.",
    "tutorial": "If for all $i$ $(1 \\leq i \\leq n - 1)$ is true $|a_i - a_{i+1}| = 5$ or $|a_i - a_{i+1}| = 7$, the answer to the problem is \"YES\", otherwise it is \"NO\". Complexity: $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nbool solve(){\n    int n;\n    cin >> n;\n    vector<int>a(n);\n    for(int i = 0; i < n; i++) cin >> a[i];\n    for(int i = 1; i < n; i++) {\n        if(abs(a[i] - a[i - 1]) != 5 && abs(a[i] - a[i - 1]) != 7) return false;\n    }\n    return true;\n}\nint main() {\n    int t;\n    cin >> t;\n    while(t--){\n        cout << (solve() ? \"YES\" : \"NO\") << \"\\n\";\n    }\n}\n",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2036",
    "index": "B",
    "title": "Startup",
    "statement": "Arseniy came up with another business plan — to sell soda from a vending machine! For this, he purchased a machine with $n$ shelves, as well as $k$ bottles, where the $i$-th bottle is characterized by the brand index $b_i$ and the cost $c_i$.\n\nYou can place any number of bottles on each shelf, but all bottles on the same shelf must be of the same brand.\n\nArseniy knows that all the bottles he puts on the shelves of the machine will be sold. Therefore, he asked you to calculate the \\textbf{maximum} amount he can earn.",
    "tutorial": "Let's create an array brand_cost of length $k$ and fill it so that brand_cost[i] stores the cost of all bottles of brand $i+1$. Then sort the array by non-growing and calculate the sum of its first min(n, k) elements, which will be the answer to the problem. Complexity: $O(k \\cdot \\log k)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n  int n, k;\n  cin >> n >> k;\n  vector<int> brand_cost(k, 0);\n  for (int i = 0; i < k; i++) {\n    int b, c;\n    cin >> b >> c;\n    brand_cost[b - 1] += c;\n  }\n  sort(brand_cost.rbegin(), brand_cost.rend());\n  long long ans = 0;\n  for (int i = 0; i < min(n, k); i++) {\n    ans += brand_cost[i];\n  }\n  cout << ans << '\\n';\n}\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}\n",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2036",
    "index": "C",
    "title": "Anya and 1100",
    "statement": "While rummaging through things in a distant drawer, Anya found a beautiful string $s$ consisting only of zeros and ones.\n\nNow she wants to make it even more beautiful by performing $q$ operations on it.\n\nEach operation is described by two integers $i$ ($1 \\le i \\le |s|$) and $v$ ($v \\in \\{0, 1\\}$) and means that the $i$-th character of the string is assigned the value $v$ (that is, the assignment $s_i = v$ is performed).\n\nBut Anya loves the number $1100$, so after each query, she asks you to tell her whether the substring \"1100\" is present in her string (i.e. there exist such $1 \\le i \\le |s| - 3$ that $s_{i}s_{i + 1}s_{i + 2}s_{i + 3} = 1100$).",
    "tutorial": "With each query, to track the change in the presence of \"1100\" in a row, you don't have to go through the entire row - you can check just a few neighboring cells. First, in a naive way, let's count $count$ - the number of times \"1100\" occurs in $s$. Then for each of $q$ queries we will update $count$: consider the substring $s[\\max(1, i - 3); \\min(i + 3, n)]$ before changing $s_i$ and find $before$ - the number of times that \"1100\" occurs in it. Then update $s_i = v$ and similarly find $after$ - the number of times that \"1100\" occurs in $s[\\max(1, i - 3); \\min(i + 3, n)]$ after applying the query. Thus, by doing $count = count + (after - before)$, we get the number of times that \"1100\" occurs in $s$ after the query is applied. If $count > 0$, the answer to the query is \"YES\", otherwise it is \"NO\". Complexity: $O(|s| + q)$",
    "code": "#include <cstdio>\n#include <cstring>\n\nusing namespace std;\ntypedef long long l;\n\nchar buf[1000000];\nl n;\n\nbool check_1100(l i) {\n\tif (i < 0) return false;\n\tif (i >= n - 3) return false;\n\tif (buf[i] == '1' && buf[i + 1] == '1' && buf[i + 2] == '0' && buf[i + 3] == '0') return true;\n\treturn false;\n}\n\nvoid solve() {\n\tscanf(\"%s\", buf);\n\tn = strlen(buf);\n\tl count = 0;\n\tfor (l i = 0; i < n; i++)\n\t\tif (check_1100(i)) count++;\n\t\n\tl q; scanf(\"%lld\", &q);\n\twhile (q--) {\n\t\tl i, v; scanf(\"%lld %lld\", &i, &v); i--;\n\t\tif (buf[i] != '0' + v) {\n\t\t    bool before = check_1100(i - 3) || check_1100(i - 2) || check_1100(i - 1) || check_1100(i);\n\t\t    buf[i] = '0' + v;\n\t\t    bool after = check_1100(i - 3) || check_1100(i - 2) || check_1100(i - 1) || check_1100(i);\n\t\t    count += after - before;\n\t\t}\n\t\tprintf(count ? \"YES\\n\" : \"NO\\n\");\n\t}\n}\n\nint main() {\n\tl t; scanf(\"%lld\", &t);\n\twhile (t--) solve();\n}\n",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2036",
    "index": "D",
    "title": "I Love 1543",
    "statement": "One morning, Polycarp woke up and realized that $1543$ is the most favorite number in his life.\n\nThe first thing that Polycarp saw that day as soon as he opened his eyes was a large wall carpet of size $n$ by $m$ cells; $n$ and $m$ are even integers. Each cell contains one of the digits from $0$ to $9$.\n\nPolycarp became curious about how many times the number $1543$ would appear in all layers$^{\\text{∗}}$ of the carpet when traversed \\textbf{clockwise}.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The first layer of a carpet of size $n \\times m$ is defined as a closed strip of length $2 \\cdot (n+m-2)$ and thickness of $1$ element, surrounding its outer part. Each subsequent layer is defined as the first layer of the carpet obtained by removing all previous layers from the original carpet.\n\\end{footnotesize}",
    "tutorial": "We will go through all layers of the carpet, adding to the answer the number of $1543$ records encountered on each layer. To do this, we can iterate over, for example, the top-left cells of each layer having the form $(i, i)$ for all $i$ in the range $[1, \\frac{min(n, m)}{2}]$, and then traverse the layer with a naive algorithm, writing the encountered digits into some array. Then traverse the array and count the $1543$ occurrences in that layer. Also, when traversing the array, we should take into account the cyclic nature of the layer, remembering to check for possible occurrences of $1543$ containing a starting cell. Complexity: $O(n \\cdot m)$",
    "code": "#include <cstdio>\n\nchar a[1005][1005];\nchar layer[4005];\n\nvoid solve() {\n    int n, m; scanf(\"%d %d\", &n, &m);\n    for (int i = 0; i < n; ++i) scanf(\"%s\", a[i]);\n    \n    int count = 0;\n    for (int i = 0; (i + 1) * 2 <= n && (i + 1) * 2 <= m; ++i) {\n        int pos = 0;\n        for (int j = i; j < m - i; ++j) layer[pos++] = a[i][j];\n        for (int j = i + 1; j < n - i - 1; ++j) layer[pos++] = a[j][m - i - 1];\n        for (int j = m - i - 1; j >= i; --j) layer[pos++] = a[n - i - 1][j];\n        for (int j = n - i - 2; j >= i + 1; --j) layer[pos++] = a[j][i];\n        \n        for (int j = 0; j < pos; ++j)\n            if (layer[j] == '1' && layer[(j + 1) % pos] == '5' && layer[(j + 2) % pos] == '4' && layer[(j + 3) % pos] == '3')\n                count++;\n        \n    }\n    \n    printf(\"%lld\\n\", count);\n}\n \nint main() {\n    int t; scanf(\"%d\", &t);\n    while (t--) solve();\n}\n",
    "tags": [
      "brute force",
      "implementation",
      "matrices"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2036",
    "index": "E",
    "title": "Reverse the Rivers",
    "statement": "A conspiracy of ancient sages, who decided to redirect rivers for their own convenience, has put the world on the brink. But before implementing their grand plan, they decided to carefully think through their strategy — that's what sages do.\n\nThere are $n$ countries, each with exactly $k$ regions. For the $j$-th region of the $i$-th country, they calculated the value $a_{i,j}$, which reflects the amount of water in it.\n\nThe sages intend to create channels between the $j$-th region of the $i$-th country and the $j$-th region of the $(i + 1)$-th country for all $1 \\leq i \\leq (n - 1)$ and for all $1 \\leq j \\leq k$.\n\nSince all $n$ countries are on a large slope, water flows towards the country with the highest number. According to the sages' predictions, after the channel system is created, the new value of the $j$-th region of the $i$-th country will be $b_{i,j} = a_{1,j} | a_{2,j} | ... | a_{i,j}$, where $|$ denotes the bitwise \"OR\" operation.\n\nAfter the redistribution of water, the sages aim to choose the most suitable country for living, so they will send you $q$ queries for consideration.\n\nEach query will contain $m$ requirements.\n\nEach requirement contains three parameters: the region number $r$, the sign $o$ (either \"$<$\" or \"$>$\"), and the value $c$. If $o$ = \"$<$\", then in the $r$-th region of the country you choose, the new value must be strictly less than the limit $c$, and if $o$ = \"$>$\", it must be strictly greater.\n\nIn other words, the chosen country $i$ must satisfy all $m$ requirements. If in the current requirement $o$ = \"$<$\", then it must hold that $b_{i,r} < c$, and if $o$ = \"$>$\", then $b_{i,r} > c$.\n\nIn response to each query, you should output a single integer — the number of the suitable country. If there are multiple such countries, output the smallest one. If no such country exists, output $-1$.",
    "tutorial": "For any non-negative integers, $a \\leq a | b$, where $|$ is the bitwise \"or\" operation. After computing the values of $b_{i,j}$ for all countries and regions, we can notice that for a fixed region $j$, the values of $b_{i,j}$ increase as the index $i$ increases. This is because the bitwise \"or\" operation cannot decrease a number, but only increase or leave it unchanged. Hence, we can use binary search to quickly find the country that matches the given conditions. For each query and for each requirement, if $o$ = \"<\", we search for the first country where $b_{i,r} \\geq c$ (this will be the first country that does not satisfy the condition). If sign $o$ = \">\", we look for the first country where $b_{i,r} \\leq c$. In both cases, we can use standard binary search to find the index. If the checks leave at least one country that satisfies all the requirements, we choose the country with the lowest number. Complexity: counting values $O(n\\cdot k)$, processing each query using binary search $O(m \\log n)$, total $O(n \\cdot k + q \\cdot m \\cdot \\log n)$.",
    "code": "#include <cstdio>\ntypedef long long l;\n\nl ** arr;\n\nint main() {\n\tl n, k, q; scanf(\"%lld %lld %lld\", &n, &k, &q);\n\t\n\tarr = new l*[n];\n\tfor (l i = 0; i < n; i++) arr[i] = new l[k];\n\tfor (l i = 0; i < n; i++) for (l j = 0; j < k; j++) scanf(\"%lld\", &arr[i][j]);\n\t\n\tfor (l i = 1; i < n; i++) for (l j = 0; j < k; j++) arr[i][j] |= arr[i - 1][j];\n\t\n\twhile (q--) {\n\t\tl m; scanf(\"%lld\", &m);\n\t\tl left_pos = 0, right_pos = n - 1;\n\t\twhile (m--) {\n\t\t\tl r, c; char o; scanf(\"%lld %c %lld\", &r, &o, &c); r--;\n\t\t\tif (o == '<') {\n\t\t\t\tl le = -1, ri = n, mid;\n\t\t\t\twhile (le + 1 != ri) {\n\t\t\t\t\tmid = (le + ri) / 2;\n\t\t\t\t\tif (arr[mid][r] < c) le = mid;\n\t\t\t\t\telse ri = mid;\n\t\t\t\t}\n\t\t\t\tif (le < right_pos) right_pos = le;\n\t\t\t} else {\n\t\t\t\tl le = -1, ri = n, mid;\n\t\t\t\twhile (le + 1 != ri) {\n\t\t\t\t\tmid = (le + ri) / 2;\n\t\t\t\t\tif (arr[mid][r] <= c) le = mid;\n\t\t\t\t\telse ri = mid;\n\t\t\t\t}\n\t\t\t\tif (ri > left_pos) left_pos = ri;\n\t\t\t}\n\t\t}\n\t\tif (left_pos <= right_pos) printf(\"%lld\\n\", left_pos + 1);\n\t\telse printf(\"-1\\n\");\n\t}\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2036",
    "index": "F",
    "title": "XORificator 3000",
    "statement": "Alice has been giving gifts to Bob for many years, and she knows that what he enjoys the most is performing bitwise XOR of interesting integers. Bob considers a positive integer $x$ to be interesting if it satisfies $x \\not\\equiv k (\\bmod 2^i)$. Therefore, this year for his birthday, she gifted him a super-powerful \"XORificator 3000\", the latest model.\n\nBob was very pleased with the gift, as it allowed him to instantly compute the XOR of all interesting integers in any range from $l$ to $r$, inclusive. After all, what else does a person need for happiness? Unfortunately, the device was so powerful that at one point it performed XOR with itself and disappeared. Bob was very upset, and to cheer him up, Alice asked you to write your version of the \"XORificator\".",
    "tutorial": "Note the base of the module Can we quickly compute XOR on the segment $[l, r]$? We also recommend the beautiful tutorial by ne_justlm! Let us introduce the notation $\\DeclareMathOperator{\\XOR}{XOR}\\XOR(l, r) = l \\oplus (l+1) \\oplus \\dots \\oplus r$ . The first thing that comes to mind when reading the condition is that we can compute XOR of all numbers on the segment $(0, x)$ for $O(1)$ by the following formula: $\\XOR(0, x) = \\begin{cases} x & \\text{if } x \\equiv 0 \\pmod{4} \\\\ 1 & \\text{if } x \\equiv 1 \\pmod{4} \\\\ x + 1 & \\text{if } x \\equiv 2 \\pmod{4} \\\\ 0 & \\text{if } x \\equiv 3 \\pmod{4} \\end{cases}$ Then $\\XOR(l, r)$ can be found as $\\XOR(0, r) \\oplus \\XOR(0, l-1)$. Now note that for the answer we only need to learn for $O(1)$ to find XOR of all uninteresting on the segment: then we can do XOR with the whole segment and get XOR of all interesting numbers already. The base of the modulus, equal to the degree of two, is not chosen by chance: we only need to \"compress\" $l$ and $r$ by $2^i$ times in such a way that the resulting range contains all uninteresting numbers shifted $i$ bits to the right. Then computing $\\XOR(l', r')$ we get exactly the desired XOR of uninteresting numbers, also shifted $i$ bits to the right. Then, to find these remaining lower $i$ bits, we just need to find the number of uninteresting numbers on the segment $[l, r]$. If it is odd, these $i$ bits will be equal to $k$, since they are all equal to $k \\mod 2^i$, and so have the same $i$ minor bits equal to $k$ proper, and so their XOR an odd number of times will also be equal to $k$. Otherwise, the lower $i$ bits of the answer will be $0$, since we have done XOR an even number of times. The number of uninteresting numbers on the segment can be calculated in a similar way to $\\XOR(l, r)$, namely find their number on the segments $[0, r]$ and $[0, l-1]$ and subtract the latter from the former. The number of numbers equal to $k$ modulo $m$ and not exceeding $r$ is calculated as $\\left\\lfloor \\frac{r - k}{m} \\right\\rfloor$. Time complexity of the solution: $O(\\mathit{\\log r})$.",
    "code": "#include <iostream>\nusing namespace std;\n#define int uint64_t\n#define SPEEDY std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0);\n \nint xor_0_n(int n) {\n    int rem = n % 4;\n    if (rem == 0) {\n        return n;\n    }\n    if (rem == 1) {\n        return 1;\n    }\n    if (rem == 2) {\n        return n + 1;\n    }\n    return 0;\n}\n \nint xor_range(int l, int r) {\n    return xor_0_n(r) ^ xor_0_n(l - 1);\n}\n \nint32_t main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        int l, r, i, k;\n        cin >> l >> r >> i >> k;\n        int highBits = xor_range((l - k + (1 << i) - 1) >> i, (r - k) >> i) << i;\n        int lowBits = k * (((r - k) / (1 << i) - (l - k - 1) / (1 << i)) & 1);\n        cout << (xor_range(l, r) ^ highBits ^ lowBits) << '\\n';\n    }\n    return 0;\n}\n",
    "tags": [
      "bitmasks",
      "dp",
      "number theory",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2036",
    "index": "G",
    "title": "Library of Magic",
    "statement": "This is an interactive problem.\n\nThe Department of Supernatural Phenomena at the Oxenfurt Academy has opened the Library of Magic, which contains the works of the greatest sorcerers of Redania — $n$ ($3 \\leq n \\leq 10^{18}$) types of books, numbered from $1$ to $n$. Each book's type number is indicated on its spine. Moreover, each type of book is stored in the library in exactly two copies! And you have been appointed as the librarian.\n\nOne night, you wake up to a strange noise and see a creature leaving the building through a window. Three thick tomes of different colors were sticking out of the mysterious thief's backpack. Before you start searching for them, you decide to compute the numbers $a$, $b$, and $c$ written on the spines of these books. All three numbers are \\textbf{distinct}.\n\nSo, you have an unordered set of tomes, which includes one tome with each of the pairwise distinct numbers $a$, $b$, and $c$, and two tomes for all numbers from $1$ to $n$, except for $a$, $b$, and $c$. You want to find these values $a$, $b$, and $c$.\n\nSince you are not working in a simple library, but in the Library of Magic, you can only use one spell in the form of a query to check the presence of books in their place:\n\n- \"xor l r\" — \\textbf{Bitwise XOR query} with parameters $l$ and $r$. Let $k$ be the number of such tomes in the library whose numbers are greater than or equal to $l$ and less than or equal to $r$. You will receive the result of the computation $v_1 \\oplus v_2 \\oplus ... \\oplus v_k$, where $v_1 ... v_k$ are the numbers on the spines of these tomes, and $\\oplus$ denotes the operation of bitwise exclusive OR.\n\nSince your magical abilities as a librarian are severely limited, you can make no more than $150$ queries.",
    "tutorial": "Have you considered the cases where $a \\oplus b \\oplus c = 0$? Suppose you are certain that at least one lost number is located on some segment $[le, ri]$. Can you choose a value $mid$ such that the queries xor {le} {mid} and xor {mid + 1} {ri} you can unambiguously understand on which of the segments ($[le, mid]$ or $[(mid + 1), ri]$) lies at least one lost number, even if both of these queries return $0$? To begin with, we note that for any number $x$, $x \\oplus x = 0$ is satisfied. Therefore, by querying xor l r, you will get bitwise XOR of only those volume numbers that are in the library in a single copy (within the scope of querying $l$ and $r$, of course). Also note that for two pairwise distinct numbers $x$ and $y$, $x \\oplus y \\neq 0$ is always satisfied. Initially, our goal is - to determine the largest bit of the maximum of the lost numbers. To do this, we can go through the bits starting from the largest significant bit in n. For each $i$-th bit, we will ask xor {2^i} {min(2^(i + 1) - 1, n)}. Note that all numbers on this interval have $i$-th bit equal to one. Then if we get a result not equal to zero, then this bit is the desired largest bit of the maximum of the lost numbers. If we get a result equal to zero, then this bit is guaranteed not to be present in any of the numbers, i.e. all three numbers are less than $2^i$. Let's prove it. If we had one or two numbers on the requested interval, their XOR would not be $0$ (see the first paragraph). If all three numbers are on this interval, then the XOR of their $i$-th bit is $1 \\oplus 1 \\oplus 1 = 1$, and hence the XOR of the numbers themselves is also different from $0$. Now that we know the largest bit $i$ of the desired number, we can find this number by any realization of binary search inside the interval $[2^i; \\min(2^{i + 1} - 1, n)]$. By the answer to any query on any interval within that interval, we can unambiguously know whether our number is present on that interval or not - the proof is similar to the one above. The first number is found. The second number can be found using any bin search, since XOR of two different numbers is always different from zero. The main thing is not to forget to \"exclude\" the already found number from the obtained result using the same XOR. And the third number can be found by requesting the result of the whole interval from $1$ to $n$ and \"excluding\" the already found two numbers from it. Number of requests: $\\approx 2 \\cdot \\log n \\approx 120 < 150$",
    "code": "#include <cstdio>\ntypedef long long l;\n\nl n, num1, num2;\n\nl req(l le, l ri, l num) {\n    if (le > n) return 0;\n    if (ri > n) ri = n;\n    \n    printf(\"xor %lld %lld\\n\", le, ri); fflush(stdout);\n    l res; scanf(\"%lld\", &res);\n    \n    if (num > 1 && le <= num1 && num1 <= ri) res ^= num1;\n    if (num > 2 && le <= num2 && num2 <= ri) res ^= num2;\n    return res;\n}\n\nvoid solve() {\n    scanf(\"%lld\", &n); num1 = 0; num2 = 0;\n    l start = 1LL << (63 - __builtin_clzll(n));\n\n    for (l i = start; i > 0; i >>= 1) {\n        l res = req(num1 | i, num1 | (i * 2 - 1), 1);\n        if (res) num1 |= i;\n    }\n\n    for (l i = start; i > 0; i >>= 1) {\n        l res = req(num2 | i, num2 | (i * 2 - 1), 2);\n        if (res) num2 |= i;\n    }\n    \n    printf(\"ans %lld %lld %lld\\n\", num1, num2, req(1, n, 3));\n    fflush(stdout);\n}\n\nint main() {\n    l t; scanf(\"%lld\", &t);\n    while (t--) solve();\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "divide and conquer",
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2037",
    "index": "A",
    "title": "Twice",
    "statement": "Kinich wakes up to the start of a new day. He turns on his phone, checks his mailbox, and finds a mysterious present. He decides to unbox the present.\n\nKinich unboxes an array $a$ with $n$ integers. Initially, Kinich's score is $0$. He will perform the following operation any number of times:\n\n- Select two indices $i$ and $j$ $(1 \\leq i < j \\leq n)$ such that neither $i$ nor $j$ has been chosen in any previous operation and $a_i = a_j$. Then, add $1$ to his score.\n\nOutput the maximum score Kinich can achieve after performing the aforementioned operation any number of times.",
    "tutorial": "We want to count how many times we can choose $i$ and $j$ such that $a_i = a_j$. Suppose $f_x$ stores the frequency of $x$ in $a$. Once we choose $a_i = a_j = x$, $f_x$ is subtracted by $2$. Thus, the answer is the sum of $\\lfloor \\frac{f_x}{2} \\rfloor$ over all $x$.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n    print(sum([a.count(x) // 2 for x in range(n + 1)]))",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2037",
    "index": "B",
    "title": "Intercepted Inputs",
    "statement": "To help you prepare for your upcoming Codeforces contest, Citlali set a grid problem and is trying to give you a $n$ by $m$ grid through your input stream. Specifically, your input stream should contain the following:\n\n- The first line contains two integers $n$ and $m$ — the dimensions of the grid.\n- The following $n$ lines contain $m$ integers each — the values of the grid.\n\nHowever, someone has intercepted your input stream, shuffled all given integers, and put them all on one line! Now, there are $k$ integers all on one line, and you don't know where each integer originally belongs. Instead of asking Citlali to resend the input, you decide to determine the values of $n$ and $m$ yourself.\n\nOutput any possible value of $n$ and $m$ that Citlali could have provided.",
    "tutorial": "It is worth noting that test $4$ is especially made to blow up python dictionaries, sets, and Collections.counter. If you are time limit exceeding, consider using a frequency array of length $n$. You must check if you can find two integers $n$ and $m$, such that $n \\cdot m+2=k$. You can either use a counter, or use two pointers. Do note that $n^2+2=k$ is an edge case that must be separated if you use a counter to implement it. This edge case does not appear in the two pointers approach. Time complexity is $O(n \\log n)$ (assuming you are wise enough to not use a hash table).",
    "code": "testcases = int(input())\nfor _ in range(testcases):\n    k = int(input())\n    list = input().split()\n    freq = []\n    for i in range(k+1):\n        freq.append(0)\n    for x in list:\n        freq[int(x)] = freq[int(x)]+1\n    solution = (-1,-1)\n    for i in range(1,k+1):\n        if i*i==k-2:\n            if freq[i]>1:\n                solution = (i,i)\n        elif (k-2)%i==0:\n            if freq[i]>0 and freq[(k-2)//i]>0:\n                solution = (i, (k-2)//i)\n    print(solution[0], solution[1])",
    "tags": [
      "brute force",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2037",
    "index": "C",
    "title": "Superultra's Favorite Permutation",
    "statement": "Superultra, a little red panda, desperately wants primogems. In his dreams, a voice tells him that he must solve the following task to obtain a lifetime supply of primogems. Help Superultra!\n\nConstruct a permutation$^{\\text{∗}}$ $p$ of length $n$ such that $p_i + p_{i+1}$ is composite$^{\\text{†}}$ over all $1 \\leq i \\leq n - 1$. If it's not possible, output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$An integer $x$ is composite if it has at least one other divisor besides $1$ and $x$. For example, $4$ is composite because $2$ is a divisor.\n\\end{footnotesize}",
    "tutorial": "Remember that all even numbers greater than $2$ are composite. As $1+3 > 2$, any two numbers with same parity sum up to a composite number. Now you only have to find one odd number and one even number that sum up to a composite number. One can manually verify that there is no such pair in $n \\leq 4$, but in $n=5$ there exists $(4,5)$ which sums up to $9$, a composite number.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    if n < 5:\n        print(-1)\n        continue\n    for i in range(2,n+1,2):\n        if i != 4:\n            print(i,end=\" \")\n    print(\"4 5\",end=\" \")\n    for i in range(1,n+1,2):\n        if i != 5:\n            print(i, end = \" \")\n    print()",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2037",
    "index": "D",
    "title": "Sharky Surfing",
    "statement": "Mualani loves surfing on her sharky surfboard!\n\nMualani's surf path can be modeled by a number line. She starts at position $1$, and the path ends at position $L$. When she is at position $x$ with a jump power of $k$, she can jump to any \\textbf{integer} position in the interval $[x, x+k]$. Initially, her jump power is $1$.\n\nHowever, her surf path isn't completely smooth. There are $n$ hurdles on her path. Each hurdle is represented by an interval $[l, r]$, meaning she cannot jump to any position in the interval $[l, r]$.\n\nThere are also $m$ power-ups at certain positions on the path. Power-up $i$ is located at position $x_i$ and has a value of $v_i$. When Mualani is at position $x_i$, she has the option to collect the power-up to increase her jump power by $v_i$. There may be multiple power-ups at the same position. When she is at a position with some power-ups, she may choose to take or ignore each individual power-up. No power-up is in the interval of any hurdle.\n\nWhat is the minimum number of power-ups she must collect to reach position $L$ to finish the path? If it is not possible to finish the surf path, output $-1$.",
    "tutorial": "Process from earliest to latest. Maintain a priority queue of power-ups left so far. If Mualani meets a power-up, add it to the priority queue. Otherwise (Mualani meets a hurdle), take power-ups in the priority queue from strongest to weakest until you can jump over the hurdle. This guarantees that each time Mualani jumps over a hurdle, she takes the minimum number of power-ups necessary. Time complexity is $O((n+m)\\log m)$, where $O(\\log m)$ is from the priority queue. Note that the hurdle intervals are inclusive. If there is a hurdle at $[l, r]$, she must jump from position $l-1$ to $r+1$.",
    "code": "import sys\nimport heapq\ninput = sys.stdin.readline\nfor _ in range(int(input())):\n    n,m,L = map(int,input().split())\n    EV = []\n    for _ in range(n):\n        EV.append((*list(map(int,input().split())),1))\n    for _ in range(m):\n        EV.append((*list(map(int,input().split())),0))\n    EV.sort()\n    k = 1\n    pwr = []\n    for a,b,t in EV:\n        if t == 0:\n            heapq.heappush(pwr,-b)\n        else:\n            while pwr and k < b-a + 2:\n                k -= heapq.heappop(pwr)\n            if k < b-a + 2:\n                print(-1)\n                break\n    else:\n        print(m-len(pwr))",
    "tags": [
      "data structures",
      "greedy",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2037",
    "index": "E",
    "title": "Kachina's Favorite Binary String",
    "statement": "This is an interactive problem.\n\nKachina challenges you to guess her favorite binary string$^{\\text{∗}}$ $s$ of length $n$. She defines $f(l, r)$ as the number of subsequences$^{\\text{†}}$ of $01$ in $s_l s_{l+1} \\ldots s_r$. \\textbf{Two subsequences are considered different if they are formed by deleting characters from different positions in the original string, even if the resulting subsequences consist of the same characters.}\n\nTo determine $s$, you can ask her some questions. In each question, you can choose two indices $l$ and $r$ ($1 \\leq l < r \\leq n$) and ask her for the value of $f(l, r)$.\n\nDetermine and output $s$ after asking Kachina no more than $n$ questions. However, it may be the case that $s$ is impossible to be determined. In this case, you would need to report $IMPOSSIBLE$ instead.\n\nFormally, $s$ is impossible to be determined if after asking $n$ questions, there are always multiple possible strings for $s$, regardless of what questions are asked. \\textbf{Note that if you report} $IMPOSSIBLE$ \\textbf{when there exists a sequence of at most $n$ queries that will uniquely determine the binary string, you will get the Wrong Answer verdict.}\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string only contains characters $0$ and $1$.\n\n$^{\\text{†}}$A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements. For example, subsequences of $\\mathtt{1011101}$ are $\\mathtt{0}$, $\\mathtt{1}$, $\\mathtt{11111}$, $\\mathtt{0111}$, but not $\\mathtt{000}$ nor $\\mathtt{11100}$.\n\\end{footnotesize}",
    "tutorial": "Notice that for if for some $r$ we have $f(1, r) < f(1, r + 1)$ then we can conclude that $s_{r + 1} = 1$ (if it is $0$ then $f(1, r) = f(1, r + 1)$ will be true) and if $f(1, r)$ is non-zero and $f(1, r) = f(1, r + 1)$ then $s_{r + 1}$ is $0$. Unfortunately this is only useful if there is a $0$ in $s_1,s_2,...,s_r$, so the next thing can try is to find is the value of the longest prefix such that $f(1, r)$ is $0$ (after this point there will be a zero in all prefixes). See that if $f(1, r) = 0$ and $f(1, r + 1) = k$ then $s_{r + 1} = 1$, the last $k$ characters of $s_1,s_2,...,s_r$ must be $0$ and the first $r - k$ characters must be $1$. To prove this we can argue by contradiction, suppose it is not true and then it will become apparent that some shorter prefix will be non-zero when we query it. The one case that this does not cover is when all prefixes are zero, from similar contradiction argument as above we can see that the string must look like $111...1100....000$ in this case, in this case it is not hard to see that all queries will give a value of zero, and thus we can report that it is impossible. So we should query all prefixes, the first one which is non-zero (if this does not exist we can report impossible) we can deduce its value as discussed above, then there will be a $0$ in the prefix so we can deduce all subsequent characters as discussed at the start.",
    "code": "def qu(a,b):\n    if (a,b) not in d:\n        print(\"?\", a+1,b+1)\n        d[(a,b)] = int(input())\n    return d[(a,b)]\nfor _ in range(int(input())):\n    d = dict()\n    n = int(input())\n    SOL = [\"0\"] * n\n    last = qu(0,n-1)\n    if last:\n        z = 1\n        for i in range(n-2,0,-1):\n            nw= qu(0,i)\n            if nw != last:\n                SOL[i+1] = \"1\"\n            last = nw\n            if last == 0:\n                z = i+1;break\n        if last:\n            SOL[1] = \"1\"\n            SOL[0] = \"0\"\n        else:\n            last = 1\n            for j in range(z-2,-1,-1):\n                nw = qu(j,z)\n                if nw == last:\n                    SOL[j] = \"1\"\n                last = nw\n        print(\"!\",\"\".join(SOL))\n    else:\n        print(\"! IMPOSSIBLE\")",
    "tags": [
      "dp",
      "greedy",
      "interactive",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2037",
    "index": "F",
    "title": "Ardent Flames",
    "statement": "You have obtained the new limited event character Xilonen. You decide to use her in combat.\n\nThere are $n$ enemies in a line. The $i$'th enemy from the left has health $h_i$ and is currently at position $x_i$. Xilonen has an attack damage of $m$, and you are ready to defeat the enemies with her.\n\nXilonen has a powerful \"ground stomp\" attack. \\textbf{Before you perform any attacks}, you select an integer $p$ and position Xilonen there ($p$ can be any integer position, including a position with an enemy currently). Afterwards, for each attack, she deals $m$ damage to an enemy at position $p$ (if there are any), $m-1$ damage to enemies at positions $p-1$ and $p+1$, $m-2$ damage to enemies at positions $p-2$ and $p+2$, and so on. Enemies that are at least a distance of $m$ away from Xilonen take no damage from attacks.\n\nFormally, if there is an enemy at position $x$, she will deal $\\max(0,m - |p - x|)$ damage to that enemy each hit. \\textbf{Note that you may not choose a different $p$ for different attacks.}\n\nOver all possible $p$, output the minimum number of attacks Xilonen must perform to defeat at least $k$ enemies. If it is impossible to find a $p$ such that eventually at least $k$ enemies will be defeated, output $-1$ instead. Note that an enemy is considered to be defeated if its health reaches $0$ or below.",
    "tutorial": "Let's perform binary search on the minimum number of hits to kill at least $k$ enemies. How do we check if a specific answer is possible? Let's consider a single enemy for now. If its health is $h_i$ and we need to kill it in at most $q$ attacks, then we need to be doing at least $\\lceil\\frac{h_i}{q}\\rceil$ damage per attack to this enemy. If this number is greater than $m$, then obviously we cannot kill this enemy in at most $q$ attacks as the maximum damage Xilonen can do is $m$ damage per hit. Otherwise, we can model the enemy as a valid interval where we can place Xilonen. Specifically, the inequality $m-|p-x|\\geq\\lceil\\frac{h_i}{q}\\rceil$ must be satisfied. Now that we have modeled each enemy as an interval, the problem is reduced to finding whether or not there exists a point on at least $k$ intervals. This is a classic problem that can be approached by a sweep-line algorithm, sorting the events of intervals starting and ending by time and adding $1$ to your counter when an interval starts and subtracting $1$ to your counter when an interval ends. Note that the maximum possible answer to any setup with a solution is $\\max( h_i)=10^9$, so if we cannot kill at least $k$ enemies in $10^9$ attacks then we can just output $-1$ as our answer. The total time complexity is $O(n\\log({n})\\log({\\max(h_i)})$.",
    "code": "import sys\ninput = sys.stdin.readline\nfrom collections import defaultdict\nfor _ in range(1):\n    n,m,k = map(int,input().split())\n    h = list(map(int,input().split()))\n    x = list(map(int,input().split()))\n    lo = 0\n    hi = int(1e10)\n    while hi - lo > 1:\n        mid = (lo + hi) // 2\n        ev = defaultdict(int)\n        for i in range(n):\n            ma = (h[i] + mid - 1) // mid\n            if ma > m: continue\n            ev[x[i]-m+ma] += 1\n            ev[x[i]+m-ma+1] -= 1\n        sc = 0\n        for y in sorted(ev.keys()):\n            sc += ev[y]\n            if sc >= k:\n                hi = mid\n                break\n        else:\n            lo = mid\n    if hi == int(1e10):\n        print(-1)\n    else:\n        print(hi)",
    "tags": [
      "binary search",
      "data structures",
      "math",
      "sortings",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2037",
    "index": "G",
    "title": "Natlan Exploring",
    "statement": "You are exploring the stunning region of Natlan! This region consists of $n$ cities, and each city is rated with an attractiveness $a_i$. A directed edge exists from City $i$ to City $j$ if and only if $i < j$ and $\\gcd(a_i,a_j)\\neq 1$, where $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\nStarting from City $1$, your task is to determine the total number of distinct paths you can take to reach City $n$, modulo $998\\,244\\,353$. Two paths are different if and only if the set of cities visited is different.",
    "tutorial": "Denote $dp[i]=$ the number of ways to get to city $i$. Brute-forcing all possible previous cities is out of the question, as this solution will take $O(n^2\\cdot\\log({\\max{a_i}}))$ time complexity. What else can we do? Instead, consider caseworking on what the greatest common factor can be. Let's keep track of an array $count$ which for index $i$ keeps track of the sum of $dp$ values of all previous cities who has a factor of $i$. Say the current city has attractiveness $a_i$. We can almost recover $dp[i]$ by adding up the $count$ values of all factors of $a_i$. Unfortunately, this fails as it overcounts many instances. For example, if $\\gcd(a_i, a_j)=12$ the $dp$ state from $i$ will be counted five times: $2, 3, 4, 6, 12$. Note that we don't actually care what the greatest common factor is, since the only requirement is that the greatest common factor is not $1$. This also means that repeat appearances of the same prime number in the factorization of $a_i$ doesn't matter at all - we can assume each prime factor occurs exactly once. Now, if $\\gcd(a_i, a_j)=12$, it is only counted three times: $2,3,6$. Now, instead of blindly adding the $count$ values from all previous states, let's instead apply the Principle of Inclusion-Exclusion on the prime factors. Let's first add the $count$ values from all prime factors, then subtract the $count$ values from all factors with two prime factors, then add the $count$ values from all factors with three prime factors, and so on. It can be seen that actually, the value is only counted one time now. So what's the time complexity of this solution? Precomputing the set of all prime number takes $O(\\max(a_i)\\log(\\max(a_i)))$ time (by the harmonic series $\\frac{n}{1}+\\frac{n}{2}+\\ldots+\\frac{n}{n}\\approx n\\log(n)$). For each number $a_i$, we have to consider all $2^{f(a_i)}$ subsets of prime factors, where $f(a_i)$ is the number of prime factors of $a_i$. The number with the most distinct prime factors is $510510=2\\cdot3\\cdot5\\cdot7\\cdot11\\cdot13\\cdot17$, so worst case $2^7=128$ operations are needed per number. This goes to a total operation count of approximately $128\\cdot n$ which will pass in the time limit. Note that we may also use the Mobius function to compute the answer. The Mobius function's properties makes it utilize the Principle of Inclusion-Exclusion efficiently. The time complexity of this solution is $O(\\max(a_i)\\log(\\max(a_i))+n\\max(d(a_i)))$ where $d(a_i)$ is the maximum number of factors of $a_i$. This time complexity can be shown to be the same as the above time complexity.",
    "code": "import sys\n\ndef input():\n    return sys.stdin.buffer.readline().strip()\n\nMOD = 998244353\nma = int(1e6 + 5)\nP = [1] * ma\nD = [[] for _ in range(ma)]\nfor i in range(2, ma):\n    if P[i] == 1:\n        for j in range(i, ma, i):\n            P[j] = i\nF = [0] * ma\nLU = [0] * ma\nBMS = [[] for _ in range(ma)]\nRES = []\nfrom itertools import combinations\ndef getBMS(x):\n    if not BMS[x]:\n        y = help(x)\n        for i in range(len(y)):\n            p = combinations(y, i + 1)\n            for a in p:\n                xx = 1\n                for j in a:\n                    xx *= j\n                BMS[x].append((xx,i))\n    return BMS[x]\ndef helps(x):\n    y = x\n    while x != 1:\n        s = P[x]\n        D[y].append(s)\n        while x % s == 0:\n            x //= s\n\n\ndef help(x):\n    if not D[x]: helps(x)\n    return D[x]\n\n\n\n\nfor yy in range(int(input())):\n    n = int(input())\n    A = list(map(int, input().split()))\n    for xx,i in getBMS(A[0]):\n        F[xx] = 1\n        LU[xx] = yy\n    for i in range(1, n - 1):\n        tot = 0\n        for xx, j in getBMS(A[i]):\n            if LU[xx] != - 1 and LU[xx] != yy:\n                F[xx] = 0\n            LU[xx] = yy\n            if F[xx]:\n                if j % 2:\n                    tot -= F[xx]\n                    tot %= MOD\n                else:\n                    tot += F[xx]\n                    tot %= MOD\n        for xx, j in getBMS(A[i]):\n            F[xx] += tot\n            F[xx] %= MOD\n    S = 0\n    for xx,i in getBMS(A[-1]):\n        if LU[xx] != - 1 and LU[xx] != yy:\n            LU[xx] = yy\n            F[xx] = 0\n        if F[xx]:\n            if i % 2:\n                S -= F[xx]\n                S %= MOD\n            else:\n                S += F[xx]\n                S %= MOD\n\n    RES.append(str(S))\nprint(\"\\n\".join(RES))",
    "tags": [
      "bitmasks",
      "combinatorics",
      "data structures",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2039",
    "index": "A",
    "title": "Shohag Loves Mod",
    "statement": "Shohag has an integer $n$. Please help him find an \\textbf{increasing} integer sequence $1 \\le a_1 \\lt a_2 \\lt \\ldots \\lt a_n \\le 100$ such that $a_i \\bmod i \\neq a_j \\bmod j$ $^{\\text{∗}}$ is satisfied over all pairs $1 \\le i \\lt j \\le n$.\n\nIt can be shown that such a sequence always exists under the given constraints.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$a \\bmod b$ denotes the remainder of $a$ after division by $b$. For example, $7 \\bmod 3 = 1, 8 \\bmod 4 = 0$ and $69 \\bmod 10 = 9$.\n\\end{footnotesize}",
    "tutorial": "THOUGHT: A general approach to tackle ad-hoc problems is to play around with the conditions and see if we can add more constraints to limit the search space. ACTION: Let's analyze the modular condition $a_i \\bmod i$. We know that $a_i \\bmod i < i$, and all $a_i \\bmod i$ values are distinct. Let's explore this step by step: $a_1 \\bmod 1$ is always $0$. $a_2 \\bmod 2$ can be $0$ or $1$. But since all $a_i \\bmod i$ values must be distinct, $a_2 \\bmod 2$ must be $1$ (otherwise, it would equal $a_1 \\bmod 1$). $a_3 \\bmod 3$ can be $0$, $1$, or $2$. Similarly, $a_3 \\bmod 3$ must be $2$ (to avoid duplication with $a_1 \\bmod 1$ or $a_2 \\bmod 2$). $\\ldots$ $a_n \\bmod n$ must be $n-1$. OBSERVATION: This leads to the constraint $a_i \\bmod i = i - 1$. THOUGHT: Next, let's consider the increasing sequence condition. OBSERVATION: Since the sequence must be increasing, we add the constraint $a_i \\ge i$. THOUGHT: To further limit the search space, note that $n$ can be up to $50$, and $a_i$ must be $\\le 100$. OBSERVATION: This suggests that we can restrict $a_i$ to values up to $2 \\cdot n$. THOUGHT: Let's compile the constraints: $a_i \\bmod i = i - 1$. $a_i \\ge i$. $a_i \\le 2 \\cdot n$. Now we need to build the sequence that satisfies these conditions. ACTION: Let's build the sequence starting from the end. $a_n \\bmod n = n-1$. Thus, $a_n$ can be $n-1$ or $2 \\cdot n - 1$. Since $a_n \\ge n$, $a_n$ must be $2 \\cdot n - 1$. $a_{n-1} \\bmod (n-1) = n-2$. So $a_{n-1}$ can be $n-2$ or $(n - 2) + (n - 1) = 2 \\cdot n - 3$. Since $a_{n-1} \\ge n-1$, $a_{n-1}$ must be $2 \\cdot n - 3$. $\\ldots$ $a_i \\bmod i = i - 1$. Thus, $a_i$ can be $i - 1$ or $2 \\cdot i - 1$ or $3 \\cdot i - 1 \\ldots$. Since $a_i \\ge i$ and the odd numbers greater than $2 \\cdot i$ have already been used, $a_i$ must be $2 \\cdot i - 1$. OBSERVATION: If we limit the elements to $2 \\cdot n$, there is exactly one sequence that satisfies all conditions. CONCLUSION: The sequence is $a_i = 2 \\cdot i - 1$, which is $1, 3, 5, \\ldots, 2 \\cdot n - 1$. VALIDATION: We can validate the solution by checking if it satisfies all the constraints. $a_i \\bmod i = (2 \\cdot i - 1) \\bmod i = i - 1$. So all $a_i \\bmod i$ are distinct and values are under $2 \\cdot n$. So the sequence is valid. Time Complexity: $\\mathcal{O}(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 3e5 + 9;\nusing ll = long long;\n\nvoid solve() {\n  int n; cin >> n;\n  for (int i = 1; i <= n; i++) {\n    cout << 2 * i - 1 << ' ';\n  }\n  cout << '\\n';\n}\n\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t = 1;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2039",
    "index": "B",
    "title": "Shohag Loves Strings",
    "statement": "For a string $p$, let $f(p)$ be the number of distinct non-empty substrings$^{\\text{∗}}$ of $p$.\n\nShohag has a string $s$. Help him find a non-empty string $p$ such that $p$ is a substring of $s$ and $f(p)$ is even or state that no such string exists.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\\end{footnotesize}",
    "tutorial": "THOUGHT: The condition seems hard to track. So a good way is to play around with smaller cases and see if we can make some observations. ACTION: Let's start with the smallest string. When $s=$ a, the number of unique substrings $f(s) = 1$, so it's odd and not valid. OBSERVATION: No one length strings are valid. ACTION: Let's try the next smallest strings. When $s=$ aa, $f(s) = 2$, so it's even and valid. When $s=$ ab, $f(s) = 3$, so it's odd and not valid. OBSERVATION: Two length strings are valid if the adjacent characters are same. THOUGHT: So if $s$ contains two consecutive same characters, we can print it right away. All that remains is to consider strings without two consecutive same characters. ACTION: Let's try the next smallest strings with adjacent different characters. When $s=$ aba, $f(s) = 5$, so it's odd and not valid. When $s=$ abc, $f(s) = 6$, so it's even and valid. OBSERVATION: Three length strings are valid if all characters are different. THOUGHT: So if $s$ contains three consecutive different characters, we can print it right away. All that remains is to consider strings without two adjacent same characters but no three consecutive different characters. So all the remaining strings are of the form $s =$ abababababa... Let's try to see if we can make some observations about these strings. ACTION: Let's try to calculate the number of unique substrings for a string of the form $s =$ abababababa... There are exactly $2$ unique substrings of length $1$: a and b. There are exactly $2$ unique substrings of length $2$: ab and ba. There are exactly $2$ unique substrings of length $3$: aba and bab. $\\ldots$ There are exactly $2$ unique substrings of length $n - 1$. However, the length $n$ substring occurs exactly once. OBSERVATION: The number of unique substrings of any length is $2$. But only the length $n$ substring occurs exactly once. So total number of unique substrings is $2n - 1$. And this is always odd! So there is no solution for these strings. THOUGHT: We have covered all the cases. CONCLUSION: If there are adjacent same characters, we can print it right away. If there are three consecutive different characters, we can print it right away. Otherwise there is no solution. Time Complexity: $\\mathcal{O}(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 3e5 + 9;\nusing ll = long long;\n\nvoid solve() {\n  string s; cin >> s;\n  int n = s.size();\n  for (int i = 0; i + 1 < n; i++) {\n    if (s[i] == s[i + 1]) {\n      cout << s.substr(i, 2) << '\\n';\n      return;\n    }\n  }\n  for (int i = 0; i + 2 < n; i++) {\n    if (s[i] != s[i + 1] and s[i] != s[i + 2] and s[i + 1] != s[i + 2]) {\n      cout << s.substr(i, 3) << '\\n';\n      return;\n    }\n  }\n  cout << -1 << '\\n';\n}\n\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t = 1;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2039",
    "index": "C1",
    "title": "Shohag Loves XOR (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The differences between the two versions are highlighted in bold. You can only make hacks if both versions of the problem are solved.}\n\nShohag has two integers $x$ and $m$. Help him count the number of integers $1 \\le y \\le m$ such that $\\mathbf{x \\neq y}$ and $x \\oplus y$ is \\textbf{a divisor$^{\\text{∗}}$ of} either $x$, $y$, or both. Here $\\oplus$ is the bitwise XOR operator.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The number $b$ is a divisor of the number $a$ if there exists an integer $c$ such that $a = b \\cdot c$.\n\\end{footnotesize}",
    "tutorial": "THOUGHT: Here $x > 0$ and $y > 0$. So $x \\oplus y$ is neither equal to $x$ nor $y$. So $x \\oplus y$ is a divisor of $x$ or $y$ and $x \\oplus y < x$ or $x \\oplus y < y$. OBSERVATION: Any divisor $d$ of $p$ such that $d < p$ we know that $d \\le \\lfloor \\frac{p}{2} \\rfloor$. Also, the highest bits of $d$ and $p$ are different when $d \\le \\lfloor \\frac{p}{2} \\rfloor$. THOUGHT: Wait but $x \\oplus y$ has the same highest bit as $y$ if $y \\ge 2 \\cdot x$. CONCLUSION: So if $y \\ge 2 \\cdot x$, then $x \\oplus y$ can not be a divisor of $y$. THOUGHT: But can it be a divisor of $x$? OBSERVATION: If $y \\ge 2 \\cdot x$, then $x \\oplus y > x$ because the highest bit in $x \\oplus y$ is greater than that in $x$. So $x \\oplus y$ can not be a divisor of $x$. CONCLUSION: If $y \\ge 2 \\cdot x$, then $x \\oplus y$ can not be a divisor of $x$ or $y$. So no solution in this case. THOUGHT: Now we need to consider the case when $y < 2 \\cdot x$. But $x$ is small in this problem, making it feasible to iterate over all possible values of $y$. ACTION: Iterate over all possible values of $y < 2 \\cdot x$ and check if $x \\oplus y$ is a divisor of either $x$ or $y$. Time Complexity: $\\mathcal{O}(x)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nvoid solve() {\n  int x; ll m; cin >> x >> m;\n\n  int ans = 0;\n  for (int y = 1; y <= min(2LL * x, m); y++) {\n    if (x != y and ((x % (x ^ y)) == 0 or (y % (x ^ y) == 0))) {\n      ++ans;\n    }\n  }\n  cout << ans << '\\n';\n}\n\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t = 1;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2039",
    "index": "C2",
    "title": "Shohag Loves XOR (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The differences between the two versions are highlighted in bold. You can only make hacks if both versions of the problem are solved.}\n\nShohag has two integers $x$ and $m$. Help him count the number of integers $1 \\le y \\le m$ such that $x \\oplus y$ is \\textbf{divisible$^{\\text{∗}}$ by} either $x$, $y$, or both. Here $\\oplus$ is the bitwise XOR operator.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The number $a$ is divisible by the number $b$ if there exists an integer $c$ such that $a = b \\cdot c$.\n\\end{footnotesize}",
    "tutorial": "THOUGHT: Consider the three cases of when $x \\oplus y$ is divisible by $x$, $y$, or both separately. Case 1: $x \\oplus y$ is divisible by $x$. THOUGHT: Let $p = x \\oplus y$. So $y = p \\oplus x$. So we can rephrase the problem as counting the number of integers $p$ such that $p$ is divisible by $x$ and $1 \\le p \\oplus x \\le m$. OBSERVATION: $p \\oplus x \\le p + x$, because xor is just addition without carry. THOUGHT: So it feels like almost all values of $p \\le m$ might work! And it's actually true because $p \\oplus x \\le p + x \\le m$, so if $p + x \\le m$ i.e. $p \\le m - x$ then $p \\oplus x \\le m$ is always true. CONCLUSION: All multiples of $x$ under $m - x$ always work! So the count is $\\lfloor \\frac{m - x}{x} \\rfloor$. THOUGHT: But how about when $p > m - x$? OBSERVATION: if $p > x$, then $p \\oplus x \\ge p - x$, because xor is like subtraction without borrowing. THOUGHT: So if $p - x > m$ i.e. $p > m + x$ then $p \\oplus x \\ge p - x > m$ is always true. CONCLUSION: So no values of $p$ work when $p > m + x$. THOUGHT: And there are two multiples of $x$ in the range $(m - x, m + x]$. So we can just check them manually. CONCLUSION: Answer is $\\lfloor \\frac{m - x}{x} \\rfloor$ plus manually checking the two multiples of $x$ in the range $(m - x, m + x]$. Case 2: $x \\oplus y$ is divisible by $y$. THOUGHT: As we already know that $x \\oplus y \\le x + y$, and when $x < y$, $x \\oplus y \\le x + y < y + y = 2 \\cdot y$. But as $x > 0$ and $y > 0$, so $x \\oplus y$ is neither $x$ nor $y$, so the smallest multiple of $y$ that can work is $2 \\cdot y$. But $x \\oplus y < 2 \\cdot y$, so no solution here. CONCLUSION: No solution when $x < y$. And as $x$ is small in this problem, so we can just iterate over all values of $y \\le x$ and manually check if $x \\oplus y$ is divisible by $y$. Case 3: $x \\oplus y$ is divisible by both $x$ and $y$. THOUGHT: So the xor is divisible by $\\text{lcm}(x, y)$. So when $x \\neq y$, $\\text{lcm}(x, y) \\ge 2 \\cdot \\max(x, y)$ but $x \\oplus y < 2 \\cdot \\max(x, y)$, so no solution here. CONCLUSION: Only works when $y = x$. FINAL CONCLUSION: So we just implement the above cases and the answer is the sum of case $1$ and case $2$ subtracted by case $3$. Time Complexity: $\\mathcal{O}(x)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nusing ll = long long;\n\nvoid solve() {\n  int x; ll m; cin >> x >> m;\n\n  // divisible by x\n  ll p = m - m % x;\n  ll ans = p / x - (x < p);\n  if ((x ^ p) >= 1 and (x ^ p) <= m) ++ans;\n  p += x;\n  if ((x ^ p) >= 1 and (x ^ p) <= m) ++ans;\n\n  // divisibly by y\n  for (int y = 1; y <= min(1LL * x, m); y++) {\n    ll cur = x ^ y;\n    if (cur % y == 0) {\n      ++ans;\n    }\n  }\n\n  // divisible by both\n  if (x <= m) {\n    --ans;\n  }\n\n  cout << ans << '\\n';\n}\n\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t = 1;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2039",
    "index": "D",
    "title": "Shohag Loves GCD",
    "statement": "Shohag has an integer $n$ and a set $S$ of $m$ unique integers. Help him find the lexicographically largest$^{\\text{∗}}$ integer array $a_1, a_2, \\ldots, a_n$ such that $a_i \\in S$ for each $1 \\le i \\le n$ and $a_{\\operatorname{gcd}(i, j)} \\neq \\operatorname{gcd}(a_i, a_j)$$^{\\text{†}}$ is satisfied over all pairs $1 \\le i \\lt j \\le n$, or state that no such array exists.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $a$ is lexicographically larger than an array $b$ of the same length if $a \\ne b$, and in the first position where $a$ and $b$ differ, the array $a$ has a larger element than the corresponding element in $b$.\n\n$^{\\text{†}}$$\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\\end{footnotesize}",
    "tutorial": "THOUGHT: For problems where we need to construct something under some conditions, then a good idea is to first see the nature of the sequences that satisfy the conditions. And to find the properties of such sequences we can try to find some necessary conditions that must have to be met for the sequence to satisfy the conditions. ACTION: The given condition is that $a_{\\text{gcd}(i, j)} \\neq \\text{gcd}(a_i, a_j)$ all $i < j$. As the given operation is gcd on indices and values, it's hard to directly find the properties of the sequence. But what happens when $i$ divides $j$? Then $a_{\\text{gcd}(i, j)} = a_i$. So the condition becomes $a_i \\neq \\text{gcd}(a_i, a_j)$ which translates to $a_i$ can not divide $a_j$ because otherwise $\\text{gcd}(a_i, a_j) = a_i$. So we have found a necessary condition: for any pair $i < j$ where $i$ divides $j$, $a_i$ can not divide $a_j$. THOUGHT: Hmm, but is the condition sufficient? One way to check the sufficiency is to find a contradiction. ACTION: Imagine two indices $i$ and $j$ where $i$ does not divide $j$ but the condition is violated: $a_{\\text{gcd}(i, j)} = \\text{gcd}(a_i, a_j)$. Then $g = \\text{gcd}(i, j)$ is a divisor of both $i$ and $j$ and as $a_g$ divides both $a_i$ and $a_j$, so for pair $(g, i)$ we have $a_{\\text{gcd}(g, i)} = a_g$ and $\\text{gcd}(a_g, a_i) = a_g$ because $a_g$ divides $a_i$. So for this pair the condition is violated! So if the condition is violated for some pair $(i, j)$ then it is violated for the pair $(g, i)$ and $(g, j)$ as well where $g = \\text{gcd}(i, j)$. So if there is no pair $(i, j)$ where $i$ divides $j$ and the condition is violated, then all the pairs also satisfy the condition. This proves the sufficiency of the condition. THOUGHT: So we have found a necessary and sufficient condition. Now we need to construct the lexicographically largest sequence that satisfies the condition. Solution 1: Consider a multiple chain $i_1 < i_2 < \\ldots < i_k$. Such that $i_1$ divides $i_2$, $i_2$ divides $i_3$, ..., $i_{k-1}$ divides $i_k$. Then we know that we have to put distinct values for all the indices in the multiple chain otherwise one number will be divisible by another which will violate the condition. And as we are aiming for the lexicographically largest sequence, it makes sense to put the values in decreasing order in a multiple chain i.e. $a_{i_1} > a_{i_2} > \\ldots > a_{i_k}$. This way we don't have to care about the divisibility condition, as the numbers are in decreasing order. Now, we definitely will try to put the largest number possible for each index. So what is the largest number that we can put for the index $x$? Consider a directed graph where there is an edge from $i$ to $j$ if $i$ divides $j$. Then the question is what is the length of the longest path in this graph ending at $x$. You can find it using a simple DP on this directed acyclic graph in $O(n \\log n)$ time. But if you think about it, the answer is actually simple. Let $p(x)$ the number of prime factors of $x$ counted with multiplicity. Then the answer is $p(x) + 1$. For example, if $x = 2 \\cdot 3^2 \\cdot 5$, then one of the longest chains ending at $x$ is $1 \\rightarrow 2 \\rightarrow 2 \\cdot 3 \\rightarrow 2 \\cdot 3^2 \\rightarrow 2 \\cdot 3^2 \\cdot 5$ which has length $4$. We can precalculate the values $p(x)$ for all $1 \\leq x \\leq n$ in $O(n \\log n)$ time using sieve. So at index $i$ we will put the ($p(i) + 1$)-th largest number from the set $S$. And the largest value of $p(i)$ for $1 \\leq i \\leq n$ is $\\lfloor \\log_2 n \\rfloor$ for the chain $1 \\rightarrow 2 \\rightarrow 2^2 \\rightarrow \\ldots \\rightarrow 2^{\\lfloor \\log_2 n \\rfloor}$. So if $m < \\lfloor \\log_2 n \\rfloor + 1$, then we can't construct the sequence and the answer is $-1$. Otherwise set $a_i = s_{m - p(i)}$ for all $i$. Also, unless you have noticed already, the actual numbers don't matter! Time Complexity: $O(n \\log n)$ Solution 2: As we are trying to construct the lexicographically largest sequence, it's always better to take larger values first. Let $s_i$ be the $i$-th smallest number in the set $S$. So, initially set $a_1 = s_m$. Then we can't use $s_m$ for any other index as it will violate the condition. Then set $a_2 = s_{m - 1}$ (because we can't use $s_m$). Then we can't use $s_{m - 1}$ for any other index $j$ where $j$ is divisible by $2$ as it will violate the condition. Then set $a_3 = s_{m - 1}$ (because we can't use $s_{m}$). Then we can't use $s_{m - 1}$ for any other index $j$ where $j$ is divisible by $3$ as it will violate the condition. Now set $a_4 = s_{m - 2}$ (because we can't use $s_{m - 1}$ or $s_m$). Then we can't use $s_{m - 2}$ for any other index $j$ where $j$ is divisible by $4$ as it will violate the condition. Then for $a_5$ we can actually use $s_{m-1}$ as $5$ is not divisible by $2, 3,$ or $4$ so the only constraint is that $a_5 \\neq a_1$. ... Notice that this is a sieve-like process where we are using the maximum number that we can use for the current index and then we are remembering that in the multiples of the current index, the current number can't be used. We can use sets to simulate the process. So this process will always construct a valid lexicographically largest sequence. If it is not possible to construct the sequence, then the answer is $-1$. Also, if you notice the construction process carefully, the actual numbers don't matter! Time Complexity: $O(n \\log^2 n)$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 1e5 + 9;\nusing ll = long long;\n\nvector<int> d[N];\nvoid solve() {\n  int n, m; cin >> n >> m;\n  vector<int> s(m + 1);\n  for (int i = 1; i <= m; i++) {\n    cin >> s[i];\n  }\n  vector<int> a(n + 1, -1);\n  for (int i = 1; i <= n; i++) {\n    set<int> banned;\n    for (int j: d[i]) {\n      banned.insert(a[j]);\n    }\n    for (int k = m; k >= 1; k--) {\n        if (banned.find(s[k]) == banned.end()) {\n            a[i] = s[k];\n            break;\n        }\n    }\n    if (a[i] == -1) {\n        cout << -1 << '\\n';\n        return;\n    }\n  }\n  for (int i = 1; i <= n; i++) {\n    cout << a[i] << ' ';\n  }\n  cout << '\\n';\n}\n\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  for (int i = 1; i < N; i++) {\n    for (int j = i + i; j < N; j += i) {\n        d[j].push_back(i);\n    }\n  }\n  int t = 1;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2039",
    "index": "E",
    "title": "Shohag Loves Inversions",
    "statement": "Shohag has an array $a$ of integers. Initially $a = [0, 1]$. He can repeatedly perform the following operation any number of times:\n\n- Let $k$ be the number of inversions$^{\\text{∗}}$ in the current array $a$.\n- Insert $k$ at any position in $a$, including the beginning or the end.\n\nFor example, if $a = [4, 6, 2, 4]$, then the number of inversions is $k = 3$. So Shohag can obtain the following arrays after the operation: $[\\textbf{3}, 4, 6, 2, 4]$, $[4, \\textbf{3}, 6, 2, 4]$, $[4, 6, \\textbf{3}, 2, 4]$, $[4, 6, 2, \\textbf{3}, 4]$, and $[4, 6, 2, 4, \\textbf{3}]$.\n\nGiven an integer $n$, help Shohag count, modulo $998\\,244\\,353$, the number of distinct arrays of length $n$ that can be obtained after performing the operations.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The number of inversions in an array $a$ is the number of pairs of indices ($i$, $j$) such that $i < j$ and $a_i > a_j$.\n\\end{footnotesize}",
    "tutorial": "It's hard to track the array when we insert new inversions as the inversion number can quickly become very large. The key observation here is to notice what happens when the inversion count becomes more than $1$. As the initial array has only $0$ and $1$ as elements when we insert an inversion count that is more than $1$, the inversion count will be larger than any element of the array. And this gives us a way to control everything! Let $\\text{dp}_i$ be the number of final arrays of length $n$ we can get from the current array of length $i$ if the current number of inversions in it is larger than any element of the array. Let $k$ be the number of inversions in the current array and $k > \\max(a)$. Then If we insert $k$ not in the end, then the new inversion count will be more than $k$, so we get the same situation for $dp_{i+1}$ Or if we insert $k$ in the end then the number of inversions will still be $k$. So if we inserted it $j$ times in the end and once somewhere else ($i$ ways to do so) then we will get the situation for $dp_{i+j+1}$ So $\\text{dp}_i = (i \\cdot \\sum_{j > i} \\text{dp}_j) + 1$, here $1$ is added as we can end the sequence here by inserting $k$ in the end $(n - i)$ times. This can be computed with simple dp in $O(n)$ time using suffix sums. Now we just need to deal with the starting array when it starts to have more than $1$ inversion. There are $(n - 1)$ ways to finish the sequence having $\\le 1$ inversion. And they are of the form $0, 0, \\ldots, 0, [0, 1, 0], 1, \\ldots, 1, 1$ this is because we first insert $0$ at the beginning for some time and then we get $1$ inversion count when we insert $0$ at the end for the first time and then we will have to insert $1$ at the end every time after that. And to count the ways to get the starting array of length $m$ with more than $1$ inversion, we can notice that it's just the sum of ways where we insert $1$ before the first $1$ in any sequence of the form like above $0, 0, \\ldots, 0, [0, 1, 0], 1, \\ldots, 1, 1$. And if the position of the first $1$ is $j$ then we have $(j - 1)$ ways to do so. So total ways is $\\sum_{j=2}^{m - 1} (j - 1) = \\frac{(m - 2) \\cdot (m - 1)}{2} - 1$ So the answer is just $n - 1 + \\sum_{m=3}^{n} \\left( \\frac{(m - 2) \\cdot (m - 1)}{2} - 1 \\right) \\cdot \\text{dp}_m$ Time Complexity: $O(n)$ Note that there are ways to write the dp so that you don't have to handle the starting array separately. Also in this problem, we have limited the total sum of $n$ over all test cases. But there exists solutions where the solution works even without the limit but we decided to let both solutions pass. Also, I am extremely sorry that during the contest we found out that some people found the second difference/derivative of the sequence on OEIS. We searched on OEIS before but couldn't find it, otherwise we would have modified the problem. Again, sorry for this issue.",
    "code": "#include <bits/stdc++.h>\n\n#include <chrono>\nstd::mt19937 eng(std::chrono::steady_clock::now().time_since_epoch().count());\nint rnd(int l, int r) { return std::uniform_int_distribution<int>(l, r)(eng); }\n\nnamespace FastIO {\n//\tchar buf[1 << 21], *p1 = buf, *p2 = buf;\n//\t#define getchar() (p1 == p2 && (p1 = buf, p2 = (p1 + fread(buf, 1, 1 << 21, stdin))) == p1 ? EOF : *p1++)\n\ttemplate <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }\n\ttemplate <typename T> inline void write(T x) { if (!x) return; write<T>(x / 10), putchar((x % 10) ^ '0'); }\n\ttemplate <typename T> inline void print(T x) { if (x > 0) write<T>(x); else if (x < 0) putchar('-'), write<T>(-x); else putchar('0'); }\n\ttemplate <typename T> inline void print(T x, char en) { print<T>(x), putchar(en); }\n//\tinline char rChar() { char ch = getchar(); while (!isalpha(ch)) ch = getchar(); return ch; }\n}; using namespace FastIO;\n\nusing i32 = int32_t;\nusing u32 = uint32_t;\nusing u64 = uint64_t;\ntemplate <uint32_t MOD> struct mint {\n\tstatic constexpr u32 get_r() {\n\t\tu32 ret = MOD;\n\t\tfor (i32 i = 0; i < 4; ++i) ret *= 2 - MOD * ret;\n\t\treturn ret;\n\t}\n\tstatic constexpr u32 r = get_r();\n\tstatic constexpr u32 n2 = -u64(MOD) % MOD;\n\tstatic_assert(r * MOD == 1, \"invalid, r * MOD != 1\");\n\tstatic_assert(MOD < (1 << 30), \"invalid, MOD >= 2 ^ 30\");\n\tstatic_assert((MOD & 1) == 1, \"invalid, MOD % 2 == 0\");\n\tu32 a;\n\tconstexpr mint() : a(0) {}\n\tconstexpr mint(const int64_t &b) : a(reduce(u64(b % MOD + MOD) * n2)){};\n\tstatic constexpr u32 reduce(const u64 &b) { return (b + u64(u32(b) * u32(-r)) * MOD) >> 32; }\n\t constexpr mint &operator += (const mint &b) { if (i32(a += b.a - 2 * MOD) < 0) a += 2 * MOD; return *this; }\n\tconstexpr mint &operator -= (const mint &b) { if (i32(a -= b.a) < 0) a += 2 * MOD; return *this; }\n\tconstexpr mint &operator *= (const mint &b) { a = reduce(u64(a) * b.a); return *this; }\n\tconstexpr mint &operator /= (const mint &b) { *this *= b.inverse(); return *this; }\n\tconstexpr mint operator + (const mint &b) const { return mint(*this) += b; }\n\tconstexpr mint operator - (const mint &b) const { return mint(*this) -= b; }\n\tconstexpr mint operator * (const mint &b) const { return mint(*this) *= b; }\n\tconstexpr mint operator / (const mint &b) const { return mint(*this) /= b; }\n\tconstexpr bool operator == (const mint &b) const { return (a >= MOD ? a - MOD : a) == (b.a >= MOD ? b.a - MOD : b.a); }\n\tconstexpr bool operator != (const mint &b) const { return (a >= MOD ? a - MOD : a) != (b.a >= MOD ? b.a - MOD : b.a); }\n\tconstexpr mint operator-() const { return mint() - mint(*this); }\n\tconstexpr mint pow(u64 n) const { mint ret(1), mul(*this); while (n > 0) { if (n & 1) ret *= mul; mul *= mul, n >>= 1; } return ret; }\n\tconstexpr mint inverse() const { return pow(MOD - 2); }\n\tfriend std::ostream &operator<< (std::ostream &os, const mint &b) { return os << b.get(); }\n\tfriend std::istream &operator>> (std::istream &is, mint &b) { int64_t t; is >> t; b = mint<MOD>(t); return (is); }\n\tconstexpr u32 get() const { u32 ret = reduce(a); return ret >= MOD ? ret - MOD : ret; }\n\tstatic constexpr u32 get_MOD() { return MOD; }\n    explicit operator u32() const { return get(); }\n}; using modint = mint<998244353>;\n\n// Let's write some brute first\n// dp[i][j] := current length is i, current number of inversions is j (not inserted)\n// dp[i][j] -> dp[>= i + 1][[j + 1, j + i]]\n// this is true for j >= 1, so let's do something when j = 0\n// we can generate [0, (0 ... ), 1, 0] -> dp[>= 3][1]\n// this is still kinda annoying because 1 > 1 does not hold, we process it till j >= 2\n// [0, 0, ..., 0, 1, 0] -> [0, 0, ..., 0, 1, 0, 1, ..., 1]\n// after that we insert an 1 before some numbers of 0 and we get dp[i][1] -> dp[>= i + 1][[j + 1, j + i - 1]]\n// the answer is sum dp[i][j] for all 1 <= i <= n, j >= 1, plus 1 ([0, 0, 0 ... 1])\n// actually we care nothing 'bout, j so let's say f[i] = sum dp[i][j]\n// (f[i] * i - 1) -> f[i + 1], f[i + 2], ..., f[n]\n\n#define MAXN 1000001\nmodint f[MAXN];\nvoid solve() {\n\tint n = read<int>(); modint ans = 1, pre = 2;\n\tf[3] = 1;\n\tfor (int i = 4; i <= n; ++i) \n\t\tf[i] = pre + modint(1), pre += f[i] * modint(i) - modint(1);\n\tfor (int i = 3; i <= n; ++i) ans += f[i];\n\t// f[3] : [0, 1, 0]\n\t// f[4] : [0, 0, 1, 0] (+1), [0, 1, 1, 0], [1, 0, 1, 0] (dp[3][1] * 2)\n\tprint<int>(ans.get(), '\\n');\n}\n\nint main() { int T = read<int>(); while (T--) solve(); return 0; }",
    "tags": [
      "combinatorics",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2039",
    "index": "F1",
    "title": "Shohag Loves Counting (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only differences between the two versions of this problem are the constraints on $t$, $m$, and the sum of $m$. You can only make hacks if both versions of the problem are solved.}\n\nFor an integer array $a$ of length $n$, define $f(k)$ as the greatest common divisor (GCD) of the maximum values of all subarrays$^{\\text{∗}}$ of length $k$. For example, if the array is $[2, 1, 4, 6, 2]$, then $f(3) = \\operatorname{gcd}(\\operatorname{max}([2, 1, 4]), \\operatorname{max}([1, 4, 6]), \\operatorname{max}([4, 6, 2])) = \\operatorname{gcd}(4, 6, 6) = 2$.\n\nAn array is good if $f(i) \\neq f(j)$ is satisfied over all pairs $1 \\le i \\lt j \\le n$.\n\nShohag has an integer $m$. Help him count the number, modulo $998\\,244\\,353$, of non-empty good arrays of arbitrary length such that each element of the array is an integer from $1$ to $m$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $d$ is a subarray of an array $c$ if $d$ can be obtained from $c$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "Let $s_k$ be the sequence of $k$ length subarray maximums of the array. Then $s_{k + 1}$ is just the adjacent maximum sequence of $s_k$. Also, let $g_k$ be the GCD of the elements of $s_k$. Then notice that every element of $s_{k + 1}$ is also divisible by $g_k$. That is $g_k$ divides $g_{k + 1}$. For the array to be good, $g_k$ must be different for all $k$. So $g_k < g_{k + 1}$ and $g_k$ divides $g_{k + 1}$. This means if the length of the array is $n$, then $n \\le \\lfloor \\log_2 m \\rfloor + 1$. Now consider a non-decreasing sequence of integers $a$ of length $n$ such that $1 \\le a_i \\le m$ for all $i$. Then the $k$ length subarray maximums of $a$ are just the last $k$ elements of $a$. So $g_k$ is the GCD of the last $k$ elements of $a$. Then for $g_k$ to be different for all $k$, all the elements of $a$ must be distinct. So the condition for $a$ to be good is that the elements are distinct and all suffix GCDs are distinct as well. Next the question is how many permutations of this increasing sequence $a$ is good as well? To count this, lets start from $s_n$. $s_n$ is just $[a_n]$. Now consider $s_{n - 1}$. We need to put $a_{n - 1}$ in the sequence such that the adjacent maximum sequence of $s_{n-1}$ becomes $s_n$. For this we clearly have $2$ ways: $[a_{n - 1}, a_n]$ and $[a_n, a_{n - 1}]$. Now consider $s_{n - 2}$. We need to put $a_{n - 2}$ in the sequence such that the adjacent maximum sequence of $s_{n-2}$ becomes $s_{n-1}$. For this we again have $2$ ways because $a_{n - 2}$ can be inserted in $2$ places: before $a_{n - 1}$ or after $a_{n - 1}$. Similarly for all other $s_k$ we have $2$ ways to insert it: putting it before $a_{k + 1}$ or after $a_{k + 1}$. So the total number of good permutations of $a$ is $2^{n - 1}$. So our problem reduces to the following: Select a length $n$ such that $1 \\le n \\le \\lfloor \\log_2 m \\rfloor + 1$. Count the number of strictly increasing sequences of length $n$ such that all suffix GCDs are distinct. Multiply the answer by $2^{n - 1}$. Sum up the answer for all valid $n$. For a fixed $n$, let's count the number of strictly increasing sequences of length $n$ such that all suffix GCDs are distinct. Let $\\text{dp}_{i, g}$ be the number of strictly increasing sequences of length $n$ such that the starting element is $i$ and the GCD of the elements is $g$. Now iterate from $i = m$ to $1$. Then the transition is to iterate over the next suffix GCD $h$ such that $g$ divides $h$, $g < h \\le m$ and $g = \\text{gcd}(i, h)$ and then add $\\text{dp}_{*, h}$ to $\\text{dp}_{i, g}$. Here $\\text{dp}_{*, h}$ is the sum of all $\\text{dp}_{j, h}$ for all $j > i$. Another way to look at the transition is that for a fixed $i$, we iterate over all $h$ and if $\\text{gcd}(i, h) < h$, then we add $\\text{dp}_{*, h}$ to $\\text{dp}_{i, \\text{gcd}(i, h)}$. But doing everything like this would still be $O(m^2 \\log m)$ which is too slow. Notice that all $g$ are the divisors of $i$. Here the main difficulty is that we need update at the index $\\text{gcd}(i, h)$ over all $h$ but it is hard to track the exact gcd but what's easier is to track the multiple of the gcd. So for each $g$, let's say we know the sum of all $\\text{dp}_{*, h}$ over all $h$ such that $g$ divides $h$. So this sums up all $\\text{dp}_{*, h}$ such that $g$ divides $\\text{gcd}(i, h)$. Then using inclusion exclusion on the divisors of $i$ we can get the sum of all $\\text{dp}_{*, h}$ for all $h$ such that $g$ is exactly $\\text{gcd}(i, h)$. This will take $O(\\sigma(i)^2)$ time for each $i$ where $\\sigma(i)$ is the number of divisors of $i$. And once we calculate the $\\text{dp}_{i, g}$ for some $i$ and $g$, then before transitioning to $i - 1$, we can add the value of $\\text{dp}_{i, g}$ to all divisors of $g$ to get the value of $\\text{dp}_{*, h}$ faster in the future. To keep track of this, we can use a separate array. So for a fixed $n$, the time complexity is $O(\\sum_{i = 1}^{m} \\sigma(i)^2)$. And we need to do this for all $n$ from $1$ to $\\lfloor \\log_2 m \\rfloor + 1$. So the overall time complexity is $O(\\log m \\cdot \\sum_{i = 1}^{m} \\sigma(i)^2)$. We actually allowed this to pass in F1. We can make the time complexity much better with a simple modification in the dp. Note that we don't need to use the length of array in the dp state. As we need to sum up after multiplying by $2^{\\text{length of array} - 1}$ at the end, we can modify the dp to directly store the sum of $2^{\\text{length of array} - 1}$. So we can just multiply the dp by $2$ during each transition. So the time complexity becomes $O(\\sum_{i = 1}^{m} \\sigma(i)^2)$. This is very fast for F1.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nconst int N = 2e5 + 9, mod = 998244353;\nusing ll = long long;\n\nint add(int a, int b){\n\ta += b;\n\tif(a > mod) a -= mod;\n\tif(a < 0) a += mod;\n\treturn a;\n}\n\n// dp[i][j] = number of arrays where starting element is i and gcd of the array is j\nint dp[N], cur[N], uni[N];\nint sum[N];\nvector<int> d[N];\nvoid solve() {\n  int m; cin >> m;\n  for (int i = 1; i <= m; i++) {\n    dp[i] = cur[i] = 0;\n\tuni[i] = 0;\n\tsum[i] = 0;\n  }\n  int ans = 0;\n  ans = 0;\n  for (int i = m; i >= 1; i--) {\n    for (int j: d[i]) {\n      cur[j] = 0;\n    }\n\tint sz = d[i].size();\n\tfor(int idj = sz-1; idj >= 0; idj--){\n\t\tint j = d[i][idj];\n\t\tuni[j] = add(sum[j],sum[j]);\n\t\tfor(int idk = idj+1; idk < sz; idk++){\n\t\t\tint k = d[i][idk];\n\t\t\tif(k%j) continue;\n\t\t\tuni[j] = add(uni[j],-uni[k]);\n\t\t}\n\t\tcur[j] = add(uni[j], - add(dp[j],dp[j]));\n\t}\n\n    cur[i] += 1;\n\n    for (int j : d[i]) {\n\t  dp[j] = add(dp[j],cur[j]);\n\t  for(auto k : d[j]){\n\t  \tsum[k] = add(sum[k],cur[j]);\n\t  }\n\t  ans = add(ans,cur[j]);\n    }\n\t\n  }\n  cout << ans << '\\n';\n}\n\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  for (int i = 1; i < N; i++) {\n    for (int j = i; j < N; j += i) {\n      d[j].push_back(i);\n    }\n  }\n  int t = 1;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2039",
    "index": "F2",
    "title": "Shohag Loves Counting (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only differences between the two versions of this problem are the constraints on $t$, $m$, and the sum of $m$. You can only make hacks if both versions of the problem are solved.}\n\nFor an integer array $a$ of length $n$, define $f(k)$ as the greatest common divisor (GCD) of the maximum values of all subarrays$^{\\text{∗}}$ of length $k$. For example, if the array is $[2, 1, 4, 6, 2]$, then $f(3) = \\operatorname{gcd}(\\operatorname{max}([2, 1, 4]), \\operatorname{max}([1, 4, 6]), \\operatorname{max}([4, 6, 2])) = \\operatorname{gcd}(4, 6, 6) = 2$.\n\nAn array is good if $f(i) \\neq f(j)$ is satisfied over all pairs $1 \\le i \\lt j \\le n$.\n\nShohag has an integer $m$. Help him count the number, modulo $998\\,244\\,353$, of non-empty good arrays of arbitrary length such that each element of the array is an integer from $1$ to $m$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $d$ is a subarray of an array $c$ if $d$ can be obtained from $c$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "First, check the editorial of F1. Note that for F2 there is no limit on the sum of $m$, so we need to change the approach a bit. And for F2 you need to remove the length from the dp state (which I described at the end of the editorial of F1). Now instead of iterating $i$ from $m$ to $1$, we iterate from $1$ to $m$. And reformulate the dp as follows. Let's say we are building the strictly increasing sequence $a$ from left to right and we are fixing what the suffix GCD of the final array $a$ starting from each element will be. Let $\\text{dp}_{j, h}$ be the sum of $2^{\\text{length of array so far} - 1}$ for all $a$ such that we are at element $j$ and the suffix GCD of the final array $a$ starting from element $j$ is $h$. Then the transition is to iterate over the previous suffix GCD $g$ at element $i$ such that $g$ divides $h$, $g < h$ and $g = \\text{gcd}(i, h)$ and then add $\\text{dp}_{i, g}$ to $\\text{dp}_{j, h}$. Just like F1, we can speed up the transitions by tracking some prefix sums and doing inclusion-exclusion on the divisors of $i$. We can use the Mobius Inversion Formula to do it in $O(\\sum_{d | i} \\sigma(d))$. Another way to make it faster is to do SOS DP on the divisors of $i$ which will take $O(\\sigma(i) \\cdot p(i))$ where $p(i)$ is the number of unique prime factors of $i$. It is hard to describe all the little details of the implementation here, please refer to the code for more details. The overall time complexity is $O(\\sum_{i = 1}^M \\sigma(i) \\cdot p(i))$ or $O(\\sum_{i = 1}^M \\sum_{d | i} \\sigma(d))$ where $M$ is the maximum value of $m$. Both work fast enough.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int N = 1e6 + 9, mod = 998244353;\n \ninline void add(int &x, int y) {\n  x = x + y >= mod ? x + y - mod : x + y;\n}\nint spf[N];\nvoid sieve() {\n  vector<int> p;\n  for(int i = 2; i < N; i++) {\n    if (spf[i] == 0) spf[i] = i, p.push_back(i);\n    int sz = p.size();\n    for (int j = 0; j < sz && i * p[j] < N && p[j] <= spf[i]; j++) {\n      spf[i * p[j]] = p[j];\n    }\n  }\n}\nint mob[N];\nvoid mobius() {\n  mob[1] = 1;\n  for (int i = 2; i < N; i++){\n    mob[i]--;\n    for (int j = i + i; j < N; j += i) {\n      mob[j] -= mob[i];\n    }\n  }\n  for (int i = 1; i < N; i++) {\n    mob[i] = (mob[i] % mod + mod) % mod;\n  }\n}\nint c[N];\nvector<int> divs[N];\nvoid gen_divs(int n) { // not sorted\n  int id = 1, x = n;\n  divs[n][0] = 1;\n  while (n > 1) {\n    int k = spf[n];\n    int cur = 1, sz = id;\n    while (n % k == 0) {\n      cur *= k;\n      n /= k;\n      for (int i = 0; i < sz; i++) {\n        divs[x][id++] = divs[x][i] * cur;\n      }\n    }\n  }\n}\n\nvoid prec() {\n  sieve();\n  // generate divisors without using push_back as its really slow on Codeforces\n  for (int i = 1; i < N; i++) {\n    for (int j = i; j < N; j += i) {\n      c[j]++;\n    }\n    divs[i].resize(c[i]);\n    gen_divs(i);\n  }\n  mobius();\n}\nint dp[N];\nint f[N];\nint tmp[N], ans[N];\nvoid solve() {\n  for (int i = 1; i < N; i++) {\n    for (int d: divs[i]) {\n      tmp[d] = (mod - f[d]) % mod;\n      for (int c: divs[d]) {\n        add(tmp[d], dp[c]);\n      }\n      tmp[d] = (2 * tmp[d] + 1) % mod;\n    }\n\n    // apply mobius inversion formula\n    for (int d: divs[i]) {\n      for (int c: divs[d]) {\n        add(dp[d], 1LL * mob[c] * tmp[d / c] % mod);\n      }\n      add(f[d], tmp[d]);\n    }\n\n    ans[i] = ans[i - 1];\n    add(ans[i], f[i]);\n  }\n}\n \nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  prec();\n  solve();\n  int t = 1;\n  cin >> t;\n  while (t--) {\n    int m; cin >> m;\n    cout << ans[m] << '\\n';\n  }\n  return 0;\n}\n",
    "tags": [
      "dp",
      "number theory"
    ],
    "rating": 3200
  },
  {
    "contest_id": "2039",
    "index": "G",
    "title": "Shohag Loves Pebae",
    "statement": "Shohag has a tree with $n$ nodes.\n\nPebae has an integer $m$. She wants to assign each node a value — an integer from $1$ to $m$. So she asks Shohag to count the number, modulo $998\\,244\\,353$, of assignments such that following conditions are satisfied:\n\n- For each pair $1 \\le u \\lt v \\le n$, the least common multiple (LCM) of the values of the nodes in the unique simple path from $u$ to $v$ is \\textbf{not} divisible by the number of nodes in the path.\n- The greatest common divisor (GCD) of the values of all nodes from $1$ to $n$ is $1$.\n\nBut this problem is too hard for Shohag to solve. As Shohag loves Pebae, he has to solve the problem. Please save Shohag!",
    "tutorial": "Let's say we assign $a_u$ to the node $u$. Let $h_u$ be the maximum length of a simple path that passes through $u$. Then a necessary condition is that $a_u$ can not be a multiple of any number $\\le h_u$. Because if $a_u$ is a multiple of $k \\le h_u$ and $v$ is a node such that the unique simple path from $u$ to $v$ has length $k$, then the LCM of the values of the nodes from $u$ to $v$ is a multiple of $k$, which is a contradiction. The condition also means that $a_u$ can not be a multiple of any prime number $p \\le h_u$. Is this a sufficient condition? Yes, and the proof is also simple. So now the problem is to count the number of assignments such that for each node $u$, $a_u$ is not a multiple of any prime number $p \\le h_u$ and $\\text{gcd}(a_1, a_2, \\ldots, a_n) = 1$. Let $f_{w, p}$ be the count of numbers from $1$ to $w$ that are not divisible by any prime $\\le p$, $D$ be the diameter of the tree, A number $x$ is good if $x$ is not divisible by any prime $\\le D$, $\\mu(g)$ be the Mobius function, $\\pi(x)$ be the number of primes $\\le x$. Then the answer to our problem is $\\sum_{g = 1}^m \\mu(g) \\cdot [g \\text{ is good}] \\cdot \\prod_{i = 1}^n f_{\\lfloor \\frac{m}{g} \\rfloor, h_i}$. As $\\lfloor \\frac{m}{g} \\rfloor$ is a non-decreasing function and has at most $2 \\sqrt{m}$ distinct values, we can iterate over $\\lfloor \\frac{m}{g} \\rfloor$ and calculate range sums of $\\mu(g) \\cdot [g \\text{ is good}]$. For calculating prefix sums of a multiplicative function (like $\\mu(g)$), it's a standard task and can be solved using Dirichlet convolution, Min25 sieve or multiple other methods. Here, we need a slight variant of the method as we need the prefix sums of $\\mu(g) \\cdot [g \\text{ is good}]$. This can be achieved using Dirichlet convolution in $\\mathcal{O}(m^{2 / 3})$ if we just imagine the prime numbers $\\le D$ do not exist in the number system. Refer to my code for more details. But for each fixed $\\lfloor \\frac{m}{g} \\rfloor$, how do we calculate $\\prod_{i = 1}^n f_{\\lfloor \\frac{m}{g} \\rfloor, h_i}$ fast enough? Trivially doing it will make the total complexity around $\\mathcal{O}(n \\sqrt{m})$ which is too slow. The key observation is to not forget that the values of $h_i$ are not random, they are the maximum length of a simple path that passes through the node $i$. So $h_i \\ge \\lceil \\frac{D}{2} \\rceil$ for all $i$ because from each node, the endpoints of the diameter are at least $\\lceil \\frac{D}{2} \\rceil$ away. So now consider two cases: Case 1: $D > 2 \\sqrt{m}$ In this case, all $h_i \\ge \\lceil \\frac{D}{2} \\rceil \\ge \\sqrt{m}$ for all $i$. So only primes or $1$ are the good numbers. So instead of going with the mobius route, we can just directly solve it by calculating the total number of ways and subtracting the number of ways where the gcd is a prime. We can calculate the total number of ways by first calculating the number of primes $\\le m$ and then $f_{m, h_i}$ is just $\\pi(m) - \\pi(h_i) + 1$. And the number of ways where the gcd is a prime is just $1$ for all primes $> D$ and $0$ otherwise. Counting primes under $m$ is also a standard task and can be done in $\\mathcal{O}(m^{2 / 3} \\log m)$ or faster. Case 2: $D \\le 2 \\sqrt{m}$ We can convert each $h_i$ to the maximum prime $\\le h_i$ and then group $h_i$ by their values. Then the maximum number of groups will be $\\mathcal{O}(\\pi(\\sqrt{m}))$. So for each fixed $k = \\lfloor \\frac{m}{g} \\rfloor$, if the sum of the mobius function in the range $(\\lfloor \\frac{m}{k + 1} \\rfloor, \\lfloor \\frac{m}{k} \\rfloor]$ is non-zero (keep in mind that when all numbers in the range are bad numbers, then the sum will definitely be $0$), then we can calculate the product of $f_{k, h_i}$ directly. Then the upper bound of the complexity will be around $\\mathcal{O}(\\frac{m}{\\log^2 m} \\cdot \\log \\left( \\frac{n}{\\pi(\\sqrt[3]{m})} \\right))$. The proof will be added later. This works fast enough.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#include<ext/pb_ds/assoc_container.hpp>\n#include<ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\n\nstruct custom_hash {\n  static uint64_t splitmix64(uint64_t x) {\n    x += 0x9e3779b97f4a7c15;\n    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;\n    x = (x ^ (x >> 27)) * 0x94d049bb133111eb;\n    return x ^ (x >> 31);\n  }\n  size_t operator()(uint64_t x) const {\n    static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n    return splitmix64(x + FIXED_RANDOM);\n  }\n};\n\nconst int N = 1e6 + 9, T = 1e7 + 9, RT = 33333, mod = 998244353; \nusing ll = long long;\n\nint power(int n, long long k) {\n  int ans = 1 % mod;\n  while (k) {\n    if (k & 1) ans = (long long) ans * n % mod;\n    n = (long long) n * n % mod;\n    k >>= 1;\n  }\n  return ans;\n}\n\nint SQRT(int n) {\n  int x = sqrt(n);\n  while (x * x < n) ++x;\n  while (x * x > n) --x;\n  return x;\n}\n\nint spf[T], id[T], DIAMETER, mu[T];\nvector<int> primes; // 1 indexed\nint prefix_prime_count[T], prefix_sum_mu[T];\nvoid init() {\n  mu[1] = 1;\n  for(int i = 2; i < T; i++) {\n    if (spf[i] == 0) spf[i] = i, mu[i] = i <= DIAMETER ? 0 : -1, primes.push_back(i);\n    int sz = primes.size();\n    for (int j = 0; j < sz && i * primes[j] < T && primes[j] <= spf[i]; j++) {\n      spf[i * primes[j]] = primes[j];\n      if (i % primes[j] == 0) mu[i * primes[j]] = 0;\n      else mu[i * primes[j]] = mu[i] * (primes[j] <= DIAMETER ? 0 : -1);\n    }\n  }\n  primes.insert(primes.begin(), 0);\n  for (int i = 1; i < primes.size(); i++) {\n    id[primes[i]] = i;\n  }\n  for (int i = 2; i < T; i++) {\n    prefix_prime_count[i] = prefix_prime_count[i - 1] + (spf[i] == i);\n  }\n  for (int i = 1; i < T; i++) prefix_sum_mu[i] = prefix_sum_mu[i - 1] + mu[i];\n}\nint cnt[N]; // count of nodes having each diameter\nint m;\nnamespace GoodNumbers { // numbers which aren't divisible by the first k primes\n  gp_hash_table<int, int, custom_hash> mp[RT << 1];\n  int count_num(int n, int k) { // n is a floor value, returns good numbers <= n\n    if (k == 0 or n == 0) return n;\n    if (primes[k] >= n) return 1;\n    if (n < T and 1LL * primes[k] * primes[k] > n) {\n      return 1 + prefix_prime_count[n] - k;\n    }\n    if (mp[k].find(n) != mp[k].end()) return mp[k][n];\n    int ans;\n    if (1LL * primes[k] * primes[k] > n) {\n      int x = upper_bound(primes.begin(), primes.begin() + k, (int)SQRT(n)) - primes.begin() - 1;\n      ans = count_num(n, x) - (k - x);\n    }\n    else ans = count_num(n, k - 1) - count_num(n / primes[k], k - 1);\n    mp[k][n] = ans;\n    return ans;\n  }\n};\n\nvector<pair<int, int>> v;\nnamespace Dirichlet {\n  // good number = numbers that aren't divisible by any prime <= DIAMETER\n  // we will run dirichlet imagining there exists no prime <= DIAMETER\n  gp_hash_table<int, int, custom_hash> mp;\n  int p_c(int n) {\n    return n < 1 ? 0 : 1;\n  }\n  int p_g(int n) {\n    return GoodNumbers::count_num(n, v.back().first);\n  }\n  int solve (int x) { // sum of mob[i] over 1 <= i <= x and i is a good number\n    if (x < T) return prefix_sum_mu[x];\n    if (mp.find(x) != mp.end()) return mp[x];\n    int ans = 0;\n    for (int i = 2, last; i <= x; i = last + 1) {\n      last = x / (x / i);\n      ans += solve(x / i) * (p_g(last) - p_g(i - 1));\n    }\n    ans = p_c(x) - ans;\n    return mp[x] = ans;\n  }\n};\n\nint count_primes(int n) {\n  if (n < T) return prefix_prime_count[n];\n  int x = SQRT(n);\n  int k = upper_bound(primes.begin(), primes.end(), x) - primes.begin() - 1;\n  return GoodNumbers::count_num(n, k) + k - 1;\n}\n\n\n// diameter > 2 * sqrt(m)\nvoid solve_large() {\n  // only primes are good, so count total ways\n  // and subtract where gcd is prime (means all nodes have a fixed prime)\n  int total_ways = 1;\n  int primes_under_m = count_primes(m);\n  for (auto [k, c]: v) {\n    if (m <= primes[k]) break;\n    total_ways = 1LL * total_ways * power((primes_under_m - k + 1) % mod, c) % mod; // 1 or a prime > k\n  }\n  int bad_ways = (max(0, primes_under_m - v.back().first)) % mod;\n  int ans = (total_ways - bad_ways + mod) % mod;\n  cout << ans << '\\n';\n}\n\n// diameter <= 2 * sqrt(m)\nvoid solve_small() {\n  int ans = 0;\n  for (int l = 1, r; l <= m; l = r + 1) {\n    int x = m / l;\n    r = m / x;\n    int cur = ((Dirichlet::solve(r) - Dirichlet::solve(l - 1)) % mod + mod) % mod;\n    if (cur) {\n      int mul = 1;\n      for (auto [k, c]: v) {\n        if (x <= primes[k]) break;\n        mul = 1LL * mul * power(GoodNumbers::count_num(x, k) % mod, c) % mod;\n      }\n      ans += 1LL * cur * mul % mod;\n      ans %= mod;\n    }\n  }\n  cout << ans << '\\n';\n}\n\nvector<int> g[N];\nint dp[N], up[N];\nvoid dfs(int u, int p = 0) {\n  dp[u] = 0;\n  if (p) g[u].erase(find(g[u].begin(), g[u].end(), p));\n  for (auto v: g[u]) {\n    if (v ^ p) {\n      dfs(v, u);\n      dp[u] = max(dp[u], dp[v] + 1);\n    }\n  }\n}\nint pref[N], suf[N];\nvoid dfs2(int u) {\n  int sz = g[u].size();\n  for (int i = 0; i < sz; i++) {\n    int v = g[u][i];\n    pref[i] = dp[v] + 1;\n    if (i) pref[i] = max(pref[i], pref[i - 1]);\n  }\n  for (int i = sz - 1; i >= 0; i--) {\n    int v = g[u][i];\n    suf[i] = dp[v] + 1;\n    if (i + 1 < sz) suf[i] = max(suf[i], suf[i + 1]);\n  }\n  for (int i = 0; i < sz; i++) {\n    int v = g[u][i];\n    int cur = up[u];\n    if (i) cur = max(cur, pref[i - 1]);\n    if (i + 1 < sz) cur = max(cur, suf[i + 1]);\n    up[v] = cur + 1;\n  }\n  for (auto v: g[u]) {\n    dfs2(v);\n  }\n}\nint mx_d[N];\nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int n; cin >> n >> m;\n  for (int i = 1; i < n; i++) {\n    int u, v; cin >> u >> v;\n    g[u].push_back(v);\n    g[v].push_back(u);\n  }\n  dfs(1);\n  dfs2(1);\n  for (int u = 1; u <= n; u++) {\n    vector<int> vec;\n    if (u != 1) vec.push_back(up[u]);\n    for (auto v: g[u]) {\n      vec.push_back(dp[v] + 1);\n    }\n    sort(vec.rbegin(), vec.rend());\n    mx_d[u] = vec[0];\n    if (vec.size() > 1) {\n      mx_d[u] += vec[1];\n    }\n    mx_d[u] += 1;\n  }\n  for (int i = 1; i <= n; i++) {\n    cnt[mx_d[i]]++;\n    DIAMETER = max(DIAMETER, mx_d[i]);\n  }\n\n  init();\n\n  int last_prime = 0;\n  for (int i = 2; i <= DIAMETER; i++) {\n    if (spf[i] == i) last_prime = i;\n    if (cnt[i]) {\n      int k = id[last_prime];\n      if (!v.empty() and v.back().first == k) {\n        v.back().second += cnt[i];\n      } else {\n        v.push_back({k, cnt[i]});\n      }\n    }\n  }\n\n  if (DIAMETER > 2 * SQRT(m)) solve_large();\n  else solve_small();\n  return 0;\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2039",
    "index": "H1",
    "title": "Cool Swap Walk (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference is the maximum number of operations you can perform. You can only make hacks if both versions are solved.}\n\nYou are given an array $a$ of size $n$.\n\nA cool swap walk is the following process:\n\n- In an $n \\times n$ grid, we note the cells in row $i$ and column $j$ as $(i, j)$. You need to walk from $(1,1)$ to $(n,n)$, taking only steps to the right or down.\n- Formally, if you are in $(x,y)$ currently, you can step to either $(x+1,y)$ or $(x,y+1)$, but you can not step beyond the boundaries of the grid.\n- When you step in $(i,j)$, you \\textbf{must} swap $a_i$ and $a_j$ when $i \\neq j$.\n\nYou can perform at most $2n+4$ cool swap walks. Sort the array $a_1, a_2, \\ldots, a_n$ in non-decreasing order. We can show that it's always possible to do so.",
    "tutorial": "We can observe that this kind of path is imporatnt - when we are in $(x, x)$, we only perform one of the following two kind of moves: Move 1 $(x, x) \\rightarrow (x, x+1) \\rightarrow (x+1, x+1)$ This move transforms $[\\ldots,a_x, a_{x+1},\\ldots]$ into $[\\ldots,a_{x+1}, a_{x},\\ldots]$. Move 2 $(x, x) \\rightarrow (x, x+1) \\rightarrow (x, x+2) \\rightarrow (x+1, x+2) \\rightarrow (x+2, x+2)$ This move transforms $[\\ldots,a_x, a_{x+1},a_{x+2},\\ldots]$ into $[\\ldots,a_{x+2}, a_{x+1},a_{x},\\ldots]$. Summary of the path: Note the arrays before and after the path as $a$ and $a'$, respectively. We can see $a'_n=a_1$, and $[a'_1,\\ldots,a'_{n-1}]$ can be obtained from $[a_2,\\ldots,a_{n}]$ through the following transformation: Swap any two adjacent numbers of $[a_2,\\ldots,a_{n}]$, but each number can be swapped at most once. This inspires us to use Odd-Even Sort algorithm. Steps to Achieve the Sorted Array: Step $1$: Initialize $a_1 = mn$: If $a_1 \\neq mn$, where $mn$ is the minimum of the array, use the following path: $(1, 1) \\rightarrow (1, p_1) \\rightarrow (p_1, p_1) \\rightarrow (p_1, n) \\rightarrow (n, n)$ This sequence ensures that $a_1 = mn$. Then, repeat steps $2$ and $3$ until the array is sorted. Step $2$: Perform Odd-Even Sorting: Perform an Odd-Even Sort (a round of comparison) using the key path above on the subarray $a_2, \\dots, a_n$. Step $3$: Maintain the orderliness of $[a_{2}, \\dots ,a_{n}]$ while repeatedly making $a_1 = mn$: After step $2$, we want $mn$ back to the head of the array. To achieve this, perform the following operations: $(1, 1) \\rightarrow (1, n) \\rightarrow (n, n)$ This sequence transforms the array as follows: $[a_1, a_2, \\dots, a_n(a_n=mn)] \\rightarrow [a'_1, a'_2, \\dots, a'_n]=[a_n, a_{n-1}, a_1, a_2, \\dots, a_{n-2}]$ When this is performed after an odd-even sort, it ensures that: $mn$ is back to the head of the array. The subarray $a_1, \\dots, a_{n-1}$ has been cyclically shifted. Handling Continuous Cyclic Shifts in Odd-Even Sort: Even Length ($n-1$ is even): Cyclic shifting does not affect the odd-even sort. You can continue applying the sort as usual. Odd Length ($n-1$ is odd): A small modification is needed. Specifically, First compare $(a_3,a_4),(a_5,a_6),\\ldots$ instead of $(a_2,a_3),(a_4,a_5),\\ldots$ This adjustment ensures that the odd-even sort operates correctly despite the continuous cyclic shifts. Overall, we obtained a sorted array using $2n$ walks.",
    "code": "#include <map>\n#include <set>\n#include <cmath>\n#include <ctime>\n#include <queue>\n#include <stack>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n#include <iostream>\n#include <bitset>\nusing namespace std;\ntypedef double db;\ntypedef long long ll;\ntypedef unsigned long long ull;\nconst int N=2010;\nint T,n,mn,tot;\nint a[N];\nvector<int> X[N],Y[N];\n\nvoid path1(int num) //(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->...\n{\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tX[num].push_back(i),Y[num].push_back(i);\n\t\tif(i!=n)\n\t\t{\n\t\t\tX[num].push_back(i),Y[num].push_back(i+1);\n\t\t\tswap(a[i],a[i+1]);\n\t\t}\n\t}\n}\n\nvoid path2(int num) //(1,1)->(1,n)->(n,n)\n{\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tX[num].push_back(1),Y[num].push_back(i);\n\t\tswap(a[1],a[i]);\n\t}\n\tfor(int i=2;i<=n;i++)\n\t{\n\t\tX[num].push_back(i),Y[num].push_back(n);\n\t\tswap(a[i],a[n]);\n\t}\n}\n\nvoid walk1(int j)\n{\n\tX[tot].push_back(j-1),Y[tot].push_back(j);\n\tX[tot].push_back(j-1),Y[tot].push_back(j+1);\n    X[tot].push_back(j),Y[tot].push_back(j+1);\n\tX[tot].push_back(j+1),Y[tot].push_back(j+1);\n    swap(a[j-1],a[j+1]);\n}\n\nvoid walk2(int j)\n{\n\tX[tot].push_back(j-1),Y[tot].push_back(j);\n\tX[tot].push_back(j),Y[tot].push_back(j);\n\tX[tot].push_back(j),Y[tot].push_back(j+1);\n\tX[tot].push_back(j+1),Y[tot].push_back(j+1);\n\tswap(a[j-1],a[j]);\n\tswap(a[j],a[j+1]);\n}\n\nint main()\n{\n\tscanf(\"%d\",&T);\n\twhile(T--)\n\t{\n\t\tscanf(\"%d\",&n);\n\t\tfor(int i=1;i<=n;i++) scanf(\"%d\",&a[i]);\n\t\tmn=n;tot=0;\n\t\tfor(int i=1;i<=n;i++)   mn=min(mn,a[i]);\n\t\tfor(int i=1;i<=3*n;i++) X[i].clear(),Y[i].clear();\n\t\tint p1;\n\t\tfor(int i=1;i<=n;i++) if(a[i]==mn) p1=i;\n\t\tif(p1!=1)\n\t\t{\n\t\t    tot++;\n\t\t    for(int i=1;i<=p1;i++) X[tot].push_back(1),Y[tot].push_back(i),swap(a[1],a[i]);\n\t\t    for(int i=2;i<=p1;i++) X[tot].push_back(i),Y[tot].push_back(p1),swap(a[i],a[p1]);\n\t\t    for(int i=p1+1;i<=n;i++) X[tot].push_back(p1),Y[tot].push_back(i),swap(a[p1],a[i]);\n\t\t    for(int i=p1+1;i<=n;i++) X[tot].push_back(i),Y[tot].push_back(n),swap(a[i],a[n]);\n\t\t}\n\t\tfor(int i=2;i<=n;i++)\n\t\t{\n\t\t\ttot++;\n\t\t\tX[tot].push_back(1),Y[tot].push_back(1);\n\t\t\tif(n&1)\n\t\t\t{\n\t\t\t\tif(i&1)\n\t\t\t\t{\n\t\t\t\t\tfor(int j=2;j<=n;j+=2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(j+1==i) walk2(j);\n\t\t\t\t\t\telse if(a[j]>a[j+1]) walk1(j);\n\t\t\t\t\t\telse walk2(j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor(int j=2;j<=n;j+=2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(a[j]>a[j+1]) walk1(j);\n\t\t\t\t\t\telse walk2(j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(i&1)\n\t\t\t\t{\n\t\t\t\t\tfor(int j=2;j<=n;j+=2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(j==i-1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tX[tot].push_back(j-1),Y[tot].push_back(j);\n\t\t\t\t\t\t\tX[tot].push_back(j),Y[tot].push_back(j);\n\t\t\t\t\t\t\tswap(a[j-1],a[j]);\n\t\t\t\t\t\t\tj--;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(a[j]>a[j+1]) walk1(j);\n\t\t\t\t\t\telse walk2(j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor(int j=2;j<=n;j+=2)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(j==i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tX[tot].push_back(j-1),Y[tot].push_back(j);\n\t\t\t\t\t\t\tX[tot].push_back(j),Y[tot].push_back(j);\n\t\t\t\t\t\t\tswap(a[j-1],a[j]);\n\t\t\t\t\t\t\tj--;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(a[j]>a[j+1]) walk1(j);\n\t\t\t\t\t\telse walk2(j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tpath2(++tot);\n\t\t}\n\t\tprintf(\"%d\\n\",tot);\n\t\tfor(int i=1;i<=tot;i++)\n\t\t{\n\t\t\tfor(int j=1;j<2*n-1;j++)\n\t\t\t{\n\t\t\t    if(X[i][j]==X[i][j-1]) printf(\"R\");\n\t\t\t    else printf(\"D\");\n\t\t\t}\n\t\t\tprintf(\"\\n\");\n\t\t}\n\n\t}\n\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2039",
    "index": "H2",
    "title": "Cool Swap Walk (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is the maximum number of operations you can perform. You can only make hacks if both versions are solved.}\n\nYou are given an array $a$ of size $n$.\n\nA cool swap walk is the following process:\n\n- In an $n \\times n$ grid, we note the cells in row $i$ and column $j$ as $(i, j)$. You need to walk from $(1,1)$ to $(n,n)$, taking only steps to the right or down.\n- Formally, if you are in $(x,y)$ currently, you can step to either $(x+1,y)$ or $(x,y+1)$, but you can not step beyond the boundaries of the grid.\n- When you step in $(i,j)$, you \\textbf{must} swap $a_i$ and $a_j$ when $i \\neq j$.\n\nYou can perform at most $n+4$ cool swap walks. Sort the array $a_1, a_2, \\ldots, a_n$ in non-decreasing order. We can show that it's always possible to do so.",
    "tutorial": "First, read the editorial of the easy version. We can see that the bottleneck lies in the fact that after every round of odd-even sorting, we need to perform a walk operation to ensure that $a_1 = mn$. The following method can break through this bottleneck: for simplicity, let's assume $n$ is even. Define the numbers smaller than or equal to $\\frac{n}{2}$ as $S$, and the numbers bigger than $\\frac{n}{2}$ as $B$. If we have $a = [S, \\ldots, S, B, \\ldots, B]$, we can repeatedly perform key path operations to get the following sequence: $[S, \\ldots, S, B, \\ldots, B] \\to [S, \\ldots, S, B, \\ldots, B, S] \\to [S, \\ldots, S, B, \\ldots, B, S, S] \\to \\ldots \\to [B, \\ldots, B, S, \\ldots, S]$ In this process, we only perform odd-even sorting for the subarray $[B, \\ldots, B]$. $[B, \\ldots, B, S, \\ldots, S] \\to [B, \\ldots, B, S, \\ldots, S, B] \\to [B, \\ldots, B, S, \\ldots, B, B] \\to \\ldots \\to [S, \\ldots, S, B, \\ldots, B]$ In this process, we only perform odd-even sorting for the subarray $[S, \\ldots, S]$. After that, the array is sorted. Finally, the only remaining problem is how to arrange $a = [S, \\ldots, S, B, \\ldots, B]$. Assume we have $k$ positions $p_1, p_2, \\ldots, p_k$ such that $1 < p_1 < p_2 < \\ldots < p_k \\leq n$. Consider what the following operations are doing: $(1, 1) \\to (1, p_1)\\to (2, p_1) \\to (2, p_2)\\to (3, p_2) \\to \\ldots \\to (k, p_k)$ If we ignore the other numbers,these operations correspond to: $\\text{swap}(a_1, a_{p_1}), \\text{swap}(a_2, a_{p_2}), \\ldots$ Then, we can take any path from $(k, p_k)$ to $(n, n)$. At first, we perform one operation to set $a_1 = n$, then choose $\\frac{n}{2}$ positions $p_1, p_2, \\ldots, p_{\\frac{n}{2}}$ to obtain $a = [S, \\ldots, S, B, \\ldots, B]$. For $n$ being odd, we need two additional operations for some little adjustments. Overall, we obtained a sorted array using $n + 4$ walks.",
    "code": "#include <map>\n#include <set>\n#include <cmath>\n#include <ctime>\n#include <queue>\n#include <stack>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <cstring>\n#include <algorithm>\n#include <iostream>\n#include <bitset>\nusing namespace std;\ntypedef double db;\ntypedef long long ll;\ntypedef unsigned long long ull;\nconst int N=2010;\nint T,n,tot;\nint a[N];\nvector<int> X[N],Y[N];\n\nvoid path1(int num)  //(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->...\n{\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tX[num].push_back(i),Y[num].push_back(i);\n\t\tif(i!=n)\n\t\t{\n\t\t\tX[num].push_back(i),Y[num].push_back(i+1);\n\t\t\tswap(a[i],a[i+1]);\n\t\t}\n\t}\n}\n\nvoid path2(int num) //(1,1)->(1,n)->(n,n)\n{\n\tfor(int i=1;i<=n;i++)\n\t{\n\t\tX[num].push_back(1),Y[num].push_back(i);\n\t\tswap(a[1],a[i]);\n\t}\n\tfor(int i=2;i<=n;i++)\n\t{\n\t\tX[num].push_back(i),Y[num].push_back(n);\n\t\tswap(a[i],a[n]);\n\t}\n}\n\nvoid path3(int num,vector<int> p) //swap(1,p[0]),(2,p[1]),... note p[0]!=1\n{\n\tfor(int i=1;i<=p[0];i++)\n\t{\n\t\tX[num].push_back(1),Y[num].push_back(i);\n\t\tswap(a[1],a[i]);\n\t}\n\tfor(int i=1;i<p.size();i++)\n\t{\n\t\tfor(int j=p[i-1];j<=p[i];j++)\n\t\t{\n\t\t\tX[num].push_back(i+1),Y[num].push_back(j);\n\t\t    swap(a[i+1],a[j]);\n\t\t}\n\t}\n\tint x=p.size(),y=p.back();\n\twhile(x!=n)\n\t{\n\t    x++;\n\t    X[num].push_back(x),Y[num].push_back(y);\n\t\tswap(a[x],a[y]);\n\t}\n\twhile(y!=n)\n\t{\n\t    y++;\n\t    X[num].push_back(x),Y[num].push_back(y);\n\t\tswap(a[x],a[y]);\n\t}\n}\n\nvoid walk1(int j)\n{\n\tX[tot].push_back(j-1),Y[tot].push_back(j);\n\tX[tot].push_back(j-1),Y[tot].push_back(j+1);\n    X[tot].push_back(j),Y[tot].push_back(j+1);\n\tX[tot].push_back(j+1),Y[tot].push_back(j+1);\n    swap(a[j-1],a[j+1]);\n}\n\nvoid walk2(int j)\n{\n\tX[tot].push_back(j-1),Y[tot].push_back(j);\n\tX[tot].push_back(j),Y[tot].push_back(j);\n\tX[tot].push_back(j),Y[tot].push_back(j+1);\n\tX[tot].push_back(j+1),Y[tot].push_back(j+1);\n\tswap(a[j-1],a[j]);\n\tswap(a[j],a[j+1]);\n}\n\nvoid walk3(int j)\n{\n\tX[tot].push_back(j-1),Y[tot].push_back(j);\n\tX[tot].push_back(j),Y[tot].push_back(j);\n\tswap(a[j-1],a[j]);\n}\n\nvoid init()\n{\n\tscanf(\"%d\",&n);\n\tfor(int i=1;i<=n;i++) scanf(\"%d\",&a[i]);\n\ttot=0;\n\tfor(int i=1;i<=3*n;i++) X[i].clear(),Y[i].clear();\n\tvector<pair<int,int> > pr;\n\tfor(int i=1;i<=n;i++) pr.push_back(make_pair(a[i],i));\n\tsort(pr.begin(),pr.end());\n\tfor(int i=1;i<=n;i++) a[pr[i-1].second]=i;\n}\n\nvoid step1()\n{\n\tint p1,pn;\n\tvector<int> p;\n\tfor(int i=1;i<=n;i++) if(a[i]==1) p1=i;\n\tif(p1!=1)\n\t{\n        p.push_back(p1);\n        path3(++tot,p);\n\t}\n\tif(n==2) return ;\n\ttot++;\n\tX[tot].push_back(1),Y[tot].push_back(1);\n\tfor(int j=2;j<=n;j+=2)\n\t{\n\t    if(j+1>n) walk3(j);\n\t    else if(a[j]==n) walk1(j);\n\t\telse walk2(j);\n\t}\n\tp1=n;\n\tfor(int i=1;i<=n;i++) if(a[i]==n) pn=i;\n    p.clear();\n    p.push_back(pn);p.push_back(p1);\n    path3(++tot,p);\n    p.clear();\n    for(int i=1;i<=n;i++) if(a[i]<=(n+1)/2) p.push_back(i);\n    path3(++tot,p);\n}\n\nvoid step2()\n{\n\tint head;\n\tif(n&1)\n\t{\n\t    for(int t=1;t<=2;t++)\n\t\t{\n            head=n/2+2;\n            for(int i=1;i<=n/2+(t==1);i++)\n            {\n                tot++;\n                X[tot].push_back(1),Y[tot].push_back(1);\n                for(int j=2;j<=n;j++)\n                {\n                    if(!(head<=j&&j<=head+n/2-1)) walk3(j);\n                    else if(j==head&&(head&1)) walk3(j);\n                    else\n                    {\n                        if(!(head<=j+1&&j+1<=head+n/2-1)) walk3(j);\n                        else if(a[j]>a[j+1]) walk1(j),j++;\n                        else walk2(j),j++;\n                    }\n                }\n                head--;\n            }\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor(int t=1;t<=2;t++)\n\t\t{\n            head=n/2+1;\n            for(int i=1;i<=n/2;i++)\n            {\n                tot++;\n                X[tot].push_back(1),Y[tot].push_back(1);\n                for(int j=2;j<=n;j++)\n                {\n                    if(!(head<=j&&j<=head+n/2-1)) walk3(j);\n                    else if(j==head&&(head&1)) walk3(j);\n                    else\n                    {\n                        if(!(head<=j+1&&j+1<=head+n/2-1)) walk3(j);\n                        else if(a[j]>a[j+1]) walk1(j),j++;\n                        else walk2(j),j++;\n                    }\n                }\n                head--;\n            }\n\t\t}\n\t}\n}\n\nvoid output()\n{\n\tprintf(\"%d\\n\",tot);\n\tfor(int i=1;i<=tot;i++)\n\t{\n\t\tfor(int j=1;j<2*n-1;j++)\n\t\t{\n\t\t    if(X[i][j]==X[i][j-1]) printf(\"R\");\n\t\t    else printf(\"D\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n}\n\nint main()\n{\n\tscanf(\"%d\",&T);\n\twhile(T--)\n\t{\n\t\tinit();\n\t\tstep1();\n\t\tstep2();\n\t\toutput();\n\t}\n\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "implementation",
      "sortings"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2040",
    "index": "A",
    "title": "Game of Division",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$ of length $n$ and an integer $k$.\n\nTwo players are playing a game. The first player chooses an index $1 \\le i \\le n$. Then the second player chooses a different index $1 \\le j \\le n, i \\neq j$. The first player wins if $|a_i - a_j|$ is not divisible by $k$. Otherwise, the second player wins.\n\nWe play as the first player. Determine whether it is possible to win, and if so, which index $i$ should be chosen.\n\nThe absolute value of a number $x$ is denoted by $|x|$ and is equal to $x$ if $x \\ge 0$, and $-x$ otherwise.",
    "tutorial": "$|x - y|$ is divisible by $k$ if and only if $x \\mod k = y \\mod k$. Let's split all numbers into groups according to the value $x \\mod k$. The second player wins if he chooses a number from the same group. This means that the first player must choose the number that is the only one in its group.",
    "code": "for _ in range(int(input())):\n    n, k = map(int, input().split())\n    a = list(map(int, input().split()))\n    b = [[] for _ in range(k)]\n    for i in range(0, n):\n        x = a[i]\n        b[x % k].append(i + 1)\n    res = -1\n    for i in range(k):\n        if len(b[i]) == 1:\n            res = b[i][0]\n            break\n    if res == -1:\n        print(\"NO\")\n    else:\n        print(\"YES\\n\" + str(res))",
    "tags": [
      "games",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2040",
    "index": "B",
    "title": "Paint a Strip",
    "statement": "You have an array of \\textbf{zeros} $a_1, a_2, \\ldots, a_n$ of length $n$.\n\nYou can perform two types of operations on it:\n\n- Choose an index $i$ such that $1 \\le i \\le n$ and $a_i = 0$, and assign $1$ to $a_i$;\n- Choose a pair of indices $l$ and $r$ such that $1 \\le l \\le r \\le n$, $a_l = 1$, $a_r = 1$, $a_l + \\ldots + a_r \\ge \\lceil\\frac{r - l + 1}{2}\\rceil$, and assign $1$ to $a_i$ for all $l \\le i \\le r$.\n\nWhat is the minimum number of operations of the \\textbf{first type} needed to make all elements of the array equal to one?",
    "tutorial": "At each moment of time, the array contains a number of non-intersecting segments consisting only of ones. Using an operation of the first type can increase the number of these segments by $1$. Using an operation of the second type decreases the number of these segments by $x - 1$, where $x$ - is the number of segments that this operation covers. Therefore, the number of operations of the second type is no more than the number of operations of the first type minus $1$. The optimal strategy - is to perform one operation of the first type, and then alternate operations of the first and second types, increasing the number of ones from $x$ to $2 \\cdot (x + 1)$ on each such pair of operations. There is no point in doing more operations of the first type on the prefix of operations, since we still must cover no more than two segments of ones with operations of the second type; otherwise, we will reduce the possible number of operations of the second type. At some point in the development of this problem, the following alternative statement appeared: we need to minimize the total number of operations of both types. How to solve this problem?",
    "code": "tt = int(input())\nfor _ in range(tt):\n    n = int(input())\n    ans = 1\n    cur = 1\n    while True:\n        if cur >= n:\n            print(ans)\n            break\n        ans += 1\n        cur = cur * 2 + 2",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2040",
    "index": "C",
    "title": "Ordered Permutations",
    "statement": "Consider a permutation$^{\\text{∗}}$ $p_1, p_2, \\ldots, p_n$ of integers from $1$ to $n$. We can introduce the following sum for it$^{\\text{†}}$:\n\n$$S(p) = \\sum_{1 \\le l \\le r \\le n} \\min(p_l, p_{l + 1}, \\ldots, p_r)$$\n\nLet us consider all permutations of length $n$ with the maximum possible value of $S(p)$. Output the $k$-th of them in lexicographical$^{\\text{‡}}$order, or report that there are less than $k$ of them.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$For example:\n\n- For the permutation $[1, 2, 3]$ the value of $S(p)$ is equal to $\\min(1) + \\min(1, 2) + \\min(1, 2, 3) + \\min(2) + \\min(2, 3) + \\min(3) =$ $1 + 1 + 1 + 2 + 2 + 3 = 10$\n- For the permutation $[2, 4, 1, 3]$ the value of $S(p)$ is equal to $\\min(2) + \\min(2, 4) + \\min(2, 4, 1) + \\min(2, 4, 1, 3) \\ +$ $ \\min(4) + \\min(4, 1) + \\min(4, 1, 3) \\ +$ $\\min(1) + \\min(1, 3) \\ +$ $\\min(3) =$ $2 + 2 + 1 + 1 + 4 + 1 + 1 + 1 + 1 + 3 = 17$.\n\n$^{\\text{‡}}$An array $a$ is lexicographically smaller than an array $b$ if and only if one of the following holds:\n\n- $a$ is a prefix of $b$, but $a \\ne b$; or\n- in the first position where $a$ and $b$ differ, the array $a$ has a smaller element than the corresponding element in $b$.\n\n\\end{footnotesize}",
    "tutorial": "These permutations are generated as follows. We will greedily go through the numbers in order from $1$ to $n$, and we will put each one either in the first free cell or in the last one. For example, if we want to put $4$ in the permutation $1, 3, \\circ, \\circ, \\dots, \\circ, 2$, we can put it either in the third cell or in the second from the end. That is, the permutation first increases and then decreases. We can prove that the greedy algorithm works like this. Let us now want to put the number $i$. When we put this number, we can immediately say that the minimum on the segments, one of the ends of which is the chosen position, is equal to $i$ (we do not take into account already placed numbers smaller than $i$). The number of these segments is equal to $n - i + 1$. The answer we get is equal to the sum of this fixed number and what we get in the future. Assume we put the number $i$ not at the end of the array. Let's consider the optimal further answer: $[\\dots, x_j, \\dots] i [\\dots, x_j, \\dots]$. Now let's put $i$ at the end of the array and leave the order of the following elements unchanged. All segments whose ends lie on elements that are larger than $i$ may no longer cover the number $i$, but the sets of numbers larger than $i$ that they cover have not changed. So the answer got better. Since we choose one of the ends independently, there are $2^{n - 1}$ of such permutations, and we can find the $k$-th one using a simple loop, similar to converting a number into binary notation.",
    "code": "tt = int(input())\nfor _ in range(tt):\n    n, k = map(int, input().split())\n    a, b = [], []\n \n    if n <= 60 and (1 << (n - 1)) < k:\n        print(-1)\n        continue\n    k -= 1\n    d = []\n    while k:\n        d.append(k % 2)\n        k //= 2\n    while len(d) < n - 1:\n        d.append(0)\n \n    a, b = [], []\n    j = 1\n    for i in range(n - 2, -1, -1):\n        if d[i] == 0:\n            a.append(j)\n        else:\n            b.append(j)\n        j += 1\n \n    b.reverse()\n    print(*a, n, *b)",
    "tags": [
      "bitmasks",
      "combinatorics",
      "constructive algorithms",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2040",
    "index": "D",
    "title": "Non Prime Tree",
    "statement": "You are given a tree with $n$ vertices.\n\nYou need to construct an array $a_1, a_2, \\ldots, a_n$ of length $n$, consisting of \\textbf{unique} integers from $1$ to $2 \\cdot n$, and such that for each edge $u_i \\leftrightarrow v_i$ of the tree, the value $|a_{u_i} - a_{v_i}|$ is not a prime number.\n\nFind any array that satisfies these conditions, or report that there is no such array.",
    "tutorial": "There are many array construction tactics that can be devised here. We will show two of them. We will perform a depth-first traversal of the graph and write a number $1$ greater than the previous one in the traversal order into each subsequent vertex. If the next vertex is not a leaf, then some number has already been written into its parent, which may violate the condition \"$|a_{u_i} - a_{v_i}|$ is prime\". If the difference is even and not equal to $2$, then the condition is satisfied. Otherwise, the condition may be satisfied, but we will still achieve an even difference not equal to $2$. If the difference is odd, first add the number $1$. If the difference becomes $2$, add another $2$. It can be shown that if we added this additional $2$, then we did not add them to the previous two vertices in the traversal order. We will write the values $2, 4, 6, \\dots$ to the vertices with even depth in breadth-first order. We will write the values $n \\cdot 2, n \\cdot 2 - 2, n \\cdot 2 - 4, \\dots$ to the vertices with odd depth in breadth-first order. In such a traversal, the condition \"$|a_{u_i} - a_{v_i}|$ is prime\" can be violated only for one pair, and one of the vertices of this pair will be a leaf. We will change the value of this leaf to the value of the parent minus $1$. There are many possible solutions to this problem, and almost all testers have implemented a unique solution. There are solutions that we could not prove correct, but we could not hack them either.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nusing ll = long long;\n \nvoid dfs(int v, vector<vector<int>>& g, vector<int>& h, int p) {\n    h[v] = h[p] + 1;\n    for (int u : g[v]) {\n        if (u == p)\n            continue;\n        dfs(u, g, h, v);\n    }\n}\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int tt;\n    cin >> tt;\n    while (tt--) {\n        int n;\n        cin >> n;\n        vector<vector<int>> g(n);\n        for (int i = 0; i < n - 1; i++) {\n            int u, v;\n            cin >> u >> v;\n            u--, v--;\n            g[u].push_back(v);\n            g[v].push_back(u);\n        }\n        vector<int> h(n);\n        dfs(0, g, h, 0);\n        vector<vector<int>> hs(n + 1);\n        for (int i = 0; i < n; i++)\n            hs[h[i]].push_back(i);\n        int l = 2, r = 2 * n;\n        int cur = 0;\n        vector<int> ans(n);\n        for (int i = 1; i <= n; i++) {\n           if (cur) {\n               for (int v : hs[i]) {\n                    ans[v] = r;\n                    r -= 2;\n               }\n           } \n           else {\n               for (int v : hs[i]) {\n                    ans[v] = l;\n                    l += 2;\n               }\n           }\n           cur ^= 1;\n        }\n        bool found = false;\n        for (int i = 0; i < n; i++) {\n            for (int v : g[i]) {\n                if (h[v] < h[i])\n                    continue;\n                if (abs(ans[v] - ans[i]) == 2) {\n                    ans[v] = ans[i] - 1;\n                    found = true;\n                    break;\n                }\n            }\n            if (found)\n                break;\n        }\n        for (int i = 0; i < n; i++)\n            cout << ans[i] << ' ';\n        cout << '\\n';\n    }\n    \n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "greedy",
      "number theory",
      "trees",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2040",
    "index": "E",
    "title": "Control of Randomness",
    "statement": "You are given a tree with $n$ vertices.\n\nLet's place a robot in some vertex $v \\ne 1$, and suppose we initially have $p$ coins. Consider the following process, where in the $i$-th step (starting from $i = 1$):\n\n- If $i$ is odd, the robot moves to an adjacent vertex in the direction of vertex $1$;\n- Else, $i$ is even. You can either pay one coin (if there are some left) and then the robot moves to an adjacent vertex in the direction of vertex $1$, or not pay, and then the robot moves to an adjacent vertex chosen \\textbf{uniformly at random}.\n\nThe process stops as soon as the robot reaches vertex $1$. Let $f(v, p)$ be the minimum possible expected number of steps in the process above if we spend our coins optimally.\n\nAnswer $q$ queries, in the $i$-th of which you have to find the value of $f(v_i, p_i)$, modulo$^{\\text{∗}}$ $998\\,244\\,353$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ Formally, let $M = 998\\,244\\,353$. It can be shown that the answer can be expressed as an irreducible fraction $\\frac{p}{q}$, where $p$ and $q$ are integers and $q \\not \\equiv 0 \\pmod{M}$. Output the integer equal to $p \\cdot q^{-1} \\bmod M$. In other words, output such an integer $x$ that $0 \\le x < M$ and $x \\cdot q \\equiv p \\pmod{M}$.\n\\end{footnotesize}",
    "tutorial": "To begin with, let's solve it without queries and forced movements. Let's consider the nature of the path. The current vertex $v$ has a parent of parent $u$. Let there be an odd move now, and the robot will go to the parent of $v$. If we're lucky, it'll go to $u$. Otherwise, it will go to the brother of vertex $v$. But this won't change anything - the next step the robot will do the same thing again. For vertex $v$ and all its brothers, the answer is the same. Let $d[v]$ be the answer for vertex $v$, and let $x$ be the number of brothers of vertex $v$, including itself. Then $d[v] = 2 + \\frac{1}{d + 1} \\cdot d[u] + \\frac{d}{d + 1} \\cdot d[v]$, whence $d[v] = d[u] + 2 \\cdot (x + 1)$. We can see that our path consists of blocks of height $2$ - the robot tries to overcome the next block until it succeeds, and then proceeds to the next one. We are now ready to answer the queries. Performing an operation is essentially skipping a block - the robot will pass it on the first try, spending not $2 \\cdot (x + 1)$ actions on it, but $2$. Therefore we will delete blocks with the largest $x$ greedily. We will traverse the graph and store two sets of degrees of vertices on the path to the root - one for vertices with odd depth, and the other for vertices with even depth. We will answer requests offline. Having detected a query, we will run through the first $p$ elements of the corresponding set and subtract them. Asymptotics of the trivial implementation, in which for each query we move up to the root, is $O(n \\cdot q)$. Asymptotics of a possible offline solution, where we will maintain sets of vertices while traversing the graph, is $O(n + \\sum_i{p_i} \\cdot set)$. This problem originally had the following constraints: $1 \\le n, q \\le 2 \\cdot 10^5$ $1 \\le n, q \\le 2 \\cdot 10^5$ The sum of $p$ in all queries is not greater than $2 \\cdot 10^5$ The sum of $p$ in all queries is not greater than $2 \\cdot 10^5$ How to solve this problem? Could you solve this problem without the second constraint? However, it is not hard thanks to a recent blog.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n, q;\n    cin >> n >> q;\n    \n    vector < vector <int> > g(n);\n    for (int i = 0; i < n - 1; i++) {\n        int u, v;\n        cin >> u >> v;\n        u--, v--;\n        g[u].push_back(v);\n        g[v].push_back(u);\n    }\n    \n    vector <int> depth(n);\n    vector <int> d(n);\n    vector < vector < pair <int,int> > > qrs(n); // <p, idx>\n    vector <int> res(q);\n    \n    for (int i = 0; i < q; i++) {\n        int v, p;\n        cin >> v >> p;\n        v--;\n        qrs[v].push_back({p, i});\n    }\n    \n    multiset <int> st[2]; // store negative number to be able to use usual foreach loop\n    \n    function <void(int, int, int)> dfs = [&](int v, int p, int pp) {\n        if (depth[v] == 1) d[v] = 1;\n        if (depth[v] > 1) d[v] = d[pp] + 2 * (int)g[p].size();\n        \n        for (pair <int, int> qr : qrs[v]) {\n            int p = qr.first, idx = qr.second;\n            int ans = d[v];\n            for (int i : st[1 - depth[v] % 2]) {\n                if (p == 0) break;\n                ans -= (-i - 1) * 2;\n                p--;\n            }\n            res[idx] = ans;\n        }\n        \n        if (depth[v] != 0) st[depth[v] % 2].insert(-(int)g[v].size());\n        \n        for (int to : g[v]) {\n            if (to == p) continue;\n            depth[to] = depth[v] + 1;\n            dfs(to, v, p);\n        }\n        \n        if (depth[v] != 0) st[depth[v] % 2].erase(st[depth[v] % 2].find(-(int)g[v].size()));\n    };\n    \n    dfs(0, 0, 0);\n    \n    for (int i = 0; i < q; i++)\n        cout << res[i] << '\\n';\n}\n \nint main() {\n    int tt;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "math",
      "probabilities",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2040",
    "index": "F",
    "title": "Number of Cubes",
    "statement": "Consider a rectangular parallelepiped with sides $a$, $b$, and $c$, that consists of unit cubes of $k$ different colors. We can apply cyclic shifts to the parallelepiped in any of the three directions any number of times$^{\\text{∗}}$.\n\nThere are $d_i$ cubes of the $i$-th color ($1 \\le i \\le k$). How many different parallelepipeds (with the given sides) can be formed from these cubes, no two of which can be made equal by some combination of cyclic shifts?\n\n\\begin{footnotesize}\n$^{\\text{∗}}$On the image:\n\n- Top left shows the top view of the original parallelepiped. Lower layers will shift in the same way as the top layer.\n- Top right shows the top view of a parallelepiped shifted to the right by $1$.\n- Bottom left shows the top view of a parallelepiped shifted down by $2$.\n- Bottom right shows the top view of a parallelepiped shifted to the right by $1$ and down by $2$.\n\n\\end{footnotesize}",
    "tutorial": "Recall Burnside's lemma - the number of elements up to an action group is: $\\frac{1}{|G|} \\cdot \\sum_{g \\in G} {\\sum_{x \\in X}{[g x = x]}}$ , where $[x] = 1$ if $x = true$ and $[x] = 0$ if $x = false$. Let's try to iterate over the elements of the action group - all triplets of numbers $[0, a)$, $[0, b)$, $[0, c)$. When applying a fixed action $(i, j, l)$, the element moves to this vector. Let's choose a cell and add a vector to it until we reach it again. We have drawn a cycle - all cells on it must be of the same type. An example of such a traversal for $(a, b, c) = (9, 4, 1)$, $(i, j, k) = (3, 2, 0)$ (each different number in the table corresponds to a cycle): 123123123456456456123123123456456456 You can count the cycles by traversal, or you can derive formula: the length of all cycles is the same and equals $N = lcm(\\frac{a}{gcd(a, i)}, \\frac{b}{gcd(b, j)}, \\frac{c}{gcd(c, l)})$. What's good about the equal lengths of the cycles? Because the formula for calculating the number of stationary parallelepipeds is simple. First, all $d_i$ must be divisible by $N$. Then we distribute them among the cycles. This is the multinomial coefficient for $(\\frac{d_1}{N}, \\frac{d_2}{N}, \\dots, \\frac{d_k}{N})$. Current total time $O(a \\cdot b \\cdot c \\cdot k)$: iterated over $a \\cdot b \\cdot c$ vector triplets, calculated $N$, checked divisibility for all $k$ numbers, and if successful, calculated the multinomial coefficient of size $k$. Let's speed up the solution. Let's calculate $G = gcd(d_1, d_2, \\dots, d_k)$. Since all $d_i$ are divisible by $N$, then $G$ is also divisible by $N$. There are no more different $N$ than the number of divisors of $a \\cdot b \\cdot c$. Let's calculate the number of triplets that give each value of $N$, and at the end we will calculate the multinomial coefficient for all identical values of $N$ at once. The total time is $O(a \\cdot b \\cdot c \\cdot \\log C + d(a \\cdot b \\cdot c) \\cdot k)$, where $d(x)$ - is the number of divisors of $x$, and $\\log$ appears due to the calculation of $gcd$. Let's continue to speed up the solution. There are two solutions further. Solution 1. Let's look again at the formula $N = lcm(\\frac{a}{gcd(a, i)} \\dots)$. For convenience, we will focus on the first element. Let's say we want the first element to be $x = \\frac{a}{gcd(a, i)}$. Then $x$ is divisible by $a$ and $\\frac{a}{x} = gcd(a, i)$. $i$ is divisible by $gcd(i, \\dots)$, so $i$ is divisible by $\\frac{a}{x}$. Then the possible $i$ are of the form $p \\cdot \\frac{a}{x}$, where $1 \\le p \\le x$, and the equality $gcd(a, \\frac{a}{x}) = \\frac{a}{x}$ is exactly satisfied. $p$ is coprime to $x$, otherwise the value of $gcd$ will be multiplied by their common divisor and the equality will be violated. Therefore the number of suitable $x$ is equal to $phi(x)$, where $phi(x)$ - Euler's function. So, let's enumerate triplets of divisors of $a$, $b$ and $c$. The number of ways to obtain a triple $(x, y, z)$ is equal to $phi(x) \\cdot phi(y) \\cdot phi(z)$. Let's calculate $phi(x)$ using the Sieve of Eratosthenes. We get a solution in $O(d(a) \\cdot d(b) \\cdot d(c) \\cdot \\log C + d(a \\cdot b \\cdot c) \\cdot k)$ and $O(a \\cdot b \\cdot c \\cdot \\log \\log (a \\cdot b \\cdot c))$ for pre-calculation. Solution 2. Let's calculate the same $N$ using dynamic programming. For convenience, we denote the dimensions of $a$, $b$, and $c$ by the array $a_i$. Let $dp[i][j]$ be the number of ways, having passed $i$ dimensions, to obtain $lcm$ equal to $j$. The transitions will be as follows: we will iterate over the pairs of the previous $lcm$ $t_1$ and the next divisor $t_2$ of the size of the next dimension $a_i$. Then the new $lcm$ will be equal to $lcm(t_1, t_2)$ and we make the transition $dp[i + 1][lcm(t_1, t_2)] += dp[i][t_1] \\cdot cnt[i][t_2]$, where $cnt[i][j]$ - the number of such $x$ that $\\frac{a_i}{gcd(a_i, x)} = j$. How to calculate the array $cnt[i][j]$. We cannot calculate it trivially in $O((a + b + c) \\cdot \\log C)$, since it is too long time. For simplicity, we calculate the array $cnt2[i][j]$ equal to the number of $x$ such that $gcd(a_i, x) = j$. We iterate over the divisors of $a_i$ in ascending order. Let the current divisor be $d_1$. Add $\\frac{a_i}{d_1}$ to $cnt2[i][d_1]$, since that many $x$ will be divisible by $d_1$. Those $x$ that are divisible by $d_1$ but are not equal to it, we will subtract later. We iterate over the divisors $d_2$ of $d_1$. We subtract $cnt2[i][d_1]$ from $cnt2[i][d_2]$, since their $gcd$ is actually not $d_2$, but $d_1$ or a number that $d_1$ divides. Let's calculate $cnt[i][j] = cnt2[i][\\frac{a_i}{j}]$. If we pre-calculate the divisors of all numbers and compress their \"coordinates\", we get a solution in $O(d(a \\cdot b \\cdot c)^2 \\cdot \\log C + d(a \\cdot b \\cdot c) \\cdot k)$.",
    "code": "#include <bits/stdc++.h>\n#define int long long\n \nusing namespace std;\n \nconst int N = 3000010;\nconst int mod = 998244353;\nint fact[N], ifact[N];\nint pos[N];\n \nint powmod(int a, int n) {\n    int res = 1;\n    while (n) {\n        if (n % 2 == 0) {\n            a = (a * a) % mod;\n            n /= 2;\n        }\n        else {\n            res = (res * a) % mod;\n            n--;\n        }\n    }\n    return res;\n}\n \nint inv(int a) {\n    return powmod(a, mod - 2);\n}\n \nvoid prepare() {\n    fact[0] = 1;\n    for (int i = 1;i < N; i++) {\n        fact[i] = (fact[i - 1] * i) % mod;\n    }\n    ifact[N - 1] = inv(fact[N - 1]);\n    for (int i = N - 2; i >= 0; i--) {\n        ifact[i] = (ifact[i + 1] * (i + 1)) % mod;\n    }\n}\n \nint C(int n, int k) {\n    return ((fact[n] * ifact[k]) % mod * ifact[n - k]) % mod;\n}\n \nint MC(vector <int> &a) {\n    int sum=0;\n    for (int i : a) sum += i;\n    int res = fact[sum];\n    for (int i : a) {\n        res = (res * ifact[i]) % mod;\n    }\n    return res;\n}\n \nint lcm(int a, int b) {\n    return a / __gcd(a, b) * b;\n}\n \nvector <int> all_divs(int x) {\n    vector <int> d1, d2;\n    for (int i = 1; i * i <= x; i++) {\n        if (x % i == 0) {\n            d1.push_back(i);\n            if (i * i != x) {\n                d2.push_back(x / i);\n            }\n        }\n    }\n    reverse(d2.begin(), d2.end());\n    for (int i : d2) d1.push_back(i);\n    return d1;\n}\n \nvoid solve() {\n    int a, b, c, k;\n    cin >> a >> b >> c >> k;\n    vector <int> v(k);\n    for (int &i : v) cin >> i;\n \n    int g = v[0];\n    for (int i : v) g = __gcd(g, i);\n    vector <int> divs_g = all_divs(g);\n \n    set <int> divs;\n    for (int i : all_divs(a)) divs.insert(i);\n    for (int i : all_divs(b)) divs.insert(i);\n    for (int i : all_divs(c)) divs.insert(i);\n    for (int i : all_divs(g)) divs.insert(i);\n    int D = divs.size();\n    int i = 0;\n    for (int j : divs) {\n        pos[j] = i;\n        i++;\n    }\n \n    int n = max({a, b, c}) + 1;\n    vector < vector <int> > tmp(3, vector <int> (D));\n    vector < vector <int> > cnt(3, vector <int> (D));\n    for (int t = 0; t < 3; t++) {\n        int x;\n        if (t == 0) x = a;\n        if (t == 1) x = b;\n        if (t == 2) x = c;\n        vector <int> divs_x = all_divs(x);\n \n        for (int i = (int)divs_x.size() - 1; i >= 0; i--) {\n            tmp[t][pos[divs_x[i]]] += x / divs_x[i];\n            for (int j = 0; j < i; j++) {\n                if (divs_x[i] % divs_x[j] == 0) {\n                    tmp[t][pos[divs_x[j]]] -= tmp[t][pos[divs_x[i]]];\n                }\n            }\n            cnt[t][pos[x / divs_x[i]]] = tmp[t][pos[divs_x[i]]];\n        }\n    }\n        \n    vector < vector <int> > dp(4, vector <int> (D));\n    dp[0][0] = 1;\n    for(int i = 0; i < 3; i++) {\n        for (int t1 : divs_g) {\n            for (int t2 : divs_g) {\n                int new_pos = lcm(t1, t2);\n                if (t2 < n) {\n                    dp[i + 1][pos[new_pos]] = (dp[i + 1][pos[new_pos]] + dp[i][pos[t1]] * cnt[i][pos[t2]]) % mod;\n                }\n            }\n        }\n    }\n \n    int sum = 0;\n    i = 0;\n    for (int j : divs) {\n        if (g % j != 0) continue;\n        int N = j, cnt = dp[3][pos[j]];\n        vector <int> u;\n        for (int t : v) u.push_back(t / N);\n        sum = (sum + (MC(u) * cnt) % mod) % mod;\n    }\n \n    sum = (sum * inv(a * b * c)) % mod;\n \n    cout << sum << endl;\n}\n \nint32_t main() {\n    prepare();\n \n    int tt;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2042",
    "index": "A",
    "title": "Greedy Monocarp",
    "statement": "There are $n$ chests; the $i$-th chest initially contains $a_i$ coins. For each chest, you can choose any non-negative ($0$ or greater) number of coins to add to that chest, with one constraint: the total number of coins in all chests must become \\textbf{at least $k$}.\n\nAfter you've finished adding coins to the chests, greedy Monocarp comes, who wants the coins. He will take the chests one by one, and since he is greedy, he will always choose the chest with the maximum number of coins. Monocarp will stop as soon as the total number of coins in chests he takes is \\textbf{at least $k$}.\n\nYou want Monocarp to take as few coins as possible, so you have to add coins to the chests in such a way that, when Monocarp stops taking chests, he will have \\textbf{exactly $k$} coins. Calculate the minimum number of coins you have to add.",
    "tutorial": "Consider several first chests that Monocarp will take before exceeding the limit if we don't add any coins; so, this will be the set of several largest chests such that the sum of this set is $s \\le k$, but if the next chest is taken, the sum would exceed $k$. For this set, the minimum number of coins that should be added is $k - s$. We can add exactly that amount if we increase the maximum element, the set of chests will include exactly the same elements, but now their sum is equal to $k$. Now we have to consider the case where we add coins to some chest that is not the part of this set. Suppose Monocarp took some chest $i$, which initially had $a_i$ coins, but did not take chest $j$, such that $a_j > a_i$. In order for chest $i$ to be taken, its final value must be at least $a_j$, as Monocarp selects the maximum chest from the available ones. Let's suppose that $x$ coins were added to chest $i$, so that $a_i + x \\ge a_j$. However, instead, we could have increased chest $j$ to the value $a_i + x$, and this would require fewer coins, since $a_j > a_i$. Thus, we have shown that it is not optimal to \"change\" the order of the chests, so we can always assume that Monocarp takes several chests that were the largest in the original order.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n);\n    for (auto& x : a) cin >> x;\n    sort(a.begin(), a.end(), greater<int>());\n    int sum = 0;\n    for (auto& x : a) {\n      if (sum + x <= k) sum += x;\n      else break;\n    }\n    cout << k - sum << '\\n';\n  }\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2042",
    "index": "B",
    "title": "Game with Colored Marbles",
    "statement": "Alice and Bob play a game. There are $n$ marbles, the $i$-th of them has color $c_i$. The players take turns; Alice goes first, then Bob, then Alice again, then Bob again, and so on.\n\nDuring their turn, a player \\textbf{must} take \\textbf{one} of the remaining marbles and remove it from the game. If there are no marbles left (all $n$ marbles have been taken), the game ends.\n\nAlice's score at the end of the game is calculated as follows:\n\n- she receives $1$ point for every color $x$ such that she has taken at least one marble of that color;\n- additionally, she receives $1$ point for every color $x$ such that she has taken \\textbf{all} marbles of that color (of course, only colors present in the game are considered).\n\nFor example, suppose there are $5$ marbles, their colors are $[1, 3, 1, 3, 4]$, and the game goes as follows: Alice takes the $1$-st marble, then Bob takes the $3$-rd marble, then Alice takes the $5$-th marble, then Bob takes the $2$-nd marble, and finally, Alice takes the $4$-th marble. Then, Alice receives $4$ points: $3$ points for having at least one marble for colors $1$, $3$ and $4$, and $1$ point for having all marbles of color $4$. \\textbf{Note that this strategy is not necessarily optimal for both players}.\n\nAlice wants to maximize her score at the end of the game. Bob wants to minimize it. Both players play optimally (i. e. Alice chooses a strategy which allows her to get as many points as possible, and Bob chooses a strategy which minimizes the amount of points Alice can get).\n\nCalculate Alice's score at the end of the game.",
    "tutorial": "It's fairly intuitive that if there is at least one unique marble available (a marble is unique if there are no other marbles with the same color), taking it is optimal: if Alice takes that marble, she gets $2$ points, and if Bob takes that marble, he denies $2$ points to Alice. So, initially, both players take unique marbles one by one, until there is none left. Let's denote the number of unique marbles as $u$; then, Alice takes $\\lceil \\frac{u}{2} \\rceil$ unique marbles and gets $2$ points for each of them. After that, all remaining marbles are non-unique; for each remaining color, there are at least two marbles. Let's denote the number of remaining colors as $k$. We can show that Alice can get $k$ more points no matter how Bob plays, but she can't get more points if Bob plays optimally. There exists a symmetric strategy for each player: if during the previous turn, your opponent took the first marble of some color, respond by taking a marble of the same color; otherwise, play any legal move. This symmetric strategy ensures that Alice gets exactly $1$ point for each remaining color, since each color will be shared between two players. So, Alice can always achieve $k$ points, and Bob can make sure she doesn't get more than $k$. So, to solve this problem, you need to calculate the number of marbles for each color. Then, let the number of colors with exactly one marble be $u$, and the number of colors with more than $1$ marble be $k$. Alice's score will be $2 \\cdot \\lceil \\frac{u}{2} \\rceil + k$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    int t;\n    scanf(\"%d\", &t);\n    for(int _ = 0; _ < t; _++)\n    {\n        int n;\n        scanf(\"%d\", &n);\n        vector<int> c(n);\n        for(int i = 0; i < n; i++)\n        {\n            scanf(\"%d\", &c[i]);\n            --c[i];\n        }\n        vector<int> cnt(n);\n        for(auto x : c) cnt[x]++;\n        int exactly1 = 0, morethan1 = 0;\n        for(auto x : cnt)\n            if (x == 1)\n                exactly1++;\n            else if(x > 1)\n                morethan1++;\n        printf(\"%d\\n\", morethan1 + (exactly1 + 1) / 2 * 2);\n    }\n}",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "2042",
    "index": "C",
    "title": "Competitive Fishing",
    "statement": "Alice and Bob participate in a fishing contest! In total, they caught $n$ fishes, numbered from $1$ to $n$ (the bigger the fish, the greater its index). Some of these fishes were caught by Alice, others — by Bob.\n\nTheir performance will be evaluated as follows. First, an integer $m$ will be chosen, and all fish will be split into $m$ \\textbf{non-empty} groups. The first group should contain several (at least one) smallest fishes, the second group — several (at least one) next smallest fishes, and so on. Each fish should belong to exactly one group, and each group should be a contiguous subsegment of fishes. Note that the groups are numbered in exactly that order; for example, the fishes from the second group cannot be smaller than the fishes from the first group, since the first group contains the smallest fishes.\n\nThen, each fish will be assigned a value according to its group index: each fish in the first group gets value equal to $0$, each fish in the second group gets value equal to $1$, and so on. So, each fish in the $i$-th group gets value equal to $(i-1)$.\n\nThe score of each contestant is simply the total value of all fishes that contestant caught.\n\nYou want Bob's score to exceed Alice's score by \\textbf{at least} $k$ points. What is the minimum number of groups ($m$) you have to split the fishes into? If it is impossible, you should report that.",
    "tutorial": "The main idea we need to solve this problem is the following one. For each fish, its value will be equal to the number of groups before its group. So, each \"border\" between two groups increases the value of every fish after the border by $1$. Let $s_i$ be the number of Bob's fishes minus the number of Alice's fishes among the fishes with indices $i, i+1, \\dots, n-1, n$; also, let $a_j$ be the index of the fish from which the $j$-th group starts. Then the difference in scores between Bob and Alice is equal to $0 \\cdot (s_{a_1} - s_{a_2}) + 1 \\cdot (s_{a_2} - s_{a_3}) + \\cdots + (m - 1) \\cdot s_{a_m}$, where $m$ is the number of groups. This sum can be rewritten as: $0 \\cdot s_{a_1} + (2 - 1) \\cdot s_{a_2} + (3 - 2) \\cdot s_{a_3} + \\cdots + s_{a_m}$. So, $s_i$ denotes how the difference between Bob's score and Alice's score changes if we split the $i$-th fish and the $(i-1)$-th fish into different groups. From this, it is clear that the final score is the sum of certain elements of the array $s$. Since we have to minimize the number of groups (the number of selected elements from the array $s$), it is optimal to choose the maximum elements. So, the solution is the following: construct the array $s$, sort it, and take the next maximum element until the sum is less than $k$. The answer to the problem is the number of selected elements plus $1$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    string s;\n    cin >> n >> k >> s;\n    vector<int> vals;\n    int sum = 0;\n    for (int i = n - 1; i > 0; --i) {\n      sum += (s[i] == '1' ? 1 : -1);\n      if (sum > 0) vals.push_back(sum);\n    }\n    sort(vals.begin(), vals.end());\n    int ans = 1;\n    while (k > 0 && !vals.empty()) {\n      k -= vals.back();\n      vals.pop_back();\n      ++ans;\n    }\n    cout << (k > 0 ? -1 : ans) << '\\n';\n  }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2042",
    "index": "D",
    "title": "Recommendations",
    "statement": "Suppose you are working in some audio streaming service. The service has $n$ active users and $10^9$ tracks users can listen to. Users can like tracks and, based on likes, the service should recommend them new tracks.\n\nTracks are numbered from $1$ to $10^9$. It turned out that tracks the $i$-th user likes form a segment $[l_i, r_i]$.\n\nLet's say that the user $j$ is a predictor for user $i$ ($j \\neq i$) if user $j$ likes all tracks the $i$-th user likes (and, possibly, some other tracks too).\n\nAlso, let's say that a track is strongly recommended for user $i$ if the track is not liked by the $i$-th user yet, but it is liked by \\textbf{every} predictor for the $i$-th user.\n\nCalculate the number of strongly recommended tracks for each user $i$. If a user doesn't have any predictors, then print $0$ for that user.",
    "tutorial": "Firstly, if several segments are equal, then the answer for all of them is zero. Now let's move to the problem where all segments are distinct. User $j$ is a predictor for user $i$ iff $l_j \\le l_i \\le r_i \\le r_j$. Also, a track is strongly recommended if it is in all predictor segments, i. e. the track belongs to the intersection $[L, R]$ of all predictors. Since the segment $[l_i, r_i]$ also belongs to $[L, R]$, then the tracks we need to find form two intervals $[L, l_i)$ and $(r_i, R]$. Let's focus on finding interval $(r_i, R]$. Since the right border of the intersection is the minimum among right borders, then our task is to find the minimum among $r_j$-s such that $r_j \\ge r_i$ while $l_j \\le l_i$. Let's do it in the following way: let's sort all segments by $l_i$ in increasing order; in case of equal $l_i$-s, sort them by $r_i$ in decreasing order. If we process segments in the given order, then by the moment we process the $i$-th segment, all its predictors will be already processed. Let's keep $r_i$-s of all processed segments so far in an \"ordered set\" $S$ (std::set, for example). Suppose we process segment $i$. Since the right borders of all predictors are already in $S$ and their $r_j \\ge r_i$, then finding the minimum among them is equivalent to just taking $R = S.\\mathrm{lower\\_bound}(r_i)$. Then we can add $R - r_i$ to the answer for the $i$-th segment. In order to calculate intervals $[L, l_i)$ we can just reflect all segments and solve the same problem. The complexity of the solution is $O(n \\log{n})$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nstruct Seg {\n\tint l, r;\n\n\tbool operator< (const Seg &oth) const {\n\t\tif (l != oth.l)\n\t\t\treturn l < oth.l;\n\t\treturn r < oth.r;\n\t};\n};\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<Seg> seg(n);\n\tfor (int i = 0; i < n; i++)\n\t\tcin >> seg[i].l >> seg[i].r;\n\t\n\tvector<int> ans(n, 0);\n\tfor (int k = 0; k < 2; k++) {\n\t\tvector<int> ord(n);\n\t\tiota(ord.begin(), ord.end(), 0);\n\n\t\tsort(ord.begin(), ord.end(), [&seg](int i, int j){\n\t\t\tif (seg[i].l != seg[j].l)\n\t\t\t\treturn seg[i].l < seg[j].l;\n\t\t\treturn seg[i].r > seg[j].r;\n\t\t});\n\n\t\tset<int> bounds;\n\t\tfor (int i : ord) {\n\t\t\tauto it = bounds.lower_bound(seg[i].r);\n\t\t\tif (it != bounds.end())\n\t\t\t\tans[i] += *it - seg[i].r;\n\t\t\tbounds.insert(seg[i].r);\n\t\t}\n\n\t\tfor (auto &s : seg) {\n\t\t\ts.l = -s.l;\n\t\t\ts.r = -s.r;\n\t\t\tswap(s.l, s.r);\n\t\t}\n\t}\n\n\tmap<Seg, int> cnt;\n\tfor (auto s: seg)\n\t\tcnt[s]++;\n\tfor (int i = 0; i < n; i++)\n\t\tif (cnt[seg[i]] > 1)\n\t\t\tans[i] = 0;\n\t\n\tfor (int a : ans)\n\t\tcout << a << '\\n';\n}\n\nint main() {\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\t\n\tint t; cin >> t;\n\twhile (t--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2042",
    "index": "E",
    "title": "Vertex Pairs",
    "statement": "You are given a tree consisting of $2n$ vertices. Recall that a tree is a connected undirected graph with no cycles. Each vertex has an integer from $1$ to $n$ written on it. Each value from $1$ to $n$ is written on \\textbf{exactly two} different vertices. Each vertex also has a cost —vertex $i$ costs $2^i$.\n\nYou need to choose a subset of vertices of the tree such that:\n\n- the subset is connected; that is, from each vertex in the subset, you can reach every other vertex in the subset by passing only through the vertices in the subset;\n- each value from $1$ to $n$ is written on at least one vertex in the subset.\n\nAmong all such subsets, you need to find the one with the smallest total cost of the vertices in it. Note that you are not required to minimize the number of vertices in the subset.",
    "tutorial": "Note that the cost function of a subset actually states the following: you are asked to choose the minimum lexicographic subset if the vertices are ordered in descending order. This can be shown by looking at the binary representations of the subset costs. Intuitively, we want to implement the following process. Iterate over the vertices in descending order and check whether we have to take the current vertex in the subset, or we can skip it. If we can, we skip it; otherwise, we take it. How to write this checking function? I think that it is easier to do this if we root the tree by a vertex that will definitely be in the answer. Finding such a vertex is easy - out of two vertices with the value $1$, at least one will definitely be in the answer. Iterate over it and take the best answer from the two options. We can compare the answers by their by binary representations. In the rooted tree, where the root is always taken, it is easier to check connectivity. If a vertex is taken in the subset, then its parent must also be taken. Otherwise, the subset will definitely be disconnected. A vertex must be taken in the subset if there is a value such that both vertices with this value are in its subtree. However, sometimes it happens that one of the two vertices with some value has already been prohibited from being taken. In this case, for this value, we need to check that only the non-prohibited vertex is in the subtree. Let's maintain the state of each vertex: the vertex must be taken in the subset; the vertex must not be taken in the subset; it has not been determined whether to take the vertex or not. Initially, we know that for each value, we must take the vertices that are on both paths from the vertices with this value to the root. So, on the path from their LCA (lowest common ancestor) to the root. If at least one such vertex is not taken, then that value will not appear in the subset. A vertex can be skipped if its state is not determined. When we decide not to take a vertex, the following happens. The vertices in its subtree must also not be taken. And if for some vertex it is marked that it must not be taken in the subset, then another vertex with the same value must now be taken. We will write two auxiliary functions. The first function marks the state as \"must take\". So, it takes a vertex $v$ and jumps over the parents of vertex $v$ until it either reaches the root or an already marked vertex. In total, this function will make $O(n)$ iterations, as with each successful iteration of the loop, another vertex gets marked. The second function marks the state as \"must not take\". That is, it takes a vertex $v$ and traverses the subtree of vertex $v$, marking all descendants as \"must not take\". I chose to implement this function using a breadth-first search. Again, we can stop the traversal when we see that a vertex is already marked as \"must not take\". In total, there will also be $O(n)$ iterations. When we mark a vertex, we call the first function from another vertex with its value. Overall complexity: $O(n \\log n)$ (where everything except LCA works in $O(n)$).",
    "code": "#include <bits/stdc++.h>\n \n#define forn(i, n) for (int i = 0; i < int(n); i++)\n \nusing namespace std;\n \nvector<vector<int>> g;\n \nstruct LCA {\n\tvector<vector<pair<int, int>>> st;\n\tvector<int> pw;\n \n\tvoid build(vector<pair<int, int>> a) {\n\t\tint n = a.size();\n\t\tint lg = 32 - __builtin_clz(n);\n\t\tst.resize(lg, vector<pair<int, int>>(n));\n\t\tst[0] = a;\n\t\tfor (int j = 1; j < lg; ++j) {\n\t\t\tfor (int i = 0; i < n; ++i) {\n\t\t\t\tst[j][i] = st[j - 1][i];\n\t\t\t\tif (i + (1 << (j - 1)) < n)\n\t\t\t\t\tst[j][i] = min(st[j][i], st[j - 1][i + (1 << (j - 1))]);\n\t\t\t}\n\t\t}\n\t\tpw.resize(n + 1);\n\t\tfor (int i = 2; i <= n; ++i)\n\t\t\tpw[i] = pw[i / 2] + 1;\n\t}\n \n\tvector<int> d, fst, par;\n\tvector<pair<int, int>> ord;\n \n\tint lca(int v, int u) {\n\t\tint l = fst[v], r = fst[u];\n\t\tif (l > r) swap(l, r);\n\t\t++r;\n\t\tint len = pw[r - l];\n\t\tassert(len < int(st.size()));\n\t\treturn min(st[len][l], st[len][r - (1 << len)]).second;\n\t}\n \n\tvoid init(int v, int p = -1) {\n\t\tif (fst[v] == -1) fst[v] = ord.size();\n\t\tord.push_back({ d[v], v });\n\t\tfor (int u : g[v]) if (u != p) {\n\t\t\tpar[u] = v;\n\t\t\td[u] = d[v] + 1;\n\t\t\tinit(u, v);\n\t\t\tord.push_back({ d[v], v });\n\t\t}\n\t}\n \n\tLCA(int r = 0) {\n\t\tint n = g.size();\n\t\td.resize(n);\n\t\tfst.assign(n, -1);\n\t\tpar.assign(n, -1);\n\t\tord.clear();\n\t\tinit(r);\n \n\t\tbuild(ord);\n\t}\n};\n\nint main() {\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tint n;\n\tcin >> n;\n\tvector<int> a(2 * n);\n\tforn(i, 2 * n){\n\t\tcin >> a[i];\n\t\t--a[i];\n\t}\n\tg.resize(2 * n);\n\tforn(i, 2 * n - 1){\n\t\tint v, u;\n\t\tcin >> v >> u;\n\t\t--v, --u;\n\t\tg[v].push_back(u);\n\t\tg[u].push_back(v);\n\t}\n\tvector<int> l(n, -1), r(n, -1);\n\tforn(i, 2 * n){\n\t\tif (l[a[i]] == -1) l[a[i]] = i;\n\t\telse r[a[i]] = i;\n\t}\n\tvector<char> res(2 * n, 1);\n\tforn(rt, 2 * n) if (a[rt] == 0){\n\t\tLCA d(rt);\n\t\tvector<int> state(2 * n, 0);\n\t\t\n\t\tauto mark = [&](int v){\n\t\t\twhile (v != -1 && state[v] != 1){\n                state[v] = 1;\n\t\t\t\tv = d.par[v];\n\t\t\t}\n\t\t};\n\t\tauto markdel = [&](int v){\n\t\t\tqueue<int> q;\n\t\t\tq.push(v);\n\t\t\tstate[v] = -1;\n\t\t\twhile (!q.empty()){\n\t\t\t\tint v = q.front();\n\t\t\t\tq.pop();\n\t\t\t\tmark(l[a[v]] ^ r[a[v]] ^ v);\n\t\t\t\tfor (int u : g[v]) if (u != d.par[v] && state[u] == 0){\n\t\t\t\t\tstate[u] = -1;\n\t\t\t\t\tq.push(u);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t\tforn(i, n) mark(d.lca(l[i], r[i]));\n\t\tfor (int i = 2 * n - 1; i >= 0; --i) if (state[i] == 0)\n\t\t\tmarkdel(i);\n\t\tvector<char> cur(2 * n, 0);\n        for (int i = 0; i < 2 * n; ++i) if (state[i] == 1)\n            cur[i] = 1;\n        reverse(cur.begin(), cur.end());\n\t\tres = min(res, cur);\n\t}\n\treverse(res.begin(), res.end());\n\tcout << count(res.begin(), res.end(), 1) << '\\n';\n\tforn(i, 2 * n) if (res[i])\n\t\tcout << i + 1 << \" \";\n\tcout << '\\n';\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2042",
    "index": "F",
    "title": "Two Subarrays",
    "statement": "You are given two integer arrays $a$ and $b$, both of size $n$.\n\nLet's define the cost of the subarray $[l, r]$ as $a_l + a_{l + 1} + \\cdots + a_{r - 1} + a_r + b_l + b_r$. If $l=r$, then the cost of the subarray is $a_l + 2 \\cdot b_l$.\n\nYou have to perform queries of three types:\n\n- \"$1$ $p$ $x$\" — assign $a_{p} := x$;\n- \"$2$ $p$ $x$\" — assign $b_{p} := x$;\n- \"$3$ $l$ $r$\" — find \\textbf{two non-empty non-overlapping subarrays} within the segment $[l, r]$ with the maximum total cost and print their total cost.",
    "tutorial": "To begin with, let's understand how to calculate the answer if we consider only one query of the third type. For this, we can use the following dynamic programming: $dp_{i, k}$ - the maximum result if we have considered the first $i$ elements and chosen $k$ boundaries of subsegments (i.e., $k=0$ - the first segment has not started yet, $k=1$ - the first segment has started, $k=2$ - the first segment is finished, but the second segment hasn't started yet, and so on). The transitions in this dynamic programming are quite straightforward: we can select the current element as the next boundary of the subsegment (increase $k$ by $1$), in which case we have to increase the value of dynamic programming by $b_{l+i}$; or we can keep the current value of $k$. Additionally, the dynamic programming value needs to be increased by $a_{l+i}$ if the value of $k$ corresponds to an open segment ($k=1$ or $k=3$). Note that an element can be both the left and the right border of the segment at the same time; so we also need a transition from $k=0$ to $k=2$ and from $k=2$ to $k=4$. Note that the transition from $dp_{i}$ to $dp_{i + 1}$ requires only $7$ numbers: $a_i$, $b_i$, $dp_{i, 0}, dp_{i, 1}, \\dots, dp_{i, 4}$. Therefore, this dynamic programming can be easily packaged within some data structure, for example, a segment tree. In each vertex of the segment tree, let's store a transition matrix $mat_{i, j}$ of size $5 \\times 5$ - the maximum result if we started in this segment in state with $k = i$ and must end in state with $k =j$. This matrix is easy to update when changing values in the arrays $a$ and $b$, and it is also easy to merge (to merge two such matrices, it is necessary to consider triples of the form $0 \\le i \\le j \\le k \\le 4$, and there are only $35$ of them). Thus, we know how to perform one query in $O(35\\log{n})$. Note that you should keep a static size array in each vertex of the segment tree (for example, you can use std::array) in C++; if you use something like a std::vector, it will consume much more memory (static arrays require about $200$ bytes for each vertex of the segment tree, which is already a lot). This also works faster in practice, even though the asymptotic complexity of the solution is the same.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int N = 200 * 1000 + 13;\nconst int K = 5;\n\nusing li = long long;\nusing mat = array<array<li, K>, K>;\n\nconst li INF = 1e18;\n\nint n, q;\nli a[N], b[N];\nmat t[4 * N];\n\nmat init(li a, li b) {\n  mat c;\n  forn(i, K) forn(j, i + 1) c[j][i] = -INF;\n  c[0][0] = c[2][2] = c[4][4] = 0;\n  c[0][1] = c[2][3] = a + b;\n  c[0][2] = c[2][4] = a + b + b;\n  c[1][1] = c[3][3] = a;\n  c[1][2] = c[3][4] = a + b;\n  return c;\n}\n\nmat combine(mat a, mat b) {\n  mat c = init(-INF, -INF);\n  forn(i, K) forn(j, i + 1) forn(k, j + 1)\n    c[k][i] = max(c[k][i], a[k][j] + b[j][i]);\n  return c;\n}\n\nvoid build(int v, int l, int r) {\n  if (l + 1 == r) {\n    t[v] = init(a[l], b[l]);\n    return;\n  }\n  int m = (l + r) / 2;\n  build(v * 2 + 1, l, m);\n  build(v * 2 + 2, m, r);\n  t[v] = combine(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\nvoid upd(int v, int l, int r, int p) {\n  if (l + 1 == r) {\n    t[v] = init(a[l], b[l]);\n    return;\n  }\n  int m = (l + r) / 2;\n  if (p < m) upd(v * 2 + 1, l, m, p);\n  else upd(v * 2 + 2, m, r, p);\n  t[v] = combine(t[v * 2 + 1], t[v * 2 + 2]);\n}\n\nmat get(int v, int l, int r, int L, int R) {\n  if (L >= R) return init(-INF, -INF);\n  if (l == L && r == R) return t[v];\n  int m = (l + r) / 2;\n  return combine(\n    get(v * 2 + 1, l, m, L, min(m, R)),\n    get(v * 2 + 2, m, r, max(m, L), R)\n  );\n}\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  cin >> n;\n  forn(i, n) cin >> a[i];\n  forn(i, n) cin >> b[i];\n  build(0, 0, n);\n  cin >> q;\n  forn(_, q) {\n    int t, x, y;\n    cin >> t >> x >> y;\n    --x;\n    if (t == 1) {\n      a[x] = y;\n      upd(0, 0, n, x);\n    } else if (t == 2) {\n      b[x] = y;\n      upd(0, 0, n, x);\n    } else {\n      auto res = get(0, 0, n, x, y);\n      cout << res[0][4] << '\\n';\n    }\n  }\n}",
    "tags": [
      "data structures",
      "dp",
      "implementation",
      "matrices"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2043",
    "index": "A",
    "title": "Coin Transformation",
    "statement": "Initially, you have a coin with value $n$. You can perform the following operation any number of times (possibly zero):\n\n- transform one coin with value $x$, where $x$ is \\textbf{greater than $3$} ($x>3$), into two coins with value $\\lfloor \\frac{x}{4} \\rfloor$.\n\nWhat is the maximum number of coins you can have after performing this operation any number of times?",
    "tutorial": "Let's try to solve this problem \"naively\": obviously, while we have at least one coin with value $>3$, we should transform it, since it increases the number of coins we get. We can simulate this process, but the number of transformations we get might be really large, so we need to speed this up. Let's make it faster the following way: instead of transforming just one coin, we will transform all coins at once. So, after one operation, we will have $2$ coins with value $\\lfloor \\frac{x}{4} \\rfloor$; after two operations, we will have $4$ coins with value $\\lfloor \\frac{x}{16} \\rfloor$ each, and so on. This can be implemented using a simple while-loop: while the value of our coins is greater than $3$, we divide it by $4$ and double the number of coins. This solution works in $O(\\log n)$. It is also possible to derive a formula for the answer: the number of times we need to divide a number by $4$ so it becomes less than $4$ is $\\lfloor \\log_4 n \\rfloor$, and the number of coins we will get is $2$ to the power of that expression. However, you must be very careful with this approach, because it can have severe precision issues due to the fact that standard logarithm functions work with floating-point numbers, so they are imprecise. You should use some way to calculate $\\lfloor \\log_4 n \\rfloor$ without floating-point calculations; for example, iterating (or binary searching) on the power of $4$ you need to divide the number by so that it becomes less than $4$.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    ans = 1\n    while n > 3:\n        n //= 4\n        ans *= 2\n    print(ans)",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2043",
    "index": "B",
    "title": "Digits",
    "statement": "Artem wrote the digit $d$ on the board exactly $n!$ times in a row. So, he got the number $dddddd \\dots ddd$ (exactly $n!$ digits).\n\nNow he is curious about which \\textbf{odd} digits from $1$ to $9$ divide the number written on the board.",
    "tutorial": "There are several ways to solve this problem. I will describe two of them. Using divisibility rules (a lot of math involved): We can try divisibility rules for all odd integers from $1$ to $9$ and find out whether they work for our numbers: $1$ is always the answer, since every integer is divisible by $1$: a number is divisible by $3$ iff its sum of digits is divisible by $3$. Since our number consists of $n!$ digits $d$, then either $n!$ or $d$ should be divisible by $3$; so, $n \\ge 3$ or $d \\bmod 3 = 0$; a number is divisible by $9$ iff its sum of digits is divisible by $9$. This is a bit trickier than the case with $3$, because it is possible that both $n!$ and $d$ are divisible by $3$ (not $9$), and it makes the sum of digits divisible by $9$; a number is divisible by $5$ iff its last digit is $5$ or $0$. Just check that $d=5$, and that's it; probably the trickiest case: a number is divisible by $7$ iff, when this number is split into blocks of $3$ digits (possibly with the first block shorter than $3$ digits), the sign-alternating sum of these blocks is divisible by $7$. Like, $1234569$ is divisible by $7$ because $(1-234+569)$ is divisible by $7$. If we apply this rule to our numbers from the problem, we can use the fact that when $n \\ge 3$, the number can be split into several blocks of length $6$, and each such block changes the alternating sum by $0$. So, if $n \\ge 3$ or $d = 7$, our number is divisible by $7$. Almost brute force (much less math involved): First, we actually need a little bit of math. If you take a number consisting of $n!$ digits equal to $d$, it is always divisible by $(n-1)!$ digits equal to $d$. This is because, if you write some integer repeatedly, the resulting number will be divisible by the original number, like, for example, $424242$ is divisible by $42$. So, if for some $n = k$, the number is divisible by some digit, then for $n = k+1$, the number will also be divisible for some digit. This means that there exists an integer $m$ such that for all integers $n \\ge m$, the results are the same if you use the same digit $d$. So, we can set $n = \\min(n, m)$, and if $m$ is small enough, use brute force. What is the value of $m$? The samples tell us that the number consisting of $7!$ ones is divisible by $1$, $3$, $7$ and $9$ (and divisibility by $5$ depends only on $d$), so you can actually use $m=7$. It is also possible to reduce $m$ to $6$, but this is not required. So, the solution is: reduce $n$ to something like $7$ if it is greater than $7$, then use brute force. You can either calculate the remainder of a big number modulo small number using a for-loop, or, if you code in Java or Python, use built-in big integers (just be careful with Python, modern versions of it forbid some operations with integers longer than $4300$ digits, you might need to override that behavior).",
    "code": "import sys\n \nsys.set_int_max_str_digits(6000)\n \ndef fact(x):\n    if x == 0:\n        return 1\n    return x * fact(x - 1)\n \nt = int(input())\nfor i in range(t):\n    n, k = map(int, input().split())\n    n = min(n, 7)\n    s = int(str(k) * fact(n))\n    for i in range(1, 10, 2):\n        if s % i == 0:\n            print(i, end = ' ')\n    print()",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2043",
    "index": "C",
    "title": "Sums on Segments",
    "statement": "You are given an array $a$ of $n$ integers, where all elements except for \\textbf{at most one} are equal to $-1$ or $1$. The remaining element $x$ satisfies $-10^9 \\le x \\le 10^9$.\n\nFind all possible sums of subarrays of $a$, including the empty subarray, whose sum is defined as $0$. In other words, find all integers $x$ such that the array $a$ has at least one subarray (possibly empty) with sum equal to $x$. A subarray is a contiguous subsegment of an array.\n\nOutput these sums in ascending order. Each sum should be printed only once, even if it is achieved by multiple subarrays.",
    "tutorial": "What could the answer to the problem be if all elements were equal to $1$ or $-1$? Let's consider all segments with a fixed left boundary $l$. The empty segment $[l; l-1]$ has a sum of $0$. As we move the right boundary to the right, the sum will change by $\\pm1$. That is, we can obtain all sums from the minimum sum to the maximum one. To find the sums for the entire array, we need to find the union of the segments. Since all segments include $0$, their union is also a segment. Therefore, the possible sums are all sums from the minimum sum to the maximum sum in the entire array. Now let's apply this reasoning to the given problem. The segments that do not include the strange element still form a segment of possible sums that includes $0$. As for the segments that include the strange element, we can look at them this way. We will remember these segments and remove the strange element. Then the resulting sums will also form a segment that includes $0$. If we return the element to its place, all sums will increase exactly by this element. Thus, it will remain a segment, however, not necessarily including $0$ now. Then the solution could be as follows. We will find the minimum and maximum sum among the segments that do not contain the strange element. We will find the minimum and maximum sum among the segments that do contain it. Then we will output the union of the obtained sum segments. Next, you need to adapt your favorite algorithm for finding the maximum sum segment for this problem. My favorite is reducing it to prefix sums. The sum of the segment $[l; r]$ is equal to $\\mathit{pref}_{r+1} - \\mathit{pref}_l$. We fix the right boundary of the segment $r$. Since the first term for all segments is now the same, the maximum sum segment with this right boundary is the one with the minimum possible prefix sum at the left boundary. We will then iterate over $r$ in increasing order and find the maximum sum among all right boundaries. The minimum prefix sum on the left can be maintained on the fly. For a fixed right boundary, we have two options: for some prefix of left boundaries, the strange element is inside the segment, and for some suffix, it is outside. This suffix may be empty if the boundary $r$ is to the left of the strange element. Therefore, we will maintain two values on the fly: the minimum prefix sum before the strange element and after it. Finally, we need to find the possible sums in the union of the two segments. There are two options here. If the segments intersect, then it includes all sums from the minimum of the left boundaries to the maximum of the right ones. If they do not intersect, then it is simply two segments. Overall complexity: $O(n)$ per testcase.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\tl1, r1 = 0, 0\n\tl2, r2 = 2*10**9, -2*10**9\n\t\n\tpr = 0\n\tmnl, mxl = 0, 0\n\tmnr, mxr = 2*10**9, -2*10**9\n\tfor i in range(n):\n\t\tpr += a[i]\n\t\tif a[i] != -1 and a[i] != 1:\n\t\t\tmnr, mxr = mnl, mxl\n\t\t\tmnl, mxl = pr, pr\n\t\tl1 = min(l1, pr - mxl)\n\t\tr1 = max(r1, pr - mnl)\n\t\tl2 = min(l2, pr - mxr)\n\t\tr2 = max(r2, pr - mnr)\n\t\tmnl = min(mnl, pr)\n\t\tmxl = max(mxl, pr)\n\tres = []\n\tif l2 > r1:\n\t\tres = list(range(l1, r1 + 1)) + list(range(l2, r2 + 1))\n\telif r2 < l1:\n\t    res = list(range(l2, r2 + 1)) + list(range(l1, r1 + 1))\n\telse:\n\t\tres = list(range(min(l1, l2), max(r1, r2) + 1))\n\tprint(len(res))\n\tprint(*res)",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2043",
    "index": "D",
    "title": "Problem about GCD",
    "statement": "Given three integers $l$, $r$, and $G$, find two integers $A$ and $B$ ($l \\le A \\le B \\le r$) such that their greatest common divisor (GCD) equals $G$ and the distance $|A - B|$ is maximized.\n\nIf there are multiple such pairs, choose the one where $A$ is minimized. If no such pairs exist, output \"-1 -1\".",
    "tutorial": "First, let's try to solve this problem with $G=1$. We can check the pair $(l, r)$. If its greatest common divisor is not $1$, then we should check $(l, r-1)$ and $(l+1, r)$, i. e. the pairs on the distance $(r-l-1)$. If these don't work, we can check $(l, r-2)$, $(l+1, r-1)$ and $(l+2, r)$, and so on, and the answer will be located fast enough (more about that in the third paragraph of the editorial). So, we get a solution in $O(K^2 \\log A)$ per test case, where $A$ is the bound on the integers on the input, and $K$ is the decrease in distance we had to make to find this pair (i. e. if the answer has distance $|A-B|$, then $K = |r - l| - |A - B|$). What to do if $G \\ne 1$? Almost the same, but first, we need to ensure that the first pair we try has both integers divisible by $G$. So, if $l \\bmod G \\ne 0$, let's shift it to the next closest integer which is divisible by $G$; and if $r \\bmod G \\ne 0$, let's subtract $r \\bmod G$ from $r$ to make it divisible. Then, we make the same process, but instead of trying pairs like $(l, r-1)$, $(l+1, r)$, $(l, r-2)$ and so on, we try $(l, r-G)$, $(l+G, r)$, $(l, r - 2G)$, and so on. Okay, now let's talk about why this works fast, i. e. why this $K$ in the complexity formula is not that big. All the following paragraphs will assume $G=1$, but we can use the same reasoning with $G>1$ if we divide everything by $G$. Intuitively, we can think about it in terms of prime gaps: as soon as $r-K$ becomes a prime number, we get our result. Average gap between two primes is about $ln A$, but there can be pretty big gaps, more than $1000$. If you're bold and brave, you can stop here and submit, but let's find a better bound. Instead of thinking about the gap between two primes, let's think about the gap between two numbers which are coprime with $l$. Let's assume that $l$ is the product of several first prime numbers (if it is not, integers which are coprime with $l$ will appear even more often). $\\frac{1}{2}$ of all integers are not divisible by $2$; $\\frac{2}{3}$ of them are not divisible by $3$; $\\frac{4}{5}$ of them are not divisible by $5$, and so on. If we repeat this process until the product of primes we considered becomes too large, we can get that, on average, $1$ in $7$ or $8$ integers is coprime with $l$. This is a better bound, but it still uses \"average\" gaps. However, this should be enough to try to submit the solution. Okay, now let's show a rigorous proof (which you really shouldn't need during the contest) of some reasonable bound. We can prove that if you consider all possible pairs of integers from intervals $[l, l+30)$ and $(r-30, r]$, you will find at least one coprime pair. There are $30$ integers in each interval, so there are $900$ pairs to consider. Suppose in some of them, both integers are divisible by $2$. There will be at most $225$ such pairs, so we are left with $675$ pairs. Suppose in some of the remaining pairs, both integers are divisible by $3$. There will be at most $10$ integers divisible by $3$ in each segment, so at most $100$ pairs. We are left with $575$ pairs. Suppose in some of the remaining pairs, both integers are divisible by $5$. There will be at most $6$ integers divisible by $5$ in each segment, so at most $36$ pairs. We are left with $539$ pairs. If we repeat this until some prime number like $37$, we will still have to \"fix\" more than $450$ pairs, so at least one number has $15$ or more pairs to \"fix\". This should mean that it is divisible by at least $15$ primes which are greater than $37$, and it means it's greater than $10^{18}$. So, in every pair of intervals $[l, l+30)$ and $(r-30, r]$ such that the numbers are not greater than $10^{18}$, there will be at least one coprime pair, and this proves that $K \\le 60$. In practice, it is much lower since, in our proof, we didn't consider the fact that a lot of pairs will have more than $1$ prime which they are divisible by; if we take this into account (or repeat the same process until primes become much greater), we can prove tighter bounds, for example, $K = 40$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nlong long gcd(long long x, long long y)\n{\n    if(x == 0) return y;\n    else return gcd(y % x, x);\n}\n \nvoid solve()\n{\n    long long l, r, g;\n    scanf(\"%lld %lld %lld\", &l, &r, &g);\n    long long L = l + (l % g == 0 ? 0 : g - (l % g));\n    long long R = r - r % g;\n    for(int i = 0; i <= (R - L) / g; i++)\n        for(int j = 0; j <= i; j++)\n            if(gcd(L + j * g, R - (i - j) * g) == g)\n            {\n                printf(\"%lld %lld\\n\", L + j * g, R - (i - j) * g);\n                return;\n            }   \n    puts(\"-1 -1\");\n}\n \nint main()\n{                             \n    int t;\n    scanf(\"%d\", &t);\n    for(int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "brute force",
      "flows",
      "math",
      "number theory"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2043",
    "index": "E",
    "title": "Matrix Transformation",
    "statement": "You are given two matrices $A$ and $B$ of size $n \\times m$, filled with integers between $0$ and $10^9$. You can perform the following operations \\textbf{on matrix $A$} in any order and any number of times:\n\n- &=: choose two integers $i$ and $x$ ($1 \\le i \\le n$, $x \\ge 0$) and replace each element in row $i$ with the result of the bitwise \\textbf{AND} operation between $x$ and that element. Formally, for every $j \\in [1, m]$, the element $A_{i,j}$ is replaced with $A_{i,j} \\text{ & } x$;\n- |=: choose two integers $j$ and $x$ ($1 \\le j \\le m$, $x \\ge 0$) and replace each element in column $j$ with the result of the bitwise \\textbf{OR} operation between $x$ and that element. Formally, for every $i \\in [1, n]$, the element $A_{i,j}$ is replaced with $A_{i,j} \\text{ | } x$.\n\nThe value of $x$ may be chosen differently for different operations.\n\nDetermine whether it is possible to transform matrix $A$ into matrix $B$ using the given operations any number of times (including zero).",
    "tutorial": "Every operation which affects multiple bits can be split into several operations which only affect one bit. For example, if you make an |= operation with $x=11$, it is the same as making three |= operations with $x=1$, $x=2$ and $x=8$. So, let's solve the problem for each bit separately. If we consider only one bit, the problem becomes the following one: You are given a binary matrix $A$, and you have to check if it is possible to transform it into another binary matrix $B$. The operations you can make are \"set all elements in some row to $0$\" and \"set all elements in some column to $1$\". Let's find all cells where $A_{i,j} \\ne B_{i,j}$. If $A_{i,j} = 0$ and $B_{i,j} = 1$, then it means that we definitely have to apply an operation to the $j$-th column. Otherwise, if $A_{i,j} = 1$ and $B_{i,j} = 0$, then we definitely have to apply an operation to the $i$-th row. That way, we can find the operations we definitely need to apply. It's pretty obvious that we don't need to do the same operation twice - if we do the same operation to the same row/column twice, we can discard the first operation, since it will be overwritten by the last operation. But these are not all operations we need to apply. Suppose $B_{i,j} = 0$, and we change everything in the $j$-th column to $1$. Then, we have to make an operation with the $i$-th row to set $B_{i,j}$ back to $0$. This means that after you apply an operation to the $j$-th column, you have to do an operation with the $i$-th row. Same when $B_{i,j} = 1$: after you apply an operation to the $i$-th row, you have to do an operation with the $j$-th column. Let's build a graph where every operation will be represented by a vertex, and a directed edge $x \\rightarrow y$ means that, if you apply the operation $x$, the operation $y$ must be applied after that. Some vertices of this graph represent operations which we definitely need to apply. If there is a cycle reachable from one of these vertices, the transformation is impossible, since we will apply operations forever and never get the matrix we need. But if there is no cycle reachable from any operation we need to apply, then we can \"mark\" all operations reachable from the operations we need, and apply them in the order of topological sorting, and we will get exactly the matrix $B$ (for every cell that was changed, the last operation applied to it will make it correct; and we enforced that we need to apply operations to all cells that must change). Searching for a cycle in a directed graph can be done with \"three-colored DFS\" - a modification of DFS which, for each vertex, maintains one of three states - either this vertex wasn't reached by DFS at all, or it was already reached and is on the DFS stack, or this vertex was already fully processed (both reached by DFS and deleted from the DFS stack). This way, we can find a back-edge that creates the cycle as follows: if we try to go from a vertex to another vertex which is on the DFS stack, it means that we have found a cycle. There are other methods of cycle detection, but this one is the most common. If for every bit, we can make the transformations we need, the answer is Yes. Otherwise, the answer is No. The solution works in $O(n m \\log A)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nstruct graph\n{\n    int V;\n    vector<vector<int>> g;\n    vector<int> color;\n \n    bool dfs(int v)\n    {\n        if(color[v] != 0) return false;\n        color[v] = 1;\n        bool res = false;\n        for(auto y : g[v])\n        {\n            if(color[y] == 2) continue;\n            else if(color[y] == 0)\n                res |= dfs(y);\n            else res = true;\n        }\n        color[v] = 2;\n        return res;\n    }\n \n    void add_edge(int x, int y)\n    {\n        g[x].push_back(y);\n    }\n \n    graph(int V)\n    {\n        this->V = V;\n        this->g.resize(V);\n        this->color.resize(V);\n    };\n};\n \nint get_bit(int x, int y)\n{\n    return (x >> y) & 1;\n}\n \nbool check(const vector<vector<int>>& a, const vector<vector<int>>& b, int k)\n{\n    int n = a.size();\n    int m = a[0].size();\n    vector<bool> must_row(n);\n    vector<bool> must_col(m);\n    auto G = graph(n + m);\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < m; j++)\n        {\n            if(get_bit(a[i][j], k) != get_bit(b[i][j], k))\n            {\n                if(get_bit(b[i][j], k) == 0) must_row[i] = true;\n                else must_col[j] = true;\n            }\n            if(get_bit(b[i][j], k) == 0) G.add_edge(j + n, i);\n            else G.add_edge(i, j + n);\n        }                 \n    for(int i = 0; i < n; i++)\n        if(must_row[i] && G.dfs(i))\n            return false;\n    for(int j = 0; j < m; j++)\n        if(must_col[j] && G.dfs(j + n))\n            return false;\n    return true;\n}\n \nvoid solve()\n{\n    int n, m;\n    scanf(\"%d %d\", &n, &m);\n    vector<vector<int>> a(n, vector<int>(m));\n    auto b = a;\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < m; j++)\n            scanf(\"%d\", &a[i][j]);\n    for(int i = 0; i < n; i++)\n        for(int j = 0; j < m; j++)\n            scanf(\"%d\", &b[i][j]);\n    for(int i = 0; i < 30; i++)\n    {\n        if(!check(a, b, i))\n        {\n            puts(\"No\");\n            return;\n        }\n    }\n    puts(\"Yes\");\n}\n \nint main()\n{                             \n    int t;\n    scanf(\"%d\", &t);\n    for(int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2043",
    "index": "F",
    "title": "Nim",
    "statement": "Recall the rules of the game \"Nim\". There are $n$ piles of stones, where the $i$-th pile initially contains some number of stones. Two players take turns choosing a non-empty pile and removing any positive (strictly greater than $0$) number of stones from it. The player unable to make a move loses the game.\n\nYou are given an array $a$, consisting of $n$ integers. Artem and Ruslan decided to play Nim on segments of this array. Each of the $q$ rounds is defined by a segment $(l_i, r_i)$, where the elements $a_{l_i}, a_{l_i+1}, \\dots, a_{r_i}$ represent the sizes of the piles of stones.\n\nBefore the game starts, Ruslan can remove any number of piles from the chosen segment. However, at least \\textbf{one pile must remain}, so in a single round he can remove at most $(r_i - l_i)$ piles. He is allowed to remove $0$ piles. After the removal, the game is played on the remaining piles within the segment.\n\n\\textbf{All rounds are independent}: the changes made in one round do not affect the original array or any other rounds.\n\nRuslan wants to remove as many piles as possible so that Artem, who always makes the first move, loses.\n\nFor each round, determine:\n\n- the maximum number of piles Ruslan can remove;\n- the number of ways to choose the \\textbf{maximum} number of piles for removal.\n\nTwo ways are considered different if there exists an index $i$ such that the pile at index $i$ is removed in one way but not in the other. Since the number of ways can be large, output it modulo $998\\,244\\,353$.\n\nIf Ruslan cannot ensure Artem's loss in a particular round, output -1 for that round.",
    "tutorial": "Let's recall the condition for the second player to win in the game of \"Nim\". The XOR of the sizes of the piles must be equal to $0$. That is, we are asked to remove as many piles as possible so that the XOR becomes $0$. Notice the following fact. Suppose there are $c$ piles of size $x$ on a segment. If we remove an even number of piles, the XOR does not change. If we remove an odd number, it changes by $x$. Therefore, there is no point in keeping more than $2$ piles. If we keep $t > 2$ piles, we can remove another $2$ piles, and it will not change anything at all. We will answer the queries independently. Let's find the count of each of the $51$ elements in the given segment. For example, we can precompute how many times each element appears in each prefix. Now we can write the following dynamic programming solution. $\\mathit{dp}[i][j][f]$ represents a pair of (maximum amount of removed elements, number of ways to remove that amount), where we have considered the first $i$ of the $51$ values, the current XOR among the non-removed values is $j$, and $f = 1$ if at least one element is not removed and $0$ otherwise. Let the amount of the current value be $c$. From each state, there are at most three transitions: remove all elements with that value - $1$ way; keep $1$ element - $c$ ways; keep $2$ elements - $\\frac{c(c-1)}{2}$ ways. The base case is $\\mathit{dp}[0][0][0] = (0, 1)$, the rest are filled with $(-1, -1)$, for example. The final state is $\\mathit{dp}[51][0][1]$. If it's equal to $(-1, -1)$, there's no answer. Since the XOR cannot exceed $63$, the number of states in the dynamic programming solution is $51 \\cdot 64 \\cdot 2$. From each state, there are three transitions, which fits within the time constraints.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define forn(i, n) for(int i = 0; i < int(n); i++) \n \nconst int MOD = 998244353;\n \nint add(int a, int b){\n\ta += b;\n\tif (a >= MOD)\n\t\ta -= MOD;\n\treturn a;\n}\n \nint mul(int a, int b){\n\treturn a * 1ll * b % MOD;\n}\n \nstruct state{\n\tint mx, cnt;\n};\n \nvoid merge(state &a, int mx, int cnt){\n\tif (a.mx > mx) return;\n\tif (a.mx < mx) a.mx = mx, a.cnt = 0;\n\ta.cnt = add(a.cnt, cnt);\n}\n \nstate dp[52][64][2];\n \nint main(){\n\tcin.tie(0);\n\tios::sync_with_stdio(false);\n\tint n, q;\n\tcin >> n >> q;\n\tvector<int> a(n);\n\tforn(i, n) cin >> a[i];\n\tint mx = *max_element(a.begin(), a.end());\n\tvector<vector<int>> cnt(n + 1, vector<int>(mx + 1));\n\tforn(i, n){\n\t\tcnt[i + 1] = cnt[i];\n\t\t++cnt[i + 1][a[i]];\n\t}\n\tforn(_, q){\n\t\tint l, r;\n\t\tcin >> l >> r;\n\t\t--l;\n\t\tmemset(dp, -1, sizeof(dp));\n\t\tdp[0][0][0] = {0, 1};\n\t\tforn(i, mx + 1){\n\t\t\tint c = cnt[r][i] - cnt[l][i];\n\t\t\tint c2 = c * 1ll * (c - 1) / 2 % MOD;\n\t\t\tforn(val, 64) forn(fl, 2) if (dp[i][val][fl].cnt >= 0){\n\t\t\t\tif (c > 0)\n\t\t\t\t\tmerge(dp[i + 1][val ^ i][true], dp[i][val][fl].mx + c - 1, mul(dp[i][val][fl].cnt, c));\n\t\t\t\tif (c > 1)\n\t\t\t\t\tmerge(dp[i + 1][val][true], dp[i][val][fl].mx + c - 2, mul(dp[i][val][fl].cnt, c2));\n\t\t\t\tmerge(dp[i + 1][val][fl], dp[i][val][fl].mx + c, dp[i][val][fl].cnt);\n\t\t\t}\n\t\t}\n\t\tauto ans = dp[mx + 1][0][1];\n\t\tif (ans.cnt == -1)\n\t\t\tcout << -1 << '\\n';\n\t\telse\n\t\t\tcout << ans.mx << ' ' << ans.cnt << '\\n';\n\t}\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp",
      "games",
      "greedy",
      "implementation",
      "shortest paths"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2043",
    "index": "G",
    "title": "Problem with Queries",
    "statement": "You are given an array $a$, consisting of $n$ integers. Your task is to process $q$ queries of two types:\n\n- $1~p~x$ — set the value of the element at index $p$ equal to $x$;\n- $2~l~r$ — count the number of pairs of indices $(i, j)$ such that $l \\le i < j \\le r$ and $a_i \\ne a_j$.\n\nNote that the queries in this task are \\textbf{encoded}; each subsequent query can only be decoded after calculating the answer to the preceding query of the second type.",
    "tutorial": "First, let's reformulate the problem. Instead of counting the number of pairs of distinct elements in a segment, we will count the number of pairs of identical elements and subtract it from the total number of pairs. To solve this problem, we will use square root decomposition on the array. Let's divide the original array into blocks of size $B$ and learn how to answer queries $(l, r)$ that satisfy the following conditions: $l = L \\cdot B$ - this means that the left boundary of the query coincides with the beginning of some block of the square root decomposition; $r = R \\cdot B - 1$ - this means that the right boundary of the query coincides with the last element of some block of the square root decomposition. Due to this restriction on the problem, we can utilize certain properties that will be necessary for our solution: The order of elements within a block does not matter; we can treat each block of our square root decomposition as an unordered multiset; Changing the value of an element in terms of a multiset can be reformulated as removing the old value and adding the new value. In general, the modified queries can be rewritten in the following format: add $ind~x$ - add an element with value $x$ to the block $ind$. del $ind~x$ - remove an element with value $x$ from the block $ind$. get $L~R$ - count the number of pairs of positions $(i, j)$, where $L \\cdot B \\le i < j \\le R \\cdot B$ and $a_i = a_j$. Let's assume we have an array $blocks[i][j]$, which stores the answer to the third type of query for all possible segments of blocks $0 \\le i \\le j \\le K$, where $K$ is the number of blocks in the square root decomposition of our array. Initially, we fill the $blocks$ array with zeros and then add all elements using the add operation. Let's observe how the first type of query modifies this array; the second type of query is considered similarly. When an element with value $x$ is added to the block $ind$, it affects all elements of the array $blocks[i][j]$ such that $0 \\le i \\le ind \\le j$. For a specific element of the array $blocks[i][j]$, its value increases by the number of occurrences of the element $x$ in the segment $[i \\cdot B; j \\cdot B]$. This happens because the added element can form a pair with all existing elements equal to the specified value that belong to this segment. Formally, this can be described as $blocks[i][j]~=blocks[i][j] + count(i, j, x)$, where $count(i, j, x)$ is a function that returns the number of occurrences of the element $x$ in the blocks $i, \\dots, j$. The function $count(i, j, x)$ can be maintained by storing an array $pref[val][i]$, where for each element $val$, it will store how many times it appears in the segment of blocks $[0, i]$. When adding an element, the number of values that need to be recalculated will be about $\\frac{K \\cdot (K - 1)}{2}$. If we can do this in $O(1)$, we can achieve a solution in $O((Q+N) \\cdot N^{\\frac{2}{3}}$, taking $B = N^{\\frac{2}{3}}$. Unfortunately, it is practically impossible to fit this within time limits, so let's try to improve the solution. Returning to the description of how to modify an arbitrary element of the array $blocks[i][j]$, let's rewrite and transform the formula: $blocks[i][j]~=blocks[i][j] + count(i, j, x)$ into $blocks[i][j]~=blocks[i][j] + count(i, ind, x) + count(ind + 1, j, x)$. The second term in this expression does not use the right boundary $j$, and the third term does not use the left boundary $i$. Suppose we want to add the second term to the relevant elements $blocks[i][j]$; we can iterate over the left boundary $i$ and add $count(i, ind, x)$ for all right boundaries where $j \\ge ind$. To perform such additions in $O(1)$, we will use something like a difference array: we will create an array $update\\_right[i][j]$, where for a fixed left boundary, we will store how the suffix of right boundaries will change. When iterating over the left boundary $i$, for the suffix of right boundaries $j \\ge ind$, we need to add the same amount $count(i, ind, x)$; but we will handle this addition on the suffix in one position of the array $update\\_right[i][ind] = update\\_right[i][ind] + count(i, ind, x)$. Then, to account for these additions in the third type of queries $get(L,~ R)$, we will need to take the sum of the elements of the array $update\\_right[L][L] + update\\_right[L][L + 1] + \\dots + update\\_right[L][R]$. The third term from the sum $blocks[i][j]~=blocks[i][j] + count(i, ind, x) + count(ind + 1, j, x)$ is processed similarly: we will iterate over the right boundary and form an array $update\\_left$, where the additions will be on the prefix. Thus, each modification query will be executed in $O(K)$. A query of the third type requires us to iterate over one of the fixed boundaries and find the sum, which will require $O(K)$ operations. By choosing $B = \\sqrt N$, each of these queries can be executed in $O(\\sqrt N)$. Returning to the original problem, let's describe how to find the answer to a query whose boundaries do not coincide with the boundaries of the blocks: First, find the answer for the problem we learned to solve above for the largest segment of blocks that is completely contained within the query; Now, we need to add the contribution of $O(B)$ elements from the blocks that are not fully included in the query. Each of these $O(B)$ elements can form a pair with all elements in our block segment, so we will need to take the number of occurrences of this element from the $pref$ array. Additionally, these $O(B)$ elements can form pairs with each other; to handle this, we can maintain an array of size $N$, where for each value, we keep track of the number of additional elements with that value. When processing some additional element $x$, we will add the count of these elements from the array to the answer and increase this count by $1$; at the end of processing the query for all additional elements, we will reset their count back to $0$. Thus, we have obtained a solution in $O((N+Q) \\cdot \\sqrt N)$.",
    "tags": [
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2044",
    "index": "A",
    "title": "Easy Problem",
    "statement": "Cube is given an integer $n$. She wants to know how many ordered pairs of positive integers $(a,b)$ there are such that $a=n-b$. Since Cube is not very good at math, please help her!",
    "tutorial": "For any $n$, Cube can set $a$ = any integer between $1$ and $n-1$ inclusive, and set $b = n - a$. $a$ cannot be less than $1$, because then it would be non-positive, and $a$ cannot be greater than $n-1$, because then $b$ would be less than $1$, which would make it non-positive. Therefore the answer is just $n-1$ for all $n$.",
    "code": "input = sys.stdin.readline\nfor _ in range(int(input())):\n    print(int(input())-1)",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2044",
    "index": "B",
    "title": "Normal Problem",
    "statement": "A string consisting of only characters 'p', 'q', and 'w' is painted on a glass window of a store. Ship walks past the store, standing directly in front of the glass window, and observes string $a$. Ship then heads inside the store, looks directly at the same glass window, and observes string $b$.\n\nShip gives you string $a$. Your job is to find and output $b$.",
    "tutorial": "The letters she reads that comprise string $b$ are just the letters that comprise string $a$, flipped left-to-right. This means that 'p' becomes 'q', 'q' becomes 'p', and 'w' stays 'w', since it is vertically symmetrical. The order in which the letters are read is also reversed, because what used to be the left side of string $a$ gets flipped over to the right side of string $b$, and vice versa. We now have an algorithm for constructing string $b$, which is to iterate from right-to-left on string $a$, outputting 'p' when there is a 'q', 'q' when there is a 'p', and 'w' when there is a 'w'.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define ll long long\n#define pll pair<ll, ll>\n\nint t;\n\nint main() {\n\tcin.tie(0)->sync_with_stdio(0);\n\tcin >> t;\n\twhile (t--) {\n\t\tstring s;\n\t\tcin >> s;\n\t\treverse(s.begin(), s.end());\n\t\tfor (char &c : s) if (c == 'q') c = 'p'; else if (c == 'p') c = 'q';\n\t\tcout << s << '\\n';\n\t}\n}",
    "tags": [
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2044",
    "index": "C",
    "title": "Hard Problem",
    "statement": "Ball is the teacher in Paperfold University. The seats of his classroom are arranged in $2$ rows with $m$ seats each.\n\nBall is teaching $a + b + c$ monkeys, and he wants to assign as many monkeys to a seat as possible. Ball knows that $a$ of them only want to sit in row $1$, $b$ of them only want to sit in row $2$, and $c$ of them have no preference. Only one monkey may sit in each seat, and each monkey's preference must be followed if it is seated.\n\nWhat is the maximum number of monkeys that Ball can seat?",
    "tutorial": "Let $A$, $B$, $C$ be three sets of monkeys, such that monkeys in $A$ can only sit in row $1$, $B$ in row $2$, and $C$ can sit anywhere. It is clear that if there is free space in row $1$, and there are monkeys left in set $A$, it is optimal to seat a monkey from set $A$ onto row $1$. This is because a monkey from set $C$ can be seated on either row, and there might be space left on the other row for that same monkey in set $C$ after you've already seated the monkey from set $A$. However, this is not the case if you start by seating the monkeys in set $C$ in the front row, since you might now leave empty seats at the back, but then have monkeys from set $A$ still left unseated. Therefore, the strategy is as follows: seat as many monkeys from set $A$ as you can in the front row, then seat as many monkeys from set $B$ as you can in the back row, then seat as many monkeys from set $C$ as you can, and that yields the answer.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\n\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt;\n    cin>>tt;\n    while(tt--)\n    {\n        int m,a,b,c;\n        cin>>m>>a>>b>>c;\n        int ans=0,rem=0;\n        ans+=min(m,a);rem+=m-min(m,a);\n        ans+=min(m,b);rem+=m-min(m,b);\n        ans+=min(rem,c);\n        cout<<ans<<'\\n';\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2044",
    "index": "D",
    "title": "Harder Problem",
    "statement": "Given a sequence of positive integers, a positive integer is called a mode of the sequence if it occurs the maximum number of times that any positive integer occurs. For example, the mode of $[2,2,3]$ is $2$. Any of $9$, $8$, or $7$ can be considered to be a mode of the sequence $[9,9,8,8,7,7]$.\n\nYou gave UFO an array $a$ of length $n$. To thank you, UFO decides to construct another array $b$ of length $n$ such that $a_i$ is a mode of the sequence $[b_1, b_2, \\ldots, b_i]$ for all $1 \\leq i \\leq n$.\n\nHowever, UFO doesn't know how to construct array $b$, so you must help her. Note that $1 \\leq b_i \\leq n$ must hold for your array for all $1 \\leq i \\leq n$.",
    "tutorial": "Observe that if you have an array where all elements are unique, they will all have frequency $1$, therefore they can all be classified as the mode. Therefore, it follows that the strategy for the construction is to just construct an array where for each prefix, the last element of this prefix appears in the array at least once. An easy way of doing is this is such: For each element $a_i$, if this value has appeared previously in the array (you can use a set to check this), set $b_i$ equal to some random integer that isn't used elsewhere in the list $a$, and keep going. Otherwise, set $b_i = a_i$.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\n\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt;\n    cin>>tt;\n    while(tt--)\n    {\n        int n;\n        cin>>n;\n        vector<int> a(n+1),b(n);\n        for(int i=0;i<n;i++)\n        {\n            int x;\n            cin>>x;\n            if(!a[x])\n            {\n                b[i]=x;\n                a[x]=1;\n            }\n        }\n        queue<int> q;\n        for(int i=1;i<=n;i++)\n            if(!a[i])\n                q.push(i);\n        for(int i=0;i<n;i++)\n        {\n            if(!b[i])\n            {\n                b[i]=q.front();\n                q.pop();\n            }\n        }\n        for(int i=0;i<n;i++)\n            cout<<b[i]<<\" \\n\"[i==n-1];\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2044",
    "index": "E",
    "title": "Insane Problem",
    "statement": "Wave is given five integers $k$, $l_1$, $r_1$, $l_2$, and $r_2$. Wave wants you to help her count the number of ordered pairs $(x, y)$ such that all of the following are satisfied:\n\n- $l_1 \\leq x \\leq r_1$.\n- $l_2 \\leq y \\leq r_2$.\n- There exists a non-negative integer $n$ such that $\\frac{y}{x} = k^n$.",
    "tutorial": "Clearly, trying to bruteforce over all possible values of $x$ or $y$ is too slow, because the bounds are $1 \\leq l_1 \\leq r_1 \\leq 10^9$. However, there is another variable that you can actually bruteforce over - and that is $n$. This is because exponentiation famously makes numbers very big very quickly - and if we set $k$ as small as possible (i.e. $2$), we only need to check $1 \\leq n \\leq 32$. This is because $2^{32} > 10^9$, so there cannot possibly be any solutions for $n > 32$ for any $k$. Now, let's rephrase the problem. We need to find pairs $(x, y)$ such that $x \\cdot k^n = y$. Now, we can check every value of $n$ from $1$ to $32$, and for each, binary search to find the smallest $x$ such that $y$ fits the conditions, and the largest $x$. Now, we can subtract these two values and add this to the answer. Note that we do not need to care about more than $32$ different values of $k^n$, because obviously $k^{32} \\ge 2^{32} > 10^9$. From here and on, we focus on solving for only one value of $k^n$. When $k^n$ is fixed and you are given $\\frac{y}{x}=k^n$, notice $y$ is fixed as $x k^n$. Therefore, if we count the values $x$ such that $y$ is in the given interval as well, we will be properly counting the ordered pairs. Formally, this condition can be cleared out as: $l_2 \\le x k^n \\le r_2$ $\\frac{l_2}{k^n} \\le x \\le \\frac{r_2}{k^n}$ Because $x$ is an integer, $\\left \\lceil {\\frac{l_2}{k^n}} \\right \\rceil \\le x \\le \\left \\lfloor {\\frac{r_2}{k^n}} \\right \\rfloor$ Thus, when we intersect the two intervals, we get the following interval at last. $\\max \\left({l_1,\\left \\lceil {\\frac{l_2}{k^n}} \\right \\rceil}\\right) \\le x \\le \\min \\left({r_1,\\left \\lfloor {\\frac{r_2}{k^n}} \\right \\rfloor}\\right)$ Compute the size of this interval for all $k^n$ (at most $32$ values) and the answer can be found. Do note the following details while implementing: When $r < l$, the size of the interval is $0$, not negative. Beware of overflows. Dealing with big integers can be helpful in avoiding this, but it may make your solution slow. Do not round up a fraction using the ceil function; This has been a recurring issue in almost every Div.4!",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\n\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt;\n    cin>>tt;\n    while(tt--)\n    {\n        ll k,l1,r1,l2,r2;\n        cin>>k>>l1>>r1>>l2>>r2;\n        ll kn=1,ans=0;\n        for(int n=0;r2/kn>=l1;n++)\n        {\n            ans+=max(0ll,min(r2/kn,r1)-max((l2-1)/kn+1,l1)+1ll);\n            kn*=k;\n        }\n        cout<<ans<<'\\n';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2044",
    "index": "F",
    "title": "Easy Demon Problem",
    "statement": "For an arbitrary grid, Robot defines its beauty to be the sum of elements in the grid.\n\nRobot gives you an array $a$ of length $n$ and an array $b$ of length $m$. You construct a $n$ by $m$ grid $M$ such that $M_{i,j}=a_i\\cdot b_j$ for all $1 \\leq i \\leq n$ and $1 \\leq j \\leq m$.\n\nThen, Robot gives you $q$ queries, each consisting of a single integer $x$. For each query, determine whether or not it is possible to perform the following operation \\textbf{exactly} once so that $M$ has a beauty of $x$:\n\n- Choose integers $r$ and $c$ such that $1 \\leq r \\leq n$ and $1 \\leq c \\leq m$\n- Set $M_{i,j}$ to be $0$ for all ordered pairs $(i,j)$ such that $i=r$, $j=c$, or both.\n\nNote that queries are \\textbf{not persistent}, meaning that you do not actually set any elements to $0$ in the process — you are only required to output if it is possible to find $r$ and $c$ such that if the above operation is performed, the beauty of the grid will be $x$. Also, note that you must perform the operation for each query, even if the beauty of the original grid is already $x$.",
    "tutorial": "This is an anti-hash test for python sets and dictionaries. Before you call us evil, we saved you from getting hacked in open hack phase. Beware! Let's denote the beauty of the matrix as $B$, and denote $\\text{SumA}$ as the sum of all the elements in the array $a$, and $\\text{SumB}$ as the sum of all the elements in the array $b$. Before applying an operation, the beauty of the matrix can be expressed as: $B = b_1 \\cdot a_1 + b_1 \\cdot a_2 + b_1 \\cdot a_3 + b_2 \\cdot a_1 + b_2 \\cdot a_2 + \\ldots$ After factoring, this simplifies to: $B = b_1 \\cdot (a_1 + a_2 + a_3 + \\ldots) + b_2 \\cdot (a_1 + a_2 + a_3 + \\ldots) + \\ldots$ Further factoring gives: $B = (a_1 + a_2 + a_3 + a_4 + \\ldots) \\cdot (b_1 + b_2 + b_3 + \\ldots)$ This can be written as: $B = \\text{SumA} \\cdot \\text{SumB}$ Now, consider the effect of an operation on a column $C$. The beauty decreases by $A_c \\cdot \\text{SumB}$. Similarly, when an operation is done on a row $R$, the beauty decreases by $B_r \\cdot \\text{SumA}$. An important observation is that the element at position $(r, c)$ is counted twice, so we must account for this in the formula. After considering this, let the beauty after the operations be denoted as $X$. Using the observations above: $X = B - (b_i \\cdot \\text{SumA} + a_j \\cdot \\text{SumB} - a_j \\cdot b_i)$ Simplifying further: $X = \\text{SumA} \\cdot \\text{SumB} - b_i \\cdot \\text{SumA} - a_j \\cdot \\text{SumB} + a_j \\cdot b_i$ Factoring terms, we obtain: $X = \\text{SumA} \\cdot (\\text{SumB} - b_i) - a_j \\cdot (\\text{SumB} - b_i)$ Finally: $X = (\\text{SumB} - b_i) \\cdot (\\text{SumA} - a_j)$ At this stage, it is sufficient to iterate over the divisors of $X$. For each ordered pair of divisors whose product is $X$, we check whether the required values of $\\text{SumB} - b_i$ and $\\text{SumA} - a_j$ can be achieved. This can be implemented using a simple map or boolean vector for faster computation, although such optimization is not required for this problem.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define FOR(i,a,b) for (int i = (a); i < (b); ++i)\n#define F0R(i,a) FOR(i,0,a)\n#define int long long\n#define vt vector\n#define endl \"\\n\"\n\nconst int N = 4e5 + 5;\nbool apos[N], aneg[N], bpos[N], bneg[N], posspos[N], possneg[N];\n\nsigned main() {\n    ios_base::sync_with_stdio(false); \n    cin.tie(0);\n    int n,m,q;\n    cin >> n >> m >> q;\n    vector<int> a(n), b(m);\n    int asum = 0, bsum = 0;\n    F0R(i, n) {\n        cin >> a[i];\n        asum += a[i];\n    }\n    F0R(i, m) {\n        cin >> b[i];\n        bsum += b[i];\n    }\n    F0R(i, n) {\n        if(abs(asum-a[i]) < N) {\n            if(asum-a[i]<0) aneg[a[i]-asum]=true;   \n            else apos[asum-a[i]]=true;\n        } \n    }\n    F0R(i, m) {\n        if(abs(bsum-b[i]) < N) {\n            if(bsum-b[i]<0) bneg[b[i]-bsum]=true;   \n            else bpos[bsum-b[i]]=true;\n        } \n    }\n    FOR(i, 1, N) {\n        FOR(j, 1, N) {\n            if(i * j > N) break;\n            if(apos[i]&&bpos[j]) posspos[i*j]=true;\n            if(apos[i]&&bneg[j]) possneg[i*j]=true;\n            if(aneg[i]&&bpos[j]) possneg[i*j]=true;\n            if(aneg[i]&&bneg[j]) posspos[i*j]=true;\n        }\n    }\n    while(q--) {\n        int x;\n        cin >> x;\n        if(x>0) {\n            if(posspos[x]) {\n                cout << \"YES\" << endl;\n            } else {\n                cout << \"NO\" << endl;\n            }\n        } else {\n            if(possneg[-x]) {\n                cout << \"YES\" << endl;\n            } else {\n                cout << \"NO\" << endl;\n            }\n        }\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2044",
    "index": "G1",
    "title": "Medium Demon Problem (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The key difference between the two versions is highlighted in bold.}\n\nA group of $n$ spiders has come together to exchange plushies. Initially, each spider has $1$ plushie. Every year, if spider $i$ has at least one plushie, he will give exactly one plushie to spider $r_i$. Otherwise, he will do nothing. Note that all plushie transfers happen at the same time. \\textbf{In this version, if any spider has more than $1$ plushie at any point in time, they will throw all but $1$ away.}\n\nThe process is stable in the current year if each spider has the same number of plushies (before the current year's exchange) as he did the previous year (before the previous year's exchange). Note that year $1$ can never be stable.\n\nFind the first year in which the process becomes stable.",
    "tutorial": "This problem deals with a specific subclass of graphs called \"functional graphs\", also known as \"successor graphs\". The key feature that they have is that each node only has one successor. Therefore, the graph in the problem will necessarily be split into $k \\geq 1$ components, where each component necessarily contains one cycle, and each node will either be in the cycle, or it will be on a path leading towards the cycle. Observe that if a node that is not on a cycle currently has a plushie, this plushie will cause the arrangement to be unstable until the plushie reaches the cycle. Proof: suppose node $u$ has the plushie on day $i$. On the next day, $u$ will no longer have this plushie, because they will have passed it down to $r_u$, therefore, the arrangement has changed. This continues inductively until the plushie reaches the cycle of its component. From this, we know that the answer is at least the distance of any node to the cycle. Now, since every node in the cycle already has a plushie, we know that these plushies just get passed round and round, so actually, nodes within the cycle cannot change the answer. Therefore, we've already found the final answer.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\n\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt;\n    cin>>tt;\n    while(tt--)\n    {\n        int n;\n        cin>>n;\n        vector<int> r(n+1),d(n+1);\n        for(int i=1;i<=n;i++)\n        {\n            cin>>r[i];\n            d[r[i]]++;\n        }\n        set<pair<int,int> > s;\n        for(int i=1;i<=n;i++)\n            s.insert({d[i],i});\n        int ans=2;\n        queue<int> q;\n        while(!s.empty()&&(*s.begin()).first==0)\n        {\n            while(!s.empty()&&(*s.begin()).first==0)\n            {\n                int k=(*s.begin()).second;\n                auto it=s.find({d[r[k]],r[k]});\n                d[r[k]]--;\n                if(it!=s.end())\n                {\n                    s.erase(it);\n                    q.push(r[k]);\n                }\n                s.erase(s.begin());\n            }\n            while(!q.empty())\n                s.insert({d[q.front()],q.front()}),q.pop();\n            ans++;\n        }\n        cout<<ans<<'\\n';\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graph matchings",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2044",
    "index": "G2",
    "title": "Medium Demon Problem (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The key difference between the two versions is highlighted in bold.}\n\nA group of $n$ spiders has come together to exchange plushies. Initially, each spider has $1$ plushie. Every year, if spider $i$ has at least one plushie, he will give exactly one plushie to spider $r_i$. Otherwise, he will do nothing. Note that all plushie transfers happen at the same time. \\textbf{In this version, each spider is allowed to have more than 1 plushie at any point in time.}\n\nThe process is stable in the current year if each spider has the same number of plushies (before the current year's exchange) as he did the previous year (before the previous year's exchange). Note that year $1$ can never be stable.\n\nFind the first year in which the process becomes stable.",
    "tutorial": "Note that similarly to G1, once all plushies end up in the hands of spiders who are in a loop, the process becomes stable. Let's model the input as a collection of rooted forests. For each spider $i$, if $i$ is part of a loop, then let's compress the loop into a single node and use that as the root of a tree. Otherwise, if spider $i$ gives a present to spider $r_i$, then let's draw an edge from $i$ to $r_i$. Now, let $i$ be any node that is not part of a loop. How long will it take until spider $i$ runs out of presents? We can see that it is the subtree size of $i$, as one present leaves the subtree each year. Thus, our challenge now is to process the nodes in an efficient order such that we can find the subtree size of all nodes. This can be done with topological sorting, which gives us an order that processes all nodes starting from the leaf upwards. After the topological sort, we may do dynamic programming to find subtree sizes of all nodes. Let $dp[i]$ be the number of days until spider $i$ runs out of presents. Let's suppose that we already calculated $dp[i]$ (we initialize it to be $1$ for all nodes since each spider starts with a present). Then, we should add $dp[i]$ to $dp[r_i]$. Doing this and adding up all $dp$ values of nodes directly before a cycle will yield the answer.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nusing namespace std;\n\n\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int tt;\n    cin>>tt;\n    while(tt--)\n    {\n        int n;\n        cin>>n;\n        vector<int> r(n+1),d(n+1),v(n+1,1);\n        for(int i=1;i<=n;i++)\n        {\n            cin>>r[i];\n            d[r[i]]++;\n        }\n        set<pair<int,int> > s;\n        for(int i=1;i<=n;i++)\n        {\n            s.insert({d[i],i});\n        }\n        int ans=2;\n        queue<int> q;\n        while(!s.empty()&&(*s.begin()).first==0)\n        {\n            while(!s.empty()&&(*s.begin()).first==0)\n            {\n                int k=(*s.begin()).second;\n                ans=max(ans,v[k]+2);v[r[k]]+=v[k];\n                auto it=s.find({d[r[k]],r[k]});\n                d[r[k]]--;\n                if(it!=s.end())\n                {\n                    s.erase(it);\n                    q.push(r[k]);\n                }\n                s.erase(s.begin());\n            }\n            while(!q.empty())\n                s.insert({d[q.front()],q.front()}),q.pop();\n        }\n        cout<<ans<<'\\n';\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2044",
    "index": "H",
    "title": "Hard Demon Problem",
    "statement": "Swing is opening a pancake factory! A good pancake factory must be good at flattening things, so Swing is going to test his new equipment on 2D matrices.\n\nSwing is given an $n \\times n$ matrix $M$ containing positive integers. He has $q$ queries to ask you.\n\nFor each query, he gives you four integers $x_1$, $y_1$, $x_2$, $y_2$ and asks you to flatten the submatrix bounded by $(x_1, y_1)$ and $(x_2, y_2)$ into an array $A$. Formally, $A = [M_{(x1,y1)}, M_{(x1,y1+1)}, \\ldots, M_{(x1,y2)}, M_{(x1+1,y1)}, M_{(x1+1,y1+1)}, \\ldots, M_{(x2,y2)}]$.\n\nThe following image depicts the flattening of a submatrix bounded by the red dotted lines. The orange arrows denote the direction that the elements of the submatrix are appended to the back of $A$, and $A$ is shown at the bottom of the image.\n\nAfterwards, he asks you for the value of $\\sum_{i=1}^{|A|} A_i \\cdot i$ (sum of $A_i \\cdot i$ over all $i$).",
    "tutorial": "Consider translating the sum back onto the matrix. For simplicity we discuss about querying the whole matrix. The sum we would like to find is $\\sum_i i\\cdot A_i$. Here, $A_i$ corresponds to $M_{(x,y)}$, so we will translate this to $\\sum_{x,y} i\\cdot M_{(x,y)}$. The issue left is on the $i$ multiplied to it. Remember that we index the entries in increasing order of $y$, and then increasing order of $x$. Assuming $y$ and $x$ were $0$-indexed, this will mean entry $(x,y)$ corresponds to $x\\cdot n + y$ (also $0$-indexed). You can notice that this naturally corresponds to the order we had defined as well. Then, what we want to find is $\\sum_{x,y} (x \\cdot n + y + 1)\\cdot M_{(x,y)}$. Notice $x \\cdot n$, $y$, $1$ are independent, and we can split them into sums $\\sum_x x \\cdot n \\cdot M_{(x,y)}$, $\\sum_y y \\cdot M_{(x,y)}$, $\\sum M_{(x,y)}$. Each of these three sums can be precomputed entry by entry, and a 2D prefix sum can solve the answer for the entire matrix. The query for a submatrix is very similar. Formally, you have to care about: That we have $y_2-y_1+1$ columns instead of $n$ now; That the precomputed values might not start from $0$ on the first row/column of the query. Still, these two issues can be fixed using the three sums we have precomputed. The time complexity becomes $\\mathcal{O}(n^2+q)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n\nvoid tc () {\n    ll n, Q;\n    cin >> n >> Q;\n    vector <vll> mat(n, vll(n));\n    for (vll &ve : mat) {\n        for (ll &i : ve) cin >> i;\n    }\n    vector <vll> psR(n, vll(n+1)), psRr(n, vll(n+1)), psRc(n+1, vll(n+1)), ps(n+1, vll(n+1)), psRrc(n+1, vll(n+1));\n    for (ll i = 0; i < n; i++) {\n        for (ll j = 0; j < n; j++) {\n            psR[i][j+1] = psR[i][j] + mat[i][j];\n        }\n    }\n    for (ll i = 0; i < n; i++) {\n        for (ll j = 0; j < n; j++) {\n            psRr[i][j+1] = psRr[i][j] + mat[i][j]*(j+1);\n        }\n    }\n    for (ll i = 0; i < n; i++) {\n        for (ll j = 0; j <= n; j++) {\n            psRc[i+1][j] = psRc[i][j] + psR[i][j]*(i+1);\n        }\n    }\n    for (ll i = 0; i < n; i++) {\n        for (ll j = 0; j <= n; j++) {\n            psRrc[i+1][j] = psRrc[i][j] + psRr[i][j];\n        }\n    }\n    for (ll i = 0; i < n; i++) {\n        for (ll j = 0; j <= n; j++) {\n            ps[i+1][j] = ps[i][j] + psR[i][j];\n        }\n    }\n    while (Q--) {\n        ll x1, y1, x2, y2;\n        cin >> x1 >> y1 >> x2 >> y2;\n        x1--; y1--; x2--; y2--;\n        ll ans = 0;\n        ans += -(ps[x2+1][y2+1]-ps[x2+1][y1]-ps[x1][y2+1]+ps[x1][y1])*x1*(y2-y1+1);\n        ans += (psRc[x2+1][y2+1] - psRc[x1][y2+1] - (ps[x2+1][y2+1]-ps[x1][y2+1]))*(y2-y1+1);\n\n        ans += (psRc[x2+1][y1] - psRc[x1][y1] - (ps[x2+1][y1]-ps[x1][y1]))*-(y2-y1+1);\n        ans += (ps[x2+1][y2+1]-ps[x1][y2+1])*-y1;\n        ans += (ps[x2+1][y1]-ps[x1][y1])*y1;\n\n        ans += psRrc[x2+1][y2+1] - psRrc[x1][y2+1];\n        ans +=-(psRrc[x2+1][y1] - psRrc[x1][y1]);\n        cout << ans << ' ';\n    }\n    cout << '\\n';\n}\n\nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2046",
    "index": "A",
    "title": "Swap Columns and Find a Path",
    "statement": "There is a matrix consisting of $2$ rows and $n$ columns. The rows are numbered from $1$ to $2$ from top to bottom; the columns are numbered from $1$ to $n$ from left to right. Let's denote the cell on the intersection of the $i$-th row and the $j$-th column as $(i,j)$. Each cell contains an integer; initially, the integer in the cell $(i,j)$ is $a_{i,j}$.\n\nYou can perform the following operation any number of times (possibly zero):\n\n- choose two columns and swap them (i. e. choose two integers $x$ and $y$ such that $1 \\le x < y \\le n$, then swap $a_{1,x}$ with $a_{1,y}$, and then swap $a_{2,x}$ with $a_{2,y}$).\n\nAfter performing the operations, you have to choose a path from the cell $(1,1)$ to the cell $(2,n)$. For every cell $(i,j)$ in the path except for the last, the next cell should be either $(i+1,j)$ or $(i,j+1)$. Obviously, the path cannot go outside the matrix.\n\nThe cost of the path is the sum of all integers in all $(n+1)$ cells belonging to the path. You have to perform the operations and choose a path so that its cost is \\textbf{maximum} possible.",
    "tutorial": "We can divide the columns in the matrix into three different groups: the columns where we go through the top cell; the columns where we go through the bottom cell; the columns where we go through both cells. There should be exactly one column in the $3$-rd group - this will be the column where we shift from the top row to the bottom row. However, all other columns can be redistributed between groups $1$ and $2$ as we want: if we want to put a column into the $1$-st group, we put it before the column where we go down; otherwise, we put it after the column where we go down. So, we can get any distribution of columns between the $1$-st and the $2$-nd group. Now let's consider the contribution of each column to the answer. Columns from the $1$-st group add $a_{1,i}$ to the answer, columns from the $2$-nd group add $a_{2,i}$, the column from the $3$-rd group adds both of these values. So, we can iterate on the index of the column where we go down, take $a_{1,i} + a_{2,i}$ for it, and take $\\max(a_{1,j}, a_{2,j})$ for every other column. This works in $O(n^2)$, and under the constraints of the problem, it is enough. However, it is possible to solve the problem in $O(n)$. To do so, calculate the sum of $\\max(a_{1,j}, a_{2,j})$ over all columns. Then, if we pick the $i$-th column as the column where we go down, the answer be equal to this sum, plus $\\min(a_{1,i}, a_{2,i})$, since this will be the only column where we visit both cells.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = []\n    for i in range(2):\n        a.append(list(map(int, input().split())))\n    best = [max(a[0][i], a[1][i]) for i in range(n)]\n    full = [a[0][i] + a[1][i] for i in range(n)]\n    sum_best = sum(best)\n    ans = -10 ** 19\n    for i in range(n):\n        ans = max(ans, sum_best + full[i] - best[i])\n    print(ans)",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2046",
    "index": "B",
    "title": "Move Back at a Cost",
    "statement": "You are given an array of integers $a$ of length $n$. You can perform the following operation zero or more times:\n\n- In one operation choose an index $i$ ($1 \\le i \\le n$), assign $a_i := a_i + 1$, and then move $a_i$ to the back of the array (to the rightmost position). For example, if $a = [3, 5, 1, 9]$, and you choose $i = 2$, the array becomes $[3, 1, 9, 6]$.\n\nFind the lexicographically smallest$^{\\text{∗}}$ array you can get by performing these operations.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $c$ is lexicographically smaller than an array $d$ if and only if one of the following holds:\n\n- $c$ is a prefix of $d$, but $c \\ne d$; or\n- in the first position where $c$ and $d$ differ, the array $c$ has a smaller element than the corresponding element in $d$.\n\n\\end{footnotesize}",
    "tutorial": "The first idea is to notice, that each element is moved to the back at most once. Indeed, if we fix a subset of elements that we ever move to the back, we can perform the operation once on each of them in any order we like, and that becomes their final order with the smallest possible increase. The optimal order is, of course, the increasing order. The question is how to select this subset of elements to move to the back. Since we need the lexicographically smallest array, we're looking for some greedy approach that chooses the smallest possible element on the next position one by one, left to right. What's the smallest number our resulting array can start with? Of course, the minimum. That means, all the elements in front of the minimum have to be moved to the back and be increased by one. What's the smallest number we can have on the second place, given that we have the minimum in the first positions? Either the smallest element to the right of the minimum, or the smallest element among those already moved to the back. ... Analysing this approach, we see that as we go left to right, we keep picking elements from the suffix minima sequence, and keep growing the set of elements we have to move to the right to ''extract'' this sequence from the initial array. At one point, the next smallest element comes not from the suffix minima sequence, but from the pile of integers we move to the right. At this point, all the remaining elements have to be moved to the right once (that is, increased by $1$), and then listed in sorted order. So, the answer is always several first elements of the suffix minima sequence, starting from the global minimum, and then all other elements, increased by $1$ and sorted in increased order. To find the point where we switch from the suffix minima sequence to the moved elements, it is convenient to precomute the minima, and keep a set of those elements we already move to the right. This solution runs in $O(n \\log n)$, along with many other.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#ifdef LOCAL\n    #define eprintf(...) fprintf(stderr, __VA_ARGS__)\n#else\n    #define eprintf(...) 42\n#endif\n\nusing ll = long long;\nusing ld = long double;\nusing D = double;\nusing uint = unsigned int;\ntemplate<typename T>\nusing pair2 = pair<T, T>;\n\n#define pb push_back\n#define mp make_pair\n#define all(x) (x).begin(),(x).end()\n#define fi first\n#define se second\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nvoid solve()\n{\n\tint n;\n\tscanf(\"%d\", &n);\n\tvector<int> a(n);\n\tfor (int i = 0; i < n; i++) scanf(\"%d\", &a[i]);\n\tvector<int> front(n);\n\tint frontfront = n;\n\tint frontback = n;\n\tmultiset<int> back;\n\tfor (int i = n - 1; i >= 0; i--)\n\t{\n\t\tif (frontfront >= frontback || a[i] <= front[frontfront]) front[--frontfront] = a[i];\n\t\telse back.insert(a[i] + 1);\n\t\twhile (frontfront < frontback && !back.empty() && front[frontback - 1] > *back.begin())\n\t\t{\n\t\t\tback.insert(front[frontback - 1] + 1);\n\t\t\tfrontback--;\n\t\t}\n\t}\n\tvector<int> answer;\n\tfor (int i = frontfront; i < frontback; i++) answer.pb(front[i]);\n\tfor (auto t : back) answer.pb(t);\n\tfor (auto t : answer) printf(\"%d \", t);\n\tprintf(\"\n\");\n}\n\nint main()\n{\n    int NT = 1;\n    scanf(\"%d\", &NT);\n    for (int T = 1; T <= NT; T++)\n    {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2046",
    "index": "C",
    "title": "Adventurers",
    "statement": "Once, four Roman merchants met in a Roman mansion to discuss their trading plans. They faced the following problem: they traded the same type of goods, and if they traded in the same city, they would inevitably incur losses. They decided to divide up the cities between them where they would trade.\n\nThe map of Rome can be represented in this problem as a plane with certain points marked — the cities of the Roman Empire.\n\nThe merchants decided to choose a certain dividing point $(x_0, y_0)$. Then, in a city with coordinates $(x_i, y_i)$,\n\n- the first merchant sells goods if $x_0 \\le x_i$ and $y_0 \\le y_i$;\n- the second merchant sells goods if $x_0 > x_i$ and $y_0 \\le y_i$;\n- the third merchant sells goods if $x_0 \\le x_i$ and $y_0 > y_i$;\n- the fourth merchant sells goods if $x_0 > x_i$ and $y_0 > y_i$.\n\nThe merchants want to choose $(x_0, y_0)$ in such a way as to \\textbf{maximize the smallest number of cities} that any of them gets (i. e., as fair as possible). Please find such a point for them.",
    "tutorial": "First, we will use the idea of binary search on the answer. Let's assume we are currently checking if we can achieve the answer $k$. We will iterate over all the necessary coordinates of the vertical lines. To do this, we note that it makes sense to iterate only over those where the lines coincide in the Y-coordinate with at least one of the points. It is obvious that in this case, the necessary vertical lines will be on the order of $O(n)$. During the iteration over the vertical line, we will maintain two segment trees for the sum: one for the left half of the plane and the other for the right. $t_y$ in each of the segment trees will represent how many points have a Y-coordinate of $y$ in the corresponding half of the plane. In each of the segment trees, we will check if it is possible to divide the half-plane into two parts by a line parallel to the x-axis, so that there are at least $k$ points in both parts; and if this is possible, we will find the set of suitable lines - it will obviously be some segment $[y_{l}, \\, y_{r}]$. If the intersection of the resulting segments in both segment trees is not empty, then we have found the answer. This can be done by descending the tree in $O(\\log n)$ time. Thus, the total time complexity of the described solution is $O(n \\log^2 n)$.",
    "code": "#include <math.h>\n#include <unordered_set>\n#include <unordered_map>\n#include <map>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <set>\n#include <array>\n#include <cstring>\n#include <ctime>\n#include <cassert>\n#include <string_view>\n#include <functional>\n#include <sstream>\n#include <numeric>\n#include <cmath>\n#include <deque>\n#include <list>\n#include <algorithm>\n#include <iomanip>\n \nusing namespace std;\n \nusing i64 = long long;\nusing ui32 = unsigned int;\nusing ui64 = unsigned long long;\n \n#define all(a) (a).begin(), (a).end()\n \n \nstruct Tree;\n \nTree* NewNode();\n \nstruct Count {\n    int left = 0;\n    int right = 0;\n    void Add(int delta) {\n        left += delta;\n        if (delta < 0) {\n            right -= delta;\n        }\n    }\n    void operator += (const Count& c) {\n        left += c.left;\n        right += c.right;\n    }\n \n    int GetMin() {\n        return min(left, right);\n    }\n};\n \nstruct Tree {\n        Count count;\n        Tree* left = nullptr;\n        Tree* right = nullptr;\n \n        void Add(int l, int r, int p, int delta = 1) {\n            count.Add(delta);\n            if (r - l == 1) {\n                return;\n            }\n            int mid = (l + r) / 2;\n            if (p < mid) {\n                if (left == nullptr) {\n                    left = NewNode();\n                }\n                left->Add(l, mid, p, delta);\n            } else {\n                if (right == nullptr) {\n                    right = NewNode();\n                }\n                right->Add(mid, r, p, delta);\n            }\n        } \n \n        Count LeftCount() {\n            if (left) {\n                return left->count;\n            }\n            return {};\n        }\n        Count RightCount() {\n            if (right) {\n                return right->count;\n            }\n            return {};\n        }\n \n        void Remove(int l, int r, int p) {\n            Add(l, r, p, -1);\n        }\n};\n \nTree nodes[7000000];\n \nTree* NewNode() {\n    static Tree* nextNode = nodes;\n    return nextNode++;\n}\n \n \nstruct Solver {\n    struct Point {\n        int x, y;\n        bool operator < (const Point& p) const {\n            return x < p.x;\n        }\n    };\n \n    int max = 0;\n    int bx = 0;\n    int by = 0;\n \n    bool FindBest(int l, int r, Tree* node, const Count& left = {}, const Count& right = {}) {\n        if (node == nullptr) {\n            return false;\n        }\n        int mid = (l + r) / 2;\n        Count newLeft = node->LeftCount();\n        Count newRight = node->RightCount();\n        newLeft += left;\n        newRight += right;\n        int mn = min(newLeft.GetMin(), newRight.GetMin());\n        bool updated = false;\n        if (mn > max) {\n            max = mn;\n            by = mid;\n            updated = true;\n        }\n        if (mn == newLeft.GetMin()) {\n            if (FindBest(mid, r, node->right, newLeft, right)) {\n                return true;\n            }\n        } else {\n            if (FindBest(l, mid, node->left, left, newRight)) {\n                return true;\n            }\n        }\n        return updated;\n    }\n \n    void Solve(istream& cin, ostream& cout) {\n        int n;\n        cin >> n;\n        vector<Point> a(n);\n        int t9 = 1000000001;\n        #ifdef pperm\n            t9 = 100;\n        #endif\n        Tree* tree = NewNode();\n        for (Point& p : a) {\n            cin >> p.x >> p.y;\n            tree->Add(-t9, t9, p.y);\n        }\n        sort(all(a));\n        for (int i = 0; i < n;) {\n            int j = i + 1;\n            while (j < n && a[j].x == a[i].x) {\n                ++j;\n            }\n            if (FindBest(-t9, t9, tree)) {\n                bx = a[i].x;\n            }\n            for (;i < j; ++i) {\n                tree->Remove(-t9, t9, a[i].y);\n \n            }\n        }\n        cout << max << '\n' << bx << ' ' << by << endl;\n    }\n};\n \nint main(int argc, char* args[]) {\n#ifdef pperm\n    ifstream cin(\"/home/pperm86/My/Codeforces/input.txt\");\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n#ifndef pperm\n    srand(time(0));\n#endif\n    int T = 1;\n    cin >> T;\n    for (int iTest = 1; iTest <= T; ++iTest) {\n\t\tSolver solver{};\n        solver.Solve(cin, cout);\n    }\n#ifdef pperm\n    cout << clock() / static_cast<double>(CLOCKS_PER_SEC) << endl;\n#endif\n    return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "sortings",
      "ternary search",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2046",
    "index": "D",
    "title": "For the Emperor!",
    "statement": "In Ancient Rome, a plan to defeat the barbarians was developed, but for its implementation, each city must be informed about it.\n\nThe northern part of the Roman Empire consists of $n$ cities connected by $m$ one-way roads. Initially, the $i$-th city has $a_i$ messengers, and each messenger can freely move between cities following the existing roads. A messenger can carry a copy of the plan with him and inform the cities he visits, and can make unlimited copies for other messengers in the city he is currently in.\n\nAt the start, you will produce some number of plans and deliver them to messengers of your choice. Your goal is to make sure that every city is visited by a messenger with a plan. Find the smallest number of the plans you need to produce originally, so that the messengers will deliver them to every city, or determine that it is impossible to do so at all.",
    "tutorial": "We will compress the graph into strongly connected components. Inside a component, each runner can move between any pair of vertices and thus visit all. We will now solve the problem for a directed acyclic graph. We will check for the existence of an answer. Suppose all runners already know the winning plan, and we will try to send them out so that each vertex is visited at least once. To do this, it is necessary to decompose the graph into paths such that: each vertex belongs to at least one path; no more than $a[i]$ paths start at each vertex (where $a[i]$ is the number of runners initially located at the vertex); paths may intersect. Take the source $s$ and the sink $t$, and now a path can be represented as a sequence $s$, $u_1$, ..., $u_k$, $t$. We will divide $u$ into $u_{in}$ and $u_{out}$ and will consider that a vertex $u$ belongs to least one transition from $u_{in}$ to $u_{out}$. We will draw the following edges: from $s$ to $u_{in}$ with capacity $cap = a[u]$; from $u_{in}$ to $u_{out}$ with $cap = inf$ and the condition of flow through the edge $f \\geq 1$; from $u_{out}$ to $t$ with $cap = inf$; from $u_{out}$ to $v_{in}$ with $cap = inf$ for all edges (u, v) in the original graph. This is equivalent to finding a flow with constraints in this graph. To do this, we will create a dummy source $s'$ and sink $t'$, and now for each edge $(u_{in}, u_{out})$ with flow through it $1 \\le f \\le inf$, we will make the following replacements by drawing edges: from $u_{in}$ to $u_{out}$ with $cap = inf - 1$; from $s'$ to $u_{out}$ with $cap = 1$; from $u_{in}$ to $t'$ with $cap = 1$; from $t$ to $s$ with $cap = inf$. Finding a flow that satisfies the constraints is equivalent to finding the maximum flow from $s'$ to $t'$, and if it equals the number of vertices, then the answer exists; otherwise, we can output $-1$ at this step. Now we minimize the number of runners who initially know the plan. Note that: it makes no sense for runners to move until they know the plan; it makes no sense to pass the plan to more than one runner from one city. We try to take this into account when constructing. Instead of adding edges from the source to $u_{in}$, we will do the following: create a vertex $u_{cnt}$ to control the number of runners and draw edges: from $s$ to $u_{cnt}$ with $cap = a[u]$; from $u_{cnt}$ to $u_{out}$ with $cap = a[u]$; from $u_{cnt}$ to $u_{in}$ with $cap = 1$, $cost = 1$. assign zero cost to all other edges. This is equivalent to ensuring that all $a[i]$ runners learn the plan, but if no one comes to our city, we will personally tell exactly one runner from this number, paying $cost=1$ for that person. The answer to the problem is the minimum cost of the maximum flow from $s'$ to $t'$ with this graph construction. The proof follows from the graph construction. MCMF can be considered as $O(n^2m^2)$ or $O(n^3m)$ for any graphs, but it is worth noting that the flow value $f$ is limited to $n$, and we have a solution in $O(fnm)$ using Ford-Bellman or $O(fm\\log n)$ using Dijkstra's algorithm with potentials. Interestingly, we note that as a result, we obtained $3n$ vertices and $m + 7n$ edges. With careful implementation, MCMF fits well within TL.",
    "code": "#define _CRT_SECURE_NO_WARNINGS\n\n#include<iostream>\n#include<fstream>\n#include<vector>\n#include<stack>\n#include<queue>\n#include<set>\n#include<map>\n#include<array>\n#include<unordered_set>\n#include<unordered_map>\n#include<cstring>\n#include<string>\n#include<memory>\n#include<iomanip>\n#include<cassert>\n#include<cmath>\n#include<random>\n#include<algorithm>\n#include<chrono>\n\n#pragma GCC optimize(\"O3,unroll-loops\")\n#pragma GCC target(\"avx2,bmi,bmi2,lzcnt,popcnt\")\n\n#define int long long\n#define ld long double\n#define endl '\n'\n\nusing namespace std;\n\n\nconstexpr int N = 500;\nvector<int> g[N], gr[N], gcmp[N];\nint a[N], acmp[N], used[N], color[N], cur_color = 0;\nvector<int> order, cmp;\n\nvoid dfs1(int u) {\n\tfor (int v : g[u]) {\n\t\tif (used[v] == 0) {\n\t\t\tused[v] = 1;\n\t\t\tdfs1(v);\n\t\t}\n\t}\n\torder.push_back(u);\n}\n\nvoid dfs2(int u) {\n\tfor (int v : gr[u]) {\n\t\tif (used[v] == 0) {\n\t\t\tused[v] = 1;\n\t\t\tdfs2(v);\n\t\t}\n\t}\n\tcolor[u] = cur_color;\n}\n\ninline array<int, 3> getInd(int u) {\n\treturn { 3 * u, 3 * u + 1, 3 * u + 2 };\n}\n\nconstexpr int INF = 0x3f3f3f3f;\n\nstruct MCMF {\n\tstruct rib {\n\t\tint b, u, c, f;\n\t\tsize_t back;\n\t};\n\n\tMCMF(int size) : n(size), g_mcmf(size) {};\n\n\tint n;\n\tvector<vector<rib>> g_mcmf;\n\n\tvoid rebuild(int sz) {\n\t\tn = sz, g_mcmf.clear(); g_mcmf.resize(sz);\n\t}\n\n\tvoid add_rib(int a, int b, int u, int c) {\n\t\trib r1 = { b, u, c, 0, g_mcmf[b].size() };\n\t\trib r2 = { a, 0, -c, 0, g_mcmf[a].size() };\n\t\tg_mcmf[a].push_back(r1);\n\t\tg_mcmf[b].push_back(r2);\n\t}\n\n\tpair<int, int> get_flow(int s, int t, int maxflow = INF) {\n\t\tint flow = 0, cost = 0;\n\t\twhile (flow < maxflow) {\n\t\t\tvector<int> id(n, 0);\n\t\t\tvector<int> d(n, INF);\n\t\t\tvector<int> q(n);\n\t\t\tvector<int> p(n);\n\t\t\tvector<size_t> p_rib(n);\n\t\t\tint qh = 0, qt = 0;\n\t\t\tq[qt++] = s;\n\t\t\td[s] = 0;\n\t\t\twhile (qh != qt) {\n\t\t\t\tint v = q[qh++];\n\t\t\t\tid[v] = 2;\n\t\t\t\tif (qh == n)  qh = 0;\n\t\t\t\tfor (size_t i = 0; i < g_mcmf[v].size(); ++i) {\n\t\t\t\t\trib& r = g_mcmf[v][i];\n\t\t\t\t\tif (r.f < r.u && d[v] + r.c < d[r.b]) {\n\t\t\t\t\t\td[r.b] = d[v] + r.c;\n\t\t\t\t\t\tif (id[r.b] == 0) {\n\t\t\t\t\t\t\tq[qt++] = r.b;\n\t\t\t\t\t\t\tif (qt == n)  qt = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (id[r.b] == 2) {\n\t\t\t\t\t\t\tif (--qh == -1)  qh = n - 1;\n\t\t\t\t\t\t\tq[qh] = r.b;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tid[r.b] = 1;\n\t\t\t\t\t\tp[r.b] = v;\n\t\t\t\t\t\tp_rib[r.b] = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (d[t] == INF)  break;\n\t\t\tint addflow = maxflow - flow;\n\t\t\tfor (int v = t; v != s; v = p[v]) {\n\t\t\t\tint pv = p[v];  size_t pr = p_rib[v];\n\t\t\t\taddflow = min(addflow, g_mcmf[pv][pr].u - g_mcmf[pv][pr].f);\n\t\t\t}\n\t\t\tfor (int v = t; v != s; v = p[v]) {\n\t\t\t\tint pv = p[v];  size_t pr = p_rib[v], r = g_mcmf[pv][pr].back;\n\t\t\t\tg_mcmf[pv][pr].f += addflow;\n\t\t\t\tg_mcmf[v][r].f -= addflow;\n\t\t\t\tcost += g_mcmf[pv][pr].c * addflow;\n\t\t\t}\n\t\t\tflow += addflow;\n\t\t}\n\t\treturn { flow, cost };\n\t}\n};\n\nvoid solve() {\n\t\n\tfor (int i =0 ; i < N; i++)\n\t{\n\t\tg[i] = {};\n\t\tgr[i] = {};\n\t\tgcmp[i] = {};\n\t}\n\tmemset(a, 0, sizeof a);\n\tmemset(acmp, 0, sizeof acmp);\n\tmemset(used, 0, sizeof used);\n\tmemset(color, 0, sizeof color);\n\tcur_color = 0;\n\torder = {};\n\tcmp = {};\n\t\n\tint n, m; cin >> n >> m;\n\tfor (int i = 0; i < n; i++) {\n\t\tg[i].clear();\n\t\tgr[i].clear();\n\t}\n\n\tfor (int i = 0; i < n; i++) cin >> a[i];\n\n\tfor (int i = 0; i < m; i++) {\n\t\tint u, v; cin >> u >> v; u--, v--;\n\t\tg[u].push_back(v);\n\t\tgr[v].push_back(u);\n\t}\n\n\torder.clear();\n\tmemset(used, 0, sizeof(used[0]) * n);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (used[i] == 0) {\n\t\t\tused[i] = 1;\n\t\t\tdfs1(i);\n\t\t}\n\t}\n\n\tmemset(used, 0, sizeof(used[0]) * n);\n\tfor (int i = 0; i < n; i++) {\n\t\tint u = order[n - i - 1];\n\t\tif (used[u] == 0) {\n\t\t\tused[u] = 1;\n\t\t\tdfs2(u);\n\t\t\tcur_color++;\n\t\t}\n\t}\n\n\t// for (int i = 0; i < n; i++) cout << color[i] << \" \"; cout << endl;\n\n\tmemset(acmp, 0, sizeof(acmp[0]) * cur_color);\n\tfor (int i = 0; i < n; i++) {\n\t\tacmp[color[i]] += a[i];\n\t\tfor (int v : g[i]) {\n\t\t\tif (color[i] != color[v]) {\n\t\t\t\tgcmp[color[i]].push_back(color[v]);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 0; i < cur_color; i++) {\n\t\tauto& e = gcmp[i];\n\t\tsort(e.begin(), e.end());\n\t\te.erase(unique(e.begin(), e.end()), e.end());\n\n\t\t// cout << i << \" \" << acmp[i] << \": \";\n\t\t// for (int v : e) cout << v << \" \"; cout << endl;\n\t}\n\n\tint s = 3 * cur_color, t = s + 1, so = t + 1, to = so + 1;\n\tMCMF gg(to + 1);\n\n\tfor (int i = 0; i < cur_color; i++) {\n\t\tauto [uin, uout, ucnt] = getInd(i);\n\t\tgg.add_rib(s, ucnt, acmp[i], 0);\n\t\tgg.add_rib(ucnt, uin, 1, 1);\n\t\tgg.add_rib(ucnt, uout, INF, 0);\n\n\t\tgg.add_rib(uin, uout, INF, 0);\n\t\tgg.add_rib(uout, t, INF, 0);\n\n\t\tgg.add_rib(so, uout, 1, 0);\n\t\tgg.add_rib(uin, to, 1, 0);\n\t}\n\n\tgg.add_rib(t, s, INF, 0);\n\n\tfor (int i = 0; i < cur_color; i++) {\n\t\tauto [uin, uout, ucnt] = getInd(i);\n\t\tfor (int v : gcmp[i]) {\n\t\t\tauto [vin, vout, vcnt] = getInd(v);\n\t\t\tgg.add_rib(uout, vin, INF, 0);\n\t\t}\n\t}\n\n\tauto [flow, cost] = gg.get_flow(so, to);\n\t// cout << flow << \" \" << cost << endl;\n\n\tif (flow < cur_color) {\n\t\tcout << -1 << endl;\n\t\treturn;\n\t}\n\n\tcout << cost << endl;\n}\n\nsigned main() {\n\t// freopen(\"input.txt\", \"r\", stdin);\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0); cout.tie(0);\n\n\tint q; cin >> q; while (q--)\n\tsolve();\n}",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2046",
    "index": "E2",
    "title": "Cheops and a Contest (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $m$ is arbitrary. You can hack only if you solved all versions of this problem.}\n\nThere is a problem-solving competition in Ancient Egypt with $n$ participants, numbered from $1$ to $n$. Each participant comes from a certain city; the cities are numbered from $1$ to $m$. There is at least one participant from each city.\n\nThe $i$-th participant has strength $a_i$, specialization $s_i$, and wisdom $b_i$, so that $b_i \\ge a_i$. Each problem in the competition will have a difficulty $d$ and a unique topic $t$. The $i$-th participant will solve the problem if\n\n- $a_i \\ge d$, i.e., their strength is not less than the problem's difficulty, or\n- $s_i = t$, and $b_i \\ge d$, i.e., their specialization matches the problem's topic, and their wisdom is not less than the problem's difficulty.\n\nCheops wants to choose the problems in such a way that each participant from city $i$ will solve strictly more problems than each participant from city $j$, for all $i < j$.\n\nPlease find a set of at most $5n$ problems, where the \\textbf{topics of all problems are distinct}, so that Cheops' will is satisfied, or state that it is impossible.",
    "tutorial": "For convenience, we will call groups that include certain cities. The key condition is that each specialization can correspond to no more than one task. Thus, cities from different groups must have \"practically sorted\" strength values as the group order increases. Let $[l_i, r_i]$ denote the segment that includes all the strengths of the cities in group $i$, where $r_i$ is the maximum strength of a city from this group, and $l_i$ is the minimum. If $l_i \\le r_{i+2}$, it is impossible to build a contest, as there must be at least a difference of 2 tasks between the cities corresponding to $l_i$ and $r_{i+2}$, but they can differ by at most 1 task in specialization. After this, the problem reduces to considering two neighboring groups and subsequently checking the task difficulties for compliance with the linear conditions of each group. Let's consider two cases: If $l_i \\ge r_{i+1}$, it is sufficient to add a few tasks (specifically, just 2) of difficulty from the segment $[r_{i+1} + 1, l_i]$ to maintain order. Otherwise, each city in the $i$-th group that lies in the intersection must solve a task with its specialization. In this case, no task can be in the segment $[l_i + 1, r_{i+1}]$, as the city with the highest strength in group $i+1$ will solve at least as many tasks as the weakest city in group $i$, which we cannot allow. To maintain order with the other groups, it is sufficient to add 2 tasks of difficulty $r_{i+1} + 1$ (unlike the first case, due to the fact that $l_i \\le r_{i+2}$ cannot occur, we can immediately determine the appropriate task difficulty, but they can be arranged using the same algorithm as for the first case). It can be noted that when adding pairs of tasks, they need to choose an unused specification (since we are not using it in principle, but otherwise it may cause collisions). We conclude that we need to arrange tasks with a specified specification that a city from the intersection of groups can solve, meaning its difficulty must not exceed the wisdom of that city, and also arrange 2 tasks of certain difficulties to maintain order between groups. These difficulties arise from possible intersections with other groups when using $r_{i+1} + 1$ as the task difficulty and possible specification collisions of cities, which may allow a city from a weaker group to solve a task that we did not intend for it, thus violating the strictness conditions between groups. Most problems cannot arise when $m=2$, so what has been said above is already a solution (without minor adjustments) to the simple version of the problem. First, we will solve how to choose the difficulty for tasks with a specific specification. To do this, we will prohibit using the task specification corresponding to cities that form the second case (i.e., from the $i+1$-th group) with difficulty $[l_i, b_j]$, where j is the number of such a city. Also, as mentioned, we cannot have a task from the segment $[l_i + 1, r_{i+1}]$ regardless of the type. To determine the difficulty, it is sufficient to set it to the maximum possible (equal to wisdom) and then gradually decrease it until we reach an allowed difficulty. To resolve the problem from the first case, we will place barriers with 2 tasks of difficulty equal to the strength of a certain city wherever possible. If there exists an answer for the given configuration, we will guarantee to construct it this way, using no more than $3 \\cdot n$ tasks. After all calculations, we need to check whether the contest we constructed meets the problem's conditions and output -1 otherwise.",
    "code": "/**\n *    author:  tourist\n *    created: 01.12.2024 18:36:51\n**/\n#undef _GLIBCXX_DEBUG\n\n#include <bits/stdc++.h>\n\nusing namespace std;\n\n#ifdef LOCAL\n#include \"algo/debug.h\"\n#else\n#define debug(...) 42\n#endif\n\nint main() {\n  ios::sync_with_stdio(false);\n  cin.tie(nullptr);\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n), b(n), c(n);\n    set<int> s;\n    for (int i = 0; i < n; i++) {\n      cin >> a[i] >> b[i] >> c[i];\n      s.insert(c[i]);\n    }\n    vector<vector<int>> vs(m);\n    for (int i = 0; i < m; i++) {\n      int foo;\n      cin >> foo;\n      vs[i].resize(foo);\n      for (int j = 0; j < foo; j++) {\n        cin >> vs[i][j];\n        --vs[i][j];\n      }\n    }\n    const int inf = int(1.01e9);\n    vector<int> min_a(m, inf);\n    vector<int> max_a(m, -1);\n    for (int i = 0; i < m; i++) {\n      for (int j : vs[i]) {\n        min_a[i] = min(min_a[i], a[j]);\n        max_a[i] = max(max_a[i], a[j]);\n      }\n    }\n    auto Unify = [&](vector<pair<int, int>>& bad) {\n      sort(bad.begin(), bad.end());\n      int ptr = 0;\n      for (int i = 1; i < int(bad.size()); i++) {\n        if (bad[i].first <= bad[ptr].second + 1) {\n          bad[ptr].second = max(bad[ptr].second, bad[i].second);\n        } else {\n          bad[++ptr] = bad[i];\n        }\n      }\n      bad.resize(ptr + 1);\n    };\n    vector<pair<int, int>> bad;\n    for (int id = 0; id < m - 1; id++) {\n      if (min_a[id] < max_a[id + 1]) {\n        bad.emplace_back(min_a[id] + 1, max_a[id + 1]);\n      }\n    }\n    Unify(bad);\n    vector<int> ctr(n);\n    for (int i = 0; i < m; i++) {\n      for (int x : vs[i]) {\n        ctr[x] = i;\n      }\n    }\n    vector<pair<int, int>> tasks;\n    int unused = 0;\n    vector<int> order(n);\n    iota(order.begin(), order.end(), 0);\n    sort(order.begin(), order.end(), [&](int i, int j) {\n      return a[i] > a[j];\n    });\n    multiset<int> before, after;\n    for (int i = 0; i < n; i++) {\n      after.insert(ctr[i]);\n    }\n    {\n      int beg = 0;\n      while (beg < n) {\n        int end = beg;\n        while (end + 1 < n && a[order[end + 1]] == a[order[end]]) {\n          end += 1;\n        }\n        for (int i = beg; i <= end; i++) {\n          before.insert(ctr[order[i]]);\n          after.erase(after.find(ctr[order[i]]));\n        }\n        if (!before.empty() && !after.empty() && *prev(before.end()) <= *after.begin()) {\n          for (int i = 0; i < 2; i++) {\n            do {\n              unused += 1;\n            } while (s.find(unused) != s.end());\n            tasks.emplace_back(a[order[end]], unused);\n          }\n        }\n        beg = end + 1;\n      }\n    }\n    map<int, int> add;\n    for (int id = 0; id < m - 1; id++) {\n      for (int i : vs[id]) {\n        if (a[i] <= max_a[id + 1]) {\n          if (add.find(c[i]) == add.end()) {\n            add[c[i]] = b[i];\n          } else {\n            add[c[i]] = min(add[c[i]], b[i]);\n          }\n        }\n      }\n    }\n    map<int, vector<pair<int, int>>> kill;\n    for (int id = 1; id < m; id++) {\n      for (int i : vs[id]) {\n        if (a[i] >= min_a[id - 1]) {\n          kill[c[i]].push_back({min_a[id - 1] + 1, b[i]});\n        }\n      }\n    }\n    for (auto& [type, x] : add) {\n      auto& k = kill[type];\n      Unify(k);\n      int dif = x;\n      while (true) {\n        bool changed = false;\n        {\n          auto it = lower_bound(bad.begin(), bad.end(), make_pair(dif + 1, -1));\n          if (it != bad.begin()) {\n            it = prev(it);\n            if (it->second >= dif) {\n              dif = it->first - 1;\n              changed = true;\n            }\n          }\n        }\n        {\n          auto it = lower_bound(k.begin(), k.end(), make_pair(dif + 1, -1));\n          if (it != k.begin()) {\n            it = prev(it);\n            if (it->second >= dif) {\n              dif = it->first - 1;\n              changed = true;\n            }\n          }\n        }\n        if (!changed) {\n          break;\n        }\n      }\n      tasks.emplace_back(dif, type);\n    }\n    debug(tasks);\n    vector<int> all;\n    map<int, int> spec;\n    for (auto& [x, y] : tasks) {\n      all.push_back(x);\n      assert(spec.find(y) == spec.end());\n      spec[y] = x;\n    }\n    sort(all.begin(), all.end());\n    vector<int> solved(n);\n    for (int i = 0; i < n; i++) {\n      solved[i] = int(upper_bound(all.begin(), all.end(), a[i]) - all.begin());\n      if (spec.find(c[i]) != spec.end() && spec[c[i]] > a[i] && spec[c[i]] <= b[i]) {\n        solved[i] += 1;\n      }\n    }\n    vector<int> min_solved(m, inf);\n    vector<int> max_solved(m, -1);\n    for (int i = 0; i < m; i++) {\n      for (int j : vs[i]) {\n        min_solved[i] = min(min_solved[i], solved[j]);\n        max_solved[i] = max(max_solved[i], solved[j]);\n      }\n    }\n    bool win = true;\n    for (int id = 0; id < m - 1; id++) {\n      if (min_solved[id] <= max_solved[id + 1]) {\n        win = false;\n        break;\n      }\n    }\n    if (win) {\n      cout << tasks.size() << '\n';\n      for (auto& [x, y] : tasks) {\n        cout << x << \" \" << y << '\n';\n      }\n    } else {\n      cout << -1 << '\n';\n    }\n  }\n  return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2046",
    "index": "F1",
    "title": "Yandex Cuneiform (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, there are no question marks. You can hack only if you solved all versions of this problem.}\n\nFor a long time, no one could decipher Sumerian cuneiform. However, it has finally succumbed to pressure! Today, you have the chance to decipher Yandex cuneiform.\n\nYandex cuneiform is defined by the following rules:\n\n- An empty string is a Yandex cuneiform.\n- If you insert exactly one copy of each of the three letters 'Y', 'D', and 'X' into a Yandex cuneiform in such a way that no two adjacent letters become equal after the operation, you obtain a Yandex cuneiform.\n- If a string can't be obtained using the above rules, it is not a Yandex cuneiform.\n\nYou are given a template. A template is a string consisting of the characters 'Y', 'D', 'X', and '?'.\n\nYou need to check whether there exists a way to replace each question mark with 'Y', 'D', or 'X' to obtain a Yandex cuneiform, and if it exists, output any of the matching options, as well as a sequence of insertion operations to obtain the resulting cuneiform.\n\nIn this version of the problem, there are \\textbf{no question marks} in the template.",
    "tutorial": "It can be noted that if the string contains the correct number of symbols 'Y', 'D', 'X' and does not have two consecutive identical symbols, then it can be obtained using the given operations. To demonstrate this, we will provide an algorithm that constructs a sequence of operations leading to the desired string. We will start from the end (from the string we want to obtain to the empty string) gradually removing symbols. Let's look at the current string. Without loss of generality, let its first symbol be 'Y'. Then the string must contain the substring 'DX' and/or the substring 'XD'. This is true because for the absence of 'DX' and 'XD', it is necessary that between any pair of symbols not equal to 'Y', there is at least one symbol 'Y'. This can be achieved at best by placing 'Y' between every symbol. Thus, the number of symbols not equal to 'Y' with $n-1$ 'Y' can be at most $n$. But $3n-1>n$ when $n>0$. Thus, the string has the form 'Y...ADXB...'. If A $\\neq$ B, we can remove the symbols 'Y', 'D', 'X' and nothing will break. If A = B, then A = B = 'Y', since A != 'D' and A != 'X'. Then the string has the form 'Y...YDXY...', and we can remove the substring 'YDX' and still have an unbroken string 'Y...Y...'.",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2046",
    "index": "F2",
    "title": "Yandex Cuneiform (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, there is no restriction on the number of question marks. You can hack only if you solved all versions of this problem.}\n\nFor a long time, no one could decipher Sumerian cuneiform. However, it has finally succumbed to pressure! Today, you have the chance to decipher Yandex cuneiform.\n\nYandex cuneiform is defined by the following rules:\n\n- An empty string is a Yandex cuneiform.\n- If you insert exactly one copy of each of the three letters 'Y', 'D', and 'X' into a Yandex cuneiform in such a way that no two adjacent letters become equal after the operation, you obtain a Yandex cuneiform.\n- If a string can't be obtained using the above rules, it is not a Yandex cuneiform.\n\nYou are given a template. A template is a string consisting of the characters 'Y', 'D', 'X', and '?'.\n\nYou need to check whether there exists a way to replace each question mark with 'Y', 'D', or 'X' to obtain a Yandex cuneiform, and if it exists, output any of the matching options, as well as a sequence of insertion operations to obtain the resulting cuneiform.\n\nIn this version of the problem, the number of question marks in the template can be arbitrary.",
    "tutorial": "We will isolate substrings from the string that consist entirely of '?'. For each, we will denote its length as $len_i$ and the two neighboring symbols (standing to the left and right) as $l_i$, $r_i$. (If the right and/or left symbol is absent, we will take it as '#', a symbol that does not match any of our interests). We will write trivial constraints on the number of available symbols of each type on the segment. It is obvious that the number of symbols of each type cannot exceed $\\frac{len_i+1}{2}$: we will place one symbol for every other symbol. But if, for example, we had a symbol 'Y' on the left, the number of positions where we can place 'Y' decreases by $1$. In total, we can place no more than $\\frac{len+1-(l_i=b)-(r_i=b)}{2}$ symbols of type b. We will write such constraints for each type of symbol and denote them as $Y, D, X$ respectively. It turns out that we can arrange $y$ symbols 'Y', $d$ symbols 'D' and $x$ symbols 'X' if and only if $y+d+x=len_i$ and $0\\leq y \\leq Y, 0 \\leq d \\leq D, 0 \\leq x \\leq X$. This can be proven by induction or checked with stress tests on small values. From this, we conclude that in order to be able to arrange $x, d, y$ symbols of each type, the inequalities above must hold. From the equality $y+d+x=len_i$, we express $d=len_i - (x+y)$. This results in three constraints: $0\\leq x \\leq X, 0 \\leq y \\leq Y, 0 \\leq len_i - (x+y) \\leq D$. The first two form a rectangle, and the third cuts off two corners at a $45$ degree angle. This is a convex polygon. Thus, if for each segment of '?' we write a polygon and sum them using Minkowski sum, we will obtain constraints for the entire string. Since in the Minkowski sum (after merging collinear consecutive segments) there will be at most 6 points, we can write a greedy algorithm that sequentially tries to match the required symbol to each '?'. The final asymptotic complexity is $O(n)$ with some constant.",
    "code": "#pragma GCC optimize(\"Ofast\")\n#include <iostream>\n#include <cmath>\n#include <cstdint>\n#include <vector>\n#include <string>\n#include <iomanip>\n#include <set>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <functional>\n#include <queue>\n#include <fstream>\n#include <random>\n//#include <numbers>\n#include <optional>\n#include <deque>\n#include <sstream>\n#include <list>\n#include <chrono>\n#include <thread>\n#include <cassert>\n \nusing namespace std;\nusing i64 = int64_t;\nusing ui64 = uint64_t;\n#define YN(b) if (b) cout << \"YES\n\"; else cout << \"NO\n\";\n \ntemplate<typename T>\nistream& operator>>(istream& is, vector<T>& v) { for (auto &e: v) { is >> e; } return is; }\n \ntemplate<typename T>\nostream& operator<<(ostream& os, vector<T>& v) { for (auto &e: v) { os << e << \" \"; } return os; }\n \ntemplate<typename T, typename V>\nistream& operator>>(istream& is, pair<T, V>& v) { return is >> v.first >> v.second; }\n \ntemplate<typename T, typename V>\nostream& operator<<(ostream& os, pair<T, V>& v) { return os << v.first << \" \" << v.second; }\n \nconst int64_t md = 1e9+7;\n\nint dx[4] = {-1, 0, 1, 0};\n \ninline int64_t sqr(int64_t x) {\n    return x * x;\n}\n \ninline int popcount(int64_t x) {\n    int c = 0;\n    while (x) c += x & 1, x >>= 1;\n    return c;\n}\n \npair<int64_t, int64_t> inter(pair<int64_t, int64_t> a, pair<int64_t, int64_t> b) {\n    return {max(a.first, b.first), min(a.second, b.second)};\n}\n\n\nstruct pt {\n    using T = int;\n    using V = int64_t;\n    T x = 0, y = 0;\n    pt() = default;\n    pt(T x, T y) : x(x), y(y) {}\n    inline pt& operator-=(const pt& other) {\n        x -= other.x;\n        y -= other.y;\n        return *this;\n    }\n    inline pt operator-(const pt& other) const {\n        pt copy(*this);\n        copy -= other;\n        return copy;\n    }\n    inline pt& operator+=(const pt& other) {\n        x += other.x;\n        y += other.y;\n        return *this;\n    }\n    inline pt operator+(const pt& other) const {\n        pt copy(*this);\n        copy += other;\n        return copy;\n    }\n    V operator^(const pt& other) const {\n        return (V)x * other.y - (V)y * other.x;\n    }\n    V operator*(const pt& other) const {\n        return (V)x * other.x + (V)y * other.y;\n    }\n    void print() const {\n        cerr << x << \" \" << y << \"\n\";\n    }\n    bool operator==(const pt&) const = default;\n};\n\n\ninline bool in_triangle(const pt& a, const pt& b, const pt& c, const pt& point) {\n    int64_t s1 = abs((b - a) ^ (c - a));\n    int64_t s2 = abs((a - point) ^ (b - point)) + abs((b - point) ^ (c - point)) + abs((c - point) ^ (a - point));\n    return s1 == s2;\n}\n\nstruct mi {\n    size_t i = 0;\n    size_t ni = 1;\n    const size_t m;\n    mi(size_t m) : m(m) {}\n    void add() {\n        ++i;\n        if (++ni == m) ni = 0;\n    }\n};\nint64_t orientation(pt a, pt b, pt c) {\n    return -((int64_t)a.x * (b.y - c.y) + (int64_t)b.x * (c.y - a.y) + (int64_t)c.x * (a.y - b.y));\n}\ninline bool comp(pt a, pt b) {\n    auto cp = a ^ b;\n    if (!cp) {\n        return a * a < b * b;\n    }\n    return (pt::V)a.x * b.x < 0 ? (a.x > b.x) : cp > 0;\n}\n\nstruct NMP {\n    array<pt, 13> pts;\n    int len = 0;\n    template<typename... Args>\n    void emplace_back(Args&& ...p) {\n        new (&pts[len++]) pt(p...);\n    }\n    void push_back(const pt& x) {\n        pts[len++] = x;\n    }\n    pt& operator[](size_t x) {\n        return pts[x];\n    }\n    size_t size() const {\n        return len;\n    }\n\n    const pt& operator[](size_t x) const {\n        return pts[x];\n    }\n    pt* begin() {\n        return &pts[0];\n    }\n    pt* end() {\n        return &pts[len];\n    }\n    void resize(size_t x) {\n        len = x;\n    }\n};\n\nstruct poly {\n    using P = pt;\n    NMP pts;\n    void add(const P& p) {\n        pts.push_back(p);\n    }\n    \n    template<typename... Args>\n    void emplace(Args&& ...p) {\n        pts.emplace_back(p...);\n    }\n\n    void sort() {\n        size_t min_id = 0;\n        for (size_t i = 1; i < pts.size(); ++i) {\n            if (pts[i].y < pts[min_id].y || (pts[i].y == pts[min_id].y && pts[i].x < pts[min_id].x)) {\n                min_id = i;\n            }\n        }\n        std::rotate(pts.begin(), pts.begin() + min_id, pts.end());\n        auto p0 = pts[0];\n        std::sort(pts.begin(), pts.end(), [&](const P& a, const P& b) {\n            auto o = orientation(p0, a, b);\n            if (!o)\n                return (int64_t)(p0.x-a.x)*(p0.x-a.x) + (int64_t)(p0.y-a.y)*(p0.y-a.y)\n                    < (int64_t)(p0.x-b.x)*(p0.x-b.x) + (int64_t)(p0.y-b.y)*(p0.y-b.y);\n            return o < 0;\n        });\n    }\n\n    void no_coll() {\n        if (pts.size() < 3) {\n            return;\n        }\n        size_t ptr = 1;\n        for (size_t j = 2; j < pts.size(); ++j) {\n            if ((pts[ptr] - pts[ptr - 1]) ^ (pts[j] - pts[ptr])) {\n                pts[++ptr] = pts[j];\n                continue;\n            }\n            pts[ptr] = pts[j];\n        }\n        pts.resize(ptr + 1);\n    }\n\n    poly operator+(const poly& other) const {\n        if (pts.size() == 1) {\n            poly c(other);\n            for (auto& p: c.pts) p += pts[0];\n            return c;\n        }\n        if (other.pts.size() < pts.size()) {\n            return other + *this;\n        }\n        // size at least 2s\n        poly res;\n        mi i(pts.size()), j(other.pts.size());\n\n        while (i.i < pts.size() && j.i < other.pts.size()) {\n            res.emplace(pts[i.i] + other.pts[j.i]);\n            auto a = (pts[i.ni] - pts[i.i]);\n            auto b = (other.pts[j.ni] - other.pts[j.i]);\n            auto cp = a ^ b;\n            if (cp < 0) {\n                j.add();\n            } else if (cp > 0) {\n                i.add();\n            } else if ((P::V)a.y * b.y >= 0) {\n                i.add();\n                j.add();\n            } else if (a.y > b.y) {\n                i.add();\n            } else {\n                j.add();\n            }\n        }\n        while (i.i < pts.size()) {\n            res.emplace(pts[i.i] + other.pts[0]);\n            i.add();\n        }\n        \n        while (j.i < other.pts.size()) {\n            res.emplace(pts[0] + other.pts[j.i]);\n            j.add();\n        }\n        \n        res.no_coll();\n        return res;\n    }\n\n    void print() {\n        for (auto &e: pts) {\n            cout << \"(\" << e.x << \" \" << e.y << \") \";\n        }\n        cout << \"\n\";\n    }\n\n    bool in(const pt& p) const {\n        if (pts.size() == 1) {\n            return pts[0] == p;\n        }\n        if (pts.size() == 2) {\n            return ((pts[0] - p) ^ (pts[1] - p)) == 0 \n                && min(pts[0].x, pts[1].x) <= p.x && p.x <= max(pts[0].x, pts[1].x)\n                && min(pts[0].y, pts[1].y) <= p.y && p.y <= max(pts[0].y, pts[1].y);\n        }\n        for (int i = 2; i < pts.size(); ++i) {\n            if (in_triangle(pts[i], pts[i - 1], pts[0], p)) {\n                return true;\n            }\n        }\n        return false;\n    }\n};\n\n\nstruct co {\n    array<int, 3> cst {};\n    poly p;\n    co() {\n        p.emplace(0, 0);\n    }\n\n    co(int l, int a, int b) {\n        cst = {\n            max(0, 1 + l - (a == 0) - (b == 0)) / 2,\n            max(0, 1 + l - (a == 1) - (b == 1)) / 2,\n            max(0, 1 + l - (a == 2) - (b == 2)) / 2\n        };\n        p.emplace(min(cst[0], l - cst[2]), max(0, l - cst[0] - cst[2]));\n        p.emplace(min(cst[0], l), max(0, l - cst[0] - cst[2]));\n        p.emplace(cst[0], min(cst[1], l - cst[0]));\n        p.emplace(min(l - cst[1], cst[0]), cst[1]);\n        p.emplace(max(0, l - cst[1] - cst[2]), min(l, cst[1]));\n        p.emplace(max(0, l - cst[1] - cst[2]), min(cst[1], l - cst[2]));\n        p.sort();\n        p.no_coll();\n    }\n\n    co operator+(const co& rhs) {\n        co res;\n        res.p = p + rhs.p;\n        for (int j = 0; j < 3; ++j) res.cst[j] = cst[j] + rhs.cst[j];\n        return res;\n    }\n\n    bool ok(int x, int y, int z) {\n        return x <= cst[0] && y <= cst[1] && z <= cst[2]; \n    }\n\n    bool in(int x, int y, int z) {\n        return ok(x, y, z) && p.in(pt(x, y));\n    }\n};\n\nchar idx[128]{};\nstring ydx = \"YDX\";\n\nstruct fenwick {\n    fenwick(int x) : t(x), n(x) {}\n    vector<int> t;\n    int n;\n    int sum (int r) {\n        int result = 0;\n        for (; r >= 0; r = (r & (r+1)) - 1)\n            result += t[r];\n        return result;\n    }\n\n    void inc (int i, int delta) {\n        for (; i < n; i = (i | (i+1)))\n            t[i] += delta;\n    }\n};\n\nusing S = std::list<pair<short, int>>;\n\nstruct cmp {\n    bool operator()(S::iterator a, S::iterator b) const {\n        return a->second < b->second;\n    };\n};\n\nauto encode1(auto a, auto b) {\n    return a * 256 + b;\n};\n\nauto encode(auto it) {\n    auto prev = it++;\n    return encode1(prev->first, it->first);\n};\n\nauto erase_char(auto& curr_pos, S& str, fenwick& alive, auto& pos, auto it) {\n    auto curr = it;\n    auto prev = --it;\n    it = curr;\n    auto next = ++it;\n    if (next != str.end()) {\n        if (!pos[encode(curr)].count(curr)) {\n            exit(-1);\n        }\n        pos[encode(curr)].erase(curr);\n    }\n    if (prev != str.end()) {\n        if (!pos[encode(prev)].count(prev)) {\n            exit(-1);\n        }\n        pos[encode(prev)].erase(prev);\n    }\n    curr_pos.emplace_back(curr->first, alive.sum(curr->second) - 1);\n    alive.inc(curr->second, -1);\n    str.erase(curr);\n    if (next != str.end() && prev != str.end()) {\n        auto p = prev;\n        ++p;\n        if (p != next) {\n            exit(-1);\n        }\n        pos[encode(prev)].emplace(prev);\n    }\n};\n\nbool is_ok(S::iterator x, S::iterator end) {\n    auto curr = x;\n    auto prev = --x;\n    auto next = ++curr;\n    if (prev != end && next != end) {\n        return prev->first != next->first;\n    }\n    return true;\n}\n\nauto got(auto& curr_pos, auto& str, auto& alive, auto& pos, vector<S::iterator> t) {\n    for (auto &e: t) {\n        erase_char(curr_pos, str, alive, pos, e);\n    }\n};\n\n\nauto relax(auto& curr_pos, auto& str, auto& alive, auto& pos, short sym, short co) {\n    auto &v = pos[co];\n    auto it = *v.begin();\n    auto A = it;\n    auto prev = --it;\n    it = A;\n    auto B = ++it;\n    auto next = ++it;\n    if (prev != str.end() && next != str.end() && prev->first == next->first) {\n        if (prev->first != sym) {\n            exit(-1);\n        }\n        got(curr_pos, str, alive, pos, {prev, A, B});\n        return false;\n    }\n    \n    got(curr_pos, str, alive, pos, {A, B});\n    return true;\n};\n\nvector<array<pair<char, int>, 3>> solve_str(const string& s) {\n    S str;\n    fenwick alive(s.size());\n\n    for (int i = 0; i < s.size(); ++i) {\n        str.emplace_back(s[i], i);\n        alive.inc(i, 1);\n    }\n\n    auto it = str.begin();\n\n    map<int, set<decltype(it), cmp>> pos;\n    while (it != str.end()) {\n        auto prev = it++;\n        if (it == str.end()) break;\n        pos[encode(prev)].emplace(prev);   \n    }\n    vector<pair<char, int>> curr_pos;\n    vector<decltype(it)> curr_t;\n    vector<array<pair<char, int>, 3>> res;\n    while (str.size()) {\n        it = str.begin();\n        auto curr = it++;\n        if (it == str.end()) {\n            exit(-1);\n        }\n        short code = curr->first;\n        erase_char(curr_pos, str, alive, pos, curr);\n\n        array<int, 2> candidates;\n        if (code == 'Y') {\n            candidates[0] = encode1('D', 'X');\n            candidates[1] = encode1('X', 'D');\n        } else if (code == 'X') {\n            candidates[0] = encode1('D', 'Y');\n            candidates[1] = encode1('Y', 'D');\n        } else {\n            candidates[0] = encode1('Y', 'X');\n            candidates[1] = encode1('X', 'Y');\n        }\n        bool ok = 0;\n        while (!ok) {\n            for (auto &c: candidates) {\n                if (!pos[c].size()) {\n                    continue;\n                }\n                if (relax(curr_pos, str, alive, pos, code, c)) {\n                    ok = 1;\n                    res.emplace_back();\n                    res.back()[0] = curr_pos[2];\n                    res.back()[1] = curr_pos[1];\n                    res.back()[2] = curr_pos[0];\n                    curr_pos.clear();\n                    break;\n                }\n                // A...ABCA, ABC removed\n                res.emplace_back();\n                for (int j = 0; j < 3; ++j) {\n                    res.back()[j] = curr_pos.back(); // removed\n                    res.back()[j].second += 1;\n                    curr_pos.pop_back();\n                }\n                break;\n            }\n        }\n    }\n    reverse(res.begin(), res.end());\n    return res;\n}\n\nbool check(const string& s) {\n    array<int, 3> cnt{};\n    char prev = -1;\n    for (auto &e: s) {\n        if (e == '?') {\n            return false;\n        }\n        if (e != 'Y' && e != 'D' && e != 'X') {\n            return false;\n        }\n        if (e == prev) return false;\n        prev = e;\n        ++cnt[idx[e]];\n    }\n    return cnt[0] == s.size() / 3 && cnt[1] == s.size() / 3 && cnt[2] == s.size() / 3;\n}\n\noptional<string> solve_fast1(string v) {\n    auto sv = v;\n    int N = v.size() / 3;\n    array<int, 3> rem{N, N, N};\n    for (auto &e: v) {\n        if (e == '?') continue;\n        --rem[idx[e]];\n    }\n    if (rem[0] < 0 || rem[1] < 0 || rem[2] < 0) return {};\n    vector<co> mink;\n    vector<pair<int, int>> segs;\n    for (int i = 0; i < v.size(); ++i) {\n        if (v[i] != '?') continue;\n        int j = i + 1;\n        while (j < v.size() && v[j] == '?') ++j;\n        mink.emplace_back(j - i, i > 0 ? idx[v[i - 1]] : 3, j < v.size() ? idx[v[j]] : 3);\n        segs.emplace_back(i, j - 1);\n        i = j - 1;\n    }\n    reverse(mink.begin(), mink.end());\n    reverse(segs.begin(), segs.end());\n    for (int i = 1; i < mink.size(); ++i) {\n        mink[i] = mink[i - 1] + mink[i];\n    }\n    if (mink.size()) {\n        mink.pop_back();\n    }\n    while (segs.size()) {\n        auto seg = segs.back();\n        segs.pop_back();\n        auto mk = mink.size() ? mink.back() : co();\n        if (mink.size()) {\n            mink.pop_back();\n        }\n        char prev = idx[seg.first ? v[seg.first - 1] : '?'];\n        char next_r = idx[seg.second + 1 < v.size() ? v[seg.second + 1] : '?'];\n        while (seg.first <= seg.second) {\n            char next = seg.first == seg.second ? next_r : -1;\n            bool found = 0;\n            for (int j = 0; j < 3; ++j) {\n                if (prev == j || next == j || !rem[j]) {\n                    continue;\n                }\n                --rem[j];\n                auto cs = co(seg.second - seg.first, j, seg.second + 1 < v.size() ? idx[v[seg.second + 1]] : 3);\n                auto vv = mk + cs;\n                if (!vv.in(rem[0], rem[1], rem[2])) {\n                    ++rem[j];\n                    continue;\n                }\n                v[seg.first++] = ydx[j];\n                prev = j;\n                found = 1;\n                break;\n            }\n            if (!found) {\n                return {};\n            }\n        }\n    }\n    return v;\n}\n\noptional<pair<vector<array<pair<char, int>, 3>>, string>> solve(string s) {\n    auto ww = solve_fast1(s);\n    if (!ww || !check(*ww)) {\n        return {};\n    }\n    return pair{solve_str(*ww), *ww};\n}\n\nsigned main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    idx['Y'] = 0;\n    idx['D'] = 1;\n    idx['X'] = 2;\n    idx['?'] = 99;\n    int t;\n    cin >> t;\n    while (t--) {\n        string s;\n        cin >> s;\n        auto r = solve(s);\n        if (r) {\n            cout << \"YES\n\" << r->second << \"\n\";\n            for (auto &x: r->first) {\n                for (auto &e: x) {\n                    cout << e.first << \" \" << e.second << \" \";\n                }\n                cout << \"\n\";\n            }\n        } else {\n            cout << \"NO\n\";\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2047",
    "index": "A",
    "title": "Alyona and a Square Jigsaw Puzzle",
    "statement": "Alyona assembles an unusual square Jigsaw Puzzle. She does so in $n$ days in the following manner:\n\n- On the first day, she starts by placing the central piece in the center of the table.\n- On each day after the first one, she places a certain number of pieces around the central piece in clockwise order, always finishing each square layer completely before starting a new one.\n\nFor example, she places the first $14$ pieces in the following order:\n\n\\begin{center}\n{\\small The colors denote the layers. The third layer is still unfinished.}\n\\end{center}\n\nAlyona is happy if at the end of the day the assembled part of the puzzle does not have any started but unfinished layers. Given the number of pieces she assembles on each day, find the number of days Alyona is happy on.",
    "tutorial": "Alyona is happy when there are no unfinished layers - that is, in front of her is a perfect square with odd side length. Since the order of pieces is fixed, it is enough to keep track of the total current size $s$ of the puzzle, and after each day check, if the $s$ is a perfect square of an odd number. The easiest way to do that is to create an additional array containing $1^2, 3^2, 5^3, ..., 99^2$, and check after each day, whether $s$ is in this array.",
    "code": "NT = int(input())\n\nsqs = set()\nk = 1\nwhile k * k <= 100 * 1000:\n\tsqs.add(k * k)\n\tk += 2\n\nfor T in range(NT):\n\tn = int(input())\n\ta = list(map(int, input().split()))\n\tanswer = 0\n\tcursum = 0\n\tfor t in a:\n\t\tcursum += t\n\t\tif cursum in sqs:\n\t\t\tanswer += 1\n\tprint(answer)",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2047",
    "index": "B",
    "title": "Replace Character",
    "statement": "You're given a string $s$ of length $n$, consisting of only lowercase English letters.\n\nYou must do the following operation exactly once:\n\n- Choose any two indices $i$ and $j$ ($1 \\le i, j \\le n$). You can choose $i = j$.\n- Set $s_i := s_j$.\n\nYou need to minimize the number of distinct permutations$^\\dagger$ of $s$. Output any string with the smallest number of distinct permutations after performing \\textbf{exactly one} operation.\n\n$^\\dagger$ A permutation of the string is an arrangement of its characters into any order. For example, \"bac\" is a permutation of \"abc\" but \"bcc\" is not.",
    "tutorial": "Find the character which appears the lowest number of times - if tied, take the earlier character in the alphabet. Find the character which appears the highest number of times - if tied, take the later character in the alphabet. Then, replace any of the lowest-occurrence characters with the highest-occurrence character.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    cin.tie(0)->sync_with_stdio(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        vector<int> occ(26);\n        for (int i=0; i<n; i++)\n            occ[s[i] - 'a'] += 1;\n        pair<pair<int,char>,int> low, high;\n        low = high = {{occ[s[0] - 'a'], s[0]}, 0};\n        for (int i=1; i<n; i++) {\n            low = min(low, {{occ[s[i] - 'a'], s[i]}, i});\n            high = max(high, {{occ[s[i] - 'a'], s[i]}, i});\n        }\n        s[low.second] = s[high.second];\n        cout << s << \"\n\";\n    }\n  return 0;\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "greedy",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "2048",
    "index": "A",
    "title": "Kevin and Combination Lock",
    "statement": "Kevin is trapped in Lakeside Village by Grace. At the exit of the village, there is a combination lock that can only be unlocked if Kevin solves it.\n\nThe combination lock starts with an integer $ x $. Kevin can perform one of the following two operations zero or more times:\n\n- If $ x \\neq 33 $, he can select two consecutive digits $ 3 $ from $ x $ and remove them simultaneously. For example, if $ x = 13\\,323 $, he can remove the second and third $ 3 $, changing $ x $ to $ 123 $.\n- If $ x \\geq 33 $, he can change $ x $ to $ x - 33 $. For example, if $ x = 99 $, he can choose this operation to change $ x $ to $ 99 - 33 = 66 $.\n\nWhen the value of $ x $ on the combination lock becomes $ 0 $, Kevin can unlock the lock and escape from Lakeside Village. Please determine whether it is possible for Kevin to unlock the combination lock and escape.",
    "tutorial": "When we transform $\\overline{x33y}$ into $\\overline{xy}$ (where $x$ and $y$ are decimal numbers), the actual value changes from $10^{p+2} \\cdot x + 33 \\cdot 10^p + y$ to $10^p \\cdot x + y$. The decrease is $99 \\cdot 10^p \\cdot x + 33 \\cdot 10^p$. It is easy to see that $33 \\mid (99 \\cdot 10^p \\cdot x + 33 \\cdot 10^p)$. Therefore, we can replace the operation of removing two consecutive $3$ s with a series of $-33$ operations. Hence, we only need to determine whether $x$ can be reduced to $0$ using a series of $-33$ operations, which is equivalent to checking whether $x \\bmod 33$ equals zero.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2048",
    "index": "A",
    "title": "Kevin and Combination Lock",
    "statement": "Kevin is trapped in Lakeside Village by Grace. At the exit of the village, there is a combination lock that can only be unlocked if Kevin solves it.\n\nThe combination lock starts with an integer $ x $. Kevin can perform one of the following two operations zero or more times:\n\n- If $ x \\neq 33 $, he can select two consecutive digits $ 3 $ from $ x $ and remove them simultaneously. For example, if $ x = 13\\,323 $, he can remove the second and third $ 3 $, changing $ x $ to $ 123 $.\n- If $ x \\geq 33 $, he can change $ x $ to $ x - 33 $. For example, if $ x = 99 $, he can choose this operation to change $ x $ to $ 99 - 33 = 66 $.\n\nWhen the value of $ x $ on the combination lock becomes $ 0 $, Kevin can unlock the lock and escape from Lakeside Village. Please determine whether it is possible for Kevin to unlock the combination lock and escape.",
    "tutorial": "When we transform $\\overline{x33y}$ into $\\overline{xy}$ (where $x$ and $y$ are decimal numbers), the actual value changes from $10^{p+2} \\cdot x + 33 \\cdot 10^p + y$ to $10^p \\cdot x + y$. The decrease is $99 \\cdot 10^p \\cdot x + 33 \\cdot 10^p$. It is easy to see that $33 \\mid (99 \\cdot 10^p \\cdot x + 33 \\cdot 10^p)$. Therefore, we can replace the operation of removing two consecutive $3$ s with a series of $-33$ operations. Hence, we only need to determine whether $x$ can be reduced to $0$ using a series of $-33$ operations, which is equivalent to checking whether $x \\bmod 33$ equals zero.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2048",
    "index": "B",
    "title": "Kevin and Permutation",
    "statement": "Kevin is a master of permutation-related problems. You are taking a walk with Kevin in Darkwoods, and during your leisure time, he wants to ask you the following question.\n\nGiven two positive integers $ n $ and $ k $, construct a permutation$^{\\text{∗}}$ $ p $ of length $ n $ to minimize the sum of the minimum values of all subarrays$^{\\text{†}}$ of length $ k $. Formally, you need to minimize\n\n$$ \\sum_{i=1}^{n-k+1}\\left( \\min_{j=i}^{i+k-1} p_j\\right). $$\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Two subarrays are considered different if the sets of \\textbf{positions} of the deleted elements are different.\n\\end{footnotesize}",
    "tutorial": "In the entire permutation, at most $k$ subintervals can contain $1$. Similarly, at most $k$ subintervals can contain $2, 3, \\ldots$. To maximize the number of subintervals where the minimum value is as small as possible, we use the following construction: $p_k=1,p_{2k}=2,\\dots,p_{\\lfloor{\\frac{n}{k}}\\rfloor\\cdot k}=\\left\\lfloor\\frac{n}{k}\\right\\rfloor$ For the remaining positions, we can fill them arbitrarily with all values from $\\lfloor \\frac{n}{k} \\rfloor + 1$ to $n$. It is easy to prove that this construction minimizes the answer.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "2048",
    "index": "B",
    "title": "Kevin and Permutation",
    "statement": "Kevin is a master of permutation-related problems. You are taking a walk with Kevin in Darkwoods, and during your leisure time, he wants to ask you the following question.\n\nGiven two positive integers $ n $ and $ k $, construct a permutation$^{\\text{∗}}$ $ p $ of length $ n $ to minimize the sum of the minimum values of all subarrays$^{\\text{†}}$ of length $ k $. Formally, you need to minimize\n\n$$ \\sum_{i=1}^{n-k+1}\\left( \\min_{j=i}^{i+k-1} p_j\\right). $$\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Two subarrays are considered different if the sets of \\textbf{positions} of the deleted elements are different.\n\\end{footnotesize}",
    "tutorial": "In the entire permutation, at most $k$ subintervals can contain $1$. Similarly, at most $k$ subintervals can contain $2, 3, \\ldots$. To maximize the number of subintervals where the minimum value is as small as possible, we use the following construction: $p_k=1,p_{2k}=2,\\dots,p_{\\lfloor{\\frac{n}{k}}\\rfloor\\cdot k}=\\left\\lfloor\\frac{n}{k}\\right\\rfloor$ For the remaining positions, we can fill them arbitrarily with all values from $\\lfloor \\frac{n}{k} \\rfloor + 1$ to $n$. It is easy to prove that this construction minimizes the answer.",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 900
  },
  {
    "contest_id": "2048",
    "index": "C",
    "title": "Kevin and Binary Strings",
    "statement": "Kevin discovered a binary string $s$ that \\textbf{starts with 1} in the river at Moonlit River Park and handed it over to you. Your task is to select two non-empty substrings$^{\\text{∗}}$ of $s$ (which can be overlapped) to maximize the XOR value of these two substrings.\n\nThe XOR of two binary strings $a$ and $b$ is defined as the result of the $\\oplus$ operation applied to the two numbers obtained by interpreting $a$ and $b$ as binary numbers, with the leftmost bit representing the highest value. Here, $\\oplus$ denotes the bitwise XOR operation.\n\nThe strings you choose may have leading zeros.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\\end{footnotesize}",
    "tutorial": "To maximize the XOR sum of the two substrings, we aim to maximize the number of binary digits in the XOR result. To achieve this, the substring $[1,n]$ must always be selected. Suppose the first character of the other substring is $1$. If it is not $1$, we can remove all leading zeros. Next, find the position of the first $0$ in the string from left to right. We want this position to be flipped to $1$, while ensuring that the $1$s earlier in the string are not changed to $0$s. Therefore, let the position of the first $0$ be $p$. The length of the other substring must be $n-p+1$. By enumerating the starting position of the other substring and calculating the XOR sum of the two substrings linearly, we can take the maximum value. The time complexity of this approach is $O(n^2)$. If the entire string consists only of $1$s, selecting $[1,n]$ and $[1,1]$ can be proven to yield the maximum XOR sum among all possible choices. Interesting fact: This problem can actually be solved in $O(n)$ time complexity. Specifically, observe that the other substring needs to satisfy the following conditions: its length is $n-p+1$, and its first character is $1$. Thus, its starting position must be less than $p$. This implies that the length of the prefix of $1$s in the other substring can be chosen from the range $[1, p-1]$. We aim to flip the first segment of $0$ s in the original string to $1$ s, while ensuring that the $1$ immediately after this segment of $0$ s remains unchanged. Let the length of the first segment of $0$ s be $q$. Then, the length of the prefix of $1$ s in the other substring must be $\\min(p-1, q)$, and the starting position can be determined efficiently. When preparing the contest and selecting problems, we determined that the $O(n)$ solution would be too difficult for a Problem C. Therefore, the problem was designed with an $O(n^2)$ data range to make it more accessible.",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2048",
    "index": "C",
    "title": "Kevin and Binary Strings",
    "statement": "Kevin discovered a binary string $s$ that \\textbf{starts with 1} in the river at Moonlit River Park and handed it over to you. Your task is to select two non-empty substrings$^{\\text{∗}}$ of $s$ (which can be overlapped) to maximize the XOR value of these two substrings.\n\nThe XOR of two binary strings $a$ and $b$ is defined as the result of the $\\oplus$ operation applied to the two numbers obtained by interpreting $a$ and $b$ as binary numbers, with the leftmost bit representing the highest value. Here, $\\oplus$ denotes the bitwise XOR operation.\n\nThe strings you choose may have leading zeros.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\\end{footnotesize}",
    "tutorial": "To maximize the XOR sum of the two substrings, we aim to maximize the number of binary digits in the XOR result. To achieve this, the substring $[1,n]$ must always be selected. Suppose the first character of the other substring is $1$. If it is not $1$, we can remove all leading zeros. Next, find the position of the first $0$ in the string from left to right. We want this position to be flipped to $1$, while ensuring that the $1$s earlier in the string are not changed to $0$s. Therefore, let the position of the first $0$ be $p$. The length of the other substring must be $n-p+1$. By enumerating the starting position of the other substring and calculating the XOR sum of the two substrings linearly, we can take the maximum value. The time complexity of this approach is $O(n^2)$. If the entire string consists only of $1$s, selecting $[1,n]$ and $[1,1]$ can be proven to yield the maximum XOR sum among all possible choices. Interesting fact: This problem can actually be solved in $O(n)$ time complexity. Specifically, observe that the other substring needs to satisfy the following conditions: its length is $n-p+1$, and its first character is $1$. Thus, its starting position must be less than $p$. This implies that the length of the prefix of $1$s in the other substring can be chosen from the range $[1, p-1]$. We aim to flip the first segment of $0$ s in the original string to $1$ s, while ensuring that the $1$ immediately after this segment of $0$ s remains unchanged. Let the length of the first segment of $0$ s be $q$. Then, the length of the prefix of $1$ s in the other substring must be $\\min(p-1, q)$, and the starting position can be determined efficiently. When preparing the contest and selecting problems, we determined that the $O(n)$ solution would be too difficult for a Problem C. Therefore, the problem was designed with an $O(n^2)$ data range to make it more accessible.",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2048",
    "index": "D",
    "title": "Kevin and Competition Memories",
    "statement": "Kevin used to get into Rio's Memories, and in Rio's Memories, a series of contests was once held. Kevin remembers all the participants and all the contest problems from that time, but he has forgotten the specific rounds, the distribution of problems, and the exact rankings.\n\nThere are $ m $ problems in total, with the $ i $-th problem having a difficulty of $ b_i $. Let each contest consist of $ k $ problems, resulting in a total of $ \\lfloor \\frac{m}{k} \\rfloor $ contests. This means that you select exactly $ \\lfloor \\frac{m}{k} \\rfloor \\cdot k $ problems for the contests in any combination you want, with each problem being selected at most once, and the remaining $m\\bmod k$ problems are left unused. For example, if $m = 17$ and $k = 3$, you should create exactly $5$ contests consisting of $3$ problems each, and exactly $2$ problems will be left unused.\n\nThere are $ n $ participants in the contests, with Kevin being the $1$-st participant. The $ i $-th participant has a rating of $ a_i $. During the contests, each participant solves all problems with a difficulty not exceeding their rating, meaning the $ i $-th participant solves the $ j $-th problem if and only if $ a_i \\geq b_j $. In each contest, Kevin's rank is one plus the number of participants who solve more problems than he does.\n\nFor each $ k = 1, 2, \\ldots, m $, Kevin wants to know the minimum sum of his ranks across all $ \\lfloor \\frac{m}{k} \\rfloor $ contests. In other words, for some value of $k$, after selecting the problems for each contest, you calculate the rank of Kevin in each contest and sum up these ranks over all $ \\lfloor \\frac{m}{k} \\rfloor $ contests. Your goal is to minimize this value.\n\nNote that contests for different values of $k$ are independent. It means that for different values of $k$, you can select the distribution of problems into the contests independently.",
    "tutorial": "Read all the hints. First, remove all contestants with a rating lower than yours, making you the contestant with the lowest rating. Since any problem you can solve can also be solved by everyone else, this does not affect your ranking. These problems can effectively be treated as having infinite difficulty. At this point, you cannot solve any problem, so your ranking in a competition is given by $(1 +$ the number of contestants who solve at least one problem in that competition $)$. Therefore, we only need to focus on the easiest problem in each competition. Precompute, for each problem, the number of contestants who can solve it, denoted as $c_i$. This can be done by sorting the contestants by rating and the problems by difficulty, then using a two-pointer or binary search approach to compute $c_i$. The remaining task is: given $c_i$, divide all $c_i$ into $\\lfloor \\frac{n}{k} \\rfloor$ groups, each containing $k$ elements, and minimize the sum of the maximum values in each group. This can be solved using a greedy algorithm: sort $c_i$ in ascending order, and for a given $k$, the answer is $(c_k+1) + (c_{2k}+1) + \\dots$. The brute force calculation is bounded by the harmonic series, and combined with sorting, the time complexity is $O(n \\log n + m \\log m)$.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2048",
    "index": "D",
    "title": "Kevin and Competition Memories",
    "statement": "Kevin used to get into Rio's Memories, and in Rio's Memories, a series of contests was once held. Kevin remembers all the participants and all the contest problems from that time, but he has forgotten the specific rounds, the distribution of problems, and the exact rankings.\n\nThere are $ m $ problems in total, with the $ i $-th problem having a difficulty of $ b_i $. Let each contest consist of $ k $ problems, resulting in a total of $ \\lfloor \\frac{m}{k} \\rfloor $ contests. This means that you select exactly $ \\lfloor \\frac{m}{k} \\rfloor \\cdot k $ problems for the contests in any combination you want, with each problem being selected at most once, and the remaining $m\\bmod k$ problems are left unused. For example, if $m = 17$ and $k = 3$, you should create exactly $5$ contests consisting of $3$ problems each, and exactly $2$ problems will be left unused.\n\nThere are $ n $ participants in the contests, with Kevin being the $1$-st participant. The $ i $-th participant has a rating of $ a_i $. During the contests, each participant solves all problems with a difficulty not exceeding their rating, meaning the $ i $-th participant solves the $ j $-th problem if and only if $ a_i \\geq b_j $. In each contest, Kevin's rank is one plus the number of participants who solve more problems than he does.\n\nFor each $ k = 1, 2, \\ldots, m $, Kevin wants to know the minimum sum of his ranks across all $ \\lfloor \\frac{m}{k} \\rfloor $ contests. In other words, for some value of $k$, after selecting the problems for each contest, you calculate the rank of Kevin in each contest and sum up these ranks over all $ \\lfloor \\frac{m}{k} \\rfloor $ contests. Your goal is to minimize this value.\n\nNote that contests for different values of $k$ are independent. It means that for different values of $k$, you can select the distribution of problems into the contests independently.",
    "tutorial": "Read all the hints. First, remove all contestants with a rating lower than yours, making you the contestant with the lowest rating. Since any problem you can solve can also be solved by everyone else, this does not affect your ranking. These problems can effectively be treated as having infinite difficulty. At this point, you cannot solve any problem, so your ranking in a competition is given by $(1 +$ the number of contestants who solve at least one problem in that competition $)$. Therefore, we only need to focus on the easiest problem in each competition. Precompute, for each problem, the number of contestants who can solve it, denoted as $c_i$. This can be done by sorting the contestants by rating and the problems by difficulty, then using a two-pointer or binary search approach to compute $c_i$. The remaining task is: given $c_i$, divide all $c_i$ into $\\lfloor \\frac{n}{k} \\rfloor$ groups, each containing $k$ elements, and minimize the sum of the maximum values in each group. This can be solved using a greedy algorithm: sort $c_i$ in ascending order, and for a given $k$, the answer is $(c_k+1) + (c_{2k}+1) + \\dots$. The brute force calculation is bounded by the harmonic series, and combined with sorting, the time complexity is $O(n \\log n + m \\log m)$.",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2048",
    "index": "E",
    "title": "Kevin and Bipartite Graph",
    "statement": "The Arms Factory needs a poster design pattern and finds Kevin for help.\n\nA poster design pattern is a bipartite graph with $ 2n $ vertices in the left part and $ m $ vertices in the right part, where there is an edge between each vertex in the left part and each vertex in the right part, resulting in a total of $ 2nm $ edges.\n\nKevin must color each edge with a positive integer in the range $ [1, n] $. A poster design pattern is good if there are no monochromatic cycles$^{\\text{∗}}$ in the bipartite graph.\n\nKevin needs your assistance in constructing a good bipartite graph or informing him if it is impossible.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A monochromatic cycle refers to a simple cycle in which all the edges are colored with the same color.\n\\end{footnotesize}",
    "tutorial": "The graph has a total of $2nm$ edges, and each color forms a forest. Therefore, for any given color, there are at most $2n + m - 1$ edges. Thus, the total number of edges cannot exceed $(2n + m - 1)n$. This gives the condition: $(2n+m-1)n\\ge 2nm$. Simplifying, we find $m \\leq 2n - 1$. Next, we only need to construct a valid case for $m = 2n - 1$ to solve the problem. In fact, this is easy to construct. Since each right-side vertex has a degree of $2n$, and there are $n$ total colors, let each color have exactly $2$ edges. For any given color, this is equivalent to choosing two left-side vertices to connect (ignoring the existence of the right-side vertices). After $2n - 1$ connections, the left-side vertices need to form a tree. It turns out that connecting the left-side vertices into a chain suffices. During construction, we can cycle the colors of the first right-side vertex. For example, for $n = 4$ and $m = 7$, the result looks like this: 1 4 4 3 3 2 2 1 1 4 4 3 3 2 2 1 1 4 4 3 3 2 2 1 1 4 4 3 3 2 2 1 1 4 4 3 3 2 2 1 1 4 4 3 3 2 2 1 1 4 4 3 3 2 2 1 Thus, a simple construction method is as follows: for left-side vertex $i$ and right-side vertex $j$, the color of the edge connecting them is given by: $\\left\\lfloor\\dfrac{(i+j)\\bmod 2n}2\\right\\rfloor+1$",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2048",
    "index": "E",
    "title": "Kevin and Bipartite Graph",
    "statement": "The Arms Factory needs a poster design pattern and finds Kevin for help.\n\nA poster design pattern is a bipartite graph with $ 2n $ vertices in the left part and $ m $ vertices in the right part, where there is an edge between each vertex in the left part and each vertex in the right part, resulting in a total of $ 2nm $ edges.\n\nKevin must color each edge with a positive integer in the range $ [1, n] $. A poster design pattern is good if there are no monochromatic cycles$^{\\text{∗}}$ in the bipartite graph.\n\nKevin needs your assistance in constructing a good bipartite graph or informing him if it is impossible.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A monochromatic cycle refers to a simple cycle in which all the edges are colored with the same color.\n\\end{footnotesize}",
    "tutorial": "The graph has a total of $2nm$ edges, and each color forms a forest. Therefore, for any given color, there are at most $2n + m - 1$ edges. Thus, the total number of edges cannot exceed $(2n + m - 1)n$. This gives the condition: $(2n+m-1)n\\ge 2nm$. Simplifying, we find $m \\leq 2n - 1$. Next, we only need to construct a valid case for $m = 2n - 1$ to solve the problem. In fact, this is easy to construct. Since each right-side vertex has a degree of $2n$, and there are $n$ total colors, let each color have exactly $2$ edges. For any given color, this is equivalent to choosing two left-side vertices to connect (ignoring the existence of the right-side vertices). After $2n - 1$ connections, the left-side vertices need to form a tree. It turns out that connecting the left-side vertices into a chain suffices. During construction, we can cycle the colors of the first right-side vertex. For example, for $n = 4$ and $m = 7$, the result looks like this: Thus, a simple construction method is as follows: for left-side vertex $i$ and right-side vertex $j$, the color of the edge connecting them is given by: $\\left\\lfloor\\dfrac{(i+j)\\bmod 2n}2\\right\\rfloor+1$",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2048",
    "index": "F",
    "title": "Kevin and Math Class",
    "statement": "Kevin is a student from Eversleeping Town, currently attending a math class where the teacher is giving him division exercises.\n\nOn the board, there are two rows of positive integers written, each containing $ n $ numbers. The first row is $ a_1, a_2, \\ldots, a_n $, and the second row is $ b_1, b_2, \\ldots, b_n $.\n\nFor each division exercise, Kevin can choose any segment $ [l, r] $ and find the smallest value $ x $ among $ b_l, b_{l+1}, \\ldots, b_r $. He will then modify each $ a_i $ for $ l \\leq i \\leq r $ to be the ceiling of $ a_i $ divided by $ x $.\n\nFormally, he selects two integers $ 1 \\leq l \\leq r \\leq n $, sets $ x = \\min_{l \\leq i \\leq r} b_i $, and changes all $ a_i $ for $ l \\leq i \\leq r $ to $ \\lceil \\frac{a_i}{x} \\rceil $.\n\nKevin can leave class and go home when all $ a_i $ become $ 1 $. He is eager to leave and wants to know the minimum number of division exercises required to achieve this.",
    "tutorial": "Construct a min Cartesian tree for the sequence $b$. It is easy to observe that we will only operate on the intervals defined by this Cartesian tree. To solve the problem, we can use DP on the Cartesian tree. Let $f_{u,i}$ represent the minimum possible maximum value of $a_x$ within the subtree rooted at $u$ after performing $i$ operations on all positions within that subtree. When merging, suppose the two child subtrees of $u$ are $ls$ and $rs$. The transition can be written as: $f_{u,k}=\\min_{i+j=k}\\left(\\max(f_{ls,i},f_{rs,j},a_u)\\right)$ Then consider division at the position corresponding to $b_u$, which updates the DP state: $f_{u,k+1}\\leftarrow\\left\\lceil\\frac{f_{u,k}}{b_u}\\right\\rceil$ Since operating on the entire sequence repeatedly can ensure that $\\log_2(\\max(a_i)) \\leq 63$ operations suffice, the second dimension of the DP state only needs to be defined for $0 \\sim 63$. Thus, the time complexity for this approach is $O(n \\log^2 a)$. The bottleneck of this approach lies in merging the DP states of the two subtrees. Observing that $f_{u,i}$ is monotonically non-increasing, the $\\min-\\max$ convolution for $f_{ls,i}$ and $f_{rs,i}$ is equivalent to merging two sequences using a merge sort-like approach. This reduces the merging complexity to $O(\\log a)$. Consequently, the overall complexity becomes $O(n \\log a)$, which is an optimal solution.",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "dp",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2048",
    "index": "F",
    "title": "Kevin and Math Class",
    "statement": "Kevin is a student from Eversleeping Town, currently attending a math class where the teacher is giving him division exercises.\n\nOn the board, there are two rows of positive integers written, each containing $ n $ numbers. The first row is $ a_1, a_2, \\ldots, a_n $, and the second row is $ b_1, b_2, \\ldots, b_n $.\n\nFor each division exercise, Kevin can choose any segment $ [l, r] $ and find the smallest value $ x $ among $ b_l, b_{l+1}, \\ldots, b_r $. He will then modify each $ a_i $ for $ l \\leq i \\leq r $ to be the ceiling of $ a_i $ divided by $ x $.\n\nFormally, he selects two integers $ 1 \\leq l \\leq r \\leq n $, sets $ x = \\min_{l \\leq i \\leq r} b_i $, and changes all $ a_i $ for $ l \\leq i \\leq r $ to $ \\lceil \\frac{a_i}{x} \\rceil $.\n\nKevin can leave class and go home when all $ a_i $ become $ 1 $. He is eager to leave and wants to know the minimum number of division exercises required to achieve this.",
    "tutorial": "Construct a min Cartesian tree for the sequence $b$. It is easy to observe that we will only operate on the intervals defined by this Cartesian tree. Proof: For any $b_x$, find the last $b_p \\leq b_x$ on its left and the first $b_q < b_x$ on its right. If we want to divide the interval by $b_x$, the operation interval cannot include both $p$ and $q$. At the same time, choosing the largest possible interval is always optimal. Hence, the operation interval must be $[p+1, q-1]$. All such intervals are exactly the intervals corresponding to the Cartesian tree. To solve the problem, we can use DP on the Cartesian tree. Let $f_{u,i}$ represent the minimum possible maximum value of $a_x$ within the subtree rooted at $u$ after performing $i$ operations on all positions within that subtree. When merging, suppose the two child subtrees of $u$ are $ls$ and $rs$. The transition can be written as: $f_{u,k}=\\min_{i+j=k}\\left(\\max(f_{ls,i},f_{rs,j},a_u)\\right)$ Then consider division at the position corresponding to $b_u$, which updates the DP state: $f_{u,k+1}\\leftarrow\\left\\lceil\\frac{f_{u,k}}{b_u}\\right\\rceil$ Since operating on the entire sequence repeatedly can ensure that $\\log_2(\\max(a_i)) \\leq 63$ operations suffice, the second dimension of the DP state only needs to be defined for $0 \\sim 63$. Thus, the time complexity for this approach is $O(n \\log^2 a)$. The bottleneck of this approach lies in merging the DP states of the two subtrees. Observing that $f_{u,i}$ is monotonically non-increasing, the $\\min-\\max$ convolution for $f_{ls,i}$ and $f_{rs,i}$ is equivalent to merging two sequences using a merge sort-like approach. This reduces the merging complexity to $O(\\log a)$. Consequently, the overall complexity becomes $O(n \\log a)$, which is an optimal solution.",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "dp",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2048",
    "index": "G",
    "title": "Kevin and Matrices",
    "statement": "Kevin has been transported to Sacred Heart Hospital, which contains all the $ n \\times m $ matrices with integer values in the range $ [1,v] $.\n\nNow, Kevin wants to befriend some matrices, but he is willing to befriend a matrix $ a $ if and only if the following condition is satisfied:\n\n$$ \\min_{1\\le i\\le n}\\left(\\max_{1\\le j\\le m}a_{i,j}\\right)\\le\\max_{1\\le j\\le m}\\left(\\min_{1\\le i\\le n}a_{i,j}\\right). $$\n\nPlease count how many matrices in Sacred Heart Hospital can be friends with Kevin.\n\nSince Kevin is very friendly, there could be many matrices that meet this condition. Therefore, you only need to output the result modulo $998\\,244\\,353$.",
    "tutorial": "Let us assume the left-hand side attains its maximum at position $L$, and the right-hand side attains its maximum at position $R$. For any $L, R$, let $P$ be the position in the same row as $L$ and the same column as $R$. Then we have $a_L \\geq a_P \\geq a_R$, which implies $a_L \\geq a_R$. Hence, we only need to consider cases where $a_L = a_R$. Now, consider positions where both sides attain their maximum value, denoted as $S$. Positions in $S$ are the maximum in their respective column and the minimum in their respective row. For any two positions $P, Q$ in $S$ that are not in the same row or column, we can observe that the positions in the same row as $P$ and the same column as $Q$, and vice versa, can also attain the maximum value. By induction, we can conclude that $S$ forms a subrectangle. Next, enumerate the maximum value $k$ and the size of $S$, denoted by $i \\times j$. The constraints are as follows: all remaining elements in the rows of $S$ must be $\\leq k$, and all remaining elements in the columns of $S$ must be $\\geq k$. Using the principle of inclusion-exclusion, we derive: $ans=\\sum_{k=1}^v\\sum_{i=1}^n\\sum_{j=1}^m(-1)^{i+j}\\binom ni\\binom mjk^{i(m-j)}(v-k+1)^{(n-i)j}v^{(n-i)(m-j)}$ The naive approach is $O(nmv)$, which is computationally expensive. Let us simplify: $=\\sum_{k=1}^v\\sum_{i=1}^n(-1)^i\\binom ni\\sum_{j=1}^m(-1)^{j}\\binom mj\\left(k^i\\right)^{m-j}\\left((v-k+1)^{n-i}\\right)^j\\left(v^{n-i}\\right)^{m-j}\\\\ =\\sum_{k=1}^v\\sum_{i=1}^n(-1)^i\\binom ni\\sum_{j=1}^m\\binom mj\\left(-(v-k+1)^{n-i}\\right)^j\\left(k^iv^{n-i}\\right)^{m-j}$ This resembles the Binomial Theorem. To simplify further, add and subtract the term for $j=0$: $=\\sum_{k=1}^v\\sum_{i=1}^n(-1)^i\\binom ni\\left(\\sum_{j=0}^m\\binom mj\\left(-(v-k+1)^{n-i}\\right)^j\\left(k^iv^{n-i}\\right)^{m-j}-\\left(k^iv^{n-i}\\right)^m\\right)\\\\ =\\sum_{k=1}^v\\sum_{i=1}^n(-1)^i\\binom ni\\left(\\left(-(v-k+1)^{n-i}+k^iv^{n-i}\\right)^m-\\left(k^iv^{n-i}\\right)^m\\right)$ Thus, the problem can be solved in $O(nv\\log m)$ time.",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2048",
    "index": "G",
    "title": "Kevin and Matrices",
    "statement": "Kevin has been transported to Sacred Heart Hospital, which contains all the $ n \\times m $ matrices with integer values in the range $ [1,v] $.\n\nNow, Kevin wants to befriend some matrices, but he is willing to befriend a matrix $ a $ if and only if the following condition is satisfied:\n\n$$ \\min_{1\\le i\\le n}\\left(\\max_{1\\le j\\le m}a_{i,j}\\right)\\le\\max_{1\\le j\\le m}\\left(\\min_{1\\le i\\le n}a_{i,j}\\right). $$\n\nPlease count how many matrices in Sacred Heart Hospital can be friends with Kevin.\n\nSince Kevin is very friendly, there could be many matrices that meet this condition. Therefore, you only need to output the result modulo $998\\,244\\,353$.",
    "tutorial": "Let us assume the left-hand side attains its maximum at position $L$, and the right-hand side attains its maximum at position $R$. For any $L, R$, let $P$ be the position in the same row as $L$ and the same column as $R$. Then we have $a_L \\geq a_P \\geq a_R$, which implies $a_L \\geq a_R$. Hence, we only need to consider cases where $a_L = a_R$. Now, consider positions where both sides attain their maximum value, denoted as $S$. Positions in $S$ are the maximum in their respective column and the minimum in their respective row. For any two positions $P, Q$ in $S$ that are not in the same row or column, we can observe that the positions in the same row as $P$ and the same column as $Q$, and vice versa, can also attain the maximum value. By induction, we can conclude that $S$ forms a subrectangle. Next, enumerate the maximum value $k$ and the size of $S$, denoted by $i \\times j$. The constraints are as follows: all remaining elements in the rows of $S$ must be $\\leq k$, and all remaining elements in the columns of $S$ must be $\\geq k$. Using the principle of inclusion-exclusion, we derive: $ans=\\sum_{k=1}^v\\sum_{i=1}^n\\sum_{j=1}^m(-1)^{i+j}\\binom ni\\binom mjk^{i(m-j)}(v-k+1)^{(n-i)j}v^{(n-i)(m-j)}$ The naive approach is $O(nmv)$, which is computationally expensive. Let us simplify: $=\\sum_{k=1}^v\\sum_{i=1}^n(-1)^i\\binom ni\\sum_{j=1}^m(-1)^{j}\\binom mj\\left(k^i\\right)^{m-j}\\left((v-k+1)^{n-i}\\right)^j\\left(v^{n-i}\\right)^{m-j}\\\\ =\\sum_{k=1}^v\\sum_{i=1}^n(-1)^i\\binom ni\\sum_{j=1}^m\\binom mj\\left(-(v-k+1)^{n-i}\\right)^j\\left(k^iv^{n-i}\\right)^{m-j}$ This resembles the Binomial Theorem. To simplify further, add and subtract the term for $j=0$: $=\\sum_{k=1}^v\\sum_{i=1}^n(-1)^i\\binom ni\\left(\\sum_{j=0}^m\\binom mj\\left(-(v-k+1)^{n-i}\\right)^j\\left(k^iv^{n-i}\\right)^{m-j}-\\left(k^iv^{n-i}\\right)^m\\right)\\\\ =\\sum_{k=1}^v\\sum_{i=1}^n(-1)^i\\binom ni\\left(\\left(-(v-k+1)^{n-i}+k^iv^{n-i}\\right)^m-\\left(k^iv^{n-i}\\right)^m\\right)$ Thus, the problem can be solved in $O(nv\\log m)$ time.",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2048",
    "index": "H",
    "title": "Kevin and Strange Operation",
    "statement": "Kevin is exploring problems related to binary strings in Chinatown. When he was at a loss, a stranger approached him and introduced a peculiar operation:\n\n- Suppose the current binary string is $ t $, with a length of $ \\vert t \\vert $. Choose an integer $ 1 \\leq p \\leq \\vert t \\vert $. For all $ 1 \\leq i < p $, \\textbf{simultaneously} perform the operation $ t_i = \\max(t_i, t_{i+1}) $, and then delete $ t_p $.\n\nFor example, suppose the current binary string is 01001, and you choose $ p = 4 $. Perform $ t_i = \\max(t_i, t_{i+1}) $ for $t_1$, $t_2$, and $ t_3 $, transforming the string into 11001, then delete $ t_4 $, resulting in 1101.\n\nKevin finds this strange operation quite interesting. Thus, he wants to ask you: Given a binary string $ s $, how many distinct non-empty binary strings can you obtain through any number of operations (possibly zero)?\n\nSince the answer may be very large, you only need to output the result modulo $998\\,244\\,353$.",
    "tutorial": "Assume that after performing several operations on the $01$ string $s$, we get the $01$ string $t$. It's not hard to notice that each element in $t$ corresponds to the $\\max$ of a subset of elements from $s$. Further observation shows that this subset must form a continuous segment, so we can express $t_i$ as $\\max\\limits_{k=l_i}^{r_i} s_k$. Initially, $t = s$, so all $l_i = r_i = i$. Suppose the current length of string $t$ is $m$, corresponding to two sequences $l$ and $r$. If an operation is performed at position $p$ where $1 \\le p \\le m$, the new sequence $t'$ will correspond to two sequences $l'$ and $r'$. Then, since for $1 \\le i < p$, we have $t'_i=\\max(t_i,t_{i+1})$, and for $p \\le i < m$, $t'_i=t_{i+1}$, it can be observed that for $1 \\le i < p$, we have $l'_i=l_i,r'_i=r_{i+1}$, and for $p \\le i < m$, $l'_i=l_{i+1},r'_i=r_{i+1}$. If we only focus on the change of sequences $l$ and $r$ to $l'$ and $r'$, it is equivalent to deleting the values $l_p$ and $r_1$. Thus, performing $k$ operations starting from the sequence $s$, the resulting sequence $t$ will correspond to the sequences $l$ and $r$, where $l$ is obtained by deleting any $k$ values from $1$ to $n$, and $r$ is the sequence from $k+1$ to $n$. Now, let's consider how to determine if the $01$ string $t$ can be generated. By reversing $t$ to get $t'$, the task becomes finding $n \\ge p_1 > p_2 > \\dots > p_k \\ge 1$ such that for all $1 \\le i \\le k$, we have $t'_i=\\max\\limits_{k=p_i}^{n-i+1}s_k$. A clearly correct greedy strategy is to choose $p_i$ in the order $i=1 \\sim k$, always selecting the largest possible value. Now consider performing DP. Let $dp_{i,j}$ represent how many length-$i$ $01$ strings $t$ can be generated such that after running the above greedy algorithm, $p_i$ exactly equals $j$. We assume that $p_0 = n+1$ and the boundary condition is $dp_{0,n+1} = 1$. We now consider the transition from $dp_{i-1,j}$ to $dp_{i,*}$: Both types of transitions can be considered as adding $dp_{i,j-1}$ to $dp_{i-1,j}$, then finding the largest $pos \\le n-i+1$ where $s_{pos} = 1$, and for all $j-1 > pos$ (i.e., $j \\ge pos+2$), adding $dp_{i,pos}$ to $dp_{i,j}$. The first type of transition can be viewed as a global shift of the DP array, while the second type requires calculating a segment suffix sum of the DP array and then performing a point update. This can be done efficiently using a segment tree in $O(n \\log n)$ time for all transitions. The final answer is the sum of all $1 \\le i \\le n, 1 \\le j \\le n$ of $dp_{i,j}$. Using a segment tree for maintenance, we can also query the sum of each entry of $dp_i$ in $O(1)$ time (by setting to zero those entries where $dp_{i-1,1}$ is out of range after the shift). Since the transitions have better properties, it's actually possible to solve the problem cleverly using prefix sums in $O(n)$ time without needing complex data structures, but that is not strictly necessary.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2048",
    "index": "H",
    "title": "Kevin and Strange Operation",
    "statement": "Kevin is exploring problems related to binary strings in Chinatown. When he was at a loss, a stranger approached him and introduced a peculiar operation:\n\n- Suppose the current binary string is $ t $, with a length of $ \\vert t \\vert $. Choose an integer $ 1 \\leq p \\leq \\vert t \\vert $. For all $ 1 \\leq i < p $, \\textbf{simultaneously} perform the operation $ t_i = \\max(t_i, t_{i+1}) $, and then delete $ t_p $.\n\nFor example, suppose the current binary string is 01001, and you choose $ p = 4 $. Perform $ t_i = \\max(t_i, t_{i+1}) $ for $t_1$, $t_2$, and $ t_3 $, transforming the string into 11001, then delete $ t_4 $, resulting in 1101.\n\nKevin finds this strange operation quite interesting. Thus, he wants to ask you: Given a binary string $ s $, how many distinct non-empty binary strings can you obtain through any number of operations (possibly zero)?\n\nSince the answer may be very large, you only need to output the result modulo $998\\,244\\,353$.",
    "tutorial": "Assume that after performing several operations on the $01$ string $s$, we get the $01$ string $t$. It's not hard to notice that each element in $t$ corresponds to the $\\max$ of a subset of elements from $s$. Further observation shows that this subset must form a continuous segment, so we can express $t_i$ as $\\max\\limits_{k=l_i}^{r_i} s_k$. Initially, $t = s$, so all $l_i = r_i = i$. Suppose the current length of string $t$ is $m$, corresponding to two sequences $l$ and $r$. If an operation is performed at position $p$ where $1 \\le p \\le m$, the new sequence $t'$ will correspond to two sequences $l'$ and $r'$. Then, since for $1 \\le i < p$, we have $t'_i=\\max(t_i,t_{i+1})$, and for $p \\le i < m$, $t'_i=t_{i+1}$, it can be observed that for $1 \\le i < p$, we have $l'_i=l_i,r'_i=r_{i+1}$, and for $p \\le i < m$, $l'_i=l_{i+1},r'_i=r_{i+1}$. If we only focus on the change of sequences $l$ and $r$ to $l'$ and $r'$, it is equivalent to deleting the values $l_p$ and $r_1$. Thus, performing $k$ operations starting from the sequence $s$, the resulting sequence $t$ will correspond to the sequences $l$ and $r$, where $l$ is obtained by deleting any $k$ values from $1$ to $n$, and $r$ is the sequence from $k+1$ to $n$. Now, let's consider how to determine if the $01$ string $t$ can be generated. By reversing $t$ to get $t'$, the task becomes finding $n \\ge p_1 > p_2 > \\dots > p_k \\ge 1$ such that for all $1 \\le i \\le k$, we have $t'_i=\\max\\limits_{k=p_i}^{n-i+1}s_k$. A clearly correct greedy strategy is to choose $p_i$ in the order $i=1 \\sim k$, always selecting the largest possible value. Now consider performing DP. Let $dp_{i,j}$ represent how many length-$i$ $01$ strings $t$ can be generated such that after running the above greedy algorithm, $p_i$ exactly equals $j$. We assume that $p_0 = n+1$ and the boundary condition is $dp_{0,n+1} = 1$. We now consider the transition from $dp_{i-1,j}$ to $dp_{i,*}$: If $s[j-1, n-i+1]$ already contains $1$, then the $i$-th position in the reversed $t$ must be $1$, and it must be the case that $p_i = j-1$, so we add $dp_{i,j-1}$ to $dp_{i-1,j}$. If $s[j-1, n-i+1]$ does not contain $1$, the $i$-th position in the reversed $t$ can be $0$. If it is $0$, then it must be the case that $p_i = j-1$, and we add $dp_{i,j-1}$ to $dp_{i-1,j}$; if we want the $i$-th position in the reversed $t$ to be $1$, we need to find the largest $pos \\le n-i+1$ such that $s_{pos} = 1$, and then set $p_i = pos$, adding $dp_{i,pos}$ to $dp_{i-1,j}$. Both types of transitions can be considered as adding $dp_{i,j-1}$ to $dp_{i-1,j}$, then finding the largest $pos \\le n-i+1$ where $s_{pos} = 1$, and for all $j-1 > pos$ (i.e., $j \\ge pos+2$), adding $dp_{i,pos}$ to $dp_{i,j}$. The first type of transition can be viewed as a global shift of the DP array, while the second type requires calculating a segment suffix sum of the DP array and then performing a point update. This can be done efficiently using a segment tree in $O(n \\log n)$ time for all transitions. The final answer is the sum of all $1 \\le i \\le n, 1 \\le j \\le n$ of $dp_{i,j}$. Using a segment tree for maintenance, we can also query the sum of each entry of $dp_i$ in $O(1)$ time (by setting to zero those entries where $dp_{i-1,1}$ is out of range after the shift). Since the transitions have better properties, it's actually possible to solve the problem cleverly using prefix sums in $O(n)$ time without needing complex data structures, but that is not strictly necessary.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2048",
    "index": "I1",
    "title": "Kevin and Puzzle (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, you need to find any one good array. You can hack only if you solved all versions of this problem.}\n\nKevin is visiting the Red Church, and he found a puzzle on the wall.\n\nFor an array $ a $, let $ c(l,r) $ indicate how many distinct numbers are among $ a_l, a_{l+1}, \\ldots, a_r $. In particular, if $ l > r $, define $ c(l,r) = 0 $.\n\nYou are given a string $ s $ of length $ n $ consisting of letters $ L $ and $ R $ only. Let a non-negative array $ a $ be called good, if the following conditions hold for $ 1 \\leq i \\leq n $:\n\n- if $s_i=\\verb!L!$, then $c(1,i-1)=a_i$;\n- if $s_i=\\verb!R!$, then $c(i+1,n)=a_i$.\n\nIf there is a good array $a$, print any of the good arrays. Otherwise, report that no such arrays exists.",
    "tutorial": "Lemma: Suppose the largest value filled is $mx$, and the number of distinct values is $c$. Let $d = c - mx$. Then, $d = 0$ or $d = 1$. Proof: Clearly, $c \\le mx + 1$. If $c < mx$, observe where $mx$ is placed, and a contradiction arises. Now, consider the leftmost and rightmost characters in sequence $s$: We recursively remove the leftmost and rightmost characters, solve for the inner region, add $1$ to all of them, and place $0$ and $x$ at both ends. Now, consider how $d$ changes: Therefore, consider the outermost RL. If it contains LL or RR inside, there is no solution. Otherwise, a solution always exists, and it can be easily constructed based on the above process, the time complexity is $O(n)$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2048",
    "index": "I1",
    "title": "Kevin and Puzzle (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, you need to find any one good array. You can hack only if you solved all versions of this problem.}\n\nKevin is visiting the Red Church, and he found a puzzle on the wall.\n\nFor an array $ a $, let $ c(l,r) $ indicate how many distinct numbers are among $ a_l, a_{l+1}, \\ldots, a_r $. In particular, if $ l > r $, define $ c(l,r) = 0 $.\n\nYou are given a string $ s $ of length $ n $ consisting of letters $ L $ and $ R $ only. Let a non-negative array $ a $ be called good, if the following conditions hold for $ 1 \\leq i \\leq n $:\n\n- if $s_i=\\verb!L!$, then $c(1,i-1)=a_i$;\n- if $s_i=\\verb!R!$, then $c(i+1,n)=a_i$.\n\nIf there is a good array $a$, print any of the good arrays. Otherwise, report that no such arrays exists.",
    "tutorial": "Lemma: Suppose the largest value filled is $mx$, and the number of distinct values is $c$. Let $d = c - mx$. Then, $d = 0$ or $d = 1$. Proof: Clearly, $c \\le mx + 1$. If $c < mx$, observe where $mx$ is placed, and a contradiction arises. Now, consider the leftmost and rightmost characters in sequence $s$: If they are L and R, we can see that both positions must be filled with $0$, and no other position can be filled with $0$. For internal positions, whether L or R, $0$ counts as a distinct number. Therefore, we can remove these two positions, recursively solve for the remaining part, add $1$ to all numbers, and then place a $0$ at both ends. If both are L, the leftmost L must be $0$. Suppose the rightmost L is filled with $x$. It is easy to prove that $x$ cannot be placed in internal positions. For internal positions, whether L or R, either $0$ or $x$ is counted as a distinct number. So, as in the previous case, we remove the two positions, recursively solve for the remaining part, add $1$ to all numbers, and then add $0$ and $x$ at both ends. The value of $x$ must be the number of distinct values inside plus 1. This condition is equivalent to the internal region satisfying $d = 1$. If both are R, the analysis is the same as for the L and L case. If the leftmost character is R and the rightmost character is L, a simple construction is to fill everything with $1$. In this case, no $0$ will appear, so this case can only correspond to $d = 0$. We recursively remove the leftmost and rightmost characters, solve for the inner region, add $1$ to all of them, and place $0$ and $x$ at both ends. Now, consider how $d$ changes: For the LR case, $d$ remains unchanged. For LL or RR, the internal region must satisfy $d = 1$. For RL, the entire region results in $d = 0$. Therefore, consider the outermost RL. If it contains LL or RR inside, there is no solution. Otherwise, a solution always exists, and it can be easily constructed based on the above process, the time complexity is $O(n)$.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2048",
    "index": "I2",
    "title": "Kevin and Puzzle (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to count the number of good arrays. You can hack only if you solved all versions of this problem.}\n\nKevin is visiting the Red Church, and he found a puzzle on the wall.\n\nFor an array $ a $, let $ c(l,r) $ indicate how many distinct numbers are among $ a_l, a_{l+1}, \\ldots, a_r $. In particular, if $ l > r $, define $ c(l,r) = 0 $.\n\nYou are given a string $ s $ of length $ n $ consisting of letters $ L $ and $ R $ only. Let a non-negative array $ a $ be called good, if the following conditions hold for $ 1 \\leq i \\leq n $:\n\n- if $s_i=\\verb!L!$, then $c(1,i-1)=a_i$;\n- if $s_i=\\verb!R!$, then $c(i+1,n)=a_i$.\n\nYou need to count the number of good arrays $a$. Since the answer may be large, you only need to output the answer modulo $998\\,244\\,353$.",
    "tutorial": "According to the easy version, we can see that most cases have very few solutions because for LR, LL, and RR, after filling in the inner part, the outer layer only has one unique way to fill. Therefore, if there is no RL layer, the answer must be $1$. Next, consider the case where RL is present. Let's assume that RL is the outermost pair of characters. It can be proved that the numbers at the R and L positions in this RL must be the same. The specific proof is omitted here, but readers can prove this for themselves easily. Let this common value be $m$. Then, enumerate the rightmost R position $x$ filled with $m$ and the leftmost L position $y$ filled with $m$. Now, let's discuss the relationship between $x$ and $y$: If $x > y$, it can be observed that all Ls to the right of $x$ must be filled with $m$, and all Rs to the right of $x$ have only one way to be filled. The same applies for $y$. For this case, we can directly enumerate $m$, then determine the unique positions for $x$ and $y$, and check if $x > y$. If $x < y$, at this point, all Rs to the left of $x$ must be filled with $m$, and the Ls to the left of $x$ have only one way to be filled. Similarly for the right side of $y$. Now, consider the section between $(x, y)$. Clearly, $m$ must not appear in the middle, so we can delete $x$ and all Rs to its left, as well as $y$ and all Ls to its right (i.e., remove all positions where the value is $m$). The resulting sequence is called the remaining sequence. After removing these characters, we solve for the remaining sequence, then add $1$ to all the numbers obtained, and finally, add all positions filled with $m$. Below is an example of an initial sequence, where the red characters are $x$ and $y$, and the omitted part is the section between $(x, y)$. Below is the corresponding remaining sequence, with $*$ representing the original sequence positions of $x$ and $y$. After filling the remaining sequence, we need to analyze the conditions for adding all positions filled with $m$: we divide the remaining sequence into three parts: \"left\", \"middle\", and \"right\", with the positions of $x$ and $y$ as boundaries, where the left part contains only Ls, and the right part contains only Rs. The condition to be satisfied is that let the total number of colors in the \"left-middle\" part be $c_1$, and the total number of colors in the \"middle-right\" part be $c_2$, then we need $m = c_1 + 1 = c_2 + 1$. Additionally, $m$ must not appear in the remaining sequence. This restriction is equivalent to requiring both the \"left-middle\" and \"middle-right\" parts to satisfy $d = 1$. It can be concluded that the remaining sequence satisfies $d = 1$. For the condition $c_1 = c_2$, it is easy to see that it is equivalent to: let $z$ be the larger of the counts of the left and right parts, then the first $z$ characters of the remaining sequence must all be L, and the last $z$ characters must all be R. The final necessary and sufficient condition is: let $x$ have $a$ Ls to the left, and $y$ have $b$ Rs to the right. Without loss of generality, assume $a \\ge b$. Remove the substring between $(x, y)$ (not including $x$ and $y$). This remaining substring needs to satisfy that the last $a-b$ characters are Rs, and after removing these $a-b$ Rs, the resulting string must satisfy $d = 1$, meaning there is no RL situation when taking the first and last characters. Since $d = 1$, if the remaining sequence satisfies this condition, there will be exactly one way to fill it. Finally, we only need to count the cases separately. The case where $x > y$ can be counted in $O(n)$, for the case where $x < y$, without loss of generality, assume $a \\ge b$, we can enumerate $y$, calculate the length of the longest consecutive Rs before $y$, denoted as $cnt$, so the restriction on $a$ becomes $b \\le a \\le b + cnt$. Through the above observations, we only need to enumerate $O(n)$ pairs of $x$ and $y$ and check whether they increase the answer by $1$. That is, the answer is at the $O(n)$ level. The last problem is: for each given interval $[l, r]$, we need to check if there is any RL situation when taking the first and last characters of this string. A simple solution is to use a bitset to maintain, for example, by scanning $r$ from small to large, and maintaining the existence of RL for each $l + r$. The time complexity of this approach is $O(\\frac{n^2}{\\omega})$, which can be handled by this problem. If using block convolution, a more optimal complexity can be achieved. In fact, if further exploring the properties, the time complexity can be reduced to $O(n \\log^2 n)$ (requiring convolution), which you can explore on your own if you are interested.",
    "tags": [
      "bitmasks",
      "fft",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2048",
    "index": "I2",
    "title": "Kevin and Puzzle (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to count the number of good arrays. You can hack only if you solved all versions of this problem.}\n\nKevin is visiting the Red Church, and he found a puzzle on the wall.\n\nFor an array $ a $, let $ c(l,r) $ indicate how many distinct numbers are among $ a_l, a_{l+1}, \\ldots, a_r $. In particular, if $ l > r $, define $ c(l,r) = 0 $.\n\nYou are given a string $ s $ of length $ n $ consisting of letters $ L $ and $ R $ only. Let a non-negative array $ a $ be called good, if the following conditions hold for $ 1 \\leq i \\leq n $:\n\n- if $s_i=\\verb!L!$, then $c(1,i-1)=a_i$;\n- if $s_i=\\verb!R!$, then $c(i+1,n)=a_i$.\n\nYou need to count the number of good arrays $a$. Since the answer may be large, you only need to output the answer modulo $998\\,244\\,353$.",
    "tutorial": "According to the easy version, we can see that most cases have very few solutions because for LR, LL, and RR, after filling in the inner part, the outer layer only has one unique way to fill. Therefore, if there is no RL layer, the answer must be $1$. Next, consider the case where RL is present. Let's assume that RL is the outermost pair of characters. It can be proved that the numbers at the R and L positions in this RL must be the same. The specific proof is omitted here, but readers can prove this for themselves easily. Let this common value be $m$. Then, enumerate the rightmost R position $x$ filled with $m$ and the leftmost L position $y$ filled with $m$. Now, let's discuss the relationship between $x$ and $y$: If $x > y$, it can be observed that all Ls to the right of $x$ must be filled with $m$, and all Rs to the right of $x$ have only one way to be filled. The same applies for $y$. For this case, we can directly enumerate $m$, then determine the unique positions for $x$ and $y$, and check if $x > y$. If $x > y$, it can be observed that all Ls to the right of $x$ must be filled with $m$, and all Rs to the right of $x$ have only one way to be filled. The same applies for $y$. For this case, we can directly enumerate $m$, then determine the unique positions for $x$ and $y$, and check if $x > y$. If $x < y$, at this point, all Rs to the left of $x$ must be filled with $m$, and the Ls to the left of $x$ have only one way to be filled. Similarly for the right side of $y$. Now, consider the section between $(x, y)$. Clearly, $m$ must not appear in the middle, so we can delete $x$ and all Rs to its left, as well as $y$ and all Ls to its right (i.e., remove all positions where the value is $m$). The resulting sequence is called the remaining sequence. After removing these characters, we solve for the remaining sequence, then add $1$ to all the numbers obtained, and finally, add all positions filled with $m$. Below is an example of an initial sequence, where the red characters are $x$ and $y$, and the omitted part is the section between $(x, y)$. Below is the corresponding remaining sequence, with $*$ representing the original sequence positions of $x$ and $y$. After filling the remaining sequence, we need to analyze the conditions for adding all positions filled with $m$: we divide the remaining sequence into three parts: \"left\", \"middle\", and \"right\", with the positions of $x$ and $y$ as boundaries, where the left part contains only Ls, and the right part contains only Rs. The condition to be satisfied is that let the total number of colors in the \"left-middle\" part be $c_1$, and the total number of colors in the \"middle-right\" part be $c_2$, then we need $m = c_1 + 1 = c_2 + 1$. Additionally, $m$ must not appear in the remaining sequence. This restriction is equivalent to requiring both the \"left-middle\" and \"middle-right\" parts to satisfy $d = 1$. It can be concluded that the remaining sequence satisfies $d = 1$. For the condition $c_1 = c_2$, it is easy to see that it is equivalent to: let $z$ be the larger of the counts of the left and right parts, then the first $z$ characters of the remaining sequence must all be L, and the last $z$ characters must all be R. The final necessary and sufficient condition is: let $x$ have $a$ Ls to the left, and $y$ have $b$ Rs to the right. Without loss of generality, assume $a \\ge b$. Remove the substring between $(x, y)$ (not including $x$ and $y$). This remaining substring needs to satisfy that the last $a-b$ characters are Rs, and after removing these $a-b$ Rs, the resulting string must satisfy $d = 1$, meaning there is no RL situation when taking the first and last characters. Since $d = 1$, if the remaining sequence satisfies this condition, there will be exactly one way to fill it. If $x < y$, at this point, all Rs to the left of $x$ must be filled with $m$, and the Ls to the left of $x$ have only one way to be filled. Similarly for the right side of $y$. Now, consider the section between $(x, y)$. Clearly, $m$ must not appear in the middle, so we can delete $x$ and all Rs to its left, as well as $y$ and all Ls to its right (i.e., remove all positions where the value is $m$). The resulting sequence is called the remaining sequence. After removing these characters, we solve for the remaining sequence, then add $1$ to all the numbers obtained, and finally, add all positions filled with $m$. Below is an example of an initial sequence, where the red characters are $x$ and $y$, and the omitted part is the section between $(x, y)$. Below is the corresponding remaining sequence, with $*$ representing the original sequence positions of $x$ and $y$. After filling the remaining sequence, we need to analyze the conditions for adding all positions filled with $m$: we divide the remaining sequence into three parts: \"left\", \"middle\", and \"right\", with the positions of $x$ and $y$ as boundaries, where the left part contains only Ls, and the right part contains only Rs. The condition to be satisfied is that let the total number of colors in the \"left-middle\" part be $c_1$, and the total number of colors in the \"middle-right\" part be $c_2$, then we need $m = c_1 + 1 = c_2 + 1$. Additionally, $m$ must not appear in the remaining sequence. This restriction is equivalent to requiring both the \"left-middle\" and \"middle-right\" parts to satisfy $d = 1$. It can be concluded that the remaining sequence satisfies $d = 1$. For the condition $c_1 = c_2$, it is easy to see that it is equivalent to: let $z$ be the larger of the counts of the left and right parts, then the first $z$ characters of the remaining sequence must all be L, and the last $z$ characters must all be R. The final necessary and sufficient condition is: let $x$ have $a$ Ls to the left, and $y$ have $b$ Rs to the right. Without loss of generality, assume $a \\ge b$. Remove the substring between $(x, y)$ (not including $x$ and $y$). This remaining substring needs to satisfy that the last $a-b$ characters are Rs, and after removing these $a-b$ Rs, the resulting string must satisfy $d = 1$, meaning there is no RL situation when taking the first and last characters. Since $d = 1$, if the remaining sequence satisfies this condition, there will be exactly one way to fill it. Finally, we only need to count the cases separately. The case where $x > y$ can be counted in $O(n)$, for the case where $x < y$, without loss of generality, assume $a \\ge b$, we can enumerate $y$, calculate the length of the longest consecutive Rs before $y$, denoted as $cnt$, so the restriction on $a$ becomes $b \\le a \\le b + cnt$. When $cnt = 0$, the value of $a$ is fixed, but the corresponding $x$ can be chosen from any position in a consecutive block of Rs. We find that because $cnt = 0$, i.e., the position before $y$ is filled with L, then the position after $x$ cannot be filled with R, so $x$ can only be chosen as the last R in the consecutive R block. When $cnt > 0$, we only need to enumerate the values of $x$. It is easy to see that each $x$ will be counted at most $2$ times. Through the above observations, we only need to enumerate $O(n)$ pairs of $x$ and $y$ and check whether they increase the answer by $1$. That is, the answer is at the $O(n)$ level. The last problem is: for each given interval $[l, r]$, we need to check if there is any RL situation when taking the first and last characters of this string. A simple solution is to use a bitset to maintain, for example, by scanning $r$ from small to large, and maintaining the existence of RL for each $l + r$. The time complexity of this approach is $O(\\frac{n^2}{\\omega})$, which can be handled by this problem. If using block convolution, a more optimal complexity can be achieved. In fact, if further exploring the properties, the time complexity can be reduced to $O(n \\log^2 n)$ (requiring convolution), which you can explore on your own if you are interested.",
    "tags": [
      "bitmasks",
      "fft",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2049",
    "index": "A",
    "title": "MEX Destruction",
    "statement": "Evirir the dragon snuck into a wizard's castle and found a mysterious contraption, and their playful instincts caused them to play with (destroy) it...\n\nEvirir the dragon found an array $a_1, a_2, \\ldots, a_n$ of $n$ non-negative integers.\n\nIn one operation, they can choose a non-empty subarray$^{\\text{∗}}$ $b$ of $a$ and replace it with the integer $\\operatorname{mex}(b)$$^{\\text{†}}$. They want to use this operation any number of times to make $a$ only contain zeros. It can be proven that this is always possible under the problem constraints.\n\nWhat is the minimum number of operations needed?\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\n$^{\\text{†}}$The minimum excluded (MEX) of a collection of integers $f_1, f_2, \\ldots, f_k$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $f$.\n\\end{footnotesize}",
    "tutorial": "Case 1: All elements are $0$. Then the answer is $0$. Case 2: Some element is non-zero, and all non-zero elements form a contiguous subarray. Then the answer is $1$ since we can choose that subarray and replace it with a $0$. Case 3: Otherwise, the answer is $2$. We can replace the entire array with a non-zero element (since $0$ is in the array), then replace the entire array again with a $0$ (since the only element left is non-zero). $1$ operation is not enough. If we only use $1$ operation, the selected subarray must contain all non-zero elements. Since the non-zero elements do not form a subarray, the selected subarray must contain a $0$, thus the $\\operatorname{MEX}$ will be non-zero.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve()\n{\n    int n; cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++)\n        cin >> a[i];\n\n    while (!a.empty() && a.back() == 0)\n        a.pop_back();\n\n    reverse(a.begin(), a.end());\n    while (!a.empty() && a.back() == 0)\n        a.pop_back();\n    reverse(a.begin(), a.end());\n\n    if (a.empty())\n    {\n        cout << 0 << '\\n';\n        return;\n    }\n\n    bool hasZero = false;\n    for (const auto x : a)\n        hasZero |= x == 0;\n    if (hasZero)\n        cout << 2 << '\\n';\n    else\n        cout << 1 << '\\n';\n}\n\nint main()\n{\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++)\n        solve();\n\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2049",
    "index": "B",
    "title": "pspspsps",
    "statement": "Cats are attracted to pspspsps, but Evirir, being a dignified dragon, is only attracted to pspspsps with oddly specific requirements...\n\nGiven a string $s = s_1s_2\\ldots s_n$ of length $n$ consisting of characters p, s, and . (dot), determine whether a permutation$^{\\text{∗}}$ $p$ of length $n$ exists, such that for all integers $i$ ($1 \\le i \\le n$):\n\n- If $s_i$ is p, then $[p_1, p_2, \\ldots, p_i]$ forms a permutation (of length $i$);\n- If $s_i$ is s, then $[p_i, p_{i+1}, \\ldots, p_{n}]$ forms a permutation (of length $n-i+1$);\n- If $s_i$ is ., then there is no additional restriction.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "Since the entire $p$ must be a permutation, if $s_1 =$s, we can set $s_1 =$., and if $s_n =$p, we can set $s_n =$.. After that, the answer is YES if and only if all non-dot characters in $s$ are all p or s. If all non-dot characters are p, we can choose the permutation $p = [1, 2, \\ldots, n]$. If all non-dot characters are s, we can choose $p = [n, n - 1, \\ldots, 1]$. Otherwise, there exists both a p and a s. Suppose for contradiction that there is a solution. Let $a$ and $b$ represent the subarrays represented by the p and s respectively. Without loss of generality, suppose $a$ is the shorter subarray. Since $b$ is also a permutation, the elements of $a$ must be in $b$. Since $p$ is a permutation, $a$ must be a subarray of $b$. However, $b$ cannot contain $a$: since $b$ is not the entire $p$, $b$ does not contain $p_1$. However, $a$ contains $p_1$. Contradiction.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid solve()\n{\n    int n; cin >> n;\n    string s; cin >> s;\n    if (s[0] == 's') s[0] = '.';\n    if (s.back() == 'p') s.back() = '.';\n    bool found_p = false;\n    bool found_s = false;\n    for (const auto c : s)\n    {\n        switch (c)\n        {\n        case 'p':\n            found_p = true;\n            break;\n        case 's':\n            found_s = true;\n            break;\n        }\n    }\n    cout << (found_p && found_s ? \"NO\" : \"YES\") << '\\n';\n}\n\nint main()\n{\n    int t; cin >> t;\n    for (int i = 0; i < t; i++) solve();\n\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graph matchings",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2049",
    "index": "C",
    "title": "MEX Cycle",
    "statement": "Evirir the dragon has many friends. They have 3 friends! That is one more than the average dragon.\n\nYou are given integers $n$, $x$, and $y$. There are $n$ dragons sitting in a circle. The dragons are numbered $1, 2, \\ldots, n$. For each $i$ ($1 \\le i \\le n$), dragon $i$ is friends with dragon $i - 1$ and $i + 1$, where dragon $0$ is defined to be dragon $n$ and dragon $n + 1$ is defined to be dragon $1$. Additionally, dragons $x$ and $y$ are friends with each other (if they are already friends, this changes nothing). Note that all friendships are mutual.\n\nOutput $n$ non-negative integers $a_1, a_2, \\ldots, a_n$ such that for each dragon $i$ ($1 \\le i \\le n$), the following holds:\n\n- Let $f_1, f_2, \\ldots, f_k$ be the friends of dragon $i$. Then $a_i = \\operatorname{mex}(a_{f_1}, a_{f_2}, \\ldots, a_{f_k})$.$^{\\text{∗}}$\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The minimum excluded (MEX) of a collection of integers $c_1, c_2, \\ldots, c_m$ is defined as the smallest non-negative integer $t$ which does not occur in the collection $c$.\n\\end{footnotesize}",
    "tutorial": "There are many possible solutions. The simplest one we can find (thanks to Kaey) is as follows: Set $a_x = 0, a_{x+1} = 1, a_{x+2} = 0, \\ldots$, alternating between 0 and 1, wrapping around accordingly. Formally, using 0-based indexing, set $a_{(x+i) \\bmod n} = i \\bmod 2$ for all $i$ ($0 \\le i \\le n - 1$). If $n$ is odd or if $x - y$ is even, set $a_x = 2$. Why this works: If $n$ is even and $x - y$ is odd, all $0$'s are only friends with $1$'s and vice versa. If $n$ is odd, $a_x$ will be adjacent to $0$ and $1$, so we set $a_x = 2$. Now $a$ is valid ignoring the extra friendship. Adding in the extra friendship, $a$ is still valid since $a_x = 2 > a_y$, so it will not affect $a_y$. If $n$ is even and $x - y$ is even, the extra friendship connects two $0$ or two $1$. Setting $a_x = 2$ works because dragon $x$'s friends still have another neighbor to maintain their $\\operatorname{MEX}$.",
    "code": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nvoid solve() {\n    int n, x, y;\n    cin >> n >> x >> y;\n    --x; --y;\n    vector<int> ans(n);\n    for (int i = 0; i < n; ++i) ans[(x + i) % n] = i % 2;\n    if (n % 2 || (x - y) % 2 == 0)\n        ans[x] = 2;\n    for (auto x : ans)cout << x << ' ';\n    cout << endl;\n}\n\nint main() {\n    int T;\n    cin >> T;\n    while (T--) solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2049",
    "index": "D",
    "title": "Shift + Esc",
    "statement": "After having fun with a certain contraption and getting caught, Evirir the dragon decides to put their magical skills to good use — warping reality to escape fast!\n\nYou are given a grid with $n$ rows and $m$ columns of non-negative integers and an integer $k$. Let $(i, j)$ denote the cell in the $i$-th row from the top and $j$-th column from the left ($1 \\le i \\le n$, $1 \\le j \\le m$). For every cell $(i, j)$, the integer $a_{i, j}$ is written on the cell $(i, j)$.\n\nYou are initially at $(1, 1)$ and want to go to $(n, m)$. You may only move down or right. That is, if you are at $(i, j)$, you can only move to $(i+1, j)$ or $(i, j+1)$ (if the corresponding cell exists).\n\nBefore you begin moving, you may do the following operation any number of times:\n\n- Choose an integer $i$ between $1$ and $n$ and cyclically shift row $i$ to the left by $1$. Formally, simultaneously set $a_{i,j}$ to $a_{i,(j \\bmod m) + 1}$ for all integers $j$ ($1 \\le j \\le m$).\n\nNote that you may not do any operation after you start moving.After moving from $(1, 1)$ to $(n, m)$, let $x$ be the number of operations you have performed before moving, and let $y$ be the sum of the integers written on visited cells (including $(1, 1)$ and $(n, m)$). Then the cost is defined as $kx + y$.\n\nFind the minimum cost to move from $(1, 1)$ to $(n, m)$.",
    "tutorial": "Let $f(i,j)$ be the minimum cost to move to cell $(i,j)$ after shifting and Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] For simplicity sake, we will add a row with all zeros above the first row. Also note that the operations with states denoting columns are all under modulo Unable to parse markup [type=CF_MATHJAX] The transitions are as follows: Base cases: Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] From row Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] In Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] The final answer is Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX]",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long int ll;\nll dp[511][511],a[511][511];\n\nvoid solve()\n{\n    int n,m,k;\n    cin>>n>>m>>k;\n    for(int i=1;i<=n;i++){\n        for(int j=0;j<m;j++)cin>>a[i][j];\n    }\n    for(int i=0;i<=n;i++){\n        for(int j=0;j<m;j++)dp[i][j] = 1e18;\n    }\n\n    dp[0][0] = 0;\n    for(int i=1;i<=n;i++){\n        for(int shift = 0;shift<m;shift++){\n            vector<ll>tmp(m,1e18);\n            for(int j=0;j<m;j++)tmp[j] = dp[i-1][j] + a[i][(j+shift)%m] + k*1LL*shift;\n\n            for(int j=0;j<m;j++)tmp[j] = min(tmp[j],tmp[(j+m-1)%m] + a[i][(j+shift)%m]);\n            for(int j=0;j<m;j++)tmp[j] = min(tmp[j],tmp[(j+m-1)%m] + a[i][(j+shift)%m]);\n            for(int j=0;j<m;j++)dp[i][j] = min(dp[i][j],tmp[j]);\n        }\n        //for(int j=0;j<m;j++)cout<<dp[i][j]<<\" \";\n       // cout<<'\\n';\n    }\n    cout<<dp[n][m-1]<<endl;\n}\n\nint main()\n{\n    int t; cin>>t;\n    for (int i = 0; i < t; i++) solve();\n}",
    "tags": [
      "brute force",
      "dp"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2049",
    "index": "E",
    "title": "Broken Queries",
    "statement": "You, a wizard whose creation was destroyed by a dragon, are determined to hunt it down with a magical AOE tracker. But it seems to be toyed with...\n\nThis is an interactive problem.\n\nThere is a hidden binary array $a$ of length $n$ ($\\mathbf{n}$ \\textbf{is a power of 2}) and a hidden integer $k\\ (2 \\le k \\le n - 1)$. The array $a$ contains \\textbf{exactly one 1} (and all other elements are 0). For two integers $l$ and $r$ ($1 \\le l \\le r \\le n$), define the range sum $s(l, r) = a_l + a_{l+1} + \\cdots + a_r$.\n\nYou have a magical device that takes ranges and returns range sums, but it returns the opposite result when the range has length at least $k$. Formally, in one query, you can give it a pair of integers $[l, r]$ where $1 \\le l \\le r \\le n$, and it will return either $0$ or $1$ according to the following rules:\n\n- If $r - l + 1 < k$, it will return $s(l, r)$.\n- If $r - l + 1 \\ge k$, it will return $1 - s(l, r)$.\n\nFind $k$ using at most $33$ queries.\n\nThe device is \\textbf{not} adaptive. It means that the hidden $a$ and $k$ are fixed before the interaction and will not change during the interaction.",
    "tutorial": "Make 2 queries Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Make 1 query: query Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Without loss of generality, assume that the 1 is in Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] If Unable to parse markup [type=CF_MATHJAX] , query Unable to parse markup [type=CF_MATHJAX] . The result is Unable to parse markup [type=CF_MATHJAX] if Unable to parse markup [type=CF_MATHJAX] and Unable to parse markup [type=CF_MATHJAX] otherwise. Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] If Unable to parse markup [type=CF_MATHJAX] , query Unable to parse markup [type=CF_MATHJAX] . The result is Unable to parse markup [type=CF_MATHJAX] if $k' \\ge k$ and Unable to parse markup [type=CF_MATHJAX] otherwise. Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] In both cases, the binary search takes Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] The limit of Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX]",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint qry(int l, int r, bool rev = 0, int n = 0) {\n    if (rev) {\n        int t = n - l;\n        l = n - r;\n        r = t;\n    }\n    cout << \"? \" << l + 1 << ' ' << r << endl;\n    cin >> r;\n    return r;\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    int a = qry(0, n / 4);\n    int b = qry(n / 4, n / 2);\n    bool kSmall = 1;\n    bool firstHalf = 1;\n    if (a == b) firstHalf = 0;\n    int bs = 0;\n    if (qry(0, n / 2, firstHalf, n) == 0) kSmall = 0;\n    if (kSmall) {\n        for (int k = n / 4; k; k /= 2)\n            if (qry(0, bs + k, firstHalf, n) == 0) bs += k;\n    } else {\n        bs = n / 2 - 1;\n        for (int k = n / 4; k; k /= 2)\n            if (qry(0, bs + k, 1-firstHalf, n) == 1) bs += k;\n    }\n    cout << \"! \" << bs + 1 << endl;\n}\n\nint main() {\n    int T = 1;\n    cin >> T;\n    while (T--) solve();\n    return 0;\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "implementation",
      "interactive"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2049",
    "index": "F",
    "title": "MEX OR Mania",
    "statement": "An integer sequence $b_1, b_2, \\ldots, b_n$ is good if $\\operatorname{mex}(b_1, b_2, \\ldots, b_n) - (b_1 | b_2 | \\ldots | b_n) = 1$. Here, $\\operatorname{mex(c)}$ denotes the MEX$^{\\text{∗}}$ of the collection $c$, and $|$ is the bitwise OR operator.\n\nShohag has an integer sequence $a_1, a_2, \\ldots, a_n$. He will perform the following $q$ updates on $a$:\n\n- $i$ $x$ — increase $a_i$ by $x$.\n\nAfter each update, help him find the length of the longest good subarray$^{\\text{†}}$ of $a$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The minimum excluded (MEX) of a collection of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $y$ which does not occur in the collection $c$.\n\n$^{\\text{†}}$An array $d$ is a subarray of an array $f$ if $d$ can be obtained from $f$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "Let's figure out when a sequence is good. Let $m$ be the maximum element of the sequence. Notice that the bitwise OR of the sequence is at least Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Now we need to check for which Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] So, a sequence is good if the maximum element is Unable to parse markup [type=CF_MATHJAX] Now, let's see how to answer the queries without any updates. To find the longest good subarray, we can use a two-pointers approach. But a better way to do this is to fix the power $k (0 \\leq k \\leq \\log_2 n)$ and find the longest good subarray with maximum element $2^k - 1$. To do this, ignore the elements greater than Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] So to sum it up, for each power Unable to parse markup [type=CF_MATHJAX] Now regarding the updates, it is hard to track everything if we do the updates normally. But its's easier if we look at them in reverse order! Then each update will be decreasing the value of $a_i$ by Unable to parse markup [type=CF_MATHJAX] Unable to parse markup [type=CF_MATHJAX] Please check my code for more details. Overall complexity is $O((n + q) \\log^2 n)$ or Unable to parse markup [type=CF_MATHJAX]",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nconst int N = 1e5 + 9, Q = 3e5 + 9;\nusing ll = long long;\n \nstruct GoodSet { // insert, erase and track distinct and total elements\n  map<int, int> mp;\n  int size;\n  int k;\n  GoodSet() {}\n  GoodSet(int _k): k(_k), size(0) { };\n  void insert(int x, int c = 1) {\n    mp[x] += c;\n    size += c;\n  }\n  void erase(int x) {\n    if (mp[x] == 1) {\n      mp.erase(x);\n    }\n    else {\n      mp[x]--;\n    }\n    size -= 1;\n  }\n  void merge(GoodSet oth) {\n    for (auto [x, c]: oth.mp) {\n      insert(x, c);\n    }\n  }\n  bool is_good() { // check if all elements from 0 to 2^k - 1 exists in the set\n    return (int) mp.size() == (1 << k);\n  }\n  int get_value() {\n    if (is_good()) return size;\n    return 0;\n  }\n};\n \nstruct MaxSet { // insert, erase and track max element\n  map<int, int> mp;\n  MaxSet() {}\n  void insert(int x) {\n    mp[x]++;\n  }\n  void erase(int x) {\n    mp[x]--;\n    if (mp[x] == 0) mp.erase(x);\n  }\n  int get_max() {\n    return mp.rbegin() -> first;\n  }\n};\n \nstruct DSU { // DSU for each power of 2\n  int n;\n  int k;\n  vector<int> par;\n  vector<GoodSet> comp;\n  MaxSet good_lengths;\n  DSU() {}\n  DSU(int _n, int _k): n(_n), k(_k) {\n    par.resize(n + 1);\n    comp.resize(n + 1);\n    for (int i = 1; i <= n; i++) {\n      par[i] = i;\n      comp[i] = GoodSet(k);\n      good_lengths.insert(comp[i].get_value());\n    }\n  }\n  int find(int u) {\n    return par[u] = (par[u] == u ? u : find(par[u]));\n  }\n  void merge(int u, int v) {\n    u = find(u); v = find(v);\n    if (u == v) return;\n    good_lengths.erase(comp[u].get_value());\n    good_lengths.erase(comp[v].get_value());\n \n    // small to large merging\n    if (comp[u].mp.size() < comp[v].mp.size()) {\n      comp[u].mp.swap(comp[v].mp);\n      swap(comp[u].size, comp[v].size);\n    }\n    comp[u].merge(comp[v]);\n    comp[v].mp.clear(); // clear to save up memory\n \n    good_lengths.insert(comp[u].get_value());\n    par[v] = u;\n  }\n  // insert or erase an element from the component that u belongs to\n  void update_in_component(int u, int x, bool insert = true) {\n    u = find(u);\n    good_lengths.erase(comp[u].get_value());\n    if (insert) comp[u].insert(x);\n    else comp[u].erase(x);\n    good_lengths.insert(comp[u].get_value());\n  }\n};\nDSU f[18];\nll a[N]; // make it long long as total sum can be huge\nint id[Q], x[Q], ans[Q];\nvoid solve() {\n  int n, q; cin >> n >> q;\n  for (int i = 1; i <= n; i++) {\n    cin >> a[i];\n  }\n  for (int i = 1; i <= q; i++) {\n    cin >> id[i] >> x[i];\n    a[id[i]] += x[i];\n  }\n  MaxSet se;\n  for (int k = 0; (1 << k) <= n; k++) {\n    f[k] = DSU(n, k);\n    for (int i = 1; i <= n; i++) {\n      if (a[i] < (1 << k)) {\n        f[k].update_in_component(i, a[i], true);\n      }\n    }\n    for (int i = 2; i <= n; i++) {\n      if (a[i] < (1 << k) and a[i - 1] < (1 << k)) {\n        f[k].merge(i - 1, i);\n      }\n    }\n    se.insert(f[k].good_lengths.get_max());\n  }\n  for (int qid = q; qid >= 1; qid--) {\n    ans[qid] = se.get_max();\n    int i = id[qid], sub = x[qid];\n    for (int k = 0; (1 << k) <= n; k++) {\n      se.erase(f[k].good_lengths.get_max());\n \n      if (a[i] < (1 << k)) f[k].update_in_component(i, a[i], false);\n      if (a[i] - sub < (1 << k)) f[k].update_in_component(i, a[i] - sub, true);\n \n      if (a[i] >= (1 << k) and a[i] - sub < (1 << k)) {\n        if (i > 1 and a[i - 1] < (1 << k)) {\n          f[k].merge(i - 1, i);\n        }\n        if (i + 1 <= n and a[i + 1] < (1 << k)) {\n          f[k].merge(i, i + 1);\n        }\n      }\n \n      se.insert(f[k].good_lengths.get_max());\n    }\n    a[i] -= sub;\n  }\n \n  for (int i = 1; i <= q; i++) {\n    cout << ans[i] << '\\n';\n  }\n}\n \nint32_t main() {\n  ios_base::sync_with_stdio(0);\n  cin.tie(0);\n  int t = 1;\n  cin >> t;\n  while (t--) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "data structures",
      "dsu",
      "implementation"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2050",
    "index": "A",
    "title": "Line Breaks",
    "statement": "Kostya has a text $s$ consisting of $n$ words made up of Latin alphabet letters. He also has two strips on which he must write the text. The first strip can hold $m$ characters, while the second can hold as many as needed.\n\nKostya must choose a number $x$ and write the first $x$ words from $s$ on the first strip, while all the remaining words are written on the second strip. To save space, the words are written without gaps, but each word must be entirely on one strip.\n\nSince space on the second strip is very valuable, Kostya asks you to choose the maximum possible number $x$ such that all words $s_1, s_2, \\dots, s_x$ fit on the first strip of length $m$.",
    "tutorial": "An important condition in the problem: we can take $x$ words on the first line from the beginning and we cannot skip any word. The main idea is to compute the total length of words as we keep adding them, and stop when we reach a word where adding the next word would exceed the capacity of the first strip (which equals $m$). It is important to take into account the case when all words can be placed on the first line or none will fit, but our solution takes this into account.",
    "code": "def solve():\n    n, m = [int(i) for i in input().split()]\n\n    ans = 0\n    for i in range(n):\n        l = input()\n        if len(l) <= m:\n            m -= len(l)\n            ans += 1\n        else:\n            for i in range(i + 1, n):\n                input()\n            break\n\n    print(ans)\n\n\nt = int(input())\nfor i in range(t):\n    solve()",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2050",
    "index": "B",
    "title": "Transfusion",
    "statement": "You are given an array $a$ of length $n$. In one operation, you can pick an index $i$ from $2$ to $n-1$ inclusive, and do one of the following actions:\n\n- Decrease $a_{i-1}$ by $1$, then increase $a_{i+1}$ by $1$.\n- Decrease $a_{i+1}$ by $1$, then increase $a_{i-1}$ by $1$.\n\nAfter each operation, all the values must be non-negative. Can you make all the elements equal after any number of operations?",
    "tutorial": "The main idea of this problem is that these operations only change elements on the positions with the same parity. So, we can solve for elements on odd and even positions independently. Let's make two arrays $od$ and $ev$ - the first one will consist of all the elements on the odd positions, and the second one will consist of all the elements on the even positions. Now we can rewrite given operations as: pick any array $od$ or $ev$, after that pick any two adjacent elements and subtract $1$ from one of these elements and add $1$ to another. In order to make all the elements in array $od$ equal, the sum of all elements in $od$ must be divisible by $|od|$, and also the sum of all the elements in $ev$ must be divisible by $|ev|$, where $|a|$ is the length of array $a$. And also to make all the elements of the initial array equal, $\\frac{sum(od)}{|od|} = \\frac{sum(ev)}{|ev|}$ must be satisfied. If all these conditions are satisfied, the answer is \"YES\", otherwise \"NO\".",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n; cin >> n;\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n    \n    long long ods = 0, evs = 0;\n    for (int i = 0; i < n; i++) {\n        if (i & 1) ods += a[i];\n        else evs += a[i];\n    }\n    int odc = n / 2, evc = n / 2;\n    if (n & 1) evc++;\n\n    if (ods % odc != 0 || evs % evc != 0 || ods / odc != evs / evc) {\n        cout << \"NO\";\n        return;\n    }\n    cout << \"YES\";\n}\n\nint main() {\n    int TESTS; cin >> TESTS;\n    while (TESTS --> 0) {\n        solve();\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2050",
    "index": "C",
    "title": "Uninteresting Number",
    "statement": "You are given a number $n$ with a length of no more than $10^5$.\n\nYou can perform the following operation any number of times: choose one of its digits, square it, and replace the original digit with the result. The result must be a digit (that is, if you choose the digit $x$, then the value of $x^2$ must be less than $10$).\n\nIs it possible to obtain a number that is divisible by $9$ through these operations?",
    "tutorial": "The requirement that a digit must remain a digit imposes the following restrictions on transformations: we can transform $0$ into $0$, $1$ into $1$, $2$ into $4$, and $3$ into $9$. Any other digit squared will exceed 9, therefore, it cannot be transformed. Transformations involving $0$ and $1$ are useless, leaving us with two possible actions: squaring the digit $2$ or the digit $3$. We will use the divisibility rule for $9$. It states that a number is divisible by $9$ if and only if the sum of its digits is divisible by $9$. Let's see how the sum of the digits will change with the possible transformations. If we square $2$, the sum of the digits increases by $2^2 - 2 = 2$, and if we square $3$, the sum of the digits increases by $3^2 - 3 = 6$. We will count the number of digits $2$ in the number and the number of digits $3$ in the number. We can choose how many of the available digits $2$ and $3$ we will transform. Transforming more than 8 twos and more than 8 threes is pointless because remainders modulo $9$ their transformation adds to the sum will repeat. Thus, the final solution looks like this: we calculate the sum of the digits in the number, count the number of digits $2$ and $3$. We will iterate over how many digits $2$ we change (possibly 0, but no more than 8), and how many digits $3$ we change (possibly 0, but also no more than 8). Let's say we changed $x$ digits $2$ and $y$ digits $3$, then the sum of the digits in the number increased by $x * 2 + y * 6$. If new sum is divisible by $9$, the answer is \"YES\". If such a situation was never reached during the iteration, then the answer is \"NO\".",
    "code": "def solve():\n    s = [int(x) for x in list(input())]\n\n    sm = sum(s)\n    twos = s.count(2)\n    threes = s.count(3)\n\n    for i in range(min(10, twos + 1)):\n        for j in range(min(10, threes + 1)):\n            if (sm + i * 2 + j * 6) % 9 == 0:\n                print('YES')\n                return\n    print('NO')\n\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "brute force",
      "dp",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2050",
    "index": "D",
    "title": "Digital string maximization",
    "statement": "You are given a string $s$, consisting of digits from $0$ to $9$. In one operation, you can pick any digit in this string, except for $0$ or the leftmost digit, decrease it by $1$, and then swap it with the digit left to the picked.\n\nFor example, in one operation from the string $1023$, you can get $1103$ or $1022$.\n\nFind the lexicographically maximum string you can obtain after any number of operations.",
    "tutorial": "Let's look at digit $s_i$. We can see that we can't move it to the left more than $s_i$ times because it will be $0$ after. So, we can say that only digits on indices from $i$ to $i+9$ can stand on index $i$, because the maximum digit $9$ can be moved to the left no more than $9$ times. Thus, for each $i$ we can brute force all digits from $s_i$ to $s_{i+9}$ and pick such $j$ that $s_j - (j - i)$ is maximum; if we have multiple maximum options, we will minimize $j$. After that, we will move $s_j$ to the left until it is on index $i$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    string s; cin >> s;\n    for (int i = 0; i < s.size(); i++) {\n        int best = s[i] - '0', pos = i;\n        for (int j = i; j < min(i + 10, (int) s.size()); j++) {\n            if (s[j] - '0' - (j - i) > best) {\n                best = s[j] - '0' - (j - i);\n                pos = j;\n            }\n        }\n        while (pos > i) {\n            swap(s[pos], s[pos - 1]);\n            pos--;\n        }\n        s[i] = char(best + '0');\n    }\n    cout << s;\n}\n\nint main() {\n    int TESTS = 1; cin >> TESTS;\n    while (TESTS --> 0) {\n        solve();\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2050",
    "index": "E",
    "title": "Three Strings",
    "statement": "You are given three strings: $a$, $b$, and $c$, consisting of lowercase Latin letters. The string $c$ was obtained in the following way:\n\n- At each step, either string $a$ or string $b$ was randomly chosen, and the first character of the chosen string was removed from it and appended to the end of string $c$, until one of the strings ran out. After that, the remaining characters of the non-empty string were added to the end of $c$.\n- Then, a certain number of characters in string $c$ were randomly changed.\n\nFor example, from the strings $a=\\textcolor{red}{\\text{abra}}$ and $b=\\textcolor{blue}{\\text{cada}}$, without character replacements, the strings $\\textcolor{blue}{\\text{ca}}\\textcolor{red}{\\text{ab}}\\textcolor{blue}{\\text{d}}\\textcolor{red}{\\text{ra}}\\textcolor{blue}{\\text{a}}$, $\\textcolor{red}{\\text{abra}}\\textcolor{blue}{\\text{cada}}$, $\\textcolor{red}{\\text{a}}\\textcolor{blue}{\\text{cada}}\\textcolor{red}{\\text{bra}}$ could be obtained.\n\nFind the minimum number of characters that could have been changed in string $c$.",
    "tutorial": "Let's use the idea of dynamic programming. Let $dp[i][j]$ be the answer to the problem when considering string $a$ as its own prefix of length $i$, string $b$ as its own prefix of length $j$, and string $c$ as its own prefix of length $i+j$. Then the dynamic programming recurrence is easy: we need to iterate over where we took the next (($i+j$)-th) character of string $c$. If the character is taken from string $a$, the answer is: $dp[i - 1][j]$, if $a_i = c_{i+j}$, $dp[i - 1][j] + 1$ otherwise (since we need to replace character $a_i$ with $c_{i+j}$). If it is taken from string $b$, the answer is calculated similarly: $dp[i][j - 1]$, if $b_j = c_{i+j}$, $dp[i][j - 1] + 1$ otherwise. Thus, to obtain the minimum value of the current dynamic programming state, we need to take the minimum of the two obtained values. To get the answer, we need to take the value of the dynamic programming table at $dp[n][m]$, where $n$ is the length of string $a$ and $m$ is the length of string $b$. The final time complexity of the solution is $\\mathcal{O}(n \\cdot m)$ per test case.",
    "code": "#include <iostream>\n#include <algorithm>\n\nstatic const int inf = 1e9;\n\nvoid solve() {\n    std::string a, b, res;\n    std::cin >> a >> b >> res;\n    int n = (int) a.size(), m = (int) b.size();\n    int dp[n + 1][m + 1];\n    std::fill(&dp[0][0], &dp[0][0] + (n + 1) * (m + 1), inf);\n    dp[0][0] = 0;\n    for (int i = 0; i < n; i++) {\n        dp[i + 1][0] = dp[i][0] + (a[i] != res[i]);\n    }\n    for (int j = 0; j < m; j++) {\n        dp[0][j + 1] = dp[0][j] + (b[j] != res[j]);\n    }\n    for (int i = 1; i <= n; i++) {\n        for (int j = 1; j <= m; j++) {\n            dp[i][j] = std::min(dp[i - 1][j] + (a[i - 1] != res[i + j - 1]),\n                                dp[i][j - 1] + (b[j - 1] != res[i + j - 1]));\n        }\n    }\n    std::cout << dp[n][m] << std::endl;\n}\n\nint main() {\n    int tests;\n    std::cin >> tests;\n    while (tests--) {\n        solve();\n    }\n}",
    "tags": [
      "dp",
      "implementation",
      "strings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2050",
    "index": "F",
    "title": "Maximum modulo equality",
    "statement": "You are given an array $a$ of length $n$ and $q$ queries $l$, $r$.\n\nFor each query, find the maximum possible $m$, such that all elements $a_l$, $a_{l+1}$, ..., $a_r$ are equal modulo $m$. In other words, $a_l \\bmod m = a_{l+1} \\bmod m = \\dots = a_r \\bmod m$, where $a \\bmod b$ — is the remainder of division $a$ by $b$. In particular, when $m$ can be infinite, print $0$.",
    "tutorial": "Let's look at two arbitrary integers $x$ and $y$. Now we want to find the maximum $m$, which satisfies $x\\bmod m = y\\bmod m$. We know that $x\\bmod m = y\\bmod m$, then $|x - y|\\bmod m = 0$, because they have the same remainder by $m$. That means that any $m$ which is a divisor of $|x - y|$ will satisfy the required condition. Now let's generalize the idea we've obtained to the segment: $a_l\\bmod m = a_{l+1}\\bmod m = \\dots = a_r\\bmod m$ means that $a_l\\bmod m = a_{l+1}\\bmod m$, and $a_{l+1}\\bmod m = a_{l+2}\\bmod m$, and ..., and $a_{r-1}\\bmod m = a_r\\bmod m$. So, $m$ must be a divisor of $|a_l - a_{l+1}|$, $|a_{l+1} - a_{l+2}|$, ..., $|a_{r-1} - a_r|$ at the same time. That means that $m$ should be GCD($|a_l - a_{l+1}|$, $|a_{l+1} - a_{l+2}|$, ..., $|a_{r-1} - a_r|$), where GCD is the greatest common divisor. $m = 0$, when all the elements on the segment [$l; r$] are equal. Let's build an array consisting of differences of adjacent elements; now we can use sparse table to find GCD on the segments efficiently.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int LOGN = 20;\n\nvector<vector<int>> stGCD;\n\nint get_gcd(int l, int r) {\n    int k = __lg(r - l + 1);\n    return __gcd(stGCD[k][l], stGCD[k][r - (1 << k) + 1]);\n}\n\nvoid solve() {\n    stGCD.clear();\n    int n, q; cin >> n >> q;\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n\n    vector<int> b;\n    for (int i = 1; i < n; i++)\n        b.push_back(abs(a[i - 1] - a[i]));\n\n    stGCD.resize(LOGN, vector<int>(b.size(), 1));\n    for (int i = 0; i < b.size(); i++)\n        stGCD[0][i] = b[i];\n    for (int i = 1; i < LOGN; i++)\n        for (int j = 0; j + (1 << (i - 1)) < b.size(); j++)\n            stGCD[i][j] = __gcd(stGCD[i - 1][j], stGCD[i - 1][j + (1 << (i - 1))]);\n\n    while (q--) {\n        int l, r; cin >> l >> r;\n        if (l == r) {\n            cout << 0 << \" \";\n            continue;\n        }\n        l--; r -= 2;\n        int gcd = get_gcd(l, r);\n        cout << gcd << \" \";\n    }\n}\n\nint main() {\n    int TESTS = 1; cin >> TESTS;\n    while (TESTS --> 0) {\n        solve();\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2050",
    "index": "G",
    "title": "Tree Destruction",
    "statement": "Given a tree$^{\\text{∗}}$ with $n$ vertices. You can choose two vertices $a$ and $b$ once and remove all vertices on the path from $a$ to $b$, including the vertices themselves. If you choose $a=b$, only one vertex will be removed.\n\nYour task is to find the maximum number of connected components$^{\\text{†}}$ that can be formed after removing the path from the tree.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\n$^{\\text{†}}$A connected component is a set of vertices such that there is a path along the edges from any vertex to any other vertex in the set (and it is not possible to reach vertices not belonging to this set)\n\\end{footnotesize}",
    "tutorial": "Let's choose some vertices $a$ and $b$, between which there are $k$ edges. Then, when removing this path, the tree will split into $s - 2 \\cdot k$, where $s$ is the sum of the degrees of the vertices on the path (this is exactly how many edges are connected to the chosen path). Let's suspend the tree from vertex $1$, and for each vertex $v$ of the given tree, we will calculate two values: $\\text{dp[v].x}$ - the best answer if the path starts at vertex $v$ and ends in its subtree, and $\\text{dp[v].y}$ - the best answer if the path passes through vertex $v$ from one of its children to another. The recalculations of the dynamic programming will be similar to those used in finding the diameter of the tree using dynamic programming. The answer will be the largest value among all $\\text{dp[v].x}$ and $\\text{dp[v].y}$.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define x first\n#define y second\n\nusing namespace std;\n\nvoid dfs(int v, int p, vector<vector<int>> &sl, vector<pair<int, int>> &dp){\n    dp[v].x = sl[v].size();\n    int m1 = -1, m2 = -1;\n    for(int u: sl[v]){\n        if(u == p){\n            continue;\n        }\n        dfs(u, v, sl, dp);\n        dp[v].x = max(dp[v].x, dp[u].x + (int)sl[v].size() - 2);\n        m2 = max(m2, dp[u].x);\n        if(m1 < m2) swap(m1, m2);\n    }\n    dp[v].y = dp[v].x;\n    if(m2 != -1){\n        dp[v].y = m1 + m2 + sl[v].size() - 4;\n    }\n}\n\nvoid solve(int tc){\n    int n;\n    cin >> n;\n    vector<vector<int>> sl(n);\n    for(int i = 1; i < n; ++i){\n        int u, v;\n        cin >> u >> v;\n        sl[--u].emplace_back(--v);\n        sl[v].emplace_back(u);\n    }\n    vector<pair<int, int>> dp(n);\n    dfs(0, 0, sl, dp);\n    int ans = 0;\n    for(int i = 0; i < n; ++i){\n        ans = max(ans, max(dp[i].x, dp[i].y));\n    }\n    cout << ans;\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2051",
    "index": "A",
    "title": "Preparing for the Olympiad",
    "statement": "Monocarp and Stereocarp are preparing for the Olympiad. There are $n$ days left until the Olympiad. On the $i$-th day, if Monocarp plans to practice, he will solve $a_i$ problems. Similarly, if Stereocarp plans to practice on the same day, he will solve $b_i$ problems.\n\nMonocarp can train on any day he wants. However, Stereocarp watches Monocarp and follows a different schedule: if Monocarp trained on day $i$ and $i < n$, then Stereocarp will train on day $(i+1)$.\n\nMonocarp wants to organize his training process in a way that the difference between the number of problems he solves and the number of problems Stereocarp solves is as large as possible. Formally, Monocarp wants to maximize the value of $(m-s)$, where $m$ is the number of problems he solves, and $s$ is the number of problems Stereocarp solves. Help Monocarp determine the maximum possible difference in the number of solved problems between them.",
    "tutorial": "Let's consider what contribution each day that Monokarp trains makes to the difference. For each day, except the last one, if Monokarp trains on that day, then the number of problems he has solved will increase by $a_i$, and the number of problems solved by Stereokarp will increase by $b_{i+1}$. Therefore, if $a_i - b_{i+1} > 0$, it is beneficial for Monokarp to train on the $i$-th day; otherwise, it is not beneficial. On the last day, it is always beneficial to train, as Stereokarp will not solve anything on the day following it.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n);\n    for (auto &x : a) cin >> x;\n    for (auto &x : b) cin >> x;\n    int ans = a[n - 1];\n    for (int i = 0; i < n - 1; ++i)\n      ans += max(0, a[i] - b[i + 1]);\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "2051",
    "index": "B",
    "title": "Journey",
    "statement": "Monocarp decided to embark on a long hiking journey.\n\nHe decided that on the first day he would walk $a$ kilometers, on the second day he would walk $b$ kilometers, on the third day he would walk $c$ kilometers, on the fourth day, just like on the first, he would walk $a$ kilometers, on the fifth day, just like on the second, he would walk $b$ kilometers, on the sixth day, just like on the third, he would walk $c$ kilometers, and so on.\n\nMonocarp will complete his journey on the day when he has walked at least $n$ kilometers in total. Your task is to determine the day on which Monocarp will complete his journey.",
    "tutorial": "Processing every day separately is too slow. Instead, we will use the fact that every three days, the number of kilometers Monocarp walks repeats, and process days in \"triples\". During every three days, Monocarp walks exactly $(a+b+c)$ kilometers, so we can do the following: while $n \\ge a + b + c$, subtract $(a+b+c)$ from $n$ and increase the answer by $3$; and finally, process the remaining days, since there will be at most $3$ of them. However, this works in $O(n)$ per test case, so it is still too slow. We need to improve the part when we subtract $a+b+c$ from $n$ until $n$ becomes less than this sum. Does this sound familiar? The number of times we need to subtract $(a+b+c)$ from $n$ is exactly $\\lfloor \\frac{n}{a+b+c} \\rfloor$, and the number we get after that is $n \\bmod (a+b+c)$ by definition of integer division and remainder. This allows us to process all \"triples\" in $O(1)$, instead of running a loop in $O(n)$. The solution we get works in $O(1)$ per test case.",
    "code": "t = int(input())\nfor i in range(t):\n    n, a, b, c = map(int, input().split())\n    sum = a + b + c\n    d = n // sum * 3\n    if n % sum == 0:\n        print(d)\n    elif n % sum <= a:\n        print(d + 1)\n    elif n % sum <= a + b:\n        print(d + 2)\n    else:\n        print(d + 3)\n",
    "tags": [
      "binary search",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2051",
    "index": "C",
    "title": "Preparing for the Exam",
    "statement": "Monocarp is preparing for his first exam at the university. There are $n$ different questions which can be asked during the exam, numbered from $1$ to $n$. There are $m$ different lists of questions; each list consists of exactly $n-1$ different questions. Each list $i$ is characterized by one integer $a_i$, which is the index of the only question which is \\textbf{not present} in the $i$-th list. For example, if $n = 4$ and $a_i = 3$, the $i$-th list contains questions $[1, 2, 4]$.\n\nDuring the exam, Monocarp will receive one of these $m$ lists of questions. Then, the professor will make Monocarp answer all questions from the list. So, Monocarp will pass only if he knows all questions from the list.\n\nMonocarp knows the answers for $k$ questions $q_1, q_2, \\dots, q_k$. For each list, determine if Monocarp will pass the exam if he receives that list.",
    "tutorial": "For every question list, we should check if Monocarp knows all questions from the list, i. e. all numbers $1, 2, \\dots, a_{i-1}, a_{i+1}, \\dots, n$ appear in the list $[q_1, q_2, \\dots, q_k]$. Searching for every number in the list $q$ naively is too slow; instead, we can make a boolean array such that the $j$-th element in it is true if and only if Monocarp knows the $j$-th question. That way, we can check if an integer appears in the list $q$ in $O(1)$. However, that is not enough, since every list of questions contains $O(n)$ questions, and there are $O(n)$ lists. We need to use the fact that every list contains exactly $n-1$ questions somehow. If Monocarp knows all $n$ questions, he can answer any question list (since he knows everything). If Monocarp knows $n-2$ questions or less, he cannot pass at all, since every question list contains more questions than he knows. The only case that's left if when $k=n-1$, i. e. Monocarp knows all questions except for one. Let's analyze it in more detail (the two next paragraphs will assume that $k=n-1$). Since every question list has the same size as the set of questions known by Monocarp, then in order for Monocarp to pass the exam, these two sets of questions must be equal. However, checking that they are equal by iterating on their contents is too slow; instead, we will check that two sets of questions are different by using the elements which are absent from them. Let's check if Monocarp knows the question $a_i$. If he does, then the $i$-th list of questions is different from the set of questions he knows, so he can't pass. But if Monocarp doesn't know the $a_i$-th question, then he knows every question which is not $a_i$, so he can pass. So, Monocarp knows the $i$-th question list if and only if he does not know the $a_i$-th question, and this can be checked in $O(1)$. This way, we get a solution working in $O(n)$ on each test case.",
    "code": "for _ in range(int(input())):\n    n, m, k = map(int, input().split())\n    a = list(map(int, input().split()))\n    q = list(map(int, input().split()))\n    used = [False for i in range(n + 1)]\n    for i in q:\n        used[i] = True\n    l = len(q)\n    for i in range(m):\n        if l == n or (l == n-1 and not used[a[i]]):\n            print(1, end='')\n        else:\n            print(0, end='')\n    print()",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2051",
    "index": "D",
    "title": "Counting Pairs",
    "statement": "You are given a sequence $a$, consisting of $n$ integers, where the $i$-th element of the sequence is equal to $a_i$. You are also given two integers $x$ and $y$ ($x \\le y$).\n\nA pair of integers $(i, j)$ is considered interesting if the following conditions are met:\n\n- $1 \\le i < j \\le n$;\n- if you simultaneously remove the elements at positions $i$ and $j$ from the sequence $a$, the sum of the remaining elements is at least $x$ and at most $y$.\n\nYour task is to determine the number of interesting pairs of integers for the given sequence $a$.",
    "tutorial": "There is a common trick in problems of the form \"count something on segment $[l, r]$\": calculate the answer for $[0, r]$, and then subtract the answer for $[0, l-1]$. We can use this trick in our problem as follows: calculate the number of pairs $i,j$ such that the sum of all other elements is less than $y+1$, and subtract the number of pairs such that the sum is less than $x$. Now we need to solve the following problem: given an array and an integer $x$, calculate the number of ways to choose $i,j$ ($1 \\le i < j \\le n$) so that the sum of all elements, except for $a_i$ and $a_j$, is less than $x$. Naive solution (iterate on the pair, calculate the sum of remaining elements) works in $O(n^3)$. It can be improved to $O(n^2)$ if, instead of calculating the sum of remaining elements in $O(n)$, we do it in $O(1)$: if we remove $a_i$ and $a_j$, the remaining elements sum up to $s - a_i - a_j$, where $s$ is the sum of all elements. However, $O(n^2)$ is still too slow. For every $i$, let's try to calculate the number of elements $j$ which \"match\" it faster. If we sort the array, the answer won't change; but in a sorted array, for every $i$, all possible values of $j$ form a suffix of the array (if $s - a_i - a_j < x$ and $a_{j+1} \\ge a_j$, then $s - a_i - a_{j+1} < x$). So, for every $i$, let's find the minimum $j'$ such that $s - a_i - a_{j'} < x$; all $j \\ge j'$ are possible \"matches\" for $i$. This can be done with two pointers method: when we decrease $i$, the index $j'$ won't decrease. Unfortunately, this method has an issue. We need to calculate only pairs where $i<j$, but this method doesn't maintain this constraint. However, this issue can be easily resolved. First, let's get rid of pairs where $i=j$. To do so, simply calculate the number of indices $i$ such that $s - 2a_i < x$. Then, let's get rid of pairs where $i>j$. For every such pair, there is a pair with $i<j$ where these two indices are swapped (and vice versa), so we just need to divide the number of pairs by $2$. Now we have a solution working in $O(n \\log n)$ for each test case. Instead of two pointers, you can use binary search, the complexity will be the same.",
    "code": "def calcLessThanX(a, x):\n    n = len(a)\n    s = sum(a)\n    j = 0\n    ans = 0\n\n    for i in range(n-1, -1, -1):\n        while j < n and s - a[i] - a[j] >= x:\n            j += 1\n        ans += (n - j)\n\n    for i in range(n):\n        if s - a[i] - a[i] < x:\n            ans -= 1\n    \n    return ans // 2\n\nfor _ in range(int(input())):\n    n, x, y = map(int, input().split())\n    a = list(map(int, input().split()))\n    \n    a = sorted(a)\n    print(calcLessThanX(a, y+1) - calcLessThanX(a, x))",
    "tags": [
      "binary search",
      "sortings",
      "two pointers"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2051",
    "index": "E",
    "title": "Best Price",
    "statement": "A batch of Christmas trees has arrived at the largest store in Berland. $n$ customers have already come to the store, wanting to buy them.\n\nBefore the sales begin, the store needs to determine the price for one tree (the price is the same for all customers). To do this, the store has some information about each customer.\n\nFor the $i$-th customer, two integers $a_i$ and $b_i$ are known, which define their behavior:\n\n- if the price of the product is at most $a_i$, the customer will buy a tree and leave a positive review;\n- otherwise, if the price of the product is at most $b_i$, the customer will buy a tree but leave a negative review;\n- otherwise, the customer will not buy a tree at all.\n\nYour task is to calculate the maximum possible earnings for the store, given that it can receive no more than $k$ negative reviews.",
    "tutorial": "First, let's design a solution in $O(n^2)$. We can solve the problem in $O(n \\cdot max b_i)$, if we iterate on the price $p$ we use, and for every price, calculate the number of trees bought and the number of negative reviews. However, we don't need to check every possible price from $1$ to $max b_i$: let's instead check every integer in the union of $a$ and $b$ (or check every $a_i$, and then check every $b_i$). Why is it always optimal? Suppose some integer price $p$ which is not present in the union of $a$ and $b$ is optimal. Then, if we use $p+1$ instead of $p$, the status of each customer will be the same, but we will get more money for each tree we sell. So, it is enough to check the elements of $a$ and the elements of $b$ as possible prices. This works in $O(n^2)$, we need to speed it up. I will explain two different methods that allow to check every price faster. Event processing (or sweep line): Shortly, we process all possible prices in ascending order, and when we go from one price to the next, we update the customers which no longer want to buy a tree with a new price, and the customers which will leave a negative review if the price is increased. One of the ways to implement it is as follows. For every customer, create two \"events\" of the type \"when price exceeds $a_i$, the customer will leave a negative review\" and \"when price exceeds $b_i$, the customer will no longer buy a tree and leave a negative review\". These events can be implemented as pairs of integers $(a_i, 1)$ and $(b_i, 2)$. Then, we can sort the events and process them from left to right in sorted order, maintaining the number of trees and negative reviews. When we process the event with price $p$, the change it makes will come into effect only when the price exceeds $p$, so we should first update the answer, then apply the change from the event. Furthermore, all events with the same price value should be processed at the same time (so if there are multiple events with the same price value, you don't update the answer after processing only several of them). All of this is a bit complicated to implement, that's why I would like to show you an Alternative approach: For every price $p$, we need to calculate two values: the number of trees bought, i. e. the number of customers $i$ such that $b_i \\ge p$; the number of negative reviews, i. e. the number of customers $i$ such that $a_i < p \\le b_i$. The first one can be calculated in $O(\\log n)$ with binary search, if we sort the array $b$. The second one is a bit trickier. Let's calculate it as follows: take the number of trees bought, and then subtract the number of trees bought without a negative review (which is the number of customers $i$ such that $a_i \\ge p$). If we sort both arrays $a$ and $b$, this value can also be processed in $O(\\log n)$ with binary search. So, we spend $O(\\log n)$ time to check one possible price, and the number of different prices we have to check is up to $2n$, so this solution works in $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n), b(n);\n    for (auto &x : a) cin >> x;\n    for (auto &x : b) cin >> x;\n    vector<pair<int, int>> ev;\n    for (int i = 0; i < n; ++i) {\n      ev.emplace_back(a[i], 1);\n      ev.emplace_back(b[i], 2);\n    }\n    sort(ev.begin(), ev.end());\n    long long ans = 0;\n    int cnt = n, bad = 0;\n    for (int i = 0; i < 2 * n;) {\n      auto [x, y] = ev[i];\n      if (bad <= k) ans = max(ans, x * 1LL * cnt);\n      while (i < 2 * n && ev[i].first == x) {\n        bad += (ev[i].second == 1);\n        bad -= (ev[i].second == 2);\n        cnt -= (ev[i].second == 2);\n        ++i;\n      }\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2051",
    "index": "F",
    "title": "Joker",
    "statement": "Consider a deck of $n$ cards. The positions in the deck are numbered from $1$ to $n$ from top to bottom. A joker is located at position $m$.\n\n$q$ operations are applied sequentially to the deck. During the $i$-th operation, you need to take the card at position $a_i$ and move it either to the beginning or to the end of the deck. For example, if the deck is $[2, 1, 3, 5, 4]$, and $a_i=2$, then after the operation the deck will be either $[1, 2, 3, 5, 4]$ (the card from the second position moved to the beginning) or $[2, 3, 5, 4, 1]$ (the card from the second position moved to the end).\n\nYour task is to calculate the number of distinct positions where the joker can be after each operation.",
    "tutorial": "Let's represent the positions where the joker can be as a set of non-overlapping segments $[l_1, r_1]$, $[l_2, r_2]$, .... Let's consider what happens to the segment $[l, r]$ after applying the $i$-th operation: if $a_i < l$, the possible positions segment becomes $[l - 1, r]$ (since moving the $a_i$-th card to the front does not change the joker's positions, while moving it to the back shifts the positions up by $1$); if $a_i > r$, the possible positions segment becomes $[l, r + 1]$ (since moving the $a_i$-th card to the front shifts the positions down by $1$, while moving it to the back does not change the joker's positions); if $l \\le a_i \\le r$, let's consider $3$ subsegments where the joker can be located: positions from the subsegment $[l, a_i - 1]$ moves to $[l, a_i]$ (similarly to the case $a_i > r$); positions from the subsegment $[a_i + 1, r]$ moves to $[a_i, r]$ (similarly to the case $a_i < l$); the joker from position $a_i$ moves to one of two positions: $1$ or $n$. Thus, in this case, the segment $[l, r]$ remains, but we need to add two new segments ($[1, 1]$ and $[n, n]$) to the set. positions from the subsegment $[l, a_i - 1]$ moves to $[l, a_i]$ (similarly to the case $a_i > r$); positions from the subsegment $[a_i + 1, r]$ moves to $[a_i, r]$ (similarly to the case $a_i < l$); the joker from position $a_i$ moves to one of two positions: $1$ or $n$. Note that when $l=r=a_i$, the current segment disappears. At first glance, it seems that this solution works in $O(nq)$, since the number of segments can be $O(n)$, and we need to update each of them. However, it is not difficult to notice that there cannot be more than $3$ segments. Specifically: the initial segment $[m, m]$, which expands to the left and right, the segment $[1,1]$, which expands only to the right, and the segment $[n, n]$, which expands only to the left.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, m, q;\n    cin >> n >> m >> q;\n    vector<pair<int, int>> segs({{1, -q}, {m, m}, {n + q + 1, n}});\n    while (q--) {\n      int x;\n      cin >> x;\n      bool ins = false;\n      for (auto& [l, r] : segs) {\n        if (x < l) l = max(1, l - 1);\n        else if (x > r) r = min(n, r + 1);\n        else {\n          ins = true;\n          if (l == r) l = n + q, r = -q;\n        }\n      }\n      if (ins) {\n        segs[0] = {1, max(segs[0].second, 1)};\n        segs[2] = {min(segs[2].first, n), n};\n      }\n      int lf = 0, rg = -1, ans = 0;\n      for (auto [l, r] : segs) {\n        if (l > r) continue;\n        if (l > rg) {\n          ans += max(0, rg - lf + 1);\n          lf = l; rg = r;\n        }\n        rg = max(rg, r);\n      }\n      ans += max(0, rg - lf + 1);\n      cout << ans << ' ';\n     }\n     cout << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2051",
    "index": "G",
    "title": "Snakes",
    "statement": "Suppose you play a game where the game field looks like a strip of $1 \\times 10^9$ square cells, numbered from $1$ to $10^9$.\n\nYou have $n$ snakes (numbered from $1$ to $n$) you need to place into some cells. Initially, each snake occupies exactly one cell, and you can't place more than one snake into one cell. After that, the game starts.\n\nThe game lasts for $q$ seconds. There are two types of events that may happen each second:\n\n- snake $s_i$ enlarges: if snake $s_i$ occupied cells $[l, r]$, it enlarges to a segment $[l, r + 1]$;\n- snake $s_i$ shrinks: if snake $s_i$ occupied cells $[l, r]$, it shrinks to a segment $[l + 1, r]$.\n\nEach second, exactly one of the events happens.\n\nIf at any moment of time, any snake runs into some obstacle (either another snake or the end of the strip), you lose. Otherwise, you win with the score equal to the maximum cell occupied by any snake so far.\n\nWhat is the minimum possible score you can achieve?",
    "tutorial": "Note that when you place snakes on the strip in some order, they form some permutation. And when you fix that permutation, you can place them greedily. In other words, when you know in what order you'll place snakes, it's always optimal to place them as close to each other as possible. Since the bigger the initial distance - the bigger the resulting distance of the farthest snake (or the bigger the final score). We can even calculate that final score precisely: it's equal to $1 + \\texttt{sum of distances} + \\texttt{number of times the last snake enlarges}$. So, we can solve the task in two steps. First, let's calculate $\\mathrm{minDist}[i][j]$ - the minimum possible distance between snakes $i$ and $j$ if we plan to place snake $j$ right after snake $i$. Suppose the initial gap between these snakes is $x$. Let's skim through all events: each time the $i$-th snake enlarges, our gap decreases, or $x' = x - 1$. each time the $j$-th snake shrinks, our gap increases, or $x' = x + 1$. if at any moment $x'$ becomes negative, then we lose. In other words, we needed bigger initial $x$. We can rephrase what happens more formally: for each event $i$ let $e_i = 1$ if $x$ increases, $e_i = -1$ if $x$ decreases or $0$ otherwise. Then after the $i$-th event the current gap will be equal to $x' = x + \\sum_{j=1}^{i}{e_j}$. The following inequality should hold for each $i$: $x + \\sum_{j=1}^{i}{e_j} \\ge 0$ or $x \\ge -\\sum_{j=1}^{i}{e_j}$. So, if we will find the minimum $\\min\\limits_{1 \\le i \\le q}{\\sum_{j=1}^{i}{e_j}}$ then we can set the initial distance to this minimum gap plus one, or $\\mathrm{minDist}[i][j] = -\\min\\limits_{1 \\le i \\le q}{\\sum_{j=1}^{i}{e_j}} + 1$. Now we know the minimum distances between neighboring snakes, so we can find the optimal order. Let's do it with bitmask dp $d[mask][lst]$, since all we need to know in each state is the set of already placed snakes $mask$ and the last snake $lst$. Transitions are straightforward: let's just choose the next snake to place and place it at distance $\\mathrm{minDist}$. The initial states are $d[2^i][i] = 1$ for each $i$. The answer is $\\min\\limits_{1 \\le i \\le n}{d[2^n - 1][i] + \\texttt{number of times snake $i$ enlarges}}$, i. e. we just choose the last snake. The time complexity is $O(n^2 q)$ for the first part (or $O(n q)$ if written more optimally) plus $O(2^n n^2)$ for the second part.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\nconst int INF = int(1e9);\n\nint n, q;\nvector<int> id, ch;\n\nbool read() {\n    if (!(cin >> n >> q))\n        return false;\n    id.resize(q);\n    ch.resize(q);\n    fore (i, 0, q) {\n        char c;\n        cin >> id[i] >> c;\n        id[i]--;\n        ch[i] = c == '+' ? 1 : -1;\n    }\n    return true;\n}\n\nint getDist(int s, int t) {\n    int pSum = 0, cMin = 0;\n    fore (e, 0, q) {\n        if (id[e] == t)\n            pSum += ch[e] < 0;\n        if (id[e] == s)\n            pSum -= ch[e] > 0;\n        cMin = min(cMin, pSum);\n    }\n    return -cMin + 1;\n}\n\ninline void solve() {\n    vector<vector<int>> minDist(n, vector<int>(n, INF));\n\n    fore (i, 0, n) fore (j, 0, n)\n        minDist[i][j] = getDist(i, j);\n\n    vector<int> len(n, 0);\n    fore (e, 0, q)\n        len[id[e]] += ch[e] > 0;\n    \n    vector< vector<int> > d(1 << n, vector<int>(n, INF));\n    fore (i, 0, n)\n        d[1 << i][i] = 1;\n    \n    fore (mask, 1, 1 << n) fore (lst, 0, n) {\n        if (d[mask][lst] == INF)\n            continue;\n        fore (nxt, 0, n) {\n            if ((mask >> nxt) & 1)\n                continue;\n            int nmask = mask | (1 << nxt);\n            d[nmask][nxt] = min(d[nmask][nxt], d[mask][lst] + minDist[lst][nxt]);\n        }\n    }\n    int ans = INF;\n    fore (lst, 0, n)\n        ans = min(ans, d[(1 << n) - 1][lst] + len[lst]);\n    cout << ans << endl;\n}\n\nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n\n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "dsu",
      "graphs"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2053",
    "index": "A",
    "title": "Tender Carpenter",
    "statement": "\\begin{quote}\nI would use a firework to announce, a wave to bid farewell, and a bow to say thanks: bygones are bygones; not only on the following path will I be walking leisurely and joyfully, but also the footsteps won't halt as time never leaves out flowing; for in the next year, we will meet again.\n\\hfill — Cocoly1990, Goodbye 2022\n\\end{quote}\n\nIn his dream, Cocoly would go on a long holiday with no worries around him. So he would try out for many new things, such as... being a carpenter. To learn it well, Cocoly decides to become an apprentice of Master, but in front of him lies a hard task waiting for him to solve.\n\nCocoly is given an array $a_1, a_2,\\ldots, a_n$. Master calls a set of integers $S$ stable if and only if, for any possible $u$, $v$, and $w$ from the set $S$ (note that $u$, $v$, and $w$ do not necessarily have to be pairwise distinct), sticks of length $u$, $v$, and $w$ can form a non-degenerate triangle$^{\\text{∗}}$.\n\nCocoly is asked to partition the array $a$ into several (possibly, $1$ or $n$) \\textbf{non-empty} continuous subsegments$^{\\text{†}}$, such that: for each of the subsegments, the set containing all the elements in it is stable.\n\nMaster wants Cocoly to partition $a$ in \\textbf{at least two} different$^{\\text{‡}}$ ways. You have to help him determine whether it is possible.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A triangle with side lengths $x$, $y$, and $z$ is called non-degenerate if and only if:\n\n- $x + y > z$,\n- $y + z > x$, and\n- $z + x > y$.\n\n$^{\\text{†}}$A sequence $b$ is a subsegment of a sequence $c$ if $b$ can be obtained from $c$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\n$^{\\text{‡}}$Two partitions are considered different if and only if at least one of the following holds:\n\n- the numbers of continuous subsegments split in two partitions are different;\n- there is an integer $k$ such that the lengths of the $k$-th subsegment in two partitions are different.\n\n\\end{footnotesize}",
    "tutorial": "Can you find a partition that is always valid? Suppose you are given a set $S$. How do you judge whether $S$ is stable in $\\mathcal O(\\lvert S\\rvert)$? Are sets that are very large really necessary? Note that: we always have a partition like $[a_1], [a_2], \\dots, [a_n]$, since $(x, x, x)$ always forms a non-degenerate (equilateral) triangle. We focus on the second partition scheme in which not all continuous subsegments have a length of $1$. One can also note that if a set $S$ is stable then for all $T \\subsetneq S$ ($T \\neq \\varnothing$), $T$ is also stable. Short proof: If $\\exists u, v, w \\in T$ such that $(u, v, w)$ doesn't form a non-degenerate triangle, therefore $u, v, w \\in S$ so it is concluded that $S$ is not stable. Contradiction! If such a partition exists, we can always split long continuous subsegments into shorter parts, while the partition remains valid. Therefore, it's enough to check the case in which there is one subsegment of length $2$ and the rest of length $1$. So, we should output NO if and only if for all $1 \\leq i < n$, $2\\min(a_i, a_{i+1}) \\leq \\max(a_i, a_{i+1})$.",
    "code": "#include <bits/stdc++.h>\n \n#define MAXN 1001\nint a[MAXN];\nvoid solve() {\n\tint n; std::cin >> n;\n\tfor (int i = 1; i <= n; ++i) std::cin >> a[i];\n\tfor (int i = 1; i < n; ++i) if (2 * std::min(a[i], a[i + 1]) > std::max(a[i], a[i + 1])) \n\t\t{ std::cout << \"YES\\n\"; return; }\n\tstd::cout << \"NO\\n\";\n}\n \nint main() {\n\tstd::ios::sync_with_stdio(false);\n\tstd::cin.tie(nullptr), std::cout.tie(nullptr);\n\tint t; std::cin >> t; while (t--) solve(); return 0;\n}",
    "tags": [
      "dp",
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2053",
    "index": "B",
    "title": "Outstanding Impressionist",
    "statement": "\\begin{quote}\nIf it was so, then let's make it a deal...\n\\hfill — MayDay, Gentleness\n\\end{quote}\n\nEven after copying the paintings from famous artists for ten years, unfortunately, Eric is still unable to become a skillful impressionist painter. He wants to forget something, but the white bear phenomenon just keeps hanging over him.\n\nEric still remembers $n$ pieces of impressions in the form of an integer array. He records them as $w_1, w_2, \\ldots, w_n$. However, he has a poor memory of the impressions. For each $1 \\leq i \\leq n$, he can only remember that $l_i \\leq w_i \\leq r_i$.\n\nEric believes that impression $i$ is unique if and only if there exists a possible array $w_1, w_2, \\ldots, w_n$ such that $w_i \\neq w_j$ holds for all $1 \\leq j \\leq n$ with $j \\neq i$.\n\nPlease help Eric determine whether impression $i$ is unique for every $1 \\leq i \\leq n$, \\textbf{independently} for each $i$. Perhaps your judgment can help rewrite the final story.",
    "tutorial": "What if for all $1 \\leq i \\leq n$, $l_i \\ne r_i$ holds? How do you prove it? Use prefix sums or similar to optimize your solution. For each $1 \\leq i \\leq n$, for each $l_i \\leq x \\leq r_i$, we want to check if it is okay for impression $i$ being unique at the value of $x$. Note that: for each $j \\neq i$, we can always switch $w_j$ to a value different from $x$ if $l_j \\neq r_j$, since there are at least two options. Therefore, it is impossible if and only if there exists a $1 \\leq j \\leq n$ with $j \\neq i$ such that $l_j = r_j = x$. Let's record $a_i$ as the number of different $k$ satisfying $1 \\leq k \\leq n$ and $l_k = r_k = i$. If $l_i \\neq r_i$, then we say impression $i$ cannot be made unique if and only if for all $l_i \\leq k \\leq r_i$, $a_k \\geq 1$; otherwise ($l_i = r_i$), it cannot be unique if and only if $a_{l_i} \\geq 2$. This can all be checked quickly within a prefix sum, so the overall time complexity is $\\mathcal O(\\sum n)$.",
    "code": "#include <bits/stdc++.h>\n \n#define MAXN 400001\nint l[MAXN], r[MAXN], sum[MAXN], cnt[MAXN];\nvoid solve() {\n\tint n; std::cin >> n;\n\tfor (int i = 1; i <= 2 * n; ++i) sum[i] = cnt[i] = 0;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tstd::cin >> l[i] >> r[i];\n\t\tif (l[i] == r[i]) sum[l[i]] = 1, ++cnt[l[i]];\n\t}\n\tfor (int i = 2; i <= 2 * n; ++i) sum[i] += sum[i - 1];\n\tfor (int i = 1; i <= n; ++i) \n\t\tstd::cout << ((l[i] == r[i] ? cnt[l[i]] <= 1 : sum[r[i]] - sum[l[i] - 1] < r[i] - l[i] + 1) ? \"1\" : \"0\");\n\tstd::cout << '\\n';\n}\nint main() {\n\tstd::ios::sync_with_stdio(false);\n\tstd::cin.tie(nullptr), std::cout.tie(nullptr);\n\tint t; std::cin >> t; while (t--) solve(); return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2053",
    "index": "C",
    "title": "Bewitching Stargazer",
    "statement": "\\begin{quote}\nI'm praying for owning a transparent heart; as well as eyes with tears more than enough...\n\\hfill — Escape Plan, Brightest Star in the Dark\n\\end{quote}\n\nIris looked at the stars and a beautiful problem emerged in her mind. She is inviting you to solve it so that a meteor shower is believed to form.\n\nThere are $n$ stars in the sky, arranged in a row. Iris has a telescope, which she uses to look at the stars.\n\nInitially, Iris observes stars in the segment $[1, n]$, and she has a lucky value of $0$. Iris wants to look for the star in the middle position for each segment $[l, r]$ that she observes. So the following recursive procedure is used:\n\n- First, she will calculate $m = \\left\\lfloor \\frac{l+r}{2} \\right\\rfloor$.\n- If the length of the segment (i.e. $r - l + 1$) is even, Iris will divide it into two equally long segments $[l, m]$ and $[m+1, r]$ for further observation.\n- Otherwise, Iris will aim the telescope at star $m$, and her lucky value will increase by $m$; subsequently, if $l \\neq r$, Iris will continue to observe two segments $[l, m-1]$ and $[m+1, r]$.\n\nIris is a bit lazy. She defines her laziness by an integer $k$: as the observation progresses, she will not continue to observe any segment $[l, r]$ with a length \\textbf{strictly less than} $k$. In this case, please predict her final lucky value.",
    "tutorial": "Process many segments simultaneously. What kind of segments do we process at a time? The length. The point that must be noted is: that if we call the process of splitting a large segment into two smaller segments a round, then all segments are of the same length when the $i$-th round of the observation is conducted; and, the number of rounds does not exceed $\\mathcal O(\\log n)$. The $k$ restriction is equivalent to specifying that only a certain prefix of rounds is computed. Here are some different approaches: (Most succinctly) Note that the distribution of segments after round 1 is centrally symmetric; Also, $x$ and $y$ being centrally symmetric implies that $x + y = n + 1$, so it is simple to calculate by simulating the number of segments and the length directly. If a segment $[l, r]$ is split into $[l, m - 1]$ and $[m + 1, r]$, its left endpoint sum changes from $l$ to $2l + \\frac{r - l}{2} + 1$, and since $(r - l)$ is fixed, the sum of the left endpoints of all segments can be maintained similarly. The following recursive method also works: the answer to $n$ can be recovered by the answer to $\\lfloor \\frac{n}{2} \\rfloor$. The time complexity is $\\mathcal O(t\\log n)$. This is written by _TernaryTree_.",
    "code": "#include <bits/stdc++.h>\n#define int long long\n \nusing namespace std;\n \nint T;\nint n, k;\n \nsigned main() {\n\tcin >> T;\n\twhile (T--) {\n\t\tcin >> n >> k;\n\t\tint mul = n + 1, sum = 0, cur = 1;\n\t\twhile (n >= k) {\n\t\t\tif (n & 1) sum += cur;\n\t\t\tn >>= 1;\n\t\t\tcur <<= 1;\n\t\t}\n\t\tcout << mul * sum / 2 << endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "dp",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2053",
    "index": "D",
    "title": "Refined Product Optimality",
    "statement": "\\begin{quote}\nAs a tester, when my solution has a different output from the example during testing, I suspect the author first.\n\\hfill — Chris, a comment\n\\end{quote}\n\nAlthough Iris occasionally sets a problem where the solution is possibly wrong, she still insists on creating problems with her imagination; after all, everyone has always been on the road with their stubbornness... And like ever before, Iris has set a problem to which she gave a wrong solution, but Chris is always supposed to save it! You are going to play the role of Chris now:\n\n- Chris is given two arrays $a$ and $b$, both consisting of $n$ integers.\n- Iris is interested in the \\textbf{largest} possible value of $P = \\prod\\limits_{i=1}^n \\min(a_i, b_i)$ after an arbitrary rearrangement of $b$. Note that she only wants to know the maximum value of $P$, and \\textbf{no} actual rearrangement is performed on $b$.\n- There will be $q$ modifications. Each modification can be denoted by two integers $o$ and $x$ ($o$ is either $1$ or $2$, $1 \\leq x \\leq n$). If $o = 1$, then Iris will increase $a_x$ by $1$; otherwise, she will increase $b_x$ by $1$.\n- Iris asks Chris the maximum value of $P$ for $q + 1$ times: once before any modification, then after every modification.\n- Since $P$ might be huge, Chris only needs to calculate it modulo $998\\,244\\,353$.\n\nChris soon worked out this problem, but he was so tired that he fell asleep. Besides saying thanks to Chris, now it is your turn to write a program to calculate the answers for given input data.\n\n\\textbf{Note}: since the input and output are large, you may need to optimize them for this problem.\n\nFor example, in C++, it is enough to use the following lines at the start of the main() function:\n\n\\begin{verbatim}\nint main() {\nstd::ios::sync_with_stdio(false);\nstd::cin.tie(nullptr); std::cout.tie(nullptr);\n}\n\n\\end{verbatim}",
    "tutorial": "What if $q = 0$? How do you keep the array sorted? The problem makes no difference when both $a$ and $b$ can be rearranged. Let the rearranged arrays of $a$ and $b$ be $c$ and $d$ respectively. If $q = 0$, we can write $c$ as $\\operatorname{SORTED}(a_1, a_2 \\ldots, a_n)$ and $d$ as $\\operatorname{SORTED}(b_1, b_2 \\ldots, b_n)$. It can be proved that this reaches the maximum value: if not so, then There must be some pair $(i, j)$ such that $c_i < c_j, d_i > d_j$. Since $\\min(c_i, d_i) \\cdot \\min(c_j, d_j) = c_i \\cdot \\min(c_j, d_j) \\leq c_i \\cdot \\min(c_j, d_i) = \\min(c_i, d_j) \\cdot \\min(c_j, d_i)$, we can swap $d_i$ and $d_j$, and the product does not decrease. Consider the modification, which is a single element increment by $1$. Without loss of generality, let $c_x$ be increased by $1$ (and the processing method for $d$ is the same). If $c_x < c_{x+1}$, then after the modification $c_x \\leq c_{x+1}$, which would be fine. Otherwise, we can modify the array $c$ in the form of a single round of \"Insertion Sort\": We continuously swap $c_x$ and $c_{x+1}$, $x \\gets x + 1$, until $c_x < c_{x+1}$ (or $x = n$), and thus the array remains sorted after the increment. In fact, the swap operation does nothing in the above process: in these cases, $c_x = c_{x+1}$ holds! So we can just set $x'$ as the maximum $k$ such that $c_k = c_x$, and then increase $c_{x'}$ by $1$, after which $c$ is still sorted. The $k$ can be found with a naive binary search, so the problem is solved in $\\mathcal O(n\\log n + q(\\log p + \\log n))$ per test case.",
    "code": "#include <bits/stdc++.h>\n \nconstexpr int MOD = 998244353;\nint qpow(int a, int x = MOD - 2) {\n\tint res = 1;\n\tfor (; x; x >>= 1, a = 1ll * a * a % MOD) if (x & 1) res = 1ll * res * a % MOD;\n\treturn res;\n}\n \n#define MAXN 200001\nint a[MAXN], b[MAXN], c[MAXN], d[MAXN];\nvoid solve() {\n\tint n, q, res = 1; std::cin >> n >> q;\n\tfor (int i = 1; i <= n; ++i) std::cin >> a[i], c[i] = a[i];\n\tfor (int i = 1; i <= n; ++i) std::cin >> b[i], d[i] = b[i];\n\tstd::sort(c + 1, c + n + 1), std::sort(d + 1, d + n + 1);\n\tfor (int i = 1; i <= n; ++i) res = 1ll * res * std::min(c[i], d[i]) % MOD;\n\tstd::cout << res << \" \\n\"[q == 0];\n\tfor (int i = 1, op, x; i <= q; ++i) {\n\t\tstd::cin >> op >> x;\n\t\tif (op == 1) {\n\t\t\tint p = std::upper_bound(c + 1, c + n + 1, a[x]) - c - 1;\n\t\t\tif (c[p] < d[p]) res = 1ll * res * qpow(c[p]) % MOD * (c[p] + 1) % MOD;\n\t\t\t++a[x], ++c[p];\n\t\t} else {\n\t\t\tint p = std::upper_bound(d + 1, d + n + 1, b[x]) - d - 1;\n\t\t\tif (d[p] < c[p]) res = 1ll * res * qpow(d[p]) % MOD * (d[p] + 1) % MOD;\n\t\t\t++b[x], ++d[p];\n\t\t}\n\t\tstd::cout << res << \" \\n\"[i == q];\n\t}\n}\n \nint main() {\n\tstd::ios::sync_with_stdio(false);\n\tstd::cin.tie(nullptr), std::cout.tie(nullptr);\n\tint t; std::cin >> t; while (t--) solve(); return 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "math",
      "schedules",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2053",
    "index": "E",
    "title": "Resourceful Caterpillar Sequence",
    "statement": "\\begin{quote}\nEndless Repeating 7 Days\n\\hfill — r-906, Panopticon\n\\end{quote}\n\nThere is a tree consisting of $n$ vertices. Let a caterpillar be denoted by an integer pair $(p, q)$ ($1 \\leq p, q \\leq n$, $p \\neq q$): its head is at vertex $p$, its tail is at vertex $q$, and it dominates all the vertices on the simple path from $p$ to $q$ (including $p$ and $q$). The caterpillar sequence of $(p, q)$ is defined as the sequence consisting only of the vertices on the simple path, sorted in the ascending order of the distance to $p$.\n\nNora and Aron are taking turns moving the caterpillar, with Nora going first. Both players will be using his or her own optimal strategy:\n\n- They will play to make himself or herself win;\n- However, if it is impossible, they will play to prevent the other person from winning (thus, the game will end in a tie).\n\nIn Nora's turn, she must choose a vertex $u$ adjacent to vertex $p$, which is not dominated by the caterpillar, and move all the vertices in it by one edge towards vertex $u$$^{\\text{∗}}$. In Aron's turn, he must choose a vertex $v$ adjacent to vertex $q$, which is not dominated by the caterpillar, and move all the vertices in it by one edge towards vertex $v$. Note that the moves allowed to the two players are different.\n\nWhenever $p$ is a leaf$^{\\text{†}}$, Nora wins$^{\\text{‡}}$. Whenever $q$ is a leaf, Aron wins. If either initially both $p$ and $q$ are leaves, or after $10^{100}$ turns the game has not ended, the result is a tie.\n\nPlease count the number of integer pairs $(p, q)$ with $1 \\leq p, q \\leq n$ and $p \\neq q$ such that, if the caterpillar is initially $(p, q)$, Aron wins the game.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$In other words: Let the current caterpillar sequence be $c_1, c_2, \\ldots, c_k$, then after the move, the new caterpillar sequence becomes $d(u, c_1), d(u, c_2), \\ldots, d(u, c_k)$. Here, $d(x, y)$ is the next vertex on the simple path from $y$ to $x$.\n\n$^{\\text{†}}$In a tree, a vertex is called a leaf if and only if its degree is $1$.\n\n$^{\\text{‡}}$Therefore, Nora never fails to choose a vertex $u$ when the game has not ended. The same goes for Aron.\n\\end{footnotesize}",
    "tutorial": "Suppose somebody wins. In which round does he or she win? A player can always undo what his opponent did in the previous turn. Can you find the necessary and sufficient condition for $(p, q)$ to be a caterpillar that makes Aron win? Denote Nora's first move as round $1$, Aron's first move as round $2$, and so on. Suppose a player does not have a winning strategy in the $k$-th round, but he or she has a winning strategy in the $(k + 2)$-th round - it can be shown impossible because the other player can always withdraw the last move of another player so that the status is the same as it was before the $k$-th round. Therefore: if a player wins in the $k$-th round, we claim that $k \\leq 2$. Given $p, q$, let's determine who will eventually win the game. If both $p$ and $q$ are leaves, the result is a tie. If $p$ is a leaf while $q$ is not, Nora wins. If $q$ is a leaf while $p$ is not, Aron wins. If neither $p$ nor $q$ is a leaf: Can $k = 1$? Nora wins if and only if $p$ is adjacent to a leaf. Can $k = 2$? Aron wins if and only if $p$ is not adjacent to a leaf, and $f(p, q)$ is adjacent to a leaf. Otherwise, the result is a tie. Can $k = 1$? Nora wins if and only if $p$ is adjacent to a leaf. Can $k = 2$? Aron wins if and only if $p$ is not adjacent to a leaf, and $f(p, q)$ is adjacent to a leaf. Otherwise, the result is a tie. The counting part can also be solved easily in $\\mathcal O(n)$. Denote $c$ as the number of leaves. The initial answer would be $c \\cdot (n - c)$, considering the third case. For the fourth case, we can enumerate $m = f(p, q)$, which is adjacent to at least one leaf. Given $m$, $q$ must be a non-leaf neighbor of $m$, and let the number of different $q$ be $k$. For each of the potential $p$, which is a non-leaf node whose neighbors are all non-leaf nodes too, it is computed exactly $k - 1$ times for all the $k$ candidates of $q$ (since $m$ must be on the simple path from $p$ to $q$), so the extra contributions are easy to calculate. (If you do not think that much, you can use some simple DP, which I will not elaborate here.)",
    "code": "#include <bits/stdc++.h>\n\n#define MAXN 200001\nstd::vector<int> g[MAXN];\ninline int deg(int u) { return g[u].size(); }\n\nint d[MAXN];\nvoid solve() {\n\tint n; std::cin >> n; long long ans = 0;\n\tfor (int i = 1, u, v; i < n; ++i) {\n\t\tstd::cin >> u >> v;\n\t\tg[u].push_back(v), g[v].push_back(u);\n\t}\n\tint c1 = 0, c2 = 0;\n\tfor (int i = 1; i <= n; ++i) c1 += (deg(i) == 1);\n\tans += 1ll * c1 * (n - c1);\n\tfor (int i = 1; i <= n; ++i) if (deg(i) > 1) {\n\t\tfor (int v : g[i]) d[i] += (deg(v) > 1);\n\t\tc2 += (d[i] == deg(i));\n\t}\n\tfor (int m = 1; m <= n; ++m) if (deg(m) > 1 && d[m] != deg(m)) \n\t\tans += 1ll * c2 * (d[m] - 1);\n\tstd::cout << ans << '\\n';\n\tfor (int i = 1; i <= n; ++i) \n\t\t(std::vector<int>()).swap(g[i]), d[i] = 0;\n}\n\nint main() {\n\tstd::ios::sync_with_stdio(false);\n\tstd::cin.tie(nullptr), std::cout.tie(nullptr);\n\tint t; std::cin >> t; while (t--) solve(); return 0;\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "games",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2053",
    "index": "F",
    "title": "Earnest Matrix Complement",
    "statement": "\\begin{quote}\n3, 2, 1, ... We are the — RiOI Team!\n\\hfill — Felix & All, Special Thanks 3\n\\end{quote}\n\n- Peter: Good news: My problem T311013 is approved!\n- $\\delta$: I'm glad my computer had gone out of battery so that I wouldn't have participated in wyrqwq's round and gained a negative delta.\n- Felix: [thumbs_up] The problem statement concerning a removed song!\n- Aquawave: Do I mourn my Chemistry?\n- E.Space: ahh?\n- Trine: Bread.\n- Iris: So why am I always testing problems?\n\nTime will pass, and we might meet again. Looking back at the past, everybody has lived the life they wanted.\n\nAquawave has a matrix $A$ of size $n\\times m$, whose elements can only be integers in the range $[1, k]$, inclusive. In the matrix, some cells are already filled with an integer, while the rest are currently not filled, denoted by $-1$.\n\nYou are going to fill in all the unfilled places in $A$. After that, let $c_{u,i}$ be the number of occurrences of element $u$ in the $i$-th row. Aquawave defines the beauty of the matrix as\n\n$$\\sum_{u=1}^k \\sum_{i=1}^{n-1} c_{u,i} \\cdot c_{u,i+1}.$$\n\nYou have to find the maximum possible beauty of $A$ after filling in the blanks optimally.",
    "tutorial": "What are we going to fill into the matrix? In other words, is there any relationship between the filed numbers? Try to come up with a naive DP solution that works in large time complexity, such as $\\mathcal O(nk^2)$. For many different numbers between two consecutive rows, however, the transition is almost the same. If $x' = \\max(a, x + b)$ and $x'' = \\max(c, x' + d)$, then $x'' = \\max(\\max(a + d, c), x + b + d)$. Conclusion: For each row, an optimal solution exists, such that the newly filled-in numbers are the same. Proof: Consider fixing the rows $i - 1$ and $i + 1$, and observe all the newly filled-in numbers at row $i$. Then a new number $u$ brings a contribution of $c_{u, i-1} + c_{u, i+1}$, and it is clear that there exists a scheme that takes the maximum value such that all the $u$ filled in are equal. Adjusting for each row leads to the above conclusion. Consider dp. Let $f_{i,j}$ denote the maximum contribution that can be achieved between the first $i$ rows (ignoring the initial contribution) when the empty elements in the $i$-th row are filled with $j$. Let $c_i$ be the number of $-1$ numbers in the $i$-th row, and $d_{i,j}$ denote the number of elements $j$ in the $i$-th row initially. The transfer should be as follows: $f_{i, j} = \\max(\\max\\limits_{1 \\leq w \\leq k}(f_{i-1, w} + c_i \\cdot d_{i-1, w} + c_{i-1} \\cdot d_{i-1, j}), f_{i-1, j} + (d_{i, j} + c_i) \\cdot (d_{i-1, j} + c_{i-1}) - d_{i, j}d_{i-1, j}).$ In addition to being able to optimize the above transition to $\\mathcal O(nk)$, the present problem in a matrix has a good property. Specifically, for the same $i$, there are only $\\mathcal O(m)$ values of $j$ such that $d_{i,j} \\neq 0$! If $d_{i,j} = 0$ and $d_{i-1, j} = 0$, the original transfer can be viewed as $f_{i,j} = \\max(\\max\\limits_{1 \\leq w \\leq k}(f_{i-1, w}), f_{i-1, j} + c_i \\cdot c_{i-1}).$ This can be seen as a global modification in the form of $x \\gets \\max(a, x + b)$. The tags are composable in $\\mathcal O(1)$; Otherwise, we can brutely update the new $dp_j$ for $\\mathcal O(m)$ positions. Therefore, this problem is solved in $\\mathcal O(nm)$. We decided to let every segment tree solution pass comfortably, so that we set small constraints and large TL. Bonus Hint for implementation: always use $\\max(a, dp_j + b)$ to get the real value.",
    "code": "#include <bits/stdc++.h>\n \nnamespace FastIO {\n\tchar buf[1 << 21], *p1 = buf, *p2 = buf;\n#define getchar() (p1 == p2 && (p1 = buf, p2 = (p1 + fread(buf, 1, 1 << 21, stdin))) == p1 ? EOF : *p1++)\n\ttemplate <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }\n\ttemplate <typename T> inline void write(T x) { if (!x) return; write<T>(x / 10), putchar((x % 10) ^ '0'); }\n\ttemplate <typename T> inline void print(T x) { if (x > 0) write<T>(x); else if (x < 0) putchar('-'), write<T>(-x); else putchar('0'); }\n\ttemplate <typename T> inline void print(T x, char en) { print<T>(x), putchar(en); }\n#undef getchar\n}; using namespace FastIO;\n \nusing ll = long long;\nvoid solve() {\n\tint n = read<int>(), m = read<int>(), k = read<int>(); ll cntP = 0, cntQ = 0;\n\tstd::vector<int> vep(m), veq(m), cntp(k + 1), cntq(k + 1), vis(k + 1);\n\tstd::vector<ll> dp(k + 1); ll a = 0, b = 0, v = 0, ext = 0; // max(a, x + b).\n\tcntp[0] = cntq[0] = m;\n\tauto get = [&](int x) -> int { return (~x) ? x : 0; };\n\tauto read_q = [&]() -> void {\n\t\tfor (int i = 0; i < m; ++i) --cntq[get(veq[i])];\n\t\tfor (int i = 0; i < m; ++i) ++cntq[get(veq[i] = read<int>())];\n\t\tcntQ = cntq[0];\n\t};\n\tauto roll = [&]() -> void { std::swap(vep, veq), std::swap(cntp, cntq), std::swap(cntP, cntQ); };\n\tauto chkmax = [&](ll &a, ll b) -> void { a = std::max(a, b); };\n\tread_q(), roll();\n\tfor (int i = 2; i <= n; ++i) {\n\t\tread_q();\n\t\tll max_dp = std::max(a, v + b);\n\t\tfor (int k : vep) if (~k) chkmax(max_dp, std::max(a, dp[k] + b) + cntP * cntq[k]);\n\t\tfor (int k : veq) if (~k) chkmax(max_dp, std::max(a, dp[k] + b) + cntP * cntq[k]);\n\t\tfor (int k : vep) if ((~k) && vis[k] != i) {\n\t\t\tvis[k] = i, ext += 1ll * cntp[k] * cntq[k];\n\t\t\tdp[k] = std::max(a, dp[k] + b) + cntP * cntq[k] + cntQ * cntp[k] - b;\n\t\t\tchkmax(dp[k], max_dp + cntp[k] * cntQ - b - cntP * cntQ);\n\t\t\tchkmax(v, dp[k]);\n\t\t} for (int k : veq) if ((~k) && vis[k] != i) {\n\t\t\tvis[k] = i;\n\t\t\tdp[k] = std::max(a, dp[k] + b) + cntP * cntq[k] + cntQ * cntp[k] - b;\n\t\t\tchkmax(dp[k], max_dp + cntp[k] * cntQ - b - cntP * cntQ);\n\t\t\tchkmax(v, dp[k]);\n\t\t} a = std::max(max_dp, a + cntP * cntQ), b += cntP * cntQ;\n\t\troll();\n\t} print<ll>(std::max(a, v + b) + ext, '\\n');\n}\n \nint main() { int T = read<int>(); while (T--) solve(); return 0; }",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2053",
    "index": "G",
    "title": "Naive String Splits",
    "statement": "\\begin{quote}\nAnd I will: love the world that you've adored; wish the smile that you've longed for. Your hand in mine as we explore, please take me to tomorrow's shore.\n\\hfill — Faye Wong, As Wished\n\\end{quote}\n\nCocoly has a string $t$ of length $m$, consisting of lowercase English letters, and he would like to split it into parts. He calls a pair of strings $(x, y)$ beautiful if and only if there exists a sequence of strings $a_1, a_2, \\ldots, a_k$, such that:\n\n- $t = a_1 + a_2 + \\ldots + a_k$, where $+$ denotes string concatenation.\n- For each $1 \\leq i \\leq k$, at least one of the following holds: $a_i = x$, or $a_i = y$.\n\nCocoly has another string $s$ of length $n$, consisting of lowercase English letters. Now, for each $1 \\leq i < n$, Cocoly wants you to determine whether the pair of strings $(s_1s_2 \\ldots s_i, \\, s_{i+1}s_{i+2} \\ldots s_n)$ is beautiful.\n\n\\textbf{Note}: since the input and output are large, you may need to optimize them for this problem.\n\nFor example, in C++, it is enough to use the following lines at the start of the main() function:\n\n\\begin{verbatim}\nint main() {\nstd::ios::sync_with_stdio(false);\nstd::cin.tie(nullptr); std::cout.tie(nullptr);\n}\n\n\\end{verbatim}",
    "tutorial": "(If we do not have to be deterministic) We do not need any hard string algorithm. In what cases won't greed work? Why? Is your brute forces actually faster (maybe you can explain it by harmonic series)? Let's call the prefix $s_1$ the short string and the suffix $s_2$ the long string. If $\\lvert s_1\\rvert\\gt \\lvert s_2\\rvert$, swapping the order doesn't affect the answer. Consider a greedy approach. We first match a few short strings until we can't match anymore. If we can't match, we try discarding a few short strings and placing one long string. We enumerate how many short strings to discard. Find the first position where we can place a long string. We call this placing once a \"matching process.\" The starting position of each \"matching process\" is the next position after the previous \"matching process.\" However, this approach has a flaw. Below, I will explain the situation where this flaw occurs. It's not difficult to view the long string as several short strings concatenated with a \"tail\" at the end. Why only find the first position? Why wouldn't it be better to backtrack and discard a few more $s_1$'s before placing the long string? The diagram above is an example. The red line indicates the cutoff position for matching $s_1$. The three orange boxes represent the possible choices for attempting to match the long string. The last one is invalid, so skip it. Replace it with the \"The first valid position to place the long string.\" box. This box is correct. The difference between choosing the second box and the first box is that when we end the matching and proceed to the next round, the content we need to match is that a suffix of $s_1$ has been moved to the beginning of $s_1$. As shown in the diagram. The alignment results in the following diagram. In the diagram, the case where $\\lvert pre\\rvert \\gt \\lvert suf\\rvert$ is shown. The other case follows similarly. $pre+suf=suf+pre$, and as can be seen from the diagram, here $pre+suf$ needs to be \"misaligned but equal.\" This means that $s_1$ must have a periodic cycle, and the \"tail\" must also be able to be formed through this cycle. Additionally, the $\\lvert s_1 \\rvert$ characters at the beginning of $s_2$ must still be able to be formed by the periodic cycle. In summary, it is equivalent to $s_1$ and $s_2$ having a common periodic cycle. In other words, backtracking twice can lead to a solution, but backtracking once may not always work. It is necessary for $s_1$ and $s_2$ to have a common periodic cycle. Having a common periodic cycle is too specific. First, the common periodic cycle of these two strings must indeed be the periodic cycle of string $s$. By finding this cycle in advance, it essentially becomes a problem of solving an equation. Let $a=\\lvert s_1\\rvert$ and $b=\\lvert s_2\\rvert$, and we need to check whether there are non-negative integer solutions $x$ and $y$ that satisfy the equation $xa+yb=\\lvert s \\rvert$. This equation-solving part is just for show. We enumerate $y$, and for each value of $y$, we compute the enumeration $\\mathcal O\\left(\\frac{m}{n}\\right)$ times. At most, we do this $n$ times, so the overall complexity is $\\mathcal O(m)$. If we directly implement this, the worst-case complexity is related to the harmonic series. Consider a case like $s_1 = \\texttt{a}, s_2 = \\texttt{aaaaaaaab}$, and $t = \\texttt{aaaaaaaaaaaaaaaaaaaaaaaaab}$. In this case, we would need to attempt $\\mathcal O\\left(\\frac{m}{\\lvert s_1\\rvert }\\right)$ steps to finish matching the short string. Each time we backtrack, it requires at most $\\mathcal O\\left(\\frac{m}{\\lvert s_2\\rvert }\\right)$ steps, and each of those takes $\\mathcal O\\left(\\frac{\\lvert s_2\\rvert }{\\lvert s_1\\rvert }\\right)$. Thanks to orzdevinwang and crazy_sea for pointing out it! Yes, this problem can indeed be solved in linear time. First, let the prefix of the long string contain $c$ short strings. Then, the first \"valid position to place the long string\" we backtrack to can only be obtained by either backtracking $c$ short strings or $c+1$ short strings. This is easy to understand. Backtracking $c$ short strings means considering the prefix of the long string, then adding the \"tail\" of the long string. Backtracking $c + 1$ short strings only happens when the \"tail\" part of the long string is a prefix of the short string. For example, the hack in the CF comment section: https://codeforces.com/blog/entry/136455?#comment-1234262 The correct output should be: When $k = 3$, $s_1 = \\texttt{aba}$, $s_2 = \\texttt{abaab}$, we first filled in 2 short strings, but if we backtrack $c = 1$ short string, it will be judged as unsolvable. This is how the error in std occurs. This situation only arises when the \"tail\" part of $s_2$ is a prefix of $s_1$. So, each time we calculate, we first use binary search to find this $c$, and the complexity is $\\mathcal O\\left(\\sum\\limits_{i=1}^n\\log(\\frac n i)\\right)=\\mathcal O(n)$. After that, backtracking only requires two checks. The backtracking process becomes linear. Next, let's accelerate the process of filling in short strings. The hack for brute-force filling has already been given above. If we directly use the method that everyone initially thought was correct, which is the \"binary search for the number of short string occurrences\" method, Then it can be accelerated by this set of hacks to achieve a $\\log$ complexity. crazy_sea points out an alternative solution. Similar to block division, let $B = \\frac{n}{\\lvert s_1\\rvert}$. We first try to match $B$ occurrences of $s_1$, meaning that each match can move forward by $n$ positions. After that, the remaining part will not exceed $B$ occurrences, and we binary search to find how many are left. For the part where we moved forward by $B$ occurrences, we can backtrack at most once, and then the binary search will take $\\mathcal O(\\log B)$. Each time, we can at least fill in $\\lvert s_2\\rvert$ occurrences. The time complexity for calculating the answer becomes $\\mathcal O\\left(\\frac{m}{\\lvert s_2\\rvert }\\log B\\right)$, and the total complexity, due to $\\mathcal O\\left(\\sum\\limits_{i=1}^n \\log(\\frac{n}{i})\\right) = \\mathcal O(n)$, is $\\mathcal O(m)$. Thus, the problem is solved in linear time. During testing, we found that jqdai0815's solution is actually more violent than we thought (We have also received something similar in contest). He specially handled the case in which $X$ and $T$ share a common shortest period, and for the rest $i$, he just used two queues to optimize the BFS progress (actually changing it to std::priority_queue<int> or similar also works), and it passed just seeming to have a larger constant time complexity. I'm curious if anybody can (hack it or) prove that it is correct. Thanks in advance! This is written by Caylex. This is written by Caylex.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntemplate <int P>\nclass mod_int\n{\n    using Z = mod_int;\n\nprivate:\n    static int mo(int x) { return x < 0 ? x + P : x; }\n\npublic:\n    int x;\n    int val() const { return x; }\n    mod_int() : x(0) {}\n    template <class T>\n    mod_int(const T &x_) : x(x_ >= 0 && x_ < P ? static_cast<int>(x_) : mo(static_cast<int>(x_ % P))) {}\n    bool operator==(const Z &rhs) const { return x == rhs.x; }\n    bool operator!=(const Z &rhs) const { return x != rhs.x; }\n    Z operator-() const { return Z(x ? P - x : 0); }\n    Z pow(long long k) const\n    {\n        Z res = 1, t = *this;\n        while (k)\n        {\n            if (k & 1)\n                res *= t;\n            if (k >>= 1)\n                t *= t;\n        }\n        return res;\n    }\n    Z &operator++()\n    {\n        x < P - 1 ? ++x : x = 0;\n        return *this;\n    }\n    Z &operator--()\n    {\n        x ? --x : x = P - 1;\n        return *this;\n    }\n    Z operator++(int)\n    {\n        Z ret = x;\n        x < P - 1 ? ++x : x = 0;\n        return ret;\n    }\n    Z operator--(int)\n    {\n        Z ret = x;\n        x ? --x : x = P - 1;\n        return ret;\n    }\n    Z inv() const { return pow(P - 2); }\n    Z &operator+=(const Z &rhs)\n    {\n        (x += rhs.x) >= P && (x -= P);\n        return *this;\n    }\n    Z &operator-=(const Z &rhs)\n    {\n        (x -= rhs.x) < 0 && (x += P);\n        return *this;\n    }\n    Z operator-() { return -x; }\n    Z &operator*=(const Z &rhs)\n    {\n        x = 1ULL * x * rhs.x % P;\n        return *this;\n    }\n    Z &operator/=(const Z &rhs) { return *this *= rhs.inv(); }\n#define setO(T, o)                                  \\\n    friend T operator o(const Z &lhs, const Z &rhs) \\\n    {                                               \\\n        Z res = lhs;                                \\\n        return res o## = rhs;                       \\\n    }\n    setO(Z, +) setO(Z, -) setO(Z, *) setO(Z, /)\n#undef setO\n        friend istream &\n        operator>>(istream &is, mod_int &x)\n    {\n        long long tmp;\n        is >> tmp;\n        x = tmp;\n        return is;\n    }\n    friend ostream &operator<<(ostream &os, const mod_int &x)\n    {\n        os << x.val();\n        return os;\n    }\n};\ntypedef long long ll;\ntypedef unsigned long long ull;\nmt19937 rnd(chrono::system_clock::now().time_since_epoch().count());\nconstexpr int p = 993244853;\nusing Hash = mod_int<p>;\n// using Hash = ull;\nconst Hash base = rnd() % 20091119 + 30;\nstring s, t;\nHash st;\nint mnlen;\nHash S[5000020];\nHash T[5000020];\nHash pw[5000020];\n// int doit;\ninline Hash SUM(const int l, const int r, const Hash *s) { return s[r] - s[l - 1] * pw[r - l + 1]; }\nint n, m;\ninline bool check(const int l, const int r, const Hash x, const int len, const Hash *S)\n{\n    // doit++;\n    return r - l + 1 >= len && SUM(l, l + len - 1, S) == x && SUM(l, r - len, S) == SUM(l + len, r, S);\n}\ninline bool calc(const int L1, const int R1, const int L2, const int R2, const int l1, const int l2)\n{\n    if (mnlen && check(L1, R1, st, mnlen, S) && check(L2, R2, st, mnlen, S))\n    {\n        if (check(1, m, st, mnlen, T))\n        {\n            for (int i = 0; i <= m; i += l2)\n            {\n                if (!((m - i) % l1))\n                    return 1;\n            }\n            return 0;\n        }\n    }\n    const Hash s1 = SUM(L1, R1, S);\n    const Hash s2 = SUM(L2, R2, S);\n    int l = 1, r = l2 / l1, okcnt = 0;\n    while (l <= r)\n    {\n        int mid = l + r >> 1;\n        if (check(L2, L2 + mid * l1 - 1, s1, l1, S))\n            l = (okcnt = mid) + 1;\n        else\n            r = mid - 1;\n    }\n    const int tt = (n / l1);\n    int ed = 0;\n    while (ed <= m)\n    {\n        int L = 1, R = (m - ed) / l1, cnt = 0;\n        int tcnt = 0;\n        while (tcnt + tt <= R && check(ed + 1, ed + (tcnt + tt) * l1, s1, l1, T))\n            tcnt += tt;\n        L = max(L, tcnt);\n        R = min(R, tcnt + tt - 1);\n        // cerr << ed << ' ' << L << ' ' << R << '\\n';\n        while (L <= R)\n        {\n            int mid = L + R >> 1;\n            if (check(ed + 1, ed + mid * l1, s1, l1, T))\n                L = (cnt = mid) + 1;\n            else\n                R = mid - 1;\n        }\n        if (ed + cnt * l1 + 1 > m)\n            return 1;\n        // int st = ed + (cnt - okcnt) * l1 + 1;\n        // if (st > ed && st + l2 - 1 <= m && SUM(st, st + l2 - 1, T) == s2)\n        // {\n        //     ed = st + l2 - 1;\n        //     continue;\n        // }\n        // return 0;\n        bool found = 0;\n        for (int st = ed + (cnt - okcnt) * l1 + 1, cnt = 1; cnt <= 2 && st > ed; st -= l1, cnt++)\n        {\n            if (st + l2 - 1 <= m && SUM(st, st + l2 - 1, T) == s2)\n            {\n                ed = st + l2 - 1;\n                found = 1;\n                break;\n            }\n        }\n        if (!found)\n            return 0;\n    }\n    return 1;\n}\nvoid solve()\n{\n    // build();\n    mnlen = 0;\n    cin >> n >> m >> s >> t;\n    s = ' ' + s;\n    t = ' ' + t;\n    for (int i = 1; i <= n; i++)\n        S[i] = S[i - 1] * base + Hash(s[i] - 'a' + 1);\n    for (int i = 1; i <= m; i++)\n        T[i] = T[i - 1] * base + Hash(t[i] - 'a' + 1);\n    for (int i = 1; i <= n; i++)\n    {\n        if (n % i == 0 && check(1, n, S[i], i, S))\n        {\n            st = S[i];\n            mnlen = i;\n            break;\n        }\n    }\n    for (int i = 1; i < n; i++)\n        putchar('0' ^ (i <= n - i ? calc(1, i, i + 1, n, i, n - i) : calc(i + 1, n, 1, i, n - i, i)));\n    putchar('\\n');\n    // cerr << doit << '\\n';\n}\nint main()\n{\n    // freopen(\"out.txt\", \"r\", stdin);\n    pw[0] = Hash(1);\n    for (int i = 1; i <= 5'000'000; i++)\n        pw[i] = pw[i - 1] * base;\n    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n    // cerr << fixed << setprecision(10) << 1.0 * clock() / CLOCKS_PER_SEC << '\\n';\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy",
      "hashing",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 3400
  },
  {
    "contest_id": "2053",
    "index": "H",
    "title": "Delicate Anti-monotonous Operations",
    "statement": "\\begin{quote}\nI shall be looking for you who would be out of Existence.\n\\hfill — HyuN, Disorder\n\\end{quote}\n\nThere are always many repetitive tasks in life. Iris always dislikes them, so she refuses to repeat them. However, time cannot be turned back; we only have to move forward.\n\nFormally, Iris has an integer sequence $a_1, a_2, \\ldots, a_n$, where each number in the sequence is between $1$ and $w$, inclusive. It is guaranteed that $w \\geq 2$.\n\nIris defines an operation as selecting two numbers $a_i, a_{i+1}$ satisfying $a_i = a_{i+1}$, and then changing them to two arbitrary integers within the range $[1, w]$. Iris does not like equality, so she must guarantee that $a_i \\neq a_{i+1}$ after the operation. Two identical pairs $a_i, a_{i+1}$ can be selected multiple times.\n\nIris wants to know the maximum possible sum of all elements of $a$ after several (possible, zero) operations, as well as the minimum number of operations required to achieve this maximum value.",
    "tutorial": "What if $w = 2$? Is it optimal to increase $\\sum\\limits_{i=0}^n [a_i \\neq a_{i+1}]$ (suppose $a_0 = a_{n+1} = 2$)? If $w \\geq 3$, what's the answer to the first question? If $a_i = a_{i+1}$, after the operation we can obtain $a_{i-1} = a_i$ or $a_{i+1} = a_{i+2}$ (and possibly, both). Try to think of the whole process reversedly. If $w \\geq 3$, $1 \\leq a_i \\leq w - 1$, can you solve the problem? How many extra operations are required for each $1 \\leq i \\leq n$ if $a_i = w$, in the above scheme you use for $a_i \\leq w - 1$? Read the Hints. $w = 2$ After any operation, $k = \\sum\\limits_{i=0}^n [a_i \\neq a_{i+1}]$ won't decrease (suppose $a_0 = a_{n+1} = 2$). For a fixed $k$, the maximal $\\sum a_i = 2n - \\frac{1}{2}k$ and can be reached by each time turning a $[2, 1, 1]$ into $[2, 2, 1]$ (or symmetrically, $[1, 1, 2] \\rightarrow [1, 2, 2]$. $w \\geq 3$ No initial operations can be conducted, or $\\min(a_i) = w$ No initial operations can be conducted, or $\\min(a_i) = w$ This case is trivial. $w \\geq 3$ Some initial operations can be conducted Some initial operations can be conducted We claim that the answer to the first question is $nw - 1$. For the second question, let's study some rather easier cases below. $w \\geq 3$ Some initial operations can be conducted $a_i \\neq w$ Some initial operations can be conducted $a_i \\neq w$ $a_i \\neq w$ We pretend that the final sequence is $[w, w, \\dots, w, (w-1), w, w, \\dots, w]$, then since $(a_i, a_{i+1})$ must be different after the operation, the last operation can only occur on $[w, (w-1)]$ (or $[(w-1), w]$). And since initially $a_i \\neq w$, each position must have been operated on at least once. This gives us states such as $[w, \\dots, w, x, x, w, \\dots, w]$, $[w, \\dots, w, y, y, x, w, \\dots, w]$, etc. To the leftmost positions, we get $a_1 = a_2$ (essentially based on Hint 3). Also, we get ...... $a_{n-1} = a_n$? This is if and only if the initial $[w, (w - 1)]$ is neither at the beginning nor at the end. If the initial $[w, (w - 1)]$ is at the beginning, we only need $a_{n-1} = a_n$ to achieve the goal, and symmetrically the same. Less is more. Obviously, we only need to satisfy either $a_1 = a_2$ or $a_{n-1} = a_n$, and then use $n - 1$ more operations to reach the target situation. How do we get to $a_1 = a_2$ (symmetrically the same)? Based on Hint 3, we find the smallest $x$ that satisfies $a_x = a_{x+1}$, and then follow the example above, again using $x - 1$ operations to conduct the equality sign to $a_1 = a_2$. Lemma 1: We can never choose an index $a_i = w$, fix it (i.e. avoid changing $a_i$ in the following operations), and then use some operations to reach $\\sum a_i = nw - 1$ unless $[a_1, \\ldots, a_i] = [w, \\ldots, w]$ or $[a_i, \\ldots, a_n] = [w, \\ldots, w]$. Proof: If not so, the array is split into two parts: $[a_1, \\ldots, a_{i-1}]$ and $[a_{i+1}, \\ldots, a_n]$. We have: after some operations, the maximum $\\sum a_i$ we can get for each part are respectively $(i-1)w - 1, (n-i)w - 1$, and add them up and we get $nw - 2$, which is less than $nw - 1$, so it's never optimal. Lemma 2: Look at the final array $a$, consisting of $n - 1$ element $w$ and $1$ element $(w - 1)$. Obtain an array $a'$ by keeping the elements with the value of $w$. Denote $t_i$ as the last round in which ${a'}_i$ was changed to $w$ (and then become fixed). Then, there exists some $k$ such that $t_1 < t_2 < \\dots < t_k > t_{k+1} > \\dots > t_{n-1}$. Proof: This follows from Lemma 1. According to Lemma 2, we can see the pattern that we used above is optimal. $w \\geq 3$ Some initial operations can be conducted $a_1 \\neq w, a_n \\neq w$ Some initial operations can be conducted $a_1 \\neq w, a_n \\neq w$ $a_1 \\neq w, a_n \\neq w$ Basically, the idea remains to reach $a_1 = a_2$ in the same way first (symmetrically the same), and then to extend to all positions. However, at this point, in the second stage, some problems may arise as follows: $[\\dots \\underline{a_k}\\ a_{k+1}\\ w\\ a_{k+3} \\dots]$ $[\\dots \\underline{\\color{red}{a_{k+1}}\\ a_{k+1}}\\ w\\ a_{k+3} \\dots]$ $[\\dots \\color{red}s\\ \\underline{\\color{red}w\\ w}\\ a_{k+3} \\dots]$ $[\\dots \\color{red}{\\underline{s\\ s}}\\ t\\ a_{k+3} \\dots]$ $[\\dots \\color{red}w\\ \\underline{\\color{red}t\\ t}\\ a_{k+3} \\dots]$ $[\\dots \\color{red}{w\\ w}\\ \\underline{\\color{red}{a_{k+3}}\\ a_{k+3}} \\dots]$ In which $s, t, w$ are three distinct integers in the range $[1, w]$ (This also explains why we need to specially deal with the $w = 2$ case). Since we cannot fix $a_{k+2} = w$ at the beginning (refer to the \"Why is it optimal?\" spoiler above), we have to first change $a_{k+2}$ into something not equal to $w$, and that cost at least $2$ extra operations, which is shown here. Do we always need $2$ extra operations? One may note that if $a_i = a_{i+1} = w$, in which the two elements are both in the way of expansion, we can only use $1$ operation to vanish their existence. Formally, if there is a maximum continuous subsegment of $w$ in the way of expansion, let its length be $L$, then we will spend $\\lceil \\frac{L}{2} \\rceil + [L = 1]$ extra operations. Suppose in the first stage, we pick $a_x = a_{x+1}$ and keep operating on it until $a_1 = a_2$. Then after it, $\\forall 3 \\leq k \\leq x + 1$, $a_k$ can be an arbitrary number which is different from the initial $a_{k-1}$, thus we can always force it to be $\\neq w$. In the above case, only elements $[a_{x+2}, \\ldots, a_n]$ are considered 'in the way of expansion', and symmetrically the same. $w \\geq 3$ Some initial operations can be conducted No additional constraints Some initial operations can be conducted No additional constraints No additional constraints It may come to you that if $a_1 = w$, we can ignore $a_1$; if $a_1 = a_2 = w$, we can ignore $a_2$. Symmetrically the same. And so on... Then we boil the problem down to the case above. It is correct unless in some rare cases when we ignore all the prefixes and suffixes, there will be no remaining $a_i = a_{i+1}$; or if we pick any pair $a_i = a_{i+1}$ as the starting pair in the remaining array, it is not optimal compared to picking an $a_k = a_{k+1} = w (a_{k+2} \\neq w)$ (symmetrically the same). So, we have to special handle the deleted prefix and suffix, once it has a length greater than $2$. In summary, the problem can be solved in $\\mathcal O(n)$.",
    "code": "#include <bits/stdc++.h>\n\n#define MAXN 200005\nint a[MAXN];\n\nvoid solve() {\n\tint N, w; scanf(\"%d%d\", &N, &w);\n\tfor (int i = 1; i <= N; ++i) scanf(\"%d\", a + i);\n\tif (N == 1) return (void)printf(\"%d 0\\n\", a[1]);\n\tif (*std::min_element(a + 1, a + N + 1) == w)\n\t\treturn (void)printf(\"%lld 0\\n\", 1ll * w * N);\n\tif (w == 2) {\n\t\tint ans = N * 2, pans = 0;\n\t\tfor (int i = 1, j = 1; i <= N; i = ++j) if (a[i] == 1) {\n\t\t\t--ans; while (j < N && a[j + 1] == 1) ++j; pans += j - i;\n\t\t}\n\t\treturn (void)printf(\"%d %d\\n\", ans, pans);\n\t}\n\tbool flag = true;\n\tfor (int i = 1; i < N; ++i) if (a[i] == a[i + 1]) flag = false;\n\tif (flag) return (void)printf(\"%lld 0\\n\", std::accumulate(a + 1, a + N + 1, 0ll));\n\tprintf(\"%lld \", 1ll * w * N - 1);\n\tif (std::accumulate(a + 1, a + N + 1, 0ll) == 1ll * w * N - 1) return (void)puts(\"0\");\n\tint ans = 0x3f3f3f3f, l = (a[1] == w ? 2 : 1), r = (a[N] == w ? N - 1 : N);\n\tif ((a[1] == w && a[2] == w) || (a[N] == w && a[N - 1] == w)) {\n\t\tint Lw = 0, Rw = N + 1;\n\t\twhile (a[Lw + 1] == w) ++Lw; while (a[Rw - 1] == w) --Rw;\n\t\tint pans = Rw - Lw;\n\t\tfor (int i = Lw + 1, j = i; i < Rw; i = ++j) if (a[i] == w) {\n\t\t\twhile (j + 1 < Rw && a[j + 1] == w) ++j;\n\t\t\tpans += (i == j ? 2 : ((j - i) >> 1) + 1);\n\t\t}\n\t\tans = pans, l = Lw + 1, r = Rw - 1;\n\t}\n\tfor (int d = 0; d < 2; std::reverse(a + l, a + r + 1), ++d) \n\t\tfor (int i = l - 1, pre = 0, len = 0; i + 2 <= r; ) {\n\t\t\tif (a[i + 1] == a[i + 2]) \n\t\t\t\tans = std::min(r - (i + 1) + r - l - 1 + pre - ((len == 1) && i + 2 < r && a[i + 3] != w ? 1 : 0), ans);\n\t\t\t++i; if (a[i] == w) ++len, pre += (len == 1 ? 2 : len == 2 ? -1 : (len & 1)); else len = 0;\n\t}\n\tprintf(\"%d\\n\", ans);\n}\n\nint main() { int T; scanf(\"%d\", &T); while (T--) solve(); return 0; }",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2053",
    "index": "I1",
    "title": "Affectionate Arrays (Easy Version)",
    "statement": "\\begin{quote}\nYou are the beginning of the letter, the development of a poem, and the end of a fairy tale.\n\\hfill — ilem, Pinky Promise\n\\end{quote}\n\n\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, you need to compute the minimum length of the arrays. You can hack only if you solved all versions of this problem.}\n\nIris treasures an integer array $a_1, a_2, \\ldots, a_n$. She knows this array has an interesting property: the maximum absolute value of all elements is less than or equal to the sum of all elements, that is, $\\max(\\lvert a_i\\rvert) \\leq \\sum a_i$.\n\nIris defines the boredom of an array as its maximum subarray$^{\\text{∗}}$ sum.\n\nIris's birthday is coming, and Victor is going to send her another array $b_1, b_2, \\ldots, b_m$ as a gift. For some seemingly obvious reasons, he decides the array $b_1, b_2, \\ldots, b_m$ should have the following properties.\n\n- $a_1, a_2, \\ldots, a_n$ should be a subsequence$^{\\text{†}}$ of $b_1, b_2, \\ldots, b_m$.\n- The two arrays have the same sum. That is, $\\sum\\limits_{i=1}^n a_i = \\sum\\limits_{i=1}^m b_i$.\n- The boredom of $b_1, b_2, \\ldots, b_m$ is the smallest possible.\n- Among the arrays with the smallest boredom, the length of the array $b$ (i.e., $m$) is the smallest possible. And in this case, Iris will understand his regard as soon as possible!\n\nEven constrained as above, there are still too many possible gifts. So Victor asks you to \\textbf{compute the value of $\\boldsymbol{m}$} of any array $b_1, b_2, \\ldots, b_m$ satisfying all the conditions above. He promises you: if you help him successfully, he will share a bit of Iris's birthday cake with you.\n\n\\textbf{Note}: since the input is large, you may need to optimize it for this problem.\n\nFor example, in C++, it is enough to use the following lines at the start of the main() function:\n\n\\begin{verbatim}\nint main() {\nstd::ios::sync_with_stdio(false);\nstd::cin.tie(nullptr); std::cout.tie(nullptr);\n}\n\n\\end{verbatim}\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\n$^{\\text{†}}$A sequence $c$ is a subsequence of a sequence $d$ if $c$ can be obtained from $d$ by the deletion of several (possibly, zero or all) element from arbitrary positions.\n\\end{footnotesize}",
    "tutorial": "What is the minimized LIS? How do you prove that it is an achievable lower bound? Go for a brute DP first. We claim that the minimized LIS is $\\sum a_i$. Let $p$ be $\\sum a_i$. Since it is required that $\\operatorname{LIS}(b) = p$ while $\\sum b_i = p$, we point out that it is equivalent to each of the prefix sums of the sequence being between $[0, p]$. Sufficiency: $\\forall X \\in [0, p], Y \\in [0, p]$, $X - Y \\leq p$. Also, we can pick $X = p, Y = 0$, so it can only be $= p$. Necessity: disproof. If a prefix sum is $< 0$, then choose the whole array except for this prefix; if a prefix sum is $> p$, then choose this prefix. Both derive a contradiction of the LIS being greater than $p$. Consider dp. Let $f_{i,j}$ denote, after considering the first $i$ numbers, the minimum extra sequence length (i.e. the actual length minus $i$), when the current prefix sum is $j$. The initial states are $f_{0,j} = [j \\neq 0]$. The transfer is simple too: $f_{i,j} = \\min\\limits_{0 \\leq k + a_i \\leq p} (f_{i-1,k} + [k + a_i \\neq j])$ It is possible to optimize the transfer to $\\mathcal O(np)$, since for each $j$, the contribution from at most one $k$ is special ($+0$). We can calculate the prefix and suffix $\\min$ for $f_{i-1}$ and it will be fast to get the dp array in the new row. Then, let's focus on optimizing it to $\\mathcal O(n)$. We call the set of $0 \\leq k \\leq p$ satisfying $0 \\leq k + a_i \\leq p$ as the legal interval of $i$ (denoted as $L_i$). It is concluded that the range of $f_{i, 0\\dots p}$ is at most $1$, and this can be proven by considering the transfer to each of the $j$ with the $k \\in L_i$ which has the least $f_{i-1, k}$. Let $v_i = \\min_{0 \\leq j \\leq p}(f_{i, j})$. We also have: for those $j$ with $f_{i,j} = v_i$, they form a consecutive segment in the integer field. Let the segment be covering $[l_i, r_i]$. Inductive proof. The essence of the transfer is that it shifts all the DP values $= v_{i-1}$ by $a_i$ unit length, and all the other numbers will be updated to $v_{i-1} + 1$. Then truncates the $j \\in ((-\\inf, 0) \\cup (p, +\\inf))$ part. The consecutive segment remains consecutive. Specially, if $[l_{i-1}, r_{i-1}] \\cap L_i = \\varnothing$, then $\\min_{k \\in L_i}(f_{i-1, k}) = v_{i-1} + 1$, hence we need to set $v_i = v_{i-1} + 1$, and $l_i, r_i$ as the range of $j = k + a_i$ in which $k \\in L_i$. Otherwise, $v_i = v_{i-1}$, and $l_i, r_i$ can be calculated by shifting $l_{i-1}, r_{i-1}$ by $a_i$ unit length. In fact, we only need to maintain three variables $l, r, v$ to represent the current consecutive segment and the current value field. Therefore, this problem can be easily solved in $\\mathcal O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nnamespace FastIO {\n\ttemplate <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }\n\ttemplate <typename T> inline void write(T x) { if (!x) return; write<T>(x / 10), putchar((x % 10) ^ '0'); }\n\ttemplate <typename T> inline void print(T x) { if (x > 0) write<T>(x); else if (x < 0) putchar('-'), write<T>(-x); else putchar('0'); }\n\ttemplate <typename T> inline void print(T x, char en) { print<T>(x), putchar(en); }\n}; using namespace FastIO;\n \n#define MAXN 3000001\nint a[MAXN];\nvoid solve() {\n\tint N = read<int>(); long long p = 0, l = 0, r = 0, v = 0;\n\tfor (int i = 1; i <= N; ++i) p += (a[i] = read<int>());\n\tfor (int i = 1; i <= N; ++i) if (a[i] >= 0) {\n\t\tl += a[i], r = std::min(r + a[i], p);\n\t\tif (l > r) ++v, l = a[i], r = p;\n\t} else {\n\t\ta[i] = -a[i];\n\t\tr -= a[i], l = std::max(l - a[i], 0ll);\n\t\tif (l > r) ++v, l = 0, r = p - a[i];\n\t}\n\tprint<int>(v + N + (int)(r != p), '\\n');\n}\nint main() { int T = read<int>(); while (T--) solve(); return 0; }",
    "tags": [
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2053",
    "index": "I2",
    "title": "Affectionate Arrays (Hard Version)",
    "statement": "\\textbf{Note that this statement is different to the version used in the official round. The statement has been corrected to a solvable version. In the official round, all submissions to this problem have been removed.}\n\n\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to compute the sum of value of different arrays. You can hack only if you solved all versions of this problem.}\n\nIris treasures an integer array $a_1, a_2, \\ldots, a_n$. She knows this array has an interesting property: the maximum absolute value of all elements is less than or equal to the sum of all elements, that is, $\\max(\\lvert a_i\\rvert) \\leq \\sum a_i$.\n\nIris defines the boredom of an array as its maximum subarray$^{\\text{∗}}$ sum.\n\nIris's birthday is coming, and Victor is going to send her another array $b_1, b_2, \\ldots, b_m$ as a gift. For some seemingly obvious reasons, he decides the array $b_1, b_2, \\ldots, b_m$ should have the following properties.\n\n- $a_1, a_2, \\ldots, a_n$ should be a subsequence$^{\\text{†}}$ of $b_1, b_2, \\ldots, b_m$.\n- The two arrays have the same sum. That is, $\\sum\\limits_{i=1}^n a_i = \\sum\\limits_{i=1}^m b_i$.\n- The boredom of $b_1, b_2, \\ldots, b_m$ is the smallest possible.\n- Among the arrays with the smallest boredom, the length of the array $b$ (i.e., $m$) is the smallest possible. And in this case, Iris will understand his regard as soon as possible!\n\nFor a possible array $b_1, b_2, \\ldots, b_m$ satisfying all the conditions above, Victor defines the value of the array as the \\textbf{number of occurrences} of array $a$ as subsequences in array $b$. That is, he counts the number of array $c_1, c_2, \\ldots, c_{n}$ that $1\\le c_1< c_2< \\ldots< c_n\\le m$ and for all integer $i$ that $1\\le i\\le n$, $b_{c_{i}}=a_i$ is satisfied, and let this be the value of array $b$.\n\nEven constrained as above, there are still too many possible gifts. So Victor asks you to \\textbf{calculate the sum of value of all possible arrays} $b_1, b_2, \\ldots, b_m$. Since the answer may be large, Victor only needs the number modulo $998\\,244\\,353$. He promises you: if you help him successfully, he will share a bit of Iris's birthday cake with you.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $c$ is a subarray of an array $d$ if $c$ can be obtained from $d$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\n$^{\\text{†}}$A sequence $c$ is a subsequence of a sequence $d$ if $c$ can be obtained from $d$ by the deletion of several (possibly, zero or all) element from arbitrary positions.\n\\end{footnotesize}",
    "tutorial": "Try insert numbers into spaces between the elements of $a$ (including the beginning and the end). Note that an array be can be formed in multiple ways (for example, you can insert a number $x$ to the left or right of the original number $x$ in array $a$). What's the number of different ways? It's actually the \"value\", that is, the number of occurrances of $a$. Use the fact that \"only one number can be inserted into each space\" to prove. Read the editorial for I1 and the hints first. According to the hint, you can count the number of ways to insert the new numbers into the space, so the dp and transitions are similar to those in problem I1. We can add an additional dp array, $g_{i, j}$ representing the number of different ways when everything meets the description of $f_{i, j}$. Let's see from which values it can be transferred: If $f_{i, j} = v_i$, then $f_{i, j}$ can only be transferred from $f_{i-1, j-a_i}$. That is, $g_{i, j} = g_{i-1, j-a_i}$. If $f_{i, j} = v_i + 1$, then $f_{i, j} = \\sum_{k \\in L_i, f_{i-1, k} = f_{i, j} - 1} g_{i-1, k}$. We can use some tags and a Deque to maintain the whole process, so the amortized time complexity is $\\mathcal O(n)$. Try to solve the initial problem: count the number of valid array $b$ for $n\\le 500$. Consider $f_{i,j,k}$: the number of ways to fill the first $i$ elements of $b$, which contains at most $j$ first elements from $a$ as a subsequence, and the sum of the first $i$ elements is $k$. Try to optimize this from $O(n^2s^2)$ to $O(n^2s)$, and then $O(\\rm{poly}(n))$, and then $O(n^3)$.",
    "code": "#include <bits/stdc++.h>\n \nnamespace FastIO {\n\ttemplate <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }\n\ttemplate <typename T> inline void write(T x) { if (!x) return; write<T>(x / 10), putchar((x % 10) ^ '0'); }\n\ttemplate <typename T> inline void print(T x) { if (x > 0) write<T>(x); else if (x < 0) putchar('-'), write<T>(-x); else putchar('0'); }\n\ttemplate <typename T> inline void print(T x, char en) { print<T>(x), putchar(en); }\n}; using namespace FastIO;\n \nconst int MOD = 998244353;\nnamespace Modint {\n\tinline int add(int x, int y) { return (x += y) >= MOD ? x - MOD : x; }\n\tinline int sub(int x, int y) { return x < y ? x - y + MOD : x - y; }\n\tinline int mul(int x, int y) { return 1ll * x * y % MOD; }\n\tinline int pow(int x, int y) { int r = 1; for (; y; y >>= 1, x = mul(x, x)) if (y & 1) r = mul(r, x); return r; }\n\tinline int inv(int x) { return pow(x, MOD - 2); }\n};\nstruct modint {\n\tint v;\n\tmodint (int x = 0) : v(x) { /* for debug only. assert(0 <= x && x < MOD); */ }\n\tinline int get() { return v; }\n\tmodint operator - () const { return v ? MOD - v : 0; }\n\tmodint operator + (const modint &k) const { return Modint::add(v, k.v); }\n\tmodint operator - (const modint &k) const { return Modint::sub(v, k.v); }\n\tmodint operator * (const modint &k) const { return Modint::mul(v, k.v); }\n\tmodint operator / (const modint &k) const { return Modint::mul(v, Modint::inv(k.v)); }\n\tmodint pow(const modint &k) const { return Modint::pow(v, k.v); }\n\tmodint inverse() const { return Modint::inv(v); }\n\tmodint operator += (const modint &k) { (v += k.v) >= MOD && (v -= MOD); return *this; }\n\tmodint operator -= (const modint &k) { (v -= k.v) < 0 && (v += MOD); return *this; }\n\tmodint operator *= (const modint &k) { return v = Modint::mul(v, k.v); }\n\tmodint operator /= (const modint &k) { return v = Modint::mul(v, Modint::inv(k.v)); }\n};\n \nstruct Node {\n\tint f; modint g; long long len;\n\tNode () {}\n\tNode (int F, int G, long long L) : f(F), g(G), len(L) {}\n\tNode (int F, modint G, long long L) : f(F), g(G), len(L) {}\n}; std::deque<Node> Q;\n \n#define MAXN 3000001\nint a[MAXN];\nvoid solve() {\n\tint N = read<int>(); long long p = 0, l = 0, r = 0, v = 0;\n\tfor (int i = 1; i <= N; ++i) p += (a[i] = read<int>());\n\tfor (int i = 1; i <= N; ++i) assert (std::abs(a[i]) <= p);\n\tQ.clear(); Q.push_back(Node(0, 1, 1)), Q.push_back(Node(1, 1, p));\n\tmodint gv = 1, gz = p % MOD, tv = 0, tz = 0;\n\tfor (int i = 1; i <= N; ++i) if (a[i] >= 0) {\n\t\tfor (long long ls = a[i]; ls > 0; ) {\n\t\t\tNode k = Q.back(); Q.pop_back();\n\t\t\tif (ls < k.len) Q.push_back(Node(k.f, k.g, k.len - ls)), k.len = ls;\n\t\t\t(k.f == v ? gv : gz) -= k.g * (k.len % MOD), ls -= k.len;\n\t\t}\n\t\tl += a[i], r = std::min(r + a[i], p);\n\t\tif (l > r) ++v, l = a[i], r = p, gv = gz, tv = tz, gz = tz = 0;\n\t\tgz += -tz * (a[i] >= MOD ? a[i] - MOD : a[i]);\n        if (a[i] > 0) Q.push_front(Node(v + 1, -tz, a[i]));\n        tz += gv + tv * ((r - l + 1) % MOD);\n\t} else if (a[i] < 0) {\n\t\ta[i] = -a[i];\n\t\tfor (long long ls = a[i]; ls > 0; ) {\n\t\t\tNode k = Q.front(); Q.pop_front();\n\t\t\tif (ls < k.len) Q.push_front(Node(k.f, k.g, k.len - ls)), k.len = ls;\n\t\t\t(k.f == v ? gv : gz) -= k.g * (k.len % MOD), ls -= k.len;\n\t\t}\n\t\tr -= a[i], l = std::max(l - a[i], 0ll);\n\t\tif (l > r) ++v, l = 0, r = p - a[i], gv = gz, tv = tz, gz = tz = 0;\n\t\tgz += -tz * (a[i] >= MOD ? a[i] - MOD : a[i]), Q.push_back(Node(v + 1, -tz, a[i])), tz += gv + tv * ((r - l + 1) % MOD);\n    }\n\tprint<int>((Q.back().g + (r == p ? tv : tz)).get(), '\\n');\n}\nint main() { int T = read<int>(); while (T--) solve(); return 0; }",
    "tags": [
      "data structures",
      "dp",
      "graphs",
      "greedy",
      "math",
      "shortest paths",
      "two pointers"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2055",
    "index": "A",
    "title": "Two Frogs",
    "statement": "\\begin{center}\n\\begin{tabular}{c}\n\\hline\n{\\small Roaming through the alligator-infested Everglades, Florida Man encounters a most peculiar showdown.} \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nThere are $n$ lilypads arranged in a row, numbered from $1$ to $n$ from left to right. Alice and Bob are frogs initially positioned on distinct lilypads, $a$ and $b$, respectively. They take turns jumping, starting with Alice.\n\nDuring a frog's turn, it can jump either one space to the left or one space to the right, as long as the destination lilypad exists. For example, on Alice's first turn, she can jump to either lilypad $a-1$ or $a+1$, provided these lilypads are within bounds. It is important to note that each frog \\textbf{must jump} during its turn and cannot remain on the same lilypad.\n\nHowever, there are some restrictions:\n\n- The two frogs cannot occupy the same lilypad. This means that Alice cannot jump to a lilypad that Bob is currently occupying, and vice versa.\n- If a frog cannot make a valid jump on its turn, it loses the game. As a result, the other frog wins.\n\nDetermine whether Alice can guarantee a win, assuming that both players play optimally. It can be proven that the game will end after a finite number of moves if both players play optimally.",
    "tutorial": "Look at the distance between the frogs. Notice that regardless of how the players move, the difference between the numbers of the lilypads the two players are standing on always alternates even and odd, depending on the starting configuration. Then, the key observation is that exactly one player has the following winning strategy: Walk towards the other player, and do not stop until they are forced onto lilypad $1$ or $n$. For instance, if Alice and Bob start on lilypads with the same parity, Bob cannot stop Alice from advancing towards him. This is because at the start of Alice's turn, she will always be able to move towards Bob due to their distance being even and therefore at least $2$, implying that there is a free lilypad for her to jump to. This eventually forces Bob into one of the lilypads $1, n$, causing him to lose. In the case that they start on lilypads with different parity, analogous logic shows that Bob wins. Therefore, for each case, we only need to check the parity of the lilypads for a constant time solution.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int T; cin >> T;\n    while (T--) {\n        int N, A, B; cin >> N >> A >> B;\n        if ((A ^ B) & 1) cout << \"NO\\n\";\n        else cout << \"YES\\n\";\n    }\n    cout.flush();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "games",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2055",
    "index": "B",
    "title": "Crafting",
    "statement": "\\begin{center}\n\\begin{tabular}{c}\n\\hline\n{\\small As you'd expect, Florida is home to many bizarre magical forces, and Florida Man seeks to tame them.} \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nThere are $n$ different types of magical materials, numbered from $1$ to $n$. Initially, you have $a_i$ units of material $i$ for each $i$ from $1$ to $n$. You are allowed to perform the following operation:\n\n- Select a material $i$ (where $1\\le i\\le n$). Then, spend $1$ unit of \\textbf{every} other material $j$ (in other words, $j\\neq i$) to gain $1$ unit of material $i$. More formally, after selecting material $i$, update array $a$ as follows: $a_i := a_i + 1$, and $a_j := a_j - 1$ for all $j$ where $j\\neq i$ and $1\\le j\\le n$. Note that all $a_j$ must remain non-negative, i.e. you cannot spend resources you do not have.\n\nYou are trying to craft an artifact using these materials. To successfully craft the artifact, you must have at least $b_i$ units of material $i$ for each $i$ from $1$ to $n$. Determine if it is possible to craft the artifact by performing the operation any number of times (including zero).",
    "tutorial": "The order of the moves is pretty much irrelevant. What happens if we try to make two different materials? The key observation is that we will never use the operation to craft two different types of materials $i, j$. This is because if we were to combine the net change in resources from these two operations, we would lose two units each of every material $k \\neq i, j$, and receive a net zero change in our amounts of materials $i, j$. Therefore, we will only ever use the operation on one type of material $i$. An immediate corollary of this observation is that we can only be deficient in at most one type of material, i.e. at most one index $i$ at which $a_i < b_i$. If no such index exists, the material is craftable using our starting resources. Otherwise, applying the operation $x$ times transforms our array to $a_j := \\begin{cases} a_j + x & \\text{if}\\ i = j \\\\ a_j - x & \\text{if}\\ i \\neq j \\end{cases}$ i.e. increasing element $a_i$ by $x$ and decreasing all other elements by $x$. We must have $x \\geq b_i - a_i$ to satisfy the requirement on material type $i$. However, there is also no point in making $x$ any larger, as by then we already have enough of type $i$, and further operations cause us to start losing materials from other types that we could potentially need to craft the artifact. Therefore, our condition in this case is just to check that $b_i - a_i \\leq \\min_{j \\neq i} a_j - b_j,$ i.e. we are deficient in type $i$ by at most as many units as our smallest surplus in all other material types $j \\neq i$. This gives an $O(n)$ solution.",
    "code": "// #include <ext/pb_ds/assoc_container.hpp>\n// #include <ext/pb_ds/tree_policy.hpp>\n// using namespace __gnu_pbds;\n// typedef tree<int, null_type, std::less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\n\n#include <bits/stdc++.h>\n\n#define f first\n#define s second\n#define pb push_back\n\ntypedef long long int ll;\ntypedef unsigned long long int ull;\nusing namespace std;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\n\ntemplate<typename T> int die(T x) { cout << x << endl; return 0; }\n\n#define mod_fft 998244353\n#define mod_nfft 1000000007\n#define INF 100000000000000\n#define LNF 1e15\n#define LOL 12345678912345719ll\n\nstruct LL {\n\n    static const ll m = mod_fft;\n    long long int val;\n\n    LL(ll v) {val=reduce(v);};\n    LL() {val=0;};\n    ~LL(){};\n    LL(const LL& l) {val=l.val;};\n    LL& operator=(int l) {val=l; return *this;}\n    LL& operator=(ll l) {val=l; return *this;}\n    LL& operator=(LL l) {val=l.val; return *this;}\n\n    static long long int reduce(ll x, ll md = m) {\n        x %= md;\n        while (x >= md) x-=md;\n        while (x < 0) x+=md;\n        return x;\n    }\n\n    bool operator<(const LL& b) { return val<b.val; }\n    bool operator<=(const LL& b) { return val<=b.val; }\n    bool operator==(const LL& b) { return val==b.val; }\n    bool operator>=(const LL& b) { return val>=b.val; }\n    bool operator>(const LL& b) { return val>b.val; }\n\n    LL operator+(const LL& b) { return LL(val+b.val); }\n    LL operator+(const ll& b) { return (*this+LL(b)); }\n    LL& operator+=(const LL& b) { return (*this=*this+b); }\n    LL& operator+=(const ll& b) { return (*this=*this+b); }\n\n    LL operator-(const LL& b) { return LL(val-b.val); }\n    LL operator-(const ll& b) { return (*this-LL(b)); }\n    LL& operator-=(const LL& b) { return (*this=*this-b); }\n    LL& operator-=(const ll& b) { return (*this=*this-b); }\n\n    LL operator*(const LL& b) { return LL(val*b.val); }\n    LL operator*(const ll& b) { return (*this*LL(b)); }\n    LL& operator*=(const LL& b) { return (*this=*this*b); }\n    LL& operator*=(const ll& b) { return (*this=*this*b); }\n\n    static LL exp(const LL& x, const ll& y){\n        ll z = y;\n        z = reduce(z,m-1);\n        LL ret = 1;\n        LL w = x;\n        while (z) {\n            if (z&1) ret *= w;\n            z >>= 1; w *= w;\n        }\n        return ret;\n    }\n    LL& operator^=(ll y) { return (*this=LL(val^y)); }\n\n    LL operator/(const LL& b) { return ((*this)*exp(b,-1)); }\n    LL operator/(const ll& b) { return (*this/LL(b)); }\n    LL operator/=(const LL& b) { return ((*this)*=exp(b,-1)); }\n    LL& operator/=(const ll& b) { return (*this=*this/LL(b)); }\n\n}; ostream& operator<<(ostream& os, const LL& obj) { return os << obj.val; }\n\nint N;\nvector<ll> segtree;\n\nvoid pull(int t) {\n    segtree[t] = max(segtree[2*t], segtree[2*t+1]);\n}\n\nvoid point_set(int idx, ll val, int L = 1, int R = N, int t = 1) {\n    if (L == R)  segtree[t] = val;\n    else {\n        int M = (L + R) / 2;\n        if (idx <= M) point_set(idx, val, L, M, 2*t);\n        else point_set(idx, val, M+1, R, 2*t+1);\n        pull(t);\n    }\n}\n\nll range_add(int left, int right, int L = 1, int R = N, int t = 1) {\n    if (left <= L && R <= right) return segtree[t];\n    else {\n        int M = (L + R) / 2;\n        ll ret = 0;\n        if (left <= M) ret = max(ret, range_add(left, right, L, M, 2*t));\n        if (right > M) ret = max(ret, range_add(left, right, M+1, R, 2*t+1));\n        return ret;\n    }\n}\n\nvoid build(vector<ll>& arr, int L = 1, int R = N, int t = 1) {\n    if (L == R)  segtree[t] = arr[L-1];\n    else {\n        int M = (L + R) / 2;\n        build(arr, L, M, 2*t);\n        build(arr, M+1, R, 2*t+1);\n        pull(t);\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int T = 1; cin >> T;\n    while (T--) {\n        int N; cin >> N;\n        vector<int> A(N), B(N);\n        for (int i = 0; i < N; i++) cin >> A[i];\n        int bad = -1, margin = 1e9, need = 0;\n        bool reject = 0;\n        for (int i = 0; i < N; i++) {\n            cin >> B[i];\n            if (A[i] < B[i]) {\n                if (bad != -1) reject = 1;\n                bad = i;\n                need = B[i] - A[i];\n            } else {\n                margin = min(margin, A[i] - B[i]);\n            }\n        }\n        if (reject) {\n            cout << \"NO\" << endl;\n            continue;\n        } else {\n            cout << ((margin >= need) ? \"YES\" : \"NO\") << endl;\n        }\n    }\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2055",
    "index": "C",
    "title": "The Trail",
    "statement": "\\begin{center}\n\\begin{tabular}{c}\n\\hline\n{\\small There are no mountains in Florida, and Florida Man cannot comprehend their existence. As such, he really needs your help with this one.} \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nIn the wilderness lies a region of mountainous terrain represented as a rectangular grid with $n$ rows and $m$ columns. Each cell in the grid is identified by its position $(i, j)$, where $i$ is the row index and $j$ is the column index. The altitude of cell $(i, j)$ is denoted by $a_{i,j}$.\n\nHowever, this region has been tampered with. A path consisting of $n + m - 1$ cells, starting from the top-left corner $(1, 1)$ and ending at the bottom-right corner $(n, m)$, has been cleared. For every cell $(i, j)$ along this path, the altitude $a_{i,j}$ has been set to $0$. The path moves strictly via downward ($\\mathtt{D}$) or rightward ($\\mathtt{R}$) steps.\n\nTo restore the terrain to its original state, it is known that the region possessed a magical property before it was tampered with: all rows and all columns shared the same sum of altitudes. More formally, there exists an integer $x$ such that $\\sum_{j=1}^m a_{i, j} = x$ for all $1\\le i\\le n$, and $\\sum_{i=1}^n a_{i, j} = x$ for all $1\\le j\\le m$.\n\nYour task is to assign new altitudes to the cells on the path such that the above magical property is restored. It can be proven that a solution always exists. If there are multiple solutions that satisfy the property, any one of them may be provided.",
    "tutorial": "Pick $x$, and find the sum of the whole grid. What does this tell you? Once you know $x$, the top left cell is fixed. What about the next cell on the trail? The naive solution of writing out a linear system and solving them will take $O((n + m)^3)$ time, which is too slow, so we will need a faster algorithm. We begin by selecting a target sum $S$ for each row and column. If we calculate the sum of all numbers in the completed grid, summing over rows gives a total of $S \\cdot n$ while summing over columns gives a total of $S \\cdot m$. Therefore, in order for our choice of $S$ to be possible, we require $S \\cdot n = S \\cdot m$, and since it is possible for $n \\neq m$, we will pick $S = 0$ for our choice to be possible in all cases of $n, m$. Notice that all choices $S \\neq 0$ will fail on $n \\neq m$, as the condition $S \\cdot n = S \\cdot m$ no longer holds. As such, $S = 0$ is the only one that will work in all cases. Now, we aim to make each row and column sum to $S$. The crux of the problem is the following observation: Denote $x_1, x_2, \\dots, x_{n+m-1}$ to be the variables along the path. Let's say variables $x_1, \\dots, x_{i-1}$ have their values set for some $1 \\leq i < n+m-1$. Then, either the row or column corresponding to variable $x_i$ has all of its values set besides $x_i$, and therefore we may determine exactly one possible value of $x_i$ to make its row or column sum to $0$. The proof of this claim is simple. At variable $x_i$, we look at the corresponding path move $s_i$. If $s_i = \\tt{R}$, then the path will never revisit the column of variable $x_i$, and its column will have no remaining unset variables since $x_1, \\dots, x_{i-1}$ are already set. Likewise, if $s_i = \\tt{D}$, then the path will never revisit the row of variable $x_i$, which can then be used to determine the value of $x_i$. Repeating this process will cause every row and column except for row $n$ and column $m$ to have a sum of zero, with $x_{n+m-1}$ being the final variable. However, we will show that we can use either the row or column to determine it, and it will give a sum of zero for both row $n$ and column $m$. WLOG we use row $n$. Indeed, if the sum of all rows and columns except for column $m$ are zero, we know that the sum of all entries of the grid is zero by summing over rows. However, we may then subtract all columns except column $m$ from this total to arrive at the conclusion that column $m$ also has zero sum. Therefore, we may determine the value of $x_{n+m-1}$ using either its row or column to finish our construction, giving a solution in $O(n \\cdot m)$.",
    "code": "#include <bits/stdc++.h>\n\n#define f first\n#define s second\n#define pb push_back\n\ntypedef long long int ll;\ntypedef unsigned long long int ull;\nusing namespace std;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\n\ntemplate<typename T> int die(T x) { cout << x << endl; return 0; }\n\n#define mod 1000000007\n#define INF 1000000000\n#define LNF 1e15\n#define LOL 12345678912345719ll\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int T; cin >> T;\n    while (T--) {\n        int N, M; cin >> N >> M;\n        string S; cin >> S;\n        vector<vector<ll>> A;\n        for (int i = 0; i < N; i++) {\n            A.push_back(vector<ll>(M));\n            for (int j = 0; j < M; j++) {\n                cin >> A[i][j];\n            }\n        }\n        int x = 0, y = 0;\n        for (char c : S) {\n            if (c == 'D') {\n                long long su = 0;\n                for (int i = 0; i < M; i++) {\n                    su += A[x][i];\n                }\n                A[x][y] = -su;\n                ++x;\n            } else {\n                long long su = 0;\n                for (int i = 0; i < N; i++) {\n                    su += A[i][y];\n                }\n                A[x][y] = -su;\n                ++y;\n            }\n        }\n        long long su = 0;\n        for (int i = 0; i < M; i++) {\n            su += A[N-1][i];\n        }\n        A[N-1][M-1] = -su;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < M; j++) {\n                cout << A[i][j] << \" \";\n            }\n            cout << endl;\n        }\n\n    }\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2055",
    "index": "D",
    "title": "Scarecrow",
    "statement": "\\begin{center}\n\\begin{tabular}{c}\n\\hline\n{\\small At his orange orchard, Florida Man receives yet another spam letter, delivered by a crow. Naturally, he's sending it back in the most inconvenient manner possible.} \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nA crow is sitting at position $0$ of the number line. There are $n$ scarecrows positioned at integer coordinates $a_1, a_2, \\ldots, a_n$ along the number line. These scarecrows have been enchanted, allowing them to move left and right at a speed of $1$ unit per second.\n\nThe crow is afraid of scarecrows and wants to stay at least a distance of $k$ ahead of the nearest scarecrow positioned \\textbf{at or before} it. To do so, the crow uses its teleportation ability as follows:\n\n- Let $x$ be the current position of the crow, and let $y$ be the largest position of a scarecrow such that $y \\le x$. If $x - y < k$, meaning the scarecrow is too close, the crow will instantly teleport to position $y + k$.\n\nThis teleportation happens instantly and continuously. The crow will keep checking for scarecrows positioned at or to the left of him and teleport whenever one gets too close (which could happen at non-integral times). Note that besides this teleportation ability, the crow will not move on its own.\n\nYour task is to determine the minimum time required to make the crow teleport to a position greater than or equal to $\\ell$, assuming the scarecrows move optimally to allow the crow to reach its goal. For convenience, you are asked to output \\textbf{twice the minimum time} needed for the crow to reach the target position $\\ell$. It can be proven that this value will always be an integer.\n\nNote that the scarecrows can start, stop, or change direction at any time (possibly at non-integral times).",
    "tutorial": "Should you ever change the order of scarecrows? What's the first thing that the leftmost scarecrow should do? What's the only way to save time? Think in terms of distances and not times. Look at the points where the crow \"switches over\" between scarecrows. Greedy. We make a few preliminary observations: (1) The order of scarecrows should never change, i.e no two scarecrows should cross each other while moving along the interval. (2) Scarecrow $1$ should spend the first $a_1$ seconds moving to position zero, as this move is required for the crow to make any progress and there is no point in delaying it. (3) Let's say that a scarecrow at position $p$ `has' the crow if the crow is at position $p + k$, and there are no other scarecrows in the interval $[p, p+k]$. A scarecrow that has the crow should always move to the right; in other words, all scarecrows that find themselves located to the left of the crow should spend all their remaining time moving to the right, as it is the only way they will be useful. (4) Let there be a scenario where at time $T$, scarecrow $i$ has the crow and is at position $x$, and another scenario at time $T$ where scarecrow $i$ also has the crow, but is at position $y \\geq x$. Then, the latter scenario is at least as good as the former scenario, assuming scarecrows numbered higher than $i$ are not fixed. (5) The only way to save time is to maximize the distance $d$ teleported by the crow. The second and fifth observations imply that the time spent to move the crow across the interval is $a_1 + \\ell - d$. Now, for each scarecrow $i$, define $b_i$ to be the position along the interval at which it begins to have the crow, i.e. the crow is transferred from scarecrow $i-1$ to $i$. For instance, in the second sample case the values of $b_i$ are $(b_1, b_2, b_3) = (0, 2.5, 4.5)$ The second observation above implies that $b_1 = 0$, and the first observation implies that $b_1 \\leq \\dots \\leq b_n$. Notice that we may express the distance teleported as $d = \\sum_{i=1}^{n} \\min(k, b_{i+1} - b_i)$ with the extra definition that $b_{n+1} = \\ell$. For instance, in the second sample case the distance teleported is $d = \\min(k, b_2 - b_1) + \\min(k, b_3 - b_2) + \\min(k, \\ell - b_3) = 2 + 2 + 0.5 = 4.5$ and the total time is $a_1 + \\ell - d = 2 + 5 - 4.5 = 2.5$. Now, suppose that $b_1, \\dots, b_{i-1}$ have been selected for some $2 \\leq i \\leq n$, and that time $T$ has elapsed upon scarecrow $i-1$ receiving the crow. We will argue the optimal choice of $b_i$. At time $T$ when scarecrow $i-1$ first receives the crow, scarecrow $i$ may be at any position in the interval $[a_i - T, \\min(a_i + T, \\ell)]$. Now, we have three cases. Case 1. $b_{i-1} + k \\leq a_i - T.$ In this case, scarecrow $i$ will need to move some nonnegative amount to the left in order to meet with scarecrow $i-1$. They will meet at the midpoint of the crow position $b_{i-1} + k$ and the leftmost possible position $a_i - T$ of scarecrow $i$ at time $T$. This gives $b_i := \\frac{a_i - T + b_{i-1} + k}{2}.$ Case 2. $a_i - T \\leq b_{i-1} + k \\leq a_i + T.$ Notice that if our choice of $b_i$ has $b_i < b_{i-1} + k$, it benefits us to increase our choice of $b_i$ (if possible) as a consequence of our fourth observation, since all such $b_i$ will cause an immediate transfer of the crow to scarecrow $i$ at time $T$. However, if we choose $b_i > b_{i-1} + k$, lowering our choice of $b_i$ is now better as it loses less potential teleported distance $\\min(k, b_i - b_{i-1})$, while leaving more space for teleported distance after position $b_i$. Therefore, we will choose $b_i := b_{i-1} + k$ in this case. Case 3. $a_i + T \\leq b_{i-1} + k.$ In this case, regardless of how we choose $b_i$, the crow will immediately transfer to scarecrow $i$ from scarecrow $i-1$ at time $T$. We might as well pick $b_i := a_i + T$. Therefore, the optimal selection of $b_i$ may be calculated iteratively as $b_i := \\min\\left(\\ell, \\overbrace{a_i + T}^{\\text{case 3}}, \\max\\left(\\overbrace{b_{i-1} + k}^{\\text{case 2}}, \\overbrace{\\frac{a_i - T + b_{i-1} + k}{2}}^{\\text{case 1}}\\right)\\right).$ It is now easy to implement the above approach to yield an $O(n)$ solution. Note that the constraints for $k, \\ell$ were deliberately set to $10^8$ instead of $10^9$ to make two times the maximum answer $4 \\cdot \\ell$ fit within $32$-bit integer types. It is not difficult to show that the values of $b_i$ as well as the answer are always integers or half-integers.",
    "code": "#include <bits/stdc++.h>\n\n#define f first\n#define s second\n#define pb push_back\n\ntypedef long long int ll;\ntypedef unsigned long long int ull;\nusing namespace std;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    int T; cin >> T;\n    while (T--) {\n        int N, k, l;\n        cin >> N >> k >> l;\n        double K = k;\n        double L = l;\n        vector<int> A(N);\n        for (int i = 0; i < N; i++) cin >> A[i];\n        double T = A[0];\n        double last_pt = 0;\n        double S = 0;\n        for (int i = 1; i < N; i++) {\n            double this_pt = min(L, min(A[i] + T,\n                                max(last_pt + K,\n                                    (A[i] - T + last_pt + K)/2.0)));\n            T += max(0.0, this_pt - last_pt - K);\n            S += min(K, this_pt - last_pt);\n            last_pt = this_pt;\n        }\n        S += min(K, L - last_pt);\n        cout << (int)round(2*(L - S + A[0])) << endl;\n    }\n    return 0;\n}\n",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2055",
    "index": "E",
    "title": "Haystacks",
    "statement": "\\begin{center}\n\\begin{tabular}{c}\n\\hline\n{\\small On the next new moon, the universe will reset, beginning with Florida. It's up to Florida Man to stop it, but he first needs to find an important item.} \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nThere are $n$ haystacks labelled from $1$ to $n$, where haystack $i$ contains $a_i$ haybales. One of the haystacks has a needle hidden beneath it, but you do not know which one. Your task is to move the haybales so that each haystack is emptied at least once, allowing you to check if the needle is hidden under that particular haystack.\n\nHowever, the process is not that simple. Once a haystack $i$ is emptied for the first time, it will be assigned a height limit and can no longer contain more than $b_i$ haybales. More formally, a move is described as follows:\n\n- Choose two haystacks $i$ and $j$. If haystack $i$ has not been emptied before, or haystack $i$ contains strictly less than $b_i$ haybales, you may move exactly $1$ haybale from haystack $j$ to haystack $i$.\n\n\\textbf{Note}: Before a haystack is emptied, it has no height limit, and you can move as many haybales as you want onto that haystack.\n\nCompute the minimum number of moves required to ensure that each haystack is emptied at least once, or report that it is impossible.",
    "tutorial": "Let's say you have to empty the haystacks in a fixed order. What's the best way to do it? Write the expression for the number of moves for a given order. In an optimal ordering, you should not gain anything by swapping two entries of the order. Using this, describe the optimal order. The constraint only limits what you can empty last. How can you efficiently compute the expression in Hint 2? Let's say we fixed some permutation $\\sigma$ of $1, \\dots, n$ such that we empty haystacks in the order $\\sigma_1, \\dots, \\sigma_n$. Notice that a choice of $\\sigma$ is possible if and only if the final stack $\\sigma_n$ can be cleared, which is equivalent to the constraint $a_{\\sigma_1} + \\dots + a_{\\sigma_n} \\leq b_{\\sigma_1} + \\dots + b_{\\sigma_{n-1}}.$ With this added constraint, the optimal sequence of moves is as follows: Iterate $i$ through $1, \\dots, n-1$. For each $i$, try to move its haybales to haystacks $1, \\dots, i-1$, and if they are all full then move haybales to haystack $n$. Once this process terminates, move all haystacks from $n$ back onto arbitrary haystacks $1, \\dots, n-1$, being careful to not overflow the height limits. The key observation is that the number of extra haybales that must be moved onto haystack $n$ is $\\max_{1 \\leq i \\leq n-1} \\left\\{\\sum_{j=1}^i a_{\\sigma_j} - \\sum_{j=1}^{i-1} b_{\\sigma_j}\\right\\}.$ To show this, consider the last time $i$ that a haybale is moved onto haystack $n$. At this time, all haybales from haystacks $1, \\dots, i$ have found a home, either on the height limited haystacks $1, \\dots, i-1$ or on haystack $n$, from which the identity immediately follows. Now, every haystack that wasn't moved onto haystack $n$ will get moved once, and every haystack that did gets moved twice. Therefore, our task becomes the following: Compute $\\sum_{i=1}^{n} a_i + \\min_{\\sigma} \\max_{1 \\leq i \\leq n-1} \\left\\{\\sum_{j=1}^i a_{\\sigma_j} - \\sum_{j=1}^{i-1} b_{\\sigma_j}\\right\\}$ for $\\sigma$ satisfying $a_{\\sigma_1} + \\dots + a_{\\sigma_n} \\leq b_{\\sigma_1} + \\dots + b_{\\sigma_{n-1}}.$ Notice that the $\\sum_{i=1}^n a_i$ term is constant, and we will omit it for the rest of this tutorial. We will first solve the task with no restriction on $\\sigma$ to gain some intuition. Denote $<_{\\sigma}$ the ordering of pairs $(a, b)$ corresponding to $\\sigma$. Consider adjacent pairs $(a_i, b_i) <_{\\sigma} (a_j, b_j)$. Then, if the choice of $\\sigma$ is optimal, it must not be better to swap their ordering, i.e. $\\begin{align*} \\overbrace{(a_i, b_i) <_{\\sigma} (a_j, b_j)}^{\\text{optimal}} \\implies& \\max(a_i, a_i + a_j - b_i) \\leq \\max(a_j, a_i + a_j - b_j) \\\\ \\iff& \\max(-a_j, -b_i) \\leq \\max(-a_i, -b_j)\\\\ \\iff& \\min(a_j, b_i) \\geq \\min(a_i, b_j). \\end{align*}$ As a corollary, there exists an optimal $\\sigma$ satisfying the following properties: Claim [Optimality conditions of $\\sigma$]. All pairs with $a_i < b_i$ come first. Then, all pairs with $a_i = b_i$ come next. Then, all pairs with $a_i > b_i$. The pairs with $a_i < b_i$ are in ascending order of $a_i$. The pairs with $a_i > b_i$ are in descending order of $b_i$. It is not hard to show that all such $\\sigma$ satisfying these properties are optimal by following similar logic as above. We leave it as an exercise for the reader. Now, we add in the constraint on the final term $\\sigma_n$ of the ordering. We will perform casework on this final haystack. Notice that for any fixed $a_n, b_n$, if $\\max_{1 \\leq i \\leq n-1} \\left\\{\\sum_{j=1}^i a_{\\sigma_j} - \\sum_{j=1}^{i-1} b_{\\sigma_j}\\right\\}$ is maximized, then so is $\\max_{1 \\leq i \\leq n} \\left\\{\\sum_{j=1}^i a_{\\sigma_j} - \\sum_{j=1}^{i-1} b_{\\sigma_j}\\right\\}.$ So, if we were to fix any last haystack $\\sigma_n$, the optimality conditions tell us that we should still order the remaining $n-1$ haystacks as before. Now, we may iterate over all valid $\\sigma_n$ and compute the answer efficiently as follows: maintain a segment tree with leaves representing pairs $(a_i, b_i)$ and range queries for $\\max_{1 \\leq i \\leq n} \\left\\{\\sum_{j=1}^i a_{\\sigma_j} - \\sum_{j=1}^{i-1} b_{\\sigma_j}\\right\\}.$ This gives an $O(n \\log n)$ solution. Note that it is possible to implement this final step using prefix and suffix sums to yield an $O(n)$ solution, but it is not necessary to do so.",
    "code": "#include <bits/stdc++.h>\n\n#define f first\n#define s second\n#define pb push_back\n\ntypedef long long int ll;\ntypedef unsigned long long int ull;\nusing namespace std;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\n\ntemplate<typename T> int die(T x) { cout << x << endl; return 0; }\n\n#define LNF 1e15\n\nint N;\nvector<pll> segtree;\n\npll f(pll a, pll b) {\n    return {max(a.first, a.second + b.first), a.second + b.second};\n}\n\nvoid pull(int t) {\n    segtree[t] = f(segtree[2*t], segtree[2*t+1]);\n}\n\nvoid point_set(int idx, pll val, int L = 1, int R = N, int t = 1) {\n    if (L == R) segtree[t] = val;\n    else {\n        int M = (L + R) / 2;\n        if (idx <= M) point_set(idx, val, L, M, 2*t);\n        else point_set(idx, val, M+1, R, 2*t+1);\n        pull(t);\n    }\n}\n\npll range_add(int left, int right, int L = 1, int R = N, int t = 1) {\n    if (left <= L && R <= right) return segtree[t];\n    else {\n        int M = (L + R) / 2;\n        pll ret = {0, 0};\n        if (left <= M) ret = f(ret, range_add(left, right, L, M, 2*t));\n        if (right > M) ret = f(ret, range_add(left, right, M+1, R, 2*t+1));\n        return ret;\n    }\n}\n\nvoid build(vector<pll>& arr, int L = 1, int R = N, int t = 1) {\n    if (L == R) segtree[t] = arr[L-1];\n    else {\n        int M = (L + R) / 2;\n        build(arr, L, M, 2*t);\n        build(arr, M+1, R, 2*t+1);\n        pull(t);\n    }\n}\n\nvector<int> theoretical(const vector<pii>& arr) {\n    vector<int> idx(arr.size());\n    for (int i = 0; i < arr.size(); ++i) {\n        idx[i] = i;\n    }\n\n    vector<int> ut, eq, lt;\n    for (int i = 0; i < arr.size(); ++i) {\n        if (arr[i].first < arr[i].second) {\n            ut.push_back(i);\n        } else if (arr[i].first == arr[i].second) {\n            eq.push_back(i);\n        } else {\n            lt.push_back(i);\n        }\n    }\n\n    sort(ut.begin(), ut.end(), [&arr](int i, int j) {\n        return arr[i].first < arr[j].first;\n    });\n\n    sort(eq.begin(), eq.end(), [&arr](int i, int j) {\n        return arr[i].first > arr[j].first;\n    });\n\n    sort(lt.begin(), lt.end(), [&arr](int i, int j) {\n        return arr[i].second > arr[j].second;\n    });\n\n    vector<int> result;\n    result.insert(result.end(), ut.begin(), ut.end());\n    result.insert(result.end(), eq.begin(), eq.end());\n    result.insert(result.end(), lt.begin(), lt.end());\n\n    return result;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    int T = 1; cin >> T;\n    while (T--) {\n        cin >> N;\n        vector<pll> data(N);\n        ll sum_a = 0;\n        ll sum_b = 0;\n        for (int i = 0; i < N; i++) {\n            cin >> data[i].f >> data[i].s;\n            sum_a += data[i].f;\n            sum_b += data[i].s;\n        }\n        vector<int> order = theoretical(vector<pii>(data.begin(), data.end()));\n\n        vector<pll> data_sorted;\n        for (int i : order) data_sorted.push_back({data[i].first, data[i].first - data[i].second});\n        data_sorted.push_back({0, 0});\n\n        ++N;\n\n        segtree = vector<pll>(4*N);\n        build(data_sorted);\n\n        ll ans = LNF;\n        for (int i = 0; i < N-1; i++) {\n            if (sum_b - (data_sorted[i].first - data_sorted[i].second) >= sum_a) {\n                point_set(i+1, data_sorted[N-1]);\n                point_set(N, data_sorted[i]);\n\n                ans = min(ans, range_add(1, N).first);\n\n                point_set(i+1, data_sorted[i]);\n                point_set(N, data_sorted[N-1]);\n            }\n        }\n        if (ans == LNF) cout << -1 << endl;\n        else cout << ans + sum_a << endl;\n    }\n}\n\n\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2055",
    "index": "F",
    "title": "Cosmic Divide",
    "statement": "\\begin{center}\n\\begin{tabular}{c}\n\\hline\n{\\small With the artifact in hand, the fabric of reality gives way to its true master — Florida Man.} \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nA polyomino is a connected$^{\\text{∗}}$ figure constructed by joining one or more equal $1 \\times 1$ unit squares edge to edge. A polyomino is convex if, for any two squares in the polyomino that share the same row or the same column, all squares between them are also part of the polyomino. Below are four polyominoes, only the first and second of which are convex.\n\nYou are given a convex polyomino with $n$ rows and an even area. For each row $i$ from $1$ to $n$, the unit squares from column $l_i$ to column $r_i$ are part of the polyomino. In other words, there are $r_i - l_i + 1$ unit squares that are part of the polyomino in the $i$-th row: $(i, l_i), (i, l_i + 1), \\ldots, (i, r_i-1), (i, r_i)$.\n\nTwo polyominoes are congruent if and only if you can make them fit exactly on top of each other by translating the polyominoes. \\textbf{Note that you are not allowed to rotate or reflect the polyominoes.} Determine whether it is possible to partition the given convex polyomino into two disjoint connected polyominoes that are congruent to each other. The following examples illustrate a valid partition of each of the two convex polyominoes shown above:\n\nThe partitioned polyominoes do not need to be convex, and each unit square should belong to exactly one of the two partitioned polyominoes.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A polyomino is connected if and only if for every two unit squares $u \\neq v$ that are part of the polyomino, there exists a sequence of distinct squares $s_1, s_2, \\ldots, s_k$, such that $s_1 = u$, $s_k = v$, $s_i$ are all part of the polyomino, and $s_i, s_{i+1}$ share an edge for each $1 \\le i \\le k - 1$.\n\\end{footnotesize}",
    "tutorial": "The results of the partition must be convex. Can you see why? The easier cases are when the polyomino must be cut vertically or horizontally. Let's discard those for now, and consider the \"diagonal cuts\". I.e. let one polyomino start from the top row, and another starting from some row $c$. WLOG the one starting on row $c$ is on the left side, we will check the other side by just duplicating the rest of the solution. Both sub-polyominoes are fixed if you choose $c$. But, it takes $O(n)$ time to check each one. Can you get rid of most $c$ with a quick check? Look at perimeters shapes, or area. Both will work. Assume there exists a valid partition of the polyomino. Note that the resulting congruent polyominoes must be convex, as it is not possible to join two non-overlapping non-convex polyominoes to create a convex one. Then, there are two cases: either the two resulting polyominoes are separated by a perfectly vertical or horizontal cut, or they share some rows. The first case is easy to check in linear time. The remainder of the solution will focus on the second case. Consider the structure of a valid partition. We will focus on the perimeter: Notice that the cut separating the two polyominoes must only ever move down and right, or up and right, as otherwise one of the formed polyominoes will not be convex. Without loss of generality, say it only goes down and right. In order for our cut to be valid, it must partition the perimeter into six segments as shown, such that the marked segments are congruent in the indicated orientations ($a$ with $a$, $b$ with $b$, $c$ with $c$.) If we label the horizontal lines of the grid to be $0, \\dots, n$ where line $i$ is located after row $i$, we notice that the division points along the left side of the original polyomino are located at lines $0, k, 2k$ for some $1 \\leq k \\leq n/2$. Notice that if we were to fix a given $k$, we can uniquely determine the lower polyomino from the first few rows of the upper polyomino. Indeed, if $a_i = r_i - \\ell_i + 1$ denotes the width of the $i$-th row of the original polyomino, we can show that the resulting polyomino for a particular choice of $k$ has $b_i = a_i - a_{i-k} + a_{i-2k} - \\dots$ cells in its $i$-th row, for $1 \\leq i \\leq n - k$. Therefore, iterating over all possible $k$ and checking them individually gives an $O(n^2)$ solution. To speed this up, we will develop a constant-time check that will prune ``most'' choices of $k$. Indeed, we may use prefix sums and hashing to verify the perimeter properties outlined above, so that we can find all $k$ that pass this check in $O(n)$ time. If there are at most $f(n)$ choices of $k$ afterwards, we can check them all for a solution in $O(n \\cdot (f(n) + \\text{hashing errors}))$. It can actually be shown that for our hashing protocol, $f(n) \\leq 9$, so that this algorithm has linear time complexity. While the proof is not difficult, it is rather long and will be left as an exercise. Instead, we will give a simpler argument to bound $f(n)$. Fix some choice of $k$, and consider the generating functions $A(x) = a_0 + a_1 x + \\dots + a_n x^n,$ $B(x) = b_0 + b_1 x + \\dots + b_{n-k} x^{n-k}.$ The perimeter conditions imply that $(1 + x^k) B(x) = A(x)$. In other words, $k$ may only be valid if $(1 + x^k)$ divides $A(x)$. Therefore, we can use cyclotomic polynomials for $1 + x^k \\mid x^{2k} - 1$ to determine that $f(n) \\leq \\text{maximum number of cyclotomic polynomials that can divide a degree}\\ n\\ \\text{polynomial}.$ As the degree of the $k$-th cyclotomic polynomial is $\\phi(k)$ for the Euler totient function $\\phi$, we can see that $f(n)$ is also at most the maximum number of $k_i \\leq n$ we can select with $\\sum_i \\phi(k_i) \\leq n$. Since $\\phi(n) \\geq \\frac{n}{\\log \\log n}$, this tells us that $f(n) = O(\\sqrt n \\cdot \\log \\log n)$ and this looser bound already yields a time complexity of at most $O(n \\sqrt n \\cdot \\log \\log n).$ While this concludes the official solution, there exist many other heuristics with different $f(n)$ that also work. It is in the spirit of the problem to admit many alternate heuristics that give small enough $f(n)$ ``in practice'', as the official solution uses hashing. One such heuristic found by testers is as follows: We take as our pruning criteria that the area of the subdivided polyomino $\\sum_{i=1}^{n-k} b_i$ is exactly half of the area of the original polyomino, which is $\\sum_{i=1}^n a_i$. Algebraically manipulating $\\sum_{i=1}^{n-k} b_i$ to be a linear function of $a_i$ shows it to be equal to $(a_1 + \\dots + a_k) - (a_{k+1} + \\dots + a_{2k}) + \\dots.$ The calculation of all these sums may be sped up with prefix sums, and therefore pruning of $k$, can be done in amortized $O(n \\log n)$ time since any fixed choice of $k$ has $\\frac nk$ segments. However, for this choice of pruning, it can actually be shown that $f(n) \\geq \\Omega(d(n))$, where $d(n)$ is the number of divisors of $n$. This lower bound is obtained at an even-sized diamond polyomino, e.g. $(a_1, \\dots, a_n) = (2, 4, \\dots, n, n, \\dots, 4, 2).$ Despite our efforts, we could not find an upper bound on $f(n)$ in this case, though we suspect that if it were not for the integrality and bounding constraints $a_i \\in {1, \\dots, 10^9}$, then $f(n) = \\Theta(n)$, with suitable choices of $a_i$ being found using linear programs. Nevertheless, the solution passes our tests, and we suspect that no countertest exists (though hacking attempts on such solutions would be interesting to see!).",
    "code": "#include <bits/stdc++.h>\n\n#define f first\n#define s second\n\ntypedef long long int ll;\ntypedef unsigned long long int ull;\nusing namespace std;\ntypedef pair<int,int> pii;\ntypedef pair<ll,ll> pll;\n\nvoid print_set(vector<int> x) {\n    for (auto i : x) {\n        cout << i << \" \";\n    }\n    cout << endl;\n}\n\nvoid print_set(vector<ll> x) {\n    for (auto i : x) {\n        cout << i << \" \";\n    }\n    cout << endl;\n}\n\nbool connected(vector<ll> &U, vector<ll> &D) {\n    if (U[0] > D[0]) return 0;\n    for (int i = 1; i < U.size(); i++) {\n        if (U[i] > D[i]) return 0;\n        if (D[i] < U[i-1]) return 0;\n        if (U[i] > D[i-1]) return 0;\n    }\n    return 1;\n}\n\nbool compare(vector<ll> &U1, vector<ll> &D1, vector<ll> &U2, vector<ll> &D2) {\n    if (U1.size() != U2.size()) return 0;\n    if (!connected(U1, D1)) return 0;\n    for (int i = 0; i < U1.size(); i++) {\n        if (U1[i] - D1[i] != U2[i] - D2[i]) return 0;\n        if (U1[i] - U1[0] != U2[i] - U2[0]) return 0;\n    }\n    return 1;\n}\n\nbool horizontal_check(vector<ll>& U, vector<ll>& D) {\n    if (U.size() % 2) return 0;\n    int N = U.size() / 2;\n    auto U1 = vector<ll>(U.begin(), U.begin() + N);\n    auto D1 = vector<ll>(D.begin(), D.begin() + N);\n    auto U2 = vector<ll>(U.begin() + N, U.end());\n    auto D2 = vector<ll>(D.begin() + N, D.end());\n    return compare(U1, D1, U2, D2);\n}\n\nbool vertical_check(vector<ll>& U, vector<ll>& D) {\n    vector<ll> M1, M2;\n    for (int i = 0; i < U.size(); i++) {\n        if ((U[i] + D[i]) % 2 == 0) return 0;\n        M1.push_back((U[i] + D[i]) / 2);\n        M2.push_back((U[i] + D[i]) / 2 + 1);\n    }\n    return compare(U, M1, M2, D);\n}\n\nll base = 2;\nll inv = 1000000006;\nll mod = 2000000011;\n\nvector<ll> base_pows;\nvector<ll> inv_pows;\nvoid precompute_powers() {\n    base_pows.push_back(1);\n    inv_pows.push_back(1);\n    for (int i = 1; i <= 300000; i++) {\n        base_pows.push_back(base_pows.back() * base % mod);\n        inv_pows.push_back(inv_pows.back() * inv % mod);\n    }\n}\n\nll sub(vector<ll> &hash_prefix, int a1, int b1) {\n    return ((mod + hash_prefix[b1] - hash_prefix[a1]) * inv_pows[a1]) % mod;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n\n    precompute_powers();\n\n    int T; cin >> T;\n    while (T--) {\n        int N; cin >> N;\n        vector<ll> U(N), D(N), H(N);\n        vector<pii> col_UL(N), col_DR(N+1);\n        vector<ll> hash_prefix_U(N), hash_prefix_D(N);\n        for (int i = 0; i < N; i++) {\n            cin >> U[i] >> D[i];\n            H[i] = D[i] - U[i] + 1;\n            col_UL[i] = {i,U[i]};\n            col_DR[i] = {i+1,D[i]+1};\n        }\n\n        // hashing\n        for (int i = 1; i < N; i++) {\n            hash_prefix_U[i] = (((mod + U[i] - U[i-1]) * base_pows[i-1])\n                                + hash_prefix_U[i-1]) % mod;\n        }\n\n        for (int i = 1; i < N; i++) {\n            hash_prefix_D[i] = (((mod + D[i] - D[i-1]) * base_pows[i-1])\n                                + hash_prefix_D[i-1]) % mod;\n        }\n\n        // horizontal split\n        if (horizontal_check(U, D)) {\n            cout << \"YES\" << endl;\n            goto next;\n        }\n\n        // vertical split\n        if (vertical_check(U, D)) {\n            cout << \"YES\" << endl;\n            goto next;\n        }\n\n        for (int _ = 0; _ < 2; _++) {\n            // down-right split\n            for (int c = 1; c <= N/2; c++) {\n                // check upper portion\n                if (sub(hash_prefix_U, 0, c-1) != sub(hash_prefix_U, c, 2*c-1)) continue;\n                if (H[0] - U[2*c] + U[2*c-1] != U[c-1] - U[c]) continue;\n\n                // check lower portion\n                if (sub(hash_prefix_D, N-c, N-1) != sub(hash_prefix_D, N-2*c, N-c-1)) continue;\n                if (H[N-1] + D[N-2*c-1] - D[N-2*c] != D[N-c-1] - D[N-c]) continue;\n\n                // check main portion\n                if (sub(hash_prefix_U, 2*c, N-1) != sub(hash_prefix_D, 0, N-2*c-1)) continue;\n\n                // brute force section\n                // polynomial division\n                bool ok = 1;\n                vector<ll> H_copy(H.begin(), H.end());\n                vector<ll> quotient(N);\n\n                // calculate quotient\n                for (int i = 0; i < N-c; i++) {\n                    quotient[i] = H_copy[i];\n                    H_copy[i+c] -= H_copy[i];\n                    if (quotient[i] < 0) ok = 0;\n                }\n\n                // check for no remainder\n                for (int i = N-c; i < N; i++) if (H_copy[i]) ok = 0;\n                if (!ok) continue;\n\n                // construct subdivision\n                vector<ll> U1, D1, U2, D2;\n                for (int i = c; i < N; i++) {\n                    int ref_height = quotient[i-c];\n                    U1.push_back(D[i-c] - ref_height + 1);\n                    D1.push_back(D[i-c]);\n                    U2.push_back(U[i]);\n                    D2.push_back(U[i] + ref_height - 1);\n                }\n\n                if (compare(U1, D1, U2, D2)) {\n                    cout << \"YES\" << endl;\n                    goto next;\n                }\n            }\n\n            // flip and go again!\n            swap(hash_prefix_U, hash_prefix_D);\n            swap(U, D);\n            for (int i = 0; i < N; i++) {\n                U[i] = -U[i];\n                D[i] = -D[i];\n            }\n        }\n        cout << \"NO\" << endl;\n        next:;\n    }\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "geometry",
      "hashing",
      "math",
      "strings"
    ],
    "rating": 3200
  },
  {
    "contest_id": "2056",
    "index": "A",
    "title": "Shape Perimeter",
    "statement": "There is an $m$ by $m$ square stamp on an infinite piece of paper. Initially, the bottom-left corner of the square stamp is aligned with the bottom-left corner of the paper. You are given two integer sequences $x$ and $y$, each of length $n$. For each step $i$ from $1$ to $n$, the following happens:\n\n- Move the stamp $x_i$ units to the right and $y_i$ units upwards.\n- Press the stamp onto the paper, leaving an $m$ by $m$ colored square at its current position.\n\n\\textbf{Note that the elements of sequences $x$ and $y$ have a special constraint: $1\\le x_i, y_i\\le m - 1$.}\n\nNote that you \\textbf{do not} press the stamp at the bottom-left corner of the paper. Refer to the notes section for better understanding.\n\nIt can be proven that after all the operations, the colored shape on the paper formed by the stamp is a single connected region. Find the perimeter of this colored shape.",
    "tutorial": "Look at the picture. I mean, look at the picture. Consider coordinates $x$ and $y$ separately. Consider coordinates $x$ and $y$ separately. Since $1 \\le x_i, y_i \\le m - 1$, after each step both coordinates increase and remain connected with the previous square. From the picture we can see that each coordinate spans from the bottom-left corner of the first square to the top-right corner of the last square. To calculate the perimeter we can add the length of that interval for both coordinates and multiply it by $2$, as it is counted in the perimeter twice, going in both directions: The coordinates of the bottom-left corner of the first square are $(x_1, y_1)$ and of the top-right corner of the last square are $(m + \\sum\\limits_{i = 1}^n x_i, m + \\sum\\limits_{i = 1}^n y_i)$. The lengths of the intervals are $m + \\sum\\limits_{i = 2}^n x_i$ and $m + \\sum\\limits_{i = 2}^n y_i$. Therefore, the answer is $2(2m + \\sum\\limits_{i = 2}^n (x_i + y_i))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> x(n), y(n);\n    for(int i = 0; i < n; i++) {\n        cin >> x[i] >> y[i];\n    }\n    int ans = 2 * (accumulate(x.begin(), x.end(), 0) + m - x[0] + accumulate(y.begin(), y.end(), 0) + m - y[0]);\n    cout << ans << '\\n';\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int ttt = 1;\n    cin >> ttt;\n    while(ttt--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2056",
    "index": "B",
    "title": "Find the Permutation",
    "statement": "You are given an undirected graph with $n$ vertices, labeled from $1$ to $n$. This graph encodes a hidden permutation$^{\\text{∗}}$ $p$ of size $n$. The graph is constructed as follows:\n\n- For every pair of integers $1 \\le i < j \\le n$, an undirected edge is added between vertex $p_i$ and vertex $p_j$ if and only if $p_i < p_j$. Note that the edge \\textbf{is not added} between vertices $i$ and $j$, but between the vertices of their respective elements. Refer to the notes section for better understanding.\n\nYour task is to reconstruct and output the permutation $p$. It can be proven that permutation $p$ can be uniquely determined.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "\"It can be proven that permutation $p$ can be uniquely determined\" This means that there is an order of elements. How to determine whether $x$ should be earlier in that order than $y$? Consider two elements $x < y$. Suppose their positions in $p$ are $i$ and $j$ correspondigly. How can we determine if $i < j$? If $i < j$ and $x < y$, we will have $g_{x, y} = g_{y, x} = 1$. Otherwise, $i > j$ and $x < y$, so $g_{x, y} = g_{y, x} = 0$. So if $g_{x, y} = 1$, we know that $i < j$, otherwise $i > j$. That way we can determine for each pair of elements which one of them should appear earlier in the permutation. Notice that this is just a definition of a comparator, which proves that the permutation is indeed unique. We can find it by sorting $p = [1, 2, \\ldots, n]$ with that comparator.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<string> g(n);\n    for(auto &i : g) {\n        cin >> i;\n    }\n    vector<int> p(n);\n    iota(p.begin(), p.end(), 0);\n    sort(p.begin(), p.end(),\n    [&](int x, int y) {\n        if(g[x][y] == '1') return x < y;\n        else return x > y;\n    });\n    for(auto i : p) cout << i + 1 << \" \"; cout << '\\n';\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int ttt = 1;\n    cin >> ttt;\n    while(ttt--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "graphs",
      "implementation",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2056",
    "index": "C",
    "title": "Palindromic Subsequences",
    "statement": "For an integer sequence $a = [a_1, a_2, \\ldots, a_n]$, we define $f(a)$ as the length of the longest subsequence$^{\\text{∗}}$ of $a$ that is a palindrome$^{\\text{†}}$.\n\nLet $g(a)$ represent the number of subsequences of length $f(a)$ that are palindromes. In other words, $g(a)$ counts the number of palindromic subsequences in $a$ that have the maximum length.\n\nGiven an integer $n$, your task is to find any sequence $a$ of $n$ integers that satisfies the following conditions:\n\n- $1 \\le a_i \\le n$ for all $1 \\le i \\le n$.\n- $g(a) > n$\n\nIt can be proven that such a sequence always exists under the given constraints.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) element from arbitrary positions.\n\n$^{\\text{†}}$A palindrome is a sequence that reads the same from left to right as from right to left. For example, $[1, 2, 1, 3, 1, 2, 1]$, $[5, 5, 5, 5]$, and $[4, 3, 3, 4]$ are palindromes, while $[1, 2]$ and $[2, 3, 3, 3, 3]$ are not.\n\\end{footnotesize}",
    "tutorial": "Analyze the example with $n = 6$. If $[a_1, a_2, \\ldots, a_k, a_{n - k + 1}, a_{n - k + 2}, \\ldots, a_n]$ is a palindrome, then $[a_1, a_2, \\ldots, a_k, a_i, a_{n - k + 1}, a_{n - k + 2}, \\ldots, a_n]$ is also a palindrome for all $k < i < n - k + 1$. If $[a_1, a_2, \\ldots, a_k, a_{n - k + 1}, a_{n - k + 2}, \\ldots, a_n]$ is a palindrome, then $[a_1, a_2, \\ldots, a_k, a_i, a_{n - k + 1}, a_{n - k + 2}, \\ldots, a_n]$ is also a palindrome for all $k < i < n - k + 1$, because we make it's length odd and add $a_i$ to the middle. We can use this to create a sequence with a big value of $g$. However, we shouldn't create a palindrome of a greater length than $2k + 1$ by using the fact above. That make us try something like $a = [1, 2, 3, \\ldots, n - 2, 1, 2]$. $f(a) = 3$ here, and any of $[a_1, a_i, a_{n - 1}]$ for $1 < i < n - 1$ and $[a_2, a_i, a_n]$ for $2 < i < n$ are palindromes, which means that $g(a) = 2(n - 3) = 2n - 6$. This construction works for $n \\ge 7$, so we have to handle $n = 6$ separately. We can also use the construction from the example with $n = 6$ directly: $a = [1, 1, 2, 3, 4, \\ldots, n - 3, 1, 2]$, which has $g(a) = 3n - 11$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    if (n == 6) {\n        cout << \"1 1 2 3 1 2\\n\";\n    }\n    else if(n == 9) {\n        cout << \"7 3 3 7 5 3 7 7 3\\n\";\n    }\n    else if(n == 15) {\n        cout << \"15 8 8 8 15 5 8 1 15 5 8 15 15 15 8\\n\";\n    }\n    else {\n        for(int i = 1; i <= n - 2; i++) cout << i << \" \"; cout << \"1 2\\n\";\n    }\n}\n\n\nsigned main() {\n    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int ttt = 1;\n    cin >> ttt;\n    while(ttt--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2056",
    "index": "D",
    "title": "Unique Median",
    "statement": "An array $b$ of $m$ integers is called good if, \\textbf{when it is sorted}, $b_{\\left\\lfloor \\frac{m + 1}{2} \\right\\rfloor} = b_{\\left\\lceil \\frac{m + 1}{2} \\right\\rceil}$. In other words, $b$ is good if both of its medians are equal. In particular, $\\left\\lfloor \\frac{m + 1}{2} \\right\\rfloor = \\left\\lceil \\frac{m + 1}{2} \\right\\rceil$ when $m$ is odd, so $b$ is guaranteed to be good if it has an odd length.\n\nYou are given an array $a$ of $n$ integers. Calculate the number of good subarrays$^{\\text{∗}}$ in $a$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $x$ is a subarray of an array $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "Solve the problem when $a_i \\le 2$. Assign $b_i = 1$ if $a_i = 2$ and $b_i = -1$ if $a_i = 1$ and calculate the number of bad subarrays. Extend this solution for $a_i \\le 10$, however, you need to take overcounting into account. When is a subarray $a[l, r]$ not good? If $r - l + 1$ is odd, $a[l, r]$ can't be bad. Otherwise, suppose the median of $a[l, r]$ is $x$. Then there need to be exactly $\\frac{r - l + 1}{2}$ elements in $a[l, r]$ that are $\\le x$ and exactly $\\frac{r - l + 1}{2}$ that are $> x$. This gives us an idea to calculate the number of bad subarrays with a median of $x$. Create another array $b$ of size $n$, where $b_i = -1$ if $a_i \\le x$ and $b_i = 1$ otherwise. $a[l, r]$, which has a median of $x$, is bad if and only if $\\sum\\limits_{i = l}^r b_i = 0$ and $r - l + 1$ is even. Notice that the second condition is not needed, as the sum of an odd length subarray of $b$ is always odd, so it can't be zero. Therefore, $a[l, r]$ with a median of $x$ is bad iff $\\sum\\limits_{i = l}^r b_i = 0$. If there is no $x$ in $[l, r]$, then the median of $a[l, r]$ trivially can't be equal to $x$. If there is an occurrence of $x$ in $a[l, r]$ and $\\sum\\limits_{i = l}^r b_i = 0$, notice that the median of $a[l, r]$ will always be exactly $x$. This is true because $\\frac{r - l + 1}{2}$ smallest elements of $a[l, r]$ are all $\\le x$, and there is an occurrence of $x$, so $\\frac{r - l + 1}{2}$-th smallest element must be $x$. This allows us to simply count the number of subarrays of $b$ with a sum of $0$ and with an occurrence of $x$ to count the number of bad subarrays with median $x$. We can subtract that value from $\\frac{n(n + 1)}{2}$ for all $x$ between $1$ and $A = 10$ to solve the problem in $O(nA)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int MAX = 11;\n\nint main() {\n    int tests;\n    cin >> tests;\n    for(int test = 0; test < tests; test++) {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for(auto &i : a) {\n            cin >> i;\n        }\n        long long ans = 0;\n        for(int x = 1; x < MAX; x++) {\n            vector<int> b(n);\n            for(int i = 0; i < n; i++) {\n                b[i] = (a[i] > x? 1 : -1);\n            }\n            int sum = n;\n            vector<int> pref(n);\n            for(int i = 0; i < n; i++) {\n                pref[i] = sum;\n                sum += b[i];\n            }\n            vector<int> cnt(2 * n + 1);\n            sum = n;\n            int j = 0;\n            for(int i = 0; i < n; i++) {\n                if(a[i] == x) {\n                    while(j <= i) {\n                        cnt[pref[j]]++;\n                        j++;\n                    }\n                }\n                sum += b[i];\n                ans += cnt[sum];\n            }\n        }\n        ans = 1ll * n * (n + 1) / 2 - ans;\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "data structures",
      "divide and conquer",
      "dp"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2056",
    "index": "E",
    "title": "Nested Segments",
    "statement": "A set $A$ consisting of pairwise distinct segments $[l, r]$ with integer endpoints is called good if $1\\le l\\le r\\le n$, and for any pair of distinct segments $[l_i, r_i], [l_j, r_j]$ in $A$, exactly one of the following conditions holds:\n\n- $r_i < l_j$ or $r_j < l_i$ (the segments do not intersect)\n- $l_i \\le l_j \\le r_j \\le r_i$ or $l_j \\le l_i \\le r_i \\le r_j$ (one segment is fully contained within the other)\n\nYou are given a good set $S$ consisting of $m$ pairwise distinct segments $[l_i, r_i]$ with integer endpoints. You want to add as many additional segments to the set $S$ as possible while ensuring that set $S$ remains good.\n\nSince this task is too easy, you need to determine the number of different ways to add the maximum number of additional segments to $S$, ensuring that the set remains good. Two ways are considered different if there exists a segment that is being added in one of the ways, but not in the other.\n\nFormally, you need to find the number of good sets $T$ of distinct segments, such that $S$ is a subset of $T$ and $T$ has the maximum possible size. Since the result might be very large, compute the answer modulo $998\\,244\\,353$.",
    "tutorial": "Forget about counting. What is the maximum size of $T$ if $m = 0$? It is $2n - 1$. What if $m$ isn't $0$? It is still $2n - 1$. To prove this represent a good set as a forest. We can always add $[1, n]$ and $[i, i]$ for all $1 \\le i \\le n$ to $S$. Now the tree of $S$ has exactly $n$ leaves. What if a vertex has more than $2$ children? What is the number of solutions when $m = 0$? It is the number of full binary trees with $n$ leaves, which is $C_{n - 1}$, where $C$ denotes the Catalan's sequence. Extend this idea to count the number of solutions for a general tree of $S$. Any good set has a tree-like structure. Specifically, represent $S$ as a forest the following way: segment $[l, r]$ has a parent $[L, R]$ iff $[l, r] \\in [L, R]$ and $R - L + 1$ is minimized (its parent is the shortest interval in which it lies). This segment is unique (or does not exist), because there can't be two segments with minimum length that cover $[l, r]$, as they would partially intersect otherwise. Notice that we can always add $[1, n]$ and $[i, i]$ for all $1 \\le i \\le n$ if they aren't in $S$ yet. Now the forest of $S$ is a tree with exactly $n$ leaves. Suppose $[L, R]$ has $k$ children $[l_1, r_1], [l_2, r_2], \\ldots, [l_k, r_k]$. If $k > 2$, we can always add $[l_1, r_2]$ to $S$, which decreases the number of children of $[L, R]$ by $1$ and increases the size of $S$ by $1$. Therefore, in the optimal solution each segment has at most $2$ children. Having exactly one child is impossible, as we have added all $[i, i]$, so every index of $[L, R]$ is covered by its children. This means that we have a tree where each vertex has either $0$ or $2$ children, which is a full binary tree. We have $n$ leaves, and every full binary tree with $n$ leaves has exactly $2n - 1$ vertices, so this is always the optimal size of $T$ regardless of $S$. To count the number of $T$, notice that when $m = 0$ the answer is the number of full binary trees with $n$ leaves, which is $C_{n - 1}$, where $C$ denotes the Catalan's sequence. To extend this to a general tree, we can add $[1, n]$ and $[i, i]$ for all $1 \\le i \\le n$ to $S$. Now suppose $[L, R]$ has $k \\ge 2$ children $[l_1, r_1], [l_2, r_2], \\ldots, [l_k, r_k]$. We need to merge some children. We can treat $[l_1, r_1]$ as $[1, 1]$, $[l_2, r_2]$ as $[2, 2]$, etc. This is now the same case as $m = 0$, so there are $C_{k - 1}$ ways to merge children of $[L, R]$. Each vertex is independent of each other, so the answer is $\\prod C_{c_v - 1}$ over all non-leaves $v$, where $c_v$ is the number of children of $v$. We can construct the tree in $O(n \\log n)$ by definition or in $O(n)$ using a stack.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int mod = 998244353;\nconst int MAX = 4e5 + 42;\n\nint fact[MAX], inv[MAX], inv_fact[MAX];\n\nint C(int n, int k) {\n    if(n < k || k < 0) return 0;\n    return (long long) fact[n] * inv_fact[k] % mod * inv_fact[n - k] % mod;\n}\n\nint Cat(int n) {\n    return (long long) C(2 * n, n) * inv[n + 1] % mod;\n}\n\nint binpow(int x, int n) {\n    int ans = 1;\n    while(n) {\n        if(n & 1) ans = (long long) ans * x % mod;\n        n >>= 1;\n        x = (long long) x * x % mod;\n    }\n    return ans;\n}\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    int initial_m = m;\n    vector<pair<int, int>> a(m);\n    for(auto &[l, r] : a) {\n        cin >> l >> r;\n    }\n    bool was_full = 0;\n    vector<int> was_single(n + 1);\n    for(auto [l, r] : a) was_full |= (r - l + 1 == n);\n    for(auto [l, r] : a) {\n        if(l == r) was_single[l] = 1;\n    }\n    if(!was_full) {\n        a.push_back({1, n});\n        m++;\n    }\n    for(int i = 1; i <= n; i++) {\n        if(!was_single[i] && n != 1) {\n            a.push_back({i, i});\n            m++;\n        }\n    }\n    for(auto &[l, r] : a) r = -r;\n    sort(a.begin(), a.end());\n    vector<int> deg(m);\n    for(int i = 0; i < m; i++) {\n        int j = i + 1;\n        while(j < m) {\n            if(-a[i].second < a[j].first) break;\n            deg[i]++;\n            j = upper_bound(a.begin(), a.end(), make_pair(-a[j].second, 1)) - a.begin();\n        }\n    }\n    for(auto &[l, r] : a) r = -r;\n    int ans = 1;\n    for(int i = 0; i < m; i++) {\n        if(deg[i] > 0) {\n            assert(deg[i] >= 2);\n            ans = (long long) ans * Cat(deg[i] - 1) % mod;\n        }\n    }\n    cout << ans << '\\n';\n}\n\nsigned main() {\n    fact[0] = 1;\n    for(int i = 1; i < MAX; i++) fact[i] = (long long) fact[i - 1] * i % mod;\n    inv_fact[MAX - 1] = binpow(fact[MAX - 1], mod - 2);\n    for(int i = MAX - 1; i; i--) inv_fact[i - 1] = (long long) inv_fact[i] * i % mod;\n    assert(inv_fact[0] == 1);\n    for(int i = 1; i < MAX; i++) inv[i] = (long long) inv_fact[i] * fact[i - 1] % mod;\n    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int ttt = 1;\n    cin >> ttt;\n    while(ttt--) {\n        solve();\n    }\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "dsu",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2056",
    "index": "F2",
    "title": "Xor of Median (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, the constraints on $t$, $k$, and $m$ are higher. You can hack only if you solved all versions of this problem.}\n\nA sequence $a$ of $n$ integers is called good if the following condition holds:\n\n- Let $\\text{cnt}_x$ be the number of occurrences of $x$ in sequence $a$. For all pairs $0 \\le i < j < m$, at least one of the following has to be true: $\\text{cnt}_i = 0$, $\\text{cnt}_j = 0$, or $\\text{cnt}_i \\le \\text{cnt}_j$. In other words, if both $i$ and $j$ are present in sequence $a$, then the number of occurrences of $i$ in $a$ is less than or equal to the number of occurrences of $j$ in $a$.\n\nYou are given integers $n$ and $m$. Calculate the value of the bitwise XOR of the median$^{\\text{∗}}$ of all good sequences $a$ of length $n$ with $0\\le a_i < m$.\n\nNote that the value of $n$ can be very large, so you are given its binary representation instead.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The median of a sequence $a$ of length $n$ is defined as the $\\left\\lfloor\\frac{n + 1}{2}\\right\\rfloor$-th smallest value in the sequence.\n\\end{footnotesize}",
    "tutorial": "The order of the sequence doesn't matter. What if we fix the sequence $\\text{cnt}$ and then calculate its contribution to the answer? By Lucas's theorem the contribution is odd iff for each set bit in $n$ there is exactly one $i$ such that $\\text{cnt}_i$ has this bit set, and $\\sum\\limits_{i = 0}^{m - 1} \\text{cnt}_i = n$. In other words, $\\text{cnt}$ has to partition all set bits in $n$. For a fixed $\\text{cnt}$ with an odd contribution, what will be the median? There is a very big element in $\\text{cnt}$. Since $\\text{cnt}$ partitions the bits of $n$, there will be $i$ which has it's most significant bit. This means that $2\\text{cnt}_i > n$, so $i$ will always be the median. Suppose there are $p$ non-zero elements in $\\text{cnt}$. We can partition all set bits of $n$ into $p$ non-empty subsequences and then choose which of the $m$ numbers will occur. How can we calculate the answer now? The only time we use the value of $n$ is when we partition all of it's set bits into subsequences. That means that the answer only depends on the number of set bits in $n$, not on $n$ itself. This allows us to solve the easy version by fixing the value of $p$ and the value of the median. To solve the hard version use Lucas's theorem again and do digit dp or SOS-dp. The order of the sequence doesn't matter, so let's fix the sequence $\\text{cnt}$ and calculate its contribution to the answer. For a fixed $\\text{cnt}$, the number of ways to order $a$ is $\\binom{n}{\\text{cnt}_0, \\text{cnt}_1, \\ldots, \\text{cnt}_{m - 1}}$. By Lucas's theorem the contribution is odd iff for each set bit in $n$ there is exactly one $i$ such that $\\text{cnt}_i$ has this bit set, and $\\sum\\limits_{i = 0}^{m - 1} \\text{cnt}_i = n$. In other words, $\\text{cnt}$ has to partition all set bits in $n$. Since $\\text{cnt}$ partitions the bits of $n$, there will be $i$ which has it's most significant bit. This means that $2\\text{cnt}_i > n$, so $i$ will always be the median. Suppose there are $p$ non-zero elements in $\\text{cnt}$. We can partition all set bits of $n$ into $p$ non-empty subsequences and then choose which of the $m$ numbers will occur. The only time we use the value of $n$ is when we partition all of it's set bits into subsequences. That means that the answer only depends on the number of set bits in $n$, not on $n$ itself. So let's fix $p$ as the number of non-zero elements in $\\text{cnt}$ and $x$ as the median. Denote $b$ as the number of set bits in $n$. There are $S(b, p)$ ways to partition the bits into $p$ non-empty subsequences, where $S$ denotes Stirling number of the second kind. There are $\\binom{x}{p - 1}$ ways to choose which other elements will have non-zero $\\text{cnt}$, because the median will always have the largest value and non-zero $\\text{cnt}_i$ must be non-decreasing. The answer is then $\\oplus_{p = 1}^b \\oplus_{x = 0}^{m - 1} \\left(S(b, p) \\bmod 2\\right) \\cdot \\left(\\binom{x}{p - 1} \\bmod 2\\right) \\cdot x$, which we can calculate in $O(km)$, which solves the easy version. To solve the hard version we can use Lucas's theorem again to get that the contribution of $x$ to the answer is the XOR of $S(b, p + 1) \\bmod 2$ over all submasks $p$ of $x$. We can limit $p$ to be between $0$ and $b - 1$. That means that only $L = \\lceil \\log_2 b \\rceil$ last bits of $x$ determine whether $x$ contributes something to the answer. We can find which of $2^L$ of them will have an odd contribution by setting $dp_p = S(b, p + 1) \\bmod 2$, and calculating it's SOS-dp. Then for fixed $L$ last bits it is easy to find the XOR of all $x < m$ with those bits. Note that $S(n, k)$ is odd iff $(n - k) \\text{&} \\frac{k - 1}{2} = 0$, which we can derive from the recurrence, combinatorics, google or OEIS. This solves the problem in $O(b \\log b) = O(k \\log k)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint S(int n, int k) {\n    return !(n - k & (k - 1 >> 1));\n}\n\nint get(int n, int m) {\n    int L = __lg(n) + 1;\n    int up = 1 << L;\n    vector<int> dp(up);\n    for(int i = 0; i < n; i++) dp[i] = S(n, i + 1);\n    for(int j = 0; j < L; j++) {\n        for(int i = 0; i < up; i++) {\n            if(i >> j & 1) dp[i] ^= dp[i ^ (1 << j)];\n        }\n    }\n    int ans = 0;\n    for(int lst = 0; lst < up && lst < m; lst++) {\n        if(!dp[lst]) continue;\n        int cnt = m - 1 - lst >> L;\n        if(cnt & 1 ^ 1) ans ^= lst;\n        if(cnt % 4 == 0) ans ^= cnt << L;\n        else if(cnt % 4 == 1) ans ^= 1ll << L;\n        else if(cnt % 4 == 2) ans ^= cnt + 1 << L;\n        else ans ^= 0;\n    }\n    return ans;\n}\n\nvoid solve() {\n    int k, m;\n    string s;\n    cin >> k >> m >> s;\n    int n = 0;\n    for(auto &i : s) n += i & 1;\n    int ans = get(n, m);\n    cout << ans << '\\n';\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int ttt = 1;\n    cin >> ttt;\n    while(ttt--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2057",
    "index": "A",
    "title": "MEX Table",
    "statement": "One day, the schoolboy Mark misbehaved, so the teacher Sasha called him to the whiteboard.\n\nSasha gave Mark a table with $n$ rows and $m$ columns. His task is to arrange the numbers $0, 1, \\ldots, n \\cdot m - 1$ in the table (each number must be used exactly once) in such a way as to maximize the sum of MEX$^{\\text{∗}}$ across all rows and columns. More formally, he needs to maximize $$\\sum\\limits_{i = 1}^{n} \\operatorname{mex}(\\{a_{i,1}, a_{i,2}, \\ldots, a_{i,m}\\}) + \\sum\\limits_{j = 1}^{m} \\operatorname{mex}(\\{a_{1,j}, a_{2,j}, \\ldots, a_{n,j}\\}),$$ where $a_{i,j}$ is the number in the $i$-th row and $j$-th column.\n\nSasha is not interested in how Mark arranges the numbers, so he only asks him to state one number — the maximum sum of MEX across all rows and columns that can be achieved.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The minimum excluded (MEX) of a collection of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $c$.\n\nFor example:\n\n- $\\operatorname{mex}([2,2,1])= 0$, since $0$ does not belong to the array.\n- $\\operatorname{mex}([3,1,0,1]) = 2$, since $0$ and $1$ belong to the array, but $2$ does not.\n- $\\operatorname{mex}([0,3,1,2]) = 4$, since $0$, $1$, $2$, and $3$ belong to the array, but $4$ does not.\n\n\\end{footnotesize}",
    "tutorial": "Note that $0$ appears in exactly one row and exactly one column. As for $1$, if it exists, it can only be placed in one of the rows or columns that contain $0$, so the answer does not exceed $\\operatorname{max}(n, m) + 1$, since only one column or row can have an answer greater than one, and in another one there can be an answer of $1$. It is not difficult to provide an example where the answer is achieved: if $n > m$, we place the numbers from $0$ to $n - 1$ in the first column; otherwise, we place the numbers from $0$ to $m - 1$ in the first row. The remaining elements can be placed arbitrarily.",
    "code": "#include <bits/stdc++.h>\n \nusing i64 = long long;\n \nvoid solve() {\n    int n, m;\n    std::cin >> n >> m;\n    std::cout << std::max(n, m) + 1 << \"\\n\";\n}\n \nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n \n    int t = 1;\n    std::cin >> t;\n    \n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2057",
    "index": "B",
    "title": "Gorilla and the Exam",
    "statement": "Due to a shortage of teachers in the senior class of the \"T-generation\", it was decided to have a huge male gorilla conduct exams for the students. However, it is not that simple; to prove his competence, he needs to solve the following problem.\n\nFor an array $b$, we define the function $f(b)$ as the smallest number of the following operations required to make the array $b$ empty:\n\n- take two integers $l$ and $r$, such that $l \\le r$, and let $x$ be the $\\min(b_l, b_{l+1}, \\ldots, b_r)$; then\n- remove all such $b_i$ that $l \\le i \\le r$ and $b_i = x$ from the array, the deleted elements are removed, the indices are renumerated.\n\nYou are given an array $a$ of length $n$ and an integer $k$. No more than $k$ times, you can choose any index $i$ ($1 \\le i \\le n$) and any integer $p$, and replace $a_i$ with $p$.\n\nHelp the gorilla to determine the smallest value of $f(a)$ that can be achieved after such replacements.",
    "tutorial": "Note that $f(a)$ is the number of distinct numbers in the array. Since it is beneficial for us to always choose the entire array as the segment, because we will eventually remove the minimum element, it is advantageous to remove it from the entire array at once. Therefore, our task has been reduced to changing no more than $k$ elements in order to minimize the number of distinct elements. To achieve this, we observe that it is always beneficial to change all the numbers that occur the least in the array and change them to the number that occurs the most frequently. This process can be easily accomplished in $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing i64 = long long;\n\nvoid solve() {\n    int n, k;\n    std::cin >> n >> k;\n    std::vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        std::cin >> a[i];\n    }\n    std::sort(a.begin(), a.end());\n    std::vector<int> cnt = {1};\n    for (int i = 1; i < n; i++) {\n        if (a[i] == a[i - 1]) {\n            cnt.back()++;\n        } else {\n            cnt.emplace_back(1);\n        }\n    }\n    std::sort(cnt.begin(), cnt.end());\n    int m = cnt.size();\n    for (int i = 0; i < m - 1; i++) {\n        if (cnt[i] > k) {\n            std::cout << m - i << \"\\n\";\n            return;\n        }\n        k -= cnt[i];\n    }\n    std::cout << 1 << \"\\n\";\n}\n\nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n\n    int t = 1;\n    std::cin >> t;\n\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2057",
    "index": "C",
    "title": "Trip to the Olympiad",
    "statement": "In the upcoming year, there will be many team olympiads, so the teachers of \"T-generation\" need to assemble a team of three pupils to participate in them. Any three pupils will show a worthy result in any team olympiad. But winning the olympiad is only half the battle; first, you need to get there...\n\nEach pupil has an independence level, expressed as an integer. In \"T-generation\", there is exactly one student with each independence levels from $l$ to $r$, inclusive. For a team of three pupils with independence levels $a$, $b$, and $c$, the value of their team independence is equal to $(a \\oplus b) + (b \\oplus c) + (a \\oplus c)$, where $\\oplus$ denotes the bitwise XOR operation.\n\nYour task is to choose any trio of students with the maximum possible team independence.",
    "tutorial": "Let's take a look at the $i$-th bit. If it appears in all numbers or in none, it contributes nothing to the answer; however, if it appears in one or two numbers, it adds $2^{i + 1}$ to the answer. Therefore, let's examine the most significant bit, let's say the $k$-th bit, which differs in the numbers $l$ and $r$, and note that the more significant bits do not affect the outcome, so the answer cannot exceed $T = 2 \\cdot (1 + 2 + \\ldots + 2^k)$. Thus, let $x$ be the only number that is divisible by $2^k$ in the range $[l, r]$. Take $y = x - 1$ and $z$ as any number in the range $[l, r]$ that is neither $x$ nor $y$. Notice that by choosing such a triplet of numbers, the value of the expression $(x \\oplus y) + (x \\oplus z) + (y \\oplus z)$ is exactly equal to $T$.",
    "code": "#include <bits/stdc++.h>\n \nusing i64 = long long;\n \nvoid solve() {\n    int l, r;\n    std::cin >> l >> r;\n    int k = 31 - __builtin_clz(l ^ r);\n    int a = l | ((1 << k) - 1), b = a + 1, c = (a == l ? r : l);\n    std::cout << a << \" \" << b << \" \" << c << \"\\n\";\n}\n \nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n \n    int t = 1;\n    std::cin >> t;\n \n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2057",
    "index": "D",
    "title": "Gifts Order",
    "statement": "\"T-Generation\" has decided to purchase gifts for various needs; thus, they have $n$ different sweaters numbered from $1$ to $n$. The $i$-th sweater has a size of $a_i$. Now they need to send some subsegment of sweaters to an olympiad. It is necessary that the sweaters fit as many people as possible, but without having to take too many of them.\n\nThey need to choose two indices $l$ and $r$ ($1 \\le l \\le r \\le n$) to maximize the convenience equal to $$\\operatorname{max} (a_l, a_{l + 1}, \\ldots, a_r) - \\operatorname{min} (a_l, a_{l + 1}, \\ldots, a_r) - (r - l),$$ that is, the range of sizes minus the number of sweaters.\n\nSometimes the sizes of the sweaters change; it is known that there have been $q$ changes, in each change, the size of the $p$-th sweater becomes $x$.\n\nHelp the \"T-Generation\" team and determine the maximum convenience among all possible pairs $(l, r)$ initially, as well as after each size change.",
    "tutorial": "To begin with, let's take a look at what an optimal segment of coats looks like. I claim that in the optimal answer, the maximum and minimum are located at the edges of the segment. Suppose this is not the case; then we can narrow the segment (from the side where the extreme element is neither the minimum nor the maximum), and the answer will improve since the length will decrease, while the minimum and maximum will remain unchanged. Okay, there are two scenarios: when the minimum is at $l$ and the maximum is at $r$, and vice versa. These two cases are analogous, so let's consider the solution when the minimum is at $l$. Let's express what the value of the segment actually is: it is $a_r - a_l - (r - l) = (a_r - r) - (a_l - l)$, meaning there is a part that depends only on $r$ and a part that depends only on $l$. Let's create a segment tree where we will store the answer, as well as the maximum of all $a_i - i$ and the minimum of all $a_i - i$ (for the segment that corresponds to the current node of the segment tree, of course). Now, let's see how to recalculate the values at the node. First, the minimum/maximum of $a_i - i$ can be easily recalculated by taking the minimum/maximum from the two children of the node in the segment tree. Now, how do we recalculate the answer? In fact, it is simply the maximum of the two answers for the children, plus (the maximum in the right child) minus (the minimum in the left child), which is the case when the maximum is in the right child and the minimum is in the left. Since we maintain this in the segment tree, we can easily handle update queries. For greater clarity, I recommend looking at the code.",
    "code": "#include <bits/stdc++.h>\n\nusing i64 = long long;\n\ntemplate<class Info>\nstruct SegmentTree {\n    int n;\n    std::vector<Info> info;\n\n    SegmentTree() : n(0) {}\n\n    SegmentTree(int n_, Info v_ = Info()) {\n        init(n_, v_);\n    }\n\n    template<class T>\n    SegmentTree(std::vector<T> init_) {\n        init(init_);\n    }\n\n    void init(int n_, Info v_ = Info()) {\n        init(std::vector<Info>(n_, v_));\n    }\n\n    template<class T>\n    void init(std::vector<T> init_) {\n        n = init_.size();\n        int sz = (1 << (std::__lg(n - 1) + 1));\n        info.assign(sz * 2, Info());\n        std::function<void(int, int, int)> build = [&](int v, int l, int r) {\n            if (l == r) {\n                info[v] = init_[l];\n                return;\n            }\n            int m = (l + r) / 2;\n            build(v + v, l, m);\n            build(v + v + 1, m + 1, r);\n            info[v] = info[v + v] + info[v + v + 1];\n        };\n        build(1, 0, n - 1);\n    }\n\n    Info rangeQuery(int v, int l, int r, int tl, int tr) {\n        if (r < tl || l > tr) {\n            return Info();\n        }\n        if (l >= tl && r <= tr) {\n            return info[v];\n        }\n        int m = (l + r) / 2;\n        return rangeQuery(v + v, l, m, tl, tr) + rangeQuery(v + v + 1, m + 1, r, tl, tr);\n    }\n\n    Info rangeQuery(int l, int r) {\n        return rangeQuery(1, 0, n - 1, l, r);\n    }\n\n    void modify(int v, int l, int r, int i, const Info &x) {\n        if (l == r) {\n            info[v] = x;\n            return;\n        }\n        int m = (l + r) / 2;\n        if (i <= m) {\n            modify(v + v, l, m, i, x);\n        } else {\n            modify(v + v + 1, m + 1, r, i, x);\n        }\n        info[v] = info[v + v] + info[v + v + 1];\n    }\n\n    void modify(int i, const Info &x) {\n        modify(1, 0, n - 1, i, x);\n    }\n\n    Info query(int v, int l, int r, int i) {\n        if (l == r) {\n            return info[v];\n        }\n        int m = (l + r) / 2;\n        if (i <= m) {\n            return query(v + v, l, m, i);\n        } else {\n            return query(v + v + 1, m + 1, r, i);\n        }\n    }\n\n    Info query(int i) {\n        return query(1, 0, n - 1, i);\n    }\n};\n\nconst int INF = 1E9;\n\nstruct Info {\n    int min1, min2, max1, max2, ans1, ans2;\n\n    Info() : min1(INF), min2(INF), max1(-INF), max2(-INF), ans1(0), ans2(0) {}\n\n    Info(std::pair<int, int> x) : min1(x.first), min2(x.second), max1(x.first), max2(x.second), ans1(0), ans2(0) {}\n};\n\nInfo operator+(const Info &a, const Info &b) {\n    Info res;\n    res.min1 = std::min(a.min1, b.min1);\n    res.min2 = std::min(a.min2, b.min2);\n    res.max1 = std::max(a.max1, b.max1);\n    res.max2 = std::max(a.max2, b.max2);\n    res.ans1 = std::max({a.ans1, b.ans1, b.max1 - a.min1});\n    res.ans2 = std::max({a.ans2, b.ans2, a.max2 - b.min2});\n    return res;\n}\n\nvoid solve() {\n    int n, q;\n    std::cin >> n >> q;\n    std::vector<int> a(n);\n    std::vector<std::pair<int, int>> t(n);\n    for (int i = 0; i < n; i++) {\n        std::cin >> a[i];\n        t[i] = {a[i] - i, a[i] + i - n + 1};\n    }\n    SegmentTree<Info> st(t);\n    auto query = [&]() {\n        return std::max(st.info[1].ans1, st.info[1].ans2);\n    };\n    std::cout << query() << \"\\n\";\n    for (int i = 0; i < q; i++) {\n        int p, x;\n        std::cin >> p >> x;\n        p--;\n        t[p] = {x - p, x + p - n + 1};\n        st.modify(p, t[p]);\n        std::cout << query() << \"\\n\";\n    }\n}\n\nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n\n    int t;\n    std::cin >> t;\n\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "math",
      "matrices"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2057",
    "index": "E1",
    "title": "Another Exercise on Graphs (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, there is an additional constraint on $m$. You can hack only if you solved all versions of this problem.}\n\nRecently, the instructors of \"T-generation\" needed to create a training contest. They were missing one problem, and there was not a single problem on graphs in the contest, so they came up with the following problem.\n\nYou are given a connected weighted undirected graph with $n$ vertices and $m$ edges, which does not contain self-loops or multiple edges.\n\nThere are $q$ queries of the form $(a, b, k)$: among all paths from vertex $a$ to vertex $b$, find the smallest $k$-th maximum weight of edges on the path$^{\\dagger}$.\n\nThe instructors thought that the problem sounded very interesting, but there is one catch. They do not know how to solve it. Help them and solve the problem, as there are only a few hours left until the contest starts.\n\n$^{\\dagger}$ Let $w_1 \\ge w_2 \\ge \\ldots \\ge w_{h}$ be the weights of all edges in a path, in non-increasing order. The $k$-th maximum weight of the edges on this path is $w_{k}$.",
    "tutorial": "We will learn how to check if there exists a path from $a$ to $b$ such that the $k$-th maximum on this path is less than or equal to $x$. For a fixed $x$, the edges are divided into two types: light (weight less than or equal to $x$) and heavy (weight strictly greater than $x$). We assign a weight of $0$ to all light edges and a weight of $1$ to all heavy edges. Then, the desired path exists if and only if the shortest path between $a$ and $b$ (considering the assigned weights) is strictly less than $k$. Now, let's consider that we have many queries. Initially, we assign a weight of $1$ to all edges and compute the length of the shortest path between each pair of vertices. Then, we will process the edges in increasing order of weight and replace their weights with $0$. After each such change, we need to be able to recalculate the shortest paths between each pair of vertices. Let $\\textrm{d}[i][j]$ be the shortest paths before changing the weight of the edge $(a, b)$; then the lengths of the new paths $\\textrm{d}'$ can be computed using the formula: $\\textrm{d}'[i][j] = \\min \\{ \\textrm{d}[i][j], \\textrm{d}[a][i] + \\textrm{d}[b][j], \\textrm{d}[b][i] + \\textrm{d}[a][j], \\}$ Thus, each recalculation of the lengths of the shortest paths can be performed in $O(n^2)$. Let $\\textrm{dp}[k][i][j]$ be the length of the shortest path between the pair of vertices $i$ and $j$, if the weights of the minimum $k$ edges are $0$, and the weights of the remaining edges are $1$. We have just learned how to recalculate this dynamic programming in $O(n^2 \\cdot m)$ time. Using the criterion, we can answer each of the queries in $O(\\log m)$ time using the binary search method and the computed array $\\textrm{dp}[k][i][j]$. On simple and non-simple paths. If there is a cycle in the path, it can be removed from this path, and the $k$-th maximum will not increase. Thus, if we restrict the set of considered paths to only simple paths (i.e., those that do not contain cycles in any form), the answer will not change.",
    "code": "#include <bits/stdc++.h>\n \nusing i64 = long long;\n \nvoid solve() {\n    int n, m, q;\n    std::cin >> n >> m >> q;\n    std::vector<std::array<int, 3>> edges(m);\n    for (int i = 0; i < m; i++) {\n        int v, u, w;\n        std::cin >> v >> u >> w;\n        v--, u--;\n        edges[i] = {v, u, w};\n    }\n    std::sort(edges.begin(), edges.end(), [&](const std::array<int, 3> &a, const std::array<int, 3> &b) {\n        return a[2] < b[2];\n    });\n    constexpr int INF = 1e9;\n    std::vector<int> value(m + 1);\n    std::vector<std::vector<std::vector<int>>> dis(m + 1, std::vector<std::vector<int>>(n, std::vector<int>(n, INF)));\n    for (int i = 0; i < n; i++) {\n        dis[0][i][i] = 0;\n    }\n    for (auto edge : edges) {\n        int v = edge[0], u = edge[1];\n        dis[0][v][u] = dis[0][u][v] = 1;\n    }\n    for (int k = 0; k < n; k++) {\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) {\n                dis[0][i][j] = std::min(dis[0][i][j], dis[0][i][k] + dis[0][k][j]);\n            }\n        }\n    }\n    int p = 1;\n    for (auto edge : edges) {\n        int v = edge[0], u = edge[1], w = edge[2];\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) {\n                dis[p][i][j] = std::min({dis[p - 1][i][j], dis[p - 1][i][v] + dis[p - 1][u][j], dis[p - 1][i][u] + dis[p - 1][v][j]});\n            }\n        }\n        value[p++] = w;\n    }\n    for (int i = 0; i < q; i++) {\n        int v, u, k;\n        std::cin >> v >> u >> k;\n        v--, u--;\n        int low = 0, high = m;\n        while (high - low > 1) {\n            int mid = (low + high) / 2;\n            if (dis[mid][v][u] < k) {\n                high = mid;\n            } else {\n                low = mid;\n            }\n        }\n        std::cout << value[high] << \" \\n\"[i == q - 1];\n    }\n}\n \nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n \n    int t = 1;\n    std::cin >> t;\n \n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "dsu",
      "graphs",
      "shortest paths",
      "sortings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2057",
    "index": "E2",
    "title": "Another Exercise on Graphs (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, there is no additional constraint on $m$. You can hack only if you solved all versions of this problem.}\n\nRecently, the instructors of \"T-generation\" needed to create a training contest. They were missing one problem, and there was not a single problem on graphs in the contest, so they came up with the following problem.\n\nYou are given a connected weighted undirected graph with $n$ vertices and $m$ edges, which does not contain self-loops or multiple edges.\n\nThere are $q$ queries of the form $(a, b, k)$: among all paths from vertex $a$ to vertex $b$, find the smallest $k$-th maximum weight of edges on the path$^{\\dagger}$.\n\nThe instructors thought that the problem sounded very interesting, but there is one catch. They do not know how to solve it. Help them and solve the problem, as there are only a few hours left until the contest starts.\n\n$^{\\dagger}$ Let $w_1 \\ge w_2 \\ge \\ldots \\ge w_{h}$ be the weights of all edges in a path, in non-increasing order. The $k$-th maximum weight of the edges on this path is $w_{k}$.",
    "tutorial": "Please read the solution to problem E1. Let's return to the process where we sequentially changed the weights of the edges from $1$ to $0$. If we replace the weight of another edge with $0$ and it connects vertices that are at a distance of $0$, it means that the shortest paths between each pair of vertices will not change at all, so we will not recalculate the shortest paths in this case. We also will not store useless layers in the array $\\textrm{dp}[k][i][j]$. This allows us to improve the asymptotic complexity of our solution to $O(n^3 + q \\log n)$. Proof. We will consider a graph that consists only of edges with weight $0$. We have $m$ consecutive requests to add an edge. Notice that we compute a new layer of $\\textrm{dp}$ only if, after adding the edge, some two components of this graph are merged, but this will happen exactly $n-1$ times.",
    "code": "#include <bits/stdc++.h>\n\nusing i64 = long long;\n\nstruct DSU {\n    std::vector<int> p, sz, h;\n    \n    DSU(int n = 0) : p(n), sz(n, 1), h(n) { \n        std::iota(p.begin(), p.end(), 0); \n    }\n\n    int leader(int x) {\n        if (x == p[x]) {\n            return x;\n        }\n        return leader(p[x]);\n    }\n\n    bool same(int x, int y) {\n        return leader(x) == leader(y);\n    }\n\n    bool merge(int x, int y) {\n        x = leader(x);\n        y = leader(y);\n        if (x == y) return false;\n        if (h[x] < h[y]) {\n            std::swap(x, y);\n        }\n        if (h[x] == h[y]) {\n            ++h[x];\n        }\n        sz[x] += sz[y];\n        p[y] = x;\n        return true;\n    }\n\n    int size(int x) { \n        return sz[leader(x)]; \n    }\n};\n\nvoid solve() {\n    int n, m, q;\n    std::cin >> n >> m >> q;\n    std::vector<std::array<int, 3>> edges(m);\n    for (int i = 0; i < m; i++) {\n        int v, u, w;\n        std::cin >> v >> u >> w;\n        v--, u--;\n        edges[i] = {v, u, w};\n    }\n    std::sort(edges.begin(), edges.end(), [&](const std::array<int, 3> &a, const std::array<int, 3> &b) {\n        return a[2] < b[2];\n    });\n    constexpr int INF = 1e9;\n    std::vector<int> value(n);\n    std::vector<std::vector<std::vector<int>>> dis(n, std::vector<std::vector<int>>(n, std::vector<int>(n, INF)));\n    for (int i = 0; i < n; i++) {\n        dis[0][i][i] = 0;\n    }\n    for (auto edge : edges) {\n        int v = edge[0], u = edge[1];\n        dis[0][v][u] = dis[0][u][v] = 1;\n    }\n    for (int k = 0; k < n; k++) {\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) {\n                dis[0][i][j] = std::min(dis[0][i][j], dis[0][i][k] + dis[0][k][j]);\n            }\n        }\n    }\n    int p = 1;\n    DSU dsu(n);\n    for (auto edge : edges) {\n        int v = edge[0], u = edge[1], w = edge[2];\n        if (dsu.merge(v, u)) {\n            for (int i = 0; i < n; i++) {\n                for (int j = 0; j < n; j++) {\n                    dis[p][i][j] = std::min({dis[p - 1][i][j], dis[p - 1][i][v] + dis[p - 1][u][j], dis[p - 1][i][u] + dis[p - 1][v][j]});\n                }\n            }\n            value[p++] = w;\n        }\n    }\n    for (int i = 0; i < q; i++) {\n        int v, u, k;\n        std::cin >> v >> u >> k;\n        v--, u--;\n        int low = 0, high = n - 1;\n        while (high - low > 1) {\n            int mid = (low + high) / 2;\n            if (dis[mid][v][u] < k) {\n                high = mid;\n            } else {\n                low = mid;\n            }\n        }\n        std::cout << value[high] << \" \\n\"[i == q - 1];\n    }\n}\n\nsigned main() {\n    std::ios::sync_with_stdio(false);\n    std::cin.tie(nullptr);\n\n    int t = 1;\n    std::cin >> t;\n\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "shortest paths",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2057",
    "index": "F",
    "title": "Formation",
    "statement": "One day, the teachers of \"T-generation\" decided to instill discipline in the pupils, so they lined them up and made them calculate in order. There are a total of $n$ pupils, the height of the $i$-th pupil in line is $a_i$.\n\nThe line is comfortable, if for each $i$ from $1$ to $n - 1$, the following condition holds: $a_i \\cdot 2 \\ge a_{i + 1}$. Initially, the line is comfortable.\n\nThe teachers do not like that the maximum height in the line is too small, so they want to feed the pupils pizza. You know that when a pupil eats one pizza, their height increases by $1$. One pizza can only be eaten by only one pupil, but each pupil can eat an unlimited number of pizzas. It is important that after all the pupils have eaten their pizzas, the line is comfortable.\n\nThe teachers have $q$ options for how many pizzas they will order. For each option $k_i$, answer the question: what is the maximum height $\\max(a_1, a_2, \\ldots, a_n)$ that can be achieved if the pupils eat at most $k_i$ pizzas.",
    "tutorial": "Hint 1: how much does a single index affect those before him? Hint 2: try looking at the formula for making an index a maximum differently Hint 3: do you need to answer all queries online? Hint 4: do you need to consider all indexes? Solution: Let's fix the index that we want our maximum to be on - let it be $i$. Then, due to $k_i$ being $\\le 10^9$ in each test case, and every number in our array $a$ also being $\\le 10^9$, we do not need to consider any indexes before $i - 30$ - they are also valid as they were part of the previous good array, and we do not need to make them bigger as $2^{31} \\ge 2 * 10^9$. Now let's try doing binary search on the answer for each query (let our current query be with the number $M$). When we fix our possible answer as $X$ at index $i$, what does that mean? It means that we need $a_i \\ge X, a_{i-1} \\ge \\lceil{\\frac{X}{2}} \\rceil$, and so on, calculating every index through the next one $(i$ from $i + 1)$. Let us call this auxiliary array $c$ $( c_0 = X, c_i = \\lceil\\frac{c_{i - 1}}{2} \\rceil)$. So, if we need to change exactly $k$ indexes before $i$ ($i$, $i - 1$, ..., $i - k$) , our condition for checking whether we could do that is as followed: $1$. $a_{i - j} \\le c_j$ for each $0 \\le j \\le k$ $2$. $\\sum_{j = 0}^{k} c_j - a_{i - j} \\le M$. Now, we can see that for each fixed $k$ from $0$ to $log MAX = 30$, we should choose such an index $i$, that its previous indexes satisfy condition $1$ from above, and $\\sum_{j = 0}^{k} a_{i - j}$ is minimal. Let's consider solving this via scanline. For each index $i$ and each $k$ from $0$ to $30$, let's consider the possible values of $M$ such that if we want our maximum to be on index $i$, it will affect exactly $(a_i, a_{i - 1}, \\ldots, a_{i - k})$. We can notice that such values form a segment $[L_{ik}, R_{ik}]$, which is possiblyinvalid $(L_{ik} > R_{ik})$. We can find these segments in $O(N log MAX)$. Now let's go through the request offline in ascending order, maintaining currently active indexes. We maintain $log MAX + 1$ multisets with the minimum possible sums on valid segments of each length, and update them on each opening/closing of a segment $($ this is done in $O(N log ^ 2 MAX) )$. On each request, we do binary search on the answer, and check all $log MAX$ length candidates.",
    "code": "// Parallel binary search technique optimizes log^3 => log^2\n// SegmentTree might be faster then std::multiset\n// sl[i] should equals max(a) at the begining cause IDK how to explain but it's obviously important\n \n#include <bits/stdc++.h>\n#include <algorithm>\n \nusing namespace std;\nusing ll = long long;\n \nconstexpr int W = 31;\nconstexpr int C = 1'000'000'000;\n \nstruct Event {\n    int x;\n    int ind;\n    ll s;\n \n    bool operator<(const Event& rhs) const { return x < rhs.x; }\n};\n \nstruct SegmentTree {\n    int n;\n    vector<ll> sgt;\n \n    SegmentTree(int n) : n(n), sgt(2 * n, -1) {}\n \n    void Change(int i, ll x) {\n        for (sgt[i += n] = x; i != 1; i >>= 1) {\n            sgt[i >> 1] = max(sgt[i], sgt[i ^ 1]);\n        }\n    }\n \n    int GlobalMax() const { return sgt[1]; }\n};\n \nvector<int> solve(const vector<int>& a, const vector<int>& q) {\n    const int n = a.size(), m = q.size();\n \n    vector<ll> ps(n + 1);\n    for (int i = 0; i < n; ++i)\n        ps[i + 1] = ps[i] + a[i];\n \n    vector<ll> min_x(n, 0);\n    vector<vector<pair<int, ll>>> change_sum(W);\n \n    vector<Event> events;\n    events.reserve(2 * n);\n    for (int j = 1; j <= W && j <= n; ++j) {\n        events.clear();\n \n        for (int i = j - 1; i < n; ++i) {\n            min_x[i] = max(min_x[i], 1 + ((a[i - j + 1] - 1ll) << (j - 1)));\n            ll max_x = i == j - 1 ? 2ll * C : ((ll)a[i - j] << j);\n            max_x = min<ll>(max_x, a[i] + C);\n \n            if (min_x[i] > max_x) {\n                continue;\n            }\n            const ll xsum = ps[i + 1] - ps[i + 1 - j];\n            events.push_back(Event{(int)min_x[i], i, xsum});\n            events.push_back(Event{(int)max_x + 1, i, -1});\n        }\n        sort(events.begin(), events.end());\n \n        SegmentTree sgt(n);\n        const int k = events.size();\n        ll was_max = -1;\n \n        for (int i = 0; i < k;) {\n            int s = i;\n            while (i < k && events[i].x == events[s].x) {\n                sgt.Change(events[i].ind, events[i].s);\n                ++i;\n            }\n            ll cur_max = sgt.GlobalMax();\n            if (cur_max != was_max) {\n                change_sum[j - 1].emplace_back(events[s].x, cur_max);\n                was_max = cur_max;\n            }\n        }\n    }\n \n    vector<int> sl(m, *max_element(a.begin(), a.end())), sr(m, 2 * C + 1);\n \n    vector<int> ord_to_check(m);\n    iota(ord_to_check.begin(), ord_to_check.end(), 0);\n    for (int iter = 32; iter--;) {\n        vector<int> sm(m);\n        for (int i = 0; i < m; ++i) {\n            sm[i] = sl[i] + (sr[i] - sl[i]) / 2;\n        }\n        sort(ord_to_check.begin(), ord_to_check.end(), [&](int lhs, int rhs) {\n            return sm[lhs] < sm[rhs];\n        });\n \n        vector<int> ptr(W);\n        vector<ll> actual_sum(W, -1);\n        for (int i : ord_to_check) {\n            const int x = sm[i];\n \n \n            ll upper_sum = 0;\n            bool nice = false;\n            for (int w = 0; w < W; ++w) {\n                int& j = ptr[w];\n                while (j < change_sum[w].size() && change_sum[w][j].first <= x) {\n                    actual_sum[w] = change_sum[w][j++].second;\n                }\n                upper_sum += 1 + ((x - 1) >> w);\n                if (upper_sum - actual_sum[w] <= q[i]) {\n                    nice = true;\n                }\n            }\n \n            if (nice) {\n                sl[i] = sm[i];\n            } else {\n                sr[i] = sm[i];\n            }\n        }\n    }\n \n    return sl;\n}\n \nint main() {\n    ios::sync_with_stdio(0);\n    cin.tie(0);\n \n    int t = 1;\n    cin >> t;\n    while (t--) {\n        int n, q;\n        cin >> n >> q;\n        vector<int> a(n), k(q);\n        for (int& x : a)\n            cin >> x;\n        for (int& x : k)\n            cin >> x;\n \n        auto ans = solve(a, k);\n        for (int x : ans)\n            cout << x << ' ';\n        cout << '\\n';\n    }\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "sortings",
      "two pointers"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2057",
    "index": "G",
    "title": "Secret Message",
    "statement": "Every Saturday, Alexander B., a teacher of parallel X, writes a secret message to Alexander G., a teacher of parallel B, in the evening. Since Alexander G. is giving a lecture at that time and the message is very important, Alexander B. has to write this message on an interactive online board.\n\nThe interactive online board is a grid consisting of $n$ rows and $m$ columns, where each cell is $1 \\times 1$ in size. Some cells of this board are already filled in, and it is impossible to write a message in them; such cells are marked with the symbol \".\", while the remaining cells are called free and are marked with the symbol \"#\".\n\nLet us introduce two characteristics of the online board:\n\n- $s$ is the number of free cells.\n- $p$ is the perimeter of the grid figure formed by the union of free cells.\n\nLet $A$ be the set of free cells. Your goal is to find a set of cells $S \\subseteq A$ that satisfies the following properties:\n\n- $|S| \\le \\frac{1}{5} \\cdot (s+p)$.\n- Any cell from $A$ either lies in $S$ or shares a side with some cell from $S$.\n\nWe can show that at least one set $S$ satisfying these properties exists; you are required to find \\textbf{any suitable} one.",
    "tutorial": "We will divide the infinite grid into $5$ sets of cells $L_1$, $L_2$, $L_3$, $L_4$, and $L_5$, where $L_i = \\{ (x, y) \\in \\mathbb{Z}^2 \\space | \\space (x + 2 y) \\equiv i \\pmod{5} \\}$. Note that for any pair $(x,y)$, all $5$ cells $(x,y)$, $(x-1, y)$, $(x+1, y)$, $(x, y-1)$, $(x, y+1)$ belong to different sets $L_1, \\ldots, L_5$. If we try to consider the sets $T_i = L_i \\cap A$, it is not guaranteed that each of them will satisfy the property: \"For each cell in the set $A$, either it or one of its neighboring cells shares a side belongs to the set $S$.\" Therefore, we denote $D_i \\subseteq A$ as the set of cells from $A$ that do not belong to $T_i$ and all four neighbors of each of them also do not belong to $T_i$. Now we need to verify the correctness of two statements: $|T_1| + |T_2| + |T_3| + |T_4| + |T_5| = s$; $|D_1| + |D_2| + |D_3| + |D_4| + |D_5| = p$; The first statement is obvious since $T_1 \\cup \\ldots \\cup T_5 = A$. The second statement is true because if some cell $(x, y)$ does not belong to $T_i$ and all its neighbors do not belong to $T_i$, it means that it has a neighbor $(x', y')$ such that $(x' + 2y') \\bmod 5 = i$. But we know that $(x', y') \\not \\in A$, which means we can mark the shared side of $(x,y)$ and $(x', y')$. If we process $T_1, \\ldots, T_5$ sequentially, then after this process, each segment of the boundary will be marked exactly once, and thus the number of such segments coincides with $|D_1| + \\ldots + |D_5|$. Now let $S_i = T_i \\cup D_i$ and note that $|S_1| + \\ldots + |S_5| = s + p$, which means, by the pigeonhole principle, there exists a $j$ such that $|S_j| \\le \\frac{1}{5} \\cdot (s + p)$, and then $S_j$ will be suitable as the desired set.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing pi = pair<int, int>;\n\nvoid solve() {\n    int n, m; cin >> n >> m;\n    vector<string> v(n);\n    for (auto& w : v) cin >> w;\n\n    auto col = [](int x, int y) {\n        int c = (x+2*y)%5;\n        if (c < 0) c += 5;\n        return c;\n    };\n    auto cell = [&](int x, int y) {\n        if (x < 0 || y < 0 || x >= n || y >= m) return false;\n        return v[x][y] == '#';\n    };\n\n    array<vector<pi>, 5> colorings;\n    for (int i = 0; i < n; ++i)\n    for (int j = 0; j < m; ++j) {\n        if (!cell(i, j)) continue;\n        colorings[col(i, j)].emplace_back(i, j);\n\n        for (int di = -1; di <= 1; ++di)\n        for (int dj = -1; dj <= 1; ++dj) {\n            if (abs(di) + abs(dj) != 1) continue;\n            if (!cell(i+di, j+dj)) {\n                colorings[col(i+di, j+dj)].emplace_back(i, j);\n            }\n        }\n    }\n\n    auto coloring = colorings[0];\n    for (const auto& w : colorings)\n        if (w.size() < coloring.size()) coloring = w;\n    for (auto [x, y] : coloring) v[x][y] = 'S';\n    for (auto line : v) cout << line << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n\n    int t; cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "math"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2057",
    "index": "H",
    "title": "Coffee Break",
    "statement": "There are very long classes in the T-Generation. In one day, you need to have time to analyze the training and thematic contests, give a lecture with new material, and, if possible, also hold a mini-seminar. Therefore, there is a break where students can go to drink coffee and chat with each other.\n\nThere are a total of $n+2$ coffee machines located in sequentially arranged rooms along a long corridor. The coffee machines are numbered from $0$ to $n+1$, and immediately after the break starts, there are $a_i$ students gathered around the $i$-th coffee machine.\n\nThe students are talking too loudly among themselves, and the teachers need to make a very important announcement. Therefore, they want to gather the maximum number of students around some single coffee machine. The teachers are too lazy to run around the corridors and gather the students, so they came up with a more sophisticated way to manipulate them:\n\n- At any moment, the teachers can choose room $i$ ($1 \\le i \\le n$) and turn off the lights there;\n- If there were $x$ students in that room, then after turning off the lights, $\\lfloor \\frac12 x \\rfloor$ students will go to room $(i-1)$, and $\\lfloor \\frac12 x \\rfloor$ other students will go to room $(i+1)$.\n- If $x$ was odd, then one student remains in the same room.\n- After that, the lights in room $i$ are turned back on.\n\nThe teachers have not yet decided where they will gather the students, so for each $i$ from $1$ to $n$, you should determine what is the maximum number of students that can be gathered around the $i$-th coffee machine.\n\nThe teachers can turn off the lights in any rooms at their discretion, in any order, possibly turning off the lights in the same room multiple times.\n\nNote that the values of $a_0$ and $a_{n+1}$ do not affect the answer to the problem, so their values will not be given to you.",
    "tutorial": "Let's call the elementary action $E_j$ the operation after which $a_j$ decreases by $2$, and the values $a_{j-1}$ and $a_{j+1}$ increase by $1$. Let $A$ be some set of actions that can be performed in some order; then this same set of actions can be performed greedily, each time performing any available elementary action. Our solution will be based on two facts: If we want to maximize $a_k$, then actions $E_1, \\ldots E_{k-1}, E_{k+1}, \\ldots E_n$ can be performed at any time, as long as it is possible. In this case, action $E_k$ cannot be performed at all. The proof of the first fact is obvious. Suppose at some moment we can perform action $E_j$ ($j \\neq k$); then if we do not apply it in the optimal algorithm, its application at that moment will not spoil anything. And if we do apply it, then let's apply this action right now instead of postponing it; this will also change nothing. The proof of the second fact is slightly less obvious, so we will postpone it for later. For now, let's figure out how to emulate the application of elementary actions on the prefix $a_1, \\ldots, a_{k-1}$ and on the suffix $a_{k+1}, \\ldots, a_n$. Without loss of generality, let's assume we are considering the prefix of the array $a$ of length $p$. Additionally, assume that $a_1, \\ldots, a_{p-1} \\le 1$, i.e., we cannot apply any of the actions $E_1, \\ldots, E_{p-1}$. If $a_p \\le 1$, then nothing can happen with this prefix for now. Otherwise, the only thing we can do is action $E_p$; after that, we may be able to apply action $E_{p-1}$, $E_{p-2}$, and so on. Let's see what happens if $a_p = 2$: $[\\ldots, 0, 1, 1, 1, 2] \\to [\\ldots, 0, 1, 1, 2, 0] \\to \\ldots \\to [\\ldots, 0, 2, 0, 1, 1] \\to [\\ldots, 1, 0, 1, 1, 1]$ Thus, the position of the last zero in the prefix increases by one, and the value of $a_{p+1}$ also increases by one. We introduce a second elementary action $I_j$ - increasing $a_j$ by one if we previously decreased it by one. This action does not affect the answer, as it can be perceived as \"reserving\" $a_j$ for the future. To understand what happens to the array $[a_1, \\ldots, a_p]$ with an arbitrary value of $a_p$, we will assume that $a_p = 0$, but we will consider that we can apply action $I_p$ $x$ times, which increases $a_p$ by one. After each action $I_p$, we will emulate the greedy application of actions $E_1, \\ldots, E_p$. This can be done as follows: In the stack $S$, we store the positions of zeros in the array $[a_1, \\ldots, a_p]$ (the other values are equal to one). Let $l$ be the position of the last zero; then: If $l=p$, then this zero simply disappears from the stack. If $l<p$, then it is easy to emulate the next $p-l$ actions $I_p$: after each of them, the array looks like $[\\ldots, 0, 1, 1, \\ldots, 1, 2]$, and thus after the greedy application of actions $E_1, \\ldots, E_p$, the value of $l$ increases by $1$. If the stack $S$ is empty, then after one action, $a_{p+1}$ increases by one, and the only element with index $1$ becomes zero. If we repeat actions after this point, the cases will break down identically with a period of $p+1$. Thus, we have learned to understand what happens with each prefix of the array $a_1, \\ldots, a_n$ if we greedily apply elementary actions $E_j$ ($1 \\le j \\le p$). In total, we can emulate these actions in $O(n)$ time. Now let's return to the second point of the statement: if we want to maximize $a_k$, then we cannot perform actions $E_k$. Without loss of generality, let's assume that we first performed actions $E_j$ ($j \\neq k$) greedily, and now we have $a_j \\le 1$ ($j \\neq k$). Suppose we performed action $E_k$ at least once; then after that, we will greedily perform elementary actions to the left and right, for which the stack scheme we considered above works. Notice that after this, the value of $a_k$ will increase by no more than $2$ (no more than $1$ after actions on the prefix and no more than $1$ after actions on the suffix). Thus, action $E_k$ after application did not lead to an increase in $a_k$, nor will it lead to an increase if we apply $E_k$ later, which means that it is useless-there is no need to perform it. Thus, we have proven that by using elementary actions $E_1, \\ldots, E_{k-1}, E_{k+1}, \\ldots E_n$ based on the principle of \"do while we can\", we can easily maximize $a_k$. But in the original problem, we could not apply elementary actions. The operation in the problem, i.e., $a_{i-1} += \\lfloor \\frac12 a_i\\ \\rfloor$, $a_{i+1} += \\lfloor \\frac12 a_i\\ \\rfloor$, $a_i = a_i \\bmod 2$, can be perceived as applying elementary actions $E_i$ consecutively while they are applicable. Fortunately, we just proved that actions can be performed in any order, which means that if we apply the operation from the problem for all indices $i \\neq k$, we will eventually reach the same result, and the value of $a_k$ will reach its maximum.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\nusing vi = vector<int>;\nusing ll = long long;\n\nvector<ll> a, lhs, rhs;\nvector<int> st;\n\nvector<ll> get_right_out(const vector<ll>& a, vector<ll>& res) {\n    const int n = a.size();\n    st.clear();\n    res.assign(n+1, 0);\n\n    for (int i = 0; i < n; ++i) {\n        ll x = a[i] + res[i];\n        st.push_back(i);\n\n        while (x != 0) {\n            if (st.empty()) {\n                const int len = i + 1;\n                const ll cnt = x / (len + 1);\n                res[i+1] += cnt * len;\n                x -= cnt * (len + 1);\n\n                if (x != 0) {\n                    res[i+1] += x;\n                    st.push_back(x-1);\n                    x = 0;\n                }\n            } else {\n                const int j = st.back();\n                if (x > i - j) {\n                    res[i+1] += i - j;\n                    st.pop_back();\n                    x -= i - j + 1;\n                } else {\n                    res[i+1] += x;\n                    st.back() += x;\n                    x = 0;\n                }\n            }\n        }\n    }\n\n    return res;\n}\n\nvector<ll> get_left_out(vector<ll>& a, vector<ll>& b) {\n    reverse(a.begin(), a.end());\n    get_right_out(a, b);\n    reverse(b.begin(), b.end());\n    reverse(a.begin(), a.end());\n    return b;\n}\n\nvoid solve() {\n    int n; cin >> n;\n    \n    a.resize(n);\n    for (ll& x : a) cin >> x;\n\n    get_right_out(a, lhs);\n    get_left_out(a, rhs);\n\n    ll ans = 0;\n    for (int i = 0; i < n; ++i)\n        cout << lhs[i] + a[i] + rhs[i+1] << ' ';\n    cout << '\\n';\n}\n\nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n\n    int t = 1;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2059",
    "index": "A",
    "title": "Milya and Two Arrays",
    "statement": "An array is called good if for any element $x$ that appears in this array, it holds that $x$ appears at least twice in this array. For example, the arrays $[1, 2, 1, 1, 2]$, $[3, 3]$, and $[1, 2, 4, 1, 2, 4]$ are good, while the arrays $[1]$, $[1, 2, 1]$, and $[2, 3, 4, 4]$ are not good.\n\nMilya has two \\textbf{good} arrays $a$ and $b$ of length $n$. She can rearrange the elements in array $a$ in any way. After that, she obtains an array $c$ of length $n$, where $c_i = a_i + b_i$ ($1 \\le i \\le n$).\n\nDetermine whether Milya can rearrange the elements in array $a$ such that there are \\textbf{at least $3$} distinct elements in array $c$.",
    "tutorial": "If there are at least three distinct values in any of the arrays, the answer is $yes$. We can select any three elements from the other array and arrange them in increasing order, then the corresponding sums will also increase. If each array contains exactly two distinct values, the answer is also $yes$. If we find elements $x$ and $y$ in the first array, where $x < y$, and elements $a$ and $b$ in the second array, such that $a < b$, we can match the elements to obtain the sums $x + a < x + b < y + b$. Since the arrays are good, $x$ appears at least twice, and all three sums can definitely be obtained. In the remaining cases, one of the arrays will contain only equal elements. Since the second array contains no more than $2$ distinct values, it will not be possible to obtain $3$ distinct sums.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nint a[55],b[55];\n \nvoid solve(){\n    int n;cin>>n;\n    set<int> sa,sb;\n    for(int i=1;i<=n;i++)cin>>a[i],sa.insert(a[i]);\n    for(int i=1;i<=n;i++)cin>>b[i],sb.insert(b[i]);\n    if(sa.size()+sb.size()<4){\n        cout<<\"NO\\n\";\n    }else{\n        cout<<\"YES\\n\";\n    }\n}\n \nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n \n    int t;cin>>t;\n    while(t--){\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2059",
    "index": "B",
    "title": "Cost of the Array",
    "statement": "You are given an array $a$ of length $n$ and an \\textbf{even} integer $k$ ($2 \\le k \\le n$). You need to split the array $a$ into exactly $k$ non-empty subarrays$^{\\dagger}$ such that each element of the array $a$ belongs to exactly one subarray.\n\nNext, all subarrays with even indices (second, fourth, $\\ldots$, $k$-th) are concatenated into a single array $b$. After that, $0$ is \\textbf{added} to the end of the array $b$.\n\nThe cost of the array $b$ is defined as the minimum index $i$ such that $b_i \\neq i$. For example, the cost of the array $b = [1, 2, 4, 5, 0]$ is $3$, since $b_1 = 1$, $b_2 = 2$, and $b_3 \\neq 3$. Determine \\textbf{the minimum} cost of the array $b$ that can be obtained with an optimal partitioning of the array $a$ into subarrays.\n\n$^{\\dagger}$An array $x$ is a subarray of an array $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.",
    "tutorial": "If $k = n$, then the partition is unique and the answer can be explicitly found. In all other cases, the answer does not exceed $2$. We want the second subarray of our partition to start not with $1$, while we can ignore all other subarrays, since in this case the answer will be $1$. We will iterate over the starting position of the second subarray, which can range from $2$ to $n - k + 2$. If we encounter only ones in this segment, then the second subarray can consist of $2$ ones, and the answer will be $2$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n    k /= 2;\n    vector<int> a(n);\n    for (auto &it: a) cin >> it;\n    if (2 * k == n) {\n        for (int i = 1; i < n; i += 2) {\n            if (a[i] != (i + 1) / 2) {\n                cout << (i + 1) / 2 << '\\n';\n                return;\n            }\n        }\n        cout << k + 1 << '\\n';\n    } else {\n        for (int i = 1; i <= n - 2 * k + 1; i++) {\n            if (a[i] != 1) {\n                cout << \"1\\n\";\n                return;\n            }\n        }\n        cout << \"2\\n\";\n    }\n}\n \nint main() {\n    int T = 1;\n    cin >> T;\n    while (T--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2059",
    "index": "C",
    "title": "Customer Service",
    "statement": "Nikyr has started working as a queue manager at the company \"Black Contour.\" He needs to choose the order of servicing customers. There are a total of $n$ queues, each initially containing $0$ people. In each of the next $n$ moments of time, there are \\textbf{two sequential} events:\n\n- New customers arrive in all queues. More formally, at the $j$-th moment of time, the number of people in the $i$-th queue increases by a \\textbf{positive} integer $a_{i,j}$.\n- Nikyr chooses \\textbf{exactly one} of the $n$ queues to be served at that moment in time. The number of customers in this queue becomes $0$.\n\nLet the number of people in the $i$-th queue after all events be $x_i$. Nikyr wants MEX$^{\\dagger}$ of the collection $x_1, x_2, \\ldots, x_n$ to be as large as possible. Help him determine the maximum value he can achieve with an optimal order of servicing the queues.\n\n$^{\\dagger}$The minimum excluded (MEX) of a collection of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $y$ which does not occur in the collection $c$.\n\nFor example:\n\n- $\\operatorname{MEX}([2,2,1])= 0$, since $0$ does not belong to the array.\n- $\\operatorname{MEX}([3,1,0,1]) = 2$, since $0$ and $1$ belong to the array, but $2$ does not.\n- $\\operatorname{MEX}([0,3,1,2]) = 4$, since $0$, $1$, $2$, and $3$ belong to the array, but $4$ does not.",
    "tutorial": "At the last moment in time, we clear some queue, and it will have an empty number of people left, so among the $x_i$, there is guaranteed to be a $0$. To maximize the value of $MEX$, it is necessary for the value $1$ to appear among the $x_i$. However, a positive number of people was added to each queue at the last moment in time. Thus, if $1$ appears among the $x_i$, then the $i$-th queue was served in the penultimate moment in time. We can continue this reasoning and conclude that if we find $x_i$ with values from $0$ to $k$, then the value $k + 1$ could only have been obtained if, in some queue different from these, one was added in each of the last $k + 1$ moments in time, and in the $k + 2$-th moment from the end, that queue was empty. Let's calculate the maximum suffix consisting only of $1$s in the array of additions for each queue. If a queue has a suffix of $m$ ones, then after all events in that queue, we could leave any number from $0$ to $m$, which will participate in $MEX$. To solve this, we will greedily collect the answer by taking the smallest suitable suffix each time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nconst int N=305;\n \nint a[N][N],suff[N];\n \nvoid solve(){\n    int n;cin>>n;\n    for(int i=1;i<=n;i++){\n        suff[i]=0;\n        for(int j=1;j<=n;j++){\n            cin>>a[i][j];\n        }\n    }\n    for(int i=1;i<=n;i++){\n        for(int j=n;j>=1;j--){\n            if(a[i][j]!=1)break;\n            suff[i]++;\n        }\n    }\n    multiset<int> s;\n    for(int i=1;i<=n;i++){\n        s.insert(suff[i]);\n    }\n    int ans=1;\n    while(!s.empty()){\n        int cur=*s.begin();\n        if(cur>=ans){\n            ans++;\n        }\n        s.extract(cur);\n    }\n    cout<<min(ans,n)<<'\\n';\n}\n \nint main(){\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n \n    int t;cin>>t;\n    while(t--){\n        solve();\n    }\n \n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "graph matchings",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2059",
    "index": "D",
    "title": "Graph and Graph",
    "statement": "You are given two connected undirected graphs with the same number of vertices. In both graphs, there is a token located at some vertex. In the first graph, the token is initially at vertex $s_1$, and in the second graph, the token is initially at vertex $s_2$. The following operation is repeated an \\textbf{infinite} number of times:\n\n- Let the token currently be at vertex $v_1$ in the first graph and at vertex $v_2$ in the second graph.\n- A vertex $u_1$, adjacent to $v_1$, is chosen in the first graph.\n- A vertex $u_2$, adjacent to $v_2$, is chosen in the second graph.\n- The tokens are moved to the chosen vertices: in the first graph, the token moves from $v_1$ to $u_1$, and in the second graph, from $v_2$ to $u_2$.\n- The cost of such an operation is equal to $|u_1 - u_2|$.\n\nDetermine the minimum possible total cost of all operations or report that this value will be infinitely large.",
    "tutorial": "First, we need to understand when the answer is less than infinity. For this to happen, the first token in the first graph must be at vertex $v$, and the second token in the second graph must also be at the vertex with the same number $v$. Additionally, there must be an identical edge from $v$ to $u$ in both graphs for some $u$. If we find ourselves in such a situation, the tokens (each in their respective graph) can move along this edge back and forth as many times as needed with a cost of $0$. Let's first identify all the vertices $v$ (which we will call good) that have this property, and then we will calculate the minimum cost to reach any of these vertices. We will create a new graph where each vertex corresponds to a specific state, and the edges represent transitions between states. We will define a state as a pair $v_1, v_2$, which indicates that the first token is currently at vertex $v_1$, and the second token is at vertex $v_2$. The number of vertices in this graph will be $n^2$. A vertex will have $deg(v_1) \\cdot deg(v_2)$ edges (where $deg(v)$ is the degree of $v$ in the graph where this vertex is located). Given the overall constraint on the sum of $deg(v)$, the number of edges in the new state graph will not exceed $m_1 \\cdot m_2$. Let's run Dijkstra's algorithm on this graph and take the distance to the pair of good vertices.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \n#define int long long\n#define eb emplace_back\n \nconst int INF = 1e18;\n \nvoid solve() {\n    int n, s1, s2;\n    cin >> n >> s1 >> s2;\n    s1--, s2--;\n    vector<vector<int>> g1(n), g2(n);\n    vector<bool> good(n);\n    set<pair<int, int>> edges;\n    int m1;\n    cin >> m1;\n    for (int i = 0; i < m1; i++) {\n        int v, u;\n        cin >> v >> u;\n        v--, u--;\n        if (v > u)\n            swap(v, u);\n        edges.insert({v, u});\n        g1[v].eb(u);\n        g1[u].eb(v);\n    }\n    int m2;\n    cin >> m2;\n    for (int i = 0; i < m2; i++) {\n        int v, u;\n        cin >> v >> u;\n        v--, u--;\n        if (v > u)\n            swap(v, u);\n        if (edges.find({v, u}) != edges.end())\n            good[v] = true, good[u] = true;\n        g2[v].eb(u);\n        g2[u].eb(v);\n    }\n    vector<vector<int>> d(n, vector<int> (n, INF));\n    d[s1][s2] = 0;\n    set<pair<int, pair<int, int>>> st;\n    st.insert({0, {s1, s2}});\n    while (!st.empty()) {\n        auto [v, u] = st.begin()->second;\n        st.erase(st.begin());\n        for (auto to1 : g1[v]) {\n            for (auto to2 : g2[u]) {\n                int w = abs(to1 - to2);\n                if (d[to1][to2] > d[v][u] + w) {\n                    st.erase({d[to1][to2], {to1, to2}});\n                    d[to1][to2] = d[v][u] + w;\n                    st.insert({d[to1][to2], {to1, to2}});\n                }\n            }\n        }\n    }\n    int ans = INF;\n    for (int i = 0; i < n; i++) {\n        if (!good[i])\n            continue;\n        ans = min(ans, d[i][i]);\n    }\n    if (ans == INF)\n        ans = -1;\n    cout << ans << '\\n';\n}\n \nsigned main() {\n    //cout << fixed << setprecision(5);\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int T = 1;\n    cin >> T;\n    //cin >> G;\n    while (T--)\n        solve();\n    return 0;\n}\n",
    "tags": [
      "data structures",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2059",
    "index": "E1",
    "title": "Stop Gaming (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version you only need to find the minimum number of operations. You can hack only if you solved all versions of this problem.}\n\nYou are given $n$ arrays, each of which has a length of $m$. Let the $j$-th element of the $i$-th array be denoted as $a_{i, j}$. It is guaranteed that all $a_{i, j}$ are \\textbf{pairwise distinct}. In one operation, you can do the following:\n\n- Choose some integer $i$ ($1 \\le i \\le n$) and an integer $x$ ($1 \\le x \\le 2 \\cdot n \\cdot m$).\n- For all integers $k$ from $i$ to $n$ in increasing order, do the following:\n\n- Add the element $x$ to the beginning of the $k$-th array.\n- Assign $x$ the value of the last element in the $k$-th array.\n- Remove the last element from the $k$-th array.\n\nIn other words, you can insert an element at the beginning of any array, after which all elements in this and all following arrays are shifted by one to the right. The last element of the last array is removed.\n\nYou are also given a description of the arrays that need to be obtained after all operations. That is, after performing the operations, the $j$-th element of the $i$-th array should be equal to $b_{i, j}$. It is guaranteed that all $b_{i, j}$ are \\textbf{pairwise distinct}.\n\nDetermine the minimum number of operations that need to be performed to obtain the desired arrays.",
    "tutorial": "Let's connect the hints together: we will iterate through the prefix of elements that were originally in the array and have not been removed from the end. We still need to understand when the prefix can be extended to the final array. We will look at the positions of elements from the current prefix, after which in the final array there are elements that do not belong to the current prefix. Claim: For a sequence of actions to exist that leads to the final array, it is necessary and sufficient that for each such element, if it was in its array at position $i$ (in the original array of arrays), there must be at least $m - i$ elements in the final array that do not belong to the current prefix before it. Proof: Necessity. Suppose there is an element that does not satisfy the above condition. Then for any sequence of actions that does not disrupt the order of elements before it, it will never be at the end of its array, meaning it is impossible to insert an element that does not belong to the prefix between it and the next ball. Therefore, in the final array, an element from the current prefix will follow it, which is a contradiction. Sufficiency. To prove sufficiency, we will use induction on the number of elements from the current prefix, after which in the final array there are elements that do not belong to the current prefix. For $n = 1$, this is obviously true. For $n + 1$, we obtain the existence of an algorithm for $n$ elements, where we added at least $m - i$ elements if the current element is at position $i$. Then we will follow this sequence of actions for the first $m - i$ additions. At this point, the $n + 1$-th element will be at the end of the flask. We will add all the elements that should be after it and not in the current prefix in the correct order, and then finish the existing sequence of actions for all previous elements. To check this condition, it is sufficient to iterate through the prefixes and build a subsequence while maintaining whether it is possible to construct with the prefix of elements up to the last element, after which in the final array there are elements that do not belong to the current prefix, and how many elements that do not belong to the current prefix are in the final array before the current element.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n * m + 1), b(n * m + 1);\n    vector<deque<int>> mat(n + 1, deque<int> (m));\n    for (int i = 1; i <= n; i++) {\n        for (int j = 0; j < m; j++) {\n            int ind = j + 1 + (i - 1) * m;\n            mat[i][j] = ind;\n            cin >> a[ind];\n        }\n    }\n    for (int i = 1; i <= n * m; i++)\n        cin >> b[i];\n    map<int, int> mp;\n    for (int i = 1; i <= n * m; i++)\n        mp[b[i]] = i;\n    vector<int> s(n * m + 1), pos(n * m + 1, -1);\n    for (int i = 1; i <= n * m; i++) {\n        if (mp.find(a[i]) != mp.end())\n            pos[i] = mp[a[i]];\n        else\n            break;\n    }\n    pos[0] = 0;\n    int skipped = 0, pref = 0;\n    bool prev = true;\n    for (int i = 1; i <= n * m; i++) {\n        if (pos[i - 1] > pos[i])\n            break;\n        int d = pos[i] - pos[i - 1] - 1;\n        if (prev)\n            skipped += d;\n        else if (d > 0)\n            break;\n        if (skipped >= m - 1)\n            prev = true;\n        else if ((i - 1) % m > (i + skipped - 1) % m || (i + skipped) % m == 0)\n            prev = true;\n        else\n            prev = false;\n        if (prev)\n            pref = i;\n    }\n    cout << n * m - pref << '\\n';\n}\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int T = 1;\n    cin >> T;\n    while (T--)\n        solve();\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "hashing",
      "strings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2059",
    "index": "E2",
    "title": "Stop Gaming (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version you need to output all the operations that need to be performed. You can hack only if you solved all versions of this problem.}\n\nYou are given $n$ arrays, each of which has a length of $m$. Let the $j$-th element of the $i$-th array be denoted as $a_{i, j}$. It is guaranteed that all $a_{i, j}$ are \\textbf{pairwise distinct}. In one operation, you can do the following:\n\n- Choose some integer $i$ ($1 \\le i \\le n$) and an integer $x$ ($1 \\le x \\le 2 \\cdot n \\cdot m$).\n- For all integers $k$ from $i$ to $n$ in increasing order, do the following:\n\n- Add the element $x$ to the beginning of the $k$-th array.\n- Assign $x$ the value of the last element in the $k$-th array.\n- Remove the last element from the $k$-th array.\n\nIn other words, you can insert an element at the beginning of any array, after which all elements in this and all following arrays are shifted by one to the right. The last element of the last array is removed.\n\nYou are also given a description of the arrays that need to be obtained after all operations. That is, after performing the operations, the $j$-th element of the $i$-th array should be equal to $b_{i, j}$. It is guaranteed that all $b_{i, j}$ are \\textbf{pairwise distinct}.\n\nDetermine the minimum number of operations that need to be performed to obtain the desired arrays, and also output the sequence of all operations itself.",
    "tutorial": "Let's find the answer to problem E1. We just need to restore the necessary sequence of actions. Let's take a closer look at the inductive proof from E1. Notice that it represents an algorithm where at each step we find the rightmost element at the end of some array after which we need to add something. Thus, such an algorithm will definitely lead to the answer. The only difficulty lies in finding the rightmost element after which something needs to be inserted. We will maintain a data structure (let's call it a segment tree) on the indices from the prefix of the remaining balls. In the $i$-th cell, we will store the number of elements that need to be added for this element to become the last in its array if something needs to be added after it; otherwise, it will be 0. When adding the next element after the $i$-th, we will subtract 1 from the suffix after it. To find the rightmost element at the end of some array after which something needs to be added, we will look for the rightmost zero in the segment tree, and when we have performed all actions for a certain element, we will write a very large number in its cell so that it never appears again.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define eb emplace_back\n#define int long long\n#define all(x) x.begin(), x.end()\n#define fi first\n#define se second\n\nconst int INF = 1e9 + 1000;\n \nstruct segtree {\n    vector<pair<int, int>> tree;\n    vector<int> ass;\n    int size = 1;\n \n    void init(vector<int> &a) {\n        while (a.size() >= size) {\n            size <<= 1;\n        }\n        tree.assign(2 * size, {});\n        ass.assign(2 * size, 0);\n        build(0, 0, size, a);\n    }\n \n    void build(int x, int lx, int rx, vector<int> &a) {\n        if (rx - lx == 1) {\n            tree[x].se = lx;\n            if (lx < a.size()) {\n                tree[x].fi = a[lx];\n            } else {\n                tree[x].fi = INF;\n            }\n            return;\n        }\n        int m = (lx + rx) / 2;\n        build(2 * x + 1, lx, m, a);\n        build(2 * x + 2, m, rx, a);\n        tree[x] = min(tree[2 * x + 1], tree[2 * x + 2]);\n    }\n \n    void push(int x, int lx, int rx) {\n        tree[x].fi += ass[x];\n        if (rx - lx == 1) {\n            ass[x] = 0;\n            return;\n        }\n        ass[2 * x + 1] += ass[x];\n        ass[2 * x + 2] += ass[x];\n        ass[x] = 0;\n    }\n \n    void update(int l, int r, int val, int x, int lx, int rx) {\n        push(x, lx,  rx);\n        if (l <= lx && rx <= r) {\n            ass[x] += val;\n            push(x, lx, rx);\n            return;\n        }\n        if (rx <= l || r <= lx) {\n            return;\n        }\n        int m = (lx + rx) / 2;\n        update(l, r, val, 2 * x + 1, lx, m);\n        update(l, r, val, 2 * x + 2, m, rx);\n        tree[x] = min(tree[2 * x + 1], tree[2 * x + 2]);\n    }\n \n    void update(int l, int r, int val) {\n        update(l, r + 1, val, 0, 0, size);\n    }\n \n    int req(int x, int lx, int rx) {\n        push(x, lx, rx);\n        if (rx - lx == 1) {\n            return tree[x].se;\n        }\n        int m = (lx + rx) / 2;\n        push(2 * x + 1, lx, m);\n        push(2 * x + 2, m, rx);\n        if (tree[2 * x + 2].fi == 0) {\n            return req(2 * x + 2, m, rx);\n        } else {\n            return req(2 * x + 1, lx, m);\n        }\n    }\n \n    int req() {\n        return req(0, 0, size);\n    }\n};\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n * m + 1), b(n * m + 1);\n    for (int i = 1; i <= n; i++) {\n        for (int j = 0; j < m; j++) {\n            int ind = j + 1 + (i - 1) * m;\n            cin >> a[ind];\n        }\n    }\n    for (int i = 1; i <= n * m; i++)\n        cin >> b[i];\n    map<int, int> mp;\n    for (int i = 1; i <= n * m; i++)\n        mp[b[i]] = i;\n    vector<int> s(n * m + 1), pos(n * m + 1, -1);\n    for (int i = 1; i <= n * m; i++) {\n        if (mp.find(a[i]) != mp.end())\n            pos[i] = mp[a[i]];\n        else\n            break;\n    }\n    pos[0] = 0;\n    int skipped = 0, pref = 0;\n    bool prev = true;\n    for (int i = 1; i <= n * m; i++) {\n        if (pos[i - 1] > pos[i])\n            break;\n        int d = pos[i] - pos[i - 1] - 1;\n        if (prev)\n            skipped += d;\n        else if (d > 0)\n            break;\n        if (skipped >= m - 1)\n            prev = true;\n        else if ((i - 1) % m > (i + skipped - 1) % m || (i + skipped) % m == 0)\n            prev = true;\n        else\n            prev = false;\n        if (prev)\n            pref = i;\n    }\n    for (int i = 1; i <= pref; i++) {\n        s[i - 1] = pos[i] - pos[i - 1] - 1;\n    }\n    s[pref] = n * m - pos[pref];\n \n    vector<pair<int, int>> ans;\n \n    int res = 0;\n    for (int i = 0; i <= n * m; i++) {\n        res += s[i];\n    }\n    vector<int> ost(pref + 1);\n    for (int i = 1; i <= pref; i++) {\n        ost[i] = (m - i % m) % m;\n    }\n    for (int i = 0; i <= pref; i++) {\n        if (s[i] == 0) {\n            ost[i] = INF;\n        }\n    }\n    vector<int> gol(pref + 1);\n    gol[0] = 1;\n    for (int i = 1; i <= pref; i++) {\n        gol[i] = (i + m - 1) / m + 1;\n    }\n \n    segtree tree;\n \n    tree.init(ost);\n \n    for (int step = 0; step < res; step++) {\n        int chel = tree.req();\n        ans.eb(gol[chel], b[pos[chel] + s[chel]]);\n        tree.update(chel + 1, pref, -1);\n        s[chel]--;\n        if (s[chel] == 0) {\n            tree.update(chel, chel, INF);\n        }\n    }\n \n    cout << ans.size() << '\\n';\n    for (auto [i, col] : ans) {\n        cout << i << \" \" << col << '\\n';\n    }\n}\n \nsigned main() {\n    //cout << fixed << setprecision(5);\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int T = 1;\n    cin >> T;\n    //cin >> G;\n    while (T--)\n        solve();\n    return 0;\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "hashing",
      "strings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2060",
    "index": "A",
    "title": "Fibonacciness",
    "statement": "There is an array of $5$ integers. Initially, you only know $a_1,a_2,a_4,a_5$. You may set $a_3$ to any positive integer, negative integer, or zero. The Fibonacciness of the array is the number of integers $i$ ($1 \\leq i \\leq 3$) such that $a_{i+2}=a_i+a_{i+1}$. Find the maximum Fibonacciness over all integer values of $a_3$.",
    "tutorial": "We can notice that the possible values of $a_3$ ranges from $-99$ to $200$. Thus, we can iterate over all values of $a_3$ from $-99$ to $200$, and for each value, compute the Fibonacciness of the sequence. The maximal of all these values gives the solution to the problem. Time Complexity : $O(3*a_{max})$ $a_3$ can be represented as either of the following: $a_3 = a_1 + a_2$, or $a_3 = a_4 - a_2$, or $a_3 = a_5 - a_4$. These are at most 3 possible values. Notice that any value of $a_3$ which increases the Fibonacciness must belong to one of the above values (Think why!). So, in order to increase the Fibonacciness of the sequence, we should choose the most frequent of the above values. Then, in the end, we can calculate the Fibonacciness of the sequence after choosing the best value for $a_3$. Time Complexity : $O(1)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n\nvoid tc () {\n    vll ve(4);\n    for (ll &i : ve) cin >> i;\n    set <ll> st;\n    st.insert(ve[3]-ve[2]);\n    st.insert(ve[2]-ve[1]);\n    st.insert(ve[0]+ve[1]);\n    cout << 4-st.size() << '\\n';\n}\n\nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}",
    "tags": [
      "brute force"
    ],
    "rating": 800
  },
  {
    "contest_id": "2060",
    "index": "B",
    "title": "Farmer John's Card Game",
    "statement": "Farmer John's $n$ cows are playing a card game! Farmer John has a deck of $n \\cdot m$ cards numbered from $0$ to $n \\cdot m-1$. He distributes $m$ cards to each of his $n$ cows.\n\nFarmer John wants the game to be fair, so each cow should only be able to play $1$ card per round. He decides to determine a turn order, determined by a permutation$^{\\text{∗}}$ $p$ of length $n$, such that the $p_i$'th cow will be the $i$'th cow to place a card on top of the center pile in a round.\n\nIn other words, the following events happen in order in each round:\n\n- The $p_1$'th cow places any card from their deck on top of the center pile.\n- The $p_2$'th cow places any card from their deck on top of the center pile.\n- ...\n- The $p_n$'th cow places any card from their deck on top of the center pile.\n\nThere is a catch. Initially, the center pile contains a card numbered $-1$. In order to place a card, the number of the card must be greater than the number of the card on top of the center pile. Then, the newly placed card becomes the top card of the center pile. If a cow cannot place any card in their deck, the game is considered to be lost.\n\nFarmer John wonders: does there exist $p$ such that it is possible for all of his cows to empty their deck after playing all $m$ rounds of the game? If so, output any valid $p$. Otherwise, output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ contains each integer from $1$ to $n$ exactly once\n\\end{footnotesize}",
    "tutorial": "Assume the cows are initially ordered correctly. A solution exists if the first cow can place $0$, the second cow can place $1$, and so on, continuing with the first cow placing $n$, the second cow placing $n+1$, and so forth. Observing the pattern, the first cow must be able to place ${0, n, 2n, \\dots}$, the second ${1, n+1, 2n+1, \\dots}$, and in general, the $i$-th cow (where $i \\in [0, n-1]$) must be able to place ${i, n+i, 2n+i, \\dots}$. For each cow, sorting their cards reveals whether they satisfy this condition: the difference between adjacent cards in the sorted sequence must be $n$. If any cow's cards do not meet this criterion, the solution does not exist, and we output $-1$. If the cows are not ordered correctly, we need to rearrange them. To construct the solution, find the index of the cow holding card $i$ for each $i \\in [0, n-1]$. Since the cards of each cow are sorted, denote $\\texttt{min_card}$ as the smallest card a cow holds. Using an array $p$, iterate over each cow $c$ from $0$ to $n-1$ and set $p_\\texttt{min_card} = c$. Finally, iterate $i$ from $0$ to $n-1$ and output $p_i$. Time Complexity : $O(nmlog(m))$. Note that sorting is not necessary, and a solution with complexity up to $O((nm)^2)$ will still pass.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n\nvoid tc () {\n    ll n, m;\n    cin >> n >> m;\n    vector <vll> ve(n, vll(m));\n    vll p(n, -16);\n    bool val = true;\n    ll c = 0;\n    for (vll &we : ve) {\n        for (ll &i : we) cin >> i;\n        ll minN = *min_element(we.begin(), we.end());\n        if (minN < n) p[minN] = c++;\n        val &= minN < n;\n        sort(we.begin(), we.end());\n        ll last = we[0]-n;\n        for (ll i : we) {\n            val &= last+n == i;\n            last = i;\n        }\n    }\n    if (!val) {\n        cout << \"-1\\n\";\n        return;\n    }\n    for (ll i : p) cout << i+1 << ' ';\n    cout << '\\n';\n}\n\nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2060",
    "index": "C",
    "title": "Game of Mathletes",
    "statement": "Alice and Bob are playing a game. There are $n$ (\\textbf{$n$ is even}) integers written on a blackboard, represented by $x_1, x_2, \\ldots, x_n$. There is also a given integer $k$ and an integer score that is initially $0$. The game lasts for $\\frac{n}{2}$ turns, in which the following events happen sequentially:\n\n- Alice selects an integer from the blackboard and erases it. Let's call Alice's chosen integer $a$.\n- Bob selects an integer from the blackboard and erases it. Let's call Bob's chosen integer $b$.\n- If $a+b=k$, add $1$ to score.\n\nAlice is playing to minimize the score while Bob is playing to maximize the score. Assuming both players use optimal strategies, what is the score after the game ends?",
    "tutorial": "Note that Bob has all the power in this game, because the order in which Alice picks numbers is irrelevant, since Bob can always pick the optimal number to give himself a point. Therefore, we can just ignore Alice and play the game from Bob's perspective. From this point on, a \"paired\" number is any number $a$ on the blackboard such that there exists a $b$ on the blackboard such that $a+b=k$. Bob's strategy is as follows: if Alice picks a paired number, Bob should pick the other number in the pair. if Alice picks a paired number, Bob should pick the other number in the pair. if Alice picks an unpaired number, Bob can pick any other unpaired number, it doesn't matter which. if Alice picks an unpaired number, Bob can pick any other unpaired number, it doesn't matter which. This always works because the number of \"unpaired numbers\" is always even, since $n$ is even and the number of \"paired numbers\" will always be even. Therefore, for every unpaired number Alice picks, Bob will always have an unpaired number to respond with. Therefore, the final score is just the number of pairs in the input. To count them, use a map of counts $c$ such that $c_x$ is the number of occurrences of $x$ on the whiteboard. Then, for each number from $1$ to $\\lfloor \\frac{k}{2} \\rfloor$, take the minimum of $c_x$ and $c_{k-x}$, and add that to the total. Remember the edge case where $k$ is even and $x = \\frac{k}{2}$. The number of pairs here is just $\\lfloor \\frac{c_x}{2} \\rfloor$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n\nvoid tc () {\n    ll n, k;\n    cin >> n >> k;\n    vll ve(n);\n    for (ll &i : ve) cin >> i;\n    vll th(k+1, 0);\n    for (ll i : ve) {\n        if (i >= k) continue;\n        th[i]++;\n    }\n    ll ans = 0;\n    for (ll i = 1; i < k; i++) {\n        if (i == k-i) {\n            ans += th[i]/2;\n            continue;\n        }\n        ll minN = min(th[i], th[k-i]);\n        th[i] -= minN;\n        th[k-i] -= minN;\n        ans += minN;\n    }\n    cout << ans << '\\n';\n}\n\nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}",
    "tags": [
      "games",
      "greedy",
      "sortings",
      "two pointers"
    ],
    "rating": 900
  },
  {
    "contest_id": "2060",
    "index": "D",
    "title": "Subtract Min Sort",
    "statement": "You are given a sequence $a$ consisting of $n$ positive integers.\n\nYou can perform the following operation any number of times.\n\n- Select an index $i$ ($1 \\le i < n$), and subtract $\\min(a_i,a_{i+1})$ from both $a_i$ and $a_{i+1}$.\n\nDetermine if it is possible to make the sequence \\textbf{non-decreasing} by using the operation any number of times.",
    "tutorial": "For clarity, let's denote $op_i$ as an operation performed on $a_i$ and $a_{i+1}$. Claim: if it is possible, then the sequence of operations $op_1,op_2,\\ldots,op_{n-1}$ will sort the array. Proof: Let $b$ be any sequence of operations that will sort the array. Let's transform the sequence $b$ such that it becomes $[op_1,op_2,\\ldots,op_{n-1}]$. First, let's note that an $op_i$ does nothing if $a_i=0$ or $a_{i+1}=0$. Additionally, after $op_i$, at least one of ${a_i,a_{i+1}}$ will become zero. Thus, we can remove all duplicates in $b$ without altering the result. Now, let $x$ be the largest number such that $op_x$ is in $b$. Since at least one of $a_x,a_{x+1}$ will be zero, operations must be performed such that each of $a_1,a_2,\\ldots,a_{x-1}$ are zero. Let $S$ be the set of indices with $i<x$ such that $op_i$ is not in $b$. Note that we can simply append each operation in $S$ at the end of $b$ without altering the result, since all elements before $a_x$ are already zero. Our sequence of operations now contain a permutation of $op_1,op_2,\\ldots,op_x$, and we have ensured that all of $a_1,a_2,\\ldots,a_x=0$. Since the sequence is now sorted, we can in fact continue performing $op_{x+1},op_{x+2},\\ldots,op_{n-1}$ in this order. Notice that this sequence of operations will keep our array sorted, as $op_y$ will make $a_y=0$ (since $a_y<a{y+1}$). Let's show that we can rearrange our operations such that $1$ comes first. There are two cases: either $op_1$ comes before $op_2$, or $op_2$ comes before $op_1$. In the first case, notice that no operation done before $op_1$ will impact either the value of $a_1$ or $a_2$, so rearranging such that $op_1$ comes first does not impact the final results. In the second case, notice that after $op_2$ is done, we must have $a_1=a_2$, as otherwise $op_1$ will not simultaneously make $a_1=a_2=0$. This implies that right before $op_2$ is performed, we must have $a_1+a_3=a_2$. Then, rearranging the operations such that $op_1$ comes first will not impact the final result. Using the same line of reasoning, we can make $op_2$ the second operation, then $op_3$, and so on. To solve the problem, we can simply simulate the operations in this order, and then check if the array is sorted at the end. Time Complexity : $O(n)$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n\nvoid tc () {\n    ll n;\n    cin >> n;\n    vll ve(n);\n    for (ll &i : ve) cin >> i;\n    ll j = 0;\n    for (ll i = 1; i < n; i++) {\n        if (ve[i-1] > ve[i]) j = i;\n    }\n    if (j == 0) { // all done\n        cout << \"YES\\n\";\n        return;\n    }\n    auto fop = [&](ll i) {\n        ll minN = min(ve[i], ve[i+1]);\n        ve[i] -= minN;\n        ve[i+1] -= minN;\n    };\n    for (ll i = 0; i < j; i++) {\n        fop(i);\n    }\n    cout << (is_sorted(ve.begin(), ve.end()) ? \"YES\" : \"NO\") << '\\n';\n}\n\nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}\n",
    "tags": [
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2060",
    "index": "E",
    "title": "Graph Composition",
    "statement": "You are given two simple undirected graphs $F$ and $G$ with $n$ vertices. $F$ has $m_1$ edges while $G$ has $m_2$ edges. You may perform one of the following two types of operations any number of times:\n\n- Select two integers $u$ and $v$ ($1 \\leq u,v \\leq n$) such that there is an edge between $u$ and $v$ in $F$. Then, remove that edge from $F$.\n- Select two integers $u$ and $v$ ($1 \\leq u,v \\leq n$) such that there is no edge between $u$ and $v$ in $F$. Then, add an edge between $u$ and $v$ in $F$.\n\nDetermine the minimum number of operations required such that for all integers $u$ and $v$ ($1 \\leq u,v \\leq n$), there is a path from $u$ to $v$ in $F$ \\textbf{if and only if} there is a path from $u$ to $v$ in $G$.",
    "tutorial": "Let's solve the problem for each operation. First, consider the operation that removes an edge from $F$. Divide $G$ into its connected components and assign each vertex a component index. Then, for each edge in $F$, if it connects vertices with different component indices, remove it and increment the operation count. This guarantees no path between $x$ and $y$ in $F$ if there is none in $G$. Next, to ensure a path exists between $x$ and $y$ in $F$ if there is one in $G$, we divide $F$ into connected components. After removing excess edges, each component of $F$ only contains vertices of the same component index. The number of operations needed now is the difference between the number of connected components in $F$ and $G$. All operations can be efficiently performed using DFS or DSU.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(time(nullptr));\n\nconst int inf = 1e9;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nvoid Gdfs(int v, vector<vector<int>> &sl, vector<int> &col, int c){\n    col[v] = c;\n    for(int u: sl[v]){\n        if(col[u] == 0){\n            Gdfs(u, sl, col, c);\n        }\n    }\n}\n\nint Fdfs(int v, vector<vector<int>> &sl, vector<int> &col, vector<int> &old_col, int c){\n    col[v] = c;\n    int res = 0;\n    for(int u: sl[v]){\n        if(col[u] == 0){\n            if(old_col[u] != c) res++;\n            else res += Fdfs(u, sl, col, old_col, c);\n        }\n    }\n    return res;\n}\n\nvoid read_con_list(vector<vector<int>> &sl, int m){\n    for(int i = 0; i < m; ++i){\n        int u, v;\n        cin >> u >> v;\n        sl[--u].emplace_back(--v);\n        sl[v].emplace_back(u);\n    }\n}\n\nvoid solve(int tc){\n    int n, mf, mg;\n    cin >> n >> mf >> mg;\n    vector<vector<int>> fsl(n), gsl(n);\n    read_con_list(fsl, mf);\n    read_con_list(gsl, mg);\n\n    vector<int> fcol(n), gcol(n);\n    int ans = 0;\n    for(int i = 0; i < n; ++i){\n        if(gcol[i] == 0){\n            Gdfs(i, gsl, gcol, i + 1);\n        }\n        if(fcol[i] == 0){\n            ans += Fdfs(i, fsl, fcol, gcol, gcol[i]);\n            if(gcol[i] < i + 1) ans++;\n        }\n    }\n    cout << ans;\n}\n\nbool multi = true;\n\nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}\n",
    "tags": [
      "dfs and similar",
      "dsu",
      "graphs",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2060",
    "index": "F",
    "title": "Multiplicative Arrays",
    "statement": "You're given integers $k$ and $n$. For each integer $x$ from $1$ to $k$, count the number of integer arrays $a$ such that all of the following are satisfied:\n\n- $1 \\leq |a| \\leq n$ where $|a|$ represents the length of $a$.\n- $1 \\leq a_i \\leq k$ for all $1 \\leq i \\leq |a|$.\n- $a_1 \\times a_2 \\times \\dots \\times a_{|a|}=x$ (i.e., the product of all elements is $x$).\n\nNote that two arrays $b$ and $c$ are different if either their lengths are different, or if there exists an index $1 \\leq i \\leq |b|$ such that $b_i\\neq c_i$.\n\nOutput the answer modulo $998\\,244\\,353$.",
    "tutorial": "When $n$ is large, many of the array's elements will be $1$. The number of non-$1$ elements can't be so large. Try to precompute all arrays without $1$ and then use combinatorics. The naive solution is to define $f_k(n)$ as the number of arrays containing $n$ elements with a product of $k$. We could then try to compute this by considering the last element of the array among the divisors of $k$, giving us: $f_k(n)=\\sum_{j|k}f_j(n-1),$ with $f_k(1)=1$. The answers would then be $\\sum_{i=1}^{n}f_1(i),\\sum_{i=1}^{n}f_2(i),\\dots,\\sum_{i=1}^{n}f_k(i)$. However, this leads to an $O(nk\\log k)$ solution, which exceeds our time constraints. We need to optimize this approach. We can prove that there are at most $16$ non-$1$ elements in our arrays. This is because: The prime factorization of $k=p_1p_2\\cdots p_t$ divides $k$ into the most non-$1$ elements. With $17$ non-$1$ elements, the smallest possible value would be $k=2^{17}=131072>10^5$. Based on this observation, we can define our dynamic programming state as: Let $dp[i][j]$ represent the number of arrays with product $i$ containing only $j$ non-$1$ elements. The recurrence relation becomes: $dp[i][j]=\\sum_{p|i,p>1}dp[\\frac{i}{p}][j-1]$. Base case: $dp[i][1]=1$ for $i>1$. This computation has a time complexity of $O(k\\log^2k)$, as we perform $\\sum_{j=1}^{k}d(j)=O(k\\log{k})$ additions for each $i$. To calculate $f_k(n)$, we: Enumerate the number of non-$1$ elements from $1$ to $16$. For $j$ non-$1$ elements in the array: We have $n-j$ elements that are $1$. We need to choose $j$ positions for non-$1$ elements. Fill these positions with $dp[k][j]$ possible sequences. This gives us: $f_k(n)=\\sum_{j=1}^{16}\\binom{n}{j}dp[k][j].$ Therefore: $\\begin{align*} &\\sum_{i=1}^{n}f_k(n)\\\\ =&\\sum_{i=1}^{n}\\sum_{j=1}^{16}\\binom{i}{j}dp[k][j]\\\\ =&\\sum_{j=1}^{16}\\left(dp[k][j]\\sum_{i=1}^{n}\\binom{i}{j}\\right)\\\\ =&\\sum_{j=1}^{16}\\binom{n+1}{j+1}dp[k][j]. \\end{align*}$ Note that $\\sum_{i=1}^{n}\\binom{i}{j} = \\binom{n+1}{j+1}$ is given by the Hockey Stick Identity. Each answer can be calculated in $O(\\log^2k)$ time, giving an overall time complexity of $O(k\\log^2k)$. Let's revisit the naive approach and define $S_k(n)=\\sum_{i=1}^{n}f_{k}(n)$ as our answers. We can observe: $\\begin{align} f_{k}(n)&=\\sum_{j|k}f_j(n-1)\\nonumber\\\\ \\Leftrightarrow f_{k}(n)-f_{k}(n-1)&=\\sum_{j|k,j<k}f_j(n-1). \\end{align}$ Accumulating Formula $(1)$ yields: $\\begin{align} &&\\sum_{i=2}^{n}\\left(f_{k}(i)-f_{k}(i-1)\\right)&=\\sum_{i=2}^{n}\\sum_{j|k,j<k}f_j(i-1)\\nonumber\\\\ &\\Leftrightarrow& f_{k}(n)-f_{k}(1)&=\\sum_{j|k,j<k}\\sum_{i=1}^{n-1}f_{j}(i)\\nonumber\\\\ &\\Leftrightarrow& f_{k}(n)&=\\sum_{j|k,j<k}S_j(n-1)+1. \\end{align}$ By induction, we can prove that both $f_{k}(n)$ and $S_k(n)$ are polynomials. Let's denote: Degree of $f_k(n)$ as $p(k)$. Degree of $S_k(n)$ as $q(k)$. From the definition of $S_k(n)$, we have $q(k)=p(k)+1$. Formula $(2)$ gives us: $p(k)=\\max_{j|k,j<k}q(k)=\\max_{j|k,j<k}p(j)+1,$ with $p(1)=0$. By induction, we can show that $p(k)$ equals the number of primes in $k$'s prime factorization. Therefore, $p(k)\\le16$ and $q(k)\\le17$. Since $q(k)$ doesn't exceed $17$, we can: Precompute $S_k(1),S_k(2),S_k(3),\\dots,S_k(18)$. Use Lagrange Interpolation to compute any $S_k(n)$. This also yields an $O(k\\log^2k)$ time complexity.",
    "code": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Runtime.Serialization.Json;\nusing System.Text;\nusing System.Threading.Tasks;\nusing TemplateF;\n\n#if !PROBLEM\nSolutionF a = new();\na.Solve();\n#endif\n\nnamespace TemplateF\n{\n    internal class SolutionF\n    {\n        private readonly StreamReader sr = new(Console.OpenStandardInput());\n        private T Read<T>()\n            where T : struct, IConvertible\n        {\n            char c;\n            dynamic res = default(T);\n            dynamic sign = 1;\n            while (!sr.EndOfStream && char.IsWhiteSpace((char)sr.Peek())) sr.Read();\n            if (!sr.EndOfStream && (char)sr.Peek() == '-')\n            {\n                sr.Read();\n                sign = -1;\n            }\n            while (!sr.EndOfStream && char.IsDigit((char)sr.Peek()))\n            {\n                c = (char)sr.Read();\n                res = res * 10 + c - '0';\n            }\n            return res * sign;\n        }\n\n        private T[] ReadArray<T>(int n)\n            where T : struct, IConvertible\n        {\n            T[] arr = new T[n];\n            for (int i = 0; i < n; ++i) arr[i] = Read<T>();\n            return arr;\n        }\n\n        public void Solve()\n        {\n            StringBuilder output = new();\n            const int maxk = 100000, mod = 998244353, bw = 20;\n            List<int>[] d = new List<int>[maxk + 1];\n            for (int i = 1; i <= maxk; ++i) d[i] = new() { 1 };\n            for (int i = 2; i <= maxk; ++i) {\n                for (int j = i; j <= maxk; j += i) d[j].Add(i);\n            }\n            int[,] dp = new int[bw + 1, maxk + 1], S = new int[bw + 1, maxk + 1];\n            for (int k = 1; k <= maxk; ++k) dp[1, k] = S[1, k] = 1;\n            for (int i = 2; i <= bw; ++i) {\n                for (int j = 1; j <= maxk; ++j) {\n                    foreach (var k in d[j]) {\n                        dp[i, j] += dp[i - 1, k];\n                        dp[i, j] %= mod;\n                    }\n                    S[i, j] = (S[i - 1, j] + dp[i, j]) % mod;\n                }\n            }\n            int T = Read<int>();\n            while (T-- > 0)\n            {\n                int k = Read<int>(), n = Read<int>();\n                if (n <= bw) {\n                    for (int j = 1; j <= k; ++j) output.Append(S[n, j]).Append(' ');\n                } else {\n                    int _k = k;\n                    for (k = 1; k <= _k; ++k)  {\n                        long ans = 0;\n                        for (int i = 1; i <= bw; ++i) {\n                            long t = S[i, k];\n                            for (int j = 1; j <= bw; ++j) {\n                                if (j == i) continue;\n                                t *= n - j;\n                                t %= mod;\n                                t *= Inv((mod + i - j) % mod, mod);\n                                t %= mod;\n                            }\n                            ans = (ans + t) % mod;\n                        }\n                        output.Append(ans).Append(' ');\n                    }\n                }\n                output.AppendLine();\n            }\n            Console.Write(output.ToString());\n        }\n        public static long Inv(long a, long Mod) {\n            long u = 0, v = 1, m = Mod;\n            while (a > 0) {\n                long t = m / a;\n                m -= t * a; (a, m) = (m, a);\n                u -= t * v; (u, v) = (v, u);\n            }\n            return (u % Mod + Mod) % Mod;\n        }\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2060",
    "index": "G",
    "title": "Bugged Sort",
    "statement": "Today, Alice has given Bob arrays for him to sort in increasing order again! At this point, no one really knows how many times she has done this.\n\nBob is given two sequences $a$ and $b$, both of length $n$. All integers in the range from $1$ to $2n$ appear exactly once in either $a$ or $b$. In other words, the concatenated$^{\\text{∗}}$ sequence $a+b$ is a permutation$^{\\text{†}}$ of length $2n$.\n\nBob must sort \\textbf{both sequences} in increasing order \\textbf{at the same time} using Alice's swap function. Alice's swap function is implemented as follows:\n\n- Given two indices $i$ and $j$ ($i \\neq j$), it swaps $a_i$ with $b_j$, and swaps $b_i$ with $a_j$.\n\nGiven sequences $a$ and $b$, please determine if both sequences can be sorted in increasing order simultaneously after using Alice's swap function any number of times.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The concatenated sequence $a+b$ denotes the sequence $[a_1, a_2, a_3, \\ldots , b_1, b_2, b_3, \\ldots]$.\n\n$^{\\text{†}}$A permutation of length $m$ contains all integers from $1$ to $m$ in some order.\n\\end{footnotesize}",
    "tutorial": "Consider $(a_i, b_i)$ as the $i$-th pair. Can two elements ever become unpaired? No. Every operation keeps the pairs intact. The best way to think about the operation is like this: Swap the pairs at index $i$ and index $j$. Swap the pairs at index $i$ and index $j$. Flip each pair (swap $a_i$ with $b_i$, and $a_j$ with $b_j$). Flip each pair (swap $a_i$ with $b_i$, and $a_j$ with $b_j$). The operations allow us to swap two pairs, but it also results in both of them getting flipped. Is there any way to swap two pairs without flipping anything? It turns out there is, and there always is, because $n \\geq 3$. To swap pairs $i$ and $j$, follow this procedure: Pick any index $k$, where $k \\ne i$ and $k \\ne j$. Pick any index $k$, where $k \\ne i$ and $k \\ne j$. Do the operation on $i$ and $k$. Do the operation on $i$ and $k$. Do the operation on $j$ and $k$. Do the operation on $j$ and $k$. Finally, do the operation on $i$ and $k$ again. This results in the pair at index $k$ being unchanged, and the pairs at $i$ and $j$ simply being swapped. Finally, do the operation on $i$ and $k$ again. This results in the pair at index $k$ being unchanged, and the pairs at $i$ and $j$ simply being swapped. Can you flip two pairs without swapping them? Yes. Just perform the operation on pairs $i$ and $j$, and then follow the procedure from Hint 2, and you are effectively swapping, then \"swapping and flipping\", therefore the final result is simply a flip of two pairs. Can you flip one pair on its own? No, this is not possible due to the parity invariant. The operation involves performing two flips at the same time, which means that it is impossible to end up in a situation where the number of flips is odd. Read the hints first. Key observation: In the final solution, the pairs must be sorted in increasing order of $\\min(a_i, b_i)$. We prove this by contradiction. Suppose there exists a pair $(a_i, b_i)$, where $a_i < b_i$ and $a_i$ is smaller than the minimum element in the previous pair. In this case, it becomes impossible to place this pair after the previous one, as $a_i$ would always be smaller than the preceding element, regardless of orientation. Since all $a_i$ and $b_i$ are distinct, there is exactly one valid final ordering of the pairs. Moreover, this ordering is always reachable because we previously proved that any two pairs can be swapped without flipping their elements. Since swapping any two items in an array an arbitrary number of times allows for sorting by definition, we can sort the pairs in this order. Thus, the solution is to initially sort the pairs based on $\\min(a_i, b_i)$. Solution: The problem simplifies to determining whether flipping pairs allows sorting. We can solve this using dynamic programming (DP), defined as follows: $dp[1][i] = 1$ if it's possible to sort up and including pair $i$ using an even number of flips, where pair $i$ is not flipped. $dp[2][i] = 1$ if it's possible to sort up and including pair $i$ using an even number of flips, where pair $i$ is flipped. $dp[3][i] = 1$ if it's possible to sort up and including pair $i$ using an odd number of flips, where pair $i$ is not flipped. $dp[4][i] = 1$ if it's possible to sort up and including pair $i$ using an odd number of flips, where pair $i$ is flipped. The base cases are as follows: $dp[1][1] = 1$, because this represents the state where the first pair is not flipped, resulting in zero flips (which is even) $dp[4][1] = 1$, because this represents the state where the first pair is flipped, resulting in one flip (which is odd). There are eight possible transitions, as you can reach each of the four states from two previous states: you either choose to flip the current element or you don't. The final answer is $dp[1][n]$ $\\texttt{OR}$ $dp[2][n]$, because by Hints 3 and 4, we can only reach states where an even number of pairs are flipped from the starting position.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define F0R(i, n) for (int i = 0; i < n; i++)\n#define FOR(i, m, n) for (int i = m; i < n; i++)\n#define print pair<int, int>\n#define vp vector<print>\n#define ALL(x) (x).begin(), (x).end()\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    vp pairs(n);\n    F0R(i, n)\n    {\n        cin >> pairs[i].first;\n    }\n    F0R(i, n)\n    {\n        cin >> pairs[i].second;\n    }\n\n    sort(ALL(pairs), [](print a, print b)\n         { return min(a.first, a.second) < min(b.first, b.second); });\n\n    vector<vector<int>> dp(4, vector<int>(n, 0));\n    dp[0][0] = 1;\n    dp[3][0] = 1;\n    FOR(i, 1, n)\n    {\n        if (pairs[i - 1].first < pairs[i].first and pairs[i - 1].second < pairs[i].second)\n        {\n            dp[0][i] |= dp[0][i - 1];\n            dp[1][i] |= dp[1][i - 1];\n            dp[2][i] |= dp[3][i - 1];\n            dp[3][i] |= dp[2][i - 1];\n        }\n        if (pairs[i - 1].first < pairs[i].second and pairs[i - 1].second < pairs[i].first)\n        {\n            dp[0][i] |= dp[2][i - 1];\n            dp[1][i] |= dp[3][i - 1];\n            dp[2][i] |= dp[1][i - 1];\n            dp[3][i] |= dp[0][i - 1];\n        }\n    }\n    cout << ((dp[0][n - 1] | dp[2][n - 1]) ? \"YES\" : \"NO\") << endl;\n}\n\nsigned main()\n{\n    int tests;\n    cin >> tests;\n    F0R(test, tests)\n    {\n        solve();\n    }\n\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2061",
    "index": "A",
    "title": "Kevin and Arithmetic",
    "statement": "To train young Kevin's arithmetic skills, his mother devised the following problem.\n\nGiven $n$ integers $a_1, a_2, \\ldots, a_n$ and a sum $s$ initialized to $0$, Kevin performs the following operation for $i = 1, 2, \\ldots, n$ in order:\n\n- Add $a_i$ to $s$. If the resulting $s$ is even, Kevin earns a point and repeatedly divides $s$ by $2$ until it becomes odd.\n\nNote that Kevin can earn at most one point per operation, regardless of how many divisions he does.\n\nSince these divisions are considered more beneficial for Kevin's development, his mother wants to rearrange $a$ so that the number of Kevin's total points is maximized. Determine the maximum number of points.",
    "tutorial": "After the first operation, $s$ is always odd. You can only earn points when $a_i$ is odd after this operation. However, during the first operation, you can only earn a point if $a_i$ is even. Let $c_0$ and $c_1$ be the number of even and odd numbers, respectively. If there is at least one even number, you can place it first, making the answer $c_1 + 1$. Otherwise, since no points can be earned during the first operation, the answer is $c_1 - 1$. Time complexity: $O(n)$.",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2061",
    "index": "B",
    "title": "Kevin and Geometry",
    "statement": "Kevin has $n$ sticks with length $a_1,a_2,\\ldots,a_n$.\n\nKevin wants to select $4$ sticks from these to form an isosceles trapezoid$^{\\text{∗}}$ with a positive area. Note that rectangles and squares are also considered isosceles trapezoids. Help Kevin find a solution. If no solution exists, output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An isosceles trapezoid is a convex quadrilateral with a line of symmetry bisecting one pair of opposite sides. In any isosceles trapezoid, two opposite sides (the bases) are parallel, and the two other sides (the legs) are of equal length.\n\\end{footnotesize}",
    "tutorial": "Let $a$ and $b$ be the lengths of the two bases, and let $c$ be the length of the two legs. A necessary and sufficient condition for forming an isosceles trapezoid with a positive area is $|a - b| < 2c$, as the longest edge must be shorter than the sum of the other three edges. To determine whether an isosceles trapezoid can be formed, consider the following cases: If there are two distinct pairs of identical numbers that do not overlap, these pairs can always form an isosceles trapezoid. If there are no pairs of identical numbers, it is impossible to form an isosceles trapezoid. If there is exactly one pair of identical numbers, denoted by $c$, we will use them as the legs. Remove this pair and check whether there exist two other numbers whose difference is less than $2c$. This can be efficiently done by sorting the remaining numbers and checking adjacent pairs. The time complexity of this approach is $O(n \\log n)$.",
    "tags": [
      "binary search",
      "geometry"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2061",
    "index": "C",
    "title": "Kevin and Puzzle",
    "statement": "Kevin enjoys logic puzzles.\n\nHe played a game with $n$ classmates who stand in a line. The $i$-th person from the left says that there are $a_i$ liars to their left (not including themselves).\n\nEach classmate is either honest or a liar, with the restriction that \\textbf{no two liars can stand next to each other}. Honest classmates always say the truth. \\textbf{Liars can say either the truth or lies}, meaning their statements are considered unreliable.\n\nKevin wants to determine the number of distinct possible game configurations modulo $998\\,244\\,353$. Two configurations are considered different if at least one classmate is honest in one configuration and a liar in the other.",
    "tutorial": "For the $i$-th person, there are at most two possible cases: If they are honest, there are exactly $a_i$ liars to their left. If they are a liar, since two liars cannot stand next to each other, the $(i-1)$-th person must be honest. In this case, there are $a_{i-1} + 1$ liars to their left. Let $dp_i$ represent the number of possible game configurations for the first $i$ people, where the $i$-th person is honest. The transitions are as follows: If the $(i-1)$-th person is honest, check if $a_i = a_{i-1}$. If true, add $dp_{i-1}$ to $dp_i$. If the $(i-1)$-th person is a liar, check if $a_i = a_{i-2} + 1$. If true, add $dp_{i-2}$ to $dp_i$. The final answer is given by $dp_n + dp_{n-1}$. Time complexity: $O(n)$.",
    "tags": [
      "2-sat",
      "combinatorics",
      "dp"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2061",
    "index": "D",
    "title": "Kevin and Numbers",
    "statement": "Kevin wrote an integer sequence $a$ of length $n$ on the blackboard.\n\nKevin can perform the following operation any number of times:\n\n- Select two integers $x, y$ on the blackboard such that $|x - y| \\leq 1$, erase them, and then write down an integer $x + y$ instead.\n\nKevin wants to know if it is possible to transform these integers into an integer sequence $b$ of length $m$ through some sequence of operations.\n\nTwo sequences $a$ and $b$ are considered the same if and only if their multisets are identical. In other words, for any number $x$, the number of times it appears in $a$ must be equal to the number of times it appears in $b$.",
    "tutorial": "It can be challenging to determine how to merge small numbers into a larger number directly. Therefore, we approach the problem in reverse. Instead of merging numbers, we consider transforming the number $b$ back into $a$. For each number $x$, it can only be formed by merging $\\lceil \\frac{x}{2} \\rceil$ and $\\lfloor \\frac{x}{2} \\rfloor$. Thus, the reversed operation is as follows: Select an integer $x$ from $b$ and split it into $\\lceil \\frac{x}{2} \\rceil$ and $\\lfloor \\frac{x}{2} \\rfloor$. We can perform this splitting operation on the numbers in $b$ exactly $n - m$ times. If the largest number in $b$ also appears in $a$, we can remove it from both $a$ and $b$ simultaneously. Otherwise, the largest number in $b$ must be split into two smaller numbers. To efficiently manage the numbers in $a$ and $b$, we can use a priority queue or a multiset. The time complexity of this approach is $O((n + m) \\log (n + m))$.",
    "tags": [
      "bitmasks",
      "data structures"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2061",
    "index": "E",
    "title": "Kevin and And",
    "statement": "Kevin has an integer sequence $a$ of length $n$. At the same time, Kevin has $m$ types of magic, where the $i$-th type of magic can be represented by an integer $b_i$.\n\nKevin can perform at most $k$ (possibly zero) magic operations. In each operation, Kevin can do the following:\n\n- Choose two indices $i$ ($1\\leq i\\leq n$) and $j$ ($1\\leq j\\leq m$), and then update $a_i$ to $a_i\\ \\&\\ b_j$. Here, $\\&$ denotes the bitwise AND operation.\n\nFind the minimum possible sum of all numbers in the sequence $a$ after performing at most $k$ operations.",
    "tutorial": "For a fixed $p$, let $f(S)$ represent the number obtained after applying the operations in set $S$ to $p$. Define $g(i)$ as the minimum value of $f(S)$ for all subsets $S$ with $|S| = i$, i.e., $g(i) = \\min_{|S| = i} f(S)$. - Lemma: The function $g$ is convex, that is for all $i$ ($1 \\leq i < m$), the inequality $2g(i) \\leq g(i-1) + g(i+1)$ holds. Proof: Let $f(S)$ be the value corresponding to the minimum of $g(i-1)$, and let $f(T)$ correspond to the minimum of $g(i+1)$. Suppose the $w$-th bit is the highest bit where $f(S)$ and $f(T)$ differ. We can always find an operation $y \\in T \\setminus S$ that turns the $w$-th bit in $g(i-1)$ into $0$. In this case, we have: $g(i - 1) - f(S \\cup \\{y\\}) \\geq 2^w.$ Moreover, since the highest bit where $f(S \\cup {y})$ and $g(i+1)$ differ is no greater than $w-1$, we have: $f(S \\cup \\{y\\}) - g(i + 1) \\leq 2^w.$ Combining these inequalities gives: $2 g(i) \\leq 2 f(S \\cup \\{y\\}) \\leq g(i - 1) + g(i + 1),$ - For each number $a_i$, we can use brute force to compute the minimum value obtained after applying $j$ operations, denoted as $num(i, j)$. From the lemma, we know that the difference $num(i, k) - num(i, k - 1)$ is non-increasing. Thus, when performing operations on this number, the reductions in value are: $num(i, 0) - num(i, 1), num(i, 1) - num(i, 2), \\dots, num(i, m - 1) - num(i, m).$ You need to perform $k$ operations in total. To minimize the result, you can choose the $k$ largest reductions from all possible operations. This can be done by sorting all operations by their cost or by using std::nth_element. Time complexity: $O(n2^m + nm)$.",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2061",
    "index": "F2",
    "title": "Kevin and Binary String (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, string $t$ consists of '0', '1' and '?'. You can hack only if you solved all versions of this problem.}\n\nKevin has a binary string $s$ of length $n$. Kevin can perform the following operation:\n\n- Choose two adjacent blocks of $s$ and swap them.\n\nA block is a maximal substring$^{\\text{∗}}$ of identical characters. Formally, denote $s[l,r]$ as the substring $s_l s_{l+1} \\ldots s_r$. A block is $s[l,r]$ satisfying:\n\n- $l=1$ or $s_l\\not=s_{l-1}$.\n- $s_l=s_{l+1} = \\ldots = s_{r}$.\n- $r=n$ or $s_r\\not=s_{r+1}$.\n\nAdjacent blocks are two blocks $s[l_1,r_1]$ and $s[l_2,r_2]$ satisfying $r_1+1=l_2$.\n\nFor example, if $s=\\mathtt{000}\\,\\mathbf{11}\\,\\mathbf{00}\\,\\mathtt{111}$, Kevin can choose the two blocks $s[4,5]$ and $s[6,7]$ and swap them, transforming $s$ into $\\mathtt{000}\\,\\mathbf{00}\\,\\mathbf{11}\\,\\mathtt{111}$.\n\nGiven a string $t$ of length $n$ consisting of '0', '1' and '?', Kevin wants to determine the minimum number of operations required to perform such that for any index $i$ ($1\\le i\\le n$), if $t_i\\not=$ '?' then $s_i=t_i$. If it is impossible, output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\\end{footnotesize}",
    "tutorial": "First, we divide the string $s$ into blocks. Let's analyze the properties of the blocks in $s$ that do not move (to simplify corner cases, we can add a block with a different number at both ends of $s$): These blocks must alternate between $0$ and $1$. Between two immovable blocks, the $0$s will shift toward the same side as the adjacent block of $0$s, and the $1$s will shift toward the same side as the adjacent block of $1$s. For example, $\\mathtt{0100101101}$ will become $\\mathtt{0000011111}$ after the shifting process. This properties can be proven by induction. - Easy Version For the easy version, since the target string $t$ is known, we can greedily determine whether each block in $s$ can remain immovable. Specifically: For each block and the previous immovable block, check if the corresponding digits are different. Also, ensure that the numbers in the interval between the two blocks meet the conditions (i.e., the $0$s and $1$s in this interval must shift to their respective sides). This can be solved efficiently using prefix sums. If there are $x$ blocks between two immovable blocks, then $\\frac{x}{2}$ moves are required. Time complexity: $O(n)$. - Hard Version For the hard version, we use dynamic programming to determine which blocks can remain immovable. Let $dp(i)$ represent the minimum cost for the $i$-th block to remain immovable. We have: $dp(i) = \\min_{0\\leq j <i, (j, i) \\text{ is valid}} (dp(j) + (i - j - 1) / 2).$ Without loss of generality, assume that the $i$-th block is composed of $0$s. Let the distance between the $i$-th block and the nearest preceding $1$-block be $p$. The number of $0$s between blocks $j$ and $i$ cannot exceed $p$. There is a restriction: $j \\geq l_i$. Similarly, for $j$, we can derive a symmetric restriction: $i \\leq r_j$. We can use a segment tree to maintain the values of $2dp(j) - j$ for all valid $j$. Specifically: For a position $j$, if the current $i > r_j$, update the corresponding value to $+\\infty$. For each $i$, query the segment tree over the valid interval to compute the minimum efficiently. Time complexity: $O(n \\log n)$.",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2061",
    "index": "G",
    "title": "Kevin and Teams",
    "statement": "This is an interactive problem.\n\nKevin has $n$ classmates, numbered $1, 2, \\ldots, n$. Any two of them may either be friends or not friends.\n\nKevin wants to select $2k$ classmates to form $k$ teams, where each team contains exactly $2$ people. Each person can belong to at most one team.\n\nLet $u_i$ and $v_i$ be two people in the $i$-th team. To avoid potential conflicts during team formation, the team members must satisfy one of the following two conditions:\n\n- For all $i$ ($1\\leq i \\leq k$), classmate $u_i$ and $v_i$ are friends.\n- For all $i$ ($1\\leq i \\leq k$), classmate $u_i$ and $v_i$ are not friends.\n\nKevin wants to determine the maximum $k$ such that, regardless of the friendship relationships among the $n$ people, he can always find $2k$ people to form the teams. After that, he needs to form $k$ teams. But asking whether two classmates are friends is awkward, so Kevin wants to achieve this while asking about the friendship status of no more than $n$ pairs of classmates.\n\nThe interactor is \\textbf{adaptive}. It means that the hidden relationship between classmates is not fixed before the interaction and will change during the interaction.",
    "tutorial": "Using graph theory terminology, let edges labeled as $0$ be represented in red and edges labeled as $1$ be represented in blue. - We can prove that if a graph has $3k + 1$ vertices, the maximum matching will be at most $k$. To see this, you can construct a blue clique of size $2k+1$, with all other edges colored red. It is not hard to verify that the maximum matching in both colors is $k$. So the maximum matching you can find is $\\lfloor \\frac{n+1}{3} \\rfloor$. - To construct a matching, we can maintain a chain of edges of the same color. Suppose we currently have a red chain $p_1, p_2, \\dots, p_k$. Now, we want to add a new vertex $q$. We check the color of the edge between $p_k$ and $q$: If the edge is red, we add $q$ to the chain. If the edge is blue, $p_{k-1}, p_k, q$ will form a \"mixed-color triplet.\" In this case, we remove $p_{k-1}$ and $p_k$ from the chain. After at most $n-1$ queries, the graph will be divided into several \"mixed-color triplets\" and one chain of edges of the same color. For the chain of length $k$, we can find $\\lfloor \\frac{k}{2} \\rfloor$ matchings. For each \"mixed-color triplet\", we can always find one matching corresponding to the color. We can construct a matching of size $\\lfloor \\frac{n+1}{3} \\rfloor$.",
    "tags": [
      "constructive algorithms",
      "graphs",
      "interactive"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2061",
    "index": "H2",
    "title": "Kevin and Stones (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to output a valid sequence of operations if one exists. You can hack only if you solved all versions of this problem.}\n\nKevin has an undirected graph with $n$ vertices and $m$ edges. Initially, some vertices contain stones, which Kevin wants to move to new positions.\n\nKevin can perform the following operation:\n\n- For each stone at $u_i$, select a neighboring vertex $v_i$. Simultaneously move each stone from $u_i$ to its corresponding $v_i$.\n\nAt any time, each vertex can contain \\textbf{at most one} stone.\n\nDetermine whether a valid sequence of operations exists that moves the stones from the initial state to the target state. Output a valid sequence of operations with no more than $2n$ moves if one exists. It can be proven that if a valid sequence exists, a valid sequence with no more than $2n$ moves exists.",
    "tutorial": "Necessary and Sufficient Conditions First, if $s = t$, the transformation is trivially feasible. Beyond this trivial case, let us consider the necessary conditions: The initial state must allow at least one valid move. The target state must allow at least one valid move. For every connected component, the number of stones in the initial state must match the number of stones in the target state. If a connected component is a bipartite graph, then after a coloring of the graph, the number of stones in each part must also satisfy corresponding constraints. We can represent a node $u$ as two separate nodes: $(u, 0)$ and $(u, 1)$, corresponding to states reachable in even and odd steps, respectively. For an undirected edge $(u, v)$, create directed edges between $(u, 0)$ and $(v, 1)$, as well as between $(u, 1)$ and $(v, 0)$. Using this transformation: It is sufficient to enumerate whether the target state is reached on an even or odd step. For each connected component, count the number of stones and verify that the condition is satisfied. The bipartite graph constraint is inherently handled within this framework, eliminating the need for special-case treatment. The first two conditions, ensuring that the initial and target states allow at least one valid move, can be verified using bipartite graph matching. If a valid matching exists, the conditions are satisfied. Time Complexity: $O(\\text{BipartiteMatching}(n, m))$, where $n$ is the number of nodes and $m$ is the number of edges. It can be shown that the above conditions are not only necessary but also sufficient. By satisfying these conditions, it is guaranteed that a valid transformation from $s$ to $t$ can be constructed. Non-constructive Proof This is a simpler, non-constructive proof. Below is a brief outline of the proof idea. Since this proof doesn't provide much help for the construction part, some details are omitted. The problem can be easily formulated as a network flow problem. You can construct a layered graph where each layer represents one step of stone movement, and the flow represents the movement of stones. Determining whether the stones can move from the initial state to the target state is equivalent to checking whether the flow is saturated. Let $c$ represent the number of stones. According to the Max-flow Min-cut Theorem, we need to consider whether there exists a cut with a capacity smaller than $c$. If we sort all the cut edges by their layer indices, there must exist two adjacent cut edges whose layers, or their distance from the source or sink, exceed $n$. To disconnect the graph, one of these two regions must fully disconnect the graph. Otherwise, after $n$ layers, the graph will remain connected. However, since there exists a valid matching between the initial and target states, it is possible to repeatedly move along this matching. This ensures that there exists a flow of size $c$ from the source or sink to any layer, meaning that the graph cannot be disconnected using fewer than $c$ edges. Constructive Proof Transforming the Graph into a Tree In the graph after splitting the nodes, if we combine the matching edges from $s$ and $t$, we obtain a structure consisting of chains and cycles. Note that for any cycle, the $s$ and $t$ edges alternate, meaning we can always adjust the matching of $t$ in this cycle to make it identical to $s$. Afterward, we can find a spanning tree among the remaining edges. This spanning tree still satisfies both the existence of matching and connectivity conditions. Moreover, all stones in $s$ and $t$ (after coloring the graph with black and white) will reside on the same layer. Solving the Tree Case For trees, it seems straightforward to move stones outward for subtrees with more stones and inward for subtrees with fewer stones. However, due to the constraint that each step must involve movement, deadlock situations may arise, making it less trivial. For example, consider the following scenario: After the first move, $S$ shifts to positions $2$ and $6$. If we only consider the number of stones in the subtrees of $s$ and $t$ or simply match based on the shortest distance, the stones might return to $1$ and $5$, leading to a deadlock. The correct sequence of moves should be $2 \\to 3$, $6 \\to 5$, then $\\to 4, 2$, and finally $\\to 3, 1$. Since $s$ and $t$ are symmetric, a meet-in-the-middle approach can be applied, where we simultaneously consider both $s$ and $t$ and aim to transform them into identical states. First find the matching for $s$ and $t$. The idea is to identify the \"outermost\" matching edge (the definition of \"outermost\" will be formalized below). WLOG, we assume it is $(t_u, t_v)$ in $t$. Then, locate the nearest matching edge $(s_u, s_v)$ in $s$ relative to $(t_u, t_v)$. Move the stones from $(s_u, s_v)$ to the corresponding nodes in $t$. Once they reach $(t_u, t_v)$, let them move back and forth between $t_u$ and $t_v$. For the remaining unmatched nodes in $s$, let them oscillate along their own matching edges for the first two steps. If the \"outermost\" matching edge is in $s$, we can perform the corresponding operations in reverse order. The explanation of how it works: First, since we are choosing the nearest matching edge in $s$, and the remaining stones move along their matching edges for the first two steps. The remaining stones will not meet the path corresponding to $s$. Otherwise, it would contradict the definition of \"nearest\". After moving $s$ to $t$, the stones will repeatedly move along the matching edge $(t_u, t_v)$ until the end of the process. This means $(t_u, t_v)$ becomes impassable for subsequent moves. Therefore, we require this edge to be \"outermost,\" meaning that after removing these two nodes, the remaining parts of $s$ and $t$ must still be connected. To find the \"outermost\" edge, we can iteratively remove the leaf nodes of the graph (nodes with degree at most 1). The first matching edge where both nodes are removed is the \"outermost\" edge. Note that this \"outermost\" criterion must consider both $s$ and $t$, taking the \"outermost\" edge among all matches in $s$ and $t$. For the remaining stones, since we ensure the process does not encounter this path or $(t_u, t_v)$, the problem reduces to a subproblem, which can be solved using the same method. This approach takes two steps each time and removes one matching edge. If the tree has $N = 2n$ nodes, the number of matching edges will not exceed $n$, so we can solve the problem in at most $2n$ steps. Time complexity: $O(\\text{BipartiteMatching}(n, m) + n^2)$. Note: The bound of $2n$ is tight. For example, consider a chain with an additional triangular loop at the tail. If the goal is to move from $1, 2$ to $1, 3$, at least one stone must traverse the triangular loop to change its parity. This requires at least $2n - O(1)$ steps.",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2061",
    "index": "I",
    "title": "Kevin and Nivek",
    "statement": "Kevin and Nivek are competing for the title of \"The Best Kevin\". They aim to determine the winner through $n$ matches.\n\nThe $i$-th match can be one of two types:\n\n- \\textbf{Type 1}: Kevin needs to spend $a_i$ time to defeat Nivek and win the match. If Kevin doesn't spend $a_i$ time on it, Nivek will win the match.\n- \\textbf{Type 2}: The outcome of this match depends on their historical records. If Kevin's number of wins is greater than or equal to Nivek's up to this match, then Kevin wins. Otherwise, Nivek wins.\n\nKevin wants to know the minimum amount of time he needs to spend to ensure he wins at least $k$ matches.\n\nOutput the answers for $k = 0, 1, \\ldots, n$.",
    "tutorial": "First, there is a straightforward dynamic programming solution with a time complexity of $O(n^2)$. Let $dp(i, j)$ represent the minimum cost for Kevin to achieve $j$ victories in the first $i$ games. However, optimizing this dynamic programming solution directly is difficult because it lacks convexity. Therefore, we use a divide-and-conquer approach to solve it (which is more commonly seen in certain counting problems). - Key Idea: To compute $dp(r, *)$ from $dp(l, *)$ efficiently, the following observations are used: At time $l$, if the difference between Kevin's and Nivek's number of victories exceeds $r-l$, then: For Type 2 matches, Kevin will either always win or always lose. For Type 1 matches, Kevin should prioritize matches with the smallest cost $a_i$ in ascending order. Let $g(i)$ denote the minimum cost of selecting $i$ matches in this range, and let $t$ represent the number of Type 2 matches in the interval. When $j - (l - j) > r-l$, the following transition applies: $dp(l,j)+g(i) \\to dp(r,j+t+i).$ Similarly, when $j - (l - j) < -(r-l)$, a similar transition is used. Since $g(i)$ is convex, the best transition point is monotonic. This property allows us to optimize this part using divide-and-conquer, achieving a time complexity of $O(n \\log n)$. For the case where $|j - (l - j)| \\leq r-l$, brute force is used to compute the transitions explicitly, with a time complexity of $O((r-l)^2)$. By dividing the sequence into blocks of size $O(\\sqrt{n \\log n})$, the overall time complexity can be reduced to $O(n \\sqrt{n \\log n})$. - To further optimize the problem, a more refined strategy is applied. Specifically, for the case where $|j - (l - j)| \\leq r-l$, instead of computing transitions explicitly with brute force, we recursively divide the problem into smaller subproblems. The goal in each subproblem is to compute the transitions from a segment of $dp(l)$ to $dp(r)$, ensuring that the segment length in $dp(l)$ does not exceed $O(r-l)$. Let $m = \\lfloor\\frac{l + r}{2}\\rfloor$. First, compute the transitions from $dp(l)$ to $dp(m)$. Then, use the results from $dp(m)$ to compute the transitions from $dp(m)$ to $dp(r)$. For each subinterval, the strategy remains the same: For differences in the number of victories that exceed the interval length, apply monotonicity to handle the transitions efficiently. For the remaining part, recursively compute transitions using the same divide-and-conquer approach. The recurrence relation for this approach is: $T(n)=2T(n/2) + O(n \\log n)$ So the time complexity is $T(n)=O(n \\log^2 n)$.",
    "tags": [
      "divide and conquer",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2062",
    "index": "A",
    "title": "String",
    "statement": "You are given a string $s$ of length $n$ consisting of $\\mathtt{0}$ and/or $\\mathtt{1}$. In one operation, you can select a non-empty subsequence $t$ from $s$ such that any two adjacent characters in $t$ are different. Then, you flip each character of $t$ ($\\mathtt{0}$ becomes $\\mathtt{1}$ and $\\mathtt{1}$ becomes $\\mathtt{0}$). For example, if $s=\\mathtt{\\underline{0}0\\underline{101}}$ and $t=s_1s_3s_4s_5=\\mathtt{0101}$, after the operation, $s$ becomes $\\mathtt{\\underline{1}0\\underline{010}}$.\n\nCalculate the minimum number of operations required to change all characters in $s$ to $\\mathtt{0}$.\n\nRecall that for a string $s = s_1s_2\\ldots s_n$, any string $t=s_{i_1}s_{i_2}\\ldots s_{i_k}$ ($k\\ge 1$) where $1\\leq i_1 < i_2 < \\ldots <i_k\\leq n$ is a subsequence of $s$.",
    "tutorial": "Let $c$ be the number of $1$s. On one hand, each operation can decrease $c$ by at most $1$, so the answer is at least $c$. On the other hand, by only operating on $1$s each time, it takes exactly $c$ operations, so the answer is at most $c$. Therefore, the answer is $c$.",
    "code": "for _ in range(int(input())):\n    print(input().count('1'))",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2062",
    "index": "B",
    "title": "Clockwork",
    "statement": "You have a sequence of $n$ time clocks arranged in a line, where the initial time on the $i$-th clock is $a_i$. In each second, the following happens in order:\n\n- Each clock's time decreases by $1$. If any clock's time reaches $0$, you lose immediately.\n- You can choose to move to an adjacent clock or stay at the clock you are currently on.\n- You can reset the time of the clock you are on back to its initial value $a_i$.\n\nNote that the above events happen in order. If the time of a clock reaches $0$ in a certain second, even if you can move to this clock and reset its time during that second, you will still lose.\n\nYou can start from any clock. Determine if it is possible to continue this process indefinitely without losing.",
    "tutorial": "On one hand, traveling from $i$ to $1$ and back takes time $2(i-1)$, and traveling from $i$ to $n$ and back takes time $2(n-i)$. Therefore, it must hold that $t_i > 2\\max(i-1, n-i)$. On the other hand, if this condition is satisfied, one can simply move back and forth between $1$ and $n$ directly.",
    "code": "for _ in range(int(input())):\n    n=int(input())\n    a=list(map(int,input().split()))\n    for i in range(n):\n        if a[i]<=max(i,n-i-1)*2:\n            print('NO')\n            break\n    else:\n        print('YES')",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2062",
    "index": "C",
    "title": "Cirno and Operations",
    "statement": "Cirno has a sequence $a$ of length $n$. She can perform either of the following two operations for any (possibly, zero) times \\textbf{unless} the current length of $a$ is $1$:\n\n- Reverse the sequence. Formally, $[a_1,a_2,\\ldots,a_n]$ becomes $[a_n,a_{n-1},\\ldots,a_1]$ after the operation.\n- Replace the sequence with its difference sequence. Formally, $[a_1,a_2,\\ldots,a_n]$ becomes $[a_2-a_1,a_3-a_2,\\ldots,a_n-a_{n-1}]$ after the operation.\n\nFind the maximum possible sum of elements of $a$ after all operations.",
    "tutorial": "Let the reversal be called operation $1$, and the difference be called operation $2$. Consider swapping two adjacent operations: $12 \\to 21$. If the sequence before the operations is $[a_1, a_2, \\dots, a_n]$, then after the operations, the sequence changes from $[a_{n-1} - a_n, a_{n-2} - a_{n-1}, \\dots, a_1 - a_2]$ to $[a_n - a_{n-1}, a_{n-1} - a_{n-2}, \\dots, a_2 - a_1]$. Thus, swapping adjacent $1,2$ is equivalent to taking the negation of each element of the array. Therefore, any operation sequence is equivalent to first performing $2$ several times, and then performing $1$ several times, and then taking the negation several times. Since $1$ does not change the sum of the sequence, the answer is the maximum absolute value of the sequence sum after performing a certain number of $2$. There is a corner case: if you don't perform $2$ at all, you can not take the negation. Besides, the upper bound of the answer is $1000\\times 2^{50}$, so you have to use 64-bit integers.",
    "code": "from math import *\nfor _ in range(int(input())):\n\tn=int(input())\n\ta=list(map(int,input().split()))\n\tans=sum(a)\n\twhile n>1:\n\t\tn-=1\n\t\ta=[a[i+1]-a[i] for i in range(n)]\n\t\tans=max(ans,abs(sum(a)))\n\tprint(ans)\n",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2062",
    "index": "D",
    "title": "Balanced Tree",
    "statement": "You are given a tree$^{\\text{∗}}$ with $n$ nodes and values $l_i, r_i$ for each node. You can choose an initial value $a_i$ satisfying $l_i\\le a_i\\le r_i$ for the $i$-th node. A tree is balanced if all node values are equal, and the value of a balanced tree is defined as the value of any node.\n\nIn one operation, you can choose two nodes $u$ and $v$, and increase the values of all nodes in the subtree$^{\\text{†}}$ of node $v$ by $1$ while considering $u$ as the root of the entire tree. Note that $u$ may be equal to $v$.\n\nYour goal is to perform a series of operations so that the tree becomes \\textbf{balanced}. Find the minimum possible value of the tree after performing these operations. Note that you \\textbf{don't} need to minimize the number of operations.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\n$^{\\text{†}}$Node $w$ is considered in the subtree of node $v$ if any path from root $u$ to $w$ must go through $v$.\n\\end{footnotesize}",
    "tutorial": "First, assume that the values of $a_i$ have already been determined and $1$ is the root of the tree. For any edge connecting $x$ and $\\text{fa}(x)$, to make $a_x=a_{\\text{fa}(x)}$, the only useful operation is to set $u=x,v=\\text{fa}(x)$ or $v=x,u=\\text{fa}(x)$. After the operation, $a_x-a_{\\text{fa}(x)}$ changes by $1$, so you will always perform exactly $|a_x - a_{\\text{fa}(x)}|$ operations to make $a_x=a_{\\text{fa}(x)}$. You will perform the above operation for each edge to make all nodes' values equal. Among those operations, the connected component containing $1$ will increase by $\\sum \\max(a_u - a_{\\text{fa}(u)}, 0)$ times. Thus, the final answer is $a_1 + \\sum \\max(a_u - a_{\\text{fa}(u)}, 0)$. Now, consider how to choose the values of $a$. If $r_u = +\\infty$, then $a_u$ should always be no less than the maximum value of its child nodes $a_v$ (why? Because decreasing $a_u$ by $1$ can only reduce $a_u - a_{\\text{fa}(u)}$ by at most $1$, but it will increase $a_v - a_u$ by at least $1$). So $a_u=\\min(r_u,\\max(l_u,\\max\\limits_{\\text{fa}(v)=u}a_v))$.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\tl,r=[],[]\n\tfor i in range(n):\n\t\tL,R=map(int,input().split())\n\t\tl.append(L)\n\t\tr.append(R)\n\te=[[] for i in range(n)]\n\tfor i in range(n-1):\n\t\tu,v=map(int,input().split())\n\t\te[u-1].append(v-1)\n\t\te[v-1].append(u-1)\n\tstk=[0]\n\tf=[-1]*n\n\tnfd=[]\n\twhile stk:\n\t\tu=stk.pop()\n\t\tnfd.append(u)\n\t\tfor v in e[u]:\n\t\t\tif v!=f[u]:\n\t\t\t\tf[v]=u\n\t\t\t\tstk.append(v)\n\tnfd.reverse()\n\tans=0\n\tfor u in nfd:\n\t\tfor v in e[u]:\n\t\t\tif f[v]==u:\n\t\t\t\tl[u]=max(l[u],l[v])\n\t\tl[u]=min(l[u],r[u])\n\t\tfor v in e[u]:\n\t\t\tif f[v]==u:\n\t\t\t\tans+=max(0,l[v]-l[u])\n\tprint(ans+l[0])",
    "tags": [
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2062",
    "index": "E1",
    "title": "The Game (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, you only need to find one of the possible nodes Cirno may choose. You can hack only if you solved all versions of this problem.}\n\nCirno and Daiyousei are playing a game with a tree$^{\\text{∗}}$ of $n$ nodes, rooted at node $1$. The value of the $i$-th node is $w_i$. They take turns to play the game; Cirno goes first.\n\nIn each turn, assuming the opponent chooses $j$ in the last turn, the player can choose any remaining node $i$ satisfying $w_i>w_j$ and delete the subtree$^{\\text{†}}$ of node $i$. In particular, Cirno can choose any node and delete its subtree in the first turn.\n\nThe first player who \\textbf{can not} operate \\textbf{wins}, and they all hope to win. Find \\textbf{one of the possible nodes Cirno may choose} so that she wins if both of them play optimally.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\n$^{\\text{†}}$Node $u$ is considered in the subtree of node $i$ if any path from $1$ to $u$ must go through $i$.\n\\end{footnotesize}",
    "tutorial": "In the first round, the node $u$ chosen by Cirno must satisfy: there exists a node $v$ outside the subtree of $u$ such that $w_v > w_u$. If no such node exists, then Cirno will lose. Among these nodes, Cirno can choose the node with the largest $w_u$. After this, Daiyousei can only select nodes that do not satisfy the above condition, and subsequently, Cirno will inevitably have no nodes left to operate on. To determine whether there exists a node $v$ outside the subtree of $u$ such that $w_v > w_u$, we record the timestamp $dfn_u$ when each node is first visited during the DFS traversal of the tree, as well as the timestamp $low_u$ when the traversal of its subtree is completed. Since the timestamps outside the subtree form two intervals, namely $[1, dfn_u)$ and $(low_u, n]$, we need to check whether $\\max(\\max\\limits_{dfn_v\\in [1,dfn_u)}w_v,\\max\\limits_{dfn_v\\in (low_u,n]}w_v)>w_u$ holds. This can be achieved by maintaining the maximum values in the prefix and suffix. Additionally, we can enumerate the nodes in descending order of $w_i$ and maintain their lowest common ancestor (LCA). If the LCA of all $v$ satisfying $w_v > w_u$ is not a descendant of $u$, then there must exist a node $v$ outside the subtree of $u$ that satisfies $w_v > w_u$. We can also enumerate the nodes in descending order of $w_i$ and maintain their minimum and maximum $dfn_i$, namely $mn,mx$. According to the conclusion above, we can check whether $mn<dfn_u$ or $mx>low_u$ holds. If either condition holds, then there must exist a node $v$ outside the subtree of $u$ that satisfies $w_v > w_u$.",
    "code": "for _ in range(int(input())):\n\tn = int(input())\n\tw=[int(x) for x in input().split()]\n\twb=[[] for i in range(n)]\n\tfor i in range(n):\n\t\tw[i]-=1\n\t\twb[w[i]].append(i)\n\te=[[] for i in range(n)]\n\tfor i in range(n-1):\n\t\tu,v=map(int,input().split())\n\t\te[u-1].append(v-1)\n\t\te[v-1].append(u-1)\n\tstk=[0]\n\tf,dfn=[-1]*n,[0]*n\n\tnfd=[]\n\twhile stk:\n\t\tu=stk.pop()\n\t\tdfn[u]=len(nfd)\n\t\tnfd.append(u)\n\t\tfor v in e[u]:\n\t\t\tif v!=f[u]:\n\t\t\t\tf[v]=u\n\t\t\t\tstk.append(v)\n\tsz=[1]*n\n\tnfd.reverse()\n\tfor u in nfd:\n\t\tif u==0:\n\t\t\tcontinue\n\t\tsz[f[u]]+=sz[u]\n\twb.reverse()\n\tmx=-1;mn=n+1\n\tfor v in wb:\n\t\tfor u in v:\n\t\t\tif mn<dfn[u] or mx>dfn[u]+sz[u]-1:\n\t\t\t\tprint(u+1)\n\t\t\t\tbreak\n\t\telse:\n\t\t\tfor u in v:\n\t\t\t\tmn=min(mn,dfn[u])\n\t\t\t\tmx=max(mx,dfn[u])\n\t\t\tcontinue\n\t\tbreak\n\telse:\n\t\tprint(0)",
    "tags": [
      "data structures",
      "dfs and similar",
      "games",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2062",
    "index": "E2",
    "title": "The Game (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, you need to find all possible nodes Cirno may choose. You can hack only if you solved all versions of this problem.}\n\nCirno and Daiyousei are playing a game with a tree$^{\\text{∗}}$ of $n$ nodes, rooted at node $1$. The value of the $i$-th node is $w_i$. They take turns to play the game; Cirno goes first.\n\nIn each turn, assuming the opponent chooses $j$ in the last turn, the player can choose any remaining node $i$ satisfying $w_i>w_j$ and delete the subtree$^{\\text{†}}$ of node $i$. In particular, Cirno can choose any node and delete its subtree in the first turn.\n\nThe first player who \\textbf{can not} operate \\textbf{wins}, and they all hope to win. Find \\textbf{all possible nodes Cirno may choose in the first turn} so that she wins if both of them play optimally.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\n$^{\\text{†}}$Node $u$ is considered in the subtree of node $i$ if any path from $1$ to $u$ must go through $i$.\n\\end{footnotesize}",
    "tutorial": "In the first round, the node $u$ chosen by Cirno must satisfy: there exists a node $v$ outside the subtree of $u$ such that $w_v > w_u$. If no such node exists, then Cirno will lose. Similar to Cirno's strategy in E1, if Daiyousei can choose a node such that Cirno can still make a move after the operation, then Daiyousei only needs to select the node with the largest $w_u$ among these nodes to win. Therefore, Cirno must ensure that she cannot make a move after Daiyousei's operation. Enumerate the node $u$ chosen by Daiyousei, then the node $v$ chosen by Cirno must satisfy: Either for all nodes $x$ with $w_x > w_u$, $x$ must be within the subtree of $u$ or $v$. In other words, $v$ must be an ancestor of the lca of all $x$ outside the subtree of $u$ that satisfy $w_x > w_u$ (denoted as $g(u) = v$). Or $v$ must prevent Daiyousei from choosing this $u$. In other words, either $w_v \\ge w_u$, or $u$ is within the subtree of $v$. Therefore, $v$ must satisfy that for all $w_u > w_v$, either $u$ is within the subtree of $v$, or $g(u)$ is within the subtree of $v$, and this is a necessary and sufficient condition. To compute $g(u)$: Enumerate $u$ from largest to smallest, which is equivalent to computing the lca of all enumerated nodes outside the subtree. This can be achieved in several ways: 1. Use a segment tree or Fenwick tree to maintain the lca of intervals on the dfs order, where the outside of the subtree corresponds to the prefix and suffix of the dfs order. Depending on the method of lca implementation, the complexity could be $O(n\\log^2n)$ or $O(n\\log n)$. 2. Since the lca of a set of nodes is equivalent to the lca of the node with the smallest dfs order and the node with the largest dfs order, std::set can be used to maintain such nodes. To determine the condition that $v$ must satisfy, also enumerate from largest to smallest. For a node $u$, if there exists a corresponding $g(u)$, then add one to the chain from $u$ to $1$, add one to the chain from $g(u)$ to $1$, and subtract one from the chain from $lca(u,g(u))$ to $1$. This way, all nodes that satisfy the condition are exactly incremented by one. It is only necessary to check whether the current value of $v$ is equal to the number of $u$. Depending on the implementation, the complexity could be $O(n\\log^2n)$ or $O(n\\log n)$. Additionally, there exists a method that does not require computing the lca.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\n#define all(x) (x).begin(),(x).end()\nconst int N = 5e5 + 2;\nvector<int> e[N];\nint dfn[N], nfd[N], low[N];\nint id, n;\nvoid dfs(int u)\n{\n\tnfd[dfn[u] = ++id] = u;\n\tfor (int v : e[u]) erase(e[v], u), dfs(v);\n\tlow[u] = id;\n}\nint main()\n{\n\tios::sync_with_stdio(0); cin.tie(0);\n\tcout << fixed << setprecision(15);\n\tint T; cin >> T;\n\twhile (T--)\n\t{\n\t\tint n, m, i, j;\n\t\tcin >> n;\n\t\tvector w(n, vector<int>());\n\t\tvector<int> c(n + 1), ans;\n\t\tfor (i = 1; i <= n; i++)\n\t\t{\n\t\t\te[i].clear(); id = 0;\n\t\t\tcin >> j;\n\t\t\tw[j - 1].push_back(i);\n\t\t}\n\t\tfor (i = 1; i < n; i++)\n\t\t{\n\t\t\tint u, v;\n\t\t\tcin >> u >> v;\n\t\t\te[u].push_back(v);\n\t\t\te[v].push_back(u);\n\t\t}\n\t\tdfs(1);\n\t\tint l = n + 1, r = 0;\n\t\tset<int> s;\n\t\tfor (i = n - 1; i >= 0; i--)\n\t\t{\n\t\t\tif (s.size())\n\t\t\t{\n\t\t\t\tfor (int u : w[i])\n\t\t\t\t{\n\t\t\t\t\tint mx = 0;\n\t\t\t\t\tfor (j = dfn[u] - 1; j; j -= j & -j) mx = max(mx, c[j]);\n\t\t\t\t\tif ((*s.begin() < dfn[u] || *s.rbegin() > low[u]) && mx <= low[u] && dfn[u] <= l && low[u] >= r)\n\t\t\t\t\t\tans.push_back(u);\n\t\t\t\t}\n\t\t\t\tfor (int u : w[i])\n\t\t\t\t{\n\t\t\t\t\tint mn = *s.begin(), mx = *s.rbegin();\n\t\t\t\t\tint L = dfn[u], R = low[u];\n\t\t\t\t\tif (mn >= L && mx <= R) continue;\n\t\t\t\t\tif (mn >= L && mn <= R) mn = *s.upper_bound(R);\n\t\t\t\t\tif (mx >= L && mx <= R) mx = *prev(s.lower_bound(L));\n\t\t\t\t\tauto fun = [&](int x, int y) {\n\t\t\t\t\t\tif (x > y) swap(x, y);\n\t\t\t\t\t\tl = min(l, y), r = max(r, x);\n\t\t\t\t\t\tfor (j = x; j <= n; j += j & -j) c[j] = max(c[j], y);\n\t\t\t\t\t};\n\t\t\t\t\tfun(mn, dfn[u]);\n\t\t\t\t\tfun(mx, dfn[u]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int u : w[i]) s.insert(dfn[u]);\n\t\t}\n\t\tsort(all(ans));\n\t\tcout << ans.size();\n\t\tfor (int x : ans) cout << ' ' << x;\n\t\tcout << '\\n';\n\t}\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "games",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2062",
    "index": "F",
    "title": "Traveling Salescat",
    "statement": "You are a cat selling fun algorithm problems. Today, you want to recommend your fun algorithm problems to $k$ cities.\n\nThere are a total of $n$ cities, each with two parameters $a_i$ and $b_i$. Between any two cities $i,j$ ($i\\ne j$), there is a bidirectional road with a length of $\\max(a_i + b_j , b_i + a_j)$. The cost of a path is defined as the total length of roads between every two adjacent cities along the path.\n\nFor $k=2,3,\\ldots,n$, find the minimum cost among all simple paths containing exactly $k$ \\textbf{distinct} cities.",
    "tutorial": "Let $x_i = \\frac{a_i + b_i}{2}$, $y_i = \\frac{a_i - b_i}{2}$. Then $\\max(a_i + b_j , b_i + a_j) = \\max( x_i + y_i + x_j - y_j , x_i - y_i + x_j + y_j) = x_i + x_j + \\max(y_i - y_j, y_j - y_i)$ $= x_i + x_j + |y_i - y_j|$. Consider a road that passes through $k$ different cities, and consider the contribution as two parts, $x$ and $y$. For the contribution of $x$, the first and last cities will only contribute to the answer once. And all other cities on the path will contribute twice. For the contribution of $y$, after determining the cities that need to be passed through and the two cities as starting or ending cities (referred to as endpoint cities), you can start from the endpoint city with smaller $y$, move to the city with the smallest $y$ among the cities to be passed through, then move to the city with the largest $y$ among the cities to be passed through, and finally move to the endpoint city with larger $y$. This way, the minimum contribution of y can be obtained while passing through all the cities that need to be passed through. You can sort the cities by $y$ and perform a dp to find the minimum answer among the first $i$ cities where $j$ cities have been selected, including $0$ or $1$ or $2$ endpoint cities. The total time complexity is $O(n^2)$.",
    "code": "class Q:\n\tdef __init__(this,x,y):\n\t\tthis.x,this.y=x+y,x-y\n\tdef __lt__(this,rhs):\n\t\treturn this.y<rhs.y\nfor _ in range(int(input())):\n\tn=int(input())\n\ta=[0]*n\n\tfor i in range(n):\n\t\tx,y=map(int,input().split())\n\t\ta[i]=Q(x,y)\n\ta.sort()\n\tl=[10**18]*(n+1)\n\tsl=l.copy();slt=l.copy();slrt=l.copy()\n\ts=10**18\n\tfor m,t in enumerate(a):\n\t\tx,y=t.x,t.y\n\t\tfor i in range(m,0,-1):\n\t\t\tslrt[i+1]=min(slrt[i+1],sl[i]+x+y,slt[i]+x*2+y*2)\n\t\t\tslt[i+1]=min(slt[i+1],slt[i]+x*2,sl[i]+x-y)\n\t\t\tsl[i+1]=min(sl[i+1],sl[i]+x*2,l[i]+x+y)\n\t\t\tl[i+1]=min(l[i+1],l[i]+x*2)\n\t\tsl[1]=min(sl[1],x-y)\n\t\tl[1]=min(l[1],x*2-y*2)\n\tprint(*[x//2 for x in slrt[2:]])",
    "tags": [
      "constructive algorithms",
      "dp",
      "geometry",
      "graphs",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2062",
    "index": "G",
    "title": "Permutation Factory",
    "statement": "You are given two permutations $p_1,p_2,\\ldots,p_n$ and $q_1,q_2,\\ldots,q_n$ of length $n$. In one operation, you can select two integers $1\\leq i,j\\leq n,i\\neq j$ and swap $p_i$ and $p_j$. The cost of the operation is $\\min (|i-j|,|p_i-p_j|)$.\n\nFind the minimum cost to make $p_i = q_i$ hold for all $1\\leq i\\leq n$ and output a sequence of operations to achieve the minimum cost.\n\nA permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).",
    "tutorial": "Because the cost of an operation is $\\min(|i-j|,|p_i-p_j|)$, we can consider this operation as two operations with different costs, one costing $|i-j|$ and the other costing $|p_i-p_j|$. Consider each number in the permutation as a point $(i, p_i)$ on a two-dimensional plane. So the first operation can be seen as moving $(i, p_i)$ to $(i, p_j)$, and simultaneously moving $(j, p_j)$ to $(j, p_i)$. The second operation can be seen as moving $(i, p_i)$ to $(j, p_i)$ and simultaneously moving $(j, p_j)$ to $(i, p_j)$. The cost of both modes of movement is the coordinate distance between these two points. Supposing that the restriction that two points should be moved simultaneously is removed. Meanwhile, divide the cost of one operation equally between the movements of two points. Then, the cost of moving a point from one coordinate to another is the Manhattan distance between these two points divided by $2$, and the minimum cost is the minimum cost matching to move each point of $p$ to match each point of $q$. Next, we will prove that the minimum answer obtained after removing the simultaneous movement restriction can always be obtained under restricted conditions. First, find any minimum cost matching between points of $p$ and points of $q$. Assume that point $(i,p_i)$ matches point $(a_i,q_{a_i})$, where $a$ is also a permutation. We first make point moves parallel to the x-axis direction. If there exists $a_i \\neq i$, find the $i$ with the smallest $a_i$ among them. Then, there must exist $j$ where $a_i \\le j < i \\le a_j$. By performing such operations on $i$ and $j$, these two points can be moved without increasing the total cost. Continuously performing this operation can complete the movement of all points in the x-axis direction. The same applies to the movement in the y-axis direction. Using the minimum cost and maximum flow to find the minimum cost matching and checking every pair of $(i,j)$ to find a swappable pair will result in a solution with $O(n^4)$ time complexity. Using the Kuhn-Munkres Algorithm to find the minimum cost matching, checking only $a_i$ mentioned above can achieve a time complexity of $O (n^3)$, but is not required.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nstruct linex{\n\tint v;\n\tint w;\n\tint nxt;\n\tint c;\n};\nint head[210],cnt,cpos[210],vis[210],qvis[210],totc,dis[210],inf=1000000000;\nlinex l[21000];\nqueue<int>que;\nvoid add(int u,int v,int w,int c){\n\tl[cnt].nxt=head[u];\n\thead[u]=cnt;\n\tl[cnt].v=v;\n\tl[cnt].w=w;\n\tl[cnt].c=c;\n\tcnt++;\n\tl[cnt].nxt=head[v];\n\thead[v]=cnt;\n\tl[cnt].v=u;\n\tl[cnt].w=0;\n\tl[cnt].c=-c;\n\tcnt++;\n}\nint spfa(int st,int en,int n){\n\tint i,j,t;\n\tfor(i=0;i<n;i++)\n\t{\n\t\tvis[i]=0;\n\t\tdis[i]=inf;\n\t\tcpos[i]=head[i];\n\t}\n\tque.push(st);\n\tdis[st]=0;\n\tvis[st]=1;\n\tqvis[st]=1;\n\twhile(!que.empty())\n\t{\n\t\tt=que.front();\n\t\tque.pop();\n\t\tqvis[t]=0;\n\t\tfor(j=head[t];j!=-1;j=l[j].nxt)\n\t\t{\n\t\t\tif(l[j].w>0&&dis[l[j].v]>dis[t]+l[j].c)\n\t\t\t{\n\t\t\t\tdis[l[j].v]=dis[t]+l[j].c;\n\t\t\t\tvis[l[j].v]=1;\n\t\t\t\tif(!qvis[l[j].v])\n\t\t\t\t{\n\t\t\t\t\tque.push(l[j].v);\n\t\t\t\t\tqvis[l[j].v]=1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn vis[en];\n}\nlong long dfs(int p,int en,int curr){\n\tint x,j,flow=0;\n\tif(p==en)return curr;\n\tfor(j=cpos[p];j!=-1&&flow<curr;j=l[j].nxt)\n\t{\n\t\tcpos[p]=j;\n\t\tqvis[p]=1;\n\t\tif(l[j].w>0&&dis[l[j].v]==dis[p]+l[j].c&&!qvis[l[j].v])\n\t\t{\n\t\t\tx=dfs(l[j].v,en,min(curr-flow,l[j].w));\n\t\t\tflow+=x;\n\t\t\tl[j].w-=x;\n\t\t\tl[j^1].w+=x;\n\t\t\ttotc+=l[j].c*x;\n\t\t}\n\t\tqvis[p]=0;\n\t}\n\treturn flow;\n}\nint p[100],q[100],id[100][100];\nint cabs(int x){\n\tif(x<0)x=-x;\n\treturn x;\n}\nstruct point{\n\tint x;\n\tint y;\n\tint tx;\n\tint ty;\n}pc[100];\nvector<int>ansv[2];\nint main(){\n\tios::sync_with_stdio(false),cin.tie(0);\n\tsrand(time(0));\n\tint T,n,i,j,flow,flag;\n\tfor(cin>>T;T>0;T--)\n\t{\n\t\tcin>>n;\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>p[i];\n\t\t\tp[i]--;\n\t\t}\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>q[i];\n\t\t\tq[i]--;\n\t\t}\n\t\tfor(i=0;i<n*2+2;i++)head[i]=-1;\n\t\tcnt=0;\n\t\ttotc=0;\n\t\tflow=0;\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tadd(n*2,i,1,0);\n\t\t\tadd(i+n,n*2+1,1,0);\n\t\t\tfor(j=0;j<n;j++)\n\t\t\t{\n\t\t\t\tid[i][j]=cnt;\n\t\t\t\tadd(i,j+n,1,cabs(i-j)+cabs(p[i]-q[j]));\n\t\t\t}\n\t\t}\n\t\twhile(spfa(n*2,n*2+1,n*2+2))flow+=dfs(n*2,n*2+1,inf);\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tpc[i].x=i;\n\t\t\tpc[i].y=p[i];\n\t\t\tfor(j=0;j<n;j++)\n\t\t\t{\n\t\t\t\tif(l[id[i][j]].w==0)\n\t\t\t\t{\n\t\t\t\t\tpc[i].tx=j;\n\t\t\t\t\tpc[i].ty=q[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twhile(1)\n\t\t{\n\t\t\tflag=0;\n\t\t\tfor(i=0;i<n;i++)\n\t\t\t{\n\t\t\t\tfor(j=0;j<n;j++)\n\t\t\t\t{\n\t\t\t\t\tif(pc[j].tx<=pc[i].x&&pc[i].x<pc[j].x&&pc[j].x<=pc[i].tx)\n\t\t\t\t\t{\n\t\t\t\t\t\tansv[0].push_back(pc[i].x);\n\t\t\t\t\t\tansv[1].push_back(pc[j].x);\n\t\t\t\t\t\tswap(pc[i].x,pc[j].x);\n\t\t\t\t\t\tflag=1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!flag)break;\n\t\t}\n\t\twhile(1)\n\t\t{\n\t\t\tflag=0;\n\t\t\tfor(i=0;i<n;i++)\n\t\t\t{\n\t\t\t\tfor(j=0;j<n;j++)\n\t\t\t\t{\n\t\t\t\t\tif(pc[j].ty<=pc[i].y&&pc[i].y<pc[j].y&&pc[j].y<=pc[i].ty)\n\t\t\t\t\t{\n\t\t\t\t\t\tansv[0].push_back(pc[i].x);\n\t\t\t\t\t\tansv[1].push_back(pc[j].x);\n\t\t\t\t\t\tswap(pc[i].y,pc[j].y);\n\t\t\t\t\t\tflag=1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!flag)break;\n\t\t}\n\t\tcout<<ansv[0].size()<<'\\n';\n\t\tfor(i=0;i<ansv[0].size();i++)cout<<ansv[0][i]+1<<' '<<ansv[1][i]+1<<'\\n';\n\t\tansv[0].clear();\n\t\tansv[1].clear();\n\t}\n\treturn 0;\n}",
    "tags": [
      "flows",
      "geometry",
      "graph matchings",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2062",
    "index": "H",
    "title": "Galaxy Generator",
    "statement": "In a two-dimensional universe, a star can be represented by a point $(x,y)$ on a two-dimensional plane. Two stars are directly connected if and only if their $x$ or $y$ coordinates are the same, and there are no other stars on the line segment between them. Define a galaxy as a connected component composed of stars connected directly or indirectly (through other stars).\n\nFor a set of stars, its value is defined as the minimum number of galaxies that can be obtained after performing the following operation for any (possibly, zero) times: in each operation, you can select a point $(x,y)$ without stars. If a star can be directly connected to at least $3$ stars after creating it here, then you create a star here.\n\nYou are given a $n\\times n$ matrix $a$ consisting of $0$ and $1$ describing a set $S$ of stars. There is a star at $(x,y)$ if and only if $a_{x,y}=1$. Calculate the sum, modulo $10^9 + 7$, of the values of all non-empty subsets of $S$.",
    "tutorial": "We will refer to the smallest rectangle containing a galaxy whose edges are parallel to the coordinate axis as the boundary rectangle of a galaxy. For two galaxies, if the projections of their boundary rectangles intersect on the x or y axis, we can merge these two galaxies in one operation. Proof: Let's assume that the projections of two rectangles on the x-axis intersect. If their projections on the x-axis are $(l_1, r_1)$ and $(l_2, r_2)$, let $l_1<l_2$, then $l_2<r_1$. Since stars in a galaxy must be connected, there must be two stars in the first galaxy with x-coordinates on either side of $x=l_2$ that are directly connected. Creating a star at the intersection of the line segment between these two stars and $x=l_2$ can connect two galaxies. The situation is the same for the y-axis. Consider continuously merging two galaxies that meet the above conditions until the projections of the boundary rectangles of all galaxies on the x-axis and y-axis are non intersecting. The set of boundary rectangles obtained in this way must be uniquely determined because such rectangles cannot be merged or split into smaller rectangles that cannot be merged. Next, we need to calculate the number of subsets of stars for each two-dimensional interval, so that all stars in this subset can obtain a unique galaxy through the above process, and the boundary rectangle of this galaxy is the two-dimensional interval. The answer can be calculated using the inclusion exclusion method, because if these stars cannot form such a galaxy, then they must have formed several smaller rectangles with projection intervals that do not intersect on the x-axis and y-axis. We can continuously add these smaller rectangles from left to right in the x-axis direction. At the same time, maintain the bitmask of the union of these rectangular projections in the y-axis direction to ensure that these rectangles do not intersect. To reduce time complexity, calculations can be performed simultaneously for all two-dimensional intervals. We can perform interval dp in the x-axis direction and directly calculate the entire set in the y-axis direction and use high-dimensional prefix sum to obtain answers for each interval. The time complexity of this dp method appears to be $O (2^n \\cdot n^5)$, because we need to enumerate the left boundary where the x-axis transition begins, the bitmask in the y-axis direction, and the four boundaries of the concatenated small rectangle when concatenating them. However, since the interval in the y-axis direction must not intersect with the bitmask, in reality, the enumeration here only needs to be calculated $\\sum_{i=1}^n (n-i+1) \\cdot 2^{n-i} = O(2^n \\cdot n)$ times. So the final time complexity is $O (2^n \\cdot n^4)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst long long mod=1000000007;\nstring s;\nlong long dp[15][15][1<<14],vl[200],sgvl[15][15][15][15];\nlong long dp2[15][1<<14],dpvl2[15][1<<14];\nint psum[15][15];\nlong long getvl(long long l,long long r,long long x,long long y){\n\tif(l>=r||x>=y)return 0;\n\treturn vl[psum[r][y]-psum[l][y]-psum[r][x]+psum[l][x]];\n}\nlong long f(long long l,long long r,long long x,long long y){\n\tlong long ans=0,i,c,tl,tr,tx,ty;\n\tfor(i=0;i<16;i++)\n\t{\n\t\tc=0;\n\t\ttl=l;\n\t\ttr=r;\n\t\ttx=x;\n\t\tty=y;\n\t\tif(i&1)\n\t\t{\n\t\t\tc^=1;\n\t\t\ttl++;\n\t\t}\n\t\tif(i&2)\n\t\t{\n\t\t\tc^=1;\n\t\t\ttr--;\n\t\t}\n\t\tif(i&4)\n\t\t{\n\t\t\tc^=1;\n\t\t\ttx++;\n\t\t}\n\t\tif(i&8)\n\t\t{\n\t\t\tc^=1;\n\t\t\tty--;\n\t\t}\n\t\tif(c)ans=(ans+mod-getvl(tl,tr,tx,ty))%mod;\n\t\telse ans=(ans+getvl(tl,tr,tx,ty))%mod;\n\t}\n\treturn ans;\n}\nint main(){\n\tios::sync_with_stdio(false),cin.tie(0);\n\tint T,n,i,j,t,p,l,r,len,cmsk;\n\tlong long ans;\n\tfor(cin>>T;T>0;T--)\n\t{\n\t\tcin>>n;\n\t\tvl[0]=0;\n\t\tfor(i=1;i<=n*n;i++)vl[i]=(vl[i-1]*2+1)%mod;\n\t\tfor(i=0;i<=n;i++)\n\t\t{\n\t\t\tfor(j=0;j<=n;j++)psum[i][j]=0;\n\t\t}\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tcin>>s;\n\t\t\tfor(j=0;j<n;j++)psum[i+1][j+1]=s[j]-'0';\n\t\t}\n\t\tfor(i=0;i<n;i++)\n\t\t{\n\t\t\tfor(j=0;j<=n;j++)psum[i+1][j]+=psum[i][j];\n\t\t}\n\t\tfor(i=0;i<=n;i++)\n\t\t{\n\t\t\tfor(j=0;j<n;j++)psum[i][j+1]+=psum[i][j];\n\t\t}\n\t\tfor(l=0;l<=n;l++)\n\t\t{\n\t\t\tfor(r=l+1;r<=n;r++)\n\t\t\t{\n\t\t\t\tfor(i=0;i<=n;i++)\n\t\t\t\t{\n\t\t\t\t\tfor(j=i+1;j<=n;j++)sgvl[l][r][i][j]=f(l,r,i,j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(i=0;i<=n;i++)\n\t\t{\n\t\t\tfor(j=0;j<=n;j++)\n\t\t\t{\n\t\t\t\tfor(t=0;t<(1<<n);t++)dp[i][j][t]=0;\n\t\t\t}\n\t\t}\n\t\tfor(i=0;i<=n;i++)dp[i][i][0]=1;\n\t\tfor(len=1;len<=n;len++)\n\t\t{\n\t\t\tfor(l=0;l+len<=n;l++)\n\t\t\t{\n\t\t\t\tr=l+len;\n\t\t\t\tfor(i=l+1;i<r;i++)\n\t\t\t\t{\n\t\t\t\t\tfor(j=1;j<(1<<n);j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(t=0;t<n;t++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcmsk=j;\n\t\t\t\t\t\t\tfor(p=t;p<n&&(j>>p&1^1);p++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcmsk|=(1<<p);\n\t\t\t\t\t\t\t\tdp[l][r][cmsk]=(dp[l][r][cmsk]+dp[l][i][j]*sgvl[i][r][t][p+1])%mod;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor(j=1;j<(1<<n);j++)\n\t\t\t\t{\n\t\t\t\t\tfor(i=0;(j>>i&1^1);i++);\n\t\t\t\t\tfor(t=n-1;(j>>t&1^1);t--);\n\t\t\t\t\tsgvl[l][r][i][t+1]=(sgvl[l][r][i][t+1]+mod-dp[l][r][j])%mod;\n\t\t\t\t}\n\t\t\t\tfor(i=0;i<n;i++)\n\t\t\t\t{\n\t\t\t\t\tcmsk=0;\n\t\t\t\t\tfor(t=i;t<n;t++)\n\t\t\t\t\t{\n\t\t\t\t\t\tcmsk|=(1<<t);\n\t\t\t\t\t\tdp[l][r][cmsk]=(dp[l][r][cmsk]+sgvl[l][r][i][t+1])%mod;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(len==1)continue;\n\t\t\t\tfor(j=0;j<(1<<n);j++)dp[l][r][j]=(dp[l][r-1][j]+dp[l][r][j])%mod;\n\t\t\t}\n\t\t}\n\t\tfor(i=0;i<=n;i++)\n\t\t{\n\t\t\tfor(j=0;j<(1<<n);j++)\n\t\t\t{\n\t\t\t\tdp2[i][j]=0;\n\t\t\t\tdpvl2[i][j]=0;\n\t\t\t}\n\t\t}\n\t\tdp2[0][0]=1;\n\t\tfor(l=0;l<n;l++)\n\t\t{\n\t\t\tfor(j=0;j<(1<<n);j++)\n\t\t\t{\n\t\t\t\tdp2[l+1][j]=(dp2[l+1][j]+dp2[l][j])%mod;\n\t\t\t\tdpvl2[l+1][j]=(dpvl2[l+1][j]+dpvl2[l][j])%mod;\n\t\t\t}\n\t\t\tfor(r=l+1;r<=n;r++)\n\t\t\t{\n\t\t\t\tfor(j=0;j<(1<<n);j++)\n\t\t\t\t{\n\t\t\t\t\tfor(i=0;i<n;i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tcmsk=j;\n\t\t\t\t\t\tfor(t=i;t<n&&(j>>t&1^1);t++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcmsk|=(1<<t);\n\t\t\t\t\t\t\tdp2[r][cmsk]=(dp2[r][cmsk]+dp2[l][j]*sgvl[l][r][i][t+1])%mod;\n\t\t\t\t\t\t\tdpvl2[r][cmsk]=(dpvl2[r][cmsk]+(dp2[l][j]+dpvl2[l][j])*sgvl[l][r][i][t+1])%mod;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tans=0;\n\t\tfor(j=1;j<(1<<n);j++)ans=(ans+dpvl2[n][j])%mod;\n\t\tcout<<ans<<'\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2063",
    "index": "A",
    "title": "Minimal Coprime",
    "statement": "\\begin{center}\n{\\small Today, Little John used all his savings to buy a segment. He wants to build a house on this segment.}\n\\end{center}\n\nA segment of positive integers $[l,r]$ is called coprime if $l$ and $r$ are coprime$^{\\text{∗}}$.\n\nA coprime segment $[l,r]$ is called minimal coprime if it does not contain$^{\\text{†}}$ any coprime segment not equal to itself. To better understand this statement, you can refer to the notes.\n\nGiven $[l,r]$, a segment of positive integers, find the number of minimal coprime segments contained in $[l,r]$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$Two integers $a$ and $b$ are coprime if they share only one positive common divisor. For example, the numbers $2$ and $4$ are not coprime because they are both divided by $2$ and $1$, but the numbers $7$ and $9$ are coprime because their only positive common divisor is $1$.\n\n$^{\\text{†}}$A segment $[l',r']$ is contained in the segment $[l,r]$ if and only if $l \\le l' \\le r' \\le r$.\n\\end{footnotesize}",
    "tutorial": "It is easy to see that two integers $l$ and $l+1$ are always coprime, due to $\\gcd(l,l+1)=\\gcd(1,l)=\\gcd(0,1)=1$. Thus, all segments in the form $[l,l+1]$ are coprime, and all minimal coprime segments must have a size of at most $2$ (otherwise, it will contain another segment of size $2$). It can be observed that the only coprime segment with size $1$ is $[1,1]$ as $\\gcd(a,a)=a$. The set of minimal coprime segments is as follows: $[1,1]$ is minimal coprime. For all $l>1$, $[l,l+1]$ is minimal coprime. And there is no other segment that is minimal coprime. The solution is thus as follows: If $x=y=1$, it contains $[1,1]$ and the answer is $1$. Otherwise, $y>1$. There exists exactly one $l$ for all $x \\le l < y$ such that $[l,*]$ is minimal coprime and is contained in $[x,y]$. In other words, the answer is $(y-1)-x+1=y-x$ in this case. In other words, the answer is $(y-1)-x+1=y-x$ in this case. The problem has been solved with time complexity $\\mathcal{O}(1)$ per test case.",
    "code": "for i in range(int(input())):\n    x,y=map(int,input().split())\n    if x==y==1:\n        print(1)\n    else:\n        print(y-x)",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2063",
    "index": "B",
    "title": "Subsequence Update",
    "statement": "\\begin{center}\n{\\small After Little John borrowed expansion screws from auntie a few hundred times, eventually she decided to come and take back the unused ones.But as they are a crucial part of home design, Little John decides to hide some in the most unreachable places — under the eco-friendly wood veneers.}\n\\end{center}\n\nYou are given an integer sequence $a_1, a_2, \\ldots, a_n$, and a segment $[l,r]$ ($1 \\le l \\le r \\le n$).\n\nYou must perform the following operation on the sequence \\textbf{exactly once}.\n\n- Choose any \\textbf{subsequence}$^{\\text{∗}}$ of the sequence $a$, and reverse it. Note that the subsequence does not have to be contiguous.\n\nFormally, choose any number of indices $i_1,i_2,\\ldots,i_k$ such that $1 \\le i_1 < i_2 < \\ldots < i_k \\le n$. Then, change the $i_x$-th element to the original value of the $i_{k-x+1}$-th element simultaneously for all $1 \\le x \\le k$.\n\nFind the \\textbf{minimum value} of $a_l+a_{l+1}+\\ldots+a_{r-1}+a_r$ after performing the operation.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) element from arbitrary positions.\n\\end{footnotesize}",
    "tutorial": "To solve this problem, it is important to observe and prove the following claim: Claim: It is not beneficial to choose indices $i<l$ and $j>r$ at the same time. Notice that we only care about values that end up on indices in $[l,r]$. If we choose $i_1,i_2,\\ldots,i_k$ such that $i_1<l$ and $i_k>r$, $i_1$ and $i_k$ will be swapped with each other and not change the values that end up on $[l,r]$. This means we can exchange it for a shorter sequence of indices $i_2,i_3,\\ldots,i_{k-1}$, preserving the values ending up on $[l,r]$. If we repeat this exchange until it is no longer possible, it will satisfy either: Every index $i$ is in $[l,n]$; or every index $i$ is in $[1,r]$. We can solve for both cases separately. For either case, we can constructively show that we can get the minimum $r-l+1$ values in the subsegment into $[l,r]$. The proof is as follows: WLOG assume we are solving for $[1,r]$, and the indices of the $k=r-l+1$ minimum values are $j_1,j_2,\\ldots,j_k$. Then: If we select every index in $[l,r]$ not one of the minimum $k$ values, there will be $x$ of them. If we select every index outside $[l,r]$ which is one of the minimum $k$ values, there will be also $x$ of them. Thus, we end up with a subsequence of length $2x$, that gets the minimum $k$ values into the subsegment $[l,r]$. As a result, we only have to find the minimum $k$ values of the subsegment. This can be done easily with sorting. Do this for both $[1,r]$ and $[l,n]$, and we get the answer. The problem has been solved with time complexity $\\mathcal{O}(n \\log n)$ per test case, due to sorting.",
    "code": "import sys\ninput=lambda:sys.stdin.readline().rstrip()\n \nfor _ in range(int(input())):\n    n,l,r=map(int,input().split());l-=1\n    arr=[*map(int,input().split())]\n    brr=arr[:l]+sorted(arr[l:])\n    crr=sorted(arr[:r])[::-1]+arr[r:]\n    print(min(sum(brr[l:r]),sum(crr[l:r])))",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2063",
    "index": "C",
    "title": "Remove Exactly Two",
    "statement": "\\begin{center}\n{\\small Recently, Little John got a tree from his aunt to decorate his house. But as it seems, just one tree is not enough to decorate the entire house. Little John has an idea. Maybe he can remove a few vertices from the tree. That will turn it into more trees! Right?}\n\\end{center}\n\nYou are given a tree$^{\\text{∗}}$ of $n$ vertices. You must perform the following operation \\textbf{exactly twice}.\n\n- Select a vertex $v$;\n- Remove all edges incident to $v$, and also the vertex $v$.\n\nPlease find the maximum number of connected components after performing the operation \\textbf{exactly twice}.\n\nTwo vertices $x$ and $y$ are in the same connected component if and only if there exists a path from $x$ to $y$. For clarity, note that the graph with $0$ vertices has $0$ connected components by definition.$^{\\text{†}}$\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\n$^{\\text{†}}$But is such a graph connected?\n\\end{footnotesize}",
    "tutorial": "The main observation behind this task is that the number of connected components increases by $\\text{deg}-1$, where $\\text{deg}$ is the degree of the removed vertex at the time of removing. Thus, the number of connected components after removing two vertices $i$ and $j$ is: $d_i+d_j-1$ if $i$ and $j$ are not adjacent; $d_i+d_j-2$ if $i$ and $j$ are adjacent, because removing $i$ will decrease $\\text{deg}$ of $j$ by $1$. The main approaches in maximizing this appear only after this observation. There are multiple approaches to this, where the editorial will introduce two of them. First Approach: Bruteforcing the First Vertex You can maintain a sorted version of the degree sequence, using a std::multiset, a heap, or possibly even simply a sorted sequence. After you fix the first vertex $i$, you can find the maximum degree after decreasing the degrees of all adjacent vertices by $1$. std::multiset can deal with this directly by removing and inserting values, while a heap or a sorted sequence can deal with this by popping elements from the end while the two maximums have the same value. Then, the second vertex is easily the one with maximum degree. Maintaining the degrees takes $\\mathcal{O}(d \\log n)$ time. As $\\sum d = 2m = 2(n-1) = \\mathcal{O}(n)$, the total time complexity of this approach is $\\mathcal{O}(n \\log n)$. Second Approach: Bruteforcing the Second Vertex If we greedily select the first vertex by degree, we can notice that selecting the first vertex as one with maximum initial degree will find at least one optimal solution. Assume that the first vertex with maximum degree had a maximum value $d_i+d_j-2$. Then, consider any solution with both vertices' initial degrees strictly less than $d_i$. This second solution's maximum possible value $d_{i'}+d_{j'}-1$ will never exceed $d_i+d_j-2$, because $d_{i'}<d_i$ and $d_{j'} \\le d_j$. Thus, at least one optimal answer must have the first vertex as one with maximum initial degree. But we do not know what to do when there are multiple first vertices with maximum initial degree. Luckily, trying only two first vertices with maximum initial degrees will always find one optimal answer. This can be proven by contradiction; If the two first vertices are $u$ and $v$, and the second vertex chosen in the bruteforce is $w$. At least one pair in $(u,v)$, $(u,w)$, $(v,w)$ will be not adjacent, because otherwise it implies the existence of a $3$-cycle, which can only exist if the graph is not a tree. Thus, if the optimal solution is in the form $d_u+d_w-1$, trying two first vertices will always find it. Therefore, we can try two vertices greedily for the first vertex and try all other vertices as the second vertex, finding at least one optimal answer in the process. The time complexity of this approach is $\\mathcal{O}(n \\log n)$ or $\\mathcal{O}(n)$ depending on how adjacency is checked. Adjacency check in $\\mathcal{O}(1)$ is possible by preprocessing parents using DFS, because \"$u$ and $v$ are adjacent\" is equivalent to \"$par_u=v$ or $par_v=u$\".",
    "code": "import sys\ninput=lambda:sys.stdin.readline().rstrip()\nfor i in range(int(input())):\n    n=int(input())\n    deg=[0]*n\n    adj=[[] for i in range(n)]\n    for i in range(n-1):\n        u,v=map(int,input().split())\n        u-=1;v-=1\n        deg[u]+=1\n        deg[v]+=1\n        adj[u].append(v)\n        adj[v].append(u)\n    ans=1\n    mans=0\n    sdeg=sorted(deg)\n    for i in range(n):\n        ans=deg[i]\n        ideg=[]\n        for v in adj[i]:\n            ideg.append(deg[v])\n        ideg.append(deg[i])\n        ideg.sort(reverse=True)\n        rem=[]\n        mx=-1\n        for d in ideg:\n            if sdeg[-1]==d:\n                sdeg.pop()\n                rem.append(d)\n        rem.reverse()\n        if sdeg:\n            mx=max(mx,sdeg[-1])\n        for v in adj[i]:\n            mx=max(mx,deg[v]-1)\n        for d in rem:\n            sdeg.append(d)\n        mans=max(ans+mx-1,mans)\n    print(mans)",
    "tags": [
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2063",
    "index": "D",
    "title": "Game With Triangles",
    "statement": "\\begin{center}\n{\\small Even Little John needs money to buy a house. But he recently lost his job; how will he earn money now? Of course, by playing a game that gives him money as a reward! Oh well, maybe not those kinds of games you are thinking about.}\n\\end{center}\n\nThere are $n+m$ distinct points $(a_1,0), (a_2,0), \\ldots, (a_{n},0), (b_1,2), (b_2,2), \\ldots, (b_{m},2)$ on the plane. Initially, your score is $0$. To increase your score, you can perform the following operation:\n\n- Choose three distinct points which are not collinear;\n- Increase your score by the area of the triangle formed by these three points;\n- Then, erase the three points from the plane.\n\n\\begin{center}\n{\\small An instance of the game, where the operation is performed twice.}\n\\end{center}\n\nLet $k_{\\max}$ be the maximum number of operations that can be performed. For example, if it is impossible to perform any operation, $k_\\max$ is $0$. Additionally, define $f(k)$ as the maximum possible score achievable by performing the operation \\textbf{exactly $k$ times}. Here, $f(k)$ is defined for all integers $k$ such that $0 \\le k \\le k_{\\max}$.\n\nFind the value of $k_{\\max}$, and find the values of $f(x)$ for all integers $x=1,2,\\ldots,k_{\\max}$ independently.",
    "tutorial": "Whenever the operation is performed, your score increases by $a_j-a_i$ or $b_j-b_i$, where $i$, $j$ are the indices you choose two points on (WLOG $a_i<a_j$ or $b_i<b_j$, but this assumption is not necessary). For simplicity, we will call an operation where you choose two on $y=0$ \"Operation A\", and those where you choose two on $y=2$ \"Operation B\". Let us define a function $g(p,q)$ as the maximum score after performing \"Operation A\" $x$ times and \"Operation B\" $y$ times, assuming it is possible. Then, it is not hard to prove that $g(p,q)$ equates to the following value: $g(p,q)=\\sum_{i=1}^p {(A_{n+1-i}-A_i)}+\\sum_{i=1}^q {(B_{m+1-i}-B_i)}$ Here, $A$ and $B$ are sorted versions of $a$ and $b$. The proof is left as a practice for the reader; if you want a rigorous proof, an approach using the rearrangement inequality might help you. Then, assuming the value $x$ is always chosen so that the operations can be performed, the value of $f(k)$ will be as follows. $f(k)= \\max_x{g(x,k-x)}$ Now we have two questions to ask ourselves: For what values of $x$ is it impossible to perform the operations? How do we maximize this value? The first is relatively easier. We first return to the definition of $g(p,q)$, and find specific inequalities from it. Then, exactly four inequalities can be found as follows: $2p+q \\le n$, because otherwise we will use more than $n$ points on $y=0$; $p+2q \\le m$, because otherwise we will use more than $m$ points on $y=2$; $p \\ge 0$, trivially; $q \\ge 0$, also trivially. The feasible region found by the inequalities. Assigning $x$ and $k-x$ to $p$ and $q$ for each inequality, we get the following four inequalities: $2x+k-x = x+k \\le n \\longleftrightarrow x \\le n-k$; $x+2(k-x) = 2k-x \\le m \\longleftrightarrow x \\ge 2k-m$; $x \\ge 0$; $k-x \\ge 0 \\longleftrightarrow x \\le k$. Compiling all four inequalities into one inequality, we get the following. $\\max(0,2k-m) \\le x \\le \\min(k,n-k)$ So now we can easily judge if the operations can be performed for some value $x$. Also, it is easy to see that when the lefthand bound exceeds the righthand bound, it is impossible to perform $k$ operations. Thus, here we can derive $k_\\max$. Though it is easy to find a closed form for $k_\\max$, it is not required for this problem. Now for the next question. Naively computing the values for every $x$ in the range for all $k$ takes us $\\mathcal{O}(nm)$ time. How to do it faster? Again, go back to the definition of $g(p,q)$. Observe that the value dependent on $p$ is a prefix sum of a strictly decreasing sequence, and thus is convex. Likewise, the value dependent on $q$ is also convex. So, given that $g(x,k-x)$ is a sum of two convex functions of $x$, $g(x,k-x)$ is just another convex function of $x$. Thus, as we already know the range of $x$, we can perform a ternary search on the range. Note that we are doing ternary search on integers and not on real values, so you might need to take extra care of off-by-one errors. There are other ways to solve this task (also relying a lot on the convexity), like doing binary search instead of ternary search, or performing two pointers for $p$ and $q$. Anyways, the time complexity is $\\mathcal{O}(n \\log n + m \\log m)$, bounded below by time complexity of sorting.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n \nint main()\n{\n  cin.tie(0)->sync_with_stdio(0);\n  int t;cin>>t;\n  while(t--)\n  {\n    int n,m;cin>>n>>m;\n    vector<ll>arr(n),brr(m);\n    for(ll&i:arr)cin>>i;\n    for(ll&i:brr)cin>>i;\n    sort(begin(arr),end(arr));\n    sort(begin(brr),end(brr));\n    vector<ll>asum(n+2),bsum(m+2);\n    for(int i=1;i<=n;i++)asum[i]=asum[i-1]+(arr[n-i]-arr[i-1]);\n    for(int i=1;i<=m;i++)bsum[i]=bsum[i-1]+(brr[m-i]-brr[i-1]);\n    vector<ll>ans{0};\n    // maximize asum[ka]+bsum[kb]\n    // s.t. ka+kb = x\n    //      ka*2+kb <= n -> ka*2+(x-ka) <= n -> ka+x <= n   -> ka <= n-x\n    //      ka+kb*2 <= m -> ka+2*(x-ka) <= m -> 2*x-ka <= m -> ka >= 2*x-m\n    //      ka >= 0, x-ka >= 0\n    for(int x=1;2*x-m<=n-x;x++)\n    {\n      ll L=max(0,2*x-m),R=min(x,n-x);\n      if(L>R)break;\n      auto f=[&](int ka){return asum[ka]+bsum[x-ka];};\n      while(R-L>3)\n      {\n        ll mL=(L*2+R)/3,mR=(L+R*2)/3;\n        if(f(mL)>f(mR))R=mR;\n        else L=mL;\n      }\n      ll mans=0;\n      for(int i=L;i<=R;i++)\n      {\n        mans=max(mans,f(i));\n      }\n      ans.push_back(mans);\n    }\n    int kmax=(int)size(ans)-1;\n    cout<<kmax<<\"\\n\";\n    for(int i=1;i<=kmax;i++)cout<<ans[i]<<\" \\n\"[i==kmax];\n  }\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "geometry",
      "greedy",
      "implementation",
      "math",
      "ternary search",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2063",
    "index": "E",
    "title": "Triangle Tree",
    "statement": "\\begin{center}\n{\\small One day, a giant tree grew in the countryside. Little John, with his childhood eagle, decided to make it his home. Little John will build a structure on the tree with galvanized square steel. However, little did he know, he could not build what is physically impossible.}\n\\end{center}\n\nYou are given a rooted tree$^{\\text{∗}}$ containing $n$ vertices rooted at vertex $1$. A pair of vertices $(u,v)$ is called a good pair if $u$ is not an ancestor$^{\\text{†}}$ of $v$ and $v$ is not an ancestor of $u$. For any two vertices, $\\text{dist}(u,v)$ is defined as the number of edges on the unique simple path from $u$ to $v$, and $\\text{lca}(u,v)$ is defined as their lowest common ancestor.\n\nA function $f(u,v)$ is defined as follows.\n\n- If $(u,v)$ is a good pair, $f(u,v)$ is the number of distinct integer values $x$ such that there exists a \\textbf{non-degenerate triangle}$^{\\text{‡}}$ formed by side lengths $\\text{dist}(u,\\text{lca}(u,v))$, $\\text{dist}(v,\\text{lca}(u,v))$, and $x$.\n- Otherwise, $f(u,v)$ is $0$.\n\nYou need to find the following value: $$\\sum_{i = 1}^{n-1} \\sum_{j = i+1}^n f(i,j).$$\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles. A rooted tree is a tree where one vertex is special and called the root.\n\n$^{\\text{†}}$An ancestor of vertex $v$ is any vertex on the simple path from $v$ to the root, including the root, but not including $v$. The root has no ancestors.\n\n$^{\\text{‡}}$A triangle with side lengths $a$, $b$, $c$ is non-degenerate when $a+b > c$, $a+c > b$, $b+c > a$.\n\\end{footnotesize}",
    "tutorial": "In this editorial, we will denote the depth of vertex $v$ as $d_v$, and the subtree size of vertex $v$ as $s_v$. They can be easily calculated using DFS. Let us try to first understand what $f(x,y)$ means. If the two edge lengths are $a$ and $b$ (WLOG $a \\le b$), the third edge length $L$ must satisfy $a+b>L$ and $a+L>b$. This results in the inequality $b-a<L<a+b$. There are exactly $2a-1$ values that satisfy this, from $b-a+1$ to $a+b-1$. This means, if $(u,v)$ is a good pair, the following holds. $f(u,v)=2 \\cdot \\min(\\text{dist}(u,\\text{lca}(u,v)),\\text{dist}(v,\\text{lca}(u,v)))-1$ And of course, if $(u,v)$ is not a good pair, $f(u,v)=0$ by definition. Naively summing this up for all pairs takes at least $\\Theta(n^2)$ time. We will simplify the function $f(u,v)$ into a form that can be computed in batches easily, and provide a different summation that finds the same answer using a double counting proof. The simplified version of $f(u,v)$ is as follows: $\\begin{split} f(u,v) & = 2 \\cdot \\min(\\text{dist}(u,\\text{lca}(u,v)),\\text{dist}(v,\\text{lca}(u,v)))-1 \\\\ & = 2 \\cdot \\min(d_u-d_\\text{lca},d_v-d_\\text{lca})-1 \\\\ & = 2 \\cdot \\min(d_u,d_v)-2 d_\\text{lca} -1 \\end{split}$ So now we can consider summing up $2 \\cdot \\min(d_u,d_v)$ and $2d_\\text{lca}+1$ separately. For the former, consider the condition for vertex $u$ to decide the value of $\\min(d_u,d_v)$. For this, $d_v$ must be no less than $d_u$, and $v$ must not be a descendant of $u$ (because then it will not be a good pair). Therefore, vertex $u$ decides $\\min(d_u,d_v)$ for $(\\#(d \\ge d_u)-s_u)$ different vertices. $\\#(d \\ge d_u)$ can be computed using a suffix sum of frequency values of $d$. Thus, we will sum up $2 d_u \\cdot (\\#(d \\ge d_u)-s_u)$ for all vertices. This only has a very small issue; it counts pairs $(u,v)$ where $d_u=d_v$ twice. But thankfully, all of these pairs are good pairs (otherwise they would be the same vertex), and we can simply subtract the sum of $2k \\cdot \\binom{\\#(d = k)}{2}$ over all $k$ from the last value. For the latter, consider the condition for vertex $w$ to be the LCA of $u$ and $v$. $u$ and $v$ should be descendants of $w$ not equal to $w$, and they should not be in the same subtree under $w$ (because then there will be a lower common ancestor). Thus, given that the number of possible descendants is $S=s_w-1$, we can get the following value for one vertex $w$ in $\\mathcal{O}(\\#(\\text{children}))$. Counting for all vertices thus takes $\\mathcal{O}(n)$ time. $\\sum_{par_u=w} {s_u(S-s_u)}$ This also has a very slight issue; it counts $(u,v)$ and $(v,u)$ separately, so we only have to divide this value by $2$ to get the number of good pairs with vertex $w$ as LCA. Multiplying $2d_w+1$ during the summation, we get the sum of the latter value. Thus, we have proved that the following sum yields the very same value that we need: $\\sum_{u=1}^n{\\left({2 d_u \\cdot (\\#(d \\ge d_u)-s_u)}\\right)}-\\sum_{k=0}^{n-1}{\\left({2k \\cdot \\binom{\\#(d = k)}{2}}\\right)}-\\frac{1}{2}\\sum_{w=1}^n {\\left({(2d_w+1) \\cdot \\sum_{par_u=w}{s_u(s_w-1-s_u)}}\\right)}$ Everything in this summation is in a form that can be computed in $\\mathcal{O}(n)$ total time. Therefore, we have solved the problem with time complexity $\\mathcal{O}(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n\nint main()\n{\n    cin.tie(0)->sync_with_stdio(0);\n    int t;cin>>t;\n    while(t--)\n    {\n        ll n;cin>>n;\n        vector<ll>d(n,0),s(n),dc(n),dcs;\n        vector<vector<ll>>adj(n);\n        for(int i=1;i<n;i++)\n        {\n            int u,v;cin>>u>>v;\n            u--;v--;\n            adj[u].push_back(v);\n            adj[v].push_back(u);\n        }\n        auto dfs1=[&](auto dfs1,int v,int p=-1)->void\n        {\n            dc[d[v]]++;\n            ll sz=1;\n            for(int w:adj[v])if(w!=p)\n            {\n                d[w]=d[v]+1;\n                dfs1(dfs1,w,v);\n                sz+=s[w];\n            }\n            s[v]=sz;\n        };\n        dfs1(dfs1,0);\n        dcs=dc;\n        for(int i=n-2;i>=0;i--)dcs[i]+=dcs[i+1];\n        ll ans=0,ans2=0;\n        auto dfs2=[&](auto dfs2,int v,int p=-1)->void\n        {\n            // v is min\n            ans+=2*d[v]*(dcs[d[v]]-s[v]);\n            // v is lca\n            ll subcnt=s[v]-1,lcnt=0;\n            for(int w:adj[v])if(w!=p)\n            {\n                lcnt+=(subcnt-s[w])*s[w];\n                dfs2(dfs2,w,v);\n            }\n            ans2+=(2*d[v]+1)*(lcnt/2);\n        };\n        dfs2(dfs2,0);\n        for(int i=0;i<n;i++)\n        {\n            ans2+=i*dc[i]*(dc[i]-1);\n        }\n        cout<<ans-ans2<<\"\\n\";\n    }\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2063",
    "index": "F1",
    "title": "Counting Is Not Fun (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, the limits on $t$ and $n$ are smaller. You can hack only if you solved all versions of this problem.}\n\n\\begin{center}\n{\\small Now Little John is rich, and so he finally buys a house big enough to fit himself and his favorite bracket sequence. But somehow, he ended up with a lot of brackets! Frustrated, he penetrates through the ceiling with the \"buddha palm\".}\n\\end{center}\n\nA bracket sequence is called balanced if it can be constructed by the following formal grammar.\n\n- The empty sequence $\\varnothing$ is balanced.\n- If the bracket sequence $A$ is balanced, then $\\mathtt{(}A\\mathtt{)}$ is also balanced.\n- If the bracket sequences $A$ and $B$ are balanced, then the concatenated sequence $A B$ is also balanced.\n\nFor example, the sequences \"(())()\", \"()\", \"(()(()))\", and the empty sequence are balanced, while \"(()\" and \"(()))(\" are not.\n\nGiven a balanced bracket sequence $s$, a pair of indices $(i,j)$ ($i<j$) is called a good pair if $s_i$ is '(', $s_j$ is ')', and the two brackets are added simultaneously with respect to Rule 2 while constructing the sequence $s$. For example, the sequence \"(())()\" has three different good pairs, which are $(1,4)$, $(2,3)$, and $(5,6)$. One can show that any balanced bracket sequence of $2n$ brackets contains exactly $n$ different good pairs, and using any order of rules to construct the same bracket sequence will yield the same set of good pairs.\n\nEmily will play a bracket guessing game with John. The game is played as follows.\n\nInitially, John has a balanced bracket sequence $s$ containing $n$ different good pairs, which is not known to Emily. John tells Emily the value of $n$ and asks Emily to guess the sequence.\n\nThroughout $n$ turns, John gives Emily the following kind of clue on each turn.\n\n- $l\\;r$: The sequence $s$ contains a good pair $(l,r)$.\n\nThe clues that John gives Emily are pairwise distinct and do not contradict each other.\n\nAt a certain point, Emily can be certain that the balanced bracket sequence satisfying the clues given so far is unique. For example, assume Emily knows that $s$ has $3$ good pairs, and it contains the good pair $(2,5)$. Out of $5$ balanced bracket sequences with $3$ good pairs, there exists only one such sequence \"((()))\" with the good pair $(2,5)$. Therefore, one can see that Emily does not always need $n$ turns to guess $s$.\n\nTo find out the content of $s$ as early as possible, Emily wants to know the number of different balanced bracket sequences that match the clues after each turn. Surely, this is not an easy job for Emily, especially when she is given so many good pairs. Now it is your turn to help Emily. Given the clues, you must find the answer before and after each turn. As the answers may be huge, you need to find them modulo $998\\,244\\,353$.",
    "tutorial": "To solve the easy subtask, you can derive some helpful properties from the usual stack-based algorithm to determine whether a bracket sequence is balanced. Note the following well-known fact. Fact: The good pairs are exactly the pairs of brackets that are popped \"together\" in the stack-based algorithm. Considering this, we can observe these two facts. The subsequence inside the good pair must be balanced, or otherwise the two brackets would not be popped together. The subsequence outside the good pair must be balanced, or otherwise the entire string won't be balanced. Then, given $k$ good pairs, you will find $\\mathcal{O}(k)$ \"minimal subsequences\" that you know are balanced, defined by this information. (In fact, it is more correct to define \"minimal balanced subsequences\" to include the good pairs themselves, but in the easy subtask we ignore this to get an easier explanation by sacrificing details.) In fact, these $\\mathcal{O}(k)$ minimal balanced subsequences are just the subsequences found by the following modification to the stack-based algorithm: In the usual stack-based algorithm, instead of pushing only brackets into the stack, push everything on the way into the stack. When you pop a closing bracket, pop everything until you find an opening bracket. Then, the $k$ popped subsequences, and the subsequence outside the outermost good pairs, are minimal balanced subsequences. It is known that there are $C_n$ different balanced bracket sequences of length $2n$, where $C_k$ is the $k$-th Catalan number. So for each of the minimal balanced subsequences, you can multiply $C_{len/2}$ to the answer, given that the minimal balanced subsequence has length $len$. This is the answer we needed to know. Therefore, you can simply update the string and re-run the stack-based algorithm everytime. Each run of the stack-based algorithm takes $\\mathcal{O}(n)$ time, so the problem is solved in $\\mathcal{O}(n^2)$ time complexity. For the easy subtask, the Catalan numbers can be preprocessed in $\\mathcal{O}(n^2)$ time, and it was not necessary to use the combinatorial definition. However, if you compute Catalan numbers on the fly instead of preprocessing, or construct a tree explicitly, the time limit may be a little tight for you as the solution will have an extra log factor. Do keep this in mind when you implement the solution.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\nconst ll md=998244353;\n \nint main()\n{\n    int t;cin>>t;\n    vector<ll>ctl(5050);\n    ctl[0]=1;\n    for(int n=1;n<5050;n++)\n    {\n        for(int i=1;i<=n;i++)\n        {\n            ctl[n]=(ctl[n]+ctl[i-1]*ctl[n-i]%md)%md;\n        }\n    }\n    while(t--)\n    {\n        int n;cin>>n;\n        ll ans=ctl[n];\n        cout<<ans<<\" \";\n        string s(2*n+2,'.');\n        s[0]='(';s[2*n+1]=')';\n        for(int a=0;a<n;a++)\n        {\n            int i,j;cin>>i>>j;\n            ans=1;\n            s[i]='(';\n            s[j]=')';\n            string stk;\n            for(char c:s)\n            {\n                if(c==')')\n                {\n                    int cnt=0;\n                    while(stk.back()!='(')\n                    {\n                        cnt++;\n                        stk.pop_back();\n                    }\n                    stk.pop_back();\n                    ans=(ans*ctl[cnt/2])%md;\n                }\n                else stk+=c;\n            }\n            cout<<ans<<\" \\n\"[a+1==n];\n        }\n    }\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "hashing",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2063",
    "index": "F2",
    "title": "Counting Is Not Fun (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, the limits on $t$ and $n$ are bigger. You can hack only if you solved all versions of this problem.}\n\n\\begin{center}\n{\\small Now Little John is rich, and so he finally buys a house big enough to fit himself and his favorite bracket sequence. But somehow, he ended up with a lot of brackets! Frustrated, he penetrates through the ceiling with the \"buddha palm\".}\n\\end{center}\n\nA bracket sequence is called balanced if it can be constructed by the following formal grammar.\n\n- The empty sequence $\\varnothing$ is balanced.\n- If the bracket sequence $A$ is balanced, then $\\mathtt{(}A\\mathtt{)}$ is also balanced.\n- If the bracket sequences $A$ and $B$ are balanced, then the concatenated sequence $A B$ is also balanced.\n\nFor example, the sequences \"(())()\", \"()\", \"(()(()))\", and the empty sequence are balanced, while \"(()\" and \"(()))(\" are not.\n\nGiven a balanced bracket sequence $s$, a pair of indices $(i,j)$ ($i<j$) is called a good pair if $s_i$ is '(', $s_j$ is ')', and the two brackets are added simultaneously with respect to Rule 2 while constructing the sequence $s$. For example, the sequence \"(())()\" has three different good pairs, which are $(1,4)$, $(2,3)$, and $(5,6)$. One can show that any balanced bracket sequence of $2n$ brackets contains exactly $n$ different good pairs, and using any order of rules to construct the same bracket sequence will yield the same set of good pairs.\n\nEmily will play a bracket guessing game with John. The game is played as follows.\n\nInitially, John has a balanced bracket sequence $s$ containing $n$ different good pairs, which is not known to Emily. John tells Emily the value of $n$ and asks Emily to guess the sequence.\n\nThroughout $n$ turns, John gives Emily the following kind of clue on each turn.\n\n- $l\\;r$: The sequence $s$ contains a good pair $(l,r)$.\n\nThe clues that John gives Emily are pairwise distinct and do not contradict each other.\n\nAt a certain point, Emily can be certain that the balanced bracket sequence satisfying the clues given so far is unique. For example, assume Emily knows that $s$ has $3$ good pairs, and it contains the good pair $(2,5)$. Out of $5$ balanced bracket sequences with $3$ good pairs, there exists only one such sequence \"((()))\" with the good pair $(2,5)$. Therefore, one can see that Emily does not always need $n$ turns to guess $s$.\n\nTo find out the content of $s$ as early as possible, Emily wants to know the number of different balanced bracket sequences that match the clues after each turn. Surely, this is not an easy job for Emily, especially when she is given so many good pairs. Now it is your turn to help Emily. Given the clues, you must find the answer before and after each turn. As the answers may be huge, you need to find them modulo $998\\,244\\,353$.",
    "tutorial": "If you have not read the editorial for the easy subtask, I strongly suggest you to read it first. It contains some important observations that carry on to the solution of the hard subtask. The easy subtask's solution relied on enumerating the \"minimal balanced subsequences\". (We will use this same term repeatedly in the hard subtask's editorial, so we abbreviate it to \"MBS(es)\" for convenience. Note that, as opposed to the easy version, the definition of MBSes in the hard version's editorial includes the good pairs themselves.) Now, the hard subtask makes it impossible to use the $\\mathcal{O}(n^2)$ solution, so we cannot enumerate the MBSes. The hard subtask asks for a more clever approach. An important observation for the hard subtask is as follows: Observation: When a new good pair is added, in fact, most MBSes do not change. If a good pair is added on an MBS $a$ which is enclosed by another MBS $b$, the MBS $b$ does not change because the good pair does not give any additional information about $b$. (It just gave the information that some supersequence of $b$ is balanced, but that doesn't make any additional information about $b$.) If a good pair is added on an MBS $c$ which encloses another MBS $d$, the MBS $d$ does not change because the good pair does not give any additional information about $d$. (It just gave the information that some supersequence of $d$ is balanced, but that doesn't make any additional information about $d$.) If a good pair is added on an MBS $e$ and there is another MBS $f$ not enclosing/enclosed by it, the MBS $f$ does not change either; the two MBSes are simply independent. Therefore, when the good pair is added on an MBS $S$, the only MBS that changes is $S$, and all other MBSes do not change. Let's observe what happens when a good pair is added on an MBS $S$. Precisely the following things happen according to the information that this good pair adds: As the subsequence inside the good pair must be balanced, the subsequence containing indices inside the good pair becomes a new MBS (assuming that it exists). As the subsequence outside the good pair must be balanced, the subsequence containing indices outside the good pair becomes a new MBS (assuming that it exists). The good pair itself becomes a new MBS, assuming the MBS $S$ was not a single good pair. Thus, the MBS splits into at most three new MBSes upon the addition of a good pair. For example, if the MBS $S$ was $[1,2,5,6,7,8,11,12,13,14]$, and the good pair is $(5,12)$, the MBS splits to three following MBSes: $[6,7,8,11]$ inside the good pair; $[1,2,13,14]$ outside the good pair; $[5,12]$ denoting the good pair itself. Note that the two brackets making a good pair are always added on the same MBS, because otherwise it must make \"contradicting informations\". If we can track the MBSes, split efficiently, and count the number of indices in the resulting MBSes, we can do the following to update the answer: When an MBS $S$ is split into three MBSes $A$, $B$ and the good pair, divide (multiply the inverse) the answer by $C_{|S|/2}$, and multiply the answer by $C_{|A|/2} \\cdot C_{|B|/2}$. The Catalan number corresponding to the good pair is automatically $1$, so it does not matter. To deal with the required operations, the model solution uses a forest of splay trees. A forest of splay trees is just a splay tree which does not specify a single root, so there can be multiple roots in the structure. In practice, a node is considered a root simply if it does not have a parent. Ideally, it is most convenient to implement it on a sequential data structure (e.g. vector) using indices than using pointers in this task, because you will need to access a node immediately given the index. It is possible to do the same using treaps, but some operations' implementation may be more convoluted if you use treaps. You can notice that detecting if there exist subsequences inside or outside the good pair naturally translate to a series of simple operations on the splay tree, like follows: Detecting a subsequence inside: if there exists a subsequence inside the good pair $(l,r)$, you can splay the node $l$ and cut its right subtree. Now the right subtree will only contain values greater than $l$, so if you splay node $r$ on it, node $r$ will not have a left subtree if and only if there was no subsequence inside $(l,r)$. If there exists a subsequence inside, then the left child of $r$ is one element of the subsequence inside. Detecting a subsequence outside: if there exists a subsequence outside the good pair $(l,r)$, the tree will have values either less than $l$ or greater than $r$. In other words, if you splay node $l$ and find a left subtree, or splay node $r$ and find a right subtree, there exists a subsequence outside. Connecting the left and right subsequences: The left subtree of $l$ after it is splayed, and the right subtree of $r$ after it is splayed, might both have two children. If that is the case, you can simply find the leftmost node in the right subtree of $r$ and splay it, and then connect the left subtree of $l$ to its left. (This is only just a simple binary search tree operation.) Counting the subsequence sizes after the split: This is simple; we already found at least one node corresponding to each of the two subsequences. Splay the two nodes and find the size of the trees. The structure of the trees before and after splitting the subsequence. Note that this might not be precisely correct in terms of splay operations. Now the only thing left in the solution is careful implementation. The solution has an amortized time complexity of $\\mathcal{O}(n \\log n)$, and runs comfortably in $1$ second. Though the model solution used a complex data structure to utilize its convenient characteristics, the author acknowledges that it is possible to replace some details or entire sections of the editorial with other data structures or techniques such as segment trees or a smaller-to-larger trick. If you can prove that your solution works in $\\mathcal{O}(n \\log n)$ time complexity with a not too terrible constant, your solution is deemed to be correct. UPD: People pointed out that the intended solution in the tutorial is overkill. Yes, I acknowledge this. Please look into the newly added alternative solution if you want a more elegant idea. Consider maintaining the MBSes directly, but instead of using a complex data structure, we will use a small-to-large trick with linked lists. Precisely, every time we have to split a linked list, we will identify the smaller section and split it out in $\\mathcal{O}(|small|)$ time, and then the amortized time complexity will be $\\mathcal{O}(n \\log n)$. In this solution, we do not consider bracket pairs as MBSes, for a specific reason. Given a linked list of indices and two nodes on it, we can identify the smaller section in $\\mathcal{O}(|small|)$ by iterating over both lists at the same time, interlacing the operations. The list which hit the end earlier will be the smaller one, and then we immediately know the value of $|small|$. The issue is that you cannot identify the size of both lists in $\\mathcal{O}(|small|)$ time. This is hard to fix using only a linked list. Instead, we will also maintain the implicit rooted tree structure of the bracket sequence. The MBSes correspond to vertices, and the bracket pairs correspond to edges. Initially, the tree just consists of one vertex of $2n$ brackets. Now, for each list node, we add a pointer to the corresponding tree vertex. Now we can know which tree vertex the list node corresponds to immediately, and if we bookkeep size informations in the tree vertices, we can also find the sum of two list sizes in $\\mathcal{O}(1)$. Therefore we can now know the size of both lists in $\\mathcal{O}(|small|)$ time. The only issue is with how to maintain the pointers to the tree vertices. But no problem, you can just do the small-to-large for this also. After splitting the tree vertex into two vertices and one edge, redirect the smaller list to the new smaller vertex. Theoretically there are enough ways to do this, such as swapping vertex indices. Also it is notable that it is not necessary to maintain the whole tree in this process, it is quite sufficient to just maintain it implicitly by just maintaining a sequence of sizes. The problem is solved online with $\\mathcal{O}(n \\log n)$ amortized time complexity.",
    "code": "#pragma GCC optimize(\"O3,unroll-loops\")\n\n#include <iostream>\n#include <numeric>\n#include <vector>\n\nconstexpr int MAX_N = 3e5;\nconstexpr long long MOD = 998244353;\n\nstruct _inv_small {\n  long long data[MAX_N + 2] = {0};\n  constexpr _inv_small() {\n    data[1] = 1;\n    for (int i = 2; i <= MAX_N; i += 2) {\n      data[i] = MOD - (MOD / i) * data[MOD % i] % MOD;\n      data[i + 1] = MOD - (MOD / (i + 1)) * data[MOD % (i + 1)] % MOD;\n    }\n  }\n};\n\nconstexpr _inv_small __inv_small;\n#define inv_small(x) __inv_small.data[x]\n\n#define inv(x) (x < MAX_N ? inv_small(x) : data[(x) - MAX_N])\nstruct _inv {\n  long long data[MAX_N + 3] = {0};\n  constexpr _inv() {\n    for (int i = 0; i <= MAX_N + 1; i += 2) {\n      data[i] = MOD - (MOD / (i + MAX_N)) * inv(MOD % (i + MAX_N)) % MOD;\n      data[i + 1] = MOD - (MOD / (i + MAX_N + 1)) * inv(MOD % (i + MAX_N + 1)) % MOD;\n    }\n  }\n};\n#undef inv\n\nconstexpr _inv __inv;\n#define inv(x) (x < MAX_N ? inv_small(x) : __inv.data[(x) - MAX_N])\n\nstruct _catalan {\n  long long data[MAX_N + 2] = {1};\n  constexpr _catalan() {\n    for (int i = 1; i <= MAX_N; i += 2) {\n      data[i] = (4 * i - 2) * data[i - 1] % MOD * inv(i + 1) % MOD;\n      data[i + 1] = (4 * i + 2) * data[i] % MOD * inv(i + 2) % MOD;\n    }\n  }\n};\n\nconstexpr _catalan __catalan;\n#define catalan(x) __catalan.data[x]\n\nstruct _catalan_inv {\n  long long data[MAX_N + 2] = {1};\n  constexpr _catalan_inv() {\n    for (int i = 1; i <= MAX_N; i += 2) {\n      data[i] = inv(2) * inv(2 * i - 1) % MOD * data[i - 1] % MOD * (i + 1) % MOD;\n      data[i + 1] = inv(2) * inv(2 * i + 1) % MOD * data[i] % MOD * (i + 2) % MOD;\n    }\n  }\n};\n\nconstexpr _catalan_inv __catalan_inv;\n#define catalan_inv(x) __catalan_inv.data[x]\n\nint main() {\n  std::cin.tie(0)->sync_with_stdio(0);\n\n  int t;\n  std::cin >> t;\n\n  for (int _ = 0; _ < t; ++_) {\n    int n;\n    std::cin >> n;\n\n    std::vector<bool> used(2 * n + 2);\n\n    std::vector<int> point(2 * n + 2);\n    std::iota(point.begin(), point.end(), 1);\n\n    std::vector<int> size(2 * n + 2);\n\n    std::vector<int> parent = {0};\n    std::vector<int> parent_idx(2 * n + 2);\n\n    used[0] = true;\n    point[0] = 2 * n + 2, point[2 * n + 1] = 2 * n + 1;\n    size[0] = 2 * n;\n\n    long long ans = catalan(n);\n\n    std::cout << ans << \" \";\n\n    for (int i = 0, l, r; i < n; ++i) {\n      std::cin >> l >> r;\n\n      point[l] = r + 1, point[r] = r;\n      used[l] = true;\n\n      int p = parent[parent_idx[l]];\n\n      int out_ptr = p + 1, ins_ptr = l + 1;\n      int out_size = 0, ins_size = 0;\n\n      while (point[out_ptr] != out_ptr && point[ins_ptr] != ins_ptr) {\n        out_size += !used[out_ptr];\n        ins_size += !used[ins_ptr];\n        out_ptr = point[out_ptr];\n        ins_ptr = point[ins_ptr];\n      }\n\n      ans = (ans * catalan_inv(size[p] / 2)) % MOD;\n\n      int upd_ptr;\n      if (point[out_ptr] == out_ptr) {\n        upd_ptr = p + 1;\n        parent.push_back(p);\n        parent[parent_idx[l]] = l;\n\n        ins_size = size[p] - 2 - out_size;\n        size[p] = out_size, size[l] = ins_size;\n      } else {\n        upd_ptr = l + 1;\n        parent.push_back(l);\n\n        out_size = size[p] - 2 - ins_size;\n        size[p] = out_size, size[l] = ins_size;\n      }\n\n      ans = (ans * catalan(size[p] / 2)) % MOD * catalan(size[l] / 2) % MOD;\n\n      while (point[upd_ptr] != upd_ptr) {\n        parent_idx[upd_ptr] = parent.size() - 1;\n        upd_ptr = point[upd_ptr];\n      }\n\n      std::cout << ans << \" \";\n    }\n\n    std::cout << '\\n';\n  }\n}",
    "tags": [
      "combinatorics",
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2064",
    "index": "A",
    "title": "Brogramming Contest",
    "statement": "One day after waking up, your friend challenged you to a brogramming contest. In a brogramming contest, you are given a binary string$^{\\text{∗}}$ $s$ of length $n$ and an initially empty binary string $t$. During a brogramming contest, you can make either of the following moves any number of times:\n\n- remove some suffix$^{\\text{†}}$ from $s$ and place it at the end of $t$, or\n- remove some suffix from $t$ and place it at the end of $s$.\n\nTo win the brogramming contest, you must make the minimum number of moves required to make $s$ contain only the character $0$ and $t$ contain only the character $1$. Find the minimum number of moves required.\\begin{footnotesize}\n$^{\\text{∗}}$A binary string is a string consisting of characters $0$ and $1$.\n\n$^{\\text{†}}$A string $a$ is a suffix of a string $b$ if $a$ can be obtained from deletion of several (possibly, zero or all) elements from the beginning of $b$.\n\\end{footnotesize}",
    "tutorial": "Notice that if $s$ starts with a $1$ we must move the entire string $s$ to $t$ at some point. Also Notice that if we perform the operation, the total number of occurrences of $01$ and $10$ across both strings can only decrease by one. This gives us an upper bound on the answer being the number of occurrences of $01$ and $10$ in $s$ adding one to this if it starts with the character $1$. Now the following construction uses the same number of moves as the upper bound (thus showing it is the minimum number of moves): If $s$ begins with $1$ then select the entire string $s$ and move it to $t$. Then repeatedly find the first character in $s$ or $t$ which is not equal to the character before it (note under this construction such an index can only exist in one string at a time) and selected the suffix starting from this character and move it to the other string. During this construction some prefix of $s$ will contain $0$s and some prefix of $t$ will contain $1$s, so after each move the total number of $01$ and $10$ will decrease. So the answer to this problem will be the number of $01$ and $10$ in $s$ adding one to the answer if it starts with $1$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n\nvoid solve(){\n    int n;\n    cin >> n;\n    \n    string s;\n    cin >> s;\n    \n    int ans = 0;\n    for (int i = 0; i < n - 1; i++) {\n        if (s[i] != s[i + 1]) ans++;\n    }\n\n    if (s[0] == '1') ans++;\n    cout << ans << \"\\n\";\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2064",
    "index": "B",
    "title": "Variety is Discouraged",
    "statement": "Define the score of an arbitrary array $b$ to be the length of $b$ minus the number of distinct elements in $b$. For example:\n\n- The score of $[1, 2, 2, 4]$ is $1$, as it has length $4$ and only $3$ distinct elements ($1$, $2$, $4$).\n- The score of $[1, 1, 1]$ is $2$, as it has length $3$ and only $1$ distinct element ($1$).\n- The empty array has a score of $0$.\n\nYou have an array $a$. You need to remove some \\textbf{non-empty} contiguous subarray from $a$ \\textbf{at most} once.\n\nMore formally, you can do the following \\textbf{at most} once:\n\n- pick two integers $l$, $r$ where $1 \\le l \\le r \\le n$, and\n- delete the contiguous subarray $[a_l,\\ldots,a_r]$ from $a$ (that is, replace $a$ with $[a_1,\\ldots,a_{l - 1},a_{r + 1},\\ldots,a_n]$).\n\nOutput an operation such that the score of $a$ is \\textbf{maximum}; if there are multiple answers, output one that \\textbf{minimises} the final length of $a$ after the operation. If there are still multiple answers, you may output any of them.",
    "tutorial": "The first thing to notice is that if we remove an element from $a$ then our score will never increase. Because removing one element will cause $|a|$ to decrease by $1$ and $\\mathrm{distinct}(a)$ will decrease by at most $1$ and so the $|a|$ - $\\mathrm{distinct}(a)$ will never increase. This means that we should be trying to removing the longest subarray which does not decrease our score. We can see that removing any element which only occurs once in $a$ will never decrease our score, and that removing any element which occurs more than once will always decrease our score. Thus we should try to find the longest subarray of elements which only have $1$ occurrence in $a$ and this will be the answer. This can be calculated with a single loop in $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n\nvoid solve(){\n    int n;\n    cin >> n;\n\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n\n    vector<int> freq(n + 1);\n    for (int x : a) freq[x]++;\n\n    vector<int> len(n + 1);\n    len[0] = freq[a[0]] == 1;\n    for (int i = 1; i < n; i++)\n        if (freq[a[i]] == 1)\n            len[i] = len[i - 1] + 1;\n    \n    int mx = *max_element(len.begin(), len.end());\n    if (mx == 0){\n        cout << \"0\\n\";\n        return;\n    }\n\n    for (int i = 0; i < n; i++){\n        if (len[i] == mx){\n            cout << i - len[i] + 2 << \" \" << i + 1 << \"\\n\";\n            return;\n        }\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2064",
    "index": "C",
    "title": "Remove the Ends",
    "statement": "You have an array $a$ of length $n$ consisting of \\textbf{non-zero} integers. Initially, you have $0$ coins, and you will do the following until $a$ is empty:\n\n- Let $m$ be the current size of $a$. Select an integer $i$ where $1 \\le i \\le m$, gain $|a_i|$$^{\\text{∗}}$ coins, and then:\n\n- if $a_i < 0$, then replace $a$ with $[a_1,a_2,\\ldots,a_{i - 1}]$ (that is, delete the suffix beginning with $a_i$);\n- otherwise, replace $a$ with $[a_{i + 1},a_{i + 2},\\ldots,a_m]$ (that is, delete the prefix ending with $a_i$).\n\nFind the maximum number of coins you can have at the end of the process.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$Here $|a_i|$ represents the absolute value of $a_i$: it equals $a_i$ when $a_i > 0$ and $-a_i$ when $a_i < 0$.\n\\end{footnotesize}",
    "tutorial": "First see that at any point we should either remove the leftmost positive element or the rightmost negative element, as if we were to take a positive element that is not the leftmost one we could have just taken the leftmost one first and had a higher score, a similar argument can be made for taking the rightmost negative element. Now if you do either of these moves some number of times you will always take some prefix of positive numbers and then the remaining suffix of negative numbers, and so to calculate the answer we only need to check all $n + 1$ ways to split the array into a prefix and suffix and take the maximum across them all which is easy to do in $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n\nvoid solve(){\n    int n;\n    cin >> n;\n\n    vector<int> a(n);\n    for (int &x : a)\n        cin >> x;\n\n    vector<ll> pre(n), suf(n);\n    if (a[0] > 0)\n        pre[0] = a[0];\n\n    for (int i = 1; i < n; i++){\n        pre[i] = pre[i - 1];\n        if (a[i] > 0)\n            pre[i] += a[i];\n    }\n\n    if (a[n - 1] < 0)\n        suf[n - 1] = -a[n - 1];\n    \n    for (int i = n - 2; i >= 0; i--){\n        suf[i] = suf[i + 1];\n        if (a[i] < 0)\n            suf[i] -= a[i];\n    }\n\n    ll ans = 0;\n    for (int i = 0; i < n; i++)\n        ans = max(ans, pre[i] + suf[i]);\n    \n    cout << ans << \"\\n\";\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2064",
    "index": "D",
    "title": "Eating",
    "statement": "There are $n$ slimes on a line, the $i$-th of which has weight $w_i$. Slime $i$ is able to eat another slime $j$ if $w_i \\geq w_j$; afterwards, slime $j$ disappears and the weight of slime $i$ becomes $w_i \\oplus w_j$$^{\\text{∗}}$.\n\nThe King of Slimes wants to run an experiment with parameter $x$ as follows:\n\n- Add a new slime with weight $x$ to the right end of the line (after the $n$-th slime).\n- This new slime eats the slime to its left if it is able to, and then takes its place (moves one place to the left). It will continue to do this until there is either no slime to its left or the weight of the slime to its left is greater than its own weight. (No other slimes are eaten during this process.)\n- The score of this experiment is the total number of slimes eaten.\n\nThe King of Slimes is going to ask you $q$ queries. In each query, you will be given an integer $x$, and you need to determine the score of the experiment with parameter $x$.\n\nNote that the King does not want you to actually perform each experiment; his slimes would die, which is not ideal. He is only asking what the hypothetical score is; in other words, the queries are \\textbf{not} persistent.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$Here $\\oplus$ denotes the bitwise XOR operation.\n\\end{footnotesize}",
    "tutorial": "First notice that if we are unable to eat the next slime then this slime must have had a $\\mathrm{msb}$ (most significant bit) at least as large as the current value of $x$. Subsequently this means that if a slime has a $\\mathrm{msb}$ strictly less than $x$ we can always eat it. Now see that if we eat a slime with lower $\\mathrm{msb}$ than $x$ then the $\\mathrm{msb}$ of $x$ will never decrease and that if we eat a slime with equal $\\mathrm{msb}$ then $\\mathrm{msb}$ of $x$ will decrease, this inspires us to do the following: at any point we should eat as many slimes as we can to the left that have smaller $\\mathrm{msb}$ (to calculate the new value of $x$ after doing this we can just do any range xor query such as prefix sums), after this the next slime will always have $\\mathrm{msb}$ greater than or equal to $x$ and so we will either not be able to eat it or we will eat it $\\mathrm{msb}$ of $x$ will decrease. Because the $\\mathrm{msb}$ will always decrease after every operation we will only need to do this operation at most $log(x)$ times! And so we should try find some way to calculate fast the first slime to our left with $\\mathrm{msb}$ greater than or equal to the current $\\mathrm{msb}$ of $x$. There are many ways to do this but I would say the cleanest way is to use prefix sums, store for each $i, j$ where $1 \\le i \\le n, 1 \\le j \\le log(W)$ (where $W$ is the max value of $w_i$ and $x$), the greatest index before it which has $\\mathrm{msb}$ greater than or equal to $j$ call this $\\mathrm{pre}_{i, j}$ Now we can update it as follows: if $\\mathrm{msb}(w_i) < j$ then $\\mathrm{pre}_{i, j} = \\mathrm{pre}_{i - 1, j}$ if $\\mathrm{msb}(w_i) < j$ then $\\mathrm{pre}_{i, j} = \\mathrm{pre}_{i - 1, j}$ else $\\mathrm{pre}_{i, j} = i$ else $\\mathrm{pre}_{i, j} = i$ And so the final complexity is $O((n + q)log(W))$",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n\nconst int W = 30;\n\nvoid solve(){\n    int n, q;\n    cin >> n >> q;\n\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n    \n    vector<int> pre(n + 1);\n    pre[0] = a[0];\n    for (int i = 1; i < n; i++){\n        pre[i] = pre[i - 1] ^a[i];\n    }\n\n    vector<array<int, W>> last(n);\n    for (int i = 0; i < n; i++){\n            fill(last[i].begin(), last[i].end(), 0);\n        if (i > 0) last[i] = last[i - 1];\n        last[i][__lg(a[i])] = i;\n\n        for (int j = W - 2; j >= 0; j--){\n            last[i][j] = max(last[i][j], last[i][j + 1]);\n        }\n    }\n\n    while (q--) {\n        int x;\n        cin >> x;\n\n        int idx = n - 1;\n        while (idx >= 0 && x > 0){\n            int msb = __lg(x);\n\n            int nxt = last[idx][msb];\n            x ^= pre[idx] ^ pre[nxt];\n            idx = nxt;\n            if (nxt == -1 || a[nxt] > x) break;\n\n            x ^= a[nxt];\n            idx--;\n        }\n\n        cout << n - idx - 1 << \"\\n\";\n    }\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "trees",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2064",
    "index": "E",
    "title": "Mycraft Sand Sort",
    "statement": "Steve has a permutation$^{\\text{∗}}$ $p$ and an array $c$, both of length $n$. Steve wishes to sort the permutation $p$.\n\nSteve has an infinite supply of coloured sand blocks, and using them he discovered a physics-based way to sort an array of numbers called gravity sort. Namely, to perform gravity sort on $p$, Steve will do the following:\n\n- For all $i$ such that $1 \\le i \\le n$, place a sand block of color $c_i$ in position $(i, j)$ for all $j$ where $1 \\le j \\le p_i$. Here, position $(x, y)$ denotes a cell in the $x$-th row from the top and $y$-th column from the left.\n- Apply downwards gravity to the array, so that all sand blocks fall as long as they can fall.\n\n\\begin{center}\n{\\small An example of gravity sort for the third testcase. $p = [4, 2, 3, 1, 5]$, $c = [2, 1, 4, 1, 5]$}\n\\end{center}\n\nAlex looks at Steve's sand blocks after performing gravity sort and wonders how many pairs of arrays $(p',c')$ where $p'$ is a permutation would have resulted in the same layout of sand. Note that the original pair of arrays $(p, c)$ will always be counted.\n\nPlease calculate this for Alex. As this number could be large, output it modulo $998\\,244\\,353$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is a $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "The first thing to notice is that the first column of sand will be identical to $c$ after sorting. This means that it must be true that $c' = c$. Now that we know $c' = c$ we need to find how many ways we can re-arrange $p$ such that the sand layout is the same. Something we can notice is that $p'$ must be able to obtainable from $p$ by only swapping values of the same colour. This is true because if we remove all sand blocks that are not of any specific colour (i.e. keeping only one colour), then by examining the new sand layout we can find what the values of the colour we didn't remove are. Now lets isolate a single colour and try to find the number of ways we can arrange it. One thing we can notice is that we can swap an arbitrary $p_i$ and $p_j$ without changing the final sand layout if and only if every number of different colour between $i$ and $j$ is strictly less than both $p_i$ and $p_j$. After staring at this operation enough you will see that each number in $p_i$ has a certain range of positions it can take. I think the easiest way to calculate this range is to use DSU, iterate in order of $p_i$ and merge with everything it can reach in one move, storing leftmost and rightmost element currently in the component to be fast enough. It is important to note that these ranges we are calculating have some form of tree structure, because of how we calculated them every pair of ranges will either not intersect or one will contain the other. This means that if we iterate in order of size and \"fix\" a position in each range we will calculate the answer. There is actually no need to build the tree, and instead we can multiply by the size of each DSU component as we are merging, after each merge decreasing the size of the component by $1$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n\nconst int MOD = 998244353;\n\ntemplate<ll mod> // template was not stolen from https://codeforces.com/profile/SharpEdged\nstruct modnum {\n    static constexpr bool is_big_mod = mod > numeric_limits<int>::max();\n\n    using S = conditional_t<is_big_mod, ll, int>;\n    using L = conditional_t<is_big_mod, __int128, ll>;\n\n    S x;\n\n    modnum() : x(0) {}\n    modnum(ll _x) {\n        _x %= static_cast<ll>(mod);\n        if (_x < 0) { _x += mod; }\n        x = _x;\n    }\n\n    modnum pow(ll n) const {\n        modnum res = 1;\n        modnum cur = *this;\n        while (n > 0) {\n            if (n & 1) res *= cur;\n            cur *= cur;\n            n /= 2;\n        }\n        return res;\n    }\n    modnum inv() const { return (*this).pow(mod-2); }\n    \n    modnum& operator+=(const modnum& a){\n        x += a.x;\n        if (x >= mod) x -= mod;\n        return *this;\n    }\n    modnum& operator-=(const modnum& a){\n        if (x < a.x) x += mod;\n        x -= a.x;\n        return *this;\n    }\n    modnum& operator*=(const modnum& a){\n        x = static_cast<L>(x) * a.x % mod;\n        return *this;\n    }\n    modnum& operator/=(const modnum& a){ return *this *= a.inv(); }\n    \n    friend modnum operator+(const modnum& a, const modnum& b){ return modnum(a) += b; }\n    friend modnum operator-(const modnum& a, const modnum& b){ return modnum(a) -= b; }\n    friend modnum operator*(const modnum& a, const modnum& b){ return modnum(a) *= b; }\n    friend modnum operator/(const modnum& a, const modnum& b){ return modnum(a) /= b; }\n    \n    friend bool operator==(const modnum& a, const modnum& b){ return a.x == b.x; }\n    friend bool operator!=(const modnum& a, const modnum& b){ return a.x != b.x; }\n    friend bool operator<(const modnum& a, const modnum& b){ return a.x < b.x; }\n\n    friend ostream& operator<<(ostream& os, const modnum& a){ os << a.x; return os; }\n    friend istream& operator>>(istream& is, modnum& a) { ll x; is >> x; a = modnum(x); return is; }\n};\n\nusing mint = modnum<MOD>;\n\ntemplate <class T> struct SegTree{\n    vector<T> seg;\n    int n;\n    const T ID = 0;\n    \n    T cmb(T a, T b){\n        return max(a, b);\n    }\n    \n    SegTree(int _n){\n        n = 1;\n        while (n < _n) n *= 2;\n        seg.assign(2 * n + 1, ID);\n    }\n    \n    void set(int pos, T val){\n        seg[pos + n] = val;\n    }\n    \n    void build(){\n        for (int i = n - 1; i >= 1; i--) seg[i] = cmb(seg[2 * i], seg[2 * i + 1]);\n    }\n    \n    void upd(int v, int tl, int tr, int pos, T val){\n        if (tl == tr){\n            seg[v] = val;\n        } else {\n            int tm = (tl + tr) / 2;\n            if (pos <= tm) upd(2 * v, tl, tm, pos, val);\n            else upd(2 * v + 1, tm + 1, tr, pos, val);\n            seg[v] = cmb(seg[2 * v], seg[2 * v + 1]);\n        }\n    }\n    \n    void upd(int pos, T val){\n        upd(1, 0, n - 1, pos, val);\n    }\n    \n    T query(int v, int tl, int tr, int l, int r){\n        if (l > r) return ID;\n        if (l == tl && r == tr) return seg[v];\n        int tm = (tl + tr) / 2;\n        T res = query(2 * v, tl, tm, l, min(tm, r));\n        res = cmb(res, query(2 * v + 1, tm + 1, tr, max(l, tm + 1), r));\n        return res;\n    }\n    \n    T query(int l, int r){\n        return query(1, 0, n - 1, l, r);\n    }\n};\n\nstruct DSU{\n    vector<int> p, sz, used, mn, mx;\n    \n    DSU(int n){\n        p.assign(n, 0);\n        sz.assign(n, 1);\n        used.assign(n, 0);\n        mx.assign(n, 0);\n        mn.assign(n, 0);\n\n        for (int i = 0; i < n; i++) p[i] = i;\n    }\n    \n    int find(int u){\n        if (p[u] == u) return u;\n        p[u] = find(p[u]);\n        return p[u];\n    }\n    \n    void unite(int u, int v){\n        u = find(u);\n        v = find(v);\n        if (u == v) return;\n        \n        if (sz[u] < sz[v]) swap(u, v);\n        p[v] = u;\n        sz[u] += sz[v];\n        used[u] += used[v];\n        mn[u] = min(mn[u], mn[v]);\n        mx[u] = max(mx[u], mx[v]);\n    }\n    \n    bool same(int u, int v){\n        return find(u) == find(v);\n    }\n    \n    int size(int u){\n        u = find(u);\n        return sz[u];\n    }\n};\n\nvoid solve(){\n    int n;\n    cin >> n;\n\n    vector<int> a(n), b(n);\n    for (int &x : a) cin >> x;\n    for (int &x : b) cin >> x;\n\n    vector<vector<int>> col(n + 1);\n    for (int i = 0; i < n; i++){\n        col[b[i]].push_back(i);\n    }\n\n    vector<vector<int>> ord(n + 1);\n\n    for (int i = 0; i <= n; i++){\n        ord[i] = col[i];\n        sort(ord[i].begin(), ord[i].end(), [&](int x, int y) -> bool{\n            return a[x] < a[y];\n        });\n    }\n\n    SegTree<int> seg(n);\n    for (int i = 0; i < n; i++){\n        seg.set(i, a[i]);\n    } seg.build();\n\n    mint ans = 1;\n    DSU dsu(n);\n    for (int i = 0; i <= n; i++){\n        for (int j = 0; j < col[i].size(); j++){\n            dsu.mn[col[i][j]] = j;\n            dsu.mx[col[i][j]] = j;\n        }\n    }\n\n    for (int i = 0; i <= n; i++){\n        for (int x : ord[i]) seg.upd(x, 0);\n\n        for (int x : ord[i]){\n            int idx = lower_bound(col[i].begin(), col[i].end(), x) - col[i].begin();\n            for (int j = idx + 1; j < col[i].size(); j++){\n                if (seg.query(x, col[i][j]) >= a[x]) break;\n\n                dsu.unite(x, col[i][j]);\n                j = dsu.mx[dsu.find(x)];\n            }\n\n            for (int j = idx - 1; j >= 0; j--){\n                if (seg.query(col[i][j], x) >= a[x]) break;\n\n                dsu.unite(x, col[i][j]);\n                j = dsu.mn[dsu.find(x)];\n            }\n\n            int u = dsu.find(x);\n            ans *= dsu.size(u) - dsu.used[u];\n            dsu.used[u]++;\n        }\n\n        for (int x : ord[i]) seg.upd(x, a[x]);\n    }\n\n    cout << ans << \"\\n\";\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}\n",
    "tags": [
      "combinatorics",
      "data structures",
      "dsu",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2064",
    "index": "F",
    "title": "We Be Summing",
    "statement": "You are given an array $a$ of length $n$ and an integer $k$.\n\nCall a non-empty array $b$ of length $m$ epic if there exists an integer $i$ where $1 \\le i < m$ and $\\min(b_1,\\ldots,b_i) + \\max(b_{i + 1},\\ldots,b_m) = k$.\n\nCount the number of epic subarrays$^{\\text{∗}}$ of $a$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "For an arbitrary array $b$ first notice that $\\min(b_1,\\ldots,b_i)$ and $\\max(b_{i + 1},\\ldots,n)$ is both non-increasing as we increase $i$. This means that if an array $b$ is epic then there exists a unique pair of integers $x, y$ such that $x + y = k$ and there exists $i, (1 \\le i < |b|)$ such that $\\min(b_1,\\ldots,b_i) = x$ and $\\max(b_{i + 1},\\ldots,n) = y$. Lets call an array $b$ $x$-epic if it is epic due to the pair $x, k - x$. Because the pair $x, y$ is unique, the answer will be equivalent to the sum of all $x$-epic subarrays of $a$. So lets try to find this sum. Lets say we are trying to find the sum of all $x$ epic subarrays for a given $x$ and let $y = k - x$. Firstly the subarray must obviously contain both $x$ and $y$, so lets try to find for each $i$ the number of subarrays that are epic where $a_i$ is the first instance of $x$ in the subarray. Notice that it must be true that the first element smaller than $x$ must come after the last element bigger than $y$. Notice also that there cannot be an element bigger than $y$ after the last instance of $y$. So we should store for each index $j$ such that $p_j = y$ the length of the longest consecutive sequence of elements strictly less than $y$, which contains $j$ as its leftmost element. Then for each $i$ where $p_i = x$ we should binary search for the last time where first element smaller than $x$ after the last element bigger than $y$. Once we can use prefix sums to find the number of possible right positions of the subarray. To find the number of possible left positions of the subarray it is just the length of the longest consecutive interval which only contains element strictly larger than $x$ and contain $i$ as its right most element. Now we know the number of possible left endpoints of the subarray and right endpoints, so we can just add their product to the answer. After doing this across all $i$ we will have the answer.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n\ntemplate <class T> struct SegTree{\n    vector<T> seg;\n    int n;\n    const T ID = {INT_MAX, -INT_MAX};\n    \n    T cmb(T a, T b){\n        array<int, 2> res;\n        res[0] = min(a[0], b[0]);\n        res[1] = max(a[1], b[1]);\n        return res;\n    }\n    \n    SegTree(int _n){\n        n = 1;\n        while (n < _n) n *= 2;\n        seg.assign(2 * n + 1, ID);\n    }\n    \n    void set(int pos, T val){\n        seg[pos + n] = val;\n    }\n    \n    void build(){\n        for (int i = n - 1; i >= 1; i--) seg[i] = cmb(seg[2 * i], seg[2 * i + 1]);\n    }\n    \n    void upd(int v, int tl, int tr, int pos, T val){\n        if (tl == tr){\n            seg[v] = val;\n        } else {\n            int tm = (tl + tr) / 2;\n            if (pos <= tm) upd(2 * v, tl, tm, pos, val);\n            else upd(2 * v + 1, tm + 1, tr, pos, val);\n            seg[v] = cmb(seg[2 * v], seg[2 * v + 1]);\n        }\n    }\n    \n    void upd(int pos, T val){\n        upd(1, 0, n - 1, pos, val);\n    }\n    \n    T query(int v, int tl, int tr, int l, int r){\n        if (l > r) return ID;\n        if (l == tl && r == tr) return seg[v];\n        int tm = (tl + tr) / 2;\n        T res = query(2 * v, tl, tm, l, min(tm, r));\n        res = cmb(res, query(2 * v + 1, tm + 1, tr, max(l, tm + 1), r));\n        return res;\n    }\n    \n    T query(int l, int r){\n        return query(1, 0, n - 1, l, r);\n    }\n};\n\nvoid solve(){\n    int n, k;\n    cin >> n >> k;\n\n    vector<int> a(n);\n    for (int &x : a) cin >> x;\n\n    vector<vector<int>> p(n + 1);\n    for (int i = 0; i < n; i++)\n        p[a[i]].push_back(i);\n    \n    vector<array<int, 2>> stk;\n    vector<int> small_l(n, -1), small_r(n, n), big_l(n, -1), big_r(n, n);\n\n    for (int i = 0; i < n; i++){\n        while (stk.size() && a[i] <= stk.back()[0])\n            stk.pop_back();\n\n        if (stk.size())\n            small_l[i] = stk.back()[1];\n        stk.push_back({a[i], i});\n    }\n\n    stk.clear();\n    for (int i = n - 1; i >= 0; i--){\n        while (stk.size() && a[i] >= stk.back()[0])\n            stk.pop_back();\n\n        if (stk.size())\n            big_r[i] = stk.back()[1];\n        stk.push_back({a[i], i});\n    }\n\n    ll ans = 0;\n    SegTree<array<int, 2>> seg_small(n), seg_big(n);\n\n    for (int x = 1; x <= n; x++){\n        int y = k - x;\n        if (y > n){\n            for (int pos : p[x])\n                seg_small.upd(pos, {pos, pos});\n            continue;\n        }\n\n        vector<int> pre(p[y].size());\n        for (int i = 0; i < p[y].size(); i++){\n            if (i > 0)\n                pre[i] += pre[i - 1];\n\n            int r = big_r[p[y][i]] - 1;\n            if (i < p[y].size() - 1)\n                r = min(r, p[y][i + 1] - 1);\n            pre[i] += r - p[y][i] + 1;\n        }\n\n        vector<int> first(p[x].size()), last(p[y].size());\n        for (int i = 0; i < p[x].size(); i++)\n            first[i] = seg_small.query(p[x][i], n - 1)[0];\n\n        for (int i = 0; i < p[y].size(); i++)\n            last[i] = seg_big.query(0, p[y][i])[1];\n\n        int prev = -1;\n        for (int i = 0; i < p[x].size(); i++){\n            int l = p[x][i];\n            int l_min = small_l[l] + 1;\n            l_min = max(l_min, prev + 1);\n            prev = l;\n\n            int nxt = upper_bound(p[y].begin(), p[y].end(), l) - p[y].begin();\n            if (nxt == p[y].size())\n                continue;\n       \n            int lo = nxt, hi = p[y].size();\n            while (lo < hi){\n                int mid = (lo + hi) / 2;\n\n                int pos = p[y][mid];\n                if (first[i] <= last[mid])\n                    hi = mid;\n                else\n                    lo = mid + 1;\n            }\n\n            lo--;\n            if (lo < nxt)\n                continue;\n\n            int res = pre[lo];\n            if (nxt > 0)\n                res -= pre[nxt - 1];\n\n            ans += 1LL * (l - l_min + 1) * res;\n        }\n\n        for (int pos : p[x])\n            seg_small.upd(pos, {pos, pos});\n        for (int pos : p[y])\n            seg_big.upd(pos, {pos, pos});\n    }\n\n    cout << ans << \"\\n\";\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2065",
    "index": "A",
    "title": "Skibidus and Amog'u",
    "statement": "Skibidus lands on a foreign planet, where the local Amog tribe speaks the Amog'u language. In Amog'u, there are two forms of nouns, which are singular and plural.\n\nGiven that the root of the noun is transcribed as $S$, the two forms are transcribed as:\n\n- Singular: $S$ $+$ \"us\"\n- Plural: $S$ $+$ \"i\"\n\nHere, $+$ denotes string concatenation. For example, abc $+$ def $=$ abcdef.\n\nFor example, when $S$ is transcribed as \"amog\", then the singular form is transcribed as \"amogus\", and the plural form is transcribed as \"amogi\". Do note that Amog'u nouns can have an \\textbf{empty} root — in specific, \"us\" is the singular form of \"i\" (which, on an unrelated note, means \"imposter\" and \"imposters\" respectively).\n\nGiven a transcribed Amog'u noun in singular form, please convert it to the transcription of the corresponding plural noun.",
    "tutorial": "Let $n$ be the length of the string. Output the first $n-2$ characters of the string (to remove the suffix \"us\"), then the lowercase letter \"i\".",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n \nvoid tc () {\n    string str;\n    cin >> str;\n    str.pop_back();\n    str.pop_back();\n    cout << str + \"i\" << '\\n';\n}\n \nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2065",
    "index": "B",
    "title": "Skibidus and Ohio",
    "statement": "Skibidus is given a string $s$ that consists of lowercase Latin letters. If $s$ contains more than $1$ letter, he can:\n\n- Choose an index $i$ ($1 \\leq i \\leq |s| - 1$, $|s|$ denotes the current length of $s$) such that $s_i = s_{i+1}$. Replace $s_i$ with any lowercase Latin letter of his choice. Remove $s_{i+1}$ from the string.\n\nSkibidus must determine the minimum possible length he can achieve through any number of operations.",
    "tutorial": "Note that if you can ever do an operation, the answer is $1$. This is because once you've done an operation on a string of length $k$, you are free to choose any character to replace $s_i$ with. Therefore, if you replace $s_i$ either with the character directly before it, or the character directly after it, you will end up with a string with length $k-1$ upon which you can do an operation again. Therefore, by induction, it's clear that you can keep operating on the string until only one character remains. However, if you cannot perform any operations, the answer is $|s|$, because you have not modified the original string. Therefore, the answer is $1$ if $s_i = s_{i+1}$ for some $i$, or $n$ otherwise.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n\nvoid tc () {\n    string str;\n    cin >> str;\n    for (ll i = 1; i < str.size(); i++) {\n        if (str[i-1] == str[i]) {\n            cout << \"1\\n\";\n            return;\n        }\n    }\n    cout << str.size() << '\\n';\n}\n\nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2065",
    "index": "C2",
    "title": "Skibidus and Fanum Tax (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, $m \\leq 2\\cdot 10^5$.}\n\nSkibidus has obtained two arrays $a$ and $b$, containing $n$ and $m$ elements respectively. For \\textbf{each} integer $i$ from $1$ to $n$, he is allowed to perform the operation \\textbf{at most once}:\n\n- Choose an integer $j$ such that $1 \\leq j \\leq m$. Set $a_i := b_j - a_i$. Note that $a_i$ may become non-positive as a result of this operation.\n\nSkibidus needs your help determining whether he can sort $a$ in non-decreasing order$^{\\text{∗}}$ by performing the above operation some number of times.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$a$ is sorted in non-decreasing order if $a_1 \\leq a_2 \\leq \\ldots \\leq a_n$.\n\\end{footnotesize}",
    "tutorial": "The overall idea for both subtasks is that you need to iterate from left to right, and upon each element, pick the operation such that you obtain the smallest value of $a_i$ that is greater than $a_{i-1}$. For C1, you only have two values to consider for each index - $b_1-a_i$ and $a_i$. First, set $a_1 = min(a_1, b_1-a_1)$, then for each subsequent element $i$, consider the two values $b_1-a_i$ and $a_i$. If the smaller of these values is greater than or equal to $a_{i-1}$, then set $a_i$ to this value. Otherwise, check the larger value. If this value is less than $a_{i-1}$, you can straight away output $NO$ and move onto the next testcase. Otherwise, set $a_i$ as the larger of the two aforementioned values. Time complexity: $\\mathcal{O}(n)$ per testcase. For C2, you now have $m$ values in the array $b$. Clearly, we now need to consider $m+1$ different possible values per index of $a$. Solving this problem in $\\mathcal{O}(nm)$ is clearly too slow. Therefore, we need to employ a different technique. Note that instead of trying every value, you can sort all the values in $m$, and then binary search for the minimal value of $b_j$ such that $b_j-a_i >= a_{i-1}$. Then, you're left with the original problem, where you either leave $a_i$ untouched or you set it to $b_j - a_i$ for this optimal index $j$ that you found using binary search. Now, by proceeding as before, the problem is solved in $\\mathcal{O}(n \\log m)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n \nconst ll INF = ll(1E18)+16;\n \nvoid tc () {\n    ll n, m;\n    cin >> n >> m;\n    vll va(n), vb(m);\n    for (ll &i : va) cin >> i;\n    for (ll &i : vb) cin >> i;\n    sort(vb.begin(), vb.end());\n    va.insert(va.begin(), -INF);\n    n++;\n    for (ll i = 1; i < n; i++) {\n        auto it = lower_bound(vb.begin(), vb.end(), -15, [&](ll a, ll _) {\n            assert(_ == -15);\n            return a-va[i] < va[i-1];\n        });\n        if (it == vb.end()) continue;\n        ll j = *it;\n        if (va[i] < va[i-1] && j-va[i] < va[i-1]) continue; // OH MY GOD\n        va[i] = min((va[i] < va[i-1] ? INF : va[i]), (j-va[i] < va[i-1] ? INF : j-va[i]));\n    }\n    cout << (is_sorted(va.begin(), va.end()) ? \"YES\" : \"NO\") << '\\n';\n}\n \nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2065",
    "index": "D",
    "title": "Skibidus and Sigma",
    "statement": "Let's denote the score of an array $b$ with $k$ elements as $\\sum_{i=1}^{k}\\left(\\sum_{j=1}^ib_j\\right)$. In other words, let $S_i$ denote the sum of the first $i$ elements of $b$. Then, the score can be denoted as $S_1+S_2+\\ldots+S_k$.\n\nSkibidus is given $n$ arrays $a_1,a_2,\\ldots,a_n$, each of which contains $m$ elements. Being the sigma that he is, he would like to concatenate them in \\textbf{any order} to form a single array containing $n\\cdot m$ elements. Please find the maximum possible score Skibidus can achieve with his concatenated array!\n\nFormally, among all possible permutations$^{\\text{∗}}$ $p$ of length $n$, output the maximum score of $a_{p_1} + a_{p_2} + \\dots + a_{p_n}$, where $+$ represents concatenation$^{\\text{†}}$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ contains all integers from $1$ to $n$ exactly once.\n\n$^{\\text{†}}$The concatenation of two arrays $c$ and $d$ with lengths $e$ and $f$ respectively (i.e. $c + d$) is $c_1, c_2, \\ldots, c_e, d_1, d_2, \\ldots d_f$.\n\\end{footnotesize}",
    "tutorial": "It is clear that the score of an array $b$ of length $n$ can be expressed as $n * b_1 + (n-1) * b_2 + (n-2) * b_3 \\dots + 1 * b_n$. Let's solve this problem with $m=1$ for $n$ arrays with $1$ element in each. Due to the above fact, it's clear that the optimal way to arrange this array is to sort the elements from largest to smallest. Now, we come to the issue of combining arrays. Suppose you have two arrays $a$ and $b$, both of length m. Is there a nice way of expressing the score of $a+b$ and the score of $b+a$ (where $+$ represents concatenation) in terms of $score(a)$ and $score(b)$? Turns out there is. The score of $a+b$ is equal to $n * sum(a) + score(a) + score(b)$. This is because of the following: $score(a+b) = (2n * a_1) + ((2n-1) * a_2) \\dots + ((n+1) * a_n) + (n * b_1) \\dots + (1 * b_n)$ Now, we can clearly replace all the $b$ terms with $score(b)$ as follows: $score(a+b) = (2n * a_1) + ((2n-1) * a_2) \\dots + ((n+1) * a_n) + score(b)$ Now, we can take out a factor of $n$ as follows: $score(a+b) = ((n+n) * a_1) + ((n + (n-1)) * a_2) \\dots + ((n+1) * a_n) + score(b)$ $score(a+b) = (n * (a_1 + a_2 + a_3)) + (n * a_1) + ((n-1) * a_2) \\dots + (1 * a_n) + score(b)$ $score(a+b) = (n * sum(a)) + score(a) + score(b)$ Therefore, whichever of $a$ and $b$ has the larger sum should go first, because then you get a larger overall score. This argument also extends beyond two arrays, so the solution is as follows: Sort the arrays themselves in terms of their sum, from largest sum to smallest Put together the final array Take the score This score is guaranteed to be maximal.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n \nvoid tc () {\n    ll n, m;\n    cin >> n >> m;\n    vector <vll> ve(n, vll(m));\n    for (vll &ve2 : ve) {\n        for (ll &i : ve2) cin >> i;\n    }\n    vll vsum(n, 0);\n    for (ll i = 0; i < n; i++) {\n        for (ll j : ve[i]) vsum[i] += j;\n    }\n    vll th(n);\n    iota(th.begin(), th.end(), 0);\n    sort(th.begin(), th.end(), [&](ll a, ll b) {\n        return vsum[a] > vsum[b];\n    });\n    ll ans = 0;\n    for (ll i = 0; i < n; i++) {\n        ans += vsum[th[i]]*(n-1-i)*m;\n    }\n    for (vll ve2 : ve) {\n        for (ll i = 0; i < m; i++) {\n            ans += ve2[i]*(m-i);\n        }\n    }\n    cout << ans << '\\n';\n}\n \nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}",
    "tags": [
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2065",
    "index": "E",
    "title": "Skibidus and Rizz",
    "statement": "With the approach of Valentine's Day, Skibidus desperately needs a way to rizz up his crush! Fortunately, he knows of just the way: creating the perfect Binary String!\n\nGiven a binary string$^{\\text{∗}}$ $t$, let $x$ represent the number of $0$ in $t$ and $y$ represent the number of $1$ in $t$. Its \\textbf{balance-value} is defined as the value of $\\max(x-y, y-x)$.\n\nSkibidus gives you three integers $n$, $m$, and $k$. He asks for your help to construct a binary string $s$ of length $n+m$ with exactly $n$ $0$'s and $m$ $1$'s such that the maximum \\textbf{balance-value} among all of its substrings$^{\\text{†}}$ is \\textbf{exactly} $k$. If it is not possible, output -1.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string only consists of characters $0$ and $1$.\n\n$^{\\text{†}}$A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\\end{footnotesize}",
    "tutorial": "Claim 1: It is impossible when $k < |n-m|$ Proof 1: The entire string will have a balance value greater than $k$. Claim 2: It is impossible when $k > max(n, m)$ Proof 2: The maximal possible balance value of any string with $n$ ones and $m$ zeroes is $max(m, n)$, as it is impossible due to the balance value definition. To complete the construction, WLOG $n \\ge m$ (because you can invert the string to get the solution for $n \\lt m$. Output $k$ zeroes, then output alternating ones and zeroes, then output the remaining ones at the end. Note that with this construction, a substring with balance value $k$ exists (as you can take the first $k$ numbers), but a substring with balance value $>k$ does not exist (as taking more of the string cannot increase the balance value).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tint n, m, k; cin >> n >> m >> k;\n\t\tif(max(n, m) - min(n, m) > k || k > max(n, m)){\n\t\t\tcout << \"-1\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\telse{\n\t\t\tpair<int, int> use1 = {n, 0}, use2 = {m, 1};\n\t\t\tif(m > n) swap(use1, use2);\n\t\t\tfor(int i = 0; i < k; i++){\n\t\t\t\tcout << use1.second;\n\t\t\t\tuse1.first--;\n\t\t\t}\n\t\t\twhile(use2.first > 0){\n\t\t\t\tcout << use2.second;\n\t\t\t\tuse2.first--;\n\t\t\t\tswap(use1, use2);\n\t\t\t}\n\t\t\twhile(use1.first > 0){\n\t\t\t\tcout << use1.second;\n\t\t\t\tuse1.first--;\n\t\t\t}\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2065",
    "index": "F",
    "title": "Skibidus and Slay",
    "statement": "Let's define the majority of a sequence of $k$ elements as the unique value that appears strictly more than $\\left \\lfloor {\\frac{k}{2}} \\right \\rfloor$ times. If such a value does not exist, then the sequence does \\textbf{not} have a majority. For example, the sequence $[1,3,2,3,3]$ has a majority $3$ because it appears $3 > \\left \\lfloor {\\frac{5}{2}} \\right \\rfloor = 2$ times, but $[1,2,3,4,5]$ and $[1,3,2,3,4]$ do not have a majority.\n\nSkibidus found a tree$^{\\text{∗}}$ of $n$ vertices and an array $a$ of length $n$. Vertex $i$ has the value $a_i$ written on it, where $a_i$ is an integer in the range $[1, n]$.\n\nFor each $i$ from $1$ to $n$, please determine if there exists a non-trivial simple path$^{\\text{†}}$ such that $i$ is the majority of the \\textbf{sequence of integers written on the vertices} that form the path.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\n$^{\\text{†}}$A sequence of vertices $v_1, v_2, ..., v_m$ ($m \\geq 2$) forms a non-trivial simple path if $v_i$ and $v_{i+1}$ are connected by an edge for all $1 \\leq i \\leq m - 1$ and all $v_i$ are pairwise distinct. \\textbf{Note that the path must consist of at least $2$ vertices.}\n\\end{footnotesize}",
    "tutorial": "Assume that a sequence a of length $n$ contains two types of elements, $1$ denoting majority and $0$ denoting \"not majority\". Then, if a contains a majority and $n \\ge 2$, the following condition holds. a must contain either $[1,1]$ or $[1,0,1]$. This can be shown by contradiction. It is given that there are $k$ instances of $1$ and $n-k$ instances of $0$. Then it is known that $k>n-k$, so $2k>n$. If a does not contain $[1,1]$, then it needs a $0$ between every $1$. The only way this can happen is when $n-k \\ge k-1$. This means $n+1 \\ge 2k$, but because $n<2k \\le n+1$ the only value $k$ can take is $\\frac{n+1}{2}$. When this happens, the only valid orientation of $a$ is $[1,0,1,0,\\ldots,0,1,0,1]$, but still this contains $[1,0,1]$. Therefore, it definitely contains either $[1,1]$ or $[1,0,1]$. But we can notice, the subarrays $[1,1]$ and $[1,0,1]$ already contain the majority $1$. So due to this, we conclude that the tree containing the pattern $[k,k]$ or $[k,x,k]$ for some value $k$, is an equivalent condition to the tree containing a non-trivial path with majority $k$. Checking the existence of $[k,k]$ and $[k,x,k]$ in the tree for all k can be done in $\\mathcal{O}(n)$ time, due to $\\sum{\\text{deg}} = 2m = 2(n-1)$. The problem has been solved in $\\mathcal{O}(n)$ time. You can solve this problem using the Auxiliary Tree technique. Formally, the auxiliary tree of $k$ specified vertices is the tree consisting of the specified vertices and their pairwise lowest common ancestors. It can be shown that such a tree will always have $\\mathcal{O}(k)$ vertices and can be found in $\\mathcal{O}(k \\log n)$ time using widely known algorithms. Observe the fact that, when you transform the value $x$ into $1$ and all other values into $-1$, $x$ is the majority of the sequence if and only if the transformed sequence has a positive sum. This hints us towards finding the maximum sum of any non-trivial path under the transformed tree. If the maximum sum is found to be positive, then we can determine that there exists a path with $x$ as its majority. This subproblem can be solved by running a modified version of Kadane's algorithm, adapted for use on a tree. This adaptation is widely known for the case when the given tree is a binary tree, and it is trivial to modify it for use on any tree while keeping the time complexity to be $\\mathcal{O}(n)$. The only problem is that solving this for all values is $\\mathcal{O}(n^2)$, so we compress the tree for each value using the Auxiliary Tree technique. By getting the auxiliary tree for the specified vertices, you get the specified vertices and their LCAs. If some vertex is specified, the value on it is transformed into $1$. Otherwise, the value on it is transformed into $-1$. Meanwhile, now there are lengths on edges, and an edge with length greater than $1$ means that there are unspecified vertices compressed in the edge. Therefore, if an edge has length $l$ which is greater than $1$, make sure to make a new vertex with value $-l+1$ in the middle of the edge as it means that $l-1$ vertices are compressed into the edge. As there are $n$ specified vertices in total, finding each auxiliary tree takes $\\mathcal{O}(n \\log n)$ time. Solving the rest of the problem for each $i$ only takes $\\mathcal{O}(n)$ time trivially. Thus, the problem has been solved in $\\mathcal{O}(n \\log n)$ time.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define f first\n#define s second\n#define ll long long\n#define pii pair<int,int>\n#define amin(a,b) a = min(a,b)\n#define amax(a,b) a = max(a,b)\n\nvector<int> adj[500005];\nint a[500005];\nint s[500005];\nint d[500005];\nint t[1000005];\nvector<int> v[500005];\n\nint timer = 0;\nvoid dfs(int node, int pa) {\n    d[node] = d[pa]+1;\n    s[node] = ++timer;\n    t[timer] = node;\n    v[a[node]].push_back(node);\n    for (auto it : adj[node]) {\n        if (it == pa)continue;\n        dfs(it,node);\n        t[++timer] = node;\n    }\n}\n\n// sparse table\npii spt[1000005][20];\n\nvoid buildspt(int n) {\n    for (int i = 1; i <= 2*n-1; ++i) {\n        spt[i][0] = {d[t[i]],i};\n    }\n    for (int j = 1; (1<<j) <= 2*n-1; ++j) {\n        for (int i = 1; i+(1<<j)-1 <= 2*n-1; ++i) {\n            spt[i][j] = min(spt[i][j-1],spt[i+(1<<(j-1))][j-1]);\n        }\n    }\n    return;\n}\n\npii qry(int l, int r) {\n    int dd = __lg(r-l+1);\n    return min(spt[l][dd],spt[r-(1<<dd)+1][dd]);\n}\n\nint _lca(int l, int r) {\n    return t[qry(s[l],s[r]).s];\n}\n\nint dp[500005];\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    int tt;\n    cin >> tt;\n    while (tt--) {\n        int n;\n        cin >> n;\n        for (int i = 1; i <= n; ++i) {\n            cin >> a[i];\n        }\n        for (int i = 1; i <= n-1; ++i) {\n            int u, _v;\n            cin >> u >> _v;\n            adj[u].push_back(_v);\n            adj[_v].push_back(u);\n        }\n        timer = 0;\n        dfs(1,0);\n        buildspt(n);\n        for (int i = 1; i <= n; ++i) {\n            vector<int> v2;\n            int ans = -2e9;\n            for (auto it : v[i]) {\n                dp[it] = 1;\n                if (v2.size()) {\n                    int lca = _lca(v2.back(),it);\n                    while (v2.size() && d[lca] < d[v2.back()]) {\n                        int z = v2.back();\n                        v2.pop_back();\n                        if (v2.empty() || d[v2.back()] < d[lca]) {\n                            dp[lca] = (a[lca] == i ? 1 : -1);\n                            v2.push_back(lca);\n                        }\n                        amax(ans,dp[v2.back()]+dp[z]-(d[z]-d[v2.back()]-1));\n                        amax(dp[v2.back()],dp[z]+(a[v2.back()] == i ? 1 : -1)-(d[z]-d[v2.back()]-1));\n                    }\n                }\n                v2.push_back(it);\n            }\n            while ((int)v2.size() > 1) {\n                int z = v2.back();\n                v2.pop_back();\n                amax(ans,dp[v2.back()]+dp[z]-(d[z]-d[v2.back()]-1));\n                amax(dp[v2.back()],dp[z]+(a[v2.back()] == i ? 1 : -1)-(d[z]-d[v2.back()]-1));\n            }\n            cout << (ans > 0);\n        } cout << '\\n';\n        for (int i = 1; i <= n; ++i) {\n            adj[i].clear();\n            v[i].clear();\n        }\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "dfs and similar",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2065",
    "index": "G",
    "title": "Skibidus and Capping",
    "statement": "Skibidus was abducted by aliens of Amog! Skibidus tries to talk his way out, but the Amog aliens don't believe him. To prove that he is not totally capping, the Amog aliens asked him to solve this task:\n\nAn integer $x$ is considered a semi-prime if it can be written as $p \\cdot q$ where $p$ and $q$ are (not necessarily distinct) prime numbers. For example, $9$ is a semi-prime since it can be written as $3 \\cdot 3$, and $3$ is a prime number.\n\nSkibidus was given an array $a$ containing $n$ integers. He must report the number of pairs $(i, j)$ such that $i \\leq j$ and $\\operatorname{lcm}(a_i, a_j)$$^{\\text{∗}}$ is semi-prime.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$Given two integers $x$ and $y$, $\\operatorname{lcm}(x, y)$ denotes the least common multiple of $x$ and $y$.\n\\end{footnotesize}",
    "tutorial": "Let $a_i=x$ and $a_j=y$ for any pair $(i,j)$ that we count. First, let's note that since $x|lcm(x,y)$, we don't need to consider any cases where $x$ or $y$ has more than two prime factors. There are three cases we must consider: $x$ and $y$ are primes, and $x\\neq y$. Then, $lcm(x,y)=x\\cdot y$ and has two prime factors. $x$ and $y$ are primes, and $x\\neq y$. Then, $lcm(x,y)=x\\cdot y$ and has two prime factors. $x$ is a semiprime, and $y$ is a prime factor of $x$. Then, $lcm(x,y)=x$. $x$ is a semiprime, and $y$ is a prime factor of $x$. Then, $lcm(x,y)=x$. $y$ is a semiprime, and $y=x$. $y$ is a semiprime, and $y=x$. To count this, let's first factorize each number in the array (either by trial division in $O(n\\sqrt{a_i})$ or $O(n\\log(n))$ sieve precomputation). Let's maintain two maps, one mapping each semiprime present in the array to its number of occurrences, and one mapping each prime present in the array to its number of occurrences. Let $cnt[x]$ be the number of occurrences of $x$. Then, we can count each case as follows: Let the total number of primes be $P$. For each prime $p$, its contribution will be $cnt[p]\\cdot(P-cnt[p])$. Note that we must divide our result by $2$ as we would have counted each pair twice. Let the total number of primes be $P$. For each prime $p$, its contribution will be $cnt[p]\\cdot(P-cnt[p])$. Note that we must divide our result by $2$ as we would have counted each pair twice. For each semiprime $pq$, add $cnt[pq]\\cdot cnt[p]+cnt[pq]\\cdot cnt[q]$. For each semiprime $pq$, add $cnt[pq]\\cdot cnt[p]+cnt[pq]\\cdot cnt[q]$. For each semiprime $pq$, add $cnt[pq]\\cdot (cnt[pq]+1)/2$. For each semiprime $pq$, add $cnt[pq]\\cdot (cnt[pq]+1)/2$. All of these can be done in $O(n\\log n)$ time. Be sure to not use dictionary, counter, or unordered_map as they can be hacked!",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n\nvector<int> prime_factors(int x){\n\tvector<int> pf;\n\tfor(ll i = 2; i * i <= x; i++){\n\t\twhile(x % i == 0){\n\t\t\tpf.push_back(i);\n\t\t\tx /= i;\n\t\t}\n\t}\n\tif(x > 1) pf.push_back(x);\n\treturn pf;\n}\n\nint main(){\n\tint t; cin >> t;\n\twhile(t--){\n\t\tint n; cin >> n;\n\t\tll ans = 0;\n\t\tvector<int> one(n+1), two_same(n+1), two_diff(n+1), cnt(n+1);\n\t\tint prime_so_far = 0;\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tint x; cin >> x;\n\t\t\tvector<int> pf = prime_factors(x);\n\t\t\tif(pf.size() > 2) continue;\n\t\t\tif(pf.size() == 1){\n\t\t\t\tone[x]++;\n\t\t\t\tprime_so_far++;\n\t\t\t\tans += two_same[x] + two_diff[x] + (prime_so_far - one[x]);\n\t\t\t}\n\t\t\telse if(pf[0] == pf[1]){\n\t\t\t\ttwo_same[pf[0]]++;\n\t\t\t\tans += one[pf[0]] + two_same[pf[0]];\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttwo_diff[pf[0]]++;\n\t\t\t\ttwo_diff[pf[1]]++;\n\t\t\t\tcnt[x]++;\n\t\t\t\tans += one[pf[0]] + one[pf[1]] + cnt[x];\n\t\t\t}\n\t\t}\n\t\tcout << ans << \"\\n\";\n\t}\n}\n",
    "tags": [
      "combinatorics",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2065",
    "index": "H",
    "title": "Bro Thinks He's Him",
    "statement": "Skibidus thinks he's Him! He proved it by solving this difficult task. Can you also prove yourself?\n\nGiven a binary string$^{\\text{∗}}$ $t$, $f(t)$ is defined as the minimum number of contiguous substrings, each consisting of identical characters, into which $t$ can be partitioned. For example, $f(00110001) = 4$ because $t$ can be partitioned as $[00][11][000][1]$ where each bracketed segment consists of identical characters.\n\nSkibidus gives you a binary string $s$ and $q$ queries. In each query, a single character of the string is flipped (i.e. $0$ changes to $1$ and $1$ changes to $0$); changes are saved after the query is processed. After each query, output the sum over all $f(b)$ where $b$ is a non-empty subsequence$^{\\text{†}}$ of $s$, modulo $998\\,244\\,353$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string consists of only characters $0$ and $1$.\n\n$^{\\text{†}}$A subsequence of a string is a string which can be obtained by removing several (possibly zero) characters from the original string.\n\\end{footnotesize}",
    "tutorial": "A brute attempt at a solution would be to go through each non-empty subset of ${1,2,...,n}$ and, for every pair of adjacent indices $(i, j)$ in the subset, increase $ans$ if $s[i] \\neq s[j]$ In other words, increase ans every time $s[i]$ and $s[j]$ create a new border This is extremely slow at $O(2^n*n)$; however, we can notice that every adjacent pair is independent from the rest in the subset. We may ask ourselves: for a fixed $(i, j)$, how many subsets increase ans through that $(i, j)$? The conditions are that: $i$ and $j$ are in the subset $i$ and $j$ are adjacent in the subset (there's no other included value in between) $s[i] \\neq s[j]$ Which leaves us free to choose the prefix and the suffix. $(2^{i-1}*2^{n-j})$. An $O(n^2)$ solution is: The rest of the solution will try to optimize how to compute that sum, and then how to maintain the answer through updates. We may notice we can pull out the $2^{n-j}$ factor and rewrite the loops as: Since the second for loop only cares about what $s[j]$ is (nothing else about $j$), we can again easily optimize it as: In other words, we don't need to recalculate $sumI$ each new $j$. Instead, we can maintain its $2$ possible values ($s[j]=0, s[j]=1$) as we increase $j$ (since $sumI$ cares about ($1\\leq i<j$)) We can run this $O(n)$ solution once before any updates, but not after each update because $O(q*n)$ is too slow. Instead, we can make the minimal adjustments needed to maintain ans correctly. Let's call the toggled index $k$: How much does $s[k]$ contribute to ans in the first place? We can partition $s[k]$'s contribution to the answer in $2$ cases: - When $j=k$, $ans += sumI[s[k]]*2^{n-k}$ - After $sumI[s[k]\\oplus1] += 2^{k-1}$, every time $sumI[s[k]\\oplus 1]$ is used to increase ans As for the first case, we can calculate the value of $sumI[s[k]]$ at $j=k$ using the sum of $2^{i-1}$ for $i < k$ and $s[i]=s[k]\\oplus1$. As for the second case, it's only slightly trickier, but along the same general idea. It can be calculated using the sum of $2^{n-j}$ for $j > k$ and $s[j]=s[k]\\oplus 1$. Fenwick (or segment) tree solves both cases, which are essentially dynamically calculating range sums on an array. Since for both cases we may consider when $s[k]=0$ or $s[k]=1$, a total of $4$ different fenwick trees will be needed. $(2^{i-1}$ when $s[i]=0, 0$ otherwise); ($2^{i-1}$ when $s[i]=1, 0$ otherwise); $(2^{n-j}$ when $s[j]=0, 0$ otherwise); $(2^{n-j}$ when $s[j]=1, 0$ otherwise) The procedure is thus: before toggling a bit, subtract its contribution from ans. After toggling the bit, add its new contribution to ans. Also, update the $4$ fenwick trees accordingly. This correctly maintains ans in $O(log(n))$ per update. So, the final complexity is $O(n+q*log(n))$",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\nusing vll = vector <ll>;\nusing ii = pair <ll, ll>;\nusing vii = vector <ii>;\n\nconst ll MAXN = 2E5+16, MOD = 998244353;\nll pw2[MAXN];\n\nstruct SegTree {\n    vll tree;\n    ll n;\n\n    SegTree (ll n): tree(2*n, 0), n(n) {}\n\n    void update (ll id, ll val) {\n        for (tree[id += n] = val; id > 1; id >>= 1)\n            tree[id>>1] = (tree[id] + tree[id^1]) % MOD;\n    }\n\n    ll query (ll ql, ll qr) {\n        ll ans = 0;\n        for (ql += n, qr += n+1; ql < qr; ql >>= 1, qr >>= 1) {\n            if (ql&1) (ans += tree[ql++]) %= MOD;\n            if (qr&1) (ans += tree[--qr]) %= MOD;\n        }\n        return ans;\n    }\n};\n\nvoid tc () {\n    string str;\n    cin >> str;\n    ll n = str.size();\n    SegTree stFreq0(n), stFreq1(n), st0(n), st1(n);\n    for (ll i = 0; i < n; i++) {\n        (str[i] == '0' ? stFreq0 : stFreq1).update(i, pw2[n-1-i]);\n        (str[i] == '0' ? st0 : st1).update(i, pw2[i]);\n    }\n    ll ans = pw2[n]-1;\n    {ll acc0 = 0, acc1 = 0;\n    for (ll i = 0; i < n; i++) {\n        (ans += (str[i] == '0' ? acc1 : acc0)*pw2[n-1-i]) %= MOD;\n        ((str[i] == '0' ? acc0 : acc1) += pw2[i]) %= MOD;\n    }}\n    ll Q;\n    cin >> Q;\n    while (Q--) {\n        ll at;\n        cin >> at;\n        at--;\n        (ans -= (str[at] == '0' ? st1 : st0).query(0, at-1)*pw2[n-1-at]) %= MOD;\n        (ans -= (str[at] == '0' ? stFreq1 : stFreq0).query(at+1, n-1)*pw2[at]) %= MOD;\n        (ans += MOD) %= MOD;\n        (str[at] == '0' ? stFreq0 : stFreq1).update(at, 0);\n        (str[at] == '0' ? st0 : st1).update(at, 0);\n        str[at] = (str[at] == '0' ? '1' : '0');\n        (str[at] == '0' ? stFreq0 : stFreq1).update(at, pw2[n-1-at]);\n        (str[at] == '0' ? st0 : st1).update(at, pw2[at]);\n        (ans += (str[at] == '0' ? st1 : st0).query(0, at-1)*pw2[n-1-at]) %= MOD;\n        (ans += (str[at] == '0' ? stFreq1 : stFreq0).query(at+1, n-1)*pw2[at]) %= MOD;\n        cout << ans << ' ';\n    }\n    cout << '\\n';\n}\n\nint main () {\n    cin.tie(nullptr) -> sync_with_stdio(false);\n    pw2[0] = 1;\n    for (ll i = 1; i < MAXN; i++) pw2[i] = pw2[i-1]*2 % MOD;\n    ll T; cin >> T; while (T--) { tc(); }\n    return 0;\n}\n",
    "tags": [
      "combinatorics",
      "data structures",
      "divide and conquer",
      "dp",
      "math",
      "matrices"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2066",
    "index": "A",
    "title": "Object Identification",
    "statement": "This is an interactive problem.\n\nYou are given an array $x_1, \\ldots, x_n$ of integers from $1$ to $n$. The jury also has a fixed but hidden array $y_1, \\ldots, y_n$ of integers from $1$ to $n$. The elements of array $y$ are \\textbf{unknown} to you. Additionally, it is known that for all $i$, $x_i \\neq y_i$, and all pairs $(x_i, y_i)$ are distinct.\n\nThe jury has secretly thought of one of two objects, and you need to determine which one it is:\n\n- \\textbf{Object A}: A directed graph with $n$ vertices numbered from $1$ to $n$, and with $n$ edges of the form $x_i \\to y_i$.\n- \\textbf{Object B}: $n$ points on a coordinate plane. The $i$-th point has coordinates $(x_i, y_i)$.\n\nTo guess which object the jury has thought of, you can make queries. In one query, you must specify two numbers $i, j$ $(1 \\leq i, j \\leq n, i \\neq j)$. In response, you receive one number:\n\n- If the jury has thought of \\textbf{Object A}, you receive the length of the shortest path (in edges) from vertex $i$ to vertex $j$ in the graph, or $0$ if there is no path.\n- If the jury has thought of \\textbf{Object B}, you receive the Manhattan distance between points $i$ and $j$, that is $|x_i -x_j| + |y_i - y_j|$.\n\nYou have $2$ queries to determine which of the objects the jury has thought of.",
    "tutorial": "Note that if Object A is chosen, we can receive the number $0$ in response to some query, while if Object B is chosen, we cannot: since $(x_i,y_i) \\neq (x_j,y_j)$. If the array $x_1, x_2, \\ldots, x_n$ is not a permutation of the numbers from $1$ to $n$, then there will be some number $1 \\leq a \\leq n$ that is not present in the array $x$. In this case, if Object A is chosen, any query $(a, *)$ will yield a response of $0$, since there are simply no edges from vertex $a$ (here $*$ denotes any number from $1$ to $n$ that is not equal to $a$). We can make such a query, and by checking whether the response is $0$, we can immediately determine which object the jury has chosen. However, if the array $x_1, x_2, \\ldots, x_n$ is a permutation. Let's find such $i$ and $j$ that $x_i=1$ and $x_j=n$, and make the queries $(i,j)$ and $(j,i)$. In the case that Object B is chosen: we should receive two identical numbers, both of which must be $\\geq n-1$, since $|x_i-x_j| = n-1$. It is not hard to see that such a situation is impossible if Object A is chosen: for $n \\geq 3$, in a directed graph with $n$ vertices and $n$ edges, it cannot be that for some pair of vertices, the distances from one to the other in both directions are $\\geq n-1$. Therefore, these two queries are sufficient to uniquely identify the objects. If both received numbers are equal and $\\geq n-1$: Object B is chosen; otherwise, Object A is chosen.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> x(n + 1), isx(n + 1);\n    for (int i = 1; i <= n; i++) {\n        cin >> x[i];\n        isx[x[i]] = 1;\n    }\n    if (accumulate(isx.begin(), isx.end(), 0) == n) {\n        int i1 = 0, in = 0;\n        for (int i = 1; i <= n; i++) {\n            if (x[i] == 1) {\n                i1 = i;\n            }\n            if (x[i] == n) {\n                in = i;\n            }\n        }\n        cout << \"? \" << i1 << ' ' << in << endl;\n        int ans;\n        cin >> ans;\n        if (ans < n - 1) {\n            cout << \"! A\" << endl;\n        } else if (ans > n - 1) {\n            cout << \"! B\" << endl;\n        } else {\n            cout << \"? \" << in << ' ' << i1 << endl;\n            cin >> ans;\n            if (ans == n - 1) {\n                cout << \"! B\" << endl;\n            } else {\n                cout << \"! A\" << endl;\n            }\n        }\n    } else {\n        for (int i = 1; i <= n; i++) {\n            if (!isx[i]) {\n                cout << \"? \" << i << ' ' << 1 + (i == 1) << endl;\n                int ans;\n                cin >> ans;\n                if (ans == 0) {\n                    cout << \"! A\" << endl;\n                } else {\n                    cout << \"! B\" << endl;\n                }\n                return;\n            }\n        }\n    }\n \n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "graphs",
      "greedy",
      "implementation",
      "interactive"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2066",
    "index": "B",
    "title": "White Magic",
    "statement": "We call a sequence $a_1, a_2, \\ldots, a_n$ magical if for all $1 \\leq i \\leq n-1$ it holds that: $\\operatorname{min}(a_1, \\ldots, a_i) \\geq \\operatorname{mex}(a_{i+1}, \\ldots, a_n)$. In particular, any sequence of length $1$ is considered magical.\n\nThe minimum excluded (MEX) of a collection of integers $a_1, a_2, \\ldots, a_k$ is defined as the smallest non-negative integer $t$ which does not occur in the collection $a$.\n\nYou are given a sequence $a$ of $n$ non-negative integers. Find the maximum possible length of a magical subsequence$^{\\text{∗}}$ of the sequence $a$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A sequence $a$ is a subsequence of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) element from arbitrary positions.\n\\end{footnotesize}",
    "tutorial": "Note that for those suffixes where there is no number $0$, $\\operatorname{mex}$ will be equal to $0$, and thus the condition will be satisfied, since at least on the left side it is definitely $\\geq 0$. That is, any array without zeros is magical. However, if there are at least two zeros in the array, it can no longer be magical, since we can consider a prefix containing one zero but not containing the second: the minimum on such a prefix is equal to $0$, while $\\operatorname{mex}$ on the corresponding suffix will definitely be $>0$, and the condition will not be satisfied. Thus, we know for sure that the answer is either $n - cnt_0$ or $n - cnt_0 + 1$, where $cnt_0$ is the number of $a_i=0$. Since we can choose a subsequence without zeros of length $n - cnt_0$, it will definitely be magical. However, any subsequence of length $>n - cnt_0 + 1$ must contain at least two zeros and cannot be magical. Therefore, we only need to determine when the answer is equal to $n - cnt_0 + 1$. In this case, we must take a subsequence with exactly one zero, since again, sequences with at least two zeros are definitely not magical. It is not difficult to understand that it is optimal to take the leftmost zero in the subsequence, as the condition $\\min \\geq \\operatorname{mex}$ will be guaranteed to be satisfied for prefixes containing a single zero. Thus, the solution looks as follows: If there are no zeros in the array, the answer is $n$. Otherwise, we need to choose a subsequence consisting of the leftmost zero and all non-zero elements of the sequence. Explicitly check whether it is magical (this can be easily done in $O(n)$, calculating prefix $\\min$ and suffix $\\operatorname{mex}$ is a well-known problem). If yes, the answer is: $n - cnt_0 + 1$. Otherwise, the answer is $n - cnt_0$, and a subsequence of all non-zero elements will suffice.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nbool check(vector<int> a) {\n    int n = (int) a.size();\n    vector<int> suf_mex(n);\n    vector<int> used(n + 1, false);\n    int mex = 0;\n    for (int i = n - 1; i >= 1; i--) {\n        if (a[i] <= n) {\n            used[a[i]] = true;\n        }\n        while (used[mex]) mex++;\n        suf_mex[i] = mex;\n    }\n    int mini = a[0];\n    for (int i = 0; i < n - 1; i++) {\n        mini = min(mini, a[i]);\n        if (mini < suf_mex[i + 1]) {\n            return false;\n        }\n    }\n    return true;\n}\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    bool was0 = false;\n    int cnt0 = 0;\n    vector<int> b;\n    for (int i = 0; i < n; i++) {\n        if (a[i] == 0) {\n            cnt0++;\n            if (!was0) {\n                b.push_back(a[i]);\n            }\n            was0 = true;\n        } else {\n            b.push_back(a[i]);\n        }\n    }\n    if (cnt0 > 0 && check(b)) {\n        cout << n - (cnt0 - 1) << '\\n';\n    } else {\n        cout << n - cnt0 << '\\n';\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2066",
    "index": "C",
    "title": "Bitwise Slides",
    "statement": "You are given an array $a_1, a_2, \\ldots, a_n$. Also, you are given three variables $P,Q,R$, initially equal to zero.\n\nYou need to process all the numbers $a_1, a_2, \\ldots, a_n$, \\textbf{in the order from $1$ to $n$}. When processing the next $a_i$, you must perform \\textbf{exactly} one of the three actions of your choice:\n\n- $P := P \\oplus a_i$\n- $Q := Q \\oplus a_i$\n- $R := R \\oplus a_i$\n\n$\\oplus$ denotes the bitwise XOR operation.\n\nWhen performing actions, you must follow the main rule: it is necessary that after each action, all three numbers $P,Q,R$ are \\textbf{not} pairwise distinct.\n\nThere are a total of $3^n$ ways to perform all $n$ actions. How many of them do not violate the main rule? Since the answer can be quite large, find it modulo $10^9 + 7$.",
    "tutorial": "Let us denote $pref_i = a_1 \\oplus \\ldots \\oplus a_i$ - the array of prefix $XOR$s. Notice that after the $i$-th action, it is always true that $P \\oplus Q \\oplus R = pref_i$, regardless of which actions were chosen. With this knowledge, we can say that after the $i$-th action, the condition \"the numbers $P, Q, R$ are not pairwise distinct\" is equivalent to the condition \"at least one of $P, Q, R$ equals $pref_i$.\" This is because if there is a pair of equal numbers among $P, Q, R$, their $XOR$ equals $0$, which means the third number must equal $pref_i$. Thus, all possible valid states $(P, Q, R)$ after the $i$-th action look like: $(pref_i, x, x), (x, pref_i, x), (x, x, pref_i)$ for some $x$. After this observation, we can try to write a dynamic programming solution: $dp[i][x]$ - the number of ways to reach one of the states of the form $(pref_i, x, x), (x, pref_i, x), (x, x, pref_i)$ after the $i$-th action. At first glance, this dynamic programming approach seems to take an unreasonable amount of time and memory. However, we will still outline its base case and recurrence. Base case: $dp[0][0] = 1$. Recurrence: suppose we want to recalculate $dp[i][x]$ using $dp[i-1][*]$. From which state can we arrive at $(x, x, pref_i)$ if the last move involved XORing one of the variables with $a_i$? There are three possible cases: $(x \\oplus a_i, x, pref_i)$, $(x, x \\oplus a_i, pref_i)$, $(x, x, pref_i \\oplus a_i)$. The number of ways to reach the state $(x, x, pref_i \\oplus a_i)$ is actually equal to $dp[i-1][x]$, since $pref_i \\oplus a_i = pref_{i-1}$. What about the case $(x \\oplus a_i, x, pref_i)$? For the state to be valid from the previous move, two of these numbers must be equal, and the third must equal $pref_{i-1}$. However, we know that $pref_i \\neq pref_{i-1}$, since $a_i \\neq 0$. Therefore, either $x \\oplus a_i = pref_{i-1}$ (which means $x = pref_i$), or $x = pref_{i-1}$. If $x = pref_i$, then the value of $dp[i][x]$ is also equal to $dp[i-1][x]$, because the state $(pref_i, pref_i, pref_i)$ can be reached from one of the states $(pref_{i-1}, pref_i, pref_i)$, $(pref_i, pref_{i-1}, pref_i)$, $(pref_i, pref_i, pref_{i-1})$, and the number of ways to reach one of these states after the $(i-1)$-th move is literally defined as $dp[i-1][pref_i]$. For $x = pref_{i-1}$: $dp[i][pref_{i-1}] = 3 \\cdot dp[i-1][pref_{i-1}] + 2 \\cdot dp[i-1][pref_i]$. There are a total of 3 ways to arrive from $(pref_{i-1}, pref_{i-1}, pref_{i-1})$, and 2 ways from the states $(pref_{i-1}, pref_i, pref_i)$, $(pref_i, pref_{i-1}, pref_i)$, $(pref_i, pref_i, pref_{i-1})$. In summary, the only $x$ for which $dp[i][x] \\neq dp[i-1][x]$ is $x = pref_{i-1}$. Therefore, unexpectedly, we do not need to recalculate the entire array $dp$, but only one of its values. And of course, since the elements of the array are quite large, we will store this $dp$ in a regular map. The answer to the problem will be the sum of all values of $dp$ at the end of the process.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\nusing namespace std;\n \nconst int M = 1'000'000'000 + 7;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n + 1), p(n + 1);\n    for (int i = 1; i <= n; i++) {\n        cin >> a[i];\n        p[i] = a[i] ^ p[i - 1];\n    }\n    map<int, int> dp;\n    dp[0] = 1;\n    for (int i = 1; i <= n; i++) {\n        dp[p[i - 1]] *= 3;\n        dp[p[i - 1]] += 2 * dp[p[i]];\n        dp[p[i - 1]] %= M;\n    }\n    int ans = 0;\n    for (auto &[_, x] : dp) {\n        ans += x;\n    }\n    ans %= M;\n    cout << ans << '\\n';\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2066",
    "index": "D1",
    "title": "Club of Young Aircraft Builders (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, all $a_i = 0$. You can hack only if you solved all versions of this problem.}\n\nThere is an $n$-story building, with floors numbered from $1$ to $n$ from bottom to top. There is exactly one person living on each floor.\n\nAll the residents of the building have a very important goal today: to launch at least $c$ paper airplanes collectively. The residents will launch the airplanes in turn. When a person from the $i$-th floor launches an airplane, all residents on the floors from $1$ to $i$ can see it as it descends to the ground.\n\nIf, from the perspective of the resident on the $i$-th floor, at least $c$ airplanes have already been launched, they will \\textbf{not} launch any more airplanes themselves. It is also known that by the end of the day, from the perspective of each resident in the building, at least $c$ airplanes have been launched, and a total of $m$ airplanes were thrown.\n\nYou carefully monitored this flash mob and recorded which resident from which floor threw each airplane. Unfortunately, the information about who exactly threw some airplanes has been lost. Find the number of ways to fill in the gaps so that the information could be credible. Since the answer can be quite large, output it modulo $10^9 + 7$.\n\n\\textbf{In this version of the problem, all information has been lost, and the entire array consists of gaps.}\n\nIt is also possible that you made a mistake in your records, and there is no possible way to restore the gaps. In that case, the answer is considered to be $0$.",
    "tutorial": "The problem is naturally solved using dynamic programming. The author's dynamic programming approach is as follows: Let's think: at which indices can the elements $a_i = 1$ be located? Notice that a person on the first floor can see every airplane, so the positions $a_{c+1} \\ldots a_m$ cannot contain a one. However, it is entirely possible for a one to be in any subset of positions $\\{1,2,\\ldots,c\\}$. Let's iterate $k$ from $0$ to $c$-the number of $a_i=1$ in the array. There are a total of $\\binom{c}{k}$ ways to place these ones. Note that the task of placing the remaining numbers is actually analogous to the original problem with parameters $(n-1,c,m-k)$, since the launches of airplanes from the first floor do not affect the \"counters\" of people not on the first floor; they can simply be ignored, and we can solve the problem of placing airplanes from the remaining $n-1$ floors into the remaining $m-k$ positions. Thus, we obtain the following dynamic programming relation: $dp[i][j]$ is the answer for $(n=i,m=j)$, with $c$ globally fixed. Base case: $dp[1][c] = 1$ Transition: $dp[i][j] = \\displaystyle\\sum_{k=0}^c \\binom{c}{k} \\cdot dp[i-1][j-k]$ The answer is, accordingly, in $dp[n][m]$, and the overall time complexity of the solution is $O(n \\cdot m \\cdot c)$. An interesting fact: the answer in the simple version of the problem can be expressed with a simple formula: $\\binom{nc-c}{m-c}$. Why is this the case? No idea. If someone finds a beautiful combinatorial interpretation-please share in the comments.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\nusing namespace std;\nconst int N = 105;\nint fact[N * N], inv_fact[N * N];\nconst int M = (int) 1e9 + 7;\n \nint binpow(int a, int x) {\n    int ans = 1;\n    while (x) {\n        if (x % 2) {\n            ans *= a;\n            ans %= M;\n        }\n        a *= a;\n        a %= M;\n        x /= 2;\n    }\n    return ans;\n}\n \nint C(int k, int n) {\n    if (k > n || k < 0) return 0;\n    return (((fact[n] * inv_fact[k]) % M) * inv_fact[n - k] % M);\n}\n \nunordered_map<int, int> info;\nconst int B = 10007;\n \nint xd(int n, int m, int c) {\n    if (m < c || m > n * c) return 0;\n    if (n == 1) return (m == c);\n    if (info.find(n*B*B+m*B+c) != info.end())return info[n*B*B+m*B+c];\n    int ans = 0;\n    for (int k = 0; k <= c; k++) {\n        ans += xd(n - 1, m - k, c) * C(k, c) % M;\n    }\n    ans %= M;\n    return info[n*B*B+m*B+c] = ans;\n}\n \nvoid solve() {\n    int n, c, m;\n    cin >> n >> c >> m;\n    vector<int> a(m + 1);\n    for (int i = 1; i <= m; i++) {\n        cin >> a[i];\n    }\n    cout << xd(n, m, c) << '\\n';\n}\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    fact[0] = inv_fact[0] = 1;\n    for (int x = 1; x < N * N; x++) {\n        fact[x] = ((x * fact[x - 1]) % M);\n        inv_fact[x] = binpow(fact[x], M - 2);\n    }\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2066",
    "index": "D2",
    "title": "Club of Young Aircraft Builders (hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, not necessary $a_i = 0$. You can hack only if you solved all versions of this problem.}\n\nThere is a building with $n$ floors, numbered from $1$ to $n$ from bottom to top. There is exactly one person living on each floor.\n\nAll the residents of the building have an important goal today: to launch at least $c$ paper airplanes collectively. The residents will launch the airplanes in turn. When a person from the $i$-th floor launches an airplane, all residents on floors from $1$ to $i$ can see it as it descends to the ground. If, from the perspective of the resident on the $i$-th floor, at least $c$ airplanes have already been launched, they will no longer launch airplanes themselves. It is also known that by the end of the day, from the perspective of each resident in the building, at least $c$ airplanes have been launched, and a total of $m$ airplanes were thrown.\n\nYou have been carefully monitoring this flash mob, and for each airplane, you recorded which resident from which floor threw it. Unfortunately, the information about who exactly threw some of the airplanes has been lost. Find the number of ways to fill in the gaps so that the information could be credible. Since the answer could be quite large, output it modulo $10^9 + 7$.\n\nIt is also possible that you made a mistake in your records, and there is no possible way to restore the gaps. In that case, the answer is considered to be $0$.",
    "tutorial": "In fact, the states in the dynamic programming for the complex version will be the same as in the simple version, but to handle non-zero elements, we will need a slightly different perspective. The conceptual basis, as we define the array that we want to consider in the answer, remains the same: we look at where in the array ones can be: only in the first $c$ positions. Where can twos be: also in the first $c$ positions, if we ignore the ones. And so on; in general, element $i$ can only be in the first $C + cnt_1 + \\ldots + cnt_{i-1}$ positions, where $cnt_i$ is the number of occurrences of $=i$ in the array. It would be great if we could incorporate $cnt_1 + \\ldots + cnt_{i-1}$ into the dynamic programming state. And we indeed can. Let $dp[el][sum]$ be the number of ways to arrange all occurrences of numbers from $1$ to $el$ in the array such that their count is $=sum$ (including those already placed for us where $el \\geq a_i > 0$). In fact, this is the same dynamic programming as in the simple version. In one dimension, we have a straightforward prefix, and in the other, the count of already placed elements, which is effectively $m - \\{\\text{the number of elements left to place}\\}$, which we had in the first dynamic programming. Thus, the states are essentially the same as in the simple version, but the thinking is slightly different, in a sense \"expanded.\" In the transition, as in the simple version, we will iterate $k$ from $0$ to $c$: how many elements $=el$ we are placing. According to our criteria, all occurrences $=el$ must be in the first $c + (sum - k)$ positions. We check this by counting the array $last[el]$ - the index of the last occurrence of $el$ in the given array. It must also hold that $sum \\geq k$, $k \\geq cnt[el]$, and $c + sum - k \\leq m$. If any of these conditions are not met, then $dp[el][sum] = 0$. The recounting has the same nature: only the first $c + sum - k$ positions are permissible. $sum - k$ of them are already occupied by smaller numbers. Therefore, there are $c$ free positions. However, some of them may be occupied by elements $\\geq el$ that have been placed beforehand. Thus, we need to find out how many elements $\\geq el$ are in the prefix of length $c + sum - k$ (which can be precomputed for all elements and all prefixes without much effort), and these positions are also occupied. In the remaining positions, we need to place $k - cnt[el]$ of our elements $=el$. Accordingly, the number of ways to do this is simply the binomial coefficient of one from the other multiplied by $dp[el-1][sum-k]$. The base of the dynamic programming is $dp[0][0] = 1$, and the answer is still in $dp[n][m]$. The asymptotic complexity is $O(n \\cdot m \\cdot c)$.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\nusing namespace std;\nconst int N = 105;\nint fact[N * N], inv_fact[N * N];\nconst int M = (int) 1e9 + 7;\n \nint binpow(int a, int x) {\n    int ans = 1;\n    while (x) {\n        if (x % 2) {\n            ans *= a;\n            ans %= M;\n        }\n        a *= a;\n        a %= M;\n        x /= 2;\n    }\n    return ans;\n}\n \nint C(int k, int n) {\n    if (k > n || k < 0) return 0;\n    return (((fact[n] * inv_fact[k]) % M) * inv_fact[n - k] % M);\n}\n \nvoid solve() {\n    int n, c, m;\n    cin >> n >> c >> m;\n    vector<int> a(m + 1);\n    vector<int> last(n + 1), cnt(n + 1);\n    for (int i = 1; i <= m; i++) {\n        cin >> a[i];\n        if (a[i] != 0) {\n            last[a[i]] = i;\n            cnt[a[i]]++;\n        }\n    }\n    vector<vector<int>> more_on_prefix(m + 1, vector<int>(n + 1));\n    for (int i = 1; i <= m; i++) {\n        for (int el = 1; el <= n; el++) {\n            more_on_prefix[i][el] = more_on_prefix[i - 1][el] + (a[i] >= el);\n        }\n    }\n \n    vector<vector<int>> dp(n + 1, vector<int>(m + 1));\n \n    dp[0][0] = 1;\n    for (int el = 1; el <= n; el++) {\n        for (int sum = 0; sum <= m; sum++) {\n            dp[el][sum] = 0;\n            for (int x = 0; x <= c; x++) {\n                if (sum < x) {\n                    continue;\n                }\n                if (last[el] > c + sum - x) {\n                    continue;\n                }\n                if (x < cnt[el]) {\n                    continue;\n                }\n                if (c + sum - x > m) {\n                    continue;\n                }\n                int free_spots = c - more_on_prefix[c + sum - x][el];\n                int need_to_put = x - cnt[el];\n                dp[el][sum] += (dp[el - 1][sum - x] * C(need_to_put, free_spots)) % M;\n                if (dp[el][sum] >= M) {\n                    dp[el][sum] -= M;\n                }\n            }\n        }\n    }\n \n    cout << dp[n][m] << '\\n';\n \n}\n \nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    fact[0] = inv_fact[0] = 1;\n    for (int x = 1; x < N * N; x++) {\n        fact[x] = ((x * fact[x - 1]) % M);\n        inv_fact[x] = binpow(fact[x], M - 2);\n    }\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "combinatorics",
      "dp",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2066",
    "index": "E",
    "title": "Tropical Season",
    "statement": "You have $n$ barrels of infinite capacity. The $i$-th barrel initially contains $a_i$ kilograms of water. In this problem, we assume that all barrels weigh the same.\n\nYou know that \\textbf{exactly} one of the barrels has a small amount of tropical poison distributed on its surface, with a total weight of $0.179$ kilograms. However, you do not know which barrel contains the poison. Your task is to identify this poisonous barrel.\n\nAll the barrels are on scales. Unfortunately, the scales do not show the exact weight of each barrel. Instead, for each pair of barrels, they show the result of a comparison between the weights of those barrels. Thus, for any two barrels, you can determine whether their weights are equal, and if not, which barrel is heavier. The poison and water are included in the weight of the barrel.\n\nThe scales are always turned on, and the information from them can be used an unlimited number of times.\n\nYou also have the ability to pour water. You can pour water from any barrel into any other barrel in any amounts.\n\nHowever, to pour water, you must physically handle the barrel from which you are pouring, so if that happens to be the poisonous barrel, you will die. This outcome must be avoided.\n\nHowever, you can pour water into the poisonous barrel without touching it.\n\nIn other words, you can choose the numbers $i, j, x$ ($i \\neq j, 1 \\leq i, j \\leq n, 0 < x \\leq a_i$, the barrel numbered $i$ is \\textbf{not} poisonous) and execute $a_i := a_i - x$, $a_j := a_j + x$. Where $x$ is not necessarily an integer.\n\nIs it possible to guarantee the identification of which barrel contains the poison and remain alive using pouring and the information from the scales? You know that the poison is located on \\textbf{exactly} one of the barrels.\n\nAdditionally, we ask you to process $q$ queries. In each query, either one of the existing barrels is removed, or an additional barrel with a certain amount of water is added. After each query, you need to answer whether it is possible to guarantee the identification of the poisonous barrel, given that there is exactly one.",
    "tutorial": "If all values $a_1, a_2, \\ldots, a_n$ are distinct, we immediately lose (except for $n=1$). Suppose initially there are two barrels of equal weight $a_i = a_j$. Then we look at what the scales indicate for the pair $(i, j)$. If it shows \"greater\" or \"less\" - we understand that the poisonous barrel is respectively $i$ or $j$ and we win immediately. If it shows \"equal,\" then both barrels are definitely not poisonous. We will keep only the barrels whose mass $(a_i)$ appears exactly once, and from all the other barrels, we can pour all the water into one of the barrels, and let the mass of this water be $L$. We have $L$ water available to pour into a safe barrel, and in the remaining barrels $b_1 < b_2 < \\ldots < b_k$ there is water. If $L$ water is currently available, we can either: Check any barrel that has $\\leq L$ water. By pouring water from the safe barrel into it until the weights are equal, we then check the scales. If they show equality, we know for sure that this barrel is safe; otherwise, we know it is poisonous. Take any two barrels with a difference of no more than $L$: $b_j - b_i \\leq L$, add water to the $i$-th barrel to equalize the weights, and also compare the barrels $(i,j)$ by checking both. We have no other methods; if with the current $L$ both of these methods are inapplicable, but there are more than one unverified barrels left - we lose. If we consider that the first method is applied \"automatically\" as long as possible, it means that at any moment we possess some prefix of barrels $b_1 < b_2 < ... < b_i < [...] < b_{i+1} < ... < b_k$, since if we have checked barrel $b_j > b_i$, we can also check $b_i$. Therefore, we need to determine whether it is true that if we have $L+b_1+b_2+\\ldots+b_i$ of free water, we can perform some action to check one of the barrels $b_{i+1} \\ldots b_k$ for all $i$ from $0$ to $k-2$. If this holds, we can iteratively determine everything; if not, at some point we will hit a wall and will not be able to determine anything about the barrels $b_{i+1} \\ldots b_k$. The upper limit is $k-2$, not $k-1$, because if we check all barrels except one, the remaining unverified barrel will be deemed poisonous by the process of elimination. Let's say that $i$ is a special index if $b_{i+1} > b_1+b_2+\\ldots+b_i$. Note that we can check the condition from the previous paragraph not for all $i$, but only for special $i$, and this will be equivalent. Since from a non-special index, we can always check barrel $i+1$. However, there are also no more than $\\log_2(b_k)$ special indices, since with each special index, the prefix sum of the array $b$ increases at least twofold. Therefore, our further plan for solving the problem is as follows: after each query, we find all special indices and explicitly check each of them, finding $\\min (b_{j+1}-b_j)$ on the suffix and comparing it with $L+b_1+\\ldots+b_i$. We will learn to find and check a special index in $O(\\log(a_n))$ and obtain a solution in $O(q \\cdot \\log^2(a_n))$. We can use a set to support \"unique\" weights of barrels and the amount of available water at the very beginning. Then, adding/removing unique barrels can be implemented using a large segment tree of size $\\max(a_i)=10^6$. Thus, finding the next \"special\" index and checking it can be implemented by descending/querying in this segment tree.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\ntypedef long long ll;\ntypedef long double ld;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define pb push_back\n#define ar(x) array<int, x>\nconst int MAXA = 1'000'009;\nconst int INF = (int) 1e18;\n \nstruct SegTreeMIN {\n    int n = 1;\n    vector<int> tree;\n \n    SegTreeMIN(int n_) {\n        while (n <= n_) n *= 2;\n        tree.assign(4 * n + 7, INF);\n    }\n \n    void upd(int v, int l, int r, int i, int x) {\n        if (l + 1 == r) {\n            tree[v] = x;\n            return;\n        }\n        int mid = (l + r) / 2;\n        if (i < mid) {\n            upd(2 * v + 1, l, mid, i, x);\n        } else {\n            upd(2 * v + 2, mid, r, i, x);\n        }\n        tree[v] = min(tree[2 * v + 1], tree[2 * v + 2]);\n    }\n \n    int get(int v, int l, int r, int lq, int rq) {\n        if (l >= rq || lq >= r) return INF;\n        if (lq <= l && r <= rq) return tree[v];\n        int mid = (l + r) / 2;\n        return min(get(2 * v + 1, l, mid, lq, rq), get(2 * v + 2, mid, r, lq, rq));\n    }\n \n    void upd(int i, int x) {\n        upd(0, 0, n, i, x);\n    }\n \n    int get(int lq, int rq) {\n        return get(0, 0, n, lq, rq);\n    }\n \n};\n \nstruct SegTreeSUM {\n    int n = 1;\n    vector<int> tree;\n \n    SegTreeSUM(int n_) {\n        while (n <= n_) n *= 2;\n        tree.assign(4 * n + 7, 0);\n    }\n \n    void upd(int v, int l, int r, int i, int x) {\n        if (l + 1 == r) {\n            tree[v] = x;\n            return;\n        }\n        int mid = (l + r) / 2;\n        if (i < mid) {\n            upd(2 * v + 1, l, mid, i, x);\n        } else {\n            upd(2 * v + 2, mid, r, i, x);\n        }\n        tree[v] = tree[2 * v + 1] + tree[2 * v + 2];\n    }\n \n    int get(int v, int l, int r, int lq, int rq) {\n        if (l >= rq || lq >= r) return 0;\n        if (lq <= l && r <= rq) return tree[v];\n        int mid = (l + r) / 2;\n        return get(2 * v + 1, l, mid, lq, rq) + get(2 * v + 2, mid, r, lq, rq);\n    }\n \n    void upd(int i, int x) {\n        upd(0, 0, n, i, x);\n    }\n \n    int get(int lq, int rq) {\n        return get(0, 0, n, lq, rq);\n    }\n \n};\n \nstruct Solver {\n    int WATER = 0; // sum of all but unique\n    map<int, int> barrels;\n    set<int> unique_barrels;\n    SegTreeMIN dist_to_next = SegTreeMIN(MAXA);\n    SegTreeSUM available_barrels = SegTreeSUM(MAXA);\n \n    int prev_unique(int x) {\n        if (*unique_barrels.begin() >= x) return -1;\n        auto it = unique_barrels.lower_bound(x);\n        it--;\n        return *it;\n    }\n \n    int next_unique(int x) {\n        if (*unique_barrels.rbegin() <= x) return -1;\n        auto it = unique_barrels.upper_bound(x);\n        return *it;\n    }\n \n    void upd_dist(int x) {\n        if (x == -1) return;\n        if (unique_barrels.find(x) == unique_barrels.end()) {\n            dist_to_next.upd(x, INF);\n            return;\n        }\n        int y = next_unique(x);\n        if (y == -1) {\n            dist_to_next.upd(x, INF);\n            return;\n        }\n        dist_to_next.upd(x, y - x);\n    }\n \n    void upd_ava(int x) {\n        if (unique_barrels.find(x) == unique_barrels.end()) {\n            available_barrels.upd(x, 0);\n        } else {\n            available_barrels.upd(x, x);\n        }\n    }\n \n    void unique_add(int x) {\n        WATER -= x;\n        unique_barrels.insert(x);\n        int y = prev_unique(x);\n        upd_dist(y);\n        upd_dist(x);\n        upd_ava(x);\n    }\n \n    void unique_erase(int x) {\n        WATER += x;\n        int y = prev_unique(x);\n        unique_barrels.erase(x);\n        upd_dist(y);\n        upd_dist(x);\n        upd_ava(x);\n    }\n \n    void add(int x) {\n        WATER += x;\n        if (barrels[x] == 1) {\n            unique_erase(x);\n        }\n        barrels[x]++;\n        if (barrels[x] == 1) {\n            unique_add(x);\n        }\n    }\n \n    void erase(int x) {\n        assert(barrels[x] >= 1);\n        WATER -= x;\n        if (barrels[x] == 1) {\n            unique_erase(x);\n        }\n        barrels[x]--;\n        if (barrels[x] == 1) {\n            unique_add(x);\n        }\n    }\n \n    int sum_water(int x) {\n        // total amount of water in u-barrels <= x\n        return available_barrels.get(0, x + 1);\n    }\n \n    bool is_special(int x) {\n        return x > WATER + sum_water(x - 1);\n    }\n \n    vector<int> find_all_special() {\n        int balance = WATER;\n        vector<int> ans;\n        while (balance < MAXA) {\n            int x = next_unique(balance);\n            if (x == -1) break;\n            if (is_special(x)) {\n                ans.push_back(x);\n            }\n            balance = WATER + sum_water(x);\n        }\n        return ans;\n    }\n \n    bool check_val(int x) {\n        // if we have all u-barrels < x, can we get another one?\n        if (unique_barrels.size() <= 1) return true;\n        int y = prev_unique(*unique_barrels.rbegin());\n        if (x > y) {\n            return true; // <=1 u-barrels left\n        }\n        int BALANCE = WATER + sum_water(x - 1);\n        y = next_unique(x - 1);\n        assert(y != -1);\n        if (BALANCE >= y) {\n            return true;\n        }\n        int min_diff = dist_to_next.get(x, dist_to_next.n);\n        if (BALANCE >= min_diff) {\n            return true;\n        }\n        return false;\n    }\n \n    bool check() {\n        if (unique_barrels.empty()) return true;\n        for (auto x: find_all_special()) {\n            if (!check_val(x)) {\n                return false;\n            }\n        }\n        return true;\n    }\n \n};\n \nvoid solve() {\n    int n, q;\n    cin >> n >> q;\n    Solver boss;\n    for (int i = 0; i < n; i++) {\n        int x;\n        cin >> x;\n        boss.add(x);\n    }\n    if (boss.check()) {\n        cout << \"Yes\\n\";\n    } else {\n        cout << \"No\\n\";\n    }\n    for (int i = 0; i < q; i++) {\n        char c;\n        int x;\n        cin >> c >> x;\n        if (c == '+') {\n            boss.add(x);\n        } else {\n            boss.erase(x);\n        }\n        if (boss.check()) {\n            cout << \"Yes\\n\";\n        } else {\n            cout << \"No\\n\";\n        }\n    }\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    solve();\n}",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2066",
    "index": "F",
    "title": "Curse",
    "statement": "You are given two arrays of integers: $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_m$.\n\nYou need to determine if it is possible to transform array $a$ into array $b$ using the following operation several (possibly, zero) times.\n\n- Among all non-empty subarrays$^{\\text{∗}}$ of $a$, choose any with the maximum sum, and replace this subarray with an arbitrary non-empty integer array.\n\nIf it is possible, you need to construct any possible sequence of operations. Constraint: in your answer, the sum of the lengths of the arrays used as replacements must not exceed $n + m$ across all operations. The numbers must not exceed $10^9$ in absolute value.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "$\\operatorname{MSS}(a)$ - the maximum sum of a non-empty subarray $a$. A detailed proof of the solution will be at the end of the analysis. First, we need to characterize all arrays reachable from $a$ through operations. Often, in such cases, we want to find some property that remains unchanged during operations or changes in a predictable way (for example, only increases). However, in this problem, neither the elements nor the length of the array are constant, so at first glance, it is unclear what kind of invariant we want to find. Let's consider a minimal example where not all arrays are explicitly reachable from the original one, and there are some restrictions. Let $a = [-1, -1]$. In the first operation, we replace one of the $-1$s. If we replace it with an array with a maximum subarray sum $> -1$, we are then obliged to replace something inside that subarray. If we replace it with an array with a maximum subarray sum $\\leq -1$, we must also replace either strictly inside that array or the second $-1$. Thus, all changes occur either in the array generated by the first $-1$ or the second $-1$. We can represent a barrier between the elements of the array: $[(-1) \\color{red}{|}(-1)]$. Any replacement of a subarray will never cross this barrier. It turns out that, in general, we can set such barriers that will never be crossed during operations in a fairly intuitive way. For the array $a_1, ..., a_n$, we define a cool partition of the array into subsegments recursively: The cool partition of an empty array is empty. We find any segment of maximum length $[l,r]$ such that $\\operatorname{MSS}(a) = a_l + \\ldots + a_r$. Then the cool partition will consist of the segments of the cool partition $a_1, \\ldots, a_{l-1}$, the segment $[l,r]$, and the segments of the cool partition $a_{r+1}, \\ldots, a_n$. It is not difficult to prove that the cool partition is uniquely defined for each array. It turns out that if we represent barriers between neighboring segments of the cool partition, these barriers will never be crossed during operations. Moreover, the cool partition of any array obtained from $a$ through operations will contain at least the same barriers as $a$. At the same time, due to the properties of construction, one operation in the array $a$ completely replaces one of the segments of the cool partition with the maximum sum. It turns out that all arrays reachable from $a$ must have the following structure: Any number $x$ is chosen from the sums of the segments of the cool partition of $a$. Among the segments of the cool partition of $a$, those segments whose sum is $< x$ remain unchanged. Among the remaining segments: one is replaced with an arbitrary non-empty array, and all others with an arbitrary non-empty array $y$ such that $\\operatorname{MSS}(y) \\leq x$. The sequence of operations is as follows: we replace all segments in descending order of their sums. The segment we want to replace with an arbitrary array is first replaced with $\\{x\\}$. After all segments are replaced, the last operation replaces this $\\{x\\}$ with an arbitrary array. Knowing this, we can solve the problem using dynamic programming in $O(n^2 \\cdot m)$. We will precompute the cool partition of the array $a$. Then we can iterate over the separator value $x$ in $O(n)$, and for each such value, we will run the dynamic programming $dp[i][j][flag]$ - whether it is possible to match a prefix of the first $i$ segments of the special partition to the prefix $b_1,b_2,\\ldots,b_j$, where $flag$ indicates whether we have already used a replacement with an arbitrary non-empty array, or all current replacements were with arrays with $\\operatorname{MSS} \\leq x$. Naively, the recalculation will work in $O(n)$, but with some simple optimizations, it is easy to achieve a total asymptotic complexity of recalculation for all states of $O(n \\cdot m)$, and then the entire dynamic programming will work in $O(n \\cdot m)$, and the whole solution in $O(n^2 \\cdot m)$. Now, here is the complete proof of the solution. Statement Given an array $a_1, a_2, \\ldots, a_n$ of integers. The following operation is given: Choose any pair $(l, r)$ such that $1 \\leq l \\leq r \\leq n$, and $a_l + \\ldots + a_r$ is maximum among all numbers of the form $a_{l'} + \\ldots + a_{r'}$. Replace the subarray $a_l...a_r$ with an arbitrary non-empty array. That is, replace the working array $[a_1, \\ldots, a_n]$ with $[a_1, \\ldots, a_{l-1}, b_1, \\ldots, b_m, a_{r+1}, \\ldots, a_n]$, where $m \\geq 1$ and $b_1, ..., b_m$ are chosen by you, and the numbers are integers. Goal: characterize all arrays reachable from $[a_1, \\ldots, a_n]$ through unlimited applications of such operations. General Remarks $[l, r]$ denotes the subarray $a_l...a_r$. $(l \\leq r)$ $sum(l, r)$ denotes $a_l + \\ldots + a_r$. Definition 1 A segment $[l, r]$ will be called cool if: $sum(l, r)$ is maximum among all segments. $\\forall (l_0 \\leq l) \\wedge (r_0 \\geq r) \\wedge (l_0 < l \\vee r_0 > r)$ it holds that $sum(l_0, r_0) < sum(l, r)$. Claim 2 If operations are applied only to cool segments, the set of reachable arrays will not change. Proof: If the segment $[l, r]$ is not cool, then $\\exists l_0, r_0$ such that $l_0 \\leq l, r_0 \\geq r$ and $[l_0, r_0]$ is cool. Then applying the operation to $[l, r]$ with the array $b_1, .., b_m$ can be replaced by applying the operation to $[l_0, r_0]$ with the array $a_{l_0}, \\ldots, a_{l-1}, b_1, \\ldots, b_m, a_{r+1}, \\ldots, a_{r_0}$, and the array after replacement will remain the same. Therefore, any operation with a non-cool segment can be freely replaced with an operation with a cool one, which proves the claim. From now on, we will assume that operations are applied only to cool segments. Thanks to Claim 2, we know that this is equivalent to the original problem. Claim 3 Two different cool segments do not intersect. That is, if $[l_1,r_1]$ and $[l_2,r_2]$ are cool segments, and $l_1 \\neq l_2 \\vee r_1 \\neq r_2$, it follows that $[l_1,r_1] \\cap [l_2,r_2] = \\emptyset$. Proof: Assume that there are intersecting cool segments. We will consider two cases: intersection and nesting. We can consider the union and intersection of our segments. The sum of the union and intersection then equals the sums of our cool segments. Thus, either the sum of the union is not less, and the segments are not cool, since they can be expanded. Or the sum of the intersection is greater, and the segments are not cool, since there exists one with a greater sum. Nesting is impossible, as the smaller segment could then be expanded to a larger one, meaning by definition it is not cool. Let's introduce the concept of partitioning the array into cool segments: a cool partition. Definition 4 For the array $a_1, ..., a_n$, we define a cool partition recursively: If $[1,n]$ is a cool segment, then the cool partition will consist of one segment $[1,n]$. Otherwise, we find any cool segment $[l,r]$. Then the cool partition will consist of the segments of the cool partition $a_1, \\ldots, a_{l-1}$, the segment $[l,r]$, and the segments of the cool partition $a_{r+1}, \\ldots, a_n$. It is easy to see that the cool partition is uniquely defined. This follows from Claim 3. Claim 5 In one operation, one of the segments of the cool partition with the maximum sum is completely replaced. It is obvious that we literally defined the cool partition such that all cool segments of the original array are included, and we replace only cool segments. Claim 6 The existing boundaries of the cool partition will necessarily remain the same after the operation. That is, if our array and its cool partition are: $[a_1, \\ldots, a_{r_1}], [a_{r_1+1}, \\ldots, a_{r_2}], \\ldots, [a_{r_{k-1}+1}, \\ldots, a_{r_k}]$ And we replace the cool segment $[a_{r_i+1}, \\ldots, a_{r_{i+1}}]$ with maximum sum with some $b_1,\\ldots, b_m$, then after the operation, the cool partition of the array will continue to contain all the same segments to the left and right of the replaced one. That is, the cool partition of the new array will look like: $[a_1, \\ldots, a_{r_1}], [a_{r_{i-1}+1}, \\ldots, a_{r_i}], BCOOL, [a_{r_{i+1}+1}, \\ldots, a_{r_{i+2}}], \\ldots, [a_{r_{k-1}+1}, \\ldots, a_{r_k}]$ Where $BCOOL$ is the cool partition of the array $b_1,\\ldots, b_m$. Proof: Any subarray $M$ from the cool partition has the property that all sums of subarrays of $M$ do not exceed the sum of $M$. Otherwise, a subsegment $M$ with a greater sum would have been chosen instead of $M$ in the cool partition. Also, we note that $\\forall l \\leq r_i a_l+\\ldots+a_{r_i}<0$, since otherwise $[a_{r_i+1}, \\ldots, a_{r_{i+1}}]$ would not be a cool segment, as it could be expanded to the left without losing its sum. Similarly, it follows that $\\forall R \\geq r_{i+1}+1, a_{r_{i+1}+1} + \\ldots + a_R < 0$. Therefore, the boundaries around the old cool segment will necessarily be preserved. If any of them is violated, the intersecting boundary array will have a prefix or suffix with a negative sum, which violates the property of the subarray from the cool partition, as the complement of this prefix/suffix would have a greater sum than the subarray itself. Since the boundaries hold, the cool partition in 3 parts will be independent of each other, and thus it will remain the same on the left and right as before, while inside will be $BCOOL$. Definition 7 The scale of the operation replacing the segment $[l,r]$ will be called $sum(l,r)$. Definition 8 A finite sequence of operations $op_1, op_2, \\ldots, op_k$ will be called reasonable if the sequence of scales of the operations is strictly non-increasing. That is, $s_i \\geq s_{i+1}$ for all $i$, where $s_i$ is the scale of the $i$-th operation. Claim 9 If we consider only reasonable sequences of operations, the set of reachable arrays will remain the same. If there is some unreasonable sequence of operations, then it has $s_i < s_{i+1}$. This means that during the $i$-th operation, the maximum sum of the cool segment increased. But as we know, the old segments all remained, and only $BCOOL$ is new. Thus, the next operation will be entirely within $b_1,\\ldots,b_m$. But then we could have made this replacement in the previous operation immediately, resulting in one less operation. Therefore, the shortest path to each reachable array is reasonable, as any unreasonable one can be shortened by one operation. Thus, any reachable array is necessarily reachable by reasonable sequences of operations. From now on, we will consider only reasonable sequences of operations. Thanks to Claim 9, this is equivalent to the original problem. Now we are ready to formulate and prove the necessary condition for a reachable array. Let the sums in the segments of the cool partition of the original array be: $[s_1, s_2, \\ldots, s_k]$. It is claimed that all reachable arrays must have the following form (necessary condition): Some integer $x$ is chosen. Among the segments of the cool partition, those segments whose sum is $<x$ remain unchanged. Among the remaining segments: one chosen segment is replaced with an arbitrary non-empty array, and all others with an arbitrary non-empty array such that the sum of its maximum subarray $\\leq x$. And the reachable array = concatenation of these segments. Let's show that any finite reasonable sequence of operations must lead us to an array of the described form. We have the initial boundaries of the cool partition of the given array. As we know, they will remain with us forever. Also, the sums in these segments cannot increase BEFORE the last operation is applied, as we are only considering reasonable sequences. The very last operation can, of course, increase the sum. Therefore, let us say that in the last operation we replace the subarray with scale $=x$. We look at the state of our array before this last operation. The segments of the cool partition with a sum $<x$ could not have changed, again because we are only considering reasonable sequences, and since $x$ is the scale of the last operation, ALL operations had a scale of at least $x$. In the segments of the cool partition with a sum $\\geq x$, now between these same boundaries, the sum of the maximum subarray must be $\\leq x$. New boundaries of the cool partition may have appeared, but this is not important to us. We are only looking at the original boundaries and the sums between them. Thus, it turns out to be a description as above. And in the last operation, one of the segments is replaced with an arbitrary array. This last segment must also lie entirely within the boundaries of one of the segments of the original cool partition. Therefore, we can safely say that the entire corresponding cool segment was replaced, as in the claimed description. In the end, any sequence of operations must fit the description. And it remains to show the sufficiency: that any array from the description is reachable. We simply take and replace the cool segments with the desired arrays in descending order of their sums. The one we plan to replace last, with an arbitrary array, is first replaced simply with $[x]$, and then when we replace everything we wanted, we replace it last with an arbitrary array. Thus, the proposed description is indeed the description of all reachable arrays.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \n// #define int long long\ntypedef long long ll;\ntypedef long double ld;\n \n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n#define sum(x) accumulate(all(x), 0)\nconst int INF = 2'000'000'000;\nconst int PLACEHOLDER = INF;\n \nvector<vector<int>> cool_split(vector<int> a) {\n    if (a.empty())return {};\n    int n = (int) a.size();\n    array<int, 4> mxi = {-INF, 0, 0, 0};\n    int sumi = 0;\n    int smallest_pref = 0, prefi = 0;\n    for (int i = 0; i < n; i++) {\n        sumi += a[i];\n        mxi = max(mxi, {sumi - smallest_pref, i - prefi, prefi, i});\n        if (smallest_pref > sumi) {\n            smallest_pref = sumi;\n            prefi = i + 1;\n        }\n    }\n    auto [_, __, l, r] = mxi;\n    vector<int> al, amid, ar;\n    for (int i = 0; i < n; i++) {\n        if (i < l) {\n            al.push_back(a[i]);\n        } else if (i <= r) {\n            amid.push_back(a[i]);\n        } else {\n            ar.push_back(a[i]);\n        }\n    }\n    vector<vector<int>> X = cool_split(al), Y = cool_split(ar);\n    X.push_back(amid);\n    for (auto el: Y)X.push_back(el);\n    return X;\n}\n \nconst int N = 503;\nbool dp[N][N][2];\narray<int, 2> go[N][N][2];\nint maxsubsum[N][N];\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    vector<int> b(m), prefb(m);\n    for (int i = 0; i < m; i++) {\n        cin >> b[i];\n    }\n    prefb[0] = b[0];\n    for (int i = 1; i < m; i++) {\n        prefb[i] = b[i] + prefb[i - 1];\n    }\n \n    auto get_sum = [&](int l, int r) {\n        if (l == 0) return prefb[r];\n        return prefb[r] - prefb[l - 1];\n    };\n \n    for (int i = 0; i < m; i++) {\n        maxsubsum[i][i] = b[i];\n    }\n    for (int l = 1; l < m; l++) {\n        for (int i = 0; i + l < m; i++) {\n            int j = i + l;\n            maxsubsum[i][j] = max({maxsubsum[i + 1][j], maxsubsum[i][j - 1], get_sum(i, j)});\n        }\n    }\n \n \n    vector<vector<int>> spa = cool_split(a);\n    vector<array<int, 2>> order;\n    for (int i = 0; i < spa.size(); i++) {\n        order.push_back({sum(spa[i]), i});\n    }\n    sort(rall(order));\n    vector<tuple<int, int, vector<int>>> ops;\n \n    auto check = [&](int u) -> bool {\n        for (int i = 0; i <= spa.size(); i++) {\n            for (int j = 0; j <= m; j++) {\n                dp[i][j][0] = dp[i][j][1] = false;\n            }\n        }\n        dp[0][0][0] = true;\n        for (int i = 0; i < spa.size(); i++) {\n            if (spa[i] != (vector<int>) {PLACEHOLDER}) {\n                for (int j = 0; j + spa[i].size() <= m; j++) {\n                    bool ok = true;\n                    for (int k = 0; k < spa[i].size(); k++) {\n                        if (spa[i][k] != b[j + k]) {\n                            ok = false;\n                            break;\n                        }\n                    }\n                    if (!ok)continue;\n                    for (auto flag: {0, 1}) {\n                        if (dp[i][j][flag]) {\n                            dp[i + 1][j + spa[i].size()][flag] = true;\n                            go[i + 1][j + spa[i].size()][flag] = {j, flag};\n                        }\n                    }\n                }\n                continue;\n            }\n            int jr = 0;\n            bool brandnew = true;\n            int lastgood0 = 0, lastgood1 = 0;\n            for (int j = 0; j < m; j++) {\n                while (jr < m && (jr < j || maxsubsum[j][jr] <= u))jr++;\n                if (dp[i][j][0]) {\n                    for (int jk = max(lastgood0, j); jk < jr; jk++) {\n                        dp[i + 1][jk + 1][0] = true;\n                        go[i + 1][jk + 1][0] = {j, 0};\n                    }\n                    lastgood0 = jr;\n                    if (brandnew) {\n                        brandnew = false;\n                        for (int jk = jr; jk < m; jk++) {\n                            dp[i + 1][jk + 1][1] = true;\n                            go[i + 1][jk + 1][1] = {j, 0};\n                        }\n                    }\n                }\n                if (dp[i][j][1]) {\n                    for (int jk = max(lastgood1, j); jk < jr; jk++) {\n                        dp[i + 1][jk + 1][1] = true;\n                        go[i + 1][jk + 1][1] = {j, 1};\n                    }\n                    lastgood1 = jr;\n                }\n            }\n        }\n        for (auto flag: {0, 1}) {\n            if (dp[spa.size()][m][flag]) {\n                int i = (int) spa.size(), j = m;\n                int idx = 0;\n                for (auto ar: spa)idx += (int) ar.size();\n                pair<int, vector<int>> last_op = {-1, {}};\n                while (i > 0) {\n                    idx -= (int) spa[i - 1].size();\n                    int j2 = go[i][j][flag][0];\n                    int flag2 = go[i][j][flag][1];\n                    if (spa[i - 1] == (vector<int>) {PLACEHOLDER}) {\n                        vector<int> xar;\n                        for (int jk = j2; jk < j; jk++) {\n                            xar.push_back(b[jk]);\n                        }\n                        if (flag == 1 && flag2 == 0) {\n                            last_op = {i - 1, xar};\n                        } else {\n                            ops.push_back({idx + 1, idx + (int) spa[i - 1].size(), xar});\n                            spa[i - 1] = xar;\n                        }\n                    }\n                    i--;\n                    j = j2;\n                    flag = flag2;\n                }\n                if (last_op.first != -1) {\n                    idx = 0;\n                    int ri = last_op.first;\n                    auto xar = last_op.second;\n                    for (int jk = 0; jk < ri; jk++)idx += (int) spa[jk].size();\n                    ops.push_back({idx + 1, idx + (int) spa[ri].size(), xar});\n                }\n                return true;\n            }\n        }\n        return false;\n    };\n \n    for (int j = 0; j < order.size(); j++) {\n        auto [u, i] = order[j];\n        int idx = 0;\n        for (int k = 0; k < i; k++) {\n            idx += (int) spa[k].size();\n        }\n        ops.push_back({idx + 1, idx + (int) spa[i].size(), {PLACEHOLDER}});\n        spa[i] = {PLACEHOLDER};\n        if (j + 1 < order.size() && order[j][0] == order[j + 1][0]) continue;\n        if (check(u)) {\n            cout << ops.size() << '\\n';\n            for (auto [l, r, xar]: ops) {\n                cout << l << ' ' << r << ' ' << xar.size() << '\\n';\n                for (auto el: xar) {\n                    if (el == PLACEHOLDER) el = u;\n                    cout << el << ' ';\n                }\n                cout << '\\n';\n            }\n            return;\n        }\n    }\n    cout << \"-1\\n\";\n}\n \n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2067",
    "index": "A",
    "title": "Adjacent Digit Sums",
    "statement": "You are given two numbers $x, y$. You need to determine if there exists an integer $n$ such that $S(n) = x$, $S(n + 1) = y$.\n\nHere, $S(a)$ denotes the sum of the digits of the number $a$ in the decimal numeral system.",
    "tutorial": "Let's look at the last digit of the number $n$. If it is not equal to $9$, then in the number $n+1$, this last digit will be increased by $1$, while the rest of the number will remain unchanged. Thus, for such $n$, we have $S(n+1) = S(n) + 1$. In general, if the number $n$ ends with $k$ consecutive digits of $9$, then it turns out that $S(n+1) = S(n) + 1 - 9k$, since all these $9$s will be replaced by $0$s after adding one to the number $n$. Therefore, if there does not exist an integer $k \\geq 0$ such that $y = x + 1 - 9k$, then the answer is definitely No. Otherwise, it is easy to see that the answer is definitely Yes. One of the suitable numbers is: $n = \\underbrace{11 \\ldots 1}_{x-9k}\\underbrace{99 \\ldots 9}_{k}$. Then, $S(n) = x - 9k + 9k = x$. And $n + 1 = \\underbrace{11 \\ldots 1}_{x-9k-1}2\\underbrace{00 \\ldots 0}_{k}$. Thus, $S(n+1) = x - 9k - 1 + 2 = x + 1 - 9k$. Therefore, to solve the problem, we need to check whether the number $\\frac{x + 1 - y}{9}$ is an integer and non-negative.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int x, y;\n    cin >> x >> y;\n    if (x + 1 >= y && (x + 1 - y) % 9 == 0) {\n        cout << \"Yes\\n\";\n    } else {\n        cout << \"No\\n\";\n    }\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2067",
    "index": "B",
    "title": "Two Large Bags",
    "statement": "You have two large bags of numbers. Initially, the first bag contains $n$ numbers: $a_1, a_2, \\ldots, a_n$, while the second bag is empty. You are allowed to perform the following operations:\n\n- Choose any number from the first bag and move it to the second bag.\n- Choose a number from the first bag that is also present in the second bag and increase it by one.\n\nYou can perform an unlimited number of operations of both types, in any order. Is it possible to make the contents of the first and second bags identical?",
    "tutorial": "Note that when a number goes into the second bag, it remains unchanged there until the end of the entire process: our operations cannot interact with this number in any way. Therefore, every time we send a number to the second bag, we must keep in mind that an equal number must remain in the first bag by the end of the operations if we want to equalize the contents of the bags. We will call this equal number in the first bag \"blocked\": as no operations should be performed with it anymore. Let's sort the array: $a_1 \\leq a_2 \\leq \\ldots \\leq a_n$. The first action we will take: sending one of the numbers to the second bag, since the second bag is empty at the beginning of the operations, which means the second operation is not available. We will prove that at some point we will definitely want to send a number equal to $a_1$ to the second bag. Proof by contradiction. Suppose we never do this. Then all the numbers in the second bag, at the end of the operations, will be $>a_1$. And the number $a_1$ will remain in the first bag, which cannot be increased if we never sent $a_1$ to the second bag. Thus, the contents of the bags will never be equal if we do not send the number $a_1$ to the second bag. Therefore, during the operations, we must do this. And we can do this as the first operation since operations with numbers $>a_1$ do not interact with $a_1$ in any case. Alright, our first move: transfer $a_1$ to the second bag. Now we need to \"block\" one copy of the number $a_1$ in the first bag and not use it in further operations. Therefore, if $a_2 > a_1$, we instantly lose. Otherwise, we fix $a_2=a_1$ in the first bag and $a_1$ in the second bag. And we return to the original problem, but now with the numbers $a_3, a_4, \\ldots, a_n$. However, now we have the number $=a_1$ in the second bag. This means that now, perhaps, the first action should not be to transfer the minimum to the second bag, but to somehow use the second operation. It turns out that it is always optimal to use the second operation when possible, not counting the \"blocked\" numbers. That is, to increase all equal $a_1$ numbers in the first bag by one. And then proceed to the same problem, but with a reduced $n$. Why is this so? Suppose we leave some equal $a_1$ numbers in the first bag without increasing them. Then, by the same logic, we must transfer one of them to the second bag, blocking the equal number in the first bag. But the same could be done if we increased both numbers by $1$, they would still be equal, and there would still be the option to transfer one of them to the second bag and block the equal one in the first. Moreover, the number equal to $a_1$ is already in the second bag, so adding a second copy does not expand the arsenal of possible operations in any way. Therefore, it is never worse to add one to all remaining $=a_1$ numbers. And proceed to the problem with the array $a_3,a_4,\\ldots,a_n$, where all numbers are $>a_1$, which can already be solved similarly. A naive simulation of this process takes $O(n^2)$, but, of course, it can be handled in $O(n \\log n)$ without much effort, and if we sort the array using counting sort, it can be done in $O(n)$ altogether.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    sort(a.begin(), a.end());\n    int mx = 0;\n    for (int i = 0; i < n; i += 2) {\n        if (max(mx, a[i]) != max(mx, a[i + 1])) {\n            cout << \"No\\n\";\n            return;\n        }\n        mx = max(mx, a[i]) + 1;\n    }\n    cout << \"Yes\\n\";\n}\n \nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2067",
    "index": "C",
    "title": "Devyatkino",
    "statement": "You are given a positive integer $n$. In one operation, you can add to $n$ any positive integer whose decimal representation contains only the digit $9$, possibly repeated several times.\n\nWhat is the minimum number of operations needed to make the number $n$ contain at least one digit $7$ in its decimal representation?\n\nFor example, if $n = 80$, it is sufficient to perform one operation: you can add $99$ to $n$, after the operation $n = 179$, which contains the digit $7$.",
    "tutorial": "The first idea: the answer does not exceed $9$, since we can add $9$ and keep track of the last digit; with each addition, it will decrease by $1$ (going from $0$ to $9$), so after $9$ additions, the last digit will complete a full cycle and will be $7$ exactly once during the process. The second idea: it is quite difficult to briefly answer how adding a number like $99..99$ will affect the digits of an arbitrary number. However, there is an arithmetically similar operation, adding a number of the form $10^x$, which affects the digits in a much more predictable way. It would be nice if we could add powers of ten in the operation instead of $99..99$. The combination of these two ideas solves the problem. Let's iterate through the possible values of the answer. For each $k$ from $0$ to $9$, we want to determine: is it possible to add exactly $k$ numbers made up of nines to produce a digit $7$? One operation is adding a number of the form $10^x - 1$. Since we know we will perform exactly $k$ operations, we can view this process as adding $k$ powers of ten to the number $n-k$. Adding a power of ten increases one of the digits of the number by $1$ (including leading zeros). It may also replace some $9$s with $0$s, which effectively is also an increase of the digit by $1$, modulo $10$. Therefore, it is not difficult to understand that the minimum number of additions of powers of ten needed to introduce a digit $7$ into the number is $\\min((7 - digit) \\bmod 10)$ across all digits $digit$ from the number, including leading zeros. In summary, we need to iterate $k$ from $0$ to $9$ and compare $k$ with $\\min((7 - digit) \\bmod 10)$ (where $digit$ is any digit from the number $n-k$, including leading zeros), and output the minimum suitable $k$. From interesting facts: during the solution process, it becomes clear that the answer is $\\leq 7$, since $digit$ can always be $0$. However, this is only true under the constraints $n \\geq 7$, as in the solution we implicitly rely on the fact that the number $n-k$ does not go negative! For $n=5$ and $n=6$, the answer is actually $8$. Additionally, the solution presented above serves as a proof of another solution that one could believe with sufficient intuition. Let's say that in the optimal answer we add the same number, meaning we never mix adding $9$ and $99$. Believing this, we can iterate through the number being added and keep adding it until we encounter the digit $7$. We then take the minimum of all options for the answer.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    for (int l = 0; l <= 9; l++) {\n        string s = to_string(n - l);\n        int md = 0;\n        for (auto c: s) {\n            if (c <= '7') {\n                md = max(md, c - '0');\n            }\n        }\n        if (l >= 7 - md) {\n            cout << l << '\\n';\n            return;\n        }\n    }\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2068",
    "index": "A",
    "title": "Condorcet Elections",
    "statement": "It is a municipality election year. Even though the leader of the country has not changed for two decades, the elections are always transparent and fair.\n\nThere are $n$ political candidates, numbered from $1$ to $n$, contesting the right to govern. The elections happen using a variation of the \\underline{Ranked Voting System}. In their ballot, each voter will rank all $n$ candidates from most preferable to least preferable. That is, each vote is a permutation of $\\{1, 2, \\ldots, n\\}$, where the first element of the permutation corresponds to the most preferable candidate.\n\nWe say that candidate $a$ defeats candidate $b$ if in more than half of the votes candidate $a$ is more preferable than candidate $b$.\n\nAs the election is fair and transparent, the state television has already decreed a list of $m$ facts—the $i$-th fact being \"candidate $a_i$ has defeated candidate $b_i$\"—all before the actual election!\n\nYou are in charge of the election commission and tallying up the votes. You need to present a list of votes that produces the outcome advertised on television, or to determine that it is not possible. However, you are strongly encouraged to find a solution, or you might upset higher-ups.",
    "tutorial": "This problem is inspired by Condorcet's paradox. To put it simply, Condorcet's paradox states that for certain voters preferences, it's impossible to always resolve the elections fairly. No matter the outcome, more than half of the voters would prefer to change the result to some other outcome. This is illustrated by the second example in the statement. The problem's answer is always YES. It's possible to construct a list of votes such that any (not trivially contradicting) list of statements \"candidate $x_i$ has defeated candidate $y_i$\" can be satisfied. Let $S = \\{(a, b) \\mid 1 \\leq a, b \\leq n, \\, a \\ne b\\}$, and let $R \\subseteq S$ be the list of requirements. Let $\\delta_{a,b}(\\text{ans})$, where $(a, b) \\in S$ and \"$\\text{ans}$\" is our answer, be how many votes prefer $a$ to $b$ minus how many votes prefer $b$ to $a$. We want to ensure that $\\delta_{a,b}(\\text{ans}) > 0$ for every $(a, b) \\in R$. For every $(a, b) \\in S$, it's actually possible to construct votes $\\pi_1$, $\\pi_2$, such that: $\\delta_{a,b}(\\{\\pi_1, \\pi_2\\}) = 2$. $\\delta_{x,y}(\\{\\pi_1, \\pi_2\\}) = 0$ for all $(x, y) \\in S$, $\\{x, y\\} \\ne \\{a, b\\}$. Then clearly adding $\\pi_1$, $\\pi_2$ for every $(a, b) \\in R$ results in a correct answer. Thus, the jury solution uses at most $2 {n \\choose 2} \\le n^2$ votes. Let us construct $\\pi_1$, $\\pi_2$. For the sake of exposition, let us assume $a = 1$, $b = 2$. Observe that the $\\pi_1$, $\\pi_2$ given below satisfy the requirements. Votes $\\pi$ for any $(a, b) \\ne (1, 2)$ can be constructed by the re-numeration. $\\pi_1 = (1, 2, 3, 4, \\ldots, n - 1, n)$ $\\pi_2 = (n, n - 1, \\ldots, 4, 3, 1, 2)$",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "probabilities"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2068",
    "index": "B",
    "title": "Urban Planning",
    "statement": "You are responsible for planning a new city! The city will be represented by a rectangular grid, where each cell is either a park or a built-up area.\n\nThe residents will naturally want to go for walks in the city parks. In particular, a \\underline{rectangular walk} is a rectangle consisting of the grid cells, which is at least 2 cells long both horizontally and vertically, such that all cells on the boundary of the rectangle are parks. Note that the cells inside the rectangle can be arbitrary.\n\n\\begin{center}\nAn example rectangular walk (cells with dark background).\n\\end{center}\n\nYour favourite number is $k$. To leave a long-lasting signature, you want to design the city in such a way that it has exactly $k$ rectangular walks.",
    "tutorial": "Solutions that do not work First of all, let us consider a square with side $n$, consisting only of parks. It has $\\left(\\frac{n(n-1)}{2}\\right)^2$ rectangular walks, since there are $\\frac{n(n-1)}{2}$ ways to choose the top and bottom rows, and $\\frac{n(n-1)}{2}$ ways to choose the left and right columns. We will denote this number of rectangular walks in a square park as $f(n)$. Now the logical idea would be to find the largest $f(n)$ that does not exceed $k$, create a park with side $n$, and then try to create additional independent parks using the remaining space on the grid to achieve $k-f(n)$ rectangular walks there. When $k=4\\cdot10^{12}$, we would choose $n=2000$, get $f(2000)=3\\,996\\,001\\,000\\,000$ walks that way, and then we would need to squeeze the remaining $3\\,999\\,000\\,000$ walks into the rest of the 2025 times 2025 grid, which looks like two overlapping 24 times 2025 rectangles after we cut out the 2000 times 2000 rectangle plus adjacent cells to make sure the additional parks do not interact with the big one. However, a 24 times 2025 rectangle has only $565\\,606\\,800$ rectangular walks, so even with two of those we have no chance to reach the required number. Therefore the idea to have a completely independent large square park is too crude, and we need to improve it. Instead of stopping at $f(n)$, let us add more park cells one by one to go from a square with side $n$ to a square with side $n+1$, first completing column $n+1$ from top to bottom, then completing row $n+1$ from left to right. For each newly added park cell, the number of rectangular walks will increase by at most $n^2$. This way we can find an incomplete square with $x$ rectangular walks such that $k-x < n^2$, so we will only need to squeeze less than $n^2$ additional walks in the remaining space. In practical terms, when $k \\le 4\\cdot10^{12}$, at the first step we will get a (partial) square with side at most 2001, and have at most $3\\,999\\,999$ remaining walks, then at the second step we will get a square with side at most 64, at the third step at most 12, then at most 6, then at most 4, then at most 3, at which moment we would have at most 3 remaining walks, which we can address by at most 3 squares with side 2. It is still impossible to put a square of side 2001 and a square of side 64 without overlapping into a grid with side 2025, but now it is clear that we have enough area in our grid for this, and it is only the shape that is the problem. Therefore we should use rectangles instead of squares. Solution that works for $k \\le 4\\cdot 10^{12}$ In the onsite version of the contest, the constraint was $k \\le 4\\cdot 10^{12}$, for which the following approach works. Let us start with a rectangle with height 1 and width 2025, and add a second row to it cell by cell from left to right, then the third row, and so on until we would have exceeded $k$ rectangular walks. After this, let us skip one row and start a new rectangle with width 2025 in the same fashion for the remaining walks, and so on until we reach exactly $k$. This way the first (partial) rectangle will be at most 1977 times 2025, the second at most 3 times 2025, and then at most six more 2 times 2025 ones, which fits into our grid even with the additional empty rows between them, so this is a working solution. Solution that works for $k \\le 4.194\\cdot 10^{12}$ In the online mirror of the contest, this problem had a higher constraint: $k \\le 4.194\\cdot 10^{12}$. Note that $f(2024) \\approx 4.191\\cdot 10^{12}$ and $f(2025) \\approx 4.2\\cdot 10^{12}$, meaning that we need a grid almost full of parks to achieve such high values of $k$, and we cannot afford to have several connected components. First, we do the same as above: let us find a partial rectangle that has almost $k$ rectangular walks. Additionally, we will force the partial rectangle to have $n$ rows and $n+1$ columns for some value of $n$, and we force the removed cells (which make the rectangle partial) to all be in one corner. In other words, we start with a full $n$ times $n+1$ rectangle, and then remove cells in the following order: first $(0, 0)$, then $(0, 1)$, then $(1, 0)$, then $(1, 1)$, then the cells with coordinates $\\le 2$, and so on until the number of rectangular walks becomes $\\le k$. Since removing each particular cell reduces the number of rectangular walks by at most $n(n-1)$, we will be able to find a partial rectangle with such number of rectangular walks $x$ that $0\\le k-x<n(n-1)$. However, for reasons that will become apparent soon, let us remove a few more cells to achieve $n(n-1)\\le k-x<2n(n-1)$. Since $f(n+1)-f(n)=O(n^3)$, and removing a cell reduces the number of rectangular walks by $\\Omega(n^2)$, we will only remove $O(n)$ cells from the full rectangle to achieve this. And because of the order in which we remove the cells, all removed cells will be concentrated in a $O(\\sqrt{n})$ times $O(\\sqrt{n})$ corner of the rectangle, which means that we will still have $n-O(\\sqrt{n})$ completely untouched rows (with $n+1$ cells each) and $n-O(\\sqrt{n})$ completely untouched columns (with $n$ cells each). Now we will add the remaining $k-x$ rectangular walks by adding cells to the right of the untouched rows (in column $n+2$) and to the bottom of the untouched columns (in row $n+1$), so the entire city will fit inside the $n+1$ times $n+2$ grid. If we add $y$ consecutive cells to the right of the untouched rows, this will add $\\frac{y(y-1)}{2}(n+1)$ rectangular walks, and adding $y$ consecutive cells to the bottom of the untouched columns will add $\\frac{y(y-1)}{2}n$ rectangular walks. Now, remember that every number $z\\ge n(n-1)$ can be represented as $pn+q(n+1)$ for some non-negative $p$ and $q$. Since $k-x\\ge n(n-1)$, we can find such non-negative $p$ and $q$ that $k-x=pn+q(n+1)$. And now we just need to represent $p$ and $q$ as the sum of values of the form $\\frac{y(y-1)}{2}$, and for each such value add a corresponding segment of $y$ extra cells to the right or to the bottom. To represent a given number $p$ as a sum of values of the form $\\frac{y(y-1)}{2}$ is a knapsack problem that we will solve greedily: take the largest value of the form $\\frac{y(y-1)}{2}$ that does not exceed $p$, and repeat for the remainder. Now since $k-x<2n(n-1)$, both $p$ and $q$ will be $O(n)$, so the first value of $y$ we will get will be $O(\\sqrt{n})$, the second will be $O(\\sqrt[4]{n})$, and so on, so the output of the greedy knapsack will fit in the $n-O(\\sqrt{n})$ untouched rows/columns. This solution does not always work for very small values of $k$, since we need a big enough $n$ for the constant factors hidden in $O()$ notation above to not matter. For those values of $k$ we can either use the solution above for the smaller constraints, or implement a very simple solution for very small constraints. For example, when $k \\le \\lfloor\\frac{2025}{3}\\rfloor^2$, we can just output a grid of separate $2 \\times 2$ squares with empty rows and columns between them. Also, since the resulting grid has $n+2$ columns, it means that we must have $n \\le 2023$, so for the values of $k$ that exceed the total number of rectangular walks in the 2023 times 2024 rectangle it will no longer be true that $k-x<2n(n-1)$. However, one can more carefully examine how much space does the greedy knapsack above need, and find that it can still fit inside the $n-O(\\sqrt{n})$ untouched rows/columns at least for $k \\le 4.1948\\cdot 10^{12}$, which is enough to solve this problem. Remarks There are of course very many approaches that work in this problem; the above solutions are just one possibility. The judges also had a solution that could get even closer to $f(2025)$, approximately to $k\\le \\frac{1}{3}f(2024) + \\frac{2}{3}f(2025)$. However, we felt that the $k \\le 4.194\\cdot 10^{12}$ constraint is similarly challenging, and did not want to restrict the possible approaches too much. The fact that we are counting hollow rectangular walks instead of rectangles that also have only parks inside them did not actually affect the above solutions. We made them hollow so that counting rectangles takes $O(n^2\\log n)$ instead of $O(n^2)$, so hopefully simple hill-climbing solutions were less likely to work.",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2068",
    "index": "C",
    "title": "Ads",
    "statement": "You have $n$ videos on your watchlist on the popular platform YooCube. The $i$-th video lasts $d_i$ minutes.\n\nYooCube has recently increased the frequency of their ads. Ads are shown only between videos. After finishing a video, an ad is shown if either of these two conditions is true:\n\n- three videos have been watched since the last ad;\n- at least $k$ minutes have passed since the end of the last ad.\n\nYou want to watch the $n$ videos in your watchlist. Given that you have just watched an ad, and that you can choose the order of the $n$ videos, what is the minimum number of ads that you are forced to watch? You can start a new video immediately after the previous video or ad ends, and you don't have to watch any ad after you finish.",
    "tutorial": "The result is equal to $g-1$ where $g$ is the number of groups of videos. Therefore, you want to minimize the number of groups and you can do this by creating large groups: first of size 3, then of size 2 and of size 1 with whatever is left. To create groups of size 3, we will pick the shortest video ($m$) as the first element of the group, the longest video ($M$) as the last and for the middle one we choose the longest video of length $x$ such that $m+x<k$. For groups of size 2, we pair the shortest video that is shorter than $k$ with the longest video. We can simulate this greedy process with a tree data structure (e.g. multiset in C++) to solve the problem in $O(n \\log n)$. Let's prove that this greedy approach gives us an optimal solution. We can consider a version of the problem where we can choose to watch an ad early if we wish. The optimal solution will be equivalent to the original problem with forced ads. This is because we can move an ad (that we watched early) forward as much as possible and the number of groups in the following videos can't be larger by induction on the number of viewed ads. If the optimal solution contains a group of size 2 or 3, there is a solution that contains the shortest and longest video in the same group. If there wasn't, we can swap the longest video overall with the last video in the group of the shortest one (without affecting the number of groups). If it's possible to create a group of size 3, there exists an optimal solution with such group. Indeed, suppose there is an optimal solution without such group. Clearly all groups can't be of size 1 in an optimal solution so there must be at least one group of size 2. We know there is a solution with a group of size 2 containing the shortest and longest video. If it's possible to insert a third video, the solution can't degrade. If it's possible to construct a group of size 3, it can consist of the shortest ($m$) and longest ($M$) video in the first and last place, respectively. For the second video we can greedily choose the longest available video $x$ such that $m+x<k$ to avoid triggering an early ad. We can prove that a greedy choice is valid with a similar swap argument as before. If it's not possible to construct groups of size 3, and it's possible to create a group of size 2, then there exists an optimal solution with at least a group of size 2. Otherwise, we would have only groups of size 1 and merging two directly decreases the number of groups. If it's not possible to construct groups of size 3, and it's possible to construct a group of size 2, then there exists an optimal solution where the shortest video is paired with the longest video. This can again be proved with a swap argument.",
    "tags": [
      "binary search",
      "greedy",
      "two pointers"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2068",
    "index": "D",
    "title": "Morse Code",
    "statement": "Morse code is a classical way to communicate over long distances, but there are some drawbacks that increase the transmission time of long messages.\n\nIn Morse code, each character in the alphabet is assigned a sequence of dots and dashes such that \\textbf{no sequence is a prefix of another}. To transmit a string of characters, the sequences corresponding to each character are sent in order. \\textbf{A dash takes twice as long to transmit as a dot.}\n\nYour alphabet has $n$ characters, where the $i$-th character appears with frequency $f_i$ in your language. Your task is to design a Morse code encoding scheme, assigning a sequence of dots and dashes to each character, that minimizes the expected transmission time for a single character. In other words, you want to minimize $f_1t_1 + f_2t_2 + \\cdots + f_nt_n$, where $t_i$ is the time required to transmit the sequence of dots and dashes assigned to the $i$-th character.",
    "tutorial": "Any assignment of Morse codes to characters can be represented with a binary tree, where going to a left child appends a dot and going to a right child appends a dash. We then associate each character with a leaf in the tree. This ensures that the codes will not be prefixes of each other. Each vertex, both leafs and internal vertices, has a depth in the tree. For this depth to correspond to the length of the associated Morse code, we declare that going to a right child increases the depth by two. Once we know what an optimal binary tree looks like, we can greedily match the characters to the leafs by assigning the most frequent characters to the leafs with the smallest depth. The key observation is that we initially do not need to know what exactly the tree looks like. We only need to know how many leafs and internal vertices exist at each depth. This allows us to use dynamic programming (DP) to determine an optimal tree bottom up. In each state, we keep track of: $v_c$, the number of vertices at the current depth level, where we can still decide whether they become leafs or internal vertices. $v_n$, the number of vertices at the next (deeper) depth level, where we can still decide whether they become leafs or internal vertices. $a$, the number of characters that have already been assigned a value The base state is $DP[0,0,0] = 0$, since transmitting nothing costs nothing. The value we want to know is $DP[1,0,n]$, the cost to transmit all characters from depth zero where we only have a root vertex. The transition function is a minimum of two values. To determine $DP[v_c,v_n,a]$, we can either make a vertex a leaf and assign a character to it, or we can determine that we do not want anymore leafs at this depth by splitting all remaining vertices into two new vertices and going to the next depth. In the first case, this results in the value $DP[v_c-1,v_n,a-1]$ with no additional costs. In the second case, this results in the value $DP[v_n+v_c,v_c,a]$ plus the sum of the frequencies of the least frequent $a$ characters; the cost is caused by the fact that these characters are now placed one level deeper. Finally, there are some boundary conditions where we assign the value infinity. If $v_c = v_n = 0$ and $a > 0$ the state is unsolvable since there are some unassigned characters left but no more leafs can be created. If $v_c + v_n > a$ then the state is trivially suboptimal since we will then obtain more leafs then needed. After completing the DP, the final step is to actually construct an optimal tree. This can be done greedily by keeping track of two vectors of partial codes (one for the current depth, one for the next one) and backtracking through the DP. Each parameter in the state description is bounded by $n$ and the transition function is constant, so overall this results in an $O(n^3)$ algorithm.",
    "tags": [
      "dp",
      "sortings",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2068",
    "index": "E",
    "title": "Porto Vs. Benfica",
    "statement": "FC Porto and SL Benfica are the two largest football teams in Portugal. Naturally, when the two play each other, a lot of people travel from all over the country to watch the game. This includes the Benfica supporters' club, which is going to travel from Lisbon to Porto to watch the upcoming game. To avoid tensions between them and the Porto supporters' club, the national police want to delay their arrival to Porto as much as they can.\n\nThe road network in Portugal can be modelled as a simple, undirected, unweighted, connected graph with $n$ vertices and $m$ edges, where vertices represent towns and edges represent roads. Vertex $1$ corresponds to Lisbon, i.e., the starting vertex of the supporters' club, and vertex $n$ is Porto, i.e., the destination vertex of the supporters' club. The supporters' club wants to minimize the number of roads they take to reach Porto.\n\nThe police are following the supporters' club carefully, and so they always know where they are. To delay their arrival, at any point the police can pick exactly one road and block it, as long as the supporters' club isn't currently traversing it. They can do this exactly once, and once they do that, the road is blocked forever. Once the police block a road, the supporters' club immediately learns that that road is blocked, and they can change their route however they prefer. Furthermore, the supporters' club knows that the police are planning on blocking some road and can plan their route accordingly.\n\nAssuming that both the supporters' club and the police always make optimal choices, determine the minimum number of roads the supporters' club needs to traverse to go from Lisbon to Porto. If the police can block the supporters' club from ever reaching Porto, then output $-1$.",
    "tutorial": "We start by making a few definitions that will help us: Definition. Denote by $f(v)$ the minimum number of roads the supporters' club needs to travel if they start from vertex $v$ and want to end up at vertex $n$, and the police can still block exactly one road. So $f(1)$ is the answer to the problem and $f(n) = 0$. Definition. Denote by $g(v, \\, e)$ the shortest path from $v$ to vertex $n$ that doesn't use edge $e$ and $g(v)$ as the maximum of $g(v, \\, e)$ for all edges $e$ adjacent to $v$. In other words, $g(v)$ is the shortest path from $v$ to $n$ that doesn't use the edge that leads to the shortest path from $v$ to $n$. Now we have the following: Lemma. $f(v) = \\max\\{g(v), \\, 1 + \\min_{v \\sim u} f(u)\\}$, where $v \\sim u$ denotes that the two vertices are adjacent. Proof. It's easy to see that the police only block an edge when the supporters' club is on a vertex adjacent to that edge; otherwise, they could have waited until they were adjacent to that edge to block it. So, when the supporters' club is at some vertex $v$, the police have two choices (and they want to pick the one that maximizes the number of traversed roads): either block some edge adjacent to $v$, or not block any edge and let the supporters' club decide where to go. If they decide to block road $e$, then the supporters' club takes $g(v, \\, e)$ roads to reach $n$, so the police might as well pick $g(v)$ to maximize this. If they decide not to block a road, the number of roads is $1$ plus $f(u)$, where $u$ is the vertex the supporters' club ends up at. Since they want to minimize the number of roads taken, they best pick $u$ that minimizes $f(u)$. Note that the values of $g$ can easily be found in $O(m^2)$ time, by running a BFS per vertex $v$. This is too slow to solve this problem, so we will see later how to compute $g$ more efficiently, which is the trickiest part. But first, let's see how to find efficiently the values of $f$ assuming we have already computed $g$. Computing $f$ assuming we know $g$ To find $f$, we can use a greedy algorithm that works exactly the same way as Dijkstra's algorithm. Consider an array $\\texttt{f}[]$ that we will use to store the values of $f$. Set $\\texttt{f}[n] = 0$ and $\\texttt{f}[v] = g(v)$ for all other $v$. Now process each vertex in the following way. Pick the unprocessed vertex $v$ with the lowest current value of $\\texttt{f}[v]$. Process $v$ by iterating through all vertices $u$ adjacent to $v$ and setting $\\texttt{f}[v] = \\max(g[v], \\, \\min(1 + \\texttt{f}[u]))$. Intuitively, this processing step amounts to applying the formula of $f$ present in the lemma above, but considering only one pair of adjacent vertices at a time. To efficiently pick the unprocessed vertex $v$ with the lowest current value of $\\texttt{}f[v]$, we can use a min-heap ordered by $\\texttt{f}[v]$, which needs to be updated accordingly. This algorithm runs in $O(m \\log n)$ time, since we process each vertex once and for each vertex we look at its neighbors and potentially update the elements in a heap containing at most $n$ elements. Lemma. After running the algorithm above, $\\texttt{f}[v] = f(v)$. Proof. The correctness of this algorithm follows from an argument very similar to the correctness of Dijkstra's algorithm. The key observation is that if $v$ is an unprocessed vertex with the lowest current value of $\\texttt{f}[v]$, then at this point we have that $\\texttt{f}[v] = \\max(g(v), \\, 1 + \\min(f(u)))$, where the minimum is over all $u$ that have been previously processed. Since $v$ has the lowest current value of $\\texttt{f}[v]$, none of the remaining unprocessed vertices could increase the value of $\\texttt{f}[v]$, which means that the current value of $\\texttt{f}[v]$ is exactly $f(v)$. Computing $g$ Let's start with two quick definitions. Definition. Denote by $\\text{dist}(v, \\, u)$ the distance between vertices $v$ and $u$ in the road network graph. Definition. Let $b(v)$ be any neighbor of $v$ such that $\\text{dist}(v, \\, n) = 1 + \\text{dist}(b(v), \\, n)$, and break ties arbitrarily. So, we can think of $g(v)$ as the distance from $v$ to $n$ that doesn't use the edge $\\{v, \\, b(v)\\}$. Consider the BFS tree from $n$, which is the same as saying the tree consisting of the edges given by $\\{v, \\, b(v)\\}$ for all $v \\neq n$, and root the tree on $n$. Observe that the path that corresponds to $g(v)$ has to necessarily be a path that uses at least one non-tree edge (otherwise it would be a path that uses $\\{v, \\, b(v)\\}$, which is invalid). Furthermore, such a path will look like the following: start at $v$, go down the subtree rooted on $v$ some number of steps (potentially $0$), take one non-tree edge that ends in a vertex that isn't in the subtree rooted at $v$ and then take the shortest path from that vertex to $n$. Note that we can easily precompute the shortest path from any vertex to $n$ by running a single BFS from $n$. To prove the above, note that once we are outside of the subtree rooted at $v$ we are free to take the shortest path to $n$ since it won't use the $\\{v, \\, b(v)\\}$ edge. Additionally, note that we don't want to ever take a non-tree edge to end up at another vertex in the subtree of $v$, since we can always take the tree path and that will always be at most as short (by definition of BFS tree). So we are left with computing for each $v$ the shortest among all paths that take some number of steps down the tree, then takes some non-tree edge, and then takes the shortest path to $n$. Let's first see an inefficient way of doing to, and then we'll make it efficient. For each vertex $v$, compute a list of all the paths of the desired form, and store this in a set (so each vertex gets a set). In particular, we store pairs of two things in this set: the distance to $n$ of the corresponding path, the endpoint of the non-tree edge we are taking. We can do so recursively (in a DFS fashion), so let's start by considering the leaves of the tree. If $v$ is a leaf, then the path can't go down the tree, so it is of the form \"take some non-tree edge and then take the shortest path to $n$\". For each non-tree edge $\\{v, \\, u\\}$, add the pair $(1 + \\text{dist}(u), \\, u)$ to the set. So now we know that $g(v)$ is the minimum element in the set. If $v$ isn't a leaf, first recursively compute the distances of all of the children of $v$. Initialize the set corresponding to $v$ by going through each non-tree edge $\\{v, \\, u\\}$, and adding the pair $(1 + \\text{dist}(u), \\, u)$. Now \"merge\" this set with all the sets of all of $v$'s children. To merge two sets, we take all pairs $(d, \\, u)$ of the children sets and add $(d + 1, \\, u)$ to $v$'s set, which corresponds to extending each path from each of the children by taking the edge from $v$ to them. Suppose the minimum element is $(d, \\, u)$. Then $u$ could be in the subtree rooted at $v$, which is an invalid path. If that's the case, we delete $(d, \\, u)$ from the set and keep deleting the top element until we find one which isn't in the subtree of $v$. Note that this doesn't affect the computation of ancestors of $v$ since $u$ would be in their subtree too. To determine whether $u$ is in the subtree of $v$ we can use DSU (Disjoint Set Union). Initially, all vertices are their own set, and as we go down the tree we merge $v$ with its children. Like before, now we know that $g(v)$ is the minimum element in the remaining set. We are almost done, but there is one inefficient step here: merging the sets of the children of $v$ could take $O(n)$ time since each set could have up to $n$ elements. To implement this step efficiently, we can do \"small-to-large merging\", just like the union by size merge in a DSU data structure. When merging two sets, don't touch the largest of the two, and copy the elements of the smallest one into the largest one. However, recall that when merging two sets, we take all pairs $(d, \\, u)$ of the children sets and add $(d + 1, \\, u)$ to $v$'s set, so we need to potentially alter the elements in the largest set if this is one of the children's sets. We can do this by assuming that each set comes with a \"modifier\", which is an integer $m$ such that if we have an element $(d, \\, u)$ in the set, the real distance is $d + m$. Intuitively, this modifier acts as a \"lazy propagator\", so that we don't have to actually change the elements in the children's sets. When we take a set from a child, we first increment its modifier, and then merge its set with $v$'s set. The total running time of this step is $O(n \\log^2 m)$, since the small-to-large merge makes sure we only move an element between sets $O(\\log m)$ times, and each move costs $O(\\log m)$.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dsu",
      "graphs",
      "shortest paths"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2068",
    "index": "F",
    "title": "Mascot Naming",
    "statement": "When organizing a big event, organizers often handle side tasks outside their expertise. For example, the chief judge of EUC 2025 must find a name for the event's official mascot while satisfying certain constraints:\n\n- The name must include specific words as subsequences$^{*}$, such as the event name and location. You are given the list $s_1,\\, s_2,\\, \\ldots,\\, s_n$ of the $n$ required words.\n- The name must not contain as a subsequence$^{*}$ the name $t$ of last year's mascot.\n\nPlease help the chief judge find a valid mascot name or determine that none exists.$^{*}$ A string $x$ is a \\underline{subsequence} of a string $y$ if $x$ can be obtained from $y$ by erasing some characters (at any positions) while keeping the remaining characters in the same order. For example, $abc$ is a subsequence of $axbycz$ but not of $acbxyz$.",
    "tutorial": "This problem requires constructing a string that contains each of the given strings $s_1, s_2, \\dots, s_n$ as subsequences but does not contain $t$ as a subsequence. Key Observation. If $t$ is a subsequence of any $s_i$, then any string containing $s_i$ as a subsequence must also contain $t$. In this case, the answer is $\\texttt{NO}$. Otherwise, we can construct a valid string using a greedy approach. Checking for Subsequences. Before solving the main problem, we describe a simple method to check if a string $b$ is a subsequence of another string $a$. We iterate through $a$, trying to match its characters to $b$ in order: If the first characters of $a$ and $b$ match, remove the first character from both. Otherwise, remove only the first character from $a$. Repeat until $a$ is empty. If $b$ becomes empty, it was a subsequence of $a$; otherwise, it was not. Constructing the Answer. We build the answer string $\\mathrm{ans}$ by appending characters one by one. Initially, $\\mathrm{ans}$ is empty. We repeat the following steps until all $s_i$ are empty: If there exists a character $c$ such that at least one $s_i$ starts with $c$ and $t$ does not start with $c$, append $c$ to $\\mathrm{ans}$ and remove the first character from all $s_i$ that start with $c$. Otherwise, all $s_i$ start with the same character as $t$. Append this character to $\\mathrm{ans}$ and remove the first character from all $s_i$ and $t$. At the end of this process, $\\mathrm{ans}$ contains all $s_i$ as subsequences. Let us understand why $t$ is not a subsequence of $\\mathrm{ans}$. Let $s_i$ be the last string to become empty during the process. Consider the steps taken for $s_i$ and $t$ alone. The sequence of character deletions mirrors the subsequence checking algorithm. Since $t$ is not a subsequence of $s_i$, it remains non-empty at the end, ensuring that $t$ is not a subsequence of $\\mathrm{ans}$ either. Thus, if $t$ is not a subsequence of any $s_i$, the algorithm constructs a valid $\\mathrm{ans}$, and the answer is $\\texttt{YES}$. The solution described is linear in the total length of all strings given in input.",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2068",
    "index": "G",
    "title": "A Very Long Hike",
    "statement": "You are planning a hike in the Peneda-Gerês National Park in the north of Portugal. The park takes its name from two of its highest peaks: Peneda (1340 m) and Gerês (1545 m).\n\nFor this problem, the park is modelled as an infinite plane, where each position $(x, y)$, with $x, y$ being integers, has a specific altitude. The altitudes are defined by an $n \\times n$ matrix $h$, which repeats periodically across the plane. Specifically, for any integers $a, b$ and $0 \\leq x, y < n$, the altitude at $(x + an, y + bn)$ is $h[x][y]$.\n\nWhen you are at position $(x, y)$, you can move to any of the four adjacent positions: $(x, y+1)$, $(x+1, y)$, $(x, y-1)$, or $(x-1, y)$. The time required to move between two adjacent positions is $1 + \\lvert \\text{alt}_1 - \\text{alt}_2 \\rvert$, where $\\text{alt}_1$ and $\\text{alt}_2$ are the altitudes of the current and destination positions, respectively.\n\nInitially, your position is $(0, 0)$. Compute the number of distinct positions you can reach within $10^{20}$ seconds. Your answer will be considered correct if its relative error is less than $10^{-6}$.",
    "tutorial": "Before diving into the solution, let us make a few key observations to build intuition for tackling the problem. Our goal is to count the number of distinct cells that can be reached within a time limit of $10^{20}$. To gain insight into this, consider first the simpler question: given a distant cell $(x, y)$ (where $x, y$ are large), how can we estimate the shortest time required to reach it from the origin? Since we do not need an exact answer but only a sufficiently precise approximation, we can reframe the previous question: how can we efficiently approximate the distance from the origin to $(x, y)$? Consider any path from $(0,0)$ to $(x, y)$. If this path visits the same position modulo $n$ at both the $i$-th and $j$-th steps, then removing the portion of the path between these two steps does not change the total cost of the remaining path. The last observation is particularly powerful and will be crucial in approximating distances efficiently. We will leverage it to resolve the subproblem identified in the first two observations. Afterward, we will use this approximation to count (approximately) the number of reachable cells within the given time constraint. Finally, we will describe how to translate these results into an algorithm with time complexity $O(n^5)$. It is worth noting that this editorial is relatively long because we rigorously prove that our approximations maintain a relative error smaller than $10^{-6}$. However, in practice, we expect that any reasonable implementation with sufficient numerical precision will be far more accurate than required. As such, contestants do not need to be overly concerned about precision. Lastly, many of the statements we prove here are significantly easier to intuit than to rigorously justify. We recommend that readers focus on understanding the core ideas on their first read and not get too caught up in the technical details. If you grasp the reasoning behind Lemma 5 and Lemma 6, you should already have the essential insights needed to solve the problem. Approximating the distance Let us denote by $D := 1545+1$ the maximum distance between two adjacent cells (i.e., the maximum altitude difference plus one). For any integers $i, j$ with $|i|+|j| \\le n$, let $t$ be the minimum number such that, for some $(a, b)$, the distance from $(a, b)$ to $(a+in, b+jn)$ is $t$. Define $T(i, j):=t/n$. This captures the idea that moving by $(i, j)$ costs $T(i, j)$. For any $x, y$, we define $f(x, y)$ as the infimum of $\\sum_{|i|+|j|\\le n} \\lambda_{ij}T(i, j)$, for any nonnegative real numbers $\\lambda_{ij}\\ge 0$, under the constraint that $\\sum_{|i|+|j| \\le n}\\lambda_{ij}(i, j) = (x, y)$. Observe that $|x|+|y|\\le f(x, y)\\le D(|x|+|y|)$. Lemma 1. For any cell $(x, y)$ such that both coordinates are divisible by $n$, we have $\\text{dist}((0, 0), (x, y)) \\ge f(x, y).$ Proof. We show it by induction on the distance from $(0, 0)$ to $(x, y)$. Consider a shortest path from $(0, 0)$ to $(x, y)$. Since $(0, 0)\\equiv(x, y) \\pmod{n}$, we can consider the two closest cells $(x_1, y_1)$ and $(x_2, y_2)$ along the path such that $(x_1, y_1)\\equiv(x_2, y_2) \\pmod{n}$. Let $(x', y') = (x_2-x_1, y_2-y_1)$. By construction, the segment of the path from $(x_1, y_1)$ to $(x_2, y_2)$ contains no two positions (besides the endpoints) that are congruent modulo $n$, so it must have at most $n^2$ steps. Thus, we obtain $|x'|+|y'|\\le n^2$. Using our third key observation from the introduction, we deduce that $\\text{dist}((0, 0), (x, y)) = \\text{dist}((x_1, y_1), (x_2, y_2)) + \\text{dist}((0, 0), (x-x', y-y')).$ $\\text{dist}((x_1, y_1), (x_2, y_2)) \\ge n T(x'/n, y'/n).$ $\\text{dist}((0, 0), (x-x', y-y')) \\ge f(x-x', y-y') .$ $\\text{dist}((0, 0), (x, y)) \\ge n T(x'/n, y'/n) + f(x-x', y-y') \\ge f(x, y).$ Lemma 2. For any cell $(x, y)$, we have $\\text{dist}((0, 0), (x, y)) \\ge f(x, y) - 2Dn.$ Proof. Let $(\\bar x, \\bar y)$ be a cell such that its coordinates are divisible by $n$ and the Manhattan distance from $(x, y)$ to $(\\bar x, \\bar y)$ is $\\le n$. We have $\\text{dist}((0, 0), (x, y)) \\ge \\text{dist}((0, 0), (\\bar x, \\bar y)) - \\text{dist}((\\bar x, \\bar y), (x, y)) \\ge f(\\bar x, \\bar y) - Dn .$ $f(x, y) \\le f(\\bar x, \\bar y) + f(x-\\bar x, y-\\bar y) \\le f(\\bar x, \\bar y) + T(x-\\bar x, y-\\bar y) \\le f(\\bar x, \\bar y) + Dn .$ $\\text{dist}((0, 0), (x, y)) \\ge f(x, y) - 2Dn.$ We have shown that $f$ provides a lower bound for the distance of $(x, y)$ to the origin. Now we turn to proving that it provides an upper bound. Lemma 3. Fix a nonnegative integer $k\\ge 0$ and two integers $i, j$ with $|i|+|j|\\le n$. For any cell $(x, y)$, we have $\\text{dist}((x, y), (x, y) + k(in, jn)) \\le kn T(i, j) + 2Dn.$ Proof. Without loss of generality, we may assume that $(x, y) = (0, 0)$. By definition of $T(i, j)$, there exists $(a, b)$ such that $\\text{dist}((a, b), (a, b) + (in, jn))=T(i, j)$. Without loss of generality, we may assume that $|a|+|b|\\le n$. Consider the path that goes from $(0, 0)$ to $(a, b)$, then to $(a, b) + k(in, jn)$ repeating $k$ times the path that defines $T(i, j)$, and finally from $(a, b)+k(in, jn)$ to $k(in, jn)$. The total length of this path is at most $Dn + kn T(i, j) + Dn$ as desired. Now that we have seen in which cases $T$ provides an upper bound, we deduce how $f$ always provides an upper bound. One can show (it follows from the argument in the next section of this editorial) that the value of $f$ does not change if we require that at most two values of $\\lambda_{ij}$ are nonzero. Lemma 4. For any cell $(x, y)$, we have $\\text{dist}((0, 0), (x, y)) \\le f(x, y) + 2Dn(n+1).$ Proof. Let $(x, y) = a(i, j) + a'(i', j')$ so that $a,a'\\ge 0$ and $f(x, y) = aT(i, j) + a'T(i', j')$. Consider the cell $(\\bar x, \\bar y) := \\big\\lfloor a/n \\big\\rfloor (in, jn) + \\big\\lfloor a'/n \\big\\rfloor (i'n, j'n).$ $\\text{dist}((0, 0), (\\bar x, \\bar y)) \\le \\big\\lfloor a/n \\big\\rfloor n T(i, j) + \\big\\lfloor a'/n \\big\\rfloor n T(i', j') \\le f(x, y) + 2Dn.$ $\\text{dist}((0, 0), (x, y)) \\le \\text{dist}((0, 0), (\\bar x, \\bar y)) + \\text{dist}((\\bar x, \\bar y), (x, y)) \\le f(x, y) + 2Dn + 2n^2D.$ The results of this section can be summarized in the following statement. Lemma 5. For any cell $(x, y)$, we have $f(x, y) - 2Dn \\le \\text{dist}((0, 0), (x, y)) \\le f(x, y) + 2Dn(n+1) .$ Counting the cells with distance $\\le R$ Let $R=10^{20}$. Our goal is to count the number of cells $(x, y)$ with $\\text{dist}((0, 0), (x, y))\\le R$. Let $q(r)$ be the number of cells $(x, y)$ with $f(x, y)\\le r$. In view of Lemma 5, we have (setting $R_1 := R-2Dn(n+1)$ and $R_2:=R+2Dn$), $q(R_1) \\le \\#\\{(x, y): \\text{dist}((0, 0), (x, y)) \\le R \\} \\le q(R_2) . \\quad (\\ast)$ Recall that $f(x, y)$ is defined as $\\inf\\left\\{\\sum_{|i|+|j|\\le n} \\lambda_{ij}T(i, j):\\, \\lambda_{ij}\\ge 0\\text{ and } \\sum_{|i|+|j|\\le n} \\lambda_{ij}(i, j) = (x, y)\\right\\} .$ $\\inf\\left\\{\\sum_{|i|+|j|\\le n} \\mu_{ij}:\\, \\mu_{ij}\\ge 0\\text{ and } \\sum_{|i|+|j|\\le n} \\mu_{ij}\\left(\\frac{i}{T(i,j)}, \\frac{j}{T(i,j)}\\right) = (x, y)\\right\\} .$ $\\inf\\left\\{t\\ge 0:\\, \\text{there are }\\mu_{ij}\\ge 0\\text{ with } \\sum_{|i|+|j|\\le n}\\mu_{ij} \\le 1\\text{ such that } \\sum_{|i|+|j|\\le n} \\mu_{ij}p_{ij} = \\frac1t(x, y)\\right\\} .$ Let $P$ be the convex hull of the points $p_{ij}$. We have proven that $f(x, y)$ is the minimum value $t\\ge 0$ such that $(x/t, y/t)$ belongs to $P$. Therefore, we have proven that Lemma 6. Let $P$ be the convex hull of the points $p_{ij}:= \\left(\\frac{i}{T(i,j)}, \\frac{j}{T(i,j)}\\right)$. For any $r>0$, the number of lattice points in $rP$ (here, $rP$ represents the scaling of $P$ by a factor $r$) coincides with $q(r)$. So, it remains only to (approximately) compute the lattice points inside $rP$. The standard way to approximate the number of lattice points in a convex subset is by computing the area of the subset. Let us check that it is precise enough in our setting. For any convex polygon, we have Lemma 7. Let $P$ be an arbitrary convex polygon. We have $\\text{area}(P) - \\text{perimeter}(P) - \\pi \\le \\#\\{(x, y)\\in P: \\, x,y\\text{ are integers}\\} \\le \\text{area}(P) + \\text{perimeter}(P) + \\pi.$ Proof. Denote by $d(x, X)$ the Euclidean distance between a point $x$ and a subset $X$ of the plane. For $r>0$, let $P_r$ be the enlargement of $P$ given by $\\{p: d(p, P)\\le r\\}$. For $r<0$, let $P_r$ be the reduction of $P$ given by $\\{p: d(p, P^c) > r\\}$. Observe that if $r_1, r_2$ have the same sign, then $(P_{r_1})_{r_2} = P_{r_1+r_2}$. Consider the disjoint squares centered at all lattice points in $P$. We have $P_{-\\frac1{\\sqrt2}} \\subseteq [-0.5, 0.5)\\times[-0.5,0.5) + \\{(x, y)\\in P:\\, x, y\\text{ integers}\\} \\subseteq P_{\\frac1{\\sqrt2}}.$ $\\text{area}\\left(P_{-\\frac1{\\sqrt2}}\\right) \\le \\#\\{(x, y)\\in P:\\, x, y\\text{ integers}\\} \\le \\text{area}\\left(P_{\\frac1{\\sqrt2}}\\right).$ Lemma 8. For $r>0$, we have $\\text{perimeter}(P_r) = \\text{perimeter}(P) + 2\\pi r,\\quad \\text{area}(P_r) = \\text{area}(P) + r\\cdot\\text{perimeter}(P) + \\pi r^2,$ $2\\sqrt{\\pi}\\sqrt{\\text{area}(P_r)}\\le \\text{perimeter}(P_r) \\le \\text{perimeter}(P),\\quad \\text{area}(P) + r\\cdot\\text{perimeter}(P) - \\pi r^2 \\le \\text{area}(P_r) \\le \\pi (R+r)^2 ,$ Proof. Let us observe that, for any $r$, $\\frac{d}{dr}\\text{area}(P_r)=\\text{perimeter}(P_r)$. The formulas for the area follow from those for the perimeter using this differential equation. The formula for the perimeter when $r>0$ is left to the reader. For $r<0$, since $P_r\\subseteq P$ we deduce $\\text{perimeter}(P_r)\\le \\text{perimeter}(P)$ and the lower bound for $\\text{perimeter}(P_r)$ is the isoperimetric inequality. Concatenating Lemma 6 and Lemma 7 together with $(\\ast)$, we have $R_1^2 \\text{area}(P)-R_1\\text{perimeter}(P)-\\pi \\le \\#\\{(x, y): \\text{dist}((0, 0), (x, y)) \\le R \\} \\le R_2^2 \\text{area}(P)+R_2\\text{perimeter}(P)+\\pi.$ Lemma 9. We have $\\text{perimeter}(P) \\le 4 D^2\\text{area}(P)$ and also $\\text{area}(P) \\ge 2D^{-2}$. Proof. By definition of $P$, it is not hard to check that $\\{(x, y): |x|+|y| \\le D^{-1}\\} \\subseteq P \\subseteq \\{(x, y): |x|+|y| \\le 1\\} .$ Thanks to this lemma, we obtain $(R_1^2-4D^2 R_1-2D^2) \\text{area}(P) \\le \\#\\{(x, y): \\text{dist}((0, 0), (x, y)) \\le R \\} \\le (R_2^2 + 4D^2R_2 + 2D^2) \\text{area}(P).$ Given the constraints of the problem, one can check that $\\frac{R_2^2 + 4D^2R_2 + 2D^2}{R_1^2-4D^2 R_1-2D^2} < 1 + 10^{-12},$ Computing the polygon $P$ fast enough Solving the problem is straightforward once we have computed $T(i, j)$ for the $O(n^2)$ pairs $(i, j)$ such that $|i|+|j|\\le n$. Indeed, once we have these values: We can compute the family of points $p_{ij}$ in $O(n^2)$. We can compute its convex hull in $O(n^2\\log(n))$. Finally, computing the area of the resulting polygon is straightforward. To compute $T(i, j)$ for all $i, j$ with $|i|+|j|\\le n$, a naive approach would be: Iterate over all $O(n^2)$ interesting pairs $(i, j)$. For each such pair, iterate over all $O(n^2)$ interesting pairs $(a, b)$. Compute the distance between $(a, b)$ and $(a+in, b+jn)$ using Dijkstra's algorithm, which takes $O(n^4\\log(n))$. This results in a total complexity of $O(n^8\\log(n))$, which is too slow. Optimization 1: Batch processing in Dijkstra. Instead of computing $T(i, j)$ separately for each pair, we observe that once $(a, b)$ is fixed, we can compute the answer for all relevant $(i, j)$ in one run of Dijkstra's algorithm. This reduces the complexity to $O(n^6\\log(n))$, which is still likely too slow. Let us remark that, when running Dijkstra's algorithm, we can completely ignore all cells at a Manhattan distance greater than $n^2$ from $(a, b)$. This is because we are only interested in paths where no two points share the same position modulo $n$. Otherwise, the path could be decomposed into multiple shorter segments, each obeying this property. Optimization 2: Reducing the search space using modulo $n$ properties. A key observation is that any path whose endpoints are equivalent modulo $n$ must contain a cell where at least one coordinate is divisible by $n$. Thus, we may assume that either $a$ or $b$ is $0$. This reduces the complexity to $O(n^5\\log(n))$, which might be sufficient to get accepted. Optimization 3: Removing the logarithmic factor. To further improve performance, note that the maximum weight is $D$. We can replace Dijkstra's priority queue with a bucket-based shortest path algorithm (similar to 0-1 BFS). This reduces the complexity per Dijkstra run to $O(n^5 + D)$.",
    "tags": [
      "shortest paths"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2068",
    "index": "H",
    "title": "Statues",
    "statement": "The mayor of a city wants to place $n$ statues at intersections around the city. The intersections in the city are at all points $(x, y)$ with integer coordinates. Distances between intersections are measured using Manhattan distance, defined as follows: $$ \\text{distance}((x_1, y_1), (x_2, y_2)) = |x_1 - x_2| + |y_1 - y_2|. $$\n\nThe city council has provided the following requirements for the placement of the statues:\n\n- The first statue is placed at $(0, 0)$;\n- The $n$-th statue is placed at $(a, b)$;\n- For $i = 1, \\dots, n-1$, the distance between the $i$-th statue and the $(i+1)$-th statue is $d_i$.\n\nIt is allowed to place multiple statues at the same intersection.\n\nHelp the mayor find a valid arrangement of the $n$ statues, or determine that it does not exist.",
    "tutorial": "Let $d_0 = a + b$ be the distance between the first and the $n$-th statue. We are going to prove that a valid arrangement exists if and only if the following two conditions are satisfied: $d_0 + d_1 + \\dots + d_{n-1}$ is even; $d_i \\leq d_0 + \\dots + d_{i-1} + d_{i+1} + \\dots + d_{n-1}$ for all $0 \\leq i \\leq n-1$. To start, let us prove that the two conditions above are necessary. Suppose there is a valid arrangement $s_1 = (x_1, y_1), \\, s_2 = (x_2, y_2), \\, \\dots, \\, s_n = (x_n, y_n)$. Then $d_0 + d_1 + \\dots + d_{n-1} = \\left( |x_n - x_1| + |y_n - y_1| \\right) + \\left( |x_1 - x_2| + |y_1 - y_2| \\right) + \\dots + \\left( |x_{n-1} - x_n| + |y_{n-1} - y_n| \\right);$ Conversely, we now show by induction on $n$ that conditions 1 and 2 are sufficient to construct a valid arrangement. Our proof will effectively yield an $O(n)$ algorithm to construct a valid arrangement. If $n=2$, condition 2 tells us that $d_0 \\leq d_1$ and $d_1 \\leq d_0$, so $d_0 = d_1$. Then the arrangement $s_0 = (0, 0), s_1 = (a, b)$ is valid. Suppose now that $n \\geq 3$. Our aim is to determine a placement $s_{n-1} = (a', b')$ for the $(n-1)$-th statue such that: $\\text{distance}(s_{n-1}, \\, s_n) = d_{n-1}$; if we define $\\hat{d_0} = \\text{distance}(s_1, \\, s_{n-1})$, then the distances $\\hat{d_0}, d_1, \\dots, d_{n-2}$ satisfy conditions 1 and 2. For any choice of $s_{n-1}$, note that $d_0 + \\hat{d_0} + d_{n-1}$ is necessarily even, because $d_0, \\hat{d_0}, d_{n-1}$ are the distances between the three points $s_1, s_{n-1}, s_n$. Therefore, $\\hat{d_0} + d_1 + \\dots + d_{n-2} \\equiv d_0 + d_1 + \\dots + d_{n-1} \\equiv 0 \\pmod 2,$ As $s_{n-1}$ varies among all integer points with $\\text{distance}(s_{n-1}, \\, s_n) = d_{n-1}$, the distance $\\hat{d_0}$ takes all values between $| d_0 - d_{n-1} |$ and $d_0 + d_{n-1}$ having the same parity as $d_0 + d_{n-1}$. The possible locations of $s_{n-1}$ are shown in red in the picture below. We are going to show that the value $\\hat{d_0} = \\min( d_0 + d_{n-1}, \\, d_1 + \\dots + d_{n-2} )$ belongs to the admissible range $\\left\\{| d_0 - d_{n-1} |, \\, \\dots, \\, d_0 + d_{n-1} \\right\\}$, has the correct parity, and makes the sequence $\\hat{d_0}, \\, d_1, \\, \\dots, \\, d_{n-2}$ satisfy condition 2. Case 1: $\\hat{d_0} = d_0 + d_{n-1} \\leq d_1 + \\dots + d_{n-2}$. Obviously, $d_0 + d_{n-1}$ belongs to the admissible range and has the correct parity. The sequence $\\hat{d_0}, \\, d_1, \\, \\dots, \\, d_{n-2}$ satisfies condition 2 for $i = 0$ because $\\hat{d_0} \\leq d_1 + \\dots + d_{n-2}$. For $i \\geq 1$, we need to check that $d_i \\leq \\hat{d_0} + d_1 + \\dots + d_{i-1} + d_{i+1} + \\dots + d_{n-2} = (d_0 + d_{n-1}) + d_1 + \\dots + d_{i-1} + d_{i+1} + \\dots + d_{n-2},$ Case 2: $\\hat{d_0} = d_1 + \\dots + d_{n-2} \\leq d_0 + d_{n-1}$. For $\\hat{d_0}$ to belong to the admissible range, we need to check that $d_1 + \\dots + d_{n-2} \\geq | d_0 - d_{n-1} |$. This is ensured by condition 2 for the original sequence $d_0, \\, \\dots, \\, d_{n-1}$ for $i=0$ and $i=n-1$. Condition 1 for the original sequence ensures that $d_1 + \\dots + d_{n-2}$ has the same parity as $d_0 + d_{n-1}$. We now check condition 2 for the sequence $\\hat{d_0}, \\, d_1, \\, \\dots, \\, d_{n-2}$. For $i=0$, we are done because $\\hat{d_0} = d_1 + \\dots + d_{n-2}$. For $i \\geq 1$, condition 2 is satisfied because $d_i \\leq \\hat{d_0}$.",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2068",
    "index": "I",
    "title": "Pinball",
    "statement": "You are playing a pinball-like game on a $h \\times w$ grid.\n\nThe game begins with a small ball located at the center of a specific cell marked as $S$. Each cell of the grid is either:\n\n- A block-type wall ($#$) that prevents the ball from entering the cell, reflecting it instead.\n- A thin oblique wall, either left-leaning ($\\\\$) or right-leaning ($/$), which reflects the ball according to its orientation.\n- A free cell ($.$) where the ball can move freely.\n\nThe goal is to make the ball escape the grid.\n\nAt the start, you can nudge the ball in one of four directions: up ($U$), down ($D$), left ($L$), or right ($R$). The ball traverses a free cell in one second, it enters and exits a cell containing a thin oblique wall in one second, and it bounces off a block-type wall in no time (the block-type wall occupies all of its cell).\n\nCollisions between the ball and all walls, both block-type and oblique, are perfectly elastic, causing the ball to reflect upon contact.\n\nFor example, the ball takes two seconds to enter a free cell, traverse it, bounce off an adjacent block-type wall, and traverse back the free cell until it exits.\n\nAs the ball moves, you may destroy oblique walls at any time, permanently converting them into free cells. You may destroy multiple oblique walls throughout the game, at any given time.\n\nDetermine whether it is possible for the ball to escape, and if so, find the \\textbf{minimum} number of oblique walls that need to be destroyed, along with the precise time each chosen wall should be destroyed.",
    "tutorial": "Let's decompose the whole grid into regions delimited by the movement of the ball without altering the walls. These regions are depicted in the picture below by colored lines. The path described by the solution is bolded. Let's build a graph over the set of all regions where we add an edge $(i, j)$ if regions $i$ and $j$ share an oblique wall. In the picture above, the red and blue regions will be connected by an edge. Similarly, the blue and purple regions, as well as the blue and green regions and the red and orange regions are adjacent in this formulation. Furthermore, let's compute the minimum distance between any of the two initial regions where the ball is located, and any of the regions that go outside the grid in this above described graph. Intuitively, this distance is a lower bound for our answer, as destroying $k$ walls can only let the ball travel to regions at distance at most $k$ from the initial regions. For a more formal proof, consider the relaxation of the problem where instead of destroying $k$ walls, we can choose $k$ walls and allow each of them to independently be active or inactive at any moment in time. Clearly, under this relaxation, the ball can only reach regions at distance at most $k$ from its initial position. Next, we can prove that this lower bound is, in fact, the answer to our problem, by providing a construction that allows the ball to escape under this minimum number of destroyed walls. There are multiple ways of solving the reconstruction problem. The easiest is perhaps to first find any sequence of $k$ regions that end up with the ball escaping. Then, starting from the most distant ($k$-th) region, simulate the game in reverse order, and once you first reach the oblique wall that connects the $k$-th and $(k-1)$-th regions, \"destroy\" such wall (in reverse, the correct formulation is to \"restore\" the already-destroyed wall), and continue the process until the ball reaches its initial position. Finally, an important aspect to quickly solve this problem is implementation. In order to simplify the implementation, one may skip constructing the graph described above and instead use it implicitly by keeping information over triplets of the form $(i, j, d)$ where $(i, j)$ is the position of the ball, and $d \\in \\{ \\texttt{U}, \\texttt{D}, \\texttt{L}, \\texttt{R} \\}$ is the direction where the ball is heading, and using 0-1 BFS or even Dijkstra to compute the minimum number of walls that need to be destroyed to reach any such state.",
    "tags": [
      "graphs",
      "shortest paths"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2068",
    "index": "J",
    "title": "The Ultimate Wine Tasting Event",
    "statement": "Rumors of the excellence of Gabriella's wine tasting events have toured the world and made it to the headlines of prestigious wine magazines. Now, she has been asked to organize an event at the EUC 2025!\n\nThis time she selected $2n$ bottles of wine, of which exactly $n$ are of white wine, and exactly $n$ of red wine. She arranged them in a line as usual, in a predetermined order described by a string $s$ of length $2n$: for $1 \\le i \\le 2n$, the $i$-th bottle from the left is white wine if $s_i = W$ and red wine if $s_i = R$.\n\nTo spice things up for the attendees (which include EUC contestants), Gabriella came up with the following wine-themed problem:\n\nConsider a way of dividing the $2n$ bottles into two disjoint subsets, each containing $n$ bottles. Then, for every $1 \\le i \\le n$, swap the $i$-th bottle in the first subset (from the left) and the $i$-th bottle of the second subset (also from the left). Is it possible to choose the subsets so that, after this operation is done exactly once, the white wines occupy the first $n$ positions?",
    "tutorial": "We will find a simple necessary and sufficient condition on the string $s$ for the operation to be successful. Then, it will be trivial to check whether this condition is satisfied. First, suppose that it is possible to rearrange the bottles as described in the statement. That is, there esist two subsets $A = \\{a_1, \\, \\dots, \\, a_n\\}$ and $B = \\{b_1, \\, \\, \\dots, \\, b_n\\}$ of $\\{1, \\, 2, \\, \\dots, \\, 2n\\}$, each of size $n$ and disjoint, such that swapping $s_{a_i}$ and $s_{b_i}$ (assuming the elements are sorted in each subset) results in the string $\\texttt{WW} \\dots \\texttt{WWRR} \\dots \\texttt{RR}$. Let $h$ be the last index such that $a_h \\le n$, and similarly let $k$ be the last index such that $b_k \\le n$. If either of them do not exist, set it equal to $0$. Note that, by definition, $h + k = n$. Modulo swapping $A$ and $B$, we can assume that $h \\le k$. Then, upon swapping $a_i$ with $b_i$ for $1 \\le i \\le n$, all the bottles at indices $a_1, \\, \\dots, \\, a_h$ will occupy positions among the leftmost $n$, which means that $s_{a_i} = \\texttt{W}$ for all $1 \\le i \\le h$. Also, after swapping, all bottles at indices $b_1, \\, \\dots, \\, b_h$ will occupy positions among the first $n$, and therefore $s_{b_i} = \\texttt{W}$ for $1 \\le i \\le h$. On the other hand, the bottles at indices $b_{h + 1}, \\, \\dots, \\, b_k$ will occupy positions greater than $n$, so that $s_{b_i} = \\texttt{R}$ for each $h + 1 \\le i \\le k$. This implies that, among the first $n$ bottles, the white ones are $2h$ and the red ones are $k - h = n - 2h$. Finally, consider the first $h$ bottles in the initial arrangement. Each of these belongs to either $\\{a_1, \\, \\dots, \\, a_h\\}$ or $\\{b_1, \\, \\dots, \\, b_h\\}$, and therefore, when swapped, it will end up in one of the first $n$ positions. This implies that $s_i = \\texttt{W}$ for $1 \\le i \\le h$. We deduced that a necessary condition is: the number of white bottles in the first half is even, say $2h$, and the first $h$ bottles are white. Note that the number of red bottles in the second half is also $2h$ and, by the same argument, the last $h$ bottles have to be red. Let's now prove that this condition is also sufficient. We construct $A$ and $B$ as follows: $A$ contains the first $h$ positions (which are white wines), and the first $n - h$ positions with red wines. $B$ contains everything else, that is, all positions with white wines except the first $h$, and the last $h$ positions (with red wines). It is easy to see that the operation of swapping $A$ and $B$ places all white wines in the first half and all red wines in the second half. Checking whether this condition is satisfied is trivial and can be done in time $O(n)$. Remark. Arrangements such as $\\texttt{WWRWWRRRRW}$ ($n = 5$), where only the \"first-half\" condition is satisfied, do not work. One needs to check that both the white wines in the first half as well as the red wines in the second half satisfy the condition.",
    "tags": [
      "combinatorics",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2068",
    "index": "K",
    "title": "Amusement Park Rides",
    "statement": "Ivan, Dmitrii, and Pjotr are celebrating Ivan's birthday at an amusement park with $n$ attractions. The $i$-th attraction operates at minutes $a_i, 2a_i, 3a_i, \\dots$ (i.e., every $a_i$ minutes).\n\nEach minute, the friends can either ride exactly one available attraction \\textbf{together} or wait. Since the rides are very short, they can board another attraction the next minute. They may ride the attractions in any order.\n\nThey want to experience each ride exactly once before heading off to enjoy the birthday cake. What is the earliest time by which they can finish all $n$ attractions?",
    "tutorial": "Assume that among the numbers $a_i$ there are $k$ distinct values, denoted by $p_1, p_2, \\dots, p_k$. Suppose each $p_j$ appears $q_j$ times in the sequence $\\{a_i\\}$. We now construct a flow graph as follows: Define the vertex set as $V = \\{S, T\\} \\cup \\{A_1, A_2, \\dots, A_k\\}$. For each vertex $A_i$ (with $1 \\le i \\le k$), add an edge from $S$ to $A_i$ with capacity $q_i$. For each positive integer $i$, introduce a vertex $B_i$. For every vertex $A_j$ (with $1 \\le j \\le k$), if $i \\equiv 0 \\pmod{p_j}$, then add an edge from $A_j$ to $B_i$ with capacity $1$. In addition, add an edge from $B_i$ to $T$ with capacity $1$. We continue adding vertices $B_i$ (in increasing order of $i$) until the maximum flow from $S$ to $T$ reaches $n$. The answer to the problem is the largest index $i$ for which a vertex $B_i$ was added. This approach has a running time of $O(\\mathrm{ans} \\cdot E)$, where $\\mathrm{ans}$ denotes the final value of $i$ and $E$ is the number of edges. However, this is too slow since it requires creating a vertex $B_i$ for every positive integer $i$. We can improve efficiency by avoiding the creation of every $B_i$. Instead, we maintain a mapping $M: \\mathbb{Z}^+ \\to \\{\\mathrm{indices}\\}$, where $M(i)$ is a set of indices. Initially, for each $1 \\le j \\le k$, we set $M(p_j) = \\{j\\}$. At each step, perform the following: Find the smallest $i$ for which $M(i)$ is nonempty. Add the vertex $B_i$ along with its edge to $T$ and add edges from $A_j$ to $B_i$ for every $j \\in M(i)$. If adding these edges increases the maximum flow, then for each $j \\in M(i)$ insert $j$ into $M(i+p_j)$. This means that a future vertex $B_{i+p_j}$ may also need to be connected to $A_j$. Otherwise, if the maximum flow does not increase, no additional edges from $A_j$ (for $j \\in M(i)$) will be needed. Finally, clear the set $M(i)$. Note that we examine at most $n+k$ distinct values of $i$ (because in each step we either increase the maximum flow or remove at least one element from $\\bigcup_i M(i)$). Therefore, the overall time complexity of the solution is $O(n \\cdot E)$, and it can be shown that $E = O(n \\log n)$.",
    "tags": [
      "flows",
      "graphs"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2069",
    "index": "A",
    "title": "Was there an Array?",
    "statement": "For an array of integers $a_1, a_2, \\dots, a_n$, we define its \\textbf{equality characteristic} as the array $b_2, b_3, \\dots, b_{n-1}$, where $b_i = 1$ if the $i$-th element of the array $a$ is equal to both of its neighbors, and $b_i = 0$ if the $i$-th element of the array $a$ is not equal to at least one of its neighbors.\n\nFor example, for the array $[1, 2, 2, 2, 3, 3, 4, 4, 4, 4]$, the equality characteristic will be $[0, 1, 0, 0, 0, 0, 1, 1]$.\n\nYou are given the array $b_2, b_3, \\dots, b_{n-1}$. Your task is to determine whether there exists such an array $a$ for which the given array is the equality characteristic.",
    "tutorial": "Let's try to find some contradiction of the following kind for the given array: we know for sure that some element $a$ must be equal to its neighbors, but the corresponding value $b_i$ is zero, or vice versa. If both $b_{i-1}$ and $b_{i+1}$ are equal to $1$, it means that the $i$-th element is equal to both of its neighbors, then $b_i$ must also be equal to $1$. That is, if there exists such an index $i$ that $b_{i-1} = b_{i+1} = 1$ and $b_i = 0$, we have a contradiction. It is not difficult to prove that if such an index does not exist, then it is always possible to find an array $a$ that satisfies all conditions. Let's construct it as follows: $a_1 = 1$; for each subsequent element $a_i$, if at least one of $(b_{i-1}, b_i)$ is equal to $1$, we must choose $a_i = a_{i-1}$, otherwise we set $a_i = a_{i-1} + 1$. This way, we can be sure that if $b_i$ is equal to $1$, then $a_{i-1} = a_i = a_{i+1}$. Therefore, the only problem may arise if some $b_i$ is equal to $0$, but at the same time $a_{i-1} = a_i = a_{i+1}$. However, if $a_{i-1} = a_i$ and $b_i = 0$, then $b_{i-1} = 1$. Similarly, $b_{i+1} = 1$. Thus, we have constructed the case where $b_{i-1} = b_{i+1} = 1$ and $b_i = 0$, which is the only case which can lead to a contradiction. Therefore, the solution reduces to checking whether there exists such an index $i$ that $b_{i-1} = b_{i+1} = 1$ and $b_i = 0$.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    s = list(input().split())\n    s = \"\".join(s)\n    if \"101\" in s:\n        print('NO')\n    else:\n        print('YES')\n",
    "tags": [
      "graph matchings",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "2069",
    "index": "B",
    "title": "Set of Strangers",
    "statement": "You are given a table of $n$ rows and $m$ columns. Initially, the cell at the $i$-th row and the $j$-th column has color $a_{i, j}$.\n\nLet's say that two cells are strangers if they \\textbf{don't} share a side. Strangers are allowed to touch with corners.\n\nLet's say that the set of cells is a set of strangers if all pairs of cells in the set are strangers. Sets with no more than one cell are sets of strangers by definition.\n\nIn one step, you can choose any set of strangers \\textbf{such that all cells in it have the same color} and paint all of them in some other color. You can choose the resulting color.\n\nWhat is the minimum number of steps you need to make the whole table the same color?",
    "tutorial": "Let's fix some color and look at all cells of that color. We can decide either to leave this color as the resulting one and then we can ignore all these cells. Or we should get rid of this color, and it would cost at least one operation. If all cells are pairwise strangers, then one operation is enough to recolor all of them in the desired color. Otherwise, we need at least two operations. It turns out that two operations are enough: each connected component of the same color can be painted in two steps if we color the table like a chessboard and choose \"black\" cells at the first step and \"white\" cells at the second step. Since components don't touch each other, we can choose subsets from different components independently. In total, we can get rid of any color in two steps. As a result, for each color, let's calculate the number of steps we need to get rid of it as $v_c$. It's equal to $1$ if it's present in the table, plus $1$ if there are two neighbors of that color. The answer then equals to $\\sum_{c=1}^{nm}{v_c}$ minus the color we decided to leave untouched. Or, optimally, $\\sum_{c=1}^{nm}{v_c} - \\max_{c=1}^{nm}{v_c}$",
    "code": "for _ in range(int(input())):\n    n, m = map(int, input().split())\n    a = [list(map(int, input().split())) for i in range(n)]\n    hasColor = [0] * (n * m)\n    hasBad = [0] * (n * m)\n    for i in range(n):\n        for j in range(m):\n            hasColor[a[i][j] - 1] = 1\n            if i + 1 < n and a[i][j] == a[i + 1][j]:\n                hasBad[a[i][j] - 1] = 1\n            if j + 1 < m and a[i][j] == a[i][j + 1]:\n                hasBad[a[i][j] - 1] = 1\n    print(sum(hasColor) + sum(hasBad) - 1 - max(hasBad))\n",
    "tags": [
      "greedy",
      "matrices"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2069",
    "index": "C",
    "title": "Beautiful Sequence",
    "statement": "Let's call an integer sequence \\textbf{beautiful} if the following conditions hold:\n\n- its length is at least $3$;\n- for every element except the first one, there is an element to the left less than it;\n- for every element except the last one, there is an element to the right larger than it;\n\nFor example, $[1, 4, 2, 4, 7]$ and $[1, 2, 4, 8]$ are beautiful, but $[1, 2]$, $[2, 2, 4]$, and $[1, 3, 5, 3]$ are not.\n\nRecall that a subsequence is a sequence that can be obtained from another sequence by removing some elements without changing the order of the remaining elements.\n\nYou are given an integer array $a$ of size $n$, where \\textbf{every element is from $1$ to $3$}. Your task is to calculate the number of beautiful subsequences of the array $a$. Since the answer might be large, print it modulo $998244353$.",
    "tutorial": "Let's change the definition of a beautiful sequence a bit. We can prove that the condition \"for every element except the first one, there is an element to the left less than it\" is equivalent to \"the first element is less than every other element in the sequence\". We can prove that these two conditions are equivalent by induction: for the $2$-nd element of the sequence $s_2$, the only element to the left is the $1$-st ($s_1$), so $s_1 < s_2$; assume we have proved that, for every $i \\in [2, k]$, $s_1 < s_i$. Let's prove that $s_1 < s_{i+1}$. Suppose that the element to the left of $s_{i+1}$ which is less than $s_{i+1}$ is $s_j$; if $j = 1$, then obviously, $s_1 < s_{i+1}$; otherwise, $s_1 < s_j$ and $s_j < s_{i+1}$, so $s_1 < s_{i+1}$. Using similar induction, we can prove that \"for every element except the last one, there is an element to the right larger than it\" is the same as \"the last element is greater than every other element in the sequence\". Since the array consists only of $1$, $2$ and $3$, we can notice that there is only one possible beautiful sequence pattern: 122...223 (i. e. one $1$, followed by any number of consecutive $2$ and one final $3$). Any other pattern is invalid: the leftmost element should be strictly less than every element in the middle (every element from the $2$-nd to the second-to-last), and the rightmost should be strictly greater than every element in the middle; so, the leftmost element should be $1$, the rightmost element should be $3$, and every element in the middle should be $2$. In order to calculate the number of subsequences that match the aforementioned pattern, we can use dynamic programming. Let $dp_{i, j}$ be the number of subsequences if we have considered the first $i$ elements of the array, and the current state is $j$ (for example, state $0$ means that the sequence is empty, state $1$ means that we have taken the element equal to $1$, state $2$ means that we have taken some number of $2$'s, state $3$ means that we have taken the element $3$ and the sequence is finished). The transitions in this dynamic programming are pretty simple and can be done in $O(1)$ for each state. So the total complexity of the solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nconst int MOD = 998244353;\n\nint add(int x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n  return x;\n}\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> dp(4, 0);\n    dp[0] = 1;\n    while (n--) {\n      int x;\n      cin >> x;\n      if (x == 2) dp[x] = add(dp[x], dp[x]);\n      dp[x] = add(dp[x], dp[x - 1]);\n    }\n    cout << dp[3] << '\\n';\n  }\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2069",
    "index": "D",
    "title": "Palindrome Shuffle",
    "statement": "You are given a string $s$ consisting of lowercase Latin letters.\n\nYou can perform the following operation with the string $s$: choose a contiguous substring (possibly empty) of $s$ and shuffle it (reorder the characters in the substring as you wish).\n\nRecall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.\n\nYour task is to determine the minimum possible length of the substring on which the aforementioned operation must be performed in order to convert the given string $s$ into a palindrome.",
    "tutorial": "I will describe a solution in $O(n \\log n)$. It is possible to solve the problem in $O(n)$ with careful implementation of two pointers method, but $O(n \\log n)$ is more intuitive and easier to understand, in my opinion. First, while the first character of the string is equal to the last character of the string, let's get rid of both of them - it's pretty obvious we shouldn't touch them. After that, we get a string for which the first character is not equal to the last character. At least one of them should be changed - so, the substring we need to shuffle is either a prefix or a suffix of the string. Suppose the string we shuffle is a prefix (if we need to shuffle a suffix, we'll check it by reversing the string and trying to shuffle a prefix of the reversed string). Suppose that, by shuffling a prefix of length $m$, we get the answer. Then, by shuffling a prefix of length $m+1$, we will also be able to make the string a palindrome. It means that the shortest possible length of the prefix we need to shuffle can be found with binary search. In our binary search, we need to check whether we can make the string a palindrome by shuffling the prefix of certain length. Let's check it in $O(n)$ by verifying the following two conditions: for every pair $(s_i, s_{n-i+1})$ such that $s_i \\ne s_{n-i+1}$, at least one of the characters should be changed, so it should belong to the prefix; for every character $c$ from a to z, let's calculate the number of pairs where this character should fill both positions (i. e. the number of pairs $(s_i, s_{n-i+1})$ where at least one of the characters is equal to $c$ and is not affected by our shuffle). This number of pairs should not exceed the number of pairs of character $c$ in the whole string, otherwise we won't have enough occurrences of $c$ to fill all these pairs of positions. It's obvious that these two conditions are necessary, but we can prove that they are sufficient: if both of them hold, we have enough characters to fill all pairs of positions where we need a fixed character, and all the remaining pairs of positions can be filled by any remaining pairs of characters (the input is guaranteed to have an even number of every character, so it's always possible to split all characters into pairs). So, we need to check if some substring is a possible answer $O(\\log n)$ times, and every such check can be done in $O(n)$. Thus, our solution works in $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    string s;\n    cin >> s;\n    int n = s.size();\n    int i = 0;\n    while (i < n / 2 && s[i] == s[n - i - 1]) ++i;\n    n -= 2 * i;\n    s = s.substr(i, n);\n    int ans = n;\n    for (int z = 0; z < 2; ++z) {\n      int l = 0, r = n;\n      while (l <= r) {\n        int m = (l + r) / 2;\n        vector<int> cnt(26);\n        for (int i = 0; i < m; ++i)\n          cnt[s[i] - 'a']++;\n        bool ok = true;\n        for (int i = 0; i < min(n / 2, n - m); ++i) {\n          char c = s[n - i - 1];\n          if (i < m) {\n            ok &= cnt[c - 'a'] > 0;\n            cnt[c - 'a']--;\n          } else {\n            ok &= (c == s[i]);\n          }\n        }\n        for (auto x : cnt)\n          ok &= (x % 2 == 0);\n        if (ok) {\n          r = m - 1;\n        } else {\n          l = m + 1;\n        }\n      }\n      ans = min(ans, r + 1); \n      reverse(s.begin(), s.end());\n    }\n    cout << ans << '\\n';\n  }\n}\n",
    "tags": [
      "binary search",
      "greedy",
      "hashing",
      "strings",
      "two pointers"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2069",
    "index": "E",
    "title": "A, B, AB and BA",
    "statement": "You are given a string $s$ consisting of characters A and B.\n\nYour task is to split it into blocks of length $1$ and $2$ in such a way that\n\n- there are no more than $a$ strings equal to \"A\";\n- there are no more than $b$ strings equal to \"B\";\n- there are no more than $ab$ strings \"AB\";\n- there are no more than $ba$ strings \"BA\";\n\nStrings \"AA\" and \"BB\" are prohibited. Each character of the initial string $s$ should belong to exactly one block.",
    "tutorial": "Firstly, let's find the solution that maximizes the number of used blocks of length $2$ (AB and BA). Each used block of length $2$ frees us one A and B, so we don't lose anything. Secondly, since we don't have AA and BB, any pair of equal neighboring characters will be split in-between in any possible partition. So, let's split them at the start. As a result, we'll get blocks with alternating characters of four types: ABA..A: if it's length $l$ it can be split in $x$ AB-s and $y$ BA-s for any $x + y \\le \\frac{l}{2}$. For example: A|BA|BA, AB|B|BA or AB|AB|A; BAB..B: practically the same as the previous, so let's just count the total number of blocks we can get from the first two types as $tot$; ABA..B: it can be split in $\\frac{l}{2}$ of AB, but if we need at least one BA the total number of blocks will reduce to $\\frac{l}{2} - 1$. For example: AB|AB|AB, but AB|A|BA|B; BAB..A: the same case, but favors BA-s instead. So, let's split ABA..B into AB and BAB..A into BA as much as we can. As a result, one of three cases will follow: We spent all $ab$: then remaining ABA..B blocks will be split into BA. We lose one pair of A and B for each ABA..B block, so it's optimal to reduce the number of remaining ABA...B, so it's optimal to split shortest ABA...B-s into AB-s at the first step. We spent all $ba$: remaining BAB..A blocks will be split into AB. The case is the same as previous and gives the same greedy: split shortest BAB..A-s into BA-s at the first step. There are no AB..B and BA..A left. Only odd-length blocks left (the first two types}, so it doesn't matter how to split it. In total we'll get $\\min{(ab + ba, tot)}$ more blocks of length $2$. In total, the strategy is the following: split AB..B-s into AB in increasing order of lengths; split BA..A-s into BA in increasing order of lengths; split remaining AB..B-s into BA in any order; split remaining BA..A-s into AB in any order; calculate extra pairs you'll get using the formula $\\min{(ab + ba, tot)}$. check that you have enough $a$ and $b$ to cover remaining A-s and B-s. Total complexity is $O(|s| \\log{|s|})$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n\ntypedef long long li;\n\ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n\treturn out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n\tfore(i, 0, sz(v)) {\n\t\tif(i) out << \" \";\n\t\tout << v[i];\n\t}\n\treturn out;\n}\n\nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n\nstring s;\nint a, b, ab, ba;\n\ninline bool read() {\n\tif(!(cin >> s))\n\t\treturn false;\n\tcin >> a >> b >> ab >> ba;\n\treturn true;\n}\n\nint process(vector<int> &rem, int &tot) {\n\tint placed = 0;\n\tsort(rem.begin(), rem.end(), greater<int>());\n\twhile (!rem.empty() && tot > 0) {\n\t\tint cnt = min(rem.back() / 2, tot);\n\t\tplaced += cnt;\n\t\ttot -= cnt;\n\t\trem.back() -= 2 * cnt;\n\t\tif (rem.back() == 0)\n\t\t\trem.pop_back();\n\t}\n\treturn placed;\n}\n\nint remnants(vector<int> &rem, int &tot) {\n\tint placed = 0;\n\tfor (int &cur : rem) {\n\t\tint cnt = min(tot, (cur - 2) / 2);\n\t\tplaced += cnt;\n\t\ttot -= cnt;\n\t\tcur -= 2 * cnt + 2;\n\t}\n\treturn placed;\n}\n\ninline void solve() {\n\ts.push_back(s.back());\n\tint eq = 0, placedPairs = 0;\n\tvector<int> remAB, remBA;\n\n\tint lst = 0;\n//\tcerr << \"s = \" << s << endl;\n\tfore (i, 1, sz(s)) {\n\t\tif (s[i] != s[i - 1])\n\t\t\tcontinue;\n\t\t\n\t\tif (s[lst] == s[i - 1]) {\n\t\t\t// ABA..A or BAB..B\n\t\t\teq += (i - lst) / 2;\n\t\t}\n\t\telse {\n\t\t\tint len = i - lst;\n\t\t\tif (s[lst] == 'A') {\n\t\t\t\t// ABA..B\n\t\t\t\tremAB.push_back(len);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// BAB..A\n\t\t\t\tremBA.push_back(len);\n\t\t\t}\n\t\t}\n//\t\tcerr << lst << \", \" << i << endl;\n\t\tlst = i;\n\t}\n\ts.pop_back();\n\t\n\tplacedPairs += process(remAB, ab);\n\tassert(remAB.empty() || ab == 0);\n\n\tplacedPairs += process(remBA, ba);\n\tassert(remBA.empty() || ba == 0);\n\n\tplacedPairs += remnants(remAB, ba);\n\tplacedPairs += remnants(remBA, ab);\n\n\tint remPlaced = min(eq, ab + ba);\n\tplacedPairs += remPlaced;\n\n\tint needA = count(s.begin(), s.end(), 'A') - placedPairs;\n\tint needB = count(s.begin(), s.end(), 'B') - placedPairs;\n\n\tif (needA <= a && needB <= b)\n\t\tcout << \"YES\\n\";\n\telse\n\t\tcout << \"NO\\n\";\n}\n\nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint t; cin >> t;\n\twhile (t--) {\n\t\tread();\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy",
      "sortings",
      "strings"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2069",
    "index": "F",
    "title": "Graph Inclusion",
    "statement": "A connected component of an undirected graph is defined as a set of vertices $S$ of this graph such that:\n\n- for every pair of vertices $(u, v)$ in $S$, there exists a path between vertices $u$ and $v$;\n- there is no vertex outside $S$ that has a path to a vertex within $S$.\n\nFor example, the graph in the picture below has three components: $\\{1, 3, 7, 8\\}$, $\\{2\\}$, $\\{4, 5, 6\\}$.\n\nWe say that graph $A$ includes graph $B$ if every component of graph $B$ is a subset of some component of graph $A$.\n\nYou are given two graphs, $A$ and $B$, both consisting of $n$ vertices numbered from $1$ to $n$. Initially, there are no edges in the graphs. You must process queries of two types:\n\n- add an edge to one of the graphs;\n- remove an edge from one of the graphs.\n\nAfter each query, you have to calculate the minimum number of edges that have to be added to $A$ so that $A$ includes $B$, and print it. Note that you don't actually add these edges, you just calculate their number.",
    "tutorial": "First, let's understand how to solve the problem without queries (given two graphs $A$ and $B$, add the minimum number of edges to $A$ so that it includes graph $B$), and then we'll deal with query processing. Let's understand what it means for graph $A$ to not include $B$. This means that some component of graph $B$ is not a subset of any component of graph $A$ - that is, there exist two vertices (let's call them $x$ and $y$) that belong to the same component in graph $B$, but do not belong to the same component in graph $A$. If this happens, let's connect vertices $x$ and $y$ with an edge in graph $A$, and then try to find such a pair of vertices again. We will continue doing this until it turns out that there is no such pair of vertices. After that, graph $A$ will include graph $B$. Let's take a look at what kind of graph we have obtained. The following holds for it: if two vertices $x$ and $y$ are in the same component either in graph $A$ or in graph $B$ (or in both of these graphs), then they are in the same component in the resulting graph (note that the reverse is not necessarily true). This means that the partition of this graph into components will be the same as if we constructed a graph that has edges from both graphs $A$ and $B$, and partitioned it into components. Thus, for graph $A$ to include graph $B$, we need to make its components match those of the union of graphs $A$ and $B$. Since the union of graphs $A$ and $B$ includes graph $A$, it is sufficient for us to count the number of components in graph $A$ and in the union, and the difference between these two numbers will be exactly the number of edges we need to add to graph $A$ for its components to coincide with the components of the union. Now let's deal with the queries. We need to maintain two graphs ($A$ and the union), add/remove edges, and compute the number of components in the graphs. Moreover, all queries can be read from the very beginning and then processed (the problem can be solved offline). This means we can use the Dynamic Connectivity Offline technique. Below is a description of this technique. First, for each edge in each graph, we will identify all segments of queries when this edge exists (that is, such segments $[l, r]$ that the edge exists from query $l$ to query $r$). In total, there will be $O(q)$ such segments. We will build a segment tree with $q$ leaves, where each leaf corresponds to a certain query. Each segment $[l, r]$ that we have identified can be split into $O(\\log q)$ segments corresponding to the vertices of the segment tree (similarly to how a segment tree splits any query on a segment into $O(\\log q)$ vertices). We will add information of the form \"this edge exists throughout this segment\" to the corresponding vertices. Now our task is the following: for each query, form the graph so that it contains only edges existing during that query. Each query corresponds to one of the leaves of the segment tree, and the edges that exist at that moment are the edges stored in the vertices on the path to that leaf of the segment tree. Thus, now for each leaf of the segment tree, we need to form a partition of the graph into components if the graph contains exactly those edges that are on the path from the root to that leaf. To do this, we can recursively traverse the segment tree. When we visit vertex $v$, we will do the following: add all edges stored in vertex $v$ of the segment tree; if vertex $v$ has children, recursively visit the children; if vertex $v$ has no children, then it is a leaf of the segment tree, and the graph is currently in such a state that we can find the answer to the corresponding query (the graph contains all edges that exist at that moment); before returning from vertex $v$, \"rollback\" all changes we made in it. We need a data structure that can add an edge to the graph and rollback the last changes. The simplest option for such a structure is a DSU with rollbacks. We will write a standard DSU with a rank heuristic, but without path compression (it does not combine well with rollbacks). Each time we make a change in the DSU, we will remember which values we changed and what was stored there before (look at the function change in the model solution to understand how to implement this most simply). Since we use only one DSU heuristic, adding one edge will take $O(\\log n)$ - and, accordingly, rolling back an edge will also take $O(\\log n)$. In total, we have $q$ segments of edge existence, each of which is split by the segment tree into $O(\\log q)$ segments, so the total number of edge addition operations will be $O(q \\log q)$, and the entire solution will work in $O(q \\log q \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;             \n\nconst int N = 400043;\nconst int BUF = N * 20;\n\nint* where[BUF];\nint val[BUF];\nint cur = 0;\n\nvoid change(int& x, int y)\n{\n    val[cur] = x;\n    where[cur] = &x;\n    x = y;\n    cur++;\n}\n\nvoid rollback()\n{\n    cur--;\n    (*where[cur]) = val[cur];\n}\n\nstruct DSU\n{\n    vector<int> p, s;\n    int n;\n    int comps;\n\n    int get(int x)\n    {\n        if(p[x] == x) return x;\n        return get(p[x]);\n    }\n\n    void merge(int x, int y)\n    {\n        x = get(x);\n        y = get(y);\n        if(x == y) return;\n        change(comps, comps - 1);\n        if(s[x] < s[y]) swap(x, y);\n        change(p[y], x);\n        change(s[x], s[x] + s[y]);    \n    }\n\n    DSU(int n = 0)\n    {\n        this->n = n;\n        s = vector<int>(n, 1);\n        p = vector<int>(n);\n        iota(p.begin(), p.end(), 0);\n        comps = n;\n    }\n};\n\nstruct edge\n{\n    char g;\n    int x;\n    int y;\n    edge(char g = 'A', int x = 0, int y = 0) : g(g), x(x), y(y) {};\n};\n\nDSU A, united;\nvector<edge> T[4 * N];\nint ans[N];\n\nvoid dfs(int v, int l, int r)\n{\n    int state = cur;\n    for(auto e : T[v])\n    {\n        united.merge(e.x, e.y);\n        if(e.g == 'A') A.merge(e.x, e.y);   \n    }\n    if(l == r - 1)\n    {\n        ans[l] = A.comps - united.comps;\n    }\n    else\n    {\n        int m = (l + r) / 2;\n        dfs(v * 2 + 1, l, m);\n        dfs(v * 2 + 2, m, r);\n    }\n    while(state != cur) rollback();\n}\n\nvoid add_edge(int v, int l, int r, int L, int R, edge e)\n{\n    if(L >= R) return;\n    if(L == l && R == r) T[v].push_back(e);\n    else\n    {\n        int m = (l + r) / 2;\n        add_edge(v * 2 + 1, l, m, L, min(m, R), e);\n        add_edge(v * 2 + 2, m, r, max(L, m), R, e);\n    }\n}\n\nmap<pair<int, int>, int> last[2];\n\nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int n, q;\n    cin >> n >> q;\n    A = DSU(n);\n    united = DSU(n);\n    for(int i = 0; i < q; i++)\n    {\n        string s;\n        int x, y;\n        cin >> s >> x >> y;\n        --x;\n        --y;\n        int idx = (s[0] == 'A' ? 0 : 1);\n        if(x > y) swap(x, y);\n        if(last[idx].count(make_pair(x, y)) == 0)\n        {\n            last[idx][make_pair(x, y)] = i;\n        }\n        else\n        {\n            add_edge(0, 0, q, last[idx][make_pair(x, y)], i, edge(s[0], x, y));\n            last[idx].erase(make_pair(x, y));\n        }\n    }\n    for(int i = 0; i < 2; i++)\n        for(auto a : last[i])\n            add_edge(0, 0, q, a.second, q, edge(char(i + 'A'), a.first.first, a.first.second));\n    dfs(0, 0, q);\n    for(int i = 0; i < q; i++)\n        cout << ans[i] << \"\\n\";\n}\n",
    "tags": [
      "data structures",
      "dfs and similar",
      "divide and conquer",
      "dsu",
      "graphs"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2070",
    "index": "A",
    "title": "FizzBuzz Remixed",
    "statement": "FizzBuzz is one of the most well-known problems from coding interviews. In this problem, we will consider a remixed version of FizzBuzz:\n\nGiven an integer $n$, process all integers from $0$ to $n$. For every integer such that its remainders modulo $3$ and modulo $5$ are the same (so, for every integer $i$ such that $i \\bmod 3 = i \\bmod 5$), print FizzBuzz.\n\nHowever, you don't have to solve it. Instead, given the integer $n$, you have to report how many times the correct solution to that problem will print FizzBuzz.",
    "tutorial": "The key observation in this problem is that, if you pick two integers $x$ and $x+15$, both their remainders modulo $3$ and modulo $5$ are the same. So, the number of integers we need to count in $[0, 14]$ is the same as in $[15, 29]$, the same as in $[30, 44]$, and so on. So, you can calculate the number of segments of length $15$ starting from $0$ before $n$ (which is $\\lfloor \\frac{n}{15}\\rfloor$), multiply it by the number of values we need in $[0, 14]$, and then process the last (partial) segment naively, since it will contain at most $15$ elements. Time complexity: $O(1)$.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    ans = 3 * (n // 15)\n    n %= 15\n    for j in range(n + 1):\n        if j % 3 == j % 5:\n            ans += 1\n    print(ans)",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2070",
    "index": "B",
    "title": "Robot Program",
    "statement": "There is a robot on the coordinate line. Initially, the robot is located at the point $x$ ($x \\ne 0$). The robot has a sequence of commands of length $n$ consisting of characters, where L represents a move to the left by one unit (from point $p$ to point $(p-1)$) and R represents a move to the right by one unit (from point $p$ to point $(p+1)$).\n\nThe robot starts executing this sequence of commands (one command per second, in the order they are presented). However, whenever the robot reaches the point $0$, the counter of executed commands is reset (i. e. it starts executing the entire sequence of commands from the very beginning). If the robot has completed all commands and is not at $0$, it stops.\n\nYour task is to calculate how many times the robot will enter the point $0$ during the next $k$ seconds.",
    "tutorial": "Let's simulate the process until either the command sequence terminates or the robot reaches the point $0$. If the sequence ends and the robot is not at $0$, then the answer to the problem is $0$. Otherwise, we need to check whether the robot can return to the point $0$ if we begin executing commands again. We can simply iterate through the sequence and record the first time the robot returns to the point $0$. If no such time exists, then the answer to the problem is $1$. Otherwise, this loop (from $0$ to $0$) will continue until time $k$ expires. In this case, the answer is $\\left\\lfloor\\frac{k'}{c}\\right\\rfloor + 1$, where $k'$ is the remaining time after the first hit of the point $0$, and $c$ is the time required for the robot to return to the same position from the point $0$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing li = long long;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    li n, x, k;\n    cin >> n >> x >> k;\n    string s;\n    cin >> s;\n    for (int i = 0; i < n; ++i) {\n      x += (s[i] == 'L' ? -1 : +1);\n      --k;\n      if (!x) break;\n    }\n    li ans = 0;\n    if (!x) {\n      ans = 1;\n      for (int i = 0; i < n; ++i) {\n        x += (s[i] == 'L' ? -1 : +1);\n        if (!x) {\n          ans += k / (i + 1);\n          break;\n        }\n      }\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "brute force",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2070",
    "index": "C",
    "title": "Limited Repainting",
    "statement": "You are given a strip, consisting of $n$ cells, all cells are initially colored red.\n\nIn one operation, you can choose a segment of consecutive cells and paint them \\textbf{blue}. Before painting, the chosen cells can be either red or blue. Note that it is not possible to paint them red. You are allowed to perform at most $k$ operations (possibly zero).\n\nFor each cell, the desired color after all operations is specified: red or blue.\n\nIt is clear that it is not always possible to satisfy all requirements within $k$ operations. Therefore, for each cell, a penalty is also specified, which is applied if the cell ends up the wrong color after all operations. For the $i$-th cell, the penalty is equal to $a_i$.\n\nThe penalty of the final painting is calculated as the \\textbf{maximum penalty} among all cells that are painted the wrong color. If there are no such cells, the painting penalty is equal to $0$.\n\nWhat is the minimum penalty of the final painting that can be achieved?",
    "tutorial": "The problem asks to minimize the maximum. An experienced participant should immediately consider binary search as a possible solution. The condition for binary search can be formulated as follows: is there a coloring such that its penalty does not exceed $x$? If the penalty does not exceed $x$, then it does not exceed $x+1$, which means the function is monotonic. This can be interpreted as follows. Cells with a penalty less than or equal to $x$ can be left red, or they can be painted blue. Cells with a penalty greater than $x$ must be painted the correct color. In fact, since we don't care about the cells of the first type, we can simply remove them from the strip. We need to ensure that the cells of the second type can be correctly colored in no more than $k$ operations. That is, we need to check that the blue cells can be divided into no more than $k$ contiguous segments. This check can be done in linear time. We can count the number of positions $i$ such that cell $i$ is blue, and cell $i-1$ is either absent or red. Each such position indicates the start of a segment. Therefore, their count is equal to the number of segments. Overall complexity: $O(n \\log A)$ for each testcase.",
    "code": "for _ in range(int(input())):\n    n, k = map(int, input().split())\n    s = input()\n    a = list(map(int, input().split()))\n    l, r = 0, 10**9\n    res = -1\n    \n    def check(d):\n        last = 'R'\n        cnt = 0\n        for i in range(n):\n            if a[i] > d:\n                if s[i] == 'B' and last != 'B':\n                    cnt += 1\n                last = s[i]\n        return cnt <= k\n    \n    while l <= r:\n        m = (l + r) // 2\n        if check(m):\n            res = m\n            r = m - 1\n        else:\n            l = m + 1\n    print(res)",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2070",
    "index": "D",
    "title": "Tree Jumps",
    "statement": "You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. Let $d_x$ be the distance (the number of edges on the shortest path) from the root to the vertex $x$.\n\nThere is a chip that is initially placed at the root. You can perform the following operation as many times as you want (possibly zero):\n\n- move the chip from the current vertex $v$ to a vertex $u$ such that $d_u = d_v + 1$. If $v$ is the root, you can choose any vertex $u$ meeting this constraint; however, if $v$ is not the root, $u$ should not be a neighbor of $v$ (there should be no edge connecting $v$ and $u$).\n\nFor example, in the tree above, the following chip moves are possible: $1 \\rightarrow 2$, $1 \\rightarrow 5$, $2 \\rightarrow 7$, $5 \\rightarrow 3$, $5 \\rightarrow 4$, $3 \\rightarrow 6$, $7 \\rightarrow 6$.\n\nA sequence of vertices is \\textbf{valid} if you can move the chip in such a way that it visits all vertices from the sequence (and only them), in the order they are given in the sequence.\n\nYour task is to calculate the number of valid vertex sequences. Since the answer might be large, print it modulo $998244353$.",
    "tutorial": "We can solve this problem by using dynamic programming. Let $dp_v$ represent the number of valid sequences ending at vertex $v$. To calculate $dp_v$, we can iterate over all previous vertices $u$ in the sequence, such that $d_v = d_u + 1$ and $u \\ne p_v$ (or $u$ is the root). Then, $dp_v$ is the sum of $dp_u$ for all such $u$. Note that the vertices should be processed in order of increasing distance from the root, because otherwise, $dp_u$ might not be calculated when we need to use it in $dp_v$. However, this approach can be very slow, as there may be $O(n)$ vertices $u$ for each vertex $v$. In order to speed up this solution, we can observe that if vertices have the same distance from the root, the calculation of their $dp$ values follows a similar pattern. Specifically, we only need to consider the $dp$ values of vertices in the previous \"layer\" of the tree, excluding their parent node. Thus, we can store the sum of all $dp$ values for each \"layer\". Let $tot_i$ be the sum of $dp_v$ for all vertices $v$ with distance $i$ from the root. Then we can easily calculate $dp_v$ as $tot_{d_v - 1} - dp_{p_v}$ (or minus $0$ if $p_v$ is the root). The answer to the problem is the sum of all values $dp_v$. To order the vertices according to the distance from the root, you can use DFS (and then sort the vertices according to the distance) or BFS. Or you can use the following method: since for every vertex, the index of its parent is less, we can process the vertices from $1$ to $n$ and set $d_v = d_{p_v} + 1$. Then, for every depth, you can build a vector of all vertices on that depth (by adding each vertex to the corresponding vector). This approach works in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\n \nint add(int x, int y) {\n  x += y;\n  if (x >= MOD) x -= MOD;\n  if (x < 0) x += MOD;\n  return x;\n}\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> p(n), d(n);\n    vector<vector<int>> vs(n);\n    for (int v = 1; v < n; ++v) {\n      cin >> p[v];\n      --p[v];\n      d[v] = d[p[v]] + 1;\n      vs[d[v]].push_back(v);\n    }\n    vector<int> dp(n), tot(n);\n    dp[0] = tot[0] = 1;\n    for (int i = 1; i < n; ++i) {\n      for (int v : vs[i]) {\n        dp[v] = add(tot[d[v] - 1], d[v] == 1 ? 0 : -dp[p[v]]);\n        tot[d[v]] = add(tot[d[v]], dp[v]);\n      }\n    }\n    int ans = 0;\n    for (int v = 0; v < n; ++v) {\n      ans = add(ans, dp[v]);\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "trees"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2070",
    "index": "E",
    "title": "Game with Binary String",
    "statement": "Consider the following game. Two players have a binary string (a string consisting of characters 0 and/or 1). The players take turns, the first player makes the first turn. During a player's turn, he or she has to choose exactly two adjacent elements of the string and remove them (\\textbf{the first element and the last element are also considered adjacent}). Furthermore, there are additional constraints depending on who makes the move:\n\n- if it's the first player's move, \\textbf{both} chosen characters should be 0;\n- if it's the second player's move, \\textbf{at least one} of the chosen characters should be 1.\n\nThe player who can't make a valid move loses the game. This also means that if the string currently has less than $2$ characters, the current player loses the game.\n\nYou are given a binary string $s$ of length $n$. You have to calculate the number of its substrings such that, if the game is played on that substring and both players make optimal decisions, the first player wins. In other words, calculate the number of pairs $(l, r)$ such that $1 \\le l \\le r \\le n$ and the first player has a winning strategy on the string $s_l s_{l+1} \\dots s_r$.",
    "tutorial": "First, we need to modify the game a bit. Suppose that, instead of removing two adjacent characters, a player can remove any pair of characters of the required type. So, the first player can remove any two characters equal to 0; the second player can remove any two characters, at least one of which is 1. Now the order of characters does not matter, only their quantities. Let $c_0$ be the number of 0's in the string, $c_1$ be the number of 1's. It's pretty obvious that in this version of the game, the second player should always remove one 0 and one 1, if it is possible (and only if there are no 0's, remove two 1's). So, after each pair of moves, one 1 and three 0's are removed. Suppose that the length of the string is divisible by $4$. Then, if $c_0 = c_1 \\cdot 3$, the game lasts until the whole string is removed, and the first player loses. If $c_0 < c_1 \\cdot 3$, the first player runs out of moves before the second, and if $c_0 > c_1 \\cdot 3$, the second player runs out of moves first. So, if the length of the string is divisible by $4$, the first player wins iff $c_0 > c_1 \\cdot 3$. If the length of the string is not divisible by $4$, then we can derive a similar condition, but it will depend on the remainder of the length modulo $4$. For example, let's derive a condition for the case when the length is equal to $3$ modulo $4$. We need to derive a threshold like \"if $c_0 \\ge f(c_1)$, the first player wins, otherwise the second player wins\". Suppose we made $\\lfloor \\frac{|s|}{4} \\rfloor$ moves for both players. Then we have removed some $x$ characters equal to 1 and $3x$ characters equal to 0. If the resulting string has at least $2$ characters equal to 0, then the first player wins, otherwise the second player wins. So, if $c_0 - 3 = c_1 \\cdot 3$ or $c_0 - 2 = (c_1 - 1) \\cdot 3$, then the first player wins. We can rewrite this condition to $c_0 \\ge c_1 \\cdot 3 - 1$: if it is met, then the first player wins (either the string gets reduced to size $3$ and the first player can make a move, or the second player runs out of 1's before that). We can derive similar conditions for $|s| \\bmod 4 = 1$ and $|s| \\bmod 4 = 2$. All of them have the form $c_0 > c_1 \\cdot 3 + k$, where $k$ is some constant depending on $|s| \\bmod 4$. You can either derive them analytically, or write a dynamic programming to check all strings with length $\\le 20$ and derive this constant $k$ for every remainder from this dynamic programming. The only issue is that we have allowed the players to take non-adjacent characters. For the second player, it does not matter: that player always wants to take one 0 and one 1, and if there are at least one pair of different characters in the string, there is at least one substring 10 or 01. However, for the first player, this might be an issue: we have allowed to remove two characters equal to 0 even if there is no substring 00. We can prove that the result of the game does not depend on it. If the first player cannot make a move according to the rules of the original game (there is no substring 00, and either the first or the last character is 1), then $c_0 \\le c_1$. And since every pair of moves removes three 0's and one 1, the first player will run out of moves before the second player even if the first player is allowed to remove non-adjacent character. Okay, now the problem reduces to the following: for every remainder of length $i$ modulo $4$, there is some constant $k_i$, and we have to calculate the number of substrings $s[l:r]$ such that: $(r - l + 1) \\bmod 4 = i$; in $s[l:r]$, $c_0 > c_1 \\cdot 3 + k_i$. Let's replace every character 1 with the integer $-3$, and every character 0 with the integer $1$. Then, the condition $c_0 > c_1 \\cdot 3 + k_i$ means that $sum[l:r] > k_i$, where $sum[l:r]$ is the sum on segment $[l, r]$ of the resulting array. To calculate the number of such subarrays efficiently, we can build the prefix sums over the array (let the sum of first $i$ elements be $p_i$), and rewrite this condition as $p_{r+1} - p_l > k_i$. Let's go through prefix sums from left to right and maintain four data structures $D_0, D_1, D_2, D_3$, where $D_i$ stores the sums on prefixes $p_j$ we met earlier such that $j \\bmod 4 = i$. When we process the prefix $p_x$, for each of these data structures $D_i$, we need to calculate the number of values $v$ in it such that $p_x - v > k_{(x-i) \\bmod 4}$, or $v < p_x - k_{(x-i) \\bmod 4}$. Then, we need to add $p_x$ into the data structure $D_{x \\bmod 4}$. Which data structure we need? It should support operations like \"insert an element\" and \"get the number of elements less than some value $x$\". You can use something like an order statistics tree, a Fenwick tree or a Segment tree. Note that you have to insert negative elements up to $-3 \\cdot n$, so if you use a Fenwick tree or a Segment tree, you should add $3n$ to all values you insert there. This solution works in $O(n \\log n)$. You can actually speed this up by merging these data structures into one and/or getting rid of the $O(\\log n)$ altogether using the fact that every next query you make is pretty close to the previous query, but this was not needed.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 300003;\nconst int M = 3 * N;\nconst int S = 4 * N;\n \nstruct segtree\n{\n    vector<int> T;\n \n    void add(int v, int l, int r, int pos, int val)\n    {\n        T[v] += val;\n        if(l != r - 1)\n        {\n            int m = (l + r) / 2;\n            if(pos < m) add(v * 2 + 1, l, m, pos, val);\n            else add(v * 2 + 2, m, r, pos, val);\n        }\n    }\n \n    int get(int v, int l, int r, int L, int R)\n    {\n        if(L >= R) return 0;\n        if(l == L && r == R) return T[v];\n        int m = (l + r) / 2;\n        return get(v * 2 + 1, l, m, L, min(m, R)) + get(v * 2 + 2, m, r, max(m, L), R);\n    }\n \n    int getSumLess(int l)\n    {\n        return get(0, 0, S, 0, l + M);\n    }\n \n    void add(int pos, int val)\n    {\n        add(0, 0, S, pos + M, val);\n    }\n \n    segtree()\n    {\n        T.resize(4 * S);\n    }\n};\n \nint threshold[] = {0, 1, 1, -2};\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n    vector<int> p(n + 1);\n    for(int i = 0; i < n; i++)\n        p[i + 1] = p[i] + (s[i] == '1' ? -3 : 1);\n    vector<segtree> trees(4);\n    long long ans = 0;\n    for(int i = 0; i <= n; i++)\n    {\n        for(int j = 0; j < 4; j++)\n        {\n            int len = (i - j + 4) % 4;\n            int bound = p[i] - threshold[len];\n            ans += trees[j].getSumLess(bound); \n        }\n        trees[i % 4].add(p[i], 1);\n    }\n    cout << ans << endl;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "games",
      "greedy",
      "math"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2070",
    "index": "F",
    "title": "Friends and Pizza",
    "statement": "Monocarp has $n$ pizzas, the $i$-th pizza consists of $a_i$ slices. Pizzas are denoted by uppercase Latin letters from A to the $n$-th letter of the Latin alphabet.\n\nMonocarp also has $m$ friends, and he wants to invite \\textbf{exactly two} of them to eat pizza. For each friend, Monocarp knows which pizzas that friend likes.\n\nAfter the friends arrive at Monocarp's house, for each pizza, the following happens:\n\n- if the pizza is not liked by any of the two invited friends, Monocarp eats it;\n- if the pizza is liked by exactly one of the two invited friends, that friend eats it;\n- and if the pizza is liked by both friends, they try to split it. If it consists of an even number of slices, they both eat exactly half of the slices. But if the pizza consists of an odd number of slices, they start quarrelling, trying to decide who will eat an extra slice — and Monocarp doesn't like that.\n\nFor each $k$ from $0$ to $\\sum a_i$, calculate the number of ways to choose \\textbf{exactly two friends} to invite so that the friends don't quarrel, and Monocarp eats exactly $k$ slices.",
    "tutorial": "Before solving this problem, I highly recommend that you learn Sum over Subsets Dynamic Programming (aka SOS DP), if you don't know it yet. For example, you can use this CF blog, it has a great explanation of SOS DP: https://codeforces.com/blog/entry/45223 First, we will somewhat change the problem. The original problem wants us to consider all pairs of friends $(i, j)$ where $1 \\le i < j \\le n$; but instead, we will consider all pairs of friends where $1 \\le i, j \\le n$ (so, $i$ can be greater than $j$ and can even be equal to $j$). After solving this modified version, we can \"subtract\" all pairs where $i=j$ (since there are only $O(m)$ of them) and divide all the answers by $2$ to get rid of the pairs where $i>j$ (they are symmetrical to $i<j$, so they yield the same answer). From now on, we consider only the version where we need to count all pairs of friends. For every friend, we can transform the string $s_i$ into a bit mask which shows what pizzas that friend likes. Then, checking if the friends quarrel and which pizzas they will eat can be done by bit operations on their masks: if the bitwise AND of their masks and the mask of odd-size pizzas is non-zero, there is at least one odd-size pizza they both like, so they will quarrel; and the mask of pizzas they will eat is just the bitwise OR of their masks. So, if for each mask, we want to calculate the number of pairs of friends which don't quarrel and result in exactly that mask being eaten, we can run the following code: Or, if for each mask, we calculate $c_i$ as the number of friends having that mask, we can rewrite it as follows: Let's first consider two special instances of this problem, and then we'll combine their solutions to solve the general case. Instance 1. What if all pizzas have even sizes? Then our mask of add pizzas is $0$, so friends will never quarrel. In this case, we can rewrite the \"naive\" code as follows: This is an OR convolution of the sequence $c$ with itself, and it can be calculated much faster than $O(4^n)$. When dealing with regular convolutions, a fast way to calculate them is the following one: Transform the sequences using FFT or NTT. Multiply the corresponding elements of the transformed sequences. Perform the inverse transformation. OR convolution can be done in the same way, but instead of FFT or NTT, we will use SOS DP. So, an OR convolution of two sequences $a$ and $b$ looks like that: Why does SOS DP do the trick? $C_i = A_i \\cdot B_i$ means that $C_i$ is the sum of $a_j \\cdot b_k$ over all $j$ and $k$ that are submasks of $i$. For some pairs $(j, k)$, their bitwise OR is exactly $i$; but for others, their bitwise OR is a submask of $i$. So, actually, $C_i$ is the sum over submasks of the sequence we need to obtain, so by applying inverse SOS DP (the transformation which returns the sequence by its sums over submasks), we get exactly what we need. Quick note about inverse SOS DP - it is done the same as the regular SOS DP, but with subtractions instead of additions. You can prove it by trying to \"rollback\" the changes the regular SOS DP does to a sequence. Okay, the instance when all pizzas have even size is done. Next, we have Instance 2. What if all pizzas have odd sizes? The \"naive\" code would look like that: Unfortunately, this is much trickier. This is called Fast Subset Convolution, and to do it faster, we have to add another dimension to our sequence. Now suppose we want to get the FSC of sequences $a$ and $b$, and the resulting sequence is named $c$. If the bitwise OR of $i$ and $j$ is $k$, and the bitwise AND of $i$ and $j$ is $0$, then $popcount(k)$ (the number of bits set to $1$ in $k)$ is equal to $popcount(i) + popcount(j)$. So, the value of $c_k$ can be represented as the sum of $a_i \\cdot b_j$ over all such $i, j$ that the bitwise OR of $i$ and $j$ is $k$, and $popcount(k) = popcount(i) + popcount(j)$. Let's transform our given sequences of length $2^n$ into two-dimensional matrices of size $(n + 1) \\times (2^n)$. Let $a'_{x,i}$ be $0$ if $popcount(i) \\ne x$, or $a_i$ if $popcount(i) = x$. Similarly, we denote $b'_{y,j}$ based on $b$. Okay, now let's try to make it so that, in the resulting convolution, the product $a'_{x,i} \\cdot b'_{y,j}$ ends up in the cell $c'_{x+y, i \\lor j}$, where $\\lor$ denotes bitwise OR. To do this, let's evaluate the $k$-th row of $c'$ as the following sum: $\\sum_{i=0}^k \\text{ORConvolution}(a'_i, b'_{k-i})$. The OR Convolution will make sure that, for every pair of $i, j$, $a_i \\cdot b_j$ ends up in some cell of the form $c'_{k, i \\lor j}$, and to verify that their bitwise AND is $0$, we can check that $k = popcount(i \\lor j)$. So, the resulting value of $c_i$ we want to get is equal to $c'_{popcount(i),i}$. This Fast Subset Convolution can be done in $O(n^2 2^n)$ if you apply SOS DP to every row of $a'$ and $b'$ to get matrices with sums over submasks in each row (let's call them $A$ and $B$), calculate $C_{k,i} = \\sum \\limits_{j=0}^k A_{j,i} \\cdot B_{k-j,i}$, and then apply Inverse SOS DP to each row of $C$ to get the matrix $c'$. Okay, now back to the original problem. Instance 3. What if some pizzas have odd size, and others have even size? We need to make a convolution for which some bits (represending even-sized pizzas) work as in OR Convolution, but other bits (representing odd-sized pizzas) work as in Fast Subset Convolution. The key idea is that we can modify Fast Subset Convolution so that it tracks only the number of bits representing odd-sized pizzas. So, let's define $F(x)$ as the number of bits representing odd-sized pizzas in $x$. So, when we transform the given sequences $a$ and $b$ to the matrices $a'$ and $b'$, we set $a'_{x,i}$ to $0$ if $F(i) \\ne x$, or $a_i$ if $F(i) = x$. And our matrices will have size $(p+1) \\times (2^n)$, where $p$ is the number of odd-sized pizzas. Note that, in our problem, the sequences $a$ and $b$ are the same, so the matrix $b'$ is actually the same as $a'$. Similarly, to get the sequence $c$ from the matrix $c'$, we set $c_i = c'_{F(i), i}$. This modification of Fast Subset Convolution works in $O(p \\cdot n \\cdot 2^n)$. Since $p \\le n$, we get a solution working in $O(n^2 2^n + mn)$ (the $O(mn)$ summand comes from processing the friends and converting them into masks).",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;             \n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int n, m;\n    cin >> n >> m;\n    vector<long long> cnt(1 << n);\n    for(int i = 0; i < m; i++)\n    {\n        string s;\n        cin >> s;\n        int mask = 0;\n        for(auto c : s) mask += (1 << (c - 'A'));\n        cnt[mask]++;\n    }\n    vector<int> a(n);\n    for(int i = 0; i < n; i++)\n        cin >> a[i];\n \n    vector<bool> odd(n);\n    int odd_pizzas = 0;\n    int odd_mask = 0;\n    for(int i = 0; i < n; i++)\n        if(a[i] % 2 == 1)\n        {\n            odd[i] = true;\n            odd_pizzas++;\n            odd_mask += (1 << i);\n        }\n \n    // calculating the number of bits representing odd-sized pizzas in each mask\n    vector<int> cnt_odd(1 << n);\n    for(int i = 0; i < (1 << n); i++)\n        for(int j = 0; j < n; j++)\n            if(odd[j] && ((i >> j) & 1) == 1)\n                cnt_odd[i]++;\n \n    // transforming the sequence a to a' (and b to b', since a and b are the same)\n    vector<vector<long long>> A(odd_pizzas + 1, vector<long long>(1 << n, 0ll));\n    for(int i = 0; i < (1 << n); i++)\n        A[cnt_odd[i]][i] = cnt[i];\n \n    // applying SOS DP to every row of the matrix\n    for(int k = 0; k <= odd_pizzas; k++)\n        for(int i = 0; i < n; i++)\n            for(int j = 0; j < (1 << n); j++)\n                if((j >> i) & 1)\n                    A[k][j] += A[k][j ^ (1 << i)];\n \n    // getting the SOS DP of the matrix c' from the editorial\n    vector<vector<long long>> B(odd_pizzas + 1, vector<long long>(1 << n, 0ll));\n    for(int x = 0; x <= odd_pizzas; x++)\n        for(int y = 0; y <= odd_pizzas - x; y++)\n            for(int i = 0; i < (1 << n); i++)\n                B[x + y][i] += A[x][i] * A[y][i];\n \n    // applying inverse SOS DP to every row\n    for(int k = 0; k <= odd_pizzas; k++)\n        for(int i = 0; i < n; i++)\n            for(int j = 0; j < (1 << n); j++)\n                if((j >> i) & 1)\n                    B[k][j] -= B[k][j ^ (1 << i)];\n \n    int size_ans = 0;\n    for(auto x : a) size_ans += x;\n    vector<long long> ans(size_ans + 1);\n    for(int i = 0; i < (1 << n); i++)\n    {\n        long long cur_cnt = B[cnt_odd[i]][i];\n        int sum = 0;\n        for(int j = 0; j < n; j++)\n            if((i >> j) & 1)\n                sum += a[j];\n        ans[sum] += cur_cnt;\n    }\n \n    for(int i = 0; i < (1 << n); i++)\n    {\n        if(i & odd_mask) continue;\n        int sum = 0;\n        for(int j = 0; j < n; j++)\n            if((i >> j) & 1)\n                sum += a[j];\n        ans[sum] -= cnt[i];\n    }\n    \n    reverse(ans.begin(), ans.end());\n    \n    for(auto x : ans) cout << x / 2 << \" \";\n    cout << endl;\n}",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "dp",
      "fft"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2071",
    "index": "A",
    "title": "The Play Never Ends",
    "statement": "Let's introduce a two-player game, table tennis, where a winner is always decided and draws are impossible.\n\nThree players, Sosai, Fofo, and Hohai, want to spend the rest of their lives playing table tennis. They decided to play forever in the following way:\n\n- In each match, two players compete while the third spectates.\n- To ensure fairness, no player can play three times in a row. The player who plays twice in a row must sit out as a spectator in the next match, which will be played by the other two players. Otherwise, the winner and the spectator will play in the next match, while the loser will spectate.\n\nNow, the players, fully immersed in this infinite loop of matches, have tasked you with solving the following problem:\n\nGiven an integer $k$, determine whether the spectator of the first match can be the spectator in the $k$-th match.",
    "tutorial": "When Fofo is the spectator of the first match, what is the earliest subsequent game in which he will spectate again? Suppose Sosai wins the first game. What becomes clear? Once the winner of the first match is decided, the rest of the game is completely predictable. For example, if Hohai wins the first match which Fofo spectated, we can see that: ${}$ $\\text{Sosai} \\overset{\\text{Spectator of 1st: Fofo}}{\\longleftrightarrow} \\text{Hohai}$ $\\text{Fofo} \\overset{\\text{Spectator of 2nd: Sosai}}{\\longleftrightarrow} \\text{Hohai}$ $\\text{Fofo} \\overset{\\text{Spectator of 3rd: Hohai}}{\\longleftrightarrow} \\text{Sosai}$ $\\text{Hohai} \\overset{\\text{Spectator of 4th: Fofo}}{\\longleftrightarrow} \\text{Sosai}$ $\\text{Hohai} \\overset{\\text{Spectator of 5th: Sosai}}{\\longleftrightarrow} \\text{Fofo}$ $\\text{Sosai} \\overset{\\text{Spectator of 6th: Hohai}}{\\longleftrightarrow} \\text{Fofo}$ $\\text{Sosai} \\overset{\\text{Spectator of 7th: Fofo}}{\\longleftrightarrow} \\text{Hohai}$ No matter who wins in the second match, Hohai won't be able to continue playing in the third match (even if he wins the second match) since he has already played two times in a row. Similarly, Fofo won't be able to play in the fourth match because he has already played twice in a row, regardless of the match result. As a result, Fofo won't be able to spectate in the $k$-th match for any $k$ of the form $3x + 1$. The overall time complexity is: $O(1)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    int k;\n    cin >> k;\n    if (k % 3 == 1) {\n        cout << \"Yes\\n\";\n    } else {\n        cout << \"No\\n\";\n    }\n}\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int tt = 1;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2071",
    "index": "B",
    "title": "Perfecto",
    "statement": "A permutation $p$ of length $n$$^{\\text{∗}}$ is perfect if, for each index $i$ ($1 \\le i \\le n$), it satisfies the following:\n\n- The sum of the first $i$ elements $p_1 + p_2 + \\ldots + p_i$ is \\textbf{not} a perfect square$^{\\text{†}}$.\n\nYou would like things to be perfect. Given a positive integer $n$, find a perfect permutation of length $n$, or print $-1$ if none exists.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$A perfect square is an integer that is the square of an integer, e.g., $9=3^2$ is a perfect square, but $8$ and $14$ are not.\n\\end{footnotesize}",
    "tutorial": "Consider the identity permutation, defined by $p_i = i$. When and why does this permutation not work? The smallest index $i$ where the issue occurs must satisfy the condition that $1 + \\ldots + i$ is a perfect square. What is the simplest and most efficient way to resolve this issue? The first observation is that if the sum $1 + 2 +  \\dots  + n = \\frac{n(n+1)}{2}$ is a perfect square, no valid perfect permutation exists. To prove that a solution always exists otherwise, start with the identity permutation $p_i = i$ and iterate through indices from $1$ to $n$. We keep on iterating as long as the prefix sum till that moment isn't a perfect square. If the prefix sum up to index $k$ becomes a perfect square, $\\frac{k(k+1)}{2} = x^2$, swap $p_k$ and $p_{k + 1}$. This changes the prefix sum to $x^2 + 1$, which is not a perfect square. To ensure this method works, we must show that $\\frac{(k+1)(k+2)}{2}$ cannot also be a perfect square. Assume for contradiction that $\\frac{(k+1)(k+2)}{2} = y^2$. Then: $y^2 = x^2 + k + 1$ Since $x > \\frac{k}{2}$ (because $x^2 = \\frac{k(k+1)}{2} > \\frac{k^2}{4}$), we have: ${}$ $y^2 = x^2 + k + 1 < x^2 + 2x + 1 = (x+1)^2 \\le y^2$ which is a contradiction. Thus, $\\frac{(k+1)(k+2)}{2}$ cannot be a perfect square, and the process can be repeated until all indices are processed, ensuring a valid permutation. The overall time complexity is: $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    auto check = [&](int k) {\n        int j = sqrtl((int64_t)k * (k + 1) / 2);\n        return ((int64_t)j * j != (int64_t)k * (k + 1) / 2);\n    };\n    int n;\n    cin >> n;\n    if (!check(n)) {\n        cout << \"-1\\n\";\n        return;\n    }\n    vector<int> ans(n + 1);\n    for (int i = 1; i <= n; i++) {\n        ans[i] = i;\n    }\n    int j = 0;\n    for (int i = 1; i <= n; i++) {\n        while ((int64_t)j * j < (int64_t)i * (i + 1) / 2) j++;\n        if ((int64_t)j * j == (int64_t)i * (i + 1) / 2) {\n            swap(ans[i], ans[i + 1]);\n        }\n        cout << ans[i] << \" \";\n    }\n    cout << \"\\n\";\n}\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int tt = 1;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2071",
    "index": "C",
    "title": "Trapmigiano Reggiano",
    "statement": "In an Italian village, a hungry mouse starts at vertex $\\textrm{st}$ on a given tree$^{\\text{∗}}$ with $n$ vertices.\n\nGiven a permutation $p$ of length $n$$^{\\text{†}}$, there are $n$ steps. For the $i$-th step:\n\n- A tempting piece of Parmesan cheese appears at vertex $p_i$. If the mouse is currently at vertex $p_i$, it will stay there and enjoy the moment. Otherwise, it will move along the simple path to vertex $p_i$ \\textbf{by one edge}.\n\nYour task is to find such a permutation so that, after all $n$ steps, the mouse inevitably arrives at vertex $\\textrm{en}$, where a trap awaits.\n\nNote that the mouse must arrive at $\\textrm{en}$ after all $n$ steps, though it may pass through $\\textrm{en}$ earlier during the process.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\n$^{\\text{†}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "Root the tree at vertex $\\textrm{en}$. What observations can you make? Can the cheese be placed at the vertices in a specific sequence that prevents the mouse from moving farther away from vertex $\\textrm{en}$? First, root the tree at vertex $\\textrm{en}$ and approach it step by step. Observe that after processing all vertices at the largest depth $n-1$, the mouse's current depth cannot exceed $n-1$. By repeating this process for the next largest depth $n-2$, the mouse's depth will inevitably become $n-2$ or less. Continuing this way, we process vertices in descending order of depth until we reach the root, achieving the desired result. The overall time complexity is: $O(n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    int n, s, e;\n    cin >> n >> s >> e;\n    vector adj(n + 1, vector<int> ());\n    for (int i = 1; i < n; i++) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v), adj[v].push_back(u);\n    }\n    vector dis(n + 1, vector<int> ());\n    vector<int> d(n + 1);\n    auto dfs = [&](auto &&self, int v, int par) -> void {\n        d[v] = d[par] + 1;\n        dis[d[v]].push_back(v);\n        for (int u: adj[v]) {\n            if (u == par) continue;\n            self(self, u, v);\n        }\n    };\n    dfs(dfs, e, 0);\n    for (int i = n; i >= 1; i--) {\n        for (int j: dis[i]) {\n            cout << j << \" \";\n        }\n    }\n    cout << \"\\n\";\n}\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int tt = 1;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "dfs and similar",
      "dp",
      "greedy",
      "sortings",
      "trees"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2071",
    "index": "D1",
    "title": "Infinite Sequence (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $l=r$. You can hack only if you solved all versions of this problem.}\n\nYou are given a positive integer $n$ and the first $n$ terms of an infinite binary sequence $a$, which is defined as follows:\n\n- For $m>n$, $a_m = a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_{\\lfloor \\frac{m}{2} \\rfloor}$$^{\\text{∗}}$.\n\nYour task is to compute the sum of elements in a given range $[l, r]$: $a_l + a_{l + 1} + \\ldots + a_r$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\oplus$ denotes the bitwise XOR operation.\n\\end{footnotesize}",
    "tutorial": "Try to determine the connection between $a_{2m}$ and $a_{2m+1}$ for indices where $2m > n$. Try to express $a_{2m}$ as the XOR of a short prefix of terms plus at most one extra term. For convenience, assume $n$ is odd (if not, increment $n$ and handle the edge case separately). Start by precomputing the first $2n$ terms $a_1, a_2, \\ldots, a_{2n}$. For queries with indices less than or equal to $2n$, directly return the precomputed value. For $2m>n$, observe the following relationship $a_{2m} = a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_m = a_{2m + 1}.$ Define $p = a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n$. Notice that when $m > n$, we can decompose the XOR sum as: ${}$ $a_{2m} = a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_m = a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n \\oplus (a_{n + 1} \\oplus a_{n + 2}) \\oplus (a_{n + 3} \\oplus a_{n + 4}) \\oplus \\ldots \\oplus a_m$ $a_{2m} = p \\oplus (a_{n + 1} \\oplus a_{n + 2}) \\oplus (a_{n + 3} \\oplus a_{n + 4}) \\oplus \\ldots \\oplus a_m$ Since $n$ is odd, the pairs $(a_{n + 1} \\oplus a_{n + 2}), (a_{n + 3} \\oplus a_{n + 4}), \\ldots$ cancel out. This simplifies the formula to: ${}$ $a_{2m} = a_{2m + 1} = \\begin{cases} p & \\text{if } m \\text{ is odd}, \\\\ p \\oplus a_m & \\text{if } m \\text{ is even}. \\end{cases}$ As a result, we can compute $a_m$ recursively by halving $m$ until $m \\le 2n$, applying the parity rule at each step. The overall time complexity is: $O(n+\\log(m))$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    int n;\n    int64_t l, r;\n    cin >> n >> l >> r;\n    vector<int> a(n + 1);\n    for (int i = 1; i <= n; i++) {\n        cin >> a[i];\n    }\n    vector<int> pref(n + 1);\n    for (int i = 1; i <= n; i++) {\n        pref[i] = pref[i - 1] + a[i];\n    }\n    if (n % 2 == 0) {\n        n++;\n        int cur = pref[n / 2] & 1;\n        a.push_back(cur);\n        pref.push_back(pref.back() + cur);\n    }\n    for (int i = n + 1; i <= n * 2; i++) {\n        a.push_back(pref[i / 2] & 1);\n        pref.push_back(pref[i - 1] + a[i]);\n    }\n    int p = pref[n] & 1;\n    auto get = [&](int64_t x) {\n        int ret = 0;\n        while (true) {\n            if (x <= n * 2) {\n                ret ^= a[x];\n                break;\n            }\n            ret ^= p;\n            if ((x / 2 - n) % 2 == 0) {\n                break;\n            }\n            x /= 2;\n        }\n        return ret;\n    };\n    cout << get(l) << \"\\n\";\n}\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int tt = 1;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2071",
    "index": "D2",
    "title": "Infinite Sequence (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $l\\le r$. You can hack only if you solved all versions of this problem.}\n\nYou are given a positive integer $n$ and the first $n$ terms of an infinite binary sequence $a$, which is defined as follows:\n\n- For $m>n$, $a_m = a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_{\\lfloor \\frac{m}{2} \\rfloor}$$^{\\text{∗}}$.\n\nYour task is to compute the sum of elements in a given range $[l, r]$: $a_l + a_{l + 1} + \\ldots + a_r$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\oplus$ denotes the bitwise XOR operation.\n\\end{footnotesize}",
    "tutorial": "Generalize the recursive method for evaluating an index to handle the computation of the prefix sum. First, check the editorial of D1. To upgrade the solution, we define a recursive function: $\\text{sum}(m) = \\left( \\displaystyle\\sum_{\\substack{i \\leq m \\\\ i \\text{ even}}} a_i,\\; \\displaystyle\\sum_{\\substack{i \\leq m \\\\ i \\text{ odd}}} a_i \\right).$ We precompute the even and odd prefix sums for $m \\le 2n$. For $m > 2n$, the term $a_m$ follows: ${}$ $a_m = \\begin{cases} p & \\text{if } \\lfloor \\frac{m}{2} \\rfloor \\text{ is odd}, \\\\ p \\oplus a_{\\lfloor \\frac{m}{2} \\rfloor} & \\text{if } \\lfloor \\frac{m}{2} \\rfloor \\text{ is even}. \\end{cases}$ For simplicity, assume $m \\equiv 1 \\pmod{4}$ (if not, keep incrementing $m$ and adjusting its contribution separately). Define $e = \\displaystyle\\sum_{\\substack{n < i \\leq \\lfloor \\frac{m}{2} \\rfloor \\\\ i \\text{ even}}} a_i = a_{n+1} + a_{n+3} + \\dots + a_{\\lfloor \\frac{m}{2} \\rfloor}$ This sum can be expressed as: $e = \\text{sum}(\\lfloor \\frac{m}{2} \\rfloor)_{\\text{even}} - prefix_{\\text{even}}(n).$ The pairs we're interested in computing are (keep in mind that $n$ is odd): ${}$ $a_{2n} = a_{2n + 1} = p$ $a_{2n + 2} = a_{2n + 3} = p \\oplus a_{n + 1}$ $a_{2n + 4} = a_{2n + 5} = p$ $a_{2n + 6} = a_{2n + 7} = p \\oplus a_{n + 3}$ $\\vdots$ $a_{m - 3} = a_{m - 2} = p$ $a_{m - 1} = a_{m} = p \\oplus a_{\\lfloor \\frac{m}{2} \\rfloor}$ Notice that the sums of the above even and odd indices are equal, and depend on $p$: ${}$ $both = \\begin{cases} e & \\text{if } p = 0, \\\\ (\\lfloor \\frac{m}{2} \\rfloor - n + 1) - e & \\text{if } p = 1. \\end{cases}$ Thus, the final sums are: $\\text{sum}(m)_{\\text{even}} = prefix_{\\text{even}}(2n - 1) + both$ $\\text{sum}(m)_{\\text{odd}} = prefix_{\\text{odd}}(2n - 1) + both$ As a result, we can compute $\\text{sum}(m)$ recursively by halving $m$ until $m \\le 2n$, benefitting the precomputed even and odd prefix sums at each step. The overall time complexity is: $O(n+\\log(m))$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nvoid solve() {\n    int n;\n    int64_t l, r;\n    cin >> n >> l >> r;\n    vector<int> a(n + 1);\n    for (int i = 1; i <= n; i++) {\n        cin >> a[i];\n    }\n    vector<int> pref(n + 1);\n    for (int i = 1; i <= n; i++) {\n        pref[i] = pref[i - 1] + a[i];\n    }\n    if (n % 2 == 0) {\n        n++;\n        int cur = pref[n / 2] & 1;\n        a.push_back(cur);\n        pref.push_back(pref.back() + cur);\n    }\n    for (int i = n + 1; i <= n * 2; i++) {\n        a.push_back(pref[i / 2] & 1);\n        pref.push_back(pref[i - 1] + a[i]);\n    }\n    vector<int> even(n * 2 + 1);\n    for (int i = 1; i <= n * 2; i++) {\n        even[i] = even[i - 1] + (i & 1 ? 0 : a[i]);\n    }\n    int p = pref[n] & 1;\n    auto get = [&](int64_t x) {\n        int ret = 0;\n        while (true) {\n            if (x <= n * 2) {\n                ret ^= a[x];\n                break;\n            }\n            ret ^= p;\n            if ((x / 2 - n) % 2 == 0) {\n                break;\n            }\n            x /= 2;\n        }\n        return ret;\n    };\n    auto sum = [&](auto&& self, int64_t m) -> pair<int64_t, int64_t> {// {sum even, sum odd}\n        if (m <= n * 2) {\n            return {even[m], pref[m] - even[m]};\n        }\n        int64_t eve = even[n * 2 - 1], odd = pref[n * 2 - 1] - eve;\n        if (m % 2 == 0) {\n            m += 1, odd -= get(m);\n        }\n        if (m / 2 % 2) {\n            m += 1, eve -= get(m);\n            m += 1, odd -= get(m);\n        }\n        auto [e, _] = self(self, m / 2);\n        e -= even[n];\n        int64_t c = m / 2 - n + 1, both = (p ? c - e : e);\n        eve += both, odd += both;\n        return {eve, odd};\n    };\n    int64_t ans = 0;\n    auto [re, ro] = sum(sum, r);\n    ans += re + ro;\n    auto [le, lo] = sum(sum, l - 1);\n    ans -= le + lo;\n    cout << ans << \"\\n\";\n}\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int tt = 1;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "data structures",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2071",
    "index": "E",
    "title": "LeaFall",
    "statement": "You are given a tree$^{\\text{∗}}$ with $n$ vertices. Over time, each vertex $i$ ($1 \\le i \\le n$) has a probability of $\\frac{p_i}{q_i}$ of falling. Determine the expected value of the number of unordered pairs$^{\\text{†}}$ of \\textbf{distinct} vertices that become leaves$^{\\text{‡}}$ in the resulting forest$^{\\text{§}}$, modulo $998\\,244\\,353$.\n\nNote that when vertex $v$ falls, it is removed along with all edges connected to it. However, adjacent vertices remain unaffected by the fall of $v$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\n$^{\\text{†}}$An unordered pair is a collection of two elements where the order in which the elements appear does not matter. For example, the unordered pair $(1, 2)$ is considered the same as $(2, 1)$.\n\n$^{\\text{‡}}$A leaf is a vertex that is connected to exactly one edge.\n\n$^{\\text{§}}$A forest is a graph without cycles\n\\end{footnotesize}",
    "tutorial": "Think about an unordered pair $(u, v)$ where both u and v are leaves in the final forest. Consider dividing all such pairs into separate categories based on their relationship in the original tree. Let the first category be the pairs that are directly connected (neighbors), and analyze under what conditions both vertices become leaves. For the pairs that are not direct neighbors, focus on those that share a common neighbor. Investigate how the state (fallen or not) of their neighbors influences the possibility of both vertices becoming leaves. Let $fall_{i}$ denote the probability that the $i$-th node falls. We partition the unordered pairs $(u,v)$ into three categories: $u$ and $v$ are direct neighbors. $u$ and $v$ share a common neighbor. Pairs that do not satisfy the first two conditions. Now, let us analyze the contribution of the first category to the final answer. For a pair $(u,v)$ of direct neighbors, both vertices become leaves if neither $u$ nor $v$ falls and if all of their other neighbors fall. Thus, the contribution of a specific pair $(u,v)$ is given by: ${}$ $contribution_1(u,v) = (1 - fall_{u}) \\cdot (1 - fall_{v}) \\cdot \\prod_{\\substack{k \\text{ is a neighbor of } u \\text{ or } v,\\, k \\neq u,\\, k \\neq v}} fall_{k}.$ The whole contribution of the first category is: ${}$ $\\sum_{(u,v) \\text{ are neighbors}} contribution_1(u,v).$ For the second category, $u$ and $v$ share a neighbor, so this shared neighbor either must be the only one not falling among the neighbors of $u$ and $v$, or it must fall and exactly one of the other neighbors of both $u$ and $v$ must not fall. Additionally, both $u$ and $v$ must not fall anyway. Therefore, the contribution for a pair $(u,v)$ in the second category is given by: ${}$ $e_i = (\\prod_{c \\text{ is a neighbor of } i, \\, c \\neq s} fall_{c}) \\cdot (\\sum_{c \\text{ is a neighbor of } i, \\, c \\neq s} \\frac{1 - fall_{c}}{fall_{c}})$ ${}$ $contribution_2(u,v) = (1 - fall_{u}) \\cdot (1 - fall_{v}) \\cdot (1 - fall_{s}) \\cdot \\prod_{\\substack{k \\text{ is a neighbor of } u \\text{ or } v,\\, k \\neq u,\\, k \\neq v,\\, k \\neq s }} fall_{k}$ ${}$ $+ (1 - fall_{u}) \\cdot (1 - fall_{v}) \\cdot (fall_{s}) \\cdot e_u \\cdot e_v$ where $s$ is the shared neighbor of $u$ and $v$. The whole contribution of the second category is: ${}$ $\\sum_{(u,v) \\text{ share a neighbor}} contribution_2(u,v).$ Moving to the third category: Here, $u$ and $v$ are neither direct neighbors nor do they share any common neighbor. In this case, the events that $u$ and $v$ become leaves are completely independent. Define $leaf_{i} = (1 - fall_{i}) \\cdot (\\prod_{c \\text{ is a neighbor of } i} fall_{c}) \\cdot (\\sum_{c \\text{ is a neighbor of } i} \\frac{1 - fall_{c}}{fall_{c}})$ as the probability that vertex $i$ becomes a leaf. Hence, for a pair $(u,v)$ in this category, the contribution is given by: ${}$ $contribution_3(u,v) = leaf_{u} \\cdot leaf_{v}.$ The whole contribution of the third category is: ${}$ $\\sum_{(u,v) \\in \\text{third category}} contribution_3(u,v).$ The final answer is obtained by summing the contributions from all three categories. We can compute the contribution of the third category by summing $leaf_{i} \\cdot leaf_{j}$ for all pairs $(i, j)$ with $i < j$, and then subtracting the contributions corresponding to pairs that satisfy one of the first two categories. The contribution of the second category can be computed by iterating over each node and accumulating the contributions from its neighbors (since these pairs share that node as their only common neighbor). The contribution of the first category can be computed in linear time too. The overall time complexity is $O(n \\cdot \\log M)$, where the $\\log$ factor arises from the modular inverse computations.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nconst int mod = 998244353;\nint add(int x, int y) {\n    return x + y - (x + y >= mod) * mod;\n}\nvoid add2(int &x, int y) {\n    x += y;\n    if (x >= mod) x -= mod;\n}\nint mul(int x, int y) {\n    return int((int64_t)x * y % mod);\n}\nint sub(int x, int y) {\n    return x - y + (x < y) * mod;\n}\nvoid sub2(int &x, int y) {\n    x -= y;\n    if (x < 0) x += mod;\n}\nint pwr(int x, int y) {\n    int ret = 1;\n    while (y) {\n        if (y & 1) ret = mul(ret, x);\n        x = mul(x, x);\n        y /= 2;\n    }\n    return ret;\n}\nint inv(int x) {\n    return pwr(x, mod - 2);\n}\nint norm(int64_t x) {\n    x %= mod;\n    if (x < 0) x += mod;\n    return int(x);\n}\nvoid solve() {\n    int n;\n    cin >> n;\n    vector adj(n + 1, vector<int> ());\n    vector<int> p(n + 1);\n    for (int i = 1; i <= n; i++) {\n        int q;\n        cin >> p[i] >> q;\n        p[i] = mul(p[i], inv(q));\n        //here, p[i] is the probability that node i will fall\n    }\n    for (int i = 1; i < n; i++) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v), adj[v].push_back(u);\n    }\n    vector<int> p1(n + 1), p2(n + 1);\n    for (int i = 1; i <= n; i++) {\n        p1[i] = sub(1, p[i]);\n        for (int u: adj[i]) {\n            p1[i] = mul(p1[i], p[u]);\n        }\n        //p1[i] is the probability that node i won't fall, but all nodes around it will fall\n        for (int u: adj[i]) {\n            add2(p2[i], mul(p1[i], mul(inv(p[u]), sub(1, p[u]))));\n        }\n        //p2[i] is the probability that node i will be a leaf (it won't fall, all it's neighbors except one will fall)\n    }\n    int ans = 0, sum = 0;\n    for (int i = 1; i <= n; i++) {\n        add2(ans, mul(p2[i], sum));\n        add2(sum, p2[i]);\n    }\n    //take all contributions of unordered pairs \n    for (int i = 1; i <= n; i++) {\n        //recalculate the contribution of neighboring pairs \n        for (auto u: adj[i]) {\n            if (u < i) continue;\n            //avoid calculating the same pair probabilty twice\n            int pi = mul(p1[i], inv(p[u]));\n            //pi is the probability that every neighbour of i would fall except for u (not including the probability of u not falling down)\n            int pu = mul(p1[u], inv(p[i]));\n            //pu is the probability that every neighbour of u would fall except for i (not including the probability of i not falling down)\n            //this case is just a tree of 2 nodes, both of them are leaves\n            add2(ans, mul(pi, pu));\n            //subtract the old contribution\n            sub2(ans, mul(p2[i], p2[u]));\n        }\n        //recalculate the contribution of pairs with a shared neighbour which is node i (ie calculate the contribution for pairs u, v such that dis(u, v) = 2 and dis(u, i) = dis(v, i) = 1\n        sum = 0;\n        for (int u: adj[i]) {\n            sub2(ans, mul(sum, p2[u]));\n            add2(sum, p2[u]);\n            //subtract the old contribution \n        }\n        //p[i] doesn't fall\n        sum = 0;\n        for (int u: adj[i]) {\n            int pu = mul(p1[u], inv(p[i]));\n            //pu is the probability that node u is a leaf connected to node i\n            add2(ans, mul(sum, pu));\n            add2(sum, mul(pu, sub(1, p[i])));\n        }\n        //p[i] falls\n        sum = 0;\n        for (int u: adj[i]) {\n            int pu = sub(p2[u], mul(p1[u], mul(inv(p[i]), sub(1, p[i]))));\n            //pu is the probability that node u is a leaf not connected to node i\n            add2(ans, mul(sum, pu));\n            add2(sum, mul(pu, inv(p[i])));\n        }\n    }\n    cout << ans << \"\\n\";\n}\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int tt = 1;\n    cin >> tt;\n    while (tt--) {\n        solve();\n    }\n}\n",
    "tags": [
      "combinatorics",
      "dp",
      "probabilities",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2071",
    "index": "F",
    "title": "Towering Arrays",
    "statement": "An array $b = [b_1, b_2, \\ldots, b_m]$ of length $m$ is called $p$-towering if there exists an index $i$ ($1\\le i\\le m$) such that for every index $j$ ($1 \\le j \\le m$), the following condition holds: $$b_j \\ge p - |i - j|.$$\n\nGiven an array $a = [a_1, a_2, \\ldots, a_n]$ of length $n$, you can remove at most $k$ elements from it. Determine the maximum value of $p$ for which the remaining array can be made $p$-towering.",
    "tutorial": "Binary search on $p$. After fixing $p$, find the maximum $p$-towering subsequence. if we denote the set of indexes that correspond to the maximum \"increasing\" $p$-towering subsequence on prefix $i$ as $S_i$, then for any $i < n$: $S_i \\subseteq S_{i + 1}$. Let's do binary search on $p$. After fixing some $p$ our goal is to find the maximum $p$-towering subsequence and check if the length of that subsequence $s$ satisfies $n - s \\le k$. To find the maximum $p$-towering subsequence, for each index $i$ we will find the maximum $p$-towering subsequence such that the \"left\" part of that subsequence is in prefix $i$ and its right part is in suffix $i$. Let's focus only on prefixes, as the suffixes can be done similarly. So, for each prefix $i$ we want to find the maximum \"increasing\" $p$-towering subsequence. To do it, we will traverse the array from left to right and maintain the currently found maximum subsequence. The key idea here is that as you move from left to right you only need to add new elements to the \"increasing\" subsequence and never delete any (or, formally speaking, if we denote the set of indexes that correspond to maximum \"increasing\" $p$-towering subsequence on prefix $i$ as $S_i$, then for any $i < n$: $S_i \\subseteq S_{i + 1}$ (the proof is left to the reader). Before moving to the details of implementation, let's elaborate a bit on the previous paragraph. Consider the fifth test case from the sample; suppose the current $p = 7$; and we have just arrived at the tenth element (denoted with star $^*$). Before this position, the maximum \"increasing\" $p$-towering subsequence consists of the first, third, and fifth elements (denoted with underlines): $[\\underline{6}, 3, \\underline{8}, 5, \\underline{8}, 3, 2, 1, 2, 7^*, 1]$. Now we need to check if we can increase the size of the subsequence. Since $p = 7$, then we certainly can add the tenth element with value $7$ to the subsequence. However, since we add a new number to the subsequence, two numbers become available: the second one with value $3$ and the forth one with value $5$. Thus, after processing the tenth element, the maximum \"increasing\" $p$-towering subsequence will look like this: $[\\underline{6}, \\color{red}{\\underline{3}}, \\underline{8}, \\color{red}{\\underline{5}}, \\underline{8}, 3, 2, 1, 2, \\color{red}{\\underline{7}}^*, 1]$. So we need some way to find such \"new\" numbers that appear when we add some elements to the subsequence (like when the element with value $5$ becomes available from the example). To resolve this we first assign $a_i := p - a_i$ for each $i$. To find the positions that are becoming available, we can search for the rightmost non-positive element on the current prefix. Once found (suppose its index is $j$), decrease all elements on the prefix $j$ by one and assign $a_j := \\infty$ (to avoid this position in the future). All these operations can be performed with the help of a segment tree. This concludes the asymptotic complexity: $O(n \\log{C} \\log{n})$.",
    "code": "#include <bits/stdc++.h>\n\n#define len(a) (int)a.size()\n#define all(a) a.begin(), a.end()\n\nusing namespace std;\nconst int MAXI = 1e9 + 1e7;\n\nconst int MAXN = 2e5 + 100;\nstruct Node {\n    int min_on_subtree = 0, push_addition = 0;\n};\nNode t[MAXN * 4];\nint a[MAXN], pref[MAXN], suf[MAXN];\n\nclass Segtree {\nprivate:\n    int n;\n    void add_on_subtree(int u, int val) {\n        t[u].push_addition += val;\n        t[u].min_on_subtree += val;\n    }\n    void push(int u) {\n        if (t[u].push_addition) {\n            add_on_subtree(u * 2 + 1, t[u].push_addition);\n            add_on_subtree(u * 2 + 2, t[u].push_addition);\n            t[u].push_addition = 0;\n        }\n    }\n    void recalc(int u) {\n        t[u].min_on_subtree = min(t[u * 2 + 1].min_on_subtree, t[u * 2 + 2].min_on_subtree);\n    }\n    void update(int u, int l, int r, int pos, int val) {\n        if (l == r) {\n            t[u].min_on_subtree = val;\n        } else {\n            push(u);\n            int mid = (l + r) / 2;\n            if (pos <= mid)\n                update(u * 2 + 1, l, mid, pos, val);\n            else\n                update(u * 2 + 2, mid + 1, r, pos, val);\n            recalc(u);\n        }\n    }\n    void add_on_segment(int u, int l, int r, int ql, int qr, int val) {\n        if (ql <= l && r <= qr)\n            add_on_subtree(u, val);\n        else {\n            push(u);\n            int mid = (l + r) / 2;\n            if (ql <= mid)\n                add_on_segment(u * 2 + 1, l, mid, ql, qr, val);\n            if (qr > mid)\n                add_on_segment(u * 2 + 2, mid + 1, r, ql, qr, val);\n            recalc(u);\n        }\n    }\n    int find_prev_non_pos_put_inf(int u, int l, int r, int pos) {\n        if (t[u].min_on_subtree > 0)\n            return -1;\n        if (l == r) {\n            t[u].min_on_subtree = MAXI;\n            return l;\n        }\n        push(u);\n        int mid = (l + r) / 2, res = -1;\n        if (pos > mid)\n            res = find_prev_non_pos_put_inf(u * 2 + 2, mid + 1, r, pos);\n        if (res == -1)\n            res = find_prev_non_pos_put_inf(u * 2 + 1, l, mid, pos);\n        recalc(u);\n        return res;\n    }\npublic:\n    explicit Segtree(int n): n(n) {\n        fill(t, t + 4 * n, Node{MAXI, 0});\n    };\n\n    void update(int pos, int val) {\n        update(0, 0, n - 1, pos, val);\n    }\n    void add_on_segment(int ql, int qr, int val) {\n        add_on_segment(0, 0, n - 1, ql, qr, val);\n    }\n    int find_prev_non_pos_put_inf(int pos) {\n        return find_prev_non_pos_put_inf(0, 0, n - 1, pos);\n    }\n};\n\nvoid f(int n, int p, int *res) {\n    Segtree tree(n);\n    int cur_sz = 0;\n    for (int i = 0; i < n; i++) {\n        tree.update(i, p - a[i]);\n        int pos = i;\n        while ((pos = tree.find_prev_non_pos_put_inf(pos)) != -1) {\n            cur_sz++;\n            tree.add_on_segment(0, pos, -1);\n        }\n        res[i] = cur_sz;\n    }\n}\n\nint32_t main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n#ifndef ONLINE_JUDGE\n    freopen(\"input.txt\", \"r\", stdin);\n    freopen(\"output.txt\", \"w\", stdout);\n#endif\n    int testcases;\n    cin >> testcases;\n    while (testcases--) {\n        int n, k;\n        cin >> n >> k;\n        int max_a = -1;\n        for (int i = 0; i < n; i++) {\n            cin >> a[i];\n            max_a = max(max_a, a[i]);\n        }\n        int l = 0, r = max_a + 1;\n        while (l + 1 < r) {\n            int mid = (l + r) / 2;\n            f(n, mid, pref);\n            reverse(a, a + n);\n            f(n, mid, suf);\n            reverse(a, a + n);\n            reverse(suf, suf + n);\n            int mx = -1;\n            for (int i = 0; i < n; i++) {\n                if (a[i] >= mid)\n                    mx = max(mx, pref[i] + suf[i] - 1);\n            }\n            if (n - mx <= k)\n                l = mid;\n            else\n                r = mid;\n        }\n        cout << l << '\\n';\n    }\n}",
    "tags": [
      "binary search",
      "data structures"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2072",
    "index": "A",
    "title": "New World, New Me, New Array",
    "statement": "Natsume Akito has just woken up in a new world and immediately received his first quest! The system provided him with an array $a$ of $n$ zeros, an integer $k$, and an integer $p$.\n\nIn one operation, Akito chooses two integers $i$ and $x$ such that $1 \\le i \\le n$ and $-p \\le x \\le p$, and performs the assignment $a_i = x$.\n\nAkito is still not fully accustomed to controlling his new body, so help him calculate the minimum number of operations required to make the sum of all elements in the array equal to $k$, or tell him that it is impossible.",
    "tutorial": "In an array $a$ of length $n$ containing numbers from $-p$ to $p$ inclusive, any sum $k$ in the range $[-p \\cdot n; p \\cdot n]$ is achievable. We will present an algorithm that constructs an array with a given sum $k$ within this range. We will construct the array for $k \\ge 0$, as the problem for $k$ and $-k$ is equivalent. Let the current sum in the array be $s = 0$. At the current step, if $s + p < k$, we will find any index $i$ such that $a_i = 0$ and assign $p$ to $a_i$, updating $s$ to $s + p$. Otherwise, if $k - s \\le p$, we can assign $k - s$ to any $a_i = 0$ in one operation and finish the algorithm. In fact, this algorithm is optimal for this problem. Let's determine how many operations will be performed. $\\left\\lfloor \\frac{k}{p} \\right\\rfloor$ operations will be spent assigning the number $p$. If $k - \\left\\lfloor \\frac{k}{p} \\right\\rfloor \\cdot p > 0$, then one more operation will be performed, which is only possible if $k$ is not divisible by $p$. This means that the number of operations will be equal to $\\left\\lceil \\frac{k}{p} \\right\\rceil = \\left\\lfloor \\frac{k + p - 1}{p} \\right\\rfloor$ operations, which is the answer to the problem. Asymptotic complexity: $\\mathcal{O}(1)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n  int n, k, p;\n  cin >> n >> k >> p;\n  if (-n * p <= k && k <= n * p) {\n    cout << (abs(k) + p - 1) / p << '\\n';\n  } else {\n    cout << \"-1\\n\";\n  }\n}\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt --> 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2072",
    "index": "B",
    "title": "Having Been a Treasurer in the Past, I Help Goblins Deceive",
    "statement": "After completing the first quest, Akito left the starting cave. After a while, he stumbled upon a goblin village.\n\nSince Akito had nowhere to live, he wanted to find out the price of housing. It is well known that goblins write numbers as a string of characters '-' and '_', and the value represented by the string $s$ is the number of distinct subsequences$^{\\text{∗}}$ of the string $s$ that are equal to the string \"-_-\" (this is very similar to goblin faces).\n\nFor example, the string $s=$\"-_--_-\" represents the number $6$, as it has $6$ subsequences \"-_-\":\n\n- $s_1+s_2+s_3$\n- $s_1+s_2+s_4$\n- $s_1+s_2+s_6$\n- $s_1+s_5+s_6$\n- $s_3+s_5+s_6$\n- $s_4+s_5+s_6$\n\nInitially, the goblins wrote a random string-number $s$ in response to Akito's question, but then they realized that they wanted to take as much gold as possible from the traveler. To do this, they ask you to rearrange the characters in the string $s$ so that the value of the number represented by the string $s$ is maximized.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A subsequence of a string $a$ is a string $b$ that can be obtained by deleting several (possibly $0$) characters from $a$. Subsequences are considered different if they are obtained by deleting different sets of indices.\n\\end{footnotesize}",
    "tutorial": "For $n \\le 2$ or when the number of $i$ such that $s_i =$ '-' is less than two or there are no indices $i$ where $s_i =$ '_', the answer will be $0$. Otherwise, let's solve the problem if there is only one symbol '_' in the string. It is easy to see that the string will look like a prefix of length $\\ell_p$ made of '-', a single symbol '_', and a suffix of length $\\ell_s$ made of the remaining '-'. Then the number of subsequences is equal to $\\ell_p \\cdot \\ell_s$. The sum $\\ell_p + \\ell_s$ is fixed and equals the number of '-' symbols in the string, let's call this number $c$. It is straightforward to show that the optimal $\\ell_p = \\left\\lfloor \\frac{c}{2} \\right\\rfloor$, and the optimal $\\ell_s = \\left\\lceil \\frac{c}{2} \\right\\rceil$. Now let's return to the original problem. In fact, the solution above is also optimal for it! The string will still consist of a prefix of length $\\ell_p$ made of '-', a suffix of length $\\ell_s$ made of '-', and $(n - c)$ symbols '_' in the middle. $(n - c)$ is constant, which means we need to maximize the product $\\ell_p \\cdot \\ell_s$, and we already know how to do that. Thus, the answer is simply $\\left\\lfloor \\frac{c}{2} \\right\\rfloor \\cdot \\left\\lceil \\frac{c}{2} \\right\\rceil \\cdot (n - c)$. Asymptotic complexity: $\\mathcal{O}(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n  int n;\n  string s;\n  cin >> n >> s;\n  int64_t dash = count(s.begin(), s.end(), '-');\n  int64_t under = n - dash;\n  int64_t ans = (dash / 2) * (dash - dash / 2) * under;\n  cout << ans << '\\n';\n}\n\nint main() {\n  int tt;\n  cin >> tt;\n  while (tt --> 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "2072",
    "index": "C",
    "title": "Creating Keys for StORages Has Become My Main Skill",
    "statement": "Akito still has nowhere to live, and the price for a small room is everywhere. For this reason, Akito decided to get a job at a bank as a key creator for storages.\n\nIn this magical world, everything is different. For example, the key for a storage with the code $(n, x)$ is an array $a$ of length $n$ such that:\n\n- $a_1 \\ | \\ a_2 \\ | \\ a_3 \\ | \\ \\ldots \\ | \\ a_n = x$, where $a \\ | \\ b$ is the bitwise \"OR\" of numbers $a$ and $b$.\n- $\\text{MEX}(\\{ a_1, a_2, a_3, \\ldots, a_n \\})$$^{\\text{∗}}$ is maximized among all such arrays.\n\nAkito diligently performed his job for several hours, but suddenly he got a headache. Substitute for him for an hour; for the given $n$ and $x$, create any key for the storage with the code $(n, x)$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\text{MEX}(S)$ is the minimum non-negative integer $z$ such that $z$ is not contained in the set $S$ and all $0 \\le y < z$ are contained in $S$.\n\\end{footnotesize}",
    "tutorial": "In problems involving $\\text{MEX}$, a common idea is its greedy maximization. This problem is no exception. Note that $a\\ |\\ b \\ge \\max(a, b)$. We will iterate through the number $m$ from $0$ to $\\min(n - 1, x)$. We will also keep a number $v$ initially set to $0$. When processing the current $m$, we check that $v\\ |\\ m$ has only those bits set that are set in the number $x$. If this is the case, we assign $m$ to $a_{m + 1}$, update $v$ to $v\\ |\\ m$, and proceed to check the next $m$. If this is not the case, we exit the loop. Finally, we need to check if the current bitwise OR of the array equals the number $x$. If so, we immediately output this array. Otherwise, we assign the number $x$ to $a_n$. Asymptotic complexity: $\\mathcal{O}(n)$.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid Solve() {\n  int len, val;\n  cin >> len >> val;\n  vector<int> ans(len, val);\n  int or_val = 0;\n  bool flag = true;\n  for (int i = 0; i < len - 1; ++i) {\n    if (((or_val | i) & val) == (or_val | i)) {\n      or_val |= i;\n      ans[i] = i;\n    } else {\n      flag = false;\n      break;\n    }\n  }\n  if (flag && (or_val | (len - 1)) == val) {\n    ans[len - 1] = len - 1;\n  }\n  for (auto it : ans) cout << it << ' ';\n  cout << '\\n';\n}\n\nsigned main() {\n  cin.tie(0)->sync_with_stdio(0);\n  int test_count = 1;\n  cin >> test_count;\n  while (test_count --> 0) Solve();\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2072",
    "index": "D",
    "title": "For Wizards, the Exam Is Easy, but I Couldn't Handle It",
    "statement": "Akito got tired of being a simple locksmith at a bank, so he decided to enroll in the Magical Academy and become the best wizard in the world! However, to enroll, he needed to solve a single problem on the exam, which the ambitious hero could not manage.\n\nIn the problem, he was given an array $a$ of length $n$. He needed to minimize the number of inversions$^{\\text{∗}}$ in the array after applying the spell \\textbf{exactly once}. The spell was simple; to apply it, Akito had to choose two numbers $l$ and $r$ such that $1 \\le l \\le r \\le n$ and perform a cyclic shift of the subarray from $l$ to $r$ one position to the left.\n\nMore formally, Akito selects the subarray $[l, r]$ and modifies the array as follows:\n\n- From the original array $[a_1, a_2, \\ldots, a_{l - 1}, \\mathbf{ a_l }, \\mathbf{ a_{l + 1} } , \\mathbf{ \\ldots }, \\mathbf{ a_{r - 1} }, \\mathbf{ a_r }, a_{r + 1}, \\ldots, a_{n - 1}, a_n]$, he obtains the array $[a_1, a_2, \\ldots, a_{l - 1}, \\mathbf{ a_{l + 1} }, \\mathbf{ a_{l + 2} }, \\mathbf{ \\ldots }, \\mathbf{ a_{r - 1} }, \\mathbf{ a_{r} }, \\mathbf{ a_{l} }, a_{r + 1}, \\ldots, a_{n - 1}, a_{n}]$.\n\nAkito is eager to start his studies, but he still hasn't passed the exam. Help him enroll and solve the problem!\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An inversion in an array $b$ of length $m$ is defined as a pair of indices $(i, j)$ such that $1 \\le i < j \\le m$ and $b_i > b_j$. For example, in the array $b = [3, 1, 4, 1, 5]$, the inversions are the pairs of indices $(1, 2)$, $(1, 4)$, $(3, 4)$.\n\\end{footnotesize}",
    "tutorial": "In fact, a cyclic shift of the subarray $[l, r]$ to the left by $1$ is the same as removing the element $a_l$ from the array and then inserting it after the $r$-th element. This means that we can move the number $a_i$ to any position $j \\ge i$. Let's see how the number of inversions in the array changes with the operation on the segment $[l, r]$. Inversions with indices from $[1, l - 1]$ and $[r + 1, n]$ will remain in the array, and any pair that forms an inversion will stay in the same relative order as in the original array. Thus, we are interested in the inversions with indices from the segment $[l, r]$. Since only the position of the number $a_l$ changes, we can remove inversions of the form $(l, i)$, where $l < i \\le r$ (let's call these first-type inversions), and add inversions of the form $(i, l)$, where $l < i \\le r$ (let's call these second-type inversions). The number of first-type inversions is equal to the number of $i$ such that $l < i \\le r$ and $a_l > a_i$, let's denote this count as $c_1$. Similarly, the number of second-type inversions is equal to the number of $i$ such that $l < i \\le r$ and $a_l < a_i$, let's denote this count as $c_2$. Then the new number of inversions in the array will change by $c_2 - c_1$. It remains to find a subarray of $a$ with the minimal difference $c_2 - c_1$, which can be done using prefix sums for the count of each $a_i$ from $1$ to $2000$ or by simply iterating over the left boundary and traversing the suffix (see the author's solution). Asymptotic complexity: $\\mathcal{O}(n^2)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n  int n;\n  cin >> n;\n  vector<int> a(n);\n  for (int i = 0; i < n; ++i) {\n    cin >> a[i];\n  }\n\n  int best_diff = 0, L = 0, R = 0;\n  for (int i = 0; i < n; ++i) {\n    int cnt_greater = 0, cnt_less = 0;\n    for (int j = i + 1; j < n; ++j) {\n      cnt_greater += a[j] > a[i];\n      cnt_less += a[j] < a[i];\n\n      if (best_diff > cnt_greater - cnt_less) {\n        best_diff = cnt_greater - cnt_less;\n        L = i, R = j;\n      }\n    }\n  }\n\n  cout << L + 1 << ' ' << R + 1 << '\\n';\n}\n\nint main() {\n  int tt = 1;\n  cin >> tt;\n  while (tt --> 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2072",
    "index": "E",
    "title": "Do You Love Your Hero and His Two-Hit Multi-Target Attacks?",
    "statement": "Akito decided to study a new powerful spell. Since it possesses immeasurable strength, it certainly requires a lot of space and careful preparation. For this, Akito went out into the field. Let's represent the field as a Cartesian coordinate system.\n\nFor the spell, Akito needs to place $0 \\le n \\le 500$ staffs at \\textbf{distinct integer coordinates} in the field such that there will be \\textbf{exactly $k$ pairs} $(i, j)$ such that $1 \\le i < j \\le n$ and $\\rho(i, j) = d(i, j)$.\n\nHere, for two points with integer coordinates $a = (x_a, y_a)$ and $b = (x_b, y_b)$, $\\rho(a, b) = \\sqrt{(x_a - x_b)^2 + (y_a - y_b)^2}$ and $d(a, b) = |x_a - x_b| + |y_a - y_b|$.",
    "tutorial": "After playing a bit with the formulas $\\rho(a, b)$ and $d(a, b)$, we can derive that $\\rho(a, b) = d(a, b)$ if $x_a = x_b$ or $y_a = y_b$. Let us define a recursive function $f(k, x_0, y_0)$ that returns a set of sticks $P$ such that there are exactly $k$ unordered pairs that satisfy the condition, given that for all sticks $p \\in P$, $x_p \\ge x_0$ and $y_p \\ge y_0$. If $k = 0$, the function will return an empty set. For $k > 0$, we find the maximum $m$ such that $\\frac{m(m - 1)}{2} \\le k$. Next, we add the sticks $(x_0, y_0), (x_0 + 1, y_0), \\ldots, (x_0 + m - 1, y_0)$ to the set $P$. Note that any pair from this set satisfies the condition, and thus there are exactly $\\frac{m(m - 1)}{2}$ such pairs. We then combine the current set $P$ with the set $f(k - \\frac{m(m - 1)}{2}, x_0 + m, y_0 + 1)$. This will yield the set of sticks that meets the problem's requirements. We will prove that there will be no more than $500$ points. Let $g(x) = \\frac{x(x - 1)}{2}$. In fact, the value $k - g(m) \\le 446$, since $g(x + 1) - g(x) = \\frac{x(x + 1)}{2} - \\frac{x(x - 1)}{2} = \\frac{x}{2}(x + 1 - x + 1) = x$, and the maximum value of $g(x) \\le 10^5$ is $g(447)$, which means the maximum value of $g(x + 1) - g(x) = 446$. For $k \\le 446$, the algorithm places no more than 43 sticks; for $k = g(x)$, the algorithm will place $x$ sticks, thus the maximum number of sticks will be $447 + 43 = 490 \\le 500$. Asymptotic complexity: $\\mathcal{O}(\\sqrt{k})$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<pair<int64_t, int64_t>> rec(int64_t k, int64_t x0 = 0, int64_t y0 = 0) {\n  if (!k) {\n    return {};\n  }\n  int64_t delta = 0;\n  while (delta * (delta - 1) / 2 <= k) {\n    delta++;\n  }\n  delta--;\n  auto remaining = rec(k - delta * (delta - 1) / 2, x0 + delta + 1, y0 + 1);\n  vector<pair<int64_t, int64_t>> ans;\n  for (int x = x0; x < x0 + delta; ++x) {\n    ans.push_back({x, y0});\n  }\n  ans.insert(ans.end(), remaining.begin(), remaining.end());\n  return ans;\n}\n\nvoid solve() {\n  int64_t k;\n  cin >> k;\n  if (!k) {\n    cout << \"1\\n69 52\\n\";\n    return;\n  }\n  auto ans = rec(k, 0, 0);\n  cout << ans.size() << '\\n';\n  for (auto [x, y] : ans) {\n    cout << x << ' ' << y << '\\n';\n  }\n}\n\nint main() {\n  int tt = 1;\n  cin >> tt;\n  while (tt --> 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "dp",
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2072",
    "index": "F",
    "title": "Goodbye, Banker Life",
    "statement": "Monsters are approaching the city, and to protect it, Akito must create a protective field around the city. As everyone knows, protective fields come in various levels. Akito has chosen the field of level $n$. To construct the field, a special phrase is required, which is the $n$-th row of the Great Magical Triangle, represented as a two-dimensional array. We will call this array $T$.\n\nThe triangle is defined as follows:\n\n- In the $i$-th row, there are $i$ integers.\n- The single integer in the first row is $k$.\n- Let the $j$-th element of the $i$-th row be denoted as $T_{i,j}$. Then $$T_{i,j} = \\begin{cases} T_{i-1,j-1} \\oplus T_{i-1,j}, &\\textrm{if } 1 < j < i \\\\ T_{i-1,j}, &\\textrm{if } j = 1 \\\\ T_{i-1,j-1}, &\\textrm{if } j = i \\end{cases}$$\n\nwhere $a \\oplus b$ is the bitwise exclusive \"OR\"(XOR) of the integers $a$ and $b$.Help Akito find the integers in the $n$-th row of the infinite triangle before the monsters reach the city.",
    "tutorial": "Since the value of the $i$-th bit in $a \\oplus b$ depends only on the $i$-th bits of the numbers $a$ and $b$, we can solve the problem separately for each bit. Let $a_i$ be the $i$-th bit of the number $a$. If $k_i = 0$, then the triangle for the $i$-th bit will consist only of $0$s. If $k_i = 1$, then since $\\oplus$ is the bitwise addition modulo $2$, we simply obtain Pascal's Triangle, where all values are taken modulo $2$. Now the problem has reduced to finding $\\binom{n}{r} \\mod 2$. $\\binom{n}{r} = \\frac{n!}{r! \\cdot (n - r)!}$, which means the parity of $\\binom{n}{r}$ depends on the power of $2$ in $n!$, $r!$, and $(n - r)!$. Let $c_n$ be the power of $2$ in $n!$. $\\binom{n}{r}$ will be odd if and only if $c_n = c_r + c_{n - r}$. It remains to learn how to find the power of $2$ in $n!$. We have $c_0 = c_1 = 0$, and $c_n = c_{n - 1} + f(n)$, where $f(n)$ is the maximum $m$ such that $2^m | n$. Asymptotic complexity: $\\mathcal{O}(N \\log N)$ for preprocessing and $\\mathcal{O}(n)$. Here, $N$ denotes the maximum possible $n$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconstexpr int64_t kMaxN = 1e6 + 69;\nvector<int64_t> c(kMaxN);\n\nvoid precalc() {\n  c[0] = c[1] = 0;\n  for (int i = 2; i < kMaxN; ++i) {\n    c[i] = c[i - 1];\n    int x = i;\n    while (x % 2 == 0) {\n      x /= 2, c[i]++;\n    }\n  }\n}\n\nvoid solve() {\n  int n, k;\n  cin >> n >> k;\n\n  --n;\n  for (int i = 0; i <= n; ++i) {\n    cout << k * (c[n] == c[i] + c[n - i]) << \" \\n\"[i == n];\n  }\n}\n\nint main() {\n  ios::sync_with_stdio(0);\n  cin.tie(0);\n\n  precalc();\n\n  int tt = 1;\n  cin >> tt;\n  while (tt --> 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "2-sat",
      "bitmasks",
      "combinatorics",
      "constructive algorithms",
      "fft",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2072",
    "index": "G",
    "title": "I've Been Flipping Numbers for 300 Years and Calculated the Sum",
    "statement": "After three hundred years of slime farming, Akito finally obtained the magical number $n$. Upon reaching the merchant, he wanted to exchange the number for gold, but the merchant gave the hero a quest.\n\nThe merchant said that for the quest, the skill $\\text{rev}(n, p)$ would be required, which Akito, by happy coincidence, had recently learned. $\\text{rev}(n, p)$ represents the following procedure:\n\n- Write the number $n$ in base $p$, let this representation be $n = \\overline{n_{\\ell - 1} \\ldots n_1 n_0}$, where $\\ell$ is the length of the base $p$ representation of the number $n$.\n- Reverse the base $p$ representation, let this be $m = \\overline{n_0 n_1 \\ldots n_{\\ell - 1}}$.\n- Convert the number $m$ back to decimal and return it as the result.\n\nThe merchant's quest was to calculate the sum $x = \\sum\\limits_{p = 2}^{k} \\text{rev}(n, p)$. Since this number can be quite large, only the remainder of $x$ when divided by $10^9 + 7$ is required. The merchant also mentioned that the previous traveler had been calculating this sum for three hundred years and had not finished it. But you will help Akito finish it faster, right?",
    "tutorial": "Let's consider three cases: $2 \\le p \\le \\sqrt{n}$. We calculate for each of the $\\mathcal{O}(\\sqrt{n})$ values of $p$ in $\\mathcal{O}(\\log n)$. One could think that it takes $\\mathcal{O}(\\sqrt{n} \\log{n})$ time, but it actually takes $\\mathcal{O}(\\sqrt{n})$ time! Read this comment for explanation. $n < p \\le k$. For each such $p$, $\\text{rev}(n, p) = n$, and their count is $k - n$. Thus, the sum for them is $(k - n) \\cdot n$. This takes $O(1)$ for the calculation. $\\sqrt{n} < p \\le n$. We note that $\\log_p{n} \\le \\log_{\\sqrt{n}}{n} = \\frac{\\log{n}}{\\log{\\sqrt{n}}} = \\frac{\\log{n}}{\\log{n^{ \\frac{1}{2} }}} = 2 \\cdot \\frac{\\log{n}}{\\log{n}} = 2$. Thus, the length of the base $p$ representation of the number $n$ is 2.Let's consider some $p$ from this range. Let $n = \\overline{n_1 n_0} = n_1 \\cdot p + n_0$. It is easy to show that $n_0 = (n \\text{ mod } p)$, and $n_1 = \\left\\lfloor \\frac{n}{p} \\right\\rfloor$. We find the value $\\text{rev}(n, p) = n_0 \\cdot p + n_1 = p \\cdot (n \\text{ mod } p) + \\left\\lfloor \\frac{n}{p} \\right\\rfloor$, so the entire sum looks like this: $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} (p \\cdot (n \\text{ mod } p) + \\left\\lfloor \\frac{n}{p} \\right\\rfloor) = \\sum\\limits_{p = \\sqrt{n} + 1}^{n} p \\cdot (n \\text{ mod } p) + \\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor$ which in turn equals $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} p \\cdot (n - \\left\\lfloor \\frac{n}{p} \\right\\rfloor \\cdot p) + \\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor = \\sum\\limits_{p = \\sqrt{n} + 1}^{n} pn - \\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor \\cdot p^2 + \\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor$ We will calculate all three sums separately. $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} pn = n \\sum\\limits_{p = \\sqrt{n} + 1}^{n} p$. The sum is simply the sum of an arithmetic progression multiplied by $n$. This takes $\\mathcal{O}(1)$ for the calculation. For the remaining sums, we need to note the following fact. The number of distinct values of $\\left\\lfloor \\frac{n}{i} \\right\\rfloor$ is $\\le 2\\sqrt{n}$. The proof is quite simple: Consider two cases: $i \\le \\sqrt{n}$ - the number of numbers we divide by is equal to the square root, so we cannot get more than $\\sqrt{n}$ distinct values. $i > \\sqrt{n}$ - if $i > \\sqrt{n}$, then $\\left\\lfloor \\frac{n}{i} \\right\\rfloor \\le \\sqrt{n}$, so there are also no more than $\\sqrt{n}$ such values. In total, we find that the number of distinct values is $\\sqrt{n} + \\sqrt{n} = 2\\sqrt{n}$ q. e. d.To calculate $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor$, we will explicitly iterate over the value $x = \\left\\lfloor \\frac{n}{p} \\right\\rfloor$ and find such $l, r$ that all numbers from $l$ to $r$ give the value $x$ and we will sum $x \\cdot (r - l + 1)$. This takes $\\mathcal{O}(\\sqrt{n})$ for the calculation. To calculate $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor \\cdot p^2$, we will do exactly the same as in the previous sum, but now $x$ will have to be multiplied by the sum of squares of numbers from $l$ to $r$. This also takes $\\mathcal{O}(\\sqrt{n})$ for the calculation. Thus, in total, the third case takes $\\mathcal{O}(1) + \\mathcal{O}(\\sqrt{n}) + \\mathcal{O}(\\sqrt{n}) = \\mathcal{O}(\\sqrt{n})$. Let's consider some $p$ from this range. Let $n = \\overline{n_1 n_0} = n_1 \\cdot p + n_0$. It is easy to show that $n_0 = (n \\text{ mod } p)$, and $n_1 = \\left\\lfloor \\frac{n}{p} \\right\\rfloor$. We find the value $\\text{rev}(n, p) = n_0 \\cdot p + n_1 = p \\cdot (n \\text{ mod } p) + \\left\\lfloor \\frac{n}{p} \\right\\rfloor$, so the entire sum looks like this: $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} (p \\cdot (n \\text{ mod } p) + \\left\\lfloor \\frac{n}{p} \\right\\rfloor) = \\sum\\limits_{p = \\sqrt{n} + 1}^{n} p \\cdot (n \\text{ mod } p) + \\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor$ which in turn equals $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} p \\cdot (n - \\left\\lfloor \\frac{n}{p} \\right\\rfloor \\cdot p) + \\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor = \\sum\\limits_{p = \\sqrt{n} + 1}^{n} pn - \\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor \\cdot p^2 + \\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor$ We will calculate all three sums separately. $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} pn = n \\sum\\limits_{p = \\sqrt{n} + 1}^{n} p$. The sum is simply the sum of an arithmetic progression multiplied by $n$. This takes $\\mathcal{O}(1)$ for the calculation. For the remaining sums, we need to note the following fact. The number of distinct values of $\\left\\lfloor \\frac{n}{i} \\right\\rfloor$ is $\\le 2\\sqrt{n}$. The proof is quite simple: Consider two cases: $i \\le \\sqrt{n}$ - the number of numbers we divide by is equal to the square root, so we cannot get more than $\\sqrt{n}$ distinct values. $i > \\sqrt{n}$ - if $i > \\sqrt{n}$, then $\\left\\lfloor \\frac{n}{i} \\right\\rfloor \\le \\sqrt{n}$, so there are also no more than $\\sqrt{n}$ such values. To calculate $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor$, we will explicitly iterate over the value $x = \\left\\lfloor \\frac{n}{p} \\right\\rfloor$ and find such $l, r$ that all numbers from $l$ to $r$ give the value $x$ and we will sum $x \\cdot (r - l + 1)$. This takes $\\mathcal{O}(\\sqrt{n})$ for the calculation. To calculate $\\sum\\limits_{p = \\sqrt{n} + 1}^{n} \\left\\lfloor \\frac{n}{p} \\right\\rfloor \\cdot p^2$, we will do exactly the same as in the previous sum, but now $x$ will have to be multiplied by the sum of squares of numbers from $l$ to $r$. This also takes $\\mathcal{O}(\\sqrt{n})$ for the calculation. Thus, in total, the third case takes $\\mathcal{O}(1) + \\mathcal{O}(\\sqrt{n}) + \\mathcal{O}(\\sqrt{n}) = \\mathcal{O}(\\sqrt{n})$. Final asymptotic complexity: $\\mathcal{O}(\\sqrt{n}) + \\mathcal{O}(1) + \\mathcal{O}(\\sqrt{n}) = \\mathcal{O}(\\sqrt{n} + \\sqrt{n}) = \\mathcal{O}(\\sqrt{n})$",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconstexpr int64_t mod = 1e9 + 7;\nconstexpr int64_t twoInv = 500'000'004;\nconstexpr int64_t sixInv = 166'666'668;\n\nint64_t add(int64_t a, int64_t b) {\n  return (a % mod + b % mod) % mod;\n}\n\nint64_t mns(int64_t a, int64_t b) {\n  return (a % mod - b % mod + mod) % mod;\n}\n\nint64_t mul(int64_t a, int64_t b) {\n  return (a % mod) * (b % mod) % mod;\n}\n\nint64_t rev(int64_t n, int64_t p) {\n  int64_t res = 0;\n  while (n) {\n    res = add(mul(res, p), n % p);\n    n /= p;\n  }\n  return res;\n}\n\nint64_t stupid(int64_t n, int64_t k) {\n  int64_t res = 0;\n  for (int64_t p = 2; p <= k; ++p) {\n    res = add(res, rev(n, p));\n  }\n  return res;\n}\n\nint64_t sum1(int64_t r) {\n  return mul(mul(r, r + 1), twoInv);\n}\n\nint64_t sum1(int64_t l, int64_t r) {\n  return mns(sum1(r), sum1(l - 1));\n}\n\nint64_t sum2(int64_t r) {\n  return mul(mul(mul(r, r + 1), 2 * r + 1), sixInv);\n}\n\nint64_t sum2(int64_t l, int64_t r) {\n  return mns(sum2(r), sum2(l - 1));\n}\n\nint64_t get(int64_t n, int64_t l, int64_t r) {\n  if (l > r) {\n    return 0;\n  }\n\n  int64_t res = mul(sum1(l, r), n);\n  int64_t minus = 0, plus = 0;\n\n  int64_t L = l;\n  while (L <= r) {\n    int64_t value = n / L;\n    int64_t R = min(r, n / value);\n\n    minus = add(minus, mul(sum2(L, R), value));\n    plus = add(plus, mul(R - L + 1, value));\n\n    L = R + 1;\n  }\n\n  return add(mns(res, minus), plus);\n}\n\nvoid solve() {\n  int64_t n, k;\n  cin >> n >> k;\n\n  int64_t sq = (int64_t)sqrtl((long double)n);\n  int64_t ans = mul(max<int64_t>(0, k - n), n);\n  ans = add(ans, stupid(n, min(sq, k)));\n  ans = add(ans, get(n, sq + 1, min(n, k)));\n\n  cout << ans << '\\n';\n}\n\nint main() {\n  int tt = 1;\n  cin >> tt;\n  while (tt --> 0) {\n    solve();\n  }\n  return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "combinatorics",
      "divide and conquer",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2074",
    "index": "A",
    "title": "Draw a Square",
    "statement": "The pink soldiers have given you $4$ \\textbf{distinct points} on the plane. The $4$ points' coordinates are $(-l,0)$, $(r,0)$, $(0,-d)$, $(0,u)$ correspondingly, where $l$, $r$, $d$, $u$ are positive integers.\n\n\\begin{center}\n{\\small In the diagram, a square is drawn by connecting the four points $L$, $R$, $D$, $U$.}\n\\end{center}\n\nPlease determine if it is possible to draw a square$^{\\text{∗}}$ with the given points as its vertices.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A square is defined as a polygon consisting of $4$ vertices, of which all sides have equal length and all inner angles are equal. No two edges of the polygon may intersect each other.\n\\end{footnotesize}",
    "tutorial": "For the given four points to make a square, we can see that the following must hold: $l$, $r$, $d$, $u$ must all be equal. The proof is left as a practice for the reader, but generally, it can be proved easily by seeing that the square is both a rhombus and a rectangle. The problem is solved in $\\mathcal{O}(1)$ per test case.",
    "code": "for i in range(int(input())):\n    l,r,d,u=map(int,input().split())\n    if l==r==d==u:\n        print(\"Yes\")\n    else:\n        print(\"No\")",
    "tags": [
      "geometry",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2074",
    "index": "B",
    "title": "The Third Side",
    "statement": "The pink soldiers have given you a sequence $a$ consisting of $n$ positive integers.\n\nYou must repeatedly perform the following operation \\textbf{until there is only $1$ element left}.\n\n- Choose two \\textbf{distinct} indices $i$ and $j$.\n- Then, choose a positive integer value $x$ such that there exists a \\textbf{non-degenerate triangle}$^{\\text{∗}}$ with side lengths $a_i$, $a_j$, and $x$.\n- Finally, remove two elements $a_i$ and $a_j$, and append $x$ to the end of $a$.\n\nPlease find the maximum possible value of the only last element in the sequence $a$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A triangle with side lengths $a$, $b$, $c$ is non-degenerate when $a+b > c$, $a+c > b$, $b+c > a$.\n\\end{footnotesize}",
    "tutorial": "We can solve this problem by observing a property on the sum of elements. After each operation, it must hold that $a_i+a_j>x$, and the new element is at most $a_i+a_j-1$. Therefore, the sum decreases by at least $1$. However, we notice that a triangle of side lengths $p$, $q$, $p+q-1$ is always non-degenerate due to the following: $p+q>p+q-1$; $p+(p+q-1)>q$ due to $2p-1>0$; $q+(p+q-1)>p$ due to $2q-1>0$. Therefore, you can decrease the sum by exactly $1$ on each operation. The maximum final sum (which is the last element) is thus $\\text{sum}-n+1$.",
    "code": "t = int(input())\nfor _ in range(t):\n    n = int(input())\n    sm = sum(map(int, input().split()))\n    print(sm - n + 1)",
    "tags": [
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2074",
    "index": "C",
    "title": "XOR and Triangle",
    "statement": "This time, the pink soldiers have given you an integer $x$ ($x \\ge 2$).\n\nPlease determine if there exists a \\textbf{positive} integer $y$ that satisfies the following conditions.\n\n- $y$ is \\textbf{strictly} less than $x$.\n- There exists a \\textbf{non-degenerate triangle}$^{\\text{∗}}$ with side lengths $x$, $y$, $x \\oplus y$. Here, $\\oplus$ denotes the bitwise XOR operation.\n\nAdditionally, if there exists such an integer $y$, output any.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A triangle with side lengths $a$, $b$, $c$ is non-degenerate when $a+b > c$, $a+c > b$, $b+c > a$.\n\\end{footnotesize}",
    "tutorial": "Let us interpret the triangle inequality in terms of bitmasking. Then, we get the following. (One is omitted as it is implied in the constraints.) $x+y>x \\oplus y$, $(x \\oplus y)+2(x \\,\\&\\, y)> x \\oplus y$, $x\\,\\&\\,y>0$; $y+(x \\oplus y)>x$, $y+(x + y) - 2(x\\,\\&\\,y)> x$, $y > x\\,\\&\\,y$. In other words, $y$ satisfies the following conditions. $y$ contains at least one bit turned on in $x$; $y$ contains at least one bit not turned on in $x$. The smallest values of $y$ that satisfy this have exactly two bits turned on; one in $x$ and one not in it. Therefore, if one such value exists, then a smallest one can be found in $\\mathcal{O}(\\log ^2 x)$ time by simply bruteforcing all integers with two bits turned on. If any one of them is less than $x$, then it satisfies all conditions. The problem has been solved in $\\mathcal{O}(\\log ^2 x)$ per test case. While there exist ways to solve it in $\\mathcal{O}(\\log x)$ per test case, they were not required.",
    "code": "t = int(input())\nfor _ in range(t):\n    x = int(input())\n    ans = -1\n    for i in range(30):\n        for j in range(30):\n            y = (1 << i) | (1 << j)\n            if y < x and x + y > (x ^ y) and y + (x ^ y) > x:\n                ans = y\n    print(ans)",
    "tags": [
      "bitmasks",
      "brute force",
      "geometry",
      "greedy",
      "probabilities"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2074",
    "index": "D",
    "title": "Counting Points",
    "statement": "The pink soldiers drew $n$ circles with their center \\textbf{on the $x$-axis} of the plane. Also, they have told that \\textbf{the sum of radii is exactly $m$}$^{\\text{∗}}$.\n\nPlease find the number of integer points \\textbf{inside or on the border of} at least one circle. Formally, the problem is defined as follows.\n\nYou are given an integer sequence $x_1,x_2,\\ldots,x_n$ and a positive integer sequence $r_1,r_2,\\ldots,r_n$, where it is known that $\\sum_{i=1}^n r_i = m$.\n\nYou must count the number of integer pairs $(x,y)$ that satisfy the following condition.\n\n- There exists an index $i$ such that $(x-x_i)^2 + y^2 \\le r_i^2$ ($1 \\le i \\le n$).\n\n\\begin{footnotesize}\n$^{\\text{∗}}$Is this information really useful? Don't ask me; I don't really know.\n\\end{footnotesize}",
    "tutorial": "For some value of $x$ and a circle centered on $(x_i,0)$ with radius $r_i$, we can find the range of $y$ where the points lie on using simple algebra. $y^2 \\le r_i^2-(x-x_i)^2 \\Longrightarrow -\\sqrt{r_i^2-(x-x_i)^2} \\le y \\le \\sqrt{r_i^2-(x-x_i)^2}$ Here, we can see that when $a=\\left \\lfloor {\\sqrt{r_i^2-(x-x_i)^2}} \\right \\rfloor$, there are $2a+1$ different integer values of $y$ in this range. Now, think of how to deal with when multiple circles cover the same value of $x$. This is not too hard; you can compute the value of $a$ for all of them and take the largest one. The rest can be ignored as the largest value of $a$ covers all of them. The implementation is not hard; it simply boils down to using a std::map or some data structure to record the maximum value of $a$ for each value of $x$ that holds at least one point. The problem is solved in time complexity $\\mathcal{O}(m \\log m)$. It is technically possible to solve the problem by fixing the value of $y$ instead of the value of $x$, but it is significantly more tedious to implement.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n \nint main()\n{\n    int t;cin>>t;\n    for(int i=0;i<t;i++)\n    {\n        int n,m;cin>>n>>m;\n        map<ll,ll>cnt;\n        auto isqrt=[&](ll x)\n        {\n            ll val=sqrtl(x)+5;\n            while(val*val>x)val--;\n            return val;\n        };\n        vector<ll>a(n),r(n);\n        for(ll&i:a)cin>>i;\n        for(ll&i:r)cin>>i;\n        for(int i=0;i<n;i++)\n        {\n            ll aa=a[i],rr=r[i];\n            for(ll x=aa-rr;x<=aa+rr;x++)\n            {\n                cnt[x]=max(cnt[x],2*isqrt(rr*rr-(x-aa)*(x-aa))+1);\n            }\n        }\n        ll ans=0;\n        for(auto[x,c]:cnt)ans+=c;\n        cout<<ans<<\"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "geometry",
      "implementation",
      "two pointers"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2074",
    "index": "E",
    "title": "Empty Triangle",
    "statement": "This is an interactive problem.\n\nThe pink soldiers hid from you $n$ ($3 \\le n \\le 1500$) \\textbf{fixed} points $(x_1,y_1), (x_2,y_2), \\ldots, (x_n,y_n)$, \\textbf{whose coordinates are not given to you}. Also, it is known that no two points have the same coordinates, and no three points are collinear.\n\nYou can ask the Frontman about three \\textbf{distinct} indices $i$, $j$, $k$. Then, he will draw a triangle with points $(x_i,y_i)$, $(x_j,y_j)$, $(x_k,y_k)$, and respond with the following:\n\n- If at least one of the hidden points lies inside the triangle, then the Frontman gives you the index of one such point. Do note that if there are multiple such points, \\textbf{the Frontman can arbitrarily select one of them}.\n- Otherwise, the Frontman responds with $0$.\n\n\\begin{center}\n{\\small Your objective in this problem is to find a triangle not containing any other hidden point, such as the blue one in the diagram.}\n\\end{center}\n\nUsing at most $\\mathbf{75}$ queries, you must find any triangle formed by three of the points, \\textbf{not containing} any other hidden point inside.\n\nDo note that the Frontman may be \\textbf{adaptive} while choosing the point to give you. In other words, the choice of the point can be determined by various factors including but not limited to the orientation of points and the previous queries. However, note that \\textbf{the sequence of points will never be altered}.\n\nHacks are disabled for this problem. Your solution will be judged on exactly $\\mathbf{35}$ input files, including the example input.",
    "tutorial": "After querying the triple $(i,j,k)$ and receiving the index $p$, we seem to gain almost no info other than the following. The three triples $(p,j,k)$, $(i,p,k)$, $(i,j,p)$ all yield strictly fewer points inside the triangle than $(i,j,k)$. One may think that repeatedly substituting one index arbitrarily with $p$ gets a worst case of $1498$ queries needed. However, there is also the following information that we gain. If we found $c_i$, $c_j$, $c_k$ points after substituting one index with $p$, and found $c$ points after querying $(i,j,k)$, then $c_i+c_j+c_k+1=c$. So, after finding $c_i+c_j+c_k=c-1$, we can infer the following facts. Due to the pigeonhole principle, at least one of $c_i$, $c_j$, $c_k$ must be no greater than $\\frac{c-1}{3}$. Then, if we substitute one index at random with equal probability, we choose this triangle with $\\frac{1}{3}$ probability. We can expect to choose the 'good' triangle $\\frac{75}{3}=25$ times on average, and the number of points inside decreases to $0$ after choosing the 'good' triangle at least $\\left \\lfloor {\\log_3(n)} \\right \\rfloor +1 \\le 7$ times. As $7 \\ll 25$, we can expect that we will almost certainly find some empty triangle within $75$ queries. Asking Wolfram Alpha for the probability after modeling the number of correct guesses as a binomial distribution, we can estimate the failure probability for one test case to be no greater than $2.4 \\cdot 10^{-7}$. As $\\left ( {1 - 2.4 \\cdot 10^{-7}} \\right )^{700} > 0.9998$, we find that this solution has strictly less than $0.02\\%$ probability to fail on at least one of the test cases. The asymptotic complexity on the number of queries required is $\\mathcal{O}(\\log n)$ with high probability. Challenge: In fact, this solution's failure probability for one test case is actually much less than given above, around $1.8 \\cdot 10^{-20}$. Why?",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint main()\n{\n    mt19937 mt(727);\n    uniform_int_distribution uni(1,3);\n    int tc;cin>>tc;\n    while(tc--)\n    {\n        int n;cin>>n;\n        if(n<0)return 0;\n        vector<int>vec(n);\n        for(int i=0;i<n;i++)vec[i]=i+1;\n        shuffle(begin(vec),end(vec),mt);\n        int ii=vec[0],jj=vec[1],kk=vec[2];\n        cerr<<n<<endl;\n        while(1)\n        {\n            cout<<\"? \"<<ii<<\" \"<<jj<<\" \"<<kk<<endl;\n            int id;cin>>id;\n            if(id<0)return 0;\n            if(id==0)break;\n            int sw=uni(mt);\n            if(sw==1)ii=id;\n            else if(sw==2)jj=id;\n            else kk=id;\n        }\n        cout<<\"! \"<<ii<<\" \"<<jj<<\" \"<<kk<<endl;\n    }\n}",
    "tags": [
      "geometry",
      "interactive",
      "probabilities"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2074",
    "index": "F",
    "title": "Counting Necessary Nodes",
    "statement": "A \\textbf{quadtree} is a tree data structure in which each node has at most four children and accounts for a square-shaped region.\n\nFormally, \\textbf{for all tuples} of nonnegative integers $k,a,b \\ge 0$, there exists \\textbf{exactly one node} accounting for the following region$^{\\text{∗}}$.\n\n$$[a \\cdot 2^k,(a+1) \\cdot 2^k] \\times [b \\cdot 2^k,(b+1) \\cdot 2^k]$$\n\nAll nodes whose region is larger than $1 \\times 1$ contain four children corresponding to the regions divided equally into four, and the nodes whose region is $1 \\times 1$ correspond to the leaf nodes of the tree.\n\n\\begin{center}\n{\\small A small subset of the regions accounted for by the nodes is shown. The relatively darker regions are closer to leaf nodes.}\n\\end{center}\n\nThe Frontman hates the widespread misconception, such that the quadtree can perform range queries in $\\mathcal{O}(\\log n)$ time when there are $n$ leaf nodes inside the region. In fact, sometimes it is necessary to query much more than $\\mathcal{O}(\\log n)$ regions for this, and the time complexity is $\\mathcal{O}(n)$ in some extreme cases. Thus, the Frontman came up with this task to educate you about this worst case of the data structure.\n\nThe pink soldiers have given you a finite region $[l_1,r_1] \\times [l_2,r_2]$, where $l_i$ and $r_i$ ($l_i < r_i$) are nonnegative integers. Please find the minimum number of nodes that you must choose in order to make the union of regions accounted for by the chosen nodes \\textbf{exactly} the same as the given region. Here, two sets of points are considered different if there exists a point included in one but not in the other.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$Regions are sets of points \\textbf{with real coordinates}, where the point $(x,y)$ is included in the region $[p,q] \\times [r,s]$ if and only if $p \\le x \\le q$ and $r \\le y \\le s$. Here, $\\times$ formally refers to Cartesian product of sets.\n\\end{footnotesize}",
    "tutorial": "Notice how the interval on each axis corresponds to those found in nodes of segment trees. Let us find the segment tree intervals on each axis and call those sets of intervals $I_x$ and $I_y$. Then, for each rectangle formed by some $a \\times b$ such that $a \\in I_x$, $b \\in I_y$, the following holds. No node with side length strictly greater than $\\min(|a|,|b|)$ can cover this rectangle without moving outside the given region. All nodes with side length no greater than $\\min(|a|,|b|)$ are either completely inside the rectangle or completely outside. Thus, we find the following strategy to cover the region optimally. For all $a \\times b$ such that $a \\in I_x$, $b \\in I_y$, cover the sub-region with the following method. As both $|a|$ and $|b|$ are powers of two, the larger one is divisible by the smaller one. Therefore, we can cover the sub-region with nodes with side length $\\min(|a|,|b|)$. This requires us to use $\\frac{\\max(|a|,|b|)}{\\min(|a|,|b|)}$ nodes. As both $|a|$ and $|b|$ are powers of two, the larger one is divisible by the smaller one. Therefore, we can cover the sub-region with nodes with side length $\\min(|a|,|b|)$. This requires us to use $\\frac{\\max(|a|,|b|)}{\\min(|a|,|b|)}$ nodes. Implementing this leads to a solution with time complexity $\\mathcal{O}(\\log^2 X)$. While there are solutions with time complexity $\\mathcal{O}(\\log X)$, they were not needed.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n \nint main()\n{\n    int t;cin>>t;\n    for(int i=0;i<t;i++)\n    {\n        int l1,r1,l2,r2;cin>>l1>>r1>>l2>>r2;\n        vector<pair<ll,ll>>it1,it2;\n        auto rec=[&](auto rec,int L,int R,int l,int r,vector<pair<ll,ll>>&v)->void\n        {\n            if(r<=L||l>=R)return;\n            if(l<=L&&R<=r)\n            {\n                v.emplace_back(L,R);\n                return;\n            }\n            rec(rec,L,(L+R)/2,l,r,v);\n            rec(rec,(L+R)/2,R,l,r,v);\n        };\n        rec(rec,0,1<<25,l1,r1,it1);\n        rec(rec,0,1<<25,l2,r2,it2);\n        ll ans=0;\n        for(auto[al,ar]:it1)\n        {\n            for(auto[bl,br]:it2)\n            {\n                ll a=ar-al,b=br-bl;\n                if(a<b)swap(a,b);\n                ans+=a/b;\n            }\n        }\n        cout<<ans<<\"\\n\";\n    }\n}",
    "tags": [
      "bitmasks",
      "divide and conquer",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2074",
    "index": "G",
    "title": "Game With Triangles: Season 2",
    "statement": "\\begin{center}\n\\begin{tabular}{c}\nThe Frontman greets you to this final round of the survival game. \\\n\\end{tabular}\n\\end{center}\n\nThere is a regular polygon with $n$ sides ($n \\ge 3$). The vertices are indexed as $1,2,\\ldots,n$ in clockwise order. On each vertex $i$, the pink soldiers have written a positive integer $a_i$. With this regular polygon, you will play a game defined as follows.\n\nInitially, your score is $0$. Then, you perform the following operation any number of times to increase your score.\n\n- Select $3$ different vertices $i$, $j$, $k$ that you \\textbf{have not chosen} before, and draw the triangle formed by the three vertices.\n\n- Then, your score increases by $a_i \\cdot a_j \\cdot a_k$.\n- However, you \\textbf{can not perform this operation} if the triangle shares a positive common area with any of the triangles drawn previously.\n\n\\begin{center}\n{\\small An example of a state after two operations is on the left. The state on the right \\textbf{is impossible} as the two triangles share a positive common area.}\n\\end{center}\n\nYour objective is to maximize the score. Please find the maximum score you can get from this game.",
    "tutorial": "If we cut a single edge and consider the regular polygon as a polyline of $n$ points, then we can think of using some form of Range DP to solve this problem. This is correct when you simply take the maximum value over all possible edges you can cut. It is not hard to see that doing this should not change the overall time complexity (unless you did recalculate the same state multiple times). However, it is hard to immediately think of a transition that is both correct and efficient. Let's find a trivially correct but slow solution and reduce the complexity. A correct $\\mathcal{O}(n^5)$ DP which is (arguably) easy to find is as follows. $\\text{dp}_{[L,R]}=\\max_{L \\le i < j < k \\le R}{\\left ({\\text{dp}_{[L,i-1]}+\\text{dp}_{[i+1,j-1]}+\\text{dp}_{[j+1,k-1]}+\\text{dp}_{[k+1,R]}+\\text{score}(i,j,k)}\\right )}$ It is not too hard to prove the correctness of this transition, as it follows from the conditions such that two triangles will not coincide anywhere. It is only tricky for us to improve the complexity. First, we can find that $\\text{score}(i,j,k)$ will also be found with $L=i$ and $k=R$ later in some smaller subproblem. Then, our transition changes. $\\text{dp}_{[L,R]}=\\max\\left ({ {\\max_{L < i < R}{\\left ({\\text{dp}_{[L+1,i-1]}+\\text{dp}_{[i+1,R-1]}+\\text{score}(L,i,R)}\\right )}},{\\max_{L \\le i < j < R}{\\left ({\\text{dp}_{[L,i]}+\\text{dp}_{[i+1,j]}+\\text{dp}_{[j+1,R]}}\\right )}} }\\right)$ This is a correct $\\mathcal{O}(n^4)$ DP which cuts a lot of useless transitions from the $\\mathcal{O}(n^5)$. But it is, in fact, still redundant. It can be reduced further. We only wanted to split our range into three disjoint ones. But even by just splitting the range into two, it later splits into two other disjoint ones in our subproblem. Now we don't need to split into three, only two is necessary. So it is as follows. $\\text{dp}_{[L,R]}=\\max\\left ({ {\\max_{L < i < R}{\\left ({\\text{dp}_{[L+1,i-1]}+\\text{dp}_{[i+1,R-1]}+\\text{score}(L,i,R)}\\right )}},{\\max_{L \\le i < R}{\\left ({\\text{dp}_{[L,i]}+\\text{dp}_{[i+1,R]}}\\right )}} }\\right)$ Now this computes the correct answer in $\\mathcal{O}(n^3)$, which is the complexity we needed. It is important to note that even though it might be easy to see the similarity to Triangulation DP problems (such as the Matrix Chain Product problem), it is not an immediate transformation from such problems. That is, it is not easy to lead to a correct transition by modifying the transition starting from Triangulation DP, and likely there will be quite an excessive amount of states that you need to compute even if you did.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nusing ll=long long;\n \nll dp[505][505];\n \nint main()\n{\n    cin.tie(0)->sync_with_stdio(0);\n    int t;cin>>t;\n    for(int tc=0;tc<t;tc++)\n    {\n        ll n;cin>>n;\n        vector<ll>vec(n);\n        for(ll&i:vec)cin>>i;\n        for(int i=0;i<n;i++)\n        {\n            for(int j=0;j<n;j++)dp[i][j]=-1e18;\n        }\n        auto value=[&](ll i,ll j,ll k)\n        {\n            return i*j*k;\n        };\n        for(int len=1;len<=n;len++)\n        {\n            for(int L=0;L<n;L++)\n            {\n                ll ans=0;\n                ll R=(L+len-1)%n;\n                if(len<=2)\n                {\n                    dp[L][R]=0;\n                    continue;\n                }\n                if(len==3)\n                {\n                    dp[L][R]=max(0LL,value(vec[L],vec[(L+1)%n],vec[R]));\n                    continue;\n                }\n                for(int i=(L+1)%n;i!=R;i=(i+1)%n)\n                {\n                    ll val=value(vec[L],vec[i],vec[R]);\n                    if(i!=(L+1)%n)val+=dp[(L+1)%n][(i+n-1)%n];\n                    if(i!=(R+n-1)%n)val+=dp[(i+1)%n][(R+n-1)%n];\n                    ans=max(ans,val);\n                }\n                for(int i=L;i!=R;i=(i+1)%n)\n                {\n                    ans=max(ans,dp[L][i]+dp[(i+1)%n][R]);\n                }\n                dp[L][R]=ans;\n            }\n        }\n        ll ans=0;\n        for(int i=0;i<n;i++)\n        {\n            ans=max(ans,dp[i][(i+n-1)%n]);\n        }\n        cout<<ans<<\"\\n\";\n    }\n}",
    "tags": [
      "dp",
      "geometry"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2075",
    "index": "A",
    "title": "To Zero",
    "statement": "You are given two integers $n$ and $k$; $k$ is an odd number not less than $3$. Your task is to turn $n$ into $0$.\n\nTo do this, you can perform the following operation any number of times: choose a number $x$ from $1$ to $k$ and subtract it from $n$. However, if the \\textbf{current} value of $n$ is even (divisible by $2$), then $x$ must also be even, and if the \\textbf{current} value of $n$ is odd (not divisible by $2$), then $x$ must be odd.\n\nIn different operations, you can choose the same values of $x$, but you don't have to. So, there are no limitations on using the same value of $x$.\n\nCalculate the minimum number of operations required to turn $n$ into $0$.",
    "tutorial": "If you subtract an odd number from an odd number, you will get an even number. And if you subtract an even number from an even number, you will also get an even number. Therefore, after each operation, we obtain an even number. Additionally, we can always subtract the maximum number that we can. If the result of the subtraction is less than $0$, we can simply use a smaller value of $x$ in the last operation. Based on this, we can write the following solution: initially, if $n$ is odd, subtract $k$ from it to make it even (or do nothing if it is already even). Then subtract $(k-1)$ from the resulting $n$ until we reach $0$ or a negative number. However, we may have to subtract $(k-1)$ from $n$ for a long time. Therefore, let's speed this up. We need to find the minimum number of operations $m$ such that $m(k-1) \\ge n$. That is, $m$ is $\\lceil \\frac{n}{k-1} \\rceil$ (the result of dividing $n$ by $(k-1)$, rounded up). You can simply calculate $\\lceil \\frac{n}{k-1} \\rceil$ using double precision floating-point numbers (type double) and round it using some standard function like ceil; in this problem, you won't have issues with calculation accuracy. However, with large values of $n$ and $k$, you may get an incorrect answer due to precision errors, so it's better to divide $n$ by $(k-1)$ with rounding up using integers. To divide the number $x$ by the number $y$ without using floating-point numbers, you can use one of two methods: either perform integer division of $x$ by $y$ rounding down (this is standard integer division), and then add $1$ to the answer if $x \\bmod y \\ne 0$; or divide $(x+y-1)$ by $y$ rounding down; this will automatically increase the answer by $1$ compared to dividing $x$ by $y$ if $x$ is not divisible by $y$.",
    "code": "t = int(input())\nfor i in range(t):\n    n, k = map(int, input().split())\n    ans = 0\n    if n % 2 == 1:\n        n -= k\n        ans = 1\n    k -= 1\n    ans += (n + k - 1) // k\n    print(ans)",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2075",
    "index": "B",
    "title": "Array Recoloring",
    "statement": "You are given an integer array $a$ of size $n$. Initially, all elements of the array are colored red.\n\nYou have to choose exactly $k$ elements of the array and paint them blue. Then, while there is at least one red element, you have to select any red element with a blue neighbor and make it blue.\n\nThe cost of painting the array is defined as the sum of the first $k$ chosen elements and the last painted element.\n\nYour task is to calculate the maximum possible cost of painting for the given array.",
    "tutorial": "Since the cost depends on the first $k$ painted elements and the last one, it cannot exceed the sum of $(k+1)$ maximum elements of the array. In fact, in most cases, you can get exactly that cost. Let $k \\ge 2$ and the positions of the $(k+1)$ maxima are $p_1, p_2, \\dots, p_k, p_{k+1}$. In this case, you can initially color the elements $p_1, p_3, \\dots, p_k, p_{k + 1}$, then all except $p_2$, and then color the element $p_2$ last. So the cost is exactly the sum of $(k+1)$ maxima. This works because the element we want to color last is between two elements we choose initially. However, if $k=1$, then whatever element we choose and how we color the remaining elements, the first or the last element of the array will be the last to be colored. Therefore, in this case, you can consider two options (and pick the one with the maximum cost): the element among the first $(n-1)$ positions is painted first, and the $n$-th element is painted last; or the element among the last $(n-1)$ positions is painted first, and the $1$-st element is painted last.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n  int t;\n  cin >> t;\n  while (t--) {\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n);\n    for (auto &x : a) cin >> x;\n    long long ans = 0;\n    if (k > 1) {\n      sort(a.begin(), a.end(), greater<int>());\n      ans = accumulate(a.begin(), a.begin() + k + 1, 0LL);\n    } else {\n      int l = *max_element(a.begin(), a.end() - 1);\n      int r = *max_element(a.begin() + 1, a.end());\n      ans = max(l + a.back(), r + a[0]);\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2075",
    "index": "C",
    "title": "Two Colors",
    "statement": "Monocarp has installed a new fence at his summer house. The fence consists of $n$ planks of the same size arranged in a row.\n\nMonocarp decided that he would paint his fence according to the following rules:\n\n- each plank of the fence will be painted in exactly one color;\n- the number of different colors that the planks will be painted in is \\textbf{exactly} two;\n- the planks of the fence that are painted in the same color must form a continuous sequence, meaning that for all pairs of planks painted in the same color, there will be no planks painted in a different color between them.\n\nMonocarp has $m$ different paints, and the paint of the $i$-th color is sufficient to paint no more than $a_i$ planks of the fence. Monocarp will not buy any additional paints.\n\nYour task is to determine the number of different ways to paint the fence that satisfy all of Monocarp's described wishes. Two ways to paint are considered different if there exists a plank that is painted in different colors in these two ways.",
    "tutorial": "Consider a general form of a fence: the planks from $1$ to $k$ are painted in one color, and the planks from $k + 1$ to $n$ are painted in another color. Let's iterate over the value of $k$. It is then easy to determine which colors are suitable for the first half and which are suitable for the second half. Any color with $a_i \\ge k$ will work for the first half, while for the second half, the colors must satisfy $a_i \\ge n - k$. If we sort the values of $a_i$ in non-decreasing order, we can find the number of available colors using binary search. In C++, we can use lower_bound, and in Python, we can use bisect.bisect_left. Let there be $x$ candidates for the first half and $y$ candidates for the second half. We would like the number of ways to choose two colors to be equal to $x \\cdot y$. However, we have accidentally counted cases where we chose the same color for both halves of the fence. The number of such cases is $\\min(x, y)$, as that color must be sufficient for both halves. Therefore, the contribution of $k$ to the answer is $x \\cdot y - \\min(x, y)$. Sum up the answers for all $k$ to obtain the final answer to the problem. Overall complexity: $O((n + m) \\log m)$ for each test case.",
    "code": "from bisect import bisect_left\n\nfor _ in range(int(input())):\n    n, m = map(int, input().split())\n    a = sorted(list(map(int, input().split())))\n    ans = 0\n    for k in range(1, n):\n        x = m - bisect_left(a, k)\n        y = m - bisect_left(a, n - k)\n        ans += x * y - min(x, y)\n    print(ans)",
    "tags": [
      "binary search",
      "combinatorics",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2075",
    "index": "D",
    "title": "Equalization",
    "statement": "You are given two non-negative integers $x$ and $y$.\n\nYou can perform the following operation any number of times (possibly zero): choose a positive integer $k$ and divide either $x$ or $y$ by $2^k$ rounding down. The cost of this operation is $2^k$. However, there is an additional constraint: you cannot select the same value of $k$ more than once.\n\nYour task is to calculate the minimum possible cost in order to make $x$ equal to $y$.",
    "tutorial": "Note that for any positive integer $x$, the following equality holds: $\\left\\lfloor\\frac{\\left\\lfloor\\frac{x}{2^a}\\right\\rfloor}{2^b}\\right\\rfloor = \\left\\lfloor\\frac{x}{2^{a+b}}\\right\\rfloor$. This means that for each number, only the total power of two by which it will be divided is significant. Due to the restriction that the same power of two cannot be used twice, we can divide all powers (in this problem, we can consider powers from $1$ to $60$) into three groups: the powers by which $x$ will be divided; the powers by which $y$ will be divided; and the powers that will not be used. However, there may be many suitable partitions, but we need to minimize the cost. To do so, we can use dynamic programming to calculate $dp_{k, i, j}$ - the minimum cost if we considered the first $k$ powers, with the sum of the first group equal to $i$ and the sum of the second group equal to $j$. The transitions in this dynamic programming are straightforward: either we add the next power to the first group, or to the second, or we exclude it. Note that this dynamic programming can be computed once and then used to calculate the answer for any given test case. Using this dynamic programming, the answer can be computed as follows: iterate over $i$ and $j$ such that $\\left\\lfloor\\frac{x}{2^i}\\right\\rfloor = \\left\\lfloor\\frac{y}{2^j}\\right\\rfloor$, and select the minimum among the values $dp_{60, i, j}$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nusing li = long long;\n\nconst int B = 60;\nconst li INF = 1e18;\n\nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  array<array<li, B>, B> dp;\n  for (int i = 0; i < B; ++i) {\n    for (int j = 0; j < B; ++j) {\n      dp[i][j] = INF;\n    }\n  }\n  dp[0][0] = 0;\n  for (int x = 0; x < B; ++x) {\n    for (int i = B - 1; i >= 0; --i) {\n      for (int j = B - 1; j >= 0; --j) {\n        if (dp[i][j] == INF) continue;\n        if (i + x < B) dp[i + x][j] = min(dp[i + x][j], dp[i][j] + (1LL << x));\n        if (j + x < B) dp[i][j + x] = min(dp[i][j + x], dp[i][j] + (1LL << x));\n      }\n    }\n  }\n  int t;\n  cin >> t;\n  while (t--) {\n    li x, y;\n    cin >> x >> y;\n    li ans = INF;\n    for (int i = 0; i < B; ++i) {\n      for (int j = 0; j < B; ++j) {\n        if ((x >> i) == (y >> j)) ans = min(ans, dp[i][j]);\n      }\n    }\n    cout << ans << '\\n';\n  }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "dp",
      "graphs",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2075",
    "index": "E",
    "title": "XOR Matrix",
    "statement": "For two arrays $a = [a_1, a_2, \\dots, a_n]$ and $b = [b_1, b_2, \\dots, b_m]$, we define the XOR matrix $X$ of size $n \\times m$, where for each pair $(i,j)$ ($1 \\le i \\le n$; $1 \\le j \\le m$) it holds that $X_{i,j} = a_i \\oplus b_j$. The symbol $\\oplus$ denotes the bitwise XOR operation.\n\nYou are given four integers $n, m, A, B$. Count the number of such pairs of arrays $(a, b)$ such that:\n\n- $a$ consists of $n$ integers, each of which is from $0$ to $A$;\n- $b$ consists of $m$ integers, each of which is from $0$ to $B$;\n- in the XOR matrix formed from these arrays, there are no more than two distinct values.",
    "tutorial": "If there are at least three pairwise distinct elements in one of the two arrays ($a$ and $b$), then there will also be at least three distinct elements in the matrix. Therefore, we can assume that the number of distinct elements in each of the arrays does not exceed $2$. This allows us to construct the answer from the following parts: the number of pairs of arrays where all elements in $a$ are the same and all elements in $b$ are the same; the number of pairs of arrays where all elements in $a$ are the same, and the number of distinct elements in $b$ is $2$; the number of pairs of arrays where the number of distinct elements in $a$ is $2$, and all elements in $b$ are the same; the number of pairs of arrays where both $a$ and $b$ have two distinct elements each. The first part of the answer is simply $(A+1) \\cdot (B+1)$, as we can choose which number all elements in $A$ will equal, and which number all elements in $B$ will equal. The second and third parts are very similar to each other. Therefore, we will explain how the second part is calculated, and the third can be computed similarly. We can choose which number will be in $a$, and the number of ways to do this is $(A+1)$. We can also choose which two numbers will be in $b$, which can be done in $\\frac{B(B+1)}{2}$ ways. Additionally, we need to choose the positions in $b$ where the first number will be; the number of ways to do this is $2^m - 2$ (not $2^m$, since we need to exclude the cases where the same number appears in all positions). Therefore, the second part of the answer is $(A+1) \\cdot \\frac{B(B+1)}{2} \\cdot (2^m-2)$. The fourth part is the most complex. The main problem is that it is important which specific values we choose for the arrays $a$ and $b$. Let all elements of $a$ be either $a_1$ or $a_2$ ($a_1 > a_2$), and all elements of $b$ be either $b_1$ or $b_2$ ($b_1 > b_2$). Then for this quadruple $(a_1, a_2, b_1, b_2)$, there are $(2^n-2) \\cdot (2^m-2)$ ways to choose which positions in which arrays correspond to which numbers. This must be multiplied by the number of suitable quadruples, so let's learn how to count them. We are interested in quadruples of numbers $(a_1, a_2, b_1, b_2)$ that satisfy the conditions: $0 \\le a_2 < a_1 \\le A$; $0 \\le b_2 < b_1 \\le B$; $a_1 \\oplus b_2 = a_2 \\oplus b_1$ (otherwise, we will have more than two distinct values in the matrix, since $a_1 \\oplus b_1 \\ne a_1 \\oplus b_2$). This condition is also equivalent to $a_1 \\oplus b_1 = a_2 \\oplus b_2$, so if it holds, there are exactly two distinct values in the matrix. The third condition can be rewritten as $a_1 \\oplus a_2 = b_1 \\oplus b_2$. Let's then count not the quadruples $(a_1, a_2, b_1, b_2)$, but the triples $(a_1, b_1, x)$ such that $0 \\le a_1 \\oplus x < a_1 \\le A$ and $0 \\le b_1 \\oplus x < b_1 \\le B$. This can be done using digit dynamic programming on the bits of these three numbers from the most significant to the least significant. Let $dp[i][f_a][f_b][f_x]$ be the number of ways to set the $i$ most significant bits in these three numbers such that: $f_a = 0$, if the number $a_1$ is still equal to the upper limit $A$, or $f_a = 1$, if it is definitely less; $f_b = 0$, if the number $b_1$ is still equal to the upper limit $B$, or $f_b = 1$, if it is definitely less; $f_x = 0$, if the number $x$ is still equal to $0$, or $f_x = 1$, if it is definitely not $0$. Transitions in this dynamic programming are done as follows: we iterate over which values will be in the next bit of these three numbers, check that this does not violate any conditions, and observe how the values of $f_a, f_b, f_x$ change. What conditions do we need to check? We need to ensure that $a_1 \\le A$, so if $f_a$ is $0$ and the next bit in $A$ is $0$, we cannot set $1$ in the next bit of $a_1$; We need to ensure that $b_1 \\le B$ (similarly); We need to ensure that $a_1 \\oplus x < a_1$, so if $f_x$ is $0$ and we set the next bit in $a_1$ to $0$, this bit must also be $0$ in the number $x$; We need to ensure that $b_1 \\oplus x < b_1$ (similarly). The flags $f_a, f_b, f_x$ are recalculated quite trivially, and we will not discuss this in detail in the explanation. The answer should be collected from all states of the form $dp[K][f_a][f_b][1]$, where $K$ is the number of bits in the numbers. This way, we will obtain the number of pairs $(a_1, a_2, b_1, b_2)$ that can be used. This dynamic programming is the most computationally intensive part of the solution, so the entire solution works in $O(\\log \\max(A,B))$, but with a very large constant in the asymptotic notation.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int MOD = 998244353;\nconst int K = 31;\n \nint add(int x, int y)\n{\n    x += y;\n    while(x >= MOD) x -= MOD;\n    while(x < 0) x += MOD;\n    return x;\n}\n \nint sub(int x, int y)\n{\n    return add(x, -y);\n}\n \nint mul(int x, int y)\n{\n    return (x * 1ll * y) % MOD;\n}\n \nint binpow(int x, int y)\n{\n    int z = 1;\n    while(y)\n    {\n        if(y & 1) z = mul(z, x);\n        x = mul(x, x);\n        y >>= 1;\n    }\n    return z;\n}\n \nint dp[K][2][2][2];\n \nint choose2(int n)\n{\n    return mul(n, mul(sub(n, 1), binpow(2, MOD - 2)));\n}   \n \nvoid solve()\n{\n    int n, m, A, B;\n    cin >> n >> m >> A >> B;\n \n    memset(dp, 0, sizeof dp);\n    dp[0][0][0][0] = 1;\n    for(int i = 0; i + 1 < K; i++)\n        for(int f1 = 0; f1 <= 1; f1++)\n            for(int f2 = 0; f2 <= 1; f2++)\n                for(int fx = 0; fx <= 1; fx++)\n                {\n                    int d = dp[i][f1][f2][fx];\n                    if(!d) continue;\n                    int j = K - 2 - i;\n                    int curA = (A >> j) & 1;\n                    int curB = (B >> j) & 1;\n                    for(int bit_a = 0; bit_a <= 1; bit_a++)\n                        for(int bit_b = 0; bit_b <= 1; bit_b++)\n                            for(int bit_x = 0; bit_x <= 1; bit_x++)\n                            {\n                                if(f1 == 0 && bit_a == 1 && curA == 0) continue;\n                                if(f2 == 0 && bit_b == 1 && curB == 0) continue;\n                                if(fx == 0 && bit_x == 1 && (bit_a == 0 || bit_b == 0)) continue;\n                                int nf1 = max(f1, bit_a ^ curA);\n                                int nf2 = max(f2, bit_b ^ curB);\n                                int nfx = max(fx, bit_x);\n                                int& d2 = dp[i + 1][nf1][nf2][nfx];\n                                d2 = add(d2, d);\n                            }\n                }\n    int pairs_of_pairs = 0;\n    for(int i = 0; i <= 1; i++)\n        for(int j = 0; j <= 1; j++)\n            pairs_of_pairs = add(pairs_of_pairs, dp[K - 1][i][j][1]);\n \n    int comb_a = sub(binpow(2, n), 2);\n    int comb_b = sub(binpow(2, m), 2);\n \n    int ans = mul(pairs_of_pairs, mul(comb_a, comb_b));\n    ans = add(ans, mul(add(A, 1), add(B, 1)));\n    ans = add(ans, mul(add(A, 1), mul(comb_b, choose2(add(B, 1)))));\n    ans = add(ans, mul(add(B, 1), mul(comb_a, choose2(add(A, 1)))));\n    cout << ans << endl;\n}\n \nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++) solve();    \n}",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2075",
    "index": "F",
    "title": "Beautiful Sequence Returns",
    "statement": "Let's call an integer sequence \\textbf{beautiful} if the following conditions hold:\n\n- for every element except the first one, there is an element to the left less than it;\n- for every element except the last one, there is an element to the right larger than it;\n\nFor example, $[1, 2]$, $[42]$, $[1, 4, 2, 4, 7]$, and $[1, 2, 4, 8]$ are beautiful, but $[2, 2, 4]$ and $[1, 3, 5, 3]$ are not.\n\nRecall that a subsequence is a sequence that can be obtained from another sequence by removing some elements (possibly zero) without changing the order of the remaining elements.\n\nYou are given an integer array $a$ of size $n$. Find the longest beautiful subsequence of the array $a$ and print its length.",
    "tutorial": "For the start, let's note that the definition of the beauty of a sequence is equivalent to the following: a sequence is beautiful if and only if the first element is a unique minimum and the last element is a unique maximum. Next, consider each element of the array as a point in $2D$: let's transform $a_i$ into the point $(i, a_i)$. Observe that the length of the longest beautiful subsequence can be found as follows: iterate over the position $i$ of the start of the subsequence and the position $j$ of the end of the subsequence; look at the rectangle where the bottom left point is $(i, a_i)$ and the top right point is $(j, a_j)$; take the corners and all points that lie strictly inside this rectangle. Notice that if the chosen point $(i, a_i)$ has another point $i'$, such that $i' < i$ and $a_{i'} \\le a_i$, then the answer for $i'$ will definitely be no worse than for $i$, which means we do not need to check the answer for $i$. Therefore, let's write down in a separate array $\\mathrm{left}$ only those elements that make sense to choose as the bottom left corners of the rectangle. These will be indices $i$ such that for all $i' < i$, $a_{i'} > a_i$ (we will call them prefix minimums). Note that the resulting array $\\mathrm{left}$ has interesting monotonicity properties: $\\mathrm{left}_k < \\mathrm{left}_{k+1}$ and at the same time $a[\\mathrm{left}_k] > a[\\mathrm{left}_{k + 1}]$. Therefore, if we look at an arbitrary point $(x, a_x)$, the left corners of the rectangles it falls into form an interval $\\mathrm{seg}_x = [l, r)$ in the array $\\mathrm{left}$, the boundaries of which can be found using binary search: $l$ is the minimum $l$ such that $a[\\mathrm{left}_l] < a[x]$; $r$ is the minimum $r$ such that $\\mathrm{left}_r \\ge x$. Now, let's note that a similar situation occurs with the top right point: we are only interested in points that form \"suffix maximums\". They will have similar monotonicity: as we move from right to left, the values $a_k$ will only increase. Therefore, let's iterate over the right corner of the rectangle from right to left, maintaining the necessary information for all left corners. Specifically, we will \"include\" and \"exclude\" points, and for each left corner, we will keep track of how many included points are located to its top right. Assume that for the current right corner $k$, we have included only points that lie strictly to its bottom left. Then we can already find the answer for it as follows: let's take the maximum over the left corners from the interval $\\mathrm{seg}_k$ - only these corners can be bottom left for the current corner, and the necessary values are already there. When we need to move from the right corner $k$ to the corner $k' < k$, we know that $a[k'] > a[k]$. Therefore, we need to: include all points $x$ for which $a[k] \\le a[x] < a[k']$; exclude all points $x$ for which $k' \\le x < k$. Including/excluding a point is simply adding $\\pm 1$ over the interval $\\mathrm{seg}_x$. Note that each point is included and excluded no more than once, which means there will be no more than $2n$ operations of addition over the segment. To handle the addition over a segment and the maximum over a segment, it is sufficient to use a Segment Tree. Thus, the resulting asymptotic complexity is $O(n \\log{n})$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n \ntypedef long long li;\ntypedef pair<int, int> pt;\n \nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\n \nvector<int> Tadd, Tmax;\n \nint getmax(int v) {\n\treturn Tmax[v] + Tadd[v];\n}\nvoid push(int v) {\n\tTadd[2 * v + 1] += Tadd[v];\n\tTadd[2 * v + 2] += Tadd[v];\n\tTadd[v] = 0;\n}\nvoid upd(int v) {\n\tTmax[v] = max(getmax(2 * v + 1), getmax(2 * v + 2));\n}\nvoid addVal(int v, int l, int r, int lf, int rg, int val) {\n\tif (l == lf && r == rg) {\n\t\tTadd[v] += val;\n\t\treturn;\n\t}\n\tpush(v);\n\tint mid = (l + r) >> 1;\n\tif (lf < mid)\n\t\taddVal(2 * v + 1, l, mid, lf, min(mid, rg), val);\n\tif (rg > mid)\n\t\taddVal(2 * v + 2, mid, r, max(lf, mid), rg, val);\n\tupd(v);\n}\n \nint n;\nvector<int> a;\n \ninline bool read() {\n\tif(!(cin >> n))\n\t\treturn false;\n\ta.resize(n);\n\tfore (i, 0, n)\n\t\tcin >> a[i];\n\treturn true;\n}\n \ninline void solve() {\n\tvector<int> ask(n, 0);\n\tint mx = -1;\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\tif (a[i] > mx) {\n\t\t\task[i] = 1;\n\t\t\tmx = a[i];\n\t\t}\n\t}\n\tvector<int> left;\n\tfore (i, 0, n) {\n\t\tif (left.empty() || a[left.back()] > a[i])\n\t\t\tleft.push_back(i);\n\t}\n \n\tvector<pt> seg(n);\n\tfore (i, 0, n) {\n\t\tint lf = upper_bound(left.begin(), left.end(), i, [&left](int v, int i) {\n\t\t\treturn a[v] > a[i];\n\t\t}) - left.begin();\n\t\tint rg = lower_bound(left.begin(), left.end(), i) - left.begin();\n\t\tseg[i] = {lf, rg};\n\t}\n \n\tTadd.assign(4 * n, 0);\n\tTmax.assign(4 * n, 0);\n \n\tvector<int> ordToAdd(n);\n\tiota(ordToAdd.begin(), ordToAdd.end(), 0);\n\tsort(ordToAdd.begin(), ordToAdd.end(), [](int i, int j) {\n\t\treturn a[i] < a[j];\n\t});\n \n\tauto addToSeg = [&left, &seg](int id, int val) {\n\t\tauto [lf, rg] = seg[id];\n\t\tif (lf < rg)\n\t\t\taddVal(0, 0, sz(left), lf, rg, val);\n\t};\n \n\tint ans = 0;\n\tint pos = 0;\n\tvector<int> added(n, 0);\n\tfor (int i = n - 1; i >= 0; i--) {\n\t\twhile (pos < n && a[ordToAdd[pos]] < a[i]) {\n\t\t\tif (ordToAdd[pos] <= i) {\n\t\t\t\taddToSeg(ordToAdd[pos], 1);\n\t\t\t\tadded[ordToAdd[pos]] = 1;\n\t\t\t}\n\t\t\tpos++;\n\t\t}\n\t\tif (ask[i]) {\n\t\t\tauto [lf, rg] = seg[i];\n\t\t\tans = max(ans, 1 + (lf < rg ? 1 + getmax(0) : 0));\n\t\t}\n\t\tif (added[i]) {\n\t\t\taddToSeg(i, -1);\n\t\t\tadded[i] = 0;\n\t\t}\n\t}\n\tcout << ans << endl;\n}\n \nint main() {\n#ifdef _DEBUG\n\tfreopen(\"input.txt\", \"r\", stdin);\n\tint tt = clock();\n#endif\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0), cout.tie(0);\n\tcout << fixed << setprecision(15);\n\t\n\tint t; cin >> t;\n\twhile(t--) {\n\t\t(read());\n\t\tsolve();\n\t\t\n#ifdef _DEBUG\n\t\tcerr << \"TIME = \" << clock() - tt << endl;\n\t\ttt = clock();\n#endif\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "implementation"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2077",
    "index": "A",
    "title": "Breach of Faith",
    "statement": "\\begin{quote}\nBreach of Faith - Supire feat.eili\n\\end{quote}\n\nYou and your team have worked tirelessly until you have a sequence $a_1, a_2, \\ldots, a_{2n+1}$ of positive integers satisfying these properties.\n\n- $1 \\le a_i \\le 10^{18}$ for all $1 \\le i \\le 2n + 1$.\n- $a_1, a_2, \\ldots, a_{2n+1}$ are pairwise \\textbf{distinct}.\n- $a_1 = a_2 - a_3 + a_4 - a_5 + \\ldots + a_{2n} - a_{2n+1}$.\n\nHowever, the people you worked with sabotaged you because they wanted to publish this sequence first. They deleted one number from this sequence and shuffled the rest, leaving you with a sequence $b_1, b_2, \\ldots, b_{2n}$. You have forgotten the sequence $a$ and want to find a way to recover it.\n\nIf there are many possible sequences, you can output any of them. It can be proven under the constraints of the problem that at least one sequence $a$ exists.",
    "tutorial": "Rearrange the equation around. Try to maximize the missing number. The equation can be rearranged to $a_{2n} = a_1 + (a_3 - a_2) + (a_5 - a_4) + \\ldots + (a_{2n-1} - a_{2n-2}) + a_{2n+1}$ Choose $a_1$ as the largest number, $a_3, a_5, \\ldots, a_{2n+1}$ as the next $n$ largest numbers, and the rest as $a_2, a_4, \\ldots, a_{2n-2}$. The value of the missing number $a_{2n}$ will be larger than $a_1$, and so larger than every number in $b$. Time complexity: $\\mathcal{O}(n \\log n)$ per test case. Logarithmic factor is from sorting.",
    "code": "for test_case in range(int(input())):\n    n = int(input())\n    b = sorted([int(_) for _ in input().split()])\n    \n    a = [0 for _ in range(2*n+1)]\n    \n    # Implementation note: 0-based index used here\n    # assign a[0], a[2], ... large numbers\n    for i in range(0, n+1):\n        a[2*i] = b[n+i-1]\n        \n    # assign a[1], a[3], .. small numbers\n    for i in range(0, n-1):\n        a[2*i+1] = b[i]\n        \n    \n    a[2*n-1] = sum(b[n-1:]) - sum(b[:n-1])\n    print(*a)\n    \n# model solution",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2077",
    "index": "B",
    "title": "Finding OR Sum",
    "statement": "\\begin{quote}\nALTER EGO - Yuta Imai vs Qlarabelle\n\\end{quote}\n\nThis is an interactive problem.\n\nThere are two hidden non-negative integers $x$ and $y$ ($0 \\leq x, y < 2^{30}$). You can ask no more than $2$ queries of the following form.\n\n- Pick a non-negative integer $n$ ($0 \\leq n < 2^{30}$). The judge will respond with the value of $(n \\mathbin{|} x) + (n \\mathbin{|} y)$, where $|$ denotes the bitwise OR operation.\n\nAfter this, the judge will give you another non-negative integer $m$ ($0 \\leq m < 2^{30}$). You must answer the correct value of $(m \\mathbin{|} x) + (m \\mathbin{|} y)$.",
    "tutorial": "Try to get information on half of the bits. Alternate the bits. The queries are $\\ldots 0101_2$ and $\\ldots 1010_2$. It's easier to look at the case with only two binary digits first. Let the result of query $01_2$ be $q_1$ and $10_2$ be $q_2$. Observe that if $q_2 = 100_2$ then the first (from the right) digit of both $x$ and $y$ is $0$. $q_2 = 100_2$ then the first (from the right) digit of both $x$ and $y$ is $0$. $q_2 = 101_2$ then the first (from the right) digit of one of $x$ or $y$ is $0$, and the other one is $1$. $q_2 = 101_2$ then the first (from the right) digit of one of $x$ or $y$ is $0$, and the other one is $1$. $q_2 = 110_2$ then the first (from the right) digit of both $x$ and $y$ is $1$. $q_2 = 110_2$ then the first (from the right) digit of both $x$ and $y$ is $1$. Similarly, if $q_1 = 10_2$ then the second (from the right) digit of both $x$ and $y$ is $0$. $q_1 = 10_2$ then the second (from the right) digit of both $x$ and $y$ is $0$. $q_1 = 100_2$ then the second (from the right) digit of one of $x$ or $y$ is $0$, and the other one is $1$. $q_1 = 100_2$ then the second (from the right) digit of one of $x$ or $y$ is $0$, and the other one is $1$. $q_1 = 110_2$ then the second (from the right) digit of both $x$ and $y$ is $1$. $q_1 = 110_2$ then the second (from the right) digit of both $x$ and $y$ is $1$. To generalize to every other digit, apply the same logic to every consecutive pair of digits in $x$ and $y$. Note that you must account for the carries from the digits before too. After this, you will know for every digit position whether both $x$ and $y$ are $0$, are $1$, or have one $0$ and one $1$. You can use this information to find $(m|x) + (m|y)$ for any $m$. Time complexity: $\\mathcal{O}(\\log \\max (x))$ per test case.",
    "code": "def query(n):\n    print(n)\n    return int(input())\n \ndef end_query():\n    print(\"!\")\n    return int(input())\n \ndef test_case():\n    n0, n1 = 0, 0\n \n    for i in range(1, 30, 2):\n        n0 |= (1 << i)\n    for i in range(0, 30, 2):\n        n1 |= (1 << i)\n    \n    q0 = query(n0)\n    q1 = query(n1)\n    m = end_query()\n    \n    val_and, val_or = 0, 0\n    \n    # solve for even indices\n    for i in range(0, 30, 2):\n        curf = (q0 >> (i + 1)) & 1\n        curb = (q0 >> i) & 1\n        pos = (1 << i)\n        \n        if curf:\n            # 10\n            val_and |= pos\n            val_or |= pos\n        elif curb:\n            # 01\n            val_or |= pos\n        \n        q0 -= 4 * pos\n    \n    # solve for odd indices\n    q1 -= 2\n    for i in range(1, 30, 2):\n        curf = (q1 >> (i + 1)) & 1\n        curb = (q1 >> i) & 1\n        pos = (1 << i)\n        \n        if curf and not curb:\n            # 10\n            val_and |= pos\n            val_or |= pos\n        elif not curf and curb:\n            # 01\n            val_or |= pos\n        \n        q1 -= 4 * pos\n    \n    ans = 0\n    for i in range(0, 30):\n        cur = (m >> i) & 1\n        curand = (val_and >> i) & 1\n        curor = (val_or >> i) & 1\n        pos = (1 << i)\n        if cur or curand:\n            ans += 2 * pos\n        elif curor:\n            ans += pos\n    \n    print(ans)\n \nif __name__ == \"__main__\":\n    t = int(input())\n    for _ in range(t):\n        test_case()\n        \n# model solution",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "implementation",
      "interactive",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2077",
    "index": "C",
    "title": "Binary Subsequence Value Sum",
    "statement": "\\begin{quote}\nLast | Moment - onoken\n\\end{quote}\n\nFor a binary string$^{\\text{∗}}$ $v$, the score of $v$ is defined as the maximum value of\n\n$$F\\big(v, 1, i\\big) \\cdot F\\big(v, i+1, |v|\\big)$$\n\nover all $i$ ($0 \\leq i \\leq |v|$).\n\nHere, $F\\big(v, l, r\\big) = r - l + 1 - 2 \\cdot \\operatorname{zero}(v, l, r)$, where $\\operatorname{zero}(v, l, r)$ denotes the number of $\\mathtt{0}$s in $v_lv_{l+1} \\ldots v_r$. If $l > r$, then $F\\big(v, l, r\\big) = 0$.\n\nYou are given a binary string $s$ of length $n$ and a positive integer $q$.\n\nYou will be asked $q$ queries.\n\nIn each query, you are given an integer $i$ ($1 \\leq i \\leq n$). You must flip $s_i$ from $\\mathtt{0}$ to $\\mathtt{1}$ (or from $\\mathtt{1}$ to $\\mathtt{0}$). Find the sum of the scores over all non-empty subsequences$^{\\text{†}}$ of $s$ after each modification query.\n\nSince the result may be large, output the answer modulo $998\\,244\\,353$.\n\nNote that the modifications are persistent.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string is a string that consists only of the characters $\\mathtt{0}$ and $\\mathtt{1}$.\n\n$^{\\text{†}}$A binary string $x$ is a subsequence of a binary string $y$ if $x$ can be obtained from $y$ by deleting several (possibly zero or all) characters.\n\\end{footnotesize}",
    "tutorial": "Find a closed-form expression for the score of a binary string. The closed-form expression for the score of a binary string is $\\lfloor \\frac{cnt_0-cnt_1}{2} \\rfloor \\lceil \\frac{cnt_0-cnt_1}{2} \\rceil$ Where $cnt_0$ and $cnt_1$ are the number of $\\tt{0}$ and $\\tt{1}$ in the binary string, respectively. $\\lfloor \\frac{cnt_0-cnt_1}{2} \\rfloor \\lceil \\frac{cnt_0-cnt_1}{2} \\rceil = \\frac{(cnt_0-cnt_1)^2}{4} - \\frac{(cnt_0-cnt_1 \\mod 2)}{4}$ The expression for counting subsequences might be simpler than you think. Think of $\\tt{0}$ as $-1$ and $\\tt{1}$ as $1$. Let us count the number of subsequences of a binary string which will have the sum of $i$. Let $cnt_0$ and $cnt_1$ as the number of $\\tt{0}$ and $\\tt{1}$ in the binary string. The number of subsequences is ${n} \\choose {i + cnt_0}$ We change the perspective on $\\tt{0}$ slightly from contributing $-1$ to the sum if chosen and $0$ to the sum if not chosen, to contributing $0$ to the sum if chosen and $1$ to the sum if not chosen. This changes the problem to having $cnt_0 + cnt_1 = n$ distinct objects and needing to pick $i+cnt_0$ of them. So the desired sum of the score over all subsequences (see expression of score of a single string in Hint 2) is $\\sum_{i = -cnt_0}^{n - cnt_0} {{n} \\choose {i + cnt_0}} (\\frac{i^2}{4} - \\frac{(i \\mod 2)}{4})$ At this point, you can throw convolution at the problem by precomputing the answer for $cnt_0 = 0, 1, \\ldots, n$ and solve it in $\\mathcal{O}(n \\log n + q)$. Alternatively, you can do more algebra to arrive at a closed-form expression. $2^{n-4}(n(n+1) - 4cnt_0n + 4cnt_0^2 - 2)$ Consider $\\sum_{i = -cnt_0}^{n - cnt_0} {{n} \\choose {i + cnt_0}} i^2$ $= \\sum_{i = 0}^{n} {{n} \\choose {i}} (i-cnt_0)^2$ $= \\sum_{i = 0}^{n} {{n} \\choose {i}} i^2 - 2cnt_0 \\sum_{i = 0}^{n} {{n} \\choose {i}} i + cnt_0^2 \\sum_{i = 0}^{n} {{n} \\choose {i}} 1$ $= n(n+1) \\cdot 2^{n-2} - 2cnt_0 n \\cdot 2^{n-1} + cnt_0^2 \\cdot 2^n$ And $\\sum_{i = -cnt_0}^{n - cnt_0} {{n} \\choose {i + cnt_0}} (i \\mod 2) = 2^{n-1}$ So $\\frac{1}{4} \\sum_{i = -cnt_0}^{n - cnt_0} {{n} \\choose {i + cnt_0}} i^2 + (i \\mod 2)$ $= \\frac{1}{4} (n(n+1) \\cdot 2^{n-2} - 2cnt_0 n \\cdot 2^{n-1} + cnt_0^2 \\cdot 2^n - 2^{n-1})$ $= 2^{n-4}(n(n+1) - 4cnt_0n + 4cnt_0^2 - 2)$ Time complexity: $\\mathcal{O}(n+q)$ per test case.",
    "code": "mod = 998244353\n \nimport sys\ninput = sys.stdin.readline\nfor test_case in range(int(input())):\n    n, q = map(int, input().split())\n    s = list(map(int, list(input()[:-1])))\n    cnt0 = n - sum(s)\n    pw2 = pow(2, n-4+mod-1, mod)\n    for _ in range(q):\n        a = int(input()) - 1\n        cnt0 += 2 * s[a] - 1\n        s[a] = 1 - s[a]\n        \n        ans = pw2 * (n*(n+1) - 4*cnt0*n + 4*cnt0*cnt0 - 2) % mod\n        ans = (ans + mod) % mod\n        \n        print(ans)\n        \n# model solution, math",
    "tags": [
      "combinatorics",
      "data structures",
      "dp",
      "fft",
      "math",
      "matrices"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2077",
    "index": "D",
    "title": "Maximum Polygon",
    "statement": "Given an array $a$ of length $n$, determine the lexicographically largest$^{\\text{∗}}$ subsequence$^{\\text{†}}$ $s$ of $a$ such that $s$ can be the side lengths of a polygon.\n\nRecall that $s$ can be the side lengths of a polygon if and only if $|s| \\geq 3$ and\n\n$$ 2 \\cdot \\max(s_1, s_2, \\ldots, s_{|s|}) < s_1 + s_2 + \\ldots + s_{|s|}. $$\n\nIf no such subsequence $s$ exists, print $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds:\n\n- $x$ is a prefix of $y$, but $x \\ne y$;\n- in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$.\n\n$^{\\text{†}}$A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deleting several (possibly zero or all) elements.\n\\end{footnotesize}",
    "tutorial": "Find a way to get the answer if you fixed the largest value or the first value of the subsequence. Sufficiently long (which is not that long) arrays will definitely be polygon side lengths. Suppose we consider some integer $x$, and we try to find the lexicographically largest subsequence (say $s$) such that the maximum element of $s$ is $x$. We can do it greedily. For the subsequence $s$ to be valid, we need to ensure that the sum of the elements of $s$ is greater than $2x$. So, our greedy strategy is like we have an empty vector $s$, and we iterate over the array $a$ from left to right, and for each element $a_i$, we do the following: If $s$ is not empty and $a_i$ is greater than the last element of $s$, we will check whether we can make the total sum of $s$ greater than $2x$, if we remove the last element of $s$. Now what can be the maximum possible sum of $s$? We can just append all the elements of $a$ which are less than or equal to $x$, and are present to the right of $a_i$ to $s$. Append $a_i$ to $s$. Thus, we see that the subsequence $s$ is the lexicographically largest subsequence such that the maximum element of $s$ is $x$. Now, we have $O(n)$ candidates for the maximum element of $s$. We cannot find the best subsequence for each candidate, as it will be too slow. Here comes the key observation. Now, what can be the maximum possible size of a sorted vector $v$ such that there does not exist any subsequence of $v$ which can form the sides of a valid polygon? We should have $v_i > \\sum_{j=1}^{i-1} v_j$. Now, to get the maximum possible size of $v$, we should have $v_1 = 1$ and $v_i = 2^{i - 2}$ for $i \\geq 2$. Thus, the maximum possible size of $v$ can be $p = \\log_2(10^9) + 2$. Our claim is that in the lexicographically largest subsequence $s$, the maximum element should be one of the largest $p + 1$ elements of $a$. Suppose we do not have the maximum element of $s$ in the largest $p + 1$ elements of $a$. Let's consider the multiset of the largest $p + 1$ elements of $a$. As we saw above, there should be a subsequence (say $t$) of this multiset which forms the sides of a valid polygon. Now if we insert the elements of $t$ in $s$, we will get a subsequence $s'$ such that $s'$ is valid and $s'$ is lexicographically larger than $s$. Thus, we cannot have a subsequence $s$ such that $s$ is the largest possible subsequence and the maximum element of $s$ is not in the largest $p + 1$ elements of $a$. Time complexity: $\\mathcal{O}(n \\log \\max(a))$ per test case.",
    "code": "#pragma GCC optimize(\"Ofast\")\n \n#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\n#define ld long double\n#define nline \"\\n\"\n#define f first\n#define s second\nconst ll INF_MUL=1e13;\nconst ll INF_ADD=1e18;\n#define sz(x) (ll)x.size()\n#define vl vector<ll>\n#define all(x) x.begin(),x.end()\n#define rall(x) x.rbegin(),x.rend() \nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\ntypedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\ntypedef tree<pair<ll,ll>, null_type, less<pair<ll,ll>>, rb_tree_tag, tree_order_statistics_node_update> ordered_pset;\n//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------     \nconst ll MOD=998244353;\nconst ll MAX=500500;\nvoid solve(){\n  ll n; cin>>n;\n  vector<ll> ans,p(n+5);\n  vector<ll> track;\n  for(ll i=1;i<=n;i++){\n    cin>>p[i];\n    track.push_back(p[i]);\n  }\n  ll till=min(60ll,n);\n  sort(rall(track));\n  vector<ll> consider;\n  for(ll i=0;i<=till-1;i++){\n    consider.push_back(track[i]);\n  }\n  for(ll x:consider){\n    vector<ll> cur;\n    vector<ll> sum(n+5,0);\n    for(ll i=n;i>=1;i--){\n      sum[i]=sum[i+1];\n      if(p[i]<=x){\n        sum[i]+=p[i];\n      }\n    }\n    ll need=2*x+1;\n    if(sum[1]<=need-1){\n      continue;\n    }\n    ll have=0;\n    for(ll i=1;i<=n;i++){\n      if(p[i]>x){\n        continue;\n      }\n      while(!cur.empty()){\n        auto last=cur.back();\n        if(last<p[i] and have-last+sum[i]>=need){\n          cur.pop_back();\n          have-=last;\n        }\n        else{\n          break;\n        }\n      }\n      cur.push_back(p[i]);\n      have+=p[i];\n    }\n    ans=max(ans,cur);\n  }\n  if(ans.empty()){\n    cout<<\"-1\\n\";\n    return;\n  }\n  cout<<sz(ans)<<nline;\n  for(auto it:ans){\n    cout<<it<<\" \";\n  }\n  cout<<nline;\n  return;\n}\nint main()                                                                                 \n{         \n  ios_base::sync_with_stdio(false);                         \n  cin.tie(NULL);                             \n  ll test_cases=1;\n  cin>>test_cases;\n  while(test_cases--){\n    solve();\n  }\n  cout<<fixed<<setprecision(15); \n  cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}\n \n// model solution",
    "tags": [
      "brute force",
      "data structures",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2077",
    "index": "E",
    "title": "Another Folding Strip",
    "statement": "For an array $b$ of length $m$, define $f(b)$ as follows.\n\nConsider a $1 \\times m$ strip, where all cells initially have darkness $0$. You want to transform it into a strip where the color at the $i$-th position has darkness $b_i$. You can perform the following operation, which consists of two steps:\n\n- Fold the paper at any line between two cells. You may fold as many times as you like, or choose not to fold at all.\n- Choose \\textbf{one} position to drop the black dye. The dye permeates from the top and flows down to the bottom, increasing the darkness of all cells in its path by $1$. After dropping the dye, you unfold the strip.\n\nLet $f(b)$ be the minimum number of operations required to achieve the desired configuration. It can be proven that the goal can always be achieved in a finite number of operations.\n\nYou are given an array $a$ of length $n$. Evaluate\n\n$$\\sum_{l=1}^n\\sum_{r=l}^n f(a_l a_{l+1} \\ldots a_r)$$\n\nmodulo $998\\,244\\,353$.",
    "tutorial": "Folding is basically alternating the parity of the indices. Maximum subarray sum. As mentioned in Hint 1, we can see that if the darkness of the cells $i_1, i_2, \\ldots, i_k$ increases in some operation, the parity of $i_j$ should be different from that of $i_{j+1}$ for $1 \\le j \\le k - 1$ Let us try to find $f(a[1, n])$. Consider an array $b$ such that $b_i = (-1)^i a_i$ for all $1 \\le i \\le n$. Let us perform exactly one operation, and say our subsequence of indices is $i_1, i_2, \\ldots, i_k$. Let $a'$ be the updated array after performing the operation, and $b'_i = (-1)^{i'} a'_i$ for all $1 \\le i \\le n$. Now we can see that $\\left| \\sum_{i = l}^{r} b'_i - \\sum_{i = l}^{r} b_i \\right| \\le 1,$ for all $1 \\le l \\le r \\le n$. This is so because for any subarray $b[l, r]$, if $x$ elements at odd indices and $y$ elements at even indices were selected, we should have $|x - y| \\le 1$. So, we can see that after any operation, the absolute sum of any subarray of $b$ decreases by at most $1$. Thus, this gives us a lower bound for the value of $f(a[1, n])$, which is $\\max_{1 \\le l \\le r \\le n} \\left| \\sum_{i = l}^{r} b_i \\right|.$ Now let us consider the following greedy algorithm for selecting a subsequence $s$ of indices: Start from $i = 1$ and move to the right. If $b_i$ is zero, we continue. If $s$ is empty, we append $i$ to $s$, and continue. If $i$ does not have the same parity as the last element of $s$, we append $i$ to $s$, and continue. Otherwise, we continue. Now suppose $T$ is the set of pairs of indices $(l, r)$ such that $b_l$ and $b_r$ are nonzero and $\\left| \\sum_{i = l}^{r} b_i \\right|$ is maximized. We can prove that the absolute sum of all subarrays in $T$ would be reduced by $1$ after performing the operation. We can notice that if $(l, r) \\in T$, then $l$ and $r$ should have the same parity. Otherwise, $\\max \\left( \\left| b[l + 1, r] \\right|, \\left| b[l, r - 1] \\right| \\right) > \\left| b[l, r] \\right|.$ Next, we claim that $l$ should be in $s$. Suppose $l$ is not in $s$. This means that there should be an index $k$ in $s$ such that $k$ has the same parity as $l$ and there are no nonzero elements between $k$ and $l$ that have a parity different from $l$. Now if that is the case, then $b[k, r]$ would have a greater absolute sum than $b[l, r]$. Thus, we conclude that $l$ will always be in $s$. Now let $d$ be the largest index in $s$ smaller than or equal to $r$. First of all, we should have $d \\ge l$. Now $d$ should have the same parity as $r$. This is so because if that is not the case, we should have $d < r$ and we would have selected $r$ or any other element having the same parity as $r$ after $d$ in $s$. Thus, we can see that for all the pairs $(l, r) \\in T$, we should have $l$ in $s$ and the largest element smaller than or equal to $r$ in $s$ should have the same parity as that of $r$. This implies that the absolute sum of all subarrays in $T$ would be reduced by $1$ after performing the operation. This is because if $l$ is odd, we would have added $1, -1, 1, -1, \\ldots, 1$ to the subarray $b[l, r]$, increasing the subarray sum of $b[l, r]$ by $1$. And if $l$ is even, we would have added $-1, 1, -1, 1, \\ldots, -1$ to the subarray $b[l, r]$, decreasing the subarray sum of $b[l, r]$ by $1$. Now we can see that the greedy algorithm would achieve the lower bound. So, the answer for the array $a$ is the maximum absolute sum over all subarrays of $b$. Let us consider an array $c$ such that $c_i = c_{i - 1} + b_i, \\quad \\text{with } c_0 = 0.$ We can further notice that the maximum absolute sum over all subarrays of $b$ is equal to $\\max_{1 \\le i \\le n} c_i - \\min_{1 \\le i \\le n} c_i.$ Now we can see that $f(a[l, r]) = \\max_{l \\le i \\le r} c_i - \\min_{l \\le i \\le r} c_i.$ Thus, $\\sum_{l = 1}^{n} \\sum_{r = l}^{n} f(a[l, r]) = \\sum_{l = 1}^{n} \\sum_{r = l}^{n} \\max_{l \\le i \\le r} c_i - \\min_{l \\le i \\le r} c_i.$ So, $\\sum_{l = 1}^{n} \\sum_{r = l}^{n} f(a[l, r]) = \\sum_{l = 1}^{n} \\sum_{r = l}^{n} \\max_{l \\le i \\le r} c_i - \\sum_{l = 1}^{n} \\sum_{r = l}^{n} \\min_{l \\le i \\le r} c_i.$ Finding the value of $\\sum_{l = 1}^{n} \\sum_{r = l}^{n} \\max_{l \\le i \\le r} c_i$ is a fairly standard exercise, which can be done using a stack in $O(n)$ time.",
    "code": "#pragma GCC optimize(\"Ofast\")\n \n#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\n#define ld long double\n#define nline \"\\n\"\n#define f first\n#define s second\nconst ll INF_MUL=1e13;\nconst ll INF_ADD=1e18;\n#define sz(x) (ll)x.size()\n#define vl vector<ll>\n#define all(x) x.begin(),x.end()\n#define rall(x) x.rbegin(),x.rend() \nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\ntypedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\ntypedef tree<pair<ll,ll>, null_type, less<pair<ll,ll>>, rb_tree_tag, tree_order_statistics_node_update> ordered_pset;\n//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------     \nconst ll MOD=998244353;\nconst ll MAX=500500;\nvoid solve(){\n  ll n; cin>>n;\n  vector<ll> a(n+5),c(n+5,0);\n  for(ll i=1;i<=n;i++){\n    cin>>a[i];\n    ll val=a[i];\n    if(i&1){\n      val=-val;\n    }\n    c[i]=c[i-1]+val;\n  }\n  auto getv=[&](vector<ll> d,ll status){\n    set<ll> track;\n    track.insert(-1); track.insert(n+1);\n    vector<pair<ll,ll>> consider;\n    ll sum=0;\n    for(ll i=0;i<=n;i++){\n      if(status==0){\n        c[i]=-c[i];\n      }\n      consider.push_back({c[i],i});\n    }\n    sort(rall(consider));\n    for(auto it:consider){\n      ll val=it.f,pos=it.s;\n      ll now=val%=MOD;\n      track.insert(pos);\n      ll l=*(--track.lower_bound(pos)),r=*(track.upper_bound(pos));\n      ll subarrays=((pos-l)*(r-pos))%MOD;\n      sum=(sum+now*subarrays)%MOD;\n    }\n    sum=(sum+MOD)%MOD;\n    return sum;\n  };\n  ll ans=(getv(c,1)+getv(c,0))%MOD;\n  cout<<ans<<nline;\n  return;\n}\nint main()                                                                                 \n{                                     \n  ll test_cases=1;\n  cin>>test_cases;\n  while(test_cases--){\n    solve();\n  }\n  cout<<fixed<<setprecision(12); \n  cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n}  ",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "data structures",
      "divide and conquer",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2077",
    "index": "F",
    "title": "AND x OR",
    "statement": "Suppose you have two arrays $c$ and $d$, each of length $k$. The pair $(c, d)$ is called \\textbf{good} if $c$ can be changed to $d$ by performing the following operation any number of times.\n\n- Select two distinct indices $i$ and $j$ ($1 \\leq i, j \\leq k$, $i \\neq j$) and a nonnegative integer $x$ ($0 \\leq x < 2^{30}$). Then, apply the following transformations:\n\n- $c_i := c_i \\mathbin{\\&} x$, where $\\&$ denotes the bitwise AND operation.\n- $c_j := c_j \\mathbin{|} x$, where $|$ denotes the bitwise OR operation.\n\nYou are given two arrays $a$ and $b$, both of length $n$, containing nonnegative integers not exceeding $m$.\n\nYou can perform two types of moves on these arrays any number of times:\n\n- Select an index $i$ ($1 \\leq i \\leq n$) and set $a_i := a_i + 1$.\n- Select an index $i$ ($1 \\leq i \\leq n$) and set $b_i := b_i + 1$.\n\nNote that the elements of $a$ and $b$ may exceed $m$ at some point while performing the moves.\n\nFind the minimum number of moves required to make the pair $(a, b)$ good.",
    "tutorial": "Characterize the property of a good pair of arrays. Think about the last operation that turns a good pair of arrays into the same array. $(a, b)$ is a good pair only if at least one of these two conditions hold $a = b$ $a = b$ There exist two distinct indices $i$, $j$ such that $b_i$ is a submask of $b_j$. There exist two distinct indices $i$, $j$ such that $b_i$ is a submask of $b_j$. If $a \\neq b$, then you need to do at least one operation to $a$. In the last operation, if you choose $i$, $j$, $x$, then $a_i$ is a submask of $x$ and $x$ is a submask of $a_j$. So in the final array, there must be at least one pair of submask and supermask. Next, we will show that this is sufficient. For every index $k$ other than $i$ and $j$, you can do this. Perform operation with $k$, $i$, $0$ Perform operation with $k$, $i$, $0$ Perform operation with $i$, $k$, $b_k$ Perform operation with $i$, $k$, $b_k$ Then Perform operation with $i$, $j$, $0$ Perform operation with $i$, $j$, $0$ Perform operation with $j$, $i$, $0$ Perform operation with $j$, $i$, $0$ Perform operation with $j$, $i$, $b_i$ Perform operation with $j$, $i$, $b_i$ Perform operation with $i$, $j$, $b_j$ Perform operation with $i$, $j$, $b_j$ We need to check the two cases. In the first case, the minimum cost will be $\\sum_{i=1}^n |a_i - b_i|$. In the second case, we want the minimum cost to create a submask-supermask pair in $b$. Solution 1 For explanation simplicity, consider the graph $G$ with $2m$ vertices, representing the numbers from $1$ to $2m$. In this graph, there's an unweighted edge from vertex $i$ to vertex $i+1$, and from vertex $i$ to all submask vertices. Color all vertices in which its value appears in $b$. The answer is the shortest path between all pairs of distinct colored vertices. The implementation itself (see below), uses dynamic programming consisting of three phases. The dynamic programming tracks the first and second closest vertex to each vertex, because the first closest vertex would be itself. Propagate each colored vertices up (from $i$ to $i+1$). Propagate each colored vertices up (from $i$ to $i+1$). Propagate to the submasks (from $i$ to its submasks). Propagate to the submasks (from $i$ to its submasks). Propagate down (from $i$ to $i-1$). Propagate down (from $i$ to $i-1$). Time complexity: $\\mathcal{O}(n \\log n + m \\log m)$ per test case. The $\\log n$ factor is from the implementation which checks for duplicates in $b$ by sorting.",
    "code": "#pragma GCC optimize(\"Ofast\")\n \n#include <bits/stdc++.h>   \n#include <ext/pb_ds/tree_policy.hpp>\n#include <ext/pb_ds/assoc_container.hpp>\nusing namespace __gnu_pbds;   \nusing namespace std;\n#define ll long long\n#define ld long double\n#define nline \"\\n\"\n#define f first\n#define s second\nconst ll INF_MUL=1e13;\nconst ll INF_ADD=1e18;\n#define sz(x) (ll)x.size()\n#define vl vector<ll>\n#define all(x) x.begin(),x.end()\n#define rall(x) x.rbegin(),x.rend() \nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\ntypedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\ntypedef tree<pair<ll,ll>, null_type, less<pair<ll,ll>>, rb_tree_tag, tree_order_statistics_node_update> ordered_pset;\n//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------     \nconst ll MOD=998244353;\nconst ll MAX=500500;\nvoid solve(){\n  ll n,m; cin>>n>>m;\n  m*=2;\n  vector<ll> a(n+5),b(n+5),closest(m+5,-INF_ADD);\n  for(ll i=1;i<=n;i++){\n    cin>>a[i];\n  }\n  vector<ll> found(m+5,0);\n  for(ll i=1;i<=n;i++){\n    cin>>b[i];\n    closest[b[i]]=b[i];\n    found[b[i]]=1;\n  }\n  ll ans=0;\n  for(ll i=1;i<=n;i++){\n    ans+=abs(a[i]-b[i]);\n  }\n  vector<ll> c=b;\n  sort(c.begin()+1,c.begin()+n+1);\n  for(ll i=1;i<=n-1;i++){\n    ans=min(ans,c[i+1]-c[i]);\n  }\n  for(ll i=1;i<=m;i++){\n    closest[i]=max(closest[i],closest[i-1]);\n  }\n  vector<ll> dp(m+5,INF_ADD),trav[m+5];\n  for(ll i=m;i>=0;i--){\n    ans=min(ans,dp[i]+i-closest[i]);\n    if(closest[i]>=0){\n      trav[closest[i]].push_back(i);\n    }\n    for(auto it:trav[i]){\n      dp[it]=min(dp[it],it-closest[it]);\n      for(ll j=0;j<=21;j++){\n        ll v=(1<<j);\n        if(it&v){\n          dp[it^v]=min(dp[it^v],dp[it]);\n        }\n      }\n    }\n    for(ll j=0;j<=21;j++){\n      ll v=(1<<j);\n      if(i&v){\n        dp[i^v]=min(dp[i^v],dp[i]);\n      }\n    }\n  }\n  cout<<ans<<nline;\n  return;\n}\nint main()                                                                                 \n{         \n  ios_base::sync_with_stdio(false);                         \n  cin.tie(NULL);                             \n  ll test_cases=1;\n  cin>>test_cases;\n  while(test_cases--){\n    solve();\n  }\n  cout<<fixed<<setprecision(15); \n  cerr<<\"Time:\"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<\"ms\\n\"; \n} ",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2077",
    "index": "G",
    "title": "RGB Walking",
    "statement": "\\begin{quote}\nRed and Blue and Green - fn and Silentroom\n\\hfill ⠀\n\\end{quote}\n\nYou are given a connected graph with $n$ vertices and $m$ bidirectional edges with weight not exceeding $x$. The $i$-th edge connects vertices $u_i$ and $v_i$, has weight $w_i$, and is assigned a color $c_i$ ($1 \\leq i \\leq m$, $1 \\leq u_i, v_i \\leq n$). The color $c_i$ is either red, green, or blue. It is guaranteed that there is \\textbf{at least} one edge of each color.\n\nFor a walk where vertices and edges may be repeated, let $s_r, s_g, s_b$ denote the sum of the weights of the red, green, and blue edges that the walk passes through, respectively. If an edge is traversed multiple times, each traversal is counted separately.\n\nFind the minimum value of $\\max(s_r, s_g, s_b) - \\min(s_r, s_g, s_b)$ over all possible walks from vertex $1$ to vertex $n$.",
    "tutorial": "It might help to solve this task with two colors first. As in, minimize the difference between red and blue. Walking back and forth can do wonders. Let the difference between the red edges and the blue edges passed be $d$. Let the edge weights of the red edges be $r_1, r_2, \\ldots$ and the blue edges be $b_1, b_2, \\ldots$. Let $c = gcd(r_1, r_2, \\ldots, b_1, b_2, \\ldots)$ and $C = lcm(r_1, r_2, \\ldots, b_1, b_2, \\ldots)$. We can find a walk with $d=0$ which passes every edge and returns to vertex $1$. For each edge, walk to one of its endpoint, walk that edge, and then walk back to vertex $1$ using the same walk. This way, we passed through every edge an even number of times. We will now walk back and forth using the edges we passed. This way, we can add to $d$ by some linear combination of $2r_1, 2r_2, \\ldots, 2b_1, 2b_2, \\ldots$. Because $d$ is divisible by $2c$, we can add to it such that $d=0$ by Bézout's identity. Note: About the \"can add by some linear combination\", there's the slight caveat that we can only add the red and subtract the blue. We can subtract the red (or similarly, add the blue) by first subtracting from blue by $2C$, then add back red just so that it is deficit by the edge weight. After passing every edge and returning to vertex $1$ with $d=0$, we can walk from vertex $1$ to vertex $n$. If the walk have $d$ divisible by $2c$, then the answer is $0$ and $c$ otherwise. The proof of this is similar to the proof above. To check if a walk with $d$ divisible by $2c$ exist or not, create a state graph where each vertex is either \"reach the vertex with $d$ divisible by $2c$\" and \"$d$ not divisible by $2c$\". In the two-color version (in Hint 1), we created a state graph on the parity. Can a similar idea be used? Think about each color separately first. Let the edge weights of the red edges be $r_1, r_2, \\ldots$, the green edges be $g_1, g_2, \\ldots$ and the blue edges be $b_1, b_2, \\ldots$. the edge weights of the red edges be $r_1, r_2, \\ldots$, the green edges be $g_1, g_2, \\ldots$ and the blue edges be $b_1, b_2, \\ldots$. $\\gcd(r_1, r_2, \\ldots)$, $\\gcd(g_1, g_2, \\ldots)$ and $\\gcd(b_1, b_2, \\ldots)$ be $c_r, c_g, c_b$. $\\gcd(r_1, r_2, \\ldots)$, $\\gcd(g_1, g_2, \\ldots)$ and $\\gcd(b_1, b_2, \\ldots)$ be $c_r, c_g, c_b$. the sum of weights of red, green and blue edges traversed be $d_r, d_g, d_b$. the sum of weights of red, green and blue edges traversed be $d_r, d_g, d_b$. Define $<d_{r_1}, d_{g_1}, d_{b_1}> = <d_{r_2}, d_{g_2}, d_{b_2}>$ only if $d_{r_1}-d_{g_1} = d_{r_2}-d_{g_2}$, $d_{r_1}-d_{b_1} = d_{r_2}-d_{b_2}$ and $d_{g_1}-d_{b_1} = d_{g_2}-d_{b_2}$. In a similar manner to hint 1, there's a walk that passes through every edge and have $<d_r, d_g, d_b> = <0, 0, 0>$. Furthermore, if we have $<d_r, d_g, d_b>$, then we can have $<d_r + 2g_r, d_g, d_b>$ and $<d_r - 2g_r, d_g, d_b>$. The analogous statement holds for the other two colors. Consequently, from any reachable $<d_r, d_g, d_b>$, we can have $<s_r, s_g, s_b>$, where $s_r$ is either $0$ or $c_r$ depending on whether $d_r \\equiv 0$ ($\\mod 2c_r$) or $d_r \\equiv c_r$ ($\\mod 2c_r$). The idea holds similarly for the other two colors. This invites us to look at each vertex as $8$ possible states, corresponding to $3$ binary options of each color. We simply need to solve the answer for each reachable state then take the minimum. Each state corresponds to the following system of linear congruences. $d_r \\equiv s_r (\\mod 2c_r)$ $d_g \\equiv s_g (\\mod 2c_g)$ $d_b \\equiv s_b (\\mod 2c_b)$ We aim to minimize $\\max(d_r, d_g, d_b) - \\min(d_r, d_g, d_b)$ over all triplets which satisfy the conditions. To do so, we will fix one of them, which we'll suppose is $d_r$, as the minimum. Denote $f_g(p)$ and $f_b(p)$ as the minimum possible $d_g - (d_r + 2pc_r)$ and $r_b - (d_r + 2pc_r)$ where $r_g, r_p \\geq d_r + 2pc_r$. We want to find $\\min_{k \\in \\mathbb{Z}} \\max(f_g(k), f_b(k))$ Observe that $f_g(k + c_g) = f_g(p)$ and $fb(k + c_b) = f_b(p)$. By the Chinese remainder theorem, the expression above reduces to $\\min_{0 \\leq k < \\gcd(c_g, c_b)} \\max(\\min_{(k_g \\mod \\gcd(c_g, c_b) = k)} f_g(k_g), \\min_{(k_b \\mod \\gcd(c_g, c_b) = k)} f_b(k_b))$ Which can be evaluated in $\\mathcal{O}(x)$. Time complexity: $\\mathcal{O}(n \\log x + x)$ per test case. The logarithmic factor is from gcd computations.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\nusing namespace std;\ntypedef pair<int, int> pii;\n \nvoid test_case() {\n    // read input\n    int n, m, x;\n    cin >> n >> m >> x;\n    \n    vector<tuple<int, int, int>> edge_list[3];\n    map<char, int> color_map = {{'r', 0}, {'g', 1}, {'b', 2}};\n    \n    for (int i = 1; i <= m; i++) {\n        int u, v, w;\n        char c;\n        cin >> u >> v >> w >> c;\n        edge_list[color_map[c]].emplace_back(u, v, w);\n    }\n    \n    // graph constuction\n    int color_gcd[3];\n    vector<pii> edge[n+1];\n    for (int i = 0; i < 3; i++) {\n        color_gcd[i] = get<2>(edge_list[i][0]);\n        for (auto [u, v, w] : edge_list[i]) color_gcd[i] = __gcd(color_gcd[i], w);\n        \n        for (auto [u, v, w] : edge_list[i]) {\n            int val = (1<<i)*(w/color_gcd[i]%2);\n            edge[u].emplace_back(v, val);\n            edge[v].emplace_back(u, val);\n        }\n    }\n    \n    // bfs\n    bool visited[n+1][8];\n    memset(visited, 0, sizeof(visited));\n    queue<pii> bfs_q;\n    bfs_q.emplace(1, 0);\n    \n    while (!bfs_q.empty()) {\n        auto [u, mask] = bfs_q.front();\n        bfs_q.pop();\n        if (visited[u][mask]) continue;\n        visited[u][mask] = true;\n        for (auto [v, val] : edge[u]) bfs_q.emplace(v, mask^val);\n    }\n    \n    // solve answer for each mask\n    int ans = INT_MAX;\n    for (int mask = 0; mask < 8; mask++) {\n        if (!visited[n][mask]) continue;\n        \n        for (int i = 0; i < 3; i++) {\n            int ssz[2];\n            for (int j = 0, cj = 0; j < 3; j++) {\n                if (i == j) continue;\n                ssz[cj++] = color_gcd[j];\n            }\n            int sgcd = 2*__gcd(ssz[0], ssz[1]);\n            \n            int seq[2][sgcd];\n            for (int j = 0; j < sgcd; j++) seq[0][j] = seq[1][j] = (int)1e9;\n            for (int j = 0, cj = 0; j < 3; j++) {\n                if (i == j) continue;\n                for (int k = 0; k < 2*ssz[cj]; k++) {\n                    int vi = ((mask>>i)&1)*color_gcd[i];\n                    int mi = 2*color_gcd[i];\n                    int vj = ((mask>>j)&1)*color_gcd[j];\n                    int mj = 2*color_gcd[j];\n                    seq[cj][k%sgcd] = min(seq[cj][k%sgcd], ((vj - vi - k*mi)%mj + mj)%mj);\n                }\n                cj++;\n            }\n            \n            for (int k = 0; k < sgcd; k++) ans = min(ans, max(seq[0][k], seq[1][k]));\n        }\n    }\n    \n    cout << ans << \"\\n\";\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int t;\n    cin >> t;\n    while (t--) test_case();\n \n    return 0;\n}\n \n// model solution",
    "tags": [
      "bitmasks",
      "chinese remainder theorem",
      "dfs and similar",
      "graphs",
      "number theory"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2078",
    "index": "A",
    "title": "Final Verdict",
    "statement": "\\begin{quote}\nTestify - void (Mournfinale) feat. 星熊南巫\n\\end{quote}\n\nYou are given an array $a$ of length $n$, and must perform the following operation until the length of $a$ becomes $1$.\n\nChoose a positive integer $k < |a|$ such that $\\frac{|a|}{k}$ is an integer. Split $a$ into $k$ subsequences$^{\\text{∗}}$ $s_1, s_2, \\ldots, s_k$ such that:\n\n- Each element of $a$ belongs to exactly one subsequence.\n- The length of every subsequence is equal.\n\nAfter this, replace $a = \\left[ \\operatorname{avg}(s_1), \\operatorname{avg}(s_2), \\ldots, \\operatorname{avg}(s_k) \\right] $, where $\\operatorname{avg}(s) = \\frac{\\sum_{i = 1}^{|s|} s_i}{|s|}$ is the average of all the values in the subsequence. For example, $\\operatorname{avg}([1, 2, 1, 1]) = \\frac{5}{4} = 1.25$.\n\nYour task is to determine whether there exists a sequence of operations such that after all operations, $a = [x]$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements.\n\\end{footnotesize}",
    "tutorial": "Something doesn't change after each operation. The average of the entire array doesn't change after each operation. Simply check whether the average value of $a$ is $x$ or not. Time complexity: $\\mathcal{O}(n)$ per test case.",
    "code": "for test_case in range(int(input())):\n    n, x = [int(_) for _ in input().split()]\n    a = [int(_) for _ in input().split()]\n    if sum(a) == n*x:\n        print(\"YES\")\n    else:\n        print(\"NO\")\n        \n# model solution",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2078",
    "index": "B",
    "title": "Vicious Labyrinth",
    "statement": "\\begin{quote}\nAxium Crisis - ak+q\n\\end{quote}\n\nThere are $n$ cells in a labyrinth, and cell $i$ ($1 \\leq i \\leq n$) is $n - i$ kilometers away from the exit. In particular, cell $n$ is the exit. Note also that each cell is connected to the exit but is not accessible from any other cell in any way.\n\nIn each cell, there is initially exactly one person stuck in it. You want to help everyone get as close to the exit as possible by installing a teleporter in each cell $i$ ($1 \\leq i \\leq n$), which translocates the person in that cell to another cell $a_i$.\n\nThe labyrinth owner caught you in the act. Amused, she let you continue, but under some conditions:\n\n- Everyone must use the teleporter exactly $k$ times.\n- No teleporter in any cell can lead to the same cell it is in. Formally, $i \\neq a_i$ for all $1 \\leq i \\leq n$.\n\nYou must find a teleporter configuration that minimizes the sum of distances of all individuals from the exit after using the teleporter exactly $k$ times while still satisfying the restrictions of the labyrinth owner.\n\nIf there are many possible configurations, you can output any of them.",
    "tutorial": "Try to put as many people in cell $n$ as possible. The minimum sum of distances will always be $1$. The following configuration gives $1$ as the sum of distances. For odd $k$: $n, n, \\ldots, n, n, n-1$ For even $k$: $n-1, n-1, \\ldots, n-1, n, n-1$ And the sum of distances cannot be $0$. Look at this as a directed (or more specifically, a functional) graph. There will be a cycle, and people in the same cycle will never be in the same cell, so not everyone can simultaneously be in cell $n$. Time complexity: $\\mathcal{O}(n)$ per test case.",
    "code": "for test_case in range(int(input())):\n    n, k = [int(_) for _ in input().split()]\n    if k % 2 == 0:\n        for i in range(n-2):\n            print(n-1, end = ' ')\n        print(n, end = ' ')\n        print(n-1)\n    else:\n        for i in range(n-2):\n            print(n, end = ' ')\n        print(n, end = ' ')\n        print(n-1)\n        \n# model solution",
    "tags": [
      "constructive algorithms",
      "graphs",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2078",
    "index": "D",
    "title": "Scammy Game Ad",
    "statement": "Consider the following game.\n\nIn this game, a level consists of $n$ pairs of gates. Each pair contains one left gate and one right gate. Each gate performs one of two operations:\n\n- \\textbf{Addition Operation} (+ a): Increases the number of people in a lane by a constant amount $a$.\n- \\textbf{Multiplication Operation} (x a): Multiplies the current number of people in a lane by an integer $a$. This means the number of people increases by $(a - 1)$ times the current count in that lane.\n\nThe additional people gained from each operation can be assigned to either lane. However, people already in a lane \\textbf{cannot} be moved to the other lane.\n\nInitially, there is one person in each lane. Your task is to determine the maximum total number of people that can be achieved by the end of the level.",
    "tutorial": "It is optimal to place everyone on the same lane. Think about the multiplier. It is best to think of each $\\tt{+}$ as \"how much can we multiply this by\". This is the greedy solution. When we get more people, place all to where the $\\tt{x}$ will occur first. If both lanes have the next multiply at the same gate pair, then choose the one with higher multiply. If the multiply is the same, look to the next multiply. It's easier to think of $\\tt{+}$ as $\\tt{x} 1$. The idea is as follows. Consider the range of gate pairs between two pairs with different multiply, and the pairs in the range all have the same multiply. You have $l$ people on the left side and $r$ on the right side before you enter the range. In this range, you will gain a constant number of people, say $x$, regardless of your actions here. You choose to allocate $y$ to the left side. At the end of the range, there's a pair of gates $\\tt{x} a$ $\\tt{x} b$ where $a > b$ (same argument for case $a < b$). After passing the gate, you will gain $(a-1)(l+y) + (b-1)(r+x-y)$ more people. With the current number people of $l+y$ on the left side and $r+x-y$ on the right side, we can see that maximizing $y$ is the optimal choice, because there always exist an allocation such that both number of people on the left and right side will exceed those with lower selection of $y$. Time complexity: $\\mathcal{O}(n)$ per test case. $\\mathcal{O}(n^2)$ implementations are also acceptable. This is the dynamic programming solution. Let $dp_l[i]$ and $dp_r[i]$ be the maximum possible multiplication possible that can be applied if a person enters the $i$-th left and right gate, respectively. Then we have the following equation (only for left is written, it's the same for the right). If the gate is $\\tt{+}$ $dp_l[i] = dp_l[i+1]$ If the gate is $\\tt{x}$ by $a$ $dp_l[i] = dp_l[i+1] + (a-1)\\max(dp_l[i+1], dp_r[i+1])$ For each $\\tt{+}$, we choose to place people at the side with more multiplication. Time complexity: $\\mathcal{O}(n)$ per test case.",
    "code": "def test_case():\n    n = int(input())\n    op = [[] for _ in range(n+1)]\n    val = [[] for _ in range(n+1)]\n    for i in range(1, n + 1):\n        tmp = input().split()\n        op[i] = [tmp[0], tmp[2]]\n        val[i] = [int(tmp[1]), int(tmp[3])]\n \n    op[0] = ['+', '+']\n    val[0] = [1, 1]\n \n    dp = [[0, 0] for _ in range(n + 2)]\n    dp[n + 1][0] = dp[n + 1][1] = 1\n \n    for i in range(n, 0, -1):\n        dp[i][0] = (dp[i + 1][0] + (val[i][0] - 1) * max(dp[i + 1][0], dp[i + 1][1])) if op[i][0] == 'x' else dp[i + 1][0]\n        dp[i][1] = (dp[i + 1][1] + (val[i][1] - 1) * max(dp[i + 1][0], dp[i + 1][1])) if op[i][1] == 'x' else dp[i + 1][1]\n \n    ans = 0\n    for i in range(1, n + 1):\n        sm = 0\n        if op[i][0] == '+':\n            sm += val[i][0]\n        if op[i][1] == '+':\n            sm += val[i][1]\n        ans += sm * max(dp[i + 1][0], dp[i + 1][1])\n \n    ans += dp[1][0]\n    ans += dp[1][1]\n \n    print(ans)\n \nt = int(input())\nfor _ in range(t):\n    test_case()\n    \n# model solution, dp",
    "tags": [
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2081",
    "index": "A",
    "title": "Math Division",
    "statement": "Ecrade has an integer $x$. He will show you this number in the form of a binary number of length $n$.\n\nThere are two kinds of operations.\n\n- Replace $x$ with $\\left\\lfloor \\dfrac{x}{2}\\right\\rfloor$, where $\\left\\lfloor \\dfrac{x}{2}\\right\\rfloor$ is the greatest integer $\\le \\dfrac{x}{2}$.\n- Replace $x$ with $\\left\\lceil \\dfrac{x}{2}\\right\\rceil$, where $\\left\\lceil \\dfrac{x}{2}\\right\\rceil$ is the smallest integer $\\ge \\dfrac{x}{2}$.\n\nEcrade will perform several operations until $x$ becomes $1$. Each time, he will independently choose to perform either the first operation or the second operation with probability $\\frac{1}{2}$.\n\nEcrade wants to know the expected number of operations he will perform to make $x$ equal to $1$, modulo $10^9 + 7$. However, it seems a little difficult, so please help him!",
    "tutorial": "Consider $x$ in binary form. What are all possible numbers of operations to make $x$ equal to $1$? Consider using dynamic programming to calculate the answer. Similar to the previous problem, the possible number of operations can only be $n-1$ or $n$, depending on whether a carry-over occurs in $x$ during the $(n-1)$ -th operation. We can use dynamic programming to compute the probability of a carry-over occurring during the $(n-1)$ -th operation. Let $f_i$ denote the probability of a carry-over occurring at the $i$ -th least significant bit. The recurrence relation is: $f_i = \\begin{cases} \\dfrac{1}{2} \\times f_{i-1} & x_i = 0 \\\\ \\dfrac{1}{2} \\times (1 - f_{i-1}) + f_{i-1} & x_i = 1 \\end{cases}$ The final answer is given by $n-1+f_{n-1}$. The time complexity is $O(\\sum n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nconst ll inv2 = 5e8 + 4,mod = 1e9 + 7;\nll t,n;\nchar s[1000009];\ninline ll read(){\n\tll s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nint main(){\n\tt = read();\n\twhile (t --){\n\t\tn = read(),scanf(\"%s\",s + 1);\n\t\tll ans = 0;\n\t\tfor (ll i = n;i > 1;i -= 1) ans = (ans + (s[i] == '1')) * inv2 % mod;\n\t\tprintf(\"%lld\\n\",(n - 1 + ans) % mod);\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2081",
    "index": "B",
    "title": "Balancing",
    "statement": "Ecrade has an integer array $a_1, a_2, \\ldots, a_n$. It's guaranteed that for each $1 \\le i < n$, $a_i \\neq a_{i+1}$.\n\nEcrade can perform several operations on the array to make it strictly increasing.\n\nIn each operation, he can choose two integers $l$ and $r$ ($1 \\le l \\le r \\le n$) and replace $a_l, a_{l+1}, \\ldots, a_r$ with any $r-l+1$ integers $a'_l, a'_{l+1}, \\ldots, a'_r$ satisfying the following constraint:\n\n- For each $l \\le i < r$, the comparison between $a'_i$ and $a'_{i+1}$ is the same as that between $a_i$ and $a_{i+1}$, i.e., if $a_i < a_{i + 1}$, then $a'_i < a'_{i + 1}$; otherwise, if $a_i > a_{i + 1}$, then $a'_i > a'_{i + 1}$; otherwise, if $a_i = a_{i + 1}$, then $a'_i = a'_{i + 1}$.\n\nEcrade wants to know the minimum number of operations to make the array strictly increasing. However, it seems a little difficult, so please help him!",
    "tutorial": "Let's only consider the comparison between adjacent pairs first. Call a pair $(a_i,a_{i+1})$ an inversion pair if $a_i>a_{i+1}$. In each operation, how can the number of inversion pairs change? Under what circumstances can we decrease the maximum number of inversion pairs in every operation? Let's only consider the comparison between adjacent pairs first. Call a pair $(a_i,a_{i+1})$ an inversion pair if $a_i>a_{i+1}$. Our goal is to decrease the number of inversion pairs to zero. If we choose to replace $a_l,a_{l+1},\\ldots,a_r$, only the comparison between $(a_{l-1},a_l)$ and $(a_{r},a_{r+1})$ can change, which means we can eliminate at most two inversion pairs in one operation. Let $s$ be the number of inversion pairs in $a_1,a_2,\\ldots,a_n$, then a lower bound of the answer is $l=\\left\\lceil\\dfrac{s}{2}\\right\\rceil$. In order to obtain the lower bound $l$, each operation must eliminate exactly two inversion pairs. This necessitates that we cannot alter any numbers before the first element $a_{p_1}$ of the first inversion pair or after the second element $a_{p_2}$ of the last inversion pair. (Why?) An intuitive idea is that the difference between $a_{p_1}$ and $a_{p_2}$ should be as large as possible (more precisely, $a_{p_2} - a_{p_1} \\geq p_2 - p_1$), so that a strictly increasing sequence can be \"accommodated\" between them. It is not difficult to constructively prove by recursion that this condition is both necessary and sufficient. In other words, when $a_{p_2} - a_{p_1} \\geq p_2 - p_1$, the answer is $l$; otherwise, an additional operation is required, making the answer $l+1$. It's not difficult to prove that the answer in this case is $l$. (Why?) The time complexity is $O(\\sum n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll t,n,a[200009];\ninline ll read(){\n\tll s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nint main(){\n\tt = read();\n\twhile (t --){\n\t\tn = read();\n\t\tfor (ll i = 1;i <= n;i += 1) a[i] = read();\n\t\tll ans = 0,pos1 = 0,pos2 = 0;\n\t\tfor (ll i = 1;i < n;i += 1) if (a[i] > a[i + 1]){\n\t\t\tans += 1,pos2 = i + 1;\n\t\t\tif (!pos1) pos1 = i;\n\t\t}\n\t\tif ((ans & 1) || (pos1 && a[pos2] - a[pos1] < pos2 - pos1)) printf(\"%lld\\n\",(ans >> 1) + 1);\n\t\telse printf(\"%lld\\n\",ans >> 1);\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2081",
    "index": "C",
    "title": "Quaternary Matrix",
    "statement": "A matrix is called quaternary if all its elements are $0$, $1$, $2$, or $3$.\n\nEcrade calls a quaternary matrix $A$ good if the following two properties hold.\n\n- The bitwise XOR of all numbers in each row of matrix $A$ is equal to $0$.\n- The bitwise XOR of all numbers in each column of matrix $A$ is equal to $0$.\n\nEcrade has a quaternary matrix of size $n \\times m$. He is interested in the minimum number of elements that need to be changed for the matrix to become good, and he also wants to find one of the possible resulting matrices.\n\nHowever, it seems a little difficult, so please help him!",
    "tutorial": "Do we really have to consider the problem on the whole matrix? Use greedy algorithm and guess some possible conclusions. Can you prove them (or construct some counterexamples) ? The problem can be rephrased as follows: Let the XOR sum of each row be $r_1, r_2, \\ldots, r_n$, and the XOR sum of each column be $c_1, c_2, \\ldots, c_m$. In each operation, we can choose any $1 \\le i \\le n$, $1 \\le j \\le m$, and $0 \\le x \\le 3$, then let $r_i \\leftarrow r_i \\oplus x$ and $c_j \\leftarrow c_j \\oplus x$. The goal is to determine the minimum number of operations required to make all $r_1, r_2, \\ldots, r_n$ and $c_1, c_2, \\ldots, c_m$ zero. Let $R_x\\ ( 0 \\le x \\le 3 )$ denote the count of $x$ in $r_1, r_2, \\ldots, r_n$, and $C_x$ denote the count of $x$ in $c_1, c_2, \\ldots, c_m$. A trivial upper bound for the answer is $s = R_1 + R_2 + R_3 + C_1 + C_2 + C_3$, which corresponds to the scenario where each operation only zeros out one of $r_i$ and $c_j$. To reduce the number of operations, we can consider grouping the non-zero elements in $r_1, \\ldots, r_n, c_1, \\ldots, c_m$ into disjoint groups where: The XOR sum of each group is zero. Each group contains at least one element from $r$ and one from $c$. For such a group, we can reduce the number of operations by one, as there always exists an operation which can zero out both $r_i$ and $c_j$. Thus, the goal is to maximize the number of such groups, and the minimum number of operations will be $s - \\text{(number of groups formed)}$. Define the following group types: $P_2$: Groups of the form $(R_1,C_1)$, $(R_2,C_2)$ or $(R_3,C_3)$. $P_3$: Groups of the form $(R_1,R_2,C_3)$, $(R_1,C_2,C_3)$, $(R_1,C_2,R_3)$, $(C_1,C_2,R_3)$, $(C_1,R_2,R_3)$ or $(C_1,R_2,C_3)$. $P_4$: Groups of the form $(R_1,R_1,C_2,C_2)$, $(R_1,R_1,C_3,C_3)$, $(R_2,R_2,C_1,C_1)$, $(R_2,R_2,C_3,C_3)$, $(R_3,R_3,C_1,C_1)$ or $(R_3,R_3,C_2,C_2)$. Conclusion 1: There exists an optimal solution where all groups are of the form $P_2$, $P_3$, or $P_4$. Each group must have size at least 2. Groups of size 2 or 3 can only be $P_2$ or $P_3$. Groups of size 4 not conforming to $P_4$ (e.g., $(R_1, R_1, R_1, C_1)$) can be decomposed into at least one $P_2$. Larger groups can be decomposed into combinations of $P_2$, $P_3$, and $P_4$. Conclusion 2: There exists an optimal solution where all $P_3$ groups share the same structure, and so do all $P_4$ groups. Two different $P_3$ groups can be decomposed into at least two $P_2$ or at least one $P_2$ and one $P_4$. Two different $P_4$ groups can be decomposed into at least two $P_2$ or at least two $P_3$. Conclusion 3: There exists an optimal solution where the elements in $P_4$ groups are a subset of those in $P_3$ groups (e.g., if $P_3$ is $(R_1, R_2, C_3)$, then $P_4$ can only be $(R_1, R_1, C_3, C_3)$ or $(R_2, R_2, C_3, C_3)$). The proof is analogous to Conclusion 2 and is left as an exercise. Based on these conclusions, the optimal strategy is: first form as many $P_2$ groups as possible; then form as many $P_3$ groups as possible from the remaining elements; then form as many $P_4$ groups as possible from the remaining elements. After grouping, each group can be zeroed out with one less operation. Note that the remaining ungrouped elements require individual operations. The time complexity is $O(\\sum nm)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll t,n,m,a[1009][1009];\nchar s[1009];\nvector <ll> row[4],col[4];\ninline ll read(){\n\tll s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nint main(){\n\tt = read();\n\twhile (t --){\n\t\tn = read(),m = read();\n\t\tfor (ll i = 1;i <= 3;i += 1) row[i].clear(),col[i].clear();\n\t\tfor (ll i = 1;i <= n;i += 1){\n\t\t\tscanf(\"%s\",s + 1);\n\t\t\tfor (ll j = 1;j <= m;j += 1) a[i][j] = s[j] - '0';\n\t\t}\n\t\tfor (ll i = 1;i <= n;i += 1){\n\t\t\tll sum = 0;\n\t\t\tfor (ll j = 1;j <= m;j += 1) sum ^= a[i][j];\n\t\t\tif (sum) row[sum].emplace_back(i);\n\t\t}\n\t\tfor (ll j = 1;j <= m;j += 1){\n\t\t\tll sum = 0;\n\t\t\tfor (ll i = 1;i <= n;i += 1) sum ^= a[i][j];\n\t\t\tif (sum) col[sum].emplace_back(j);\n\t\t}\n\t\tll ans = 0;\n\t\tfor (ll i = 1;i <= 3;i += 1){\n\t\t\twhile (row[i].size() && col[i].size()){\n\t\t\t\tans += 1;\n\t\t\t\ta[row[i].back()][col[i].back()] ^= i;\n\t\t\t\trow[i].pop_back(),col[i].pop_back();\n\t\t\t}\n\t\t}\n\t\tfor (ll i = 1;i <= 3;i += 1){\n\t\t\tll j = i % 3 + 1,k = j % 3 + 1;\n\t\t\twhile (row[i].size() && col[j].size() && col[k].size()){\n\t\t\t\tans += 2;\n\t\t\t\ta[row[i].back()][col[j].back()] ^= j;\n\t\t\t\ta[row[i].back()][col[k].back()] ^= k;\n\t\t\t\trow[i].pop_back(),col[j].pop_back(),col[k].pop_back();\n\t\t\t}\n\t\t\twhile (col[i].size() && row[j].size() && row[k].size()){\n\t\t\t\tans += 2;\n\t\t\t\ta[row[j].back()][col[i].back()] ^= j;\n\t\t\t\ta[row[k].back()][col[i].back()] ^= k;\n\t\t\t\tcol[i].pop_back(),row[j].pop_back(),row[k].pop_back();\n\t\t\t}\n\t\t}\n\t\tfor (ll i = 1;i <= 3;i += 1) for (ll j = 1;j <= 3;j += 1) if (i != j){\n\t\t\twhile (row[i].size() >= 2 && col[j].size() >= 2){\n\t\t\t\tll r1 = row[i].back(); row[i].pop_back();\n\t\t\t\tll r2 = row[i].back(); row[i].pop_back();\n\t\t\t\tll c1 = col[j].back(); col[j].pop_back();\n\t\t\t\tll c2 = col[j].back(); col[j].pop_back();\n\t\t\t\tans += 3;\n\t\t\t\ta[r1][c1] ^= i;\n\t\t\t\ta[r2][c1] ^= (i ^ j);\n\t\t\t\ta[r2][c2] ^= j;\n\t\t\t}\n\t\t}\n\t\tfor (ll i = 1;i <= 3;i += 1){\n\t\t\twhile (row[i].size()) ans += 1,a[row[i].back()][1] ^= i,row[i].pop_back();\n\t\t\twhile (col[i].size()) ans += 1,a[1][col[i].back()] ^= i,col[i].pop_back();\n\t\t}\n\t\tprintf(\"%lld\\n\",ans);\n\t\tfor (ll i = 1;i <= n;i += 1,puts(\"\")) for (ll j = 1;j <= m;j += 1) printf(\"%lld\",a[i][j]);\n\t}\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "implementation",
      "matrices"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2081",
    "index": "D",
    "title": "MST in Modulo Graph",
    "statement": "You are given a complete graph with $n$ vertices, where the $i$-th vertex has a weight $p_i$. The weight of the edge connecting vertex $x$ and vertex $y$ is equal to $\\operatorname{max}(p_x, p_y) \\bmod \\operatorname{min}(p_x, p_y)$.\n\nFind the smallest total weight of a set of $n - 1$ edges that connect all $n$ vertices in this graph.",
    "tutorial": "There are only $O(n\\log n)$ edges that are truly useful in the whole graph. First, for vertices with the same weight, they can naturally be treated as a single vertex. We observe that in the interval of weights $(kx,(k+1)x)\\ (k\\ge 1)$, only the smallest $y$ is useful. It is because, if $x<y<z<2x$, connecting edges $(x,y)$ and $(y,z)$ will always be better than connecting $(x,y)$ and $(x,z)$. Therefore, for a vertex with weight $x$, we enumerate $k = x , 2 x , \\ldots , \\lfloor \\frac{n}{x}\\rfloor\\cdot x$. For each $k$, we connect $x$ to the smallest $y$ that is greater than or equal to $k$. It can be proven that this approach guarantees a connected graph (since connecting only the first edge larger than $x$ already forms a connected structure). This method generates $O(n\\log n)$ edges (due to the harmonic series property). Directly applying Kruskal's algorithm would result in a time complexity of $O(n\\log^2 n)$. With radix sort, this can be optimized to $O(n\\log n)$.",
    "code": "#include<iostream>\n#include<cstdio>\n#include<algorithm>\n#include<string.h>\n#include<vector>\n#include<queue>\n#include<map>\n#include<ctime>\n#include<bitset>\n#include<set>\n#include<math.h>\n//#include<unordered_map>\n#define fi first\n#define se second\n#define mp make_pair\n#define pii pair<int,int>\n#define pb push_back\n#define pil pair<int,long long>\n#define pll pair<long long,long long>\n#define vi vector<int>\n#define vl vector<long long>\n#define ci ios::sync_with_stdio(false)\n//#define int long long\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long ull;\nint read(){\n\tchar c=getchar();\n\tll x=1,s=0;\n\twhile(c<'0'||c>'9'){\n\t   if(c=='-')x=-1;c=getchar();\n\t}\n\twhile(c>='0'&&c<='9'){\n\t   s=s*10+c-'0';c=getchar();\n\t}\n\treturn s*x;\n}\nconst int N=5e5+55;\nint MAXN=0;\nint n,tot,ans,maxx,f[N],siz[N],p[N],bj[N],pre[N],suf[N],pos[N];\nstruct node{\n\tint from,to,dis;\n}a[N*20];\nint cmp(node x,node y){\n\treturn x.dis<y.dis;\n}\nint find(int x){\n\tif(f[x]!=x)return f[x]=find(f[x]);\n\telse return x;\n}\nvoid merge(int x,int y){\n\tx=find(x);y=find(y);\n\tif(siz[x]<siz[y])swap(x,y);\n\tsiz[x]+=siz[y];\n\tf[y]=x;\n}\nint T;\nint main(){\n\tT=read();\n\twhile(T--)\n\t{\n\t\ttot=ans=maxx=0;\n\t\tfor(int i=1;i<=MAXN;++i)\n\t\t{\n\t\t\tf[i]=siz[i]=p[i]=bj[i]=pre[i]=suf[i]=pos[i]=0;\n\t\t}\n\t\tfor(int i=0;i<=MAXN*19;++i)\n\t\ta[i].from=a[i].to=a[i].dis=0;\n\t\t\n\t\t\n\t\t\n\t\tn=read();\n\t\tMAXN=n;\n\t\tfor(int i=1;i<=n;i++)p[i]=read(),bj[p[i]]=1,maxx=max(maxx,p[i]),MAXN=max(MAXN,p[i]);\n\t\tsort(p+1,p+n+1);\n\t\tfor(int i=1;i<=maxx;i++){\n\t\t\tif(bj[i])pre[i]=i;\n\t\t\telse pre[i]=pre[i-1];\n\t\t}\n\t\tfor(int i=maxx;i>=1;i--){\n\t\t\tif(bj[i])suf[i]=i;\n\t\t\telse suf[i]=suf[i+1];\n\t\t}\n\t\tfor(int i=1;i<=n;i++)pos[p[i]]=i;\n\t\tfor(int i=1;i<=n;i++){\n\t\t\tif(p[i]==p[i-1]){\n\t\t\t\ta[++tot]={i,i-1,0};\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor(int k=1;k*p[i]<=maxx;k++){\n\t\t\t\tint tmy=0;\n\t\t\t\tif(bj[k*p[i]] and k!=1){\n\t\t\t\t\ta[++tot]={pos[k*p[i]],i,0};\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(suf[k*p[i]+1]<=(k+1)*p[i])tmy=suf[k*p[i]+1];\n\t\t\t\tif(!tmy)continue;\n\t\t\t\tint cost=abs(k*p[i]-tmy);\n\t\t\t\ta[++tot]={pos[tmy],i,cost};\n\t\t\t}\n\t\t}\n\t\tsort(a+1,a+tot+1,cmp);\n\t\tfor(int i=1;i<=n;i++)f[i]=i,siz[i]=1;\n\t\tfor(int i=1;i<=tot;i++){\n\t\t\tif(find(a[i].from)!=find(a[i].to)){\n\t\t\t\tmerge(a[i].from,a[i].to);\n\t\t\t\tans+=a[i].dis;\n\t\t\t}\n\t\t}\n\t\tcout<<ans<<endl;\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dsu",
      "graphs",
      "greedy",
      "math",
      "number theory",
      "sortings",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2081",
    "index": "E",
    "title": "Quantifier",
    "statement": "Given a rooted tree with $n+1$ nodes labeled from $0$ to $n$, where the root is node $0$, and \\textbf{its only child is node $1$}. There are $m$ \\textbf{distinct} chips labeled from $1$ to $m$, each colored either black or white. Initially, they are arranged on edge $(0,1)$ from top to bottom in ascending order of labels.\n\n\\begin{center}\n{\\small The initial position of the chips. Tree nodes are shown in blue.}\n\\end{center}\n\nYou can perform the following operations any number of times (possibly zero) in any order:\n\n- Select two edges ($u,v$) and ($v,w$) such that $u$ is the parent of $v$ and $v$ is the parent of $w$, where edge ($u,v$) contains at least one chip. Move the \\textbf{bottommost} chip on edge ($u,v$) to the \\textbf{topmost} place on edge ($v,w$), i. e., above all existing chips on ($v,w$).\n- Select two edges ($u,v$) and ($v,w$) such that $u$ is the parent of $v$ and $v$ is the parent of $w$, where edge ($v,w$) contains at least one chip. Move the \\textbf{topmost} chip on edge ($v,w$) to the \\textbf{bottommost} place on edge ($u,v$), i. e., below all existing chips on ($u,v$).\n- Select two \\textbf{adjacent} chips of the same color on the same edge, and swap their positions.\n\n\\begin{center}\n{\\small Permitted operations.}\n\\end{center}\n\nEach chip $i$ has a movement range, defined as all edges on the simple path from the root to node $d_i$. During operations, you must ensure that no chip is moved to an edge outside its movement range.\n\nFinally, you must move all chips back to edge $(0,1)$. It can be found that the order of the chips may change. Compute the number of possible permutations of chips for the final arrangement on the edge $(0,1)$ modulo $998\\,244\\,353$.\n\nA permutation of chips is defined as a sequence of length $m$ consisting of the \\textbf{labels} of the chips from top to bottom.",
    "tutorial": "Move each chip as deep as possible in descending order of labels. Can we simplify the operations after that? Now we only need to move the chips upward and swap adjacent chips with the same color. What can we do after that? We can perform dynamic programming (DP) to calculate the numbers. What information do we need to record? We need to record the color and the length of the top monochromatic segment. How can we perform the DP in $\\mathcal{O}(m^2)$ time complexity? First, in descending order of labels, move each chip to the deepest possible position successively. It can be shown that this allows each chip to reach the theoretically deepest position it can attain. Consequently, every final state can be obtained from this configuration by performing only upward moves of chips and swaps of adjacent chips with the same color. Next comes the process of moving chips upward while performing dynamic programming (DP). Let $e_u$ denote the edge from node $u$ to its parent. Assume we have decided the order of all the chips in subtree $u$ (except the ones on $e_u$), and we need to merge them with the original chips on $e_u$. If the bottom chip on $e_u$ shares color with the subtree's top chip, we need to know the length of the subtree's topmost maximal monochromatic contiguous segment to calculate the number of ways to merge the two parts, i.e., if the length of the bottommost segment on $e_u$ is $x$ and the length of the topmost segment of the subtree is $y$, we have $\\dbinom{x+y}{x}$ ways to combine them. So we need to record the color and the length of the top segment. Let $f_{u,0/1,i}$ denote the number of permutation schemes on $e_u$ after moving all the chips in subtree $u$ to $e_u$, where: The topmost chip on $e_u$ is black/white (0/1). The length of the topmost maximal monochromatic contiguous segment on $e_u$ is $i$. When calculating $f_{u,0/1,i}$ for all $i$, we first merge the DP states of all the subtrees of node $u$, and then merge the original chips on $e_u$ into the resulting DP states. Subtree merging: Assume we merge two subtrees $v$ and $w$. Let $S$ and $T$ denote the number of chips on $e_v$ and $e_w$ respectively, and let $g_{0/1,i}$ be a temporary DP array initialized to all zeros. Let's consider two cases. Suppose the top chip comes from $e_v$ after merging. Then the maximal monochromatic segment length from $e_w$ becomes irrelevant, and therefore let $h_c=\\sum_{i=1}^T f_{w,c,i}$. If the top chip of $e_w$ would split the top segment of $e_v$, enumerate split positions. The split position should be strictly inside the top segment of $e_v$. $g_{c,i}\\leftarrow g_{c,i} + \\dbinom{S-i+T-1}{T-1} h_{1-c} \\sum_{k=i+1}^S f_{v,c,k}\\ (1\\le i\\le S)$ Otherwise, the position of the top chip of $e_w$ becomes irrelevant. $g_{c,i}\\leftarrow g_{c,i} + \\dbinom{S-i+T}{T} h_{1-c} f_{v,c,i}$ With suffix sum optimization, this achieves $\\mathcal{O}(m^2)$ time complexity. If there are only chips of this color on both edges: $g_{c,S+T}\\leftarrow g_{c,S+T} + \\dbinom{S+T}{T} f_{v,c,S} f_{w,c,T}$ Otherwise, assume the topmost different-colored chip is from subtree $w$ after merging. Enumerate insertion positions where this chip splits the top segment of the other (not necessarily strictly inside the segment). $g_{c,i+j}\\leftarrow g_{c,i+j} + \\dbinom{i+j}{j} \\dbinom{S-i+T-j-1}{T-j-1} f_{w,c,j} \\sum_{k=i}^S f_{v,c,k}\\ (0\\le i\\le S,\\ 1\\le j < T)$ (Similar transition equation for $v$.) With suffix sum optimization, this forms a tree knapsack DP with $\\mathcal{O}(m^2)$ time complexity. After computing $g_{0/1,i}$, we can treat $g$ as the DP states of a subtree, and continue to perform the process above. Merging original chips on $e_u$ into the results: We first account for internal permutations of original monochromatic segments. After that, if the bottom chip on $e_u$ shares color with merged subtrees' top chip (with segment lengths $x$ and $y$), multiply the DP state by $\\dbinom{x+y}{x}$. Assuming $n$ and $m$ are of the same order, the overall time complexity is $\\mathcal{O}(m^2)$.",
    "code": "#include <bits/stdc++.h>\n#define eb emplace_back\nusing namespace std;\ntypedef long long ll;\nconst int p=998244353;\nint T,n,m,fa[5005],col[5005],d[5005],stk[5005],top,ct[5005][2];\nint C[5005][5005],fac[5005],siz[5005],f[5005][2][5005],g[2][5005],ans;\nvector<int> to[5005],vec[5005];\ninline void diff(int u,int v){\n\tint S=siz[u],T=siz[v];\n\tfor(int x=0,A,B;x<2;++x){\n\t\tA=B=0;\n\t\tfor(int j=1;j<=T;++j)B=(B+f[v][x^1][j])%p;\n\t\tfor(int i=S;i>=1;--i){\n\t\t\tg[x][i]=(g[x][i]+((ll)A*C[S+T-i-1][T-1]+(ll)f[u][x][i]*C[S+T-i][T])%p*B)%p;\n\t\t\tA=(A+f[u][x][i])%p;\n\t\t}\n\t}\n}\ninline void same1(int u,int v){\n\tint S=siz[u],T=siz[v];\n\tfor(int x=0,A,B;x<2;++x){\n\t\tfor(int i=1;i<S;++i){\n\t\t\tif(!(A=f[u][x][i]))continue;\n\t\t\tB=0;\n\t\t\tfor(int j=T;j>=0;--j){\n\t\t\t\tB=(B+f[v][x][j])%p;\n\t\t\t\tg[x][i+j]=(g[x][i+j]+(ll)A*B%p*C[i+j][j]%p*C[S-i-1+T-j][T-j])%p;\n\t\t\t}\n\t\t}\n\t}\n}\ninline void same(int u,int v){\n\tsame1(u,v),same1(v,u);\n\tint S=siz[u],T=siz[v];\n\tfor(int x=0;x<2;++x)\n\t\tg[x][S+T]=(g[x][S+T]+(ll)f[u][x][S]*f[v][x][T]%p*C[S+T][T])%p;\n}\ninline void merge(int u,int v){\n\tfor(int i=1;i<=siz[u]+siz[v];++i)g[0][i]=g[1][i]=0;\n\tdiff(u,v),diff(v,u),same(u,v);\n\tsiz[u]+=siz[v];\n\tfor(int i=1;i<=siz[u];++i)\n\t\tf[u][0][i]=g[0][i],f[u][1][i]=g[1][i];\n}\nvoid dfs(int u){\n\tsiz[u]=0;\n\tfor(auto v:to[u]){\n\t\tdfs(v);\n\t\tif(!siz[v])continue;\n\t\tif(siz[u])merge(u,v);\n\t\telse{\n\t\t\tfor(int i=1;i<=siz[v];++i)\n\t\t\t\tf[u][0][i]=f[v][0][i],f[u][1][i]=f[v][1][i];\n\t\t\tsiz[u]=siz[v];\n\t\t}\n\t}\n\tif(vec[u].empty())return;\n\tint prd=1,L=vec[u].size(),c=vec[u][0],fir=0,lst=0,res=0;\n\tfor(int i=0,j=0;i<L;i=j){\n\t\twhile(j<L && vec[u][i]==vec[u][j])++j;\n\t\tif(i==0)fir=j-i;\n\t\tif(j==L)lst=j-i;\n\t\tprd=(ll)prd*fac[j-i]%p;\n\t}\n\tfor(int i=siz[u]+1;i<=siz[u]+L;++i)f[u][0][i]=f[u][1][i]=0;\n\tif(!siz[u])f[u][vec[u][L-1]][lst]=prd;\n\telse if(fir==L){\n\t\tfor(int i=siz[u];i>=1;--i){\n\t\t\tf[u][c][i+L]=(ll)f[u][c][i]*C[i+L][i]%p*fac[L]%p;\n\t\t\tres=(res+f[u][c^1][i])%p;\n\t\t\tf[u][c^1][i]=0;\n\t\t}\n\t\tfor(int i=1;i<L;++i)f[u][c][i]=0;\n\t\tf[u][c][L]=(ll)res*fac[L]%p;\n\t}\n\telse{\n\t\tfor(int i=1;i<=siz[u];++i){\n\t\t\tres=(res+(ll)f[u][c][i]*C[i+fir][i]+f[u][c^1][i])%p;\n\t\t\tf[u][0][i]=f[u][1][i]=0;\n\t\t}\n\t\tf[u][vec[u][L-1]][lst]=(ll)res*prd%p;\n\t}\n\tsiz[u]+=L;\n}\nint main(){\n\tscanf(\"%d\",&T);\n\twhile(T--){\n\t\tscanf(\"%d%d\",&n,&m);\n\t\tfor(int i=0;i<=n;++i){\n\t\t\tto[i].clear(),vec[i].clear();\n\t\t\tct[i][0]=ct[i][1]=0;\n\t\t}\n\t\tfor(int i=1;i<=n;++i)\n\t\t\tscanf(\"%d\",fa+i),to[fa[i]].eb(i);\n\t\tfor(int i=1;i<=m;++i)scanf(\"%d\",col+i);\n\t\tfor(int i=1;i<=m;++i)scanf(\"%d\",d+i);\n\t\tfor(int i=m,u;i>=1;--i){\n\t\t\ttop=0,u=d[i];\n\t\t\twhile(u)stk[++top]=u,u=fa[u];\n\t\t\tfor(int j=top;j>=1;--j){\n\t\t\t\tif(j>1 && !ct[stk[j]][col[i]^1])continue;\n\t\t\t\tvec[stk[j]].eb(col[i]),++ct[stk[j]][col[i]];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tC[0][0]=fac[0]=1;\n\t\tfor(int i=1;i<=m;++i){\n\t\t\tfor(int j=1;j<=i;++j)\n\t\t\t\tC[i][j]=(C[i-1][j-1]+C[i-1][j])%p;\n\t\t\tC[i][0]=1;\n\t\t\tfac[i]=(ll)fac[i-1]*i%p;\n\t\t}\n\t\tdfs(1),ans=0;\n\t\tfor(int i=1;i<=m;++i)\n\t\t\tans=((ll)ans+f[1][0][i]+f[1][1][i])%p;\n\t\tprintf(\"%d\\n\",ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "implementation"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2081",
    "index": "F",
    "title": "Hot Matrix",
    "statement": "Piggy Zhou loves matrices, especially those that make him get excited, called hot matrix.\n\nA hot matrix of size $n \\times n$ can be defined as follows. Let $a_{i, j}$ denote the element in the $i$-th row, $j$-th column ($1 \\le i, j \\le n$).\n\n- Each column and row of the matrix is a permutation of all numbers from $0$ to $n-1$.\n- For each pair of indices $i$, $j$, such that $1 \\le i, j \\le n$, $a_{i, j} + a_{i, n - j + 1} = n - 1$.\n- For each pair of indices $i$, $j$, such that $1 \\le i, j \\le n$, $a_{i, j} + a_{n - i + 1, j} = n - 1$.\n- All ordered pairs $\\left(a_{i, j}, a_{i, j + 1}\\right)$, where $1 \\le i \\le n$, $1 \\le j < n$, are distinct.\n- All ordered pairs $\\left(a_{i, j}, a_{i + 1, j}\\right)$, where $1 \\le i < n$, $1 \\le j \\le n$, are distinct.\n\nNow, Piggy Zhou gives you a number $n$, and you need to provide him with a hot matrix if the hot matrix exists for the given $n$, or inform him that he will never get excited if the hot matrix does not exist for the given $n$.",
    "tutorial": "First, it is not difficult to observe that when $n$ is odd, a solution exists if and only if $n = 1$. When $n$ is even, a solution always exists. Consider the following construction: Let $n = 2m$. Use $(x, y)$ to denote the cell in the $x$-th row and $y$-th column of the matrix, and assume the top-left corner of the matrix is $(1, 1)$, while the bottom-right corner is $(n, n)$. For $(a, b)$ and $(c, d)$, let $k_1 = c - a$ and $k_2 = d - b$. When $|k_1| = |k_2|$, denote $(a, b) \\sim (c, d)$ as: $(a, b), (a+1, b+1), \\dots, (a+k_1, b+k_2)$ if $k_1, k_2 \\geq 0$. $(a, b), (a+1, b-1), \\dots, (a+k_1, b+k_2)$ if $k_1 \\geq 0, k_2 \\leq 0$. $(a, b), (a-1, b+1), \\dots, (a+k_1, b+k_2)$ if $k_1 \\leq 0, k_2 \\geq 0$. $(a, b), (a-1, b-1), \\dots, (a+k_1, b+k_2)$ if $k_1, k_2 \\leq 0$. For any $1 \\leq i \\leq m$, we alternately fill the numbers $2i-1$ and $2i-2$ in the cells along the paths $(1, 2i) \\sim (n-2i+1, n)$, $(n-2i+2, n) \\sim (n, n-2i+2)$, $(n, n-2i+1) \\sim (2i, 1)$, and $(2i-1, 1) \\sim (1, 2i-1)$. An illustration for $n = 10$: Next, we prove that this construction satisfies all the requirements of the problem: Each row and column of $A$ is a permutation of $0 \\sim n-1$. For each $1 \\leq i \\leq m$, color the cells containing the numbers $2i-1$ and $2i-2$ black and white alternately along the paths described above. It can be shown that each row and column contains exactly one black and one white cell, ensuring that $2i-1$ and $2i-2$ appear exactly once in each row and column. Thus, each row and column is a permutation of $0 \\sim n-1$. $a_{i,j} + a_{i,n-j+1} = n-1$ and $a_{i,j} + a_{n-i+1,j} = n-1$. From the filling process, the cells containing $2i-1$ and $2i-2$ and the cells containing $n-2i+1$ and $n-2i$ are symmetric with respect to the midline between the $m$-th and $(m+1)$-th rows, as well as the midline between the $m$-th and $(m+1)$-th columns. This symmetry further ensures that $2i-1$ and $n-2i$ are symmetric, as are $2i-2$ and $n-2i+1$. Therefore, both $a_{i,j} + a_{i,n-j+1} = n-1$ and $a_{i,j} + a_{n-i+1,j} = n-1$ are satisfied. All ordered pairs $\\langle a_{i,j}, a_{i,j+1} \\rangle$ (for $1 \\leq i \\leq n, 1 \\leq j < n$) are distinct, and all ordered pairs $\\langle a_{i,j}, a_{i+1,j} \\rangle$ (for $1 \\leq i < n, 1 \\leq j \\leq n$) are distinct. For each $1 \\leq i \\leq m$, divide the cells containing $2i-1$ and $2i-2$ into four categories: First category: $(1, 2i) \\sim (n-2i+1, n)$ Second category: $(n-2i+2, n) \\sim (n, n-2i+2)$ Third category: $(n, n-2i+1) \\sim (2i, 1)$ Fourth category: $(2i-1, 1) \\sim (1, 2i-1)$ For any $1 \\leq i < j \\leq m$: The first and third category cells of $2i-1, 2i-2$ do not neighbor the first and third category cells of $2j-1, 2j-2$ (since the sum of their coordinates is odd). The second and fourth category cells of $2i-1, 2i-2$ do not neighbor the second and fourth category cells of $2j-1, 2j-2$ (since the sum of their coordinates is even). The second and fourth category cells of $2i-1, 2i-2$ do not have row-wise neighbors with the first and third category cells of $2j-1, 2j-2$, and the first and third category cells of $2i-1, 2i-2$ have exactly $2$ pairs of row-wise neighbors with the second and fourth category cells of $2j-1, 2j-2$ (this can be visualized and proven through diagrams). Specifically: The first category cells of $2i-1, 2i-2$ and the second category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{n-i-j+1,n+i-j} = 2i-2 + ((i+j+1) \\bmod 2), a_{n-i-j+1,n+i-j+1} = 2j-2 + ((i+j+1) \\bmod 2)$ $a_{n-i-j+2,n+i-j+1} = 2i-2 + ((i+j) \\bmod 2), a_{n-i-j+2,n+i-j} = 2j-2 + ((i+j) \\bmod 2)$ The first category cells of $2i-1, 2i-2$ and the second category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{n-i-j+1,n+i-j} = 2i-2 + ((i+j+1) \\bmod 2), a_{n-i-j+1,n+i-j+1} = 2j-2 + ((i+j+1) \\bmod 2)$ $a_{n-i-j+2,n+i-j+1} = 2i-2 + ((i+j) \\bmod 2), a_{n-i-j+2,n+i-j} = 2j-2 + ((i+j) \\bmod 2)$ The first category cells of $2i-1, 2i-2$ and the fourth category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{j-i,i+j-1} = 2i-2 + ((i+j) \\bmod 2), a_{j-i,i+j} = 2j-2 + ((i+j+1) \\bmod 2)$ $a_{j-i+1,i+j} = 2i-2 + ((i+j+1) \\bmod 2), a_{j-i+1,i+j-1} = 2j-2 + ((i+j) \\bmod 2)$ The first category cells of $2i-1, 2i-2$ and the fourth category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{j-i,i+j-1} = 2i-2 + ((i+j) \\bmod 2), a_{j-i,i+j} = 2j-2 + ((i+j+1) \\bmod 2)$ $a_{j-i+1,i+j} = 2i-2 + ((i+j+1) \\bmod 2), a_{j-i+1,i+j-1} = 2j-2 + ((i+j) \\bmod 2)$ The third category cells of $2i-1, 2i-2$ and the second category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{n+i-j+1,n-i-j+2} = 2i-2 + ((i+j) \\bmod 2), a_{n+i-j+1,n-i-j+1} = 2j-2 + ((i+j+1) \\bmod 2)$ $a_{n+i-j,n-i-j+1} = 2i-2 + ((i+j+1) \\bmod 2), a_{n+i-j,n-i-j+2} = 2j-2 + ((i+j) \\bmod 2)$ The third category cells of $2i-1, 2i-2$ and the second category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{n+i-j+1,n-i-j+2} = 2i-2 + ((i+j) \\bmod 2), a_{n+i-j+1,n-i-j+1} = 2j-2 + ((i+j+1) \\bmod 2)$ $a_{n+i-j,n-i-j+1} = 2i-2 + ((i+j+1) \\bmod 2), a_{n+i-j,n-i-j+2} = 2j-2 + ((i+j) \\bmod 2)$ The third category cells of $2i-1, 2i-2$ and the fourth category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{i+j,j-i+1} = 2i-2 + ((i+j+1) \\bmod 2), a_{i+j,j-i} = 2j-2 + ((i+j+1) \\bmod 2)$ $a_{i+j-1,j-i} = 2i-2 + ((i+j) \\bmod 2), a_{i+j-1,j-i+1} = 2j-2 + ((i+j) \\bmod 2)$ The third category cells of $2i-1, 2i-2$ and the fourth category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{i+j,j-i+1} = 2i-2 + ((i+j+1) \\bmod 2), a_{i+j,j-i} = 2j-2 + ((i+j+1) \\bmod 2)$ $a_{i+j-1,j-i} = 2i-2 + ((i+j) \\bmod 2), a_{i+j-1,j-i+1} = 2j-2 + ((i+j) \\bmod 2)$ From the above analysis and by enumerating the parity of $i+j$, it is clear that all ordered pairs $\\langle a_{i,j}, a_{i,j+1} \\rangle$ (for $1 \\leq i \\leq n, 1 \\leq j < n$) are distinct, and all ordered pairs $\\langle a_{i,j}, a_{i+1,j} \\rangle$ (for $1 \\leq i < n, 1 \\leq j \\leq n$) are distinct. In conclusion, we have provided a construction for even $n$ and proven that it satisfies all the problem's requirements. The time complexity is $O(\\sum n^2)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\nint Test_num,n;\nint a[3002][3002];\nvoid solve()\n{\n\tscanf(\"%d\",&n);\n\tif(n>=3 && (n&1))return (void)(puts(\"NO\"));\n\tputs(\"YES\");\n\tif(n==1)return (void)(puts(\"0\"));\n\tfor(int i=0;i<n;i+=2)\n\t{\n\t\tfor(int j=1;j<=i+1;++j)a[j][i+2-j]=i+((j&1)^1);\n\t\tfor(int j=i+2;j<=n;++j)a[j][j-i-1]=i+((j&1)^1);\n\t\tfor(int j=1;j<=n-i-1;++j)a[j][i+1+j]=i+(j&1);\n\t\tfor(int j=n-i;j<=n;++j)a[j][2*n-i-j]=i+(j&1);\n\t}\n\tfor(int i=1;i<=n;++i)for(int j=1;j<=n;++j)printf(\"%d%c\",a[i][j],j==n? '\\n':' ');\n}\nint main()\n{\n\tfor(scanf(\"%d\",&Test_num);Test_num--;)solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2081",
    "index": "G1",
    "title": "Hard Formula",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, the limits on $n$ and the time limit are smaller. You can hack only if you solved all versions of this problem.}\n\nYou are given an integer $n$, and you need to compute $(\\sum_{k=1}^n k\\bmod\\varphi(k))\\bmod 2^{32}$, where $\\varphi(k)$ equals the number of positive integers no greater than $k$ that are coprime with $k$.",
    "tutorial": "If $g'(np)\\neq g'(n)$ , then $p\\le n$ unless $n=2,p=3$ or $n=1,p=2$ . Think about the method of $\\min 25$ sieve. We define $\\displaystyle g(n)=\\frac n{\\varphi(n)}=\\prod_{p|n}\\frac p{p-1},g'(n)=\\lfloor g(n)\\rfloor$. It's easy to see that $res=\\frac{N(N+1)}2-\\sum_{i=1}^Ng'(i)\\varphi(i)$. Let's consider how to calculate $\\sum_{i=1}^Ng'(i)\\varphi(i)$. $\\texttt{Key observation 1}$:if $g'(np)\\neq g'(n)$, then $p\\le n$ unless $n=2,p=3$ or $n=1,p=2$. $\\begin{aligned} &\\because g(n)\\cdot\\frac p{p-1}\\ge g'(np)\\ge g'(n)+1\\\\ &\\therefore p\\le\\frac{g'(n)+1}{g'(n)+1-g(n)}\\\\ &\\therefore p\\le\\dfrac{\\left\\lfloor\\dfrac n{\\varphi(n)}\\right\\rfloor\\varphi(n)+\\varphi(n)}{\\left\\lfloor\\dfrac n{\\varphi(n)}\\right\\rfloor\\varphi(n)+\\varphi(n)-n}\\\\ &\\texttt{let}\\ x=\\left\\lfloor\\dfrac n{\\varphi(n)}\\right\\rfloor\\varphi(n)+\\varphi(n)-n\\ge 1\\\\ &\\therefore p\\le\\dfrac{x+n}x\\le n+1\\\\ \\end{aligned}$ if $p=n+1$, then $\\dfrac{x+n}x=n+1\\implies x=1\\implies \\left(1+\\left\\lfloor \\dfrac n{\\phi(n)}\\right\\rfloor\\right)\\varphi(n) = n+1 \\implies \\varphi(n)\\mid n+1$. if $n\\gt 2$ then $\\varphi(n)\\ge 2$, but $\\varphi(n)\\mid n+1=p$, which is contradict the fact that $p$ is a prime number. The case of $n\\le 2$ is easy to check. Therefore, all the prime factors $p$ that $\\gt \\sqrt N$ wouldn't change the number of $g'(n)$. Use a linear sieve to find all the prime numbers $\\le \\sqrt N$, following the approach for handling composite numbers in the min25 sieve: Let's define: $s(n,k)=\\varphi(n)\\sum_{k\\leq p\\leq\\lfloor\\frac{N}{n}\\rfloor}g'(np)\\times\\varphi(p)$ $S(n,k)=s(n,k)+\\sum_{k\\leq p\\leq\\sqrt N\\And p^e\\leq\\lfloor\\frac{N}{n}\\rfloor}S(np^e,p)+[e\\neq 1]g'(np^e)\\times\\varphi(np^e)$ When $p\\leq\\frac{n+(\\varphi(n)-n\\mod\\varphi(n))}{\\varphi(n)-n\\mod\\varphi(n)}$, there is $g'(np)=g'(n)+1$, otherwise $g'(np)=g'(n)$. Pre-calculate the prefix of $\\varphi(p)$ among prime numbers, we can calculate $s(n,k)$ like this: $s(n,k)=\\varphi(n)\\times\\left(g'(n)\\sum_{k\\leq p\\leq\\lfloor\\frac{N}{n}\\rfloor}\\varphi(p)+\\sum_{k\\leq p\\leq\\min\\left(\\frac{n+(\\varphi(n)-n\\mod\\varphi(n))}{\\varphi(n)-n\\mod\\varphi(n)},\\lfloor\\frac{N}{n}\\rfloor\\right)}\\varphi(p)\\right)$ The answer is $\\frac{N(N+1)}{2}-1-S(1,1)$. With time complexity $\\mathcal O\\left(\\frac{n^{0.75}}{\\log n}\\right)$, it could pass the test cases of $N\\le 10^{11}$.",
    "code": "#include<cstdio>\n#include<cmath>\ntypedef unsigned long long ull;\ntypedef unsigned uint;\nconst uint M=1e6+5;\null N;const uint ANS[11]={0,0,0,1,1,2,2,3,3,6,8};\nuint B,n4,top,pri[M],F0[M],F1[M],G0[M],G1[M],SF[M],SG[M];\ninline ull Div(const ull&n,const ull&m){\n\treturn double(n)/m;\n}\ninline ull min(const ull&a,const ull&b){\n\treturn a>b?b:a;\n}\ninline uint DFS(const ull&n,uint k,const ull&phi){\n    const ull&T=Div(N,n);\n    const uint&g=int(n*1./phi),&R=min(Div((g+1)*phi,(g+1)*phi-n),min(ull(B),T));\n\tuint ans=0;\n\tif(k>top)ans=T<=B?0:g*phi*(SF[n]-SG[B]);\n\telse if(pri[k]>T)ans=0;\n\telse if(pri[k]<=R)ans=g*phi*((n<=B?SF[n]:SG[T])-SG[R])+(g+1)*phi*(SG[R]-SG[pri[k-1]]);\n\telse ans=g*phi*((n<=B?SF[n]:SG[T])-SG[pri[k-1]]);\n\tfor(;k<=top;++k){\n\t\tconst uint&p=pri[k],&w=p<=R?g+1:g;if(1ull*p*p>T)break;\n\t\tfor(ull x=n,tp=phi*(p-1);x*p<=N;tp*=p)ans+=DFS(x*=p,k+1,tp)+w*tp;\n\t\tans-=w*phi*(p-1);\n\t}\n\treturn ans;\n}\nsigned main(){\n\tscanf(\"%llu\",&N);\n\tif(N<=10)return!printf(\"%d\",ANS[N]);B=sqrt(N);n4=sqrt(B);\n\tfor(uint i=1;i<=B;++i){\n\t\tconst ull&w=Div(N,i);\n\t\tF0[i]=w-1;F1[i]=w*(w+1)/2-1;\n\t\tG0[i]=i-1;G1[i]=i*(i+1ull)/2-1;\n\t}\n\tfor(uint p=2;p<=n4;++p)if(G0[p]!=G0[p-1]){\n\t\tconst uint&lim=Div(B,p),&S0=G0[p-1],&S1=G1[p-1];pri[++top]=p;\n\t\tfor(uint k=1;k<=lim;++k){\n\t\t\tF0[k]-=F0[k*p]-S0;F1[k]-=p*(F1[k*p]-S1);\n\t\t}\n\t\tfor(uint k=lim+1;k<=B;++k){\n\t\t\tconst uint&x=Div(N,k*p);F0[k]-=G0[x]-S0;F1[k]-=p*(G1[x]-S1);\n\t\t}\n\t\tfor(uint k=B,e=lim;e>=p;--e)for(uint x=e*p,V0=G0[e]-S0,V1=p*(G1[e]-S1);k>=x;--k){\n\t\t\tG0[k]-=V0;G1[k]-=V1;\n\t\t}\n\t}\n\tfor(uint p=n4+1;p<=B;++p)if(G0[p]!=G0[p-1]){\n\t\tconst uint&lim=Div(B,p),&T=Div(N,1ll*p*p),&S0=G0[p-1],&S1=G1[p-1];pri[++top]=p;\n\t\tfor(uint k=1;k<=lim;++k){\n\t\t\tF0[k]-=F0[k*p]-S0;F1[k]-=p*(F1[k*p]-S1);\n\t\t}\n\t\tfor(uint k=lim+1;k<=T;++k){\n\t\t\tconst uint&x=Div(N,k*p);F0[k]-=G0[x]-S0;F1[k]-=p*(G1[x]-S1);\n\t\t}\n\t}\n\tfor(uint i=1;i<=B;++i)SF[i]=F1[i]-F0[i],SG[i]=G1[i]-G0[i];\n\tprintf(\"%u\",N*(N+1)/2-1-DFS(1,1,1));\n}",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2081",
    "index": "G2",
    "title": "Hard Formula (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, the limit on $n$ and the time limit are higher. You can hack only if you solved all versions of this problem.}\n\nYou are given an integer $n$, and you need to compute $(\\sum_{k=1}^n k\\bmod\\varphi(k))\\bmod 2^{32}$, where $\\varphi(k)$ equals the number of positive integers no greater than $k$ that are coprime with $k$.",
    "tutorial": "Consider the DFS structure of $\\min 25$ sieve. What kind of nodes are important? How many of nodes are important? Consider using Du Sieve to get some important functions. For further optimization, let's consider the DFS tree of $\\min25$ sieve: $N$ vertices, rooted on $1$, the father of a node $d$ is $\\frac{d}{\\text{maxp}(d)}$ where $\\text{maxp}(d)$ denotes the maximum prime factor of $d$. Consider all the positions $d$ that $g'(d)\\neq g'(fa_d)$. Let's divide them into two cases: $d$ is a leaf, which means $d\\le N\\lt d\\times \\operatorname{maxp}(d)$. $d$ is not a leaf, which means $d\\times \\operatorname{maxp}(d)\\le N$. The answer could be calculated like this: $\\sum_{g'(d)\\neq g'(fa_d)\\text{ or }d=1}G(\\frac{d}{\\mathrm{maxp}(d)},\\mathrm{maxp}(d))$ where $G(d,p)$ denotes the sum of $\\varphi$ in the subtree of node $d$, and $G(d,p)$ could be calculated like this: $G(d,p)=\\varphi(d)\\sum_{i=1}^{\\lfloor\\frac{N}{d}\\rfloor}[\\mathrm{minp}(i)=p]\\varphi(i)$ We could use DFS to search all the nodes $d$ which satisfy case 2, and we can calculate its contribution to the answer during our DFS. For a non-leaf node $u$, let's consider its child nodes $up$ which satisfy case 1. It's easy to see that $p$ is in an interval, which allows $O(1)$ calculation of the contributions of these nodes. As a result, we get the number of nodes $d$. Let's consider how to calculate $G(d,p)$. Define: $f_k(x)=\\sum_{i=1}^n [\\text{minp}(i)\\ge k]\\varphi(i)$ where $\\text{minp}(i)$ denote the minimum prime number of $i$. Then we can see that: $G(d,p)=f_p(\\lfloor\\frac{N}{d}\\rfloor)-f_{p+1}(\\lfloor\\frac{N}{d}\\rfloor)$ It's easy to see that $F_0(x)=\\frac{\\zeta(x-1)}{\\zeta(x)}$, we can use Du Sieve to get all the $f_0(\\lfloor \\frac Nd\\rfloor)$ in $O(N^{\\frac 23})$. According to $\\texttt{Key observation 1}$, $\\forall d\\notin{2,6},\\mathrm{maxp}(d)\\leq\\sqrt d$. Let $k=\\max_{g'(d)\\neq g'(fa_d)\\And d\\leq B}(\\mathrm{maxp}(d))$, categorize these nodes $d$ again: (i) $\\mathrm{maxp}(d)\\leq k$, Then $\\mathrm{maxp}(d)\\leq \\sqrt B$. (ii) $\\mathrm{maxp}(d)>k$, then $B\\leq\\mathrm{maxp^2(d)}\\leq d$, $\\lfloor\\frac{N}{d}\\rfloor<\\frac NB$. For those $d$ satisfy condition (i), let's begin with $f_0$, delete the prime numbers from small to large, until $f_k$ and calculate the contributions of these $d$. We could use Dirichlet convolution to calculate $f_{p+1}$ from $f_p$. Step 1: $h_p(N)=f_p(N)-p\\times f_p(\\lfloor\\frac{N}{p}\\rfloor)$ Step 2: $f_{p+1}(N)=\\sum_{i=0}h_p(\\lfloor\\frac{N}{p^i}\\rfloor)=h_p(N)+f_{p+1}(\\lfloor\\frac{N}{p}\\rfloor)$ These could solve in $O\\left(\\frac{\\sqrt N \\times \\sqrt B}{\\log n}\\right)$. For those $d$ satisfy condition (ii), we calculate $G(d,p)$ in this method: $G(d,p)=\\sum_{k=1}\\varphi(dp^k)f_{p+1}(\\lfloor\\frac{N}{dp^k}\\rfloor)$ Because $p\\geq \\sqrt B$ and $d\\geq B$, we only need to consider $k\\le \\frac{\\log N}{\\log B}$, which is similar to $O(1)$. In this part, we only need $f(x)$ for $x\\le B$, so to calculate these $f$ is actually a two-dimensional partial order problem which can be solved using a BIT, time complexity $O(\\frac NB\\log N)$. Since for each $d$, we get $G(d,p)$ in $O(1)$ in case (i), and $O(\\log N)$ in case (ii). The total time complexity is $O\\left(N^{\\frac 23} + \\frac{\\sqrt N\\times \\sqrt B}{\\log N}+ \\frac NB\\log N+D\\log N\\right)$. Let $B=N^{\\frac 13}\\log^{\\frac 43}N$, the total time complexity is $O\\left(N^{\\frac 23}+ \\frac{N^{\\frac 23}}{\\log^{\\frac 13}N}+D\\log N\\right)$. This part is included in the offline contest. $\\texttt{Key observation 2}$ : The number of $i$ in range $[1,n]$ that satisfy $\\mathrm{minp}\\geq n^{\\frac{1}{4}}$ is of the order of $\\frac{n}{\\ln n}$. $O\\left(\\sum_{x=\\pi(n^{\\frac{1}{4}})}^{\\pi(n)}\\sum_{y=\\pi(n^{\\frac{1}{4}})}^{\\pi(\\frac{n}{p_x})}\\max\\left(\\pi(\\frac{n}{p_xp_y})-\\pi(n^{\\frac{1}{4}}),0\\right)\\right)=O\\left(\\sum_{x=\\pi(n^{\\frac{1}{4}})}^{\\pi(n)}\\pi(\\frac{n}{p_x})\\sum_{y=\\pi(n^{\\frac{1}{4}})}^{\\pi(\\frac{n}{p_x})}\\frac{1}{p_y}\\right)$ $O\\left(\\sum_{n^{\\frac{1}{3}}\\leq p\\leq n}\\frac{1}{p}\\right)=O(\\log\\log n-\\log\\log n^{\\frac{1}{3}})=O(\\log 3)$ $O\\left(\\sum_{x=\\pi(n^{\\frac{1}{4}})}^{\\pi(n)}\\pi(\\frac{n}{p_x})\\sum_{y=\\pi(n^{\\frac{1}{4}})}^{\\pi(\\frac{n}{p_x})}\\frac{1}{p_y}\\right)=O\\left(\\sum_{x=\\pi(n^{\\frac{1}{4}})}^{\\pi(n)}\\pi(\\frac{n}{p_x})\\right)=O(\\pi(n))=O(\\frac{n}{\\log n})$ Since we only need to calculate $G(\\frac{d}{\\mathrm{maxp}(d)},\\mathrm{maxp}(d))$ where $\\text{maxp}(d)\\gt \\sqrt B$ in case (ii). We actually only need to consider those $\\text{minp}(i)\\gt \\sqrt B$, and $i\\le \\frac{d}{\\text{maxp}(d)}\\le\\frac N{\\sqrt B}$. Then if $B\\gt N^{\\frac 13}$, the actual size to append into the BIT is only $O(\\frac{N}{B\\log N})$, so the time complexity of case ii is $O(\\frac NB)$. Then we could adjust $B$ to $N^{\\frac 13}\\log^{\\frac 23}N$, the time complexity could reduce to $O\\left(\\frac {N^{\\frac 23}}{\\log^{\\frac 23}N}+D\\log N+N^{\\frac 23}\\right)$. To further optimize, let's introduce a method that could significantly reduce the time consumption of Du Sieve. The formula of Du Sieve is $\\sum_{xy\\leq N}f(x)g(y)=S_{f*g}(N)$. We can see that $\\min(x,y)\\leq\\sqrt{N}$, Let $B=\\lfloor\\sqrt{N}\\rfloor$, the formula could be rewritten like this: $\\sum_{i=1}^Bf(i)S_g(\\lfloor\\frac{N}{i}\\rfloor)+g(i)S_f(\\lfloor\\frac{N}{i}\\rfloor)-S_f(B)S_g(B)=S_{f*g}(N)$ $S_f(N)=S_{f*g}(N)+S_f(B)S_g(B)-\\sum_{i=2}^Bf(i)S_g(\\lfloor\\frac{N}{i}\\rfloor)+g(i)S_f(\\lfloor\\frac{N}{i}\\rfloor)-S_g(N)$ Traditionally, we need $[6B,8B]$ times of division, but using this method need a maximum of $2B$ times of division. As for what we need to calculate in this problem, we can get the formula: $S_{\\varphi}(N)=\\frac{N(N-1)}{2}+S_{\\varphi(B)}\\times B-\\sum_{i=2}^B\\varphi(i)\\lfloor\\frac{N}{i}\\rfloor+iS_{\\varphi}(\\lfloor\\frac{N}{i}\\rfloor)$ Without using things like $\\text{std::map}$, and use dynamic programming instead of DFS, we can further reduce the time consumption. Then consider how to optimize Du Sieve to $O\\left(\\frac{N^{\\frac{2}{3}}}{\\log N}\\right)$. Definition: if $f$ is a multiplicative function, then we define a multiplicative function $f_x(p^k)=[p\\geq x]f(p^k)$. We can calculate $\\varphi_{N^{\\frac{1}{6}}}(\\lfloor\\frac {N}{i} \\rfloor)$ for each $i$ and then recurrence $\\varphi$ from $\\varphi_{N^{\\frac 16}}$. Let $n6=N^{\\frac{1}{6}}$, we can change the formula into: $S_{\\varphi_{n6}}(N)=S_{id_{n6}}(N)-S_{1_{n6}}(N)+S_{\\varphi_{n6}}(B)S_{1_{n6}}(B)-\\sum_{i=2}^B[\\mathrm{minp}(i)\\geq n6]\\varphi(i)S_{1_{n6}}(\\lfloor\\frac{N}{i}\\rfloor)+S_{\\varphi_{n6}}(\\lfloor\\frac{N}{i})$ Where $\\text{id}(x)=x$ and $1(x)=1$, which can be calculated through $\\text{min25}$ Seive, but we only need to solve $p\\leq n6$ instead of $p\\leq\\sqrt N$. According to $\\texttt{Key observation 2}$, we know that the number of $i\\le \\sqrt N$ that satisfy $\\mathrm{minp}(i)\\geq n6$ is about $\\frac{\\sqrt N}{\\log N}$, find them and iterate these numbers in the Du Sieve. The time complexity of this part is $O\\left(\\frac{N^{\\frac{2}{3}}}{\\log N}\\right)$. At last we get a solution of $O\\left(\\frac{N^{\\frac{2}{3}}}{\\log N}+\\frac{\\sqrt{NK}}{\\log N}+\\frac{N}{K}\\right)$.",
    "code": "#include<bitset>\n#include<cstdio>\n#include<vector>\n#include<cmath>\n#include<ctime>\nusing std::min;\nusing std::max;\ntypedef unsigned uint;\ntypedef unsigned long long ull;\nnamespace Sol{\n    const uint M=4162277+5,Pi=1001258+5,M2=500000000+5;\n    uint sum;ull N;\n    uint F[M],G[M];\n    uint top,Sp[Pi],pri[Pi],pi[M],phi[M2];double g[Pi];\n    uint n4,K,B,m,lim,BIT[M];\n    double st,ed;\n    struct nb{\n        ull n;uint phi;\n        nb(const ull&n=1,const uint&phi=1):n(n),phi(phi){}\n    };std::vector<nb>d[Pi];\n    inline ull div(const ull&n,const ull&m){\n        return n*1./m;\n    }\n    inline void Add(uint n,const uint&V){\n        while(n<=B)BIT[n]+=V,n+=n&-n;\n    }\n    inline uint Qry(uint n){\n        uint ans(0);while(n)ans+=BIT[n],n-=n&-n;return ans;\n    }\n    inline bool check(double P,ull n,uint k){\n        ull x(1);while(P>1&&k<=m&&x*pri[k]<=n)P*=g[k],x*=pri[k++];return P>1;\n    }\n    inline bool DFS1(const ull&n,uint k,const ull&phi){\n        const ull&T=div(N,n);const uint&w=int(n/phi)+1; \n        if(check(w*phi*1./n,T,k))return true;\n        //g(n)*p/(p-1)>=int(g(n))+1\n        const uint&R=pi[min(div(w*phi,w*phi-n),min(ull(B),T))];\n        for(;k<=m;++k){\n            const uint&p=pri[k];if(p*p>T)break;\n            if(k<=R)d[k].push_back(nb(n,phi)),n*p<=B&&(lim=max(lim,k));\n            for(ull x=n,tp=phi*(p-1);x*p<=N;tp*=p)if(DFS1(x*=p,k+1,tp))break;\n        }\n        if(k<=R)sum+=phi*(Sp[R]-Sp[k-1]);\n        return false;\n    }\n    inline void DFS2(const uint&n,uint k,const uint&phi){\n        const uint&T=div(B,n);Add(n,phi);\n        for(;k<=m;++k){\n            const uint&p=pri[k],&T2=div(B,p);if(p>T)return;\n            for(uint x=n,tp=phi*(p-1);x<=T2;tp*=p)DFS2(x*=p,k+1,tp);\n        }\n    }\n    void sieve(const uint&n){\n        phi[1]=1;\n        for(uint i=2;i<=n;++i){\n            if(!phi[i]){\n            \tphi[i]=i-1;if(i<=B)pri[++top]=i,g[top]=1.*(i-1)/i,Sp[top]=Sp[top-1]+phi[i],pi[i]=1;\n\t\t\t}\n            for(uint x,j=1;j<=top&&(x=i*pri[j])<=n;++j){\n\t\t\t    phi[x]=phi[i]*(pri[j]-1);if(div(i,pri[j])*pri[j]==i){phi[x]+=phi[i];break;}\n\t\t\t}\n            if(i<=B)pi[i]+=pi[i-1];\n        }\n    }\n    void Getphi(const ull&n){\n    \tconst uint&B2=div(N,K);\n\t\tfor(uint i=1;i<=B;++i)G[i]=G[i-1]+phi[i];for(uint i=div(N,B);i>=1;--i)F[B]+=phi[i];\n\t\tfor(uint i=B-1;i>B2;--i){\n\t\t\tconst uint&L=div(N,i+1)+1,&R=div(N,i);F[i]=F[i+1];for(uint k=L;k<=R;++k)F[i]+=phi[k];\n\t\t}\n    \tfor(uint i=B2;i>=1;--i){\n    \t\tconst ull&T=div(N,i);const uint&lim=sqrt(T);F[i]=lim*G[lim]+T*(T-1)/2;\n    \t\tfor(uint k=2;k<=lim;++k){\n    \t\t\tconst uint&x=div(T,k);F[i]-=(i*k<=B?F[i*k]:G[x])+phi[k]*x;\n\t\t\t}\n\t\t}\n    }\n    uint Solve(const ull&n){\n    \tst=clock();\n        N=n;B=sqrt(N);n4=sqrt(B);\n        sieve(K=uint(pow(N,2./3)));m=pi[B];\n        fprintf(stderr,\"sieve(%d) done %lf\\n\",K,((ed=clock())-st)/1000);st=ed;\n        DFS1(1,1,1);\n        fprintf(stderr,\"DFS done %lf\\n\",((ed=clock())-st)/1000);st=ed;\n        Getphi(N);sum+=F[1];\n        fprintf(stderr,\"Getphi done %lf\\n\",((ed=clock())-st)/1000);st=ed;\n        for(uint i=1;i<=lim;++i){\n            const uint&p=pri[i],&T=B/p;const ull&k=div(N,p);\n            for(nb&x:d[i])sum+=x.phi*(x.n<=B?F[x.n]:G[div(N,x.n)]);\n            for(uint i=1;i<=T;++i)F[i]-=p*F[i*p];\n            for(uint i=T+1;i<=B;++i)F[i]-=p*G[div(k,i)];\n            for(uint i=B,j=div(i,p);j;--j)for(uint e=j*p,V=p*G[j];i>=e;--i)G[i]-=V;\n            for(uint i=p,j=1;i<=B;++j)for(uint e=min(i+p,B+1),V=G[j];i<e;++i)G[i]+=V;\n            for(uint i=B;i>T;--i)F[i]+=G[div(k,i)];\n            for(uint i=T;i>=1;--i)F[i]+=F[i*p];\n            for(nb&x:d[i])sum-=x.phi*(x.n<=B?F[x.n]:G[div(N,x.n)]);\n        }\n        fprintf(stderr,\"case1 done %lf\\n\",((ed=clock())-st)/1000);st=ed;\n        Add(1,1);\n        for(uint i=m;i>lim;--i){\n            const uint&p=pri[i];\n            for(nb&x:d[i]){\n                ull n=N/x.n/p,phi=x.phi*(p-1);\n                while(n)sum+=phi*Qry(n),n/=p,phi*=p;\n            }\n            for(ull x=p,phi=p-1;x<=B;x*=p,phi*=p)DFS2(x,i+1,phi);\n        }\n        fprintf(stderr,\"case2 done %lf\\n\",((ed=clock())-st)/1000);st=ed;\n        return n*(n+1)/2-sum;\n    }\n}\nnamespace sol{\n\tuint top,pri[10005],pos[10005],phi[10005];\n\tinline uint solve(const uint&N){\n\t\tuint sum(0);phi[1]=1;\n\t\tfor(uint i=2;i<=N;++i){\n\t\t\tif(!pos[i])pri[pos[i]=++top]=i,phi[i]=i-1;\n\t\t\tfor(uint x,j=1;j<=pos[i]&&(x=i*pri[j])<=N;++j)phi[x]=(pos[x]=j)==pos[i]?phi[i]*pri[j]:phi[i]*(pri[j]-1);\n\t\t\tsum+=i%phi[i];\n\t\t}\n\t\treturn sum;\n\t} \n}\nsigned main(){\n    ull n;scanf(\"%llu\",&n);if(n<=10000)return printf(\"%u\\n\",sol::solve(n)),0;printf(\"%u\\n\",Sol::Solve(n));\n}",
    "tags": [
      "math"
    ],
    "rating": 3400
  },
  {
    "contest_id": "2082",
    "index": "A",
    "title": "Binary Matrix",
    "statement": "A matrix is called binary if all its elements are either $0$ or $1$.\n\nEcrade calls a binary matrix $A$ good if the following two properties hold:\n\n- The bitwise XOR of all numbers in each row of matrix $A$ is equal to $0$.\n- The bitwise XOR of all numbers in each column of matrix $A$ is equal to $0$.\n\nEcrade has a binary matrix of size $n \\cdot m$. He is interested in the minimum number of elements that need to be changed for the matrix to become good.\n\nHowever, it seems a little difficult, so please help him!",
    "tutorial": "Do we really have to consider the problem on the whole matrix? Let $r$ be the number of rows where the bitwise XOR of all the numbers in it is $1$, and $c$ be the number of columns where the bitwise XOR of all the numbers in it is $1$. Our goal is to make both $r$ and $c$ zero. When we change an element in the matrix, both $r$ and $c$ change by exactly one. Thus, it's not hard to see that the answer is $\\max (r,c)$. The time complexity is $O(\\sum nm)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll t,n,m,r,c;\nchar s[1009];\nbool a[1009][1009];\ninline ll read(){\n\tll s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nint main(){\n\tt = read();\n\twhile (t --){\n\t\tn = read(),m = read(),r = c = 0;\n\t\tfor (ll i = 1;i <= n;i += 1){\n\t\t\tscanf(\"%s\",s + 1);\n\t\t\tfor (ll j = 1;j <= m;j += 1) a[i][j] = s[j] - '0';\n\t\t}\n\t\tfor (ll i = 1;i <= n;i += 1){\n\t\t\tbool sum = 0;\n\t\t\tfor (ll j = 1;j <= m;j += 1) sum ^= a[i][j];\n\t\t\tif (sum) r += 1;\n\t\t}\n\t\tfor (ll j = 1;j <= m;j += 1){\n\t\t\tbool sum = 0;\n\t\t\tfor (ll i = 1;i <= n;i += 1) sum ^= a[i][j];\n\t\t\tif (sum) c += 1;\n\t\t}\n\t\tprintf(\"%lld\\n\",max(r,c));\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "2082",
    "index": "B",
    "title": "Floor or Ceil",
    "statement": "Ecrade has an integer $x$. There are two kinds of operations.\n\n- Replace $x$ with $\\left\\lfloor \\dfrac{x}{2}\\right\\rfloor$, where $\\left\\lfloor \\dfrac{x}{2}\\right\\rfloor$ is the greatest integer $\\le \\dfrac{x}{2}$.\n- Replace $x$ with $\\left\\lceil \\dfrac{x}{2}\\right\\rceil$, where $\\left\\lceil \\dfrac{x}{2}\\right\\rceil$ is the smallest integer $\\ge \\dfrac{x}{2}$.\n\nEcrade will perform exactly $n$ first operations and $m$ second operations in any order. He wants to know the minimum and the maximum possible value of $x$ after $n+m$ operations. However, it seems a little difficult, so please help him!",
    "tutorial": "Consider $x$ in binary form. What are all possible values of $x$ after $n+m$ operations? Let's consider how to find the maximum value first. Consider $x$ in binary form. Let the number formed by the last $n+m$ bits of $x$ be denoted as $r$, and the remaining higher bits form the number $l$ (for instance, if $x=12=(1100)_2$, $n=1$, $m=2$, then $l=1=(1)_2$, $r=4=(100)_2$), then the final value of $x$ after $n+m$ operations will be either $l$ or $l+1$, depending on whether a carry-over occurs in $r$ during the last operation. If there are no $1$s in the higher $m$ bits of $r$, then the carry-over in $r$ during the last operation can never occur (operating on some small tests may give you a better understanding). Otherwise, we can choose to perform $n$ floor operations first followed by $m$ ceil operations, which can guarantee a carry-over in $r$ during the last operation. This demonstrates that performing $n$ floor operations first followed by $m$ ceil operations will always yield the maximum value. Similarly, performing $m$ ceil operations first followed by $n$ floor operations will always produce the minimum value. We can simply simulate these operations because after $O(\\log x)$ same operations, $x$ will remain unchanged. The time complexity is $O(T\\log x)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll t,x,n,m;\ninline ll read(){\n\tll s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nll F(ll x,ll n){\n\twhile (n --){\n\t\tif (!x) return x;\n\t\tx = (x >> 1);\n\t}\n\treturn x;\n}\nll C(ll x,ll n){\n\twhile (n --){\n\t\tif (x <= 1) return x;\n\t\tx = ((x + 1) >> 1);\n\t}\n\treturn x;\n}\nint main(){\n\tt = read();\n\twhile (t --){\n\t\tx = read(),n = read(),m = read();\n\t\tprintf(\"%lld %lld\\n\",F(C(x,m),n),C(F(x,n),m));\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2084",
    "index": "A",
    "title": "Max and Mod",
    "statement": "You are given an integer $n$. Find any permutation $p$ of length $n$$^{\\text{∗}}$ such that:\n\n- For all $2 \\le i \\le n$, $\\max(p_{i - 1}, p_i) \\bmod i$ $^{\\text{†}}$ $= i - 1$ is satisfied.\n\nIf it is impossible to find such a permutation $p$, output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$$x \\bmod y$ denotes the remainder from dividing $x$ by $y$.\n\\end{footnotesize}",
    "tutorial": "When $n$ is odd, we can construct $p = [n, 1, 2, \\ldots, n - 1]$. In this case: For $i = 2$, $\\max(p_1, p_2) = n$ and $n \\bmod 2 = 1$. For $i \\geq 3$, $\\max(p_{i - 1}, p_i) = i - 1$ and $(i - 1) \\bmod i = i - 1$. It can be proven that there is no solution when $n$ is even. Clearly, $n$ cannot be placed at $p_1, p_2$, or $p_n$. If $n$ is placed in position $3 \\sim n - 1$, let $x$ be the position of $n$, then we have $\\max(p_{x - 1}, p_x) = \\max(p_x, p_{x + 1}) = n$. Thus, there must exist an even number $2 \\leq i \\leq n$ such that $\\max(p_{i - 1}, p_i) = n$ and it must satisfy $\\max(p_{i - 1}, p_i) \\bmod i = i - 1$. However, an even number modulo another even number can never yield an odd result, leading to a contradiction. Time complexity: $O(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint T, n;\n\tcin >> T;\n\twhile (T--) {\n\t\tcin >> n;\n\t\tif (n & 1) {\n\t\t\tcout << n << ' ';\n\t\t\tfor (int i = 1; i < n; ++i) {\n\t\t\t\tcout << i << \" \\n\"[i == n - 1];\n\t\t\t}\n\t\t} else {\n\t\t\tcout << \"-1\\n\";\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2084",
    "index": "B",
    "title": "MIN = GCD",
    "statement": "You are given a positive integer sequence $a$ of length $n$. Determine if it is possible to rearrange $a$ such that there exists an integer $i$ ($1 \\le i<n$) satisfying $$ \\min([a_1,a_2,\\ldots,a_i])=\\gcd([a_{i+1},a_{i+2},\\ldots,a_n]). $$\n\nHere $\\gcd(c)$ denotes the greatest common divisor of $c$, which is the maximum positive integer that divides all integers in $c$.",
    "tutorial": "For any positive integer sequence $a$, we always have $\\gcd(a) \\leq \\min(a)$. Let $x = \\min(a)$, then $x$ must be placed on the $\\min([a_1, a_2, \\ldots, a_i])$ side. Thus, we can conclude that: $\\min([a_1, a_2, \\ldots, a_i]) = \\gcd([a_{i + 1}, a_{i + 2}, \\ldots, a_n]) = x$ Now, we need to select some numbers, excluding one occurrence of $x$, to be placed on the $\\gcd([a_{i + 1}, a_{i + 2}, \\ldots, a_n])$ side, ensuring that $\\gcd([a_{i + 1}, a_{i + 2}, \\ldots, a_n]) = x$. A greedy strategy is to place all multiples of $x$ on the $\\gcd$ side after removing one occurrence of $x$. This minimizes $\\gcd$ while ensuring it remains a multiple of $x$. Thus, we only need to check whether the $\\gcd$ of the remaining multiples of $x$ (after removing one occurrence of $x$) is still equal to $x$. Time complexity: $O(n + \\log a)$ or $O(n \\log a)$ (depending on which $\\gcd$ implementation you use) per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tint T, n;\n\tcin >> T;\n\twhile (T--) {\n\t\tcin >> n;\n\t\tvector<ll> a(n);\n\t\tfor (ll &x : a) {\n\t\t\tcin >> x;\n\t\t}\n\t\tint p = min_element(a.begin(), a.end()) - a.begin();\n\t\tll g = 0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (i != p && a[i] % a[p] == 0) {\n\t\t\t\tg = __gcd(g, a[i]);\n\t\t\t}\n\t\t}\n\t\tcout << (g == a[p] ? \"Yes\\n\" : \"No\\n\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2084",
    "index": "C",
    "title": "You Soared Afar With Grace",
    "statement": "You are given a permutation $a$ and $b$ of length $n$$^{\\text{∗}}$. You can perform the following operation at most $n$ times:\n\n- Choose two indices $i$ and $j$ ($1 \\le i, j \\le n$, $i \\ne j$), swap $a_i$ with $a_j$, swap $b_i$ with $b_j$.\n\nDetermine whether $a$ and $b$ can be reverses of each other after operations. In other words, for each $i = 1, 2, \\ldots, n$, $a_i = b_{n + 1 - i}$.\n\nIf it is possible, output any valid sequence of operations. Otherwise, output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "By analyzing the structure of the operation, we can see that each pair $(a_i, b_i)$ is swapped together, meaning that the corresponding $b_i$ of a given $a_i$ remains unchanged. Since our goal is to make $b$ the reverse of $a$, in the final sequence, $(a_{n - i + 1}, b_{n - i + 1})$ must be equal to $(b_i, a_i)$. This implies that in the initial sequence, if $(a_i, b_i)$ exists, then $(b_i, a_i)$ must also exist; otherwise, no solution is possible. In particular, if $n$ is odd, there must be exactly one pair $(a_i, b_i)$ satisfying $a_i = b_i$, and this pair must be swapped to position $\\frac{n + 1}{2}$. As for the construction method, first, if $n$ is odd, move the pair where $a_i = b_i$ to position $\\frac{n + 1}{2}$. Then, let $p_i$ denote the position of $i$ in $a$. Iterate over $i = 1, 2, \\ldots, \\left\\lfloor\\frac{n}{2}\\right\\rfloor$, swapping positions $p_{b_i}$ and $n - i + 1$. This ensures that by the time we reach $i$, for every $1 \\leq j \\leq i$, the conditions $a_j = b_{n - j + 1}$ and $a_{n - j + 1} = b_j$ hold. This process requires at most $\\left\\lceil\\frac{n}{2}\\right\\rceil$ operations. Time complexity: $O(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int maxn = 200100;\n\nint n, a[maxn], b[maxn], m, p[maxn], ans[maxn][2];\n\ninline void work(int x, int y) {\n\tif (x == y) {\n\t\treturn;\n\t}\n\tans[++m][0] = x;\n\tans[m][1] = y;\n\tswap(a[x], a[y]);\n\tswap(p[a[x]], p[a[y]]);\n\tswap(b[x], b[y]);\n}\n\nvoid solve() {\n\tcin >> n;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tcin >> a[i];\n\t\tp[a[i]] = i;\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tcin >> b[i];\n\t}\n\tm = 0;\n\tint x = 0;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tif (a[i] == b[i]) {\n\t\t\tif (n % 2 == 0 || x) {\n\t\t\t\tcout << \"-1\\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tx = i;\n\t\t} else if (b[p[b[i]]] != a[i]) {\n\t\t\tcout << \"-1\\n\";\n\t\t\treturn;\n\t\t}\n\t}\n\tif (n & 1) {\n\t\twork(x, (n + 1) / 2);\n\t}\n\tfor (int i = 1; i <= n / 2; ++i) {\n\t\twork(p[b[i]], n - i + 1);\n\t}\n\tcout << m << '\\n';\n\tfor (int i = 1; i <= m; ++i) {\n\t\tcout << ans[i][0] << ' ' << ans[i][1] << '\\n';\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2084",
    "index": "D",
    "title": "Arcology On Permafrost",
    "statement": "You are given three integers $n$, $m$, and $k$, where $m \\cdot k < n$.\n\nFor a sequence $b$ consisting of non-negative integers, define $f(b)$ as follows:\n\n- You may perform the following operation on $b$:\n\n- Let $l$ denote the current length of $b$. Choose a positive integer $1 \\leq i \\leq l - k + 1$, remove the subarray from index $i$ to $i + k - 1$ and concatenate the remaining parts. In other words, replace $b$ with $$[b_1, b_2, \\ldots, b_{i - 1}, b_{i + k}, b_{i + k + 1}, \\ldots, b_l].$$\n\n- $f(b)$ is defined as the \\textbf{minimum} possible value of $\\operatorname{mex}(b)$$^{\\text{∗}}$ after performing the above operation \\textbf{at most $m$ times} (possibly zero).\n\nYou need to construct a sequence $a$ of length $n$ consisting of non-negative integers, such that:\n\n- For all $1 \\le i \\le n$, $0 \\le a_i \\le 10^9$.\n- Over all such sequences $a$, $f(a)$ is \\textbf{maximized}.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The minimum excluded (MEX) of a collection of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $c$.\n\\end{footnotesize}",
    "tutorial": "Since performing the operation will never increase $\\operatorname{mex}$ of the sequence, we can treat \"at most $m$ operations\" as \"exactly $m$ operations\". Next, we consider computing the maximum value of $f(a)$. First, we have $f(a) \\leq n - m \\cdot k$ because after the operations, the length of $a$ becomes $n - m \\cdot k$, and the $\\operatorname{mex}$ of a sequence must be no more than its length. Second, we have $f(a) \\leq \\frac{n}{m + 1}$, because to ensure that all numbers in $0 \\sim f(a) - 1$ are not completely removed, each of them must appear at least $m + 1$ times. We claim that the maximum value of $f(a)$ is $\\min(n - m \\cdot k, \\left\\lfloor\\frac{n}{m + 1}\\right\\rfloor)$ Next, we prove that this maximum value can be achieved through construction. If $n - m \\cdot k < \\frac{n}{m + 1}$, then $n < (m + 1) \\cdot k$, which implies $n - m \\cdot k < k$, meaning that the final length of $a$ is less than $k$. In this case, we construct $a_i = i \\bmod k$. This ensures that no matter which subarray is removed, the remaining sequence still satisfies $a_i = i \\bmod k$. After performing $m$ deletions, we are left with $a_i = i$. If $n - m \\cdot k \\geq \\frac{n}{m + 1}$, then $n \\geq (m + 1) \\cdot k$, which implies $\\frac{n}{m + 1} \\geq k$. Here, we construct $a_i = i \\bmod \\left\\lfloor\\frac{n}{m + 1}\\right\\rfloor$. This guarantees that every pair of identical numbers has a distance of at least $k$, and that all numbers in $0 \\sim \\left\\lfloor\\frac{n}{m + 1}\\right\\rfloor - 1$ appear at least $m + 1$ times. Thus, each deletion can remove at most one of these numbers, ensuring that no number is completely removed after $m$ deletions. Time complexity: $O(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tint n, m, k;\n\t\tcin >> n >> m >> k;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tcout << i % (n < (m + 1) * k ? k : n / (m + 1)) << \" \\n\"[i == n - 1];\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2084",
    "index": "E",
    "title": "Blossom",
    "statement": "You are given a permutation $a$ of length $n$$^{\\text{∗}}$ where some elements are missing and represented by $-1$.\n\nDefine the value of a permutation as the sum of the MEX$^{\\text{†}}$ of all its non-empty subsegments$^{\\text{‡}}$.\n\nFind the sum of the value of all possible valid permutations that can be formed by filling in the missing elements of $a$ modulo $10^9 + 7$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ A permutation of length $n$ is an array consisting of $n$ distinct integers \\textbf{from $\\bf{0}$ to $\\bf{n - 1}$} in arbitrary order. For example, $[1,2,0,4,3]$ is a permutation, but $[0,1,1]$ is not a permutation ($1$ appears twice in the array), and $[0,2,3]$ is also not a permutation ($n=3$ but there is $3$ in the array).\n\n$^{\\text{†}}$The minimum excluded (MEX) of a collection of integers $c_1, c_2, \\ldots, c_k$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $c$.\n\n$^{\\text{‡}}$A sequence $a$ is a subsegment of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "We transform $\\operatorname{mex}([a_i, a_{i + 1}, \\ldots, a_j])$ into $\\sum\\limits_{k = 0}^{n - 1} [\\text{numbers from 0 to}\\ k\\ \\text{all appear in}\\ [i, j]]$. Let there be $t$ occurrences of $-1$ in $a$. Since $a$ needs to be a permutation, for each number from $0$ to $k$, if it has appeared in $a$, it must appear in $[i, j]$. For such a group $(i, j, k)$, let $[i, j]$ contain $c_1$ $-1$s, and the number of elements in $0 \\sim k$ that have not appeared in $a$ be $c_2$. The contribution is: $\\binom{c_1}{c_2} \\cdot c_2! \\cdot (t - c_2)!$ As for the optimization, consider enumerating $k$ and $c_1$. We need to quickly find how many intervals $[i, j]$ satisfy: There are exactly $c_1$ $-1$s in $[i, j]$; For every number from $0$ to $k$, if it appears in $a$, its position must lie within $[i, j]$. Let $d_{i, j}$ be the number of intervals satisfying these conditions for $c_1 = i$ and $k = j$. We enumerate each interval $[i, j]$, and let $x$ be the number of $-1$s in $[i, j]$, and $y$ be the minimum number of numbers that appeared in $a$ but whose positions do not lie in $[i, j]$ (if no such number exists, then $y = n$). The contribution of this interval to $d$ is that $d_{x, 0}, d_{x, 1}, \\ldots, d_{x, y - 1}$ are all added by $1$. Time complexity: $O(n^2)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int maxn = 5050;\nconst int mod = 1000000007;\n\nint n, a[maxn], fac[maxn], C[maxn][maxn], b[maxn], d[maxn][maxn];\nbool vis[maxn];\n\nvoid solve() {\n\tcin >> n;\n\tfor (int i = 0; i <= n; ++i) {\n\t\tvis[i] = 0;\n\t\tfor (int j = 0; j <= n; ++j) {\n\t\t\td[i][j] = 0;\n\t\t}\n\t}\n\tfac[0] = 1;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tcin >> a[i];\n\t\tfac[i] = 1LL * fac[i - 1] * i % mod;\n\t\tb[i] = b[i - 1] + (a[i] == -1);\n\t\tif (a[i] != -1) {\n\t\t\tvis[a[i]] = 1;\n\t\t}\n\t}\n\tfor (int i = 0; i <= n; ++i) {\n\t\tC[i][0] = C[i][i] = 1;\n\t\tfor (int j = 1; j < i; ++j) {\n\t\t\tC[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod;\n\t\t}\n\t}\n\tint mn1 = n;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tint mn2 = n;\n\t\tfor (int j = n; j >= i; --j) {\n\t\t\tint x = b[j] - b[i - 1], y = min(mn1, mn2);\n\t\t\t++d[x][0];\n\t\t\t--d[x][y];\n\t\t\tif (a[j] != -1) {\n\t\t\t\tmn2 = min(mn2, a[j]);\n\t\t\t}\n\t\t}\n\t\tif (a[i] != -1) {\n\t\t\tmn1 = min(mn1, a[i]);\n\t\t}\n\t}\n\tfor (int i = 0; i <= b[n]; ++i) {\n\t\tfor (int j = 1; j <= n; ++j) {\n\t\t\td[i][j] += d[i][j - 1];\n\t\t}\n\t}\n\tint ans = 0, cnt = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tcnt += (!vis[i]);\n\t\tfor (int j = cnt; j <= b[n]; ++j) {\n\t\t\tans = (ans + 1LL * C[j][cnt] * fac[cnt] % mod * fac[b[n] - cnt] % mod * d[j][i]) % mod;\n\t\t}\n\t}\n\tcout << ans << '\\n';\n}\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "combinatorics",
      "dp",
      "implementation",
      "math",
      "two pointers"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2084",
    "index": "F",
    "title": "Skyscape",
    "statement": "You are given a permutation $a$ of length $n$$^{\\text{∗}}$.\n\nWe say that a permutation $b$ of length $n$ is good if the two permutations $a$ and $b$ can become the same after performing the following operation \\textbf{at most $n$ times} (possibly zero):\n\n- Choose two integers $l, r$ such that $1 \\le l < r \\le n$ and $a_r = \\min(a_l, a_{l + 1}, \\ldots, a_r)$.\n- Cyclically shift the subsegment $[a_l, a_{l + 1}, \\ldots, a_r]$ one position to the right. In other words, replace $a$ with $[a_1, \\ldots, a_{l - 1}, \\; a_r, a_l, a_{l + 1}, \\ldots, a_{r - 1}, \\; a_{r + 1}, \\ldots, a_n]$.\n\nYou are also given a permutation $c$ of length $n$ where some elements are missing and represented by $0$.\n\nYou need to find a \\textbf{good} permutation $b_1, b_2, \\ldots, b_n$ such that $b$ can be formed by filling in the missing elements of $c$ (i.e., for all $1 \\le i \\le n$, if $c_i \\ne 0$, then $b_i = c_i$). If it is impossible, output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "A permutation $b$ is considered good if and only if the ordered pairs in $a$ remain ordered pairs in $b$. In other words, for any pair $i < j$, if the position of $i$ in $a$ is smaller than that of $j$, then the position of $i$ in $b$ must also be smaller than that of $j$. Proof of necessity: The operation will not turn any originally ordered pair in $a$ into an inversion. Proof of sufficiency: For $a$ and $b$ that satisfy the above condition, it is always possible to make $a$ identical to $b$ through the following operation: Iterate over $i = 1, 2, \\ldots, n$. If $a_i = b_i$, skip; otherwise, let $j$ be the position of $b_i$ in $a$, and perform an operation with $l = i, r = j$. Iterate over $i = 1, 2, \\ldots, n$. If $a_i = b_i$, skip; otherwise, let $j$ be the position of $b_i$ in $a$, and perform an operation with $l = i, r = j$. For numbers in $c$ that are not $0$, if they violate the above condition, then it is clearly impossible to find a solution. Otherwise, for a number $x$ that does not appear in $c$, if we only consider the restrictions imposed by the numbers in $c$, the legal range for its position in $c$ is an interval $[l_x, r_x]$. $l_x$ and $r_x$ can be calculated using a Fenwick Tree or Segment Tree. It seems that this is a classic greedy problem of \"filling numbers into positions, where the $i$-th number's position must be within the interval $[l_i, r_i]$.\" The approach is to determine each position from left to right. For the $i$-th position, fill the smallest number $j$ such that $l_j \\leq i$ and $r_j$ is the minimum over all numbers $j$ that have not been filled yet. This can be implemented with a heap. However, we must also consider the mutual constraints between the numbers to be placed in $c$. In fact, we can observe that for any $x < y$, if $x$'s position in $a$ is smaller than $y$'s position, then $l_x \\leq l_y$ and $r_x \\leq r_y$. Therefore, if we directly apply the above greedy approach (when multiple $r_j$'s are the smallest, fill the smallest $j$), the legality condition will naturally be satisfied. Time complexity: $O(n \\log n)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst int maxn = 500100;\n\nint n, a[maxn], b[maxn], c[maxn], p[maxn], q[maxn];\n\nstruct node {\n\tint r, x;\n\tnode(int a = 0, int b = 0) : r(a), x(b) {}\n};\n\ninline bool operator < (const node &a, const node &b) {\n\treturn a.r > b.r || (a.r == b.r && a.x > b.x);\n}\n\nvector<node> vc[maxn];\n\nstruct DS1 {\n\tint c[maxn];\n\t\n\tinline void init() {\n\t\tfor (int i = 0; i <= n; ++i) {\n\t\t\tc[i] = 0;\n\t\t}\n\t}\n\t\n\tinline void update(int x, int d) {\n\t\tfor (int i = x; i <= n; i += (i & (-i))) {\n\t\t\tc[i] = max(c[i], d);\n\t\t}\n\t}\n\t\n\tinline int query(int x) {\n\t\tint res = 0;\n\t\tfor (int i = x; i; i -= (i & (-i))) {\n\t\t\tres = max(res, c[i]);\n\t\t}\n\t\treturn res;\n\t}\n} T1;\n\nstruct DS2 {\n\tint c[maxn];\n\t\n\tinline void init() {\n\t\tfor (int i = 0; i <= n; ++i) {\n\t\t\tc[i] = n + 1;\n\t\t}\n\t}\n\t\n\tinline void update(int x, int d) {\n\t\tfor (int i = x; i; i -= (i & (-i))) {\n\t\t\tc[i] = min(c[i], d);\n\t\t}\n\t}\n\t\n\tinline int query(int x) {\n\t\tint res = n + 1;\n\t\tfor (int i = x; i <= n; i += (i & (-i))) {\n\t\t\tres = min(res, c[i]);\n\t\t}\n\t\treturn res;\n\t}\n} T2;\n\nvoid solve() {\n\tcin >> n;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tcin >> a[i];\n\t\tp[a[i]] = i;\n\t\tq[i] = 0;\n\t\tvector<node>().swap(vc[i]);\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tcin >> b[i];\n\t\tif (b[i]) {\n\t\t\tq[b[i]] = i;\n\t\t}\n\t}\n\tT1.init();\n\tfor (int i = 1; i <= n; ++i) {\n\t\tif (q[i]) {\n\t\t\tif (T1.query(p[i]) > q[i]) {\n\t\t\t\tcout << \"-1\\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tT1.update(p[i], q[i]);\n\t\t}\n\t}\n\tT1.init();\n\tT2.init();\n\tfor (int i = 1; i <= n; ++i) {\n\t\tif (q[a[i]]) {\n\t\t\tT1.update(a[i], q[a[i]]);\n\t\t} else {\n\t\t\tc[i] = T1.query(a[i]) + 1;\n\t\t}\n\t}\n\tfor (int i = n; i; --i) {\n\t\tif (q[a[i]]) {\n\t\t\tT2.update(a[i], q[a[i]]);\n\t\t} else {\n\t\t\tint r = T2.query(a[i]) - 1;\n\t\t\tif (c[i] > r) {\n\t\t\t\tcout << \"-1\\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvc[c[i]].emplace_back(r, a[i]);\n\t\t}\n\t}\n\tpriority_queue<node> pq;\n\tfor (int i = 1; i <= n; ++i) {\n\t\tfor (node u : vc[i]) {\n\t\t\tpq.push(u);\n\t\t}\n\t\tif (!b[i]) {\n\t\t\tif (pq.empty() || pq.top().r < i) {\n\t\t\t\tcout << \"-1\\n\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tb[i] = pq.top().x;\n\t\t\tpq.pop();\n\t\t}\n\t}\n\tfor (int i = 1; i <= n; ++i) {\n\t\tcout << b[i] << \" \\n\"[i == n];\n\t}\n}\n\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2084",
    "index": "G1",
    "title": "Wish Upon a Satellite (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $t \\le 1000$, $n \\le 5000$ and the sum of $n$ does not exceed $5000$. You can hack only if you solved all versions of this problem.}\n\nFor a non-empty sequence $c$ of length $k$, define $f(c)$ as follows:\n\n- Turtle and Piggy are playing a game on a sequence. They are given the sequence $c_1, c_2, \\ldots, c_k$, and Turtle goes first. Turtle and Piggy alternate in turns (so, Turtle does the first turn, Piggy does the second, Turtle does the third, etc.).\n- The game goes as follows:\n\n- Let the current length of the sequence be $m$. If $m = 1$, the game ends.\n- If the game does not end and it's Turtle's turn, then Turtle must choose an integer $i$ such that $1 \\le i \\le m - 1$, set $c_i$ to $\\min(c_i, c_{i + 1})$, and remove $c_{i + 1}$.\n- If the game does not end and it's Piggy's turn, then Piggy must choose an integer $i$ such that $1 \\le i \\le m - 1$, set $c_i$ to $\\max(c_i, c_{i + 1})$, and remove $c_{i + 1}$.\n\n- Turtle wants to \\textbf{maximize} the value of $c_1$ in the end, while Piggy wants to \\textbf{minimize} the value of $c_1$ in the end.\n- $f(c)$ is the value of $c_1$ in the end if both players play optimally.\n\nFor a permutation $p$ of length $n$$^{\\text{∗}}$, Turtle defines the beauty of the permutation as $\\sum\\limits_{i = 1}^n \\sum\\limits_{j = i}^n f([p_i, p_{i + 1}, \\ldots, p_j])$ (i.e., the sum of $f(c)$ where $c$ is a non-empty subsegment$^{\\text{†}}$ of $p$).\n\nPiggy gives Turtle a permutation $a$ of length $n$ where some elements are missing and represented by $0$.\n\nTurtle asks you to determine a permutation $b$ of length $n$ such that:\n\n- $b$ can be formed by filling in the missing elements of $a$ (i.e., for all $1 \\le i \\le n$, if $a_i \\ne 0$, then $b_i = a_i$).\n- The beauty of the permutation $b$ is \\textbf{maximized}.\n\nFor convenience, you only need to find the maximum beauty of such permutation $b$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$A sequence $a$ is a subsegment of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "First, we have $f(c) = \\begin{cases} \\min(c_1, c_k) & k \\bmod 2 = 0 \\\\ \\max(c_1, c_k) & k \\bmod 2 = 1 \\end{cases}$ Symmetrically, let $g(c)$ be the result when the order of the first and second players is swapped. Then, $g(c) = \\begin{cases} \\max(c_1, c_k) & k \\bmod 2 = 0 \\\\ \\min(c_1, c_k) & k \\bmod 2 = 1 \\end{cases}$ Proof: Consider an inductive approach. The base case $k \\leq 2$ is evident. For $k \\geq 3$, consider computing $f(c)$. Assume $k$ is odd. If the first player chooses $2 \\leq i \\leq k - 2$, the game reduces to $g(c')$, and the answer is $\\max(c_1, c_k)$. If the first player chooses $i = 1$ or $i = k - 1$, the answer is at most $\\max(c_1, c_k)$. Other cases follow similarly. Thus, for a permutation $p_1, p_2, \\dots, p_n$, we have $\\begin{aligned} & \\sum\\limits_{i = 1}^n \\sum\\limits_{j = i}^n f([p_i, p_{i + 1}, \\dots, p_j]) \\\\ = & \\sum\\limits_{i = 1}^n \\sum\\limits_{j = i}^n \\Big( [i \\bmod 2 = j \\bmod 2] \\max(p_i, p_j) + [i \\bmod 2 \\neq j \\bmod 2] \\min(p_i, p_j) \\Big) \\\\ = & \\sum\\limits_{i = 1}^n \\sum\\limits_{j = i}^n \\max(p_i, p_j) - \\sum\\limits_{i = 1}^n \\sum\\limits_{j = i + 1}^n [i \\bmod 2 \\neq j \\bmod 2] (\\max(p_i, p_j) - \\min(p_i, p_j)) \\\\ = & \\sum\\limits_{i = 1}^n i^2 - \\sum\\limits_{i = 1}^n \\sum\\limits_{j = i + 1}^n [i \\bmod 2 \\neq j \\bmod 2] |p_i - p_j| \\end{aligned}$ Thus, the problem reduces to minimizing the following expression: $\\sum\\limits_{i = 1}^n \\sum\\limits_{j = i + 1}^n [i \\bmod 2 \\neq j \\bmod 2] |b_i - b_j|$ This can be further transformed into a problem involving a number line from $1$ to $n$, where point $i$ can be black, white, or undetermined. If $i$ is at an odd index in sequence $a$, it is black; if even, it is white. If $i$ does not appear in $a$, it is undetermined. Our goal is to color the undetermined points as either black or white such that: There are exactly $\\left\\lceil\\frac{n}{2}\\right\\rceil$ black points. The sum of distances between all pairs of differently colored points is minimized. This sum can be rewritten as: for each $1 \\leq k < n$, the number of black points in $1 \\sim k$ times the number of white points in $k + 1 \\sim n$, plus the number of white points in $1 \\sim k$ times the number of black points in $k + 1 \\sim n$. This reformulated problem can be solved using DP. Define $f_{i, j}$ as the minimum possible sum of the above distances when $1 \\le k < i$ after determining the colors of the first $i$ points, with exactly $j$ black points. For transitions, first update $f_{i, j}$ by adding the contribution from $k = i$. That is to add $j \\times (\\left\\lfloor\\frac{n}{2}\\right\\rfloor - (i - j)) + (i - j) \\times (\\left\\lceil\\frac{n}{2}\\right\\rceil - j)$ to all $f_{i, j}$. Then, consider whether the $(i+1)$-th point is black or white: If it can be white, then perform $f_{i + 1, j} = \\min(f_{i + 1, j}, f_{i, j})$. If it can be black, then perform $f_{i + 1, j + 1} = \\min(f_{i + 1, j + 1}, f_{i, j})$. The final answer is $\\sum\\limits_{i = 1}^n i^2 - f_{n, \\left\\lceil\\frac{n}{2}\\right\\rceil}$. Time complexity: $O(n^2)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nvoid solve() {\n\tint n;\n\tcin >> n;\n\tvector<int> a(n + 1, -1);\n\tvector< vector<ll> > f(n + 1, vector<ll>(n + 1, 1e18));\n\tfor (int i = 1, x; i <= n; ++i) {\n\t\tcin >> x;\n\t\tif (x) {\n\t\t\ta[x] = i & 1;\n\t\t}\n\t}\n\tif (a[1] != 1) {\n\t\tf[1][0] = 0;\n\t}\n\tif (a[1] != 0) {\n\t\tf[1][1] = 0;\n\t}\n\tfor (int i = 1; i < n; ++i) {\n\t\tfor (int j = 0; j <= i; ++j) {\n\t\t\tf[i][j] += j * (n / 2 - (i - j)) + (i - j) * ((n + 1) / 2 - j);\n\t\t\tif (a[i + 1] != 1) {\n\t\t\t\tf[i + 1][j] = min(f[i + 1][j], f[i][j]);\n\t\t\t}\n\t\t\tif (a[i + 1] != 0) {\n\t\t\t\tf[i + 1][j + 1] = min(f[i + 1][j + 1], f[i][j]);\n\t\t\t}\n\t\t}\n\t}\n\tll ans = -f[n][(n + 1) / 2];\n\tfor (int i = 1; i <= n; ++i) {\n\t\tans += i * i;\n\t}\n\tcout << ans << '\\n';\n}\n\nint main() {\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "games"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2084",
    "index": "G2",
    "title": "Wish Upon a Satellite (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $t \\le 10^4$, $n \\le 5 \\cdot 10^5$ and the sum of $n$ does not exceed $5 \\cdot 10^5$. You can hack only if you solved all versions of this problem.}\n\nFor a non-empty sequence $c$ of length $k$, define $f(c)$ as follows:\n\n- Turtle and Piggy are playing a game on a sequence. They are given the sequence $c_1, c_2, \\ldots, c_k$, and Turtle goes first. Turtle and Piggy alternate in turns (so, Turtle does the first turn, Piggy does the second, Turtle does the third, etc.).\n- The game goes as follows:\n\n- Let the current length of the sequence be $m$. If $m = 1$, the game ends.\n- If the game does not end and it's Turtle's turn, then Turtle must choose an integer $i$ such that $1 \\le i \\le m - 1$, set $c_i$ to $\\min(c_i, c_{i + 1})$, and remove $c_{i + 1}$.\n- If the game does not end and it's Piggy's turn, then Piggy must choose an integer $i$ such that $1 \\le i \\le m - 1$, set $c_i$ to $\\max(c_i, c_{i + 1})$, and remove $c_{i + 1}$.\n\n- Turtle wants to \\textbf{maximize} the value of $c_1$ in the end, while Piggy wants to \\textbf{minimize} the value of $c_1$ in the end.\n- $f(c)$ is the value of $c_1$ in the end if both players play optimally.\n\nFor a permutation $p$ of length $n$$^{\\text{∗}}$, Turtle defines the beauty of the permutation as $\\sum\\limits_{i = 1}^n \\sum\\limits_{j = i}^n f([p_i, p_{i + 1}, \\ldots, p_j])$ (i.e., the sum of $f(c)$ where $c$ is a non-empty subsegment$^{\\text{†}}$ of $p$).\n\nPiggy gives Turtle a permutation $a$ of length $n$ where some elements are missing and represented by $0$.\n\nTurtle asks you to determine a permutation $b$ of length $n$ such that:\n\n- $b$ can be formed by filling in the missing elements of $a$ (i.e., for all $1 \\le i \\le n$, if $a_i \\ne 0$, then $b_i = a_i$).\n- The beauty of the permutation $b$ is \\textbf{maximized}.\n\nFor convenience, you only need to find the maximum beauty of such permutation $b$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$A sequence $a$ is a subsegment of a sequence $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "Please read the solution for G1 first. Now, consider the operations we need to perform on the DP array at each step: For all $j$, update $f_{i, j}$ by adding $j \\times \\left(\\left\\lfloor\\frac{n}{2}\\right\\rfloor - (i - j)\\right) + (i - j) \\times \\left(\\left\\lceil\\frac{n}{2}\\right\\rceil - j\\right) = 2j^2 + (-2i - (n \\bmod 2)) j + i \\cdot \\left\\lceil\\frac{n}{2}\\right\\rceil$, which is a quadratic function of $j$; Perform the transition $f_{i + 1, j} = \\min(f_{i + 1, j}, f_{i, j})$; Perform the transition $f_{i + 1, j + 1} = \\min(f_{i + 1, j + 1}, f_{i, j})$. We can inductively prove that $f_{i, j}$ is convex downward, meaning the difference array of $f_i$ is non-decreasing. Instead of maintaining $f_{i, j}$ directly, consider maintaining its difference array $g_{i, j} = f_{i, j + 1} - f_{i, j}$. Then, the operations transform into: For all $j$, add a linear function of $j$ to $g_{i, j}$; Shift $g_{i, j}$ one position to the right; Insert a zero into $g_i$ while keeping it sorted. To efficiently maintain $g_{i, j}$, we use a Treap. Each node in the Treap stores the value of $g_{i, j}$ along with its index $j$, so all operations can be rewritten as linear transformations of $(g_{i, j}, j)$, which can be efficiently handled using vectors and matrices. Time complexity: $O(n \\log n)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst int maxn = 500100;\n\nint n, a[maxn];\nmt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());\n\nint p[maxn], nt, ls[maxn], rs[maxn], sz[maxn];\nbool vis[maxn];\n\nstruct vec {\n\tll a0, a1, a2;\n\tvec(ll a = 0, ll b = 0, ll c = 0) : a0(a), a1(b), a2(c) {}\n} val[maxn];\n\nstruct mat {\n\tll a00, a01, a02, a10, a11, a12, a20, a21, a22;\n\tmat(ll a = 0, ll b = 0, ll c = 0, ll d = 0, ll e = 0, ll f = 0, ll g = 0, ll h = 0, ll i = 0) : a00(a), a01(b), a02(c), a10(d), a11(e), a12(f), a20(g), a21(h), a22(i) {}\n} I, tag[maxn];\n\ninline vec operator * (const vec &a, const mat &b) {\n\tvec res;\n\tres.a0 = a.a0 * b.a00 + a.a1 * b.a10 + a.a2 * b.a20;\n\tres.a1 = a.a0 * b.a01 + a.a1 * b.a11 + a.a2 * b.a21;\n\tres.a2 = a.a0 * b.a02 + a.a1 * b.a12 + a.a2 * b.a22;\n\treturn res;\n}\n\ninline mat operator * (const mat &a, const mat &b) {\n\tmat res;\n\tres.a00 = a.a00 * b.a00 + a.a01 * b.a10 + a.a02 * b.a20;\n\tres.a01 = a.a00 * b.a01 + a.a01 * b.a11 + a.a02 * b.a21;\n\tres.a02 = a.a00 * b.a02 + a.a01 * b.a12 + a.a02 * b.a22;\n\tres.a10 = a.a10 * b.a00 + a.a11 * b.a10 + a.a12 * b.a20;\n\tres.a11 = a.a10 * b.a01 + a.a11 * b.a11 + a.a12 * b.a21;\n\tres.a12 = a.a10 * b.a02 + a.a11 * b.a12 + a.a12 * b.a22;\n\tres.a20 = a.a20 * b.a00 + a.a21 * b.a10 + a.a22 * b.a20;\n\tres.a21 = a.a20 * b.a01 + a.a21 * b.a11 + a.a22 * b.a21;\n\tres.a22 = a.a20 * b.a02 + a.a21 * b.a12 + a.a22 * b.a22;\n\treturn res;\n}\n\ninline void init() {\n\tfor (int i = 0; i <= nt; ++i) {\n\t\tp[i] = ls[i] = rs[i] = sz[i] = 0;\n\t\tval[i] = vec();\n\t\ttag[i] = I;\n\t\tvis[i] = 0;\n\t}\n\tnt = 0;\n}\n\ninline int newnode(ll x, ll y) {\n\tint u = ++nt;\n\tp[u] = rnd();\n\tls[u] = rs[u] = 0;\n\tsz[u] = 1;\n\tval[u] = vec(x, y, 1);\n\ttag[u] = I;\n\tvis[u] = 0;\n\treturn u;\n}\n\ninline void pushup(int x) {\n\tsz[x] = sz[ls[x]] + sz[rs[x]] + 1;\n}\n\ninline void pushtag(int x, const mat &y) {\n\tif (!x) {\n\t\treturn;\n\t}\n\tval[x] = val[x] * y;\n\ttag[x] = tag[x] * y;\n\tvis[x] = 1;\n}\n\ninline void pushdown(int x) {\n\tif (!vis[x]) {\n\t\treturn;\n\t}\n\tpushtag(ls[x], tag[x]);\n\tpushtag(rs[x], tag[x]);\n\tvis[x] = 0;\n\ttag[x] = I;\n}\n\nvoid split(int u, int &x, int &y) {\n\tif (!u) {\n\t\tx = y = 0;\n\t\treturn;\n\t}\n\tpushdown(u);\n\tif (val[u].a0 < 0) {\n\t\tx = u;\n\t\tsplit(rs[u], rs[u], y);\n\t} else {\n\t\ty = u;\n\t\tsplit(ls[u], x, ls[u]);\n\t}\n\tpushup(u);\n}\n\nint merge(int x, int y) {\n\tif (!x || !y) {\n\t\treturn x | y;\n\t}\n\tpushdown(x);\n\tpushdown(y);\n\tif (p[x] < p[y]) {\n\t\trs[x] = merge(rs[x], y);\n\t\tpushup(x);\n\t\treturn x;\n\t} else {\n\t\tls[y] = merge(x, ls[y]);\n\t\tpushup(y);\n\t\treturn y;\n\t}\n}\n\nll f[maxn], tot;\n\nvoid dfs(int u) {\n\tif (!u) {\n\t\treturn;\n\t}\n\tpushdown(u);\n\tdfs(ls[u]);\n\tf[++tot] = val[u].a0;\n\tdfs(rs[u]);\n}\n\nvoid solve() {\n\tcin >> n;\n\tfor (int i = 1; i <= n; ++i) {\n\t\ta[i] = -1;\n\t}\n\tfor (int i = 1, x; i <= n; ++i) {\n\t\tcin >> x;\n\t\tif (x) {\n\t\t\ta[x] = (i & 1);\n\t\t}\n\t}\n\tinit();\n\tint rt = 0;\n\tll l = 0, r = 0, x = 0;\n\tif (a[1] == 1) {\n\t\tl = r = 1;\n\t} else if (a[1] == -1) {\n\t\trt = newnode(0, 1);\n\t\tr = 1;\n\t}\n\tfor (ll i = 1; i < n; ++i) {\n\t\tx += l * l * 2 + (-i - i - (n & 1)) * l + i * ((n + 1) / 2);\n\t\tpushtag(rt, mat(1, 0, 0, 4, 1, 0, -i - i - (n & 1) - 2, 0, 1));\n\t\tif (a[i + 1] == 1) {\n\t\t\tpushtag(rt, mat(1, 0, 0, 0, 1, 0, 0, 1, 1));\n\t\t\t++l;\n\t\t\t++r;\n\t\t} else if (a[i + 1] == -1) {\n\t\t\tint u, v;\n\t\t\tsplit(rt, u, v);\n\t\t\tpushtag(v, mat(1, 0, 0, 0, 1, 0, 0, 1, 1));\n\t\t\trt = merge(merge(u, newnode(0, l + 1 + sz[u])), v);\n\t\t\t++r;\n\t\t}\n\t}\n\ttot = 0;\n\tdfs(rt);\n\tll ans = -x;\n\tfor (int i = 1; i <= (n + 1) / 2 - l; ++i) {\n\t\tans -= f[i];\n\t}\n\tfor (ll i = 1; i <= n; ++i) {\n\t\tans += i * i;\n\t}\n\tcout << ans << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tI.a00 = I.a11 = I.a22 = 1;\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "dp"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2084",
    "index": "H",
    "title": "Turtle and Nediam 2",
    "statement": "\\begin{quote}\nLGR-205-Div.1 C Turtle and Nediam\n\\end{quote}\n\nYou are given a binary sequence $s$ of length $n$ which only consists of $0$ and $1$.\n\nYou can do the following operation \\textbf{at most $n - 2$ times} (possibly zero):\n\n- Let $m$ denote the current length of $s$. Choose an integer $i$ such that $1 \\le i \\le m - 2$.\n- Let the median$^{\\text{∗}}$ of the subarray $[s_i, s_{i + 1}, s_{i + 2}]$ be $x$, and let $j$ be the smallest integer such that $j \\ge i$ and $s_j = x$.\n- Remove $s_j$ from the sequence and concatenate the remaining parts. In other words, replace $s$ with $[s_1, s_2, \\ldots, s_{j - 1}, s_{j + 1}, s_{j + 2}, \\ldots, s_m]$.\n\nNote that after every operation, the length of $s$ decreases by $1$.\n\nFind how many different binary sequences can be obtained after performing the operation, modulo $10^9 + 7$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The median of an array of odd length $k$ is the $\\frac{k + 1}{2}$-th element when sorted.\n\\end{footnotesize}",
    "tutorial": "First, extract the longest contiguous segments in $s$ where the values remain the same. Suppose there are $m$ such segments with lengths $a_1, a_2, \\dots, a_m$. Then, the operations can be described as follows: Choose an index $1 \\leq i \\leq |a|$ such that $a_i \\geq 2$ and decrease $a_i$ by 1. Choose an index $2 \\leq i < |a|$ such that $a_{i-1} = a_i = 1$. Remove $a_{i-1}$. If $i \\geq 3$, then merge $a_{i-2}$ with $a_i$ and remove $a_i$. First handle the corner case when $m \\leq 2$. It can be observed that the length of the last segment never increases, and it is independent of the preceding segments. Thus, we only need to consider the strings that can be generated from $a_1, a_2, \\ldots, a_{m-1}$, and the final answer is multiplied by $a_m$. Now, consider counting the strings that begin with the same character as $s_1$. For a generated sequence of contiguous segments $b_1, b_2, \\dots, b_k$, we greedily find the shortest prefix in $a$ that can generate $b_1, b_2, \\dots, b_k$. Define $f_i$ as the number of strings that can match $a_i$. For the transition when adding a new segment $b_{k+1}$, iterate over indices $j > i$ such that $j \\bmod 2 \\neq i \\bmod 2$. Let $x$ be the maximum value of $b_{k+1}$ that can be generated by the previous $j$. Then, the maximum value that $j$ can generate for $b_{k+1}$ is $\\max(x+1, a_j)$. Thus, if $b_{k+1}$ is matched at position $j$, we have $x < b_{k+1} \\leq \\max(x+1, a_j)$, which gives $\\max(x+1, a_j) - x$ possible values for $b_{k+1}$. Thus, the transition is as follows: The initial values are given by $f_1 = a_1, \\forall i \\geq 3 \\land i \\bmod 2 = 1, f_i = 1$. The final answer is $a_m \\cdot \\sum\\limits_{i = 1}^{m - 1} [(m - i) \\bmod 2 = 1] f_i$. Next, consider counting the strings whose first character is different from $s_1$. It turns out that if the resulting string starts with a different character, then in order to delete the first contiguous segment, the second segment can be at most of length $1$. Therefore, after removing $a_1$ and setting $a_2$ to $1$, we can repeat the above process. Next, we optimize the above $O(m^2)$ DP. Define $\\text{nxt}_i$ as the smallest $j$ such that $j \\bmod 2 = i \\bmod 2 \\land a_j - \\frac{j}{2} > a_i - \\frac{i}{2}$. For a given $i$, the transition works as follows: Maintain a variable $j$ initialized as $j = i + 1$. Perform a special transition at $j$. For $j + 2 \\leq k < \\text{nxt}_j$ such that $k \\bmod 2 = j \\bmod 2$, update $f_k$ by adding $f_i$ (which can be implemented using a difference array). Set $j = \\text{nxt}_j$ and repeat the process. By directly simulating the transition process, it can be shown that the complexity is $O\\left(\\sum a_i\\right) = O(n)$, since each $a_i$ is only jumped to at most $a_i$ times. We can further optimize the DP process to $O(m)$. Define $g_i$ as the sum of $f$-values of all positions that can jump to $i$. Then, the transition is $g_{\\text{nxt}_i} \\gets g_{\\text{nxt}_i} + g_i$. Additionally, for $i + 2 \\leq k < \\text{nxt}_i$ such that $k \\bmod 2 = i \\bmod 2$, update $f_k$ by adding $g_i$, and then perform a special transition for $f_{\\text{nxt}_i}$. Time complexity: $O(n)$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n\nconst int maxn = 2000100;\nconst ll mod = 1000000007;\n\nint n, a[maxn], m, nxt[maxn], stk[maxn], top;\nll f[maxn], g[maxn], d[maxn];\nchar s[maxn];\n\ninline ll calc() {\n\ttop = 0;\n\tfor (int i = m; i >= 1; i -= 2) {\n\t\twhile (top && a[stk[top]] - stk[top] / 2 < a[i] - i / 2) {\n\t\t\t--top;\n\t\t}\n\t\tnxt[i] = stk[top];\n\t\tstk[++top] = i;\n\t}\n\ttop = 0;\n\tfor (int i = m - 1; i >= 1; i -= 2) {\n\t\twhile (top && a[stk[top]] - stk[top] / 2 < a[i] - i / 2) {\n\t\t\t--top;\n\t\t}\n\t\tnxt[i] = stk[top];\n\t\tstk[++top] = i;\n\t}\n\tfor (int i = 1; i < m; ++i) {\n\t\tf[i] = g[i] = d[i] = 0;\n\t}\n\tf[1] = a[1];\n\tfor (int i = 3; i < m; i += 2) {\n\t\tf[i] = 1;\n\t}\n\tll ans = 0;\n\tfor (int i = 1; i < m; ++i) {\n\t\tif (i >= 3) {\n\t\t\td[i] = (d[i] + d[i - 2]) % mod;\n\t\t}\n\t\tf[i] = (f[i] + d[i]) % mod;\n\t\tg[i + 1] = (g[i + 1] + f[i]) % mod;\n\t\tf[i + 1] = (f[i + 1] + f[i] * a[i + 1]) % mod;\n\t\td[i + 2] = (d[i + 2] + g[i]) % mod;\n\t\tif (nxt[i]) {\n\t\t\tg[nxt[i]] = (g[nxt[i]] + g[i]) % mod;\n\t\t\tf[nxt[i]] = (f[nxt[i]] + g[i] * (a[nxt[i]] - a[i] - (nxt[i] - i) / 2 + 1)) % mod;\n\t\t\td[nxt[i]] = (d[nxt[i]] - g[i] + mod) % mod;\n\t\t}\n\t\tif ((m - i) & 1) {\n\t\t\tans = (ans + f[i]) % mod;\n\t\t}\n\t}\n\treturn ans * a[m] % mod;\n}\n\nvoid solve() {\n\tcin >> n >> s;\n\tm = 0;\n\tfor (int i = 0, j = 0; i < n; i = (++j)) {\n\t\twhile (j + 1 < n && s[j + 1] == s[i]) {\n\t\t\t++j;\n\t\t}\n\t\ta[++m] = j - i + 1;\n\t}\n\tif (m == 1) {\n\t\tcout << n - 1 << '\\n';\n\t\treturn;\n\t}\n\tif (m == 2) {\n\t\tcout << 1LL * a[1] * a[2] % mod << '\\n';\n\t\treturn;\n\t}\n\tll ans = calc();\n\t--m;\n\tfor (int i = 1; i <= m; ++i) {\n\t\ta[i] = a[i + 1];\n\t}\n\ta[1] = 1;\n\tans = (ans + calc()) % mod;\n\tcout << ans << '\\n';\n}\n\nint main() {\n\tios::sync_with_stdio(0);\n\tcin.tie(0);\n\tint T;\n\tcin >> T;\n\twhile (T--) {\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2085",
    "index": "A",
    "title": "Serval and String Theory",
    "statement": "A string $r$ consisting only of lowercase Latin letters is called universal if and only if $r$ is lexicographically smaller$^{\\text{∗}}$ than the reversal$^{\\text{†}}$ of $r$.\n\nYou are given a string $s$ consisting of $n$ lowercase Latin letters. You are required to make $s$ universal. To achieve this, you can perform the following operation on $s$ \\textbf{at most} $k$ times:\n\n- Choose two indices $i$ and $j$ ($1\\le i,j\\le n$), then swap $s_i$ and $s_j$. Note that if $i=j$, you do nothing.\n\nDetermine whether you can make $s$ universal by performing the above operation at most $k$ times.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A string $a$ is lexicographically smaller than a string $b$ of the same length, if and only if the following holds:\n\n- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.\n\n$^{\\text{†}}$The reversal of a string $r$ is the string obtained by writing $r$ from right to left. For example, the reversal of the string $abcad$ is $dacba$.\n\\end{footnotesize}",
    "tutorial": "When $s$ is lexicographically equal to or greater than the reversal of $s$, is it possible to make $s$ universal by performing the operations? If possible, what is the minimum number of the operations required to make $s$ universal? Case 1. If $s$ contains only one kind of letter, the answer will be NO. Case 2. If $s$ is universal already, no operation is needed, and the answer will be YES. Otherwise, $s$ falls into the following Case 3. Case 3.1. When $s$ is not a palindrome, one can make $s$ universal in one operation by swapping the first pair of different letters of $s$ and its reversal. $\\left.\\begin{aligned} s ={}& \\texttt{s}{\\color{red}{\\underline{\\texttt{t}}}}\\texttt{rings} \\\\ \\text{reversal of } s ={}& \\texttt{s}{\\color{red}{\\underline{\\texttt{g}}}}\\texttt{nirts} \\end{aligned}\\;\\right\\} \\xrightarrow{\\text{swap}} \\boxed{\\texttt{sgrints}}$ Case 3.2. When $s$ is a palindrome, swapping any two distinct letters will make $s$ no longer a palindrome. Note that the reversal of $s$ after the swap can be obtained by swapping the letters in the symmetric positions of the original $s$. Since either $s$ or its reversal is universal, the original $s$ can be made universal in one operation. $s = \\texttt{l}{\\color{red}{\\underline{\\texttt{e}}}}{\\color{blue}{\\underline{\\texttt{v}}}}\\texttt{el} \\xrightarrow{\\text{swap}} \\left\\{\\;\\begin{aligned} s' ={}& \\texttt{l}{\\color{blue}{\\underline{\\texttt{v}}}}{\\color{red}{\\underline{\\texttt{e}}}}\\texttt{el} \\\\ \\text{reversal of } s' ={}& \\texttt{le}{\\color{red}{\\underline{\\texttt{e}}}}{\\color{blue}{\\underline{\\texttt{v}}}}\\texttt{l} \\end{aligned}\\;\\right\\} \\;\\boxed{\\texttt{leevl}}$ Thus, for Case 3, the answer will be NO if no operation can be performed; otherwise, the answer will be YES.",
    "code": "getint = lambda: int(input())\ngetints = lambda: map(int, input().split())\n\ndef solve():\n\tn, k = getints()\n\ts = input().strip()\n\tif s < s[::-1] or (k >= 1 and min(s) != max(s)):\n\t\tprint('YES')\n\telse:\n\t\tprint('NO')\n\nt = getint()\nfor _ in range(t):\n\tsolve()",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 900
  },
  {
    "contest_id": "2085",
    "index": "B",
    "title": "Serval and Final MEX",
    "statement": "You are given an array $a$ consisting of $n\\ge 4$ non-negative integers.\n\nYou need to perform the following operation on $a$ until its length becomes $1$:\n\n- Select two indices $l$ and $r$ ($1\\le {\\textcolor{red}{ l < r }} \\le |a|$), and replace the subarray $[a_l,a_{l+1},\\ldots,a_r]$ with a single integer $\\operatorname{mex}([a_l,a_{l+1},\\ldots,a_r])$, where $\\operatorname{mex}(b)$ denotes the minimum excluded (MEX)$^{\\text{∗}}$ of the integers in $b$. In other words, let $x=\\operatorname{mex}([a_l,a_{l+1},\\ldots,a_r])$, the array $a$ will become $[a_1,a_2,\\ldots,a_{l-1},x,a_{r+1},a_{r+2},\\ldots,a_{|a|}]$. Note that the length of $a$ decreases by $(r-l)$ after this operation.\n\nServal wants the final element in $a$ to be $0$. Help him!\n\nMore formally, you have to find a sequence of operations, such that after performing these operations in order, the length of $a$ becomes $1$, and the final element in $a$ is $0$.\n\nIt can be shown that at least one valid operation sequence exists under the constraints of the problem, and the length of any valid operation sequence does not exceed $n$.\n\nNote that you do \\textbf{not} need to minimize the number of operations.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The minimum excluded (MEX) of a collection of integers $b_1, b_2, \\ldots, b_k$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $b$.\n\\end{footnotesize}",
    "tutorial": "Before the last operation, what should the array be to obtain $0$? How to make all the elements in the array non-zero? Note that before the last operation, all the integers in the array should be positive. Thus, we aim to turn the zeroes in $a$ into non-zeroes. To achieve this, we split the given array $a$ into two halves and perform the operations on the halves that contain zeroes. After that, there will be no zeroes in either of the two halves. The final $0$ can be obtained by performing the last operation on the entire array. $[{\\color{red}{\\underline{1, 0, 1, 1}}}, {\\color{blue}{2, 0, 8, 5}}] \\to [{\\color{red}{2}}, {\\color{blue}{\\underline{2, 0, 8, 5}}}] \\to [\\underline{{\\color{red}{2}}, {\\color{blue}{1}}}] \\to [0]$ In fact, the final element can be $0$ after the operations for any array of length $4$. Can you solve the problem under the constraint of $n=4$? When $n>4$, you can perform the operation on any subarray of length $(n-3)$. After the operation, the array $a$ will contain only $4$ integers, which can be solved by brute force.",
    "code": "getint = lambda: int(input())\ngetints = lambda: map(int, input().split())\n\ndef solve():\n\tn = getint()\n\ta = list(getints())\n\top = []\n\tmid, r = n // 2, n\n\tif 0 in a[mid:]:\n\t\top.append([mid + 1, n])\n\t\tr -= n - mid - 1\n\tif 0 in a[:mid]:\n\t\top.append([1, mid])\n\t\tr -= mid - 1\n\top.append([1, r])\n\tprint(len(op))\n\tfor o in op:\n\t\tprint(*o)\n\nt = getint()\nfor _ in range(t):\n\tsolve()",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2085",
    "index": "C",
    "title": "Serval and The Formula",
    "statement": "You are given two positive integers $x$ and $y$ ($1\\le x, y\\le 10^9$).\n\nFind a \\textbf{non-negative} integer $k\\le 10^{18}$, such that $(x+k) + (y+k) = (x+k)\\oplus (y+k)$ holds$^{\\text{∗}}$, or determine that such an integer does not exist.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\oplus$ denotes the bitwise XOR operation.\n\\end{footnotesize}",
    "tutorial": "The formula $(x+k) + (y+k) = (x+k) \\oplus (y+k)$ is equivalent to $(x+k) \\mathbin{\\&} (y+k) = 0$, where $\\&$ denotes the bitwise AND operation. Note that a power of $2$ shares no common bits with any positive integer less than it. It can be shown that such an non-negative integer $k$ does not exist when $x=y$. When $x\\neq y$, one can show that $k = 2^n - \\max(x, y)$ is a possible answer, where $2^n$ is a power of $2$ that is sufficiently large.",
    "code": "getint = lambda: int(input())\ngetints = lambda: map(int, input().split())\n\ndef solve():\n\tx, y = getints()\n\tif x == y:\n\t\tprint(-1)\n\telse:\n\t\tprint(2 ** 48 - max(x, y))\n\nt = getint()\nfor _ in range(t):\n\tsolve()",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "dp",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2085",
    "index": "D",
    "title": "Serval and Kaitenzushi Buffet",
    "statement": "Serval has just found a Kaitenzushi buffet restaurant. Kaitenzushi means that there is a conveyor belt in the restaurant, delivering plates of sushi in front of the customer, Serval.\n\nIn this restaurant, each plate contains exactly $k$ pieces of sushi and the $i$-th plate has a deliciousness $d_i$. Serval will have a meal in this restaurant for $n$ minutes, and within the $n$ minutes, he must eat up \\textbf{all} the pieces of sushi he took from the belt.\n\nDenote the counter for uneaten taken pieces of sushi as $r$. Initially, $r=0$. In the $i$-th minute ($1\\leq i\\leq n$), only the $i$-th plate of sushi will be delivered in front of Serval, and he can do \\textbf{one} of the following:\n\n- Take the $i$-th plate of sushi (whose deliciousness is $d_i$) from the belt, and $r$ will be increased by $k$;\n- Eat one uneaten piece of sushi that he took from the belt before, and $r$ will be decreased by $1$. Note that you can do this only if $r>0$;\n- Or, do nothing, and $r$ will remain unchanged.\n\nNote that after the $n$ minutes, the value of $r$ \\textbf{must} be $0$.\n\nServal wants to maximize the sum of the deliciousnesses of all the plates he took. Help him find it out!",
    "tutorial": "Do not go for DP. How many plates of sushi can be taken? What are the constraints on the time of taking plates of sushi? Note that the last $i$-th time taking a plate of sushi should be no later than the $(n - i\\cdot(k+1) + 1)$-th minute. This constraint limits the time that a taking action can be performed. Therefore, we enumerate the $n$ minutes in chronological order, and greedily take the untaken plates delivered before with the greatest deliciousness when we reach a constraint, i.e., the current minute is the $(n - i\\cdot(k+1) + 1)$-th minute for a certain $i$. The deliciousnesses of the untaken plates can be maintained by a heap. The total complexity is $O(n \\log n)$.",
    "code": "#include <cstdio>\n#include <queue>\n\nusing namespace std;\n\nconst int N = 2e5 + 5;\n\nint n, k;\nint d[N];\nlong long ans;\n\nvoid solve() {\n\tscanf(\"%d%d\", &n, &k);\n\tans = 0;\n\tpriority_queue <int> q;\n\tfor (int i = 1; i <= n; i++) {\n\t\tscanf(\"%d\", &d[i]);\n\t\tq.push(d[i]);\n\t\tif ((n - i + 1) % (k + 1) == 0) {\n\t\t\tans += q.top();\n\t\t\tq.pop();\n\t\t}\n\t}\n\tprintf(\"%lld\\n\", ans);\n}\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "graph matchings",
      "greedy"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2085",
    "index": "E",
    "title": "Serval and Modulo",
    "statement": "There is an array $a$ consisting of $n$ non-negative integers and a magic number $k$ ($k\\ge 1$, $k$ is an integer). Serval has constructed another array $b$ of length $n$, where $b_i = a_i \\bmod k$ holds$^{\\text{∗}}$ for all $1\\leq i\\leq n$. Then, he \\textbf{shuffled} $b$.\n\nYou are given the two arrays $a$ and $b$. Find a possible magic number $k$. However, there is a small possibility that Serval fooled you, and such an integer does not exist. In this case, output $-1$.\n\nIt can be shown that, under the constraints of the problem, if such an integer $k$ exists, then there exists a valid answer no more than $10^9$. And you need to guarantee that $k\\le 10^9$ in your output.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$a_i \\bmod k$ denotes the remainder from dividing $a_i$ by $k$.\n\\end{footnotesize}",
    "tutorial": "What happens when an integer $a_i$ mods $k$? Note that the difference between $a_i$ and $b_i$ is a multiple of $k$. The same holds for the difference between the sum of $a_i$ and the sum of $b_i$. Notice that $d(n) \\leq 2304$ holds for all $n \\leq 10^{10}$, where $d(n)$ denotes the number of divisors of $n$. Note that if such a magic number $k$ exists, it will be a divisor of $\\Delta = \\sum a_i - \\sum b_i$ when $\\Delta \\neq 0$, or it can be any integer greater than all the $a_i$. Thus, we can check all the divisors of $\\Delta$, resulting in a solution of $O\\left(\\sum (n \\cdot d(\\sum a_i) + \\sqrt{\\sum a_i})\\right)$ time, where $d(n)$ denotes the number of divisors of $n$.",
    "code": "#include <cstdio>\n\nusing namespace std;\n\nconst int N = 1e4 + 5;\nconst int C = 1e6 + 5;\n\nint n;\nint a[N], b[N];\nint cnt[C];\nlong long s;\n\nbool check(int k) {\n\tfor (int i = 1; i <= n; i++)\n\t\tcnt[a[i] % k]++;\n\tfor (int i = 1; i <= n; i++)\n\t\tif (--cnt[b[i]] < 0) {\n\t\t\tcnt[b[i]] = 0;\n\t\t\tfor (int i = 1; i <= n; i++)\n\t\t\t\tcnt[a[i] % k] = 0;\n\t\t\treturn 0;\n\t\t}\n\treturn 1;\n}\n\nvoid solve() {\n\tscanf(\"%d\", &n);\n\ts = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tscanf(\"%d\", &a[i]);\n\t\ts += a[i];\n\t}\n\tfor (int i = 1; i <= n; i++) {\n\t\tscanf(\"%d\", &b[i]);\n\t\ts -= b[i];\n\t}\n\tif (s == 0) {\n\t\tprintf(\"%d\\n\", check(0xc0ffee) ? 0xc0ffee : -1);\n\t\treturn;\n\t}\n\tfor (int i = 1; 1ll * i * i <= s; i++)\n\t\tif (s % i == 0) {\n\t\t\tif (check(i)) {\n\t\t\t\tprintf(\"%d\\n\", i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (i < C && check(s / i)) {\n\t\t\t\tprintf(\"%d\\n\", (int)(s / i));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\tprintf(\"-1\\n\");\n}\n\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2085",
    "index": "F1",
    "title": "Serval and Colorful Array (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $n\\le 3000$. You can hack only if you solved all versions of this problem.}\n\nServal has a magic number $k$ ($k\\ge 2$). We call an array $r$ colorful if and only if:\n\n- The length of $r$ is $k$, and\n- Each integer between $1$ and $k$ appears \\textbf{exactly once} in $r$.\n\nYou are given an array $a$ consisting of $n$ integers between $1$ and $k$. It is guaranteed that each integer between $1$ and $k$ appears in $a$ at least once. You can perform the following operation on $a$:\n\n- Choose an index $i$ ($1\\le i < n$), then swap $a_i$ and $a_{i+1}$.\n\nFind the minimum number of operations needed to make at least one subarray$^{\\text{∗}}$ of $a$ colorful. It can be shown that this is always possible under the constraints of the problem.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "Consider the integers in the colorful subarray after swapping. How to gather these integers together, forming a colorful subarray, with the minimum number of swaps? Consider the middle one among all the the elements in the colorful subarray. Consider the elements in the colorful subarray after swapping. The first observation is as follows. Observation. Mark the elements in the colorful subarray. Before swapping, to make these marked elements continuous, gathering them toward the middle one among them minimizes the number of swaps. Proof. It is not optimal to swap two marked elements. Thus, the leftmost $x$ elements will move to their right, and the rightmost $(k-x)$ elements will move to their left. They will meet at some point between the $x$-th element and the $(x+1)$-th element. If $x < {k\\over 2}$, adjusting the meeting point to its right reduces $(k-x)-x > 0$ swaps. If $x > {k\\over 2}$, we can adjust it to its left and reduce the number of swaps similarly. Therefore, one can show that setting the meeting point to the middle of them is optimal through adjustments. $\\square$ From the observation we can also conclude that, the minimum number of swaps required to make the marked elements continuous is the difference between the sum of the distances from each marked element to the middle position before swapping and that sum after swapping, if the marked elements are swapped toward the middle position. Notice that the latter sum is a fixed constant only related to $k$. Focusing on the middle position of the colorful subarray, we enumerate all the positions in the array as possible middle positions. For each possible middle position $p$, to form the colorful subarray whose middle position is $p$, we should choose ${k\\over 2}$ distinct integers from its left and the other $k\\over 2$ from its right. The rounding of $k\\over 2$ will not affect the correctness as long as the sum of the rounded numbers is $k$. For each $1\\leq i\\leq k$, we should determine whether $i$ should be chosen from the left side of $p$ or the right side of $p$. Let the distance from $p$ to the rightmost integer $i$ on its left be $l_i$, and the distance for the right side be $r_i$. We should choose either $l_i$ or $r_i$ for each $i$ under the constraint that both the number of chosen $l_i$ and that of $r_i$ are $k\\over 2$, minimizing the sum of the distances we choose. This can be done by first forcing to choose all the $l_i$, and then choosing the smallest $k\\over 2$ elements of $(r_i-l_i)$ greedily. In implementation, when enumerating the middle position $p$, both $l_i$ and $r_i$ can be simply calculated in $O(n)$ time, and then sort $(r_i - l_i)$ in $O(n\\log n)$ time. The total complexity is $O(n^2\\log n)$.",
    "code": "#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 3005;\nconst long long oo = 1e18;\n\nint n, k;\nint a[N], l[N], r[N], d[N];\nlong long ans;\n\nvoid solve() {\n\tscanf(\"%d%d\", &n, &k);\n\tfor (int i = 1; i <= n; i++)\n\t\tscanf(\"%d\", &a[i]);\n\tans = oo;\n\tfor (int i = 1; i <= n; i++) {\n\t\tfor (int j = 1; j <= k; j++)\n\t\t\tl[j] = r[j] = n + 1;\n\t\tfor (int j = i; j; j--)\n\t\t\tl[a[j]] = min(l[a[j]], i - j);\n\t\tfor (int j = i; j <= n; j++)\n\t\t\tr[a[j]] = min(r[a[j]], j - i);\n\t\tlong long s = 0;\n\t\tfor (int j = 1; j <= k; j++) {\n\t\t\ts += l[j];\n\t\t\td[j] = r[j] - l[j];\n\t\t}\n\t\tsort(d + 1, d + k + 1);\n\t\tfor (int j = 1; j <= (k + 1) / 2; j++)\n\t\t\ts += d[j];\n\t\tans = min(ans, s);\n\t}\n\tfor (int i = 1; i <= k; i++)\n\t\tans -= abs(i - (k + 1) / 2);\n\tprintf(\"%lld\\n\", ans);\n}\n\nint main() {\n\tint T;\n\tscanf(\"%d\", &T);\n\twhile (T--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2085",
    "index": "F2",
    "title": "Serval and Colorful Array (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $n\\le 4\\cdot 10^5$. You can hack only if you solved all versions of this problem.}\n\nServal has a magic number $k$ ($k\\ge 2$). We call an array $r$ colorful if and only if:\n\n- The length of $r$ is $k$, and\n- Each integer between $1$ and $k$ appears \\textbf{exactly once} in $r$.\n\nYou are given an array $a$ consisting of $n$ integers between $1$ and $k$. It is guaranteed that each integer between $1$ and $k$ appears in $a$ at least once. You can perform the following operation on $a$:\n\n- Choose an index $i$ ($1\\le i < n$), then swap $a_i$ and $a_{i+1}$.\n\nFind the minimum number of operations needed to make at least one subarray$^{\\text{∗}}$ of $a$ colorful. It can be shown that this is always possible under the constraints of the problem.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "Is it possible to simplify the constraints? Is it possible to remove the constraint that exactly $k\\over 2$ elements should be chosen from both sides of the enumerated position? Optimizing the solution of F1 using (possibly, heavy) data structures results in a $O(n\\log n)$ solution. Here we introduce a linear approach for F2 came up by Error_Yuan. In fact, the following proposition holds. Proposition. The answer obtained is still correct without the constraint that exactly $k\\over 2$ elements should be chosen from both sides of the enumerated position. Without the constraint, when enumerating the position $p$, we can directly choose the smaller one between $l_i$ and $r_i$ for each $1\\leq i\\leq k$. Proof. On the one hand, notice that the distance sum will not be smaller when $p$ is not the middle position among the chosen elements. On the other hand, consider the colorful subarray that produces the optimal answer, and mark the elements in it first. When $p$ enumerates to the middle position of the marked elements before swapping, the minimal distance sum without the constraint is no greater than that under the constraint. Therefore, all the considered candidates are no less than the real answer, and the real answer can be reached, completing the proof. $\\square$ In implementation, we consider the contribution to each position $p$ for each integer $1\\leq i\\leq k$. For a certain $i$, it can be shown that the delta of the contribution will be one of $-1$, $0$, or $+1$ when $p$ moves to an adjacent position. The delta of the contribution remains unchanged for most positions, and only changes either at the position where $i$ placed, or at the midpoint between two adjacent $i$. By pre-calculating the changes of contribution deltas over all the $i$ and performing the prefix sum on the array twice, we can obtain the distance sums, resulting in an $O(n)$ solution.",
    "code": "#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nconst int N = 4e5 + 5;\nconst long long oo = 1e18;\n\nint n, k;\nint a[N];\nint last[N], dd[N];\nlong long s, d, ans;\n\nvoid solve() {\n\tscanf(\"%d%d\", &n, &k);\n\tfor (int i = 1; i <= n; i++)\n\t\tlast[i] = dd[i] = 0;\n\ts = 0;\n\tfor (int i = 1; i <= n; i++) {\n\t\tscanf(\"%d\", &a[i]);\n\t\tif (!last[a[i]])\n\t\t\ts += i - 1;\n\t\telse {\n\t\t\tint pre = last[a[i]];\n\t\t\tint mid = (pre + i) / 2;\n\t\t\tif ((pre + i) & 1) {\n\t\t\t\tdd[mid]--;\n\t\t\t\tdd[mid + 1]--;\n\t\t\t} else\n\t\t\t\tdd[mid] -= 2;\n\t\t}\n\t\tdd[i] += 2;\n\t\tlast[a[i]] = i;\n\t}\n\tans = oo;\n\td = -k;\n\tfor (int i = 1; i <= n; i++) {\n\t\tans = min(ans, s);\n\t\td += dd[i];\n\t\ts += d;\n\t}\n\tfor (int i = 1; i <= k; i++)\n\t\tans -= abs(i - (k + 1) / 2);\n\tprintf(\"%lld\\n\", ans);\n}\n\nint main() {\n\tint T;\n\tscanf(\"%d\", &T);\n\twhile (T--)\n\t\tsolve();\n\treturn 0;\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2086",
    "index": "A",
    "title": "Cloudberry Jam",
    "statement": "The most valuable berry of the Karelian forests is cloudberry. To make jam from cloudberries, you take equal amounts of berries and sugar and cook them. Thus, if you have $2$ kg of berries, you need $2$ kg of sugar. However, from $2$ kg of berries and $2$ kg of sugar, you will not get $4$ kg of jam, as one might expect, but only $3$ kg, since some of the jam evaporates during cooking. Specifically, during standard cooking, exactly a quarter (or $25\\%$) of the jam evaporates.\n\nHow many kilograms of cloudberries are needed to prepare $n$ $3$-kilogram jars of jam?",
    "tutorial": "As stated in the problem, to prepare one $3$kg jar of jam, $2$ kg of berries are required; therefore, to prepare $n$ jars, you need to take $2 \\cdot n$ kg of cloudberries.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \nint main(){\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        cout << n * 2 << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2086",
    "index": "B",
    "title": "Large Array and Segments",
    "statement": "There is an array $a$ consisting of $n$ \\textbf{positive} integers, and a positive integer $k$. An array $b$ is created from array $a$ according to the following rules:\n\n- $b$ contains $n \\cdot k$ numbers;\n- the first $n$ numbers of array $b$ are the same as the numbers of array $a$, that is, $b_{i} = a_{i}$ for $i \\le n$;\n- for any $i > n$, it holds that $b_{i} = b_{i - n}$.\n\nFor example, if $a = [2, 3, 1, 4]$ and $k = 3$, then $b = [2, 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4]$.\n\nGiven a number $x$, it is required to count the number of such positions $l$ ($1 \\le l \\le n \\cdot k$), for which there exists a position $r \\ge l$, such that the sum of the elements of array $b$ on the segment $[l, r]$ is \\textbf{at least} $x$ (in other words, $b_{l} + b_{l+1} + \\dots + b_{r} \\ge x$).",
    "tutorial": "In this problem, the array $b$ is obtained by copying the array $a$ exactly $k$ times. Notice that all elements of the array $a$ are positive; therefore, the elements of the array $b$ are also positive. From this, we can conclude that the optimal $r$ for any $l$ that maximizes the sum over the segment [$l, r$] is always equal to $n \\cdot k$. It also follows that the maximum sum for $l$ is less than the maximum sum for $l - 1$. The condition of monotonicity holds, so we can perform a binary search to find the first such $l$ for which the maximum sum is $< x$. How do we write a check for such a binary search? Given a position $m$, we need to calculate the maximum sum for it. To do this, we find how many \"full arrays $a$\" fit into the suffix $[m, n \\cdot k]$: there are $\\lfloor \\frac{n \\cdot k - m + 1}{n} \\rfloor$ of them. In addition to this, there are $suff = (n \\cdot k - m + 1) \\bmod n$ elements from the suffix of the array $a$ on this segment, so the total sum of the elements of the array $b$ over the segment [$m, n \\cdot k$] can be found using the formula: $\\lfloor \\frac{n \\cdot k - m + 1}{n} \\rfloor \\cdot \\sum_{i=1}^{n} a_{i} + \\sum_{i = n - suff + 1}^{n} a_{i}$ At this point, we can write a solution that works in $O(n \\cdot (\\log n + \\log k))$. If we pre-calculate all suffix sums for the array $a$, then the formula above can be calculated in $O(1)$, so the solution can be optimized to $O(n + \\log k)$. There are also other solutions with $O(n + k)$ complexity that also get Accepted.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nvoid solve(){\n    int n, k, x;\n    cin >> n >> k >> x;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++){\n        cin >> a[i];\n    }\n\n    if (accumulate(a.begin(), a.end(), 0ll) * k < x){\n        cout << 0 << '\\n';\n        return;\n    }\n\n    int l = 1, r = n * k;\n    while(l <= r){\n        int m = l + (r - l) / 2;\n        int cnt_a = (n * k - m + 1) / n;\n        int suff = (n * k - m + 1) % n;\n        int sum = cnt_a * accumulate(a.begin(), a.end(), 0ll);\n        for (int i = n - suff; i < n; i++){\n            sum += a[i];\n        }\n        if (sum < x){\n            r = m - 1;\n        }\n        else{\n            l = m + 1;\n        }\n    }\n\n    cout << r << '\\n';\n}\n \nsigned main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\t\n\tint t;\n\tcin >> t;\n\twhile(t--){\n\t    solve();\n\t}\n}",
    "tags": [
      "binary search",
      "brute force",
      "greedy"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2086",
    "index": "C",
    "title": "Disappearing Permutation",
    "statement": "A permutation of integers from $1$ to $n$ is an array of size $n$ where each integer from $1$ to $n$ appears exactly once.\n\nYou are given a permutation $p$ of integers from $1$ to $n$. You have to process $n$ queries. During the $i$-th query, you replace $p_{d_i}$ with $0$. Each element is replaced with $0$ exactly once. The changes made in the queries are saved, that is, after the $i$-th query, all integers $p_{d_1}, p_{d_2}, \\dots, p_{d_i}$ are zeroes.\n\nAfter each query, you have to find the minimum number of operations required to fix the array; in other words, to transform the current array into any permutation of integers from $1$ to $n$ (possibly into the original permutation $p$, possibly into some other permutation).\n\nThe operation you can perform to fix the array is the following one:\n\n- choose the integer $i$ from $1$ to $n$, replace the $i$-th element of the array \\textbf{with $i$}.\n\nNote that the answer for each query is calculated independently, meaning you do not actually apply any operations, just calculate the minimum number of operations.",
    "tutorial": "Let's take a closer look at how the fixing the array operation works: Suppose we have a missing number $p_{d_{i}}$, we know that the final permutation must contain this number, and the only place we can put the number $p_{d_{i}}$ is position $p_{d_{i}}$. However, if we place the number there, we might lose $p_{p_{d_{i}}}$, which also needs to be placed in the final permutation, and the only place we can put it is position $p_{p_{d_{i}}}$, but we might again lose some number, and so on. This process will end when we place a number in the position of an already missing number. This process can be implemented either recursively or iteratively, and we are only interested in the set of positions we need to fix. Let's denote the set of all positions to be fixed as $X$. Then we can observe the following: if the current query $d_{i}$ is contained in $X$, then the union of the sets of fixable positions for $d_{i}$ and $X$ is equal to $X$. If the query $d_{i}$ is not contained in $X$, then it adds some positions to the set $X$. Based on this observation, we can write a solution. I will outline the main points of the solution: we maintain the set $X$; when the query comes with $d_{i}$ that is contained in $X$, we do nothing and simply output the size of the set $X$; when the query comes with $d_{i}$ that is not contained in $X$, then we add all the positions that are necessary to fix the array if $d_{i}$ is missing, and output the size of the set $X$. The final implementation may have a complexity of $O(n)$ or $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nvoid solve(){\n    int n;\n    cin >> n;\n    vector<int> p(n);\n    for (int i = 0; i < n; i++){\n        cin >> p[i];\n        p[i]--;\n    }\n\n    set<int> X;\n    for (int i = 0; i < n; i++){\n        int d;\n        cin >> d;\n        d--;\n        while(!X.contains(d)){\n            X.insert(d);\n            d = p[d];\n        }\n        cout << X.size() << ' ';\n    } \n    cout << endl;\n}\n \nsigned main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n\n\tint t;\n\tcin >> t;\n\twhile(t--){\n\t    solve();\n\t}\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2086",
    "index": "D",
    "title": "Even String",
    "statement": "You would like to construct a string $s$, consisting of lowercase Latin letters, such that the following condition holds:\n\n- For every pair of indices $i$ and $j$ such that $s_{i} = s_{j}$, the difference of these indices is even, that is, $|i - j| \\bmod 2 = 0$.\n\nConstructing any string is too easy, so you will be given an array $c$ of $26$ numbers — the required number of occurrences of each individual letter in the string $s$. So, for every $i \\in [1, 26]$, the $i$-th letter of the Latin alphabet should occur exactly $c_i$ times.\n\nYour task is to count the number of distinct strings $s$ that satisfy all these conditions. Since the answer can be huge, output it modulo $998\\,244\\,353$.",
    "tutorial": "From the statement, it follows that all identical letters in $s$ must be positioned either at even indices or at odd indices simultaneously. Let's examine how the ways to construct the string $s$ are formed: A subset of letters that we take for the odd positions (the remaining letters will be at the even positions); The number of ways to create a string with a fixed subset of letters at the odd positions. Let $S$ denote the sum of the array $c$. We also denote $odd = \\lceil\\frac{S}{2}\\rceil$ as the number of odd positions, and $even = \\lfloor\\frac{S}{2}\\rfloor$ as the number of even positions. For now, let's ignore the second point and calculate how many ways there are to distribute the letters such that we can create at least one suitable string $s$. That is, we need to count the number of ways to choose a set of letters that will occupy the odd positions. This resembles a modification of the classical knapsack problem, which can be solved using dynamic programming. Let $\\text{dp}[i]$ denote the number of ways to take a subset of letters such that the number of letters taken equals $i$. The base case of the dynamic programming is $\\text{dp}[i] = 0$, and the entire dynamic can be computed using two nested loops: The number we're interested in will be in $\\text{dp}[odd]$. Now we need to understand what to do with point $2$. Notice that if we have fixed a subset of letters $X$ at the odd positions, then the number of ways to create the string is equal to the product of the multinomial coefficients: $\\frac{odd!}{\\prod_{i \\in X} c_{i}!} \\cdot \\frac{even!}{\\prod_{i \\notin X} c_{i}!}$ Notice that this product is a constant, meaning it does not depend on the specific subset $X$: $\\frac{odd! \\cdot even!}{\\prod_{i = 0}^{26} c_{i}!}$ Thus, the answer to the entire problem is simply the product: $\\frac{odd! \\cdot even!}{\\prod_{i = 0}^{26} c_{i}!} \\cdot \\text{dp}[odd]$ The total complexity complexity is $O(S \\cdot 26)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n#define int long long\n \nconst int MOD = 998'244'353;\n \nint bpow(int x, int p){\n\tint res = 1;\n\twhile(p){\n\t\tif (p % 2){\n\t\t\tres = (res * x) % MOD;\n\t\t}\n\t\tp >>= 1;\n\t\tx = (x * x) % MOD;\n\t}\n\treturn res;\n}\n \nint fact(int x){\n\tint res = 1;\n\tfor (int i = 1; i <= x; i++){\n\t\tres = (res * i) % MOD;\n\t}\n\treturn res;\n}\n \nvoid solve(){\n\tvector<int> c(26);\n\tfor (int i = 0; i < 26; i++){\n\t\tcin >> c[i];\n\t}\n \n\tint s = accumulate(c.begin(), c.end(), 0ll);\n\t\n\tvector<int> dp(s + 1);\n\tdp[0] = 1;\n \n\tfor (int i = 0; i < 26; i++){\n\t\tif (c[i] == 0){\n\t\t\tcontinue;\n\t\t}\n\t\tfor (int j = s; j >= 0; j--){\n\t\t\tif (j + c[i] <= s){\n\t\t\t\tdp[j + c[i]] = (dp[j + c[i]] + dp[j]) % MOD;\n\t\t\t}\n\t\t}\n\t}\n \n\tint ans = dp[s / 2] * fact(s / 2) % MOD * fact((s + 1) / 2) % MOD;\n\tfor (int i = 0; i < 26; i++){\n\t\tans = (ans * bpow(fact(c[i]), MOD - 2)) % MOD;\n\t}\n \n\tcout << ans << '\\n';\n}\n \nsigned main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n \n    int t;\n    cin >> t;\n    while(t--){\n        solve();\n    }\n}",
    "tags": [
      "brute force",
      "combinatorics",
      "dp",
      "math",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2086",
    "index": "E",
    "title": "Zebra-like Numbers",
    "statement": "We call a positive integer zebra-like if its binary representation has alternating bits up to the most significant bit, and the least significant bit is equal to $1$. For example, the numbers $1$, $5$, and $21$ are zebra-like, as their binary representations $1$, $101$, and $10101$ meet the requirements, while the number $10$ is not zebra-like, as the least significant bit of its binary representation $1010$ is $0$.\n\nWe define the zebra value of a positive integer $e$ as the minimum integer $p$ such that $e$ can be expressed as the sum of $p$ zebra-like numbers (possibly the same, possibly different)\n\nGiven three integers $l$, $r$, and $k$, calculate the number of integers $x$ such that $l \\le x \\le r$ and the zebra value of $x$ equals $k$.",
    "tutorial": "First, let's see how many zebra-Like numbers less than or equal to $10^{18}$ exist. It turns out there are only $30$ of them, and based on some zebra-like number $z_{i}$, the next one can be calculated using the formula $z_{i + 1} = 4 \\cdot z_{i} + 1$. Then, we have to be able to quickly calculate the zebra value for an arbitrary number $x$. Since each subsequent zebra-like number is approximately $4$ times larger than the previous one, intuitively, it seems like a greedy algorithm should be optimal: for any number $x$, we can determine its zebra value by subtracting the largest zebra-like number that does not exceed $x$, until $x$ becomes $0$. Let's prove the correctness of the greedy algorithm: Assume that $y$ is the smallest number for which the greedy algorithm does not work, meaning that in the optimal decomposition of $y$ into zebra-like numbers, the largest zebra-like number $z_{i}$ that does not exceed $y$ does not appear at all. If the greedy algorithm works for all numbers less than $y$, then in the decomposition of the number $y$, there must be at least one number $z_{i - 1}$. And since $y - z_{i - 1}$ can be decomposed greedily and will contain at least $3$ numbers $z_{i - 1}$, we will end up with at least $4$ numbers $z_{i - 1}$ in the decomposition. Moreover, there will be at least $5$ numbers in the decomposition because $4 \\cdot z_{i - 1} < z_{i}$, which means it is also less than $y$. Therefore, if the fifth number is $1$, we simply combine $4 \\cdot z_{i - 1}$ with $1$ to obtain $z_{i}$; otherwise, we decompose the fifth number into $4$ smaller numbers plus $1$, and we also combine this $1$ with $4 \\cdot z_{i - 1}$ to get $z_{i}$. Thus, the new decomposition of the number $y$ into zebra-like numbers will have no more numbers than the old one, but it will include the number $z_i$ - the maximum zebra-like number that does not exceed $y$. This means that $y$ can be decomposed greedily. We have reached a contradiction; therefore, the greedy algorithm works for any positive number. Now, let's express the greedy decomposition of the number $x$ in a more convenient form. We will represent the decomposition as a string $s$ of length $30$ consisting of digits, where the $i$-th character will denote how many zebra numbers $z_{i}$ are present in this decomposition. Let's take a closer look at what such a string might look like: $s_{i} \\in \\{0, 1, 2, 3, 4\\}$; if $s_{i} = 4$, then for any $j < i$, the character $s_{j} = 0$ (this follows from the proof of the greedy algorithm). Moreover, any number generates a unique string of this form. This is very similar to representing a number in a new numeric system, which we will call zebroid. In summary, the problem has been reduced to counting the number of numbers in the interval $[l, r]$ such that the sum of the digits in the zebroid numeral system equals $x$. This is a standard problem that can be solved using dynamic programming on digits. Instead of counting the suitable numbers in the interval $[l, r]$, we will count the suitable numbers in the intervals $[1, l]$ and $[1, r]$ and subtract the first from the second to get the answer. Let $\\text{dp}[\\text{ind}][\\text{sum}][\\text{num_less_m}][\\text{was_4}]$ be the number of numbers in the interval $[1, m]$ such that: they have $\\text{ind} + 1$ digits; the sum of the digits equals $\\text{sum}$; $\\text{num_less_m} = 0$ if the prefix of $\\text{ind} + 1$ digits of the number $m$ is lexicographically greater than these numbers, otherwise $\\text{num_less_m} = 1$; $\\text{was_4} = 0$ if there has not been a $4$ in the $\\text{ind} + 1$ digits of these numbers yet, otherwise $\\text{was_4} = 1$. Transitions in this dynamic programming are not very difficult - they are basically appending a new digit at the end. The complexity of the solution is $O(\\log^2 A)$, if we estimate the number of zebra-like numbers up to $A = 10^{18}$ as $\\log A$. Alternative solution (BledDest) First, let's prove that we can decompose numbers into zebra-like numbers greedily, constantly subtracting the maximum zebra-like number we can (the proof is the same as in the first solution). After that, we will learn to calculate the following dynamic programming: $dp_{i,j}$ - the number of numbers from $0$ to $i-1$ with a zebra value of exactly $j$. The base states of the dynamic programming will be as follows: $dp_{0,x} = 0$ (since there are no numbers in the interval); $dp_{1,0} = 1$ (since the number $0$ has a zebra value of $0$); $dp_{1,i} = 0$ for $i \\ne 0$ (similarly); $dp_{i,j} = 0$ for $i < 0$ (numbers cannot have negative zebra value). Additionally, the same can be done for $j$ greater than the number of zebra-like numbers multiplied by $4$ (since there cannot be more than $4$ identical zebra-like numbers in the decomposition of a number). Okay, now let's consider the transitions in this dynamic programming. Suppose we want to calculate $dp_{i,j}$. We find the largest zebra-like number $k$ that is less than $i$. Then for all numbers from $k$ to $i-1$, the maximum zebra number in the decomposition is $k$, and if we subtract it from them, we get the interval of numbers from $0$ to $i-k-1$. Therefore, $dp_{i,j} = dp_{k,j} + dp_{i-k,j-1}$. Intuitively, it seems that there are not many states in this dynamic programming, so it can be calculated \"lazily\", and we can store all already computed values in a map. But let's prove this. $j$ will be on the order of $\\log A$, so let's estimate the number of different values of $i$ that we will need. We will divide them into two categories - zebra-like numbers $i$ and all others. If $i$ is a zebra-like number, then the previous zebra number is $k = \\frac{i - 1}{4}$. Therefore, $dp_{i,j} = dp_{k,j} + dp_{i-k,j-1} = \\dots = dp_{k,j} + dp_{k,j-1} + dp_{k,j-2} + dp_{k,j-3} + dp_{1,j-4}$. Thus, the states where $i$ is a zebra-like number generate $O(1)$ new states, and in total, the states where $i$ is zebra-like and the states generated by them will require only $O(\\log A)$ different values of $i$. If $i$ is not a zebra-like number, one of the transitions leads to a state with a zebra-like number, and the other does not. That is, from each state, there is a \"chain\" of states with values of $i$ that are not zebra-like numbers, and the length of such a chain is $O(\\log A)$ (since every $O(1)$ steps in the chain effectively take $i$ modulo some zebra-like number), so there will be a total of $O(\\log A)$ values of $i$ that are not zebra numbers. Thus, the total number of states in the dynamic programming will be $O(\\log^2 A)$, so the entire solution will work in $O(\\log^2 A \\log \\log A)$ for each test case.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvector<long long> z;\n \nvoid precalc()\n{\n    z = {1ll};\n    while(z.back() < 1e18)\n        z.push_back(4 * z.back() + 1);\n}\n \nmap<pair<long long, long long>, long long> dp;\n \nlong long get(long long r, long long x)\n{\n    if(dp.count(make_pair(r, x))) return dp[make_pair(r, x)];\n    long long& d = dp[make_pair(r, x)];\n    if(x > 4 * z.size()) return d = 0;\n    if(x < 0) return d = 0;\n    if(r == 0) return d = 0;\n    if(r == 1)\n    {\n        if(x == 0) return d = 1;\n        return d = 0;\n    }\n    auto it = lower_bound(z.begin(), z.end(), r);\n    --it;\n    long long y = *it;\n    return d = get(y, x) + get(r - y, x - 1);\n}\n \nint main() \n{\n    precalc();\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        long long l, r, x;\n        cin >> l >> r >> x;\n        cout << get(r + 1, x) - get(l, x) << endl;\n    }\n}",
    "tags": [
      "bitmasks",
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2086",
    "index": "F",
    "title": "Online Palindrome",
    "statement": "This is an interactive problem.\n\nThe jury has a string $s$ consisting of lowercase Latin letters. The following constraints apply to this string:\n\n- the string has an odd length that does not exceed $99$;\n- the string consists only of the characters \"a\" and \"b\".\n\nThere is also a string $t$, which is initially empty. Then, $|s|$ steps happen. During the $i$-th step, the following events occur:\n\n- first, the jury tells you the character $s_i$ and appends it to the end of the string $t$;\n- then, you may swap any two characters in $t$, or do nothing.\n\nYour task is to ensure that after the $|s|$-th step, the string $t$ is a palindrome.",
    "tutorial": "From the problem statement, it can be understood that at each step, when we have an odd number of characters, the string $t$ must be a palindrome, since the length of the string $s$ is not provided. Therefore, we need to come up with a strategy for swaps to ensure this condition is met. The first thought is to try a brute-force approach of the following kind: When the current step is odd (i.e., $|t| \\bmod 2 = 1$), let's obtain the next character $s_{i}$, add it to the end of $t$, and perform some swap. After this, two conditions must be satisfied: if we then add the character \"a\", the string $t$ can be turned into a palindrome with no more than one swap; if we then add the character \"b\", the string $t$ can be turned into a palindrome with no more than one swap. If the step is even, let's obtain the next character $s_{i}$, add it to the end of $t$, and perform a swap so that $t$ becomes a palindrome. If we try to submit this solution, we will get WA, as there can be situations where both conditions for the odd step are not satisfied simultaneously. This is due to the fact that we allow the construction of any palindromes. Based on this, we conclude that any palindrome is not suitable for us, and we need to maintain some template palindrome. The most challenging part of this problem is to find such a template. Next, I will describe how the template should look: if there is more than one letter \"a\", then we place the letter \"a\" as the first and last character; if there is more than one letter \"b\", then we place the letter \"b\" as the second and second-to-last character; if there is more than one letter \"a\", then we place the letter \"a\" as the third and third-to-last character; we alternate this way while possible; then we fill all paired positions with the letter that has more than one left; the center is filled unambiguously. All palindromes that start with the letter \"b\" and have the same form are also suitable for us. For example, the following strings fit the template: \"a\"; \"bab\"; \"abbabba\"; \"abababaaaaabababa\"; For this template, there are transitions (i.e., swaps such that from a template of length $x$ we can transition to a template of length $x + 2$ by adding any possible pair of characters), however, deriving them manually is quite complicated, as there are many situations. However, this can be added to our brute-force approach for the odd step. Once again, here's how it will look: obtain the next character from the input; iterate through a pair of characters in the string that we want to swap; for each iterated pair, consider two variants of the second incoming character. Check if we can obtain the expected template from the current string with no more than one swap; this can be checked unambiguously with a linear pass through the string and the expected template, looking at the differing positions; if for the checked permutation we can transition to the template with any next letter, then we perform that permutation. For the even step, we can simply find the necessary swap in a linear manner. Thus, the asymptotic complexity of this solution is $O(|s|^{4})$. As an appendix, I will list examples of transitions by pairs of characters in the template: \"aaa\" + \"aa\" $\\to$ \"aaaaa\"; \"aaa\" + \"ab\" $\\to$ \"aabaa\"; \"aaa\" + \"bb\" $\\to$ \"ababa\"; \"bab\" + \"aa\" $\\to$ \"ababa\"; \"bab\" + \"ab\" $\\to$ \"abbba\"; \"bab\" + \"bb\" $\\to$ \"bbabb\"; \"ababa\" + \"aa\" $\\to$ \"abaaaba\"; \"ababa\" + \"ab\" $\\to$ \"abababa\"; \"ababa\" + \"bb\" $\\to$ \"abbabba\"; \"abbba\" + \"aa\" $\\to$ \"abababa\"; \"abbba\" + \"ab\" $\\to$ \"abbabba\"; \"abbba\" + \"bb\" $\\to$ \"abbbbba\"; \"bbabb\" + \"aa\" $\\to$ \"abbabba\"; \"bbabb\" + \"ab\" $\\to$ \"abbbbba\"; \"bbabb\" + \"bb\" $\\to$ \"bbbabbb\"; \"ababbbbbbbaba\" + \"aa\" $\\to$ \"abababbbbbababa\"; \"ababbbbbbbaba\" + \"ab\" $\\to$ \"ababbbbabbbbaba\"; \"ababbbbbbbaba\" + \"bb\" $\\to$ \"ababbbbbbbbbaba\"; \"ababbbabbbaba\" + \"aa\" $\\to$ \"abababbabbababa\"; \"ababbbabbbaba\" + \"ab\" $\\to$ \"abababbbbbababa\"; \"ababbbabbbaba\" + \"bb\" $\\to$ \"ababbbbabbbbaba\"; \"ababaaaaababa\" + \"aa\" $\\to$ \"ababaaaaaaababa\"; \"ababaaaaababa\" + \"ab\" $\\to$ \"ababaaabaaababa\"; \"ababaaaaababa\" + \"bb\" $\\to$ \"abababaaabababa\"; \"ababaabaababa\" + \"aa\" $\\to$ \"ababaaabaaababa\"; \"ababaabaababa\" + \"ab\" $\\to$ \"abababaaabababa\"; \"ababaabaababa\" + \"bb\" $\\to$ \"abababababababa\";",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\n#define forn(i, n) for(int i = 0; i < int(n); i++) \nconst int N = 100;\n \nbool dp[N][N];\npair<int, int> nxt[N][N][2];\nbitset<N> cur;\nbitset<N> form[N][N];\n \nint main(){\n\tforn(i, N) forn(j, N) dp[i][j] = (i + j) % 2;\n\tfor (int len = 1; len < N; len += 2){\n\t\tforn(x, len + 1){\n\t\t\tint y = len - x;\n\t\t\tint nx = x, ny = y;\n\t\t\tint i = 0;\n\t\t\twhile (nx > 1 || ny > 1){\n\t\t\t\tif (nx > 1){\n\t\t\t\t\tnx -= 2;\n\t\t\t\t\t++i;\n\t\t\t\t}\n\t\t\t\tif (ny > 1){\n\t\t\t\t\tform[x][y][i] = form[x][y][len - i - 1] = 1;\n\t\t\t\t\tny -= 2;\n\t\t\t\t\t++i;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (ny > 0){\n\t\t\t\tform[x][y][i] = 1;\n\t\t\t}\n\t\t}\n\t}\n\tfor (int len = N - 3; len >= 1; len -= 2){\n\t\tforn(x, len + 1){\n\t\t\tint y = len - x;\n\t\t\tcur = form[x][y];\n\t\t\tforn(c, 2){\n\t\t\t\tcur[len] = c;\n\t\t\t\tbool found = false;\n\t\t\t\tforn(l, len + 1){\n\t\t\t\t\tforn(r, l + 1){\n\t\t\t\t\t\tif (cur[l] != cur[r]) cur[l].flip(), cur[r].flip();\n\t\t\t\t\t\tbool ok = true;\n\t\t\t\t\t\tforn(d, 2){\n\t\t\t\t\t\t\tcur[len + 1] = d;\n\t\t\t\t\t\t\tint nx = x + (c == 0) + (d == 0);\n\t\t\t\t\t\t\tint ny = y + (c == 1) + (d == 1);\n\t\t\t\t\t\t\tif ((cur ^ form[nx][ny]).count() > 2){\n\t\t\t\t\t\t\t\tok = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (ok){\n\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\tnxt[x][y][c] = {l, r};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (cur[l] != cur[r]) cur[l].flip(), cur[r].flip();\n\t\t\t\t\t\tif (found) break;\n\t\t\t\t\t}\n\t\t\t\t\tif (found) break;\n\t\t\t\t}\n\t\t\t\tif (!found){\n\t\t\t\t\tdp[x][y] = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tstring s;\n\tcur.reset();\n\tfor (int i = 0;; ++i){\n\t\tcin >> s;\n\t\tif (s == \"0\") break;\n\t\tint c = s[0] - 'a';\n\t\tint py = cur.count(), px = i - py;\n\t\tcur[i] = c;\n\t\tint nx = px + (c == 0), ny = py + (c == 1);\n\t\tint l = -1, r = -1;\n\t\tif (i % 2 == 1){\n\t\t\tauto res = nxt[px][py][c];\n\t\t\tif (res.first != res.second){\n\t\t\t\tl = res.first;\n\t\t\t\tr = res.second;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tassert(dp[nx][ny]);\n\t\t\tbitset<N> dif = cur ^ form[nx][ny];\n\t\t\tassert(dif.count() <= 2);\n\t\t\tif (dif.count() == 2){\n\t\t\t\tl = dif._Find_first();\n\t\t\t\tr = dif._Find_next(l);\n\t\t\t}\n\t\t}\n\t\tif (l == -1){\n\t\t\tcout << 0 << \" \" << 0 << endl;\n\t\t}\n\t\telse{\n\t\t\tcout << l + 1 << \" \" << r + 1 << endl;\n\t\t\tif (cur[l] != cur[r]) cur[l].flip(), cur[r].flip();\n\t\t}\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2089",
    "index": "A",
    "title": "Simple Permutation",
    "statement": "Given an integer $n$. Construct a permutation $p_1, p_2, \\ldots, p_n$ of length $n$ that satisfies the following property:\n\nFor $1 \\le i \\le n$, define $c_i = \\lceil \\frac{p_1+p_2+\\ldots +p_i}{i} \\rceil$, then among $c_1,c_2,\\ldots,c_n$ there must be at least $\\lfloor \\frac{n}{3} \\rfloor - 1$ prime numbers.",
    "tutorial": "Lemma (Bertrand's postulate): For each positive integer $x$, there is a prime $p$ inside the interval $[x,2x]$. Find a prime number $p$ between $\\lfloor \\frac{n}{3} \\rfloor$ and $\\lceil \\frac{2n}{3} \\rceil$, and construct the permutation in an alternating way: $p, p-1, p+1, p-2, p+2, \\dots$. Place the remaining numbers arbitrarily. In this construction, we have $c_1 = c_3 = c_5 = \\dots = c_{2 \\lfloor \\frac{n}{3} \\rfloor - 1} = p$, which meets the requirement with at least $\\lfloor \\frac{n}{3} \\rfloor$ numbers being prime. 2089B1 - Canteen (Easy Version) Idea: Ecrade_",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\nbool isPrime(int x){\n\tif(x <= 1)\n\t\treturn 0;\n\tfor(int i = 2 ; i * i <= x ; ++i)\n\t\tif(x % i == 0)\n\t\t\treturn 0;\n\treturn 1;\n}\n\nvector<int> generateSol(int n, int p){\n\tvector<int> ans;\n\tans.push_back(p);\n\tfor(int i = 1 ; i <= n ; ++i){\n\t\tif(p - i > 0)\n\t\t\tans.push_back(p - i);\n\t\tif(p + i <= n)\n\t\t\tans.push_back(p + i);\n\t}\n\treturn ans;\n}\n\nint main(){\n\tint t;\n\tcin >> t;\n\tfor(int i = 1 ; i <= t ; ++i){\n\t\tint n;\n\t\tcin >> n;\n\t\tvector < int > ans;\n\t\tfor(int x = 0 ; ; ++x){\n\t\t\tif(isPrime(n / 2 - x)){\n\t\t\t\tans = generateSol(n , n / 2 - x);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(isPrime(n / 2 + x)){\n\t\t\t\tans = generateSol(n , n / 2 + x);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tfor(int i = 0 ; i < n ; ++i)\n\t\t\tcout << ans[i] << \" \\n\"[i == n - 1];\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2089",
    "index": "B1",
    "title": "Canteen (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $k=0$. You can hack only if you solved all versions of this problem.}\n\nEcrade has two sequences $a_0, a_1, \\ldots, a_{n - 1}$ and $b_0, b_1, \\ldots, b_{n - 1}$ consisting of integers. It is guaranteed that the sum of all elements in $a$ does not exceed the sum of all elements in $b$.\n\nInitially, Ecrade can make exactly $k$ changes to the sequence $a$. It is guaranteed that $k$ does not exceed the sum of $a$. In each change:\n\n- Choose an integer $i$ ($0 \\le i < n$) such that $a_i > 0$, and perform $a_i := a_i - 1$.\n\nThen Ecrade will perform the following three operations sequentially on $a$ and $b$, which constitutes one round of operations:\n\n- For each $0 \\le i < n$: $t := \\min(a_i, b_i), a_i := a_i - t, b_i := b_i - t$;\n- For each $0 \\le i < n$: $c_i := a_{(i - 1) \\bmod n}$;\n- For each $0 \\le i < n$: $a_i := c_i$;\n\nEcrade wants to know the minimum number of rounds required for all elements in $a$ to become equal to $0$ after exactly $k$ changes to $a$.\n\nHowever, this seems a bit complicated, so please help him!",
    "tutorial": "For each $a_i$, calculate the minimum number of cyclic right shifts required to reduce it to zero, denoted as $d_i$. The answer is the maximum $d_i$ across all $i$. For cyclic problems, we can consider breaking the cycle into a chain (i.e., let $a_{i+n} = a_i$, $b_{i+n} = b_i$). Consider constructing a parenthesis sequence $s$ by concatenating $a_0$ left parentheses, $b_0$ right parentheses, $a_1$ left parentheses, $b_1$ right parentheses, ... ,$a_{2n-1}$ left parentheses and $b_{2n-1}$ right parentheses. The operation in the original problem corresponds to the process of matching parentheses in $s$: \"Set the smaller of $(a_i, b_i)$ to zero and the larger to their difference\" $\\Rightarrow$ \"Match the parentheses corresponding to $(a_i, b_i)$\". \"Cyclically right-shift $a$\" $\\Rightarrow$ \"Unmatched left parentheses continue to find matching right parentheses\". The first time $a_i$ is reduced to zero depends on which $b_j$ 's right parenthesis matches the leftmost parenthesis corresponding to $a_i$. We can use prefix sums to find matchings of the parenthesis: Let $c_i = \\sum\\limits_{j=0}^i (a_j - b_j)$. Define $p_i$ as the smallest index satisfying $p_i > i$ and $c_{p_i} \\leq c_i$, then $d_i = p_i - i$. We can compute all $p_i$ with a monotonic stack. It should be pointed out that matching parentheses is just an intuitive way of understanding the solution. You can, of course, also draw the above conclusion by direct observation. The time complexity is $O(\\sum n)$. 2089B2 - Canteen (Hard Version) Idea: Ecrade_",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll t,n,k,a[400009],stk[400009];\ninline ll read(){\n\tll s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nint main(){\n\tt = read();\n\twhile (t --){\n\t\tn = read(),k = read();\n\t\tfor (ll i = 1;i <= n;i += 1) a[i] = read();\n\t\tfor (ll i = 1;i <= n;i += 1) a[i] = a[i + n] = a[i] - read();\n\t\tfor (ll i = 1;i <= 2 * n;i += 1) a[i] += a[i - 1];\n\t\tll tp = 0,ans = 0;\n\t\tfor (ll i = 2 * n;i >= 1;i -= 1){\n\t\t\twhile (tp && a[stk[tp]] > a[i]) tp -= 1;\n\t\t\tif (i <= n) ans = max(ans,stk[tp] - i);\n\t\t\tstk[++ tp] = i;\n\t\t}\n\t\tprintf(\"%lld\\n\",ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "flows",
      "greedy",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2089",
    "index": "B2",
    "title": "Canteen (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, there are no additional limits on $k$. You can hack only if you solved all versions of this problem.}\n\nEcrade has two sequences $a_0, a_1, \\ldots, a_{n - 1}$ and $b_0, b_1, \\ldots, b_{n - 1}$ consisting of integers. It is guaranteed that the sum of all elements in $a$ does not exceed the sum of all elements in $b$.\n\nInitially, Ecrade can make exactly $k$ changes to the sequence $a$. It is guaranteed that $k$ does not exceed the sum of $a$. In each change:\n\n- Choose an integer $i$ ($0 \\le i < n$) such that $a_i > 0$, and perform $a_i := a_i - 1$.\n\nThen Ecrade will perform the following three operations sequentially on $a$ and $b$, which constitutes one round of operations:\n\n- For each $0 \\le i < n$: $t := \\min(a_i, b_i), a_i := a_i - t, b_i := b_i - t$;\n- For each $0 \\le i < n$: $c_i := a_{(i - 1) \\bmod n}$;\n- For each $0 \\le i < n$: $a_i := c_i$;\n\nEcrade wants to know the minimum number of rounds required for all elements in $a$ to become equal to $0$ after exactly $k$ changes to $a$.\n\nHowever, this seems a bit complicated, so please help him!",
    "tutorial": "We can use binary search on the answer $x$, and calculate the minimum number of changes needed to make $a$ zero within $x$ rounds. However, direct computation on the cyclic chain of $2n$ elements is troublesome (due to overlapping contributions). Instead, we can cyclically shift $a$ and $b$ such that $c_{n-1} = \\min\\limits_{i=0}^{n-1} c_i$, which ensures that no $a_{n-1}>0$ will be cyclically shifted to $a_0$, enabling us to only consider the first $n$ elements of the chain. For the adjusted $a$ and $b$, we can greedily process $i$ from $n - x - 1$ to $-1$: If $\\min\\limits_{j=i+1}^{i+x}c_j > c_i$, then we should apply $\\min\\limits_{j=i+1}^{i+x}c_j - c_i$ changes to $a_{i+1}$ (assume that $c_{-1}=0$). We can also use a monotonic stack to maintain the whole process. Note that if $\\sum\\limits_{i=0}^{n-1} a_i=k$, we should output $0$. The time complexity is $O(\\sum n\\log k)$. Bonus: Find an $O(\\sum n)$ solution. 2089C2 - Key of Like (Hard Version) Idea: SpiritualKhorosho",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll t,n,k,pos,a[400009],stk[400009];\ninline ll read(){\n\tll s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nbool judge(ll x){\n\tll l = 1,r = 0,res = 0;\n\tfor (ll i = pos;i >= pos - n;i -= 1){\n\t\tif (l <= r && stk[l] - i > x) l += 1;\n\t\tif (pos - i >= x) res += max(0ll,a[stk[l]] - a[i]);\n\t\tif (res > k) return 0;\n\t\twhile (l <= r && a[stk[r]] > a[i]) r -= 1;\n\t\tstk[++ r] = i;\n\t}\n\treturn 1;\n}\nint main(){\n\tt = read();\n\twhile (t --){\n\t\tn = read(),k = read();\n\t\tll suma = 0;\n\t\tfor (ll i = 1;i <= n;i += 1) a[i] = read(),suma += a[i];\n\t\tfor (ll i = 1;i <= n;i += 1) a[i] -= read(),a[i + n] = a[i];\n\t\tif (suma == k){puts(\"0\"); continue;}\n\t\tfor (ll i = 1;i <= 2 * n;i += 1) a[i] += a[i - 1];\n\t\tpos = n;\n\t\tfor (ll i = n + 1;i <= 2 * n;i += 1) if (a[i] < a[pos]) pos = i;\n\t\tll l = 1,r = n,ans = n;\n\t\twhile (l <= r){\n\t\t\tll mid = (l + r) >> 1;\n\t\t\tif (judge(mid)) ans = mid,r = mid - 1;\n\t\t\telse l = mid + 1;\n\t\t}\n\t\tprintf(\"%lld\\n\",ans);\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "data structures",
      "dp",
      "flows",
      "greedy",
      "two pointers"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2089",
    "index": "C2",
    "title": "Key of Like (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $k$ can be non-zero. You can hack only if you solved all versions of this problem.}\n\nA toy box is a refrigerator filled with childhood delight. Like weakness, struggle, hope ... When such a sleeper is reawakened, what kind of surprises will be waiting?\n\nM received her toy box as a birthday present from her mother. A jewellery designer would definitely spare no effort in decorating yet another priceless masterpiece as a starry firmament with exquisitely shaped gemstones. In addition, $l$ distinct locks secure the tiny universe of her lovely daughter: a hair clip featuring a flower design, a weathered feather pen, a balloon shaped like the letter M ... each piece obscures a precious moment.\n\nA few days ago, M rediscovered her toy box when she was reorganizing her bedroom, along with a ring of keys uniquely designed for the toy box. Attached to the key ring are $(l + k)$ keys, of which $l$ keys are able to open one of the $l$ locks correspondingly, while the other $k$ keys are nothing but counterfeits to discourage brute-force attack. To remind the correspondence, M's mother adorned each key with a gemstone of a different type. However, passing days have faded M's memory away.\n\n\"... So I have to turn to you all,\" M said while laying that ring of keys on the table.\n\nK picked up the keys and examined them carefully. \"The appearance of these keys unveils nothing fruitful. Thus, I am afraid that we shall inspect them sequentially.\"\n\nAlthough everyone is willing to help M, nobody has a plan. Observing others' reactions, T suggested, \"Let's play a game. Everyone tries a key in turn, and who opens the most locks is amazing.\"\n\n$n$ members, including M herself, take turns to unlock the toy box recursively in the same order until all the $l$ locks are unlocked. At each turn, the current member only selects a single key and tests it on exactly one of the locks. To open the toy box as soon as possible, every member chooses the key and the lock that maximize the probability of being a successful match. If there are multiple such pairs, a member will randomly choose one of such pairs with equal probability. Apparently, if a lock has been matched with a key, then neither the lock nor the key will be chosen again in following attempts.\n\nAssume that at the very beginning, the probability that a lock can be opened by any key is equal. If everyone always tries the optimal pairs of keys and locks based on all the historical trials, what will the expected number of successful matches be for each member?",
    "tutorial": "This problem is inspired by a minigame from a recently released party video game, but the story was modified to comply with the title. We tried to isolate the artistic part and the theoretical part, and I apologize if you still feel like working on reading comprehension exercises. Noticing that each member's strategy is not maximizing the total outcome (which is the expected number of successful matches between keys and locks), but only maximizing the outcome in her current turn, and equally likely to adopt each of optimal (pure) strategies, it will be ideal if there is some simple form of the strategy that only depends on $L$ and $K$. At the very beginning, when there is no information about the relationship between keys and locks, the first member in her first turn must randomly choose a key and a lock. What about the second member, if the first one is not lucky enough? Since she will not choose the same pair of keys and locks, there are three different types of (pure) strategies: Choose a different key to open the same lock; Choose a different key to open the same lock; Choose the same key to open a different lock; Choose the same key to open a different lock; Choose a different key and a different lock. Choose a different key and a different lock. For the first type of strategy, since there are $(L+K-1)$ keys remaining (after the very first attempt), and among them is only one correct key, the probability of opening the same lock is $1/(L+K-1)$. For the second type, it can be proven that the probability is also $1/(L+K-1)$. Another way to think of this is, add $K$ imaginary locks and match each of them with a counterfeit key. Then, it is apparent that a new lock matches the selected key with the given probability. The key selected by the first member can either be a real key or a counterfeit one. Denote the event of the key being authentic as $A$, and that of it failing to open the lock at the first turn as $B$. Then, according to the Bayes' theorem along with the law of total probability, $\\begin{equation} \\begin{split} P(A|B) &= \\frac{P(B|A)P(A)}{P(B)} = \\frac{P(B|A)P(A)}{P(B|A)P(A) + P\\left(B\\left|\\bar{A}\\right.\\right)P\\left(\\bar{A}\\right)} \\\\ &= \\frac{((L-1)/L)\\cdot (L/(L+K))}{((L-1)/L)\\cdot (L/(L+K)) + 1\\cdot(K/(L+K))}\\\\ &= \\frac{L-1}{L+K-1},\\\\ P\\left(\\left.\\bar{A}\\right|B\\right) &= 1 - P(A|B) = \\frac{K}{L+K-1}. \\end{split} \\end{equation}$ Thus, the probability that the same key selected by the first member can open another lock randomly chosen by the second member (denoted as $C$) is $\\begin{equation} \\begin{split} P(C|B) &= P(A|B)\\cdot P(C|AB) + P\\left(\\left.\\bar{A}\\right|B\\right)\\cdot P\\left(C\\left|\\bar{A}B\\right.\\right)\\\\ &=\\frac{L-1}{L+K-1}\\cdot\\frac{1}{L-1} + \\frac{K}{L+K-1}\\cdot 0\\\\ &= \\frac{1}{L+K-1}. \\end{split} \\end{equation}$ For the third type of strategy, its probability can be computed from either the first type or the second type, as $(L+K-1)$ different outcomes are equally likely to happen: $\\begin{equation} \\frac{1-1/(L+K-1)}{L+K-1}=\\frac{L+K-2}{(L+K-1)^2}<\\frac{1}{L+K-1}. \\end{equation}$ In conclusion, the second member will either choose the same key or the same lock. Because there are $(L - 1)$ pairs of the same key and other locks, and $(L + K - 1)$ pairs of other keys and the same lock, the second member will use the same key with probability $(L - 1)/(2L + K - 2)$, or check the same lock with probability $(L + K - 1)/(2L + K - 2)$. As for all the following attempts, a similar Proof shows that, everyone will imitate the strategy adopted by the second member. That is to say, if the second member decides to continue with the same key, everyone will keep using this same key, until a lock is opened or all the locks are checked; if the second member picks a different key for the same lock, everyone will challenge this same lock, until it is eventually settled (and obviously it will). Furthermore, whenever a key is identified as counterfeit, or a lock is opened, the information 'collapses', which turns the original problem into a subproblem with either one less counterfeit key (corresponding to $K' = K - 1$), or both one less valid key and one less lock ($L' = L - 1$), respectively. To sum up, the process of the game is: Whenever a lock is opened, the original problem is reduced to a subproblem with $L' = L - 1$; Whenever a key is proven counterfeit, the original problem is reduced to a subproblem where $K' = K - 1$; -The first member randomly chooses a key and a lock to check if they match; If the first member fails, the second member adopts the same key with probability $(L - 1)/(2L + K - 2)$, or investigates the same lock with probability $(L + K - 1)/(2L + K - 2)$; If the second member fails as well, all the following attempts will replicate the choice of whether to employ the same key or the same lock. Knowing the concrete strategies, the task now becomes how to compute the expected values efficiently. As you might have imagined, it can be achieved using dynamic programming due to the existence of overlapping subproblems. But let's examine another approach which might be easier to understand: compute $p_i (l, k)$, the total probability that the $i$-th member begins a subproblem with $l$ locks and $k$ counterfeit keys, and accumulate $e_i$'s during the computation. Transitions for $p$ itself include (and those from $p$ to $e$ will be similar to): The first member manages to open the lock without any prior information; The second member makes a successful guess; Any of the succeeding attempts succeeds; Everyone uses the same key but it fails on all the locks. For each $p_i(l, k)$, all the transition can be easily processed in $\\Theta(1)$ time, except the third one. A verbatim implementation requires $O(L + K)$ time per state, which is apparently not efficient enough. Since $N \\ll L$, a possible work-around is to compute the transition coefficient for each member, instead of each attempt. Intuitively, all attempts should share the same probability of success, regardless of the order. A simplified model is to draw all balls sequentially without replacement from a box of $1$ red ball and $(x-1)$ white balls, in which the red ball appears at the $i$-th attempt with an equal probability of $1/x$. Of course, the observation for our problem can also be proven mathematically, but let's omit it for simplicity. This important observation reduces the time complexity of the third type of transition to $O(N)$, as we can first compute the maximum number of attempts for each member, and then multiply it with the common probability of a single attempt. However, this is still not enough for passing the problem (and we adjusted the constraints to prevent so). The final trick to pass all testcases requires revisiting the transition coefficients we just computed. Notice that, if all the members have $a$ attempts in total (but for the third type of transition only, which excludes the first two), then: If $a$ is a multiple of $N$, then every member can have at most $a/N$ attempts; If $a$ is a multiple of $N$, then every member can have at most $a/N$ attempts; Otherwise, the first $a \\bmod N$ members (right after the second member, who decides to advance with the same key or the same lock) can have at most $\\lceil a/N\\rceil$ attempts, while all the others can have at most $\\lfloor a/N\\rfloor$ attempts. Otherwise, the first $a \\bmod N$ members (right after the second member, who decides to advance with the same key or the same lock) can have at most $\\lceil a/N\\rceil$ attempts, while all the others can have at most $\\lfloor a/N\\rfloor$ attempts. This implies that the transition coefficients consists of at most $3$ maximal contiguous subsequences of the same coefficients (in fact, if the coefficients are treated as a circular sequence, then there will be exactly $1$ or $2$ for the two cases respectively). Using techniques such as prefix sums helps further decrease the complexity of the computation to $\\Theta(1)$ per state. The total time complexity is $O(NLK)$. 2089D - Conditional Operators Idea: E.Space",
    "code": "#include <cstdio>\n#include <cstring>\nusing namespace std;\n#define MOD 1000000007\n#define MAXN 108\n#define MAXL 5004\n#define MAXK 27\nint e[MAXN], p[2][MAXK][MAXN], inv[2 * MAXL + MAXK];  \ninline void _update(int * const a, const int lbd, const int rbd, const int base, const int diff) {\n\t(a[0] += base) %= MOD;\n\t(a[lbd] += diff) %= MOD;\n\t(a[rbd] += MOD - diff) %= MOD;\n\treturn ;\n}\n#define Hill(_a, _lbd, _rbd, _base, _diff) _update(_a, _lbd, _rbd, _base, _diff)\n#define Valley(_a, _lbd, _rbd, _base, _diff) _update(_a, _rbd, _lbd, ((_base) + (_diff)) % MOD, MOD - (_diff))\n#define Update(_a, _lbd, _rbd, _base, _diff) { if (_lbd < _rbd) Hill(_a, _lbd, _rbd, _base, _diff); else Valley(_a, _lbd, _rbd, _base, _diff); }\nint like() {\n\tint n, l, k, i, j, a, b, dh, now, nxt, totk, ntry, prob, pd, pb, lbd, rbd;\n\tscanf(\"%d %d %d\", &n, &l, &k);\n\tif (n == 1) {\n\t\tprintf(\"%d\\n\", l);\n\t\treturn 0;\n\t}\n\tinv[1] = 1;\n\tj = 2 * l + k;\n\tfor (i = 2; i <= j; ++i) inv[i] = 1ll * (MOD - MOD / i) * inv[MOD % i] % MOD;\n\t\n\tmemset(p, 0, sizeof(p));\n\tmemset(e, 0, sizeof(e));\n\tp[0][0][0] = 1;\n\tp[0][0][1] = -1;\n\tnow = 0; nxt = 1;\n\tfor (i = 0; i < l; ++i) {\n\t\tfor (j = 0; j <= k; ++j) {\n\t\t\ttotk = l + k - i - j;\n\t\t\tfor (a = 1; a < n; ++a) (p[now][j][a] += p[now][j][a - 1]) %= MOD;\n\t\t\tfor (a = 0; a < n; ++a) {\n\t\t\t\t// Match at the first try\n\t\t\t\tprob = 1ll * p[now][j][a] * inv[totk] % MOD;\n\t\t\t\t(e[a] += prob) %= MOD;\n\t\t\t\tif (a != n - 1) (e[a + 1] += MOD - prob) %= MOD;\n\t\t\t\t(p[nxt][j][(a + 1) % n] += prob) %= MOD;\n\t\t\t\tif (a != n - 2) (p[nxt][j][(a + 2) % n] += MOD - prob) %= MOD;\n\n\t\t\t\tprob = 1ll * prob * inv[totk + l - i - 2] % MOD;\n\t\t\t\t// Same lock\n\t\t\t\tpd = 1ll * prob * (ntry = totk - 1) % MOD;\n\t\t\t\tpb = 1ll * (ntry / n) * pd % MOD;\n\t\t\t\tif (dh = ntry % n) {\n\t\t\t\t\tlbd = (a + 1) % n;\n\t\t\t\t\trbd = (a + dh) % n + 1; \n\t\t\t\t\tUpdate(e, lbd, rbd, pb, pd);\n\t\t\t\t\t(++lbd) %= n;\n\t\t\t\t\t++(rbd  %= n); \n\t\t\t\t\tUpdate(p[nxt][j], lbd, rbd, pb, pd);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t(e[0] += pb) %= MOD;\n\t\t\t\t\t(p[nxt][j][0] += pb) %= MOD;\n\t\t\t\t}\n\n\t\t\t\t// Same key\n\t\t\t\tpd = 1ll * prob * (ntry = l - i - 1) % MOD;\n\t\t\t\tif (j < k) {\n\t\t\t\t\tpb = 1ll * pd * (k - j) % MOD; \n\t\t\t\t\tb = (a + l - i) % n;\n\t\t\t\t\t(p[now][j + 1][b] += pb) %= MOD;\n\t\t\t\t\tif (b != n - 1) (p[now][j + 1][b + 1] += MOD - pb) %= MOD;\n\t\t\t\t}\n\t\t\t\tpb = 1ll * (ntry / n) * pd % MOD;\n\t\t\t\tif (dh = ntry % n) {\n\t\t\t\t\tlbd = (a + 1) % n;\n\t\t\t\t\trbd = (a + dh) % n + 1; \n\t\t\t\t\tUpdate(e, lbd, rbd, pb, pd);\n\t\t\t\t\t(++lbd) %= n;\n\t\t\t\t\t++(rbd  %= n); \n\t\t\t\t\tUpdate(p[nxt][j], lbd, rbd, pb, pd);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t(e[0] += pb) %= MOD;\n\t\t\t\t\t(p[nxt][j][0] += pb) %= MOD;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tnow ^= 1;\n\t\tnxt ^= 1;\n\t\tmemset(p[nxt], 0, sizeof(int) * MAXK * MAXN);\n\t}\n\tfor (i = 1; i < n; ++i) (e[i] += e[i - 1]) %= MOD;\n\n\tfor (i = 0; i < n; ++i) printf(\"%d%c\", e[i], \" \\n\"[i == n - 1]);\n\treturn 0;\n}\nint main() {\n\tint t;\n\tscanf(\"%d\", &t);\n\twhile (t--) {\n\t\tlike();\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "math",
      "probabilities"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2089",
    "index": "D",
    "title": "Conditional Operators",
    "statement": "In C++, the conditional operator ?: is used as the value of x?y:z is $y$ if $x$ is true; otherwise, the value is $z$. $x$, $y$, and $z$ may also be expressions. It is right-associated; that is, a?b:c?d:e is equivalent to a?b:(c?d:e). $0$ means false and $1$ means true.\n\nGiven a binary string with length $2n+1$, you need to show whether the value of the expression can be $1$ after inserting $n$ conditional operators into the string. You can use parentheses. For example, the string 10101 can be transformed into (1?0:1)?0:1, whose value is $1$.",
    "tutorial": "Each operation transform three adjacent characters into one. If the string starts with 11, the answer should be yes since we can first transform the remaining part into a single 0 or 1 and then the value of 11? is always $1$. If the string ends with 1, only 101 has no solution, otherwise it starts with 11 or 0, or we can transform 10? in the front of the string into a 0. Then transform the rest part of the string into a single character to make the last operation 0?(anything):1 makes 1. If an operation transformed a string ending with 0 into one ending with 1, it must be 1?1:0 makes 1. Consider the case where the strings contains 11 as a substring. After transforming the remaining part, ?11?? or ??11? will be derived. The cases are 01100, 00110, 01110, 10110. All other cases start with 11 or end with 1. All cases of ??11? have a solution: (0?0:1)?1:0 makes 1. (0?1:1)?1:0 makes 1. 1?(0?1:1):0 makes 1. However, 01100 has no solution. Since 0?0:1 equals 1, before the last 1, any two adjacent 0's with no 1 in between can be eliminated. Thus, if there are two 1's with an even number of 0's in between, and there are an even number of characters in front the former 1, i.e., (..)*1(00)*1(..)*0 in regular expression, the answer should be yes, since after eliminating the 0's in between, the 1's become adjacent. The parity of the characters before the former 1 guarantees that it will not become 01100. Another case is that the string ends with 0 and every pair of adjacent 1's has an odd number of 0's in between. Since 0(1?0:1)0 makes 000, 1(0?1:0)1 makes 101, 10(1?0:0)01 makes 10001, there is no way to change the parity of the consecutive 0's to make 11 to change the ending 0 into 1. In the remaining case, there are even 0's between some pair of adjacent 1's, but the number of characters before the first 1 is odd, there must be only one pair. Suppose the string is 1-indexed. It is because the indices of such pair of 1's must be [odd, even]; while the indices in the previous case must be [even, odd]. Thus, if there are two such pairs of this case [odd, even], in the parity sequence [odd, even, ..., odd, even] there must be an [even, odd] as a substring. Therefore, any other pair of adjacent 1's must have odd 0's in between, i.e., $0(00)^*\\color{blue}{(10(00)^*)^*}\\color{red}1\\color{black}(00)^*\\color{red}1\\color{blue}{((00)^*01)^*}\\color{black}(00)^+$ in regular expression. Any operation remains the string in this case, except that the string is $0(00)^*\\color{blue}{(10(00)^*)^*}\\color{red}1\\color{red}1\\color{black}(00)^+$ and the operation is $\\color{red}1\\color{black}?\\color{red}1\\color{black}:0$ makes 1. Since it must ends with 00, it becomes a string ending with 0 and every pair of adjacent 1's has odd 0's in between, which is a case mentioned before that has no solution. In conclusion, it has a solution if and only of at least one of the two following conditions is met: It ends with 1 but it is not 101. It has two adjacent 1's such that there are even 0's in between and the number of characters before the former 1 is even. 2089E - Black Cat Collapse Idea: abruce",
    "code": "#include<bits/stdc++.h>\nchar s[333333];\nchar val(char x,char y,char z){\n\treturn x=='1'?y:z;\n}\nstd::pair<std::string, char> fold(int l,int r){\n\tstd::string str;\n\tchar v=s[r];\n\tfor(int i=l;i<r;i+=2){\n\t\tstr+=s[i];\n\t\tstr+='?';\n\t\tstr+=s[i+1];\n\t\tstr+=':';\n\t}\n\tstr+=s[r];\n\tfor(int i=r-2;i>=l;i-=2){\n\t\tv=val(s[i],s[i+1],v);\n\t}\n\treturn std::make_pair(str,v);\n}\nvoid solve(){\n\tint n;\n\tscanf(\"%d\",&n);\n\tn=2*n+1;\n\tscanf(\"%s\",s+1);\n\tint last=0;\n\tfor(int i=1;i<=n;++i){\n\t\tif(s[i]=='1'&&last>0){\n\t\t\tif(i%2==0&&last&1){\n\t\t\t\tputs(\"Yes\");\n\t\t\t\tstd::string s4=fold(last+1,i).first;\n\t\t\t\tauto tmp=fold(i+1,n);\n\t\t\t\tstd::string s5=tmp.first;\n\t\t\t\tchar v5=tmp.second;\n\t\t\t\tif(last==1){\n\t\t\t\t\tprintf(\"1?(%s):(%s)\\n\",s4.c_str(),s5.c_str());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttmp=fold(1,last-2);\n\t\t\t\tstd::string s1=tmp.first;\n\t\t\t\tchar v1=tmp.second;\n\t\t\t\tif(v1=='1'){\n\t\t\t\t\tprintf(\"(%s)?(%c?1:(%s)):(%s)\\n\",s1.c_str(),s[last-1],s4.c_str(),s5.c_str());\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tprintf(\"((%s)?%c:1)?(%s):(%s)\\n\",s1.c_str(),s[last-1],s4.c_str(),s5.c_str());\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif(s[i]=='1'){\n\t\t\tlast=i;\n\t\t}\n\t}\n\tif(s[n]=='1'&&std::string(s+1)!=\"101\"){\n\t\tputs(\"Yes\");\n\t\tauto left=s[1]=='0'?fold(1,1):fold(1,3);\n\t\tauto mid=s[1]=='0'?fold(2,n-1):fold(4,n-1);\n\t\tprintf(\"(%s)?(%s):1\\n\",left.first.c_str(),mid.first.c_str());\n\t\treturn;\n\t}\n\tputs(\"No\");\n\treturn;\n}\nint main(){\n\tint T;\n\tscanf(\"%d\",&T);\n\twhile(T--){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 3200
  },
  {
    "contest_id": "2089",
    "index": "E",
    "title": "Black Cat Collapse",
    "statement": "The world of the black cat is collapsing.\n\nIn this world, which can be represented as a rooted tree with root at node $1$, Liki and Sasami need to uncover the truth about the world.\n\nEach day, they can explore a node $u$ that has not yet collapsed. After this exploration, the black cat causes $u$ and all nodes in its subtree to collapse. Additionally, at the end of the $i$ th day, if it exists, the number $n-i+1$ node will also collapse.\n\nFor each $i$ from $1$ to $n$, determine the number of exploration schemes where Liki and Sasami explore exactly $i$ days (i.e., they perform exactly $i$ operations), with the last exploration being at node $1$. The result should be computed modulo $998\\,244\\,353$.\n\n\\textbf{Note:} It is guaranteed that nodes $1$ to $n$ can form a \"DFS\" order of the tree, meaning there exists a depth-first search traversal where the $i$ th visited node is $i$.",
    "tutorial": "Firstly, consider a classical dp to calculate $dp_{u,k}$ as the number of delete $k$ vertices in subtree $u$ without considering deleting vertex $n-i+1$ everyday. This is trivial. Then, due to the existence of an \"automatic deletion\" process, we cannot view the selected points within the subtree of $u$ as operations with only relative order, because they may be illegal. However, we consider the final operation sequence, putting the vertex chosen on the $i$ th day in the position $n-i+1$. That is, if we firstly choose $4$, then $3$, then $1$, it will be $0431$. Then, one vertex $u$ must be put in position $u$ or later. Then, we find that for the subtree of vertex $u$ with DFS order interval $[l,r]$, all vertices can't be put in position before $l$, and it is always legal to put in position after $r$ if parent-child relations are satisfied. So we consider a dp $f_{u,i,j,k}$ which represents that the subtree of $u$ leaves position $i$ for ancestors (which means nothing can be placed at position $i$ or before, and if $i=0$, then nothing is left for ancestors), there are $j$ empty spaces (not including the one left for ancestors), and $k$ vertices need to be put into positions after the subtree of $u$. In the $i=0$ case, we merge subtrees, and the subtree with smaller DFS order can put some backward operations into the space of the subtree with bigger DFS order. Specifically, consider the sons of $u$ enumerated in reverse order of DFS, and the son is $v$. Then enumerate $w$ as how many backward operations of $v$ will fill in space of $u$. The transition is $f_{u,0,j+j1-w,k+k1-w}\\leftarrow f_{u,0,j+j1-w,k+k1-w}+f_{u,0,j,k}\\times f_{v,0,j1,k1}\\times \\binom{j}{w}\\times\\binom{k+k1-w}{k}$. That is, after putting $w$ operations from backward operations of $v$ into spaces of $u$, we merge the spaces of $u$ and $v$, then the backward operations of $u$ and $v$. For $f_{v,i,j,k}(i\\neq 0)$, it won't interfere with the transition with its following siblings. And for $f_{u,i,j,k}$,any operations from $v$ can't put into the subtree of $u$ and $v$, so we only need to merge backward operations of $u$ and $v$. After finishing the transition of subtrees, we consider where to put $u$. If we don't put $u$, there will be one more space, and we can consider whether to leave it for ancestors if $i=0$.That is $f_{u,i,j,k}\\rightarrow f_{u,i,j+1,k},f_{u,0,j,k}\\rightarrow f_{u,u,j,k}$. We put $u$ into the position left for ancestors, that is $f_{u,i,j,k}\\rightarrow f_{u,0,j+1,k}$. And we can leave another position for ancestors of $u$, that is $f_{u,i,j,k}\\rightarrow f_{u,i1,j+1,k}(i1<i)$. We put $u$ into position $u$, in that case, we can't leave position for ancestors of $u$, that is $f_{u,0,j,k}\\rightarrow f_{u,0,j,k}$. We put $u$ backward, then we can't put anything in the subtree of $u$, but we can leave position for ancestors of $u$, that is $f_{u,i,siz_u-2,k}\\rightarrow f_{u,i,siz_u-1,k+1},f_{u,0,siz_u-1,k}\\rightarrow f_{u,0,siz_u,k+1}$. The answer for $i$ operations is just we leave position $n-i+1$ for $1$, and there are $n-i$ spaces (therefore the spaces are before $n-i+1$) and no backward operations. The time complexity is $O(\\sum n^5)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nint read() {\n\tint x=0,f=1;\n\tchar c=getchar();\n\twhile(c<'0'||c>'9') {\n\t\tif(c=='-')f=-1;\n\t\tc=getchar();\n\t}\n\twhile(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();\n\treturn x*f;\n}\nnamespace tokido_saya {\n\tconst int maxn=81,mod=998244353;\n\ttypedef vector<int>::iterator iter;\n\tint n,lp[maxn],rp[maxn],siz[maxn],t;\n\tvector<int> v[maxn];\n\tll f[maxn][maxn][maxn][maxn],dp[maxn][maxn],fac[maxn],inv[maxn];\n\tint zc[maxn][maxn][maxn][maxn];\n\tll qpow(ll x,int y)\n\t{\n\t\tll w=1;\n\t\twhile(y)\n\t\t{\n\t\t\tif(y&1)w=w*x%mod;\n\t\t\tx=x*x%mod,y>>=1;\n\t\t}\n\t\treturn w;\n\t}\n\tll C(int x,int y)\n\t{\n\t\tif(y<0||y>x)return 0;\n\t\treturn fac[x]*inv[x-y]%mod*inv[y]%mod;\n\t}\n\tvoid dfs1(int u)\n\t{\n\t\tlp[u]=rp[u]=u;\n\t\tfor(iter it=v[u].begin();it!=v[u].end();it++)dfs1(*it),rp[u]=max(rp[u],rp[*it]);\n\t}\n\tvoid dfs2(int u)\n\t{\n\t\tf[u][0][0][0]=1,dp[u][0]=1;\n\t\tfor(iter it=v[u].begin();it!=v[u].end();it++)\n\t\t{\n\t\t\tint v=*it;\n\t\t\tdfs2(v);\n\t\t\tfor(int i=siz[u];i>=0;i--)\n\t\t\t\tfor(int j=siz[v];j;j--)dp[u][i+j]=(dp[u][i+j]+dp[u][i]*dp[v][j]%mod*C(i+j,j))%mod;\n\t\t\tfor(int j1=0;j1<=siz[v];j1++)\n\t\t\t\tfor(int k1=0;k1<=min(j1+1,siz[v]);k1++)\n\t\t\t\t{\n\t\t\t\t\tmemset(zc[j1][k1],0,sizeof(zc[j1][k1]));\n\t\t\t\t\tfor(int j=0;j<=siz[u];j++)\n\t\t\t\t\t\tfor(int k=0;k<=j+1;k++)\n\t\t\t\t\t\t\tfor(int w=0;w<=min(k1,j);w++)zc[j1][k1][j+j1-w][k+k1-w]=(zc[j1][k1][j+j1-w][k+k1-w]+f[u][0][j][k]*C(j,w)%mod*C(k+k1-w,k))%mod;\n\t\t\t\t}\t\n\t\t\tmemset(f[u][0],0,sizeof(f[u][0]));\n\t\t\tfor(int j=0;j<=siz[v];j++)\n\t\t\t\tfor(int k=0;k<=j+1;k++)\n\t\t\t\t\tfor(int j1=0;j1<=siz[u]+siz[v];j1++)\n\t\t\t\t\t\tfor(int k1=0;k1<=min(siz[u]+siz[v],j1+1);k1++)\n\t\t\t\t\t\t\tif(zc[j][k][j1][k1])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst int w=zc[j][k][j1][k1];\n\t\t\t\t\t\t\t\tf[u][0][j1][k1]=(f[u][0][j1][k1]+f[v][0][j][k]*w)%mod;\n\t\t\t\t\t\t\t\tfor(int i=lp[v];i<=rp[v];i++)f[u][i][j1][k1]=(f[u][i][j1][k1]+f[v][i][j][k]*w)%mod;\n\t\t\t\t\t\t\t}\n\t\t\tfor(int i=rp[v]+1;i<=rp[u];i++)\n\t\t\t\tfor(int j=siz[u]-1;j>=i-rp[v]-1;j--)\n\t\t\t\t\tfor(int k=j+1;k>=0;k--)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst int val=f[u][i][j][k];\n\t\t\t\t\t\tf[u][i][j][k]=0;\n\t\t\t\t\t\tfor(int p=0;p<=siz[v];p++)\n\t\t\t\t\t\t\tfor(int w=0;w<=min(p,j-(i-rp[v]-1));w++)f[u][i][j+siz[v]-w][k+p-w]=(f[u][i][j+siz[v]-w][k+p-w]+dp[v][p]*val%mod*C(j-(i-rp[v]-1),w)%mod*C(k+p-w,k))%mod;\n\t\t\t\t\t}\n\t\t\tsiz[u]+=siz[v];\n\t\t}\n\t\tfor(int i=siz[u];i>=0;i--)dp[u][i+1]=(dp[u][i+1]+dp[u][i])%mod;\n\t\tif(u!=1)for(int j=siz[u];j>=0;j--)\n\t\t\tfor(int k=min(j+1,siz[u]);k>=0;k--)\n\t\t\t{\n\t\t\t\tll sum=0;\n\t\t\t\tfor(int i=rp[u];i>=lp[u];i--)\n\t\t\t\t{\n\t\t\t\t\tconst int w=f[u][i][j][k];\n\t\t\t\t\tf[u][i][j+1][k]=(f[u][i][j+1][k]+w)%mod;\n\t\t\t\t\tif(j==siz[u]-1)f[u][i][j+1][k+1]=(f[u][i][j+1][k+1]+w)%mod;\n\t\t\t\t\tf[u][i][j][k]=sum,sum=(sum+w)%mod;\n\t\t\t\t}\n\t\t\t\tconst int w=f[u][0][j][k];\n\t\t\t\tf[u][lp[u]][j][k]=(f[u][lp[u]][j][k]+w)%mod,f[u][0][j+1][k]=(f[u][0][j+1][k]+w+sum)%mod;\n\t\t\t\tif(j==siz[u])f[u][0][j+1][k+1]=(f[u][0][j+1][k+1]+w)%mod,f[u][lp[u]][j][k+1]=(f[u][lp[u]][j][k+1]+w)%mod;\n\t\t\t}\n\t\tsiz[u]++;\n\t}\n\tint main() {\n\t\tint x,y;\n\t\tt=read(),fac[0]=1;\n\t\tfor(int i=1;i<=80;i++)fac[i]=fac[i-1]*i%mod;\n\t\tinv[80]=qpow(fac[80],mod-2);\n\t\tfor(int i=80;i;i--)inv[i-1]=inv[i]*i%mod;\n\t\twhile(t--)\n\t\t{\n\t\t\tn=read(),memset(f,0,sizeof(f)),memset(dp,0,sizeof(dp)),memset(siz,0,sizeof(siz));\n\t\t\tfor(int i=1;i<=n;i++)v[i].clear();\n\t\t\tfor(int i=1;i<n;i++)\n\t\t\t{\n\t\t\t\tx=read(),y=read();\n\t\t\t\tif(x>y)swap(x,y);\n\t\t\t\tv[x].push_back(y);\n\t\t\t}\n\t\t\tfor(int i=1;i<n;i++)sort(v[i].begin(),v[i].end()),reverse(v[i].begin(),v[i].end());\n\t\t\tdfs1(1),dfs2(1);\n\t\t\tfor(int i=n;i>1;i--)printf(\"%lld \",f[1][i][i-2][0]);\n\t\t\tputs(\"1\");\n\t\t}\n\t\treturn 0;\n\t}\n}\nint main() {\n\treturn tokido_saya::main();\n}",
    "tags": [],
    "rating": 3500
  },
  {
    "contest_id": "2090",
    "index": "A",
    "title": "Treasure Hunt",
    "statement": "Little B and his friend Little K found a treasure map, and now they just need to dig up the treasure, which is buried at a depth of $a.5$ meters.\n\nThey take turns digging. On the first day, Little B digs; on the second day, Little K. After each day, they switch. Little B digs exactly $x$ meters of soil each day, while Little K digs $y$ meters. They became curious about who will dig up the treasure first, meaning during whose day the total dug depth will exceed $a.5$.\n\nBut they are too busy digging, so help them and tell who will dig up the treasure!",
    "tutorial": "Let's calculate how many operations we need. The number of pairs of operations is $\\left\\lfloor\\frac{a}{x + y}\\right\\rfloor$. Additionally, we add $+1$ if $(a \\bmod (x + y)) \\ge x$, because in this case, the first player will be able to make one more move. Note that the first part is always even, which means the answer depends only on whether $(a \\bmod (x + y)) \\ge x$, and in this case, the answer is YES.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int x, y, a;\n    cin >> x >> y >> a;\n    if (a % (x + y) < x) {\n        cout << \"NO\\n\";\n    } else {\n        cout << \"YES\\n\";\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n\n    int t;\n    cin >> t;\n    while (t--)\n        solve();\n}",
    "tags": [
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2090",
    "index": "B",
    "title": "Pushing Balls",
    "statement": "Ecrade has an $n \\times m$ grid, originally empty, and he has pushed several (possibly, zero) balls in it.\n\nEach time, he can push one ball into the grid either from the leftmost edge of a particular row or the topmost edge of a particular column of the grid.\n\nWhen a ball moves towards a position:\n\n- If there is no ball originally at that position, the incoming ball will stop and occupy the position.\n- If there is already a ball at that position, the incoming ball will stop and occupy the position, while the original ball will continue moving to the next position in the same direction.\n\nNote that if a row or column is full (i.e., all positions in that row or column have balls), he cannot push a ball into that row or column.\n\nGiven the final state of whether there is a ball at each position of the grid, you need to determine whether it is possible for Ecrade to push the balls to reach the final state.",
    "tutorial": "We can transform the problem into: select a row / column and replace the leftmost / topmost $0$ with $1$. Then the solution is clear: if, for each $1$ in the grid, there does not exist any $0$ on its top, or does not exist any $0$ on its left, then the answer is YES; otherwise NO. But how to prove that if the condition is satisfied, we can always construct a valid series of ball-pushing operations? We can consider the problem in reverse order: given the final state, if, for an $1$ in the grid, there does not exist any $0$ on its top, or does not exist any $0$ on its left, then we can turn it into $0$, and our goal is to turn all $1$ s into $0$ s. We can always reach the goal if we choose $1$ s in descending order of $i+j$, where $(i,j)$ is their coordinates in the grid.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\nll t,n,m,a[59][59],vis[59][59];\nchar s[59];\ninline ll read(){\n\tll s = 0,w = 1;\n\tchar ch = getchar();\n\twhile (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();}\n\twhile (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar();\n\treturn s * w;\n}\nint main(){\n\tt = read();\n\twhile (t --){\n\t\tn = read(),m = read();\n\t\tfor (ll i = 1;i <= n;i += 1){\n\t\t\tscanf(\"%s\",s + 1);\n\t\t\tfor (ll j = 1;j <= m;j += 1){\n\t\t\t\ta[i][j] = s[j] - '0';\n\t\t\t\tvis[i][j] = 0;\n\t\t\t}\n\t\t}\n\t\tfor (ll i = 1;i <= n;i += 1){\n\t\t\tfor (ll j = 1;j <= m;j += 1){\n\t\t\t\tif (!a[i][j]) break;\n\t\t\t\tvis[i][j] = 1;\n\t\t\t}\n\t\t}\n\t\tfor (ll j = 1;j <= m;j += 1){\n\t\t\tfor (ll i = 1;i <= n;i += 1){\n\t\t\t\tif (!a[i][j]) break;\n\t\t\t\tvis[i][j] = 1;\n\t\t\t}\n\t\t}\n\t\tbool fl = 1;\n\t\tfor (ll i = 1;i <= n && fl;i += 1){\n\t\t\tfor (ll j = 1;j <= m;j += 1){\n\t\t\t\tif (a[i][j] && !vis[i][j]){\n\t\t\t\t\tfl = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tputs(fl ? \"YES\" : \"NO\");\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2090",
    "index": "C",
    "title": "Dining Hall",
    "statement": "Inside the large kingdom, there is an infinite dining hall. It can be represented as a set of cells ($x, y$), where $x$ and $y$ are non-negative integers. There are an infinite number of tables in the hall. Each table occupies four cells ($3x + 1, 3y + 1$), ($3x + 1, 3y + 2$), ($3x + 2, 3y + 1$), ($3x + 2, 3y + 2$), where $x$ and $y$ are arbitrary non-negative integers. All cells that do not belong to any of the tables are corridors.\n\nThere are $n$ guests that come to the dining hall one by one. Each guest appears in the cell $(0, 0)$ and wants to reach a table cell. In one step, they can move to any neighboring by side \\textbf{corridor} cell, and in their \\textbf{last} step, they must move to a neighboring by side a free \\textbf{table} cell. They occupy the chosen table cell, and no other guest can move there.\n\nEach guest has a characteristic $t_i$, which can either be $0$ or $1$. They enter the hall in order, starting to walk from the cell ($0, 0$). If $t_i=1$, the $i$-th guest walks to the nearest vacant table cell. If $t_i=0$, they walk to the nearest table cell that belongs to a completely unoccupied table. Note that other guests may choose the same table later.\n\nThe distance is defined as the smallest number of steps needed to reach the table cell. If there are multiple table cells at the same distance, the guests choose the cell with the smallest $x$, and if there are still ties, they choose among those the cell with the smallest $y$.\n\nFor each guest, find the table cell which they choose.",
    "tutorial": "Original idea from myee has $4$ cases, which is a medium difficulty problem using deletable heap. You may find the original statement in zh-cn on GitHub later. The Codeforces version by FairyWinx has only $2$ cases, in order to meet the difficulty as Div2C. The En/Ru statement changes for times after checking. Sorry for the inconvenience. Firstly we can get the distance of each cell by BFS or Math Way: $d(x,y)=x+y+2[x\\bmod3=y\\bmod3=2]$. The proof is trivial. Then we can sort out the first $4n$ table cell with the lowest distance in $O(n)$ time: by BFS or enumerating possible $d(x,y)=k$. Suppose we record whether a table cell is occupied or not by a bool array. Then we can check whether a cell can be allowed to go by someone $o=0/1$ in $O(1)$ time. Suppose the shortest table cell we can choose is $x_0$ -th and $x_1$ -th ones, then $x_1\\le x_0\\le4n$. We can keep trying the smallest $x_o$ until it's okay. The time complexity is $O(n)$. 2089A - Simple Permutation Idea: QuietBeautifulThoughts",
    "code": "#include <bits/stdc++.h>\n\nusing uint = unsigned;\nusing bol = bool;\n\nconst uint T=2000;\nconst uint R=200000;\n\nuint Ord[R+5];\nuint Nxt(uint p,uint o)\n{\n    uint x=p/T,y=p%T;\n    if(o&1)y=y/3*3+3-y%3;\n    if(o&2)x=x/3*3+3-x%3;\n    return x*T+y;\n}\n\nbol G[2][T*T];uint Ans[2];\n\nint main()\n{\n#ifdef MYEE\n    freopen(\"QAQ.in\",\"r\",stdin);\n    freopen(\"QAQ.out\",\"w\",stdout);\n#endif\n    for(uint i=2,tp=0;i<T&&tp<R;i++)if(i%3==2)\n    {\n        for(uint x=1;x<i&&tp<R;x+=3)Ord[tp++]=x*T+i-x;\n    }\n    else if(!(i%3))\n    {\n        for(uint x=1;x<=i-2&&tp<R;x++)\n            if(x%3==1)Ord[tp++]=x*T+i-x;\n            else if(x%3==2)Ord[tp++]=x*T+i-x-2,Ord[tp++]=x*T+i-x;\n        Ord[tp++]=(i-1)*T+1;\n    }\n    uint t;scanf(\"%u\",&t);\n    while(t--)\n    {\n        uint q;scanf(\"%u\",&q);\n        for(uint i=0;i<q*4;i++)G[0][Ord[i]]=G[1][Ord[i]]=0;\n        Ans[0]=Ans[1]=0;\n        while(q--)\n        {\n            uint t;scanf(\"%u\",&t);while(G[t][Ord[Ans[t]]])Ans[t]++;\n            t=Ord[Ans[t]];printf(\"%u %u\\n\",t/T,t%T);\n            G[1][t]=1;for(uint o=0;o<4;o++)G[0][Nxt(t,o)]=1;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2091",
    "index": "A",
    "title": "Olympiad Date",
    "statement": "The final of the first Olympiad by IT Campus \"NEIMARK\" is scheduled for March 1, 2025. A nameless intern was tasked with forming the date of the Olympiad using digits — 01.03.2025.\n\nTo accomplish this, the intern took a large bag of digits and began drawing them one by one. In total, he drew $n$ digits — the digit $a_i$ was drawn in the $i$-th turn.\n\nYou suspect that the intern did extra work. Determine at which step the intern could have first assembled the digits to form the date of the Olympiad (the separating dots can be ignored), or report that it is impossible to form this date from the drawn digits. Note that leading zeros \\textbf{must be displayed}.",
    "tutorial": "Let's start a digit counter $cnt[i]$ ($0 \\leq i \\leq 9$). At the moment when $3 \\leq cnt[0]$, $1 \\leq cnt[1]$, $2 \\leq cnt[2]$, $1 \\leq cnt[3]$, $1 \\leq cnt[5]$ - the answer is found. If after counting all the digits one of the conditions is not fulfilled, then there is no solution and the answer is $0$. $O(n)$.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    int cnt[10] = {};\n    bool f = 0;\n    \n    for (int i = 0; i < n; i++) {\n        int dig;\n        cin >> dig;\n        cnt[dig]++;\n        if (cnt[0] >= 3 && cnt[1] >= 1 && cnt[2] >= 2 &&\n            cnt[3] >= 1 && cnt[5] >= 1 && !f) {\n                cout << i + 1 << endl;\n                f = 1;\n            }\n    }\n    if (!f) cout << 0 << endl;\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "greedy",
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2091",
    "index": "B",
    "title": "Team Training",
    "statement": "At the IT Campus \"NEIMARK\", there are training sessions in competitive programming — both individual and team-based!\n\nFor the next team training session, $n$ students will attend, and the skill of the $i$-th student is given by a positive integer $a_i$.\n\nThe coach considers a team strong if its strength is at least $x$. The strength of a team is calculated as the number of team members multiplied by the minimum skill among the team members.\n\nFor example, if a team consists of $4$ members with skills $[5, 3, 6, 8]$, then the team's strength is $4 \\cdot min([5, 3, 6, 8]) = 12$.\n\nOutput the maximum possible number of strong teams, given that each team must have at least one participant and every participant must belong to exactly one team.",
    "tutorial": "Let's assume that there are $k$ people in a team and $a[i_1]$ - the student with the lowest skill. Then all other participants will have skill greater than or equal to $a[i_1] \\leq a[i_2], \\ldots a[i_k]$. The greater the value of $a[i_1]$, the fewer people are needed to form a team. In essence, at each stage after sorting in non-increasing order, we choose whether the current student $a_i$ will be the weakest in the team or not. If not, it means that we will put this student aside for now to add someone to the team. If yes, it means that from the put aside students we will add some number so that $x \\leq a_i \\cdot k$, where $k$ - the number of students in the team. With each transition to the next student, the size of the team, if he is the weakest - will monotonically non-decrease. And to maximize the number of strong teams - their size should be the minimum possible, which will be suitable for a strong team. Accordingly, at the moment when we find a student who can be called the weakest in the team, but at the same time the number of team members will allow the team to be strong, then we immediately form such a strong team. $O(n \\space log \\space n)$.",
    "code": "#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve() {\n    int n, x;\n    cin >> n >> x;\n    int a[n];\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    sort(a, a + n);\n    reverse(a, a + n);\n\n    int ans = 0;\n    for (int i = 0, cnt = 1; i < n; i++, cnt++) {\n        if (a[i] * cnt >= x) {\n            ans++;\n            cnt = 0;\n        }\n    }\n    cout << ans << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "dp",
      "greedy",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2091",
    "index": "C",
    "title": "Combination Lock",
    "statement": "At the IT Campus \"NEIMARK\", there are several top-secret rooms where problems for major programming competitions are developed. To enter one of these rooms, you must unlock a circular lock by selecting the correct code. This code is updated every day.\n\nToday's code is a permutation$^{\\text{∗}}$ of the numbers from $1$ to $n$, with the property that in every cyclic shift$^{\\text{†}}$ of it, there is exactly one fixed point. That is, in every cyclic shift, there exists exactly one element whose value is equal to its position in the permutation.\n\nOutput any valid permutation that satisfies this condition. Keep in mind that a valid permutation might not exist, then output $-1$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation is defined as a sequence of length $n$ consisting of integers from $1$ to $n$, where each number appears exactly once. For example, (2 1 3), (1), (4 3 1 2) are permutations; (1 2 2), (3), (1 3 2 5) are not.\n\n$^{\\text{†}}$A cyclic shift of an array is obtained by moving the last element to the beginning of the array. A permutation of length $n$ has exactly $n$ cyclic shifts.\n\\end{footnotesize}",
    "tutorial": "Let after $k$ cyclic shifts the element $p_i$ be at position $(i + k) \\mod n$. For this point to be fixed, it is necessary that $(i + k) \\mod n = p_i$. Let assume that permutation $p$ is starting from $0$, $[0, 1, 2, \\ldots, n - 1]$. From this we get that $k = p_i - i \\ (mod \\ n)$. For any cyclic shift to be a fixed point - it must be possible to obtain any $k$ from $0$ to $n - 1$. Let us sum both sides for all possible values of $k = p_i - i \\ (mod \\ n)$. We get $\\sum_{k=0}^{n - 1} k = \\frac{n \\cdot (n - 1)}{2}$ and $\\sum_{i=0}^{n - 1} (p_i - i) =\\sum_{0=1}^{n - 1} p_i - \\sum_{i=0}^{n - 1} i = 0$. In order to construct a permutation, these sums must be equal modulo $n$, i.e. $\\frac{n \\cdot (n - 1)}{2} = 0 \\ (mod \\ n)$. For even $n$ - this is impossible and the answer is $-1$. And for odd $n$ one of the options - $p = [n, n - 1, \\ldots, 2, 1]$. $O(n)$.",
    "code": "#include <iostream>\n\nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    if (n % 2 == 0) {\n        cout << -1 << endl;\n        return;\n    }\n    for (int i = n; i > 0; i--) {\n        cout << i << ' ';\n    }\n    cout << endl;\n}\n \nint main() {\n    int t = 1;\n    cin >> t;\n    while (t--) \n        solve();\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2091",
    "index": "D",
    "title": "Place of the Olympiad",
    "statement": "For the final of the first Olympiad by IT Campus \"NEIMARK\", a rectangular venue was prepared. You may assume that the venue is divided into $n$ rows, each containing $m$ spots for participants' desks. A total of $k$ participants have registered for the final, and each participant will sit at an individual desk. Now, the organizing committee must choose the locations for the desks in the venue.\n\nEach desk occupies one of the $m$ spots in a row. Moreover, if several desks occupy consecutive spots in the same row, we call such a group of desks a bench, and the number of desks in the group is the bench's length. For example, seating $7$ participants on a $3 \\times 4$ venue (with $n = 3, m = 4$) can be arranged as follows:\n\nIn the figure above, the first row has one bench of length $3$, the second row has one bench of length $2$, and the third row has two benches of length $1$.\n\nThe organizing committee wants to choose the locations so that the length of the longest bench is as small as possible. In particular, the same $7$ desks can be arranged in a more optimal way, so that the lengths of all benches do not exceed $2$:\n\nGiven the integers $n$, $m$, and $k$, determine the minimum possible length of the longest bench.",
    "tutorial": "Let the length of the maximal bench be $x$, then to maximize the number of desks in one row - we need to put as many benches of exactly $x$ length as possible. There should be an indent after each bench, let's say, that the length of the block is $x + 1$. The total number of such blocks in a row will be $\\lfloor \\frac{m}{x + 1} \\rfloor$, and the last bench will have a length of $m \\mod (x + 1)$. Then the number of desks in one row can reach $f(x) = x \\cdot \\lfloor \\frac{m}{x + 1} \\rfloor +(m \\mod (x + 1))$. Since the rows are independent, there should be $k \\leq n \\cdot f(x)$ desks in total. We need to find the minimum $x$, and since $f(x)$ is monotonically non-decreasing, then the answer can be found using binary search. (You can also come up with a formula, we'll leave it as an exercise). $O(log \\ k)$ or $O(1)$.",
    "code": "#include <iostream>\n \nusing namespace std;\n \nvoid solve() {\n    long long n, m, k, l, r, mid;\n    cin >> n >> m >> k;\n    l = 0, r = m;\n    \n    while (l + 1 < r) {\n        mid = (l + r) / 2;\n        if ((m / (mid + 1) * mid + m % (mid + 1)) * n >= k) {\n            r = mid;\n        } else {\n            l = mid;\n        }\n    }\n    \n    cout << r << endl;\n} \n \nint main() {\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    \n}",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2091",
    "index": "E",
    "title": "Interesting Ratio",
    "statement": "Recently, Misha at the IT Campus \"NEIMARK\" camp learned a new topic — the Euclidean algorithm.\n\nHe was somewhat surprised when he realized that $a \\cdot b = lcm(a, b) \\cdot gcd(a, b)$, where $gcd(a, b)$ — is the greatest common divisor (GCD) of the numbers $a$ and $b$ and $lcm(a, b)$ — is the least common multiple (LCM). Misha thought that since the product of LCM and GCD exists, it might be interesting to consider their quotient: $F(a,b)=\\frac{lcm(a, b)}{gcd(a, b)}$.\n\nFor example, he took $a = 2$ and $b = 4$, computed $F(2, 4) = \\frac{4}{2} = 2$ and obtained a prime number (a number is prime if it has exactly two divisors)! Now he considers $F(a, b)$ to be an interesting ratio if $a < b$ and $F(a, b)$ is a prime number.\n\nSince Misha has just started studying number theory, he needs your help to calculate — how many different pairs of numbers $a$ and $b$ are there such that $F(a, b)$ is an interesting ratio and $1 \\leq a < b \\leq n$?",
    "tutorial": "Let $a = gcd(a, b) \\cdot x$, $b = gcd(a, b) \\cdot y$ for some $x$ and $y$. Now $F(a,b)=\\frac{lcm(a, b)}{gcd(a, b)} = \\frac{a \\cdot b}{ gcd(a,b)^2} = x \\cdot y$. Since $F(a,b)$ - is a prime number, then $x \\cdot y$ - is a prime number. For $x \\cdot y$ to be a prime number, then one of the numbers must be prime and the other must be equal to $1$. We have the condition that $a < b$, which means that $x = 1$, and $y$ - is a prime number. We get that $a = gcd(a, b)$, $b = gcd(a, b) \\cdot y$, where $y$ - is a prime number. The problem becomes the following - count pairs $(a,b)$ such that $1 \\leq gcd(a,b) < gcd(a,b) \\cdot y \\leq n$. Let's fix $y$, then $gcd(a,b)$ can take any value from $1$ to $\\lfloor \\frac{n}{y} \\rfloor$. Thus, for each prime $y$, the number of suitable pairs $(a, b)$ is $\\lfloor \\frac{n}{y} \\rfloor$. It remains to enumerate all prime numbers up to $n$. With the constraint $n \\leq 10^7$, this can be done using the sieve of Eratosthenes. $O(n \\ log \\ log \\ n)$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int MAXN = 10000001;\nbool prime[MAXN];\n\nvoid solve() {\n    int n, ans = 0;\n    cin >> n;\n    \n    for (int i = 2; i <= n; i++) {\n        if (prime[i]) {\n            ans += n / i;\n        }\n    }\n    \n    cout << ans << endl;\n}\n\nint main() {\n    for (int i = 0; i < MAXN; i++) prime[i] = 1;\n    prime[0] = prime[1] = 0;\n\tfor (int i = 2; i * i < MAXN; i++) {\n\t    if (!prime[i]) continue;\n\t    for (int j = i * i; j < MAXN; j += i) \n            prime[j] = 0;\n\t}\n\t\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "brute force",
      "math",
      "number theory",
      "two pointers"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2091",
    "index": "F",
    "title": "Igor and Mountain",
    "statement": "The visitors of the IT Campus \"NEIMARK\" are not only strong programmers but also physically robust individuals! Some practice swimming, some rowing, and some rock climbing!\n\nMaster Igor is a prominent figure in the local rock climbing community. One day, he went on a mountain hike to ascend one of the peaks. As an experienced climber, Igor decided not to follow the established trails but to use his skills to climb strictly vertically.\n\nIgor found a rectangular vertical section of the mountain and mentally divided it into $n$ horizontal levels. He then split each level into $m$ segments using vertical partitions. Upon inspecting these segments, Igor discovered convenient protrusions that can be grasped (hereafter referred to as holds). Thus, the selected part of the mountain can be represented as an $n \\times m$ rectangle, with some cells containing holds.\n\nBeing an experienced programmer, Igor decided to count the number of valid routes. A route is defined as a sequence of \\textbf{distinct} holds. A route is considered valid if the following conditions are satisfied:\n\n- The first hold in the route is located on the very bottom level (row $n$);\n- The last hold in the route is located on the very top level (row $1$);\n- Each subsequent hold is not lower than the previous one;\n- At least one hold is used on each level (i.e., in every row of the rectangle);\n- At most two holds are used on each level (since Igor has only two hands);\n- Igor can reach from the current hold to the next one if the distance between the centers of the corresponding sections does not exceed Igor's arm span.\n\nIgor's arm span is $d$, which means he can move from one hold to another if the \\textbf{Euclidean distance} between the centers of the corresponding segments does not exceed $d$. The distance between sections ($i_1, j_1$) and ($i_2, j_2$) is given by $\\sqrt{(i_1 - i_2) ^ 2 + (j_1 - j_2) ^ 2}$.\n\nCalculate the number of different valid routes. Two routes are considered different if they differ in the list of holds used or in the order in which these holds are visited.",
    "tutorial": "Let's use the dynamic programming method $dp[i][j][f]$: $i$ - row number. $j$ - column number. $f = 0$ means that exactly one hold has already been selected in the current row, and a second one can still be added (since there are a maximum of two holds per level). $f = 1$ means that two holds have already been used in this level. $dp[i][j][f]$ - the number of ways to construct a correct route starting with a hold in cell $(i,j)$, given that $f + 1$ holds are already used in row $i$. For a cell $(i,j)$ with a hold (i.e. $s[i][j] =$ 'X'): At the lower level, i.e. $i = n - 1$, this hold can serve as the start of the route, so all such $dp[n - 1][j][f] = 1$. If one hold $f = 0$ is already selected at the current level, then you can take the second hold at the same level at a distance of no more than $d$, i.e. $dp[i][j][f]= dp[i][j][f] + \\sum_{y = j - d}^{j + d}{dp[i][y][1]} - dp[i][j][1]$ (let's not forget to exclude the point $(i, j)$ from the sum, so as not to count it twice). The transition to the next level (if possible) $i$ in $i+1$ takes a vertical distance equal to $1$. So the range of $j$ for the transition will be $[j - dx, j + dx]$, where $dx = \\lfloor \\sqrt{d^2 - 1^2} \\rfloor = d - 1$$dp[i][j][f]= dp[i][j][f] + \\sum_{y = j - dx}^{j + dx}{dp[i + 1][y][0]}$ $dp[i][j][f]= dp[i][j][f] + \\sum_{y = j - dx}^{j + dx}{dp[i + 1][y][0]}$ This solution recalculates each state in $O(d)$, to make it more efficient - you need to use prefix sums. $O(n \\cdot m)$.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nconst int MAXN = 2010;\nconst int MOD = 998244353;\n\nstring s[MAXN];\nint dp[MAXN][MAXN][2];\nlong long sdp[MAXN][MAXN][2];\n\nint n, m, d;\n\nlong long getsum(int x, int y1, int y2, int f) {\n    long long res = sdp[x][y2][f];\n    if (y1) res -= sdp[x][y1 - 1][f];\n    return res;\n}\n\nint get(int i, int j, int f) {\n    if (s[i][j] != 'X') return 0;\n    long long res = 0;\n    if (i == n - 1) res++;\n\n    if (!f) {\n        res += getsum(i, max(0, j - d),\n                      min(m - 1, j + d), 1);\n        res -= dp[i][j][1];\n    }\n\n    if (i < n - 1) {\n        res += getsum(i + 1, max(0, j - d + 1),\n                      min(m - 1, j + d - 1), 0);\n    }\n\n    return res % MOD;\n}\n\nvoid solve() {\n\n    cin >> n >> m >> d;\n    for (int i = 0; i < n; i++) {\n        cin >> s[i];\n    }\n    for (int i = n - 1; i >= 0; i--) {\n        for (int f = 1; f >= 0; f--) {\n            for (int j = 0; j < m; j++) {\n                sdp[i][j][f] = dp[i][j][f] = get(i, j, f);\n            }\n            for (int j = 1; j < m; j++) {\n                sdp[i][j][f] += sdp[i][j - 1][f];\n            }\n        }\n    }\n\n    long long ans = 0;\n    for (int j = 0; j < m; j++) {\n        ans += dp[0][j][0];\n    }\n\n    cout << ans % MOD << endl;\n\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "dp"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2091",
    "index": "G",
    "title": "Gleb and Boating",
    "statement": "Programmer Gleb frequently visits the IT Campus \"NEIMARK\" to participate in programming training sessions.\n\nNot only is Gleb a programmer, but he is also a renowned rower, so he covers part of his journey from home to the campus by kayaking along a river. Assume that Gleb starts at point $0$ and must reach point $s$ (i.e., travel $s$ meters along a straight line). To make the challenge tougher, Gleb has decided not to go outside the segment $[0, s]$. The dimensions of the kayak can be neglected.\n\nGleb is a strong programmer! Initially, his power is $k$. Gleb's power directly affects the movement of his kayak. If his current power is $x$, then with one paddle stroke the kayak moves $x$ meters in the current direction. Gleb can turn around and continue moving in the opposite direction, but such a maneuver is quite challenging, and after each turn, his power decreases by $1$. The power can never become $0$ — if his current power is $1$, then even after turning it remains $1$. Moreover, Gleb cannot make two turns in a row — after each turn, he must move at least once before making another turn. Similarly, Gleb cannot make a turn immediately after the start — he must first perform a paddle stroke.\n\nGleb wants to reach point $s$ from point $0$ without leaving the segment $[0, s]$ and while preserving as much power as possible. Help him — given the value $s$ and his initial power $k$, determine the maximum possible power he can have upon reaching point $s$.",
    "tutorial": "Let's consider a simple solution - we will iterate through Gleb's current strength $t$, from $k$ to $1$, and check which positions can be reached using that strength value. For each fixed $t$, the set of positions can be obtained by any search method, for example, breadth-first search. Next, let's assume that Gleb has turned around and we will start a search from all reached positions with strength $t-1$ and in the opposite direction. For one strength value, such a search works in the worst case in $O(s)$, so the overall complexity of the algorithm will be $O(s \\cdot k)$ (which, of course, will take too long) and will require $O(s)$ memory. Now we need to speed up this solution. First, we need to solve the problem for very large values of $s$. It is not difficult to prove that if $k \\geq 3$, then for $s > k^2$, the answer to the problem will be $k$ or $k-2$. Indeed, let's assume that Gleb with strength $k$ has reached the maximum possible position on the segment. Next, he turns around, takes one step back (with strength $k-1$). Let's find the position where Gleb will end up if he turns around and moves to the right with strength $k-2$ until he crosses the boundary $s$ (including the assumption that he can swim beyond $s$). Let this position be $s + r$, where $0 \\leq r < k - 2$. Then, Gleb would need to take another $r$ steps to the left with strength $k-1$ before the second turn; in this case, he will end up exactly at point $s$ with strength $k-2$. For this maneuver, he will need a distance of at most $k + (r+1) \\cdot (k-1) < k + (k-1)^2 < k^2$. Thus, for $s \\geq k^2$, we can obtain either the answer $k$ (which can be checked by simple division) or the answer $k-2$ (we print it if the answer $k$ is not possible). It is also easy to see that this statement remains true when starting from any point from $0$ to $s$. Next, we will assume that $s \\leq k^2$. Let the answer to the problem be $ans$. Then, if in the algorithm described above we stop the iteration upon reaching point $s$ for some $t$, the total running time will be $O(s \\cdot (k - ans))$. Considering the above, we can assert that $ans \\geq \\sqrt{s} - 3$ (due to the even number of turns, the answer $\\sqrt{s} - 2$ may not be suitable). Then the running time of the algorithm does not exceed $T = (k - \\sqrt{s}) \\cdot s$ We can rewrite this value as follows: $(k - \\sqrt{s}) \\cdot s = (k - \\sqrt{s}) \\cdot (\\sqrt{s})^2 = \\frac{(2 \\cdot k - 2 \\cdot \\sqrt{s}) \\cdot \\sqrt{s} \\cdot \\sqrt{s}}{2}$ Next, we note that the sum of the factors in the numerator equals $2 \\cdot k$, meaning that the maximum value is achieved when they are equal (see, for example, Karamata's inequality). We obtain that: $T \\leq \\frac{1}{2} \\cdot \\left(\\frac{2 \\cdot k}{3}\\right)^3 = \\frac{4 \\cdot k^3}{27}$ which is already fast enough to pass all tests. In practice, even in the worst case, the specified algorithm requires even fewer operations and comfortably fits within the time limits.",
    "code": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint s, k, p;\nvector<bool> was1, was2;\n\nvoid bfs() {\n    vector<int> v;\n    for (int i = 0; i < s; i++) {\n        if (was1[i])\n            v.push_back(i);\n    }\n\n    int q = 0;\n    while (q < v.size()) {\n        int x = v[q++];\n        int y = x + p * k;\n        if (y >= 0 && y <= s && !was1[y]) {\n            was1[y] = 1;\n            v.push_back(y);\n        }\n    }\n}\n\nvoid solve() {\n    cin >> s >> k;\n    if (s % k == 0) {\n        cout << k << endl;\n        return;\n    }\n    if (s > k * k) {\n        cout << max(1, k - 2) << endl;\n        return;\n    }\n\n    was1.resize(s + 1);\n    was2.resize(s + 1);\n    for (int i = 0; i <= s; i++) {\n        was1[i] = was2[i] = 0;\n    }\n\n    p = 1;\n    was1[k] = 1;\n    while (1) {\n        bfs();\n        if (was1[s]) {\n            cout << k << endl;\n            return;\n        }\n        k = max(k - 1, 1);\n        p *= -1;\n        for (int i = 0; i <= s; i++) {\n            was2[i] = 0;\n        }\n        for (int i = 0; i < s; i++) {\n            if (was1[i]) {\n                if (i + p * k >= 0 && i + p * k <= s) {\n                    was2[i + p * k] = 1;\n                }\n            }\n        }\n        swap(was1, was2);\n    }\n\n\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "data structures",
      "dp",
      "graphs",
      "greedy",
      "math",
      "number theory",
      "shortest paths"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2092",
    "index": "A",
    "title": "Kamilka and the Sheep",
    "statement": "Kamilka has a flock of $n$ sheep, the $i$-th of which has a beauty level of $a_i$. All $a_i$ are distinct. Morning has come, which means they need to be fed. Kamilka can choose a non-negative integer $d$ and give each sheep $d$ bunches of grass. After that, the beauty level of each sheep increases by $d$.\n\nIn the evening, Kamilka must choose \\textbf{exactly two} sheep and take them to the mountains. If the beauty levels of these two sheep are $x$ and $y$ (after they have been fed), then Kamilka's pleasure from the walk is equal to $\\gcd(x, y)$, where $\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\nThe task is to find the maximum possible pleasure that Kamilka can get from the walk.",
    "tutorial": "It's always possible to make Kamilka's pleasure at least $|x - y|$ for any $x, y \\in a$. First of all, it can be observed that for any two sheep with beauty levels $x < y$, the maximum possible pleasure cannot exceed $y - x$, since $\\gcd(x, y) = \\gcd(x, y - x)$. Secondly, we can choose $x = \\min(a)$, $y = \\max(a)$, and $d = -x \\bmod (y - x)$, achieving a pleasure of $\\max(a) - \\min(a)$. Thus, the answer is $\\max(a) - \\min(a)$.",
    "code": "t = int(input())\n \nfor test in range(t):\n    n = int(input())\n    a = [int(i) for i in input().split()]\n    print(max(a) - min(a))\n\n",
    "tags": [
      "greedy",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2092",
    "index": "B",
    "title": "Lady Bug",
    "statement": "As soon as Dasha Purova crossed the border of France, the villain Markaron kidnapped her and placed her in a prison under his large castle. Fortunately, the wonderful Lady Bug, upon hearing the news about Dasha, immediately ran to save her in Markaron's castle. However, to get there, she needs to crack a complex password.\n\nThe password consists of two bit strings $a$ and $b$, each of which has a length of $n$. In one operation, Lady Bug can choose any index $2 \\le i \\le n$ and perform one of the following actions:\n\n- swap($a_i$, $b_{i-1}$) (swap the values of $a_i$ and $b_{i-1}$), or\n- swap($b_i$, $a_{i-1}$) (swap the values of $b_i$ and $a_{i-1}$).\n\nLady Bug can perform any number of operations. The password is considered cracked if she can ensure that the first string consists only of zeros. Help her understand whether or not she will be able to save the unfortunate Dasha.",
    "tutorial": "Note that you can split strings $a$ and $b$ into two \"zig-zags\": $a_0, b_1, a_2, b_3, \\dots$ and $b_0, a_1, b_2, a_3, \\dots$ What are the necessary and sufficient conditions for each of these zig-zags? Note that you can split strings $a$ and $b$ into two \"zig-zags\": $a_0, b_1, a_2, b_3, \\dots$ and $b_0, a_1, b_2, a_3, \\dots$. For each of these zig-zags, you can achieve any sequence of 0s and 1s, provided that their quantities within the zig-zag are preserved. Therefore, the answer is Yes if and only if the number of 0 is at least $\\lceil \\frac{n}{2} \\rceil$ in the first zig-zag and at least $\\lfloor \\frac{n}{2} \\rfloor$ in the second one.",
    "code": "t = int(input())\n \nfor test in range(t):\n    n = int(input())\n    a = input()\n    b = input()\n    cnt1, cnt2 = 0, 0\n    for i in range(n):\n        if i % 2:\n            cnt2 += (a[i] == '0')\n            cnt1 += (b[i] == '0')\n        else:\n            cnt1 += (a[i] == '0')\n            cnt2 += (b[i] == '0')\n \n    if cnt1 >= (n + 1) // 2 and cnt2 >= n // 2:\n        print(\"Yes\")\n    else:\n        print(\"No\")\n\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "implementation",
      "math"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2092",
    "index": "C",
    "title": "Asuna and the Mosquitoes",
    "statement": "For her birthday, each of Asuna's $n$ admirers gifted her a tower. The height of the tower from the $i$-th admirer is equal to $a_i$.\n\nAsuna evaluates the beauty of the received gifts as $\\max(a_1, a_2, \\ldots, a_n)$. She can perform the following operation an arbitrary number of times (possibly, zero).\n\n- Take such $1 \\le i \\neq j \\le n$ that $a_i + a_j$ is odd and $a_i > 0$, then decrease $a_i$ by $1$ and increase $a_j$ by $1$.\n\nIt is easy to see that the heights of the towers remain non-negative during the operations. Help Asuna find the maximum possible beauty of the gifts after any number of operations!",
    "tutorial": "Consider two cases: first, when all numbers have the same parity; and second, when there is at least one even and one odd number. Let $S$ be the sum of all numbers, and $k$ be the number of odd numbers in the array. Then, in the second case, the answer is $S - k + 1$. Case 1. All numbers in $a$ have the same parity. In this case, it is impossible to perform any operation, so the answer is $\\max(a)$. Case 2. There is at least one even and one odd number. Let $S$ be the sum of all numbers, and $k$ be the number of odd numbers in the array. We will now prove that the answer is $S - k + 1$. First of all, the answer cannot exceed $S - k + 1$, since the number of odd elements in the array remains unchanged after performing the operation. Secondly, we will show that $S - k + 1$ is always achievable. Consider an arbitrary odd number $A \\in a$. We can then merge all even numbers into $A$ $\\left( \\text{i.e.} \\ (A, 2k) \\to (A + 2k, 0) \\right)$, resulting in an array consisting of the number $A + 2m$, $k-1$ odd numbers, and zeros for the remaining elements (here $2m$ denotes the sum of all even numbers in the initial array). After this step, for each remaining odd number, we can sacrifice one unit by transferring it to any zero element in the array and then merge the resulting even number into $A$. It's easy to see that there will always be at least one zero available in the array before merging each odd number. Eventually, we will obtain an array consisting of one element equal to $S - k + 1$, $k - 1$ elements equal to one, and zeros filling the remaining positions. Therefore, the answer in this case will be $S-k+1$.",
    "code": "t = int(input())\n \nfor test in range(t):\n    n = int(input())\n    a = [int(i) for i in input().split()]\n    ans, cnt = 0, 0\n    for i in a:\n        ans += i\n        cnt += i % 2\n        \n    if not cnt or cnt == n:\n        print(max(a))\n    else:\n        print(ans - cnt + 1)\n\n",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2092",
    "index": "D",
    "title": "Mishkin Energizer",
    "statement": "In anticipation of a duel with his old friend Fernan, Edmond is preparing an energy drink called \"Mishkin Energizer\". The drink consists of a string $s$ of length $n$, made up only of the characters L, I, and T, which correspond to the content of three different substances in the drink.\n\nWe call the drink balanced if it contains an equal number of all substances. To boost his aura and ensure victory in the duel, Edmond must make the initial string balanced by applying the following operation:\n\n- Choose an index $i$ such that $s_i \\neq s_{i+1}$ (where $i + 1$ must not exceed the \\textbf{current} size of the string).\n- Insert a character $x$, either L, I, or T, between them such that $x \\neq s_i$ and $x \\neq s_{i+1}$.\n\nHelp Edmond make the drink balanced and win the duel by performing \\textbf{no more than $\\textbf{2n}$ operations}. If there are multiple solutions, any one of them can be output. If it is impossible, you must report this.",
    "tutorial": "It is impossible to balance the string if and only if all its letters are the same. It is clear that there is no solution if all the letters in $s$ are the same. Let us now prove that a solution always exists in all other cases. While the string remains unbalanced, let us assume that $\\text{cnt}(a) \\le \\text{cnt}(b) \\le \\text{cnt}(c)$, where $a, b, c \\in \\lbrace \\tt{L}, \\tt{I}, \\tt{T} \\rbrace$, and $\\text{cnt}(l)$ denotes the number of occurrences of the letter $l$ in $s$. Consider two cases: The string $s$ contains the substring bc or cb. In this case, we can perform the operation on it to obtain bac or cab. The string $s$ contains the substring bc or cb. In this case, we can perform the operation on it to obtain bac or cab. Otherwise, the string $s$ must contain the substring ca or ac. Without loss of generality, assume that $s$ contains ca. Then we can perform the following sequence of operations: ca $\\to$ cba $\\to$ cbca $\\to$ cbaca $\\to$ cabaca. Otherwise, the string $s$ must contain the substring ca or ac. Without loss of generality, assume that $s$ contains ca. Then we can perform the following sequence of operations: ca $\\to$ cba $\\to$ cbca $\\to$ cbaca $\\to$ cabaca. It can be observed that after each operation, the value of $2 \\cdot \\text{cnt}(c) - \\text{cnt}(b) - \\text{cnt}(a)$ decreases by one. Here, $a$, $b$, and $c$ are always chosen such that $\\text{cnt}(a) \\le \\text{cnt}(b) \\le \\text{cnt}(c)$. Therefore, the algorithm is guaranteed to terminate, and it does so when $2 \\cdot \\text{cnt}(c) - \\text{cnt}(b) - \\text{cnt}(a) = 0$, which implies $\\text{cnt}(a) = \\text{cnt}(b) = \\text{cnt}(c)$. It remains to prove that the number of operations performed by the proposed algorithm does not exceed $2n$. Assume that initially $x = \\text{cnt}(a), y = \\text{cnt}(b), z = \\text{cnt}(c)$, where $\\text{cnt}(a) \\le \\text{cnt}(b) \\le \\text{cnt}(c)$. Then $x + y + z = n$. While $\\text{cnt}(a) < \\text{cnt}(b)$, we increment $\\text{cnt}(a)$ by one in each step, using no more than $4$ operations per step. Therefore, this phase requires at most $4(y - x)$ operations. Afterwards, the algorithm alternately increments $\\text{cnt}(a)$ and $\\text{cnt}(b)$ by one until both become equal to $\\text{cnt}(c)$. I claim that this phase will use the $4$-operations sequence (i.e., the second case in the algorithm) at most once. Indeed, let us consider the first time we perform the transformation ca $\\to$ cabaca. It is easy to see that all subsequent steps will involve only single-operation transformations. Thus, this phase requires no more than $2(z - y) + 3$ operations. Summing up, the total number of operations is bounded above by $4(y - x) + 2(z - y) + 3 = 2z + 2y - 4x + 3$. If $x \\neq 0$, this number is less than $2n$ given that $n = x + y + z$. Otherwise, the first step of the algorithm will be either bc $\\to$ bac or cb $\\to$ cab, requiring only one operation. This improves the estimate for the number of operations in the first phase from $4(y-x)$ to $4(y - x) - 3$. As a result, in the case where $x = 0$, the total number of operations does not exceed $4(y - x) - 3 + 2(z-y) + 3 = 2z + 2y = 2n$. We assume that a solution exists (refer to the beginning of the first solution). Now, at each step, let's greedily find the first position where the rarest letter can be inserted and place it there. If no such position exists during a given iteration, we insert the most frequent letter instead. The algorithm terminates when all letters occur the same number of times. We claim that this greedy strategy performs no more than $2n$ operations. Assume that initially $x = \\text{cnt}(a), y = \\text{cnt}(b), z = \\text{cnt}(c)$, where $\\text{cnt}(a) \\le \\text{cnt}(b) \\le \\text{cnt}(c)$. Then $x + y + z = n$. Here, $\\text{cnt}(l)$ denotes the number of occurrences of the letter $l$ in $s$. Claim 1. If the rarest letter cannot be inserted, there always exists a position where the most frequent letter can be inserted. Suppose not. Then every pair of distinct adjacent letters must contain both a and c. This would imply that the number of bs is zero, which contradicts the condition $y \\ge x$. Claim 2. If $x = y$, the solution can always be obtained in exactly $(z - x) + (z - y) = 2z - x - y$ operations. Let's find the first position $i$ such that $s_i \\ne s_{i+1}$ and either $s_i$ or $s_{i+1}$ is c. Without loss of generality, assume the substring is of the form cb.... Then, the algorithm performs the following sequence of operations: cb... $\\to$ cab... $\\to$ cbab... $\\to$ cabab $\\to$ $\\dots$ $\\to$ cbababab... Since every two iterations increase the counts of both a and b by one, we will reach a count of $z$ in exactly the required number of steps. Now consider the case when $x < y$. Observe that in two operations, the algorithm increases the count of the rarest letter by one and increases the count of the most frequent letter by at most one. This is true because, after inserting the most frequent letter, we obtain a substring like bc. It is easy to see that a can be inserted into it, and the algorithm, being greedy, will do exactly that. After some number of iterations, $x$ becomes equal to $y$ (note that $y$ remains unchanged throughout the algorithm). Then, by the reasoning above, the final value of $z' = \\text{cnt}(c)$ satisfies: $z' \\le z + (y - x)$ Applying Claim 2, we get that the total number of operations does not exceed $((z + (y - x)) - y) + ((z + (y - x)) - x) = 2z + y - 3x \\le 2n$",
    "code": "#include <vector>\n#include <string>\n#include <iostream>\n#include <set>\n#include <map>\nusing namespace std;\n \nvector<char> a = {'L', 'I', 'T'};\n \nint main() {\n    int t; cin >> t;\n    while (t--) {\n        int n; cin >> n;\n        string s; cin >> s;\n        set<char> se;\n        for (auto u : s) se.insert(u);\n        if (se.size() == 1) {\n            cout << -1 << endl;\n            continue;\n        }\n        vector<int> ans;\n        map<char, int> mp;\n        for (auto u : s) {\n            mp[u]++;\n        }\n        auto func = [&](int i) {\n            for (auto u : a) {\n                if (s[i] != u && s[i + 1] != u) return u;\n            }\n            return '$';\n        };\n        while (max({mp['L'], mp['I'], mp['T']}) != min({mp['L'], mp['I'], mp['T']})) {\n            int mn = min({mp['L'], mp['I'], mp['T']});\n            int mx = max({mp['L'], mp['I'], mp['T']});\n            int ok = 0;\n            for (int i = 0; i < s.size() - 1; i++) {\n                char x = func(i);\n                if (s[i] != s[i + 1] && mp[x] == mn) {\n                    mp[x]++;\n                    ok = 1;\n                    s.insert(s.begin() + i + 1, x);\n                    ans.push_back(i);\n                    break;\n                }\n            }\n            if (!ok) {\n                for (int i = 0; i < s.size() - 1; i++) {\n                    char x = func(i);\n                    if (s[i] != s[i + 1] && mp[x] == mx) {\n                        mp[x]++;\n                        s.insert(s.begin() + i + 1, x);\n                        ans.push_back(i);\n                        ok = 1;\n                        break;\n                    }\n                }\n            }\n        }\n        cout << ans.size() << endl;\n        for (auto u : ans) {\n            cout << u + 1 << endl;\n        }\n    }\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "implementation",
      "strings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2092",
    "index": "E",
    "title": "She knows...",
    "statement": "D. Pippy is preparing for a \"black-and-white\" party at his home. He only needs to repaint the floor in his basement, which can be represented as a board of size $n \\times m$.\n\nAfter the last party, the entire board is painted green, except for some $k$ cells $(x_1, y_1), (x_2, y_2), \\ldots, (x_k, y_k)$, each of which is painted either white or black. For the upcoming party, D. Pippy wants to paint \\textbf{each} of the remaining green cells either black or white. At the same time, he wants the number of pairs of adjacent cells with different colors on the board to be even after repainting.\n\nFormally, if $$A = \\left\\{((i_1, j_1), (i_2, j_2)) \\ | \\ 1 \\le i_1, i_2 \\le n, 1 \\le j_1, j_2 \\le m, i_1+j_1<i_2+j_2, |i_1-i_2|+|j_1-j_2| = 1, \\operatorname{color}(i_1, j_1) \\neq \\operatorname{color}(i_2, j_2) \\right\\},$$ where $\\operatorname{color}(x, y)$ denotes the color of the cell $(x, y)$, then it is required that $|A|$ be even.\n\nHelp D. Pippy find the number of ways to repaint the floor so that the condition is satisfied. Since this number can be large, output the remainder of its division by $10^9 + 7$.",
    "tutorial": "If a cell has an even number of neighbours, does its color matter? Let $S$ be the set of cells that have an odd number of neighbouring cells. It is easy to observe that $S$ consists of border cells, excluding the corner ones. More precisely, $S = \\{(i, j) \\ \\vert \\ \\left( i \\in \\{1, n\\} \\right) \\ \\bigoplus \\ \\left( j \\in \\{1, m\\} \\right) = 1 \\}$ Idea 1. I claim that the number of adjacent border cell pairs with different colors is even. Indeed, if we walk along the border-which essentially forms a cycle-starting and ending at $(1, 1)$, we must change color an even number of times. Idea 2. It can be observed that the parity of $|A|$ does not change when flipping the color of any cell not in $S$, since such a cell has an even number of neighbouring cells. Therefore, if we fix the coloring of the border cells, the parity of $|A|$ remains unchanged if we imagine recoloring all non-border cells white. This implies that the parity of $|A|$ depends solely on the parity of the number of black (or white) cells in $S$. Moreover, it can be seen that these parities are actually equal. Idea 3. Now, we are left with counting the number of colorings such that $|S|$ contains an even number of black cells. Let's consider two cases: All cells in $S$ are initially colored. In this case, the answer is $2^{n \\cdot m - k}$ if the number of black cells in $S$ is even, and $0$ otherwise, since the colors of the remaining cells do not affect the parity. All cells in $S$ are initially colored. In this case, the answer is $2^{n \\cdot m - k}$ if the number of black cells in $S$ is even, and $0$ otherwise, since the colors of the remaining cells do not affect the parity. At least one cell in $S$ is uncolored. In this case, the answer is $2^{n \\cdot m - k - 1}$. This follows from the basic identity of the binomial coefficients: At least one cell in $S$ is uncolored. In this case, the answer is $2^{n \\cdot m - k - 1}$. This follows from the basic identity of the binomial coefficients: $C^0_n + C^2_n + C^4_n + \\dots = C^1_n + C^3_n + C^5_n + \\dots$",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nusing ll = long long;\nconst ll mod = 1000000007;\n \nll binpow (ll a, ll n) {\n    ll res = 1;\n    while (n) {\n        if (n & 1) {\n            res *= a; res %= mod;\n        }\n        a *= a; a %= mod; n >>= 1;\n    }\n    return res;\n}\n \nvoid solve() {\n    ll n, m, k; cin >> n >> m >> k;\n    int good = 0, sum = 0;\n    for (int i = 0; i < k; ++i) {\n        int x, y, c; cin >> x >> y >> c;\n        if ((x == 1 && y == 1) || (x == 1 && y == m) || (x == n && y == 1) || (x == n && y == m)) continue;\n        if (x == 1 || y == 1 || x == n || y == m) {\n            ++good; sum += c;\n        }\n    }\n    if (good == 2 * (n + m - 4)) {\n        cout << (sum % 2 ? 0 : binpow(2, n * m - k)) << '\\n';\n    } else {\n        cout << binpow(2, n * m - k - 1) << '\\n';\n    }\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int t; cin >> t;\n    while (t--) solve();\n}\n\n",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "graphs",
      "math"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2092",
    "index": "F",
    "title": "Andryusha and CCB",
    "statement": "Let us define the beauty of a binary string $z$ as the number of indices $i$ such that $1 \\le i < |z|$ and $z_i \\neq z_{i+1}$.\n\nWhile waiting for his friends from the CCB, Andryusha baked a pie, represented by a binary string $s$ of length $n$. To avoid offending anyone, he wants to divide this string into $k$ substrings such that each digit belongs to exactly one substring, and the beauties of all substrings are the same.\n\nAndryusha does not know the exact number of friends from the CCB who will come to his house, so he wants to find the number of values of $k$ for which it is possible to split the pie into exactly $k$ parts with equal beauties.\n\nHowever, Andryusha's brother, Tristan, decided that this formulation of the problem is too simple. Therefore, he wants you to find the number of such values of $k$ \\textbf{for each prefix of the string}. In other words, for each $i$ from $1$ to $n$, you need to find the number of values of $k$ for which it is possible to split the prefix $s_1 s_2 \\ldots s_i$ into exactly $k$ parts with equal beauties.",
    "tutorial": "It is sufficient to consider only two types of blocks of consecutive 0s and 1s: those of size $1$ and those of size greater than $1$. For a fixed beauty value $m$ of a substring, there are $O\\left(\\frac{sz}{m}\\right)$ possible values of $k$, where $sz$ is the number of blocks of consecutive 0s and 1s. For a fixed pair $(m, k)$, let $S$ be the set of indices $i$ such that it is possible to divide the prefix $[1, i]$ of the string into $k$ substrings of beauty $m$. It is claimed that $S$ forms a continuous segment $[l, r]$ for some $1 \\le l \\le r \\le sz$. First, note that it is sufficient to consider only two types of blocks of consecutive 0s and 1s: those of size $1$ and those of size greater than $1$. Based on this, we construct a new string of length $sz$, consisting of characters 1 and 2, representing the types of blocks. For example, for the original string 00101110, the new string is 21121. Let's fix a value of $m$-the desired beauty of the substrings we are dividing the string into. It is easy to see that there are $O\\left(\\frac{sz}{m}\\right)$ possible values of $k$ (the number of substrings). Now, for a fixed pair $(m, k)$, let $S_k$ be the set of indices $i$ such that it is possible to divide the prefix $[1, i]$ of the new string (representing block types) into $k$ substrings of beauty $m$. It is claimed that $S_k$ forms a continuous segment $[l, r]$ for some $1 \\le l \\le r \\le sz$. Let's prove this by induction. Base case ($k = 1$). We set $l = m$, $r = m$ (0-based indexing). Inductive step ($k \\rightarrow k + 1$). Suppose that for every index $i \\in [l, r]$, the first $i$ blocks can be divided into $k$ substrings of beauty $m$. Then we can construct a valid division into $k+1$ substrings by: Simply appending a new substring of length $m+1$ starting at block $i+1$, giving us a new upper bound at $i + m + 1$. Simply appending a new substring of length $m+1$ starting at block $i+1$, giving us a new upper bound at $i + m + 1$. Additionally, if block $i$ is of type $2$, we can split it between the $k$-th and $(k+1)$-th substrings, allowing us to finish the $k$-th substring earlier and start the $(k+1)$-th within the same block. This enables us to reach $i + m$ as well. Additionally, if block $i$ is of type $2$, we can split it between the $k$-th and $(k+1)$-th substrings, allowing us to finish the $k$-th substring earlier and start the $(k+1)$-th within the same block. This enables us to reach $i + m$ as well. Thus, we conclude: $S_{k+1} = [l + m, r + m + 1]$ if the $l$-th block is of type 2. $S_{k+1} = [l + m, r + m + 1]$ if the $l$-th block is of type 2. Otherwise, $S_{k+1} = [l + m + 1, r + m + 1]$. Otherwise, $S_{k+1} = [l + m + 1, r + m + 1]$. To compute the full solution, we iterate over all values of $m$ from $1$ to $sz - 1$. For each $m$, we iterate over $k$ until the left bound $l$ of the corresponding segment exceeds $sz$. The special case $m=0$ should be handled separately. For each $k$, we need to increment the answer for all positions from $l$ to $r$ by one. This can be efficiently done by recording the operations $(l, +1)$ and $(r + 1, -1)$ and then applying a scanline technique to process the accumulated changes. Since there are $O\\left(\\frac{sz}{m}\\right)$ possible values of $k$ for each $m$, the total complexity of this solution is $O(n \\log n)$.",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nusing ll = long long;\n \nvoid solve() {\n    int n; cin >> n;\n    string s; cin >> s;\n    vector <int> a;\n    int curr = 0;\n    for (int i = 0; i < n; ++i) {\n        if (i && s[i] != s[i - 1]) {\n            if (curr) a.push_back(curr);\n            curr = 1;\n        }\n        else ++curr;\n    }\n    a.push_back(curr);\n    int sz = a.size();\n \n    vector <int> ans(n, 0), left(sz, 0), right(sz, 0);\n    for (int i = 0; i < sz; ++i) {\n        if (!i) {\n            left[i] = 0; right[i] = a[i] - 1;\n        } else {\n            left[i] = right[i - 1] + 1;\n            right[i] = left[i] + a[i] - 1;\n        }\n    }\n    for (int i = 0; i < sz; ++i) {\n        for (int j = left[i]; j <= right[i]; ++j) {\n            ans[j] += j - i + 1;\n        }\n    }\n    vector <int> add(sz, 0);\n    for (int m = 1; m < sz; ++m) {\n        ll l = m, r = m, k = 1;\n        while (l < sz) {\n            ++add[l];\n            if (r + 1 < sz) --add[r + 1];\n \n            if (a[l] == 1) {\n                l += m + 1;\n            } else {\n                l += m;\n            }\n \n            r += m + 1;\n            ++k;\n        }\n    }\n    int pref = 0;\n    for (int i = 0; i < sz; ++i) {\n        pref += add[i];\n        for (int j = left[i]; j <= right[i]; ++j) {\n            ans[j] += pref;\n        }\n    }\n    for (int i = 0; i < n; ++i) {\n        cout << ans[i];\n        if (i != n - 1) cout << ' ';\n    }\n    cout << '\\n';\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int t; cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n\n",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math",
      "number theory",
      "strings"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2093",
    "index": "A",
    "title": "Ideal Generator",
    "statement": "We call an array $a$, consisting of $k$ positive integers, palindromic if $[a_1, a_2, \\dots, a_k] = [a_k, a_{k-1}, \\dots, a_1]$. For example, the arrays $[1, 2, 1]$ and $[5, 1, 1, 5]$ are palindromic, while the arrays $[1, 2, 3]$ and $[21, 12]$ are not.\n\nWe call a number $k$ an ideal generator if any integer $n$ ($n \\ge k$) can be represented as the sum of the elements of a palindromic array of length exactly $k$. Each element of the array must be greater than $0$.\n\nFor example, the number $1$ is an ideal generator because any natural number $n$ can be generated using the array $[n]$. However, the number $2$ is not an ideal generator — there is no palindromic array of length $2$ that sums to $3$.\n\nDetermine whether the given number $k$ is an ideal generator.",
    "tutorial": "If we consider some palindromic array $a$ of the form $[a_1, a_2, \\dots, a_k]$ and its sum, we should discuss two different cases. When $k$ is even ($k = 2m$), the array $a$ looks as follows: $[a_1, a_2, \\dots, a_{m - 1}, a_m, a_m, a_{m - 1}, \\dots, a_2, a_1]$. Its sum in this case is the number $2 \\cdot (a_1 + a_2 + \\dots + a_m)$. This implies that any palindromic array of even length also has an even sum, and thus it is impossible to generate odd numbers $n$ for even values of $k$. On the other hand, if $k$ is an odd number ($k = 2m + 1$), the array $a$ looks like $[a_1, a_2, \\dots, a_m, a_{m + 1}, a_m, \\dots, a_2, a_1]$. Its sum is the number $a_{m + 1} + 2 \\cdot (a_1 + a_2 + \\dots + a_m)$. In this case, for any integer $n$, there exists a palindromic array of the form $[1, \\dots, 1, n - (k - 1), 1, \\dots, 1]$. In conclusion, if $k$ is an odd number, the answer is <<Yes>>, and if $k$ is even, the answer will be <<No>>.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n \n    while (t--) {\n        int n;\n        cin >> n;\n        if (n % 2 == 1) {\n            cout << \"YES\\n\";\n        } else {\n            cout << \"NO\\n\";\n        }\n    }\n \n    return 0;\n}\n",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2093",
    "index": "B",
    "title": "Expensive Number",
    "statement": "The cost of a positive integer $n$ is defined as the result of dividing the number $n$ by the sum of its digits.\n\nFor example, the cost of the number $104$ is $\\frac{104}{1 + 0 + 4} = 20.8$, and the cost of the number $111$ is $\\frac{111}{1 + 1 + 1} = 37$.\n\nYou are given a positive integer $n$ that does not contain leading zeros. You can remove any number of digits from the number $n$ (including none) so that the remaining number contains at least one digit and \\textbf{is strictly greater than zero}. The remaining digits \\textbf{cannot} be rearranged. As a result, you \\textbf{may} end up with a number that has leading zeros.\n\nFor example, you are given the number $103554$. If you decide to remove the digits $1$, $4$, and one digit $5$, you will end up with the number $035$, whose cost is $\\frac{035}{0 + 3 + 5} = 4.375$.\n\nWhat is the minimum number of digits you need to remove from the number so that its cost becomes the minimum possible?",
    "tutorial": "We will prove that the minimum possible cost of the resulting number is always equal to $1$. Consider an arbitrary positive number $n = \\overline{a_1a_2\\ldots a_k}$, where $a_i$ are its digits in order. We evaluate the cost of this number as $cost(n) = \\frac{\\overline{a_1a_2\\ldots a_k}}{a_1+a_2+\\ldots+a_k} = \\frac{a_1 \\cdot 10^{k - 1} + a_2\\cdot 10^{k - 2} + \\ldots + a_k}{a_1+a_2+\\ldots+a_k} \\geq \\frac{a_1+a_2+\\ldots+a_k}{a_1+a_2+\\ldots+a_k} = 1$. We also note that if any of the digits $a_1, a_2, \\ldots, a_{k - 1}$ are not equal to zero, then the inequality will be strict. Thus, a cost of $1$ can always be achieved by leaving exactly one non-zero digit and several leading zeros before it. Therefore, our task reduces to leaving some non-zero digit and as many leading zeros as possible before it. To do this, we will keep the rightmost non-zero digit in the number, all the zeros to its left, and remove the other digits.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        string s;\n        cin >> s;\n        int n = s.size();\n        bool met_positive = false;\n        int cnt_zero = 0;\n        \n        for (auto i = n - 1; i >= 0; --i) {\n            if (s[i] != '0') {\n                met_positive = true;\n            } else if (met_positive) {\n                cnt_zero++;\n            }\n        }\n        \n        cout << n - (cnt_zero + 1) << '\\n';\n    }\n    return 0;\n}\n",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2093",
    "index": "C",
    "title": "Simple Repetition",
    "statement": "Pasha loves prime numbers$^{\\text{∗}}$! Once again, in his attempts to find a new way to generate prime numbers, he became interested in an algorithm he found on the internet:\n\n- To obtain a new number $y$, repeat $k$ times the decimal representation of the number $x$ (without leading zeros).\n\nFor example, for $x = 52$ and $k = 3$, we get $y = 525252$, and for $x = 6$ and $k = 7$, we get $y = 6666666$.\n\nPasha really wants the resulting number $y$ to be prime, but he doesn't yet know how to check the primality of numbers generated by this algorithm. Help Pasha and tell him whether $y$ is prime!\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An integer $x$ is considered prime if it has \\textbf{exactly} $2$ distinct divisors: $1$ and $x$. For example, $13$ is prime because it has only $2$ divisors: $1$ and $13$. Note that the number $1$ is not prime, as it has only one divisor.\n\\end{footnotesize}",
    "tutorial": "Let the number $x$ have $b$ digits in its decimal representation. What does it mean to write it $k$ times? It can be shown that $y = x \\cdot 10^0 + x \\cdot 10^b + x \\cdot 10^{2b} + \\dots + x \\cdot 10^{(k - 1)b} = x \\cdot (10^0 + 10^b + 10^{2b} + \\dots + 10^{(k-1)b})$ We are left to consider 2 cases: $k = 1$, in this case the number $x$ is written 1 time, that is, $y = x$. Thus, it is necessary to simply check the number $x$ for primality, which can be done using a known algorithm in $\\mathcal{O}(\\sqrt{x})$. $x = 1$, in this case the number looks like: $11\\dots11$, that is, it is a number consisting of $k$ ones. This number can be generated and checked for primality in $\\mathcal{O}(\\sqrt{10^k}) = \\mathcal{O}(10^{k/2})$. It is also possible to precompute prime numbers consisting only of ones and notice that for $k \\leq 7$, the only prime number occurs when $k = 2$, which is $11$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nbool is_prime(int x) {\n    if (x <= 1) {\n        return false;\n    }\n    for (int i = 2; i * i <= x; i++) {\n        if (x % i == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n \nvoid solve() {\n    int x, k;\n    cin >> x >> k;\n    if (k > 1 && x > 1) {\n        cout << \"NO\";\n    } else if (k == 1) {\n        cout << (is_prime(x) ? \"YES\" : \"NO\");\n    } else {\n        cout << ((k == 2) ? \"YES\" : \"NO\");\n    }\n}\n \nint main() {\n    int tests;\n    cin >> tests;\n    while (tests--) {\n        solve();\n        cout << '\\n';\n    }\n}\n",
    "tags": [
      "math",
      "number theory"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2093",
    "index": "D",
    "title": "Skibidi Table",
    "statement": "Vadim loves filling square tables with integers. But today he came up with a way to do it for fun! Let's take, for example, a table of size $2 \\times 2$, with rows numbered from top to bottom and columns numbered from left to right. We place $1$ in the top left cell, $2$ in the bottom right, $3$ in the bottom left, and $4$ in the top right. That's all he needs for fun!\n\nFortunately for Vadim, he has a table of size $2^n \\times 2^n$. He plans to fill it with integers from $1$ to $2^{2n}$ in ascending order. To fill such a large table, Vadim will divide it into $4$ equal square tables, filling the top left one first, then the bottom right one, followed by the bottom left one, and finally the top right one. Each smaller table will be divided into even smaller ones as he fills them until he reaches tables of size $2 \\times 2$, which he will fill in the order described above.\n\nNow Vadim is eager to start filling the table, but he has $q$ questions of two types:\n\n- what number will be in the cell at the $x$-th row and $y$-th column;\n- in which cell coordinates will the number $d$ be located.\n\nHelp answer Vadim's questions.",
    "tutorial": "Note that there are $4$ possible positions of the cell and the values within it: $x,y \\le 2^{n-1} \\Leftrightarrow d \\le 2^{2n-2}$; $x,y > 2^{n-1} \\Leftrightarrow 2^{2n-2} < d \\le 2 \\cdot 2^{2n-2}$; $x > 2^{n-1}, y \\le 2^{n-1} \\Leftrightarrow 2 \\cdot 2^{2n-2} < d \\le 3 \\cdot 2^{2n-2}$; $x \\le 2^{n-1}, y > 2^{n-1} \\Leftrightarrow 3 \\cdot 2^{2n-2} < d \\le 4 \\cdot 2^{2n-2}$. This can be implemented either with a recursive function, or by subtracting the necessary powers of two, or by integer division of the coordinates by $2$ and the value by $4$, or by analyzing the bits in the binary representation of $x-1, y-1$, and $d-1$, or through a kind of binary search. Each of these solutions answers one query in $O(n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t;\n    cin >> t;\n    \n    while (t--) {\n        int n, q;\n        cin >> n >> q;\n        \n        while (q--) {\n            string type;\n            cin >> type;\n            \n            if (type == \"->\") {\n                int x, y;\n                cin >> x >> y;\n                x--, y--;\n                \n                long long num = 0;\n                for (int i = n - 1; i >= 0; --i) {\n                    int cur = 1 << i;\n                    if (!(x & cur) && !(y & cur))\n                        num ^= 0ll << (2 * i);\n                    if ((x & cur) && (y & cur))\n                        num ^= 1ll << (2 * i);\n                    if ((x & cur) && !(y & cur))\n                        num ^= 2ll << (2 * i);\n                    if (!(x & cur) && (y & cur))\n                        num ^= 3ll << (2 * i);\n                }\n                cout << num + 1 << '\\n';\n            }\n            else {\n                long long num;\n                cin >> num;\n                num--;\n                \n                int x = 0, y = 0;\n                for (int i = n - 1; i >= 0; --i) {\n                    long long cur = 3ll << (2 * i);\n                    if ((num & cur) >> (2 * i) == 0)\n                        x ^= 0 << i, y ^= 0 << i;\n                    if ((num & cur) >> (2 * i) == 1)\n                        x ^= 1 << i, y ^= 1 << i;\n                    if ((num & cur) >> (2 * i) == 2)\n                        x ^= 1 << i, y ^= 0 << i;\n                    if ((num & cur) >> (2 * i) == 3)\n                        x ^= 0 << i, y ^= 1 << i;\n                }\n                cout << x + 1 << ' ' << y + 1 << '\\n';\n            }\n        }\n    }\n    \n    return 0;\n}\n",
    "tags": [
      "bitmasks",
      "implementation"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2093",
    "index": "E",
    "title": "Min Max MEX",
    "statement": "You are given an array $a$ of length $n$ and a number $k$.\n\nA subarray is defined as a sequence of one or more consecutive elements of the array. You need to split the array $a$ into $k$ non-overlapping subarrays $b_1, b_2, \\dots, b_k$ such that the union of these subarrays equals the entire array. Additionally, you need to maximize the value of $x$, which is equal to the minimum MEX$(b_i)$, for $i \\in [1..k]$.\n\nMEX$(v)$ denotes the smallest non-negative integer that is not present in the array $v$.",
    "tutorial": "To solve the problem, we use binary search on the answer. To do this, we need to learn how to check for a given $x$ whether there exists a partition that allows achieving an answer of at least $x$. To do this, we will collect the segments one by one, that is, first we will find the minimal valid first segment, then the second, and so on. Since the segments must be non-overlapping and must give the entire array in union, it means that in a correct partition there must exist a segment containing the first element; also, the MEX of this segment must be at least $x$, which means it needs to be increased until the MEX becomes greater than or equal to $x$. As soon as this happens, it makes no sense to further increase the segment, so we move on to the next element and begin to select the next segment. To maintain MEX on a segment, we can use a counting array and a variable in which we store the current MEX. When a new number is added to the segment, we run a while loop, and while there is a number in the segment equal to the current MEX, we increase MEX by one. This works amortized in the number of elements in the segment, since MEX on the segment cannot be greater than the length of the segment. Asymptotic of the solution: $O(n\\cdot log(n))$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<int> nums(2e5 + 5, 0);\n\nbool check(vector<int>& v, int k, int m)\n{\n    int cnt = 0;\n    int cur_mex = 0;\n    for (int i = 0; i < v.size(); i++) {\n        if (v[i] <= v.size() + 1) {\n            nums[v[i]] = 1;\n        }\n        while (nums[cur_mex]) {\n            cur_mex++;\n        }\n        if (cur_mex >= m) {\n            cnt++;\n            for (int j = 0; j < min(m + 1, (int)v.size() + 2); j++) {\n                nums[j] = 0;\n            }\n            cur_mex = 0;\n        }\n    }\n    for (int j = 0; j < v.size() + 2; j++) {\n        nums[j] = 0;\n    }\n    return cnt >= k;\n}\n\nvoid solve()\n{\n    int n, k;\n    cin >> n >> k;\n\n    vector<int> v(n);\n    for (int i = 0; i < n; i++) {\n        cin >> v[i];\n    }\n\n    int l = 0;\n    int r = 1e9;\n    while (r - l > 1) {\n        int m = (r + l) / 2;\n        if (check(v, k, m)) {\n            l = m;\n        } else {\n            r = m;\n        }\n    }\n\n    cout << l << '\\n';\n}\n\nsigned main()\n{\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++) {\n        solve();\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "greedy"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2093",
    "index": "F",
    "title": "Hackers and Neural Networks",
    "statement": "Hackers are once again trying to create entertaining phrases using the output of neural networks. This time, they want to obtain an array of strings $a$ of length $n$.\n\nInitially, they have an array $c$ of length $n$, filled with blanks, which are denoted by the symbol $*$. Thus, if $n=4$, then initially $c=[*,*,*,*]$.\n\nThe hackers have access to $m$ neural networks, each of which has its own version of the answer to their request – an array of strings $b_i$ of length $n$.\n\nThe hackers are trying to obtain the array $a$ from the array $c$ using the following operations:\n\n- Choose a neural network $i$, which will perform the next operation on the array $c$: it will select a {\\textbf{random}} \\textbf{blank}, for example, at position $j$, and replace $c_j$ with $b_{i, j}$.For example, if the first neural network is chosen and $c = [*, \\text{«like»}, *]$, and $b_1 = [\\text{«I»}, \\text{«love»}, \\text{«apples»}]$, then after the operation with the first neural network, $c$ may become either $[\\text{«I»}, \\text{«like»}, *]$ or $[*, \\text{«like»}, \\text{«apples»}]$.\n- Choose position $j$ and replace $c_j$ with a blank.\n\nUnfortunately, because of the way hackers access neural networks, they will only be able to see the modified array $c$ after all operations are completed, so they will have to specify the entire sequence of operations in advance.\n\nHowever, the random behavior of the neural networks may lead to the situation where the desired array is never obtained, or obtaining it requires an excessive number of operations.\n\nTherefore, the hackers are counting on your help in choosing a sequence of operations that will guarantee the acquisition of array $a$ in the minimum number of operations.\n\nMore formally, if there exists a sequence of operations that can \\textbf{guarantee} obtaining array $a$ from array $c$, then among all such sequences, find the one with the \\textbf{minimum} number of operations, and output the number of operations in it.\n\nIf there is no sequence of operations that transforms array $c$ into array $a$, then output $-1$.",
    "tutorial": "Let's call the operation of the first type a miss if after it $c_i \\neq a_i$. Let $x = \\max_{i = 1 \\dots m}( \\sum_{j=1}^{n} b_{i,j} = a_j)$. Notice that in any case we will have at least $n - x$ misses. Why? Since the positions are chosen randomly, and we need to guarantee obtaining the array $a$, we must assume the worst case: if there is a possibility to choose a position $j$ such that $a_j \\neq b_{i, j}$, then this will happen. Accordingly, if one neural network has $y$ positions that match the array $a$, it will first choose $n-y$ non-matching positions. Therefore, to minimize the number of misses before the first correct word, we need to select the neural network with the maximum number of positions matching the array $a$ - that is, the neural network on which $x$ from the definition above is achieved. Consequently, whatever we do, we will end up with $n-x$ extra words that need to be removed. This means we have at least $n + (n - x)$ operations. It is impossible to obtain the desired string in fewer than $n - x$ additional operations - after we have removed $n-x$ extra words, we need to fill them in. Thus, the theoretical minimum number of operations is $n + 2 \\cdot (n - x)$. We will present an algorithm that achieves this and is therefore optimal. Let's take the neural network where $x$ is achieved; after $n$ operations, we will have $x$ matching words and $n - x$ non-matching ones. These can be swapped using the second operation: suppose we have a non-matching word at the $i$-th position, then we will place a blank there and refer to the neural network where this word is correct - since there is only one blank, the neural network will guarantee to place exactly the word we need. We will do this for all words. This will take us $n - x$ operations of the second type and another $n - x$ operations of the first type - thus we have just reached our minimal estimate.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<string> a(n);\n    for (auto &i: a) {\n        cin >> i;\n    }\n    vector<vector<string>> b(m, vector<string>(n));\n    for (auto &ar: b) {\n        for (auto &s: ar) {\n            cin >> s;\n        }\n    }\n    vector<bool> exists(n);\n    int x = 0;\n    for (int i = 0; i < m; i++) {\n        int cnt = 0;\n        for (int j = 0; j < n; j++) {\n            if (a[j] == b[i][j]) {\n                cnt++;\n                exists[j] = true;\n            }\n        }\n        x = max(x, cnt);\n    }\n    if (all_of(exists.begin(), exists.end(), identity())) {\n        cout << n + 2 * (n - x) << \"\\n\";\n    } else {\n        cout << \"-1\\n\";\n    }\n}\n \nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}\n",
    "tags": [
      "bitmasks",
      "brute force",
      "greedy"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2093",
    "index": "G",
    "title": "Shorten the Array",
    "statement": "The beauty of an array $b$ of length $m$ is defined as $\\max(b_i \\oplus b_j)$ among all possible pairs $1 \\le i \\le j \\le m$, where $x \\oplus y$ is the bitwise XOR of numbers $x$ and $y$. We denote the beauty value of the array $b$ as $f(b)$.\n\nAn array $b$ is called beautiful if $f(b) \\ge k$.\n\nRecently, Kostya bought an array $a$ of length $n$ from the store. He considers this array too long, so he plans to cut out some beautiful subarray from it. That is, he wants to choose numbers $l$ and $r$ ($1 \\le l \\le r \\le n$) such that the array $a_{l \\dots r}$ is beautiful. The length of such a subarray will be the number $r - l + 1$. The entire array $a$ is also considered a subarray (with $l = 1$ and $r = n$).\n\nYour task is to find the length of the shortest beautiful subarray in the array $a$. If no subarray is beautiful, you should output the number $-1$.",
    "tutorial": "First, note that in the optimal segment $[l, r]$, the maximum value of $a_i \\oplus a_j$ must be achieved precisely when $i = l$ and $j = r$. Otherwise, we can shift at least one of the boundaries, thereby reducing the length of the found segment. Our task then becomes to find the nearest pair of indices $i$ and $j$ such that $a_i \\oplus a_j \\ge k$. Next, we consider all numbers in the array as binary strings padded with leading zeros to a length of $30$. Note that ordinary comparison of numbers is equivalent to lexicographical order on such strings. Let $x = x_{29}x_{28}{\\dots}x_{1}x_{0}$, $y = y_{29}y_{28}{\\dots}y_{1}y_{0}$, $k = k_{29}k_{28}{\\dots}k_{1}k_{0}$, then the condition $x \\oplus y \\ge k$ is equivalent to the existence of a bit $i$ such that $x_{29} \\oplus y_{29} = k_{29}, \\dots, x_{i + 1} \\oplus y_{i + 1} = k_{i + 1}$ and $x_{i} \\oplus y_{i} > k_{i}$. Or $x \\oplus y = k$, and then for any $i$ it will hold that $x_i \\oplus y_i = k_i$. Suppose we have fixed the values of $x$, $k$, and $i$, then we need to find such a number $y$ that $y_{29} = x_{29} \\oplus k_{29}, \\dots y_{i + 1} = x_{i + 1} \\oplus k_{i + 1}$ and $k_i = 0$ and $x_i \\neq y_i$. For the given $a_i$ and $k$, we are interested in the nearest $a_j$ that satisfies these conditions. We will traverse the array $a$ from left to right and maintain in a binary trie all the numbers we have already passed. We will also keep track of the maximum index among the added numbers in the corresponding subtree at each node of the trie. Thus, the search for the nearest suitable $a_j$ for a given $a_i$ will look like a descent in the trie along the string $a_i \\oplus k$. If the value in the $j$-th bit of the number $k$ is $1$, we need to descend along the edge $a_{ij} \\oplus 1$. Otherwise, if $k_j = 0$, we should check the maximum index in the subtree $a_{ij} \\oplus 1$, but we will descend along the edge $a_{ij} \\oplus 0$. Thus, after processing all the numbers in the array, we will find a pair of nearest $a_i$, $a_j$, for which $a_i \\oplus a_j \\ge k$. The solution works in $O(N \\log{10^9})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int LOG_X = 29;\n \nstruct node {\n    int children[2] { -1, -1 };\n    int last = -1;\n};\n \nint find(const vector<node>& trie, int value, int border) {\n    int res = -1;\n    int current = 0;\n    bool ok = true;\n    for (int position = LOG_X; ok && position >= 0; position--) {\n        int x_bit = (value >> position) & 1;\n        int k_bit = (border >> position) & 1;\n        auto& children = trie[current].children;\n        if (k_bit == 1) {\n            if (children[x_bit ^ 1] != -1) {\n                current = children[x_bit ^ 1];\n            } else {\n                ok = false;\n            }\n        } else {\n            if (children[x_bit ^ 1] != -1) {\n                res = max(res, trie[children[x_bit ^ 1]].last);\n            }\n            if (children[x_bit] != -1) {\n                current = children[x_bit];\n            } else {\n                ok = false;\n            }\n        }\n    }\n    if (ok) {\n        res = max(res, trie[current].last);\n    }\n    return res;\n}\n \nvoid add(vector<node>& trie, int value, int index) {\n    int current = 0;\n    trie[current].last = max(trie[current].last, index);\n    for (int position = LOG_X; position >= 0; position--) {\n        int x_bit = (value >> position) & 1;\n        if (trie[current].children[x_bit] == -1) {\n            trie[current].children[x_bit] = trie.size();\n            trie.push_back(node());\n        }\n        current = trie[current].children[x_bit];\n        trie[current].last = max(trie[current].last, index);\n    }\n}\n \nvoid solve() {\n    int n, k;\n    cin >> n >> k;\n \n    int ans = n + 1;\n    vector<node> trie(1);\n    for (int i = 0; i < n; i++) {\n        int x;\n        cin >> x;\n        add(trie, x, i);\n        int y = find(trie, x, k);\n        if (y != -1) {\n            ans = min(ans, i - y + 1);\n        }\n    }\n \n    if (ans == n + 1) {\n        cout << \"-1\\n\";\n    } else {\n        cout << ans << '\\n';\n    }\n}\n \nint main() {\n    int t;\n    cin >> t;\n    \n    while (t--) {\n        solve();\n    }\n \n    return 0;\n}\n",
    "tags": [
      "binary search",
      "bitmasks",
      "data structures",
      "dfs and similar",
      "greedy",
      "strings",
      "trees",
      "two pointers"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2094",
    "index": "A",
    "title": "Trippi Troppi",
    "statement": "Trippi Troppi resides in a strange world. The ancient name of each country consists of three strings. The first letter of each string is concatenated to form the country's modern name.\n\nGiven the country's ancient name, please output the modern name.",
    "tutorial": "This can be solved by printing the zero-th index of each string in sequence. For example, suppose your strings are $a$, $b$, and $c$. Then in C++, you can use cout << a[0] << b[0] << c[0] << '\\n';, and similarly, in Python you can use print(a[0] + b[0] + c[0]). See your preferred language's syntax for how to obtain a given indexed character from a string.",
    "code": "t = int(input())\nfor _ in range(t):\n    inp = input()\n    for w in inp.split():\n        print(w[0],end=\"\")\n    print()",
    "tags": [
      "strings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2094",
    "index": "B",
    "title": "Bobritto Bandito",
    "statement": "In Bobritto Bandito's home town of residence, there are an infinite number of houses on an infinite number line, with houses at $\\ldots, -2, -1, 0, 1, 2, \\ldots$. On day $0$, he started a plague by giving an infection to the unfortunate residents of house $0$. Each succeeding day, the plague spreads to \\textbf{exactly one} healthy household that is next to an infected household. It can be shown that each day the infected houses form a continuous segment.\n\nLet the segment starting at the $l$-th house and ending at the $r$-th house be denoted as $[l, r]$. You know that after $n$ days, the segment $[l, r]$ became infected. Find any such segment $[l', r']$ that could have been infected on the $m$-th day ($m \\le n$).",
    "tutorial": "What is the condition for $l'$ and $r'$ to be valid? We must have $r' - l' = m$ and $l\\leq l' \\leq 0 \\leq r'\\leq r$. The problem reduces to finding $l'$ and $r'$ such that $r' - l' = m$ and $l\\leq l' \\leq 0 \\leq r'\\leq r$. There are several different approaches; two are outlined below. One approach which runs in $O(1)$ time is to case on whether $m\\leq r$. If $m\\leq r$, we can choose $l' = 0$ and $r' = m$, and then we see that $r' - l' = m - 0 = m$ and $l \\leq 0 \\leq 0 \\leq m \\leq r$ as desired. If $m>r$, we can choose $l' = r-m$ and $r' = r$, and then we see that $r' - l' = r - (r-m) = m$ and $l \\leq r-m \\leq 0 \\leq r \\leq r$, where $l \\leq r-m$ holds because $r-l = n \\geq m$. An alternative approach which runs in $O(m)$ time is to simply simulate the process; expand in an arbitrary direction which satisfies the desired inequalities until $r' - l' = m$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nvoid solve() {\n    int n, m, l, r; cin >> n >> m >> l >> r;\n    int diff = n - m;\n    l = abs(l);\n    if (l >= diff) {\n        l -= diff;\n        diff = 0;\n    }\n    else {\n        diff -= l;\n        l = 0;\n    }\n    cout << -l << \" \" << r - diff << '\\n';\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "2094",
    "index": "C",
    "title": "Brr Brrr Patapim",
    "statement": "Brr Brrr Patapim is trying to learn of Tiramisù's secret passcode, which is a permutation$^{\\text{∗}}$ of $2\\cdot n$ elements. To help Patapim guess, Tiramisù gave him an $n\\times n$ grid $G$, in which $G_{i,j}$ (or the element in the $i$-th row and $j$-th column of the grid) contains $p_{i+j}$, or the $(i+j)$-th element in the permutation.\n\nGiven this grid, please help Patapim crack the forgotten code. It is guaranteed that the permutation exists, and it can be shown that the permutation can be determined uniquely.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of $m$ integers is a sequence of $m$ integers which contains each of $1,2,\\ldots,m$ exactly once. For example, $[1, 3, 2]$ and $[2, 1]$ are permutations, while $[1, 2, 4]$ and $[1, 3, 2, 3]$ are not.\n\\end{footnotesize}",
    "tutorial": "How can we find $p_i$ for $2\\leq i\\leq n$? How can we find $p_i$ for $n+1\\leq i\\leq 2n$? For $2\\leq i\\leq n$, we can find $p_i$ by checking $G_{1, i-1}$. For $n+1\\leq i\\leq 2n$, we can find $p_i$ by checking $G_{n, i-n}$. Observe that for all $2\\leq i\\leq n$, we can find $p_i$ by checking $G_{1, i-1}$. Then for all $n+1\\leq i\\leq 2n$, we can find $p_i$ by checking $G_{n, i-n}$. Now, we only have to find the value of $p_1$. However, each value from $1$ to $2n$ must appear exactly once in $p$. Thus, we can simply find the value which has not appeared yet, and choose that as $p_1$. This can be done by storing which values have been seen in a boolean array, and then finding which one remains false.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nvoid solve() {\n    int n; cin >> n;\n    vector<int> ans(2*n+1, 0);\n    vector<bool> used(2*n+1, false);\n    for (int i = 1; i <= n; i++) {\n        for (int j = 1; j <= n; j++) {\n            int x; cin >> x;\n            ans[i + j] = x;\n            used[x] = true;\n        }\n    }\n    for (int i = 1; i <= 2 * n; i++) {\n        if (ans[i] != 0) cout << ans[i] << \" \";\n        else {\n            for (int j = 1; j <= n * 2; j++) {\n                if (!used[j]) {\n                    used[j] = true;\n                    cout << j << \" \";\n                    break;\n                }\n            }\n        }\n    }\n    cout << \"\\n\";\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2094",
    "index": "D",
    "title": "Tung Tung Sahur",
    "statement": "You have two drums in front of you: a left drum and a right drum. A hit on the left can be recorded as \"L\", and a hit on the right as \"R\".\n\nThe strange forces that rule this world are fickle: sometimes, a blow sounds once, and sometimes it sounds twice. Therefore, a hit on the left drum could have sounded as either \"L\" or \"LL\", and a hit on the right drum could have sounded as either \"R\" or \"RR\".\n\nThe sequence of hits made is recorded in the string $p$, and the sounds heard are in the string $s$. Given $p$ and $s$, determine whether it is true that the string $s$ could have been the result of the hits from the string $p$.\n\nFor example, if $p=$\"LR\", then the result of the hits could be any of the strings \"LR\", \"LRR\", \"LLR\", and \"LLRR\", but the strings \"LLLR\" or \"LRL\" cannot.",
    "tutorial": "What would happen if $s_1$ consists of only $L$? In this case, the answer is yes if and only if $|s_1| \\leq |s_2| \\leq 2|s_1|$. Now try to generalize this. First, let us consider a simpler case of the problem: suppose that there is only $L$ in both $s_1$ and $s_2$. Then it is clear that the answer is yes if and only if $|s_1| \\leq |s_2| \\leq 2|s_1|$. If this holds (in particular, we also necessitate that $s_1$ and $s_2$ consist of only a single character, and the same character), we will call $s_2$ an extension of $s_1$. Now, observe that the problem given is simply the simpler version, repeated several times alternating between $L$ and $R$. So we can partition $s_1$ into \"blocks\" (where we define a block to be a maximal group of contiguous identical characters). Then the answer is yes if and only if $s_2$ is the concatenation of extensions of blocks in $s_1$. For example, consider $s_1 = LLLLLRL$. We see that this consists of five $L$s, one $R$, and one $L$. So the answer is yes if and only if $s_2$ consists of between five and ten $L$s (inclusive), between one and two $R$s, and between one and two $L$ 's, concatenated in that order.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nvoid solve() {\n    string a, b; cin >> a >> b;\n    int n = a.size();\n    int m = b.size();\n    if (m < n || m > 2 * n || a[0] != b[0]) {\n        cout << \"NO\\n\";\n        return;\n    }\n    vector<int> aa, bb;\n    int cnt = 1;\n    for (int i = 1; i < n; i++) {\n        if (a[i] != a[i-1]) {\n            aa.push_back(cnt);\n            cnt = 1;\n        }\n        else cnt++;\n    }\n    aa.push_back(cnt);\n    cnt = 1;\n    for (int i = 1; i < m; i++) {\n        if (b[i] != b[i-1]) {\n            bb.push_back(cnt);\n            cnt = 1;\n        }\n        else cnt++;\n    }\n    bb.push_back(cnt);\n    if (aa.size() != bb.size()) {\n        cout << \"NO\\n\";\n        return;\n    }\n    n = aa.size();\n    for (int i = 0; i < n; i++) {\n        if (aa[i] > bb[i] || aa[i] * 2 < bb[i]) {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    cout << \"YES\\n\";\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "greedy",
      "strings",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2094",
    "index": "E",
    "title": "Boneca Ambalabu",
    "statement": "Boneca Ambalabu gives you a sequence of $n$ integers $a_1,a_2,\\ldots,a_n$.\n\nOutput the maximum value of $(a_k\\oplus a_1)+(a_k\\oplus a_2)+\\ldots+(a_k\\oplus a_n)$ among all $1 \\leq k \\leq n$. Note that $\\oplus$ denotes the bitwise XOR operation.",
    "tutorial": "Consider each bit independently. Suppose we fix $k$. How can we compute the desired sum quickly? Note that this may require preprocessing. Here, it suffices to consider each bit independently, because addition is both commutative and associative. For $0\\leq i < 30$, let $cnt_i$ denote the number of elements of $a$ which have the $i$-th bit set (where bits are indexed from the least significant bit being the $0$-th bit); note that these can be found in $O(30n)$ time (more generally, we need $O(\\log\\max{a_i})$ operations per element). Now, suppose we choose a particular $k$. Then we can find the sum $(a_k\\oplus a_1) + (a_k\\oplus a_2) \\dots + (a_k\\oplus a_n)$ as follows: for a given bit position $i$, the number of elements $a_j$ such that $a_k \\oplus a_j$ has the $i$-th bit set will be $cnt_i$ if the $i$-th bit of $a_k$ is not set, and $n-cnt_i$ if the $i$-th bit of $a_k$ is set. So we can simply add $cnt_i \\cdot 2^i$ to our sum if the $i$-th bit of $a_k$ is not set, and add $(n-cnt_i) \\cdot 2^i$ to our sum if the $i$-th bit of $a_k$ is set. This allows us to compute $(a_k\\oplus a_1) + (a_k\\oplus a_2) \\dots + (a_k\\oplus a_n)$ for any $k$ in $O(30)$ time, so we can now compute this sum for all $k$ in $O(30n)$ time and output the maximum.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nvoid solve() {\n    int n; cin >> n;\n    int arr[n+1];\n    vector<int> cnt(30, 0);\n    for (int i = 1; i <= n; i++) {\n        cin >> arr[i];\n        for (int j = 0; j < 30; j++) {\n            cnt[j] += ((arr[i] >> j) & 1);\n        }\n    }\n    int ans = 0;\n    for (int i = 1; i <= n; i++) {\n        int tot = 0;\n        for (int j = 0; j < 30; j++) {\n            bool f = ((arr[i] >> j) & 1);\n            if (f) tot += (1 << j) * (n - cnt[j]);\n            else tot += (1 << j) * cnt[j];\n        }\n        ans = max(ans, tot);\n    }\n    cout << ans << \"\\n\";\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "bitmasks"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2094",
    "index": "F",
    "title": "Trulimero Trulicina",
    "statement": "Trulicina gives you integers $n$, $m$, and $k$. It is guaranteed that $k\\geq 2$ and $n\\cdot m\\equiv 0 \\pmod{k}$.\n\nOutput a $n$ by $m$ grid of integers such that each of the following criteria hold:\n\n- Each integer in the grid is between $1$ and $k$, inclusive.\n- Each integer from $1$ to $k$ appears an equal number of times.\n- No two cells that share an edge have the same integer.\n\nIt can be shown that such a grid always exists. If there are multiple solutions, output any.",
    "tutorial": "What would happen if we tried outputting the numbers $1, \\dots, k, 1, \\dots, k, \\dots$ in the natural reading order? For example, for $n=3$, $m=4$, and $k=6$, we would output the following: In which cases does this fail? This fails if and only if $m$ is a multiple of $k$, because we see that horizontally adjacent elements differ by $1\\pmod k$ and vertically adjacent elements differ by $m\\pmod k$. Now try to resolve this case. There are many working constructions for this problem; one of them is to case on whether or not $m$ is a multiple of $k$. Suppose $m$ is not a multiple of $k$. For example, consider the second sample, where $n=3$, $m=4$, and $k=6$. Then we can output the numbers $1, \\dots, k, 1, \\dots, k, \\dots$ in the natural reading order, as follows: and we see that any two horizontally adjacent elements differ by $1\\pmod k$, whereas any two vertically adjacent elements differ by $m\\pmod k$, so no two adjacent elements are the same, as desired. Now, suppose $m$ is a multiple of $k$. For example, consider the case $n=4$, $m=6$, and $k=3$. Suppose we were to try the above strategy, then we get: which doesn't work, since vertically adjacent elements are the same. We can fix this by cyclically shifting every other row as follows: and we see that any two horizontally adjacent elements differ by $1\\pmod k$ as before, whereas any two vertically adjacent elements also differ by $1\\pmod k$, so no two adjacent elements are the same, as desired.",
    "code": "import sys\ninput = sys.stdin.readline\nfor _ in range(int(input())):\n    n,m,k = map(int,input().split())\n    LAST = [-1 for _ in range(m)]\n    for i in range(n):\n        shift = False\n        CUR = [0 for _ in range(m)]\n        for j in range(m):\n            elm = ((i * m + j) % k) + 1\n            if elm == LAST[j]:\n                shift = True\n            CUR[j] = elm\n        if shift:\n            CUR = [CUR[(j+1)%m] for j in range(m)]\n        print(*CUR)\n        LAST = CUR",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2094",
    "index": "G",
    "title": "Chimpanzini Bananini",
    "statement": "Chimpanzini Bananini stands on the brink of a momentous battle—one destined to bring finality.\n\nFor an arbitrary array $b$ of length $m$, let's denote the rizziness of the array to be $\\sum_{i=1}^mb_i\\cdot i=b_1\\cdot 1+b_2\\cdot 2+b_3\\cdot 3+\\ldots + b_m\\cdot m$.\n\nChimpanzini Bananini gifts you an empty array. There are three types of operations you can perform on it.\n\n- Perform a cyclic shift on the array. That is, the array $[a_1, a_2, \\ldots, a_n]$ becomes $[a_n, a_1, a_2, \\ldots, a_{n-1}].$\n- Reverse the entire array. That is, the array $[a_1, a_2, \\ldots, a_n]$ becomes $[a_n, a_{n-1}, \\ldots, a_1].$\n- Append an element to the end of the array. The array $[a_1, a_2, \\ldots, a_n]$ becomes $[a_1, a_2, \\ldots, a_n, k]$ after appending $k$ to the end of the array.\n\nAfter each operation, you are interested in calculating the rizziness of your array.\n\nNote that all operations are \\textbf{persistent}. This means that each operation modifies the array, and subsequent operations should be applied to the current state of the array after the previous operations.",
    "tutorial": "Note that reversing an array then pushing an element to the back is similar to simply pushing an element to the front. Thus, we would like to push elements to both ends of the array. What data structure supports this? A deque is the most natural choice to use. Most languages, including C++, Java, and Python, include deques in their standard library, so you likely do not have to implement it yourself. What other values do we need to maintain in order to keep track of score? It suffices to keep track of the current score, the score of the array if it were backwards, the size of the array, and the sum of the array. We can solve this using a deque. Let $score$ denote the current score, and $rscore$ denote the score of the array if it were backwards. Let $size$ denote the size of the array, and $sum$ denote the sum of the array. Then we consider how these three values change as each operation is performed. Suppose operation 1 is performed. This is equivalent to popping the back element of the array and pushing it in the front. When you pop the back element of the array, $score$ decreases by $a_n \\cdot size$. Then when you push it to the front, $score$ increases by $sum$ because $a_n$ is pushed to the first spot and every element from $a_1$ to $a_{n-1}$ moves forward one spot. Notice that $rscore$ changes in the reverse way; this is equivalent to popping the front element of the array and pushing it to the back. When you pop the front element of the array, $rscore$ decreases by $sum$, and when you push it to the back, $rscore$ increases by $a_n \\cdot size$. Note that $size$ and $sum$ remain unchanged. Suppose operation 2 is performed. Then we swap $score$ and $rscore$, and we also want to \"reverse\" the array. However, it is costly to entirely reverse the deque. Instead, we will set a flag to indicate that the array has been reversed (and similarly, if the flag is already set, we will unset it). If the flag is set, we simply switch the front and back ends whenever we access or modify the deque while performing operations 1 or 3. Suppose operation 3 is performed. Then we see that $size$ increases by $1$ and $sum$ increases by $k$. Then $score$ increases by $k \\cdot size$ and $rscore$ increases by $sum$ (using the new value of $sum$), by identical reasoning to that in operation 1. Additional optimization: we don't actually have to maintain $rscore$; we can obtain it with the expression: $(n+1)\\sum_{i=1}^na_i-score$. This is because $score + rscore = (n+1)\\sum_{i=1}^na_i$ since the $i$-th term is counted $i$ times in $score$ and $n+1-i$ times in $rscore$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nvoid solve() {\n    int norm = 0, rev = 0;\n    int q; cin >> q;\n    int tot = 0;\n    int n = 0;\n    deque<int> qNorm, qRev;\n    int p = 0;\n    while (q--) {\n        int s; cin >> s;\n        if (s == 1) {\n            int last = qNorm.back();\n            qNorm.pop_back();\n            qNorm.push_front(last);\n            norm += (tot - last);\n            norm -= last * n;\n            norm += last;\n\n            last = qRev.front();\n            qRev.pop_front();\n            qRev.push_back(last);\n            rev -= (tot - last);\n            rev += last * n;\n            rev -= last;\n        }\n        else if (s == 2) {\n            swap(rev, norm);\n            swap(qNorm, qRev);\n        }\n        else if (s == 3) {\n            n++;\n            int k; cin >> k;\n            qNorm.push_back(k);\n            qRev.push_front(k);\n            norm += k * n;\n            rev += tot;\n            rev += k;\n            tot += k;\n        }\n        cout << norm << \"\\n\";\n    }\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "data structures",
      "implementation",
      "math"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2094",
    "index": "H",
    "title": "La Vaca Saturno Saturnita",
    "statement": "Saturnita's mood depends on an array $a$ of length $n$, which only he knows the meaning of, and a function $f(k, a, l, r)$, which only he knows how to compute. Shown below is the pseudocode for his function $f(k, a, l, r)$.\n\n\\begin{verbatim}\nfunction f(k, a, l, r):\nans := 0\nfor i from l to r (inclusive):\nwhile k is divisible by a[i]:\nk := k/a[i]\nans := ans + k\nreturn ans\n\n\\end{verbatim}\n\nYou are given $q$ queries, each containing integers $k$, $l$, and $r$. For each query, please output $f(k,a,l,r)$.",
    "tutorial": "What must the value of $a[i]$ be in order for $k$ to change? $a[i]$ must be a divisor of $k$. Can we use this to bound the number of times $k$ changes? For each divisor $d$ of $k$, $k$ can only change once, because after the first iteration with $a[i] = d$, $k$ is no longer divisible by $d$. Thus, the number of times $k$ changes is bounded by the number of divisors of $k$. Consider a particular query. We make the following two observations: first, the value of $k$ only changes if $a[i]$ is a divisor of $k$, and second, if there exists $a[i_1] = a[i_2]$ with $l\\leq i_1 < i_2 \\leq r$, then the value of $k$ will not change at $i=i_2$ (because after the iteration $i=i_1$, we have that $k$ is no longer divisible by $a[i_2]$). This allows us to bound the number of times $k$ changes by $d(k)$, where $d(k)$ is the number of divisors of $k$. Note that the divisors of $d(k)$ can be found in $O(\\sqrt{k})$ time by checking if $a$ divides $k$ for every $a$ from $2$ to $\\sqrt{k}$, and if so, $a$ and $\\frac{k}{a}$ are both divisors of $k$. Furthermore, at the scale constrained by the problem bounds, $d(k)$ is around $O(\\sqrt[3]{k})$, so we only have to update $k$ at most $O(\\sqrt[3]{k})$ times. Now, we would like to find the first time each divisor of $k$ appears in $a[l], \\dots, a[r]$. This can be done by storing the array $a$ in a map, where each value is mapped to a vector of indices where that values appears. Then for a given divisor of $k$, we can use lower_bound() (or generally, binary search) to find the smallest index at or after $l$ where this divisor appears, and we can check if it is no greater than $r$. Now, we have a list of indices at which $k$ might change. So, suppose that $k$ changes to $k'$ at index $i_1$, and then changes to $k' '$ at index $i_2$ (and these are adjacent changes). Then we know that we have a value of $k'$ from $i=i_1$ to $i_2-1$, so we can add $k' \\cdot (i_2 - i_1)$ to $ans$. We can then do this for all changes. This allows us to solve the problem in $O(n\\log{n})$ preprocessing time and $O(\\sqrt{k} + d(k)\\log{n})$ time per query. There are a few ways to optimize the runtime further, if your implementation is too slow. We can use a vector (of vectors) instead of a map, since $A = \\max a_i = 10^5$ is reasonably small. Note that instantiating a vector of this size in every test case is too slow, so you may have to instantiate it globally and clear the vectors that were used after each test case. Another optimization is to preprocess divisors instead of computing them on the spot. We can compute and store the divisors of all integers $2\\leq a_i\\leq 10^5$ in $O(A\\log A)$ time in a vector of vectors where $divisor[a_i]$ contains all divisors of $a_i$ as follows: for all $2\\leq i\\leq A$, we push $i$ into $divisors[j]$ for all multiples $j$ of $i$. (The runtime follows from the fact that there are $\\lfloor\\frac{A}{i}\\rfloor$ multiples of $i$ which are at most $A$, so across all $i$, we have at most $\\frac{A}{1} + \\frac{A}{2} + \\cdots + \\frac{A}{A} = A(\\frac{1}{1} + \\cdots + \\frac{1}{A}) = AH(A) = O(A\\log A)$ computations). This allows us to remove the $\\sqrt{k}$ term in the runtime of each query.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n\nvoid solve() {\n    map<int, vector<int>> pos;\n    map<int, int> ptr;\n    int n, q; cin >> n >> q;\n    int arr[n+1];\n    for (int i = 1; i <= n; i++) {\n        cin >> arr[i];\n        pos[arr[i]].push_back(i);\n        ptr[arr[i]] = 0;\n    }\n    vector<tuple<int, int, int, int>> qr(q);\n    int c = 0;\n    for (auto &[l, r, v, i]: qr) {\n        cin >> v >> l >> r;\n        i = c++;\n    }\n    vector<int> anss(q);\n    sort(qr.begin(), qr.end());\n    int prevL = 1;\n    for (auto [l, r, v, idd]: qr) {\n        for (int j = prevL; j < l; j++) {\n            ptr[arr[j]]++;\n        }\n        prevL = l;\n        vector<pair<int, int>> facts;\n        for (int i = 1; i * i <= v; i++) {\n            if (v % i == 0) {\n                int fact1 = v / i;\n                if (!(pos[fact1].size() == 0 || ptr[fact1] >= pos[fact1].size() || pos[fact1][ptr[fact1]] > r || fact1 == 1)) {\n                    facts.push_back({pos[fact1][ptr[fact1]], fact1});\n                }\n                int fact2 = i;\n                if (fact2 == fact1) continue;\n                if (!(pos[fact2].size() == 0 || ptr[fact2] >= pos[fact2].size() || pos[fact2][ptr[fact2]] > r || fact2 == 1)) {\n                    facts.push_back({pos[fact2][ptr[fact2]], fact2});\n                }\n            }\n        }\n        sort(facts.begin(), facts.end());\n        int pr = l;\n        int ans = 0;\n        for (auto [idx, val]: facts) {\n            int rr = idx - pr;\n            ans += v * rr;\n            while (v % val == 0) v /= val;\n            pr = idx;\n        }\n        if (facts.empty()) ans = v * (r - l + 1);\n        else ans += (r - pr + 1) * v;\n        anss[idd] = ans;\n    }\n    for (int i = 0; i < q; i++) cout << anss[i] << \"\\n\";\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "math",
      "number theory"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2096",
    "index": "A",
    "title": "Wonderful Sticks",
    "statement": "You are the proud owner of $n$ sticks. Each stick has an integer length from $1$ to $n$. The lengths of the sticks are \\textbf{distinct}.\n\nYou want to arrange the sticks in a row. There is a string $s$ of length $n - 1$ that describes the requirements of the arrangement.\n\nSpecifically, for each $i$ from $1$ to $n - 1$:\n\n- If $s_i = <$, then the length of the stick at position $i + 1$ must be \\textbf{smaller} than all sticks before it;\n- If $s_i = >$, then the length of the stick at position $i + 1$ must be \\textbf{larger} than all sticks before it.\n\nFind any valid arrangement of sticks. We can show that an answer always exists.",
    "tutorial": "Create your own test cases and solve them! What can you observe? What is the length of the $n$-th stick? If $s_{n - 1} = \\texttt{<}$, then $a_n = 1$, because the $n$-th stick must be shorter than all the other sticks. If $s_{n - 1} = \\texttt{>}$, then $a_n = n$, because the $n$-th stick must be longer than all the other sticks. Can we do something similar for the remaining sticks? Yes! Remove the $n$-th stick, and then solve for the remaining $n - 1$ sticks. We can make similar observations about the $(n - 1)$-th stick. Then, remove the $(n - 1)$-th stick, and solve for the remaining $n - 2$ sticks, and so on. So the algorithm is as follows: Initialize an array $b = [1, 2, \\ldots, n]$. This represents the lengths of the remaining sticks. For each $i$ from $n - 1$ to $1$: If $s_i = \\texttt{<}$, then set $a_{i + 1} = \\min(b)$. If $s_i = \\texttt{>}$, then set $a_{i + 1} = \\max(b)$. Now remove $a_{i + 1}$ from $b$, and continue. If $s_i = \\texttt{<}$, then set $a_{i + 1} = \\min(b)$. If $s_i = \\texttt{>}$, then set $a_{i + 1} = \\max(b)$. Now remove $a_{i + 1}$ from $b$, and continue. In the end, we have $1$ remaining element in $b$. This is the value of $a_1$. The time complexity of this solution is $O(n^2)$. We can notice that at any point, $b$ has the form $[l, l + 1, \\ldots, r]$. So we can represent $b$ using two integers $l$ and $r$: When we remove $\\min(b)$, we increase $l$ by $1$. When we remove $\\max(b)$, we decrease $r$ by $1$. Now the time complexity of our solution is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid test() {\n    int n;\n    cin >> n;\n    string s;\n    cin >> s;\n\n    int l = 1;\n    int r = n;\n    vector<int> a(n);\n    for (int i = n - 2; i >= 0; i--) {\n        if (s[i] == '<') {\n            a[i + 1] = l;\n            l++;\n        }\n        if (s[i] == '>') {\n            a[i + 1] = r;\n            r--;\n        }\n    }\n    a[0] = l;\n\n    for (int i = 0; i < n; i++) {\n        cout << a[i] << \" \";\n    }\n    cout << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++) {\n        test();\n    }\n    \n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "2096",
    "index": "B",
    "title": "Wonderful Gloves",
    "statement": "You are the proud owner of many colorful gloves, and you keep them in a drawer. Each glove is in one of $n$ colors numbered $1$ to $n$. Specifically, for each $i$ from $1$ to $n$, you have $l_i$ left gloves and $r_i$ right gloves with color $i$.\n\nUnfortunately, it's late at night, so \\textbf{you can't see any of your gloves}. In other words, you will only know the color and the type (left or right) of a glove \\textbf{after} you take it out of the drawer.\n\nA matching pair of gloves with color $i$ consists of exactly one left glove and one right glove with color $i$. Find the minimum number of gloves you need to take out of the drawer to \\textbf{guarantee} that you have \\textbf{at least} $k$ matching pairs of gloves with \\textbf{different} colors.\n\nFormally, find the smallest positive integer $x$ such that:\n\n- For any set of $x$ gloves you take out of the drawer, there will always be at least $k$ matching pairs of gloves with different colors.",
    "tutorial": "Let's look at the third test case in the example. We have $k = 2$, and the answer is $x = 303$. If we take out $302$ gloves, then it's possible that we only have matching pairs of $1$ color. How can we generalize this fact for any $k$ and $x$? If we take out $(x - 1)$ gloves or fewer, then it's possible that we only have at most $(k - 1)$ matching pairs of different colors. So we can solve the problem as follows: Let $y$ be the maximum number of gloves we can take out so that there are at most $(k - 1)$ matching pairs of different colors. Then the answer to the problem is $x = y + 1$. Set $m = k - 1$. Now we need to find the maximum number of gloves so that there are at most $m$ matching pairs of different colors. Try solving it for $m = 0$ first. When $m = 0$, we want to find the maximum number of gloves so that there are no matching pairs. Therefore, for each color $i$, we can either take all the left gloves, or all the right gloves. So we should choose the type with more gloves. Formally, let $a_i = \\max(l_i, r_i)$. Then the maximum number of gloves we can take is $y = a_1 + a_2 + \\ldots + a_n$. Now, using the solution for $m = 0$, solve it for $m = 1$. Then solve it for $m = 2$, and so on. When $m = 0$, we take $a_i$ gloves of color $i$. So we're left with $b_i = \\min(l_i, r_i)$ gloves of color $i$ that we haven't taken. To get from $m = 0$ to $m = 1$, we can additionally form matching pairs of $1$ color. Therefore, we can choose a color $i$, and take the remaining $b_i$ gloves. So we should choose the color $i$ with the maximum value of $b_i$. In other words, for $m = 1$, the maximum number of gloves we can take is $y = a_1 + a_2 + \\ldots + a_n + \\max(b_1, b_2, \\ldots, b_n)$. To get from $m = 0$ to $m = 2$, we can additionally form matching pairs of $2$ different colors. Therefore, we can choose two different colors $i$ and $j$, and take the remaining $b_i + b_j$ gloves. So we should choose the two colors $i$ and $j$ with the maximum value of $b_i + b_j$. We can generalize this idea for any $m$. So the algorithm is as follows: Set $m = k - 1$. For each $i$ from $1$ to $n$, let $a_i = \\max(l_i, r_i)$ and $b_i = \\min(l_i, r_i)$. Set $y = a_1 + a_2 + \\ldots + a_n$. Sort the values of $b$ in descending order. Add the $m$ largest values of $b$ to $y$. The answer is $x = y + 1$. The time complexity of this solution is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid test() {\n    int n, k;\n    cin >> n >> k;\n    int m = k - 1;\n\n    vector<int> l(n);\n    for (int i = 0; i < n; i++) {\n        cin >> l[i];\n    }\n    vector<int> r(n);\n    for (int i = 0; i < n; i++) {\n        cin >> r[i];\n    }\n\n    vector<int> a(n), b(n);\n    long long y = 0;\n    for (int i = 0; i < n; i++) {\n        a[i] = max(l[i], r[i]);\n        b[i] = min(l[i], r[i]);\n        y += a[i];\n    }\n\n    sort(b.begin(), b.end(), greater<>());\n    for (int i = 0; i < m; i++) {\n        y += b[i];\n    }\n\n    long long x = y + 1;\n    cout << x << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++) {\n        test();\n    }\n    \n    return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2096",
    "index": "C",
    "title": "Wonderful City",
    "statement": "You are the proud leader of a city in Ancient Berland. There are $n^2$ buildings arranged in a grid of $n$ rows and $n$ columns. The height of the building in row $i$ and column $j$ is $h_{i, j}$.\n\nThe city is beautiful if no two adjacent by side buildings have the same height. In other words, it must satisfy the following:\n\n- There \\textbf{does not} exist a position $(i, j)$ ($1 \\leq i \\leq n$, $1 \\leq j \\leq n - 1$) such that $h_{i, j} = h_{i, j + 1}$.\n- There \\textbf{does not} exist a position $(i, j)$ ($1 \\leq i \\leq n - 1$, $1 \\leq j \\leq n$) such that $h_{i, j} = h_{i + 1, j}$.\n\nThere are $n$ workers at company A, and $n$ workers at company B. Each worker can be hired \\textbf{at most once}.\n\nIt costs $a_i$ coins to hire worker $i$ at company A. After hiring, worker $i$ will:\n\n- Increase the heights of all buildings in row $i$ by $1$. In other words, increase $h_{i, 1}, h_{i, 2}, \\ldots, h_{i, n}$ by $1$.\n\nIt costs $b_j$ coins to hire worker $j$ at company B. After hiring, worker $j$ will:\n\n- Increase the heights of all buildings in column $j$ by $1$. In other words, increase $h_{1, j}, h_{2, j}, \\ldots, h_{n, j}$ by $1$.\n\nFind the minimum number of coins needed to make the city beautiful, or report that it is impossible.",
    "tutorial": "We are given an $n \\times n$ matrix of positive integers. There are two types of operations we can perform: When we hire worker $i$ from company A, let's call it row operation $i$. When we hire worker $j$ from company B, let's call it column operation $j$. Each row and column operation can be performed at most once. After performing the operations, the matrix must satisfy the following: Horizontal Condition: No two horizontally adjacent elements are the same. Vertical Condition: No two vertically adjacent elements are the same. Suppose the matrix does not satisfy the Horizontal Condition, so there is a position $(i, j)$ such that $h_{i,j} = h_{i, j + 1}$. What operations can we perform to fix this? Don't worry about other positions for now. We just want $h_{i,j} \\neq h_{i, j + 1}$. We can either: Only perform column operation $j$, and increase $h_{i, j}$ by $1$; Or only perform column operation $(j + 1)$, and increase $h_{i, j + 1}$ by $1$. Notice that when we perform row operation $i$, we increase both $h_{i, j}$ and $h_{i, j + 1}$ by $1$. Therefore, the difference between the two elements does not change. Formally, when we perform row operation $i$, the value $d = h_{i, j} - h_{i, j + 1}$ does not change. From our previous observations, we see that: Only column operations affect the Horizontal Condition. Only row operations affect the Vertical Condition. So we can solve for the Horizontal Condition and the Vertical Condition independently. Using DP, we will calculate: The minimum total cost of the row operations required to satisfy the Vertical Condition. The minimum total cost of the column operations required to satisfy the Horizontal Condition. To get the answer, we add the two costs. Let $dp(i, x)$ be the minimum total cost of the row operations required so that: The first $i$ rows of the matrix satisfy the Vertical Condition. If $x = 0$, then we do not perform row operation $i$. If $x = 1$, then we perform row operation $i$. If it is impossible, then $dp(i, x) = \\infty$. Our base cases are $dp(1, 0) = 0$ and $dp(1, 1) = a_1$. For $i > 1$, initialize $dp(i, x)$ to $\\infty$. Our $dp(i, x)$ will depend on some $dp(i - 1, y)$. Now we need to check if row $(i - 1)$ and row $i$ satisfy the Vertical Condition: The elements in row $i - 1$ are: $(h_{i - 1, 1} + y), (h_{i - 1, 2} + y), \\ldots, (h_{i - 1, n} + y)$. The elements in row $i$ are: $(h_{i, 1} + x), (h_{i, 2} + x), \\ldots, (h_{i, n} + x)$. If no two vertically adjacent elements are the same, then: For $x = 0$, set $dp(i, x) = \\min(dp(i, x), dp(i - 1, y))$. For $x = 1$, set $dp(i, x) = \\min(dp(i, x), dp(i - 1, y) + a_i)$. The minimum total cost required so that the entire matrix satisfies the Vertical Condition is $\\min(dp(n, 0), dp(n, 1))$. Similarly, we can solve for the Horizontal Condition. The time complexity of this solution is $O(n^2)$. To avoid repetition, we can solve for the Horizontal Condition by transposing the matrix and treating it as the Vertical Condition instead.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nconst long long INF = 1e18;\n\nlong long solveHor(int n, vector<vector<int>>& h, vector<int>& a) {\n    vector<vector<long long>> dp(n, vector<long long>(2, INF));\n    dp[0][0] = 0;\n    dp[0][1] = a[0];\n\n    for (int i = 1; i < n; i++) {\n        for (int x = 0; x < 2; x++) {\n            for (int y = 0; y < 2; y++) {\n                bool ok = true;\n                for (int j = 0; j < n; j++) {\n                    ok &= (h[i - 1][j] + y != h[i][j] + x);\n                }\n                if (ok) {\n                    if (x == 0) {\n                        dp[i][x] = min(dp[i][x], dp[i - 1][y]);\n                    }\n                    if (x == 1) {\n                        dp[i][x] = min(dp[i][x], dp[i - 1][y] + a[i]);\n                    }\n                }\n            }\n        }\n    }\n\n    return min(dp[n - 1][0], dp[n - 1][1]);\n}\n\nvoid transpose(int n, vector<vector<int>>& h) {\n    for (int i = 0; i < n; i++) {\n        for (int j = i + 1; j < n; j++) {\n            swap(h[i][j], h[j][i]);\n        }\n    }\n}\n\nvoid test() {\n    int n;\n    cin >> n;\n\n    vector<vector<int>> h(n, vector<int>(n));\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < n; j++) {\n            cin >> h[i][j];\n        }\n    }\n\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n\n    vector<int> b(n);\n    for (int i = 0; i < n; i++) {\n        cin >> b[i];\n    }\n\n    long long horCost = solveHor(n, h, a);\n    transpose(n, h);\n    long long verCost = solveHor(n, h, b);\n    long long totalCost = horCost + verCost;\n\n    if (totalCost >= INF) {\n        cout << -1 << '\\n';\n    }\n    else {\n        cout << totalCost << '\\n';\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++) {\n        test();\n    }\n    \n    return 0;\n}",
    "tags": [
      "dp",
      "implementation"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2096",
    "index": "D",
    "title": "Wonderful Lightbulbs",
    "statement": "You are the proud owner of an infinitely large grid of lightbulbs, represented by a Cartesian coordinate system. Initially, all of the lightbulbs are turned off, except for one lightbulb, where you buried your proudest treasure.\n\nIn order to hide your treasure's position, you perform the following operation an arbitrary number of times (possibly zero):\n\n- Choose two \\textbf{integer} numbers $x$ and $y$, and switch the state of the $4$ lightbulbs at $(x, y)$, $(x, y + 1)$, $(x + 1, y - 1)$, and $(x + 1, y)$. In other words, for each lightbulb, turn it on if it was off, and turn it off if it was on. Note that there are \\textbf{no constraints} on $x$ and $y$.\n\nIn the end, there are $n$ lightbulbs turned on at coordinates $(x_1, y_1), (x_2, y_2), \\ldots, (x_n, y_n)$. Unfortunately, you have already forgotten where you buried your treasure, so now you have to figure out one possible position of the treasure. Good luck!",
    "tutorial": "What can we say about the number of lightbulbs that are turned on for any valid configuration in the input? Can the number of lightbulbs that are turned on be even? The number of lightbulbs that are turned on is always odd. This is because we start with exactly one lightbulb turned on. Every operation changes the state of $4$ lightbulbs, which is an even number. So no matter what operations we perform, we will always have an odd number of lightbulbs turned on. Let's use the idea of parity to come up with stricter conditions. Consider the lightbulbs on the vertical line $x = c$. What can we say about the number of lightbulbs that are turned on? Suppose the treasure is buried at position $(s, t)$. If $c = s$, then the line $x = c$ has an odd number of lightbulbs turned on. If $c \\neq s$, then the line $x = c$ has an even number of lightbulbs turned on. This is because every operation $(u, v)$ changes the state of $4$ lightbulbs: $(u, v)$, $(u, v + 1)$, $(u + 1, v - 1)$, $(u + 1, v)$. $2$ of them are on the vertical line $x = u$. $2$ of them are on the vertical line $x = u + 1$. From our previous observations, we can uniquely determine the value of $s$. Can we do the same for the value of $t$? Consider the lightbulbs on the diagonal line $x + y = c$. What can we say about the number of lightbulbs that are turned on? Suppose the treasure is buried at position $(s, t)$. If $c = s + t$, then the line $x + y = c$ has an odd number of lightbulbs turned on. If $c \\neq s + t$, then the line $x + y = c$ has an even number of lightbulbs turned on. This is because every operation $(u, v)$ changes the state of $4$ lightbulbs: $(u, v)$, $(u, v + 1)$, $(u + 1, v - 1)$, $(u + 1, v)$. $2$ of them are on the diagonal line $x + y = u + v$. $2$ of them are on the diagonal line $x + y = u + v + 1$. So, to summarize, we find two lines: The vertical line that has an odd number of lightbulbs turned on The diagonal line that has an odd number of lightbulbs turned on The intersection of these two lines is the position of the treasure.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid test() {\n    int n;\n    cin >> n;\n\n    map<int, int> cntVer, cntDiag;\n    for (int i = 0; i < n; i++) {\n        int x, y;\n        cin >> x >> y;\n        cntVer[x]++;\n        cntDiag[x + y]++;\n    }\n\n    int s;\n    for (auto [c, cnt]: cntVer) {\n        if (cnt % 2 == 1) {\n            s = c;\n            break;\n        }\n    }\n\n    int t;\n    for (auto [c, cnt]: cntDiag) {\n        if (cnt % 2 == 1) {\n            t = c - s;\n            break;\n        }\n    }\n\n    cout << s << \" \" << t << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++) {\n        test();\n    }\n    \n    return 0;\n}",
    "tags": [
      "combinatorics",
      "constructive algorithms",
      "math"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2096",
    "index": "E",
    "title": "Wonderful Teddy Bears",
    "statement": "You are the proud owner of $n$ teddy bears, which are arranged in a row on a shelf. Each teddy bear is colored either black or pink.\n\nAn arrangement of teddy bears is beautiful if all the black teddy bears are to the left of all the pink teddy bears. In other words, there \\textbf{does not} exist a pair of indices $(i, j)$ ($1 \\leq i < j \\leq n$) such that the $i$-th teddy bear is pink, and the $j$-th teddy bear is black.\n\nYou want to reorder the teddy bears into a beautiful arrangement. You are too short to reach the shelf, but luckily, you can send instructions to a robot to move the teddy bears around. In a single instruction, the robot can:\n\n- Choose an index $i$ ($1 \\le i \\le n - 2$) and reorder the teddy bears at positions $i$, $i + 1$ and $i + 2$ so that all the black teddy bears are to the left of all the pink teddy bears.\n\nWhat is the minimum number of instructions needed to reorder the teddy bears?",
    "tutorial": "First, we'll treat all the black teddy bears as $0$ and all the pink teddy bears as $1$. So we are given a binary array of length $n$. In one operation, we can choose three consecutive elements and sort them in ascending order. Now we need to find the minimum number of operations required to sort the array. There are four possible types of operations, depending on the values of the elements: Operation A: $(0, 1, 0) \\rightarrow (0, 0, 1)$ Operation B: $(1, 0, 0) \\rightarrow (0, 0, 1)$ Operation C: $(1, 0, 1) \\rightarrow (0, 1, 1)$ Operation D: $(1, 1, 0) \\rightarrow (0, 1, 1)$ Let's think of a greedy solution first. Which operations are better than others? We can evaluate an operation by how much it reduces the number of inversions in the array: Operation A reduces the number of inversions by $1$. Operation B reduces the number of inversions by $2$. Operation C reduces the number of inversions by $1$. Operation D reduces the number of inversions by $2$. Therefore, ideally, we'd only perform operations B and D. Let $x$ be the number of inversions in the original array. Then the answer is at least $\\left\\lceil \\frac{x}{2} \\right\\rceil$. Suppose we keep performing operations B and D until we can no longer do so. What will the array look like? The array will have the form $[0, 0, \\ldots, 0, 0, 1, 0, 1, 0, \\ldots 1, 0, 1, 0, 1, 1, \\ldots, 1, 1]$. In other words, the array will consist of: A (possibly empty) sequence of consecutive $0$'s; A (possibly empty) sequence of alternating $1$'s and $0$'s; And a (possibly empty) sequence of consecutive $1$'s. Since the array has a sequence of alternating $1$'s and $0$'s, we should think about parity. Let $a$ be the number of $0$'s in the entire array, and $b$ be the number of $0$'s in the even positions. When the array is sorted, all the $0$'s will be at the beginning of the array. So in the end, $b = \\left\\lfloor \\frac{a}{2} \\right\\rfloor$. Consider how each type of operation changes the value of $b$: Operation A either increases or decreases the value of $b$ by $1$. Operation B does not change the value of $b$. Operation C either increases or decreases the value of $b$ by $1$. Operation D does not change the value of $b$. Therefore, we can only use operations A and C to change the value of $b$. Let $d = \\lvert \\, \\left\\lfloor \\frac{a}{2} \\right\\rfloor - b \\, \\rvert$. Then we need at least $d$ operations of type A or type C. After these $d$ operations, the array will have $(x - d)$ inversions. We can show that $(x - d)$ must be even. Then, we perform $\\frac{x - d}{2}$ operations of type B or type D to reduce the number of inversions to $0$. So the answer to the problem is: $d + \\frac{x - d}{2} = \\frac{x + d}{2}$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid test() {\n    int n;\n    cin >> n;\n\n    string s;\n    cin >> s;\n\n    long long x = 0;\n    int a = 0;\n    int b = 0;\n    for (int i = n - 1; i >= 0; i--) {\n        if (s[i] == 'B') {\n            a++;\n            if ((i + 1) % 2 == 0) {\n                b++;\n            }\n        }\n        if (s[i] == 'P') {\n            x += a;\n        }\n    }\n\n    int d = abs(a / 2 - b);\n    cout << (x + d) / 2 << '\\n';\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    int t;\n    cin >> t;\n    for (int i = 0; i < t; i++) {\n        test();\n    }\n    \n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2096",
    "index": "F",
    "title": "Wonderful Impostors",
    "statement": "You are a proud live streamer known as Gigi Murin. Today, you will play a game with $n$ viewers numbered $1$ to $n$.\n\nIn the game, each player is either a crewmate or an impostor. You don't know the role of each viewer.\n\nThere are $m$ statements numbered $1$ to $m$, which are either \\textbf{true or false}. For each $i$ from $1$ to $m$, statement $i$ is one of two types:\n\n- $0\\:a_i\\:b_i$ ($1 \\leq a_i \\leq b_i \\leq n$) — there are no impostors among viewers $a_i, a_i + 1, \\ldots, b_i$;\n- $1\\:a_i\\:b_i$ ($1 \\leq a_i \\leq b_i \\leq n$) — there is \\textbf{at least} one impostor among viewers $a_i, a_i + 1, \\ldots, b_i$.\n\nAnswer $q$ questions of the following form:\n\n- $l\\:r$ ($1 \\leq l \\leq r \\leq m$) — is it possible that statements $l, l + 1, \\ldots, r$ are \\textbf{all true}?\n\nNote that it is \\textbf{not guaranteed} that there is at least one impostor among all viewers, and it is \\textbf{not guaranteed} that there is at least one crewmate among all viewers.",
    "tutorial": "Let's call a set of statements satisfiable if it's possible that all of them are true. How do we check if a set of statements is satisfiable? For each statement of the form $0\\,a_l\\,a_r$, assign all viewers from $a_l$ to $a_r$ as crewmates. Then, assign the rest of the viewers as impostors. Now check if all statements of the form $1\\,b_l\\,b_r$ are true. When a segment of statements $[s_l, s_r]$ is satisfiable, what can we say about other segments of statements? If $[s_l, s_r]$ is satisfiable, then $[s_l + 1, s_r]$ and $[s_l, s_r - 1]$ are also satisfiable. We'll use the two pointers method. For each $s_r$, let $low(s_r)$ be the smallest $s_l$ such that $[s_l, s_r]$ is satisfiable. To answer a question $s_l\\,s_r$, we just check that $s_l \\geq low(s_r)$. When we increment $s_r$, we will add statement $(s_r + 1)$. So we must increment $s_l$ and remove statements from the beginning of the segment until $[s_l, s_r + 1]$ is satisfiable. Now we need to efficiently check if we can add a new statement to our current set of statements. Let's rephrase how to determine if a set of statements is satisfiable. For statements of the form $0\\,a_l\\,a_r$, we'll call $[a_l, a_r]$ a $0$-segment. For statements of the form $0\\,a_l\\,a_r$, we'll call $[a_l, a_r]$ a $0$-segment. Similarly, for statements of the form $1\\,b_l\\,b_r$, we'll call $[b_l, b_r]$ a $1$-segment. Similarly, for statements of the form $1\\,b_l\\,b_r$, we'll call $[b_l, b_r]$ a $1$-segment. When $0$-segments overlap and form a larger segment, we'll call it a $0$-component. When $0$-segments overlap and form a larger segment, we'll call it a $0$-component. Then, a set of statements is satisfiable if there does not exist a $1$-segment that is fully covered by a $0$-component. When we add a $1$-segment $[b_l, b_r]$, we need to check if it will be fully covered by a $0$-component. For each $i$ from $1$ to $n$, let $count(i)$ be the number of $0$-segments that contain viewer $i$. Then, we can add $[b_l, b_r]$ if $\\min(count(b_l), count(b_l + 1), \\ldots, count(b_r)) = 0$. The values of $count(i)$ can be maintained using a segment tree. When we add a $0$-segment $[a_l, a_r]$, it might merge several $0$-components. So first we need to find the $0$-component $[c_l, c_r]$ that contains $[a_l, a_r]$: $c_l$ is the smallest value such that $\\min(count(c_l), count(c_l + 1), \\ldots, count(a_l)) > 0$. $c_r$ is the largest value such that $\\min(count(a_r), count(a_r + 1), \\ldots, count(c_r)) > 0$. Both of these values can be found by performing a walk on the segment tree. Now we need to check if there's a $1$-segment that's fully covered by $[c_l, c_r]$. Sort all the $1$-segments in the input by ascending value of $b_r$. Then, for all segments that satisfy $b_r \\leq c_r$, find the one with largest value of $b_l$. If $b_l \\geq c_l$, then $[b_l, b_r]$ is fully covered by $[c_l, c_r]$. We can maintain another segment tree with prefix-max queries.",
    "tags": [
      "data structures",
      "implementation",
      "two pointers"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2096",
    "index": "G",
    "title": "Wonderful Guessing Game",
    "statement": "\\textbf{This is an interactive problem.}\n\nYou are a proud teacher at the Millennium Science School. Today, a student named Alice challenges you to a guessing game.\n\nAlice is thinking of an integer from $1$ to $n$, and you must guess it by asking her some queries.\n\nTo make things harder, she says you must \\textbf{ask all the queries first}, and she will \\textbf{ignore} exactly $1$ query.\n\nFor each query, you choose an array of $k$ \\textbf{distinct} integers from $1$ to $n$, where $k$ is even. Then, Alice will respond with one of the following:\n\n- $L$: the number is one of the first $\\frac{k}{2}$ elements of the array;\n- $R$: the number is one of the last $\\frac{k}{2}$ elements of the array;\n- $N$: the number is not in the array;\n- $?$: this query is ignored.\n\nAlice is impatient, so you must find a strategy that \\textbf{minimizes} the number of queries. Can you do it?\n\nFormally, let $f(n)$ be the minimum number of queries required to determine Alice's number. Then you must find a strategy that uses \\textbf{exactly} $f(n)$ queries.\n\nNote that the interactor is \\textbf{adaptive}, which means Alice's number is not fixed at the beginning and may depend on your queries. However, it is guaranteed that there exists at least one number that is consistent with Alice's responses.\n\nWe can show that $f(n) \\leq 20$ for all $n$ such that $2 \\le n \\le 2 \\cdot 10^5$.",
    "tutorial": "First, try solving it if Alice doesn't ignore any queries. We can represent the queries using a table. Let's look at the second test case in the example: Each row is a query. Column $x$ contains Alice's responses if her number was $x$. Let's treat $\\texttt{L}$ as $-1$, $\\texttt{R}$ as $1$, and $\\texttt{N}$ as $0$. Then, our strategy works if each row has a sum of $0$ and all $n$ columns are distinct. Since there are only $3$ possible values, we need at least $q = \\left\\lceil \\log_3(n) \\right\\rceil$ queries. In fact, this lower bound can be achieved. We generate all $3^{q}$ possible columns: $[x_1, x_2, \\ldots, x_q]$, where $x_i \\in$ $\\text{\\{}$$-1, 0, 1$$\\text{\\}}$. Now we need to choose $n$ of them so that they sum to $0$. To do this, we can choose one pair of columns at a time: First, we choose $[x_1, x_2, \\ldots, x_q]$; Then, we choose $[-x_1, -x_2, \\ldots, -x_q]$. We see that each pair of columns sums to $0$. If $n$ is odd, we can include $[0, 0, \\ldots, 0]$. Now let's try to solve the original problem. For our strategy to work, it must satisfy the following: Each row has a sum of $0$. No two columns are the same. No two columns differ by exactly $1$ element. To achieve this, we only need $1$ additional query. Here's another way to think about it: For each column, no matter which element is ignored, we should be able to uniquely determine the missing value. We use the same solution as before, but with $1$ more element: For each column $[x_1, x_2, \\ldots, x_q]$, add an element $x_{q + 1}$ such that $(x_1 + x_2 + \\ldots + x_{q + 1})\\mod 3 = 0$. Because the sum of each column is $0$ modulo $3$, we can uniquely recover any missing element.",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "interactive"
    ],
    "rating": 3200
  },
  {
    "contest_id": "2096",
    "index": "H",
    "title": "Wonderful XOR Problem",
    "statement": "You are the proud... never mind, just solve this problem.\n\nThere are $n$ intervals $[l_1, r_1], [l_2, r_2], \\ldots [l_n, r_n]$. For each $x$ from $0$ to $2^m - 1$, find the number, modulo $998\\,244\\,353$, of sequences $a_1, a_2, \\ldots a_n$ such that:\n\n- $l_i \\leq a_i \\leq r_i$ for all $i$ from $1$ to $n$;\n- $a_1 \\oplus a_2 \\oplus \\ldots \\oplus a_n = x$, where $\\oplus$ denotes the bitwise XOR operator.",
    "tutorial": "Is this FFT? Let's consider the XOR convolution. Given two polynomials $A(x)$ and $B(x)$ with degree at most $(2^{m} - 1)$, the XOR convolution $C(x) = A(x) \\star B(x)$ is defined as follows: $\\displaystyle [x^k]C(x) = \\sum_{0 \\leq i < 2^m \\\\ 0 \\leq j < 2^m \\\\ i \\oplus j = k} [x^i]A(x) \\cdot [x^j]B(x)$ To efficiently compute the XOR convolution, we can use FWHT. First, let $s(k, i) = (-1)^{\\text{popcount}(k\\,\\&\\,i)}$. Then, $F(A(x))$ is defined as follows: $\\displaystyle [x^k]F(A(x)) = \\sum_{0 \\leq i < 2^m} [x^i]A(x) \\cdot s(k, i)$ Given $A^{\\,\\prime}(x) = F(A(x))$, we can uniquely determine $A(x) = F^{-1}(A^{\\,\\prime}(x))$ using the inverse of FWHT. To compute $F(A(x))$ and $F^{-1}(A^{\\,\\prime}(x))$, we can use SOS DP. Define the dot product $D(x) = A(x) \\cdot B(x)$ as follows: $\\displaystyle [x^k]D(x) = [x^k]A(x) \\cdot [x^k]B(x)$ We can show that $F(A(x) \\star B(x)) = F(A(x)) \\cdot F(B(x))$ for any two polynomials $A(x)$ and $B(x)$. Let's solve the problem. For each interval $[l_i, r_i]$, let $A_i(x) = x^{l_i} + x^{l_i + 1} + \\ldots + x^{r_i}$. We want to find $A_1(x) \\star A_2(x) \\star \\ldots \\star A_n(x)$. To do this, we'll compute $F^{-1}(F(A_1(x)) \\cdot F(A_2(x)) \\cdot \\ldots \\cdot F(A_n(x)))$. We can note that $\\displaystyle [x^k]F(A_i(x)) = \\sum_{l_i \\leq j \\leq r_i} s(k, j)$ Let $f(k, r) = \\displaystyle \\sum_{0 \\leq j \\leq r} s(k, j)$. Then $\\displaystyle [x^k]F(A_i(x)) = f(k, r_i) - f(k, l_i - 1)$. Now we need to find a way to compute $f(k, r)$ efficiently. Let $p$ be the ($0$-indexed) position of the least significant bit of $k$. Let $c = \\left\\lfloor \\frac{r}{2^{p + 1}} \\right\\rfloor$. Then $f(k, r) = \\displaystyle f(k, c \\cdot 2^{p+1} - 1) + \\sum_{c \\cdot 2^{p + 1} \\leq j \\leq r} s(k, j)$ Due to cancellation of terms, we have $f(k, c \\cdot 2^{p+1} - 1) = 0$. We can also see that $s(k, j) = s(2^p, j) \\cdot s\\left(\\left\\lfloor \\frac{k}{2^{p + 1}} \\right\\rfloor, \\left\\lfloor \\frac{j}{2^{p + 1}} \\right\\rfloor\\right) = s(2^p, j) \\cdot s\\left(\\left\\lfloor \\frac{k}{2^{p + 1}} \\right\\rfloor, c\\right)$ Therefore, $\\displaystyle f(k, r) = \\left(\\sum_{c \\cdot 2^{p + 1} \\leq j \\leq r} s(2^p, j)\\right) \\cdot s\\left(\\left\\lfloor \\frac{k}{2^{p + 1}} \\right\\rfloor, c\\right)$. Returning to $F(A_i(x))$, we get: $\\displaystyle [x^k]F(A_i(x)) = a_i \\cdot s(k^{\\,\\prime}, c_i) + b_i \\cdot s(k^{\\,\\prime}, d_i)$ where: $a_i$ and $b_i$ are constants independent of $k$. $k^{\\,\\prime} = \\left\\lfloor \\frac{k}{2^{p + 1}} \\right\\rfloor$, $c_i = \\left\\lfloor \\frac{r_i}{2^{p + 1}} \\right\\rfloor$, and $d_i = \\left\\lfloor \\frac{l_i - 1}{2^{p + 1}} \\right\\rfloor$. But wait! This is just $[x^{k^{\\,\\prime}}]F(a_i \\cdot x^{c_i} + b_i \\cdot x^{d_i})$. So we'll let $B_i(x) = a_i \\cdot x^{c_i} + b_i \\cdot x^{d_i}$. Therefore, $[x^k](F(A_1(x)) \\cdot F(A_2(x)) \\cdot \\ldots \\cdot F(A_n(x))) = [x^{k^{\\,\\prime}}]F(B_1(x) \\star B_2(x) \\star \\ldots \\star B_n(x))$ Now we need to find a way to compute $F(B_1(x) \\star B_2(x) \\star \\ldots \\star B_n(x))$ efficiently. First, we can normalize each polynomial: $a \\cdot x^c + b \\cdot x^d = (a + b \\cdot x^{c\\,\\oplus\\,d}) \\star x^c$ Now all polynomials have the form $a_i + b_i \\cdot x^{c_i}$. Next, we can convolve polynomials with matching powers of $x$: $(a_1 + b_1 \\cdot x^c) \\star (a_2 + b_2 \\cdot x^c) = (a_1 a_2 + b_1 b_2) + (a_1 b_2 + b_1 a_2) \\cdot x^c$ Now the expression is of the form: $F((a_0 + b_0 \\cdot x^0) \\star (a_1 + b_1 \\cdot x^1) \\star \\ldots \\star (a_{2^m - 1} + b_{2^m - 1} \\cdot x^{2^m - 1})) = F(B_0) \\cdot F(B_1) \\cdot \\ldots \\cdot F(B_{2^m - 1})$ Finally, we have: $\\displaystyle [x^k] (F(B_0) \\cdot F(B_1) \\cdot \\ldots \\cdot F(B_{2^m - 1})) = \\prod_{i = 0}^{2^m - 1} (a_i + b_i \\cdot s(k, i))$ This can be computed using SOS DP.",
    "tags": [
      "bitmasks",
      "combinatorics",
      "dp",
      "fft",
      "math"
    ],
    "rating": 3200
  },
  {
    "contest_id": "2097",
    "index": "A",
    "title": "Sports Betting",
    "statement": "The boarding process for various flights can occur in different ways: either by \\textbf{bus} or through a \\textbf{telescopic jet bridge}. Every day, exactly one flight is made from St. Petersburg to Minsk, and Vadim decided to demonstrate to the students that he always knows in advance how the boarding will take place.\n\nVadim made a bet with $n$ students, and with the $i$-th student, he made a bet on day $a_i$. Vadim wins the bet if he correctly predicts the boarding process on both day $a_i+1$ and day $a_i+2$.\n\nAlthough Vadim does not know in advance how the boarding will occur, he really wants to win the bet \\textbf{at least} with one student and convince him of his predictive abilities. Check if there exists a strategy for Vadim that allows him to \\textbf{guarantee} success.",
    "tutorial": "Let's sort the array $a$ in non-decreasing order: $a_1 \\le a_2 \\le \\ldots \\le a_n$. Suppose Vadim argues with the students in turn. We can formalize the problem as follows: since there are only two possible seating arrangements each day, we can encode them with the digits $0$ and $1$. Each of Vadim's predictions can be represented by a pair of numbers $(c_i, d_i)$-the seating arrangement for days $a_i+1$ and $a_i+2$, respectively. Vadim will be able to win in the following cases: If there exists a quadruple of students $a_i = a_{i+1} = a_{i+2} = a_{i+3}$, meaning those students he will argue with on the same day. In this case, he can provide all possible $4$ predictions for days $a_i+1$ and $a_i+2$ and will guarantee at least one correct prediction. If there exists a pair of indices $i < j$ such that $a_i = a_{i+1} < a_j = a_{j+1}$ and for each $x \\in \\{ a_i+1, a_i+2, \\ldots, a_j-1 \\}$ there exists a $k$ such that $a_k = x$. Suppose on day $x$ and day $y$ ($x < y$) Vadim argues with at least two students, and on days $x+1,\\ldots,y-1$ with at least one student. On day $x$, Vadim makes predictions $(0,1)$ and $(1,1)$. On each of the days $x+1,\\ldots,y-1$, Vadim makes predictions $(0,1)$. On day $y$, Vadim makes predictions $(0,0)$ and $(0,1)$. Suppose on day $x$ and day $y$ ($x < y$) Vadim argues with at least two students, and on days $x+1,\\ldots,y-1$ with at least one student. On day $x$, Vadim makes predictions $(0,1)$ and $(1,1)$. On each of the days $x+1,\\ldots,y-1$, Vadim makes predictions $(0,1)$. On day $y$, Vadim makes predictions $(0,0)$ and $(0,1)$. To prove the correctness of Vadim's strategy, consider the string $s_{x+1} \\ldots s_{y+1} s_{y+2}$-the seating arrangements from day $x$ to day $y$. If $s_{x+1} \\neq 0$ or $s_{y+1} \\neq 1$, then Vadim can definitively convince at least one student on day $x$ or day $y$. Otherwise, if $s_{x+1}=0$ and $s_{y+1}=1$, then there exists a day $z$ ($x \\le z < y$) such that $s_{z+1}=0$ and $s_{z+2}=1$, which means Vadim can convince a student on day $z$. It can be shown that in all other cases, Vadim loses. To demonstrate this, we need to fix an arbitrary strategy of Vadim's and try to find a counterexample to his strategy. The general plan for the proof is as follows: If $a_i + 2 \\le a_i$, then the segments of students $[1, i]$ and $[i+1, n]$ can be considered independently. Let's consider a block of students with whom Vadim argues without breaks. If $a_1 < a_2$ or $a_{n-1} < a_n$, then the first or, respectively, the last student can be easily discarded without affecting the other students. Otherwise, we have $a_1 = a_2 \\le \\ldots \\le a_{n-1} = a_n$, which is the only case where Vadim has no winning strategy according to the previous point, when $n \\le 3$.",
    "tags": [
      "2-sat",
      "brute force",
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2097",
    "index": "B",
    "title": "Baggage Claim",
    "statement": "Every airport has a baggage claim area, and Balbesovo Airport is no exception. At some point, one of the administrators at Sheremetyevo came up with an unusual idea: to change the traditional shape of the baggage claim conveyor from a carousel to a more complex form.\n\nSuppose that the baggage claim area is represented as a rectangular grid of size $n \\times m$. The administration proposed that the path of the conveyor should pass through the cells $p_1, p_2, \\ldots, p_{2k+1}$, where $p_i = (x_i, y_i)$.\n\nFor each cell $p_i$ and the next cell $p_{i+1}$ (where $1 \\leq i \\leq 2k$), these cells must share a common side. Additionally, the path must be simple, meaning that for no pair of indices $i \\neq j$ should the cells $p_i$ and $p_j$ coincide.\n\nUnfortunately, the route plan was accidentally spoiled by spilled coffee, and only the cells with odd indices of the path were preserved: $p_1, p_3, p_5, \\ldots, p_{2k+1}$. Your task is to determine the number of ways to restore the original complete path $p_1, p_2, \\ldots, p_{2k+1}$ given these $k+1$ cells.\n\nSince the answer can be very large, output it modulo $10^9+7$.",
    "tutorial": "If any pair of adjacent cells $p_{2i-1}$ and $p_{2i+1}$ is at a distance other than $2$, then the answer is $0$. Otherwise, for each such pair of cells, there are two possible cases: Cells $p_{2i-1}$ and $p_{2i+1}$ are in the same row or column. Then cell $p_{2i}$ must be located between them. In the other case, there are two possible positions for cell $p_{2i}$. We will construct a graph where the vertices are all the cells of the field, and edges are created for each even cell $p_2, \\ldots, p_{2k}$. If cell $p_{2i}$ can only be in position $\\alpha$, we draw a self-loop at vertex $\\alpha$. If cell $p_{2i}$ can be in position $\\alpha$ or $\\beta$, we draw an edge connecting these two vertices. Thus, we need to choose an incident vertex for each edge such that each vertex is chosen at most once. It is clear that this problem can be solved independently for each connected component, and then we multiply the answers for all components: If a component with $s$ vertices contains more than $s$ edges, then the answer is $0$ (Dirichlet's principle). If a component with $s$ vertices has exactly $s$ edges, then the component contains exactly one cycle. If this cycle is a loop, then the answer is $1$. If it is a non-degenerate cycle, then the answer is $2$. If this cycle is a loop, then the answer is $1$. If it is a non-degenerate cycle, then the answer is $2$. If the component with $s$ vertices is a tree, then the answer is $s$ (we choose an unchosen vertex, and then everything is determined).",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "dp",
      "dsu",
      "graphs",
      "implementation",
      "math",
      "trees"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2097",
    "index": "C",
    "title": "Bermuda Triangle",
    "statement": "The Bermuda Triangle — a mysterious area in the Atlantic Ocean where, according to rumors, ships and airplanes disappear without a trace. Some blame magnetic anomalies, others — portals to other worlds, but the truth remains hidden in a fog of mysteries.\n\nA regular passenger flight 814 was traveling from Miami to Nassau on a clear sunny day. Nothing foreshadowed trouble until the plane entered a zone of strange flickering fog. Radio communication was interrupted, the instruments spun wildly, and flashes of unearthly light flickered outside the windows.\n\nFor simplicity, we will assume that the Bermuda Triangle and the airplane are on a plane, and the vertices of the triangle have coordinates $(0, 0)$, $(0, n)$, and $(n, 0)$. Initially, the airplane is located at the point $(x, y)$ \\textbf{strictly inside} the Bermuda Triangle and is moving with a velocity vector $(v_x, v_y)$. All instruments have failed, so the crew cannot control the airplane.\n\nThe airplane can escape from the triangle if it ever reaches exactly one of the vertices of the triangle. However, if at any moment (possibly non-integer) the airplane hits the boundary of the triangle (but not at a vertex), its velocity vector is immediately reflected relative to that side$^\\dagger$, and the airplane continues to move in the new direction.\n\nDetermine whether the airplane can ever escape from the Bermuda Triangle (i.e., reach exactly one of its vertices). If this is possible, also calculate how many times before that moment the airplane will hit the boundary of the triangle (each touch of the boundary, even at the same point, counts; crossing a vertex does not count).\n\n$^\\dagger$ Reflection occurs according to the usual laws of physics. The angle of incidence equals the angle of reflection.",
    "tutorial": "We will use the idea of reflections. Instead of saying that the plane is reflected with respect to a side, we will say that it actually flew further but ended up in the triangle that results from reflecting the original triangle with respect to that side. All such triangles form a pattern of the following kind. The vertices of the triangles are located at all possible points of the form $(nx, ny)$ ($x, y \\in \\mathbb{Z}$). Accordingly, it is easy to see that we can reduce the velocity vector such that $\\textrm{gcd}(v_x, v_y) = 1$. Then, to determine the time it will take for the plane to exit the triangle, we use the Chinese remainder theorem: $v_x t + x \\equiv 0 \\pmod{n}$ $v_y t + y \\equiv 0 \\pmod{n}$ Accordingly, we can compute such a minimal non-negative suitable $t$. Next, we need to calculate the number of reflections. Essentially, this is the number of times the segment $(x, y)$, $(v_x t + x, v_y t + y)$ intersects the lines in the figure above. If the endpoint is $(t_x \\cdot n, t_y \\cdot n)$, then the number of intersections is as follows: the number of intersections with vertical segments is $t_x - 1$, with horizontal segments is $t_y - 1$, the number of lines parallel to the hypotenuse of the original triangle is $\\lfloor \\frac{1}{2}[t_x+t_y] \\rfloor$, and the number of lines perpendicular to the original hypotenuse is $\\lfloor \\frac{1}{2} |t_x-t_y| \\rfloor$.",
    "tags": [
      "chinese remainder theorem",
      "geometry",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2097",
    "index": "D",
    "title": "Homework",
    "statement": "Some teachers work at the educational center \"Sirius\" while simultaneously studying at the university. In this case, the trip does not exempt them from completing their homework, so they do their homework right on the plane. Artem is one of those teachers, and he was assigned the following homework at the university.\n\nWith an arbitrary string $a$ of \\textbf{even} length $m$, he can perform the following operation. Artem splits the string $a$ into two halves $x$ and $y$ of equal length, after which he performs \\textbf{exactly one} of three actions:\n\n- For each $i \\in \\left\\{ 1, 2, \\ldots, \\frac{m}{2}\\right\\}$ assign $x_i = (x_i + y_i) \\bmod 2$;\n- For each $i \\in \\left\\{ 1, 2, \\ldots, \\frac{m}{2}\\right\\}$ assign $y_i = (x_i + y_i) \\bmod 2$;\n- Perform an arbitrary number of operations (the same operations defined above, applied recursively) on the strings $x$ and $y$, independently of each other. Note that in this case, the strings $x$ and $y$ must be of even length.\n\nAfter that, the string $a$ is replaced by the strings $x$ and $y$, concatenated in the same order.Unfortunately, Artem fell asleep on the plane, so you will have to complete his homework. Artem has two binary strings $s$ and $t$ of length $n$, each consisting of $n$ characters 0 or 1. Determine whether it is possible to make string $s$ equal to string $t$ with \\textbf{an arbitrary} number of operations.",
    "tutorial": "The problem itself is trivial, but solving it requires not skipping lectures on linear algebra. Suspecting that not all participants are familiar with the basics of linear algebra, we will try to explain each step in detail. Part 1. Matrices. Let $n = k \\cdot m$, where $m$ is an odd number, and $k$ is a power of two. Any binary string $s$ of length $n$ can be represented as a matrix $M(s)$: $M(s) = \\begin{pmatrix} s_1 & s_2 & \\cdots & s_m \\\\ s_{m+1} & s_{m+2} & \\cdots & s_{2m} \\\\ \\vdots & \\vdots & \\ddots & \\vdots \\\\ s_{n-m+1} & s_{n-m+2} & \\cdots & s_{n} \\end{pmatrix}$ It is easy to prove that any operation $\\mu$ (one move, several moves, or none) that transforms string $s$ into string $t$ can be expressed as $\\hat{\\mu} \\cdot M(s) = M(t)$, where $\\hat{\\mu}$ is a matrix in $\\mathbb{Z}_2^{k \\times k}$. Indeed: If $k=1$, the only possible operation $\\mu$ does nothing, and $\\hat{\\mu} = I_n$ (the identity matrix). If the operation $\\mu$ adds the second half of $s$ to the first half, then $\\hat{\\mu}$ can be written in block form: $\\hat{\\mu} = \\begin{pmatrix} I & I \\\\ I & 0 \\end{pmatrix}$ $\\hat{\\mu} = \\begin{pmatrix} I & I \\\\ I & 0 \\end{pmatrix}$ If the operation $\\mu$ adds the first half to the second half, then $\\hat{\\mu}$ can also be written in block form. If $\\mu$ independently changes the left and right halves of $s$ using operations $\\mu_1$ and $\\mu_2$, then $\\hat{\\mu}$ has the form: $\\hat{\\mu} = \\begin{pmatrix} \\hat{\\mu}_1 & 0 \\\\ 0 & \\hat{\\mu}_2 \\end{pmatrix}$ $\\hat{\\mu} = \\begin{pmatrix} \\hat{\\mu}_1 & 0 \\\\ 0 & \\hat{\\mu}_2 \\end{pmatrix}$ If $\\mu$ is a combination of operations $\\mu_1, \\ldots, \\mu_l$, then $\\hat{\\mu} = \\hat{\\mu_l} \\ldots \\hat{\\mu_1}$. Part 2. Torment and Suffering. Proposition. For any invertible matrix $A \\in \\textrm{GL}(\\mathbb{Z}_2^k)$, there exists an operation $\\mu$ such that $\\hat{\\mu} = A$. Proof. The case $k=1$ is trivial; for $k=2$, we can explicitly provide expressions for elementary transformations. Adding one row to another is trivial, and swapping them can be done as follows: $\\begin{pmatrix}x\\\\y\\end{pmatrix} \\to \\begin{pmatrix}x+y\\\\y\\end{pmatrix} \\to \\begin{pmatrix}x+y\\\\x+2y\\end{pmatrix} = \\begin{pmatrix}x+y\\\\x\\end{pmatrix} \\to \\begin{pmatrix}y\\\\x\\end{pmatrix}$ Comment. Yes, this is the implementation of std::swap using the XOR operation. Now consider the case $k > 2$. By the induction hypothesis, we can apply any invertible transformation to the halves of string $s$ at any moment. Let $x_1, \\ldots, x_t$ be the first $t = \\frac{k}{2}$ rows of the matrix $M(s)$, and $y_1, \\ldots, y_t$ be the second half of the rows. We will show that we can add row $y_1$ to row $x_1$ using the specified operations: $\\begin{pmatrix} x_1 \\\\ x_2 \\\\ \\vdots \\\\ x_t \\\\ y_1 \\\\ y_2 \\\\ \\vdots \\\\ y_t \\end{pmatrix} \\to \\begin{pmatrix} x_1 + x_2 \\\\ x_1 \\\\ \\vdots \\\\ x_t \\\\ y_1 \\\\ y_2 \\\\ \\vdots \\\\ y_t \\end{pmatrix} \\to \\begin{pmatrix} x_1 + x_2 \\\\ x_1 \\\\ \\vdots \\\\ x_t \\\\ y_1 + x_1 + x_2 \\\\ y_2 + x_1 \\\\ \\vdots \\\\ y_t + x_t \\end{pmatrix} \\to \\begin{pmatrix} x_1 + x_2 \\\\ x_1 \\\\ \\vdots \\\\ x_t \\\\ y_1 + y_2 + x_2 \\\\ y_2 + x_1 \\\\ \\vdots \\\\ y_t + x_t \\end{pmatrix} \\to \\begin{pmatrix} x_1 + x_2 \\\\ x_1 \\\\ \\vdots \\\\ x_t \\\\ y_1 + y_2 + x_1 \\\\ y_2 \\\\ \\vdots \\\\ y_t \\end{pmatrix} \\to \\begin{pmatrix} x_1 \\\\ x_2 \\\\ \\vdots \\\\ x_t \\\\ y_1 + x_1 \\\\ y_2 \\\\ \\vdots \\\\ y_t \\end{pmatrix}$ Then, to add any row from the second half to the first, we should shuffle the rows in the first and second halves so that the required rows are at the top, perform the specified sequence of actions, and then restore the original order of the rows. Similarly, a row from the first half can be added to the second half. Thus, any row can be added to any other. And since swapping two rows is realized through this operation, and considering that matrices live in $\\mathbb{Z}_2$, this means that any elementary operation can be represented in terms of the operations described. Since any invertible matrix $A$ can be represented as a composition of elementary operations, it can be represented as a composition of some operations $\\mu$. To summarize, this proof turned out to be a bit more unpleasant than we expected. A good concept here would be to feel the idea of this proof instead of getting bogged down in every technical transition. Part 3. A Cute Algorithm. To check whether string $s$ can be transformed into string $t$, based on the above proof, it is sufficient to check whether there exists an invertible matrix $A$ such that $A \\cdot M(s) = M(t)$. We apply the Gaussian elimination algorithm to $M(s)$ and $M(t)$, which uses row operations to bring $M(s)$ and $M(t)$ to reduced row echelon form $G(s)$ and $G(t)$, respectively. Then the answer to the problem is \"Yes\" if and only if $G(s) = G(t)$, which follows from the uniqueness of the reduced row echelon form of a matrix. The Gaussian elimination algorithm for a matrix $M$ of size $m \\times k$ runs in time: $O(m k \\cdot \\textrm{rnk} \\, B) = O(m k \\cdot \\min \\{m, k\\}) = O(n \\sqrt n)$ Since we are working with bit matrices, using std::bitset, the algorithm can be improved to run in time $O\\left(\\frac{n \\sqrt n}{w}\\right)$; however, the solution without bitsets also runs in an acceptable time despite the large constraints in the problem.",
    "tags": [
      "bitmasks",
      "math",
      "matrices"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2097",
    "index": "E",
    "title": "Clearing the Snowdrift",
    "statement": "Boy Vasya loves to travel very much. In particular, flying in airplanes brings him extraordinary pleasure. He was about to fly to another city, but the runway was heavily covered with snow and needed to be cleared.\n\nThe runway can be represented as $n$ consecutive sections numbered from $1$ to $n$. The snowstorm was quite strong, but it has already stopped, so Vasya managed to calculate that the $i$-th section is covered with $a_i$ meters of snow. For such situations, the airport has a snowplow that works in a rather unusual way. In one minute, the snowplow can do the following:\n\n- Choose a consecutive segment of length no more than $d$ and remove one meter of snow from the most snow-covered sections.Formally, one can choose $1 \\le l \\le r \\le n$ ($r - l + 1 \\le d$). After that, $c = \\max \\{ a_l, a_{l + 1}, \\ldots , a_r \\}$ is calculated, and if $c > 0$, then for all $i \\colon l \\le i \\le r$ such that $a_i = c$, the value of $a_i$ is decreased by one.\n\nVasya has been preparing for the flight for a long time and wants to understand how much time he has left to wait until all sections are completely cleared of snow. In other words, it is required to calculate the minimum number of minutes that the snowplow will need to achieve $a_i = 0$ for all $i$ from $1$ to $n$.",
    "tutorial": "We will assign to each operation the maximum $a_i$ on the segment of that operation. Consider some order of operations that zeroes out the entire array. If there are two adjacent operations in which the maximum on the segment of the earlier operation is smaller, then we can swap these two operations without changing anything (we leave this simple case analysis as an exercise for the reader). Thus, from any sequence, we can obtain a sequence of operations of the same length where the assigned maximums on the segments of the operations do not increase during the process. Now let $C$ denote the maximum element in the array. Then one of the optimal sequences of operations will first decrease by one all numbers equal to $C$, then all numbers equal to $C - 1$, and so on. How can we calculate the minimum number of operations needed to decrease all numbers equal to the current maximum in the array by one? We will look at the positions of these maximums (let's denote this set of positions as $S$); they need to be covered by the minimum number of segments of length no more than $d$. This is a standard problem that can be solved using a greedy algorithm: Take the leftmost uncovered point $x \\in S$, place a segment $[x, \\min(x + d - 1, n)]$, Remove all points from $S \\cap [x, \\min(x + d - 1, n)]$, Repeat until $S$ is empty. Now we can solve the problem in $O(n \\cdot C)$, but that is slow. Let's denote the sorted set of numbers in the array as $x_1 < x_2 \\ldots < x_k$. We will also introduce $x_0 = 0$. While we are decreasing the maximums from $x_i$ to $x_{i-1}$, the set $S$ does not change, meaning the greedy process is the same and always selects the same number of segments. Thus, it is sufficient to run the greedy process once. We obtain a solution in $O(n^2)$. Now let's optimize this solution. We only need to find the number of segments in the greedy process for the sets $S_j = \\{i : a_i \\geq x_j\\}, 0 \\leq j \\leq k$. Let's simulate this process simultaneously from left to right. Consider $a_1$. Let $a_1 = x_i$. Then for all sets numbered from $0$ to $i$, a segment of length $d$ starts at this element. Let's remember this and say that these sets will return to consideration when we reach the processing of $a_{d+1}$, because up to that point the elements are covered by the segment. We will continue doing this. We take all sets with numbers less than or equal to $j$ (where the current element of the array is equal to $x_j$), for which the segments have already ended, update the answer, and say that these sets will finish their segment after $d$ processed elements in the scanline. These are some operations with sets that can be maintained in a segment tree, which essentially stores the indices of the sets included in the segment tree, meaning only the paths to the leaves corresponding to the numbers of these sets are stored (somewhat similar to an implicit segment tree). The asymptotic complexity of the solution is $O(n \\cdot \\log(n))$. Similar operations can be maintained in a Cartesian tree, but that would lead to a larger constant and $O(n \\cdot \\log^2(n))$, which should not pass the time limits. For more details, you can read the author's solution. There is also a solution using link-cut trees, which is simpler to understand but requires knowledge of this structure, so it was not intended as the author's solution.",
    "tags": [
      "data structures",
      "dfs and similar",
      "dp",
      "greedy"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2097",
    "index": "F",
    "title": "Lost Luggage",
    "statement": "As is known, the airline \"Trouble\" often loses luggage, and concerned journalists decided to calculate the maximum number of luggage pieces that may not return to travelers.\n\nThe airline \"Trouble\" operates flights between $n$ airports, numbered from $1$ to $n$. The journalists' experiment will last for $m$ days. It is known that at midnight before the first day of the experiment, there were $s_j$ lost pieces of luggage in the $j$-th airport. On the $i$-th day, the following occurs:\n\n- \\textbf{In the morning}, $2n$ flights take off simultaneously, including $n$ flights of the first type and $n$ flights of the second type.\n\n- The $j$-th flight of the first type flies from airport $j$ to airport $(((j-2) \\bmod n )+ 1)$ (the previous airport, with the first airport being the last), and it can carry no more than $a_{i,j}$ lost pieces of luggage.\n- The $j$-th flight of the second type flies from airport $j$ to airport $((j \\bmod n) + 1)$ (the next airport, with the last airport being the first), and it can carry no more than $c_{i,j}$ lost pieces of luggage.\n\n- \\textbf{In the afternoon}, a check of lost luggage is conducted at the airports. If after the flights have departed on that day, there are $x$ pieces of luggage remaining in the $j$-th airport and $x \\ge b_{i, j}$, then at least $x - b_{i, j}$ pieces of luggage are found, and they \\textbf{cease to be lost}.\n- \\textbf{In the evening}, all $2n$ flights conclude, and the lost luggage transported that day arrives at the corresponding airports.\n\nFor each $k$ from $1$ to $m$, the journalists want to know the maximum number of lost pieces of luggage that may be \\textbf{unfound} during the checks over the first $k$ days. Note that for each $k$, these values are calculated independently.",
    "tutorial": "It is clear that the problem can be solved using flows. We will introduce a dummy source $s$ and $(m+1) n$ vertices $(i,j)$ ($0 \\le i \\le m$, $1 \\le j \\le n$), and the following edges will be added to the network: For all $j$ ($1 \\le j \\le n$), edges from $s$ to $(0, j)$ with capacity $s_j$. For all pairs $i$, $j$ ($1 \\le i \\le m$, $1 \\le j \\le n$), edges from $(i-1,j)$ to $(i,(j-2)\\bmod n + 1)$ with capacity $a_{i,j}$. For all pairs $i$, $j$ ($1 \\le i \\le m$, $1 \\le j \\le n$), edges from $(i-1,j)$ to $(i,j)$ with capacity $b_{i,j}$. For all pairs $i$, $j$ ($1 \\le i \\le m$, $1 \\le j \\le n$), edges from $(i-1,j)$ to $(i,j \\bmod n + 1)$ with capacity $c_{i,j}$. To each layer $i$ ($1 \\le i \\le m$), we will connect edges to the sink $t_i$ (for all $j$, edges from $(i, j)$ to $t_i$ will have capacity $\\infty$). Thus, the answer to the problem is the values of the maximum flows from $s$ to $t_1, t_2, \\ldots, t_m$, respectively. Unfortunately for the participants, the maximum flows $f_1, \\ldots, f_m$ ($f_i$ is the maximum flow from $s$ to $t_i$) can differ significantly from each other. This causes algorithms based on the Ford-Fulkerson method to work unjustifiably slowly, specifically in time $\\Omega(m^2 n^3)$. If we are wrong, and you managed to squeeze your solution, please share it in the comments :) The values of the maximum flows can be found using the Ford-Fulkerson theorem with the help of dynamic programming. Specifically, let $\\textrm{dp}[k][\\textrm{msk}]$ be the minimum $ST$-cut on the subgraph $s \\cup\\{ (i,j) \\}_{i,j=0,1}^{k,n}$, where the vertex $(k,j)$ is in the $T$ part of the cut if and only if the $j$-th bit of the mask $\\textrm{msk}$ is equal to $1$. This dynamic can be easily computed in time $O(m \\cdot 4^n)$, but again, this is too slow. The author's solution is to speed up the recalculation of the next layer of dynamics to time $O(2^n \\cdot n)$. Let $\\textrm{prv} = \\textrm{dp}[i-1]$ be the already computed layer of dynamics, and $\\textrm{nxt} = \\textrm{dp}[i]$ be the layer of dynamics that we want to compute. Instead of indexing by the mask in the forms, we will index these arrays by sets of vertices of the corresponding layer that are in the $T$ part of the cut. $\\textrm{nxt}[U] = \\min_{W} \\left\\{ \\textrm{prv}[W] + \\sum_{i=1}^n \\sum_{j=-1}^1 [i+j \\not \\in W] \\cdot [i \\in U] \\cdot e(i, j) \\right\\}$ A couple of clarifications: $e(i, j)$ is simply the weights of the edges between layers $i-1$ and $i$ in a convenient order. It is very difficult for me to keep track of the indices accurately, and this is just a technical detail, so reconstruct how to form $e(i,j)$ from the arrays $a_i$, $b_i$, and $c_i$ from the context. $i + j \\not \\in W$ actually means $(i+j-1)\\bmod n + 1 \\not \\in W$. Here $[ P ]$ is the Iverson bracket. $[P]=1$ when the predicate $P$ is satisfied, and $[P]=0$ otherwise. The main difficulty of the recalculation lies in the fact that the set $U$ determines which summands will participate in the sum and which will not. For a fixed $U$, each zero bit in the mask $W$ is assigned its own penalty; in other words, we define $\\lambda_U(i) = \\sum_{j=-1}^1 [i - j \\in U] e(i, j)$, then: $\\textrm{nxt}[U] = \\min_{W} \\left\\{ \\textrm{prv}[W] + \\sum_{i=1}^n [i \\not \\in W] \\cdot \\lambda_U(i) \\right\\}$ To efficiently recalculate, we will build a segment tree. Formally, it will be defined as follows: The segment tree contains $n+1$ layers numbered $0,1,2,\\ldots,n$. The indices of the vertices of the $i$-th layer are subsets $\\{1,2,\\ldots,i\\}$, and the two children of the vertex $L$ of the $i$-th layer are the vertices $L$ and $L \\cup \\{i+1\\}$ from the $(i+1)$-th layer. The value at the vertex $L$ from the $i$-th layer is equal to $x(i, L)$, where: $x(i, L) = \\min_{D \\subseteq \\{i+1, \\ldots, n\\}} \\{ \\textrm{prv}[L \\cup D] + \\sum_{j=i+1}^n [j \\not \\in W] \\cdot \\lambda_U(j) \\}$ $x(i, L) = \\min_{D \\subseteq \\{i+1, \\ldots, n\\}} \\{ \\textrm{prv}[L \\cup D] + \\sum_{j=i+1}^n [j \\not \\in W] \\cdot \\lambda_U(j) \\}$ It is clear that the value $x(i-1, L)$ can be easily computed as $x(i-1, L) = \\min \\{x(i, L) + \\lambda_U(i), x(i, L \\cup \\{i\\}\\}$. This structure is good because when changing $U$, we only need to recalculate the constructed tree up to the last layer where the weight function $\\lambda_U$ changed. Now we will iterate over $U$ in the order of Gray codes approximately in the following order: $\\emptyset \\to \\{2\\} \\to \\{2, 3\\} \\to \\{3\\} \\to \\ldots \\{1, \\ldots \\} \\to \\ldots$ The essence of this process is that we will iterate through all possible sets $U$, where the 2nd bit will change $2^{n-1}$ times, the 3rd bit will change $2^{n-2}$ times, and so on, the $n$-th bit will change $2$ times, while the 1st bit will change only once. When changing the $i$-th bit in $U$, the function $\\lambda_U$ will change at points $i-1$, $i$, and $i+1$, thus: If $2 \\le i \\le n-1$, only the first $i+1$ layers of the segment tree will change, and it will take $2^{i+2}$ operations to recalculate them, which will happen $2^{n+1-i}$ times. If $i = 1$ or $i=n$, the entire tree will need to be rebuilt, but this will only happen $3$ times. The total number of affected vertices when iterating over $U$ will be: $3 \\cdot 2^{n+1} + \\sum_{i=1}^{n-1} 2^{i+1} \\cdot 2^{n+1-i} = 3 \\cdot 2^{n+1} + (n-2) 2^{n+2} = (2n-1) \\cdot 2^{n+1} = O(n \\cdot 2^n)$ Here the constant is not very good and the time constraints are strict, so we will also have to put effort into the implementation. I think it is worth mentioning that using a segment tree on pointers is not a very good idea, and one should write the segment tree in the same indexing as a regular segment tree.",
    "tags": [
      "dp",
      "flows"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2098",
    "index": "A",
    "title": "Vadim's Collection",
    "statement": "We call a phone number a beautiful if it is a string of $10$ digits, where the $i$-th digit from the left is at least $10 - i$. That is, the first digit must be at least $9$, the second at least $8$, $\\ldots$, with the last digit being at least $0$.\n\nFor example, 9988776655 is a beautiful phone number, while 9099999999 is not, since the second digit, which is $0$, is less than $8$.\n\nVadim has a \\textbf{beautiful} phone number. He wants to rearrange its digits in such a way that the result is the \\textbf{smallest possible beautiful} phone number. Help Vadim solve this problem.\n\nPlease note that the phone numbers are compared as integers.",
    "tutorial": "Our goal is to obtain the minimally possible string that satisfies the conditions of beauty. Therefore, we need to arrange the digits in order from the first to the last, each time choosing the minimally possible suitable digit. More formally: For the $i$-th position, we need to place the smallest available digit that is not less than $10 - i$. After placing a digit, it becomes unavailable for further use. We repeat the process for all $10$ positions. Why does this work? Notice that when we place a digit in the $i$-th position, we have at least $i$ digits in the original number that are greater than or equal to $10 - i$, meaning that at most $i-1$ digits have been used from them earlier, and there is always some option available. Thus, at each step, it is beneficial to choose the smallest available suitable digit because the number can always be completed to the end, and choosing a larger digit would result in a larger number.",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "2098",
    "index": "B",
    "title": "Sasha and the Apartment Purchase",
    "statement": "Sasha wants to buy an apartment on a street where the houses are numbered from $1$ to $10^9$ from left to right.\n\nThere are $n$ bars on this street, located in houses with numbers $a_1, a_2, \\ldots, a_n$. Note that there might be multiple bars in the same house, and in this case, these bars are considered distinct.\n\nSasha is afraid that by the time he buys the apartment, some bars may close, but \\textbf{no more than} $k$ bars can close.\n\nFor any house with number $x$, define $f(x)$ as the sum of $|x - y|$ over all open bars $y$ (that is, after closing some bars).\n\nSasha can potentially buy an apartment in a house with number $x$ (where $1 \\le x \\le 10^9$) if and only if it is possible to close at most $k$ bars so that after that $f(x)$ becomes minimal among all houses.\n\nDetermine how many different houses Sasha can potentially buy an apartment in.",
    "tutorial": "Note that for a fixed position, the optimal point is the median (or for an even number of elements, any point between the two medians). Proof: Observe that if we move the point between $x$ and $x + 1$, the answer changes by the difference in the number of elements to the left and right between $x$ and $x + 1$. Therefore, $f(x)$ monotonically decreases to the median. This means that the optimum is indeed located at the median. Now the problem has been reduced to the following: how many such points exist such that if we remove no more than $k$ of the original elements, this point remains the median. Note that to obtain the optimal answer, we can simply remove elements from the beginning or from the end, since if two elements are on different sides of the median, this action does nothing. Thus, our answer lies within the segment, and it is (the formulas need to be adjusted with the correct plus or minus one, we will leave this as an exercise for the participants) $a_{\\frac{n + k}{2}} - a_{\\frac{n - k}{2}}$, where $a$ is sorted beforehand.",
    "tags": [
      "math",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2101",
    "index": "A",
    "title": "Mex in the Grid",
    "statement": "You are given $n^2$ cards with values from $0$ to $n^2-1$. You are to arrange them in a $n$ by $n$ grid such that there is \\textbf{exactly} one card in each cell.\n\nThe MEX (minimum excluded value) of a subgrid$^{\\text{∗}}$ is defined as the smallest non-negative integer that does not appear in the subgrid.\n\nYour task is to arrange the cards such that the sum of MEX values over all $\\left(\\frac{n(n+1)}{2}\\right)^2$ subgrids is maximized.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A subgrid of a $n$ by $n$ grid is specified by four numbers $l_1, r_1, l_2, r_2$ satisfying $1\\le l_1\\le r_1\\le n$ and $1\\le l_2\\le r_2\\le n$. The element in the $i$-th row and the $j$-th column of the grid is part of the subgrid if and only if $l_1\\le i\\le r_1$ and $l_2\\le j\\le r_2$.\n\\end{footnotesize}",
    "tutorial": "What is the MEX, if $0$ is not there? When is the MEX equal to $k$? If we want a subgrid to be included in as many other subgrids as possible, what shape should it have? What about its place? The first fact to notice is that if the subgrid does not contain $0$, then the MEX is $0$ and we can ignore such subgrids. If the MEX is going to be $k$, it means all the values from $0$ to $k-1$ are included in the subgrid. For each $0\\le k\\le n^2$, we count how many subgrids have a MEX of at least $k$, aiming to maximize this. To find the total sum of all MEX values, for each $k$ we count the number of subgrids that contain all the values from $0$ to $k-1$. Summing these counts gives us the final result. We claim that if our subgrid is nearly square (either a perfect square or a difference of $1$ in lengths), and is placed in the middle of the grid, then the answer is maximized. Proof: The multiplication of two numbers with the same sum is maximized when they are as close to each other as possible. Therefore, for each subgrid, if we consider the empty rows above and below it and separately consider the columns on its right and left, if one is fixed, the place is optimized to be in the middle. Now, similarly, we can say that it is optimal if the length and height of the subgrid are close to each other as well, as increasing one will cause the other one to decrease. With these two observations combined, a subgrid having the above properties is optimal when it's a nearly square subgrid in the middle of the grid. Any ordering with this property works; an easy example is a spiral shape that starts from the center of the grid and turns around itself. We had the idea of dividing this problem into two subtasks, in which the second subtask requires you to count the sum of MEX of all subgrids! Do you have a solution for this? Comment it below",
    "code": "def magical_spiral(n):\n    arr = [[-1] * n for _ in range(n)]\n    \n    if n % 2 == 0:\n        x, y = n // 2 - 1, n // 2 - 1\n    else:\n        x, y = n // 2, n // 2\n    \n    arr[x][y] = 0\n    value = step = 1\n\n    dir = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n\n    while value < n * n:\n        for d in range(4):\n            steps = step\n            \n            step += d % 2; dx, dy = dir[d]\n\n            for _ in range(steps):\n                x += dx; y += dy\n\n                if 0 <= x < n and 0 <= y < n and arr[x][y] == -1:\n                    arr[x][y] = value\n                    value += 1\n                if value >= n * n:\n                    break\n            \n            if value >= n * n:\n                break\n\n\n    for row in arr:\n        print(\" \".join(str(num) for num in row))\n    print()\n\n\nt = int(input())\n\nfor _ in range(t):\n    n = int(input())\n\n    magical_spiral(n)",
    "tags": [
      "constructive algorithms",
      "implementation"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2101",
    "index": "B",
    "title": "Quartet Swapping",
    "statement": "You are given a permutation $a$ of length $n$$^{\\text{∗}}$. You are allowed to do the following operation any number of times (possibly zero):\n\n- Choose an index $1\\le i\\le n - 3$. Then, swap $a_i$ with $a_{i + 2}$, and $a_{i + 1}$ with $a_{i + 3}$ simultaneously. In other words, permutation $a$ will be transformed from $[\\ldots, a_i, a_{i+1}, a_{i+2}, a_{i+3}, \\ldots]$ to $[\\ldots, a_{i+2}, a_{i+3}, a_{i}, a_{i+1}, \\ldots]$.\n\nDetermine the lexicographically smallest permutation$^{\\text{†}}$ that can be obtained by applying the above operation any number of times.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{†}}$An array $x$ is lexicographically smaller than an array $y$ of the same size if and only if the following holds:\n\n- in the first position where $x$ and $y$ differ, the array $x$ has a smaller element than the corresponding element in $y$.\n\n\\end{footnotesize}",
    "tutorial": "Is it possible for an element to change its index parity after some operations? What else is not effected by the operation? How to combine the above two properties under the time limit? The first observation is that the parity of the position of the elements doesn't change with the operations. Thus, if an element is at an odd or even index in the initial permutation, it will retain the same parity in the final permutation. As long as we have four elements left, we can freely adjust them within their index parity zone, but what about the last three ones? We can see that the parity of the number of inversions is fixed, so by counting the inversions of the initial permutation, the order of the last four elements will be uniquely determined. This problem was one of the first problems that we had, and the intended constraits were $n\\le 3000$ as a D1A, but later was moved to D1B with $n\\le 2\\cdot 10^5$! Do you know how to count the parity of inversions without counting the number of inversions?",
    "code": "#include <bits/stdc++.h>\n\n#define pb push_back\n#define int long long \n#define F first\n#define S second\n#define sz(a) (int)a.size()\n#define pii pair<int,int> \n#define rep(i , a , b) for(int i = (a) ; i <= (b) ; i++)\n#define per(i , a , b) for(int i = (a) ; i >= (b) ; i--)\n#define all(a) a.begin(),a.end() \n\nusing namespace std ;\nconst int maxn = 1e6 + 10 ;\nint a[maxn] , n , fen[maxn] ; \n\nvoid upd(int x){\n    while(x <= n){\n        fen[x]++;\n        x += x&-x;\n    }\n}\n\nint que(int x){\n    int ans =0 ;\n    while(x){\n        ans += fen[x] ;\n        x -= x&-x;\n    }\n    return ans ; \n}\n\nint f(vector<int> x){\n    rep(i , 0, n)fen[i] =0;\n    int ans =0 ;\n    per(i , sz(x)-1 , 0){\n        ans += que(x[i]);\n        upd(x[i]) ;\n    }\n    \n    return ans ; \n}\n\nsigned main(){\n    ios::sync_with_stdio(0) ; cin.tie(0);\n    \n    int T ;\n    cin >> T ;\n    \n    while(T--){\n        vector <int> a1 , a2 ; \n        \n        cin >> n ;\n        rep(i ,1 ,n){\n            int x; cin >> x; \n            \n            if (i%2==1) {\n                a1.pb(x);\n            } else {\n                a2.pb(x);\n            }\n        }    \n        \n        bool v = (f(a1)%2 != f(a2)%2);\n        \n        sort(all(a1)); sort(all(a2));\n        \n        int x1 = 0, x2 =0;    \n        \n        rep (i ,1 , n) {\n            if (i%2==1) {\n                a[i] = a1[x1] ; x1++; \n            } else {\n                a[i] = a2[x2] ; x2++;\n            }\n        }\n        \n        if (v) {\n            swap(a[n] , a[n-2]) ;\n        }\n        \n        rep(i ,1 ,n) cout << a[i] << \" \";\n        cout << \"\\n\";\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "divide and conquer",
      "greedy",
      "sortings"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2101",
    "index": "C",
    "title": "23 Kingdom",
    "statement": "The distance of a value $x$ in an array $c$, denoted as $d_x(c)$, is defined as the largest gap between any two occurrences of $x$ in $c$.\n\nFormally, $d_x(c) = \\max(j - i)$ over all pairs $i < j$ where $c_i = c_j = x$. If $x$ appears only once or not at all in $c$, then $d_x(c) = 0$.\n\nThe beauty of an array is the sum of the distances of each distinct value in the array. Formally, the beauty of an array $c$ is equal to $\\sum\\limits_{1\\le x\\le n} d_x(c)$.\n\nGiven an array $a$ of length $n$, an array $b$ is nice if it also has length $n$ and its elements satisfy $1\\le b_i\\le a_i$ for all $1\\le i\\le n$. Your task is to find the maximum possible beauty of any nice array.",
    "tutorial": "Does it matter if there are $2$ occurance of a number or $200$? What greedy approaches can you think of? Are they fast enough? The first observation is that we only care about the first and last occurrences of each number in the final array, as anything in between doesn't change the maximum distance. Instead of counting the distances directly, the main idea of this problem is to break them down into pieces. For example, the distance of a pair $(i, j)$ such that $1\\le i < j\\le n$ and $a_i = a_j$ and also these indices are the farthest possible, instead of adding up $j-i$, we count one for each index in between $i$ and $j$. In Another word, for each index $i$, we count how many begins are in or before $i$, and how many ends are after $i$, adding up these values for each index gives us the sum of distances. For each prefix and suffix of our array, we count the maximum number of different begins that we can get greedily. It can be proven that if we try to match each $a_i$ with the biggest unmatched number left, we'll end up getting the maximum number of different matches possible. Doing so can be calculated in many different ways, one using sets is shown in the implementation below. After that, for each $1\\le i < n$, we have a bound for the number of pairs that these indices can be in between of, as we calculated the maximum distinct matches possible for both sides (one prefix and one suffix). It can be proven that there exists an array $b$ meeting the problem conditions such that the bound for each index is held, and therefore summing up all values gives us the final answer. We thought every greedy approach for this problem is wrong, and the intended solution used to be a $O(n^3)$ DP, but later realized we were wrong! Can you think of a rational DP idea that despite the time limit can solve this question?",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n\n// #pragma GCC target(\"avx2,bmi,bmi2,lzcnt,popcnt\")\n// #pragma GCC optimize(\"O3\")\n// #pragma GCC optimize(\"unroll-loops\")\n\n\n#define F first \n#define S second\n#define mp make_pair\n#define pb push_back\n#define all(x) x.begin(), x.end()\n#define kill(x) cout << x << \"\\n\", exit(0);\n#define pii pair<int, int>\n#define pll pair<long long, long long>\n#define endl \"\\n\"\n \n \n \nusing namespace std;\ntypedef long long ll;\n// typedef __int128_t lll;\ntypedef long double ld;\n\n\nconst int MAXN = (int)1e6 + 7;\nconst int MOD = (int)1e9 + 7;\nconst ll INF = (ll)1e18 + 7;\n\nint n, m, k, tmp, t, tmp2, tmp3, tmp4, u, v, w, p, q, ans, flag;\nint arr[MAXN], f[MAXN][2];\nset<int> st;\n\n\nvoid solve() {\n    cin >> n;\n\n    for (int i=1; i<=n; i++) cin >> arr[i];\n\n    for (int j=0; j<2; j++) {\n        st.clear();\n        for (int i=1; i<=n; i++) st.insert(i);\n\n        for (int i=(j? n : 1); (j?i>1 : i<n); (j? i-- : i++)) {\n            auto it = st.upper_bound(arr[i]);\n\n            if (it != st.begin()) it--, st.erase(*it);\n\n            f[i][j] = n-st.size();\n        }\n    }\n    \n    ans = 0;\n    for (int i=1; i<n; i++) ans += min(f[i][0], f[i+1][1]);\n\n    cout << ans << endl;\n}\n\nint32_t main() {\n    #ifdef LOCAL\n    freopen(\"inp.in\", \"r\", stdin);\n    freopen(\"res.out\", \"w\", stdout);\n    #else\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    #endif\n\n    cin >> t;\n\n    while (t--) solve();\n\n\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "ternary search",
      "two pointers"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2101",
    "index": "D",
    "title": "Mani and Segments",
    "statement": "An array $b$ of length $|b|$ is cute if the sum of the length of its Longest Increasing Subsequence (LIS) and the length of its Longest Decreasing Subsequence (LDS)$^{\\text{∗}}$ is \\textbf{exactly} one more than the length of the array. More formally, the array $b$ is cute if $\\operatorname{LIS}(b) + \\operatorname{LDS}(b) = |b| + 1$.\n\nYou are given a permutation $a$ of length $n$$^{\\text{†}}$. Your task is to count the number of non-empty subarrays$^{\\text{‡}}$ of permutation $a$ that are cute.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) element from arbitrary positions.\n\nThe longest increasing (decreasing) subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing (decreasing) order.\n\n$^{\\text{†}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\n$^{\\text{‡}}$An array $x$ is a subarray of an array $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "What are some characteristics of a cute subarray? Is cuteness a monotone property? How to find the maximal cute subarray for a fixed index $i$? The first observation is that a subarray is cute, iff there is an index $i$, such that it is the one and only share of the LIS and LDS, and all other elements belong to either LIS or LDS. Proof: We know that there cannot be two elements belonging to both LIS and LDS, and if there is none, the property won't be held. Therefore, we conclude that there is exactly one element shared between the LIS and LDS. Diving deeper into the shared element, we can see that the smaller elements before it must all be ascending, and the bigger elements after it must also all be ascending (as this will make our LIS). Similarly, all the bigger elements before it and all the smaller elements after it should be descending. This gives us a good pattern, and we can easily see that any subarray included within a cute subarray is cute itself (call this monotonic property). For counting the total number of cute subarrays, we calculate the values of $R_i$ and $L_i$ for each index. Let $L_i$ be the biggest index before $i$, such that the condition above is met. Similarly define $R_i$ as the $smallest$ index after $i$. If we can somehow calculate this values for all indices, then we'll end up with $n$ segments (for each $1\\le i\\le n$), and a subarray is cute iff it's included in at least one segment. This is a very classic problem, so the solution won't be discussed here. The only detail left is how to calculate the values of $L_i$ and $R_i$? We'll discuss the process of calculating the $R_i$ here, but the $L_i$ follows a very similar pattern. We claim that $R_i = min(R_{i+1}, f(i))$. In here $f(i)$ is defined as follow: if $a_i > a_{i+1}$: then $f(i)$ is minimum index $j$, such that $a_{i+1}\\le a_j\\le a_i$. if $a_i < a_{i+1}$: in this case $f(i)$ is minimum $j$ such that $a_i\\le a_j\\le a_{i+1}$. Proof: The fact that $R_i\\le R_{i+1}$ can easily be concluded from the fact thay cuteness is a monotonic property. Also going back to the conditions described above, we can see that $f(i)$ is basically the first index that will ruin our condition, so based on the definition of $R_i$, we can say that $R_i = min(R_{i+1}, f(i))$. The calculation of $L_i$ and $R_i$ can both be implemented using a Segment Tree or a Monotonic Stack; both implementations are included below. After we have those values, we count the number of subarrays included in at least one segment, and that would be our final answer. We ended up having two D1D difficulty problems, but in the end chose this one as it was more cute! We believe this was one of the cleanest problems we had. However, both the statement and solution made it look too classic, so we had a hard time making sure this idea had not been used elsewhere! Do you have a different approach than ours? Tell us in the comments.",
    "code": "#include <bits/stdc++.h>\n \n#define pb push_back\n#define int long long \n#define F first\n#define S second\n#define sz(a) (int)a.size()\n#define pii pair<int,int> \n#define rep(i , a , b) for(int i = (a) ; i <= (b) ; i++)\n#define per(i , a , b) for(int i = (a) ; i >= (b) ; i--)\n#define all(a) a.begin(),a.end() \n \nusing namespace std ;\nconst int maxn = 5e5 + 10 , mod = 1e9 + 7;\nint a[maxn] , ri[maxn] , le[maxn] , bl[maxn] , br[maxn] , sl[maxn] , sr[maxn] ;\n \n \nsigned main(){\n    ios::sync_with_stdio(0) ; cin.tie(0);\n    \n    int T;\n    cin >> T;\n    \n    while(T--) {\n        int n; cin >> n; \n        \n        rep(i ,1, n) {\n            cin >> a[i];\n        }    \n        \n        vector <int> s , b; \n        \n        rep(i , 1 ,n){\n            while(sz(s) && a[s.back()] > a[i])s.pop_back() ;\n            while(sz(b) && a[b.back()] < a[i])b.pop_back() ;\n            \n            sl[i] = (sz(s) ? s.back() : 0);\n            bl[i] = (sz(b) ? b.back() : 0);    \n            s.pb(i); b.pb(i) ;\n        }\n        \n        s.clear();\n        b.clear(); \n        \n        per(i , n , 1){\n            while(sz(s) && a[s.back()] > a[i])s.pop_back() ;\n            while(sz(b) && a[b.back()] < a[i])b.pop_back() ;\n            sr[i] = (sz(s) ? s.back() : n+1);\n            br[i] = (sz(b) ? b.back() : n+1);    \n            s.pb(i); b.pb(i) ;    \n        }\n        \n        ri[n] = n;\n        per(i , n-1 ,1){\n            ri[i] = ri[i+1];        \n            if(a[i] > a[i+1] && a[br[i+1]] < a[i]){\n                ri[i] = min(ri[i] , br[i+1]-1);\n            }\n            \n            if(a[i] < a[i+1] && a[sr[i+1]] > a[i]){\n                ri[i] = min(ri[i] , sr[i+1]-1);\n            }\n        }\n        \n        \n        le[1] = 1 ;\n        rep(i , 2,n){\n            le[i] = le[i-1] ;\n            if(a[i] > a[i-1] && a[bl[i-1]] < a[i]){\n                le[i] = max(le[i] , bl[i-1]+1);\n            }\n            if(a[i] < a[i-1] && a[sl[i-1]] > a[i]){\n                le[i] = max(le[i] , sl[i-1]+1);\n            }\n        }\n        \n        int ans = ri[1] ;     \n        rep(i , 2 , n){\n            ans = (ans + (i-1 - le[i] + 1) * (ri[i] - ri[i-1]) + ri[i]-i+1) ;\n        }\n        cout << ans << \"\\n\" ; \n    }\n}",
    "tags": [
      "data structures",
      "implementation",
      "sortings",
      "two pointers"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2101",
    "index": "E",
    "title": "Kia Bakes a Cake",
    "statement": "You are given a binary string $s$ of length $n$ and a tree $T$ with $n$ vertices. Let $k$ be the number of 1s in $s$. We will construct a complete undirected weighted graph with $k$ vertices as follows:\n\n- For each $1\\le i\\le n$ with $s_i = \\mathtt{1}$, create a vertex labeled $i$.\n- For any two vertices labeled $u$ and $v$ that are created in the above step, define the edge weight between them $w(u, v)$ as the distance$^{\\text{∗}}$ between vertex $u$ and vertex $v$ in the tree $T$.\n\nA \\textbf{simple} path$^{\\text{†}}$ that visits vertices labeled $v_1, v_2, \\ldots, v_m$ in this order is nice if for all $1\\le i\\le m - 2$, the condition $2\\cdot w(v_i, v_{i + 1})\\le w(v_{i + 1}, v_{i + 2})$ holds. In other words, the weight of each edge in the path must be at least twice the weight of the previous edge. Note that $s_{v_i} = \\mathtt{1}$ has to be satisfied for all $1\\le i\\le m$, as otherwise, there would be no vertex with the corresponding label.\n\nFor each vertex labeled $i$ ($1\\le i\\le n$ and $s_i = \\mathtt{1}$) in the complete undirected weighted graph, determine the maximum number of vertices in any nice simple path starting from the vertex labeled $i$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The distance between two vertices $a$ and $b$ in a tree is equal to the number of edges on the unique simple path between vertex $a$ and vertex $b$.\n\n$^{\\text{†}}$A path is a sequence of vertices $v_1, v_2, \\ldots, v_m$ such that there is an edge between $v_i$ and $v_{i + 1}$ for all $1\\le i\\le m - 1$. A simple path is a path with no repeated vertices, i.e., $v_i\\neq v_j$ for all $1\\le i < j\\le m$.\n\\end{footnotesize}",
    "tutorial": "Can we see any node twice in our walk? What is the upper bound on the length of the path? How do we approach this using dynamic programming? How to optimize the DP? The length of each two nodes in a tree is always less than the number of nodes, and therefore the maximum weight that we can see in our constructed graph has an upper bound of $n-1$. Because the weight of any nice path is doubled every time, the maximum length of any nice path won't exceed $log_2(n)$. The next observation is that we cannot see any node twice in a nice path (in other words, there are no cycles). Proof: Let's assume that a cycle exists. We know that the weight of each edge is always greater than the sum of all previous edges, so even without any waste, $\\sum_{i=0}^{k} 2^i < 2^{k+1}$. This tells us no matter how far we get, because we're taking more steps in the last edge than the sum of all previous ones, we can never end up in the first node. Therefore, every nice path is a simple path, and no cycles can be made. Now, let's define $dp_{i, j}$ as the maximum weight of any edge to start a simple path from vertex $j$ and take $i$ steps, and $0$ if not possible. The idea here is to build the nicest path reversly, from the end to the beginning. We can update this $dp$ and build the paths backwards, and this will give us an $O(n^2\\cdot log(n))$ solution as $i\\le log_2(n)$. To optimize this, we use the suffix trick on centroid decomposition and keep the maximum two suffixes every time, to update $dp_{i, ?}$ in increasing order of $i$ accordingly. This would result in a $O(n\\cdot log(n)^3)$ implementation, which can be further optimized to $O(n\\cdot log(n)^2)$ using the fact that we can use counting sort for sorting as we have an upper bound of $n$. Both implementations are included below. We aimed to kill $log(n)^3$ implementations but then ended up making some correct $log(n)^2$ ones TLE, and gave up! What was your favorite part about this problem? Comment it below.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll  = long long;\nusing ld  = long double;\nusing pii = pair<int, int>;\nusing pll = pair<long long, long long>;\nusing ull = unsigned long long;\n\n#define X               first\n#define Y               second\n#define SZ(x)           int(x.size())\n#define all(x)          x.begin(), x.end()\n#define mins(a,b)       (a = min(a,b))\n#define maxs(a,b)       (a = max(a,b))\n#define pb              push_back\n#define Mp              make_pair\n#define lc              id<<1\n#define rc              lc|1\n#define mid             ((l+r)>>1)\nmt19937_64              rng(chrono::steady_clock::now().time_since_epoch().count());\n\nconst ll  INF = 1e9 + 23;\nconst ll  MOD = 1e9 + 7;\nconst int MXN = 7e4+2;\nconst int LOG = 18;\n\nint n;\nstring s;\nvector<int> g[MXN];\nint dp[LOG][MXN];\n\nbool dead[MXN];\nint sz[MXN];\nint get_sz(int v, int p=0) {\n    sz[v] = 1;\n    for(int u : g[v])\n        if(!dead[u] && u!=p)\n            sz[v] += get_sz(u, v);\n    return sz[v];\n}\nint centroid(int v, int N, int p=0) {\n    for(int u : g[v])\n        if(!dead[u] && u!=p && sz[u]+sz[u]>N)\n            return centroid(u, N, v);\n    return v;\n}\n\nvector<pair<int, int>> U;\nvector<pair<int, int>> G;\nint h[MXN], par[MXN];\n\nvoid dfs(int i, int v, int p=0) {\n    if(s[v-1]=='1') {\n        G.pb({h[v]<<1, v});\n        if(dp[i-1][v]>=2*h[v]) U.pb({dp[i-1][v]-2*h[v], v});\n    }\n    for(int u : g[v])\n        if(!dead[u] && u!=p)\n            par[u] = par[v],\n            h[u] = h[v]+1,\n            dfs(i, u, v);\n}\n\nvoid solve(int i, int v) {\n    dead[v=centroid(v,get_sz(v))] = 1;\n    U.clear();\n    G.clear();\n    h[v] = 0;\n    par[v] = v;\n    if(s[v-1]=='1') {\n        G.pb({h[v]<<1, v});\n        if(dp[i-1][v]>=2*h[v]) U.pb({dp[i-1][v]-2*h[v], v});\n    }\n    for(int u : g[v])\n        if(!dead[u]) {\n            par[u] = u;\n            h[u] = 1;\n            dfs(i, u);\n        }\n    sort(all(U), greater<>());\n    sort(all(G), greater<>());\n    int mx1=0, mx2=0, ptr=0;\n    for(auto [lim, u] : G) {\n        while(ptr<SZ(U) && U[ptr].X>=lim) {\n            if(mx1 && par[mx1]==par[U[ptr].Y]) {\n                if(h[U[ptr].Y]>h[mx1]) mx1 = U[ptr].Y;\n            }\n            else if(mx2 && par[mx2]==par[U[ptr].Y]) {\n                if(h[U[ptr].Y]>h[mx2]) mx2 = U[ptr].Y;\n                if(h[mx2]>h[mx1]) swap(mx1, mx2);\n            }\n            else {\n                if(!mx1 || h[U[ptr].Y]>h[mx1]) mx2=mx1, mx1=U[ptr].Y;\n                else if(!mx2 || h[U[ptr].Y]>h[mx2]) mx2=U[ptr].Y;\n            }\n            ptr++;\n        }\n        if(mx1) {\n            if(mx1 && par[mx1]!=par[u]) maxs(dp[i][u], h[mx1]+h[u]);\n            else if(mx2) maxs(dp[i][u], h[mx2]+h[u]);\n        }\n    }\n    for(int u : g[v])\n        if(!dead[u])\n            solve(i, u);\n}\n\nvoid Main() {\n    cin >> n >> s;\n    for(int i=1; i<=n; i++) g[i].clear();\n    for(int i=1,u,v; i<n; i++) {\n        cin >> u >> v;\n        g[u].pb(v);\n        g[v].pb(u);\n    }\n    for(int i=1; i<=n; i++)\n        if(s[i-1]=='1')\n            dp[0][i] = 2*n-2;\n        else\n            dp[0][i] = -1;\n    for(int i=1; i<LOG; i++) {\n        fill(dead+1, dead+n+1, 0);\n        fill(dp[i]+1, dp[i]+n+1, -1);\n        solve(i, 1);\n    }\n    for(int i=1; i<=n; i++)\n        if(s[i-1]=='1') {\n            for(int j=LOG-1; j>=0; j--)\n                if(dp[j][i]!=-1) {\n                    cout << j+1 << ' ';\n                    break;\n                }\n        }\n        else cout << \"-1 \";\n    cout << '\\n';\n}\n\nint32_t main() {\n    cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);\n    int T = 1;\n    cin >> T;\n    while(T--) Main();\n    return 0;\n}",
    "tags": [
      "data structures",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2101",
    "index": "F",
    "title": "Shoo Shatters the Sunshine",
    "statement": "You are given a tree with $n$ vertices, where each vertex can be colored red, blue, or white. The coolness of a coloring is defined as the maximum distance$^{\\text{∗}}$ between a red and a blue vertex.\n\nFormally, if we denote the color of the $i$-th vertex as $c_i$, the coolness of a coloring is $\\max d(u, v)$ over all pairs of vertices $1\\le u, v\\le n$ where $c_u$ is red and $c_v$ is blue. If there are no red or no blue vertices, the coolness is zero.\n\nYour task is to calculate the sum of coolness over all $3^n$ possible colorings of the tree, modulo $998\\,244\\,353$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The distance between two vertices $a$ and $b$ in a tree is equal to the number of edges on the unique simple path between vertex $a$ and vertex $b$.\n\\end{footnotesize}",
    "tutorial": "What are some properties of such colored trees? Is the farthest blue and red node unique? Should we look for an $O(n^2)$ solution or optimizes a slower one? Note: For the purpose of this editorial, the diameter of a colored tree is defined as a simple path with maximum coolness which has a blue and red node on each side. Let's say a node is special iff the distance of the farthest blue node from it plus the distance of the farthesrt red node is equal to the length of the diameter of the tree. We also define a special edge as an edge such that the distances of the farthes red nodes on both sides are equal, and the distances of the blue nodes on each side are also equal to each other. Something like this: We can see that the sum of distances of the farthest blue and green plus one is the length of the diameter. We claim that if there is no special node in a colored tree, then there must be a special edge. Proof: If there is no special node in a tree, then that means the farthest red and blue node for each vertex are on one side of it. We know that if there is at least one blue and one red colored node, then we have a valid diameter, so considering each node on that diameter, becuase it is not a special node the farthest blue and red of it must be on one side, and this leasds us towards a speical edge, the formal proof is described later when discussing $T'$. Let's make some more observations. It's easy to see that the diameter of a tree is not necessarily unique, but an interesting fact is that every two valid diameters must intersect with each other. Proof: if not, consider the tree is rooted from the blue/red node of one diameter, this would trivially show us a new blue and red node that has a distance longer than our current diameter and therefore a contradiction. This gives us the idea that the intersection of all valid diameters is a non-empty simple path on the tree. Proof: Consider two diameters and take their intersection, then add the rest one by one and take the intersection of the intersections. If there are any two pairs with intersections that do not intersect, this means there exists a pair of valid diameters which do not intersect with each other, and this is against our hypothesis. Before continuing, you must have an idea so far that we are aiming to count the trees with special node based on their node, and others based on their special edge, but there is still a lot to discuss. Going back to the special nodes, it's easy to see that they must must be on our diameter, and what makes this more interesting is that they must be on all diameters! So, taking the simple path that was the intersection of all valid diameters, we know that all of our special nodes lie on this path. Getting deeper on special nodes, we can see that for a non-special node such as $v$, the farthest blue and red are both on the same subtree if we root the tree from $v$. This makes the sum of distances to farthest red plus the farthest blue result in a number always bigger than the actual length of our diameter (as there is a shared part). Call the child in which both the farthest red and blue lie on a cool child. Let's create another graph based on our tree (call it $T'$) that has identical nodes to the tree, and directed edges. For each non-special node, give a directed edge from the identical vertex in $T'$ to its cool child. It's easy to see that special nodes would not have any incoming edges to them in this new graph, but every non-special node has at least one. We can use this graph to formally prove almost everything. Let's start with the fact that why any tree without a special node has a special edge? Proof: No special edge means that there are $n$ nodes in our tree that each have an outgoing edge, therefore $n$ directed edges as well. Our initial tree had only $n-1$ edge, so therefore based on the pigeonhole principle, there must be an edge in the initial tree, that two directed edges pass above it. It's trivial that those edges cannot have the same direction, and therefore this will lead us to a directed cycle of length two. Well, think about it, this is exactly what a special edge is! So if no special node is there, now we know that there is at least one special edge there somewhere. Well, it appears that we also cannot have more than one special edge in a colored tree. Proof: If so, we know that both of them must appear on the diameter, and considering their placement, this will contradict the fact that the distance of red and blue from both sides must be equal. Combining both above observations, now we know that if there is no special node in the colored tree, then there is exactly one special edge there somewhere. Now let's solve the first sub-problem, which is how to solve the problem if there is no special node. Define $f(v, a, b)$ for a node $v$ as the number of colourings which the farthest blue has a distance of $a$, and the farthest red has a distance of $b$. How to calculate $f$? Define $g(v, a, b)$ as the same thing, but this time for the distance of at most $a$ for blue and at most $b$ for red. It's easy to see that if we somehow calculate $g(v, a, b)$, then the following equation holds: $\\begin{equation} f(v, a, b) = g(v, a, b) - g(v, a-1, b) - g(v, a, b-1) + g(v, a-1, b-1) \\end{equation}$ $\\begin{equation} g(v, a, b) = 3^{p\\cdot q}\\cdot 1^r \\end{equation}$ $p = \\#\\{u \\mid d(u, v) \\le a \\}$ $q = \\#\\{ u \\mid a < d(u, v) \\le b \\}$ $r = \\#\\{ u \\mid b < d(u, v) \\}$ This will so far give us an $O(n^3)$ solution, dw we'll optimize it further later. Now we count the result for each edge of the tree, considering it will be a special edge in some colourings. Call both sides of the edge $u$ and $v$ just like the diagram shown above. Assuming we have $f$ calculated for all nodes, the answer is: $\\begin{equation} \\sum_{a=0}^{n} \\sum_{b=0}^{n} f(u, a, b) \\cdot f(v, a, b) \\cdot (a + b + 1) \\end{equation}$ Let's define a super-special node a node that is special, and not only does it have the farthest blue and red on different sides, but also either a blue node with distance one less than the farthest blue, or a red node with distance one less than the farthest red. Using the same observations that we made earlier and a deeper understanding of $T'$, you can prove that there is at least one super-special node, also at most one super-special node, and therefore always exactly one super-special node if there exists at least one special node. For such trees, we aim to calculate the answer for them based on their super-special node. Make the tree rooted from an arbitrary node. Define $dp_{v, i, a, b, j}$ as if you're in vertext $v$, you iterated $i$ children, so far the farthest blue node has a distance of $a$, the farthest red node has a distance of $b$, and $j=0$ if these two don't belong to one subtree (if possible, preferably $0$), and $1$ otherwise. Iterate over new subtrees and use the $f$ function defined before to end up with a computable $O(n^4)$ implementation! Now add another dimension $k$ to the above DP to keep track of if there is any blue node with distance one less than the farthest blue, or a red node with distance one less than the farthest red. Note that this really doesn't change anything. The above DP, though correct, won't give us a good solution and is only explained for gaining deeper insight. After truly understanding what is going on and what we are looking for, we can break down the same idea and calculate it manually, which will result in a $O(n^2)$ solution in the end. The primary fact to notice is that if the number of edges between two farthest red vertices is even, then it can be proven that the middle vertex of this path is a special node, and if odd, the middle edge is a special edge. As explaining everything in detail takes forever, try to prove the things we missed yourself and ask if you encountered any issues. The intended solution was the $O(n^3)$ discussed with some further optimizations, but then a new $O(n^2)$ solution showed up that changed everything! We thought of dividing the problem into two subtasks, but didn't do so, as the observation required for the $O(n^2)$ solution was quite beautiful. Also, we would like to thank Hamed_Ghaffari for his contributions to this problem.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nusing ll  = long long;\nusing ld  = long double;\nusing pii = pair<int, int>;\nusing pll = pair<long long, long long>;\nusing ull = unsigned long long;\n\n#define X               first\n#define Y               second\n#define SZ(x)           int(x.size())\n#define all(x)          x.begin(), x.end()\n#define mins(a,b)       (a = min(a,b))\n#define maxs(a,b)       (a = max(a,b))\n#define pb              push_back\n#define Mp              make_pair\n#define lc              id<<1\n#define rc              lc|1\n#define mid             ((l+r)>>1)\nmt19937_64              rng(chrono::steady_clock::now().time_since_epoch().count());\n\nconst ll  INF = 1e9 + 23;\nconst ll  MOD = 998244353;\nconst int MXN = 3006;\nconst int LOG = 23;\n\ntemplate<typename T>\ninline T md(T x) { return x &mdash; (x>=MOD ? MOD : 0); }\ntemplate<typename T>\ninline void fix(T &x) { x = md(x); }\n\nint n;\nvector<int> g[MXN];\nvector<int> H[MXN];\nint cnt[MXN], pscnt[MXN];\nll red[MXN], redb[MXN];\nll two[MXN], thr[MXN], itwo[MXN];\nll ans;\nll ps[MXN];\n\nvoid dfs(int v, int h=0, int p=-1) {\n    cnt[h]++;\n    H[h].back()++;\n    for(int u : g[v])\n        if(u!=p)\n            dfs(u, h+1, v);\n}\n\nvoid Main() {\n    cin >> n;\n    for(int i=1; i<=n; i++) g[i].clear();\n    ans = 0;\n    for(int i=0, u,v; i<n-1; i++) {\n        cin >> u >> v;\n        g[u].pb(v);\n        g[v].pb(u);\n    }\n    for(int v=1; v<=n; v++) {\n        for(int adj=-1; adj<SZ(g[v]); adj++) {\n            for(int i=0; i<n; i++) H[i].clear(), cnt[i]=0;\n            if(adj==-1) {\n                cnt[0]++;\n                for(int u : g[v]) {\n                    for(int i=0; i<n; i++) H[i].pb(0);\n                    dfs(u, 1, v);\n                }\n            }\n            else {\n                if(g[v][adj]<v) continue;\n                for(int i=0; i<n; i++) H[i].pb(0);\n                dfs(v, 0, g[v][adj]);\n                for(int i=0; i<n; i++) H[i].pb(0);\n                dfs(g[v][adj], 0, v);\n            }\n            pscnt[0] = cnt[0];\n            for(int i=1; i<n; i++) pscnt[i] = pscnt[i-1] + cnt[i];\n            red[0] = 1;\n            redb[0] = 1;\n            for(int i=1; i<n; i++) {\n                red[i] = two[cnt[i]]-1;\n                for(int a : H[i])\n                    fix(red[i] += MOD-(two[a]-1));\n                redb[i] = md(thr[cnt[i]]-two[cnt[i]]+MOD);\n                for(int a : H[i])\n                    fix(redb[i] += MOD-(thr[a]-two[a]+MOD)*two[cnt[i]-a]%MOD);\n            }\n            for(int i=0; i<n; i++) {\n                ps[i] = red[i]*two[i==0?0:pscnt[i-1]]%MOD*(i+(adj!=-1))%MOD;\n                if(i) fix(ps[i] += ps[i-1]);\n            }\n            for(int j=0; j<n; j++)\n                fix(ans += thr[j==0?0:pscnt[j-1]]\n                        *(thr[cnt[j]]-two[cnt[j]]+MOD)%MOD\n                        *itwo[pscnt[j]]%MOD\n                        *(ps[n-1]-ps[j]+MOD)%MOD);\n            for(int i=0; i<n; i++) {\n                ps[i] = red[i]*two[i==0?0:pscnt[i-1]]%MOD;\n                if(i) fix(ps[i] += ps[i-1]);\n            }\n            for(int j=0; j<n; j++)\n                fix(ans += thr[j==0?0:pscnt[j-1]]\n                        *(thr[cnt[j]]-two[cnt[j]]+MOD)%MOD\n                        *itwo[pscnt[j]]%MOD\n                        *j%MOD\n                        *(ps[n-1]-ps[j]+MOD)%MOD);\n            for(int i=0; i<n; i++) {\n                ps[i] = redb[i]\n                        *thr[i==0?0:pscnt[i-1]]%MOD\n                        *itwo[pscnt[i]]%MOD\n                        *(i+(adj!=-1))%MOD;\n                if(i) fix(ps[i] += ps[i-1]);\n            }\n            for(int j=1; j<n; j++)\n                fix(ans += two[pscnt[j-1]]%MOD\n                        *(two[cnt[j]]-1)%MOD\n                        *ps[j-1]%MOD);\n            for(int i=0; i<n; i++) {\n                ps[i] = redb[i]\n                        *thr[i==0?0:pscnt[i-1]]%MOD\n                        *itwo[pscnt[i]]%MOD;\n                if(i) fix(ps[i] += ps[i-1]);\n            }\n            for(int j=1; j<n; j++)\n                fix(ans += two[pscnt[j-1]]%MOD\n                        *(two[cnt[j]]-1)%MOD\n                        *j%MOD\n                        *ps[j-1]%MOD);\n            for(int i=0; i<n; i++) {\n                fix(ans += (redb[i]-red[i]+MOD)*thr[i==0?0:pscnt[i-1]]%MOD*(i+i+(adj!=-1))%MOD);\n            }\n        }\n    }\n    cout << ans << '\\n';\n}\n\nint32_t main() {\n    cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);\n    int T = 1;\n    cin >> T;\n    two[0] = 1;\n    for(int i=1; i<MXN; i++) two[i] = two[i-1]*2%MOD;\n    thr[0] = 1;\n    for(int i=1; i<MXN; i++) thr[i] = thr[i-1]*3%MOD;\n    itwo[0] = 1;\n    for(int i=1; i<MXN; i++) itwo[i] = itwo[i-1]*((MOD+1)/2)%MOD;\n    while(T--) Main();\n    return 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "trees"
    ],
    "rating": 3300
  },
  {
    "contest_id": "2102",
    "index": "A",
    "title": "Dinner Time",
    "statement": "Given four integers $n$, $m$, $p$, and $q$, determine whether there exists an integer array $a_1, a_2, \\ldots, a_n$ (elements may be negative) satisfying the following conditions:\n\n- The sum of all elements in the array is equal to $m$: $$a_1 + a_2 + \\ldots + a_n = m$$\n- The sum of every $p$ consecutive elements is equal to $q$: $$a_i + a_{i + 1} + \\ldots + a_{i + p - 1} = q,\\qquad\\text{ for all }1\\le i\\le n-p+1$$",
    "tutorial": "If you have the first $p$ elements, what happens to the rest? What happens if $n\\%p\\neq0$? How can the fact that we can also use negative numbers be useful? The first thing to realize is that if the first $p$ elements of the array are determined, the rest will be unique ($a_i = a_{i-p}$ to hold the sum). If $p$ divides $n$, there will be $\\frac{n}{p}$ blocks, each summing to $q$, so their total sum which is $q\\cdot \\frac{n}{p}$ should be equal to $m$. If not, the incomplete block that is created at the end can be used to cover any difference in sum, so it's always possible! This problem was supposed to be for cyclic arrays, and also required construction, but due to D2A difficulty it was adjusted! Do you have a solution for the cyclic array version? Comment it below",
    "code": "t = int(input())\n\nfor _ in range(t):\n    n, m, p, q = map(int, input().split())\n    \n    if n % p == 0 and (n // p) * q != m:\n        print(\"NO\")\n    else:\n        print(\"YES\")",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2102",
    "index": "B",
    "title": "The Picky Cat",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$. You are allowed to do the following operation any number of times (possibly zero):\n\n- Choose an index $i$ ($1\\le i\\le n$). Multiply $a_i$ by $-1$ (i.e., update $a_i := -a_i$).\n\nYour task is to determine whether it is possible to make the element at index $1$ become the median of the array after doing the above operation any number of times. Note that operations can be applied to index $1$ as well, meaning the median can be either the original value of $a_1$ or its negation.\n\nThe median of an array $b_1, b_2, \\ldots, b_m$ is defined as the $\\left\\lceil \\frac{m}{2} \\right\\rceil$-th$^{\\text{∗}}$ smallest element of array $b$. For example, the median of the array $[3, 1, 2]$ is $2$, while the median of the array $[10, 1, 8, 3]$ is $3$.\n\nIt is guaranteed that the absolute value of the elements of $a$ are distinct. Formally, there are no pairs of indices $1\\le i < j\\le n$ where $|a_i| = |a_j|$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\lceil x \\rceil$ is the ceiling function which returns the least integer greater than or equal to $x$.\n\\end{footnotesize}",
    "tutorial": "Does the initial sign and order of elements matter? If an element is before the median in the sorted array, can you shift it forward? What if it is initially after the median? Before starting, we take the absolute value of all elements since their signs do not matter. Then, if the first element of the array is equal to or smaller than the $\\left\\lfloor \\frac{n}{2}\\right\\rfloor + 1$ smallest element of the array, the answer is possible. Else, it is impossible. The proof is as follows: If the first element is equal to or smaller than the $\\left\\lceil\\frac{n}{2}\\right\\rceil$ smallest element of the array, we can negate the big values until the first element becomes the $\\left\\lceil\\frac{n}{2}\\right\\rceil$ smallest element of the array, hence becoming the median. If the first element is equal to or smaller than the $\\left\\lceil\\frac{n}{2}\\right\\rceil$ smallest element of the array, we can negate the big values until the first element becomes the $\\left\\lceil\\frac{n}{2}\\right\\rceil$ smallest element of the array, hence becoming the median. If the first element is equal to the $\\left\\lfloor \\frac{n}{2}\\right\\rfloor + 1$ smallest element of the array, we can negate the entire array, which results in the first element becoming the $\\left\\lceil\\frac{n}{2}\\right\\rceil$ smallest element of the array. If the first element is equal to the $\\left\\lfloor \\frac{n}{2}\\right\\rfloor + 1$ smallest element of the array, we can negate the entire array, which results in the first element becoming the $\\left\\lceil\\frac{n}{2}\\right\\rceil$ smallest element of the array. Otherwise, if the first element of the array is larger than the $\\left\\lfloor \\frac{n}{2}\\right\\rfloor + 1$ smallest element of the array, negating values smaller than it has no effect, while negating values larger than it just makes the first element further away from the median position. You can verify that negating the first element itself does not help either by using similar cases. Otherwise, if the first element of the array is larger than the $\\left\\lfloor \\frac{n}{2}\\right\\rfloor + 1$ smallest element of the array, negating values smaller than it has no effect, while negating values larger than it just makes the first element further away from the median position. You can verify that negating the first element itself does not help either by using similar cases. Would it be easier to calculate the answer for all indices and just output for the first index? What's up with the name of the problem?",
    "code": "t = int(input())\n\nfor _ in range(t):\n    n = int(input())\n    a = list(map(int, input().split()))\n    \n    pairs = [(abs(a[i]), i) for i in range(n)]\n    pairs.sort()\n    \n    ans = [0] * n\n    \n    for i in range(n // 2 + 1):\n        _, index = pairs[i]\n        ans[index] = 1\n    \n    if ans[0]:\n        print(\"YES\")\n    else:\n        print(\"NO\")",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 900
  },
  {
    "contest_id": "2103",
    "index": "A",
    "title": "Common Multiple",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$. An array $x_1, x_2, \\ldots, x_m$ is beautiful if there exists an array $y_1, y_2, \\ldots, y_m$ such that the elements of $y$ are distinct (in other words, $y_i\\neq y_j$ for all $1 \\le i < j \\le m$), and the product of $x_i$ and $y_i$ is the same for all $1 \\le i \\le m$ (in other words, $x_i\\cdot y_i = x_j\\cdot y_j$ for all $1 \\le i < j \\le m$).\n\nYour task is to determine the maximum size of a subsequence$^{\\text{∗}}$ of array $a$ that is beautiful.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A sequence $b$ is a subsequence of a sequence $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) element from arbitrary positions.\n\\end{footnotesize}",
    "tutorial": "We need to solve the same problem $t$ times. We will make use of loops to do so. From now we will focus on solving a problem for one test case, but remember that all of the following will be in a loop. So the array $x$ is beautiful if there exists an array of distinct elements $y$ such that $x_i \\cdot y_i$ is the same for all $1 \\le i \\le n$. We will try to make the condition into something more understandable. Suppose that the common product is some constant $C$. How can you express each $y_i$ in terms of $C$ and $x_i$? It can be expressed as $y_i = \\frac{C}{x_i}$. If all $y_i = \\frac{C}{x_i}$ must be all different, what does that force upon the array $x$ for it to be beautiful? Let $i$ and $j$ be indices of two arbitrary elements of $x$. Then for array $x$ to be beautiful the following needs to hold: $y_i \\neq y_j$ $\\frac{C}{x_i} \\neq \\frac{C}{x_j}$, divide both sides by $C$ $\\frac{1}{x_i} \\neq \\frac{1}{x_j}$, as neither $x_i$ nor $x_j$ are $0$, multiply by $x_i \\cdot x_j$ $x_j \\neq x_i$ Therefore, all values of $x_i$ must be distinct. But is it enough just that all values of $x$ are distinct? It is, and here is how to easily construct the integer array $y$ that satisfies the constraints. Let $P$ be the product of all elements of $x$. Then make $y_i = \\frac{P}{x_i}$ for all $1 \\le i \\le n$. As all values of $x$ are distinct and nonzero, it is guaranteed that all values of $y$ will also be distinct. The solution is the number of distinct values in $a$. How can we count that? We can only count the first appearance of each value. So the problem is now how to check if the appearance of value at some position $i$ is indeed the first appearance of $a_i$. Read the hints. The answer to the problem is the number of distinct elements in the array. There are many ways to find it; we will present one of the easiest. We will count only the first appearances of every value. That means that if array is for example [ $1$, $3$, $1$, $5$, $3$, $1$], we will only count $1$ at position $1$, $3$ at position $2$ and $5$ at position $4$. We will not count values $1$ at positions $3$ and $6$, nor the value $3$ at position $5$, as they are not the first appearance of those values. We will iterate through every element in $x$ and for an element $x_i$, check if there exists some $x_j$ $(j \\lt i)$ such that $x_i = x_j$. If we can't find such $j$, then that means it's the first appearance of $x_i$. We can do it by having one loop iterate over $i$, and it will have a variable that says whether it is the first appearance, originally set to true. Then we will iterate in another loop over all indices $1 \\le j < i$ and if at any point $a_i = a_j$, we will set the value of the variable to false. Then we increase the count of different values if the variable is still true. Memory complexity is $O(n)$. Time complexity is $O(n^2)$ per testcase giving us a total time complexity of $O(tn^2)$. Come up with more ways to count the number of different elements in the array.",
    "code": "t = int(input())\nfor i in range(t):\n    n = int(input())\n    a = input().split(\" \")\n    count = 0\n    for i in range(0, n):\n        add = 1\n        for j in range(0, i):\n            if a[i]==a[j]:\n                add = 0\n        count += add\n    print(count)\n",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2103",
    "index": "B",
    "title": "Binary Typewriter",
    "statement": "You are given a binary string $s$ of length $n$ and a typewriter with two buttons: 0 and 1. Initially, your finger is on the button 0. You can do the following two operations:\n\n- Press the button your finger is currently on. This will type out the character that is on the button.\n- Move your finger to the other button. If your finger is on button 0, move it to button 1, and vice versa.\n\nThe cost of a binary string is defined as the minimum number of operations needed to type the entire string.\n\nBefore typing, you may reverse at most one substring$^{\\text{∗}}$ of $s$. More formally, you can choose two indices $1\\le l\\le r\\le n$, and reverse the substring $s_{l\\ldots r}$, resulting in the new string $s_1s_2\\ldots s_{l-1}s_rs_{r-1}\\ldots s_ls_{r+1}\\ldots s_n$.\n\nYour task is to find the minimum possible cost among all strings obtainable by performing at most one substring reversal on $s$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\\end{footnotesize}",
    "tutorial": "Given the string $s$, how do we calculate the answer? We know that we need to type a character (apply operation $1$ exactly $n$ times). How many switches do we do? If the string $s$ starts with a 1, we need to do a switch immediately. From that point on, we only switch if the current number in the string changes. We can assume that we start with a 0, as the other case can be handled by appending 0 to the start and subtracting $1$ from the final answer. We will assume that we only want to make the answer smaller, as for keeping the answer, we can pick any interval of size $1$. How does reversing some interval [ $l$, $r$ ] change the answer? Notice that all switches before $l-1$, after $r+1$ and inbetween $l$ and $r$ will stay. So we only care about the values of $s_{l-1}$, $s_l$, $s_r$ and $s_{r+1}$. Notice that if $s_l = s_r$, then the swap does not change the number of changes. So we can assume that $s_l \\neq s_r$ in the optimal swap. Now, to evaluate how good the swap is, we can observe the following: if $s_{l-1} = s_l$, the number of changes increases by $1$, otherwise it decreases by $1$. if $s_{r} = s_{r+1}$, the number of changes increases by $1$, otherwise it decreases by $1$. Those 2 changes stack. From the previous hint, we can conclude that we can decrease the number of changes by at most $2$. For us to be able to decrease the number of changes by $2$, it shall hold that $s_{l-1} \\neq s_l$ and $s_r \\neq s_{r+1}$. If we want to decrease the number of changes by $1$, it is enough to make $s_{l-1} \\neq s_l$ and to make $r=n$. If we cannot do either of the previous two, the number of changes cannot be decreased. Read the hints. As said in the hints, we will assume that string $s$ starts with a 0. Now we need to check if it is possible to pick indices $l$ and $r$ such that the number of changes after the swap decreases by $2$. With some casework, we can see that it is always possible if the original number of changes is at least $3$. If the original number of changes is $2$, we cannot decrease it by $2$, but we can decrease it by $1$. If the original number of changes is $0$ or $1$, we cannot decrease it. Counting the number of changes can be done in a single pass of a loop. The time and memory complexities are $O(n)$ per testcase. Solve the problem if you were given $n$ strings. You will swap their order however you want and then concatenate them all into one string $s$. What is the minimal number of operations needed to write $s$ obtained in that way?",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = input().strip()\n    cnt = 0\n    for i in range(n-1):\n        if a[i] != a[i+1]: cnt += 1\n    if cnt == 0:\n        print(n + int(a[0] == \"1\"))\n    elif cnt == 1:\n        print(n + 1)\n    else:\n        print(n+cnt-1 - int(a[0] == \"0\" and cnt > 2))",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2103",
    "index": "C",
    "title": "Median Splits",
    "statement": "The median of an array $b_1, b_2, \\ldots b_m$, written as $\\operatorname{med}(b_1, b_2, \\ldots, b_m)$, is the $\\left\\lceil \\frac{m}{2} \\right\\rceil$-th$^{\\text{∗}}$ smallest element of array $b$.\n\nYou are given an array of integers $a_1, a_2, \\ldots, a_n$ and an integer $k$. You need to determine whether there exists a pair of indices $1 \\le l < r < n$ such that:\n\n$$\\operatorname{med}(\\operatorname{med}(a_1, a_2, \\ldots, a_l), \\operatorname{med}(a_{l+1}, a_{l+2}, \\ldots, a_r), \\operatorname{med}(a_{r+1}, a_{r+2}, \\ldots, a_n)) \\le k.$$\n\nIn other words, determine whether it is possible to split the array into three contiguous subarrays$^{\\text{†}}$ such that the median of the three subarray medians is less than or equal to $k$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\lceil x \\rceil$ is the ceiling function which returns the least integer greater than or equal to $x$.\n\n$^{\\text{†}}$An array $x$ is a subarray of an array $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "We split our array into $3$ subarrays, take their medians, and the final median needs to be $\\le k$. That means that the median of at least $2$ of those subarrays needs to be $\\le k$. For a given array $x$ of length $m$, what is the condition that $\\operatorname{med}(x_1, x_2, \\ldots, x_m) \\le k$? There need to be at least as many elements in $x$ that are $\\le k$ as those that are $>k$. How can we simplify this? We can replace all elements that are $\\le k$ with $1$ and all elementsthat are $> k$ with $-1$. Now the median of $x$ is $\\le k$ if and only if the sum of elements in $x$ is non-negative. Now that we replaced the elements of $a$, the question is if it is possible to split it into $3$ subarrays, of which at least $2$ have a non-negative sum. There are $3$ cases: The first and second subarrays have non-negative sums. The second and third subarrays have non-negative sums. The first and third subarrays have non-negative sums. Use prefix/suffix sums and maximums/ minimums to help you compute the answer in linear time. Read the hints. Cases $1$ and $2$ from hint 5 are symmetric, so we will only explain how to do case $1$. Compute the prefix sum of the array, let it be array $p$. The subarray [$l$, $r$] has non-negative sum if $p_{l-1} \\le p_{r}$. For each index $2 \\le i < n$ compute value $msp$ (max suffix prefix), such that $msp_i = max(p_i, p_{i+1},\\ldots, p_{n-1})$. Then iterate over index $1 \\le i \\le n-2$ that will be the end of the first subarray. If $p_i \\ge 0$ and $msp_{i+1} \\ge p_i$, then it will be possible to split the array such that the medians of the first and second subarrays are $\\le k$. Case $3$ is even easier. Find positions $x$ and $y$ such that [ $1$ , $x$ ] is the shortest prefix with median $\\le k$ and [ $y$, $n$ ] is the shortest suffix with median $\\le k$. Then the split into three subarrays such that the first and third have median $\\le k$ is possible if and only if [ $x+1$ , $y-1$ ] is a valid subarray, in other words, if $x + 2 \\le y$. As both cases can be checked with a few array passes, the time and memory complexities are $O(n)$ per testcase. Solve the problem if you need to find the smallest $k$ for which the answer is YES.",
    "code": "def check_prefix_and_middle(n, arr):\n    suf = [0] * (n + 1)\n    minsuf = [0] * (n + 1)\n    suf[n] = minsuf[n] = arr[n - 1]\n\n    for i in range(n - 2, -1, -1):\n        suf[i + 1] = suf[i + 2] + arr[i]\n        minsuf[i + 1] = min(minsuf[i + 2], suf[i + 1])\n\n    s = 0\n    for i in range(n - 2):\n        s += arr[i]\n        if s < 0:\n            continue\n        if suf[i + 2] >= minsuf[i + 3]:\n            return True\n\n    return False\n\ndef solve():\n    n, k = map(int, input().split())\n    arr = list(map(int, input().split()))\n\n    # Transform the array based on the value of k\n    for i in range(n):\n        arr[i] = 1 if arr[i] <= k else -1\n\n    a, b = n + 1, -1\n    s = 0\n\n    for i in range(n):\n        s += arr[i]\n        if s >= 0:\n            a = i + 1\n            break\n\n    s = 0\n    for i in range(n - 1, -1, -1):\n        s += arr[i]\n        if s >= 0:\n            b = i + 1\n            break\n\n    if a + 1 < b:\n        print(\"YES\")\n        return\n\n    if check_prefix_and_middle(n, arr):\n        print(\"YES\")\n        return\n\n    arr.reverse()\n\n    if check_prefix_and_middle(n, arr):\n        print(\"YES\")\n        return\n\n    print(\"NO\")\n\nt = int(input())\nfor _ in range(t):\n    solve()",
    "tags": [
      "binary search",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2103",
    "index": "D",
    "title": "Local Construction",
    "statement": "An element $b_i$ ($1\\le i\\le m$) in an array $b_1, b_2, \\ldots, b_m$ is a local minimum if at least one of the following holds:\n\n- $2\\le i\\le m - 1$ and $b_i < b_{i - 1}$ and $b_i < b_{i + 1}$, or\n- $i = 1$ and $b_1 < b_2$, or\n- $i = m$ and $b_m < b_{m - 1}$.\n\nSimilarly, an element $b_i$ ($1\\le i\\le m$) in an array $b_1, b_2, \\ldots, b_m$ is a local maximum if at least one of the following holds:\n\n- $2\\le i\\le m - 1$ and $b_i > b_{i - 1}$ and $b_i > b_{i + 1}$, or\n- $i = 1$ and $b_1 > b_2$, or\n- $i = m$ and $b_m > b_{m - 1}$.\n\nNote that local minima and maxima are not defined for arrays with only one element.\n\nThere is a hidden permutation$^{\\text{∗}}$ $p$ of length $n$. The following two operations are applied to permutation $p$ alternately, starting from operation 1, until there is only one element left in $p$:\n\n- \\textbf{Operation 1} — remove all elements of $p$ which are \\textbf{not} local minima.\n- \\textbf{Operation 2} — remove all elements of $p$ which are \\textbf{not} local maxima.\n\nMore specifically, operation 1 is applied during every odd iteration, and operation 2 is applied during every even iteration, until there is only one element left in $p$.\n\nFor each index $i$ ($1\\le i\\le n$), let $a_i$ be the iteration number that element $p_i$ is removed, or $-1$ if it was never removed.\n\nIt can be proven that there will be only one element left in $p$ after at most $\\lceil \\log_2 n\\rceil$ iterations (in other words, $a_i \\le \\lceil \\log_2 n\\rceil$).\n\nYou are given the array $a_1, a_2, \\ldots, a_n$. Your task is to construct any permutation $p$ of $n$ elements that satisfies array $a$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "Try to prove the claim that $a_i \\le \\lceil \\log_2 n\\rceil$. It also shall help you understand when the construction is possible, which is often a good way to think about constructive problems. We can notice that among any two consecutive elements $p_i$ and $p_{i+1}$, one of them has to be deleted. That means that after each operation, around half of the elements are deleted, therefore giving us the bound $a_i \\le \\lceil \\log_2 n\\rceil$. It also means that for array $a$ to describe a possible permutation, it must not contain two consecutive elements on any layer that do not get deleted in next iteration. The whole function on going to next layer is defined in recursive way. Also, WLOG we can assume that local maximums stay, as it is symmetrical for local minimums. It makes sense to think about how to arrange elements on current layer and select those that do and those that do not get deleted. Then we will apply recursive step on next layer to arrange those that do not get deleted. But how can we guarantee elements at some position will not get deleted? If there are $k$ positions at which elements that should not be deleted go, then we can just select the $k$ biggest elements to go there and the rest of the array we fill in with smaller ones. But how do we guarantee that one of the smaller ones does not become a local maximum? We can sort the smaller elements in increasing/ decreasing order, so none of them will be local maximum. However, there is an edge case of the smallest elements that form a prefix/ suffix. The part of smallest elements that form a prefix must be sorted in increasing order and the part of smallest elements that form a suffix must be sorted in decreasing order. Otherwise we might get that elements at first or last positions are local maximum when we do not want them to be. Read the hints. We process each layer separately and WLOG assume that we delete those that are not local maximums. We will have some elements that go onto next layer, and we will get their order when we process the next layer, for now we just know their positions. Say exactly $k$ elements are going to next layer, then we can select them to be the largest $k$ elements, which guarantees they will be local maximums. Now the question is how to place smaller elements. We can imagine that bigger elements divide the layer into subarrays of indices that will be deleted. It does not matter how we fill in those subarrays with smaller elements, as long as they are in sorted order. If the subarray is the prefix of a layer, it must be sorted increasingly, and if it is the suffix of the layer, it must be sorted decreasingly. Depending on implementation time complexity is either $O(n)$ or $O(n log n)$, both of which are fast enough to pass. Memory complexity is $O(n)$.",
    "code": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <deque>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <string>\n#include <vector>\ntypedef long long ll;\ntypedef long double ld;\nusing namespace std;\n \nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--)\n    {\n        int n;\n        cin >> n;\n        vector<int> a(n), p(n);\n        for (int i = 0; i < n; i++) cin >> a[i];\n        int mx = max(0, *max_element(a.begin(), a.end())) + 1;\n        for (int i = 0; i < n; i++) if (a[i] == -1) a[i] = mx;\n \n        int l = 1, r = n;\n        for (int k = 1; k <= mx; k++)\n        {\n            int mr = n - 1;\n            while (mr >= 0 && a[mr] <= k) mr--;\n            for (int i = 0; i < mr; i++)\n            {\n                if (a[i] == k)\n                {\n                    p[i] = ((k & 1) ? r-- : l++);\n                }\n            }\n            for (int i = n - 1; i > mr; i--)\n            {\n                if (a[i] == k)\n                {\n                    p[i] = ((k & 1) ? r-- : l++);\n                }\n            }\n        }\n        for (int i = 0; i < n; i++) cout << p[i] << \" \\n\"[i == n - 1];\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "implementation",
      "two pointers"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2103",
    "index": "E",
    "title": "Keep the Sum",
    "statement": "You are given an integer $k$ and an array $a$ of length $n$, where each element satisfies $0 \\le a_i \\le k$ for all $1 \\le i \\le n$. You can perform the following operation on the array:\n\n- Choose two distinct indices $i$ and $j$ ($1 \\le i,j \\le n$ and $i \\neq j$) such that $a_i + a_j = k$.\n- Select an integer $x$ satisfying $-a_j \\le x \\le a_i$.\n- Decrease $a_i$ by $x$ and increase $a_j$ by $x$. In other words, update $a_i := a_i - x$ and $a_j := a_j + x$.\n\nNote that the constraints on $x$ ensure that all elements of array $a$ remain between $0$ and $k$ throughout the operations.\n\nYour task is to determine whether it is possible to make the array $a$ non-decreasing$^{\\text{∗}}$ using the above operation. If it is possible, find a sequence of at most $3n$ operations that transforms the array into a non-decreasing one.\n\nIt can be proven that if it is possible to make the array non-decreasing using the above operation, there exists a solution that uses at most $3n$ operations.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ An array $a_1, a_2, \\ldots, a_n$ is said to be non-decreasing if for all $1 \\le i \\le n - 1$, it holds that $a_i \\le a_{i+1}$.\n\\end{footnotesize}",
    "tutorial": "When is the solution trivially -1? When it is impossible to do any operation and array is not sorted in the beginning. Is that enough though? It is enough. If we have even a single pair of values that sums up to $k$, we can make the array non-decreasing. From now assume there is only one such pair as we can ignore other pairs. The constraint of $3n$ hints that a solution is linear. Maybe we are actually supposed to sort the array? Let's assume indices of values that sum up to $k$ are $a$ and $b$. How do we swap values at some other two indices $c$ and $d$. We can do the following sequence of operations. It could change values of elements at positions $a$ and $b$, but their sum will remain $k$ and values at indices $c$ and $d$ will be swapped. We do operation on indices $a$ and $b$ and we make it so that $value[a] := k - value[c]$ and $value[b] := value[c]$. We do operation on indices $a$ and $c$ and we make it so that $value[a] := k - value[d]$ and $value[c] := value[d]$. We do operation on indices $a$ and $d$ and we make it so that $value[a] := k - value[b]$ and $value[d] := value[b]$. Notice that after this sequence of operations we swapped values at positions $c$ and $d$ and $value[a] + value[b]$ is still $k$. We can now sort the rest of the array (without $a$ and $b$) and then adjust values of $a$ and $b$ at the end. However, there is still a problem. It might be impossible to adjust values of $a$ and $b$. Take $k=5$ and array [$1$, $3$, $2$, $3$, $5$] for example, with $a = 3$ and $b = 4$. How do we avoid such problems? If $a = 1$ and $b = n$ we can just make $value[a]=0$ and $value[b] = k$ and as all other elements are between $0$ and $k$, it is guaranteed that array is sorted. How do we do it? We will assume that both $a$ and $b$ are neither $1$ nor $n$. If they are, then we will skip some steps. The following sequence of operations makes $a=1$ and $b=n$ a valid choice. Note that $a$ and $b$ are referring to their original indices. We do operation on indices $a$ and $b$ and we make it so that $value[a] := k - value[1]$ and $value[b] := value[1]$. We do operation on indices $1$ and $a$ and we make it so that $value[1] := k - value[n]$ and $value[a] := value[n]$. After those two operations we can just sort the rest of the array with sequence of $3$ operations previously described. Then at the end, we do operation to make $value[1] = 0$ and $value[n] = k$. Due to $n>4$ in total we use a bit less than $3n$ operations in the worst case. Solve the problem in $\\lceil \\frac{3n}{2} \\rceil$ queries.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nusing namespace std;\nconst int maxn=2e5+5;\nint n,k,arr[maxn],A,B,p[maxn];\nmap<int,int> pos;\nvector<tuple<int,int,int>> V; /// All operations\nvoid dooperation(int a,int b,int x){\n   arr[a]-=x;\n   arr[b]+=x;\n   V.push_back(make_tuple(a,b,x));\n}\nvoid setvalue(int pos,int b,int target){ /// Does operation on (pos, b) such that value of pos becomes target\n   if(arr[pos]==target)\n      return;\n   int dif=target-arr[pos];\n   dooperation(b,pos,dif);\n}\nvoid performswap(int x,int y){\n   int vx=arr[x],vy=arr[y];\n   setvalue(A,B,k-vx);\n   setvalue(x,A,vy);\n   setvalue(y,A,vx);\n}\nbool cmp(int a,int b){\n   return arr[a]<arr[b];\n}\nvoid solve(){\n   pos.clear();\n   V.clear();\n   A=B=-1;\n   cin>>n>>k;\n   for(int i=1;i<=n;i++)\n      cin>>arr[i];\n   bool issorted=true;\n   for(int i=2;i<=n;i++)\n      if(arr[i]<arr[i-1])\n         issorted=false;\n   if(issorted){\n      cout<<\"0\\n\";\n      return;\n   }\n   for(int i=1;i<=n;i++){\n      if(pos.find(k-arr[i])!=pos.end()){\n         B=i;\n         A=pos[k-arr[i]];\n         break;\n      }\n      pos[arr[i]]=i;\n   }\n   if(A==-1){\n      cout<<\"-1\\n\";\n      return;\n   }\n   if(A!=1){\n      setvalue(A,B,k-arr[1]);\n      setvalue(1,A,k-arr[B]);\n      A=1;\n   }\n   if(B!=n){\n      setvalue(B,A,k-arr[n]);\n      setvalue(n,B,k-arr[A]);\n      B=n;\n   }\n   vector<int> invp;\n   for(int i=2;i<n;i++)\n      invp.push_back(i);\n   sort(invp.begin(),invp.end(),cmp);\n   for(int i=0;i<invp.size();i++)\n      p[invp[i]]=i+2;\n   for(int i=2;i<n;i++){\n      if(p[i]==i)\n         continue;\n      performswap(p[i],i);\n      swap(p[p[i]],p[i]);\n      i--;\n   }\n   setvalue(B,A,k);\n   cout<<V.size()<<\"\\n\";\n   for(auto x:V)\n      cout<<(get<0>(x))<<\" \"<<(get<1>(x))<<\" \"<<(get<2>(x))<<\"\\n\";\n   return;\n}\nint main(){\n   int T;\n   cin>>T;\n   while(T--)\n      solve();\n   return 0;\n}",
    "tags": [
      "constructive algorithms",
      "implementation",
      "two pointers"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2103",
    "index": "F",
    "title": "Maximize Nor",
    "statement": "The bitwise nor$^{\\text{∗}}$ of an array of $k$-bit integers $b_1, b_2, \\ldots, b_m$ can be computed by calculating the bitwise nor cumulatively from left to right. More formally, $\\operatorname{nor}(b_1, b_2, \\ldots, b_m) = \\operatorname{nor}(\\operatorname{nor}(b_1, b_2, \\ldots, b_{m - 1}), b_m)$ for $m\\ge 2$, and $\\operatorname{nor}(b_1) = b_1$.\n\nYou are given an array of $k$-bit integers $a_1, a_2, \\ldots, a_n$. For each index $i$ ($1\\le i\\le n$), find the maximum bitwise nor among all subarrays$^{\\text{†}}$ of $a$ containing index $i$. In other words, for each index $i$, find the maximum value of $\\operatorname{nor}(a_l, a_{l+1}, \\ldots, a_r)$ among all $1 \\le l \\le i \\le r \\le n$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$ The logical nor of two boolean values is $1$ if both values are $0$, and $0$ otherwise. The bitwise nor of two $k$-bit integers is calculated by performing the logical nor operation on each pair of the corresponding bits.\n\nFor example, let us compute $\\operatorname{nor}(2, 6)$ when they are represented as $4$-bit numbers. In binary, $2$=$0010_2$ and $6=0110_2$. Therefore, $\\operatorname{nor}(2,6) = 1001_2 = 9$ as by performing the logical nor operations from left to right, we have:\n\n- $\\operatorname{nor}(0,0) = 1$\n- $\\operatorname{nor}(0,1) = 0$\n- $\\operatorname{nor}(1,0) = 0$\n- $\\operatorname{nor}(1,1) = 0$\n\nNote that if $2$ and $6$ were represented as $3$-bit integers instead, then $\\operatorname{nor}(2,6) = 1$.\n\n$^{\\text{†}}$An array $x$ is a subarray of an array $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "If problem had queries of form \"What is nor of some interval [$l$, $r$]\", how would you answer them? You can look at all the bits separately and answer for each. For each bit, we only care about the position of the last $1$ on it before $r$. Let that position be $x$. If $x>l$, then if $x$ and $r$ are of the same parity, the bit will be $0$; otherwise, it will be $1$. If $x=l$, the bit will be $1$ if $l$ and $r$ are the same parity and otherwise $0$. If $x<l$, the bit will be $1$ if $l$ and $r$ are different parity and otherwise $0$. From the previous hint we conclude that for a fixed $r$, the values of interval [$l$, $r$] repeat when you increase $l$ by $2$, except at positions near where last $1$ is for some bit. That means there will be only $O(k)$ different values of nor of an interval ending at some $r$. Read the hints. We can go from beginning to the end of the array and keep all the possible nor values of intervals ending at $r$ in some vector. For each value we will also remember the highest position $l$ for which we can obtain such value. When we find all those intervals for some $r$, we use segment tree to set answer to all positions in this interval to max of current answer and nor of our interval. Time complexity is $O(nk^2 + nk log n)$ and memory complexity is $O(n)$. Nor and Nand are well known for being able to mimic any bitwise operation if applied enough times. Make a circuit to add three $1$-bit numbers (those are zero and one) using $9$ NAND gates.",
    "code": "#include<bits/stdc++.h>\n#define ll long long\nusing namespace std;\nconst int maxn=2e5+5;\nint N,M,arr[maxn],pref[maxn][25],logg,st[4*maxn],stk;\nint nor(int a,int b){\n   return M^(a|b);\n}\nint getlog(int x){\n   int ans=-1;\n   while(x){\n      ans+=1;\n      x/=2;\n   }\n   return ans;\n}\nint internor(int l,int r){\n   if(l<=0 or l>r)\n      return 0;\n   if(l==r)\n      return arr[r];\n   int ans=0;\n   for(int j=0;j<=logg;j++){\n      int bit=(1<<j);\n      if(pref[r][j]<l)\n         if((r-l+1)%2==1)\n            bit=0;\n      if(pref[r][j]==l)\n         if((r-l+1)%2==0)\n            bit=0;\n      if(pref[r][j]>l)\n         if((r-pref[r][j]+1)%2==1)\n            bit=0;\n      ans+=bit;\n   }\n   return ans;\n}\nvoid update(int lb,int rb,int x,int pos=1,int l=1,int r=stk){\n   lb=max(1,lb);\n   rb=min(N,rb);\n   if(rb<lb)\n      return;\n   if(l==lb and r==rb){\n      st[pos]=max(st[pos],x);\n      return;\n   }\n   int mid=(l+r)/2;\n   if(rb<=mid)\n      return update(lb,rb,x,pos*2,l,mid);\n   if(lb>mid)\n      return update(lb,rb,x,pos*2+1,mid+1,r);\n   update(lb,mid,x,pos*2,l,mid);\n   update(mid+1,rb,x,pos*2+1,mid+1,r);\n   return;\n}\nint get(int pos){\n   pos+=stk-1;\n   int v=0;\n   while(pos){\n      v=max(v,st[pos]);\n      pos/=2;\n   }\n   return v;\n}\nvoid solve(){\n   int K;\n   cin>>N>>K;\n   stk=1;\n   while(stk<N)\n      stk<<=1;\n   M=(1<<K)-1;\n   for(int i=1;i<=N;i++)\n      cin>>arr[i];\n\n   logg=getlog(M+1)-1;\n   for(int i=1;i<=N;i++){\n      for(int j=0;j<=logg;j++)\n         if(arr[i]&(1<<j))\n            pref[i][j]=i;\n         else\n            pref[i][j]=pref[i-1][j];\n   }\n   for(int i=1;i<=N;i++){\n      for(int j=0;j<=logg;j++){\n         int p=pref[i][j];\n         for(int add=-2;add<=2;add++)\n            update(p+add,i,internor(p+add,i));\n      }\n      update(1,i,internor(1,i));\n   }\n   for(int i=1;i<=N;i++)\n      cout<<get(i)<<\" \\n\"[i==N];\n}\nvoid reset(){\n   for(int i=0;i<=N+2;i++){\n      arr[i]=0;\n      for(int j=0;j<=logg+2;j++)\n         pref[i][j]=0;\n   }\n   logg=0;\n   for(int i=0;i<=stk+stk;i++)\n      st[i]=0;\n}\nint main(){\n   int T=1;\n   cin>>T;\n   while(T--){\n      solve();\n      reset();\n   }\n   return 0;\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "dp",
      "implementation",
      "sortings"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2104",
    "index": "A",
    "title": "Three Decks",
    "statement": "Monocarp placed three decks of cards in a row on the table. The first deck consists of $a$ cards, the second deck consists of $b$ cards, and the third deck consists of $c$ cards, with the condition $a < b < c$.\n\nMonocarp wants to take some number of cards (at least one, but no more than $c$) from the \\textbf{third} deck and distribute them between the first two decks so that each of the taken cards ends up in either the first or the second deck. It is possible that all the cards taken from the third deck will go into the same deck.\n\nYour task is to determine whether Monocarp can make the number of cards in all three decks equal using the described operation.",
    "tutorial": "Let us assume that we have managed to make the number of cards equal. Then each deck contains $x$ cards. Since the total number of cards from the hasn't changed, there were $3x$ cards in total. This means that if $a + b + c$ is not divisible by $3$, the answer is definitely \"NO\". Otherwise, we know that $3x = a + b + c$, which means $x = \\frac{a + b + c}{3}$. If the first or the second deck already has more cards than $x$, the answer is also \"NO\". Otherwise, we can move $x - a$ cards to the first deck and $x - b$ cards to the second deck. Since $b > a$, it's enough to check if $b \\le x$. Overall complexity: $O(1)$ per test case.",
    "code": "for _ in range(int(input())):\n    a, b, c = map(int, input().split())\n    if (a + b + c) % 3 != 0:\n        print(\"NO\")\n        continue\n    x = (a + b + c) // 3\n    print(\"YES\" if b <= x else \"NO\")",
    "tags": [
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2104",
    "index": "B",
    "title": "Move to the End",
    "statement": "You are given an array $a$ consisting of $n$ integers.\n\nFor every integer $k$ from $1$ to $n$, you have to do the following:\n\n- choose an arbitrary element of $a$ and move it to the right end of the array (you can choose the last element, then the array won't change);\n- print the sum of $k$ last elements of $a$;\n- move the element you've chosen on the first step to its original position (restore the original array $a$).\n\nFor every $k$, you choose the element which you move so that the value you print is \\textbf{the maximum possible}.\n\nCalculate the value you print for every $k$.",
    "tutorial": "If we move an element to the end of the array, then each element (except the one we selected) will either remain in its place or move $1$ position to the left. This means that if we are interested in the sum of the last $k$ elements after we have shifted some element to the end, it will necessarily include the last $(k-1)$ elements of the original array (each of them will move at most $1$ position to the left, so they will still be included in the last $k$ elements). Thus, the answer for each $k$ is the sum of the last $(k-1)$ elements, plus some additional element. Can we use any element? It turns out, yes; if we want to use the element at index $i$, which is not among the last $(k-1)$, we just need to move it to the end. Obviously, among all these elements, we need to take the maximum. Therefore, the answer for each value of $k$ is $\\max \\limits_{i=1}^{n-k+1} a_i + \\sum\\limits_{i=n-k+2}^n a_i$. Calculating these values naively is too slow, but we can speed it up as follows: we will build two arrays $psum_i$ and $pmax_i$, where $psum_i$ is the sum of the first $i$ elements of the array, and $pmax_i$ is the maximum of them. Then the answer for $k$ is simply $pmax_{n-k+1} + psum_n - psum_{n-k+1}$. To quickly construct these two arrays, we can use the fact that $psum_i=pmax_i=0$, $psum_{i+1} = psum_i + a_{i+1}$, and $pmax_{i+1} = \\max(pmax_i, a_{i+1})$. This way, we will obtain a solution in $O(n)$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nint main()\n{\n    int t;\n    cin >> t;\n    for(int i = 0; i < t; i++)\n    {\n        int n;\n        cin >> n;\n        vector<int> a(n);\n        for(int j = 0; j < n; j++) cin >> a[j];\n        vector<int> pmax(n + 1);\n        vector<long long> psum(n + 1);\n        for(int j = 0; j < n; j++)\n        {\n            pmax[j + 1] = max(pmax[j], a[j]);\n            psum[j + 1] = psum[j] + a[j];\n        }\n        for(int k = 1; k <= n; k++)\n            cout << pmax[n - k + 1] + psum[n] - psum[n - k + 1] << \" \";\n        cout << endl;\n    }\n}",
    "tags": [
      "brute force",
      "data structures",
      "dp",
      "greedy",
      "implementation"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2104",
    "index": "C",
    "title": "Card Game",
    "statement": "Alice and Bob are playing a game. They have $n$ cards numbered from $1$ to $n$. At the beginning of the game, some of these cards are given to Alice, and the rest are given to Bob.\n\nCard with number $i$ beats card with number $j$ if and only if $i > j$, \\textbf{with one exception}: card $1$ beats card $n$.\n\nThe game continues as long as each player has at least one card. During each turn, the following occurs:\n\n- Alice chooses one of her cards and places it face up on the table;\n- Bob, seeing Alice's card, chooses one of his cards and places it face up on the table;\n- if Alice's card beats Bob's card, both cards are taken by Alice. Otherwise, both cards are taken by Bob.\n\nA player can use a card that they have taken during one of the previous turns.\n\nThe player who has no cards at the beginning of a turn loses. Determine who will win if both players play optimally.",
    "tutorial": "There are many ways to solve this problem. I will describe one of the ways that doesn't use too much casework. The key observation we need is that, if a player has a strategy that allows him/her to take the cards on turn $i$, then he/she has a strategy to take the cards on turn $i+1$. There are two ways to prove it, choose any of them: the first way is to consider the options each player has. When a player loses a card, they lose one of their options; when a player gains a card, they gain a new option for a turn. So, if a player can't take cards on some turn, then on the next turn, their options will be even more limited, and the opponent will still be able to use all the cards they were able to use on the previous turn; the second way is to consider it for Alice and Bob separately. If Alice can take cards on turn $i$ no matter what Bob does, then she has a card which beats every card Bob has (and she will still have this card on the next turn). Otherwise, if Bob can take cards on turn $i$ no matter what Alice does, then for every card Alice has, Bob has a card that beats it (and that won't change on the next turn). So, if a player can take cards on the first turn, they win. All that's left to check is who wins on the first turn. If Alice has a card that beats every card Bob has, she wins. Otherwise, Bob wins.",
    "code": "def beats(n, x, y):\n    if x == 0:\n        return y == n - 1\n    if x == n - 1:\n        return y != 0\n    return x > y\n \nfor _ in range(int(input())):\n    n = int(input())\n    owner = input()\n    good = False\n    for i in range(n):\n        if owner[i] != 'A':\n            continue\n        good_move = True\n        for j in range(n):\n            if owner[j] == 'B' and beats(n, j, i):\n                good_move = False\n        if good_move:\n            good = True\n    if good:\n        print('Alice')\n    else:\n        print('Bob')",
    "tags": [
      "brute force",
      "constructive algorithms",
      "games",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2104",
    "index": "D",
    "title": "Array and GCD",
    "statement": "You are given an integer array $a$ of size $n$.\n\nYou can perform the following operations any number of times (possibly, zero):\n\n- pay one coin and increase any element of the array by $1$ (you must have at least $1$ coin to perform this operation);\n- gain one coin and decrease any element of the array by $1$.\n\nLet's say that an array is ideal if both of the following conditions hold:\n\n- each element of the array is at least $2$;\n- for each pair of indices $i$ and $j$ ($1 \\le i, j \\le n$; $i \\ne j$) the greatest common divisor (GCD) of $a_i$ and $a_j$ is equal to $1$. If the array has less than $2$ elements, this condition is automatically satisfied.\n\nLet's say that an array is beautiful if it can be transformed into an ideal array using the aforementioned operations, provided that you initially have no coins. If the array is already ideal, then it is also beautiful.\n\nThe given array is not necessarily beautiful or ideal. You can remove any elements from it (including removing the entire array or not removing anything at all). Your task is to calculate the minimum number of elements you have to remove (possibly, zero) from the array $a$ to make it \\textbf{beautiful}.",
    "tutorial": "First, let's understand that operations from the statement impose only one restriction: the sum of the resulting array must not be greater than the sum of the original one. Now let's consider an ideal array. If there is an element that contains at least two distinct prime factors (or its factorization includes some prime more than once), we can reduce the element to any of its factors and the array remains ideal. This means, we can transform any ideal array into another ideal array that consists only of primes. Furthermore, if a prime $p$ is in the array, but another prime $q$, such that $p > q$, is absent, we can reduce $p$ to $q$ without losing the array's ideal property. Therefore, any ideal array of length $n$ can be transformed into the array that consists of the first $n$ primes. Based on the aforementioned facts, an array of length $n$ is beautiful if its sum is at least the sum of the first $n$ prime numbers. To solve the problem, we can iterate over the number of remaining elements $k$. If the sum of $k$ maximums from the array $a$ is at least the sum of $k$ first primes, we can update the answer. It's also useful to note that the sieve of Eratosthenes can efficiently generate the list of the first prime numbers. You need $4 \\cdot 10^5$ primes, so you have to use the sieve up to something like $6 \\cdot 10^6$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 6e6;\n \nint main() {\n  ios::sync_with_stdio(false); cin.tie(0);\n  vector<int> p, ip(N, 1);\n  for (int i = 2; i < N; ++i) {\n    if (!ip[i]) continue;\n    p.push_back(i);\n    for (int j = i; j < N; j += i) {\n      ip[j] = 0;\n    }\n  }\n  int t;\n  cin >> t;\n  while (t--) {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (auto& x : a) cin >> x;\n    sort(a.begin(), a.end(), greater<int>());\n    int ans = 0;\n    long long suma = 0, sump = 0;\n    for (int i = 0; i < n; ++i) {\n      suma += a[i];\n      sump += p[i];\n      if (suma >= sump) ans = i + 1;\n    }\n    cout << n - ans << endl;\n  }\n}",
    "tags": [
      "binary search",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2104",
    "index": "E",
    "title": "Unpleasant Strings",
    "statement": "Let's call a letter allowed if it is a lowercase letter and is one of the first $k$ letters of the Latin alphabet.\n\nYou are given a string $s$ of length $n$, consisting only of allowed letters.\n\nLet's call a string $t$ pleasant if $t$ is a subsequence of $s$.\n\nYou are given $q$ strings $t_1, t_2, \\dots, t_q$. All of them consist only of allowed letters. For each string $t_i$, calculate the minimum number of allowed letters you need to append to it on the right so that it \\textbf{stops} being pleasant.\n\nA sequence $t$ is a subsequence of a sequence $s$ if $t$ can be obtained from $s$ by the deletion of several (possibly, zero or all) element from arbitrary positions.",
    "tutorial": "For a start, let's think about how to check, is $t$ a subsequence of $s$. There is a greedy solution to that: let's match $t_0$ with the leftmost character in $s$ that is equal to it. Then match $t_1$ with the next leftmost character in $s$ that goes after the first one, and so on. If we matched all characters in $t$, then $t$ is a subsequence of $s$. One of the common ways to write the algorithm above is to count array $\\mathrm{nxt}[n][k]$ where $\\mathrm{nxt}[i][c]$ is the position of the next occurrence of character $c$ starting from position $i$. Array $\\mathrm{nxt}$ can be calculated in linear time, since $\\mathrm{nxt}[i]$ differs from $\\mathrm{nxt}[i + 1]$ in only one position. Then we can check the string $t$ in $\\mathcal{O}(|t|)$ time, just jumping from current position $p$ (in $s$) to $\\mathrm{nxt}[p][t_i]$ until either $t$ ends or $\\mathrm{nxt}$ \"doesn't exist\" (we can set such $\\mathrm{nxt}$ equal to $n$ (remember, zero indexation)). So, how to add the minimum numbers of characters to string $t_i$ to make it unpleasant? It's equivalent to making the minimum number of extra jumps in $\\mathrm{nxt}$ array to reach $\\mathrm{nxt}[p][c] = n$. Suppose, we applied the algorithm above on $t_i$ and finished at position $p$. Now, we are choosing which character to add. It's the same as choosing which $\\mathrm{nxt}[p + 1][c]$ to choose as the next jump. It's not hard to prove that it's optimal to choose $\\mathrm{nxt}[p + 1][c]$ with the maximum value (since it won't increase the answer). After that, we jump to $p' = \\mathrm{nxt}[p + 1][c]$ and the procedure repeats. When $p$ becomes bigger or equal to $n$, we've reached the goal. In other words, the answer depends only on the \"starting\" position $p$. So, we can calculate all of them as a dp array $d[n]$, where $d[i]$ is the minimum number of jumps needed. Then $d[i]$ is equal to $1 + d[\\max{(\\mathrm{nxt}[i + 1][c])}]$ ($i + 1$ here is to exclude the situation where we match the same character in $s$ with several characters from $t$). In total, we precalculate arrays $\\mathrm{nxt}$ and $d$. Then for each $t_i$ we match it in $O(|t_i|)$ and print the value of $d[p]$. The total complexity is $\\mathcal{O}(nk + \\sum{|t_i|})$.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \n#define fore(i, l, r) for(int i = int(l); i < int(r); i++)\n#define sz(a) int((a).size())\n \n#define x first\n#define y second\n \ntypedef long long li;\ntypedef long double ld;\ntypedef pair<int, int> pt;\n \ntemplate<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {\n    return out << \"(\" << p.x << \", \" << p.y << \")\";\n}\ntemplate<class A> ostream& operator <<(ostream& out, const vector<A> &v) {\n    fore(i, 0, sz(v)) {\n        if(i) out << \" \";\n        out << v[i];\n    }\n    return out;\n}\n \nconst int INF = int(1e9);\nconst li INF64 = li(1e18);\nconst ld EPS = 1e-9;\n \nint n, k;\nstring s;\n \ninline bool read() {\n    if(!(cin >> n >> k))\n        return false;\n    cin >> s;\n    return true;\n}\n \ninline void solve() {\n    vector<int> d(n + 1, 0);\n    vector<vector<int>> nxt(n + 2, vector<int>(k, n));\n    for (int i = n - 1; i >= 0; i--) {\n        nxt[i] = nxt[i + 1];\n        int mx = *max_element(nxt[i].begin(), nxt[i].end());\n        d[i] = 1 + d[mx];\n        nxt[i][s[i] - 'a'] = i;\n    }\n \n    int q; cin >> q;\n    while (q--) {\n        string t; cin >> t;\n        int pos = -1;\n        for (char c : t)\n            pos = nxt[pos + 1][c - 'a'];\n        cout << d[pos] << \"\\n\";\n    }\n}\n \nint main() {\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n    int tt = clock();\n#endif\n    ios_base::sync_with_stdio(false);\n    cin.tie(0), cout.tie(0);\n    cout << fixed << setprecision(15);\n    \n    if(read()) {\n        solve();\n        \n#ifdef _DEBUG\n        cerr << \"TIME = \" << clock() - tt << endl;\n        tt = clock();\n#endif\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "strings"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2104",
    "index": "F",
    "title": "Numbers and Strings",
    "statement": "For each integer $x$ from $1$ to $n$, we will form the string $S(x)$ according to the following rules:\n\n- compute $(x+1)$;\n- write $x$ and $x+1$ next to each other in the decimal system without separators and leading zeros;\n- in the resulting string, sort all digits in non-decreasing order.\n\nFor example, the string $S(139)$ is 011349 (before sorting the digits, it is 139140). The string $S(99)$ is 00199.\n\nYour task is to count the number of distinct strings among $S(1), S(2), \\dots, S(n)$.",
    "tutorial": "Consider how the decimal representation of $(x+1)$ depends on $x$. Usually, all digits of $(x+1)$ remain the same, except for the last digit, which is increased by $1$. It does not actually work if the last digit of $x$ is $9$, but we can get a more general rule that handles that case: all $9$'s at the end of the number change to $0$'s, and then the digit before that block of $9$'s gets increased by $1$. Let's split each integer into three parts: the last block of $9$'s (possibly empty), the digit before that block of $9$'s, and all digits before that (possibly none). For example, the number $133799$ is split as follows: $[133, 7, 99]$. The first part of the integer will not be affected if we increase the integer by $1$. So, the order of digits in the first part does not matter: $133799$ gives the same string $S(x)$ as $331799$, since $133$ is a permutation of $331$. So, if there are two integers for which the \"middle\" and the \"right\" part are the same, and the left parts are permutations of each other, the strings $S(x)$ are the same for them. Among several numbers having the same $S(x)$, we are interested only in the smallest number. Let's brute force all numbers such that their left parts are sorted in non-descending order. So, if some digit of the number is less than the previous one, then this digit is the \"middle\" part and every digit to the right of it should be $9$. In my opinion, the easiest way to do this is to run a recursive function like rec(cur, flag), where cur is the current decimal representation of the number, and flag denotes whether we have already built the left and the middle part of the number. If flag is false, we can append any digit to the end of the number (and if it is less than the last digit of cur, we set flag to true); otherwise, we can only append $9$. This may cause our integers to have leading zeroes, but I have an easy fix for this: when converting the decimal representation of the integer to the integer itself, if it has leading zeroes, swap the first digit with the first non-zero digit. Unfortunately, this brute force approach may generate multiple integers having the same $S(x)$, since, for example, $199$ and $901$ have the same $S(x)$, but their left parts are not permutations of each other. So we need to filter the list of numbers we get: if multiple numbers give the same $S(x)$, get rid of all of them except for the minimum one. The model solution does this by storing pairs $(S(x), x)$ and sorting them. After we've filtered the numbers, we can sort them again in non-descending order and use binary search to answer the test cases. The only thing that's left to discuss is why this works fast. We can estimate the number of integers our search will consider as follows: each integer consists of the left part, the digit after it, and the block of $9$'s. The length of the integer is at most $9$, so the length of the left part is at most $8$. The number of possible left parts of length $k$ is ${{k+9}\\choose{k}}$, since constructing the integer of length $k$ with ascending digits can be represetned as a partition of $k$ into $10$ non-negative summands. If the length of the left part is $8$, the number of possible left parts is $24310$, the number of ways to choose the middle part is $9$. This is clearly the largest group of numbers we are interested in, but if you want to check the other groups as well, you can sum them up as follows: $\\sum\\limits_{k=0}^{8} {{k+9}\\choose{k}} \\cdot 9 \\cdot (9-k)$ $(9-k)$ here represents the number of ways to choose the length for the block of $9$'s. Evaluating this formula gives that a bit less than $700000$ integers are considered by our search.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nconst long long A = (long long)(1e18);\n \nstring S(long long x)\n{\n    string s = to_string(x) + to_string(x + 1);\n    sort(s.begin(), s.end());\n    return s;\n}\n \nvector<long long> aux2;\nvector<pair<string, long long>> aux;\n \nlong long get_num(string cur)\n{\n    int first_non_zero = 0;\n    while(cur[first_non_zero] == '0') first_non_zero++;\n    swap(cur[first_non_zero], cur[0]);\n    return stoll(cur);\n}\n \nvoid rec(string cur, bool flag)\n{\n    if(*max_element(cur.begin(), cur.end()) > '0')\n    {\n        long long x = get_num(cur);\n        aux.push_back(make_pair(S(x), x));\n    }\n    if(cur.size() < 9)\n    {\n        if(flag)\n            rec(cur + \"9\", true);\n        else\n            for(char c = '0'; c <= '9'; c++)\n                rec(cur + string(1, c), c < cur.back());    \n    }\n}   \n \nvoid precalc()\n{\n    for(char c = '0'; c <= '9'; c++)\n        rec(string(1, c), false);\n    sort(aux.begin(), aux.end());\n    for(int i = 0; i < aux.size(); i++)\n        if(i == 0 || aux[i].first != aux[i - 1].first)\n            aux2.push_back(aux[i].second);\n    sort(aux2.begin(), aux2.end());\n}\n \nint main()\n{\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    precalc();\n    for(int i = 0; i < t; i++)\n    {\n        long long n;\n        cin >> n;\n        cout << upper_bound(aux2.begin(), aux2.end(), n) - aux2.begin() << endl;              \n    }\n}",
    "tags": [
      "binary search",
      "brute force",
      "dfs and similar",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2104",
    "index": "G",
    "title": "Modulo 3",
    "statement": "Surely, you have seen problems which require you to output the answer modulo $10^9+7$, $10^9+9$, or $998244353$. But have you ever seen a problem where you have to print the answer modulo $3$?\n\nYou are given a functional graph consisting of $n$ vertices, numbered from $1$ to $n$. It is a directed graph, in which each vertex has exactly one outgoing arc. The graph is given as the array $g_1, g_2, \\dots, g_n$, where $g_i$ means that there is an arc that goes from $i$ to $g_i$. For some vertices, the outgoing arcs might be self-loops.\n\nInitially, all vertices of the graph are colored in color $1$. You can perform the following operation: select a vertex and a color from $1$ to $k$, and then color this vertex and all vertices that are reachable from it. You can perform this operation any number of times (even zero).\n\nYou should process $q$ queries. The query is described by three integers $x$, $y$ and $k$. For each query, you should:\n\n- assign $g_x := y$;\n- then calculate the number of different graph colorings for the given value of $k$ (two colorings are different if there exists at least one vertex that is colored in different colors in these two colorings); since the answer can be very large, print it \\textbf{modulo $3$}.\n\nNote that in every query, the initial coloring of the graph is reset (all vertices initially have color $1$ in each query).",
    "tutorial": "First, let's find out how to solve the following problem: you are given a directed graph where all vertices have color $1$. You can choose a vertex and a color from $1$ to $k$, then color it and all vertices reachable from it with that color. How many different colorings are there? Clearly, if a pair of vertices is in the same strongly connected component, they will always have the same color. Furthermore, if we fix a color for each strongly connected component, there is always a way to color the graph such that the colors for all components match the chosen ones. To do this, we can condense the graph and color it in topological order of the condensation. Therefore, the answer for an arbitrary directed graph is $k^c$, where $c$ is the number of strongly connected components. Now let's return to the original problem and try to utilize the fact that the answer is required modulo $3$ (this is probably an important constraint). If $k \\bmod 3 = 0$ or $k \\bmod 3 = 1$, then any power of $k$ is equal to $k$ itself. Therefore, the only complex case is when $k \\bmod 3 = 2$. For $k \\bmod 3 = 2$, even powers are equal to $1$ modulo $3$, while odd powers are equal to $2$. Thus, we are actually interested in the parity of the number of strongly connected components. Let's try to understand how to conveniently count the parity of the number of SCCs for a functional graph. Vertices that are not on cycles represent separate components, and each cycle is a separate component. If a cycle has even length, it changes the parity of the number of SCCs, while if it has odd length, it leaves it unchanged. Therefore, we are actually interested in the number of cycles of even length in the functional graph. If instead of a directed graph, we treat it as an undirected one (making each edge bidirectional), the cycles will not change. We are interested in the number of even cycles, and since there will be a cycle in each connected component, we are interested in the number of connected components without odd cycles. In other words, we need to maintain the number of bipartite connected components in the undirected graph. The further part of the solution is purely technical. Let's use the Dynamic Connectivity Offline method: For each edge, find all time segments during which it exists. Build a segment tree, where each leaf represents a moment in time (the $1$-st leaf is the $1$-st query, the $2$-nd leaf is the $2$-nd query, and so on). For each existence segment of an edge, do the following: break it into $O(\\log q)$ vertices of the segment tree (as in any segment query) and add information to each corresponding vertex that this edge exists throughout this segment. Implement a Disjoint Set Union with the ability to roll back the last operations (we will need to use rank heuristics, but not path compression heuristics). Since we need to maintain bipartiteness, for each vertex in the DSU we will store the parity of the distance to the parent. To perform rollbacks, we can store two arrays that will show for each operation which cell's value changed (the address of the modified variable) and what it was before. We will traverse the segment tree using depth-first search. Each time we enter a vertex of the segment tree, we will add all edges that exist throughout this segment to the DSU and recalculate the number of bipartite components. Upon exiting a vertex, we will roll back the DSU to the version that was present when we entered the vertex. When processing a leaf of the segment tree, we will know how many bipartite components are in the graph at that moment, and thus we will count the number of colorings modulo $3$. Complexity of the solution: $O((q+n) \\log q \\log n)$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nusing pt = pair<int, int>;\n \nconst int N = 200007;\n \nint n, q;\nint k[N];\nvector<pt> t[4 * N];\nint p[N], e[N], rk[N];\nint *pos[3 * N];\nint val[3 * N];\nint csz;\nint ans[N];\n \nvoid upd(int v, int l, int r, int L, int R, pt val) {\n  if (L >= R) return;\n  if (l == L && r == R) {\n    t[v].push_back(val);\n    return;\n  }\n  int m = (l + r) / 2;\n  upd(v * 2 + 1, l, m, L, min(R, m), val);\n  upd(v * 2 + 2, m, r, max(m, L), R, val);\n}\n \nvoid rollback(int tsz) {\n  while (csz > tsz) {\n    --csz;\n    (*pos[csz]) = val[csz];\n  }\n}\n \npt get(int v) {\n  if (p[v] == v) return {v, 0};\n  auto [u, d] = get(p[v]);\n  return {u, d ^ e[v]};\n}\n \nvoid assign(int& x, int y) {\n  pos[csz] = &x;\n  val[csz] = x;\n  ++csz;\n  x = y;\n}\n \npt unite(int x, int y) {\n  auto [v, d1] = get(x);\n  auto [u, d2] = get(y);\n  if (v == u) return {0, d1 ^ d2};\n  if (rk[v] > rk[u]) swap(v, u);\n  assign(p[v], u);\n  assign(e[v], d1 ^ d2 ^ 1);\n  assign(rk[u], rk[v] + rk[u]);\n  return {1, 0};\n}\n \nvoid solve(int v, int l, int r, int cnt) {\n  int tsz = csz;\n  for (auto [x, y] : t[v]) {\n    auto [f, d] = unite(x, y);\n    //cerr << l << \" \" << r << \" \" << x + 1 << \" \" << y + 1 << \" \" << f << \" \" << d << endl;\n    if (!f) cnt ^= d;\n  }\n  if (l != r - 1) {\n    int m = (l + r) / 2;\n    solve(v * 2 + 1, l, m, cnt);\n    solve(v * 2 + 2, m, r, cnt);\n  } else {\n    ans[l] = k[l] % 3;\n    if (ans[l] == 2) ans[l] = cnt + 1;\n  }\n  rollback(tsz);\n}\n \nint main() {\n  cin >> n >> q;\n  vector<int> g(n), lst(n);\n  for (int i = 0; i < n; ++i) {\n    cin >> g[i];\n    --g[i];\n  }\n  for (int i = 0; i < q; ++i) {\n    int x, y;\n    cin >> x >> y >> k[i];\n    --x; --y;\n    upd(0, 0, q, lst[x], i, {x, g[x]});\n    g[x] = y;\n    lst[x] = i;\n  }\n  for (int i = 0; i < n; ++i) {\n    upd(0, 0, q, lst[i], q, {i, g[i]});\n    p[i] = i;\n    rk[i] = 1;\n  }\n  solve(0, 0, q, n & 1);\n  for (int i = 0; i < q; ++i) {\n    cout << ans[i] << '\\n';\n  }\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "dsu",
      "graphs",
      "trees"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2106",
    "index": "A",
    "title": "Dr. TC",
    "statement": "In order to test his patients' intelligence, Dr. TC created the following test.\n\nFirst, he creates a binary string$^{\\text{∗}}$ $s$ having $n$ characters. Then, he creates $n$ binary strings $a_1, a_2, \\ldots, a_n$. It is known that $a_i$ is created by first copying $s$, then flipping the $i$'th character ($1$ becomes $0$ and vice versa). After creating all $n$ strings, he arranges them into a grid where the $i$'th row is $a_i$.\n\nFor example,\n\n- If $s = 101$, $a = [001, 111, 100]$.\n- If $s = 0000$, $a = [1000, 0100, 0010, 0001]$.\n\nThe patient needs to count the number of $1$s written on the board in less than a second. Can you pass the test?\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string is a string that only consists of characters $1$ and $0$.\n\\end{footnotesize}",
    "tutorial": "Every character of $a$ is flipped in exactly one string. Therefore, if $a_i = 1$, we need to add $n-1$ to the answer (since the $i$-$th$ character will stay $1$ for $n-1$ strings), and if $a_i = 0$ we need to add $1$ (since the $i$-$th$ character will be $1$ in exactly one string).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n    int n; cin >> n;\n    string s; cin >> s;\n    int ans = 0;\n    for (auto x: s) {\n        if (x == '0') ans++;\n        else ans += n - 1;\n    }\n    cout << ans << '\\n';\n}\n \nint main() {\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2106",
    "index": "B",
    "title": "St. Chroma",
    "statement": "Given a permutation$^{\\text{∗}}$ $p$ of length $n$ that contains every integer from $0$ to $n-1$ and a strip of $n$ cells, St. Chroma will paint the $i$-th cell of the strip in the color $\\operatorname{MEX}(p_1, p_2, ..., p_i)$$^{\\text{†}}$.\n\nFor example, suppose $p = [1, 0, 3, 2]$. Then, St. Chroma will paint the cells of the strip in the following way: $[0, 2, 2, 4]$.\n\nYou have been given two integers $n$ and $x$. Because St. Chroma loves color $x$, construct a permutation $p$ such that the number of cells in the strip that are painted color $x$ is \\textbf{maximized}.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is a sequence of $n$ elements that contains every integer from $0$ to $n-1$ exactly once. For example, $[0, 3, 1, 2]$ is a permutation, but $[1, 2, 0, 1]$ isn't since $1$ appears twice, and $[1, 3, 2]$ isn't since $0$ does not appear at all.\n\n$^{\\text{†}}$The $\\operatorname{MEX}$ of a sequence is defined as the first non-negative integer that does not appear in it. For example, $\\operatorname{MEX}(1, 3, 0, 2) = 4$, and $\\operatorname{MEX}(3, 1, 2) = 0$.\n\\end{footnotesize}",
    "tutorial": "If $x = n$ then we can output any permutation, since in order for the $\\operatorname{MEX}$ to be equal to $n$, every value $0, 1, ..., n-1$ must appear. Otherwise, we want to build a permutation $p$ such that two main conditions hold. Firstly, we want $x$ to appear on the final strip as soon as possible. In other words, the first index $i$ such that $\\operatorname{MEX}(p_1, p_2, ..., p_i) = x$ must be minimized. In addition, the index $j$ such that $p_j = x$ must be maximized, since the $\\operatorname{MEX}$ of a set that contains $x$ cannot be equal to $x$. There are a lot of constructions that satisfy those conditions. One of them is the permutation $p = [0, 1, ..., x-1, x+1, ..., n-1, x]$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n    int n, x; cin >> n >> x;\n    for (int i = 0; i < x; i++) cout << i << \" \";\n    for (int i = x+1; i < n; i++) cout << i << \" \";\n    if (x < n) cout << x;\n    cout << '\\n';\n}\n \nint main() {\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2106",
    "index": "C",
    "title": "Cherry Bomb",
    "statement": "Two integer arrays $a$ and $b$ of size $n$ are \\textbf{complementary} if there exists an integer $x$ such that $a_i + b_i = x$ over all $1 \\le i \\le n$. For example, the arrays $a = [2, 1, 4]$ and $b = [3, 4, 1]$ are complementary, since $a_i + b_i = 5$ over all $1 \\le i \\le 3$. However, the arrays $a = [1, 3]$ and $b = [2, 1]$ are not complementary.\n\nCow the Nerd thinks everybody is interested in math, so he gave Cherry Bomb two integer arrays $a$ and $b$. It is known that $a$ and $b$ both contain $n$ \\textbf{non-negative} integers not greater than $k$.\n\nUnfortunately, Cherry Bomb has lost some elements in $b$. Lost elements in $b$ are denoted with $-1$. Help Cherry Bomb count the number of possible arrays $b$ such that:\n\n- $a$ and $b$ are \\textbf{complementary}.\n- All lost elements are replaced with non-negative integers no more than $k$.",
    "tutorial": "Suppose that the two arrays $a$ and $b$ of size $n$ are called $s$-complementary if and only if $a_i + b_i = s$ for all $1 \\le i \\le n$. Observation 1: If we know every element of $a$, and we know $s$, we can uniquely determine the elements of $b$. We split the problem into two cases. The first case is if there exists at least one element in $b$ that is not missing. Then we know the required sum $s = a_i + b_i$ for every $1 \\le i \\le n$. For every index $i$, we know $b_i = s - a_i$. If $0 \\le s - a_i \\le k$ doesn't hold for some index, the answer is $0$, since it is impossible for the two arrays to be complementary while $0 \\le b_i \\le k$. Otherwise, the answer is $1$ from Observation 1. The second case is if every element of $b$ is missing: Observation 2: if $a$ and $b$ are $s$-complementary, then the maximum element of $b$ is positioned at the index where the minimum element of $a$ is positioned at. That is because in order for $a_i + b_i = s$ to hold when $a_i$ is minimum, $b_i$ must be maximized. Observation 3: The maximum element of $b$ must be at least $mx_a - mn_a$, i.e. the difference between the maximum and minimum elements of $a$. Suppose that the maximum of $b$ is positioned at index $i$, and $b_i < mx_a - mn_a$. From Observation 2, $a_i = mn_a$, since the position of the maximum element of $b$ is the position of the minimum element of $a$. Then $s = a_i + b_i$, and $a_i + b_i < a_i + mx_a - mn_a$ (since $b_i < mx_a - mn_a$), so $s < mn_a + mx_a - mn_a = mx_a$ (since $a_i = mn_a$). However, $s < mx_a$ cannot hold (since elements of $b$ cannot be negative), therefore this is a contradiciton. From Observation 3 and 1, we can set the maximum element of $b$ to $mx_a - mn_a, mx_a - mn_a + 1, ..., k$, which results to $k - (mx_a - mn_a) + 1$ different solutions.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve() {\n    int n, k; cin >> n >> k;\n    int a[n], b[n];\n    for (int i = 0; i < n; i++) cin >> a[i];\n    for (int i = 0; i < n; i++) cin >> b[i];\n    int s = -1;\n    for (int i = 0; i < n; i++) {\n        if (b[i] != -1) {\n            if (s == -1) s = a[i] + b[i];\n            else {\n                if (s != a[i] + b[i]) {\n                    cout << 0 << '\\n';\n                    return;\n                }\n            }\n        }\n    }\n    if (s == -1) {\n        sort(a, a+n);\n        int mx = a[n-1] - a[0];\n        cout << k - mx + 1 << '\\n';\n        return;\n    }\n    for (int i = 0; i < n; i++) {\n        if (a[i] > s || s - a[i] > k) {\n            cout << 0 << '\\n';\n            return;\n        }\n    }\n    cout << 1 << '\\n';\n}\n \nint main() {\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2106",
    "index": "D",
    "title": "Flower Boy",
    "statement": "Flower boy has a garden of $n$ flowers that can be represented as an integer sequence $a_1, a_2, \\dots, a_n$, where $a_i$ is the beauty of the $i$-th flower from the left.\n\nIgor wants to collect exactly $m$ flowers. To do so, he will walk the garden \\textbf{from left to right} and choose whether to collect the flower at his current position. The $i$-th flower among ones he collects must have a beauty of \\textbf{at least} $b_i$.\n\nIgor noticed that it might be impossible to collect $m$ flowers that satisfy his beauty requirements, so \\textbf{before} he starts collecting flowers, he can pick any integer $k$ and use his magic wand to grow a new flower with beauty $k$ and place it \\textbf{anywhere} in the garden (between two flowers, before the first flower, or after the last flower). Because his magic abilities are limited, he may do this \\textbf{at most once}.\n\nOutput the \\textbf{minimum} integer $k$ Igor must pick when he performs the aforementioned operation to ensure that he can collect $m$ flowers. If he can collect $m$ flowers without using the operation, output $0$. If it is impossible to collect $m$ flowers despite using the operation, output $-1$.",
    "tutorial": "There is a greedy strategy. Every time you see some flower in $a$, if its beauty is not less than the beauty of next flower you must pick from $b$, you will pick it. The answer is $0$ if we run the greedy without inserting a new flower in $a$ and still collecting all $m$ needed flowers. Now, consider what inserting a new flower of beauty $k$ in $a$ will do. It will allow you to \"skip\" some flower listed in $b$, as you can place it anywhere in $a$ and just pick it up when necessary. Therefore, instead of inserting a new element, we can reconsider the problem as deleting some element listed in $b$. So, one slow solution would be to try deleting $b_1$, then running the greedy on $a$, and repeat for $b_2$, $b_3, ..., b_m$. Then, we can keep the minimum $b_i$ such that the greedy was successful when deleting that flower. The solution is too slow. Instead, we can compute for every index $1 \\le i \\le m$ the minimum index $j$ such that if we run the greedy on the prefix $a_1, a_2, ..., a_j$, we will have collected flowers $b_1, b_2, ..., b_i$. Let this value for index $i$ of $b$ be $p_i$. Do the same for each suffix of $a$. Specifically, let $s_i$ be the maximum index $j$ such that if we run the greedy on the suffix $a_j, a_{j+1}, ..., a_n$ we would have collected the flowers $b_i, b_{i+1}, ..., b_m$. These values can be calculated with two pointers. Now, we can delete $b_j$ if $p_{j-1} < s_{j+1}$ (to delete $b_1$, it must be that $s_{2} > 0$ and to delete $b_m$ that $p_{m-1} \\le n$). We keep the minimum among all deletable values in $b$. If there does not exist such a value the answer is $-1$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst int INF = 1e9 + 5;\n \nint main(){\n    int T; cin >> T;\n    while(T--){\n        int N, M; cin >> N >> M;\n        vector<int> a(N), b(M);\n        for(int i = 0; i < N; i++) cin >> a[i];\n        for(int i = 0; i < M; i++) cin >> b[i];\n        vector<int> backwards_match(M);\n        int j = N - 1;\n        for(int i = M - 1; i >= 0; i--){\n            while(j >= 0 && a[j] < b[i]) j--;\n            backwards_match[i] = j--;\n        }\n        vector<int> forwards_match(M);\n        j = 0;\n        for(int i = 0; i < M; i++){\n            while(j < N && a[j] < b[i]) j++;\n            forwards_match[i] = j++;\n        }\n        if(forwards_match.back() < N){\n            cout << 0 << endl;\n            continue;\n        }\n        int ans = INF;\n        for(int i = 0; i < M; i++){\n            int match_previous = i == 0 ? -1 : forwards_match[i - 1];\n            int match_next = i + 1 == M ? N : backwards_match[i + 1];\n            if(match_next > match_previous){\n                ans = min(ans, b[i]);\n            }\n        }\n        cout << (ans == INF ? -1 : ans) << \"\\n\";\n    }\n}\n",
    "tags": [
      "binary search",
      "dp",
      "greedy",
      "two pointers"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2106",
    "index": "E",
    "title": "Wolf",
    "statement": "Wolf has found $n$ sheep with tastiness values $p_1, p_2, ..., p_n$ where $p$ is a permutation$^{\\text{∗}}$. Wolf wants to perform binary search on $p$ to find the sheep with tastiness of $k$, but $p$ may not necessarily be sorted. The success of binary search on the range $[l, r]$ for $k$ is represented as $f(l, r, k)$, which is defined as follows:\n\nIf $l > r$, then $f(l, r, k)$ fails. Otherwise, let $m = \\lfloor\\frac{l + r}{2}\\rfloor$, and:\n\n- If $p_m = k$, then $f(l, r, k)$ is \\textbf{successful},\n- If $p_m < k$, then $f(l, r, k) = f(m+1, r, k)$,\n- If $p_m > k$, then $f(l, r, k) = f(l, m-1, k)$.\n\nCow the Nerd decides to help Wolf out. Cow the Nerd is given $q$ queries, each consisting of three integers $l$, $r$, and $k$. Before the search begins, Cow the Nerd may choose a non-negative integer $d$, and $d$ indices $1 \\le i_1 < i_2 < \\ldots < i_d \\le n$ where $p_{i_j} \\neq k$ over all $1 \\leq j \\leq d$. Then, he may re-order the elements $p_{i_1}, p_{i_2}, ..., p_{i_d}$ however he likes.\n\nFor each query, output the \\textbf{minimum} integer $d$ that Cow the Nerd must choose so that $f(l, r, k)$ can be \\textbf{successful}, or report that it is impossible. Note that the queries are independent and the reordering is not actually performed.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array that contains every integer from $1$ to $n$ exactly once.\n\\end{footnotesize}",
    "tutorial": "Consider some permutation $p_1, p_2, ..., p_n$. Before answering queries, precompute the index of integer $i$ $(1 \\le i \\le n)$, suppose it is represented as $idx_i$. Let's see how to answer some query $l, r, x$. Obviously, if $idx_x$ does not belong in the range $[l, r]$, the answer is $-1$. Otherwise, we want to somehow manipulate the elements so the binary search ends up checking $idx_x$. Suppose the binary search is currently working on some range $[a, b]$. Let $m = \\lfloor\\frac{a + b}{2}\\rfloor$. If $p_m = x$, we are done. Otherwise, consider the following cases: $p_m < x$ and $m < idx_x$: the binary search will continue on $[m+1, b]$, and since $idx_x$ belongs in that range, we simply let it continue. We must not swap this value. $p_m < x$ and $m > idx_x$: the binary search will continue on $[m+1, b]$, but $idx_x$ does not belong in that range. To fix this, we must replace $p_m$ with a value that is greater than $x$, in which case the search will continue on $[a, m-1]$. $p_m > x$ and $m < idx_x$: the binary search will continue on $[a, m-1]$, but $idx_x$ does not belong in that range. To fix this, we must replace $p_m$ with a value that is less than $x$, in which case the search will continue on $[m+1, b]$. $p_m > x$ and $m > idx_x$: the binary search will continue on $[a, m-1]$, and since $idx_x$ belongs in that range, we simply let it continue. We must not swap this value. Keep doing this process until $p_m = x$. Suppose that the amount of integers less than $x$ needed are $s$, and the amount of integers greater than $x$ needed are $b$. In addition, let the values smaller than $x$ that we can't swap (because they already lead to the wanted direction) be denoted by $ss$ and those bigger as $bb$. There are $n - x$ greater values available in $p$, and $x-1$ smaller values available. Therefore, if $b > n - x - bb$ or $s > x - 1 - ss$, the answer is $-1$. If the answer is not $-1$, we swap as many values as possible from $b$ and $s$ (which will be $\\min{(b, s)} * 2$) and those that are still left after that (which will be $(\\max{(b, s)} - \\min{(b, s)}) * 2)$. The final answer is $(\\max{(b, s)} - \\min{(b, s)}) * 2 + \\min{(b, s)} * 2$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n \nvoid solve() {\n    int n, q; cin >> n >> q;\n    int arr[n+1];\n    vector<int> idx(n+1, 0);\n    for (int i = 1; i <= n; i++) {\n        cin >> arr[i];\n        idx[arr[i]] = i;\n    }\n    while (q--) {\n        int l, r, k; cin >> l >> r >> k;\n        if (idx[k] > r || idx[k] < l) {\n            cout << -1 << \" \";\n            continue;\n        }\n        int big = n - k, small = k - 1;\n        int needBig = 0, needSmall = 0;\n        int bigAv = n - k, smallAv = k - 1;\n        int lo = l, hi = r;\n        while (lo <= hi) {\n            int mid = (lo + hi) / 2;\n            if (arr[mid] == k) break;\n            if (mid < idx[k]) { // i want to go right\n                if (k < arr[mid]) {\n                    needSmall++;\n                }\n                else smallAv--;\n                small--;\n                lo = mid+1;\n            }\n            else { // i want to go left\n                if (k > arr[mid]) { \n                    needBig++;\n                }\n                else bigAv--;\n                big--;\n                hi = mid-1;\n            }\n        }\n        if (big < 0 || small < 0) {\n            cout << -1 << \" \";\n            continue;\n        }\n        int ans = 2 * min(needBig, needSmall);\n        int diff = abs(needBig - needSmall);\n        if (needBig > needSmall) {\n            if (bigAv < diff) cout << -1 << \" \";\n            else cout << ans + 2 * diff << \" \";\n        }\n        else {\n            if (smallAv < diff) cout << -1 << \" \";\n            else cout << ans + 2 * diff << \" \";\n        }\n    }\n}\n \nsigned main() {\n    int t; cin >> t;\n    while (t--){\n      solve();\n      cout << \"\\n\";\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "greedy",
      "math"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2106",
    "index": "F",
    "title": "Goblin",
    "statement": "Dr. TC has a new patient called Goblin. He wants to test Goblin's intelligence, but he has gotten bored of his standard test. So, he decided to make it a bit harder.\n\nFirst, he creates a binary string$^{\\text{∗}}$ $s$ having $n$ characters. Then, he creates $n$ binary strings $a_1, a_2, \\ldots, a_n$. It is known that $a_i$ is created by first copying $s$, then flipping the $i$-th character ($1$ becomes $0$ and vice versa). After creating all $n$ strings, he arranges them into an $n \\times n$ grid $g$ where $g_{i, j} = a_{i_j}$.\n\nA set $S$ of size $k$ containing distinct integer pairs $\\{(x_1, y_1), (x_2, y_2), \\ldots, (x_k, y_k)\\}$ is considered good if:\n\n- $1 \\leq x_i, y_i \\leq n$ for all $1 \\leq i \\leq k$.\n- $g_{x_i, y_i} = 0$ for all $1 \\leq i \\leq k$.\n- For any two integers $i$ and $j$ ($1 \\leq i, j \\leq k$), coordinate $(x_i, y_i)$ is reachable from coordinate $(x_j, y_j)$ by traveling through a sequence of adjacent cells (which share a side) that all have a value of $0$.\n\nGoblin's task is to find the maximum possible size of a good set $S$. Because Dr. TC is generous, this time he gave him two seconds to find the answer instead of one. Goblin is not known for his honesty, so he has asked you to help him cheat.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string is a string that only consists of characters $1$ and $0$.\n\\end{footnotesize}",
    "tutorial": "Each column can be broken down to $3$ components: If $a_i = 0$, the top-most component will contain $i-1$ zeros, the second component a single one, and the third component $n-i$ zeros. If $a_i = 1$, the top-most component will contain $i-1$ ones, the second component a single zero, and the third component $n-i$ ones. The easiest way to visualize is with DSU. For each column, create $3$ components, and for each component implicitly store the number of $0$s in it. Now, we will try to merge all adjacent components that both consist of zeros. Consider the following transitions, for every $1 < i \\le n$: If $a_i = 0$ and $a_{i-1} = 0$, then the top-most component of column $i-1$ will be merged with the top-most component of column $i$. The same goes for the two bottom-most components. If $a_i = 0$ and $a_{i-1} = 1$, then the top-most component of column $i$ will be merged with the top-most component of column $i-1$. If $a_i = 1$ and $a_{i-1} = 0$, then the bottom-most component of column $i$ will be merged with the bottom-most component of column $i-1$. If $a_i = 1$ and $a_{i-1} = 1$, we merge nothing. After we finish the merging, we just take the component with the maximum number of zeros, which will be the answer to this problem. Note that you do not actually have to use DSU; we only care about the sizes and not the representatives, so we can also use simple prefix sums.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n \nstruct DSU{\n    vector<int> p, sz;\n    vector<ll> score;\n    \n    DSU(int n){\n        p.assign(n, 0);\n        sz.assign(n, 1);\n        score.assign(n, 0);\n        \n        for (int i = 0; i < n; i++) p[i] = i;\n    }\n    \n    int find(int u){\n        if (p[u] == u) return u;\n        p[u] = find(p[u]);\n        return p[u];\n    }\n    \n    void unite(int u, int v){\n        u = find(u);\n        v = find(v);\n        if (u == v) return;\n        \n        if (sz[u] < sz[v]) swap(u, v);\n        p[v] = u;\n        sz[u] += sz[v];\n        score[u] += score[v];\n    }\n    \n    bool same(int u, int v){\n        return find(u) == find(v);\n    }\n    \n    int size(int u){\n        u = find(u);\n        return sz[u];\n    }\n};\n \nvoid solve(){\n    int n;\n    cin >> n;\n \n    string s;\n    cin >> s;\n    \n    DSU dsu(2 * n);\n    vector<array<int, 2>> prev;\n    for (int i = 0; i < n; i++){\n        if (s[i] == '1'){\n            dsu.score[2 * i] = 1;\n            dsu.unite(2 * i, 2 * i + 1);\n            \n            for (int j = 0; j < prev.size(); j++){\n                int l = prev[j][0];\n                int r = prev[j][1];\n                if (i >= l && i <= r)\n                    dsu.unite(2 * i, 2 * (i - 1) + j);\n            }\n            prev = {{i, i}};\n            continue;\n        }\n \n        vector<array<int, 2>> nxt = {{0, i - 1}, {i + 1, n - 1}};\n        for (int j = 0; j < nxt.size(); j++){\n            auto [l, r] = nxt[j];\n            dsu.score[2 * i + j] = r - l + 1;\n        }\n \n        for (int j = 0; j < prev.size(); j++){\n            for (int k = 0; k < nxt.size(); k++){\n                auto [l1, r1] = prev[j];\n                auto [l2, r2] = nxt[k];\n \n                if (l2 > r1 || r2 < l1)\n                    continue;\n \n                dsu.unite(2 * i + k, 2 * (i - 1) + j);\n            }\n        }\n        prev = nxt;\n    }\n \n    ll ans = 0;\n    for (int i = 0; i < 2 * n; i++)\n        ans = max(ans, dsu.score[i]);\n    cout << ans << \"\\n\";\n}\n \nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "dfs and similar",
      "dp",
      "dsu",
      "greedy",
      "math"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2106",
    "index": "G1",
    "title": "Baudelaire (easy version)",
    "statement": "\\textbf{This is the easy version of the problem. The only difference between the two versions is that in this version, it is guaranteed that every node is adjacent to node $1$.}\n\nThis problem is interactive.\n\nBaudelaire is very rich, so he bought a tree of size $n$ that is rooted at some arbitrary node. Additionally, every node has a value of $1$ or $-1$. \\textbf{In this version, every node is adjacent to node $1$. However, please note that node $1$ is not necessarily the root.}\n\nCow the Nerd saw the tree and fell in love with it. However, computer science doesn't pay him enough, so he can't afford to buy it. Baudelaire decided to play a game with Cow the Nerd, and if he won, he would gift him the tree.\n\nCow the Nerd does not know which node is the root, and he doesn't know the values of the nodes either. However, he can ask Baudelaire queries of two types:\n\n- $1$ $k$ $u_1$ $u_2$ $...$ $u_k$: Let $f(u)$ be the sum of the values of all nodes in the path from the root of the tree to node $u$. Cow the Nerd may choose an integer $k$ $(1 \\le k \\le n)$ and $k$ nodes $u_1, u_2, ..., u_k$, and he will receive the value $f(u_1) + f(u_2) + ... + f(u_k)$.\n- $2$ $u$: Baudelaire will toggle the value of node $u$. Specifically, if the value of $u$ is $1$ it will become $-1$, and vice versa.\n\nCow the Nerd wins if he guesses the value of every node correctly (the values of the final tree, \\textbf{after} performing the queries) within $n + 200$ total queries. Can you help him win?",
    "tutorial": "For some node $u$, let $v_u$ be its value and $s_u$ be the sum of the values of all nodes on the simple path from the root of the tree to node $u$ ($s_u$ will also be referenced as \"the sum of node $u$\" for the purposes of this solution). Also, let $p_u$ be the parent of node $u$ (if $u$ is not the root). Suppose that we know which node is the root of the tree. Then, we can make $n$ queries to find $s_1, s_2, ..., s_n$, which is sufficient to figure out $v_1, v_2, ..., v_n$: it holds that $s_u = s_{p_u} + v_u$, therefore $v_u = s_u - s_{p_u}$. Then, we have $200$ queries left to find the actual root of the tree. Consider some node $u$, and all of its neighbor nodes $c_1, c_2, ..., c_k$. Observation 1: Toggling the value of node $u$ will change the sum of every adjacent node to $u$ that is not the parent. Observation 2: We can find the parent of node $u$ within $3\\log k$ queries. Consider doing binary search to find which node does not change its sum when toggling the value of $u$. In order to check if the prefix $c_1, c_2, ..., c_m$ includes the parent of $u$, we do the following: query for $s1 = s_{c_1} + s_{c_2} + ... + s_{c_m}$, toggle the value of $u$, and query for $s2 = s_{c_1}' + s_{c_2}' + ... + s_{c_m}'$ again. Let $D = |s1 - s2|$. From Observation 1, if every node among $c_1, c_2, ..., c_m$ changed its value, then $D = 2m$, so we know that the parent does not belong in that prefix. Otherwise, there is a node that did not change its sum, so we can continue our binary search on that prefix. This takes $3$ queries performed $\\log k$ times. Note that if we never find the parent, it must mean that $u$ is the root of the tree. Since the tree is a star, if we find the parent of node $1$, we will find the root. If there does not exist a parent, then $1$ is the root. The problem has been solved in $n + 3 \\log(n)$ queries, which comfortably fits the query limit. There are a lot of other (better) solutions for this version (for example, this solution), but this solution helps best for coming up with the idea for G2.",
    "code": "#include <bits/stdc++.h>\nusing i64 = long long;\n \nvoid solve() {\n    int n;\n    std::cin >> n;\n    std::vector<int> a(n+1), son(n-1);\n    for (int i = 1; i < n; ++i) {\n        int u, v;\n        std::cin >> u >> v;\n        son[i-1] = i + 1;\n    }\n    int Q = 0;\n    auto ask = [&](int op, const std::vector<int> &v) {\n        if (++Q > n + 200) {\n            assert(false);\n        }\n        std::cout << \"? \" << op;\n        if (op == 1) {\n            std::cout << ' ' << v.size();\n            for (auto u: v) std::cout << ' ' << u;\n            std::cout << std::endl;\n            int res = 0;\n            std::cin >> res;\n            return res;\n        } else {\n            std::cout << ' ' << v[0] << std::endl;\n            return 0;\n        }\n    };\n    int rt = 0;\n    int bef = ask(1, son);\n    ask(2, std::vector<int>{1});\n    int af = ask(1, son);\n    if (std::abs(bef - af) == 2 * son.size()) {\n        rt = 1;\n    } else {\n        int l = 0, r = son.size() - 1;\n        while (l < r) {\n            int mid = l + (r - l) / 2;\n            std::vector<int> query(son.begin() + l, son.begin() + mid + 1);\n            int bef = ask(1, query);\n            ask(2, std::vector<int>{1});\n            int af = ask(1, query);\n            if (std::abs(bef - af) != 2 * (mid - l + 1)) {\n                r = mid;\n            } else {\n                l = mid + 1;\n            }\n        }\n        rt = son[l];\n    }\n    for (int i = 1; i <= n; ++i) {\n        a[i] = ask(1, std::vector<int>{i});\n    }\n    for (int i = 2; i <= n; ++i) {\n        if (rt != i) {\n            a[i] -= a[1];\n        }\n    }\n    if (rt > 1) a[1] -= a[rt];\n    std::cout << '!';\n    for (int i = 1; i <= n; ++i) {\n        std::cout << ' ' << a[i];\n    }\n    std::cout << std::endl;\n}\n \nint main() {\n    std::cin.tie(nullptr)->sync_with_stdio(false);\n    int T = 1;\n    std::cin >> T;\n    while (T--) solve();\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "divide and conquer",
      "greedy",
      "interactive",
      "trees"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2106",
    "index": "G2",
    "title": "Baudelaire (hard version)",
    "statement": "\\textbf{This is the Hard Version of the problem. The only difference between the two versions is that in the Hard Version the tree may be of any shape.}\n\nThis problem is interactive.\n\nBaudelaire is very rich, so he bought a tree of size $n$, rooted at some arbitrary node. Additionally, every node has a value of $1$ or $-1$.\n\nCow the Nerd saw the tree and fell in love with it. However, computer science doesn't pay him enough, so he can't afford to buy it. Baudelaire decided to play a game with Cow the Nerd, and if he won, he would gift him the tree.\n\nCow the Nerd does not know which node is the root, and he doesn't know the values of the nodes either. However, he can ask Baudelaire queries of two types:\n\n- $1$ $k$ $u_1$ $u_2$ $...$ $u_k$: Let $f(u)$ be the sum of the values of all nodes in the path from the root of the tree to node $u$. Cow the Nerd may choose an integer $k$ $(1 \\le k \\le n)$ and $k$ nodes $u_1, u_2, ..., u_k$, and he will receive the value $f(u_1) + f(u_2) + ... + f(u_k)$.\n- $2$ $u$: Baudelaire will toggle the value of node $u$. Specifically, if the value of $u$ is $1$, it will become $-1$, and vice versa.\n\nCow the Nerd wins if he guesses the value of every node correctly (the values of the final tree, \\textbf{after} performing the queries) within $n + 200$ total queries. Can you help him win?",
    "tutorial": "Read the solution to the Easy Version first. Obviously, if we know the parent of some node, we know which nodes are under that node's subtree, so we never have to consider them as candidates for the root of the tree. Let's use this to choose nodes in a way such that each time we eliminate as many candidates as possible, even in the worst case. Specifically, consider querying for the centroid of the tree (a centroid of a tree is a node that if it is deleted, every connected component left has size no more than half of the original tree). When querying for the centroid, there are two cases: either it is the root of the tree, in which case we are finished, or we find its parent, which eliminates at least half of the current candidates. Then, we delete all nodes that could not possibly be the root, and query for the new centroid. Since the candidates get halved each time, we repeat the above process no more than $\\log n$ times. In the absolute worst case (which is not realistic), we make $3\\log (n) + 3\\log (\\frac{n}{2}) + 3\\log (\\frac{n}{4}) + ... + 3$ queries. For $n = 1000$, this is about $165$ queries. I do want to stress that this case is impossible; the $200$ queries are pretty loose but I want to allow a lot of different solutions (there are some even better ones than the one I described here, feel free to describe better solutions in the comments).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n \nvector<vector<int>> tree, cd;\nvector<int> sub, val;\nvector<bool> del;\nint n, cdRoot = -1;\n \nint ask(vector<int> a) {\n    int k = a.size();\n    cout << \"? 1 \" << k << \" \";\n    for (auto x: a) {\n        cout << x << \" \";\n    }\n    cout << endl;\n    int ans; cin >> ans;\n    return ans;\n}\n \nvoid toggle(int u) {\n    cout << \"? 2 \" << u << endl;\n}\n \nvoid answer(vector<int> ans) {\n    cout << \"! \";\n    for (int i = 1; i <= n; i++) cout << ans[i] << \" \";\n    cout << endl;\n}\n \nvoid calc_sums(int node, int par = 0) {\n    sub[node] = 0;\n    if (del[node]) return;\n    for (auto next: tree[node]) {\n        if (next == par) continue;\n        calc_sums(next, node);\n        sub[node] += sub[next];\n    }\n    sub[node]++;\n}\n \nint find_centroid(int node, int sz, int par = 0) {\n    for (auto next: tree[node]) {\n        if (next == par || del[next]) continue;\n        if (sub[next] * 2 >= sz) return find_centroid(next, sz, node);\n    }\n    return node;\n}\n \nvoid build(int node, int prev) {\n    cd[prev].push_back(node);\n    del[node] = true;\n    for (auto next: tree[node]) {\n        if (del[next]) continue;\n        calc_sums(next, node);\n        int cent = find_centroid(next, sub[next], node);\n        build(cent, node);\n    }\n}\n \nbool inspect(vector<int> a, int tog) {\n    int b4 = ask(a);\n    toggle(tog);\n    int aft = ask(a);\n    int k = a.size();\n    int must = b4;\n    if (aft < b4) {\n        must -= 2 * k;\n    }\n    else must += 2 * k;\n    if (aft != must) return true;\n    else return false;\n}\n \nint find_sus(vector<int> a, int tog) {\n    int k = a.size();\n    int lo = 0, hi = k-1;\n    int ans = -1;\n    while (lo <= hi) {\n        int mid = (lo + hi) / 2;\n        vector<int> qr;\n        for (int j = 0; j <= mid; j++) {\n            qr.push_back(a[j]);\n        }\n        if (inspect(qr, tog)) {\n            ans = mid;\n            hi = mid-1;\n        }\n        else lo = mid+1;\n    }\n    return ans; \n}\n \nint find_root(int node, int par = 0) {\n    if (cd[node].empty()) return node;\n    vector<int> ch;\n    for (auto next: cd[node]) {\n        if (next == par) continue;\n        ch.push_back(next);\n    }\n    int sus = find_sus(ch, node);\n    if (sus == -1) return node;\n    return find_root(ch[sus], node);\n}\n \nvoid find_vals(int node, int par = 0, int above = 0) {\n    val[node] -= above;\n    above += val[node];\n    for (auto next: tree[node]) {\n        if (next != par) {\n            find_vals(next, node, above);\n        }\n    }\n}\n \nvoid solve() {\n    cin >> n;\n    cd.assign(n+1, {});\n    tree.assign(n+1, {});\n    for (int i = 1; i < n; i++) {\n        int u, v; cin >> u >> v;\n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }    \n    del.assign(n+1, false);\n    sub.assign(n+1, 0);\n    calc_sums(1);\n    cdRoot = find_centroid(1, n);\n    build(cdRoot, 0);\n    int root = find_root(cdRoot);\n    val.resize(n+1);\n    for (int i = 1; i <= n; i++) {\n        val[i] = ask({i});\n    }\n    find_vals(root);\n    answer(val);\n}\n \nsigned main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t; cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "divide and conquer",
      "implementation",
      "interactive",
      "trees"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2107",
    "index": "A",
    "title": "LRC and VIP",
    "statement": "You have an array $a$ of size $n$ — $a_1, a_2, \\ldots a_n$.\n\nYou need to divide the $n$ elements into $2$ sequences $B$ and $C$, satisfying the following conditions:\n\n- Each element belongs to exactly one sequence.\n- Both sequences $B$ and $C$ contain at least one element.\n- $\\gcd$ $(B_1, B_2, \\ldots, B_{|B|}) \\ne \\gcd(C_1, C_2, \\ldots, C_{|C|})$ $^{\\text{∗}}$\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.\n\\end{footnotesize}",
    "tutorial": "When all the elements of the array are equal, the solution is trivially impossible since the $\\gcd$ of any subset will always be equal to $a_1$. That is infact the only $\\texttt{No}$ case. We show a construction otherwise. Let $\\operatorname{mx} = \\max(a)$. Put all the elements equal to $\\operatorname{mx}$ in one set, and all the other elements in the other set. Then, the $\\gcd$ of the first set is $\\operatorname{mx}$ while the other set will have a strictly smaller $\\gcd$ (because $\\gcd(a, b) \\le \\min(a, b)$) Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    \n    while (t--){\n        int n; cin >> n;\n        vector <int> a(n);\n        for (int i = 0; i < n; i++){\n            cin >> a[i];\n        }\n        int mn = *min_element(a.begin(), a.end());\n        int mx = *max_element(a.begin(), a.end());\n        if (mn == mx){\n            cout << \"No\\n\";\n            continue;\n        }\n        cout << \"Yes\\n\";\n        for (int i = 0; i < n; i++){\n            cout << (1 + (a[i] == mx)) << \" \\n\"[i + 1 == n];\n        }\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "number theory"
    ],
    "rating": 800
  },
  {
    "contest_id": "2107",
    "index": "B",
    "title": "Apples in Boxes",
    "statement": "Tom and Jerry found some apples in the basement. They decided to play a game to get some apples.\n\nThere are $n$ boxes, and the $i$-th box has $a_i$ apples inside. Tom and Jerry take turns picking up apples. Tom goes first. On their turn, they have to do the following:\n\n- Choose a box $i$ ($1 \\le i \\le n$) with a positive number of apples, i.e. $a_i > 0$, and pick $1$ apple from this box. Note that this reduces $a_i$ by $1$.\n- If no valid box exists, the current player loses.\n- If \\textbf{after the move}, $\\max(a_1, a_2, \\ldots, a_n) - \\min(a_1, a_2, \\ldots, a_n) > k$ holds, then the current player (who made the last move) also loses.\n\nIf both players play optimally, predict the winner of the game.",
    "tutorial": "Suppose $\\max(a) - \\min(a) \\le k$ holds, and there is at least one $a_i \\ge 1$. Then, infact it is possible to take one apple while still keeping the condition of $\\max(a) - \\min(a) \\le k$. We will subtract from the maximum element. Then $\\min(a)$ does not change except when $a_1 = a_2 = \\ldots = a_n$. In that special case, you can check that the move is valid as $\\max(a) - \\min(a)$ becomes $1$. In any other case, $\\max(a)$ reduces by $0$ or $1$, so $\\max(a) - min(a)$ only decreases, and thus $\\max(a) - \\min(a) \\le k$ clearly holds. Thus, for an array with $\\max(a) - \\min(a) \\le k$, the only way for a player to lose is when all $a_i = 0$. But this happens exactly after the $\\sum(a_i)$-th turn because each turn reduces $\\sum(a_i)$ by $1$. It may be possible that a first move itself is not possible. For example, in the case that $a = [4, 1], k = 1$. We should check that after subtracting the maximum element, the array has the property that $\\max(a) - \\min(a) \\le k$ and immediately print $\\texttt{Jerry}$ otherwise. In the other case, we can simply print $\\texttt{Tom}$ when $\\sum(a_i)$ is odd, and $\\texttt{Jerry}$ when $\\sum(a_i)$ is even. This is because when $\\sum (a_i)$ is odd, Tom will be the last person to make a move since he went first and the total number of turns is odd, and vice versa. Time complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    \n    while (t--){\n        int n, k; cin >> n >> k;\n        \n        vector <int> a(n);\n        for (auto &x : a) cin >> x;\n        \n        long long sum = accumulate(a.begin(), a.end(), 0LL);\n        \n        sort(a.begin(), a.end());\n        a[n - 1]--;\n        sort(a.begin(), a.end());\n        \n        if (a[n - 1] - a[0] > k || sum % 2 == 0){\n            cout << \"Jerry\\n\";\n            continue;\n        }\n        cout << \"Tom\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "games",
      "greedy",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2107",
    "index": "C",
    "title": "Maximum Subarray Sum",
    "statement": "You are given an array $a_1,a_2,\\ldots,a_n$ of length $n$ and a positive integer $k$, but some parts of the array $a$ are missing. Your task is to fill the missing part so that the \\textbf{maximum subarray sum}$^{\\text{∗}}$ of $a$ is exactly $k$, or report that no solution exists.\n\nFormally, you are given a binary string $s$ and a partially filled array $a$, where:\n\n- If you remember the value of $a_i$, $s_i = 1$ to indicate that, and you are given the real value of $a_i$.\n- If you don't remember the value of $a_i$, $s_i = 0$ to indicate that, and you are given $a_i = 0$.\n\nAll the values that you remember satisfy $|a_i| \\le 10^6$. However, you may use values up to $10^{18}$ to fill in the values that you do not remember. It can be proven that if a solution exists, a solution also exists satisfying $|a_i| \\le 10^{18}$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$The \\textbf{maximum subarray sum} of an array $a$ of length $n$, i.e. $a_1, a_2, \\ldots a_n$ is defined as $\\max_{1 \\le i \\le j \\le n} S(i, j)$ where $S(i, j) = a_i + a_{i + 1} + \\ldots + a_j$.\n\\end{footnotesize}",
    "tutorial": "We assume that there is at least one $s_i = 0$ (unfilled position). In the other case that all $s_i = 1$, we can easily check if the maximum subarray sum is $k$ or not. Let us first figure out when the answer is impossible. Replace all $a_i = -\\texttt{INF}$ such that $s_i = 0$. If the maximum subarray sum is still $> k$, then the answer is clearly impossible. In every other case, the answer is infact possible! All positions with $s_i = 0$ will be kept $-\\texttt{INF}$ except for $1$. Choose that position arbitrarily, let's call it $pos$. Let $b =$ max prefix sum in the subarray $[a_{pos + 1}, a_{pos + 2}, \\ldots, a_n]$. Let $c =$ max suffix sum in the subarray $[a_1, a_2, \\ldots, a_{pos - 1}]$. Here we will allow the empty prefix and suffix too. Suppose the value of $a_{pos} = x$. Then, the maximum subarray sum including $pos$ will be $x + b + c$. And the maximum subarray not including $pos$ will be $\\le k$, because thats equivalent to replacing $a_{pos}$ with $-\\texttt{INF}$. Thus, we can simply replace $x$ with $k - b - c$ and it will satisfy the conditions. Let $f(x)$ be defined as the maximum subarray sum when we replace $a_{pos}$ with $x$. Note the following properties of $f(x)$: $f(-\\texttt{INF}) \\le k$: Because this is the assumption for the non-impossible case. $f(-\\texttt{INF}) \\le k$: Because this is the assumption for the non-impossible case. $f(k) \\ge k$: Because the subarray $[a_{pos}]$ itself has a sum of $k$, so the maximum subarray sum must be greater. $f(k) \\ge k$: Because the subarray $[a_{pos}]$ itself has a sum of $k$, so the maximum subarray sum must be greater. $f(x + 1) \\ge f(x)$ : Because increasing an element cannot reduce the maximum subarray sum. $f(x + 1) \\ge f(x)$ : Because increasing an element cannot reduce the maximum subarray sum. $f(x + 1) \\le f(x) + 1$: Because by increasing $a_{pos}$, each subarray increases by $0$ or $1$ depending on whether it includes $pos$. Thus, there is no way for the function calculating maximum subarray sum to increase by more than $1$. $f(x + 1) \\le f(x) + 1$: Because by increasing $a_{pos}$, each subarray increases by $0$ or $1$ depending on whether it includes $pos$. Thus, there is no way for the function calculating maximum subarray sum to increase by more than $1$. With these observations, we can infact binary search on the first $x$ such that $f(x) = k$. This is because, $f$ becomes continuous on the set of integers by the third and fourth property, and hence it will take all values in the range $[f(a), f(b)]$ for $a \\le b$, and we have shown that $k \\in [f(-\\texttt{INF}), f(k)]$ by the first and second property. In both solutions, be careful to avoid overflow. One simple way is to have $\\texttt{INF} = 10^{13}$, as that is sufficient for our purposes (prevents overflow, but still larger than $k + \\sum{a_i}$). Time complexity: $O(n)$ or $O(n \\cdot \\log(A))$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    while (t--){\n        int n; \n        long long k; \n        cin >> n >> k;\n        string s; cin >> s;\n        vector <long long> a(n);\n        for (auto &x : a) cin >> x;\n        \n        int pos = -1;\n        for (int i = 0; i < n; i++){\n            if (s[i] == '0'){\n                pos = i;\n                a[i] = -1e13;\n            }\n        }\n        \n        long long mx = 0;\n        long long curr = 0;\n        for (int i = 0; i < n; i++){\n            curr = max(curr + a[i], a[i]);\n            mx = max(mx, curr);\n        }\n        if (mx > k || (mx != k && pos == -1)){\n            cout << \"No\\n\";\n            continue;\n        }\n        if (pos != -1){\n            mx = 0, curr = 0;\n            long long L, R;\n            \n            for (int i = pos + 1; i < n; i++){\n                curr += a[i];\n                mx = max(mx, curr);\n            }\n            L = mx;\n            mx = 0;\n            curr = 0;\n            for (int i = pos - 1; i >= 0; i--){\n                curr += a[i];\n                mx = max(mx, curr);\n            }\n            R = mx;\n            \n            a[pos] = k - L - R;\n        }\n        \n        cout << \"Yes\\n\";\n        for (int i = 0; i < n; i++){\n            cout << a[i] << \" \\n\"[i + 1 == n];\n        }\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2107",
    "index": "D",
    "title": "Apple Tree Traversing",
    "statement": "There is an apple tree with $n$ nodes, initially with one apple at each node. You have a paper with you, initially with nothing written on it.\n\nYou are traversing on the apple tree, by doing the following action as long as there is at least one apple left:\n\n- Choose an \\textbf{apple path} $(u,v)$. A path $(u,v)$ is called an \\textbf{apple path} if and only if for every node on the path $(u,v)$, there's an apple on it.\n- Let $d$ be the number of apples on the path, write down three numbers $(d,u,v)$, in this order, on the paper.\n- Then remove all the apples on the path $(u,v)$.\n\nHere, the path $(u, v)$ refers to the sequence of vertices on the unique shortest walk from $u$ to $v$.\n\nLet the number sequence on the paper be $a$. Your task is to find the lexicographically largest possible sequence $a$.",
    "tutorial": "Note that the problem has a simple $O(n^2)$ solution by greedily finding the largest diameter in the current forest (set of disjoint trees) at every step, tiebreaking by the lexicographic order of the endpoints, then removing the diameter and continuing this process while at least $1$ node remains. Property $1$: $2$ diameters always share at least one node. With some background theory about diameters, this becomes trivial as when diameter length (in terms of nodes) is odd, they share a common central node; and when even, they share an edge (which shares $2$ nodes). Nevertheless, we provide an elementary proof. Let $a_1, a_2, \\ldots a_d$ and $b_1, b_2, \\ldots b_d$ be $2$ distinct diameters that do not share any node. Consider the closest pair of $2$ points in these $2$ paths, say $a_i$ and $b_j$ are closest. Then, the path $(a_i, b_j)$ cannot contain any other $a_k$ or any other $b_k$ because otherwise it would be a contradiction to the fact that they are closest. Now, the length of the path $(a_1, b_1)$ is $(i - 1) + \\operatorname{dist}(a_i, b_j) + (j - 1)$, where $\\operatorname{dist}(x, y)$ denotes the number of nodes on the path $(x, y)$. Assume that $i, j \\ge \\frac{d + 1}{2}$, then $\\operatorname{dist}(a_1, b_1)$ is strictly larger than $d$ (using $\\operatorname{dist}(a_i, b_j) \\ge 2$), contradicting that $d$ is the diameter. In the other cases of $i, j$ being smaller than $\\frac{d + 1}{2}$, we can check the pairs $(a_1, b_d), (a_d, b_1)$ and $(a_d, b_d)$. It is easy to see at least one of them will be larger than $d$. Property $2$ : Let $(u, v)$ denote a diameter path, and $T$ denote the tree. Then $\\operatorname{diam}(T \\setminus (u, v)) < \\operatorname{diam}(T)$ (strictly smaller). This comes directly from the previous property. Since all diameters share at least one node, the new forest generated after removing path $(u, v)$ will have a strictly smaller diameter. Property $3$ : In any sequence of positive numbers such that $a_1 + a_2 + \\ldots + a_k \\le n$ such that $a_i < a_j$ for all $1 \\le i < j \\le k$, $k$ is at most $O(\\sqrt{n})$. This is a classical property. Note that $a_i \\ge i$ for all $1 \\le i \\le k$ by induction. And thus, $a_1 + a_2 + \\ldots + a_k \\ge 1 + 2 + \\ldots + k = \\dfrac{k \\cdot (k + 1)}{2}$. But, $a_1 + a_2 + \\ldots + a_k \\le n$ implies $\\dfrac{k \\cdot (k + 1)}{2} \\le n$, and so $k \\le 2 \\cdot \\sqrt{n}$. With these $3$ properties, we can now solve the problem. We describe the algorithm below: Maintain a collection of subtrees (of nodes which have apples). Initially, the whole tree is there as one component. Maintain a collection of subtrees (of nodes which have apples). Initially, the whole tree is there as one component. For every subtree, find it's lexicographically largest triplet of $(d, u, v)$ using a BFS/DFS. For every subtree, find it's lexicographically largest triplet of $(d, u, v)$ using a BFS/DFS. Remove the nodes on the diameter path for each subtree. This divides the component into several smaller subtrees. Add them to our collection. Remove the nodes on the diameter path for each subtree. This divides the component into several smaller subtrees. Add them to our collection. Repeat steps $2$ and $3$ while our collection is non-empty. Repeat steps $2$ and $3$ while our collection is non-empty. Finally, sort (in descending order) the list of $(d, u, v)$ collected throughout all the steps, and output. Finally, sort (in descending order) the list of $(d, u, v)$ collected throughout all the steps, and output. It is not hard to see that the above approach produces the correct answer. And it runs in $O(n \\cdot \\sqrt{n})$ time because steps $2$ and $3$ are repeated only $O(\\sqrt{n})$ times. Every smaller tree is formed from a larger \"parent\" tree. The diameter of the smaller tree is smaller than the diameter of the larger tree using Property $2$. Suppose that there is some tree that is formed at $k$-th step. Then, consider the sequence of parent trees of this tree, and their diameters. Their diameters form a strictly increasing sequence, but their sum must be bounded by $n$ since we remove that many nodes, and total removed nodes is $n$. Thus, using Property $3$, we get $k \\le \\sqrt{2 \\cdot n}$. There are several correct ways to implement Step $2$. One of the neatest way is as follows: Find the furthest node from $1$, tie breaking lexicographically, say we got $x$. Find the furthest node from $x$, again tie breaking lexicopgraphically, say we got $y$. Then $(\\max(x, y), \\min(x, y))$ is the required diameter. To prove that these $2$ traversals are enough, you can use the fact mentioned in proof of property $1$, i.e. diameters share a central node or an edge (depending on parity). To find the furthest node, we can use BFS or DFS both fairly easily. For step $3$, we can keep recursing to the parent of $y$ till we reach $x$, assuming we have calculated the parents of all vertices with a dfs from $x$. You may refer to the code. Solve the problem in $O(n \\cdot \\log(n))$. Let $f_i,g_i$ be the longest and second longest path from $i$ in $i$'s subtree, the diameter will be $\\max \\limits_{i=1}^n {f_i+g_i}$. When we find a diameter $(u,v)$, let update $f_u,g_u$ for all $u$ on the path $(\\operatorname{lca}(u,v),\\text{root})$. Note that the path $(\\operatorname{lca}(u,v),\\text{root})$ will be always shorter than the diameter, so the total update times will be $\\mathcal O(n)$. Use a std::set to find $f_u,g_u$ for every node $u$ and a std::priority_queue to maintain the maximum $f_i + g_i$, the total complexity is $\\mathcal O(n \\log n)$. Compute provably the exact worst case, and construct a tree that obtains it. It can be proven that diameter decreases by $2$ each iteration and not just $1$, and it is possible to obtain this as we show later. So the best bound is $d$ where $1 + 3 + 5 + \\ldots + (2 \\cdot d - 1) \\le n$, which comes out to be $\\sqrt{n}$. Let $L = \\sqrt{n}$. Make $P_1, P_2, \\ldots, P_L$ where $P_i$ is a line graph of size $2 \\cdot i - 1$. Now, connect the central nodes of $P_i$ and $P_{i - 1}$ for all $i$. Refer to Wuhudsm comment for a picture.",
    "code": "#include<bits/stdc++.h>\n#ifdef DEBUG_LOCAL\n#include <mydebug/debug.h>\n#endif\nusing ll = long long;\nconst int N = 5e5+5;\nusing namespace std;\nusing pi = pair<int,int>;\nusing ti = tuple<int,int,int,int>;\nint T,n,u,v,del[N],fa[N],ct;  vector<int> g[N]; set<pi> t[N];\nvoid dfs(int u,int f){\n    t[u].emplace(0,u),fa[u] = f;\n    for(int v : g[u]) if(v != f){\n        dfs(v,u); auto [x,y] = *--t[v].end();\n        t[u].emplace(x+1,y);\n    }\n}ti gt(int u){\n    assert(t[u].size() >= 1);\n    if(t[u].size() == 1) return {0,u,u,u};\n    auto [x,y] = *--t[u].end();\n    auto [p,q] = *--(--t[u].end());\n    return {x + p,max(y,q),min(y,q),u};\n}void los(){\n    cin >> n;\n    for(int i = 1;i <= n;i ++) g[i].clear(),del[i] = 0,t[i].clear();\n    for(int i = 1;i < n;i ++) cin >> u >> v,g[u].push_back(v),g[v].push_back(u);\n    ct = 0,dfs(1,0); priority_queue<ti> q;\n    for(int i = 1;i <= n;i ++) q.emplace(gt(i));\n    while(q.size()){\n        auto [di,u,v,d] = q.top(); q.pop();\n        if(del[d] || ti{di,u,v,d} != gt(d)) continue;\n        cout << di + 1 << \" \" << u << \" \" << v << \" \";\n        while(u != d) del[u] = 1,u = fa[u];\n        while(v != d) del[v] = 1,v = fa[v];\n        del[d] = 1; \n        auto [x,y] = *--t[d].end();\n        while(fa[d] && !del[fa[d]]){\n            d = fa[d];\n            if(t[d].count({++x,y})) t[d].erase({x,y});\n            q.emplace(gt(d));\n            if(fa[d]){\n                auto [a,b] = *--t[d].end();\n                t[fa[d]].emplace(a+1,b);\n            }\n        }\n    }cout << \"\\n\";\n}int main(){\n    ios::sync_with_stdio(0),cin.tie(0);\n    for(cin >> T;T --;) los();\n}",
    "tags": [
      "brute force",
      "dfs and similar",
      "greedy",
      "implementation",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2107",
    "index": "E",
    "title": "Ain and Apple Tree",
    "statement": "If I was also hit by an apple falling from an apple tree, could I become as good at physics as Newton?\n\nTo be better at physics, Ain wants to build an apple tree so that she can get hit by apples on it. Her apple tree has $n$ nodes and is rooted at $1$. She defines the weight of an apple tree as $\\sum \\limits_{i=1}^n \\sum \\limits_{j=i+1}^n \\text{dep}(\\operatorname{lca}(i,j))$.\n\nHere, $\\text{dep}(x)$ is defined as the number of edges on the unique shortest path from node $1$ to node $x$. $\\operatorname{lca}(i, j)$ is defined as the unique node $x$ with the largest value of $\\text{dep}(x)$ and which is present on both the paths $(1, i)$ and $(1, j)$.\n\nFrom some old books Ain reads, she knows that Newton's apple tree's weight is around $k$, but the exact value of it is lost.\n\nAs Ain's friend, you want to build an apple tree with $n$ nodes for her, and the absolute difference between your tree's weight and $k$ should be \\textbf{at most $1$}, i.e. $|\\text{weight} - k| \\le 1$. Unfortunately, this is not always possible, in this case please report it.",
    "tutorial": "Let $C(n, k)$ denote $\\frac{n!}{k! \\cdot (n - k)!}$. We first start from the maximum possible value of $k$, and the tree that achieves it, i.e. a straight line path rooted at $1$. It is not too hard to see that this tree has the largest weight, and the weight of this tree is $C(n, 3)$. Thus, for $k > C(n, 3) + 1$, we answer $\\texttt{No}$. We can prove the largest weight point by proving each node should have exactly $1$ child. Suppose instead some node $u$ has $\\ge 2$ children, $c_1$ and $c_2$, but then if we attached $c_1$ to $c_2$ and broke the $c_1$ and $u$ edge, it increases the weight. Now, infact the answer is possible for all $0 \\le k \\le C(n, 3) + 1$. We try to modify the line graph to give a valid construction. First of all, replace $k$ with $C(n, 3) - k$ and view the problem as reducing the weight of the line graph instead. Suppose we broke the edge $(n - 1) - n$ and added the edge $x - n$, then the weight decreases by $C(n - x, 2)$. This is because the depth of LCA with nodes $n - 1$, $n - 2, \\ldots, x$ change and they decrease by $n - x - 1, n - x - 2, \\ldots 1$ respectively. Suppose, after this step, we further broke the edge $(n - 2) - (n - 1)$, and added the edge $y - (n - 1)$. It is tempting to say that the weight again decreases by $C(n - 1 - y, 2)$ but this is only true when $y \\ge x$. If we generalize the above, and break the edges $(i - 1) - i$ and add the edge $a_i - i$ ($a_i < i$), then the weight will decrease by $C(i - a_i, 2)$ as long as the sequence $a$ is decreasing (or $a_i = i - 1$, i.e. we do not change the parent). Because $a$ must be decreasing, that means that $i - a_i$ can only contain distinct elements (or $i - a_i = 1$). This reduces the problem to Find sum of distinct elements of $C(i, 2)$ ($0 \\le i \\le n - 1$)at most $1$ from k. Infact the greedy algorithm solves this problem, i.e. take the largest (untaken) value of $C(i, 2) \\le k$ at each step. We prove by induction. For $n \\le 5$, it can be verified through bruteforce for all cases. For $n \\ge 6$, if $k$ is $\\le C(n - 1, 3)$, just set $n = n - 1$ and by induction it is solvable. If $C(n - 1, 3) < k \\le C(n, 3)$, then we set $k = k - C(n - 1, 2)$ and use induction. It can be verified that $0 \\le k \\le C(n - 1, 3)$ after this modification and so it is valid.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    while (t--){\n        int n; cin >> n;\n        long long k; cin >> k;\n        \n        long long mx = 1LL * n * (n - 1) * (n - 2) / 6;\n        if (k > mx + 1){\n            cout << \"No\\n\";\n            continue;\n        }\n        cout << \"Yes\\n\";\n        k = mx - min(k, mx);\n        \n        int p = n - 1;\n        for (int i = n; i >= 2; i--){\n            while (1LL * p * (p - 1) / 2 > k){\n                p--;\n            }\n            k -= 1LL * p * (p - 1) / 2;\n            \n            cout << (i - p) << \" \" << i << \"\\n\";\n            if (p != 1) p--;\n        }\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "math",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2107",
    "index": "F1",
    "title": "Cycling (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $1\\le n\\le 5\\cdot 10^3$ and you don't need to output the answer for each prefix. You can hack only if you solved all versions of this problem.}\n\nLeo works as a programmer in the city center, and his lover teaches at a high school in the suburbs. Every weekend, Leo would ride his bike to the suburbs to spend a nice weekend with his lover.\n\nThere are $n$ cyclists riding in front of Leo on this road right now. They are numbered $1$, $2$, $\\ldots$, $n$ from front to back. Initially, Leo is behind the $n$-th cyclist. The $i$-th cyclist has an agility value $a_i$.\n\nLeo wants to get ahead of the $1$-st cyclist. Leo can take the following actions as many times as he wants:\n\n- Assuming that the first person in front of Leo is cyclist $i$, he can go in front of cyclist $i$ for a cost of $a_i$. This puts him behind cyclist $i - 1$.\n- Using his super powers, swap $a_i$ and $a_j$ ($1\\le i < j\\le n$) for a cost of $(j - i)$.\n\nLeo wants to know the minimum cost to get in front of the $1$-st cyclist. Here you only need to print the answer for the whole array, i.e. $[a_1, a_2, \\ldots, a_n]$.",
    "tutorial": "Let us try to figure out the optimal strategy. We want to use small values for the \"overtake\" operation, and we will use \"swap\" operations to make the overtakes less costly. Suppose $p =$ first position of minima element. We should over take cyclists $1, 2, \\ldots, p$ for the cost of $a_p$, swapping $p$ till first. This is because all $a_i (1 \\le i < p)$ is $\\ge a_p + 1$, and so the swap + overtake can't be worse. And obviously, if we are using $a_q (q > p)$, it is less costly in terms of swaps to use $p$ since the overtake cost cannot be worse. Now, we might use the value $a_p$ for overtakes in the suffix as well, i.e. there exists some $q \\ge p$ such that we overtake cyclists $1, 2, \\ldots, q$ using $a_p$. This reduces the problem to the subproblem $a[q + 1, n]$, and thus we can use Dynamic Programming! But why are the problems independent in $a[q + 1, n]$ and the rest of the array? Suppose that we took some $a_i (i \\le q)$ to be used for swaps in the suffix $a[q + 1, n]$, but we could then instead set up the swaps such that first $p$ reaches $q$, and then $p$ is taken for these suffix swaps. This won't add any additional swaps, and may only reduce the cost. Let $dp_i$ be the answer for the suffix $a[i, n]$. Then, we compute $p =$ position of minima in $a[i, n]$, iterate on partition index $j$ such that we will take $p$ to $j$ using it for swaps $1, 2 \\ldots, j$, value computed as $dp_{j + 1} + a_p \\cdot (j - i) + S$, where $S$ denotes the total swaps made ($S = 2 \\cdot (j - p) + (p - i - 1)$). This solves the problem in $O(n^2)$.",
    "code": "\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main(){\n    int t; cin >> t;\n    while (t--){\n        int n; cin >> n;\n        \n        vector <int> a(n + 1);\n        for (int i = 1; i <= n; i++){\n            cin >> a[i];\n        }\n        \n        vector <long long> dp(n + 1, 1e18);\n        dp[n] = 0;\n        \n        for (int i = n - 1; i >= 0; i--){\n            int p = i + 1;\n            for (int j = i + 1; j <= n; j++) if (a[j] < a[p]){\n                p = j;\n            }\n            \n            for (int j = p; j <= n; j++){\n                dp[i] = min(dp[i], dp[j] + 2 * (j - p) + 1LL * (j - i) * a[p] + (p - i - 1));\n            }\n        }\n        \n        cout << dp[0] << \"\\n\";\n    }\n    return 0;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "dp",
      "greedy"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2107",
    "index": "F2",
    "title": "Cycling (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $1\\le n\\le 10^6$ and you need to output the answer for each prefix. You can hack only if you solved all versions of this problem.}\n\nLeo works as a programmer in the city center, and his lover teaches at a high school in the suburbs. Every weekend, Leo would ride his bike to the suburbs to spend a nice weekend with his lover.\n\nThere are $n$ cyclists riding in front of Leo on this road right now. They are numbered $1$, $2$, $\\ldots$, $n$ from front to back. Initially, Leo is behind the $n$-th cyclist. The $i$-th cyclist has an agility value $a_i$.\n\nLeo wants to get ahead of the $1$-st cyclist. Leo can take the following actions as many times as he wants:\n\n- Assuming that the first person in front of Leo is cyclist $i$, he can go in front of cyclist $i$ for a cost of $a_i$. This puts him behind cyclist $i - 1$.\n- Using his super powers, swap $a_i$ and $a_j$ ($1\\le i < j\\le n$) for a cost of $(j - i)$.\n\nLeo wants to know the minimum cost to get in front of the $1$-st cyclist.\n\nIn addition, he wants to know the answer for each $1\\le i \\le n$, $[a_1, a_2, \\ldots, a_i]$ as the original array. The problems of different $i$ are independent. To be more specific, in the $i$-th problem, Leo starts behind the $i$-th cyclist instead of the $n$-th cyclist, and cyclists numbered $i + 1, i + 2, \\ldots, n$ are not present.",
    "tutorial": "Read the editorial for F1 first. We considered the positions that we would take $p$ to, which we assumed was $q$ and iterated $q = p, p + 1, \\ldots, n$, finding the cost for each. Property : Optimal $q$ is only $q = p$ or $q = n$. Suppose $q \\ne p$, i.e. we use $a_p$ for overtaking $p + 1$, and we used $a_i$ for overtaking $q + 1$. Then, if $a_p + 2 \\le a_i$, it is not less optimal to overtake $q + 1$ using $a_p$ as well, and if $a_i \\le a_p + 1$, it is not less optimal to overtake $q$ using $a_i$. Thus, $q$ is only ever the \"edges\" of the ranges , i.e. $p$ or $n$. Now, let $p_1$ be the first minima in $a[1, n]$, then $p_2$ be the first minima in $a[p_1 + 1, n]$, $p_3$ be the first minima in $a[p_2 + 1, n]$, and so on. Let $q_i =$ where $p_i$ is taken to for each $i$. Due to the above property, we can see that the optimal strategy is : for some $x$, $q_x = n$ and $q_i = p_i$ for $i < x$, i.e. choose to take some index $p_x$ to $n$, and the previous indices do not move. We get a $O(n)$ solution for a single array by trying all values of $x$. But, we need to answer prefix queries. Note that each option of $x$ gives a linear equation in the length of the array. And appending an element to the end of the array adds at most $1$ extra option for $x$. We can maintain all the linear equations in a CHT/Lichao tree and find the minimum each time. It can be proven that only $min(a) \\le a_i \\le min(a) + 20$ need to be considered, and we will never overtake using a larger value. This property gives us simpler solutions in $O(n \\cdot 20)$ with $0$ data structures. Assume $min(a) = 1$. Let $L_i$ denote the number of overtakes using the value $i$, and we use values $1, 2 \\ldots, k$. Then, it is easy to see the indices $1, 2, \\ldots, L_1$ will be overtaken with $1$, after that $L_1 + 1, L_1 + 2, \\ldots, L_2$ will be overtaken with $2$ and so on. It should not be more optimal to take the value $i$ to cover the entire suffix, and so this gives us additional constraints of the form (by calculating the difference of costs in the current way, and the modified way) $2 \\cdot (L_{i + 1} + L_{i + 2} + \\ldots + L_k) > L_{i + 1} \\cdot 1 + L_{i + 2} \\cdot 2 + L_{i + 3} \\cdot 3 + \\ldots$. This simplies to $L_{i + 1} \\ge L_{i + 3} + 2 \\cdot L_{i + 4} + \\ldots$. Because of $L_{i + 1} \\ge 2 \\cdot L_{i + 4}$, we get a bound of $3 \\cdot log_2(n)$, but the exact bound can be computed by a greedy approach.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define int long long\n#define INF (int)1e18\n\n#define inf 1e18\n#define ld long double\n\nmt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());\n\n \nstruct chtDynamicMin {  \n\tstruct line {\n\t\tint m, b; ld x; \n\t\tint om, ob;\n\t\tint val; bool isQuery; \n\t\tline(int _m = 0, int _b = 0, int _om = 0, int _ob = 0) {\n\t\t\tm = _m;\n\t\t\tb = _b;\n\t\t\tom = _om;\n\t\t\tob = _ob;\n\t\t\tval = 0;\n\t\t\tx = -inf;\n\t\t\tisQuery = false;\n\t\t}\n\t\t\t\n\t\t\n\t\tint eval(int x) const { return m * x + b;\t}\n\t\tbool parallel(const line &l) const { return m == l.m; }\n\t\tld intersect(const line &l) const {\n\t\t\treturn parallel(l) ? inf : 1.0 * (l.b - b) / (m - l.m);\n\t\t}\n\t\tbool operator < (const line &l) const {\n\t\t\tif(l.isQuery) return x < l.val;\n\t\t\telse return m < l.m; \n\t\t}\n\t};\n \n\tset<line> hull; \n\ttypedef set<line> :: iterator iter; \n \n\tbool cPrev(iter it) { return it != hull.begin(); }\n\tbool cNext(iter it) { return it != hull.end() && next(it) != hull.end(); }\n \n\tbool bad(const line &l1, const line &l2, const line &l3) {\n\t\treturn l1.intersect(l3) <= l1.intersect(l2); \n\t}\n\tbool bad(iter it) {\n\t\treturn cPrev(it) && cNext(it) && bad(*prev(it), *it, *next(it));\n\t}\n \n\titer update(iter it) {\n\t\tif(!cPrev(it)) return it; \n\t\tld x = it -> intersect(*prev(it));\n\t\tline tmp(*it); tmp.x = x;\n\t\tit = hull.erase(it); \n\t\treturn hull.insert(it, tmp);\n\t}\n    \n\tvoid addLine(int m, int b) { \n\t\tint om = m, ob = b;\n\t\tm *= -1;\n\t\tb *= -1;\n\t\tline l(m, b, om, ob); \n\t\titer it = hull.lower_bound(l); \n\t\tif(it != hull.end() && l.parallel(*it)) {\n\t\t\tif(it -> b < b) it = hull.erase(it); \n\t\t\telse return;\n\t\t}\n \n\t\tit = hull.insert(it, l); \n\t\tif(bad(it)) return (void) hull.erase(it);\n \n\t\twhile(cPrev(it) && bad(prev(it))) hull.erase(prev(it));\n\t\twhile(cNext(it) && bad(next(it))) hull.erase(next(it));\n \n\t\tit = update(it);\n\t\tif(cPrev(it)) update(prev(it));\n\t\tif(cNext(it)) update(next(it));\n\t}\n \n\tint query(int x) const { \n\t\tif(hull.empty()) return inf;\n\t\tline q; q.val = x, q.isQuery = 1;\n\t\titer it = --hull.lower_bound(q);\n\t\treturn - it -> eval(x);\n\t}\n};\n\nvoid Solve() \n{\n    int n; cin >> n;\n    \n    // insert lines and calculate CHT \n    chtDynamicMin cht;\n    \n    vector <int> a(n + 1);\n    for (int i = 1; i <= n; i++){\n        cin >> a[i];\n    }\n    \n    vector <int> pv(n + 1, 0);\n    // previous smaller \n    stack <pair<int, int>> st;\n    for (int i = n; i >= 1; i--){\n        while (!st.empty() && st.top().first >= a[i]){\n            pv[st.top().second] = i;\n            st.pop();\n        }\n        \n        st.push({a[i], i});\n    }\n    \n    vector <int> dp(n + 1, 0);\n    \n    for (int i = 1; i <= n; i++){\n        dp[i] = dp[pv[i]] + a[i] * (i - pv[i]) + (i - pv[i] - 1);\n        // slope is +2 + a[i] \n        // constant - slope * i  \n        int m = 2 + a[i];\n        int c = dp[i] - m * i;\n        cht.addLine(m, c);\n        \n        int ans = cht.query(i);\n        cout << ans << \" \\n\"[i == n];\n    }\n}\n\nint32_t main() \n{\n    auto begin = std::chrono::high_resolution_clock::now();\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    int t = 1;\n    // freopen(\"in\",  \"r\", stdin);\n    // freopen(\"out\", \"w\", stdout);\n    \n    cin >> t;\n    for(int i = 1; i <= t; i++) \n    {\n        //cout << \"Case #\" << i << \": \";\n        Solve();\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);\n    cerr << \"Time measured: \" << elapsed.count() * 1e-9 << \" seconds.\\n\"; \n    return 0;\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "greedy"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2108",
    "index": "A",
    "title": "Permutation Warm-Up",
    "statement": "For a permutation $p$ of length $n$$^{\\text{∗}}$, we define the function:\n\n$$ f(p) = \\sum_{i=1}^{n} \\lvert p_i - i \\rvert $$\n\nYou are given a number $n$. You need to compute how many \\textbf{distinct} values the function $f(p)$ can take when considering \\textbf{all possible} permutations of the numbers from $1$ to $n$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "Let's start with $p = [1, 2, 3,  \\dots , n]$. For this $p$, $f(p) = 0$. Let's move $n$ to the beginning one position at a time. It's easy to see that we increase the answer by $2$ at each step. Now, let's move $n - 1$ to position $2$, then $n - 2$ to position $3$, and so on, until we reach $p = [n, n - 1,  \\dots , 2, 1]$. For this $p$, $f(p) = \\lfloor \\frac{n^2}{2} \\rfloor$. While doing this, we obtained every even value from $0$ to $\\lfloor \\frac{n^2}{2} \\rfloor$, since we were adding $+2$ at each step. Let's prove that we can't get any other values. First of all, it's easy to see that we can't obtain a value less than $0$ or greater than $\\lfloor \\frac{n^2}{2} \\rfloor$. Second, we can only obtain even values, because each swap changes the answer by an even number. So the answer is $\\lfloor \\frac{n^2}{4} \\rfloor + 1$ Time complexity : $\\text{O}(1)$.",
    "code": "#include <iostream>\n#include <vector>\nusing namespace std;\ntypedef long long int ll;\n#define SPEEDY std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0);\n#define forn(i, n) for (ll i = 0; i < ll(n); ++i)\n\nvoid solution(){\n    ll n;cin>>n;\n    ll k=n/2;\n    if (n%2){cout<<k*(k+1)+1;return;}\n    cout<<k*k+1;\n}\n\nint main() {\n    SPEEDY;\n    int t; cin>>t;\n    while (t--){\n        solution();\n        cout << '\\n';\n    } return 0;\n}\n",
    "tags": [
      "combinatorics",
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2108",
    "index": "B",
    "title": "SUMdamental Decomposition",
    "statement": "On a recent birthday, your best friend Maurice gave you a pair of numbers $n$ and $x$, and asked you to construct an array of \\textbf{positive} numbers $a$ of length $n$ such that $a_1 \\oplus a_2 \\oplus \\cdots \\oplus a_n = x$ $^{\\text{∗}}$.\n\nThis task seemed too simple to you, and therefore you decided to give Maurice a return gift by constructing an array among all such arrays that has the smallest sum of its elements. You immediately thought of a suitable array; however, since writing it down turned out to be too time-consuming, Maurice will have to settle for just the sum of its elements.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$\\oplus$ denotes the bitwise XOR operation.\n\\end{footnotesize}",
    "tutorial": "Let $x > 1$, and let $c$ denote the number of 1-bits in its binary representation. Clearly, when $n \\le c$, it is optimal to simply distribute distinct powers of two across the elements of the array, resulting in the minimum achievable sum of $x$. If, however, $n > c$, then it is obviously beneficial to add only ones to the extra $n - c$ elements. In the case where $n - c$ is odd, we will also need to add one more one to one of the $c$ blocks with powers of two so that the $\\text{XOR}$ of all ones equals $x$ $\\text{mod}$ $2$. If $x = 1$, then for odd $n$ we can clearly just fill all array elements with ones. Otherwise, we need to use the pair $[2, 3]$, whose $\\text{XOR}$ is $1$, resulting in the minimum score of $n + 3$. In the remaining case of $x = 0$, the situation is nearly identical to the previous one, with the exception that no valid example exists for $n = 1$ (this is the only case with an answer of $-1$). So for even $n$, the answer is simply $n$, and otherwise it's $n + 3$ (since we use the triple $1 \\oplus 2 \\oplus 3 = 0$). The time complexity is $\\text{O}(1)$ per test.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int ll;\n\nvoid solution(){\n    int n,x;cin>>n>>x;\n    int bits=__builtin_popcountll(x);\n    if (n<=bits){cout<<x;return;}\n    if ((n-bits)%2==0)cout<<x+n-bits;\n    else{\n        if (x>1){cout<<x+n-bits+1;return;}\n        if (x==1){cout<<n+3;return;}\n        else{\n            if (n==1){cout<<-1;return;}\n            else cout<<n+3;\n        }\n    }\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n    cout.tie(nullptr);\n    int t=1; \n    cin>>t;\n    while (t--){\n        solution();\n        cout << '\\n';\n    } return 0;\n}\n",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2108",
    "index": "C",
    "title": "Neo's Escape",
    "statement": "Neo wants to escape from the Matrix. In front of him are $n$ buttons arranged in a row. Each button has a weight given by an integer: $a_1, a_2, \\ldots, a_n$.\n\nNeo is immobilized, but he can create and move clones. This means he can perform an unlimited number of actions of the following two types in any order:\n\n- Create a clone in front of a specific button.\n- Move an existing clone one position to the left or right.\n\nAs soon as a clone is in front of another button that has not yet been pressed—regardless of whether he was created or moved — he \\textbf{immediately} presses it. If the button has already been pressed, a clone does nothing — buttons can only be pressed once.\n\nFor Neo to escape, he needs to press \\textbf{all} the buttons in such an order that the sequence of their weights is \\textbf{non-increasing} — that is, if $b_1, b_2, \\ldots, b_n$ are the weights of the buttons in the order they are pressed, then it must hold that $b_1 \\geq b_2 \\geq \\cdots \\geq b_n$.\n\nYour task is to determine the minimum number of clones that Neo needs to create in order to press all the buttons in a valid order.",
    "tutorial": "Note that consecutive buttons with the same weight do not affect the result, so we will keep only one of them in such sequences. In the resulting array, we find peaks (local maxima - elements that are strictly greater than both of their neighbors). The number of such peaks is the answer, because: - Each peak is separated from others by smaller elements. Therefore, the only way to reach a peak is by creating a clone there. - If a button was visited, we can return to it. - Any element other than a peak can be reached from a larger neighbor, since we have already visited it. Thus, creating clones in all other elements is not necessary. Complexity: $\\text{O}(n)$",
    "code": "#include <iostream>\n#include <vector>\n \nusing namespace std;\n \nint main() {\n    int tt = 1;\n    cin >> tt;\n    while(tt--){\n        int n; cin >> n;\n        vector<int> a;\n        a.push_back(-1e9);\n        for (int i = 0; i < n; i++){\n            int x; cin >> x;\n            if (a.back() == x);\n            else a.push_back(x);\n        }\n        a.push_back(-1e9);\n        \n        int ans = 0;\n        for (int i = 1; i < a.size() - 1; i++) \n            if (a[i - 1] < a[i] && a[i] > a[i + 1]) ans++;\n \n        cout << ans << endl;\n    }\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "dsu",
      "graphs",
      "greedy",
      "implementation"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2108",
    "index": "D",
    "title": "Needle in a Numstack",
    "statement": "This is an interactive problem.\n\nYou found the numbers $k$ and $n$ in the attic, but lost two arrays $A$ and $B$.\n\nYou remember that:\n\n- $|A| + |B| = n$, the total length of the arrays is $n$.\n- $|A| \\geq k$ and $|B| \\geq k$, the length of each array is at least $k$.\n- The arrays consist only of numbers from $1$ to $k$.\n- If you take any $k$ consecutive elements from array $A$, they will all be different. Also, if you take any $k$ consecutive elements from array $B$, they will all be different.\n\nFortunately, a kind spirit that settled in the attic found these arrays and concatenated them into an array $C$ of length $n$. That is, the elements of array $A$ were first written into array $C$, followed by the elements of array $B$.\n\nYou can ask the kind spirit up to $250$ questions. Each question contains an index $i$ ($1 \\leq i \\leq n$). In response, you will receive the $i$-th element of the concatenated array $C$.\n\nYou need to find the lengths of arrays $A$ and $B$, or report that it is impossible to determine them uniquely.",
    "tutorial": "Let $k = 4$ and the following array is guessed: [ 2 4 3 1 2 4 3 1 2 1 3 2 4 1 3 2 4 1 ] For clarity, let's divide it into groups of $k$ elements: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 ] By statement, the lengths of the left and right sides are at least $k$. Let's request the left $k$ and right $k$ elements. We will mark all the elements of the left array in red, and all the elements of the right array in blue: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 ] Let's add two numbers to our array on the right (for clarity of permutations): [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 3 2 ] We got the permutations in a \"normalized\" form: $[2, 4, 3, 1]$ and $[4, 1, 3, 2]$. Let's take any position where the elements in the permutations differ. Let it be the second position. Note all the elements at the selected positions in the guessed array: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 3 2 ] Among them, we find boundary elements via binary search for $\\log\\frac{n}{k}$ queries: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 3 2 ] Next, consider the segment between these boundary elements: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 3 2 ] We are not interested in positions that match in both permutations (in our case, this is only the third position). Let's discard the elements in these positions: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 3 2 ] Using binary search, we find the boundary elements for $\\log k$ queries: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 3 2 ] If there are \"no-man's land\" between the boundary elements, then there is no single solution and we output $-1$. In our case, there are no such elements, the problem is solved: [ 2 4 3 1 ] [ 2 4 3 1 ] [ 2 1 3 2 ] [ 4 1 3 2 ] [ 4 1 ] Total complexity: $2k + \\log\\frac{n}{k} + \\log k$ queries.",
    "code": "#include <cstdio>\n#include <cstdlib>\n#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))\n#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))\ntypedef long long l;\n\nl a[55], b[55], ui[55];\n\nl ask(l v) {\n    printf(\"? %lld\\n\", v + 1);\n    fflush(stdout);\n    l t; scanf(\"%lld\", &t);\n    return t;\n}\n\nvoid noans() {\n    printf(\"! -1\\n\");\n    fflush(stdout);\n}\n\nvoid ans(l a, l b) {\n    printf(\"! %lld %lld\\n\", a, b);\n    fflush(stdout);\n}\n\nvoid solve() {\n    l n, k; scanf(\"%lld %lld\", &n, &k);\n\n    for (l i = 0; i < k; ++i) a[i] = ask(i);\n    for (l i = n - k; i < n; ++i) b[i % k] = ask(i);\n\t\n    l uc = 0;\n    for (l i = 0; i < k; ++i) if (a[i] != b[i]) ui[uc++] = i;\n    \n    if (!uc) {\n        if (n == k * 2) ans(k, k);\n        else noans();\n        return;\n    }\n    \n    l le = ui[0], ri = ui[0] + (n - 1) / k * k;\n    while (le + k != ri) {\n        l mid = le + (ri - le) / k / 2 * k;\n        if (ask(mid) == a[ui[0]]) le = mid;\n        else ri = mid;\n    }\n    \n    l lee = 0, rii = uc;\n    while (lee + 1 != rii) {\n        l mid = (lee + rii) / 2;\n        if (ask(le - ui[0] + ui[mid]) == a[ui[mid]]) lee = mid;\n        else rii = mid;\n    }\n    \n    l pos1 = MAX(le - ui[0] + ui[lee], k - 1);\n    l pos2 = MIN(le - ui[0] + ((rii == uc) ? (ui[0] + k) : ui[rii]), n - k);\n    \n    if (pos1 + 1 != pos2) { noans(); return; }\n    ans(pos2, n - pos2);\n}\n\nint main() {\n    l t; scanf(\"%lld\", &t);\n    while (t--) solve();\n}\n",
    "tags": [
      "binary search",
      "brute force",
      "implementation",
      "interactive"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2108",
    "index": "E",
    "title": "Spruce Dispute",
    "statement": "It's already a hot April outside, and Polycarp decided that this is the perfect time to finally take down the spruce tree he set up several years ago. As he spent several hours walking around it, gathering his strength, he noticed something curious: the spruce is actually a tree$^{\\text{∗}}$ — and not just any tree, but one consisting of an \\textbf{odd} number of vertices $n$. Moreover, on $n-1$ of the vertices hang Christmas ornaments, painted in exactly $\\frac{n-1}{2}$ distinct colors, with exactly two ornaments painted in each color. The remaining vertex, as tradition dictates, holds the tree's topper.\n\nAt last, after several days of mental preparation, Polycarp began dismantling the spruce. First, he removed the topper and had already started taking apart some branches when suddenly a natural question struck him: how can he remove one of the tree's edges and rearrange the ornaments in such a way that the sum of the lengths of the simple paths between ornaments of the same color is as large as possible?\n\nIn this problem, removing an edge from the tree is defined as follows: choose a pair of adjacent vertices $a$ and $b$ ($a < b$), then remove vertex $b$ from the tree and reattach all of $b$'s adjacent vertices (except for $a$) directly to $a$.\n\nPolycarp cannot continue dismantling his spruce until he gets an answer to this question. However, checking all possible options would take him several more years. Knowing your experience in competitive programming, he turned to you for help. But can you solve this dispute?\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles.\n\\end{footnotesize}",
    "tutorial": "Let's assume we have already removed one of the edges from the original tree. Then, we are left with a tree containing an even number of vertices, namely $n - 1$. Note that the maximum possible sum of distances between same-colored balls in this tree will be achieved if, for every edge, all vertices in its smaller subtree are of different colors. In that case, the edge will contribute the maximum possible number of times to the answer - specifically, $\\min(a, b)$, where $a$ and $b$ are the sizes of the subtrees connected by this edge (since, obviously, no more paths can pass through this edge). Great - now let's root our tree at its centroid, which is a vertex that splits the tree into subtrees whose sizes do not exceed half of the total size. It can be proven that such a vertex always exists in any tree (and if there are two such vertices, we can pick either). Now, let's divide all vertices into groups based on which child subtree of the centroid they belong to, adding the centroid itself to the smallest group. Notice that the sizes of all groups still do not exceed $\\frac{n - 1}{2}$. Therefore, we can pair up the vertices in such a way that each pair contains vertices from different groups. This can be done greedily using a heap in $O(n \\log n)$, or by running DFS from the centroid and coloring vertices modulo $\\frac{n - 1}{2}$ (clearly, with this method, no group will have two vertices of the same color), which has complexity $O(n)$. Thus, we are left to determine which edge we should remove so that the total sum of the minimal subtree sizes across all edges in the original tree decreases as little as possible. Note that, since initially the tree has an odd number of vertices, its centroid is uniquely defined and will not change no matter which edge we remove. At the same time, since all paths pass through the centroid, the total sum of their lengths can be rewritten as the sum of distances to the centroid. Now, let's make two observations: It is more beneficial to remove a leaf than any other type of vertex. Among all leaves, it is best to remove the one closest to the centroid. The second observation follows directly from the first and the earlier remark, so we only need to justify the first one. But this is fairly obvious: when we remove an edge, besides subtracting the depth of its nearest vertex, we also decrease the depths of all vertices in its subtree by one. Therefore, it will always be better to remove deeper edges rather than shallower ones. As a result, after finding the centroid in $O(n)$, we get an overall complexity of $O(n \\log n)$ (if we use a heap) or $O(n)$.",
    "code": "#include <cstdio>\n#include <vector>\n\n#define S 200005\n\nusing namespace std;\ntypedef long long l;\n\nl coloring[S], centroid, best, best_dist, n, color;\nvector<vector<l>> g;\n\nl search_centroid(l u, l from) {\n  l sum = 0;\n  bool f = true;\n  for (l v : g[u]) if (v != from) {\n    l t = search_centroid(v, u);\n    if (t > n / 2) f = false;\n    sum += t;\n  }\n  \n  if (f && n - 1 - sum <= n / 2) centroid = u;\n  return sum + 1;\n}\n\nvoid make_coloring(l u, l from, l dist) {\n  coloring[u] = (color++) % (n / 2) + 1;\n  if (g[u].size() == 1 && dist < best_dist) {\n    best_dist = dist;\n    best = u;\n  }\n  for (l v : g[u]) if (v != from)\n    make_coloring(v, u, dist + 1);\n}\n\nvoid solve() {\n  centroid = -1, best_dist = S, color = 0;\n  scanf(\"%lld\", &n);\n  g.assign(n, vector<l>());\n  for (l i = 0; i < n - 1; ++i) {\n    l u, v; scanf(\"%lld %lld\", &u, &v); --u, --v;\n    g[u].push_back(v); g[v].push_back(u);\n  }\n  \n  search_centroid(1543 % n, -1);\n  make_coloring(centroid, -1, 0);\n  \n  l bbest = max(best, g[best][0]);\n  coloring[centroid] = coloring[bbest];\n  coloring[bbest] = 0;\n  \n  printf(\"%lld %lld\\n\", best + 1, g[best][0] + 1);\n  for (l i = 0; i < n; ++i) {\n    if (i) printf(\" \");\n    printf(\"%lld\", coloring[i]);\n  }\n  printf(\"\\n\");\n}\n\nint main() {\n  l tc; scanf(\"%lld\", &tc);\n  while (tc--) solve();\n}\n",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "greedy",
      "implementation",
      "shortest paths",
      "trees"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2108",
    "index": "F",
    "title": "Fallen Towers",
    "statement": "Pizano built an array $a$ of $n$ towers, each consisting of $a_i \\ge 0$ blocks.\n\nPizano can knock down a tower so that the next $a_i$ towers grow by $1$. In other words, he can take the element $a_i$, increase the next $a_i$ elements by one, and then set $a_i$ to $0$. The blocks that fall outside the array of towers disappear. If Pizano knocks down a tower with $0$ blocks, nothing happens.\n\nPizano wants to knock down all $n$ towers in any order, \\textbf{each exactly once}. That is, for each $i$ from $1$ to $n$, he will knock down the tower at position $i$ exactly once.\n\nMoreover, the resulting array of tower heights \\textbf{must be non-decreasing}. This means that after he knocks down all $n$ towers, for any $i < j$, the tower at position $i$ must not be taller than the tower at position $j$.\n\nYou are required to output the maximum $\\text{MEX}$ of the resulting array of tower heights.\n\nThe $\\text{MEX}$ of an array is the smallest non-negative integer that is not present in the array.",
    "tutorial": "It can be shown that for any array $A$ obtained after collapsing all $n$ towers, we can also obtain any other array $B$ whose elements do not exceed the elements of $A$. A strict formal proof is provided in the spoiler below; here is a brief explanation. Suppose $k$ blocks fell onto the $i$-th tower over the entire process. Then, for its height in the final array to be $A_i$, $A_i$ blocks must have fallen after its collapse, while the remaining $k - A_i$ blocks fell before. Thus, we can always rearrange the order in which the towers collapse so that its height becomes $B_i \\leq A_i$. In other words, we ensure that $B_i$ blocks fall onto the $i$-th tower after its collapse, and $k - B_i$ fall before. From this claim about the possibility of obtaining a smaller array, two facts follow: For any answer $\\text{MEX} = x$, we can also obtain the answer $x - 1$. This means we can apply binary search on the answer. For any answer $\\text{MEX} = x$, we can also obtain the answer $x - 1$. This means we can apply binary search on the answer. For any answer $\\text{MEX} = x$, we can achieve it in the form $[0, 0, 0, 0, \\ldots, 1, 2, 3, \\ldots, x - 1]$. Thus, at each iteration of the binary search, we need to check the possibility of obtaining such an array. To do this, we traverse the towers from left to right, tracking the number of cubes that fall onto each tower at some point and collapsing each tower after the required number of cubes have fallen onto it. The most efficient way to track the number of cubes is using the scanline method. For any answer $\\text{MEX} = x$, we can achieve it in the form $[0, 0, 0, 0, \\ldots, 1, 2, 3, \\ldots, x - 1]$. Thus, at each iteration of the binary search, we need to check the possibility of obtaining such an array. To do this, we traverse the towers from left to right, tracking the number of cubes that fall onto each tower at some point and collapsing each tower after the required number of cubes have fallen onto it. The most efficient way to track the number of cubes is using the scanline method. In total, there are $\\text{O}(\\log n)$ iterations in the binary search over the answer and $\\text{O}(n)$ operations per iteration. The final complexity is $\\text{O}(n \\log n)$. Let the array $a$ of length $n$ be some input data for the problem. Let $r$ and $r'$ be arrays of length $n$ such that $\\forall i : 0 \\leq r'_i \\leq r_i$. Assertion 1: Suppose there exists a permutation $p$ such that the tower with index $i$ collapses $p_i$-th in order, resulting in the array $r$. Then, there exists a permutation $p'$ such that the tower with index $i$ collapses $p'_i$-th in order, resulting in the array $r'$. $\\square$ Let $s_i$ be the total number of towers that ever fell onto position $i$ when collapsing the towers in the order $p$. Note that out of these, $r_i$ towers were collapsed later than the $i$-th, and the rest were collapsed earlier. The height of the $i$-th tower at the moment of its collapse is $a_i + (s_i - r_i)$. Inductive hypothesis: There exists a permutation $p^{(k)}$ of numbers from $1$ to $k \\leq n$ such that if the $i$-th tower is collapsed $p^{(k)}_i$-th in order, then: The resulting height at the $i$-th position will be $r'_i$. The resulting height at the $i$-th position will be $r'_i$. The number (denoted as $s^{(k)}_i$) of towers that fell onto position $i$ when collapsing the towers in the order $p^{(k)}$ is greater than or equal to $s_i$. The number (denoted as $s^{(k)}_i$) of towers that fell onto position $i$ when collapsing the towers in the order $p^{(k)}$ is greater than or equal to $s_i$. Base case: The permutation $p^{(1)} = [1]$. After collapsing, the tower's height becomes $0$, so $r'_1 = r_1 = 0$ in any resulting array. $s^{(1)}_1 = s_1 = 0$. Inductive step: Suppose the permutation $p^{(k - 1)}$ exists. We prove the existence of $p^{(k)}$. $\\forall i \\leq k - 1$, the height of the $i$-th tower at the moment of collapse under the order $p^{(k - 1)}$ is no less than under the order $p$: $(s^{(k - 1)}_i \\geq s_i \\land r'_i \\leq r_i) ~~~ \\Longrightarrow ~~~ a_i + (s^{(k - 1)}_i - r'_i) \\geq a_i + (s_i - r_i)$ From this, it follows that when collapsing in the order $p^{(k - 1)}$, at least $s_k$ towers will fall onto position $k$ (let their count be $x \\geq s_k \\geq r'_k$). This is because the heights at the moment of collapse for all towers $i < k$ have either remained the same or increased. If $x > r'_k$, let tower $j$ be the $(x - r'_k)$-th tower among those that fell onto position $k$. Then, collapse tower $k$ immediately after tower $j$. If $x = r'_k$, collapse tower $k$ first. In both cases, after collapsing $k$, $r'_k$ towers will fall onto it, and its height will become $r'_k$. Formally, for $x > r'_k$, the permutation $p^{(k)}$ is constructed as follows: $\\forall i < k : p^{(k - 1)}_i \\leq p^{(k - 1)}_j \\Rightarrow p^{(k)}_i = p^{(k - 1)}_i$ $\\forall i < k : p^{(k - 1)}_i \\leq p^{(k - 1)}_j \\Rightarrow p^{(k)}_i = p^{(k - 1)}_i$ $p^{(k)}_k = p^{(k - 1)}_j + 1$ $p^{(k)}_k = p^{(k - 1)}_j + 1$ $\\forall i < k : p^{(k - 1)}_i > p^{(k - 1)}_j \\Rightarrow p^{(k)}_i = p^{(k - 1)}_i + 1$ $\\forall i < k : p^{(k - 1)}_i > p^{(k - 1)}_j \\Rightarrow p^{(k)}_i = p^{(k - 1)}_i + 1$ For $x = r'_k$: $p^{(k)}_k = 1$ $p^{(k)}_k = 1$ $\\forall i < k : p^{(k)}_i = p^{(k - 1)}_i + 1$ $\\forall i < k : p^{(k)}_i = p^{(k - 1)}_i + 1$ The array $s^{(k)}$ is constructed as $\\forall i < k : s^{(k)}_i = s^{(k - 1)}_i$ and $s^{(k)}_k = x$. The induction is proven. Thus, we set $p' = p^{(n)}$, and the assertion is proven. $\\blacksquare$ Corollary 1: If we can obtain $\\text{MEX}(r) > 0$ as the answer to the problem for the resulting array $r$, then we can also obtain $\\text{MEX}(r) - 1$ as the answer to the problem. $\\square$ Set $r'_i = \\max(0, r_i - 1)$. Then, by Assertion 1, $r'$ can be obtained as the resulting array. $\\text{MEX}(r') = \\text{MEX}(r) - 1$. $\\blacksquare$ Corollary 2: If we can obtain $\\text{MEX}(r)$ as the answer to the problem for the resulting array $r$, then we can obtain $\\text{MEX}(r') = \\text{MEX}(r)$ for the resulting array $r'$, where $r'_i = \\max(0, (\\text{MEX}(r) - 1) - (n - i))$. $\\square$ By Assertion 1, $r'$ can be obtained as the resulting array. $\\blacksquare$ We can perform binary search on the answer (from Corollary 1), and at each iteration, when checking the answer $x$, verify whether we can obtain the resulting array $r$ of the form $r_i = \\max(0, (x - 1) - (n - i))$ (from Corollary 2).",
    "code": "#include <cstdio>\n#include <algorithm>\n#include <cstring>\n\n#define S 100005\n\ntypedef long long l;\n \nl a[S], d[S], n;\n\nbool check(l ans) {\n    memset(d, 0, sizeof(l) * n);\n    l acc = 0;\n    \n    for (l i = 0; i < n; ++i) {\n        acc -= d[i];\n        \n        l need = std::max(0LL, i - (n - ans));\n        if (acc < need) return false;\n        \n        l end = i + a[i] + (acc++) - need + 1;\n        if (end < n) ++d[end];\n    }\n    \n    return true;\n}\n\nvoid solve() {\n    scanf(\"%lld\", &n);\n    for (l i = 0; i < n; ++i) scanf(\"%lld\", &a[i]);\n    \n    l le = 1, ri = n + 1, mid;\n    while (ri - le > 1) {\n        mid = (le + ri) / 2;\n        if (check(mid)) le = mid;\n        else ri = mid;\n    }\n    \n    printf(\"%lld\\n\", le);\n}\n\nint main() {\n    l tc; scanf(\"%lld\", &tc);\n    while (tc--) solve();\n}\n",
    "tags": [
      "binary search",
      "greedy"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2109",
    "index": "A",
    "title": "It's Time To Duel",
    "statement": "Something you may not know about Mouf is that he is a big fan of the Yu-Gi-Oh! card game. He loves to duel with anyone he meets. To gather all fans who love to play as well, he decided to organize a big Yu-Gi-Oh! tournament and invited $n$ players.\n\nMouf arranged the $n$ players in a line, numbered from $1$ to $n$. They then held $n - 1$ consecutive duels: for each $i$ from $1$ to $n - 1$, player $i$ faced player $i + 1$, producing one winner and one loser per match. Afterward, each player reports a value $a_i(0 \\le a_i \\le 1)$:\n\n- $0$ indicating they won no duels;\n- $1$ indicating they won at least one duel.\n\nSince some may lie about their results (e.g., reporting a $1$ instead of a $0$, or vice versa) to influence prize outcomes, Mouf will cancel the tournament if he can prove any report to be false.\n\nGiven the array $a$, determine whether at least one player must be lying.",
    "tutorial": "What can you say when every player has reported a win? A report array can be genuine only if it meets both of these conditions: There must be at least one player who reported $0$ - there are $n - 1$ duels and $n$ players. There cannot be two adjacent players who both reported $0$ - one of them must have won the duel between them. If either condition fails, the answer is YES (there is definitely a liar); otherwise, the answer is NO.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n\n    if (accumulate(a.begin(), a.end(), 0) == n) {\n        cout << \"YES\" << \"\\n\";\n        return;\n    }\n\n    for (int i = 0; i < n - 1; i++) if (!a[i] && !a[i + 1]) {\n        cout << \"YES\" << \"\\n\";\n        return;\n    }\n\n    cout << \"NO\" << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2109",
    "index": "B",
    "title": "Slice to Survive",
    "statement": "Duelists Mouf and Fouad enter the arena, which is an $n \\times m$ grid!\n\nFouad's monster starts at cell $(a, b)$, where rows are numbered $1$ to $n$ and columns $1$ to $m$.\n\nMouf and Fouad will keep duelling until the grid consists of only one cell.\n\nIn each turn:\n\n- Mouf first cuts the grid along a row or column line into two parts, discarding the part without Fouad's monster. Note that the grid must have at least two cells; otherwise, the game has already ended.\n- After that, in the same turn, Fouad moves his monster to any cell (possibly the same one it was in) within the remaining grid.\n\n\\begin{center}\n{\\small Visualization of the phases of the fourth test case.}\n\\end{center}\n\nMouf wants to minimize the number of turns, while Fouad wants to maximize them. How many turns will this epic duel last if both play optimally?",
    "tutorial": "What changes if the turn order is reversed - starting with Fouad's move before Mouf's cut? Can the row and column dimensions be treated independently, or do they interact? How might that influence your approach? We restructure the game by grouping each move (Fouad's move) with the following cut (Mouf's cut). After Mouf performs his initial cut, each combined turn consists of Fouad first moving to any remaining cell, followed by Mouf cutting the grid. Now, let's temporarily set aside the initial cut and focus on the state of the grid just before Fouad's first move in this new structure. Suppose the remaining Grid has dimensions $n' \\times m'$. Since each cut affects only one dimension, we can handle the row and column reductions independently. Thus, the number of required turns is: $f(n') + f(m')$ where $f(l)$ denotes the number of turns required to reduce a $1 \\times l$ grid to a single cell. The function $f(l)$ can be defined recursively as: $f(l) = \\begin{cases} 0 & l = 1, \\\\ 1 + \\max\\limits_{1 \\le i \\le l} \\min(f(i), f(l - i + 1)) & l > 1. \\end{cases}$ Given that $f$ is non-decreasing, the minimum between $f(i)$ and $f(l - i + 1)$ is maximized when $i = \\left\\lfloor \\frac{l}{2} \\right\\rfloor$. Thus, we simplify the recurrence as: $f(l) = 1 + f\\left(\\left\\lceil \\frac{l}{2} \\right\\rceil \\right)$ Now returning to the initial cut, note that it is in Mouf's best interest to minimize $n'$ and $m'$ since $f$ is non-decreasing. To do so, he should ensure Fouad ends up on the boundary of the remaining grid after the first cut. This yields four possible configurations: $(n', m') \\in S = \\{ (a, m),\\ (n - a + 1, m),\\ (n, b),\\ (n, m - b + 1) \\}$ The total number of turns, including the initial cut, is: $\\text{ans} = 1 + \\min\\limits_{(n', m') \\in S} \\left[ f(n') + f(m') \\right]$ The overall time complexity is: $O(\\log(n) + \\log(m))$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n, m, a, b;\n    cin >> n >> m >> a >> b;\n\n    vector<pair<int, int>> rec({\n    make_pair(a, m), make_pair(n - a + 1, m),\n    make_pair(n, b), make_pair(n, m - b + 1)});\n\n    int ans = n + m;\n    for (auto [n1, m1] : rec) {\n        int res = 0;\n        while (n1 > 1) {\n            ++res;\n            n1 = (n1 + 1) / 2;\n        }\n        while (m1 > 1) {\n            ++res;\n            m1 = (m1 + 1) / 2;\n        }\n        ans = min(ans, res);\n    }\n\n    cout << 1 + ans << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "greedy",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2109",
    "index": "C1",
    "title": "Hacking Numbers (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. In this version, you can send at most $\\mathbf{7}$ commands. You can make hacks only if all versions of the problem are solved.}\n\nThis is an interactive problem.\n\nWelcome, Duelists! In this interactive challenge, there is an unknown integer $x$ ($1 \\le x \\le 10^9$). You must make it equal to a given integer in the input $n$. By harnessing the power of \"Mathmech\" monsters, you can send a command to do one of the following:\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||l||l||c|}\n\\hline\n\\textbf{Command} & \\textbf{Constraint} & \\textbf{Result} & \\textbf{Case} & \\textbf{Update} & \\textbf{Jury's response} \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"add $y$\"} & \\multirow{2}{*}{$-10^{18} \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x + y$} & $\\text{if } 1 \\le \\mathrm{res} \\le 10^{18}$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"mul $y$\"} & \\multirow{2}{*}{$1 \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x \\cdot y$} & $\\text{if } 1 \\le \\mathrm{res} \\le 10^{18}$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"div $y$\"} & \\multirow{2}{*}{$1 \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x/y$} & $\\text{if } y$ divides $x$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\"digit\" & — & $\\mathrm{res} = S(x)$$^{\\text{∗}}$ & — & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nYou have to make $x$ equal to $n$ using \\textbf{at most} $\\mathbf{7}$ commands.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$S(n)$ is a function that returns the sum of all the individual digits of a non-negative integer $n$. For example, $S(123) = 1 + 2 + 3 = 6$\n\\end{footnotesize}",
    "tutorial": "Figure out a way to make $x$ equal $1$, then the final command will be $\\texttt{\"add n-1\"}$. What range of values can $x$ take after the first application of the $\\texttt{\"digit\"}$ command? What about the second application of the $\\texttt{\"digit\"}$ command? Avoid overusing the $\\texttt{\"digit\"}$ command - after the second application, $x$ is limited to the range $[1, 16]$. Consider using the binary representation of $x$ instead. Apply $\\texttt{\"digit\"}$ $\\rightarrow$ $x \\in [1, 81]$. Apply $\\texttt{\"digit\"}$ $\\rightarrow$ $x \\in [1, 16]$. Apply $\\texttt{\"add -8\"}$ $\\rightarrow$ $x \\in [1, 8]$. Apply $\\texttt{\"add -4\"}$ $\\rightarrow$ $x \\in [1, 4]$. Apply $\\texttt{\"add -2\"}$ $\\rightarrow$ $x \\in [1, 2]$. Apply $\\texttt{\"add -1\"}$ $\\rightarrow$ $x$ becomes exactly $1$. Finally, apply $\\texttt{\"add n-1\"}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n\n    cout << \"digit\" << endl;\n    int x;\n    cin >> x;\n\n    cout << \"digit\" << endl;\n    cin >> x;\n\n    for (int i = 8; i >= 1; i /= 2) {\n        cout << \"add \" << -i << endl;\n        cin >> x;\n    }\n\n    cout << \"add \" << n - 1 << endl;\n    cin >> x;\n\n    cout << \"!\" << endl;\n    cin >> x;\n    assert(x == 1);\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "bitmasks",
      "constructive algorithms",
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2109",
    "index": "C2",
    "title": "Hacking Numbers (Medium Version)",
    "statement": "\\textbf{This is the medium version of the problem. In this version, you can send at most $\\mathbf{4}$ commands. You can make hacks only if all versions of the problem are solved.}\n\nThis is an interactive problem.\n\nWelcome, Duelists! In this interactive challenge, there is an unknown integer $x$ ($1 \\le x \\le 10^9$). You must make it equal to a given integer in the input $n$. By harnessing the power of \"Mathmech\" monsters, you can send a command to do one of the following:\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||l||l||c|}\n\\hline\n\\textbf{Command} & \\textbf{Constraint} & \\textbf{Result} & \\textbf{Case} & \\textbf{Update} & \\textbf{Jury's response} \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"add $y$\"} & \\multirow{2}{*}{$-10^{18} \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x + y$} & $\\text{if } 1 \\le \\mathrm{res} \\le 10^{18}$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"mul $y$\"} & \\multirow{2}{*}{$1 \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x \\cdot y$} & $\\text{if } 1 \\le \\mathrm{res} \\le 10^{18}$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"div $y$\"} & \\multirow{2}{*}{$1 \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x/y$} & $\\text{if } y$ divides $x$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\"digit\" & — & $\\mathrm{res} = S(x)$$^{\\text{∗}}$ & — & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nYou have to make $x$ equal to $n$ using \\textbf{at most} $\\mathbf{4}$ commands.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$S(n)$ is a function that returns the sum of all the individual digits of a non-negative integer $n$. For example, $S(123) = 1 + 2 + 3 = 6$\n\\end{footnotesize}",
    "tutorial": "The first command is not $\\texttt{\"digit\"}$. The first command is $\\texttt{\"mul\"}$. Combining the $\\texttt{\"mul\"}$ and $\\texttt{\"digit\"}$ commands is powerful! Consider a number that links these two commands. Recall that well-known fact from high school: a number is divisible by $9$ if and only if the sum of its digits is divisible by $9$. Apply $\\texttt{\"mul 9\"}$. Apply $\\texttt{\"digit\"}$ $\\rightarrow$ $x \\in [9, 18, 27, 36, 45, 54, 63, 72, 81]$. Apply $\\texttt{\"digit\"}$ $\\rightarrow$ $x$ becomes exactly $9$. Finally, apply $\\texttt{\"add n-9\"}$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n\n    cout << \"mul \" << 9 << endl;\n    int x;\n    cin >> x;\n\n    cout << \"digit\" << endl;\n    cin >> x;\n\n    cout << \"digit\" << endl;\n    cin >> x;\n\n    cout << \"add \" << n - 9 << endl;\n    cin >> x;\n\n    cout << \"!\" << endl;\n    cin >> x;\n    assert(x == 1);\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2109",
    "index": "C3",
    "title": "Hacking Numbers (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. In this version, the limit of commands you can send is described in the statement. You can make hacks only if all versions of the problem are solved.}\n\nThis is an interactive problem.\n\nWelcome, Duelists! In this interactive challenge, there is an unknown integer $x$ ($1 \\le x \\le 10^9$). You must make it equal to a given integer in the input $n$. By harnessing the power of \"Mathmech\" monsters, you can send a command to do one of the following:\n\n\\begin{center}\n\\begin{tabular}{|c||c||c||l||l||c|}\n\\hline\n\\textbf{Command} & \\textbf{Constraint} & \\textbf{Result} & \\textbf{Case} & \\textbf{Update} & \\textbf{Jury's response} \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"add $y$\"} & \\multirow{2}{*}{$-10^{18} \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x + y$} & $\\text{if } 1 \\le \\mathrm{res} \\le 10^{18}$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"mul $y$\"} & \\multirow{2}{*}{$1 \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x \\cdot y$} & $\\text{if } 1 \\le \\mathrm{res} \\le 10^{18}$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\\multirow{2}{*}{\"div $y$\"} & \\multirow{2}{*}{$1 \\le y \\le 10^{18}$} & \\multirow{2}{*}{$\\mathrm{res} = x/y$} & $\\text{if } y$ divides $x$ & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\hline\n& & & $\\mathrm{else}$ & $x \\leftarrow x$ & \"0\" \\\n\\hline\n\\hline\n\"digit\" & — & $\\mathrm{res} = S(x)$$^{\\text{∗}}$ & — & $x \\leftarrow \\mathrm{res}$ & \"1\" \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nLet $f(n)$ be the minimum integer such that there is a sequence of $f(n)$ commands that transforms $x$ into $n$ for all $x(1 \\le x \\le 10^9)$. You do not know the value of $x$ in advance. Find $f(n)$ such that, no matter what $x$ is, you can always transform it into $n$ using at most $f(n)$ commands.\n\nYour task is to change $x$ into $n$ using \\textbf{at most} $f(n)$ commands.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$$S(n)$ is a function that returns the sum of all the individual digits of a non-negative integer $n$. For example, $S(123) = 1 + 2 + 3 = 6$\n\\end{footnotesize}",
    "tutorial": "While $9$ connects the $\\texttt{\"mul\"}$ and $\\texttt{\"digit\"}$ commands, there may be other numbers that do so as well. Another valid solution for the medium version is as follows: $\\texttt{\"digit\"}$. $\\texttt{\"mul 99\"}$. $\\texttt{\"digit\"}$. $\\texttt{\"add n-18\"}$. But what's the reasoning behind this sequence? $S[(10^d - 1)x] = 9d \\quad \\forall x \\in [1,10^d]$. Let's prove that $S[(10^d - 1)x] = 9d \\quad \\forall x \\in [1, 10^d].$ Observe that $x \\cdot (10^d-1) = x \\cdot 10^d - x = (x - 1) \\cdot 10^d + 10^d - x = (x - 1) \\cdot 10^d + [(10^d - 1) - (x - 1)].$ The first term represents $(x - 1)$ shifted $d$ places to the left (i.e. multiplies by $10^d$). The second term is the $d$-digit string of nines minus $(x - 1)$, namely $\\underbrace{999 \\ldots 999}_{d \\text{ times}} - (x - 1).$ Therefore, for every $i$ ($1 \\le i \\le d$), the $i$-th digit of the second term and the $(i + d)$-th digit of the first term complement each other to sum to $9$. Drumroll, please! The number we're about to use is $999\\,999\\,999$. With just three commands, we can turn any $x$ into $n$: Apply $\\texttt{\"mul } 999\\,999\\,999 \\texttt{\"}$. Apply $\\texttt{\"digit\"}$ $\\rightarrow$ $x$ becomes exactly $81$. Finally, apply $\\texttt{\"add n-81\"}$. There's one special case: if $n = 81$, you only need the first two commands - meaning $f(81) = 2$. Now let's see why no other $n$ can get away with just two commands. First, note that the digit-sum function $S(i)$ always changes when you add $1$, so $S(i) \\neq S(i + 1)$. Consider your choice of first command: $\\texttt{\"add y\"}$: When $y$ is positive, it shifts the entire range of possible $x$-values. Otherwise, it shrinks the range but never cuts it down below half its size. In either case, it can't force $x$ into a single value. $\\texttt{\"div y\"}$: It fails even on small $x$-values (e.g. $1 \\le x \\le 4$) - it doesn't force a single outcome. $\\texttt{\"digit\"}$: After the first application, it only restricts $x$ to $[1, 81]$, and a second application only narrows it to $[1, 16]$. You still don't get a single fixed value. That leaves only one candidate to start with, which is $\\texttt{\"mul y\"}$. Suppose some other multiplier $y \\neq 999\\,999\\,999$ made $S(x \\cdot y)$ constant. Test it against $x = 1$ and $x = 999\\,999\\,999$: $S(1 \\cdot y) \\le 80 < 81 = S(999\\,999\\,999\\cdot y)$ They can't both be the same, so no such $y \\neq 999\\,999\\,999$ exists. Similar to the above reasoning, keeping in mind that $S(i) \\neq S(i + 1)$, the only possible second command is $\\texttt{\"digit\"}$ (as this is the only way to shrink the range, since no other command can do so). Hence, only $n = 81$ can reach a fixed result in two commands; every other $n$ requires three.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n\n    cout << \"mul 999999999\" << endl;\n    int x;\n    cin >> x;\n\n    cout << \"digit\" << endl;\n    cin >> x;\n\n    if (n != 81) {\n        cout << \"add \" << n - 81 << endl;\n        cin >> x;\n    }\n\n    cout << \"!\" << endl;\n    cin >> x;\n    assert(x == 1);\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "interactive",
      "math",
      "number theory"
    ],
    "rating": 2600
  },
  {
    "contest_id": "2109",
    "index": "D",
    "title": "D/D/D",
    "statement": "Of course, a problem with the letter D is sponsored by Declan Akaba.\n\nYou are given a simple, connected, undirected graph with $n$ vertices and $m$ edges. The graph contains no self-loops or multiple edges. You are also given a multiset $A$ consisting of $\\ell$ elements: $$ A = \\{A_1, A_2, \\ldots, A_\\ell\\} $$\n\nStarting from vertex $1$, you may perform the following move \\textbf{any number} of times, as long as the multiset $A$ is not empty:\n\n- Select an element $k \\in A$ and remove it from the multiset . You must remove exactly one occurrence of $k$ from $A$.\n- Traverse any walk$^{\\text{∗}}$ of exactly $k$ edges to reach some vertex (possibly the same one you started from).\n\nFor each $i$ ($1 \\le i \\le n$), determine whether there exists a sequence of such moves that starts at vertex $1$ and ends at vertex $i$, using the original multiset $A$.\n\nNote that the check for each vertex $i$ is independent — you restart from vertex $1$ and use the original multiset $A$ for each case.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A walk of length $k$ is a sequence of vertices $v_0, v_1, \\ldots, v_{k - 1}, v_k$ such that each consecutive pair of vertices $(v_i, v_{i + 1})$ is connected by an edge in the graph. The sequence may include repeated vertices.\n\\end{footnotesize}",
    "tutorial": "Suppose you've reached vertex $i$, what is the shortest possible sequence of moves that brings you back to $i$? At any vertex $j$ adjacent to $i$, you may take back-and-forth move $[i \\to j \\to i].$ Let us temporarily set aside the multiset $A$. Starting from vertex $1$, define ${}$ $\\mathrm{dist}[i][p] = \\min \\{ \\, \\text{length of a walk from } 1 \\text{ to } i \\mid \\text{length} \\bmod 2 = p \\, \\}, \\text{ for parity } p \\in \\{0, 1\\}.$ Since any walk of length $d$ can be extended to $d + 2$ by inserting a back-and-forth move $[i \\to j \\to i]$ at any vertex $j$ adjacent to $i$, only the minimal even and odd distances matter. By performing a breadth-first search from vertex $1$, we derive $\\mathrm{dist}$. Now reintroduce the multiset $A$ with total sum $S = \\sum A$. We would like to select a sub-multiset whose sum $S'$ satisfies both $S' \\ge \\mathrm{dist}[i][p];$ $S' \\bmod 2 = p.$ Taking all elements gives $S' = S$. Let $p = S \\bmod 2$, then any vertex with $\\mathrm{dist}[i][p] \\le S$ is reachable by a walk of parity $p$. Otherwise, we must find a suitable $S' \\bmod 2 = 1 - p$ satisfying $\\mathrm{dist}[i][1 - p] \\le S'$, and the minimal way to flip parity is to remove the smallest odd element $\\min_{\\mathrm{odd}}$ from the multiset $A$. Parity change is impossible if no such odd element exists, since removing any even element leaves the parity unchanged. Setting $S' = S - a_{\\mathrm{odd}}$, any vertex with $\\mathrm{dist}[i][1 - p] \\le S'$ is reachable by a walk of parity $1 - p$. In conclusion, vertex $i$ is attainable by a walk using the original multiset $A$ if and only if either $\\mathrm{dist}[i][p] \\le S \\text{ when } p = S \\bmod 2 \\text{, or}$ $\\mathrm{dist}[i][p] \\le S - \\min_{\\mathrm{odd}} \\text{ when } p \\neq S \\bmod 2 \\text{ and the smallest odd element } \\min_{\\mathrm{odd}} \\in A \\text{ exists.}$ The overall time complexity is: $O(n + m + \\ell)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n, m, l;\n    cin >> n >> m >> l;\n\n    int const inf = 2e9 + 1;\n    int sum = 0, min_odd = inf;\n    vector<int> a(l);\n    for (int i = 0; i < l; ++i) {\n        cin >> a[i];\n        sum += a[i];\n        if (a[i] % 2) {\n            min_odd = min(min_odd, a[i]);\n        }\n    }\n\n    vector adj(n, vector<int>());\n    for (int i = 0; i < m; ++i) {\n        int u, v;\n        cin >> u >> v;\n        --u;\n        --v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n\n    vector<array<int, 2>> dist(n, {inf, inf});\n    queue<pair<int, int>> q;\n    q.push({0, 0});\n    dist[0][0] = 0;\n    while (q.size()) {\n        auto [u, p] = q.front();\n        q.pop();\n        for (auto v : adj[u]) {\n            if (dist[v][!p] > dist[u][p] + 1) {\n                dist[v][!p] = dist[u][p] + 1;\n                q.push({v, !p});\n            }\n        }\n    }\n\n    for (int i = 0; i < n; ++i) {\n        bool found = 0;\n        for (int p = 0; p < 2; ++p) {\n            int s = sum - (p == sum % 2 ? 0 : min_odd);\n            if (dist[i][p] <= s) {\n                found = 1;\n            }\n        }\n        cout << found;\n    }\n    cout << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "greedy",
      "shortest paths"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2109",
    "index": "E",
    "title": "Binary String Wowee",
    "statement": "Mouf is bored with themes, so he decided not to use any themes for this problem.\n\nYou are given a binary$^{\\text{∗}}$ string $s$ of length $n$. You are to perform the following operation exactly $k$ times:\n\n- select an index $i$ ($1 \\le i \\le n$) such that $s_i = \\mathtt{0}$;\n- then flip$^{\\text{†}}$ each $s_j$ for all indices $j$ ($1 \\le j \\le i$).\n\nYou need to count the number of possible ways to perform all $k$ operations.\n\nSince the answer could be ginormous, print it modulo $998\\,244\\,353$.\n\nTwo sequences of operations are considered different if they differ in the index selected at any step.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A binary string is a string that consists only of the characters $\\mathtt{0}$ and $\\mathtt{1}$.\n\n$^{\\text{†}}$Flipping a binary character is changing it from $\\mathtt{0}$ to $\\mathtt{1}$ or vice versa.\n\\end{footnotesize}",
    "tutorial": "The state of $s_i$ depend entirely on how many operations have been performed on the suffix $s_i, s_{i+1}, \\ldots, s_n$. Let $dp[i][j]$ denote the number of ways to perform exactly $j$ moves on the suffix $s_i, s_{i+1}, \\ldots, s_n$. Some useful insight is to see that if you operate on an element, then every element after it will be unaffected; similarly, the state of an element in the string depends only on the number of operations used on the suffix after it. More specifically, an element's state flips with each operation applied to a suffix that includes it, so its value depends entirely on the number of operations done to its suffix. This inspires the following $dp$ state: ${}$ $dp[i][j] = \\text{the number of ways to make exactly } j \\text{ moves on the suffix only } s_i,...,s_n.$ Now, regarding transitions - the number of ways to move from state $dp[i][j]$ to $dp[i - 1][j + k]$ (in other words the number of ways to add $k$ operations at the $(i - 1)$-th index) can be thought of in terms of forming strings composed of characters $A$ and $B$, where $A$ represents making a move on $s_{i - 1}$ and $B$ represents making a move on $s_i,...,s_n$. Each valid string with $j$ $B$s and $k$ $A$s represents a unique sequence of moves, so the total number of transitions corresponds to the number of such valid strings. Notice that a string will be valid if and only if every $A$ occurs when $s_{i - 1}$ is $0$, because $s_{i - 1}$ flips every operation, meaning that every $A$ should occur on either only even indices or only odd indices depending on the initial value of $s_{i - 1}$. This means that the transition will be either $\\displaystyle\\binom{\\left\\lfloor \\frac{j + k}{2} \\right\\rfloor}{k}$ or $\\displaystyle\\binom{\\left\\lceil \\frac{j + k}{2} \\right\\rceil}{k}$. Finally, the answer can be found in $dp[1][k]$. The overall time complexity is: $O(n \\cdot k^2)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n\nconst int MOD = 998244353;\n\ntemplate<ll mod> // template was not stolen from https://codeforces.com/profile/SharpEdged\nstruct modnum {\n    static constexpr bool is_big_mod = mod > numeric_limits<int>::max();\n\n    using S = conditional_t<is_big_mod, ll, int>;\n    using L = conditional_t<is_big_mod, __int128, ll>;\n\n    S x;\n\n    modnum() : x(0) {}\n    modnum(ll _x) {\n        _x %= static_cast<ll>(mod);\n        if (_x < 0) { _x += mod; }\n        x = _x;\n    }\n\n    modnum pow(ll n) const {\n        modnum res = 1;\n        modnum cur = *this;\n        while (n > 0) {\n            if (n & 1) res *= cur;\n            cur *= cur;\n            n /= 2;\n        }\n        return res;\n    }\n    modnum inv() const { return (*this).pow(mod-2); }\n    \n    modnum& operator+=(const modnum& a){\n        x += a.x;\n        if (x >= mod) x -= mod;\n        return *this;\n    }\n    modnum& operator-=(const modnum& a){\n        if (x < a.x) x += mod;\n        x -= a.x;\n        return *this;\n    }\n    modnum& operator*=(const modnum& a){\n        x = static_cast<L>(x) * a.x % mod;\n        return *this;\n    }\n    modnum& operator/=(const modnum& a){ return *this *= a.inv(); }\n    \n    friend modnum operator+(const modnum& a, const modnum& b){ return modnum(a) += b; }\n    friend modnum operator-(const modnum& a, const modnum& b){ return modnum(a) -= b; }\n    friend modnum operator*(const modnum& a, const modnum& b){ return modnum(a) *= b; }\n    friend modnum operator/(const modnum& a, const modnum& b){ return modnum(a) /= b; }\n    \n    friend bool operator==(const modnum& a, const modnum& b){ return a.x == b.x; }\n    friend bool operator!=(const modnum& a, const modnum& b){ return a.x != b.x; }\n    friend bool operator<(const modnum& a, const modnum& b){ return a.x < b.x; }\n\n    friend ostream& operator<<(ostream& os, const modnum& a){ os << a.x; return os; }\n    friend istream& operator>>(istream& is, modnum& a) { ll x; is >> x; a = modnum(x); return is; }\n};\n\nusing mint = modnum<MOD>;\n\nstruct Combi{\n    vector<mint> _fac, _ifac;\n    int n;\n    \n    Combi() {\n        n = 1;\n        _fac.assign(n + 1, 1);\n        _ifac.assign(n + 1, 1);\n    }\n    \n    void check_size(int m){\n        int need = n;\n        while (need < m) need *= 2;\n        m = need;\n        if (m <= n) return;\n        \n        _fac.resize(m + 1);\n        _ifac.resize(m + 1);\n        for (int i = n + 1; i <= m; i++) _fac[i] = i * _fac[i - 1];\n        \n        _ifac[m] = _fac[m].inv();\n        for (int i = m - 1; i > n; i--) _ifac[i] = _ifac[i + 1] * (i + 1);\n        n = m;\n    }\n    \n    mint fac(int m){\n        check_size(m);\n        return _fac[m];\n    }\n    \n    mint ifac(int m){\n        check_size(m);\n        return _ifac[m];\n    }\n    \n    mint ncr(int n, int r){\n        if (n < r || r < 0) return 0;\n        \n        return fac(n) * ifac(n - r) * ifac(r);\n    }\n    \n    mint npr(int n, int r){\n        if (n < r || r < 0) return 0;\n        \n        return fac(n) * ifac(n - r);\n    }\n} comb;\n\nvoid solve(){\n    int n, k;\n    cin >> n >> k;\n\n    string s;\n    cin >> s;\n\n    vector<vector<mint>> dp(n, vector<mint>(k + 1));\n    dp[n - 1][0] = 1;\n    if (s[n - 1] == '0')\n        dp[n - 1][1] = 1;\n\n    for (int i = n - 2; i >= 0; i--){\n        for (int j = 0; j <= k; j++){\n            for (int c = 0; j + c <= k; c++){\n                int spaces = (j + c + (s[i] == '0')) / 2;\n                dp[i][j + c] += dp[i + 1][j] * comb.ncr(spaces, c);\n            }\n        }\n    }\n\n    cout << dp[0][k] << \"\\n\";\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    cout.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "combinatorics",
      "dp",
      "strings"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2109",
    "index": "F",
    "title": "Penguin Steps",
    "statement": "Mouf, the clever master of Darkness, and Fouad, the brave champion of Light, have entered the Grid Realm once more. This time, they have found the exit, but it is guarded by fierce monsters! They must fight with their bare hands instead of summoning monsters!\n\nMouf and Fouad are standing on an $n \\times n$ grid. Each cell $(i, j)$ has a value $a_{i,j}$ and a color. The color of a cell is white if $c_{i,j} = 0$ and black if $c_{i,j} = 1$.\n\nMouf starts at the top-left corner $(1, 1)$, and Fouad starts at the bottom-left corner $(n, 1)$. Both are trying to reach the exit cell at $(r, n)$.\n\nA path is defined as a sequence of adjacent cells (sharing a horizontal or vertical edge). The cost of a path is the maximum value of $a_{i, j}$ among all cells included in the path (including the first and last cells).\n\nLet:\n\n- $\\mathrm{dis}_M$ denote the minimum possible cost of a valid path from Mouf's starting position $(1, 1)$ to the exit $(r, n)$;\n- $\\mathrm{dis}_F$ denote the minimum possible cost of a valid path from Fouad's starting position $(n, 1)$ to the exit $(r, n)$.\n\nBefore moving, Mouf can perform up to $k$ operations. In each operation, he may select any black cell and increment its value by $1$ (possibly choosing the same cell multiple times).\n\nMouf wants to maximize $\\mathrm{dis}_F$ while ensuring that his own cost $\\mathrm{dis}_M$ remains \\textbf{unchanged} (as if he performed no operations). If Mouf acts optimally, what are the values of $\\mathrm{dis}_M$ and $\\mathrm{dis}_F$?",
    "tutorial": "Suppose you need $\\mathrm{dis}_F \\ge x$. To achieve this, construct a \"cage\" - a contiguous path of cells all with values at least $x$ - that separates Fouad from the exit, while ensuring that $\\mathrm{dis}_M$ remains unchanged. Try to find a path for Mouf that impacts the building of the \"cage\" as little as possible. First, find $\\mathrm{dis}_M$ using Dijkstra's algorithm or DSU. Define $can(x)$ to be true if you can make $\\mathrm{dis}_F$ greater than or equal to $x$, and false otherwise. It's clear that if $can(x)$ is true, then $can(x-1)$ is also true, which leads us to perform a binary search on the value of $x$. Suppose we choose a set $S$ of black cells with values strictly less than $x$ and decide to apply operations on them; the optimal strategy is to make the values of all chosen cells equal to $x$. Now, suppose we don't care about $\\mathrm{dis}_M$. How can we find the maximum possible $\\mathrm{dis}_F$? We need to create a cage that separates Fouad from the exit. The cage consists of the borders of the grid, in addition to cells with values greater than or equal to $x$ (after applying operations), forming a connected chain such that every two consecutive cells in the chain share an edge or corner. By using multi-source Dijkstra's algorithm, start from one border and try to reach another, where the weight of each cell represents how many operations are needed to raise its value to at least $x$. If it cannot be reached (e.g., if the cell is white and its value is less than $x$), then set the weight to infinity. We have six cases to build the cage, as described in the picture below: Now we have two cases to consider: $x \\le \\mathrm{dis}_M$: In this scenario, $\\mathrm{dis}_M$ will remain unchanged regardless of the set $S$ we choose. $x > \\mathrm{dis}_M$: Here, we must ensure that at least one path for Mouf has a cost equal to $\\mathrm{dis}_M$, while ensuring that no cell in this path is included in $S$. But which path should we retain? Suppose Mouf takes a path $P$. This action divides the grid into two parts: Every cell reachable from $(n,1)$ without passing through any cell in $P$. This portion belongs to Fouad (if $(n, 1)$ is already in $P$, then there are no cells that belong to Fouad's part). Every cell reachable from $(n,1)$ without passing through any cell in $P$. This portion belongs to Fouad (if $(n, 1)$ is already in $P$, then there are no cells that belong to Fouad's part). The remaining cells belong to Mouf. The remaining cells belong to Mouf. As we observe, the more cells allocated to Fouad's part, the greater the options we have for constructing a cage. Therefore, we define a super path as a path that leaves the maximum number of cells available for Fouad's part. But how many super paths exist? In fact, there is only one super path; the proof can be found below. Suppose we have two super paths that intersect at certain cells (including the first and last cells). In this case, we have two scenarios to consider: They only intersect at the first and last cells. In this situation, one of the paths cannot be a super path, leading to a contradiction. They only intersect at the first and last cells. In this situation, one of the paths cannot be a super path, leading to a contradiction. They intersect at other cells: If this is the case, then neither of the paths can be considered a super path. We can take the optimal segments from each path to construct a superior path, which also leads to a contradiction. They intersect at other cells: If this is the case, then neither of the paths can be considered a super path. We can take the optimal segments from each path to construct a superior path, which also leads to a contradiction. For further clarification, please refer to the illustration below. Now, how do we identify that super path? We begin by performing a multi-source BFS, initializing the queue with the cells in the first row and the first $r$ cells of the last column (as they always belong to Mouf's part). When visiting a cell, we mark it. If its value is less than or equal to $\\mathrm{dis}_M$, we pop it from the queue and continue; otherwise, we spread to the eight neighboring cells. Through this process, we will have certainly marked the super path (and potentially some additional cells from Mouf's part). If $x > \\mathrm{dis}_M$, it becomes impossible to utilize any marked cell to construct the cage - therefore, we set the weight for these cells to infinity. While you might consider the marked cells that are not part of the super path, this is inconsequential since any cage utilizing these cells will invariably pass through the super path. The overall time complexity of this approach is: $O(n^2 \\cdot \\log(A_{MAX} + k) \\cdot \\log(n))$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nusing i64 = long long;\n\nconstexpr int inf = 1e9;\narray<int, 8> dx{0, 0, 1, -1, 1, 1, -1, -1};\narray<int, 8> dy{1, -1, 0, 0, -1, 1, -1, 1};\n\nvoid solve() {\n    int n, r, k;\n    cin >> n >> r >> k;\n    --r;\n    \n    vector a(n, vector<int>(n));\n    for (int i = 0; i < n; ++i) {\n        for (int j = 0; j < n; ++j) {\n            cin >> a[i][j];\n        }\n    }\n    \n    vector b(n, vector<int>(n));\n    for (int i = 0; i < n; ++i) {\n        string s;\n        cin >> s;\n        for (int j = 0; j < n; ++j) {\n            b[i][j] = s[j] - '0';\n        }\n    }\n    \n    auto in = [&](int i, int j) {\n        return (0 <= i && i < n && 0 <= j && j < n);\n    };\n    \n    priority_queue<array<int, 3>, vector<array<int, 3>>, greater<>> pq;\n    pq.push({a[0][0], 0, 0});\n    vector dis(n, vector<int>(n, inf));\n    dis[0][0] = a[0][0];\n    while (pq.size()) {\n        auto [mx, i, j] = pq.top();\n        pq.pop();\n        if (dis[i][j] != mx) {\n            continue;\n        }\n        for (int dir = 0; dir < 4; ++dir) {\n            int ni = i + dx[dir];\n            int nj = j + dy[dir];\n            if (in(ni, nj) && dis[ni][nj] > max(mx, a[ni][nj])) {\n                int nmx = max(mx, a[ni][nj]);\n                dis[ni][nj] = nmx;\n                pq.push({nmx, ni, nj});\n            }\n        }\n    }\n    int mouf = dis[r][n - 1];\n    \n    vector dont(n, vector<int>(n));\n    auto run = [&](auto &&run, int i, int j) -> void {\n        for (int dir = 0; dir < 8; ++dir) {\n            int ni = i + dx[dir];\n            int nj = j + dy[dir];\n            if (in(ni, nj) && dont[ni][nj] == 0) {\n                dont[ni][nj] = 1;\n                if (a[ni][nj] > mouf) {\n                    run(run, ni, nj);\n                }\n            }\n        }\n    };\n    \n    for (int j = 0; j < n; ++j) {\n        dont[0][j] = 1;\n        if (a[0][j] > mouf) {\n            run(run, 0, j);\n        }\n    }\n    for (int i = 0; i <= r; ++i) {\n        dont[i][n - 1] = 1;\n        if (a[i][n - 1] > mouf) {\n            run(run, i, n - 1);\n        }\n    }\n    \n    int L = 1, R = 2e6;\n    while (L <= R) {\n        int mid = (L + R) / 2;\n        for (int j = 0; j < n; ++j) {\n            if ((mid > mouf && dont[n - 1][j]) || (mid > a[n - 1][j] && b[n - 1][j] == 0)) {\n                continue;\n            }\n            pq.push({max(0, mid - a[n - 1][j]), n - 1, j});\n        }\n        for (int i = r; i < n; ++i) {\n            if ((mid > mouf && dont[i][n - 1]) || (mid > a[i][n - 1] && b[i][n - 1] == 0)) {\n                continue;\n            }\n            pq.push({max(0, mid - a[i][n - 1]), i, n - 1});\n        }\n        fill(dis.begin(), dis.end(), vector<int>(n, inf));\n        while (pq.size()) {\n            auto [cost, i, j] = pq.top();\n            pq.pop();\n            dis[i][j] = min(dis[i][j], cost);\n            if (dis[i][j] != cost) {\n                continue;\n            }\n            for (int dir = 0; dir < 8; ++dir) {\n                int ni = i + dx[dir];\n                int nj = j + dy[dir];\n                if (in(ni, nj)) {\n                    if ((mid > mouf && dont[ni][nj]) || (mid > a[ni][nj] && b[ni][nj] == 0)) {\n                        continue;\n                    }\n                    if (dis[ni][nj] > cost + max(0, mid - a[ni][nj])) {\n                        int ncost = cost + max(0, mid - a[ni][nj]);\n                        dis[ni][nj] = ncost;\n                        pq.push({ncost, ni, nj});\n                    }\n                }\n            }\n        }\n        int minCost = inf;\n        if (mid <= mouf) {\n            for (int j = 0; j < n; ++j) {\n                minCost = min(minCost, dis[0][j]);\n            }\n            for (int i = 0; i <= r; ++i) {\n                minCost = min(minCost, dis[i][n - 1]);\n            }\n        }\n        for (int i = 1; i < n; ++i) {\n            minCost = min(minCost, dis[i][0]);\n        }\n        if (minCost <= k) {\n            L = mid + 1;\n        } else {\n            R = mid - 1;\n        }\n    }\n            \n    cout << mouf << \" \" << R << \"\\n\";\n}\n\nint main() {\n    ios::sync_with_stdio(0), cin.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "flows",
      "graphs",
      "shortest paths"
    ],
    "rating": 3000
  },
  {
    "contest_id": "2110",
    "index": "A",
    "title": "Fashionable Array",
    "statement": "In 2077, everything became fashionable among robots, even arrays...\n\nWe will call an array of integers $a$ fashionable if $\\min(a) + \\max(a)$ is divisible by $2$ without a remainder, where $\\min(a)$ — the value of the minimum element of the array $a$, and $\\max(a)$ — the value of the maximum element of the array $a$.\n\nYou are given an array of integers $a_1, a_2, \\ldots, a_n$. In one operation, you can remove any element from this array. Your task is to determine the minimum number of operations required to make the array $a$ fashionable.",
    "tutorial": "Sort the array $a$. Notice that now, after any removals, the minimum element is the leftmost of the remaining elements, and the maximum is the rightmost of the remaining elements. Check if it is fashionable. If yes, then the answer is $0$. Otherwise, $a_1 + a_n$ is not divisible by $2$. Thus, we need to remove the minimum number of elements to change the parity of $\\min(a)$ or $\\max(a)$, which will change the parity of $\\min(a) + \\max(a)$, making it divisible by $2$. To do this, find the first number $a_i$ that has a different parity than $\\min(a)$, and the last number $a_j$ that has a different parity than $\\max(a)$. Then the answer is $\\min(i - 1, n - j)$. The final asymptotic complexity is $O(n \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> x(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> x[i];\n    }\n    sort(x.begin(), x.end());\n    if (x[0] % 2 == x[n - 1] % 2) {\n        cout << 0 << endl;\n        return;\n    }\n    int left = n, right = n;\n    for (int i = 1; i < n; ++i) {\n        if (x[i] % 2 != x[0] % 2) {\n            left = i;\n            break;\n        }\n    }\n    for (int i = 1; i < n; ++i) {\n        if (x[n - i - 1] % 2 != x[n - 1] % 2) {\n            right = i;\n            break;\n        }\n    }\n    cout << min(left, right) << '\\n';\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}\n",
    "tags": [
      "implementation",
      "sortings"
    ],
    "rating": 800
  },
  {
    "contest_id": "2110",
    "index": "B",
    "title": "Down with Brackets",
    "statement": "In 2077, robots decided to get rid of balanced bracket sequences once and for all!\n\nA bracket sequence is called balanced if it can be constructed by the following formal grammar.\n\n- The empty sequence $\\varnothing$ is balanced.\n- If the bracket sequence $A$ is balanced, then $\\mathtt{(}A\\mathtt{)}$ is also balanced.\n- If the bracket sequences $A$ and $B$ are balanced, then the concatenated sequence $A B$ is also balanced.\n\nYou are the head of the department for combating balanced bracket sequences, and your main task is to determine which brackets you can destroy and which you cannot.\n\nYou are given a balanced bracket sequence represented by a string $s$, consisting of the characters ( and ). Since the robots' capabilities are not limitless, they can remove \\textbf{exactly} one opening bracket and \\textbf{exactly} one closing bracket from the string.\n\nYour task is to determine whether the robots can delete such two brackets so that the string $s$ is no longer a balanced bracket sequence.",
    "tutorial": "Let's recall the algorithm for checking the correctness of a bracket sequence. To do this, we check that the balance $bal$ at each prefix is non-negative, and that the balance $bal$ of the entire sequence is equal to $0$. To break a correct bracket sequence, we need to violate at least one of the conditions. Note that the balance $bal$ of the entire sequence will not change when we remove one opening bracket and one closing bracket. Therefore, we need to violate the first condition. Notice that removing an opening bracket will decrease $bal$ by 1 in the suffix to the right of the bracket. Similarly, for a closing bracket, it will increase $bal$ by 1 in the suffix. It is clear that among all closing brackets, it is advantageous to remove the very last one, as this will not increase any $bal$. Among all opening brackets, it is advantageous to remove the very first one, as this will decrease all $bal$ by 1 (which is obviously the most optimal option after removal). Thus, the answer is actually the result of checking the original bracket sequence without the first and last brackets for correctness. If it is correct, then the sequence cannot be broken; otherwise, it can be.",
    "code": "#include \"bits/stdc++.h\"\n#define int long long\n#define all(v) (v).begin(), (v).end()\n#define pb push_back\n#define em emplace_back\n#define mp make_pair\n#define F first\n#define S second\n\nusing namespace std;\ntemplate<class C>\nusing vec = vector<C>;\nusing vi = vector<int>;\nusing vpi = vector<pair<int, int>>;\nusing pii = pair<int, int>;\n\nvoid solve() {\n  string s;\n  cin >> s;\n  int n = s.size();\n  int bal = 0;\n  for (int i = 1; i + 1 < n; i++) {\n    if (s[i] == '(') bal++;\n    else bal--;\n    if (bal < 0) {\n      cout << \"YES\\n\";\n      return;\n    }\n  }\n  if (bal == 0) {\n    cout << \"NO\\n\";\n  } else {\n    cout << \"YES\\n\";\n  }\n}\n\nsigned main() {\n  int tt;\n  cin >> tt;\n  while (tt--) {\n    solve();\n  }\n}\n",
    "tags": [
      "strings"
    ],
    "rating": 900
  },
  {
    "contest_id": "2110",
    "index": "C",
    "title": "Racing",
    "statement": "In 2077, a sport called hobby-droning is gaining popularity among robots.\n\nYou already have a drone, and you want to win. For this, your drone needs to fly through a course with $n$ obstacles.\n\nThe $i$-th obstacle is defined by two numbers $l_i, r_i$. Let the height of your drone at the $i$-th obstacle be $h_i$. Then the drone passes through this obstacle if $l_i \\le h_i \\le r_i$. Initially, the drone is on the ground, meaning $h_0 = 0$.\n\nThe flight program for the drone is represented by an array $d_1, d_2, \\ldots, d_n$, where $h_{i} - h_{i-1} = d_i$, and $0 \\leq d_i \\leq 1$. This means that your drone either does not change height between obstacles or rises by $1$. You already have a flight program, but some $d_i$ in it are unknown and marked as $-1$. Replace the unknown $d_i$ with numbers $0$ and $1$ to create a flight program that passes through the entire obstacle course, or report that it is impossible.",
    "tutorial": "Let's maintain the bounds $L, R$ - the segment of heights in which $h_i$ can currently be. Initially, $L = R = 0$. Now, we will iterate from $i = 1$ to $n$. We could have risen by $1$, so $R$ increases by $1$. We also cannot rise above $r_i$ or drop below $l_i$, so if $R > r_i$, then $R = r_i$, and if $L < l_i$, then $L = l_i$. If at any point $L > R$, then such an array $d$ does not exist. Otherwise, it can be restored in reverse. The final asymptotic complexity is $O(n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> d(n);\n    for (auto &x : d) {\n        cin >> x;\n    }\n    vector<int> l(n), r(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> l[i] >> r[i];\n    }\n    int left = 0;\n    vector<int> last;\n    for (int i = 0; i < n; ++i) {\n        if (d[i] == -1) {\n            last.push_back(i);\n        } else {\n            left += d[i];\n        }\n        while (left < l[i]) {\n            if (last.empty()) {\n                cout << -1 << '\\n';\n                return;\n            }\n            d[last.back()] = 1;\n            ++left;\n            last.pop_back();\n        }\n        while (left + last.size() > r[i]) {\n            if (last.empty()) {\n                cout << -1 << '\\n';\n                return;\n            }\n            d[last.back()] = 0;\n            last.pop_back();\n        }\n    }\n    for (auto &x : d) {\n        cout << max(0, x) << \" \";\n    }\n    cout << \"\\n\";\n    return;\n}\n\nsigned main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2110",
    "index": "D",
    "title": "Fewer Batteries",
    "statement": "In 2077, when robots took over the world, they decided to compete in the following game.\n\nThere are $n$ checkpoints, and the $i$-th checkpoint contains $b_i$ batteries. Initially, the Robot starts at the $1$-st checkpoint with no batteries and must reach the $n$-th checkpoint.\n\nThere are a total of $m$ one-way passages between the checkpoints. The $i$-th passage allows movement from point $s_i$ to point $t_i$ ($s_i < t_i$), but not the other way. Additionally, the $i$-th passage can only be used if the robot has at least $w_i$ charged batteries; otherwise, it will run out of power on the way.\n\nWhen the robot arrives at point $v$, it can additionally take any number of batteries from $0$ to $b_v$, inclusive. Moreover, it always carries all previously collected batteries, and at each checkpoint, it recharges all previously collected batteries.\n\nFind the minimum number of batteries that the robot can have at the end of the journey, or report that it is impossible to reach from the first checkpoint to the last.",
    "tutorial": "We will build a directed graph: vertices are points, and edges are passages. We will perform a binary search on the answer. Suppose we are currently checking that $ans \\leq mid$. Then we will perform the following dynamic programming: $dp_v$ - the maximum number of batteries that the robot can have when it is at vertex $v$. Initially, $dp_i = -\\infty \\space(i > 1), dp_1 = 0$. We will recalculate forward. Let's consider vertex $v$. First, we add $b_v$ to $dp_v$, as we could take batteries at vertex $v$. Then we set $dp_v = min(dp_v, mid)$, because we cannot have more than $mid$ batteries. Then, for each outgoing edge $v, u, w$, if $dp_v < w$, we cannot pass through this edge. Otherwise, $dp_u = max(dp_u, dp_v)$. If $dp_n > 0$, then $ans \\leq mid$, otherwise not. The final asymptotic complexity is $O((n + m) \\log W)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nconst int INF = 1e9 + 11;\n\nstruct edge {\n    int t, w;\n    edge(int t, int w) : t(t), w(w) {}\n};\n\nvoid solve() {\n    int n, m;\n    cin >> n >> m;\n    vector<int> b(n);\n    for (auto &x : b) {\n        cin >> x;\n    }\n    vector<vector<edge>> graph(n);\n    for (int i = 0; i < m; ++i) {\n        int s, t, w;\n        cin >> s >> t >> w;\n        --s; --t;\n        graph[s].push_back(edge(t, w));\n    }\n    auto check = [&](int maxW) {\n        vector<int> best(n, 0);\n        for (int i = 0; i < n; ++i) {\n            if (i > 0 && best[i] == 0) {\n                continue;\n            }\n            best[i] += b[i];\n            best[i] = min(best[i], maxW);\n            for (auto p : graph[i]) {\n                if (p.w <= best[i]) {\n                    best[p.t] = max(best[p.t], best[i]);\n                }\n            }\n        }\n        return (best.back() > 0);\n    };\n    if (!check(INF)) {\n        cout << -1 << endl;\n        return;\n    }\n    int l = 0, r = INF;\n    while (r - l > 1) {\n        int mid = (l + r) / 2;\n        if (check(mid)) {\n            r = mid;\n        } else {\n            l = mid;\n        }\n    }\n    cout << r << endl;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "hashing"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2110",
    "index": "E",
    "title": "Melody",
    "statement": "In 2077, the robots that took over the world realized that human music wasn't that great, so they started composing their own.\n\nTo write music, the robots have a special musical instrument capable of producing $n$ different sounds. Each sound is characterized by its volume and pitch. A sequence of sounds is called music. Music is considered beautiful if any two consecutive sounds differ either only in volume or only in pitch. Music is considered boring if the volume or pitch of any three consecutive sounds is the same.\n\nYou want to compose beautiful, \\textbf{non}-boring music that contains each sound produced by your musical instrument exactly once.",
    "tutorial": "Let's construct a bipartite graph, where all possible volumes of sounds are on the left and pitches are on the right. Then a pair of vertices $p,v$ will be connected by an edge if the musical instrument can produce the sound $(p,v)$. Notice that each path in such a graph represents $beautiful$ music. This is because any two adjacent edges share a common vertex, meaning they either have the same volume or the same pitch. Also, this music is not $boring$, as no three consecutive edges share any common vertices, meaning they cannot have a common volume or pitch. Now, notice that music consisting of all sounds is an Eulerian path in our graph. Thus, we have reduced our problem to the standard problem of finding an Eulerian path. The final asymptotic complexity is $O(n\\space log\\space n)$ or $O(n)$, depending on the implementation of the Eulerian path.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvector<set<int>> graph;\nvector<int> ans;\n\nvoid dfs(int v) {\n    while (!graph[v].empty()) {\n        int u = *graph[v].begin();\n        graph[u].erase(v);\n        graph[v].erase(u);\n        dfs(u);\n    }\n    ans.push_back(v);\n}\n\nsigned main() {\n    int t;\n    cin >> t;\n    while (t--) {\n        graph.clear();\n        ans.clear();\n        int n;\n        cin >> n;\n        map<int, int> p, v;\n        map<pair<int, int>, int> toIndex;\n        vector<pair<int, int>> part;\n        for (int i = 1; i <= n; ++i) {\n            int volume, pitch;\n            cin >> volume >> pitch;\n            toIndex[make_pair(volume, pitch)] = i;\n            if (p.count(pitch) == 0) {\n                p[pitch] = graph.size();\n                graph.push_back(set<int>());\n                part.push_back(make_pair(0, pitch));\n            }\n            if (v.count(volume) == 0) {\n                v[volume] = graph.size();\n                graph.push_back(set<int>());\n                part.push_back(make_pair(volume, 0));\n            }\n            graph[v[volume]].insert(p[pitch]);\n            graph[p[pitch]].insert(v[volume]);\n        }\n        int root = 0;\n        int cnt = 0;\n        for (int i = 0; i < graph.size(); ++i) {\n            if (graph[i].size() % 2 == 1) {\n                ++cnt;\n                root = i;\n            }\n        }\n        dfs(root);\n        if (ans.size() != n + 1 || cnt > 2) {\n            cout << \"NO\" << endl;\n            continue;\n        }\n        vector<int> out;\n        for (int i = 0; i < n; ++i) {\n            auto p1 = part[ans[i]];\n            auto p2 = part[ans[i + 1]];\n            out.push_back(toIndex[make_pair(p1.first + p2.first, p1.second + p2.second)]);\n            if (out[i] == 0) {\n                out.clear();\n                break;\n            }\n        }\n        if (out.empty()) {\n            cout << \"NO\" << endl;\n        } else {\n            cout << \"YES\" << endl;\n            for (int i = 0; i < n; ++i) {\n                cout << out[i] << \" \";\n            }\n            cout << endl;\n        }\n    }\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation"
    ],
    "rating": 2300
  },
  {
    "contest_id": "2110",
    "index": "F",
    "title": "Faculty",
    "statement": "In 2077, after the world was enslaved by robots, the robots decided to implement an educational reform, and now the operation of taking the modulus is only taught in the faculty of \"Ancient World History\". Here is one of the entrance tasks for this faculty:\n\nWe define the beauty of an array of positive integers $b$ as the maximum $f(b_i, b_j)$ over all pairs $1 \\leq i, j \\leq n$, where $f(x, y) = (x \\bmod y) + (y \\bmod x)$.\n\nGiven an array of positive integers $a$ of length $n$, output $n$ numbers, where the $i$-th number ($1 \\leq i \\leq n$) is the beauty of the array $a_1, a_2, \\ldots, a_i$.\n\n$x \\bmod y$ is the remainder of the division of $x$ by $y$.",
    "tutorial": "To solve the problem, several facts need to be noted. Fact I. $f(x, y) \\leq \\max(x, y)$. If $x = y$, then $f(x, y) = 0$. Otherwise, let $x < y$. Then $x \\mod y = x$. Thus, $f(x, y) = x + y - \\lfloor{\\frac{y}{x}}\\rfloor \\cdot x \\leq y$, since $\\lfloor{\\frac{y}{x}}\\rfloor \\geq 1$. Fact II. We can only consider pairs with the maximum, that is, such $i, j$ that $b_i$ is the maximum element of $b$. Let $b_{max}$ be the maximum element of the array $b$. Suppose that $f(b_i, b_j)$ is greater than the found value. Let $b_i \\leq b_j$. From Fact I, it follows that $f(b_i, b_j) \\leq b_j$. Now consider $f(b_j, b_{max})$. Since $b_j < b_{max}$, we have $b_j \\mod b_{max} = b_j$, which means $f(b_j, b_{max}) \\geq b_j \\geq f(b_i, b_j)$. Fact III. Let $b_i < b_j$. If $b_j < b_i \\cdot 2$, then $f(b_i, b_j) = b_j$. This is true because $\\lfloor{\\frac{b_j}{b_i}}\\rfloor = 1$, which means $f(b_i, b_j) = b_i + b_j - \\lfloor{\\frac{b_j}{b_i}}\\rfloor \\cdot b_i = b_j$. Now let's go through the prefixes one by one. We will maintain $b_{max}$ - the maximum element in the prefix. Suppose we are currently at prefix $i$. If $b_i \\leq b_{max}$, then the maximum has not changed, and we can simply update the answer with $f(b_{max}, b_i)$ from Fact II. $O(1)$. If $b_{max} < b_i < b_{max} \\cdot 2$, then we can say that the answer is $b_i$, since $f(b_i, b_{max}) = b_i$ from Fact III. $O(1)$. If $b_{max} \\cdot 2 \\leq b_i$, then we will simply iterate through all previous $j < i$ and update the answer with $f(b_i, b_j)$. $O(n)$. The number of such iterations will be no more than $log_2{A}$, since in each of them the maximum increases by a factor of $2$. The final asymptotic complexity is $O(n \\log A)$, where $A$ is the maximum element of the array $a$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint f(int x, int y) {\n    return (x % y) + (y % x);\n}\n\nvoid Solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    int ans = 0;\n    int mx = a[0];\n    for (int i = 0; i < n; ++i) {\n        ans = max(ans, f(mx, a[i]));\n        if (a[i] > mx) {\n            if (a[i] >= mx * 2) {\n                mx = a[i];\n                for (int j = 0; j < i; ++j) {\n                    ans = max(ans, f(a[i], a[j]));\n                }\n            } else {\n                mx = a[i];\n                ans = mx;\n            }\n        }\n        cout << ans << ' ';\n    }\n    cout << endl;\n}\n\nint main() {\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        Solve();\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2111",
    "index": "A",
    "title": "Energy Crystals",
    "statement": "There are three energy crystals numbered $1$, $2$, and $3$; let's denote the energy level of the $i$-th crystal as $a_i$. Initially, all of them are discharged, meaning their energy levels are equal to $0$. Each crystal needs to be charged to level $x$ \\textbf{(exactly $x$, not greater)}.\n\nIn one action, you can increase the energy level of any one crystal by any positive amount; however, the energy crystals are synchronized with each other, so an action can only be performed if the following condition is met afterward:\n\n- for each pair of crystals $i$, $j$, it must hold that $a_{i} \\ge \\lfloor\\frac{a_{j}}{2}\\rfloor$.\n\nWhat is the minimum number of actions required to charge all the crystals?",
    "tutorial": "Let's relax the requirement that all crystals must be charged exactly to level $x$ and allow the energy level to rise above it, i.e., $a_{i} \\ge x$ in the end. We will try to come up with a greedy algorithm to charge the crystals. The simplest idea is to take the crystal with the minimum energy level and charge it as much as possible. If all three crystals have $a_{i} \\ge x$, then we have our answer. The energy level will change as follows: $[0, 0, 0] \\to [\\color{red}{1}, 0, 0] \\to [1, \\color{red}{1}, 0] \\to [1, 1, \\color{red}{3}] \\to [1, \\color{red}{3}, 3] \\to [\\color{red}{7}, 3, 3] \\to \\dots$ Each action takes a crystal and charges it to level $2 \\cdot m + 1$, where $m$ is the minimum charge of the other two crystals at that moment. Note that if we apply the action to a crystal, its energy level increases by at least $2$; therefore, the answer can be obtained in $O(\\log x)$ actions. It turns out that this algorithm already solves the problem, and the condition that the energy level must be exactly $x$ does not affect anything. This is because, at the last moment when the greedy algorithm is about to charge some crystal to level: $2 \\cdot m + 1 > x$ We can instead set it to exactly $x$. Let's check why this is permissible and does not change the number of moves: The state will be $[m, m, x]$, where $m < x$ and $2 \\cdot m + 1 > x$, so the next two actions can be as follows: $[m, m, x] \\to [\\color{red}{x}, m, x] \\to [x, \\color{red}{x}, x]$ Meanwhile, the greedy algorithm would also perform two actions: $[m, m, 2 \\cdot m + 1] \\to [\\color{red}{2 \\cdot m + 1}, m, 2 \\cdot m + 1] \\to [2 \\cdot m + 1, \\color{red}{4 \\cdot m + 3}, 2 \\cdot m + 1]$",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \n#define int long long\n \nvoid solve(){\n\tint x;\n\tcin >> x;\n\tint ans = 0;\n\tint a1 = 0, a2 = 0, a3 = 0;\n\twhile(min({a1, a2, a3}) < x){\n\t\tif (a1 <= a2 && a1 <= a3){\n\t\t\ta1 = min(a2, a3) * 2 + 1;\n\t\t}\n\t\telse if (a2 <= a1 && a2 <= a3){\n\t\t\ta2 = min(a1, a3) * 2 + 1;\n\t\t}\n\t\telse{\n\t\t\ta3 = min(a1, a2) * 2 + 1;\n\t\t}\n\t\tans++;\n\t}\n\tcout << ans << '\\n';\n}\n \nsigned main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n \n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 0; test < tests; test++){\n\t\tsolve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2111",
    "index": "B",
    "title": "Fibonacci Cubes",
    "statement": "There are $n$ Fibonacci cubes, where the side of the $i$-th cube is equal to $f_{i}$, where $f_{i}$ is the $i$-th Fibonacci number.\n\nIn this problem, the Fibonacci numbers are defined as follows:\n\n- $f_{1} = 1$\n- $f_{2} = 2$\n- $f_{i} = f_{i - 1} + f_{i - 2}$ for $i > 2$\n\nThere are also $m$ empty boxes, where the $i$-th box has a width of $w_{i}$, a length of $l_{i}$, and a height of $h_{i}$.\n\nFor each of the $m$ boxes, you need to determine whether all the cubes can fit inside that box. The cubes must be placed in the box following these rules:\n\n- The cubes can only be stacked in the box such that the sides of the cubes are parallel to the sides of the box;\n- Every cube must be placed either on the bottom of the box or on top of other cubes in such a way that all space below the cube is occupied;\n- A larger cube cannot be placed on top of a smaller cube.",
    "tutorial": "Notice the following: if we can fit the two largest cubes from the set into the box, then we can also fit all the smaller cubes into it. To fit the two largest cubes, it is sufficient that all sides of the box are at least $f_{n}$, and the larger of the sides of the box is at least $f_{n + 1}$. The first condition is quite obvious; if it were not satisfied, we would not be able to fit even the largest cube into the box. The second condition, however, is a bit more interesting. Let's simplify the problem a bit and remove one dimension, meaning all cubes will turn into squares. We will check that the rectangle $f_{n} \\times f_{n + 1}$ can accommodate all these squares. This resembles a picture where a Fibonacci spiral is drawn: Each time we draw a square with a side of $f_{i}$, the remaining area turns into a rectangle with sides $f_{i}$ and $f_{i - 1}$. Now, if we add a third dimension $f_{n}$ to the rectangle and $f_{i}$ to squares, all cubes will also remain within the rectangular parallelepiped. The rectangle could serve as either the bottom or one of the side faces. Thus, if the rectangle was a side face, then in the picture presented above, some larger cubes would be resting on smaller cubes, which is not allowed. However, if we redraw the squares in the rectangle slightly differently, all requirements will be met: For example, like this",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n#define int long long\n \nvoid solve(){\n\tint n, m;\n\tcin >> n >> m;\n\tvector<vector<int>> a(m);\n \n\tfor (int i = 0; i < m; i++){\n\t\tfor (int j = 0; j < 3; j++){\n\t\t\tint x;\n\t\t\tcin >> x;\n\t\t\ta[i].emplace_back(x);\n\t\t}\n\t\tsort(a[i].begin(), a[i].end());\n\t}\n\n\tvector<int> fib(n + 5);\n\tfib[0] = 1;\n\tfib[1] = 2;\n\tfor (int i = 2; i < n + 1; i++){\n\t\tfib[i] = fib[i - 1] + fib[i - 2];\n\t}\n \n\tfor (int i = 0; i < m; i++){\n\t\tif (a[i][0] >= fib[n - 1] && a[i][1] >= fib[n - 1] && a[i][2] >= fib[n]){\n\t\t\tcout << '1';\n\t\t}\n\t\telse{\n\t\t\tcout << '0';\n\t\t}\n\t}\n\tcout << '\\n';\n}\n \nsigned main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n \n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 0; test < tests; test++){\n        solve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "dp",
      "implementation",
      "math"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2111",
    "index": "C",
    "title": "Equal Values",
    "statement": "You are given an array $a_1, a_2, \\dots, a_n$, consisting of $n$ integers.\n\nIn one operation, you are allowed to perform one of the following actions:\n\n- Choose a position $i$ ($1 < i \\le n$) and make all elements to the left of $i$ equal to $a_i$. That is, assign the value $a_i$ to all $a_j$ ($1 \\le j < i$). The cost of such an operation is $(i - 1) \\cdot a_i$.\n- Choose a position $i$ ($1 \\le i < n$) and make all elements to the right of $i$ equal to $a_i$. That is, assign the value $a_i$ to all $a_j$ ($i < j \\le n$). The cost of such an operation is $(n - i) \\cdot a_i$.\n\nNote that the elements affected by an operation may already be equal to $a_i$, but that doesn't change the cost.\n\nYou are allowed to perform any number of operations (including zero). What is the minimum total cost to make all elements of the array equal?",
    "tutorial": "The first minor observation is that the cost of both operations is the value of the element times the number of the elements affected by the operation. Let's also expand the scope of both operations so that we can apply the first operation to the first element (with cost $0$, since $0$ elements are affected) and the second operation to the last element. Fix the value $x$ that will be the final value of all elements of the array. Obviously, it only makes sense to apply the operations to the elements equal to $x$. Let's consider the operations of the first and second types separately. Note that if we apply an operation that changes values to the left at position $a$, and an operation that changes values to the right at position $b$, with $a > b$, we can always reduce the total cost by applying both operations to either $a$ or $b$. This means that there exists an optimal solution in which operations of the first type never affect elements changed by operations of the second type. Now, let's consider only the operations that change elements to the left. Suppose one operation is applied at position $a$, and another at position $b$. If instead of them we apply one operation at position $\\max(a, b)$, the effect will be exactly the same. Similarly, we can show this for operations that change elements to the right. Thus, it is sufficient to apply one operation of each type. Let the operation to the left be applied at position $a$, and the operation to the right at position $b$ (with $a \\le b$). All elements between $a$ and $b$ must be equal to $x$, because they are not affected by the operations. The total cost of such operations will be equal to $(a - 1) \\cdot x + (n - b) \\cdot x = x \\cdot (n - 1 - (b - a))$. So, the answer depends on the distance between $a$ and $b$ and the value of $x$. Since all values between $a$ and $b$ must be equal to $x$, they form a continuous block of identical values. Therefore, to find the optimal answer, it is sufficient to iterate over the blocks of identical values in the array and choose the minimum answer from them. This can be done using the two-pointer method. Overall complexity: $O(n)$ per test case.",
    "code": "for _ in range(int(input())):\n    n = int(input())\n    a = list(map(int, input().split()))\n    i = 0\n    ans = 10**18\n    while i < n:\n        j = i\n        while j < n and a[j] == a[i]:\n            j += 1\n        ans = min(ans, (i + n - j) * a[i])\n        i = j\n    print(ans)",
    "tags": [
      "brute force",
      "greedy",
      "two pointers"
    ],
    "rating": 1100
  },
  {
    "contest_id": "2111",
    "index": "D",
    "title": "Creating a Schedule",
    "statement": "A new semester is about to begin, and it is necessary to create a schedule for the first day. There are a total of $n$ groups and $m$ classrooms in the faculty. It is also known that each group has exactly $6$ classes on the first day, and the $k$-th class of each group takes place at the same time. Each class must be held in a classroom, and at the same time, there cannot be classes for more than one group in the same classroom.\n\nEach classroom has its own index (at least three digits), and all digits of this index, except for the last two, indicate the floor on which the classroom is located. For example, classroom $479$ is located on the $4$-th floor, while classroom $31415$ is on the $314$-th floor. Between floors, one can move by stairs; for any floor $x > 1$, one can either go down to floor $x - 1$ or go up to floor $x + 1$; from the first floor, one can only go up to the second; from the floor $10^7$ (which is the last one), it is possible to go only to the floor $9999999$.\n\nThe faculty's dean's office has decided to create the schedule in such a way that students move as much as possible between floors, meaning that \\textbf{the total number of movements between floors across all groups should be maximized}. When the students move from one floor to another floor, they take the shortest path.\n\nFor example, if there are $n = 2$ groups and $m = 4$ classrooms $[479, 290, 478, 293]$, the schedule can be arranged as follows:\n\n\\begin{center}\n\\begin{tabular}{|c||c||c|}\n\\hline\n\\textbf{Class No.} & \\textbf{Group 1} & \\textbf{Group 2} \\\n\\hline\n\\hline\n$1$ & $290$ & $293$ \\\n\\hline\n\\hline\n$2$ & $478$ & $479$ \\\n\\hline\n\\hline\n$3$ & $293$ & $290$ \\\n\\hline\n\\hline\n$4$ & $479$ & $478$ \\\n\\hline\n\\hline\n$5$ & $293$ & $290$ \\\n\\hline\n\\hline\n$6$ & $479$ & $478$ \\\n\\hline\n\\end{tabular}\n\\end{center}\n\nIn such a schedule, the groups will move between the $2$nd and $4$th floors each time, resulting in a total of $20$ movements between floors.\n\nHelp the dean's office create any suitable schedule!",
    "tutorial": "Let $f_{i,j}$ be the floor where the $i$-th group has its $j$-th class. Then, the number of moves between floors can be expressed as follows: $\\sum\\limits_{j=1}^{5} \\sum\\limits_{i=1}^{n} |f_{i,j} - f_{i,j+1}|$ Using the fact that $|x-y| = \\max(x,y) - \\min(x,y)|$, we can rewrite it as follows: $\\sum\\limits_{j=1}^{5} \\sum\\limits_{i=1}^{n} max(f_{i,j}, f_{i,j+1}) - min(f_{i,j}, f_{i,j+1})$ Or as follows: $\\sum\\limits_{j=1}^{5} \\sum\\limits_{i=1}^{n} max(f_{i,j}, f_{i,j+1}) - \\sum\\limits_{j=1}^{5} \\sum\\limits_{i=1}^{n} min(f_{i,j}, f_{i,j+1})$ Let's analyze how big can we make the first part of this expression, and how small can we make the second part of this expression. Every auditorium can be used at most twice during two consecutive classes, so if the number of groups is even, then $\\sum\\limits_{i=1}^{n} max(f_{i,j}, f_{i,j+1})$ cannot be greater than the sum of $\\frac{n}{2}$ maximum floors, multiplied by $2$. If $n$ is odd, then we also add the $(\\frac{n}{2}+1)$-th maximum floor. Similarly, if $n$ is even, then $\\sum\\limits_{i=1}^{n} min(f_{i,j}, f_{i,j+1})$ cannot be less than the sum of $\\frac{n}{2}$ minimum floors, multiplied by $2$. If $n$ is odd, then we also add the $(\\frac{n}{2}+1)$-th minimum floor. This is a bound on the number of movements; if we achieve it, our answer will be optimal. Achieving it is actually not that difficult. Suppose the list of auditoriums is sorted (sorting it also sorts the list of floors where the auditoriums are located). If $n$ is even, we can split all groups into two parts of sizes $\\frac{n}{2}$. The first half will have their first classes in the $\\frac{n}{2}$ lowest auditoriums, then go to the $\\frac{n}{2}$ highest auditoriums, then return to $\\frac{n}{2}$ lowest auditoriums, and so on. The second half will do the opposite: start in the $\\frac{n}{2}$ highest auditoriums, then go to the $\\frac{n}{2}$ lowest auditoriums, then return, and so on. If $n$ is odd, then the \"extra\" group can use the $(\\frac{n}{2} + 1)$-th lowest auditorium for odd-indexed classes and $(\\frac{n}{2} + 1)$-th highest auditorium for even-indexed classes. This solution achieves the bound which we proved earlier, so it is optimal.",
    "code": "#include<bits/stdc++.h>\n \nusing namespace std;\n \nvoid solve(){\n\tint n, m;\n\tcin >> n >> m;\n\tvector<int> a(m);\n\tfor (int i = 0; i < m; i++){\n\t\tcin >> a[i];\n\t}\n\tsort(a.begin(), a.end());\n\tvector<vector<int>> ans(n, vector<int> (6));\n \n\tfor (int i = 0; i < n; i += 2){\n\t\tif (i + 1 == n){\n\t\t\tfor (int j = 0; j < 6; j++){\n\t\t\t\tif (j % 2 == 0){\n\t\t\t\t\tans[i][j] = a[i / 2];\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tans[i][j] = a[m - i / 2 - 1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tfor (int j = 0; j < 6; j++){\n\t\t\t\tif (j % 2 == 0){\n\t\t\t\t\tans[i][j] = a[i / 2];\n\t\t\t\t\tans[i + 1][j] = a[m - i / 2 - 1];\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tans[i][j] = a[m - i / 2 - 1];\n\t\t\t\t\tans[i + 1][j] = a[i / 2];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n \n\tfor (int i = 0; i < n; i++){\n\t\tfor (int j = 0; j < 6; j++){\n\t\t\tcout << ans[i][j] << ' ';\n\t\t}\n\t\tcout << '\\n';\n\t}\n}\n \nsigned main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n \n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 0; test < tests; test++){\n\t\tsolve();\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "constructive algorithms",
      "data structures",
      "greedy",
      "implementation",
      "sortings"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2111",
    "index": "E",
    "title": "Changing the String",
    "statement": "Given a string $s$ that consists only of the first three letters of the Latin alphabet, meaning each character of the string is either a, b, or c.\n\nAlso given are $q$ operations that need to be performed on the string. In each operation, two letters $x$ and $y$ from the set of the first three letters of the Latin alphabet are provided, and for each operation, one of the following two actions must be taken:\n\n- change any (one) occurrence of the letter $x$ in the string $s$ to the letter $y$ (if at least one occurrence of the letter $x$ exists);\n- do nothing.\n\nThe goal is to perform all operations in the given order in such a way that the string $s$ becomes lexicographically minimal.\n\nRecall that a string $a$ is lexicographically less than a string $b$ if and only if one of the following conditions holds:\n\n- $a$ is a prefix of $b$, but $a \\neq b$;\n- at the first position where $a$ and $b$ differ, the string $a$ has a letter that comes earlier in the alphabet than the corresponding letter in $b$.",
    "tutorial": "First, let's try to understand what operations and sequences of operations make sense to perform. Each letter can be transformed at most two times: if we change it more than twice, then at two moments in time it will be the same, and all operations between them can be omitted. Clearly, there is no point in transforming the letter a at all, as it cannot be made lexicographically smaller. The letter b can only be transformed into the letter a, either directly or indirectly through the letter c. The letter c can be transformed into both the letter a (directly or indirectly through the letter b) or the letter b (but only directly; there is no point in transforming it into a to then transform it into b). This means that we are actually interested in the following sequences of transformations: $b \\rightarrow a$; $b \\rightarrow c \\rightarrow a$; $c \\rightarrow a$; $c \\rightarrow b$; $c \\rightarrow b \\rightarrow a$. Moreover, there is no point in combining sequences of types $2$ and $5$ (the only ones with two operations) because if there are two sequences of types $2$ and $5$, we can instead transform them into two sequences of types $1$ and $3$. Now let's try to actually solve the problem. We will go through the string from left to right and for each character, we will try to transform it into the smallest possible character (considering that we still need to transform characters in the prefix and that some operations may be unavailable). When we encounter the character b, let's first try to build a sequence of type $1$ for it, and if that doesn't work, a sequence of type $2$. When we encounter the character c, we will first try to build a sequence of type $3$, if that doesn't work, then type $5$, and if that still doesn't work, type $4$. To build the sequences, we will keep a set of all queries for each possible transformation of one character into another; if there is only one transformation in the sequence, we will take the earliest one; if there are two, we will take the earliest of the first type and use lower_bound to find the earliest of the second type that can be taken with it. Let's prove that this greedy approach works. To do this, we will analyze two \"dangerous\" moments in our greedy approach: What if transforming characters into a directly is not always beneficial? We try to transform them directly first and only then indirectly; what if this is incorrect? What if our choice of the earliest operations for transformations is not correct because it may prohibit us from performing some sequence of operations later? We will prove that point $1$ is not a problem. Suppose in the optimal solution we transformed some character $s_i$ into a indirectly, although at that moment we could have done it directly. If we still have unused operations to transform $s_i$ into a directly, we can use the direct transformation instead of the indirect one, and the answer will not change. Otherwise, suppose we used that direct transformation on character $s_j$ ($j > i$). If $s_i = s_j$, we can \"swap\" them, and the answer will not change. If $s_i \\ne s_j$, this means that we indirectly transformed the character b into a and the character c into a - and we previously proved that in the optimal solution, we can ignore such cases. Now let's prove that point $2$ is also not a problem. If we use a single transformation of character b or c into a, it is always beneficial to take the earliest operation of that type: later operations of that type may be needed for indirect transformations (sequences of transformations of types $2$ or $5$), and in such sequences, the operation of transforming into a is the second one, so it is beneficial to leave later operations of transforming into a for such sequences. We can also use a single transformation from c to b, but we only use it when the operations for transforming b into a have either already ended or the last such operation occurs later than the first operation of transforming c into b, so we definitely cannot use the transformation from c to b in a sequence of two operations, and we can take any such operation (including the earliest one). Therefore, the solution can be implemented as follows: For each type of operation, form a set of all queries in which such an operation can be performed. Go through the string from left to right and greedily transform the current character into the smallest possible character. First, we will try to transform it into a (first directly, then indirectly); if that doesn't work, then into b. In each transformation, we will use the earliest operation (if two operations are needed, the earliest operation of the first type and the earliest operation of the second type that comes after the first). The complexity of the solution is $O((n + q) \\log q)$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n \n#define int long long\n \nvoid solve(){\n\tint n, q;\n\tcin >> n >> q;\n\tstring s;\n\tcin >> s;\n\tvector<vector<set<int>>> st(3, vector<set<int>> (3));\n\tfor (int i = 0; i < q; i++){\n\t\tchar x, y;\n\t\tcin >> x >> y;\n\t\tst[x - 'a'][y - 'a'].insert(i);\n\t}\n\n\tfor (int i = 0; i < n; i++){\n\t\tif (s[i] == 'a'){\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (s[i] == 'b'){\n\t\t\tif (!st[1][0].empty()){\n\t\t\t\tst[1][0].erase(st[1][0].begin());\n\t\t\t\ts[i] = 'a';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!st[1][2].empty()){\n\t\t\t\tauto ind = *st[1][2].begin();\n\t\t\t\tauto lb = st[2][0].lower_bound(ind);\n\t\t\t\tif (lb != st[2][0].end()){\n\t\t\t\t\tst[1][2].erase(ind);\n\t\t\t\t\tst[2][0].erase(lb);\n\t\t\t\t\ts[i] = 'a';\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (s[i] == 'c'){\n\t\t\tif (!st[2][0].empty()){\n\t\t\t\tst[2][0].erase(st[2][0].begin());\n\t\t\t\ts[i] = 'a';\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!st[2][1].empty()){\n\t\t\t\tauto ind = *st[2][1].begin();\n\t\t\t\tst[2][1].erase(ind);\n\t\t\t\ts[i] = 'b';\n\t\t\t\tauto lb = st[1][0].lower_bound(ind);\n\t\t\t\tif (lb != st[1][0].end()){\n\t\t\t\t\tst[1][0].erase(lb);\n\t\t\t\t\ts[i] = 'a';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << s << '\\n';\n}\n \nsigned main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n \n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 0; test < tests; test++){\n                solve();\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "binary search",
      "data structures",
      "greedy",
      "implementation",
      "sortings",
      "strings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2111",
    "index": "F",
    "title": "Puzzle",
    "statement": "You have been gifted a puzzle, where each piece of this puzzle is a square with a side length of one. You can glue any picture onto this puzzle, cut it, and obtain an almost ordinary jigsaw puzzle.\n\nYour friend is an avid mathematician, so he suggested you consider the following problem. Is it possible to arrange the puzzle pieces in such a way that the following conditions are met:\n\n- the pieces are aligned parallel to the coordinate axes;\n- the pieces do not overlap each other;\n- all pieces form a single connected component (i.e., there exists a path from each piece to every other piece along the pieces, where each two consecutive pieces share a side);\n- the ratio of the perimeter of this component to the area of this component equals $\\frac{p}{s}$;\n- the number of pieces used does not exceed $50\\,000$.\n\nCan you handle it?\n\n\\begin{center}\n{\\small For this figure, the ratio of the perimeter to the area is $\\frac{11}{9}$}\n\\end{center}",
    "tutorial": "If a figure consists of a single piece, then its perimeter-to-area ratio is $4$ to $1$. In fact, this is the maximum ratio that can be achieved. That is, if $\\frac{p}{s} > 4$, the answer is $-1$. Now we need to understand what other ratios can exist: Suppose we have placed one piece; let's add one neighboring piece to it. Notice that if the next unit piece touches one side of our figure, the area increases by $1$, and the perimeter increases by $2$. Thus, if we add $x$ pieces to our very first one in this manner, the ratio will be: $\\frac{4 + 2 \\cdot x}{1 + x}$ This can be transformed into the following form: $\\frac{2 + (2 + 2 \\cdot x)}{1 + x} = \\frac{2}{1 + x} + \\frac{2 \\cdot (x + 1)}{x + 1} = \\frac{2}{1 + x} + 2$ This means that if the ratio is $> 2$ and can be represented in this form, then we can draw it as a strip figure, that is, a rectangle $1 \\times (x + 1)$. Now let's imagine a situation where we added $x$ pieces in the manner described above, and then we add a piece that touches two or more sides of our figure. In this case, the area increases by $1$, but the perimeter does not increase: $\\frac{4 + 2 \\cdot x + 0}{1 + x + 1} = \\frac{2 \\cdot (2 + x)}{2 + x} = 2$ Thus, if we constructed the figure in this way, the ratio $\\frac{p}{s} \\le 2$. This means that if the ratio cannot be represented in the form $\\frac{2}{1 + x} + 2$ and is greater than two, the answer is also $-1$. We are left to deal with the case when $\\frac{p}{s} \\le 2$. In fact, when it equals two, we can draw a square with a side of $2$, and that will be our answer. If $\\frac{p}{s} < 2$, then any figure with such a ratio can be obtained. The ratios can be divided into two cases: when the numerator is even and when it is odd. When the numerator is odd, it is straightforward: we remember that if we place a piece on some figure so that it touches only one side, the perimeter increases by $2$, and the area by $1$. So let's subtract $2$ from $p$ and $1$ from $s$ until we get $\\frac{1}{s}$. Such a ratio can easily be drawn as a square with a side of $4 \\cdot s$. Thus, any ratio in this case can be represented as a square to which a strip has been added. When the numerator is even, let's subtract $2$ from $p$ and $1$ from $s$ until we get the ratio $\\frac{2}{s}$. This ratio can also be represented as a square with a side of $2 \\cdot s$. Therefore, all figures with a ratio $\\frac{p}{s} \\le 2$ can be drawn as a square to which a strip has been added. Like this Let's estimate the number of pieces used in such a solution. Obviously, the worst case will be when we need to draw a large square, for example, for the ratio $\\frac{p}{s} = \\frac{1}{50}$ or $\\frac{p}{s} = \\frac{2}{49}$. But even in such cases, $16 \\cdot s^{2} = 40\\,000$ and $4 \\cdot s^{2} = 9\\,604$ pieces are needed, respectively.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\n\n#define int long long\n \nvoid solve(){\n\tint p, s;\n\tcin >> p >> s;\n\n\tif (p > 4 * s){\n\t\tcout << \"-1\\n\";\n\t\treturn;\n\t}\n\tif (p > 2 * s){\n\t\tfor (int i = 1; i <= 50000; i++){\n\t\t\tif (p * i == (2 + 2 * i) * s){\n\t\t\t\tcout << i << '\\n';\n\t\t\t\tfor (int j = 0; j < i; j++){\n\t\t\t\t\tcout << \"0 \" << j << '\\n';\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcout << \"-1\\n\";\n\t\treturn;\n\t}\n\n\tint k = 0;\n\twhile(p > 2){\n\t\tp -= 2;\n\t\ts -= 1;\n\t\tk++;\n\t}\n\n\tif (p == 2){\n\t\tcout << 4 * s * s + 4 * s * k << '\\n';\n\t\tfor (int i = 0; i < 2 * s; i++){\n\t\t\tfor (int j = 0; j < 2 * s; j++){\n\t\t\t\tcout << i << ' ' << j << '\\n';\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < 4 * s * k; i++){\n\t\t\tcout << 0 << ' ' << 2 * s + i << '\\n';\n\t\t}\n\t}\n\telse{\n\t\tcout << 16 * s * s + 16 * s * k << '\\n';\n\t\tfor (int i = 0; i < 4 * s; i++){\n\t\t\tfor (int j = 0; j < 4 * s; j++){\n\t\t\t\tcout << i << ' ' << j << '\\n';\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < 16 * s * k; i++){\n\t\t\tcout << 0 << ' ' << 4 * s + i << '\\n';\n\t\t}\n\t}\n}\n \nsigned main()\n{\n\tios_base::sync_with_stdio(false);\n\tcin.tie(0);\n\tcout.tie(0);\n \n\tint tests = 1;\n\tcin >> tests;\n\tfor (int test = 0; test < tests; test++){\n        solve();\n\t}\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2111",
    "index": "G",
    "title": "Divisible Subarrays",
    "statement": "\\textbf{Technically, this is an interactive problem.}\n\nAn array $a$ of $m$ numbers is called divisible if at least one of the following conditions holds:\n\n- There exists an index $i$ ($1 \\le i < m$) and an integer $x$ such that for all indices $j$ ($j \\le i$), it holds that $a_{j} \\le x$ and for all indices $k$ ($k > i$), it holds that $a_{k} > x$.\n- There exists an index $i$ ($1 \\le i < m$) and an integer $x$ such that for all indices $j$ ($j \\le i$), it holds that $a_{j} > x$ and for all indices $k$ ($k > i$), it holds that $a_{k} \\le x$.\n\nYou are given a permutation $p$ of integers $1, 2, \\dots, n$. Your task is to answer queries of the following form fast: if we take only the segment [$l$, $r$] from the permutation, that is, the numbers $p_{l}, p_{l + 1}, \\dots, p_{r}$, is this subarray of numbers divisible?\n\nQueries will be submitted in interactive mode in groups of $10$, meaning you will not receive the next group of queries until you output all answers for the current group.",
    "tutorial": "Solution 1: Note that you are asked to solve the problem \"online\". This means there is some simple \"offline\" solution that is being cut off. In other words, the problem can be solved more easily if you could answer the queries in an arbitrary order. Let's iterate over $x$ in an increasing order. Maintain the following binary array $b$: $b_i$ is equal to $0$ if $p_i \\le x$, and $1$ if $p_i > x$. When you move from $x$ to $x+1$, find $x+1$ in the permutation and change the corresponding value in $b$ from $1$ to $0$. Then, the segment from $l$ to $r$ is divisible by the value $x$ if the corresponding subsegment in $b$ is of the form $000\\dots0011\\dots111$ or $111\\dots1100\\dots000$, where the number of $0$s and $1$s is strictly greater than $0$. Let's consider blocks of consecutive zeros and ones (maximal by inclusion) in the array $b$. Now you can say that $l$ and $r$ must belong to neighboring blocks. Note that when moving from $x$ to $x+1$, the number of blocks in the array changes by at most $2$. That is, for all $n$ possible values of $x$, there are $O(n)$ different blocks in total. The blocks themselves can be maintained in a set of pairs. The blocks of equal elements look like $\\{(L_1, R_1], (L_2, R_2], \\dots, (L_k, R_k]\\}$. For convenience, let's store the blocks as half-intervals. Each time the blocks change, you should write down new neighboring pairs in the form of triples $(L_i, L_{i+1}, R_{i+1})$. In this interpretation, the segment $[l, r]$ is divisible if there exists a triple $(L, M, R)$ such that $L \\le l < M \\le r < R$. This check can be performed using a sweep line. For each triple, let's add two events: at time $L$, the triple is turned on; at time $M$, the triple is turned off. Let's process the events in order of increasing time. The query $[l, r]$ can be answered at time $l$. Each triple $(L, M, R)$, that is currently on, generates a half-interval $[M, R)$. So, you need to check if there is at least one half-interval that includes index $r$. This can be implemented using a segment tree. When the triple is turned on, you add $1$ on the half-interval $[M, R)$. When it is turned off, you subtract $1$. To check, you can query the value at point $r$. If the value is $0$, the answer is \"NO\"; otherwise, it is \"YES\". This algorithm solves the problem \"offline\" because it answers queries not in the order of the input but in the order of increasing $l$. You can apply the classic trick to convert the problem to \"online\". At each moment of time, you are only interested in the state of the segment tree, so you can make the tree persistent, saving a version at each moment of time. Now you can answer the queries \"online\". Overall complexity: $O((n + q) \\log n)$. Solution 2: Without loss of generality, let's check only the first condition. To check the second one, you can reverse the array (and transform $l$ and $r$ accordingly) and check the first condition. Now let's restate the condition as follows: there exists an index $i$ such that the maximum to the left of $i$ (inclusive) is less than or equal to the minimum to the right of $i$ (exclusive). Let's learn to check if the array $a$ is divisible in a smarter way than by iterating through all possible $i$ and checking the maximum and minimum. Let's fix the index of the maximum in the left half, let it be $L$. Where can the cut $i$ be? All values in the right half must be greater than $a_L$. That is, let's find the index of the nearest number to the right of $L$ that is greater than $a_L$. Let this be index $j$. Then all values on indices from $L$ to $j$ (exclusive) must belong to the left half. The index $j$ cannot belong to the left half, as $a_j > a_L$, and it's been fixed that $a_L$ is the maximum. Thus, for each prefix maximum (since the left half is a prefix of the array $a$), there is only one candidate for the cut -the index before the next prefix maximum. First, let's precompute the index of the nearest greater number to the right for each element. This can be done using a monotonic stack by traversing from right to left. Let's call this $\\mathit{nxt}_t$ for each index $t$. Then the solution should go as follows. Let's try to answer the query. Find the first and second prefix maxima on the segment $[l, r]$. Let them be at indices $t$ and $\\mathit{nxt}_t$, respectively. Check that $\\mathit{nxt}_t$ is a valid cut for $[l, r]$, by ensuring that all values on indices from $\\mathit{nxt}_t$ to $r$ are strictly greater than $a_t$. If this is not the case, move on to the second and third prefix maxima ($\\mathit{nxt}_t$ and $\\mathit{nxt}_{\\mathit{nxt}_t}$). And so on. If the next prefix maximum lies to the right of $r$, and no pair of neighboring prefix maxima fits, then the answer is \"NO\". Obviously, you can make $O(n)$ of these jumps in the worst case, so for now, the solution is too slow. Ideally, you would like to replace trivial jumps with the binary lifting to answer queries in $O(\\log n)$. However, for this, you want to have a condition that can be used to check the cuts in bulk. That is, to perform the check simultaneously for $2^k$ cuts. Such a condition can be stated as follows. Once again, let there be a prefix maximum at index $t$ and the next prefix maximum at index $\\mathit{nxt}_t$. Then for all indices from $\\mathit{nxt}_t$ to $r$, all values must be greater than $a_t$. In other words, the nearest number to the right of $\\mathit{nxt}_t$ that is less than $a_t$ must lie strictly to the right of $r$. Great, now you can save this index of the nearest number in the binary lifting. Let's call it $\\mathit{val}_t$. To check many cuts at once, you can do the following: if at least one of the values $\\mathit{val}_t$ is greater than $r$, then the answer is \"YES\". That is, if the maximum of them is greater than $r$, then the answer is \"YES\". Thus, you can also save the maximum in the binary lifting. The only thing left is to learn how to find the nearest number to the right of $\\mathit{nxt}_t$ that is less than $a_t$. This can also be done using a monotonic stack with a sweep line. In the first pass, let's find the values $\\mathit{nxt}_t$ for all $t$ with an increasing monotonic stack (the next larger, the next larger after that, and so on). In the second pass from right to left, maintain a decreasing monotonic stack. To find the nearest number to the right of $\\mathit{nxt}_t$ that is less than $a_t$, you can perform a binary search on the stack built for index $\\mathit{nxt}_t$. After these two passes with the monotonic stack, you finally have all the information needed for the binary lifting. Calculate the binary lifting, while saving the maximum of $\\mathit{val}$ over $2^k$ jumps. Then you can answer the query as follows. Start from index $l$. Let $\\mathit{nxt}[l][k]$ be the index after $2^k$ jumps, and $\\mathit{val}[l][k]$ be the minimum over the corresponding $2^k$ jumps. If $\\mathit{nxt}[l][k] > r$, decrease $k$. If $k = -1$, the answer is \"NO\". Otherwise, if $\\mathit{val}[l][k] > r$, the answer is \"YES\". Otherwise, set $l = \\mathit{nxt}[l][k]$ and continue checking. Overall complexity: $O((n + q) \\log n)$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define forn(i, n) for (int i = 0; i < int(n); ++i)\n\nconst int INF = 1e9;\nconst int LOGN = 18;\n\nstruct solver{\n    int n;\n    vector<int> p;\n\n    solver(const vector<int> &p) : p(p){\n        n = p.size();\n        build();\n    }\n\n    vector<int> nxtmn, nxtmx;\n\n    vector<vector<int>> up;\n    vector<vector<int>> mx;\n\n    void build(){\n        nxtmx.resize(n);\n        vector<int> stmn, stmx;\n        for (int i = n - 1; i >= 0; --i){\n            while (!stmx.empty() && p[stmx.back()] < p[i])\n                stmx.pop_back();\n            nxtmx[i] = (stmx.empty() ? n : stmx.back());\n            stmx.push_back(i);\n        }\n        vector<vector<int>> qr(n + 1);\n        forn(i, n) qr[nxtmx[i]].push_back(i);\n        nxtmn.assign(n, n);\n        for (int i = n - 1; i >= 0; --i){\n            while (!stmn.empty() && p[stmn.back()] > p[i])\n                stmn.pop_back();\n            stmn.push_back(i);\n            for (int j : qr[i]){\n                int l = 0, r = int(stmn.size()) - 1;\n                while (l <= r){\n                    int m = (l + r) / 2;\n                    if (p[stmn[m]] < p[j]){\n                        nxtmn[j] = stmn[m];\n                        l = m + 1;\n                    }\n                    else{\n                        r = m - 1;\n                    }\n                }\n            }\n        }\n        up.assign(n + 1, vector<int>(LOGN));\n        mx.assign(n + 1, vector<int>(LOGN));\n        forn(i, n){\n            up[i][0] = nxtmx[i];\n            mx[i][0] = nxtmn[i];\n        }\n        up[n][0] = n;\n        mx[n][0] = 0;\n        for (int j = 1; j < LOGN; ++j) forn(i, n + 1){\n            up[i][j] = up[up[i][j - 1]][j - 1];\n            mx[i][j] = max(mx[i][j - 1], mx[up[i][j - 1]][j - 1]);\n        }\n    }\n\n    bool query(int l, int r){\n        int v = l;\n        for (int i = LOGN - 1; i >= 0; --i){\n            if (up[v][i] >= r) continue;\n            if (mx[v][i] >= r) return true;\n            v = up[v][i];\n        }\n        return false;\n    }\n};\n\nint main(){\n#ifdef _DEBUG\n    freopen(\"input.txt\", \"r\", stdin);\n#endif\n    cin.tie(0);\n    ios::sync_with_stdio(false);\n    int n;\n    cin >> n;\n    vector<vector<int>> p(2, vector<int>(n));\n    forn(i, n){\n        cin >> p[0][i];\n        --p[0][i];\n    }\n    p[1] = p[0];\n    reverse(p[1].begin(), p[1].end());\n    solver p0(p[0]);\n    solver p1(p[1]);\n    int m;\n    cin >> m;\n    forn(i, m){\n\t\tif (i % 10 == 0){\n\t\t\tcout.flush();\n\t\t}\n        int l, r;\n        cin >> l >> r;\n        --l; -- r;\n        bool ans = p0.query(l, r + 1) || p1.query(n - r - 1, n - l);\n        cout << (ans ? \"YES\\n\" : \"NO\\n\");\n    }\n    cout.flush();\n}",
    "tags": [
      "binary search",
      "bitmasks",
      "brute force",
      "data structures",
      "interactive"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2113",
    "index": "A",
    "title": "Shashliks",
    "statement": "You are the owner of a popular shashlik restaurant, and your grill is the heart of your kitchen. However, the grill has a peculiarity: after cooking each shashlik, its temperature drops.\n\nYou need to cook as many portions of shashlik as possible, and you have an unlimited number of portions of two types available for cooking:\n\n- The first type requires a temperature of at least $a$ degrees at the start of cooking, and after cooking, the grill's temperature decreases by $x$ degrees.\n- The second type requires a temperature of at least $b$ degrees at the start of cooking, and after cooking, the grill's temperature decreases by $y$ degrees.\n\nInitially, the grill's temperature is $k$ degrees. Determine the maximum total number of portions of shashlik that can be cooked.\n\nNote that the grill's temperature can be negative.",
    "tutorial": "Notice that it is beneficial for us to cook the portion of barbecue that we can prepare and, at the same time, after cooking it, the temperature drops by the smallest amount. Indeed, the higher the current temperature of the grill, the more portions of barbecue we can prepare. Therefore, the complete solution is as follows-let us cook the maximum possible number of portions of barbecue for which the decrease in grill temperature after cooking is minimal. After that, we cook the maximum possible number of portions of the second type of barbecue.",
    "code": "#include <iostream>\n\nusing namespace std;\n\nvoid solve() {\n    int t, a, b, x, y;\n    cin >> t >> a >> b >> x >> y;\n    auto solve = [&](int t, int a, int b, int x, int y) {\n        int cur = 0;\n        cur += max((t - a + x) / x, 0);\n        t -= max((t - a + x) / x, 0) * x;\n        cur += max((t - b + y) / y, 0);\n        return cur;\n    };\n    cout << max(solve(t, a, b, x, y), solve(t, b, a, y, x)) << endl;\n}\n\nsigned main() {\n    int q = 1;\n    cin >> q;\n    while (q --> 0)\n        solve();\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2113",
    "index": "B",
    "title": "Good Start",
    "statement": "The roof is a rectangle of size $w \\times h$ with the bottom left corner at the point $(0, 0)$ on the plane. Your team needs to completely cover this roof with identical roofing sheets of size $a \\times b$, with the following conditions:\n\n- The sheets cannot be rotated (not even by $90^\\circ$).\n- The sheets must not overlap (but they can touch at the edges).\n- The sheets can extend beyond the boundaries of the rectangular roof.\n\nA novice from your team has already placed two such sheets on the roof in such a way that the sheets \\textbf{do not overlap} and each of them \\textbf{partially covers the roof}.\n\nYour task is to determine whether it is possible to completely tile the roof without removing either of the two already placed sheets.",
    "tutorial": "Let $x_1 \\neq x_2, y_1 \\neq y_2$. We will show that the necessary and sufficient condition to tile the roof is $(x_2 - x_1)~\\text{mod}~a = 0$ or $(y_2 - y_1)~\\text{mod}~b = 0$. If this condition is satisfied, then we can tile the roof either \"by columns\" or \"by rows\". On the other hand, suppose there is some tiling, then some rectangle covers the cell $(x_1 - 1, y_1)$ and either it is in the same column as the first polygon, or it also covers the cell $(x_1 - 1, y_1 - 1)$. If the second case occurs, note that the rectangle covering the cell $(x_1, y_1 - 1)$ must be in the same row as it. Thus, any tiling is either by rows or by columns, and our condition must be satisfied. In the cases $x_1 = x_2$ or $y_1 = y_2$, note that the tiling must necessarily be by rows or columns, respectively. This follows from the reasoning described earlier. The final solution, taking into account the cases described, looks as follows: if $(x_1 \\neq x_2~\\text{and}~(x_2 - x_1)~\\text{mod}~a = 0)$ $(y_1 \\neq y_2~\\text{and}~(y_2 - y_1)~\\text{mod}~b = 0)$",
    "code": "def solve():\n    w, h, a, b = map(int, input().split())\n    x1, y1, x2, y2 = map(int, input().split())\n \n    if x1 == x2:\n        if abs(y1 - y2) % b == 0:\n            return \"Yes\"\n        else:\n            return \"No\"\n \n    if y1 == y2:\n        if abs(x1 - x2) % a == 0:\n            return \"Yes\"\n        else:\n            return \"No\"\n \n    if (x1 - x2) % a == 0 or (y1 - y2) % b == 0:\n        return \"Yes\"\n    return \"No\"\n \nt = int(input())\nfor _ in range(t):\n    print(solve())",
    "tags": [
      "constructive algorithms",
      "math"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2113",
    "index": "C",
    "title": "Smilo and Minecraft",
    "statement": "The boy Smilo is playing Minecraft! To prepare for the battle with the dragon, he needs a lot of golden apples, and for that, he requires a lot of gold. Therefore, Smilo goes to the mine.\n\nThe mine is a rectangular grid of size $n \\times m$, where each cell can be either gold ore, stone, or an empty cell. Smilo can blow up dynamite in any empty cell. When dynamite explodes in an empty cell with coordinates $(x, y)$, all cells within a square of side $2k + 1$ centered at cell $(x, y)$ become empty. If gold ore was located \\textbf{strictly inside} this square (not on the boundary), it disappears. However, if the gold ore was on the boundary of this square, Smilo collects that gold.\n\nDynamite can only be detonated inside the mine, but the explosion square can extend beyond the mine's boundaries.\n\nDetermine the maximum amount of gold that Smilo can collect.",
    "tutorial": "Let us consider the first explosion. Note that all the gold ore that was inside this square will be lost. However, observe that all the remaining gold ore in the mine will be obtained for sure. Indeed, we make explosions first in all the cells on the border of the square with side $3$ and center at the point of the first explosion, then on the border of the square with side $5$, $7$, and so on. Thus, the problem reduces to minimizing the loss of gold during the first explosion. To do this, simply iterate over the possible locations of the first explosion and keep track of the sum in the current explosion square, which can be done using prefix sums.",
    "code": "#include <algorithm>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <random>\n#include <chrono>\n#include <cassert>\n#include <numeric>\n#include <bitset>\n#include <iomanip>\n#include <queue>\n#include <unordered_set>\n#include <fstream>\n#include <random>\n\nusing namespace std;\n\nusing ll = long long;\n\nmt19937 gen(chrono::steady_clock::now().time_since_epoch().count());\nconst int MAXN = 500;\nint sum[MAXN + 1][MAXN + 1];\n\nint n, m, k;\nint check(int i, int mx) {\n\treturn min(max(i, 0), mx);\n}\n\nint pref(int i, int j) {\n\treturn sum[check(i, n)][check(j, m)];\n}\n\nvoid solve() {\n\tcin >> n >> m >> k; k--;\n\tvector<string> mine(n);\n\tint all_gold = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tcin >> mine[i];\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tall_gold += (mine[i][j] == 'g');\n\t\t}\n\t}\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tsum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + (mine[i][j] == 'g');\n\t\t}\n\t}\n\tint ans = all_gold;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < m; j++) {\n\t\t\tif (mine[i][j] == '.') {\n\t\t\t\tint a = i - k, b = i + k + 1, c = j - k, d = j + k + 1;\n\t\t\t\tans = min(ans, pref(b, d) - pref(a, d) - pref(b, c) + pref(a, c));\n\t\t\t}\n\t\t}\n\t}\n\tcout << all_gold - ans << \"\\n\";\n}\n\nint main() {\n\tios_base::sync_with_stdio(false); cin.tie(0);\n\tint t = 1;\n\tcin >> t;\n\twhile (t--) {\n\t\tsolve();\n\t}\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "greedy"
    ],
    "rating": 1700
  },
  {
    "contest_id": "2113",
    "index": "D",
    "title": "Cheater",
    "statement": "You are playing a new card game in a casino with the following rules:\n\n- The game uses a deck of $2n$ cards with different values.\n- The deck is evenly split between the player and the dealer: each receives $n$ cards.\n- Over $n$ rounds, the player and the dealer simultaneously play one top card from their hand. The cards are compared, and the point goes to the one whose card has a higher value. The winning card is removed from the game, while the losing card is returned to the hand \\textbf{and placed on top of the other cards} in the hand of the player who played it.\n\nNote that the game always lasts \\textbf{exactly} $n$ rounds.\n\nYou have tracked the shuffling of the cards and know the order of the cards in the dealer's hand (from top to bottom). You want to maximize your score, so you can swap any two cards in your hand \\textbf{no more than once} (to avoid raising suspicion).\n\nDetermine the maximum number of points you can achieve.",
    "tutorial": "Let us consider all prefix minimums, and let their positions be $k_{1}, k_{2}, \\ldots, k_{s}$. Note that if at some round the card $a_{k_{j}}$ wins ($a_{k_{j}} > b_{t}$), then the cards $a_{k_{j} + 1}, a_{k_{j} + 2}, \\ldots, a_{k_{j + 1}}$ will also win, since all of them have a nominal value greater than $a_{k_{j}}$. Since the answer is a monotonic function, we use binary search on the answer. For a fixed prefix length of the player's cards, we replace the minimum on this prefix with the maximum on the remaining suffix and simulate the game.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\n#define sz(x) (int) ((x).size())\n#define all(x) (x).begin(), (x).end()\n#define rall(x) (x).rbegin(), (x).rend()\n\ntypedef long long ll;\ntypedef long double ld;\ntypedef pair<int, int> pii;\ntypedef pair<ll, ll> pll;\n\nconst char en = '\\n';\nconst int INF = 1e9 + 7;\nconst ll INFLL = 1e18;\n\nmt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n\n#ifdef LOCAL\n#include \"debug.h\"\n#define numtest(x) cerr << \"Test #\" << (x) << \": \" << endl;\n#else\n#define debug(...) 42\n#define numtest(x) 42\n#endif\n\nint merge(const vector<int> &a, const vector<int> &b) {\n    int n = sz(a);\n    int res = 0;\n    for (int c = 0, i = 0, j = 0; c < n; ++c) {\n        if (a[i] > b[j]) {\n            ++res;\n            ++i;\n        } else if (a[i] < b[j]) {\n            ++j;\n        } else {\n            assert(0);\n        }\n    }\n    return res;\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n);\n    for (int i = 0; i < n; ++i) {\n        cin >> a[i];\n    }\n    for (int i = 0; i < n; ++i) {\n        cin >> b[i];\n    }\n    vector<int> pref_min(n), suf_max(n);\n    pref_min[0] = 0;\n    for (int i = 1; i < n; ++i) {\n        pref_min[i] = pref_min[i - 1];\n        if (a[i] < a[pref_min[i - 1]]) {\n            pref_min[i] = i;\n        }\n    }\n    suf_max[n - 1] = n - 1;\n    for (int i = n - 2; i >= 0; --i) {\n        suf_max[i] = suf_max[i + 1];\n        if (a[i] > a[suf_max[i + 1]]) {\n            suf_max[i] = i;\n        }\n    }\n    int cur = merge(a, b);\n    int l = cur, r = n;\n    while (r - l > 1) {\n        int m = l + (r - l) / 2;\n        swap(a[pref_min[m - 1]], a[suf_max[m]]);\n        if (merge(a, b) >= m) {\n            l = m;\n        } else {\n            r = m;\n        }\n        swap(a[pref_min[m - 1]], a[suf_max[m]]);\n    }\n    cout << l << en;\n}\n\nint32_t main() {\n    int tests = 1;\n#ifdef LOCAL\n    freopen(\"input.txt\", \"r\", stdin);\n    tests = 1;\n#else\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n#endif\n    cin >> tests;\n    for (int testcase = 1; testcase <= tests; ++testcase) {\n        solve();\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "constructive algorithms",
      "greedy",
      "implementation"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2113",
    "index": "E",
    "title": "From Kazan with Love",
    "statement": "Marat is a native of Kazan. Kazan can be represented as an undirected tree consisting of $n$ vertices. In his youth, Marat often got into street fights, and now he has $m$ enemies, numbered from $1$ to $m$, living in Kazan along with him.\n\nEvery day, all the people living in the city go to work. Marat knows that the $i$-th of his enemies lives at vertex $a_i$ and works at vertex $b_i$. He himself lives at vertex $x$ and works at vertex $y$. It is guaranteed that $a_i \\ne x$.\n\nAll enemies go to work via the shortest path and leave their homes at time $1$. That is, if we represent the shortest path between vertices $a_i$ and $b_i$ as $c_1, c_2, c_3, \\ldots, c_k$ (where $c_1 = a_i$ and $c_k = b_i$), then at the moment $p$ ($1 \\le p \\le k$), the enemy numbered $i$ will be at vertex $c_p$.\n\nMarat really does not want to meet any of his enemies at the same vertex at the same time, as this would create an awkward situation, but they \\textbf{can meet on an edge}. Marat also leaves his home at time $1$, and at each subsequent moment in time, he can either move to an adjacent vertex or stay at his current one.\n\nNote that Marat can only meet the $i$-th enemy at the moments $2, 3, \\ldots, k$ (where $c_1, c_2, \\ldots, c_k$ is the shortest path between vertices $a_i$ and $b_i$). In other words, starting from the moment after the enemy reaches work, Marat \\textbf{can no longer meet him}.\n\nHelp Marat find the earliest moment in time when he can reach work without encountering any enemies along the way, or determine that it is impossible.",
    "tutorial": "Lemma: If the answer $\\neq$ -1, then it does not exceed $2 \\times N + 1$. Proof: Let the optimal path be $s_1 = x, s_2, s_3, \\cdots, s_k = y$. Then, at time $N+1$, all the enemies have already reached work, and we can go from $s_{N+1}$ to $s_{k}$ in $\\leq N$ moves $\\Rightarrow k \\leq 2 \\times N + 1$. Let us call a moment $t$ for a vertex $v$ bad if at this moment there is an enemy at this vertex. Obviously, the total number of bad moments over all vertices is $\\leq N \\times M$. Then the problem can be solved in $O(N^2)$: Let us define $dp_{v, t}$ - whether Marat can be at vertex $v$ at time $t$. Initially, $dp_{x, 1} = 1$. For each $t$, we make transitions by iterating over vertices, and if $dp_{v, t} = 1$, then we can set $dp_{u, t+1} = 1$ for all neighbors $u$ of $v$, including $v$ itself. And if at time $t$ there is an enemy at vertex $v$, then we must set $dp_{v, t} = 0$. The answer is the minimal $t$ such that $dp_{y, t} = 1$. Solution in $O(N \\times M)$: Let us maintain a set $S_t$ of vertices where Marat can potentially be at time $t$, i.e., for which $dp_{v, t} = 1$. Clearly, $S_{1} = \\{x\\}$. How do $S_t$ and $S_{t+1}$ differ? If at time $t+1$ there is an enemy at vertex $v$, then $v$ definitely does not belong to $S_{t+1}$ Otherwise, if $v \\in S_t$ then $v \\in S_{t+1}$ Also, if any neighbor of vertex $v$ belongs to $S_t$, then $v \\in S_{t+1}$ The set $S$ is easy to update when moving from $t$ to $t+1$. We are interested in two types of vertices: 1. Those that have an enemy at time $t+1$ 2. Those that are not in $S_t$, but have a neighbor in $S_t$ Vertices of type 1 are easy to process. For example, we can ignore their existence, recalculate $S_{t+1}$, and remove all type 1 vertices, having previously recorded them in a separate list. In total, over all $t$, the number of type 1 vertices is at most $N \\times M$, since their number does not exceed the sum of the lengths of all enemy paths. Vertices of type 2 are processed as follows: when some vertex enters the set (and was not in it in the previous moment), we mark all its neighbors in the tree as \"candidates\" for addition. Also, we add to the candidates all vertices that were of type 1 in the previous moment - these are vertices that could be in the candidate list now, but were removed from it in the previous year. Then we try to add all candidates to $S$, and clear the list. In total, there are $O(N \\times M)$ candidates, since each vertex can \"enter\" the set no more than $M+1$ times. (To \"enter\", it must have \"left\" before. This could have happened no more than $M$ times.) Therefore, its list of neighbors is added to the candidates no more than $M+1$ times. The sum of the lengths of the neighbor lists $=$ the sum of the degrees of the vertices $=$ $2 \\times N = O(N)$ Total: $O(N \\times M)$.",
    "code": "//#pragma GCC optimize(\"Ofast\")\n\n#include \"bits/stdc++.h\"\n\n#define rep(i, n) for (int i = 0; i < (n); ++i)\n#define rep1(i, n) for (int i = 1; i < (n); ++i)\n#define rep1n(i, n) for (int i = 1; i <= (n); ++i)\n#define repr(i, n) for (int i = (n) - 1; i >= 0; --i)\n//#define pb push_back\n#define eb emplace_back\n#define all(a) (a).begin(), (a).end()\n#define rall(a) (a).rbegin(), (a).rend()\n#define each(x, a) for (auto &x : a)\n#define ar array\n#define vec vector\n#define range(i, n) rep(i, n)\n\nusing namespace std;\n\nusing ll = long long;\nusing ull = unsigned long long;\nusing ld = double;\nusing str = string;\nusing pi = pair<int, int>;\nusing pl = pair<ll, ll>;\n\nusing vi = vector<int>;\nusing vl = vector<ll>;\nusing vpi = vector<pair<int, int>>;\nusing vvi = vector<vi>;\n\nint Bit(int mask, int b) { return (mask >> b) & 1; }\n\ntemplate<class T>\nbool ckmin(T &a, const T &b) {\n    if (b < a) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n\ntemplate<class T>\nbool ckmax(T &a, const T &b) {\n    if (b > a) {\n        a = b;\n        return true;\n    }\n    return false;\n}\n\n// [l, r)\ntemplate<typename T, typename F>\nT FindFirstTrue(T l, T r, const F &predicat) {\n    --l;\n    while (r - l > 1) {\n        T mid = l + (r - l) / 2;\n        if (predicat(mid)) {\n            r = mid;\n        } else {\n            l = mid;\n        }\n    }\n    return r;\n}\n\n\ntemplate<typename T, typename F>\nT FindLastFalse(T l, T r, const F &predicat) {\n    return FindFirstTrue(l, r, predicat) - 1;\n}\n\nconst int INFi = 2e9;\nconst ll INF = 2e18;\n\nvoid solve() {\n    int n, m, x, y; cin >> n >> m >> x >> y;\n    x--;\n    y--;\n    vvi g(n);\n    rep(_, n - 1) {\n        int u, v; cin >> u >> v;\n        u--;\n        v--;\n        g[u].push_back(v);\n        g[v].push_back(u);\n    }\n\n    vector<vi> block;\n\n    vi path;\n    auto dfs = [&] (auto &&self, int v, int p, int t) -> bool {\n        path.push_back(v);\n        if (v == t) return true;\n        for(auto &u : g[v]) {\n            if (u == p) continue;\n            if (self(self, u, v, t)) return true;\n        }\n        path.pop_back();\n        return false;\n    };\n\n    rep(i, m) {\n        int a, b; cin >> a >> b;\n        a--;\n        b--;\n\n        dfs(dfs, a, -1, b);\n        assert(!path.empty());\n\n        if (block.size() < path.size()) block.resize(path.size());\n\n        rep(j, path.size()) block[j].push_back(path[j]);\n        path.clear();\n    }\n\n    vector<bool> ok(n, false);\n    vi q;\n    q.push_back(x);\n\n    vector<bool> cur(n, false);\n    vi was(n, -1);\n    for(int t = 0;;++t) {\n\n        if (t < block.size()) for(auto &u : block[t]) cur[u] = true;\n        vi nxt;\n        for(auto &v : q) {\n            if (ok[v] || cur[v] || was[v] == t) continue;\n            was[v] = t;\n            bool nei = 0;\n            for(auto &u : g[v]) nei |= ok[u];\n            if (t && !nei) continue;\n            nxt.push_back(v);\n        }\n\n        q.clear();\n        if (t < block.size()) {\n            for(auto &u : block[t]) {\n                cur[u] = false;\n                if (ok[u]) {\n                    ok[u] = false;\n                }\n                q.push_back(u);\n            }\n        }\n\n        for(auto &v : nxt) {\n            assert(!ok[v]);\n            ok[v] = true;\n            for(auto &u : g[v]) {\n                if (!ok[u]) {\n                    q.push_back(u);\n                }\n            }\n        }\n\n        if (ok[y]) {\n            cout << t + 1 << '\\n';\n            return;\n        }\n\n\n\n        if (t > (int)block.size() && q.empty()) {\n            cout << \"-1\\n\";\n            return;\n        }\n    }\n}\n\nsigned main() {\n    ios_base::sync_with_stdio(false);\n    cin.tie(0);\n    cout << setprecision(12) << fixed;\n    int t = 1;\n    cin >> t;\n    rep(_, t) {\n        solve();\n    }\n\n    return 0;\n}",
    "tags": [
      "dfs and similar",
      "graphs",
      "implementation",
      "trees"
    ],
    "rating": 2800
  },
  {
    "contest_id": "2113",
    "index": "F",
    "title": "Two Arrays",
    "statement": "You are given two arrays $a$ and $b$ of length $n$. You can perform the following operation an unlimited number of times:\n\n- Choose an integer $i$ from $1$ to $n$ and swap $a_i$ and $b_i$.\n\nLet $f(c)$ be the number of distinct numbers in array $c$. Find the maximum value of $f(a) + f(b)$. Also, output the arrays $a$ and $b$ after performing all operations.",
    "tutorial": "This problem has many different solutions. Feel free to share your ideas in the comments. Let us consider an arbitrary number $x$: If it does not appear in arrays $a$ and $b$, then it does not affect the answer in any way. If it appears exactly once, then no matter how we perform the operations, it always contributes $1$ to the answer. If it appears at least twice, then it contributes either $1$ or $2$ to the answer. If all occurrences are in one of the two arrays, the contribution is $1$, otherwise it is $2$. Thus, if $\\mathrm{cnt}_x$ is the number of occurrences of $x$ in both arrays, then its contribution does not exceed $\\min(\\mathrm{cnt}_x, 2)$. Therefore, the answer does not exceed: $\\sum \\min(\\mathrm{cnt}_x, 2)$ Solution 1 Let us build a graph on the values in the arrays. For each $i$, add an undirected edge between vertices $a_i$ and $b_i$. Now, we need to orient the edges of the graph in such a way that from each vertex of degree at least $2$ there is at least one outgoing edge, and into each vertex of degree at least $2$ there is at least one incoming edge. If the $i$-th edge is oriented from vertex $x$ to vertex $y$, then $(a_i, b_i) = (x, y)$. In each connected component, build a DFS tree rooted at an arbitrary vertex. Orient all edges of this tree from top to bottom, and orient the back edges from bottom to top. It is easy to see that in this construction, the orientation condition is satisfied for all vertices except possibly the root. For the root, the condition is not satisfied only if its degree is at least $2$ and there is no back edge entering it. In this case, the root has at least two subtrees, so it is enough to choose any of them and reverse all the edges in it. This gives a construction that achieves the bound, and can be built in $\\mathcal{O}(n)$. Solution 2 Consider all occurrences of the number $x$ in both arrays. Split them into pairs. If there is an odd number of occurrences, leave one occurrence unpaired. For each pair, replace the occurrence of $x$ in it with some new number, different from all existing ones. Thus, we obtain two arrays where each number appears at most twice. Now, build a graph similar to Solution 1. Since the degree of each vertex does not exceed $2$, it breaks up into cycles and paths. Each path can be oriented from start to end. The edges in a cycle can be oriented in one direction so that the cycle becomes directed. This gives a construction in $\\mathcal{O}(n)$.",
    "code": "#include \"bits/stdc++.h\"\n \nusing namespace std;\n \nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n);\n    for (int i = 0; i < n; i++) {\n        cin >> a[i];\n    }\n    vector<int> b(n);\n    for (int i = 0; i < n; i++) {\n        cin >> b[i];\n    }\n    vector<int> want(n);\n    auto make = [&] (int i, int x, int y) {\n        if (!want[i]) {\n            if (a[i] != x) {\n                swap(a[i], b[i]);\n            }\n            want[i] = 1;\n        }\n    };\n    const int N = 2 * n + 22;\n    vector<vector<pair<int, int>>> g(N);\n    for (int i = 0; i < n; i++) {\n        g[a[i]].push_back({b[i], i});\n        g[b[i]].push_back({a[i], i});\n    }\n    vector<int> used(N);\n    auto dfs = [&] (auto&& dfs, int v, int h) -> void {\n        used[v] = h;\n        for (auto& [u, i] : g[v]) {\n            if (used[u] <= 0) {\n                make(i, v, u);\n                dfs(dfs, u, h + 1);\n            } else if (used[u] < used[v]) {\n                make(i, v, u);\n            }\n        }\n    };\n    for (int i = 0; i < N; i++) {\n        if (used[i] == 0 && int(g[i].size()) == 1) {\n            dfs(dfs, i, 1);\n        }\n    }\n    int rt;\n    auto find = [&] (auto&& find, int v, int pr) -> void {\n        used[v] = -1;\n        for (auto& [u, i] : g[v]) {\n            if (used[u] == 0) {\n                find(find, u, i);\n            } else if (i != pr) {\n                rt = u;\n            }\n        }\n    };\n    for (int i = 0; i < N; i++) {\n        if (used[i] == 0 && !g[i].empty()) {\n            rt = -1;\n            find(find, i, -1);\n            dfs(dfs, rt, 1);\n        }\n    }\n    cout << set<int>(a.begin(), a.end()).size() + set<int>(b.begin(), b.end()).size() << '\\n';\n    for (int i = 0; i < n; i++) {\n        cout << a[i] << \" \";\n    }\n    cout << '\\n';\n    for (int i = 0; i < n; i++) {\n        cout << b[i] << \" \";\n    }\n    cout << '\\n';\n}\n \nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        solve();\n    }\n}",
    "tags": [
      "constructive algorithms",
      "dfs and similar",
      "graphs",
      "math"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2114",
    "index": "A",
    "title": "Square Year",
    "statement": "One can notice the following remarkable mathematical fact: the number $2025$ can be represented as $(20+25)^2$.\n\nYou are given a year represented by a string $s$, consisting of exactly $4$ characters. Thus, leading zeros are allowed in the year representation. For example, \"0001\", \"0185\", \"1375\" are valid year representations. You need to express it in the form $(a + b)^2$, where $a$ and $b$ are \\textbf{non-negative integers}, or determine that it is impossible.\n\nFor example, if $s$ = \"0001\", you can choose $a = 0$, $b = 1$, and write the year as $(0 + 1)^2 = 1$.",
    "tutorial": "To solve this problem it was enough to check whether number $s$ is the square of some integer $x$. If yes, then the answer to the set of input data could be a pair of numbers $a=0$, $b=x$, or any other existing partition of number $x$ into a pair of non-negative summands. Otherwise, the answer to the problem is - $-1$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    int sq = ceil(sqrt(n));\n    if (sq * sq == n) {\n        cout << 0 << ' ' << sq << \"\\n\";\n    } else {\n        cout << \"-1\\n\";\n    }\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while (t--) solve();\n}",
    "tags": [
      "binary search",
      "brute force",
      "math"
    ],
    "rating": 800
  },
  {
    "contest_id": "2114",
    "index": "B",
    "title": "Not Quite a Palindromic String",
    "statement": "Vlad found a binary string$^{\\text{∗}}$ $s$ of even length $n$. He considers a pair of indices ($i, n - i + 1$), where $1 \\le i < n - i + 1$, to be good if $s_i = s_{n - i + 1}$ holds true.\n\nFor example, in the string '010001' there is only $1$ good pair, since $s_1 \\ne s_6$, $s_2 \\ne s_5$, and $s_3=s_4$. In the string '0101' there are no good pairs.\n\nVlad loves palindromes, but not too much, so he wants to rearrange some characters of the string so that there are exactly $k$ good pairs of indices.\n\nDetermine whether it is possible to rearrange the characters in the given string so that there are exactly $k$ good pairs of indices ($i, n - i + 1$).\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A string $s$ is called binary if it consists only of the characters '0' and '1'\n\\end{footnotesize}",
    "tutorial": "To begin, let's solve a simpler problem: we will find the minimum and maximum possible number of good pairs. To achieve the minimum number of pairs, we will place all zeros at the beginning of the string and all ones at the end. Then, if the number of zeros is $c_0$ and the number of ones is $c_1$, the number of good pairs will be $\\max(c_0, c_1) - \\frac{n}{2}$ (they will be in the middle of the string). The maximum number of good pairs is equal to $\\lfloor\\frac{c_0}{2}\\rfloor + \\lfloor\\frac{c_1}{2}\\rfloor$. For $k$ to be achievable, it must obviously be no less than the minimum and no more than the maximum possible number of pairs; this condition is necessary but not sufficient. For example, in a string of $2$ zeros and $2$ ones, you can obtain $0$ or $2$ good pairs, but you cannot obtain one. This happens because any swap of symbols changes the number of good pairs either by $0$ or by $2$. Let's demonstrate the results of swaps between the first elements of the pairs: 00 and 10 $\\rightarrow$ 10 and 00: the number of good pairs did not change; 00 and 11 $\\rightarrow$ 10 and 01: the number of good pairs changed by $2$; 01 and 10 $\\rightarrow$ 11 and 00: the number of good pairs changed by $2$; 01 and 11 $\\rightarrow$ 11 and 01: the number of good pairs did not change; other pairs are either symmetrical to those shown or do not change the string.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(time(nullptr));\n\nconst int inf = 1e9;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nvoid solve(int tc){\n    int n, k;\n    cin >> n >> k;\n    string s;\n    cin >> s;\n    vector<int> cnt(2);\n    for(char c: s){\n        cnt[c - '0']++;\n    }\n    int mn = max(cnt[0], cnt[1]) - n / 2;\n    int mx = cnt[0] / 2 + cnt[1] / 2;\n    if(k >= mn && (k - mn) % 2 == 0 && k <= mx) cout << \"YES\";\n    else cout << \"NO\";\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "math"
    ],
    "rating": 900
  },
  {
    "contest_id": "2114",
    "index": "C",
    "title": "Need More Arrays",
    "statement": "Given an array $a$ and $n$ integers. It is sorted in non-decreasing order, that is, $a_i \\le a_{i + 1}$ for all $1 \\le i < n$.\n\nYou can remove any number of elements from the array (including the option of not removing any at all) without changing the order of the remaining elements. After the removals, the following will occur:\n\n- $a_1$ is written to a new array;\n- if $a_1 + 1 < a_2$, then $a_2$ is written to a new array; otherwise, $a_2$ is written to the same array as $a_1$;\n- if $a_2 + 1 < a_3$, then $a_3$ is written to a new array; otherwise, $a_3$ is written to the same array as $a_2$;\n- $\\cdots$\n\nFor example, if $a=[1, 2, 4, 6]$, then:\n\n- $a_1 = 1$ is written to the new array, resulting in arrays: $[1]$;\n- $a_1 + 1 = 2$, so $a_2 = 2$ is added to the existing array, resulting in arrays: $[1, 2]$;\n- $a_2 + 1 = 3$, so $a_3 = 4$ is written to a new array, resulting in arrays: $[1, 2]$ and $[4]$;\n- $a_3 + 1 = 5$, so $a_4 = 6$ is written to a new array, resulting in arrays: $[1, 2]$, $[4]$, and $[6]$.\n\nYour task is to remove elements in such a way that the described algorithm creates as many arrays as possible. If you remove all elements from the array, no new arrays will be created.",
    "tutorial": "We will be selecting elements from left to right, skipping some of them. If a new element is supposed to go into the same array as the last one we took, then skipping it will not make things worse. This is true because if we took an element equal to $x$, then skipping an element equal to $x + 1$ will allow an element equal to $x + 2$ to go into a new array instead of the previous elements. Similarly, it is always beneficial to take the first element of the array first, as the second element may be larger and the answer may worsen.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve(int tc){\n    int n;\n    cin >> n;\n    int last = -1, ans = 0;\n    for(int i = 0; i < n; ++i){\n        int a;\n        cin >> a;\n        if(a - last > 1){\n            ans++;\n            last = a;\n        }\n    }\n    cout << ans;\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy"
    ],
    "rating": 1000
  },
  {
    "contest_id": "2114",
    "index": "D",
    "title": "Come a Little Closer",
    "statement": "The game field is a matrix of size $10^9 \\times 10^9$, with a cell at the intersection of the $a$-th row and the $b$-th column denoted as ($a, b$).\n\nThere are $n$ monsters on the game field, with the $i$-th monster located in the cell ($x_i, y_i$), while the other cells are empty. No more than one monster can occupy a single cell.\n\nYou can move one monster to any cell on the field that is not occupied by another monster \\textbf{at most once} .\n\nAfter that, you must select \\textbf{one} rectangle on the field; all monsters within the selected rectangle will be destroyed. You must pay $1$ coin for each cell in the selected rectangle.\n\nYour task is to find the minimum number of coins required to destroy all the monsters.",
    "tutorial": "The minimum rectangle that we can choose must have sides of length $\\max_i(x_i) - \\min_i(x_i) + 1$ and $\\max_i(y_i) - \\min_i(y_i) + 1$, meaning that the maximum and minimum values along both axes are important. Let's consider the movement of a certain monster; we will not choose a new position but will simply examine the rectangle needed to cover the remaining ones. To find the new maximums and minimums, we can use a multiset or a similar ordered data structure. The code below will utilize a simple fact: if we remove a point with the maximum coordinate along some axis, the new maximum will become the second maximum (similarly for minimums). Thus, for each axis, we can store two minimums and two maximums. Now that we know how to find the minimum rectangle for all monsters except the current one, we just need to determine if it can fit inside this rectangle. If the area of the rectangle is equal to $n - 1$, then all the spaces inside it are already occupied, and one of the sides must be increased; otherwise, the monster can be placed inside it.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(time(nullptr));\n\nconst int inf = 1e9;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nstruct min_max{\n    int mx1, mx2, mn1, mn2;\n\n    void fix_mx(){\n        if(mx1 < mx2){\n            swap(mx1, mx2);\n        }\n    }\n    void fix_mn(){\n        if(mn1 > mn2){\n            swap(mn1, mn2);\n        }\n    }\n\n    min_max(int a, int b){\n        mx1 = mn1 = a;\n        mx2 = mn2 = b;\n        fix_mx();\n        fix_mn();\n    }\n\n    void add(int x){\n        mx2 = max(mx2, x);\n        mn2 = min(mn2, x);\n        fix_mx();\n        fix_mn();\n    }\n\n    int get_seg(int x){\n        pair<int, int> res = {mn1, mx1};\n        if(x == mn1) res.x = mn2;\n        if(x == mx1) res.y = mx2;\n        return res.y - res.x + 1;\n    }\n};\n\nvoid solve(int tc){\n    int n;\n    cin >> n;\n    vector<pair<int, int>> coord(n);\n    for(auto &e: coord){\n        cin >> e.x >> e.y;\n    }\n    if(n <= 2){\n        cout << n;\n        return;\n    }\n\n    min_max xc(coord[0].x, coord[1].x), yc(coord[0].y, coord[1].y);\n    for(int i = 2; i < n; ++i){\n        xc.add(coord[i].x);\n        yc.add(coord[i].y);\n    }\n\n    int ans = xc.get_seg(-1) * yc.get_seg(-1);\n    for(int i = 0; i < n; ++i){\n        int x = xc.get_seg(coord[i].x);\n        int y = yc.get_seg(coord[i].y);\n        if(x * y == n - 1){\n            ans = min(ans, min((x + 1) * y, x * (y + 1)));\n        }\n        else{\n            ans = min(ans, x * y);\n        }\n    }\n    cout << ans;\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if (multi)cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "greedy",
      "implementation",
      "math"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2114",
    "index": "E",
    "title": "Kirei Attacks the Estate",
    "statement": "Once, Kirei stealthily infiltrated the trap-filled estate of the Ainzbern family but was discovered by Kiritugu's familiar. Assessing his strength, Kirei decided to retreat. The estate is represented as a tree with $n$ vertices, with the \\textbf{root} at vertex $1$. Each vertex of the tree has a number $a_i$ recorded, which represents the danger of vertex $i$. Recall that a tree is a connected undirected graph without cycles.\n\nFor a successful retreat, Kirei must compute the threat value for each vertex. The threat of a vertex is equal to the \\textbf{maximum} alternating sum along the vertical path starting from that vertex. The alternating sum along the vertical path starting from vertex $i$ is defined as $a_i - a_{p_i} + a_{p_{p_i}} - \\ldots$, where $p_i$ is the parent of vertex $i$ on the path to the root (to vertex $1$).\n\nFor example, in the tree below, vertex $4$ has the following vertical paths:\n\n- $[4]$ with an alternating sum of $a_4 = 6$;\n- $[4, 3]$ with an alternating sum of $a_4 - a_3 = 6 - 2 = 4$;\n- $[4, 3, 2]$ with an alternating sum of $a_4 - a_3 + a_2 = 6 - 2 + 5 = 9$;\n- $[4, 3, 2, 1]$ with an alternating sum of $a_4 - a_3 + a_2 - a_1 = 6 - 2 + 5 - 4 = 5$.\n\n\\begin{center}\n{\\small The dangers of the vertices are indicated in red.}\n\\end{center}\n\nHelp Kirei compute the threat values for all vertices and escape the estate.",
    "tutorial": "Let's consider each vertex separately. The sign with which its danger enters the sign-variable sum depends on the parity of its index on the path. When we calculate $f(v)$ - the maximum value of the threat of the vertex, we can either stay in it or subtract the minimum value of the threat of our parent: $f(v) = \\max(a_v, a_v - g(p_v))$; $g(v) = \\min(a_v, a_v, - f(p_v))$. It is important not to forget to handle the case with the root: $f(1) = g(1) = a_1$. Thus, the values of $f$ and $g$ are computed trivially by performing a depth-first traversal of the tree. The array of values $f$ is the answer to the problem.",
    "code": "from math import inf\nfrom sys import setrecursionlimit\n\n\ndef solve(v, p, mini, maxi):\n    global res\n    res[v] = max(arr[v], mini * -1 + arr[v])\n    mini = min(arr[v], maxi * -1 + arr[v])\n    for u in gr[v]:\n        if u == p:\n            continue\n        solve(u, v, mini, res[v])\n\n\nsetrecursionlimit(400_000)\nt = int(input())\nfor _ in range(t):\n    n = int(input())\n    arr = list(map(int, input().split()))\n    gr = [[] for _ in range(n)]\n    for j in range(n - 1):\n        v, u = map(int, input().split())\n        gr[v - 1].append(u - 1)\n        gr[u - 1].append(v - 1)\n    res = [0] * n\n    solve(0, -1, 0, 0)\n    print(*res)",
    "tags": [
      "dfs and similar",
      "dp",
      "greedy",
      "trees"
    ],
    "rating": 1400
  },
  {
    "contest_id": "2114",
    "index": "F",
    "title": "Small Operations",
    "statement": "Given an integer $x$ and an integer $k$. In one operation, you can perform one of two actions:\n\n- choose an integer $1 \\le a \\le k$ and assign $x = x \\cdot a$;\n- choose an integer $1 \\le a \\le k$ and assign $x = \\frac{x}{a}$, where the value of $\\frac{x}{a}$ must be an integer.\n\nFind the minimum number of operations required to make the number $x$ equal to $y$, or determine that it is impossible.",
    "tutorial": "It is not difficult to guess that first we need to use operations of the second type to make $x$ equal to $gcd(x, y)$, and only then use operations of the first type to make it equal to $y$. That is, now we need to decompose the numbers $x/gcd(x, y)$ and $y/gcd(x, y)$ into the minimum number of factors not exceeding $k$. We will learn to find this quantity for an arbitrary number $a$. We will use dynamic programming, let $dp[i]$ be the minimum number of factors not exceeding $k$ into which we can decompose the number $i$. To find this quantity for $i$, we will iterate over the number $j$, such that $i$ is divisible by $j$ and $\\frac{i}{j} \\le k$, and we will update the value $dp[i] = \\min(dp[i], dp[j] + 1)$. It is easy to notice that this approach works in $\\mathcal{O}(a^2)$, which is too slow. To make our dynamic programming faster, we note that values of $i$ that are not divisors of $a$ are not needed. We will find all divisors of $a$, and their count is denoted as $d(a)$. For supercomposite numbers, it can be estimated as $\\mathcal{O}(\\sqrt[3]{a})$, so by using only the divisors as states, we will achieve an asymptotic complexity of $O(a^\\frac{2}{3})$.",
    "code": "#include <bits/stdc++.h>\n \n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n \ntypedef long double ld;\ntypedef long long ll;\n \nusing namespace std;\n \nmt19937 rnd(time(nullptr));\n \nconst int inf = 1e9;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nint gcd(int a, int b) {\n    return b == 0 ? a : gcd(b, a % b);\n}\n\nint get_ans(int x, int k){\n    if(x == 1) return 0;\n    vector<int> divs;\n    for(int i = 1; i * i <= x; i++){\n        if(x % i == 0){\n            divs.push_back(i);\n            divs.push_back(x / i);\n        }\n    }\n    sort(all(divs));\n    int n = divs.size();\n    vector<int> dp(n, 100);\n    dp[0] = 0;\n    for(int i = 1; i < n; i++){\n        for(int j = i - 1; j >= 0; j--){\n            if(divs[i] / divs[j] > k){\n                break;\n            }\n            if(divs[i] % divs[j] == 0) {\n                dp[i] = min(dp[i], dp[j] + 1);\n            }\n        }\n    }\n    return dp[n - 1] == 100 ? -1 : dp[n - 1];\n}\n\nvoid solve(int tc){\n    int x, y, k;\n    cin >> x >> y >> k;\n    int g = gcd(x, y);\n    x /= g;\n    y /= g;\n    int ax = get_ans(x, k);\n    int ay = get_ans(y, k);\n    if(ax == -1 || ay == -1) cout << -1;\n    else cout << ax + ay;\n}\n\nbool multi = true;\n\nsigned main() {\n    int t = 1;\n    if (multi) cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "dfs and similar",
      "dp",
      "math",
      "number theory",
      "sortings"
    ],
    "rating": 2000
  },
  {
    "contest_id": "2114",
    "index": "G",
    "title": "Build an Array",
    "statement": "Yesterday, Dima found an empty array and decided to add some integers to it. He can perform the following operation an unlimited number of times:\n\n- add any integer to the left or right end of the array.\n- then, as long as there is a pair of identical adjacent elements in the array, they will be replaced by their sum.\n\nIt can be shown that there can be at most one such pair in the array at the same time.\n\nFor example, if the array is $[3, 6, 4]$ and we add the number $3$ to the left, the array will first become $[3, 3, 6, 4]$, then the first two elements will be replaced by $6$, and the array will become $[6, 6, 4]$, and then — $[12, 4]$.\n\nAfter performing the operation \\textbf{exactly} $k$ times, he thinks he has obtained an array $a$ of length $n$, but he does not remember which operations he applied. Determine if there exists a sequence of $k$ operations that could result in the given array $a$ from an empty array, or determine that it is impossible.",
    "tutorial": "Let's start with a slow solution: we will iterate through the element that we will add first for as many operations as possible and will add the other elements to the left and right, using as many operations as possible. When adding a new number, we will also look at the number that was added before it from the same side. Let's denote the previous number as $b$ and the current number as $c$. We can add $c$ by adding $\\frac{c}{2^x}$ for some $x$, and we will find the maximum value of $x$ for which $c$ is divisible by $2^x$. However, if we only add the values $\\frac{c}{2^x}$, they may merge with $b$ if $\\frac{c}{b}$ is a power of two. In that case, in order to add $c$ without merging with $b$, we must first add $2 \\cdot b$, and only then as many elements $\\frac{c}{2^x}$ as possible. After calculating all these values, we know the maximum possible number of operations to construct the array for a fixed starting element. Now, note that if two elements merged into one after an operation, they could have been added in one operation, meaning the number of operations can always be reduced by $1$. Thus, if the maximum is greater than $k$, it is also possible to construct the array in $k$ operations. In fact, the values for some starting elements may not be entirely accurate, since more operations can be performed when adding the first two elements, but they will be counted correctly when we process the larger of the two neighboring elements as the starting one. Now, to make our solution work in $\\mathcal{O}(n \\cdot \\log{A})$ instead of $\\mathcal{O}(n^2 \\cdot \\log{A})$, we note that we are calculating the sums of additions for the same $c=a_i$, $b=a_{i \\pm 1}$ multiple times, so we can simply precompute these values on the prefix and suffix and find answers for fixed starting elements in $\\mathcal{O}(1)$.",
    "code": "#include <bits/stdc++.h>\n\n#define int long long\n#define pb emplace_back\n#define mp make_pair\n#define x first\n#define y second\n#define all(a) a.begin(), a.end()\n#define rall(a) a.rbegin(), a.rend()\n\ntypedef long double ld;\ntypedef long long ll;\n\nusing namespace std;\n\nmt19937 rnd(time(nullptr));\n\nconst int inf = 1e9;\nconst int M = 1e9 + 7;\nconst ld pi = atan2(0, -1);\nconst ld eps = 1e-6;\n\nint max_op(int a, int b) {\n    int min_part = a;\n    while (min_part % 2 == 0 && min_part / 2 != b) {\n        min_part /= 2;\n    }\n    if (min_part % 2 == 1) {\n        return a / min_part;\n    }\n    int true_min = min_part;\n    while (true_min % 2 == 0) {\n        true_min /= 2;\n    }\n    return 1 + (a - min_part) / true_min;\n}\n\nvoid solve(int tc){\n    int n, k;\n    cin >> n >> k;\n    vector<int> a(n);\n    for (int &e: a) cin >> e;\n    vector<int> pre(n, 0);\n    for (int j = 1; j < n; ++j) {\n        pre[j] = pre[j - 1] + max_op(a[j - 1], a[j]);\n    }\n    vector<int> suf(n, 0);\n    for (int j = n - 2; j >= 0; --j) {\n        suf[j] = suf[j + 1] + max_op(a[j + 1], a[j]);\n    }\n    for (int i = 0; i < n; i++) {\n        int res = max_op(a[i], 0) + pre[i] + suf[i];\n        if (res >= k) {\n            cout << \"YES\";\n            return;\n        }\n    }\n    cout << \"NO\";\n}\n\nbool multi = true;\n\nsigned main() {\n\n    int t = 1;\n    if (multi) cin >> t;\n    for (int i = 1; i <= t; ++i) {\n        solve(i);\n        cout << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dp",
      "greedy",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2115",
    "index": "A",
    "title": "Gellyfish and Flaming Peony",
    "statement": "Gellyfish hates math problems, but she has to finish her math homework:\n\nGellyfish is given an array of $n$ positive integers $a_1, a_2, \\ldots, a_n$.\n\nShe needs to do the following two-step operation until all elements of $a$ are equal:\n\n- Select two indexes $i$, $j$ satisfying $1 \\leq i, j \\leq n$ and $i \\neq j$.\n- Replace $a_i$ with $\\gcd(a_i, a_j)$.\n\nNow, Gellyfish asks you for the minimum number of operations to achieve her goal.\n\nIt can be proven that Gellyfish can always achieve her goal.",
    "tutorial": "Try to think about why Gellyfish can always achieve her goal, and ultimately what all the elements will turn into. When you've figured out Hint 1, try using dynamic programming to reach your goal. Let $g = \\gcd(a_1, a_2, \\dots, a_n)$, It can be shown that eventually all elements become $g$. Consider the assumption that eventually all numbers are $x$. Then for all $i$, there is $x\\ |\\ a_i$; this is because as $a_i := \\gcd(a_i, a_j)$, the new $a_i$ value will only be a factor of the original. It further follows that $x\\ |\\ g$. Further analysis reveals that $x$ cannot be less than $g$, no matter how it is manipulated. Thus we have $x = g$. Next we consider that after a certain number of operations, if there exists some $a_k$ equal to $g$. In the next operations, for each element $a_i$ that is not equal to $g$, we simply choose $j=k$ and then make $a_i := \\gcd(a_i, a_k)$. After this, all elements will become $g$. If $g$ is initially in $a$, then the problem is simple; we just need to count the number of elements in $a$ that are not equal to $g$. But if the initial $g$ is not in $a$, we are actually trying to make an element equal to $g$ by minimizing the number of operations. This is not difficult to achieve through dynamic programming, using $f_x$ to indicate that it takes at least a few operations to make an element equal to $x$. The transition is simple, just enumerate $x$ from largest to smallest, and then for all $i$, use $f_{x}+1$ to update $f_{\\gcd(x, a_i)}$. But computing $\\gcd(x, y)$ is $O(\\log x)$, a direct transition takes $O(n \\max(a) \\log \\max(a))$ time. So we need to preprocess this. Let $h_{x, y} = \\gcd(x, y)$, then there is obviously $h_{x, y} = h_{y, x \\bmod y}$. Before all test cases, $h$ can be preprocessed in $O(\\max(a)^2)$ time complexity. Time complexity: $O(n \\max(a))$ per test case and $O(\\max(a)^2)$ for preprocessing. Memory complexity: $O(n+\\max(a))$ per test case and $O(\\max(a)^2)$ for preprocessing. Try to solve $n, a_i \\leq 2 \\times 10^5$ with only one test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 5000 + 5;\n\ninline void checkmax(int &x, int y){\n\tif(y > x) x = y;\n}\n\ninline void checkmin(int &x, int y){\n\tif(y < x) x = y;\n}\n\nint n = 0, m = 0, k = 0, a[N] = {}, f[N] = {};\nint g[N][N] = {}, ans = 0;\n\ninline void solve(){\n\tscanf(\"%d\", &n); m = k = 0;\n\tfor(int i = 1 ; i <= n ; i ++){\n\t\tscanf(\"%d\", &a[i]);\n\t\tk = g[k][a[i]];\n\t}\n\tmemset(f, 0x3f, sizeof(f));\n\tfor(int i = 1 ; i <= n ; i ++) a[i] /= k, checkmax(m, a[i]), f[a[i]] = 0;\n\tfor(int x = m ; x >= 1 ; x --) for(int i = 1 ; i <= n ; i ++){\n\t\tint y = a[i];\n\t\tcheckmin(f[g[x][y]], f[x] + 1);\n\t}\n\tans = max(f[1] - 1, 0);\n\tfor(int i = 1 ; i <= n ; i ++) if(a[i] > 1) ans ++;\n\tprintf(\"%d\\n\", ans);\n}\n\nint T = 0;\n\nint main(){\n\tfor(int x = 0 ; x < N ; x ++) g[x][0] = g[0][x] = g[x][x] = x;\n\tfor(int x = 1 ; x < N ; x ++) for(int y = 1 ; y < x ; y ++) g[x][y] = g[y][x] = g[y][x % y];\n\tscanf(\"%d\", &T);\n\twhile(T --) solve();\n\treturn 0;\n}",
    "tags": [
      "constructive algorithms",
      "dp",
      "math",
      "number theory"
    ],
    "rating": 1500
  },
  {
    "contest_id": "2115",
    "index": "B",
    "title": "Gellyfish and Camellia Japonica",
    "statement": "Gellyfish has an array of $n$ integers $c_1, c_2, \\ldots, c_n$. In the beginning, $c = [a_1, a_2, \\ldots, a_n]$.\n\nGellyfish will make $q$ modifications to $c$.\n\nFor $i = 1,2,\\ldots,q$, Gellyfish is given three integers $x_i$, $y_i$, and $z_i$ between $1$ and $n$. Then Gellyfish will set $c_{z_i} := \\min(c_{x_i}, c_{y_i})$.\n\nAfter the $q$ modifications, $c = [b_1, b_2, \\ldots, b_n]$.\n\nNow Flower knows the value of $b$ and the value of the integers $x_i$, $y_i$, and $z_i$ for all $1 \\leq i \\leq q$, but she doesn't know the value of $a$.\n\nFlower wants to find any possible value of the array $a$ or report that no such $a$ exists.\n\nIf there are multiple possible values of the array $a$, you may output any of them.",
    "tutorial": "Try working backwards from the final sequence, to the initial. If you're confused about Hint 1, it's probably because the result isn't unique each time. Think carefully about whether you can just take the \"tightest\" result possible Let's think of the problem in another way, if we only require that for all $i$, the final value of $c_i$ is greater than or equal to $b_i$, what will be the limitations for all $a_i$? It is possible to prove that the restricted form exists as a sequence $l$. It is sufficient that $a_i \\geq l_i$ for all $i$. Next we try to illustrate this thing, we need to work backward from the last operation and observe the restrictions on $c$ in each step. After the last operation, we have $c_i \\geq b_i$, which means $l = b$. Consider an operation that replaces $c_z$ with $\\min(c_x, c_y)$. If for a post-operation restriction of $l$, can we recover the pre-operation restriction $l'$? Let us think as follows: It is not difficult to find that for $i \\notin {x, y, z}$, $l'_i = l_i$. $l'_z = 0$, because the $c_z$ before the operation is overwritten, it will not actually have any restrictions. $l'_x = \\max(l_x, l_z), l'_y = \\max(l_y, l_z)$. Since the new $c_z$ is the original $\\min(c_x, c_y)$, it can be found that for the original $c_x$, we have $c_x \\geq \\min(c_x, c_y) = c_z \\geq l_z$, while for $y$ is symmetric. We have thus proved that, according to the eventually obtained $l$, $a_i \\geq l_i$ for all $i$ is a sufficient condition to eventually make all $c_i \\geq b_i$ for all $i$ . And ultimately all $c_i = b_i$, thus for all $i$, $a_i \\geq l_i$ is necessary. In fact, we could just take $a=l$ and do all the operations sequentially to see if we end up with $c=b$. This is because as $a$ decreases, eventually $c$ decreases as well, and by the $l$ guarantee there is always $c_i \\geq b_i$, so in effect we are trying to minimize all of $c$, and then minimizing all of $a$ is clearly an optimal decision. Time complexity: $O(n + q)$ per test case. Memory complexity: $O(n + q)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 3e5 + 5;\nint n = 0, q = 0, a[N] = {}, b[N] = {}, c[N] = {};\nint x[N] = {}, y[N] = {}, z[N] = {};\n\ninline void init(){\n\tfor(int i = 1 ; i <= n ; i ++) a[i] = b[i] = c[i] = 0;\n\tfor(int i = 1 ; i <= q ; i ++) x[i] = y[i] = z[i] = 0;\n\tn = q = 0;\n}\n\ninline void solve(){\n\tcin >> n >> q;\n\tfor(int i = 1 ; i <= n ; i ++){\n\t\tcin >> b[i];\n\t\tc[i] = b[i];\n\t}\n\tfor(int i = 1 ; i <= q ; i ++) cin >> x[i] >> y[i] >> z[i];\n\tfor(int i = q ; i >= 1 ; i --){\n\t\tint v = c[z[i]]; c[z[i]] = 0;\n\t\tc[x[i]] = max(c[x[i]], v), c[y[i]] = max(c[y[i]], v);\n\t}\n\tfor(int i = 1 ; i <= n ; i ++) a[i] = c[i];\n\tfor(int i = 1 ; i <= q ; i ++) c[z[i]] = min(c[x[i]], c[y[i]]);\n\tfor(int i = 1 ; i <= n ; i ++) if(b[i] != c[i]){\n\t\tcout << \"-1\\n\";\n\t\treturn;\n\t}\n\tfor(int i = 1 ; i <= n ; i ++) cout << a[i] << ' ';\n\tcout << '\\n';\n}\n\nint T = 0;\n\nint main(){\n\tios :: sync_with_stdio(0);\n\tcin.tie(0), cout.tie(0);\n\tcin >> T;\n\tfor(int i = 0 ; i < T ; i ++) init(), solve();\n\t\n\treturn 0;\n}",
    "tags": [
      "brute force",
      "constructive algorithms",
      "dfs and similar",
      "dp",
      "graphs",
      "greedy",
      "trees"
    ],
    "rating": 2100
  },
  {
    "contest_id": "2115",
    "index": "C",
    "title": "Gellyfish and Eternal Violet",
    "statement": "There are $n$ monsters, numbered from $1$ to $n$, in front of Gellyfish. The HP of the $i$-th monster is $h_i$.\n\nGellyfish doesn't want to kill them, but she wants to keep these monsters from being a threat to her. So she wants to reduce the HP of all the monsters to exactly $1$.\n\nNow, Gellyfish, with The Sword Sharpened with Tears, is going to attack the monsters for $m$ rounds. For each round:\n\n- The Sword Sharpened with Tears shines with a probability of $p$.\n- Gellyfish can choose whether to attack:\n\n- If Gellyfish doesn't attack, nothing happens.\n- If Gellyfish chooses to attack and The Sword Sharpened with Tears shines, the HP of all the monsters will be reduced by $1$.\n- If Gellyfish chooses to attack and The Sword Sharpened with Tears does not shine, Gellyfish can choose one of the monsters and reduce its HP by $1$.\n\nPlease note that before Gellyfish decides whether or not to attack, she will know whether the sword shines or not. Also, when the sword shines, Gellyfish can only make attacks on all the monsters and cannot make an attack on only one monster.\n\nNow, Gellyfish wants to know what the probability is that she will reach her goal if she makes choices optimally during the battle.",
    "tutorial": "Try to find an $O(nm h^2)$ solution using dynamic programming. Re-examining Gellyfish's strategy, there are definitely situations where she chooses to carry out an attack. Can we divide the $m$ rounds into two phases by some nature? Considering all current monsters, if the lowest HP of the monsters is $l$, Gellyfish can only make at most $l-1$ \"ranged\" attacks. So for each monster, if its HP is $h_i$, then it must be subject to at least $h_i - l$ \"pointing\" attacks. Further, we can see that we only care about $l$ and $\\sum\\limits_{i=1}^n (h_i - l)$. Consider directly using $f_{i, l, x}$ to indicate that there are still $i$ rounds to go, the lowest HP of the monsters is $l$, and $x = \\sum\\limits_{i=1}^n (h_i - l)$, the probability that Gellyfish will reach her goal. This solves the problem within $O(nmh^2)$, but that's not enough. Consider the initial HP of all monsters, let $l = \\min\\limits_{i=1}^n h_i, s = \\sum\\limits_{i=1}^n (h_i - l)$. For the first $s$ times the sword doesn't shine, Gellyfish will obviously launch an attack. So we using $g_{i, j}$ to indicate the probability that the sword did not shine exactly $j$ times in the first $i$ rounds and the last time the sword did not shine. We then enumerate the $s$-th time that the sword didn't shine. We can divide the problem into two parts. The first half can be solved using $g$, while the second half can be solved using $f$, We just need to merge the results of the two parts, which is not difficult. When we use f to solve the second part, it is easy to see that initially all monsters have the same HP, and each \"pointing\" attack can directly attacks the monster with the highest HP, which doesn't make the answer worse. So we have $h_i - l \\leq 1$ for any time, and the range of $x$ that we actually need is compressed to $[0, n)$. Time complexity: $O(nmh)$ per test case. Memory complexity: $O(nmh)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 22, K = 4000 + 5, M = 400 + 5, Inf = 0x3f3f3f3f;\n\ninline void checkmin(double &x, double y){\n\tif(y < x) x = y;\n}\n\nint n = 0, m = 0, s = 0, k = 0, p0 = 0, h[N] = {};\ndouble p = 0, f[K][K] = {}, g[K][N][M] = {}, ans = 0;\n\ninline void init(){\n\tfor(int i = 0 ; i <= k ; i ++){\n\t\tfor(int c = 0 ; c < n ; c ++) for(int x = 0 ; x <= m ; x ++) g[i][c][x] = 0;\n\t\tfor(int x = 0 ; x <= s ; x ++) f[i][x] = 0;\n\t}\n\tm = Inf, s = 0, ans = 0;\n}\n\ninline void solve(){\n\tscanf(\"%d %d %d\", &n, &k, &p0);\n\tp = 1.0 * p0 / 100;\n\tfor(int i = 1 ; i <= n ; i ++){\n\t\tscanf(\"%d\", &h[i]); h[i] --;\n\t\tm = min(m, h[i]);\n\t}\n\tfor(int i = 1 ; i <= n ; i ++) s += h[i] - m;\n\tif(s > k){\n\t    printf(\"0.000000\\n\");\n\t    return;\n\t}\n\tg[0][0][0] = 1;\n\tfor(int i = 1 ; i <= k ; i ++){\n\t\tg[i][0][0] = 1;\n\t\tfor(int x = 1 ; x <= m ; x ++) g[i][0][x] = g[i - 1][0][x - 1] * p + max(g[i - 1][0][x], g[i - 1][n - 1][x - 1]) * (1 - p);\n\t\tfor(int c = 1 ; c < n ; c ++){\n\t\t\tg[i][c][0] = g[i - 1][c][0] * p + g[i - 1][c - 1][0] * (1 - p);\n\t\t\tfor(int x = 1 ; x <= m ; x ++) g[i][c][x] = g[i - 1][c][x - 1] * p + g[i - 1][c - 1][x] * (1 - p);\n\t\t}\n\t}\n\tf[0][0] = 1;\n\tfor(int i = 0 ; i < k ; i ++) for(int x = 0 ; x < s ; x ++){\n\t\tf[i + 1][x] += f[i][x] * p;\n\t\tf[i + 1][x + 1] += f[i][x] * (1 - p);\n\t}\n\tfor(int i = s ; i <= k ; i ++){\n\t\tdouble r = 0;\n\t\tfor(int x = 0 ; x <= min(i - s, m) ; x ++) r = max(r, g[k - i][0][m - x]);\n\t\tans += r * f[i][s];\n\t}\n\tprintf(\"%.6lf\\n\", ans);\n}\n\nint T = 0;\n\nint main(){\n\tscanf(\"%d\", &T);\n\twhile(T --) init(), solve();\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "dp",
      "greedy",
      "math",
      "probabilities"
    ],
    "rating": 2700
  },
  {
    "contest_id": "2115",
    "index": "D",
    "title": "Gellyfish and Forget-Me-Not",
    "statement": "Gellyfish and Flower are playing a game.\n\nThe game consists of two arrays of $n$ integers $a_1,a_2,\\ldots,a_n$ and $b_1,b_2,\\ldots,b_n$, along with a binary string $c_1c_2\\ldots c_n$ of length $n$.\n\nThere is also an integer $x$ which is initialized to $0$.\n\nThe game consists of $n$ rounds. For $i = 1,2,\\ldots,n$, the round proceeds as follows:\n\n- If $c_i = \\mathtt{0}$, Gellyfish will be the active player. Otherwise, if $c_i = \\mathtt{1}$, Flower will be the active player.\n- The active player will perform \\textbf{exactly one} of the following operations:\n\n- Set $x:=x \\oplus a_i$.\n- Set $x:=x \\oplus b_i$.\n\nHere, $\\oplus$ denotes the bitwise XOR operation.\n\nGellyfish wants to minimize the final value of $ x $ after $ n $ rounds, while Flower wants to maximize it.\n\nFind the final value of $ x $ after all $ n $ rounds if both players play optimally.",
    "tutorial": "Consider if $c$ consists only of $0$, this problem turned out to be another classic problem. So you need at least something that you know what it is. \"linear basis\" is the answer to Hint 1. Please try to understand this: all addition operations are interpreted as XOR operations. We can assume that the initial value of $x$ is $\\sum a_i$. In each step, we can choose to add $c_i = a_i + b_i$ to $x$, or do nothing. Each suffix of the sequence can be seen as a subproblem, so we prove inductively that the answer, as a function $f(x)$ of the initial value of $x$, is an affine transformation, i.e., $f(x) = Ax + b$. When $n = 0$, this is trivial: $f(x) = x$. When $n > 1$, we can choose to add $c_i$ to $x$ or not. Let $f(x)$ denote the answer function from the second operation onward. The two possible outcomes correspond to: Not choosing $c_i$: result is $f(x)$ Choosing $c_i$: result is $f(x + c_i) = f(x) + f(c_i) + b$. Although we don't know the exact value of $x$, $f(c_i) + b$ is a constant. Suppose the highest set bit in the binary representation of $f(c_i) + b$ is at position $k$. Then, the decision of whether to apply this operation depends only on: Whether we want to maximize or minimize the final answer Whether the $k$-th bit of $f(x)$ is $0$ or $1$ It is easy to observe that the new function $g(x)$ (before this decision) remains a affine transformation, satisfying $g(x) = g(x + c_i)$. Based on the above process, we can represent the answer function $f(x)$ using a orthogonal basis. Each element in the orthogonal basis represents a vector in the null space of $A$. Additionally, we keep a tag for each vector, indicating whether it is used to increase or decrease the value of $x$. In each iteration, we try to insert $c_i$ into the linear basis, and associate it with a tag depending on the index $i$. Time complexity: $O(n \\log \\max(a, b, x))$ per test case. Memory complexity: $O(n + \\log \\max(a, b, x))$ per test case.",
    "code": "#include <bits/stdc++.h>\nusing i64 = long long;\nconstexpr int L = 60;\nint main() {\n\tstd::ios::sync_with_stdio(false), std::cin.tie(0);\n\tint T;\n\tfor(std::cin >> T; T; T --) {\n\t\tint n; \n\t\tstd::cin >> n;\n\t\tstd::vector<i64> a(n), b(n);\n\t\tstd::string str;\n\t\ti64 all = 0;\n\t\tfor(auto &x : a) std::cin >> x, all ^= x;\n\t\tfor(int i = 0; i < n; i ++) {\n\t\t\tstd::cin >> b[i];\n\t\t\tb[i] ^= a[i];\n\t\t}\n\t\tstd::cin >> str;\n\t\tstd::vector<i64> bas(L);\n\t\tstd::vector<int> bel(L, -1);\n\t\ti64 ans = 0;\n\t\tfor(int i = n - 1; i >= 0; i --) {\n\t\t\ti64 x = b[i], col = str[i] - '0';\n\t\t\tfor(int i = L - 1; i >= 0; i --) if(x >> i & 1) {\n\t\t\t\tif(bas[i]) {\n\t\t\t\t\tx ^= bas[i];\n\t\t\t\t} else {\n\t\t\t\t\tfor(int j = i - 1; j >= 0; j --) if(x >> j & 1) {\n\t\t\t\t\t\tx ^= bas[j];\n\t\t\t\t\t}\n\t\t\t\t\tbas[i] = x;\n\t\t\t\t\tfor(int j = L - 1; j > i; j --) if(bas[j] >> i & 1){\n\t\t\t\t\t\tbas[j] ^= bas[i];\n\t\t\t\t\t} \n\t\t\t\t\tbel[i] = col;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\n\t\tfor(int i = L - 1; i >= 0; i --) if(all >> i & 1) {\n\t\t\tall ^= bas[i];\n\t\t}\n\t\tfor(int i = 0; i < L; i ++) if(bel[i] == 1) ans ^= bas[i];\n\t\tstd::cout << (all ^ ans) << '\\n';\n\t}\n\t\n\treturn 0;\n}",
    "tags": [
      "bitmasks",
      "dp",
      "games",
      "greedy",
      "math"
    ],
    "rating": 2900
  },
  {
    "contest_id": "2115",
    "index": "E",
    "title": "Gellyfish and Mayflower",
    "statement": "\\begin{quote}\nMayflower by Plum\n\\end{quote}\n\nMay, Gellyfish's friend, loves playing a game called \"Inscryption\" which is played on a directed acyclic graph with $n$ vertices and $m$ edges. All edges $ a \\rightarrow b$ satisfy $a<b$.\n\nYou start in vertex $1$ with some coins. You need to move from vertex $1$ to the vertex where the boss is located along the directed edges, and then fight with the final boss.\n\nEach of the $n$ vertices of the graph contains a Trader who will sell you a card with power $w_i$ for $c_i$ coins. You can buy as many cards as you want from each Trader. However, you can only trade with the trader on the $i$-th vertex if you are currently on the $i$-th vertex.\n\nIn order to defeat the boss, you want the sum of the power of your cards to be as large as possible.\n\nYou will have to answer the following $q$ queries:\n\n- Given integers $p$ and $r$. If the final boss is located at vertex $p$, and you have $r$ coins in the beginning, what is the maximum sum of the power of your cards when you fight the final boss? Note that you are allowed to trade cards on vertex $p$.",
    "tutorial": "There is an easy way to solve the problem in $O(m \\max(r) + q)$ time complexity. Thus for cases with small $r$, we can easily solve them, but what about cases with large $r$? There is a classic but mistaken greed where we only take the item with the largest $\\frac w c$. This is obviously wrong, but Hint 1 lets us rule out the case where r is small; is there an efficient algorithm that can fix this greed for larger $r$? Let $s$ be any path from vertex $1$ to vertex $p$, the vertices that pass through in turn are $s_1, s_2, \\dots, s_k$. Let $z$ be the vertex in $s$ with the largest $\\frac {w} {c}$, and $C = c_z, W = w_z$. Let's call your cards you don't get from vertex $z$ as special cards. Lemma1. There exists an optimal solution such that the number of special cards does not exceed $C$. Proof. Let $c'_1, c'_2, \\dots, c'_{k'}$ be the cost of the special cards, and $p'_i = \\sum_{j=1}^i {c'}_j$. If there exists $0 \\leq l < r \\leq k',\\ p'_l \\equiv p'_r \\bmod C$, we will get that $\\sum_{i=l'+1}^{r'} p_i \\equiv 0 \\bmod C$. Then we can replaces these cards with $\\frac {\\sum_{i=l'+1}^{r'} p_i} C$ cards from vertex $z$, the answer won't be worse. Since there are only $C+1$ values of $x \\bmod C$ for all non-negative integers $x$, there are no more than $C$ special cards. So it's not hard to find the total cost of special cards won't exceed $\\max(c)^2$. Now we can use dynamic programming to solve this problem: $dp(u, v, x, 0/1)$ means we are current at vertex $u$, the vertex on the path with the largest $\\frac {w} {c}$ is $v$, the total cost of the cards is $x$, we have reached the vertex $v$ or not, the maximum sum of the power of the cards. Since the remainder will be filled by cards from $v$, We just need to find the value of $dp(u, v, x)$ that satisfies $1 \\leq x \\leq \\max(c)^2$. But unfortunately, the time complexity of the algorithm is $O(mn\\max(c)^2)$. It's not fast enough. At this point you'll find that solving the problem directly becomes incredibly tricky, so we'll try to split it into two problems. We first consider the following problem: whether there is a better solution when $r$ is sufficiently large? We need to broaden the problem, so we try to be able to buy a negative number of cards with the largest $\\frac {w} {c}$. Doing so would make the answer larger, but when $r$ is large enough, the answer won't change. Because according to Lemma1, if the total cost of special cards exceed $\\max(c)^2$, there will be a solution that's at least not worse. Thus when $r > \\max(c)^2$, that's the answer of the problem. And we can use another dynamic programming to solve this problem: $g(u, v, x, 0/1)$ means we are current at vertex $u$, the vertex on the path with the largest $\\frac {w} {c}$ is $v$, the total cost of the cards is $x$, we have reached the vertex $v$ or not, the maximum sum of the power of the cards. But unlike the original, when $x$ is equal to or greater than $c_v$, we remove several cards from vertex $v$ to make $0 \\leq x < c_v$. The time complexity becomes $O(mn \\max(c))$, now it's fast enough. For each query, we can just enumerate $v$ in $O(n)$ time complexity. As for $r \\leq max(c)^2$? It's an easy problem: $f(u, x)$ means we are current at vertex $u$, the total cost of the cards is $x$, the maximum sum of the power of the cards. The time complexity is $O(m \\max(c)^2)$. For each query, we can get the answer directly from $f$ in $O(1)$ time complexity. Over all, we have solved the problem. Time complexity: $O(mn \\max(c) + m \\max(c)^2 + qn)$ Memory complexity: $O(n^2 \\max(c) + n \\max(c)^2)$",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nconst ll N = 200 + 5, Inf = 0xcfcfcfcfcfcfcfcf;\n\ninline ll sqr(ll x){\n\treturn x * x;\n}\n\ninline ll gcd(ll x, ll y){\n\tif(y) return gcd(y, x % y);\n\telse return x;\n}\n\ninline void checkmax(ll &x, ll y){\n\tif(y > x) x = y;\n}\n\nll n = 0, m = 0, magic = 0, w[N] = {}, c[N] = {};\nll f[N][N * N] = {}, g[N][N][N][2] = {};\nvector<vector<ll> > G(N);\n\ninline void main_min(){\n\tmemset(f, 0xcf, sizeof(f));\n\tfor(ll x = 0 ; x <= magic ; x ++) f[1][x] = 0;\n\tfor(ll u = 1 ; u <= n ; u ++){\n\t\tfor(ll x = 0 ; x + c[u] <= magic ; x ++) checkmax(f[u][x + c[u]], f[u][x] + w[u]);\n\t\tfor(ll v : G[u]) for(ll x = 0 ; x <= magic ; x ++) checkmax(f[v][x], f[u][x]);\n\t}\n}\n\ninline void solve_max(ll i){\n\tll a = c[i], b = w[i];\n\tfor(ll x = 0 ; x < a ; x ++) g[i][1][x][0] = 0;\n\tfor(ll u = 1 ; u <= n ; u ++){\n\t\tif(u == i) for(ll x = 0 ; x < a ; x ++) checkmax(g[i][u][x][1], g[i][u][x][0]);\n\t\telse if(w[u] * a > c[u] * b) memset(g[i][u], 0xcf, sizeof(g[i][u]));\n\t\tfor(ll s = 0, k = gcd(c[u], a) ; s < k ; s ++) for(ll x = s, t = 0 ; t < 2 * (a / k) ; x = (x + c[u]) % a, t ++){\n\t\t\tcheckmax(g[i][u][(x + c[u]) % a][0], g[i][u][x][0] + w[u] - ((x + c[u]) / a) * b);\n\t\t\tcheckmax(g[i][u][(x + c[u]) % a][1], g[i][u][x][1] + w[u] - ((x + c[u]) / a) * b);\n\t\t}\n\t\tfor(ll v : G[u]) for(ll x = 0 ; x < a ; x ++){\n\t\t\tcheckmax(g[i][v][x][0], g[i][u][x][0]);\n\t\t\tcheckmax(g[i][v][x][1], g[i][u][x][1]);\n\t\t}\n\t}\n}\n\ninline void main_max(){\n\tmemset(g, 0xcf, sizeof(g));\n\tfor(ll i = 1 ; i <= n ; i ++) solve_max(i);\n}\n\nint main(){\n\tscanf(\"%lld %lld\", &n, &m);\n\tfor(ll i = 1 ; i <= n ; i ++){\n\t\tscanf(\"%lld %lld\", &c[i], &w[i]);\n\t\tmagic = max(magic, sqr(c[i]));\n\t}\n\tfor(ll i = 1, u = 0, v = 0 ; i <= m ; i ++){\n\t\tscanf(\"%lld %lld\", &u, &v);\n\t\tG[u].push_back(v);\n\t}\n\tmain_min(), main_max();\n\tll q = 0, p = 0, r = 0;\n\tscanf(\"%lld\", &q);\n\twhile(q --){\n\t\tscanf(\"%lld %lld\", &p, &r);\n\t\tif(r <= magic) printf(\"%lld\\n\", f[p][r]);\n\t\telse{\n\t\t\tll ans = Inf;\n\t\t\tfor(ll i = 1 ; i <= n ; i ++){\n\t\t\t\tll a = c[i], b = w[i];\n\t\t\t\tcheckmax(ans, g[i][p][r % a][1] + (r / a) * b);\n\t\t\t}\n\t\t\tprintf(\"%lld\\n\", ans);\n\t\t}\n\t}\n\treturn 0;\n}",
    "tags": [
      "dp",
      "graphs"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2115",
    "index": "F1",
    "title": "Gellyfish and Lycoris Radiata (Easy Version)",
    "statement": "\\textbf{This is the easy version of the problem. The difference between the versions is that in this version, the time limit and the constraints on $n$ and $q$ are lower. You can hack only if you solved all versions of this problem.}\n\nGellyfish has an array consisting of $n$ sets. Initially, all the sets are empty.\n\nNow Gellyfish will do $q$ operations. Each operation contains one modification operation and one query operation, for the $i$-th ($1 \\leq i \\leq q$) operation:\n\nFirst, there will be a modification operation, which is one of the following:\n\n- \\textbf{Insert} operation: You are given an integer $r$. For the $1$-th to $r$-th sets, insert element $i$. Note that the element inserted here is $i$, the index of the operation, not the index of the set.\n- \\textbf{Reverse} operation: You are given an integer $r$. Reverse the $1$-th to $r$-th sets.\n- \\textbf{Delete} operation: You are given an integer $x$. Delete element $x$ from all sets that contain $x$.\n\nFollowed by a query operation:\n\n- \\textbf{Query} operation: You are given an integer $p$. Output the smallest element in the $p$-th set (If the $p$-th set is empty, the answer is considered to be $0$).\n\nNow, Flower needs to provide the answer for each query operation. Please help her!\n\n\\textbf{Additional constraint on the problem}: Gellyfish will only give the next operation after Flower has answered the previous query operation. That is, you need to solve this problem \\textbf{online}. Please refer to the input format for more details.",
    "tutorial": "We apply block decomposition to the operations, dividing every $B$ operations into a single round. Within each round, the sequence is partitioned into $O(B)$ segments. For each segment, we maintain a queue that records all elements added to that segment during the round. Type 1 and 2 operations can be handled directly by pushing into the appropriate segment's queue or toggling a reversal flag. Type 3 (deletion) is handled by marking the element $x$ as deleted without immediately removing it from queues. At the end of each round, we rebuild the sequence. Specifically, for each position in the sequence, we record which segment it belongs to, and treat the position as containing all elements currently in that segment's queue. For queries, we process the contribution from each round one by one. In each round: Identify the segment that contains position $p$. Iterate through the queue of that segment. For each element, if it has been marked as deleted, remove it from the front of the queue and continue; otherwise, consider it as present. Since each element is inserted and deleted at most once per segment, and each segment has $O(1)$ amortized processing per round, the total cost per query remains efficient. We choose $B = \\sqrt{q}$, resulting in $O(\\sqrt{q})$ rounds in total. The total time and space complexity is: $O((n + q)\\sqrt{q})$",
    "code": "#pragma GCC optimize(2)\n#pragma GCC optimize(\"Ofast\")\n#pragma GCC optimize(\"inline\",\"fast-math\",\"unroll-loops\",\"no-stack-protector\")\n#pragma GCC diagnostic error \"-fwhole-program\"\n#pragma GCC diagnostic error \"-fcse-skip-blocks\"\n#pragma GCC diagnostic error \"-funsafe-loop-optimizations\"\n// MagicDark\n#include <bits/stdc++.h>\n#define debug cerr << \"\\33[32m[\" << __LINE__ << \"]\\33[m \"\n#define SZ(x) ((int) x.size() - 1)\n#define all(x) x.begin(), x.end()\n#define ms(x, y) memset(x, y, sizeof x)\n#define F(i, x, y) for (int i = (x); i <= (y); i++)\n#define DF(i, x, y) for (int i = (x); i >= (y); i--)\nusing namespace std;\ntypedef long long ll;\ntypedef unsigned long long ull;\ntemplate <typename T> T& chkmax(T& x, T y) {return x = max(x, y);}\ntemplate <typename T> T& chkmin(T& x, T y) {return x = min(x, y);}\n// template <typename T> T& read(T &x) {\n// \tx = 0; int f = 1; char c = getchar();\n// \tfor (; !isdigit(c); c = getchar()) if (c == '-') f = -f;\n// \tfor (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);\n// \treturn x *= f;\n// }\n// bool be;\nconst int N = 1e5 + 1010, B = 500, B1 = N / B + 5, B2 = B + 5;\nint n, q, ans, p[N], wp[N], tot, t[N], tl[N], tr[N];\nbool rev[N];\nbool ed[N];\n// bool vv[N];\n// struct Q1 {\n// \tint tl = 1, tr;\n// \tint a[B2];\n// \tbool chk() {\n// \t\treturn tl <= tr;\n// \t}\n// \tint front() {\n// \t\treturn a[tl];\n// \t}\n// \tvoid pop() {\n// \t\ttl++;\n// \t}\n// \tvoid push(int x) {\n// \t\ta[++tr] = x;\n// \t}\n// } tq[N];\n// struct Q2 {\n// \tint tl = 1, tr;\n// \tint a[B1];\n// \tbool chk() {\n// \t\treturn tl <= tr;\n// \t}\n// \tint front() {\n// \t\treturn a[tl];\n// \t}\n// \tvoid pop() {\n// \t\ttl++;\n// \t}\n// \tvoid push(int x) {\n// \t\ta[++tr] = x;\n// \t}\n// } vq[N];\nqueue <int> tq[N], vq[N];\nvector <int> cur;\nint qq(int x) {\n\twhile (tq[x].size()) {\n\t\tif (!ed[tq[x].front()]) return tq[x].front();\n\t\ttq[x].pop();\n\t}\n\treturn 0;\n}\nint query(int x) {\n\tint s = 0;\n\tfor (int i: cur) {\n\t\ts += tr[i] - tl[i] + 1;\n\t\tif (s >= x) {\n\t\t\tint g = s - x + 1;\n\t\t\tint y;\n\t\t\tif (rev[i]) {\n\t\t\t\ty = p[tl[i] + g - 1];\n\t\t\t} else {\n\t\t\t\ty = p[tr[i] - g + 1];\n\t\t\t}\n\t\t\twhile (vq[y].size()) {\n\t\t\t\tint tmp = qq(vq[y].front());\n\t\t\t\tif (tmp) return tmp;\n\t\t\t\tvq[y].pop();\n\t\t\t}\n\t\t\t// int tmp = qq(i);\n\t\t\t// if (~tmp) return tmp;\n\t\t\treturn qq(i);\n\t\t}\n\t}\n\tassert(false);\n\t// return -1;\n}\n// bool ee;\n// int cnt = 0;\nsigned main() {\n\tios::sync_with_stdio(0); // don't use puts\n\tcin.tie(0), cout.tie(0);\n\t// debug << abs(&ee - &be) / 1024 / 1024 << endl;\n\tcin >> n >> q;\n\tF(i, 1, n) p[i] = i;\n\tcur.push_back(++tot);\n\ttl[1] = 1, tr[1] = n;\n\tF(i, 1, q) {\n\t\tint f, x, y; cin >> f >> x >> y;\n\t\tif (f == 3) {\n\t\t\tx = (x + ans - 1) % q + 1;\n\t\t} else {\n\t\t\tx = (x + ans - 1) % n + 1;\n\t\t}\n\t\ty = (y + ans - 1) % n + 1;\n\t\t// auto split = [&] (int x) {\n\t\t// \tif (x > n || vv[x]) return;\n\t\t// \t// vv[x] = true;\n\t\t// \tfor (auto [])\n\t\t// };\n\t\tif (f == 1) {\n\t\t\tint s = 0;\n\t\t\tfor (int j: cur) {\n\t\t\t\tint w = tr[j] - tl[j] + 1;\n\t\t\t\ts += w;\n\t\t\t\tif (s >= x) {\n\t\t\t\t\tif (s > x) {\n\t\t\t\t\t\ttot++;\n\t\t\t\t\t\ttq[tot] = tq[j];\n\t\t\t\t\t\tint g = s - x;\n\t\t\t\t\t\tif (rev[tot] = rev[j]) {\n\t\t\t\t\t\t\ttl[tot] = tl[j];\n\t\t\t\t\t\t\ttr[tot] = (tl[j] += g) - 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttr[tot] = tr[j];\n\t\t\t\t\t\t\ttl[tot] = (tr[j] -= g) + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcur.insert(next(find(all(cur), j)), tot);\n\t\t\t\t\t}\n\t\t\t\t\ttq[j].push(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttq[j].push(i);\n\t\t\t}\n\t\t}\n\t\tif (f == 2) {\n\t\t\tint s = 0, sz = 0;\n\t\t\tfor (int j: cur) {\n\t\t\t\tsz++;\n\t\t\t\tint w = tr[j] - tl[j] + 1;\n\t\t\t\ts += w;\n\t\t\t\tif (s >= x) {\n\t\t\t\t\tif (s > x) {\n\t\t\t\t\t\ttot++;\n\t\t\t\t\t\ttq[tot] = tq[j];\n\t\t\t\t\t\tint g = s - x;\n\t\t\t\t\t\tif (rev[tot] = rev[j]) {\n\t\t\t\t\t\t\ttl[tot] = tl[j];\n\t\t\t\t\t\t\ttr[tot] = (tl[j] += g) - 1;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttr[tot] = tr[j];\n\t\t\t\t\t\t\ttl[tot] = (tr[j] -= g) + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcur.insert(next(find(all(cur), j)), tot);\n\t\t\t\t\t}\n\t\t\t\t\treverse(cur.begin(), cur.begin() + sz);\n\t\t\t\t\tF(j, 0, sz - 1) rev[cur[j]] ^= true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (f == 3) {\n\t\t\tif (x < i) ed[x] = true;\n\t\t}\n\t\tcout << (ans = query(y)) << '\\n';\n\t\tif (cur.size() >= B) {\n\t\t\tint cnt = 0;\n\t\t\tfor (int j: cur) {\n\t\t\t\tif (rev[j]) {\n\t\t\t\t\tDF(k, tr[j], tl[j]) {\n\t\t\t\t\t\tvq[wp[++cnt] = p[k]].push(j);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tF(k, tl[j], tr[j]) {\n\t\t\t\t\t\tvq[wp[++cnt] = p[k]].push(j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tF(j, 1, n) {\n\t\t\t\tp[j] = wp[j];\n\t\t\t}\n\t\t\tcur.clear();\n\t\t\tcur.push_back(++tot);\n\t\t\ttl[tot] = 1, tr[tot] = n;\n\t\t}\n\t\t// for (int j: cur) {\n\t\t// \tdebug << tl[j] << \" \" << tr[j] << \" \" << rev[j] << endl;\n\t\t// }\n\t}\n\treturn 0;\n}\n",
    "tags": [
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2115",
    "index": "F2",
    "title": "Gellyfish and Lycoris Radiata (Hard Version)",
    "statement": "\\textbf{This is the hard version of the problem. The difference between the versions is that in this version, the time limit and the constraints on $n$ and $q$ are higher. You can hack only if you solved all versions of this problem.}\n\nGellyfish has an array consisting of $n$ sets. Initially, all the sets are empty.\n\nNow Gellyfish will do $q$ operations. Each operation contains one modification operation and one query operation, for the $i$-th ($1 \\leq i \\leq q$) operation:\n\nFirst, there will be a modification operation, which is one of the following:\n\n- \\textbf{Insert} operation: You are given an integer $r$. For the $1$-th to $r$-th sets, insert element $i$. Note that the element inserted here is $i$, the index of the operation, not the index of the set.\n- \\textbf{Reverse} operation: You are given an integer $r$. Reverse the $1$-th to $r$-th sets.\n- \\textbf{Delete} operation: You are given an integer $x$. Delete element $x$ from all sets that contain $x$.\n\nFollowed by a query operation:\n\n- \\textbf{Query} operation: You are given an integer $p$. Output the smallest element in the $p$-th set (If the $p$-th set is empty, the answer is considered to be $0$).\n\nNow, Flower needs to provide the answer for each query operation. Please help her!\n\n\\textbf{Additional constraint on the problem}: Gellyfish will only give the next operation after Flower has answered the previous query operation. That is, you need to solve this problem \\textbf{online}. Please refer to the input format for more details.",
    "tutorial": "We consider using leafy persistent balanced trees to maintain the sequence. At each non-leaf node, we store a set $S_u$ as a lazy tag, indicating that every set in the subtree rooted at $u$ contains $S_u$. However, since $|S_u|$ can be large, it's difficult to push down the tag efficiently. To address this, we split each set $S_u$ into two components: $T_u$: A part of $S_u$ stored directly at node $u$ A collection of child nodes $v_{u,1}, v_{u,2}, \\cdots, v_{u,k}$, each storing a subset of $S_u$ We maintain the invariant: $S_u = T_u + \\sum_{i=1}^k S_{v_{u,i}}$. Thus, we make the balanced tree persistent. When we create a new node $u$ and initialize its children as $ls(u)$ and $rs(u)$, we add $u$ into both $v_{ls(u)}$ and $v_{rs(u)}$. During split and merge, we do not modify $T_u$, which ensures these operations still run in logarithmic time. Type 1 (Insert): We split the balanced tree into two parts. Let the root of the first part be $rt$, and simply add an element into $T_{rt}$. Type 2 (Reverse a segment): Just mark the root of the relevant subtree with a \"reverse\" flag. Type 3 (Delete): Since each element $x$ appears in only one $T$, we can directly remove it from that node's $T$. For queries, We first locate the leaf node $u$. To compute $S_u$, we need to compute all $S_{v_{u,i}}$. Due to persistence, we can guarantee: $\\max(S_{v_{u,i}}) < \\min(S_{v_{u,i+1}})$ Thus, we can sequentially check whether each $S_{v_{u,i}}$ is empty. We process this recursively. Every time we encounter a node $x$ with $S_x = \\emptyset$ and $x$ is not part of the latest tree version, then $S_x$ will always be empty, and we can safely delete $x$. During a query, we encounter three types of nodes: Nodes with $|S_x| \\ne 0$: We only encounter one such node per query - this is where we find the minimum value. Nodes with $|S_x| = 0$ and $x$ not in the latest tree: These nodes are deleted. Since the total number of persistent nodes is $O(q \\log n)$, these nodes also appear at most that many times. Nodes with $|S_x| = 0$ and $x$ in the latest tree: These are ancestors of leaf $u$, so there are at most $O(\\log n)$ of them per query. Why can we just do $O(\\log n)$ rounds of recursion? Because we replace all the nodes we pass through on the path, so the size of the subtree doesn't change from the time the node is created to the time it is removed from the tree. Furthermore, if we recurse from node $u$ to node $v$, this means that $v$ is the parent of $u$ at least at some point on the WBLT. Since the WBLT is weight-balanced, the size of the $v$ subtree is actually at least a constant multiple of the size of the $u$ subtree, and this constant greater than $1$ will be based on your WBLT. Time complexity: $O(q \\log n + n)$. Memory complexity: $O(q \\log n + n)$.",
    "code": "#include <bits/stdc++.h>\nconstexpr int N = 3e5 + 10, S = 1.1e7, SS = 2 * S;\nint n, q;\nint next[SS], val[SS], cnt;\nstruct queue {\n\tint head, tail;\n\tvoid push(int x) {\n\t\tif(head) {\n\t\t\tnext[tail] = ++ cnt, val[cnt] = x; tail = cnt;\n\t\t} else {\n\t\t\thead = tail = ++ cnt, val[cnt] = x;\n\t\t}\n\t\tassert(cnt < SS - 100);\n\t}\n\tvoid pop() {head = next[head];}\n\tint front() {return val[head];}\n\tbool check() {return head == tail;}\n\tbool empty() {return head == 0;}\n\tvoid clear() {head = tail = 0;}\n};\nstruct node {\n\tint ls, rs;\n\tqueue fa;\n\tint val, exit;\n\tint size, rev;\n}a[S];\nint tot;\nint id[N];\nvoid pushup(int u) {\n\ta[u].size = a[a[u].ls].size + a[a[u].rs].size;\n}\nvoid setR(int u) {\n\ta[u].rev ^= 1;\n\tstd::swap(a[u].ls, a[u].rs);\n}\nvoid setT(int u, int v) {\n\ta[u].fa.push(v);\n}\nvoid pushdown(int u) {\n\tif(a[u].rev) {\n\t\tsetR(a[u].ls);\n\t\tsetR(a[u].rs);\n\t\ta[u].rev = 0;\n\t}\n}\nint newnode() {\n\tint u = ++ tot;\n\ta[u].exit = 2;\n\treturn u;\n}\nint newleaf() {\n\tint u = newnode();\n\ta[u].size = 1;\n\treturn u;\n}\nint join(int x, int y) {\n\tint u = newnode();\n\ta[u].ls = x, a[u].rs = y;\n\ta[x].fa.push(u);\n\ta[y].fa.push(u);\n\tpushup(u);\n\treturn u;\n}\nauto cut(int x) {\n\tpushdown(x);\n\ta[x].exit = 1;\n\treturn std::make_pair(a[x].ls, a[x].rs);\n}\nint get_val(int u) {\n\tif(a[u].exit == 0) return 0;\n\tif(a[u].val != 0) return a[u].val;\n\tif(a[u].fa.empty()) return 0;\n\tint ans = 0;\n\twhile(1) {\n\t\tans = get_val(a[u].fa.front());\n\t\tif(ans) return ans;\n\t\tif(a[u].fa.check()) break;\n\t\ta[u].fa.pop();\n\t}\n\tif(a[u].exit == 1) {\n\t\ta[u].exit = 0;\n\t\ta[u].fa.pop();\n\t\ta[u].fa.clear();\n\t}\n\treturn 0;\n}\nint newtag(int x) {\n\tint u = ++ tot;\n\ta[u].val = x;\n\ta[u].exit = 1;\n\treturn u;\n}\nconstexpr double ALPHA = 0.292;\nbool too_heavy(int sx, int sy) {\n\treturn sy < ALPHA * (sx + sy);\n}\nint merge(int x, int y) {\n\tif(!x || !y) return x + y;\n\tif(too_heavy(a[x].size, a[y].size)) {\n\t\tauto [u, v] = cut(x);\n    \tif(too_heavy(a[v].size + a[y].size, a[u].size)) {\n    \t\tauto [z, w] = cut(v);\n    \t\treturn merge(merge(u, z), merge(w, y));\n   \t\t} else {\n    \t\treturn merge(u, merge(v, y));\n    \t}\n  \t} else if(too_heavy(a[y].size, a[x].size)) {\n\t\tauto [u, v] = cut(y);\n\t\tif(too_heavy(a[u].size + a[x].size, a[v].size)) {\n\t\t\tauto [z, w] = cut(u);\n\t\t\treturn merge(merge(x, z), merge(w, v));\n\t\t} else {\n\t\t\treturn merge(merge(x, u), v);\n\t\t}\n\t} else {\n\t\treturn join(x, y);\n\t}\n}\nstd::pair<int, int> split(int x, int k) {\n\tif(!x) return {0, 0};\n\tif(!k) return {0, x};\n\tif(k == a[x].size) return {x, 0};\n\tauto [u, v] = cut(x);\n\tif(k <= a[u].size) {\n\t\tauto [w, z] = split(u, k);\n\t\treturn {w, merge(z, v)};\n\t} else {\n\t\tauto [w, z] = split(v, k - a[u].size);\n\t\treturn {merge(u, w), z};\n\t}\n}\nint find(int u, int k) {\n\tif(a[u].size == 1) return u;\n\tpushdown(u);\n\tif(k <= a[a[u].ls].size) return find(a[u].ls, k);\n\telse return find(a[u].rs, k - a[a[u].ls].size);\n}\nint build(int n) {\n\tif(n == 1) return newleaf();\n\tint x = build(n / 2);\n\tint y = build(n - n / 2);\n\treturn join(x, y);\n}\nint main() {\n\tstd::ios::sync_with_stdio(false), std::cin.tie(0);\n\tstd::cin >> n >> q;\n\tint rt = build(n);\n\tint lastans = 0;\n\tfor(int i = 1; i <= q; i ++) {\n\t\tint o;\n\t\tstd::cin >> o;\n\t\tif(o == 1) {\n\t\t\tint p;\n\t\t\tstd::cin >> p;\n\t\t\tp = (p + lastans - 1) % n + 1;\n\t\t\tauto [A, B] = split(rt, p);\n\t\t\tsetT(A, id[i] = newtag(i));\n\t\t\trt = merge(A, B);\n\t\t} else if(o == 2) {\n\t\t\tint p;\n\t\t\tstd::cin >> p;\n\t\t\tp = (p + lastans - 1) % n + 1;\n\t\t\tauto [A, B] = split(rt, p);\n\t\t\tsetR(A);\n\t\t\trt = merge(A, B);\n\t\t} else if(o == 3) {\n\t\t\tint x;\n\t\t\tstd::cin >> x;\n\t\t\tx = (x + lastans - 1) % q + 1;\n\t\t\ta[id[x]].exit = 0;\n\t\t} \n\t\tint p;\n\t\tstd::cin >> p;\n\t\tp = (p + lastans - 1) % n + 1;\n\t\tint u = find(rt, p);\n\t\tstd::cout << (lastans = get_val(u)) << '\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "data structures"
    ],
    "rating": 3500
  },
  {
    "contest_id": "2116",
    "index": "A",
    "title": "Gellyfish and Tricolor Pansy",
    "statement": "Gellyfish and Flower are playing a game called \"Duel\".\n\nGellyfish has $a$ HP, while Flower has $b$ HP.\n\nEach of them has a knight. Gellyfish's knight has $c$ HP, while Flower's knight has $d$ HP.\n\nThey will play a game in rounds until one of the players wins. For $k = 1, 2, \\ldots$ in this order, they will perform the following actions:\n\n- If $k$ is odd and Gellyfish's knight is alive:\n\n- Gellyfish's knight can attack Flower and reduce $b$ by $1$. If $b \\leq 0$, \\textbf{Gellyfish wins}. Or,\n- Gellyfish's knight can attack Flower's knight and reduce $d$ by $1$. If $d \\leq 0$, Flower's knight dies.\n\n- If $k$ is even and Flower's knight is alive:\n\n- Flower's knight can attack Gellyfish and reduce $a$ by $1$. If $a \\leq 0$, \\textbf{Flower wins}. Or,\n- Flower's knight can attack Gellyfish's knight and reduce $c$ by $1$. If $c \\leq 0$, Gellyfish's knight dies.\n\nAs one of the smartest people in the world, you want to tell them who will win before the game. Assume both players play optimally.\n\nIt can be proven that the game will never end in a draw. That is, one player has a strategy to end the game in a finite number of moves.",
    "tutorial": "Please think carefully about what happens after the death of either knight. While a player who goes to $0$ HP will lose the game outright, when a player's knight dies, she loses the ability to attack; then in future rounds, she can only be attacked by her opponent and thus lose the game. Thus it can be found that the player herself is as important as her knights, and she loses the game when either of them becomes $0$ HP. Therefore, the optimal strategy for both of them is to attack the one with lower HP. So when $\\min(a, c)$ is greater than or equal to $\\min(b, d)$, Gellyfish wins, otherwise Flower wins. Time complexity: $O(1)$ per test case. Memory complexity: $O(1)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ninline void solve(){\n\tint a = 0, b = 0, c = 0, d = 0;\n\tscanf(\"%d %d %d %d\", &a, &b, &c, &d);\n\tif(min(a, c) >= min(b, d)) printf(\"Gellyfish\\n\");\n\telse printf(\"Flower\\n\");\n}\n\nint T = 0;\n\nint main(){\n\tscanf(\"%d\", &T);\n\tfor(int i = 0 ; i < T ; i ++) solve();\n\treturn 0;\n}",
    "tags": [
      "games",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "2116",
    "index": "B",
    "title": "Gellyfish and Baby's Breath",
    "statement": "Flower gives Gellyfish two permutations$^{\\text{∗}}$ of $[0, 1, \\ldots, n-1]$: $p_0, p_1, \\ldots, p_{n-1}$ and $q_0, q_1, \\ldots, q_{n-1}$.\n\nNow Gellyfish wants to calculate an array $r_0,r_1,\\ldots,r_{n-1}$ through the following method:\n\n- For all $i$ ($0 \\leq i \\leq n-1$), $r_i = \\max\\limits_{j=0}^{i} \\left(2^{p_j} + 2^{q_{i-j}} \\right)$\n\nBut since Gellyfish is very lazy, you have to help her figure out the elements of $r$.\n\nSince the elements of $r$ are very large, you are only required to output the elements of $r$ modulo $998\\,244\\,353$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $b$ is a permutation of an array $a$ if $b$ consists of the elements of $a$ in arbitrary order. For example, $[4,2,3,4]$ is a permutation of $[3,2,4,4]$ while $[1,2,2]$ is not a permutation of $[1,2,3]$.\n\\end{footnotesize}",
    "tutorial": "How to quickly compare $2^a + 2^b$ and $2^c + 2^d$ for given integers $a, b, c, d$ is the key. We are given two permutations of $p$ and $q$, which means that each element will appear only once in both $p$ and $q$, respectively. What's the point of this? For given integers $a, b, c, d$ , if we want to compare $2^a+2^b$ and $2^c+2^d$, we actually need to compare $\\max(a, b)$ with $\\max(c, d)$ first, and $\\min(a, b)$ with $\\min(c, d)$ second. This is due to $2^k = 2^{k-1} + 2^{k-1}$; when $\\max(c, d) < \\max(a, b)$, $2^c + 2^d \\leq 2 \\times 2^{\\max(c, d)} \\leq 2^{\\max(a, b)}$, and it's symmetric for $\\max(a, b) < \\max(c, d)$. So for all $i$, we only need to find $j = \\arg \\max\\limits_{1 \\leq l \\leq i} p_l, k = \\arg \\max\\limits_{1 \\leq l \\leq i} q_l$, then $r_i = \\max(2^{p_j} + 2^{q_{i-j}}, 2^{p_{i-k}} + 2^{q_k})$. This is easily done in $O(n)$ time. Time complexity: $O(n)$ per test case. Memory complexity: $O(n)$ per test case.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nconst int N = 1e5 + 5, Mod = 998244353;\nint n = 0, s[N] = {}, p[N] = {}, q[N] = {}, r[N] = {};\n\ninline void solve(){\n\tscanf(\"%d\", &n);\n\tfor(int i = 0 ; i < n ; i ++) scanf(\"%d\", &p[i]);\n\tfor(int i = 0 ; i < n ; i ++) scanf(\"%d\", &q[i]);\n\tfor(int i = 0, j = 0, k = 0 ; k < n ; k ++){\n\t\tif(p[k] > p[i]) i = k; if(q[k] > q[j]) j = k;\n\t\tif(p[i] != q[j]){\n\t\t\tif(p[i] > q[j]) printf(\"%d \", (s[p[i]] + s[q[k - i]]) % Mod);\n\t\t\telse printf(\"%d \", (s[q[j]] + s[p[k - j]]) % Mod);\n\t\t}\n\t\telse printf(\"%d \", (s[p[i]] + s[max(q[k - i], p[k - j])]) % Mod);\n\t}\n\tprintf(\"\\n\");\n}\n\nint T = 0;\n\nint main(){\n\ts[0] = 1; for(int i = 1 ; i < N ; i ++) s[i] = s[i - 1] * 2 % Mod;\n\tscanf(\"%d\", &T);\n\twhile(T --) solve();\n\treturn 0;\n}",
    "tags": [
      "greedy",
      "math",
      "sortings"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2117",
    "index": "A",
    "title": "False Alarm",
    "statement": "Yousef is at the entrance of a long hallway with $n$ doors in a row, numbered from $1$ to $n$. He needs to pass through all the doors from $1$ to $n$ in order of numbering and reach the exit (past door $n$).\n\nEach door can be open or closed. If a door is open, Yousef passes through it in $1$ second. If the door is closed, Yousef can't pass through it.\n\nHowever, Yousef has a special button which he can use \\textbf{at most once} at any moment. This button makes all closed doors become open for $x$ seconds.\n\nYour task is to determine if Yousef can pass through all the doors if he can use the button at most once.",
    "tutorial": "When is the optimal time to use the button? It's not necessary to use the button when a door is already open. Therefore, it's always optimal to use the button as soon as we hit a closed door. Let's call the position of the first closed door $l$ and the position of the last closed door $r$. The length of this interval is $r - l + 1$, so we need to check that $x$ is greater than or equal to $r - l + 1$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nvoid solve() {\n    int n, x;\n    cin >> n >> x;\n\n    int l = 1e5, r = -1;\n    for(int i = 0; i < n; i++) {\n        int door;\n        cin >> door;\n\n        if(door == 1) {\n            l = min(l, i);\n            r = max(r, i);\n        }\n    }\n\n    cout << (x >= r - l + 1 ? \"YES\" : \"NO\") << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "greedy",
      "implementation"
    ],
    "rating": 800
  },
  {
    "contest_id": "2117",
    "index": "B",
    "title": "Shrink",
    "statement": "A shrink operation on an array $a$ of size $m$ is defined as follows:\n\n- Choose an index $i$ ($2 \\le i \\le m - 1$) such that $a_i \\gt a_{i - 1}$ and $a_i \\gt a_{i + 1}$.\n- Remove $a_i$ from the array.\n\nDefine the score of a permutation$^{\\text{∗}}$ $p$ as the maximum number of times that you can perform the shrink operation on $p$.\n\nYousef has given you a single integer $n$. Construct a permutation $p$ of length $n$ with the \\textbf{maximum} possible score. If there are multiple answers, you can output any of them.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "When are we unable to remove the maximum element? We can always remove the maximum element as long as it exists between two elements. How can we generalize this? In a permutation, the maximum element can only occur once. Since all other elements are guaranteed to be smaller than maximum, we can remove the maximum if there exists an element on its left and another on its right. After we remove the maximum element, another maximum appears, which we also want to remove. This process can keep going until the length of the permutation becomes $2$, since both remaining elements are on the ends and can not be removed. Therefore, any permutation with $1$ and $2$ on the ends is acceptable, since any value greater than $2$ will eventually be a maximum in between two elements.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    \n    for(int i = 2; i <= n; i++) cout << i << ' ';\n    cout << 1 << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 800
  },
  {
    "contest_id": "2117",
    "index": "C",
    "title": "Cool Partition",
    "statement": "Yousef has an array $a$ of size $n$. He wants to partition the array into one or more contiguous segments such that each element $a_i$ belongs to exactly one segment.\n\nA partition is called cool if, for every segment $b_j$, all elements in $b_j$ also appear in $b_{j + 1}$ (if it exists). That is, every element in a segment must also be present in the segment following it.\n\nFor example, if $a = [1, 2, 2, 3, 1, 5]$, a cool partition Yousef can make is $b_1 = [1, 2]$, $b_2 = [2, 3, 1, 5]$. This is a cool partition because every element in $b_1$ (which are $1$ and $2$) also appears in $b_2$. In contrast, $b_1 = [1, 2, 2]$, $b_2 = [3, 1, 5]$ is not a cool partition, since $2$ appears in $b_1$ but not in $b_2$.\n\nNote that after partitioning the array, you do \\textbf{not} change the order of the segments. Also, note that if an element appears several times in some segment $b_j$, it only needs to appear at least once in $b_{j + 1}$.\n\nYour task is to help Yousef by finding the maximum number of segments that make a cool partition.",
    "tutorial": "The last segment of a valid partition must contain all distinct elements of the array. From the first hint, we can say that any segment ending at some position $r$ must contain all distinct elements of the prefix $[1, r]$. Claim: In a valid partition, if a segment ends at some position $r$, it must contain all distinct elements in the prefix $[1, r]$. Call the segments $b_1,b_2,\\dots,b_k$. Notice that an element in some segment $b_j$ must also appear in $b_{j+1}, b_{j+2}, ..., b_k$. Now, let's prove by contradiction. Assume that some segment $b_j$ doesn't contain all distinct elements in $[1, r]$, where $r$ is the end position of $b_j$. Then, the distinct elements that don't appear in $b_j$ surely appear in some previous segment(s). This does not make a valid partition since at least one previous segment contains an element which $b_j$ does not have. Let $d_i$ be the number of distinct elements in the range $[1, i]$. To maximize the number of segments, we make them as small as possible. Let $r$ be the end position for the current segment, we will iterate from $r$ to the left until we find the first position $l$ such that the number of distinct elements in $[l, r] = d_r$, then increment our answer and set $r = l - 1$. We repeat until $l=1$. Similarly to the above solution, we can have a segment $[l, r]$ if and only if $[l, r]$ contains all of the same elements as $[1, r]$. We now build our segments greedily from the front, iterating through each element. Suppose the element we are currently on is $a_i$. We make the following claim: if we can end the current segment at $a_i$, we should do so. (There is one exception to this, which is covered after the proof.) Suppose we are able to end the current segment at $a_i$. Clearly, if $a_i$ is the last element of the array, we must end the segment. Otherwise, suppose that instead, it is optimal to end the segment at $a_j$ for $j>i$. Then we could just instead end the segment at $a_i$, and merge the elements from $a_{i+1}$ to $a_j$ into the next segment. This doesn't cause any issues with legality, because by assumption, it is legal to end the current segment at $a_i$, and the subsequent segment only gets bigger so it has at least as many distinct values as before. Furthermore, this does not affect the number of segments we have, so this is also an optimal solution. Now, we just end segments whenever we can. The only \"special\" case that needs to be taken care of, is whether or not the last segment is legal. But if it isn't, we can simply merge it into the last legal segment, which only makes this segment bigger and thus doesn't cause any issues since it has at least as many distinct values as before. It turns out that this doesn't really affect the implementation, since we just have to count the number of times we can end the segment. So how do we do this quickly? Let's keep a set of all elements in $[1, i]$, and a set of all elements in $[l, i]$. Then if these sets are the same size, we know that $[l, i]$ contains all of the same elements as $[1, i]$. If this is the case, we will end the segment at $i$. Then we will increment our answer, and set $l:=i+1$ (in the implementation, we will clear the set of elements in $[l, i]$).",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n \nvoid solve(){\n    int n, ans = 0;\n    cin >> n;\n    vector<int> a(n);\n    for(int i=0; i<n; i++) cin >> a[i];\n    set<int> cur, seen;\n    for(int i=0; i<n; i++){\n        cur.insert(a[i]);\n        seen.insert(a[i]);\n        if(cur.size() == seen.size()){\n            ans++;\n            seen.clear();\n        }\n    }\n    cout << ans << '\\n';\n}\n \nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(NULL);\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "data structures",
      "greedy"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2117",
    "index": "D",
    "title": "Retaliation",
    "statement": "Yousef wants to explode an array $a_1, a_2, \\dots, a_n$. An array gets exploded when all of its elements become equal to zero.\n\nIn one operation, Yousef can do \\textbf{exactly} one of the following:\n\n- For every index $i$ in $a$, decrease $a_i$ by $i$.\n- For every index $i$ in $a$, decrease $a_i$ by $n - i + 1$.\n\nYour task is to help Yousef determine if it is possible to explode the array using any number of operations.",
    "tutorial": "What happens when we do $1$ operation of the first type and $1$ operation of the second type? If we perform both types of the operation once, each element $a_i$ is decreased by $n + 1$. Suppose we are able to explode the array with $x$ operations of the first type and $y$ operations of the second type. Then, let's pair as many operations as we can, allowing us to perform $\\min(x, y)$ pairs of operations. Now, assume we finished pairing the operations. This leaves us with some operations (possibly none) of only one type, so the array must become an arithmetic sequence; the absolute difference between two consecutive elements is the number of operations that we have to perform. We don't yet know the number of pairs of operations $\\min(x, y)$ that we have to perform, since we don't know the value of $x$ and $y$, but we now know the number of extra operations we perform after pairing the operations. Since we need to have an arithmetic sequence in order to explode the array, we should verify that the difference between adjacent elements are all the same. Let's call the number of extra operations $k = |x-y|$, which is equal to the difference between adjacent elements. If the array is increasing, the extra operations must be of the first type. Otherwise, they must be of the second type. Now, let's first perform the $k$ operations on the array. Since the consecutive differences are all the same, after performing the $k$ extra operations, all elements should be equal. It remains to check that the elements are non-negative and are divisible by $n + 1$, so we can now perform pairs of operations to explode the array. Suppose we did $x$ operations of the first type and $y$ operations of the second type to explode the array. What must the value of $a_1$ be? From the first hint, we know the first element $a_1 = 1 \\cdot x + n \\cdot y$. What about the second element? Let's consider the first two elements. Suppose we needed $x$ operations of the first type and $y$ operations of the second type to explode the array, then we know $a_1 = 1 \\cdot x + n \\cdot y$. For the second element, we know $a_2 = 2 \\cdot x + (n - 1) \\cdot y$. Now, let's solve for $x$ and $y$. Subtracting $a_2$ from $a_1$ gives us $\\begin{align*} a_1 - a_2 &= (x + n \\cdot y) - (2 \\cdot x + (n - 1) \\cdot y) \\newline &= y - x \\newline \\Longrightarrow x &= y - a_1 + a_2 \\end{align*}$ Let's substitute $y - a_1 + a_2$ for $x$ in the first formula. $\\begin{align*} a_1 &= (y - a_1 + a_2) + n \\cdot y \\newline \\Longrightarrow y &= \\frac{2 \\cdot a_1 - a_2}{n + 1} \\end{align*}$ Now, we have the value of $y$, which means we can easily find the value of $x$. From the formula $x = y - a_1 + a_2$, substitute $y$ with its value to get $x$. What remains is just to check if the array becomes $a_1 = a_2 = \\dots = a_n = 0$ after all the operations.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\ntypedef long long ll;\n\nvoid solve() {\n    ll n;\n    cin >> n;\n    vector<ll> v(n);\n    for(auto &it : v) cin >> it;\n\n    ll y = (2 * v[0] - v[1]) / (n + 1);\n    ll x = v[1] - v[0] + y;\n\n    if(y < 0 || x < 0) {\n        cout << \"NO\" << endl;\n        return;\n    }\n\n    for(int i = 0; i < n; i++) {\n        v[i] -= x * (i + 1);\n        v[i] -= y * (n - i);\n    }\n\n    for(int i = 0; i < n; i++) {\n        if(v[i] != 0) {\n            cout << \"NO\" << endl;\n            return;\n        }\n    }\n\n    cout << \"YES\" << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "binary search",
      "math",
      "number theory"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2117",
    "index": "E",
    "title": "Lost Soul",
    "statement": "You are given two integer arrays $a$ and $b$, each of length $n$.\n\nYou may perform the following operation any number of times:\n\n- Choose an index $i$ $(1 \\le i \\le n - 1)$, and set $a_i := b_{i + 1}$, \\textbf{or} set $b_i := a_{i + 1}$.\n\n\\textbf{Before} performing any operations, you are allowed to choose an index $i$ $(1 \\le i \\le n)$ and remove both $a_i$ and $b_i$ from the arrays. This removal can be done \\textbf{at most once}.\n\nLet the number of matches between two arrays $c$ and $d$ of length $m$ be the number of positions $j$ $(1 \\le j \\le m)$ such that $c_j = d_j$.\n\nYour task is to compute the maximum number of matches you can achieve.",
    "tutorial": "If we can get a match at position $i$, then we can have at least $i$ matches. Why is this true? For a certain position $i$, given the ability to remove index $i + 1$, we can pull any value from the range $[i + 2, n]$. It's clear to see that if a match exists at position $i$, then we can repeatedly set $a_j := b_{j+1}$ and $b_j := a_{j+1}$ for all $j$, where $j$ starts as $i - 1$ and goes backwards until the start of the array. This allows us to have at least $i$ matches (including the match at position $i$). Therefore, the optimal approach is to maximize the index $i$ where $a_i = b_i$. Suppose we can't remove any element. Then, for some $a_i$, we can set it to any $b_j$ such that $j \\pmod 2 \\neq i \\pmod 2$ and $j \\gt i$, or set it to any $a_j$ such that $j \\pmod 2 = i \\pmod 2$ and $j \\gt i$. However, if we wanted to set $a_i$ to some $b_j$ where $j \\pmod 2 = i \\pmod 2$, then we can just remove index $i + 1$ from the array. By similar reasoning, we can set $a_i$ to any $a_j$ where $j \\pmod 2 \\neq i \\pmod 2$ and $j \\gt i+1$. Notice that we removed index $i + 1$, so we can't set $a_i := a_{i+1}$. Now, we know that we can set any $a_i$ to any $a_j$ or $b_j$ such that $j \\gt i + 1$. This can be generalized for $b_i$ as well. So the solution is that, for each position $i$, we want to check if any $a_j$ or $b_j$, such that $j > i + 1$, matches $a_i$ or $b_i$, allowing us to get a match at position $i$. We also need to check if position $i$ already contains a match, or if $a_i = a_{i + 1}$ or $b_i = b_{i + 1}$.",
    "code": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nvoid solve() {\n    int n;\n    cin >> n;\n    vector<int> a(n), b(n);\n\n    for(auto &it : a) cin >> it;\n    for(auto &it : b) cin >> it;\n\n    vector<bool> seen(n + 1);\n    if(a.back() == b.back()) {\n        cout << n << endl;\n        return;\n    }\n\n    int ans = -1;\n    for(int i = n - 2; i >= 0; i--) {\n        if(a[i] == b[i] || a[i] == a[i + 1] || b[i] == b[i + 1] || seen[a[i]] || seen[b[i]]) {\n            ans = i;\n            break;\n        }\n\n        seen[a[i + 1]] = seen[b[i + 1]] = true;\n    }\n\n    cout << ans + 1 << endl;\n}\n\nint main() {\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "brute force",
      "greedy"
    ],
    "rating": 1600
  },
  {
    "contest_id": "2117",
    "index": "F",
    "title": "Wildflower",
    "statement": "Yousef has a rooted tree$^{\\text{∗}}$ consisting of exactly $n$ vertices, which is rooted at vertex $1$. You would like to give Yousef an array $a$ of length $n$, where each $a_i$ $(1 \\le i \\le n)$ \\textbf{can either be $1$ or $2$}.\n\nLet $s_u$ denote the sum of $a_v$ where vertex $v$ is in the subtree$^{\\text{†}}$ of vertex $u$. Yousef considers the tree special if all the values in $s$ are \\textbf{pairwise distinct} (i.e., all subtree sums are unique).\n\nYour task is to help Yousef count the number of different arrays $a$ that result in the tree being special. Two arrays $b$ and $c$ are different if there exists an index $i$ such that $b_i \\neq c_i$.\n\nAs the result can be very large, you should print it modulo $10^9 + 7$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected undirected graph with $n - 1$ edges.\n\n$^{\\text{†}}$The subtree of a vertex $v$ is the set of all vertices that pass through $v$ on a simple path to the root. Note that vertex $v$ is also included in the set.\n\\end{footnotesize}",
    "tutorial": "There can only be at most $2$ leaves. This means the tree can either be a chain or Y-shaped. If the tree is a chain, subtree sums will always be strictly increasing as you move towards the root, which means that the answer for any chain is $2^n$. Claim: For an answer to exist, the tree should have at most $2$ leaves. We can use pigeonhole principle. Suppose the tree has more than $2$ leaves. Then for each leaf $\\ell$, its subtree sum is $a_\\ell \\in \\lbrace 1,2 \\rbrace$. By pigeonhole principle, among three leaves there must be two with the same value, forcing subtree sums to not be unique. Thus, it is impossible to make all values in $s$ pairwise distinct if there are $3$ or more leaves. We only need to consider two cases, the case of $1$ leaf and the case of $2$ leaves. $1$ leaf case: We can see that $\\lbrace 1,2 \\rbrace$ are positive values, so $s$ is strictly increasing as you move towards the root. Therefore, any array $a$ will be valid. The answer for this case would be $2^n$. $2$ leaves case: Let $v$ be the lowest common ancestor between leaf $x$ and leaf $y$. From $v$ going up towards the root, we can see that it follows the same idea of the $1$ leaf case, which means that any vertex in the path between the root and $v$ can be assigned to either $1$ or $2$. Without loss of generality, suppose leaf $x$ has smaller depth than leaf $y$. Say we assigned $a_x = 1$ and $a_y = 2$; it is easy to see that we are forced to assign vertices to $2$ as we're going up, until we eventually finish assigning a branch. So the number of vertices that are free to be assigned to either $1$ or $2$ in $y$'s branch is simply $\\texttt{depth}_y - \\texttt{depth}_x$. If we assign $a_x = 2$ and $a_y = 1$ instead, then $y$ would have one more vertex forced to be assigned to $2$, meaning there are only $\\texttt{depth}_y - \\texttt{depth}_x - 1$ free vertices in $y$'s branch. Finally, the last case to be checked is if $\\texttt{depth}_x = \\texttt{depth}_y$. In this case, whether we assign $x$ to $1$ and $y$ to $2$, or we assign $x$ to $2$ and $y$ to $1$, all vertices in both branches are forced, so there are no free vertices in either branch. Let the number of leaves be $\\texttt{cnt}$. Then we have that: $\\texttt{Answer}$ = $\\begin{cases} 0 &\\text{if }\\texttt{cnt} > 2 \\newline 2^n &\\text{if }\\texttt{cnt} = 1 \\newline (2^{\\texttt{depth}_y - \\texttt{depth}_x} + 2^{\\texttt{depth}_y - \\texttt{depth}_x - 1}) \\cdot 2^{\\texttt{depth}_v} &\\text{if }\\texttt{cnt} = 2\\text{ and }\\texttt{depth}_x < \\texttt{depth}_y \\newline 2^{\\texttt{depth}_v} + 2^{\\texttt{depth}_v} &\\text{if }\\texttt{cnt} = 2\\text{ and }\\texttt{depth}_x = \\texttt{depth}_y \\end{cases}$",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nconst int N = 2e5 + 10, MOD = 1e9 + 7;\n#define int long long\n \nvector<int> adj[N], lens;\nint pw[N];\nint lca;\n \nvoid dfs(int u, int par, int len) {\n    if(adj[u].size() > 2) lca = len;\n    \n    bool leaf = true;\n    for(int v : adj[u]) {\n        if(v != par) {\n            dfs(v, u, len + 1);\n            leaf = false;\n        }\n    }\n \n    if(leaf) lens.push_back(len);\n}\n\nvoid solve() {\n    int n;\n    cin >> n;\n\n    for(int i = 1; i <= n; i++) adj[i].clear();\n    lens.clear();\n    lca = -1;\n\n    for(int i = 0; i < n - 1; i++) {\n        int u, v;\n        cin >> u >> v;\n        adj[u].push_back(v);\n        adj[v].push_back(u);\n    }\n\n    adj[1].push_back(0); // dummy node\n    dfs(1, 0, 1);\n    if(lens.size() > 2) cout << 0 << endl;\n    else if(lens.size() == 1) cout << pw[n] << endl;\n    else {\n        int diff = abs(lens[0] - lens[1]);\n        int x = diff + lca;\n        if(diff) cout << (pw[x] + pw[x - 1]) % MOD << endl;\n        else cout << (2 * pw[x]) % MOD << endl;\n    }\n}\n\nsigned main() {\n    pw[0] = 1;\n    for(int i = 1; i < N; i++) pw[i] = (pw[i - 1] * 2) % MOD;\n\n    int t;\n    cin >> t;\n    while(t--) solve();\n}",
    "tags": [
      "combinatorics",
      "dfs and similar",
      "trees"
    ],
    "rating": 1800
  },
  {
    "contest_id": "2117",
    "index": "G",
    "title": "Omg Graph",
    "statement": "You are given an undirected connected weighted graph. Define the cost of a path of length $k$ to be as follows:\n\n- Let the weights of all the edges on the path be $w_1,...,w_k$.\n- The cost of the path is $(\\min_{i = 1}^{k}{w_i}) + (\\max_{i=1}^{k}{w_i})$, or in other words, the maximum edge weight + the minimum edge weight.\n\nAcross all paths from vertex $1$ to $n$, report the cost of the path with minimum cost. Note that the path is not necessarily simple.",
    "tutorial": "Try fixing the minimum edge on the path. There are two common ways to solve this problem; one uses DSU and the other uses Dijkstra. I will explain the Dijkstra approach here: The main idea here is to pick some edge $e$ and pretend that $e$ is the minimum-weight edge, then find the smallest maximum edge weight across all paths containing $e$. This method will only ever overestimate the answer, and equality holds when we choose $e$ to be the minimum-weight edge of the optimal path, so the answer must be the minimum of these values across all possible choices. Lets define a new cost function. Instead of $cost(w_1,...,w_k) = (\\min_{i = 1}^{k}{w_i}) + (\\max_{i=1}^{k}{w_i})$, let's define $cost_j(w_1,...,w_k) = w_j + (\\max_{i=1}^{k}{w_i})$, i.e. the weight of edge $j$ + the max weight. By the above reasoning, the minimum value of $cost_j(w_1,...,w_k)$ across all $j$ is the same as the minimum value of $cost(w_1,...,w_k)$. This function is a lot easier to minimize than the initial one. Let's iterate over each edge $j$ - denote its endpoints to be $u_j$ and $v_j$, and its weight to be $w_j$ - and find the minimum value of $cost_j(w_1,...,w_k)$. Now we just need to find the minimum possible value of $\\max_{i=1}^{k}{w_i}$ across all paths that contain $j$. To do this, we just want to minimize the max weight of the path from $1$ to $u$ and from $v$ to $n$, so we have reduced the problem to finding the minimum max weight on a path from $1$ to all other nodes, and finding the minimum max weight on a path from every node to $n$. But how do we do this? The idea is very similar to Dijkstra - recall the proof that Dijkstra finds the minimum sum of weights on a path. The main idea is that whenever we pop a node from the heap, we know that the minimum cost to it has already been found. We can use the same reasoning to prove that if we change path cost from path sum to path max, then the algorithm will still work. So all we have to do is simply run this max Dijkstra variation from $1$ and from $n$. Now we just need to find the minimum value of $w_i + \\max(\\mathrm{cost}(1, u_i), \\mathrm{cost}(v_i, n), w_i)$ across all edges $i$.",
    "code": "#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long ll;\n#define debug(x) cout << #x << \" = \" << x << \"\\n\";\n#define vdebug(a) cout << #a << \" = \"; for(auto x: a) cout << x << \" \"; cout << \"\\n\";\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\nint uid(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }\nll uld(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(rng); }\n\nvoid solve(){\n    int n, m;\n    cin >> n >> m;\n\n    vector<vector<array<int, 2>>> g(n);\n    for (int i = 0; i < m; i++){\n        int u, v, w;\n        cin >> u >> v >> w;\n        u--;\n        v--;\n\n        g[u].push_back({v, w});\n        g[v].push_back({u, w});\n    }\n\n    auto uwu = [&](int u) -> vector<ll>{\n        vector<ll> dis(n, 1e18);\n        vector<bool> vis(n);       \n\n        priority_queue<array<ll, 2>> q;\n        q.push({0, u});\n        while (q.size()){\n            auto [d, c] = q.top();\n            d = -d;\n            q.pop();\n\n            if (vis[c])\n                continue;\n            vis[c] = true;\n            dis[c] = d;\n\n            for (auto [x, w] : g[c]){\n                if (vis[x])\n                    continue;\n\n                q.push({-max(d, 1LL * w), x});\n            }\n        }\n\n        return dis;\n    };\n\n    ll ans = 1e18;\n    vector<ll> dis_s = uwu(0), dis_t = uwu(n - 1);\n    for (int u = 0; u < n; u++){\n        for (auto [v, w] : g[u]){\n            ans = min(ans, {max({dis_s[u], dis_t[v], 1LL * w}) + w});\n        }\n    }\n\n    cout << ans << \"\\n\";\n}\n\nint main(){\n    ios::sync_with_stdio(false);\n    cin.tie(0);\n    \n    int t;\n    cin >> t;\n    while (t--) solve();\n}\n",
    "tags": [
      "brute force",
      "dsu",
      "graphs",
      "greedy",
      "shortest paths",
      "sortings"
    ],
    "rating": 1900
  },
  {
    "contest_id": "2117",
    "index": "H",
    "title": "Incessant Rain",
    "statement": "\\textbf{Note the unusual memory limit.}\n\nSilver Wolf gives you an array $a$ of length $n$ and $q$ queries. In each query, she replaces an element in $a$. After each query, she asks you to output the maximum integer $k$ such that there exists an integer $x$ such that it is the $k$-majority of a subarray$^{\\text{∗}}$ of $a$.\n\nAn integer $y$ is the $k$-majority of array $b$ if $y$ appears at least $\\lfloor \\frac{|b|+1}{2} \\rfloor +k$ times in $b$, where $|b|$ represents the length of $b$. Note that $b$ may not necessarily have a $k$-majority.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.\n\\end{footnotesize}",
    "tutorial": "Try to think of an offline solution. Rephrase the problem to maximum subarray sums. The unusual memory limit is meant to cut persistent segment tree solutions. Obviously it isn't perfect (I apologize if it caused issues), but it's the best I could do. Let's first pretend that $x$ in the problem is fixed. For example, if $x = 2$, then we want to find the maximum $k$ such that $2$ is a $k$-majority of some subarray. To solve this problem, let's build an array $b_1, b_2, \\ldots, b_n$ such that $b_i = 1$ if $a_i = x$, and $b_i = -1$ otherwise. Let $s$ be the maximum subarray sum over all subarrays of $b$. The answer to the problem is $\\lfloor \\frac{s}{2} \\rfloor$. Now let's consider how to handle updates. If we are asked to update index $k$ with an element $y$, we have two cases. If $a_k \\neq x$ and $y=x$, then we update $b_k = 1$. Otherwise, if $a_k = x$ and $y \\neq x$, then we set $b_k = -1$. Then, we can answer the query by finding the maximum subarray sum of $b$ using a segment tree. This is a standard problem. Let $b_i$ denote the sequence of arrays that correspond to the array $b$ that fixes $i$. Now let's stop fixing $x$. For each update, notice that at most two of the arrays in the sequence is modified (precisely, $b_{a_k}$ and $b_y$). To answer the query, let $\\texttt{res}_x$ denote the answer maximum subarray sums of arrays $b_x$ for all $x \\in [1, n]$ so far. The answer to this query is just $\\lfloor \\frac{\\max(\\texttt{res}_1, \\texttt{res}_2, \\ldots, \\texttt{res}_n)}{2} \\rfloor$. Additionally, because of the update, notice that only $\\texttt{res}_{a_k}$ and $\\texttt{res}_y$ might change. This motivates an approach where we track $\\texttt{res}_x$ overall all $x$ and extract the maximum. For each $x$, let's keep track of all updates that modifies an index $k$ where it was $a_k = x$ originally or $a_k = x$ after the update. Let Notice that for the former case, we are setting $b_{x_k} = -1$ and in the latter case, we are setting $b_{x_k} = -1$. Notice that we are tracking at most $2q$ updates because each update modifies at most two $b_x$, as explained in the previous paragraph. Let's store all such updates in an array $v_x$. Let's try to construct $b_x$ for each $x \\in [1, n]$ now. To do so, let's first create a global array $b$, where initially $b_i = -1$ over all $1 \\leq i \\leq n$. Then, we can iterate over all elements of $a$ where $a_j = x$ and set $b_j = 1$. Now we can iterate over the queries in $v_x$. For each query in $v_x$, we can track the maximum subarray sum of $b$ after each update. If this is the $j$'th query, then we must note that after the $j$'th query, we will update $\\texttt{res}_x$. We can iterate over all $x \\in [1, n]$ and perform the above process in $O((n + q)\\log n))$ time total. Now, we know when to update $\\texttt{res}_x$ for each $x \\in [1, n]$. Finally, let's loop through all $q$ queries one last time and store all $\\texttt{res}_x$ in a multiset. If the $j$'th query affects $\\texttt{res}_y$, then we will erase the old $\\texttt{res}_y$ from the multiset and replace it with the new one. To answer the query, we can simply extract the maximum element in the multiset. First, consider the $k$-majority for a single element $y$. By definition, for a subarray $b$, the $k$-majority is given by $\\lfloor{\\frac{2 \\cdot \\text{cnt}(y) - |b|}{2}}\\rfloor$. Instead of computing this directly, we construct a new array $c$, where $c_i = 1$ if $b_i = y$ and $c_i = -1$ otherwise. Then, the $k$-majority for the element $y$ is equivalent to the maximum sum among all subarrays of $c$, floor-divided by 2. This transformation reduces our problem to finding the maximal subarray sum. Since we must efficiently handle updates, we require a dynamic data structure capable of both updates and queries. This can be accomplished using a segment tree that maintains the maximum subarray sum, maximum prefix sum, maximum suffix sum, and total sum within each node. To apply this method to all possible values of $y$, we process all queries offline. Initially, we set all elements of array $c$ to $-1$. For each distinct element $y$, we first update the array $c$ by setting $c_i = 1$ wherever $a_i$ initially equals $y$. Next, we sequentially apply all updates involving $y$, calculating the maximal $k$-majority for $y$ after each update. This procedure generates $q + n$ segments, each segment holding the maximal $k$-majority information for an element $y$. By inserting and removing these maximum values into a multiset, we efficiently retrieve the global maximal $k$-majority at every step. Giving $O((n + q)\\log n)$.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nusing ll = long long;\n#define F first\n#define S second\n#define all(x) x.begin(), x.end()\n#define pb push_back\n#define FOR(i,a,b) for(int i = (a); i < (b); ++i)\n#define trav(a,x) for(auto& a: x)\n#define sz(x) (int)x.size()\ntemplate<typename T> istream& operator>>(istream& in, vector<T>& a) {for(auto &x : a) in >> x; return in;};\n\nstruct Node {\n    int sum;    // total sum of segment\n    int pref;   // max prefix sum\n    int suff;   // max suffix sum\n    int best;   // max subarray sum\n    Node(): sum(0), pref(0), suff(0), best(0) {}\n    Node(int x): sum(x), pref(max(0,x)), suff(max(0,x)), best(max(0,x)) {}\n};\n\nNode merge(const Node &L, const Node &R) {\n    Node res;\n    res.sum  = L.sum + R.sum;\n    res.pref = max(L.pref, L.sum + R.pref);\n    res.suff = max(R.suff, R.sum + L.suff);\n    res.best = max({ L.best, R.best, L.suff + R.pref });\n    return res;\n}\n\nstruct segtree {\n    int n;\n    vector<Node> st;\n     segtree(int _n) {\n        n = _n;\n        st.resize(4*n);\n        build(1, 0, n-1);\n    }\n    void build(int p, int l, int r) {\n        if (l == r) {\n            st[p] = Node(-1);\n            return;\n        }\n        int m = (l + r) / 2;\n        build(p<<1,   l,   m);\n        build(p<<1|1, m+1, r);\n        st[p] = merge(st[p<<1], st[p<<1|1]);\n    }\n    void update(int p, int l, int r, int idx, int val) {\n        if (l == r) {\n            st[p] = Node(val);\n            return;\n        }\n        int m = (l + r) / 2;\n        if (idx <= m) update(p<<1,   l,   m, idx, val);\n        else          update(p<<1|1, m+1, r, idx, val);\n        st[p] = merge(st[p<<1], st[p<<1|1]);\n    }\n    void update(int idx, int val) {\n        update(1, 0, n-1, idx, val);\n    }\n    Node query(int p, int l, int r, int i, int j) {\n        if (i > r || j < l) {\n            Node nullnode;\n            nullnode.sum = 0;\n            nullnode.pref = nullnode.suff = nullnode.best = INT_MIN;\n            return nullnode;\n        }\n        if (l >= i && r <= j) {\n            return st[p];\n        }\n        int m = (l + r) / 2;\n        Node L = query(p<<1,   l,   m, i, j);\n        Node R = query(p<<1|1, m+1, r, i, j);\n        if (L.best == INT_MIN) return R;\n        if (R.best == INT_MIN) return L;\n        return merge(L, R);\n    }\n    int max_subarray() {\n        Node res = query(1, 0, n-1, 0, n-1);\n        return res.best;\n    }\n};\n\nvoid solve() {\n\tint n, q; cin >> n >> q;\n\tvector<int> a(n); cin >> a;\n\tvector<vector<int>> at(n+1);\n\tFOR(i,0,n) at[a[i]].pb(i);\n\tvector<vector<array<int, 3>>> updates(n+1);\n\tFOR(idx,0,q){\n\t\tint i, x; cin >> i >> x;\n\t\t--i;\n\t\tif(x != a[i]){\n\t\t\tupdates[a[i]].pb({idx, i, -1});\n\t\t\ta[i] = x;\n\t\t\tupdates[x].pb({idx, i, 1});\n\t\t}\n\t}\n\tvector<vector<int>> final_at(n+1);\n\tFOR(i,0,n) final_at[a[i]].pb(i);\n\tsegtree st(n);\n\tvector<int> init(n+1);\n\tvector<vector<pair<int,int>>> change(q);\n\tFOR(x,1,n+1){\n\t\ttrav(i, at[x]){\n\t\t\tst.update(i, 1);\n\t\t}\n\t\tint cur = st.max_subarray();\n\t\tinit[x] = cur;\n\t\ttrav(i, updates[x]){\n\t\t\tst.update(i[1], i[2]);\n\t\t\tint new_cur = st.max_subarray();\n\t\t\tchange[i[0]].pb({cur, new_cur});\n\t\t\tcur = new_cur;\n\t\t}\n\t\ttrav(i, final_at[x]){\n\t\t\tst.update(i, -1);\n\t\t}\n\t}\n\tmultiset<int> ms;\n\tFOR(i,1,n+1) ms.insert(init[i]);\n\tFOR(i,0,q){\n\t\ttrav(j, change[i]){\n\t\t\tms.erase(ms.find(j.F));\n\t\t\tms.insert(j.S);\n\t\t}\n\t\tcout << *prev(ms.end())/2 << \" \";\n\t}\n\tcout << \"\\n\";\n}\n\nsigned main() {\n\tcin.tie(0) -> sync_with_stdio(0);\n\tint t = 1;\n\tcin >> t;\n\tfor(int test = 1; test <= t; test++){\n\t\tsolve();\n\t}\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "sortings"
    ],
    "rating": 2500
  },
  {
    "contest_id": "2118",
    "index": "A",
    "title": "Equal Subsequences",
    "statement": "We call a bitstring$^{\\text{∗}}$ perfect if it has the same number of $\\mathtt{101}$ and $\\mathtt{010}$ subsequences$^{\\text{†}}$. Construct a perfect bitstring of length $n$ where the number of $\\mathtt{1}$ characters it contains is exactly $k$.\n\nIt can be proven that the construction is always possible. If there are multiple solutions, output any of them.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A bitstring is a string consisting only of the characters $\\mathtt{0}$ and $\\mathtt{1}$.\n\n$^{\\text{†}}$A sequence $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly zero or all) characters.\n\\end{footnotesize}",
    "tutorial": "It is somehow difficult to count the number of such subsequences in an arbitrary string. Can you think of strings where it is trivial? The number of such subsequences can be $0$. Key observation: A bitstring where all $\\mathtt{1}$ bits come before all $\\mathtt{0}$ bits is perfect as it has no $\\mathtt{101}$ or $\\mathtt{010}$ subsequences. You can fix the number of $\\mathtt{1}$ bits to be $k$ and then put $n-k$ $\\mathtt{0}$ bits after them. This achieves a perfect bitstring with the number of $\\mathtt{1}$ bits being $k$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\n \nint main() {\n    int t; cin >> t;\n    for (int tc = 1; tc <= t; tc++) {\n        int n, k; cin >> n >> k;\n        for (int i = 0; i < n-k; i++) cout << 0;\n        for (int i = 0; i < k; i++) cout << 1;\n        cout << \"\\n\";\n        \n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy"
    ],
    "rating": 800
  },
  {
    "contest_id": "2118",
    "index": "B",
    "title": "Make It Permutation",
    "statement": "There is a matrix $A$ of size $n\\times n$ where $A_{i,j}=j$ for all $1 \\le i,j \\le n$.\n\nIn one operation, you can select a row and reverse any subarray$^{\\text{∗}}$ in it.\n\nFind a sequence of at most $2n$ operations such that every column will contain a permutation$^{\\text{†}}$ of length $n$.\n\nIt can be proven that the construction is always possible. If there are multiple solutions, output any of them.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deleting zero or more elements from the beginning and zero or more elements from the end.\n\n$^{\\text{†}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).\n\\end{footnotesize}",
    "tutorial": "The answer matrix will have permutations in every row and column. Can you think of such a matrix? Let our final matrix have all cyclic shifts of the identity permutation in each row. Can you perform a cyclic shift using $3$ operations? One of the operations performed on each row becomes redundant. Key observation: You can cyclic shift an array using $3$ operations. The operations to achieve this are \"$1$ $n$\", \"$1$ $i$\", \"$i+1$ $n$\". Perform these with a different $i$ for each row, you will obtain all cyclic shifts of the identity permutation. To optimize it to $2n$ operations observe that performing \"$1$ $n$\" on each row does nothing.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nusing ll = long long;\n \nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int t; cin >> t;\n    for (int tc = 1; tc <= t; tc++) {\n        int n; cin >> n;\n        cout << 2*n-1 << \"\\n\";\n        for (int i = 1; i < n; i++) {\n            cout << i << \" \" << 1 << \" \" << i << \"\\n\";\n            cout << i << \" \" << i+1 << \" \" << n << \"\\n\";\n        }\n        cout << n << \" 1 \" << n << \"\\n\";\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms"
    ],
    "rating": 1200
  },
  {
    "contest_id": "2118",
    "index": "C",
    "title": "Make It Beautiful",
    "statement": "You are given an array $a$ of $n$ integers. We define the $\\text{beauty}$ of a number $x$ to be the number of $1$ bits in its binary representation. We define the beauty of an array to be the sum of beauties of the numbers it contains.\n\nIn one operation, you can select an index $i$ $(1 \\le i \\le n)$ and increase $a_i$ by $1$.\n\nFind the maximum beauty of the array after doing \\textbf{at most} $k$ operations.",
    "tutorial": "Think in binary. Let $x$ be an integer. What is the smallest number $y>x$ that is more beautiful than $x$? $y$ always equals $x$ with the smallest valued $0$ bit set to $1$. Key observation: To increase the beauty of a number, it is always optimal to set the least valued $0$ bit to $1$. Let our number be $x$ and call the least valued $0$ bit special. Let $y$ be $x$ with the special bit set to $1$. To increase the beauty, we must increase $x$ by at least $1$. This will set the special bit to $1$, and all bits with a smaller value to $0$. Until we reach $y$, there will always be at least one $0$ bit with a smaller value than the special bit while the bits with a higher value stay the same. This means that no number is more beautiful between $x$ and $y$, showing that the observation is correct. From this, we can construct a solution. Let us count the number of $0$ bits at each position. Iterate from the least valued bit to the highest. Greedily set one such bit to $1$ until we run out of $0$ bits or the remaining $k$ is less than the value of the bit. This solution has a time complexity $O(N\\log{10^{18}})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nusing ll = long long;\n \nvoid solve() {\n    ll n, k; cin >> n >> k;\n    ll ans = 0;\n    vector<ll> a(n);\n    for (ll &i : a) {\n        cin >> i;\n        ans += __builtin_popcountll(i);\n    }\n    for (int j = 0; j <= 60; j++) {\n        ll bb = (1ll<<j);\n        for (ll x : a) {\n            if (!(x & bb) && k >= bb) {\n                ans++;\n                k -= bb;\n            }\n        }\n    }\n    cout << ans << \"\\n\";\n}\n \nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int tc; cin >> tc;\n    while (tc--) solve();\n    return 0;\n}",
    "tags": [
      "bitmasks",
      "data structures",
      "greedy",
      "math"
    ],
    "rating": 1300
  },
  {
    "contest_id": "2118",
    "index": "D2",
    "title": "Red Light, Green Light (Hard version)",
    "statement": "\\textbf{This is the hard version of the problem. The only difference is the constraint on $k$ and the total sum of $n$ and $q$ across all test cases. You can make hacks only if both versions of the problem are solved.}\n\nYou are given a strip of length $10^{15}$ and a constant $k$. There are exactly $n$ cells that contain a traffic light; each has a position $p_i$ and an initial delay $d_i$ for which $d_i < k$. The $i$-th traffic light works the following way:\n\n- it shows red at the $l \\cdot k + d_i$-th second, where $l$ is an integer,\n- it shows green otherwise.\n\nAt second $0$, you are initially positioned at some cell on the strip, facing the positive direction. At each second, you perform the following actions in order:\n\n- If the current cell contains a red traffic light, you turn around.\n- Move one cell in the direction you are currently facing.\n\nYou are given $q$ different starting positions. For each one, determine whether you will eventually leave the strip within $10^{100}$ seconds.",
    "tutorial": "Divide the problem into some subproblems: Find the next traffic light efficiently. Detect cycles efficiently. For D1 it is enough to do the first subproblem in $O(N)$, the second subproblem with $O(N)$ calls of the first subproblem. For D2 we need to do better. Try to simulate the problem by hand. Iterate over all traffic lights and check if we would collide with it if we don't turn. Then we can select the next traffic light in the correct direction. This is $O(N)$. If we collide with the same traffic light from the same direction twice than the answer is no. For detecting cycles we can store visited traffic lights that we collided together with direction. Notice that we can only collide with a specific traffic light in a unique time modulo $k$. This solution has a time complexity $O(Q*N^2)$. First, let's quickly find the next traffic light in the positive direction. Imagine movement by moving along diagonals, refer to the images in the statement for a visual representation. Group the traffic lights by $(d_i-p_i)\\bmod k$, when at position $x$ at time $t$ you will collide with the group of $(t-x)\\bmod k$. We can binary search the next position on this. To do the same for the anti-diagonals you can group by $(d_i+p_i)\\bmod k$ and search by $(t+x)\\bmod k$. We can still simulate each query, but after finding out the answer you can store for each state the result. In later queries, you can refer to the already checked states. In total, you will only check each state at most once. Alternatively, you can notice that after colliding with a traffic light in a specific direction, the next traffic light will always be the same. From this you can build a graph and detect cycles before reading queries. Both solutions have a time complexity of $O(N\\log{N})$.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nusing ll = long long;\n \nvoid solve() {\n    ll m, k; cin >> m >> k;\n    vector<ll> p(m+1), d(m+1);\n    for (int i = 1; i <= m; i++) cin >> p[i];\n    for (int i = 1; i <= m; i++) cin >> d[i];\n    map<ll, vector<ll>> mpl, mpr;\n    map<ll, ll> traffic;\n    for (int i = 1; i <= m; i++) {\n        traffic[p[i]] = d[i];\n        mpl[(d[i]+p[i])%k].emplace_back(p[i]);\n        mpr[(((d[i]-p[i])%k)+k)%k].emplace_back(p[i]);\n    }\n \n    auto get_next_left = [&](ll pos, ll t) {\n        ll val = (t + pos) % k;\n        auto &vec = mpl[val];\n        auto it = lower_bound(vec.begin(), vec.end(), pos);\n        if (it == vec.begin()) return -1ll;\n        it--;\n        return *it;\n    };\n \n    auto get_next_right = [&](ll pos, ll t) {\n        ll val = (((t - pos) % k) + k) % k;\n        auto &vec = mpr[val];\n        auto it = lower_bound(vec.begin(), vec.end(), pos+1);\n        if (it == vec.end()) return -1ll;\n        return *it;\n    };\n \n    map<pair<ll, ll>, bool> dp;\n \n    int q; cin >> q;\n \n    for (int i = 1; i <= q; i++) {\n        ll x; cin >> x;\n        ll dir = 1, t = 0;\n \n        set<pair<ll, ll>> states;\n \n        bool ok = false;\n        if (traffic.count(x) && traffic[x] == 0) dir ^= 1;\n \n        for (int it = 0; it < 2*m; it++) {\n \n            ll y = dir ? get_next_right(x, t) : get_next_left(x, t);\n            if (y == -1) {\n                ok = true;\n                break;\n            } else {\n                t += abs(y-x);\n                x = y;\n                dir ^= 1;\n            }\n \n            if (states.count({x, dir})) break;\n            states.insert({x, dir});\n \n            if (dp.count({x, dir})) {\n                ok = dp[{x, dir}];\n                break;\n            }\n        }\n \n        for (auto [a, b] : states) {\n            dp[{a, b}] = ok;\n        }\n \n        cout << (ok?\"YES\\n\":\"NO\\n\");\n    }\n \n}\n \nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int t = 1;\n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dfs and similar",
      "dp",
      "graphs",
      "implementation",
      "math",
      "number theory"
    ],
    "rating": 2200
  },
  {
    "contest_id": "2118",
    "index": "E",
    "title": "Grid Coloring",
    "statement": "There is a $n\\times m$ grid with each cell initially white. You have to color all the cells one-by-one. After you color a cell, all the \\textbf{colored cells} furthest from it receive a penalty. Find a coloring order, where no cell has more than $3$ penalties.\n\n\\textbf{Note that $n$ and $m$ are both odd.}\n\nThe distance metric used is the chessboard distance while we decide ties between cells with Manhattan distance. Formally, a cell $(x_2, y_2)$ is further away than $(x_3, y_3)$ from a cell $(x_1, y_1)$ if one of the following holds:\n\n- $\\max\\big(\\lvert x_1 - x_2 \\rvert, \\lvert y_1 - y_2 \\rvert\\big)>\\max\\big(\\lvert x_1 - x_3 \\rvert, \\lvert y_1 - y_3 \\rvert\\big)$\n- $\\max\\big(\\lvert x_1 - x_2 \\rvert, \\lvert y_1 - y_2 \\rvert\\big)=\\max\\big(\\lvert x_1 - x_3 \\rvert, \\lvert y_1 - y_3 \\rvert\\big)$ \\textbf{and} $\\lvert x_1 - x_2 \\rvert + \\lvert y_1 - y_2 \\rvert>\\lvert x_1 - x_3 \\rvert + \\lvert y_1 - y_3 \\rvert$\n\nIt can be proven that at least one solution always exists.\n\n\\begin{center}\n{\\small Example showing penalty changes after coloring the center of a $5 \\times 5$ grid. The numbers indicate the penalty of the cells.}\n\\end{center}",
    "tutorial": "Why is it important that both $N$ and $M$ are odd? Try generalizing the trivial case when $N=1$. Try extending the solution from a smaller case... in a literal sense. Key observation: Having $N \\ge M$ and N, M both odd, an $(N - 2) \\times M$ grid can easily be extended into a $N \\times M$ grid To achieve this first color a cell in the middle of both of the $M$ long sides. By this we ensure that the rectangle will be so wide that its side will be at maximum chessboard distance from each other. This means that any cells colored next to one of its sides can only increase the penalty of cells of the opposite side. By coloring cells alternating up and down on each side (similarly to the solution to the case $N=1$) we can ensure that every cell gets at most $2$ penalty. This only leaves the corners as corner cases (as they can be increased from two sides), but they can also be solved by choosing the order of vertical and horizontal extensions correctly.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nusing ll = long long;\n \nvoid solve() {\n    int n, m; cin >> n >> m;\n    \n    auto print = [&](int x, int y) {\n        if (1 <= x && x <= n && 1 <= y && y <= m) {\n            cout << x << \" \" << y << \"\\n\";\n        }\n    };\n    \n    int cx = (n+1)/2;\n    int cy = (m+1)/2;\n    int layers = max(n, m)/2;\n    print(cx, cy);\n    for (int i = 1; i <= layers; i++) {\n        for (int j = 0; j < 2*i-1; j++) {\n            int sgn = (j & 1) ? 1 : -1;\n            print(cx+sgn*(j+1)/2, cy+i);\n            print(cx+sgn*(j+1)/2, cy-i);\n        }\n        for (int j = 0; j < 2*i-1; j++) {\n            int sgn = (j & 1) ? 1 : -1;\n            print(cx+i, cy+sgn*(j+1)/2);\n            print(cx-i, cy+sgn*(j+1)/2);\n        }\n        print(cx-i, cy-i);\n        print(cx-i, cy+i);\n        print(cx+i, cy-i);\n        print(cx+i, cy+i);\n    }\n}\n \nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int tc; cin >> tc;\n    while (tc--) solve();\n}",
    "tags": [
      "constructive algorithms",
      "geometry",
      "greedy",
      "math"
    ],
    "rating": 2400
  },
  {
    "contest_id": "2118",
    "index": "F",
    "title": "Shifts and Swaps",
    "statement": "You are given arrays $a$ and $b$ of length $n$ and an integer $m$.\n\nThe arrays only contain integers from $1$ to $m$, and both arrays contain all integers from $1$ to $m$.\n\nYou may repeatedly perform either of the following operations on $a$:\n\n- cyclic shift$^{\\text{∗}}$ the array to the left\n- swap two neighboring elements if their difference is at least $2$.\n\nIs it possible to transform the first array into the second?\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A left cyclic shift of a zero-indexed array $p$ of length $n$ is an array $q$ such that $q_i = p_{(i + 1) \\bmod n}$ for all $0 \\le i < n$.\n\\end{footnotesize}",
    "tutorial": "The order of two elements only matters if the absolute value of their difference is at most 1. Try to store the positions of elements with value $v$ relative to elements with value $v+1$. (The next hint will be about what to do with these.) We want to somehow hash the relative positions. (The next hint will be about a thing you might not have known you can hash.) It is possible to hash rooted trees, see Vladosiya's blog post. Note: the structure you hopefully came up with using hint 2 will certainly not be a single rooted tree, use this algorithm more as a guide. (The next hint will be about how you can check if two strings are rotations of each other.) You can check if two strings are rotations of each other either by using KMP or hashing. We'll consider the arrays cyclic: $a_1$ and $a_n$ are also adjacent. For each array, let's build rooted trees where the children of each vertex are ordered. Each vertex corresponds to an value in an array. For each index $i$, let its children be the occurrences of the value $a_i - 1$ in order between the $i$-th element and the next occurrence of the value $a_i$. The roots of the trees will be nodes with value $m$ in an array. We hash each tree, then compare if the sequences of hashes are rotations of each other (for example using KMP). For hashing a tree, see Vladosiya's blog post. This solution has a time complexity $O(N\\log{N})$ if you use a map for deterministic hashing.",
    "code": "#include <bits/stdc++.h>\n \nusing namespace std;\nusing ll = long long;\n \n \ninline int sign_of_non_zero(const int x) {\n    return x > 0 ? 1 : -1;\n}\n \nstruct IllegalTransformationException : public std::runtime_error {\n    using std::runtime_error::runtime_error;\n};\n \ntemplate <\n    std::uint64_t ELEMENT_MULTIPLIER,\n    std::uint64_t HASH_MULTIPLIER,\n    std::uint64_t OFFSET\n>\ninline std::uint64_t circular_hash(const std::vector<std::uint64_t>& arr) {\n    std::uint64_t current_hash = 0;\n \n    for (const std::uint64_t& elem : arr) {\n        current_hash *= ELEMENT_MULTIPLIER;\n        current_hash += elem;\n    }\n \n    std::uint64_t first_multiplier = 1;\n    for (int i = 0; i + 1 < arr.size(); i++)\n        first_multiplier *= ELEMENT_MULTIPLIER;\n \n    std::vector<std::uint64_t> hashes;\n \n    for (const std::uint64_t& elem : arr) {\n        hashes.push_back(current_hash);\n \n        current_hash -= first_multiplier * elem;\n        current_hash *= ELEMENT_MULTIPLIER;\n        current_hash += elem;\n    }\n \n    sort(hashes.begin(), hashes.end());\n \n    std::uint64_t result = 0;\n    std::uint64_t hash_multipler = 1;\n \n    for (const std::uint64_t& hash : hashes) {\n        result += hash * hash + hash * hash_multipler + OFFSET;\n \n        hash_multipler *= HASH_MULTIPLIER;\n    }\n \n    return result;\n}\n \n \n// VEC must support indexing and have `.size()`.\ntemplate <typename VEC = std::vector<int>>\nclass braid_graph {\n    VEC braid;\n    int strand_count;\n    std::vector<std::vector<int>> children;\n \n    template <\n        std::uint64_t CHILD_MULTIPLIER,\n        std::uint64_t OFFSET,\n        std::uint64_t NEGATIVE_MULTIPLIER,\n        std::uint64_t NEGATIVE_OFFSET\n    >\n    std::uint64_t hash_of_vertex(std::vector<std::uint64_t>& hashes, const int& v) const {\n        if (hashes[v] == 0) {\n            std::uint64_t result = 0;\n            std::uint64_t multiplier = 1;\n \n            for (const int& child : children[v]) {\n                const std::uint64_t base_hash = hash_of_vertex<CHILD_MULTIPLIER, OFFSET, NEGATIVE_MULTIPLIER, NEGATIVE_OFFSET>(hashes, child);\n                result += base_hash * base_hash + base_hash * multiplier + OFFSET;\n \n                multiplier *= CHILD_MULTIPLIER;\n            }\n \n            if (braid[v] < 0)\n                result = result * result + result * NEGATIVE_MULTIPLIER + NEGATIVE_OFFSET;\n \n            hashes[v] = result;\n        }\n \n        return hashes[v];\n    }\n \n    template <\n        std::uint64_t CHILD_MULTIPLIER,\n        std::uint64_t OFFSET,\n        std::uint64_t NEGATIVE_MULTIPLIER,\n        std::uint64_t NEGATIVE_OFFSET,\n        std::uint64_t CIRCULAR_HASH_ELEMENT_MULTIPLIER,\n        std::uint64_t CIRCULAR_HASH_HASH_MULTIPLIER,\n        std::uint64_t CIRCULAR_HASH_OFFSET\n    >\n    std::uint64_t hash_more_than_two_strands() const {\n        // Implementation based on: https://codeforces.com/blog/entry/113465\n \n        // Since C++20 is not supported, instead of `optional<int>`, `0` will be used as semantic value for non-existance.\n        std::vector<std::uint64_t> hashes(braid.size());\n \n        std::vector<std::uint64_t> top_hashes;\n        // Not tested if faster.\n        top_hashes.reserve(braid.size());\n \n        for (int i = 0; i < braid.size(); i++) {\n            if (abs(braid[i]) != strand_count - 1)\n                continue;\n \n            top_hashes.push_back(hash_of_vertex<CHILD_MULTIPLIER, OFFSET, NEGATIVE_MULTIPLIER, NEGATIVE_OFFSET>(hashes, i));\n        }\n \n        return circular_hash<CIRCULAR_HASH_ELEMENT_MULTIPLIER, CIRCULAR_HASH_HASH_MULTIPLIER, CIRCULAR_HASH_OFFSET>(top_hashes);\n    }\n \n    template <\n        std::uint64_t MULTIPLIER,\n        std::uint64_t POSITIVE,\n        std::uint64_t NEGATIVE,\n        std::uint64_t CIRCULAR_HASH_ELEMENT_MULTIPLIER,\n        std::uint64_t CIRCULAR_HASH_HASH_MULTIPLIER,\n        std::uint64_t CIRCULAR_HASH_OFFSET\n    >\n    std::uint64_t hash_two_strands() const {\n        std::vector<std::uint64_t> hashes(braid.size());\n \n        for (int i = 0; i < braid.size(); i++)\n            hashes[i] = braid[i] == 1 ? POSITIVE : NEGATIVE;\n \n        const std::uint64_t result = circular_hash<CIRCULAR_HASH_ELEMENT_MULTIPLIER, CIRCULAR_HASH_HASH_MULTIPLIER, CIRCULAR_HASH_OFFSET>(hashes);\n \n        return result;\n    }\n \npublic:\n    braid_graph(\n        const VEC braid,\n        const int strand_count\n    ) :\n        braid(braid),\n        strand_count(strand_count)\n    {\n        if (strand_count == 2)\n            return;\n \n        children.resize(braid.size());\n \n        // Since C++20 is not supported, instead of `optional<int>`, `-1` will be used as semantic value for non-existance.\n        std::vector<std::vector<int>> last_occurence(strand_count);\n \n        for (int i = 0; i < braid.size(); i++) {\n            const int cur = abs(braid[i]);\n \n            // Because sigmas start from 1, this is fine.\n            last_occurence[cur - 1].clear();\n            last_occurence[cur].push_back(i);\n        }\n \n        for (int i = 0; i < braid.size(); i++) {\n            const int cur = abs(braid[i]);\n \n            // Because sigmas start from 1, this is fine.\n            children[i] = last_occurence[cur - 1];\n            last_occurence[cur - 1].clear();\n \n            last_occurence[cur].push_back(i);\n        }\n    }\n \n    // It is recommended that CHILD_MULTIPLIER be a prime and all template parameters are sufficiently different.\n    template <\n        std::uint64_t MULTIPLIER = 1'000'000'007,\n        std::uint64_t OFFSET = 42,\n        std::uint64_t NEGATIVE_MULTIPLIER = 3'141'592,\n        std::uint64_t NEGATIVE_OFFSET = 2'622'057,\n        // Only used for `strand_count == 2`.\n        std::uint64_t POSITIVE = 2'718'281,\n        std::uint64_t EMPTY_HASH = 1'618'033,\n        std::uint64_t CIRCULAR_HASH_ELEMENT_MULTIPLIER = MULTIPLIER,\n        std::uint64_t CIRCULAR_HASH_HASH_MULTIPLIER = 693'147,\n        std::uint64_t CIRCULAR_HASH_OFFSET = 1'414'213\n    >\n    std::uint64_t hash() const {\n        if (strand_count == 1)\n            return EMPTY_HASH;\n        if (strand_count == 2)\n            return hash_two_strands<\n                MULTIPLIER,\n                POSITIVE,\n                NEGATIVE_OFFSET,\n                CIRCULAR_HASH_ELEMENT_MULTIPLIER,\n                CIRCULAR_HASH_HASH_MULTIPLIER,\n                CIRCULAR_HASH_OFFSET\n            >();\n        else\n            return hash_more_than_two_strands<\n                MULTIPLIER,\n                OFFSET,\n                NEGATIVE_MULTIPLIER,\n                NEGATIVE_OFFSET,\n                CIRCULAR_HASH_ELEMENT_MULTIPLIER,\n                CIRCULAR_HASH_HASH_MULTIPLIER,\n                CIRCULAR_HASH_OFFSET\n            >();\n    }\n};\n \n \nstd::uint64_t sim_single_hash(const vector<ll> input, const int strand_count) {\n    const braid_graph<vector<ll>> g(input, strand_count+1);\n    return g.hash();\n}\n \nvoid solve() {\n    int n, m; cin >> n >> m;\n    vector<ll> a(n), b(n);\n    for (ll &x : a) cin >> x;\n    for (ll &x : b) cin >> x;\n    cout << (sim_single_hash(a, m) == sim_single_hash(b, m) ? \"YES\\n\" : \"NO\\n\");\n}\n \nint main() {\n    ios::sync_with_stdio(0); cin.tie(0);\n    int t = 1; \n    cin >> t;\n    while (t--) solve();\n    return 0;\n}",
    "tags": [
      "data structures",
      "graphs",
      "hashing",
      "trees"
    ],
    "rating": 3100
  },
  {
    "contest_id": "2120",
    "index": "A",
    "title": "Square of Rectangles",
    "statement": "Aryan is an ardent lover of squares but a hater of rectangles (Yes, he knows all squares are rectangles). But Harshith likes to mess with Aryan. Harshith gives Aryan three rectangles of sizes $l_1\\times b_1$, $l_2\\times b_2$, and $l_3\\times b_3$ such that $l_3\\leq l_2\\leq l_1$ and $b_3\\leq b_2\\leq b_1$. Aryan, in order to defeat Harshith, decides to arrange these three rectangles to form a square such that no two rectangles overlap and the rectangles are aligned along edges. Rotating rectangles is \\textbf{not} allowed. Help Aryan determine if he can defeat Harshith.",
    "tutorial": "There are only two possible ways to arrange rectangles into a square if possible. The only cases possible to arrange rectangles into a square are: All three rectangles are put side by side, i.e. $l_1=l_2=l_3=b_1+b_2+b_3$ or $b_1=b_2=b_3=l_1+l_2+l_3$. Rectangles $2$ and $3$ are side by side with rectangle $1$ above it, i.e. $l_1+l_2=l_1+l_3=b_1=b_2+b_3$ or $b_1+b_2=b_1+b_3=l_1=l_2+l_3$. Check both these cases, and if either is true, output YES, otherwise NO. Complexity is $O(1)$ per test.",
    "code": "#include <iostream>\nusing namespace std;\n \nint main(){\n    int t;\n    cin >> t;\n    \n    int l1, b1, l2, b2, l3, b3;\n    \n    auto check = [&] () {\n        if (l1 == l2 && l2 == l3) return (l1 == b1 + b2 + b3 || (b1 == b2 + b3 && 2*l1 == b1));\n        if (l2 == l3) return (b2 + b3 == b1 && b1 == l2 + l1);\n        return false;\n    };\n    \n    while(t--) {\n        cin >> l1 >> b1 >> l2 >> b2 >> l3 >> b3;\n        if(check()) cout << \"YES\\n\";\n        else {\n            swap(l1, b1); swap(l2, b2); swap(l3, b3);\n            if(check()) cout << \"YES\\n\";\n            else cout << \"NO\\n\";\n        }\n    }\n    \n    return 0;\n}\n",
    "tags": [
      "geometry",
      "math"
    ]
  },
  {
    "contest_id": "2120",
    "index": "B",
    "title": "Square Pool",
    "statement": "Aryan and Harshith are playing pool in universe AX120 on a fixed square pool table of side $s$ with \\textbf{pockets} at its $4$ corners. The corners are situated at $(0,0)$, $(0,s)$, $(s,0)$, and $(s,s)$. In this game variation, $n$ identical balls are placed on the table with integral coordinates such that no ball lies on the edge or corner of the table. Then, they are all simultaneously shot at $10^{100}$ units/sec speed (only at $45$ degrees with the axes).\n\nIn universe AX120, balls and pockets are almost point-sized, and the collisions are elastic, i.e., the ball, on hitting any surface, bounces off at the same angle and with the same speed.\n\nHarshith shot the balls, and he provided Aryan with the balls' positions and the angles at which he shot them. Help Aryan determine the number of balls potted into the \\textbf{pockets} by Harshith.\n\nIt is guaranteed that multiple collisions do not occur at the same moment and position.",
    "tutorial": "What happens to the balls that collide with an edge, eventually? How does a collision between two balls affect the outcome? Observations Any ball on the diagonals of the square that is shot towards a pocket will be potted on a free table. Any ball that collides with an edge will be in a $4$-periodic path colliding with the $4$ edges forever on a free table. The collisions are elastic, so if two balls collide, they exchange their directions. $\\bigstar$ Neither collisions affect the effective number of balls traversing towards a pocket. Therefore, the answer is the number of balls initially on the diagonals of the square and shot towards the pockets. Hope you liked the figures; a lot of effort went into them.",
    "code": "#include <iostream>\nusing namespace std;\n\nint main() {\n    int t;\n    cin >> t;\n    \n    int n, s, ans = 0, dxi, dyi, xi, yi;\n    while(t--) {\n        cin >> n >> s;\n        \n        for (int i = 0; i < n; i++) {\n            cin >> dxi >> dyi >> xi >> yi;\n            if (dxi == dyi) ans += (xi == yi);\n            else ans += (xi + yi == s);\n        }\n        \n        cout << ans << '\\n';\n        ans = 0;\n    }\n    return 0;\n}",
    "tags": [
      "geometry"
    ]
  },
  {
    "contest_id": "2120",
    "index": "C",
    "title": "Divine Tree",
    "statement": "Harshith attained enlightenment in Competitive Programming by training under a Divine Tree. A divine tree is a rooted tree$^{\\text{∗}}$ with $n$ nodes, labelled from $1$ to $n$. The divineness of a node $v$, denoted $d(v)$, is defined as the smallest node label on the unique simple path from the root to node $v$.\n\nAryan, being a hungry Competitive Programmer, asked Harshith to pass on the knowledge. Harshith agreed on the condition that Aryan would be given two positive integers $n$ and $m$, and he had to construct a divine tree with $n$ nodes such that the total divineness of the tree is $m$, i.e., $\\displaystyle\\sum\\limits_{i=1}^n d(i)=m$. If no such tree exists, Aryan must report that it is impossible.\n\nDesperate for knowledge, Aryan turned to you for help in completing this task. As a good friend of his, help him solve the task.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A tree is a connected graph without cycles. A rooted tree is a tree where one vertex is special and called the root.\n\\end{footnotesize}",
    "tutorial": "What are bounds on $m$ for a given $n$ to have a divine tree? And how does the tree look for the lower bound and the upper bound? The $\\text{min}$ and $\\text{max}$ value of $m$ for a divine tree to exist are $n$ and $\\frac{n \\cdot (n + 1)}{2}$ respectively. $\\text{POC:}$ Any $m \\in [\\text{min}, \\text{max}]$ can be achieved similar to exhaustive subset sum with redraws enabled. Let $p = m - n$, $\\text{cur} = 0$, $\\text{ans}$ = [ ]. Now, we need to select a multiset of $n$ non-negative integers that sum to $p$. $\\text{Greedy:}$ Loop $j$ from $n - 1$ to $0$, if $\\text{cur} + i \\le p$: $\\text{cur}$ += $i + 1,$ $\\text{ans.push_back}(i + 1)$ If $\\text{ans.back}()$ is not $1$ add a $1$, why? $\\text{Construction:}$ The tree can always be simple path, why? Tree is rooted at $\\text{ans}[0]$. Let's store $\\text{vis}[0:n - 1] = \\text{false}$ to keep track if a node is visited or not. Loop $i$ from $1$ to $\\text{size(ans)}$ and add edge between $\\text{ans}[i-1]$ to $\\text{ans}[i]$ and mark all of them $\\text{true}$ in $\\text{vis}$. Take all un-visited in the array $\\text{unvis}$ and add an edge from $1$ to $\\text{unvis}[0]$. Loop $i$ from $1$ to $\\text{size(unvis)}$ and add an edge from $\\text{unvis}[i-1]$ to $\\text{unvis}[i]$. The divine tree which is a simple path looks like $\\text{ans}[0] \\leftrightarrow$ . . . $\\leftrightarrow 1 \\leftrightarrow \\text{unvis}[0] \\leftrightarrow$ . . . $\\leftrightarrow \\text{unvis.back}()$.",
    "code": "#include <iostream>\n#include <cstdint>\n#include <cassert>\n#include <vector>\n\nusing namespace std;\n\n#define i64 int64_t\n\nvoid solve() {\n    i64 n, sum;\n    cin >> n >> sum;\n\n    if(sum < n || sum > n * (n + 1) / 2) {\n        cout << \"-1\\n\";\n        return;\n    }\n\n    i64 k = sum - n;\n\n    vector<i64> ans;\n    i64 curr = 0, nsum = 0;\n\n    for(i64 i = n - 1; i >= 0; --i) {\n        if(curr == k) break;\n        if(curr + i <= k) {\n            curr += i;\n            ans.push_back(i + 1);\n            nsum += i + 1;\n        }\n    }\n\n    i64 ct = ans.size();\n    for(i64 i = 0; i < n - ct; ++i) ans.push_back(1);\n\n    nsum += (n - ct);\n    \n    assert(nsum == sum);\n\n    if(n == sum) {\n        cout << \"1\\n\";\n        for(i64 i = 1; i < n; i++) cout << i << ' ' << i + 1 << '\\n';\n        return;\n    }\n\n    vector<bool> vis(n + 1, 1);\n    cout << ans[0] << '\\n';\n    vis[ans[0]] = 0;\n\n    for(i64 i = 1; i <= n; i++) {\n        cout << ans[i - 1] << ' ' << ans[i] << '\\n';\n        vis[ans[i - 1]] = 0, vis[ans[i]] = 0;\n\n        if(ans[i] == 1) {\n            i64 prev = 1;\n            for(i64 j = 2; j <= n; ++j) {\n                if(vis[j]) {\n                    cout << prev << ' ' << j << '\\n';\n                    prev = j;\n                }\n            }\n            return;\n        }\n    }\n}\n\nint main() {\n    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);\n    \n    i64 t;\n    cin >> t;\n\n    while(t--) solve();\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "math",
      "sortings",
      "trees"
    ]
  },
  {
    "contest_id": "2120",
    "index": "D",
    "title": "Matrix game",
    "statement": "Aryan and Harshith play a game. They both start with three integers $a$, $b$, and $k$. Aryan then gives Harshith two integers $n$ and $m$. Harshith then gives Aryan a matrix $X$ with $n$ rows and $m$ columns, such that each of the elements of $X$ is between $1$ and $k$(inclusive). After that, Aryan wins if he can find a submatrix$^{\\text{∗}}$ $Y$ of $X$ with $a$ rows and $b$ columns such that all elements of $Y$ are equal.\n\nFor example, when $a=2, b=2, k=6, n=3$ and $m=3$, if Harshith gives Aryan the matrix below, it is a win for Aryan as it has a submatrix of size $2\\times 2$ with all elements equal to $1$ as shown below.\n\n\\begin{center}\nExample of a matrix where Aryan wins\n\\end{center}\n\nAryan gives you the values of $a$, $b$, and $k$. He asks you to find the lexicographically minimum tuple $(n,m)$ that he should give to Harshith such that Aryan always wins. Help Aryan win the game. Assume that Harshith plays optimally. The values of $n$ and $m$ can be large, so output them modulo $10^9+7$. A tuple $(n_1, m_1)$ is said to be lexicographically smaller than $(n_2, m_2)$ if either $n_1<n_2$ or $n_1=n_2$ and $m_1<m_2$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A submatrix of a matrix is obtained by removing some rows and/or columns from the original matrix.\n\\end{footnotesize}",
    "tutorial": "Use pigeonhole principle to get minimum $n$ and then minimum $m$. If each row is of size $k(a-1)+1$, by pigeonhole principle, it will have at least $a$ elements with the same value. Let those elements appear positions $p_1<p_2<...<p_a$($p_i$ is the column number where the element occurs) and let the value be $v$. Consider the tuple $(v, p_1,p_2,...,p_a)$. If the same tuple appears $b$ times, we are done as we obtain an $a*b$ submatrix with all elements of same value. The number of possible values of the tuple is $k\\times^nC_a$. So, there should be atleast $(b-1)k\\times^nC_a+1$ rows for there to be $b$ repetitions by pigeonhole principle.",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\nconst long long mod=1000000007;\nlong long inv[100001];\nint main(){\n\tios::sync_with_stdio(false),cin.tie(0);\n\tint T;\n\tlong long i,a,b,k,d,ans;\n\tinv[1]=1;\n\tfor(i=2;i<=100000;i++)inv[i]=(mod-mod/i)*inv[mod%i]%mod;\n\tfor(cin>>T;T>0;T--)\n\t{\n\t\tcin>>a>>b>>k;\n\t\td=k*a-k+1;\n\t\tans=k;\n\t\tfor(i=1;i<=a;i++)ans=ans*((d-i+1)%mod)%mod*inv[i]%mod;\n\t\tcout<<d%mod<<' '<<(ans*b-ans+1+mod)%mod<<'\\n';\n\t}\n\treturn 0;\n}",
    "tags": [
      "combinatorics",
      "math"
    ]
  },
  {
    "contest_id": "2120",
    "index": "E",
    "title": "Lanes of Cars",
    "statement": "Harshith is the president of TollClub. He tasks his subordinate Aryan to oversee a toll plaza with $n$ lanes. Initially, the $i$-th lane has $a_i$ cars waiting in a queue. Exactly one car from the front of each lane passes through the toll every second.\n\nThe angriness of a car is defined as the number of seconds it had to wait before passing through the toll. Consider it takes 1 sec for each car to pass the toll, i.e., the first car in a lane has angriness $1$, the second car has angriness $2$, and so on.\n\nTo reduce congestion and frustration, cars are allowed to switch lanes. A car can instantly move to the back of any other lane at any time. However, changing lanes increases its angriness by an additional $k$ units due to the confusion caused by the lane change.\n\nHarshith, being the awesome person he is, wants to help the drivers by minimising the total angriness of all cars. He asks Aryan to do so or get fired. Aryan is allowed to change lanes of any car anytime (possibly zero), but his goal is to find the minimum possible total angriness if the lane changes are done optimally. Help Aryan retain his job by determining the minimum angriness he can achieve.",
    "tutorial": "Use binary search to find minimum number of cars in a lane after optimal number lane shifts. Adjust cars afterwards such that minimum number of cars remains same as found in binary search, but angriness is minimized. Observe the following(Let $1$ car shift lanes at a time): It is always optimal to shift the car at the back of a lane before shifting cars in front of it. The optimal condition is that in every iteration, the car shifts from the back of the lane with max cars to the back of the lane with minimum cars. If $(\\text{cars in the max lane} - \\text{cars in min lane}) <= K$, then it is not optimal to shift any cars as it will only increase the angriness. It doesn't matter when a car switches lane; it can switch at any time and the optimal answer remains the same. For a value $v$, let $def(v)$ be number of cars required such that each lane has atleast $v$ cars, i.e. $def(v)=\\sum_{i=1}^N max(0, v-a[i]))$ $defs(v)$ be number of lanes with less than $v$ cars initially, i.e. $defs(v)=\\sum_{i=1}^N (v-a[i]>0)$. $exc(v)$ be number of cars to remove such that each lanes has atmost $v$ cars, i.e. $exc(v)=\\sum_{i=1}^N max(0, a[i]-v)$ $excs(v)$ be number of lanes with more than $v$ cars initially, i.e. $excs=\\sum_{i=1}^N (a[i]-v>0)$ Using binary search, find the maximum value of $v$ for which $exc(v+k)>def(v)$. This $v$ denotes the minimum value that the array will have after cars have switched lanes optimally, and the maximum value of the array will be $v+k$ if $exc(v+k)=def(v)$ and $v+k+1$ if $exc(v+k)>def(v)$. Final sorted array $A'$ after optimal lane switches will have values between $v+1$ and $v+k-1$ remain the same as array $A$. Of the first $defs(v)$ elements, last $max(0, exc(v)-def(v)-excs(v))$ values will be $v+1$ and remaining values will be $v$. Of the last $excs(v)$ elements, last $min(excs(v), exc(v)-def(v))$ values will be $v+k+1$ and remaining elements will be $v+k$. Find minimum angriness after optimal lane switches using array $A'$ and calculating number of cars that have switched lanes. Time complexity is $O(n \\log \\max(A_i))$ Special thanks to picramide for the initial problem idea, which I misheard and it turned into this problem.",
    "code": "//��\n#include<bits/stdc++.h>\nusing namespace std;\ntypedef long long LL;\ntypedef double DB;\nconst int N = 1111111;\nconst LL inf = 1e18;\nint n,k,a[N];\nLL s[N];\nint main(){\n\tint T,i,l,r,h;\n\tLL x,y,z,o,p,t;\n\tscanf(\"%d\",&T);\n\twhile(T--){\n\t\tscanf(\"%d%d\",&n,&k);\n\t\tfor(i=1;i<=n;i++)\n\t\t\tscanf(\"%d\",a+i);\n\t\tsort(a+1,a+n+1);\n\t\tfor(i=1;i<=n;i++)\n\t\t\ts[i]=s[i-1]+a[i];\n\t\tz=inf,o=-1;\n\t\tl=0,r=N;\n\t\twhile(l<=r){\n\t\t\th=l+r>>1;\n\t\t\ti=lower_bound(a+1,a+n+1,h)-a-1;\n\t\t\tx=(LL)i*h-s[i];\n\t\t\ti=lower_bound(a+1,a+n+1,h+k)-a-1;\n\t\t\ty=(s[n]-s[i])-(LL)(n-i)*(h+k);\n\t\t\tif(z>max(x,y))\n\t\t\t\tz=max(x,y),o=h;\n\t\t\tif(x<y)\n\t\t\t\tl=h+1;\n\t\t\telse\n\t\t\t\tr=h-1;\n\t\t}\n\t\t//cout<<z<<' '<<o<<endl;\n\t\tp=z*k;\n\t\tt=0;\n\t\tfor(i=1;i<=n;i++){\n\t\t\tx=min(max((LL)a[i],o),o+k);\n\t\t\tp+=(LL)x*(x+1)/2;\n\t\t\tt+=x-a[i];\n\t\t}\n\t\tif(t>0)\n\t\t\tp-=(o+k)*t;\n\t\tif(t<0)\n\t\t\tp+=(o+1)*-t;\n\t\tprintf(\"%lld\\n\",p);\n\t}\n\treturn 0;\n}",
    "tags": [
      "binary search",
      "dp",
      "ternary search"
    ]
  },
  {
    "contest_id": "2120",
    "index": "F",
    "title": "Superb Graphs",
    "statement": "As we all know, Aryan is a funny guy. He decides to create fun graphs. For a graph $G$, he defines fun graph $G'$ of $G$ as follows:\n\n- Every vertex $v'$ of $G'$ maps to a non-empty independent set$^{\\text{∗}}$ or clique$^{\\text{†}}$ in $G$.\n- The sets of vertices of $G$ that the vertices of $G'$ map to are pairwise disjoint and combined cover all the vertices of $G$, i.e., the sets of vertices of $G$ mapped by vertices of $G'$ form a partition of the vertex set of $G$.\n- If an edge connects two vertices $v_1'$ and $v_2'$ in $G'$, then there is an edge between every vertex of $G$ in the set mapped to $v_1'$ and every vertex of $G$ in the set mapped to $v_2'$.\n- If an edge does not connect two vertices $v_1'$ and $v_2'$ in $G'$, then there is not an edge between any vertex of $G$ in the set mapped to $v_1'$ and any vertex of $G$ in the set mapped to $v_2'$.\n\nAs we all know again, Harshith is a superb guy. He decides to use fun graphs to create his own superb graphs. For a graph $G$, a fun graph $G' '$ is called a superb graph of $G$ if $G' '$ has the minimum number of vertices among all possible fun graphs of $G$.\n\nAryan gives Harshith $k$ simple undirected graphs$^{\\text{‡}}$ $G_1, G_2,\\ldots,G_k$, all on the same vertex set $V$. Harshith then wonders if there exist $k$ other graphs $H_1, H_2,\\ldots,H_k$, all on some other vertex set $V'$ such that:\n\n- $G_i$ is a superb graph of $H_i$ for all $i\\in \\{1,2,\\ldots,k\\}$.\n- If a vertex $v\\in V$ maps to an independent set of size greater than $1$ in one $G_i, H_i$ ($1\\leq i\\leq k$) pair, then there exists no pair $G_j, H_j$ ($1\\leq j\\leq k, j\\neq i$) where $v$ maps to a clique of size greater than $1$.\n\nHelp Harshith solve his wonder.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$For a graph $G$, a subset $S$ of vertices is called an independent set if no two vertices of $S$ are connected with an edge.\n\n$^{\\text{†}}$For a graph $G$, a subset $S$ of vertices is called a clique if every vertex of $S$ is connected to every other vertex of $S$ with an edge.\n\n$^{\\text{‡}}$A graph is a simple undirected graph if its edges are undirected and there are no self-loops or multiple edges between the same pair of vertices.\n\\end{footnotesize}",
    "tutorial": "If two vertices have same open neighborhood in some graph $G_i$, atleast one of them has to correpond to a clique in every $G_i, H_i$ pair. If two vertices have same closed neighborhood in some graph $G_i$, atleast one of them has to correpond to an independent set in every $G_i, H_i$ pair. In a graph $G$, two vertices $v_1$ and $v_2$ are said to be of type1 if they are not adjacent and have the same open neighborhood, i.e., $v_1v_2 \\not\\in E(G)$ and $N_G(v_1)=N_G(v_2)$. In a graph $G$, two vertices $v_1$ and $v_2$ are said to be of type2 if they are adjacent and have the same closed neighborhood, i.e., $v_1v_2 \\in E(G)$ and $N_G[v_1]=N_G[v_2]$. An equivalence class is defined as the set of vertices of the same type. Here, note that if two vertices of type1 are present, then both vertices can't correspond to independent sets as we can merge them to a larger independent set and denote it by a single vertex. Similarly, if two vertices of type2 are present, then both can't correspond to cliques as we can merge them to a larger clique and denote it by a single vertex. Proof: Graph is superb $\\rightarrow$ Every type1 pair has atleast one vertex correspond to a clique and every type2 pair has atleast one vertex correspond to an independent set(We'll prove contrapositive). Assume there exists a type1 pair $v_1v_2$ that has both vertices corresponding to an independent set. Let their vertex set be $V_1$ and $V_2$. Consider the set $V=V_1 \\cup V_2$ and a new vertex $v$ that has the same neighborhood as $v_1(or v_2)$. Each vertex in the set $V$ satisfies all of the $4$ conditions given, as if vertices in set $V_1$ were connected to a vertex, so is every vertex in the set $V_2$ and vice versa. Hence, we can merge both $v_1$ and $v_2$ into a single vertex $v$ and still satisfy the conditions, making the graph not superb as it doesn't have minimum order. Same reasoning goes for a type2 pair. Every type1 pair has atleast one vertex correspond to a clique and every type2 pair has atleast one vertex correspond to an independent set $\\rightarrow$ Graph is superb. Consider a graph $G({v_i}, E)$. Let its fun graph be $G'({V_i}, E')$. Observe that if two vertices $V_i$ and $V_j$ have different neighborhoods (excluding each other), then we can't have any fun graph $G2'$ in which a vertex $K$ contains some non-zero vertices of $V_i$ and some non-zero vertices of $V_j$. This is because if that happens, then it means all vertices in set $K$ have the same neighborhood, excluding each other, meaning that $V_i$ and $V_j$ have the same neighborhood, excluding each other, a contradiction. For the same reasons, if two vertices have the same neighborhood, excluding each other, they have to be either a type1 or type2 pair for there to exist another fun graph $G2'$ in which a vertex $K$ contains some non-zero vertices from both sets. Suppose every type1 pair has at least one vertex corresponding to a clique, and every type2 pair has at least one vertex corresponding to an independent set. In that case, there can't be any fun graph $G2'$ in which a vertex K contains some non-zero vertices from two sets of $G'$ as set $K$ has either all vertices in it connected or none of them connected. So, in $G2'$, each vertex $K$ corresponds to a subset of vertices of $G'$, implying that it has at least as many vertices as $G'$. So, $G'$ is of minimum cardinality and so is superb. \\end{enumerate} So, for this problem, a vertex is assigned $0$ if it is assigned an independent set and a vertex is assigned $1$ if it is assigned a clique. Consider two vertices $a$ and $b$. If both are type1, then we can denote it by $a \\lor b$(both can't be I.S.) and if both are type2, we can denote it by $\\lnot a \\lor \\lnot b$(Both can't be cliques). We can make a $2$-sat equation using this. If the $2$-sat has a solution, then the graph is a superb graph. Else, it is not. Expected complexity is $O(n^3)$ When is a graph a superb graph of itself?",
    "code": "#include <bits/stdc++.h>\nusing namespace std;\n#define endl '\\n'\n#define int long long\n\nbool twoSAT(vector<vector<int>> &adj, vector<vector<int>> &adj_rev, vector<bool> &assignment) {\n    int n = adj.size();\n    vector<int> order;\n    vector<bool> used(n, false);\n\n    function<void(int)> dfs1 = [&](int v) {\n        used[v] = true;\n\n        for(auto u : adj[v]) \n            if(!used[u])\n                dfs1(u);\n\n        order.push_back(v);\n    };\n\n    vector<int> comp(n, -1);\n\n    function<void(int, int)> dfs2 = [&](int v, int color) {\n        comp[v] = color;\n\n        for(auto u : adj_rev[v]) \n            if(comp[u] == -1)\n                dfs2(u, color);\n    };\n\n    for(int i = 0; i < n; ++i) \n        if(!used[i])\n            dfs1(i);\n\n    used.assign(n, false);\n\n    for(int i = 0, j = 0; i < n; ++i) {\n        int v = order[n - i - 1];\n        if(comp[v] == -1)\n            dfs2(v, j++);\n    }\n\n    assignment.assign(n / 2, false);\n    for(int i = 0; i < n; i += 2) {\n        if(comp[i] == comp[i + 1]) \n            return false; \n        assignment[i / 2] = comp[i] > comp[i + 1];\n    }\n    return true;\n}\n\nvoid solve() {\n    int n, k; cin >> n >> k;\n\n    vector<vector<int>> adj(2*n), adj_rev(2*n);\n\n    auto add_or = [&](int a, bool nega, int b, bool negb) {\n        a = (2*a) + nega;\n        b = (2*b) + negb;\n        adj[a^1].push_back(b);\n        adj[b^1].push_back(a);\n        adj_rev[b].push_back(a^1);\n        adj_rev[a].push_back(b^1);\n    };\n\n    function<void(int, vector<vector<int>>&)> process = [&n, &add_or](int m, vector<vector<int>> &adj) {\n        map<vector<int>, vector<int>> mp;\n\n        for(int i = 0; i < n; ++i) {\n            auto temp = adj[i];\n            temp.push_back(i);\n            sort(temp.begin(), temp.end());\n\n            mp[temp].push_back(i);\n        }\n\n        for(auto [x, y] : mp) {\n            for(int i = 0; i < y.size(); ++i) {\n                for(int j = i + 1; j < y.size(); ++j) {\n                    add_or(y[i], 1, y[j], 1);\n                }\n            }\n        }\n\n        mp.clear();\n\n        for(int i = 0; i < n; ++i) {\n            sort(adj[i].begin(), adj[i].end());\n            mp[adj[i]].push_back(i);\n        }\n\n        for(auto [x, y] : mp) {\n            for(int i = 0; i < y.size(); ++i) {\n                for(int j = i + 1; j < y.size(); ++j) {\n                    add_or(y[i], 0, y[j], 0);\n                }\n            }\n        }\n    };\n\n    for(int i = 0; i < k; ++i) {\n        int m; cin >> m;\n        vector<vector<int>> adj(n);\n\n        for(int j = 0; j < m; ++j) {\n            int x, y; cin >> x >> y;\n            x--; y--;\n            adj[x].push_back(y);\n            adj[y].push_back(x);\n        }\n\n        process(m, adj);\n    }\n\n    vector<bool> assignment(n, false);\n    cout << ((twoSAT(adj, adj_rev, assignment)) ? \"Yes\" : \"No\");\n}\n\nint32_t main() {\n    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n    int _TC = 0; cin >> _TC;\n    for(int _ct = 1; _ct <= _TC; ++_ct) {\n        solve(); cout << endl;\n    }\n}",
    "tags": [
      "2-sat",
      "graphs"
    ]
  },
  {
    "contest_id": "2120",
    "index": "G",
    "title": "Eulerian Line Graph",
    "statement": "Aryan loves graph theory more than anything. Well, no, he likes to flex his research paper on line graphs to everyone more. To start a conversation with you, he decides to give you a problem on line graphs. In the mathematical discipline of graph theory, the line graph of a simple undirected graph $G$ is another simple undirected graph $L(G)$ that represents the adjacency between every two edges in $G$.\n\nPrecisely speaking, for an undirected graph $G$ without self-loops or multiple edges, its line graph $L(G)$ is a graph such that\n\n- Each vertex of $L(G)$ represents an edge of $G$.\n- Two vertices of $L(G)$ are adjacent if and only if their corresponding edges share a common endpoint in $G$.\n\nAlso, $L^0(G)=G$ and $L^k(G)=L(L^{k-1}(G))$ for $k\\geq 1$.\n\nAn Euler trail is a sequence of edges that visits every edge of the graph exactly once. This trail can be either a path (starting and ending at different vertices) or a cycle (starting and ending at the same vertex). Vertices may be revisited during the trail, but each edge must be used exactly once.\n\nAryan gives you a simple connected graph $G$ with $n$ vertices and $m$ edges and an integer $k$, and it is guaranteed that $G$ has an Euler trail and it is not a path graph$^{\\text{∗}}$. He asks you to determine if $L^k(G)$ has an Euler trail.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$A path graph is a tree where every vertex is connected to atmost two other vertices.\n\\end{footnotesize}",
    "tutorial": "If $G$ has an Euler cycle, what can we say about $L^k(G), k\\geq1$ If $L(G)$ has Euler path, how to determine if $L^k(G), k\\geq2$ has an Euler path? If $L(G)$ doesn't Euler tour, but $L^2(G)$ does, what can we say about structure of $G$? Can there exist another graph $H$ such that $L(H)=G$? Following are the cases where Euler tour is possible: For the case of Euler cycle- If $G$ has an Euler cycle, then $L(G)$ always has an Euler cycle. If $G$ has an Euler cycle, then $L(G)$ always has an Euler cycle. If after removing the two odd-degree vertices of $G$, the remaining graph is fully disconnected(i.e. the odd-degree vertices form a vertex cover), then $L^2(G)$ has an Euler cycle. If after removing the two odd-degree vertices of $G$, the remaining graph is fully disconnected(i.e. the odd-degree vertices form a vertex cover), then $L^2(G)$ has an Euler cycle. For the case of Euler path- If $G$ doesn't have an Euler tour but $L(G)$ does, then there is no graph $H$ such that $G=L^2(H)$. So, we only need to consider cases where $G$ has an Euler tour, $L(G)$ doesn't, but $L^2(G)$ does and where both $G$ and $L(G)$ have Euler tour. If $G$ doesn't have an Euler tour but $L(G)$ does, then there is no graph $H$ such that $G=L^2(H)$. So, we only need to consider cases where $G$ has an Euler tour, $L(G)$ doesn't, but $L^2(G)$ does and where both $G$ and $L(G)$ have Euler tour. If $G$ has an Euler path, $L(G)$ doesn't, but $L^2(G)$ does, then $G$ has exactly two odd-degree vertices $v_1$ and $v_2$. Additionally, graph obtained after removing $v_1$ and $v_2$ from $G$(i.e. $G\\backslash${$v_1,v_2$}) consists of exactly one connected component with more than one vertex, and the rest are isolated vertices. Additionally, each connected component/isolated vertex in $G\\backslash${$v_1,v_2$} has exactly two edges connecting them to $v_1$, $v_2$ in $G$. Here, $L^k(G), k\\geq3$ won't have Euler tour. If $G$ has an Euler path, $L(G)$ doesn't, but $L^2(G)$ does, then $G$ has exactly two odd-degree vertices $v_1$ and $v_2$. Additionally, graph obtained after removing $v_1$ and $v_2$ from $G$(i.e. $G\\backslash${$v_1,v_2$}) consists of exactly one connected component with more than one vertex, and the rest are isolated vertices. Additionally, each connected component/isolated vertex in $G\\backslash${$v_1,v_2$} has exactly two edges connecting them to $v_1$, $v_2$ in $G$. Here, $L^k(G), k\\geq3$ won't have Euler tour. If $G$ has an Euler tour and $L(G)$ also has an Euler tour, find the smallest trailing path of $G$(trailing path means a path where the degree of all vertices is either $1$ or $2$. There will be only $2$ of them as $G$ has an Euler tour) and return its length, and that will be the answer as the length of a trailing path decreases by $1$ from $G$ to $L(G)$. If $G$ has an Euler tour and $L(G)$ also has an Euler tour, find the smallest trailing path of $G$(trailing path means a path where the degree of all vertices is either $1$ or $2$. There will be only $2$ of them as $G$ has an Euler tour) and return its length, and that will be the answer as the length of a trailing path decreases by $1$ from $G$ to $L(G)$. All of this can be checked in initial graph itself in $O(n+m)$ time. The removed problem was supposed to be G in the Div. 1 + Div. 2, the same problem exists and is available here. Let $s_i$ be the maximum number such that array $[a_1, a_2, ...a_i-1, s_i, a_i+1, .., a_n]$ is valid. Lemma 1: There exists at most one index $i$ such that $a_i \\ge s_i$. Proof 1: Assume there exist two indices $i$ and $j$ such that $a_i \\ge s_i$ and $a_j \\ge s_j$, say $i \\lt j$. $a_j \\ge s_j >= j-1 + a_1 + a_2 + ... + a_{j-1} \\Rightarrow a_j \\ge j-1 + \\sum_{k = 1}^{j-1} a_k \\Lleftarrow \\text{Eq}_1$ For an index $i \\lt j$, $a_i \\ge s_i$ when $a_j \\ge s_j \\Rightarrow$ $a[i] \\ge a[j] - (j-i) + 1 \\Lleftarrow \\text{Eq}_2$ $\\text{Eq}_1$ and $\\text{Eq}_2 \\Rightarrow$ $a_j + a_i \\ge j-1 - (j-i) + 1 + a_j + \\sum_{k = 1}^{j-1} a_k \\Rightarrow a_i \\ge i + \\sum_{k = 1}^{j-1} a_k$ since $i \\lt j \\Rightarrow$ $a_i \\ge i + a_1 + a_2 + .... + a_i + ... + a_{j-1} \\Rightarrow 0 \\ge i + a_1 + ... + a_{i-1} + .... + a_j$ $\\text{Contradiction!!}$ Lemma 2: If $a_i \\le s_i$ $\\forall$ $i \\in [1, n]$, $a$ is valid. Proof 2: Backwards induction - let's divide it into two cases. Case 1. $a_i \\lt s_i$ $\\forall$ $i \\in [1, n]$. Let $j \\gt 0$ be the smallest index such that $a_j > 0$ and say $j$-th index car overtakes the one ahead $i.e.,$ $0 ... a_{j-1}, a_j, a_{j+1} ... a_n \\Rightarrow 0 ... a_j-1, a_{j-1}, a_{j+1} ... a_n$ $0 ... s_{j-1}, s_j, s_{j+1} ... s_n \\Rightarrow 0 ... s_j-1, \\ge s_{j-1} + a_j, s_{j+1} ... s_n$ For all $i \\lt j-1$ and $i \\gt j$, $a_i \\lt s_i$ holds as they were unaffected, why? At index $j-1$ since $a_j \\lt s_j \\Rightarrow a[j]-1 \\lt s[j]-1$ holds. At index $j$ since $a_{j-1} < s_{j-1} \\Rightarrow a_{j-1} < s_{j-1} + a_j$ holds. Case 2. Now, for an index $j$ if $a_j = s_j \\Rightarrow$ we choose the index $k \\gt j$ such that $a_k \\gt 0$; if there's no such $k$, we choose $j$. Condition holds similarly, why? $\\text{Solution}$ Let $p = [0, a_1, a_1 + a_2, a_1 + a_2 + a_3, .... ]$ and say an index $i$ is critical $\\Leftrightarrow$ $i + p[i] < a_i$. Lemma 3: It is sufficient to check the greatest critical index $i.e.,$ if $i_1, i_2, ..., i_k$ are critical, $check(a, i_k)$ would be enough to determine whether $a$ is valid or not. Proof 3: Trivial, if $i_k$ performs $a_{i_k}$ overtakes successfully $\\Rightarrow$ overtakes at indices $i < i_k$ will be nullified by $a_{i_k}$ Special thanks to Proelectro444 for the formal proof. $\\looparrowright$ Alternate Solution: $O(n \\cdot log n)$ data structure optimized $check(a, i_k)$ $\\forall$ $k \\in [1, n]$. If $a$ is valid, also determine the index of the first overtaker, if multiple are possible, return any one of them.",
    "code": "#include \"bits/stdc++.h\"\nusing namespace std;\nusing ll = long long int;\nmt19937_64 RNG(chrono::high_resolution_clock::now().time_since_epoch().count());\n\n#include <ext/pb_ds/assoc_container.hpp>\n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\ntemplate<class T>\nusing Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;\n\nstruct FT {\n    vector<ll> s;\n    FT(int n) : s(n) {}\n    void update(int pos, ll dif) { // a[pos] += dif↵\n        for (; pos < size(s); pos |= pos + 1) s[pos] += dif;\n    }\n    ll query(int pos) { // sum of values in [0, pos)\n        ll res = 0;\n        for (; pos > 0; pos &= pos - 1) res += s[pos-1];\n        return res;\n    }\n};\n\nint main()\n{\n    ios::sync_with_stdio(false); cin.tie(0);\n\n    map<vector<int>, bool> cache;\n    auto brute = [&] (const auto &self, auto v) -> bool {\n        if (ranges::max(v) == 0) return true;\n        if (cache.find(v) != cache.end()) return cache[v];\n \n        for (int i = 1; i < v.size(); ++i) {\n            if (v[i] > 0) {\n                auto w = v;\n                --w[i];\n                swap(w[i], w[i-1]);\n                bool res = self(self, w);\n \n                if (res) return cache[v] = true;\n            }\n        }\n        return cache[v] = false;\n    };\n\n    auto solve = [&] (auto v) {\n        int n = size(v);\n\n        vector<int> b(n);\n        Tree<array<int, 2>> cur;\n        for (int i = 0; i < n; ++i) {\n            if (v[i] == 0) b[i] = i;\n            else {\n                // v[i]-th largest element↵\n                if (cur.size() >= v[i]) {\n                    int want = cur.size() - v[i];\n                    auto [val, _] = *cur.find_by_order(want);\n                    b[i] = val;\n                }\n                else b[i] = -1;\n            }\n            cur.insert({b[i], i});\n        }\n\n        vector deactivate(n+1, vector<int>());\n        for (int i = 0; i < n; ++i)\n            if (b[i] >= 0) deactivate[b[i]].push_back(i);\n        \n        ll pref = 0;\n        for (int i = 0; i < n; ++i) pref += v[i] + 1;\n\n        FT fen(n);\n        ll suf = 0;\n        for (int i = n-1; i >= 0; --i) {\n            pref -= v[i] + 1;\n            \n            ranges::reverse(deactivate[i]);\n            for (int x : deactivate[i]) {\n                if (v[x]) {\n                    int sub = fen.query(x+1) - fen.query(i+1);\n                    sub = x - i - sub;\n                    suf -= v[x] - sub;\n                    fen.update(x, -1);\n                }\n                suf -= fen.query(n) - fen.query(x);\n            }\n            ll have = pref + suf;\n            if (v[i] > have) return false;\n            if (v[i] > 0) {\n                suf += v[i];\n                fen.update(i, 1);\n            }\n        }\n        return true;\n    };\n\n    int t; cin >> t;\n    while (t--) {\n        int n; cin >> n;\n        vector a(n, 0);\n        for (int &x : a) cin >> x;\n        \n        if (solve(a)) cout << \"Yes\\n\";\n        else cout << \"No\\n\";\n    }\n}",
    "tags": [
      "graphs",
      "greedy",
      "math"
    ]
  },
  {
    "contest_id": "2121",
    "index": "A",
    "title": "Letter Home",
    "statement": "You are given an array of distinct integers $x_1, x_2, \\ldots, x_n$ and an integer $s$.\n\nInitially, you are at position $pos = s$ on the $X$ axis. In one step, you can perform exactly one of the following two actions:\n\n- Move from position $pos$ to position $pos + 1$.\n- Move from position $pos$ to position $pos - 1$.\n\nA sequence of steps will be considered successful if, during the entire journey, you visit each position $x_i$ on the $X$ axis at least once. Note that the initial position $pos = s$ is also considered visited.\n\nYour task is to determine the minimum number of steps in any successful sequence of steps.",
    "tutorial": "Notice that if we visit positions $x_1$ and $x_n$, we will necessarily visit all other positions $x_i$. Therefore, our goal will be to visit positions $x_1$ and $x_n$. We then have two options: From position $s$, go to position $x_1$, and from there go to position $x_n$. We will need to make $|s - x_1| + |x_n - x_1|$ steps. From position $s$, go to position $x_n$, and from there go to position $x_1$. We will need to make $|s - x_n| + |x_n - x_1|$ steps. From the two cases, we choose the smaller one. The answer will be $\\min(|s - x_1|, |s - x_n|) + x_n - x_1$. The solution can be implemented in $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, s;\n        cin >> n >> s;\n        vector<int> x(n);\n        for (int i = 0; i < n; i++) cin >> x[i];\n        int ans = min(abs(s - x[0]), abs(s - x.back())) + x.back() - x[0];\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "brute force",
      "math"
    ]
  },
  {
    "contest_id": "2121",
    "index": "B",
    "title": "Above the Clouds",
    "statement": "You are given a string $s$ of length $n$, consisting of lowercase letters of the Latin alphabet. Determine whether there exist three \\textbf{non-empty} strings $a$, $b$, and $c$ such that:\n\n- $a + b + c = s$, meaning the concatenation$^{\\text{∗}}$ of strings $a$, $b$, and $c$ equals $s$.\n- The string $b$ is a substring$^{\\text{†}}$ of the string $a + c$, which is the concatenation of strings $a$ and $c$.\n\n\\begin{footnotesize}\n$^{\\text{∗}}$Concatenation of strings $a$ and $b$ is defined as the string $a + b = a_1a_2 \\ldots a_pb_1b_2 \\ldots b_q$, where $p$ and $q$ are the lengths of strings $a$ and $b$, respectively. For example, the concatenation of the strings \"code\" and \"forces\" is \"codeforces\".\n\n$^{\\text{†}}$A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.\n\\end{footnotesize}",
    "tutorial": "Notice that if there exist three non-empty strings $a$, $b$, and $c$ that satisfy the condition, then there exist three non-empty strings $a'$, $b'$, and $c'$ that satisfy the condition, where the length of string $b'$ is equal to $1$. To achieve this, one can choose any character from string $b$, append all characters before it to the end of string $a$, and prepend all characters after it to the beginning of string $c$. Let $cnt_l$ be the number of times character $l$ appears in string $s$. Then the answer \"Yes\" will be given if any of the following conditions hold: There exists a character $l$ such that $cnt_l \\geq 3$. We can choose the second occurrence of character $l$ in string $s$ as string $b$. There exists a character $l$ such that $cnt_l = 2$ and either the first or the last character of string $s$ is not equal to $l$. We can choose any occurrence of character $l$ in the string as string $b$, except when it is the first or last character of string $s$. The solution can be implemented in $O(n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        vector<int> cnt(26, 0);\n        for (auto c : s) cnt[c - 'a']++;\n        int flag = 0;\n        for (int i = 0; i < 26; i++) {\n            if (cnt[i] >= 3) flag = 1;\n            else if (cnt[i] == 2 && (s[0] - 'a' != i || s.back() - 'a' != i)) flag = 1;\n        }\n        if (flag) cout << \"Yes\" << '\\n';\n        else cout << \"No\" << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "constructive algorithms",
      "greedy",
      "strings"
    ]
  },
  {
    "contest_id": "2121",
    "index": "C",
    "title": "Those Who Are With Us",
    "statement": "You are given a matrix of integers with $n$ rows and $m$ columns. The cell at the intersection of the $i$-th row and the $j$-th column contains the number $a_{ij}$.\n\nYou can perform the following operation \\textbf{exactly once}:\n\n- Choose two numbers $1 \\leq r \\leq n$ and $1 \\leq c \\leq m$.\n- For all cells $(i, j)$ in the matrix such that $i = r$ or $j = c$, decrease $a_{ij}$ by one.\n\nYou need to find the minimal possible maximum value in the matrix $a$ after performing exactly one such operation.",
    "tutorial": "Let $mx$ be the maximum value in the matrix. Note that the answer to the problem will be either $mx - 1$ or $mx$. When will the answer be $mx - 1$? If there exists a pair $(r, c)$ such that all values of $mx$ are contained in row $r$ or column $c$. Let $row_r$ be the number of times $mx$ appears in row $r$; $col_c$ be the number of times $mx$ appears in column $c$. Then in row $r$ or column $c$, the number $mx$ appears $row_r + col_c$ times. However, there is an edge case: if $a_{rc} = mx$, we have counted it twice, so we need to subtract one. If this count equals the total occurrences of $mx$ in the matrix, then we can achieve the answer $mx - 1$. The solution can be implemented in $O(n \\cdot m)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, m;\n        cin >> n >> m;\n        vector<vector<int>> a(n, vector<int> (m));\n        int mx = 0, cnt_mx = 0;\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                cin >> a[i][j];\n                if (a[i][j] > mx) {\n                    mx = a[i][j], cnt_mx = 1;\n                } else if (a[i][j] == mx) {\n                    cnt_mx++;\n                }\n            }\n        }\n        vector<int> r(n), c(m);\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                if (a[i][j] == mx) {\n                    r[i]++;\n                    c[j]++;\n                }\n            }\n        }\n        int flag = 0;\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < m; j++) {\n                if (r[i] + c[j] - (a[i][j] == mx) == cnt_mx) {\n                    flag = 1;\n                }\n            }\n        }\n        cout << mx - flag << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "greedy",
      "implementation"
    ]
  },
  {
    "contest_id": "2121",
    "index": "D",
    "title": "1709",
    "statement": "You are given two arrays of integers $a_1, a_2, \\ldots, a_n$ and $b_1, b_2, \\ldots, b_n$. It is guaranteed that each integer from $1$ to $2 \\cdot n$ appears in exactly one of the arrays.\n\nYou need to perform a certain number of operations (possibly zero) so that \\textbf{both} of the following conditions are satisfied:\n\n- For each $1 \\leq i < n$, it holds that $a_i < a_{i + 1}$ and $b_i < b_{i + 1}$.\n- For each $1 \\leq i \\leq n$, it holds that $a_i < b_i$.\n\nDuring each operation, you can perform exactly one of the following three actions:\n\n- Choose an index $1 \\leq i < n$ and swap the values $a_i$ and $a_{i + 1}$.\n- Choose an index $1 \\leq i < n$ and swap the values $b_i$ and $b_{i + 1}$.\n- Choose an index $1 \\leq i \\leq n$ and swap the values $a_i$ and $b_i$.\n\nYou do not need to minimize the number of operations, but the total number must not exceed $1709$. Find any sequence of operations that satisfies \\textbf{both} conditions.",
    "tutorial": "Using bubble sort, we will sort array $a$: while there exists an index $1 \\leq i < n$ such that $a_i > a_{i + 1}$, we will swap them. Similarly, we will sort array $b$. In this part of the task, we will perform no more than $\\frac{n \\cdot (n - 1)}{2} + \\frac{n \\cdot (n - 1)}{2} = n \\cdot (n - 1)$ operations, since the number of swaps in bubble sort is equal to the number of inversions in the array. Next, for all $1 \\leq i \\leq n$ such that $a_i > b_i$, we will swap $a_i$ and $b_i$. After this, we will satisfy both conditions and perform a total of no more than $n \\cdot (n - 1) + n = n^2$ operations. The solution can be implemented in $O(n^2)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        vector<int> a(n), b(n);\n        for (int i = 0; i < n; i++) cin >> a[i];\n        for (int i = 0; i < n; i++) cin >> b[i];\n        vector<pair<int, int>> ans;\n        for (int i = 0; i < n; i++) {\n            for (int j = 1; j < n; j++) {\n                if (a[j - 1] > a[j]) {\n                    swap(a[j - 1], a[j]);\n                    ans.push_back({1, j});\n                }\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            for (int j = 1; j < n; j++) {\n                if (b[j - 1] > b[j]) {\n                    swap(b[j - 1], b[j]);\n                    ans.push_back({2, j});\n                }\n            }\n        }\n        for (int i = 0; i < n; i++) {\n            if (a[i] > b[i]) {\n                ans.push_back({3, i + 1});\n            }\n        }\n        cout << ans.size() << '\\n';\n        for (auto [x, y] : ans) cout << x << \" \" << y << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "implementation",
      "sortings"
    ]
  },
  {
    "contest_id": "2121",
    "index": "E",
    "title": "Sponsor of Your Problems",
    "statement": "For two integers $a$ and $b$, we define $f(a, b)$ as the number of positions in the decimal representation of the numbers $a$ and $b$ where their digits are the same. For example, $f(12, 21) = 0$, $f(31, 37) = 1$, $f(19891, 18981) = 2$, $f(54321, 24361) = 3$.\n\nYou are given two integers $l$ and $r$ of the \\textbf{same} length in decimal representation. Consider all integers $l \\leq x \\leq r$. Your task is to find the minimum value of $f(l, x) + f(x, r)$.",
    "tutorial": "Note that the number $x$ will have the same length in decimal representation as the numbers $l$ and $r$. Consider the example $l = 12345$ and $r = 12534$. For the number $x$ to be in the range between $l$ and $r$ inclusive, it must be of length $5$ and start with the digits $12$. In other words, the greatest common prefix of the numbers $l$ and $r$ will be the beginning of the number $x$. Next, look at the digits following the greatest common prefix, which in this case are $3$ and $5$. If these digits differ by at least two, we can choose a digit between them, excluding the boundaries, and then fill in the remaining lower digits such that there are no common digits with the numbers $l$ and $r$. In this case, for example, we can take the number $x = 12400$: we chose the digit $4$ between $3$ and $5$, and then we can choose the lower two digits arbitrarily-let's choose them so that there are no common digits with the numbers $l$ and $r$. In summary, if the digits after the greatest common prefix differ by at least two, the answer will be equal to twice the common prefix. Now consider the example $l = 1239990$ and $r = 1240037$. Again, we can conclude that the number $x$ will be of length $7$ and start with the digits $12$. But in this case, the digits after the greatest common prefix differ by $1$, which means we need to choose one of them. Let's consider two options for selection: The number $x$ will be of length $7$ and start with the digits $123$. Then this number will definitely be $< r$. We just need to ensure that this number is not less than $l$ and minimize the number of common digits. Notice that the next digit in $l$ is $9$, so we can guarantee that the number $x$ must start with the digits $123999$. The number $x$ will be of length $7$ and start with the digits $124$. Then this number will definitely be $> l$. We just need to ensure that this number is not greater than $r$ and minimize the number of common digits. Notice that the next digit in $r$ is $0$, so we can guarantee that the number $x$ must start with the digits $12400$. If we skip the complete breakdown of cases, the answer will consist of three parts that need to be summed: Twice the common prefix. One (since we are choosing one of the digits after the greatest common prefix, and it will be in one of the numbers). The number of consecutive digits $i$ after the first differing digit in the numbers $l$ and $r$, such that $l_i = 9$ and $r_i = 0$. Thus, in this case, the answer is $2 + 1 + 2 = 5$. We can choose the number $x = 1240001$, for example.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        string l, r;\n        cin >> l >> r;\n        if (l == r) {\n            cout << 2 * l.size() << '\\n';\n            continue;\n        }\n        int ptr = 0;\n        while (ptr < l.size() && l[ptr] == r[ptr]) ptr++;\n        if (l[ptr] + 1 < r[ptr]) {\n            cout << 2 * ptr << '\\n';\n        } else {\n            int res = 2 * ptr + 1;\n            for (int i = ptr + 1; i < l.size(); i++) {\n                if (l[i] == '9' && r[i] == '0') res++;\n                else break;\n            }\n            cout << res << '\\n';\n        }\n    }\n    return 0;\n}",
    "tags": [
      "dp",
      "greedy",
      "implementation",
      "strings"
    ]
  },
  {
    "contest_id": "2121",
    "index": "F",
    "title": "Yamakasi",
    "statement": "You are given an array of integers $a_1, a_2, \\ldots, a_n$ and two integers $s$ and $x$. Count the number of subsegments of the array whose sum of elements equals $s$ and whose maximum value equals $x$.\n\nMore formally, count the number of pairs $1 \\leq l \\leq r \\leq n$ such that:\n\n- $a_l + a_{l + 1} + \\ldots + a_r = s$.\n- $\\max(a_l, a_{l + 1}, \\ldots, a_r) = x$.",
    "tutorial": "To start, let's recall how to solve the following problem: how many subsegments of the array have a sum of elements equal to $s$. Let $pref_i$ be the sum of the first $i$ elements of the array. Then the sum of a subsegment will be equal to $pref_r - pref_{l - 1}$. We will iterate over the right boundary $r$ and count the number of suitable left boundaries $l$, that is, such boundaries that $pref_r - pref_{l - 1} = s$ or $pref_{l - 1} = pref_r - s$. For this, we will additionally maintain a map to keep track of the number of left boundaries with a given prefix sum value for the considered prefix. Now we must also take into account the fact that the maximum value must equal $x$. For this, we will maintain a pointer $lef$ - the smallest left boundary that we have not yet added to the map, but can add when the maximum in the subsegment $(lef, r)$ equals $x$. Next, we have the following options: If $a_r > x$, then we need to clear the map and set $lef = r + 1$, since no good subsegment can contain the element $a_r$. If $a_r = x$, we need to add information about the left boundaries $lef, lef + 1, \\ldots, r$ to the map (add information about their values $pref_{l - 1}$). After this, set $lef = r + 1$. If $a_r < x$, nothing changes. And similarly, for each right boundary, we can count the number of suitable left boundaries. The solution can be implemented in $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nint const maxn = 2e5 + 5;\nint a[maxn];\nll pref[maxn], s;\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n, x;\n        cin >> n >> s >> x;\n        for (int i = 1; i <= n; i++) {\n            cin >> a[i];\n            pref[i] = pref[i - 1] + a[i];\n        }\n        ll ans = 0;\n        map<ll, int> cnt;\n        int lef = 1;\n        for (int r = 1; r <= n; r++) {\n            if (a[r] > x) cnt.clear(), lef = r + 1;\n            else if (a[r] == x) {\n                while (lef <= r) {\n                    cnt[pref[lef - 1]]++;\n                    lef++;\n                }\n            }\n            ans += cnt[pref[r] - s];\n        }\n        cout << ans << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "greedy",
      "two pointers"
    ]
  },
  {
    "contest_id": "2121",
    "index": "G",
    "title": "Gangsta",
    "statement": "You are given a binary string $s_1s_2 \\ldots s_n$ of length $n$. A string $s$ is called binary if it consists only of zeros and ones.\n\nFor a string $p$, we define the function $f(p)$ as the maximum number of occurrences of any character in the string $p$. For example, $f(00110) = 3$, $f(01) = 1$.\n\nYou need to find the sum $f(s_ls_{l+1} \\ldots s_r)$ for all pairs $1 \\leq l \\leq r \\leq n$.",
    "tutorial": "Let $c_0$ be the number of zeros in the subsegment, and $c_1$ be the number of ones. Notice that $\\max(c_0, c_1) = \\frac{c_0 + c_1 + |c_0 - c_1|}{2}$. Then we will find the sum $c_0 + c_1 + |c_0 - c_1|$ over all subsegments, and this sum divided by two will be the answer. Let $pref_i$ be the difference between the number of ones and the number of zeros in the prefix of length $i$. Then $f(s_ls_{l+1} \\ldots s_r) = r - l + 1 + |pref_r - pref_{l - 1}|$. We will separately calculate the sum $r - l + 1$ over all subsegments. This can be done in $O(n)$: the number of segments of length $len$ will be $n - len + 1$, so we need to find $\\sum\\limits_{len = 1}^n len \\cdot (n - len + 1)$. We still need to find the sum $|pref_r - pref_{l - 1}|$ over all subsegments. To do this, we will sort the array $pref$ (here we need to be careful, as this array consists of $n + 1$ elements, not $n$). After sorting, we will eliminate the absolute value, and we will need to find the sum $pref_r - pref_{l - 1}$ over all subsegments. This sum will be equal to $\\sum\\limits_{i = 0}^n pref_i \\cdot (i - (n - i))$, since in $i$ terms we will take $pref_i$ with a positive sign, and in $n - i$ terms we will take it with a negative sign. The solution can be implemented in $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\ntypedef long long ll;\nint const maxn = 2e5 + 5;\nint pref[maxn];\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        string s;\n        cin >> s;\n        ll ans = 0;\n        for (int i = 0; i < n; i++) {\n            pref[i + 1] = pref[i];\n            if (s[i] == '0') pref[i + 1]--;\n            else pref[i + 1]++;\n        }\n        for (int i = 1; i <= n; i++) {\n            ans += (ll)i * (n - i + 1);\n        }\n        sort(pref, pref + n + 1);\n        for (int i = 0; i <= n; i++) {\n            ans += (ll)pref[i] * (i - (n - i));\n        }\n        cout << ans / 2 << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "data structures",
      "divide and conquer",
      "math",
      "sortings"
    ]
  },
  {
    "contest_id": "2121",
    "index": "H",
    "title": "Ice Baby",
    "statement": "The longest non-decreasing subsequence of an array of integers $a_1, a_2, \\ldots, a_n$ is the longest sequence of indices $1 \\leq i_1 < i_2 < \\ldots < i_k \\leq n$ such that $a_{i_1} \\leq a_{i_2} \\leq \\ldots \\leq a_{i_k}$. The length of the sequence is defined as the number of elements in the sequence. For example, the length of the longest non-decreasing subsequence of the array $a = [3, 1, 4, 1, 2]$ is $3$.\n\nYou are given two arrays of integers $l_1, l_2, \\ldots, l_n$ and $r_1, r_2, \\ldots, r_n$. For each $1 \\le k \\le n$, solve the following problem:\n\n- Consider all arrays of integers $a$ of length $k$, such that for each $1 \\leq i \\leq k$, it holds that $l_i \\leq a_i \\leq r_i$. Find the maximum length of the longest non-decreasing subsequence among all such arrays.",
    "tutorial": "Let $dp[i][j]$ be the minimum number $x$ such that we can choose the values of the elements $a_1, a_2, \\ldots, a_i$ in such a way that there exists a non-decreasing subsequence of length $j$ with the last element of the subsequence equal to $x$. If it is impossible to choose a subsequence of length $j$, we will consider $dp[i][j] = \\inf$. We also note that $dp[i][j] \\leq dp[i][j + 1]$. Consider the recalculation of the dynamics when transitioning from $i$ to $i + 1$: If $dp[i][j] \\leq l_{i + 1}$, then $dp[i + 1][j] = dp[i][j]$. If $dp[i][j - 1] \\leq r_{i + 1}$, then $dp[i + 1][j] = \\max(l_{i + 1}, dp[i][j - 1])$. It is worth noting that the number $\\max(l_{i + 1}, dp[i][j - 1])$ will definitely not be greater than $dp[i][j]$ (if we have indeed entered this case and not the first one!). If $dp[i][j - 1] > r_{i + 1}$, then $dp[i + 1][j] = dp[i][j]$. The first and third transitions are not of interest to us, as they preserve the previous value of the dynamics for a fixed $j$. We only need to process the second transition. Here we will use the fact that $dp[i][j] \\leq dp[i][j + 1]$. Let $lef$ be the smallest index such that $dp[i][lef] \\geq l_i$; $righ$ be the largest index such that $dp[i][righ] \\leq r_i$. The assertion is: then $dp[i + 1][lef] = l$, $dp[i + 1][j] = dp[i][j - 1]$ for $lef < j \\leq righ + 1$. Note that $dp_i$ is a multiset of values, and since $dp[i][j] \\leq dp[i][j + 1]$, the positions do not matter; only the values are important (they will uniquely determine the $i$-th layer of dynamics). Let's see how the multiset of values $dp_i$ differs from $dp_{i + 1}$: An element $l$ is added. At most one element is removed, namely the smallest element that is greater than $r$ (if such an element exists). Therefore, it is sufficient to maintain only the multiset of values of the $i$-th layer of dynamics (initially it is empty). We will handle two changes: insertion into the multiset (insert) and removal (erase) of the smallest element that is greater than a given number (such an element can be found using the upper_bound method). The solution can be implemented in $O(n \\log n)$.",
    "code": "#include<bits/stdc++.h>\n\nusing namespace std;\n\nmain() {\n    ios_base::sync_with_stdio(0);\n    cin.tie(0);\n    cout.tie(0);\n    int t;\n    cin >> t;\n    while (t--) {\n        int n;\n        cin >> n;\n        multiset<int> dp;\n        for (int i = 1; i <= n; i++) {\n            int l, r;\n            cin >> l >> r;\n            auto it = dp.upper_bound(r);\n            if (it != dp.end()) {\n                dp.erase(it);\n            }\n            dp.insert(l);\n            cout << dp.size() << \" \";\n        }\n        cout << '\\n';\n    }\n    return 0;\n}",
    "tags": [
      "binary search",
      "brute force",
      "data structures",
      "dp",
      "implementation",
      "sortings"
    ]
  }
]
